{"text": "#include <boost/test/unit_test.hpp>\n\n#include \"Werk/Math/SummaryStatistics.hpp\"\n\nBOOST_AUTO_TEST_SUITE(SummaryStatistics)\n\nBOOST_AUTO_TEST_CASE(TestEmpty) {\n\tWerk::SummaryStatistics<double> s;\n\tBOOST_REQUIRE_EQUAL(s.count(),0);\n}\n\nBOOST_AUTO_TEST_CASE(TestBasic) {\n\tWerk::SummaryStatistics<double> s;\n\ts.sample(5.0);\n\ts.sample(1.0);\n\tBOOST_REQUIRE_EQUAL(s.count(), 2);\n    BOOST_REQUIRE_EQUAL(s.sum(), 6.0);\n    BOOST_REQUIRE_EQUAL(s.average(), 3.0);\n    BOOST_REQUIRE_EQUAL(s.variance(), 4.0);\n    BOOST_REQUIRE_EQUAL(s.stddev(), 2.0);\n    s.reset();\n    BOOST_REQUIRE_EQUAL(s.count(),0);\n    const char* filename = \"summary.txt\";\n    FILE* file = fopen(filename, \"rb\");\n    s.writeJson(file);\n}\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "2662b94ebebdea02af699358171ac965213e029a", "size": 725, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/WerkTest/Math/SummaryStatistics.cpp", "max_stars_repo_name": "mish24/werk", "max_stars_repo_head_hexsha": "2f8822842fb8f68a4402775d1d3b41021b5a9945", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/WerkTest/Math/SummaryStatistics.cpp", "max_issues_repo_name": "mish24/werk", "max_issues_repo_head_hexsha": "2f8822842fb8f68a4402775d1d3b41021b5a9945", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/WerkTest/Math/SummaryStatistics.cpp", "max_forks_repo_name": "mish24/werk", "max_forks_repo_head_hexsha": "2f8822842fb8f68a4402775d1d3b41021b5a9945", "max_forks_repo_licenses": ["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.8928571429, "max_line_length": 43, "alphanum_fraction": 0.7144827586, "num_tokens": 190, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.4999988529344828}}
{"text": "#include <ql/quantlib.hpp>\n\n#include <boost/make_shared.hpp>\n#include <iostream>\n#include <fstream>\n\nusing namespace QuantLib;\n\nvoid outputBasket(std::vector<boost::shared_ptr<CalibrationHelper> > basket,\n                  boost::shared_ptr<TermStructure> termStructure) {\n\n    std::cout << \"Calibration Basket:\" << std::endl;\n    std::cout << \"expiry;maturityDate;expiryTime;maturityTime;nominal;rate;marketvol\" << std::endl;\n    for(Size j=0;j<basket.size();j++) {\n        boost::shared_ptr<SwaptionHelper> helper = boost::dynamic_pointer_cast<SwaptionHelper>(basket[j]);\n        Date endDate = helper->underlyingSwap()->fixedSchedule().dates().back();\n        Real nominal = helper->underlyingSwap()->nominal();\n        Real vol = helper->volatility()->value();\n        Real rate = helper->underlyingSwap()->fixedRate();\n        Date expiry = helper->swaption()->exercise()->date(0);\n        Real expiryTime = termStructure->timeFromReference(expiry);\n        Real endTime = termStructure->timeFromReference(endDate);\n        // std::cout << expiry << \";\" << endDate << \";\" << expiryTime << \";\" << endTime << \";\" <<\n        //     nominal << \";\" << rate << \";\" << vol << std::endl;\n        std::cout << expiry << \" & \" << endDate << \" & \" << expiryTime << \" & \" << endTime << \" & \" <<\n            nominal << \" & \" << rate << \" \\\\\\\\\" << std::endl;\n    }\n\n}\n\nvoid outputModel(std::vector<Date>& expiries, boost::shared_ptr<Gsr> model) {\n\n    std::cout << \"Model parameters: \";\n    std::cout << \"expiry;volatility\" << std::endl;\n    for(Size i=0;i<expiries.size();i++) { // first parameters are the vols, after that the mean reversions follow\n        //std::cout << expiries[i] << \";\" << model->params()[i] << std::endl;\n        std::cout << expiries[i] << \" & \" << model->volatility()[i] << \" \\\\\\\\\" << std::endl;\n    }\n    std::cout << std::endl;\n\n}\n\nint main(int, char* []) {\n\n    Date refDate(17,June,2013);\n    Settings::instance().evaluationDate() = refDate;\n    Date effective = TARGET().advance(refDate,2*Days);\n    Date maturity = TARGET().advance(effective,10*Years);\n\n    // market data: flat yts 3%, flat vol 20%\n\n    Real rateLevel = 0.03;\n    Real volLevel = 0.20;\n\n    boost::shared_ptr<Quote> ytsQuote0(new SimpleQuote(rateLevel));\n    boost::shared_ptr<Quote> ytsQuote1(new SimpleQuote(rateLevel+0.0010)); // 10bp shift up for dv01, dv02 calculation\n    boost::shared_ptr<Quote> ytsQuote2(new SimpleQuote(rateLevel-0.0010)); // 10bp shift down for dv01, dv02 calculation\n\n    RelinkableHandle<Quote> ytsQuote(ytsQuote0);\n\n    Handle<YieldTermStructure> yts( boost::shared_ptr<YieldTermStructure>(new FlatForward(0,TARGET(),ytsQuote,\n                                                                                              Actual365Fixed())));\n\n    boost::shared_ptr<Quote> volQuote0(new SimpleQuote(volLevel));\n    boost::shared_ptr<Quote> volQuote1(new SimpleQuote(volLevel+0.01));\n\n    RelinkableHandle<Quote> volQuote(volQuote0);\n\n    boost::shared_ptr<SwaptionVolatilityStructure> swaptionVol(new ConstantSwaptionVolatility(0,TARGET(),\n                                                          ModifiedFollowing,volQuote,Actual365Fixed()));\n\n    boost::shared_ptr<IborIndex> iborIndex(new Euribor(6*Months,yts));\n    boost::shared_ptr<SwapIndex> standardSwapBase(new EuriborSwapIsdaFixA(10*Years,yts));\n\n    // spread Quote\n\n    Real spreadLevel = 0.0100;\n    boost::shared_ptr<Quote> spreadQuote0(new SimpleQuote(spreadLevel));\n\n    RelinkableHandle<Quote> spreadQuote(spreadQuote0);\n\n    // non standard swaption instrument (10y, amortizing nominal and step up coupon, yearly exercise dates)\n    // we use the nonstandard swap and the nonstandard swaption for bond pricing, i.e. set the floating side to zero\n    // receiver swap means we are long the bond\n    // we are short the call right, so the rebate is positive\n\n    std::vector<Real> fixedNominal(10), floatingNominal(20,0.0), fixedRate(10);\n    for(Size i=0;i<10;i++) {\n        fixedNominal[i] = 100.0;//-i*10.0;//-i*5000000;//(i>0 ? fixedNominal[i-1] : 100000000.0 )*1.075;\n        floatingNominal[2*i] = floatingNominal[2*i+1] = 0.0; //fixedNominal[i];\n        fixedRate[i] = 0.035;//+0.0030*i;\n    }\n\n    Schedule fixedSchedule(effective,maturity,1*Years,TARGET(),ModifiedFollowing,ModifiedFollowing,\n                           DateGeneration::Forward,false);\n    Schedule floatingSchedule(effective,maturity,6*Months,TARGET(),ModifiedFollowing,ModifiedFollowing,\n                           DateGeneration::Forward,false);\n\n    boost::shared_ptr<NonstandardSwap> underlying(new NonstandardSwap(VanillaSwap::Receiver,fixedNominal,floatingNominal,\n                                                                      fixedSchedule,fixedRate,Thirty360(),floatingSchedule,\n                                                                      iborIndex,1.0,0.0,Actual360(),true,true));\n\n    std::vector<Date> exerciseDates;\n    std::vector<Real> rebates;\n    for(Size i=1;i<10;i++) {\n        exerciseDates.push_back(TARGET().advance(fixedSchedule[i],-2*Days));\n        rebates.push_back(-100.0);\n    }\n\n    //BermudanExercise exerciseTmp(exerciseDates, false);\n    boost::shared_ptr<RebatedExercise> exercise =\n        boost::make_shared<RebatedExercise>(\n            BermudanExercise(exerciseDates, false), rebates, 2, TARGET(),\n            Following);\n\n    boost::shared_ptr<NonstandardSwaption> swaption(\n        new NonstandardSwaption(underlying, exercise));\n\n    // pricing of vanilla bond part\n\n    std::cout << \"============================================================\" << std::endl;\n    std::cout << \"Vanilla part pricing\" << std::endl;\n    std::cout << \"============================================================\" << std::endl;\n\n    Leg vanilla = underlying->leg(0);\n    Leg other = underlying->leg(1);\n\n    Real vanillaNpv = CashFlows::npv(vanilla,*yts,spreadQuote->value(),yts->dayCounter(),Continuous,NoFrequency,false);\n    Real otherNpv = CashFlows::npv(other,*yts,spreadQuote->value(),yts->dayCounter(),Continuous,NoFrequency,false);\n\n    std::cout << \"npv = \" << vanillaNpv << \" (other = \" << otherNpv << \")\" << std::endl;\n\n    // gsr model (1% mean reversion, intially 1% vol)\n\n    exerciseDates.pop_back();\n    std::vector<Date> stepDates(exerciseDates);\n    std::vector<Real> vols(exerciseDates.size()+1,0.01);\n    std::vector<Real> reversions(exerciseDates.size()+1,0.01);\n\n    boost::shared_ptr<Gsr> gsr(new Gsr(yts,stepDates,vols,reversions,50.0));\n\n    // engines for nonstandard swaption and standard swaption\n\n    // this engine is used for standard swaptions used in model calibration\n    boost::shared_ptr<PricingEngine> standardEngine(new Gaussian1dSwaptionEngine(gsr));\n    // this engine is used for the non standard swaption\n    boost::shared_ptr<PricingEngine> nonStandardEngine(new Gaussian1dNonstandardSwaptionEngine(gsr,64,7.0,true,false,\n                                                                                        spreadQuote));\n\n    swaption->setPricingEngine(nonStandardEngine);\n\n    std::cout.precision(6);\n    std::cout << std::fixed;\n\n    std::cout << \"============================================================\" << std::endl;\n    std::cout << \"Model is not calibrated\" << std::endl;\n    std::cout << \"============================================================\" << std::endl;\n    outputModel(stepDates,gsr);\n\n    std::cout << \"Calculate calibration basket\" << std::endl;\n    std::vector<boost::shared_ptr<CalibrationHelper> > basket = swaption->calibrationBasket(standardSwapBase,swaptionVol);\n    for(Size i=0;i<basket.size();i++) basket[i]->setPricingEngine(standardEngine);\n    outputBasket(basket,*gsr->termStructure());\n\n    std::cout << \"Calibrate the model to the initial basket\" << std::endl;\n    LevenbergMarquardt lm;\n    EndCriteria ec(2000,200,1E-8,1E-8,1E-8);\n    gsr->calibrateVolatilitiesIterative(basket,lm,ec);\n    outputModel(stepDates,gsr);\n\n    std::cout << \"Calculate calibration basket\" << std::endl;\n\n    std::vector<boost::shared_ptr<CalibrationHelper> > basket2 = swaption->calibrationBasket(standardSwapBase,swaptionVol);\n    for(Size i=0;i<basket2.size();i++) basket2[i]->setPricingEngine(standardEngine);\n    outputBasket(basket2,*gsr->termStructure());\n\n    std::cout << \"Calibrate the model to the second basket\" << std::endl;\n\n    gsr->calibrateVolatilitiesIterative(basket2,lm,ec);\n    outputModel(stepDates,gsr);\n\n    std::cout << \"Price the nonstandard swaption\" << std::endl;\n\n    Real npv0 = swaption->NPV();\n\n    std::cout << \"Shift the rate curve by 10bp up, down and reprice to compute delta, gamma\" << std::endl;\n\n    ytsQuote.linkTo(ytsQuote1);\n    Real npv1 = swaption->NPV();\n    ytsQuote.linkTo(ytsQuote2);\n    Real npv2 = swaption->NPV();\n    ytsQuote.linkTo(ytsQuote0);\n\n    Real npv3 = swaption->NPV();\n\n    std::cout << \"NPV(-10bp) = \" << npv2 << \" NPV(0) = \" << npv0 << \" NPV(+10bp) = \" << npv1 << std::endl;\n    std::cout << \"DV01 = \" << (npv1-npv2) / 20.0 << std::endl;\n    std::cout << \"DV02 = \" << (npv1-2.0*npv0+npv2) / 100.0 << std::endl;\n    std::cout << \"Vega = \" << (npv3-npv0) << std::endl;\n\n    std::cout << \"============================================================\" << std::endl;\n    std::cout << \"Compute delta, gamma with model recalibration\" << std::endl;\n    std::cout << \"============================================================\" << std::endl;\n\n    gsr->calibrateVolatilitiesIterative(basket2,lm,ec);\n    outputModel(stepDates,gsr);\n    npv0 = swaption->NPV();\n\n    ytsQuote.linkTo(ytsQuote1);\n    gsr->calibrateVolatilitiesIterative(basket2,lm,ec); outputModel(stepDates,gsr);\n    npv1 = swaption->NPV();\n    ytsQuote.linkTo(ytsQuote2);\n    gsr->calibrateVolatilitiesIterative(basket2,lm,ec); outputModel(stepDates,gsr);\n    npv2 = swaption->NPV();\n    ytsQuote.linkTo(ytsQuote0);\n\n    for(Size i=0;i<basket2.size();i++) boost::dynamic_pointer_cast<SimpleQuote>(*basket2[i]->volatility())\n                                           ->setValue(volQuote1->value());\n    gsr->calibrateVolatilitiesIterative(basket2,lm,ec); outputModel(stepDates,gsr);\n    npv3 = swaption->NPV();\n    for(Size i=0;i<basket2.size();i++) boost::dynamic_pointer_cast<SimpleQuote>(*basket2[i]->volatility())\n                                           ->setValue(volQuote0->value());\n\n    std::cout << \"NPV(-10bp) = \" << npv2 << \" NPV(0) = \" << npv0 << \" NPV(+10bp) = \" << npv1 << std::endl;\n    std::cout << \"DV01 = \" << (npv1-npv2) / 20.0 << std::endl;\n    std::cout << \"DV02 = \" << (npv1-2.0*npv0+npv2) / 100.0 << std::endl;\n    std::cout << \"Vega = \" << (npv3-npv0) << std::endl;\n\n    std::cout << \"============================================================\" << std::endl;\n    std::cout << \"Compute delta, gamma with basket recalculation and recalibration\" << std::endl;\n    std::cout << \"============================================================\" << std::endl;\n\n    gsr->calibrateVolatilitiesIterative(basket2,lm,ec);\n    outputModel(stepDates,gsr);\n    npv0 = swaption->NPV();\n\n    ytsQuote.linkTo(ytsQuote1);\n    gsr->calibrateVolatilitiesIterative(basket2,lm,ec); outputModel(stepDates,gsr);\n    std::vector<boost::shared_ptr<CalibrationHelper> > basket3a = swaption->calibrationBasket(standardSwapBase,swaptionVol);\n    for(Size i=0;i<basket3a.size();i++) basket3a[i]->setPricingEngine(standardEngine);\n    outputBasket(basket3a,*gsr->termStructure());\n    gsr->calibrateVolatilitiesIterative(basket3a,lm,ec); outputModel(stepDates,gsr);\n    npv1 = swaption->NPV();\n\n    ytsQuote.linkTo(ytsQuote2);\n\n    gsr->calibrateVolatilitiesIterative(basket2,lm,ec); outputModel(stepDates,gsr);\n    std::vector<boost::shared_ptr<CalibrationHelper> > basket3b = swaption->calibrationBasket(standardSwapBase,swaptionVol);\n    for(Size i=0;i<basket3b.size();i++) basket3b[i]->setPricingEngine(standardEngine);\n    outputBasket(basket3b,*gsr->termStructure());\n    gsr->calibrateVolatilitiesIterative(basket3b,lm,ec); outputModel(stepDates,gsr);\n    npv2 = swaption->NPV();\n\n    ytsQuote.linkTo(ytsQuote0);\n\n    for(Size i=0;i<basket2.size();i++) boost::dynamic_pointer_cast<SimpleQuote>(*basket2[i]->volatility())->\n                                           setValue(volQuote1->value());\n    volQuote.linkTo(volQuote1);\n    gsr->calibrateVolatilitiesIterative(basket2,lm,ec); outputModel(stepDates,gsr);\n    std::vector<boost::shared_ptr<CalibrationHelper> > basket3c = swaption->calibrationBasket(standardSwapBase,swaptionVol);\n    for(Size i=0;i<basket3c.size();i++) basket3c[i]->setPricingEngine(standardEngine);\n    outputBasket(basket3c,*gsr->termStructure());\n    gsr->calibrateVolatilitiesIterative(basket3c,lm,ec); outputModel(stepDates,gsr);\n    npv3 = swaption->NPV();\n    for(Size i=0;i<basket2.size();i++) boost::dynamic_pointer_cast<SimpleQuote>(*basket2[i]->volatility())->\n                                           setValue(volQuote0->value());\n    volQuote.linkTo(volQuote0);\n\n\n    std::cout << \"NPV(-10bp) = \" << npv2 << \" NPV(0) = \" << npv0 << \" NPV(+10bp) = \" << npv1 << std::endl;\n    std::cout << \"DV01 = \" << (npv1-npv2) / 20.0 << std::endl;\n    std::cout << \"DV02 = \" << (npv1-2.0*npv0+npv2) / 100.0 << std::endl;\n    std::cout << \"Vega = \" << (npv3-npv0) << std::endl;\n\n\n\n}\n", "meta": {"hexsha": "f1f28dcd6666f032b5b215ff4ad6b9825a3dbb45", "size": 13199, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Examples/CallableBonds2/CallableBonds2.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": "Examples/CallableBonds2/CallableBonds2.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": "Examples/CallableBonds2/CallableBonds2.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": 47.4784172662, "max_line_length": 124, "alphanum_fraction": 0.615425411, "num_tokens": 3653, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6477982315512488, "lm_q1q2_score": 0.4999988529344827}}
{"text": "#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/random.hpp>\n\nusing namespace boost::multiprecision;\nusing namespace boost::random;\n\n\nuint256_t rand_gen(){\n\ttypedef independent_bits_engine<mt19937, 256, uint256_t> generator_type;\n   generator_type gen;\n   //\n   // Generate some values:\n   //\n   //std::cout << std::hex << std::showbase;\n   //for(unsigned i = 0; i < 10; ++i)\n    //  std::cout << gen() << std::endl;\n    return gen();\n}\n", "meta": {"hexsha": "53e6c9d3510ea92b52f9458250330de7fa3fec88", "size": 448, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/rand_gen.hpp", "max_stars_repo_name": "SwaroopReddyBasireddy/Proof-of-Assets", "max_stars_repo_head_hexsha": "011ee85ad4e7941c2bfbf53c1872fbaa40038cf5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/rand_gen.hpp", "max_issues_repo_name": "SwaroopReddyBasireddy/Proof-of-Assets", "max_issues_repo_head_hexsha": "011ee85ad4e7941c2bfbf53c1872fbaa40038cf5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/rand_gen.hpp", "max_forks_repo_name": "SwaroopReddyBasireddy/Proof-of-Assets", "max_forks_repo_head_hexsha": "011ee85ad4e7941c2bfbf53c1872fbaa40038cf5", "max_forks_repo_licenses": ["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.5789473684, "max_line_length": 73, "alphanum_fraction": 0.6629464286, "num_tokens": 120, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6477982179521105, "lm_q1q2_score": 0.4999988424380762}}
{"text": "\n# include <vector>\n# include <iostream>\n# include <string>\n# include <math.h>\n# include <fstream>\n# include <sstream>\n# include <tuple>\n# include <algorithm>\n# include <random>\n# include <chrono>\n#include <unistd.h>\n\n#include <armadillo>\n\n\nusing namespace std;\n\n\nvector<string> split(string& input, char delimiter)\n{\n    istringstream stream(input);\n    string field;\n    vector<string> result;\n    while (getline(stream, field, delimiter)) {\n        result.push_back(field);\n    }\n    return result;\n}\n\nint get_dataset(const char* file_path, int*& ou_array, int*& ov_array, float*& y0_array)\n{\t\n\n\tvector<int> ou;\n\tvector<int> ov;\n\tvector<float> y0;\n\tifstream ifs(file_path);\n\tstring line;\n\twhile(getline(ifs,line)){\n\n\t\tstd::vector<string> strvec = split(line, ' ');\n\n\t\tou.push_back( stoi(strvec.at(0)) );\n\t\tov.push_back( stoi(strvec.at(1)) );\n\t\ty0.push_back( stof(strvec.at(2)) );\n\n\n\t}\n\tint k = ou.size();\n\tou_array = new int[k];\n\tov_array = new int[k];\n\ty0_array = new float[k];\n\tfor (int i = 0; i < k; ++i)\n\t{\n\t\tou_array[i] = ou[i];\n\t\tov_array[i] = ov[i];\n\t\ty0_array[i] = (float)y0[i];\n\t}\n\n\treturn k;\n}\n\nvoid show_vec_array(const std::vector<std::vector<int> >& array)\n{\n\tfor (int i = 0; i < array.size(); ++i)\n\t{\n\t\t\n\t\t// std::vector<int> array_i = array[i];\n\t\tfor (int j = 0; j < array[i].size(); ++j)\n\t\t{\n\t\t\tprintf(\"%i \", array[i][j]);\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n}\n\nvoid show_array(int N, int M, float** array)\n{\n\tfor (int i = 0; i < N; ++i)\n\t{\n\t\tfor (int j = 0; j < M; ++j)\n\t\t{\n\t\t\tprintf(\"%f \", array[i][j]);\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n}\n\nint maximum_value(int* array, int size)\n{\n\tint max = array[0];\n\tfor (int i = 0; i < size; ++i)\n\t{\n\t\tif (max < array[i])\n\t\t{\n\t\t\tmax = array[i];\n\t\t}\n\t}\n\treturn max;\n}\n\nfloat mean_matrix(float** matrix, int N, int M)\n{\n\tfloat sm = 0;\n\tfor (int i = 0; i < N; ++i)\n\t{\n\t\tfor (int j = 0; j < M; ++j)\n\t\t{\n\t\t\tsm += matrix[i][j];\n\t\t}\n\t}\n\tsm = sm/(float)(N*M);\n\treturn sm;\n}\n\nfloat mean_array(float* array, int size)\n{\n\tfloat sm = 0;\n\tfor (int i = 0; i < size; ++i)\n\t{\n\t\tsm += array[i];\n\t}\n\treturn sm/(float)size;\n}\n\nfloat std_array(float* array, int size, float mean)\n{\n\tfloat sm = 0;\n\tfor (int i = 0; i < size; ++i)\n\t{\n\t\tsm += pow(array[i]-mean, 2);\n\t}\n\tsm = sm / (float)size;\n\tsm = sqrt(sm);\n\treturn sm;\n}\n\n\ntuple<  vector< vector<int> >, vector< vector<int> >, vector< vector<int> >, vector< vector<int> >  > getNb(int* ou, int* ov,int N,int M,int k)\n{\n\tvector< vector<int> > nbu;\n\tvector< vector<int> > nbv;\n\tvector< vector<int> > nbul;\n\tvector< vector<int> > nbvl;\n\n\tnbu = vector<vector<int>>(N, vector<int>(0, 0));\n\tnbul = vector<vector<int>>(N, vector<int>(0, 0));\n\tnbv = vector<vector<int>>(M, vector<int>(0, 0));\n\tnbvl = vector<vector<int>>(M, vector<int>(0, 0));\n\n\tfor (int i = 0; i < k; ++i)\n\t{\n\t\tint u_ind = ou[i];\n\t\tint v_ind = ov[i];\n\n\t\tnbu[u_ind].push_back(v_ind);\n\t\tnbul[u_ind].push_back(i);\n\n\t\tnbv[v_ind].push_back(u_ind);\n\t\tnbvl[v_ind].push_back(i);\n\t}\n\n\treturn std::forward_as_tuple(nbu, nbv, nbul, nbvl);\n\n}\n\ntuple<  float**, float**, int, float*  > cbmf(int N, int M, int* ou, int* ov, const vector<vector<int>>& nbu, const vector<vector<int>>& nbv, const vector<vector<int>>& nbul, const vector<vector<int>>& nbvl, int k, float* y0, int maxCnt, float gam, double conv, int R, float lam, int* te_u, int* te_v, float* te_y0, int k_te, float mean, float std)\n{\n\n\tstd::random_device rd;\n\tstd::mt19937 mt(rd());\n\tstd::uniform_real_distribution<float> rdm(0.0, 1.0);\n\n\tfloat *rmse_arr = new float[maxCnt];\n\n\t// allocating memory\n\tfloat **a_hat = new float*[k];\n\tfloat **b_hat = new float*[k];\n\tfloat **c_hat = new float*[k];\n\tfloat **d_hat = new float*[k];\n\tfloat **alf = new float*[k];\n\tfloat **beta = new float*[k];\n\tfloat **gamma = new float*[k];\n\tfloat **delta = new float*[k];\n\tfor (int i = 0; i < k; ++i)\n\t{\n\t\ta_hat[i] = new float[R];\n\t\tb_hat[i] = new float[R];\n\t\tc_hat[i] = new float[R];\n\t\td_hat[i] = new float[R];\n\t\talf[i] = new float[R];\n\t\tbeta[i] = new float[R];\n\t\tgamma[i] = new float[R];\n\t\tdelta[i] = new float[R];\n\t}\n\n\n\tfloat **a_m_hat = new float*[N];\n\tfloat **b_m_hat = new float*[N];\n\tfloat **c_m_hat = new float*[M];\n\tfloat **d_m_hat = new float*[M];\n\tfor (int i = 0; i < N; ++i)\n\t{\n\t\ta_m_hat[i] = new float[R];\n\t\tb_m_hat[i] = new float[R];\n\t}\n\tfor (int i = 0; i < M; ++i)\n\t{\n\t\tc_m_hat[i] = new float[R];\n\t\td_m_hat[i] = new float[R];\n\t}\n\n\tfloat *alf_m = new float[k];\n    float *beta_m = new float[k];\n    float *gamma_m = new float[k];\n    float *delta_m = new float[k];\n\n    float **u = new float*[N];\n    for (int i = 0; i < N; ++i)\n    {\n    \tu[i] = new float[R];\n    }\n    float **v = new float*[M];\n    for (int i = 0; i < M; ++i)\n    {\n    \tv[i] = new float[R];\n    }\n\n\n    auto t0 = std::chrono::system_clock::now();\n\n\n    // initialize u and v\n\tarma::sp_mat spmx(N,M);\n    for (int i = 0; i < k; ++i)\n    {\n    \tspmx(ou[i], ov[i]) = y0[i];\n    }\n    arma::mat U;\n\tarma::vec s;\n\tarma::mat V;\n\n\tsvds(U, s, V, spmx, R);\n\n\ts = arma::sqrt(s);\n\tarma::mat S = diagmat(s);\n\n\tU = U*S;\n\tV = V*S;\n\n\n    for (int i = 0; i < N; ++i)\n    {\n    \tfor (int r = 0; r < R; ++r)\n    \t{\n    \t\tu[i][r] = U(i,r);\n    \t}\n    }\n    for (int i = 0; i < M; ++i)\n    {\n    \tfor (int r = 0; r < R; ++r)\n    \t{\n    \t\tv[i][r] = V(i,r);\n    \t}\n    }\n\n\n\tfor (int i = 0; i < k; ++i)\n\t{\n\t\tfor (int j = 0; j < R; ++j)\n\t\t{\n\t\t\ta_hat[i][j] = rdm(mt)*5;\n\t\t\tb_hat[i][j] = -a_hat[i][j]*u[ou[i]][j];\n\t\t\t\n\t\t\tc_hat[i][j] = rdm(mt)*5;\n\t\t\td_hat[i][j] = -c_hat[i][j]*v[ov[i]][j];\n\t\t}\n\t}\n\n\n\tfor (int i = 0; i < N; ++i)\n\t{\n\t\tfor (int r = 0; r < R; ++r)\n\t\t{\n\t\t\t\n\t\t\tfloat a_sm = 0;\n\t\t\tfloat b_sm = 0;\n\t\t\tfor (const auto& nb: nbul[i])\n\t\t\t{\n\t\t\t\ta_sm += a_hat[nb][r];\n\t\t\t\tb_sm += b_hat[nb][r];\n\t\t\t}\n\t\t\ta_m_hat[i][r] = a_sm + lam;\n\t\t\tb_m_hat[i][r] = b_sm;\n\t\t}\n\t}\n\tfor (int i = 0; i < M; ++i)\n\t{\n\t\tfor (int r = 0; r < R; ++r)\n\t\t{\n\t\t\t\n\t\t\tfloat c_sm = 0;\n\t\t\tfloat d_sm = 0;\n\t\t\tfor (const auto& nb: nbvl[i])\n\t\t\t{\n\t\t\t\tc_sm += c_hat[nb][r];\n\t\t\t\td_sm += d_hat[nb][r];\n\t\t\t}\n\t\t\tc_m_hat[i][r] = c_sm + lam;\n\t\t\td_m_hat[i][r] = d_sm;\n\t\t}\n\t}\n\n\n\tfor (int i = 0; i < k; ++i)\n\t{\n\t\tfor (int r = 0; r < R; ++r)\n\t\t{\n\t\t\tfloat vov = v[ov[i]][r];\n\t\t\tfloat vov2 = pow(vov, 2);\n\t\t\tfloat uou = u[ou[i]][r];\n    \t\tfloat uou2 = pow(uou, 2);\n\t\t\talf[i][r] = vov2 / ( a_m_hat[ou[i]][r] - a_hat[i][r] );\n\t\t\tbeta[i][r] = ( b_m_hat[ou[i]][r] - b_hat[i][r] ) * vov / ( a_m_hat[ou[i]][r] - a_hat[i][r] );\n\t\t\tgamma[i][r] = uou2 /( c_m_hat[ov[i]][r] - c_hat[i][r] );\n\t\t\tdelta[i][r] = ( d_m_hat[ov[i]][r] - d_hat[i][r] ) * uou / ( c_m_hat[ov[i]][r] - c_hat[i][r] );\n\t\t}\n\t}\n\n\tfloat sm1;\n\tfloat sm2;\n\tfloat sm3;\n\tfloat sm4;\n\tfor (int i = 0; i < k; ++i)\n\t{\t\n\t\tsm1 = 0;\n\t\tsm2 = 0;\n\t\tsm3 = 0;\n\t\tsm4 = 0;\n\t\tfor (int r = 0; r < R; ++r)\n\t\t{\n\t\t\tsm1 += alf[i][r];\n\t\t\tsm2 += beta[i][r];\n\t\t\tsm3 += gamma[i][r];\n\t\t\tsm4 += delta[i][r];\n\t\t}\n\t\talf_m[i] = sm1 + 1;\n\t\tbeta_m[i] = sm2;\n\t\tgamma_m[i] = sm3 + 1;\n\t\tdelta_m[i] = sm4;\n\t}\n\t\n\n\n\t  ///////////////\n     /* main loop */\n    ///////////////\n    int cnt;\n    float rmse = 0.0;\n    for (cnt = 0; cnt < maxCnt; ++cnt)\n    {\n\n    \t/* u update */\n\n\n    \t// update alf and beta\n    \tfloat dm;\n    \tfloat vov;\n    \tfloat vov2;\n    \tfor (int i = 0; i < k; ++i)\n\t\t{\n\t\t\tfor (int r = 0; r < R; ++r)\n\t\t\t{\n\t\t\t\tvov = v[ov[i]][r];\n\t\t\t\tvov2 = pow(vov, 2);\n\t\t\t\tdm = a_m_hat[ou[i]][r] - a_hat[i][r];\n\n\t\t\t\talf[i][r] = vov2 / dm;\n\t\t\t\tbeta[i][r] = ( b_m_hat[ou[i]][r] - b_hat[i][r] ) * vov / dm;\n\t\t\t}\n\t\t}\n\n\n\t\t// update alf_m and beta_m\n\t\tfloat sm1;\n\t\tfloat sm2;\n\t\tfor (int i = 0; i < k; ++i)\n\t\t{\t\n\t\t\tsm1 = 0;\n\t\t\tsm2 = 0;\n\t\t\tfor (int r = 0; r < R; ++r)\n\t\t\t{\n\t\t\t\tsm1 += alf[i][r];\n\t\t\t\tsm2 += beta[i][r];\n\t\t\t}\n\t\t\talf_m[i] = sm1 + 1;\n\t\t\tbeta_m[i] = sm2 + y0[i];\n\t\t}\n\n\n    \t// update a and b hat\n    \tfor (int i = 0; i < k; ++i)\n    \t{\t\n    \t\tfor (int r = 0; r < R; ++r)\n    \t\t{\n    \t\t\tvov = v[ov[i]][r];\n    \t\t\tvov2 = pow(vov, 2);\n    \t\t\tdm = alf_m[i] - alf[i][r];\n\n    \t\t\ta_hat[i][r] = (1-gam)*a_hat[i][r] + gam*vov2/dm;\n    \t\t\tb_hat[i][r] = (1-gam)*b_hat[i][r] - gam*( beta_m[i] - beta[i][r] )*vov/dm;\n    \t\t}\n    \t}\n\n\n    \t// update a and b marginalized hat\n    \tfloat a_sm;\n    \tfloat b_sm;\n    \tfor (int i = 0; i < N; ++i)\n\t\t{\n\t\t\tfor (int r = 0; r < R; ++r)\n\t\t\t{\n\t\t\t\ta_sm = 0;\n\t\t\t\tb_sm = 0;\n\t\t\t\tfor (const auto& nb: nbul[i])\n\t\t\t\t{\n\t\t\t\t\ta_sm += a_hat[nb][r];\n\t\t\t\t\tb_sm += b_hat[nb][r];\n\t\t\t\t}\n\t\t\t\ta_m_hat[i][r] = a_sm + lam;\n\t\t\t\tb_m_hat[i][r] = b_sm;\n\t\t\t}\n\t\t}\n\n\n\t\t// update u\n\t\tfor (int i = 0; i < N; ++i)\n\t\t{\n\t\t\tfor (int r = 0; r < R; ++r)\n\t\t\t{\n\t\t\t\tu[i][r] = -b_m_hat[i][r]/a_m_hat[i][r];\n\t\t\t}\n\t\t}\n\n\n\n\t\t/* update v */\n\n\t\t// update gamma and delta\n\t\tfloat uou;\n\t\tfloat uou2;\n\t\tfor (int i = 0; i < k; ++i)\n\t\t{\n\t\t\tfor (int r = 0; r < R; ++r)\n\t\t\t{\n\t\t\t\tuou = u[ou[i]][r];\n\t    \t\tuou2 = pow(uou, 2);\n\t    \t\tdm = c_m_hat[ov[i]][r] - c_hat[i][r];\n\n\t\t\t\tgamma[i][r] = uou2 /dm;\n\t\t\t\tdelta[i][r] = ( d_m_hat[ov[i]][r] - d_hat[i][r] ) * uou / dm;\n\t\t\t}\n\t\t}\n\n\n\t\t// update gamma_m and delta_m\n\t\tfor (int i = 0; i < k; ++i)\n\t\t{\t\n\t\t\tsm1 = 0.0;\n\t\t\tsm2 = 0.0;\n\t\t\tfor (int r = 0; r < R; ++r)\n\t\t\t{\n\t\t\t\tsm1 += gamma[i][r];\n\t\t\t\tsm2 += delta[i][r];\n\t\t\t}\n\t\t\tgamma_m[i] = sm1 + 1;\n\t\t\tdelta_m[i] = sm2 + y0[i];\n\t\t}\n\n\n\t\t// update c and d hat\n    \tfor (int i = 0; i < k; ++i)\n    \t{\n    \t\tfor (int r = 0; r < R; ++r)\n    \t\t{\n    \t\t\tuou = u[ou[i]][r];\n    \t\t\tuou2 = pow(uou, 2);\n    \t\t\tdm = gamma_m[i] - gamma[i][r];\n\n    \t\t\tc_hat[i][r] = (1-gam)*c_hat[i][r] + gam*uou2/dm;\n    \t\t\td_hat[i][r] = (1-gam)*d_hat[i][r] - gam*( delta_m[i] - delta[i][r] )*uou/dm;\n    \t\t}\n    \t}\n\n    \t// update c and d marginalized hat\n    \tfloat c_sm;\n    \tfloat d_sm;\n    \tfor (int i = 0; i < M; ++i)\n\t\t{\n\t\t\tfor (int r = 0; r < R; ++r)\n\t\t\t{\n\t\t\t\t\n\t\t\t\tc_sm = 0;\n\t\t\t\td_sm = 0;\n\t\t\t\tfor (const auto& nb: nbvl[i])\n\t\t\t\t{\n\t\t\t\t\tc_sm += c_hat[nb][r];\n\t\t\t\t\td_sm += d_hat[nb][r];\n\t\t\t\t}\n\t\t\t\tc_m_hat[i][r] = c_sm + lam;\n\t\t\t\td_m_hat[i][r] = d_sm;\n\t\t\t}\n\t\t}\n\n\t\t\n\n\t\t// update v\n\t\tfor (int i = 0; i < M; ++i)\n\t\t{\n\t\t\tfor (int r = 0; r < R; ++r)\n\t\t\t{\n\t\t\t\tv[i][r] = -d_m_hat[i][r]/c_m_hat[i][r];\n\t\t\t}\n\t\t}\n\n\n\n\t\t// calulate test rmse\n\t\tfloat mse = 0;\n\t\tfor (int i = 0; i < k_te; ++i)\n\t\t{\n\n\t\t\tfloat inf_y0 = 0;\n\t\t\tint u_i = te_u[i];\n\t\t\tint v_i = te_v[i];\n\t\t\tfor (int r = 0; r < R; ++r)\n\t\t\t{\n\t\t\t\tinf_y0 += u[u_i][r]*v[v_i][r];\n\t\t\t}\n\t\t\tinf_y0 = inf_y0*std + mean;\n\t\t\tmse += pow(inf_y0 - te_y0[i], 2);\n\n\t\t}\n\t\tmse = mse / (float)k_te;\n\t\tfloat new_rmse = sqrt(mse);\n\t\tfloat dif = abs(new_rmse-rmse);\n\n\t\trmse_arr[cnt] = new_rmse;\n\n\t\tif (cnt%1 == 0)\n\t\t{\n\t\t\tprintf(\"iteration:%d \", cnt);\n\t\t\tprintf(\"rmse:%f\\n\", new_rmse);\n\t\t}\n\n\t\trmse = new_rmse;\n\t\tif (dif < conv || dif != dif)\n\t\t{\n\t\t\tbreak;\n\t\t}\n\t\t\n\n\n    } // end main loop\n\n    return std::forward_as_tuple(u, v, cnt, rmse_arr);\n\n}\n\n\n\ntuple<  float**, float**, int, float*  > approx_cbmf(int N, int M, int* ou, int* ov, const vector<vector<int>>& nbu, const vector<vector<int>>& nbv, const vector<vector<int>>& nbul, const vector<vector<int>>& nbvl, int k, float* y0, int maxCnt, float gam, double conv, int R, float lam, int* te_u, int* te_v, float* te_y0, int k_te, float mean, float std)\n{\n\n\tstd::random_device rd;\n\tstd::mt19937 mt(rd());\n\tstd::uniform_real_distribution<float> rdm(0.0, 1.0);\n\tstd::normal_distribution<float> g_rdm(0.0,1.0);\n\n\tfloat *rmse_arr = new float[maxCnt];\n\n\t// allocating memory\n\tfloat *a = new float[k];\n\tfloat *b = new float[k];\n\tfloat *c = new float[k];\n\tfloat *d = new float[k];\n\n\n\tfloat **a_hat = new float*[N];\n\tfloat **b_hat = new float*[N];\n\tfloat **u = new float*[N];\n\tfloat **c_hat = new float*[M];\n\tfloat **d_hat = new float*[M];\n\tfloat **v = new float*[M];\n\tfor (int i = 0; i < N; ++i)\n\t{\n\t\ta_hat[i] = new float[R];\n\t\tb_hat[i] = new float[R];\n\t\tu[i] = new float[R];\n\t}\n\tfor (int i = 0; i < M; ++i)\n\t{\n\t\tc_hat[i] = new float[R];\n\t\td_hat[i] = new float[R];\n\t\tv[i] = new float[R];\n\t}\n\n\n    arma::sp_mat spmx(N,M);\n    for (int i = 0; i < k; ++i)\n    {\n    \tspmx(ou[i], ov[i]) = y0[i];\n    }\n    arma::mat U;\n\tarma::vec s;\n\tarma::mat V;\n\n\tsvds(U, s, V, spmx, R);\n\n\ts = arma::sqrt(s);\n\tarma::mat S = diagmat(s);\n\n\tU = U*S;\n\tV = V*S;\n\n\n    for (int i = 0; i < N; ++i)\n    {\n    \tfor (int r = 0; r < R; ++r)\n    \t{\n    \t\tu[i][r] = U(i,r);\n    \t}\n    }\n    for (int i = 0; i < M; ++i)\n    {\n    \tfor (int r = 0; r < R; ++r)\n    \t{\n    \t\tv[i][r] = V(i,r);\n    \t}\n    }\n\n\n    // initialize a,b,c,d hat\n\tfor (int i = 0; i < N; ++i)\n\t{\n\t\tfor (int j = 0; j < R; ++j)\n\t\t{\n\t\t\ta_hat[i][j] = rdm(mt)+100;\n\t\t\tb_hat[i][j] = (a_hat[i][j])*u[i][j];\n\t\t}\n\t}\n\tfor (int i = 0; i < M; ++i)\n\t{\n\t\tfor (int j = 0; j < R; ++j)\n\t\t{\n\t\t\tc_hat[i][j] = rdm(mt)+100;\n\t\t\td_hat[i][j] = (c_hat[i][j])*v[i][j];\n\t\t}\n\t}\n\n\t// initialize alf, beta, gamma, delta\n\tfor (int i = 0; i < k; ++i)\n\t{\n\t\ta[i] = rdm(mt);\n\t\tb[i] = rdm(mt);\n\t\tc[i] = rdm(mt);\n\t\td[i] = rdm(mt);\n\t}\n\n\n\t  ///////////////\n     /* main loop */\n    ///////////////\n    printf(\"main loop\\n\");\n    float vov;\n\tfloat vov2;\n\tfloat uou;\n\tfloat uou2;\n    float sm1;\n    float sm2;\n    int cnt;\n    float rmse = 0.0;\n    for (cnt = 0; cnt < maxCnt; ++cnt)\n    {\n\n    \t/* u update */\n\n    \t// update alf and beta\n    \tfor (int i = 0; i < k; ++i)\n\t\t{\t\n\t\t\tsm1 = 0;\n\t\t\tsm2 = 0;\n\t\t\tfor (int r = 0; r < R; ++r)\n\t\t\t{\n\t\t\t\tvov = v[ov[i]][r];\n\t\t\t\tuou = u[ou[i]][r];\n\t\t\t\tvov2 = pow(vov, 2);\n\n\n\t\t\t\t// a\n\t\t\t\tsm1 += vov2/(a_hat[ou[i]][r]+lam);\n\t\t\t\t// b\n\t\t\t\tsm2 += vov*uou;\n\t\t\t}\n\t\t\tb[i] = ( y0[i]-sm2+a[i]*b[i] ) / ( 1+a[i] );\n\t\t\ta[i] = sm1;\n\t\t\t\n\t\t}\n\n\n\n    \t// update a and b hat\n    \tfor (int i = 0; i < N; ++i)\n\t\t{\n\t\t\tfor (int r = 0; r < R; ++r)\n\t\t\t{\n\t\t\t\tsm1 = 0;\n\t\t\t\tsm2 = 0;\n\t\t\t\tfor (const auto& nb: nbul[i])\n\t\t\t\t{\n\t\t\t\t\tvov = v[ov[nb]][r];\n\t\t\t\t\tvov2 = pow(vov, 2);\n\t\t\t\t\tuou = u[i][r];\n\n\t\t\t\t\t// a_hat\n\t\t\t\t\tsm1 += vov2/(1+a[nb]);\n\n\t\t\t\t\t// b_hat\n\t\t\t\t\tsm2 += b[nb]*vov;\n\t\t\t\t\tsm2 += uou*vov2/(1+a[nb]);\n\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tb_hat[i][r] = (1-gam)*b_hat[i][r] + gam*sm2;\n\t\t\t\ta_hat[i][r] = (1-gam)*a_hat[i][r] + gam*sm1;\n\n\t\t\t\t// update u\n\t\t\t\tu[i][r] = b_hat[i][r]/(a_hat[i][r]+lam);\n\n\t\t\t}\n\t\t}\n\n\n\n\t\t/* update v */\n\n\t\t// update c and d\n    \tfor (int i = 0; i < k; ++i)\n\t\t{\t\n\t\t\tsm1 = 0;\n\t\t\tsm2 = 0;\n\t\t\tfor (int r = 0; r < R; ++r)\n\t\t\t{\n\t\t\t\tvov = v[ov[i]][r];\n\t\t\t\tuou = u[ou[i]][r];\n\t\t\t\tuou2 = pow(uou, 2);\n\n\t\t\t\t// a\n\t\t\t\tsm1 += uou2/(c_hat[ov[i]][r]+lam);\n\t\t\t\t// b\n\t\t\t\tsm2 += vov*uou;\n\t\t\t}\n\t\t\td[i] = ( y0[i]-sm2+c[i]*d[i] ) / ( 1+c[i] );\n\t\t\tc[i] = sm1;\n\t\t\t\n\t\t}\n\n\n\t\t// update c and d hat\n    \tfor (int i = 0; i < M; ++i)\n\t\t{\n\t\t\tfor (int r = 0; r < R; ++r)\n\t\t\t{\n\t\t\t\tsm1 = 0;\n\t\t\t\tsm2 = 0;\n\t\t\t\tfor (const auto& nb: nbvl[i])\n\t\t\t\t{\n\t\t\t\t\t// vov = v[ov[nb]][r];\n\t\t\t\t\tvov = v[i][r];\n\t\t\t\t\tuou = u[ou[nb]][r];\n\t\t\t\t\tuou2 = pow(uou, 2);\n\n\t\t\t\t\t// a_hat\n\t\t\t\t\tsm1 += uou2/(1+c[nb]);\n\n\t\t\t\t\t// b_hat\n\t\t\t\t\tsm2 += d[nb]*uou;\n\t\t\t\t\tsm2 += vov*uou2/(1+c[nb]);\n\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\td_hat[i][r] = (1-gam)*d_hat[i][r] + gam*sm2;\n\t\t\t\tc_hat[i][r] = (1-gam)*c_hat[i][r] + gam*sm1;\n\n\t\t\t\t// update v\n\t\t\t\tv[i][r] = d_hat[i][r]/(c_hat[i][r]+lam);\n\t\t\t}\n\t\t}\n\t\t\n\n\n\n\t\t// calulate test rmse\n\t\tfloat mse = 0;\n\t\tfor (int i = 0; i < k_te; ++i)\n\t\t{\n\n\t\t\tfloat inf_y0 = 0;\n\t\t\tint u_i = te_u[i];\n\t\t\tint v_i = te_v[i];\n\t\t\tfor (int r = 0; r < R; ++r)\n\t\t\t{\n\t\t\t\tinf_y0 += u[u_i][r]*v[v_i][r];\n\t\t\t}\n\t\t\tinf_y0 = inf_y0*std + mean;\n\n\t\t\tmse += pow(inf_y0 - te_y0[i], 2);\n\n\t\t}\n\t\tmse = mse / (float)k_te;\n\t\tfloat new_rmse = sqrt(mse);\n\t\tfloat dif = abs(new_rmse-rmse);\n\n\t\trmse_arr[cnt] = new_rmse;\n\n\t\tif (cnt%1 == 0)\n\t\t{\n\t\t\tprintf(\"iteration:%d \", cnt);\n\t\t\tprintf(\"rmse:%f\\n\", new_rmse);\n\t\t}\n\n\t\trmse = new_rmse;\n\t\tif (dif < conv || dif != dif)\n\t\t{\n\t\t\tbreak;\n\t\t}\n\n\n    } // end main loop\n\n    return std::forward_as_tuple(u, v, cnt, rmse_arr);\n\n}\n\nvoid usage(string& doc)\n{\n\tdoc = \"Usage:\\n\";\n\tdoc += \"   ./cbmf [-l learningrate] [-L lambda] [-R rank] [-m maxiteration] [-r trainfilename] [-t testfilename] [-o outpath] [-c convint] [-p] [-h] [-v]\\n\";\n\tdoc += \"\\n\";\n\tdoc += \"Options:\\n\";\n\tdoc += \"   -l   Learning rate. [default: 0.3]\\n\";\n\tdoc += \"   -L   Regularization parameter. [default: 3]\\n\";\n\tdoc += \"   -R   Rank. [default: 10]\\n\";\n\tdoc += \"   -m   Maximum number of iterations. [default: 100]\\n\";\n\tdoc += \"   -r   Filename of dataset for training. [default: dataset/ml_1m_train.txt]\\n\";\n\tdoc += \"   -t   Filename of dataset for test. [default: dataset/ml_1m_test.txt]\\n\";\n\tdoc += \"   -o   Where output files are to be placed. [default: output/]\\n\";\n\tdoc += \"   -c   Exponent of convergence condition. If RMSE < pow(10, convint) is satisfied, it is regarded as convergence. [default: -5]\\n\";\n\tdoc += \"   -p   If this option is set, ACBMF is to be performed. Without this option, CBMF is to be done.\\n\";\n\tdoc += \"   -h   Show help.\\n\";\n\tdoc += \"   -v   Show version.\\n\";\n\tdoc += \"\\n\";\n\tdoc += \"Examples:\\n\";\n\tdoc += \"Performing CBMF using 'dataset/ml_1m_train.txt' as training dataset and 'dataset/ml_1m_test.txt' as test dataset.\\n\";\n\tdoc += \"   ./cbmf -r dataset/ml_1m_train.txt -t dataset/ml_1m_test.txt\\n\";\n\tdoc += \"Performing ACBMF using 'dataset/ml_1m_train.txt' as training dataset and 'dataset/ml_1m_test.txt' as test dataset.\\n\";\n\tdoc += \"   ./cbmf -p -r dataset/ml_1m_train.txt -t dataset/ml_1m_test.txt\\n\";\n\tdoc += \"Showing help.\\n\";\n\tdoc += \"   ./cbmf -h\\n\";\n\tdoc += \"Showing version.\\n\";\n\tdoc += \"   ./cbmf -v\";\n}\n\nvoid version(string& doc)\n{\n\tdoc = \"cbmf v1.0\";\n}\n\n\nint main(int argc, char **argv)\n{\n\tfloat gam = 0.3;\n\tfloat lam = 3;\n\tint R = 10;\n\tint maxCnt = 100;\n\tconst char* train_filename = \"dataset/ml_1m_train.txt\";\n\tconst char* test_filename = \"dataset/ml_1m_test.txt\";\n\tconst char* outpath = \"output/\";\n\tint is_approx = 0;\n\tint conv_int = -5;\n\tint opt;\n\tstring doc = \"\";\n\tusage(doc);\n\tstring vsn = \"\";\n\tversion(vsn);\n\twhile ((opt = getopt(argc, argv, \"l:L:R:m:r:t:o:c:pshv\")) != -1) {\n        switch (opt) {\n            case 'l': gam=atof(optarg); break;\n            case 'L': lam=atof(optarg); break;\n            case 'R': R=atoi(optarg); break;\n            case 'm': maxCnt=atoi(optarg); break;\n            case 'r': train_filename=optarg; break;\n            case 't': test_filename=optarg; break;\n            case 'o': outpath=optarg; break;\n            case 'c': conv_int=atoi(optarg); break;\n            case 'p': is_approx=1; break;\n            case 'h':\n            \tprintf(\"%s\\n\", doc.c_str());\n            \treturn 0;\n            case 'v':\n            \tprintf(\"%s\\n\", vsn.c_str());\n            \treturn 0;\n            default: \n            \tprintf(\"%s\\n\", doc.c_str());\n            \treturn 1;\n        }\n    }\n    double conv = pow(10, conv_int);\n\tint folds = 10;\n\n\t\n\tprintf(\"learning rate:%f\\n\", gam);\n\tprintf(\"lambda:%f\\n\", lam);\n\tprintf(\"rank:%d\\n\", R);\n\tprintf(\"maxCnt:%d\\n\", maxCnt);\n\tprintf(\"is_approx:%d\\n\", is_approx);\n\tprintf(\"conv:%f\\n\", conv);\n\n\n\tint* ou_te = NULL;\n\tint* ov_te = NULL;\n\tfloat* y0_te = NULL;\n\tint* ou_tr = NULL;\n\tint* ov_tr = NULL;\n\tfloat* y0_tr = NULL;\n\tint k_te = get_dataset(test_filename,ou_te, ov_te, y0_te);\n\tint k_tr = get_dataset(train_filename,ou_tr, ov_tr, y0_tr);\n\n\tprintf(\"dataset loaded\\n\");\n\n\tint N = maximum_value(ou_tr, k_tr)+1;\n\tint M = maximum_value(ov_tr, k_tr)+1;\n\tint K = k_tr;\n\tprintf(\"N:%d\\n\", N);\n\tprintf(\"M:%d\\n\", M);\n\tprintf(\"K:%d\\n\", K);\n\n\n\tfloat mean = mean_array(y0_tr, k_tr);\n\tfloat std = std_array(y0_tr, k_tr, mean);\n\tprintf(\"mean:%f\\n\", mean);\n\tprintf(\"std:%f\\n\", std);\n\tfor (int i = 0; i < k_tr; ++i)\n\t{\n\t\ty0_tr[i] = (y0_tr[i]-mean)/std;\n\t}\n\n\n\tvector< vector<int> > nbu;\n\tvector< vector<int> > nbv;\n\tvector< vector<int> > nbul;\n\tvector< vector<int> > nbvl;\n\tstd::tie(nbu, nbv, nbul, nbvl) = getNb(ou_tr, ov_tr, N, M, K);\n\n\tprintf(\"got nb\\n\");\n\n\n\tfloat** u;\n\tfloat** v;\n\tint cnt;\n\tfloat* rmse_arr;\n\n\tauto start = std::chrono::system_clock::now();\n\tif (is_approx == 0)\n\t{\n\t\tstd::tie(u, v, cnt, rmse_arr) = cbmf(N, M, ou_tr, ov_tr, nbu, nbv, nbul, nbvl, K, y0_tr, maxCnt, gam, conv, R, lam, ou_te, ov_te, y0_te, k_te, mean, std);\n\t}\n\telse\n\t{\n\t\tstd::tie(u, v, cnt, rmse_arr) = approx_cbmf(N, M, ou_tr, ov_tr, nbu, nbv, nbul, nbvl, K, y0_tr, maxCnt, gam, conv, R, lam, ou_te, ov_te, y0_te, k_te, mean, std);\n\t}\n\tauto end = std::chrono::system_clock::now();\n\n\t\n\tchar gam_char[8];\n\tsprintf(gam_char, \"%.2f\", gam);\n\tchar lam_char[8];\n\tsprintf(lam_char, \"%.5f\", lam);\n\tstd::string filename_base = \"gam=\" + string(gam_char) + \"_lam=\" + string(lam_char) + \"_R=\" + to_string(R) + \"_is_approx=\" + to_string(is_approx);\n\tofstream rmse_f(outpath + filename_base + \"_rmse_approx.txt\");\n\tfor (int i = 0; i < cnt+1; ++i)\n\t{\n\t\tchar rmse_char[16];\n\t\tsprintf(rmse_char, \"%.5f\", rmse_arr[i]);\n\t\trmse_f << rmse_char;\n\t\trmse_f << '\\n';\n\t}\n\trmse_f.close();\n\t\n\n\tprintf(\"main end\\n\");\n\t\n\t \n\treturn 0;\n}", "meta": {"hexsha": "0f7d533446c0871221c5ad8cdd1129a0dd80621d", "size": 20196, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cbmf.cpp", "max_stars_repo_name": "chnoguchi/cbmf", "max_stars_repo_head_hexsha": "3fceb4605b5f682c42606fb067d49efd85a593a6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cbmf.cpp", "max_issues_repo_name": "chnoguchi/cbmf", "max_issues_repo_head_hexsha": "3fceb4605b5f682c42606fb067d49efd85a593a6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cbmf.cpp", "max_forks_repo_name": "chnoguchi/cbmf", "max_forks_repo_head_hexsha": "3fceb4605b5f682c42606fb067d49efd85a593a6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-28T02:50:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-09T14:21:40.000Z", "avg_line_length": 20.0955223881, "max_line_length": 355, "alphanum_fraction": 0.5051000198, "num_tokens": 7850, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.49999884243807613}}
{"text": "\r\n#include <NTL/LLL.h>\r\n\r\n#include <NTL/new.h>\r\n\r\nNTL_START_IMPL\r\n\r\n\r\nstatic void ExactDiv(ZZ& qq, const ZZ& a, const ZZ& b)\r\n{\r\n   NTL_ZZRegister(q);\r\n   NTL_ZZRegister(r);\r\n\r\n   DivRem(q, r, a, b);\r\n   if (!IsZero(r)) {\r\n      cerr << \"a = \" << a << \"\\n\";\r\n      cerr << \"b = \" << b << \"\\n\";\r\n      LogicError(\"ExactDiv: nonzero remainder\");\r\n   }\r\n   qq = q;\r\n}\r\n\r\n\r\nstatic void BalDiv(ZZ& q, const ZZ& a, const ZZ& d)\r\n\r\n//  rounds a/d to nearest integer, breaking ties\r\n//    by rounding towards zero.  Assumes d > 0.\r\n\r\n{\r\n   NTL_ZZRegister(r);\r\n   DivRem(q, r, a, d);\r\n\r\n\r\n   add(r, r, r);\r\n\r\n   long cmp = compare(r, d);\r\n   if (cmp > 0 || (cmp == 0 && q < 0))\r\n      add(q, q, 1);\r\n}\r\n\r\n\r\n\r\nstatic void MulAddDiv(ZZ& c, const ZZ& c1, const ZZ& c2, \r\n                      const ZZ& x, const ZZ& y, const ZZ& z)\r\n\r\n// c = (x*c1 + y*c2)/z\r\n\r\n{\r\n   NTL_ZZRegister(t1);\r\n   NTL_ZZRegister(t2);\r\n\r\n   mul(t1, x, c1);\r\n   mul(t2, y, c2);\r\n   add(t1, t1, t2);\r\n   ExactDiv(c, t1, z);\r\n}\r\n\r\n\r\nstatic void MulSubDiv(ZZ& c, const ZZ& c1, const ZZ& c2, \r\n                      const ZZ& x, const ZZ& y, const ZZ& z)\r\n\r\n// c = (x*c1 - y*c2)/z\r\n\r\n{\r\n   NTL_ZZRegister(t1);\r\n   NTL_ZZRegister(t2);\r\n\r\n   mul(t1, x, c1);\r\n   mul(t2, y, c2);\r\n   sub(t1, t1, t2);\r\n   ExactDiv(c, t1, z);\r\n}\r\n   \r\n\r\n\r\n\r\n\r\n#if 0\r\n\r\nstatic void MulSubDiv(vec_ZZ& c, const vec_ZZ& c1, const vec_ZZ& c2,\r\n                      const ZZ& x, const ZZ& y, const ZZ& z)\r\n\r\n// c = (x*c1 + y*c2)/z\r\n\r\n{\r\n   long n = c1.length();\r\n   if (c2.length() != n) LogicError(\"MulSubDiv: length mismatch\");\r\n   c.SetLength(n);\r\n\r\n   long i;\r\n   for (i = 1; i <= n; i++) \r\n      MulSubDiv(c(i), c1(i), c2(i), x, y, z);\r\n}\r\n\r\n#endif\r\n\r\nstatic void RowTransform(vec_ZZ& c1, vec_ZZ& c2,\r\n                         const ZZ& x, const ZZ& y, const ZZ& u, const ZZ& v)\r\n\r\n// (c1, c2) = (x*c1 + y*c2, u*c1 + v*c2)\r\n\r\n{\r\n   long n = c1.length();\r\n   if (c2.length() != n) LogicError(\"MulSubDiv: length mismatch\");\r\n   NTL_ZZRegister(t1);\r\n   NTL_ZZRegister(t2);\r\n   NTL_ZZRegister(t3);\r\n   NTL_ZZRegister(t4);\r\n\r\n   long i;\r\n   for (i = 1; i <= n; i++) {\r\n      mul(t1, x, c1(i));\r\n      mul(t2, y, c2(i));\r\n      add(t1, t1, t2);\r\n\r\n      mul(t3, u, c1(i));\r\n      mul(t4, v, c2(i));\r\n      add(t3, t3, t4);\r\n\r\n      c1(i) = t1;\r\n      c2(i) = t3;\r\n   }\r\n}\r\n\r\nstatic void RowTransform(ZZ& c1, ZZ& c2,\r\n                         const ZZ& x, const ZZ& y, const ZZ& u, const ZZ& v)\r\n\r\n// (c1, c2) = (x*c1 + y*c2, u*c1 + v*c2)\r\n\r\n{\r\n   NTL_ZZRegister(t1);\r\n   NTL_ZZRegister(t2);\r\n   NTL_ZZRegister(t3);\r\n   NTL_ZZRegister(t4);\r\n\r\n   mul(t1, x, c1);\r\n   mul(t2, y, c2);\r\n   add(t1, t1, t2);\r\n\r\n   mul(t3, u, c1);\r\n   mul(t4, v, c2);\r\n   add(t3, t3, t4);\r\n\r\n   c1 = t1;\r\n   c2 = t3;\r\n}\r\n\r\n\r\n\r\nstatic void MulSubFrom(vec_ZZ& c, const vec_ZZ& c2, const ZZ& x)\r\n\r\n// c = c - x*c2\r\n\r\n{\r\n   long n = c.length();\r\n   if (c2.length() != n) LogicError(\"MulSubFrom: length mismatch\");\r\n\r\n   long i;\r\n   for (i = 1; i <= n; i++)\r\n      MulSubFrom(c(i), c2(i), x);\r\n}\r\n\r\nstatic void MulSubFrom(vec_ZZ& c, const vec_ZZ& c2, long x)\r\n\r\n// c = c - x*c2\r\n\r\n{\r\n   long n = c.length();\r\n   if (c2.length() != n) LogicError(\"MulSubFrom: length mismatch\");\r\n\r\n   long i;\r\n   for (i = 1; i <= n; i++)\r\n      MulSubFrom(c(i), c2(i), x);\r\n}\r\n\r\n\r\n      \r\n      \r\n   \r\nstatic long SwapTest(const ZZ& d0, const ZZ& d1, const ZZ& d2, const ZZ& lam,\r\n                     long a, long b)\r\n\r\n// test if a*d1^2 > b*(d0*d2 + lam^2)\r\n\r\n{\r\n   NTL_ZZRegister(t1);\r\n   NTL_ZZRegister(t2);\r\n\r\n   mul(t1, d0, d2);\r\n   sqr(t2, lam);\r\n   add(t1, t1, t2);\r\n   mul(t1, t1, b);\r\n\r\n   sqr(t2, d1);\r\n   mul(t2, t2, a);\r\n\r\n   return t2 > t1;\r\n}\r\n\r\n\r\n\r\n\r\n\r\n\r\nstatic\r\nvoid reduce(long k, long l, \r\n            mat_ZZ& B, vec_long& P, vec_ZZ& D, \r\n            vec_vec_ZZ& lam, mat_ZZ* U)\r\n{\r\n   NTL_ZZRegister(t1);\r\n   NTL_ZZRegister(r);\r\n\r\n   if (P(l) == 0) return;\r\n   add(t1, lam(k)(P(l)), lam(k)(P(l)));\r\n   abs(t1, t1);\r\n   if (t1 <= D[P(l)]) return;\r\n\r\n   long j;\r\n   long rr, small_r;\r\n\r\n   BalDiv(r, lam(k)(P(l)), D[P(l)]);\r\n\r\n   if (r.WideSinglePrecision()) {\r\n      small_r = 1;\r\n      rr = to_long(r);\r\n   }\r\n   else {\r\n      small_r = 0;\r\n   }\r\n      \r\n   if (small_r) {\r\n      MulSubFrom(B(k), B(l), rr);\r\n\r\n      if (U) MulSubFrom((*U)(k), (*U)(l), rr);\r\n\r\n      for (j = 1; j <= l-1; j++)\r\n         if (P(j) != 0)\r\n            MulSubFrom(lam(k)(P(j)), lam(l)(P(j)), rr);\r\n      MulSubFrom(lam(k)(P(l)), D[P(l)], rr);\r\n   }\r\n   else {\r\n      MulSubFrom(B(k), B(l), r);\r\n\r\n      if (U) MulSubFrom((*U)(k), (*U)(l), r);\r\n\r\n      for (j = 1; j <= l-1; j++)\r\n         if (P(j) != 0)\r\n            MulSubFrom(lam(k)(P(j)), lam(l)(P(j)), r);\r\n      MulSubFrom(lam(k)(P(l)), D[P(l)], r);\r\n   }\r\n\r\n\r\n}\r\n\r\n\r\nstatic\r\nlong swap(long k, mat_ZZ& B, vec_long& P, vec_ZZ& D, \r\n          vec_vec_ZZ& lam, mat_ZZ* U, long m, long verbose)\r\n\r\n// swaps vectors k-1 and k;  assumes P(k-1) != 0\r\n// returns 1 if vector k-1 need to be reduced after the swap...\r\n//    this only occurs in 'case 2' when there are linear dependencies\r\n\r\n{\r\n   long i, j;\r\n   NTL_ZZRegister(t1);\r\n   NTL_ZZRegister(t2);\r\n   NTL_ZZRegister(t3);\r\n   NTL_ZZRegister(e);\r\n   NTL_ZZRegister(x);\r\n   NTL_ZZRegister(y);\r\n\r\n\r\n   if (P(k) != 0) {\r\n      if (verbose) cerr << \"swap case 1: \" << k << \"\\n\";\r\n\r\n      swap(B(k-1), B(k));\r\n      if (U) swap((*U)(k-1), (*U)(k));\r\n   \r\n      for (j = 1; j <= k-2; j++)\r\n         if (P(j) != 0)\r\n            swap(lam(k-1)(P(j)), lam(k)(P(j)));\r\n\r\n      for (i = k+1; i <= m; i++) {\r\n         MulAddDiv(t1, lam(i)(P(k)-1), lam(i)(P(k)), \r\n                   lam(k)(P(k)-1), D[P(k)-2], D[P(k)-1]); \r\n         MulSubDiv(t2, lam(i)(P(k)-1), lam(i)(P(k)), \r\n                   D[P(k)], lam(k)(P(k)-1), D[P(k)-1]);\r\n         lam(i)(P(k)-1) = t1;\r\n         lam(i)(P(k)) = t2;\r\n      }\r\n\r\n      MulAddDiv(D[P(k)-1], D[P(k)], lam(k)(P(k)-1),\r\n                D[P(k)-2], lam(k)(P(k)-1), D[P(k)-1]);\r\n\r\n      return 0;\r\n   }\r\n   else if (!IsZero(lam(k)(P(k-1)))) {\r\n      if (verbose) cerr << \"swap case 2: \" << k << \"\\n\";\r\n      XGCD(e, x, y, lam(k)(P(k-1)), D[P(k-1)]);\r\n\r\n      ExactDiv(t1, lam(k)(P(k-1)), e);\r\n      ExactDiv(t2, D[P(k-1)], e);\r\n\r\n      t3 = t2;\r\n      negate(t2, t2);\r\n      RowTransform(B(k-1), B(k), t1, t2, y, x);\r\n      if (U) RowTransform((*U)(k-1), (*U)(k), t1, t2, y, x);\r\n      for (j = 1; j <= k-2; j++)\r\n         if (P(j) != 0)\r\n            RowTransform(lam(k-1)(P(j)), lam(k)(P(j)), t1, t2, y, x);\r\n\r\n      sqr(t2, t2);\r\n      ExactDiv(D[P(k-1)], D[P(k-1)], t2);\r\n\r\n      for (i = k+1; i <= m; i++)\r\n         if (P(i) != 0) {\r\n            ExactDiv(D[P(i)], D[P(i)], t2);\r\n            for (j = i+1; j <= m; j++) {\r\n               ExactDiv(lam(j)(P(i)), lam(j)(P(i)), t2);\r\n            }\r\n         }\r\n\r\n      for (i = k+1; i <= m; i++) {\r\n         ExactDiv(lam(i)(P(k-1)), lam(i)(P(k-1)), t3);\r\n      }\r\n\r\n      swap(P(k-1), P(k));\r\n\r\n      return 1;\r\n   }\r\n   else {\r\n      if (verbose) cerr << \"swap case 3: \" << k << \"\\n\";\r\n\r\n      swap(B(k-1), B(k));\r\n      if (U) swap((*U)(k-1), (*U)(k));\r\n   \r\n      for (j = 1; j <= k-2; j++)\r\n         if (P(j) != 0)\r\n            swap(lam(k-1)(P(j)), lam(k)(P(j)));\r\n\r\n      swap(P(k-1), P(k));\r\n\r\n      return 0;\r\n   }\r\n}\r\n\r\n   \r\n\r\n\r\nstatic\r\nvoid IncrementalGS(mat_ZZ& B, vec_long& P, vec_ZZ& D, vec_vec_ZZ& lam, \r\n                   long& s, long k)\r\n{\r\n   long n = B.NumCols();\r\n   long m = B.NumRows();\r\n\r\n   NTL_ZZRegister(u);\r\n   NTL_ZZRegister(t1);\r\n   NTL_ZZRegister(t2);\r\n\r\n   long i, j;\r\n\r\n   for (j = 1; j <= k-1; j++) {\r\n      long posj = P(j);\r\n      if (posj == 0) continue;\r\n\r\n      InnerProduct(u, B(k), B(j));\r\n      for (i = 1; i <= posj-1; i++) {\r\n         mul(t1, D[i], u);\r\n         mul(t2, lam(k)(i), lam(j)(i));\r\n         sub(t1, t1, t2);\r\n         div(t1, t1, D[i-1]);\r\n         u = t1;\r\n      }\r\n\r\n      lam(k)(posj) = u;\r\n   }\r\n\r\n   InnerProduct(u, B(k), B(k));\r\n   for (i = 1; i <= s; i++) {\r\n      mul(t1, D[i], u);\r\n      mul(t2, lam(k)(i), lam(k)(i));\r\n      sub(t1, t1, t2);\r\n      div(t1, t1, D[i-1]);\r\n      u = t1;\r\n   }\r\n\r\n   if (u == 0) {\r\n      P(k) = 0;\r\n   }\r\n   else {\r\n      s++;\r\n      P(k) = s;\r\n      D[s] = u;\r\n   }\r\n}\r\n\r\n\r\nstatic\r\nlong LLL(vec_ZZ& D, mat_ZZ& B, mat_ZZ* U, long a, long b, long verbose)\r\n{\r\n   long m = B.NumRows();\r\n   long n = B.NumCols();\r\n\r\n   long force_reduce = 1;\r\n\r\n   vec_long P;\r\n   P.SetLength(m);\r\n\r\n   D.SetLength(m+1);\r\n   D[0] = 1;\r\n\r\n   vec_vec_ZZ lam;\r\n\r\n   lam.SetLength(m);\r\n\r\n   long j;\r\n   for (j = 1; j <= m; j++)\r\n      lam(j).SetLength(m);\r\n\r\n   if (U) ident(*U, m);\r\n\r\n   long s = 0;\r\n\r\n   long k = 1;\r\n   long max_k = 0;\r\n\r\n\r\n   while (k <= m) {\r\n      if (k > max_k) {\r\n         IncrementalGS(B, P, D, lam, s, k);\r\n         max_k = k;\r\n      }\r\n\r\n      if (k == 1) {\r\n         force_reduce = 1; \r\n         k++;\r\n         continue;\r\n      }\r\n\r\n      if (force_reduce)\r\n         for (j = k-1; j >= 1; j--)\r\n            reduce(k, j, B, P, D, lam, U);\r\n\r\n      if (P(k-1) != 0 && \r\n          (P(k) == 0 || \r\n           SwapTest(D[P(k)], D[P(k)-1], D[P(k)-2], lam(k)(P(k)-1), a, b))) {\r\n         force_reduce = swap(k, B, P, D, lam, U, max_k, verbose);\r\n         k--;\r\n      }\r\n      else {\r\n         force_reduce = 1;\r\n         k++;\r\n      }\r\n   }\r\n\r\n   D.SetLength(s+1);\r\n   return s;\r\n}\r\n\r\n\r\n\r\nstatic\r\nlong image(ZZ& det, mat_ZZ& B, mat_ZZ* U, long verbose)\r\n{\r\n   long m = B.NumRows();\r\n   long n = B.NumCols();\r\n\r\n   long force_reduce = 1;\r\n\r\n   vec_long P;\r\n   P.SetLength(m);\r\n\r\n   vec_ZZ D;\r\n   D.SetLength(m+1);\r\n   D[0] = 1;\r\n\r\n   vec_vec_ZZ lam;\r\n\r\n   lam.SetLength(m);\r\n\r\n   long j;\r\n   for (j = 1; j <= m; j++)\r\n      lam(j).SetLength(m);\r\n\r\n   if (U) ident(*U, m);\r\n\r\n   long s = 0;\r\n\r\n   long k = 1;\r\n   long max_k = 0;\r\n\r\n\r\n   while (k <= m) {\r\n      if (k > max_k) {\r\n         IncrementalGS(B, P, D, lam, s, k);\r\n         max_k = k;\r\n      }\r\n\r\n      if (k == 1) {\r\n         force_reduce = 1; \r\n         k++;\r\n         continue;\r\n      }\r\n\r\n      if (force_reduce)\r\n         for (j = k-1; j >= 1; j--) \r\n            reduce(k, j, B, P, D, lam, U);\r\n\r\n      if (P(k-1) != 0 && P(k) == 0) {\r\n         force_reduce = swap(k, B, P, D, lam, U, max_k, verbose);\r\n         k--;\r\n      }\r\n      else {\r\n         force_reduce = 1;\r\n         k++;\r\n      }\r\n   }\r\n\r\n   det = D[s];\r\n   return s;\r\n}\r\n\r\nlong LLL(ZZ& det, mat_ZZ& B, mat_ZZ& U, long verbose)\r\n{\r\n   vec_ZZ D;\r\n   long s;\r\n   s = LLL(D, B, &U, 3, 4, verbose);\r\n   det = D[s];\r\n   return s;\r\n}\r\n\r\nlong LLL(ZZ& det, mat_ZZ& B, long verbose)\r\n{\r\n   vec_ZZ D;\r\n   long s;\r\n   s = LLL(D, B, 0, 3, 4, verbose);\r\n   det = D[s];\r\n   return s;\r\n}\r\n\r\nlong LLL(ZZ& det, mat_ZZ& B, mat_ZZ& U, long a, long b, long verbose)\r\n{\r\n   if (a <= 0 || b <= 0 || a > b || b/4 >= a) LogicError(\"LLL: bad args\");\r\n\r\n   vec_ZZ D;\r\n   long s;\r\n   s = LLL(D, B, &U, a, b, verbose);\r\n   det = D[s];\r\n   return s;\r\n}\r\n\r\nlong LLL(ZZ& det, mat_ZZ& B, long a, long b, long verbose)\r\n{\r\n   if (a <= 0 || b <= 0 || a > b || b/4 >= a) LogicError(\"LLL: bad args\");\r\n\r\n   vec_ZZ D;\r\n   long s;\r\n   s = LLL(D, B, 0, a, b, verbose);\r\n   det = D[s];\r\n   return s;\r\n}\r\n\r\n\r\nlong LLL_plus(vec_ZZ& D_out, mat_ZZ& B, mat_ZZ& U, long verbose)\r\n{\r\n   vec_ZZ D;\r\n   long s;\r\n   s = LLL(D, B, &U, 3, 4, verbose);\r\n   D_out = D;\r\n   return s;\r\n}\r\n\r\nlong LLL_plus(vec_ZZ& D_out, mat_ZZ& B, long verbose)\r\n{\r\n   vec_ZZ D;\r\n   long s;\r\n   s = LLL(D, B, 0, 3, 4, verbose);\r\n   D_out = D;\r\n   return s;\r\n}\r\n\r\nlong LLL_plus(vec_ZZ& D_out, mat_ZZ& B, mat_ZZ& U, long a, long b, long verbose)\r\n{\r\n   if (a <= 0 || b <= 0 || a > b || b/4 >= a) LogicError(\"LLL_plus: bad args\");\r\n\r\n   vec_ZZ D;\r\n   long s;\r\n   s = LLL(D, B, &U, a, b, verbose);\r\n   D_out = D;\r\n   return s;\r\n}\r\n\r\nlong LLL_plus(vec_ZZ& D_out, mat_ZZ& B, long a, long b, long verbose)\r\n{\r\n   if (a <= 0 || b <= 0 || a > b || b/4 >= a) LogicError(\"LLL_plus: bad args\");\r\n\r\n   vec_ZZ D;\r\n   long s;\r\n   s = LLL(D, B, 0, a, b, verbose);\r\n   D_out = D;\r\n   return s;\r\n}\r\n\r\n\r\nlong image(ZZ& det, mat_ZZ& B, mat_ZZ& U, long verbose)\r\n{\r\n   return image(det, B, &U, verbose);\r\n}\r\n\r\nlong image(ZZ& det, mat_ZZ& B, long verbose)\r\n{\r\n   return image(det, B, 0, verbose);\r\n}\r\n\r\nlong LatticeSolve(vec_ZZ& x, const mat_ZZ& A, const vec_ZZ& y, long reduce)\r\n{\r\n   long n = A.NumRows();\r\n   long m = A.NumCols();\r\n\r\n   if (y.length() != m)\r\n      LogicError(\"LatticeSolve: dimension mismatch\");\r\n\r\n   if (reduce < 0 || reduce > 2)\r\n      LogicError(\"LatticeSolve: bad reduce parameter\");\r\n\r\n   if (IsZero(y)) {\r\n      x.SetLength(n);\r\n      clear(x);\r\n      return 1;\r\n   }\r\n\r\n   mat_ZZ A1, U1;\r\n   ZZ det2;\r\n   long im_rank, ker_rank;\r\n\r\n   A1 = A;\r\n\r\n   im_rank = image(det2, A1, U1);\r\n   ker_rank = n - im_rank;\r\n\r\n   mat_ZZ A2, U2;\r\n   long new_rank;\r\n   long i;\r\n\r\n   A2.SetDims(im_rank + 1, m);\r\n   for (i = 1; i <= im_rank; i++)\r\n      A2(i) = A1(ker_rank + i);\r\n\r\n   A2(im_rank + 1) = y;\r\n\r\n   new_rank = image(det2, A2, U2);\r\n\r\n   if (new_rank != im_rank || \r\n      (U2(1)(im_rank+1) != 1  && U2(1)(im_rank+1) != -1))\r\n      return 0;\r\n\r\n   vec_ZZ x1;\r\n   x1.SetLength(im_rank);\r\n\r\n   for (i = 1; i <= im_rank; i++)\r\n      x1(i) = U2(1)(i);\r\n\r\n   if (U2(1)(im_rank+1) == 1)\r\n      negate(x1, x1);\r\n\r\n   vec_ZZ x2, tmp;\r\n   x2.SetLength(n);\r\n   clear(x2);\r\n   tmp.SetLength(n);\r\n\r\n   for (i = 1; i <= im_rank; i++) {\r\n      mul(tmp, U1(ker_rank+i), x1(i));\r\n      add(x2, x2, tmp);\r\n   }\r\n\r\n   if (reduce == 0) {\r\n      x = x2;\r\n      return 1;\r\n   }\r\n   else if (reduce == 1) {\r\n      U1.SetDims(ker_rank+1, n);\r\n      U1(ker_rank+1) = x2;\r\n      image(det2, U1);\r\n\r\n      x = U1(ker_rank + 1);\r\n      return 1;\r\n   }\r\n   else if (reduce == 2) {\r\n      U1.SetDims(ker_rank, n);\r\n      LLL(det2, U1);\r\n      U1.SetDims(ker_rank+1, n);\r\n      U1(ker_rank+1) = x2;\r\n      image(det2, U1);\r\n\r\n      x = U1(ker_rank + 1);\r\n      return 1;\r\n   }\r\n\r\n   return 0;\r\n} \r\n\r\n\r\n\r\nNTL_END_IMPL\r\n", "meta": {"hexsha": "d511deefd1d4b3b95b0e526fc98d83c2d102f668", "size": 13793, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "WinNTL-8_1_2/src/LLL.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/LLL.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/LLL.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.5091937765, "max_line_length": 81, "alphanum_fraction": 0.4410208077, "num_tokens": 5039, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.49999884243807613}}
{"text": "// In debug builds define\r\n// #define GSL_THROW_ON_CONTRACT_VIOLATION\r\n// In release builds define\r\n// #define GSL_UNENFORCED_ON_CONTRACT_VIOLATION    // Segmentation fault on GCC\r\n// or use assert() and define / undefine NDEBUG\r\n#include <iostream>\r\n#include <chrono>\r\n#include <string>\r\n#include <typeinfo>\r\n#include <cassert>\r\n#include <boost/type_index.hpp>\r\n#if !defined(NDEBUG)\r\n#define GSL_THROW_ON_CONTRACT_VIOLATION\r\n#include <gsl/gsl>\r\n#else\r\n#define Expects(cond)\r\n#define Ensures(cond)\r\n#endif\r\n\r\nusing std::cout; using std::wcout; using std::endl;\r\nusing namespace std::string_literals;\r\n\r\n\r\n// User-defined literals\r\nclass Probability\r\n{\r\npublic:\r\n    constexpr explicit Probability(long double v)\r\n        : value(v)\r\n        {\r\n            Expects(v < 1.0 && 0.0 <= v);\r\n            // assert(v < 1.0 && 0.0 <= v);\r\n        }\r\nprivate:\r\n    long double value;\r\n\r\n    friend constexpr Probability operator \"\" _prob(long double v);\r\n    friend std::ostream& operator<<(std::ostream& os, const Probability& prob)\r\n        { return os << \"Probability{\" << prob.value << \"}\"; }\r\n};\r\n\r\nclass BadProbability : public std::logic_error\r\n{ \r\npublic:\r\n    explicit BadProbability(long double v)\r\n        : std::logic_error( \"BadProbability exception, got value: \" + std::to_string(v) )\r\n        { }\r\n};\r\n\r\nconstexpr Probability operator \"\" _prob(long double v)\r\n{\r\n    return 1.0 < v ? throw BadProbability{v} : Probability{v};\r\n    // literals never represent negative values - no need to check for v < 0.0\r\n}\r\n\r\nusing boost::typeindex::type_id_with_cvr;\r\nint main()\r\ntry{\r\n    // std::basic_string<wchar_t>\r\n    auto s1 = \"String literal\"s;        // this is a std::string;\r\n    auto s2 = L\"Wide string literal\"s;  // this is a std::wstring;\r\n    auto s3 = std::basic_string<wchar_t>(L\"This is a very explicit wstring\");\r\n    cout << \"s1:\\n\\t\" << s1 << \"\\n\\ttypeid \" << type_id_with_cvr<decltype(s1)>().pretty_name() << endl;\r\n    wcout << L\"s2:\\n\\t\" << s2 << L\"\\n\\ttypeid \";\r\n    cout << type_id_with_cvr<decltype(s2)>().pretty_name() << endl;\r\n    wcout << L\"s3:\\n\\t\" << s3 << L\"\\n\\ttypeid \";\r\n    cout << type_id_with_cvr<decltype(s3)>().pretty_name() << endl;\r\n\r\n    cout << \"\\nUser defined literals\\n\" << \"Probability\\n\" << endl;\r\n    \r\n    // constexpr auto prob1 = 1.2_prob;   // compiletime error;\r\n\r\n    // auto prob2 = 1.2_prob;  // NOT a compiletimer error - throws at runtime\r\n\r\n    constexpr auto prob3 = 0.3_prob;   // OK\r\n        cout << prob3 << endl;\r\n\r\n    // constexpr auto prob4 = Probability{1.2}; // Compiletime error\r\n\r\n    constexpr auto prob5 = Probability{0.5};\r\n        cout << prob5 << endl;\r\n\r\n    auto prob6 = 0.6_prob;\r\n        cout << prob6 << endl;\r\n\r\n    // auto prob7 = Probability{1.7}; // runtime error\r\n    //     cout << prob7 << endl;\r\n}\r\ncatch( const std::exception& e )\r\n{\r\n    std::cerr << e.what () << endl;\r\n}", "meta": {"hexsha": "15ff708538d774362a16fb221b62a5ef78ab1ac4", "size": 2861, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Patterns/Misc/literals.cpp", "max_stars_repo_name": "kant/Always-be-learning", "max_stars_repo_head_hexsha": "7c3b3b4f5e8f0dfcb4d8f4b7f7428d5c8ab164c5", "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": "Patterns/Misc/literals.cpp", "max_issues_repo_name": "kant/Always-be-learning", "max_issues_repo_head_hexsha": "7c3b3b4f5e8f0dfcb4d8f4b7f7428d5c8ab164c5", "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": "Patterns/Misc/literals.cpp", "max_forks_repo_name": "kant/Always-be-learning", "max_forks_repo_head_hexsha": "7c3b3b4f5e8f0dfcb4d8f4b7f7428d5c8ab164c5", "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.097826087, "max_line_length": 104, "alphanum_fraction": 0.6155190493, "num_tokens": 764, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.7718434873426302, "lm_q1q2_score": 0.49999883563849806}}
{"text": "#include \"generator.hpp\"\n\n#include <boost/random/uniform_int.hpp>\n#include <boost/random/uniform_real.hpp>\n#include <boost/math/distributions/normal.hpp>\n\n#include <boost/random/variate_generator.hpp>\n\nnamespace crossbow {\n\nCrossbowRandomGenerator::CrossbowRandomGenerator (unsigned int seed) {\n\n\tthis->seed = seed;\n\tthis->rng  = new rng_t(seed);\n}\n\nfloat CrossbowRandomGenerator::nextafter (const float value) {\n\n\treturn boost::math::nextafter<float>(value, std::numeric_limits<float>::max());\n}\n\nvoid CrossbowRandomGenerator::randomUniformFill (float *buffer, const int count, const float start, const float end) {\n\n\tif (buffer == NULL) {\n\t\tfprintf(stderr, \"error: buffer to fill must not be null\\n\");\n\t\texit (1);\n\t}\n\n\tif (count < 0) {\n\t\tfprintf(stderr, \"error: number of buffer elements to fill must be greater or equal to 0\\n\");\n\t\texit (1);\n\t}\n\n\tif (start > end) {\n\t\tfprintf(stderr, \"error: invalid uniform random distribution specification\\n\");\n\t\texit (1);\n\t}\n\n\tboost::uniform_real<float> dist (start, nextafter (end));\n\tboost::variate_generator<crossbow::rng_t *, boost::uniform_real<float> > variate_generator (this->rng, dist);\n\n\tfor (int i = 0; i < count; ++i)\n\t\tbuffer [i] = variate_generator ();\n\n\treturn;\n}\n\nvoid CrossbowRandomGenerator::randomGaussianFill (float *buffer, const int count, const float mean, const float std, const int truncate) {\n\n\tif (buffer == NULL) {\n\t\tfprintf(stderr, \"error: buffer to fill must not be null\\n\");\n\t\texit (1);\n\t}\n\n\tif (count < 0) {\n\t\tfprintf(stderr, \"error: number of buffer elements to fill must be greater or equal to 0\\n\");\n\t\texit (1);\n\t}\n\n\tif (std <= 0) {\n\t\tfprintf(stderr, \"error: invalid normal distribution specification\\n\");\n\t\texit (1);\n\t}\n\n\tboost::normal_distribution<float> dist (mean, std);\n\tboost::variate_generator<crossbow::rng_t *, boost::normal_distribution<float> > variate_generator (this->rng, dist);\n\t\n\t/* float checksum = 0; */\n\n\tif (truncate) {\n\n\t\t/*\n\t\t * Added on 14 Apr 2018: Hard-coded truncated version:\n\t\t *\n\t\t * Values whose magnitude is more than 2 standard deviations\n\t\t * from the mean are dropped and re-picked.\n\t\t */\n\t\tfloat min = mean - (2 * std);\n\t\tfloat max = mean + (2 * std);\n\t\tint maxiterations = 100;\n\t\n\t\tfloat sample;\n\t\tint correct = 0;\n\t\tfor (int i = 0; i < count; ++i) {\n\t\t\tfor (int j = 0; j < maxiterations; ++j) {\n\t\t\t\tsample = variate_generator ();\n\t\t\t\tif ((sample > min) && (sample < max)) {\n\t\t\t\t\tcorrect ++;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbuffer [i] = sample;\n\t\t\t/* checksum += buffer [i]; */\n\t\t}\n\t\tif (correct < count)\n\t\t\tfprintf(stderr, \"warning: only %d out of %d values truncated\\n\", correct, count);\n\t}\n\telse {\n\t\tfor (int i = 0; i < count; ++i) {\n\t\t\tbuffer [i] = variate_generator ();\n\t\t\t/* checksum += buffer [i]; */\n\t\t}\n\t}\n\t/*\n\t * fprintf(stdout, \"[DBG] checksum is %.5f\\n\", checksum);\n\t * fflush (stdout);\n\t */\n\n\treturn;\n}\n\nvoid CrossbowRandomGenerator::dump () {\n\n\tfprintf(stdout, \"CrossbowRandom (%du)\\n\", seed);\n\tfflush (stdout);\n}\n\n}  /* namespace crossbow */\n", "meta": {"hexsha": "2f41febaaa7e79e2318a4a0d8ecf26f27de5f936", "size": 2962, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "clib-multigpu/random/generator.cpp", "max_stars_repo_name": "lsds/Crossbow", "max_stars_repo_head_hexsha": "d4441b35315f9f7d48293fe81faaf21e1ca48002", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 50.0, "max_stars_repo_stars_event_min_datetime": "2019-01-09T14:30:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T11:42:51.000Z", "max_issues_repo_path": "clib-multigpu/random/generator.cpp", "max_issues_repo_name": "lsds/Crossbow", "max_issues_repo_head_hexsha": "d4441b35315f9f7d48293fe81faaf21e1ca48002", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-01-18T07:31:39.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-14T21:16:53.000Z", "max_forks_repo_path": "clib-multigpu/random/generator.cpp", "max_forks_repo_name": "lsds/Crossbow", "max_forks_repo_head_hexsha": "d4441b35315f9f7d48293fe81faaf21e1ca48002", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-03-20T14:56:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T06:13:09.000Z", "avg_line_length": 24.8907563025, "max_line_length": 138, "alphanum_fraction": 0.6576637407, "num_tokens": 812, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.4999988319416692}}
{"text": "#include \"third_party/frc971/control_loops/paths/path.h\"\n#include <Eigen/Geometry>\n\n#define _USE_MATH_DEFINES\n#include <cmath>\n\n#include \"muan/logging/logger.h\"\n\nnamespace frc971 {\nnamespace control_loops {\nnamespace paths {\n\nEigen::Vector2d Projection(Eigen::Vector2d a, Eigen::Vector2d direction) {\n  return a.dot(direction) * direction.dot(direction) * direction;\n}\n\nPosition FromMagDirection(double magnitude, double direction) {\n  return magnitude * (Position() << ::std::cos(direction), ::std::sin(direction)).finished();\n}\n\nPose::Pose(Eigen::Vector3d values) : values_(values) {}\n\nPose::Pose(Position pos, double theta) {\n  values_.block<2, 1>(0, 0) = pos;\n  values_(2) = remainder(theta, 2 * M_PI);\n}\n\nPose Pose::operator+(const Pose &other) const {\n  Eigen::Vector3d new_values = values_ + other.values_;\n\n  // Wrap the heading into [-pi, pi]\n  new_values(2) = remainder(new_values(2), 2 * M_PI);\n\n  return Pose(new_values);\n}\n\nPose Pose::TranslateBy(const Position &delta) const {\n  Eigen::Vector3d new_values = values_;\n  new_values.block<2, 1>(0, 0) += delta;\n  return Pose(new_values);\n}\n\nPose Pose::RotateBy(double theta) const {\n  Eigen::Vector3d new_values = values_;\n  new_values.block<2, 1>(0, 0) = Eigen::Rotation2D<double>(theta) * new_values.block<2, 1>(0, 0);\n\n  // Wrap the heading into [-pi, pi]\n  new_values(2) = remainder(new_values(2) + theta, 2 * M_PI);\n\n  return Pose(new_values);\n}\n\nPose Pose::operator-(const Pose &other) const {\n  Eigen::Vector3d new_values = values_ - other.values_;\n\n  // Wrap the heading into [-pi, pi]\n  new_values(2) = remainder(new_values(2), 2 * M_PI);\n  return Pose(new_values);\n}\n\nPose Pose::Compose(const Pose &other) const { return other.RotateBy(heading()).TranslateBy(translational()); }\n\nHermitePath::HermitePath(Pose initial, Pose final,\n                         double initial_velocity, double final_velocity, bool backwards,\n                         double extra_distance_initial, double extra_distance_final,\n                         double initial_angular_velocity,\n                         double final_angular_velocity)\n    : HermitePath(initial.translational(),\n                  FromMagDirection(1, initial.heading()),\n                  final.translational(),\n                  FromMagDirection(1, final.heading()),\n                  initial_velocity, final_velocity, backwards,\n                  extra_distance_initial, extra_distance_final,\n                  initial_angular_velocity, final_angular_velocity) {}\n\nHermitePath::HermitePath(Position initial_position, Eigen::Vector2d initial_tangent,\n                         Position final_position, Eigen::Vector2d final_tangent,\n                         double initial_velocity, double final_velocity, bool backwards,\n                         double extra_distance_initial, double extra_distance_final,\n                         double initial_angular_velocity,\n                         double final_angular_velocity) {\n  backwards_ = backwards;\n\n  Eigen::Vector2d initial_derivative_basis;\n  Eigen::Vector2d final_derivative_basis;\n  double initial_deriv_magnitude;\n  double final_deriv_magnitude;\n\n  {\n    Eigen::Vector2d distance = final_position - initial_position;\n    // How far to the side are we driving, relative to initial state?\n    Eigen::Vector2d sideways = distance - Projection(distance, initial_tangent);\n    // How far to the front is the sideways vector, relative to final state?\n    double forwards2 = sideways.dot(final_tangent);\n    if (backwards) {\n      forwards2 *= -1;\n    }\n    // Rough estimate of the curvature, this should be approximately\n    // correct as long as the curvature doesn't have excessively large changes.\n    double approx_curve = (sideways.norm() * 2 - forwards2) / distance.norm();\n    // Standard hermite spline uses tangent * |distance|, but initial velocity\n    // should be taken into account as well, although only sigmificantly if\n    // distance is short and initial velocity is high. This formula was found\n    // experimentally.\n    initial_deriv_magnitude = distance.norm() + extra_distance_initial * 5.0 +\n        initial_velocity * initial_velocity * 0.5 * approx_curve * approx_curve;\n    final_deriv_magnitude = distance.norm() + extra_distance_final * 5.0 +\n        final_velocity * final_velocity * 0.5 * approx_curve * approx_curve;\n  }\n\n  initial_derivative_basis = initial_tangent * initial_deriv_magnitude;\n  final_derivative_basis = final_tangent * final_deriv_magnitude;\n\n  if (backwards_) {\n    initial_derivative_basis *= -1;\n    final_derivative_basis *= -1;\n  }\n\n  Eigen::Vector2d initial_acceleration = Eigen::Vector2d::Zero();\n  if (initial_velocity > 0.01 || initial_velocity < -0.01) {\n    initial_acceleration =\n          (Eigen::Vector2d() << -initial_tangent(1), initial_tangent(0)).finished() *\n          initial_deriv_magnitude * final_deriv_magnitude *\n          initial_angular_velocity / initial_velocity;\n  } else if (initial_angular_velocity > 0.01 || initial_angular_velocity < -0.01) {\n    LOG(WARNING, \"Initial velocity required if initial angular velocity present\"\n                 \" (v_0 = %f, omega_0 = %f, cutoff = 0.01)\",\n        initial_velocity, initial_angular_velocity);\n  }\n\n  Eigen::Vector2d final_acceleration = Eigen::Vector2d::Zero();\n  if (final_velocity > 0.01 || final_velocity < -0.01) {\n    final_acceleration =\n          (Eigen::Vector2d() << -final_tangent(1), final_tangent(0)).finished() *\n          final_deriv_magnitude * final_deriv_magnitude *\n          final_angular_velocity / final_velocity;\n  } else if (final_angular_velocity > 0.01 || final_angular_velocity < -0.01) {\n    LOG(WARNING, \"Final velocity required if final angular velocity present\"\n                 \" (v_f = %f, omega_f = %f, cutoff = 0.01)\",\n        final_velocity, final_angular_velocity);\n  }\n\n  coefficients_ = Eigen::Matrix<double, 4, 6>::Zero();\n  coefficients_.block<2, 1>(0, 0) = initial_position;\n  coefficients_.block<2, 1>(0, 1) = initial_derivative_basis;\n  coefficients_.block<2, 1>(0, 2) = 0.5 * initial_acceleration;\n  coefficients_.block<2, 1>(0, 3) =\n          -10 * initial_position - 6 * initial_derivative_basis +\n          -1.5 * initial_acceleration + 0.5 * final_acceleration +\n          -4 * final_derivative_basis + 10 * final_position;\n  coefficients_.block<2, 1>(0, 4) =\n          15 * initial_position + 8 * initial_derivative_basis +\n          1.5 * initial_acceleration - 1 * final_acceleration +\n          7 * final_derivative_basis - 15 * final_position;\n  coefficients_.block<2, 1>(0, 5) =\n          -6 * initial_position - 3 * initial_derivative_basis +\n          -0.5 * initial_acceleration + 0.5 * final_acceleration +\n          -3 * final_derivative_basis + 6 * final_position;\n\n  for (int i = 0; i < 6; i++) {\n    coefficients_.block<2, 1>(2, i) = coefficients_.block<2, 1>(0, i) * i;\n  }\n\n  initial_heading_ = remainder(::std::atan2(initial_tangent(1), initial_tangent(0)), 2 * M_PI);\n}\n\nvoid HermitePath::Populate(double s_min, double s_max, Pose *pose_arr, size_t arr_len) const {\n  Eigen::Matrix<double, 6, 1> s_polynomial_bases;\n  double step = (s_max - s_min) / (arr_len - 1);\n  for (size_t i = 0; i < arr_len; i++) {\n    double s = s_min + i * step;\n    s_polynomial_bases << 1.0, s, s * s, s * s * s, s * s * s * s, s * s * s * s * s;\n\n    Eigen::Vector4d combined = coefficients_ * s_polynomial_bases;\n\n    double theta;\n    if (s == 0) {\n      // When s is _exactly_ zero, we can't get the heading directly from\n      // the derivative (because it collapses to zero)! Let's use the cached\n      // value instead.\n      theta = initial_heading_;\n    } else {\n      theta = ::std::atan2(combined(3), combined(2));\n      if (backwards_) {\n        if (theta > 0) {\n          theta -= M_PI;\n        } else {\n          theta += M_PI;\n        }\n      }\n    }\n\n    pose_arr[i] = Pose(combined.block<2, 1>(0, 0), theta);\n  }\n}\n\n}  // namespace paths\n}  // namespace control_loops\n}  // namespace frc971\n", "meta": {"hexsha": "dd91c963d33f365d5969328e46dda4ede086733c", "size": 7951, "ext": "cc", "lang": "C++", "max_stars_repo_path": "third_party/frc971/control_loops/paths/path.cc", "max_stars_repo_name": "hansonl02/frc-robot-code", "max_stars_repo_head_hexsha": "4b120c917a7709df9f010c9089a87c320bab3a16", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 61.0, "max_stars_repo_stars_event_min_datetime": "2017-01-22T04:38:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T00:04:37.000Z", "max_issues_repo_path": "third_party/frc971/control_loops/paths/path.cc", "max_issues_repo_name": "hansonl02/frc-robot-code", "max_issues_repo_head_hexsha": "4b120c917a7709df9f010c9089a87c320bab3a16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-06-28T05:34:57.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-16T15:46:22.000Z", "max_forks_repo_path": "third_party/frc971/control_loops/paths/path.cc", "max_forks_repo_name": "hansonl02/frc-robot-code", "max_forks_repo_head_hexsha": "4b120c917a7709df9f010c9089a87c320bab3a16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2017-05-12T15:32:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-09T12:49:38.000Z", "avg_line_length": 39.755, "max_line_length": 110, "alphanum_fraction": 0.6649478053, "num_tokens": 2037, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042768, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.499984820924629}}
{"text": "/*\nBSD 3-Clause License\n\nCopyright (c) 2020, The Regents of the University of Minnesota\n\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\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#include <vector>\n#include <queue>\n#include <math.h>\n#include <cmath>\n#include <iostream>\n#include <stdlib.h>\n#include <map>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <time.h>\n#include <sstream>\n#include <iterator>\n#include <string>\n\n#include <Eigen/Sparse>\n#include <Eigen/SparseLU>\n#include \"opendb/db.h\"\n#include \"ir_solver.h\"\n#include \"node.h\"\n#include \"gmat.h\"\n#include \"get_power.h\"\n#include \"openroad/Error.hh\"\n\nusing ord::error;\nusing ord::warn;\nusing odb::dbBlock;\nusing odb::dbBox;\nusing odb::dbChip;\nusing odb::dbDatabase;\nusing odb::dbInst;\nusing odb::dbNet;\nusing odb::dbSBox;\nusing odb::dbSet;\nusing odb::dbSigType;\nusing odb::dbSWire;\nusing odb::dbTech;\nusing odb::dbTechLayer;\nusing odb::dbTechLayerDir;\nusing odb::dbVia;\nusing odb::dbViaParams;\n\nusing namespace std;\nusing std::vector;\nusing Eigen::Map;\nusing Eigen::VectorXd;\nusing Eigen::SparseMatrix; \nusing Eigen::SparseLU;\nusing Eigen::Success;\n\n\n//! Returns the created G matrix for the design\n/*\n * \\return G Matrix\n */\nGMat* IRSolver::GetGMat()\n{\n  return m_Gmat;\n}\n\n\n//! Returns current map represented as a 1D vector\n/* \n * \\return J vector\n */\nvector<double> IRSolver::GetJ()\n{\n  return m_J;\n}\n\n\n//! Function to solve for voltage using SparseLU \nvoid IRSolver::SolveIR()\n{\n  if(!m_connection) {\n    cout<<\"WARNING: Powergrid is not connected to all instances,\"<<\n          \"IR Solver may not be accurate, LVS may also fail.\"<<endl;\n  }\n  int unit_micron = (m_db->getTech())->getDbUnitsPerMicron();\n  clock_t t1, t2;\n  CscMatrix*        Gmat = m_Gmat->GetGMat();\n// fill A\n  int     nnz     = Gmat->nnz;\n  int               m    = Gmat->num_rows;\n  int               n    = Gmat->num_cols;\n  double* values  = &(Gmat->values[0]);\n  int*    row_idx = &(Gmat->row_idx[0]);\n  int*    col_ptr = &(Gmat->col_ptr[0]);\n  Map<SparseMatrix<double> > A( Gmat->num_rows,\n                                Gmat->num_cols,\n                                Gmat->nnz,\n                                col_ptr, // read-write\n                                row_idx,\n                                values);\n    \n\n  vector<double>    J = GetJ();\n  Map<VectorXd> b(J.data(),J.size());\n  VectorXd x;\n  SparseLU<SparseMatrix<double> > solver;\n  cout << \"INFO: Factorizing G\" << endl;\n  solver.compute(A);\n  if(solver.info()!=Success) {\n    // decomposition failed\n    cout<<\"Error: LU factorization of GMatrix failed\"<<endl;\n    return;\n  }\n  cout << \"INFO: Solving GV=J\" << endl;\n  cout << \"INFO: SparseLU begin solving\" << endl;\n  x = solver.solve(b);\n  cout << \"INFO: SparseLU finished solving\" << endl;\n  if(solver.info()!=Success) {\n    // solving failed\n    cout<<\"Error: Solving V = inv(G)*J failed\"<<endl;\n    return;\n  }\n  ofstream ir_report;\n  ir_report.open (m_out_file);\n  ir_report<<\"Instance name, \"<<\" X location, \"<<\" Y location, \"<<\" Voltage \"<<\"\\n\";\n  int num_nodes         = m_Gmat->GetNumNodes();\n  int node_num =0;\n  double       sum_volt = 0;\n  wc_voltage            = vdd;\n  while(node_num < num_nodes) {\n    Node* node = m_Gmat->GetNode(node_num);\n    double volt = x(node_num);\n    sum_volt   = sum_volt + volt;\n    if (volt < wc_voltage) {\n      wc_voltage = volt;\n    }\n    node->SetVoltage(volt);\n    node_num++;\n    if(node->HasInstances()) {\n      NodeLoc node_loc = node->GetLoc();\n      float loc_x = ((float)node_loc.first)/((float)unit_micron);\n      float loc_y = ((float)node_loc.second)/((float)unit_micron);\n      std::vector<dbInst*> insts = node->GetInstances();\n      std::vector<dbInst*>::iterator inst_it;\n      if (m_out_file != \"\") {\n        for(inst_it = insts.begin();inst_it!=insts.end();inst_it++) {\n          ir_report<<(*inst_it)->getName()<<\", \"<<loc_x<<\", \" <<loc_y<<\", \"<<setprecision(10)<<volt<<\"\\n\";\n        }\n      }\n    }\n  }\n  ir_report<<endl;\n  ir_report.close();\n  avg_voltage = sum_volt / num_nodes;\n}\n\n//! Function to add C4 bumps to the G matrix\nbool IRSolver::AddC4Bump()\n{\n  if (m_C4Bumps.size() == 0) {\n    cout << \"ERROR: Invalid number of voltage sources\" << endl;\n    return false;\n  }\n  for (unsigned int it = 0; it < m_C4Nodes.size(); ++it) {\n    NodeIdx node_loc = m_C4Nodes[it].first;\n    double  voltage  = m_C4Nodes[it].second;\n    m_Gmat->AddC4Bump(node_loc, it);  // add the 0th bump\n    m_J.push_back(voltage);           // push back first vdd\n    vdd = voltage;\n  }\n  return true;\n}\n\n\n\n//! Function that parses the Vsrc file\nvoid IRSolver::ReadC4Data()\n{\n  int unit_micron = (m_db->getTech())->getDbUnitsPerMicron();\n  cout << \"INFO: Reading location of VDD and VSS sources \" << endl;\n  if(m_vsrc_file != \"\") {\n  std::ifstream file(m_vsrc_file);\n    std::string line = \"\";\n  // Iterate through each line and split the content using delimiter\n  while (getline(file, line)) {\n    tuple<int, int, int, double> c4_bump;\n    int                          first, second, size;\n    double                       voltage;\n    stringstream                 X(line);\n    string                       val;\n    for (int i = 0; i < 4; ++i) {\n      getline(X, val, ',');\n      if (i == 0) {\n        first = (int) (unit_micron * stod(val));\n      } else if (i == 1) {\n        second = (int) (unit_micron * stod(val));\n      } else if (i == 2) {\n        size = (int) (unit_micron * stod(val));\n      } else {\n        voltage = stod(val);\n      }\n    }\n    m_C4Bumps.push_back(make_tuple(first, second, size, voltage));\n  }\n  file.close();\n  }\n  else {\n    cout << \"Warning: Voltage pad location file not spcified, defaulting pad location to origin\" << endl;\n    m_C4Bumps.push_back(make_tuple(0,0,0,0));\n  }\n}\n\n\n//! Function that parses the Vsrc file\n/*void IRSolver::ReadResData()\n{\n  cout << \"Default resistance file\" << m_def_res << endl;\n  cout << \"INFO: Reading resistance of layers and vias \" << endl;\n  std::ifstream file(m_def_res);    \n  std::string line = \"\";\n  int line_num = 0;\n  // Iterate through each line and split the content using delimiter\n  while (getline(file, line)) {\n    line_num ++;\n    if (line_num == 1) {\n      continue;\n    }\n    //tuple<int, double, double> layer_res;\n    int                          routing_level;\n    double                       res_per_unit;\n    double                       res_via;\n    stringstream                 X(line);\n    string                       val;\n    for (int i = 0; i < 3; ++i) {\n      getline(X, val, ',');\n      if (i == 0) {\n        routing_level = stoi(val);\n      } else if (i == 1) {\n        res_per_unit = stod(val);\n      } else {\n        res_via = stod(val);\n      }\n    }\n    m_layer_res.push_back(make_tuple(routing_level, res_per_unit, res_via));\n  }\n  file.close();\n}\n*/\n\n//! Function to create a J vector from the current map\nbool IRSolver::CreateJ()\n{  // take current_map as an input?\n  int num_nodes = m_Gmat->GetNumNodes();\n  m_J.resize(num_nodes, 0);\n\n  vector<pair<string, double>> power_report = GetPower();\n  dbChip*                      chip         = m_db->getChip();\n  dbBlock*                     block        = chip->getBlock();\n  for (vector<pair<string, double>>::iterator it = power_report.begin();\n       it != power_report.end();\n       ++it) {\n    dbInst* inst = block->findInst(it->first.c_str());\n    if (inst == NULL) {\n      cout << \"Warning instance \" << it->first << \" not found within database\"\n           << endl;\n      continue;\n    }\n    int x, y;\n    inst->getLocation(x, y);\n    //cout << \"Got location\" <<endl;\n    int   l      = m_bottom_layer;  // atach to the bottom most routing layer\n    Node* node_J = m_Gmat->GetNode(x, y, l,true);\n    NodeLoc node_loc = node_J->GetLoc();\n    if( abs(node_loc.first - x) > m_node_density || abs(node_loc.second - y) > m_node_density ){\n      cout<<\"WARNING: Instance current node at \"<<node_loc.first<<\" \"<<node_loc.second<<\" layer \"<<l<<\" moved from \"<<x<<\" \"<<y<<endl;\n      cout<<\"Instance: \" << it->first <<endl;\n    }\n    //TODO modify for ground network\n    node_J->AddCurrentSrc(it->second);\n    node_J->AddInstance(inst);\n  }\n  for (int i = 0; i < num_nodes; ++i) {\n    Node* node_J = m_Gmat->GetNode(i);\n    m_J[i] = -1 * (node_J->GetCurrent());  // as MNA needs negative\n    // cout << m_J[i] <<endl;\n  }\n  cout << \"INFO: Created J vector\" << endl;\n  return true;\n}\n\n\n//! Function to create a G matrix using the nodes\nbool IRSolver::CreateGmat(bool connection_only)\n{\n  cout<<\"Creating G Matrix\"<<endl;\n  std::vector<Node*> node_vector;\n  dbTech*                      tech   = m_db->getTech();\n  //dbSet<dbTechLayer>           layers = tech->getLayers();\n  dbSet<dbTechLayer>::iterator litr;\n  int unit_micron = tech->getDbUnitsPerMicron();\n  int num_routing_layers = tech->getRoutingLayerCount();\n\n  m_Gmat                    = new GMat(num_routing_layers);\n  dbChip*             chip  = m_db->getChip();\n  dbBlock*            block = chip->getBlock();\n  dbSet<dbNet>        nets  = block->getNets();\n  std::vector<dbNet*> vdd_nets;\n  std::vector<dbNet*> gnd_nets;\n  std::vector<dbNet*> power_nets;\n  int num_wires =0;\n  cout << \"Extracting power stripes on net \" << m_power_net <<endl;\n  dbSet<dbNet>::iterator nIter;\n  for (nIter = nets.begin(); nIter != nets.end(); ++nIter) {\n    dbNet* curDnet = *nIter;\n    dbSigType nType = curDnet->getSigType();\n    if(m_power_net == \"VSS\") {\n      if (nType == dbSigType::GROUND) {\n        power_nets.push_back(curDnet);\n      } else {\n        continue;\n      }\n    } else if(m_power_net == \"VDD\") {\n      if (nType == dbSigType::POWER) {\n        power_nets.push_back(curDnet);\n      } else {\n        continue;\n      }\n    } else {\n      cout << \"Warning: Net not specifed as VDD or VSS. Power grid checker is not run.\" <<endl;\n      return false;\n    }\n  }\n  if(power_nets.size() == 0) {\n    cout<<\"Warning:No power stipes found in design. Power grid checker is not run.\"<<endl;\n    return false;\n  }\n  std::vector<dbNet*>::iterator vIter;\n  for (vIter = power_nets.begin(); vIter != power_nets.end(); ++vIter) {\n    dbNet*                   curDnet = *vIter;\n    dbSet<dbSWire>           swires  = curDnet->getSWires();\n    dbSet<dbSWire>::iterator sIter;\n    for (sIter = swires.begin(); sIter != swires.end(); ++sIter) {\n      dbSWire*                curSWire = *sIter;\n      dbSet<dbSBox>           wires    = curSWire->getWires();\n      dbSet<dbSBox>::iterator wIter;\n      for (wIter = wires.begin(); wIter != wires.end(); ++wIter) {\n        num_wires++;\n        dbSBox* curWire = *wIter;\n        int l;\n        dbTechLayerDir::Value layer_dir; \n        if (curWire->isVia()) {\n          dbVia* via      = curWire->getBlockVia();\n          dbTechLayer* via_layer = via->getTopLayer();\n          l = via_layer->getRoutingLevel();\n          layer_dir = via_layer->getDirection();\n        } else {\n          dbTechLayer* wire_layer = curWire->getTechLayer();\n          l = wire_layer->getRoutingLevel();\n          layer_dir = wire_layer->getDirection();\n          if (l < m_bottom_layer) {\n            m_bottom_layer = l ; \n            m_bottom_layer_dir = layer_dir;\n          }\n        }\n        if (l > m_top_layer) {\n          m_top_layer = l ; \n          m_top_layer_dir = layer_dir;\n        }\n      }\n    }\n  }\n  cout<<\"Creating Nodes:     \";\n  int progress_wires=0;\n  int progress_percent=1;\n  for (vIter = power_nets.begin(); vIter != power_nets.end(); ++vIter) {\n    dbNet*                   curDnet = *vIter;\n    dbSet<dbSWire>           swires  = curDnet->getSWires();\n    dbSet<dbSWire>::iterator sIter;\n    for (sIter = swires.begin(); sIter != swires.end(); ++sIter) {\n      dbSWire*                curSWire = *sIter;\n      dbSet<dbSBox>           wires    = curSWire->getWires();\n      dbSet<dbSBox>::iterator wIter;\n      for (wIter = wires.begin(); wIter != wires.end(); ++wIter) {\n        if(progress_wires >= ((progress_percent/100.0)*num_wires)-1.0 ){\n          cout<<\"\\b\\b\\b\\b\"<<setw(3)<<progress_percent++<<\"%\"<< std::flush;\n        }\n        progress_wires++;\n        dbSBox* curWire = *wIter;\n        if (curWire->isVia()) {\n          dbVia* via      = curWire->getBlockVia();\n          dbBox* via_bBox = via->getBBox();\n          int check_params = via->hasParams();\n          int x_cut_size = 0;\n          int y_cut_size = 0;\n          int x_bottom_enclosure = 0;\n          int y_bottom_enclosure = 0;\n          int x_top_enclosure = 0;\n          int y_top_enclosure = 0;\n\t\t  if(check_params == 1) {\n\t\t    dbViaParams params;\n\t\t\tvia->getViaParams(params);\n\t\t    x_cut_size = params.getXCutSize();\n\t\t    y_cut_size = params.getYCutSize();\n            x_bottom_enclosure = params.getXBottomEnclosure();\n            y_bottom_enclosure = params.getYBottomEnclosure();\n            x_top_enclosure = params.getXTopEnclosure();\n            y_top_enclosure = params.getYTopEnclosure();\n\t\t  }\n          BBox   bBox = make_pair((via_bBox->getDX()) / 2, (via_bBox->getDY()) / 2);\n          int x, y;\n          curWire->getViaXY(x, y);\n          dbTechLayer* via_layer = via->getBottomLayer();\n          dbTechLayerDir::Value layer_dir  = via_layer->getDirection();\n          int          l         = via_layer->getRoutingLevel();\n          int x_loc1,x_loc2,y_loc1,y_loc2;\n          if (m_bottom_layer != l && l != m_top_layer) {//do not set for top and bottom layers\n            if (layer_dir == dbTechLayerDir::Value::HORIZONTAL) {\n              y_loc1 = y;\n              y_loc2 = y;\n              x_loc1 = x - (x_bottom_enclosure+x_cut_size/2);\n              x_loc2 = x + (x_bottom_enclosure+x_cut_size/2);\n            } else {\n              y_loc1 = y - (y_bottom_enclosure+y_cut_size/2);\n              y_loc2 = y + (y_bottom_enclosure+y_cut_size/2);\n              x_loc1 = x;\n              x_loc2 = x;\n            }\n            m_Gmat->SetNode(x_loc1, y_loc1, l, make_pair(0, 0));\n            m_Gmat->SetNode(x_loc2, y_loc2, l, make_pair(0, 0));\n            m_Gmat->SetNode(x, y, l, bBox);\n          }\n          via_layer = via->getTopLayer();\n          l         = via_layer->getRoutingLevel();\n\n          //TODO this may count the stripe conductance twice but is needed to\n          //fix a staggered stacked via\n          layer_dir  = via_layer->getDirection();\n          if (m_bottom_layer != l && l != m_top_layer) {//do not set for top and bottom layers\n            if (layer_dir == dbTechLayerDir::Value::HORIZONTAL) {\n              y_loc1 = y;\n              y_loc2 = y;\n              x_loc1 = x - (x_top_enclosure+x_cut_size/2);\n              x_loc2 = x + (x_top_enclosure+x_cut_size/2);\n            } else {\n              y_loc1 = y - (y_top_enclosure+y_cut_size/2);\n              y_loc2 = y + (y_top_enclosure+y_cut_size/2);\n              x_loc1 = x;\n              x_loc2 = x;\n            }\n            m_Gmat->SetNode(x_loc1, y_loc1, l, make_pair(0, 0));\n            m_Gmat->SetNode(x_loc2, y_loc2, l, make_pair(0, 0));\n            m_Gmat->SetNode(x, y, l, bBox);\n          }\n        } else {\n          int                   x_loc1, x_loc2, y_loc1, y_loc2;\n          dbTechLayer*          wire_layer = curWire->getTechLayer();\n          int                   l          = wire_layer->getRoutingLevel();\n          dbTechLayerDir::Value layer_dir  = wire_layer->getDirection();\n          if(l == m_bottom_layer){\n            layer_dir = dbTechLayerDir::Value::HORIZONTAL;\n          }\n          if (layer_dir == dbTechLayerDir::Value::HORIZONTAL) {\n            y_loc1 = (curWire->yMin() + curWire->yMax()) / 2;\n            y_loc2 = (curWire->yMin() + curWire->yMax()) / 2;\n            x_loc1 = curWire->xMin();\n            x_loc2 = curWire->xMax();\n          } else {\n            x_loc1 = (curWire->xMin() + curWire->xMax()) / 2;\n            x_loc2 = (curWire->xMin() + curWire->xMax()) / 2;\n            y_loc1 = curWire->yMin();\n            y_loc2 = curWire->yMax();\n          }\n          if (l == m_bottom_layer || l == m_top_layer) {  // special case for bottom and top layers we design a dense grid\n            if (layer_dir == dbTechLayerDir::Value::HORIZONTAL ) {\n              int x_i;\n              x_loc1 = (x_loc1/m_node_density)*m_node_density; //quantize the horizontal direction\n              x_loc2 = (x_loc2/m_node_density)*m_node_density; //quantize the horizontal direction\n              for (x_i = x_loc1; x_i <= x_loc2; x_i = x_i + m_node_density) {\n                m_Gmat->SetNode(x_i, y_loc1, l, make_pair(0, 0));\n              }\n            } else {\n              y_loc1 = (y_loc1/m_node_density)*m_node_density; //quantize the vertical direction\n              y_loc2 = (y_loc2/m_node_density)*m_node_density; //quantize the vertical direction\n              int y_i;\n              for (y_i = y_loc1; y_i <= y_loc2; y_i = y_i + m_node_density) {\n                m_Gmat->SetNode(x_loc1, y_i, l, make_pair(0, 0));\n              }\n            }\n          } else {  // add end nodes\n            m_Gmat->SetNode(x_loc1, y_loc1, l, make_pair(0, 0));\n            m_Gmat->SetNode(x_loc2, y_loc2, l, make_pair(0, 0));\n          }\n        }\n      }\n    }\n  }\n  cout<<endl;\n  progress_wires =0;\n  progress_percent =1;\n  // insert c4 bumps as nodes\n  int num_C4 =0;\n  for (unsigned int it = 0; it < m_C4Bumps.size(); ++it) {\n    int x = get<0>(m_C4Bumps[it]);\n    int y = get<1>(m_C4Bumps[it]);\n    int size = get<2>(m_C4Bumps[it]);\n    double v  = get<3>(m_C4Bumps[it]);\n    std::vector<Node*> RDL_nodes;\n    RDL_nodes = m_Gmat->GetRDLNodes(m_top_layer, \n                                    m_top_layer_dir,\n                                    x-size/2, \n                                    x+size/2,\n                                    y-size/2,\n                                    y+size/2);\n    if (RDL_nodes.empty() == true) {\n      Node* node = m_Gmat->GetNode(x,y,m_top_layer,true);\n      NodeLoc node_loc = node->GetLoc();\n      double new_loc1 = ((double)node_loc.first) /((double) unit_micron);\n      double new_loc2 = ((double)node_loc.second) /((double) unit_micron);\n      double old_loc1 = ((double)x) /((double) unit_micron);\n      double old_loc2 = ((double)y) /((double) unit_micron);\n      double old_size = ((double)size) /((double) unit_micron);\n      cout<<\"WARNING: Vsrc location at x=\"<<std::setprecision(3)<<old_loc1<<\"um , y=\"<<old_loc2\n          <<\"um and size =\"<<old_size<<\"um,  is not located on a power stripe.\"<<endl;\n      cout<<\"         Moving to closest stripe at x=\"<<std::setprecision(3)<<new_loc1<<\"um , y=\"<<new_loc2<<\"um\"<<endl;\n      RDL_nodes = m_Gmat->GetRDLNodes(m_top_layer, \n                                      m_top_layer_dir,\n                                      node_loc.first-size/2, \n                                      node_loc.first+size/2,\n                                      node_loc.second-size/2,\n                                      node_loc.second+size/2);\n\n    }\n    vector<Node*>::iterator node_it;\n    for(node_it = RDL_nodes.begin(); node_it != RDL_nodes.end(); ++node_it) {\n      Node* node = *node_it;\n      m_C4Nodes.push_back(make_pair(node->GetGLoc(),v));\n      num_C4++;\n    }\n  }\n  // All new nodes must be inserted by this point\n  // initialize G Matrix\n\n  cout << \"INFO: Number of nodes on net \" << m_power_net <<\" =\" << m_Gmat->GetNumNodes() << endl;\n  cout << \"Creating Connections:     \";\n  m_Gmat->InitializeGmatDok(num_C4);\n  int err_flag_via = 1;\n  int err_flag_layer = 1;\n  for (vIter = power_nets.begin(); vIter != power_nets.end();\n       ++vIter) {  // only 1 is expected?\n    dbNet*                   curDnet = *vIter;\n    dbSet<dbSWire>           swires  = curDnet->getSWires();\n    dbSet<dbSWire>::iterator sIter;\n    for (sIter = swires.begin(); sIter != swires.end();\n         ++sIter) {  // only 1 is expected?\n      dbSWire*                curSWire = *sIter;\n      dbSet<dbSBox>           wires    = curSWire->getWires();\n      dbSet<dbSBox>::iterator wIter;\n      for (wIter = wires.begin(); wIter != wires.end(); ++wIter) {\n        if(progress_wires >= ((progress_percent/100.0)*num_wires)-1.0 ){\n          cout<<\"\\b\\b\\b\\b\"<<setw(3)<<progress_percent++<<\"%\"<< std::flush;\n        }\n        progress_wires++;\n        dbSBox* curWire = *wIter;\n        if (curWire->isVia()) {\n          dbVia* via      = curWire->getBlockVia();\n          int num_via_rows = 1;\n          int num_via_cols = 1;\n          int check_params = via->hasParams();\n          int x_cut_size = 0;\n          int y_cut_size = 0;\n          int x_bottom_enclosure = 0;\n          int y_bottom_enclosure = 0;\n          int x_top_enclosure = 0;\n          int y_top_enclosure = 0;\n\t\t  if(check_params == 1) {\n\t\t    dbViaParams params;\n\t\t\tvia->getViaParams(params);\n\t\t    num_via_rows = params.getNumCutRows();\n\t\t    num_via_cols = params.getNumCutCols();\n\t\t    x_cut_size = params.getXCutSize();\n\t\t    y_cut_size = params.getYCutSize();\n            x_bottom_enclosure = params.getXBottomEnclosure();\n            y_bottom_enclosure = params.getYBottomEnclosure();\n            x_top_enclosure = params.getXTopEnclosure();\n            y_top_enclosure = params.getYTopEnclosure();\n\t\t  }\n          dbBox* via_bBox = via->getBBox();\n          BBox   bBox\n              = make_pair((via_bBox->getDX()) / 2, (via_bBox->getDY()) / 2);\n          int x, y;\n          curWire->getViaXY(x, y);\n          dbTechLayer* via_layer = via->getBottomLayer();\n          int          l         = via_layer->getRoutingLevel();\n\n          double R = via_layer->getUpperLayer()->getResistance();\n          R = R/(num_via_rows * num_via_cols);\n          if (R == 0.0) {\n            err_flag_via = 0;\n            //R = get<2>(m_layer_res[l]); /// Must figure out via resistance value\n            //cout << \"Via Resistance\" << R << endl;\n          }\n          bool top_or_bottom = ((l == m_bottom_layer) || (l == m_top_layer));\n          Node* node_bot = m_Gmat->GetNode(x, y, l,top_or_bottom);\n          NodeLoc node_loc = node_bot->GetLoc();\n          if( abs(node_loc.first - x) > m_node_density || abs(node_loc.second - y) > m_node_density ){\n            cout<<\"WARNING: Node at \"<<node_loc.first<<\" \"<<node_loc.second<<\" layer \"<<l<<\" moved from \"<<x<<\" \"<<y<<endl;\n          }\n\n          via_layer      = via->getTopLayer();\n          l              = via_layer->getRoutingLevel();\n          top_or_bottom = ((l == m_bottom_layer) || (l == m_top_layer));\n          Node* node_top = m_Gmat->GetNode(x, y, l,top_or_bottom);\n          node_loc = node_top->GetLoc();\n          if( abs(node_loc.first - x) > m_node_density || abs(node_loc.second - y) > m_node_density ){\n            cout<<\"WARNING: Node at \"<<node_loc.first<<\" \"<<node_loc.second<<\" layer \"<<l<<\" moved from \"<<x<<\" \"<<y<<endl;\n          }\n\n          if (node_bot == nullptr || node_top == nullptr) {\n            cout << \"ERROR: null pointer received for expected node. Code may \"\n                    \"fail ahead.\"<<endl;\n            return false;\n          } else {\n            if(R <= 1e-12){ //if the resitance was not set.\n                m_Gmat->SetConductance(node_bot, node_top, 0);\n            } else {\n                m_Gmat->SetConductance(node_bot, node_top, 1 / R);\n            }\n          }\n          \n          via_layer = via->getBottomLayer();\n          dbTechLayerDir::Value layer_dir  = via_layer->getDirection();\n          l         = via_layer->getRoutingLevel();\n          if(l != m_bottom_layer) {\n            double       rho        = via_layer->getResistance()\n                         * double(via_layer->getWidth())\n                         / double(unit_micron);\n            if (rho <= 1e-12) {\n              rho = 0;\n              err_flag_layer = 0;\n            }\n            int x_loc1,x_loc2,y_loc1,y_loc2;\n            if (layer_dir == dbTechLayerDir::Value::HORIZONTAL) {\n              y_loc1 = y - y_cut_size/2;\n              y_loc2 = y + y_cut_size/2;\n              x_loc1 = x - (x_bottom_enclosure+x_cut_size/2);\n              x_loc2 = x + (x_bottom_enclosure+x_cut_size/2);\n            } else {\n              y_loc1 = y - (y_bottom_enclosure+y_cut_size/2);\n              y_loc2 = y + (y_bottom_enclosure+y_cut_size/2);\n              x_loc1 = x - x_cut_size/2;\n              x_loc2 = x + x_cut_size/2;\n            }\n            m_Gmat->GenerateStripeConductance(via_layer->getRoutingLevel(),\n                                              layer_dir,\n                                              x_loc1,\n                                              x_loc2,\n                                              y_loc1,\n                                              y_loc2,\n                                              rho);\n          }\n          via_layer = via->getTopLayer();\n          layer_dir  = via_layer->getDirection();\n          l         = via_layer->getRoutingLevel();\n          if(l != m_top_layer) {\n            double       rho        = via_layer->getResistance()\n                         * double(via_layer->getWidth())\n                         / double(unit_micron);\n            if (rho <= 1e-12) {\n              rho = 0;\n              err_flag_layer = 0;\n            }\n            int x_loc1,x_loc2,y_loc1,y_loc2;\n            if (layer_dir == dbTechLayerDir::Value::HORIZONTAL) {\n              y_loc1 = y - y_cut_size/2;\n              y_loc2 = y + y_cut_size/2;\n              x_loc1 = x - (x_top_enclosure+x_cut_size/2);\n              x_loc2 = x + (x_top_enclosure+x_cut_size/2);\n            } else {\n              y_loc1 = y - (y_top_enclosure+y_cut_size/2);\n              y_loc2 = y + (y_top_enclosure+y_cut_size/2);\n              x_loc1 = x - x_cut_size/2;\n              x_loc2 = x + x_cut_size/2;\n            }\n            m_Gmat->GenerateStripeConductance(via_layer->getRoutingLevel(),\n                                              layer_dir,\n                                              x_loc1,\n                                              x_loc2,\n                                              y_loc1,\n                                              y_loc2,\n                                              rho);\n          }\n\n\n        } else {\n          dbTechLayer* wire_layer = curWire->getTechLayer();\n          int l  = wire_layer->getRoutingLevel();\n          double       rho        = wire_layer->getResistance()\n                       * double(wire_layer->getWidth())\n                       / double(unit_micron);\n          if (rho <= 1e-12) {\n            rho = 0;\n            err_flag_layer = 0;\n          }\n          dbTechLayerDir::Value layer_dir = wire_layer->getDirection();\n          if (l == m_bottom_layer){//ensure that the bootom layer(rail) is horizontal\n            layer_dir = dbTechLayerDir::Value::HORIZONTAL;\n          }\n          int x_loc1 = curWire->xMin();\n          int x_loc2 = curWire->xMax();\n          int y_loc1 = curWire->yMin();\n          int y_loc2 = curWire->yMax();\n          if (l == m_bottom_layer || l == m_top_layer) {  // special case for bottom and top layers we design a dense grid\n            if (layer_dir == dbTechLayerDir::Value::HORIZONTAL ) {\n              x_loc1 = (x_loc1/m_node_density)*m_node_density; //quantize the horizontal direction\n              x_loc2 = (x_loc2/m_node_density)*m_node_density; //quantize the horizontal direction\n            } else {\n              y_loc1 = (y_loc1/m_node_density)*m_node_density; //quantize the vertical direction\n              y_loc2 = (y_loc2/m_node_density)*m_node_density; //quantize the vertical direction\n            }\n          }\n          m_Gmat->GenerateStripeConductance(wire_layer->getRoutingLevel(),\n                                            layer_dir,\n                                            x_loc1,    \n                                            x_loc2,\n                                            y_loc1,\n                                            y_loc2,\n                                            rho);\n        }\n      }\n    }\n  }\n  cout<<endl;\n  cout << \"INFO: G matrix created \" << endl;\n  if (err_flag_via == 0 && !connection_only) {\n    cout << \"Error: Atleast one via resistance not found in DB. Check the LEF or set it with a odb::setResistance command\"<<endl;\n    return false;\n  }\n  if (err_flag_layer == 0 && !connection_only) {\n    cout << \"Error: Atleast one layer per unit resistance not found in DB. Check the LEF or set it with a odb::setResistance command\"<<endl;\n    return false;\n  }\n  return true;\n}\n\nbool IRSolver::CheckConnectivity()\n{\n  std::vector<std::pair<NodeIdx,double>>::iterator c4_node_it;\n  int x,y;\n  CscMatrix*        Amat = m_Gmat->GetAMat();\n  int num_nodes = m_Gmat->GetNumNodes();\n\n  dbTech* tech   = m_db->getTech();\n  int unit_micron = tech->getDbUnitsPerMicron();\n\n  for(c4_node_it = m_C4Nodes.begin(); c4_node_it != m_C4Nodes.end() ; c4_node_it++){\n    Node* c4_node = m_Gmat->GetNode((*c4_node_it).first);\n    std::queue<Node*> node_q;\n    node_q.push(c4_node);\n    while(!node_q.empty()) {\n      NodeIdx col_loc, n_col_loc;\n      Node* node = node_q.front();\n      node_q.pop();\n      node->SetConnected();\n      NodeIdx col_num = node->GetGLoc();\n      col_loc  = Amat->col_ptr[col_num];\n      if(col_num < Amat->col_ptr.size()-1) {\n        n_col_loc  = Amat->col_ptr[col_num+1];\n      } else {\n        n_col_loc  = Amat->row_idx.size() ;\n      }\n      std::vector<NodeIdx> col_vec(Amat->row_idx.begin()+col_loc,\n                                   Amat->row_idx.begin()+n_col_loc);\n\n\n      std::vector<NodeIdx>::iterator col_vec_it;\n      for(col_vec_it = col_vec.begin(); col_vec_it != col_vec.end(); col_vec_it++){\n        if(*col_vec_it<num_nodes) {\n          Node* node_next = m_Gmat->GetNode(*col_vec_it);\n          if(!(node_next->GetConnected())) {\n            node_q.push(node_next);\n          }\n        }\n      }\n    }\n  }\n  int uncon_err_cnt = 0;\n  int uncon_err_flag = 0;\n  int uncon_inst_cnt = 0;\n  int uncon_inst_flag = 0;\n  std::vector<Node*> node_list = m_Gmat->GetAllNodes();\n  std::vector<Node*>::iterator node_list_it;\n  bool unconnected_node =false;\n  for(node_list_it = node_list.begin(); node_list_it != node_list.end(); node_list_it++){\n    if(!(*node_list_it)->GetConnected()){\n      uncon_err_cnt++;\n      NodeLoc node_loc = (*node_list_it)->GetLoc();\n      float loc_x = ((float)node_loc.first)/((float)unit_micron);\n      float loc_y = ((float)node_loc.second)/((float)unit_micron);\n\n      //if(uncon_err_cnt>25 && uncon_err_flag ==0 ) {\n      //  uncon_err_flag =1;\n      //  cout<<\"Error display limit reached, suppressing further unconnected node error messages\"<<endl;\n      //} else if( uncon_err_flag ==0) {\n        //cout<<\"node_not_connected =================================\"<<endl;\n        unconnected_node =true;\n        cout<<\"Warning: Unconnected PDN node on net \" << m_power_net<<\" at location x:\"<<loc_x<<\"um, y:\"\n            <<loc_y<<\"um ,layer: \"<<(*node_list_it)->GetLayerNum()<<endl;\n      //}\n      //if(uncon_inst_cnt>25 && uncon_inst_flag ==0 ) {\n      //  uncon_inst_flag =1;\n      //  cout<<\"Error display limit reached, suppressing further unconnected instance error messages\"<<endl;\n      //} else if( uncon_inst_flag ==0) {\n        if((*node_list_it)->HasInstances()){\n          std::vector<dbInst*> insts = (*node_list_it)->GetInstances();\n          std::vector<dbInst*>::iterator inst_it;\n          for(inst_it = insts.begin();inst_it!=insts.end();inst_it++) {\n            uncon_inst_cnt++;\n            cout<<\"Warning: Instance: \"<< (*inst_it)->getName() <<\"at location x:\"<<loc_x<<\"um, y:\"\n              <<loc_y<<\"um ,layer: \"<<(*node_list_it)->GetLayerNum()<<endl;\n          }\n        }\n      //}\n    }\n  }\n  if(unconnected_node == false){\n    cout<<\"INFO: No dangling stripe found on net \"<<m_power_net<< endl;\n    cout <<\"INFO: Connection between all PDN nodes established on net \"<<m_power_net <<endl;\n  }\n  return !unconnected_node;\n}\n\nint IRSolver::GetConnectionTest(){\n  if(m_connection){\n    return 1;\n  } else {\n    return 0;\n  }\n}\n\n//! Function to get the power value from OpenSTA\n/*\n *\\return vector of pairs of instance name \n and its corresponding power value\n*/\nvector<pair<string, double>> IRSolver::GetPower()\n{\n  PowerInst                    power_inst;\n  vector<pair<string, double>> power_report = power_inst.executePowerPerInst(\n      m_sta);\n\n  return power_report;\n}\n\nbool IRSolver::GetResult(){\n  return m_result; \n}\n\nint IRSolver::PrintSpice() {\n  DokMatrix*        Gmat = m_Gmat->GetGMatDOK();\n  map<GMatLoc, double>::iterator it;\n  \n  ofstream pdnsim_spice_file;\n  pdnsim_spice_file.open (m_spice_out_file);\n  if (!pdnsim_spice_file.is_open()) {\n    cout << \"File did not open\" << endl;\n    return 0;\n  }\n  vector<double>    J = GetJ();\n  int num_nodes = m_Gmat->GetNumNodes();\n  int resistance_number = 0;\n  int voltage_number = 0;\n  int current_number = 0; \n\n  NodeLoc node_loc;\n  for(it = Gmat->values.begin(); it!= Gmat->values.end(); it++){\n    NodeIdx col = (it->first).first;\n    NodeIdx row = (it->first).second;\n    if(col <= row) {\n      continue; //ignore lower half and diagonal as matrix is symmetric\n    }\n    double cond = it->second;           // get cond value\n    if(abs(cond) < 1e-15){            //ignore if an empty cell\n      continue;\n    }\n\n    string net_name = \"vdd\";\n    if(col < num_nodes) { //resistances\n      double resistance = -1/cond;\n\n      Node* node1 = m_Gmat->GetNode(col); \n      Node* node2 = m_Gmat->GetNode(row); \n      node_loc = node1->GetLoc();\n      int x1 = node_loc.first;\n      int y1 = node_loc.second;\n      int l1 = node1->GetLayerNum();\n      string node1_name = net_name + \"_\" + to_string(x1) + \"_\" + to_string(y1) + \"_\" + to_string(l1);\n\n      node_loc = node2->GetLoc();\n      int x2 = node_loc.first;\n      int y2 = node_loc.second;\n      int l2 = node2->GetLayerNum();\n      string node2_name = net_name + \"_\" + to_string(x2) + \"_\" + to_string(y2) + \"_\" + to_string(l2);\n      \n      string resistance_name = \"R\" + to_string(resistance_number); \n      resistance_number++;\n\n      pdnsim_spice_file<< resistance_name <<\" \"<< node1_name << \" \" << node2_name <<\" \"<< to_string(resistance) <<endl;\n\n      double current = node1->GetCurrent();\n      string current_name = \"I\" + to_string(current_number); \n      if(abs(current)> 1e-18) {\n        pdnsim_spice_file<< current_name <<\" \"<< node1_name << \" \" << 0 <<\" \"<< current <<endl;\n        current_number++;\n      }\n\n\n    } else { //voltage\n      Node* node1 = m_Gmat->GetNode(row); //VDD location \n      node_loc = node1->GetLoc();\n      double voltage = J[col];\n      int x1 = node_loc.first;\n      int y1 = node_loc.second;\n      int l1 = node1->GetLayerNum();\n      string node1_name = net_name + \"_\" + to_string(x1) + \"_\" + to_string(y1) + \"_\" + to_string(l1);\n      string voltage_name = \"V\" + to_string(voltage_number); \n      voltage_number++;\n      pdnsim_spice_file<< voltage_name <<\" \"<< node1_name << \" 0 \" << to_string(voltage) <<endl;\n    }\n  } \n  \n  pdnsim_spice_file<<\".OPTION NUMDGT=6\"<<endl;\n  pdnsim_spice_file<<\".OP\"<<endl;\n  pdnsim_spice_file<<\".END\"<<endl;\n  pdnsim_spice_file<<endl;\n  pdnsim_spice_file.close();\n  return 1;\n}\n\nbool IRSolver::Build() {\n  bool res = true;\n  ReadC4Data();\n  if(res) {\n    res = CreateGmat(); \n  }\n  if(res) {\n    res = CreateJ();\n  }\n  if(res) {\n    res = AddC4Bump();\n  }\n  if(res) {\n    res = m_Gmat->GenerateCSCMatrix();\n    res = m_Gmat->GenerateACSCMatrix();\n  }\n  if(res) {\n    m_connection = CheckConnectivity();\n    res = m_connection;\n  }\n  m_result = res;\n  return m_result;\n}\n\nbool IRSolver::BuildConnection() {\n  bool res = true;\n  ReadC4Data();\n  if(res) {\n    res = CreateGmat(true); \n  }\n  if(res) {\n    res = AddC4Bump();\n  }\n  if(res) {\n    res = m_Gmat->GenerateACSCMatrix();\n  }\n  if(res) {\n    m_connection = CheckConnectivity();\n    res = m_connection;\n  }\n  m_result = res;\n  return m_result;\n}\n \n", "meta": {"hexsha": "29db40c2bb38f7b762570273a03e1c770d4fadec", "size": 37016, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/PDNSim/src/ir_solver.cpp", "max_stars_repo_name": "tgingold/OpenROAD", "max_stars_repo_head_hexsha": "c37064854166551adb257ef8c4aa438f9cec5493", "max_stars_repo_licenses": ["BSD-3-Clause-Clear"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-14T06:27:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-14T06:27:26.000Z", "max_issues_repo_path": "src/PDNSim/src/ir_solver.cpp", "max_issues_repo_name": "tgingold/OpenROAD", "max_issues_repo_head_hexsha": "c37064854166551adb257ef8c4aa438f9cec5493", "max_issues_repo_licenses": ["BSD-3-Clause-Clear"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/PDNSim/src/ir_solver.cpp", "max_forks_repo_name": "tgingold/OpenROAD", "max_forks_repo_head_hexsha": "c37064854166551adb257ef8c4aa438f9cec5493", "max_forks_repo_licenses": ["BSD-3-Clause-Clear"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-14T06:27:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-14T06:27:38.000Z", "avg_line_length": 36.685827552, "max_line_length": 140, "alphanum_fraction": 0.5620002161, "num_tokens": 9904, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4999848209246289}}
{"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_FUNCTION_DOT_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_DOT_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-reduction\n    Function object implementing dot capabilities\n\n    returns the dot product of the two vector arguments\n\n    @par Semantic:\n\n    For every parameters of type T:\n\n    @code\n    scalar_of_t<T> r = dot(x,y);\n    @endcode\n\n    is similar to:\n\n    @code\n    scalar_of_t<T> r = sum(x*conj(y));\n    @endcode\n\n  **/\n  const boost::dispatch::functor<tag::dot_> dot = {};\n} }\n#endif\n\n#include <boost/simd/function/scalar/dot.hpp>\n#include <boost/simd/function/simd/dot.hpp>\n\n#endif\n", "meta": {"hexsha": "18ebfb9bb68cdee48ced1fb87c419b41fe004709", "size": 1087, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/dot.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/function/dot.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/function/dot.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": 22.1836734694, "max_line_length": 100, "alphanum_fraction": 0.5722171113, "num_tokens": 236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673133042217, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.49998481255940025}}
{"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/*!\n * \\file\n**/\n#ifndef BOOST_SIMD_SWAR_FUNCTIONS_CUMTRAPZ_HPP_INCLUDED\n#define BOOST_SIMD_SWAR_FUNCTIONS_CUMTRAPZ_HPP_INCLUDED\n#include <boost/simd/include/functor.hpp>\n#include <boost/dispatch/include/functor.hpp>\n#include <boost/simd/operator/functions/multiplies.hpp>\n#include <boost/simd/constant/constants/one.hpp>\n\n\n/*!\n * \\ingroup boost_simd_swar\n * \\defgroup boost_simd_swar_cumtrapz cumtrapz\n *\n * \\par Description\n * compute the cumulate trapz of the vector elements using the abscissae differences\n * is they are given\n *  z = cumtrapz(y) computes an approximation of the cumulative\n *  integral of y via the trapezoidal method (with unit spacing).  to\n *  compute the integral for spacing different from one, multiply z by\n *  the spacing incrementor use cumtrapz(dx, y) where dx is the abscisae\n *  constant and SCALAR increment.\n *\n *  for vectors, cumtrapz(y) is a vector containing the cumulative\n *  integral of y. for matrices, cumtrapz(y) is a matrix the same size as\n *  x with the cumulative integral over each column. for n-d arrays,\n *  cumtrapz(y) works along the first non-singleton dimension.\n *\n *  z = cumtrapz(x,y) computes the cumulative integral of y with respect\n *  to x using trapezoidal integration.  x and y must be vectors of the\n *  same length, or x must be a column vector and y an array whose first\n *  non-singleton dimension is length(x).  cumtrapz operates across this\n *  dimension.\n *  if x is scalar the increment is considered constant and of value x.\n *  (A 1x1 matrix expression is not a scalar)\n *\n *  z = cumtrapz(x,y,dim) or cumtrapz(y,dim) integrates along dimension\n *  dim of y. the length of x must be the same as size(y,dim)).\n *\n * \\par Header file\n *\n * \\code\n * #include <nt2/include/functions/cumtrapz.hpp>\n * \\endcode\n *\n *\n * \\synopsis\n *\n * \\code\n * namespace boost::simd\n * {\n *   template <class A0>\n *     meta::call<tag::cumtrapz_(A0)>::type\n *     cumtrapz(const A0 & x, const A1 & y, const A2 & dim);\n * }\n * \\endcode\n *\n *\n**/\n\nnamespace boost { namespace simd { namespace tag\n  {\n    /*!\n     * \\brief Define the tag cumtrapz_ of functor cumtrapz\n     *        in namespace boost::simd::tag for toolbox boost.simd.swar\n    **/\n    struct cumtrapz_ : tag::formal_\n    {\n      typedef tag::formal_ parent;\n    };\n  }\n  BOOST_DISPATCH_FUNCTION_IMPLEMENTATION(tag::cumtrapz_, cumtrapz, 1)\n  BOOST_DISPATCH_FUNCTION_IMPLEMENTATION(tag::cumtrapz_, cumtrapz, 2)\n  BOOST_DISPATCH_FUNCTION_IMPLEMENTATION(tag::cumtrapz_, cumtrapz, 3)\n} }\n\n#endif\n\n// modified by jt the 25/12/2010\n", "meta": {"hexsha": "1bf79349a2727faf110995842055bce26a164063", "size": 3054, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/swar/include/boost/simd/swar/functions/cumtrapz.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/swar/include/boost/simd/swar/functions/cumtrapz.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/swar/include/boost/simd/swar/functions/cumtrapz.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": 34.3146067416, "max_line_length": 84, "alphanum_fraction": 0.6640471513, "num_tokens": 806, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.6150878555160666, "lm_q1q2_score": 0.4999848097709907}}
{"text": "//\n// Copyright (c) 2019-2020 INRIA\n//\n\n#include \"pinocchio/autodiff/casadi.hpp\"\n\n#include \"pinocchio/algorithm/rnea.hpp\"\n#include \"pinocchio/algorithm/rnea-derivatives.hpp\"\n#include \"pinocchio/algorithm/aba.hpp\"\n#include \"pinocchio/algorithm/aba-derivatives.hpp\"\n#include \"pinocchio/algorithm/joint-configuration.hpp\"\n\n#include \"pinocchio/parsers/sample-models.hpp\"\n\n#include <casadi/casadi.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include <boost/utility/binary.hpp>\n\nBOOST_AUTO_TEST_SUITE(BOOST_TEST_MODULE)\n\nBOOST_AUTO_TEST_CASE(test_integrate)\n{\n  typedef double Scalar;\n  typedef casadi::SX ADScalar;\n  \n  typedef pinocchio::ModelTpl<Scalar> Model;\n  typedef Model::Data Data;\n  \n  typedef pinocchio::ModelTpl<ADScalar> ADModel;\n  typedef ADModel::Data ADData;\n  \n  Model model;\n  pinocchio::buildModels::humanoidRandom(model);\n  model.lowerPositionLimit.head<3>().fill(-1.);\n  model.upperPositionLimit.head<3>().fill(1.);\n  Data data(model);\n  \n  typedef Model::ConfigVectorType ConfigVector;\n  typedef Model::TangentVectorType TangentVector;\n  ConfigVector q(model.nq);\n  q = pinocchio::randomConfiguration(model);\n  TangentVector v(TangentVector::Random(model.nv));\n  TangentVector a(TangentVector::Random(model.nv));\n  \n  typedef ADModel::ConfigVectorType ConfigVectorAD;\n  ADModel ad_model = model.cast<ADScalar>();\n  ADData ad_data(ad_model);\n  \n  pinocchio::rnea(model,data,q,v,a);\n  \n  casadi::SX cs_q = casadi::SX::sym(\"q\", model.nq);\n  casadi::SX cs_v_int = casadi::SX::sym(\"v_inc\", model.nv);\n  \n  ConfigVectorAD q_ad(model.nq), v_int_ad(model.nv), q_int_ad(model.nq);\n  q_ad = Eigen::Map<ConfigVectorAD>(static_cast< std::vector<ADScalar> >(cs_q).data(),model.nq,1);\n  v_int_ad = Eigen::Map<ConfigVectorAD>(static_cast< std::vector<ADScalar> >(cs_v_int).data(),model.nv,1);\n  \n  pinocchio::integrate(ad_model,q_ad,v_int_ad,q_int_ad);\n  casadi::SX cs_q_int(model.nq,1);\n  pinocchio::casadi::copy(q_int_ad,cs_q_int);\n  \n  std::cout << \"cs_q_int:\" << cs_q_int << std::endl;\n  casadi::Function eval_integrate(\"eval_integrate\",\n                                  casadi::SXVector {cs_q,cs_v_int},\n                                  casadi::SXVector {cs_q_int});\n  std::vector<double> q_vec((size_t)model.nq);\n  Eigen::Map<ConfigVector>(q_vec.data(),model.nq,1) = q;\n  \n  std::vector<double> v_int_vec((size_t)model.nv);\n  Eigen::Map<TangentVector>(v_int_vec.data(),model.nv,1).setZero();\n  casadi::DM q_int_res = eval_integrate(casadi::DMVector {q_vec,v_int_vec})[0];\n  \n  Data::ConfigVectorType q_int_vec = Eigen::Map<Data::TangentVectorType>(static_cast< std::vector<double> >(q_int_res).data(),model.nq,1);\n  \n  ConfigVector q_plus(model.nq);\n  pinocchio::integrate(model,q,TangentVector::Zero(model.nv),q_plus);\n  \n  std::cout << \"q_int_vec: \" << q_int_vec.transpose() << std::endl;\n  BOOST_CHECK(q_plus.isApprox(q_int_vec));\n}\n  \nBOOST_AUTO_TEST_CASE(test_rnea_derivatives)\n{\n  typedef double Scalar;\n  typedef casadi::SX ADScalar;\n  \n  typedef pinocchio::ModelTpl<Scalar> Model;\n  typedef Model::Data Data;\n  \n  typedef pinocchio::ModelTpl<ADScalar> ADModel;\n  typedef ADModel::Data ADData;\n  \n  Model model;\n  pinocchio::buildModels::humanoidRandom(model);\n  model.lowerPositionLimit.head<3>().fill(-1.);\n  model.upperPositionLimit.head<3>().fill(1.);\n  Data data(model);\n  \n  typedef Model::ConfigVectorType ConfigVector;\n  typedef Model::TangentVectorType TangentVector;\n  ConfigVector q(model.nq);\n  q = pinocchio::randomConfiguration(model);\n  TangentVector v(TangentVector::Random(model.nv));\n  TangentVector a(TangentVector::Random(model.nv));\n  \n  typedef ADModel::ConfigVectorType ConfigVectorAD;\n  typedef ADModel::TangentVectorType TangentVectorAD;\n  ADModel ad_model = model.cast<ADScalar>();\n  ADData ad_data(ad_model);\n  \n  pinocchio::rnea(model,data,q,v,a);\n  \n  casadi::SX cs_q = casadi::SX::sym(\"q\", model.nq);\n  casadi::SX cs_v_int = casadi::SX::sym(\"v_inc\", model.nv);\n  \n  ConfigVectorAD q_ad(model.nq), v_int_ad(model.nv), q_int_ad(model.nq);\n  q_ad = Eigen::Map<ConfigVectorAD>(static_cast< std::vector<ADScalar> >(cs_q).data(),model.nq,1);\n  v_int_ad = Eigen::Map<ConfigVectorAD>(static_cast< std::vector<ADScalar> >(cs_v_int).data(),model.nv,1);\n  \n  pinocchio::integrate(ad_model,q_ad,v_int_ad,q_int_ad);\n  casadi::SX cs_q_int(model.nq,1);\n  pinocchio::casadi::copy(q_int_ad,cs_q_int);\n  std::vector<double> q_vec((size_t)model.nq);\n  Eigen::Map<ConfigVector>(q_vec.data(),model.nq,1) = q;\n  \n  std::vector<double> v_int_vec((size_t)model.nv);\n  Eigen::Map<TangentVector>(v_int_vec.data(),model.nv,1).setZero();\n  \n  casadi::SX cs_v = casadi::SX::sym(\"v\", model.nv);\n  TangentVectorAD v_ad(model.nv);\n  v_ad = Eigen::Map<TangentVectorAD>(static_cast< std::vector<ADScalar> >(cs_v).data(),model.nv,1);\n  \n  casadi::SX cs_a = casadi::SX::sym(\"a\", model.nv);\n  TangentVectorAD a_ad(model.nv);\n  a_ad = Eigen::Map<TangentVectorAD>(static_cast< std::vector<ADScalar> >(cs_a).data(),model.nv,1);\n  \n  rnea(ad_model,ad_data,q_int_ad,v_ad,a_ad);\n  casadi::SX cs_tau(model.nv,1);\n  for(Eigen::DenseIndex k = 0; k < model.nv; ++k)\n  {\n    cs_tau(k) = ad_data.tau[k];\n  }\n  casadi::Function eval_rnea(\"eval_rnea\",\n                             casadi::SXVector {cs_q,cs_v_int, cs_v, cs_a},\n                             casadi::SXVector {cs_tau});\n  \n  std::vector<double> v_vec((size_t)model.nv);\n  Eigen::Map<TangentVector>(v_vec.data(),model.nv,1) = v;\n  \n  std::vector<double> a_vec((size_t)model.nv);\n  Eigen::Map<TangentVector>(a_vec.data(),model.nv,1) = a;\n  \n  // check return value\n  casadi::DM tau_res = eval_rnea(casadi::DMVector {q_vec,v_int_vec,v_vec,a_vec})[0];\n  std::cout << \"tau_res = \" << tau_res << std::endl;\n  Data::TangentVectorType tau_vec = Eigen::Map<Data::TangentVectorType>(static_cast< std::vector<double> >(tau_res).data(),model.nv,1);\n  \n  BOOST_CHECK(data.tau.isApprox(tau_vec));\n  \n  // compute references\n  Data::MatrixXs dtau_dq_ref(model.nv,model.nv), dtau_dv_ref(model.nv,model.nv), dtau_da_ref(model.nv,model.nv);\n  dtau_dq_ref.setZero(); dtau_dv_ref.setZero(); dtau_da_ref.setZero();\n  \n  pinocchio::computeRNEADerivatives(model,data,q,v,a,dtau_dq_ref,dtau_dv_ref,dtau_da_ref);\n  dtau_da_ref.triangularView<Eigen::StrictlyLower>() = dtau_da_ref.transpose().triangularView<Eigen::StrictlyLower>();\n  \n  // check with respect to q+dq\n  casadi::SX dtau_dq = jacobian(cs_tau, cs_v_int);\n  casadi::Function eval_dtau_dq(\"eval_dtau_dq\",\n                                casadi::SXVector {cs_q,cs_v_int, cs_v, cs_a},\n                                casadi::SXVector {dtau_dq});\n  \n  casadi::DM dtau_dq_res = eval_dtau_dq(casadi::DMVector {q_vec,v_int_vec,v_vec,a_vec})[0];\n  std::vector<double> dtau_dq_vec(static_cast< std::vector<double> >(dtau_dq_res));\n  BOOST_CHECK(Eigen::Map<Data::MatrixXs>(dtau_dq_vec.data(),model.nv,model.nv).isApprox(dtau_dq_ref));\n  \n  // check with respect to v+dv\n  casadi::SX dtau_dv = jacobian(cs_tau, cs_v);\n  casadi::Function eval_dtau_dv(\"eval_dtau_dv\",\n                                casadi::SXVector {cs_q,cs_v_int, cs_v, cs_a},\n                                casadi::SXVector {dtau_dv});\n  \n  casadi::DM dtau_dv_res = eval_dtau_dv(casadi::DMVector {q_vec,v_int_vec,v_vec,a_vec})[0];\n  std::vector<double> dtau_dv_vec(static_cast< std::vector<double> >(dtau_dv_res));\n  BOOST_CHECK(Eigen::Map<Data::MatrixXs>(dtau_dv_vec.data(),model.nv,model.nv).isApprox(dtau_dv_ref));\n  \n  // check with respect to a+da\n  casadi::SX dtau_da = jacobian(cs_tau, cs_a);\n  casadi::Function eval_dtau_da(\"eval_dtau_da\",\n                                casadi::SXVector {cs_q,cs_v_int, cs_v, cs_a},\n                                casadi::SXVector {dtau_da});\n  \n  casadi::DM dtau_da_res = eval_dtau_da(casadi::DMVector {q_vec,v_int_vec,v_vec,a_vec})[0];\n  std::vector<double> dtau_da_vec(static_cast< std::vector<double> >(dtau_da_res));\n  BOOST_CHECK(Eigen::Map<Data::MatrixXs>(dtau_da_vec.data(),model.nv,model.nv).isApprox(dtau_da_ref));\n  \n  // call RNEA derivatives in Casadi\n  casadi::SX cs_dtau_dq(model.nv,model.nv);\n  casadi::SX cs_dtau_dv(model.nv,model.nv);\n  casadi::SX cs_dtau_da(model.nv,model.nv);\n  \n  computeRNEADerivatives(ad_model,ad_data,q_ad,v_ad,a_ad);\n  ad_data.M.triangularView<Eigen::StrictlyLower>()\n  = ad_data.M.transpose().triangularView<Eigen::StrictlyLower>();\n  \n  pinocchio::casadi::copy(ad_data.dtau_dq,cs_dtau_dq);\n  pinocchio::casadi::copy(ad_data.dtau_dv,cs_dtau_dv);\n  pinocchio::casadi::copy(ad_data.M,cs_dtau_da);\n  \n  casadi::Function eval_rnea_derivatives_dq(\"eval_rnea_derivatives_dq\",\n                                            casadi::SXVector {cs_q, cs_v, cs_a},\n                                            casadi::SXVector {cs_dtau_dq});\n  \n  casadi::DM dtau_dq_res_direct = eval_rnea_derivatives_dq(casadi::DMVector {q_vec,v_vec,a_vec})[0];\n  Data::MatrixXs dtau_dq_res_direct_map = Eigen::Map<Data::MatrixXs>(static_cast< std::vector<double> >(dtau_dq_res_direct).data(),model.nv,model.nv);\n  BOOST_CHECK(dtau_dq_ref.isApprox(dtau_dq_res_direct_map));\n  \n  casadi::Function eval_rnea_derivatives_dv(\"eval_rnea_derivatives_dv\",\n                                            casadi::SXVector {cs_q, cs_v, cs_a},\n                                            casadi::SXVector {cs_dtau_dv});\n  \n  casadi::DM dtau_dv_res_direct = eval_rnea_derivatives_dv(casadi::DMVector {q_vec,v_vec,a_vec})[0];\n  Data::MatrixXs dtau_dv_res_direct_map = Eigen::Map<Data::MatrixXs>(static_cast< std::vector<double> >(dtau_dv_res_direct).data(),model.nv,model.nv);\n  BOOST_CHECK(dtau_dv_ref.isApprox(dtau_dv_res_direct_map));\n  \n  casadi::Function eval_rnea_derivatives_da(\"eval_rnea_derivatives_da\",\n                                            casadi::SXVector {cs_q, cs_v, cs_a},\n                                            casadi::SXVector {cs_dtau_da});\n  \n  casadi::DM dtau_da_res_direct = eval_rnea_derivatives_da(casadi::DMVector {q_vec,v_vec,a_vec})[0];\n  Data::MatrixXs dtau_da_res_direct_map = Eigen::Map<Data::MatrixXs>(static_cast< std::vector<double> >(dtau_da_res_direct).data(),model.nv,model.nv);\n  BOOST_CHECK(dtau_da_ref.isApprox(dtau_da_res_direct_map));\n}\n  \n  BOOST_AUTO_TEST_CASE(test_aba)\n  {\n    typedef double Scalar;\n    typedef casadi::SX ADScalar;\n\n    typedef pinocchio::ModelTpl<Scalar> Model;\n    typedef Model::Data Data;\n\n    typedef pinocchio::ModelTpl<ADScalar> ADModel;\n    typedef ADModel::Data ADData;\n\n    Model model;\n    pinocchio::buildModels::humanoidRandom(model);\n    model.lowerPositionLimit.head<3>().fill(-1.);\n    model.upperPositionLimit.head<3>().fill(1.);\n    Data data(model);\n\n    typedef Model::ConfigVectorType ConfigVector;\n    typedef Model::TangentVectorType TangentVector;\n    ConfigVector q(model.nq);\n    q = pinocchio::randomConfiguration(model);\n    TangentVector v(TangentVector::Random(model.nv));\n    TangentVector tau(TangentVector::Random(model.nv));\n\n    typedef ADModel::ConfigVectorType ConfigVectorAD;\n    typedef ADModel::TangentVectorType TangentVectorAD;\n    ADModel ad_model = model.cast<ADScalar>();\n    ADData ad_data(ad_model);\n\n    pinocchio::aba(model,data,q,v,tau);\n\n    casadi::SX cs_q = casadi::SX::sym(\"q\", model.nq);\n    casadi::SX cs_v_int = casadi::SX::sym(\"v_inc\", model.nv);\n    ConfigVectorAD q_ad(model.nq), v_int_ad(model.nv), q_int_ad(model.nq);\n    q_ad = Eigen::Map<ConfigVectorAD>(static_cast< std::vector<ADScalar> >(cs_q).data(),model.nq,1);\n    v_int_ad = Eigen::Map<ConfigVectorAD>(static_cast< std::vector<ADScalar> >(cs_v_int).data(),model.nv,1);\n    \n    pinocchio::integrate(ad_model,q_ad,v_int_ad,q_int_ad);\n    casadi::SX cs_q_int(model.nq,1);\n    pinocchio::casadi::copy(q_int_ad,cs_q_int);\n    std::vector<double> q_vec((size_t)model.nq);\n    Eigen::Map<ConfigVector>(q_vec.data(),model.nq,1) = q;\n    \n    std::vector<double> v_int_vec((size_t)model.nv);\n    Eigen::Map<TangentVector>(v_int_vec.data(),model.nv,1).setZero();\n\n    casadi::SX cs_v = casadi::SX::sym(\"v\", model.nv);\n    TangentVectorAD v_ad(model.nv);\n    v_ad = Eigen::Map<TangentVectorAD>(static_cast< std::vector<ADScalar> >(cs_v).data(),model.nv,1);\n\n    casadi::SX cs_tau = casadi::SX::sym(\"tau\", model.nv);\n    TangentVectorAD tau_ad(model.nv);\n    tau_ad = Eigen::Map<TangentVectorAD>(static_cast< std::vector<ADScalar> >(cs_tau).data(),model.nv,1);\n\n    // ABA\n    aba(ad_model,ad_data,q_int_ad,v_ad,tau_ad);\n    casadi::SX cs_ddq(model.nv,1);\n    for(Eigen::DenseIndex k = 0; k < model.nv; ++k)\n      cs_ddq(k) = ad_data.ddq[k];\n    casadi::Function eval_aba(\"eval_aba\",\n                              casadi::SXVector {cs_q, cs_v_int, cs_v, cs_tau},\n                              casadi::SXVector {cs_ddq});\n\n    std::vector<double> v_vec((size_t)model.nv);\n    Eigen::Map<TangentVector>(v_vec.data(),model.nv,1) = v;\n\n    std::vector<double> tau_vec((size_t)model.nv);\n    Eigen::Map<TangentVector>(tau_vec.data(),model.nv,1) = tau;\n\n    casadi::DM ddq_res = eval_aba(casadi::DMVector {q_vec, v_int_vec, v_vec, tau_vec})[0];\n    Data::TangentVectorType ddq_mat = Eigen::Map<Data::TangentVectorType>(static_cast< std::vector<double> >(ddq_res).data(),\n                                                            model.nv,1);\n\n    BOOST_CHECK(ddq_mat.isApprox(data.ddq));\n    \n    // compute references\n    Data::MatrixXs ddq_dq_ref(model.nv,model.nv), ddq_dv_ref(model.nv,model.nv), ddq_dtau_ref(model.nv,model.nv);\n    ddq_dq_ref.setZero(); ddq_dv_ref.setZero(); ddq_dtau_ref.setZero();\n    \n    pinocchio::computeABADerivatives(model,data,q,v,tau,ddq_dq_ref,ddq_dv_ref,ddq_dtau_ref);\n    ddq_dtau_ref.triangularView<Eigen::StrictlyLower>()\n    = ddq_dtau_ref.transpose().triangularView<Eigen::StrictlyLower>();\n    \n    // check with respect to q+dq\n    casadi::SX ddq_dq = jacobian(cs_ddq, cs_v_int);\n    casadi::Function eval_ddq_dq(\"eval_ddq_dq\",\n                                  casadi::SXVector {cs_q,cs_v_int,cs_v,cs_tau},\n                                  casadi::SXVector {ddq_dq});\n    \n    casadi::DM ddq_dq_res = eval_ddq_dq(casadi::DMVector {q_vec,v_int_vec,v_vec,tau_vec})[0];\n    std::vector<double> ddq_dq_vec(static_cast< std::vector<double> >(ddq_dq_res));\n    BOOST_CHECK(Eigen::Map<Data::MatrixXs>(ddq_dq_vec.data(),model.nv,model.nv).isApprox(ddq_dq_ref));\n    \n    // check with respect to v+dv\n    casadi::SX ddq_dv = jacobian(cs_ddq, cs_v);\n    casadi::Function eval_ddq_dv(\"eval_ddq_dv\",\n                                  casadi::SXVector {cs_q,cs_v_int, cs_v, cs_tau},\n                                  casadi::SXVector {ddq_dv});\n    \n    casadi::DM ddq_dv_res = eval_ddq_dv(casadi::DMVector {q_vec,v_int_vec,v_vec,tau_vec})[0];\n    std::vector<double> ddq_dv_vec(static_cast< std::vector<double> >(ddq_dv_res));\n    BOOST_CHECK(Eigen::Map<Data::MatrixXs>(ddq_dv_vec.data(),model.nv,model.nv).isApprox(ddq_dv_ref));\n    \n    // check with respect to a+da\n    casadi::SX ddq_dtau = jacobian(cs_ddq, cs_tau);\n    casadi::Function eval_ddq_da(\"eval_ddq_da\",\n                                  casadi::SXVector {cs_q,cs_v_int, cs_v, cs_tau},\n                                  casadi::SXVector {ddq_dtau});\n    \n    casadi::DM ddq_dtau_res = eval_ddq_da(casadi::DMVector {q_vec,v_int_vec,v_vec,tau_vec})[0];\n    std::vector<double> ddq_dtau_vec(static_cast< std::vector<double> >(ddq_dtau_res));\n    BOOST_CHECK(Eigen::Map<Data::MatrixXs>(ddq_dtau_vec.data(),model.nv,model.nv).isApprox(ddq_dtau_ref));\n    \n    // call ABA derivatives in Casadi\n    casadi::SX cs_ddq_dq(model.nv,model.nv);\n    casadi::SX cs_ddq_dv(model.nv,model.nv);\n    casadi::SX cs_ddq_dtau(model.nv,model.nv);\n    \n    computeABADerivatives(ad_model,ad_data,q_ad,v_ad,tau_ad);\n    ad_data.Minv.triangularView<Eigen::StrictlyLower>()\n    = ad_data.Minv.transpose().triangularView<Eigen::StrictlyLower>();\n    \n    pinocchio::casadi::copy(ad_data.ddq_dq,cs_ddq_dq);\n    pinocchio::casadi::copy(ad_data.ddq_dv,cs_ddq_dv);\n    pinocchio::casadi::copy(ad_data.Minv,cs_ddq_dtau);\n    \n    casadi::Function eval_aba_derivatives_dq(\"eval_aba_derivatives_dq\",\n                                              casadi::SXVector {cs_q, cs_v, cs_tau},\n                                              casadi::SXVector {cs_ddq_dq});\n    \n    casadi::DM ddq_dq_res_direct = eval_aba_derivatives_dq(casadi::DMVector {q_vec,v_vec,tau_vec})[0];\n    Data::MatrixXs ddq_dq_res_direct_map = Eigen::Map<Data::MatrixXs>(static_cast< std::vector<double> >(ddq_dq_res_direct).data(),model.nv,model.nv);\n    BOOST_CHECK(ddq_dq_ref.isApprox(ddq_dq_res_direct_map));\n    \n    casadi::Function eval_aba_derivatives_dv(\"eval_aba_derivatives_dv\",\n                                              casadi::SXVector {cs_q, cs_v, cs_tau},\n                                              casadi::SXVector {cs_ddq_dv});\n    \n    casadi::DM ddq_dv_res_direct = eval_aba_derivatives_dv(casadi::DMVector {q_vec,v_vec,tau_vec})[0];\n    Data::MatrixXs ddq_dv_res_direct_map = Eigen::Map<Data::MatrixXs>(static_cast< std::vector<double> >(ddq_dv_res_direct).data(),model.nv,model.nv);\n    BOOST_CHECK(ddq_dv_ref.isApprox(ddq_dv_res_direct_map));\n    \n    casadi::Function eval_aba_derivatives_dtau(\"eval_aba_derivatives_dtau\",\n                                              casadi::SXVector {cs_q, cs_v, cs_tau},\n                                              casadi::SXVector {cs_ddq_dtau});\n    \n    casadi::DM ddq_dtau_res_direct = eval_aba_derivatives_dtau(casadi::DMVector {q_vec,v_vec,tau_vec})[0];\n    Data::MatrixXs ddq_dtau_res_direct_map = Eigen::Map<Data::MatrixXs>(static_cast< std::vector<double> >(ddq_dtau_res_direct).data(),model.nv,model.nv);\n    BOOST_CHECK(ddq_dtau_ref.isApprox(ddq_dtau_res_direct_map));\n  }\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "d3d98e358a659d3f98e31f7b6b286cd00525e146", "size": 17587, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittest/casadi-algo-derivatives.cpp", "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": "unittest/casadi-algo-derivatives.cpp", "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": "unittest/casadi-algo-derivatives.cpp", "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": 45.3273195876, "max_line_length": 154, "alphanum_fraction": 0.6791379997, "num_tokens": 5323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128672997041659, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.49998480419417113}}
{"text": "/* ---------------------------------------------------------------------\n *\n * Copyright (C) 2000 - 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 *\n * Author: Wolfgang Bangerth, University of Heidelberg, 2000\n */\n\n\n\n#include <deal.II/base/quadrature_lib.h>\n#include <deal.II/base/symbolic_function.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_dgp.h>\n#include <deal.II/fe/fe_dgq.h>\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#include <deal.II/fe/fe_values_extractors.h>\n\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.h>\n\n#include <deal.II/lac/affine_constraints.h>\n#include <deal.II/lac/dynamic_sparsity_pattern.h>\n#include <deal.II/lac/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#include <deal.II/lac/sparse_matrix.h>\n#include <deal.II/lac/vector.h>\n\n#include <deal.II/numerics/data_out.h>\n#include <deal.II/numerics/error_estimator.h>\n#include <deal.II/numerics/vector_tools.h>\n\n#include <fstream>\n\nusing namespace dealii;\n\n\n\ntemplate <int dim>\nclass Step6\n{\npublic:\n  Step6();\n\n  void\n  run();\n\nprivate:\n  void\n  setup_system();\n  void\n  assemble_system();\n  void\n  solve();\n  void\n  refine_grid();\n  void\n  output_results(const unsigned int cycle) const;\n\n  Triangulation<dim> triangulation;\n\n  FE_Q<dim>     fe_velocity;\n  FE_DGP<dim>   fe_pressure;\n  FESystem<dim> fe;\n\n  FEValuesExtractors::Vector velocity;\n  FEValuesExtractors::Scalar pressure;\n\n  DoFHandler<dim> dof_handler;\n\n  AffineConstraints<double> constraints;\n\n  SparseMatrix<double> system_matrix;\n  SparsityPattern      sparsity_pattern;\n\n  Vector<double> solution;\n  Vector<double> system_rhs;\n};\n\n\n\ntemplate <int dim>\nStep6<dim>::Step6()\n  : fe_velocity(2)\n  , fe_pressure(1)\n  , fe(fe_velocity, dim, fe_pressure, 1)\n  , velocity(0)\n  , pressure(dim)\n  , dof_handler(triangulation)\n{}\n\n\n\ntemplate <int dim>\nvoid\nStep6<dim>::setup_system()\n{\n  dof_handler.distribute_dofs(fe);\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, constraints);\n\n\n  VectorTools::interpolate_boundary_values(dof_handler,\n                                           0,\n                                           Functions::ZeroFunction<dim>(dim +\n                                                                        1),\n                                           constraints,\n                                           fe.component_mask(velocity));\n\n  constraints.close();\n\n  DynamicSparsityPattern dsp(dof_handler.n_dofs());\n  DoFTools::make_sparsity_pattern(dof_handler,\n                                  dsp,\n                                  constraints,\n                                  /*keep_constrained_dofs = */ false);\n\n  sparsity_pattern.copy_from(dsp);\n\n  system_matrix.reinit(sparsity_pattern);\n}\n\n\n\ntemplate <int dim>\nvoid\nStep6<dim>::assemble_system()\n{\n  const QGauss<dim> quadrature_formula(fe.degree + 1);\n\n  FEValues<dim> fe_values(fe,\n                          quadrature_formula,\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\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  Functions::SymbolicFunction<dim> rhs_function(\n    dim == 2 ?\n      \"x^2*y^2*(x - 1)^2*(2*y - 2) + 2*x^2*y*(x - 1)^2*(y - 1)^2;-x^2*y^2*(2*x - 2)*(y - 1)^2 - 2*x*y^2*(x - 1)^2*(y - 1)^2; 0\" :\n      \"x^2*y^2*(x - 1)^2*(2*y - 2) + 2*x^2*y*(x - 1)^2*(y - 1)^2;-x^2*y^2*(2*x - 2)*(y - 1)^2 - 2*x*y^2*(x - 1)^2*(y - 1)^2; 0; 0\");\n\n  Vector<double> rhs_values(dim + 1);\n  for (const auto &cell : dof_handler.active_cell_iterators())\n    {\n      cell_matrix = 0;\n      cell_rhs    = 0;\n\n      fe_values.reinit(cell);\n\n      for (const unsigned int q_index : fe_values.quadrature_point_indices())\n        {\n          rhs_function.vector_value(fe_values.quadrature_point(q_index),\n                                    rhs_values);\n          for (const unsigned int i : fe_values.dof_indices())\n            {\n              auto v      = fe_values[velocity].value(i, q_index);\n              auto div_v  = fe_values[velocity].divergence(i, q_index);\n              auto grad_v = fe_values[velocity].gradient(i, q_index);\n              auto q      = fe_values[pressure].value(i, q_index);\n\n              for (const unsigned int j : fe_values.dof_indices())\n                {\n                  auto div_u  = fe_values[velocity].divergence(j, q_index);\n                  auto grad_u = fe_values[velocity].gradient(j, q_index);\n                  auto p      = fe_values[pressure].value(j, q_index);\n\n                  cell_matrix(i, j) +=\n                    (scalar_product(grad_u, grad_v) - div_v * p - div_u * q) *\n                    fe_values.JxW(q_index); // dx\n                }\n              for (unsigned int d = 0; d < dim; ++d)\n                cell_rhs(i) += (1000 * rhs_values[d] *   // f(x)\n                                v[d] *                   // phi_i(x_q)\n                                fe_values.JxW(q_index)); // dx\n            }\n        }\n\n      cell->get_dof_indices(local_dof_indices);\n      constraints.distribute_local_to_global(\n        cell_matrix, cell_rhs, local_dof_indices, system_matrix, system_rhs);\n    }\n}\n\n\n\ntemplate <int dim>\nvoid\nStep6<dim>::solve()\n{\n  SparseDirectUMFPACK inverse;\n  inverse.initialize(system_matrix);\n\n  // SolverControl            solver_control(1000, 1e-12);\n  // SolverCG<Vector<double>> solver(solver_control);\n\n  // PreconditionSSOR<SparseMatrix<double>> preconditioner;\n  // preconditioner.initialize(system_matrix, 1.2);\n\n  // solver.solve(system_matrix, solution, system_rhs, preconditioner);\n\n  inverse.vmult(solution, system_rhs);\n  constraints.distribute(solution);\n}\n\n\n\ntemplate <int dim>\nvoid\nStep6<dim>::refine_grid()\n{\n  Vector<float> estimated_error_per_cell(triangulation.n_active_cells());\n\n  KellyErrorEstimator<dim>::estimate(dof_handler,\n                                     QGauss<dim - 1>(fe.degree + 1),\n                                     {},\n                                     solution,\n                                     estimated_error_per_cell,\n                                     fe.component_mask(velocity));\n\n  GridRefinement::refine_and_coarsen_fixed_number(triangulation,\n                                                  estimated_error_per_cell,\n                                                  0.3,\n                                                  0.03);\n\n  triangulation.execute_coarsening_and_refinement();\n}\n\n\n\ntemplate <int dim>\nvoid\nStep6<dim>::output_results(const unsigned int cycle) const\n{\n  {\n    std::vector<std::string> solution_names(dim, \"velocity\");\n    solution_names.emplace_back(\"pressure\");\n    DataOutBase::VtkFlags flags;\n    flags.write_higher_order_cells = true;\n\n    std::vector<DataComponentInterpretation::DataComponentInterpretation>\n      data_component_interpretation(\n        dim, DataComponentInterpretation::component_is_part_of_vector);\n\n    data_component_interpretation.push_back(\n      DataComponentInterpretation::component_is_scalar);\n    DataOut<dim> data_out;\n    data_out.set_flags(flags);\n\n    data_out.attach_dof_handler(dof_handler);\n    data_out.add_data_vector(solution,\n                             solution_names,\n                             DataOut<dim>::type_dof_data,\n                             data_component_interpretation);\n    data_out.build_patches(fe.degree);\n\n    std::ofstream output(\"solution-\" + std::to_string(cycle) + \".vtu\");\n    data_out.write_vtu(output);\n  }\n}\n\n\n\ntemplate <int dim>\nvoid\nStep6<dim>::run()\n{\n  for (unsigned int cycle = 0; cycle < 4; ++cycle)\n    {\n      std::cout << \"Cycle \" << cycle << ':' << std::endl;\n\n      if (cycle == 0)\n        {\n          GridGenerator::hyper_cube(triangulation);\n          triangulation.refine_global(4);\n        }\n      else\n        refine_grid();\n\n\n      std::cout << \"   Number of active cells:       \"\n                << triangulation.n_active_cells() << std::endl;\n\n      setup_system();\n\n      std::cout << \"   Number of degrees of freedom: \" << dof_handler.n_dofs()\n                << std::endl;\n\n      assemble_system();\n      solve();\n      output_results(cycle);\n    }\n}\n\n\n\nint\nmain()\n{\n  try\n    {\n      Step6<2> laplace_problem_2d;\n      laplace_problem_2d.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  return 0;\n}\n", "meta": {"hexsha": "ecfd2481fd8d7d720fd9dfcef79d86e839a33d3b", "size": 10114, "ext": "cc", "lang": "C++", "max_stars_repo_path": "cpp/08_saddle_point_problems/stokes.cc", "max_stars_repo_name": "luca-heltai/advanced-fem", "max_stars_repo_head_hexsha": "7dc5416db07ee67410819e4f9680471548c6641a", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-03-13T22:07:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-12T07:59:37.000Z", "max_issues_repo_path": "cpp/08_saddle_point_problems/stokes.cc", "max_issues_repo_name": "luca-heltai/advanced-fem", "max_issues_repo_head_hexsha": "7dc5416db07ee67410819e4f9680471548c6641a", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp/08_saddle_point_problems/stokes.cc", "max_forks_repo_name": "luca-heltai/advanced-fem", "max_forks_repo_head_hexsha": "7dc5416db07ee67410819e4f9680471548c6641a", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8622589532, "max_line_length": 132, "alphanum_fraction": 0.5625865137, "num_tokens": 2403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4999430241191715}}
{"text": " #include <boost/spirit.hpp>\n #include <boost/spirit/tree/ast.hpp>\n #include <string>\n #include <cassert>\n #include <iostream>\n #include <istream>\n #include <ostream>\n\n using boost::spirit::rule;\n using boost::spirit::parser_tag;\n using boost::spirit::ch_p;\n using boost::spirit::real_p;\n\n using boost::spirit::tree_node;\n using boost::spirit::node_val_data;\n\n // The grammar\n struct parser: public boost::spirit::grammar<parser>\n {\n   enum rule_ids { addsub_id, multdiv_id, value_id, real_id };\n\n   struct set_value\n   {\n     set_value(parser const& p): self(p) {}\n     void operator()(tree_node<node_val_data<std::string::iterator,\n                                             double> >& node,\n                     std::string::iterator begin,\n                     std::string::iterator end) const\n     {\n       node.value.value(self.tmp);\n     }\n     parser const& self;\n   };\n\n   mutable double tmp;\n\n   template<typename Scanner> struct definition\n   {\n     rule<Scanner, parser_tag<addsub_id> > addsub;\n     rule<Scanner, parser_tag<multdiv_id> > multdiv;\n     rule<Scanner, parser_tag<value_id> > value;\n     rule<Scanner, parser_tag<real_id> > real;\n\n     definition(parser const& self)\n     {\n       using namespace boost::spirit;\n       addsub = multdiv\n         >> *((root_node_d[ch_p('+')] | root_node_d[ch_p('-')]) >> multdiv);\n       multdiv = value\n         >> *((root_node_d[ch_p('*')] | root_node_d[ch_p('/')]) >> value);\n       value = real | inner_node_d[('(' >> addsub >> ')')];\n       real = leaf_node_d[access_node_d[real_p[assign_a(self.tmp)]][set_value(self)]];\n     }\n\n     rule<Scanner, parser_tag<addsub_id> > const& start() const\n     {\n       return addsub;\n     }\n   };\n };\n\n template<typename TreeIter>\n double evaluate(TreeIter const& i)\n {\n   double op1, op2;\n   switch (i->value.id().to_long())\n   {\n   case parser::real_id:\n     return i->value.value();\n   case parser::value_id:\n   case parser::addsub_id:\n   case parser::multdiv_id:\n     op1 = evaluate(i->children.begin());\n     op2 = evaluate(i->children.begin()+1);\n     switch(*i->value.begin())\n     {\n     case '+':\n       return op1 + op2;\n     case '-':\n       return op1 - op2;\n     case '*':\n       return op1 * op2;\n     case '/':\n       return op1 / op2;\n     default:\n       assert(!\"Should not happen\");\n     }\n   default:\n     assert(!\"Should not happen\");\n   }\n   return 0;\n }\n\n // the read/eval/write loop\n int main()\n {\n   parser eval;\n   std::string line;\n   while (std::cout << \"Expression: \"\n          && std::getline(std::cin, line)\n          && !line.empty())\n   {\n     typedef boost::spirit::node_val_data_factory<double> factory_t;\n     boost::spirit::tree_parse_info<std::string::iterator, factory_t> info =\n       boost::spirit::ast_parse<factory_t>(line.begin(), line.end(),\n                                           eval, boost::spirit::space_p);\n     if (info.full)\n     {\n       std::cout << \"Result: \" << evaluate(info.trees.begin()) << std::endl;\n     }\n     else\n     {\n       std::cout << \"Error in expression.\" << std::endl;\n     }\n   }\n };\n", "meta": {"hexsha": "6293355eda2e103c76cedbef8359592a87e0dad0", "size": 3065, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lang/C++/arithmetic-evaluation.cpp", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-11-09T22:08:38.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-09T22:08:38.000Z", "max_issues_repo_path": "lang/C++/arithmetic-evaluation.cpp", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/C++/arithmetic-evaluation.cpp", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-11-09T22:08:40.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-09T22:08:40.000Z", "avg_line_length": 26.1965811966, "max_line_length": 86, "alphanum_fraction": 0.5768352365, "num_tokens": 782, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.4999430241191714}}
{"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\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include <boost/timer.hpp>\n#include <iostream>\n#include <list>\n\n#include <boost/numeric/linear_algebra/accumulate.hpp>\n#include <boost/numeric/linear_algebra/concept_maps.hpp>\n#include <boost/numeric/linear_algebra/operators.hpp>\n\n\ntemplate <typename Element>\nvoid test_accumulate(const char* name)\n{\n    const int   array_size= 10;\n    Element     array[array_size];\n    for (int i= 0; i < array_size; i++) \n    \tarray[i]= Element(i);\n\n    std::list<Element> l;\n    for (int i= 0; i < array_size; i++) \n    \tl.push_back(Element(i));\n    \n    std::cout << '\\n' << name << '\\n' << \" Add: \";\n    math::accumulate(&array[0], array+array_size, Element(0), math::add<Element>());\n    std::cout << \"Mult: \";\n    math::accumulate(array, array+array_size, Element(1), math::mult<Element>());\n    std::cout << \"Mult [with a list]: \";\n    math::accumulate(l.begin(), l.end(), Element(1), math::mult<Element>());\n    std::cout << \" Min: \";\n    math::accumulate(array, array+array_size, Element(1000), math::min<Element>());\n    std::cout << \" Max: \";\n    math::accumulate(array, array+array_size, Element(-1000), math::max<Element>());\n}\n\n\nint main(int, char* [])\n{\n    test_accumulate<int>(\"int\");\n    test_accumulate<float>(\"float\");\n    test_accumulate<double>(\"double\");\n    std::cout << '\\n';\n\n    return 0;\n}\n", "meta": {"hexsha": "0e30a4af0e573340d9a0f3c4cf5673ce56032711", "size": 1748, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/linear_algebra/test/accumulation_simple.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/linear_algebra/test/accumulation_simple.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/linear_algebra/test/accumulation_simple.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": 31.2142857143, "max_line_length": 94, "alphanum_fraction": 0.6458810069, "num_tokens": 461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.6926419894793248, "lm_q1q2_score": 0.49990965030315493}}
{"text": "// Copyright (c) 2020 Sabar Nimmagadda. All rights reserved.\n\n#include \"matrix_app.h\"\n\n#include <cinder/app/App.h>\n#include <Eigen/Dense>\n#include <cinder/gl/gl.h>\n#include <cinder/Font.h>\n#include <cinder/Text.h>\n#include <cinder/Vector.h>\n#include <cinder/gl/draw.h>\n#include <Linear Algebra/computations.h>\n#include <iostream>\n#include <utility>\n#include \"CinderImGui.h\"\nusing Eigen::MatrixXd;\nnamespace matrixapp {\nusing cinder::app::KeyEvent;\nusing cinder::Color;\nusing cinder::ColorA;\nusing cinder::Rectf;\nusing cinder::TextBox;\nusing std::string;\nconst char kNormalFont[] = \"Arial\";\n\nMatrixApp::MatrixApp()\n    : state_{AppState::kSelecting} {}\n\n\nvoid MatrixApp::setup() {\n    ui::initialize();\n    test_mat << 1, 2, 3,\n            4, 5, 6,\n            7, 8, 9;\n}\n\nvoid MatrixApp::update() {\n    if (state_ == AppState::kInputtingData) {\n        InputMatrix();\n        String_To_Matrix();\n    }\n}\n\nvoid MatrixApp::draw() {\n    DrawBackground();\n    const cinder::vec2 center = getWindowCenter();\n    const cinder::ivec2 size = {500, 50};\n    const Color color = Color::white();\n    if (state_ == AppState::kSelecting) {\n        PrintText(\"WELCOME\", color, size, {100, 50});\n        CreateMenu();\n    }\n    if (state_ == AppState::kSolved) {\n        DrawAnswer();\n    }\n}\n\n\nvoid MatrixApp::CreateMenu() {\n    ui::ScopedWindow window( \"Choose problem\", ImGuiWindowFlags_MenuBar );\n    if( ui::BeginMenuBar() ){\n        if( ui::BeginMenu( \"Problem Type\" )) {\n            if (ui::MenuItem( \"RREF\" )) {\n                problemType = ProblemType::RREF;\n                state_= AppState::kInputtingData;\n            }\n            if (ui::MenuItem( \"Row Space\" )) {\n                problemType = ProblemType::RowSpace;\n                state_= AppState::kInputtingData;\n            }\n            if (ui::MenuItem( \"Column Space\")) {\n                problemType = ProblemType::ColumnSpace;\n                state_= AppState::kInputtingData;\n            }\n            if (ui::MenuItem(\"LU Decomposition\")) {\n                problemType = ProblemType::LUDecomposition;\n                state_= AppState::kInputtingData;\n            }\n            if (ui::MenuItem( \"Permutation Matrix\")) {\n                problemType = ProblemType::PermutationMatrix;\n                state_= AppState::kInputtingData;\n            }\n            if (ui::MenuItem( \"Inverse\")) {\n                problemType = ProblemType::Inverse;\n                state_= AppState::kInputtingData;\n            }\n            if (ui::MenuItem( \"Matrix Multiplication\")) {\n                problemType = ProblemType::MatrixMultiplication;\n                state_ = AppState::kInputtingData;\n            }\n            if (ui::MenuItem(\"QR Decomposition\")) {\n                problemType = ProblemType::QRDecomposition;\n                state_ = AppState::kInputtingData;\n            }\n            if (ui::MenuItem(\"Dot Product\")) {\n                problemType = ProblemType::DotProduct;\n                state_ = AppState::kInputtingData;\n            }\n            if (ui::MenuItem(\"Eigen Vectors\")) {\n                problemType = ProblemType::EigenVectors;\n                state_ = AppState::kInputtingData;\n            }\n            if (ui::MenuItem(\"Eigen Values\")) {\n                problemType = ProblemType::EigenValues;\n                state_ = AppState::kInputtingData;\n            }\n            if (ui::MenuItem(\"Determinant\")) {\n                problemType = ProblemType::Determinant;\n                state_ = AppState::kInputtingData;\n            }\n            ui::EndMenu();\n        }\n        ui::EndMenuBar();\n    }\n    const ImVec2 vec2(500, 500);\n    ui::SetWindowSize(\"Choose problem\", vec2);\n}\n\n\nvoid MatrixApp::DrawAnswer() {\n    if (problemType == ProblemType::QRDecomposition) {\n        DrawQRAnswer(in_mat1);\n    }\n    if (problemType == ProblemType::LUDecomposition) {\n        DrawLUAnswer(in_mat1);\n    }\n    if (problemType == ProblemType::PermutationMatrix) {\n        DrawPermutationAnswer(in_mat1);\n    }\n    if (problemType == ProblemType::RREF) {\n        DrawRREFAnswer(in_mat1);\n    }\n    if (problemType == ProblemType::EigenValues) {\n        DrawEigenValuesAnswer(in_mat1);\n    }\n    if (problemType == ProblemType::Inverse) {\n        DrawInverseAnswer(in_mat1);\n    }\n    if (problemType == ProblemType::EigenVectors) {\n        DrawEigenVectorsAnswer(in_mat1);\n    }\n    if (problemType == ProblemType::DotProduct) {\n        DrawDotProductAnswer(in_mat1, in_mat2);\n    }\n    if (problemType == ProblemType::MatrixMultiplication) {\n        DrawMultiplicationAnswer(in_mat1, in_mat2);\n    }\n    if (problemType == ProblemType::Determinant) {\n        DrawDeterminantAnswer(in_mat1);\n    }\n    if (problemType == ProblemType::RowSpace) {\n        DrawRowSpaceAnswer(in_mat1);\n    }\n    if (problemType == ProblemType::ColumnSpace) {\n        DrawColSpaceAnswer(in_mat1);\n    }\n}\n\n\nvoid MatrixApp::keyDown(KeyEvent event) {\n}\n\nvoid MatrixApp::PrintText(const string& text, const Color color, const cinder::ivec2& size,\n               const cinder::vec2& loc) {\n    cinder::gl::color(color);\n    auto box = TextBox()\n            .alignment(TextBox::CENTER)\n            .font(cinder::Font(kNormalFont, 30))\n            .size(size)\n            .color(color)\n            .backgroundColor(ColorA(0, 0, 1, 0))\n            .text(text);\n\n    const auto box_size = box.getSize();\n    const cinder::vec2 locp = {loc.x - box_size.x / 2, loc.y - box_size.y / 2};\n    const auto surface = box.render();\n    const auto texture = cinder::gl::Texture::create(surface);\n    cinder::gl::draw(texture, locp);\n}\nvoid MatrixApp::DrawBackground() const {\n    cinder::gl::clear(Color(0, 0, 0));\n}\nvoid MatrixApp::DrawLUAnswer(const MatrixXd& matrix) {\n    const cinder::vec2 center = getWindowCenter();\n    const cinder::ivec2 size = {500, 500};\n    const Color color = Color::white();\n    std::stringstream ss;\n    ss << Computations::ComputeL(matrix);\n    PrintText(\"Your L Matrix is\",color,{500,500},{center.x-50,center.y - 50});\n    PrintText(ss.str(), color, size , center);\n    std::stringstream st;\n    st << Computations::ComputeU(matrix);\n    PrintText(\"Your U Matrix is\",color,{500,500},{center.x-50,center.y + 150});\n    PrintText(st.str(), color, size, {center.x, center.y + 200});\n    BackToMenu();\n}\n\nvoid MatrixApp::DrawDotProductAnswer(MatrixXd matrix1, MatrixXd matrix2) {\n    const cinder::vec2 center = getWindowCenter();\n    const cinder::ivec2 size = {500, 500};\n    const Color color = Color::white();\n    std::stringstream ss;\n    ss << Computations::ComputeDotProduct(std::move(matrix1), std::move(matrix2), kDimension);\n    PrintText(\"Your Dot Product is\", color, {500,500},{center.x-50,center.y - 50});\n    PrintText(ss.str(), color, size, center);\n    BackToMenu();\n}\n\nvoid MatrixApp::DrawPermutationAnswer(MatrixXd matrix) {\n    const cinder::vec2 center = getWindowCenter();\n    const cinder::ivec2 size = {500, 500};\n    const Color color = Color::white();\n    std::stringstream ss;\n    ss << Computations::ComputePermutationMatrix(std::move(matrix));\n    PrintText(\"Your Permutation Matrix is\",color,{500,500},{center.x-50,center.y - 50});\n    PrintText(ss.str(), color, size , center);\n    BackToMenu();\n}\n\nvoid MatrixApp::DrawRREFAnswer(const MatrixXd& matrix) {\n    const cinder::vec2 center = getWindowCenter();\n    const cinder::ivec2 size = {500, 500};\n    const Color color = Color::white();\n    std::stringstream ss;\n    ss << Computations::ComputeRREF(matrix);\n    PrintText(\"Your Row Reduced Matrix is\",color,{500,500},{center.x-50,center.y - 50});\n    PrintText(ss.str(), color, size , center);\n    BackToMenu();\n}\n\nvoid MatrixApp::DrawMultiplicationAnswer(MatrixXd matrix1, MatrixXd matrix2) {\n    const cinder::vec2 center = getWindowCenter();\n    const cinder::ivec2 size = {500, 500};\n    const Color color = Color::white();\n    std::stringstream ss;\n    ss << Computations::ComputeMultiply(std::move(matrix1), std::move(matrix2));\n    PrintText(\"The product Matrix is\",color,{500,500},{center.x-50,center.y - 50});\n    PrintText(ss.str(), color, size , center);\n    BackToMenu();\n}\n\nvoid MatrixApp::DrawInverseAnswer(const MatrixXd& matrix) {\n    const cinder::vec2 center = getWindowCenter();\n    const cinder::ivec2 size = {500, 500};\n    const Color color = Color::white();\n    std::stringstream ss;\n    ss << Computations::ComputeInverse(matrix);\n    PrintText(\"The Inverse Matrix is\",color,{500,500},{center.x-50,center.y - 50});\n    PrintText(ss.str(), color, size , center);\n    BackToMenu();\n}\n\nvoid MatrixApp::DrawQRAnswer(const MatrixXd& matrix) {\n    const cinder::vec2 center = getWindowCenter();\n    const cinder::ivec2 size = {500, 500};\n    const Color color = Color::white();\n    std::stringstream ss;\n    ss << Computations::ComputeQ(matrix);\n    PrintText(\"Your Q Matrix is\",color,{500,500},{center.x-50,center.y - 50});\n    PrintText(ss.str(), color, size , center);\n    std::stringstream st;\n    st << Computations::ComputeR(matrix);\n    PrintText(\"Your R Matrix is\",color,{500,500},{center.x-50,center.y + 150});\n    PrintText(st.str(), color, size, {center.x, center.y + 200});\n    BackToMenu();\n}\n\nvoid MatrixApp::DrawEigenVectorsAnswer(MatrixXd matrix) {\n    const cinder::vec2 center = getWindowCenter();\n    const cinder::ivec2 size = {500, 500};\n    const Color color = Color::white();\n    std::stringstream ss;\n    ss << Computations::ComputeEigenVectors(matrix);\n    PrintText(\"The Matrix of EigenVectors is\",color,{500,500},{center.x-50,center.y - 50});\n    PrintText(ss.str(), color, size , center);\n    BackToMenu();\n}\n\nvoid MatrixApp::DrawEigenValuesAnswer(MatrixXd matrix) {\n    const cinder::vec2 center = getWindowCenter();\n    const cinder::ivec2 size = {500, 500};\n    const Color color = Color::white();\n    std::stringstream ss;\n    ss << Computations::ComputeEigenValues(matrix);\n    PrintText(\"The Eigenvalues are\",color,{500,500},{center.x-50,center.y - 50});\n    PrintText(ss.str(), color, size , center);\n    BackToMenu();\n}\n\nvoid MatrixApp::DrawDeterminantAnswer(const MatrixXd& matrix) {\n    const cinder::vec2 center = getWindowCenter();\n    const cinder::ivec2 size = {500, 500};\n    const Color color = Color::white();\n    std::stringstream ss;\n    ss << Computations::ComputeDeterminant(matrix);\n    PrintText(\"Your determinant is\", color, {500,500},{center.x-50,center.y - 50});\n    PrintText(ss.str(), color, size, center);\n    BackToMenu();\n}\n\nvoid MatrixApp::DrawColSpaceAnswer(const MatrixXd& matrix) {\n    const cinder::vec2 center = getWindowCenter();\n    const cinder::ivec2 size = {500, 500};\n    const Color color = Color::white();\n    std::stringstream ss;\n    ss << Computations::ComputeEigenVectors(matrix.inverse());\n    PrintText(\"Your Column Space Matrix is\", color, {500,500},{center.x-50,center.y - 50});\n    PrintText(ss.str(), color, size, center);\n    BackToMenu();\n}\n\nvoid MatrixApp::DrawRowSpaceAnswer(const MatrixXd& matrix) {\n    const cinder::vec2 center = getWindowCenter();\n    const cinder::ivec2 size = {500, 500};\n    const Color color = Color::white();\n    std::stringstream ss;\n    ss << Computations::ComputeEigenVectors(matrix);\n    PrintText(\"Your Row Space Matrix is\", color, {500,500},{center.x-50,center.y - 50});\n    PrintText(ss.str(), color, size, center);\n    BackToMenu();\n}\n\nvoid MatrixApp::InputMatrix() {\n    if (problemType != ProblemType::DotProduct && problemType != ProblemType::MatrixMultiplication) {\n        ui::InputInt(\"Enter dimension\",  &kDimension);\n        ui::InputText(\"Input matrix\", &input_string);\n    } else {\n        ui::InputInt(\"Enter dimension\",  &kDimension);\n        ui::InputText(\"Input first matrix\", &input_string);\n        ui::InputText(\"Input second matrix\", &input_string2);\n        str_mat2 = input_string2;\n    }\n    str_mat = input_string;\n}\n\n\nvoid MatrixApp::String_To_Matrix() {\n    int mat_size = kDimension *kDimension;\n    if ( problemType != ProblemType::DotProduct\n     && problemType != ProblemType::MatrixMultiplication\n     && str_mat.size() == mat_size * 2 && mat_size != 0) { // <= size * 2\n        //When the computation only needs one matrix.\n        std::istringstream ss(str_mat);\n        for (int r = 0; r < kDimension; r++) {\n            for (int c = 0; c < kDimension; c++) {\n                int elem;\n                ss >> elem;\n                in_mat1(r, c) = elem;\n            }\n        }\n        state_ = AppState::kSolved;\n    } else if (str_mat.size() == mat_size * 2 && str_mat2.size() == mat_size * 2 && mat_size != 0){\n        //Made else if instead of else, because size cannot be zero ever.\n        std::istringstream ss1(str_mat);\n        std::istringstream ss2(str_mat2);\n        for (int r = 0; r < kDimension; r++) {\n            for (int c = 0; c < kDimension; c++) {\n                int elem1;\n                int elem2;\n                ss1 >> elem1;\n                ss2 >> elem2;\n                in_mat1(r, c) = elem1;\n                in_mat2(r, c) = elem2;\n            }\n        }\n        state_ = AppState::kSolved;\n    }\n}\n\nvoid MatrixApp::BackToMenu() {\n    const cinder::ivec2 button_size = {500, 50};\n    if (ui::Button(\"BACK TO MAIN MENU\", button_size)) {\n        state_ = AppState::kSelecting;\n        input_string = \"\";\n        input_string2 = \"\";\n        kDimension = 0;\n    }\n}\n\n\n}  // namespace myapp\n", "meta": {"hexsha": "8ff19c59250e095040efa88d5b0e0bc3d2ad92fa", "size": 13278, "ext": "cc", "lang": "C++", "max_stars_repo_path": "apps/matrix_app.cc", "max_stars_repo_name": "CS126SP20/Matrix-Machine-LinAlgComputer-SabarNimmagadda", "max_stars_repo_head_hexsha": "928af6c373363eabc7edadf63f3e3a7220d864f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "apps/matrix_app.cc", "max_issues_repo_name": "CS126SP20/Matrix-Machine-LinAlgComputer-SabarNimmagadda", "max_issues_repo_head_hexsha": "928af6c373363eabc7edadf63f3e3a7220d864f1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "apps/matrix_app.cc", "max_forks_repo_name": "CS126SP20/Matrix-Machine-LinAlgComputer-SabarNimmagadda", "max_forks_repo_head_hexsha": "928af6c373363eabc7edadf63f3e3a7220d864f1", "max_forks_repo_licenses": ["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.7591623037, "max_line_length": 101, "alphanum_fraction": 0.6140231963, "num_tokens": 3424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.7217431943271999, "lm_q1q2_score": 0.499909637432791}}
{"text": "//\n// OpenTissue, A toolbox for physical based simulation and animation.\n// Copyright (C) 2007 Department of Computer Science, University of Copenhagen\n//\n#include <OpenTissue/configuration.h>\n\n#include <OpenTissue/core/math/math_basic_types.h>\n#include <OpenTissue/core/geometry/geometry_plane_box.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <OpenTissue/utility/utility_push_boost_filter.h>\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n#include <OpenTissue/utility/utility_pop_boost_filter.h>\n\nBOOST_AUTO_TEST_SUITE(opentissue_geometry_util_plane_box);\n\nBOOST_AUTO_TEST_CASE(case_by_case_testing)\n{\n\n  typedef OpenTissue::math::BasicMathTypes<double, size_t> math_types;\n  typedef math_types::vector3_type                         vector3_type;\n  typedef math_types::real_type                            real_type;\n\n  typedef OpenTissue::geometry::PlaneBox<math_types>  plane_box_type;  \n  plane_box_type plane_box;\n\n  real_type tol = 0.0001;\n\n  vector3_type min_coord(0,0,0);\n  vector3_type max_coord(1,1,1);\n\n  plane_box.init(min_coord,max_coord);\n  BOOST_CHECK( plane_box.box().min().is_equal( min_coord, tol ) );\n  BOOST_CHECK( plane_box.box().max().is_equal( max_coord, tol ) );\n\n  BOOST_CHECK( plane_box.n() == vector3_type(1,0,0) );\n  BOOST_CHECK( plane_box.plane().n() == vector3_type(1,0,0) );\n\n  plane_box.set_y_axis();\n  BOOST_CHECK( plane_box.n() == vector3_type(0,1,0) );\n  BOOST_CHECK( plane_box.plane().n() == vector3_type(0,1,0) );\n\n  plane_box.set_z_axis();\n  BOOST_CHECK( plane_box.n() == vector3_type(0,0,1) );\n  BOOST_CHECK( plane_box.plane().n() == vector3_type(0,0,1) );\n\n  plane_box.set_x_axis();\n  BOOST_CHECK( plane_box.n() == vector3_type(1,0,0) );\n  BOOST_CHECK( plane_box.plane().n() == vector3_type(1,0,0) );\n\n  real_type w1 = plane_box.plane().w();\n  plane_box.decrement();\n  real_type w2 = plane_box.plane().w();\n  BOOST_CHECK( w2 < w1 );\n  plane_box.increment();\n  real_type w3 = plane_box.plane().w();\n  BOOST_CHECK( w3 > w2 );\n\n  plane_box.set_x_axis();\n  for(size_t i=0;i<500;++i)\n  {\n    plane_box.increment();\n    BOOST_CHECK( plane_box.p0() <= max_coord );\n    BOOST_CHECK( plane_box.p0() >= min_coord );\n    BOOST_CHECK( plane_box.p1() <= max_coord );\n    BOOST_CHECK( plane_box.p1() >= min_coord );\n    BOOST_CHECK( plane_box.p2() <= max_coord );\n    BOOST_CHECK( plane_box.p2() >= min_coord );\n    BOOST_CHECK( plane_box.p3() <= max_coord );\n    BOOST_CHECK( plane_box.p3() >= min_coord );\n  }\n\n  plane_box.set_y_axis();\n  for(size_t i=0;i<500;++i)\n  {\n    plane_box.increment();\n    BOOST_CHECK( plane_box.p0() <= max_coord );\n    BOOST_CHECK( plane_box.p0() >= min_coord );\n    BOOST_CHECK( plane_box.p1() <= max_coord );\n    BOOST_CHECK( plane_box.p1() >= min_coord );\n    BOOST_CHECK( plane_box.p2() <= max_coord );\n    BOOST_CHECK( plane_box.p2() >= min_coord );\n    BOOST_CHECK( plane_box.p3() <= max_coord );\n    BOOST_CHECK( plane_box.p3() >= min_coord );\n  }\n\n  plane_box.set_z_axis();\n  for(size_t i=0;i<500;++i)\n  {\n    plane_box.increment();\n    BOOST_CHECK( plane_box.p0() <= max_coord );\n    BOOST_CHECK( plane_box.p0() >= min_coord );\n    BOOST_CHECK( plane_box.p1() <= max_coord );\n    BOOST_CHECK( plane_box.p1() >= min_coord );\n    BOOST_CHECK( plane_box.p2() <= max_coord );\n    BOOST_CHECK( plane_box.p2() >= min_coord );\n    BOOST_CHECK( plane_box.p3() <= max_coord );\n    BOOST_CHECK( plane_box.p3() >= min_coord );\n  }\n\n\n  plane_box.set_x_axis();\n  for(size_t i=0;i<500;++i)\n  {\n    plane_box.decrement();\n    BOOST_CHECK( plane_box.p0() <= max_coord );\n    BOOST_CHECK( plane_box.p0() >= min_coord );\n    BOOST_CHECK( plane_box.p1() <= max_coord );\n    BOOST_CHECK( plane_box.p1() >= min_coord );\n    BOOST_CHECK( plane_box.p2() <= max_coord );\n    BOOST_CHECK( plane_box.p2() >= min_coord );\n    BOOST_CHECK( plane_box.p3() <= max_coord );\n    BOOST_CHECK( plane_box.p3() >= min_coord );\n  }\n\n  plane_box.set_y_axis();\n  for(size_t i=0;i<500;++i)\n  {\n    plane_box.decrement();\n    BOOST_CHECK( plane_box.p0() <= max_coord );\n    BOOST_CHECK( plane_box.p0() >= min_coord );\n    BOOST_CHECK( plane_box.p1() <= max_coord );\n    BOOST_CHECK( plane_box.p1() >= min_coord );\n    BOOST_CHECK( plane_box.p2() <= max_coord );\n    BOOST_CHECK( plane_box.p2() >= min_coord );\n    BOOST_CHECK( plane_box.p3() <= max_coord );\n    BOOST_CHECK( plane_box.p3() >= min_coord );\n  }\n\n  plane_box.set_z_axis();\n  for(size_t i=0;i<500;++i)\n  {\n    plane_box.decrement();\n    BOOST_CHECK( plane_box.p0() <= max_coord );\n    BOOST_CHECK( plane_box.p0() >= min_coord );\n    BOOST_CHECK( plane_box.p1() <= max_coord );\n    BOOST_CHECK( plane_box.p1() >= min_coord );\n    BOOST_CHECK( plane_box.p2() <= max_coord );\n    BOOST_CHECK( plane_box.p2() >= min_coord );\n    BOOST_CHECK( plane_box.p3() <= max_coord );\n    BOOST_CHECK( plane_box.p3() >= min_coord );\n  }\n\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "0cf33d1f4773d8565dc53bc0269a998098bacd8f", "size": 4964, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/core/geometry/plane_box/src/unit_plane_box.cpp", "max_stars_repo_name": "ricortiz/OpenTissue", "max_stars_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 76.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:45:06.000Z", "max_issues_repo_path": "unit_tests/core/geometry/plane_box/src/unit_plane_box.cpp", "max_issues_repo_name": "ricortiz/OpenTissue", "max_issues_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2018-11-20T14:32:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T15:26:45.000Z", "max_forks_repo_path": "unit_tests/core/geometry/plane_box/src/unit_plane_box.cpp", "max_forks_repo_name": "ricortiz/OpenTissue", "max_forks_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2018-02-21T01:45:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T07:06:49.000Z", "avg_line_length": 33.0933333333, "max_line_length": 78, "alphanum_fraction": 0.6730459307, "num_tokens": 1380, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834649, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.49985030200527825}}
{"text": "#include <cstdlib>\n#include <iostream>\n#define BOOST_UBLAS_NO_ELEMENT_PROXIES\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/triangular.hpp>\n#include <boost/numeric/bindings/ublas/vector.hpp>\n#include <boost/numeric/bindings/ublas/matrix.hpp>\n#include <boost/numeric/bindings/ublas/triangular.hpp>\n#include <boost/numeric/bindings/blas/level2.hpp>\n#include \"print.hpp\"\n#include \"random.hpp\"\n\nnamespace ublas=boost::numeric::ublas;\nnamespace blas=boost::numeric::bindings::blas;\n\nint main(int argc, char *argv[]) {\n  {\n    typedef ublas::vector<double> vector;\n    typedef ublas::matrix<double, ublas::column_major> matrix;\n    typedef ublas::triangular_matrix<double, ublas::lower, ublas::column_major> matrix_l;\n    typedef ublas::triangular_matrix<double, ublas::upper, ublas::column_major> matrix_u;\n    typedef typename vector::size_type size_type;\n    rand_normal<double>::reset();\n    size_type n=8;\n    matrix_l A_l(n, n);\n    matrix_u A_u(n, n);\n    for (size_type j=0; j<n; ++j) {\n      A_u(j, j)=rand_normal<double>::get();\n      A_l(j, j)=A_u(j, j);\n      for (size_type i=0; i<j; ++i) {\n        A_u(i, j)=rand_normal<double>::get();\n        A_l(j, i)=A_u(i, j);\n      }\n    }\n    vector x(n);\n    for (size_type i=0; i<n; ++i)\n      x(i)=rand_normal<double>::get();\n    vector y(n);\n    for (size_type i=0; i<n; ++i)\n      y(i)=rand_normal<double>::get();\n    double alpha(rand_normal<double>::get());\n    matrix P;\n    {\n      P=ublas::outer_prod(alpha*x, y);\n      P+=ublas::outer_prod(y, alpha*x);\n      for (size_type j=0; j<n; ++j)\n        for (size_type i=0; i<j; ++i)\n          P(i, j)=0;\n      matrix A1(P+A_l);\n      matrix_l A2(A_l);\n      blas::spr2(alpha, x, y, A2);\n      std::cout << print_mat(A1) << '\\n'\n                << print_mat(A2) << '\\n';\n    }\n    {\n      P=ublas::outer_prod(alpha*x, y);\n      P+=ublas::outer_prod(y, alpha*x);\n      for (size_type j=0; j<n; ++j)\n        for (size_type i=j+1; i<n; ++i)\n          P(i, j)=0;\n      matrix A1(P+A_u);\n      matrix_u A2(A_u);\n      blas::spr2(alpha, x, y, A2);\n      std::cout << print_mat(A1) << '\\n'\n                << print_mat(A2) << '\\n';\n    }\n  }\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "81219be83b8445bfca275a6a3aba04c7bb245d9a", "size": 2188, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/blas/spr2.cc", "max_stars_repo_name": "rabauke/numeric_bindings", "max_stars_repo_head_hexsha": "f4de93bd7a01a8b31c9367fad35c81d086768f99", "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/blas/spr2.cc", "max_issues_repo_name": "rabauke/numeric_bindings", "max_issues_repo_head_hexsha": "f4de93bd7a01a8b31c9367fad35c81d086768f99", "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/blas/spr2.cc", "max_forks_repo_name": "rabauke/numeric_bindings", "max_forks_repo_head_hexsha": "f4de93bd7a01a8b31c9367fad35c81d086768f99", "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.2571428571, "max_line_length": 89, "alphanum_fraction": 0.5973491773, "num_tokens": 675, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4998502965702018}}
{"text": "#include \"vc.h\"\n\n#include \"cropper.h\"\n#include \"fft_plan.h\"\n#include \"tensorOps.h\"\n\n#include <Eigen/SVD>\n\nCx4 VBC(Cx4 &maps, Log &log)\n{\n  Index const nc = maps.dimension(0);\n  Index const nx = maps.dimension(1);\n  Index const ny = maps.dimension(2);\n  Index const nz = maps.dimension(3);\n\n  Eigen::Map<Eigen::MatrixXcf const> mat(maps.data(), nc, nx * ny * nz);\n  log.info(\"VBC SVD size {}x{}\", mat.rows(), mat.cols());\n  auto const svd = mat.bdcSvd(Eigen::ComputeThinV);\n  Cx4 body(maps.dimensions());\n  Eigen::Map<Eigen::MatrixXcf> bodymat(body.data(), nc, nx * ny * nz);\n  bodymat = svd.matrixV().transpose();\n  log.image(maps, \"vbc-maps.nii\");\n  log.image(body, \"vbc-body.nii\");\n  bodymat = bodymat.array().conjugate() / bodymat.array().abs();\n  return body;\n}\n\nvoid VCC(Cx4 &data, Log &log)\n{\n  Index const nc = data.dimension(0);\n  Index const nx = data.dimension(1);\n  Index const ny = data.dimension(2);\n  Index const nz = data.dimension(3);\n\n  // Assemble our virtual conjugate channels\n  Cx4 cdata(nc, nx, ny, nz);\n  FFT::Planned<5, 3> fft(cdata, log);\n  cdata = data;\n  log.image(cdata, \"vcc-cdata.nii\");\n  fft.forward(cdata);\n  log.image(cdata, \"vcc-cdata-ks.nii\");\n  Cx4 rdata = cdata.slice(Sz4{0, 1, 1, 1}, Sz4{nc, nx - 1, ny - 1, nz - 1})\n                .reverse(Eigen::array<bool, 4>({false, true, true, true}))\n                .conjugate();\n  cdata.setZero();\n  cdata.slice(Sz4{0, 1, 1, 1}, Sz4{nc, nx - 1, ny - 1, nz - 1}) = rdata;\n  log.image(cdata, \"vcc-cdata-conj-ks.nii\");\n  fft.reverse(cdata);\n  log.image(cdata, \"vcc-cdata-conj.nii\");\n\n  Cx3 phase(nx, ny, nz);\n  phase.setZero();\n  for (Index iz = 1; iz < nz; iz++) {\n    for (Index iy = 1; iy < ny; iy++) {\n      for (Index ix = 1; ix < nx; ix++) {\n        Cx1 const vals = data.chip(iz, 3).chip(iy, 2).chip(ix, 1);\n        Cx1 const cvals = cdata.chip(iz, 3).chip(iy, 2).chip(ix, 1).conjugate(); // Dot has a conj\n        float const p = std::log(Dot(cvals, vals)).imag() / 2.f;\n        phase(ix, iy, iz) = std::polar(1.f, -p);\n      }\n    }\n  }\n  log.image(phase, \"vcc-correction.nii\");\n  log.info(\"Applying Virtual Conjugate Coil phase correction\");\n  data = data * Tile(phase, nc);\n  log.image(data, \"vcc-corrected.nii\");\n}\n\nCx3 Hammond(Cx4 const &maps, Log &log)\n{\n  Index const nc = maps.dimension(0);\n  Index const nx = maps.dimension(1);\n  Index const ny = maps.dimension(2);\n  Index const nz = maps.dimension(3);\n  log.info(\"Combining images via the Hammond method\");\n\n  Index const refSz = 9;\n  Cropper refCrop(Sz3{nx, ny, nz}, Sz3{refSz, refSz, refSz}, log);\n  Cx1 const ref =\n    refCrop.crop4(maps).sum(Sz3{1, 2, 3}).conjugate() / refCrop.crop4(maps).sum(Sz3{1, 2, 3}).abs();\n\n  using FixedOne = Eigen::type2index<1>;\n  Eigen::IndexList<int, FixedOne, FixedOne, FixedOne> rsh;\n  rsh.set(0, nc);\n  Eigen::IndexList<FixedOne, int, int, int> brd;\n  brd.set(1, nx);\n  brd.set(2, ny);\n  brd.set(3, nz);\n  auto const broadcasted = ref.reshape(rsh).broadcast(brd);\n  Cx3 const combined = (maps * broadcasted).sum(Sz1{0});\n  Cx3 const rss = maps.square().sum(Sz1{0}).sqrt();\n  log.image(combined, \"hammond-combined.nii\");\n  log.image(rss, \"hammond-rss.nii\");\n\n  return combined;\n}", "meta": {"hexsha": "a988d63b51515423a068402b239bbd4ccbcafc24", "size": 3162, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/vc.cpp", "max_stars_repo_name": "spinicist/riesling", "max_stars_repo_head_hexsha": "fa98ef1380345aa47d57ba91c970f37fe8fc5405", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2021-02-08T21:28:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T08:08:50.000Z", "max_issues_repo_path": "src/vc.cpp", "max_issues_repo_name": "spinicist/riesling", "max_issues_repo_head_hexsha": "fa98ef1380345aa47d57ba91c970f37fe8fc5405", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 29.0, "max_issues_repo_issues_event_min_datetime": "2021-02-19T11:59:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-24T20:45:57.000Z", "max_forks_repo_path": "src/vc.cpp", "max_forks_repo_name": "spinicist/riesling", "max_forks_repo_head_hexsha": "fa98ef1380345aa47d57ba91c970f37fe8fc5405", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-07-29T14:54:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T10:59:05.000Z", "avg_line_length": 32.9375, "max_line_length": 100, "alphanum_fraction": 0.623655914, "num_tokens": 1094, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744717487329, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4998502938526635}}
{"text": "// Copyright 2008 Chung-Lin Wen.\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n/*************************************************************************************************/\n\n#ifndef GIL_LAB_H\n#define GIL_LAB_H\n\n////////////////////////////////////////////////////////////////////////////////////////\n/// \\file\n/// \\brief Support for CIE Lab color space\n/// \\author Chung-Lin Wen \\n\n////////////////////////////////////////////////////////////////////////////////////////\n\n#include <boost/cast.hpp>\n#include <boost/gil/gil_all.hpp>\n\nnamespace boost { namespace gil {\n\n/// \\addtogroup ColorNameModel\n/// \\{\nnamespace lab_color_space\n{\n/// \\brief Luminance\nstruct luminance_t {};    \n/// \\brief a Color Component\nstruct a_color_opponent_t {};\n/// \\brief b Color Component\nstruct b_color_opponent_t {}; \n}\n/// \\}\n\n/// \\ingroup ColorSpaceModel\ntypedef mpl::vector3< lab_color_space::luminance_t\n                    , lab_color_space::a_color_opponent_t\n                    , lab_color_space::b_color_opponent_t\n                    > lab_t;\n\n/// \\ingroup LayoutModel\ntypedef layout<lab_t> lab_layout_t;\n\n\nGIL_DEFINE_ALL_TYPEDEFS( 32f, lab );\n\n/// \\ingroup ColorConvert\n/// \\brief RGB to LAB\ntemplate <>\nstruct default_color_converter_impl< rgb_t, lab_t >\n{\n   template <typename P1, typename P2>\n   void operator()( const P1& src, P2& dst ) const\n   {\n      using namespace lab_color_space;\n\n      // only bits32f for lab is supported\n      bits32f temp_red   = channel_convert<bits32f>( get_color( src, red_t()   ));\n      bits32f temp_green = channel_convert<bits32f>( get_color( src, green_t() ));\n      bits32f temp_blue  = channel_convert<bits32f>( get_color( src, blue_t()  ));\n\n      // first, transfer to xyz color space\n      bits32f normalized_r = temp_red / 255.f;\n      bits32f normalized_g = temp_green / 255.f;\n      bits32f normalized_b = temp_blue / 255.f;\n\n      if( normalized_r > 0.04045f )\n      {\n\t  \t   normalized_r = pow( (( normalized_r + 0.055f ) / 1.055f ), 2.4f );\n      }\n\t   else\n\t   {\n\t  \t   normalized_r /= 12.92f;\n      }\n\n      if( normalized_g > 0.04045f )\n      {\n\t  \t   normalized_g = pow((( normalized_g + 0.055f ) / 1.055f ), 2.4f );\n      }\n\t   else\n\t   {\n\t  \t   normalized_g /= 12.92f;\n      }\n\n      if( normalized_b > 0.04045f )\n      {\n\t  \t   normalized_b = pow( (( normalized_b + 0.055f ) / 1.055f ), 2.4f );\n      }\n\t   else\n\t   {\n\t  \t   normalized_b /= 12.92f;\n      }\n\n\t  normalized_r *= 100.f;\n\t  normalized_g *= 100.f;\n\t  normalized_b *= 100.f;\n\n      bits32f x, y, z;\n      x = normalized_r * 0.4124f + normalized_g * 0.3576f + normalized_b * 0.1805f;\n      y = normalized_r * 0.2126f + normalized_g * 0.7152f + normalized_b * 0.0722f;\n      z = normalized_r * 0.0193f + normalized_g * 0.1192f + normalized_b * 0.9505f;\n\n      // then, transfer to lab color space\n      bits32f ref_x = 95.047f;\n      bits32f ref_y = 100.000f;\n      bits32f ref_z = 108.883f;\n      bits32f normalized_x = x / ref_x;\n      bits32f normalized_y = y / ref_y;\n      bits32f normalized_z = z / ref_z;\n\n      if( normalized_x > 0.008856f )\n      {\n         normalized_x = pow( normalized_x, 0.333f );\n      }\n\t   else\n\t   {\n\t  \t   normalized_x = (7.787f * normalized_x) + ( 16.f/116.f );\n      }\n\n      if( normalized_y > 0.008856f )\n      {\n\t  \t   normalized_y = pow( normalized_y, 0.333f );\n      }\n\t   else\n\t   {\n\t  \t   normalized_y = (7.787f * normalized_y) + ( 16.f/116.f );\n      }\n\n\t   if( normalized_z > 0.008856f )\n\t   {\n\t  \t   normalized_z = pow( normalized_z, 0.333f );\n      }\n\t   else\n\t   {\n\t  \t   normalized_z = ( 7.787f * normalized_z ) + ( 16.f/116.f );\n      }\n\n      bits32f luminance, a_color_opponent, b_color_opponent;\n      luminance = ( 116.f * normalized_y ) - 16.f;\n      a_color_opponent = 500.f * ( normalized_x - normalized_y );\n      b_color_opponent = 200.f * ( normalized_y - normalized_z );\n\n      get_color( dst, luminance_t() ) = luminance;\n      get_color( dst, a_color_opponent_t() ) = a_color_opponent;\n      get_color( dst, b_color_opponent_t() ) = b_color_opponent;\n   }\n};\n\n/// \\ingroup ColorConvert\n/// \\brief LAB to RGB\ntemplate <>\nstruct default_color_converter_impl<lab_t,rgb_t>\n{\n   template <typename P1, typename P2>\n   void operator()( const P1& src, P2& dst) const\n   {\n      using namespace lab_color_space;\n\n      bits32f luminance = get_color( src, luminance_t() );\n      bits32f a_color_opponent = get_color( src, a_color_opponent_t() );\n      bits32f b_color_opponent = get_color( src, b_color_opponent_t() );\n\n      // first, transfer to xyz color space\n      bits32f normalized_y = ( luminance + 16.f ) / 116.f;\n      bits32f normalized_x = ( a_color_opponent / 500.f ) + normalized_y;\n      bits32f normalized_z = normalized_y - ( b_color_opponent / 200.f );\n\n      if( pow( normalized_y, 3.f ) > 0.008856f ) \n      {\n         normalized_y = pow( normalized_y, 3.f );\n      }\n      else\n      {\n         normalized_y = ( normalized_y - 16.f / 116.f ) / 7.787f;\n      }\n\n      if( pow( normalized_x, 3.f ) > 0.008856f ) \n      {\n         normalized_x = pow( normalized_x, 3.f );\n      }\n      else\n      {\n         normalized_x = ( normalized_x - 16.f / 116.f ) / 7.787f;\n      }\n\n      if( pow( normalized_z, 3.f ) > 0.008856f )\n      {\n         normalized_z = pow( normalized_z, 3.f );\n      }\n      else\n      {\n         normalized_z = ( normalized_z - 16.f / 116.f ) / 7.787f;\n      }\n\n      bits32f reference_x = 95.047f;\n      bits32f reference_y = 100.000f;\n      bits32f reference_z = 108.883f;\n      bits32f x, y, z;\n      x = reference_x * normalized_x;\n      y = reference_y * normalized_y;\n      z = reference_z * normalized_z;\n\n      // then, transfer to rgb color space\n      normalized_x = x / 100.f;\n      normalized_y = y / 100.f;\n      normalized_z = z / 100.f;\n\n      bits32f result_r = normalized_x *  3.2406f + normalized_y * -1.5372f + normalized_z * -0.4986f;\n      bits32f result_g = normalized_x * -0.9689f + normalized_y *  1.8758f + normalized_z *  0.0415f;\n      bits32f result_b = normalized_x *  0.0557f + normalized_y * -0.2040f + normalized_z *  1.0570f;\n\n      if( result_r > 0.0031308f )\n      { \n         result_r = 1.055f * pow( result_r, 1.f/2.4f ) - 0.055f;\n      }\n      else\n      {\n         result_r = 12.92f * result_r;\n      }\n\n      if( result_g > 0.0031308f ) \n      {\n         result_g = 1.055f * pow( result_g, 1.f/2.4f ) - 0.055f;\n      }\n      else\n      {\n         result_g = 12.92f * result_g;\n      }\n\n      if( result_b > 0.0031308f )\n      {\n         result_b = 1.055f * pow( result_b, 1.f/2.4f ) - 0.055f;\n      }\n      else\n      {\n         result_b = 12.92f * result_b;\n      }\n\n      bits32f red, green, blue;\n      red   = result_r * 255.f;\n      green = result_g * 255.f;\n      blue  = result_b * 255.f;\n\n      get_color(dst,red_t())  =\n         channel_convert<typename color_element_type<P2, red_t>::type>( red );\n      get_color(dst,green_t())=\n         channel_convert<typename color_element_type<P2, green_t>::type>( green );\n      get_color(dst,blue_t()) =\n         channel_convert<typename color_element_type<P2, blue_t>::type>( blue );\n   }\n};\n\n} }  // namespace boost::gil\n\n#endif // GIL_LAB_H\n", "meta": {"hexsha": "cc05960a8d8738150e74095e9823034c1325073c", "size": 7257, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3rdparty/boost/boost/gil/extension/toolbox/lab.hpp", "max_stars_repo_name": "Greentwip/windy", "max_stars_repo_head_hexsha": "4eb8174f952c5b600ff004827a5c85dbfb013091", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-07-13T21:11:55.000Z", "max_stars_repo_stars_event_max_datetime": "2017-07-13T21:11:55.000Z", "max_issues_repo_path": "3rdparty/boost/boost/gil/extension/toolbox/lab.hpp", "max_issues_repo_name": "Greentwip/Windy", "max_issues_repo_head_hexsha": "4eb8174f952c5b600ff004827a5c85dbfb013091", "max_issues_repo_licenses": ["MIT"], "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/boost/boost/gil/extension/toolbox/lab.hpp", "max_forks_repo_name": "Greentwip/Windy", "max_forks_repo_head_hexsha": "4eb8174f952c5b600ff004827a5c85dbfb013091", "max_forks_repo_licenses": ["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.34765625, "max_line_length": 101, "alphanum_fraction": 0.569656883, "num_tokens": 2170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038221, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4998502911351252}}
{"text": "// Implementation for kc_test\n//\n\n#include \"stdafx.h\"\n#include <cmath>\n#include \"funcs.h\"\n#include \"ck_sdk.h\"\n#include \"KCSdkUtilities.h\"\n#include \"SMask.h\"\n#include \"TestUtil.h\"\n#include \"splines.h\"\n#include \"SplineHelper.h\"\n#include <fstream>\n#include <chrono>\n#include <Eigen/Core>\n#include <unsupported/Eigen/Splines>\n\nconst double MIN_TOL = .00005;\nusing namespace Eigen;\nusing timer = std::chrono::steady_clock;\nusing std::chrono::time_point;\nusing std::chrono::duration_cast;\nusing std::chrono::milliseconds;\ntypedef Matrix<double, -1, -1> Points;\nint TestSplineLibrary() {\n\tint status = CKNoError;\n\tCKPart part = CKGetActivePart();\n\tif (!part.IsValid()) {\n\t\treturn CK_NO_PART;\n\t}\n\tstd::vector<CKSCoord> control_points;   // Holds the 4 control points for entire segment\n  std::vector <double> coeffs;\n  CKSMatrix worldMat;\n  CKSEntityArray curves = CurvesSelect(part);\n  status = GetCoeffFromCurves(part, curves, coeffs, .0000001);\n  CKSEntity spline = part.AddSpline(true, false, coeffs, NULL, &worldMat);\n  //CKSEntity spline = SplineSelect(part);\n  if (!spline.IsValid()) {\n\t\tMessageBox(nullptr, _T(\"Error with spline selection\"), _T(\"Spline Data\"), MB_OK_STOP);\n\t\tstatus = CKError;\n\t}\n\telse {\n\t\tbool is3D = false;\n\t\tbool isClosed = false;\n\n    HPMatrix splineMatrix;\n\t\tCKSCoordArray nodePoints;\n\t\tCKSCoord startVector, endVector;\n\t\tpart.GetSpline(spline, NULL, coeffs, is3D, isClosed, NULL, &splineMatrix);\n\t\tpart.GetSpline(spline, NULL, nodePoints, &startVector, &endVector, is3D, isClosed, NULL, &splineMatrix);\n\t\tsize_t blockSize = 0;\n\t\tif (is3D) {\n\t\t\tblockSize = 12;\n\t\t}\n\t\telse {\n\t\t\tblockSize = 8;\n\t\t}\n\t\tdouble param[3][4] = { 0.0 };   // Array to hold current segment coefficients\n\t\tfor (size_t i = 0; i < coeffs.size(); i += blockSize) {\n\t\t\tif (is3D) {\n\t\t\t\tfor (size_t j = 0; j < 3; ++j) {\n\t\t\t\t\tfor (size_t k = 0; k < 4; ++k) {\n\t\t\t\t\t\tparam[j][k] = coeffs[i + (j * 4) + k];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {  // 2D Spline\n\t\t\t\tfor (size_t j = 0; j < 2; ++j) {\n\t\t\t\t\tfor (size_t k = 0; k < 4; ++k) {\n\t\t\t\t\t\tparam[j][k] = coeffs[i + (j * 4) + k];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tGetSplineControlPoints(param, control_points);\n\t\t}\n\n\t\t//// Test old normal function using 2nd derivative\n\t\t//CKSCoord old_normal;\n\t\t//CKSCoord old_tangent;\n\t\t//CKSCoord old_position;\n\n\t\t//CKSMath::Evaluate(spline, NULL, false, false, false, 1, .0625, &splineMatrix, &old_position,\n\t\t//\t&old_normal, &old_tangent);\n\t\t////GetSplineNormal(coeffs, 1, .5, old_normal);\n\t\t//if (old_normal.Magnitude() > .001) {\n\t\t//\told_normal.Normalize();\n\t\t//}\n\t\t//if (old_tangent.Magnitude() > .001) {\n\t\t//\told_tangent.Normalize();\n\t\t//}\n\n\t\t////GetSplineCoord(coeffs, 1, .5, old_position);\n\t\t//old_normal = old_position + old_normal;\n\t\t//old_tangent = old_position + old_tangent;\n\t\t//part.AddPoint(old_position);\n\t\t//part.AddPoint(old_normal);\n\t\t//part.AddPoint(old_tangent);\n\t\t//part.NoteState();\n\n\t\t//// Test 2D spline points\n\t\t//CKSCoord2D cp_2d;\n\t\t//std::vector<CKSCoord2D> points_2d;\n\t\t//for (auto i : control_points) {\n\t\t//\tcp_2d.m_dX = i.m_dX;\n\t\t//\tcp_2d.m_dY = i.m_dY;\n\t\t//\tpoints_2d.push_back(cp_2d);\n\t\t//}\n\t\tconst size_t degree = 3;\n\n\t\t//// Test elevate degree 2d. Works\n\t\t//std::vector<CKSCoord2D> elevated_points = bezier::ElevateDegree<double>(points_2d, bezier::Dimension::k2d, degree);\n\t\t//for (auto i: elevated_points) {\n\t\t//\tpart.AddPoint(i.m_dX, i.m_dY, 0.0);\n\t\t//}\n\t\t//part.NoteState();\n\n\t\t//// Test segment split 2d. Works.\n\t\t//std::vector<CKSCoord2D> split_points;\n\t\t//for (size_t i = 0; i < points_2d.size() / (degree + 1); ++i) {\n\t\t//\tsplit_points = bezier::SplitSegment<double>(points_2d, .5, i, degree, 2);\n\t\t//\tfor (auto j : split_points) {\n\t\t//\t\tpart.AddPoint(j.m_dX, j.m_dY, 0.0);\n\t\t//\t}\n\t\t//}\n\t\t//part.NoteState();\n\n\t\t//// Create spline from calculated coefficients 2d\n\t\t//for (size_t i = 0; i < 2; ++i) {\n\t\t//\tstd::vector<double> new_coeff = bezier::GetCoefficients<double>(split_points, i, degree, bezier::k2d);\n\t\t//\tpart.AddSpline(false, false, kc_coeff);\n\t\t//}\n\t\t//part.NoteState();\n\n\t\t//// Test tangent and normal functions 2d. Works\n\t\t//CKSCoord2D coordinate;\n\t\t//CKSCoord2D tangent;\n\t\t//CKSCoord2D normal;\n\t\t//for (size_t i = 0; i < points_2d.size() / 4; ++i) {\n  //    for (size_t j = 0; j < 4; ++j) {\n  //      double t = j / 4.0;\n  //      coordinate = bezier::GetPosition<double>(points_2d, t, i, degree, bezier::k2d);\n  //      part.AddPoint(coordinate.m_dX, coordinate.m_dY, 0.0);\n  //      tangent = bezier::GetFirstDerivative<double>(points_2d, t, i, degree, bezier::k2d);\n  //      normal = bezier::GetNormal<double>(points_2d, t, i, degree, bezier::k2d);\n  //      CKSMatrix temp;\n  //      CKSCoord v1(coordinate.m_dX, coordinate.m_dY, 0.0);\n  //      CKSCoord v2(tangent.m_dX, tangent.m_dY, 0.0);\n  //      CKSCoord v3(normal.m_dX, normal.m_dY, 0.0);\n  //      CKSMath::MatrixVector(v1, v1 + v2, temp);\n  //      CKEntityAttrib attrib;\n  //      attrib.m_ucColorNumber = 7;\n  //      part.AddVector(.25, &temp, &attrib);\n  //      attrib.m_ucColorNumber = 10;\n  //      CKSMath::MatrixVector(v1, v1 + v3, temp);\n  //      part.AddVector(.25, &temp, &attrib);\n  //    }\n\t\t//}\n\t\t//part.NoteState();\n\n\t\t//// Test elevate degree 3d. Works\n\t\t//CKSCoordArray elevated_points = bezier::ElevateDegree<double>(control_points, bezier::Dimension::k3d, 3);\n\t\t//for (size_t i = 0; i < elevated_points.size(); ++i) {\n\t\t//\tpart.AddPoint(elevated_points[i]);\n\t\t//}\n\t\t//part.NoteState();\n\n\t\t// Test segment split 3d. Works.\n\t\t//const size_t degree = 3;\n\t\t//std::vector<CKSCoord> split_points;\n\t\t//for (size_t i = 0; i < control_points.size() / (degree + 1); ++i) {\n\t\t//\tsplit_points = bezier::SplitSegment<double>(control_points, .5, i, degree, 3);\n\t\t//\tfor (auto j : split_points) {\n\t\t//\t\tpart.AddPoint(j);\n\t\t//\t}\n\t\t//}\n\t\t//part.NoteState();\n\n\t\t// Create spline from calculated coefficients 3d. Works\n\t\t//for (size_t i = 0; i < 2; ++i) {\n\t\t//\tstd::vector<double> new_coeff = bezier::GetCoefficients<double>(split_points, i);\n\t\t//\tpart.AddSpline(true, false, kc_coeff);\n\t\t//}\n\t\t//part.NoteState();\n\n\t\t//// Test tangent and normal functions 3d. Works\n\t\t//CKSCoord coordinate;\n\t\t//CKSCoord tangent;\n\t\t//CKSCoord normal;\n\t\t//CKSCoord curvature;\n\t\t//for (size_t i = 0; i < control_points.size() / 4; ++i) {\n\t\t//\tfor (auto j = 0; j < 5; ++j) {\n\t\t//\t\tdouble t = j / 4.0;\n\t\t//\t\tcoordinate = bezier::GetPosition<double>(control_points, t, i, 3, bezier::k3d);\n\t\t//\t\tpart.AddPoint(coordinate);\n\t\t//\t\ttangent = bezier::GetFirstDerivative<double>(control_points, t, i, 3, bezier::k3d);\n\t\t//\t\tnormal = bezier::GetNormal<double>(control_points, t, i, 3, bezier::k3d);\n\t\t//\t\tcurvature = bezier::GetSecondDerivative<double>(control_points, t, i, 3, bezier::k3d);\n\t\t//\t\ttangent.Normalize();\n\t\t//\t\tnormal.Normalize();\n\t\t//\t\tcurvature.Normalize();\n\t\t//\t\tCKSMatrix temp;\n\t\t//\t\tCKSMath::MatrixVector(coordinate, coordinate + tangent, temp);\n\t\t//\t\tCKEntityAttrib attrib;\n\t\t//\t\tattrib.m_ucColorNumber = 7;\n\t\t//\t\tpart.AddVector(1.0, &temp, &attrib);\n\t\t//\t\tattrib.m_ucColorNumber = 10;\n\t\t//\t\tCKSMath::MatrixVector(coordinate, coordinate + normal, temp);\n\t\t//\t\tpart.AddVector(1.0, &temp, &attrib);\n\t\t//\t\t//attrib.m_ucColorNumber = 2;\n\t\t//\t\t//CKSMath::MatrixVector(coordinate, coordinate + curvature, temp);\n\t\t//\t\t//part.AddVector(1.0, &temp, &attrib);\n\t\t//\t}\n\t\t//}\n    //part.DeleteEntity(spline);\n    //part.NoteState();\n\n    coeffs.clear();\n    coeffs = bezier::GetCoefficients<double>(control_points);\n    size_t coeffs_size = coeffs.size();\n    size_t control_point_set = degree + 1;\n    size_t segment_size = control_point_set * 3;\n    size_t segment_count = coeffs_size / segment_size;\n    std::vector<double> quad_coeffs(3);\n    std::vector<double> linear_coeffs(2);\n    std::vector<double> t_values;\n    for (size_t i = 0; i < segment_count; ++i) {\n      for (size_t j = 0; j < 3; ++j) {\n        for (size_t k = 0; k < 3; ++k) {\n          quad_coeffs[k] = coeffs[(i * segment_size) + (j * 4) + k] * (3 - k);\n          if (k < 2) {\n            linear_coeffs[k] = quad_coeffs[k] * (2 - k);\n          }\n        }\n        bezier::SolveQuadratic(quad_coeffs, t_values);\n        t_values.push_back(bezier::SolveLinear(linear_coeffs));\n      }\n    }\n    //auto t_end = std::remove_if(t_values.begin(), t_values.end(), [](double a) {\n    //  return (a <= 0.0 || a >= 1.0);\n    //});\n    //t_values.erase(t_end, t_values.end());\n    t_values.push_back(0.0);\n    t_values.push_back(1.0);\n    for (auto it : t_values) {\n      if (it >= 0.0 && it <= 1.0) {\n        CKSCoord position = bezier::GetPosition(control_points, it);\n        part.AddPoint(position);\n      }\n    }\n    part.NoteState();\n    WriteData(\"nodes.dat\", nodePoints);\n\t\tWriteCoefficients(\"coeff.dat\", coeffs);\n    WriteCoefficients(\"derivatives.dat\", t_values);\n\t\tWriteControlPoints(\"ctrl.dat\", control_points);\n\t\tCKSCoordArray fitPoints;\n\t\tSplineToPoints(part, spline, fitPoints);\n\t\tWriteData(\"spline.dat\", fitPoints);\n\t\tfitPoints.clear();\n\t}\n\treturn status;\n}\n\nint SplineHelix()\n{\n  CWnd* pWnd = AfxGetMainWnd();\n  int status = CKNoError;\n  CKPart part = CKGetActivePart();\n  if (!part.IsValid())\n  {\n    return CK_NO_PART;\n  }\n\n  CKSMatrix worldMat;\n  CKSMask mask;\n  mask.AddEntity(CKMaskLine);\n  mask.AddEntity(CKMaskArc);\n  mask.AddEntity(CKMaskSpline);\n  mask.AddEntity(CKMaskNURBSpline);\n  mask.AddEntity(CKMaskPolyline);\n  mask.AddEntity(CKMaskEllipse);\n  mask.AddEntity(CKMaskParabola);\n  mask.AddEntity(CKMaskHyperbola);\n\n  // Test create helical spline along a 3D curve\n  Events keyCheck;\n  double diameter = 1.0;\n  double pitch = 0.25;\n  CRegistry reg;\n  if (reg.KeyExists(_T(\"Software\\\\HPM\\\\HPMTools\\\\SplineHelix\")))\n  {\n    reg.SetKey(_T(\"Software\\\\HPM\\\\HPMTools\\\\SplineHelix\"), FALSE);\n    diameter = reg.ReadFloat(_T(\"Diameter\"), 1.0);\n    pitch = reg.ReadFloat(_T(\"Pitch\"), .25);\n  }\n  else\n  {\n    reg.CreateKey(_T(\"Software\\\\HPM\\\\HPMTools\\\\SplineHelix\"));\n    reg.SetKey(_T(\"Software\\\\HPM\\\\HPMTools\\\\SplineHelix\"), FALSE);\n    reg.WriteFloat(_T(\"Diameter\"), 1.0);\n    reg.WriteFloat(_T(\"Pitch\"), .25);\n  }\n  int step = 0;\n  while (true)\n  {\n    switch (step)\n    {\n    case 0:\n    {\n      keyCheck = ck_get_input(_T(\"Enter diameter: \"), _T(\"\"), diameter, true, 0, CKS::GreaterThan, 0.0);\n      switch (keyCheck)\n      {\n      case CKBackup:\n      case CKEscape:\n        return keyCheck;\n      case CKNoError:\n      {\n        reg.WriteFloat(_T(\"Diameter\"), diameter);\n        step++;\n        break;\n      }\n      default:\n        return keyCheck;\n      }\n    }\n    case 1:\n    {\n      keyCheck = ck_get_input(_T(\"Enter pitch: \"), _T(\"\"), pitch);\n      switch (keyCheck)\n      {\n      case CKBackup:\n      {\n        step--;\n        continue;\n      }\n      case CKEscape:\n        return keyCheck;\n      case CKNoError:\n      {\n        reg.WriteFloat(_T(\"Pitch\"), pitch);\n        step++;\n        break;\n      }\n      default:\n        return keyCheck;\n      }\n      if (CKSMath::CompareToZero(pitch, .01) <= 0)\n      {\n        pWnd->MessageBox(_T(\"The pitch entered is too small\"), MB_TITLE, MB_OK_INFO);\n        step--;\n        continue;\n      }\n    }\n    case 2:\n    {\n      CKSEntityArray driveCurves;\n      status = part.GenSel(_T(\"Select the sweep path chain of curves\"), driveCurves);\n      switch (status)\n      {\n      case CKNoError:\n        break;\n      case CKBackup:\n      {\n        step--;\n        continue;\n      }\n      default:\n        if ((status < CKMenu1) || (status >= CKEscape))\n          return status;\n        //case CKEscape:\n        //case CK_NO_PART:\n        //  return status;\n      }\n      CKSCoordArray helixPnts;\n      CKSCoord startVec, endVec;\n      status = GetHelicalSplinePoints(part, driveCurves, helixPnts, startVec, endVec, diameter, pitch, .0001);\n      if (helixPnts.size())\n      {\n        std::ofstream out_file(\"helix.points\");\n        for (auto p : helixPnts) {\n          out_file << p.m_dX << '\\t' << p.m_dY << '\\t' << p.m_dZ << '\\n';\n        }\n        time_point<timer> start_time;\n        time_point<timer> end_time;\n        milliseconds elapsed;\n        CString eigen_time;\n        CString kc_time;\n        CKSEntity helicalSpline;\n        CKEntityAttrib attrib;\n\n        start_time = timer::now();\n        size_t point_count = helixPnts.size();\n        Points points(3, point_count);\n        for (size_t i = 0; i < point_count; ++i) {\n          points(0, i) = helixPnts[i][0];\n          points(1, i) = helixPnts[i][1];\n          points(2, i) = helixPnts[i][2];\n        }\n        Spline3d testspline = SplineFitting<Spline3d>::Interpolate(points, 3);\n        size_t knots_size = testspline.knots().size();\n        std::vector<double> knots(knots_size);\n        for (size_t j = 0; j < knots_size; ++j) {\n          knots[j] = testspline.knots().data()[j];\n        }\n        Matrix<double, -1, -1> control_points = testspline.ctrls();\n        size_t ctrl_size = control_points.cols();\n        std::vector<CKSCoord> ctrl_points(ctrl_size);\n        for (size_t j = 0; j < ctrl_size; ++j) {\n          ctrl_points[j].m_dX = control_points(0, j);\n          ctrl_points[j].m_dY = control_points(1, j);\n          ctrl_points[j].m_dZ = control_points(2, j);\n        }\n        attrib.m_ucColorNumber = 7;\n        std::vector<double> weights(ctrl_size, 1.0);\n        helicalSpline = part.AddNURBSpline(3, true, false, knots, ctrl_points, weights, &attrib);\n        end_time = timer::now();\n        elapsed = duration_cast<milliseconds>(end_time - start_time);\n        eigen_time.Format(_T(\"Eigen Spline creation time: %d ms\\n\"), elapsed.count());\n        part.NoteState();\n        helicalSpline = part.AddSpline(true, false, true, true, startVec, endVec, helixPnts, NULL, &worldMat);\n        part.NoteState();\n        //helicalSpline = part.AddSpline(true, false, false, false, startVec, endVec, helixPnts, NULL, &worldMat);\n        //start_time = timer::now();\n        //attrib.m_ucColorNumber = 9;\n        //helicalSpline = part.AddNURBSpline(3, true, false, helixPnts, &attrib, &worldMat);\n        //end_time = timer::now();\n        //elapsed = duration_cast<milliseconds>(end_time - start_time);\n        //kc_time.Format(_T(\"KC spline time: %d ms\\n\"), elapsed.count());\n        //part.NoteState();\n        if (!helicalSpline.IsValid()) {\n          pWnd->MessageBox(_T(\"Error creating helical spline\"), MB_TITLE, MB_OK_STOP);\n          return CKError;\n        }\n        CString all_time = eigen_time + kc_time;\n        //CString all_time = eigen_time;\n        pWnd->MessageBox(all_time, MB_TITLE, MB_OK_STOP);\n      }\n    }\n    }\n  }\n  return status;\n}\n", "meta": {"hexsha": "b7dd9a3cd41335ab4ab028698d9d01ea268535a0", "size": 14428, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kc_test/kc_testFuncs.cpp", "max_stars_repo_name": "hpmachining/splines", "max_stars_repo_head_hexsha": "9df0e51eac3169f0f518159752719f3b0fbfdb9c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-07-22T15:29:18.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-04T21:31:33.000Z", "max_issues_repo_path": "kc_test/kc_testFuncs.cpp", "max_issues_repo_name": "hpmachining/splines", "max_issues_repo_head_hexsha": "9df0e51eac3169f0f518159752719f3b0fbfdb9c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kc_test/kc_testFuncs.cpp", "max_forks_repo_name": "hpmachining/splines", "max_forks_repo_head_hexsha": "9df0e51eac3169f0f518159752719f3b0fbfdb9c", "max_forks_repo_licenses": ["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.6425339367, "max_line_length": 119, "alphanum_fraction": 0.6120044358, "num_tokens": 4539, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186787341014, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.49976404549839515}}
{"text": "/**\nThis file is part of Deformable Shape Tracking (DEST).\n\nCopyright(C) 2015/2016 Christoph Heindl\nAll rights reserved.\n\nThis software may be modified and distributed under the terms\nof the BSD license.See the LICENSE file for details.\n*/\n\n#define CATCH_CONFIG_MAIN\n#include \"catch.hpp\"\n\n#include <dest/core/shape.h>\n#include <Eigen/Geometry>\n\nTEST_CASE(\"similarity-transform-translate\")\n{\n    dest::core::Shape to(2, 4);\n    to << 0.f, 2.f, 2.f, 0.f,\n          0.f, 0.f, 2.f, 2.f;\n    \n    Eigen::AffineCompact2f t;\n    t = Eigen::Translation2f(1.f, 1.f);\n    \n    dest::core::Shape from = t.matrix() * to.colwise().homogeneous();\n    \n    Eigen::AffineCompact3f s = dest::core::estimateSimilarityTransform(from, to);\n    \n    Eigen::AffineCompact2f expected;\n    expected = Eigen::Translation2f(-1.f, -1.f);\n\n    REQUIRE(s.isApprox(expected));\n\n}\n\nTEST_CASE(\"similarity-transform-compound\")\n{\n    dest::core::Shape to(2, 4);\n    to << 0.f, 2.f, 2.f, 0.f,\n    0.f, 0.f, 2.f, 2.f;\n    \n    Eigen::AffineCompact2f t;\n    t = Eigen::Translation2f(1.f, 1.f) * Eigen::Rotation2Df(0.17f) * Eigen::Scaling(1.8f);\n    \n    dest::core::Shape from = t.matrix() * to.colwise().homogeneous();\n    \n    Eigen::AffineCompact3f s = dest::core::estimateSimilarityTransform(from, to);\n    \n    Eigen::AffineCompact2f expected = t.inverse();\n    \n    REQUIRE(s.isApprox(expected));    \n}\n\n\nTEST_CASE(\"similarity-transform-between-rects\")\n{\n    dest::core::Rect r = dest::core::createRectangle(Eigen::Vector2f(-2.f, -2.f), Eigen::Vector2f(2.f, 2.f));\n\n    Eigen::AffineCompact2f t;\n    t = Eigen::Rotation2Df(0.17f);\n\n    r = t.matrix() * r.colwise().homogeneous();\n\n    dest::core::Rect n = dest::core::unitRectangle();\n    Eigen::AffineCompact3f s = dest::core::estimateSimilarityTransform(r, n);\n\n    r = s.matrix() * r.colwise().homogeneous();\n    REQUIRE(r.isApprox(n));\n}", "meta": {"hexsha": "bf96b53dc6068cb1be60dbdd16370326b31bf247", "size": 1860, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_transform.cpp", "max_stars_repo_name": "wangqianyun001/Facial-Landmark-Detection", "max_stars_repo_head_hexsha": "b8e2bc6b210ad2adea35f17fa8a8e58ac695e8f5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/test_transform.cpp", "max_issues_repo_name": "wangqianyun001/Facial-Landmark-Detection", "max_issues_repo_head_hexsha": "b8e2bc6b210ad2adea35f17fa8a8e58ac695e8f5", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/test_transform.cpp", "max_forks_repo_name": "wangqianyun001/Facial-Landmark-Detection", "max_forks_repo_head_hexsha": "b8e2bc6b210ad2adea35f17fa8a8e58ac695e8f5", "max_forks_repo_licenses": ["BSD-3-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.5714285714, "max_line_length": 109, "alphanum_fraction": 0.6456989247, "num_tokens": 571, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.6261241702517975, "lm_q1q2_score": 0.49976403391817614}}
{"text": "#include <blitzml/sparse_linear/lasso_solver.h>\n\n#include <blitzml/base/math_util.h>\n#include <blitzml/base/vector_util.h>\n#include <blitzml/base/subproblem_controller.h>\n\nusing std::vector;\n\nnamespace BlitzML {\n\nvalue_t LassoSolver::compute_dual_obj() const { \n  value_t loss = 0.5 * l2_norm_sq(x);\n  return -(loss + l1_penalty * l1_norm(omega));\n}\n\n\nvalue_t LassoSolver::compute_primal_obj_x() const {\n  value_t ip = inner_product(data->b_values(), &x[0], num_examples);\n  return 0.5 * sq(kappa_x) * l2_norm_sq(x) + kappa_x * ip;\n}\n\n\nvalue_t LassoSolver::compute_primal_obj_y() const {\n  value_t ip = inner_product(data->b_values(), &y[0], num_examples);\n  return 0.5 * l2_norm_sq(y) + ip;\n}\n\n\nvalue_t LassoSolver::update_coordinates_in_working_set() {\n  value_t ret = 0.;\n  for (const_index_itr i = ws.begin(); i != ws.end(); ++i) {\n    value_t subgrad = update_feature_lasso(*i);\n    ret += sq(subgrad);\n  }\n  ws.shuffle();\n  return ret;\n}\n\n\ninline value_t LassoSolver::update_feature_lasso(index_t i) {\n  value_t inv_L = inv_lipschitz_cache[i];\n  if (inv_L < 0) {\n    return 0.;\n  }\n\n  const Column& col = *A_cols[i];\n  value_t current_value = omega[i];\n  value_t grad = col.inner_product(x) \n                          + num_examples * Delta_bias * col_means_cache[i];\n  if (current_value == 0. && fabs(grad) < l1_penalty) {\n    return 0.;\n  }\n\n  value_t pre_shrink = current_value - grad * inv_L;\n  value_t new_value = soft_threshold(pre_shrink, l1_penalty * inv_L);\n  value_t delta = new_value - current_value;\n  if (delta == 0.) {\n    return 0.;\n  }\n  col.add_multiple(x, delta);\n  omega[i] = new_value;\n  if (use_bias) {\n    Delta_bias -= col_means_cache[i] * delta;\n  }\n\n  return grad + sign(current_value) * l1_penalty;\n}\n\n\nvoid LassoSolver::update_bias(int max_newton_itr) {\n  if (!use_bias) {\n    return;\n  }\n  value_t grad = sum_vector(x);\n  value_t delta = -grad / x.size();\n  bias += delta;\n  add_scalar_to_vector(x, delta);\n} \n\n\nvoid LassoSolver::perform_backtracking() {\n  if (use_bias) {\n    add_scalar_to_vector(x, Delta_bias);\n    bias += Delta_bias;\n  }\n}\n\n\nvoid LassoSolver::setup_proximal_newton_problem() { \n  Delta_bias = 0.;\n}\n\n}\n\n", "meta": {"hexsha": "cdb91c5fa68fd1a3f0a4103abd6e01e52663781e", "size": 2158, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sparse_linear/lasso_solver.cpp", "max_stars_repo_name": "tbjohns/BlitzML", "max_stars_repo_head_hexsha": "0523743e1ae3614bfe3f16aa226d7a27fab2d623", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-06-16T05:17:17.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-02T05:50:01.000Z", "max_issues_repo_path": "src/sparse_linear/lasso_solver.cpp", "max_issues_repo_name": "tbjohns/BlitzML", "max_issues_repo_head_hexsha": "0523743e1ae3614bfe3f16aa226d7a27fab2d623", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-05-13T13:53:58.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-11T14:53:26.000Z", "max_forks_repo_path": "src/sparse_linear/lasso_solver.cpp", "max_forks_repo_name": "tbjohns/BlitzML", "max_forks_repo_head_hexsha": "0523743e1ae3614bfe3f16aa226d7a27fab2d623", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-08-02T05:50:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-21T04:44:15.000Z", "avg_line_length": 22.7157894737, "max_line_length": 75, "alphanum_fraction": 0.6742354032, "num_tokens": 635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186768138228, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.49976403347506654}}
{"text": "#include <boost/math/distributions/hypergeometric.hpp>\n", "meta": {"hexsha": "217ea655eb1c41a824000769f365fba4460ad3b5", "size": 55, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_distributions_hypergeometric.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_distributions_hypergeometric.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_distributions_hypergeometric.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 27.5, "max_line_length": 54, "alphanum_fraction": 0.8363636364, "num_tokens": 12, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637648915617, "lm_q2_score": 0.5813030906443134, "lm_q1q2_score": 0.4997252034463912}}
{"text": "\r\n\r\n#include <bio/defs.h>\r\nUSING_BIO_NS\r\n\r\n#include <boost/test/unit_test.hpp>\r\n#include <boost/test/parameterized_test.hpp>\r\n#include <boost/assign/list_of.hpp>\r\n#undef max\r\n#include <boost/numeric/ublas/matrix.hpp>\r\n#include <boost/numeric/ublas/matrix_sparse.hpp>\r\nusing namespace boost;\r\nusing namespace boost::assign;\r\nusing boost::unit_test::test_suite;\r\n\r\n#include <iostream>\r\nusing namespace std;\r\n\r\n#include <math.h>\n\r\n#include \"blas1c.h\"\n#include \"lapackc.h\"\n#include \"arlsmat.h\"\n//#include \"arcomp.h\"\n#include \"arlsmat.h\"\n#include \"arlnsmat.h\"\n#include \"arlssym.h\"\n#include \"arlgsym.h\"\n#include \"arlsnsym.h\"\n#include \"arlgnsym.h\"\n#include \"arlscomp.h\"\n#include \"arlgcomp.h\"\n\r\n\r\n\r\n#define VERBOSE_CHECKING\r\n\r\n\n\ntemplate <class FLOAT>\nint AREig(arcomplex<FLOAT> EigVal[], int n, int nnz, arcomplex<FLOAT> A[],\n          int irow[], int pcol[], int nev, char* which = \"LM\", int ncv = 0,\n          FLOAT tol = 0.0, int maxit = 0, arcomplex<FLOAT>* resid = 0,\n          bool AutoShift = true)\n{\n\n  // Creating a matrix in ARPACK++ format.\n\n  ARluNonSymMatrix<arcomplex<FLOAT> > matrix(n, nnz, A, irow, pcol);\n\n  // Defining the eigenvalue problem.\n\n  ARluCompStdEig<FLOAT> prob(nev, matrix, which, ncv, tol,\n                             maxit, resid, AutoShift);\n\n  // Finding eigenvalues.\n\n  return prob.Eigenvalues(EigVal);\n\n} // complex standard problem, only eigenvalues, regular mode.\n\n\ntemplate <class FLOAT>\nint AREig(arcomplex<FLOAT> EigVal[], arcomplex<FLOAT> EigVec[], int n,\n          int nnz, arcomplex<FLOAT> A[], int irow[], int pcol[],\n          int nev, char* which = \"LM\", int ncv = 0, FLOAT tol = 0.0,\n          int maxit = 0, arcomplex<FLOAT>* resid = 0, bool AutoShift = true)\n{\n\n  // Creating a matrix in ARPACK++ format.\n\n  ARluNonSymMatrix<arcomplex<FLOAT> > matrix(n, nnz, A, irow, pcol);\n\n  // Defining the eigenvalue problem.\n\n  ARluCompStdEig<FLOAT> prob(nev, matrix, which, ncv, tol,\n                             maxit, resid, AutoShift);\n\n  // Finding eigenvalues and eigenvectors.\n\n  return prob.EigenValVectors(EigVec, EigVal);\n\n} // complex standard problem, values and vectors, regular mode.\n\n\ntemplate <class FLOAT>\nint AREig(arcomplex<FLOAT> EigVal[], int n, int nnz, arcomplex<FLOAT> A[],\n          int irow[], int pcol[], arcomplex<FLOAT> sigma, int nev,\n          char* which = \"LM\", int ncv = 0, FLOAT tol = 0.0, int maxit = 0,\n          arcomplex<FLOAT>* resid = 0, bool AutoShift = true)\n{\n\n  // Creating a matrix in ARPACK++ format.\n\n  ARluNonSymMatrix<arcomplex<FLOAT> > matrix(n, nnz, A, irow, pcol);\n\n  // Defining the eigenvalue problem.\n\n  ARluCompStdEig<FLOAT> prob(nev, matrix, sigma, which, ncv,\n                             tol, maxit, resid, AutoShift);\n\n  // Finding eigenvalues.\n\n  return prob.Eigenvalues(EigVal);\n\n} // complex standard problem, only eigenvalues, shift-and-invert.\n\n\ntemplate <class FLOAT>\nint AREig(arcomplex<FLOAT> EigVal[], arcomplex<FLOAT> EigVec[], int n,\n          int nnz, arcomplex<FLOAT> A[], int irow[], int pcol[],\n          arcomplex<FLOAT> sigma, int nev, char* which = \"LM\",\n          int ncv = 0, FLOAT tol = 0.0, int maxit = 0,\n          arcomplex<FLOAT>* resid = 0, bool AutoShift = true)\n{\n\n  // Creating a matrix in ARPACK++ format.\n\n  ARluNonSymMatrix<arcomplex<FLOAT> > matrix(n, nnz, A, irow, pcol);\n\n  // Defining the eigenvalue problem.\n\n  ARluCompStdEig<FLOAT> prob(nev, matrix, sigma, which, ncv,\n                             tol, maxit, resid, AutoShift);\n\n  // Finding eigenvalues and eigenvectors.\n\n  return prob.EigenValVectors(EigVec, EigVal);\n\n} // complex standard problem, values and vectors, shift-and-invert.\n\n\ntemplate <class FLOAT>\nint AREig(arcomplex<FLOAT> EigVal[], int n, int nnzA,\n          arcomplex<FLOAT> A[], int irowA[], int pcolA[], int nnzB,\n          arcomplex<FLOAT> B[], int irowB[], int pcolB[], int nev,\n          char* which = \"LM\", int ncv = 0, FLOAT tol = 0.0, int maxit = 0,\n          arcomplex<FLOAT>* resid = 0, bool AutoShift = true)\n{\n\n  // Creating two matrices in ARPACK++ format.\n\n  ARluNonSymMatrix<arcomplex<FLOAT> > matrixA(n, nnzA, A, irowA, pcolA);\n  ARluNonSymMatrix<arcomplex<FLOAT> > matrixB(n, nnzB, B, irowB, pcolB);\n\n  // Defining the eigenvalue problem.\n\n  ARluCompGenEig<FLOAT> prob(nev, matrixA, matrixB, which,\n                             ncv, tol, maxit, resid, AutoShift);\n\n  // Finding eigenvalues.\n\n  return prob.Eigenvalues(EigVal);\n\n} // complex generalized problem, only eigenvalues, regular mode.\n\n\ntemplate <class FLOAT>\nint AREig(arcomplex<FLOAT> EigVal[], arcomplex<FLOAT> EigVec[], int n,\n          int nnzA, arcomplex<FLOAT> A[], int irowA[], int pcolA[],\n          int nnzB, arcomplex<FLOAT> B[], int irowB[], int pcolB[],\n          int nev, char* which = \"LM\", int ncv = 0, FLOAT tol = 0.0,\n          int maxit = 0, arcomplex<FLOAT>* resid = 0, bool AutoShift = true)\n{\n\n  // Creating two matrices in ARPACK++ format.\n\n  ARluNonSymMatrix<arcomplex<FLOAT> > matrixA(n, nnzA, A, irowA, pcolA);\n  ARluNonSymMatrix<arcomplex<FLOAT> > matrixB(n, nnzB, B, irowB, pcolB);\n\n  // Defining the eigenvalue problem.\n\n  ARluCompGenEig<FLOAT> prob(nev, matrixA, matrixB, which,\n                             ncv, tol, maxit, resid, AutoShift);\n\n  // Finding eigenvalues and eigenvectors.\n\n  return prob.EigenValVectors(EigVec, EigVal);\n\n} // complex generalized problem, values and vectors, regular mode.\n\n\ntemplate <class FLOAT>\nint AREig(arcomplex<FLOAT> EigVal[], int n, int nnzA, arcomplex<FLOAT> A[],\n          int irowA[], int pcolA[], int nnzB, arcomplex<FLOAT> B[],\n          int irowB[], int pcolB[], arcomplex<FLOAT> sigma, int nev,\n          char* which = \"LM\", int ncv = 0, FLOAT tol = 0.0, int maxit = 0,\n          arcomplex<FLOAT>* resid = 0, bool AutoShift = true)\n{\n\n  // Creating two matrices in ARPACK++ format.\n\n  ARluNonSymMatrix<arcomplex<FLOAT> > matrixA(n, nnzA, A, irowA, pcolA);\n  ARluNonSymMatrix<arcomplex<FLOAT> > matrixB(n, nnzB, B, irowB, pcolB);\n\n  // Defining the eigenvalue problem.\n\n  ARluCompGenEig<FLOAT> prob(nev, matrixA, matrixB, sigma, which,\n                             ncv, tol, maxit, resid, AutoShift);\n\n  // Finding eigenvalues.\n\n  return prob.Eigenvalues(EigVal);\n\n} // complex generalized problem, only eigenvalues, shift-and-invert mode.\n\n\ntemplate <class FLOAT>\nint AREig(arcomplex<FLOAT> EigVal[], arcomplex<FLOAT> EigVec[], int n,\n          int nnzA, arcomplex<FLOAT> A[], int irowA[], int pcolA[],\n          int nnzB, arcomplex<FLOAT> B[], int irowB[], int pcolB[],\n          arcomplex<FLOAT> sigma, int nev, char* which = \"LM\",\n          int ncv = 0, FLOAT tol = 0.0, int maxit = 0,\n          arcomplex<FLOAT>* resid = 0, bool AutoShift = true)\n{\n\n  // Creating two matrices in ARPACK++ format.\n\n  ARluNonSymMatrix<arcomplex<FLOAT> > matrixA(n, nnzA, A, irowA, pcolA);\n  ARluNonSymMatrix<arcomplex<FLOAT> > matrixB(n, nnzB, B, irowB, pcolB);\n\n  // Defining the eigenvalue problem.\n\n  ARluCompGenEig<FLOAT> prob(nev, matrixA, matrixB, sigma, which,\n                             ncv, tol, maxit, resid, AutoShift);\n\n  // Finding eigenvalues and eigenvectors.\n\n  return prob.EigenValVectors(EigVec, EigVal);\n\n} // complex generalized problem, values and vectors, shift-and-invert mode.\n\n\ntemplate <class FLOAT>\nint AREig(double EigValR[], FLOAT EigValI[], int n, int nnz,\n          FLOAT A[], int irow[], int pcol[], int nev, char* which = \"LM\",\n          int ncv = 0, FLOAT tol = 0.0, int maxit = 0, FLOAT* resid = 0,\n          bool AutoShift = true)\n{\n\n  // Creating a matrix in ARPACK++ format.\n\n  ARluNonSymMatrix<FLOAT> matrix(n, nnz, A, irow, pcol);\n\n  // Defining the eigenvalue problem.\n\n  ARluNonSymStdEig<FLOAT> prob(nev, matrix, which, ncv, tol,\n                               maxit, resid, AutoShift);\n\n  // Finding eigenvalues.\n\n  return prob.Eigenvalues(EigValR, EigValI);\n\n} // real nonsymmetric standard problem, only eigenvalues, regular mode.\n\n\ntemplate <class FLOAT>\nint AREig(float EigValR[], FLOAT EigValI[], int n, int nnz,\n          FLOAT A[], int irow[], int pcol[], int nev, char* which = \"LM\",\n          int ncv = 0, FLOAT tol = 0.0, int maxit = 0, FLOAT* resid = 0,\n          bool AutoShift = true)\n{\n\n  // Creating a matrix in ARPACK++ format.\n\n  ARluNonSymMatrix<FLOAT> matrix(n, nnz, A, irow, pcol);\n\n  // Defining the eigenvalue problem.\n\n  ARluNonSymStdEig<FLOAT> prob(nev, matrix, which, ncv, tol,\n                               maxit, resid, AutoShift);\n\n  // Finding eigenvalues.\n\n  return prob.Eigenvalues(EigValR, EigValI);\n\n} // real nonsymmetric standard problem, only eigenvalues, regular mode.\n\n\ntemplate <class FLOAT>\nint AREig(FLOAT EigValR[], FLOAT EigValI[], FLOAT EigVec[], int n, int nnz,\n          FLOAT A[], int irow[], int pcol[], int nev, char* which = \"LM\",\n          int ncv = 0, FLOAT tol = 0.0, int maxit = 0, FLOAT* resid = 0,\n          bool AutoShift = true)\n{\n\n  // Creating a matrix in ARPACK++ format.\n\n  ARluNonSymMatrix<FLOAT> matrix(n, nnz, A, irow, pcol);\n\n  // Defining the eigenvalue problem.\n\n  ARluNonSymStdEig<FLOAT> prob(nev, matrix, which, ncv, tol,\n                               maxit, resid, AutoShift);\n\n  // Finding eigenvalues and eigenvectors.\n\n  return prob.EigenValVectors(EigVec, EigValR, EigValI);\n\n} // real nonsymmetric standard problem, values and vectors, regular mode.\n\n\ntemplate <class FLOAT>\nint AREig(double EigValR[], FLOAT EigValI[], int n, int nnz,\n          FLOAT A[], int irow[], int pcol[], FLOAT sigma, int nev,\n          char* which = \"LM\", int ncv = 0, FLOAT tol = 0.0,\n          int maxit = 0, FLOAT* resid = 0, bool AutoShift = true)\n{\n\n  // Creating a matrix in ARPACK++ format.\n\n  ARluNonSymMatrix<FLOAT> matrix(n, nnz, A, irow, pcol);\n\n  // Defining the eigenvalue problem.\n\n  ARluNonSymStdEig<FLOAT> prob(nev, matrix, sigma, which, ncv,\n                               tol, maxit, resid, AutoShift);\n\n  // Finding eigenvalues.\n\n  return prob.Eigenvalues(EigValR, EigValI);\n\n} // real nonsymmetric standard problem, only eigenvalues, shift-and-invert.\n\n\ntemplate <class FLOAT>\nint AREig(float EigValR[], FLOAT EigValI[], int n, int nnz,\n          FLOAT A[], int irow[], int pcol[], FLOAT sigma, int nev,\n          char* which = \"LM\", int ncv = 0, FLOAT tol = 0.0,\n          int maxit = 0, FLOAT* resid = 0, bool AutoShift = true)\n{\n\n  // Creating a matrix in ARPACK++ format.\n\n  ARluNonSymMatrix<FLOAT> matrix(n, nnz, A, irow, pcol);\n\n  // Defining the eigenvalue problem.\n\n  ARluNonSymStdEig<FLOAT> prob(nev, matrix, sigma, which, ncv,\n                               tol, maxit, resid, AutoShift);\n\n  // Finding eigenvalues.\n\n  return prob.Eigenvalues(EigValR, EigValI);\n\n} // real nonsymmetric standard problem, only eigenvalues, shift-and-invert.\n\n\ntemplate <class FLOAT>\nint AREig(FLOAT EigValR[], FLOAT EigValI[], FLOAT EigVec[], int n, int nnz,\n          FLOAT A[], int irow[], int pcol[], FLOAT sigma, int nev,\n          char* which = \"LM\", int ncv = 0, FLOAT tol = 0.0, int maxit = 0,\n          FLOAT* resid = 0, bool AutoShift = true)\n{\n\n  // Creating a matrix in ARPACK++ format.\n\n  ARluNonSymMatrix<FLOAT> matrix(n, nnz, A, irow, pcol);\n\n  // Defining the eigenvalue problem.\n\n  ARluNonSymStdEig<FLOAT> prob(nev, matrix, sigma, which, ncv,\n                               tol, maxit, resid, AutoShift);\n\n  // Finding eigenvalues and eigenvectors.\n\n  return prob.EigenValVectors(EigVec, EigValR, EigValI);\n\n} // real nonsymmetric standard problem, values and vectors, shift-and-invert.\n\n\ntemplate <class FLOAT>\nint AREig(double EigValR[], FLOAT EigValI[], int n, int nnzA,\n          FLOAT A[], int irowA[], int pcolA[], int nnzB,\n          FLOAT B[], int irowB[], int pcolB[], int nev,\n          char* which = \"LM\", int ncv = 0, FLOAT tol = 0.0,\n          int maxit = 0, FLOAT* resid = 0, bool AutoShift = true)\n{\n\n  // Creating two matrices in ARPACK++ format.\n\n  ARluNonSymMatrix<FLOAT> matrixA(n, nnzA, A, irowA, pcolA);\n  ARluNonSymMatrix<FLOAT> matrixB(n, nnzB, B, irowB, pcolB);\n\n  // Defining the eigenvalue problem.\n\n  ARluNonSymGenEig<FLOAT> prob(nev, matrixA, matrixB, which,\n                               ncv, tol, maxit, resid, AutoShift);\n\n  // Finding eigenvalues.\n\n  return prob.Eigenvalues(EigValR, EigValI);\n\n} // real nonsymmetric generalized problem, only eigenvalues, regular mode.\n\n\ntemplate <class FLOAT>\nint AREig(float EigValR[], FLOAT EigValI[], int n, int nnzA,\n          FLOAT A[], int irowA[], int pcolA[], int nnzB,\n          FLOAT B[], int irowB[], int pcolB[], int nev,\n          char* which = \"LM\", int ncv = 0, FLOAT tol = 0.0,\n          int maxit = 0, FLOAT* resid = 0, bool AutoShift = true)\n{\n\n  // Creating two matrices in ARPACK++ format.\n\n  ARluNonSymMatrix<FLOAT> matrixA(n, nnzA, A, irowA, pcolA);\n  ARluNonSymMatrix<FLOAT> matrixB(n, nnzB, B, irowB, pcolB);\n\n  // Defining the eigenvalue problem.\n\n  ARluNonSymGenEig<FLOAT> prob(nev, matrixA, matrixB, which,\n                               ncv, tol, maxit, resid, AutoShift);\n\n  // Finding eigenvalues.\n\n  return prob.Eigenvalues(EigValR, EigValI);\n\n} // real nonsymmetric generalized problem, only eigenvalues, regular mode.\n\n\ntemplate <class FLOAT>\nint AREig(FLOAT EigValR[], FLOAT EigValI[], FLOAT EigVec[], int n,\n          int nnzA, FLOAT A[], int irowA[], int pcolA[],\n          int nnzB, FLOAT B[], int irowB[], int pcolB[],\n          int nev, char* which = \"LM\", int ncv = 0, FLOAT tol = 0.0,\n          int maxit = 0, FLOAT* resid = 0, bool AutoShift = true)\n{\n\n  // Creating two matrices in ARPACK++ format.\n\n  ARluNonSymMatrix<FLOAT> matrixA(n, nnzA, A, irowA, pcolA);\n  ARluNonSymMatrix<FLOAT> matrixB(n, nnzB, B, irowB, pcolB);\n\n  // Defining the eigenvalue problem.\n\n  ARluNonSymGenEig<FLOAT> prob(nev, matrixA, matrixB, which,\n                               ncv, tol, maxit, resid, AutoShift);\n\n  // Finding eigenvalues and eigenvectors.\n\n  return prob.EigenValVectors(EigVec, EigValR, EigValI);\n\n} // real nonsymmetric generalized problem, values and vectors, regular mode.\n\n\ntemplate <class FLOAT>\nint AREig(double EigValR[], FLOAT EigValI[], int n, int nnzA,\n          FLOAT A[], int irowA[], int pcolA[], int nnzB,\n          FLOAT B[], int irowB[], int pcolB[], FLOAT sigma,\n          int nev, char* which = \"LM\", int ncv = 0, FLOAT tol = 0.0,\n          int maxit = 0, FLOAT* resid = 0, bool AutoShift = true)\n{\n\n  // Creating two matrices in ARPACK++ format.\n\n  ARluNonSymMatrix<FLOAT> matrixA(n, nnzA, A, irowA, pcolA);\n  ARluNonSymMatrix<FLOAT> matrixB(n, nnzB, B, irowB, pcolB);\n\n  // Defining the eigenvalue problem.\n\n  ARluNonSymGenEig<FLOAT> prob(nev, matrixA, matrixB, sigma, which,\n                               ncv, tol, maxit, resid, AutoShift);\n\n  // Finding eigenvalues.\n\n  return prob.Eigenvalues(EigValR, EigValI);\n\n} // real nonsymmetric generalized problem, only eigenvalues,\n  // real shift-and-invert mode.\n\n\ntemplate <class FLOAT>\nint AREig(float EigValR[], FLOAT EigValI[], int n, int nnzA,\n          FLOAT A[], int irowA[], int pcolA[], int nnzB,\n          FLOAT B[], int irowB[], int pcolB[], FLOAT sigma,\n          int nev, char* which = \"LM\", int ncv = 0, FLOAT tol = 0.0,\n          int maxit = 0, FLOAT* resid = 0, bool AutoShift = true)\n{\n\n  // Creating two matrices in ARPACK++ format.\n\n  ARluNonSymMatrix<FLOAT> matrixA(n, nnzA, A, irowA, pcolA);\n  ARluNonSymMatrix<FLOAT> matrixB(n, nnzB, B, irowB, pcolB);\n\n  // Defining the eigenvalue problem.\n\n  ARluNonSymGenEig<FLOAT> prob(nev, matrixA, matrixB, sigma, which,\n                               ncv, tol, maxit, resid, AutoShift);\n\n  // Finding eigenvalues.\n\n  return prob.Eigenvalues(EigValR, EigValI);\n\n} // real nonsymmetric generalized problem, only eigenvalues,\n  // real shift-and-invert mode.\n\n\ntemplate <class FLOAT>\nint AREig(FLOAT EigValR[], FLOAT EigValI[], FLOAT EigVec[], int n,\n          int nnzA, FLOAT A[], int irowA[], int pcolA[], int nnzB,\n          FLOAT B[], int irowB[], int pcolB[], FLOAT sigma, int nev,\n          char* which = \"LM\", int ncv = 0, FLOAT tol = 0.0,\n          int maxit = 0, FLOAT* resid = 0, bool AutoShift = true)\n{\n\n  // Creating two matrices in ARPACK++ format.\n\n  ARluNonSymMatrix<FLOAT> matrixA(n, nnzA, A, irowA, pcolA);\n  ARluNonSymMatrix<FLOAT> matrixB(n, nnzB, B, irowB, pcolB);\n\n  // Defining the eigenvalue problem.\n\n  ARluNonSymGenEig<FLOAT> prob(nev, matrixA, matrixB, sigma, which,\n                               ncv, tol, maxit, resid, AutoShift);\n\n  // Finding eigenvalues and eigenvectors.\n\n  return prob.EigenValVectors(EigVec, EigValR, EigValI);\n\n} // real nonsymmetric generalized problem, values and vectors,\n  // real shift-and-invert mode.\n\n\ntemplate <class FLOAT>\nint AREig(FLOAT EigValR[], FLOAT EigValI[], int n, int nnzA, FLOAT A[],\n          int irowA[], int pcolA[], int nnzB, FLOAT B[], int irowB[],\n          int pcolB[], char part, FLOAT sigmaR, FLOAT sigmaI,\n          int nev, char* which = \"LM\", int ncv = 0, FLOAT tol = 0.0,\n          int maxit = 0, FLOAT* resid = 0, bool AutoShift = true)\n{\n\n  // Creating two matrices in ARPACK++ format.\n\n  ARluNonSymMatrix<FLOAT> matrixA(n, nnzA, A, irowA, pcolA);\n  ARluNonSymMatrix<FLOAT> matrixB(n, nnzB, B, irowB, pcolB);\n\n  // Defining the eigenvalue problem.\n\n  ARluNonSymGenEig<FLOAT> prob(nev, matrixA, matrixB, part,\n                               sigmaR, sigmaI, which, ncv,\n                               tol, maxit, resid, AutoShift);\n\n  // Finding eigenvalues.\n\n  return prob.Eigenvalues(EigValR, EigValI);\n\n} // real nonsymmetric generalized problem, only eigenvalues,\n  // complex shift-and-invert mode.\n\n\ntemplate <class FLOAT>\nint AREig(FLOAT EigValR[], FLOAT EigValI[], FLOAT EigVec[], int n, int nnzA,\n          FLOAT A[], int irowA[], int pcolA[], int nnzB, FLOAT B[],\n          int irowB[], int pcolB[], char part, FLOAT sigmaR, FLOAT sigmaI,\n          int nev, char* which = \"LM\", int ncv = 0, FLOAT tol = 0.0,\n          int maxit = 0, FLOAT* resid = 0, bool AutoShift = true)\n{\n\n  // Creating two matrices in ARPACK++ format.\n\n  ARluNonSymMatrix<FLOAT> matrixA(n, nnzA, A, irowA, pcolA);\n  ARluNonSymMatrix<FLOAT> matrixB(n, nnzB, B, irowB, pcolB);\n\n  // Defining the eigenvalue problem.\n\n  ARluNonSymGenEig<FLOAT> prob(nev, matrixA, matrixB, part,\n                               sigmaR, sigmaI, which, ncv,\n                               tol, maxit, resid, AutoShift);\n\n  // Finding eigenvalues and eigenvectors.\n\n  return prob.EigenValVectors(EigVec, EigValR, EigValI);\n\n} // real nonsymmetric generalized problem, values and vectors,\n  // complex shift-and-invert mode.\n\n\ntemplate <class FLOAT>\nint AREig(FLOAT EigVal[], int n, int nnz, FLOAT A[], int irow[],\n          int pcol[], char uplo, int nev, char* which = \"LM\",\n          int ncv = 0, FLOAT tol = 0.0, int maxit = 0,\n          FLOAT* resid = 0, bool AutoShift = true)\n{\n\n  // Creating a matrix in ARPACK++ format.\n\n  ARluSymMatrix<FLOAT> matrix(n, nnz, A, irow, pcol, uplo);\n\n  // Defining the eigenvalue problem.\n\n  ARluSymStdEig<FLOAT> prob(nev, matrix, which, ncv, tol,\n                            maxit, resid, AutoShift);\n\n  // Finding eigenvalues.\n\n  return prob.Eigenvalues(EigVal);\n\n} // real symmetric standard problem, only eigenvalues, regular mode.\n\n\ntemplate <class FLOAT>\nint AREig(FLOAT EigVal[], FLOAT EigVec[], int n, int nnz, FLOAT A[],\n          int irow[], int pcol[], char uplo, int nev,\n          char* which = \"LM\", int ncv = 0, FLOAT tol = 0.0,\n          int maxit = 0, FLOAT* resid = 0, bool AutoShift = true)\n{\n\n  // Creating a matrix in ARPACK++ format.\n\n  ARluSymMatrix<FLOAT> matrix(n, nnz, A, irow, pcol, uplo);\n\n  // Defining the eigenvalue problem.\n\n  ARluSymStdEig<FLOAT> prob(nev, matrix, which, ncv, tol,\n                            maxit, resid, AutoShift);\n\n  // Finding eigenvalues and eigenvectors.\n\n  return prob.EigenValVectors(EigVec, EigVal);\n\n} // real symmetric standard problem, values and vectors, regular mode.\n\n\ntemplate <class FLOAT>\nint AREig(FLOAT EigVal[], int n, int nnz, FLOAT A[], int irow[],\n          int pcol[], char uplo, FLOAT sigma, int nev,\n          char* which = \"LM\", int ncv = 0, FLOAT tol = 0.0,\n          int maxit = 0, FLOAT* resid = 0, bool AutoShift = true)\n{\n\n  // Creating a matrix in ARPACK++ format.\n\n  ARluSymMatrix<FLOAT> matrix(n, nnz, A, irow, pcol, uplo);\n\n  // Defining the eigenvalue problem.\n\n  ARluSymStdEig<FLOAT> prob(nev, matrix, sigma, which, ncv,\n                            tol, maxit, resid, AutoShift);\n\n  // Finding eigenvalues.\n\n  return prob.Eigenvalues(EigVal);\n\n} // real symmetric standard problem, only eigenvalues, shift-and-invert.\n\n\ntemplate <class FLOAT>\nint AREig(FLOAT EigVal[], FLOAT EigVec[], int n, int nnz, FLOAT A[],\n          int irow[], int pcol[], char uplo, FLOAT sigma,\n          int nev, char* which = \"LM\", int ncv = 0, FLOAT tol = 0.0,\n          int maxit = 0, FLOAT* resid = 0, bool AutoShift = true)\n{\n\n  // Creating a matrix in ARPACK++ format.\n\n  ARluSymMatrix<FLOAT> matrix(n, nnz, A, irow, pcol, uplo);\n\n  // Defining the eigenvalue problem.\n\n  ARluSymStdEig<FLOAT> prob(nev, matrix, sigma, which, ncv,\n                            tol, maxit, resid, AutoShift);\n\n  // Finding eigenvalues and eigenvectors.\n\n  return prob.EigenValVectors(EigVec, EigVal);\n\n} // real symmetric standard problem, values and vectors, shift-and-invert.\n\n\ntemplate <class FLOAT>\nint AREig(FLOAT EigVal[], int n, int nnzA, FLOAT A[], int irowA[],\n          int pcolA[], int nnzB, FLOAT B[], int irowB[], int pcolB[],\n          char uplo, int nev, char* which = \"LM\", int ncv = 0,\n          FLOAT tol = 0.0, int maxit = 0, FLOAT* resid = 0,\n          bool AutoShift = true)\n{\n\n  // Creating two matrices in ARPACK++ format.\n\n  ARluSymMatrix<FLOAT> matrixA(n, nnzA, A, irowA, pcolA, uplo);\n  ARluSymMatrix<FLOAT> matrixB(n, nnzB, B, irowB, pcolB, uplo);\n\n  // Defining the eigenvalue problem.\n\n  ARluSymGenEig<FLOAT> prob(nev, matrixA, matrixB, which,\n                            ncv, tol, maxit, resid, AutoShift);\n\n  // Finding eigenvalues.\n\n  return prob.Eigenvalues(EigVal);\n\n} // real symmetric generalized problem, only eigenvalues, regular mode.\n\n\ntemplate <class FLOAT>\nint AREig(FLOAT EigVal[], FLOAT EigVec[], int n, int nnzA, FLOAT A[],\n          int irowA[], int pcolA[], int nnzB, FLOAT B[], int irowB[],\n          int pcolB[], char uplo, int nev, char* which = \"LM\",\n          int ncv = 0, FLOAT tol = 0.0, int maxit = 0,\n          FLOAT* resid = 0, bool AutoShift = true)\n{\n\n  // Creating two matrices in ARPACK++ format.\n\n  ARluSymMatrix<FLOAT> matrixA(n, nnzA, A, irowA, pcolA, uplo);\n  ARluSymMatrix<FLOAT> matrixB(n, nnzB, B, irowB, pcolB, uplo);\n\n  // Defining the eigenvalue problem.\n\n  ARluSymGenEig<FLOAT> prob(nev, matrixA, matrixB, which,\n                            ncv, tol, maxit, resid, AutoShift);\n\n  // Finding eigenvalues and eigenvectors.\n\n  return prob.EigenValVectors(EigVec, EigVal);\n\n} // real symmetric generalized problem, values and vectors, regular mode.\n\n\ntemplate <class FLOAT>\nint AREig(FLOAT EigVal[], int n, int nnzA, FLOAT A[], int irowA[],\n          int pcolA[], int nnzB, FLOAT B[], int irowB[], int pcolB[],\n          char uplo, char InvertMode, FLOAT sigma, int nev,\n          char* which = \"LM\", int ncv = 0, FLOAT tol = 0.0,\n          int maxit = 0, FLOAT* resid = 0, bool AutoShift = true)\n{\n\n  // Creating two matrices in ARPACK++ format.\n\n  ARluSymMatrix<FLOAT> matrixA(n, nnzA, A, irowA, pcolA, uplo);\n  ARluSymMatrix<FLOAT> matrixB(n, nnzB, B, irowB, pcolB, uplo);\n\n  // Defining the eigenvalue problem.\n\n  ARluSymGenEig<FLOAT> prob(InvertMode, nev, matrixA, matrixB, sigma,\n                            which, ncv, tol, maxit, resid, AutoShift);\n\n  // Finding eigenvalues.\n\n  return prob.Eigenvalues(EigVal);\n\n} // real symmetric generalized problem, only eigenvalues,\n  // shift-and-invert, buckling and Cayley modes.\n\n\ntemplate <class FLOAT>\nint AREig(FLOAT EigVal[], FLOAT EigVec[], int n, int nnzA, FLOAT A[],\n          int irowA[], int pcolA[], int nnzB, FLOAT B[], int irowB[],\n          int pcolB[], char uplo, char InvertMode, FLOAT sigma,\n          int nev, char* which = \"LM\", int ncv = 0, FLOAT tol = 0.0,\n          int maxit = 0, FLOAT* resid = 0, bool AutoShift = true)\n{\n\n  // Creating two matrices in ARPACK++ format.\n\n  ARluSymMatrix<FLOAT> matrixA(n, nnzA, A, irowA, pcolA, uplo);\n  ARluSymMatrix<FLOAT> matrixB(n, nnzB, B, irowB, pcolB, uplo);\n\n  // Defining the eigenvalue problem.\n\n  ARluSymGenEig<FLOAT> prob(InvertMode, nev, matrixA, matrixB, sigma,\n                            which, ncv, tol, maxit, resid, AutoShift);\n\n  // Finding eigenvalues and eigenvectors.\n\n  return prob.EigenValVectors(EigVec, EigVal);\n\n} // real symmetric generalized problem, values and vectors,\n  // shift-and-invert, buckling and Cayley modes.\n\n\n\ntemplate<class FLOAT, class INT>\nvoid SymmetricMatrixA(INT nx, INT& n, INT& nnz, FLOAT* &A, \n                      INT* &irow, INT* &pcol, char uplo = 'L')\n\n{\n\n  // Defining internal variables.\n\n  INT    i, j;\n  FLOAT  h2, df, dd;\n\n  // Defining constants.\n\n  h2  = 1.0/(FLOAT(nx+1)*FLOAT(nx+1));\n  dd  = 4.0/h2;\n  df  = -1.0/h2;\n\n  // Defining the number of columns and nonzero elements of matrix.\n\n  n   = nx*nx;\n  nnz = 3*n-2*nx;\n\n  // Creating output vectors.\n\n  A    = new FLOAT[nnz];\n  irow = new INT[nnz];\n  pcol = new INT[n+1];\n\n  // Defining  matrix A.\n\n  pcol[0] = 0;\n  i       = 0;\n\n  if (uplo == 'U') {\n\n    for (j = 0; j < n; j++) {\n      if (j >= nx) {\n        A[i] = df;   irow[i++] = j-nx;\n      }\n      if ((j%nx) != 0) {\n        A[i] = df;   irow[i++] = j-1;\n      }\n      A[i] = dd;     irow[i++] = j;\n      pcol[j+1] = i;\n    }\n\n  }\n  else {\n\n    for (j = 0; j < n; j++) {\n      A[i] = dd;     irow[i++] = j;\n      if (((j+1)%nx) != 0) {\n        A[i] = df;   irow[i++] = j+1;\n      }\n      if (j < n-nx) {\n        A[i] = df;   irow[i++] = j+nx;\n      }\n      pcol[j+1] = i;\n    }\n\n  }\n\n} // SymmetricMatrixA.\n\r\n\ntemplate<class FLOAT, class INT>\nvoid Solution(INT nconv, INT n, INT nnz, FLOAT A[], INT irow[], INT pcol[],\n              char uplo, FLOAT EigVal[], FLOAT* EigVec = 0)\n/*\n  Prints eigenvalues and eigenvectors of symmetric eigen-problems\n  on standard \"cout\" stream.\n*/\n\n{\n\n  INT                  i;\n  FLOAT*               Ax;\n  FLOAT*               ResNorm;\n  ARluSymMatrix<FLOAT> matrix(n, nnz, A, irow, pcol, uplo);\n\n  cout << endl << endl << \"Testing ARPACK++ function AREig\" << endl;\n  cout << \"Real symmetric eigenvalue problem: A*x - lambda*x \\n \\n\";\n\n  cout << \"Dimension of the system            : \" << n     << endl;\n  cout << \"Number of 'converged' eigenvalues  : \" << nconv << endl << endl;\n\n  // Printing eigenvalues.\n\n  cout << \"Eigenvalues:\" << endl;\n\n  for (i=0; i<nconv; i++) {\n    cout << \"  lambda[\" << (i+1) << \"]: \" << EigVal[i] << endl;\n  }\n  cout << endl;\n\n  // Printing eigenvectors.\n\n  if (EigVec != 0) {\n\n    // Finding the residual norm || A*x - lambda*x ||\n    // for the nconv accurately computed eigenvectors.\n\n    Ax      = new FLOAT[n];\n    ResNorm = new FLOAT[nconv+1];\n\n    for (i=0; i<nconv; i++) {\n      matrix.MultMv(&EigVec[i*n], Ax);\n      axpy(n, -EigVal[i], &EigVec[i*n], 1, Ax, 1);\n      ResNorm[i] = nrm2(n, Ax, 1)/fabs(EigVal[i]);\n    }\n\n    for (i=0; i<nconv; i++) {\n      cout << \"||A*x(\" << (i+1) << \") - lambda(\" << (i+1);\n      cout << \")*x(\" << (i+1) << \")||: \" << ResNorm[i] << endl;\n    }\n    cout << endl;\n\n    delete[] Ax;\n    delete[] ResNorm;\n\n  }\n\n} // Solution.\n\n\ntemplate<class FLOAT, class INT>\nvoid Solution(INT nconv, INT n, INT nnzA, FLOAT A[], INT irowA[],\n              INT pcolA[], INT nnzB, FLOAT B[], INT irowB[], INT pcolB[],\n              char uplo, FLOAT EigVal[], FLOAT* EigVec = 0)\n/*\n  Prints eigenvalues and eigenvectors of symmetric generalized\n  eigen-problem on standard \"cout\" stream.\n*/\n\n{\n\n  INT                  i;\n  FLOAT                *Ax, *Bx;\n  FLOAT                *ResNorm;\n  ARluSymMatrix<FLOAT> matrixA(n, nnzA, A, irowA, pcolA, uplo);\n  ARluSymMatrix<FLOAT> matrixB(n, nnzB, B, irowB, pcolB, uplo);\n\n  cout << endl << endl << \"Testing ARPACK++ function AREig\" << endl;\n  cout << \"Real symmetric generalized eigenvalue problem: A*x - lambda*B*x\";\n  cout << endl << endl;\n\n  cout << \"Dimension of the system            : \" << n     << endl;\n  cout << \"Number of 'converged' eigenvalues  : \" << nconv << endl << endl;\n\n  // Printing eigenvalues.\n\n  cout << \"Eigenvalues:\" << endl;\n\n  for (i=0; i<nconv; i++) {\n    cout << \"  lambda[\" << (i+1) << \"]: \" << EigVal[i] << endl;\n  }\n  cout << endl;\n\n  // Printing eigenvectors.\n\n  if (EigVec != 0) {\n\n    // Printing the residual norm || A*x - lambda*B*x ||\n    // for the nconv accurately computed eigenvectors.\n\n    Ax      = new FLOAT[n];\n    Bx      = new FLOAT[n];\n    ResNorm = new FLOAT[nconv+1];\n\n    for (i=0; i<nconv; i++) {\n      matrixA.MultMv(&EigVec[i*n], Ax);\n      matrixB.MultMv(&EigVec[i*n], Bx);\n      axpy(n, -EigVal[i], Bx, 1, Ax, 1);\n      ResNorm[i] = nrm2(n, Ax, 1)/fabs(EigVal[i]);\n    }\n\n    for (i=0; i<nconv; i++) {\n      cout << \"||A*x(\" << i << \") - lambda(\" << i;\n      cout << \")*B*x(\" << i << \")||: \" << ResNorm[i] << endl;\n    }\n    cout << endl;\n\n    delete[] Ax;\n    delete[] Bx;\n    delete[] ResNorm;\n\n  }\n\n} // Solution.\n\n\r\n\r\nvoid\r\ncheck_eigen_solve()\r\n{\r\n\tcout << \"******* check_eigen_solve()\" << endl;\r\n\r\n\tint     nx;\n\tint     n;           // Dimension of the problem.\n\tint     nconv;       // Number of \"converged\" eigenvalues.\n\tint     nnz;         // Number of nonzero elements in A.\n\tint*    irow;        // pointer to an array that stores the row\n\t// indices of the nonzeros in A.\n\tint*    pcol;        // pointer to an array of pointers to the\n\t// beginning of each column of A in vector A.\n\tdouble* A;           // pointer to an array that stores the\n\t// nonzero elements of A.\n\tdouble EigVal[101];  // Eigenvalues.\n\tdouble EigVec[1001]; // Eigenvectors stored sequentially.\n\tchar    uplo;        // Variable that indicates whether the upper\n\t// (uplo='U') ot the lower (uplo='L') part of\n\t// A will be stored in A, irow and pcol.\n\n\t// Creating a 100x100 matrix.\n\n\tnx = 10;\n\tuplo = 'U';\n\tSymmetricMatrixA(nx, n, nnz, A, irow, pcol, uplo);\n\n\t// Finding the four eigenvalues with smallest magnitude and\n\t// the related eigenvectors.\n\n\tnconv = AREig(EigVal, EigVec, n, nnz, A, irow, pcol, uplo, 4, \"SM\");\n\n\t// Printing solution.\n\n\tSolution(nconv, n, nnz, A, irow, pcol, uplo, EigVal, EigVec);\n}\r\n\r\n\r\nvoid\r\nregister_eigen_solve_tests( boost::unit_test::test_suite * test )\r\n{\r\n\ttest->add( BOOST_TEST_CASE( &check_eigen_solve ), 0);\r\n}\r\n", "meta": {"hexsha": "e2431779b65b05da70fd9e63c9f1df94119bba21", "size": 30367, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "C++/test/check_eigen_solve.cpp", "max_stars_repo_name": "JohnReid/biopsy", "max_stars_repo_head_hexsha": "1eeb714ba5b53f2ecf776d865d32e2078cbc0338", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "C++/test/check_eigen_solve.cpp", "max_issues_repo_name": "JohnReid/biopsy", "max_issues_repo_head_hexsha": "1eeb714ba5b53f2ecf776d865d32e2078cbc0338", "max_issues_repo_licenses": ["MIT"], "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++/test/check_eigen_solve.cpp", "max_forks_repo_name": "JohnReid/biopsy", "max_forks_repo_head_hexsha": "1eeb714ba5b53f2ecf776d865d32e2078cbc0338", "max_forks_repo_licenses": ["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.0961347869, "max_line_length": 78, "alphanum_fraction": 0.6178417361, "num_tokens": 9336, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149978955811, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.49969551649868293}}
{"text": "#pragma once\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\nint calculateInt()\n{\n    int number = 22;\n    for (int i=1; i<20; ++i)\n    {\n        number = i * number / 4;\n    }\n    return number;\n}\n\nEigen::Vector3f calculateVec()\n{\n    auto x = Eigen::Vector3f{1, 0, 0};\n    auto y = Eigen::Vector3f{0, 1, 0};\n    return x.cross(y);\n}", "meta": {"hexsha": "fd51589e8248e3018db6c716a8963535e8752d75", "size": 333, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/mini-project/include/smallfunctions.hpp", "max_stars_repo_name": "thautwarm/clang-build", "max_stars_repo_head_hexsha": "79cc6bd8e17a328d9e6a0fbdada2ba88600423aa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-02-28T10:16:43.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-08T22:12:45.000Z", "max_issues_repo_path": "test/mini-project/include/smallfunctions.hpp", "max_issues_repo_name": "thautwarm/clang-build", "max_issues_repo_head_hexsha": "79cc6bd8e17a328d9e6a0fbdada2ba88600423aa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 23.0, "max_issues_repo_issues_event_min_datetime": "2018-02-25T21:46:37.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-09T20:47:15.000Z", "max_forks_repo_path": "test/mini-project/include/smallfunctions.hpp", "max_forks_repo_name": "thautwarm/clang-build", "max_forks_repo_head_hexsha": "79cc6bd8e17a328d9e6a0fbdada2ba88600423aa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.8571428571, "max_line_length": 38, "alphanum_fraction": 0.5615615616, "num_tokens": 112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.49969550416435493}}
{"text": "#include <iostream>\n#include <chrono>\n#include <boost/numeric/bindings/lapack/lapack.h>\n#include <boost/numeric/bindings/blas/blas.h>\n#include <algorithm>\n\n  int cc_find_new_j(double val [],\n          int vct,\n          double as [],\n          int nas,\n          double tol,\n          double res []);\n  \n  \n  void cc_solve_stomp(\n          double * a,\n          double * y,\n          int * asize,\n          int * ressize,\n\t  double OptTol,\n\t  int maxIters,\n          int *niter,\n          int *naSet,\n          double *asol,\n\t  double *activeSet,\n\t  double *aresult);\n   \n  double cmeana_ms(double * vals, int size,double * res);\n  ", "meta": {"hexsha": "0f1355af65daf74208e9eaa2069de6220f46a8f7", "size": 632, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "swinzip-v2.0/src/StOMP/ccstomp.hpp", "max_stars_repo_name": "msalloum80/SWinzip", "max_stars_repo_head_hexsha": "5d43e9f11776d513218b891683b7aa00b36fae23", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-17T07:58:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-17T07:58:23.000Z", "max_issues_repo_path": "swinzip-v2.5/src/StOMP/ccstomp.hpp", "max_issues_repo_name": "msalloum80/SWinzip", "max_issues_repo_head_hexsha": "5d43e9f11776d513218b891683b7aa00b36fae23", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "swinzip-v2.5/src/StOMP/ccstomp.hpp", "max_forks_repo_name": "msalloum80/SWinzip", "max_forks_repo_head_hexsha": "5d43e9f11776d513218b891683b7aa00b36fae23", "max_forks_repo_licenses": ["BSD-3-Clause"], "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": 21.7931034483, "max_line_length": 57, "alphanum_fraction": 0.5553797468, "num_tokens": 160, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.49969549409500735}}
{"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_EXPONENTIAL_FUNCTIONS_GENERIC_POW2_HPP_INCLUDED\n#define NT2_EXPONENTIAL_FUNCTIONS_GENERIC_POW2_HPP_INCLUDED\n\n#include <nt2/exponential/functions/pow2.hpp>\n#include <boost/assert.hpp>\n#include <boost/simd/sdk/config.hpp>\n#include <nt2/include/constants/one.hpp>\n#include <nt2/include/functions/simd/fast_ldexp.hpp>\n#include <nt2/include/functions/simd/toint.hpp>\n\n#ifndef BOOST_SIMD_NO_INVALIDS\n#include <boost/simd/operator/functions/details/assert_utils.hpp>\n#include <nt2/include/functions/simd/is_finite.hpp>\n#endif\n\nnamespace nt2 { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT  ( pow2_, tag::cpu_\n                            , (A0)(A1)\n                            , (generic_< floating_<A0> >)\n                              (generic_< integer_<A1> >)\n                            )\n  {\n    typedef A0 result_type;\n\n    NT2_FUNCTOR_CALL(2)\n    {\n      return nt2::fast_ldexp(a0, a1);\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  ( pow2_, tag::cpu_\n                            , (A0)\n                            , (generic_< floating_<A0> >)\n                              (generic_< floating_<A0> >)\n                            )\n  {\n\n    typedef A0 result_type;\n\n    NT2_FUNCTOR_CALL_REPEAT(2)\n    {\n      #ifndef BOOST_SIMD_NO_INVALIDS\n      BOOST_ASSERT_MSG(boost::simd::assert_all(is_finite(a1)),\n                       \"pow2 is not defined for an invalid second parameter\");\n      #endif\n      return nt2::fast_ldexp(a0, nt2::toint(a1));\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  ( pow2_, tag::cpu_\n                            , (A0)(A1)\n                            , (generic_< integer_<A0> >)\n                              (generic_< integer_<A1> >)\n                            )\n  {\n\n    typedef A0 result_type;\n\n    NT2_FUNCTOR_CALL_REPEAT(2)\n    {\n      return nt2::fast_ldexp(a0, a1);\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  ( pow2_, tag::cpu_\n                            , (A0)\n                            , (generic_< integer_<A0> >)\n                            )\n  {\n\n    typedef A0 result_type;\n\n    NT2_FUNCTOR_CALL_REPEAT(1)\n    {\n      return nt2::fast_ldexp(One<A0>(), a0);\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  ( pow2_, tag::cpu_\n                            , (A0)\n                            , (generic_< floating_<A0> >)\n                            )\n  {\n\n    typedef A0 result_type;\n\n    NT2_FUNCTOR_CALL_REPEAT(1)\n    {\n      #ifndef BOOST_SIMD_NO_INVALIDS\n      BOOST_ASSERT_MSG(boost::simd::assert_all(is_finite(a0)),\n                       \"pow2 with one parameter is not defined for an invalid entry\");\n      #endif\n      return nt2::fast_ldexp(One<A0>(), toint(a0));\n    }\n  };\n} }\n\n#endif\n", "meta": {"hexsha": "78f84418f6079cfe4268b7e419541a64c6058edd", "size": 3129, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/exponential/include/nt2/exponential/functions/generic/pow2.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/exponential/include/nt2/exponential/functions/generic/pow2.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/exponential/include/nt2/exponential/functions/generic/pow2.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": 28.9722222222, "max_line_length": 86, "alphanum_fraction": 0.5170981144, "num_tokens": 733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.661922862511608, "lm_q1q2_score": 0.4996954890603335}}
{"text": "/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n#include <cmath>\n#include <iostream>\n\n#include <lagrange/testing/common.h>\n\n#include <Eigen/Geometry>\n\n#include <lagrange/common.h>\n#include <lagrange/compute_mesh_covariance.h>\n#include <lagrange/create_mesh.h>\n#include <lagrange/utils/safe_cast.h>\n\nTEST_CASE(\"ComputeMeshCovariance\", \"[mesh][covariance]\")\n{\n    using namespace lagrange;\n\n    Vertices3D ref_vertices(6 + 3, 3);\n    Triangles facets(4 + 1, 3);\n\n    const double a = 0.5;\n    const double b = 2.0;\n    const double large_number = 1000;\n\n    ref_vertices.row(0) << -a / 2., -b / 2., 0;\n    ref_vertices.row(1) << +a / 2., -b / 2., 0;\n    ref_vertices.row(2) << +a / 2., 0, 0;\n    ref_vertices.row(3) << +a / 2., b / 4., 0;\n    ref_vertices.row(4) << +a / 2., b / 2., 0;\n    ref_vertices.row(5) << -a / 2., b / 2., 0;\n    // Don't include in computation\n    ref_vertices.row(6) << large_number, large_number, large_number;\n    ref_vertices.row(7) << -large_number, -large_number, -large_number;\n    ref_vertices.row(8) << 2 * large_number, 2 * large_number, 2 * large_number;\n\n\n    facets.row(0) << 0, 1, 2;\n    // Don't include in computation\n    facets.row(1) << 6, 7, 8;\n    //\n    facets.row(2) << 0, 2, 3;\n    facets.row(3) << 0, 3, 4;\n    facets.row(4) << 0, 4, 5;\n\n    // Reference values without transformations\n    const double ref_area = a * b;\n    Eigen::Vector3d ref_center(0, 0, 0);\n    Eigen::Matrix3d ref_covariance = Eigen::Matrix3d::Zero();\n    ref_covariance(0, 0) = b * a * a * a / 12.;\n    ref_covariance(1, 1) = a * b * b * b / 12.;\n\n    // Translate\n    // Eigen::Vector3d tr(0,0,0);\n    Eigen::Vector3d tr(-1, 3, 4);\n\n    // Rotate\n    // Eigen::Matrix3d rot = Eigen::Matrix3d::Identity();\n    Eigen::Matrix3d rot =\n        Eigen::AngleAxisd(1.2365, Eigen::Vector3d(-1, 2, 5.1).normalized()).toRotationMatrix();\n    Eigen::Matrix3d rot_covariance = rot * ref_covariance * rot.transpose();\n    Eigen::Matrix3d rot_covariance_tr = rot_covariance + ref_area * tr * tr.transpose();\n\n    // Create the vertices\n    Vertices3D vertices = (ref_vertices * rot.transpose()).rowwise() + tr.transpose();\n\n    auto mesh_unique = lagrange::create_mesh(vertices, facets);\n    auto out_covariance_at_zero =\n        compute_mesh_covariance(*mesh_unique, Eigen::RowVector3d::Zero(), {0, 2, 3, 4});\n    auto out_covariance_at_centroid =\n        compute_mesh_covariance(*mesh_unique, tr.transpose(), {0, 2, 3, 4});\n\n    CHECK((out_covariance_at_zero - rot_covariance_tr).norm() == Approx(0.).margin(1e-10));\n    CHECK((out_covariance_at_centroid - rot_covariance).norm() == Approx(0.).margin(1e-10));\n\n    // std::cout << out_covariance_at_zero.covariance << std::endl;\n    // std::cout << rot_covariance_tr << std::endl;\n\n\n} // end of TEST\n", "meta": {"hexsha": "1c5bf103f45115cd4f7e7173c097f8dbac7a96b2", "size": 3330, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/core/tests/test_compute_mesh_covariance.cpp", "max_stars_repo_name": "LaudateCorpus1/lagrange", "max_stars_repo_head_hexsha": "2a49d3ee93c1f1e712c93c5c87ea25b9a83c8f40", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 156.0, "max_stars_repo_stars_event_min_datetime": "2021-01-08T19:53:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T18:32:52.000Z", "max_issues_repo_path": "modules/core/tests/test_compute_mesh_covariance.cpp", "max_issues_repo_name": "LaudateCorpus1/lagrange", "max_issues_repo_head_hexsha": "2a49d3ee93c1f1e712c93c5c87ea25b9a83c8f40", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-01-11T20:18:07.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-04T15:53:57.000Z", "max_forks_repo_path": "modules/core/tests/test_compute_mesh_covariance.cpp", "max_forks_repo_name": "LaudateCorpus1/lagrange", "max_forks_repo_head_hexsha": "2a49d3ee93c1f1e712c93c5c87ea25b9a83c8f40", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2021-01-11T21:03:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-24T06:27:44.000Z", "avg_line_length": 37.0, "max_line_length": 95, "alphanum_fraction": 0.657957958, "num_tokens": 1012, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825007, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.4996914303276552}}
{"text": "/*\n@copyright Louis Dionne 2014\nDistributed under the Boost Software License, Version 1.0.\n(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n */\n\n#include <boost/hana/detail/assert.hpp>\n#include <boost/hana/detail/constexpr.hpp>\n#include <boost/hana/functional.hpp>\n#include <boost/hana/list/instance.hpp>\nusing namespace boost::hana;\n\n\nint main() {\n    //! [main]\n    BOOST_HANA_CONSTEXPR_LAMBDA auto is_permutation_of = curry<2>([](auto xs, auto perm) {\n        return elem(permutations(xs), perm);\n    });\n\n    BOOST_HANA_CONSTEXPR_ASSERT(\n        all(\n            list(\n                list('1', 2, 3.0),\n                list('1', 3.0, 2),\n                list(2, '1', 3.0),\n                list(2, 3.0, '1'),\n                list(3.0, '1', 2),\n                list(3.0, 2, '1')\n            ),\n            is_permutation_of(list('1', 2, 3.0))\n        )\n    );\n    //! [main]\n}\n", "meta": {"hexsha": "60baecd7afed5023868e459712f696b4298e7f0c", "size": 910, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/list/permutations.cpp", "max_stars_repo_name": "rbock/hana", "max_stars_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-05-07T14:29:13.000Z", "max_stars_repo_stars_event_max_datetime": "2015-07-04T10:59:46.000Z", "max_issues_repo_path": "example/list/permutations.cpp", "max_issues_repo_name": "rbock/hana", "max_issues_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/list/permutations.cpp", "max_forks_repo_name": "rbock/hana", "max_forks_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.0, "max_line_length": 90, "alphanum_fraction": 0.5494505495, "num_tokens": 257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.4996914237749792}}
{"text": "#include <iostream>\n#include <fstream>\n#include <Eigen/Dense>\n#include <unsupported/Eigen/FFT>\n#include <gravitysolvers.hpp>\n\n// ************************************************************************* //\n// ******************************** DATA IO ******************************** //\n// ************************************************************************* //\n\nGravitysolver::DataIO::DataIO()\n{\n  epsilon = 0.0;\n}\n\nbool Gravitysolver::DataIO::readDataOld(const std::string &filename)\n{\n  std::ifstream infile(filename);\n  int numParticles, numGasParticles, numStarParticles;\n\n  if(infile.is_open()) {\n    infile >> numParticles >> numGasParticles >> numStarParticles;\n\n    particles = Eigen::MatrixXf::Zero(MATRIX_DATA_ROWS, numParticles);\n\n    for(int i = 0; i < numParticles; i++) {\n      infile >> particles(0, i); // m\n    }\n\n    for(int i = 0; i < numParticles; i++) {\n      infile >> particles(1, i); // x\n    }\n\n    for(int i = 0; i < numParticles; i++) {\n      infile >> particles(2, i); // y\n    }\n\n    for(int i = 0; i < numParticles; i++) {\n      infile >> particles(3, i); // z\n    }\n\n    for(int i = 0; i < numParticles; i++) {\n      infile >> particles(4, i); // vx\n    }\n\n    for(int i = 0; i < numParticles; i++) {\n      infile >> particles(5, i); // vy\n    }\n\n    for(int i = 0; i < numParticles; i++) {\n      infile >> particles(6, i); // vz\n    }\n\n    return true;\n  }\n\n  std::cout << \"Gravitysolver::DataIO::readDataOld(\\\"\" << filename << \"\\\") \" << \"could not read file\" << std::endl;\n  return false;\n}\n\nbool Gravitysolver::DataIO::readData(const std::string &filename)\n{\n  std::ifstream infile(filename);\n  int N;\n\n  if(infile.is_open()) {\n    infile >> N >> epsilon;\n    particles = Eigen::MatrixXf::Zero(MATRIX_DATA_ROWS, N);\n\n    float m, x, y, z, vx, vy, vz, fx, fy, fz;\n\n    for(int j = 0; j < N; j++) {\n      infile >> m >> x >> y >> z >> vx >> vy >> vz >> fx >> fy >> fz;\n      particles(0, j) = m;\n      particles(1, j) = x;\n      particles(2, j) = y;\n      particles(3, j) = z;\n      particles(4, j) = vx;\n      particles(5, j) = vy;\n      particles(6, j) = vz;\n      particles(7, j) = fx;\n      particles(8, j) = fy;\n      particles(9, j) = fz;\n    }\n\n    return true;\n  }\n\n  std::cout << \"Gravitysolver::DataIO::readData(\\\"\" << filename << \"\\\") \" << \"could not read file\" << std::endl;\n  return false;\n}\n\nbool Gravitysolver::DataIO::writeData(const std::string &filename)\n{\n  std::ofstream outfile(filename);\n  int N = particles.cols();\n\n  if(outfile.is_open()) {\n    outfile << N << \" \" << epsilon << \"\\n\";\n\n    for(int j = 0; j < N; j++) {\n      outfile << particles(0, j) << \"\\n\"; // m\n      outfile << particles(1, j) << \"\\n\"; // x\n      outfile << particles(2, j) << \"\\n\"; // y\n      outfile << particles(3, j) << \"\\n\"; // z\n      outfile << particles(4, j) << \"\\n\"; // vx\n      outfile << particles(5, j) << \"\\n\"; // vy\n      outfile << particles(6, j) << \"\\n\"; // vz\n      outfile << particles(7, j) << \"\\n\"; // fx\n      outfile << particles(8, j) << \"\\n\"; // fy\n      outfile << particles(9, j) << \"\\n\"; // fz\n    }\n\n    return true;\n  }\n\n  std::cout << \"Gravitysolver::DataIO::writeData(\\\"\" << filename << \"\\\") \" << \"could not write file\" << std::endl;\n  return false;\n}\n\n// ************************************************************************* //\n// ***************************** DIRECT SOLVER ***************************** //\n// ************************************************************************* //\n\nGravitysolver::Direct::Direct()\n{\n\n}\n\nfloat Gravitysolver::Direct::softening()\n{\n  return epsilon;\n}\n\nvoid Gravitysolver::Direct::setSoftening(float eps)\n{\n  epsilon = eps;\n}\n\nvoid Gravitysolver::Direct::solve()\n{\n  for(int i = 0; i < particles.cols(); i++) {\n    particles(7, i) = .0;\n    particles(8, i) = .0;\n    particles(9, i) = .0;\n  }\n\n  float mi, mj, dx, dy, dz, sqrtInvDist, sqrtInvDist3, fx, fy, fz;\n\n  for(int i = 0; i < particles.cols(); i++) {\n    for(int j = i + 1; j < particles.cols(); j++) {\n      mi = particles(0, i);\n      mj = particles(0, j);\n      dx = particles(1, i) - particles(1, j);\n      dy = particles(2, i) - particles(2, j);\n      dz = particles(3, i) - particles(3, j);\n\n      sqrtInvDist = 1.0 / std::sqrt(dx * dx + dy * dy + dz * dz + epsilon * epsilon);\n      sqrtInvDist3 = sqrtInvDist * sqrtInvDist * sqrtInvDist;\n\n      // Assumption: G = 1\n      fx = -mi * mj * dx * sqrtInvDist3;\n      fy = -mi * mj * dy * sqrtInvDist3;\n      fz = -mi * mj * dz * sqrtInvDist3;\n\n      particles(7, i) += fx;\n      particles(8, i) += fy;\n      particles(9, i) += fz;\n      particles(7, j) -= fx;\n      particles(8, j) -= fy;\n      particles(9, j) -= fz;\n    }\n  }\n}\n\nconst MatrixData &Gravitysolver::Direct::data()\n{\n  return particles;\n}\n\n// ************************************************************************* //\n// ******************************* PM SOLVER ******************************* //\n// ************************************************************************* //\n\nGravitysolver::PM::PM(int numGridCells)\n{\n  // The Tensor in Eigen experiences a strange case of std::bad_alloc()\n  // if it has more than 776 = 2*388 complex valued elements per dimension\n  if(numGridCells > 0 && numGridCells <= 388) {\n    Ng = numGridCells;\n  }\n  else {\n    std::cout << \"Gravitysolver::PM::PM(\" << numGridCells << \") numGridCells must be > 0\" << std::endl;\n    Ng = 1;\n  }\n\n  h = .0;\n}\n\n/**\n* Returns indices for a mesh cell for the galaxy given world coordinates.\n* World coordinates have the center of the galaxy at (0, 0, 0).\n* The mapping to grid coordinates is an affine mapping where the galaxy center\n* (0, 0, 0) is in the center of the mesh as well.\n*/\nVector3i Gravitysolver::PM::worldToGrid(float x, float y, float z)\n{\n  Vector3i gridCoor;\n\n  gridCoor(0) = std::floor((x + (worldLen / 2)) / worldLen * Ng);\n  gridCoor(1) = std::floor((y + (worldLen / 2)) / worldLen * Ng);\n  gridCoor(2) = std::floor((z + (worldLen / 2)) / worldLen * Ng);\n\n  return gridCoor;\n}\n\n/**\n* Returns position at the center of a mesh cell in world coordinates given cell indices\n* The position is mapped in a fashin such that (0, 0, 0) is the center of the galaxy\n* in world coordinates.\n*/\nVector3f Gravitysolver::PM::gridToWorld(int i, int j, int k)\n{\n  Vector3f worldCoor;\n\n  worldCoor(0) = (i * worldLen / Ng) - (worldLen / 2) + (h / 2);\n  worldCoor(1) = (j * worldLen / Ng) - (worldLen / 2) + (h / 2);\n  worldCoor(2) = (k * worldLen / Ng) - (worldLen / 2) + (h / 2);\n\n  return worldCoor;\n}\n\nvoid Gravitysolver::PM::fft3d(FieldTensorCF &t)\n{\n  const int x = t.dimension(0);\n  const int y = t.dimension(1);\n  const int z = t.dimension(2);\n\n  Eigen::FFT<float> fft;\n\n  for(int k = 0; k < z; k++) { // for each 2d sheet make a 2d fft\n    for(int j = 0; j < y; j++) { // fft in x-dir\n      VectorXcf tv(x);\n      for(int i = 0; i < x; i++)\n          tv(i) = t(i, j, k);\n\n      VectorXcf fv = fft.fwd(tv);\n      for(int i = 0; i < x; i++)\n          t(i, j, k) = fv(i);\n    }\n\n    for(int i = 0; i < x; i++) { // fft in y-dir\n      VectorXcf tv(y);\n      for(int j = 0; j < y; j++)\n          tv(j) = t(i, j, k);\n\n      VectorXcf fv = fft.fwd(tv);\n      for(int j = 0; j < y; j++)\n          t(i, j, k) = fv(j);\n    }\n  }\n\n  for(int i = 0; i < x; i++) { // and for each of the x*y spikes pointing upwards in z-dir do a 1D fft\n    for(int j = 0; j < y; j++) {\n\n      VectorXcf tv(z);\n      for(int k = 0; k < z; k++)\n        tv(k) = t(i, j, k);\n\n      VectorXcf fv = fft.fwd(tv);\n      for(int k = 0; k < z; k++)\n        t(i, j, k) = fv(k);\n    }\n  }\n}\n\nvoid Gravitysolver::PM::ifft3d(FieldTensorCF &t)\n{\n  const int x = t.dimension(0);\n  const int y = t.dimension(1);\n  const int z = t.dimension(2);\n\n  const float invXYZ = 1.0 / (x*y*z);\n\n  for(int i = 0; i < x; i++) {\n    for(int j = 0; j < y; j++) {\n      for(int k = 0; k < z; k++) {\n        t(i,j,k) = std::conj(t(i,j,k));\n      }\n    }\n  }\n\n  fft3d(t);\n\n  for(int i = 0; i < x; i++) {\n    for(int j = 0; j < y; j++) {\n      for(int k = 0; k < z; k++) {\n        t(i,j,k) = std::conj(t(i,j,k)) * invXYZ;\n      }\n    }\n  }\n}\n\nvoid Gravitysolver::PM::conv3d(FieldTensorCF &out, FieldTensorCF &in, FieldTensorCF &kernel)\n{\n  int x = in.dimension(0);\n  int y = in.dimension(1);\n  int z = in.dimension(2);\n\n  fft3d(in);\n  fft3d(kernel);\n\n  for(int i = 0; i < x; i++) {\n    for(int j = 0; j < y; j++) {\n      for(int k = 0; k < z; k++) {\n        out(i,j,k) = in(i,j,k) * kernel(i,j,k);\n      }\n    }\n  }\n\n  ifft3d(out);\n}\n\nvoid Gravitysolver::PM::solve()\n{\n  const int N = particles.cols();\n  Vector3f maxPos = particles.block(1, 0, 3, N).rowwise().maxCoeff();\n  Vector3f minPosAbs = particles.block(1, 0, 3, N).rowwise().minCoeff().cwiseAbs();\n\n  worldLen = std::max(maxPos.maxCoeff(), minPosAbs.maxCoeff()) * 2;\n\n  // adds one layer of cells in each dimension so particles at the edge will\n  // contribute with their entire mass to the density field\n  worldLen += (worldLen / Ng);\n  h = worldLen / Ng;\n\n  std::cout << \"PM solver global parameters\" << std::endl;\n  std::cout << \"---------------------------\" << std::endl;\n  std::cout << \"worldLen:   \" << worldLen << std::endl;\n  std::cout << \"Ng:         \" << Ng << std::endl;\n  std::cout << \"h:          \" << h << std::endl;\n  std::cout << \"---------------------------\" << std::endl;\n\n  density.resize(2*Ng, 2*Ng, 2*Ng);\n  greenFunction.resize(2*Ng, 2*Ng, 2*Ng);\n  potential.resize(2*Ng, 2*Ng, 2*Ng);\n\n  ax.resize(Ng, Ng, Ng);\n  ay.resize(Ng, Ng, Ng);\n  az.resize(Ng, Ng, Ng);\n\n  // density field construction\n  for(int col = 0; col < particles.cols(); col++) {\n    float m = particles(0, col);\n    float px = particles(1, col);\n    float py = particles(2, col);\n    float pz = particles(3, col);\n\n    // (NGP)\n    Vector3i ti = worldToGrid(px, py, pz);\n    density(ti(0), ti(1), ti(2)) += (m / (h*h*h));\n  }\n\n  // green's function construction\n  for(int i = 0; i < Ng; i++) {\n    for(int j = 0; j < Ng; j++) {\n      for(int k = 0; k < Ng; k++) {\n        Vector3f worldPos = gridToWorld(i, j, k);\n\n        // Assumption: G = 1\n        float res = -1.0 / worldPos.norm();\n\n        // make the function symmetric accross all axes\n        greenFunction(i,               j,            k) = res;\n        greenFunction(i,               j,     2*Ng-k-1) = res;\n        greenFunction(i,        2*Ng-j-1,            k) = res;\n        greenFunction(i,        2*Ng-j-1,     2*Ng-k-1) = res;\n        greenFunction(2*Ng-i-1,        j,            k) = res;\n        greenFunction(2*Ng-i-1,        j,     2*Ng-k-1) = res;\n        greenFunction(2*Ng-i-1, 2*Ng-j-1,            k) = res;\n        greenFunction(2*Ng-i-1, 2*Ng-j-1,     2*Ng-k-1) = res;\n      }\n    }\n  }\n\n  // solve the poisson equation to get the potential\n  conv3d(potential, density, greenFunction);\n\n  // calculate acceleration field from potential\n  for(int i = 1; i < Ng - 1; i++) {\n    for(int j = 1; j < Ng - 1; j++) {\n      for(int k = 1; k < Ng - 1; k++) {\n        ax(i, j, k) = -(potential(i+1,j,k).real() - potential(i-1,j,k).real()) / (2*h);\n        ay(i, j, k) = -(potential(i,j+1,k).real() - potential(i,j-1,k).real()) / (2*h);\n        az(i, j, k) = -(potential(i,j,k+1).real() - potential(i,j,k-1).real()) / (2*h);\n      }\n    }\n  }\n\n  // interpolate acceleration field back from mesh to particles\n  for(int col = 0; col < particles.cols(); col++) {\n    float m = particles(0, col);\n    float px = particles(1, col);\n    float py = particles(2, col);\n    float pz = particles(3, col);\n\n    // (NGP)\n    Vector3i ti = worldToGrid(px, py, pz);\n\n    // F = m*a\n    particles(7, col) = m * ax(ti(0), ti(1), ti(2));\n    particles(8, col) = m * ay(ti(0), ti(1), ti(2));\n    particles(9, col) = m * az(ti(0), ti(1), ti(2));\n  }\n}\n\nconst MatrixData &Gravitysolver::PM::data()\n{\n  return particles;\n}\n", "meta": {"hexsha": "7d248a2145d586756baf4afab8bf0103be5ab9b5", "size": 11723, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/gravitysolvers.cpp", "max_stars_repo_name": "azurite/AST-245-N-Body", "max_stars_repo_head_hexsha": "cc3e3acd61f62415c1e5f40c8aba5b93703837fa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/gravitysolvers.cpp", "max_issues_repo_name": "azurite/AST-245-N-Body", "max_issues_repo_head_hexsha": "cc3e3acd61f62415c1e5f40c8aba5b93703837fa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gravitysolvers.cpp", "max_forks_repo_name": "azurite/AST-245-N-Body", "max_forks_repo_head_hexsha": "cc3e3acd61f62415c1e5f40c8aba5b93703837fa", "max_forks_repo_licenses": ["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.8456057007, "max_line_length": 115, "alphanum_fraction": 0.5033694447, "num_tokens": 3722, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.4996914237749792}}
{"text": "#pragma once\n#include <memory>\n#include <Eigen/Dense>\n#include \"Bound3Intersect.hpp\"\n#include \"../Ray.hpp\"\n\nclass Bound3\n{\npublic:\n    Bound3(Eigen::Vector3f min, Eigen::Vector3f max) : _min(min), _max(max){};\n\n    Bound3Intersect intersect_ray(const Ray &ray) const\n    {\n        const auto &origin = ray.get_origin();\n        const auto &dir = ray.get_direction();\n\n        auto tIn = (_min - origin).cwiseQuotient(dir).minCoeff();\n        auto tOut = (_max - origin).cwiseQuotient(dir).maxCoeff();\n\n        if (tIn < std::numeric_limits<float>::epsilon())\n            return Bound3Intersect(0.0f, tOut);\n\n        if (tOut - tIn > -std::numeric_limits<float>::epsilon())\n            return Bound3Intersect(tIn, tOut);\n\n        return Bound3Intersect();\n    };\n\n    static std::unique_ptr<Bound3> union_bound3(const std::unique_ptr<Bound3> &box1, const std::unique_ptr<Bound3> &box2)\n    {\n        auto min = box1->_min.cwiseMin(box2->_min);\n        auto max = box1->_max.cwiseMax(box2->_max);\n        return std::make_unique<Bound3>(min, max);\n    };\n\n    const Eigen::Vector3f &min() { return _min; };\n\n    const Eigen::Vector3f &max() { return _max; };\n\nprivate:\n    Eigen::Vector3f _min;\n\n    Eigen::Vector3f _max;\n};\n", "meta": {"hexsha": "4bea8e11303fa1eb343e92c67642bfc20641e95c", "size": 1223, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/render/accelerate/Bound3.hpp", "max_stars_repo_name": "yzx9/NeuronSdfViewer", "max_stars_repo_head_hexsha": "454164dfccf80b806aac3cd7cca09e2cb8bd3c2a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-31T10:29:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-31T10:29:56.000Z", "max_issues_repo_path": "src/render/accelerate/Bound3.hpp", "max_issues_repo_name": "yzx9/NeuronSdfViewer", "max_issues_repo_head_hexsha": "454164dfccf80b806aac3cd7cca09e2cb8bd3c2a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/render/accelerate/Bound3.hpp", "max_forks_repo_name": "yzx9/NeuronSdfViewer", "max_forks_repo_head_hexsha": "454164dfccf80b806aac3cd7cca09e2cb8bd3c2a", "max_forks_repo_licenses": ["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.1777777778, "max_line_length": 121, "alphanum_fraction": 0.6287816844, "num_tokens": 347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.779992900254107, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.49969141842334114}}
{"text": "/*\n * SWE_Plane_Normal_Modes.hpp\n *\n *  Created on: 17 Nov 2019\n *      Author: Pedro Peixoto <pedrosp@ime.usp.br>\n *\n *      based on previous implementation by Martin Schreiber in swe_plane.cpp\n *\n */\n\n#ifndef SRC_PROGRAMS_SWE_PLANE_NORMAL_MODES_HPP_\n#define SRC_PROGRAMS_SWE_PLANE_NORMAL_MODES_HPP_\n\n#include <rexi/EXPFunctions.hpp>\n#include <sweet/plane/PlaneData_Physical.hpp>\n#include <sweet/plane/PlaneData_Spectral.hpp>\n#include <sweet/plane/PlaneData_SpectralComplex.hpp>\n#include <sweet/SimulationVariables.hpp>\n#include <sweet/plane/PlaneOperators.hpp>\n#include <functional>\n#if SWEET_EIGEN\n#include <Eigen/Eigenvalues>\n#endif\n/**\n * SWE Plane normal mode\n */\nclass SWE_Plane_Normal_Modes\n{\npublic:\n\n\ttemplate <typename TCallbackClass>\n\tstatic\n\tvoid normal_mode_analysis(\n\t\t\tPlaneData_Spectral &io_prog_h_pert, // h: surface height (perturbation)\n\t\t\tPlaneData_Spectral &io_prog_u, // u: velocity in x-direction\n\t\t\tPlaneData_Spectral &io_prog_v, // v: velocity in y-direction\n\t\t\tint number_of_prognostic_variables,\n\t\t\tSimulationVariables &i_simVars, // Simulation variables\n\t\t\tTCallbackClass *i_class,\n\t\t\tvoid(TCallbackClass::* const i_run_timestep_method)(void)\n\t)\n\t{\n\n\t\tconst PlaneDataConfig *planeDataConfig = io_prog_h_pert.planeDataConfig;\n\n\t\t// dummy time step to get time step size\n\t\tif (i_simVars.timecontrol.current_timestep_size <= 0)\n\t\t\tSWEETError(\"Normal mode analysis requires setting fixed time step size\");\n\n\t\t/*\n\t\t *\n\t\t * Mode-wise normal mode analysis\n\t\t *\n\t\t *\n\t\t */\n\n\t\tif (i_simVars.misc.normal_mode_analysis_generation == 4)\n\t\t{\n#if SWEET_EIGEN\n#if SWEET_USE_PLANE_SPECTRAL_DEALIASING\n\t\t\tSWEETError(\"SWE_Plane_Normal_Modes: This test was build for linear or linearized models, so please compile without dealising --plane-spectral-dealiasing=disable.\");\n#endif\n\n\n\t\t\t/*\n\t\t\t * Setup all output files\n\t\t\t */\n\t\t\tconst char* filename; //general filename\n\t\t\tchar buffer_real[1024];\n\n\t\t\tif (i_simVars.iodata.output_file_name == \"\")\n\t\t\t\tfilename = \"output_%s_t%020.8f.csv\";\n\t\t\telse\n\t\t\t\tfilename = i_simVars.iodata.output_file_name.c_str();\n\n\t\t\tsprintf(buffer_real, filename, \"normal_modes_plane\", i_simVars.timecontrol.current_timestep_size*i_simVars.iodata.output_time_scale);\n\t\t\tstd::ofstream file(buffer_real, std::ios_base::trunc);\n\t\t\tstd::cout << \"Writing normal mode analysis to files of the form '\" << buffer_real << \"'\" << std::endl;\n\n\t\t\t//Positive inertia-gravity modes\n\t\t\tsprintf(buffer_real, filename, \"normal_modes_plane_igpos\", i_simVars.timecontrol.current_timestep_size*i_simVars.iodata.output_time_scale);\n\t\t\tstd::ofstream file_igpos(buffer_real, std::ios_base::trunc);\n\n\t\t\t//Negative inertia-gravity modes\n\t\t\tsprintf(buffer_real, filename, \"normal_modes_plane_igneg\", i_simVars.timecontrol.current_timestep_size*i_simVars.iodata.output_time_scale);\n\t\t\tstd::ofstream file_igneg(buffer_real, std::ios_base::trunc);\n\n\t\t\t//Geostrophic modes\n\t\t\tsprintf(buffer_real, filename, \"normal_modes_plane_geo\", i_simVars.timecontrol.current_timestep_size*i_simVars.iodata.output_time_scale);\n\t\t\tstd::ofstream file_geo(buffer_real, std::ios_base::trunc);\n\n\t\t\t//std::cout << \"WARNING: OUTPUT IS TRANSPOSED!\" << std::endl;\n\n\t\t\t// use very high precision\n\t\t\tfile << std::setprecision(20);\n\t\t\tfile_igpos << std::setprecision(20);\n\t\t\tfile_igneg << std::setprecision(20);\n\t\t\tfile_geo << std::setprecision(20);\n\n\t\t\tfile << \"# dt \" << i_simVars.timecontrol.current_timestep_size << std::endl;\n\t\t\tfile << \"# g \" << i_simVars.sim.gravitation << std::endl;\n\t\t\tfile << \"# h \" << i_simVars.sim.h0 << std::endl;\n\t\t\tfile << \"# r \" << i_simVars.sim.sphere_radius << std::endl;\n\t\t\tfile << \"# f \" << i_simVars.sim.plane_rotating_f0 << std::endl;\n\n#if SWEET_USE_PLANE_SPECTRAL_SPACE\n\t\t\tint specmodes = planeDataConfig->get_spectral_iteration_range_area(0)+planeDataConfig->get_spectral_iteration_range_area(1);\n\t\t\tfile << \"# specnummodes \" << specmodes << std::endl;\n\t\t\tfile << \"# specrealresx \" << planeDataConfig->spectral_real_modes[0] << std::endl;\n\t\t\tfile << \"# specrealresy \" << planeDataConfig->spectral_real_modes[1] << std::endl;\n#endif\n\n\t\t\tfile << \"# physresx \" << planeDataConfig->physical_res[0] << std::endl;\n\t\t\tfile << \"# physresy \" << planeDataConfig->physical_res[1] << std::endl;\n\t\t\tfile << \"# normalmodegeneration \" << i_simVars.misc.normal_mode_analysis_generation << std::endl;\n\t\t\tfile << \"# antialiasing \";\n#if SWEET_USE_PLANE_SPECTRAL_DEALIASING\n\t\t\tfile << 1;\n#else\n\t\t\tfile << 0;\n#endif\n\t\t\tfile << std::endl;\n\n\t\t\tPlaneData_Spectral* prog[3] = {&io_prog_h_pert, &io_prog_u, &io_prog_v};\n\n\t\t\tint number_of_prognostic_variables = 3;\n\t\t\t//The basic state is with zero in all variables\n\t\t\t// The only non zero variable in the basic state is the total height\n\t\t\t//    for which the constant is added within run_timestep()\n\t\t\tio_prog_h_pert.spectral_set_zero();\n\t\t\tio_prog_u.spectral_set_zero();\n\t\t\tio_prog_v.spectral_set_zero();\n\n\t\t\t//int num_timesteps = 1;\n\n\t\t\t// Timestep and perturbation\n\t\t\tdouble dt = i_simVars.timecontrol.current_timestep_size;\n\t\t\tdouble eps = dt;\n\n\t\t\t//Matrix representing discrete linear operator in spectral space\n\t\t\tEigen::MatrixXcf A(3,3) ;\n\t\t\t//Eigen solver\n\t\t\tEigen::ComplexEigenSolver<Eigen::MatrixXcf> ces;\n\t\t\t//Final eigenvalues\n\t\t\tstd::complex<double> eval[3];\n\n\t\t\t//For each spectral mode\n\t\t\t//for (int r = 0; r < 2; r++) //only required to get the symmetric half of the spectrum\n\t\t\t//{\n\t\t\tint r = 0;\n\n\t\t\tfor (std::size_t i = planeDataConfig->spectral_data_iteration_ranges[r][0][0]; i < planeDataConfig->spectral_data_iteration_ranges[r][0][1]; i++)\n\t\t\t{\n\t\t\t\tstd::cout << \".\" << std::flush;\n\t\t\t\tfor (std::size_t j = planeDataConfig->spectral_data_iteration_ranges[r][1][0]; j < planeDataConfig->spectral_data_iteration_ranges[r][1][1]; j++)\n\t\t\t\t{\n\t\t\t\t\t//This is the mode to be analysed\n\t\t\t\t\t//std::cout << \"Mode (i,j)= (\" << i << \" , \" << j <<\")\"<< std::endl;\n\n\n\t\t\t\t\tfor (int outer_prog_id = 0; outer_prog_id < number_of_prognostic_variables; outer_prog_id++)\n\t\t\t\t\t{\n\n\t\t\t\t\t\t// reset time control\n\t\t\t\t\t\ti_simVars.timecontrol.current_timestep_nr = 0;\n\t\t\t\t\t\ti_simVars.timecontrol.current_simulation_time = 0;\n\n\t\t\t\t\t\tfor (int inner_prog_id = 0; inner_prog_id < number_of_prognostic_variables; inner_prog_id++)\n\t\t\t\t\t\t\tprog[inner_prog_id]->spectral_set_zero();\n\n\t\t\t\t\t\t// activate mode via real coefficient\n\t\t\t\t\t\tprog[outer_prog_id]->spectral_set(j, i, 1.0);\n\t\t\t\t\t\t//Activate the symetric couterpart of the mode (only needed if j>0 )\n\t\t\t\t\t\tif (j > 0)\n\t\t\t\t\t\t\tprog[outer_prog_id]->spectral_set(planeDataConfig->spectral_data_size[1]-j, i, 1.0);\n\n\t\t\t\t\t\t/*\n\t\t\t\t\t\t * RUN timestep\n\t\t\t\t\t\t */\n\t\t\t\t\t\t////prog[outer_prog_id]->request_data_physical();\n\t\t\t\t\t\t(i_class->*i_run_timestep_method)();\n\n\t\t\t\t\t\t/*\n\t\t\t\t\t\t * compute\n\t\t\t\t\t\t * 1/dt * (U(t+1) - U(t))\n\t\t\t\t\t\t */\n\t\t\t\t\t\t///////prog[outer_prog_id]->request_data_spectral();\n\n\t\t\t\t\t\tstd::complex<double> val = prog[outer_prog_id]->spectral_get(j, i);\n\t\t\t\t\t\tval = val - 1.0; //subtract U(0) from mode\n\t\t\t\t\t\tprog[outer_prog_id]->spectral_set(j, i, val);\n\n\t\t\t\t\t\tfor (int inner_prog_id = 0; inner_prog_id < number_of_prognostic_variables; inner_prog_id++)\n\t\t\t\t\t\t\t(*prog[inner_prog_id]) /= eps;\n\n\t\t\t\t\t\tfor (int inner_prog_id = 0; inner_prog_id < number_of_prognostic_variables; inner_prog_id++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tA(inner_prog_id,outer_prog_id)=prog[inner_prog_id]->spectral_get(j, i);;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\t//std::cout << \"Lik matrix\" << std::endl;\n\t\t\t\t\t//std::cout << A << std::endl;\n\n\t\t\t\t\t//std::cout<<\"Normal modes\" << std::endl;\n\t\t\t\t\tces.compute(A);\n\t\t\t\t\tfor(int i=0; i<3; i++)\n\t\t\t\t\t{\n\t\t\t\t\t\teval[i]=ces.eigenvalues()[i];\n\t\t\t\t\t\t//std::cout << \"Eigenvalue \"<< i << \" : \" << eval[i].real() <<\" \"<<eval[i].imag() << std::endl;\n\n\t\t\t\t\t}\n\t\t\t\t\t/* We will try to separate the modes in 3 types:\n\t\t\t\t\t * -positive inertia-gravity (imag>f) - we will adopt coriolis f to test as if > zero, since the exact freq is sqrt(f^2+cK*K)\n\t\t\t\t\t * -negative inertia-gravity (imag<-f)\n\t\t\t\t\t * -negative inertia-gravity (imag aprox 0) - we will fit all other modes here\n\t\t\t\t\t */\n\t\t\t\t\tint count_igpos=0;\n\t\t\t\t\tint count_igneg=0;\n\t\t\t\t\tint count_geo=0;\n\t\t\t\t\tfor(int i=0; i<3; i++)\n\t\t\t\t\t{\n\t\t\t\t\t\tif(eval[i].imag() > 0.5 * i_simVars.sim.plane_rotating_f0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t//std::cout<< \"IG pos mode: \" << eval[i].imag() << std::endl;\n\t\t\t\t\t\t\t//file_igpos << eval[i].imag();\n\t\t\t\t\t\t\tfile_igpos << eval[i].real()<< \"\\t\" << eval[i].imag();\n\t\t\t\t\t\t\tfile_igpos << \"\\t\";\n\t\t\t\t\t\t\tcount_igpos++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif(eval[i].imag() < - 0.5 * i_simVars.sim.plane_rotating_f0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t//std::cout<< \"IG neg mode: \" << eval[i].imag() << std::endl;\n\t\t\t\t\t\t\t//file_igneg << eval[i].imag();\n\t\t\t\t\t\t\tfile_igneg << eval[i].real()<< \"\\t\" << eval[i].imag();\n\t\t\t\t\t\t\tfile_igneg << \"\\t\";\n\t\t\t\t\t\t\tcount_igneg++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif(eval[i].imag() >= - 0.5 * i_simVars.sim.plane_rotating_f0 && eval[i].imag() <=  0.5 * i_simVars.sim.plane_rotating_f0 )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t//std::cout<< \"IG geo mode: \" << eval[i].imag() << std::endl;\n\t\t\t\t\t\t\t//file_geo << eval[i].imag();\n\t\t\t\t\t\t\tfile_geo << eval[i].real()<< \"\\t\" << eval[i].imag();\n\t\t\t\t\t\t\tfile_geo << \"\\t\";\n\t\t\t\t\t\t\tcount_geo++;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t//Check if we got the correct modes\n\t\t\t\t\tif ( count_igpos * count_igneg * count_geo > 0 )\n\t\t\t\t\t{\n\t\t\t\t\t\tcount_igpos=0;\n\t\t\t\t\t\tcount_igneg=0;\n\t\t\t\t\t\tcount_geo=0;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tSWEETError(\"SWE_Plane_Normal_Modes: Could not separate modes!!\");\n\t\t\t\t\t}\n\n\t\t\t\t\t//std::cout<<\"-------------------------\" << std::endl;\n\t\t\t\t}\n\t\t\t\tfile_igpos << std::endl;\n\t\t\t\tfile_igneg << std::endl;\n\t\t\t\tfile_geo << std::endl;\n\t\t\t}\n\n\t\t\t//}\n\t\t\t//std::cout<<\"-------------------------\" << std::endl;\n\t\t\t//SWEETError(\"still needs work...\");\n#else\n\t\t\tSWEETError(\"SWE_Plane_Normal_Modes: Cannot test this without Eigen library. Please compile with --eigen=enable\");\n#endif\n\t\t}\n\t\t/*\n\t\t * Do a normal mode analysis using perturbation, see\n\t\t * Hillary Weller, John Thuburn, Collin J. Cotter,\n\t\t * \"Computational Modes and Grid Imprinting on Five Quasi-Uniform Spherical C Grids\"\n\t\t */\n\t\telse\n\t\t{\n\n\t\t\t//run_timestep();\n\t\t\tconst char* filename;\n\t\t\tchar buffer_real[1024];\n\n\t\t\tif (i_simVars.iodata.output_file_name == \"\")\n\t\t\t\tfilename = \"output_%s_normalmodes.csv\";\n\t\t\telse\n\t\t\t\tfilename = i_simVars.iodata.output_file_name.c_str();\n\n\n\t\t\tsprintf(buffer_real, filename, \"normal_modes_physical\", i_simVars.timecontrol.current_timestep_size*i_simVars.iodata.output_time_scale);\n\t\t\tstd::ofstream file(buffer_real, std::ios_base::trunc);\n\t\t\tstd::cout << \"Writing normal mode analysis to file '\" << buffer_real << \"'\" << std::endl;\n\n\t\t\tstd::cout << \"WARNING: OUTPUT IS TRANSPOSED!\" << std::endl;\n\n\t\t\t// use very high precision\n\t\t\tfile << std::setprecision(20);\n\n\t\t\tPlaneData_Spectral* prog[3] = {&io_prog_h_pert, &io_prog_u, &io_prog_v};\n\n\t\t\t/*\n\t\t\t * Maximum number of prognostic variables\n\t\t\t *\n\t\t\t * Advection e.g. has only one\n\t\t\t */\n\t\t\tif (number_of_prognostic_variables <= 0)\n\t\t\t\tSWEETError(\"simVars.pde.number_of_prognostic_variables must be set!\");\n\n\t\t\tif (number_of_prognostic_variables == 3)\n\t\t\t{\n\t\t\t\tio_prog_h_pert.spectral_set_zero();\n\t\t\t\tio_prog_u.spectral_set_zero();\n\t\t\t\tio_prog_v.spectral_set_zero();\n\t\t\t}\n\t\t\telse if (number_of_prognostic_variables == 1)\n\t\t\t{\n\t\t\t\tio_prog_h_pert.spectral_set_zero();\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tSWEETError(\"Not yet supported\");\n\t\t\t}\n\n#if 0\n\t\t\tif (i_simVars.disc.timestepping_method == SimulationVariables::Discretization::LEAPFROG_EXPLICIT)\n\t\t\t{\n\t\t\t\tSWEETError(\"Not yet tested and supported\");\n\t\t\t\tstd::cout << \"WARNING: Leapfrog time stepping doesn't make real sense since 1st step is based on RK-like method\" << std::endl;\n\t\t\t\tstd::cout << \"We'll do two Leapfrog time steps here to take the LF errors into account!\" << std::endl;\n\t\t\t\tstd::cout << \"Therefore, we also halve the time step size here\" << std::endl;\n\n\t\t\t\ti_simVars.timecontrol.current_timestep_size = 0.5*i_simVars.sim.CFL;\n\t\t\t\ti_simVars.sim.CFL = -i_simVars.timecontrol.current_timestep_size;\n\t\t\t}\n#endif\n\n\t\t\tint num_timesteps = 1;\n\t\t\tif (i_simVars.misc.normal_mode_analysis_generation >= 10)\n\t\t\t{\n\t\t\t\tif (i_simVars.timecontrol.max_timesteps_nr > 0)\n\t\t\t\t\tnum_timesteps = i_simVars.timecontrol.max_timesteps_nr;\n\t\t\t}\n\n\t\t\tif (i_simVars.timecontrol.max_simulation_time > 0)\n\t\t\t\tfile << \"# t \" << i_simVars.timecontrol.max_simulation_time << std::endl;\n\t\t\telse\n\t\t\t\tfile << \"# t \" << (num_timesteps*(-i_simVars.timecontrol.current_timestep_size)) << std::endl;\n\n\t\t\tfile << \"# g \" << i_simVars.sim.gravitation << std::endl;\n\t\t\tfile << \"# h \" << i_simVars.sim.h0 << std::endl;\n//\t\t\tfile << \"# r \" << i_simVars.sim.sphere_radius << std::endl;\n\t\t\tfile << \"# f \" << i_simVars.sim.plane_rotating_f0 << std::endl;\n\n#if SWEET_USE_PLANE_SPECTRAL_SPACE\n\t\t\tint specmodes = planeDataConfig->get_spectral_iteration_range_area(0)+planeDataConfig->get_spectral_iteration_range_area(1);\n\t\t\tfile << \"# specnummodes \" << specmodes << std::endl;\n\t\t\tfile << \"# specrealresx \" << planeDataConfig->spectral_real_modes[0] << std::endl;\n\t\t\tfile << \"# specrealresy \" << planeDataConfig->spectral_real_modes[1] << std::endl;\n#endif\n\n\t\t\tfile << \"# physresx \" << planeDataConfig->physical_res[0] << std::endl;\n\t\t\tfile << \"# physresy \" << planeDataConfig->physical_res[1] << std::endl;\n\t\t\tfile << \"# normalmodegeneration \" << i_simVars.misc.normal_mode_analysis_generation << std::endl;\n\t\t\tfile << \"# antialiasing \";\n\n#if SWEET_USE_PLANE_SPECTRAL_DEALIASING\n\t\t\tfile << 1;\n#else\n\t\t\tfile << 0;\n#endif\n\n\t\t\tfile << std::endl;\n\n\n\t\t\t// iterate over all prognostic variables\n\t\t\tfor (int outer_prog_id = 0; outer_prog_id < number_of_prognostic_variables; outer_prog_id++)\n\t\t\t{\n\t\t\t\tif (i_simVars.misc.normal_mode_analysis_generation == 1 || i_simVars.misc.normal_mode_analysis_generation == 11)\n\t\t\t\t{\n\t\t\t\t\t// iterate over physical space\n\t\t\t\t\tfor (std::size_t outer_i = 0; outer_i < planeDataConfig->physical_array_data_number_of_elements; outer_i++)\n\t\t\t\t\t{\n\t\t\t\t\t\t// reset time control\n\t\t\t\t\t\ti_simVars.timecontrol.current_timestep_nr = 0;\n\t\t\t\t\t\ti_simVars.timecontrol.current_simulation_time = 0;\n\n\t\t\t\t\t\tstd::cout << \".\" << std::flush;\n\n\t\t\t\t\t\tfor (int inner_prog_id = 0; inner_prog_id < number_of_prognostic_variables; inner_prog_id++)\n\t\t\t\t\t\t\tprog[inner_prog_id]->spectral_set_zero();\n\n\t\t\t\t\t\t// activate mode\n\t\t\t\t\t\t///prog[outer_prog_id]->request_data_physical();\n\t\t\t\t\t\t///prog[outer_prog_id]->physical_space_data[outer_i] = 1;\n\t\t\t\t\t\tPlaneData_Physical tmp = prog[outer_prog_id]->toPhys();\n\t\t\t\t\t\ttmp.physical_space_data[outer_i] = 1;\n\t\t\t\t\t\tprog[outer_prog_id]->loadPlaneDataPhysical(tmp);\n\n\t\t\t\t\t\t/*\n\t\t\t\t\t\t * RUN timestep\n\t\t\t\t\t\t */\n\n\t\t\t\t\t\t(i_class->*i_run_timestep_method)();\n\n\t\t\t\t\t\tif (i_simVars.misc.normal_mode_analysis_generation == 1)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t/*\n\t\t\t\t\t\t\t * compute\n\t\t\t\t\t\t\t * 1/dt * (U(t+1) - U(t))\n\t\t\t\t\t\t\t */\n\t\t\t\t\t\t\t///////prog[outer_prog_id]->request_data_physical();\n\t\t\t\t\t\t\t///////prog[outer_prog_id]->physical_space_data[outer_i] -= 1.0;\n\t\t\t\t\t\t\tPlaneData_Physical tmp2 = prog[outer_prog_id]->toPhys();\n\t\t\t\t\t\t\ttmp2.physical_space_data[outer_i] -= 1.0;\n\n\t\t\t\t\t\t\tfor (int inner_prog_id = 0; inner_prog_id < number_of_prognostic_variables; inner_prog_id++)\n\t\t\t\t\t\t\t\ttmp2 /= i_simVars.timecontrol.current_timestep_size;\n\t\t\t\t\t\t\t\t//(*prog[inner_prog_id]) /= i_simVars.timecontrol.current_timestep_size;\n\n\t\t\t\t\t\t\tprog[outer_prog_id]->loadPlaneDataPhysical(tmp2);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\ttmp = prog[outer_prog_id]->toPhys();\n\t\t\t\t\t\tfor (int inner_prog_id = 0; inner_prog_id < number_of_prognostic_variables; inner_prog_id++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t///prog[inner_prog_id]->request_data_physical();\n\t\t\t\t\t\t\tfor (std::size_t k = 0; k < planeDataConfig->physical_array_data_number_of_elements; k++)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t///file << prog[inner_prog_id]->physical_space_data[k];\n\t\t\t\t\t\t\t\tfile << tmp.physical_space_data[k];\n\t\t\t\t\t\t\t\tif (inner_prog_id != number_of_prognostic_variables-1 || k != planeDataConfig->physical_array_data_number_of_elements-1)\n\t\t\t\t\t\t\t\t\tfile << \"\\t\";\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\tfile << std::endl;\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#if 1\n\t\t\t\telse if (i_simVars.misc.normal_mode_analysis_generation == 3 || i_simVars.misc.normal_mode_analysis_generation == 13)\n\t\t\t\t{\n#if !SWEET_USE_PLANE_SPECTRAL_SPACE\n\t\t\t\t\tSWEETError(\"Only available with if plane spectral space is activated during compile time!\");\n#else\n\n\t\t\t\t\t// iterate over spectral space\n\t\t\t\t\tfor (int r = 0; r < 2; r++)\n\t\t\t\t\t{\n\n\t\t\t\t\t\tfor (std::size_t j = planeDataConfig->spectral_data_iteration_ranges[r][1][0]; j < planeDataConfig->spectral_data_iteration_ranges[r][1][1]; j++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfor (std::size_t i = planeDataConfig->spectral_data_iteration_ranges[r][0][0]; i < planeDataConfig->spectral_data_iteration_ranges[r][0][1]; i++)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t// reset time control\n\t\t\t\t\t\t\t\ti_simVars.timecontrol.current_timestep_nr = 0;\n\t\t\t\t\t\t\t\ti_simVars.timecontrol.current_simulation_time = 0;\n\n\t\t\t\t\t\t\t\tstd::cout << \".\" << std::flush;\n\n\t\t\t\t\t\t\t\tfor (int inner_prog_id = 0; inner_prog_id < number_of_prognostic_variables; inner_prog_id++)\n\t\t\t\t\t\t\t\t\tprog[inner_prog_id]->spectral_set_zero();\n\n\t\t\t\t\t\t\t\t// activate mode via real coefficient\n\t\t\t\t\t\t\t\tprog[outer_prog_id]->spectral_set(j, i, 1.0);\n\n\t\t\t\t\t\t\t\t/*\n\t\t\t\t\t\t\t\t * RUN timestep\n\t\t\t\t\t\t\t\t */\n\t\t\t\t\t\t\t\t(i_class->*i_run_timestep_method)();\n\n\n\t\t\t\t\t\t\t\tif (i_simVars.misc.normal_mode_analysis_generation == 3)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t/*\n\t\t\t\t\t\t\t\t\t * compute\n\t\t\t\t\t\t\t\t\t * 1/dt * (U(t+1) - U(t))\n\t\t\t\t\t\t\t\t\t */\n\t\t\t\t\t\t\t\t\t///prog[outer_prog_id]->request_data_spectral();\n\n\t\t\t\t\t\t\t\t\tstd::complex<double> val = prog[outer_prog_id]->spectral_get(j, i);\n\t\t\t\t\t\t\t\t\tval = val - 1.0;\n\t\t\t\t\t\t\t\t\tprog[outer_prog_id]->spectral_set(j, i, val);\n\n\t\t\t\t\t\t\t\t\tfor (int inner_prog_id = 0; inner_prog_id < number_of_prognostic_variables; inner_prog_id++)\n\t\t\t\t\t\t\t\t\t\t(*prog[inner_prog_id]) /= i_simVars.timecontrol.current_timestep_size;\n\t\t\t\t\t\t\t\t}\n\n\n\t\t\t\t\t\t\t\tfor (int inner_prog_id = 0; inner_prog_id < number_of_prognostic_variables; inner_prog_id++)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t///prog[inner_prog_id]->request_data_spectral();\n\n\t\t\t\t\t\t\t\t\t/*\n\t\t\t\t\t\t\t\t\t * REAL\n\t\t\t\t\t\t\t\t\t */\n\n\t\t\t\t\t\t\t\t\tfor (int r = 0; r < 2; r++)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tfor (std::size_t j = planeDataConfig->spectral_data_iteration_ranges[r][1][0]; j < planeDataConfig->spectral_data_iteration_ranges[r][1][1]; j++)\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tfor (std::size_t i = planeDataConfig->spectral_data_iteration_ranges[r][0][0]; i < planeDataConfig->spectral_data_iteration_ranges[r][0][1]; i++)\n\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\tfile << prog[inner_prog_id]->spectral_get(j, i).real();\n\t\t\t\t\t\t\t\t\t\t\t\tfile << \"\\t\";\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\n\n\t\t\t\t\t\t\t\tfor (int inner_prog_id = 0; inner_prog_id < number_of_prognostic_variables; inner_prog_id++)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t/*\n\t\t\t\t\t\t\t\t\t * IMAG\n\t\t\t\t\t\t\t\t\t */\n\t\t\t\t\t\t\t\t\tint c = 0;\n\t\t\t\t\t\t\t\t\tfor (int r = 0; r < 2; r++)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tfor (std::size_t j = planeDataConfig->spectral_data_iteration_ranges[r][1][0]; j < planeDataConfig->spectral_data_iteration_ranges[r][1][1]; j++)\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tfor (std::size_t i = planeDataConfig->spectral_data_iteration_ranges[r][0][0]; i < planeDataConfig->spectral_data_iteration_ranges[r][0][1]; i++)\n\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\tfile << prog[inner_prog_id]->spectral_get(j, i).imag();\n\n\t\t\t\t\t\t\t\t\t\t\t\tif (inner_prog_id != number_of_prognostic_variables-1 || c != specmodes-1)\n\t\t\t\t\t\t\t\t\t\t\t\t\tfile << \"\\t\";\n\t\t\t\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\t\t\t\tfile << std::endl;\n\n\t\t\t\t\t\t\t\t\t\t\t\tc++;\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n#endif\n\t\t\t\t}\n#else\n\t\t\t\telse if (i_simVars.misc.normal_mode_analysis_generation == 3 || i_simVars.misc.normal_mode_analysis_generation == 13)\n\t\t\t\t{\n\t\t\t\t\tPlaneData_SpectralComplex t1(planeDataConfig);\n\t\t\t\t\tPlaneData_SpectralComplex t2(planeDataConfig);\n\t\t\t\t\tPlaneData_SpectralComplex t3(planeDataConfig);\n\t\t\t\t\tPlaneDataComplex* prog_cplx[3] = {&t1, &t2, &t3};\n\n\t\t\t\t\t// iterate over spectral space\n\t\t\t\t\tfor (std::size_t outer_i = 0; outer_i < planeDataConfig->spectral_complex_array_data_number_of_elements; outer_i++)\n\t\t\t\t\t{\n\t\t\t\t\t\t// reset time control\n\t\t\t\t\t\ti_simVars.timecontrol.current_timestep_nr = 0;\n\t\t\t\t\t\ti_simVars.timecontrol.current_simulation_time = 0;\n\n\t\t\t\t\t\tstd::cout << \".\" << std::flush;\n\n\t\t\t\t\t\tfor (int inner_prog_id = 0; inner_prog_id < number_of_prognostic_variables; inner_prog_id++)\n\t\t\t\t\t\t\tprog_cplx[inner_prog_id]->spectral_set_zero();\n\n\t\t\t\t\t\t// activate mode via real coefficient\n\t\t\t\t\t\tprog_cplx[outer_prog_id]->request_data_spectral();\n\t\t\t\t\t\tprog_cplx[outer_prog_id]->spectral_space_data[outer_i].real(1);\n\n\t\t\t\t\t\t// convert PlaneData_SpectralComplex to PlaneData\n\t\t\t\t\t\tfor (int inner_prog_id = 0; inner_prog_id < number_of_prognostic_variables; inner_prog_id++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t*prog[inner_prog_id] = Convert_PlaneDataSpectralComplex_To_PlaneDataSpectral::physical_convert(*prog_cplx[inner_prog_id]);\n\t\t\t\t\t\t\tprog[inner_prog_id]->spectral_zeroAliasingModes();\n\t\t\t\t\t\t}\n\n\n\t\t\t\t\t\t/*\n\t\t\t\t\t\t * RUN timestep\n\t\t\t\t\t\t */\n\t\t\t\t\t\t(i_class->*i_run_timestep_method)();\n\n\t\t\t\t\t\tfor (int inner_prog_id = 0; inner_prog_id < number_of_prognostic_variables; inner_prog_id++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tprog[inner_prog_id]->spectral_zeroAliasingModes();\n#warning \"update this physical_convert maybe to spectral_convert\"\n\n\t\t\t\t\t\t\t*prog_cplx[inner_prog_id] = Convert_PlaneDataSpectral_To_PlaneDataSpectralComplex::physical_convert(*prog[inner_prog_id]);\n\n\t\t\t\t\t\t\tprog_cplx[inner_prog_id]->request_data_spectral();\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (i_simVars.misc.normal_mode_analysis_generation == 3)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t/*\n\t\t\t\t\t\t\t * compute\n\t\t\t\t\t\t\t * 1/dt * (U(t+1) - U(t))\n\t\t\t\t\t\t\t */\n\t\t\t\t\t\t\tprog_cplx[outer_prog_id]->request_data_spectral();\n\t\t\t\t\t\t\tprog_cplx[outer_prog_id]->spectral_space_data[outer_i] -= 1.0;\n\n\t\t\t\t\t\t\tfor (int inner_prog_id = 0; inner_prog_id < number_of_prognostic_variables; inner_prog_id++)\n\t\t\t\t\t\t\t\tprog_cplx[inner_prog_id]->operator*=(1.0/i_simVars.timecontrol.current_timestep_size);\n\t\t\t\t\t\t}\n\n\n\t\t\t\t\t\t// convert PlaneData_SpectralComplex to PlaneData\n\t\t\t\t\t\tfor (int inner_prog_id = 0; inner_prog_id < number_of_prognostic_variables; inner_prog_id++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tprog_cplx[inner_prog_id]->request_data_spectral();\n\n\t\t\t\t\t\t\t/*\n\t\t\t\t\t\t\t * REAL\n\t\t\t\t\t\t\t */\n\t\t\t\t\t\t\tfor (std::size_t k = 0; k < planeDataConfig->spectral_complex_array_data_number_of_elements; k++)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tfile << prog_cplx[inner_prog_id]->spectral_space_data[k].real();\n\t\t\t\t\t\t\t\tfile << \"\\t\";\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t/*\n\t\t\t\t\t\t\t * IMAG\n\t\t\t\t\t\t\t */\n\t\t\t\t\t\t\tfor (std::size_t k = 0; k < planeDataConfig->spectral_complex_array_data_number_of_elements; k++)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tfile << prog_cplx[inner_prog_id]->spectral_space_data[k].imag();\n\n\t\t\t\t\t\t\t\tif (inner_prog_id != number_of_prognostic_variables-1 || k != planeDataConfig->spectral_complex_array_data_number_of_elements-1)\n\t\t\t\t\t\t\t\t\tfile << \"\\t\";\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\tfile << std::endl;\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#endif\n\t\t\t}\n\t\t}\n\t}\n\n\n\t~SWE_Plane_Normal_Modes()\n\t{\n\n\t}\n};\n\n#endif /* SRC_PROGRAMS_SWE_PLANE_NORMAL_MODES_HPP_ */\n", "meta": {"hexsha": "00e8ca51c1637e5bf29df4c8f6dbb970bc26ce3e", "size": 22579, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/programs/swe_plane_timeintegrators/SWE_Plane_Normal_Modes.hpp", "max_stars_repo_name": "schreibm/sweet", "max_stars_repo_head_hexsha": "a1b97e5862c3871177dff877dff825fd4b98a085", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/programs/swe_plane_timeintegrators/SWE_Plane_Normal_Modes.hpp", "max_issues_repo_name": "schreibm/sweet", "max_issues_repo_head_hexsha": "a1b97e5862c3871177dff877dff825fd4b98a085", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/programs/swe_plane_timeintegrators/SWE_Plane_Normal_Modes.hpp", "max_forks_repo_name": "schreibm/sweet", "max_forks_repo_head_hexsha": "a1b97e5862c3871177dff877dff825fd4b98a085", "max_forks_repo_licenses": ["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.9520123839, "max_line_length": 167, "alphanum_fraction": 0.6523318127, "num_tokens": 6399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.779992900254107, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.49969141842334114}}
{"text": "#include <iostream>\n#include <fstream>\n#include <cstring>\n#include <cstdlib>\n#include <vector>\n#include <limits>       // std::numeric_limits\n#include <boost/crc.hpp>\n#include <boost/program_options.hpp>\n#include <boost/system/error_code.hpp>\n\nusing namespace boost ;\n\nconst int CRC16_CCITT_R=0x8408;  //https://en.wikipedia.org/wiki/Cyclic_redundancy_check\nconst int DEFAULT_SIZE_OF_PACK=1;\nconst int DEFAULT_PACK_COUNT=10;\n\nunsigned int packSize = DEFAULT_SIZE_OF_PACK;\nunsigned int packCount = DEFAULT_PACK_COUNT;\n\nstd::vector<unsigned int> data;\nstd::vector<unsigned int> remote;\n\nstd::string sOutputFile = \"file.binary\";\nstd::string sInpuFile = \"\";\n\nunsigned int sawSize = std::numeric_limits<int>::max();\nunsigned int rndSize = 0;\nunsigned int mulSize = 1;\nunsigned int crcPoly = CRC16_CCITT_R;\n\nint main(int argc, char* argv[])\n{\n\n    namespace po = boost::program_options;\n    po::options_description desc(\"Allowed options\");\n    desc.add_options()\n    (\"help,h\", \"show options\")\n    (\"addcrc,c\", po::value<unsigned int> (&packSize), \"count crc after this\")\n    (\"addsum,u\", po::value<unsigned int> (&packSize), \"count simple sum after this\")\n    (\"datacount,d\", po::value<unsigned int> (&packCount), \"count of genrated packs\")\n    (\"outfile,f\", po::value<std::string> (&sOutputFile), \"outputfilename, default:file.binary\")\n    (\"inputfile,k\", po::value<std::string> (&sInpuFile), \"get data from inputfile instead of algo\" )\n    (\"saw,s\", po::value<unsigned int> (&sawSize), \"algorithm: saw modulo (default:maxint)\")\n    (\"rnd,r\", po::value<unsigned int> (&rndSize), \"algorithm: random modulo (default:0)\")\n    (\"mul,m\", po::value<unsigned int> (&mulSize), \"algorithm: multiplication (default:1)\")\n    (\"crcpoly,e\", po::value<unsigned int> (&crcPoly), \"crc polynominal (default:0x8408)\")\n    (\"print,p\", \"show data\")\n    ;\n    po::variables_map vm;\n    po::store(po::command_line_parser(argc, argv).\n              options(desc).run(), vm);\n    po::notify(vm);\n\n    if (vm.count(\"help\"))\n    {\n        std::cerr << argv[0] << \" - data generator\" << std::endl;\n        std::cerr << \"The idea of this program is to generate data with or without crc.\"<< std::endl;\n        std::cerr << \"For testing purposes.\"<< std::endl;\n        std::cerr << \"Algorithm: ((rnd + (j*CRC_packSize + i)) * mul) % saw\" << std::endl;\n        std::cerr << \"Examples:\"<< std::endl;\n        std::cerr << \"\\t./xgenerator -d 8 -s 30 -p -m 10:\"<< std::endl;\n        std::cerr << \"\\t\\t>0 10 20 0 10 20 0 10\"<< std::endl;\n        std::cerr << \"\\t./xgenerator -d 8 -p\"<< std::endl;\n        std::cerr << \"\\t\\t>0 1 2 3 4 5 6 7\"<< std::endl;\n        std::cerr << \"\\t./xgenerator -d 8 -p -r 20\"<< std::endl;\n        std::cerr << \"\\t\\t>3 7 19 18 17 20 12 19\"<< std::endl;\n        std::cerr << \"\\t./xgenerator -d 2 -p -c 4\"<< std::endl;\n        std::cerr << \"\\t\\t0 1 2 3 37368\"<< std::endl;\n        std::cerr << \"\\t\\t4 5 6 7 24536\"<< std::endl;\n        std::cerr << desc << std::endl ;\n        return system::errc::success;\n    }\n\n    auto myfile = std::fstream(sOutputFile, std::ios::out | std::ios::binary);\n\n    if (sInpuFile != \"\" && vm.count(\"addcrc\"))\n    {\n\n        auto remotefile = std::fstream(sInpuFile, std::ios::in | std::ios::binary);\n        unsigned int val ;\n        while (remotefile.read((char*)&val,sizeof(unsigned int)))\n        {\n            remote.push_back(val);\n        }\n        remotefile.close();\n\n        assert( remote.size() >= packCount * packSize);\n    }\n\n    int crcqCnt=0; //Count of crc that landend in output file\n    int sumqCnt=0; //Count of crc that landend in output file\n    int cnt=0; //Count of data read from remote file\n    for(auto j = 0; j < packCount; j++)\n    {\n\n        std::vector<unsigned int> crcq;\n        unsigned int sumq = 0;\n\n        for(auto i = 0; i < packSize; ++i)\n        {\n\n            auto rndVector = 0;\n            unsigned int val ;\n            if (sInpuFile != \"\" && vm.count(\"addcrc\"))\n            {\n                val = remote[cnt++];\n            }\n            else\n            {\n                if (rndSize>0)\n                {\n                    rndVector = rand()%rndSize;\n                }\n                val = ((rndVector + (j*packSize + i)) * mulSize)%sawSize ;\n            }\n            data.push_back(val);\n            if (vm.count(\"addcrc\"))\n            {\n                crcq.push_back(val);\n            }\n            if (vm.count(\"print\"))\n            {\n                std::cout << val << \" \";\n            }\n\n            if (vm.count(\"addsum\"))\n            {\n                sumq+=val;\n            }\n        }\n\n        if (vm.count(\"addcrc\"))\n        {\n\n            boost::crc_basic<16> crcfn(crcPoly, 0x0, 0x0, false, false);\n            crcfn.process_bytes(crcq.data(), sizeof(unsigned int) * crcq.size());\n            if (vm.count(\"print\"))\n            {\n                std::cout << crcfn.checksum() << std::endl ;\n            }\n            data.push_back(crcfn.checksum());\n            crcqCnt++;\n        }\n\n        if (vm.count(\"addsum\"))\n        {\n            if (vm.count(\"print\"))\n            {\n                std::cout << sumq << std::endl ;\n            }\n            data.push_back(sumq);\n            sumqCnt++;\n        }\n    }\n\n    if (vm.count(\"print\"))\n    {\n        std::cout << std::endl ;\n    }\n\n    myfile.write((char*)data.data(), data.size()*sizeof(unsigned int));\n    myfile.close();\n\n    std::cout << \"count:\"<< packCount * packSize << std::endl;\n    if (vm.count(\"addcrc\"))\n    {\n        std::cout << \"crc cnt:\"<< crcqCnt << std::endl;\n    }\n    if (vm.count(\"addsum\"))\n    {\n        std::cout << \"sum cnt:\"<< sumqCnt << std::endl;\n    }\n    std::cout << \"output:\" << sOutputFile << std::endl;\n    std::cout << \"done.\" << std::endl;\n    return system::errc::success;\n}\n", "meta": {"hexsha": "3ac7396feab0e8ba9835cbd5d1d94ae8947196de", "size": 5749, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/generator/generator.cpp", "max_stars_repo_name": "michalwidera/abracadabradb", "max_stars_repo_head_hexsha": "13d4f66454b3b6af7e8353bd10186409230634e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-12-04T16:51:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-09T15:13:13.000Z", "max_issues_repo_path": "examples/generator/generator.cpp", "max_issues_repo_name": "michalwidera/abracadabradb", "max_issues_repo_head_hexsha": "13d4f66454b3b6af7e8353bd10186409230634e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2019-12-07T21:21:41.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-17T16:44:36.000Z", "max_forks_repo_path": "examples/generator/generator.cpp", "max_forks_repo_name": "michalwidera/abracadabradb", "max_forks_repo_head_hexsha": "13d4f66454b3b6af7e8353bd10186409230634e2", "max_forks_repo_licenses": ["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.4802259887, "max_line_length": 101, "alphanum_fraction": 0.5371368934, "num_tokens": 1580, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.779992900254107, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.49969141842334114}}
{"text": "// File: morton_dense.cpp\n\n#include <iostream>\n#include <boost/numeric/mtl/mtl.hpp>\n\nint main(int, char**)\n{\n    using namespace mtl;\n\n    // Z-order matrix\n    morton_dense<double, recursion::morton_z_mask>  A(10, 10);\n\n    A= 0;\n    A(2, 3)= 7.0;\n    A[2][4]= 3.0;\n    std::cout << \"A is \\n\" << A << \"\\n\";\n    \n    // B is an N-order matrix with column-major 4x4 blocks, see paper\n    morton_dense<float, recursion::doppled_4_col_mask> B(10, 10);\n\n    // Assign the identity matrix times 3 to B\n    B= 3;\n    std::cout << \"B is \\n\" << B << \"\\n\";\n\n    return 0;\n}\n\n", "meta": {"hexsha": "3dfbd4b581e8446b9cd643c41c5fbfea14f7fcdc", "size": 566, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/examples/morton_dense.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/morton_dense.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/morton_dense.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": 20.2142857143, "max_line_length": 69, "alphanum_fraction": 0.5777385159, "num_tokens": 199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.4996914184233411}}
{"text": "#include \"refill/system_models/linearized_system_model.h\"\n\n#include <gtest/gtest.h>\n\n#include <Eigen/Dense>\n\n#include \"refill/distributions/gaussian_distribution.h\"\n\nnamespace refill {\n\nclass LinearizedSystemModelClass : public LinearizedSystemModel {\n public:\n  LinearizedSystemModelClass(const size_t& state_dim,\n                             const DistributionInterface& system_noise)\n      : LinearizedSystemModel(state_dim, system_noise) {}\n  LinearizedSystemModelClass(const size_t& state_dim,\n                             const DistributionInterface& system_noise,\n                             const size_t& input_dim)\n      : LinearizedSystemModel(state_dim, system_noise, input_dim) {}\n  Eigen::VectorXd propagate(const Eigen::VectorXd& state,\n                            const Eigen::VectorXd& input,\n                            const Eigen::VectorXd& noise) const {\n    return state + noise;\n  }\n};\n\nTEST(LinearizedSystemModelTest, NoInputTest) {\n  GaussianDistribution system_noise(Eigen::Vector2d::Zero(),\n                                    Eigen::Matrix2d::Identity());\n\n  LinearizedSystemModelClass system_model(2, system_noise);\n\n  Eigen::MatrixXd state_jacobian = system_model.getStateJacobian(\n      Eigen::Vector2d::Zero(), Eigen::VectorXd::Zero(0));\n\n  ASSERT_EQ(state_jacobian.rows(), state_jacobian.cols());\n  ASSERT_EQ(system_model.getStateDim(), state_jacobian.rows());\n  ASSERT_EQ(Eigen::Matrix2d::Identity(), state_jacobian);\n\n  Eigen::MatrixXd noise_jacobian = system_model.getNoiseJacobian(\n      Eigen::Vector2d::Zero(), Eigen::VectorXd::Zero(0));\n\n  ASSERT_EQ(system_model.getStateDim(), noise_jacobian.rows());\n  ASSERT_EQ(system_model.getNoiseDim(), noise_jacobian.cols());\n  ASSERT_EQ(Eigen::Matrix2d::Identity(), noise_jacobian);\n}\n\nTEST(LinearizedSystemModelTest, WithInputTest) {\n  GaussianDistribution system_noise(Eigen::Vector2d::Zero(),\n                                    Eigen::Matrix2d::Identity());\n\n  LinearizedSystemModelClass system_model(2, system_noise, 2);\n\n  Eigen::MatrixXd state_jacobian = system_model.getStateJacobian(\n      Eigen::Vector2d::Zero(), Eigen::Vector2d::Zero());\n\n  ASSERT_EQ(state_jacobian.rows(), state_jacobian.cols());\n  ASSERT_EQ(system_model.getStateDim(), state_jacobian.rows());\n  ASSERT_EQ(Eigen::Matrix2d::Identity(), state_jacobian);\n\n  Eigen::MatrixXd noise_jacobian = system_model.getNoiseJacobian(\n      Eigen::Vector2d::Zero(), Eigen::Vector2d::Zero());\n\n  ASSERT_EQ(system_model.getStateDim(), noise_jacobian.rows());\n  ASSERT_EQ(system_model.getNoiseDim(), noise_jacobian.cols());\n  ASSERT_EQ(Eigen::Matrix2d::Identity(), noise_jacobian);\n}\n\n}  // namespace refill\n", "meta": {"hexsha": "5b071fc4923e75cdfcb5b8ababcb4de440cc5490", "size": 2650, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/tests/linearized_system_model_test.cc", "max_stars_repo_name": "jwidauer/refill", "max_stars_repo_head_hexsha": "64947e0a8e15855f4a5ad048f09f8d38715bbe91", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-06-13T07:28:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-08T11:26:34.000Z", "max_issues_repo_path": "src/tests/linearized_system_model_test.cc", "max_issues_repo_name": "jwidauer/refill", "max_issues_repo_head_hexsha": "64947e0a8e15855f4a5ad048f09f8d38715bbe91", "max_issues_repo_licenses": ["MIT"], "max_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/linearized_system_model_test.cc", "max_forks_repo_name": "jwidauer/refill", "max_forks_repo_head_hexsha": "64947e0a8e15855f4a5ad048f09f8d38715bbe91", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-06-01T13:21:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-01T20:33:20.000Z", "avg_line_length": 37.8571428571, "max_line_length": 71, "alphanum_fraction": 0.7052830189, "num_tokens": 579, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541067, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.49969141842334097}}
{"text": "#include <boost/program_options.hpp>\n#include <string>\n#include <math.h>\n#include <proj_api.h>\n#include \"elevation.hxx\"\n#include \"ObjWriter.hxx\"\n#include \"Delaunay.h\"\n\nusing namespace std;\nusing namespace osmwave;\n\nstatic projPJ wgs84 = pj_init_plus(\"+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs\");\n\n// Note: in place addition\nstatic void vecAdd(XYZ& a, const XYZ& b) {\n    a.x += b.x;\n    a.y += b.y;\n    a.z += b.z;\n}\n\nstatic void vecSub(const XYZ& a, const XYZ& b, XYZ& result) {\n    result.x = a.x - b.x;\n    result.y = a.y - b.y;\n    result.z = a.z - b.z;\n}\n\nstatic void triangleNormal(const XYZ* coords, const ITRIANGLE& tri, XYZ& normal) {\n    XYZ u;\n    XYZ v;\n\n    vecSub(coords[tri.p2], coords[tri.p1], u);\n    vecSub(coords[tri.p3], coords[tri.p1], v);\n\n    normal.x = u.y*v.z - u.z*v.y;\n    normal.y = u.z*v.x - u.x*v.z;\n    normal.z = u.x*v.y - u.y*v.x;\n\n    double l = sqrt(normal.x*normal.x+normal.y*normal.y+normal.z*normal.z);\n\n    normal.x = normal.x / l;\n    normal.y = normal.y / l;\n    normal.z = normal.z / l;\n}\n\nstatic double findNearHeight(int rows, int cols, int index, int dx, int dy, XYZ* verts) {\n    int s = index;\n    do {\n        s += dx * rows + dy;\n    } while (std::isnan(verts[s].z));\n\n    return verts[s].z;\n}\n\nstatic int thin(int rows, int cols, XYZ* verts, double tolerance) {\n    int index = 0;\n    int nonEmpty = 0;\n\n    for (int i = 1; i < cols - 1; i++) {\n        for (int j = 1; j < rows - 1; j++) {\n            if (!std::isnan(verts[index].z)) {\n                double e1 = verts[index].z;\n                double e2 = findNearHeight(rows, cols, index, 1, -1, verts);\n                double e3 = findNearHeight(rows, cols, index, 1, 0, verts);\n                double e4 = findNearHeight(rows, cols, index, 1, 1, verts);\n                double d2 = abs(e1 - e2);\n                double d3 = abs(e1 - e3);\n                double d4 = abs(e1 - e4);\n\n                if (d2 <= tolerance &&\n                    d3 <= tolerance &&\n                    d4 <= tolerance) {\n                    verts[index].z = NAN;\n                } else {\n                    nonEmpty++;\n                }\n            }\n\n            index++;\n        }\n    }\n\n    return nonEmpty;\n}\n\nvoid terrain_to_obj(const std::string& elevationPath, const std::string& projDef, double x1, double y1, double x2, double y2) {\n    Elevation elevation(floor(y1), floor(x1), ceil(y2), ceil(x2), elevationPath);\n    ObjWriter writer(cout);\n    projPJ proj = pj_init_plus(projDef.c_str());\n    double step = 1.0 / 3600;\n    int rows = (int)floor((y2 - y1) / step + 1);\n    int cols = (int)floor((x2 - x1) / step + 1);\n    double bounds[] = {x1*DEG_TO_RAD, y1*DEG_TO_RAD, x2*DEG_TO_RAD, y2*DEG_TO_RAD};\n\n    pj_transform(wgs84, proj, 2, 2, (double*)&bounds, (double*)&bounds + 1, nullptr);\n\n    cerr << \"rows: \" << rows << \", cols: \" << cols << endl;\n    cerr << \"bounds: \" << bounds[0] << \", \" << bounds[1] << \" - \" << bounds[2] << \", \" << bounds[3] << endl;\n\n    cerr << \"Calculating vertices...\" << endl;\n    XYZ* coords = new XYZ[rows * cols + 3];\n    XYZ* normals = new XYZ[rows * cols];\n\n    int i = 0;\n    // Having columns as outer loop ensures x will be growing,\n    // which is a requirement for the triangulation algorithm,\n    // as long as projection is west to east.\n    for (int c = 0; c < cols; c++) {\n        double x = bounds[0] + (bounds[2] - bounds[0]) * c / cols;\n        for (int r = 0; r < rows; r++) {\n            double y = bounds[1] + (bounds[3] - bounds[1]) * r / rows;\n            double ll[2] = {x, y};\n            pj_transform(proj, wgs84, 1, 2, (double*)&ll, (double*)&ll + 1, nullptr);\n\n            XYZ& coord = coords[i++];\n            coord.x = x;\n            coord.y = y;\n            coord.z = elevation.elevation(ll[1]*RAD_TO_DEG, ll[0]*RAD_TO_DEG);\n\n            //cerr << (ll[0] * RAD_TO_DEG) << \", \" << (ll[1] * RAD_TO_DEG) << \" (\" << coord.x << \", \" << coord.y << \"): \" << coord.z << endl;\n        }\n    }\n\n    int startCount = rows * cols,\n        lastCount = 0,\n        count = -1;\n    cerr << \"Thinning \" << startCount << \" vertices...\" << endl;\n    while (lastCount != count) {\n        lastCount = count;\n        count = thin(rows, cols, coords, 2);\n    }\n\n    int j = 0;\n    for (int i = 0; i < rows * cols; i++) {\n        if (!std::isnan(coords[i].z)) {\n            coords[j++] = coords[i];\n        }\n    }\n    cerr << \"Thinned to \" << j << \" vertices\" << endl;\n\n    cerr << \"Triangulating...\" << endl;\n    ITRIANGLE *tris = new ITRIANGLE[3 * rows * cols];\n    int numTriangles;\n    Triangulate(j, coords, tris, numTriangles);\n    cerr << numTriangles << \" triangles\" << endl;\n\n    memset((void*)normals, 0, sizeof(XYZ) * j);\n    for (int i = 0; i < numTriangles; i++) {\n        XYZ normal;\n        triangleNormal(coords, tris[i], normal);\n        vecAdd(normals[tris[i].p1], normal);\n        vecAdd(normals[tris[i].p2], normal);\n        vecAdd(normals[tris[i].p3], normal);\n    }\n\n    writer.checkpoint();\n    for (int i = 0; i < j; i++) {\n        writer.vertex(coords[i].y, coords[i].z, coords[i].x, normals[i].y, normals[i].z, normals[i].x);\n    }\n\n    for (int i = 0; i < numTriangles; i++) {\n        writer.beginFace();\n        writer << tris[i].p1 << tris[i].p2 << tris[i].p3;\n        writer.endFace();\n    }\n\n    delete coords;\n    delete normals;\n    delete tris;\n}\n\nint main(int argc, char* argv[]) {\n    namespace po = boost::program_options;\n    po::options_description desc(\"Options\");\n    desc.add_options()\n        (\"elevation_dir,e\", po::value<string>()->required(), \"Set directory containing elevation data\")\n        (\"proj,p\", po::value<string>(), \"Projection definition\")\n        (\"x1\", po::value<double>()->required(), \"X1\")\n        (\"y1\", po::value<double>()->required(), \"Y1\")\n        (\"x2\", po::value<double>()->required(), \"X2\")\n        (\"y2\", po::value<double>()->required(), \"Y2\");\n    po::positional_options_description positionOptions;\n    positionOptions.add(\"x1\", 1);\n    positionOptions.add(\"y1\", 1);\n    positionOptions.add(\"x2\", 1);\n    positionOptions.add(\"y2\", 1);\n\n    po::variables_map vm;\n    try {\n        po::store(po::command_line_parser(argc, argv)\n            .options(desc)\n            .positional(positionOptions)\n            .run(), vm);\n\n        po::notify(vm);\n    } catch (po::error& e) {\n        cerr << \"Error \" << e.what() << endl << endl;\n        cerr << desc << endl;\n        return 1;\n    }\n\n    const string& elevPath(vm[\"elevation_dir\"].as<string>());\n    const string* projDef = nullptr;\n    const double x1 = vm[\"x1\"].as<double>();\n    const double y1 = vm[\"y1\"].as<double>();\n    const double x2 = vm[\"x2\"].as<double>();\n    const double y2 = vm[\"y2\"].as<double>();\n\n    if (vm.count(\"proj\")) {\n        projDef = &vm[\"proj\"].as<string>();\n    } else {\n        ostringstream stream;\n        stream << \"+proj=tmerc +lat_0=\" << ((y1 + y2) / 2) << \" +lon_0=\" << ((x1 + x2) / 2) << \" +k=1.000000 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs\";\n        projDef = new string(stream.str());\n    }\n\n    terrain_to_obj(elevPath, *projDef, x1, y1, x2, y2);\n\n    return 0;\n}\n\n", "meta": {"hexsha": "eca116be3640c1de8b4a9b9592eda5333a4d8231", "size": 7081, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/terrain.cxx", "max_stars_repo_name": "perliedman/osmwave", "max_stars_repo_head_hexsha": "a0ffa931844702cdc31b83f27d2632651973026a", "max_stars_repo_licenses": ["0BSD"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2015-12-05T17:27:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T04:45:41.000Z", "max_issues_repo_path": "src/terrain.cxx", "max_issues_repo_name": "perliedman/osmwave", "max_issues_repo_head_hexsha": "a0ffa931844702cdc31b83f27d2632651973026a", "max_issues_repo_licenses": ["0BSD"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-08-14T10:26:21.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-17T10:33:22.000Z", "max_forks_repo_path": "src/terrain.cxx", "max_forks_repo_name": "perliedman/osmwave", "max_forks_repo_head_hexsha": "a0ffa931844702cdc31b83f27d2632651973026a", "max_forks_repo_licenses": ["0BSD"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-11-08T10:15:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-23T12:20:49.000Z", "avg_line_length": 32.0407239819, "max_line_length": 168, "alphanum_fraction": 0.5333992374, "num_tokens": 2137, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240964782011, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4996629055632428}}
{"text": "#ifndef MLT_MODELS_TRANSFORMERS_SPARSE_TIED_AUTOENCODER_HPP\n#define MLT_MODELS_TRANSFORMERS_SPARSE_TIED_AUTOENCODER_HPP\n\n#include <cmath>\n#include <tuple>\n#include <type_traits>\n\n#include <Eigen/Core>\n\n#include \"transformer.hpp\"\n#include \"../implementations/autoencoder.hpp\"\n#include \"../../utils/eigen.hpp\"\n\nnamespace mlt {\nnamespace models {\nnamespace transformers {\n\tusing namespace utils::eigen;\n\n\ttemplate <class HiddenActivation, class ReconstructionActivation, class Optimizer>\n\tclass SparseTiedAutoencoder : public Transformer<SparseTiedAutoencoder<HiddenActivation, ReconstructionActivation, Optimizer>> {\n\tpublic:\n\t\ttemplate <typename H, typename R, typename O,\n\t\t\tclass = enable_if<is_convertible<decay_t<H>, HiddenActivation>::value\n\t\t\t&& is_convertible<decay_t<R>, ReconstructionActivation>::value\n\t\t\t&& is_convertible<decay_t<O>, Optimizer>::value>>\n\t\texplicit SparseTiedAutoencoder(int hidden_units, H&& hidden_activation, R&& reconstruction_activation, O&& optimizer, double regularization,\n\t\tdouble sparsity, double sparsity_weight) : _hidden_units(hidden_units), _hidden_activation(forward<H>(hidden_activation)),\n\t\t\t_reconstruction_activation(forward<R>(reconstruction_activation)), _optimizer(forward<O>(optimizer)), _regularization(regularization),\n\t\t\t_sparsity(sparsity), _sparsity_weight(sparsity_weight) {}\n\n\t\tResult transform(Features input) const {\n\t\t\tassert(_fitted);\n\t\t\treturn _hidden_activation.compute((_weights * input).colwise() + _hidden_intercepts);\n\t\t}\n\n\t\tSelf& fit(Features input, bool cold_start = true) {\n\t\t\tVectorXd init(_hidden_units * input.rows() + _hidden_units + input.rows());\n\n\t\t\tif (_fitted && !cold_start) {\n\t\t\t\tinit.block(0, 0, _weights.size(), 1) = ravel(_weights);\n\t\t\t\tinit.block(_weights.size(), 0, _hidden_intercepts.size(), 1) = _hidden_intercepts;\n\n\t\t\t\tinit.block(_weights.size() + _hidden_intercepts.size(),\n\t\t\t\t\t0, _reconstruction_intercepts.size(), 1) = _reconstruction_intercepts;\n\t\t\t} else {\n\t\t\t\tinit = (init.setRandom() * 4 / sqrt(6.0 / (_hidden_units + input.rows())));\n\t\t\t}\n\n\t\t\tVectorXd coeffs = _optimizer(*this, input, input, init, cold_start);\n\n\t\t\t_weights = unravel(coeffs.block(0, 0, _hidden_units * input.rows(), 1), _hidden_units, input.rows());\n\t\t\t_hidden_intercepts = coeffs.block(_hidden_units * input.rows(), 0, _hidden_units, 1);\n\t\t\t_reconstruction_intercepts = coeffs.block(_hidden_units * input.rows() + _hidden_units, 0, input.rows(), 1);\n\n\t\t\t_fitted = true;\n\n\t\t\treturn _self();\n\t\t}\n\n\t\tusing Transformer<Self>::fit;\n\n\t\tauto loss(VectorXdRef coeffs, Features input, Features target) const {\n\t\t\tauto weights = unravel(coeffs.block(0, 0, _hidden_units * input.rows(), 1), _hidden_units, input.rows());\n\t\t\tauto hidden_intercepts = coeffs.block(_hidden_units * input.rows(), 0, _hidden_units, 1);\n\t\t\tauto reconstruction_intercepts = coeffs.block(_hidden_units * input.rows() + _hidden_units, 0, input.rows(), 1);\n\n\t\t\treturn implementations::autoencoder::sparse_loss(_hidden_activation, _reconstruction_activation, weights, hidden_intercepts,\n\t\t\t\tweights.transpose(), reconstruction_intercepts, _regularization, _sparsity, _sparsity_weight, input, target);\n\t\t}\n\n\t\tauto gradient(VectorXdRef coeffs, Features input, Features target) const {\n\t\t\tauto weights = unravel(coeffs.block(0, 0, _hidden_units * input.rows(), 1), _hidden_units, input.rows());\n\t\t\tauto hidden_intercepts = coeffs.block(_hidden_units * input.rows(), 0, _hidden_units, 1);\n\t\t\tauto reconstruction_intercepts = coeffs.block(_hidden_units * input.rows() + _hidden_units, 0, input.rows(), 1);\n\n\t\t\tMatrixXd weights_grad, weights_transp_grad;\n\t\t\tVectorXd hid_inter_grad, rec_inter_grad;\n\t\t\ttie(weights_grad, hid_inter_grad, weights_transp_grad, rec_inter_grad) = implementations::autoencoder::sparse_gradient(_hidden_activation,\n\t\t\t\t_reconstruction_activation, weights, hidden_intercepts, weights.transpose(), reconstruction_intercepts, _regularization, \n\t\t\t\t_sparsity, _sparsity_weight, input, target);\n\n\t\t\tVectorXd gradient(coeffs.rows());\n\n\t\t\tgradient.block(0, 0, weights_grad.size(), 1) = ravel(weights_grad + weights_transp_grad.transpose());\n\t\t\tgradient.block(weights_grad.size(), 0, hid_inter_grad.size(), 1) = hid_inter_grad;\n\n\t\t\tgradient.block(weights_grad.size() + hid_inter_grad.size(),\n\t\t\t\t0, rec_inter_grad.size(), 1) = rec_inter_grad;\n\n\t\t\treturn gradient;\n\t\t}\n\n\t\tauto loss_and_gradient(VectorXdRef coeffs, Features input, Features target) const {\n\t\t\tauto weights = unravel(coeffs.block(0, 0, _hidden_units * input.rows(), 1), _hidden_units, input.rows());\n\t\t\tauto hidden_intercepts = coeffs.block(_hidden_units * input.rows(), 0, _hidden_units, 1);\n\t\t\tauto reconstruction_intercepts = coeffs.block(_hidden_units * input.rows() + _hidden_units, 0, input.rows(), 1);\n\n\t\t\tdouble loss;\n\t\t\tMatrixXd weights_grad, weights_transp_grad;\n\t\t\tVectorXd hid_inter_grad, rec_inter_grad;\n\t\t\ttie(loss, weights_grad, hid_inter_grad, weights_transp_grad, rec_inter_grad) = implementations::autoencoder::sparse_loss_and_gradient(\n\t\t\t\t_hidden_activation, _reconstruction_activation, weights, hidden_intercepts, weights.transpose(), reconstruction_intercepts,\n\t\t\t\t_regularization, _sparsity, _sparsity_weight, input, target);\n\n\t\t\tVectorXd gradient(coeffs.rows());\n\n\t\t\tgradient.block(0, 0, weights_grad.size(), 1) = ravel(weights_grad + weights_transp_grad.transpose());\n\t\t\tgradient.block(weights_grad.size(), 0, hid_inter_grad.size(), 1) = hid_inter_grad;\n\n\t\t\tgradient.block(weights_grad.size() + hid_inter_grad.size(),\n\t\t\t\t0, rec_inter_grad.size(), 1) = rec_inter_grad;\n\n\t\t\treturn make_tuple(loss, gradient);\n\t\t}\n\n\tprotected:\n\t\tint _hidden_units;\n\t\tHiddenActivation _hidden_activation;\n\t\tReconstructionActivation _reconstruction_activation;\n\t\tOptimizer _optimizer;\n\t\tdouble _regularization;\n\t\tdouble _sparsity;\n\t\tdouble _sparsity_weight;\n\n\t\tMatrixXd _weights;\n\t\tVectorXd _hidden_intercepts;\n\t\tVectorXd _reconstruction_intercepts;\n\t};\n\n\ttemplate <class HiddenActivation, class ReconstructionActivation, class Optimizer>\n\tauto create_sparse_tied_autoencoder(int hidden_units, HiddenActivation&& hidden_activation,\n\tReconstructionActivation&& reconstruction_activation, Optimizer&& optimizer,\n\tdouble regularization, double sparsity, double sparsity_weight) {\n\t\treturn SparseTiedAutoencoder<HiddenActivation, ReconstructionActivation, Optimizer>(\n\t\t\thidden_units,\n\t\t\tforward<HiddenActivation>(hidden_activation), \n\t\t\tforward<ReconstructionActivation>(reconstruction_activation),\n\t\t\tforward<Optimizer>(optimizer),\n\t\t\tregularization, sparsity, sparsity_weight);\n\t}\n}\n}\n}\n#endif", "meta": {"hexsha": "626ead3dc3c567dc548f82ab4764fcac84bf45b9", "size": 6500, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/mlt/models/transformers/sparse_tied_autoencoder.hpp", "max_stars_repo_name": "fedeallocati/MachineLearningToolkit", "max_stars_repo_head_hexsha": "8614ee2c8c5211a3eefceb10a50576e0485cefd9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-08-31T11:43:19.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-22T11:03:47.000Z", "max_issues_repo_path": "src/mlt/models/transformers/sparse_tied_autoencoder.hpp", "max_issues_repo_name": "fedeallocati/MachineLearningToolkit", "max_issues_repo_head_hexsha": "8614ee2c8c5211a3eefceb10a50576e0485cefd9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mlt/models/transformers/sparse_tied_autoencoder.hpp", "max_forks_repo_name": "fedeallocati/MachineLearningToolkit", "max_forks_repo_head_hexsha": "8614ee2c8c5211a3eefceb10a50576e0485cefd9", "max_forks_repo_licenses": ["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.1388888889, "max_line_length": 142, "alphanum_fraction": 0.7663076923, "num_tokens": 1568, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.49966289753538856}}
{"text": "#include <boost/gil.hpp>\n#include <boost/gil/extension/io/jpeg.hpp>\n#include <boost/gil/extension/numeric/sampler.hpp>\n#include <boost/gil/extension/numeric/resample.hpp>\n#include <boost/gil/extension/numeric/kernel.hpp>\n#include <boost/gil/extension/numeric/convolve.hpp>\n\n#include <cmath>\n\nusing namespace std;\nusing namespace boost::gil;\n\n// value of strong edge pixel\nstatic const int TOP_VALUE = 255;\n// value of weak (maybe edge) pixel\nstatic const int MIDDLE_VALUE = 150;\n// value of definitely not-edge pixel\nstatic const int BOTTOM_VALUE = 0;\n\n// Example how to detect edges via Canny algorithm\n// Read more about Canny edge detection algorithm on\n// https://docs.opencv.org/3.1.0/da/d22/tutorial_py_canny.html\n\ntemplate <typename SrcView>\nvoid gaussian_blur(const SrcView &src)\n{\n    //1-D Gaussian blur kernel with kernel size 5, Sigma 1.0\n    float gaussian[] = {0.06136f, 0.24477f, 0.38774f, 0.24477f, 0.06136f};\n    kernel_1d<float> kernel(gaussian, 5, 2);\n\n    convolve_rows<gray32f_pixel_t>(src, kernel, src, convolve_option_output_ignore);\n    convolve_cols<gray32f_pixel_t>(src, kernel, src, convolve_option_output_ignore);\n}\n\n// Function calculates image gradient (intensity and direction)\n// Smoothened image is filtered with a Sobel kernels in both horizontal and vertical\n// direction to get first derivative in horizontal direction (Gx) and vertical direction (Gy).\n// Gradient manitude is found as G = sqrt(Gx^2 + Gy^2)\n// Direction is found as angle = arctan(Gy / Gx)\n// More information about sobel filtering on https://en.wikipedia.org/wiki/Sobel_operator\nvoid sobel_filtering(const gray8c_view_t &src,\n                     const gray8_view_t &magnitude, const gray32f_view_t &slope)\n{\n    // This we used 1-D convolution\n    // Gx = second * (first * img)\n    // Gy = first * (second * img)\n    // where * is convolution\n    float first_sobel[] = {1.f, 0.f, -1.f};\n    float second_sobel[] = {1.f, 2.f, 1.f};\n\n    kernel_1d<float> first_sobel_kernel(first_sobel, 3, 1);\n    kernel_1d<float> second_sobel_kernel(second_sobel, 3, 1);\n\n    //16 bits signed matrix is used in order to avoid char overflow\n    gray16s_image_t vertical(src.dimensions());\n    gray16s_image_t horizontal(src.dimensions());\n\n    convolve_rows<gray32f_pixel_t>(src, first_sobel_kernel,\n                                   view(vertical), convolve_option_output_zero);\n    convolve_cols<gray32f_pixel_t>(const_view(vertical), second_sobel_kernel,\n                                   view(vertical), convolve_option_output_zero);\n\n    convolve_rows<gray32f_pixel_t>(src, second_sobel_kernel, view(horizontal),\n                                   convolve_option_output_zero);\n    convolve_cols<gray32f_pixel_t>(const_view(horizontal), first_sobel_kernel,\n                                   view(horizontal), convolve_option_output_zero);\n\n    // Magnitude and angle calculation\n    auto ver_it = view(vertical).begin();\n    auto hor_it = view(horizontal).begin();\n    auto slope_it = slope.begin();\n\n    for (auto mag_it = magnitude.begin(); mag_it != magnitude.end();\n            ++mag_it, ++ver_it, ++hor_it, ++slope_it) {\n\n        // std::min was used to be sure, that pixel max value less than 256\n        *mag_it = std::min(UINT8_MAX,\n                           (int)std::sqrt(\n                               std::pow((int)(*ver_it), 2) + std::pow((int)(*hor_it), 2)));\n\n        *slope_it = (float)std::atan2((int)(*hor_it), (int)(*ver_it));\n    }\n}\n\n// Non-maximum suppression method is perfomed to thin out edges of the image\n// Method goes throug all the points on the gradient intensity matrix and\n// finds the pixels with maximum value in the edge direction\nvoid non_maximal_suppression(const gray8c_view_t &magnitude, const gray32fc_view_t &angle,\n                             const gray8_view_t &dst)\n{\n    // Dst matrix fills with 0\n    fill_pixels(dst, int8_t(0));\n\n    auto mag_loc = magnitude.xy_at(1, 1);\n    int q, r;\n    int index;\n    int curVal;\n    for (int y = 1; y < magnitude.height() - 1; ++y) {\n        auto dst_it = dst.row_begin(y);\n        auto angle_it = angle.row_begin(y);\n\n        for (int x = 1; x < dst.width() - 1; ++x, ++angle_it, ++dst_it, ++mag_loc.x()) {\n            // Index helps to find direction of the edge\n            // Pixel has 8 neighbors and 4 possible directions\n            // (-1,-1) (0,-1) (1,-1)\n            // (-1, 0) (0, 0) (1, 0)\n            // (-1, 1) (0, 1) (1, 1)\n            // On each direction 2 possible neighbors\n            // If both of them is smaller than current value (0, 0),\n            // then current value is saved in output image\n            index = (int)((*angle_it)[0] * 8 / M_PI);\n            index = (index < 0) ? index + 8 : index;\n\n            curVal = mag_loc(0, 0);\n\n            switch (index) {\n            // Horizontal direction\n            case 0:\n            case 7:\n            case 8:\n                q = mag_loc(1, 0);\n                r = mag_loc(-1, 0);\n                break;\n            // 45 degree\n            case 1:\n            case 2:\n                q = mag_loc(1, 1);\n                r = mag_loc(-1, -1);\n                break;\n            // Vertical direction\n            case 3:\n            case 4:\n                q = mag_loc(0, 1);\n                r = mag_loc(0, -1);\n                break;\n            // 135 degree\n            case 5:\n            case 6:\n                q = mag_loc(1, -1);\n                r = mag_loc(-1, 1);\n                break;\n            }\n\n            if ((curVal >= q) && (curVal >= r)) {\n                *dst_it = curVal;\n            }\n        }\n        mag_loc += point2<std::ptrdiff_t>(-dst.width() + 2, 1);\n    }\n}\n\nvoid hysteresis_threshold(const gray8_view_t &dst, int minVal, int maxVal)\n{\n    // Histogram calculation of 3 groups: strong pixel, weak pixel, definitely not-edge pixel\n    for_each_pixel(dst, [minVal, maxVal](gray8_pixel_t &pixel) {\n        pixel = (pixel < minVal) ? BOTTOM_VALUE :\n                ((pixel > maxVal) ? TOP_VALUE : MIDDLE_VALUE);\n    });\n\n    // Weak pixels check\n    // If weak pixel has a strong neighbor, then it is strong one\n    // otherwise it is definitely not-edge pixel\n    auto dst_loc = dst.xy_at(1, 1);\n    for (int i = 1; i < dst.height() - 1; ++i) {\n        for (int j = 1; j < dst.width() - 1; ++j, ++dst_loc.x()) {\n            if (dst_loc(0, 0) == MIDDLE_VALUE) {\n                if (dst_loc(-1, -1) == TOP_VALUE || dst_loc(-1, 0) == TOP_VALUE ||\n                        dst_loc(-1, 1) == TOP_VALUE || dst_loc(1, -1) == TOP_VALUE ||\n                        dst_loc(1, 0) == TOP_VALUE || dst_loc(1, 1) == TOP_VALUE ||\n                        dst_loc(0, -1) == TOP_VALUE || dst_loc(0, 1) == TOP_VALUE)\n                    dst_loc(0, 0) = TOP_VALUE;\n                else\n                    dst_loc(0, 0) = BOTTOM_VALUE;\n            }\n        }\n        dst_loc += point2<std::ptrdiff_t>(-dst.width() + 2, 1);\n    }\n}\n\nvoid canny_edge_detection(const rgb8c_view_t &src,\n                          const gray8_view_t &dst, int minVal, int maxVal)\n{\n    // Canny edge detection algorithm works on grayscale images only\n    gray8_image_t gray_img(src.dimensions());\n    copy_pixels(color_converted_view<gray8_pixel_t>(src), view(gray_img));\n\n    gaussian_blur(view(gray_img));\n\n    gray32f_image_t angle(src.dimensions());\n    gray8_image_t magnitude(src.dimensions());\n    sobel_filtering(view(gray_img), view(magnitude), view(angle));\n\n    non_maximal_suppression(view(magnitude), view(angle), dst);\n\n    hysteresis_threshold(dst, minVal, maxVal);\n}\n\nint main(int argc, char *argv[])\n{\n    char *input = \"test.jpg\";\n    char *output = \"canny.jpg\";\n    int min_threshold_value = 30;\n    int max_threshold_value = 70;\n\n    if (argc >= 2 && (argv[1][0] == '-') && (argv[1][1] == 'H' || argv[1][1] == 'h')) {\n        printf(\"canny [path_to_input [path_to_output \"\n               \"[min_threshold_value [max_threshold_value]]]]\\n\");\n        return 0;\n    }\n    if (argc >= 2) input = argv[1];\n    if (argc >= 3) output = argv[2];\n    if (argc >= 4) min_threshold_value = atoi(argv[3]);\n    if (argc >= 5) max_threshold_value = atoi(argv[4]);\n\n    if (min_threshold_value > max_threshold_value)\n        std::swap(min_threshold_value, max_threshold_value);\n\n    rgb8_image_t img;\n    read_image(input, img, jpeg_tag{});\n\n    gray8_image_t res_img(img.dimensions());\n    canny_edge_detection(const_view(img), view(res_img),\n                         min_threshold_value, max_threshold_value);\n    write_view(output, view(res_img), jpeg_tag{});\n    return 0;\n}\n", "meta": {"hexsha": "1f8af033ffa006bc4536d6563b6978a70440f445", "size": 8534, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/canny.cpp", "max_stars_repo_name": "Antropovi/gil", "max_stars_repo_head_hexsha": "1f67b483956e655a391906a1c84f40572d2d8403", "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": "example/canny.cpp", "max_issues_repo_name": "Antropovi/gil", "max_issues_repo_head_hexsha": "1f67b483956e655a391906a1c84f40572d2d8403", "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": "example/canny.cpp", "max_forks_repo_name": "Antropovi/gil", "max_forks_repo_head_hexsha": "1f67b483956e655a391906a1c84f40572d2d8403", "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.5947136564, "max_line_length": 94, "alphanum_fraction": 0.5925708929, "num_tokens": 2283, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702880639791, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.4996571563768525}}
{"text": "/**\n * @file\n * @brief Solution of source-free heat equation and computation of H1\n *  \t  seminorms on different triangular meshes and refinement levels\n * @author Julien Gacon, Am\u00e9lie Loher\n * @date   March 2019\n */\n\n#include \"unstablebvp.h\"\n// General includes\n#include <array>\n#include <fstream>\n#include <memory>\n#include <string>\n// Eigen\n#include <Eigen/Core>\n#include <Eigen/SparseLU>\n// Lehrfempp\n#include <lf/assemble/assemble.h>\n#include <lf/base/base.h>\n#include <lf/geometry/geometry.h>\n#include <lf/mesh/hybrid2d/hybrid2d.h>\n#include <lf/uscalfe/uscalfe.h>\n\nnamespace UnstableBVP {\n\nstd::shared_ptr<lf::refinement::MeshHierarchy> createMeshHierarchy(\n    const int reflevels, const std::string &mesh_type) {\n  // Helper object: mesh factory\n  std::shared_ptr<lf::mesh::hybrid2d::MeshFactory> mesh_factory_ptr =\n      std::make_shared<lf::mesh::hybrid2d::MeshFactory>(2);\n\n  // Decide where the triangular domain should be located in x_2 direction\n  // by adding an offset to the x_2 coordinate of the nodes\n  double offset = 0;\n  if (mesh_type == \"top\") {\n    offset = 1.5;\n  } else if (mesh_type == \"bottom\") {\n    offset = -1.5;\n  } else {\n    // already at 0\n  }\n\n  // Define the nodes\n  std::array<std::array<double, 2>, 3> node_coord{\n      std::array<double, 2>({0.5, -0.5 + offset}),\n      std::array<double, 2>({0, 0.5 + offset}),\n      std::array<double, 2>({1, 0.5 + offset})};\n\n  for (const auto &node : node_coord) {\n    mesh_factory_ptr->AddPoint(Eigen::Vector2d({node[0], node[1]}));\n  }\n\n  // Initialize triangle\n  mesh_factory_ptr->AddEntity(lf::base::RefEl::kTria(),\n                              std::vector<lf::base::size_type>({0, 1, 2}),\n                              std::unique_ptr<lf::geometry::Geometry>(nullptr));\n\n  // Get a pointer to the mesh\n  std::shared_ptr<lf::mesh::Mesh> mesh_p = mesh_factory_ptr->Build();\n\n  // (optional) Print information about the mesh\n  // std::cout << \"   Mesh info\\n\" << *mesh_p;\n\n  // Ask LehrFEM++ to create a hierarchy of nested meshes\n  std::shared_ptr<lf::refinement::MeshHierarchy> multi_mesh_p =\n      lf::refinement::GenerateMeshHierarchyByUniformRefinemnt(mesh_p,\n                                                              reflevels);\n\n  return multi_mesh_p;\n}\n\ndouble solveTemperatureDistribution(\n    std::shared_ptr<const lf::mesh::Mesh> mesh_p) {\n  // **********************************************************************\n  // Stage 0: provide all coefficient functions mainly through lambda\n  //          functions and derived MeshFunctions\n  // **********************************************************************\n\n  // The boundary condition\n  auto bc = [](Eigen::Vector2d x) -> double {\n    return x[1] <= 0 ? 1 - x[1] : 0;\n  };\n  // Wrap into a MeshFunction\n  lf::mesh::utils::MeshFunctionGlobal mf_bc{bc};\n\n  // We use lowest-order (p.w. linear Lagrangian finite elements), for which\n  // LehrFEM++ provides a built-in description according to the paradigm of\n  // parametric finite elements.\n  auto fe_space =\n      std::make_shared<lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n  // Reference to current mesh\n  const lf::mesh::Mesh &mesh{*(fe_space->Mesh())};\n  // Obtain local->global index mapping for current finite element space\n  const lf::assemble::DofHandler &dofh{fe_space->LocGlobMap()};\n\n  // **********************************************************************\n  // Stage 1: Assemble finite element Galerkin matrix\n  // **********************************************************************\n\n  // Dimension of finite element space`\n  const lf::base::size_type N_dofs(dofh.NumDofs());\n  // Matrix in triplet format holding Galerkin matrix, zero initially.\n  lf::assemble::COOMatrix<double> A(N_dofs, N_dofs);\n\n  // Element matrix builder for the negative Laplacian\n  lf::uscalfe::LinearFELaplaceElementMatrix elmat_builder{};\n\n  // Invoke assembly on cells (co-dimension = 0 as first argument)\n  // Information about the mesh and the local-to-global map is passed through\n  // a Dofhandler object, argument 'dofh'. This function call adds triplets to\n  // the internal COO-format representation of the sparse matrix A.\n  lf::assemble::AssembleMatrixLocally(0, dofh, dofh, elmat_builder, A);\n\n  // **********************************************************************\n  // Stage 2: Right-hand side vector\n  // **********************************************************************\n\n  // Define RHS vector\n  // No source, hence it is simply zero\n  Eigen::Matrix<double, Eigen::Dynamic, 1> phi(N_dofs);\n  phi.setZero();\n\n  // **********************************************************************\n  // Stage 3: Fixing solution components according to essential (Dirichlet)\n  //          boundary conditions\n  // **********************************************************************\n\n  // Obtain specification for shape functions on edges\n  std::shared_ptr<const lf::uscalfe::ScalarReferenceFiniteElement<double>>\n      rsf_edge_p = fe_space->ShapeFunctionLayout(lf::base::RefEl::kSegment());\n  LF_ASSERT_MSG(rsf_edge_p != nullptr, \"FE specification for edges missing\");\n\n  // Obtain an array of boolean flags for the edges (codim 1) of the mesh,\n  // `true` indicates that the edge lies on the boundary\n  auto bd_flags{lf::mesh::utils::flagEntitiesOnBoundary(fe_space->Mesh(), 1)};\n\n  // Fetch flags and values for degrees of freedom located on Dirichlet\n  // edges.\n  auto ess_bdc_flags_values{lf::uscalfe::InitEssentialConditionFromFunction(\n      dofh, *rsf_edge_p,\n      [&bd_flags](const lf::mesh::Entity &edge) -> bool {\n        return (bd_flags(edge));\n      },\n      mf_bc)};\n\n  // Eliminate Dirichlet dofs from linear system\n  lf::assemble::FixFlaggedSolutionComponents<double>(\n      [&ess_bdc_flags_values](lf::assemble::glb_idx_t gdof_idx) {\n        return ess_bdc_flags_values[gdof_idx];\n      },\n      A, phi);\n\n  // **********************************************************************\n  // Stage 4: Solve LSE\n  // **********************************************************************\n\n  // Assembly completed: Convert COO matrix A into CRS format using Eigen's\n  // internal conversion routines.\n  Eigen::SparseMatrix<double> A_crs = A.makeSparse();\n\n  // Solve linear system using Eigen's sparse direct elimination\n  Eigen::SparseLU<Eigen::SparseMatrix<double>> solver;\n  solver.compute(A_crs);\n  LF_VERIFY_MSG(solver.info() == Eigen::Success, \"LU decomposition failed\");\n  Eigen::VectorXd sol_vec = solver.solve(phi);\n  LF_VERIFY_MSG(solver.info() == Eigen::Success, \"Solving LSE failed\");\n\n  // **********************************************************************\n  // Stage 5: Compute H1 seminorm\n  // **********************************************************************\n\n  // Compute the difference to a function that's zero everywhere, hence\n  // just the gradient of the solution (which is encapsulated in the fe_space).\n  // We use this trick to avoid the manual computation and make use of the\n  // LehrFEM facilities :)\n  lf::uscalfe::MeshFunctionL2GradientDifference loc_comp(\n      fe_space,\n      lf::mesh::utils::MeshFunctionConstant(Eigen::Vector2d(0.0, 0.0)), 2);\n\n  // Compute the norm of the ``difference'' (i.e. the norm of the gradient of\n  // the solution)\n  const double norm = lf::uscalfe::NormOfDifference(dofh, loc_comp, sol_vec);\n\n  return norm;\n}\n\n}  // namespace UnstableBVP\n", "meta": {"hexsha": "c93ac3118d2fed153b4301f0e1b34b6ba9e7ee89", "size": 7338, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/UnstableBVP/templates/unstablebvp.cc", "max_stars_repo_name": "padomu/NPDECODES", "max_stars_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "homeworks/UnstableBVP/templates/unstablebvp.cc", "max_issues_repo_name": "padomu/NPDECODES", "max_issues_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homeworks/UnstableBVP/templates/unstablebvp.cc", "max_forks_repo_name": "padomu/NPDECODES", "max_forks_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_forks_repo_licenses": ["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.8253968254, "max_line_length": 80, "alphanum_fraction": 0.6046606705, "num_tokens": 1786, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.689305616785446, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.4996571528095028}}
{"text": "#include \"sv/util/eigen.h\"\n\n#include <Eigen/Cholesky>\n\n#include \"sv/util/logging.h\"\n\nnamespace sv {\n\nvoid StableRotateBlockTopLeft(MatrixXdRef H,\n                              VectorXdRef b,\n                              int block_ind,\n                              int block_size) {\n  CHECK_EQ(H.rows(), b.size());\n  CHECK_EQ(H.cols(), b.size());\n  CHECK_GE(block_ind, 0);\n  CHECK_GT(block_size, 0);\n  CHECK_LT(block_ind * block_size, H.rows());\n\n  if (block_ind == 0) return;\n  const auto n = block_size;\n\n  // Permute block of rows up gradually, also need to permute b\n  for (int i = block_ind; i > 0; --i) {\n    const auto r = i * block_size;\n    // swap current rows with above rows\n    H.middleRows(r, n).swap(H.middleRows(r - n, n));\n    b.segment(r, n).swap(b.segment(r - n, n));\n  }\n\n  // Permute block of cols\n  for (int j = block_ind; j > 0; --j) {\n    const auto c = j * block_size;\n    // swap current cols with left cols\n    H.middleCols(c, n).swap(H.middleCols(c - n, n));\n  }\n}\n\nvoid FillLowerTriangular(MatrixXdRef M) {\n  CHECK_EQ(M.rows(), M.cols());\n  M.triangularView<Eigen::Lower>() =\n      M.triangularView<Eigen::Upper>().transpose();\n}\n\nvoid FillUpperTriangular(MatrixXdRef M) {\n  CHECK_EQ(M.rows(), M.cols());\n  M.triangularView<Eigen::Upper>() =\n      M.triangularView<Eigen::Lower>().transpose();\n}\n\nvoid MakeSymmetric(MatrixXdRef M) {\n  CHECK_EQ(M.rows(), M.cols());\n  M += M.transpose().eval();\n  M.array() /= 2.0;\n}\n\nvoid MargTopLeftBlock(const MatrixXdCRef& Hf,\n                      const VectorXdCRef& bf,\n                      MatrixXdRef Hm,\n                      VectorXdRef bm,\n                      int dim) {\n  // Pre-condition\n  // 1. Hf is square and match bsc and symmetric\n  // 2. Hm is quare and match bpr\n  const auto nf = bf.size();\n  const auto nm = bm.size();\n  CHECK_GT(dim, 0);\n  CHECK_EQ(nm + dim, nf);\n  CHECK_EQ(Hf.rows(), nf);\n  CHECK_EQ(Hf.cols(), nf);\n  CHECK_EQ(Hm.rows(), nm);\n  CHECK_EQ(Hm.cols(), nm);\n  CHECK_EQ(Hf, Hf.transpose()) << \"\\n\" << Hf;\n\n  // Hf                     bf\n  // [ H00 H01 ] [ x0 ] = [ b0 ]\n  // [ H10 H11 ] [ x1 ] = [ b1 ]\n  // Hm = H11 - H10 * H00^-1 * H01\n  // bm =  b1 - H10 * H00^-1 * b0\n  const auto H01 = Hf.topRightCorner(dim, nm);\n  const auto H10 = Hf.bottomLeftCorner(nm, dim);\n\n  // Benchmark shows that simply inverse has similar speed as llt\n  // However to account for rank-deficiency we use ldlt to inverse\n  const auto H00_inv = Hf.topLeftCorner(dim, dim)\n                           .selfadjointView<Eigen::Lower>()\n                           .ldlt()\n                           .solve(Eigen::MatrixXd::Identity(dim, dim))\n                           .eval();\n\n  Hm = Hf.bottomRightCorner(nm, nm);\n  Hm.noalias() -= H10 * H00_inv * H01;\n\n  const auto b0 = bf.head(dim);\n  bm = bf.tail(nm);  // b1\n  bm.noalias() -= H10 * (H00_inv * b0);\n\n  // Make sure Hpr is symmetric\n  MakeSymmetric(Hm);\n\n  // Post-condition\n  // 1. Hpr shape doesn't change\n  // 2. Hpr is symmetric\n  CHECK_EQ(Hm.rows(), nm);\n  CHECK_EQ(Hm.cols(), nm);\n  CHECK_EQ(Hm, Hm.transpose()) << \"\\n\" << Hm;\n}\n\n}  // namespace sv\n", "meta": {"hexsha": "1f8425fc30c595100b03e6d18dd4f8fe4e7608d0", "size": 3089, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sv/util/eigen.cpp", "max_stars_repo_name": "versatran01/dsol", "max_stars_repo_head_hexsha": "1c390f10f55fed0d0ef62b0f18e9003bd82c3876", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 52.0, "max_stars_repo_stars_event_min_datetime": "2022-03-17T02:03:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T06:11:52.000Z", "max_issues_repo_path": "sv/util/eigen.cpp", "max_issues_repo_name": "versatran01/dsol", "max_issues_repo_head_hexsha": "1c390f10f55fed0d0ef62b0f18e9003bd82c3876", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sv/util/eigen.cpp", "max_forks_repo_name": "versatran01/dsol", "max_forks_repo_head_hexsha": "1c390f10f55fed0d0ef62b0f18e9003bd82c3876", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2022-03-17T06:13:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T09:15:58.000Z", "avg_line_length": 28.3394495413, "max_line_length": 70, "alphanum_fraction": 0.5681450308, "num_tokens": 918, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.6893056040203135, "lm_q1q2_score": 0.49965714355643764}}
{"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_CONSTANT_TWOTOM10_HPP_INCLUDED\n#define BOOST_SIMD_CONSTANT_TWOTOM10_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n  /*!\n    @ingroup group-constant\n\n    Generate 2 to the power -10 (\\f$2^{-10}\\f$)\n\n\n    @par Header <boost/simd/constant/twotom10.hpp>\n\n    @par Semantic:\n\n    @code\n    T r = Twotom10<T>();\n    @endcode\n\n    is similar to:\n\n    @code\n    T r = pow(2, -10);\n    @endcode\n\n    @return The Twotom10 constant for the proper type\n  **/\n  template<typename T> T Twotom10();\n\n  namespace functional\n  {\n    /*!\n      @ingroup group-callable-constant\n      Generate the  constant twotom10.\n\n      @return The Twotom10 constant for the proper type\n    **/\n    const boost::dispatch::functor<tag::twotom10_> twotom10 = {};\n  }\n} }\n#endif\n\n#include <boost/simd/constant/scalar/twotom10.hpp>\n#include <boost/simd/constant/simd/twotom10.hpp>\n\n#endif\n", "meta": {"hexsha": "2408557dd04d5bf47523a0b5adff3c37c406cbd0", "size": 1293, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/constant/twotom10.hpp", "max_stars_repo_name": "TobiasLudwig/boost.simd", "max_stars_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/simd/constant/twotom10.hpp", "max_issues_repo_name": "TobiasLudwig/boost.simd", "max_issues_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/constant/twotom10.hpp", "max_forks_repo_name": "TobiasLudwig/boost.simd", "max_forks_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-02-16T09:58:18.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:22:43.000Z", "avg_line_length": 22.2931034483, "max_line_length": 100, "alphanum_fraction": 0.5746326373, "num_tokens": 319, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702642896702, "lm_q2_score": 0.6893056104028797, "lm_q1q2_score": 0.49965713998908784}}
{"text": "/*\n * Copyright (c) 2013-2015 Masahide Kashiwagi (kashi@waseda.jp)\n */\n\n#ifndef NEWTON_HPP\n#define NEWTON_HPP\n\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n#include <kv/autodif.hpp>\n#include <limits>\n#include <boost/random.hpp>\n#include <ctime>\n#include <cmath>\n\n\nnamespace kv {\n\nnamespace ub = boost::numeric::ublas;\n\n\ntemplate <class T, class F>\nbool\nnewton(F f, ub::vector<T>& x, T epsilon = std::numeric_limits<T>::epsilon(), int maxloop = 100)\n{\n\tint s = x.size();\n\tint i, j, r;\n\tub::vector<T> fx;\n\tub::matrix<T> fdx;\n\tT norm1, norm2;\n\n\tfor (i=0; i<maxloop; i++) {\n\t\ttry {\n\t\t\tautodif<T>::split(f(autodif<T>::init(x)), fx, fdx);\n\t\t\tub::permutation_matrix<> pm(s);\n\t\t\tr = ub::lu_factorize(fdx, pm);\n\t\t\tif (r != 0) return false;\n\t\t\tub::lu_substitute(fdx, pm, fx);\n\t\t}\n\t\tcatch (...) {\n\t\t\treturn false;\n\t\t}\n\n\t\tnorm1 = 1.;\n\t\tnorm2 = 0.;\n\t\tfor (j=0; j<s; j++) {\n\t\t\tusing std::abs;\n\t\t\tnorm1 = std::max(norm1, abs(x(j)));\n\t\t\tnorm2 = std::max(norm2, abs(fx(j)));\n\t\t}\n\n\t\tx = x - fx;\n\t\tif (norm2 <= norm1 * epsilon) return true;\n\t}\n\treturn false;\n}\n\ntemplate <class T, class F>\nbool\nnewton_random(F f, ub::vector<T>& x, T epsilon = std::numeric_limits<T>::epsilon(), int maxloop = 100)\n{\n\tint s = x.size();\n\tint i;\n\n\tusing namespace boost;\n\t// use \"static\" to be \"randomized\" only once\n\tstatic variate_generator< mt19937, normal_distribution<> > rand (mt19937(time(0)), normal_distribution<>(0., 10.));\n\n\tfor (i=0; i<s; i++) x(i) = rand();\n\treturn newton(f, x, epsilon, maxloop);\n}\n\n} // namespace kv\n\n#endif // NEWTON_HPP\n", "meta": {"hexsha": "42da5ae537c641862baa8a661749c87679be5f92", "size": 1593, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "kv/newton.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/newton.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/newton.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": 20.6883116883, "max_line_length": 116, "alphanum_fraction": 0.630257376, "num_tokens": 533, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743167997235783, "lm_q2_score": 0.6723317123102956, "lm_q1q2_score": 0.49965541211574704}}
{"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_CORE_FUNCTIONS_COMMON_FREQSPACE_HPP_INCLUDED\n#define NT2_CORE_FUNCTIONS_COMMON_FREQSPACE_HPP_INCLUDED\n\n#include <nt2/core/functions/freqspace.hpp>\n#include <nt2/include/functions/freqspace1.hpp>\n#include <nt2/include/functions/colon.hpp>\n#include <nt2/include/functions/tie.hpp>\n#include <nt2/include/functions/scalar/floor.hpp>\n#include <nt2/include/functions/scalar/rec.hpp>\n#include <nt2/include/constants/half.hpp>\n#include <nt2/options.hpp>\n#include <boost/mpl/bool.hpp>\n\nnamespace nt2 { namespace ext\n{\n  //============================================================================\n  // This version of freqspace is called whenever a tie(...) = freqspace(...) is\n  // captured before assign is resolved. As a tieable function, freqspace\n  // retrieves rhs/lhs pair as inputs\n  //============================================================================\n  NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::freqspace_, tag::cpu_\n                              , (A0)(N0)(A1)(N1)\n                              , ((node_ < A0, nt2::tag::freqspace_\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>::type       child0;\n    typedef typename boost::proto::result_of::child_c<A1&,0>::type       child1;\n    typedef typename boost::dispatch::meta::\n            terminal_of< typename boost::dispatch::meta::\n                         semantic_of<child0>::type\n                       >::type                                            in0_t;\n    typedef typename boost::dispatch::meta::\n            terminal_of< typename boost::dispatch::meta::\n                         semantic_of<child1>::type\n                       >::type                                            out_t;\n\n    typedef typename out_t::value_type                                  value_t;\n\n    BOOST_FORCEINLINE result_type operator()( A0& a0, A1& a1 ) const\n    {\n      int n = 0, m = 0;\n      bool whole =  false;\n      bool meshgrid = false;\n      getmn(a0, m, n, whole, meshgrid, N0(), N1() );\n      compute(a1, m, n, whole, meshgrid, N1());\n    }\n\n    private:\n    BOOST_FORCEINLINE void compute( A1 & a1, int m, int, bool whole\n                                  , bool, boost::mpl::long_<1> const&\n                                  ) const\n    {\n      if (whole)\n        boost::proto\n             ::child_c<0>(a1) = freqspace1(m,nt2::whole_,meta::as_<value_t>());\n      else\n        boost::proto::child_c<0>(a1) = freqspace1(m, meta::as_<value_t>());\n    }\n\n    void compute( A1 & a1, int m, int n, bool\n                , bool /*meshgrid*/, boost::mpl::long_<2> const&\n                ) const\n    {\n      value_t hvm = m*nt2::Half<value_t>();\n      value_t hvn = n*nt2::Half<value_t>();\n      value_t hm = nt2::rec(hvm);\n      value_t hn = nt2::rec(hvn);\n      value_t lm = -nt2::floor(hvm)*hm;\n      value_t ln = -nt2::floor(hvn)*hn;\n\n      // TODO: implement support for meshgrid option\n      //if (meshgrid)\n      // {\n      boost::proto::child_c<0>(a1) = nt2::_(ln, hn, value_t(1)-value_t(2)/n);\n      boost::proto::child_c<1>(a1) = nt2::_(lm, hm, value_t(1)-value_t(1)/m);\n      // }\n      // else\n      // {\n      //   boost::proto::child_c<0>(a1) = ??;\n      //   boost::proto::child_c<1>(a1) = ??;\n      // }\n    }\n\n    BOOST_FORCEINLINE  //[f]       = freqspace(n)\n    void getmn(A0 const &a0, int &m,  int& n, bool&, bool&,\n               boost::mpl::long_<3> const &,//number of inputs\n               boost::mpl::long_<1> const &//number of outputs\n               ) const\n    {\n      m = int(boost::proto::value(boost::proto::child_c<1>(a0)));\n      n = 0;\n    }\n\n    BOOST_FORCEINLINE  //[f1, f2]       = freqspace(n)\n    void getmn(A0 const &a0, int &m,  int& n, bool&, bool&\n              , boost::mpl::long_<3> const &    //number of inputs\n              , boost::mpl::long_<2> const &\n              ) const//number of outputs\n    {\n      typedef typename boost::proto::result_of::child_c<A0&,1>::type child1;\n      typedef typename boost::proto::result_of::value<child1>::type  type_t;\n      typedef typename meta::is_scalar<type_t>::type               choice_t;\n      m = getval(boost::proto::value(boost::proto::child_c<1>(a0)),0,choice_t());\n      n = getval(boost::proto::value(boost::proto::child_c<1>(a0)),1,choice_t());\n    }\n\n    template < class T > static int getval(const T & a0, int,\n                                           const boost::mpl::bool_<true> &)\n      { return a0; }\n\n    template < class T > static int getval(const T & a0, int i,\n                                           const boost::mpl::bool_<false>  &)\n      {return a0[i]; }\n\n    BOOST_FORCEINLINE //[f]       = freqspace(n, whole_)\n      void getmn( A0 const &a0, int &m, int& n, bool &whole, bool&\n                , boost::mpl::long_<4> const &  //number of inputs\n                , boost::mpl::long_<1> const &  //number of outputs\n                ) const\n    {\n      m = int(boost::proto::value(boost::proto::child_c<1>(a0)));\n      n = 0;\n      whole =  true;\n    }\n\n    BOOST_FORCEINLINE //[f,g]       = freqspace(n, whole_)\n    void getmn( A0 const &a0, int &m,  int& n, bool &whole, bool&\n              , boost::mpl::long_<4> const &  //number of inputs\n              , boost::mpl::long_<2> const &  //number of outputs\n              ) const\n    {\n      m = int(boost::proto::value(boost::proto::child_c<1>(a0)));\n      n = 0;\n      whole =  true;\n    }\n\n    template < class Dummy >\n    BOOST_FORCEINLINE // [f1, f2]  = freqspace([m, n])\n    void getmn( A0 const &a0, int &m,  int& n, bool&, bool&\n              , boost::mpl::long_<3> const &  //number of inputs\n              , boost::mpl::long_<2> const &  //number of outputs\n              , Dummy()\n              ) const\n    {\n      typedef typename boost::proto::result_of::child_c<A0&,1>::type child1;\n      typedef typename boost::proto::result_of::value<child1>::type  type_t;\n      typedef typename meta::is_scalar<type_t>::type               choice_t;\n      m = getval(boost::proto::value(boost::proto::child_c<1>(a0)),0,choice_t());\n      n = getval(boost::proto::value(boost::proto::child_c<1>(a0)),1,choice_t());\n    }\n\n    template < class Dummy >\n    BOOST_FORCEINLINE // [f1, f2]  = freqspace([m, n], meshgrid_)\n    void getmn( A0 const &a0, int &m,  int& n, bool&, bool& meshgrid\n              , boost::mpl::long_<4> const &  //number of inputs\n              , boost::mpl::long_<2> const &  //number of outputs\n              , Dummy()\n              ) const\n    {\n      typedef typename boost::proto::result_of::child_c<A0&,1>::type child1;\n      typedef typename boost::proto::result_of::value<child1>::type  type_t;\n      typedef typename meta::is_scalar<type_t>::type               choice_t;\n      m = getval(boost::proto::value(boost::proto::child_c<1>(a0)),0,choice_t());\n      n = getval(boost::proto::value(boost::proto::child_c<1>(a0)),1,choice_t());\n      meshgrid = true;\n    }\n  };\n} }\n\n#endif\n", "meta": {"hexsha": "f66589a7e2df3824965e496c97137459586557d2", "size": 7841, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/generative/include/nt2/core/functions/common/freqspace.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/generative/include/nt2/core/functions/common/freqspace.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/generative/include/nt2/core/functions/common/freqspace.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": 41.9304812834, "max_line_length": 81, "alphanum_fraction": 0.5035072057, "num_tokens": 2041, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743167997235783, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.49965540723647395}}
{"text": "#include <boost/test/unit_test.hpp>\n\n#include <askr/utility/crc.h>\n#include <string_view>\n\nconstexpr uint32_t crc32(std::string_view str)\n{\n    askr::crc<32> crc;\n    crc.update(str);\n    return crc.checksum();\n}\n\nBOOST_AUTO_TEST_SUITE(CRC)\n\nBOOST_AUTO_TEST_CASE(CompileTimeTest)\n{\n    static_assert(crc32(\"123456789\") == 0xCBF43926);\n}\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "69dadbf663faf925e4b5cdac0cca87a1882ef986", "size": 365, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "askr/utility/test/crc_unittest.cpp", "max_stars_repo_name": "blackkaiserxjc/askr", "max_stars_repo_head_hexsha": "dd1196b60305f20abeeef4d96de6f0dab13b738e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "askr/utility/test/crc_unittest.cpp", "max_issues_repo_name": "blackkaiserxjc/askr", "max_issues_repo_head_hexsha": "dd1196b60305f20abeeef4d96de6f0dab13b738e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "askr/utility/test/crc_unittest.cpp", "max_forks_repo_name": "blackkaiserxjc/askr", "max_forks_repo_head_hexsha": "dd1196b60305f20abeeef4d96de6f0dab13b738e", "max_forks_repo_licenses": ["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.25, "max_line_length": 52, "alphanum_fraction": 0.7369863014, "num_tokens": 100, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.6723316926137811, "lm_q1q2_score": 0.4996554051268425}}
{"text": "#include \"include_and_types.cpp\"\n#include <set>\n#include \"my_transitive_closure.cpp\"\n#include <boost/graph/graphml.hpp>\n#include <boost/property_map/dynamic_property_map.hpp>\n#include <boost/graph/transitive_closure.hpp>\n\n//Ad-hoc typedef interator_property_map types\ntypedef boost::iterator_property_map<__gnu_cxx::__normal_iterator<long unsigned int*, std::vector<long unsigned int> >,\n        boost::vec_adj_list_vertex_id_map<boost::no_property, long unsigned int>,\n                long unsigned int, long unsigned int&> typeVertex;\n\ntypedef boost::iterator_property_map<__gnu_cxx::__normal_iterator<std::set<long unsigned int>**,\n        std::vector<std::set<long unsigned int>*> >,\n        boost::vec_adj_list_vertex_id_map<boost::no_property, long unsigned int>, std::set<long unsigned int>*,\n                std::set<long unsigned int>*&> typeSetVertex;\n\nusing namespace std;\n\n\nint main(int, char*[]){\n\n    //Reading graph from stdin\n    Graph g;\n    dynamic_properties dp;\n    read_graphml(std::cin, g, dp);\n\n    //Graph printing\n    std::cout << \"A directed graph:\" << std::endl;\n    print_graph(g, get(vertex_index, g));\n    std::cout << std::endl;\n\n    //Declaration of TransitiveClosure object\n    TransitiveClosure <typeVertex, typeBool, typeInt, typeSetVertex> transitive_cl(&g);\n    transitive_cl.transitive_closure_scc();\n\n    //used only to compare results. This applies the built-in function of Boost for applying transitive closure\n    std::cout << \"BGL\"<<std::endl;\n    Graph gt;\n    transitive_closure(g,gt);\n    print_graph(gt, get(vertex_index,gt));\n\n    return 0;\n}", "meta": {"hexsha": "3369cba32c555b984f447b45d4e5e8b7c605582e", "size": 1590, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main_transitive_closure.cpp", "max_stars_repo_name": "phisco/advance_algorithms_project", "max_stars_repo_head_hexsha": "2961959cf6036ed4c85d479dd14389315df55ee1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-07-04T13:46:31.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-28T16:42:31.000Z", "max_issues_repo_path": "main_transitive_closure.cpp", "max_issues_repo_name": "phisco/advance_algorithms_project", "max_issues_repo_head_hexsha": "2961959cf6036ed4c85d479dd14389315df55ee1", "max_issues_repo_licenses": ["MIT"], "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_transitive_closure.cpp", "max_forks_repo_name": "phisco/advance_algorithms_project", "max_forks_repo_head_hexsha": "2961959cf6036ed4c85d479dd14389315df55ee1", "max_forks_repo_licenses": ["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.1363636364, "max_line_length": 119, "alphanum_fraction": 0.7157232704, "num_tokens": 381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.6723316860482762, "lm_q1q2_score": 0.49965540024756927}}
{"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_IS_NOT_INFINITE_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_IS_NOT_INFINITE_HPP_INCLUDED\n#include <boost/simd/detail/overload.hpp>\n\n#include <boost/simd/meta/hierarchy/simd.hpp>\n#include <boost/simd/meta/as_logical.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/true.hpp>\n#include <boost/simd/function/abs.hpp>\n#include <boost/simd/function/is_not_equal.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n   namespace bd = boost::dispatch;\n   namespace bs = boost::simd;\n   BOOST_DISPATCH_OVERLOAD_IF(is_not_infinite_\n                          , (typename A0, typename X)\n                          , (detail::is_native<X>)\n                          , bd::cpu_\n                          , bs::pack_<bd::integer_<A0>, X>\n                          )\n   {\n     using result = bs::as_logical_t<A0>;\n     BOOST_FORCEINLINE result operator()(const A0&) const BOOST_NOEXCEPT\n     {\n       return bs::True<result>();\n     }\n   };\n\n   BOOST_DISPATCH_OVERLOAD_IF(is_not_infinite_\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 bs::as_logical_t<A0> operator()( const A0& a0) const BOOST_NOEXCEPT\n      {\n        return is_not_equal(bs::abs(a0),bs::Inf<A0>());\n      }\n   };\n\n} } }\n#endif\n\n", "meta": {"hexsha": "4daeeedac0bed5ceebb7206548036aee9890c29b", "size": 1912, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/simd/function/is_not_infinite.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/is_not_infinite.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/is_not_infinite.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 33.5438596491, "max_line_length": 100, "alphanum_fraction": 0.5439330544, "num_tokens": 410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743167997235783, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.49965539747792787}}
{"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\u2019s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n#pragma once\n\n#include \"../util/ButterworthHPFilter.hpp\"\n#include \"../util/FluidEigenMappings.hpp\"\n#include \"../util/SlideUDFilter.hpp\"\n#include \"../../data/FluidIndex.hpp\"\n#include \"../../data/TensorTypes.hpp\"\n#include <Eigen/Core>\n#include <cmath>\n\nnamespace fluid {\nnamespace algorithm {\n\nclass EnvelopeGate\n{\n\n  using ArrayXd = Eigen::ArrayXd;\n\npublic:\n  EnvelopeGate(index maxSize)\n  {\n    mInputStorage = ArrayXd(maxSize);\n    mOutputStorage = ArrayXd(maxSize);\n  }\n\n  void init(double onThreshold, double offThreshold, double hiPassFreq,\n            index minTimeAboveThreshold, index upwardLookupTime,\n            index minTimeBelowThreshold, index downwardLookupTime)\n  {\n    using namespace std;\n\n    mMinTimeAboveThreshold = minTimeAboveThreshold;\n    mUpwardLookupTime = upwardLookupTime;\n    mMinTimeBelowThreshold = minTimeBelowThreshold,\n    mDownwardLookupTime = downwardLookupTime;\n    mDownwardLatency = max<index>(minTimeBelowThreshold, mDownwardLookupTime);\n    mLatency = max<index>(mMinTimeAboveThreshold + mUpwardLookupTime,\n                          mDownwardLatency);\n    if (mLatency < 0) mLatency = 1;\n    mHiPassFreq = hiPassFreq;\n    initFilters(mHiPassFreq);\n    double initVal = min(onThreshold, offThreshold) - 1;\n    initBuffers(initVal);\n    mSlide.init(initVal);\n    mInputState = false;\n    mOutputState = false;\n    mOnStateCount = 0;\n    mOffStateCount = 0;\n    mEventCount = 0;\n    mSilenceCount = 0;\n    mInitialized = true;\n  }\n\n  double processSample(const double in, double onThreshold, double offThreshold,\n                       index rampUpTime, index rampDownTime, double hiPassFreq,\n                       index minEventDuration, index minSilenceDuration)\n  {\n    using namespace std;\n    assert(mInitialized);\n\n    mSlide.updateCoeffs(rampUpTime, rampDownTime);\n\n    double filtered = in;\n    if (hiPassFreq != mHiPassFreq)\n    {\n      initFilters(hiPassFreq);\n      mHiPassFreq = hiPassFreq;\n    }\n    if (mHiPassFreq > 0)\n      filtered = mHiPass2.processSample(mHiPass1.processSample(in));\n\n    double rectified = abs(filtered);\n    double dB = 20 * log10(rectified);\n    double floor = min(offThreshold, onThreshold) - 1;\n    double clipped = max(dB, floor);\n    double smoothed = mSlide.processSample(clipped);\n    bool   forcedState = false;\n\n    // case 1: we are waiting for event to finish\n    if (mOutputState && mEventCount > 0)\n    {\n      if (mEventCount >= minEventDuration) { mEventCount = 0; }\n      else\n      {\n        forcedState = true;\n        mOutputBuffer(mLatency - 1) = 1;\n        mEventCount++;\n      }\n      // case 2: we are waiting for silence to finish\n    }\n    else if (!mOutputState && mSilenceCount > 0)\n    {\n      if (mSilenceCount >= minSilenceDuration) { mSilenceCount = 0; }\n      else\n      {\n        forcedState = true;\n        mOutputBuffer(mLatency - 1) = 0;\n        mSilenceCount++;\n      }\n    }\n    // case 3: need to compute state\n    if (!forcedState)\n    {\n      bool nextState = mInputState;\n      if (!mInputState && smoothed >= onThreshold) { nextState = true; }\n      if (mInputState && smoothed <= offThreshold) { nextState = false; }\n      updateCounters(nextState);\n      // establish and refine\n      if (!mOutputState && mOnStateCount >= mMinTimeAboveThreshold &&\n          mFillCount >= mLatency)\n      {\n        index onsetIndex =\n            refineStart(mLatency - mMinTimeAboveThreshold - mUpwardLookupTime,\n                        mUpwardLookupTime);\n        mOutputBuffer.segment(onsetIndex, mLatency - onsetIndex) = 1;\n        mEventCount = mOnStateCount;\n        mOutputState = true; // we are officially on\n      }\n      else if (mOutputState && mOffStateCount >= mDownwardLatency &&\n               mFillCount >= mLatency)\n      {\n\n        index offsetIndex =\n            refineStart(mLatency - mDownwardLatency, mDownwardLookupTime);\n        mOutputBuffer.segment(offsetIndex, mLatency - offsetIndex) = 0;\n        mSilenceCount = mOffStateCount;\n        mOutputState = false; // we are officially off\n      }\n\n      mOutputBuffer(mLatency - 1) = mOutputState ? 1 : 0;\n      mInputState = nextState;\n    }\n    if (mLatency > 1)\n    {\n      mOutputBuffer.segment(0, mLatency - 1) =\n          mOutputBuffer.segment(1, mLatency - 1);\n\n      mInputBuffer.segment(0, mLatency - 1) =\n          mInputBuffer.segment(1, mLatency - 1);\n    }\n    mInputBuffer(mLatency - 1) = smoothed;\n    if (mFillCount < mLatency) mFillCount++;\n    return mOutputBuffer(0);\n  }\n\n  index getLatency() { return mLatency; }\n  bool  initialized() { return mInitialized; }\n\n\nprivate:\n  void initBuffers(double initialValue)\n  {\n    using namespace std;\n    mInputBuffer = mInputStorage.segment(0, max<index>(mLatency, 1))\n                       .setConstant(initialValue);\n    mOutputBuffer =\n        mOutputStorage.segment(0, max<index>(mLatency, 1)).setZero();\n    mInputState = false;\n    mOutputState = false;\n    mFillCount = max<index>(mLatency, 1);\n  }\n\n  void initFilters(double cutoff)\n  {\n    mHiPass1.init(cutoff);\n    mHiPass2.init(cutoff);\n  }\n\n  index refineStart(index start, index nSamples)\n  {\n    if (nSamples < 2) return start + nSamples;\n    ArrayXd        seg = mInputBuffer.segment(start, nSamples);\n    ArrayXd::Index index;\n    seg.minCoeff(&index);\n    return start + index;\n  }\n\n  void updateCounters(bool nextState)\n  {\n    if (!mInputState && nextState)\n    {\n      mOffStateCount = 0;\n      mOnStateCount = 1;\n    }\n    else if (mInputState && !nextState)\n    {\n      mOnStateCount = 0;\n      mOffStateCount = 1;\n    }\n    else if (mInputState && nextState)\n    {\n      mOnStateCount++;\n    }\n    else if (!mInputState && !nextState)\n    {\n      mOffStateCount++;\n    }\n  }\n\n  index  mLatency;\n  index  mFillCount;\n  double mHiPassFreq{0};\n\n  index mMinTimeAboveThreshold{440};\n  index mDownwardLookupTime{10};\n  index mDownwardLatency;\n  index mMinTimeBelowThreshold{10};\n  index mUpwardLookupTime{24};\n\n  ArrayXd mInputBuffer;\n  ArrayXd mOutputBuffer;\n  ArrayXd mInputStorage;\n  ArrayXd mOutputStorage;\n\n  bool mInputState{false};\n  bool mOutputState{false};\n\n  index mOnStateCount{0};\n  index mOffStateCount{0};\n  index mEventCount{0};\n  index mSilenceCount{0};\n  bool  mInitialized{false};\n\n  ButterworthHPFilter mHiPass1;\n  ButterworthHPFilter mHiPass2;\n  SlideUDFilter       mSlide;\n};\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "3259a0421270b92a151d4979b05d6f4101c4e4da", "size": 6763, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/public/EnvelopeGate.hpp", "max_stars_repo_name": "elgiano/flucoma-core", "max_stars_repo_head_hexsha": "d34a04e7a68f24eaf09b24df57020d45664061fc", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/algorithms/public/EnvelopeGate.hpp", "max_issues_repo_name": "elgiano/flucoma-core", "max_issues_repo_head_hexsha": "d34a04e7a68f24eaf09b24df57020d45664061fc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-03-15T10:39:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-15T13:19:22.000Z", "max_forks_repo_path": "include/algorithms/public/EnvelopeGate.hpp", "max_forks_repo_name": "elgiano/flucoma-core", "max_forks_repo_head_hexsha": "d34a04e7a68f24eaf09b24df57020d45664061fc", "max_forks_repo_licenses": ["BSD-3-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.1791666667, "max_line_length": 80, "alphanum_fraction": 0.6596185125, "num_tokens": 1809, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4996253373409008}}
{"text": "// Copyright 2019, Collabora, Ltd.\n// SPDX-License-Identifier: BSL-1.0\n/*!\n * @file\n * @brief  C++ sensor fusion/filtering code that uses flexkalman\n * @author Ryan Pavlik <ryan.pavlik@collabora.com>\n * @ingroup aux_tracking\n */\n\n#pragma once\n\n#ifndef __cplusplus\n#error \"This header is C++-only.\"\n#endif\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include \"flexkalman/AugmentedProcessModel.h\"\n#include \"flexkalman/AugmentedState.h\"\n#include \"flexkalman/BaseTypes.h\"\n#include \"flexkalman/PoseState.h\"\n\n\nnamespace xrt::auxiliary::tracking {\n\nnamespace types = flexkalman::types;\nusing flexkalman::types::Vector;\n\n//! For things like accelerometers, which on some level measure the local vector\n//! of a world direction.\ntemplate <typename State>\nclass WorldDirectionMeasurement : public flexkalman::MeasurementBase<WorldDirectionMeasurement<State>>\n{\npublic:\n\tEIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\tstatic constexpr size_t Dimension = 3;\n\tusing MeasurementVector = types::Vector<Dimension>;\n\tusing MeasurementSquareMatrix = types::SquareMatrix<Dimension>;\n\tWorldDirectionMeasurement(types::Vector<3> const &direction,\n\t                          types::Vector<3> const &reference,\n\t                          types::Vector<3> const &variance)\n\t    : direction_(direction.normalized()), reference_(reference.normalized()), covariance_(variance.asDiagonal())\n\t{}\n\n\tMeasurementSquareMatrix const &\n\tgetCovariance(State const & /*s*/)\n\t{\n\t\treturn covariance_;\n\t}\n\n\ttypes::Vector<3>\n\tpredictMeasurement(State const &s) const\n\t{\n\t\treturn s.getCombinedQuaternion() * reference_;\n\t}\n\n\tMeasurementVector\n\tgetResidual(MeasurementVector const &predictedMeasurement, State const &s) const\n\t{\n\t\treturn predictedMeasurement - reference_;\n\t}\n\n\tMeasurementVector\n\tgetResidual(State const &s) const\n\t{\n\t\treturn getResidual(predictMeasurement(s), s);\n\t}\n\nprivate:\n\ttypes::Vector<3> direction_;\n\ttypes::Vector<3> reference_;\n\tMeasurementSquareMatrix covariance_;\n};\n#if 0\n//! For things like accelerometers, which on some level measure the local vector\n//! of a world direction.\nclass LinAccelWithGravityMeasurement\n    : public flexkalman::MeasurementBase<LinAccelWithGravityMeasurement>\n{\npublic:\n\tEIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\tstatic constexpr size_t Dimension = 3;\n\tusing MeasurementVector = types::Vector<Dimension>;\n\tusing MeasurementSquareMatrix = types::SquareMatrix<Dimension>;\n\tLinAccelWithGravityMeasurement(types::Vector<3> const &direction,\n\t                          types::Vector<3> const &reference,\n\t                          types::Vector<3> const &variance)\n\t    : direction_(direction), reference_(reference),\n\t      covariance_(variance.asDiagonal())\n\t{}\n\n\t// template <typename State>\n\tMeasurementSquareMatrix const &\n\tgetCovariance(State const & /*s*/)\n\t{\n\t\treturn covariance_;\n\t}\n\n\t// template <typename State>\n\ttypes::Vector<3>\n\tpredictMeasurement(State const &s) const\n\t{\n\t\treturn reference_;\n\t}\n\n\t// template <typename State>\n\tMeasurementVector\n\tgetResidual(MeasurementVector const &predictedMeasurement,\n\t            State const &s) const\n\t{\n\t\ts.getQuaternion().conjugate() *\n\t\t        predictedMeasurement return predictedMeasurement -\n\t\t    reference_.normalized();\n\t}\n\n\ttemplate <typename State>\n\tMeasurementVector\n\tgetResidual(State const &s) const\n\t{\n\t\tMeasurementVector residual =\n\t\t    direction_ - reference_ * s.getQuaternion();\n\t\treturn getResidual(predictMeasurement(s), s);\n\t}\n\nprivate:\n\ttypes::Vector<3> direction_;\n\ttypes::Vector<3> reference_;\n\tMeasurementSquareMatrix covariance_;\n};\n#endif\n\nclass BiasedGyroMeasurement : public flexkalman::MeasurementBase<BiasedGyroMeasurement>\n{\npublic:\n\tEIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\tstatic constexpr size_t Dimension = 3;\n\tusing MeasurementVector = types::Vector<Dimension>;\n\tusing MeasurementSquareMatrix = types::SquareMatrix<Dimension>;\n\tBiasedGyroMeasurement(types::Vector<3> const &angVel, types::Vector<3> const &variance)\n\t    : angVel_(angVel), covariance_(variance.asDiagonal())\n\t{}\n\n\ttemplate <typename State>\n\tMeasurementSquareMatrix const &\n\tgetCovariance(State const & /*s*/)\n\t{\n\t\treturn covariance_;\n\t}\n\n\ttemplate <typename State>\n\ttypes::Vector<3>\n\tpredictMeasurement(State const &s) const\n\t{\n\t\treturn s.b().stateVector() + angVel_;\n\t}\n\n\ttemplate <typename State>\n\tMeasurementVector\n\tgetResidual(MeasurementVector const &predictedMeasurement, State const &s) const\n\t{\n\t\treturn predictedMeasurement - s.a().angularVelocity();\n\t}\n\n\ttemplate <typename State>\n\tMeasurementVector\n\tgetResidual(State const &s) const\n\t{\n\t\treturn getResidual(predictMeasurement(s), s);\n\t}\n\nprivate:\n\ttypes::Vector<3> angVel_;\n\tMeasurementSquareMatrix covariance_;\n};\n/*!\n * For PS Move-like things, where there's a directly-computed absolute position\n * that is not at the tracked body's origin.\n */\nclass AbsolutePositionLeverArmMeasurement : public flexkalman::MeasurementBase<AbsolutePositionLeverArmMeasurement>\n{\npublic:\n\tEIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\tusing State = flexkalman::pose_externalized_rotation::State;\n\tstatic constexpr size_t Dimension = 3;\n\tusing MeasurementVector = types::Vector<Dimension>;\n\tusing MeasurementSquareMatrix = types::SquareMatrix<Dimension>;\n\n\t/*!\n\t * @todo the point we get from the camera isn't the center of the ball,\n\t * but the center of the visible surface of the ball - a closer\n\t * approximation would be translation along the vector to the center of\n\t * projection....\n\t */\n\tAbsolutePositionLeverArmMeasurement(MeasurementVector const &measurement,\n\t                                    MeasurementVector const &knownLocationInBodySpace,\n\t                                    MeasurementVector const &variance)\n\t    : measurement_(measurement), knownLocationInBodySpace_(knownLocationInBodySpace),\n\t      covariance_(variance.asDiagonal())\n\t{}\n\n\tMeasurementSquareMatrix const &\n\tgetCovariance(State const & /*s*/)\n\t{\n\t\treturn covariance_;\n\t}\n\n\ttypes::Vector<3>\n\tpredictMeasurement(State const &s) const\n\t{\n\t\treturn s.getIsometry() * knownLocationInBodySpace_;\n\t}\n\n\tMeasurementVector\n\tgetResidual(MeasurementVector const &predictedMeasurement, State const & /*s*/) const\n\t{\n\t\treturn measurement_ - predictedMeasurement;\n\t}\n\n\tMeasurementVector\n\tgetResidual(State const &s) const\n\t{\n\t\treturn getResidual(predictMeasurement(s), s);\n\t}\n\nprivate:\n\tMeasurementVector measurement_;\n\tMeasurementVector knownLocationInBodySpace_;\n\tMeasurementSquareMatrix covariance_;\n};\n\n} // namespace xrt::auxiliary::tracking\n", "meta": {"hexsha": "ffb9c9e0f1d8ad7de045fccc762950fb92aa1689", "size": 6403, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/xrt/auxiliary/tracking/t_fusion.hpp", "max_stars_repo_name": "leviathanch/monado", "max_stars_repo_head_hexsha": "36a540a764fd5529018dfceb28e10804db9596bf", "max_stars_repo_licenses": ["Unlicense", "Apache-2.0", "BSD-2-Clause", "MIT", "BSL-1.0", "BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-11-08T05:17:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T12:50:59.000Z", "max_issues_repo_path": "src/xrt/auxiliary/tracking/t_fusion.hpp", "max_issues_repo_name": "SimulaVR/monado", "max_issues_repo_head_hexsha": "b5d46eebf5f9b7f96a52639484a1b35d8ab3cd21", "max_issues_repo_licenses": ["Unlicense", "Apache-2.0", "BSD-2-Clause", "MIT", "BSL-1.0", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/xrt/auxiliary/tracking/t_fusion.hpp", "max_forks_repo_name": "SimulaVR/monado", "max_forks_repo_head_hexsha": "b5d46eebf5f9b7f96a52639484a1b35d8ab3cd21", "max_forks_repo_licenses": ["Unlicense", "Apache-2.0", "BSD-2-Clause", "MIT", "BSL-1.0", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4806866953, "max_line_length": 115, "alphanum_fraction": 0.7441824145, "num_tokens": 1468, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.85391273808085, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.49962532863994674}}
{"text": "#include <boost/math/special_functions/ellint_rg.hpp>\n", "meta": {"hexsha": "fc837f579029a6736ec1992e7691f5d034d70fc8", "size": 54, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_special_functions_ellint_rg.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_special_functions_ellint_rg.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_special_functions_ellint_rg.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 27.0, "max_line_length": 53, "alphanum_fraction": 0.8333333333, "num_tokens": 13, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891479496521, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4996140638452899}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2006, 2007, 2015 Ferdinando Ametrano\n Copyright (C) 2006 Cristina Duminuco\n Copyright (C) 2007 Giorgio Facchinetti\n Copyright (C) 2015 Paolo Mazzocchi\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n#ifndef quantlib_abcdcalibration_hpp\n#define quantlib_abcdcalibration_hpp\n\n\n#include <ql/math/optimization/endcriteria.hpp>\n#include <ql/math/optimization/projectedcostfunction.hpp>\n#include <ql/math/array.hpp>\n\n#include <boost/shared_ptr.hpp>\n\n#include <vector>\n\n\nnamespace QuantLib {\n    \n    class Quote;\n    class OptimizationMethod;\n    class ParametersTransformation;\n\n    class AbcdCalibration {\n      private:\n        class AbcdError : public CostFunction {\n          public:\n            AbcdError(AbcdCalibration* abcd) : abcd_(abcd) {}\n\n            Real value(const Array& x) const {\n                const Array y = abcd_->transformation_->direct(x);\n                abcd_->a_ = y[0];\n                abcd_->b_ = y[1];\n                abcd_->c_ = y[2];\n                abcd_->d_ = y[3];\n                return abcd_->error();\n            }\n            Disposable<Array> values(const Array& x) const {\n                const Array y = abcd_->transformation_->direct(x);\n                abcd_->a_ = y[0];\n                abcd_->b_ = y[1];\n                abcd_->c_ = y[2];\n                abcd_->d_ = y[3];\n                return abcd_->errors();\n            }\n          private:\n            AbcdCalibration* abcd_;\n        };\n\n        class AbcdParametersTransformation : public ParametersTransformation {\n          public:\n            AbcdParametersTransformation() : y_(Array(4)) {}\n            // to constrained <- from unconstrained\n            Array direct(const Array& x) const;\n            // to unconstrained <- from constrained\n            Array inverse(const Array& x) const;\n          private:\n            mutable Array y_;\n        };\n\n      public:\n        AbcdCalibration() {};\n        AbcdCalibration(\n             const std::vector<Real>& t,\n             const std::vector<Real>& blackVols,\n             Real aGuess = -0.06,\n             Real bGuess =  0.17,\n             Real cGuess =  0.54,\n             Real dGuess =  0.17,\n             bool aIsFixed = false,\n             bool bIsFixed = false,\n             bool cIsFixed = false,\n             bool dIsFixed = false,\n             bool vegaWeighted = false,\n             const boost::shared_ptr<EndCriteria>& endCriteria\n                      = boost::shared_ptr<EndCriteria>(),\n             const boost::shared_ptr<OptimizationMethod>& method\n                      = boost::shared_ptr<OptimizationMethod>());\n        //! adjustment factors needed to match Black vols\n        std::vector<Real> k(const std::vector<Real>& t,\n                            const std::vector<Real>& blackVols) const;\n        void compute();\n        //calibration results\n        Real value(Real x) const;\n        Real error() const;\n        Real maxError() const;\n        Disposable<Array> errors() const;\n        EndCriteria::Type endCriteria() const;\n        Real a() const { return a_; }\n        Real b() const { return b_; }\n        Real c() const { return c_; }\n        Real d() const { return d_; }\n        bool aIsFixed_, bIsFixed_, cIsFixed_, dIsFixed_;\n        Real a_, b_, c_, d_;\n        boost::shared_ptr<ParametersTransformation> transformation_;\n      private:\n        // optimization method used for fitting\n        mutable EndCriteria::Type abcdEndCriteria_;\n        boost::shared_ptr<EndCriteria> endCriteria_;\n        boost::shared_ptr<OptimizationMethod> optMethod_;\n        mutable std::vector<Real> weights_;\n        bool vegaWeighted_;\n        //! Parameters\n        std::vector<Real> times_, blackVols_;\n    };\n\n}\n\n/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2006, 2015 Ferdinando Ametrano\n Copyright (C) 2006 Cristina Duminuco\n Copyright (C) 2005, 2006 Klaus Spanderen\n Copyright (C) 2007 Giorgio Facchinetti\n Copyright (C) 2015 Paolo Mazzocchi\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n#include <ql/math/optimization/method.hpp>\n#include <ql/math/optimization/constraint.hpp>\n#include <ql/math/optimization/levenbergmarquardt.hpp>\n#include <ql/pricingengines/blackformula.hpp>\n#include <ql/termstructures/volatility/abcd.hpp>\n#include <ql/math/distributions/normaldistribution.hpp>\n#include <ql/math/interpolations/abcdinterpolation.hpp>\n\nnamespace QuantLib {\n\n    // to constrained <- from unconstrained\n    inline Array AbcdCalibration::AbcdParametersTransformation::direct(const Array& x) const {\n        y_[1] = x[1];\n        y_[2] = std::exp(x[2]);\n        y_[3] = std::exp(x[3]);\n        y_[0] = std::exp(x[0]) - y_[3];\n        return y_;\n    }\n\n    // to unconstrained <- from constrained\n    inline Array AbcdCalibration::AbcdParametersTransformation::inverse(const Array& x) const {\n        y_[1] = x[1];\n        y_[2] = std::log(x[2]);\n        y_[3] = std::log(x[3]);\n        y_[0] = std::log(x[0] + x[3]);\n        return y_;\n    }\n\n    // to constrained <- from unconstrained\n\n    inline AbcdCalibration::AbcdCalibration(\n               const std::vector<Real>& t,\n               const std::vector<Real>& blackVols,\n               Real a, Real b, Real c, Real d,\n               bool aIsFixed, bool bIsFixed, bool cIsFixed, bool dIsFixed,\n               bool vegaWeighted,\n               const boost::shared_ptr<EndCriteria>& endCriteria,\n               const boost::shared_ptr<OptimizationMethod>& optMethod)\n    : aIsFixed_(aIsFixed), bIsFixed_(bIsFixed),\n      cIsFixed_(cIsFixed), dIsFixed_(dIsFixed),\n      a_(a), b_(b), c_(c), d_(d),\n      abcdEndCriteria_(EndCriteria::None), endCriteria_(endCriteria),\n      optMethod_(optMethod), weights_(blackVols.size(), 1.0/blackVols.size()),\n      vegaWeighted_(vegaWeighted),\n      times_(t), blackVols_(blackVols) {\n\n        AbcdMathFunction::validate(a, b, c, d);\n\n        QL_REQUIRE(blackVols.size()==t.size(),\n                       \"mismatch between number of times (\" << t.size() <<\n                       \") and blackVols (\" << blackVols.size() << \")\");\n\n        // if no optimization method or endCriteria is provided, we provide one\n        if (!optMethod_) {\n            Real epsfcn = 1.0e-8;\n            Real xtol = 1.0e-8;\n            Real gtol = 1.0e-8;\n            bool useCostFunctionsJacobian = false;\n            optMethod_ = boost::shared_ptr<OptimizationMethod>(new\n                LevenbergMarquardt(epsfcn, xtol, gtol, useCostFunctionsJacobian));\n        }\n        if (!endCriteria_) {\n            Size maxIterations = 10000;\n            Size maxStationaryStateIterations = 1000;\n            Real rootEpsilon = 1.0e-8;\n            Real functionEpsilon = 0.3e-4;     // Why 0.3e-4 ?\n            Real gradientNormEpsilon = 0.3e-4; // Why 0.3e-4 ?\n            endCriteria_ = boost::shared_ptr<EndCriteria>(new\n                EndCriteria(maxIterations, maxStationaryStateIterations,\n                            rootEpsilon, functionEpsilon, gradientNormEpsilon));\n        }\n    }\n\n    inline void AbcdCalibration::compute() {\n        if (vegaWeighted_) {\n            Real weightsSum = 0.0;\n            for (Size i=0; i<times_.size() ; i++) {\n                Real stdDev = std::sqrt(blackVols_[i]* blackVols_[i]* times_[i]);\n                // when strike==forward, the blackFormulaStdDevDerivative becomes\n                weights_[i] = CumulativeNormalDistribution().derivative(.5*stdDev);\n                weightsSum += weights_[i];\n            }\n            // weight normalization\n            for (Size i=0; i<times_.size() ; i++) {\n                weights_[i] /= weightsSum;\n            }\n        }\n\n        // there is nothing to optimize\n        if (aIsFixed_ && bIsFixed_ && cIsFixed_ && dIsFixed_) {\n            abcdEndCriteria_ = EndCriteria::None;\n            //error_ = interpolationError();\n            //maxError_ = interpolationMaxError();\n            return;\n        } else {\n\n            AbcdError costFunction(this);\n            transformation_ = boost::shared_ptr<ParametersTransformation>(new\n                AbcdParametersTransformation);\n\n            Array guess(4);\n            guess[0] = a_;\n            guess[1] = b_;\n            guess[2] = c_;\n            guess[3] = d_;\n\n            std::vector<bool> parameterAreFixed(4);\n            parameterAreFixed[0] = aIsFixed_;\n            parameterAreFixed[1] = bIsFixed_;\n            parameterAreFixed[2] = cIsFixed_;\n            parameterAreFixed[3] = dIsFixed_;\n\n            Array inversedTransformatedGuess(transformation_->inverse(guess));\n\n            ProjectedCostFunction projectedAbcdCostFunction(costFunction,\n                            inversedTransformatedGuess, parameterAreFixed);\n\n            Array projectedGuess\n                (projectedAbcdCostFunction.project(inversedTransformatedGuess));\n\n            NoConstraint constraint;\n            Problem problem(projectedAbcdCostFunction, constraint, projectedGuess);\n            abcdEndCriteria_ = optMethod_->minimize(problem, *endCriteria_);\n            Array projectedResult(problem.currentValue());\n            Array transfResult(projectedAbcdCostFunction.include(projectedResult));\n\n            Array result = transformation_->direct(transfResult);\n            AbcdMathFunction::validate(a_, b_, c_, d_);\n            a_ = result[0];\n            b_ = result[1];\n            c_ = result[2];\n            d_ = result[3];\n\n        }\n    }\n\n    inline Real AbcdCalibration::value(Real x) const {\n        return abcdBlackVolatility(x,a_,b_,c_,d_);\n    }\n\n    inline std::vector<Real> AbcdCalibration::k(const std::vector<Real>& t,\n                                         const std::vector<Real>& blackVols) const {\n        QL_REQUIRE(blackVols.size()==t.size(),\n               \"mismatch between number of times (\" << t.size() <<\n               \") and blackVols (\" << blackVols.size() << \")\");\n        std::vector<Real> k(t.size());\n        for (Size i=0; i<t.size() ; i++) {\n            k[i]=blackVols[i]/value(t[i]);\n        }\n        return k;\n    }\n\n    inline Real AbcdCalibration::error() const {\n        Size n = times_.size();\n        Real error, squaredError = 0.0;\n        for (Size i=0; i<times_.size() ; i++) {\n            error = (value(times_[i]) - blackVols_[i]);\n            squaredError += error * error * weights_[i];\n        }\n        return std::sqrt(n*squaredError/(n-1));\n    }\n\n    inline Real AbcdCalibration::maxError() const {\n        Real error, maxError = QL_MIN_REAL;\n        for (Size i=0; i<times_.size() ; i++) {\n            error = std::fabs(value(times_[i]) - blackVols_[i]);\n            maxError = std::max(maxError, error);\n        }\n        return maxError;\n    }\n\n    // calculate weighted differences\n    inline Disposable<Array> AbcdCalibration::errors() const {\n        Array results(times_.size());\n        for (Size i=0; i<times_.size() ; i++) {\n            results[i] = (value(times_[i]) - blackVols_[i])* std::sqrt(weights_[i]);\n        }\n        return results;\n    }\n\n    inline EndCriteria::Type AbcdCalibration::endCriteria() const{\n        return abcdEndCriteria_;\n    }\n\n}\n\n#endif", "meta": {"hexsha": "fd95e8a6395b46936853766401f9457ff01c4ffb", "size": 12444, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/termstructures/volatility/abcdcalibration.hpp", "max_stars_repo_name": "markxio/Quantuccia", "max_stars_repo_head_hexsha": "ebe71a1b9c2a9ee7fc4ea918a9602f100316869d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2017-03-20T14:17:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-22T08:00:52.000Z", "max_issues_repo_path": "ql/termstructures/volatility/abcdcalibration.hpp", "max_issues_repo_name": "markxio/Quantuccia", "max_issues_repo_head_hexsha": "ebe71a1b9c2a9ee7fc4ea918a9602f100316869d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2017-04-02T14:34:07.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-13T05:31:12.000Z", "max_forks_repo_path": "ql/termstructures/volatility/abcdcalibration.hpp", "max_forks_repo_name": "markxio/Quantuccia", "max_forks_repo_head_hexsha": "ebe71a1b9c2a9ee7fc4ea918a9602f100316869d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2017-03-19T05:56:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T13:30:20.000Z", "avg_line_length": 37.0357142857, "max_line_length": 95, "alphanum_fraction": 0.5969945355, "num_tokens": 3033, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.4996140585502039}}
{"text": "//  (C) Copyright John Maddock 2005.\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_MATH_COMPLEX_ASIN_INCLUDED\r\n#define BOOST_MATH_COMPLEX_ASIN_INCLUDED\r\n\r\n#ifndef BOOST_MATH_COMPLEX_DETAILS_INCLUDED\r\n#  include <boost/math/complex/details.hpp>\r\n#endif\r\n#ifndef BOOST_MATH_LOG1P_INCLUDED\r\n#  include <boost/math/special_functions/log1p.hpp>\r\n#endif\r\n#include <boost/assert.hpp>\r\n\r\n#ifdef BOOST_NO_STDC_NAMESPACE\r\nnamespace std{ using ::sqrt; using ::fabs; using ::acos; using ::asin; using ::atan; using ::atan2; }\r\n#endif\r\n\r\nnamespace boost{ namespace math{\r\n\r\ntemplate<class T> \r\ninline std::complex<T> asin(const std::complex<T>& z)\r\n{\r\n   //\r\n   // This implementation is a transcription of the pseudo-code in:\r\n   //\r\n   // \"Implementing the complex Arcsine and Arccosine Functions using Exception Handling.\"\r\n   // T E Hull, Thomas F Fairgrieve and Ping Tak Peter Tang.\r\n   // ACM Transactions on Mathematical Software, Vol 23, No 3, Sept 1997.\r\n   //\r\n\r\n   //\r\n   // These static constants should really be in a maths constants library:\r\n   //\r\n   static const T one = static_cast<T>(1);\r\n   //static const T two = static_cast<T>(2);\r\n   static const T half = static_cast<T>(0.5L);\r\n   static const T a_crossover = static_cast<T>(1.5L);\r\n   static const T b_crossover = static_cast<T>(0.6417L);\r\n   static const T s_pi = boost::math::constants::pi<T>();\r\n   static const T half_pi = s_pi / 2;\r\n   static const T log_two = boost::math::constants::ln_two<T>();\r\n   static const T quarter_pi = s_pi / 4;\r\n#ifdef BOOST_MSVC\r\n#pragma warning(push)\r\n#pragma warning(disable:4127)\r\n#endif\r\n   //\r\n   // Get real and imaginary parts, discard the signs as we can \r\n   // figure out the sign of the result later:\r\n   //\r\n   T x = std::fabs(z.real());\r\n   T y = std::fabs(z.imag());\r\n   T real, imag;  // our results\r\n\r\n   //\r\n   // Begin by handling the special cases for infinities and nan's\r\n   // specified in C99, most of this is handled by the regular logic\r\n   // below, but handling it as a special case prevents overflow/underflow\r\n   // arithmetic which may trip up some machines:\r\n   //\r\n   if((boost::math::isnan)(x))\r\n   {\r\n      if((boost::math::isnan)(y))\r\n         return std::complex<T>(x, x);\r\n      if((boost::math::isinf)(y))\r\n      {\r\n         real = x;\r\n         imag = std::numeric_limits<T>::infinity();\r\n      }\r\n      else\r\n         return std::complex<T>(x, x);\r\n   }\r\n   else if((boost::math::isnan)(y))\r\n   {\r\n      if(x == 0)\r\n      {\r\n         real = 0;\r\n         imag = y;\r\n      }\r\n      else if((boost::math::isinf)(x))\r\n      {\r\n         real = y;\r\n         imag = std::numeric_limits<T>::infinity();\r\n      }\r\n      else\r\n         return std::complex<T>(y, y);\r\n   }\r\n   else if((boost::math::isinf)(x))\r\n   {\r\n      if((boost::math::isinf)(y))\r\n      {\r\n         real = quarter_pi;\r\n         imag = std::numeric_limits<T>::infinity();\r\n      }\r\n      else\r\n      {\r\n         real = half_pi;\r\n         imag = std::numeric_limits<T>::infinity();\r\n      }\r\n   }\r\n   else if((boost::math::isinf)(y))\r\n   {\r\n      real = 0;\r\n      imag = std::numeric_limits<T>::infinity();\r\n   }\r\n   else\r\n   {\r\n      //\r\n      // special case for real numbers:\r\n      //\r\n      if((y == 0) && (x <= one))\r\n         return std::complex<T>(std::asin(z.real()), z.imag());\r\n      //\r\n      // Figure out if our input is within the \"safe area\" identified by Hull et al.\r\n      // This would be more efficient with portable floating point exception handling;\r\n      // fortunately the quantities M and u identified by Hull et al (figure 3), \r\n      // match with the max and min methods of numeric_limits<T>.\r\n      //\r\n      T safe_max = detail::safe_max(static_cast<T>(8));\r\n      T safe_min = detail::safe_min(static_cast<T>(4));\r\n\r\n      T xp1 = one + x;\r\n      T xm1 = x - one;\r\n\r\n      if((x < safe_max) && (x > safe_min) && (y < safe_max) && (y > safe_min))\r\n      {\r\n         T yy = y * y;\r\n         T r = std::sqrt(xp1*xp1 + yy);\r\n         T s = std::sqrt(xm1*xm1 + yy);\r\n         T a = half * (r + s);\r\n         T b = x / a;\r\n\r\n         if(b <= b_crossover)\r\n         {\r\n            real = std::asin(b);\r\n         }\r\n         else\r\n         {\r\n            T apx = a + x;\r\n            if(x <= one)\r\n            {\r\n               real = std::atan(x/std::sqrt(half * apx * (yy /(r + xp1) + (s-xm1))));\r\n            }\r\n            else\r\n            {\r\n               real = std::atan(x/(y * std::sqrt(half * (apx/(r + xp1) + apx/(s+xm1)))));\r\n            }\r\n         }\r\n\r\n         if(a <= a_crossover)\r\n         {\r\n            T am1;\r\n            if(x < one)\r\n            {\r\n               am1 = half * (yy/(r + xp1) + yy/(s - xm1));\r\n            }\r\n            else\r\n            {\r\n               am1 = half * (yy/(r + xp1) + (s + xm1));\r\n            }\r\n            imag = boost::math::log1p(am1 + std::sqrt(am1 * (a + one)));\r\n         }\r\n         else\r\n         {\r\n            imag = std::log(a + std::sqrt(a*a - one));\r\n         }\r\n      }\r\n      else\r\n      {\r\n         //\r\n         // This is the Hull et al exception handling code from Fig 3 of their paper:\r\n         //\r\n         if(y <= (std::numeric_limits<T>::epsilon() * std::fabs(xm1)))\r\n         {\r\n            if(x < one)\r\n            {\r\n               real = std::asin(x);\r\n               imag = y / std::sqrt(-xp1*xm1);\r\n            }\r\n            else\r\n            {\r\n               real = half_pi;\r\n               if(((std::numeric_limits<T>::max)() / xp1) > xm1)\r\n               {\r\n                  // xp1 * xm1 won't overflow:\r\n                  imag = boost::math::log1p(xm1 + std::sqrt(xp1*xm1));\r\n               }\r\n               else\r\n               {\r\n                  imag = log_two + std::log(x);\r\n               }\r\n            }\r\n         }\r\n         else if(y <= safe_min)\r\n         {\r\n            // There is an assumption in Hull et al's analysis that\r\n            // if we get here then x == 1.  This is true for all \"good\"\r\n            // machines where :\r\n            // \r\n            // E^2 > 8*sqrt(u); with:\r\n            //\r\n            // E =  std::numeric_limits<T>::epsilon()\r\n            // u = (std::numeric_limits<T>::min)()\r\n            //\r\n            // Hull et al provide alternative code for \"bad\" machines\r\n            // but we have no way to test that here, so for now just assert\r\n            // on the assumption:\r\n            //\r\n            BOOST_ASSERT(x == 1);\r\n            real = half_pi - std::sqrt(y);\r\n            imag = std::sqrt(y);\r\n         }\r\n         else if(std::numeric_limits<T>::epsilon() * y - one >= x)\r\n         {\r\n            real = x/y; // This can underflow!\r\n            imag = log_two + std::log(y);\r\n         }\r\n         else if(x > one)\r\n         {\r\n            real = std::atan(x/y);\r\n            T xoy = x/y;\r\n            imag = log_two + std::log(y) + half * boost::math::log1p(xoy*xoy);\r\n         }\r\n         else\r\n         {\r\n            T a = std::sqrt(one + y*y);\r\n            real = x/a; // This can underflow!\r\n            imag = half * boost::math::log1p(static_cast<T>(2)*y*(y+a));\r\n         }\r\n      }\r\n   }\r\n\r\n   //\r\n   // Finish off by working out the sign of the result:\r\n   //\r\n   if((boost::math::signbit)(z.real()))\r\n      real = (boost::math::changesign)(real);\r\n   if((boost::math::signbit)(z.imag()))\r\n      imag = (boost::math::changesign)(imag);\r\n\r\n   return std::complex<T>(real, imag);\r\n#ifdef BOOST_MSVC\r\n#pragma warning(pop)\r\n#endif\r\n}\r\n\r\n} } // namespaces\r\n\r\n#endif // BOOST_MATH_COMPLEX_ASIN_INCLUDED\r\n", "meta": {"hexsha": "4b1e0f8ef04f9bbe1b7ceecdb43de02801a5b310", "size": 7606, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "master/core/third/boost/math/complex/asin.hpp", "max_stars_repo_name": "importlib/klib", "max_stars_repo_head_hexsha": "a59837857689d0e60d3df6d2ebd12c3160efa794", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 198.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T05:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:46:46.000Z", "max_issues_repo_path": "master/core/third/boost/math/complex/asin.hpp", "max_issues_repo_name": "isuhao/klib", "max_issues_repo_head_hexsha": "a59837857689d0e60d3df6d2ebd12c3160efa794", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 197.0, "max_issues_repo_issues_event_min_datetime": "2017-07-06T16:53:59.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-31T17:57:51.000Z", "max_forks_repo_path": "master/core/third/boost/math/complex/asin.hpp", "max_forks_repo_name": "isuhao/klib", "max_forks_repo_head_hexsha": "a59837857689d0e60d3df6d2ebd12c3160efa794", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 30.1825396825, "max_line_length": 102, "alphanum_fraction": 0.4884301867, "num_tokens": 1945, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4996140585502038}}
{"text": "#include <opencv2/opencv.hpp>\n#include <sophus/se3.h>\n#include <Eigen/Core>\n#include <vector>\n#include <string>\n#include <boost/format.hpp>\n#include <pangolin/pangolin.h>\n\nusing namespace std;\nusing namespace Eigen;\nusing namespace cv;\n\ntypedef vector<Eigen::Vector2d, Eigen::aligned_allocator<Eigen::Vector2d>> VecVector2d;\n\n// Camera intrinsics\n// \u5185\u53c2\ndouble fx = 718.856, fy = 718.856, cx = 607.1928, cy = 185.2157;\n// \u57fa\u7ebf\ndouble baseline = 0.573;\n// paths\nstring left_file = \"../left.png\";\nstring disparity_file = \"../disparity.png\";\nboost::format fmt_others(\"../%06d.png\");    // other files\n\n// useful typedefs\ntypedef Eigen::Matrix<double, 6, 6> Matrix6d;\ntypedef Eigen::Matrix<double, 2, 6> Matrix26d;\ntypedef Eigen::Matrix<double, 6, 1> Vector6d;\n\n// TODO implement this function\n/**\n * pose estimation using direct method\n * @param img1\n * @param img2\n * @param px_ref\n * @param depth_ref\n * @param T21\n */\nvoid DirectPoseEstimationMultiLayer(\n        const cv::Mat &img1,\n        const cv::Mat &img2,\n        const VecVector2d &px_ref,\n        const vector<double> depth_ref,\n        Sophus::SE3 &T21\n);\n\n// TODO implement this function\n/**\n * pose estimation using direct method\n * @param img1\n * @param img2\n * @param px_ref\n * @param depth_ref\n * @param T21\n */\nvoid DirectPoseEstimationSingleLayer(\n        const cv::Mat &img1,\n        const cv::Mat &img2,\n        const VecVector2d &px_ref,\n        const vector<double> depth_ref,\n        Sophus::SE3 &T21\n);\n\n// bilinear interpolation\ninline float GetPixelValue(const cv::Mat &img, float x, float y) {\n    uchar *data = &img.data[int(y) * img.step + int(x)];\n    float xx = x - floor(x);\n    float yy = y - floor(y);\n    return float(\n            (1 - xx) * (1 - yy) * data[0] +\n            xx * (1 - yy) * data[1] +\n            (1 - xx) * yy * data[img.step] +\n            xx * yy * data[img.step + 1]\n    );\n}\n\ninline bool OutOfImg(float u, float v, int col, int row){\n\tif(u >= 0 && u < col && v >= 0 && v < row)\n\t\treturn false;\n\telse{\n\t\treturn true;\n\t}\n}\n\nint main(int argc, char **argv) {\n\n    cv::Mat left_img = cv::imread(left_file, 0);\n    cv::Mat disparity_img = cv::imread(disparity_file, 0);\n\n    // let's randomly pick pixels in the first image and generate some 3d points in the first image's frame\n    cv::RNG rng;\n    int nPoints = 1000;\n    int boarder = 40;\n    VecVector2d pixels_ref;\n    vector<double> depth_ref;\n\n    // generate pixels in ref and load depth data\n    for (int i = 0; i < nPoints; i++) {\n        int x = rng.uniform(boarder, left_img.cols - boarder);  // don't pick pixels close to boarder\n        int y = rng.uniform(boarder, left_img.rows - boarder);  // don't pick pixels close to boarder\n        int disparity = disparity_img.at<uchar>(y, x);\n        double depth = fx * baseline / disparity; // you know this is disparity to depth\n        depth_ref.push_back(depth);\n        pixels_ref.push_back(Eigen::Vector2d(x, y));\n    }\n\n    // estimates 01~05.png's pose using this information\n    Sophus::SE3 T_cur_ref;\n\n    for (int i = 1; i < 6; i++) {  // 1~10\n        cv::Mat img = cv::imread((fmt_others % i).str(), 0);\n       // DirectPoseEstimationSingleLayer(left_img, img, pixels_ref, depth_ref, T_cur_ref);    // first you need to test single layer\n        DirectPoseEstimationMultiLayer(left_img, img, pixels_ref, depth_ref, T_cur_ref);\n    }\n}\n\nvoid DirectPoseEstimationSingleLayer(\n        const cv::Mat &img1,\n        const cv::Mat &img2,\n        const VecVector2d &px_ref,\n        const vector<double> depth_ref,\n        Sophus::SE3 &T21\n) {\n\n    // parameters\n    int half_patch_size = 4;\n    int iterations = 100;\n\n    double cost = 0, lastCost = 0;\n    int nGood = 0;  // good projections\n    VecVector2d goodProjection;\n\n    for (int iter = 0; iter < iterations; iter++) {\n        nGood = 0;\n        goodProjection.clear();\n\n        // Define Hessian and bias\n        Matrix6d H = Matrix6d::Zero();  // 6x6 Hessian\n        Vector6d b = Vector6d::Zero();  // 6x1 bias\n\n        for (size_t i = 0; i < px_ref.size(); i++) {\n\n            // compute the projection in the second image\n            // TODO START YOUR CODE HERE\n            float u = px_ref[i](0), v = px_ref[i](1);\n\t\t\tdouble zCam1 = depth_ref[i];\n\t\t\tdouble xCam1 = double(zCam1 / fx * (u - cx));\n\t\t\tdouble yCam1 = double(zCam1 / fy * (v - cy));\n\t\t\tVector3d pCam1(xCam1, yCam1, zCam1);\n\t\t\tVector3d pCam2 = T21 * pCam1;\n\t\t\tdouble xCam2 = pCam2[0], yCam2 = pCam2[1], zCam2 = pCam2[2];\n\t\t\tfloat u2 = float(fx * xCam2 / zCam2 + cx);\n\t\t\tfloat v2 = float(fy * yCam2 / zCam2 + cy);\n\t\t\t\n\t\t\tif(OutOfImg(u-half_patch_size, v-half_patch_size, img1.cols, img1.rows)\n\t\t\t  || OutOfImg(u+half_patch_size-1, v+half_patch_size-1, img1.cols, img1.rows) \n\t\t\t  || OutOfImg(u2-half_patch_size, v2-half_patch_size, img2.cols, img2.rows)\n\t\t\t  || OutOfImg(u2+half_patch_size-1, v2+half_patch_size-1, img2.cols, img2.rows)\n\t\t\t  ){\n\t\t\t//\tcout << \"[DM] pixel out of img \" << endl;\n\t\t\t//\tcout << u << \"  \" << v << \" \" << img1.cols << \" \" << img1.rows << endl;\n\t\t\t//\tcout << u2 << \"  \" << v2 << \" \" << img2.cols << \" \" << img2.rows << endl;\n\t\t\t\tcontinue;\n\t\t\t}\n\n//\t\t\tcout << \"uv in cam1:\" << u << \" \" << v << endl;\n//\t\t\tcout << \"uv in cam2:\" << u2 << \" \" << v2 << endl;\n//\t\t\tcout << \"p in cam2: \" << pCam2 << endl; \n//\t\t\tcout << \"p in cam1: \" << pCam1 << endl; \n            nGood++;\n            goodProjection.push_back(Eigen::Vector2d(u2, v2));\n\n\t\t\tdouble xCam2_2 = xCam2 * xCam2, yCam2_2 = yCam2 * yCam2, zCam2_2 = zCam2 * zCam2;\n\t\t\tMatrix26d J_pixel_xi;   // pixel to \\xi in Lie algebra\n\t\t\tJ_pixel_xi(0,0) = fx / zCam2;\n\t\t\tJ_pixel_xi(0,1) = 0;\n\t\t    J_pixel_xi(0,2) = - fx * xCam2 / zCam2_2;\n\t\t    J_pixel_xi(0,3) = - fx * xCam2 * yCam2 / zCam2_2;\n\t\t    J_pixel_xi(0,4) = fx + fx * xCam2_2 / zCam2_2;\n\t\t    J_pixel_xi(0,5) = - fx * yCam2 / zCam2;\n\t\t    J_pixel_xi(1,0) = 0;\n\t\t    J_pixel_xi(1,1) = fy / zCam2;\n\t\t    J_pixel_xi(1,2) = -fy * yCam2 / zCam2_2;\n\t\t    J_pixel_xi(1,3) = -fy - fy * yCam2_2 / zCam2_2;\n\t\t    J_pixel_xi(1,4) = fy * xCam2 * yCam2 / zCam2_2;\n\t\t    J_pixel_xi(1,5) = fy * xCam2 / zCam2;\n    \n\t\t\t// and compute error and jacobian\n            for (int x = -half_patch_size; x < half_patch_size; x++)\n                for (int y = -half_patch_size; y < half_patch_size; y++) {\n\n                    double error = 0;\n                    Eigen::Vector2d J_img_pixel;    // image gradients\n\n                    float u1_patch = u + x, v1_patch = v + y;\n\t\t\t\t\tfloat u2_patch = u2 + x, v2_patch = v2 + y;\n\t\t\t\t\terror = GetPixelValue(img1, u1_patch, v1_patch) - GetPixelValue(img2, u2_patch, v2_patch);\n\t\t    \t\tJ_img_pixel[0] = (GetPixelValue(img2, u2_patch + 1, v2_patch) - GetPixelValue(img2, u2_patch - 1, v2_patch)) / 2;\n\t\t  \t\t\tJ_img_pixel[1] = (GetPixelValue(img2, u2_patch, v2_patch + 1) - GetPixelValue(img2, u2_patch, v2_patch - 1)) / 2 ;\t\n\t\t\t\t\t// total jacobian\n                    Vector6d J = -J_pixel_xi.transpose() * J_img_pixel;\n\n                    H += J * J.transpose();\n                    b += -error * J;\n                    cost += error * error;\n                }\n            // END YOUR CODE HERE\n        }\n\n        // solve update and put it into estimation\n        // TODO START YOUR CODE HERE\n        Vector6d update;\n\t\tupdate = H.ldlt().solve(b);\n        T21 = Sophus::SE3::exp(update) * T21;\n        // END YOUR CODE HERE\n\n        cost /= nGood;\n\n        if (std::isnan(update[0])) {\n            // sometimes occurred when we have a black or white patch and H is irreversible\n            cout << \"update is nan\" << endl;\n            break;\n        }\n        if (iter > 0 && cost > lastCost) {\n//            cout << \"cost increased: \" << cost << \", \" << lastCost << endl;\n            break;\n        }\n        lastCost = cost;\n//        cout << \"cost = \" << cost << \", good = \" << nGood << endl;\n    }\n//    cout << \"good projection: \" << nGood << endl;\n//    cout << \"T21 = \\n\" << T21.matrix() << endl;\n\n    // in order to help you debug, we plot the projected pixels here\n//    cv::Mat img1_show, img2_show;\n//    cv::cvtColor(img1, img1_show, CV_GRAY2BGR);\n//    cv::cvtColor(img2, img2_show, CV_GRAY2BGR);\n//    for (auto &px: px_ref) {\n//        cv::rectangle(img1_show, cv::Point2f(px[0] - 2, px[1] - 2), cv::Point2f(px[0] + 2, px[1] + 2),\n//                      cv::Scalar(0, 250, 0));\n//    }\n//    for (auto &px: goodProjection) {\n//        cv::rectangle(img2_show, cv::Point2f(px[0] - 2, px[1] - 2), cv::Point2f(px[0] + 2, px[1] + 2),\n//                      cv::Scalar(0, 250, 0));\n//    }\n//    cv::imshow(\"reference\", img1_show);\n//    cv::imshow(\"current\", img2_show);\n//    cv::waitKey();\n}\n\nvoid DirectPoseEstimationMultiLayer(\n        const cv::Mat &img1,\n        const cv::Mat &img2,\n        const VecVector2d &px_ref,\n        const vector<double> depth_ref,\n        Sophus::SE3 &T21\n) {\n\n    // parameters\n    int pyramids = 4;\n    double pyramid_scale = 0.5;\n    double scales[] = {1.0, 0.5, 0.25, 0.125};\n\n    // create pyramids\n    vector<cv::Mat> pyr1, pyr2; // image pyramids\n    // TODO START YOUR CODE HERE\n\tfor(int i = 0; i < pyramids; i++){\n\t\tMat img1_resize, img2_resize;\n\t\tcv::resize(img1, img1_resize, Size(img1.cols * scales[i], img1.rows * scales[i]));\n\t\tcv::resize(img2, img2_resize, Size(img2.cols * scales[i], img2.rows * scales[i]));\n\t\tpyr1.push_back(img1_resize);\n\t\tpyr2.push_back(img2_resize);\n\t}\n    // END YOUR CODE HERE\n\n    double fxG = fx, fyG = fy, cxG = cx, cyG = cy;  // backup the old values\n    for (int level = pyramids - 1; level >= 0; level--) {\n        VecVector2d px_ref_pyr; // set the keypoints in this pyramid level\n        for (auto &px: px_ref) {\n            px_ref_pyr.push_back(scales[level] * px);\n        }\n\n        // TODO START YOUR CODE HERE\n        // scale fx, fy, cx, cy in different pyramid levels\n\t\tfx = fxG * scales[level];\n\t\tfy = fyG * scales[level];\n\t\tcx = cxG * scales[level];\n\t\tcy = cyG * scales[level];\n\n        // END YOUR CODE HERE\n        DirectPoseEstimationSingleLayer(pyr1[level], pyr2[level], px_ref_pyr, depth_ref, T21);//T21 have add before's cal result.\n    }\n\tcout << \"Multi T21 = \\n\" << T21.matrix() << endl;\n}\n", "meta": {"hexsha": "2629064ad49f46b9096979ca1e90109a45562467", "size": 10084, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "slam/PA6_code/code/direct_method.cpp", "max_stars_repo_name": "wallEVA96/algorithm", "max_stars_repo_head_hexsha": "c64e50eff9ad928015ce2780086dd9682c8e2220", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2018-12-27T05:44:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T03:36:15.000Z", "max_issues_repo_path": "slam/PA6_code/code/direct_method.cpp", "max_issues_repo_name": "wallEVA96/algorithm", "max_issues_repo_head_hexsha": "c64e50eff9ad928015ce2780086dd9682c8e2220", "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": "slam/PA6_code/code/direct_method.cpp", "max_forks_repo_name": "wallEVA96/algorithm", "max_forks_repo_head_hexsha": "c64e50eff9ad928015ce2780086dd9682c8e2220", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2020-04-23T02:01:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-28T02:55:16.000Z", "avg_line_length": 34.1830508475, "max_line_length": 133, "alphanum_fraction": 0.5800277668, "num_tokens": 3225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189134878876, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.4996140559026607}}
{"text": "//\n//  AMGCLSolver.hpp\n//  IPC\n//\n//  Created by Minchen Li on 11/06/19.\n//\n\n#ifndef AMGCLSolver_hpp\n#define AMGCLSolver_hpp\n\n#include \"LinSysSolver.hpp\"\n\n#include <amgcl/make_solver.hpp>\n#include <amgcl/solver/cg.hpp>\n#include <amgcl/solver/lgmres.hpp>\n#include <amgcl/amg.hpp>\n#include <amgcl/coarsening/smoothed_aggregation.hpp>\n#include <amgcl/relaxation/spai0.hpp>\n#include <amgcl/relaxation/gauss_seidel.hpp>\n#include <amgcl/adapter/crs_tuple.hpp>\n#include <amgcl/adapter/block_matrix.hpp>\n#include <amgcl/value_type/static_matrix.hpp>\n\n#include <Eigen/Eigen>\n\n#include <vector>\n#include <set>\n\n#define USE_BW_BACKEND // use blockwise backend, must undef USE_BW_AGGREGATION\n// #define USE_BW_AGGREGATION // use scalar backend but blockwise aggregation, must undef USE_BW_BACKEND\n// if neither of above is defined, will use scalar backend and aggregation\n\n// #define USE_AMG_SOLVER // use a single V-cycle to approximately solve the linear system\n// if not defined then will use V-cycle preconditioned CG to solve the linear system\n\nnamespace IPC {\n\ntemplate <typename vectorTypeI, typename vectorTypeS>\nclass AMGCLSolver : public LinSysSolver<vectorTypeI, vectorTypeS> {\n    typedef LinSysSolver<vectorTypeI, vectorTypeS> Base;\n\n#ifdef USE_BW_BACKEND\n    typedef amgcl::static_matrix<double, DIM, DIM> value_type;\n    typedef amgcl::static_matrix<double, DIM, 1> rhs_type;\n    typedef amgcl::backend::builtin<value_type> BBackend;\n    using Solver = amgcl::make_solver<\n        // Use AMG as preconditioner:\n        amgcl::amg<\n            BBackend,\n            amgcl::coarsening::smoothed_aggregation,\n            amgcl::relaxation::gauss_seidel>,\n        // And BiCGStab as iterative solver:\n        amgcl::solver::lgmres<BBackend>>;\n#else\n    typedef amgcl::backend::builtin<double> Backend;\n    // Use AMG as preconditioner:\n    typedef amgcl::make_solver<\n        // Use AMG as preconditioner:\n        amgcl::amg<\n            Backend,\n            amgcl::coarsening::smoothed_aggregation,\n            amgcl::relaxation::gauss_seidel>,\n        // And CG as iterative solver:\n        amgcl::solver::lgmres<Backend>>\n        Solver;\n#endif\n\nprotected:\n    Solver* solver;\n    std::vector<int> _ia, _ja;\n    std::vector<double> _a;\n\npublic:\n    AMGCLSolver(void);\n    ~AMGCLSolver(void);\n\n    void set_pattern(const std::vector<std::set<int>>& vNeighbor,\n        const std::set<int>& fixedVert);\n    void load(const char* filePath, Eigen::VectorXd& rhs);\n\n    void load_AMGCL(const char* filePath, Eigen::VectorXd& rhs);\n    void write_AMGCL(const char* filePath, const Eigen::VectorXd& rhs) const;\n\n    void copyOffDiag_IJ(void);\n    void copyOffDiag_a(void);\n\n    void analyze_pattern(void);\n\n    bool factorize(void);\n\n    void solve(Eigen::VectorXd& rhs,\n        Eigen::VectorXd& result);\n};\n\n} // namespace IPC\n\n#endif /* AMGCLSolver_hpp */\n", "meta": {"hexsha": "6b9887d9fba450ce580d7ff2d9a9ccf08abd79ba", "size": 2852, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/LinSysSolver/AMGCLSolver.hpp", "max_stars_repo_name": "vincentkslim/IPC", "max_stars_repo_head_hexsha": "eb702ead6f23a1dc0be39c9f5a0fd62c80abeb98", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2021-11-03T18:39:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T09:19:14.000Z", "max_issues_repo_path": "src/LinSysSolver/AMGCLSolver.hpp", "max_issues_repo_name": "vincentkslim/IPC", "max_issues_repo_head_hexsha": "eb702ead6f23a1dc0be39c9f5a0fd62c80abeb98", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-11-03T18:47:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-28T19:41:49.000Z", "max_forks_repo_path": "src/LinSysSolver/AMGCLSolver.hpp", "max_forks_repo_name": "vincentkslim/IPC", "max_forks_repo_head_hexsha": "eb702ead6f23a1dc0be39c9f5a0fd62c80abeb98", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-11-03T18:57:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-22T06:43:37.000Z", "avg_line_length": 29.1020408163, "max_line_length": 104, "alphanum_fraction": 0.7040673212, "num_tokens": 767, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.49961405325511743}}
{"text": "#include <Eigen/Eigen>\n#include <boost/geometry.hpp>\n#include <limits>\n#include <lmlib/intersection.h>\n\nnamespace lm\n{\nbox2f get_box(Eigen::Vector2f extents) { return box2f{-extents, extents}; }\n\nfloat distance(Eigen::Vector2f point, Eigen::Vector2f box_extents)\n{\n    box2f box = get_box(box_extents);\n\n    if (boost::geometry::within(point, box))\n    {\n        Eigen::Vector2f a{-box_extents[0], -box_extents[1]},\n          b{-box_extents[0], box_extents[1]}, c{box_extents[0], box_extents[1]},\n          d{box_extents[0], -box_extents[1]};\n\n        std::initializer_list<segment2f> segments{\n          {a, b}, {b, c}, {c, d}, {d, a}};\n\n        float distance{std::numeric_limits<float>::max()};\n\n        for (auto segment : segments)\n        {\n            distance = std::min(\n              (float)boost::geometry::distance(segment, point), distance);\n        }\n        return -distance;\n    }\n\n    return boost::geometry::distance(point, box);\n}\n\nstd::pair<segment2f, float>\n  closest_edge(Eigen::Vector2f point, Eigen::Vector2f box_extents)\n{\n    Eigen::Vector2f a{-box_extents[0], -box_extents[1]},\n      b{-box_extents[0], box_extents[1]}, c{box_extents[0], box_extents[1]},\n      d{box_extents[0], -box_extents[1]};\n\n    std::initializer_list<segment2f> segments{{a, b}, {b, c}, {c, d}, {d, a}};\n\n    float min_distance{std::numeric_limits<float>::max()};\n    segment2f closest;\n\n    for (auto segment : segments)\n    {\n        double segment_distance = boost::geometry::distance(segment, point);\n        if (segment_distance < min_distance)\n        {\n            min_distance = segment_distance;\n            closest = segment;\n        }\n    }\n\n    return {closest, min_distance};\n}\n} // namespace lm\n", "meta": {"hexsha": "7b6a0aa7fb9ff341b2072940b4a0dee9d13f2d53", "size": 1709, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lmlib/src/geometry/intersection.cpp", "max_stars_repo_name": "Lawrencemm/LM-Engine", "max_stars_repo_head_hexsha": "9c5e59e64e2a5a24c347538fa49046ab5a88d1f5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 40.0, "max_stars_repo_stars_event_min_datetime": "2020-03-13T06:12:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-16T21:05:34.000Z", "max_issues_repo_path": "lmlib/src/geometry/intersection.cpp", "max_issues_repo_name": "Lawrencemm/LM-Engine", "max_issues_repo_head_hexsha": "9c5e59e64e2a5a24c347538fa49046ab5a88d1f5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 31.0, "max_issues_repo_issues_event_min_datetime": "2020-02-09T06:25:12.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-31T04:37:08.000Z", "max_forks_repo_path": "lmlib/src/geometry/intersection.cpp", "max_forks_repo_name": "Lawrencemm/LM-Engine", "max_forks_repo_head_hexsha": "9c5e59e64e2a5a24c347538fa49046ab5a88d1f5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-03-13T06:12:12.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-21T15:41:17.000Z", "avg_line_length": 28.0163934426, "max_line_length": 80, "alphanum_fraction": 0.6184903452, "num_tokens": 482, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.49961405325511743}}
{"text": "//////////////////////////////////////////////////////////////////////////////\n// distribution::toolkit::distributions::gamma::is_log_concave               //\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_GAMMA_IS_LOG_CONCAVE_HPP_ER_2009\n#define BOOST_STATISTICS_DETAIL_DISTRIBUTION_TOOLKIT_GAMMA_IS_LOG_CONCAVE_HPP_ER_2009\n#include <cmath>\n#include <boost/math/distributions/gamma.hpp>\n#include <boost/math/policies/policy.hpp>\n\nnamespace boost{\nnamespace math{\n\ntemplate <class T, class P>\ninline bool is_log_concave(\n    const boost::math::gamma_distribution<T, P>& dist\n){\n    return ( dist.shape() > static_cast<T>(1) );\n}\n\n}// math\n}// boost\n\n#endif\n", "meta": {"hexsha": "01bab13ae9622b75d0e349f2213675342a8fc6c9", "size": 1137, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "distribution_toolkit/boost/statistics/detail/distribution_toolkit/distributions/gamma/is_log_concave.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/distributions/gamma/is_log_concave.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/distributions/gamma/is_log_concave.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": 39.2068965517, "max_line_length": 85, "alphanum_fraction": 0.545294635, "num_tokens": 229, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891218080991, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.49961404796003095}}
{"text": "/*-------------Lanczos.cpp----------------------------------------------------//\n*\n* Purpose: To diagonalize a random matrix using the Lanczos algorithm\n*\n*   Notes: Compile with (for Arch systems):\n*              g++ -I /usr/include/eigen3/ Lanczos.cpp\n*          0's along the prime diagonal. I don't know what this means.\n*\n*-----------------------------------------------------------------------------*/\n \n#include <iostream>\n#include <Eigen/Core>\n#include <Eigen/QR>\n#include <random>\n#include <vector>\n#include <math.h>\n\nusing namespace Eigen;\n\n// Function for the lanczos algorithm, returns Tri-diagonal matrix\nMatrixXd lanczos(MatrixXd &d_matrix, int row_num);\n\n// Function for QR decomposition\nMatrixXd qrdecomp(MatrixXd &Tridiag);\n\n// Function to perform the Power Method\nvoid p_method(MatrixXd &Tridiag, MatrixXd &Q);\n\n// Function to return sign of value (signum function)\nint sign(double value);\n\n// Function to check eigenvectors and values\nvoid eigentest(MatrixXd &d_matrix, MatrixXd &Q);\n\n/*----------------------------------------------------------------------------//\n* MAIN\n*-----------------------------------------------------------------------------*/\n\nint main(){\n\n    int size = 200;\n    MatrixXd d_matrix(size,size);\n\n    // set up random device\n    static std::random_device rd;\n    int seed = rd();\n    static std::mt19937 gen(seed);\n    std::uniform_real_distribution<double> dist(0,1);\n\n    for (size_t i = 0; i < d_matrix.rows(); ++i){\n        for (size_t j = 0; j <= i; ++j){\n            d_matrix(i,j) = dist(gen);\n            d_matrix(j,i) = d_matrix(i,j);\n        }\n    }\n\n    MatrixXd Tridiag = lanczos(d_matrix, 20);\n\n    //std::cout << '\\n' << \"Tridiagonal matrix is: \\n\" << Tridiag << '\\n';\n\n    /*\n    // Testing for eigenvalue determination\n    MatrixXd Tridiag(3,3);\n    Tridiag << 1, 2, 0,\n               2, 1, 0,\n               0, 0, -3;\n\n    MatrixXd Tridiag(5,5);\n    Tridiag << 5, 0, 0, 0, 0,\n               0, 4, 0, 0, 0,\n               0, 0, 3, 0, 0,\n               0, 0, 0, 2, 0,\n               0, 0, 0, 0, 7;\n    Tridiag = lanczos(Tridiag, 5);\n    */\n\n    //std::cout << \"Tridiag is: \" << '\\n' << Tridiag << '\\n';\n\n    MatrixXd Q = qrdecomp(Tridiag);\n\n    MatrixXd Qtemp = Q;\n\n    //std::cout << \"Q is: \" << '\\n';\n    //std::cout << Q << '\\n';\n\n    std::cout << \"Finding eigenvalues: \" << '\\n';\n    p_method(Tridiag, Q);\n\n    //std::cout << \"Q is: \" << '\\n' << Q << '\\n';\n\n    Qtemp = Qtemp - Q;\n    //std::cout << \"After the Power Method: \" << Qtemp.squaredNorm() << '\\n';\n    eigentest(Tridiag, Q);\n\n}\n\n/*----------------------------------------------------------------------------//\n* SUBROUTINE\n*-----------------------------------------------------------------------------*/\n\n// Function for the lanczos algorithm, returns Tri-diagonal matrix\nMatrixXd lanczos(MatrixXd &d_matrix, int row_num){\n\n    // Creating random device\n    static std::random_device rd;\n    int seed = rd();\n    static std::mt19937 gen(seed);\n    std::uniform_real_distribution<double> dist(0,1); \n\n    // Defining values\n    double threshold = 0.01;\n    int j = 0;\n    int size = d_matrix.rows();\n\n    // Setting beta arbitrarily large for now \n    double beta = 10;\n\n    // generating the first rayleigh vector\n    // alpha is actually just a double... sorry about that.\n    MatrixXd rayleigh(d_matrix.rows(),1), q(d_matrix.rows(),1),\n             alpha(1, 1);\n    MatrixXd identity = MatrixXd::Identity(d_matrix.rows(), d_matrix.cols());\n\n    // krylov is the krylovian subspace... Note, there might be a dynamic way to\n    // do this. Something like:\n    //std::vector <MatrixXd> krylov;\n    MatrixXd krylov(d_matrix.rows(), row_num);\n\n    for (size_t i = 0; i < size; ++i){\n        rayleigh(i) = dist(gen);\n    }\n\n    //std::cout << rayleigh << '\\n';\n\n    //while (beta > threshold){\n    for (size_t i = 0; i < row_num; ++i){\n        beta = rayleigh.norm();\n        //std::cout << \"beta is: \\n\" << beta << '\\n';\n\n        q = rayleigh / beta;\n        //std::cout << \"q is: \\n\" << q << '\\n';\n\n        alpha = q.transpose() * d_matrix * q;\n        //std::cout << \"alpha is \\n\" << alpha << '\\n';\n\n        if (j == 0){\n            rayleigh = (d_matrix - alpha(0,0) * identity) * q;\n        }\n        else{\n            rayleigh = (d_matrix - alpha(0,0) * identity) * q \n                       - beta * krylov.col(j - 1);\n\n        }\n        //std::cout << \"rayleigh is: \\n\" << rayleigh <<'\\n';\n        //std::cout << \"i is: \" << i << '\\n';\n\n        //krylov.push_back(q);\n        krylov.col(j) = q;\n        j = j+1;\n        // std::cout << j << '\\n';\n    }\n\n    /*\n    MatrixXd krylov_id = krylov.transpose() * krylov;\n    std::cout << \"The identity matrix from the krylov subspace is: \\n\" \n              << krylov_id << '\\n';\n    */\n\n    MatrixXd T(row_num,row_num);\n    T = krylov.transpose() * d_matrix * krylov;\n\n    return T;\n}\n\n// Function for QR decomposition\n// Because we only need Q for the power method, I will retun only Q\nMatrixXd qrdecomp(MatrixXd &Tridiag){\n    // Q is and orthonormal vector => Q'Q = 1\n    MatrixXd Id = MatrixXd::Identity(Tridiag.rows(), Tridiag.cols());\n    MatrixXd Q = Id;\n    MatrixXd P(Tridiag.rows(), Tridiag.cols());\n\n    // R is the upper triangular matrix\n    MatrixXd R = Tridiag;\n\n    int row_num = Tridiag.rows();\n    int countx = 0, county = 0;\n\n    // Scale R \n    double sum = 0.0, sigma, tau, fak, max_val = 0;\n\n    bool sing;\n\n    // Defining vectors for algorithm\n    MatrixXd diag(row_num,1);\n\n    //std::cout << R << '\\n';\n\n    for (int i = 0; i < row_num-1; ++i){\n        diag = MatrixXd::Zero(row_num, 1);\n\n        sum = 0;\n        for (size_t j = i; j < row_num; ++j){\n            sum += R(j,i) * R(j,i);\n            //std::cout << R(j,i) << '\\n';\n        }\n        sum = sqrt(sum);\n\n        if (R(i,i) > 0){\n            sigma = -sum;\n        }\n        else{\n            sigma = sum;\n        }\n\n        //std::cout << \"sigma is: \" << sigma << '\\n';\n\n        sum = 0;\n        //diag = R.block(i,i, row_num - i, 1);\n        //std::cout << \"diag is: \" << '\\n';\n        for (int j = i; j < row_num; ++j){\n            //std::cout << i << '\\t' << j << '\\n';\n            if (j == i){\n                diag(j) = R(j,i) + sigma;\n            }\n            else{\n                diag(j) = R(j, i);\n            }\n            //std::cout << diag(j) << '\\n';\n            sum = sum + diag(j) * diag(j);\n        }\n        sum = sqrt(sum);\n\n        //std::cout << \"sum is: \" << sum << '\\n';\n\n        if (sum > 0.000000000000001){\n\n            for (int j = i; j < row_num; ++j){\n                diag(j) = diag(j) / sum;\n            }\n    \n            //std::cout << \"normalized diag is: \" << '\\n' << diag << '\\n';\n            \n            P = Id - (diag * diag.transpose()) * 2.0;\n    \n            R = P * R;\n            Q = Q * P;\n        }\n\n        //std::cout << \"R is: \" << R << '\\n';\n\n    }\n    //std::cout << \"R is: \" << R << '\\n';\n    //std::cout << \"Q is: \" << Q << '\\n';\n\n    //std::cout << \"QR is: \" << '\\n' << Q*R << '\\n';\n\n    //std::cout << \"Q^T * Q is: \" << '\\n' << Q.transpose() * Q << '\\n' << '\\n';\n    //std::cout << \"QR - A is: \" << '\\n' << Q*R - Tridiag << '\\n';\n    //std::cout << \"Q^T * A - R: \" << '\\n'\n    //          << Q.transpose() * Tridiag - R << '\\n' << '\\n';\n\n    return Q;\n}\n\n// Function to perform the Power Method\nvoid p_method(MatrixXd &Tridiag, MatrixXd &Q){\n\n    //std::cout << \"Q is: \" << '\\n' << Q << '\\n';\n    //std::cout << \"Tridiag is : \" << '\\n' << Tridiag << '\\n';\n\n    // Find all eigenvectors\n    MatrixXd eigenvectors(Tridiag.rows(), Tridiag.cols());\n    MatrixXd Z(Tridiag.rows(), Tridiag.cols());\n    MatrixXd Qtemp = Q;\n\n    // Iteratively defines eigenvectors\n    for (int i = 0; i < Tridiag.rows(); ++i){\n        Z = Tridiag * Q;\n        Q = qrdecomp(Z);\n\n    }\n\n    Qtemp = Qtemp - Q;\n    //std::cout << \"This should not be 0: \" << Qtemp.squaredNorm() << '\\n';\n\n}\n\n// Function to return sign of value (signum function)\nint sign(double value){\n    if (value < 0.0){\n        return -1;\n    }\n    else if (value > 0){\n        return 1;\n    }\n    else {\n        return 0;\n    }\n}\n\n// Function to check eigenvectors and values\nvoid eigentest(MatrixXd &Tridiag, MatrixXd &Q){\n\n    // Calculating the Rayleigh quotient (v^t * A * v) / (v^t * v)\n    // Note, that this should be a representation of eigenvalues\n\n    std::vector<double> eigenvalues(Tridiag.rows());\n    MatrixXd checkvector(Tridiag.rows(),1);\n    double QQ, QAQ;\n\n    for (size_t i = 0; i < Tridiag.rows(); ++i){\n        QQ = Q.col(i).transpose() * Q.col(i);    \n        QAQ = Q.col(i).transpose() * Tridiag * Q.col(i);\n        eigenvalues[i] =  QAQ / QQ;\n        std::cout << \"eigenvalue is: \" << eigenvalues[i] << '\\n';\n\n        checkvector = ((Tridiag * Q.col(i)) / eigenvalues[i]) - Q.col(i);\n        //std::cout << checkvector << '\\n' << '\\n';\n        std::cout << \"This should be 0: \" << '\\t' \n                  << checkvector.squaredNorm() << '\\n';\n        \n    }\n\n}\n\n", "meta": {"hexsha": "f7ea3788ba2bf5fb8d1158e4d3f8dcddf6f7d35e", "size": 8946, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "DMRG/Lanczos.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": "DMRG/Lanczos.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": "DMRG/Lanczos.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": 27.3577981651, "max_line_length": 80, "alphanum_fraction": 0.4765258216, "num_tokens": 2644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189121808099, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.49961404796003095}}
{"text": "  \n#ifndef SOLVERSPOINTS_HPP\n#define SOLVERSPOINTS_HPP\n\n#include <Eigen/Core>\n#include <vector>\n\n// ##########################################################\n// Solver for 6L. The solver is from Stewenius paper,\n// and was implemented by Kneip.\n// ##########################################################\ntemplate <typename floatPrec>\nstd::vector<Eigen::Matrix<floatPrec,4,4>> solver3Q(\n    std::vector<std::pair<Eigen::Matrix<floatPrec,4,1>, Eigen::Matrix<floatPrec,4,1>>> ptPair,\n\tstd::vector<std::pair<Eigen::Matrix<floatPrec,4,1>, Eigen::Matrix<floatPrec,4,1>>> plPair,\n\tstd::vector<std::pair<std::pair<Eigen::Matrix<floatPrec,4,1>, Eigen::Matrix<floatPrec,4,1>>,\n        std::pair<Eigen::Matrix<floatPrec,4,1>, Eigen::Matrix<floatPrec,4,1>>>> lPair\n);\n\n#endif", "meta": {"hexsha": "b91e2e7cf8157655ceaf949562942ac113ca1d03", "size": 767, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/solverPoints.hpp", "max_stars_repo_name": "3DVisionISR/3DMinRegLineIntersect", "max_stars_repo_head_hexsha": "6ddfb39d34725f6bbd82ce7b6ca9be61fedd0438", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2020-06-11T15:50:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-23T10:36:39.000Z", "max_issues_repo_path": "include/solverPoints.hpp", "max_issues_repo_name": "3DVisionISR/3DMinRegLineIntersect", "max_issues_repo_head_hexsha": "6ddfb39d34725f6bbd82ce7b6ca9be61fedd0438", "max_issues_repo_licenses": ["MIT"], "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/solverPoints.hpp", "max_forks_repo_name": "3DVisionISR/3DMinRegLineIntersect", "max_forks_repo_head_hexsha": "6ddfb39d34725f6bbd82ce7b6ca9be61fedd0438", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-06-17T16:25:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-22T02:23:18.000Z", "avg_line_length": 38.35, "max_line_length": 94, "alphanum_fraction": 0.6036505867, "num_tokens": 201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189121808099, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.49961404796003084}}
{"text": "#include \"nmea/vtg.h\"\n#include <ros/ros.h>\n#include <boost/algorithm/string.hpp>\n#include \"geometry_msgs/Vector3Stamped.h\"\n#include \"angles/angles.h\"\n\nusing std::string;\nusing std::vector;\nusing std::tuple;\nusing std::get;\n\nnmea::vtg\nv3s_to_vtg_ros_msg(geometry_msgs::Vector3Stamped const &message);\n\nnmea::vtg\nv3s_to_vtg_ros_msg(geometry_msgs::Vector3Stamped const &message)\n{\n  double const speedMagMps = sqrt(message.vector.x * message.vector.x +\n                                  message.vector.y * message.vector.y +\n                                  message.vector.z * message.vector.z);\n\n  double const trackFromEastRad = atan2(-message.vector.y, message.vector.x);\n  double const trackFromNorthDeg = angles::to_degrees(trackFromEastRad);\n\n  nmea::vtg ros_msg;\n  ros_msg.true_track_made_good = trackFromNorthDeg;\n  ros_msg.magnetic_track_made_good_valid = false;\n  ros_msg.ground_speed_knots = speedMagMps * 1.94384;\n  ros_msg.ground_speed_kph = speedMagMps * 3.6;\n  return ros_msg;\n}\n\nclass NmeaSubVelToNmeaPubVtg\n{\npublic:\n  inline NmeaSubVelToNmeaPubVtg(ros::NodeHandle *const nh)\n      : vtgPub(nh->advertise<nmea::vtg>(\"vtg\", 10))\n  {\n  }\n\n  inline void Callback(geometry_msgs::Vector3Stamped const &message)\n  {\n    this->vtgPub.publish(v3s_to_vtg_ros_msg(message));\n  }\n\nprivate:\n  ros::Publisher vtgPub;\n};\n\nint main(int argc, char *argv[])\n{\n  ros::init(argc, argv, \"vel_to_vtg\");\n\n  ros::NodeHandle n;\n  NmeaSubVelToNmeaPubVtg nmea_sub_vel_to_nmea_pub_vtg(&n);\n  ros::Subscriber sub =\n      n.subscribe(\"gps/fix_velocity\", 10, &NmeaSubVelToNmeaPubVtg::Callback,\n                  &nmea_sub_vel_to_nmea_pub_vtg);\n\n  ros::spin();\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "443f63c97fe6ed452f3fbdd73378f34523a252c3", "size": 1671, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/geometry_msgs_Vector3Stamped_to_vtg.cpp", "max_stars_repo_name": "geoffviola/raw_nmea", "max_stars_repo_head_hexsha": "37282e1c07a067d8f7370564c5bb94af0c34af90", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_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_msgs_Vector3Stamped_to_vtg.cpp", "max_issues_repo_name": "geoffviola/raw_nmea", "max_issues_repo_head_hexsha": "37282e1c07a067d8f7370564c5bb94af0c34af90", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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_msgs_Vector3Stamped_to_vtg.cpp", "max_forks_repo_name": "geoffviola/raw_nmea", "max_forks_repo_head_hexsha": "37282e1c07a067d8f7370564c5bb94af0c34af90", "max_forks_repo_licenses": ["BSD-3-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.109375, "max_line_length": 77, "alphanum_fraction": 0.710353082, "num_tokens": 498, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891130942474, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.49961404266494414}}
{"text": "/*----------------------------------------------------------------------------*/\n/* Copyright (c) 2020-2021 FIRST. All Rights Reserved.                        */\n/* Open Source Software - may be modified and shared by FRC teams. The code   */\n/* must be accompanied by the FIRST BSD license file in the root directory of */\n/* the project.                                                               */\n/*----------------------------------------------------------------------------*/\n\n#include <Eigen/QR>\n#include <wpi/MathExtras.h>\n\n#include \"frc/geometry/Pose2d.h\"\n#include \"frc/system/LinearSystem.h\"\n#include \"frc/system/plant/LinearSystemId.h\"\n#include \"frc/trajectory/TestTrajectory.h\"\n#include \"frc/trajectory/TrajectoryGenerator.h\"\n#include \"frc/trajectory/constraint/DifferentialDriveVelocitySystemConstraint.h\"\n#include \"gtest/gtest.h\"\n\n// TODO: The constraint used in this test violates the max voltage, but not\n// doing so would mean the only way to reach the max steady-state velocity for\n// that voltage is open-loop exponential convergence. The constraint's\n// optimization intent should be clarified so we can write a better test.\nTEST(DifferentialDriveVelocitySystemTest, DISABLED_Constraint) {\n  constexpr auto kMaxVoltage = 10_V;\n\n  // Pick an unreasonably large kA to ensure the constraint has to do some work\n  const frc::LinearSystem<2, 2, 2> system =\n      frc::LinearSystemId::IdentifyDrivetrainSystem(\n          1_V / 1_mps, 3_V / 1_mps_sq, 1_V / 1_rad_per_s, 3_V / 1_rad_per_s_sq);\n  const frc::DifferentialDriveKinematics kinematics{0.5_m};\n  auto config = frc::TrajectoryConfig(12_mps, 12_mps_sq);\n  config.AddConstraint(frc::DifferentialDriveVelocitySystemConstraint(\n      system, kinematics, kMaxVoltage));\n\n  auto trajectory = frc::TestTrajectory::GetTrajectory(config);\n\n  auto time = 0_s;\n  auto dt = 20_ms;\n  auto duration = trajectory.TotalTime();\n\n  while (time < duration) {\n    auto point = trajectory.Sample(time);\n    time += dt;\n\n    const frc::ChassisSpeeds chassisSpeeds{point.velocity, 0_mps,\n                                           point.velocity * point.curvature};\n\n    auto [left, right] = kinematics.ToWheelSpeeds(chassisSpeeds);\n\n    auto x = frc::MakeMatrix<2, 1>(left.to<double>(), right.to<double>());\n\n    // Not really a strictly-correct test as we're using the chassis accel\n    // instead of the wheel accel, but much easier than doing it \"properly\" and\n    // a reasonable check anyway\n    auto xDot = frc::MakeMatrix<2, 1>(point.acceleration.to<double>(),\n                                      point.acceleration.to<double>());\n\n    Eigen::Matrix<double, 2, 1> u =\n        system.B().householderQr().solve(xDot - system.A() * x);\n\n    EXPECT_GE(u(0), -kMaxVoltage.to<double>() - 0.5);\n    EXPECT_LE(u(0), kMaxVoltage.to<double>() + 0.5);\n    EXPECT_GE(u(1), -kMaxVoltage.to<double>() - 0.5);\n    EXPECT_LE(u(1), kMaxVoltage.to<double>() + 0.5);\n  }\n}\n\nTEST(DifferentialDriveVelocitySystemTest, HighCurvature) {\n  constexpr auto kMaxVoltage = 10_V;\n\n  const frc::LinearSystem<2, 2, 2> system =\n      frc::LinearSystemId::IdentifyDrivetrainSystem(\n          1_V / 1_mps, 3_V / 1_mps_sq, 1_V / 1_rad_per_s, 3_V / 1_rad_per_s_sq);\n  // Large trackwidth - need to test with radius of curvature less than half of\n  // trackwidth\n  const frc::DifferentialDriveKinematics kinematics{3_m};\n\n  auto config = frc::TrajectoryConfig(12_fps, 12_fps_sq);\n  config.AddConstraint(frc::DifferentialDriveVelocitySystemConstraint(\n      system, kinematics, kMaxVoltage));\n\n  EXPECT_NO_FATAL_FAILURE(frc::TrajectoryGenerator::GenerateTrajectory(\n      frc::Pose2d{1_m, 0_m, frc::Rotation2d{90_deg}}, {},\n      frc::Pose2d{0_m, 1_m, frc::Rotation2d{180_deg}}, config));\n\n  config.SetReversed(true);\n\n  EXPECT_NO_FATAL_FAILURE(frc::TrajectoryGenerator::GenerateTrajectory(\n      frc::Pose2d{0_m, 1_m, frc::Rotation2d{180_deg}}, {},\n      frc::Pose2d{1_m, 0_m, frc::Rotation2d{90_deg}}, config));\n}\n", "meta": {"hexsha": "4ddd5b1065eaf405f9fa8e750b65da24b11ae5e5", "size": 3940, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/cpp/frc/trajectory/constraint/DifferentialDriveVelocitySystemTest.cpp", "max_stars_repo_name": "frc3512/Robot-2019", "max_stars_repo_head_hexsha": "376a94f138562f8af59215f5e21a41a68b3f5cd2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-07-05T01:06:25.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-17T15:18:49.000Z", "max_issues_repo_path": "src/test/cpp/frc/trajectory/constraint/DifferentialDriveVelocitySystemTest.cpp", "max_issues_repo_name": "frc3512/Robot-2019", "max_issues_repo_head_hexsha": "376a94f138562f8af59215f5e21a41a68b3f5cd2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/test/cpp/frc/trajectory/constraint/DifferentialDriveVelocitySystemTest.cpp", "max_forks_repo_name": "frc3512/Robot-2019", "max_forks_repo_head_hexsha": "376a94f138562f8af59215f5e21a41a68b3f5cd2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-14T16:21:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-14T16:21:42.000Z", "avg_line_length": 42.8260869565, "max_line_length": 80, "alphanum_fraction": 0.6626903553, "num_tokens": 1046, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894520743981, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.4995851053396952}}
{"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_CONV_HPP\n#define SP_ALGO_NN_LAYER_CONV_HPP\n\n#include <boost/assert.hpp>\n\n#include \"layer.hpp\"\n#include \"connectivity.hpp\"\n#include \"detail/layers.hpp\"\n#include \"sp/util/types.hpp\"\n#include \"params.hpp\"\n\n\nSP_ALGO_NN_NAMESPACE_BEGIN\n\n/**\n * \\brief Convolutional Layer implementation\n *\n * Convolves input by a set of feature kernels and returns the convolution\n * results\n *\n * Note: This convolution implementation does not rotate the kernel\n *       and is therefore not convolution but cross correlation, mathematically\n *       speaking.\n *\n * Summary of parameters (Soft and Hard, i.e. parameterized and derived)\n *  - N - Number of images in a mini-batch\n *  - C - The number of input feature maps\n *  - H - Height of input image\n *  - W - Width of input image\n *  - K - Number of output feature maps (number of kernels)\n *  - R - Height of filter kernel\n *  - S - Width of filter kernel\n *  - U - Vertical Stride\n *  - V - Horizontal Stride\n *  - pad_h - Height of zero-padding\n *  - pad_w - Width of zero-padding\n *\n * Output O of is a four dimensional tensor in R^NKPQ,\n *  where ```P = f(H, R, u, pad_h) and Q = f(W, S, v, pad_w)```\n *  where\n *  *   ```f(H, R, u, pad_h) = ceil((H - R + 1 + 2 * pad_h) / 2)```\n *  *   ```f(W, S, v, pad_w) = ceil((W - S + 1 + 2 * pad_w) / 2)```\n *\n * Convolution Modes (common LA terms, matlab, octave)\n *  - valid - ```pad_w = pad_h = 0```\n *  - same  - ```pad_h = R/2 and pad_w = S / 2```\n *  - full  - ```pad_h = R - 1, pad_w = S - 1```\n *\n * \\tparam InputDim, includes:\n * - Width\n * - Height\n * - Depth (or channels)\n * \\tparam KernelDim, includes:... tbd\n * \\tparam Biased (optional) default true. Whether or not the layer contains bias.\n * \\tparam Sparsity The sparsity object. See #group_sparsity and #no_sparsity\n */\ntemplate<\n    typename InputVolume,\n    typename KernelParams = kernel_params_default,\n    bool Biased = true,\n    typename Connectivity = full_connectivity,\n    size_t Dilation = 0\n>\nstruct conv_layer : layer<\n    InputVolume,\n    detail::convolution_kernel_out_dims_t<InputVolume, KernelParams>,\n    conv_layer<InputVolume, KernelParams, Biased, Connectivity, Dilation>\n> {\n\n    /**\n     * Base type\n     */\n    using base = layer<\n        InputVolume,\n        detail::convolution_kernel_out_dims_t<InputVolume, KernelParams>,\n        conv_layer<InputVolume, KernelParams, Biased, Connectivity, Dilation>\n    >;\n\n    /**\n     * Validates KernelParams type\n     */\n    static_assert(util::is_instantiation_of_v<KernelParams, kernel_params>, \"KernelParams template parameter must be an instance of kernel_params\");\n\n    /**\n     * Kernel parameters\n     */\n    using kernel_params = KernelParams;\n\n    /**\n     * Connectivity type (full, ngroups, etc)\n     */\n    using connectivity_type = Connectivity;\n\n    /**\n     * \\brief Dilation parameter\n     * \\todo TBD: https://arxiv.org/abs/1511.07122\n     */\n    static_assert(Dilation == 0, \"Dilation is not implemented\");\n\n    /**\n     * Whether or not this layer has biased\n     */\n    constexpr static bool biased = Biased;\n\n    /**\n     * \\brief Input Dimensions\n     */\n    using input_dims = typename base::input_dims;\n\n    /**\n     * \\brief Output Dimensions\n     */\n    using output_dims = typename base::output_dims;\n\n    /**\n     * \\brief Weight dimensions\n     */\n    using weights_dims = weight_dims<\n        output_dims::d,\n        input_dims::d,\n        kernel_params::h,\n        kernel_params::w\n    >;\n\n    void forward_prop_impl(tensor_4& input, tensor_4& output) {\n\n        /**\n         * Number of samples in the input\n         */\n        const size_t samples = input.dimension(0);\n\n        /**\n         * Perform  forward propagation for every sample\n         */\n        #pragma omp parallel for simd\n        for (size_t si = 0; si < samples; ++si) {\n            /**\n             * Loop over the pairs of (D_out, D_in), i.e. input_dims::d*output_dims::d\n             */\n            for (size_t od = 0; od < output_dims::d; ++od) {\n                for (size_t id = 0; id < input_dims::d; ++id) {\n                    if(connections(od, id)) {\n                        /*\n                         * If the output channel is connected to the input channel,\n                         * then perform convolution. This is done to support limited\n                         * connectivity when required\n                         *\n                         * Then, perform the convolution op\n                         *\n                         * \\todo add dilation\n                         * \\todo Optimize for smaller kernels (common, 2x2, 3x3, etc)\n                         */\n                        for (size_t oy = 0, iny = 0; oy < output_dims::h; ++oy, iny += kernel_params::s_h) {\n                            for (size_t ox = 0, inx = 0; ox < output_dims::w; ++ox, inx += kernel_params::s_w) {\n                                float_t sum = 0;\n                                for (size_t ky = 0; ky < kernel_params::h; ++ky) {\n                                    for (size_t kx = 0; kx < kernel_params::w; ++kx) {\n                                        auto& in_val = input(si, id, iny+ky, inx+kx);\n                                        auto& w_val = w(od, id, ky, kx);\n                                        sum += in_val * w_val;\n                                    }\n                                }\n                                output(si, od, oy, ox) += sum;\n                            }\n                        }\n                    }\n                }\n                if constexpr(biased) {\n                    /**\n                     * Add bias to every output vector the depth slice at output(od)\n                     */\n                    output.chip(si, 0).chip(od, 0) = output.chip(si, 0).chip(od, 0) + b(od);\n                }\n            }\n        }\n    }\n\n    /**\n     * \\brief Back propagation implementation\n     *\n     * \\todo Optimize\n     */\n    void backward_prop_impl(    tensor_4& prev_out,\n                                tensor_4& prev_delta,\n                                tensor_4& curr_out,\n                                tensor_4& curr_delta)  {\n\n\n        /**\n         * Number of samples in the previous output\n         */\n        const size_t samples = prev_out.dimension(0);\n\n        /**\n         * Perform back propagation\n         *\n         * For every sample in the input\n         */\n        #pragma omp parallel for simd\n        for(size_t si = 0; si < samples; ++si) {\n            /**\n             * For every (input depth, output depth) pair that is connected\n             */\n            for (size_t id = 0; id < input_dims::d; ++id) {\n                for (size_t od = 0; od < output_dims::d; ++od) {\n                    if(connections(od, id)) {\n                        /* Propagate the current delta to the previous delta through the kernel */\n                        for (size_t oy = 0, iny = 0; oy < output_dims::h; ++oy, iny += kernel_params::s_h) {\n                            for (size_t ox = 0, inx = 0; ox < output_dims::w; ++ox, inx += kernel_params::s_w) {\n                                float_t& grad = curr_delta(si, od, oy, ox);\n                                for (size_t wy = 0; wy < weights_dims::h; ++wy) {\n                                    for (size_t wx = 0; wx < weights_dims::w; ++wx) {\n                                        auto& w_val = w(od, id, wy, wx);\n                                        prev_delta(si, id, iny + wy, inx + wx) += w_val * grad;\n                                    }\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n            for (size_t id = 0; id < input_dims::d; ++id) {\n                for (size_t od = 0; od < output_dims::d; ++od) {\n                    if(connections(od, id)) {\n                        for (size_t wy = 0; wy < weights_dims::h; ++wy) {\n                            for (size_t wx = 0; wx < weights_dims::w; ++wx) {\n                                float_t delta = 0;\n                                for (size_t oy = 0, iny = 0; oy < output_dims::h; ++oy, iny += kernel_params::s_h) {\n                                    for (size_t ox = 0, inx = 0; ox < output_dims::w; ++ox, inx += kernel_params::s_w) {\n                                        auto& po = prev_out(si, id, oy + wy, ox + wx);\n                                        auto& cd = curr_delta(si, od, oy, ox);\n                                        delta +=  po * cd;\n                                    }\n                                }\n                                dw(si, od, id, wy, wx) += delta;\n                            }\n                        }\n                    }\n                }\n            }\n            if (biased) {\n                for (size_t od = 0; od < output_dims::d; ++od) {\n                    tensor_0 sum = curr_delta.chip(si, 0).chip(od, 0).sum();\n                    db(si, od) += sum(0);\n                }\n            }\n        }\n    }\n\n    /**\n     * \\brief Weights of the layer.\n     */\n    weights_type w;\n\n    /**\n     * Weights Delta\n     */\n    weights_delta_type dw;\n\n    /**\n     * \\brief Bias.\n     */\n    bias_type b;\n\n    /**\n     * Bias Delta.\n     */\n    bias_delta_type db;\n\n    connectivity_type connections;\n\n};\n\n\nSP_ALGO_GEN_NAMESPACE_END\n\n#endif\t/* SP_ALGO_NN_LAYER_CONV_HPP */\n\n", "meta": {"hexsha": "59cf223ad9bd2ec3a4ce550068734759607b0686", "size": 9612, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/sp/algo/nn/layer/convolution.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/convolution.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/convolution.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": 33.4912891986, "max_line_length": 148, "alphanum_fraction": 0.4783603829, "num_tokens": 2299, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199511728004, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.4995843028520153}}
{"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_DIFFERENTIATION_LANCZOS_SMOOTHING_HPP\n#define BOOST_MATH_DIFFERENTIATION_LANCZOS_SMOOTHING_HPP\n#include <cmath> // for std::abs\n#include <cstddef>\n#include <limits> // to nan initialize\n#include <vector>\n#include <string>\n#include <stdexcept>\n#include <type_traits>\n#include <boost/math/tools/assert.hpp>\n\nnamespace boost::math::differentiation {\n\nnamespace detail {\ntemplate <typename Real>\nclass discrete_legendre {\n  public:\n    explicit discrete_legendre(std::size_t n, Real x) : m_n{n}, m_r{2}, m_x{x},\n                                                        m_qrm2{1}, m_qrm1{x},\n                                                        m_qrm2p{0}, m_qrm1p{1},\n                                                        m_qrm2pp{0}, m_qrm1pp{0}\n    {\n        using std::abs;\n        BOOST_MATH_ASSERT_MSG(abs(m_x) <= 1, \"Three term recurrence is stable only for |x| <=1.\");\n        // The integer n indexes a family of discrete Legendre polynomials indexed by k <= 2*n\n    }\n\n    Real norm_sq(int r) const\n    {\n        Real prod = Real(2) / Real(2 * r + 1);\n        for (int k = -r; k <= r; ++k) {\n            prod *= Real(2 * m_n + 1 + k) / Real(2 * m_n);\n        }\n        return prod;\n    }\n\n    Real next()\n    {\n        Real N = 2 * m_n + 1;\n        Real num = (m_r - 1) * (N * N - (m_r - 1) * (m_r - 1)) * m_qrm2;\n        Real tmp = (2 * m_r - 1) * m_x * m_qrm1 - num / Real(4 * m_n * m_n);\n        m_qrm2 = m_qrm1;\n        m_qrm1 = tmp / m_r;\n        ++m_r;\n        return m_qrm1;\n    }\n\n    Real next_prime()\n    {\n        Real N = 2 * m_n + 1;\n        Real s = (m_r - 1) * (N * N - (m_r - 1) * (m_r - 1)) / Real(4 * m_n * m_n);\n        Real tmp1 = ((2 * m_r - 1) * m_x * m_qrm1 - s * m_qrm2) / m_r;\n        Real tmp2 = ((2 * m_r - 1) * (m_qrm1 + m_x * m_qrm1p) - s * m_qrm2p) / m_r;\n        m_qrm2 = m_qrm1;\n        m_qrm1 = tmp1;\n        m_qrm2p = m_qrm1p;\n        m_qrm1p = tmp2;\n        ++m_r;\n        return m_qrm1p;\n    }\n\n    Real next_dbl_prime()\n    {\n        Real N = 2*m_n + 1;\n        Real trm1 = 2*m_r - 1;\n        Real s = (m_r - 1) * (N * N - (m_r - 1) * (m_r - 1)) / Real(4 * m_n * m_n);\n        Real rqrpp = 2*trm1*m_qrm1p + trm1*m_x*m_qrm1pp - s*m_qrm2pp;\n        Real tmp1 = ((2 * m_r - 1) * m_x * m_qrm1 - s * m_qrm2) / m_r;\n        Real tmp2 = ((2 * m_r - 1) * (m_qrm1 + m_x * m_qrm1p) - s * m_qrm2p) / m_r;\n        m_qrm2 = m_qrm1;\n        m_qrm1 = tmp1;\n        m_qrm2p = m_qrm1p;\n        m_qrm1p = tmp2;\n        m_qrm2pp = m_qrm1pp;\n        m_qrm1pp = rqrpp/m_r;\n        ++m_r;\n        return m_qrm1pp;\n    }\n\n    Real operator()(Real x, std::size_t k)\n    {\n        BOOST_MATH_ASSERT_MSG(k <= 2 * m_n, \"r <= 2n is required.\");\n        if (k == 0)\n        {\n            return 1;\n        }\n        if (k == 1)\n        {\n            return x;\n        }\n        Real qrm2 = 1;\n        Real qrm1 = x;\n        Real N = 2 * m_n + 1;\n        for (std::size_t r = 2; r <= k; ++r) {\n            Real num = (r - 1) * (N * N - (r - 1) * (r - 1)) * qrm2;\n            Real tmp = (2 * r - 1) * x * qrm1 - num / Real(4 * m_n * m_n);\n            qrm2 = qrm1;\n            qrm1 = tmp / r;\n        }\n        return qrm1;\n    }\n\n    Real prime(Real x, std::size_t k) {\n        BOOST_MATH_ASSERT_MSG(k <= 2 * m_n, \"r <= 2n is required.\");\n        if (k == 0) {\n            return 0;\n        }\n        if (k == 1) {\n            return 1;\n        }\n        Real qrm2 = 1;\n        Real qrm1 = x;\n        Real qrm2p = 0;\n        Real qrm1p = 1;\n        Real N = 2 * m_n + 1;\n        for (std::size_t r = 2; r <= k; ++r) {\n            Real s =\n                (r - 1) * (N * N - (r - 1) * (r - 1)) / Real(4 * m_n * m_n);\n            Real tmp1 = ((2 * r - 1) * x * qrm1 - s * qrm2) / r;\n            Real tmp2 = ((2 * r - 1) * (qrm1 + x * qrm1p) - s * qrm2p) / r;\n            qrm2 = qrm1;\n            qrm1 = tmp1;\n            qrm2p = qrm1p;\n            qrm1p = tmp2;\n        }\n        return qrm1p;\n    }\n\n  private:\n    std::size_t m_n;\n    std::size_t m_r;\n    Real m_x;\n    Real m_qrm2;\n    Real m_qrm1;\n    Real m_qrm2p;\n    Real m_qrm1p;\n    Real m_qrm2pp;\n    Real m_qrm1pp;\n};\n\ntemplate <class Real>\nstd::vector<Real> interior_velocity_filter(std::size_t n, std::size_t p) {\n    auto dlp = discrete_legendre<Real>(n, 0);\n    std::vector<Real> coeffs(p+1);\n    coeffs[1] = 1/dlp.norm_sq(1);\n    for (std::size_t l = 3; l < p + 1; l += 2)\n    {\n        dlp.next_prime();\n        coeffs[l] = dlp.next_prime()/ dlp.norm_sq(l);\n    }\n\n    // We could make the filter length n, as f[0] = 0,\n    // but that'd make the indexing awkward when applying the filter.\n    std::vector<Real> f(n + 1);\n    // This value should never be read, but this is the correct value *if it is read*.\n    // Hmm, should it be a nan then? I'm not gonna agonize.\n    f[0] = 0;\n    for (std::size_t j = 1; j < f.size(); ++j)\n    {\n        Real arg = Real(j) / Real(n);\n        dlp = discrete_legendre<Real>(n, arg);\n        f[j] = coeffs[1]*arg;\n        for (std::size_t l = 3; l <= p; l += 2)\n        {\n            dlp.next();\n            f[j] += coeffs[l]*dlp.next();\n        }\n        f[j] /= (n * n);\n    }\n    return f;\n}\n\ntemplate <class Real>\nstd::vector<Real> boundary_velocity_filter(std::size_t n, std::size_t p, int64_t s)\n{\n    std::vector<Real> coeffs(p+1, std::numeric_limits<Real>::quiet_NaN());\n    Real sn = Real(s) / Real(n);\n    auto dlp = discrete_legendre<Real>(n, sn);\n    coeffs[0] = 0;\n    coeffs[1] = 1/dlp.norm_sq(1);\n    for (std::size_t l = 2; l < p + 1; ++l)\n    {\n        // Calculation of the norms is common to all filters,\n        // so it seems like an obvious optimization target.\n        // I tried this: The spent in computing the norms time is not negligible,\n        // but still a small fraction of the total compute time.\n        // Hence I'm not refactoring out these norm calculations.\n        coeffs[l] = dlp.next_prime()/ dlp.norm_sq(l);\n    }\n\n    std::vector<Real> f(2*n + 1);\n    for (std::size_t k = 0; k < f.size(); ++k)\n    {\n        Real j = Real(k) - Real(n);\n        Real arg = j/Real(n);\n        dlp = discrete_legendre<Real>(n, arg);\n        f[k] = coeffs[1]*arg;\n        for (std::size_t l = 2; l <= p; ++l)\n        {\n            f[k] += coeffs[l]*dlp.next();\n        }\n        f[k] /= (n * n);\n    }\n    return f;\n}\n\ntemplate <class Real>\nstd::vector<Real> acceleration_filter(std::size_t n, std::size_t p, int64_t s)\n{\n    BOOST_MATH_ASSERT_MSG(p <= 2*n, \"Approximation order must be <= 2*n\");\n    BOOST_MATH_ASSERT_MSG(p > 2, \"Approximation order must be > 2\");\n\n    std::vector<Real> coeffs(p+1, std::numeric_limits<Real>::quiet_NaN());\n    Real sn = Real(s) / Real(n);\n    auto dlp = discrete_legendre<Real>(n, sn);\n    coeffs[0] = 0;\n    coeffs[1] = 0;\n    for (std::size_t l = 2; l < p + 1; ++l)\n    {\n        coeffs[l] = dlp.next_dbl_prime()/ dlp.norm_sq(l);\n    }\n\n    std::vector<Real> f(2*n + 1, 0);\n    for (std::size_t k = 0; k < f.size(); ++k)\n    {\n        Real j = Real(k) - Real(n);\n        Real arg = j/Real(n);\n        dlp = discrete_legendre<Real>(n, arg);\n        for (std::size_t l = 2; l <= p; ++l)\n        {\n            f[k] += coeffs[l]*dlp.next();\n        }\n        f[k] /= (n * n * n);\n    }\n    return f;\n}\n\n\n} // namespace detail\n\ntemplate <typename Real, std::size_t order = 1>\nclass discrete_lanczos_derivative {\npublic:\n    discrete_lanczos_derivative(Real const & spacing,\n                                std::size_t n = 18,\n                                std::size_t approximation_order = 3)\n        : m_dt{spacing}\n    {\n        static_assert(!std::is_integral_v<Real>,\n                      \"Spacing must be a floating point type.\");\n        BOOST_MATH_ASSERT_MSG(spacing > 0,\n                         \"Spacing between samples must be > 0.\");\n\n        if constexpr (order == 1)\n        {\n            BOOST_MATH_ASSERT_MSG(approximation_order <= 2 * n,\n                             \"The approximation order must be <= 2n\");\n            BOOST_MATH_ASSERT_MSG(approximation_order >= 2,\n                             \"The approximation order must be >= 2\");\n\n            if constexpr (std::is_same_v<Real, float> || std::is_same_v<Real, double>)\n            {\n                auto interior = detail::interior_velocity_filter<long double>(n, approximation_order);\n                m_f.resize(interior.size());\n                for (std::size_t j = 0; j < interior.size(); ++j)\n                {\n                    m_f[j] = static_cast<Real>(interior[j])/m_dt;\n                }\n            }\n            else\n            {\n                m_f = detail::interior_velocity_filter<Real>(n, approximation_order);\n                for (auto & x : m_f)\n                {\n                    x /= m_dt;\n                }\n            }\n\n            m_boundary_filters.resize(n);\n            // This for loop is a natural candidate for parallelization.\n            // But does it matter? Probably not.\n            for (std::size_t i = 0; i < n; ++i)\n            {\n                if constexpr (std::is_same_v<Real, float> || std::is_same_v<Real, double>)\n                {\n                    int64_t s = static_cast<int64_t>(i) - static_cast<int64_t>(n);\n                    auto bf = detail::boundary_velocity_filter<long double>(n, approximation_order, s);\n                    m_boundary_filters[i].resize(bf.size());\n                    for (std::size_t j = 0; j < bf.size(); ++j)\n                    {\n                        m_boundary_filters[i][j] = static_cast<Real>(bf[j])/m_dt;\n                    }\n                }\n                else\n                {\n                    int64_t s = static_cast<int64_t>(i) - static_cast<int64_t>(n);\n                    m_boundary_filters[i] = detail::boundary_velocity_filter<Real>(n, approximation_order, s);\n                    for (auto & bf : m_boundary_filters[i])\n                    {\n                        bf /= m_dt;\n                    }\n                }\n            }\n        }\n        else if constexpr (order == 2)\n        {\n            // High precision isn't warranted for small p; only for large p.\n            // (The computation appears stable for large n.)\n            // But given that the filters are reusable for many vectors,\n            // it's better to do a high precision computation and then cast back,\n            // since the resulting cost is a factor of 2, and the cost of the filters not working is hours of debugging.\n            if constexpr (std::is_same_v<Real, double> || std::is_same_v<Real, float>)\n            {\n                auto f = detail::acceleration_filter<long double>(n, approximation_order, 0);\n                m_f.resize(n+1);\n                for (std::size_t i = 0; i < m_f.size(); ++i)\n                {\n                    m_f[i] = static_cast<Real>(f[i+n])/(m_dt*m_dt);\n                }\n                m_boundary_filters.resize(n);\n                for (std::size_t i = 0; i < n; ++i)\n                {\n                    int64_t s = static_cast<int64_t>(i) - static_cast<int64_t>(n);\n                    auto bf = detail::acceleration_filter<long double>(n, approximation_order, s);\n                    m_boundary_filters[i].resize(bf.size());\n                    for (std::size_t j = 0; j < bf.size(); ++j)\n                    {\n                        m_boundary_filters[i][j] = static_cast<Real>(bf[j])/(m_dt*m_dt);\n                    }\n                }\n            }\n            else\n            {\n                // Given that the purpose is denoising, for higher precision calculations,\n                // the default precision should be fine.\n                auto f = detail::acceleration_filter<Real>(n, approximation_order, 0);\n                m_f.resize(n+1);\n                for (std::size_t i = 0; i < m_f.size(); ++i)\n                {\n                    m_f[i] = f[i+n]/(m_dt*m_dt);\n                }\n                m_boundary_filters.resize(n);\n                for (std::size_t i = 0; i < n; ++i)\n                {\n                    int64_t s = static_cast<int64_t>(i) - static_cast<int64_t>(n);\n                    m_boundary_filters[i] = detail::acceleration_filter<Real>(n, approximation_order, s);\n                    for (auto & bf : m_boundary_filters[i])\n                    {\n                        bf /= (m_dt*m_dt);\n                    }\n                }\n            }\n        }\n        else\n        {\n            BOOST_MATH_ASSERT_MSG(false, \"Derivatives of order 3 and higher are not implemented.\");\n        }\n    }\n\n    Real get_spacing() const\n    {\n        return m_dt;\n    }\n\n    template<class RandomAccessContainer>\n    Real operator()(RandomAccessContainer const & v, std::size_t i) const\n    {\n        static_assert(std::is_same_v<typename RandomAccessContainer::value_type, Real>,\n                      \"The type of the values in the vector provided does not match the type in the filters.\");\n\n        BOOST_MATH_ASSERT_MSG(std::size(v) >= m_boundary_filters[0].size(),\n            \"Vector must be at least as long as the filter length\");\n\n        if constexpr (order==1)\n        {\n            if (i >= m_f.size() - 1 && i <= std::size(v) - m_f.size())\n            {\n                // The filter has length >= 1:\n                Real dvdt = m_f[1] * (v[i + 1] - v[i - 1]);\n                for (std::size_t j = 2; j < m_f.size(); ++j)\n                {\n                    dvdt += m_f[j] * (v[i + j] - v[i - j]);\n                }\n                return dvdt;\n            }\n\n            // m_f.size() = N+1\n            if (i < m_f.size() - 1)\n            {\n                auto &bf = m_boundary_filters[i];\n                Real dvdt = bf[0]*v[0];\n                for (std::size_t j = 1; j < bf.size(); ++j)\n                {\n                    dvdt += bf[j] * v[j];\n                }\n                return dvdt;\n            }\n\n            if (i > std::size(v) - m_f.size() && i < std::size(v))\n            {\n                int k = std::size(v) - 1 - i;\n                auto &bf = m_boundary_filters[k];\n                Real dvdt = bf[0]*v[std::size(v)-1];\n                for (std::size_t j = 1; j < bf.size(); ++j)\n                {\n                    dvdt += bf[j] * v[std::size(v) - 1 - j];\n                }\n                return -dvdt;\n            }\n        }\n        else if constexpr (order==2)\n        {\n            if (i >= m_f.size() - 1 && i <= std::size(v) - m_f.size())\n            {\n                Real d2vdt2 = m_f[0]*v[i];\n                for (std::size_t j = 1; j < m_f.size(); ++j)\n                {\n                    d2vdt2 += m_f[j] * (v[i + j] + v[i - j]);\n                }\n                return d2vdt2;\n            }\n\n            // m_f.size() = N+1\n            if (i < m_f.size() - 1)\n            {\n                auto &bf = m_boundary_filters[i];\n                Real d2vdt2 = bf[0]*v[0];\n                for (std::size_t j = 1; j < bf.size(); ++j)\n                {\n                    d2vdt2 += bf[j] * v[j];\n                }\n                return d2vdt2;\n            }\n\n            if (i > std::size(v) - m_f.size() && i < std::size(v))\n            {\n                int k = std::size(v) - 1 - i;\n                auto &bf = m_boundary_filters[k];\n                Real d2vdt2 = bf[0] * v[std::size(v) - 1];\n                for (std::size_t j = 1; j < bf.size(); ++j)\n                {\n                    d2vdt2 += bf[j] * v[std::size(v) - 1 - j];\n                }\n                return d2vdt2;\n            }\n        }\n\n        // OOB access:\n        std::string msg = \"Out of bounds access in Lanczos derivative.\";\n        msg += \"Input vector has length \" + std::to_string(std::size(v)) + \", but user requested access at index \" + std::to_string(i) + \".\";\n        throw std::out_of_range(msg);\n        return std::numeric_limits<Real>::quiet_NaN();\n    }\n\n    template<class RandomAccessContainer>\n    void operator()(RandomAccessContainer const & v, RandomAccessContainer & w) const\n    {\n        static_assert(std::is_same_v<typename RandomAccessContainer::value_type, Real>,\n                      \"The type of the values in the vector provided does not match the type in the filters.\");\n        if (&w[0] == &v[0])\n        {\n            throw std::logic_error(\"This transform cannot be performed in-place.\");\n        }\n\n        if (std::size(v) < m_boundary_filters[0].size())\n        {\n            std::string msg = \"The input vector must be at least as long as the filter length. \";\n            msg += \"The input vector has length = \" + std::to_string(std::size(v)) + \", the filter has length \" + std::to_string(m_boundary_filters[0].size());\n            throw std::length_error(msg);\n        }\n\n        if (std::size(w) < std::size(v))\n        {\n            std::string msg = \"The output vector (containing the derivative) must be at least as long as the input vector.\";\n            msg += \"The output vector has length = \" + std::to_string(std::size(w)) + \", the input vector has length \" + std::to_string(std::size(v));\n            throw std::length_error(msg);\n        }\n\n        if constexpr (order==1)\n        {\n            for (std::size_t i = 0; i < m_f.size() - 1; ++i)\n            {\n                auto &bf = m_boundary_filters[i];\n                Real dvdt = bf[0] * v[0];\n                for (std::size_t j = 1; j < bf.size(); ++j)\n                {\n                    dvdt += bf[j] * v[j];\n                }\n                w[i] = dvdt;\n            }\n\n            for(std::size_t i = m_f.size() - 1; i <= std::size(v) - m_f.size(); ++i)\n            {\n                Real dvdt = m_f[1] * (v[i + 1] - v[i - 1]);\n                for (std::size_t j = 2; j < m_f.size(); ++j)\n                {\n                    dvdt += m_f[j] *(v[i + j] - v[i - j]);\n                }\n                w[i] = dvdt;\n            }\n\n\n            for(std::size_t i = std::size(v) - m_f.size() + 1; i < std::size(v); ++i)\n            {\n                int k = std::size(v) - 1 - i;\n                auto &f = m_boundary_filters[k];\n                Real dvdt = f[0] * v[std::size(v) - 1];;\n                for (std::size_t j = 1; j < f.size(); ++j)\n                {\n                    dvdt += f[j] * v[std::size(v) - 1 - j];\n                }\n                w[i] = -dvdt;\n            }\n        }\n        else if constexpr (order==2)\n        {\n            // m_f.size() = N+1\n            for (std::size_t i = 0; i < m_f.size() - 1; ++i)\n            {\n                auto &bf = m_boundary_filters[i];\n                Real d2vdt2 = 0;\n                for (std::size_t j = 0; j < bf.size(); ++j)\n                {\n                    d2vdt2 += bf[j] * v[j];\n                }\n                w[i] = d2vdt2;\n            }\n\n            for (std::size_t i = m_f.size() - 1; i <= std::size(v) - m_f.size(); ++i)\n            {\n                Real d2vdt2 = m_f[0]*v[i];\n                for (std::size_t j = 1; j < m_f.size(); ++j)\n                {\n                    d2vdt2 += m_f[j] * (v[i + j] + v[i - j]);\n                }\n                w[i] = d2vdt2;\n            }\n\n            for (std::size_t i = std::size(v) - m_f.size() + 1; i < std::size(v); ++i)\n            {\n                int k = std::size(v) - 1 - i;\n                auto &bf = m_boundary_filters[k];\n                Real d2vdt2 = bf[0] * v[std::size(v) - 1];\n                for (std::size_t j = 1; j < bf.size(); ++j)\n                {\n                    d2vdt2 += bf[j] * v[std::size(v) - 1 - j];\n                }\n                w[i] = d2vdt2;\n            }\n        }\n    }\n\n    template<class RandomAccessContainer>\n    RandomAccessContainer operator()(RandomAccessContainer const & v) const\n    {\n        RandomAccessContainer w(std::size(v));\n        this->operator()(v, w);\n        return w;\n    }\n\n\n    // Don't copy; too big.\n    discrete_lanczos_derivative( const discrete_lanczos_derivative & ) = delete;\n    discrete_lanczos_derivative& operator=(const discrete_lanczos_derivative&) = delete;\n\n    // Allow moves:\n    discrete_lanczos_derivative(discrete_lanczos_derivative&&) = default;\n    discrete_lanczos_derivative& operator=(discrete_lanczos_derivative&&) = default;\n\nprivate:\n    std::vector<Real> m_f;\n    std::vector<std::vector<Real>> m_boundary_filters;\n    Real m_dt;\n};\n\n} // namespaces\n#endif\n", "meta": {"hexsha": "4fc7954552d412377df37b4436482bf65f008923", "size": 20395, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/math/differentiation/lanczos_smoothing.hpp", "max_stars_repo_name": "oleg-alexandrov/math", "max_stars_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 233.0, "max_stars_repo_stars_event_min_datetime": "2015-01-12T19:26:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T09:21:47.000Z", "max_issues_repo_path": "include/boost/math/differentiation/lanczos_smoothing.hpp", "max_issues_repo_name": "oleg-alexandrov/math", "max_issues_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 626.0, "max_issues_repo_issues_event_min_datetime": "2015-02-05T18:12:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T13:19:18.000Z", "max_forks_repo_path": "include/boost/math/differentiation/lanczos_smoothing.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": 34.9828473413, "max_line_length": 159, "alphanum_fraction": 0.461387595, "num_tokens": 5730, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.6297746143530797, "lm_q1q2_score": 0.4994780007075923}}
{"text": "//\n// Created by Anshuman Mishra on 11/26/19.\n//\n\n#include \"headers/Policy.h\"\n#include <algorithm>\n#include <random>\n#include <functional>\n#include <boost/math/special_functions/beta.hpp>\n#include \"headers/MathUtils.h\"\n\nusing namespace std;\nusing namespace Eigen;\n\nPolicy::Policy (int numActions_, int stateTerms_, unsigned seed){\n//  cout << \"Initializing without theta\" << endl;\n//  cout << \"Theta before \" << theta.size() << endl;\n  // init theta\n  numActions = numActions_;\n  stateTerms = stateTerms_;\n  theta = MatrixXd(stateTerms, numActions);\n  //  unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();\n  gen = default_random_engine (seed);\n//  cout << \"Theta after \" << theta.size() << endl;\n}\n\nPolicy::Policy (VectorXd& theta_init, int numActions_, int stateTerms_, unsigned seed){\n  numActions = numActions_;\n  stateTerms = stateTerms_;\n//  cout << \"Initializing with theta \" << theta_init.size() << endl;\n//  cout << \"Theta before \" << theta.size() << endl;\n  theta = MatrixXd::Map(theta_init.data(),  stateTerms, numActions);\n//  cout << \"Theta after \" << theta.size() << endl;\n  gen = default_random_engine (seed);\n}\n\nPolicy::Policy(Policy pi, unsigned seed){\n  numActions = pi.getNumActions();\n  stateTerms = pi.getStateTerms();\n  theta = MatrixXd::Map(pi.getTheta().data(), stateTerms, numActions);\n  gen = default_random_engine (seed);\n}\n\nvoid Policy::setTheta(const VectorXd& newTheta) {\n//  cout << \"Setting theta \" << newTheta.size() << endl;\n//  cout << \"Theta before \" << theta.size() << endl;\n  theta = MatrixXd::Map(newTheta.data(), theta.rows(), theta.cols());\n//  cout << \"Theta after \" << theta.size() << endl;\n}\n\nVectorXd Policy::getTheta() const{\n  return VectorXd::Map(theta.data(), theta.size());\n}\n\nint Policy::getNumActions() const{\n  return numActions;\n}\n\nint Policy::getStateTerms() const{\n  return stateTerms;\n}\n\n// Softmax Action Selection with Linear Function Approximation\nint Policy::getAction (const VectorXd& phi){\n//  cout << \"Getting Action\" << endl;\n//  cout << phi.cols() << \"x\" << phi.rows() << \"dot\" << theta.rows() << \"x\" << theta.cols()  << endl;\n//  cout << \"Phi \" << phi.transpose() << endl;\n//  cout << \"Theta\\n \" << theta << endl;\n  VectorXd dot = phi.transpose()*theta;\n  VectorXd q = exp(dot.array() - dot.maxCoeff());\n//  cout << \"q \" << q << endl;\n\n  discrete_distribution<int> dist(q.data(), q.data() + q.rows() * q.cols());\n  int action = dist(gen);\n//  cout << \"Action:\" << action << endl;\n  return action;\n}\n\ndouble Policy::getActionProbability (const VectorXd& phi, int action) const {\n//  cout << \"Getting Action Probability\";\n//  cout << phi.cols() << \"x\" << phi.rows() << \"dot\" << theta.rows() << \"x\" << theta.cols()  << endl;\n//  cout << \"Phi \" << phi.transpose() << endl;\n//  cout << \"Theta\\n\" << theta << endl;\n  VectorXd dot = phi.transpose()*theta;\n//  cout << \"dot \" << dot.transpose() << endl;\n  VectorXd q = exp(dot.array() - dot.maxCoeff());\n\n  discrete_distribution<int> dist(q.data(), q.data() + q.rows() * q.cols());\n  double p = dist.probabilities()[action];\n  if (isnan(p))\n    p = 1.0;\n//  if (isnan(p)){\n//    cout << \"Action Probability is nan\" << endl;\n//    cout << \"phi: \" << phi.transpose() << endl;\n//    cout << \"Q: \" << q.transpose() << endl;\n//    cout << \"action: \" << action << endl;\n//    getchar();\n//  }\n//  cout << \"p=\" << p << endl;\n  return p;\n}", "meta": {"hexsha": "0501c8650e211ede44d62cbc76c4dac1e08d48c5", "size": 3366, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Project/Policy.cpp", "max_stars_repo_name": "anshuman1811/cs687-reinforcementlearning", "max_stars_repo_head_hexsha": "cf30cc0ab2b0e515cd4b643fc55c60cc5f38a481", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Project/Policy.cpp", "max_issues_repo_name": "anshuman1811/cs687-reinforcementlearning", "max_issues_repo_head_hexsha": "cf30cc0ab2b0e515cd4b643fc55c60cc5f38a481", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Project/Policy.cpp", "max_forks_repo_name": "anshuman1811/cs687-reinforcementlearning", "max_forks_repo_head_hexsha": "cf30cc0ab2b0e515cd4b643fc55c60cc5f38a481", "max_forks_repo_licenses": ["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.3267326733, "max_line_length": 101, "alphanum_fraction": 0.6256684492, "num_tokens": 905, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.49947800005913506}}
{"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_ILOG2_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_ILOG2_HPP_INCLUDED\n#include <boost/simd/detail/overload.hpp>\n\n#include <boost/simd/meta/hierarchy/simd.hpp>\n#include <boost/simd/function/bitwise_cast.hpp>\n#include <boost/simd/function/clz.hpp>\n#include <boost/simd/function/exponent.hpp>\n#include <boost/simd/function/minus.hpp>\n#include <boost/simd/function/dec.hpp>\n#include <boost/simd/function/splat.hpp>\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   BOOST_DISPATCH_OVERLOAD_IF(ilog2_\n                          , (typename A0, typename X)\n                          , (detail::is_native<X>)\n                          , bd::cpu_\n                          , bs::pack_<bd::floating_<A0>, X>\n                          )\n   {\n      using result = bd::as_integer_t<A0>;\n      BOOST_FORCEINLINE result operator()( const A0& a0) const BOOST_NOEXCEPT\n      {\n        return bs::exponent(a0);\n      }\n   };\n\n   BOOST_DISPATCH_OVERLOAD_IF(ilog2_\n                          , (typename A0, typename X)\n                          , (detail::is_native<X>)\n                          , bd::cpu_\n                          , bs::pack_<bd::arithmetic_<A0>, X>\n                          )\n   {\n      using result = bd::as_integer_t<A0>;\n      BOOST_FORCEINLINE result operator()( const A0& a0) const BOOST_NOEXCEPT\n      {\n        return saturated_(dec)(sizeof(bd::scalar_of_t<A0>)*8-bs::clz(bitwise_cast<result>(a0)));\n      }\n   };\n\n} } }\n\n\n#endif\n\n", "meta": {"hexsha": "a9806545bd47960b4811dc046fbdffbb8e77f432", "size": 2017, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/simd/function/ilog2.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/ilog2.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/ilog2.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.0655737705, "max_line_length": 100, "alphanum_fraction": 0.5493306891, "num_tokens": 440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.49947798903707796}}
{"text": "#ifdef MEX\n\n#include <mex.h>\n#include <igl/C_STR.h>\n#include <igl/matlab/mexErrMsgTxt.h>\n#undef assert\n#define assert( isOK ) ( (isOK) ? (void)0 : (void) mexErrMsgTxt(C_STR(__FILE__<<\":\"<<__LINE__<<\": failed assertion `\"<<#isOK<<\"'\"<<std::endl) ) )\n#endif\n#include <igl/matlab/MexStream.h>\n\n#include <igl/per_vertex_normals.h>\n#include <igl/parallel_for.h>\n#include <igl/signed_distance.h>\n#include <igl/per_edge_normals.h>\n#include <igl/matlab/validate_arg.h>\n#include <igl/per_face_normals.h>\n#include <igl/WindingNumberAABB.h>\n#include <igl/matlab/prepare_lhs.h>\n#include <igl/matlab/parse_rhs.h>\n#include <igl/C_STR.h>\n\n#include <Eigen/Core>\n#include <iostream>\n\nvoid parse_rhs(\n  const int nrhs, \n  const mxArray *prhs[], \n  Eigen::MatrixXd & P,\n  Eigen::MatrixXd & V,\n  Eigen::MatrixXi & F,\n  igl::SignedDistanceType & type)\n{\n  using namespace std;\n  using namespace igl;\n  using namespace igl::matlab;\n  using namespace Eigen;\n  mexErrMsgTxt(nrhs >= 3, \"The number of input arguments must be >=3.\");\n\n  const int dim = mxGetN(prhs[0]);\n\n\n  parse_rhs_double(prhs,P);\n  parse_rhs_double(prhs+1,V);\n  parse_rhs_index(prhs+2,F);\n\n  mexErrMsgTxt(P.cols()==3 || P.cols()==2,\"P must be #P by (3|2)\");\n  mexErrMsgTxt(V.cols()==3 || V.cols()==2,\"V must be #V by (3|2)\");\n  mexErrMsgTxt(V.cols()==P.cols(),\"dim(V) must be dim(P)\");\n  mexErrMsgTxt(F.cols()==V.cols(),\"F must be #F by dim(V)\");\n\n  type = SIGNED_DISTANCE_TYPE_PSEUDONORMAL;\n  {\n    int i = 3;\n    while(i<nrhs)\n    {\n      mexErrMsgTxt(mxIsChar(prhs[i]),\"Parameter names should be strings\");\n      // Cast to char\n      const char * name = mxArrayToString(prhs[i]);\n      if(strcmp(\"SignedDistanceType\",name) == 0)\n      {\n        validate_arg_char(i,nrhs,prhs,name);\n        const char * type_name = mxArrayToString(prhs[++i]);\n        if(strcmp(\"pseudonormal\",type_name)==0)\n        {\n          type = igl::SIGNED_DISTANCE_TYPE_PSEUDONORMAL;\n        }else if(strcmp(\"winding_number\",type_name)==0)\n        {\n          type = igl::SIGNED_DISTANCE_TYPE_WINDING_NUMBER;\n        }else\n        {\n          mexErrMsgTxt(false,C_STR(\"Unknown SignedDistanceType: \"<<type_name));\n        }\n      }else\n      {\n        mexErrMsgTxt(false,\"Unknown parameter\");\n      }\n      i++;\n    }\n  }\n}\n\n//void precompute(\n//  const Eigen::MatrixXd & V,\n//  const Eigen::MatrixXi & F,\n//  const igl::SignedDistanceType sign_type,\n//  State & state)\n//{\n//  using namespace igl;\n//  using namespace std;\n//  using namespace Eigen;\n\n  // This will remember the data structures for subsequent calls (without an\n  // calls in between with different (V,F) or type\n  static Eigen::MatrixXd g_V;\n  static Eigen::MatrixXi g_F;\n  static igl::SignedDistanceType g_sign_type = \n    igl::NUM_SIGNED_DISTANCE_TYPE;\n  static igl::AABB<Eigen::MatrixXd,3> g_tree;\n  static igl::WindingNumberAABB<\n    Eigen::RowVector3d,\n    Eigen::MatrixXd,\n    Eigen::MatrixXi> g_hier;\n  static Eigen::MatrixXd g_FN,g_VN,g_EN;\n  static Eigen::MatrixXi g_E;\n  static Eigen::VectorXi g_EMAP;\n\nvoid mexFunction(\n  int nlhs, mxArray *plhs[], \n  int nrhs, const mxArray *prhs[])\n{\n  using namespace std;\n  using namespace Eigen;\n  using namespace igl;\n  using namespace igl::matlab;\n\n  igl::matlab::MexStream mout;        \n  std::streambuf *outbuf = cout.rdbuf(&mout);\n  //mexPrintf(\"Compiled at %s on %s\\n\",__TIME__,__DATE__);\n\n  MatrixXd P,V,C,N;\n  MatrixXi F;\n  VectorXi I;\n  VectorXd S;\n  SignedDistanceType type;\n  parse_rhs(nrhs,prhs,P,V,F,type);\n\n  if(F.rows() > 0)\n  {\n    switch(V.cols())\n    {\n      case 2:\n      {\n        // Persistent data not supported for 2D\n        signed_distance(P,V,F,type,S,I,C,N);\n        break;\n      }\n      case 3:\n      {\n        if(g_sign_type != type || g_V != V || g_F != F)\n        {\n          g_V = V;\n          g_F = F;\n          g_sign_type = type;\n          // Clear the tree\n          g_tree.deinit();\n\n          // Prepare distance computation\n          g_tree.init(V,F);\n          switch(type)\n          {\n            default:\n              assert(false && \"Unknown SignedDistanceType\");\n            case SIGNED_DISTANCE_TYPE_DEFAULT:\n            case SIGNED_DISTANCE_TYPE_WINDING_NUMBER:\n              g_hier.set_mesh(V,F);\n              g_hier.grow();\n              break;\n            case SIGNED_DISTANCE_TYPE_PSEUDONORMAL:\n              // \"Signed Distance Computation Using the Angle Weighted Pseudonormal\"\n              // [B\u00e6rentzen & Aan\u00e6s 2005]\n              per_face_normals(V,F,g_FN);\n              per_vertex_normals(V,F,PER_VERTEX_NORMALS_WEIGHTING_TYPE_ANGLE,\n                g_FN,g_VN);\n              per_edge_normals(\n                V,F,PER_EDGE_NORMALS_WEIGHTING_TYPE_UNIFORM,\n                g_FN,g_EN,g_E,g_EMAP);\n              break;\n          }\n        }\n\n        N.resize(P.rows(),3);\n        S.resize(P.rows(),1);\n        I.resize(P.rows(),1);\n        C.resize(P.rows(),3);\n        //for(int p = 0;p<P.rows();p++)\n        igl::parallel_for(P.rows(),[&](const int p)\n        {\n          const Eigen::RowVector3d q(P(p,0),P(p,1),P(p,2));\n          double s,sqrd;\n          Eigen::RowVector3d c;\n          int i;\n          switch(type)\n          {\n            default:\n              assert(false && \"Unknown SignedDistanceType\");\n            case SIGNED_DISTANCE_TYPE_DEFAULT:\n            case SIGNED_DISTANCE_TYPE_WINDING_NUMBER:\n              signed_distance_winding_number(\n                g_tree,g_V,g_F,g_hier,q,s,sqrd,i,c);\n              break;\n            case SIGNED_DISTANCE_TYPE_PSEUDONORMAL:\n            {\n              RowVector3d n(0,0,0);\n              signed_distance_pseudonormal(\n                g_tree,g_V,g_F,g_FN,g_VN,g_EN,g_EMAP,\n                q,s,sqrd,i,c,n);\n              N.row(p) = n;\n              break;\n            }\n          }\n          I(p) = i;\n          S(p) = s*sqrt(sqrd);\n          C.row(p) = c;\n        },10000);\n        break;\n      }\n    }\n  }\n\n  switch(nlhs)\n  {\n    default:\n    {\n      mexErrMsgTxt(false,\"Too many output parameters.\");\n    }\n    case 4:\n    {\n      prepare_lhs_double(N,plhs+3);\n      // Fall through\n    }\n    case 3:\n    {\n      prepare_lhs_double(C,plhs+2);\n      // Fall through\n    }\n    case 2:\n    {\n      prepare_lhs_index(I,plhs+1);\n      // Fall through\n    }\n    case 1:\n    {\n      prepare_lhs_double(S,plhs+0);\n      // Fall through\n    }\n    case 0: break;\n  }\n\n  // Restore the std stream buffer Important!\n  std::cout.rdbuf(outbuf);\n}\n\n\n\n", "meta": {"hexsha": "9c3aaf194f54992c31656abc784d994f850f1246", "size": 6396, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Geometry_Processing_Toolbox/src/cppmex/signed_distance.cpp", "max_stars_repo_name": "sidgairo18/SCILAB_MEX_TOOLBOX", "max_stars_repo_head_hexsha": "fc679f6d226c03b992b632823a5e57abea05cefa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Geometry_Processing_Toolbox/src/cppmex/signed_distance.cpp", "max_issues_repo_name": "sidgairo18/SCILAB_MEX_TOOLBOX", "max_issues_repo_head_hexsha": "fc679f6d226c03b992b632823a5e57abea05cefa", "max_issues_repo_licenses": ["MIT"], "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_Processing_Toolbox/src/cppmex/signed_distance.cpp", "max_forks_repo_name": "sidgairo18/SCILAB_MEX_TOOLBOX", "max_forks_repo_head_hexsha": "fc679f6d226c03b992b632823a5e57abea05cefa", "max_forks_repo_licenses": ["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.106122449, "max_line_length": 145, "alphanum_fraction": 0.5798936836, "num_tokens": 1748, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.49947798903707796}}
{"text": "/**\n * Conversion routines. Convert from coordinate type to coordinate type\n * via from_type foo = converter<to_type>()(from_type bar)\n *\n * Copyright 2013 Bruce Ide\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 \"coordinates.hpp\"\n#include <Eigen/Core>\n#include <type_traits>\n\n#ifndef _HPP_CONVERTS\n#define _HPP_CONVERTS\n\nnamespace fr {\n\n  namespace coordinates {\n\n    template <typename convert_to>\n    struct converter {\n\n    };\n\n    /***************************************************************\n     * Put convert to lat_long bits here\n     */\n\n    template <>\n    struct converter<lat_long> {\n     \n      // Converting from lat_long to lat_long is kind of odd, but I'll\n      // cover the case anyway\n      template <typename convert_from>\n      typename std::enable_if<std::is_same<convert_from,lat_long>::value,lat_long>::type\n\toperator()(const convert_from &c)\n      {\n\treturn c;\n      }\n\n      // ECEF to Latlong\n      template <typename convert_from>\n      typename std::enable_if<std::is_same<convert_from,ecef>::value,lat_long>::type \n      operator()(const convert_from &xyz, const ellipsoid_parameters &e = WGS84_ELLIPSOID, double tolerance = 0.0000000001 )\n      {\n\tdouble diff = 2 * tolerance;\n\tdouble t = e.ee * xyz.get_z();\n\tdouble n = 0.0;\n\tdouble nph = 0.0;\n\tdouble sinPhi = 0.0;\n\tdouble lat;\n\tdouble longitude;\n\tdouble alt;\n\n\tlongitude = atan2(xyz.get_y(), xyz.get_x()) * 180 / fr::constants::pi;\n\twhile(diff > tolerance) {\n\t  double zT = xyz.get_z() + t;\n\t  nph = sqrt(pow(xyz.get_x(), 2) + pow(xyz.get_y(), 2) + pow(zT, 2));\n\t  sinPhi = zT / nph;\n\t  n = e.ae / sqrt(1 - e.ee * sinPhi * sinPhi);\n\t  double told = t;\n\t  t = n * e.ee * sinPhi;\n\t  diff = fabs(t - told);\n\t}\n\t\n\tlat = asin(sinPhi) * 180 / fr::constants::pi;\n\talt = nph - n;\n\tlat_long retval(lat, longitude, alt);\n\treturn retval;\n      }\n\n      // ecef_vel to lat_long (Loses velocity information)\n      \n      template <typename convert_from>\n      typename std::enable_if<std::is_same<convert_from,ecef_vel>::value,lat_long>::type\n      operator()(const convert_from &c, const ellipsoid_parameters &e = WGS84_ELLIPSOID)\n      {\n\tecef interim = converter<ecef>()(c);\n\tlat_long retval = converter<lat_long>()(interim, e);\n\treturn retval;\n      }\n\n      // tod_eci_vel to latlong (Loses velocity information)\n      template <typename convert_from>\n      typename std::enable_if<std::is_same<convert_from,tod_eci_vel>::value,lat_long>::type\n      operator()(const convert_from &c, const double &t, const ellipsoid_parameters e = WGS84_ELLIPSOID)\n      {\n\t// Convert from tod_eci to ecef_vel\n\tecef_vel interim = converter<ecef_vel>()(c,t);\n\t// Then use the function before this one to convert to lat/long\n\tlat_long retval = converter<lat_long>()(interim, e);\n\treturn retval;\n      }\n      \n    };\n\n    /*********************************************************\n     * Put convert to ECEF bits here\n     */\n\n    template <>\n    struct converter<ecef> {\n      \n      // ECEF to ECEF conversion. \n      template <typename convert_from>\n      typename std::enable_if<std::is_same<convert_from,ecef>::value,ecef>::type\n      operator()(const convert_from &c)\n      {\n\treturn c;\n      }\n\n      // latlong to ecef\n      template <typename convert_from>\n      typename std::enable_if<std::is_same<convert_from,lat_long>::value,ecef>::type\n      operator()(const convert_from &c, const ellipsoid_parameters &e = WGS84_ELLIPSOID)\n      {\n\tdouble x,y,z;\n\tconst double &pi = fr::constants::pi;\n\tdouble slat = sin(c.get_lat() * pi / 180);\n\tdouble clat = cos(c.get_lat() * pi / 180);\n\tdouble slon = sin(c.get_long() * pi / 180);\n\tdouble clon = cos(c.get_long() * pi / 180);\n\tdouble n = e.ae / sqrt(1.0 - e.ee * pow(slat, 2));\n\tx = (n + c.get_alt()) * clat * clon;\n\ty = (n + c.get_alt()) * clat * slon;\n\tz = (n * (1.0 - e.ee) + c.get_alt()) * slat;\n\tecef retval(x,y,z);\n\treturn retval;\n      }\n\n      // ecef_vel to ecef (loses velocity information)\n      template <typename convert_from>\n      typename std::enable_if<std::is_same<convert_from,ecef_vel>::value,ecef>::type\n      operator()(const convert_from &c)\n      {\n\tecef retval(c.get_x(), c.get_y(), c.get_z());\n\treturn retval;\n      }\n\n      // tod_eci to ecef (Requires time coordinate was measured)\n      template <typename convert_from>\n      typename std::enable_if<std::is_same<convert_from,tod_eci>::value,ecef>::type\n      operator()(const convert_from &c, const double &at_time)\n      {\n\teci_to_ecef conversion_matrix(at_time);\n\tEigen::Vector3d c_vec = c.get_xyz();\n\tEigen::Matrix3d c_mat = conversion_matrix.get();\n\tEigen::Vector3d interim = c_mat * c_vec;\n\tecef retval(interim(0), interim(1), interim(2));\n\treturn retval;\n      }\n      \n    };\n\n\n    /**********************************************************\n     * Put tod_eci stuff here\n     */\n\n    template<>\n    struct converter<tod_eci> {\n      \n      // ECI to ECI conversion\n\n      template <typename convert_from>\n      typename std::enable_if<std::is_same<convert_from,tod_eci>::value,tod_eci>::type\n      operator()(const convert_from &c)\n      {\n\treturn c;\n      }\n\n      // ecef to tod_eci (Requires time coordinate was measured)\n      template <typename convert_from>\n      typename std::enable_if<std::is_same<convert_from,ecef>::value,tod_eci>::type\n      operator()(const convert_from &c, const double &time_at)\n      {\n\tecef_to_eci conversion_matrix(time_at);\n\tEigen::Vector3d c_vec = c.get_xyz();\n\tEigen::Matrix3d c_mat = conversion_matrix.get();\n\tEigen::Vector3d interim = c_mat * c_vec;\n\ttod_eci retval(interim(0), interim(1), interim(2));\n\treturn retval;\n      }\n\n    };\n\n    /***************************************************************\n     * Put ecef_vel stuff here\n     */\n\n    template<>\n    struct converter<ecef_vel> {\n      // ecef_vel to ecef_vel conversion\n      template <typename convert_from>\n      typename std::enable_if<std::is_same<convert_from,ecef_vel>::value,ecef_vel>::type\n      operator()(const convert_from &c)\n      {\n\treturn c;\n      }\n\n      // tod_eci_vel to ecef_vel (requires time component)\n      template <typename convert_from>\n      typename std::enable_if<std::is_same<convert_from,tod_eci_vel>::value,ecef_vel>::type\n      operator()(const convert_from &c, const double &time_at)\n      {\n\tEigen::Matrix<double,6,1> vec = c.get_vector();\n\teci_to_ecef cm(time_at);\n\tEigen::Matrix<double,6,6> c_mat = cm.get_xyz_vel();\n\tEigen::Matrix<double,6,1> interim = c_mat * vec;\n\tecef_vel retval(interim(0), interim(1), interim(2), interim(3), interim(4), interim(5));\n\treturn retval;\n      }      \n\n    };\n\n    /********************************************************************\n     * Put tod_eci_vel stuff here\n     */\n\n    template<>\n    struct converter<tod_eci_vel> {\n      \n      // From tod_eci_vel to tod_eci_vel\n      template <typename convert_from>\n      typename std::enable_if<std::is_same<convert_from,tod_eci_vel>::value,tod_eci_vel>::type\n      operator()(const convert_from &c)\n      {\n\treturn c;\n      }\n\n      // from ecef_vel to tod_eci_vel\n      template <typename convert_from>\n      typename std::enable_if<std::is_same<convert_from,ecef_vel>::value,tod_eci_vel>::type\n      operator()(const convert_from &c, const double &t)\n      {\n\tecef_to_eci cm(t);\n\tEigen::Matrix<double,6,1> vec = c.get_vector();\n\tEigen::Matrix<double,6,6> c_mat = cm.get_xyz_vel();\n\tEigen::Matrix<double,6,1> interim = c_mat * vec;\n\ttod_eci_vel retval(interim(0), interim(1), interim(2), interim(3), interim(4), interim(5));\n\treturn retval;\t\t\t   \n      }\n\n    };\n    \n  }\n\n}\n\n#endif\n", "meta": {"hexsha": "15c56101b788ada20faed677a07fe6d4d83f30a5", "size": 8054, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "converts.hpp", "max_stars_repo_name": "FlyingRhenquest/coordinates", "max_stars_repo_head_hexsha": "b6558b7e49e9927b4867456f4ce9fd81ec8bab81", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "converts.hpp", "max_issues_repo_name": "FlyingRhenquest/coordinates", "max_issues_repo_head_hexsha": "b6558b7e49e9927b4867456f4ce9fd81ec8bab81", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-03-30T12:28:44.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-10T06:36:53.000Z", "max_forks_repo_path": "converts.hpp", "max_forks_repo_name": "FlyingRhenquest/coordinates", "max_forks_repo_head_hexsha": "b6558b7e49e9927b4867456f4ce9fd81ec8bab81", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-02-08T16:17:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-14T14:48:59.000Z", "avg_line_length": 30.6235741445, "max_line_length": 124, "alphanum_fraction": 0.6295008691, "num_tokens": 2124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059414036511, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.49947798287759204}}
{"text": "\n#include <Eigen/Dense>\n#include <cmath>\n#include <iostream>\n\n#include \"rlbot/bot.h\"\n#include \"rlbot/rlbot_generated.h\"\n#include \"rlbot/scopedrenderer.h\"\n\n#include \"util.h\"\n\n\n\n\nusing namespace Eigen;\n\n\n\nnamespace util {\n\n\tconst float M_PI = 3.14159265;\n\n\tVector3f convert(const rlbot::flat::Vector3& vec) {\n\t\treturn { vec.x(), vec.y(), vec.z() };\n\t}\n\n\tVector3f convert(const rlbot::flat::Rotator& vec) {\n\t\t\n\t\treturn { vec.pitch(), vec.yaw(), vec.roll() };\n\t}\n\n\trlbot::flat::Vector3 convert(const Vector3f& vec) {\n\t\treturn rlbot::flat::Vector3{ vec[0], vec[1], vec[2] };\n\t}\n\n\tPhysics::Physics(const rlbot::flat::Physics& phys) :\n\t\tlocation(convert(*phys.location())),\n\t\tvelocity(convert(*phys.velocity())),\n\t\trotation(convert(*phys.rotation())),\n\t\tangularVelocity(convert(*phys.angularVelocity())) {}\n\n\n\tPhysics::Physics(const BallPhysics& bp) :\n\t\tlocation(bp.location),\n\t\tvelocity(bp.velocity),\n\t\trotation(bp.rotation),\n\t\tangularVelocity(bp.angularVelocity) {}\n\n\t\n\n\tBallPhysics::BallPhysics(const rlbot::flat::Physics& phys) :\n\t\tlocation(convert(*phys.location())),\n\t\tvelocity(convert(*phys.velocity())),\n\t\trotation(Vector3f::Zero()),\n\t\tangularVelocity(convert(*phys.angularVelocity())) {}\n\n\n\tVector3f Physics::forward() const {\n\n\t\tfloat\tsp = sin(rotation.pitch),\n\t\t\t\tcp = cos(rotation.pitch),\n\t\t\t\tsr = sin(rotation.roll),\n\t\t\t\tcr = cos(rotation.roll),\n\t\t\t\tsy = sin(rotation.yaw),\n\t\t\t\tcy = cos(rotation.yaw);\n\n\n\t\treturn { cp * cy, cp * sy, sp };\n\t}\n\n\tVector3f Physics::right() const {\n\t\t//pitch roll yaw\n\t\tfloat\tsp = sin(rotation.pitch),\n\t\t\t\tcp = cos(rotation.pitch),\n\t\t\t\tsr = sin(rotation.roll),\n\t\t\t\tcr = cos(rotation.roll),\n\t\t\t\tsy = sin(rotation.yaw),\n\t\t\t\tcy = cos(rotation.yaw);\n\n\n\t\treturn { cy * sp * sr - cr * sy, sy * sp * sr + cr * cy, -cp * sr };\n\n\t}\n\n\tVector3f Physics::up() const {\n\n\t\tfloat\tsp = sin(rotation.pitch),\n\t\t\t\tcp = cos(rotation.pitch),\n\t\t\t\tsr = sin(rotation.roll),\n\t\t\t\tcr = cos(rotation.roll),\n\t\t\t\tsy = sin(rotation.yaw),\n\t\t\t\tcy = cos(rotation.yaw);\n\n\t\treturn { -cr * cy * sp - sr * sy, -cr * sy * sp + sr * cy, cp * cr };\n\t}\n\n\tRotation::operator Vector3f() const {\n\t\treturn Vector3f(pitch, yaw, roll);\n\t}\n\n\tRotation::Rotation(const Vector3f& rot) :\n\t\tpitch(rot[0]),\n\t\tyaw(rot[1]),\n\t\troll(rot[2]) {\n\t}\n\n\tRotation::Rotation(const rlbot::flat::Rotator& rot) :\n\t\tpitch(rot.pitch()),\n\t\tyaw(rot.yaw()),\n\t\troll(rot.roll()) {}\n\t\t\n\n\tScoreInfo::ScoreInfo(const rlbot::flat::ScoreInfo& inf) :\n\t\tscore(inf.score()),\n\t\tgoals(inf.goals()),\n\t\townGoals(inf.ownGoals()),\n\t\tassists(inf.assists()),\n\t\tsaves(inf.saves()),\n\t\tshots(inf.shots()),\n\t\tdemolitions(inf.demolitions()) {}\n\n\tBoxShape::BoxShape(const rlbot::flat::BoxShape& box) :\n\t\tlength(box.length()),\n\t\twidth(box.width()),\n\t\theight(box.height()) {}\n\n\tCar::Car(const rlbot::flat::PlayerInfo& info) :\n\t\tphysics(*info.physics()),\n\t\tscoreInfo(*info.scoreInfo()),\n\t\tisDemolished(info.isDemolished()),\n\t\thasWheelContact(info.hasWheelContact()),\n\t\tisSupersonic(info.isSupersonic()),\n\t\tisBot(info.isBot()),\n\t\tjumped(info.jumped()),\n\t\tdoubleJumped(info.doubleJumped()),\n\t\tname((*info.name()).str()),\n\t\tteam(info.team()),\n\t\tboost(info.boost()),\n\t\thitbox(*info.hitbox()),\n\t\thitboxOffset(convert(*info.hitboxOffset())) {\n\t}\n\n\tTouch::Touch(const rlbot::flat::Touch& t) :\n\t\tgameSeconds(t.gameSeconds()),\n\t\tlocation(convert(*t.location())),\n\t\tnormal(convert(*t.normal())),\n\t\tteam(t.team()),\n\t\tplayerIndex(t.playerIndex()) {}\n\n\tDropShotBallInfo::DropShotBallInfo(const rlbot::flat::DropShotBallInfo& drop) :\n\t\tabsorbedForce(drop.absorbedForce()),\n\t\tdamageIndex(drop.damageIndex()),\n\t\tforceAccumRecent(drop.forceAccumRecent()) {}\n\n\tCollisionShape::CollisionShape(rlbot::flat::CollisionShape coll) : type(0) {} //TODO FIX TYPE\n\n\tBall::Ball(const rlbot::flat::BallInfo& ball) :\n\t\tphysics(*ball.physics()),\n\t\tlatestTouch(*ball.latestTouch()),\n\t\tdropShotInfo(*ball.dropShotInfo()),\n\t\tshape_type(ball.shape_type()) {}\n\n\tPredictionSlice::PredictionSlice(const rlbot::flat::PredictionSlice* slice) :\n\t\tgameSeconds(slice->gameSeconds()),\n\t\tphysics(*slice->physics()) {}\n\n\tBallPrediction::BallPrediction(const rlbot::flat::BallPrediction& bp){\n\t\tint max = bp.slices()->size();\n\t\tfor (int i = 0; i < max; ++i) {\n\t\t\tpredictionSlices.push_back(bp.slices()->Get(i));\n\n\t\t}\n\t}\n\n\n\tVector3f Car::other_goal() const{\n\t\tfloat t = team == 1 ? 1 : -1;\n\t\treturn Vector3f{ 0, -5120 * t, 92.75 };\n\t}\n\n\tVector3f Car::own_goal() const{\n\t\tfloat t = team == 1 ? 1 : -1;\n\t\treturn Vector3f{ 0,  5120 * t, 92.75 };\n\t}\n\n\t\n\n\tVector3f to_local(Car c, Vector3f target) {\n\n\t\t//TODO MAKE ACTUAL MATRIX IMPLENTATION INSTEAD OF WHATEVER THIS IS\n\n\t\t\n\t\tVector3f local = {\n\t\t\t(target - c.physics.location).dot(c.physics.forward()),\n\t\t\t(target - c.physics.location).dot(c.physics.right()),\n\t\t\t(target - c.physics.location).dot(c.physics.up())\n\t\t};\n\n\t\t\n\t\treturn local;\n\t}\n\n\ttemplate<typename T>\n\tT map(T value, T old_min, T old_max, T new_min, T new_max) {\n\t\treturn (value - old_min) * (new_max - new_min) / (old_max - old_min) + new_min;\n\t}\n\n\ttemplate<typename T>\n\tT clamp(T value, T min, T max) {\n\t\tif (value < min) return min;\n\t\tif (value > max) return max;\n\t\treturn value;\n\t}\n\n\trlbot::Controller optimalGroundControl(const Car& car, const std::vector<Vector3f>& path) {\n\n\t\tbool debug = 1;\n\n\t\trlbot::Controller controller{ 0 };\n\n\t\t//take average of first 20% of the path (10)\n\t\tVector3f aim = { 0, 0, 0 };\n\t\tint len = std::min((int)path.size(), util::NUM_POINTS/5);\n\t\tfor (auto i = 0; i < len; ++i) aim += path[i];\n\t\taim /= len;\n\n\t\t//aim = path[path.size() / 2];\n\n\t\t//aim = path[0];\n\n\t\trlbot::ScopedRenderer renderer(\"OPTIMAL GROUND CONTROL \" + std::to_string(car.team));\n\n\t\t//Vector3f local = to_local(car, aim);\n\n\t\tfloat angle = atan2(aim.y() - car.physics.location.y(), \n\t\t\t\t\t\t\taim.x() - car.physics.location.x());\n\n\n\t\tangle -= car.physics.rotation.yaw;\n\n\t\n\n\t\tif (angle < -M_PI) angle += 2 * M_PI;\n\t\tif (angle > M_PI) angle -= 2 * M_PI;\n\n\t\tfloat steer = angle/M_PI;\n\n\t\tsteer *= 10;\n\t\tsteer = clamp<float>(steer, -1, 1);\n\n\t\t//steer = steer > 0 ? 1 : -1;\n\t\t//steer = clamp<float>(steer, -1, 1);\n\n\t\tif (debug && car.team == 0) {\n\t\t\trenderer.DrawRect3D(rlbot::Color::black, convert(aim),\n\t\t\t\t20, 20, true, true);\n\t\t}\n\n\n\t\t//if steer is way too big, slow down\n\t\t\n\t\t//bool is_going_forward = ( car.physics.forward().dot(car.physics.velocity) > 0);\n\t\t/*\n\t\tif (is_going_forward && path[path.size() -1].z() > 400) {\n\t\t\tcontroller.throttle = 1 - 2 * std::abs(steer);\n\t\t}\n\t\telse {\n\t\t\tcontroller.throttle = 1;\n\t\t}*/\n\n\t\tcontroller.throttle = clamp<float>(1.3 - std::abs(steer), 0, 1);\n\n\t\tif (steer > 0.05) steer = 1;\n\t\tif (steer < -0.05) steer = -1;\n\n\t\tcontroller.steer = steer;\n\n\t\t\n\n\t\tif (std::abs(steer) < 0.05 && car.hasWheelContact) controller.boost = 1;\n\n\n\t\t//if car is stuck\n\t\t\n\n\t\tVector3f origin = { 0, 0, 92.75 };\n\n\t\t// If ball is at center(kickoff)\n\t\tif ((path[path.size() - 1] - origin).norm() < 5) {\n\t\t\tcontroller.boost = 1;\n\t\t\tcontroller.steer = controller.steer > 0 ? 1 : -1;\n\t\t}//else if (car.physics.velocity.norm() < 5) controller.jump = 1;\n\n\n\t\t//jump if car is close to ball\n\t\tif ((path[path.size() - 1] - path[0]).norm() < 200 && car.hasWheelContact && path[path.size() - 1].z() < 200 && std::abs(controller.steer) < 0.1 ) {\n\t\t\tcontroller.jump = 1;\n\t\t}\n\n\t\t// If car is in the air\n\t\tif (!car.hasWheelContact) {\n\t\t\tif ((path[path.size() - 1] - path[0]).norm() < 200) {\n\t\t\t\tcontroller.pitch = 1;\n\t\t\t\t\n\t\t\t\tcontroller.jump = 1;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tcontroller.pitch = clamp<float>(-2*car.physics.rotation.pitch, -1, 1);\n\t\t\t\tcontroller.yaw = clamp<float>(2*controller.steer, -1, 1);\n\t\t\t\tcontroller.roll = clamp<float>(-2*car.physics.rotation.roll, -1, 1);\n\t\t\t}\n\t\t}\n\n\t\t//if target is in the air slow down\n\t\tVector3f target = path[path.size() - 1];\n\t\ttarget.z() = 0;\n\n\t\tVector3f now = car.physics.location;\n\t\tnow.z() = 0;\n\n\t\tfloat groundDist = (target - now).norm();\n\n\t\t//if (path[path.size() - 1].z() > 300 && groundDist < 500 && std::abs(controller.steer) < 0.1) \n\t\t\t//controller.throttle = -1 * is_going_forward;\n\n\n\t\tif (debug && car.team == 0) {\n\t\t\trenderer.DrawString2D(\t\"boost: \" + std::to_string(controller.boost) + \"\\n\" +\n\t\t\t\t\t\t\t\t\t\"handbrake: \" + std::to_string(controller.handbrake) + \"\\n\" +\n\t\t\t\t\t\t\t\t\t\"jump: \" + std::to_string(controller.jump) + \"\\n\" +\n\t\t\t\t\t\t\t\t\t\"steer: \" + std::to_string(controller.steer) + \"\\n\" +\n\t\t\t\t\t\t\t\t\t\"throttle: \" + std::to_string(controller.throttle) + \"\\n\" +\n\t\t\t\t\t\t\t\t\t\"pitch: \" + std::to_string(controller.pitch) + \"\\n\" +\n\t\t\t\t\t\t\t\t\t\"roll: \" + std::to_string(controller.roll) + \"\\n\" +\n\t\t\t\t\t\t\t\t\t\"yaw: \" + std::to_string(controller.yaw) + \"\\n\",\n\t\t\t\t\t\t\t\t\trlbot::Color::green,\n\t\t\t\t\t\t\t\t\trlbot::flat::Vector3{ 10, 200, 0 },\n\t\t\t\t\t\t\t\t\t2, 2);\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\n\t\t}\n\n\t\treturn controller;\n\n\t}\n\n\n}//namespace util", "meta": {"hexsha": "1f26204b1a4bcdf60cc123a9973ae8893169294e", "size": 8636, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "util/util.cpp", "max_stars_repo_name": "steinraf/badbotcpp", "max_stars_repo_head_hexsha": "6b517bd0c9ce1f1b717dbfdd790e627434259219", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-09T23:13:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-09T23:13:03.000Z", "max_issues_repo_path": "util/util.cpp", "max_issues_repo_name": "steinraf/badbotcpp", "max_issues_repo_head_hexsha": "6b517bd0c9ce1f1b717dbfdd790e627434259219", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "util/util.cpp", "max_forks_repo_name": "steinraf/badbotcpp", "max_forks_repo_head_hexsha": "6b517bd0c9ce1f1b717dbfdd790e627434259219", "max_forks_repo_licenses": ["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.816091954, "max_line_length": 150, "alphanum_fraction": 0.6218156554, "num_tokens": 2684, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4994705318870042}}
{"text": "#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <complex>\n#include <tuple>\n#include <algorithm>\n#include <boost/range/iterator_range.hpp>\n\n#include \"common.hpp\"\n#include \"fft.hpp\"\n#include \"spectrum_image.hpp\"\n#include \"segment_envelope.hpp\"\n\nspectrum_image::spectrum_image(\n  const window_list_t &window,\n  const std::vector< int16_t > &audio,\n  int x_,\n  uint32_t sample_rate_,\n  uint32_t resolution_,\n  uint32_t scale_,\n  int weight,\n  unsigned int interval\n) : x( x_ ), resolution( resolution_ ), scale( scale_ ), sample_rate( sample_rate_ ) {\n  a = powf( 2.f, float( scale ) + weight );\n  b = float( interval ) * float( scale );\n  const auto converted = fftref( window, audio, resolution, a, b, x );\n  pixels_begin = converted.second.get();\n  pixels = converted.second;\n  envelope = std::move( converted.first );\n  const auto delay_end = std::find_if( envelope.begin(), envelope.end(), []( float v ) { return v != 0.f; } );\n  const auto delay_size = std::distance( envelope.begin(), delay_end );\n  pixels_begin += delay_size * x;\n  envelope.erase( envelope.begin(), delay_end );\n  y = envelope.size();\n  const auto tail_blank_end = std::find_if( envelope.rbegin(), envelope.rend(), []( float v ) { return v != 0.f; } );\n  const auto tail_blank_size = std::distance( envelope.rbegin(), tail_blank_end );\n  envelope.resize( envelope.size() - tail_blank_size );\n  y = envelope.size();\n  std::tie( delay, attack, release ) = segment_envelope( envelope, a, b );\n  delay_time = ( a * delay * delay + b * delay ) * tinyfm3::delta;\n  attack_time = ( a * attack * attack + b * attack ) * tinyfm3::delta;\n  release_time = ( a * release * release + b * release ) * tinyfm3::delta;\n  total_time = ( a * envelope.size() * envelope.size() + b * envelope.size() ) * tinyfm3::delta;\n  std::cout << __FILE__ << \" \" << __LINE__ << \" \" << delay_time << \" \" << attack_time << \" \" << release_time << \" \" << total_time << std::endl;\n}\nfloat get_distance(\n  const spectrum_image &ref,\n  const window_list_t &window,\n  const std::vector< int16_t > &audio\n) {\n  const float a = ref.get_a();\n  const float b = ref.get_b();\n  const auto converted = fftcomp( ref.get_pixels(), ref.get_height(), window, audio, ref.get_resolution(), a, b, ref.get_width() );\n  float delay, attack, release;\n  std::tie( delay, attack, release ) = segment_envelope( converted.second, ref.get_a(), ref.get_b() );\n  double delay_time = ( a * delay * delay + b * delay ) * tinyfm3::delta;\n  double attack_time = ( a * attack * attack + b * attack ) * tinyfm3::delta;\n  double release_time = ( a * release * release + b * release ) * tinyfm3::delta;\n  double delay_distance = std::abs( ref.get_delay_time() - delay_time );\n  double attack_distance = std::abs( ref.get_attack_time() - attack_time );\n  double release_distance = std::abs( ref.get_release_time() - release_time );\n//  std::cout << delay_distance << \" \" << attack_distance << \" \" << release_distance << std::endl;\n  return double( converted.first )/ref.get_width()/ref.get_height() * ( delay_distance * 40.f + attack_distance * 40.f + release_distance * 40.f + 1.f );\n}\n\n", "meta": {"hexsha": "141bb7e7b1f4b9088fdd79a817838d04a30eab7c", "size": 3141, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/spectrum_image.cpp", "max_stars_repo_name": "Fadis/genetic_fm", "max_stars_repo_head_hexsha": "415158b02e2c0dad8fafc81b5762b8889e493f10", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2016-10-08T08:55:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-17T03:19:54.000Z", "max_issues_repo_path": "src/spectrum_image.cpp", "max_issues_repo_name": "Fadis/genetic_fm", "max_issues_repo_head_hexsha": "415158b02e2c0dad8fafc81b5762b8889e493f10", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/spectrum_image.cpp", "max_forks_repo_name": "Fadis/genetic_fm", "max_forks_repo_head_hexsha": "415158b02e2c0dad8fafc81b5762b8889e493f10", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-06-21T00:06:30.000Z", "max_forks_repo_forks_event_max_datetime": "2018-06-21T00:06:30.000Z", "avg_line_length": 46.1911764706, "max_line_length": 153, "alphanum_fraction": 0.6711238459, "num_tokens": 842, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544911, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4994705283867921}}
{"text": "#ifndef CHARGE_EV_PHEM_HPP\n#define CHARGE_EV_PHEM_HPP\n\n#include \"common/constant_function.hpp\"\n#include \"common/serialization.hpp\"\n\n#include \"ev/consumption_model.hpp\"\n\n#include <boost/algorithm/string.hpp>\n\n#include <cstdint>\n\nnamespace charge::ev {\nnamespace detail {\n\nenum class PHEMVehicleType : std::int32_t {\n    PEUGEOT_ION,\n    EV_NO_AUX,\n    EV_SPRING,\n    EV_SUMMER,\n    EV_WINTER,\n    INVALID = -1\n};\n\nclass PHEMConsumptionModel : public ConsumptionModel {\n  public:\n    PHEMConsumptionModel(double speed_parameter, double slope_parameter, double const_parameter)\n        : speed_parameter(speed_parameter), slope_parameter(slope_parameter),\n          const_parameter(const_parameter) {}\n\n    LimitedTradeoffFunction tradeoff_function(const double length, const double slope,\n                                              const double min_speed,\n                                              const double max_speed) const override final {\n        assert(min_speed <= max_speed);\n        assert(min_speed > 0);\n        assert(max_speed < 300);\n\n        const double limited_slope = std::max(-10.0, slope*100);\n        // Original code has a scaling by 1000, this causes numeric problems.\n        // const double a = 1000.0 * length * speed_parameter * (3.6 * 3.6 * length * length);\n        // const double b = 0.0;\n        // const double c = 1000.0 * length * (slope_parameter * limited_slope + const_parameter);\n        const double a = length * speed_parameter * (3.6 * 3.6 * length * length);\n        const double b = 0.0;\n        const double c = length * (slope_parameter * limited_slope + const_parameter);\n        const double min_duration = length * 3.6 / max_speed;\n        const double max_duration = length * 3.6 / min_speed;\n        assert(min_duration <= max_duration);\n        assert(min_duration >= 0);\n\n        assert(std::isfinite(a));\n        assert(std::isfinite(b));\n        assert(std::isfinite(c));\n        assert(std::isfinite(min_duration));\n        assert(std::isfinite(max_duration));\n\n        LimitedTradeoffFunction tradeoff;\n        if (a > 0)\n            tradeoff = {min_duration, max_duration, common::HyperbolicFunction{a, b, c}};\n        else\n            tradeoff = {min_duration, max_duration, common::ConstantFunction{c}};\n\n        // Only return a tradeoff function of the min and max speed are different\n        if (max_speed - min_speed <= 1 || max_duration - min_duration < 1) {\n            auto constant_consumption = tradeoff(tradeoff.min_x);\n            return LimitedTradeoffFunction{min_duration, min_duration, common::ConstantFunction{constant_consumption}};\n        } else {\n            return tradeoff;\n        }\n    }\n\n  private:\n    double speed_parameter;\n    double slope_parameter;\n    double const_parameter;\n};\n\nstd::unique_ptr<ConsumptionModel> make_consumption_model(PHEMVehicleType type) {\n    double speed_parameter, slope_parameter, const_parameter;\n\n    switch (type) {\n    case PHEMVehicleType::PEUGEOT_ION:\n        speed_parameter = 0.00001084948;\n        slope_parameter = 0.02863728;\n        const_parameter = 0.08052179;\n        break;\n    case PHEMVehicleType::EV_NO_AUX:\n        speed_parameter = 0.00001129197;\n        slope_parameter = 0.05127720;\n        const_parameter = 0.1247448;\n        break;\n    case PHEMVehicleType::EV_SPRING:\n        speed_parameter = 0.00001105337;\n        slope_parameter = 0.05135052;\n        const_parameter = 0.1287824;\n        break;\n    case PHEMVehicleType::EV_SUMMER:\n        speed_parameter = 0.000009192936;\n        slope_parameter = 0.05194433;\n        const_parameter = 0.1605070;\n        break;\n    case PHEMVehicleType::EV_WINTER:\n        speed_parameter = 0.000004730422;\n        slope_parameter = 0.05345339;\n        const_parameter = 0.2379125;\n        break;\n    default:\n        throw std::runtime_error(\"Unknown vehicle type\");\n    }\n\n    return std::make_unique<PHEMConsumptionModel>(speed_parameter, slope_parameter,\n                                                  const_parameter);\n}\n}\n\nstd::unordered_map<std::string, std::unique_ptr<ConsumptionModel>>\nmake_phem_consumption_models() {\n    std::unordered_map<std::string, std::unique_ptr<ConsumptionModel>> models;\n\n    models[\"Peugeot Ion\"] =\n        detail::make_consumption_model(detail::PHEMVehicleType::PEUGEOT_ION);\n    models[\"EV No Aux\"] =\n        detail::make_consumption_model(detail::PHEMVehicleType::EV_NO_AUX);\n    models[\"EV Spring\"] =\n        detail::make_consumption_model(detail::PHEMVehicleType::EV_SPRING);\n    models[\"EV Summer\"] =\n        detail::make_consumption_model(detail::PHEMVehicleType::EV_SUMMER);\n    models[\"EV Winter\"] =\n        detail::make_consumption_model(detail::PHEMVehicleType::EV_WINTER);\n\n    return models;\n}\n}\n\n#endif\n", "meta": {"hexsha": "0cb764147902ec6b29ef11784fe8de8d63c4926b", "size": 4748, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ev/phem.hpp", "max_stars_repo_name": "TheMarex/charge", "max_stars_repo_head_hexsha": "85e35f7a6c8b8c161ecd851124d1363d5a450573", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2018-03-09T14:37:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-27T06:56:35.000Z", "max_issues_repo_path": "include/ev/phem.hpp", "max_issues_repo_name": "AlexBlazee/charge", "max_issues_repo_head_hexsha": "85e35f7a6c8b8c161ecd851124d1363d5a450573", "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/ev/phem.hpp", "max_forks_repo_name": "AlexBlazee/charge", "max_forks_repo_head_hexsha": "85e35f7a6c8b8c161ecd851124d1363d5a450573", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2018-04-14T02:27:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-13T23:30:44.000Z", "avg_line_length": 34.9117647059, "max_line_length": 119, "alphanum_fraction": 0.6575400168, "num_tokens": 1144, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.4994428544730137}}
{"text": "// Copyright (c) 2012-2017 VideoStitch SAS\n// Copyright (c) 2018 stitchEm\n\n#include \"eigengeometry.hpp\"\n\n#include <Eigen/Geometry>\n\nnamespace VideoStitch {\nnamespace Calibration {\n\n#ifndef __clang_analyzer__  // VSA-7040\nvoid rotationFromEulerZXY(Eigen::Matrix3d& R, double yaw, double pitch, double roll) {\n  Eigen::AngleAxisd X(-pitch, Eigen::Vector3d::UnitX());\n  Eigen::AngleAxisd Y(-yaw, Eigen::Vector3d::UnitY());\n  Eigen::AngleAxisd Z(-roll, Eigen::Vector3d::UnitZ());\n\n  R = Z.matrix() * X.matrix() * Y.matrix();\n}\n#endif  // __clang_analyzer__\n\nvoid EulerZXYFromRotation(Eigen::Vector3d& vr, const Eigen::Matrix3d& R) {\n  vr(0) = atan2(R(2, 0), R(2, 2));\n  vr(1) = -asin(R(2, 1));\n  vr(2) = atan2(R(0, 1), R(1, 1));\n}\n\n}  // namespace Calibration\n}  // namespace VideoStitch\n", "meta": {"hexsha": "e042878b7235d35cd96c96840d4b77a8d70185fd", "size": 784, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/src/calibration/eigengeometry.cpp", "max_stars_repo_name": "tlalexander/stitchEm", "max_stars_repo_head_hexsha": "cdff821ad2c500703e6cb237ec61139fce7bf11c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 182.0, "max_stars_repo_stars_event_min_datetime": "2019-04-19T12:38:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T16:48:20.000Z", "max_issues_repo_path": "lib/src/calibration/eigengeometry.cpp", "max_issues_repo_name": "doymcc/stitchEm", "max_issues_repo_head_hexsha": "20693a55fa522d7a196b92635e7a82df9917c2e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 107.0, "max_issues_repo_issues_event_min_datetime": "2019-04-23T10:49:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-02T18:12:28.000Z", "max_forks_repo_path": "lib/src/calibration/eigengeometry.cpp", "max_forks_repo_name": "doymcc/stitchEm", "max_forks_repo_head_hexsha": "20693a55fa522d7a196b92635e7a82df9917c2e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 59.0, "max_forks_repo_forks_event_min_datetime": "2019-06-04T11:27:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T23:49:49.000Z", "avg_line_length": 27.0344827586, "max_line_length": 86, "alphanum_fraction": 0.6772959184, "num_tokens": 268, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677737461007, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4993590052004749}}
{"text": "#include \"comparator.h\"\n#include \"tools.h\"\n#include <helib/debugging.h>\n#include <helib/polyEval.h>\n#include <random>\n#include <map> \n#include <NTL/ZZ_pE.h>\n#include <NTL/mat_ZZ_pE.h>\n#include <helib/Ptxt.h>\n\nusing namespace he_cmp;\n\n// polynomial coefficients of bivariate polynomial decomposition as in Theorem 2 for different plaintext moduli\nmap<unsigned long, vector<vector<long>>> fcoefs {\n  {11,\n  \t{\n  \t\t{-4, 4, 2, -2, -2, 2, -4, -1},\n  \t\t{5, -5, 2, -2, -3, 4},\n  \t\t{-4, 4, 4, 4},\n  \t\t{2, 5},\n  \t\t{-1}\n  \t}\n  },\n  {13,\n  \t{\n  \t\t{-5, 5, 5, -5, -4, 4, 6, -6, -5, -1},\n  \t\t{3, -3, -5, 5, 4, -4, -4, 5},\n  \t\t{4, -4, -6, 6, -5, 1},\n  \t\t{3, -3, 6, 1},\n  \t\t{2, 6},\n  \t\t{1}\n  \t}\n  },\n  {17, \n    {\n    \t{-4, 4, -8, 8, 3, -3, 7, -7, -8, 8, -4, 4, -7, -1},\n    \t{4, -4, -1, 1, 4, -4, -4, 4, -7, 7, -6, 7},\n    \t{-6, 6, -4, 4, -7, 7, 7, -7, 3, 8},\n    \t{-4, 4, 3, -3, -2, 2, 3, 4},\n    \t{2, -2, -4, 4, 2, 2},\n    \t{-4, 4, 7, 8},\n    \t{-3, 5},\n    \t{1}\n    }\n  },\n  {19,\n  \t{\n  \t\t{4, -4, 6, -6, 8, -8, -1, 1, 6, -6, 1, -1, 8, -8, -8, -1},\n\t\t{-2, 2, -6, 6, 2, -2, -7, 7, -1, 1, -5, 5, -7, 8},\n    \t{2, -2, -9, 9, 2, -2, -1, 1, 7, -7, 9, 3},\n    \t{9, -9, -7, 7, 6, -6, 5, -5, -8, -4},\n    \t{7, -7, -9, 9, 4, -4, -7, 9},\n    \t{5, -5, 3, -3, -9, -1},\n    \t{7, -7, 5, -9},\n    \t{-3, -4},\n    \t{-1}\n  \t}\n  },\n  {23,\n  \t{\n  \t\t{8, -8, -1, 1, -11, 11, 7, -7, -3, 3, -9, 9, 1, -1, 7, -7, -6, 6, -10, -1},\n\t\t{9, -9, 6, -6, -2, 2, -8, 8, -1, 1, 8, -8, -11, 11, 1, -1, -9, 10},\n\t\t{-10, 10, 4, -4, 3, -3, 0, 0, 7, -7, 2, -2, 7, -7, 2, -11},\n\t\t{5, -5, 9, -9, 1, -1, 0, 0, -8, 8, 2, -2, 10, -3},\n\t\t{-10, 10, -6, 6, -7, 7, -2, 2, 2, -2, -9, 7},\n\t\t{6, -6, -3, 3, -2, 2, -11, 11, 5, -8},\n\t\t{10, -10, -10, 10, 6, -6, -2, -2},\n\t\t{-6, 6, 5, -5, 10, -8},\n\t\t{10, -10, -2, -5},\n\t\t{4, -1},\n\t\t{-1}\n  \t}\n  },\n  {29,\n  \t{\n  \t\t{2,-2,-6,6,-2,2,14,-14,5,-5,-4,4,-10,10,-4,4,-1,1,0,0,-9,9,-8,8,-13,-1},\n\t\t{8,-8,0,0,10,-10,-12,12,4,-4,11,-11,-2,2,3,-3,-6,6,-3,3,-14,14,-12,13},\n\t\t{4,-4,9,-9,4,-4,12,-12,-11,11,0,0,-11,11,-14,14,-5,5,7,-7,1,-13},\n\t\t{13,-13,0,0,10,-10,-13,13,5,-5,-7,7,-2,2,7,-7,12,-12,-6,13},\n\t\t{-9,9,-14,14,3,-3,-7,7,-13,13,-1,1,7,-7,5,-5,-6,-2},\n\t\t{9,-9,7,-7,-13,13,-3,3,-8,8,-10,10,12,-12,-2,10},\n\t\t{-6,6,8,-8,3,-3,12,-12,-14,14,14,-14,6,-9},\n\t\t{-6,6,7,-7,-5,5,-1,1,-10,10,-14,4},\n\t\t{3,-3,2,-2,-9,9,10,-10,12,12},\n\t\t{-1,1,-6,6,-9,9,-2,-10},\n\t\t{-9,9,-12,12,-14,1},\n\t\t{-1,1,-4,-13},\n\t\t{-5,-6},\n\t\t{1}\n  \t}\n  },\n  {31,\n  \t{\n  \t\t{-14,14,9,-9,-5,5,4,-4,-9,9,-1,1,-15,15,-11,11,9,-9,0,0,-1,1,13,-13,12,-12,-14,-1},\n\t\t{8,-8,5,-5,9,-9,-1,1,-10,10,12,-12,15,-15,10,-10,-2,2,8,-8,9,-9,-10,10,-13,14},\n\t\t{-14,14,-15,15,-13,13,-10,10,2,-2,13,-13,0,0,-5,5,0,0,-12,12,7,-7,11,7},\n\t\t{-9,9,-6,6,6,-6,-8,8,-11,11,-2,2,-13,13,5,-5,14,-14,-4,4,8,-1},\n\t\t{-13,13,12,-12,-6,6,10,-10,-13,13,10,-10,-1,1,8,-8,-11,11,9,12},\n\t\t{-8,8,9,-9,-4,4,-9,9,-13,13,2,-2,5,-5,-15,15,-12,-15},\n\t\t{-14,14,3,-3,-10,10,-2,2,-4,4,10,-10,9,-9,-12,-6},\n\t\t{-4,4,6,-6,-2,2,-7,7,-1,1,9,-9,12,-10},\n\t\t{-11,11,10,-10,-9,9,-12,12,8,-8,-7,-11},\n\t\t{9,-9,0,0,12,-12,9,-9,3,-6},\n\t\t{-1,1,-9,9,-3,3,2,3},\n\t\t{-14,14,6,-6,15,-14},\n\t\t{-1,1,-12,-11},\n\t\t{-5,9},\n\t\t{-1}\n  \t}\n  }\n};\n\nDoubleCRT Comparator::create_shift_mask(double& size, long shift)\n{\n\tcout << \"Mask for shift \" << shift << \" is being created\" << endl;\n\t// get EncryptedArray\n  \tconst EncryptedArray& ea = m_context.getEA();\n\n  \t//extract slots\n\tlong nSlots = ea.size();\n\n\t//number of batches in one slot\n\tlong batch_size = nSlots / m_expansionLen;\n\n\t// create a mask vector\n\tvector<long> mask_vec(nSlots,1);\n\n\t//starting position of all batches\n\tlong start = 0;\n\n\t// set zeros in the unused slots\n\tlong nEndZeros = nSlots - batch_size * m_expansionLen;\n\tfor (int i = 1; i <= nEndZeros; i++)\n\t{\n\tlong indx = (start + nSlots - i) % nSlots;\n\tmask_vec[indx] = 0;\n\t}\n\n\t// masking values rotated outside their batches\n\tfor (long i = 0; i < batch_size; i++)\n\t{\n\tif (shift < 0)\n\t{\n\t  for (long j = 0;  j < -shift; j++)\n\t  {\n\t    long indx = (start + (i + 1) * m_expansionLen - j - 1) % nSlots;\n\t    mask_vec[indx] = 0;\n\t  }\n\t}\n\telse if (shift > 0)\n\t{\n\t  for (long j = 0;  j < shift; j++)\n\t  {\n\t    long indx = (start + i * m_expansionLen + j) % nSlots;\n\t    mask_vec[indx] = 0;\n\t  }\n\t}\n\t}\n\tZZX mask_zzx;\n\tea.encode(mask_zzx, mask_vec);\n\n\tsize = conv<double>(embeddingLargestCoeff(mask_zzx, m_context.getZMStar()));\n\n\tDoubleCRT mask_crt = DoubleCRT(mask_zzx, m_context, m_context.allPrimes());\n\treturn mask_crt;\n}\n\nvoid Comparator::create_all_shift_masks()\n{\n\tlong shift = 1;\n\twhile (shift < m_expansionLen)\n\t{\n\t\tdouble size;\n\t    DoubleCRT mask_ptxt = create_shift_mask(size, -shift);\n\t    m_mulMasks.push_back(mask_ptxt);\n\t    m_mulMasksSize.push_back(size);\n\n\t    shift <<=1;\n\t}\n\tcout << \"All masks are created\" << endl;\n}\n\nvoid Comparator::compute_poly_params()\n{\n\t// get p\n\tZZ p = ZZ(m_context.getP());\n\tlong p_long = conv<long>(p);\n\n\t// hardcoded babysteps sizes\n\tmap<unsigned long, unsigned long> bs_nums\n\t{\n\t\t{5, 1},\n\t\t{7, 2}, // 4\n\t\t{11, 3}, // 3 (6), 1..4\n  \t\t{13, 3}, // 3 (6), 1..5\n  \t\t{17, 4}, // 4 (7), 1..5\n  \t\t{19, 3}, // 3 (8), 1..4\n  \t\t{23, 5}, // 5 (9), 3..6\n  \t\t{29, 5}, // 5 (10), 1..6\n  \t\t{31, 5}, // 5 (10), 4..6\n  \t\t{37, 5}, // 5 (12)\n  \t\t{47, 5}, // 5 (13), 2..11 \n  \t\t{61, 6}, // 6 (14), 4..8 \n  \t\t{67, 5}, // 5 (15), 4..8\n  \t\t{71, 4}, // 4 (15), 3..7\n  \t\t{101, 7}, // 7 (16), 4..8\n  \t\t{109, 7}, // 7 (19)\n  \t\t{131, 8}, // 8 (19), 4..11\n  \t\t{167, 10}, // 10 (21), 8..12\n  \t\t{173, 10},  // 10 (21), 8..12\n  \t\t{271, 9},  // 9 (26), 9..10\n  \t\t{401, 12},  // 12 (28), 9..14\n  \t\t{659, 11}\t// 11 (41), 11..12\n  \t};\n\n  \tm_bs_num_comp = -1;\n  \tm_bs_num_min = -1;\n  \tif(bs_nums.count(p_long) > 0)\n  \t{\n  \t\tm_bs_num_comp = bs_nums[p_long];\n  \t\tm_bs_num_min = bs_nums[p_long];\n  \t}\n\n  \t// if p > 3, d = (p-3)/2\n  \tlong d_comp = deg(m_univar_less_poly);\n  \t// if p > 3, d = (p-1)/2\n  \tlong d_min = deg(m_univar_min_max_poly);\n\n  \t// How many baby steps: set sqrt(d/2), rounded up/down to a power of two\n\n\t// FIXME: There may be some room for optimization here: it may be possible to choose this number as something other than a power of two and still maintain optimal depth, in principle we can try all possible values of m_babystep_num between two consecutive powers of two and choose the one that gives the least number of multiplies, conditioned on minimum depth.\n\n  \tif (m_bs_num_comp <= 0) \n\t{\n\t\tlong kk = static_cast<long>(sqrt(d_comp/2.0)); //sqrt(d/2)\n\t\tm_bs_num_comp = 1L << NextPowerOfTwo(kk);\n\n    \t// heuristic: if #baby_steps >> kk then use a smaler power of two\n    \tif ((m_bs_num_comp==16 && d_comp>167) || (m_bs_num_comp>16 && m_bs_num_comp>(1.44*kk)))\n      \t\tm_bs_num_comp /= 2;\n  \t}\n  \tif (m_bs_num_min <= 0) \n\t{\n\t\tlong kk = static_cast<long>(sqrt(d_min/2.0)); //sqrt(d/2)\n\t\tm_bs_num_min = 1L << NextPowerOfTwo(kk);\n\n    \t// heuristic: if #baby_steps >> kk then use a smaler power of two\n    \tif ((m_bs_num_min==16 && d_min>167) || (m_bs_num_min>16 && m_bs_num_min>(1.44*kk)))\n      \t\tm_bs_num_min /= 2;\n  \t}\n\n\tif(m_verbose)\n\t{\n\t\tcout << \"Number of baby steps for comparison: \" << m_bs_num_comp << endl;\n\t\tcout << \"Number of baby steps for min/max: \" << m_bs_num_min << endl;\n\t}\n\n\t// #giant_steps = ceil(d/#baby_steps), d >= #giant_steps * #baby_steps\n\tm_gs_num_comp = divc(d_comp,m_bs_num_comp);\n\tm_gs_num_min = divc(d_min,m_bs_num_min);\n\n\tif(m_verbose)\n\t{\n\t\tcout << \"Number of giant steps for comparison: \" << m_bs_num_comp << endl;\n\t\tcout << \"Number of giant steps for min/max: \" << m_bs_num_min << endl;\n\t}      \n\n\t// If #giant_steps is not a power of two, ensure that poly is monic and that\n\t// its degree is divisible by #baby_steps, then call the recursive procedure\n\n\t// top coefficient is equal to (p^2 - 1)/8 mod p\n\t// its inverse is equal to -8 mod p\n\tm_top_coef_comp = LeadCoeff(m_univar_less_poly);\n\tm_top_coef_min = LeadCoeff(m_univar_min_max_poly);\n\tZZ topInv_comp = ZZ(-8) % p; // the inverse mod p of the top coefficient of poly (if any)\n\tZZ topInv_min = ZZ(-8) % p; // the inverse mod p of the top coefficient of poly (if any)\n\tbool divisible_comp = (m_gs_num_comp * m_bs_num_comp == d_comp); // is the degree divisible by #baby_steps?\n\tbool divisible_min = (m_gs_num_min * m_bs_num_min == d_min); // is the degree divisible by #baby_steps?\n\n\t// FIXME: There may be some room for optimization below: instead of\n\t// adding a term X^{n*k} we can add X^{n'*k} for some n'>n, so long\n\t// as n' is smaller than the next power of two. We could save a few\n\t// multiplications since giantStep[n'] may be easier to compute than\n\t// giantStep[n] when n' has fewer 1's than n in its binary expansion.\n\n\tm_extra_coef_comp = ZZ::zero();    // extra!=0 denotes an added term extra*X^{#giant_steps * #baby_steps}\n\tm_extra_coef_min = ZZ::zero();    // extra!=0 denotes an added term extra*X^{#giant_steps * #baby_steps}\n\n\tif (m_gs_num_comp != (1L << NextPowerOfTwo(m_gs_num_comp)))\n\t{\n\t\tif (!divisible_comp) \n\t\t{  // need to add a term\n\t    \tm_top_coef_comp = NTL::to_ZZ(1);  // new top coefficient is one\n\t    \ttopInv_comp = m_top_coef_comp;    // also the new inverse is one\n\t    \t// set extra = 1 - current-coeff-of-X^{n*k}\n\t    \tm_extra_coef_comp = SubMod(m_top_coef_comp, coeff(m_univar_less_poly, m_gs_num_comp * m_bs_num_comp), p);\n\t    \tSetCoeff(m_univar_less_poly, m_gs_num_comp * m_bs_num_comp); // set the top coefficient of X^{n*k} to one\n\t\t}\n\n\t\tif (!IsOne(m_top_coef_comp)) \n\t\t{\n\t    \tm_univar_less_poly *= topInv_comp; // Multiply by topInv to make into a monic polynomial\n\t    \tfor (long i = 0; i <= m_gs_num_comp * m_bs_num_comp; i++) rem(m_univar_less_poly[i], m_univar_less_poly[i], p);\n\t    \tm_univar_less_poly.normalize();\n\t\t}\n\t}\n\n\t/*\n\tcout << \"Less-than poly: \";\n\tprintZZX(cout, m_univar_less_poly, conv<long>(p));\n\tcout << endl;\n\t*/\n\n\tif (m_gs_num_min != (1L << NextPowerOfTwo(m_gs_num_min)))\n\t{\n\t\tif (!divisible_min) \n\t\t{  // need to add a term\n\t    \tm_top_coef_min = NTL::to_ZZ(1);  // new top coefficient is one\n\t    \ttopInv_min = m_top_coef_min;    // also the new inverse is one\n\t    \t// set extra = 1 - current-coeff-of-X^{n*k}\n\t    \tm_extra_coef_min = SubMod(m_top_coef_min, coeff(m_univar_min_max_poly, m_gs_num_min * m_bs_num_min), p);\n\t    \tSetCoeff(m_univar_min_max_poly, m_gs_num_min * m_bs_num_min); // set the top coefficient of X^{n*k} to one\n\t\t}\n\n\t\tif (!IsOne(m_top_coef_min)) \n\t\t{\n\t    \tm_univar_min_max_poly *= topInv_min; // Multiply by topInv to make into a monic polynomial\n\t    \tfor (long i = 0; i <= m_gs_num_min * m_bs_num_min; i++) rem(m_univar_min_max_poly[i], m_univar_min_max_poly[i], p);\n\t    \tm_univar_min_max_poly.normalize();\n\t\t}\n\t}\n\n\t/*\n\tcout << \"Min-max poly: \";\n\tprintZZX(cout, m_univar_min_max_poly, conv<long>(p));\n\tcout << endl;\n\t*/\n\n\tlong top_deg = conv<long>(p-1) >> 1;\n\tm_baby_index = top_deg % m_bs_num_comp;\n\tm_giant_index = top_deg / m_bs_num_comp;\n\tif(m_baby_index == 0)\n\t{\n\t\tm_baby_index = m_bs_num_comp;\n\t\tm_giant_index -= 1;\n\t}\n}\n\nvoid Comparator::create_poly()\n{\n\tcout << \"Creating comparison polynomial\" << endl;\n\t// get p\n\tunsigned long p = m_context.getP();;\n\n\tif(m_type == UNI)\n\t{\n\t\t// polynomial coefficient\n\t\tZZ_p coef;\n\t\tcoef.init(ZZ(p));\n\n\t\t// field element\n\t\tZZ_p field_elem;\n\t\tfield_elem.init(ZZ(p));\n\n\t\t// initialization of the univariate comparison polynomial\n\t\tm_univar_less_poly = ZZX(INIT_MONO, 0, 0);\n\n\t\t// loop over all odd coefficient indices\n\t\tfor (long indx = 1; indx < p - 1; indx+=2)\n\t\t{ \n\t\t\t// coefficient f_i = sum_a a^{p-1-indx} where a runs over [1,...,(p-1)/2]\n\t\t\tcoef = 1;\n\t\t\tfor(long a = 2; a <= ((p-1) >> 1); a++)\n\t\t\t{\n\t\t\t  field_elem = a;\n\t\t\t  coef += power(field_elem, p - 1 - indx);\n\t\t\t}\n\n\t\t\tm_univar_less_poly += ZZX(INIT_MONO, (indx-1) >> 1, rep(coef));\n\t\t}\n\n\t\t/*\n\t\tcout << \"Less-than poly: \";\n\t\tprintZZX(cout, m_univar_less_poly, p);\n\t\tcout << endl;\n\t\t*/\n\n\t\tm_univar_min_max_poly = m_univar_less_poly * ZZX(INIT_MONO, 1, 1);\n\n\t\t/*\n\t\tcout << \"Min-max poly: \";\n\t\tprintZZX(cout, m_univar_min_max_poly, p);\n\t\tcout << endl;\n\t\t*/\n\n\t\tcompute_poly_params();\n\t}\n\telse if (m_type == TAN)\n\t{\n\t\t// computing the coefficients of the bivariate polynomial of Tan et al.\n\t\tm_bivar_less_coefs.SetDims(p,p);\n\n\t\t// y^{p-1}\n\t\tm_bivar_less_coefs[0][p-1] = ZZ(1);\n\n\t\t// (p+1)/2 * x^{(p-1)/2} * y^{(p-1)/2}\n\t\tm_bivar_less_coefs[(p-1) >> 1][(p-1) >> 1] = ZZ((p+1) >> 1);\n\n\t\t// iterator\n\t\tZZ_p field_elem;\n\t\tfield_elem.init(ZZ(p));\n\n\t\t// inner sum\n\t\tZZ_p inner_sum;\n\t\tinner_sum.init(ZZ(p));\n\t\t\n\t\t// outer sum\n\t\tZZ_p outer_sum;\n\t\touter_sum.init(ZZ(p));\n\n\t\tfor (long i = 1; i < p; i++)\n\t\t{\n\t\t\tfor (long j = 1; j < p; j++)\n\t\t\t{\n\t\t\t\t// x^i * y^i have the zero coefficient except for i = (p-1)/2\n\t\t\t\tif (i == j)\n\t\t\t\t\tcontinue;\n\n\t\t\t\touter_sum = 0;\n\t\t\t\t// sum_{a=1}^{p-1} a^{p-1-i} sum_{b = a+1}^{p-1} b^{p-1-j} \n\t\t\t\tfor (long a = 1; a < p; a++)\n\t\t\t\t{\n\t\t\t\t\tinner_sum = 0;\n\t\t\t\t\t// sum_{b = a+1}^{p-1} b^{p-1-j} \n\t\t\t\t\tfor (long b = a+1; b < p; b++)\n\t\t\t\t\t{\n\t\t\t\t\t\t// b^{p-1-j}\n\t\t\t\t\t\tfield_elem = b;\n\t\t\t\t\t\tfield_elem = power(field_elem, p - 1 - j);\n\n\t\t\t\t\t\tinner_sum += field_elem;\n\t\t\t\t\t}\n\t\t\t\t\t// a^{p-1-i}\n\t\t\t\t\tfield_elem = a;\n\t\t\t\t\tfield_elem = power(field_elem, p - 1 - i);\n\n\t\t\t\t\tinner_sum *= field_elem;\n\t\t\t\t\touter_sum += inner_sum;\n\t\t\t\t}\n\t\t\t\tm_bivar_less_coefs[i][j] = rep(outer_sum);\n\t\t\t}\n\t\t}\n\n\t\tcout << \"Bivariate coefficients\" << endl << m_bivar_less_coefs << endl;\n\n\t\tif (m_verbose)\n\t\t{\n\t\t\tcout << \"Comparison polynomial: \" << endl;\n\t\t\tprintZZX(cout, m_univar_less_poly, (p-1)>>1);\n\t\t\tcout << endl;\n\t\t}\n\t}\n\n\tcout << \"Comparison polynomial is created\" << endl;\n}\n\nvoid Comparator::find_prim_root(ZZ_pE& root) const\n{\n\tZZ qm1 = root.cardinality() - 1;\n\n\tcout << \"Slot order: \" << qm1 << endl;\n\tcout << \"Slot poly: \" << root.modulus() << endl;\n\n\tvector<ZZ> facts;\n\tfactorize(facts, qm1); // factorization of slot order\n\n\tNTL::set(root);\n\n\tfor (unsigned long i = 0; i < facts.size(); i++) \n\t{\n\t\tZZ p = facts[i];\n\t\tZZ pp = p;\n\t\tZZ ee = qm1 / p;\n\t\twhile (ee % p == 0) \n\t\t{\n\t  \t\tee = ee / p;\n\t  \t\tpp = pp * p;\n\t\t}\n\t\t// so now we have e = pp * ee, where pp is\n\t\t// the power of p that divides e.\n\t\t// Our goal is to find an element of order pp\n\n\t\tNTL::PrimeSeq s;\n\t\tZZ_pE q = root;\n\t\tZZ_pE qq = root;\n\t\tZZ_pE qq1 = root;\n\t\tlong iter = 0;\n\t\tdo \n\t\t{\n\t  \t\titer++;\n\t  \t\tif (iter > 1000000)\n\t    \t\tthrow RuntimeError(\"FindPrimitiveRoot: possible infinite loop?\");\n\t  \t\trandom(q);\n\t  \t\tNTL::conv(qq, q);\n\t  \t\tpower(qq1, qq, qm1 / p);\n\t\t} \n\t\twhile (IsOne(qq1));\n\t\tpower(qq1, qq, qm1 / pp); // qq1 has order pp\n\n\t\tmul(root, root, qq1);\n\t}\n\n\t// independent check that we have an e-th root of unity\n\t{\n\t\tZZ_pE s;\n\n\t\tpower(s, root, qm1);\n\t\tif (!IsOne(s))\n\t  \t\tthrow RuntimeError(\"FindPrimitiveRoot: internal error (1)\");\n\n\t\t// check that s^{e/p} != 1 for any prime divisor p of e\n\t\tfor (unsigned long i = 0; i < facts.size(); i++) \n\t\t{\n\t  \t\tZZ e2 = qm1 / facts[i];\n\t  \t\tpower(s, root, e2); // s = root^{e/p}\n\t  \t\tif (IsOne(s))\n\t    \t\tthrow RuntimeError(\"FindPrimitiveRoot: internal error (2)\");\n\t\t}\n\t}\n}\n\nvoid Comparator::extraction_init()\n{\n\t// get the total number of slots\n\tconst EncryptedArray& ea = m_context.getEA();\n\tlong nslots = ea.size();\n\n\t// get p\n\tlong p = m_context.getP();\n\t//cout << \"p: \" << p << endl;\n\n\t// get the order of p\n\tlong d = m_context.getOrdP();\n\n\t// get the defining polynomial of a slot mod p\n\tZZX def_poly = m_context.getSlotRing()->G;\n\n\t//cout << \"Def. poly\" << def_poly << endl;\n\n\tZZ_pX def_poly_p;\n\tfor (long iCoef = 0; iCoef <= deg(def_poly); iCoef++)\n\t{\n\t\tZZ_p coef;\n\t\tcoef.init(ZZ(p));\n\t\tcoef = conv<long>(def_poly[iCoef]);\n\t\tSetCoeff(def_poly_p, iCoef, coef);\n\t}\n\t//cout << \"Def. poly mod p \" << def_poly_p << endl;\n\t\n\t// build the trace matrix\n\tmat_ZZ_pE trace_matrix;\n\tmat_ZZ_pE inv_trace_matrix;\n\ttrace_matrix.SetDims(d, d);\n\t\n\tZZ_pE prim_elem;\n\tprim_elem.init(def_poly_p);\n\tprim_elem = conv<ZZ_pE>(ZZ_pX(INIT_MONO, 1, 1));\n\n\t//find_prim_root(prim_elem);\n\t//cout << \"Primitive element \" << prim_elem << endl;\n\n\tZZ_pE coef;\n\tcoef.init(def_poly_p);\n\n\tfor (long iRow = 0; iRow < d; iRow++)\n\t{\n\t\tfor (long iCol = 0; iCol < d; iCol++)\n\t\t{\n\t\t\t// x^(iRow * p^iCol)\n\t\t\tcoef = power(prim_elem, iRow * power_long(p, iCol));\n\t\t\ttrace_matrix[iRow][iCol] = coef;\n\t\t}\n\t}\n\t//cout << \"Trace matrix: \" << trace_matrix << endl;\n\t//cout << \"Modulus: \" << trace_matrix[0][0].modulus() << endl; \n\n\tinv_trace_matrix = NTL::inv(trace_matrix);\n\t//cout << \"Inverse of trace matrix\" << inv_trace_matrix << endl;\n\t\t\n\n\t//cout << \"Extraction consts: \" << endl;\n\tfor (long iCoef = 0; iCoef < d; iCoef++)\n\t{\n\t\tvector<DoubleCRT> tmp_crt_vec;\n\t\tvector<double> size_vec;\n\n\t\tfor (long iFrob = 0; iFrob < d; iFrob++)\n\t\t{\n\t\t\tZZX tmp = conv<ZZX>(rep(inv_trace_matrix[iFrob][iCoef]));\n\n\t\t\t//cout << tmp << endl;\n\n\t\t\tvector<ZZX> vec_const(nslots, tmp);\n\t\t\tea.encode(tmp, vec_const);\n\n\t\t\tDoubleCRT tmp_crt(tmp, m_context, m_context.allPrimes());\n\n\t\t\tdouble const_size = conv<double>(embeddingLargestCoeff(tmp, m_context.getZMStar()));\n\t\t\tsize_vec.push_back(const_size);\n\n\t\t\ttmp_crt_vec.push_back(tmp_crt);\n\t\t}\n\t\tm_extraction_const.push_back(tmp_crt_vec);\n\t\tm_extraction_const_size.push_back(size_vec);\n\t}\n}\n\nvoid Comparator::extract_mod_p(vector<Ctxt>& mod_p_coefs, const Ctxt& ctxt_x) const\n{\n\tHELIB_NTIMER_START(Extraction);\n\tmod_p_coefs.clear();\n\n\tif (m_slotDeg == 1)\n\t{\n\t\tmod_p_coefs.push_back(ctxt_x);\n\t\treturn;\n\t}\n\n\tconst EncryptedArray& ea = m_context.getEA();\n\tlong nslots = ea.size();\n\n\t// get max slot degree\n\tlong d = m_context.getOrdP();\n\n\t// TODO: how to use key switching hoisting from CRYPTO'18?\n\tvector<Ctxt> ctxt_frob(d-1, ctxt_x);\n\tfor(long iFrob = 1; iFrob < d; iFrob++)\n\t{\n\t\tctxt_frob[iFrob-1].frobeniusAutomorph(iFrob);\n\t} \n\n\tfor(long iCoef = 0; iCoef < m_slotDeg; iCoef++)\n\t{\n\t\t//cout << \"Extract coefficient \" << iCoef << endl;\n\t\tCtxt mod_p_ctxt = ctxt_x;\n\n\t\tmod_p_ctxt.multByConstant(m_extraction_const[iCoef][0], m_extraction_const_size[iCoef][0]);\n\n\t\tfor(long iFrob = 1; iFrob < d; iFrob++)\n\t\t{\n\t\t\tCtxt tmp = ctxt_frob[iFrob-1];\n\t\t\ttmp.multByConstant(m_extraction_const[iCoef][iFrob], m_extraction_const_size[iCoef][iFrob]);\n\t\t\tmod_p_ctxt += tmp; \n\t\t}\n\t\tmod_p_coefs.push_back(mod_p_ctxt);\n\t}\n\tHELIB_NTIMER_STOP(Extraction);\n}\n\nComparator::Comparator(const Context& context, CircuitType type, unsigned long d, unsigned long expansion_len, const SecKey& sk, bool verbose): m_context(context), m_type(type), m_slotDeg(d), m_expansionLen(expansion_len), m_sk(sk), m_pk(sk), m_verbose(verbose)\n{\n\t//determine the order of p in (Z/mZ)*\n\tunsigned long ord_p = context.getOrdP();\n\t//check that the extension degree divides the order of p\n\tif (ord_p < d != 0)\n\t{\n\t\tthrow invalid_argument(\"Field extension must be larger than the order of the plaintext modulus\\n\");\n\t}\n\n\tcreate_all_shift_masks();\n\tcreate_poly();\n\textraction_init();\n}\n\nconst DoubleCRT& Comparator::get_mask(double& size, long index) const\n{\n\tsize = m_mulMasksSize[index];\n\treturn m_mulMasks[index];\n}\n\nconst ZZX& Comparator::get_less_than_poly() const\n{\n\treturn m_univar_less_poly;\n}\n\nconst ZZX& Comparator::get_min_max_poly() const\n{\n\treturn m_univar_min_max_poly;\n}\n\nvoid Comparator::print_decrypted(const Ctxt& ctxt) const\n{\n\t// get EncryptedArray\n\tconst EncryptedArray& ea = m_context.getEA();\n\n\t// get order of p\n\tunsigned long ord_p = m_context.getOrdP();\n\n    long nSlots = ea.size();\n    vector<ZZX> decrypted(nSlots);\n    ea.decrypt(ctxt, m_sk, decrypted);\n\n    for(int i = 0; i < nSlots; i++)\n    {\n      printZZX(cout, decrypted[i], ord_p);\n      cout << endl;\n    }\n}\n\nvoid Comparator::batch_shift(Ctxt& ctxt, long start, long shift) const\n{\n\tHELIB_NTIMER_START(BatchShift);\n\t// get EncryptedArray\n\tconst EncryptedArray& ea = m_context.getEA();\n\t\n\t// if shift is zero, do nothing\n\tif(shift == 0)\n\t\treturn;\n\n\t// left cyclic rotation\n\tea.rotate(ctxt, shift);\n\n\t// masking elements shifted out of batch\n\tlong index = static_cast<long>(intlog(2, -shift));\n\t//cout << \"Mask index: \" << index << endl;\n\tdouble size;\n\tDoubleCRT mask = get_mask(size, index);\n\tctxt.multByConstant(mask, size);\n\tHELIB_NTIMER_STOP(BatchShift);\n}\n\nvoid Comparator::batch_shift_for_mul(Ctxt& ctxt, long start, long shift) const\n{\n\tHELIB_NTIMER_START(BatchShiftForMul);\n\t// get EncryptedArray\n\tconst EncryptedArray& ea = m_context.getEA();\n\t\n\t// if shift is zero, do nothing\n\tif(shift == 0)\n\t\treturn;\n\t// left cyclic rotation\n\tea.rotate(ctxt, shift);\n\t\n\tlong index = static_cast<long>(intlog(2, -shift));\n\t//cout << \"Mask index: \" << index << endl;\n\tdouble mask_size;\n\tDoubleCRT mask = get_mask(mask_size, index);\n\tctxt.multByConstant(mask, mask_size);\n\n\t// add 1 to masked slots\n\tctxt.addConstant(ZZ(1));\n\tmask.Negate();\n\tctxt.addConstant(mask, mask_size);\n\n\tHELIB_NTIMER_STOP(BatchShiftForMul);\n}\n\nvoid Comparator::shift_and_add(Ctxt& x, long start, long shift_direction) const\n{\n  HELIB_NTIMER_START(ShiftAdd);\n  long shift_sign = -1;\n  if(shift_direction)\n    shift_sign = 1;\n\n  long e = 1;\n\n  // shift and add\n  while (e < m_expansionLen){\n    Ctxt tmp = x;\n    batch_shift(tmp, start, e * shift_sign);\n    x += tmp;\n    e <<=1;\n  }\n  HELIB_NTIMER_STOP(ShiftAdd);\n}\n\nvoid Comparator::shift_and_mul(Ctxt& x, long start, long shift_direction) const\n{\n  HELIB_NTIMER_START(ShiftMul);\n  long shift_sign = -1;\n  if(shift_direction)\n    shift_sign = 1;\n\n  long e = 1;\n\n  // shift and add\n  while (e < m_expansionLen){\n    Ctxt tmp = x;\n    batch_shift_for_mul(tmp, start, e * shift_sign);\n    x.multiplyBy(tmp);\n    e <<=1;\n  }\n  HELIB_NTIMER_STOP(ShiftMul);\n}\n\nvoid Comparator::mapTo01_subfield(Ctxt& ctxt, long pow) const\n{\n  HELIB_NTIMER_START(MapTo01);\t\n  // get EncryptedArray\n  const EncryptedArray& ea = m_context.getEA();\n\n  // get p\n  long p = ctxt.getPtxtSpace();\n  if (p != ea.getPAlgebra().getP()) // ptxt space is p^r for r>1\n    throw helib::LogicError(\"mapTo01 not implemented for r>1\");\n\n  if (p % pow != 0)\n  \tthrow helib::LogicError(\"Exponent must divide p\");\n\n  if (p > 2)\n    ctxt.power((p - 1) / pow); // set y = x^{p-1}\n\n  HELIB_NTIMER_STOP(MapTo01);\n}\n\nvoid Comparator::less_than_mod_2(Ctxt& ctxt_res, const Ctxt& ctxt_x, const Ctxt& ctxt_y) const\n{\n\t//Comp(x,y) = y(x+1)\n\tcout << \"Compute comparison polynomial\" << endl;\n\n\t// x + 1\n\tCtxt x_plus_1 = ctxt_x;\n\tx_plus_1.addConstant(ZZ(1));\n\n\t// y(x+1)\n\tctxt_res = ctxt_y;\n\tctxt_res.multiplyBy(x_plus_1);\n\n\tif(m_verbose)\n\t  {\n\t    print_decrypted(ctxt_res);\n\t    cout << endl;\n\t  }\n}\n\nvoid Comparator::less_than_mod_3(Ctxt& ctxt_res, const Ctxt& ctxt_x, const Ctxt& ctxt_y) const\n{\n\t//Comp(x,y) = -y(x-y)(x+1)\n\tcout << \"Compute comparison polynomial\" << endl;\n\n\t// x + 1\n\tCtxt x_plus_1 = ctxt_x;\n\tx_plus_1.addConstant(ZZ(1));\n\n\t// y(x - y)\n\tctxt_res = ctxt_x;\n\tctxt_res -= ctxt_y;\n\tctxt_res.multiplyBy(ctxt_y);\n\n\t// -y(x-y)(x+1)\n\tctxt_res.multiplyBy(x_plus_1);\n\tctxt_res.negate();\n\n\tif(m_verbose)\n\t  {\n\t    print_decrypted(ctxt_res);\n\t    cout << endl;\n\t  }\n}\n\nvoid Comparator::less_than_mod_5(Ctxt& ctxt_res, const Ctxt& ctxt_x, const Ctxt& ctxt_y) const\n{\n\t//Comp(x,y)=\u2212(x+1) y(x\u2212y) (x (x+1) \u2212 y(x\u2212y)).\n\tcout << \"Compute comparison polynomial\" << endl;\n\n\t// y(x - y)\n\tCtxt y_x_min_y = ctxt_x;\n\ty_x_min_y -= ctxt_y;\n\ty_x_min_y.multiplyBy(ctxt_y);\n\n\t// x + 1\n\tCtxt x_plus_1 = ctxt_x;\n\tx_plus_1.addConstant(ZZ(1));\n\n\t// x * (x+1)\n\tctxt_res = ctxt_x;\n\tctxt_res.multiplyBy(x_plus_1);\n\n\t// x * (x+1) - y * (x-y)\n\tctxt_res -= y_x_min_y;\n\n\t// y * (x-y) * (x * (x+1) - y * (x-y))\n\tctxt_res.multiplyBy(y_x_min_y);\n\n\t// -(x+1) * y * (x-y) * (x * (x+1) - y * (x-y))\n\tctxt_res.multiplyBy(x_plus_1);\n\tctxt_res.negate();\n\n\tif(m_verbose)\n\t  {\n\t    print_decrypted(ctxt_res);\n\t    cout << endl;\n\t  }\n}\n\nvoid Comparator::less_than_mod_7(Ctxt& ctxt_res, const Ctxt& ctxt_x, const Ctxt& ctxt_y) const\n{\n\t// Comp(x,y) = -y(x-y)(x+1)(x(x+1)(x(x+1)+3) + 5y(x-y)(x(x+1)+2x+3y(x-y)))\n\tcout << \"Compute comparison polynomial\" << endl;\n\n\t// x\n\tCtxt y_x_min_y = ctxt_x;\n\t// x - y\n\ty_x_min_y -= ctxt_y;\n\t// y(x-y)\n\ty_x_min_y.multiplyBy(ctxt_y);\n\n\t// x + 1\n\tCtxt x_plus_1 = ctxt_x;\n\tx_plus_1.addConstant(ZZ(1));\n\n\t// x(x+1)\n\tCtxt x_x_plus_1 = x_plus_1;\n\tx_x_plus_1.multiplyBy(ctxt_x);\n\n\t// x(x+1)(x(x+1)+3)\n\tCtxt tmp = x_x_plus_1;\n\ttmp.addConstant(ZZ(3));\n\ttmp.multiplyBy(x_x_plus_1);\n\tctxt_res = tmp;\n\n\t// x(x+1) + 2x + 3y(x-y)\n\ttmp = y_x_min_y;\n\ttmp.multByConstant(ZZ(3));\n\ttmp += x_x_plus_1;\n\ttmp += ctxt_x;\n\ttmp += ctxt_x;\n\n\t// 5y(x-y)(x(x+1) + 2x + 3y(x-y))\n\ttmp.multiplyBy(y_x_min_y);\n\ttmp.multByConstant(ZZ(5));\n\n\t// (x^2+x)(x^2+x+3) + 5y(x-y)(x^2+x+2x+3y(x-y))\n\tctxt_res += tmp;\n\n\t// -y(x-y)(x+1)((x^2+x)(x^2+x+3) + 5y(x-y)(x^2+x+2x+3y(x-y)))\n\tctxt_res.multiplyBy(y_x_min_y);\n\tctxt_res.multiplyBy(x_plus_1);\n\tctxt_res.negate();\n\n\tif(m_verbose)\n\t{\n\t\tprint_decrypted(ctxt_res);\n\t\tcout << endl;\n\t}\n}\n\nvoid Comparator::less_than_mod_any(Ctxt& ctxt_res, const Ctxt& ctxt_x, const Ctxt& ctxt_y) const\n{\n\tcout << \"Compute comparison polynomial\" << endl;\n\t\n\tCtxt Y = ctxt_x;\n\t// x - y\n\tY -= ctxt_y;\n\t// Y = y(x-y)\n\tY.multiplyBy(ctxt_y);\n\n\tCtxt x_plus_1 = ctxt_x;\n\t// x+1\n\tx_plus_1.addConstant(ZZ(1));\n\n\tunsigned long p = m_context.getP();\n\n\tunsigned long y_powers = ((p-3) >> 1);\n\t//powers of x\n\tDynamicCtxtPowers x_powers(ctxt_x, p-3);\n\t//powers of Y\n\tDynamicCtxtPowers Y_powers(Y, y_powers);\n\tCtxt Ypow(m_pk);\n\n\tCtxt fx(m_pk);\n\n\tvector<ZZX> fpolys(y_powers);\n\tfor (size_t iPoly = 0; iPoly < y_powers; iPoly++)\n\t{\n\t\tfor (size_t iCoef = 0; iCoef < fcoefs[p][iPoly].size(); iCoef++)\n\t\t{\n\t\t\tSetCoeff(fpolys[iPoly], iCoef+1, fcoefs[p][iPoly][iCoef]);\t\n\t\t}\n\t\tif(iPoly == 0)\n\t\t{\n\t\t\tsimplePolyEval(ctxt_res, fpolys[iPoly], x_powers);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tsimplePolyEval(fx, fpolys[iPoly], x_powers);\n\t\t\tYpow = Y_powers.getPower(iPoly);\n\t\t\tfx.multiplyBy(Ypow);\n\t\t\tctxt_res += fx;\n\t\t}\n\t}\n\n\t// c*Y^y_powers\n\tfx = Y_powers.getPower(y_powers);\n\tfx.multByConstant(ZZ(fcoefs[p][y_powers][0]));\n\tctxt_res += fx;\n\t\n\t// (x+1)*f(x)\n\tctxt_res.multiplyBy(x_plus_1);\n\t// Y*(x+1)*f(x)\n\tctxt_res.multiplyBy(Y);\n\t\n\tif(m_verbose)\n\t{\n\t\tprint_decrypted(ctxt_res);\n\t\tcout << endl;\n\t}\n}\n\nvoid Comparator::evaluate_univar_less_poly(Ctxt& ret, Ctxt& ctxt_p_1, const Ctxt& x) const\n{\n\tHELIB_NTIMER_START(ComparisonCircuitUnivar);\n\t// get p\n\tZZ p = ZZ(m_context.getP());\n\n\tif (p > ZZ(3)) //if p > 3, use the generic Paterson-Stockmeyer strategy\n\t{\n\t  // z^2\n\t  \tCtxt x2 = x;\n\t  \tx2.square();\n\n\t\tDynamicCtxtPowers babyStep(x2, m_bs_num_comp);\n\t\tconst Ctxt& x2k = babyStep.getPower(m_bs_num_comp);\n\n\t\tDynamicCtxtPowers giantStep(x2k, m_gs_num_comp);\n\n\t\t// Special case when #giant_steps is a power of two\n\t\tif (m_gs_num_comp == (1L << NextPowerOfTwo(m_gs_num_comp))) \n\t\t{\n\t\t\t//cout << \"I'm computing degPowerOfTwo\" << endl;\n\t    \tdegPowerOfTwo(ret, m_univar_less_poly, m_bs_num_comp, babyStep, giantStep);\n\t    }\n\t    else\n\t    {\n\t\t  \trecursivePolyEval(ret, m_univar_less_poly, m_bs_num_comp, babyStep, giantStep);\n\n\t\t  \tif (!IsOne(m_top_coef_comp)) \n\t\t  \t{\n\t\t    \tret.multByConstant(m_top_coef_comp);\n\t\t\t}\n\n\t\t\tif (!IsZero(m_extra_coef_comp)) \n\t\t\t{ // if we added a term, now is the time to subtract back\n\t\t    \tCtxt topTerm = giantStep.getPower(m_gs_num_comp);\n\t\t    \ttopTerm.multByConstant(m_extra_coef_comp);\n\t\t    \tret -= topTerm;\n\t\t\t}\n\t\t}\n\t\tret.multiplyBy(x);\n\n\t\t// TODO: depth here is not optimal\n\t\tCtxt top_term = babyStep.getPower(m_baby_index);\n\t\ttop_term.multiplyBy(giantStep.getPower(m_giant_index));\n\n\t\tctxt_p_1 = top_term; \n\n\t\ttop_term.multByConstant(ZZ((p+1)>> 1));\n\n\t\tret += top_term;\n\n\t\t/*\n\t\tcout << \"Computed baby steps\" << endl;\n\t\tfor(int i = 0; i < babyStep.size(); i++)\n\t\t{\n\t\t\tcout << i + 1 << ' ' << babyStep.isPowerComputed(i+1) << endl; \n\t\t}\n\n\t\tcout << \"Computed giant steps\" << endl;\n\t\tfor(int i = 0; i < giantStep.size(); i++)\n\t\t{\n\t\t\tcout << i + 1 << ' ' << giantStep.isPowerComputed(i+1) << endl;\n\t\t}\n\t\t*/\n\t}\n\telse //circuit for p=3\n\t{\n\t\tret = x;\n\n\t\tctxt_p_1 = x;\n\t\tctxt_p_1.square();\n\n\t\tCtxt top_term = ctxt_p_1;\n\t\ttop_term.multByConstant(ZZ(2));\n\n\t\tret += top_term;\n\t}\n\tHELIB_NTIMER_STOP(ComparisonCircuitUnivar);\n}\n\nvoid Comparator::evaluate_min_max_poly(Ctxt& ctxt_min, Ctxt& ctxt_max, const Ctxt& ctxt_x, const Ctxt& ctxt_y) const\n{\n\tHELIB_NTIMER_START(MinMaxCircuitUnivar);\n\t// get p\n\tZZ p = ZZ(m_context.getP());\n\n\t// Subtraction z = x - y\n\tcout << \"Subtraction\" << endl;\n\tCtxt ctxt_z = ctxt_x;\n\tctxt_z -= ctxt_y;\n\n\tif(m_verbose)\n\t{\n\t\tprint_decrypted(ctxt_z);\n\t\tcout << endl;\n\t}\n  \t\n  \t// z^2\n  \tCtxt ctxt_z2 = ctxt_z;\n  \tctxt_z2.square(); \n\n\tif (p > ZZ(3)) //if p > 3, use the generic Paterson-Stockmeyer strategy\n\t{\n\t\tDynamicCtxtPowers babyStep(ctxt_z2, m_bs_num_min);\n\t\tconst Ctxt& ctxt_z2k = babyStep.getPower(m_bs_num_min);\n\n\t\tDynamicCtxtPowers giantStep(ctxt_z2k, m_gs_num_min);\n\n\t\t// compute g(z^2)\n\t\tCtxt g_z2 = Ctxt(ctxt_z2.getPubKey());;\n\t\t// Special case when #giant_steps is a power of two\n\t\tif (m_gs_num_min == (1L << NextPowerOfTwo(m_gs_num_min))) \n\t\t{\n\t\t\t//cout << \"I'm computing degPowerOfTwo\" << endl;\n\t    \tdegPowerOfTwo(g_z2, m_univar_min_max_poly, m_bs_num_min, babyStep, giantStep);\n\t    }\n\t    else\n\t    {\n\t\t  \trecursivePolyEval(g_z2, m_univar_min_max_poly, m_bs_num_min, babyStep, giantStep);\n\n\t\t  \tif (!IsOne(m_top_coef_min)) \n\t\t  \t{\n\t\t    \tg_z2.multByConstant(m_top_coef_min);\n\t\t\t}\n\n\t\t\tif (!IsZero(m_extra_coef_min)) \n\t\t\t{ // if we added a term, now is the time to subtract back\n\t\t    \tCtxt topTerm = giantStep.getPower(m_gs_num_min);\n\t\t    \ttopTerm.multByConstant(m_extra_coef_min);\n\t\t    \tg_z2 -= topTerm;\n\t\t\t}\n\t\t}\n\n\t\t// last term: ((p+1)/2) * (x + y) \n\t\tCtxt last_term = ctxt_x;\n\t\tlast_term += ctxt_y; \n\t\tlast_term.multByConstant(ZZ((p+1)>> 1));\n\n\t\tctxt_min = last_term;\n\t\tctxt_min += g_z2;\n\t\tctxt_max = last_term;\n\t\tctxt_max -= g_z2;\n\n\t\t/*\n\t\tcout << \"Computed baby steps\" << endl;\n\t\tfor(int i = 0; i < babyStep.size(); i++)\n\t\t{\n\t\t\tcout << i + 1 << ' ' << babyStep.isPowerComputed(i+1) << endl; \n\t\t}\n\n\t\tcout << \"Computed giant steps\" << endl;\n\t\tfor(int i = 0; i < giantStep.size(); i++)\n\t\t{\n\t\t\tcout << i + 1 << ' ' << giantStep.isPowerComputed(i+1) << endl;\n\t\t}\n\t\t*/\n\t}\n\telse //circuit for p=3\n\t{\n\t\t// last term: ((p+1)/2) * (x + y) \n\t\tCtxt last_term = ctxt_x;\n\t\tlast_term += ctxt_y; \n\t\tlast_term.multByConstant(ZZ((p+1)>> 1));\n\n\t\tctxt_min = last_term;\n\t\tctxt_min += ctxt_z2;\n\t\tctxt_max = last_term;\n\t\tctxt_max -= ctxt_z2;\n\t}\n\tHELIB_NTIMER_STOP(MinMaxCircuitUnivar);\n}\n\nvoid Comparator::less_than_bivar(Ctxt& ctxt_res, const Ctxt& ctxt_x, const Ctxt& ctxt_y) const\n{\n  HELIB_NTIMER_START(ComparisonCircuitBivar);\n\n  //compare with the circuit of Tan et al.\n  if (m_type == TAN)\n  {\n  \tless_than_bivar_tan(ctxt_res, ctxt_x, ctxt_y);\n  \treturn;\n  }\n\n  unsigned long p = m_context.getP();\n\n  if(p > 31)\n  {\n  \tthrow helib::LogicError(\"Bivariate circuit is not implemented for p > 31\");\n  }\n\n  if(p == 2)\n  {\n    less_than_mod_2(ctxt_res, ctxt_x, ctxt_y);\n  }\n  \n  if(p == 3)\n  {\n  \tless_than_mod_3(ctxt_res, ctxt_x, ctxt_y);\n  }\n\n  if(p == 5)\n  {\n  \tless_than_mod_5(ctxt_res, ctxt_x, ctxt_y);\n  }\n\n  if(p == 7)\n  {\n  \tless_than_mod_7(ctxt_res, ctxt_x, ctxt_y);\n  }\n\n  if(p > 7)\n  {\n    less_than_mod_any(ctxt_res, ctxt_x, ctxt_y);\n  }\n\n  if(m_verbose)\n  {\n    print_decrypted(ctxt_res);\n    cout << endl;\n  }\n\n  HELIB_NTIMER_STOP(ComparisonCircuitBivar);\n}\n\nvoid Comparator::less_than_bivar_tan(Ctxt& ctxt_res, const Ctxt& ctxt_x, const Ctxt& ctxt_y) const\n{\n\tcout << \"Compute Tan's comparison polynomial\" << endl;\n\n\tlong p = m_context.getP();\n\n\tDynamicCtxtPowers x_powers(ctxt_x, p-1);\n\tDynamicCtxtPowers y_powers(ctxt_y, p-1);\n\n\tctxt_res = y_powers.getPower(p-1);\n\n\tfor (long i = 1; i < p; i++)\n\t{\n\t\t// zero ciphertext\n\t\tCtxt sum = Ctxt(ctxt_x.getPubKey());\n\t\tfor (long j = 1; j < p; j++)\n\t\t{\n\t\t\tif (m_bivar_less_coefs[i][j] == ZZ(0))\n\t\t\t\tcontinue;\n\t\t\tCtxt tmp = y_powers.getPower(j);\n\t\t\ttmp.multByConstant(m_bivar_less_coefs[i][j]);\n\t\t\tsum += tmp;\n\t\t}\n\t\tsum.multiplyBy(x_powers.getPower(i));\n\t\tctxt_res += sum;\n\t}\n}\n\nvoid Comparator::is_zero(Ctxt& ctxt_res, const Ctxt& ctxt_z, long pow) const\n{\n  HELIB_NTIMER_START(EqualityCircuit);\n\n  ctxt_res = ctxt_z;\n\n  //compute mapTo01: (z_i)^{p^d-1}\n  //cout << \"Mapping to 0 and 1\" << endl;\n  mapTo01_subfield(ctxt_res, pow);\n\n  if(m_verbose)\n  {\n    print_decrypted(ctxt_res);\n    cout << endl;\n  }\n\n  //cout << \"Computing NOT\" << endl;\n  //compute 1 - mapTo01(z_i)\n  ctxt_res.negate();\n  ctxt_res.addConstant(ZZ(1));\n\n  if(m_verbose)\n  {\n    print_decrypted(ctxt_res);\n    cout << endl;\n  }\n\n  HELIB_NTIMER_STOP(EqualityCircuit);\n}\n\nvoid Comparator::compare(Ctxt& ctxt_res, const Ctxt& ctxt_x, const Ctxt& ctxt_y) const\n{\n\tHELIB_NTIMER_START(Comparison);\n\n\tvector<Ctxt> ctxt_less_p;\n\tvector<Ctxt> ctxt_eq_p;\n\n\t// bivariate circuit\n\tif (m_type == BI || m_type == TAN)\n\t{\n\t\t//cout << \"Extraction\" << endl;\n\t\t// extract mod p coefficients\n\t\tvector<Ctxt> ctxt_x_p;\n\t\textract_mod_p(ctxt_x_p, ctxt_x);\n\n\t\tif(m_verbose)\n\t    {\n\t    \tfor (long iCoef = 0; iCoef < m_slotDeg; iCoef++)\n\t    \t{\n\t    \t\tcout << \"Ctxt x with coefficient \" << iCoef << endl;\n\t\t    \tprint_decrypted(ctxt_x_p[iCoef]);\n\t\t    \tcout << endl;\n\t\t    }\n\t\t}\n\n\t\tvector<Ctxt> ctxt_y_p;\n\t\textract_mod_p(ctxt_y_p, ctxt_y);\n\n\t\tif(m_verbose)\n\t    {\n\t    \tfor (long iCoef = 0; iCoef < m_slotDeg; iCoef++)\n\t    \t{\n\t    \t\tcout << \"Ctxt y with coefficient \" << iCoef << endl;\n\t\t    \tprint_decrypted(ctxt_y_p[iCoef]);\n\t\t    \tcout << endl;\n\t\t    }\n\t\t}\n\n\t\t//cout << \"Compute the less-than function modulo p\" << endl;\n\t\tfor (long iCoef = 0; iCoef < m_slotDeg; iCoef++)\n\t\t{\n\t\t\tCtxt ctxt_tmp = Ctxt(ctxt_x.getPubKey());\n\t\t\tless_than_bivar(ctxt_tmp, ctxt_x_p[iCoef], ctxt_y_p[iCoef]);\n\t\t\tctxt_less_p.push_back(ctxt_tmp);\n\t\t}\n\n\t\t//cout << \"Compute the equality function modulo p\" << endl;\n\t\tfor (long iCoef = 0; iCoef < m_slotDeg; iCoef++)\n\t\t{\n\t\t\t// Subtraction z = x - y\n\t\t\t//cout << \"Subtraction\" << endl;\n\t\t\tCtxt ctxt_z = ctxt_x_p[iCoef];\n\t\t\tctxt_z -= ctxt_y_p[iCoef];\n\t\t\tCtxt ctxt_tmp = Ctxt(ctxt_z.getPubKey());\n\t\t\tis_zero(ctxt_tmp, ctxt_z);\n\t\t\tctxt_eq_p.push_back(ctxt_tmp);\n\t\t}\n\t}\n\telse // univariate circuit\n\t{\n\t\t// Subtraction z = x - y\n\t\t//cout << \"Subtraction\" << endl;\n\t\tCtxt ctxt_z = ctxt_x;\n\t\tctxt_z -= ctxt_y;\n\n\t\tif(m_verbose)\n\t\t{\n\t\t\tprint_decrypted(ctxt_z);\n\t\t\tcout << endl;\n\t\t}\n\n\t\t// extract mod p coefficients\n\t\t//cout << \"Extraction\" << endl;\n\t\tvector<Ctxt> ctxt_z_p;\n\t\textract_mod_p(ctxt_z_p, ctxt_z);\n\n\t\tif(m_verbose)\n\t    {\n\t    \tfor (long iCoef = 0; iCoef < m_slotDeg; iCoef++)\n\t    \t{\n\t    \t\tcout << \"Ctxt x with coefficient \" << iCoef << endl;\n\t\t    \tprint_decrypted(ctxt_z_p[iCoef]);\n\t\t    \tcout << endl;\n\t\t    }\n\t\t}\n\n\t\t//cout << \"Compute the less-than and equality functions modulo p\" << endl;\n\t\tfor (long iCoef = 0; iCoef < m_slotDeg; iCoef++)\n\t\t{\n\t\t\tCtxt ctxt_tmp = Ctxt(ctxt_z.getPubKey());\n\t\t\tCtxt ctxt_tmp_eq = Ctxt(ctxt_z.getPubKey());\n\n\t\t\t// compute polynomial function for 'z < 0'\n\t\t\t//cout << \"Compute univariate comparison polynomial\" << endl;\n\t\t\tevaluate_univar_less_poly(ctxt_tmp, ctxt_tmp_eq, ctxt_z_p[iCoef]);\n\n\t\t\tif(m_verbose)\n\t\t\t{\n\t\t\t  cout << \"Result of the less-than function\" << endl;\n\t\t\t  print_decrypted(ctxt_tmp);\n\t\t\t  cout << endl;\n\t\t\t}\n\n\t\t\tctxt_less_p.push_back(ctxt_tmp);\n\n\t\t\t//cout << \"Computing NOT\" << endl;\n\t\t\t//compute 1 - mapTo01(r_i*(x_i - y_i))\n\t\t\tctxt_tmp_eq.negate();\n\t\t\tctxt_tmp_eq.addConstant(ZZ(1));\n\n\t\t\tif(m_verbose)\n\t\t\t{\n\t\t\t  cout << \"Result of the equality function\" << endl;\n\t\t\t  print_decrypted(ctxt_tmp_eq);\n\t\t\t  cout << endl;\n\t\t\t}\n\n\t\t\tctxt_eq_p.push_back(ctxt_tmp_eq);\n\t\t}\t\n\t}\n\n\t//cout << \"Compare digits\" << endl;\n\tCtxt ctxt_less = ctxt_less_p[m_slotDeg-1];\n\tCtxt ctxt_eq = ctxt_eq_p[m_slotDeg-1];\n\n\tfor (long iCoef = m_slotDeg-2; iCoef >= 0; iCoef--)\n\t{\n\t\tCtxt tmp = ctxt_eq;\n\t\ttmp.multiplyBy(ctxt_less_p[iCoef]);\n\t\tctxt_less += tmp;\n\n\t\tctxt_eq.multiplyBy(ctxt_eq_p[iCoef]);\n\t}\n\n\tif(m_verbose)\n\t{\n\t\tcout << \"Comparison results\" << endl;\n\t\tprint_decrypted(ctxt_less);\n\t\tcout << endl;\n\n\t\tcout << \"Equality results\" << endl;\n\t\tprint_decrypted(ctxt_eq);\n\t\tcout << endl;\n\t}\n\n\tif(m_expansionLen == 1)\n\t{\n\t\tctxt_res = ctxt_less;\n\t\treturn;\n\t}\n\n\n\t//compute running products: prod_i 1 - (x_i - y_i)^{p^d-1}\n\t//cout << \"Rotating and multiplying slots with equalities\" << endl;\n\tshift_and_mul(ctxt_eq, 0);\n\n\tif(m_verbose)\n\t{\n\t\tprint_decrypted(ctxt_eq);\n\t\tcout << endl;\n\t}\n\n\t//Remove the least significant digit and shift to the left\n\t//cout << \"Remove the least significant digit\" << endl;\n\tbatch_shift_for_mul(ctxt_eq, 0, -1);\n\n\tif(m_verbose)\n\t{\n\t\tprint_decrypted(ctxt_eq);\n\t\tcout << endl;\n\t}\n\n\t//cout << \"Final result\" << endl;\n\n\tctxt_res = ctxt_eq;\n\tctxt_res.multiplyBy(ctxt_less);\n\tshift_and_add(ctxt_res, 0);\n\n\tif(m_verbose)\n\t{\n\t\tprint_decrypted(ctxt_res);\n\t\tcout << endl;\n\t}\n\n\tif(m_verbose)\n    {\n      cout << \"Input x: \" << endl;\n      print_decrypted(ctxt_x);\n      cout << endl;\n      cout << \"Input y: \" << endl;\n      print_decrypted(ctxt_y);\n      cout << endl;\n    }\t\n\n    HELIB_NTIMER_STOP(Comparison);\n}\n\nvoid Comparator::min_max_digit(Ctxt& ctxt_min, Ctxt& ctxt_max, const Ctxt& ctxt_x, const Ctxt& ctxt_y) const\n{\n\tHELIB_NTIMER_START(MinMaxDigit);\n\tif(m_type != UNI)\n\t\tthrow helib::LogicError(\"Min/Max is not implemented with the bivariate circuit\");\n\n\tif(m_expansionLen != 1 || m_slotDeg != 1)\n\t\tthrow helib::LogicError(\"Min/Max is not implemented for vectors over F_p\");\n\n\t// get EncryptedArray\n  \tconst EncryptedArray& ea = m_context.getEA();\n  \t//extract slots\n\tlong nSlots = ea.size();\n\n\tvector<Ctxt> ctxt_min_p;\n\tvector<Ctxt> ctxt_max_p;\n\n\t// extract mod p coefficients\n\tcout << \"Extraction\" << endl;\n\tvector<Ctxt> ctxt_x_p;\n\textract_mod_p(ctxt_x_p, ctxt_x);\n\n\tif(m_verbose)\n    {\n    \tfor (long iCoef = 0; iCoef < m_slotDeg; iCoef++)\n    \t{\n    \t\tcout << \"Ctxt x with coefficient \" << iCoef << endl;\n\t    \tprint_decrypted(ctxt_x_p[iCoef]);\n\t    \tcout << endl;\n\t    }\n\t}\n\n\tvector<Ctxt> ctxt_y_p;\n\textract_mod_p(ctxt_y_p, ctxt_y);\n\n\tif(m_verbose)\n    {\n    \tfor (long iCoef = 0; iCoef < m_slotDeg; iCoef++)\n    \t{\n    \t\tcout << \"Ctxt y with coefficient \" << iCoef << endl;\n\t    \tprint_decrypted(ctxt_y_p[iCoef]);\n\t    \tcout << endl;\n\t    }\n\t}\n\n\tcout << \"Compute min/max functions modulo p\" << endl;\n\tfor (long iCoef = 0; iCoef < m_slotDeg; iCoef++)\n\t{\n\t\tCtxt ctxt_tmp_min = Ctxt(ctxt_x.getPubKey());\n\t\tCtxt ctxt_tmp_max = Ctxt(ctxt_x.getPubKey());\n\n\t\t// compute polynomial function for 'z < 0'\n\t\tcout << \"Compute univariate min/max polynomial\" << endl;\n\t\tevaluate_min_max_poly(ctxt_tmp_min, ctxt_tmp_max, ctxt_x_p[iCoef], ctxt_y_p[iCoef]);\n\n\t\tif(m_verbose)\n\t\t{\n\t\t  cout << \"Result of the min function\" << endl;\n\t\t  print_decrypted(ctxt_tmp_min);\n\t\t  cout << endl;\n\t\t}\n\n\t\tif(m_verbose)\n\t\t{\n\t\t  cout << \"Result of the max function\" << endl;\n\t\t  print_decrypted(ctxt_tmp_max);\n\t\t  cout << endl;\n\t\t}\n\n\t\tctxt_min_p.push_back(ctxt_tmp_min);\n\t\tctxt_max_p.push_back(ctxt_tmp_max);\n\t}\n\n\tctxt_min = ctxt_min_p[0];\n\tctxt_max = ctxt_max_p[0];\n\n\tfor (long iCoef = 1; iCoef < m_slotDeg; iCoef++)\n\t{\n\t\tvector<ZZX> x_power(nSlots, ZZX(INIT_MONO, iCoef, 1));\n\t\tZZX x_power_ptxt;\n\t\tea.encode(x_power_ptxt, x_power);\n\n\t\t// agregate minimum values\n\t\tCtxt tmp = ctxt_min_p[iCoef];\n\t\ttmp.multByConstant(x_power_ptxt);\n\t\tctxt_min += tmp;\n\n\t\t// agregate maximum values\n\t\ttmp = ctxt_max_p[iCoef];\n\t\ttmp.multByConstant(x_power_ptxt);\n\t\tctxt_max += tmp;\n\t}\n\n\tHELIB_NTIMER_STOP(MinMaxDigit);\n}\n\nvoid Comparator::min_max(Ctxt& ctxt_min, Ctxt& ctxt_max, const Ctxt& ctxt_x, const Ctxt& ctxt_y) const\n{\n\tHELIB_NTIMER_START(MinMax);\n\tif(m_type == UNI && m_expansionLen == 1 && m_slotDeg == 1)\n\t{\n\t\tmin_max_digit(ctxt_min, ctxt_max, ctxt_x, ctxt_y);\n\t\treturn;\n\t}\n\n\tCtxt ctxt_z = ctxt_x;\n\tctxt_z -= ctxt_y;\n\n\tCtxt ctxt_tmp = Ctxt(ctxt_z.getPubKey());\n\tcompare(ctxt_tmp, ctxt_x, ctxt_y);\n\tctxt_tmp.multiplyBy(ctxt_z);\n\n\tctxt_min = ctxt_y;\n\tctxt_min += ctxt_tmp;\n\n\tctxt_max = ctxt_x;\n\tctxt_max -= ctxt_tmp;\n\n\tif(m_verbose)\n\t{\n\t\tcout << \"Minimum\" << endl;\n\t\tprint_decrypted(ctxt_min);\n\t\tcout << endl;\n\t}\n\n\tif(m_verbose)\n\t{\n\t\tcout << \"Maximum\" << endl;\n\t\tprint_decrypted(ctxt_max);\n\t\tcout << endl;\n\t}\n\n\tif(m_verbose)\n    {\n      cout << \"Input x: \" << endl;\n      print_decrypted(ctxt_x);\n      cout << endl;\n      cout << \"Input y: \" << endl;\n      print_decrypted(ctxt_y);\n      cout << endl;\n    }\n\tHELIB_NTIMER_STOP(MinMax);\n}\n\nvoid Comparator::array_min(Ctxt& ctxt_res, const vector<Ctxt>& ctxt_in, long depth) const\n{\n\tHELIB_NTIMER_START(ArrayMin);\n\n\tif (depth < 0)\n\t\tthrow helib::LogicError(\"depth parameter must be non-negative\");\n\n\tcout << \"Computing the minimum of an array\" << endl;\n\n\tsize_t input_len = ctxt_in.size();\n\n\tvector<Ctxt> ctxt_res_vec;\n\tfor (size_t i  = 0; i < input_len; i++)\n\t{\n\t\tctxt_res_vec.push_back(ctxt_in[i]);\n\t}\n\n\tsize_t cur_len = input_len;\n\tlong level = depth;\n\n\twhile(cur_len > 1 && level > 0)\n\t{\n\t\tcout << \"Comparison level: \" << depth-level << endl;\n\t\t// compare x[i] and x[n-1-i] where n is the length of ctxt_res_vec\n\t\tfor (size_t i  = 0; i < (cur_len >> 1); i++)\n\t\t{\n\t\t\tif(i != cur_len -  1 - i)\n\t\t\t{\n\t\t\t\tcout << \"Comparing ciphertexts \" << i << \" and \" << cur_len -  1 - i << endl;\n\t\t\t\tmin_max(ctxt_res_vec[i], ctxt_res_vec[cur_len -  1 - i], ctxt_res_vec[i], ctxt_res_vec[cur_len -  1 - i]);\n\t\t\t}\n\t\t}\n\t\tcur_len = (cur_len >> 1) + (cur_len % 2);\n\t\tctxt_res_vec.resize(cur_len, Ctxt(m_pk));\n\t\tlevel--;\n\t}\n\n\tif(cur_len > 1)\n\t{\n\t\t// plaintext modulus\n  \t\tlong p = m_context.getP();\n\t\t// multiplications in the equality circuit\n\t\tlong eq_mul_num = static_cast<long>(floor(log2(p-1))) + weight(ZZ(p-1)) - 1;\n\t\tlong eq_depth = static_cast<long>(ceil(log2(p-1)));\n\t\tlong prod_depth = static_cast<long>(ceil(log2(cur_len-1)));\n\n\t\tif ((((cur_len - 2 > eq_mul_num) && (eq_depth == prod_depth)) || (eq_depth < prod_depth)) && cur_len <= p)\n\t\t{\n\t\t\tcout << \"Computing minimum via equality\" << endl;\n\t\t\tcout << \"Mult. of equality: \" << eq_mul_num << endl;\n\t\t\tcout << \"Depth of equality: \" << eq_depth << endl;\n\t\t\tcout << \"Depth of product: \" << prod_depth << endl;\n\t\t\t// create a table with all pairwise comparisons and compute the Hamming weight of every row\n\t\t\tvector<Ctxt> ham_weights;\n\t\t\tget_sorting_index(ham_weights, ctxt_res_vec);\n\n\t\t\tcout << \"Computing the minimum\" << endl;\n\t\t\tctxt_res = Ctxt(m_pk);\n\t\t\tfor(size_t i = 0; i < ctxt_res_vec.size(); i++)\n\t\t\t{\n\t\t\t\t//compare the Hamming weight of the jth row with i\n\t\t\t\tCtxt tmp_prod = ham_weights[i];\n\t\t\t\ttmp_prod.addConstant(ZZX(-(cur_len-1)));\n\t\t\t\tmapTo01_subfield(tmp_prod, 1);\n\t\t\t\ttmp_prod.negate();\n\t\t\t\ttmp_prod.addConstant(ZZX(1));\n\n\t\t\t\t//multiply by the jth input ciphertext\n\t\t\t\ttmp_prod.multiplyBy(ctxt_res_vec[i]);\n\t\t\t\tif(i == 0)\n\t\t\t\t\tctxt_res = tmp_prod;\n\t\t\t\telse\n\t\t\t\t\tctxt_res += tmp_prod;\n\t\t\t}\n\t\t}\n\t\telse \n\t\t{\n\t\t\tcout << \"Computing minimum via punctured products\" << endl;\n\t\t\tcout << \"Mult. of equality: \" << eq_mul_num << endl;\n\t\t\tcout << \"Depth of equality: \" << eq_depth << endl;\n\t\t\tcout << \"Depth of product: \" << prod_depth << endl;\n\t\t\tvector<vector<Ctxt>> ctxt_products;\n\t\t\t// compute the product of every row\n\t\t\tfor(size_t i = 0; i < ctxt_res_vec.size(); i++)\n\t\t\t{\n\t\t\t\tvector<Ctxt> ctxt_vec;\n\t\t\t\tctxt_products.push_back(ctxt_vec);\n\t\t\t}\n\n\t\t\tcout << \"Computing the comparison table\" << endl;\n\t\t\tfor (size_t i = 0; i < ctxt_res_vec.size() - 1; i++)\n\t\t\t{\n\t\t\t\tcout << \"Computing Row \" << i << endl;\n\t\t\t\tfor(size_t j = i + 1; j < ctxt_res_vec.size(); j++)\n\t\t\t\t{\n\t\t\t\t\tcout << \"Computing Column \" << j << endl;\n\t\t\t\t\t// compute upper diagonal entries of the comparison table and multiply them\n\t\t\t\t\tCtxt comp_col = Ctxt(m_pk);\n\t\t\t\t\tcompare(comp_col, ctxt_res_vec[i], ctxt_res_vec[j]);\n\n\t\t\t\t\tif (ctxt_products[i].empty())\n\t\t\t\t\t{\n\t\t\t\t\t\tctxt_products[i].push_back(comp_col);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tlong wt = weight(ZZ(j));\n\t\t\t\t\t\tint len_i = ctxt_products[i].size();\n\t\t\t\t\t\tif (wt > len_i)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tctxt_products[i].push_back(comp_col);\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\tctxt_products[i][len_i - 1].multiplyBy(comp_col);\n\t\t\t\t\t\t\tfor (int k = len_i - 2; k >= (wt-1); k--)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tctxt_products[i][k].multiplyBy(ctxt_products[i][k+1]);\n\t\t\t\t\t\t\t\tctxt_products[i].pop_back();\t\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\t// compute lower diagonal entries of the comparison table by transposition and logical negation of upper diagonal entries\n\t\t\t\t\t//NOT the result to multiply to the jth row\n\t\t\t\t\tcomp_col.negate();\n\t\t\t\t\tcomp_col.addConstant(ZZ(1));\n\n\t\t\t\t\tif (ctxt_products[j].empty())\n\t\t\t\t\t{\n\t\t\t\t\t\tctxt_products[j].push_back(comp_col);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tlong wt = weight(ZZ(i+1));\n\t\t\t\t\t\tint len_j = ctxt_products[j].size();\n\t\t\t\t\t\tif (wt > len_j)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tctxt_products[j].push_back(comp_col);\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\tctxt_products[j][len_j - 1].multiplyBy(comp_col);\n\t\t\t\t\t\t\tfor (int k = len_j - 2; k >= (wt-1); k--)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tctxt_products[j][k].multiplyBy(ctxt_products[j][k+1]);\n\t\t\t\t\t\t\t\tctxt_products[j].pop_back();\t\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcout << \"Computing the minimum\" << endl;\n\t\t\tctxt_res = Ctxt(m_pk);\n\t\t\tfor(size_t i = 0; i < ctxt_res_vec.size(); i++)\n\t\t\t{\n\t\t\t\tint len_i = ctxt_products[i].size();\n\t\t\t\tfor (int k = len_i - 2; k >= 0; k--)\n\t\t\t\t{\n\t\t\t\t\tctxt_products[i][k].multiplyBy(ctxt_products[i][k+1]);\n\t\t\t\t\tctxt_products[i].pop_back();\t\n\t\t\t\t}\n\t\t\t\tCtxt tmp_prod = ctxt_products[i][0];\n\n\t\t\t\t//multiply by the ith input ciphertext\n\t\t\t\ttmp_prod.multiplyBy(ctxt_res_vec[i]);\n\n\t\t\t\t//add to the result\n\t\t\t\tctxt_res += tmp_prod;\n\t\t\t}\n\t\t}\n\t}\n\telse\n\t{\n\t\tctxt_res = ctxt_res_vec[0];\n\t}\n\n\tHELIB_NTIMER_STOP(ArrayMin);\n}\n\nvoid Comparator::int_to_slot(ZZX& poly, unsigned long input, unsigned long enc_base) const\n{ \n    vector<long> decomp;\n\n    //decomposition of a digit\n    digit_decomp(decomp, input, enc_base, m_slotDeg);\n    poly = ZZX(INIT_MONO, 0, 0);\n    for (int iCoef = 0; iCoef < m_slotDeg; iCoef++)\n    {\n        poly+=ZZX(INIT_MONO, iCoef, decomp[iCoef]);\n    }\n}\n\nvoid Comparator::get_sorting_index(vector<Ctxt>& ctxt_out, const vector<Ctxt>& ctxt_in) const\n{\n\tctxt_out.clear();\n\n\t// length of the input vector\n\tsize_t input_len = ctxt_in.size();\n\n\t// plaintext modulus\n  \tlong p = m_context.getP();\n\n\tif (input_len > p)\n\t\tthrow helib::LogicError(\"The number of ciphertexts cannot be larger than the plaintext modulus\");\n\n\t// compute the Hamming weight of every row\n\tfor(size_t i = 0; i < input_len; i++)\n\t{\n\t\t//initialize Hamming weights to zero\n\t\tCtxt ctxt_tmp = Ctxt(ctxt_in[0].getPubKey());\n\t\tctxt_out.push_back(ctxt_tmp);\n\t}\n\n\tcout << \"Computing the comparison table\" << endl;\n\tfor (size_t i = 0; i < input_len - 1; i++)\n\t{\n\t\tcout << \"Computing Row \" << i << endl;\n\t\tfor(size_t j = i + 1; j < input_len; j++)\n\t\t{\n\t\t\tcout << \"Computing Column \" << j << endl;\n\t\t\t// compute upper diagonal entries of the comparison table and sum them\n\t\t\tCtxt comp_col_j = Ctxt(ctxt_in[0].getPubKey());\n\t\t\tcompare(comp_col_j, ctxt_in[i], ctxt_in[j]);\n\t\t\tctxt_out[i] += comp_col_j;\n\n\t\t\t// compute lower diagonal entries of the comparison table by transposition and logical negation of upper diagonal entries\n\t\t\t//NOT the result to add to the jth row\n\t\t\tcomp_col_j.negate();\n\t\t\tcomp_col_j.addConstant(ZZ(1));\n\n\t\t\t// add lower diagonal entries to Hamming weight accumulators of related rows\n\t\t\tctxt_out[j] += comp_col_j;\n\t\t}\n\t}\n}\n\nvoid Comparator::sort(vector<Ctxt>& ctxt_out, const vector<Ctxt>& ctxt_in) const\n{\n\tHELIB_NTIMER_START(Sorting);\n\n\tctxt_out.clear();\n\n\t// length of the input vector\n\tsize_t input_len = ctxt_in.size();\n\n\t// plaintext modulus\n  \tlong p = m_context.getP();\n\n\tif (input_len > p)\n\t\tthrow helib::LogicError(\"The number of ciphertexts cannot be larger than the plaintext modulus\");\n\n\t// multiplications in the equality circuit\n\tlong eq_mul_num = static_cast<long>(floor(log2(p-1))) + weight(ZZ(p-1)) - 1;\n\tcout << \"Multiplications in the equality circuit: \" << eq_mul_num << endl;\n\n\t// create a table with all pairwise comparisons and compute the Hamming weight of every row\n\tvector<Ctxt> ham_weights;\n\n\tget_sorting_index(ham_weights, ctxt_in);\n\t/*\n\tfor(size_t i = 0; i < input_len; i++)\n\t{\n\t\t//initialize Hamming weights to zero\n\t\tCtxt ctxt_tmp = Ctxt(ctxt_in[0].getPubKey());\n\t\tham_weights.push_back(ctxt_tmp);\n\t}\n\n\tcout << \"Computing the comparison table\" << endl;\n\tfor (size_t i = 0; i < input_len - 1; i++)\n\t{\n\t\tcout << \"Computing Row \" << i << endl;\n\t\tfor(size_t j = i + 1; j < input_len; j++)\n\t\t{\n\t\t\tcout << \"Computing Column \" << j << endl;\n\t\t\t// compute upper diagonal entries of the comparison table and sum them\n\t\t\tCtxt comp_col_j = Ctxt(ctxt_in[0].getPubKey());\n\t\t\tcompare(comp_col_j, ctxt_in[i], ctxt_in[j]);\n\t\t\tham_weights[i] += comp_col_j;\n\n\t\t\t// compute lower diagonal entries of the comparison table by transposition and logical negation of upper diagonal entries\n\t\t\t//NOT the result to add to the jth row\n\t\t\tcomp_col_j.negate();\n\t\t\tcomp_col_j.addConstant(ZZ(1));\n\n\t\t\t// add lower diagonal entries to Hamming weight accumulators of related rows\n\t\t\tham_weights[j] += comp_col_j;\n\t\t}\n\t}\n\t*/\n\n\t// print Hamming weights\n\t/*\n\tfor(size_t i = 0; i < input_len; i++)\n\t{\n\t\tcout << i << \" Row:\" << endl;\n\t\tprint_decrypted(ham_weights[i]);\n      \tcout << endl;\n\t}\n\t*/\n\n\tif(eq_mul_num * input_len <= p - 2)\n\t//if(true)\n\t{\n\t\tfor(size_t i = 0; i < input_len; i++)\n\t\t{\n\t\t\tcout << \"Computing Element \" << i << endl;\n\t\t\tCtxt tmp_sum = Ctxt(ctxt_in[i].getPubKey());\n\t\t\tfor(size_t j = 0; j < input_len; j++)\n\t\t\t{\n\t\t\t\t//compare the Hamming weight of the jth row with i\n\t\t\t\tCtxt tmp_prod = ham_weights[j];\n\t\t\t\ttmp_prod.addConstant(ZZX(-i));\n\t\t\t\tmapTo01_subfield(tmp_prod, 1);\n\t\t\t\ttmp_prod.negate();\n\t\t\t\ttmp_prod.addConstant(ZZX(1));\n\n\t\t\t\t//multiply by the jth input ciphertext\n\t\t\t\ttmp_prod.multiplyBy(ctxt_in[j]);\n\t\t\t\ttmp_sum += tmp_prod;\n\t\t\t}\n\t\t\tctxt_out.push_back(tmp_sum);\n\t\t}\n\t}\n\telse\n\t{\n\t\t// equality sums\n\t\tvector<Ctxt> eq_sums;\n\n\t\t// fill ctxt_out with zeros\n\t\tfor(size_t i = 0; i < input_len; i++)\n\t\t{\n\t\t\tctxt_out.push_back(Ctxt(ctxt_in[0].getPubKey()));\n\t\t\teq_sums.push_back(Ctxt(ctxt_in[0].getPubKey()));\n\t\t}\n\n\t\tfor (size_t i = 0; i < input_len; i++)\n\t\t{\n\t\t\tcout << \"Adding element \" << i << endl;\n\n\t\t\t// hw_i^j, j in [1,p-1]\n\t\t\tDynamicCtxtPowers hw_powers(ham_weights[i], p-1);\n\t\t\t\n\t\t\t// eq_sums[0] = 1 - hw_i^(p-1)\n\t\t\teq_sums[0].clear();\n\t\t\teq_sums[0] = hw_powers.getPower(p-1);\n\t\t\teq_sums[0].negate();\n\t\t\teq_sums[0].addConstant(ZZX(1));\n\n\t\t\t// eq_sums[0] * ctxt_in[i]\n\t\t\teq_sums[0].multiplyBy(ctxt_in[i]);\n\n\t\t\t// sum_i eq_sums[0] * ctxt_in[i]\n\t\t\tctxt_out[0] += eq_sums[0];\t\n\n\t\t\tfor (size_t k = 1; k < input_len; k++)\n\t\t\t{\n\t\t\t\t// zeroize\n\t\t\t\teq_sums[k].clear();\n\n\t\t\t\t// current sorting index\n\t\t\t\tZZ_p k_zzp;\n\t\t\t\tk_zzp.init(ZZ(p));\n\t\t\t\tk_zzp = k;\n\n\t\t\t\tZZ_p k_power;\n\t\t\t\tk_power.init(ZZ(p));\n\n\t\t\t\tfor (int j = 1; j < p; j++)\n\t\t\t\t{\n\t\t\t\t\t// k^(p-1-j) mod p\n\t\t\t\t\tk_power = power(k_zzp, p - 1 - j);\n\t\t\t\t\t// hw_i^j\n\t\t\t\t\tCtxt tmp = hw_powers.getPower(j);\n\t\t\t\t\t// hw_i^j * k^(p-1-j)\n\t\t\t\t\ttmp.multByConstant(rep(k_power));\n\t\t\t\t\t// sum hw_i^j * k^(p-1-j)\n\t\t\t\t\teq_sums[k] += tmp;\n\t\t\t\t}\n\t\t\t\t// add k^(p-1) to eq_sums\n\t\t\t\teq_sums[k].addConstant(rep(power(k_zzp, p-1)));\n\n\t\t\t\t// 1 - sum_(j=0)^(p-1) hw_i^j * k^(p-1-j)\n\t\t\t\teq_sums[k].negate();\n\t\t\t\teq_sums[k].addConstant(ZZX(1));\n\n\t\t\t\t// eq_sums[k] * ctxt_in[i]\n\t\t\t\teq_sums[k].multiplyBy(ctxt_in[i]);\n\n\t\t\t\t// sum_i eq_sums[k] * ctxt_in[i]\n\t\t\t\tctxt_out[k] += eq_sums[k];\n\t\t\t}\n\t\t}\n\t}\n\t\n\n\t// print output ciphertexts\n\t/*\n\tfor(size_t i = 0; i < input_len; i++)\n\t{\n\t\tcout << i << \" ctxt:\" << endl;\n\t\tprint_decrypted(ctxt_out[i]);\n      \tcout << endl;\n\t}\n\t*/\n\tHELIB_NTIMER_STOP(Sorting);\n}\n\nvoid Comparator::test_sorting(int num_to_sort, long runs) const\n{\n\t//reset timers\n  setTimersOn();\n  \n  // initialize the random generator\n  random_device rd;\n  mt19937 eng(rd());\n  uniform_int_distribution<unsigned long> distr_u;\n  uniform_int_distribution<long> distr_i;\n\n  // get EncryptedArray\n  const EncryptedArray& ea = m_context.getEA();\n\n  //extract number of slots\n  long nslots = ea.size();\n\n  //get p\n  unsigned long p = m_context.getP();\n\n  //order of p\n  unsigned long ord_p = m_context.getOrdP();\n\n  //amount of numbers in one ciphertext\n  unsigned long numbers_size = nslots / m_expansionLen;\n\n  // number of slots occupied by encoded numbers\n  unsigned long occupied_slots = numbers_size * m_expansionLen;\n\n  //encoding base, ((p+1)/2)^d\n  //if 2-variable comparison polynomial is used, it must be p^d\n  unsigned long enc_base = (p + 1) >> 1;\n  if (m_type == BI || m_type == TAN)\n  {\n  \tenc_base = p;\n  }\n\n  unsigned long digit_base = power_long(enc_base, m_slotDeg);\n\n  //check that field_size^expansion_len fits into 64-bits\n  int space_bit_size = static_cast<int>(ceil(m_expansionLen * log2(digit_base)));\n  unsigned long input_range = ULONG_MAX;\n  if(space_bit_size < 64)\n  {\n    //input_range = power_long(field_size, expansion_len);\n    input_range = power_long(digit_base, m_expansionLen);\n  }\n  cout << \"Maximal input: \" << input_range << endl;\n\n  long min_capacity = 1000;\n  long capacity;\n\n  for (int run = 0; run < runs; run++)\n  {\n    printf(\"Run %d started\\n\", run);\n\n    // all slots contain the same value\n    vector<vector<ZZX>> expected_result;\n    for (int i = 0; i < num_to_sort; i++)\n    {\n    \tvector<ZZX> tmp_vec(occupied_slots,ZZX(INIT_MONO,0,0));\n    \texpected_result.push_back(tmp_vec);\n    }\n    \n    // vector of input longs\n    vector<vector<unsigned long>> input_xs;\n    for (int i = 0; i < numbers_size; i++)\n    {\n    \tvector<unsigned long> tmp_vec(num_to_sort,0);\n    \tinput_xs.push_back(tmp_vec);\n    }\n\n    ZZX pol_slot;\n\n    //ciphertexts to sort\n    vector<Ctxt> ctxt_in;\n\n    //sorted ciphertexts\n    vector<Ctxt> ctxt_out;\n\n    for (int i = 0; i < num_to_sort; i++)\n    {\n\t\t// the plaintext polynomials\n\t\tvector<ZZX> pol_x(nslots);\n\n\t\t//encoding of slots\n\t\tfor (int k = 0; k < numbers_size; k++)\n\t\t{\n\t\t\tunsigned long input_x = distr_u(eng) % input_range;\n\n\t\t\tinput_xs[k][i] = input_x;\n\t\t\n\t\t\tif(m_verbose)\n\t\t\t{\n\t\t\t\tcout << \"Input\" << endl;\n\t\t\t\tcout << input_x << endl;\n\t\t\t}\n\n\t\t\tvector<long> decomp_int_x;\n\n\t\t\t//decomposition of input integers\n\t\t\tdigit_decomp(decomp_int_x, input_x, digit_base, m_expansionLen);\n\t\t\tfor (int j = 0; j < m_expansionLen; j++)\n\t\t\t{\n\t\t\t    //decomposition of a digit\n\t\t\t    int_to_slot(pol_slot, decomp_int_x[j], enc_base);\n\t\t\t    pol_x[k * m_expansionLen + j] = pol_slot;\n\t\t\t}\n\t\t}\n\n      \tif(m_verbose)\n\t    {\n\t      cout << \"Input\" << endl;\n\t      for(int j = 0; j < nslots; j++)\n\t      {\n\t          printZZX(cout, pol_x[j], ord_p);\n\t          cout << endl;\n\t      }\n\t    }\n\n\t    Ctxt ctxt_x(m_pk);\n    \tea.encrypt(ctxt_x, m_pk, pol_x);\n\n    \tctxt_in.push_back(ctxt_x);\n    }\n\n    //cout << \"Input\" << endl;\n    for (int i = 0; i < numbers_size; i++)\n    {\n    \t//for (int j = 0; j < num_to_sort; j++)\n    \t//\tcout << input_xs[i][j] << \" \";\n    \t//cout << endl;\n    \tstd::sort(input_xs[i].begin(), input_xs[i].end());\n    }\n\n    //cout << \"Expected results\" << endl;\n    for (int i = num_to_sort-1; i >= 0; i--)\n    {\n\t\tfor (int k = 0; k < numbers_size; k++)\n\t\t{\n\t\t\tvector<long> decomp_int_x;\n\n\t\t\t//decomposition of input integers\n\t\t\tdigit_decomp(decomp_int_x, input_xs[k][i], digit_base, m_expansionLen);\n\t\t\tfor (int j = 0; j < m_expansionLen; j++)\n\t\t\t{\n\t\t\t    //decomposition of a digit\n\t\t\t    int_to_slot(pol_slot, decomp_int_x[j], enc_base);\n\t\t\t    expected_result[num_to_sort-1-i][k * m_expansionLen + j] = pol_slot;\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\tcout << num_to_sort-1-i << endl;\n\t\tfor(int j = 0; j < nslots; j++)\n\t\t{\n\t\t\tprintZZX(cout, expected_result[num_to_sort-1-i][j], ord_p);\n        \tcout << endl;\n\t\t}\n\t\t*/\t\n    }\n\n    // comparison function\n    cout << \"Start of sorting\" << endl;\n    this->sort(ctxt_out, ctxt_in);\n\n    printNamedTimer(cout, \"Extraction\");\n    printNamedTimer(cout, \"ComparisonCircuitBivar\");\n    printNamedTimer(cout, \"ComparisonCircuitUnivar\");\n    printNamedTimer(cout, \"EqualityCircuit\");\n    printNamedTimer(cout, \"ShiftMul\");\n    printNamedTimer(cout, \"ShiftAdd\");\n    printNamedTimer(cout, \"Comparison\");\n    printNamedTimer(cout, \"Sorting\");\n\n    const FHEtimer* sort_timer = getTimerByName(\"Sorting\");\n\n    cout << \"Avg. time per batch: \" << 1000.0 * sort_timer->getTime()/static_cast<double>(run+1)/static_cast<double>(numbers_size) << \" ms\" << endl;\n    cout << \"Number of integers in one ciphertext \"<< numbers_size << endl;\n\n    // remove the line below if it gives bizarre results \n    ctxt_out[0].cleanUp();\n    capacity = ctxt_out[0].bitCapacity();\n    cout << \"Final capacity: \" << capacity << endl;\n    if (capacity < min_capacity)\n      min_capacity = capacity;\n    cout << \"Min. capacity: \" << min_capacity << endl;\n    cout << \"Final size: \" << ctxt_out[0].logOfPrimeSet()/log(2.0) << endl;\n    \n    for (int i = 0; i < num_to_sort; i++)\n    {\n    \tvector<ZZX> decrypted(nslots);\n\t    ea.decrypt(ctxt_out[i], m_sk, decrypted);\n\n\t    for(int j = 0; j < numbers_size; j++)\n\t    { \n\t    \tfor(int k = 0; k < m_expansionLen; k++)\n\t    \t{\n\t    \t\tif (decrypted[j * m_expansionLen + k] != expected_result[i][j * m_expansionLen + k])\n\t\t\t    {\n\t\t\t    \tprintf(\"Slot %ld: \", j * m_expansionLen + k);\n\t\t\t    \tprintZZX(cout, decrypted[j * m_expansionLen + k], ord_p);\n\t\t\t        cout << endl;\n\t\t\t        cout << \"Failure\" << endl;\n\t\t\t        return;\n\t\t\t    }\n\t    \t}\n\t    }\n    }\n  }\n}\n\nvoid Comparator::test_compare(long runs) const\n{\n  //reset timers\n  setTimersOn();\n  \n  // initialize the random generator\n  random_device rd;\n  mt19937 eng(rd());\n  uniform_int_distribution<unsigned long> distr_u;\n  uniform_int_distribution<long> distr_i;\n\n  // get EncryptedArray\n  const EncryptedArray& ea = m_context.getEA();\n\n  //extract number of slots\n  long nslots = ea.size();\n\n  //get p\n  unsigned long p = m_context.getP();\n\n  //order of p\n  unsigned long ord_p = m_context.getOrdP();\n\n  //amount of numbers in one ciphertext\n  unsigned long numbers_size = nslots / m_expansionLen;\n\n  // number of slots occupied by encoded numbers\n  unsigned long occupied_slots = numbers_size * m_expansionLen;\n\n  //encoding base, ((p+1)/2)^d\n  //if 2-variable comparison polynomial is used, it must be p^d\n  unsigned long enc_base = (p + 1) >> 1;\n  if (m_type == BI || m_type == TAN)\n  {\n  \tenc_base = p;\n  }\n\n  unsigned long digit_base = power_long(enc_base, m_slotDeg);\n\n  //check that field_size^expansion_len fits into 64-bits\n  int space_bit_size = static_cast<int>(ceil(m_expansionLen * log2(digit_base)));\n  cout << \"Space bit size \" << space_bit_size << endl;\n  unsigned long input_range = ULONG_MAX;\n  if(space_bit_size < 64)\n  {\n    //input_range = power_long(field_size, expansion_len);\n    input_range = power_long(digit_base, m_expansionLen);\n  }\n  cout << \"Maximal input: \" << input_range << endl;\n\n  long min_capacity = 1000;\n  long capacity;\n  for (int run = 0; run < runs; run++)\n  {\n    printf(\"Run %d started\\n\", run);\n\n    vector<ZZX> expected_result(occupied_slots);\n    vector<ZZX> decrypted(occupied_slots);\n\n    // Create the plaintext polynomials for the text and for the pattern\n    vector<ZZX> pol_x(nslots);\n    vector<ZZX> pol_y(nslots);\n    \n    unsigned long input_x;\n    unsigned long input_y;\n    ZZX pol_slot;\n\n    for (int i = 0; i < numbers_size; i++)\n    {\n      input_x = distr_u(eng) % input_range;\n      input_y = distr_u(eng) % input_range;\n\n      if(m_verbose)\n      {\n        cout << \"Input \" << i << endl;\n        cout << input_x << endl;\n        cout << input_y << endl;\n      }\n\n      if (input_x < input_y)\n      {\n        expected_result[i * m_expansionLen] = ZZX(INIT_MONO, 0, 1);\n      }\n      else\n      {\n        expected_result[i * m_expansionLen] = ZZX(INIT_MONO, 0, 0);\n      }\n\n      vector<long> decomp_int_x;\n      vector<long> decomp_int_y;\n      vector<long> decomp_char;\n\n      //decomposition of input integers\n      digit_decomp(decomp_int_x, input_x, digit_base, m_expansionLen);\n      digit_decomp(decomp_int_y, input_y, digit_base, m_expansionLen);\n\n      if(m_verbose)\n      {\n      \tcout << \"Input decomposition into digits\" << endl;\n      \tfor(int j = 0; j < m_expansionLen; j++)\n      \t{\n      \t\tcout << decomp_int_x[j] << \" \" << decomp_int_y[j] << endl;\n      \t}\n      }\n\n      //encoding of slots\n      for (int j = 0; j < m_expansionLen; j++)\n      {\n          //decomposition of a digit\n          int_to_slot(pol_slot, decomp_int_x[j], enc_base);\n          pol_x[i * m_expansionLen + j] = pol_slot;\n      }\n\n      for (int j = 0; j < m_expansionLen; j++)\n      {\n          //decomposition of a digit\n          int_to_slot(pol_slot, decomp_int_y[j], enc_base);\n          pol_y[i * m_expansionLen + j] = pol_slot;\n      }\n    }\n\n    if(m_verbose)\n    {\n      cout << \"Input\" << endl;\n      for(int i = 0; i < nslots; i++)\n      {\n          printZZX(cout, pol_x[i], ord_p);\n          printZZX(cout, pol_y[i], ord_p);\n          cout << endl;\n      }\n    }\n\n    Ctxt ctxt_x(m_pk);\n    Ctxt ctxt_y(m_pk);\n    ea.encrypt(ctxt_x, m_pk, pol_x);\n    ea.encrypt(ctxt_y, m_pk, pol_y);\n    \n    Ctxt ctxt_res(m_pk);\n\n    // comparison function\n    cout << \"Start of comparison\" << endl;\n    compare(ctxt_res, ctxt_x, ctxt_y);\n\n    if(m_verbose)\n    {\n      cout << \"Input\" << endl;\n      for(int j = 0; j < nslots; j++)\n      {\n          printZZX(cout, pol_x[j], ord_p);\n          printZZX(cout, pol_y[j], ord_p);\n          cout << endl;\n      }\n\n      cout << \"Output\" << endl;\n      print_decrypted(ctxt_res);\n      cout << endl;\n    }\n    printNamedTimer(cout, \"Extraction\");\n    printNamedTimer(cout, \"ComparisonCircuitBivar\");\n    printNamedTimer(cout, \"ComparisonCircuitUnivar\");\n    printNamedTimer(cout, \"EqualityCircuit\");\n    printNamedTimer(cout, \"ShiftMul\");\n    printNamedTimer(cout, \"ShiftAdd\");\n    printNamedTimer(cout, \"Comparison\");\n\n    const FHEtimer* comp_timer = getTimerByName(\"Comparison\");\n\n    cout << \"Avg. time per integer: \" << 1000.0 * comp_timer->getTime()/static_cast<double>(run+1)/static_cast<double>(numbers_size) << \" ms\" << endl;\n    cout << \"Number of integers in one ciphertext \"<< numbers_size << endl;\n\n    // remove the line below if it gives bizarre results \n    ctxt_res.cleanUp();\n    capacity = ctxt_res.bitCapacity();\n    cout << \"Final capacity: \" << capacity << endl;\n    if (capacity < min_capacity)\n      min_capacity = capacity;\n    cout << \"Min. capacity: \" << min_capacity << endl;\n    cout << \"Final size: \" << ctxt_res.logOfPrimeSet()/log(2.0) << endl;\n    ea.decrypt(ctxt_res, m_sk, decrypted);\n\n    for(int i = 0; i < numbers_size; i++)\n    { \n      if (decrypted[i * m_expansionLen] != expected_result[i * m_expansionLen])\n      {\n        printf(\"Slot %ld: \", i * m_expansionLen);\n        printZZX(cout, decrypted[i * m_expansionLen], ord_p);\n        cout << endl;\n        cout << \"Failure\" << endl;\n        return;\n      }\n    }\n    cout << endl;\n  }\n}\n\nvoid Comparator::test_min_max(long runs) const\n{\n\t//reset timers\n  setTimersOn();\n  \n  // initialize the random generator\n  random_device rd;\n  mt19937 eng(rd());\n  uniform_int_distribution<unsigned long> distr_u;\n  uniform_int_distribution<long> distr_i;\n\n  // get EncryptedArray\n  const EncryptedArray& ea = m_context.getEA();\n\n  //extract number of slots\n  long nslots = ea.size();\n\n  //get p\n  unsigned long p = m_context.getP();\n\n  //order of p\n  unsigned long ord_p = m_context.getOrdP();\n\n  //amount of numbers in one ciphertext\n  unsigned long numbers_size = nslots / m_expansionLen;\n\n  // number of slots occupied by encoded numbers\n  unsigned long occupied_slots = numbers_size * m_expansionLen;\n\n  //encoding base, ((p+1)/2)^d\n  //if 2-variable comparison polynomial is used, it must be p^d\n  unsigned long enc_base = (p + 1) >> 1;\n  if (m_type == BI || m_type == TAN)\n  {\n  \tenc_base = p;\n  }\n\n  unsigned long digit_base = power_long(enc_base, m_slotDeg);\n\n  //check that field_size^expansion_len fits into 64-bits\n  int space_bit_size = static_cast<int>(ceil(m_expansionLen * log2(digit_base)));\n  unsigned long input_range = ULONG_MAX;\n  if(space_bit_size < 64)\n  {\n    //input_range = power_long(field_size, expansion_len);\n    input_range = power_long(digit_base, m_expansionLen);\n  }\n  cout << \"Maximal input: \" << input_range << endl;\n\n  long min_capacity = 1000;\n  long capacity;\n  for (int run = 0; run < runs; run++)\n  {\n    printf(\"Run %d started\\n\", run);\n\n    vector<ZZX> expected_result_min(occupied_slots);\n    vector<ZZX> expected_result_max(occupied_slots);\n    vector<ZZX> decrypted_min(occupied_slots);\n    vector<ZZX> decrypted_max(occupied_slots);\n\n    // Create the plaintext polynomials for the text and for the pattern\n    vector<ZZX> pol_x(nslots);\n    vector<ZZX> pol_y(nslots);\n    \n    unsigned long input_x;\n    unsigned long input_y;\n    ZZX pol_slot;\n\n    for (int i = 0; i < numbers_size; i++)\n    {\n      input_x = distr_u(eng) % input_range;\n      input_y = distr_u(eng) % input_range;\n\n      if(m_verbose)\n      {\n        cout << \"Input\" << endl;\n        cout << input_x << endl;\n        cout << input_y << endl;\n      }\n\n      vector<long> decomp_int_x;\n      vector<long> decomp_int_y;\n      vector<long> decomp_char;\n\n      //decomposition of input integers\n      digit_decomp(decomp_int_x, input_x, digit_base, m_expansionLen);\n      digit_decomp(decomp_int_y, input_y, digit_base, m_expansionLen);\n\n      //encoding of slots\n      for (int j = 0; j < m_expansionLen; j++)\n      {\n          //decomposition of a digit\n          int_to_slot(pol_slot, decomp_int_x[j], enc_base);\n          pol_x[i * m_expansionLen + j] = pol_slot;\n      }\n\n      for (int j = 0; j < m_expansionLen; j++)\n      {\n          //decomposition of a digit\n          int_to_slot(pol_slot, decomp_int_y[j], enc_base);\n          pol_y[i * m_expansionLen + j] = pol_slot;\n      }\n\n      if (input_x < input_y)\n      {\n      \tfor (int j = 0; j < m_expansionLen; j++)\n      \t{\n\t        expected_result_min[i * m_expansionLen + j] = pol_x[i * m_expansionLen + j];\n\t        expected_result_max[i * m_expansionLen + j] = pol_y[i * m_expansionLen + j];\n\t    }\n      }\n      else\n      {\n        for (int j = 0; j < m_expansionLen; j++)\n      \t{\n\t        expected_result_min[i * m_expansionLen + j] = pol_y[i * m_expansionLen + j];\n\t        expected_result_max[i * m_expansionLen + j] = pol_x[i * m_expansionLen + j];\n\t    }\n      }\n    }\n\n    if(m_verbose)\n    {\n      cout << \"Input\" << endl;\n      for(int i = 0; i < nslots; i++)\n      {\n          printZZX(cout, pol_x[i], ord_p);\n          printZZX(cout, pol_y[i], ord_p);\n          cout << endl;\n      }\n    }\n\n    Ctxt ctxt_x(m_pk);\n    Ctxt ctxt_y(m_pk);\n    ea.encrypt(ctxt_x, m_pk, pol_x);\n    ea.encrypt(ctxt_y, m_pk, pol_y);\n    \n    Ctxt ctxt_min(m_pk);\n    Ctxt ctxt_max(m_pk);\n\n    // comparison function\n    cout << \"Start of Min/Max\" << endl;\n    min_max(ctxt_min, ctxt_max, ctxt_x, ctxt_y);\n\n    if(m_verbose)\n    {\n      cout << \"Input\" << endl;\n      for(int i = 0; i < nslots; i++)\n      {\n          printZZX(cout, pol_x[i], ord_p);\n          printZZX(cout, pol_y[i], ord_p);\n          cout << endl;\n      }\n\n      cout << \"Output min\" << endl;\n      print_decrypted(ctxt_min);\n      cout << endl;\n\n      cout << \"Output max\" << endl;\n      print_decrypted(ctxt_max);\n      cout << endl;\n    }\n    printNamedTimer(cout, \"Extraction\");\n    printNamedTimer(cout, \"MinMax\");\n\n    const FHEtimer* min_max_timer = getTimerByName(\"MinMax\");\n\n    cout << \"Avg. time per integer: \" << 1000.0 * min_max_timer->getTime()/static_cast<double>(run+1)/static_cast<double>(numbers_size) << \" ms\" << endl;\n    cout << \"Number of integers in one ciphertext \"<< numbers_size << endl;\n\n    // remove the line below if it gives bizarre results \n    ctxt_min.cleanUp();\n    capacity = ctxt_min.bitCapacity();\n    ctxt_max.cleanUp();\n    cout << \"Final capacity: \" << capacity << endl;\n    if (capacity < min_capacity)\n      min_capacity = capacity;\n    cout << \"Min. capacity: \" << min_capacity << endl;\n    cout << \"Final size: \" << ctxt_min.logOfPrimeSet()/log(2.0) << endl;\n    ea.decrypt(ctxt_min, m_sk, decrypted_min);\n    ea.decrypt(ctxt_max, m_sk, decrypted_max);\n\n    for(int i = 0; i < numbers_size; i++)\n    { \n      if (decrypted_min[i * m_expansionLen] != expected_result_min[i * m_expansionLen])\n      {\n        printf(\"Slot %ld: \", i * m_expansionLen);\n        printZZX(cout, decrypted_min[i * m_expansionLen], ord_p);\n        cout << endl;\n        cout << \"Failure\" << endl;\n        return;\n      }\n    }\n    cout << endl;\n    for(int i = 0; i < numbers_size; i++)\n    { \n      if (decrypted_max[i * m_expansionLen] != expected_result_max[i * m_expansionLen])\n      {\n        printf(\"Slot %ld: \", i * m_expansionLen);\n        printZZX(cout, decrypted_max[i * m_expansionLen], ord_p);\n        cout << endl;\n        cout << \"Failure\" << endl;\n        return;\n      }\n    }\n    cout << endl;\n  }\n}\n\nvoid Comparator::test_array_min(int input_len, long depth, long runs) const\n{\n\t//reset timers\n  setTimersOn();\n  \n  // initialize the random generator\n  random_device rd;\n  mt19937 eng(rd());\n  uniform_int_distribution<unsigned long> distr_u;\n  uniform_int_distribution<long> distr_i;\n\n  // get EncryptedArray\n  const EncryptedArray& ea = m_context.getEA();\n\n  //extract number of slots\n  long nslots = ea.size();\n\n  //get p\n  unsigned long p = m_context.getP();\n\n  //order of p\n  unsigned long ord_p = m_context.getOrdP();\n\n  //amount of numbers in one ciphertext\n  unsigned long numbers_size = nslots / m_expansionLen;\n\n  // number of slots occupied by encoded numbers\n  unsigned long occupied_slots = numbers_size * m_expansionLen;\n\n  //encoding base, ((p+1)/2)^d\n  //if 2-variable comparison polynomial is used, it must be p^d\n  unsigned long enc_base = (p + 1) >> 1;\n  if (m_type == BI || m_type == TAN)\n  {\n  \tenc_base = p;\n  }\n\n  unsigned long digit_base = power_long(enc_base, m_slotDeg);\n\n  //check that field_size^expansion_len fits into 64-bits\n  int space_bit_size = static_cast<int>(ceil(m_expansionLen * log2(digit_base)));\n  unsigned long input_range = ULONG_MAX;\n  if(space_bit_size < 64)\n  {\n    //input_range = power_long(field_size, expansion_len);\n    input_range = power_long(digit_base, m_expansionLen);\n  }\n  cout << \"Maximal input: \" << input_range << endl;\n\n  long min_capacity = 1000;\n  long capacity;\n\n  for (int run = 0; run < runs; run++)\n  {\n    printf(\"Run %d started\\n\", run);\n\n    vector<ZZX> expected_result(occupied_slots,ZZX(INIT_MONO,0,0));\n    \n    // vector of input longs\n    vector<vector<unsigned long>> input_xs;\n    for (int i = 0; i < numbers_size; i++)\n    {\n    \tvector<unsigned long> tmp_vec(input_len,0);\n    \tinput_xs.push_back(tmp_vec);\n    }\n\n    ZZX pol_slot;\n\n    //ciphertexts to sort\n    vector<Ctxt> ctxt_in;\n\n    //sorted ciphertexts\n    Ctxt ctxt_out(m_pk);\n\n    for (int i = 0; i < input_len; i++)\n    {\n\t\t// the plaintext polynomials\n\t\tvector<ZZX> pol_x(nslots);\n\n\t\t//encoding of slots\n\t\tfor (int k = 0; k < numbers_size; k++)\n\t\t{\n\t\t\tunsigned long input_x = distr_u(eng) % input_range;\n\n\t\t\tinput_xs[k][i] = input_x;\n\t\t\n\t\t\tif(m_verbose)\n\t\t\t{\n\t\t\t\tcout << \"Input\" << endl;\n\t\t\t\tcout << input_x << endl;\n\t\t\t}\n\n\t\t\tvector<long> decomp_int_x;\n\n\t\t\t//decomposition of input integers\n\t\t\tdigit_decomp(decomp_int_x, input_x, digit_base, m_expansionLen);\n\t\t\tfor (int j = 0; j < m_expansionLen; j++)\n\t\t\t{\n\t\t\t    //decomposition of a digit\n\t\t\t    int_to_slot(pol_slot, decomp_int_x[j], enc_base);\n\t\t\t    pol_x[k * m_expansionLen + j] = pol_slot;\n\t\t\t}\n\t\t}\n\n      \tif(m_verbose)\n\t    {\n\t      cout << \"Input\" << endl;\n\t      for(int j = 0; j < nslots; j++)\n\t      {\n\t          printZZX(cout, pol_x[j], ord_p);\n\t          cout << endl;\n\t      }\n\t    }\n\n\t    Ctxt ctxt_x(m_pk);\n    \tea.encrypt(ctxt_x, m_pk, pol_x);\n\n    \tctxt_in.push_back(ctxt_x);\n    }\n\n    //cout << \"Input\" << endl;\n    vector<unsigned long> output_xs(numbers_size, 0);\n    for (int i = 0; i < numbers_size; i++)\n    {\n    \t/*\n    \tfor (int j = 0; j < input_len; j++)\n    \t\tcout << input_xs[i][j] << \" \";\n    \tcout << endl;\n    \t*/\n    \toutput_xs[i] = *std::min_element(input_xs[i].begin(), input_xs[i].end());\n    \t//cout << \"Output: \" << output_xs[i] << endl;\n    }\n\n    //cout << \"Expected results\" << endl;\n\tfor (int k = 0; k < numbers_size; k++)\n\t{\n\t\tvector<long> decomp_int_x;\n\n\t\t//decomposition of input integers\n\t\tdigit_decomp(decomp_int_x, output_xs[k], digit_base, m_expansionLen);\n\t\tfor (int j = 0; j < m_expansionLen; j++)\n\t\t{\n\t\t    //decomposition of a digit\n\t\t    int_to_slot(pol_slot, decomp_int_x[j], enc_base);\n\t\t    expected_result[k * m_expansionLen + j] = pol_slot;\n\t\t}\n\t}\n\n\t/*\n\tcout << input_len-1-i << endl;\n\tfor(int j = 0; j < nslots; j++)\n\t{\n\t\tprintZZX(cout, expected_result[input_len-1-i][j], ord_p);\n    \tcout << endl;\n\t}\n\t*/\n\n    // comparison function\n    cout << \"Start of array minimum\" << endl;\n    this->array_min(ctxt_out, ctxt_in, depth);\n\n    printNamedTimer(cout, \"Extraction\");\n    printNamedTimer(cout, \"ComparisonCircuitBivar\");\n    printNamedTimer(cout, \"ComparisonCircuitUnivar\");\n    printNamedTimer(cout, \"EqualityCircuit\");\n    printNamedTimer(cout, \"ShiftMul\");\n    printNamedTimer(cout, \"ShiftAdd\");\n    printNamedTimer(cout, \"Comparison\");\n    printNamedTimer(cout, \"ArrayMin\");\n\n    const FHEtimer* sort_timer = getTimerByName(\"ArrayMin\");\n\n    cout << \"Avg. time per batch: \" << 1000.0 * sort_timer->getTime()/static_cast<double>(run+1)/static_cast<double>(numbers_size) << \" ms\" << endl;\n    cout << \"Number of integers in one ciphertext \"<< numbers_size << endl;\n\n    // remove the line below if it gives bizarre results \n    ctxt_out.cleanUp();\n    capacity = ctxt_out.bitCapacity();\n    cout << \"Final capacity: \" << capacity << endl;\n    if (capacity < min_capacity)\n      min_capacity = capacity;\n    cout << \"Min. capacity: \" << min_capacity << endl;\n    cout << \"Final size: \" << ctxt_out.logOfPrimeSet()/log(2.0) << endl;\n    \n\tvector<ZZX> decrypted(nslots);\n    ea.decrypt(ctxt_out, m_sk, decrypted);\n\n    for(int j = 0; j < numbers_size; j++)\n    { \n    \tfor(int k = 0; k < m_expansionLen; k++)\n    \t{\n    \t\tif (decrypted[j * m_expansionLen + k] != expected_result[j * m_expansionLen + k])\n\t\t    {\n\t\t    \tprintf(\"Slot %ld: \", j * m_expansionLen + k);\n\t\t    \tprintZZX(cout, decrypted[j * m_expansionLen + k], ord_p);\n\t\t        cout << endl;\n\t\t        cout << \"Failure\" << endl;\n\t\t        return;\n\t\t    }\n    \t}\n    }\n  }\n}\n", "meta": {"hexsha": "7ca5c77559d7f65d9799d633f146e5419e1f6359", "size": 73359, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/comparator.cpp", "max_stars_repo_name": "iliailia/comparison-circuit-over-fq", "max_stars_repo_head_hexsha": "bc48a9101278997f0847b6ace59c8f3b83884dc0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2021-03-24T07:58:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T00:41:08.000Z", "max_issues_repo_path": "code/comparator.cpp", "max_issues_repo_name": "iliailia/comparison-circuit-over-fq", "max_issues_repo_head_hexsha": "bc48a9101278997f0847b6ace59c8f3b83884dc0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-03-24T03:03:11.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-01T09:23:59.000Z", "max_forks_repo_path": "code/comparator.cpp", "max_forks_repo_name": "iliailia/comparison-circuit-over-fq", "max_forks_repo_head_hexsha": "bc48a9101278997f0847b6ace59c8f3b83884dc0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-19T16:28:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-19T16:28:37.000Z", "avg_line_length": 25.6410346033, "max_line_length": 362, "alphanum_fraction": 0.6169113538, "num_tokens": 24385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936879, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.49935899162515957}}
{"text": "// This file is part of the dune-gdt project:\n//   https://github.com/dune-community/dune-gdt\n// Copyright 2010-2017 dune-gdt developers and contributors. All rights reserved.\n// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)\n//      or  GPL-2.0+ (http://opensource.org/licenses/gpl-license)\n//          with \"runtime exception\" (http://www.dune-project.org/license.html)\n// Authors:\n//   Tobias Leibner  (2017)\n\n#ifndef DUNE_GDT_HYPERBOLIC_PROBLEMS_MOMENTMODELS_BASISFUNCTIONS_SPHERICALHARMONICS_HH\n#define DUNE_GDT_HYPERBOLIC_PROBLEMS_MOMENTMODELS_BASISFUNCTIONS_SPHERICALHARMONICS_HH\n\n#include <boost/math/special_functions/legendre.hpp>\n#include <boost/math/special_functions/spherical_harmonic.hpp>\n\n#include \"base.hh\"\n\nnamespace Dune {\nnamespace GDT {\nnamespace Hyperbolic {\nnamespace Problems {\n\n\n// TODO: use complex arithmetic, currently only usable for Pn Models in 2D, test for only_positive = false\ntemplate <class DomainFieldType, class RangeFieldType, size_t order, size_t fluxDim, bool only_positive = true>\nclass SphericalHarmonics\n    : public BasisfunctionsInterface<DomainFieldType,\n                                     3,\n                                     RangeFieldType,\n                                     only_positive ? ((order + 1) * (order + 2)) / 2 : (order + 1) * (order + 1),\n                                     1,\n                                     fluxDim>\n{\npublic:\n  static const size_t dimDomain = 3;\n  static const size_t dimRange = only_positive ? ((order + 1) * (order + 2)) / 2 : (order + 1) * (order + 1);\n  static const size_t dimFlux = fluxDim;\n\nprivate:\n  typedef BasisfunctionsInterface<DomainFieldType, dimDomain, RangeFieldType, dimRange, 1, dimFlux> BaseType;\n\npublic:\n  using typename BaseType::DomainType;\n  using typename BaseType::RangeType;\n  using typename BaseType::MatrixType;\n  template <class DiscreteFunctionType>\n  using VisualizerType = typename BaseType::template VisualizerType<DiscreteFunctionType>;\n\n  virtual RangeType evaluate(const DomainType& v) const override\n  {\n    const auto v_spherical = XT::Common::CoordinateConverter<DomainFieldType>::to_spherical(v);\n    return evaluate_in_spherical_coords(v_spherical);\n  } // ... evaluate(...)\n\n  RangeType evaluate_in_spherical_coords(const FieldVector<DomainFieldType, 2>& coords) const\n  {\n    const DomainFieldType theta = coords[0];\n    const DomainFieldType phi = coords[1];\n    RangeType ret(0);\n    // TODO: use complex arithmetic, remove real() call\n    for (size_t ll = 0; ll <= order; ++ll)\n      for (int mm = only_positive ? 0 : -int(ll); mm <= int(ll); ++mm)\n        ret[helper<only_positive>::pos(ll, mm)] = boost::math::spherical_harmonic(ll, mm, theta, phi).real();\n    return ret;\n  } // ... evaluate(...)\n\n  virtual RangeType integrated() const override\n  {\n    RangeType ret(0);\n    ret[0] = std::sqrt(4. * M_PI);\n    return ret;\n  }\n\n  virtual MatrixType mass_matrix() const override\n  {\n    MatrixType M(dimRange, dimRange, 0);\n    for (size_t rr = 0; rr < dimRange; ++rr)\n      M[rr][rr] = 1;\n    return M;\n  }\n\n  virtual MatrixType mass_matrix_inverse() const override\n  {\n    return mass_matrix();\n  }\n\n  virtual FieldVector<MatrixType, dimFlux> mass_matrix_with_v() const override\n  {\n    FieldVector<MatrixType, dimFlux> ret(MatrixType(dimRange, dimRange, 0));\n    ret[0] = create_Bx();\n    ret[1] = create_Bz();\n    //    if (dimFlux == 3)\n    //      ret[2] = create_By();\n    return ret;\n  } // ... mass_matrix_with_v()\n\n  template <class DiscreteFunctionType>\n  VisualizerType<DiscreteFunctionType> visualizer() const\n  {\n    return [](const DiscreteFunctionType& u_n, const std::string& filename_prefix, const size_t ii) {\n      component_visualizer<DiscreteFunctionType, dimRange, 0>(u_n, filename_prefix, ii, std::sqrt(4 * M_PI));\n    };\n  }\n\n  std::pair<RangeType, RangeType> calculate_isotropic_distribution(const RangeType& u) const\n  {\n    RangeType u_iso(0), alpha_iso(0);\n    u_iso[0] = u[0];\n    alpha_iso[0] = std::log(u[0] / (4. * M_PI));\n    return std::make_pair(u_iso, alpha_iso);\n  }\n\nprivate:\n  static RangeFieldType A_lm(const size_t l, const int m)\n  {\n    return std::sqrt((l + m) * (l - m) / ((2. * l + 1.) * (2. * l - 1.)));\n  }\n\n  static RangeFieldType B_lm(const size_t l, const int m)\n  {\n    return std::sqrt((l + m) * (l + m - 1.) / ((2. * l + 1.) * (2. * l - 1.)));\n  }\n\n  static MatrixType create_Bx()\n  {\n    MatrixType Bx(dimRange, dimRange, 0);\n    const auto& pos = helper<only_positive>::pos;\n    for (size_t l1 = 0; l1 <= order; ++l1) {\n      for (int m1 = only_positive ? 0 : -int(l1); size_t(std::abs(m1)) <= l1; ++m1) {\n        for (size_t l2 = 0; l2 <= order; ++l2) {\n          for (int m2 = -int(l2); size_t(std::abs(m2)) <= l2; ++m2) {\n            size_t row = pos(l1, m1);\n            size_t col = pos(l2, only_positive ? std::abs(m2) : m2);\n            RangeFieldType factor = !only_positive ? 1. : (m2 < 0 ? std::pow(-1., m2) : 1.);\n            if (l1 == l2 + 1 && m1 == m2 + 1)\n              Bx[row][col] += -0.5 * factor * B_lm(l2 + 1, m2 + 1);\n            if (l1 == l2 - 1 && m1 == m2 + 1)\n              Bx[row][col] += 0.5 * factor * B_lm(l2, -m2);\n            if (l1 == l2 + 1 && m1 == m2 - 1)\n              Bx[row][col] += 0.5 * factor * B_lm(l2 + 1, -m2 - 1);\n            if (l1 == l2 - 1 && m1 == m2 - 1)\n              Bx[row][col] += -0.5 * factor * B_lm(l2, m2);\n          } // m2\n        } // l2\n      } // m1\n    } // l1\n    return Bx;\n  } // ... create_Bx()\n\n  //    static MatrixType create_By()\n  //    {\n  //      MatrixType By(dimRange, dimRange, 0);\n  //      const auto& pos = helper<only_positive>::pos;\n  //      for (size_t l1 = 0; l1 <= order; ++l1) {\n  //        for (int m1 = only_positive ? 0 : -l1; size_t(std::abs(m1)) <= l1; ++m1) {\n  //          for (size_t l2 = 0; l2 <= order; ++l2) {\n  //            for (int m2 = -int(l2); size_t(std::abs(m2)) <= l2; ++m2) {\n  //              size_t row = pos(l1, m1);\n  //              size_t col = pos(l2, only_positive ? std::abs(m2) : m2);\n  //              RangeFieldType factor = !only_positive ? 1. : (m2 < 0 ? std::pow(-1., m2) : 1.);\n  //              if (l1 == l2 + 1 && m1 == m2 + 1)\n  //                By[row][col] += 0.5 * factor * std::complex<RangeFieldType>(0, 1) * B_lm(l2 + 1, m2 + 1);\n  //              if (l1 == l2 - 1 && m1 == m2 + 1)\n  //                By[row][col] += -0.5 * factor * std::complex<RangeFieldType>(0, 1) * B_lm(l2, -m2);\n  //              if (l1 == l2 + 1 && m1 == m2 - 1)\n  //                By[row][col] += 0.5 * factor * std::complex<RangeFieldType>(0, 1) * B_lm(l2 + 1, -m2 - 1);\n  //              if (l1 == l2 - 1 && m1 == m2 - 1)\n  //                By[row][col] += -0.5 * factor * std::complex<RangeFieldType>(0, 1) * B_lm(l2, m2);\n  //            } // m2\n  //          } // l2\n  //        } // m1\n  //      } // l1\n  //      return By;\n  //    } // ... create_By()\n\n  static MatrixType create_Bz()\n  {\n    MatrixType Bz(dimRange, dimRange, 0);\n    const auto& pos = helper<only_positive>::pos;\n    for (size_t l1 = 0; l1 <= order; ++l1) {\n      for (int m1 = only_positive ? 0. : -int(l1); size_t(std::abs(m1)) <= l1; ++m1) {\n        for (size_t l2 = 0; l2 <= order; ++l2) {\n          size_t row = pos(l1, m1);\n          size_t col = pos(l2, m1); // m1 == m2, else matrix entry is 0\n          if (l1 == l2 + 1)\n            Bz[row][col] += A_lm(l2 + 1, m1);\n          if (l1 == l2 - 1)\n            Bz[row][col] += A_lm(l2, m1);\n        } // l2\n      } // m1\n    } // l1\n    return Bz;\n  }\n\n  template <bool positive, class anything = void>\n  struct helper\n  {\n    // Converts a pair (l, m) to a vector index. The vector is ordered by l first, then by m.\n    // Each l has 2l+1 values of m, so (l, m) has position\n    // (\\sum_{k=0}^{l-1} (2k+1)) + (m+l) = l^2 + m + l\n    static size_t pos(const size_t l, const int m)\n    {\n      return size_t(l * l + m + l);\n    }\n  };\n\n  template <class anything>\n  struct helper<true, anything>\n  {\n    // Converts a pair (l, m) to a vector index. The vector is ordered by l first, then by m.\n    // Each l has l+1 non-negative values of m, so (l, m) has position\n    // (\\sum_{k=0}^{l-1} (l+1)) + m = l(l+1)/2 + m\n    static size_t pos(const size_t l, const int m)\n    {\n      return l * (l + 1) / 2 + m;\n    }\n  };\n}; // class SphericalHarmonics<DomainFieldType, 3, ...>\n\n\ntemplate <class DomainFieldType, class RangeFieldType, size_t order, size_t fluxDim, bool only_even = false>\nclass RealSphericalHarmonics\n    : public BasisfunctionsInterface<DomainFieldType,\n                                     3,\n                                     RangeFieldType,\n                                     only_even ? ((order + 1) * (order + 2)) / 2 : (order + 1) * (order + 1),\n                                     1,\n                                     fluxDim>\n{\npublic:\n  static const size_t dimDomain = 3;\n  static const size_t dimFlux = fluxDim;\n  static const size_t dimRange = only_even ? ((order + 1) * (order + 2)) / 2 : (order + 1) * (order + 1);\n\nprivate:\n  typedef BasisfunctionsInterface<DomainFieldType, dimDomain, RangeFieldType, dimRange, 1, dimFlux> BaseType;\n\npublic:\n  typedef typename Dune::QuadratureRule<DomainFieldType, dimDomain> QuadratureType;\n  using typename BaseType::DomainType;\n  using typename BaseType::RangeType;\n  using typename BaseType::MatrixType;\n  template <class DiscreteFunctionType>\n  using VisualizerType = typename BaseType::template VisualizerType<DiscreteFunctionType>;\n\n  virtual RangeType evaluate(const DomainType& v) const override\n  {\n    const auto v_spherical = XT::Common::CoordinateConverter<DomainFieldType>::to_spherical(v);\n    return evaluate_in_spherical_coords(v_spherical);\n  } // ... evaluate(...)\n\n  RangeType evaluate_in_spherical_coords(const FieldVector<DomainFieldType, 2>& coords) const\n  {\n    const DomainFieldType theta = coords[0];\n    const DomainFieldType phi = coords[1];\n    RangeType ret(0);\n    for (size_t ll = 0; ll <= order; ++ll)\n      for (int mm = -int(ll); mm <= int(ll); ++mm)\n        if (!only_even || !((mm + ll) % 2))\n          ret[helper<only_even>::pos(ll, mm)] = evaluate_lm(theta, phi, int(ll), mm);\n    return ret;\n  } // ... evaluate(...)\n\n  virtual RangeType integrated() const override\n  {\n    RangeType ret(0);\n    ret[0] = std::sqrt(4. * M_PI);\n    return ret;\n  }\n\n  virtual MatrixType mass_matrix() const override\n  {\n    MatrixType M(dimRange, dimRange, 0);\n    for (size_t rr = 0; rr < dimRange; ++rr)\n      M[rr][rr] = 1;\n    return M;\n  }\n\n  virtual MatrixType mass_matrix_inverse() const override\n  {\n    return mass_matrix();\n  }\n\n  virtual FieldVector<MatrixType, dimFlux> mass_matrix_with_v() const override\n  {\n    FieldVector<MatrixType, dimFlux> ret(MatrixType(dimRange, dimRange, 0));\n    ret[0] = create_Bx();\n    ret[1] = create_By();\n    if (dimFlux == 3)\n      ret[2] = create_Bz();\n    return ret;\n  } // ... mass_matrix_with_v()\n\n  std::pair<RangeType, RangeType> calculate_isotropic_distribution(const RangeType& u) const\n  {\n    RangeType u_iso(0), alpha_iso(0);\n    u_iso[0] = u[0];\n    alpha_iso[0] = std::log(u[0] / std::sqrt(4. * M_PI)) * std::sqrt(4. * M_PI);\n    return std::make_pair(u_iso, alpha_iso);\n  }\n\n  template <class DiscreteFunctionType>\n  VisualizerType<DiscreteFunctionType> visualizer() const\n  {\n    return [](const DiscreteFunctionType& u_n, const std::string& filename_prefix, const size_t ii) {\n      component_visualizer<DiscreteFunctionType, dimRange, 0>(u_n, filename_prefix, ii, std::sqrt(4 * M_PI));\n    };\n  }\n\n  RangeFieldType realizability_limiter_max(const RangeType& u, const RangeType& u_bar) const\n  {\n    return 2 * std::max(u[0], u_bar[0]);\n  }\n\nprivate:\n  static RangeFieldType A_lm(const size_t l, const int m)\n  {\n    return std::sqrt((l + m) * (l - m) / ((2. * l + 1.) * (2. * l - 1.)));\n  }\n\n  static RangeFieldType B_lm(const size_t l, const int m)\n  {\n    return std::sqrt((l + m) * (l + m - 1.) / ((2. * l + 1.) * (2. * l - 1.)));\n  }\n\n  static MatrixType create_Bx()\n  {\n    MatrixType Bx(dimRange, dimRange, 0.);\n    const auto& pos = helper<only_even>::pos;\n    for (size_t l1 = 0; l1 <= order; ++l1) {\n      for (int m1 = -int(l1); size_t(std::abs(m1)) <= l1; ++m1) {\n        for (size_t l2 = 0; l2 <= order; ++l2) {\n          for (int m2 = -int(l2); size_t(std::abs(m2)) <= l2; ++m2) {\n            if (!only_even || (!((m1 + l1) % 2) && !((m2 + l2) % 2))) {\n              if (l1 == l2 - 1 && m1 == m2 - 1 && m2 > 0)\n                Bx[pos(l1, m1)][pos(l2, m2)] += 0.5 * std::sqrt(1. + (m2 == 1)) * B_lm(l2, m2);\n              if (l1 == l2 + 1 && m1 == m2 - 1 && m2 > 0)\n                Bx[pos(l1, m1)][pos(l2, m2)] += -0.5 * std::sqrt(1. + (m2 == 1)) * B_lm(l2 + 1, -m2 + 1);\n              if (l1 == l2 - 1 && m1 == m2 + 1 && m2 > 0)\n                Bx[pos(l1, m1)][pos(l2, m2)] += -0.5 * B_lm(l2, -m2);\n              if (l1 == l2 + 1 && m1 == m2 + 1 && m2 > 0)\n                Bx[pos(l1, m1)][pos(l2, m2)] += 0.5 * B_lm(l2 + 1, m2 + 1);\n              if (l1 == l2 - 1 && m1 == m2 + 1 && m2 < 0)\n                Bx[pos(l1, m1)][pos(l2, m2)] += 0.5 * (1. - (-m2 == 1)) * B_lm(l2, -m2);\n              if (l1 == l2 + 1 && m1 == m2 + 1 && m2 < 0)\n                Bx[pos(l1, m1)][pos(l2, m2)] += -0.5 * (1. - (-m2 == 1)) * B_lm(l2 + 1, m2 + 1);\n              if (l1 == l2 - 1 && m1 == m2 - 1 && m2 < 0)\n                Bx[pos(l1, m1)][pos(l2, m2)] += -0.5 * B_lm(l2, m2);\n              if (l1 == l2 + 1 && m1 == m2 - 1 && m2 < 0)\n                Bx[pos(l1, m1)][pos(l2, m2)] += 0.5 * B_lm(l2 + 1, -m2 + 1);\n              if (l1 == l2 - 1 && m1 == 1 && m2 == 0)\n                Bx[pos(l1, m1)][pos(l2, m2)] += -1. / std::sqrt(2.) * B_lm(l2, 0);\n              if (l1 == l2 + 1 && m1 == 1 && m2 == 0)\n                Bx[pos(l1, m1)][pos(l2, m2)] += 1. / std::sqrt(2.) * B_lm(l2 + 1, 1);\n            }\n          } // m2\n        } // l2\n      } // m1\n    } // l1\n    return Bx;\n  }\n\n  static MatrixType create_By()\n  {\n    MatrixType By(dimRange, dimRange, 0.);\n    const auto& pos = helper<only_even>::pos;\n    for (size_t l1 = 0; l1 <= order; ++l1) {\n      for (int m1 = -int(l1); size_t(std::abs(m1)) <= l1; ++m1) {\n        for (size_t l2 = 0; l2 <= order; ++l2) {\n          for (int m2 = -int(l2); size_t(std::abs(m2)) <= l2; ++m2) {\n            if (!only_even || (!((m1 + l1) % 2) && !((m2 + l2) % 2))) {\n              if (l1 == l2 + 1 && m1 == -m2 + 1 && m2 > 0)\n                By[pos(l1, m1)][pos(l2, m2)] += 0.5 * (1. - (m2 == 1)) * B_lm(l2 + 1, -m2 + 1);\n              if (l1 == l2 - 1 && m1 == -m2 + 1 && m2 > 0)\n                By[pos(l1, m1)][pos(l2, m2)] += -0.5 * (1. - (m2 == 1)) * B_lm(l2, m2);\n              if (l1 == l2 - 1 && m1 == -m2 - 1 && m2 > 0)\n                By[pos(l1, m1)][pos(l2, m2)] += -0.5 * B_lm(l2, -m2);\n              if (l1 == l2 + 1 && m1 == -m2 - 1 && m2 > 0)\n                By[pos(l1, m1)][pos(l2, m2)] += 0.5 * B_lm(l2 + 1, m2 + 1);\n              if (l1 == l2 - 1 && m1 == -m2 - 1 && m2 < 0)\n                By[pos(l1, m1)][pos(l2, m2)] += 0.5 * std::sqrt(1. + (-m2 == 1)) * B_lm(l2, -m2);\n              if (l1 == l2 + 1 && m1 == -m2 - 1 && m2 < 0)\n                By[pos(l1, m1)][pos(l2, m2)] += -0.5 * std::sqrt(1. + (-m2 == 1)) * B_lm(l2 + 1, m2 + 1);\n              if (l1 == l2 - 1 && m1 == -m2 + 1 && m2 < 0)\n                By[pos(l1, m1)][pos(l2, m2)] += 0.5 * B_lm(l2, m2);\n              if (l1 == l2 + 1 && m1 == -m2 + 1 && m2 < 0)\n                By[pos(l1, m1)][pos(l2, m2)] += -0.5 * B_lm(l2 + 1, -m2 + 1);\n              if (l1 == l2 - 1 && m1 == -1 && m2 == 0)\n                By[pos(l1, m1)][pos(l2, m2)] += -1. / std::sqrt(2.) * B_lm(l2, 0);\n              if (l1 == l2 + 1 && m1 == -1 && m2 == 0)\n                By[pos(l1, m1)][pos(l2, m2)] += 1. / std::sqrt(2.) * B_lm(l2 + 1, 1);\n            }\n          } // m2\n        } // l2\n      } // m1\n    } // l1\n    return By;\n  } // ... create_By()\n\n  static MatrixType create_Bz()\n  {\n    MatrixType Bz(dimRange, dimRange, 0);\n    const auto& pos = helper<only_even>::pos;\n    for (size_t l1 = 0; l1 <= order; ++l1) {\n      for (int m1 = -int(l1); size_t(std::abs(m1)) <= l1; ++m1) {\n        for (size_t l2 = 0; l2 <= order; ++l2) {\n          for (int m2 = -int(l2); size_t(std::abs(m2)) <= l2; ++m2) {\n            if (!only_even || (!((m1 + l1) % 2) && !((m2 + l2) % 2))) {\n              if (m1 == m2 && l1 == l2 + 1)\n                Bz[pos(l1, m1)][pos(l2, m2)] += A_lm(l2 + 1, m2);\n              if (m1 == m2 && l1 == l2 - 1)\n                Bz[pos(l1, m1)][pos(l2, m2)] += A_lm(l2, m2);\n            }\n          } // m2\n        } // l2\n      } // m1\n    } // l1\n    return Bz;\n  } // ... create_Bz()\n\n  template <bool even, class anything = void>\n  struct helper\n  {\n    // Converts a pair (l, m) to a vector index. The vector is ordered by l first, then by m.\n    // Each l has 2l+1 values of m, so (l, m) has position\n    // (\\sum_{k=0}^{l-1} (2k+1)) + (m+l) = l^2 + m + l\n    static size_t pos(const size_t l, const int m)\n    {\n      return size_t(l * l + m + l);\n    }\n  };\n\n  template <class anything>\n  struct helper<true, anything>\n  {\n    // Converts a pair (l, m) to a vector index. The vector is ordered by l first, then by m.\n    // Each l has l+1 values of m (as only m s.t. m+l is even are considered), so (l, m) has position\n    // (\\sum_{k=0}^{l-1} (k+1)) + (m+l)/2 = l(l+1)/2 + (l+m)/2\n    static size_t pos(const int l, const int m)\n    {\n      return size_t(l * (l + 1) / 2 + (m + l) / 2);\n    }\n  };\n\n  // Notation from Garrett, Hauck, \"A Comparison of Moment Closures for Linear Kinetic Transport Equations: The Line\n  // Source Benchmark\",\n  // http://www.tandfonline.com/doi/full/10.1080/00411450.2014.910226?src=recsys&, Section 4.1\n  RangeFieldType N_lm(const int l, const int m) const\n  {\n    assert(l >= 0 && m >= 0 && m <= l);\n    return std::sqrt((2. * l + 1.) * XT::Common::factorial(l - m) / (XT::Common::factorial(l + m) * 4. * M_PI));\n  }\n\n  RangeFieldType evaluate_lm(const DomainFieldType theta, const DomainFieldType phi, const int l, const int m) const\n  {\n    const auto cos_theta = std::cos(theta);\n    assert(l >= 0 && std::abs(m) <= l);\n    if (m < 0)\n      return std::sqrt(2) * N_lm(l, -m) * boost::math::legendre_p(l, -m, cos_theta) * std::sin(-m * phi);\n    else if (m == 0)\n      return N_lm(l, 0) * boost::math::legendre_p(l, 0, cos_theta);\n    else\n      return std::sqrt(2) * N_lm(l, m) * boost::math::legendre_p(l, m, cos_theta) * std::cos(m * phi);\n  }\n}; // class RealSphericalHarmonics<DomainFieldType, 3, ...>\n\n\n} // namespace Problems\n} // namespace Hyperbolic\n} // namespace GDT\n} // namespace Dune\n\n#endif // DUNE_GDT_HYPERBOLIC_PROBLEMS_MOMENTMODELS_BASISFUNCTIONS_SPHERICALHARMONICS_HH\n", "meta": {"hexsha": "423b6b2908466228a379a6e42e3ef8ef1ea8d17d", "size": 18704, "ext": "hh", "lang": "C++", "max_stars_repo_path": "dune/gdt/test/hyperbolic/problems/momentmodels/basisfunctions/spherical_harmonics.hh", "max_stars_repo_name": "tobiasleibner/dune-gdt", "max_stars_repo_head_hexsha": "5d3dc6c7f5fd66db78ebb294d7ee4803f8e0bf5b", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dune/gdt/test/hyperbolic/problems/momentmodels/basisfunctions/spherical_harmonics.hh", "max_issues_repo_name": "tobiasleibner/dune-gdt", "max_issues_repo_head_hexsha": "5d3dc6c7f5fd66db78ebb294d7ee4803f8e0bf5b", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dune/gdt/test/hyperbolic/problems/momentmodels/basisfunctions/spherical_harmonics.hh", "max_forks_repo_name": "tobiasleibner/dune-gdt", "max_forks_repo_head_hexsha": "5d3dc6c7f5fd66db78ebb294d7ee4803f8e0bf5b", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.4599156118, "max_line_length": 116, "alphanum_fraction": 0.5324529512, "num_tokens": 6476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.49935899162515945}}
{"text": "#include \"OGR.h\"\n#include <boost/math/constants/constants.hpp>\n#include <macgyver/Exception.h>\n#include <ogr_geometry.h>\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Calculate area in m^2 for a geography\n *\n * Refs: Some algorithms for polygons on a sphere\n *       http://hdl.handle.net/2014/40409\n *\n *       https://trac.osgeo.org/openlayers/browser/trunk/openlayers/lib/OpenLayers/Geometry/LinearRing.js\n *\n * Note: The algorithm returns a positive number for clockwise rings.\n */\n// ----------------------------------------------------------------------\n\ndouble geographic_area(const OGRLineString *theGeom)\n{\n  try\n  {\n    double area = 0;\n\n    std::size_t npoints = theGeom->getNumPoints();\n\n    for (std::size_t i = 0; i < npoints - 1; i++)\n    {\n      double x1 = theGeom->getX(i) * boost::math::double_constants::degree;\n      double y1 = theGeom->getY(i) * boost::math::double_constants::degree;\n      double x2 = theGeom->getX(i + 1) * boost::math::double_constants::degree;\n      double y2 = theGeom->getY(i + 1) * boost::math::double_constants::degree;\n\n      area += (x2 - x1) * (2 + sin(y1) + sin(y2));\n    }\n    area *= 6378137.0 * 6378137.0 / 2.0;\n\n    return std::abs(area);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\ndouble geographic_area(const OGRLinearRing *theGeom)\n{\n  try\n  {\n    return geographic_area(static_cast<const OGRLineString *>(theGeom));\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief get_Area substitute for OGRLineString copied from OGRLinearRing::get_Area()\n *\n * The area is computed according to Green's Theorem:\n *\n * Area is \"Sum(x(i)*(y(i+1) - y(i-1)))/2\" for i = 0 to pointCount-1,\n * assuming the last point is a duplicate of the first.\n *\n */\n// ----------------------------------------------------------------------\n\ndouble metric_area(const OGRLineString *theGeom)\n{\n  try\n  {\n    std::size_t npoints = theGeom->getNumPoints();\n    if (npoints < 2)\n      return 0;\n\n    double area = theGeom->getX(0) * (theGeom->getY(1) - theGeom->getY(npoints - 1));\n\n    for (std::size_t i = 1; i < npoints - 1; i++)\n      area += theGeom->getX(i) * (theGeom->getY(i + 1) - theGeom->getY(i - 1));\n\n    area += theGeom->getX(npoints - 1) * (theGeom->getY(0) - theGeom->getY(npoints - 2));\n\n    return 0.5 * std::abs(area);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Despeckle OGR geometry\n */\n// ----------------------------------------------------------------------\n\nOGRPolygon *despeckle_polygon(const OGRPolygon *theGeom, double theLimit, bool theGeogFlag)\n{\n  try\n  {\n    // Quick exit if the exterior is too small\n\n    const auto *exterior = theGeom->getExteriorRing();\n    double area = (theGeogFlag ? geographic_area(exterior) : exterior->get_Area());\n\n    if (area < theLimit)\n      return nullptr;\n\n    // We have at least a valid exterior\n\n    auto *out = new OGRPolygon;\n    out->addRingDirectly(dynamic_cast<OGRLinearRing *>(exterior->clone()));\n\n    // Remove too small holes too\n\n    for (int i = 0, n = theGeom->getNumInteriorRings(); i < n; ++i)\n    {\n      const auto *hole = theGeom->getInteriorRing(i);\n      area = (theGeogFlag ? geographic_area(hole) : hole->get_Area());\n      if (area >= theLimit)\n        out->addRingDirectly(dynamic_cast<OGRLinearRing *>(hole->clone()));\n    }\n\n    return out;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Despeckle OGR geometry\n */\n// ----------------------------------------------------------------------\n\nOGRLineString *despeckle_linestring(const OGRLineString *theGeom, double theLimit, bool theGeogFlag)\n{\n  try\n  {\n    if (theGeom == nullptr || theGeom->IsEmpty() != 0)\n      return nullptr;\n\n    if (!theGeom->get_IsClosed())\n      return dynamic_cast<OGRLineString *>(theGeom->clone());\n\n    // Despeckle closed linestrings only\n\n    // TODO: Old GDAL does not have get_Area for linestrings\n    // double area = (theGeogFlag ? geographic_area(theGeom) : geom->get_Area());\n    double area = (theGeogFlag ? geographic_area(theGeom) : metric_area(theGeom));\n\n    if (area < theLimit)\n      return nullptr;\n\n    return dynamic_cast<OGRLineString *>(theGeom->clone());\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Despeckle OGR geometry\n */\n// ----------------------------------------------------------------------\n\nOGRPoint *despeckle_point(const OGRPoint *theGeom)\n{\n  try\n  {\n    if (theGeom == nullptr || theGeom->IsEmpty() != 0)\n      return nullptr;\n\n    return dynamic_cast<OGRPoint *>(theGeom->clone());\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Despeckle OGR geometry\n */\n// ----------------------------------------------------------------------\n\nOGRMultiPoint *despeckle_multipoint(const OGRMultiPoint *theGeom)\n{\n  try\n  {\n    if (theGeom == nullptr || theGeom->IsEmpty() != 0)\n      return nullptr;\n\n    return dynamic_cast<OGRMultiPoint *>(theGeom->clone());\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Despeckle OGR geometry\n */\n// ----------------------------------------------------------------------\n\nOGRMultiLineString *despeckle_multilinestring(const OGRMultiLineString *theGeom,\n                                              double theLimit,\n                                              bool theGeogFlag)\n{\n  try\n  {\n    if (theGeom == nullptr || theGeom->IsEmpty() != 0)\n      return nullptr;\n    ;\n\n    auto *out = new OGRMultiLineString();\n\n    for (int i = 0, n = theGeom->getNumGeometries(); i < n; ++i)\n    {\n      auto *geom = despeckle_linestring(\n          dynamic_cast<const OGRLineString *>(theGeom->getGeometryRef(i)), theLimit, theGeogFlag);\n      if (geom != nullptr)\n        out->addGeometryDirectly(geom);\n    }\n\n    if (out->IsEmpty() == 0)\n      return out;\n\n    delete out;\n    return nullptr;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Despeckle OGR geometry\n */\n// ----------------------------------------------------------------------\n\nOGRMultiPolygon *despeckle_multipolygon(const OGRMultiPolygon *theGeom,\n                                        double theLimit,\n                                        bool theGeogFlag)\n{\n  try\n  {\n    if (theGeom == nullptr || theGeom->IsEmpty() != 0)\n      return nullptr;\n\n    auto *out = new OGRMultiPolygon();\n\n    for (int i = 0, n = theGeom->getNumGeometries(); i < n; ++i)\n    {\n      auto *geom = despeckle_polygon(\n          dynamic_cast<const OGRPolygon *>(theGeom->getGeometryRef(i)), theLimit, theGeogFlag);\n      if (geom != nullptr)\n        out->addGeometryDirectly(geom);\n    }\n\n    if (out->IsEmpty() == 0)\n      return out;\n\n    delete out;\n    return nullptr;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Despeckle OGR geometry\n */\n// ----------------------------------------------------------------------\n\n// Needed since two functions call each other\n\nOGRGeometry *despeckle_geom(const OGRGeometry *theGeom, double theLimit, bool theGeogFlag);\n\nOGRGeometryCollection *despeckle_geometrycollection(const OGRGeometryCollection *theGeom,\n                                                    double theLimit,\n                                                    bool theGeogFlag)\n{\n  try\n  {\n    if (theGeom == nullptr || theGeom->IsEmpty() != 0)\n      return nullptr;\n\n    auto *out = new OGRGeometryCollection;\n\n    for (int i = 0, n = theGeom->getNumGeometries(); i < n; ++i)\n    {\n      auto *geom = despeckle_geom(theGeom->getGeometryRef(i), theLimit, theGeogFlag);\n      if (geom != nullptr)\n        out->addGeometryDirectly(geom);\n    }\n\n    if (out->IsEmpty() == 0)\n      return out;\n\n    delete out;\n    return nullptr;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Despeckle OGR geometry to output geometry\n */\n// ----------------------------------------------------------------------\n\nOGRGeometry *despeckle_geom(const OGRGeometry *theGeom, double theLimit, bool theGeogFlag)\n{\n  try\n  {\n    OGRwkbGeometryType id = theGeom->getGeometryType();\n\n    switch (id)\n    {\n      case wkbPoint:\n        return despeckle_point(dynamic_cast<const OGRPoint *>(theGeom));\n      case wkbLineString:\n        return despeckle_linestring(\n            dynamic_cast<const OGRLineString *>(theGeom), theLimit, theGeogFlag);\n      case wkbPolygon:\n        return despeckle_polygon(dynamic_cast<const OGRPolygon *>(theGeom), theLimit, theGeogFlag);\n      case wkbMultiPoint:\n        return despeckle_multipoint(dynamic_cast<const OGRMultiPoint *>(theGeom));\n      case wkbMultiLineString:\n        return despeckle_multilinestring(\n            dynamic_cast<const OGRMultiLineString *>(theGeom), theLimit, theGeogFlag);\n      case wkbMultiPolygon:\n        return despeckle_multipolygon(\n            dynamic_cast<const OGRMultiPolygon *>(theGeom), theLimit, theGeogFlag);\n      case wkbGeometryCollection:\n        return despeckle_geometrycollection(\n            dynamic_cast<const OGRGeometryCollection *>(theGeom), theLimit, theGeogFlag);\n      case wkbLinearRing:\n        throw Fmi::Exception::Trace(BCP, \"Direct despeckling of LinearRings is not supported\");\n      case wkbNone:\n        throw Fmi::Exception::Trace(\n            BCP, \"Encountered a 'none' geometry component when despeckling a geometry\");\n      default:\n        throw Fmi::Exception::Trace(\n            BCP, \"Encountered an unknown geometry component when clipping polygons\");\n    }\n\n    // NOT REACHED\n    return nullptr;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Despeckle a geometry so that small polygons are removed\n *\n * \\return Empty GeometryCollection if the result is empty\n */\n// ----------------------------------------------------------------------\n\nOGRGeometry *Fmi::OGR::despeckle(const OGRGeometry &theGeom, double theAreaLimit)\n{\n  try\n  {\n    // Area calculations for geographies must be done by ourselves, OGR\n    // does it in the native system and hence would produce square degrees.\n\n    OGRSpatialReference *crs = theGeom.getSpatialReference();\n    bool geographic = (crs != nullptr ? (crs->IsGeographic() != 0) : false);\n\n    // Actual despeckling\n\n    auto *geom =\n        despeckle_geom(&theGeom, theAreaLimit * 1000 * 1000, geographic);  // from m^2 to km^2\n\n    if (geom != nullptr)\n      geom->assignSpatialReference(theGeom.getSpatialReference());  // SR is ref. counted\n\n    return geom;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n", "meta": {"hexsha": "8bbe1bb27028c4203ce7775fbba4f1af1d06e9fa", "size": 11563, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gis/OGR-despeckle.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/OGR-despeckle.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/OGR-despeckle.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": 28.3406862745, "max_line_length": 105, "alphanum_fraction": 0.5396523394, "num_tokens": 2799, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.49935899162515945}}
{"text": "/////////////////////////////////////////////////////////////////////////\n// Copyright (C) 2016 Sergey Koshelev                                   \n/////////////////////////////////////////////////////////////////////////\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE \"HammingDistanceClass\"\n\n#include <boost/test/unit_test.hpp>\n\n#include \"../lib/HammingDistance.h\"\n\nBOOST_AUTO_TEST_CASE( calculateBlobsEqSz )\n{\n   // 2 bytes completely different\n   unsigned int a = 0xFFFF;\n   unsigned int b = 0x0000;\n   BOOST_CHECK( HammingDistance::calculate( &a, &b, 1 ) == 16 );\n\n   // move 1 set bit through integer and calculate Hamming distance. Must be always 1\n   for ( int i = 0; i < sizeof( int ) * 8; ++i )\n   {\n      unsigned int a = 1 << i;\n      unsigned int b = 0;\n      BOOST_CHECK( HammingDistance::calculate( &a, &b, 1 ) == 1 );\n   }\n\n   // check array\n   int aa[] = { 0xFFFF, 0x0000 };\n   int bb[] = { 0xFFFE, 0x0010 };\n   BOOST_CHECK( HammingDistance::calculate( aa, bb, 2 ) == 2 );\n}\n\nBOOST_AUTO_TEST_CASE( calculateBlobsDifSz )\n{\n   int aa[] = { 0xFFFF, 0x0000 };\n   int bb[] = { 0xFFFF };\n   BOOST_CHECK( HammingDistance::calculate( aa, bb, 2, 1 ) == sizeof(int)*8 );\n}\n\nBOOST_AUTO_TEST_CASE( calculateBlobsZeroTerm )\n{\n   int aa[] = { 0xFFFF, 0xFFFF, 0x1000, 0 };\n   int bb[] = { 0xFFFF, 0xFEFF, 0x0100, 0 };\n   BOOST_CHECK( HammingDistance::calculate( aa, bb ) == 3 );\n}\n\nBOOST_AUTO_TEST_CASE( calculateStrings )\n{\n   std::string a = \"1011101\";\n   std::string b = \"1001001\";\n   BOOST_CHECK( HammingDistance::calculate( a, b ) == 2 );\n\n   a = \"2173896\";\n   b = \"2233796\";\n   BOOST_CHECK( HammingDistance::calculate( a, b ) == 3 );\n\n   a = \"2173896\";\n   b = \"223379\";\n   BOOST_CHECK( HammingDistance::calculate( a, b ) == 4 );\n\n}\n\n\n", "meta": {"hexsha": "af56506dab373a4282c52af41778e039be29e81a", "size": 1748, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/HDUnitTests.cpp", "max_stars_repo_name": "serge-koshelev/HammingDistanceLib", "max_stars_repo_head_hexsha": "b682783b1eee7efd3a7423cd0ccbf54700b528f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/HDUnitTests.cpp", "max_issues_repo_name": "serge-koshelev/HammingDistanceLib", "max_issues_repo_head_hexsha": "b682783b1eee7efd3a7423cd0ccbf54700b528f1", "max_issues_repo_licenses": ["MIT"], "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/HDUnitTests.cpp", "max_forks_repo_name": "serge-koshelev/HammingDistanceLib", "max_forks_repo_head_hexsha": "b682783b1eee7efd3a7423cd0ccbf54700b528f1", "max_forks_repo_licenses": ["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.3125, "max_line_length": 85, "alphanum_fraction": 0.5652173913, "num_tokens": 524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.727975460709318, "lm_q2_score": 0.6859494614282922, "lm_q1q2_score": 0.4993543752065695}}
{"text": "#ifndef STAN_MATH_PRIM_MAT_FUN_DIAG_PRE_MULTIPLY_HPP\n#define STAN_MATH_PRIM_MAT_FUN_DIAG_PRE_MULTIPLY_HPP\n\n#include <stan/math/prim/mat/err/check_vector.hpp>\n#include <stan/math/prim/scal/err/check_size_match.hpp>\n#include <stan/math/prim/mat/fun/Eigen.hpp>\n#include <boost/math/tools/promotion.hpp>\n\nnamespace stan {\n  namespace math {\n\n    template <typename T1, typename T2, int R1, int C1, int R2, int C2>\n    Eigen::Matrix<typename boost::math::tools::promote_args<T1, T2>::type,\n                  R2, C2>\n    diag_pre_multiply(const Eigen::Matrix<T1, R1, C1>& m1,\n                  const Eigen::Matrix<T2, R2, C2>& m2) {\n      check_vector(\"diag_pre_multiply\", \"m1\", m1);\n      int m2_rows = m2.rows();\n      check_size_match(\"diag_pre_multiply\",\n                       \"m1.size()\", m1.size(),\n                       \"m2.rows()\", m2_rows);\n      int m2_cols = m2.cols();\n      Eigen::Matrix<typename boost::math::tools::promote_args<T1, T2>::type,\n                    R2, C2>\n        result(m2_rows, m2_cols);\n      for (int j = 0; j < m2_cols; ++j)\n        for (int i = 0; i < m2_rows; ++i)\n          result(i, j) = m1(i) * m2(i, j);\n      return result;\n    }\n\n  }\n}\n#endif\n", "meta": {"hexsha": "152ea0388ce118e2b580affe1dee44a2c358ee41", "size": 1182, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/mat/fun/diag_pre_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/prim/mat/fun/diag_pre_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/prim/mat/fun/diag_pre_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": 33.7714285714, "max_line_length": 76, "alphanum_fraction": 0.60321489, "num_tokens": 347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.4993543671100745}}
{"text": "//This file was modified slightly from\n//  http://boost.2283326.n4.nabble.com/accumulators-histogram-td2639100.html\n//I just added the IsDensity flag\n#pragma once\n#include <vector>\n#include <limits>\n#include <functional>\n#include <boost/range.hpp>\n#include <boost/parameter/keyword.hpp>\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/count.hpp>\n#include <boost/accumulators/statistics/max.hpp>\n#include <boost/accumulators/statistics/min.hpp>\n\nnamespace boost { namespace accumulators\n{\n\n///////////////////////////////////////////////////////////////////////////////\n// cache_size and num_bins named parameters\n//\nBOOST_PARAMETER_NESTED_KEYWORD(tag, histogram_num_bins, num_bins)\nBOOST_PARAMETER_NESTED_KEYWORD(tag, histogram_min_range, min_range)\nBOOST_PARAMETER_NESTED_KEYWORD(tag, histogram_max_range, max_range)\n\nnamespace impl\n{\n    ///////////////////////////////////////////////////////////////////////////////\n    // histogram_impl\n    //  histogram histogram\n    /**\n        @brief Histogram histogram estimator\n\n        The histogram histogram estimator returns a histogram of the sample distribution. The positions and sizes of the bins\n        are determined using a specifiable number of cached samples (cache_size). The range between the minimum and the\n        maximum of the cached samples is subdivided into a specifiable number of bins (num_bins) of same size. Additionally,\n        an under- and an overflow bin is added to capture future under- and overflow samples. Once the bins are determined,\n        the cached samples and all subsequent samples are added to the correct bins. At the end, a range of std::pair is\n        return, where each pair contains the position of the bin (lower bound) and the samples count (normalized with the\n        total number of samples).\n\n        @param  histogram_cache_size Number of first samples used to determine min and max.\n        @param  histogram_num_bins Number of bins (two additional bins collect under- and overflow samples).\n    */\n    template<typename Sample, bool IsDensity>\n    struct histogram_impl\n      : accumulator_base\n    {\n        // typedef typename numeric::functional::average<Sample, std::size_t>::result_type float_type;\n        using float_type = double;\n        typedef std::vector<std::pair<float_type, float_type> > histogram_type;\n        typedef std::vector<float_type> array_type;\n        // for boost::result_of\n        typedef iterator_range<typename histogram_type::iterator> result_type;\n\n      template<typename Args>\n      histogram_impl(Args const& args) :\n\t\tnum_bins(args[histogram_num_bins]),\n\t\tminimum (args[histogram_min_range]),\n\t\tmaximum (args[histogram_max_range]),\n\t\tbin_size (numeric::average(args[histogram_max_range] - args[histogram_min_range], args[histogram_num_bins])),\n\t\tsamples_in_bin(args[histogram_num_bins] + 2, 0.),\n\t\tbin_positions(args[histogram_num_bins] + 2),\n\t\t_histogram(\n\t\t   args[histogram_num_bins] + 2,\n\t\t   std::make_pair(0,1)\n\t\t   ),\n\t     is_dirty(true)\n      {\n\t\t\t// determine bin positions (their lower bounds)\n            for (std::size_t i = 0; i < this->num_bins + 2; ++i)\n            {\n                this->bin_positions[i] = minimum + (i - 1.0) * bin_size;\n            }\n      }\n\n      template<typename Args>\n      void operator ()(Args const &args)\n      {\n\t\t\t// std::size_t cnt = count(args);\n            {\n                if (args[sample] < this->bin_positions[1])\n                {\n                    ++(this->samples_in_bin[0]);\n                }\n                else if (args[sample] >= this->bin_positions[this->num_bins + 1])\n                {\n                    ++(this->samples_in_bin[this->num_bins + 1]);\n                }\n                else\n                {\n                    typename array_type::iterator it = std::upper_bound(\n                        this->bin_positions.begin()\n                      , this->bin_positions.end()\n                      , args[sample]\n                    );\n\n                    std::size_t d = std::distance(this->bin_positions.begin(), it);\n                    ++(this->samples_in_bin[d - 1]);\n                }\n            }\n        }\n\n        template<typename Args>\n        result_type result(Args const &args) const\n        {\n            {\n                // creates a vector of std::pair where each pair i holds\n                // the values bin_positions[i] (x-axis of histogram) and\n                // samples_in_bin[i] / cnt (y-axis of histogram).\n\n                for (std::size_t i = 0; i < this->num_bins + 2; ++i)\n                {\n                    if(IsDensity)\n                       this->_histogram[i] = std::make_pair(this->bin_positions[i], numeric::average(this->samples_in_bin[i], count(args)));\n                    else\n                       this->_histogram[i] = std::make_pair(this->bin_positions[i], this->samples_in_bin[i]);\n                }\n            }\n            // returns a range of pairs\n            return make_iterator_range(this->_histogram);\n        }\n\n    private:\n        std::size_t\t\t\t\tnum_bins;        // number of bins\n\t\tfloat_type\t\t\t\tminimum;\n\t\tfloat_type\t\t\t\tmaximum;\n\t\tfloat_type\t\t\t\tbin_size;\n        array_type\t\t\t\tsamples_in_bin;  // number of samples in each bin\n        array_type\t\t\t\tbin_positions;   // lower bounds of bins\n        mutable histogram_type\t_histogram;       // histogram\n\t\tmutable\tbool\t\t\tis_dirty;\n    };\n\n} // namespace impl\n\n///////////////////////////////////////////////////////////////////////////////\n// tag::histogram_density and tag::histogram_count\n//\nnamespace tag\n{\n    template <bool IsDensity = false>\n    struct histogram_generic\n      : depends_on<count>\n\t      , histogram_num_bins\n\t\t  , histogram_min_range\n\t\t  , histogram_max_range\n    {\n        /// INTERNAL ONLY\n        ///\n\tstruct impl {\n\t  template<typename Sample, typename Weight>\n\t  struct apply {\n        typedef boost::accumulators::impl::histogram_impl<Sample, IsDensity> type;\n\t  };\n\t};\n    };\n\n    using histogram_density = histogram_generic<true>;\n    using histogram_count = histogram_generic<false>;\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// extract::histogram\n//\nnamespace extract\n{\n   extractor<tag::histogram_density> const histogram_density = {};\n   extractor<tag::histogram_count> const histogram_count = {};\n}\n\nusing extract::histogram_count;\nusing extract::histogram_density;\n\n// // So that histogram can be automatically substituted\n// // with weighted_histogram when the weight parameter is non-void.\n// template<>\n// struct as_weighted_feature<tag::histogram>\n// {\n//     typedef tag::weighted_histogram type;\n// };\n\n// template<>\n// struct feature_of<tag::weighted_histogram>\n//   : feature_of<tag::histogram>\n// {\n// };\n\n}} // namespace boost::accumulators\n\n\n", "meta": {"hexsha": "50aad2db4441493f19f40eb7a03ed3645d32d193", "size": 7131, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/stat_log/stats/accumulator_types/boost_hist.hpp", "max_stars_repo_name": "vladon/stat_log", "max_stars_repo_head_hexsha": "39cd364d6010dd6fd1d734d474961becccc04a09", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-08-08T18:12:59.000Z", "max_stars_repo_stars_event_max_datetime": "2016-08-08T18:12:59.000Z", "max_issues_repo_path": "include/stat_log/stats/accumulator_types/boost_hist.hpp", "max_issues_repo_name": "vladon/stat_log", "max_issues_repo_head_hexsha": "39cd364d6010dd6fd1d734d474961becccc04a09", "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/stat_log/stats/accumulator_types/boost_hist.hpp", "max_forks_repo_name": "vladon/stat_log", "max_forks_repo_head_hexsha": "39cd364d6010dd6fd1d734d474961becccc04a09", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-07-05T07:50:08.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-13T08:59:29.000Z", "avg_line_length": 36.1979695431, "max_line_length": 140, "alphanum_fraction": 0.6146403029, "num_tokens": 1510, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.6859494485880927, "lm_q1q2_score": 0.49935435776272447}}
{"text": "#include \"Integrator21GL.hh\"\n\n#include <Eigen/Dense>\n#include <map>\n#include <iterator>\n\n#include \"GSLSamplerGL.hh\"\n#include \"TypesFunctions.hh\"\n\nusing namespace Eigen;\nusing namespace std;\n\nIntegrator21GL::Integrator21GL(size_t xbins, int xorders, double* xedges, int yorder, double ymin, double ymax) :\nIntegrator21Base(xbins, xorders, xedges, yorder, ymin, ymax)\n{\n  init_sampler();\n}\n\nIntegrator21GL::Integrator21GL(size_t xbins, int* xorders, double* xedges, int yorder, double ymin, double ymax) :\nIntegrator21Base(xbins, xorders, xedges, yorder, ymin, ymax)\n{\n  init_sampler();\n}\n\nvoid Integrator21GL::sample(FunctionArgs& fargs){\n  auto& rets=fargs.rets;\n  GSLSamplerGL sampler;\n  auto& x=rets[0];\n  auto& y=rets[1];\n  sampler.fill_bins(m_xorders.size(), m_xorders.data(), m_xedges.data(), x.buffer, m_xweights.data());\n  sampler.fill(m_yorder, m_ymin, m_ymax, y.buffer, m_yweights.data());\n\n  m_weights = m_xweights.matrix() * m_yweights.matrix().transpose();\n\n  rets[2].x = m_xedges.cast<double>();\n\n  auto npoints=m_xedges.size()-1;\n  rets[3].x = 0.5*(m_xedges.tail(npoints)+m_xedges.head(npoints));\n  rets[4].mat = x.vec.replicate(1, m_yweights.size());\n  rets[5].mat = y.vec.transpose().replicate(m_xweights.size(), 1);\n  rets[6].x = 0.0;\n\n  rets.untaint();\n  rets.freeze();\n}\n\n", "meta": {"hexsha": "8482ab9fefdfe82e2d34ce622f10062ea1c2400c", "size": 1291, "ext": "cc", "lang": "C++", "max_stars_repo_path": "transformations/integrator/Integrator21GL.cc", "max_stars_repo_name": "gnafit/gna", "max_stars_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-10-14T01:06:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-02T16:33:06.000Z", "max_issues_repo_path": "transformations/integrator/Integrator21GL.cc", "max_issues_repo_name": "gnafit/gna", "max_issues_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "transformations/integrator/Integrator21GL.cc", "max_forks_repo_name": "gnafit/gna", "max_forks_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_forks_repo_licenses": ["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.4680851064, "max_line_length": 114, "alphanum_fraction": 0.7149496514, "num_tokens": 400, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118111485244, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4992775800698366}}
{"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_ASEC_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_ASEC_HPP_INCLUDED\n\n#include <boost/simd/detail/overload.hpp>\n#include <boost/simd/constant/pio_2.hpp>\n#include <boost/simd/function/acsc.hpp>\n#include <boost/simd/function/minus.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n   namespace bd = boost::dispatch;\n   namespace bs = boost::simd;\n  BOOST_DISPATCH_OVERLOAD_IF ( asec_\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      A0 tmp =  (Pio_2<A0>()-acsc(a0)) +  Constant<A0, 0x3c91a62633145c07ll>();\n      return if_zero_else(is_equal(a0, One<A0>()), tmp);\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD_IF( asec_\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        return (bs::Pio_2<A0>()-bs::acsc(a0));\n      }\n   };\n\n} } }\n\n#endif\n", "meta": {"hexsha": "64e2f9d343ed78a2c4273ae00ae9093fd862f705", "size": 1727, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/simd/function/asec.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/asec.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/asec.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.5849056604, "max_line_length": 100, "alphanum_fraction": 0.5066589461, "num_tokens": 400, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4992775697559786}}
{"text": "//=======================================================================\r\n// Copyright 2007 Aaron Windsor\r\n//\r\n// Distributed under the Boost Software License, Version 1.0. (See\r\n// accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n//=======================================================================\r\n#ifndef __IS_KURATOWSKI_SUBGRAPH_HPP__\r\n#define __IS_KURATOWSKI_SUBGRAPH_HPP__\r\n\r\n#include <boost/config.hpp>\r\n#include <boost/utility.hpp> //for next/prior\r\n#include <boost/tuple/tuple.hpp>   //for tie\r\n#include <boost/property_map/property_map.hpp>\r\n#include <boost/graph/properties.hpp>\r\n#include <boost/graph/isomorphism.hpp>\r\n#include <boost/graph/adjacency_list.hpp>\r\n\r\n#include <algorithm>\r\n#include <vector>\r\n#include <set>\r\n\r\n\r\n\r\nnamespace boost\r\n{\r\n  \r\n  namespace detail\r\n  {\r\n\r\n    template <typename Graph>\r\n    Graph make_K_5()\r\n    {\r\n      typename graph_traits<Graph>::vertex_iterator vi, vi_end, inner_vi;\r\n      Graph K_5(5);\r\n      for(tie(vi,vi_end) = vertices(K_5); vi != vi_end; ++vi)\r\n        for(inner_vi = next(vi); inner_vi != vi_end; ++inner_vi)\r\n          add_edge(*vi, *inner_vi, K_5);\r\n      return K_5;\r\n    }\r\n\r\n\r\n    template <typename Graph>\r\n    Graph make_K_3_3()\r\n    {\r\n      typename graph_traits<Graph>::vertex_iterator \r\n        vi, vi_end, bipartition_start, inner_vi;\r\n      Graph K_3_3(6);\r\n      bipartition_start = next(next(next(vertices(K_3_3).first)));\r\n      for(tie(vi, vi_end) = vertices(K_3_3); vi != bipartition_start; ++vi)\r\n        for(inner_vi= bipartition_start; inner_vi != vi_end; ++inner_vi)\r\n          add_edge(*vi, *inner_vi, K_3_3);\r\n      return K_3_3;\r\n    }\r\n\r\n\r\n    template <typename AdjacencyList, typename Vertex>\r\n    void contract_edge(AdjacencyList& neighbors, Vertex u, Vertex v)\r\n    {\r\n      // Remove u from v's neighbor list\r\n      neighbors[v].erase(std::remove(neighbors[v].begin(), \r\n                                     neighbors[v].end(), u\r\n                                     ), \r\n                         neighbors[v].end()\r\n                         );\r\n      \r\n      // Replace any references to u with references to v\r\n      typedef typename AdjacencyList::value_type::iterator \r\n        adjacency_iterator_t;\r\n      \r\n      adjacency_iterator_t u_neighbor_end = neighbors[u].end();\r\n      for(adjacency_iterator_t u_neighbor_itr = neighbors[u].begin();\r\n          u_neighbor_itr != u_neighbor_end; ++u_neighbor_itr\r\n          )\r\n        {\r\n          Vertex u_neighbor(*u_neighbor_itr);\r\n          std::replace(neighbors[u_neighbor].begin(), \r\n                       neighbors[u_neighbor].end(), u, v\r\n                       );\r\n        }\r\n      \r\n      // Remove v from u's neighbor list\r\n      neighbors[u].erase(std::remove(neighbors[u].begin(), \r\n                                     neighbors[u].end(), v\r\n                                     ), \r\n                         neighbors[u].end()\r\n                         );\r\n      \r\n      // Add everything in u's neighbor list to v's neighbor list\r\n      std::copy(neighbors[u].begin(), \r\n                neighbors[u].end(), \r\n                std::back_inserter(neighbors[v])\r\n                );\r\n      \r\n      // Clear u's neighbor list\r\n      neighbors[u].clear();\r\n\r\n    }\r\n\r\n    enum target_graph_t { tg_k_3_3, tg_k_5};\r\n\r\n  } // namespace detail\r\n\r\n\r\n\r\n\r\n  template <typename Graph, typename ForwardIterator, typename VertexIndexMap>\r\n  bool is_kuratowski_subgraph(const Graph& g,\r\n                              ForwardIterator begin, \r\n                              ForwardIterator end, \r\n                              VertexIndexMap vm\r\n                              )\r\n  {\r\n\r\n    typedef typename graph_traits<Graph>::vertex_descriptor vertex_t;\r\n    typedef typename graph_traits<Graph>::vertex_iterator vertex_iterator_t;\r\n    typedef typename graph_traits<Graph>::edge_descriptor edge_t;\r\n    typedef typename graph_traits<Graph>::edges_size_type e_size_t;\r\n    typedef typename graph_traits<Graph>::vertices_size_type v_size_t;\r\n    typedef typename std::vector<vertex_t> v_list_t;\r\n    typedef typename v_list_t::iterator v_list_iterator_t;\r\n    typedef iterator_property_map\r\n      <typename std::vector<v_list_t>::iterator, VertexIndexMap> \r\n      vertex_to_v_list_map_t;\r\n\r\n    typedef adjacency_list<vecS, vecS, undirectedS> small_graph_t;\r\n\r\n    detail::target_graph_t target_graph = detail::tg_k_3_3; //unless we decide otherwise later\r\n\r\n    static small_graph_t K_5(detail::make_K_5<small_graph_t>());\r\n\r\n    static small_graph_t K_3_3(detail::make_K_3_3<small_graph_t>());\r\n\r\n    v_size_t n_vertices(num_vertices(g));\r\n    v_size_t max_num_edges(3*n_vertices - 5);\r\n\r\n    std::vector<v_list_t> neighbors_vector(n_vertices);\r\n    vertex_to_v_list_map_t neighbors(neighbors_vector.begin(), vm);\r\n\r\n    e_size_t count = 0;\r\n    for(ForwardIterator itr = begin; itr != end; ++itr)\r\n      {\r\n\r\n        if (count++ > max_num_edges)\r\n          return false;\r\n\r\n        edge_t e(*itr);\r\n        vertex_t u(source(e,g));\r\n        vertex_t v(target(e,g));\r\n\r\n        neighbors[u].push_back(v);\r\n        neighbors[v].push_back(u);\r\n\r\n      }\r\n\r\n\r\n    for(v_size_t max_size = 2; max_size < 5; ++max_size)\r\n      {\r\n\r\n        vertex_iterator_t vi, vi_end;\r\n        for(tie(vi,vi_end) = vertices(g); vi != vi_end; ++vi)\r\n          {\r\n            vertex_t v(*vi);\r\n\r\n            //a hack to make sure we don't contract the middle edge of a path\r\n            //of four degree-3 vertices\r\n            if (max_size == 4 && neighbors[v].size() == 3)\r\n              {\r\n                if (neighbors[neighbors[v][0]].size() +\r\n                    neighbors[neighbors[v][1]].size() +\r\n                    neighbors[neighbors[v][2]].size()\r\n                    < 11 // so, it has two degree-3 neighbors\r\n                    )\r\n                  continue;\r\n              }\r\n\r\n            while (neighbors[v].size() > 0 && neighbors[v].size() < max_size)\r\n              {\r\n                // Find one of v's neighbors u such that that v and u\r\n                // have no neighbors in common. We'll look for such a \r\n                // neighbor with a naive cubic-time algorithm since the \r\n                // max size of any of the neighbor sets we'll consider \r\n                // merging is 3\r\n                \r\n                bool neighbor_sets_intersect = false;\r\n                \r\n                vertex_t min_u = graph_traits<Graph>::null_vertex();\r\n                vertex_t u;\r\n                v_list_iterator_t v_neighbor_end = neighbors[v].end();\r\n                for(v_list_iterator_t v_neighbor_itr = neighbors[v].begin();\r\n                    v_neighbor_itr != v_neighbor_end; \r\n                    ++v_neighbor_itr\r\n                    )\r\n                  {\r\n                    neighbor_sets_intersect = false;\r\n                    u = *v_neighbor_itr;\r\n                    v_list_iterator_t u_neighbor_end = neighbors[u].end();\r\n                    for(v_list_iterator_t u_neighbor_itr = \r\n                          neighbors[u].begin();\r\n                        u_neighbor_itr != u_neighbor_end && \r\n                          !neighbor_sets_intersect; \r\n                        ++u_neighbor_itr\r\n                        )\r\n                      {\r\n                        for(v_list_iterator_t inner_v_neighbor_itr = \r\n                              neighbors[v].begin();\r\n                            inner_v_neighbor_itr != v_neighbor_end; \r\n                            ++inner_v_neighbor_itr\r\n                            )\r\n                          {\r\n                            if (*u_neighbor_itr == *inner_v_neighbor_itr)\r\n                              {\r\n                                neighbor_sets_intersect = true;\r\n                                break;\r\n                              }\r\n                          }\r\n                        \r\n                      }\r\n                    if (!neighbor_sets_intersect &&\r\n                        (min_u == graph_traits<Graph>::null_vertex() || \r\n                         neighbors[u].size() < neighbors[min_u].size())\r\n                        )\r\n                      {\r\n                        min_u = u;\r\n                      }\r\n                        \r\n                  }\r\n\r\n                if (min_u == graph_traits<Graph>::null_vertex())\r\n                  // Exited the loop without finding an appropriate neighbor of\r\n                  // v, so v must be a lost cause. Move on to other vertices.\r\n                  break;\r\n                else\r\n                  u = min_u;\r\n\r\n                detail::contract_edge(neighbors, u, v);\r\n\r\n              }//end iteration over v's neighbors\r\n\r\n          }//end iteration through vertices v\r\n\r\n        if (max_size == 3)\r\n          {\r\n            // check to see whether we should go on to find a K_5\r\n            for(tie(vi,vi_end) = vertices(g); vi != vi_end; ++vi)\r\n              if (neighbors[*vi].size() == 4)\r\n                {\r\n                  target_graph = detail::tg_k_5;\r\n                  break;\r\n                }\r\n\r\n            if (target_graph == detail::tg_k_3_3)\r\n              break;\r\n          }\r\n        \r\n      }//end iteration through max degree 2,3, and 4\r\n\r\n    \r\n    //Now, there should only be 5 or 6 vertices with any neighbors. Find them.\r\n    \r\n    v_list_t main_vertices;\r\n    vertex_iterator_t vi, vi_end;\r\n    \r\n    for(tie(vi,vi_end) = vertices(g); vi != vi_end; ++vi)\r\n      {\r\n        if (!neighbors[*vi].empty())\r\n          main_vertices.push_back(*vi);\r\n      }\r\n    \r\n    // create a graph isomorphic to the contracted graph to test \r\n    // against K_5 and K_3_3\r\n    small_graph_t contracted_graph(main_vertices.size());\r\n    std::map<vertex_t,typename graph_traits<small_graph_t>::vertex_descriptor> \r\n      contracted_vertex_map;\r\n    \r\n    typename v_list_t::iterator itr, itr_end;\r\n    itr_end = main_vertices.end();\r\n    typename graph_traits<small_graph_t>::vertex_iterator \r\n      si = vertices(contracted_graph).first;\r\n    \r\n    for(itr = main_vertices.begin(); itr != itr_end; ++itr, ++si)\r\n      {\r\n        contracted_vertex_map[*itr] = *si;\r\n      }\r\n\r\n    typename v_list_t::iterator jtr, jtr_end;\r\n    for(itr = main_vertices.begin(); itr != itr_end; ++itr)\r\n      {\r\n        jtr_end = neighbors[*itr].end();\r\n        for(jtr = neighbors[*itr].begin(); jtr != jtr_end; ++jtr)\r\n          {\r\n            if (get(vm,*itr) < get(vm,*jtr))\r\n              {\r\n                add_edge(contracted_vertex_map[*itr],\r\n                         contracted_vertex_map[*jtr],\r\n                         contracted_graph\r\n                         );\r\n              }\r\n          }\r\n      }\r\n    \r\n    if (target_graph == detail::tg_k_5)\r\n      {\r\n        return isomorphism(K_5,contracted_graph);\r\n      }\r\n    else //target_graph == tg_k_3_3\r\n      {\r\n        return isomorphism(K_3_3,contracted_graph);\r\n      }\r\n    \r\n    \r\n  }\r\n\r\n\r\n\r\n\r\n\r\n  template <typename Graph, typename ForwardIterator>\r\n  bool is_kuratowski_subgraph(const Graph& g, \r\n                              ForwardIterator begin, \r\n                              ForwardIterator end\r\n                              )\r\n  {\r\n    return is_kuratowski_subgraph(g, begin, end, get(vertex_index,g));\r\n  }\r\n\r\n\r\n\r\n  \r\n}\r\n\r\n#endif //__IS_KURATOWSKI_SUBGRAPH_HPP__\r\n", "meta": {"hexsha": "a9509649f0c9c050122e1b3d8560d30169c21443", "size": 11281, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "trunk/win/Source/Includes/Boost/graph/is_kuratowski_subgraph.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/graph/is_kuratowski_subgraph.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/graph/is_kuratowski_subgraph.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": 33.8768768769, "max_line_length": 95, "alphanum_fraction": 0.5099725202, "num_tokens": 2352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859598, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.4991291025590494}}
{"text": "//\n// Created by Alex Beccaro on 21/03/18.\n//\n\n#define BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n#include \"../../src/problems/101-150/101/problem101.hpp\"\n\nBOOST_AUTO_TEST_SUITE( Problem101 )\n\n    BOOST_AUTO_TEST_CASE( Example1 ) {\n        auto res = problems::problem101::solve([](int32_t x) { return x * x * x; });\n        BOOST_CHECK_EQUAL(res, 74);\n    }\n\n    BOOST_AUTO_TEST_CASE( Solution ) {\n        auto res = problems::problem101::solve();\n        BOOST_CHECK_EQUAL(res, 37076114526);\n    }\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "41e764b9f8ac039ce028ccbbb686d54f20955729", "size": 541, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/101-150/test_problem101.cpp", "max_stars_repo_name": "abeccaro/project-euler", "max_stars_repo_head_hexsha": "c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T10:17:15.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-25T10:17:15.000Z", "max_issues_repo_path": "tests/101-150/test_problem101.cpp", "max_issues_repo_name": "abeccaro/project-euler", "max_issues_repo_head_hexsha": "c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3", "max_issues_repo_licenses": ["MIT"], "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/101-150/test_problem101.cpp", "max_forks_repo_name": "abeccaro/project-euler", "max_forks_repo_head_hexsha": "c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3", "max_forks_repo_licenses": ["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.7619047619, "max_line_length": 84, "alphanum_fraction": 0.6709796673, "num_tokens": 141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859598, "lm_q2_score": 0.6513548714339145, "lm_q1q2_score": 0.4991290973728813}}
{"text": "//\n// Copyright (c) 2015-2020 CNRS INRIA\n// Copyright (c) 2015 Wandercraft, 86 rue de Paris 91400 Orsay, France.\n//\n\n#include \"pinocchio/math/fwd.hpp\"\n#include \"pinocchio/multibody/joint/joints.hpp\"\n#include \"pinocchio/algorithm/rnea.hpp\"\n#include \"pinocchio/algorithm/aba.hpp\"\n#include \"pinocchio/algorithm/crba.hpp\"\n#include \"pinocchio/algorithm/jacobian.hpp\"\n#include \"pinocchio/algorithm/compute-all-terms.hpp\"\n\n#include <boost/test/unit_test.hpp>\n#include <iostream>\n\nusing namespace pinocchio;\n\ntemplate<typename D>\nvoid addJointAndBody(Model & model,\n                     const JointModelBase<D> & jmodel,\n                     const Model::JointIndex parent_id,\n                     const SE3 & joint_placement,\n                     const std::string & joint_name,\n                     const Inertia & Y)\n{\n  Model::JointIndex idx;\n  \n  idx = model.addJoint(parent_id,jmodel,joint_placement,joint_name);\n  model.appendBodyToJoint(idx,Y);\n}\n\nBOOST_AUTO_TEST_SUITE(JointSpherical)\n  \nBOOST_AUTO_TEST_CASE(spatial)\n{\n  SE3 M(SE3::Random());\n  Motion v(Motion::Random());\n  \n  MotionSpherical mp(MotionSpherical::Vector3(1.,2.,3.));\n  Motion mp_dense(mp);\n  \n  BOOST_CHECK(M.act(mp).isApprox(M.act(mp_dense)));\n  BOOST_CHECK(M.actInv(mp).isApprox(M.actInv(mp_dense)));\n  \n  BOOST_CHECK(v.cross(mp).isApprox(v.cross(mp_dense)));\n}\n\nBOOST_AUTO_TEST_CASE(vsFreeFlyer)\n{\n  using namespace pinocchio;\n  typedef SE3::Vector3 Vector3;\n  typedef Eigen::Matrix <double, 6, 1> Vector6;\n  typedef Eigen::Matrix <double, 7, 1> VectorFF;\n  typedef SE3::Matrix3 Matrix3;\n\n  Model modelSpherical, modelFreeflyer;\n\n  Inertia inertia(1., Vector3(0.5, 0., 0.0), Matrix3::Identity());\n  SE3 pos(1); pos.translation() = SE3::LinearType(1.,0.,0.);\n\n  addJointAndBody(modelSpherical,JointModelSpherical(),0,pos,\"spherical\",inertia);\n  addJointAndBody(modelFreeflyer,JointModelFreeFlyer(),0,pos,\"free-flyer\",inertia);\n  \n  Data dataSpherical(modelSpherical);\n  Data dataFreeFlyer(modelFreeflyer);\n\n  Eigen::VectorXd q = Eigen::VectorXd::Ones(modelSpherical.nq);q.normalize();\n  VectorFF qff; qff << 0, 0, 0, q[0], q[1], q[2], q[3];\n  Eigen::VectorXd v = Eigen::VectorXd::Ones(modelSpherical.nv);\n  Vector6 vff; vff << 0, 0, 0, 1, 1, 1;\n  Eigen::VectorXd tauSpherical = Eigen::VectorXd::Ones(modelSpherical.nv);\n  Eigen::VectorXd tauff; tauff.resize(7); tauff << 0,0,0,1,1,1,1;\n  Eigen::VectorXd aSpherical = Eigen::VectorXd::Ones(modelSpherical.nv);\n  Eigen::VectorXd aff(vff);\n  \n  forwardKinematics(modelSpherical, dataSpherical, q, v);\n  forwardKinematics(modelFreeflyer, dataFreeFlyer, qff, vff);\n\n  computeAllTerms(modelSpherical, dataSpherical, q, v);\n  computeAllTerms(modelFreeflyer, dataFreeFlyer, qff, vff);\n\n  BOOST_CHECK(dataFreeFlyer.oMi[1].isApprox(dataSpherical.oMi[1]));\n  BOOST_CHECK(dataFreeFlyer.liMi[1].isApprox(dataSpherical.liMi[1]));\n  BOOST_CHECK(dataFreeFlyer.Ycrb[1].matrix().isApprox(dataSpherical.Ycrb[1].matrix()));\n  BOOST_CHECK(dataFreeFlyer.f[1].toVector().isApprox(dataSpherical.f[1].toVector()));\n  \n  Eigen::VectorXd nle_expected_ff(3); nle_expected_ff << dataFreeFlyer.nle[3],\n                                                         dataFreeFlyer.nle[4],\n                                                         dataFreeFlyer.nle[5]\n                                                         ;\n  BOOST_CHECK(nle_expected_ff.isApprox(dataSpherical.nle));\n  BOOST_CHECK(dataFreeFlyer.com[0].isApprox(dataSpherical.com[0]));\n\n  // InverseDynamics == rnea\n  tauSpherical = rnea(modelSpherical, dataSpherical, q, v, aSpherical);\n  tauff = rnea(modelFreeflyer, dataFreeFlyer, qff, vff, aff);\n\n  Vector3 tau_expected; tau_expected << tauff(3), tauff(4), tauff(5);\n  BOOST_CHECK(tauSpherical.isApprox(tau_expected));\n\n  // ForwardDynamics == aba\n  Eigen::VectorXd aAbaSpherical = aba(modelSpherical,dataSpherical, q, v, tauSpherical);\n  Eigen::VectorXd aAbaFreeFlyer = aba(modelFreeflyer,dataFreeFlyer, qff, vff, tauff);\n  Vector3 a_expected; a_expected << aAbaFreeFlyer[3],\n                                    aAbaFreeFlyer[4],\n                                    aAbaFreeFlyer[5]\n                                    ;\n  BOOST_CHECK(aAbaSpherical.isApprox(a_expected));\n\n  // crba\n  crba(modelSpherical, dataSpherical,q);\n  crba(modelFreeflyer, dataFreeFlyer, qff);\n\n  Eigen::Matrix<double, 3, 3> M_expected(dataFreeFlyer.M.bottomRightCorner<3,3>());\n\n  BOOST_CHECK(dataSpherical.M.isApprox(M_expected));\n   \n  // Jacobian\n  Eigen::Matrix<double, 6, Eigen::Dynamic> jacobian_planar;jacobian_planar.resize(6,3); jacobian_planar.setZero();\n  Eigen::Matrix<double, 6, Eigen::Dynamic> jacobian_ff;jacobian_ff.resize(6,6);jacobian_ff.setZero();\n  computeJointJacobians(modelSpherical, dataSpherical, q);\n  computeJointJacobians(modelFreeflyer, dataFreeFlyer, qff);\n  getJointJacobian(modelSpherical, dataSpherical, 1, LOCAL, jacobian_planar);\n  getJointJacobian(modelFreeflyer, dataFreeFlyer, 1, LOCAL, jacobian_ff);\n\n\n  Eigen::Matrix<double, 6, 3> jacobian_expected; jacobian_expected << jacobian_ff.col(3),\n                                                                      jacobian_ff.col(4),\n                                                                      jacobian_ff.col(5)\n                                                                      ;\n\n  BOOST_CHECK(jacobian_planar.isApprox(jacobian_expected));\n\n}\nBOOST_AUTO_TEST_SUITE_END()\n\nBOOST_AUTO_TEST_SUITE(JointSphericalZYX)\n  \nBOOST_AUTO_TEST_CASE(spatial)\n{\n  SE3 M(SE3::Random());\n  Motion v(Motion::Random());\n  \n  MotionSpherical mp(MotionSpherical::Vector3(1.,2.,3.));\n  Motion mp_dense(mp);\n  \n  BOOST_CHECK(M.act(mp).isApprox(M.act(mp_dense)));\n  BOOST_CHECK(M.actInv(mp).isApprox(M.actInv(mp_dense)));\n  \n  BOOST_CHECK(v.cross(mp).isApprox(v.cross(mp_dense)));\n}\n\nBOOST_AUTO_TEST_CASE(vsFreeFlyer)\n{\n  // WARNIG : Dynamic algorithm's results cannot be compared to FreeFlyer's ones because\n  // of the representation of the rotation and the ConstraintSubspace difference.\n  using namespace pinocchio;\n  typedef SE3::Vector3 Vector3;\n  typedef Eigen::Matrix <double, 6, 1> Vector6;\n  typedef Eigen::Matrix <double, 7, 1> VectorFF;\n  typedef SE3::Matrix3 Matrix3;\n\n  Model modelSphericalZYX, modelFreeflyer;\n\n  Inertia inertia(1., Vector3(0.5, 0., 0.0), Matrix3::Identity());\n  SE3 pos(1); pos.translation() = SE3::LinearType(1.,0.,0.);\n\n  addJointAndBody(modelSphericalZYX,JointModelSphericalZYX(),0,pos,\"spherical-zyx\",inertia);\n  addJointAndBody(modelFreeflyer,JointModelFreeFlyer(),0,pos,\"free-flyer\",inertia);\n\n  Data dataSphericalZYX(modelSphericalZYX);\n  Data dataFreeFlyer(modelFreeflyer);\n\n  Eigen::AngleAxisd rollAngle(1, Eigen::Vector3d::UnitZ());\n  Eigen::AngleAxisd yawAngle(1, Eigen::Vector3d::UnitY());\n  Eigen::AngleAxisd pitchAngle(1, Eigen::Vector3d::UnitX());\n  Eigen::Quaterniond q_sph = rollAngle * yawAngle * pitchAngle;\n  \n  Eigen::VectorXd q = Eigen::VectorXd::Ones(modelSphericalZYX.nq);\n  VectorFF qff; qff << 0, 0, 0, q_sph.x(), q_sph.y(), q_sph.z(), q_sph.w();\n  Eigen::VectorXd v = Eigen::VectorXd::Ones(modelSphericalZYX.nv);\n  Vector6 vff; vff << 0, 0, 0, 1, 1, 1;\n  Eigen::VectorXd tauSpherical = Eigen::VectorXd::Ones(modelSphericalZYX.nv);\n  Eigen::VectorXd tauff; tauff.resize(6); tauff << 0,0,0,1,1,1;\n  Eigen::VectorXd aSpherical = Eigen::VectorXd::Ones(modelSphericalZYX.nv);\n  Eigen::VectorXd aff(vff);\n  \n  forwardKinematics(modelSphericalZYX, dataSphericalZYX, q, v);\n  forwardKinematics(modelFreeflyer, dataFreeFlyer, qff, vff);\n\n  computeAllTerms(modelSphericalZYX, dataSphericalZYX, q, v);\n  computeAllTerms(modelFreeflyer, dataFreeFlyer, qff, vff);\n\n  BOOST_CHECK(dataFreeFlyer.oMi[1].isApprox(dataSphericalZYX.oMi[1]));\n  BOOST_CHECK(dataFreeFlyer.liMi[1].isApprox(dataSphericalZYX.liMi[1]));\n  BOOST_CHECK(dataFreeFlyer.Ycrb[1].matrix().isApprox(dataSphericalZYX.Ycrb[1].matrix()));\n\n  BOOST_CHECK(dataFreeFlyer.com[0].isApprox(dataSphericalZYX.com[0]));\n}\n\nBOOST_AUTO_TEST_CASE(test_rnea)\n{\n  using namespace pinocchio;\n  typedef SE3::Vector3 Vector3;\n  typedef SE3::Matrix3 Matrix3;\n\n  Model model;\n  Inertia inertia(1., Vector3(0.5, 0., 0.0), Matrix3::Identity());\n\n  addJointAndBody(model,JointModelSphericalZYX(),model.getJointId(\"universe\"),SE3::Identity(),\"root\",inertia);\n\n  Data data(model);\n\n  Eigen::VectorXd q = Eigen::VectorXd::Zero(model.nq);\n  Eigen::VectorXd v = Eigen::VectorXd::Zero(model.nv);\n  Eigen::VectorXd a = Eigen::VectorXd::Zero(model.nv);\n\n  rnea(model, data, q, v, a);\n  Vector3 tau_expected(0., -4.905, 0.);\n\n  BOOST_CHECK(tau_expected.isApprox(data.tau, 1e-14));\n\n  q = Eigen::VectorXd::Ones(model.nq);\n  v = Eigen::VectorXd::Ones(model.nv);\n  a = Eigen::VectorXd::Ones(model.nv);\n\n  rnea(model, data, q, v, a);\n  tau_expected << -0.53611600195085, -0.74621832606188, -0.38177329067604;\n\n  BOOST_CHECK(tau_expected.isApprox(data.tau, 1e-12));\n\n  q << 3, 2, 1;\n  v = Eigen::VectorXd::Ones(model.nv);\n  a = Eigen::VectorXd::Ones(model.nv);\n\n  rnea(model, data, q, v, a);\n  tau_expected << 0.73934458094049,  2.7804530848031, 0.50684940972146;\n\n  BOOST_CHECK(tau_expected.isApprox(data.tau, 1e-12));\n}\n\nBOOST_AUTO_TEST_CASE(test_crba)\n{\n  using namespace pinocchio;\n  using namespace std;\n  typedef SE3::Vector3 Vector3;\n  typedef SE3::Matrix3 Matrix3;\n\n  Model model;\n  Inertia inertia(1., Vector3(0.5, 0., 0.0), Matrix3::Identity());\n\n  addJointAndBody(model,JointModelSphericalZYX(),model.getJointId(\"universe\"),SE3::Identity(),\"root\",inertia);\n\n  Data data(model);\n\n  Eigen::VectorXd q(Eigen::VectorXd::Zero(model.nq));\n  Eigen::MatrixXd M_expected(model.nv,model.nv);\n\n  crba(model, data, q);\n  M_expected <<\n  1.25,    0,    0,\n  0, 1.25,    0,\n  0,    0,    1;\n\n  BOOST_CHECK(M_expected.isApprox(data.M, 1e-14));\n\n  q = Eigen::VectorXd::Ones(model.nq);\n\n  crba(model, data, q);\n  M_expected <<\n  1.0729816454316, -5.5511151231258e-17,     -0.8414709848079,\n  -5.5511151231258e-17,                 1.25,                    0,\n  -0.8414709848079,                    0,                    1;\n\n  BOOST_CHECK(M_expected.isApprox(data.M, 1e-12));\n\n  q << 3, 2, 1;\n\n  crba(model, data, q);\n  M_expected <<\n  1.043294547392, 2.7755575615629e-17,   -0.90929742682568,\n  0,                1.25,                   0,\n  -0.90929742682568,                   0,                  1;\n\n  BOOST_CHECK(M_expected.isApprox(data.M, 1e-10));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "4a5068221e781e3f1b85a2bb6ceb301c6cc3e3cc", "size": 10311, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittest/joint-spherical.cpp", "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": "unittest/joint-spherical.cpp", "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": "unittest/joint-spherical.cpp", "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": 35.5551724138, "max_line_length": 114, "alphanum_fraction": 0.6780137717, "num_tokens": 3121, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6513548714339145, "lm_q1q2_score": 0.49912909737288125}}
{"text": "#include<iostream>\r\n#include<cmath>\r\n#include<algorithm>\r\n#include<vector>\r\n#include<ctime>\r\n#include <boost/random.hpp>\r\n#include <boost/random/mersenne_twister.hpp>\r\n#include <boost/random/normal_distribution.hpp>\r\n#include <boost/random/variate_generator.hpp>\r\n#include<fstream>  \r\n#include<string>\r\n#include <numeric>\r\nusing namespace std;\r\n// Function to print the vector\r\nvoid PrintData(vector<double>& data);\r\n// Function to print the matrix\r\nvoid PrintData(vector< vector<double> >& data);\r\n\r\n// Function to do Cholesky decomposition\r\nvector< vector<double> > Cholesky(vector< vector<double> >& data);\r\n\r\n//Function to write matrix into csv file\r\nvoid WriteToCsv(string CsvFile, vector< vector<double> >& data);\r\n\r\n//Function to write vector into csv file\r\nvoid WriteToCsv(string CsvFile, vector<double>& data);\r\n\r\n// Function to calculate standard deviation\r\ndouble CaclVariance(vector<double>& data);", "meta": {"hexsha": "00776289061b3d30b7f7edee1fd917f7ed3abc5a", "size": 910, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Extra.hpp", "max_stars_repo_name": "icezerowjj/Monte-Carlo-Simulation", "max_stars_repo_head_hexsha": "a9cfb6cc0fcdd274138590f2845b758d8bc3c9e7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-01-27T15:17:59.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-27T15:17:59.000Z", "max_issues_repo_path": "Extra.hpp", "max_issues_repo_name": "icezerowjj/Monte-Carlo-Option-Pricing", "max_issues_repo_head_hexsha": "a9cfb6cc0fcdd274138590f2845b758d8bc3c9e7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Extra.hpp", "max_forks_repo_name": "icezerowjj/Monte-Carlo-Option-Pricing", "max_forks_repo_head_hexsha": "a9cfb6cc0fcdd274138590f2845b758d8bc3c9e7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-04-11T06:14:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-19T04:20:04.000Z", "avg_line_length": 31.3793103448, "max_line_length": 67, "alphanum_fraction": 0.7483516484, "num_tokens": 191, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548646660543, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.499129092186713}}
{"text": "#include <catch.hpp>\n#include <Eigen/Core>\n#include <random>\n\n#include \"check_adjoint.h\"\n#include \"test_utils.h\"\n#include \"renderer_blending.cuh\"\n\n\ntemplate<kernel::BlendMode blendMode>\nvoid testAdjointBlending()\n{\n\ttypedef empty TmpStorage_t;\n\ttypedef VectorXr Vector_t;\n\n\tauto forward = [](const Vector_t& x, TmpStorage_t* tmp) -> Vector_t\n\t{\n\t\tconst real4 acc = fromEigen4(x.segment(0, 4));\n\t\tconst real4 current = fromEigen4(x.segment(4, 4));\n\t\tconst real_t stepsize = x[8];\n\n\t\tconst real4 output = kernel::Blending<blendMode>::blend(\n\t\t\tacc, current, stepsize);\n\n\t\treturn toEigen(output);\n\t};\n\tauto adjoint = [](const Vector_t& x, const Vector_t& e, const Vector_t& g,\n\t\tVector_t& z, const TmpStorage_t& tmp)\n\t{\n\t\tconst real4 acc = fromEigen4(x.segment(0, 4));\n\t\tconst real4 current = fromEigen4(x.segment(4, 4));\n\t\tconst real_t stepsize = x[8];\n\n\t\tconst real4 output = fromEigen4(e);\n\t\tconst real4 adj_output = fromEigen4(g);\n\n\t\treal4 adj_acc, adj_current;\n\t\treal_t adj_stepsize;\n\n\t\treal4 acc_in = kernel::Blending<blendMode>::adjoint(\n\t\t\toutput, current, stepsize, adj_output,\n\t\t\tadj_acc, adj_current, adj_stepsize);\n\n\t\tINFO(\"input-acc: \" << acc);\n\t\tINFO(\"reconstructed-acc: \" << acc_in);\n\t\tREQUIRE(acc.x == Approx(acc_in.x));\n\t\tREQUIRE(acc.y == Approx(acc_in.y));\n\t\tREQUIRE(acc.z == Approx(acc_in.z));\n\t\tREQUIRE(acc.w == Approx(acc_in.w));\n\n\t\tz.segment<4>(0) = toEigen(adj_acc);\n\t\tz.segment<4>(4) = toEigen(adj_current);\n\t\tz[8] = adj_stepsize;\n\t};\n\n\tstd::default_random_engine rnd(42);\n\tstd::uniform_real_distribution<real_t> distr(0.01, 0.99);\n\tint N = 20;\n\tfor (int i = 0; i < N; ++i)\n\t{\n\t\tINFO(\"N=\" << i);\n\t\tVector_t x(9);\n\t\tfor (int j = 0; j < 9; ++j) x[j] = distr(rnd);\n\n\t\tcheckAdjoint<Vector_t, TmpStorage_t>(x, forward, adjoint,\n\t\t\t1e-5, 1e-5, 1e-6);\n\t}\n}\n\nTEST_CASE(\"Adjoint-Blending-BeerLambert\", \"[adjoint]\")\n{\n\ttestAdjointBlending<kernel::BlendBeerLambert>();\n}\n\nTEST_CASE(\"Adjoint-Blending-Alpha\", \"[adjoint]\")\n{\n\ttestAdjointBlending<kernel::BlendAlpha>();\n}\n\n", "meta": {"hexsha": "1aa1aad910a6beaaffcbd4193f42ab9be8327aeb", "size": 1980, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittests/testAdjointBlending.cpp", "max_stars_repo_name": "shamanDevel/DiffDVR", "max_stars_repo_head_hexsha": "99fbe9f114d0097daf402bde2ae35f18dade335d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2021-08-02T04:51:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-14T18:02:27.000Z", "max_issues_repo_path": "unittests/testAdjointBlending.cpp", "max_issues_repo_name": "shamanDevel/DiffDVR", "max_issues_repo_head_hexsha": "99fbe9f114d0097daf402bde2ae35f18dade335d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-11-04T14:23:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-28T10:30:13.000Z", "max_forks_repo_path": "unittests/testAdjointBlending.cpp", "max_forks_repo_name": "shamanDevel/DiffDVR", "max_forks_repo_head_hexsha": "99fbe9f114d0097daf402bde2ae35f18dade335d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-07-16T10:23:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-04T02:51:43.000Z", "avg_line_length": 24.75, "max_line_length": 75, "alphanum_fraction": 0.6803030303, "num_tokens": 632, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.4991290921867129}}
{"text": "//============================================================================\n// Daniel J. Greenhoe\n// normed linear space R^2\n//=============================================================================\n//=====================================\n// headers\n//=====================================\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <Eigen/Dense>  // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=89325\n#include \"r1.h\"\n#include \"r4.h\"\ntypedef Eigen::Matrix< double, 4, 1 > Vector4d;\n\n//=====================================\n// oquad\n//=====================================\n//-----------------------------------------------------------------------------\n// oquad constructors\n//-----------------------------------------------------------------------------\noquad::oquad(void)\n{\n  xx.at(0) = 0.0;\n  xx.at(1) = 0.0;\n  xx.at(2) = 0.0;\n  xx.at(3) = 0.0;\n}\n\noquad::oquad(double u0, double u1, double u2, double u3)\n{\n  xx.at(0) = u0;\n  xx.at(1) = u1;\n  xx.at(2) = u2;\n  xx.at(3) = u3;\n}\n\noquad::oquad(double u)\n{\n  xx.at(0) = u;\n  xx.at(1) = u;\n  xx.at(2) = u;\n  xx.at(3) = u;\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief oquad put member functions\n//-----------------------------------------------------------------------------\nvoid oquad::put(double u)\n{\n  xx.at(0) = u;\n  xx.at(1) = u;\n  xx.at(2) = u;\n  xx.at(3) = u;\n}\n\nvoid oquad::put(oquad u)\n{\n  xx.at(0) = u.get(0);\n  xx.at(1) = u.get(1);\n  xx.at(2) = u.get(2);\n  xx.at(3) = u.get(3);\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief Write values to oquad\n//-----------------------------------------------------------------------------\nvoid oquad::put(double u0, double u1, double u2, double u3)\n{\n  xx.at(0) = u0;\n  xx.at(1) = u1;\n  xx.at(2) = u2;\n  xx.at(3) = u3;\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief Write values to oquad\n//-----------------------------------------------------------------------------\nvoid oquad::put(int n,double u)\n{\n  xx.at(n) = u;\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief return the 4-tuple value\n//-----------------------------------------------------------------------------\noquad oquad::get(void)\n{\n  oquad u;\n  u.put( 0, get1() );\n  u.put( 1, get2() );\n  u.put( 2, get3() );\n  u.put( 3, get4() );\n  return u;\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief return the minimum element of the 4 tupple\n//-----------------------------------------------------------------------------\ndouble oquad::min(void) const\n{\n  const Eigen::Map< const Vector4d > a( getdata() );\n  const double minVal = a.minCoeff();\n  return minVal;\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief return the maximum element of the 4 tupple\n//-----------------------------------------------------------------------------\ndouble oquad::max(void) const\n{\n  const Eigen::Map< const Vector4d > a( getdata() );\n  const double maxVal = a.maxCoeff();\n  return maxVal;\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief print the tuple\n//-----------------------------------------------------------------------------\nvoid oquad::list(const char *str1, const char *str2) const\n{\n  if(strlen(str1)!=0)printf(\"%s\",str1);\n  putchar('(');\n  printf(\"%9.6lf,\", get1() );\n  printf(\"%9.6lf,\", get2() );\n  printf(\"%9.6lf,\", get3() );\n  printf(\"%9.6lf)\", get4() );\n  if(strlen(str2)!=0)printf(\"%s\",str2);\n}\n\n//=====================================\n// vectR4 functions\n//=====================================\n//-----------------------------------------------------------------------------\n//! \\brief return the 4-tuple value\n//-----------------------------------------------------------------------------\nconst vectR4 vectR4::get(void)\n{\n  vectR4 u;\n  u.put( 0, get1() );\n  u.put( 1, get2() );\n  u.put( 2, get3() );\n  u.put( 3, get4() );\n  return u;\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief magnitude\n//-----------------------------------------------------------------------------\ndouble vectR4::mag(void) const\n{\n  const Eigen::Map< const Vector4d > a( getdata() );\n  return a.norm();\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief Multiply the vector by a scalar a\n//-----------------------------------------------------------------------------\nvectR4 vectR4::mpy(const double a)\n{\n  vectR4 w;\n  const Eigen::Map< const Vector4d > vv( getdata() );\n  Eigen::Map< Vector4d > ww( w.getdataa() );\n  ww = a * vv;\n  return w;\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief operator: +=\n//-----------------------------------------------------------------------------\nvoid vectR4::operator+=(vectR4 q)\n{\n  Eigen::Map< Vector4d > pp( getdataa() );\n  const Eigen::Map< const Vector4d > qq( q.getdata() );\n  pp = pp + qq;\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief operator: -=\n//-----------------------------------------------------------------------------\nvoid vectR4::operator-=(vectR4 q)\n{\n  Eigen::Map< Vector4d > pp( getdataa() );\n  const Eigen::Map< const Vector4d > qq( q.getdata() );\n  pp = pp - qq;\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief operator: -=\n//-----------------------------------------------------------------------------\nvoid vectR4::operator*=(double a)\n{\n  vectR4  p=get();\n  p = a*p;\n  put(p);\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief operator: a*y\n//-----------------------------------------------------------------------------\nvectR4 operator*(const double a, const vectR4 x)\n{\n  vectR4 y;\n  const Eigen::Map< const Vector4d > xx( x.getdata() );\n  Eigen::Map< Vector4d > yy( y.getdataa() );\n  yy = a * xx;\n  return y;\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief operator: dot product of p and q\n//-----------------------------------------------------------------------------\ndouble operator^(vectR4 p,vectR4 q)\n{\n  const  Eigen::Map< const Vector4d > pp( p.getdata() );\n  const  Eigen::Map< const Vector4d > qq( q.getdata() );\n  double innerProduct = pp.adjoint() * qq;\n  return innerProduct;\n}\n\n//=====================================\n//! \\brief seqR4\n//=====================================\n//-----------------------------------------------------------------------------\n//! \\brief constructor initializing seqR1 to 0\n//-----------------------------------------------------------------------------\nseqR4::seqR4(long M)\n{\n  N=M;\n  x = new vectR4[N];\n  clear();\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief constructor initializing seqR1 to <u>\n//-----------------------------------------------------------------------------\nseqR4::seqR4( long M, double u )\n{\n  N=M;\n  x = new vectR4[N];\n  fill( u );\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief Fill the seqR3 with a value 0\n//-----------------------------------------------------------------------------\nvoid seqR4::clear(void)\n{\n  fill( 0.0 );\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief fill the seqR4 with a value <u>\n//-----------------------------------------------------------------------------\nvoid seqR4::fill(double u)\n{\n  for(long n=0; n<N; n++) put( n, u );\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief put a single value u=(u1,u2,u3,u4) into the seqR4 x at location n\n//-----------------------------------------------------------------------------\nint seqR4::put(long n, double u1,double u2,double u3,double u4)\n{\n  int retval=0;\n  if(n<N)x[n].put(u1,u2,u3,u4);\n  else{\n    fprintf(stderr,\"n=%ld larger than seqR1 size N=%ld\\n\",n,N);\n    retval=-1;\n    }\n  return retval;\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief put a single value (u,u,u,u) into the seqR4 x at location n\n//-----------------------------------------------------------------------------\nint seqR4::put(long n, vectR4 u)\n{\n  int retval=0;\n  if(n<N)x[n].put(u);\n  else{\n    fprintf(stderr,\"n=%ld larger than seqR4 size N=%ld\\n\",n,N);\n    retval=-1;\n    }\n  return retval;\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief list contents of sequence\n//-----------------------------------------------------------------------------\nvoid seqR4::list(const long start, const long end, const char* str1, const char *str2, FILE *fptr){\n  long n,m;\n  vectR4 p;\n  if(strlen(str1)>0){\n    printf(\"%s\",str1);\n    if(fptr!=NULL)fprintf(fptr,\"%s\",str1);\n    }\n  for(n=start,m=1; n<=end; n++,m++){\n    p=x[n];\n    printf(\"(%5.2lf,%5.2lf,%5.2lf,%5.2lf) \",p.get1(),p.get2(),p.get3(),p.get4());\n    if(m%2==0)printf(\"\\n\");\n    if(fptr!=NULL){\n      fprintf(fptr,\"(%5.2lf,%5.2lf,%5.2lf,%5.2lf) \",p.get1(),p.get2(),p.get3(),p.get4());\n      if(m%2==0)fprintf(fptr,\"\\n\");\n      }\n    }\n  if(strlen(str2)>0){\n    printf(\"%s\",str2);\n    if(fptr!=NULL)fprintf(fptr,\"%s\",str2);\n    }\n  }\n\n//-----------------------------------------------------------------------------\n//! \\brief list contents of seqR1 using 1 digit per element\n//-----------------------------------------------------------------------------\nvoid seqR4::list1(const long start, const long end, const char *str1, const char *str2,FILE *fptr){\n  long n,m;\n  vectR4 p;\n  if(strlen(str1)>0){\n    printf(\"%s\",str1);\n    if(fptr!=NULL)fprintf(fptr,\"%s\",str1);\n    }\n  for(n=start,m=1; n<=end; n++,m++){\n    p=x[n];\n    printf(\" %1.0lf%1.0lf%1.0lf%1.0lf\",p.get1(),p.get2(),p.get3(),p.get4());\n    if(fptr!=NULL)fprintf(fptr,\" %1.0lf%1.0lf%1.0lf%1.0lf\",p.get1(),p.get2(),p.get3(),p.get4());\n    if(m%10==0)printf(\"\\n\");\n    if(fptr!=NULL)if(m%10==0)fprintf(fptr,\"\\n\");\n    }\n  if(strlen(str2)>0){\n    printf(\"%s\",str2);\n    if(fptr!=NULL)fprintf(fptr,\"%s\",str2);\n    }\n  }\n\n/*=====================================\n//! \\brief external operations\n *=====================================*/\n//-----------------------------------------------------------------------------\n//! \\brief operator: return p+q\n//-----------------------------------------------------------------------------\nvectR4 operator+(vectR4 p, vectR4 q){\n  int i;\n  vectR4 y;\n  for(i=0;i<4;i++)y.put(i,p.get(i)+q.get(i));\n  return y;\n  }\n\n//-----------------------------------------------------------------------------\n//! \\brief operator: return p-q\n//-----------------------------------------------------------------------------\nvectR4 operator-(vectR4 p, vectR4 q){\n  int i;\n  vectR4 y;\n  for(i=0;i<4;i++)y.put(i,p.get(i)-q.get(i));\n  return y;\n  }\n\n//-----------------------------------------------------------------------------\n//! \\brief operator: return -p\n//-----------------------------------------------------------------------------\nvectR4 operator-(vectR4 p){\n  vectR4 q;\n  int i;\n  for(i=0;i<4;i++)q.put(i,-p.get(i));\n  return q;\n  }\n\n//-----------------------------------------------------------------------------\n//! \\brief return the angle theta in radians between the two vectors induced by\n//! \\brief the points <p> and <q> in the space R^4.\n//! \\brief on SUCCESS return theta in the closed interval [0:PI]\n//! \\brief on ERROR   return negative value or exit with value EXIT_FAILURE\n//-----------------------------------------------------------------------------\ndouble pqtheta(const vectR4 p, const vectR4 q){\n  const double rp = p.r();\n  const double rq = q.r();\n  double y,theta;\n  if(rp==0) return -1;\n  if(rq==0) return -2;\n  y = (p^q)/(rp*rq);\n  if(y>+1)  {fprintf(stderr,\"\\nERROR using pqtheta(vectR4 p, vectR4 q): (p^q)/(rp*rq)=%lf>+1\\n\",y); exit(EXIT_FAILURE);}\n  if(y<-1)  {fprintf(stderr,\"\\nERROR using pqtheta(vectR4 p, vectR4 q): (p^q)/(rp*rq)=%lf<-1\\n\",y); exit(EXIT_FAILURE);}\n  theta = acos(y);\n  return theta;\n  }\n\n/*=====================================\n//! \\brief external operations\n *=====================================*/\n//-----------------------------------------------------------------------------\n//! \\brief compute magnitude of R^1 sequence\n//-----------------------------------------------------------------------------\n//int mag(seqR4 *xR4, seqR1 *ymag){\n//  const long Nx=xR4->getN();\n//  const long Ny=ymag->getN();\n//  long n;\n//  int retval=0;\n//  vectR4 u;\n//  ymag->clear();\n//  if(Nx!=Ny){\n//    fprintf(stderr,\"ERROR using y=mag(xR4): lengths of xR4 (%ld) and ymag (%ld) differ.\\n\",Nx,Ny);\n//    exit(EXIT_FAILURE);\n//    }\n//  for(n=0;n<Nx;n++){\n//    u=xR4->get(n);\n//    ymag->put(n,u.mag());\n//    }\n//  return retval;\n//  }\n\n", "meta": {"hexsha": "a62159806f2404112de19cc2bdf0f9788952fbca", "size": 12895, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "r4.cpp", "max_stars_repo_name": "dgreenhoe/symbolic-sequence-processing", "max_stars_repo_head_hexsha": "8e9f5a40dbddf44fd0fde0a461d7ed73208c9598", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "r4.cpp", "max_issues_repo_name": "dgreenhoe/symbolic-sequence-processing", "max_issues_repo_head_hexsha": "8e9f5a40dbddf44fd0fde0a461d7ed73208c9598", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "r4.cpp", "max_forks_repo_name": "dgreenhoe/symbolic-sequence-processing", "max_forks_repo_head_hexsha": "8e9f5a40dbddf44fd0fde0a461d7ed73208c9598", "max_forks_repo_licenses": ["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.2227602906, "max_line_length": 120, "alphanum_fraction": 0.3499806126, "num_tokens": 2909, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.4991290852338524}}
{"text": "/*    Copyright (c) 2010-2019, Delft University of Technology\r\n *    All rigths reserved\r\n *\r\n *    This file is part of the Tudat. Redistribution and use in source and\r\n *    binary forms, with or without modification, are permitted exclusively\r\n *    under the terms of the Modified BSD license. You should have received\r\n *    a copy of the license with this file. If not, please or visit:\r\n *    http://tudat.tudelft.nl/LICENSE.\r\n */\r\n\r\n\r\n#define BOOST_TEST_MAIN\r\n\r\n#include <boost/test/unit_test.hpp>\r\n#include <boost/make_shared.hpp>\r\n#include <boost/bind.hpp>\r\n\r\n#include \"Tudat/Mathematics/BasicMathematics/leastSquaresEstimation.h\"\r\n#include \"Tudat/External/SpiceInterface/spiceInterface.h\"\r\n#include \"Tudat/SimulationSetup/tudatSimulationHeader.h\"\r\n#include \"Tudat/Mathematics/Statistics/basicStatistics.h\"\r\nnamespace tudat\r\n{\r\n\r\nnamespace unit_tests\r\n{\r\n\r\nusing namespace tudat::simulation_setup;\r\nusing namespace tudat::propagators;\r\nusing namespace tudat::numerical_integrators;\r\nusing namespace tudat::orbital_element_conversions;\r\nusing namespace tudat::basic_mathematics;\r\nusing namespace tudat::unit_conversions;\r\n\r\ndouble computeLenseThirringPericenterPrecession(\r\n        const double gravitationalParameter,\r\n        const double angularMomentum,\r\n        const double semiMajorAxis,\r\n        const double eccentricity,\r\n        const double inclination )\r\n{\r\n    return - 6.0 * gravitationalParameter * angularMomentum * std::cos(inclination  ) /\r\n            ( physical_constants::SPEED_OF_LIGHT * physical_constants::SPEED_OF_LIGHT * semiMajorAxis * semiMajorAxis * semiMajorAxis *\r\n              std::pow( 1.0 - eccentricity * eccentricity, 1.5 ) );\r\n}\r\n\r\ndouble computeLenseThirringNodePrecession(\r\n        const double gravitationalParameter,\r\n        const double angularMomentum,\r\n        const double semiMajorAxis,\r\n        const double eccentricity )\r\n{\r\n    return 2.0 * gravitationalParameter * angularMomentum /\r\n            ( physical_constants::SPEED_OF_LIGHT * physical_constants::SPEED_OF_LIGHT * semiMajorAxis * semiMajorAxis * semiMajorAxis *\r\n              std::pow( 1.0 - eccentricity * eccentricity, 1.5 ) );\r\n}\r\n\r\ndouble computeSchwarzschildPericenterPrecession(\r\n        const double gravitationalParameter,\r\n        const double semiMajorAxis,\r\n        const double eccentricity )\r\n{\r\n    return 3.0 * std::pow( gravitationalParameter, 1.5 ) /\r\n            ( physical_constants::SPEED_OF_LIGHT * physical_constants::SPEED_OF_LIGHT * std::pow(\r\n                  semiMajorAxis, 2.5 ) *( 1.0 - eccentricity * eccentricity ) );\r\n}\r\n\r\ndouble computeDeSitterPericenterPrecession( const double meanDistanceEarthToSun,\r\n                                            const double meanEccentricity )\r\n{\r\n    return 1.5 * 1.327124E20 / ( physical_constants::SPEED_OF_LIGHT * physical_constants::SPEED_OF_LIGHT * meanDistanceEarthToSun ) * 2.0 * mathematical_constants::PI /\r\n            ( physical_constants::JULIAN_YEAR ) * std::sqrt( 1.0 - meanEccentricity * meanEccentricity );\r\n}\r\n\r\nBOOST_AUTO_TEST_SUITE( test_relativistic_acceleration_corrections )\r\n\r\nvoid testControlPropagation(\r\n        Eigen::Vector6d asterixInitialStateInKeplerianElements,\r\n        std::vector< std::map< double, double > > elementMaps,\r\n        double earthGravitationalParameter )\r\n{\r\n    std::vector< double > polynomialPowers = { 0, 1 };\r\n    for( unsigned elementIndex = 0; elementIndex < 5; elementIndex++ )\r\n    {\r\n        std::vector< double > fitOutput = linear_algebra::getLeastSquaresPolynomialFit(\r\n                    elementMaps[ elementIndex ], polynomialPowers );\r\n        BOOST_CHECK_CLOSE_FRACTION( asterixInitialStateInKeplerianElements( elementIndex ), fitOutput.at( 0 ), 1.0E-10 );\r\n        if( elementIndex == 1 )\r\n        {\r\n            BOOST_CHECK_SMALL( fitOutput.at( 1 ), 1.0E-18 );\r\n        }\r\n        else\r\n        {\r\n            BOOST_CHECK_SMALL( fitOutput.at( 1 ), 1.0E-12 );\r\n        }\r\n    }\r\n}\r\n\r\nvoid testLenseThirringPropagation(\r\n        Eigen::Vector6d asterixInitialStateInKeplerianElements,\r\n        std::vector< std::map< double, double > > elementMaps,\r\n        double earthGravitationalParameter )\r\n{\r\n    double theoreticalLenseThirringPericenterPrecession =\r\n            computeLenseThirringPericenterPrecession(\r\n                earthGravitationalParameter, 1.0E9,  asterixInitialStateInKeplerianElements( semiMajorAxisIndex ),\r\n                asterixInitialStateInKeplerianElements( eccentricityIndex ),\r\n                asterixInitialStateInKeplerianElements( inclinationIndex ) );\r\n    double theoreticalLenseThirringNodePrecession =\r\n            computeLenseThirringNodePrecession(\r\n                earthGravitationalParameter, 1.0E9,  asterixInitialStateInKeplerianElements( semiMajorAxisIndex ),\r\n                asterixInitialStateInKeplerianElements( eccentricityIndex ) );\r\n\r\n    std::vector< double > polynomialPowers = { 0, 1 };\r\n    for( unsigned elementIndex = 0; elementIndex < 5; elementIndex++ )\r\n    {\r\n        std::vector< double > fitOutput = linear_algebra::getLeastSquaresPolynomialFit(\r\n                    elementMaps[ elementIndex ], polynomialPowers );\r\n        BOOST_CHECK_CLOSE_FRACTION( asterixInitialStateInKeplerianElements( elementIndex ), fitOutput.at( 0 ), 1.0E-10 );\r\n        if( elementIndex == 1 )\r\n        {\r\n            BOOST_CHECK_SMALL( fitOutput.at( 1 ), 1.0E-18 );\r\n        }\r\n        else if( elementIndex == 3 )\r\n        {\r\n            BOOST_CHECK_CLOSE_FRACTION( fitOutput.at( 1 ), theoreticalLenseThirringPericenterPrecession, 1.0E-5 );\r\n        }\r\n        else if( elementIndex == 4 )\r\n        {\r\n            BOOST_CHECK_CLOSE_FRACTION( fitOutput.at( 1 ), theoreticalLenseThirringNodePrecession, 1.0E-5 );\r\n        }\r\n        else\r\n        {\r\n            BOOST_CHECK_SMALL( fitOutput.at( 1 ), 1.0E-12 );\r\n        }\r\n    }\r\n}\r\n\r\nvoid testSchwarzschildPropagation(\r\n        Eigen::Vector6d asterixInitialStateInKeplerianElements,\r\n        std::vector< std::map< double, double > > elementMaps,\r\n        double earthGravitationalParameter )\r\n{\r\n    double theoreticalSchwarzschildPericenterPrecession =\r\n            computeSchwarzschildPericenterPrecession(\r\n                earthGravitationalParameter, asterixInitialStateInKeplerianElements( semiMajorAxisIndex ),\r\n                asterixInitialStateInKeplerianElements( eccentricityIndex ) );\r\n\r\n    std::vector< double > polynomialPowers = { 0, 1 };\r\n    for( unsigned elementIndex = 0; elementIndex < 5; elementIndex++ )\r\n    {\r\n        std::vector< double > fitOutput = linear_algebra::getLeastSquaresPolynomialFit(\r\n                    elementMaps[ elementIndex ], polynomialPowers );\r\n        if( elementIndex != 1 )\r\n        {\r\n            BOOST_CHECK_CLOSE_FRACTION( asterixInitialStateInKeplerianElements( elementIndex ), fitOutput.at( 0 ), 1.0E-8 );\r\n        }\r\n        else\r\n        {\r\n            BOOST_CHECK_CLOSE_FRACTION( asterixInitialStateInKeplerianElements( elementIndex ), fitOutput.at( 0 ), 1.0E-7 );\r\n        }\r\n        if( elementIndex == 1 )\r\n        {\r\n            BOOST_CHECK_SMALL( fitOutput.at( 1 ), 1.0E-16 );\r\n        }\r\n        else if( elementIndex == 3 )\r\n        {\r\n            BOOST_CHECK_CLOSE_FRACTION( fitOutput.at( 1 ), theoreticalSchwarzschildPericenterPrecession, 1.0E-5 );\r\n        }\r\n        else\r\n        {\r\n            BOOST_CHECK_SMALL( fitOutput.at( 1 ), 1.0E-10 );\r\n        }\r\n    }\r\n}\r\n\r\nvoid testDeSitterPropagation(\r\n        Eigen::Vector6d asterixInitialStateInKeplerianElements,\r\n        std::vector< std::map< double, double > > elementMaps,\r\n        double meanDistanceEarthToSun,\r\n        double meanEarthEccentricity )\r\n{\r\n    std::vector< double > polynomialPowers = { 0, 1 };\r\n    for( unsigned elementIndex = 0; elementIndex < 5; elementIndex++ )\r\n    {\r\n        std::vector< double > fitOutput = linear_algebra::getLeastSquaresPolynomialFit(\r\n                    elementMaps[ elementIndex ], polynomialPowers );\r\n        if( elementIndex != 4 )\r\n        {\r\n            BOOST_CHECK_CLOSE_FRACTION( asterixInitialStateInKeplerianElements( elementIndex ), fitOutput.at( 0 ), 1.0E-10 );\r\n        }\r\n        else\r\n        {\r\n            BOOST_CHECK_CLOSE_FRACTION( asterixInitialStateInKeplerianElements( elementIndex ), fitOutput.at( 0 ), 1.0E-8 );\r\n        }\r\n        if( elementIndex == 1 )\r\n        {\r\n            BOOST_CHECK_SMALL( fitOutput.at( 1 ), 1.0E-18 );\r\n        }\r\n        else if( elementIndex == 4 )\r\n        {\r\n           BOOST_CHECK_CLOSE_FRACTION( fitOutput.at( 1 ), computeDeSitterPericenterPrecession(\r\n                                           meanDistanceEarthToSun, meanEarthEccentricity  ), 2.5E-2 );\r\n        }\r\n        else\r\n        {\r\n            BOOST_CHECK_SMALL( fitOutput.at( 1 ), 1.0E-12 );\r\n        }\r\n    }\r\n}\r\nBOOST_AUTO_TEST_CASE( testLenseThirring )\r\n{\r\n    // Load Spice kernels.\r\n    spice_interface::loadStandardSpiceKernels( );\r\n\r\n    // Set simulation end epoch.\r\n    const double simulationEndEpoch = 0.25 * tudat::physical_constants::JULIAN_YEAR;\r\n\r\n\r\n    // Create body objects.\r\n    std::vector< std::string > bodiesToCreate;\r\n    bodiesToCreate.push_back( \"Earth\" );\r\n    bodiesToCreate.push_back( \"Sun\" );\r\n\r\n    std::map< std::string, std::shared_ptr< BodySettings > > bodySettings =\r\n            getDefaultBodySettings( bodiesToCreate );\r\n\r\n    // Create Earth object\r\n    NamedBodyMap bodyMap = createBodies( bodySettings );\r\n\r\n    // Create spacecraft object.\r\n    bodyMap[ \"Asterix\" ] = std::make_shared< simulation_setup::Body >( );\r\n\r\n    // Finalize body creation.\r\n    setGlobalFrameBodyEphemerides( bodyMap, \"SSB\", \"ECLIPJ2000\" );\r\n\r\n    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n    ///////////////////////            CREATE ACCELERATIONS          //////////////////////////////////////////////////////\r\n    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n\r\n    for( unsigned int testCase = 0; testCase < 4; testCase++ )\r\n    {\r\n        // Define propagator settings variables.\r\n        SelectedAccelerationMap accelerationMap;\r\n        std::vector< std::string > bodiesToPropagate;\r\n        std::vector< std::string > centralBodies;\r\n\r\n        bodiesToPropagate.push_back( \"Asterix\" );\r\n        centralBodies.push_back( \"Earth\" );\r\n\r\n        // Define propagation settings.\r\n        std::map< std::string, std::vector< std::shared_ptr< AccelerationSettings > > > accelerationsOfAsterix;\r\n        accelerationsOfAsterix[ \"Earth\" ].push_back( std::make_shared< AccelerationSettings >(\r\n                                                         basic_astrodynamics::central_gravity ) );\r\n        if( testCase == 1 )\r\n        {\r\n            accelerationsOfAsterix[ \"Earth\" ].push_back( std::make_shared< RelativisticAccelerationCorrectionSettings >(\r\n                                                             false, true, false, \"\", 1.0E9 * Eigen::Vector3d::UnitZ( ) ) );\r\n        }\r\n        if( testCase == 2 )\r\n        {\r\n            accelerationsOfAsterix[ \"Earth\" ].push_back( std::make_shared< RelativisticAccelerationCorrectionSettings >(\r\n                                                             true, false, false ) );\r\n        }\r\n        if( testCase == 3 )\r\n        {\r\n            accelerationsOfAsterix[ \"Earth\" ].push_back( std::make_shared< RelativisticAccelerationCorrectionSettings >(\r\n                                                             false, false, true, \"Sun\" ) );\r\n        }\r\n        accelerationMap[ \"Asterix\" ] = accelerationsOfAsterix;\r\n\r\n        // Create acceleration models and propagation settings.\r\n        basic_astrodynamics::AccelerationMap accelerationModelMap = createAccelerationModelsMap(\r\n                    bodyMap, accelerationMap, bodiesToPropagate, centralBodies );\r\n\r\n\r\n\r\n        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n        ///////////////////////             CREATE PROPAGATION SETTINGS            ////////////////////////////////////////////\r\n        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n\r\n        // Set initial conditions for the Asterix satellite that will be propagated in this simulation.\r\n        // The initial conditions are given in Keplerian elements and later on converted to Cartesian\r\n        // elements.\r\n\r\n        // Set Keplerian elements for Asterix.\r\n        Eigen::Vector6d asterixInitialStateInKeplerianElements;\r\n        asterixInitialStateInKeplerianElements( semiMajorAxisIndex ) = 5000.0E3;\r\n        asterixInitialStateInKeplerianElements( eccentricityIndex ) = 0.2;\r\n        asterixInitialStateInKeplerianElements( inclinationIndex ) = convertDegreesToRadians( 65.3 );\r\n        asterixInitialStateInKeplerianElements( argumentOfPeriapsisIndex )\r\n                = convertDegreesToRadians( 235.7 );\r\n        asterixInitialStateInKeplerianElements( longitudeOfAscendingNodeIndex )\r\n                = convertDegreesToRadians( 23.4 );\r\n        asterixInitialStateInKeplerianElements( trueAnomalyIndex ) = convertDegreesToRadians( 0.0 );\r\n\r\n        // Convert Asterix state from Keplerian elements to Cartesian elements.\r\n        double earthGravitationalParameter = bodyMap.at( \"Earth\" )->getGravityFieldModel( )->getGravitationalParameter( );\r\n        Eigen::VectorXd systemInitialState = convertKeplerianToCartesianElements(\r\n                    asterixInitialStateInKeplerianElements,\r\n                    earthGravitationalParameter );\r\n\r\n        std::shared_ptr< TranslationalStatePropagatorSettings< double > > propagatorSettings =\r\n                std::make_shared< TranslationalStatePropagatorSettings< double > >\r\n                ( centralBodies, accelerationModelMap, bodiesToPropagate, systemInitialState, simulationEndEpoch, encke );\r\n\r\n\r\n        // Create numerical integrator.\r\n        std::shared_ptr< IntegratorSettings< > > integratorSettings =\r\n                std::make_shared< RungeKuttaVariableStepSizeSettings< > >\r\n                ( 0.0, 10.0,\r\n                  RungeKuttaCoefficients::rungeKuttaFehlberg78, 1.0E-3, 1.0E3, 1.0E-12, 1.0E-12 );\r\n\r\n        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n        ///////////////////////             PROPAGATE ORBIT            ////////////////////////////////////////////////////////\r\n        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n\r\n        // Create simulation object and propagate dynamics.\r\n        SingleArcDynamicsSimulator< > dynamicsSimulator(\r\n                    bodyMap, integratorSettings, propagatorSettings );\r\n        std::map< double, Eigen::VectorXd > integrationResult = dynamicsSimulator.getEquationsOfMotionNumericalSolution( );\r\n        std::map< double, Eigen::VectorXd > keplerianIntegrationResult;\r\n\r\n        // Compute map of Kepler elements\r\n        Eigen::Vector6d currentCartesianState;\r\n        std::vector< std::map< double, double > > elementMaps;\r\n        elementMaps.resize( 6 );\r\n\r\n        std::vector< double > solarDistances;\r\n        std::vector< double > earthSemiMajorAxes;\r\n        std::vector< double > earthEccentricities;\r\n\r\n        Eigen::Vector6d earthKeplerianState;\r\n        Eigen::Vector6d earthCartesianState;\r\n\r\n        for( std::map< double, Eigen::VectorXd >::const_iterator stateIterator = integrationResult.begin( );\r\n             stateIterator != integrationResult.end( ); stateIterator++ )\r\n        {\r\n            // Retrieve current Cartesian state (convert to Moon-centered frame if needed)\r\n            currentCartesianState = stateIterator->second;\r\n            keplerianIntegrationResult[ stateIterator->first ] =\r\n                    convertCartesianToKeplerianElements(\r\n                        currentCartesianState, earthGravitationalParameter );\r\n            for( unsigned elementIndex = 0; elementIndex < 6; elementIndex++ )\r\n            {\r\n                elementMaps[ elementIndex ][ stateIterator->first ] = keplerianIntegrationResult[ stateIterator->first ]( elementIndex );\r\n            }\r\n\r\n            if( testCase == 3 )\r\n            {\r\n                earthCartesianState = spice_interface:: getBodyCartesianStateAtEpoch(\r\n                            \"Earth\", \"Sun\", \"ECLIPJ2000\", \"None\", stateIterator->first );\r\n                earthKeplerianState  = convertCartesianToKeplerianElements(\r\n                            earthCartesianState, spice_interface::getBodyGravitationalParameter( \"Sun\" ) );\r\n\r\n                earthSemiMajorAxes.push_back( earthKeplerianState( 0 ) );\r\n                earthEccentricities.push_back( earthKeplerianState( 1 ) );\r\n\r\n                solarDistances.push_back( earthCartesianState.segment( 0, 3 ).norm( ) );\r\n            }\r\n        }\r\n\r\n        if( testCase == 0 )\r\n        {\r\n            testControlPropagation( asterixInitialStateInKeplerianElements, elementMaps, earthGravitationalParameter );\r\n        }\r\n        else if( testCase == 1 )\r\n        {\r\n            testLenseThirringPropagation( asterixInitialStateInKeplerianElements, elementMaps, earthGravitationalParameter );\r\n        }\r\n        else if( testCase == 2 )\r\n        {\r\n            testSchwarzschildPropagation( asterixInitialStateInKeplerianElements, elementMaps, earthGravitationalParameter );\r\n        }\r\n        else if( testCase == 3 )\r\n        {\r\n            testDeSitterPropagation(\r\n                        asterixInitialStateInKeplerianElements, elementMaps, statistics::computeSampleMean( solarDistances ),\r\n                        statistics::computeSampleMean( earthEccentricities ) );\r\n        }\r\n    }\r\n}\r\n\r\nBOOST_AUTO_TEST_SUITE_END( )\r\n\r\n}\r\n\r\n}\r\n", "meta": {"hexsha": "43a859098c06b424dd0c7b3f6d67c52363f801e1", "size": 17838, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/Relativity/UnitTests/unitTestRelativisticAccelerationCorrection.cpp", "max_stars_repo_name": "sebranchett/tudat", "max_stars_repo_head_hexsha": "24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tudat/Astrodynamics/Relativity/UnitTests/unitTestRelativisticAccelerationCorrection.cpp", "max_issues_repo_name": "sebranchett/tudat", "max_issues_repo_head_hexsha": "24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tudat/Astrodynamics/Relativity/UnitTests/unitTestRelativisticAccelerationCorrection.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": 45.8560411311, "max_line_length": 169, "alphanum_fraction": 0.6023657361, "num_tokens": 3934, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.63341027751814, "lm_q1q2_score": 0.49908371729736584}}
{"text": "// $Id$\n//\n//  Copyright (C) 2003-2009 Greg Landrum and Rational Discovery LLC\n//\n//   @@ All Rights Reserved @@\n//  This file is part of the RDKit.\n//  The contents are covered by the terms of the BSD license\n//  which is included in the file license.txt, found at the root\n//  of the RDKit source tree.\n//\n#include \"MolOps.h\"\n#include \"RDKitBase.h\"\n#include <RDGeneral/Invariant.h>\n#include <RDGeneral/RDLog.h>\n\n#include <boost/dynamic_bitset.hpp>\n#include <iomanip>\n\nnamespace RDKit {\nnamespace MolOps {\ndouble computeBalabanJ(double *distMat, int nb, int nAts) {\n  // NOTE that the distance matrix is modified here for the sake of\n  // efficiency\n  PRECONDITION(distMat, \"bogus distance matrix\")\n  double sum = 0.0;\n  int nActive = nAts;\n  int mu = nb - nActive + 1;\n\n  if (mu == -1) return 0.0;\n\n  for (int i = 0; i < nAts; i++) {\n    int iTab = i * nAts;\n    sum = 0.0;\n    for (int j = 0; j < nAts; j++) {\n      if (j != i) {\n        sum += distMat[iTab + j];\n      }\n    }\n    distMat[iTab + i] *= sum;\n  }\n  double accum = 0.0;\n  for (int i = 0; i < nAts; i++) {\n    int iTab = i * nAts + i;\n    for (int j = i + 1; j < nAts; j++) {\n      // NOTE: this isn't strictly the Balaban J value, because we\n      // aren't only adding in adjacent atoms.  Since we're doing a\n      // discriminator, that shouldn't be a problem.\n      if (j != i) {\n        accum += (1.0 / sqrt(distMat[iTab] * distMat[j * nAts + j]));\n      }\n    }\n  }\n  return nActive / ((mu + 1) * accum);\n}\n\ndouble computeBalabanJ(const ROMol &mol, bool useBO, bool force,\n                       const std::vector<int> *bondPath, bool cacheIt) {\n  RDUNUSED_PARAM(useBO);\n  double res = 0.0;\n  if (!force && mol.hasProp(common_properties::BalabanJ)) {\n    mol.getProp(common_properties::BalabanJ, res);\n  } else {\n    double *dMat;\n    int nb = 0, nAts = 0;\n    if (bondPath) {\n      boost::dynamic_bitset<> atomsUsed(mol.getNumAtoms());\n      boost::dynamic_bitset<> bondsUsed(mol.getNumBonds());\n      for (int ci : *bondPath) {\n        bondsUsed[ci] = 1;\n      }\n      std::vector<const Bond *> bonds;\n      bonds.reserve(bondPath->size());\n      std::vector<int> atomsInPath;\n      atomsInPath.reserve(bondPath->size() + 1);\n\n      ROMol::EDGE_ITER beg, end;\n      boost::tie(beg, end) = mol.getEdges();\n      while (beg != end) {\n        const Bond *bond = mol[*beg];\n        if (bondsUsed[bond->getIdx()]) {\n          int begIdx = bond->getBeginAtomIdx();\n          int endIdx = bond->getEndAtomIdx();\n          bonds.push_back(bond);\n          if (!atomsUsed[begIdx]) {\n            atomsInPath.push_back(begIdx);\n            atomsUsed[begIdx] = 1;\n          }\n          if (!atomsUsed[endIdx]) {\n            atomsInPath.push_back(endIdx);\n            atomsUsed[endIdx] = 1;\n          }\n        }\n        beg++;\n      }\n      nb = rdcast<int>(bondPath->size());\n      nAts = rdcast<int>(atomsInPath.size());\n      dMat = MolOps::getDistanceMat(mol, atomsInPath, bonds, true, true);\n      res = computeBalabanJ(dMat, nb, nAts);\n      delete[] dMat;\n    } else {\n      nb = mol.getNumBonds();\n      nAts = mol.getNumAtoms();\n      dMat = MolOps::getDistanceMat(mol, true, true, true, nullptr);\n      res = computeBalabanJ(dMat, nb, nAts);\n      delete[] dMat;\n    }\n\n    if (cacheIt) mol.setProp(common_properties::BalabanJ, res, true);\n  }\n  return res;\n}\n}  // end of namespace MolOps\n}  // end of namespace RDKit\n", "meta": {"hexsha": "79594739693b2ad513693f030f07df38114606da", "size": 3391, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modified_rdkit/Code/GraphMol/MolDiscriminators.cpp", "max_stars_repo_name": "hjuinj/RDKit_mETKDG", "max_stars_repo_head_hexsha": "b270e765caa61d289e9e33595d4264b156f9062e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-03-30T04:00:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-31T01:32:13.000Z", "max_issues_repo_path": "modified_rdkit/Code/GraphMol/MolDiscriminators.cpp", "max_issues_repo_name": "hjuinj/RDKit_mETKDG", "max_issues_repo_head_hexsha": "b270e765caa61d289e9e33595d4264b156f9062e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-05-23T17:31:04.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-26T06:52:47.000Z", "max_forks_repo_path": "modified_rdkit/Code/GraphMol/MolDiscriminators.cpp", "max_forks_repo_name": "hjuinj/RDKit_mETKDG", "max_forks_repo_head_hexsha": "b270e765caa61d289e9e33595d4264b156f9062e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-03-30T04:00:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-25T23:11:52.000Z", "avg_line_length": 29.7456140351, "max_line_length": 73, "alphanum_fraction": 0.5818342672, "num_tokens": 1024, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.63341027059799, "lm_q1q2_score": 0.4990837118447637}}
{"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_FUNCTION_SIGNIFICANTS_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_SIGNIFICANTS_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-exponential\n    Function object implementing significants capabilities\n\n    Compute the rounding to n significants digits\n\n    @par Semantic:\n\n    For every parameter of floating type T and strictly positive integer n\n\n    @code\n    T r = significants(x, n);\n    @endcode\n\n    is equivalent to round(x, m) where m is n-iceil(log10(abs(x)))\n\n    @see round,  iceil, log10\n\n  **/\n  const boost::dispatch::functor<tag::significants_> significants = {};\n} }\n#endif\n\n#include <boost/simd/function/scalar/significants.hpp>\n#include <boost/simd/function/simd/significants.hpp>\n\n#endif\n", "meta": {"hexsha": "285dfb97b81b88024e3575dfe463cf5154576fc4", "size": 1198, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/significants.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/function/significants.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/function/significants.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": 25.4893617021, "max_line_length": 100, "alphanum_fraction": 0.6118530885, "num_tokens": 255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.63341027059799, "lm_q1q2_score": 0.4990837118447637}}
{"text": "//=======================================================================\r\n// Copyright 2001 Jeremy G. Siek, Andrew Lumsdaine, Lie-Quan Lee, \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#ifdef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION\r\n#error The vector_as_graph.hpp header requires partial specialization\r\n#endif\r\n\r\n#include <vector>\r\n#include <list>\r\n#include <iostream> // needed by graph_utility. -Jeremy\r\n#include <boost/graph/vector_as_graph.hpp>\r\n#include <boost/graph/graph_utility.hpp>\r\n\r\nint\r\nmain()\r\n{\r\n  enum\r\n  { r, s, t, u, v, w, x, y, N };\r\n  char name[] = \"rstuvwxy\";\r\n  typedef std::vector < std::list < int > > Graph;\r\n  Graph g(N);\r\n  g[r].push_back(v);\r\n  g[s].push_back(r);\r\n  g[s].push_back(r);\r\n  g[s].push_back(w);\r\n  g[t].push_back(x);\r\n  g[u].push_back(t);\r\n  g[w].push_back(t);\r\n  g[w].push_back(x);\r\n  g[x].push_back(y);\r\n  g[y].push_back(u);\r\n  boost::print_graph(g, name);\r\n  return 0;\r\n}\r\n", "meta": {"hexsha": "c987d188a3fd0208bfdf4f902fce7aca08a29c70", "size": 1116, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/graph/example/vector-as-graph.cpp", "max_stars_repo_name": "zyiacas/boost-doc-zh", "max_stars_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 198.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T05:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:46:46.000Z", "max_issues_repo_path": "libs/graph/example/vector-as-graph.cpp", "max_issues_repo_name": "sdfict/boost-doc-zh", "max_issues_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/graph/example/vector-as-graph.cpp", "max_forks_repo_name": "sdfict/boost-doc-zh", "max_forks_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 27.9, "max_line_length": 74, "alphanum_fraction": 0.5681003584, "num_tokens": 289, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. Yes\n2. Yes", "lm_q1_score": 0.6334102636778403, "lm_q2_score": 0.7879312031126512, "lm_q1q2_score": 0.4990837111235823}}
{"text": "#include \"smooth_pair_finder.h\"\n\n#include <NTL/RR.h>\n\n#include \"norm_finding.h\"\n#include \"util.h\"\n\nnamespace {\n    using namespace NTL;\n}\n\nnamespace gnfs {\n    SmoothPairFinder::SmoothPairFinder(const ZZ& n, long B, const ZZX& f, const ZZ& m)\n      : n_(n), B_(B), f_(f), m_(m), M_(B), Mold_(0), a_(B), b_(-1) {\n        ZZX fprime = diff(f);\n\n        // Figure out what the factorbase columns represent.\n        // Each one is a pair (p,r), where p is a prime up to B\n        // and r is something where f(r) \\equiv 0 (mod p).\n        PrimeSeq pseq;\n        long p;\n        while ((p = pseq.next()) <= B) {\n            cols_modular_.push_back(p);\n            for (long r = 0; r < p; r++) {\n                ZZ res = eval(f, ZZ(r));\n                if (res % p == 0)\n                    cols_algebraic_.emplace_back(p, r);\n            }\n        }\n\n        // Generate pairs (q,s) for Adleman columns.\n        // For each q (named p here), find an s where\n        // f(s) \\equiv 0 (mod p) and f'(s) \\not\\equiv 0 (mod p).\n        long k = conv<long>(3 * log(conv<RR>(n)));\n        long k_so_far = 0;\n        while (k_so_far < k) {\n            for (long s = 0; s < p; s++) {\n                ZZ zs(s);\n                if (eval(f, zs) % p == 0 && eval(fprime, zs) % p != 0) {\n                    cols_adleman_.emplace_back(p, s);\n                    k_so_far++;\n                }\n            }\n\n            p = pseq.next();\n        }\n    }\n\n    bool SmoothPairFinder::add_cols_modular(long a, long b, vec_GF2& ret) {\n        ZZ ammb = a - m_ * b;\n        ammb %= n_;\n\n        if (ammb < 0) {\n            ammb *= -1;\n            ret.append(GF2(1));\n        } else {\n            ret.append(GF2(0));\n        }\n\n        for (const auto& p : cols_modular_) {\n            bool divcount = false;\n            while (ammb % p == 0) {\n                ammb /= p;\n                divcount ^= true;\n            }\n            ret.append(divcount ? GF2(1) : GF2(0));\n        }\n\n        return ammb == 1;\n    }\n\n    bool SmoothPairFinder::add_cols_algebraic(long a, long b, vec_GF2& ret) {\n        ZZ namab = eval_norm(f_, ZZ(a), ZZ(b));\n\n        // Iterate through each prime.\n        // For each one, find r first,\n        // then set the appropriate entry in the index vector.\n\n        // Here, we'll keep a cursor into cols_algebraic_.\n        auto alg_it = cols_algebraic_.cbegin();\n\n        for (const auto& p : cols_modular_) {\n            long r = lincon(a, b, p);\n\n            // Get the divcount as before\n            bool divcount = false;\n            while (namab % p == 0) {\n                namab /= p;\n                divcount ^= true;\n            }\n            GF2 to_add = divcount ? GF2(1) : GF2(0);\n\n            // Scroll past algebraic factorbase entries\n            // until we find where we want to add this item.\n            // Then add it.\n            while (alg_it->first != p || alg_it->second != r) {\n                ++alg_it;\n                ret.append(GF2(0));\n            }\n            ++alg_it;\n            ret.append(to_add);\n        }\n\n        // Add the rest of the zeros to the vector that we return.\n        while (alg_it != cols_algebraic_.cend()) {\n            ++alg_it;\n            ret.append(GF2(0));\n        }\n\n        return namab == 1;\n    }\n\n    bool SmoothPairFinder::add_cols_adleman(long a, long b, NTL::vec_GF2& ret) {\n        for (const auto& qs : cols_adleman_) {\n            long q = qs.first;\n            long s = qs.second;\n            long jacobi_top = a - b * s;\n            long jacobi = Jacobi(ZZ(jacobi_top % q), ZZ(q));\n            ret.append(jacobi == -1 ? GF2(1) : GF2(0));\n        }\n\n        return true;\n    }\n\n    vec_GF2 SmoothPairFinder::generate_row(long a, long b) {\n        vec_GF2 ret;  // if this length != num_cols, invalid\n        // we always return ret so we can have the return value optimzn\n        // even if ret ends up being invalid\n\n        // Modular factorbase and -1.\n        if (!add_cols_modular(a, b, ret)) {\n            // ammb is not B-smooth\n            // make SURE the length is invalid\n            if (ret.length() == num_cols()) ret.append(GF2(0));\n            return ret;\n        }\n\n        // Algebraic factorbase.\n        if (!add_cols_algebraic(a, b, ret)) {\n            // namab is not B-smooth\n            // make SURE the length is invalid\n            if (ret.length() == num_cols()) ret.append(GF2(0));\n            return ret;\n        }\n\n        // Adleman columns.\n        if (!add_cols_adleman(a, b, ret)) {\n            // result is wrong\n            // make SURE the length is invalid\n            if (ret.length() == num_cols()) ret.append(GF2(0));\n            return ret;\n        }\n\n        return ret;\n    }\n\n    std::pair<std::pair<long, long>, vec_GF2> SmoothPairFinder::get() {\n        // TODO\n        return std::make_pair(std::make_pair(0, 0), vec_GF2(INIT_SIZE, num_cols()));\n    }\n}\n", "meta": {"hexsha": "ae69542a8f4c9e4064c6338e8e08a23ac8a3ea2c", "size": 4873, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/smooth_pair_finder.cc", "max_stars_repo_name": "MathSquared/general-number-field-sieve", "max_stars_repo_head_hexsha": "0ab4efd447f24b726597ec9a6ddae669b1709a20", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-05-25T09:36:07.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-23T11:54:46.000Z", "max_issues_repo_path": "src/smooth_pair_finder.cc", "max_issues_repo_name": "MathSquared/general-number-field-sieve", "max_issues_repo_head_hexsha": "0ab4efd447f24b726597ec9a6ddae669b1709a20", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-06T10:34:07.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-06T10:34:07.000Z", "max_forks_repo_path": "src/smooth_pair_finder.cc", "max_forks_repo_name": "MathSquared/general-number-field-sieve", "max_forks_repo_head_hexsha": "0ab4efd447f24b726597ec9a6ddae669b1709a20", "max_forks_repo_licenses": ["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.0802469136, "max_line_length": 86, "alphanum_fraction": 0.482864765, "num_tokens": 1321, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.49908370639216176}}
{"text": "#include \"stdafx.h\"\n#include \"Math.h\"\n#include <boost/math/constants/constants.hpp>\n\nnamespace\n{\nconstexpr double PI = boost::math::constants::pi<double>();\n}\n\ndouble DegreesToRadians(double degrees)\n{\n\treturn degrees * PI / 180.0;\n}\n\ndouble RadiansToDegrees(double radians)\n{\n\treturn radians * 180.0 / PI;\n}\n", "meta": {"hexsha": "964aa6b9587a148696c0f16a470130a42aaa1442", "size": 309, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Observer/WindTracking/Math.cpp", "max_stars_repo_name": "chosti34/ood", "max_stars_repo_head_hexsha": "3d74b5253f667d3de1ee610fb7509cf3015ea79c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Observer/WindTracking/Math.cpp", "max_issues_repo_name": "chosti34/ood", "max_issues_repo_head_hexsha": "3d74b5253f667d3de1ee610fb7509cf3015ea79c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2018-02-09T06:12:29.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-06T06:26:40.000Z", "max_forks_repo_path": "Observer/WindTracking/Math.cpp", "max_forks_repo_name": "chosti34/ood", "max_forks_repo_head_hexsha": "3d74b5253f667d3de1ee610fb7509cf3015ea79c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.2631578947, "max_line_length": 59, "alphanum_fraction": 0.7216828479, "num_tokens": 74, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7879312056025699, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.499083701795518}}
{"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 <boost/math/special_functions/zeta.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n\n#include \"graph_tool.hh\"\n#include \"hash_map_wrap.hh\"\n#include \"int_part.hh\"\n#include \"util.hh\"\n\ndouble spence(double);\n\nnamespace graph_tool\n{\n\nusing namespace std;\n\nboost::multi_array<double, 2> __q_cache;\n\ndouble log_sum(double a, double b)\n{\n    return std::max(a, b) + std::log1p(exp(-abs(a-b)));\n}\n\nvoid init_q_cache(size_t n_max)\n{\n    size_t old_n = __q_cache.shape()[0];\n    if (old_n >= n_max)\n        return;\n\n    __q_cache.resize(boost::extents[n_max + 1][n_max + 1]);\n    std::fill(__q_cache.data(), __q_cache.data() + __q_cache.num_elements(),\n              -std::numeric_limits<double>::infinity());\n\n    for (size_t n = 1; n <= n_max; ++n)\n    {\n        __q_cache[n][1] = 0;\n        for (size_t k = 2; k <= n; ++k)\n        {\n            __q_cache[n][k] = log_sum(__q_cache[n][k], __q_cache[n][k - 1]);\n            if (n > k)\n                __q_cache[n][k] = log_sum(__q_cache[n][k], __q_cache[n - k][k]);\n        }\n    }\n}\n\ndouble q_rec(int n, int k)\n{\n    if (n <= 0 || k < 1)\n        return 0;\n    if (k > n)\n        k = n;\n    if (k == 1)\n        return 1;\n    return q_rec(n, k - 1) + q_rec(n - k, k);\n}\n\ngt_hash_map<pair<int, int>, double> __q_memo;\n\ndouble q_rec_memo(int n, int k)\n{\n    if (k > n || n <= 0 || k < 1)\n        return 0;\n    if (k > n)\n        k = n;\n    if (k == 1)\n        return 1;\n    auto key = make_pair(n, k);\n    auto iter = __q_memo.find(key);\n    if (iter != __q_memo.end())\n        return iter->second;\n    auto res = q_rec_memo(n, k - 1) + q_rec_memo(n - k, k);\n    __q_memo[key] = res;\n    return res;\n}\n\ndouble log_q_approx_big(size_t n, size_t k)\n{\n    double C = M_PI * sqrt(2/3.);\n    double S = C * sqrt(n) - log(4 * sqrt(3) * n);\n    if (k < n)\n    {\n        double x = k / sqrt(n) - log(n) / C;\n        S -= (2 / C) * exp(-C * x / 2);\n    }\n    return S;\n}\n\ndouble log_q_approx_small(size_t n, size_t k)\n{\n    return lbinom_fast(n - 1, k - 1) - lgamma_fast(k + 1);\n}\n\ndouble get_v(double u, double epsilon=1e-8)\n{\n    double v = u;\n    double delta = 1;\n    while (delta > epsilon)\n    {\n        // spence(exp(v)) = -spence(exp(-v)) - (v*v)/2\n        double n_v = u * sqrt(spence(exp(-v)));\n        delta = abs(n_v - v);\n        v = n_v;\n    }\n    return v;\n}\n\ndouble log_q_approx(size_t n, size_t k)\n{\n    if (k < pow(n, 1/4.))\n        return log_q_approx_small(n, k);\n    double u = k / sqrt(n);\n    double v = get_v(u);\n    double lf = log(v) - log1p(- exp(-v) * (1 + u * u/2)) / 2 - log(2) * 3 / 2.\n        - log(u) - log(M_PI);\n    double g = 2 * v / u - u * log1p(-exp(-v));\n    return lf - log(n) + sqrt(n) * g;\n}\n\n\n} // namespace graph_tool\n", "meta": {"hexsha": "723ed116c3e430db9f35351bc742bc6b6d7c9657", "size": 3497, "ext": "cc", "lang": "C++", "max_stars_repo_path": "graph-tool-2.27/src/graph/inference/support/int_part.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/inference/support/int_part.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/inference/support/int_part.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": 25.5255474453, "max_line_length": 80, "alphanum_fraction": 0.5784958536, "num_tokens": 1097, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.6688802735722129, "lm_q1q2_score": 0.4990776537813043}}
{"text": "#include <gauss_msgs/NewDeconfliction.h>\n#include <gauss_msgs/NewThreats.h>\n#include <gauss_msgs/ReadIcao.h>\n#include <gauss_msgs/ReadOperation.h>\n#include <gauss_msgs/ReadGeofences.h>\n#include <gauss_msgs/Waypoint.h>\n#include <geometry_msgs/Vector3.h>\n#include <ros/ros.h>\n#include <visualization_msgs/Marker.h>\n#include <visualization_msgs/MarkerArray.h>\n\n#include <Eigen/Eigen>\n\nbool in_range(double x, double min_x, double max_x) {\n    return (x > min_x) && (x < max_x);\n}\n\ndouble clamp(double x, double min_x, double max_x) {\n    if (min_x > max_x) {\n        ROS_ERROR(\"[Monitoring] min_x[%lf] > max_x[%lf], swapping!\", min_x, max_x);\n        std::swap(min_x, max_x);\n    }\n    return std::max(std::min(x, max_x), min_x);\n}\n\ndouble dot(const geometry_msgs::Vector3& u, const geometry_msgs::Vector3& v) {\n    return u.x * v.x + u.y * v.y + u.z * v.z;\n}\n\ndouble length(const geometry_msgs::Vector3& u) {\n    return sqrt(u.x * u.x + u.y * u.y + u.z * u.z);\n}\n\n// TODO: Use geometry_msgs/Point instead of Waypoint?\ngeometry_msgs::Vector3 vector_from_point_to_point(const gauss_msgs::Waypoint& A, const gauss_msgs::Waypoint& B) {\n    geometry_msgs::Vector3 AB;\n    AB.x = B.x - A.x;\n    AB.y = B.y - A.y;\n    AB.z = B.z - A.z;\n    return AB;\n}\n\n// Signed Distance Fucntion from P to:\n// a sphere centered in C with radius r\ndouble sdSphere(const gauss_msgs::Waypoint& P, const gauss_msgs::Waypoint& C, double r) {\n    return length(vector_from_point_to_point(C, P)) - r;\n}\n\n// Signed Distance Fucntion from P to:\n// a segment (A,B) with some radius r\ndouble sdSegment(const gauss_msgs::Waypoint& P, const gauss_msgs::Waypoint& A, const gauss_msgs::Waypoint& B, double r = 0) {\n    geometry_msgs::Vector3 AP = vector_from_point_to_point(A, P);\n    geometry_msgs::Vector3 AB = vector_from_point_to_point(A, B);\n    double h = clamp(dot(AP, AB) / dot(AB, AB), 0.0, 1.0);\n    geometry_msgs::Vector3 aux;\n    aux.x = AP.x - AB.x * h;  // TODO: Use eigen?\n    aux.y = AP.y - AB.y * h;\n    aux.z = AP.z - AB.z * h;\n    return length(aux) - r;\n}\n\ngeometry_msgs::Point translateToPoint(const gauss_msgs::Waypoint& WP) {\n    geometry_msgs::Point P;\n    P.x = WP.x;\n    P.y = WP.y;\n    P.z = WP.z;\n    return P;\n}\n\nstruct Segment {\n    Segment() = default;\n    Segment(gauss_msgs::Waypoint A, gauss_msgs::Waypoint B) {\n        // if (A == B) { ROS_WARN(\"A == B == [%lf, %lf, %lf, %lf]\", A.x, A.y, A.z, A.stamp.toSec()); }  // TODO: compare function\n        point_A = A;\n        point_B = B;\n        t_A = A.stamp.toSec();\n        t_B = B.stamp.toSec();\n        if (t_A >= t_B) {\n            // ROS_WARN(\"t_A[%lf] >= t_B[%lf]\", t_A, t_B);\n        }\n    }\n\n    gauss_msgs::Waypoint point_at_time(double t) const {\n        if (t < t_A) {\n            // ROS_WARN(\"t[%lf] < t_A[%lf]\", t, t_A);\n            return point_A;\n        }\n        if (t > t_B) {\n            // ROS_WARN(\"t[%lf] > t_B[%lf]\", t, t_B);\n            return point_B;\n        }\n        if (t_A == t_B) {\n            // ROS_WARN(\"t_A == t_B == %lf\", t_A);\n            return point_A;\n        }\n        if (std::isnan(t)) {\n            // ROS_WARN(\"t is NaN\");\n            return point_A;\n        }\n\n        double m = (t - t_A) / (t_B - t_A);\n        gauss_msgs::Waypoint point;\n        point.x = point_A.x + m * (point_B.x - point_A.x);\n        point.y = point_A.y + m * (point_B.y - point_A.y);\n        point.z = point_A.z + m * (point_B.z - point_A.z);\n        point.stamp.fromSec(t);\n        return point;\n    }\n\n    gauss_msgs::Waypoint point_at_param(double m) const {\n        gauss_msgs::Waypoint point;\n        point.x = point_A.x + m * (point_B.x - point_A.x);\n        point.y = point_A.y + m * (point_B.y - point_A.y);\n        point.z = point_A.z + m * (point_B.z - point_A.z);\n        double t =  t_A + m * (t_B - t_A);\n        point.stamp.fromSec(t);\n        return point;\n    }\n\n    visualization_msgs::Marker translateToMarker(int id, std_msgs::ColorRGBA color) {\n        visualization_msgs::Marker marker;\n        marker.header.stamp = ros::Time::now();\n        marker.header.frame_id = \"map\";  // TODO: other?\n        marker.ns = \"segments\";\n        marker.id = id;\n        marker.type = visualization_msgs::Marker::ARROW;\n        marker.action = visualization_msgs::Marker::ADD;\n        marker.pose.orientation.w = 1;\n        marker.scale.x = 5.0;  // shaft diameter\n        marker.scale.y = 1.5;  // head diameter\n        marker.scale.z = 1.0;  // head length (if not zero)\n        marker.color = color;\n        marker.lifetime = ros::Duration(1.0);  // TODO: pair with frequency\n        marker.points.push_back(translateToPoint(point_A));\n        marker.points.push_back(translateToPoint(point_B));\n        return marker;\n    }\n\n    friend std::ostream& operator<<(std::ostream& out, const Segment& s);\n    gauss_msgs::Waypoint point_A;\n    gauss_msgs::Waypoint point_B;\n    double t_A = 0;\n    double t_B = 0;\n};\n\nstd::ostream& operator<<(std::ostream& out, const Segment& s) {\n    out << \"[(\" << s.point_A << \"); (\" << s.point_B << \")]\";\n    return out;\n}\n\nstd::pair<geometry_msgs::Vector3, geometry_msgs::Vector3> delta(const Segment& first, const Segment& second) {\n    geometry_msgs::Vector3 delta_alpha;\n    delta_alpha.x = second.point_A.x - first.point_A.x;\n    delta_alpha.y = second.point_A.y - first.point_A.y;\n    delta_alpha.z = second.point_A.z - first.point_A.z;\n    geometry_msgs::Vector3 delta_beta;\n    delta_beta.x = second.point_B.x - first.point_B.x;\n    delta_beta.y = second.point_B.y - first.point_B.y;\n    delta_beta.z = second.point_B.z - first.point_B.z;\n    return std::make_pair(delta_alpha, delta_beta);\n}\n\ndouble sq_distance(const Segment& first, const Segment& second, double mu) {\n    if (mu < 0) {\n        // ROS_WARN(\"mu[%lf] < 0, clamping!\", mu);\n        mu = 0;\n    }\n\n    if (mu > 1) {\n        // ROS_WARN(\"mu[%lf] > 1, clamping!\", mu);\n        mu = 1;\n    }\n\n    auto d = delta(first, second);\n    double delta_x = d.first.x + mu * (d.second.x - d.first.x);\n    double delta_y = d.first.y + mu * (d.second.y - d.first.y);\n    double delta_z = d.first.z + mu * (d.second.z - d.first.z);\n    return pow(delta_x, 2) + pow(delta_y, 2) + pow(delta_z, 2);\n}\n\nstd::pair<double, double> quadratic_roots(double a, double b, double c) {\n    if ((a == 0) && (b == 0) && (c == 0)) {\n        // ROS_WARN(\"a = b = c = 0, any number is a solution!\");\n        return std::make_pair(std::nan(\"\"), std::nan(\"\"));\n    }\n    if ((a == 0) && (b == 0) && (c != 0)) {\n        // ROS_WARN(\"a = b = 0, there is no solution!\");\n        return std::make_pair(std::nan(\"\"), std::nan(\"\"));\n    }\n    if ((a == 0) && (b != 0)) {\n        // ROS_WARN(\"a = 0, non quadratic!\");\n        return std::make_pair(-c / b, -c / b);\n    }\n\n    float d = b * b - 4 * a * c;\n    if (d < 0) {\n        // ROS_WARN(\"d = [%lf], complex solutions!\", d);\n        return std::make_pair(std::nan(\"\"), std::nan(\"\"));\n    }\n    double e = sqrt(d);\n    return std::make_pair((-b - e) / (2 * a), (-b + e) / (2 * a));\n}\n\nstd::vector<Segment> getFirstSetOfContiguousSegments(const std::vector<Segment>& input) {\n    std::vector<Segment> output;\n    if (input.size() < 1) {\n        ROS_ERROR(\"[Monitoring] input.size() < 1\");\n        return output;\n    }\n\n    output.push_back(input[0]);\n    float t_gap_threshold = 1.0;  // [s]  TODO: as a parameter?\n    for (int i = 1; i < input.size(); i++) {\n        double t_gap = fabs(input[i].t_A - input[i - 1].t_B);\n        if (t_gap > t_gap_threshold) {\n            // i-th Segment is not contiguous\n            break;\n        }\n        output.push_back(input[i]);\n    }\n\n    return output;\n}\n\ngeometry_msgs::Vector3 getUnitOutwardVector(const gauss_msgs::Circle& circle, const gauss_msgs::Waypoint wp) {\n    geometry_msgs::Vector3 out;\n    out.x = wp.x - circle.x_center;\n    out.y = wp.y - circle.y_center;\n    auto len = sqrt(pow(out.x, 2) + pow(out.y, 2));\n    out.x /= len;\n    out.y /= len;\n    return out;\n}\n\nstruct LossConflictiveSegments {\n    LossConflictiveSegments(const Segment& first, const Segment& second) : first(first), second(second) {}\n\n    friend std::ostream& operator<<(std::ostream& out, const LossConflictiveSegments& r);\n    Segment first;\n    Segment second;\n    double t_min = std::nan(\"\");\n    double s_min = std::nan(\"\");\n    double t_crossing_0 = std::nan(\"\");\n    double t_crossing_1 = std::nan(\"\");\n    bool threshold_is_violated = false;\n};\n\nstd::ostream& operator<<(std::ostream& out, const LossConflictiveSegments& r) {\n    out << \"first = \" << r.first << '\\n';\n    out << \"second = \" << r.second << '\\n';\n    out << \"t_min[s] = \" << r.t_min << '\\n';\n    out << \"s_min[m2] = \" << r.s_min << '\\n';\n    out << \"t_crossing_0[s] = \" << r.t_crossing_0 << '\\n';\n    out << \"t_crossing_1[s] = \" << r.t_crossing_1 << '\\n';\n    out << \"threshold_is_violated = \" << r.threshold_is_violated << '\\n';\n    return out;\n}\n\nLossConflictiveSegments checkUnifiedSegmentsLoss(Segment first, Segment second, double s_threshold) {\n    // print('checkUnifiedSegmentsLoss:')\n    // print(first.point_A)\n    // print(first.point_B)\n    // print('___________')\n    // print(second.point_A)\n    // print(second.point_B)\n    auto d = delta(first, second);\n    // print(d)\n    double c_x = pow(d.first.x, 2);\n    double c_y = pow(d.first.y, 2);\n    double c_z = pow(d.first.z, 2);\n    double b_x = 2 * (d.first.x * d.second.x - c_x);\n    double b_y = 2 * (d.first.y * d.second.y - c_y);\n    double b_z = 2 * (d.first.z * d.second.z - c_z);\n    double a_x = pow(d.second.x - d.first.x, 2);\n    double a_y = pow(d.second.y - d.first.y, 2);\n    double a_z = pow(d.second.z - d.first.z, 2);\n    double a = a_x + a_y + a_z;\n    double b = b_x + b_y + b_z;\n    double c = c_x + c_y + c_z;\n\n    double mu_min, t_min, s_min;\n    if (a == 0) {\n        // ROS_WARN(\"a = 0\");\n        if (b >= 0) {\n            mu_min = 0;\n            t_min = first.t_A;\n            s_min = c;\n        } else {\n            mu_min = 1;\n            t_min = first.t_B;\n            s_min = b + c;\n        }\n\n    } else {  // a != 0\n        double mu_star = -0.5 * b / a;\n        double t_star = first.t_A + mu_star * (first.t_B - first.t_A);\n        // print(mu_star)\n        // print(t_star)\n        // print(sq_distance(first, second, mu_star))\n        mu_min = clamp(mu_star, 0, 1);\n        t_min = first.t_A + mu_min * (first.t_B - first.t_A);\n        s_min = sq_distance(first, second, mu_min);\n        // print(mu_min)\n        // print(t_min)\n        // print(s_min)\n    }\n    auto result = LossConflictiveSegments(first, second);\n    result.t_min = t_min;\n    result.s_min = s_min;\n\n    if (s_min > s_threshold) {\n        // ROS_INFO(\"s_min[%lf] > s_threshold[%lf]\", s_min, s_threshold);\n        result.threshold_is_violated = false;\n        return result;\n    }\n\n    auto mu_bar = quadratic_roots(a, b, c - s_threshold);\n    double t_bar_0 = first.t_A + mu_bar.first * (first.t_B - first.t_A);\n    double t_bar_1 = first.t_A + mu_bar.second * (first.t_B - first.t_A);\n    // print(mu_bar)\n    // print(t_bar_0, t_bar_1)\n    double mu_crossing_0 = clamp(mu_bar.first, 0, 1);\n    double mu_crossing_1 = clamp(mu_bar.second, 0, 1);\n    double t_crossing_0 = first.t_A + mu_crossing_0 * (first.t_B - first.t_A);\n    double t_crossing_1 = first.t_A + mu_crossing_1 * (first.t_B - first.t_A);\n    // print(mu_crossing_0, mu_crossing_1)\n    // print(t_crossing_0, t_crossing_1)\n    auto first_in_conflict = Segment(first.point_at_time(t_crossing_0), first.point_at_time(t_crossing_1));\n    auto second_in_conflict = Segment(second.point_at_time(t_crossing_0), second.point_at_time(t_crossing_1));\n\n    result.first = first_in_conflict;\n    result.second = second_in_conflict;\n    result.t_crossing_0 = t_crossing_0;\n    result.t_crossing_1 = t_crossing_1;\n    result.threshold_is_violated = true;\n    return result;\n}\n\nLossConflictiveSegments checkSegmentsLoss(const std::pair<Segment, Segment>& segments, double s_threshold) {\n    // print('checkSegmentsLoss:')\n    // print(first.point_A)\n    // print(first.point_B)\n    // print('___________')\n    // print(second.point_A)\n    // print(second.point_B)\n    double t_A1 = segments.first.t_A;\n    double t_B1 = segments.first.t_B;\n    double t_A2 = segments.second.t_A;\n    double t_B2 = segments.second.t_B;\n    double t_alpha = std::max(t_A1, t_A2);\n    double t_beta = std::min(t_B1, t_B2);\n    if (t_alpha > t_beta) {\n        // ROS_INFO(\"t_alpha[%lf] > t_beta[%lf]\", t_alpha, t_beta);\n        return LossConflictiveSegments(segments.first, segments.second);\n    }\n\n    auto P_alpha1 = segments.first.point_at_time(t_alpha);\n    auto P_beta1 = segments.first.point_at_time(t_beta);\n    auto P_alpha2 = segments.second.point_at_time(t_alpha);\n    auto P_beta2 = segments.second.point_at_time(t_beta);\n    return checkUnifiedSegmentsLoss(Segment(P_alpha1, P_beta1), Segment(P_alpha2, P_beta2), s_threshold);\n}\n\nstd::vector<LossConflictiveSegments> checkTrajectoriesLoss(const std::pair<gauss_msgs::WaypointList, gauss_msgs::WaypointList>& trajectories, double s_threshold) {\n    std::vector<LossConflictiveSegments> segment_loss_results;\n    if (trajectories.first.waypoints.size() < 2) {\n        // TODO: Warn and push the same point twice?\n        ROS_ERROR(\"[Monitoring] Trajectory must contain at least 2 points, [%ld] found in first argument\", trajectories.first.waypoints.size());\n        return segment_loss_results;\n    }\n    if (trajectories.second.waypoints.size() < 2) {\n        // TODO: Warn and push the same point twice?\n        ROS_ERROR(\"[Monitoring] Trajectory must contain at least 2 points, [%ld] found in second argument\", trajectories.second.waypoints.size());\n        return segment_loss_results;\n    }\n\n    for (int i = 0; i < trajectories.first.waypoints.size() - 1; i++) {\n        std::pair<Segment, Segment> segments;\n        // printf(\"First segment, i = %d\\n\", i);\n        segments.first = Segment(trajectories.first.waypoints[i], trajectories.first.waypoints[i + 1]);\n        // std::cout << segments.first.point_A << \"_____________\\n\" << segments.first.point_B << '\\n';\n        for (int j = 0; j < trajectories.second.waypoints.size() - 1; j++) {\n            // printf(\"Second segment, j = %d\\n\", j);\n            segments.second = Segment(trajectories.second.waypoints[j], trajectories.second.waypoints[j + 1]);\n            // std::cout << segments.second.point_A << \"_____________\\n\" << segments.second.point_B << '\\n';\n            auto loss_check = checkSegmentsLoss(segments, s_threshold);\n            if (loss_check.threshold_is_violated) {\n                // ROS_ERROR(\"[Monitoring] Loss of separation! [i = %d, j = %d]\", i, j);\n                // std::cout << loss_check << '\\n';\n                segment_loss_results.push_back(loss_check);\n            }\n        }\n    }\n    return segment_loss_results;\n}\n\nstruct LossExtreme {\n    gauss_msgs::Waypoint in_point;\n    gauss_msgs::Waypoint out_point;\n};\n\nvisualization_msgs::Marker translateToMarker(const LossExtreme& extremes, int id = 0) {\n    visualization_msgs::Marker marker;\n    std_msgs::ColorRGBA red, green;  // TODO: constants\n    red.r = 1.0;\n    red.a = 1.0;\n    green.g = 1.0;\n    green.a = 1.0;\n\n    marker.header.stamp = ros::Time::now();\n    marker.header.frame_id = \"map\";  // TODO: other?\n    marker.ns = \"extremes\";          // TODO: other?\n    marker.id = id;\n    marker.type = visualization_msgs::Marker::SPHERE_LIST;\n    marker.action = visualization_msgs::Marker::ADD;\n    marker.pose.orientation.w = 1;\n    marker.scale.x = 5.0;\n    marker.scale.y = 5.0;\n    marker.scale.z = 5.0;\n    marker.lifetime = ros::Duration(1.0);  // TODO: pair with frequency\n    marker.points.push_back(translateToPoint(extremes.in_point));\n    marker.colors.push_back(red);\n    marker.points.push_back(translateToPoint(extremes.out_point));\n    marker.colors.push_back(green);\n    return marker;\n}\n\ngauss_msgs::ConflictiveOperation fillConflictiveOperation(const int& _trajectory_index, const std::map<int, gauss_msgs::Operation>& _index_to_operation_map) {\n    gauss_msgs::ConflictiveOperation out_msg;\n    out_msg.actual_wp = _index_to_operation_map.at(_trajectory_index).track.waypoints.back();\n    out_msg.current_wp = _index_to_operation_map.at(_trajectory_index).current_wp;\n    out_msg.estimated_trajectory = _index_to_operation_map.at(_trajectory_index).estimated_trajectory;\n    out_msg.flight_plan = _index_to_operation_map.at(_trajectory_index).flight_plan;\n    out_msg.flight_plan_updated = _index_to_operation_map.at(_trajectory_index).flight_plan_updated;\n    out_msg.landing_spots = _index_to_operation_map.at(_trajectory_index).landing_spots;\n    out_msg.operational_volume = _index_to_operation_map.at(_trajectory_index).operational_volume;\n    out_msg.uav_id = _index_to_operation_map.at(_trajectory_index).uav_id;\n\n    return out_msg;\n}\n\nstruct LossResult {\n    LossResult(const int i, const int j) : first_trajectory_index(i), second_trajectory_index(j) {}\n    friend std::ostream& operator<<(std::ostream& out, const LossResult& r);\n    int first_trajectory_index;\n    int second_trajectory_index;\n    std::vector<LossConflictiveSegments> loss_conflictive_segments;\n\n    bool isEqual(const LossResult& other) {\n        const float check_time_margin = 10.0;  // [s]\n        return (first_trajectory_index == other.first_trajectory_index && second_trajectory_index == other.second_trajectory_index) &&\n               (std::abs(loss_conflictive_segments.front().t_crossing_0 - other.loss_conflictive_segments.front().t_crossing_0) <= check_time_margin ||\n                std::abs(loss_conflictive_segments.front().t_crossing_1 - other.loss_conflictive_segments.front().t_crossing_1) <= check_time_margin ||\n                std::abs(loss_conflictive_segments.back().t_crossing_0 - other.loss_conflictive_segments.back().t_crossing_0) <= check_time_margin ||\n                std::abs(loss_conflictive_segments.back().t_crossing_1 - other.loss_conflictive_segments.back().t_crossing_1) <= check_time_margin);\n    }\n    gauss_msgs::NewThreat convertToThreat(const std::map<int, gauss_msgs::Operation>& _index_to_operation_map, double& count_id) {\n        gauss_msgs::NewThreat out_threat;\n        out_threat.threat_id = count_id++;\n        out_threat.threat_type = out_threat.LOSS_OF_SEPARATION;\n        out_threat.uav_ids.push_back(_index_to_operation_map.at(first_trajectory_index).uav_id);\n        out_threat.uav_ids.push_back(_index_to_operation_map.at(second_trajectory_index).uav_id);\n        out_threat.priority_ops.push_back(_index_to_operation_map.at(first_trajectory_index).priority);\n        out_threat.priority_ops.push_back(_index_to_operation_map.at(second_trajectory_index).priority);\n        out_threat.conflictive_operations.push_back(fillConflictiveOperation(first_trajectory_index, _index_to_operation_map));\n        out_threat.conflictive_operations.push_back(fillConflictiveOperation(second_trajectory_index, _index_to_operation_map));\n        for (auto j : loss_conflictive_segments) {\n            out_threat.loss_conflictive_segments.segment_first.push_back(j.first.point_A);\n            out_threat.loss_conflictive_segments.segment_first.push_back(j.first.point_B);\n            out_threat.loss_conflictive_segments.segment_second.push_back(j.second.point_A);\n            out_threat.loss_conflictive_segments.segment_second.push_back(j.second.point_B);\n            out_threat.loss_conflictive_segments.t_min = j.t_min;\n            out_threat.loss_conflictive_segments.s_min = j.s_min;\n            out_threat.loss_conflictive_segments.t_crossing_0 = j.t_crossing_0;\n            out_threat.loss_conflictive_segments.t_crossing_1 = j.t_crossing_1;\n            out_threat.loss_conflictive_segments.point_at_t_min_segment_first = j.first.point_at_time(j.t_min);\n            out_threat.loss_conflictive_segments.point_at_t_min_segment_second = j.second.point_at_time(j.t_min);\n        }\n\n        return out_threat;\n    }\n};\n\nstruct GeoConflictiveTrajectory {\n    GeoConflictiveTrajectory(int i): trajectory_index(i) {}\n    int trajectory_index;\n    std::vector<Segment> geofence_conflictive_segments;\n    gauss_msgs::Waypoint closest_exit_wp;  // Use the mandatory field as intrusion flag\n\n    bool isEqual(const GeoConflictiveTrajectory& other) {\n        const double check_time_margin = 10.0;\n        return (trajectory_index == other.trajectory_index &&\n                closest_exit_wp.mandatory == other.closest_exit_wp.mandatory &&\n               (geofence_conflictive_segments.front().t_A - other.geofence_conflictive_segments.front().t_A <= check_time_margin ||\n                geofence_conflictive_segments.back().t_B - other.geofence_conflictive_segments.back().t_B <= check_time_margin));\n    }\n};\n\nstruct GeofenceResult {\n    GeofenceResult(int i): geofence_id(i) {}\n    int geofence_id;\n    std::vector<GeoConflictiveTrajectory> geo_conflictive_trajectories;\n    \n    bool isEqual(const GeofenceResult& other) {\n        const float check_time_margin = 10.0;  // [s]\n        if (geofence_id != other.geofence_id) {\n            return false;\n        } else {\n            for (auto geo_trajectory : geo_conflictive_trajectories) {\n                std::vector<GeoConflictiveTrajectory>::const_iterator traj_it = std::find_if(other.geo_conflictive_trajectories.begin(), other.geo_conflictive_trajectories.end(),\n                                                                                             [geo_trajectory](GeoConflictiveTrajectory _traj) { return _traj.isEqual(geo_trajectory);});\n                return (traj_it != other.geo_conflictive_trajectories.end());\n            }\n        }\n    }\n    std::vector<gauss_msgs::NewThreat> convertToThreat(const std::map<int, gauss_msgs::Operation>& _index_to_operation_map, const std::map<int, gauss_msgs::Geofence>& _index_to_geofence_map, double& count_id) {\n        std::vector<gauss_msgs::NewThreat> out_threats;\n        for (auto geo_conflictive_trajectory : geo_conflictive_trajectories) {\n            gauss_msgs::NewThreat aux_threat;\n            aux_threat.threat_id = count_id++;\n            aux_threat.geofence_ids.push_back(geofence_id);\n            aux_threat.uav_ids.push_back(_index_to_operation_map.at(geo_conflictive_trajectory.trajectory_index).uav_id);\n            aux_threat.conflictive_geofences.push_back(_index_to_geofence_map.at(geofence_id));\n            aux_threat.conflictive_operations.push_back(fillConflictiveOperation(geo_conflictive_trajectory.trajectory_index, _index_to_operation_map));\n            std::vector<Segment> aux_vec = getFirstSetOfContiguousSegments(geo_conflictive_trajectory.geofence_conflictive_segments);\n            for (auto segment : aux_vec) {\n                aux_threat.geofence_conflictive_segments.first_contiguous_segment.push_back(segment.point_A);\n                aux_threat.geofence_conflictive_segments.first_contiguous_segment.push_back(segment.point_B);\n            }\n            for (auto segment : geo_conflictive_trajectory.geofence_conflictive_segments) {\n                aux_threat.geofence_conflictive_segments.all_segments.push_back(segment.point_A);\n                aux_threat.geofence_conflictive_segments.all_segments.push_back(segment.point_B);\n            }\n\n            auto geo_circle = _index_to_geofence_map.at(geofence_id).circle;\n            auto crossing_0 = aux_threat.geofence_conflictive_segments.first_contiguous_segment.front();\n            auto crossing_1 = aux_threat.geofence_conflictive_segments.first_contiguous_segment.back();\n            aux_threat.geofence_conflictive_segments.crossing_0_out_vector = getUnitOutwardVector(geo_circle, crossing_0);\n            aux_threat.geofence_conflictive_segments.crossing_1_out_vector = getUnitOutwardVector(geo_circle, crossing_1);\n            if (geo_conflictive_trajectory.closest_exit_wp.mandatory) {\n                aux_threat.threat_type = aux_threat.GEOFENCE_INTRUSION;\n                auto closest_exit = geo_conflictive_trajectory.closest_exit_wp;\n                aux_threat.geofence_conflictive_segments.closest_exit_wp = closest_exit;\n                aux_threat.geofence_conflictive_segments.closest_exit_out_vector = getUnitOutwardVector(geo_circle, closest_exit);\n            } else {\n                aux_threat.threat_type = aux_threat.GEOFENCE_CONFLICT;\n            }\n            out_threats.push_back(aux_threat);\n        }\n\n        return out_threats;\n    }\n};\n\nstd::vector<LossResult> getContiguousResults(const LossResult& input) {\n    std::vector<LossResult> output;\n    if (input.loss_conflictive_segments.size() < 1) {\n        ROS_ERROR(\"[Monitoring] input.loss_conflictive_segments.size() < 1\");\n        return output;\n    }\n\n    float t_gap_threshold = 1.0;  // [s]  TODO: as a parameter?\n    auto current_loss_result = input;\n    current_loss_result.loss_conflictive_segments.clear();\n    current_loss_result.loss_conflictive_segments.push_back(input.loss_conflictive_segments[0]);\n    for (int i = 1; i < input.loss_conflictive_segments.size(); i++) {\n        double t_gap_first = fabs(input.loss_conflictive_segments[i].first.t_A - input.loss_conflictive_segments[i - 1].first.t_B);\n        double t_gap_second = fabs(input.loss_conflictive_segments[i].second.t_A - input.loss_conflictive_segments[i - 1].second.t_B);\n        if ((t_gap_first > t_gap_threshold) || (t_gap_second > t_gap_threshold)) {\n            // i-th element is not contiguous\n            output.push_back(current_loss_result);\n            current_loss_result.loss_conflictive_segments.clear();\n        }\n        current_loss_result.loss_conflictive_segments.push_back(input.loss_conflictive_segments[i]);\n    }\n    output.push_back(current_loss_result);\n\n    return output;\n}\n\nstd::pair<LossExtreme, LossExtreme> calculateExtremes(const LossResult& result) {\n    std::pair<LossExtreme, LossExtreme> extremes;\n    if (result.loss_conflictive_segments.size() < 1) {\n        ROS_ERROR(\"[Monitoring] result.loss_conflictive_segments.size() < 1\");\n        return extremes;\n    }\n\n    // In points are for sure A's from segment 0\n    extremes.first.in_point = result.loss_conflictive_segments[0].first.point_A;\n    extremes.second.in_point = result.loss_conflictive_segments[0].second.point_A;\n\n    // Initialize out points as B's from segment 0...\n    extremes.first.out_point = result.loss_conflictive_segments[0].first.point_B;\n    extremes.second.out_point = result.loss_conflictive_segments[0].second.point_B;\n    //  ...but update if more contiguous segments are available\n    float t_gap_threshold = 1.0;  // [s]\n    // Check for first\n    for (int i = 1; i < result.loss_conflictive_segments.size(); i++) {\n        double t_gap = fabs(result.loss_conflictive_segments[i].first.t_A - result.loss_conflictive_segments[i - 1].first.t_B);\n        if (t_gap > t_gap_threshold) {\n            break;\n        }\n        extremes.first.out_point = result.loss_conflictive_segments[i].first.point_B;\n    }\n    // Check for second\n    for (int i = 1; i < result.loss_conflictive_segments.size(); i++) {\n        double t_gap = fabs(result.loss_conflictive_segments[i].second.t_A - result.loss_conflictive_segments[i - 1].second.t_B);\n        if (t_gap > t_gap_threshold) {\n            break;\n        }\n        extremes.second.out_point = result.loss_conflictive_segments[i].second.point_B;\n    }\n\n    return extremes;\n}\n\nvisualization_msgs::Marker translateToMarker(const LossResult& result) {\n    visualization_msgs::Marker marker;\n    marker.header.stamp = ros::Time::now();\n    marker.header.frame_id = \"map\";  // TODO: other?\n    marker.ns = \"loss_\" + std::to_string(result.first_trajectory_index) + \"_\" + std::to_string(result.second_trajectory_index);\n    marker.type = visualization_msgs::Marker::LINE_LIST;\n    marker.action = visualization_msgs::Marker::ADD;\n    marker.pose.orientation.w = 1;\n    marker.scale.x = 1.0;\n    marker.color.r = 1.0;  // TODO: color?\n    marker.color.a = 1.0;\n    marker.lifetime = ros::Duration(1.0);  // TODO: pair with frequency\n    for (auto segments_loss : result.loss_conflictive_segments) {\n        marker.points.push_back(translateToPoint(segments_loss.first.point_A));\n        marker.points.push_back(translateToPoint(segments_loss.first.point_B));\n        marker.points.push_back(translateToPoint(segments_loss.second.point_A));\n        marker.points.push_back(translateToPoint(segments_loss.second.point_B));\n    }\n    /*\n  double t_min = std::nan(\"\");\n  double s_min = std::nan(\"\");\n  double t_crossing_0 = std::nan(\"\");\n  double t_crossing_1 = std::nan(\"\");\n  bool threshold_is_violated = false;\n*/\n    return marker;\n}\n\nstd::ostream& operator<<(std::ostream& out, const LossResult& r) {\n    out << \"first_trajectory_index = \" << r.first_trajectory_index << '\\n';\n    out << \"second_trajectory_index = \" << r.second_trajectory_index << '\\n';\n    out << \"loss_conflictive_segments = [\" << r.second_trajectory_index << '\\n';\n    for (int i = 0; i < r.loss_conflictive_segments.size(); i++) {\n        out << r.loss_conflictive_segments[i] << '\\n';\n    }\n    out << \"]\\n\";\n    return out;\n}\n\nbool happensBefore(const LossResult& a, const LossResult& b) {\n    if (a.loss_conflictive_segments.size() < 1) {\n        ROS_ERROR(\"[Monitoring] a.loss_conflictive_segments.size() < 1\");\n        return false;\n    }\n    if (b.loss_conflictive_segments.size() < 1) {\n        ROS_ERROR(\"[Monitoring] b.loss_conflictive_segments.size() < 1\");\n        return true;\n    }\n\n    return a.loss_conflictive_segments[0].t_crossing_0 < b.loss_conflictive_segments[0].t_crossing_0;\n}\n\nvoid cleanStoredList(std::vector<LossResult>& _stored_loss_result_list, std::vector<GeofenceResult>& _stored_geofence_result_list, const std::vector<LossResult>& _actual_loss_result_list, const std::vector<GeofenceResult>& _actual_geofence_result_list, const double& _check_time_margin) {\n    if (_actual_loss_result_list.size() == 0) {\n        _stored_loss_result_list.clear();\n    } else {\n        for (auto _stored_result = _stored_loss_result_list.begin(); _stored_result != _stored_loss_result_list.end();) {\n            std::vector<LossResult>::const_iterator actual_it = std::find_if(_actual_loss_result_list.begin(), _actual_loss_result_list.end(),\n                                                                             [_stored_result](LossResult _actual_result) { return _actual_result.isEqual(*_stored_result); });\n            bool do_erase = (actual_it == _actual_loss_result_list.end());\n            if (do_erase) {\n                _stored_result = _stored_loss_result_list.erase(_stored_result);\n            } else {\n                _stored_result++;\n            }\n        }\n    }\n}\n\ngauss_msgs::NewThreats manageResultList(std::vector<LossResult>& _loss_result_list, std::vector<GeofenceResult>& _geofence_result_list, const std::map<int, gauss_msgs::Operation>& _index_to_operation_map, const std::map<int, gauss_msgs::Geofence>& _index_to_geofence_map) {\n    double check_time_margin = 10.0;\n    static double threat_count_id = 0;\n    static double stored_loss_id_count = 0;\n    static double stored_geofence_id_count = 0;\n    gauss_msgs::NewThreats out_threats;\n    static std::vector<LossResult> stored_loss_result_list;\n    static std::vector<GeofenceResult> stored_geofence_result_list;\n\n    if (stored_loss_result_list.size() > 0 || stored_geofence_result_list.size() > 0) cleanStoredList(stored_loss_result_list, stored_geofence_result_list, _loss_result_list, _geofence_result_list, check_time_margin);\n    if (_loss_result_list.size() > 0) {\n        if (stored_loss_result_list.size() == 0) {\n            stored_loss_result_list.push_back(_loss_result_list.front());\n            out_threats.request.threats.push_back(_loss_result_list[0].convertToThreat(_index_to_operation_map, threat_count_id));\n        } else {\n            for (auto _loss_result : _loss_result_list) {\n                bool save_loss_result = false;\n                // Using lambda, check if both trajectory index of _loss_result are in stored_loss_result_list\n                std::vector<LossResult>::iterator stored_it = std::find_if(stored_loss_result_list.begin(), stored_loss_result_list.end(),\n                                                                           [_loss_result](LossResult stored_loss_result) { return stored_loss_result.isEqual(_loss_result); });\n                save_loss_result = (stored_it == stored_loss_result_list.end());\n                if (save_loss_result) {\n                    stored_loss_result_list.push_back(_loss_result);\n                    out_threats.request.threats.push_back(_loss_result.convertToThreat(_index_to_operation_map, threat_count_id));\n                }\n            }\n        }\n    }\n    if (_geofence_result_list.size() > 0) {\n        if (stored_geofence_result_list.size() == 0) {\n            stored_geofence_result_list.push_back(_geofence_result_list.front());\n            std::vector<gauss_msgs::NewThreat> aux_vec = _geofence_result_list[0].convertToThreat(_index_to_operation_map, _index_to_geofence_map, threat_count_id);\n            out_threats.request.threats.insert(out_threats.request.threats.end(), aux_vec.begin(), aux_vec.end());\n        } else {\n            for (auto _geofence_result : _geofence_result_list) {\n                bool save_geofence_result = false;\n                // Using lambda, check if both trajectory index of _geofence_result are in stored_geofence_result_list\n                std::vector<GeofenceResult>::iterator stored_it = std::find_if(stored_geofence_result_list.begin(), stored_geofence_result_list.end(),\n                                                                               [_geofence_result](GeofenceResult stored_loss_result) { return stored_loss_result.isEqual(_geofence_result); });\n                save_geofence_result = (stored_it == stored_geofence_result_list.end());\n                if (save_geofence_result) {\n                    stored_geofence_result_list.push_back(_geofence_result);\n                    std::vector<gauss_msgs::NewThreat> aux_vec = _geofence_result.convertToThreat(_index_to_operation_map, _index_to_geofence_map, threat_count_id);\n                    out_threats.request.threats.insert(out_threats.request.threats.end(), aux_vec.begin(), aux_vec.end());\n                }\n            }\n        }\n    }\n\n    return out_threats;\n}\n\nstd::pair<double, double> checkGeofence2D(const Segment& segment, const gauss_msgs::Circle& circle) {\n\n    auto translated_segment = segment;\n    translated_segment.point_A.x -= circle.x_center;\n    translated_segment.point_A.y -= circle.y_center;\n    translated_segment.point_B.x -= circle.x_center;\n    translated_segment.point_B.y -= circle.y_center;\n\n    float sq_distance_A = pow(translated_segment.point_A.x, 2) + pow(translated_segment.point_A.y, 2);\n    float sq_distance_B = pow(translated_segment.point_B.x, 2) + pow(translated_segment.point_B.y, 2);\n    float sq_radius = pow(circle.radius, 2);\n\n    bool point_A_is_in = (sq_distance_A < sq_radius);\n    bool point_B_is_in = (sq_distance_B < sq_radius);\n\n    // Geofence2DResult result;\n    if (point_A_is_in && point_B_is_in) {\n        // A and B inside the circle\n        // ROS_INFO(\"A and B inside the circle\");\n        return std::make_pair(segment.t_A, segment.t_B);\n    }\n\n    float a_x = pow(translated_segment.point_B.x - translated_segment.point_A.x, 2);\n    float b_x = 2.0 * (translated_segment.point_B.x - translated_segment.point_A.x) * translated_segment.point_A.x;\n    float c_x = pow(translated_segment.point_A.x, 2);\n    float a_y = pow(translated_segment.point_B.y - translated_segment.point_A.y, 2);\n    float b_y = 2.0 * (translated_segment.point_B.y - translated_segment.point_A.y) * translated_segment.point_A.y;\n    float c_y = pow(translated_segment.point_A.y, 2);\n\n    auto m_crossing = quadratic_roots(a_x + a_y, b_x + b_y, c_x + c_y - sq_radius);\n    // ROS_INFO(\"Roots: m = [%lf, %lf]\", m_crossing.first, m_crossing.second);\n\n    if (std::isnan(m_crossing.first)) {  // m_crossing.second should also be nan\n        // There is no intersection at all\n        // ROS_INFO(\"There is no intersection at all\");\n        return std::make_pair(std::nan(\"\"), std::nan(\"\"));\n    }\n\n    if ((m_crossing.first > 1) || (m_crossing.second < 0)) {\n        // ROS_INFO(\"Intersection is out of the segment\");\n        return std::make_pair(std::nan(\"\"), std::nan(\"\"));\n    }\n\n    auto t_crossing_0 = translated_segment.t_A + clamp(m_crossing.first,  0, 1) * (translated_segment.t_B - translated_segment.t_A);\n    auto t_crossing_1 = translated_segment.t_A + clamp(m_crossing.second, 0, 1) * (translated_segment.t_B - translated_segment.t_A);\n    return std::make_pair(t_crossing_0, t_crossing_1);\n}\n\nbool checkOverlappingInTime(std::pair<double, double> time_interval_a, std::pair<double, double> time_interval_b) {\n    return (time_interval_a.first <= time_interval_b.second) && (time_interval_a.second >= time_interval_b.first);\n}\n\ngeometry_msgs::Point calculateClosestExit(const geometry_msgs::Point& current, const gauss_msgs::Circle& circle) {\n    geometry_msgs::Point out;\n    float delta_x = current.x - circle.x_center;\n    float delta_y = current.y - circle.y_center;\n    auto distance = sqrt(pow(delta_x, 2) + pow(delta_y, 2));\n    if (distance < 1e-3) {\n        // At the center of the geofence? Go East!\n        out.x = circle.x_center + circle.radius;\n        out.y = circle.y_center;\n        // out.x = std::nan(\"\");  // TODO: Better NaN and handle later?\n        // out.y = std::nan(\"\");\n        return out;\n    }\n    out.x = circle.x_center + (delta_x / distance) * circle.radius;\n    out.y = circle.y_center + (delta_y / distance) * circle.radius;\n    return out;\n}\n\nstd::vector<GeoConflictiveTrajectory> checkGeofenceConflict(const std::vector<gauss_msgs::WaypointList>& trajectories, const std::vector<double>& volumes, const gauss_msgs::Geofence& geofence) {\n    std::vector<GeoConflictiveTrajectory> result;\n\n    if (!geofence.cylinder_shape) {\n        // TODO: implement also for polygons\n        ROS_ERROR(\"[Monitoring] Polygon geofences not implemented yet\");\n        return result;\n        // float64 min_altitude\t# meters\n        // float64 max_altitude\t# meters\n        // Polygon polygon\n        //     float64[] x\n        //     float64[] y\n    }\n\n    if (trajectories.size() != volumes.size()) {\n        ROS_ERROR(\"[Monitoring] Sizes do not match: trajectories.size() = %ld, volumes.size() = %ld\", trajectories.size(), volumes.size());\n        return result;\n    }\n\n    for (int i = 0; i < trajectories.size(); i++) {\n        // ROS_INFO(\"Checking trajectory [%d]\", i);\n        GeoConflictiveTrajectory current_result(i);\n\n        if (trajectories[i].waypoints.size() < 2) {\n            // TODO: Warn and push the same point twice?\n            ROS_ERROR(\"[Monitoring]: trajectory must contain at least 2 points, [%ld] found in second argument\", trajectories[i].waypoints.size());\n            continue;\n        }\n        auto operational_volume = volumes[i];\n        auto rectified_geofence = geofence;\n        rectified_geofence.min_altitude -= operational_volume;\n        rectified_geofence.max_altitude += operational_volume;\n        rectified_geofence.circle.radius += operational_volume;\n\n        for (int j = 0; j < trajectories[i].waypoints.size() - 1; j++) {\n            // ROS_INFO(\"Checking segment [%d, %d]\", j, j + 1);\n            auto segment = Segment(trajectories[i].waypoints[j], trajectories[i].waypoints[j + 1]);\n\n            // TODO: combine the following two ifs into a single one?\n            if ((segment.point_A.z < rectified_geofence.min_altitude) && (segment.point_B.z < rectified_geofence.min_altitude)) {\n                // The whole segment lies below the rectified_geofence\n                // ROS_INFO(\"The whole segment lies below the geofence\");\n                continue;\n            }\n            if ((segment.point_A.z > rectified_geofence.max_altitude) && (segment.point_B.z > rectified_geofence.max_altitude)) {\n                // The whole segment lies above the rectified_geofence\n                // ROS_INFO(\"The whole segment lies above the geofence\");\n                continue;\n            }\n\n            // TODO: enlarge the circle with operational volume (* some security_gain)\n            float delta_z = segment.point_B.z - segment.point_A.z;\n            // if (fabs(delta_z) < 1e-3) {  // TODO: Early return?\n            //     // We can consider the whole segment lies inside the geofence z interval\n            //     // TODO: Consider the special case of j == 0 for geofence intrusion!\n            //     ROS_INFO(\"We can consider the whole segment lies inside the geofence z interval\");\n            // }\n\n            // Get the segment that does lie between min_alt, max_alt\n            if (segment.point_A.z < rectified_geofence.min_altitude) {\n                // Point A lies below the geofence z interval\n                // ROS_INFO(\"Point A lies below the geofence z interval\");\n                float m_min = (rectified_geofence.min_altitude - segment.point_A.z) / delta_z;\n                segment.point_A = segment.point_at_param(m_min);\n                // TODO: Consider the special case of j == 0 for geofence intrusion!\n            } else if (segment.point_A.z > rectified_geofence.max_altitude) {\n                // Point A lies above the geofence z interval\n                // ROS_INFO(\"Point A lies above the geofence z interval\");\n                float m_max = (rectified_geofence.max_altitude - segment.point_A.z) / delta_z;\n                segment.point_A = segment.point_at_param(m_max);\n                // TODO: Consider the special case of j == 0 for geofence intrusion!\n            }\n\n            // Same for point B  // TODO: repeated code!\n            if (segment.point_B.z < rectified_geofence.min_altitude) {\n                // Point B lies below the geofence z interval\n                // ROS_INFO(\"Point B lies below the geofence z interval\");\n                float m_min = (rectified_geofence.min_altitude - segment.point_B.z) / delta_z;\n                segment.point_B = segment.point_at_param(m_min);\n            } else if (segment.point_B.z > rectified_geofence.max_altitude) {\n                // Point B lies above the geofence z interval\n                // ROS_INFO(\"Point B lies above the geofence z interval\");\n                float m_max = (rectified_geofence.max_altitude - segment.point_B.z) / delta_z;\n                segment.point_B = segment.point_at_param(m_max);\n            }\n\n            auto conflict_times = checkGeofence2D(segment, rectified_geofence.circle);\n            if (std::isnan(conflict_times.first)) {  // conflict_times.second should be also nan\n                // ROS_INFO(\"No conflicts\");\n                // return result; // TODO: Only for debug!\n                continue;\n            }  // TODO: Rename to GeofenceConflict?\n\n            auto current_time = ros::Time::now().toSec();\n            if (current_time > conflict_times.second) {  // Should be also > conflict_times.second\n                // ROS_INFO(\"Past conflicts do not count :)\");\n                // return result; // TODO: Only for debug!\n                continue;\n            }\n\n            if (checkOverlappingInTime(conflict_times, std::make_pair(rectified_geofence.start_time.toSec(), rectified_geofence.end_time.toSec()))) {\n                // ROS_INFO(\"Conflict!\");  // TODO\n                auto current_position = trajectories[i].waypoints[j];\n                // Check also for intrusion:\n                if ((j == 0)\n                    && in_range(current_position.z, rectified_geofence.min_altitude, rectified_geofence.max_altitude)\n                    && (pow(current_position.x - rectified_geofence.circle.x_center, 2) + pow(current_position.y - rectified_geofence.circle.y_center, 2) < pow(rectified_geofence.circle.radius, 2))\n                    ) {\n                    // ROS_ERROR(\"[Monitoring] Geofence intrusion! [i = %d]\", current_result.trajectory_index);\n                    current_result.closest_exit_wp.mandatory = true;\n                    auto exit_circle = geofence.circle;\n                    exit_circle.radius += operational_volume * 2.0;\n                    auto xy_closest_exit = calculateClosestExit(translateToPoint(current_position), exit_circle);\n                    // auto xy_closest_exit = calculateClosestExit(translateToPoint(current_position), rectified_geofence.circle);\n                    current_result.closest_exit_wp.x = xy_closest_exit.x;\n                    current_result.closest_exit_wp.y = xy_closest_exit.y;\n                    current_result.closest_exit_wp.z = current_position.z;  // Suppose we want the closest exit with no changes in altuitude!\n                }\n                current_result.geofence_conflictive_segments.push_back(Segment(segment.point_at_time(conflict_times.first), segment.point_at_time(conflict_times.second)));\n            }\n            // result.push_back(current_result);  // TODO: Only for debug!\n            // return result;  // TODO: Only for debug!\n        }\n        if (current_result.geofence_conflictive_segments.size() > 0) {\n            result.push_back(current_result);\n        }\n    }\n\n    return result;\n}\n\nint main(int argc, char** argv) {\n    ros::init(argc, argv, \"continuous_monitoring\");\n\n    ros::NodeHandle n;\n    // ros::NodeHandle np(\"~\");\n    ROS_INFO(\"[Monitoring] Started monitoring node!\");\n    double safety_distance;\n    bool just_one_threat;\n    n.param(\"safetyDistance\", safety_distance, 10.0);\n    n.param(\"just_one_threat\", just_one_threat, false);\n    double safety_distance_sq = pow(safety_distance, 2);\n\n    auto read_icao_srv_url = \"/gauss/read_icao\";\n    auto read_operation_srv_url = \"/gauss/read_operation\";\n    auto read_geofences_srv_url = \"/gauss/read_geofences\";\n    auto tactical_srv_url = \"/gauss/new_tactical_deconfliction\";\n    auto alternatives_topic_url = \"/gauss/possible_alternatives\";\n    auto new_threats_srv_url = \"/gauss/new_threats\";\n    auto visualization_topic_url = \"/gauss/visualize_monitoring\";\n\n    ros::ServiceClient icao_client = n.serviceClient<gauss_msgs::ReadIcao>(read_icao_srv_url);\n    ros::ServiceClient operation_client = n.serviceClient<gauss_msgs::ReadOperation>(read_operation_srv_url);\n    ros::ServiceClient geofences_client = n.serviceClient<gauss_msgs::ReadGeofences>(read_geofences_srv_url);\n    ros::ServiceClient tactical_client = n.serviceClient<gauss_msgs::NewDeconfliction>(tactical_srv_url);\n    ros::ServiceClient possible_alternatives_client = n.serviceClient<gauss_msgs::NewDeconfliction>(alternatives_topic_url);\n    ros::ServiceClient new_threats_client = n.serviceClient<gauss_msgs::NewThreats>(new_threats_srv_url);\n    ros::Publisher visualization_pub = n.advertise<visualization_msgs::MarkerArray>(visualization_topic_url, 1);\n\n    ROS_INFO(\"[Monitoring] Waiting for required services...\");\n    ros::service::waitForService(read_icao_srv_url, -1);\n    ROS_INFO(\"[Monitoring] %s: ok\", read_icao_srv_url);\n    ros::service::waitForService(read_operation_srv_url, -1);\n    ROS_INFO(\"[Monitoring] %s: ok\", read_operation_srv_url);\n    ros::service::waitForService(read_geofences_srv_url, -1);\n    ROS_INFO(\"[Monitoring] %s: ok\", read_geofences_srv_url);\n    ros::service::waitForService(tactical_srv_url, -1);\n    ROS_INFO(\"[Monitoring] %s: ok\", tactical_srv_url);\n    ros::service::waitForService(new_threats_srv_url, -1);\n    ROS_INFO(\"[Monitoring] %s: ok\", new_threats_srv_url);\n    ros::Rate rate(1);  // [Hz]\n    while (ros::ok()) {\n        gauss_msgs::ReadIcao read_icao;\n        if (icao_client.call(read_icao)) {\n            // ROS_INFO(\"[Monitoring] Read icao addresses... ok\");\n            // std::cout << read_icao.response << '\\n';\n        } else {\n            ROS_ERROR(\"[Monitoring] Failed to call service: [%s]\", read_icao_srv_url);\n            return 1;\n        }\n\n        gauss_msgs::ReadOperation read_operation;\n        read_operation.request.uav_ids = read_icao.response.uav_id;\n        if (operation_client.call(read_operation)) {\n            // ROS_INFO(\"[Monitoring] Read operations... ok\");\n            // std::cout << read_operation.response << '\\n';\n        } else {\n            ROS_ERROR(\"[Monitoring] Failed to call service: [%s]\", read_operation_srv_url);\n            return 1;\n        }\n\n        gauss_msgs::ReadGeofences read_geofences;\n        read_geofences.request.geofences_ids = read_icao.response.geofence_id;\n        if (geofences_client.call(read_geofences)) {\n            // ROS_INFO(\"[Monitoring] Read geofences... ok\");\n            // std::cout << read_geofences.response << '\\n';\n        } else {\n            ROS_ERROR(\"[Monitoring] Failed to call service: [%s]\", read_geofences_srv_url);\n            return 1;\n        }\n\n        std::map<std::string, int> icao_to_index_map;\n        std::map<int, gauss_msgs::Operation> index_to_operation_map;\n        std::map<int, gauss_msgs::Geofence> index_to_geofence_map;\n        std::vector<gauss_msgs::WaypointList> estimated_trajectories;\n        std::vector<double> operational_volumes;\n        for (auto operation : read_operation.response.operation) {\n            // std::cout << operation << '\\n';\n            if (operation.is_started) {\n                icao_to_index_map[operation.icao_address] = estimated_trajectories.size();\n                index_to_operation_map[estimated_trajectories.size()] = operation;\n                estimated_trajectories.push_back(operation.estimated_trajectory);\n                operational_volumes.push_back(operation.operational_volume);\n            }\n        }\n\n        std::vector<GeofenceResult> geofence_results_list;\n        for (auto geofence : read_geofences.response.geofences) {\n            index_to_geofence_map[geofence.id] = geofence;\n            // std::cout << geofence << '\\n';\n            // ROS_INFO(\"_________________________\");\n            // ROS_INFO(\"Checking geofence id [%d]\", geofence.id);\n            GeofenceResult current_result(geofence.id);\n            current_result.geo_conflictive_trajectories = checkGeofenceConflict(estimated_trajectories, operational_volumes, geofence);\n            if (current_result.geo_conflictive_trajectories.size() > 0) {\n                geofence_results_list.push_back(current_result);\n            }\n        }\n        // Visualize...\n        visualization_msgs::MarkerArray marker_array;\n        for (int i = 0; i < geofence_results_list.size(); i++) {\n            auto geofence_result = geofence_results_list[i];\n            // geofence_result.geofence_id\n            for (int j = 0; j < geofence_result.geo_conflictive_trajectories.size(); j++) {\n                auto trajectory = geofence_result.geo_conflictive_trajectories[j];\n                // trajectory.trajectory_index;\n                auto all_conflicts = trajectory.geofence_conflictive_segments;\n                auto first_conflict = getFirstSetOfContiguousSegments(all_conflicts);\n                auto conflicts = first_conflict;\n                int segment_id = 1e6 * i + 1e3 * j;\n                std_msgs::ColorRGBA segment_color;\n                segment_color.a = 1.0;\n                segment_color.r = 1.0;\n                if (trajectory.closest_exit_wp.mandatory) {\n                    // Means it is an intrusion!\n                    Segment way_out(trajectory.closest_exit_wp, conflicts.back().point_B);\n                    marker_array.markers.push_back(way_out.translateToMarker(segment_id+1e9, segment_color));\n                    // continue;\n                }\n                // else:\n                for (int k = 0; k < conflicts.size(); k++) {\n                    segment_id += k;\n                    segment_color.g = 0.5;\n                    marker_array.markers.push_back(conflicts[k].translateToMarker(segment_id, segment_color));\n                }\n            }\n        }\n\n        std::vector<LossResult> loss_results_list;\n        if (estimated_trajectories.size() >= 2) {\n            for (int i = 0; i < estimated_trajectories.size() - 1; i++) {\n                std::pair<gauss_msgs::WaypointList, gauss_msgs::WaypointList> trajectories;\n                trajectories.first = estimated_trajectories[i];\n                for (int j = i + 1; j < estimated_trajectories.size(); j++) {\n                    // ROS_INFO(\"Checking trajectories: [%d, %d]\", i, j);\n                    trajectories.second = estimated_trajectories[j];\n                    double s_threshold = std::max(safety_distance_sq, pow(operational_volumes[i] + operational_volumes[j], 2));\n                    auto loss_conflictive_segments = checkTrajectoriesLoss(trajectories, s_threshold);\n                    if (loss_conflictive_segments.size() > 0) {\n                        LossResult loss_result(i, j);\n                        loss_result.loss_conflictive_segments = loss_conflictive_segments;\n                        loss_results_list.push_back(loss_result);\n                    }\n                }\n            }\n        }\n\n        std::sort(loss_results_list.begin(), loss_results_list.end(), happensBefore);\n        gauss_msgs::NewThreats threats_msg;\n        if (just_one_threat && (loss_results_list.size() > 0 || geofence_results_list.size() > 0)) {\n            threats_msg = manageResultList(loss_results_list, geofence_results_list, index_to_operation_map, index_to_geofence_map);\n            just_one_threat = false;\n        }\n        if (threats_msg.request.threats.size() > 0) {\n            std::string cout_threats;\n            for (auto threat : threats_msg.request.threats) {\n                cout_threats = cout_threats + \" [\" + std::to_string(threat.threat_id) + \" \" + std::to_string(threat.threat_type) + \" |\";\n                for (auto uav_id : threat.uav_ids) cout_threats = cout_threats + \" \" + std::to_string(uav_id);\n                cout_threats = cout_threats + \"]\";\n            }\n            ROS_INFO_STREAM(\"[Monitoring] Threats detected: [id type | uav] \" + cout_threats);\n            if (new_threats_client.call(threats_msg)) {\n                // ROS_INFO(\"[Monitoring] Call tactical... ok\");\n            } else {\n                ROS_ERROR(\"[Monitoring] Failed to call service: [%s]\", tactical_srv_url);\n                return 1;\n            }\n        }\n\n        for (int i = 0; i < loss_results_list.size(); i++) {\n            // std::cout << loss_results_list[i] << '\\n';\n            marker_array.markers.push_back(translateToMarker(loss_results_list[i]));\n            auto extremes = calculateExtremes(loss_results_list[i]);\n            marker_array.markers.push_back(translateToMarker(extremes.first, 10 * i));\n            marker_array.markers.push_back(translateToMarker(extremes.second, 10 * i + 1));\n        }\n        visualization_pub.publish(marker_array);\n\n        ros::spinOnce();\n        rate.sleep();\n    }\n\n    // ros::spin();\n    return 0;\n}\n", "meta": {"hexsha": "a6502c506e2a36fc50ce2eff4528471bc3d9ff11", "size": 54683, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "usp_nodes/monitoring/src/continuous_monitoring.cpp", "max_stars_repo_name": "hecperleo/gauss", "max_stars_repo_head_hexsha": "20ece37af00455ee760dcef1d583300eaa347a1d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-06-22T16:53:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-27T05:06:49.000Z", "max_issues_repo_path": "usp_nodes/monitoring/src/continuous_monitoring.cpp", "max_issues_repo_name": "hecperleo/gauss", "max_issues_repo_head_hexsha": "20ece37af00455ee760dcef1d583300eaa347a1d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-09-10T10:24:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-10T10:24:20.000Z", "max_forks_repo_path": "usp_nodes/monitoring/src/continuous_monitoring.cpp", "max_forks_repo_name": "hecperleo/gauss", "max_forks_repo_head_hexsha": "20ece37af00455ee760dcef1d583300eaa347a1d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-03-25T12:50:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T11:14:21.000Z", "avg_line_length": 48.6936776492, "max_line_length": 288, "alphanum_fraction": 0.6493974361, "num_tokens": 13536, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.49907764885633754}}
{"text": "#include <cstdio>\n#include <cstdlib>\n#include <cmath>\n#include <iostream>\n#include <png.h>\n#include <TaskGraph>\n#include <TaskUserFunctions.h>\n#include <boost/static_assert.hpp>\n#include <boost/ptr_container/ptr_vector.hpp>\n#include \"mandelbrot.hpp\"\n\nusing namespace tg;\n\nconst int IMG_X = 12800;\nconst int IMG_Y ((IMG_X/(NUM_SPES*4))*3*NUM_SPES); // Approximately 4:3 aspect ratio with number of rows multiple of NUM_SPES\n\nconst int MAX_ITERATIONS = 1000;\nconst char* OUTPUT_FILE = \"mandelbrot_set.png\";\nconst float GAMMA_EXPONENT = 3.5f;\n\nconst int  UNROLL_FACTOR = 8; // MUST BE A DIVISOR OF IMG_X!\nBOOST_STATIC_ASSERT(IMG_X % UNROLL_FACTOR == 0);\n\ntypedef TaskGraph<void, int, char[IMG_X]> mandel_tg;\n\nint main(int argc, char* argv[]) {\n  int threads;\n  const Options options = getOptions(\"mandelbrot\", argc, argv);\n\n  if (options.threads < 1 || options.threads > NUM_SPES)\n  {\n    std::cerr << \"Please select a number of threads between 1 and \" << NUM_SPES << \" (inclusive).\" << std::endl;\n    exit(EXIT_FAILURE);\n  }\n  else if (IMG_Y % options.threads != 0)\n  {\n    std::cerr << \"Please choose a number of threads that is a factor of the image height (\" << IMG_Y << \").\" << std::endl;\n    exit(EXIT_FAILURE);\n  }\n  else\n  {\n    threads = options.threads;\n  }\n\n  FILE *output_file;\n  boost::ptr_vector<mandel_tg> taskGraphs; \n  TaskFarm tFarm;\n\n  mandel_tg T; \n  taskgraph(mandel_tg, T, tuple2(y_pos, line)) {\n    tVar(float, x);\n    tVar(float, y);\n    tVar(float, x0);\n    tVar(float, y0);\n    tVar(float, xtemp);\n    tVar(int, x_pos);\n    tVar(int, iteration);\n    tVar(float, pixel);\n  \n    y0 = (y_pos * (3.0f / IMG_Y)) - 1.5f;\n    \n    // Iterate over the scanline\n    tFor (x_pos, 0, IMG_X - 1) {\n      x0 = (x_pos * (3.5f / IMG_X)) - 2.5f;\n      \n      // Unroll the loop\n      for (int i = 0; i < UNROLL_FACTOR; ++i) {\n        x = x0;\n        y = y0;\n        iteration = 0;\n      \n        // Test if this location is in the set\n        tWhile ((x*x + y*y) < 4 && iteration < MAX_ITERATIONS) {\n          xtemp = (x*x) - (y*y) + x0;\n          y = 2*x*y + y0;\n          x = xtemp;\n          iteration+=1;\n        }\n\n        // Calculate and set the value of the pixel\n        tIf(iteration == MAX_ITERATIONS)\n          pixel = 0.0f;\n        tElse\n          pixel = 8.0f * (iteration + 1.0f - tLogf(tLogf(tSqrtf(x*x + y*y))) / std::log(2.0f)) / MAX_ITERATIONS;\n\n        line[x_pos] = tPowf(pixel, (1.0f / GAMMA_EXPONENT)) * 255.0f;\n        x_pos+=1;\n      }\n      x_pos-=1;\n    }\n  }\n\n  T.compile(tg::SPU_GCC, false);\n\n  for(int index=0; index<threads; ++index)\n  {\n    taskGraphs.push_back(new mandel_tg(T.duplicate()));\n    tFarm.add(&taskGraphs.back());\n  }\n\n  png_structp png_ptr;\n  png_infop info_ptr;\n  \n  if (!(output_file = fopen(OUTPUT_FILE, \"wb\"))) {\n    std::cerr << \"Unable to open \" << OUTPUT_FILE << \" for writing. Aborting now.\" << std::endl;\n    exit(1);\n  }\n  \n  if (!(png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL))) {\n    std::cerr << \"Failed to create png write struct. Aborting now.\" << std::endl;\n    exit(1);\n  }\n  \n  if (!(info_ptr = png_create_info_struct(png_ptr))) {\n    std::cerr << \"Failed to create png info struct. Aborting now.\" << std::endl;\n    // Clean up\n    png_destroy_write_struct(&png_ptr,static_cast<png_infopp>(NULL));\n    exit(1);\n  }\n  \n  png_init_io(png_ptr, output_file);  \n  png_set_IHDR(png_ptr, info_ptr, IMG_X, IMG_Y, 8,\n               PNG_COLOR_TYPE_PALETTE,\n               PNG_INTERLACE_NONE,\n               PNG_COMPRESSION_TYPE_DEFAULT,\n               PNG_FILTER_TYPE_DEFAULT);\n  png_set_gamma(png_ptr, 0.5, 0.45455);\n\n  std::vector<png_color> palette(generateBlueYellowColourMap());\n  png_set_PLTE(png_ptr, info_ptr, &palette[0], palette.size());\n  png_write_info(png_ptr, info_ptr);\n \n  std::vector<char*> scanlines(threads); \n\n  for (int spe = 0; spe < threads; ++spe)\n    scanlines[spe] = static_cast<char*>(spu_malloc(IMG_X));\n\n  for (int line = 0; line < IMG_Y; line+=threads)\n  {\n    std::vector<int> lineNumbers(threads);\n\n    for(int spe=0; spe<threads; ++spe)\n    {\n      lineNumbers[spe] = line+spe;\n      taskGraphs[spe].setParameters(lineNumbers[spe], scanlines[spe]);\n    }\n\n    tFarm.execute();\n\n    for (int spe = 0; spe < threads; ++spe) \n    {\n      png_bytep png_row_ptr = reinterpret_cast<png_bytep>(scanlines[spe]);\n      png_write_row(png_ptr, png_row_ptr);\n    }\n  }\n  \n  for (int spe = 0; spe < threads; ++spe)\n    spu_free(scanlines[spe]);\n    \n  png_write_end(png_ptr, info_ptr);\n  png_destroy_write_struct(&png_ptr, &info_ptr);\n\n  exit(EXIT_SUCCESS);\n}\n\n", "meta": {"hexsha": "b61e607814935cc4dd5fe67de5682ceec0dcc284", "size": 4572, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/cell/mandelbrot/mandelbrot.cc", "max_stars_repo_name": "paulhjkelly/taskgraph-metaprogramming", "max_stars_repo_head_hexsha": "54c4e2806a97bec555a90784ab4cf0880660bf89", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-04-11T21:30:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-04T16:16:09.000Z", "max_issues_repo_path": "examples/cell/mandelbrot/mandelbrot.cc", "max_issues_repo_name": "paulhjkelly/taskgraph-metaprogramming", "max_issues_repo_head_hexsha": "54c4e2806a97bec555a90784ab4cf0880660bf89", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/cell/mandelbrot/mandelbrot.cc", "max_forks_repo_name": "paulhjkelly/taskgraph-metaprogramming", "max_forks_repo_head_hexsha": "54c4e2806a97bec555a90784ab4cf0880660bf89", "max_forks_repo_licenses": ["BSD-3-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.5421686747, "max_line_length": 125, "alphanum_fraction": 0.6194225722, "num_tokens": 1399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.6688802669716106, "lm_q1q2_score": 0.49907764885633754}}
{"text": "#ifndef UTIL_RANDOM_HPP_\n#define UTIL_RANDOM_HPP_\n\n#include <random>\n#include <vector>\n\n#include <boost/assert.hpp>\n\n#include \"SpinMutex.hpp\"\n#include \"ThreadIndexManager.hpp\"\n\nnamespace util\n{\n\nclass Random\n{\nprivate:\n\tstatic std::vector<Random> random;\n\tstatic util::SpinMutex mutex;\n\npublic:\n\tRandom() : engine(std::random_device{}()) {}\n\tstd::default_random_engine engine;\n\n\tstatic void seed(unsigned int seed, int thread = util::ThreadIndexManager::getLocalId())\n\t{\n\t\tgetEngine(thread).seed(seed);\n\t}\n\t\n\tstatic int nextInt(int min, int max, int thread = util::ThreadIndexManager::getLocalId())\n\t{\n\t\tstd::uniform_int_distribution<> dist(min, max);\n\t\treturn dist(getEngine(thread));\n\t}\n\n\tstatic unsigned long long nextULL(int thread = util::ThreadIndexManager::getLocalId())\n\t{\n\t\tstd::uniform_int_distribution<unsigned long long> dist(\n\t\t\tstd::numeric_limits<unsigned long long>::min(),\n\t\t\tstd::numeric_limits<unsigned long long>::max()\n\t\t);\n\t\treturn dist(getEngine(thread));\n\t}\n\n\tstatic float nextReal(int thread = util::ThreadIndexManager::getLocalId())\n\t{\n\t\tstd::uniform_real_distribution<> dist;\n\t\treturn dist(getEngine(thread));\n\t}\n\n\tstatic std::default_random_engine& getEngine(int thread = util::ThreadIndexManager::getLocalId())\n\t{\n\t\tif(random.size() <= thread){\n            std::lock_guard<util::SpinMutex> lock(mutex);\n\t\t\tif(random.size() <= thread){\n                random.resize(thread + 1);\n            }\n        }\n\n\t\treturn random[thread].engine;\n\t}\n};\n\n} // end of namespace util\n\n#endif\n", "meta": {"hexsha": "c71add2a2849696ca47a1a91ae932611194527a8", "size": 1506, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "solver/modules/util/include/util/Random.hpp", "max_stars_repo_name": "taiheioki/procon2014_ut", "max_stars_repo_head_hexsha": "8199ff0a54220f1a0c51acece377f65b64db4863", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-04-14T06:41:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-29T01:56:08.000Z", "max_issues_repo_path": "solver/modules/util/include/util/Random.hpp", "max_issues_repo_name": "taiheioki/procon2014_ut", "max_issues_repo_head_hexsha": "8199ff0a54220f1a0c51acece377f65b64db4863", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "solver/modules/util/include/util/Random.hpp", "max_forks_repo_name": "taiheioki/procon2014_ut", "max_forks_repo_head_hexsha": "8199ff0a54220f1a0c51acece377f65b64db4863", "max_forks_repo_licenses": ["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.4776119403, "max_line_length": 98, "alphanum_fraction": 0.7011952191, "num_tokens": 351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.6688802537704064, "lm_q1q2_score": 0.4990776465580952}}
{"text": "/*\nMIT License\n\nCopyright (c) 2018 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#ifndef _VECTOR3_H_\n#define _VECTOR3_H_\n\n#include <meta_operations/MetaOperations.hpp>\n#include <Eigen/Dense>\n\n/**\n * @brief Class representing a 3D vector\n */\ntemplate<typename X0, typename X1, typename X2>\nclass Vector3\n{\n    public:\n\t\t/**\n\t\t * @brief Evaluation of the vector value\n\t\t */\n        template<typename T, typename ...Args>\n        static inline Eigen::Vector3d eval(const T &p, Args... args)\n\t\t{\n\t\t\treturn Eigen::Vector3d(X0::eval(p,args...),X1::eval(p,args...),X2::eval(p,args...));\n\t\t};\n\n\t\t/**\n\t\t * @brief Writing of the vector value\n\t\t */\n        template<typename ...Args>\n        static std::string write(Args... args)\n        {\n            return \"(\" + X0::write(args...) + \",\" + X1::write(args...) + \",\" + X2::write(args...) + \")\";\n        };\n\t\t\n\t\t/**\n\t\t * @brief Struct recursively applying the modifier F<T>\n\t\t */\n\t\ttemplate<template<typename T> typename F>\n\t\tstruct apply_rec\n\t\t{\n\t\t\tusing type = Vector3<typename X0::template apply_rec<F>::type,\n\t\t\t\t\t\t\t\t typename X1::template apply_rec<F>::type,\n\t\t\t\t\t\t\t\t typename X2::template apply_rec<F>::type>;\n\t\t};\n\n\t\t/**\n\t\t * @brief Importance order\n\t\t */\n\t\tstatic const unsigned int outerOrder = 3;\n\n\t\t/**\n\t\t * @brief Importance order\n\t\t */\n\t\tstatic const unsigned int innerOrder = 0;\n};\n\n/**\n * @brief Derivative of the parameter with respect to an argument\n */\ntemplate<typename X0, typename X1, typename X2, typename A>\nstruct Der<Vector3<X0,X1,X2>,A>\n{\n    using type = Vector3<typename Der<X0,A>::type,typename Der<X1,A>::type,typename Der<X2,A>::type>;\n};\n\n/**\n * @brief Simplification of the 3D vector\n */\ntemplate<typename X0, typename X1, typename X2>\nstruct Simp<Vector3<X0,X1,X2> >\n{\n    using type = Vector3<typename Simp<X0>::type,typename Simp<X1>::type,typename Simp<X2>::type>;\n};\n\n#endif //_VECTOR3_H_\n\n", "meta": {"hexsha": "53e14aa9b3fd8128eb4f49f3b3fccdba3d7b5db1", "size": 2864, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/lib/basic_operands/Vector3.hpp", "max_stars_repo_name": "Ibujah/derivative", "max_stars_repo_head_hexsha": "7f1187323e23ea84ce719b7b539390b0d58940e3", "max_stars_repo_licenses": ["MIT"], "max_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/basic_operands/Vector3.hpp", "max_issues_repo_name": "Ibujah/derivative", "max_issues_repo_head_hexsha": "7f1187323e23ea84ce719b7b539390b0d58940e3", "max_issues_repo_licenses": ["MIT"], "max_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/basic_operands/Vector3.hpp", "max_forks_repo_name": "Ibujah/derivative", "max_forks_repo_head_hexsha": "7f1187323e23ea84ce719b7b539390b0d58940e3", "max_forks_repo_licenses": ["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.2244897959, "max_line_length": 104, "alphanum_fraction": 0.6951815642, "num_tokens": 711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.49907764163312834}}
{"text": "//\n// Created by Dominik Krupke, http://krupke.cc on 10/7/17.\n//\n\n#include <gtest/gtest.h>\n#include <boost/graph/adjacency_list.hpp>\n#include \"min_vertex_cover.h\"\n\nTEST(Library, IsValidVertexCover) {\n  using Graph = boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS>;\n  Graph graph{6};\n  boost::add_edge(0, 3, graph);\n  boost::add_edge(0, 4, graph);\n  boost::add_edge(0, 5, graph);\n  boost::add_edge(1, 3, graph);\n  boost::add_edge(1, 4, graph);\n  boost::add_edge(1, 5, graph);\n  boost::add_edge(2, 3, graph);\n  boost::add_edge(2, 4, graph);\n  boost::add_edge(2, 5, graph);\n\n  std::vector<boost::graph_traits<Graph>::vertex_descriptor> vertex_cover_1;\n  vertex_cover_1.push_back(0);\n  vertex_cover_1.push_back(1);\n  std::vector<boost::graph_traits<Graph>::vertex_descriptor> vertex_cover_2;\n  vertex_cover_2.push_back(0);\n  vertex_cover_2.push_back(1);\n  vertex_cover_2.push_back(2);\n\n  ASSERT_FALSE(bipartvc::is_valid_vertex_cover(graph, vertex_cover_1));\n  ASSERT_TRUE(bipartvc::is_valid_vertex_cover(graph, vertex_cover_2));\n}\n\nTEST(Library, MinVertexCover) {\n  using Graph = boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS>;\n  Graph graph{7};\n  boost::add_edge(0, 3, graph);\n  boost::add_edge(0, 4, graph);\n  boost::add_edge(0, 5, graph);\n  boost::add_edge(1, 3, graph);\n  boost::add_edge(1, 4, graph);\n  boost::add_edge(1, 5, graph);\n  boost::add_edge(2, 3, graph);\n  boost::add_edge(2, 4, graph);\n  boost::add_edge(2, 5, graph);\n  boost::add_edge(2, 6, graph);\n\n  auto partition_classifier = [](boost::graph_traits<Graph>::vertex_descriptor v) -> bipartvc::Partition {\n    if (v < 3) {\n      return bipartvc::Partition::A;\n    } else {\n      return bipartvc::Partition::B;\n    }\n  };\n  auto vertex_cover = bipartvc::get_minimal_vertex_cover(graph, partition_classifier);\n\n  ASSERT_EQ(vertex_cover.size(), 3);\n  ASSERT_TRUE(bipartvc::is_valid_vertex_cover(graph, vertex_cover));\n\n  //swap partitions (A is treated differently than B by the algorithm so we should check this)\n  auto complementary_partition_classifier = [](boost::graph_traits<Graph>::vertex_descriptor v) -> bipartvc::Partition {\n    if (v < 3) {\n      return bipartvc::Partition::B;\n    } else {\n      return bipartvc::Partition::A;\n    }\n  };\n  auto vertex_cover_2 = bipartvc::get_minimal_vertex_cover(graph, complementary_partition_classifier);\n\n  ASSERT_EQ(vertex_cover_2.size(), 3);\n  ASSERT_TRUE(bipartvc::is_valid_vertex_cover(graph, vertex_cover_2));\n\n  //and with automatic partition detection.\n  auto vertex_cover_3 = bipartvc::get_minimal_vertex_cover(graph);\n  ASSERT_EQ(vertex_cover_3.size(), 3);\n  ASSERT_TRUE(bipartvc::is_valid_vertex_cover(graph, vertex_cover_3));\n}\n\nTEST(MinVertexCover, Star) {\n  using Graph = boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS>;\n  Graph graph{7};\n  boost::add_edge(0, 2, graph);\n  boost::add_edge(0, 3, graph);\n  boost::add_edge(0, 4, graph);\n  boost::add_edge(0, 5, graph);\n  boost::add_edge(0, 6, graph);\n  boost::add_edge(1, 2, graph);\n  boost::add_edge(1, 3, graph);\n  boost::add_edge(1, 4, graph);\n  boost::add_edge(1, 5, graph);\n  boost::add_edge(1, 6, graph);\n  auto partition_classifier = [](boost::graph_traits<Graph>::vertex_descriptor v) -> bipartvc::Partition {\n    if (v < 2) {\n      return bipartvc::Partition::A;\n    } else {\n      return bipartvc::Partition::B;\n    }\n  };\n  auto vertex_cover = bipartvc::get_minimal_vertex_cover(graph, partition_classifier);\n\n  ASSERT_EQ(vertex_cover.size(), 2);\n  ASSERT_TRUE(bipartvc::is_valid_vertex_cover(graph, vertex_cover));\n\n  //swap partitions (A is treated differently than B by the algorithm so we should check this)\n  auto complementary_partition_classifier = [](boost::graph_traits<Graph>::vertex_descriptor v) -> bipartvc::Partition {\n    if (v < 2) {\n      return bipartvc::Partition::B;\n    } else {\n      return bipartvc::Partition::A;\n    }\n  };\n  auto vertex_cover_2 = bipartvc::get_minimal_vertex_cover(graph, complementary_partition_classifier);\n\n  ASSERT_EQ(vertex_cover_2.size(), 2);\n  ASSERT_TRUE(bipartvc::is_valid_vertex_cover(graph, vertex_cover_2));\n\n  //and with automatic partition detection.\n  auto vertex_cover_3 = bipartvc::get_minimal_vertex_cover(graph);\n  ASSERT_EQ(vertex_cover_3.size(), 2);\n  ASSERT_TRUE(bipartvc::is_valid_vertex_cover(graph, vertex_cover_3));\n\n}\n\nTEST(MinVertexCover, ConnectedStar) {\n  using Graph = boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS>;\n  Graph graph{12};\n  boost::add_edge(0, 2, graph);\n  boost::add_edge(0, 3, graph);\n  boost::add_edge(0, 4, graph);\n  boost::add_edge(0, 5, graph);\n  boost::add_edge(0, 6, graph);\n  boost::add_edge(1, 7, graph);\n  boost::add_edge(1, 8, graph);\n  boost::add_edge(1, 9, graph);\n  boost::add_edge(1, 10, graph);\n  boost::add_edge(1, 11, graph);\n  boost::add_edge(0, 1, graph);\n\n  auto vertex_cover_3 = bipartvc::get_minimal_vertex_cover(graph);\n  ASSERT_EQ(vertex_cover_3.size(), 2);\n  ASSERT_TRUE(bipartvc::is_valid_vertex_cover(graph, vertex_cover_3));\n\n}\n\nTEST(MinVertexCover, EvenCycle) {\n  using Graph = boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS>;\n  Graph graph{12};\n  boost::add_edge(0, 1, graph);\n  boost::add_edge(1, 2, graph);\n  boost::add_edge(2, 3, graph);\n  boost::add_edge(3, 4, graph);\n  boost::add_edge(4, 5, graph);\n  boost::add_edge(5, 6, graph);\n  boost::add_edge(6, 7, graph);\n  boost::add_edge(7, 8, graph);\n  boost::add_edge(8, 9, graph);\n  boost::add_edge(9, 10, graph);\n  boost::add_edge(10, 11, graph);\n  boost::add_edge(11, 0, graph);\n\n  auto vertex_cover_3 = bipartvc::get_minimal_vertex_cover(graph);\n  ASSERT_EQ(vertex_cover_3.size(), 6);\n  ASSERT_TRUE(bipartvc::is_valid_vertex_cover(graph, vertex_cover_3));\n\n}\n\n", "meta": {"hexsha": "78893369a7116c44e74e94763b3db343d46f5826", "size": 5717, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "min_vertex_cover_gtest.cpp", "max_stars_repo_name": "d-krupke/bipartite_vertex_cover", "max_stars_repo_head_hexsha": "4ad5bbf1d8490e131d093cd12addaac8f531345f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "min_vertex_cover_gtest.cpp", "max_issues_repo_name": "d-krupke/bipartite_vertex_cover", "max_issues_repo_head_hexsha": "4ad5bbf1d8490e131d093cd12addaac8f531345f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "min_vertex_cover_gtest.cpp", "max_forks_repo_name": "d-krupke/bipartite_vertex_cover", "max_forks_repo_head_hexsha": "4ad5bbf1d8490e131d093cd12addaac8f531345f", "max_forks_repo_licenses": ["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.2335329341, "max_line_length": 120, "alphanum_fraction": 0.7091131712, "num_tokens": 1753, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.49907763900640423}}
{"text": "#pragma once\n#include <iostream>\n#include <boost/math/common_factor_rt.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_int_distribution.hpp>\n#include <chrono>\n#include <vector>\n\n#include \"globals.hpp\"\n\n//the Test_Suite namespace contains functions that aid in\n//verifying the correctness of gcd algorithms as well as\n//testing the performance of generic gcd routines\nnamespace Test_Suite{\n\t\n\t//these functions make sure that the gcd algorithms are correct\n\ttemplate <typename IntegerType=Default_Test_Element> bool Check_Algorithm_Validity(std::vector<IntegerType>&(*fun_)(std::vector<IntegerType>&));\n\ttemplate <typename IntegerType=Default_Test_Element> bool Check_Answer_Validity(std::vector<Default_Test_Element> const& vec);\n\t\n\t//utility\n\ttemplate <typename IntegerType=Default_Test_Element> boost::random::uniform_int_distribution<IntegerType> Get_Specified_Bit_Length_Distribution(int bit_length);\n\t\n};\n\n//these functions make sure that the gcd algorithms are correct\ntemplate <typename IntegerType> bool Test_Suite::Check_Algorithm_Validity(std::vector<IntegerType>&(*fun_)(std::vector<IntegerType>&)){\n\tint fail_rate=0;\n\t\n\tboost::random::mt19937 gen(std::time(0));\n\tDefault_Test_Element a;\n\tstd::vector<Default_Test_Element> vec;\n\tauto dist = Test_Suite::Get_Specified_Bit_Length_Distribution(30);\n\t\n\t//fill up the vector\n\tfor (int i = 0; i < 100; ++i){\n\t\ta = dist(gen);\n\t\tvec.push_back(a);\n\t}\n\t\n\t//std::cout << \"no: \"; for (auto it: vec){std::cout << it << \",\";}std::cout << std::endl << std::endl;\n\t\n\tfun_(vec);\n\tfail_rate += Test_Suite::Check_Answer_Validity(vec);\n\t\n\tbool failed = false;\n\tif (fail_rate > 0){failed = true;}\n\treturn failed;\n}\ntemplate <typename IntegerType> bool Test_Suite::Check_Answer_Validity(std::vector<Default_Test_Element> const& vec){\n\t\n\tDefault_Test_Element min = 0;\n\tif (!vec.empty()){\n\t\tmin = vec[0];\n\t}\n\t\n\tfor (auto const& it: vec){\n\t\tif (min > it){\n\t\t\tstd::cerr << \"list not sorted.\" << std::endl;\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\t//std::cout << \"yes: \"; for (auto it: vec){std::cout << it << \",\";}std::cout << std::endl << std::endl;\n\t\n\treturn true;\n}\n\n//utility\ntemplate <typename IntegerType> boost::random::uniform_int_distribution<IntegerType> Test_Suite::Get_Specified_Bit_Length_Distribution(int bit_length){\n\tIntegerType min = pow(2,bit_length-1);\n\tIntegerType max = pow(2,bit_length)-1;\n\treturn boost::random::uniform_int_distribution<IntegerType>(min,max);\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "73fa36bc11e1276036004304b76d6b20a16c0d9e", "size": 2456, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "source/code/scratch/old_repos/edinboro/CSCI-385/sort-algorithms/code/test_suite.hpp", "max_stars_repo_name": "luxe/CodeLang-compiler", "max_stars_repo_head_hexsha": "78837d90bdd09c4b5aabbf0586a5d8f8f0c1e76a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 33.0, "max_stars_repo_stars_event_min_datetime": "2019-05-30T07:43:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-30T13:12:32.000Z", "max_issues_repo_path": "source/code/scratch/old_repos/edinboro/CSCI-385/sort-algorithms/code/test_suite.hpp", "max_issues_repo_name": "luxe/CodeLang-compiler", "max_issues_repo_head_hexsha": "78837d90bdd09c4b5aabbf0586a5d8f8f0c1e76a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 371.0, "max_issues_repo_issues_event_min_datetime": "2019-05-16T15:23:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-04T15:45:27.000Z", "max_forks_repo_path": "source/code/scratch/old_repos/edinboro/CSCI-385/sort-algorithms/code/test_suite.hpp", "max_forks_repo_name": "UniLang/compiler", "max_forks_repo_head_hexsha": "c338ee92994600af801033a37dfb2f1a0c9ca897", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2019-08-22T17:37:36.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-07T07:15:32.000Z", "avg_line_length": 26.989010989, "max_line_length": 161, "alphanum_fraction": 0.7333061889, "num_tokens": 630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389817407016, "lm_q2_score": 0.6688802537704064, "lm_q1q2_score": 0.4990776314547131}}
{"text": "// Author(s): Jeroen Keiren\n// Copyright: see the accompanying file COPYING or copy at\n// https://github.com/mCRL2org/mCRL2/blob/master/COPYING\n//\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//\n// / \\file bag_test.cpp\n// / \\brief Basic regression test for bag expressions.\n\n#define BOOST_TEST_MODULE bag_test\n#include <boost/test/included/unit_test.hpp>\n\n#include \"mcrl2/data/bag.h\"\n#include \"mcrl2/data/parse.h\"\n#include \"mcrl2/data/rewriter.h\"\n\n\nusing namespace mcrl2;\nusing namespace mcrl2::data;\n\n// test whether parsing s returns an expression matching predicate p.\n// Furthermore check whether the expression does not satisfy q.\ntemplate <typename Predicate, typename NegativePredicate>\nvoid test_data_expression(const std::string& s, const variable_vector& v, Predicate p, NegativePredicate q)\n{\n  std::cerr << \"testing data expression \" << s << std::endl;\n  data_expression e = parse_data_expression(s, v);\n  std::cerr << \"parsed expression \" << e << \"\\n\";\n  BOOST_CHECK(p(e));\n  BOOST_CHECK(!q(e));\n}\n\nvoid test_expression(const std::string& evaluate, const std::string& expected, data::rewriter r)\n{\n  data_expression d1 = parse_data_expression(evaluate);\n  data_expression d2 = parse_data_expression(expected);\n  if (r(d1)!=r(d2))\n  {\n    std::cerr << \"Evaluating: \" << evaluate << \"\\n\";\n    std::cerr << \"Result: \" << d1 << \"\\n\";\n    std::cerr << \"Expected result: \" << expected << \"\\n\";\n    BOOST_CHECK(r(d1) == r(d2));\n    std::cerr << \"------------------------------------------------------\\n\";\n  }\n}\n\n\nvoid bag_expression_test()\n{\n  data::data_specification specification;\n\n  specification.add_context_sort(sort_bag::bag(sort_pos::pos()));\n  specification.add_context_sort(sort_bag::bag(sort_bool::bool_()));\n\n  data::rewriter normaliser(specification);\n\n  variable_vector v;\n  v.push_back(parse_variable(\"b:Bag(Nat)\"));\n\n  BOOST_CHECK(sort_bag::is_bag(sort_bag::bag(sort_nat::nat())));\n  BOOST_CHECK(!sort_bag::is_bag(sort_nat::nat()));\n\n  test_data_expression(\"{x : Nat | x}\", v, sort_bag::is_constructor_application, sort_bag::is_in_application);\n  test_data_expression(\"1 in b\", v, sort_bag::is_in_application, sort_bag::is_union_application);\n  test_data_expression(\"{:} + b\", v, sort_bag::is_union_application, sort_bag::is_intersection_application);\n  test_data_expression(\"(({:} + b) - {20:1}) * {40:5}\", v, sort_bag::is_intersection_application, is_less_application<data_expression>);\n  test_data_expression(\"{10:count(20,b)} < b\", v, is_less_application<data_expression>, sort_bag::is_bag_comprehension_application);\n  test_data_expression(\"b <= {20:2}\", v, is_less_equal_application<data_expression>, sort_bag::is_set2bag_application);\n  test_data_expression(\"Set2Bag({20,30,40})\", v, sort_bag::is_set2bag_application, sort_bag::is_union_application);\n  test_data_expression(\"{20:2} + Set2Bag({20,30,40})\", v, sort_bag::is_union_application, is_less_equal_application<data_expression>);\n  test_data_expression(\"b <= Set2Bag({20,30,40})\", v, is_less_equal_application<data_expression>, sort_bag::is_constructor_application);\n\n  test_data_expression(\"b <= {20:2} + Set2Bag({20,30,40})\", v, is_less_equal_application<data_expression>, sort_bag::is_constructor_application);\n\n  data_expression e = parse_data_expression(\"{20:1}\", v);\n  BOOST_CHECK(sort_fbag::is_cons_application(normaliser(e)));\n\n  e = parse_data_expression(\"{20:4, 30:3, 40:2}\", v);\n  BOOST_CHECK(sort_fbag::is_cons_application(normaliser(e)));\n\n  e = parse_data_expression(\"{10:count(20,b)}\", v);\n  BOOST_CHECK(sort_fbag::is_cinsert_application(normaliser(e)));\n\n  // Chect the operation == on bags\n  test_expression(\"{:} == ({true:2} - {true:2})\",\"true\",normaliser);  // {true}-{true} is a trick to type {:} == {:}. \n  test_expression(\"{:} == {false:2}\", \"false\",normaliser);\n  test_expression(\"{:} == {true:2}\", \"false\",normaliser);\n  test_expression(\"{true:2} == {true:3}\", \"false\",normaliser);\n  test_expression(\"{false:2} == {false:2}\", \"true\",normaliser);\n  test_expression(\"{true:2} == {false:2, true:2}\", \"false\",normaliser);\n  test_expression(\"{false:2, true:2} == {false:2}\", \"false\",normaliser);\n  test_expression(\"{false:2, true:2} == {true:2, false:2}\", \"true\",normaliser);\n\n  // Check the operation < on bags.\n  test_expression(\"{:} < ({true:2} - {true:2})\",\"false\",normaliser);  // {true}-{true} is a trick to type {:} == {:}. \n  test_expression(\"{true:2} < {false:4}\", \"false\",normaliser);\n  test_expression(\"{true:2} < {false:2}\", \"false\",normaliser);\n  test_expression(\"{false:2} < {true:4}\", \"false\",normaliser);\n  test_expression(\"{true:2} < {true:3}\", \"true\",normaliser);\n  test_expression(\"{false:2} < {false:1}\", \"false\",normaliser);\n  test_expression(\"{true:2} < {false:4, true:2}\", \"true\",normaliser);\n  test_expression(\"{false:2} < {false:1, true:2}\", \"false\",normaliser);\n  test_expression(\"{true:2} < {true:4, false:2}\", \"true\",normaliser);\n  test_expression(\"{false:2} < {true:4, false:2}\", \"true\",normaliser);\n  test_expression(\"{true:2, false:4} < {true:4}\", \"false\",normaliser);\n  test_expression(\"{true:2, false:4} < {false:2}\", \"false\",normaliser);\n  test_expression(\"{false:2, true:4} < {true:2}\", \"false\",normaliser);\n  test_expression(\"{false:2, true:4} < {false:5}\", \"false\",normaliser);\n  test_expression(\"{true:2, false:4} < {false:2, true:2}\", \"false\",normaliser);\n  test_expression(\"{true:2, false:4} < {true:2, false:2}\", \"false\",normaliser);\n  test_expression(\"{false:2, true:1} < {false:2, true:2}\", \"true\",normaliser);\n  test_expression(\"{false:2, true:4} < {true:7, false:2}\", \"true\",normaliser);\n  test_expression(\"{false:1, false:1} < {false:2}\", \"false\",normaliser);\n  \n  // Check the operation <= on bags.\n  test_expression(\"{:} <= ({true:2}-{true:2})\",\"true\",normaliser);  // {true} - {true} is a trick to type {:} == {:}.\n  test_expression(\"{true:2} <= {false:2}\", \"false\",normaliser);\n  test_expression(\"{false:2} <= {true:2}\", \"false\",normaliser);\n  test_expression(\"{true:2} <= {true:2}\", \"true\",normaliser);\n  test_expression(\"{true:3} <= {true:2}\", \"false\",normaliser);\n  test_expression(\"{false:2} <= {false:1}\", \"false\",normaliser);\n  test_expression(\"{false:2} <= {false:7}\", \"true\",normaliser);\n  test_expression(\"{true:2} <= {false:2, true:2}\", \"true\",normaliser);\n  test_expression(\"{false:2} <= {false:4, true:2}\", \"true\",normaliser);\n  test_expression(\"{true:2} <= {true:1, false:2}\", \"false\",normaliser);\n  test_expression(\"{false:2} <= {true:2, false:2}\", \"true\",normaliser);\n  test_expression(\"{true:2, false:2} <= {true:3}\", \"false\",normaliser);\n  test_expression(\"{true:2, false:2} <= {false:1}\", \"false\",normaliser);\n  test_expression(\"{false:2, true:2} <= {true:2}\", \"false\",normaliser);\n  test_expression(\"{false:2, true:2} <= {false:2}\", \"false\",normaliser);\n  test_expression(\"{true:2, false:2} <= {false:2, true:2}\", \"true\",normaliser);\n  test_expression(\"{true:2, false:2} <= {true:2, false:2}\", \"true\",normaliser);\n  test_expression(\"{false:2, true:2} <= {false:2, true:2}\", \"true\",normaliser);\n  test_expression(\"{false:2, true:2} <= {true:2, false:2}\", \"true\",normaliser);\n  test_expression(\"{false:1, false:2} <= {false:2}\", \"false\", normaliser);\n\n  // Test the operation - on bags.\n  test_expression(\"{true:0} - {:}\", \"{true:0}\", normaliser);\n  test_expression(\"{:} - {true:1}\", \"{true:0}\", normaliser);\n  test_expression(\"{true:1} - {:}\", \"{true:1}\", normaliser);\n  test_expression(\"{:} - {true:2}\", \"{true:0}\", normaliser);\n  test_expression(\"{true:2} - {:}\", \"{true:2}\", normaliser);\n  test_expression(\"{true:1} - {true:1}\", \"{true:0}\", normaliser);\n  test_expression(\"{true:2} - {true:1}\", \"{true:1}\", normaliser);\n  test_expression(\"{true:1} - {true:2}\", \"{true:0}\", normaliser);\n  test_expression(\"{true:1} - {false:1}\", \"{true:1}\", normaliser);\n  test_expression(\"{false:1} - {true:1}\", \"{false:1}\", normaliser);\n  test_expression(\"{true:2} - {false:1}\", \"{true:2}\", normaliser);\n  test_expression(\"{false:2} - {true:1}\", \"{false:2}\", normaliser);\n  test_expression(\"{true:1} - {false:2}\", \"{true:1}\", normaliser);\n  test_expression(\"{false:1} - {true:2}\", \"{false:1}\", normaliser);\n  test_expression(\"{true:1, false:1} - {false:1}\", \"{true:1}\", normaliser);\n  test_expression(\"{true:1, false:1} - {true:1}\", \"{false:1}\", normaliser);\n  test_expression(\"{true:1, false:1} - {true:1, false:1}\", \"{true:0}\",\n                  normaliser);\n  test_expression(\"{true:1, false:1} - {false:1, true:1}\", \"{true:0}\",\n                  normaliser);\n  test_expression(\"{true:2, false:2} - {false:1}\", \"{true:2, false:1}\",\n                  normaliser);\n  test_expression(\"{true:2, false:2} - {true:1}\", \"{true:1, false:2}\",\n                  normaliser);\n  test_expression(\"{true:2, false:2} - {true:1,false:1}\", \"{true:1, false:1}\",\n                  normaliser);\n  test_expression(\"{true:2, false:2} - {false:1,true:1}\", \"{true:1, false:1}\",\n                  normaliser);\n  test_expression(\"{true:2, false:2} - {false:2}\", \"{true:2}\", normaliser);\n  test_expression(\"{true:2, false:2} - {false:2}\", \"{true:2}\", normaliser);\n}\n\nBOOST_AUTO_TEST_CASE(test_main)\n{\n  bag_expression_test();\n}\n\n", "meta": {"hexsha": "b446bbba1acb871615c13358007e3b56a5a07d07", "size": 9175, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libraries/data/test/bag_test.cpp", "max_stars_repo_name": "sdrees/mCRL2", "max_stars_repo_head_hexsha": "bbda4c85022bc21cfa3eab3aafd07e60e89dee2d", "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": "libraries/data/test/bag_test.cpp", "max_issues_repo_name": "sdrees/mCRL2", "max_issues_repo_head_hexsha": "bbda4c85022bc21cfa3eab3aafd07e60e89dee2d", "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": "libraries/data/test/bag_test.cpp", "max_forks_repo_name": "sdrees/mCRL2", "max_forks_repo_head_hexsha": "bbda4c85022bc21cfa3eab3aafd07e60e89dee2d", "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": 51.8361581921, "max_line_length": 145, "alphanum_fraction": 0.6563487738, "num_tokens": 2735, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389817407016, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.499077631454713}}
{"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//// Compressible module (field solver)\n// Compute field variables and field sources\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-panels (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 \"solve_field.h\"\n#include \"compute_fVars.h\"\n\nusing namespace std;\nusing  namespace Eigen;\n\n#define GAMMA 1.4\n#define CMU 1.0\n#define M_C 1.0\n\nvoid solve_field(double Minf, Vector3d &vInf, Network &bPan, Field &fPan, Subpanel &sp,\n                 Body_AIC &b2fAIC, Field2field_AIC &f2fAIC, Subpanel_AIC &spAIC) {\n\n    //// Begin\n    cout << \"Computing field variables... \" << flush;\n\n    //// Field variables\n    compute_fVars(Minf, vInf, bPan, fPan, sp, b2fAIC, f2fAIC, spAIC);\n\n    //// Field sources\n    // Density gradient\n    for (int i = 0; i < fPan.nE; i++) {\n        int f = fPan.eIdx(i);\n        double dU, dV, dW; // Variables for residual\n\n        // X-derivative\n        double fb=0, ff=0, fb2=0, ff2=0;\n        if (fPan.fbdMap(f,0)) {\n            fb = (fPan.rho(f) - fPan.rho(f - 1)) / fPan.deltaX;\n            fb2 = (fPan.U(f,0) - fPan.U(f - 1,0)) / fPan.deltaX;\n        }\n        if (fPan.fbdMap(f,1)) {\n            ff = (fPan.rho(f + 1) - fPan.rho(f)) / fPan.deltaX;\n            ff2 = (fPan.U(f + 1,0) - fPan.U(f,0)) / fPan.deltaX;\n        }\n        if (fPan.fbdMap(f,0) && fPan.fbdMap(f,1)) {\n            fPan.dRho(f,0) = 0.5*(fb+ff);\n            dU = 0.5*(fb2+ff2);\n        }\n        else {\n            fPan.dRho(f,0) = fb+ff;\n            dU = fb2+ff2;\n        }\n\n        // Y-derivative\n        fb=0, ff=0, fb2=0, ff2=0;\n        if (fPan.fbdMap(f,2)) {\n            fb = (fPan.rho(f) - fPan.rho(f - fPan.nX*fPan.nZ)) / fPan.deltaY;\n            fb2 = (fPan.U(f,1) - fPan.U(f - fPan.nX*fPan.nZ,1)) / fPan.deltaY;\n        }\n        if (fPan.fbdMap(f,3)) {\n            ff = (fPan.rho(f + fPan.nX*fPan.nZ) - fPan.rho(f)) / fPan.deltaY;\n            ff2 = (fPan.U(f + fPan.nX*fPan.nZ,1) - fPan.U(f,1)) / fPan.deltaY;\n        }\n        if (fPan.fbdMap(f,2) && fPan.fbdMap(f,3)) {\n            fPan.dRho(f,1) = 0.5*(fb+ff);\n            dV = 0.5*(fb2+ff2);\n        }\n        else {\n            fPan.dRho(f,1) = fb+ff;\n            dV = fb2+ff2;\n        }\n\n        // Z-derivative\n        fb=0, ff=0, fb2=0, ff2=0;\n        if (fPan.fbdMap(f,4)) {\n            fb = (fPan.rho(f) - fPan.rho(f - fPan.nX)) / fPan.deltaZ;\n            fb2 = (fPan.U(f,2) - fPan.U(f - fPan.nX,2)) / fPan.deltaZ;\n        }\n        if (fPan.fbdMap(f,5)) {\n            ff = (fPan.rho(f + fPan.nX) - fPan.rho(f)) / fPan.deltaZ;\n            ff2 = (fPan.U(f + fPan.nX,2) - fPan.U(f,2)) / fPan.deltaZ;\n        }\n        if (fPan.fbdMap(f,4) && fPan.fbdMap(f,5)) {\n            fPan.dRho(f,2) = 0.5*(fb+ff);\n            dW = 0.5*(fb2+ff2);\n        }\n        else {\n            fPan.dRho(f,2) = fb+ff;\n            dW = fb2+ff2;\n        }\n\n        // Field source\n        fPan.sigma(f) = -1 / (fPan.rho(f)) * fPan.U.row(f).dot(fPan.dRho.row(f));\n        // Residual\n        fPan.epsilon(f) = dU + dV + dW - fPan.sigma(f);\n    }\n\n    // TODO 1) Artificial density (pros: physical; cons: does not work on MG or RG/MG)\n    // TODO 2) Artificial viscosity (pros: works on RG/MG; cons: cut through surface, not physical)\n    // TODO NB) With current form, x-upwinding gives same results as s-upwinding.\n\n    //// Artificial viscosity\n    for (int i = 0; i < fPan.nE; i++) {\n        int f = fPan.eIdx(i);\n        double mu, deltaSigmaX, deltaSigmaY, deltaSigmaZ; // Variables for artificial viscosity\n\n        if (fPan.M(f) > M_C) {\n            mu = CMU * (1 - M_C * M_C / (fPan.M(f) * fPan.M(f)));\n\n            // X-contribution\n            if (fPan.U(f,0) > 0 && fPan.fbdMap(f,0))\n                deltaSigmaX = fPan.sigma(f) - fPan.sigma(f - 1);\n            else if (fPan.U(f,0) < 0 && fPan.fbdMap(f,1))\n                deltaSigmaX = fPan.sigma(f + 1) - fPan.sigma(f);\n            else\n                deltaSigmaX = 0;\n            // Y-contribution\n            if (fPan.U(f,1) > 0 && fPan.fbdMap(f,2))\n                deltaSigmaY = fPan.sigma(f) - fPan.sigma(f - fPan.nX*fPan.nZ);\n            else if (fPan.U(f,1) < 0 && fPan.fbdMap(f,3))\n                deltaSigmaY = fPan.sigma(f + fPan.nX*fPan.nZ) - fPan.sigma(f);\n            else\n                deltaSigmaY = 0;\n            // Z-contribution\n            if (fPan.U(f,2) > 0 && fPan.fbdMap(f,4))\n                deltaSigmaZ = fPan.sigma(f) - fPan.sigma(f - fPan.nX);\n            else if (fPan.U(f,2) < 0 && fPan.fbdMap(f,5))\n                deltaSigmaZ = fPan.sigma(f + fPan.nX) - fPan.sigma(f);\n            else\n                deltaSigmaZ = 0;\n\n            fPan.sigma(f) -= mu / fPan.U.row(f).norm() *\n                               (fPan.U(f, 0) * deltaSigmaX + fPan.U(f, 1) * deltaSigmaY + fPan.U(f, 2) * deltaSigmaZ);\n        }\n    }\n\n    cout << \"Done!\" << endl;\n    cout << \"Max. Mach number: \" << fPan.M.maxCoeff() << endl;\n    cout << \"Field sources strength: \" << fPan.sigma.norm() << endl << endl;\n}", "meta": {"hexsha": "90b09dd09b4f115ec1937dc6be1401f29a4b4017", "size": 5852, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/solve_field.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/solve_field.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/solve_field.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": 35.4666666667, "max_line_length": 118, "alphanum_fraction": 0.5251196172, "num_tokens": 1977, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.49900608043264527}}
{"text": "\ufeff#include <iostream>\r\n#include <complex>\r\n#include <cmath>\r\n#include <vector>\r\n#include <numeric>\r\n#include <tuple>\r\n#include <fstream>\r\n#include <ctime>\r\n#include <chrono>\r\n#include <stdio.h>\r\n#include <Eigen/Dense>\r\n#include <Eigen/Core>\r\n#include <omp.h>\r\n\r\n// Defining special types\r\ntypedef std::complex<double> dcomp;\r\ntypedef std::vector<double> dvec;\r\ntypedef std::vector< std::vector<double> > ddvec;\r\ntypedef std::vector<int> ivec;\r\ntypedef std::vector< std::vector<int> > iivec;\r\ntypedef std::vector< std::complex<double> > dcvec;\r\ntypedef std::vector< std::vector<std::complex<double> > > ddcvec;\r\n\r\n/* --------------------------------------------------------------------\r\n\r\n\t\tFUNCTIONS\r\n\r\n-----------------------------------------------------------------------*/\r\n\r\ninline const double pi()\r\n{\r\n\t// Set teh value fo pi\r\n\tconst double pi = std::atan(1) * 4;\r\n\treturn pi;\r\n}\r\n\r\n/* --------------------------------------------------------------------\r\n\t\tFROM MICROSECONDS TO HH:MM:SS:MS\r\n-----------------------------------------------------------------------*/\r\nstd::tuple<long long, long long, long long, long long> ms_to_time(long long ms)\r\n{\r\n\t// Defining the variables\r\n\tlong long s, m, h;\r\n\r\n\t// Calculating the time in hour:minutes:seconds:microseconds\r\n\ts = ms / 1000000;\r\n\tms = ms % 1000000;\r\n\tm = s / 60;\r\n\ts = s % 60;\r\n\th = m / 60;\r\n\tm = m % 60;\r\n\r\n\treturn { ms,s,m,h };\r\n}\r\n/* --------------------------------------------------------------------\r\n\t\tPRINT in HH:MM:SS:MS FORMAT\r\n-----------------------------------------------------------------------*/\r\nvoid time_print(long long ms, long long s, long long m, long long h)\r\n{\r\n\r\n\t// Print the time\r\n\tif (h < 10)\r\n\t{\r\n\t\tstd::cout << \"0\" << h << \":\";\r\n\t}\r\n\telse\r\n\t{\r\n\t\tstd::cout << \"\" << h << \":\";\r\n\t}\r\n\tif (m < 10)\r\n\t{\r\n\t\tstd::cout << \"0\" << m << \":\";\r\n\t}\r\n\telse\r\n\t{\r\n\t\tstd::cout << \"\" << m << \":\";\r\n\t}\r\n\tif (s < 10)\r\n\t{\r\n\t\tstd::cout << \"0\" << s << \":\" << ms;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tstd::cout << \"\" << s << \":\" << ms;\r\n\t}\r\n\r\n\treturn;\r\n}\r\n/* --------------------------------------------------------------------\r\n\t\tCHI FROM Z\r\n-----------------------------------------------------------------------*/\r\ninline dcomp chi_from_z(dcomp z, dcomp z1, dcomp z2, double L, double mu)\r\n{\r\n\t// Defining the variables\r\n\tdcomp z0, Z, chi;\r\n\r\n\t// Calculating the chi from a z value\r\n\tz0 = 0.5 * (z1 + z2);\r\n\tZ = exp(dcomp(0, -1) * mu) * 2.0 * (z - z0) / L;\r\n\tchi = Z + sqrt(Z - 1.0) * sqrt(Z + 1.0);\r\n\r\n\treturn chi;\r\n}\r\n/* --------------------------------------------------------------------\r\n\t\tZ FROM CHI\r\n-----------------------------------------------------------------------*/\r\ninline dcomp z_from_chi(dcomp chi, dcomp z1, dcomp z2, double L, double mu)\r\n{\r\n\t// Defining the variables\r\n\tdcomp z, z0, Z;\r\n\r\n\t// Calculating the z from a chi value\r\n\tz0 = 0.5 * (z1 + z2);\r\n\tZ = 0.5 * (chi + 1.0 / chi);\r\n\tz = 0.5 * L * Z * exp(dcomp(0, 1) * mu) + z0;\r\n\r\n\treturn z;\r\n}\r\n/* --------------------------------------------------------------------\r\n\t\tANGEL CHANGE\r\n-----------------------------------------------------------------------*/\r\ninline double angel_change(dcomp z, dcomp z1, dcomp z2)\r\n{\r\n\t// Defining the variables\r\n\tdouble u, v, eta;\r\n\r\n\t// Calculating the angels\r\n\tu = arg(z - z1);\r\n\tv = arg(z1 - z2);\r\n\r\n\t// Correct to angel of 0 to 2pi\r\n\tif (u < 0)\r\n\t{\r\n\t\tu += 2 * pi();\r\n\t}\r\n\tif (v < 0)\r\n\t{\r\n\t\tv += 2 * pi();\r\n\t}\r\n\r\n\t// Calculate angel between the vectors\r\n\teta = abs(u - v);\r\n\r\n\t// Correct to angel of 0 to pi\r\n\tif (eta > pi())\r\n\t{\r\n\t\teta -= 2 * pi();\r\n\t}\r\n\r\n\teta = abs(eta);\r\n\r\n\treturn eta;\r\n}\r\n/* --------------------------------------------------------------------\r\n\t\tFIND INTERSECTION POINT\r\n-----------------------------------------------------------------------*/\r\ninline std::tuple<dcomp, int> intersection_point(dcomp z1, dcomp z2, dcomp z3, dcomp z4)\r\n{\r\n\t// Defining the variables\r\n\tdcomp zint, Z1, Z2;\r\n\tint int_check = 0;\r\n\r\n\tif (z1 != z3 || z2 != z4)\r\n\t{\r\n\t\t// Calculating the intersection point\r\n\t\tzint = ((conj(z2 - z1) * z1 - (z2 - z1) * conj(z1)) * (z4 - z3) - (conj(z4 - z3) * z3 - (z4 - z3) * conj(z3)) * (z2 - z1)) / ((z4 - z3) * conj(z2 - z1) - (z2 - z1) * conj(z4 - z3));\r\n\r\n\t\t// Check if intersection is on the lines\r\n\t\tZ1 = (zint - .5 * (z1 + z2)) / (.5 * (z1 - z2));\r\n\t\tZ2 = (zint - .5 * (z3 + z4)) / (.5 * (z3 - z4));\r\n\r\n\t\tif (real(Z1 * conj(Z1)) < 1.0)\r\n\t\t{\r\n\t\t\tif (real(Z2 * conj(Z2)) < 1.0)\r\n\t\t\t{\r\n\t\t\t\tint_check = 1;\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t}\r\n\r\n\treturn { zint, int_check };\r\n}\r\n/* --------------------------------------------------------------------\r\n\t\tGET DELTA\r\n-----------------------------------------------------------------------*/\r\ninline dcomp get_delta(ddcvec ab, int nab, int m, ivec pos_z1, ivec pos_z2)\r\n{\r\n\t// Defintion of variables\r\n\tdcomp delta;\r\n\r\n\tdelta = 0;\r\n\tfor (int ii = 0; ii < nab; ii++)\r\n\t{\r\n\t\t// Adding the jump for the z1 elements\r\n\t\tif (pos_z1[ii] == 1)\r\n\t\t{\r\n\t\t\tfor (int jj = 0; jj < m; jj++)\r\n\t\t\t{\r\n\t\t\t\tdelta += ab[ii][jj]* pow(-1, jj);\r\n\t\t\t}\r\n\t\t}\r\n\t\t// Adding the jump for the z2 elements\r\n\t\tif (pos_z2[ii] == 1)\r\n\t\t{\r\n\t\t\tfor (int jj = 0; jj < m; jj++)\r\n\t\t\t{\r\n\t\t\t\tdelta -= ab[ii][jj];\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t}\r\n\r\n\treturn delta;\r\n}\r\n/* --------------------------------------------------------------------\r\n\t\tTAU UNIFORM STRESS\r\n-----------------------------------------------------------------------*/\r\ninline std::tuple<dcomp, dcomp>  tau_uni(double sigma_11inf)\r\n{\r\n\t// Defining the variables\r\n\tdcomp tau_11, tau_12, phi, psi;\r\n\r\n\t// Get the phi and psi\r\n\tphi = -0.5 * sigma_11inf;\r\n\tpsi = -0.5 * sigma_11inf;\r\n\r\n\t// calculating the tau\r\n\ttau_11 = -phi - psi;\r\n\ttau_12 = -phi - phi;\r\n\r\n\treturn { tau_11, tau_12 };\r\n}\r\n/* --------------------------------------------------------------------\r\n\t\tTAU CRACK\r\n-----------------------------------------------------------------------*/\r\ninline std::tuple<dcomp, dcomp> tau_crack(dcomp z, dcomp z1, dcomp z2, double L, double mu, int m, dcvec a)\r\n{\r\n\t// Defining the variables\r\n\tdcomp chi, chi_bar, Z, chi_pow;\r\n\tdcomp dphi, dphi_bar, ddphi, dpsi;\r\n\tdcomp tau_11, tau_12, S1, L_frac;\r\n\r\n\t// Getting the chi - and Z - coordinates\r\n\tchi = chi_from_z(z, z1, z2, L, mu);\r\n\tchi_bar = conj(chi);\r\n\tZ = exp(dcomp(0, -1) * mu) * 2.0 * (z - 0.5 * (z1 + z2)) / L;\r\n\r\n\t// Calculating the series\r\n\tdphi = 0;\r\n\tdphi_bar = 0;\r\n\tddphi = 0;\r\n\tdpsi = 0;\r\n\tchi_pow = chi * chi - 1.0;\r\n\tfor (int ii = 0; ii < m; ii++)\r\n\t{\r\n\t\tdouble n = ii + 1.0;\r\n\t\tdcomp beta_n = a[ii] * n;\r\n\t\tdcomp chipow = pow(chi, (1.0 - n)) / chi_pow;\r\n\t\tdphi += conj(beta_n) * chipow;\r\n\t\tdphi_bar += beta_n * conj(chipow);\r\n\t\tddphi -= conj(beta_n) * (pow(chi, (2.0 - n)) / (chi_pow * chi_pow * chi_pow)) * ((n + 1.0) * chi * chi - n + 1.0);\r\n\t\tdpsi -= beta_n * chipow;\r\n\t}\r\n\r\n\t// Multiplying the constants\r\n\tL_frac = (4.0 / L) * exp(dcomp(0, -1) * mu);\r\n\tdphi *= L_frac;\r\n\tdphi_bar *= conj(L_frac);\r\n\tddphi *= (16.0 / (L * L)) * exp(dcomp(0, -2) * mu);\r\n\tdpsi *= L_frac;\r\n\r\n\t// Calcualting tau\r\n\ttau_11 = -0.5 * L * (Z - conj(Z)) * ddphi - exp(dcomp(0, -1) * mu) * (dphi + dpsi);\r\n\ttau_12 = -exp(dcomp(0, 1) * mu) * dphi - exp(dcomp(0, -1) * mu) * dphi_bar;\r\n\r\n\treturn { tau_11, tau_12 };\r\n}\r\n/* --------------------------------------------------------------------\r\n\t\tTAU TOTAL\r\n-----------------------------------------------------------------------*/\r\ninline std::tuple<dcomp, dcomp>  tau_total(dcomp z, double sigma_11inf, dcvec z1, dcvec z2, dvec L, dvec mu, int ma, int na, ddcvec a, int m_not_a)\r\n{\r\n\t// Defining the variables\r\n\tdcomp tau_11, tau_12;\r\n\r\n\t// Add the unifrom stress field\r\n\tstd::tie(tau_11, tau_12) = tau_uni(sigma_11inf);\r\n\r\n\t// Add the analytic element for a crack\r\n\tif (na > 0)\r\n\t{\r\n\t\tfor (int ii = 0; ii < na; ii++)\r\n\t\t{\r\n\t\t\tif (ii != m_not_a)\r\n\t\t\t{\r\n\t\t\t\tdcomp tau_11c, tau_12c;\r\n\t\t\t\tstd::tie(tau_11c, tau_12c) = tau_crack(z, z1[ii], z2[ii], L[ii], mu[ii], ma, a[ii]);\r\n\t\t\t\ttau_11 += tau_11c;\r\n\t\t\t\ttau_12 += tau_12c;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\treturn { tau_11, tau_12 };\r\n}\r\n/* --------------------------------------------------------------------\r\n\t\tT TOTAL\r\n-----------------------------------------------------------------------*/\r\ninline dcomp T_total(dcomp z, double sigma_11inf, dcvec z1a, dcvec z2a, dvec La, dvec mua, int ma, int na, ddcvec a, int m_not_a, int m_is_a)\r\n{\r\n\t// Defining the variables\r\n\tdcomp tau_11, tau_12, T;\r\n\r\n\t// Get teh taus\r\n\tstd::tie(tau_11, tau_12) = tau_total(z, sigma_11inf, z1a, z2a, La, mua, ma, na, a, m_not_a);\r\n\r\n\t// Calculate the tractions\r\n\tT = dcomp(0, -.5) * (tau_11 * exp(dcomp(0, 2) * mua[m_is_a]) - tau_12);\r\n\r\n\treturn { T };\r\n}\r\n/* --------------------------------------------------------------------\r\n\t\tSOLVE CRACK ANALYTIC ELEMENT A (BETA IN PAPER)\r\n-----------------------------------------------------------------------*/\r\ninline dcvec AE_crack_solver(Eigen::VectorXd T_s, Eigen::VectorXd T_n, Eigen::MatrixXd A, int ma, int Na, dvec pa, double sigma_11inf, dcvec z1a, dcvec z2a, dvec La, dvec mua, int na, ddcvec a_in, dcvec zint, ivec int_check, int m_is_a)\r\n{\r\n\t// Defining the variables\r\n\tdcvec a(ma);\r\n\tEigen::VectorXd b1(ma);\r\n\tEigen::VectorXd b2(ma);\r\n\r\n\t// Count number of intersections\r\n\tint int_count = std::accumulate(int_check.begin(), int_check.end(), 0.0);\r\n\r\n\t// Check if the crack has any intersection\r\n\tif (int_count == 0)\r\n\t{\r\n\t\t// Solving the linear system (without intersections)\r\n\t\tb1 = A.bdcSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(T_s);\r\n\t\tb2 = A.bdcSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(T_n);\r\n\t}\r\n\telse\r\n\t{\r\n\t\t// Define new matrices for A and T and assign the pre-calculated values\r\n\t\tEigen::MatrixXd A_int_s(Na + int_count * 3, ma);\r\n\t\tEigen::MatrixXd A_int_n(Na + int_count, ma);\r\n\t\tEigen::VectorXd T_s_int(Na + int_count * 3);\r\n\t\tEigen::VectorXd T_n_int(Na + int_count);\r\n\t\t#pragma omp parallel for default(none) shared(A_int_s, A_int_n, A, T_n_int, T_n, T_s_int, T_s)\r\n\t\tfor (int ii = 0; ii < Na; ii++)\r\n\t\t{\r\n\t\t\tfor (int jj = 0; jj < ma; jj++)\r\n\t\t\t{\r\n\t\t\t\t/*A_int_re(ii, jj) = A(ii, jj);\r\n\t\t\t\tA_int_im(ii, jj) = A(ii, jj);*/\r\n\t\t\t\tA_int_s(ii, jj) = A(ii, jj);\r\n\t\t\t\tA_int_n(ii, jj) = A(ii, jj);\r\n\t\t\t}\r\n\t\t\tT_s_int(ii) = T_s(ii);\r\n\t\t\tT_n_int(ii) = T_n(ii);\r\n\t\t}\r\n\t\tint cnt_s = 0;\r\n\t\tint cnt_n = 0;\r\n\t\tfor (int ii = 0; ii < na; ii++)\r\n\t\t{\r\n\t\t\t// Check if element ii has any intersections\r\n\t\t\tif (int_check[ii] == 1)\r\n\t\t\t{\r\n\t\t\t\t// Define variables\r\n\t\t\t\tdcomp chia, tau11, chi_pow, L_frac, T_temp;\r\n\t\t\t\tdouble thetaa;\r\n\r\n\t\t\t\t// Compute the intersection angel in the chi-plane\r\n\t\t\t\tchia = chi_from_z(zint[ii], z1a[m_is_a], z2a[m_is_a], La[m_is_a], mua[m_is_a]);\r\n\t\t\t\tthetaa = imag(log(chia));\r\n\r\n\t\t\t\t// Pre-calcualte terms\r\n\t\t\t\tchi_pow = chia /( chia * chia - 1.0 );\r\n\t\t\t\tL_frac = (dcomp(0,8.0) / La[m_is_a]) * exp(dcomp(0, -2) * mua[m_is_a]);\r\n\r\n\t\t\t\t// Add the intersection to the A matrix\r\n\t\t\t\tfor (int jj = 0; jj < ma; jj++)\r\n\t\t\t\t{\r\n\t\t\t\t\tdouble n = jj + 1.0;\r\n\t\t\t\t\t// Add a control point at the intersection - tau^11 condition\r\n\t\t\t\t\tA_int_s(Na + cnt_s, jj) = real( chi_pow * L_frac * n * pow(chia, -n) );\r\n\t\t\t\t\tA_int_s(Na + (cnt_s + 1), jj) = imag( chi_pow * L_frac * n * pow(chia, -n) );\r\n\t\t\t\t\t\r\n\t\t\t\t\t// Add a control point at the intersection - traction condition\r\n\t\t\t\t\tA_int_s(Na + (cnt_s + 2), jj) = n * sin(n * thetaa);\r\n\t\t\t\t\tA_int_n(Na + cnt_n, jj) = n * sin(n * thetaa);\r\n\t\t\t\t}\r\n\r\n\t\t\t\t// Calculate the taus at the intersection\r\n\t\t\t\tdcomp tau_11, tau_12;\r\n\t\t\t\tstd::tie(tau_11, tau_12) = tau_total(zint[ii], sigma_11inf, z1a, z2a, La, mua, ma, na, a_in, m_is_a);\r\n\r\n\t\t\t\t// Add the intersection to the T_s vector\r\n\t\t\t\tT_s_int(Na + cnt_s) = -real(tau_11);\r\n\t\t\t\tT_s_int(Na + (cnt_s + 1)) = -imag(tau_11);\r\n\r\n\t\t\t\t// Calculate the traction at the control point at the intersection\r\n\t\t\t\tT_temp = T_total(zint[ii], sigma_11inf, z1a, z2a, La, mua, ma, na, a_in, m_is_a, m_is_a);\r\n\r\n\t\t\t\t// Add the intersection to the T vectors\r\n\t\t\t\tT_s_int(Na + (cnt_s + 2)) = real(T_temp) * 0.5 * La[m_is_a] * sin(thetaa);\r\n\t\t\t\tT_n_int(Na + cnt_n) = (pa[ii] + imag(T_temp)) * -0.5 * La[m_is_a] * sin(thetaa);\r\n\r\n\t\t\t\t// Add step to loop count\r\n\t\t\t\tcnt_s += 3;\r\n\t\t\t\tcnt_n += 1;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t}\r\n\r\n\t\t// Solving the linear system (with intersections)\r\n\t\tb1 = A_int_s.bdcSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(T_s_int);\r\n\t\tb2 = A_int_n.bdcSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(T_n_int);\r\n\t}\r\n\t// Assign to a\r\n\tfor (int ii = 0; ii < ma; ii++)\r\n\t{\r\n\t\ta[ii] = dcomp(b2[ii], b1[ii]);\r\n\t}\r\n\r\n\r\n\treturn { a };\r\n}\r\n/* --------------------------------------------------------------------\r\n\t\tITERATOR\r\n-----------------------------------------------------------------------*/\r\ninline ddcvec iterator(double cond, int ITR, int Na, dvec pa, double sigma_11inf, dcvec z1a, dcvec z2a, dvec La, dvec mua, int ma, int na)\r\n{\r\n\t// Defining the variables\r\n\tdcomp tau_11, tau_12, T;\r\n\tEigen::MatrixXd A(Na, ma);\r\n\tdvec theta_a(Na);\r\n\tddvec term(na, dvec(Na));\r\n\tddcvec za(na, dcvec(Na));\r\n\tddcvec a(na, dcvec(ma));\r\n\tddcvec zint(na, dcvec(na));\r\n\tiivec int_check(na, ivec(na));\r\n\tivec int_count(na);\r\n\tdouble theta_0a, delthetaa;\r\n\r\n\t// Print the conditions\r\n\tstd::cout << std::scientific;\r\n\tstd::cout << \"Solver for \" << na << \" analytical element cracks with \" << ma << \" coefficients at \" << Na << \" integration points.\" << std::endl;\r\n\tstd::cout << \"Iterations break after: error < \" << cond << \" or iterations > \" << ITR << \".\" << std::endl << std::endl;\r\n\tstd::cout << \"\tError:\" << \"\t\tIteration:\" << std::endl;\r\n\r\n\r\n\t// Assigning variables\r\n\ttheta_0a = pi() / (Na);\r\n\tdelthetaa = (pi() - 2.5*theta_0a) / (Na - 1.0);\r\n\r\n\tif (na > 0)\r\n\t{\r\n\t\t// Find the intersection points\r\n\t\t#pragma omp parallel for default(none) shared(zint, int_check, int_count, z1a, z2a)\r\n\t\tfor (int ii = 0; ii < na; ii++)\r\n\t\t{\r\n\t\t\tfor (int jj = 0; jj < na; jj++)\r\n\t\t\t{\r\n\t\t\t\tstd::tie(zint[ii][jj], int_check[ii][jj]) = intersection_point(z1a[ii], z2a[ii], z1a[jj], z2a[jj]);\r\n\t\t\t}\r\n\t\t\tint_count[ii] = std::accumulate(int_check[ii].begin(), int_check[ii].end(), 0.0);\r\n\t\t}\r\n\r\n\t\t// Calculating the A, a theta and term matrices\r\n\t\t#pragma omp parallel for default(none) shared(theta_a, theta_0a, delthetaa)\r\n\t\tfor (int ii = 0; ii < Na; ii++)\r\n\t\t{\r\n\t\t\ttheta_a[ii] = theta_0a + ii * delthetaa;\r\n\t\t}\r\n\r\n\t\t//#pragma omp parallel for default(none) shared(A, za, term, z1a, z2a, La, mua, theta_a)\r\n\t\tfor (int ii = 0; ii < Na; ii++)\r\n\t\t{\r\n\t\t\tfor (int mm = 0; mm < ma; mm++)\r\n\t\t\t{\r\n\t\t\t\tA(ii, mm) = (mm + 1.0) * sin((mm + 1.0) * theta_a[ii]);\r\n\t\t\t}\r\n\t\t\tfor (int jj = 0; jj < na; jj++)\r\n\t\t\t{\r\n\t\t\t\tdcomp chi;\r\n\t\t\t\tchi = exp(dcomp(0, 1) * theta_a[ii]);\r\n\t\t\t\tza[jj][ii] = z_from_chi(chi, z1a[jj], z2a[jj], La[jj], mua[jj]);\r\n\t\t\t\tterm[jj][ii] = -0.5 * La[jj] * sin(theta_a[ii]);\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t}\r\n\r\n\t// Sovle the a (betas in paper)\r\n\tdouble error = 1;\r\n\tddcvec a_old(na, dcvec(ma, 0));\r\n\tdouble error_a;\r\n\tint NIT = 0;\r\n\twhile ( error > cond && NIT < ITR )\r\n\t{\r\n\t\t\t\tfor (int ii = 0; ii < na; ii++)\r\n\t\t\t\t{\r\n\t\t\t\t\tEigen::VectorXd T_s(Na);\r\n\t\t\t\t\tEigen::VectorXd T_n(Na);\r\n\t\t\t\t\t#pragma omp parallel for default(none) shared(T_s, T_n, za, sigma_11inf, z1a, z2a, La, mua, ma, na, a)\r\n\t\t\t\t\tfor (int jj = 0; jj < Na; jj++)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tdcomp T;\r\n\t\t\t\t\t\tT = T_total(za[ii][jj], sigma_11inf, z1a, z2a, La, mua, ma, na, a, ii, ii);\r\n\t\t\t\t\t\tT_s(jj) = -real(T) * term[ii][jj];\r\n\t\t\t\t\t\tT_n(jj) = (pa[ii] + imag(T)) * term[ii][jj];\r\n\t\t\t\t\t}\r\n\t\t\t\t\tdcomp tau_11, tau_12;\r\n\t\t\t\t\ta[ii] = AE_crack_solver(T_s, T_n, A, ma, Na, pa, sigma_11inf, z1a, z2a, La, mua, na, a, zint[ii], int_check[ii], ii);\r\n\t\t\t\t\tstd::tie(tau_11, tau_12) = tau_total(zint[0][1], sigma_11inf, z1a, z2a, La, mua, ma, na, a, -1);\r\n\t\t\t\t}\r\n\r\n\t\t// Calcualte the error\r\n\t\terror_a = 0;\r\n\t\tif (na > 0)\r\n\t\t{\r\n\t\t\tdvec dela(na);\r\n\t\t\t#pragma omp parallel for default(none) shared(dela, a, error_a)\r\n\t\t\tfor (int ii = 0; ii < na; ii++)\r\n\t\t\t{\r\n\t\t\t\tdvec dela_temp(ma);\r\n\t\t\t\tfor (int jj = 0; jj < ma; jj++)\r\n\t\t\t\t{\r\n\t\t\t\t\tdela_temp[jj] = abs(a[ii][jj] - a_old[ii][jj]);\r\n\t\t\t\t}\r\n\t\t\t\tdela[ii] = *max_element(dela_temp.begin(), dela_temp.end());\r\n\t\t\t}\r\n\t\t\terror_a = *max_element(dela.begin(), dela.end());\r\n\t\t}\r\n\t\tdvec error_vec{ error_a };\r\n\t\terror = *max_element(error_vec.begin(), error_vec.end());\r\n\r\n\t\tNIT += 1;\r\n\t\ta_old = a;\r\n\r\n\t\tstd::cout << std::scientific;\r\n\t\tstd::cout << \"\t\" << error << \"\t\" << NIT << std::endl;\r\n\r\n\t}\r\n\r\n\treturn { a };\r\n}\r\n/* --------------------------------------------------------------------\r\n\t\tSTRESS TOTAL\r\n-----------------------------------------------------------------------*/\r\ninline std::tuple<double, double, double> sigma_total(dcomp z, double sigma_11inf, dcvec z1a, dcvec z2a, dvec La, dvec mua, int ma, int na, ddcvec a)\r\n{\r\n\t// Defining the variables\r\n\tdcomp S1, S2, tau_11, tau_12;\r\n\tdouble sigma_11, sigma_22, sigma_12;\r\n\r\n\t// Calculating the tau\r\n\tstd::tie(tau_11, tau_12) = tau_total(z, sigma_11inf, z1a, z2a, La, mua, ma, na, a, -1);\r\n\r\n\t// Calculate the sigmas\r\n\tS1 = .5 * (tau_11 + tau_12);\r\n\tS2 = .5 * (-tau_11 + tau_12);\r\n\tsigma_11 = real(S1);\r\n\tsigma_22 = real(S2);\r\n\tsigma_12 = -imag(S1);\r\n\r\n\treturn { sigma_11, sigma_22, sigma_12 };\r\n}\r\n/* --------------------------------------------------------------------\r\n\t\tSTRESS FIELD\r\n-----------------------------------------------------------------------*/\r\nstd::tuple<dvec, dvec, ddvec, ddvec, ddvec> stress_field(double xfrom, double xto, double yfrom, double yto, int Nx, int Ny, double sigma_11inf, dcvec z1a, dcvec z2a, dvec La, dvec mua, int ma, int na, ddcvec a)\r\n{\r\n\t// Defining the variables\r\n\tddvec grid_11(Nx, dvec(Ny));\r\n\tddvec grid_22(Nx, dvec(Ny));\r\n\tddvec grid_12(Nx, dvec(Ny));\r\n\tdouble dx;\r\n\tdouble dy;\r\n\tdvec x_vec(Nx);\r\n\tdvec y_vec(Ny);\r\n\r\n\t// Calcualte the sigma grids\r\n\tdx = (xto - xfrom) / (Nx - 1.0);\r\n\tdy = (yto - yfrom) / (Ny - 1.0);\r\n\t#pragma omp parallel for default(none) shared(grid_11, grid_22, grid_12, x_vec, y_vec, sigma_11inf, z1a, z2a, La, mua, ma, na, a)\r\n\tfor (int ii = 0; ii < Nx; ii++)\r\n\t{\r\n\t\tfor (int jj = Ny; jj--;)\r\n\t\t{\r\n\t\t\tx_vec[ii] = xfrom + ii * dx;\r\n\t\t\ty_vec[jj] = yfrom + jj * dy;\r\n\t\t\tstd::tie(grid_11[ii][jj], grid_22[ii][jj], grid_12[ii][jj]) = sigma_total(dcomp(x_vec[ii], y_vec[jj]), sigma_11inf, z1a, z2a, La, mua, ma, na, a);\r\n\t\t}\r\n\t}\r\n\treturn { x_vec, y_vec, grid_11, grid_22, grid_12 };\r\n}\r\n/* --------------------------------------------------------------------\r\n\t\tPRINCIPAL STRESSES\r\n-----------------------------------------------------------------------*/\r\nstd::tuple<double, double, double> principal_sigma(dcomp z, double sigma_11inf, dcvec z1a, dcvec z2a, dvec La, dvec mua, int ma, int na, ddcvec a)\r\n{\r\n\t// Defining the variables\r\n\tdouble sigma_1;\r\n\tdouble sigma_2;\r\n\tdouble theta_p;\r\n\tdouble frac1, frac2, sqrt1;\r\n\tdcomp S1, S2, tau_11, tau_12;\r\n\tdouble sigma_11, sigma_22, sigma_12;\r\n\r\n\t// Calculating the tau\r\n\tstd::tie(tau_11, tau_12) = tau_total(z, sigma_11inf, z1a, z2a, La, mua, ma, na, a, -1);\r\n\r\n\t// Calculate the sigmas\r\n\tS1 = .5 * (tau_11 + tau_12);\r\n\tS2 = .5 * (-tau_11 + tau_12);\r\n\tsigma_11 = real(S1);\r\n\tsigma_22 = real(S2);\r\n\tsigma_12 = -imag(S1);\r\n\r\n\t// Calculating the terms\r\n\tfrac1 = (sigma_11 + sigma_22) / 2.0;\r\n\tfrac2 = (sigma_11 - sigma_22) / 2.0;\r\n\tsqrt1 = sqrt(frac2 * frac2 + sigma_12 * sigma_12);\r\n\r\n\t// Calculating the principal stresses and the angel of sigma\r\n\tsigma_1 = frac1 + sqrt1;\r\n\tsigma_2 = frac1 - sqrt1;\r\n\r\n\t// Calcuating the angel theta_p\r\n\ttheta_p = -0.5 * imag(log(tau_11));\r\n\r\n\t// Changing the absolut sigma is sigma_2 > sigma_1 (TURNED OFF)\r\n\t/*if (abs(sigma_2) > abs(sigma_1))\r\n\t{\r\n\t\tsigma_1 = frac1 - sqrt1;\r\n\t\tsigma_2 = frac1 + sqrt1;\r\n\t\ttheta_p = -0.5*imag(log(tau_11)) + pi() / 2;\r\n\t}\r\n\t*/\r\n\r\n\r\n\r\n\treturn { sigma_1, sigma_2, theta_p };\r\n}\r\n/* --------------------------------------------------------------------\r\n\t\tPRINCIPAL STRESSES PLOT\r\n-----------------------------------------------------------------------*/\r\nstd::tuple<double, double, double> principal_sigma_plt(double sigma_11, double sigma_22, double sigma_12)\r\n{\r\n\t// Defining the variables\r\n\tdouble sigma_1;\r\n\tdouble sigma_2;\r\n\tdouble theta_p;\r\n\tdouble frac1, frac2, sqrt1;\r\n\tdcomp tau_11;\r\n\r\n\t// Calculating the tau\r\n\ttau_11 = sigma_11 - sigma_22 - dcomp(0, 2) * sigma_12;\r\n\r\n\t// Calculating the terms\r\n\tfrac1 = (sigma_11 + sigma_22) / 2.0;\r\n\tfrac2 = (sigma_11 - sigma_22) / 2.0;\r\n\tsqrt1 = sqrt(frac2 * frac2 + sigma_12 * sigma_12);\r\n\r\n\t// Calculating the principal stresses and the angel of sigma\r\n\tsigma_1 = frac1 + sqrt1;\r\n\tsigma_2 = frac1 - sqrt1;\r\n\r\n\t// Calcuating the angel theta_p\r\n\ttheta_p = -0.5 * imag(log(tau_11));\r\n\r\n\t// Changing the absolut sigma is sigma_2 > sigma_1 (TURNED OFF)\r\n\t/*if (abs(sigma_2) > abs(sigma_1))\r\n\t{\r\n\t\tsigma_1 = frac1 - sqrt1;\r\n\t\tsigma_2 = frac1 + sqrt1;\r\n\t\ttheta_p = -0.5*imag(log(tau_11)) + pi() / 2;\r\n\t}\r\n\t*/\r\n\r\n\r\n\r\n\treturn { sigma_1, sigma_2, theta_p };\r\n}\r\n/* --------------------------------------------------------------------\r\n\t\tPRINCIPAL STRESS FIELDS\r\n-----------------------------------------------------------------------*/\r\nstd::tuple<ddvec, ddvec, ddvec> principal_stress_field(int Nx, int Ny, ddvec grid_11, ddvec grid_22, ddvec grid_12)\r\n{\r\n\t// Defining the variables\r\n\tddvec grid_1(Nx, dvec(Ny));\r\n\tddvec grid_2(Nx, dvec(Ny));\r\n\tddvec grid_tp(Nx, dvec(Ny));\r\n\r\n\t// Calculate teh principal stresses from the stress feilds\r\n\t#pragma omp parallel for default(none) shared(grid_1, grid_2, grid_tp, grid_11, grid_22, grid_12)\r\n\tfor (int ii = 0; ii < Nx; ii++)\r\n\t{\r\n\t\tfor (int jj = Ny; jj--;)\r\n\t\t{\r\n\t\t\tstd::tie(grid_1[ii][jj], grid_2[ii][jj], grid_tp[ii][jj]) = principal_sigma_plt(grid_11[ii][jj], grid_22[ii][jj], grid_12[ii][jj]);\r\n\t\t}\r\n\t}\r\n\treturn { grid_1, grid_2, grid_tp };\r\n}\r\n/* --------------------------------------------------------------------\r\n\t\tPRINCIPAL STRESS TRAJECTORIES\r\n-----------------------------------------------------------------------*/\r\nstd::tuple<ddcvec, ddcvec> principal_stress_trajectories(double xfrom, double xto, double yfrom, double yto, dcvec xtraj, dcvec ytraj, int Ntraj, int lvs_traj, double sigma_11inf, dcvec z1a, dcvec z2a, dvec La, dvec mua, int ma, int na, ddcvec a)\r\n{\r\n\t// Defining the variables\r\n\tddcvec traj_1(lvs_traj * 2, dcvec(Ntraj));\r\n\tddcvec traj_2(lvs_traj * 2, dcvec(Ntraj));\r\n\tdouble dx, dy, dx_lvsre, dx_lvsim, dy_lvsre, dy_lvsim, pi_val;\r\n\tdouble cond;\r\n\tint NIT;\r\n\r\n\t// Getting the starting points\r\n\tdx = (xto - xfrom) / (Ntraj * 0.8);\r\n\tdy = (yto - yfrom) / (Ntraj * 0.8);\r\n\tdx_lvsre = (real(xtraj[1]) - real(xtraj[0])) / (lvs_traj - 1.0);\r\n\tdx_lvsim = (imag(xtraj[1]) - imag(xtraj[0])) / (lvs_traj - 1.0);\r\n\tdy_lvsre = (real(ytraj[1]) - real(ytraj[0])) / (lvs_traj - 1.0);\r\n\tdy_lvsim = (imag(ytraj[1]) - imag(ytraj[0])) / (lvs_traj - 1.0);\r\n\tpi_val = 0.5 * pi();\r\n\tcond = 1e-6;\r\n\tNIT = 10;\r\n\r\n\t// SIGMA 1\r\n\t#pragma omp parallel for default(none) shared(traj_1, sigma_11inf, z1a, z2a, La, mua, ma, na, a)\r\n\tfor (int ii = 0; ii < lvs_traj; ii++)\r\n\t{\r\n\t\ttraj_1[ii][0] = dcomp(real(xtraj[0]) + ii * dx_lvsre, imag(xtraj[0]) + ii * dx_lvsim);\r\n\t\tdcomp z = traj_1[ii][0];\r\n\t\tdcomp z_old = z;\r\n\t\tdouble dx1 = dx;\r\n\t\tfor (int jj = 1; jj < Ntraj; jj++)\r\n\t\t{\r\n\t\t\tdcomp zt, z11, z_oldt, sigma, sigmat;\r\n\t\t\tdouble sigma_1, theta_p;\r\n\t\t\tdouble ee, eta;\r\n\t\t\tstd::tie(sigma_1, std::ignore, theta_p) = principal_sigma(z, sigma_11inf, z1a, z2a, La, mua, ma, na, a);\r\n\t\t\tsigma = abs(sigma_1) * exp(dcomp(0, 1) * theta_p);\r\n\t\t\tz11 = z + sigma / abs(sigma) * dx1;\r\n\t\t\teta = angel_change(z11, z, z_old);\r\n\t\t\tif (eta > pi_val && jj > 1) {\r\n\t\t\t\tdx1 = -dx1;\r\n\t\t\t}\r\n\t\t\tzt = z + sigma / abs(sigma) * dx1;\r\n\r\n\t\t\tee = 1;\r\n\t\t\tfor (int rr = NIT; rr--;)\r\n\t\t\t{\r\n\t\t\t\tz_oldt = zt;\r\n\t\t\t\tstd::tie(sigma_1, std::ignore, theta_p) = principal_sigma(zt, sigma_11inf, z1a, z2a, La, mua, ma, na, a);\r\n\t\t\t\tsigmat = abs(sigma_1) * exp(dcomp(0, 1) * theta_p);\r\n\t\t\t\tz11 = z + (sigma + sigmat) / abs(sigma + sigmat) * dx1;\r\n\t\t\t\teta = angel_change(z11, z, z_old);\r\n\t\t\t\tif (eta > pi_val && jj > 1) {\r\n\t\t\t\t\tdx1 = -dx1;\r\n\t\t\t\t}\r\n\t\t\t\tzt = z + (sigma + sigmat) / abs(sigma + sigmat) * dx1;\r\n\t\t\t\tee = std::norm(z_oldt - zt);\r\n\t\t\t\tif (ee < cond)\r\n\t\t\t\t{\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\ttraj_1[ii][jj] = zt;\r\n\t\t\tz_old = z;\r\n\t\t\tz = zt;\r\n\t\t}\r\n\r\n\t\tint kk = ii + lvs_traj;\r\n\t\ttraj_1[kk][0] = traj_1[ii][0];\r\n\t\tz = traj_1[kk][0];\r\n\t\tz_old = z;\r\n\t\tdx1 = -dx;\r\n\t\tfor (int jj = 1; jj < Ntraj; jj++)\r\n\t\t{\r\n\t\t\tdcomp zt, z11, z_oldt, sigma, sigmat;\r\n\t\t\tdouble sigma_1, theta_p;\r\n\t\t\tdouble ee, eta;\r\n\t\t\tstd::tie(sigma_1, std::ignore, theta_p) = principal_sigma(z, sigma_11inf, z1a, z2a, La, mua, ma, na, a);\r\n\t\t\tsigma = abs(sigma_1) * exp(dcomp(0, 1) * theta_p);\r\n\t\t\tz11 = z + sigma / abs(sigma) * dx1;\r\n\t\t\teta = angel_change(z11, z, z_old);\r\n\t\t\tif (eta > pi_val && jj > 1) {\r\n\t\t\t\tdx1 = -dx1;\r\n\t\t\t}\r\n\t\t\tzt = z + sigma / abs(sigma) * dx1;\r\n\r\n\t\t\tee = 1;\r\n\t\t\tfor (int rr = NIT; rr--;)\r\n\t\t\t{\r\n\t\t\t\tz_oldt = zt;\r\n\t\t\t\tstd::tie(sigma_1, std::ignore, theta_p) = principal_sigma(zt, sigma_11inf, z1a, z2a, La, mua, ma, na, a);\r\n\t\t\t\tsigmat = abs(sigma_1) * exp(dcomp(0, 1) * theta_p);\r\n\t\t\t\tz11 = z + (sigma + sigmat) / abs(sigma + sigmat) * dx1;\r\n\t\t\t\teta = angel_change(z11, z, z_old);\r\n\t\t\t\tif (eta > pi_val && jj > 1) {\r\n\t\t\t\t\tdx1 = -dx1;\r\n\t\t\t\t}\r\n\t\t\t\tzt = z + (sigma + sigmat) / abs(sigma + sigmat) * dx1;\r\n\t\t\t\tee = std::norm(z_oldt - zt);\r\n\t\t\t\tif (ee < cond)\r\n\t\t\t\t{\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\ttraj_1[kk][jj] = zt;\r\n\t\t\tz_old = z;\r\n\t\t\tz = zt;\r\n\t\t}\r\n\t}\r\n\r\n\t// SIGMA 2\r\n\t#pragma omp parallel for default(none) shared(traj_2, sigma_11inf, z1a, z2a, La, mua, ma, na, a)\r\n\tfor (int ii = 0; ii < lvs_traj; ii++)\r\n\t{\r\n\t\ttraj_2[ii][0] = dcomp(real(ytraj[0]) + ii * dy_lvsre, imag(ytraj[0]) + ii * dy_lvsim);\r\n\t\tdouble dy1 = dy;\r\n\t\tdcomp z = traj_2[ii][0];\r\n\t\tdcomp z_old = z;\r\n\t\tfor (int jj = 1; jj < Ntraj; jj++)\r\n\t\t{\r\n\t\t\tdcomp zt, z11, z_oldt, sigma, sigmat;\r\n\t\t\tdouble sigma_2, theta_p;\r\n\t\t\tdouble ee, eta;\r\n\t\t\tstd::tie(std::ignore, sigma_2, theta_p) = principal_sigma(z, sigma_11inf, z1a, z2a, La, mua, ma, na, a);\r\n\t\t\tsigma = abs(sigma_2) * exp(dcomp(0, 1) * (theta_p + pi_val));\r\n\t\t\tz11 = z + sigma / abs(sigma) * dy1;\r\n\t\t\teta = angel_change(z11, z, z_old);\r\n\t\t\tif (eta > pi_val && jj > 1) {\r\n\t\t\t\tdy1 = -dy1;\r\n\t\t\t}\r\n\t\t\tzt = z + sigma / abs(sigma) * dy1;\r\n\r\n\t\t\tee = 1;\r\n\t\t\tfor (int rr = NIT; rr--;)\r\n\t\t\t{\r\n\t\t\t\tz_oldt = zt;\r\n\t\t\t\tstd::tie(std::ignore, sigma_2, theta_p) = principal_sigma(zt, sigma_11inf, z1a, z2a, La, mua, ma, na, a);\r\n\t\t\t\tsigmat = abs(sigma_2) * exp(dcomp(0, 1) * (theta_p + pi_val));\r\n\t\t\t\tz11 = z + (sigma + sigmat) / abs(sigma + sigmat) * dy1;\r\n\t\t\t\teta = angel_change(z11, z, z_old);\r\n\t\t\t\tif (eta > pi_val && jj > 1) {\r\n\t\t\t\t\tdy1 = -dy1;\r\n\t\t\t\t}\r\n\t\t\t\tzt = z + (sigma + sigmat) / abs(sigma + sigmat) * dy1;\r\n\t\t\t\tee = std::norm(z_oldt - zt);\r\n\t\t\t\tif (ee < cond)\r\n\t\t\t\t{\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\ttraj_2[ii][jj] = zt;\r\n\t\t\tz_old = traj_2[ii][(int)(jj - 1)];\r\n\t\t\tz = zt;\r\n\t\t}\r\n\r\n\t\tint kk = ii + lvs_traj;\r\n\t\ttraj_2[kk][0] = traj_2[ii][0];\r\n\t\tdy1 = -dy;\r\n\t\tz = traj_2[kk][0];\r\n\t\tz_old = z;\r\n\t\tfor (int jj = 1; jj < Ntraj; jj++)\r\n\t\t{\r\n\t\t\tdcomp zt, z11, z_oldt, sigma, sigmat;\r\n\t\t\tdouble sigma_2, theta_p;\r\n\t\t\tdouble ee, eta;\r\n\t\t\tstd::tie(std::ignore, sigma_2, theta_p) = principal_sigma(z, sigma_11inf, z1a, z2a, La, mua, ma, na, a);\r\n\t\t\tsigma = abs(sigma_2) * exp(dcomp(0, 1) * (theta_p + pi_val));\r\n\t\t\tz11 = z + sigma / abs(sigma) * dy1;\r\n\t\t\teta = angel_change(z11, z, z_old);\r\n\t\t\tif (eta > pi_val && jj > 1) {\r\n\t\t\t\tdy1 = -dy1;\r\n\t\t\t}\r\n\t\t\tzt = z + sigma / abs(sigma) * dy1;\r\n\r\n\t\t\tee = 1;\r\n\t\t\tfor (int rr = NIT; rr--;)\r\n\t\t\t{\r\n\t\t\t\tz_oldt = zt;\r\n\t\t\t\tstd::tie(std::ignore, sigma_2, theta_p) = principal_sigma(zt, sigma_11inf, z1a, z2a, La, mua, ma, na, a);\r\n\t\t\t\tsigmat = abs(sigma_2) * exp(dcomp(0, 1) * (theta_p + pi_val));\r\n\t\t\t\tz11 = z + (sigma + sigmat) / abs(sigma) * dy1;\r\n\t\t\t\teta = angel_change(z11, z, z_old);\r\n\t\t\t\tif (eta > pi_val && jj > 1) {\r\n\t\t\t\t\tdy1 = -dy1;\r\n\t\t\t\t}\r\n\t\t\t\tzt = z + (sigma + sigmat) / abs(sigma + sigmat) * dy1;\r\n\t\t\t\tee = std::norm(z_oldt - zt);\r\n\t\t\t\tif (ee < cond)\r\n\t\t\t\t{\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\ttraj_2[kk][jj] = zt;\r\n\t\t\tz_old = z;\r\n\t\t\tz = zt;\r\n\t\t}\r\n\t}\r\n\treturn { traj_1, traj_2 };\r\n}\r\n/* --------------------------------------------------------------------\r\n\t\tW UNIFORM STRESS\r\n-----------------------------------------------------------------------*/\r\ninline dcomp  w_uni(dcomp z, double kappa, double G, double sigma_11inf)\r\n{\r\n\t// Defining the variables\r\n\tdcomp phi_bar, dphi, psi, w;\r\n\r\n\t// calculating the veriables\r\n\tphi_bar = -0.5 * sigma_11inf * conj(z);\r\n\tdphi = -0.5 * sigma_11inf;\r\n\tpsi = -0.5 * sigma_11inf * z;\r\n\r\n\t// Calculating w\r\n\tw = 1 / (4 * G) * ((z - conj(z)) * dphi + kappa * phi_bar + psi);\r\n\r\n\treturn { w };\r\n}\r\n/* --------------------------------------------------------------------\r\n\t\tW CRACK - ANALYTIC ELEMENT\r\n-----------------------------------------------------------------------*/\r\ninline dcomp w_crack(dcomp z, double kappa, double G, dcomp z1, dcomp z2, double L, double mu, int m, dcvec a)\r\n{\r\n\t// Defining the variables\r\n\tdcomp chi, chi_bar, Z, chi_pow;\r\n\tdcomp dphi, phi_bar, psi;\r\n\tdcomp w, L_frac;\r\n\tdouble n;\r\n\r\n\t// Getting the chi - and Z - coordinates\r\n\tchi = chi_from_z(z, z1, z2, L, mu);\r\n\tchi_bar = conj(chi);\r\n\tZ = exp(dcomp(0, -1) * mu) * 2.0 * (z - 0.5 * (z1 + z2)) / L;\r\n\r\n\t// Calculating the series\r\n\tphi_bar = 0;\r\n\tdphi = 0;\r\n\tpsi = 0;\r\n\tn = 0;\r\n\tchi_pow = chi * chi - 1.0;\r\n\tfor (int ii = 0; ii < m; ii++)\r\n\t{\r\n\t\tdcomp a_n;\r\n\t\tn += 1;\r\n\t\ta_n = a[ii] * n;\r\n\t\tdphi += conj(a_n) * pow(chi, (1.0 - n)) / chi_pow;\r\n\t\tphi_bar -= a[ii] * pow(chi_bar, -n);\r\n\t\tpsi += a[ii] * pow(chi, -n);\r\n\t}\r\n\r\n\t// Multiplying the constants\r\n\tL_frac = (4.0 / L) * exp(dcomp(0, -1) * mu);\r\n\tdphi *= L_frac;\r\n\r\n\t// Calcualting w\r\n\tw = 1 / (4 * G) * (0.5 * L * (Z - conj(Z)) * exp(dcomp(0, 1) * mu) * dphi + kappa * phi_bar + psi);\r\n\r\n\treturn { w };\r\n}\r\n/* --------------------------------------------------------------------\r\n\t\tW TOTAL\r\n-----------------------------------------------------------------------*/\r\ninline dcomp  w_total(dcomp z, double kappa, double G, double sigma_11inf, dcvec z1a, dcvec z2a, dvec La, dvec mua, int ma, int na, ddcvec a)\r\n{\r\n\t// Defining the variables\r\n\tdcomp w, wg;\r\n\r\n\t// Add the unfirm stress field\r\n\tw = w_uni(z, kappa, G, sigma_11inf);\r\n\r\n\t// Add the anlytic element for a crack\r\n\tif (na > 0)\r\n\t{\r\n\t\tfor (int ii = 0; ii < na; ii++)\r\n\t\t{\r\n\t\t\tdcomp wc;\r\n\t\t\twc = w_crack(z, kappa, G, z1a[ii], z2a[ii], La[ii], mua[ii], ma, a[ii]);\r\n\t\t\tw += wc * exp(dcomp(0, -1) * mua[ii]);\r\n\t\t}\r\n\t}\r\n\r\n\treturn { w };\r\n}\r\n/* --------------------------------------------------------------------\r\n\t\tDISPLACEMENT FIELD\r\n-----------------------------------------------------------------------*/\r\nstd::tuple<dvec, dvec, ddcvec> w_field(double xfrom, double xto, double yfrom, double yto, int Nw, double kappa, double G, double sigma_11inf, dcvec z1a, dcvec z2a, dvec La, dvec mua, int ma, int na, ddcvec a)\r\n\r\n{\r\n\t// Defining the variables\r\n\tddcvec grid_w(Nw, dcvec(Nw));\r\n\tdvec x_vecw(Nw), y_vecw(Nw);\r\n\tdouble dx;\r\n\tdouble dy;\r\n\r\n\t// Calcualte the displacement grid\r\n\tdx = (xto - xfrom) / (Nw - 1.0);\r\n\tdy = (yto - yfrom) / (Nw - 1.0);\r\n#pragma omp parallel for default(none) shared(grid_w, x_vecw, y_vecw, kappa, G, sigma_11inf, z1a, z2a, La, mua, ma, na, a)\r\n\tfor (int ii = 0; ii < Nw; ii++)\r\n\t{\r\n\t\tfor (int jj = 0; jj < Nw; jj++)\r\n\t\t{\r\n\r\n\t\t\tx_vecw[ii] = xfrom + ii * dx;\r\n\t\t\ty_vecw[jj] = yfrom + jj * dy;\r\n\t\t\tgrid_w[ii][jj] = w_total(dcomp(x_vecw[ii], y_vecw[jj]), kappa, G, sigma_11inf, z1a, z2a, La, mua, ma, na, a);\r\n\t\t}\r\n\t}\r\n\treturn { x_vecw, y_vecw, grid_w };\r\n}\r\n/*---------------------------------------------------------------------\r\n\t\tDISPLACEMENT TRAJECTORIES\r\n-----------------------------------------------------------------------*/\r\nddcvec w_trajectories(double xfrom, double xto, double yfrom, double yto, int Ntraj, int Nw, double kappa, double G, double sigma_11inf, dcvec z1a, dcvec z2a, dvec La, dvec mua, int ma, int na, ddcvec a)\r\n{\r\n\t// Defining the variables\r\n\tddcvec traj_w((int)(Nw * 2), dcvec(Ntraj));\r\n\tdouble dx, dy_lvs;\r\n\tdouble cond, pi_val;\r\n\tint NIT;\r\n\r\n\t// Getting the starting points\r\n\tdx = (xto - xfrom) / (Ntraj);\r\n\tdy_lvs = (yto - yfrom) / (Nw - 1.0);\r\n\tpi_val = 0.5 * pi();\r\n\tcond = 1e-6;\r\n\tNIT = 10;\r\n\r\n\t// w trajectories\r\n#pragma omp parallel for default(none) shared(traj_w, kappa, G, sigma_11inf, z1a, z2a, La, mua, ma, na, a)\r\n\tfor (int ii = 0; ii < Nw; ii++)\r\n\t{\r\n\t\ttraj_w[ii][0] = dcomp(xfrom, yfrom + ii * dy_lvs);\r\n\t\tdcomp z = traj_w[ii][0];\r\n\t\tdcomp z_old = z;\r\n\t\tdouble dx1 = dx;\r\n\t\tfor (int jj = 1; jj < Ntraj; jj++)\r\n\t\t{\r\n\t\t\tdcomp zt, z_oldt, w, w1;\r\n\t\t\tdouble ee;\r\n\t\t\tw = w_total(z, kappa, G, sigma_11inf, z1a, z2a, La, mua, ma, na, a);\r\n\t\t\tzt = z + conj(w) / abs(w) * dx1;\r\n\r\n\t\t\tee = 1;\r\n\t\t\tfor (int rr = NIT; rr--;)\r\n\t\t\t{\r\n\t\t\t\tz_oldt = zt;\r\n\t\t\t\tw1 = w_total(zt, kappa, G, sigma_11inf, z1a, z2a, La, mua, ma, na, a);\r\n\t\t\t\tzt = z + conj(w + w1) / abs(w + w1) * dx1;\r\n\t\t\t\tee = std::norm(z_oldt - zt);\r\n\t\t\t\tif (ee < cond)\r\n\t\t\t\t{\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\ttraj_w[ii][jj] = zt;\r\n\t\t\tz_old = z;\r\n\t\t\tz = zt;\r\n\t\t}\r\n\r\n\t\tint kk = ii + Nw;\r\n\t\ttraj_w[kk][0] = dcomp(xto, yfrom + ii * dy_lvs);\r\n\t\tz = traj_w[kk][0];\r\n\t\tz_old = z;\r\n\t\tdx1 = dx;\r\n\t\tfor (int jj = 1; jj < Ntraj; jj++)\r\n\t\t{\r\n\t\t\tdcomp zt, z_oldt, w, w1;\r\n\t\t\tdouble ee;\r\n\t\t\tw = w_total(z, kappa, G, sigma_11inf, z1a, z2a, La, mua, ma, na, a);\r\n\t\t\tzt = z + conj(w) / abs(w) * dx1;\r\n\r\n\t\t\tee = 1;\r\n\t\t\tfor (int rr = NIT; rr--;)\r\n\t\t\t{\r\n\t\t\t\tz_oldt = zt;\r\n\t\t\t\tw1 = w_total(zt, kappa, G, sigma_11inf, z1a, z2a, La, mua, ma, na, a);\r\n\t\t\t\tzt = z + conj(w + w1) / abs(w + w1) * dx1;\r\n\t\t\t\tee = std::norm(z_oldt - zt);\r\n\t\t\t\tif (ee < cond)\r\n\t\t\t\t{\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\ttraj_w[kk][jj] = zt;\r\n\t\t\tz_old = z;\r\n\t\t\tz = zt;\r\n\r\n\t\t}\r\n\t}\r\n\treturn { traj_w };\r\n}\r\n\r\n/* --------------------------------------------------------------------\r\n\r\n\t\tMAIN SCRIPT\r\n\r\n-----------------------------------------------------------------------*/\r\nint main()\r\n{\r\n\t/* --------------------------------------------------------------------\r\n\t\t\tDefining variables and importing data\r\n\t-----------------------------------------------------------------------*/\r\n\r\n\t// Header in console window\r\n\tauto start = std::chrono::high_resolution_clock::now(); // Start the clock\r\n\r\n\tstd::cout << \"=================================================================\" << std::endl << std::endl;\r\n\tstd::cout << \"\t\tANALYTIC ELEMENT LINEAR ELASTIC SOLVER\t\" << std::endl << std::endl;\r\n\tstd::cout << \"=================================================================\" << std::endl << std::endl;\r\n\r\n\tauto date_time1 = std::chrono::system_clock::now();\r\n\tstd::time_t start_time = std::chrono::system_clock::to_time_t(date_time1);\r\n\tchar str_time1[26];\r\n\tctime_s(str_time1, sizeof str_time1, &start_time);\r\n\tstd::cout << \"Program started: \" << str_time1 << std::endl;\r\n\r\n\t// Setting the data types\r\n\tdcomp z;\r\n\tdouble kappa, sigma_11inf, G, cond;\r\n\tint na, ma, Na, NIT;\r\n\r\n\t// Read the input data from binary file PART 1\r\n\tstd::ifstream input_file(\"geometry_data.bin\", std::ios::in | std::ios::binary | std::ios::ate);\r\n\tstd::streampos size = input_file.tellg();\r\n\tchar* memblock = new char[size];\r\n\tinput_file.seekg(0, std::ios::beg);\r\n\tinput_file.read(memblock, size);\r\n\tdouble* fin = (double*)memblock;//reinterpret as doubles\r\n\r\n\tsigma_11inf = fin[0];\r\n\tkappa = fin[1];\r\n\tG = fin[2];\r\n\tna = (int)fin[3];\r\n\tma = (int)fin[4];\r\n\tNa = (int)fin[5];\r\n\tcond = (double)fin[6];\r\n\tNIT = (int)fin[7];\r\n\r\n\t// Declaring the vecotrs\r\n\tdcvec z1a(na), z2a(na);\r\n\tdvec pa(na), La(na), mua(na);\r\n\tddcvec a(na, dcvec(ma));\r\n\r\n\tint pos = 7 + 1;\r\n\tif (na > 0)\r\n\t{\r\n\t\tfor (int ii = 0; ii < na; ii++)\r\n\t\t{\r\n\t\t\tint re = pos + ii;\r\n\t\t\tint im = pos + na + ii;\r\n\t\t\tz1a[ii] = dcomp(fin[re], fin[im]);\r\n\t\t}\r\n\t\tpos += 2 * na;\r\n\t\tfor (int ii = 0; ii < na; ii++)\r\n\t\t{\r\n\t\t\tint re = pos + ii;\r\n\t\t\tint im = pos + na + ii;\r\n\t\t\tz2a[ii] = dcomp(fin[re], fin[im]);\r\n\t\t}\r\n\t\tpos += 2 * na;\r\n\t\tfor (int ii = 0; ii < na; ii++)\r\n\t\t{\r\n\t\t\tpa[ii] = fin[pos + ii];\r\n\t\t}\r\n\t\tpos += na;\r\n\t\tfor (int ii = 0; ii < na; ii++)\r\n\t\t{\r\n\t\t\tLa[ii] = fin[pos + ii];\r\n\t\t}\r\n\t\tpos += na;\r\n\t\tfor (int ii = 0; ii < na; ii++)\r\n\t\t{\r\n\t\t\tmua[ii] = fin[pos + ii];\r\n\t\t}\r\n\t\tpos += na;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tz1a = { dcomp(0, 0) };\r\n\t\tz2a = { dcomp(0, 0) };\r\n\t\tLa = { 0 };\r\n\t\tmua = { 0 };\r\n\t\ta = { { dcomp(0,0) } };\r\n\t\tma = 1;\r\n\t\tNa = 1;\r\n\t}\r\n\r\n\t// Setting the data types\r\n\tdouble xfrom, xto, yfrom, yto;\r\n\tint Nx, Ny, Nw, Ntraj, lvs_traj;\r\n\tddvec grid_11, grid_22, grid_12, grid_1, grid_2, theta_p;\r\n\tddcvec traj_1, traj_2, grid_w, traj_w;\r\n\tdvec x_vec, y_vec, x_vecw, y_vecw;\r\n\tdcvec xtraj, ytraj;\r\n\r\n\t// Read the plot data from binary file\r\n\tstd::ifstream plot_file(\"plot_data.bin\", std::ios::in | std::ios::binary | std::ios::ate);\r\n\tstd::streampos size2 = plot_file.tellg();\r\n\tchar* memblock2 = new char[size2];\r\n\tplot_file.seekg(0, std::ios::beg);\r\n\tplot_file.read(memblock2, size2);\r\n\tdouble* fplot = (double*)memblock2;//reinterpret as doubles\r\n\r\n\txfrom = fplot[0];\r\n\txto = fplot[1];\r\n\tyfrom = fplot[2];\r\n\tyto = fplot[3];\r\n\tNx = (int)fplot[4];\r\n\tNy = (int)fplot[5];\r\n\tNw = (int)fplot[6];\r\n\tNtraj = (int)fplot[7];\r\n\tlvs_traj = (int)fplot[8];\r\n\txtraj = { fplot[9] + dcomp(0,1) * fplot[10], fplot[11] + dcomp(0,1) * fplot[12] };\r\n\tytraj = { fplot[13] + dcomp(0,1) * fplot[14], fplot[15] + dcomp(0,1) * fplot[16] };\r\n\r\n\t// Displying the plot data in the command window\r\n\tstd::cout << \"=================================================================\" << std::endl << std::endl;\r\n\tstd::cout << \"\t\tTHE GEOMETRY DATA\t\" << std::endl << std::endl;\r\n\tstd::cout << \"=================================================================\" << std::endl << std::endl;\r\n\tstd::cout << \"This is the retrived geometry data:\\n\";\r\n\tstd::cout << \"sigma_11inf = \" << sigma_11inf << std::endl;\r\n\tstd::cout << \"      kappa = \" << kappa << std::endl;\r\n\tstd::cout << \"          G = \" << G << std::endl;\r\n\tstd::cout << \"         na = \" << na << std::endl;\r\n\tstd::cout << \"         ma = \" << ma << std::endl;\r\n\tstd::cout << \"         Na = \" << Na << std::endl;\r\n\t// Displying the plot data in the command window\r\n\tstd::cout << \"=================================================================\" << std::endl << std::endl;\r\n\tstd::cout << \"\t\tTHE READ PLOT DATA\t\" << std::endl << std::endl;\r\n\tstd::cout << \"=================================================================\" << std::endl << std::endl;\r\n\tstd::cout << \"This is the retrived plot data:\\n\";\r\n\tstd::cout << \"x from: \" << xfrom << \" to \" << xto << std::endl;\r\n\tstd::cout << \"y from: \" << yfrom << \" to \" << yto << std::endl;\r\n\tstd::cout << \"x resolution: \" << Nx << std::endl;\r\n\tstd::cout << \"y resolution: \" << Ny << std::endl;\r\n\tstd::cout << \"Total number of points: \" << Nx * Ny << std::endl;\r\n\tstd::cout << \"Number of steps in trajectories: \" << Ntraj << std::endl;\r\n\tstd::cout << \"Number of trajectory levels: \" << lvs_traj << std::endl;\r\n\tstd::cout << \"Total number of trajectory points: \" << Ntraj * lvs_traj * 4 << std::endl;\r\n\tstd::cout << \"sigma_1 starting line from: \" << xtraj[0] << \" to \" << xtraj[1] << std::endl;\r\n\tstd::cout << \"sigma_2 starting line from: \" << ytraj[0] << \" to \" << ytraj[1] << std::endl;\r\n\tstd::cout << \"x and y quiver resolution: \" << Nw << std::endl << std::endl;\r\n\tstd::cout << std::endl;\r\n\r\n\t/* --------------------------------------------------------------------\r\n\t\t\tSolve the system\r\n\t-----------------------------------------------------------------------*/\r\n\tstd::cout << \"=================================================================\" << std::endl << std::endl;\r\n\tstd::cout << \"\t\tINITIALIZING THE SOVLER\t\" << std::endl << std::endl;\r\n\tstd::cout << \"=================================================================\" << std::endl << std::endl;\r\n\r\n\tauto start_solv = std::chrono::high_resolution_clock::now();\r\n\ta = iterator(cond, NIT, Na, pa, sigma_11inf, z1a, z2a, La, mua, ma, na);\r\n\tauto stop_solv = std::chrono::high_resolution_clock::now();\r\n\tauto duration_solv = std::chrono::duration_cast<std::chrono::microseconds>(stop_solv - start_solv);\r\n\r\n\t// Displaying the computation time\r\n\tstd::cout << std::endl;\r\n\tlong long ms_solv = duration_solv.count();\r\n\tlong long s_solv, m_solv, h_solv;\r\n\tstd::tie(ms_solv, s_solv, m_solv, h_solv) = ms_to_time(ms_solv);\r\n\tstd::cout << \"Computations finnished after \";\r\n\ttime_print(ms_solv, s_solv, m_solv, h_solv);\r\n\r\n\tstd::cout << std::endl;\r\n\r\n\t/* --------------------------------------------------------------------\r\n\t\t\tChecking the error\r\n\t-----------------------------------------------------------------------*/\r\n\tdouble error_med_a_re{}, error_mean_a_re{}, error_max_a_re{}, error_med_a_im{}, error_mean_a_im{}, error_max_a_im{}, error_med_int{}, error_mean_int{}, error_max_int{};\r\n\tstd::cout << \"=================================================================\" << std::endl << std::endl;\r\n\tstd::cout << \"\t\tERRORS\t\" << std::endl << std::endl;\r\n\tstd::cout << \"=================================================================\" << std::endl << std::endl;\r\n\tint numa;\r\n\tnuma = (int)round(Na);\r\n\tdcvec T_check(numa* na);\r\n\tif (na > 0)\r\n\t{\r\n\t\t// Calculate the error along the cracks, i.e. T = t_s + i*t_n = 0 + i*p\r\n\t\tdvec T_check_a_re(numa * na), T_check_a_im(numa * na);\r\n\t\tdouble theta_0a = pi()/numa;\r\n\t\tdouble delthetaa = (pi() - 2.0*theta_0a) / (numa-1.0);\r\n\t\tfor (int ii = 0; ii < na; ii++)\r\n\t\t{\r\n\t\t\tfor (int jj = 0; jj < numa; jj++)\r\n\t\t\t{\r\n\t\t\t\tdcomp z, tau_11, tau_12;\r\n\t\t\t\tdouble theta;\r\n\t\t\t\ttheta = theta_0a + (jj) * delthetaa;\r\n\t\t\t\tz = z_from_chi(exp(dcomp(0, 1) * theta), z1a[ii], z2a[ii], La[ii], mua[ii]);\r\n\t\t\t\tT_check[(ii * numa) + jj] = T_total(z, sigma_11inf, z1a, z2a, La, mua, ma, na, a, -1, ii) + dcomp(0, pa[ii]);\r\n\t\t\t\tT_check_a_re[(ii * numa) + jj] = abs(real(T_check[(ii * numa) + jj]));\r\n\t\t\t\tT_check_a_im[(ii * numa) + jj] = abs(imag(T_check[(ii * numa) + jj]));\r\n\t\t\t}\r\n\t\t}\r\n\t\t// Median\r\n\t\tsize_t n1 = T_check_a_re.size() / 2;\r\n\t\tnth_element(T_check_a_re.begin(), T_check_a_re.begin() + n1, T_check_a_re.end());\r\n\t\terror_med_a_re = T_check_a_re[n1];\r\n\t\tnth_element(T_check_a_im.begin(), T_check_a_im.begin() + n1, T_check_a_im.end());\r\n\t\terror_med_a_im = T_check_a_im[n1];\r\n\t\t// Mean\r\n\t\terror_mean_a_re = 1.0 * std::accumulate(T_check_a_re.begin(), T_check_a_re.end(), 0.0) / (n1 * 2);\r\n\t\terror_mean_a_im = 1.0 * std::accumulate(T_check_a_im.begin(), T_check_a_im.end(), 0.0) / (n1 * 2);\r\n\t\t// Max\r\n\t\terror_max_a_re = *max_element(T_check_a_re.begin(), T_check_a_re.end());\r\n\t\terror_max_a_im = *max_element(T_check_a_im.begin(), T_check_a_im.end());\r\n\t\t// Print the results\r\n\t\tstd::cout << \"     Analytic Element for a Crack\" << std::endl;\r\n\t\tstd::cout << \"     Difference for ts\" << std::endl;\r\n\t\tstd::cout << \"     Maximum = \" << error_max_a_re << std::endl;\r\n\t\tstd::cout << \"     Mean    = \" << error_mean_a_re << std::endl;\r\n\t\tstd::cout << \"     Median  = \" << error_med_a_re << std::endl;\r\n\t\tstd::cout << \"     Difference for tn\" << std::endl;\r\n\t\tstd::cout << \"     Maximum = \" << error_max_a_im << std::endl;\r\n\t\tstd::cout << \"     Mean    = \" << error_mean_a_im << std::endl;\r\n\t\tstd::cout << \"     Median  = \" << error_med_a_im << std::endl;\r\n\r\n\t\t// Error at the intersection\r\n\t\tddcvec zint(na, dcvec(na));\r\n\t\tiivec int_check(na, ivec(na));\r\n\t\tivec int_count(na);\r\n\r\n\t\t// Find the intersection points\r\n\t\t#pragma omp parallel for default(none) shared(zint, int_check, int_count, z1a, z2a)\r\n\t\tfor (int ii = 0; ii < na; ii++)\r\n\t\t{\r\n\t\t\tfor (int jj = 0; jj < na; jj++)\r\n\t\t\t{\r\n\t\t\t\tstd::tie(zint[ii][jj], int_check[ii][jj]) = intersection_point(z1a[ii], z2a[ii], z1a[jj], z2a[jj]);\r\n\t\t\t}\r\n\t\t\tint_count[ii] = std::accumulate(int_check[ii].begin(), int_check[ii].end(), 0.0);\r\n\t\t}\r\n\t\tint int_sum = std::accumulate(int_count.begin(), int_count.end(), 0.0);\r\n\t\tdvec int_error(int_sum);\r\n\t\tint cnt_int = 0;\r\n\r\n\t\t// Calcualte the error at the intersections, i.e. real(tau^11) = 0\r\n\t\tif (int_sum > 0)\r\n\t\t{\r\n\t\t\tfor (int ii = 0; ii < na; ii++)\r\n\t\t\t{\r\n\t\t\t\tif (int_count[ii] > 0)\r\n\t\t\t\t{\r\n\t\t\t\t\tint cnt_er = 0;\r\n\t\t\t\t\tfor (int jj = 0; jj < na; jj++)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tif (int_check[ii][jj] == 1)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tdcomp tau_11, tau_12, T;\r\n\t\t\t\t\t\t\tstd::tie(tau_11, tau_12) = tau_total(zint[ii][jj], sigma_11inf, z1a, z2a, La, mua, ma, na, a, -1);\r\n\t\t\t\t\t\t\tT = T_total(z, sigma_11inf, z1a, z2a, La, mua, ma, na, a, -1, ii);\r\n\t\t\t\t\t\t\tstd::cout << \"z = \" << zint[ii][jj] << \" tau_11 = \" << tau_11 << \" tau_12 = \" << tau_12 << \" T = \" << T << std::endl;\r\n\t\t\t\t\t\t\tint_error[cnt_int + cnt_er] = abs(real(tau_11));\r\n\t\t\t\t\t\t\tcnt_er += 1;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tcnt_int += int_count[ii];\r\n\t\t\t}\r\n\r\n\t\t\t// Mean\r\n\t\t\terror_mean_int = std::accumulate(int_error.begin(), int_error.end(), 0.0) / (int_sum);\r\n\t\t\t// Max\r\n\t\t\terror_max_int = *max_element(int_error.begin(), int_error.end());\r\n\t\t\t// Median\r\n\t\t\tsize_t n2 = int_error.size() / 2;\r\n\t\t\tnth_element(int_error.begin(), int_error.begin() + n2, int_error.end());\r\n\t\t\terror_med_int = int_error[n2];\r\n\t\t\t// Print the results\r\n\t\t\tstd::cout << \"     Intersection/s:\" << std::endl;\r\n\t\t\tstd::cout << \"     Maximum = \" << error_max_int << std::endl;\r\n\t\t\tstd::cout << \"     Mean    = \" << error_mean_int << std::endl;\r\n\t\t\tstd::cout << \"     Median  = \" << error_med_int << std::endl;\r\n\t\t}\r\n\t}\r\n\r\n\t// Create/open the two output files\r\n\tstd::ofstream outfile_coef(\"input_data.bin\", std::ios::out | std::ios::binary);\r\n\r\n\t// Save the plot properties\r\n\tdvec prop = { sigma_11inf,  kappa, G, 1.0 * na, 1.0 * ma};\r\n\tconst char* pointerprop = reinterpret_cast<const char*>(&prop[0]);\r\n\tstd::size_t bytesprop = prop.size() * sizeof(prop[0]);\r\n\toutfile_coef.write(pointerprop, bytesprop);\r\n\r\n\r\n\t// saving the coordinates of the cracks\r\n\tif (na > 0)\r\n\t{\r\n\t\tdvec fz1_re(na);\r\n\t\tdvec fz1_im(na);\r\n\t\tfor (int jj = 0; jj < na; jj++)\r\n\t\t{\r\n\t\t\tfz1_re[jj] = real(z1a[jj]);\r\n\t\t\tfz1_im[jj] = imag(z1a[jj]);\r\n\t\t}\r\n\t\tconst char* pointerz1_re = reinterpret_cast<const char*>(&fz1_re[0]);\r\n\t\tstd::size_t bytesz1_re = fz1_re.size() * sizeof(fz1_re[0]);\r\n\t\toutfile_coef.write(pointerz1_re, bytesz1_re);\r\n\t\tconst char* pointerz1_im = reinterpret_cast<const char*>(&fz1_im[0]);\r\n\t\tstd::size_t bytesz1_im = fz1_im.size() * sizeof(fz1_im[0]);\r\n\t\toutfile_coef.write(pointerz1_im, bytesz1_im);\r\n\r\n\t\tdvec fz2_re(na);\r\n\t\tdvec fz2_im(na);\r\n\t\tfor (int jj = 0; jj < na; jj++)\r\n\t\t{\r\n\t\t\tfz2_re[jj] = real(z2a[jj]);\r\n\t\t\tfz2_im[jj] = imag(z2a[jj]);\r\n\t\t}\r\n\t\tconst char* pointerz2_re = reinterpret_cast<const char*>(&fz2_re[0]);\r\n\t\tstd::size_t bytesz2_re = fz2_re.size() * sizeof(fz2_re[0]);\r\n\t\toutfile_coef.write(pointerz2_re, bytesz2_re);\r\n\t\tconst char* pointerz2_im = reinterpret_cast<const char*>(&fz2_im[0]);\r\n\t\tstd::size_t bytesz2_im = fz2_im.size() * sizeof(fz2_im[0]);\r\n\t\toutfile_coef.write(pointerz2_im, bytesz2_im);\r\n\r\n\t\tdvec fL = La;\r\n\t\tconst char* pointerL = reinterpret_cast<const char*>(&fL[0]);\r\n\t\tstd::size_t bytesL = fL.size() * sizeof(fL[0]);\r\n\t\toutfile_coef.write(pointerL, bytesL);\r\n\r\n\t\tdvec fmu = mua;\r\n\t\tconst char* pointermu = reinterpret_cast<const char*>(&fmu[0]);\r\n\t\tstd::size_t bytesmu = fmu.size() * sizeof(fmu[0]);\r\n\t\toutfile_coef.write(pointermu, bytesmu);\r\n\r\n\t\t// Save the a\r\n\t\tfor (int ii = 0; ii < na; ii++)\r\n\t\t{\r\n\t\t\tdvec fbeta_re(ma);\r\n\t\t\tdvec fbeta_im(ma);\r\n\r\n\t\t\tfor (int jj = 0; jj < ma; jj++)\r\n\t\t\t{\r\n\t\t\t\tfbeta_re[jj] = real(a[ii][jj]);\r\n\t\t\t\tfbeta_im[jj] = imag(a[ii][jj]);\r\n\t\t\t}\r\n\t\t\tconst char* pointerbeta_re = reinterpret_cast<const char*>(&fbeta_re[0]);\r\n\t\t\tstd::size_t bytesbeta_re = fbeta_re.size() * sizeof(fbeta_re[0]);\r\n\t\t\toutfile_coef.write(pointerbeta_re, bytesbeta_re);\r\n\t\t\tconst char* pointerbeta_im = reinterpret_cast<const char*>(&fbeta_im[0]);\r\n\t\t\tstd::size_t bytesbeta_im = fbeta_im.size() * sizeof(fbeta_im[0]);\r\n\t\t\toutfile_coef.write(pointerbeta_im, bytesbeta_im);\r\n\t\t}\r\n\t}\r\n\r\n\t// Estimate the time of the program\r\n\tstd::cout << \"=================================================================\" << std::endl << std::endl;\r\n\tstd::cout << \"\t\tESTIMATED CALCULATION TIME\t\" << std::endl << std::endl;\r\n\tstd::cout << \"=================================================================\" << std::endl << std::endl;\r\n\tint Ne = (Nx + Ny + Ntraj) / 100;\r\n\tif (Ne < 8)\r\n\t{\r\n\t\tNe = 8;\r\n\t}\r\n\tauto start0 = std::chrono::high_resolution_clock::now();\r\n\tstress_field(xfrom, xto, yfrom, yto, Ne, Ne, sigma_11inf, z1a, z2a, La, mua, ma, na, a);\r\n\tauto stop0 = std::chrono::high_resolution_clock::now();\r\n\tauto start01 = std::chrono::high_resolution_clock::now();\r\n\tprincipal_stress_trajectories(xfrom, xto, yfrom, yto, xtraj, ytraj, Ne, Ne, sigma_11inf, z1a, z2a, La, mua, ma, na, a);\r\n\tauto stop01 = std::chrono::high_resolution_clock::now();\r\n\tauto duration0 = std::chrono::duration_cast<std::chrono::microseconds>(stop0 - start0);\r\n\tlong long ms0 = duration0.count();\r\n\tauto duration01 = std::chrono::duration_cast<std::chrono::microseconds>(stop01 - start01);\r\n\tlong long ms01 = duration01.count();\r\n\tlong long calcs0 = (int)(2 * Nx * Ny) + (int)(Nw * Nw);\r\n\tlong long calcs01 = (int)(Ntraj * lvs_traj) + (int)(Ntraj * Nw);\r\n\tms0 = ((ms0 / ((int)Ne * Ne) * calcs0 + ms01 / ((int)Ne * Ne) * calcs01))*0.7;\r\n\tlong long s0, m0, h0;\r\n\tstd::tie(ms0, s0, m0, h0) = ms_to_time(ms0);\r\n\tstd::cout << \"Estimated calculation time:  \";\r\n\ttime_print(ms0, s0, m0, h0);\r\n\tstd::cout << std::endl << std::endl;\r\n\tauto date_time2 = std::chrono::system_clock::now();\r\n\tstd::time_t start_time2 = std::chrono::system_clock::to_time_t(date_time2);\r\n\tchar str_time2[26];\r\n\tctime_s(str_time2, sizeof str_time2, &start_time2);\r\n\tstd::cout << \"Plotting started: \" << str_time2 << std::endl << std::endl;\r\n\r\n\t/* --------------------------------------------------------------------\r\n\t\t\tCalculating the plots\r\n\t-----------------------------------------------------------------------*/\r\n\r\n\tstd::cout << \"=================================================================\" << std::endl << std::endl;\r\n\tstd::cout << \"\t\tCOMPUTING THE PLOTS\t\" << std::endl << std::endl;\r\n\tstd::cout << \"=================================================================\" << std::endl << std::endl;\r\n\r\n\t// Get the Cartisian stress field\r\n\tstd::cout << \"Initiating the stress field calculation\\n\";\r\n\tauto start1 = std::chrono::high_resolution_clock::now();\r\n\tstd::tie(x_vec, y_vec, grid_11, grid_22, grid_12) = stress_field(xfrom, xto, yfrom, yto, Nx, Ny, sigma_11inf, z1a, z2a, La, mua, ma, na, a);\r\n\tauto stop1 = std::chrono::high_resolution_clock::now();\r\n\tauto duration1 = std::chrono::duration_cast<std::chrono::microseconds>(stop1 - start1);\r\n\tstd::cout << \"Completed, time taken by function: stress_field = \";\r\n\tlong long ms1, s1, m1, h1;\r\n\tms1 = duration1.count();\r\n\tstd::tie(ms1, s1, m1, h1) = ms_to_time(ms1);\r\n\ttime_print(ms1, s1, m1, h1);\r\n\tstd::cout << std::endl << std::endl;\r\n\r\n\t// Get the principal stress field\r\n\tstd::cout << \"Initiating the principal stress field calculation\\n\";\r\n\tauto start2 = std::chrono::high_resolution_clock::now();\r\n\tstd::tie(grid_1, grid_2, theta_p) = principal_stress_field(Nx, Ny, grid_11, grid_22, grid_12);\r\n\tauto stop2 = std::chrono::high_resolution_clock::now();\r\n\tauto duration2 = std::chrono::duration_cast<std::chrono::microseconds>(stop2 - start2);\r\n\tstd::cout << \"Completed, time taken by function: principal_stress_field = \";\r\n\tms1 = duration2.count();\r\n\tstd::tie(ms1, s1, m1, h1) = ms_to_time(ms1);\r\n\ttime_print(ms1, s1, m1, h1);\r\n\tstd::cout << std::endl << std::endl;\r\n\r\n\t// Get the stress trajectories\r\n\tstd::cout << \"Initiating the principal stress trajectories calculation\\n\";\r\n\tauto start3 = std::chrono::high_resolution_clock::now();\r\n\tstd::tie(traj_1, traj_2) = principal_stress_trajectories(xfrom, xto, yfrom, yto, xtraj, ytraj, Ntraj, lvs_traj, sigma_11inf, z1a, z2a, La, mua, ma, na, a);\r\n\tauto stop3 = std::chrono::high_resolution_clock::now();\r\n\tauto duration3 = std::chrono::duration_cast<std::chrono::microseconds>(stop3 - start3);\r\n\tstd::cout << \"Completed, time taken by function: principal_stress_trajectories = \";\r\n\tms1 = duration3.count();\r\n\tstd::tie(ms1, s1, m1, h1) = ms_to_time(ms1);\r\n\ttime_print(ms1, s1, m1, h1);\r\n\tstd::cout << std::endl << std::endl;\r\n\r\n\t// Get the displacement field\r\n\tstd::cout << \"Initiating the displacement field calculation\\n\";\r\n\tauto start4 = std::chrono::high_resolution_clock::now();\r\n\tstd::tie(x_vecw, y_vecw, grid_w) = w_field(xfrom, xto, yfrom, yto, Nw, kappa, G, sigma_11inf, z1a, z2a, La, mua, ma, na, a);\r\n\tauto stop4 = std::chrono::high_resolution_clock::now();\r\n\tauto duration4 = std::chrono::duration_cast<std::chrono::microseconds>(stop4 - start4);\r\n\tstd::cout << \"Completed, time taken by function: w_field = \";\r\n\tms1 = duration4.count();\r\n\tstd::tie(ms1, s1, m1, h1) = ms_to_time(ms1);\r\n\ttime_print(ms1, s1, m1, h1);\r\n\tstd::cout << std::endl << std::endl;\r\n\r\n\r\n\t// Get the displacement trajectories\r\n\tstd::cout << \"Initiating the displacement trajectories calculation\\n\";\r\n\tauto start5 = std::chrono::high_resolution_clock::now();\r\n\ttraj_w = w_trajectories(xfrom, xto, yfrom, yto, Ntraj, Nw, kappa, G, sigma_11inf, z1a, z2a, La, mua, ma, na, a);\r\n\tauto stop5 = std::chrono::high_resolution_clock::now();\r\n\tauto duration5 = std::chrono::duration_cast<std::chrono::microseconds>(stop5 - start5);\r\n\tstd::cout << \"Completed, time taken by function: w_trajectories = \";\r\n\tms1 = duration5.count();\r\n\tstd::tie(ms1, s1, m1, h1) = ms_to_time(ms1);\r\n\ttime_print(ms1, s1, m1, h1);\r\n\tstd::cout << std::endl << std::endl;\r\n\r\n\t// Displaying the computation time\r\n\tstd::cout << \"=================================================================\" << std::endl << std::endl;\r\n\tlong long mstime = duration1.count() + duration2.count() + duration3.count() + duration4.count() + duration5.count();\r\n\tlong long stime, mtime, htime;\r\n\tstd::tie(mstime, stime, mtime, htime) = ms_to_time(mstime);\r\n\tstd::cout << \"Total calculation time: \";\r\n\ttime_print(mstime, stime, mtime, htime);\r\n\tstd::cout << std::endl << std::endl;\r\n\r\n\t/* --------------------------------------------------------------------\r\n\t\t\tSaving the data as binary files\r\n\t-----------------------------------------------------------------------*/\r\n\r\n\t// Create/open the two output files\r\n\tstd::ofstream outfile(\"data.bin\", std::ios::out | std::ios::binary);\r\n\tstd::ofstream outfiledim(\"dim_data.bin\", std::ios::out | std::ios::binary);\r\n\r\n\t// Save the x and y vectors\r\n\tdvec fx = x_vec;\r\n\tconst char* pointerx = reinterpret_cast<const char*>(&fx[0]);\r\n\tstd::size_t bytesx = fx.size() * sizeof(fx[0]);\r\n\toutfile.write(pointerx, bytesx);\r\n\r\n\tdvec fy = y_vec;\r\n\tconst char* pointery = reinterpret_cast<const char*>(&fy[0]);\r\n\tstd::size_t bytesy = fy.size() * sizeof(fy[0]);\r\n\toutfile.write(pointery, bytesy);\r\n\r\n\tdvec fxw = x_vecw;\r\n\tconst char* pointerxw = reinterpret_cast<const char*>(&fxw[0]);\r\n\tstd::size_t bytesxw = fxw.size() * sizeof(fxw[0]);\r\n\toutfile.write(pointerxw, bytesxw);\r\n\r\n\tdvec fyw = y_vecw;\r\n\tconst char* pointeryw = reinterpret_cast<const char*>(&fyw[0]);\r\n\tstd::size_t bytesyw = fyw.size() * sizeof(fyw[0]);\r\n\toutfile.write(pointeryw, bytesyw);\r\n\r\n\t// Save the grids\r\n\tfor (size_t ii = 0; ii < grid_11.size(); ii++)\r\n\t{\r\n\t\tdvec fg11 = grid_11[ii];\r\n\t\tconst char* pointerg11 = reinterpret_cast<const char*>(&fg11[0]);\r\n\t\tstd::size_t bytesg11 = fg11.size() * sizeof(fg11[0]);\r\n\t\toutfile.write(pointerg11, bytesg11);\r\n\t}\r\n\tfor (size_t ii = 0; ii < grid_22.size(); ii++)\r\n\t{\r\n\t\tdvec fg22 = grid_22[ii];\r\n\t\tconst char* pointerg22 = reinterpret_cast<const char*>(&fg22[0]);\r\n\t\tstd::size_t bytesg22 = fg22.size() * sizeof(fg22[0]);\r\n\t\toutfile.write(pointerg22, bytesg22);\r\n\t}\r\n\tfor (size_t ii = 0; ii < grid_12.size(); ii++)\r\n\t{\r\n\t\tdvec fg12 = grid_12[ii];\r\n\t\tconst char* pointerg12 = reinterpret_cast<const char*>(&fg12[0]);\r\n\t\tstd::size_t bytesg12 = fg12.size() * sizeof(fg12[0]);\r\n\t\toutfile.write(pointerg12, bytesg12);\r\n\t}\r\n\tfor (size_t ii = 0; ii < grid_1.size(); ii++)\r\n\t{\r\n\t\tdvec fg1 = grid_1[ii];\r\n\t\tconst char* pointerg1 = reinterpret_cast<const char*>(&fg1[0]);\r\n\t\tstd::size_t bytesg1 = fg1.size() * sizeof(fg1[0]);\r\n\t\toutfile.write(pointerg1, bytesg1);\r\n\t}\r\n\tfor (size_t ii = 0; ii < grid_2.size(); ii++)\r\n\t{\r\n\t\tdvec fg2 = grid_2[ii];\r\n\t\tconst char* pointerg2 = reinterpret_cast<const char*>(&fg2[0]);\r\n\t\tstd::size_t bytesg2 = fg2.size() * sizeof(fg2[0]);\r\n\t\toutfile.write(pointerg2, bytesg2);\r\n\t}\r\n\tfor (size_t ii = 0; ii < theta_p.size(); ii++)\r\n\t{\r\n\t\tdvec fgtp = theta_p[ii];\r\n\t\tconst char* pointergtp = reinterpret_cast<const char*>(&fgtp[0]);\r\n\t\tstd::size_t bytesgtp = fgtp.size() * sizeof(fgtp[0]);\r\n\t\toutfile.write(pointergtp, bytesgtp);\r\n\t}\r\n\tfor (size_t ii = 0; ii < traj_1.size(); ii++)\r\n\t{\r\n\t\tdvec fgt1_re(Ntraj);\r\n\t\tdvec fgt1_im(Ntraj);\r\n\r\n\t\tfor (size_t jj = 0; jj < traj_1[0].size(); jj++)\r\n\t\t{\r\n\t\t\tfgt1_re[jj] = real(traj_1[ii][jj]);\r\n\t\t\tfgt1_im[jj] = imag(traj_1[ii][jj]);\r\n\t\t}\r\n\t\tconst char* pointergt1_re = reinterpret_cast<const char*>(&fgt1_re[0]);\r\n\t\tstd::size_t bytesgt1_re = fgt1_re.size() * sizeof(fgt1_re[0]);\r\n\t\toutfile.write(pointergt1_re, bytesgt1_re);\r\n\t\tconst char* pointergt1_im = reinterpret_cast<const char*>(&fgt1_im[0]);\r\n\t\tstd::size_t bytesgt1_im = fgt1_im.size() * sizeof(fgt1_im[0]);\r\n\t\toutfile.write(pointergt1_im, bytesgt1_im);\r\n\t}\r\n\tfor (size_t ii = 0; ii < traj_2.size(); ii++)\r\n\t{\r\n\t\tdvec fgt2_re(Ntraj);\r\n\t\tdvec fgt2_im(Ntraj);\r\n\t\tfor (size_t jj = 0; jj < traj_2[0].size(); jj++)\r\n\t\t{\r\n\t\t\tfgt2_re[jj] = real(traj_2[ii][jj]);\r\n\t\t\tfgt2_im[jj] = imag(traj_2[ii][jj]);\r\n\t\t}\r\n\t\tconst char* pointergt2_re = reinterpret_cast<const char*>(&fgt2_re[0]);\r\n\t\tstd::size_t bytesgt2_re = fgt2_re.size() * sizeof(fgt2_re[0]);\r\n\t\toutfile.write(pointergt2_re, bytesgt2_re);\r\n\t\tconst char* pointergt2_im = reinterpret_cast<const char*>(&fgt2_im[0]);\r\n\t\tstd::size_t bytesgt2_im = fgt2_im.size() * sizeof(fgt2_im[0]);\r\n\t\toutfile.write(pointergt2_im, bytesgt2_im);\r\n\t}\r\n\tfor (size_t ii = 0; ii < grid_w.size(); ii++)\r\n\t{\r\n\t\tdvec fgw_re(Nw);\r\n\t\tdvec fgw_im(Nw);\r\n\t\tfor (size_t jj = 0; jj < grid_w[0].size(); jj++)\r\n\t\t{\r\n\t\t\tfgw_re[jj] = real(grid_w[ii][jj]);\r\n\t\t\tfgw_im[jj] = imag(grid_w[ii][jj]);\r\n\t\t}\r\n\t\tconst char* pointergw_re = reinterpret_cast<const char*>(&fgw_re[0]);\r\n\t\tstd::size_t bytesgw_re = fgw_re.size() * sizeof(fgw_re[0]);\r\n\t\toutfile.write(pointergw_re, bytesgw_re);\r\n\t\tconst char* pointergw_im = reinterpret_cast<const char*>(&fgw_im[0]);\r\n\t\tstd::size_t bytesgw_im = fgw_im.size() * sizeof(fgw_im[0]);\r\n\t\toutfile.write(pointergw_im, bytesgw_im);\r\n\t}\r\n\tfor (size_t ii = 0; ii < traj_w.size(); ii++)\r\n\t{\r\n\t\tdvec fgtw_re(Ntraj);\r\n\t\tdvec fgtw_im(Ntraj);\r\n\t\tfor (size_t jj = 0; jj < traj_w[0].size(); jj++)\r\n\t\t{\r\n\t\t\tfgtw_re[jj] = real(traj_w[ii][jj]);\r\n\t\t\tfgtw_im[jj] = imag(traj_w[ii][jj]);\r\n\t\t}\r\n\t\tconst char* pointergtw_re = reinterpret_cast<const char*>(&fgtw_re[0]);\r\n\t\tstd::size_t bytesgtw_re = fgtw_re.size() * sizeof(fgtw_re[0]);\r\n\t\toutfile.write(pointergtw_re, bytesgtw_re);\r\n\t\tconst char* pointergtw_im = reinterpret_cast<const char*>(&fgtw_im[0]);\r\n\t\tstd::size_t bytesgtw_im = fgtw_im.size() * sizeof(fgtw_im[0]);\r\n\t\toutfile.write(pointergtw_im, bytesgtw_im);\r\n\t}\r\n\tif (na > 0)\r\n\t{\r\n\t\tdvec fT_res(numa * na);\r\n\t\tdvec fT_ims(numa * na);\r\n\t\tfor (int jj = 0; jj < numa * na; jj++)\r\n\t\t{\r\n\t\t\tfT_res[jj] = real(T_check[jj]);\r\n\t\t\tfT_ims[jj] = imag(T_check[jj]);\r\n\t\t}\r\n\t\tconst char* pointerT_res = reinterpret_cast<const char*>(&fT_res[0]);\r\n\t\tstd::size_t bytesT_res = fT_res.size() * sizeof(fT_res[0]);\r\n\t\toutfile.write(pointerT_res, bytesT_res);\r\n\t\tconst char* pointerT_ims = reinterpret_cast<const char*>(&fT_ims[0]);\r\n\t\tstd::size_t bytesT_ims = fT_ims.size() * sizeof(fT_ims[0]);\r\n\t\toutfile.write(pointerT_ims, bytesT_ims);\r\n\t}\r\n\t\r\n\r\n\t// Save the plot properties\r\n\tdvec dim = { 1.0 * Nx, 1.0 * Ny, 1.0 * Nw, 1.0 * Ntraj, 1.0 * lvs_traj, 1.0 * na, error_med_a_re, error_mean_a_re, error_max_a_re, error_med_a_im, error_mean_a_im, error_max_a_im, error_med_int, error_mean_int, error_max_int};\r\n\tconst char* pointerdim = reinterpret_cast<const char*>(&dim[0]);\r\n\tstd::size_t bytesdim = dim.size() * sizeof(dim[0]);\r\n\toutfiledim.write(pointerdim, bytesdim);\r\n\r\n\t// saving the coordinates of the cracks\r\n\tif (na > 0)\r\n\t{\r\n\t\tdvec fz1_res(na);\r\n\t\tdvec fz1_ims(na);\r\n\t\tfor (int jj = 0; jj < na; jj++)\r\n\t\t{\r\n\t\t\tfz1_res[jj] = real(z1a[jj]);\r\n\t\t\tfz1_ims[jj] = imag(z1a[jj]);\r\n\t\t}\r\n\t\tconst char* pointerz1_res = reinterpret_cast<const char*>(&fz1_res[0]);\r\n\t\tstd::size_t bytesz1_res = fz1_res.size() * sizeof(fz1_res[0]);\r\n\t\toutfiledim.write(pointerz1_res, bytesz1_res);\r\n\t\tconst char* pointerz1_ims = reinterpret_cast<const char*>(&fz1_ims[0]);\r\n\t\tstd::size_t bytesz1_ims = fz1_ims.size() * sizeof(fz1_ims[0]);\r\n\t\toutfiledim.write(pointerz1_ims, bytesz1_ims);\r\n\r\n\t\tdvec fz2_res(na);\r\n\t\tdvec fz2_ims(na);\r\n\t\tfor (int jj = 0; jj < na; jj++)\r\n\t\t{\r\n\t\t\tfz2_res[jj] = real(z2a[jj]);\r\n\t\t\tfz2_ims[jj] = imag(z2a[jj]);\r\n\t\t}\r\n\t\tconst char* pointerz2_re = reinterpret_cast<const char*>(&fz2_res[0]);\r\n\t\tstd::size_t bytesz2_re = fz2_res.size() * sizeof(fz2_res[0]);\r\n\t\toutfiledim.write(pointerz2_re, bytesz2_re);\r\n\t\tconst char* pointerz2_im = reinterpret_cast<const char*>(&fz2_ims[0]);\r\n\t\tstd::size_t bytesz2_im = fz2_ims.size() * sizeof(fz2_ims[0]);\r\n\t\toutfiledim.write(pointerz2_im, bytesz2_im);\r\n\r\n\t}\r\n\r\n\t// Close the output files\r\n\toutfile.close();\r\n\toutfiledim.close();\r\n\r\n\t// Get the date and execution time\r\n\tauto end = std::chrono::high_resolution_clock::now();\r\n\tauto date_time3 = std::chrono::system_clock::now();\r\n\tauto elapsed_seconds = std::chrono::duration_cast<std::chrono::microseconds>(end - start);\r\n\tlong long mseconds = elapsed_seconds.count();\r\n\tlong long seconds, hours, minutes;\r\n\tstd::tie(mseconds, seconds, minutes, hours) = ms_to_time(mseconds);\r\n\tstd::time_t end_time = std::chrono::system_clock::to_time_t(date_time3);\r\n\tchar str_time[26];\r\n\tctime_s(str_time, sizeof str_time, &end_time);\r\n\r\n\tstd::cout << \"Program finnished after \";\r\n\ttime_print(mseconds, seconds, minutes, hours);\r\n\tstd::cout << std::endl;\r\n\tstd::cout << \"Output data saved to binary files: data.bin and dim_data.bin\" << std::endl;\r\n\r\n\treturn 0;\r\n}", "meta": {"hexsha": "c539f7d7be8dd983f59d0e034aa4e3c9e49afafb", "size": 61312, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AE_LE_master.cpp", "max_stars_repo_name": "eriktoller/AE_LE_crack", "max_stars_repo_head_hexsha": "e8d8c067da2fd1d184e8926b8075fe9f58e3250e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AE_LE_master.cpp", "max_issues_repo_name": "eriktoller/AE_LE_crack", "max_issues_repo_head_hexsha": "e8d8c067da2fd1d184e8926b8075fe9f58e3250e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AE_LE_master.cpp", "max_forks_repo_name": "eriktoller/AE_LE_crack", "max_forks_repo_head_hexsha": "e8d8c067da2fd1d184e8926b8075fe9f58e3250e", "max_forks_repo_licenses": ["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.2142857143, "max_line_length": 247, "alphanum_fraction": 0.5420472338, "num_tokens": 20282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.6442251133170356, "lm_q1q2_score": 0.4990060751417248}}
{"text": "#include \"potgen.hpp\"\n#include \"global.hpp\"\n#include \"profiling.hpp\"\n#include \"dynamic_grid.hpp\"\n#include \"fft.hpp\"\n#include \"multiindex.hpp\"\n#include \"discretize.hpp\"\n#include \"randomize.hpp\"\n\n#include <array>\n#include <cmath>\n#include <cassert>\n#include <future>\n#include <iostream>\n#include <boost/throw_exception.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n\n// defined here so can be inlined\ninline double pow_small(double base, int exponent)\n{\n    switch(exponent)\n    {\n        case 0:\n            return 1;\n        case 1:\n            return base;\n        case 2:\n            return base*base;\n        case 3:\n            return base*base*base;\n        default:\n            return std::pow(base, exponent);\n    }\n}\n\n// -------------------------------------------------------------------------------------------------------------\n// calculate the derivative in position space if the fourier transform is given\n// this assumes that the original function was defined inside [-1, 1]^N\n/// takes order_per_dir by value to make calling from multiple threads easier.\n/// threads safe, if \\p f_k is not changed when function is run, otherwise undefined behaviour\ndefault_grid calculateDerivative( std::vector<int> order_per_dir, const complex_grid& f_k )\n{\n    std::size_t dimension = f_k.getDimension();\n    // argument checks\n    if(order_per_dir.size() != f_k.getDimension())\n    THROW_EXCEPTION( std::invalid_argument, \"derivation index %1% count does not match data dimension %2%\", order_per_dir.size(), f_k.getDimension() );\n\n    /// \\todo maybe just enable fft access and disable after the function...\n    if( f_k.getAccessMode() != TransformationType::FFT_INDEX )\n    THROW_EXCEPTION( std::invalid_argument, \"grid is not in fft index mode\" );\n\n    /// \\todo this might throw. Catch and generate more detailed error message\n    auto der_grid = f_k.clone();\n\n    std::size_t total_order = std::accumulate( std::begin(order_per_dir), std::end(order_per_dir), (size_t)0 );\n    for( unsigned i = 0; i < dimension; ++i)\n    {\n        if(order_per_dir[i] < 0)\n        THROW_EXCEPTION( std::invalid_argument, \"negative order of derivative %1% supplied\", i );\n    }\n\n    // the actual calculation starts here\n    {\n        MultiIndex index( dimension );\n        for(unsigned i = 0; i < dimension; ++i)\n        {\n            // get extents returns unsigned ints, so we need to explicitly convert so singed to apply the unary minus.\n            index.setLowerBoundAt( i, -(int)(f_k.getExtents()[i]/2) );\n            index.setUpperBoundAt( i, (int)f_k.getExtents()[i]/2 );\n        }\n\n\n        PROFILE_BLOCK(\"derivative calculation\");\n        complex_t i_factor = std::pow( complex_t(0, pi), total_order );\n\n        for(index.init() ;index.valid(); ++index)\n        {\n            /// \\todo add comment how/why this works\n            // f'(k) = i k f(k)\n            double r_factor = 1;\n            // this is pushed into another function\n            for(unsigned dir = 0; dir < dimension; ++dir)\n            {\n                // if no derivative in that direction, factor is 1 so no computation needed\n                if(order_per_dir[dir] == 0)\n                    continue;\n\n                r_factor *= pow_small(2*index[dir], order_per_dir[dir]);\n            }\n\n            der_grid(index) *= r_factor * i_factor;\n        }\n    }\n\n    ifft(der_grid);\n\n    default_grid result( f_k.getExtents(), TransformationType::FFT_INDEX );\n    std::transform(der_grid.begin(), der_grid.end(), result.begin(), (double(*)(const complex_t&))&std::real);\n    return std::move(result);\n}\n\n\n// -------------------------------------------------------------------------------------------------------------\n//  first step of potential generation: generate the new potential in k - space\n// -------------------------------------------------------------------------------------------------------------\ncomplex_grid generatePotentialInKSpace( std::vector<std::size_t> sizes, std::vector<double> support, correlation_fn cor_fun, const PGOptions& opt )\n{\n    // create discrete correlation function and fourier transform -> power spectrum\n    // load discretized function data into correlation array\n    auto grid = discretizeFunctionForFFT(sizes, support, cor_fun);\n\n    /// \\todo logging\n\n    // calculate fft of correlation\n    fft(grid);\n\n    // calculate randomize potential in momentum space\n    // potential is square root of power spectrum\n    {\n        PROFILE_BLOCK(\"power spectrum\")\n\n        for(auto& v : grid )\n        {\n            double real = std::real(v);\n            /// \\todo actually measure the error here and return it in PGResult\n            if( real < -1e-5 || std::abs(std::imag(v)) > 1e-5)\n            {\n                THROW_EXCEPTION( std::runtime_error, \"power spectrum contains negative or imaginary components, check correlation function!\" );\n            }\n            // it is faster (and better?) to use v as a nonnegative real here for sqrt calculation\n            v = real < 0 ? 0 : std::sqrt(real);\n        }\n    }\n\n    // randomize phases\n    if( opt.randomize )\n    {\n        randomizePhases(grid, opt.randomSeed);\n    }\n\n    return std::move(grid);\n}\n\n\n// -------------------------------------------------------------------------------------------------------------\n// takes a potential in k-space and calculates all requested derivatives, stores inside a Potential datatype\n/// \\todo write tests for this function\n\nvoid calculateAllDerivatives(Potential &potential, const complex_grid &potential_k, unsigned int max_order)\n{\n    PROFILE_BLOCK(\"calculate all derivatives\");\n\n    typedef std::future<default_grid> f_type;\n    std::vector<f_type> started_tasks;\n    std::vector<MultiIndex> task_orders;\n\n    // calculation function\n    auto calc_deriv = [&potential_k](MultiIndex order)\n    {\n        auto deriv = calculateDerivative(order.getAsVector(), potential_k);\n\n        // use same scale factor as for potential\n        std::size_t vec_element_count = potential_k.getElementCount();\n        double factor = std::sqrt(vec_element_count);\n        scaleVectorBy( deriv, factor );\n        return std::move(deriv);\n    };\n\n    for(MultiIndex order( potential.getDimension(), 0, max_order + 1 ); order.valid(); ++order)\n    {\n        // check total order of derivative\n        std::size_t total_order = order.getAccumulated();\n        if(total_order <= max_order && total_order > 0)\n        {\n            started_tasks.push_back( std::async(std::launch::async, calc_deriv, order) );\n            task_orders.push_back( order );\n        }\n    }\n\n    for(unsigned i = 0; i < task_orders.size(); ++i)\n    {\n        try\n        {\n            potential.setDerivative( task_orders[i], std::move(started_tasks[i].get()) );\n        } catch (const std::bad_alloc& e)\n        {\n            std::cerr << \"bad alloc called in multi threaded derivative calculation. probably ran out of memory. \"\n                    \"retry as sequential calculation to reduce memory footprint.\";\n\n            potential.setDerivative( task_orders[i], std::move( calc_deriv(task_orders[i]) ) );\n        }\n    }\n}\n\n\n// -------------------------------------------------------------------------------------------------------------\n\nPotential generatePotential( std::vector<std::size_t> sizes, std::vector<double> support, const PGOptions& opt )\n{\n    Potential res(sizes, std::vector<double>(sizes.size(), 1.0));\n    res.setCreationInfo(opt.randomSeed, 3, opt.corrlength);\n\n    // setup threads\n    setFFTThreads(opt.numThreads);\n\n    // calculate the potential in k-space\n    auto potential_k = generatePotentialInKSpace(sizes, support, opt.cor_fun, opt);\n\n    // calculate derivatives in k-space\n    calculateAllDerivatives( res, potential_k, opt.maxDerivativeOrder );\n\n    std::size_t vec_element_count = potential_k.getElementCount();\n\n    // calculate potential in position space\n    auto& cpotential_x = potential_k;\n    ifft(cpotential_x);\n\n    // this requires additional memory again\n    /// \\todo actually measure the error here and return it in PGResult\n    double averageComplexPart = 0;\n    double average = 0;\n\n    default_grid potential_x(sizes, TransformationType::IDENTITY);\n\n    auto it = potential_x.begin();\n    for( auto& value : cpotential_x)\n    {\n        *it = std::real(value);\n        ++it;\n\n        average += std::real( value );\n        averageComplexPart += std::imag( value );\n    }\n\n    average /= vec_element_count;\n    averageComplexPart /= vec_element_count;\n\n    // calculate average and shift\n    double variance = 0.0;\n    for( auto& d : potential_x )\n    {\n        d -= average;\n        variance += d*d;\n    }\n\n    if(opt.verbose)\n        std::cout << \"original quality: \" << average << \" \" << variance << \"\\n\";\n    res.scalePotential( std::sqrt(1.0/variance) );\n\n    scaleVectorBy( potential_x, std::sqrt(vec_element_count / variance) );\n    // take scaling into account\n    if( opt.verbose )\n        std::cout << \"the average imaginary component in the result was \" << averageComplexPart * std::sqrt(vec_element_count / variance)<< \"\\n\";\n\n    res.setPotential( std::move(potential_x) );\n\n    res.setSupport( support );\n    return std::move(res);\n}\n\n", "meta": {"hexsha": "d245d518bc04e2e0ee95623ad53ee54b79cd3487", "size": 9167, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/potgen/potgen.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/potgen/potgen.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/potgen/potgen.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": 35.122605364, "max_line_length": 151, "alphanum_fraction": 0.6007417912, "num_tokens": 2018, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.49900607372806105}}
{"text": "#include <emscripten.h>\n#include <emscripten/bind.h> \n#include \"geometrycentral/surface/manifold_surface_mesh.h\"\n#include \"geometrycentral/utilities/mesh_data.h\"\n#include \"geometrycentral/surface/edge_length_geometry.h\"\n#include \"geometrycentral/surface/heat_method_distance.h\"\n#include <Eigen/Core>\n#include <stdio.h>\n#include <iostream>\n\nusing namespace geometrycentral;\nusing namespace geometrycentral::surface;\ntypedef int iptr_t;\ntypedef int dptr_t;\n\n// mesh data\nstatic Eigen::MatrixX3i faces;\nstatic Eigen::MatrixX3d edges;\nstatic EdgeData<double> edgeLengths;\n\n// mesh containers\nstatic std::unique_ptr<ManifoldSurfaceMesh> mesh;\nstatic std::unique_ptr<EdgeLengthGeometry> geometry;\n\n// the Heat Method solver\nstatic std::unique_ptr<HeatMethodDistanceSolver> heatSolver;\n\n// the output vertex data\nstatic VertexData<double> distToSource;\n\n// parameters\nstatic double timeStep = 1.0;\nstatic bool robust = false;\nstatic bool verbose = true;\n\nstd::string getExceptionMessage(intptr_t exceptionPtr) {\n    return std::string(reinterpret_cast<std::exception *>(exceptionPtr)->what());\n}\n\nEMSCRIPTEN_BINDINGS(Bindings) {\n  emscripten::function(\"getExceptionMessage\", &getExceptionMessage);\n};\n\nextern \"C\" {\n\n  EMSCRIPTEN_KEEPALIVE\n  iptr_t allocate_faces(size_t num_faces){\n    faces.resize(num_faces, 3);\n    edges.resize(num_faces, 3);\n    return reinterpret_cast<iptr_t>(&faces(0, 0));\n  }\n  EMSCRIPTEN_KEEPALIVE\n  void set_face(size_t f, size_t idx0, size_t idx1, size_t idx2){\n    faces(f, 0) = idx0;\n    faces(f, 1) = idx1;\n    faces(f, 2) = idx2;\n  }\n  EMSCRIPTEN_KEEPALIVE\n  void set_face_edges(size_t f, double e0, double e1, double e2){\n    edges(f, 0) = e0;\n    edges(f, 1) = e1;\n    edges(f, 2) = e2;\n  }\n  EMSCRIPTEN_KEEPALIVE\n  void print_faces(){\n    std::cout << \"Faces:\\n\" << faces << \"\\n\";\n  }\n  EMSCRIPTEN_KEEPALIVE\n  dptr_t get_edge_ptr(){\n    return reinterpret_cast<dptr_t>(&edges(0, 0));\n  }\n  EMSCRIPTEN_KEEPALIVE\n  void print_edges(){\n    std::cout << \"Edges:\\n\" << edges << \"\\n\";\n  }\n\n  EMSCRIPTEN_KEEPALIVE\n  iptr_t allocate_edges(size_t num_edges){\n    edges.resize(num_edges, 3);\n    return reinterpret_cast<iptr_t>(&edges(0, 0));\n  }\n\n  EMSCRIPTEN_KEEPALIVE\n  void set_verbose(bool v = true){\n    verbose = v;\n  }\n  EMSCRIPTEN_KEEPALIVE\n  void set_quiet(){\n    set_verbose(false);\n  }\n  EMSCRIPTEN_KEEPALIVE\n  void set_time_step(double step){\n    timeStep = step;\n  }\n  EMSCRIPTEN_KEEPALIVE\n  void set_robust(bool flag){\n    robust = flag;\n  }\n\n  EMSCRIPTEN_KEEPALIVE\n  void create_surface_mesh(){\n    // create underlying mesh topology\n    mesh.reset(new ManifoldSurfaceMesh(faces));\n    mesh->compress();\n    if(verbose)\n      mesh->printStatistics();\n  }\n\n  EMSCRIPTEN_KEEPALIVE \n  void precompute(){\n\n    // create implicit geometry using edge lengths and mesh\n    edgeLengths = EdgeData<double>(*mesh);\n    for(size_t i = 0; i < faces.rows(); ++i){\n      if(verbose)\n        printf(\"Setting lengths of face #%zu\\n\", i);\n      Face f = mesh->face(i);\n      if(!f.isTriangle()){\n        printf(\"Face is not a triangle\\n\");\n        return;\n      }\n      Halfedge he = f.halfedge(); edgeLengths[he.edge()] = edges(i, 0);\n      he = he.next(); edgeLengths[he.edge()] = edges(i, 1);\n      he = he.next(); edgeLengths[he.edge()] = edges(i, 2);\n    }\n    if(verbose){\n      std::cout << \"Edges:\\n\" << edgeLengths.raw() << \"\\n\";\n      for(Edge e : mesh->edges()){\n        printf(\"Edge #%zu = %g\\n\", e.getIndex(), edgeLengths[e]);\n      }\n    }\n    geometry.reset(new EdgeLengthGeometry(*mesh, edgeLengths));\n\n    // create heat method distance solver (precomputation happens here)\n    heatSolver.reset(new HeatMethodDistanceSolver(*geometry, timeStep, robust));\n  }\n\n  EMSCRIPTEN_KEEPALIVE\n  dptr_t compute_from_source(size_t srcIndex){\n    const Vertex v = mesh->vertex(srcIndex);\n    distToSource = heatSolver->computeDistance(v);\n\n    if(verbose)\n      printf(\"Returning result pointer\\n\");\n\n    Eigen::VectorXd &mat = distToSource.raw();\n    double* ptr = &mat(0, 0);\n    return reinterpret_cast<dptr_t>(ptr);\n  }\n\n}", "meta": {"hexsha": "3ed87792df857a53153bcfa7325d15f40e6d2b17", "size": 4047, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geodesic-dist/gdist.cpp", "max_stars_repo_name": "xionluhnis/knitsketching", "max_stars_repo_head_hexsha": "3e13670caa911b6d5e3c9c036c0ee15184e7d138", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-08-16T05:19:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-09T17:46:12.000Z", "max_issues_repo_path": "libs/geodesic-dist/gdist.cpp", "max_issues_repo_name": "xionluhnis/knitsketching", "max_issues_repo_head_hexsha": "3e13670caa911b6d5e3c9c036c0ee15184e7d138", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2021-08-25T07:11:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T09:16:05.000Z", "max_forks_repo_path": "libs/geodesic-dist/gdist.cpp", "max_forks_repo_name": "xionluhnis/knitsketching", "max_forks_repo_head_hexsha": "3e13670caa911b6d5e3c9c036c0ee15184e7d138", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-08-12T11:49:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-19T07:51:53.000Z", "avg_line_length": 26.8013245033, "max_line_length": 81, "alphanum_fraction": 0.6849518162, "num_tokens": 1113, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721303, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.49900606985080437}}
{"text": "//\n// Copyright (c) 2016,2018 CNRS\n//\n\n#ifndef __pinocchio_math_fwd_hpp__\n#define __pinocchio_math_fwd_hpp__\n\n#include \"pinocchio/fwd.hpp\"\n#include <math.h>\n#include <boost/math/constants/constants.hpp>\n#include \"pinocchio/math/sincos.hpp\"\n\n#ifdef PINOCCHIO_WITH_CPPAD_SUPPORT\nnamespace boost\n{\n  namespace math\n  {\n    namespace constants\n    {\n      namespace detail\n      {\n        template<typename Scalar>\n        struct constant_pi< CppAD::AD<Scalar> > : constant_pi<Scalar> {};\n        \n#if defined(PINOCCHIO_WITH_CPPADCG_SUPPORT) && defined(PINOCCHIO_WITH_CXX11_SUPPORT)\n        template<typename Scalar>\n        struct constant_pi< CppAD::cg::CG<Scalar> > : constant_pi<Scalar> {};\n#endif\n      }\n    }\n  }\n}\n#endif\n\nnamespace pinocchio\n{\n  ///\n  /// \\brief Returns the value of PI according to the template parameters Scalar\n  ///\n  /// \\tparam Scalar The scalar type of the return pi value\n  ///\n  template<typename Scalar>\n  const Scalar PI()\n  { return boost::math::constants::pi<Scalar>(); }\n  \n  /// The value of PI for double scalar type\n  const double PId = PI<double>();\n  \n  namespace math\n  {\n    using std::fabs;\n    using std::sqrt;\n    using std::atan;\n    using std::acos;\n    using std::asin;\n    using std::pow;\n    using std::cos;\n    using std::sin;\n    \n#ifdef PINOCCHIO_WITH_CPPAD_SUPPORT\n    using CppAD::fabs;\n    using CppAD::sqrt;\n    using CppAD::atan;\n    using CppAD::acos;\n    using CppAD::asin;\n    using CppAD::atan2;\n    using CppAD::pow;\n    using CppAD::cos;\n    using CppAD::sin;\n#else\n    using std::atan2;\n#endif\n  }\n}\n\n#endif //#ifndef __pinocchio_math_fwd_hpp__\n", "meta": {"hexsha": "04b940add52dcf3b9c09ca3e7460e3488f95caf8", "size": 1610, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/math/fwd.hpp", "max_stars_repo_name": "matthieuvigne/pinocchio", "max_stars_repo_head_hexsha": "01f211eceda3ac2e5edc8cf101690afb6f3184d3", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-22T15:42:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-22T15:42:45.000Z", "max_issues_repo_path": "src/math/fwd.hpp", "max_issues_repo_name": "matthieuvigne/pinocchio", "max_issues_repo_head_hexsha": "01f211eceda3ac2e5edc8cf101690afb6f3184d3", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/math/fwd.hpp", "max_forks_repo_name": "matthieuvigne/pinocchio", "max_forks_repo_head_hexsha": "01f211eceda3ac2e5edc8cf101690afb6f3184d3", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-21T09:14:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-21T09:14:26.000Z", "avg_line_length": 20.9090909091, "max_line_length": 84, "alphanum_fraction": 0.6633540373, "num_tokens": 437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.49900606702347655}}
{"text": "#include <CGAL/Exact_predicates_exact_constructions_kernel.h>\n#include <CGAL/iterator.h>\n#include <CGAL/point_generators_2.h>\n\n#include <boost/bind.hpp>\n\ntypedef CGAL::Exact_predicates_exact_constructions_kernel K;\ntypedef K::Point_2                     Point;\ntypedef K::Segment_2                   Segment;\n\ntypedef CGAL::Creator_uniform_2<double,Point>              Pt_creator;\ntypedef CGAL::Random_points_on_segment_2<Point,Pt_creator> P1;\ntypedef CGAL::Random_points_on_circle_2<Point,Pt_creator>  P2;\ntypedef CGAL::Creator_uniform_2< Point, Segment>           Seg_creator;\ntypedef CGAL::Join_input_iterator_2< P1, P2, Seg_creator>  Seg_iterator;\n\nstruct Intersector{\n  typedef CGAL::cpp11::result_of<K::Intersect_2(Segment,Segment)>::type result_type;\n  const Segment& s;\n  K::Intersect_2 intersect;\n\n  Intersector(const Segment& seg): s(seg) {}\n\n  result_type\n  operator() ( const Segment& other) const\n  {\n    return intersect(s, other);\n  }\n};\n\nint main()\n{\n  std::vector<Segment> input;\n\n  // Prepare point generator for the horizontal segment, length 200.\n  P1 p1( Point(-100,0), Point(100,0));\n\n  // Prepare point generator for random points on circle, radius 250.\n  P2 p2( 250);\n\n  // Create segments.\n  Seg_iterator g( p1, p2);\n  std::copy_n( g, 200, std::back_inserter(input));\n\n\n  // splitting results with Dispatch_output_iterator\n  std::vector<Point> points;\n  std::vector<Segment> segments;\n\n  typedef CGAL::Dispatch_output_iterator<\n    std::tuple<Point,Segment>, std::tuple< std::back_insert_iterator<std::vector<Point> >,\n                                               std::back_insert_iterator<std::vector<Segment> > > >\n    Dispatcher;\n\n  Dispatcher disp = CGAL::dispatch_output<Point,Segment>( std::back_inserter(points),\n                                                          std::back_inserter(segments) );\n\n  // intersects the first segment of input with all other segments\n  // The resulting points or segments are written in the vectors with the same names\n  std::transform( input.begin(), input.end(), disp,\n                  Intersector(input.front()) );\n\n\n  std::cout << \"Point intersections: \" << points.size() << std::endl;\n  std::cout << \"Segment intersections: \" << segments.size() << std::endl;\n\n\n  return 0;\n}\n", "meta": {"hexsha": "283fd5b9aada7804969b838c9f505e33ca69dc2e", "size": 2252, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Kernel_23/examples/Kernel_23/intersections.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": "Kernel_23/examples/Kernel_23/intersections.cpp", "max_issues_repo_name": "gaschler/cgal", "max_issues_repo_head_hexsha": "d1fe2afa18da5524db6d4946f42ca4b8d00e0bda", "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": "Kernel_23/examples/Kernel_23/intersections.cpp", "max_forks_repo_name": "gaschler/cgal", "max_forks_repo_head_hexsha": "d1fe2afa18da5524db6d4946f42ca4b8d00e0bda", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-02T11:11:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-02T11:11:36.000Z", "avg_line_length": 32.1714285714, "max_line_length": 99, "alphanum_fraction": 0.6758436945, "num_tokens": 552, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.4990060525643794}}
{"text": "//==================================================================================================\n/*!\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#include <boost/simd/function/scalar/sqrt1pm1.hpp>\n#include <scalar_test.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/minf.hpp>\n#include <boost/simd/constant/nan.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/mone.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/constant/mzero.hpp>\n#include <boost/simd/constant/sqrt_2.hpp>\n#include <boost/simd/constant/eps.hpp>\n#include <boost/simd/constant/halfeps.hpp>\n\nSTF_CASE_TPL (\" sqrt1pm1\",  STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::sqrt1pm1;\n\n  using r_t = decltype(sqrt1pm1(T()));\n\n  // return type conformity test\n  STF_TYPE_IS(r_t, T);\n\n  // specific values tests\n#ifndef BOOST_SIMD_NO_INVALIDS\n  STF_ULP_EQUAL(sqrt1pm1(bs::Inf<T>()), bs::Inf<r_t>(), 0);\n  STF_ULP_EQUAL(sqrt1pm1(bs::Minf<T>()), bs::Nan<r_t>(), 0);\n  STF_ULP_EQUAL(sqrt1pm1(bs::Nan<T>()), bs::Nan<r_t>(), 0);\n#endif\n  STF_ULP_EQUAL(sqrt1pm1(bs::Mone<T>()), bs::Mone<r_t>(), 0);\n  STF_ULP_EQUAL(sqrt1pm1(bs::One<T>()), bs::Sqrt_2<r_t>()-bs::One<r_t>(), 2);\n  STF_ULP_EQUAL(sqrt1pm1(bs::Zero<T>()), bs::Zero<r_t>(), 0);\n  STF_ULP_EQUAL(sqrt1pm1(bs::Eps<T>()), bs::Halfeps<r_t>(), 0.5);\n}\n", "meta": {"hexsha": "6154005534ceca9575f82549efaa4a4172ab8894", "size": 1610, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/scalar/sqrt1pm1.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": "test/function/scalar/sqrt1pm1.cpp", "max_issues_repo_name": "remymuller/boost.simd", "max_issues_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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/function/scalar/sqrt1pm1.cpp", "max_forks_repo_name": "remymuller/boost.simd", "max_forks_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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": 35.7777777778, "max_line_length": 100, "alphanum_fraction": 0.6149068323, "num_tokens": 472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585669110202, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.49900137609057704}}
{"text": "//    Copyright 2017 Rainer Gemulla\n// \n//    Licensed under the Apache License, Version 2.0 (the \"License\");\n//    you may not use this file except in compliance with the License.\n//    You may obtain a copy of the License at\n// \n//        http://www.apache.org/licenses/LICENSE-2.0\n// \n//    Unless required by applicable law or agreed to in writing, software\n//    distributed under the License is distributed on an \"AS IS\" BASIS,\n//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//    See the License for the specific language governing permissions and\n//    limitations under the License.\n/** \\file\n *\n * Illustrates matrix factorization with SGD. We first creates factors and then a data matrix\n * from these factors. THis process ensures that we know the best factorization of the input.\n * We then try to reconstruct the factors using SGD.\n */\n#include <iostream>\n\n#include <boost/math/distributions/normal.hpp>\n#include <boost/random/uniform_real.hpp>\n\n#include <util/evaluation.h>\n#include <util/io.h>\n\n#include <mf/mf.h>\n\nusing namespace std;\nusing namespace mf;\nusing namespace rg;\nusing namespace boost::numeric::ublas;\n\nlog4cxx::LoggerPtr logger(log4cxx::Logger::getLogger(\"main\"));\n\nint main(int argc, char* argv[]) {\n#ifndef NDEBUG\n\tLOG4CXX_WARN(logger, \"Warning: Debug mode activated (runtimes may be slow).\");\n#endif\n\n\t// parameters for the factorization\n\tmf_size_type size1 = 10000;\n\tmf_size_type size2 = 10000;\n\tmf_size_type nnz = 1000000;\n\tdouble sigma = 1; // standard deviation\n\tdouble lambda = 1/sigma/sigma;\n\tmf_size_type r = 10;\n\n\t// parameters for SGD\n\tdouble eps0 = 0.1;\n\tunsigned epochs = 20;\n\tSgdOrder order = SGD_ORDER_WOR;\n\ttypedef UpdateTruncate<UpdateNzsl> Update;\n\ttypedef RegularizeL2 Regularize;\n\ttypedef SumLoss<NzslLoss, L2Loss> Loss;\n\ttypedef NzslLoss TestLoss;\n\tUpdate update = Update(UpdateNzsl(), -10*sigma, 10*sigma); // truncate for numerical stability\n\tRegularize regularize = Regularize(lambda);\n\tLoss loss((NzslLoss()), L2Loss(lambda));\n\tTestLoss testLoss;\n\tmf_size_type testNnz = nnz/100;\n\tBalanceType balanceType = BALANCE_NONE;\n\tBalanceMethod balanceMethod = BALANCE_SIMPLE;\n\n\n\t// generate original factors by sampling from a normal(0,sigma) distribution\n\tRandom32 random; // note: this takes a default seed (not randomized!)\n\tDenseMatrix wIn(size1, r);\n\tDenseMatrixCM hIn(r, size2);\n\tgenerateRandom(wIn, random, boost::normal_distribution<>(0, sigma));\n\tgenerateRandom(hIn, random, boost::normal_distribution<>(0, sigma));\n\n\t// generate a sparse matrix by selecting random entries from the generated factors\n\t// and add small Gaussian noise\n\tSparseMatrix v;\n\tgenerateRandom(v, nnz, wIn, hIn, random);\n\taddRandom(v, random, boost::normal_distribution<>(0, 0.1));\n\tLOG4CXX_INFO(logger, \"Data matrix: \"\n\t\t<< v.size1() << \" x \" << v.size2() << \", \" << v.nnz() << \" nonzeros\");\n\tLOG4CXX_INFO(logger, \"Loss with original factors: \" << loss((FactorizationData<>(v, wIn, hIn))));\n\n\t// create a test matrix (without noise)\n\tSparseMatrix vTest;\n\tgenerateRandom(vTest, testNnz, wIn, hIn, random);\n\tLOG4CXX_INFO(logger, \"Test matrix: \"\n\t\t<< v.size1() << \" x \" << v.size2() << \", \" << vTest.nnz() << \" nonzeros\");\n\n\t// take a small sample and remove empty rows/columns\n\tProjectedSparseMatrix Vsample;\n\tprojectRandomSubmatrix(random, v, Vsample, v.size1()/5, v.size2()/5);\n\tprojectFrequent(Vsample, 0);\n\tLOG4CXX_INFO(logger, \"Sample matrix: \"\n\t\t<< Vsample.data.size1() << \" x \" << Vsample.data.size2()\n\t\t<< \", \" << Vsample.data.nnz() << \" nonzeros\");\n\n\t// generate initial factors by sampling from a uniform[-0.5,0.5] distribution\n\tDenseMatrix w(size1, r);\n\tDenseMatrixCM h(r, size2);\n\tgenerateRandom(w, random, boost::uniform_real<>(-0.5, 0.5));\n\tgenerateRandom(h, random, boost::uniform_real<>(-0.5, 0.5));\n\n\t// initialize the SGD\n\tTimer t;\n\tSgdRunner sgdRunner(random);\n\tSgdJob<Update,Regularize> job(v, w, h, update, regularize, order);\n\tFactorizationData<> testJob(vTest, w, h);\n\tDecayAuto<Update,Regularize,Loss> decay(job, loss, Vsample, eps0, 4);\n\tTrace trace;\n\n\t// print the test loss\n\tLOG4CXX_INFO(logger, \"Initial test loss: \"\n\t\t\t<< testLoss(FactorizationData<>(vTest,w,h)));\n\n\t// run SGD to try to reconstruct the original factors\n\tt.start();\n\tsgdRunner.run(job, loss, epochs, decay, trace, balanceType, balanceMethod, &testJob, &testLoss);\n\tt.stop();\n\tLOG4CXX_INFO(logger, \"Total time: \" << t);\n\n\t// print the test loss\n\tLOG4CXX_INFO(logger, \"Final test loss: \"\n\t\t\t<< testLoss(FactorizationData<>(vTest,w,h)));\n\n\t// write trace to an R file\n\tLOG4CXX_INFO(logger, \"Writing trace to \" << \"/tmp/sgd-trace.R\");\n\ttrace.toRfile(\"/tmp/sgd-trace.R\", \"sgd\");\n\n\treturn 0;\n}\n\n", "meta": {"hexsha": "1e83a71f1d64e0574831584f1e27a5b764e81212", "size": 4646, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/mf/sgd.cc", "max_stars_repo_name": "Hui-Li/DSGDPP", "max_stars_repo_head_hexsha": "0ce5b115bfbed81cee1c39fbfa4a8f67a5e1b72e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2017-01-10T11:39:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-02T23:03:55.000Z", "max_issues_repo_path": "examples/mf/sgd.cc", "max_issues_repo_name": "Hui-Li/DSGDPP", "max_issues_repo_head_hexsha": "0ce5b115bfbed81cee1c39fbfa4a8f67a5e1b72e", "max_issues_repo_licenses": ["Apache-2.0"], "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/mf/sgd.cc", "max_forks_repo_name": "Hui-Li/DSGDPP", "max_forks_repo_head_hexsha": "0ce5b115bfbed81cee1c39fbfa4a8f67a5e1b72e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-10-27T18:40:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-05T15:10:56.000Z", "avg_line_length": 35.196969697, "max_line_length": 98, "alphanum_fraction": 0.713086526, "num_tokens": 1299, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585669110203, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.49900137137000417}}
{"text": "//////////////////////////////////////////////////////////////////////////////\n///   Copyright 2003 and onward LASMEA UMR 6602 CNRS/U.B.P Clermont-Ferrand\n///   Copyright 2009 and onward LRI    UMR 8623 CNRS/Univ Paris Sud XI\n///\n///          Distributed under the Boost Software License, Version 1.0\n///                 See accompanying file LICENSE.txt or copy at\n///                     http://www.boost.org/LICENSE_1_0.txt\n//////////////////////////////////////////////////////////////////////////////\n#ifndef NT2_TOOLBOX_IEEE_FUNCTION_SCALAR_NEXTPOW2_HPP_INCLUDED\n#define NT2_TOOLBOX_IEEE_FUNCTION_SCALAR_NEXTPOW2_HPP_INCLUDED\n#include <nt2/sdk/meta/as_integer.hpp>\n#include <nt2/sdk/constant/real.hpp>\n#include <nt2/sdk/meta/as_integer.hpp>\n#include <nt2/sdk/meta/adapted_traits.hpp>\n#include <boost/fusion/tuple.hpp>\n\n#include <nt2/include/functions/frexp.hpp>\n#include <nt2/include/functions/tofloat.hpp>\n#include <nt2/include/functions/minusone.hpp>\n#include <nt2/include/functions/abs.hpp>\n\n\n/////////////////////////////////////////////////////////////////////////////\n// Implementation when type A0 is arithmetic_\n/////////////////////////////////////////////////////////////////////////////\nNT2_REGISTER_DISPATCH(tag::nextpow2_, tag::cpu_,\n                          (A0),\n                          (arithmetic_<A0>)\n                         )\n\nnamespace nt2 { namespace ext\n{\n  template<class Dummy>\n  struct call<tag::nextpow2_(tag::arithmetic_),\n              tag::cpu_, Dummy> : callable\n  {\n    template<class Sig> struct result;\n    template<class This,class A0>\n      struct result<This(A0)> :\n      meta::as_integer<typename std::tr1::result_of<meta::floating(A0)>::type, signed>{};\n\n    NT2_FUNCTOR_CALL(1)\n    {\n      return nt2::nextpow2(tofloat(a0));\n    }\n  };\n} }\n\n/////////////////////////////////////////////////////////////////////////////\n// Implementation when type A0 is real_\n/////////////////////////////////////////////////////////////////////////////\nNT2_REGISTER_DISPATCH(tag::nextpow2_, tag::cpu_,\n                          (A0),\n                          (real_<A0>)\n                         )\n\nnamespace nt2 { namespace ext\n{\n  template<class Dummy>\n  struct call<tag::nextpow2_(tag::real_),\n              tag::cpu_, Dummy> : callable\n  {\n    template<class Sig> struct result;\n    template<class This,class A0>\n      struct result<This(A0)> :\n      meta::as_integer<typename std::tr1::result_of<meta::floating(A0)>::type, signed>{};\n\n    NT2_FUNCTOR_CALL(1)\n    {\n      typedef typename meta::as_integer<A0, signed>::type int_type;\n      A0 m;\n      int_type p;\n      boost::fusion::tie(m, p) = nt2::frexp(nt2::abs(a0));\n      return (m == Half<A0>())  ? minusone(p) :  p;\n    }\n  };\n} }\n\n#endif\n// modified by jt the 26/12/2010", "meta": {"hexsha": "00c625b5ddb78a058b09da82d1707f6be4c00b2b", "size": 2769, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/ieee/include/nt2/toolbox/ieee/function/scalar/nextpow2.hpp", "max_stars_repo_name": "brycelelbach/nt2", "max_stars_repo_head_hexsha": "73d7e8dd390fa4c8d251c6451acdae65def70e0b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-24T03:35:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T03:35:10.000Z", "max_issues_repo_path": "modules/ieee/include/nt2/toolbox/ieee/function/scalar/nextpow2.hpp", "max_issues_repo_name": "brycelelbach/nt2", "max_issues_repo_head_hexsha": "73d7e8dd390fa4c8d251c6451acdae65def70e0b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/ieee/include/nt2/toolbox/ieee/function/scalar/nextpow2.hpp", "max_forks_repo_name": "brycelelbach/nt2", "max_forks_repo_head_hexsha": "73d7e8dd390fa4c8d251c6451acdae65def70e0b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.6125, "max_line_length": 89, "alphanum_fraction": 0.5258215962, "num_tokens": 611, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585669110202, "lm_q2_score": 0.6825737214979745, "lm_q1q2_score": 0.49900136664943107}}
{"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) 2011 STA Steering Board (space.trajectory.analysis AT gmail.com) ----\n*/\n/*\n------------------ Author: Guillermo Ortega  ----------------------------------------\n May 2011\n\n */\n\n#include \"serviceDistanceRateUnit.h\"\n\n#include <Eigen/Core>\n\nusing namespace Eigen;\n\n#include \"QDebug\"\n\nDialogServiceDistanceRateUnitFrame::DialogServiceDistanceRateUnitFrame( QWidget * parent, Qt::WindowFlags f) : QFrame(parent,f)\n{\n\tsetupUi(this);\n    distanceRateUnitWidget = DialogServiceDistanceRateUnitFrame::comboBoxDistanceRateUnitsChoice;\n    myPastUnits = 0;\n    comboBoxDistanceRateUnitsChoice->setCurrentIndex(myPastUnits);\n}\n\nDialogServiceDistanceRateUnitFrame::~DialogServiceDistanceRateUnitFrame()\n{\n}\n\n\n// Index meaning is as follows:\n// index = 0  is Kilometers/s\n// index = 1  is meters/s\n// index = 2  is centi-meters/s\n// index = 3  is mili-meters/s\n// index = 4 is Astronomical Units/s\n\n\n\n// Matrix coefficients as follows\n//  Km->Km, Km->m, Km->cm, Km->mm, Km->AU,\n//  m->Km,   m->m,  m->cm,  m->mm,  m->AU,\n//  cm->Km, cm->m, cm->cm, cm->mm, cm-> AU,\n//  mm->Km, mm->m, mm->cm, mm->mm, mm->AU,\n//  AU->Km, AU->m, AU->cm, AU->mm, AU->AU\n// The matrice has to be transposed !!\n\n\nstatic double distanceRateConversionMatrixCoeffs[25] =\n{1.0,            0.001,           0.00001,        0.000001,       1.495978707e+08,\n 1000.0,         1.0,             0.01,           0.001,          1.495978707e+11,\n 100000.0,       100.0,           1.0,            0.1,            1.495978707e+13,\n 1000000.0,      1000.0,          10.0,           1.0,            1.495978707e+14,\n 0.6684587e-19,  0.6684587e-12,   0.6684587e-13,  0.6684587e-16,  1.0};\n\nstatic const Matrix<double, 5, 5> distanceRateConversionMatrix(distanceRateConversionMatrixCoeffs);\n\n\n\ndouble DialogServiceDistanceRateUnitFrame::convertDistanceRate(int fromDistanceRateUnit, int toDistanceRateUnit, double distance)\n{\n    double finalDistanceRate = distance * distanceRateConversionMatrix(fromDistanceRateUnit, toDistanceRateUnit);\n    return finalDistanceRate;\n}\n\n\n//// Sets the input distance, the output distance and the current index inside the method\nvoid DialogServiceDistanceRateUnitFrame::setInputDistanceRate(double niceInputDistanceRate)\n{\n    myPastDistanceRate = niceInputDistanceRate;\n}\n\n\n\n// Index meaning is as follows:\n// index = 0  is Kilometers/s\n// index = 1  is meters/s\n// index = 2  is centi-meters/s\n// index = 3  is mili-meters/s\n// index = 4 is Astronomical Units/s\nvoid DialogServiceDistanceRateUnitFrame::on_comboBoxDistanceRateUnitsChoice_currentIndexChanged(int myIndex)\n{\n    myFutureUnits = myIndex;\n    myFutureDistanceRate = convertDistanceRate(myPastUnits, myFutureUnits, myPastDistanceRate);\n    myPastDistanceRate = myFutureDistanceRate;\n    myPastUnits = myFutureUnits;\n    myRealDistanceRateForXMLSchema = convertDistanceRate (myPastUnits, 0, myFutureDistanceRate);\n}\n\n", "meta": {"hexsha": "94252ab20a13b02030623f1eda0a584d6c2ade28", "size": 3591, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sta-src/Services/serviceDistanceRateUnit.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/Services/serviceDistanceRateUnit.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/Services/serviceDistanceRateUnit.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": 33.25, "max_line_length": 129, "alphanum_fraction": 0.701754386, "num_tokens": 1011, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.4989450860328344}}
{"text": "/*    Copyright (c) 2010-2018, Delft University of Technology\n *    All rigths reserved\n *\n *    This file is part of the Tudat. Redistribution and use in source and\n *    binary forms, with or without modification, are permitted exclusively\n *    under the terms of the Modified BSD license. You should have received\n *    a copy of the license with this file. If not, please or visit:\n *    http://tudat.tudelft.nl/LICENSE.\n *\n *    References\n *      Montenbruck, O., Gill, E. Satellite Orbits: Models, Methods, Applications, Springer, 2005.\n *      The Mathworks, Inc. DOPRI78, Symbolic Math Toolbox, 2012.\n *\n *    Notes\n *      All the test for this integrator are based on the data generated using the Symbolic Math\n *      Toolbox (MathWorks, 2012). Ideally, another source of data should be used to complete the\n *      testing.\n *\n *      The single step and full integration error tolerances were picked to be as small as\n *      possible, without causing the tests to fail. These values are not deemed to indicate any\n *      bugs in the code; however, it is important to take these discrepancies into account when\n *      using this numerical integrator.\n *\n */\n\n#define BOOST_TEST_MAIN\n\n#include <boost/make_shared.hpp>\n#include <boost/test/unit_test.hpp>\n\n#include \"Tudat/Mathematics/NumericalIntegrators/rungeKuttaVariableStepSizeIntegrator.h\"\n#include \"Tudat/InputOutput/matrixTextFileReader.h\"\n#include \"Tudat/Mathematics/NumericalIntegrators/numericalIntegrator.h\"\n#include \"Tudat/Mathematics/NumericalIntegrators/reinitializableNumericalIntegrator.h\"\n#include \"Tudat/Mathematics/NumericalIntegrators/rungeKuttaCoefficients.h\"\n#include \"Tudat/Mathematics/NumericalIntegrators/UnitTests/numericalIntegratorTests.h\"\n#include \"Tudat/Mathematics/NumericalIntegrators/UnitTests/numericalIntegratorTestFunctions.h\"\n\n#include \"Tudat/InputOutput/basicInputOutput.h\"\n#include \"Tudat/Mathematics/BasicMathematics/linearAlgebra.h\"\n\n#include <limits>\n#include <string>\n\n#include <Eigen/Core>\n\nnamespace tudat\n{\nnamespace unit_tests\n{\n\nBOOST_AUTO_TEST_SUITE( test_runge_kutta_87_dormand_and_prince_integrator )\n\nusing linear_algebra::flipMatrixRows;\n\nusing numerical_integrators::NumericalIntegratorXdPointer;\nusing numerical_integrators::ReinitializableNumericalIntegratorXdPointer;\nusing numerical_integrators::RungeKuttaVariableStepSizeIntegratorXd;\nusing numerical_integrators::RungeKuttaCoefficients;\n\nusing numerical_integrator_test_functions::computeNonAutonomousModelStateDerivative;\n\n//! Test Runge-Kutta 87 Dormand-Prince integrator using benchmark data from (The MathWorks, 2012).\nBOOST_AUTO_TEST_CASE( testRungeKutta87DormandAndPrinceIntegratorUsingMatlabData )\n{\n    using namespace numerical_integrator_tests;\n\n    // Read in benchmark data (generated using Symbolic Math Toolbox in Matlab\n    // (The MathWorks, 2012)). This data is generated using the DOPRI78 numerical integrator.\n    const std::string pathToForwardIntegrationOutputFile = input_output::getTudatRootPath( )\n            + \"/Mathematics/NumericalIntegrators/UnitTests\"\n            + \"/matlabOutputRungeKutta87DormandPrinceForward.txt\";\n    const std::string pathToDiscreteEventIntegrationOutputFile = input_output::getTudatRootPath( )\n            + \"/Mathematics/NumericalIntegrators/UnitTests\"\n            + \"/matlabOutputRungeKutta87DormandPrinceDiscreteEvent.txt\";\n\n    // Store benchmark data in matrix.\n    const Eigen::MatrixXd matlabForwardIntegrationData =\n            input_output::readMatrixFromFile( pathToForwardIntegrationOutputFile, \",\" );\n    Eigen::MatrixXd matlabBackwardIntegrationData = matlabForwardIntegrationData;\n    flipMatrixRows( matlabBackwardIntegrationData );\n    const Eigen::MatrixXd matlabDiscreteEventIntegrationData =\n            input_output::readMatrixFromFile( pathToDiscreteEventIntegrationOutputFile, \",\" );\n\n    // Set integrator parameters.\n\n    // All of the following parameters are set such that the input data is fully accepted by the\n    // integrator, to determine the steps to be taken.\n    const double zeroMinimumStepSize = std::numeric_limits< double >::epsilon( );\n    const double infiniteMaximumStepSize = std::numeric_limits< double >::infinity( );\n    const double infiniteRelativeErrorTolerance = std::numeric_limits< double >::infinity( );\n    const double infiniteAbsoluteErrorTolerance = std::numeric_limits< double >::infinity( );\n\n    // The following parameters set how the error control mechanism should work.\n    const double relativeErrorTolerance = 1.0e-15;\n    const double absoluteErrorTolerance = 1.0e-15;\n\n    // Case 1: Execute integrateTo() to integrate one step forward in time.\n    {\n        // Declare integrator with all necessary settings.\n        NumericalIntegratorXdPointer integrator\n                = std::make_shared< RungeKuttaVariableStepSizeIntegratorXd >(\n                    RungeKuttaCoefficients::get( RungeKuttaCoefficients::rungeKutta87DormandPrince ),\n                    &computeNonAutonomousModelStateDerivative,\n                    matlabForwardIntegrationData( FIRST_ROW, TIME_COLUMN_INDEX ),\n                    ( Eigen::VectorXd( 1 )\n                      << matlabForwardIntegrationData( FIRST_ROW,\n                                                       STATE_COLUMN_INDEX ) ).finished( ),\n                    zeroMinimumStepSize,\n                    infiniteMaximumStepSize,\n                    infiniteRelativeErrorTolerance,\n                    infiniteAbsoluteErrorTolerance );\n\n        executeOneIntegrateToStep( matlabForwardIntegrationData, 1.0e-15, integrator );\n    }\n\n    // Case 2: Execute performIntegrationStep() to perform multiple integration steps until final\n    //         time.\n    {\n        // Declare integrator with all necessary settings.\n        NumericalIntegratorXdPointer integrator\n                = std::make_shared< RungeKuttaVariableStepSizeIntegratorXd >(\n                    RungeKuttaCoefficients::get( RungeKuttaCoefficients::rungeKutta87DormandPrince ),\n                    &computeNonAutonomousModelStateDerivative,\n                    matlabForwardIntegrationData( FIRST_ROW, TIME_COLUMN_INDEX ),\n                    ( Eigen::VectorXd( 1 )\n                      << matlabForwardIntegrationData( FIRST_ROW,\n                                                       STATE_COLUMN_INDEX ) ).finished( ),\n                    zeroMinimumStepSize,\n                    infiniteMaximumStepSize,\n                    infiniteRelativeErrorTolerance,\n                    infiniteAbsoluteErrorTolerance );\n\n        performIntegrationStepToSpecifiedTime( matlabForwardIntegrationData,\n                                               1.0e-15, 1.0e-15, integrator );\n    }\n\n    // Case 3: Execute performIntegrationStep() to perform multiple integration steps until initial\n    //         time (backwards).\n    {\n        // Declare integrator with all necessary settings.\n        NumericalIntegratorXdPointer integrator\n                = std::make_shared< RungeKuttaVariableStepSizeIntegratorXd >(\n                    RungeKuttaCoefficients::get( RungeKuttaCoefficients::rungeKutta87DormandPrince ),\n                    &computeNonAutonomousModelStateDerivative,\n                    matlabBackwardIntegrationData( FIRST_ROW, TIME_COLUMN_INDEX ),\n                    ( Eigen::VectorXd( 1 )\n                      << matlabBackwardIntegrationData( FIRST_ROW,\n                                                        STATE_COLUMN_INDEX ) ).finished( ),\n                    zeroMinimumStepSize,\n                    infiniteMaximumStepSize,\n                    infiniteRelativeErrorTolerance,\n                    infiniteAbsoluteErrorTolerance );\n\n        performIntegrationStepToSpecifiedTime( matlabBackwardIntegrationData,\n                                               1.0e-15, 1.0e-14, integrator );\n    }\n\n    // Case 4: Execute integrateTo() to integrate to specified time in one step.\n    {\n        // Note that this test has a strange issue that the if the absolute error tolerance is set\n        // to 1.0e-15, the last step that the integrateTo() function takes does not result in the\n        // expected final time of 1.0. As a temporary solution, the absolute error tolerance has\n        // been multiplied by 10.0, which seems to solve the problem. This error indicated a\n        // possible problem with the implementation of the integrateTo() function, which needs to\n        // be investigated in future.\n\n        // Declare integrator with all necessary settings.\n        NumericalIntegratorXdPointer integrator\n                = std::make_shared< RungeKuttaVariableStepSizeIntegratorXd >(\n                    RungeKuttaCoefficients::get( RungeKuttaCoefficients::rungeKutta87DormandPrince ),\n                    &computeNonAutonomousModelStateDerivative,\n                    matlabForwardIntegrationData( FIRST_ROW, TIME_COLUMN_INDEX ),\n                    ( Eigen::VectorXd( 1 )\n                      << matlabForwardIntegrationData( FIRST_ROW,\n                                                       STATE_COLUMN_INDEX ) ).finished( ),\n                    zeroMinimumStepSize,\n                    infiniteMaximumStepSize,\n                    relativeErrorTolerance,\n                    absoluteErrorTolerance * 10.0 );\n\n        executeIntegrateToToSpecifiedTime( matlabForwardIntegrationData, 1.0e-15, integrator,\n                                           matlabForwardIntegrationData(\n                                               matlabForwardIntegrationData.rows( ) - 1,\n                                               TIME_COLUMN_INDEX ) );\n    }\n\n    // Case 5: Execute performIntegrationstep() to integrate to specified time in multiple steps,\n    //         including discrete events.\n    {\n        // Declare integrator with all necessary settings.\n        ReinitializableNumericalIntegratorXdPointer integrator\n                = std::make_shared< RungeKuttaVariableStepSizeIntegratorXd >(\n                    RungeKuttaCoefficients::get( RungeKuttaCoefficients::rungeKutta87DormandPrince ),\n                    &computeNonAutonomousModelStateDerivative,\n                    matlabForwardIntegrationData( FIRST_ROW, TIME_COLUMN_INDEX ),\n                    ( Eigen::VectorXd( 1 )\n                      << matlabForwardIntegrationData( FIRST_ROW,\n                                                       STATE_COLUMN_INDEX ) ).finished( ),\n                    zeroMinimumStepSize,\n                    infiniteMaximumStepSize,\n                    infiniteRelativeErrorTolerance,\n                    infiniteAbsoluteErrorTolerance );\n\n        performIntegrationStepToSpecifiedTimeWithEvents( matlabDiscreteEventIntegrationData,\n                                                         1.0e-15, 1.0e-12, integrator );\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END( )\n\n} // namespace unit_tests\n} // namespace tudat\n", "meta": {"hexsha": "e46f11df1693159d791e2d310cc988198ec975d3", "size": 10825, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Mathematics/NumericalIntegrators/UnitTests/unitTestRungeKutta87DormandPrinceIntegrator.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/Mathematics/NumericalIntegrators/UnitTests/unitTestRungeKutta87DormandPrinceIntegrator.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/Mathematics/NumericalIntegrators/UnitTests/unitTestRungeKutta87DormandPrinceIntegrator.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.5841121495, "max_line_length": 101, "alphanum_fraction": 0.6686374134, "num_tokens": 2258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.49894508095359763}}
{"text": "//==================================================================================================\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#include <boost/simd/function/ifrexp.hpp>\n#include <boost/simd/constant/nbmantissabits.hpp>\n#include <boost/simd/constant/halfeps.hpp>\n#include <scalar_test.hpp>\n\nnamespace bs = boost::simd;\nnamespace bd = boost::dispatch;\n\nSTF_CASE_TPL(\"Check basic behavior of ifrexp\", STF_IEEE_TYPES)\n{\n  STF_EXPR_IS ( (bs::ifrexp(T(0)))\n              , (std::pair<T,bd::as_integer_t<T,signed>>)\n              );\n\n  auto p = bs::ifrexp(T(1));\n  STF_EQUAL(p.first  , T(0.5));\n  STF_EQUAL(p.second , T(1));\n}\n\nSTF_CASE_TPL(\"Check behavior of ifrexp on Zero\", STF_IEEE_TYPES)\n{\n  auto r = bs::ifrexp(T(0));\n\n  STF_EQUAL (r.first , T(0));\n  STF_EQUAL (r.second, T(0));\n  STF_EQUAL (ldexp(r.first,r.second), T(0));\n}\n\nSTF_CASE_TPL(\"Check behavior of ifrexp on Valmax\", STF_IEEE_TYPES)\n{\n  auto r = bs::ifrexp(bs::Valmax<T>());\n\n  STF_ULP_EQUAL (r.first , T(1)-bs::Halfeps<T>(), 1);\n  STF_EQUAL     (r.second, bs::Limitexponent<T>());\n  STF_EQUAL     (ldexp(r.first,r.second),bs::Valmax<T>());\n}\n", "meta": {"hexsha": "b1facdaab98c476b04607e5c28a05e3c6c419e5a", "size": 1359, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/scalar/ifrexp.regular.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": "test/function/scalar/ifrexp.regular.cpp", "max_issues_repo_name": "remymuller/boost.simd", "max_issues_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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/function/scalar/ifrexp.regular.cpp", "max_forks_repo_name": "remymuller/boost.simd", "max_forks_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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.2, "max_line_length": 100, "alphanum_fraction": 0.565857248, "num_tokens": 379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.757794360334681, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.49894507882977335}}
{"text": "// In KAI C++ 3.2c, restrict causes problems for copy propagation.\n// Temporary kludge is to disable use of the restrict keyword.\n\n#define BZ_DISABLE_RESTRICT\n\n#include <blitz/vector.h>\n#include <blitz/array.h>\n#include <blitz/rand-uniform.h>\n#include <blitz/benchext.h>\n\n#ifdef BENCHMARK_VALARRAY\n#include <valarray>\n#endif\n\nBZ_USING_NAMESPACE(blitz)\n\n#ifdef BZ_FORTRAN_SYMBOLS_WITH_TRAILING_UNDERSCORES\n #define fdaxpy   fdaxpy_\n #define f90daxpy f90daxpy_\n #define fidaxpy  fidaxpy_\n #define fidaxpyo fidaxpyo_\n#endif\n\n#ifdef BZ_FORTRAN_SYMBOLS_CAPS\n #define fdaxpy   FDAXPY\n #define f90daxpy F90DAXPY\n #define fidaxpy  FIDAXPY\n #define fidaxpyo FIDAXPYO\n#endif\n\nextern \"C\" {\n  void fdaxpy(const int& N, const double& da, double* x,\n    const int& xstride, const double* y, const int& ystride);\n\n  void f90daxpy(const double& a, double* x, \n    const double* y, const int& length, const int& iters);\n\n  void fidaxpy(const double& a, double* x, const double* y,\n    const int& length, const int& iters);\n\n  void fidaxpyo(const double& a, double* x, const double* y,\n    const int& length, const int& iters);\n}\n\nvoid daxpyVectorVersion(BenchmarkExt<int>& bench, double a, double b);\nvoid daxpyArrayVersion(BenchmarkExt<int>& bench, double a);\nvoid daxpyF77Version(BenchmarkExt<int>& bench, double a);\nvoid daxpyBLASVersion(BenchmarkExt<int>& bench, double a);\nvoid daxpyF90Version(BenchmarkExt<int>& bench, double a);\n\n#ifdef BENCHMARK_VALARRAY\nvoid daxpyValarrayVersion(BenchmarkExt<int>& bench, double a);\n#endif\n\nint main()\n{\n\n#ifdef BENCHMARK_VALARRAY\n    int numBenchmarks = 6;\n#else\n    int numBenchmarks = 5;\n#endif\n\n    BenchmarkExt<int> bench(\"DAXPY Benchmark\", numBenchmarks);\n\n    const int numSizes = 19;\n    bench.setNumParameters(numSizes);\n    bench.setRateDescription(\"Mflops/s\");\n\n    Vector<int> parameters(numSizes);\n    Vector<long> iters(numSizes);\n    Vector<double> flops(numSizes);\n\n    for (int i=0; i < numSizes; ++i)\n    {\n        parameters[i] = pow(10.0, (i+1)/4.0);\n        iters[i] = 50000000L / parameters[i];\n        if (iters[i] < 2)\n            iters[i] = 2;\n        flops[i] = 2 * parameters[i] * 2;\n    }\n\n    bench.setParameterVector(parameters);\n    bench.setIterations(iters);\n    bench.setOpsPerIteration(flops);\n\n    bench.beginBenchmarking();\n\n    float a = .398498293819823;\n\n    daxpyVectorVersion(bench, a, -a);\n    daxpyArrayVersion(bench, a);\n    daxpyF77Version(bench, a);\n    daxpyBLASVersion(bench, a);\n    daxpyF90Version(bench, a);\n\n#ifdef BENCHMARK_VALARRAY\n    daxpyValarrayVersion(bench, a);\n#endif\n\n    bench.endBenchmarking();\n\n    bench.saveMatlabGraph(\"daxpy2.m\");\n\n    return 0;\n}\n\nvoid initializeRandomDouble(double* data, int numElements, int stride = 1)\n{\n    static Random<Uniform> rnd;\n\n    for (int i=0; i < numElements; ++i)\n        data[i*stride] = rnd.random();\n}\n\ntemplate<class T>\nvoid initializeArray(T& array, int numElements)\n{\n    static Random<Uniform> rnd;\n\n    for (size_t i=0; i < numElements; ++i)\n        array[i] = rnd.random();\n}\n\nvoid daxpyVectorVersion(BenchmarkExt<int>& bench, double a, double b)\n{\n    bench.beginImplementation(\"Vector<T>\");\n\n    while (!bench.doneImplementationBenchmark())\n    {\n        int N = bench.getParameter();\n\n        cout << \"Vector<T>: N = \" << N << endl;\n        cout.flush();\n\n        long iters = bench.getIterations();\n\n        Vector<double> x(N), y(N);\n        initializeRandomDouble(x.data(), N);\n        initializeRandomDouble(y.data(), N);\n\n        bench.start();\n        for (long i=0; i < iters; ++i)\n        { \n            y += a * x;\n            y += b * x;\n        }\n        bench.stop();\n    }\n\n    bench.endImplementation();\n}\n\n\nvoid daxpyArrayVersion(BenchmarkExt<int>& bench, double a)\n{\n    bench.beginImplementation(\"Array<T,1>\");\n\n    while (!bench.doneImplementationBenchmark())\n    {\n        int N = bench.getParameter();\n\n        cout << \"Array<T,1>: N = \" << N << endl;\n        cout.flush();\n\n        long iters = bench.getIterations();\n\n        Array<double,1> x(N), y(N);\n        initializeRandomDouble(x.data(), N);\n        initializeRandomDouble(y.data(), N);\n\n        double b = - a;\n\n        bench.start();\n        for (long i=0; i < iters; ++i)\n        {\n            y += a * x;\n            y += b * x;\n        }\n        bench.stop();\n    }\n\n    bench.endImplementation();\n}\n\nvoid daxpyF77Version(BenchmarkExt<int>& bench, double a)\n{\n    bench.beginImplementation(\"Fortran 77\");\n\n    while (!bench.doneImplementationBenchmark())\n    {\n        int N = bench.getParameter();\n\n        cout << \"Fortran 77: N = \" << N << endl;\n        cout.flush();\n\n        int iters = bench.getIterations();\n\n        double* x = new double[N];\n        double* y = new double[N];\n        initializeRandomDouble(x, N);\n        initializeRandomDouble(y, N);\n\n        bench.start();\n        fidaxpy(a, x, y, N, iters);\n        bench.stop();\n\n        delete [] x;\n        delete [] y;\n    }\n\n    bench.endImplementation();\n}\n\n\nvoid daxpyBLASVersion(BenchmarkExt<int>& bench, double a)\n{\n    bench.beginImplementation(\"Fortran BLAS\");\n\n    while (!bench.doneImplementationBenchmark())\n    {\n        int N = bench.getParameter();\n\n        cout << \"Fortran BLAS: N = \" << N << endl;\n        cout.flush();\n\n        int iters = bench.getIterations();\n\n        double* x = new double[N];\n        double* y = new double[N];\n        initializeRandomDouble(x, N);\n        initializeRandomDouble(y, N);\n\n        int xstride = 1, ystride = 1;\n        double b = - a;\n\n        bench.start();\n        for (long i=0; i < iters; ++i)\n        {\n            fdaxpy(N, a, x, xstride, y, ystride);\n            fdaxpy(N, b, x, xstride, y, ystride);\n        }\n        bench.stop();\n\n        delete [] x;\n        delete [] y;\n    }\n\n    bench.endImplementation();\n}\n\nvoid daxpyF90Version(BenchmarkExt<int>& bench, double a)\n{\n    bench.beginImplementation(\"Fortran 90\");\n\n    while (!bench.doneImplementationBenchmark())\n    {\n        int N = bench.getParameter();\n\n        cout << \"Fortran 90: N = \" << N << endl;\n        cout.flush();\n\n        int iters = bench.getIterations();\n\n        double* x = new double[N];\n        double* y = new double[N];\n        initializeRandomDouble(x, N);\n        initializeRandomDouble(y, N);\n\n        bench.start();\n        f90daxpy(a, x, y, N, iters);\n        bench.stop();\n\n        delete [] x;\n        delete [] y;\n    }\n\n    bench.endImplementation();\n}\n\n#ifdef BENCHMARK_VALARRAY\nvoid daxpyValarrayVersion(BenchmarkExt<int>& bench, double a)\n{\n    bench.beginImplementation(\"valarray<T>\");\n\n    while (!bench.doneImplementationBenchmark())\n    {\n        int N = bench.getParameter();\n\n        cout << \"valarray<T>: N = \" << N << endl;\n        cout.flush();\n\n        long iters = bench.getIterations();\n\n        valarray<double> x(N), y(N);\n        initializeArray(x, N);\n        initializeArray(y, N);\n\n        double b = - a;\n\n        bench.start();\n        for (long i=0; i < iters; ++i)\n        {\n            y += a * x;\n            y += b * x;\n        }\n        bench.stop();\n    }\n\n    bench.endImplementation();\n}\n#endif\n", "meta": {"hexsha": "a84670420474e1519fa3d7c6b4a27b2ba31e3afb", "size": 7074, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depspawn-blitz-0.10/benchmarks/daxpy2.cpp", "max_stars_repo_name": "fraguela/depspawn", "max_stars_repo_head_hexsha": "b5760f4c0d38a1b245ee5274e2ccc5c5fe2d3d45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-04-12T11:05:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T11:10:27.000Z", "max_issues_repo_path": "ibtk/third_party/blitz-0.10/benchmarks/daxpy2.cpp", "max_issues_repo_name": "MSV-Project/IBAMR", "max_issues_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ibtk/third_party/blitz-0.10/benchmarks/daxpy2.cpp", "max_forks_repo_name": "MSV-Project/IBAMR", "max_forks_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_forks_repo_licenses": ["BSD-3-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.6006389776, "max_line_length": 74, "alphanum_fraction": 0.5976816511, "num_tokens": 1896, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.4989450758743609}}
{"text": "#include <cv.h>\n#include <highgui.h>\n#include <cstdlib>\n#include <ctime>\n#include <iostream>\n#include <sstream>\n#include <limits>\n#include <utility>\n#include \"otherheaders.h\"\n\n/// TODO: @Yupeng added\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n#include <Eigen/Sparse>\n\n#include <MatOp/SparseCholesky.h>\n#include <MatOp/SparseGenMatProd.h>\n#include <SymGEigsSolver.h>\n\n// using namespace Eigen;\ntypedef Eigen::SparseMatrix<double> SpMat;\ntypedef Eigen::Triplet<double, double> T;\n\nusing namespace cv;\nusing namespace std;\n\n/* sort pair<int,int> based on first value */\ntypedef std::pair<int, int> mypair;\nbool comparatorPair(const mypair& l, const mypair& r) {\n    return l.first < r.first;\n}\n\nvoid spectralPb(std::vector<Mat*>& sPb, Mat* mPb, Size orig_size, std::string outFile, int nvec) {\n    int ty = mPb->rows;\n    int tx = mPb->cols;\n    /*\n    Mat A1  = mPb->t();\n    int ty = A1.rows;\n    int tx = A1.cols;\n    */\n\n    /*\n    cout << \"========Printing mPb ============\" <<endl;\n    double* ptrData;\n    for (int i = 0; i < mPb->rows; i++) {\n        ptrData = (double*) mPb->ptr(i);\n        for (int j = 0; j < mPb->cols; j++) {\n            cout << ptrData[j] << \",\";\n        }\n        cout << endl;\n    }\n    cout << \"========Ended Printing mPb ============\" <<endl;\n    */\n\n    Mat l1 = Mat::zeros(ty + 1, tx, CV_64F);\n    Mat l2 = Mat::zeros(ty, tx + 1, CV_64F);\n\n    mPb->copyTo(l1(Rect(0, 1, tx, ty)));\n    mPb->copyTo(l2(Rect(1, 0, tx, ty)));\n\n    log_info(\"Setting the sparse symmetric affinity matrix\");\n    vector<double> val;\n    vector<int> I;      /// FIXME: long int or long long int??\n    vector<int> J;      /// FIXME: long int or long long int??\n    vector<double> valD;\n\n    time_t now1, now2, now3, now4, now5, now5a, now5b, now6, now7, now8, now9, now10, now11;\n    time(&now1);\n    buildW(valD, val, I, J, l1, l2);    /// FIXME: check the output order of val I and J\n    time(&now2);\n\n    log_info(\"At the end of buildW: %ld\", now2 - now1);\n\n    /// TODO: @Yupeng uncomment @Manu's display codes\n    /*\n    cout << \"=====Display matrix =======\" << endl;\n    for (int i = 0 ;i < val.size(); i++) {\n        cout << \"(\"<<I.at(i)+1<<\",\" << J.at(i)+1<<\") =  \" << val.at(i) << endl;\n    }\n    cout << \"=====Display ended =======\" << endl;\n    */\n\n    int nnz = val.size();\n    int nnzD1 = valD.size();\n\n    /// FIXME: @Yupeng added\n    log_debug(\"nnz = %d, nnzD1 = %d\", nnz, nnzD1);\n    log_debug(\"ty = %d, tx = %d\", ty, tx);\n\n    assert(val.size() == I.size() && I.size() == J.size());\n\n    int wy = (int) *max_element(I.begin(), I.end());\n    time(&now3);\n    log_info(\"Time for one max: %ld\", now3 - now2);\n    int wx = (int) *max_element(J.begin(), J.end());\n\n    // cout << \"wy = \" << wy << \"wx = \" << wx << endl;\n    int wymin = (int)*min_element(I.begin(), I.end());\n    int wxmin = (int)*min_element(J.begin(), J.end());\n    // cout << \"wymin = \" << wymin << \"wxmin = \" << wxmin << endl;\n    int n = (wy == wx) ? wy + 1 : max(wy, wx) + 1;      /*  added one because indices start from zero */\n\n    double valmin = (double)*min_element(val.begin(), val.end());\n    double valmax = (double)*max_element(val.begin(), val.end());\n\n    time(&now4);\n    log_info(\"Time for all comparisons: %ld\", now4 - now2);\n    // cout << \"valmax = \" << valmax << \" valmin = \" << valmin << endl;\n\n    vector<int> pcol(n + 1, -1);\n    int colInd = 0;\n    pcol.at(colInd) = 0;\n    for (int i = 1; i < nnz; i++) {\n        if (I.at(i) != I.at(i - 1)) pcol.at(++colInd) = i;\n    }\n    pcol.at(++colInd) = nnz;\n\n    time(&now5a);\n\n    log_debug(\"Time pcol: %ld\", now5a - now4);\n\n    /// FIXME: part below commented because of more efficient version above\n    /*\n    vector<int> pcol_old(n + 1, -1);\n    std::vector<int>::iterator it;\n    for (int i = 0; i < n; i++) {\n        fs << \"orig_size\" << orig_size;\n        it = find(I.begin(), I.end(), i);\n        if (it != I.end()) {\n            pcol_old.at(i) = it - I.begin();\n        }\n    }\n    pcol_old.at(n) = nnz;\n    */\n\n    time(&now5);\n    log_debug(\"Time pcol_old: %ld\", now5 - now5a);\n\n    time(&now5b);\n    log_debug(\"Comparison time: %ld\", now5b - now5);\n\n    int nnzD = n;\n    std::vector<double> valDmW(nnz);\n    for (int i = 0; i < nnz; i++) {\n        if (I.at(i) != J.at(i)) {\n            valDmW.at(i) = -val.at(i);\n        }\n        else {\n            /// FIXME: if any element changes to zero\n            valDmW.at(i) = valD.at(I.at(i)) - val.at(i);\n        }\n    }\n\n    time(&now6);\n    log_info(\"Time pcol: %ld\", now6 - now5);\n    std::vector<int> IB;\n    IB.reserve(n);\n    int cnt = 0;\n    std::generate_n(std::back_inserter(IB), n, [cnt]() mutable { return cnt++; });\n\n    time(&now7);\n    log_info(\"Time generate_n: %ld\", now7 - now6);\n    // cout << IB.at(0) << \",\" << IB.at(n - 1) << \",\" << nnzD << endl;\n\n    std::vector<int> JB(IB);\n    JB.push_back(nnzD);\n\n    std::vector<double> valB(nnzD);\n    for (int i = 0; i < nnzD; i++) {\n        valB.at(i) = 0;\n        if (pcol.at(i) != -1)\n            for (int j = pcol[i]; j < pcol[i + 1]; j++) {\n                valB.at(i) += val.at(j);\n            }\n    }\n\n    /*\n    cout << \"=====Display matrix =======\" << endl;\n    for (int i = 0; i < valD.size(); i++) {\n        cout << \"(\"<<IB.at(i)+1<<\",\" << JB.at(i)+1<<\") =  \" << valD.at(i) << endl;\n    }\n    cout << \"=====Display ended =======\" << endl;\n    */\n\n    time(&now8);\n\n    /// FIXME: @Yupeng fixed\n    log_info(\"Before Spectra: %ld\", now8 - now7);\n    log_info(\"Overall orig reported: %ld\", now8 - now2);\n    log_info(\"Setting up matrices D and D-W for Spectra\");\n\n    time(&now9);\n\n    /// FIXME: @Yupeng output for debugging\n    log_info(\"OutFile: %s | ty (rows) = %d, tx (cols) = %d\", outFile.c_str(), ty, tx);\n\n    /* eigenvector computation using Spectra library begins */\n    double* p_eigVals;\n    double* p_eigVec;\n\n    int nD = ty * tx;       /* nrows * ncols */\n    Eigen::SparseMatrix<double> D2mW2(nD, nD);\n    std::vector<T> D2mW2_tripletList;\n    D2mW2_tripletList.reserve(nnz);\n    for (int i = 0; i < nnz; i++) {\n        /* I is rowIdx, J is colIdx, condition \"tempCol >= row\" for push_back of I, J, val */\n        D2mW2_tripletList.push_back(T(J.at(i), I.at(i), valDmW.at(i)));\n    }\n    D2mW2.setFromTriplets(D2mW2_tripletList.begin(), D2mW2_tripletList.end());\n    D2mW2.makeCompressed();\n\n    Eigen::SparseMatrix<double> D2(nD, nD);\n    std::vector<T> D2_tripletList;\n    D2_tripletList.reserve(nD);\n    for (int i = 0; i < nD; i++) {\n        D2_tripletList.push_back(T(i, i, valD.at(i)));\n    }\n    D2.setFromTriplets(D2_tripletList.begin(), D2_tripletList.end());\n    D2.makeCompressed();\n\n    Spectra::SparseGenMatProd<double> opA(D2mW2);\n    Spectra::SparseCholesky<double> opB(D2);\n\n    /// FIXME: @Yupeng maxLabel is something got after watershed\n    // int ncv = (maxLabel < 2*nvec) ? maxLabel : 2*nvec;\n    log_debug(\"Spectra nvec: %d\", nvec);\n    int ncv = 2 * nvec;     /*  nev < ncv <= n (size of matrix) */\n\n    Spectra::SymGEigsSolver<double, Spectra::SMALLEST_MAGN, Spectra::SparseGenMatProd<double>,\n                            Spectra::SparseCholesky<double>, Spectra::GEIGS_CHOLESKY>\n    geigs(&opA, &opB, nvec, ncv);\n\n    geigs.init();\n    int nconv = geigs.compute();\n\n    Eigen::VectorXd evalues;\n    Eigen::MatrixXd evecs;\n    if (geigs.info() == Spectra::SUCCESSFUL) {\n        evalues = geigs.eigenvalues();      /* nvec */\n        evecs = geigs.eigenvectors();       /* (rows, cols) = (nD, nvec) */\n    }\n    else {\n        log_error(\"Geigs is failing\");\n    }\n    log_debug(\"Rows: %ld, Cols: %ld\", evecs.rows(), evecs.cols());\n    stringstream sStream;\n    sStream << evalues;\n    log_debug(\"Generalized eigenvalues found: %s\", sStream.str().c_str());\n    sStream.str(\"\");\n    sStream << evecs.topRows(10);\n    log_debug(\"Generalized eigenvectors found: %s\", sStream.str().c_str());\n\n    log_debug(\"n: %d\", n);\n    log_debug(\"Rows: %ld, Cols: %ld\", evecs.rows(), evecs.cols());\n    log_debug(\"VectorXd size: %ld\", evalues.size());\n\n    /* data interface conversion */\n    p_eigVals = new double[nvec];\n    for (int i = 0; i < nvec; i++) p_eigVals[i] = evalues(i);\n    p_eigVec = new double[n * nvec];    /// TODO: not sure about the conflict between n and nD\n    for (int i = 0; i < nvec; i++) {\n        for (int j = 0; j < nD; j++) {\n            p_eigVec[i * nD + j] = evecs(j, i);\n        }\n    }\n\n    /* eigenvector computation using Spectra library ends */\n\n    std::vector<Mat*> vect(nvec);\n    vect.at(0) = new Mat(ty, tx, CV_64FC1, Scalar::all(0));\n\n    double* data;\n    double minVal, maxVal, minXi, maxXi;\n    Point minLoc, maxLoc;\n    std::string imageName;\n    double alpha, beta;\n    Mat destIm(ty, tx, CV_64FC1);\n    for (int i = 1; i < nvec; i++) {    /* excluding i = 0 */\n        vect.at(i) = new Mat(ty, tx, CV_64FC1);\n        data = (double*)vect.at(i)->data;\n        for (int j = 0; j < n; j++) {\n            data[j] = p_eigVec[i * n + j];\n        }\n        minMaxLoc(*vect.at(i), &minVal, &maxVal, &minLoc, &maxLoc);\n        *(vect.at(i)) -= minVal;\n        *(vect.at(i)) /= maxVal - minVal;   /// FIXME: check order of precedence\n        minMaxLoc(*vect.at(i), &minVal, &maxVal, &minLoc, &maxLoc);\n    }\n\n    /* OE parameters */\n    int hil = 0;\n    int deriv = 1;\n    int support = 3;\n    double sigma = 1.0;\n    int nOrient = 8;\n    double dtheta = PI / nOrient;\n    vector<int> ch_per = {3, 2, 1, 0, 7, 6, 5, 4};\n    double theta = 0.0;\n    sPb.resize(nOrient);\n    /* initilaize sPb */\n    for (int i = 0; i < nOrient; i++) {\n        sPb.at(i) = new Mat(ty, tx, CV_64FC1, Scalar::all(0));\n    }\n\n    log_info(\"Filtering the sPb values\");\n\n    for (int i = 1; i < nvec; i++) {\n        if (p_eigVals[i] >\n            /// TODO: check what happens for zero of smallest eigenvalue\n            std::numeric_limits<double>::epsilon()) {\n            log_debug(\"Eigenvalue %d: %f\", i, p_eigVals[i]);\n            *(vect.at(i)) /= sqrt(p_eigVals[i]);\n            for (int o = 0; o < nOrient; o++) {\n                double theta = dtheta * static_cast<double>(o);\n                /// FIXME: hil not handled and also not required\n                Mat f = oeFilter(sigma, support, theta, deriv, hil);\n                Mat destIm;\n                filter2D(*vect.at(i), destIm, -1, f, Point(-1, -1), 0, BORDER_REFLECT_101);\n                *(sPb.at(ch_per.at(o))) += abs(destIm);\n            }\n        }\n    }\n\n    /// FIXME: @Yupeng comment\n    /*\n    double alpha, beta;\n    for (int i = 0; i < nOrient; i++) {\n        // cout << \"here_seg\" << endl;\n        imageName = outFile + \"_sPb_i_\" + to_string(i) + \".png\";\n        minMaxLoc(*sPb.at(i), &minXi, &maxXi);\n        alpha = 255.0 / (maxXi - minXi);\n        beta = -minXi * 255.0 / (maxXi - minXi);\n        Mat destIm;\n        sPb.at(i)->convertTo(destIm, CV_8U, alpha, beta);\n        imwrite(imageName, destIm);\n    }\n    cout << \"here seg 1\" << endl;\n    */\n\n    /// FIXME: @Yupeng potential memory leak problems\n    delete[] p_eigVals;\n    delete[] p_eigVec;\n}\n", "meta": {"hexsha": "d9356e7ec42b973d830693340c12bf462a7bf31c", "size": 10960, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/spectralPb.cpp", "max_stars_repo_name": "yanyp/UCM-MPI-GPU", "max_stars_repo_head_hexsha": "24f6794820c0efd4e99337030b5051994bea9223", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2018-05-05T03:51:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-30T01:05:33.000Z", "max_issues_repo_path": "src/spectralPb.cpp", "max_issues_repo_name": "yanyp/UCM-MPI-GPU", "max_issues_repo_head_hexsha": "24f6794820c0efd4e99337030b5051994bea9223", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-08-13T08:49:05.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-13T08:49:05.000Z", "max_forks_repo_path": "src/spectralPb.cpp", "max_forks_repo_name": "yanyp/UCM-MPI-GPU", "max_forks_repo_head_hexsha": "24f6794820c0efd4e99337030b5051994bea9223", "max_forks_repo_licenses": ["BSD-3-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.8604651163, "max_line_length": 104, "alphanum_fraction": 0.5373175182, "num_tokens": 3578, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746407, "lm_q2_score": 0.6584175005616829, "lm_q1q2_score": 0.4989450758743609}}
{"text": "#ifndef UTIL_HPP\n#define UTIL_HPP\n\n#include <glog/logging.h>\n#include <gflags/gflags.h>\n\n#include <time.h>\n#include <math.h>\n#include <ctype.h>\n#include <stdlib.h>\n#include <fstream>\n\n// Google Log hack\n#define LR LOG(INFO)<<\"(rank:\"<<ctx_->rank<<\") \"\n\n// Container hack\n#define RANGE(x) ((x).begin()), ((x).end())\n#define SUM(x)   (std::accumulate(RANGE(x), .0))\n\n// Random hack\n#include <chrono>\n#include <random>\n#define CLOCK (std::chrono::system_clock::now().time_since_epoch().count())\nstatic std::mt19937 _rng(CLOCK);\nstatic std::uniform_real_distribution<double> _unif01;\nstatic std::normal_distribution<double> _stdnormal;\n\nstruct ThreadRNG {\n  ThreadRNG() : rng_(CLOCK) {}\n  std::mt19937 rng_;\n  std::uniform_real_distribution<double> unif01_;\n  std::normal_distribution<double> stdnormal_;\n};\n\n// Eigen\n#define EIGEN_INITIALIZE_MATRICES_BY_ZERO\n#define EIGEN_DEFAULT_IO_FORMAT \\\n        Eigen::IOFormat(StreamPrecision,1,\" \",\" \",\"\",\"\",\"[\",\"]\")\n#include <Eigen/Dense>\nusing EMatrix = Eigen::MatrixXd;\nusing EVector = Eigen::VectorXd;\nusing EArray  = Eigen::ArrayXd;\nusing EMAtrix = Eigen::ArrayXXd;\nusing EMatrixMap = Eigen::Map<EMatrix>;\nusing EVectorMap = Eigen::Map<EVector>;\nusing EArrayMap  = Eigen::Map<EArray>;\n\ntemplate<typename T>\nusing TMatrix = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>;\n\ntemplate<typename T>\nstatic void save_matrix(const TMatrix<T>& mat, std::string file) {\n  std::ofstream fout(file); CHECK(fout.good());\n  Eigen::IOFormat space_sep(Eigen::StreamPrecision,0,\" \",\"\\n\",\"\",\"\",\"\",\"\");\n  fout << mat.format(space_sep);\n  fout.close();\n}\n\ntemplate<typename T>\nstatic void load_matrix(TMatrix<T> *mat, std::string file) {\n  std::ifstream fin(file); CHECK(fin.good());\n  int nrows = 0;\n  std::string line;\n  while (std::getline(fin, line)) ++nrows;\n  fin.clear(); fin.seekg(0); // rewind\n  T val;\n  std::vector<T> flat; // row major\n  while (not fin.eof()) {\n    fin >> val;\n    flat.push_back(val);\n  }\n  fin.close();\n  mat->resize(flat.size() / nrows, nrows);\n  memcpy(mat->data(), flat.data(), sizeof(double) * flat.size());\n  mat->transposeInPlace();\n}\n\ntemplate<typename T>\nstatic void rowwise_max_ind(const TMatrix<T>& mat, TMatrix<int> *ind) {\n  int nrows = mat.rows();\n  ind->resize(nrows, 1);\n  for (int i = 0; i < nrows; ++i) {\n    mat.row(i).maxCoeff(ind->data() + i);\n  }\n}\n\n// Multivariate Normal with mean = covariance * v; covariance = inv(precision)\nstatic EVector draw_mvgaussian(const EMatrix& precision, const EVector& v) {\n  Eigen::LLT<EMatrix> chol;\n  chol.compute(precision);\n  EVector alpha = chol.matrixL().solve(v); // alpha = L' * mu\n  EVector mu = chol.matrixU().solve(alpha);\n  EVector z(v.size());\n  for (int i = 0; i < v.size(); ++i)\n    z(i) = _stdnormal(_rng);\n  EVector x = chol.matrixU().solve(z);\n  return mu + x;\n}\n\n// Get monotonic time in seconds from a starting point\nstatic double get_time() {\n  struct timespec start;\n  clock_gettime(CLOCK_MONOTONIC, &start);\n  return (start.tv_sec + start.tv_nsec/1000000000.0);\n}\n\nclass Timer {\npublic:\n  void   tic() { start_ = get_time(); }\n  double toc() { double ret = get_time() - start_; time_ += ret; return ret; }\n  double get() { return time_; }\nprivate:\n  double time_  = .0;\n  double start_ = get_time();\n};\n\n// Google flags hack\nstatic void print_help() {\n  fprintf(stderr, \"Program Flags:\\n\");\n  std::vector<google::CommandLineFlagInfo> all_flags;\n  google::GetAllFlags(&all_flags);\n  for (const auto& flag : all_flags) {\n    if (flag.filename.find(\"src/\") != 0) // HACK: filter out built-in flags\n      fprintf(stderr,\n              \"-%s: %s (%s, default:%s)\\n\",\n              flag.name.c_str(),\n              flag.description.c_str(),\n              flag.type.c_str(),\n              flag.default_value.c_str());\n  }\n  exit(1);\n}\n\n// Google flags hack\nstatic void print_flags() {\n  LOG(INFO) << \"---------------------------------------------------------------------\";\n  std::vector<google::CommandLineFlagInfo> all_flags;\n  google::GetAllFlags(&all_flags);\n  for (const auto& flag : all_flags) {\n    if (flag.filename.find(\"src/\") != 0) // HACK: filter out built-in flags\n      LOG(INFO) << flag.name << \": \" << flag.current_value;\n  }\n  LOG(INFO) << \"---------------------------------------------------------------------\";\n}\n\n// Faster strtol without error checking.\nstatic long int strtol(const char *nptr, char **endptr) {\n  // Skip spaces\n  while (isspace(*nptr)) ++nptr;\n  // Sign\n  bool is_negative = false;\n  if (*nptr == '-') {\n    is_negative = true;\n    ++nptr;\n  } else if (*nptr == '+') {\n    ++nptr;\n  }\n  // Go!\n  long int res = 0;\n  while (isdigit(*nptr)) {\n    res = (res * 10) + (*nptr - '0');\n    ++nptr;\n  }\n  if (endptr != NULL) *endptr = (char *)nptr;\n  if (is_negative) return -res;\n  return res;\n}\n\n#endif\n", "meta": {"hexsha": "07610662087466719542bf745dc889692ae5c555", "size": 4759, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/strads/apps/medlda_release/util.hpp", "max_stars_repo_name": "daiwei89/wdai_petuum_public", "max_stars_repo_head_hexsha": "4068859897061201d0a63630a3da6011b0d0f75f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2015-07-10T04:23:33.000Z", "max_stars_repo_stars_event_max_datetime": "2017-01-18T09:02:13.000Z", "max_issues_repo_path": "src/strads/apps/medlda_release/util.hpp", "max_issues_repo_name": "daiwei89/wdai_petuum_public", "max_issues_repo_head_hexsha": "4068859897061201d0a63630a3da6011b0d0f75f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-10-09T19:51:57.000Z", "max_issues_repo_issues_event_max_datetime": "2015-10-10T10:09:43.000Z", "max_forks_repo_path": "src/strads/apps/medlda_release/util.hpp", "max_forks_repo_name": "daiwei89/wdai_petuum_public", "max_forks_repo_head_hexsha": "4068859897061201d0a63630a3da6011b0d0f75f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2017-02-17T14:40:51.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-07T06:48:26.000Z", "avg_line_length": 27.9941176471, "max_line_length": 87, "alphanum_fraction": 0.6257617146, "num_tokens": 1316, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.49894506571588715}}
{"text": "/**\n * vector_mutator_test.cc\n * Copyright 2016 John Lawson\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 \"vector_mutator.h\"\n\n#include \"gtest/gtest.h\"\n#include \"qv/quiver_matrix.h\"\n\n#include <armadillo>\n\nnamespace refl {\nnamespace {\nusing Matrix = arma::Mat<int>;\n}\nTEST(VecMut, A2) {\n\tMatrix a = { { 2, 1 }, { 1, 2 } };\n\tcluster::QuiverMatrix q(\"{ { 0 1 } { -1 0 } }\");\n\tVectorMutator vm(q, a);\n\tarma::mat vecs = { { 0, 1 }, { 1, 0 } };\n\tarma::mat res(2, 2);\n\tvm.mutate(vecs, 0, res);\n\tarma::mat exp = { { 0, 1 }, { 1, 0 } };\n\tEXPECT_TRUE(arma::all(arma::all(exp == res)));\n\n\tarma::mat res2(2, 2);\n\tvm.mutate(vecs, 1, res2);\n\tarma::mat exp2 = { { -1, 1 }, { 1, 0 } };\n\tEXPECT_TRUE(arma::all(arma::all(exp2 == res2)));\n}\nTEST(VecMut, A3) {\n\tMatrix a = { { 2, 1, -1 }, { 1, 2, 1 }, { -1, 1, 2 } };\n\tcluster::QuiverMatrix q(\"{ { 0 1 0 } { -1 0 1 } { 0 -1 0 } }\");\n\tVectorMutator vm(q, a);\n\tarma::mat vecs = { { 1, 0, 0 }, { 0, 1, 0 }, { 0, 0, 1 } };\n\tarma::mat res(3, 3);\n\tvm.mutate(vecs, 0, res);\n\tarma::mat exp = vecs;\n\tEXPECT_TRUE(arma::all(arma::all(exp == res)));\n\n\tarma::mat res2(3, 3);\n\tvm.mutate(vecs, 1, res2);\n\tarma::mat exp2 = { { 1, 0, 0 }, { -1, 1, 0 }, { 0, 0, 1 } };\n\tEXPECT_TRUE(arma::all(arma::all(exp2 == res2)));\n\n\tarma::mat res3(3, 3);\n\tvm.mutate(vecs, 2, res3);\n\tarma::mat exp3 = { { 1, 0, 0 }, { 0, 1, 0 }, { 0, -1, 1 } };\n\tEXPECT_TRUE(arma::all(arma::all(exp2 == res2)));\n}\nTEST(VecMut, A3signs) {\n\tMatrix a = { { 2, -1, -1 }, { -1, 2, -1 }, { -1, -1, 2 } };\n\tcluster::QuiverMatrix q(\"{ { 0 1 0 } { -1 0 1 } { 0 -1 0 } }\");\n\tVectorMutator vm(q, a);\n\tarma::mat vecs = { { 1, 0, 0 }, { 0, 1, 0 }, { 0, 0, 1 } };\n\tarma::mat res(3, 3);\n\tvm.mutate(vecs, 0, res);\n\tarma::mat exp = vecs;\n\tEXPECT_TRUE(arma::all(arma::all(exp == res)));\n\n\tarma::mat res2(3, 3);\n\tvm.mutate(vecs, 1, res2);\n\tarma::mat exp2 = { { 1, 0, 0 }, { 1, 1, 0 }, { 0, 0, 1 } };\n\tEXPECT_TRUE(arma::all(arma::all(exp2 == res2)));\n\n\tarma::mat res3(3, 3);\n\tvm.mutate(vecs, 2, res3);\n\tarma::mat exp3 = { { 1, 0, 0 }, { 0, 1, 0 }, { 0, 1, 1 } };\n\tEXPECT_TRUE(arma::all(arma::all(exp2 == res2)));\n}\n}\n", "meta": {"hexsha": "d8d5623c5ef29504cb1f67a1cccf5d82d39a1f69", "size": 2605, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/vector_mutator_test.cc", "max_stars_repo_name": "jwlawson/qvrefl", "max_stars_repo_head_hexsha": "e843c48837949c5bb76d66959530e7cd55fec0ec", "max_stars_repo_licenses": ["Apache-2.0"], "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/vector_mutator_test.cc", "max_issues_repo_name": "jwlawson/qvrefl", "max_issues_repo_head_hexsha": "e843c48837949c5bb76d66959530e7cd55fec0ec", "max_issues_repo_licenses": ["Apache-2.0"], "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/vector_mutator_test.cc", "max_forks_repo_name": "jwlawson/qvrefl", "max_forks_repo_head_hexsha": "e843c48837949c5bb76d66959530e7cd55fec0ec", "max_forks_repo_licenses": ["Apache-2.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.0119047619, "max_line_length": 75, "alphanum_fraction": 0.5692898273, "num_tokens": 1049, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.757794360334681, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.49894505851282644}}
{"text": "//\n// Created by kellerberrin on 19/4/21.\n//\n\n\n#include \"kol_OntologyTypes.h\"\n#include \"kol_InformationAncestorMean.h\"\n\n#include \"kol_SetUtilities.h\"\n#include \"kol_Accumulators.h\"\n\n\n#include <boost/accumulators/statistics/max.hpp>\n\n\nnamespace kol = kellerberrin::ontology;\n\n\n//! A method for calculating the shared infromation between two concepts.\n/*!\n  This method returns the shared information between two concepts.\n*/\ndouble kol::InformationAncestorMean::sharedInformation(const std::string &termA, const std::string &termB) const  {\n  // return 0 for any terms not in the datbase\n  if (not ic_map_ptr_->validateTerms(termA, termB)) {\n\n    return 0.0;\n\n  }\n\n  Accumulators::MeanAccumulator meanIC;\n\n  OntologySetType<std::string> ancestorsA = graph_ptr_->getSelfAncestorTerms(termA);\n  OntologySetType<std::string> ancestorsB = graph_ptr_->getSelfAncestorTerms(termB);\n\n  OntologySetType<std::string> sharedAncestors = SetUtilities::setIntersection(ancestorsA, ancestorsB);\n\n  for (auto const &term : sharedAncestors) {\n\n    meanIC(ic_map_ptr_->termInformation(term));\n\n  }\n\n  return Accumulators::extractMean(meanIC);\n\n}\n\n", "meta": {"hexsha": "0309ebaf1ee215ef3e2504f7621fc227ce36b4b8", "size": 1128, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kol_ontology/kol_InformationAncestorMean.cpp", "max_stars_repo_name": "kellerberrin/KGL_Gene", "max_stars_repo_head_hexsha": "f8e6c14b8b2009d82d692b28354561b5f0513c5e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-09T16:24:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-09T16:24:06.000Z", "max_issues_repo_path": "kol_ontology/kol_InformationAncestorMean.cpp", "max_issues_repo_name": "kellerberrin/KGL_Gene", "max_issues_repo_head_hexsha": "f8e6c14b8b2009d82d692b28354561b5f0513c5e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kol_ontology/kol_InformationAncestorMean.cpp", "max_forks_repo_name": "kellerberrin/KGL_Gene", "max_forks_repo_head_hexsha": "f8e6c14b8b2009d82d692b28354561b5f0513c5e", "max_forks_repo_licenses": ["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.5, "max_line_length": 115, "alphanum_fraction": 0.7562056738, "num_tokens": 294, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.49892194881452023}}
{"text": "/*******************************************************************************\n * Copyright (c) 2018-, UT-Battelle, LLC.\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the MIT License \n * which accompanies this distribution. \n *\n * Contributors:\n *   Alexander J. McCaskey - initial API and implementation\n *   Thien Nguyen - implementation\n *******************************************************************************/\n#include \"qsim_utils.hpp\"\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n#include <Eigen/QR>\n#include <cassert>\nnamespace qcor {\nnamespace QuaSiMo {\nstd::shared_ptr<CostFunctionEvaluator>\ngetEvaluator(Operator *observable, const HeterogeneousMap &params) {\n  // If an evaluator was provided explicitly:\n  if (params.pointerLikeExists<CostFunctionEvaluator>(\"evaluator\")) {\n    return xacc::as_shared_ptr(\n        params.getPointerLike<CostFunctionEvaluator>(\"evaluator\"));\n  }\n\n  // Cost Evaluator was provided by name:\n  if (params.stringExists(\"evaluator\")) {\n    return getObjEvaluator(observable, params.getString(\"evaluator\"));\n  }\n\n  // No specific evaluator/evaluation method was requested,\n  // use the default one (partial tomography based).\n  return getObjEvaluator(observable);\n}\n\nPronyResult pronyFit(const std::vector<std::complex<double>> &in_signal) {\n  assert(!in_signal.empty());\n\n  // Returns the Hankel matrix constructed from the first column c, and\n  // (optionally) the last row r.\n  auto hankelMat =\n      [](const std::vector<std::complex<double>> &c,\n         const std::vector<std::complex<double>> &r) -> Eigen::MatrixXcd {\n    Eigen::MatrixXcd result = Eigen::MatrixXcd::Zero(c.size(), r.size());\n    const auto m = c.size();\n    for (int i = 0; i < result.rows(); ++i) {\n      for (int j = 0; j < result.cols(); ++j) {\n        // H(i,j) = c(i+j),  i+j < m;\n        if (i + j < m) {\n          result(i, j) = c[i + j];\n        } else {\n          // H(i,j) = r(i+j+1-m),  otherwise\n          result(i, j) = r[i + j + 1 - m];\n        }\n      }\n    }\n\n    return result;\n  };\n\n  // Pythonic vector slice:\n  auto vectorSlice = [](const std::vector<std::complex<double>> &in_vec,\n                        int in_start, int in_end) {\n    std::vector<std::complex<double>> result;\n    auto startIter = in_vec.begin() + in_start;\n    auto endIter =\n        in_end > 0 ? in_vec.begin() + in_end : (in_vec.end() + in_end);\n    result.assign(startIter, endIter);\n    return result;\n  };\n\n  const size_t num_freqs = in_signal.size() / 2;\n  auto hankel0 = hankelMat(vectorSlice(in_signal, 0, num_freqs),\n                           vectorSlice(in_signal, num_freqs - 1, -1));\n  auto hankel1 = hankelMat(vectorSlice(in_signal, 1, num_freqs + 1),\n                           vectorSlice(in_signal, num_freqs, 0));\n  // std::cout << \"Hankel Matrix 0: \\n\" << hankel0 << \"\\n\";\n  // std::cout << \"Hankel Matrix 1: \\n\" << hankel1 << \"\\n\";\n\n  hankel0.transposeInPlace();\n  hankel1.transposeInPlace();\n  Eigen::MatrixXcd shift_matrix =\n      Eigen::MatrixXcd::Zero(hankel0.cols(), hankel1.cols());\n\n  for (size_t i = 0; i < hankel1.cols(); ++i) {\n    Eigen::VectorXcd shift_matrix_col =\n        hankel0.fullPivHouseholderQr().solve(hankel1.col(i));\n    shift_matrix.col(i) = shift_matrix_col;\n  }\n  // std::cout << \"Shift matrix: \\n\" << shift_matrix << \"\\n\";\n\n  shift_matrix.transposeInPlace();\n  Eigen::ComplexEigenSolver<Eigen::MatrixXcd> s(shift_matrix);\n  auto phases = s.eigenvalues();\n  Eigen::MatrixXcd generation_matrix =\n      Eigen::MatrixXcd::Zero(in_signal.size(), phases.size());\n  for (int i = 0; i < generation_matrix.rows(); ++i) {\n    for (int j = 0; j < generation_matrix.cols(); ++j) {\n      generation_matrix(i, j) = std::pow(phases[j], i);\n    }\n  }\n\n  auto signalData = in_signal;\n  Eigen::VectorXcd signal =\n      Eigen::Map<Eigen::VectorXcd>(signalData.data(), signalData.size());\n  Eigen::VectorXcd amplitudes =\n      generation_matrix.fullPivHouseholderQr().solve(signal);\n  assert(phases.size() == amplitudes.size());\n  // std::cout << \"Amplitude:\\n\" << amplitudes << \"\\n\";\n  // std::cout << \"Phases:\\n\" << phases << \"\\n\";\n  PronyResult finalResult;\n  for (size_t i = 0; i < phases.size(); ++i) {\n    finalResult.emplace_back(std::make_pair(amplitudes(i), phases(i)));\n  }\n\n  // Sort by amplitude:\n  std::sort(finalResult.begin(), finalResult.end(),\n            [](const auto &a, const auto &b) {\n              return std::abs(a.first) < std::abs(b.first);\n            });\n\n  return finalResult;\n}\n} // namespace QuaSiMo\n} // namespace qcor", "meta": {"hexsha": "b12f110f11dea3cc4c076fa79c01179b893b8405", "size": 4561, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/quasimo/impls/utils/qsim_utils.cpp", "max_stars_repo_name": "vetter/qcor", "max_stars_repo_head_hexsha": "6f86835737277a26071593bb10dd8627c29d74a3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 59.0, "max_stars_repo_stars_event_min_datetime": "2019-08-22T18:40:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:12:42.000Z", "max_issues_repo_path": "lib/quasimo/impls/utils/qsim_utils.cpp", "max_issues_repo_name": "vetter/qcor", "max_issues_repo_head_hexsha": "6f86835737277a26071593bb10dd8627c29d74a3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 137.0, "max_issues_repo_issues_event_min_datetime": "2019-09-13T15:50:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-06T14:19:46.000Z", "max_forks_repo_path": "lib/quasimo/impls/utils/qsim_utils.cpp", "max_forks_repo_name": "vetter/qcor", "max_forks_repo_head_hexsha": "6f86835737277a26071593bb10dd8627c29d74a3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2019-07-08T17:30:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-03T16:24:12.000Z", "avg_line_length": 36.488, "max_line_length": 81, "alphanum_fraction": 0.6103924578, "num_tokens": 1229, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4989219441107211}}
{"text": "#include \"TriangleMuscleConstraint.h\"\n#include <Eigen/SVD>\n#include <Eigen/Sparse>\n#include <Eigen/Geometry>\n#include <iostream>\n\nusing namespace FEM;\nTriangleMuscleConstraint::\nTriangleMuscleConstraint(double stiffness,const Eigen::Vector2d& fiber_direction,int i0,int i1,int i2,double area,const Eigen::Matrix2d& invDm)\n\t:Constraint(stiffness),mFiberDirection(fiber_direction),\n\tmi0(i0),mi1(i1),mi2(i2),mArea(area),mInvDm(invDm),mActivationLevel(0.0)\n{\n\n}\nint\nTriangleMuscleConstraint::\nGetDof()\n{\n\treturn 1;\n}\n\nvoid\nTriangleMuscleConstraint::\nEvaluateJMatrix(int index, std::vector<Eigen::Triplet<double>>& J_triplets)\n{\n\tEigen::MatrixXd Ai(3,9);\n\n\tEigen::Vector2d v = mInvDm*mFiberDirection;\n\n\tAi<<\n\t\t-v[0]-v[1],0,0,v[0],0,0,v[1],0,0,\n\t\t0,-v[0]-v[1],0,0,v[0],0,0,v[1],0,\n\t\t0,0,-v[0]-v[1],0,0,v[0],0,0,v[1];\n\n\tEigen::MatrixXd MuAiT = mStiffness*mArea*Ai.transpose();\n\n\tint idx[3] = {mi0,mi1,mi2};\n\n\tfor(int i=0;i<3;i++)\n\t{\n\t\tJ_triplets.push_back(Eigen::Triplet<double>(3*idx[i]+0, 3*(index)+0, MuAiT(3*i+0,0)));\n\t\tJ_triplets.push_back(Eigen::Triplet<double>(3*idx[i]+0, 3*(index)+1, MuAiT(3*i+0,1)));\n\t\tJ_triplets.push_back(Eigen::Triplet<double>(3*idx[i]+0, 3*(index)+2, MuAiT(3*i+0,2)));\n\t\tJ_triplets.push_back(Eigen::Triplet<double>(3*idx[i]+1, 3*(index)+0, MuAiT(3*i+1,0)));\n\t\tJ_triplets.push_back(Eigen::Triplet<double>(3*idx[i]+1, 3*(index)+1, MuAiT(3*i+1,1)));\n\t\tJ_triplets.push_back(Eigen::Triplet<double>(3*idx[i]+1, 3*(index)+2, MuAiT(3*i+1,2)));\n\t\tJ_triplets.push_back(Eigen::Triplet<double>(3*idx[i]+2, 3*(index)+0, MuAiT(3*i+2,0)));\n\t\tJ_triplets.push_back(Eigen::Triplet<double>(3*idx[i]+2, 3*(index)+1, MuAiT(3*i+2,1)));\n\t\tJ_triplets.push_back(Eigen::Triplet<double>(3*idx[i]+2, 3*(index)+2, MuAiT(3*i+2,2)));\n\t}\n}\nvoid\nTriangleMuscleConstraint::\nEvaluateLMatrix(std::vector<Eigen::Triplet<double>>& L_triplets)\n{\n\tEigen::MatrixXd Ai(3,9);\n\n\tEigen::Vector2d v = mInvDm*mFiberDirection;\n\tAi<<\n\t\t-v[0]-v[1],0,0,v[0],0,0,v[1],0,0,\n\t\t0,-v[0]-v[1],0,0,v[0],0,0,v[1],0,\n\t\t0,0,-v[0]-v[1],0,0,v[0],0,0,v[1];\n\n\tEigen::MatrixXd MuAiTAi = mStiffness*mArea*((Ai.transpose())*Ai);\n\n\tint idx[3] = {mi0,mi1,mi2};\n\tfor(int i =0;i<3;i++)\n\t{\n\t\tfor(int j=0;j<3;j++)\n\t\t{\n\t\t\tL_triplets.push_back(Eigen::Triplet<double>(3*idx[i]+0, 3*idx[j]+0, MuAiTAi(3*i+0, 3*j+0)));\n\t\t\tL_triplets.push_back(Eigen::Triplet<double>(3*idx[i]+0, 3*idx[j]+1, MuAiTAi(3*i+0, 3*j+1)));\n\t\t\tL_triplets.push_back(Eigen::Triplet<double>(3*idx[i]+0, 3*idx[j]+2, MuAiTAi(3*i+0, 3*j+2)));\n\t\t\tL_triplets.push_back(Eigen::Triplet<double>(3*idx[i]+1, 3*idx[j]+0, MuAiTAi(3*i+1, 3*j+0)));\n\t\t\tL_triplets.push_back(Eigen::Triplet<double>(3*idx[i]+1, 3*idx[j]+1, MuAiTAi(3*i+1, 3*j+1)));\n\t\t\tL_triplets.push_back(Eigen::Triplet<double>(3*idx[i]+1, 3*idx[j]+2, MuAiTAi(3*i+1, 3*j+2)));\n\t\t\tL_triplets.push_back(Eigen::Triplet<double>(3*idx[i]+2, 3*idx[j]+0, MuAiTAi(3*i+2, 3*j+0)));\n\t\t\tL_triplets.push_back(Eigen::Triplet<double>(3*idx[i]+2, 3*idx[j]+1, MuAiTAi(3*i+2, 3*j+1)));\n\t\t\tL_triplets.push_back(Eigen::Triplet<double>(3*idx[i]+2, 3*idx[j]+2, MuAiTAi(3*i+2, 3*j+2)));\n\t\t}\n\t}\n}\nvoid\nTriangleMuscleConstraint::\nEvaluateDVector(const Eigen::VectorXd& x)\n{\n\tEigen::Vector3d x0(x.segment<3>(mi0*3));\n\n\tEigen::Matrix32d Ds, P;\n\tDs.col(0) = x.segment<3>(mi1*3) - x0;\n\tDs.col(1) = x.segment<3>(mi2*3) - x0;\n\n\tP.col(0) = Ds.col(0).normalized();\n\tP.col(1) = (Ds.col(1)-Ds.col(1).dot(P.col(0))*P.col(0)).normalized();\n\n\tEigen::Matrix2d F = P.transpose()*Ds*mInvDm;\n\n\tmd = (1.0-mActivationLevel)*P*F*mFiberDirection;\t\n}\nvoid\nTriangleMuscleConstraint::\nGetDVector(int& index,Eigen::VectorXd& d)\n{\n\td.segment<3>(3*(index)) = md;\n\tindex++;\n}", "meta": {"hexsha": "7fd2ebd44b5226fd0812838c916d6fb4633def34", "size": 3590, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sim/fem/Constraint/TriangleMuscleConstraint.cpp", "max_stars_repo_name": "liusida/SoftCon", "max_stars_repo_head_hexsha": "39adcb1e2364dd7583b01966af7038d77977e083", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 140.0, "max_stars_repo_stars_event_min_datetime": "2019-09-05T03:24:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-18T13:44:48.000Z", "max_issues_repo_path": "sim/fem/Constraint/TriangleMuscleConstraint.cpp", "max_issues_repo_name": "liusida/SoftCon", "max_issues_repo_head_hexsha": "39adcb1e2364dd7583b01966af7038d77977e083", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-03-15T14:23:02.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-15T14:23:02.000Z", "max_forks_repo_path": "sim/fem/Constraint/TriangleMuscleConstraint.cpp", "max_forks_repo_name": "liusida/SoftCon", "max_forks_repo_head_hexsha": "39adcb1e2364dd7583b01966af7038d77977e083", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 23.0, "max_forks_repo_forks_event_min_datetime": "2019-09-08T02:51:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T12:49:05.000Z", "avg_line_length": 33.8679245283, "max_line_length": 143, "alphanum_fraction": 0.6601671309, "num_tokens": 1493, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148981, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.49892193940692176}}
{"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_TANH_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_TANH_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n\n    @ingroup group-hyperbolic\n    This function object returns the hyperbolic tangent: \\f$\\sinh(x)/\\cosh(x)\\f$.\n\n    @see sinh, cosh, sech, csch, sinhcosh\n\n\n    @par Header <boost/simd/function/tanh.hpp>\n\n    @par Example:\n\n      @snippet tanh.cpp tanh\n\n    @par Possible output:\n\n      @snippet tanh.txt tanh\n  **/\n  IEEEValue tanh(IEEEValue const& x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/tanh.hpp>\n#include <boost/simd/function/simd/tanh.hpp>\n\n#endif\n", "meta": {"hexsha": "2911bbe3f7946d97397ccb450b4372f86170724e", "size": 1022, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/tanh.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/tanh.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/tanh.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 23.2272727273, "max_line_length": 100, "alphanum_fraction": 0.5714285714, "num_tokens": 236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256313782277, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4989219347031223}}
{"text": "#include <Kokkos_Core.hpp>\n#include <iostream>\n\n#include <boost/program_options.hpp>\n\n#define PI 3.1415926535897932384\n\ntypedef int int_t;\n\n//#include \"Tile3D.h\"\nKOKKOS_FUNCTION double left_flux(double left, double self, double cfl)\n{\n    return -cfl * left + cfl * self;\n}\n\nKOKKOS_FUNCTION double right_flux(double self, double right, double cfl)\n{\n    return -cfl * right + cfl * self;\n}\n\nKOKKOS_FUNCTION double stencil6p(double self, double xm, double xp, double ym,\n    double yp, double zm, double zp, double cfl)\n{\n    return (1.0 - 6.0 * cfl) * self + cfl * (xm + xp + ym + yp + zm + zp);\n}\n\nint main(int argc, char* argv[])\n{\n    double cfl = 0.1;    // must be less than 1/6\n\n    namespace bpo = boost::program_options;\n    bpo::options_description desc(\"ABFT3D\");\n\n    desc.add_options()(\n        \"xsize\", bpo::value<int>()->default_value(98), \"X Dimension\");\n    desc.add_options()(\n        \"ysize\", bpo::value<int>()->default_value(98), \"Y Dimension\");\n    desc.add_options()(\n        \"zsize\", bpo::value<int>()->default_value(98), \"Z Dimension\");\n\n    bpo::variables_map vm;\n\n    // Setup commandline arguments\n    bpo::store(bpo::parse_command_line(argc, argv, desc), vm);\n    bpo::notify(vm);\n\n    int xsize = vm[\"xsize\"].as<int>();\n    int ysize = vm[\"ysize\"].as<int>();\n    int zsize = vm[\"zsize\"].as<int>();\n\n    bool do_check_sum = true;\n\n    Kokkos::initialize(argc, argv);\n    {\n        using range_policy = Kokkos::RangePolicy<>;\n\n        Kokkos::View<double***> stencil_0(\n            \"data1\", xsize + 2, ysize + 2, zsize + 2);\n        Kokkos::View<double***> stencil_1(\n            \"data2\", xsize + 2, ysize + 2, zsize + 2);\n\n        // Soft copy\n        auto stencil_old = stencil_0;\n        auto stencil_new = stencil_1;\n        auto stencil_tmp = stencil_new;\n        Kokkos::View<double*, Kokkos::MemoryTraits<Kokkos::Atomic>> checksum(\n            \"checksum\", 1);\n\n        Kokkos::View<double*, Kokkos::DefaultHostExecutionSpace> hchecksum(\n            \"h_checksum\", 1);\n        hchecksum[0] = 0.;\n\n        Kokkos::deep_copy(checksum, hchecksum);\n\n        // Initialize stencil\n        Kokkos::parallel_for(\n            \"init\", range_policy(0, ysize + 2), KOKKOS_LAMBDA(int j) {\n                for (int k = 0; k < zsize + 2; ++k)\n                {\n                    for (int i = 0; i < xsize + 2; ++i)\n                    {\n                        stencil_old(i, j, k) = std::sin(1.0 * PI * (double) i /\n                            (double) (xsize + 1));    //*\n                        stencil_new(i, j, k) = stencil_old(i, j, k);\n                    }\n                }\n            });\n        Kokkos::fence();\n\n        Kokkos::Timer timer;\n\n        //\n        // How to catch the error ... order matters.  where does the error come from?\n        // Physical location could matter (plus interaction with OS)\n        //\n\n        // Original checksum\n        if (do_check_sum)\n        {\n            Kokkos::parallel_for(\n                \"init_checksum\", range_policy(1, xsize + 1),\n                KOKKOS_LAMBDA(int i) {\n                    for (int j = 1; j <= ysize; ++j)\n                    {\n                        for (int k = 1; k <= zsize; ++k)\n                        {\n                            checksum[0] += stencil_old(i, j, k);\n                        }\n                    }\n                });\n            Kokkos::fence();\n        }\n\n        Kokkos::deep_copy(hchecksum, checksum);\n\n        std::cout << \"Initial Checksum \" << std::scientific << hchecksum[0]\n                  << std::endl;\n\n        double chk_ = 0;\n        for (int its = 0; its < 10; ++its)\n        {\n            if (do_check_sum)\n            {\n                // Deduct the checksum from the boundary\n                Kokkos::parallel_for(\n                    \"first_loop\", range_policy(1, zsize + 1),\n                    KOKKOS_LAMBDA(int k) {\n                        for (int j = 1; j <= ysize; ++j)\n                        {\n                            checksum[0] -= left_flux(stencil_old(0, j, k),\n                                               stencil_old(1, j, k), cfl) +\n                                right_flux(stencil_old(xsize, j, k),\n                                    stencil_old(xsize + 1, j, k), cfl);\n                        }\n                    });\n                Kokkos::fence();\n\n                Kokkos::parallel_for(\n                    \"second_loop\", range_policy(1, zsize + 1),\n                    KOKKOS_LAMBDA(int k) {\n                        for (int i = 1; i <= xsize; ++i)\n                        {\n                            checksum[0] -= left_flux(stencil_old(i, 0, k),\n                                               stencil_old(i, 1, k), cfl) +\n                                right_flux(stencil_old(i, ysize, k),\n                                    stencil_old(i, ysize + 1, k), cfl);\n                        }\n                    });\n                Kokkos::fence();\n\n                Kokkos::parallel_for(\n                    \"third_loop\", range_policy(1, ysize + 1),\n                    KOKKOS_LAMBDA(int j) {\n                        for (int i = 1; i <= xsize; ++i)\n                        {\n                            checksum[0] -= left_flux(stencil_old(i, j, 0),\n                                               stencil_old(i, j, 1), cfl) +\n                                right_flux(stencil_old(i, j, zsize),\n                                    stencil_old(i, j, zsize + 1), cfl);\n                        }\n                    });\n                Kokkos::fence();\n            }\n\n            // Apply stencil\n            // Replace the loops by parallel for\n            //\n            Kokkos::parallel_reduce(\n                \"stencil_op\", range_policy(1, xsize + 1),\n                KOKKOS_LAMBDA(int i, double& chk_) {\n                    for (int j = 1; j <= ysize; ++j)\n                    {\n                        for (int k = 1; k <= zsize; ++k)\n                        {\n                            //std::cout << \"Old \" << i << \" \" << j << \" \" << k << \": \" <<  stencil_old(i,j,k) << std::endl;\n                            stencil_new(i, j, k) = stencil6p(\n                                stencil_old(i, j, k), stencil_old(i - 1, j, k),\n                                stencil_old(i + 1, j, k),\n                                stencil_old(i, j - 1, k),\n                                stencil_old(i, j + 1, k),\n                                stencil_old(i, j, k - 1),\n                                stencil_old(i, j, k + 1), cfl);\n\n                            chk_ += stencil_new(i, j, k);\n                        }\n                    }\n                },\n                chk_);\n            Kokkos::fence();\n\n            // chk_ = 0;\n\n            if (do_check_sum)\n            {\n                Kokkos::deep_copy(hchecksum, checksum);\n\n                // Testing the checksum\n                auto error = std::abs((chk_ - hchecksum[0]));\n\n                std::cout << \"New Checksum \" << std::scientific << chk_\n                          << \" and analytical checksum \" << hchecksum[0]\n                          << \" with Error: \" << error << std::endl;\n\n                if (error > 1e-2)\n                {\n                    std::cout << \"Failed \" << error << std::endl;\n                }\n\n                // Alternate stencil assignment\n                if (its % 2 == 0)\n                {\n                    stencil_old = stencil_1;\n                    stencil_new = stencil_0;\n                }\n                else\n                {\n                    stencil_old = stencil_0;\n                    stencil_new = stencil_1;\n                }\n\n                chk_ = 0.;\n            }\n        }\n\n        double time_taken = timer.seconds();\n\n        std::cout << \"Executed in: \" << time_taken << std::endl;\n    }\n\n    Kokkos::finalize();\n    return 0;\n}", "meta": {"hexsha": "0fd7564e472a5692ca45fa1fb70a865c71d1c345", "size": 7827, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "applications/non-resilient/ABFT3D.cpp", "max_stars_repo_name": "NK-Nikunj/Kokkos-Resilient-Spaces", "max_stars_repo_head_hexsha": "7203d40747d1961286cb4f9ca872354f395ac601", "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": "applications/non-resilient/ABFT3D.cpp", "max_issues_repo_name": "NK-Nikunj/Kokkos-Resilient-Spaces", "max_issues_repo_head_hexsha": "7203d40747d1961286cb4f9ca872354f395ac601", "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": "applications/non-resilient/ABFT3D.cpp", "max_forks_repo_name": "NK-Nikunj/Kokkos-Resilient-Spaces", "max_forks_repo_head_hexsha": "7203d40747d1961286cb4f9ca872354f395ac601", "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.7370689655, "max_line_length": 123, "alphanum_fraction": 0.41459052, "num_tokens": 1870, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4988423771839308}}
{"text": "/**\n * \\file libsanm/tensor_polymat.cpp\n * This file is part of SANM, a symbolic asymptotic numerical solver.\n */\n\n#include \"libsanm/stl.h\"\n#include \"libsanm/tensor_impl_helper.h\"\n\n#include <Eigen/Dense>\n#include <complex>\n#include <functional>\n#include <mutex>\n#include <span>\n\nusing namespace sanm;\n\nnamespace {\n\nusing cfp_t = std::complex<fp_t>;\n\n/*!\n * \\brief compute the DFT of given coeffs using the FFT algorithm\n *\n * Evaluate the polynomial defined by the \\p coeffs at the points \\f$\\omega_n^0,\n * \\ldots, \\omega_n^{n-1}\\f$ where \\f$n\\f$ is \\p nr_term and must be a power of\n * two.\n *\n * \\return the real part and the imaginary part\n */\nstd::pair<TensorArray, TensorArray> fft(const TensorArray& coeffs,\n                                        size_t nr_term) {\n    sanm_assert(!(nr_term & (nr_term - 1)));\n    if (coeffs.size() == 1) {\n        return {TensorArray(nr_term, coeffs[0]),\n                TensorArray(nr_term, coeffs[0].fill_with(0))};\n    }\n    if (nr_term == 1) {\n        TensorND sum = coeffs[0];\n        for (size_t i = 1; i < coeffs.size(); ++i) {\n            sum += coeffs[i];\n        }\n        return {{sum}, {sum.fill_with(0)}};\n    }\n\n    TensorArray coeffs_even, coeffs_odd;\n    coeffs_even.reserve((coeffs.size() + 1) / 2);\n    coeffs_odd.reserve(coeffs.size() / 2);\n    for (size_t i = 0; i < coeffs.size(); i += 2) {\n        coeffs_even.emplace_back(coeffs[i]);\n        if (i + 1 < coeffs.size()) {\n            coeffs_odd.emplace_back(coeffs[i + 1]);\n        }\n    }\n\n    auto result_even = fft(coeffs_even, nr_term / 2),\n         result_odd = fft(coeffs_odd, nr_term / 2);\n\n    TensorArray ret_real(nr_term), ret_imag(nr_term);\n    for (size_t si = 0; si < nr_term / 2; ++si) {\n        const TensorND& a_real = result_even.first[si];\n        const TensorND& a_imag = result_even.second[si];\n        const TensorND& b_real = result_odd.first[si];\n        const TensorND& b_imag = result_odd.second[si];\n\n        for (size_t i : {si, si + nr_term / 2}) {\n            TensorND& y_real = ret_real[i];\n            TensorND& y_imag = ret_imag[i];\n\n            fp_t angle = fp_t(i) * (M_PI * 2) / fp_t(nr_term),\n                 x_real = std::cos(angle), x_imag = std::sin(angle);\n\n            // y = a + x * b\n            y_real.set_shape(coeffs[0].shape());\n            y_imag.set_shape(coeffs[0].shape());\n            as_vector_w(y_real) = as_vector_r(a_real) +\n                                  as_vector_r(b_real) * x_real -\n                                  as_vector_r(b_imag) * x_imag;\n            as_vector_w(y_imag) = as_vector_r(a_imag) +\n                                  as_vector_r(b_imag) * x_real +\n                                  as_vector_r(b_real) * x_imag;\n        }\n    }\n    return {std::move(ret_real), std::move(ret_imag)};\n}\n\nsize_t next_pow2(size_t x) {\n    size_t y = 1;\n    while (y < x) {\n        y <<= 1;\n    }\n    return y;\n}\n\nTensorND compute_polymat_det_coeff_with_fft(const TensorArray& coeffs,\n                                            size_t nr_term_pow2,\n                                            size_t target_order) {\n    std::pair<TensorArray, TensorArray> polymat_dft;\n    {\n        SANM_SCOPED_PROFILER(\"polymat_det_fft\");\n        polymat_dft = fft(coeffs, nr_term_pow2);\n    }\n\n    const size_t batch = coeffs[0].shape(0);\n    const Eigen::Index mdim = coeffs[0].shape(1);\n    ScopedAllowMalloc allow_malloc;\n    Eigen::Matrix<cfp_t, Eigen::Dynamic, Eigen::Dynamic> eigmat(mdim, mdim);\n\n    TensorND ret{TensorShape{batch, 1}};\n    auto ret_ptr = ret.woptr();\n    for (size_t ib = 0; ib < batch; ++ib) {\n        // do the inverse dft to solve the target coefficient\n        cfp_t accum = 0;\n        for (size_t i = 0; i < nr_term_pow2; ++i) {\n            EigenMatDyn mreal{const_cast<fp_t*>(polymat_dft.first[i].ptr()) +\n                                      ib * mdim * mdim,\n                              mdim, mdim},\n                    mimag{const_cast<fp_t*>(polymat_dft.second[i].ptr()) +\n                                  ib * mdim * mdim,\n                          mdim, mdim};\n            eigmat.real() = mreal;\n            eigmat.imag() = mimag;\n            cfp_t dfti = eigmat.determinant();\n            fp_t angle =\n                    -(M_PI * 2) * fp_t(i * target_order) / fp_t(nr_term_pow2);\n            accum += dfti * cfp_t{std::cos(angle), std::sin(angle)};\n        }\n        accum /= fp_t(nr_term_pow2);\n        sanm_assert(std::fabs(accum.imag()) <\n                            1e-4 * std::max<fp_t>(1, std::fabs(accum.real())),\n                    \"IDFT not real: real=%g imag=%g\", accum.real(),\n                    accum.imag());\n        ret_ptr[ib] = accum.real();\n    }\n\n    return ret;\n}\n\nTensorArray transpose_coeffs(const TensorArray& coeffs) {\n    TensorArray ret;\n    ret.resize(coeffs.size());\n    for (size_t i = 0; i < coeffs.size(); ++i) {\n        TensorND& dst = ret[i];\n        const TensorND& src = coeffs[i];\n        sanm_assert(src.rank() == 3);\n        size_t n = src.shape(0), m0 = src.shape(1), m1 = src.shape(2);\n        dst.set_shape({m0, m1, n});\n        EigenMatDyn mdst{dst.woptr(), static_cast<Eigen::Index>(n),\n                         static_cast<Eigen::Index>(m0 * m1)},\n                msrc{const_cast<fp_t*>(src.ptr()),\n                     static_cast<Eigen::Index>(m0 * m1),\n                     static_cast<Eigen::Index>(n)};\n        mdst = msrc.transpose();\n    }\n    return ret;\n}\n\nusing EigenVecArr = std::span<EigenVec>;\n\nvoid conv(EigenVecArr dst, EigenVecArr x, EigenVecArr y) {\n    for (EigenVec& i : dst) {\n        i.setZero();\n    }\n    for (size_t i = 0; i < x.size(); ++i) {\n        for (size_t j = 0; j < y.size() && i + j < dst.size(); ++j) {\n            dst[i + j].array() += x[i].array() * y[j].array();\n        }\n    }\n}\n\nvoid conv_k(size_t k, EigenVec& dst, EigenVecArr x, EigenVecArr y) {\n    bool first = true;\n    for (size_t i = std::max(0, int(k) + 1 - int(y.size()));\n         i < x.size() && i <= k; ++i) {\n        if (first) {\n            dst = x[i].array() * y[k - i].array();\n            first = false;\n        } else {\n            dst.array() += x[i].array() * y[k - i].array();\n        }\n    }\n    if (first) {\n        dst.setZero();\n    }\n}\n\nclass EigenVecArrStorage : public ObjArray<EigenVec> {\npublic:\n    explicit EigenVecArrStorage(size_t size)\n            : ObjArray<EigenVec>(size, nullptr, 0, 1) {}\n};\n\n/*!\n * \\brief Compute a single term in the expansion of determinant\n *\n * The result is the product of mat[i][row_indices[i]]\n * Result is negated if row_indices[0]<0 or row_indices[1]<0\n *\n * \\param coeffs_trans transposed coefficients in (m, m, batch) shape\n * \\param k target term order\n */\nclass DetSingleTermCompute {\n    TensorArray m_coeffs_trans;\n    const size_t m_batch;\n    const size_t m_k;\n    std::unique_ptr<fp_t[]> m_buf_storage;\n    TensorND m_ret;\n    EigenVecArrStorage m_buf0, m_buf1, m_opr0, m_opr1;\n\npublic:\n    DetSingleTermCompute(const TensorArray& coeffs, size_t k)\n            : m_coeffs_trans{transpose_coeffs(coeffs)},\n              m_batch{m_coeffs_trans[0].shape(2)},\n              m_k{k},\n              m_buf_storage{new fp_t[2 * (k + 1) * m_batch]},\n              m_ret{TensorShape{m_batch, 1}},\n              m_buf0{k + 1},\n              m_buf1{k + 1},\n              m_opr0{coeffs.size()},\n              m_opr1{coeffs.size()} {\n        auto ptr = m_buf_storage.get();\n        for (size_t i = 0; i <= k; ++i) {\n            reset(m_buf0[i], ptr + (i * 2) * m_batch, m_batch);\n            reset(m_buf1[i], ptr + (i * 2 + 1) * m_batch, m_batch);\n        }\n    }\n\n    TensorND operator()(std::span<const int> row_indices) {\n        auto extract = [&row_indices, this, msize = m_coeffs_trans[0].shape(1)](\n                               EigenVecArr dst, int r) {\n            for (size_t i = 0; i < m_coeffs_trans.size(); ++i) {\n                size_t c = std::abs(row_indices[r]);\n                reset(dst[i],\n                      m_coeffs_trans[i].ptr() + (r * msize + c) * m_batch,\n                      m_batch);\n            }\n        };\n\n        auto conv_ret = [this, &row_indices](EigenVecArr x, EigenVecArr y) {\n            auto ret_vec = as_vector_w(m_ret);\n            conv_k(m_k, ret_vec, x, y);\n            if (row_indices[0] < 0 || row_indices[1] < 0) {\n                m_ret.inplace_neg();\n            }\n            return m_ret;\n        };\n\n        extract(m_opr0, 0);\n        extract(m_opr1, 1);\n        if (row_indices.size() == 2) {\n            return conv_ret(m_opr0, m_opr1);\n        }\n\n        EigenVecArrStorage *prod = &m_buf0, *prod_next = &m_buf1;\n        conv(*prod, m_opr0, m_opr1);\n\n        for (size_t i = 2; i + 1 < row_indices.size(); ++i) {\n            extract(m_opr0, i);\n            conv(*prod_next, *prod, m_opr0);\n            std::swap(prod, prod_next);\n        }\n        extract(m_opr0, row_indices.size() - 1);\n        return conv_ret(*prod, m_opr0);\n    }\n};\n\n/*!\n * \\brief get the terms in the expansion of determinant\n * \\return vector of size m! * m; the sign of items i*m are the sign of the\n *      terms\n */\nconst std::vector<int>& get_det_terms(size_t m) {\n    static std::mutex mutex;\n    static std::vector<std::vector<int>> results{std::vector<int>{0}};\n    static auto compute = [&](int size) {\n        sanm_assert(results.size() == static_cast<size_t>(size - 1));\n        std::vector<int>& cur = results.emplace_back();\n        const auto& prev = results[size - 2];\n        for (int i = 0; i < size; ++i) {\n            for (size_t j = 0; j < prev.size();) {\n                size_t r0 = cur.size();\n                bool neg = i % 2;\n                cur.push_back(i);\n                for (int jdt = 0; jdt < size - 1; ++jdt) {\n                    int p = prev[j + jdt];\n                    if (p < 0) {\n                        neg = !neg;\n                        p = -p;\n                    }\n                    cur.push_back(p + (p >= i));\n                }\n                if (neg) {\n                    if (cur[r0]) {\n                        cur[r0] = -cur[r0];\n                    } else {\n                        cur[r0 + 1] = -cur[r0 + 1];\n                    }\n                }\n                j += size - 1;\n            }\n        }\n#if 0\n        printf(\"det(%d):\\n\", size);\n        for (size_t i = 0; i < cur.size(); ++i) {\n            printf(\"%d\", cur[i]);\n            if ((i + 1) % size == 0) {\n                printf(\"\\n\");\n            } else {\n                printf(\" \");\n            }\n        }\n#endif\n    };\n\n    sanm_assert(m >= 1);\n    std::lock_guard<std::mutex> mutex_lg{mutex};\n    if (m - 1 < results.size()) {\n        return results[m - 1];\n    }\n    for (size_t i = results.size() + 1; i <= m; ++i) {\n        compute(i);\n    }\n    return results[m - 1];\n}\n\nTensorND compute_polymat_det_coeff_by_expanding(const TensorArray& coeffs,\n                                                size_t target_order) {\n    DetSingleTermCompute tc{coeffs, target_order};\n    size_t m = coeffs[0].shape(1);\n    const auto& terms = get_det_terms(m);\n\n    TensorND ret;\n    for (size_t i = 0; i < terms.size(); i += m) {\n        TensorND cur = tc({terms.data() + i, m});\n        if (!i) {\n            ret = cur;\n        } else {\n            ret += cur;\n        }\n    }\n    return ret;\n}\n}  // anonymous namespace\n\nTensorND sanm::compute_polymat_det_coeff(const TensorArray& coeffs,\n                                         size_t order) {\n    SANM_SCOPED_PROFILER(\"polymat_det\");\n    sanm_assert(!coeffs.empty() && coeffs[0].rank() == 3 &&\n                coeffs[0].shape(1) == coeffs[0].shape(2));\n    for (size_t i = 1; i < coeffs.size(); ++i) {\n        sanm_assert(coeffs[i].shape() == coeffs[0].shape());\n    }\n\n    const size_t batch = coeffs[0].shape(0), mdim = coeffs[0].shape(1),\n                 nr_term = (coeffs.size() - 1) * mdim + 1;\n    sanm_assert(mdim >= 2);\n\n    if (order >= nr_term) {\n        return TensorND{TensorShape{batch, 1}}.fill_with_inplace(0);\n    }\n    if (order == 0) {\n        return coeffs[0].batched_determinant();\n    }\n    if (order == 1) {\n        TensorND ret{TensorShape{batch, 1}},\n                src = coeffs[0].batched_cofactor() * coeffs[1];\n        EigenMatDyn smat{const_cast<fp_t*>(src.ptr()),\n                         static_cast<Eigen::Index>(mdim * mdim),\n                         static_cast<Eigen::Index>(batch)};\n        as_vector_w(ret) = smat.colwise().sum().transpose();\n        return ret;\n    }\n\n    if (mdim <= 4) {\n        return compute_polymat_det_coeff_by_expanding(coeffs, order);\n    }\n\n    return compute_polymat_det_coeff_with_fft(coeffs, next_pow2(nr_term),\n                                              order);\n}\n", "meta": {"hexsha": "97fca3ecfdff01823e49b16ff08ef22058acd184", "size": 12639, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libsanm/tensor_polymat.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/tensor_polymat.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/tensor_polymat.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": 33.2605263158, "max_line_length": 80, "alphanum_fraction": 0.5093757418, "num_tokens": 3455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430353105599, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.49884237467359155}}
{"text": "\n/*=========================================================================\n\n  Program:   Small Body Geophysical Analysis\n  Module:    SBGATSphericalHarmo.hpp\n\n  Class derived from VTK's vtkPolyDataAlgorithm by Benjamin Bercovici  \n\n  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n  All rights reserved.\n  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.\n\n     This software is distributed WITHOUT ANY WARRANTY; without even\n     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n     PURPOSE.  See the above copyright notice for more information.\n\n=========================================================================*/\n/**\n @class  SBGATSphericalHarmo\n @author Benjamin Bercovici\n @author Jay McMahon\n@date October 2018\n @brief  Computes/evaluates the outer spherical harmonics expansion of the exterior gravity\n field around a constant density polyhedron\n\n @details  Computes/evaluates the outer spherical harmonics expansion of the exterior gravity\nfield around a constant density polyhedron. Normalized or non-normalized coefficients can be computed.\nThe computed coefficients are completely independent of the mass and density of the considered object\nas they are only a geometric construct, thanks to the constant-density assumption. This class will always use results expressed in `meters` as their distance unit (e.g accelerations in m/s^2, potentials in m^2/s^2,...) . Unit consistency is enforced through the use of the SetScaleMeters()\nand SetScaleKiloMeters() method. \n\nAdapted from the works of Yu Takahashi and Siamak Hesar by Benjamin Bercovici, University of Colorado Boulder\nfor more details, see \nWerner, R. a. (1997). \nSpherical harmonic coefficients for the potential of a constant-density polyhedron. \nComputers & Geosciences, \n23(10), \n1071\u20131077. \nhttps://doi.org/10.1016/S0098-3004(97)00110-6\n@copyright MIT License, Benjamin Bercovici and Jay McMahon\n*/\n\n#ifndef SBGATSphericalHarmo_h\n#define SBGATSphericalHarmo_h\n\n#include <vtkFiltersCoreModule.h> // For export macro\n#include <vtkPolyDataAlgorithm.h>\n#include <armadillo>\n\nclass VTKFILTERSCORE_EXPORT SBGATSphericalHarmo : public vtkPolyDataAlgorithm{\npublic:\n  /**\n   * Constructs with initial values of zero.\n   */\n  static SBGATSphericalHarmo *New();\n\n  vtkTypeMacro(SBGATSphericalHarmo,vtkPolyDataAlgorithm);\n  void PrintSelf(std::ostream& os, vtkIndent indent) override;\n  void PrintHeader(std::ostream& os, vtkIndent indent) override;\n  void PrintTrailer(std::ostream& os, vtkIndent indent) override;\n\n  /**\n  Sets degree of spherical harmonics expansion\n  @param deg degree of spherical harmonics expansion\n  */\n  void SetDegree(const unsigned int deg){\n    this -> degree = deg;\n    this -> degreeSet = true;\n  }\n\n  /**\n  Sets reference radius in spherical harmonics expansion. Must be consistent \n  with the units in which the shape coordinates are expressed\n  @param ref_radius reference radius in spherical harmonics expansion\n  */\n  void SetReferenceRadius(const double ref_radius){\n    this -> referenceRadius = ref_radius;\n    this -> referenceRadiusSet = true;\n  }\n\n  /**\n  Sets polyhedron density \n  @param density bulk density of polyhedron (kg/m^3)\n  */\n  void SetDensity(const double density){\n    this -> density = density;\n    this -> densitySet = true;\n  }\n\n\n  /*\n  Will return normalized coefficients next (default is normalized)\n  */\n  void IsNormalized(){\n    this -> normalized = true;\n  }\n\n  /*\n  Will return non-normalized coefficients next (default is normalized)\n  */\n  void IsNonNormalized(){\n    this -> normalized = false;\n  }\n\n  /*\n  Return Cnm array of coefficients ordered like in the exemple below where degree = 5\n\n    1     0     0     0    0      0\n  C_10  C_11  C_12  C_13  C_14  C_15\n  C_20  C_21  C_22  C_23  C_24  C_25 \n  C_30  C_31  C_32  C_33  C_34  C_35 \n  C_40  C_41  C_42  C_43  C_44  C_45\n  C_50  C_51  C_52  C_53  C_54  C_55\n\n\n  @return Cnm array of coefficients\n  */\n  arma::mat GetCnm() {this -> Update(); return this -> Cnm;}\n\n\n  /*\n  Return Cnm array of coefficients ordered like in the exemple below where degree = 5\n\n    1     0     0     0    0      0\n  C_10  C_11  C_12  C_13  C_14  C_15\n  C_20  C_21  C_22  C_23  C_24  C_25 \n  C_30  C_31  C_32  C_33  C_34  C_35 \n  C_40  C_41  C_42  C_43  C_44  C_45\n  C_50  C_51  C_52  C_53  C_54  C_55\n\n\n  @param[out] Cnm array of coefficients\n  */\n  void GetCnm(arma::mat & C_nm) {this -> Update(); C_nm = this -> Cnm;}\n\n\n  /*\n  \n  Return Snm array of coefficients ordered like in the exemple below where degree = 5\n\n    0     0     0     0    0      0\n    0  S_11  S_12  S_13  S_14  S_15\n    0  S_21  S_22  S_23  S_24  S_25 \n    0  S_31  S_32  S_33  S_34  S_35 \n    0  S_41  S_42  S_43  S_44  S_45\n    0  S_51  S_52  S_53  S_54  S_55\n\n\n  @return Snm array of coefficients\n  */\n  arma::mat GetSnm() {this -> Update(); return this -> Snm;}\n\n  /*\n  Return Snm array of coefficients ordered like in the exemple below where degree = 5\n\n    0     0     0     0    0      0\n    0  S_11  S_12  S_13  S_14  S_15\n    0  S_21  S_22  S_23  S_24  S_25 \n    0  S_31  S_32  S_33  S_34  S_35 \n    0  S_41  S_42  S_43  S_44  S_45\n    0  S_51  S_52  S_53  S_54  S_55\n\n  @param[out] Snm array of coefficients\n  */\n  void GetSnm(arma::mat & S_nm) {this -> Update(); S_nm = this -> Snm;}\n\n  /**\n  Return the acceleration due to gravity at the specified point\n  @param pos position at which the acceleration must be evaluated (meters)\n  @return acceleration (m / s ^ 2)\n  */\n  arma::vec::fixed<3> GetAcceleration(const arma::vec::fixed<3> & pos);\n\n\n  /** \n  Evaluates the gravity gradient matrix (the partial derivative of the spherical \n  harmonics acceleration with respect to the position vector) at the prescribed\n  location. Note that this gravity gradient matrix is expressed in the body-fixed frame of the considered object.\n  @param[in] pos position at which the gravity gradient matrix must be evaluated, expressed in the same frame/same unit L as \n  the shape used to build the spherical harmonics expansion.\n  @param[out] dAccdPos container holding the gravity gradient matrix (1 / s ^ 2)\n  */\n  void GetGravityGradientMatrix(const arma::vec::fixed<3> & pos,\n    arma::mat::fixed<3,3> & dAccdPos);\n\n\n  /** \n  Evaluates the partial derivative of the spherical harmonics acceleration\n  with respect to the spherical harmonics coefficients. The coefficients and the partials of the acceleration w/r to the coefficients\n  are ordered like so:\n  \n  Cnm :\n(C_00 == 1)  0     0    0     0     0\n  C_10     C_11    0    0     0     0 \n  C_20     C_21  C_22   0     0     0  \n  C_30     C_31  C_32  C_33   0     0  \n  C_40     C_41  C_42  C_43  C_44   0\n  C_50     C_51  C_52  C_53  C_54  C_55\n  \n  Snm :\n  0    0     0     0    0      0\n  0  S_11    0     0    0      0\n  0  S_21  S_22    0    0      0 \n  0  S_31  S_32  S_33   0      0 \n  0  S_41  S_42  S_43  S_44    0\n  0  S_51  S_52  S_53  S_54  S_55\n\n  so \n\n  partial_C = [ dA/C_00,dA/C_10,dA/C_11,dA/C_20,dA/C_21,dA/C_22,...]\n  partial_S = [ dA/S_11,dA/C_21,dA/S_22,dA/S_31,dA/S_32,dA/S_33,...]\n\n  @param[in] pos position at which the partial derivatives must be evaluated, expressed in the same frame/same unit as \n  the shape used to build the spherical harmonics expansion.\n  @param[out] partial_C container holding the partial derivative of the acceleration \n  with respect to the Cnm spherical harmonic coefficients. If the degree/order is n, then there are (n+1) * (n + 2)/2 non-zero Cnm coefficients\n  \n  @param[out] partial_S container holding the partial derivative of the acceleration \n  with respect to the Snm spherical harmonic coefficients. If the degree/order is n, then there are (n+1) * (n + 2)/2 - n non-zero Snm coefficients\n\n  */\n  void GetPartialHarmonics(const arma::vec::fixed<3> & pos,\n    arma::mat & partial_C, \n    arma::mat & partial_S);\n  /**\n  Sets the scale factor to 1, indicative that the polydata has its coordinates expressed in meters\n  */\n  void SetScaleMeters() { this -> scaleFactor = 1; this -> scaleFactorSet = true;}\n\n  /**\n  Sets the scale factor to 1000, indicative that the polydata has its coordinates expressed in kilometers\n  */\n  void SetScaleKiloMeters() { this -> scaleFactor = 1000; this -> scaleFactorSet = true;}\n\n\n  /**\n  Exports the computed spherical harmonics expansion to \n  a JSON file. The saved fields are:\n  - facets == number of facets\n  - vertices == number of vertices\n  - totalMass : {value, unit}\n  - density : {value, unit}\n  - reference_radius : {value, unit}\n  - normalized == true if the coefficients are normalized\n  - degree == degree of the spherical expansion\n  - Cnm_coefs - vector of coefficients triplets {n,m,Cnm}\n  - Snm_coefs - vector of coefficients triplets {n,m,Snm}\n  @param path JSON file where the spherical harmonics model will be saved\n\n  */\n  void SaveToJson(std::string path) const;\n\n  /**\n  Loads a previously computed spherical harmonics expansion\n  from a JSON file. Will set the appropriate fields in the SBGATSphericalHarmo object to\n  allow calls to other methods. \n  The loadable fields are:\n  - facets == number of facets (not needed for evaluation)\n  - vertices == number of vertices (not needed for evaluation)\n  - totalMass : {value, unit}\n  - density : {value, unit}\n  - reference_radius : {value, unit}\n  - normalized == true if the coefficients are normalized\n  - degree == degree of the spherical expansion\n  - Cnm_coefs - vector of coefficients triplets {n,m,Cnm}\n  - Snm_coefs - vector of coefficients triplets {n,m,Snm}\n  @param path JSON file storing the spherical harmonics model\n  */\n  void LoadFromJson(std::string path);\n\n  /**\n  Sets the Cnm coefficients. There is normally no need to use this method outside of Sbgat's tests\n  @param[in] Cnm coefficients\n  */\n  void SetCnm(arma::mat Cnm){this ->Cnm =Cnm;}\n\n  /**\n  Sets the Snm coefficients. There is normally no need to use this method outside of Sbgat's tests\n  @param[in] Snm coefficients\n  */\n  void SetSnm(arma::mat Snm){this ->Snm =Snm;}\n\n\n\nprotected:\n  SBGATSphericalHarmo();\n  ~SBGATSphericalHarmo() override;\n\n  int RequestData(vtkInformation* request,\n    vtkInformationVector** inputVector,\n    vtkInformationVector* outputVector) override;\n\n  arma::mat Cnm;\n  arma::mat Snm;\n\n  double referenceRadius;\n  double density;\n  double totalMass;\n  double scaleFactor = 1;\n\n  bool normalized;\n  unsigned int degree;\n\n  int n_facets;\n  int n_vertices;\n\n  bool degreeSet;\n  bool densitySet;\n  bool referenceRadiusSet;\n  bool scaleFactorSet;\n  bool setFromJSON;\n\nprivate:\n  SBGATSphericalHarmo(const SBGATSphericalHarmo&) = delete;\n  void operator=(const SBGATSphericalHarmo&) = delete;\n};\n\n#endif\n\n\n", "meta": {"hexsha": "626418cc2d286c5866d864033811dcba7f5cc9dc", "size": 10637, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "SbgatCore/include/SbgatCore/SBGATSphericalHarmo.hpp", "max_stars_repo_name": "bbercovici/SBGAT", "max_stars_repo_head_hexsha": "93e935baff49eb742470d7d593931f0573f0c062", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2017-11-29T02:47:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-26T05:25:44.000Z", "max_issues_repo_path": "SbgatCore/include/SbgatCore/SBGATSphericalHarmo.hpp", "max_issues_repo_name": "bbercovici/SBGAT", "max_issues_repo_head_hexsha": "93e935baff49eb742470d7d593931f0573f0c062", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 34.0, "max_issues_repo_issues_event_min_datetime": "2017-02-09T15:38:35.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-25T20:53:37.000Z", "max_forks_repo_path": "SbgatCore/include/SbgatCore/SBGATSphericalHarmo.hpp", "max_forks_repo_name": "bbercovici/SBGAT", "max_forks_repo_head_hexsha": "93e935baff49eb742470d7d593931f0573f0c062", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-03-12T12:20:25.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-12T12:20:25.000Z", "avg_line_length": 33.1370716511, "max_line_length": 289, "alphanum_fraction": 0.6935226098, "num_tokens": 3164, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681086260461, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.49862325260044765}}
{"text": "#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#include <complex>\n#include \"larsson_iccv19.h\"\n#include \"kukelova_iccv13.h\"\n#include \"../misc/univariate.h\"\n#include \"../misc/distortion.h\"\n\nusing namespace Eigen;\nusing namespace radialpose;\nusing std::complex;\n\nstatic const double SMALL_NUMBER = 1e-8;\nstatic const double DAMP_FACTOR = 1e-8;\n\n\n\nstatic void linsolve_known_pose_dist(const Points2D &x, const Points3D &X, double t3, int Np, int Nd, double damp, Camera* camera)\n{\n\tint n_pts = x.cols();\n\tint n_param = 1 + Np + Nd;\n\n\tint n_rows = n_pts;\n\tif (damp > 0)\n\t\tn_rows += n_param - 1;\n\n\t// System matrix for normal equations\n\tEigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> A(n_rows, n_param);\n\tEigen::Matrix<double, Eigen::Dynamic, 1> b(n_rows, 1);\n\tA.setZero();  b.setZero();\n\n\tdouble r_pow[4];\n\tfor (int i = 0; i < n_pts; i++) {\n\n\t\tdouble uu, uv;\n\t\tif (std::abs(x(0, i)) < SMALL_NUMBER) {\n\t\t\tuv = x(1, i);\n\t\t\tuu = X(1, i) / (t3 + X(2, i));\n\t\t}\n\t\telse {\n\t\t\tuv = x(0, i);\n\t\t\tuu = X(0, i) / (t3 + X(2, i));\n\t\t}\n\n\t\t//double rd2 = x(0, i) * x(0, i) + x(1, i) * x(1, i);\n\t\tdouble ru2 = (X(0, i) * X(0, i) + X(1, i) * X(1, i)) / ((X(2, i) + t3) * (X(2, i) + t3));\t\t\t\t\n\n\t\t// compute powers\n\t\tr_pow[0] = ru2;            // r^2\n\t\tr_pow[1] = ru2 * ru2;      // r^4\n\t\tr_pow[2] = ru2 * r_pow[1]; // r^6\n\t\tr_pow[3] = ru2 * r_pow[2]; // r^8\n\n\t\tA(i, 0) = uu;\n\t\tfor (int k = 0; k < Np; k++)\n\t\t\tA(i, 1 + k) = r_pow[k] * uu;\n\t\tfor (int k = 0; k < Nd; k++)\n\t\t\tA(i, 1 + Np + k) = -uv * r_pow[k];\n\t\tb(i) = uv;\n\t}\n\tif (damp > 0) {\n\t\tfor (int i = 1; i < n_param; i++)\n\t\t\tA(n_pts - 1 + i, i) += damp;\n\t}\n\n\t//Eigen::JacobiSVD<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>> svd(A);\t\n\t//std::cout << \"A: \" << A << \"\\n\";\n\t//std::cout << \"svd(A): \" << svd.singularValues() << \"\\n\";\n\n\tEigen::Matrix<double, Eigen::Dynamic, 1> sol = A.fullPivHouseholderQr().solve(b);\n\tcamera->focal = sol(0);\n\tfor (int i = 1; i < n_param; i++) {\n\t\tif (i <= Np)\n\t\t\tcamera->dist_params.push_back(sol(i) / camera->focal);\n\t\telse\n\t\t\tcamera->dist_params.push_back(sol(i));\n\t}\n}\n\nstatic void linsolve_known_pose_undist(const Points2D &x, const Points3D &X, double t3, int Np, int Nd, double damp, Camera* camera)\n{\n\tint n_pts = x.cols();\n\tint n_param = 1 + Np + Nd;\n\n\tint n_rows = n_pts;\n\tif (damp > 0)\n\t\tn_rows += n_param - 1;\n\n\t// System matrix for normal equations\n\tEigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> A(n_rows, n_param);\n\tEigen::Matrix<double, Eigen::Dynamic, 1> b(n_rows, 1);\n\tA.setZero();  b.setZero();\n\n\tdouble r_pow[4];\n\tfor (int i = 0; i < n_pts; i++) {\n\n\t\tdouble uu, uv;\n\t\tif (std::abs(x(0, i)) < SMALL_NUMBER) {\n\t\t\tuv = x(1, i);\n\t\t\tuu = X(1, i) / (t3 + X(2, i));\n\t\t} else {\n\t\t\tuv = x(0, i);\n\t\t\tuu = X(0, i) / (t3 + X(2, i));\n\t\t}\n\n\t\tdouble rd2 = x(0, i) * x(0, i) + x(1, i) * x(1, i);\t\t\n\t\t\t\n\t\t// compute powers\n\t\tr_pow[0] = rd2;            // r^2\n\t\tr_pow[1] = rd2 * rd2;      // r^4\n\t\tr_pow[2] = rd2 * r_pow[1]; // r^6\n\t\tr_pow[3] = rd2 * r_pow[2]; // r^8\n\n\t\tA(i, 0) = uu;\n\t\tfor (int k = 0; k < Np; k++)\n\t\t\tA(i, 1 + k) = -r_pow[k] * uv;\n\t\tfor (int k = 0; k < Nd; k++)\n\t\t\tA(i, 1 + Np + k) = uu * r_pow[k];\n\t\tb(i) = uv;\n\t}\n\tif (damp > 0) {\n\t\tfor (int i = 1; i < n_param; i++)\n\t\t\tA(n_pts - 1 + i, i) += damp;\n\t}\n\n\n\tEigen::Matrix<double, Eigen::Dynamic, 1> sol = A.fullPivHouseholderQr().solve(b);\n\tcamera->focal = sol(0);\n\tdouble f2 = camera->focal * camera->focal;\n\tdouble f2k = f2;\n\t// We have the real mu_k = sol * f^2k and lambda_k = sol * f^2k-1\n\tfor (int i = 1; i < n_param; i++) {\n\t\tif (i == Np+1)\n\t\t\tf2k = camera->focal;\n\t\tcamera->dist_params.push_back(sol(i) * f2k);\n\t\tf2k = f2k * f2;\n\t}\n}\n\n\n// Small refinement on the minimal sample. TODO: Move this to refinement.cc\ntemplate<int Np, int Nd>\nvoid radial_refinement_dist(Camera &p, const Points2D &x, const Points3D &X, double damp_factor) {\n\t// It is assumed that X is already rotated by p\n\tconstexpr int n_pts = std::max(2 + Np + Nd, 5);\n\n\tMatrix<double, 2 * n_pts, 2 + Np + Nd> J;\n\tMatrix<double, 2 * n_pts, 1> res;\n\tMatrix<double, 2 + Np + Nd, 1> dx;\n\n\tfor (int i = 0; i < Np; ++i)\n\t\tp.dist_params[i] *= p.focal;\n\n\tfor (int iter = 0; iter < 5; ++iter) {\n\t\tfor (int i = 0; i < n_pts; ++i) {\n\t\t\tdouble d = X(2, i) + p.t(2);\n\t\t\tdouble d2 = d * d;\n\t\t\tdouble r2 = X.block<2, 1>(0, i).squaredNorm();\n\n\t\t\tdouble num = p.focal;\n\t\t\tdouble denom = d;\n\n\t\t\tdouble dnum_dt = 0.0;\n\t\t\tdouble ddenom_dt = 1.0;\n\n\n\t\t\tfor (int k = 0; k < Np; k++) {\n\t\t\t\tdouble r2d2 = std::pow(r2 / d2, k + 1);\n\n\t\t\t\tnum += p.dist_params[k] * r2d2;\n\t\t\t\tdnum_dt += - p.dist_params[k] * 2 * (k + 1) * r2d2 / d;\n\n\t\t\t}\n\t\t\tfor (int k = 0; k < Nd; k++) {\n\t\t\t\tdouble r2d2 = std::pow(r2 / d2, k + 1);\n\n\t\t\t\tdenom += d * p.dist_params[Np + k] * r2d2;\n\t\t\t\tddenom_dt += -p.dist_params[Np + k] * (2 * k + 1)*r2d2;\n\t\t\t}\n\n\t\t\tdouble factor = num / denom;\n\t\t\tdouble dfactor_dt = (dnum_dt*denom - num * ddenom_dt) / (denom*denom);\n\t\t\tdouble dfactor_df = 1 / denom;\n\n\t\t\tres(2 * i + 0) = factor * X(0, i) - x(0, i);\n\t\t\tres(2 * i + 1) = factor * X(1, i) - x(1, i);\n\n\t\t\tJ(2 * i + 0, 0) = dfactor_dt * X(0, i);\n\t\t\tJ(2 * i + 1, 0) = dfactor_dt * X(1, i);\n\t\t\tJ(2 * i + 0, 1) = dfactor_df * X(0, i);\n\t\t\tJ(2 * i + 1, 1) = dfactor_df * X(1, i);\n\n\t\t\tfor (int k = 0; k < Np; ++k) {\n\t\t\t\tdouble r2d2 = std::pow(r2 / d2, k + 1);\n\t\t\t\tdouble dfactor_dmu = r2d2 / denom;\n\n\t\t\t\tJ(2 * i + 0, 2 + k) = dfactor_dmu * X(0, i);\n\t\t\t\tJ(2 * i + 1, 2 + k) = dfactor_dmu * X(1, i);\n\t\t\t}\n\n\t\t\tfor (int k = 0; k < Nd; ++k) {\n\t\t\t\tdouble r2d2 = std::pow(r2 / d2, k + 1);\n\t\t\t\tdouble dfactor_dlambda = -d * r2d2 * num / (denom*denom);\n\t\t\t\tJ(2 * i + 0, 2 + Np + k) = dfactor_dlambda * X(0, i);\n\t\t\t\tJ(2 * i + 1, 2 + Np + k) = dfactor_dlambda * X(1, i);\n\t\t\t}\n\n\t\t}\n\n\t\tif (res.norm() < SMALL_NUMBER)\n\t\t\tbreak;\n\n\t\t//std::cout << \"res = \" << res << \"\\n\";\n\t\t//std::cout << \"jac = \" << J << \"\\n\";\n\n\t\tMatrix<double, 2 + Np + Nd, 2 + Np + Nd> H = J.transpose()*J;\n\t\tH.diagonal().array() += 1e-6; // LM dampening\n\t\tMatrix<double, 2 + Np + Nd, 1> g = -J.transpose()*res;\n\n\t\tif (Nd > 0 && Np > 0 && damp_factor > 0) {\n\t\t\t// For rational models we add a small dampening factor\t\t\t\n\t\t\tH.template block<Np + Nd,Np + Nd>(2, 2).diagonal().array() += damp_factor;\n\t\t\tfor(int i = 0; i < Np+Nd; i++)\n\t\t\t\tg(2+i) -= damp_factor * p.dist_params[i];\n\t\t}\n\n\n\t\tdx = H.ldlt().solve(g);\n\n\t\tp.t(2) += dx(0);\n\t\tp.focal += dx(1);\n\t\tfor (int i = 0; i < Np; ++i)\n\t\t\tp.dist_params[i] += dx(2 + i);\n\t\tfor (int i = 0; i < Nd; ++i)\n\t\t\tp.dist_params[i + Np] += dx(Np + 2 + i);\n\n\t\tif (dx.array().abs().maxCoeff() < SMALL_NUMBER)\n\t\t\tbreak;\n\t}\n\n\tfor (int i = 0; i < Np; ++i)\n\t\tp.dist_params[i] /= p.focal;\n}\n\n\ntemplate<int Np, int Nd>\nvoid radial_refinement_undist(Camera &p, const Points2D &x, const Points3D &X, double damp_factor) {\n\t// It is assumed that X is already rotated by p\n\tconstexpr int n_pts = std::max(2 + Np + Nd, 5);\n\n\tMatrix<double, 2 * n_pts, 2 + Np + Nd> J;\n\tMatrix<double, 2 * n_pts, 1> res;\n\tMatrix<double, 2 + Np + Nd, 1> dx;\n\n\t// Change of variables\n\tdouble f2 = p.focal * p.focal;\n\tdouble f2k = f2;\n\tfor (int i = 0; i < Np; ++i) {\n\t\tp.dist_params[i] /= f2k;\n\t\tf2k *= f2;\n\t}\n\tf2k = p.focal;\n\tfor (int i = 0; i < Nd; ++i) {\n\t\tp.dist_params[Np + i] /= f2k;\n\t\tf2k *= f2;\n\t}\n\n\tdouble r_pow[3];\n\n\tfor (int iter = 0; iter < 5; ++iter) {\n\t\tfor (int i = 0; i < n_pts; ++i) {\n\t\t\tdouble d = X(2, i) + p.t(2);\n\t\t\tdouble r2 = x.col(i).squaredNorm();\n\n\t\t\tdouble num = 1.0;\n\t\t\tdouble denom = p.focal;\n\n\t\t\tr_pow[0] = r2; // 2\n\t\t\tr_pow[1] = r2 * r2; // 4\n\t\t\tr_pow[2] = r2 * r_pow[1]; // 6\n\n\n\t\t\tfor (int k = 0; k < Np; k++) {\n\t\t\t\tnum += p.dist_params[k] * r_pow[k];\n\t\t\t}\n\t\t\tfor (int k = 0; k < Nd; k++) {\n\t\t\t\tdenom += p.dist_params[Np + k] * r_pow[k];\n\t\t\t}\n\n\t\t\tdouble factor = num / denom;\n\n\t\t\tdouble dfactor_df = -factor / denom;\n\n\t\t\tres(2 * i + 0) = factor * x(0, i) - X(0, i) / d;\n\t\t\tres(2 * i + 1) = factor * x(1, i) - X(1, i) / d;\n\n\t\t\tJ(2 * i + 0, 0) = X(0, i) / (d*d); // t\n\t\t\tJ(2 * i + 1, 0) = X(1, i) / (d*d);\n\t\t\tJ(2 * i + 0, 1) = dfactor_df * x(0, i);\n\t\t\tJ(2 * i + 1, 1) = dfactor_df * x(1, i);\n\n\t\t\tfor (int k = 0; k < Np; ++k) {\n\t\t\t\tdouble dfactor_dmu = r_pow[k] / denom;\n\t\t\t\tJ(2 * i + 0, 2 + k) = dfactor_dmu * x(0, i);\n\t\t\t\tJ(2 * i + 1, 2 + k) = dfactor_dmu * x(1, i);\n\t\t\t}\n\t\t\tfor (int k = 0; k < Nd; ++k) {\n\t\t\t\tdouble dfactor_dlambda = -r_pow[k] * num / (denom*denom);\n\t\t\t\tJ(2 * i + 0, 2 + Np + k) = dfactor_dlambda * x(0, i);\n\t\t\t\tJ(2 * i + 1, 2 + Np + k) = dfactor_dlambda * x(1, i);\n\t\t\t}\n\t\t}\n\n\t\t//std::cout << \"res = \" << res << \"\\n\";\n\t\t//std::cout << \"jac = \" << J << \"\\n\";\n\t\tif (res.norm() < SMALL_NUMBER)\n\t\t\tbreak;\n\n\t\tMatrix<double, 2 + Np + Nd, 2 + Np + Nd> H = J.transpose()*J;\n\t\tH.diagonal().array() += 1e-6; // LM dampening\n\t\tMatrix<double, 2 + Np + Nd, 1> g = -J.transpose()*res;\n\n\t\tif (Nd > 0 && Np > 0 && damp_factor > 0) {\n\t\t\t// For rational models we add a small dampening factor\n\t\t\tH.template block<Np + Nd,Np + Nd>(2, 2).diagonal().array() += damp_factor;\n\t\t\tfor (int i = 0; i < Np + Nd; i++)\n\t\t\t\tg(2 + i) -= damp_factor * p.dist_params[i];\n\t\t}\n\n\n\t\tdx = H.ldlt().solve(g);\n\n\t\tp.t(2) += dx(0);\n\t\tp.focal += dx(1);\n\t\tfor (int i = 0; i < Np; ++i)\n\t\t\tp.dist_params[i] += dx(2 + i);\n\t\tfor (int i = 0; i < Nd; ++i)\n\t\t\tp.dist_params[i + Np] += dx(Np + 2 + i);\n\n\t\tif (dx.array().abs().maxCoeff() < SMALL_NUMBER)\n\t\t\tbreak;\n\t}\n\n\t// Revert change of variables\n\tf2 = p.focal * p.focal;\n\tf2k = f2;\n\tfor (int i = 0; i < Np; ++i) {\n\t\tp.dist_params[i] *= f2k;\n\t\tf2k *= f2;\n\t}\n\tf2k = p.focal;\n\tfor (int i = 0; i < Nd; ++i) {\n\t\tp.dist_params[Np + i] *= f2k;\n\t\tf2k *= f2;\n\t}\n}\n\ninline double simple_preconditioner(const Points2D &x, const Points3D &X) {\n\t// Simple preconditioner using the first two points\n\tdouble nx1 = x.col(0).squaredNorm();\n\tdouble nx2 = x.col(1).squaredNorm();\n\tdouble sx1 = X.block<2, 1>(0, 0).dot(x.col(0));\n\tdouble sx2 = X.block<2, 1>(0, 1).dot(x.col(1));\n\treturn (X(2, 1)*nx2*sx1 - X(2, 0)*nx1*sx2) / (nx1 * sx2 - nx2 * sx1);\n}\n\ntemplate<int Np, int Nd, bool DistortionModel>\nint radialpose::larsson_iccv19::Solver<Np,Nd,DistortionModel>::solve(const Points2D& image_points, const Points3D& world_points, std::vector<Camera>* poses) const\n{\n\n\tstd::vector<Camera> initial_poses;\n\tstd::vector<double> t3;\n\n\tif (use_radial_solver) {\n\t\tkukelova_iccv13::Radial1DSolver::p5p_radial_impl(image_points, world_points, &initial_poses);\n\t} else {\n\t\tinitial_poses.push_back(Camera(Matrix3d::Identity(), Vector3d::Zero()));\n\t}\n\tMatrix<double, 3, Dynamic> X;\n\n\tfor (int k = 0; k < initial_poses.size(); k++) {\n\t\tt3.clear();\n\n\t\tX = initial_poses[k].R * world_points;\n\t\tX.colwise() += initial_poses[k].t;\n\n\t\t//std::cout << \"Initial pose \" << k + 1 << \"/\" << initial_poses.size() << \"\\n\";\n\t\t//std::cout << \"R=\" << initial_poses[k].R << \"\\nt=\" << initial_poses[k].t << \"\\n\";\n\t\t//std::cout << \"X=\" << X << \"\\n\";\n\n\t\tdouble t0 = 0;\n\t\tif (use_precond) {\n\t\t\tt0 = simple_preconditioner(image_points, X);\n\t\t\tX.row(2).array() += t0;\n\t\t}\n\n\t\tsolver_impl(image_points, X, &t3);\n\n\t\tfor (int i = 0; i < t3.size(); ++i) {\n\t\t\tCamera pose;\n\t\t\tpose.R = initial_poses[k].R;\n\t\t\tpose.t = initial_poses[k].t;\n\t\t\tpose.t(2) = t3[i];\n\n\t\t\tif (DistortionModel) {\n\t\t\t\tlinsolve_known_pose_dist(image_points, X, t3[i], Np, Nd, damp_factor, &pose);\n\t\t\t\tif(root_refinement)\n\t\t\t\t\tradial_refinement_dist<Np, Nd>(pose, image_points, X, damp_factor);\n\t\t\t} else {\n\t\t\t\tlinsolve_known_pose_undist(image_points, X, t3[i], Np, Nd, damp_factor, &pose);\n\t\t\t\tif(root_refinement)\n\t\t\t\t\tradial_refinement_undist<Np, Nd>(pose, image_points, X, damp_factor);\n\t\t\t}\t\t\t\n\n\t\t\tif (pose.focal < 0) {\n\t\t\t\t// flipped solution\n\t\t\t\tpose.focal = -pose.focal;\n\t\t\t\tpose.R.row(0) = -pose.R.row(0);\n\t\t\t\tpose.R.row(1) = -pose.R.row(1);\n\t\t\t\tpose.t(0) = -pose.t(0);\n\t\t\t\tpose.t(1) = -pose.t(1);\n\t\t\t}\n\n\t\t\t\n\t\t\t// Revert precond\n\t\t\tpose.t(2) += t0;\n\n\t\t\t//std::cout << \"solution[\" << i << \"], t3=\" << pose.t(2) << \"\\n\";\n\t\t\tposes->push_back(pose);\n\t\t}\n\t}\n\treturn poses->size();\n}\n\n\n\n\n// Template instantiations\ntemplate class radialpose::larsson_iccv19::Solver<1, 0, true>;\ntemplate class radialpose::larsson_iccv19::Solver<2, 0, true>;\ntemplate class radialpose::larsson_iccv19::Solver<3, 0, true>;\ntemplate class radialpose::larsson_iccv19::Solver<3, 3, true>;\ntemplate class radialpose::larsson_iccv19::Solver<1, 0, false>;\n//template class radialpose::larsson_iccv19::Solver<2, 0, false>;\n//template class radialpose::larsson_iccv19::Solver<3, 0, false>;\n//template class radialpose::larsson_iccv19::Solver<3, 3, false>;\n\ntemplate class radialpose::PoseEstimator<radialpose::larsson_iccv19::Solver<1, 0, true>>;\ntemplate class radialpose::PoseEstimator<radialpose::larsson_iccv19::Solver<2, 0, true>>;\ntemplate class radialpose::PoseEstimator<radialpose::larsson_iccv19::Solver<3, 0, true>>;\ntemplate class radialpose::PoseEstimator<radialpose::larsson_iccv19::Solver<3, 3, true>>;\ntemplate class radialpose::PoseEstimator<radialpose::larsson_iccv19::Solver<1, 0, false>>;\n\n/*\n This is broken?\n// These are implemented in larsson_iccv19_impl.cc\nextern template int radialpose::larsson_iccv19::Solver<1, 0, true>::solver_impl(Eigen::Matrix<double, 2, Eigen::Dynamic>, Eigen::Matrix<double, 3, Eigen::Dynamic>, std::vector<double>*);\nextern template int radialpose::larsson_iccv19::Solver<2, 0, true>::solver_impl(Eigen::Matrix<double, 2, Eigen::Dynamic>, Eigen::Matrix<double, 3, Eigen::Dynamic>, std::vector<double>*);\nextern template int radialpose::larsson_iccv19::Solver<3, 0, true>::solver_impl(Eigen::Matrix<double, 2, Eigen::Dynamic>, Eigen::Matrix<double, 3, Eigen::Dynamic>, std::vector<double>*);\nextern template int radialpose::larsson_iccv19::Solver<3, 3, true>::solver_impl(Eigen::Matrix<double, 2, Eigen::Dynamic>, Eigen::Matrix<double, 3, Eigen::Dynamic>, std::vector<double>*);\nextern template int radialpose::larsson_iccv19::Solver<1, 0, false>::solver_impl(Eigen::Matrix<double, 2, Eigen::Dynamic>, Eigen::Matrix<double, 3, Eigen::Dynamic>, std::vector<double>*);\n*/", "meta": {"hexsha": "b8bbcf263066dc2af85246adcb336c2c6602d03f", "size": 13757, "ext": "cc", "lang": "C++", "max_stars_repo_path": "solvers/larsson_iccv19.cc", "max_stars_repo_name": "vlarsson/radialpose", "max_stars_repo_head_hexsha": "e620fc208f573820ade6a6fe321731d0f3eb082d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2019-10-29T02:48:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T20:28:29.000Z", "max_issues_repo_path": "solvers/larsson_iccv19.cc", "max_issues_repo_name": "vlarsson/radialpose", "max_issues_repo_head_hexsha": "e620fc208f573820ade6a6fe321731d0f3eb082d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-31T16:16:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-31T19:39:41.000Z", "max_forks_repo_path": "solvers/larsson_iccv19.cc", "max_forks_repo_name": "vlarsson/radialpose", "max_forks_repo_head_hexsha": "e620fc208f573820ade6a6fe321731d0f3eb082d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-11-04T21:38:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T20:41:11.000Z", "avg_line_length": 29.7770562771, "max_line_length": 187, "alphanum_fraction": 0.5750527004, "num_tokens": 5386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680904463333, "lm_q2_score": 0.5813030906443134, "lm_q1q2_score": 0.4986232420325245}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace Eigen;\nusing namespace std;\n\nint main() {\n  ArrayXXf m(2, 2);\n\n  // assign some values coefficient by coefficient\n  m(0, 0) = 1.0;\n  m(0, 1) = 2.0;\n  m(1, 0) = 3.0;\n  m(1, 1) = m(0, 1) + m(1, 0);\n\n  // print values to standard output\n  cout << m << endl << endl;\n\n  // using the comma-initializer is also allowed\n  m << 1.0, 2.0,\n      3.0, 4.0;\n\n  // print values to standard output\n  cout << m << endl;\n}\n", "meta": {"hexsha": "701a6b875c1cb571326f19b756102e5081a58a00", "size": 467, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "include/Eigen-3.3/doc/examples/Tutorial_ArrayClass_accessors.cpp", "max_stars_repo_name": "chen0510566/CarND-Path-Planning-Project", "max_stars_repo_head_hexsha": "4652e5c459980252e4ab72a0fd687341f3245466", "max_stars_repo_licenses": ["MIT"], "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/Eigen-3.3/doc/examples/Tutorial_ArrayClass_accessors.cpp", "max_issues_repo_name": "chen0510566/CarND-Path-Planning-Project", "max_issues_repo_head_hexsha": "4652e5c459980252e4ab72a0fd687341f3245466", "max_issues_repo_licenses": ["MIT"], "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/Eigen-3.3/doc/examples/Tutorial_ArrayClass_accessors.cpp", "max_forks_repo_name": "chen0510566/CarND-Path-Planning-Project", "max_forks_repo_head_hexsha": "4652e5c459980252e4ab72a0fd687341f3245466", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.9615384615, "max_line_length": 50, "alphanum_fraction": 0.5824411135, "num_tokens": 176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6791786861878392, "lm_q2_score": 0.7341195385342971, "lm_q1q2_score": 0.4985983436865467}}
{"text": "/*!\n  \\file gpp_hyperparameter_optimization_demo.cpp\n  \\rst\n  ``moe/optimal_learning/cpp/gpp_hyperparameter_optimization_demo.cpp``\n\n  This is a demo for the model selection (via hyperparameter optimization) capability\n  present in this project.  These capabilities live in\n  gpp_model_selection.\n\n  In gpp_expected_improvement_demo, we choose the hyperparameters arbitrarily.  Here,\n  we will walk through an example of how one would select hyperparameters for a given\n  class of covariance function; here, SquareExponential will do.  This demo supports:\n\n  1. User-specified training data\n  2. Randomly generated training data (more automatic)\n\n  More details on the second case:\n\n  1. Choose a set of hyperparameters randomly: source covariance\n  2. Build a fake\\* training set by drawing from a GP with source covariance, at randomly\n     chosen locations\n     \\* By defining OL_USER_INPUTS to 1, you can specify your own input data.\n  3. Choose a new random set of hyperparameters and run hyperparameter optimization\n\n     a. Show log likelihood using the optimized hyperparameters AND the source hyperparameters\n     b. observe that with larger training sets, the optimized hyperparameters converge\n        to the source values; but in smaller sets other optima may exist\n\n  Further notes about [newton] optimization performance and robustness are spread throughout the\n  demo code, placed near the function call/object construction that they are relevant to.\n\n  Please read and understand gpp_expected_improvement_demo.cpp before going through\n  this example.  In addition, understanding gpp_model_selection.hpp's\n  file comments (as well as cpp for devs) is prerequisite.\n\\endrst*/\n\n#include <cstdio>\n\n#include <vector>\n\n#include <boost/random/uniform_real.hpp>  // NOLINT(build/include_order)\n\n#include \"gpp_common.hpp\"\n#include \"gpp_covariance.hpp\"\n#include \"gpp_domain.hpp\"\n#include \"gpp_logging.hpp\"\n#include \"gpp_math.hpp\"\n#include \"gpp_model_selection.hpp\"\n#include \"gpp_optimizer_parameters.hpp\"\n#include \"gpp_random.hpp\"\n#include \"gpp_test_utils.hpp\"\n\n#define OL_USER_INPUTS 0\n\nusing namespace optimal_learning;  // NOLINT, i'm lazy in this file which has no external linkage anyway\n\nint main() {\n  using DomainType = TensorProductDomain;\n  using HyperparameterDomainType = TensorProductDomain;\n  // here we set some configurable parameters\n  // feel free to change them (and recompile) as you explore\n  // comments next to each parameter will indicate its purpose and domain\n\n  // the \"spatial\" dimension, aka the number of independent (experiment) parameters\n  // i.e., this is the dimension of the points in points_sampled\n  static const int dim = 3;  // > 0\n\n  // number of points that we have already sampled; i.e., size of the training set\n  static const int num_sampled = 100;  // >= 0\n  // observe that as num_sampled increases, the optimal set of hyperparameters (via optimization) will approach\n  // the set used to generate the input data (in the case of generating inputs randomly from a GP).  Don't try overly\n  // large values or it will be slow; for reference 500 samples takes ~2-3 min on my laptop whereas 100 samples takes ~1s\n\n  // the log likelihoods will also decrease in value since by adding more samples, we are more greatly restricting the GP\n  // into ever-narrower sets of likely realizations\n\n  UniformRandomGenerator uniform_generator(314);  // repeatable results\n  // construct with (base_seed, thread_id) to generate a 'random' seed\n\n  // specifies the domain of each independent variable in (min, max) pairs\n  // set appropriately for user-specified inputs\n  // mostly irrelevant for randomly generated inputs\n  std::vector<ClosedInterval> domain_bounds = {\n    {-1.5, 2.3},  // first dimension\n    {0.1, 3.1},   // second dimension\n    {1.7, 2.9}};  // third dimension\n  DomainType domain(domain_bounds.data(), dim);\n\n  // now we allocate point sets; ALL POINTS MUST LIE INSIDE THE DOMAIN!\n  std::vector<double> points_sampled(num_sampled*dim);\n\n  std::vector<double> points_sampled_value(num_sampled);\n\n  // default to 0 noise\n  std::vector<double> noise_variance(num_sampled, 0.0);  // each entry must be >= 0.0\n  // choosing too much noise makes little sense: cannot make useful predicitions if data\n  // is drowned out by noise\n  // choosing 0 noise is dangerous for large problems; the covariance matrix becomes very\n  // ill-conditioned, and adding noise caps the maximum condition number at roughly\n  // 1.0/min(noise_variance)\n\n  // covariance selection\n  using CovarianceClass = SquareExponential;  // see gpp_covariance.hpp for other options\n\n  // arbitrary hyperparameters used to generate data\n  std::vector<double> hyperparameters_original(1 + dim);\n  CovarianceClass covariance_original(dim, 1.0, 1.0);\n  // CovarianceClass provides SetHyperparameters, GetHyperparameters to read/modify\n  // hyperparameters later on\n  // Generate hyperparameters randomly\n  boost::uniform_real<double> uniform_double_for_hyperparameter(0.5, 1.5);\n  FillRandomCovarianceHyperparameters(uniform_double_for_hyperparameter, &uniform_generator,\n                                      &hyperparameters_original, &covariance_original);\n\n  std::vector<ClosedInterval> hyperparameter_domain_bounds(covariance_original.GetNumberOfHyperparameters(), {1.0e-10, 1.0e10});\n  HyperparameterDomainType hyperparameter_domain(hyperparameter_domain_bounds.data(),\n                                                 covariance_original.GetNumberOfHyperparameters());\n\n  // now fill data\n#if OL_USER_INPUTS == 1\n  // if you prefer, insert your own data here\n  // requirements aka variables that must be set:\n  // noise variance, num_sampled values: defaulted to 0; need to set this for larger data sets to deal with conditioning\n  // points_sampled, num_sampled*dim values: the locations of already-sampled points; must be INSIDE the domain\n  // points_sampled_value, num_sampled values: the function values at the already-sampled points\n  // covariance_perturbed: a CovarianceClass object constructed with perturbed (from covariance_original) hyperparameters;\n  //   must have decltype(covariance_perturbed) == decltype(covariance_original) for hyperparameter opt to make any sense\n\n  // NOTE: the GP is 0-mean, so shift your points_sampled_value entries accordingly\n  // e.g., if the samples are from a function with mean M, subtract it out\n#else\n  // generate GP inputs randomly\n\n  // set noise\n  std::fill(noise_variance.begin(), noise_variance.end(), 1.0e-1);  // arbitrary choice\n\n  // use latin hypercube sampling to get a reasonable distribution of training point locations\n  domain.GenerateUniformPointsInDomain(num_sampled, &uniform_generator, points_sampled.data());\n\n  // build an empty GP: since num_sampled (last arg) is 0, none of the data arrays will be used here\n  GaussianProcess gp_generator(covariance_original, points_sampled.data(), points_sampled_value.data(),\n                               noise_variance.data(), dim, 0);\n  // fill the GP with randomly generated data\n  FillRandomGaussianProcess(points_sampled.data(), noise_variance.data(), dim, num_sampled,\n                            points_sampled_value.data(), &gp_generator);\n\n  // choose a random initial guess reasonably far away from hyperparameters_original\n  // to find some optima (see WARNING2 below), it may be necessary to start with hyperparameters smaller than the originals or\n  // of similar magnitude\n  std::vector<double> hyperparameters_perturbed(covariance_original.GetNumberOfHyperparameters());\n  CovarianceClass covariance_perturbed(dim, 1.0, 1.0);\n  boost::uniform_real<double> uniform_double_for_wrong_hyperparameter(5.0, 12.0);\n  FillRandomCovarianceHyperparameters(uniform_double_for_wrong_hyperparameter, &uniform_generator,\n                                      &hyperparameters_perturbed, &covariance_perturbed);\n#endif\n\n  // log likelihood type selection\n  using LogLikelihoodEvaluator = LogMarginalLikelihoodEvaluator;\n  // log likelihood evaluator object\n  LogLikelihoodEvaluator log_marginal_eval(points_sampled.data(), points_sampled_value.data(),\n                                           noise_variance.data(), dim, num_sampled);\n\n  int total_newton_errors = 0;  // number of newton runs that failed due to singular hessians\n  int newton_max_num_steps = 500;  // max number of newton steps\n  double gamma_newton = 1.05;  // newton diagonal dominance scale-down factor (see newton docs for details)\n  double pre_mult_newton = 1.0e-1;  // newton diagonal dominance scaling factor (see newton docs for details)\n  double max_relative_change_newton = 1.0;\n  double tolerance_newton = 1.0e-11;\n  NewtonParameters newton_parameters(1, newton_max_num_steps, gamma_newton, pre_mult_newton,\n                                     max_relative_change_newton, tolerance_newton);\n\n  // call newton to optimize hyperparameters\n  // in general if this takes the full hyperparameter_max_num_steps iterations, something went wrong\n  // newton's solution:\n  std::vector<double> new_newton_hyperparameters(covariance_original.GetNumberOfHyperparameters());\n\n  printf(OL_ANSI_COLOR_CYAN \"ORIGINAL HYPERPARMETERS:\\n\" OL_ANSI_COLOR_RESET);\n  printf(\"Original Hyperparameters:\\n\");\n  PrintMatrix(hyperparameters_original.data(), 1, covariance_original.GetNumberOfHyperparameters());\n\n  printf(OL_ANSI_COLOR_CYAN \"NEWTON OPTIMIZED HYPERPARAMETERS:\\n\" OL_ANSI_COLOR_RESET);\n  // run newton optimization\n  total_newton_errors += NewtonHyperparameterOptimization(log_marginal_eval, covariance_perturbed,\n                                                          newton_parameters, hyperparameter_domain,\n                                                          new_newton_hyperparameters.data());\n  // WARNING: the gradient of log marginal appears to go to 0 as you move toward infinity.  if you do not start\n  // close enough to an optima or have overly aggressive diagonal dominance settings, newton will skip miss everything\n  // going on locally and shoot out to these solutions.\n  // Having hyperparameters = 1.0e10 is nonsense, and usually this problem is further signaled by a log marginal likelihood\n  // that is POSITIVE (impossible since p \\in [0,1], so log(p) \\in (-\\infty, 0])\n\n  // Long-term, we should solve this problem by multistarting newton.  Additionally there will be some kind of \"quick kill\"\n  // mechanism needed--when newton is wandering down the wrong path (or to an already-known solution?) we should detect it\n  // and kill it quickly to keep cost low.\n  // For now, just play around with different initial conditions or more conservative gamam settings.\n\n  // WARNING2: for small num_sampled, it often appears that the solution becomes independent of one or more hyperparameters.\n  // e.g., in 2D, we'd have an optimal \"ridge.\"  Finding this robustly requires starting near it, so the random choice of\n  // initial conditions can fail horribly in general.\n\n  // WARNING3: if you choose large values of num_sampled (like 300), this can be quite slow; about 5min on my computer\n  // sometimes the reason is that machine prescision prevents us from reaching the cutoff criterion:\n  // norm_gradient_likelihood <= 1.0e-13 in NewtonHyperparameterOptimization() in gpp_model_selection...cpp\n  // So you may need to relax this to 1.0e-10 or something so that we aren't just spinning wheels at almost-converged but\n  // unable to actually move anywhere.\n\n  printf(\"Result of newton:\\n\");\n  PrintMatrix(new_newton_hyperparameters.data(), 1, covariance_original.GetNumberOfHyperparameters());\n\n  if (total_newton_errors > 0) {\n    printf(\"WARNING: %d newton runs exited due to singular Hessian matrices.\\n\", total_newton_errors);\n  }\n\n  printf(OL_ANSI_COLOR_CYAN \"LOG LIKELIHOOD + GRADIENT AT NEWTON OPTIMIZED FINAL HYPERPARAMS:\\n\" OL_ANSI_COLOR_RESET);\n\n  CovarianceClass covariance_final(dim, new_newton_hyperparameters[0], new_newton_hyperparameters.data() + 1);\n  typename LogLikelihoodEvaluator::StateType log_marginal_state_newton_optimized_hyper(log_marginal_eval,\n                                                                                       covariance_final);\n  double newton_log_marginal_opt = log_marginal_eval.ComputeLogLikelihood(log_marginal_state_newton_optimized_hyper);\n  printf(\"newton optimized log marginal likelihood = %.18E\\n\", newton_log_marginal_opt);\n\n  std::vector<double> grad_log_marginal_opt(covariance_final.GetNumberOfHyperparameters());\n  log_marginal_eval.ComputeGradLogLikelihood(&log_marginal_state_newton_optimized_hyper,\n                                             grad_log_marginal_opt.data());\n  printf(\"grad log likelihood: \");\n  PrintMatrix(grad_log_marginal_opt.data(), 1, covariance_final.GetNumberOfHyperparameters());\n\n  printf(OL_ANSI_COLOR_CYAN \"LOG LIKELIHOOD + GRADIENT AT ORIGINAL HYPERPARAMS:\\n\" OL_ANSI_COLOR_RESET);\n  typename LogLikelihoodEvaluator::StateType log_marginal_state_original_hyper(log_marginal_eval,\n                                                                               covariance_original);\n\n  double original_log_marginal = log_marginal_eval.ComputeLogLikelihood(log_marginal_state_original_hyper);\n  printf(\"original log marginal likelihood = %.18E\\n\", original_log_marginal);\n\n  std::vector<double> original_grad_log_marginal(covariance_original.GetNumberOfHyperparameters());\n  log_marginal_eval.ComputeGradLogLikelihood(&log_marginal_state_original_hyper,\n                                             original_grad_log_marginal.data());\n  printf(\"grad log likelihood: \");\n  PrintMatrix(original_grad_log_marginal.data(), 1, covariance_original.GetNumberOfHyperparameters());\n\n  return 0;\n}  // end main\n", "meta": {"hexsha": "9b9b5302745b750137be039eae6967e81ca7bade", "size": 13625, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "moe/optimal_learning/cpp/gpp_hyperparameter_optimization_demo.cpp", "max_stars_repo_name": "dstoeckel/MOE", "max_stars_repo_head_hexsha": "5b5a6a2c6c3cf47320126f7f5894e2a83e347f5c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 966.0, "max_stars_repo_stars_event_min_datetime": "2015-01-10T05:27:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T21:04:36.000Z", "max_issues_repo_path": "moe/optimal_learning/cpp/gpp_hyperparameter_optimization_demo.cpp", "max_issues_repo_name": "dstoeckel/MOE", "max_issues_repo_head_hexsha": "5b5a6a2c6c3cf47320126f7f5894e2a83e347f5c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 46.0, "max_issues_repo_issues_event_min_datetime": "2015-01-16T22:33:08.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T16:33:27.000Z", "max_forks_repo_path": "moe/optimal_learning/cpp/gpp_hyperparameter_optimization_demo.cpp", "max_forks_repo_name": "dstoeckel/MOE", "max_forks_repo_head_hexsha": "5b5a6a2c6c3cf47320126f7f5894e2a83e347f5c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 143.0, "max_forks_repo_forks_event_min_datetime": "2015-01-07T03:57:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T01:10:45.000Z", "avg_line_length": 56.0699588477, "max_line_length": 128, "alphanum_fraction": 0.7492844037, "num_tokens": 3129, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6791786861878392, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.4985983357849044}}
{"text": "\n#include \"mex.h\"\n#include <Eigen/Dense>\n#include \"re3q3/re3q3.h\"\n\nvoid printUsage() {\n\tmexPrintf(\"[x] = re3q3(C);\\n\");\n\tmexPrintf(\"    coefficient order is [ x^2, xy, xz, y^2, yz, z^2, x, y, z, 1.0 ]\\n\");\n}\n\nvoid mexFunction(int nlhs,mxArray *plhs[], int nrhs, const mxArray *prhs[]) {\n\n\tif (nrhs != 1) {\n\t\tprintUsage();\n\t\tmexErrMsgTxt(\"Please, specify 3 x 10N coefficient matrix\");\n\t}\n\tif (nlhs != 1) {\n\t\tprintUsage();\n\t\tmexErrMsgTxt(\"Require one output argument.\");\n\t}\n\t\n\tif ((mxGetM(prhs[0]) != 3) || (mxGetN(prhs[0]) % 10 != 0)) {\n\t\tprintUsage();\n\t\tmexErrMsgTxt(\"One input 3 x 10N matrix is required.\");\n\t}\n\n\tint n_instances = mxGetN(prhs[0]) / 10;\n\t\n\tdouble *data = mxGetPr(prhs[0]);\n\n\tEigen::Matrix<double, 3, 10> coeffs;\n\tEigen::Matrix<double, 3, 8> solutions;\n\n\tif (n_instances == 1) {\n\t\t// we are solving a single instance, output is 3xNsols\n\t\tcoeffs = Eigen::Map<Eigen::Matrix<double, 3, 10>>(data);\n\n\t\tint n_sols = re3q3::re3q3(coeffs, &solutions);\n\t\tplhs[0] = mxCreateDoubleMatrix(3, n_sols, mxREAL);\n\n\t\tEigen::Map<Eigen::MatrixXd> output_matrix = Eigen::Map<Eigen::MatrixXd>(mxGetPr(plhs[0]), 3, n_sols);\n\t\toutput_matrix = solutions.block(0, 0, 3, n_sols);\n\t} else {\n\t\t// we are solving multiple instances, output is 3x8N\n\t\tplhs[0] = mxCreateDoubleMatrix(3, 8 * n_instances, mxREAL);\n\t\tdouble *output = mxGetPr(plhs[0]);\n\n\t\tEigen::Map<Eigen::MatrixXd> output_matrix = Eigen::Map<Eigen::MatrixXd>(mxGetPr(plhs[0]), 3, 8*n_instances);\n\t\toutput_matrix.setZero();\n\n\t\tfor (int i = 0; i < n_instances; i++) {\n\t\t\tcoeffs = Eigen::Map<Eigen::Matrix<double, 3, 10>>(data + 30 * i);\n\t\t\tsolutions.setZero();\n\t\t\tint n_sols = re3q3::re3q3(coeffs, &solutions);\n\t\t\toutput_matrix.block(0, i * 8, 3, n_sols) = solutions.block(0,0,3,n_sols);\n\t\t}\n\t}\n}\n", "meta": {"hexsha": "ac7c3ccac9aa9a081e4cd6874208159bc600b8c7", "size": 1746, "ext": "cc", "lang": "C++", "max_stars_repo_path": "re3q3_mex.cc", "max_stars_repo_name": "vlarsson/re3q3", "max_stars_repo_head_hexsha": "ab03d271f0a30f516f052d750773b0277898751f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-03-26T09:30:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T10:14:01.000Z", "max_issues_repo_path": "re3q3_mex.cc", "max_issues_repo_name": "vlarsson/re3q3", "max_issues_repo_head_hexsha": "ab03d271f0a30f516f052d750773b0277898751f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "re3q3_mex.cc", "max_forks_repo_name": "vlarsson/re3q3", "max_forks_repo_head_hexsha": "ab03d271f0a30f516f052d750773b0277898751f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-18T06:19:02.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-18T06:19:02.000Z", "avg_line_length": 29.593220339, "max_line_length": 110, "alphanum_fraction": 0.6466208477, "num_tokens": 641, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195152660688, "lm_q2_score": 0.679178692681616, "lm_q1q2_score": 0.49859833265047027}}
{"text": "#include <igl/per_vertex_normals.h>\n#include <igl/principal_curvature.h>\n#include <igl/avg_edge_length.h>\n#include <igl/massmatrix.h>\n#include <igl/adjacency_list.h>\n#include <igl/per_face_normals.h>\n#include <igl/barycenter.h>\n#include <igl/pinv.h>\n#include <igl/edges.h>\n#include <Eigen/SparseCore>\n#include <igl/adjacency_list.h>\n#include <igl/adjacency_matrix.h>\n#include <igl/per_face_normals.h>\n#include <igl/per_vertex_normals.h>\n#include <igl/avg_edge_length.h>\n#include <igl/edge_flaps.h>\n#include <igl/unique_edge_map.h>\n#include <igl/vertex_triangle_adjacency.h>\n#include <igl/principal_curvature.h>\n#include <igl/collapse_edge.h>\n#include <igl/writeOBJ.h>\n#include <igl/C_STR.h>\n#include <igl/circulation.h>\n#include <igl/is_edge_manifold.h>\n#include <igl/decimate.h>\n#include <igl/shortest_edge_and_midpoint.h>\n#include <igl/infinite_cost_stopping_condition.h>\n#include \"split_edges.h\"\nusing namespace std;\n\nvoid split_edges_until_bound(Eigen::MatrixXd & V,Eigen::MatrixXi & F, Eigen::VectorXi & feature, Eigen::VectorXd & high, Eigen::VectorXd & low){\n    \n    using namespace Eigen;\n    int m = F.rows();\n    int n = V.rows();\n    int num_feat = feature.size();\n    std::vector<std::vector<int>> A;\n    std::vector<bool> is_feature_vertex;\n    is_feature_vertex.resize(n);\n    Eigen::VectorXi is_feature_vertex_vec;\n    is_feature_vertex_vec.setZero(n);\n    igl::adjacency_list(F,A);\n    Eigen::MatrixXi E,uE;\n    Eigen::VectorXi EMAP;\n    std::vector<std::vector<int>> uE2E;\n    igl::unique_edge_map(F,E,uE,EMAP,uE2E);\n    int k = uE.rows();\n    //std::cout << \"Start split_edges_until_bound\" << std::endl;\n    \n    \n    for (int s = 0; s < num_feat; s++) {\n        is_feature_vertex[feature(s)] = true;\n       // is_feature_vertex_vec(feature(s)) = 1;\n    }\n    \n    bool keep_splitting = true;\n    std::vector<int> edges_to_split;\n    \n    while (keep_splitting) {\n        //std::cout << \"A\" << std::endl;\n        edges_to_split.resize(0);\n        \n        for (int i = 0; i < uE.rows(); i++) {\n            //std::cout << \"B\" << std::endl;\n            if (!is_feature_vertex[uE(i,0)] && !is_feature_vertex[uE(i,1)] && uE2E[i].size()==2) {\n            //if (is_feature_vertex_vec(uE(i,0))==0 && is_feature_vertex_vec(uE(i,1))==0 && uE2E[i].size()==2) {\n                if ( (V.row(uE(i,0))-V.row(uE(i,1))).norm()>((high(uE(i,0))+high(uE(i,1)))/2)  ){\n                    edges_to_split.push_back(i);\n                    //std::cout << \"C\" << std::endl;\n                }\n            }\n        }\n        \n        //std::cout << \"B\" << std::endl;\n        \n        //std::cout << \"D\" << std::endl;\n        if(edges_to_split.size()==0){\n            keep_splitting = false;\n        }else{\n            // SPLIT EDGES IN VECTOR edges_to_split\n            //\n            \n            //std::cout << \"Before call to split_edges\" << std::endl;\n            //std::cout << edges_to_split.size() << std::endl;\n            split_edges(V,F,E,uE,EMAP,uE2E,high,low,edges_to_split);\n            //igl::writeOBJ(\"test.obj\",V,F);\n            //igl::unique_edge_map(F,E,uE,EMAP,uE2E);\n            //std::cout << igl::is_edge_manifold(F) << std::endl;\n            //std::cout << \"After call to split_edges\" << std::endl;\n            \n        }\n        \n        \n       keep_splitting = false; // THIS IS A PATCH, NOT GOOD\n    }\n    \n    \n}\n\n\n// g++ -I/usr/local/libigl/external/eigen -I/usr/local/libigl/include -std=c++11 -framework Accelerate main.cpp remesh_botsch.cpp -o main\n\n", "meta": {"hexsha": "5f08f87e66c35e3a28ef7f814b9229807676775e", "size": 3477, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/split_edges_until_bound.cpp", "max_stars_repo_name": "sgsellan/opening-and-closing-surfaces", "max_stars_repo_head_hexsha": "57127178c2e8d50396c02a853c4456a90e9220c5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2020-10-27T00:03:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T19:44:35.000Z", "max_issues_repo_path": "src/split_edges_until_bound.cpp", "max_issues_repo_name": "sgsellan/opening-and-closing-surfaces", "max_issues_repo_head_hexsha": "57127178c2e8d50396c02a853c4456a90e9220c5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/split_edges_until_bound.cpp", "max_forks_repo_name": "sgsellan/opening-and-closing-surfaces", "max_forks_repo_head_hexsha": "57127178c2e8d50396c02a853c4456a90e9220c5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-10-27T01:40:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-23T13:42:16.000Z", "avg_line_length": 33.7572815534, "max_line_length": 144, "alphanum_fraction": 0.5970664366, "num_tokens": 998, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529376, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.4985801115639822}}
{"text": "#include <stan/math/mix.hpp>\n#include <gtest/gtest.h>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/math/distributions.hpp>\n#include <vector>\n\nTEST(ProbDistributions, fvar_var) {\n  using Eigen::Dynamic;\n  using Eigen::Matrix;\n  using stan::math::fvar;\n  using stan::math::var;\n\n  Matrix<fvar<var>, Dynamic, 1> theta(3, 1);\n  theta << 0.2, 0.3, 0.5;\n  Matrix<fvar<var>, Dynamic, 1> alpha(3, 1);\n  alpha << 1.0, 1.0, 1.0;\n  for (int i = 0; i < 3; i++) {\n    theta(i).d_ = 1.0;\n    alpha(i).d_ = 1.0;\n  }\n\n  EXPECT_FLOAT_EQ(0.6931472,\n                  stan::math::dirichlet_log(theta, alpha).val_.val());\n  EXPECT_FLOAT_EQ(0.99344212, stan::math::dirichlet_log(theta, alpha).d_.val());\n\n  Matrix<fvar<var>, Dynamic, 1> theta2(4, 1);\n  theta2 << 0.01, 0.01, 0.8, 0.18;\n  Matrix<fvar<var>, Dynamic, 1> alpha2(4, 1);\n  alpha2 << 10.5, 11.5, 19.3, 5.1;\n  for (int i = 0; i < 3; i++) {\n    theta2(i).d_ = 1.0;\n    alpha2(i).d_ = 1.0;\n  }\n\n  EXPECT_FLOAT_EQ(-43.40045,\n                  stan::math::dirichlet_log(theta2, alpha2).val_.val());\n  EXPECT_FLOAT_EQ(2017.2858,\n                  stan::math::dirichlet_log(theta2, alpha2).d_.val());\n}\n\nTEST(ProbDistributions, fvar_varVectorised) {\n  using Eigen::Dynamic;\n  using Eigen::Matrix;\n  using stan::math::dirichlet_log;\n  using stan::math::fvar;\n  using stan::math::var;\n\n  Matrix<fvar<var>, Dynamic, 1> theta1(3, 1), theta2(3, 1), theta3(3, 1);\n  theta1 << 0.2, 0.3, 0.5;\n  theta2 << 0.1, 0.8, 0.1;\n  theta3 << 0.6, 0.1, 0.3;\n\n  Matrix<fvar<var>, Dynamic, 1> alpha1(3, 1), alpha2(3, 1), alpha3(3, 1);\n  alpha1 << 1.0, 1.0, 1.0;\n  alpha2 << 6.2, 3.5, 9.1;\n  alpha3 << 2.5, 7.4, 6.1;\n\n  std::vector<Matrix<fvar<var>, Dynamic, 1>> theta_vec(3);\n  theta_vec[0] = theta1;\n  theta_vec[1] = theta2;\n  theta_vec[2] = theta3;\n\n  std::vector<Matrix<fvar<var>, Dynamic, 1>> alpha_vec(3);\n  alpha_vec[0] = alpha1;\n  alpha_vec[1] = alpha2;\n  alpha_vec[2] = alpha3;\n\n  Matrix<fvar<var>, Dynamic, 1> result(3);\n  result[0] = dirichlet_log(theta1, alpha1);\n  result[1] = dirichlet_log(theta2, alpha2);\n  result[2] = dirichlet_log(theta3, alpha3);\n\n  fvar<var> out = dirichlet_log(theta_vec, alpha_vec);\n\n  EXPECT_FLOAT_EQ(result.val().val().sum(), out.val_.val());\n  EXPECT_FLOAT_EQ(result.d().val().sum(), out.d_.val());\n\n  result[0] = dirichlet_log(theta1, alpha1);\n  result[1] = dirichlet_log(theta2, alpha1);\n  result[2] = dirichlet_log(theta3, alpha1);\n\n  out = dirichlet_log(theta_vec, alpha1);\n\n  EXPECT_FLOAT_EQ(result.val().val().sum(), out.val_.val());\n  EXPECT_FLOAT_EQ(result.d().val().sum(), out.d_.val());\n\n  result[0] = dirichlet_log(theta1, alpha1);\n  result[1] = dirichlet_log(theta1, alpha2);\n  result[2] = dirichlet_log(theta1, alpha3);\n\n  out = dirichlet_log(theta1, alpha_vec);\n\n  EXPECT_FLOAT_EQ(result.val().val().sum(), out.val_.val());\n  EXPECT_FLOAT_EQ(result.d().val().sum(), out.d_.val());\n}\n\nTEST(ProbDistributions, fvar_fvar_var) {\n  using Eigen::Dynamic;\n  using Eigen::Matrix;\n  using stan::math::fvar;\n  using stan::math::var;\n\n  Matrix<fvar<fvar<var>>, Dynamic, 1> theta(3, 1);\n  theta << 0.2, 0.3, 0.5;\n  Matrix<fvar<fvar<var>>, Dynamic, 1> alpha(3, 1);\n  alpha << 1.0, 1.0, 1.0;\n  for (int i = 0; i < 3; i++) {\n    theta(i).d_ = 1.0;\n    alpha(i).d_ = 1.0;\n  }\n\n  EXPECT_FLOAT_EQ(0.6931472,\n                  stan::math::dirichlet_log(theta, alpha).val_.val_.val());\n  EXPECT_FLOAT_EQ(0.99344212,\n                  stan::math::dirichlet_log(theta, alpha).d_.val_.val());\n\n  Matrix<fvar<fvar<var>>, Dynamic, 1> theta2(4, 1);\n  theta2 << 0.01, 0.01, 0.8, 0.18;\n  Matrix<fvar<fvar<var>>, Dynamic, 1> alpha2(4, 1);\n  alpha2 << 10.5, 11.5, 19.3, 5.1;\n  for (int i = 0; i < 3; i++) {\n    theta2(i).d_ = 1.0;\n    alpha2(i).d_ = 1.0;\n  }\n\n  EXPECT_FLOAT_EQ(-43.40045,\n                  stan::math::dirichlet_log(theta2, alpha2).val_.val_.val());\n  EXPECT_FLOAT_EQ(2017.2858,\n                  stan::math::dirichlet_log(theta2, alpha2).d_.val_.val());\n}\n\nTEST(ProbDistributions, fvar_fvar_varVectorised) {\n  using Eigen::Dynamic;\n  using Eigen::Matrix;\n  using stan::math::dirichlet_log;\n  using stan::math::fvar;\n  using stan::math::var;\n\n  Matrix<fvar<fvar<var>>, Dynamic, 1> theta1(3, 1), theta2(3, 1), theta3(3, 1);\n  theta1 << 0.2, 0.3, 0.5;\n  theta2 << 0.1, 0.8, 0.1;\n  theta3 << 0.6, 0.1, 0.3;\n\n  Matrix<fvar<fvar<var>>, Dynamic, 1> alpha1(3, 1), alpha2(3, 1), alpha3(3, 1);\n  alpha1 << 1.0, 1.0, 1.0;\n  alpha2 << 6.2, 3.5, 9.1;\n  alpha3 << 2.5, 7.4, 6.1;\n\n  std::vector<Matrix<fvar<fvar<var>>, Dynamic, 1>> theta_vec(3);\n  theta_vec[0] = theta1;\n  theta_vec[1] = theta2;\n  theta_vec[2] = theta3;\n\n  std::vector<Matrix<fvar<fvar<var>>, Dynamic, 1>> alpha_vec(3);\n  alpha_vec[0] = alpha1;\n  alpha_vec[1] = alpha2;\n  alpha_vec[2] = alpha3;\n\n  Matrix<fvar<fvar<var>>, Dynamic, 1> result(3);\n  result[0] = dirichlet_log(theta1, alpha1);\n  result[1] = dirichlet_log(theta2, alpha2);\n  result[2] = dirichlet_log(theta3, alpha3);\n\n  fvar<fvar<var>> out = dirichlet_log(theta_vec, alpha_vec);\n\n  EXPECT_FLOAT_EQ(result.val().val().val().sum(), out.val_.val_.val());\n  EXPECT_FLOAT_EQ(result.d().val().val().sum(), out.d_.val_.val());\n\n  result[0] = dirichlet_log(theta1, alpha1);\n  result[1] = dirichlet_log(theta2, alpha1);\n  result[2] = dirichlet_log(theta3, alpha1);\n\n  out = dirichlet_log(theta_vec, alpha1);\n\n  EXPECT_FLOAT_EQ(result.val().val().val().sum(), out.val_.val_.val());\n  EXPECT_FLOAT_EQ(result.d().val().val().sum(), out.d_.val_.val());\n\n  result[0] = dirichlet_log(theta1, alpha1);\n  result[1] = dirichlet_log(theta1, alpha2);\n  result[2] = dirichlet_log(theta1, alpha3);\n\n  out = dirichlet_log(theta1, alpha_vec);\n\n  EXPECT_FLOAT_EQ(result.val().val().val().sum(), out.val_.val_.val());\n  EXPECT_FLOAT_EQ(result.d().val().val().sum(), out.d_.val_.val());\n}\n", "meta": {"hexsha": "f3b6092b9f1d9d0f9fad297e91e646525b03d8aa", "size": 5747, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/mix/prob/dirichlet_test.cpp", "max_stars_repo_name": "bayesmix-dev/math", "max_stars_repo_head_hexsha": "3616f7195adc95ef8e719a2af845d61102bc9272", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-14T14:33:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-14T14:33:37.000Z", "max_issues_repo_path": "test/unit/math/mix/prob/dirichlet_test.cpp", "max_issues_repo_name": "bayesmix-dev/math", "max_issues_repo_head_hexsha": "3616f7195adc95ef8e719a2af845d61102bc9272", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/unit/math/mix/prob/dirichlet_test.cpp", "max_forks_repo_name": "bayesmix-dev/math", "max_forks_repo_head_hexsha": "3616f7195adc95ef8e719a2af845d61102bc9272", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-05-10T12:55:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-10T12:55:07.000Z", "avg_line_length": 30.7326203209, "max_line_length": 80, "alphanum_fraction": 0.6276318079, "num_tokens": 2188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.49858011156398213}}
{"text": "//==================================================================================================\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//! [reduce-phase]\n#include <boost/simd/algorithm/reduce.hpp>\n#include <iostream>\n#include <numeric>\n\nint main()\n{\n  float values[] = {1.f,2.f,3.f,4.f,5.f,6.f,7.f,8.f,9.f,};\n\n  std::cout << \"SIMD reduce    :\"\n            << boost::simd::reduce( &values[0], &values[0]+9, 1.f\n                                  , boost::simd::multiplies\n                                  )\n            << std::endl;\n\n  return 0;\n}\n//! [reduce-phase]\n", "meta": {"hexsha": "10713798aac70e60e7bb54804ab60e673ee8bdfd", "size": 812, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/doc/range/reduce.phase.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": "test/doc/range/reduce.phase.cpp", "max_issues_repo_name": "remymuller/boost.simd", "max_issues_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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/doc/range/reduce.phase.cpp", "max_forks_repo_name": "remymuller/boost.simd", "max_forks_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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.0740740741, "max_line_length": 100, "alphanum_fraction": 0.4150246305, "num_tokens": 178, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624890918021, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.498580107236145}}
{"text": "#define BOOST_TEST_MODULE \"Test General Distance Function\"\n\n#include <boost/test/unit_test.hpp>\n#include <cmath>\n#include <iostream>\n\n#include \"distance/Euclidean.hpp\"\n#include \"distance/Chebyshev.hpp\"\n#include \"distance/Manhattan.hpp\"\n#include \"distance/Cosine.hpp\"\n#include \"distance/Distance.hpp\"\n#include \"Exception.hpp\"\n#include \"TimeSeries.hpp\"\n\nusing namespace genex;\nusing std::isinf;\n\n#define TOLERANCE 1e-9\nstruct MockData\n{\n  dist_t euclidean_dist = pairwiseDistance<Euclidean, double>;\n  dist_t manhattan_dist = pairwiseDistance<Manhattan, double>;\n  dist_t chebyshev_dist = pairwiseDistance<Chebyshev, double>;\n\n  dist_t euclidean_warped_dist = warpedDistance<Euclidean, double>;\n  dist_t manhattan_warped_dist = warpedDistance<Manhattan, double>;\n  dist_t chebyshev_warped_dist = warpedDistance<Chebyshev, double>;\n\n  data_t dat_1[5] = {1, 2, 3, 4, 5};\n  data_t dat_2[5] = {11, 2, 3, 4, 5};\n\n  data_t dat_3[2] = {2, 4};\n  data_t dat_4[5] = {2, 2, 2, 4, 4};\n\n  data_t dat_5[4] = {1, 2, 2, 4};\n  data_t dat_6[4] = {1, 2, 4, 5};\n\n  data_t dat_7[4] = {2, 2, 2, 2};\n  data_t dat_8[4] = {20, 20, 20, 15};\n\n  data_t dat_9[6]  = {2, 2, 2, 2, 2, 2};\n  data_t dat_10[6] = {4, 3, 3, 3, 3, 3};\n\n  data_t dat_11[7] = {4, 3, 5, 3, 5, 3, 4};\n  data_t dat_12[7] = {4, 3, 3, 1, 1, 3, 4};\n\n  data_t dat_13[10] = {0, 2, 3, 5, 8, 6, 3, 2, 3, 5};\n  data_t dat_14[7] =  {8, 4, 6, 1, 5, 10, 9};\n};\n\nBOOST_AUTO_TEST_CASE( general_distance, *boost::unit_test::tolerance(TOLERANCE) )\n{\n  MockData data;\n  TimeSeries ts_1(data.dat_1, 0, 0, 5);\n  TimeSeries ts_2(data.dat_2, 0, 0, 5);\n\n  data_t total_1 = data.euclidean_dist(ts_1, ts_2, INF, gNoMatching);\n  BOOST_TEST( total_1, 2.0 );\n\n  data_t total_2 = data.manhattan_dist(ts_1, ts_2, INF, gNoMatching);\n  BOOST_TEST( total_2, 2.0 );\n\n  data_t total_3 = data.chebyshev_dist(ts_1, ts_2, INF, gNoMatching);\n  BOOST_TEST( total_3, 10.0 );\n}\n\nBOOST_AUTO_TEST_CASE( easy_general_warped_distance, *boost::unit_test::tolerance(TOLERANCE) )\n{\n  MockData data;\n  TimeSeries ts_1{data.dat_1, 0, 0, 2};\n  TimeSeries ts_2{data.dat_2, 0, 0, 2};\n\n  TimeSeries ts_3{data.dat_3, 0, 0, 2};\n  TimeSeries ts_4{data.dat_4, 0, 0, 5};\n\n  TimeSeries ts_5{data.dat_5, 0, 0, 4};\n  TimeSeries ts_6{data.dat_6, 0, 0, 4};\n\n  TimeSeries ts_11{data.dat_11, 0, 0, 7};\n  TimeSeries ts_12{data.dat_12, 0, 0, 7};\n\n  setWarpingBandRatio(1.0);\n\n  data_t total_0 = data.euclidean_warped_dist(ts_1, ts_2, INF, gNoMatching);\n  BOOST_TEST( total_0 == sqrt(100.0) / (2 * 2) );\n\n  data_t total_1 = data.euclidean_warped_dist(ts_3, ts_4, INF, gNoMatching);\n  BOOST_TEST( total_1 == 0.0 );\n\n  data_t total_2 = data.manhattan_warped_dist(ts_3, ts_4, INF, gNoMatching);\n  BOOST_TEST( total_2 == 0.0 );\n\n  data_t total_3 = data.chebyshev_warped_dist(ts_3, ts_4, INF, gNoMatching);\n  BOOST_TEST( total_3 == 0.0 );\n\n  data_t total_4 = data.euclidean_warped_dist(ts_5, ts_6, INF, gNoMatching);\n  BOOST_TEST( total_4 == sqrt(1.0) / (2 * 4.0) );\n\n  data_t total_5 = data.manhattan_warped_dist(ts_5, ts_6, INF, gNoMatching);\n  BOOST_TEST( total_5 == 1.0/ (2 * 4.0) );\n\n  data_t total_6 = data.chebyshev_warped_dist(ts_5, ts_6, INF, gNoMatching);\n  BOOST_TEST( total_6 == 1.0 );\n\n  data_t total_7 = data.euclidean_warped_dist(ts_11, ts_12, INF, gNoMatching);\n  data_t result_7 = sqrt(12.0)/ (2 * 7);\n  BOOST_TEST( total_7 == result_7 );\n\n  data_t total_8 = data.manhattan_warped_dist(ts_11, ts_12, INF, gNoMatching);\n  BOOST_TEST( total_8 == 8.0 / (2 * 7) );\n\n  data_t total_9 = data.chebyshev_warped_dist(ts_11, ts_12, INF, gNoMatching);\n  BOOST_TEST( total_9 == (2.0) );\n\n  matching_t matching_1 = {};\n  matching_t matching_1_test = {{0, 0}, {1, 1}};\n  data_t total_10 = data.euclidean_warped_dist(ts_1, ts_2, INF, matching_1);\n  BOOST_TEST( total_10 == sqrt(100.0) / (2 * 2) );\n  BOOST_TEST( matching_1 == matching_1_test);\n\n  matching_t matching_2 = {};\n  matching_t matching_2_test = {{0, 0}, {0, 1}, {0, 2}, {1, 3}, {1, 4}};\n  data_t total_11 = data.euclidean_warped_dist(ts_3, ts_4, INF, matching_2);\n  BOOST_TEST( total_11 == 0 );\n  BOOST_TEST( matching_2 == matching_2_test);\n\n  matching_t matching_3 = {};\n  matching_t matching_3_test = {{0, 0}, {0, 1}, {0, 2}, {1, 3}, {1, 4}};\n  data_t total_12 = data.manhattan_warped_dist(ts_3, ts_4, INF, matching_3);\n  BOOST_TEST( total_12 == 0 );\n  BOOST_TEST( matching_3 == matching_3_test);\n\n  matching_t matching_4 = {};\n  matching_t matching_4_test = {{0, 0}, {0, 1}, {0, 2}, {1, 3}, {1, 4}};\n  data_t total_13 = data.chebyshev_warped_dist(ts_3, ts_4, INF, matching_4);\n  BOOST_TEST( total_13 == 0 );\n  BOOST_TEST( matching_4 == matching_4_test);\n\n  matching_t matching_5 = {};\n  matching_t matching_5_test = {{0, 0}, {1, 1}, {2, 1}, {3, 2}, {3, 3}};\n  data_t total_14 = data.euclidean_warped_dist(ts_5, ts_6, INF, matching_5);\n  BOOST_TEST( total_14 == sqrt(1.0) / (2 * 4.0) );\n  BOOST_TEST( matching_5 == matching_5_test);\n\n  matching_t matching_6 = {};\n  matching_t matching_6_test = {{0, 0}, {1, 1}, {2, 1}, {3, 2}, {3, 3}};\n  data_t total_15 = data.manhattan_warped_dist(ts_5, ts_6, INF, matching_6);\n  BOOST_TEST( total_15 == sqrt(1.0) / (2 * 4.0) );\n  BOOST_TEST( matching_6 == matching_6_test);\n  \n  matching_t matching_7 = {};\n  matching_t matching_7_test = {{0, 0}, {1, 1}, {2, 1}, {3, 2}, {3, 3}};\n  data_t total_16 = data.chebyshev_warped_dist(ts_5, ts_6, INF, matching_7);\n  BOOST_TEST( total_16 == 1.0 );\n  BOOST_TEST( matching_7 == matching_7_test);\n}\n\nBOOST_AUTO_TEST_CASE( easy_gwd_dropout, *boost::unit_test::tolerance(TOLERANCE) )\n{\n  MockData data;\n  TimeSeries ts_3{data.dat_3, 0, 0, 2};\n  TimeSeries ts_4{data.dat_4, 0, 0, 5};\n\n  TimeSeries ts_7{data.dat_7, 0, 0, 4};\n  TimeSeries ts_8{data.dat_8, 0, 0, 4};\n\n  data_t total_1 = data.euclidean_warped_dist(ts_3, ts_4, 5, gNoMatching);\n  BOOST_TEST( total_1 == 0.0 );\n\n  data_t total_2 = data.manhattan_warped_dist(ts_3, ts_4, 5, gNoMatching);\n  BOOST_TEST( total_2 == 0.0 );\n\n  data_t total_3 = data.chebyshev_warped_dist(ts_3, ts_4, 5, gNoMatching);\n  BOOST_TEST( total_3 == 0.0 );\n\n  data_t total_5 = data.manhattan_warped_dist(ts_7, ts_8, 5, gNoMatching);\n  BOOST_TEST( isinf(total_5) );\n\n  data_t total_6 = data.chebyshev_warped_dist(ts_7, ts_8, 5, gNoMatching);\n  BOOST_TEST( isinf(total_6) );\n}\n\nBOOST_AUTO_TEST_CASE( gwd_different_distances, *boost::unit_test::tolerance(TOLERANCE) )\n{\n  MockData data;\n  TimeSeries ts_9{data.dat_9, 0, 0, 6};\n  TimeSeries ts_10{data.dat_10, 0, 0, 6};\n\n  data_t total_1 = data.euclidean_warped_dist(ts_9, ts_10, INF, gNoMatching);\n  BOOST_TEST( total_1 == sqrt(9.0)/(2 * 6) );\n\n  data_t total_2 = data.manhattan_warped_dist(ts_9, ts_10, INF, gNoMatching);\n  BOOST_TEST( total_2 == 7.0/ (2 * 6) );\n\n  data_t total_3 = data.chebyshev_warped_dist(ts_9, ts_10, INF, gNoMatching);\n  BOOST_TEST( total_3 == 2.0 );\n}\n\nBOOST_AUTO_TEST_CASE( get_distance_metric, *boost::unit_test::tolerance(TOLERANCE) )\n{\n  MockData data;\n  TimeSeries ts_for_function_call{data.dat_3, 0, 0, 2};\n  const dist_t d = getDistanceFromName(\"euclidean\");\n  BOOST_CHECK(d);\n}\n\nBOOST_AUTO_TEST_CASE( distance_not_found )\n{\n  BOOST_CHECK_THROW( getDistanceFromName(\"oracle\"), GenexException );\n}\n\nBOOST_AUTO_TEST_CASE( keogh_lower_bound, *boost::unit_test::tolerance(TOLERANCE) )\n{\n  MockData data;\n  TimeSeries a{data.dat_13, 10};\n  TimeSeries b{data.dat_14, 7};\n\n  setWarpingBandRatio(0.2);\n  data_t klb = keoghLowerBound(a, b, 10);\n\n  BOOST_TEST( klb == sqrt(31.0) / (2 * 10) );\n}\n", "meta": {"hexsha": "de886ad90ecdb53dc8675b231bcd35df88a90966", "size": 7400, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/distance/DistanceTest.cpp", "max_stars_repo_name": "mihinsumaria/genex", "max_stars_repo_head_hexsha": "34786b0cf5d573348b82e5d164dbc05e0411d6a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-06-28T07:36:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-11T07:49:24.000Z", "max_issues_repo_path": "test/distance/DistanceTest.cpp", "max_issues_repo_name": "mihinsumaria/genex", "max_issues_repo_head_hexsha": "34786b0cf5d573348b82e5d164dbc05e0411d6a8", "max_issues_repo_licenses": ["MIT"], "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/distance/DistanceTest.cpp", "max_forks_repo_name": "mihinsumaria/genex", "max_forks_repo_head_hexsha": "34786b0cf5d573348b82e5d164dbc05e0411d6a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-01T20:25:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-01T20:25:42.000Z", "avg_line_length": 33.1838565022, "max_line_length": 93, "alphanum_fraction": 0.6852702703, "num_tokens": 2885, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.6370308013713525, "lm_q1q2_score": 0.49858010617067905}}
{"text": "#include <iostream>\n#include <cmath>\n#include <algorithm>\n#include <vector>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/lexical_cast.hpp>\nusing namespace boost::multiprecision;\nusing namespace std;\nvoid solve(cpp_int x, vector<cpp_int> &v) {\n    if (x > 3234566667) return;\n    v.push_back(x);\n    cpp_int base = x * 10, m = x % 10;\n    for (int i = -1; i <= 1; i++) {\n        if (m + i >= 0 && m + i <= 9) solve(base + (m + i), v);\n    }\n}\nint main() {\n    int k; cin >> k;\n    vector<cpp_int> v;\n    for (int i = 1; i <= 9; i++) solve(i, v);\n    sort(v.begin(), v.end());\n    cout << v[k - 1] << endl;\n}\n", "meta": {"hexsha": "354a4ea955cbc0ec09da053b491b72a385d4eaeb", "size": 622, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AtCoder/abc161/d/main.cpp", "max_stars_repo_name": "H-Tatsuhiro/Com_Pro-Cpp", "max_stars_repo_head_hexsha": "fd79f7821a76b11f4a6f83bbb26a034db577a877", "max_stars_repo_licenses": ["MIT"], "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/abc161/d/main.cpp", "max_issues_repo_name": "H-Tatsuhiro/Com_Pro-Cpp", "max_issues_repo_head_hexsha": "fd79f7821a76b11f4a6f83bbb26a034db577a877", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-10-19T08:47:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T05:23:56.000Z", "max_forks_repo_path": "AtCoder/abc161/d/main.cpp", "max_forks_repo_name": "H-Tatsuhiro/Com_Pro-Cpp", "max_forks_repo_head_hexsha": "fd79f7821a76b11f4a6f83bbb26a034db577a877", "max_forks_repo_licenses": ["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.9166666667, "max_line_length": 63, "alphanum_fraction": 0.5643086817, "num_tokens": 206, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624890918021, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.4985800964495385}}
{"text": "//------------------------------------------------------------------------------\n/*\n    This file is part of rippled: https://github.com/ripple/rippled\n    Copyright (c) 2012-2015 Ripple Labs Inc.\n\n    Permission to use, copy, modify, and/or distribute this software for any\n    purpose  with  or without fee is hereby granted, provided that the above\n    copyright notice and this permission notice appear in all copies.\n\n    THE  SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n    WITH  REGARD  TO  THIS  SOFTWARE  INCLUDING  ALL  IMPLIED  WARRANTIES  OF\n    MERCHANTABILITY  AND  FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n    ANY  SPECIAL ,  DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n    WHATSOEVER  RESULTING  FROM  LOSS  OF USE, DATA OR PROFITS, WHETHER IN AN\n    ACTION  OF  CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n    OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n*/\n//==============================================================================\n\n#include <ripple/basics/mulDiv.h>\n#include <ripple/basics/contract.h>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <limits>\n#include <utility>\n\nnamespace ripple\n{\n\nstd::pair<bool, std::uint64_t>\nmulDiv(std::uint64_t value, std::uint64_t mul, std::uint64_t div)\n{\n    using namespace boost::multiprecision;\n\n    uint128_t result;\n    result = multiply(result, value, mul);\n\n    result /= div;\n\n    auto constexpr limit = std::numeric_limits<std::uint64_t>::max();\n\n    if (result > limit)\n        return { false, limit };\n\n    return { true, static_cast<std::uint64_t>(result) };\n}\n\n} // ripple\n", "meta": {"hexsha": "232817aaeab1b1f8e6db77756c2c2bae6c357f0f", "size": 1645, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ripple/basics/impl/mulDiv.cpp", "max_stars_repo_name": "tlongwell-ripple/rippled", "max_stars_repo_head_hexsha": "4e3dc0e820aa5bcf187ebe1b5d4471932845cc89", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-02T01:19:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-02T01:19:23.000Z", "max_issues_repo_path": "src/ripple/basics/impl/mulDiv.cpp", "max_issues_repo_name": "tlongwell-ripple/rippled", "max_issues_repo_head_hexsha": "4e3dc0e820aa5bcf187ebe1b5d4471932845cc89", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2020-02-03T14:00:08.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-23T17:29:21.000Z", "max_forks_repo_path": "src/ripple/basics/impl/mulDiv.cpp", "max_forks_repo_name": "tlongwell-ripple/rippled", "max_forks_repo_head_hexsha": "4e3dc0e820aa5bcf187ebe1b5d4471932845cc89", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-02-03T14:22:58.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-28T20:57:19.000Z", "avg_line_length": 34.2708333333, "max_line_length": 80, "alphanum_fraction": 0.6443768997, "num_tokens": 367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.49858008999076964}}
{"text": "#include <CGAL/Polyhedron_3.h>\n#include <CGAL/Polyhedron_items_with_id_3.h>\n#include <CGAL/boost/graph/graph_traits_Polyhedron_3.h>\n#include <CGAL/Simple_cartesian.h>\n#include <CGAL/extract_mean_curvature_flow_skeleton.h>\n#include <CGAL/Polygon_mesh_processing/connected_components.h>\n#include <CGAL/IO/Polyhedron_iostream.h>\n\n#include <boost/foreach.hpp>\n\n#include <fstream>\n#include <set>\n#include <queue>\n\ntypedef CGAL::Simple_cartesian<double>                               Kernel;\ntypedef Kernel::Point_3                                              Point;\ntypedef Kernel::Vector_3                                             Vector;\ntypedef CGAL::Polyhedron_3<Kernel, CGAL::Polyhedron_items_with_id_3> Polyhedron;\ntypedef boost::graph_traits<Polyhedron>::vertex_descriptor           vertex_descriptor;\n\ntypedef CGAL::Mean_curvature_flow_skeletonization<Polyhedron>        Mean_curvature_skeleton;\ntypedef Mean_curvature_skeleton::Skeleton                            Skeleton;\ntypedef boost::graph_traits<Skeleton>::vertex_descriptor             vertex_desc;\ntypedef boost::graph_traits<Skeleton>::edge_descriptor             edge_desc;\n\n// The input of the skeletonization algorithm must be a pure triangular closed\n// mesh and has only one component.\nbool is_mesh_valid(Polyhedron& pMesh)\n{\n  if (!pMesh.is_closed())\n  {\n    std::cerr << \"The mesh is not closed.\";\n    return false;\n  }\n  if (!pMesh.is_pure_triangle())\n  {\n    std::cerr << \"The mesh is not a pure triangle mesh.\";\n    return false;\n  }\n\n  // the algorithm is only applicable on a mesh\n  // that has only one connected component\n  std::size_t num_component;\n  CGAL::Counting_output_iterator output_it(&num_component);\n  CGAL::internal::corefinement::extract_connected_components(pMesh, output_it);\n  ++output_it;\n  if (num_component != 1)\n  {\n    std::cerr << \"The mesh is not a single closed mesh. It has \"\n              << num_component << \" components.\";\n    return false;\n  }\n  return true;\n}\n\nint main()\n{\n  Polyhedron mesh;\n  std::ifstream input(\"data/elephant.off\");\n\n  if ( !input || !(input >> mesh) || mesh.empty() ) {\n    std::cerr << \"Cannot open data/elephant.off\" << std::endl;\n    return EXIT_FAILURE;\n  }\n  if (!is_mesh_valid(mesh)) {\n    return EXIT_FAILURE;\n  }\n\n  Skeleton skeleton;\n\n  CGAL::extract_mean_curvature_flow_skeleton(mesh, skeleton);\n\n  if (num_vertices(skeleton) == 0)\n  {\n    std::cerr << \"The number of skeletal points is zero!\\n\";\n    return EXIT_FAILURE;\n  }\n\n// check all vertices are seen exactly once\n{\n  std::set<vertex_descriptor> visited;\n  BOOST_FOREACH(vertex_desc v, vertices(skeleton))\n  {\n    BOOST_FOREACH(vertex_descriptor vd, skeleton[v].vertices)\n      if (!visited.insert(vd).second)\n      {\n        std::cerr << \"A vertex was seen twice!\\n\";\n        return EXIT_FAILURE;\n      }\n  }\n\n  BOOST_FOREACH(vertex_descriptor vd, vertices(mesh))\n  {\n    if (!visited.count(vd))\n    {\n      std::cerr << \"A vertex was not seen!\\n\";\n      return EXIT_FAILURE;\n    }\n  }\n}\n\n// check the skeleton is connected\n{\n  std::queue<vertex_desc> qu;\n  std::set<vertex_desc> visited;\n\n  qu.push(*vertices(skeleton).first);\n  visited.insert(qu.back());\n\n  while (!qu.empty())\n  {\n    vertex_desc cur = qu.front();\n    qu.pop();\n\n    BOOST_FOREACH(edge_desc ed, in_edges(cur, skeleton))\n    {\n      vertex_desc next = source(ed, skeleton);\n      if (visited.insert(next).second)\n        qu.push(next);\n    }\n  }\n\n  BOOST_FOREACH(vertex_desc vd, vertices(skeleton))\n  {\n    if (!visited.count(vd))\n    {\n      std::cerr << \"Skeleton curve is not fully connected!\\n\";\n      return EXIT_FAILURE;\n    }\n  }\n}\n  std::cout << \"Pass connectivity test.\\n\";\n  return EXIT_SUCCESS;\n}\n\n", "meta": {"hexsha": "c6984fac8a5c1346102b93c51a82799bb26a38f7", "size": 3679, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "graphics/cgal/Surface_mesh_skeletonization/test/Surface_mesh_skeletonization/skeleton_connectivity_test.cpp", "max_stars_repo_name": "hlzz/dotfiles", "max_stars_repo_head_hexsha": "0591f71230c919c827ba569099eb3b75897e163e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-03-30T14:31:52.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-02T05:01:32.000Z", "max_issues_repo_path": "graphics/cgal/Surface_mesh_skeletonization/test/Surface_mesh_skeletonization/skeleton_connectivity_test.cpp", "max_issues_repo_name": "hlzz/dotfiles", "max_issues_repo_head_hexsha": "0591f71230c919c827ba569099eb3b75897e163e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "graphics/cgal/Surface_mesh_skeletonization/test/Surface_mesh_skeletonization/skeleton_connectivity_test.cpp", "max_forks_repo_name": "hlzz/dotfiles", "max_forks_repo_head_hexsha": "0591f71230c919c827ba569099eb3b75897e163e", "max_forks_repo_licenses": ["BSD-3-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.0514705882, "max_line_length": 93, "alphanum_fraction": 0.6605055722, "num_tokens": 897, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140728, "lm_q2_score": 0.6370307875894138, "lm_q1q2_score": 0.49858008892530375}}
{"text": "/******************************************************\n    Author : shipeng_liu \n    Email : 1196075299@qq.com\n    Description: Adaptive dynamic programming \n******************************************************/\n#include <cmath>\n#include<iostream>\n#include <fstream>\n#include <iomanip>\n#include <Eigen/Dense>\n#include \"rambot_controller/src/controller/adp_learning/critic_network.cpp\"\nusing namespace std;\n\n/****************************************************************** \n    Action Network\n    Input: S, diff_s\n    number of hidden_layer: 1\n    number of active_function: hidden_number\n    output: steer_cmd\n    parameter_layer1: parameters from input to hidden_layer\n    parameter_layer2: parameters from hidden_layer to output\n******************************************************************/\n\nclass action_network {\n\n  private:\n\n    double learning_rate = 0.00001 ; //learning rate\n    double reward_count = 1;\n    Eigen::MatrixXd parameter_layer1;\n    Eigen::MatrixXd parameter_layer2;\n    Eigen::MatrixXd input_variable;\n    Eigen::MatrixXd hidden_layer;\n    Eigen::MatrixXd p_hidden_layer;\n    double output;\n    int hidden_number;\n    double deriva_J_u;\n    static double active_function(double input) {\n        // 1 - exp( - qi(t) ) / 1 + exp( - qi(t) ) )\n        double ret = std::exp(- input);\n        double tmp = (2)/(1 + ret) - 1;\n        return tmp;\n    }\n\n\n  public:\n\n    action_network() \n    {\n        hidden_number = 4;\n        init();\n    }\n\n    void init()\n    {\n        parameter_layer1 = Eigen::MatrixXd::Random(2, hidden_number);\n        parameter_layer2 = Eigen::MatrixXd::Random(hidden_number, 1);\n        \n        hidden_layer = Eigen::MatrixXd::Random(1, hidden_number);\n        p_hidden_layer = Eigen::MatrixXd::Random(1, hidden_number);\n        input_variable = Eigen::MatrixXd::Random(1,2);\n        output = 0;\n\n    }\n\n    double output_cmd(double s, double diff_s)\n    {\n        input_variable(0,0) = s;\n        input_variable(0,1) = diff_s;\n        //cout << parameter_layer1 << endl;\n        //cout << parameter_layer2 << endl;\n        hidden_layer = input_variable * parameter_layer1;\n        \n        for (int i = 0; i < hidden_number; i++)\n        {\n            p_hidden_layer(0,i) = active_function(hidden_layer(0,i));\n            // limit the p_Hidden_layer\n            if (p_hidden_layer(0,i) < 0.000001 && p_hidden_layer(0,i) > 0 )\n                p_hidden_layer(0,i) = 0.000001;\n            else if (p_hidden_layer(0,i) > -0.000001 && p_hidden_layer(0,i) < 0)\n                p_hidden_layer(0,i) = - 0.000001;\n        }\n        Eigen::MatrixXd test = p_hidden_layer * parameter_layer2;\n        output = test(0,0);\n        output = active_function(output);\n        return output;\n    }\n\n    void update_weight(double J_cost, critic_network *critic_network)\n    {\n       \n        \n        double reference_signal = 0;\n        double eat = J_cost - reference_signal;\n        cout << \"\\naction_network_information:\\n\";\n        cout << left << setw(20) << \"[ refer: \" << right\n             << setw(20) << reference_signal << \"]\" << endl;\n        cout << left << setw(20) << \"[ J_cost: \" << right\n             << setw(20) << J_cost << \"]\" << endl;\n        cout << left << setw(20) << \"[ eat: \" << right\n             << setw(20) << eat << \"]\" << endl;\n        cout << left << setw(20) << \"[ p_hidden_layer: \" << right\n             << setw(20) << p_hidden_layer << \"]\" << endl;\n        cout << \"[ p_hidden_layer: \" << endl;\n        cout << p_hidden_layer << endl;\n        \n        // cout <<  \"[ parameter_layer1: \" << endl;\n        // cout << parameter_layer1 << endl;\n        \n        // cout << \"[ parameter_layer2: \" << endl;\n        // cout << parameter_layer2 << endl;\n    \n             \n        // compute the derivative of J to U\n        for (int l = 0; l < 4; l++)\n        {\n            deriva_J_u += ( critic_network->return_parameter_layer2()(l,0) ) * 0.5 * (1 - pow(critic_network->return_p_hidden_layer()(0,l),2)) * critic_network->return_parameter_layer1()(2,l);\n        }\n        for (int j = 0; j < hidden_number; j++)\n        {\n            //compute the parameter_layer1\n            for (int k = 0; k < 2; k++)\n            {\n                \n                double derivative_1 = reward_count * eat *  0.5 * (1-pow(output,2)) * parameter_layer2(j,0) * 0.5 * (1 - pow(p_hidden_layer(0,j),2)) * input_variable(0,k) * deriva_J_u;\n                double delta_weight1 = learning_rate * (- derivative_1);\n                \n                parameter_layer1(k,j) += delta_weight1; \n            }\n\n            // compute the parameter_layer2 \n           \n            double derivative =  reward_count * eat * 0.5 * (1-pow(output,2)) *(p_hidden_layer(0,j)) * deriva_J_u;\n            \n            double delta_weight = learning_rate * (- derivative);\n            parameter_layer2(j,0) += delta_weight;\n\n        }\n        \n    }\n};\n    \n    ", "meta": {"hexsha": "76ee7a787c1872d858cb59399894f23579be8370", "size": 4889, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/controller/src/controller/adp_learning/action_network.cpp", "max_stars_repo_name": "TJ-Work/CVSC", "max_stars_repo_head_hexsha": "6850bcffe765a6586dc5a81900206398be6dc1f5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/controller/src/controller/adp_learning/action_network.cpp", "max_issues_repo_name": "TJ-Work/CVSC", "max_issues_repo_head_hexsha": "6850bcffe765a6586dc5a81900206398be6dc1f5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/controller/src/controller/adp_learning/action_network.cpp", "max_forks_repo_name": "TJ-Work/CVSC", "max_forks_repo_head_hexsha": "6850bcffe765a6586dc5a81900206398be6dc1f5", "max_forks_repo_licenses": ["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.1888111888, "max_line_length": 192, "alphanum_fraction": 0.5313970137, "num_tokens": 1187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970748488297, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4985474701109455}}
{"text": "#pragma once\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <vector>\n#include <random>\n#include <numeric>\n#include <iostream>\n\nusing namespace std;\nusing namespace Eigen;\n\ntemplate <typename state>\nstruct ParticleFilter{\n    ParticleFilter(int number_of_particles, int states, function<void (int id)> process, function<double (int id)> cost,\n                   VectorXd &start, double std):\n            number_of_particles(number_of_particles), process(process), cost(cost), start(start){\n        particles.resize(number_of_particles, VectorXd(states));\n        weights.resize(number_of_particles, 1.0/number_of_particles);\n        costs.resize(number_of_particles,RAND_MAX);\n        cumsum.resize(number_of_particles);\n        indx.resize(number_of_particles);\n\n        distribution = normal_distribution<double>(0,std);\n        state_length = particles.begin()->size();\n\n        resample(true);\n    }\n\n    void step(){\n        double sum_of_elems = 0.0;\n        for(uint i=0;i<number_of_particles;i++){\n            process(i);\n            costs[i] = cost(i);\n            sum_of_elems += costs[i];\n        }\n\n        double Neff = 0.0, weight_sum = 0.0;\n        for(uint i=0;i<number_of_particles;i++){\n            weights[i] = costs[i]/sum_of_elems;\n            weight_sum += weights[i];\n            Neff += pow(weights[i],2.0);\n        }\n\n        Neff = 1.0/Neff;\n\n        if(Neff < number_of_particles/2.0) {\n            cout <<\"resample, Neff: \" << Neff << endl;\n            resample(false, Neff);\n        }\n    }\n\n    double result(state &winner, int *index){\n        double val;\n        minimum<double>(costs, val, index);\n        winner = particles[*index];\n        return val;\n    }\n\n    function<double (int id)> cost;\n    function<void (int id)> process;\n\n    void resample(bool all, int N = 0){\n        if(all){ //resample all\n            for(state &particle:particles){\n                particle = start;\n                for(int i=0;i<state_length;i++){\n                    particle(i) += distribution(generator);\n                }\n            }\n        }else{ // Sampling Importance Resampling\n            vector<size_t> indexes = sort_indexes<double>(weights);\n            for(uint i=0;i<N;i++){\n                particles[indexes[i]] = particles[indexes[number_of_particles-1-i]];\n                double w0 = weights[indexes[i]], w1 = indexes[number_of_particles-1-i];\n\n            }\n\n        }\n    }\n\n    template<typename T>\n    void minimum(vector<T> &v, T &val, int *index ){\n        *index = 0;\n        val = v[0];\n        for(uint i=1; i<v.size(); i++){\n            if(v[i]<val){\n                val = v[i];\n                *index = i;\n            }\n        }\n    }\n\n    template <typename T>\n    vector<size_t> sort_indexes(const vector<T> &v) {\n\n        // initialize original index locations\n        vector<size_t> idx(v.size());\n        iota(idx.begin(), idx.end(), 0);\n\n        // sort indexes based on comparing values in v\n        sort(idx.begin(), idx.end(),\n             [&v](size_t i1, size_t i2) {return v[i1] > v[i2];});\n\n        return idx;\n    }\n\n    vector<state> particles;\n    vector<double> weights, costs;\n    vector<double> cumsum;\n    vector<int> indx;\n    int number_of_particles;\n    default_random_engine generator;\n    normal_distribution<double> distribution;\n    int state_length;\n    VectorXd start;\n};", "meta": {"hexsha": "e3fb3670439c17da1cb6778ac91f2ca5392fb855", "size": 3358, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/darkroom/ParticleFilter.hpp", "max_stars_repo_name": "Roboy/DarkRoom_rviz", "max_stars_repo_head_hexsha": "8f049218bc600d4b179303493a70bfe2389df73c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-07-06T15:34:19.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-04T00:22:54.000Z", "max_issues_repo_path": "include/darkroom/ParticleFilter.hpp", "max_issues_repo_name": "Roboy/DarkRoom_rviz", "max_issues_repo_head_hexsha": "8f049218bc600d4b179303493a70bfe2389df73c", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/darkroom/ParticleFilter.hpp", "max_forks_repo_name": "Roboy/DarkRoom_rviz", "max_forks_repo_head_hexsha": "8f049218bc600d4b179303493a70bfe2389df73c", "max_forks_repo_licenses": ["BSD-3-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.7008547009, "max_line_length": 120, "alphanum_fraction": 0.5652173913, "num_tokens": 767, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.810478926981208, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4985157451378339}}
{"text": "/*\n * Path-related utility functions.\n *\n * Copyright (C) 2014-2015 DubinsPathPlanner.\n * Created by David Goodman <dagoodma@gmail.com>\n * Redistribution and use of this file is allowed according to the terms of the MIT license.\n * For details see the LICENSE file distributed with DubinsPathPlanner.\n */\n#include <stdio.h>\n#include <math.h>\n#include <algorithm>\n\n#include <Eigen/Dense>\n\n#include <DubinsCurves.h>\n\n#include <dpp/basic/basic.h>\n#include <dpp/basic/Logger.h>\n#include <dpp/basic/Path.h>\n#include <dpp/basic/Util.h>\n\nusing Eigen::Vector3d;\nusing Eigen::Vector2d;\n\n\n#define HEADING_TOLERANCE          1E-10 // upperbound for Euclidean metric, radius safe?\n\nnamespace dpp {\n\n/**\n * Calculate the shortest Dubins' path distance to the node. Note that all angles\n * used in this function are heading angles from 0 at the y-axis, and\n * counter-clockwise is positive. \n * @FIXME Add RLR and LRL curves. Does this fix dist > 3*r?\n */\ndouble dubinsPathLength(VehicleConfiguration &Cs, VehicleConfiguration &Ce,\n    double turnRadius) {\n    double r = turnRadius; // shorter name\n    Vector2d Ps = Vector2d(Cs.x(), Cs.y()),\n        Pe = Vector2d(Ce.x(), Ce.y());\n    double Xs = Cs.m_heading,\n        Xe = Ce.m_heading;\n    double dist = (Ps - Pe).norm();\n\n    Logger::logDebug(DPP_LOGGER_VERBOSE_3) << \"Given Cs=\" << Cs << \", Ce=\" << Ce << \", r=\" << r << std::endl;\n    Logger::logDebug(DPP_LOGGER_VERBOSE_3) << \"Got dist=\" << dist << \" compared to r=\" << r << \".\" << std::endl;\n\n\n    // Added tolerance to avoid numerical instability for paths with no curviture\n    // TODO compute curviture as ratio w.r.t. turn radius?\n    // FIXME this does not take into account the feasability of the path! \n    //        Should add an isReachable( func)\n    if (fabs(Xs - Xe) <= HEADING_TOLERANCE) {\n        Logger::logDebug(DPP_LOGGER_VERBOSE_3) << \"Using straight line L=\" << (Pe - Ps).norm() << \". |Xs - Xe| = \"\n            << fabs(Xs - Xe) << \" <= \" << HEADING_TOLERANCE << std::endl;\n        return (Pe - Ps).norm();\n    }\n\n    //DPP_ASSERT(dist >= 3.0 * r);\n    // FIXME: return an unfeasible path macro, eg -1\n    // FIXME: improve this function so that we don't have to use the dubins-curves library\n    //         this is needed for boustrophedon algorithm which does not care if the\n    //         point dist is >= 3.0 * r\n    // note: Detect if the final heading is close to the opposite of the initial,\n    //       to allow for implementing CCC-type paths (ie. U-turns) via Dubins\n    //       Corollarry to theorem 1. Though this may not satisfy all cases where \n    //       no feasible paths exist. \"U-turn\" is either: {RLR or LRL}?\n    if (dist < 3.0 * r) {\n        //return DPP_MAX_EDGE_COST;\n        double *q0, *q1;\n        Cs.asArray(&q0);\n        Ce.asArray(&q1);\n        q0[2] = dpp::headingToAngle(q0[2]);\n        q1[2] = dpp::headingToAngle(q1[2]);\n        DubinsCurves::DubinsPath path;\n        DubinsCurves::dubins_init( q0, q1, turnRadius, &path);\n        double expectedLength = DubinsCurves::dubins_path_length(&path);\n        return expectedLength;\n    }\n    //if (dist < 3.0 * r) {\n    //  std::domain_error(\"distance must be larger than 3*r\");\n    //}\n\n    // Convert headings to circular angles\n    double alpha = headingToAngle(Xs),\n           beta = headingToAngle(Xe);\n\n    // Find circle center points for each case\n    Vector3d R_rs(cos(alpha - M_PI/2.0), sin(alpha - M_PI/2.0), 0.0),\n        R_ls(cos(alpha + M_PI/2.0), sin(alpha + M_PI/2.0), 0.0),\n        R_re(cos(beta - M_PI/2.0), sin(beta - M_PI/2.0), 0.0),\n        R_le(cos(beta + M_PI/2.0), sin(beta + M_PI/2.0), 0.0);\n\n    Vector3d PC_rs(Cs.x(), Cs.y(), 0.0),\n        PC_ls(Cs.x(), Cs.y(), 0.0),\n        PC_re(Ce.x(), Ce.y(), 0.0),\n        PC_le(Ce.x(), Ce.y(), 0.0);\n\n    PC_rs = PC_rs.transpose() + r*R_rs.transpose();\n    PC_ls = PC_ls.transpose() + r*R_ls.transpose();\n    PC_re = PC_re.transpose() + r*R_re.transpose();\n    PC_le = PC_le.transpose() + r*R_le.transpose();\n\n    Logger::logDebug(DPP_LOGGER_VERBOSE_3) << \"PC_rs: (\" << PC_rs.x() << \",\" << PC_rs.y()\n        << \",\" << PC_rs.z() << \",\" <<\").\" << std::endl;\n    Logger::logDebug(DPP_LOGGER_VERBOSE_3) << \"PC_ls: (\" << PC_ls.x() << \",\" << PC_ls.y()\n        << \",\" << PC_ls.z() << \",\" <<\").\" << std::endl;\n    Logger::logDebug(DPP_LOGGER_VERBOSE_3) << \"PC_re: (\" << PC_re.x() << \",\" << PC_re.y()\n        << \",\" << PC_re.z() << \",\" <<\").\" << std::endl;\n    Logger::logDebug(DPP_LOGGER_VERBOSE_3) << \"PC_le: (\" << PC_le.x() << \",\" << PC_le.y()\n        << \",\" << PC_le.z() << \",\" <<\").\" << std::endl;\n\n    // Case I, R-S-R\n    double x = headingBetween(PC_rs, PC_re);\n    double L1 = (PC_rs - PC_re).norm() \n        + r*wrapAngle(2.0 * M_PI + wrapAngle(x - M_PI/2.0) - wrapAngle(Xs - M_PI/2.0))\n        + r*wrapAngle(2.0 * M_PI + wrapAngle(Xe - M_PI/2.0) - wrapAngle(x - M_PI/2.0));\n\n    Logger::logDebug(DPP_LOGGER_VERBOSE_3) << \"L1: \" << L1 << \", with x=\" << x << std::endl;\n\n    // Case II, R-S-L\n    double ls = (PC_le - PC_rs).norm();\n    x = headingBetween(PC_rs, PC_le);\n    double x2 = x - M_PI/2.0 + asin(2.0*r/ls);\n    double L2 = sqrt(ls*ls - 4*r*r) + r*wrapAngle(2.0*M_PI + wrapAngle(x2)\n        - wrapAngle(Xs - M_PI/2.0)) + r*wrapAngle(2.0*M_PI + wrapAngle(x2 + M_PI)\n        - wrapAngle(Xe + M_PI/2.0));\n    Logger::logDebug(DPP_LOGGER_VERBOSE_3) << \"L2: \" << L2 << \" with ls=\" << ls << \", x=\" << x << \", x2=\" << x2 << std::endl;\n\n    // Case III, L-S-R\n    ls = (PC_re - PC_ls).norm();\n    x = headingBetween(PC_ls, PC_re);\n    double ratioOA = 2.0*r/ls;\n    // Bound the ratio from -1 to 1\n    ratioOA = std::max<double> (-1.0, ratioOA);\n    ratioOA = std::min<double> (1.0, ratioOA);\n    DPP_ASSERT(ratioOA <= 1.0 && ratioOA >= -1.0);\n    x2 = acos(ratioOA);\n    double L3 = sqrt(ls*ls - 4*r*r) + r*wrapAngle(2.0*M_PI + wrapAngle(Xs + M_PI/2.0) \n        - wrapAngle(x + x2)) + r*wrapAngle(2.0*M_PI + wrapAngle(Xe - M_PI/2.0)\n        - wrapAngle(x + x2 - M_PI));\n\n    Logger::logDebug(DPP_LOGGER_VERBOSE_3) << \"L3: \" << L3 << \" with ls=\" << ls << \", x=\" << x << \", x2=\"\n        << x2 << std::endl;\n\n    // Case IV, L-S-L\n    x = headingBetween(PC_ls, PC_le);\n    double L4 = (PC_ls - PC_le).norm() + r*wrapAngle(2.0*M_PI + wrapAngle(Xs + M_PI/2.0)\n        - wrapAngle(x + M_PI/2.0)) + r*wrapAngle(2.0*M_PI + wrapAngle(x + M_PI/2.0)\n        - wrapAngle(Xe + M_PI/2.0));\n\n    Logger::logDebug(DPP_LOGGER_VERBOSE_3) << \"L4: \" << L4 << \", with x=\" << x << std::endl;\n    Logger::logDebug(DPP_LOGGER_VERBOSE_3) << \"Comparing L1=\" << L1 << \" L2=\" << L2 << \" L3=\" << L3 << \" L4=\"\n        << L4 << std::endl;\n\n    return std::min({L1, L2, L3, L4});\n}\n\n/**\n * Finds the cost of the shortest dubins path over the given tour with headings.\n * If returnCost is true, the cost of returning back to the first node in the\n * tour will be included.\n * @param[in] G graph with nodes to tour\n * @param[in] GA attributes of the graph\n * @param[in] Tour ordered list of nodes to visit\n * @param[in] Headings for vehicle at each node\n * @param[in] turnRadius of the vehicle\n * @param[in] returnEdge whether to add a return edge back to the first node\n */\ndouble dubinsTourCost(ogdf::Graph &G, ogdf::GraphAttributes &GA,\n    ogdf::List<ogdf::node> &Tour, ogdf::NodeArray<double> &Headings,\n    double turnRadius, bool returnCost) {\n    ogdf::ListIterator<ogdf::node> iter;\n    double cost = 0.0;\n\n    if (Tour.size() < 2) {\n        Logger::logWarn(DPP_LOGGER_VERBOSE_1) << \"Zero cost for an empty tour.\" << std::endl;\n        return 0.0;\n    }\n\n    // Add the return edge if necessary\n    ogdf::List<ogdf::node> modTour(Tour);\n    ogdf::node lastNode = modTour.back();\n    if (returnCost && lastNode != *(modTour.begin())) {\n        modTour.pushBack(*(Tour.begin()));\n    }\n    else if (!returnCost && lastNode == *(modTour.begin())) {\n        modTour.popBack();\n    }\n\n    int m = modTour.size() - 1;\n    int i = 0; // edge index\n    for ( iter = modTour.begin(); (i < m && iter != modTour.end()); iter++ ) {\n        ogdf::node u = *iter, v = *(iter.succ());\n\n        VehicleConfiguration Cu(GA.x(u), GA.y(u), Headings(u)),\n                      Cv(GA.x(v), GA.y(v), Headings(v));\n        cost += dubinsPathLength(Cu, Cv, turnRadius);\n        i++;\n       \n        Logger::logDebug(DPP_LOGGER_VERBOSE_3) << \"Found cost \" << cost << \" from node \"\n            << GA.idNode(u) << \"->\" << GA.idNode(v) << \", where headings \"\n            << GA.idNode(u) << \": \" << Headings(u) << \", \" << GA.idNode(v) << \": \"\n            << Headings(v) << std::endl;\n    }\n    Logger::logDebug(DPP_LOGGER_VERBOSE_2) << \"Found total cost \"\n    << cost << \" for tour.\" << std::endl;\n\n    return cost;\n}\n\n/**\n * Adds weighted edges to the graph with the cost of the shortest dubins path\n * between each node in the tour. If returnEdge is true, an edge returning to the\n * origin is added. Added edges are saved into the list of edges.\n * @param[in] G graph with nodes to tour\n * @param[in] GA attributes of the graph\n * @param[in] Tour ordered list of nodes to visit\n * @param[in] Headings for vehicle at each node\n * @param[in] turnRadius of the vehicle\n * @param[out] Edges ordered list of edges to build\n * @param[in] returnEdge whether to add a return edge back to the first node\n */\ndouble createDubinsTourEdges(ogdf::Graph &G, ogdf::GraphAttributes &GA,\n    ogdf::List<ogdf::node> &Tour, ogdf::NodeArray<double> &Headings,\n    double turnRadius, ogdf::List<ogdf::edge> &Edges, bool returnEdge) {\n    ogdf::ListIterator<ogdf::node> iter;\n    double total_cost = 0.0;\n\n    if (Tour.size() < 2) return 0.0;\n    DPP_ASSERT(G.numberOfEdges() < 1);\n    //    std::range_error(\"Cannot have existing edges in graph\");\n    //}\n\n    // Add the return edge if necessary\n    ogdf::List<ogdf::node> modTour(Tour);\n    ogdf::node lastNode = modTour.back();\n    if (returnEdge && lastNode != *(modTour.begin())) {\n        modTour.pushBack(*(Tour.begin()));\n    }\n    else if (!returnEdge && lastNode == *(modTour.begin())) {\n        modTour.popBack();\n    }\n \n    int m = modTour.size() - 1;\n    int i = 0; // edge index\n    for ( iter = modTour.begin(); (i < m && iter != modTour.end()); iter++ ) {\n        ogdf::node u = *iter, v = *(iter.succ());\n\n        VehicleConfiguration Cu(GA.x(u), GA.y(u), Headings(u)),\n                      Cv(GA.x(v), GA.y(v), Headings(v));\n        double cost = dubinsPathLength(Cu, Cv, turnRadius);\n\n        Logger::logDebug(DPP_LOGGER_VERBOSE_3) << \"Found cost \" << cost << \" from node \"\n            << GA.idNode(u) << \"->\" << GA.idNode(v) << \", where headings \"\n            << GA.idNode(u) << \": \" << Headings(u) << \", \" << GA.idNode(v) << \": \"\n            << Headings(v) << std::endl;\n        //printf(\"Found cost %0.1f from node %d->%d, where headings %d: %0.1f, %d: %0.1f\\n\",\n        //    cost, GA.idNode(u), GA.idNode(v), GA.idNode(u), Headings(u), GA.idNode(v), Headings(v));\n\n        // Add the edge\n        ogdf::edge e = G.newEdge(u,v);\n        GA.doubleWeight(e) = cost;\n        Edges.pushBack(e);\n        total_cost += cost;\n        i++;\n    }\n    Logger::logDebug(DPP_LOGGER_VERBOSE_2) << \"Created tour edges with total cost \"\n    << total_cost << \": \" << std::endl;\n    Logger::logDebug(DPP_LOGGER_VERBOSE_2) << printEdges(G, GA, Edges);\n\n    return total_cost;\n}\n\n\n\n/**\n * Computes an adjacency matrix of Dubins path lengths between nodes with the\n * given headings (for ATSP).\n */\nvoid buildDubinsAdjacencyMatrix(ogdf::Graph &G, ogdf::GraphAttributes &GA, \n    NodeMatrix<double> &A, ogdf::NodeArray<double> &Headings, double turnRadius) {\n  \n    ogdf::node i, j;\n    forall_nodes(i, G) {\n        VehicleConfiguration Ci(GA.x(i), GA.y(i), Headings(i));\n\n        forall_nodes(j, G) {\n            if (i == j) {\n                A[i][i] = DPP_MAX_EDGE_COST;\n                continue;\n            }\n            VehicleConfiguration Cj(GA.x(j), GA.y(j), Headings(j));\n            \n            double w = dubinsPathLength(Ci, Cj, turnRadius);\n            A[i][j] = w;\n        }\n    }\n}\n\n} // namespace DPP\n\n", "meta": {"hexsha": "259c50d91080b6fd6c21baf3099aa9e47f4350f8", "size": 11966, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/dpp/basic/Path.cpp", "max_stars_repo_name": "dagoodma/dubins_coverage", "max_stars_repo_head_hexsha": "f05333b55fb2cb073bb572562726f8b711df54ad", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2017-09-28T00:56:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T16:02:56.000Z", "max_issues_repo_path": "src/dpp/basic/Path.cpp", "max_issues_repo_name": "dagoodma/dubins_coverage", "max_issues_repo_head_hexsha": "f05333b55fb2cb073bb572562726f8b711df54ad", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/dpp/basic/Path.cpp", "max_forks_repo_name": "dagoodma/dubins_coverage", "max_forks_repo_head_hexsha": "f05333b55fb2cb073bb572562726f8b711df54ad", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2016-12-16T03:32:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-31T06:54:03.000Z", "avg_line_length": 39.4917491749, "max_line_length": 125, "alphanum_fraction": 0.5828179843, "num_tokens": 3670, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257653, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.49851573950643224}}
{"text": "///////////////////////////////////////////////////////////////////////////////\r\n// weighted_variance.hpp\r\n//\r\n//  Copyright 2005 Daniel Egloff, Eric Niebler. Distributed under the Boost\r\n//  Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef BOOST_ACCUMULATORS_STATISTICS_WEIGHTED_VARIANCE_HPP_EAN_28_10_2005\r\n#define BOOST_ACCUMULATORS_STATISTICS_WEIGHTED_VARIANCE_HPP_EAN_28_10_2005\r\n\r\n#include <boost/mpl/placeholders.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/variance.hpp>\r\n#include <boost/accumulators/statistics/weighted_sum.hpp>\r\n#include <boost/accumulators/statistics/weighted_mean.hpp>\r\n#include <boost/accumulators/statistics/weighted_moment.hpp>\r\n\r\nnamespace boost { namespace accumulators\r\n{\r\n\r\nnamespace impl\r\n{\r\n    //! Lazy calculation of variance of weighted samples.\r\n    /*!\r\n        The default implementation of the variance of weighted samples is based on the second moment\r\n        \\f$\\widehat{m}_n^{(2)}\\f$ (weighted_moment<2>) and the mean\\f$ \\hat{\\mu}_n\\f$ (weighted_mean):\r\n        \\f[\r\n            \\hat{\\sigma}_n^2 = \\widehat{m}_n^{(2)}-\\hat{\\mu}_n^2,\r\n        \\f]\r\n        where \\f$n\\f$ is the number of samples.\r\n    */\r\n    template<typename Sample, typename Weight, typename MeanFeature>\r\n    struct lazy_weighted_variance_impl\r\n      : accumulator_base\r\n    {\r\n        typedef typename numeric::functional::multiplies<Sample, Weight>::result_type weighted_sample;\r\n        // for boost::result_of\r\n        typedef typename numeric::functional::average<weighted_sample, Weight>::result_type result_type;\r\n\r\n        lazy_weighted_variance_impl(dont_care) {}\r\n\r\n        template<typename Args>\r\n        result_type result(Args const &args) const\r\n        {\r\n            extractor<MeanFeature> const some_mean = {};\r\n            result_type tmp = some_mean(args);\r\n            return weighted_moment<2>(args) - tmp * tmp;\r\n        }\r\n    };\r\n\r\n    //! Iterative calculation of variance of weighted samples.\r\n    /*!\r\n        Iterative calculation of variance of weighted samples:\r\n        \\f[\r\n            \\hat{\\sigma}_n^2 =\r\n                \\frac{\\bar{w}_n - w_n}{\\bar{w}_n}\\hat{\\sigma}_{n - 1}^2\r\n              + \\frac{w_n}{\\bar{w}_n - w_n}\\left(X_n - \\hat{\\mu}_n\\right)^2\r\n            ,\\quad n\\ge2,\\quad\\hat{\\sigma}_0^2 = 0.\r\n        \\f]\r\n        where \\f$\\bar{w}_n\\f$ is the sum of the \\f$n\\f$ weights \\f$w_i\\f$ and \\f$\\hat{\\mu}_n\\f$\r\n        the estimate of the mean of the weighted smaples. Note that the sample variance is not defined for\r\n        \\f$n <= 1\\f$.\r\n    */\r\n    template<typename Sample, typename Weight, typename MeanFeature, typename Tag>\r\n    struct weighted_variance_impl\r\n      : accumulator_base\r\n    {\r\n        typedef typename numeric::functional::multiplies<Sample, Weight>::result_type weighted_sample;\r\n        // for boost::result_of\r\n        typedef typename numeric::functional::average<weighted_sample, Weight>::result_type result_type;\r\n\r\n        template<typename Args>\r\n        weighted_variance_impl(Args const &args)\r\n          : weighted_variance(numeric::average(args[sample | Sample()], numeric::one<Weight>::value))\r\n        {\r\n        }\r\n\r\n        template<typename Args>\r\n        void operator ()(Args const &args)\r\n        {\r\n            std::size_t cnt = count(args);\r\n\r\n            if(cnt > 1)\r\n            {\r\n                extractor<MeanFeature> const some_mean = {};\r\n\r\n                result_type tmp = args[parameter::keyword<Tag>::get()] - some_mean(args);\r\n\r\n                this->weighted_variance =\r\n                    numeric::average(this->weighted_variance * (sum_of_weights(args) - args[weight]), sum_of_weights(args))\r\n                  + numeric::average(tmp * tmp * args[weight], sum_of_weights(args) - args[weight] );\r\n            }\r\n        }\r\n\r\n        result_type result(dont_care) const\r\n        {\r\n            return this->weighted_variance;\r\n        }\r\n\r\n    private:\r\n        result_type weighted_variance;\r\n    };\r\n\r\n} // namespace impl\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// tag::weighted_variance\r\n// tag::immediate_weighted_variance\r\n//\r\nnamespace tag\r\n{\r\n    struct lazy_weighted_variance\r\n      : depends_on<weighted_moment<2>, weighted_mean>\r\n    {\r\n        /// INTERNAL ONLY\r\n        ///\r\n        typedef accumulators::impl::lazy_weighted_variance_impl<mpl::_1, mpl::_2, weighted_mean> impl;\r\n    };\r\n\r\n    struct weighted_variance\r\n      : depends_on<count, immediate_weighted_mean>\r\n    {\r\n        /// INTERNAL ONLY\r\n        ///\r\n        typedef accumulators::impl::weighted_variance_impl<mpl::_1, mpl::_2, immediate_weighted_mean, sample> impl;\r\n    };\r\n}\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// extract::weighted_variance\r\n// extract::immediate_weighted_variance\r\n//\r\nnamespace extract\r\n{\r\n    extractor<tag::lazy_weighted_variance> const lazy_weighted_variance = {};\r\n    extractor<tag::weighted_variance> const weighted_variance = {};\r\n}\r\n\r\nusing extract::lazy_weighted_variance;\r\nusing extract::weighted_variance;\r\n\r\n// weighted_variance(lazy) -> lazy_weighted_variance\r\ntemplate<>\r\nstruct as_feature<tag::weighted_variance(lazy)>\r\n{\r\n    typedef tag::lazy_weighted_variance type;\r\n};\r\n\r\n// weighted_variance(immediate) -> weighted_variance\r\ntemplate<>\r\nstruct as_feature<tag::weighted_variance(immediate)>\r\n{\r\n    typedef tag::weighted_variance type;\r\n};\r\n\r\n////////////////////////////////////////////////////////////////////////////\r\n//// droppable_accumulator<weighted_variance_impl>\r\n////  need to specialize droppable lazy weighted_variance to cache the result at the\r\n////  point the accumulator is dropped.\r\n///// INTERNAL ONLY\r\n/////\r\n//template<typename Sample, typename Weight, typename MeanFeature>\r\n//struct droppable_accumulator<impl::weighted_variance_impl<Sample, Weight, MeanFeature> >\r\n//  : droppable_accumulator_base<\r\n//        with_cached_result<impl::weighted_variance_impl<Sample, Weight, MeanFeature> >\r\n//    >\r\n//{\r\n//    template<typename Args>\r\n//    droppable_accumulator(Args const &args)\r\n//      : droppable_accumulator::base(args)\r\n//    {\r\n//    }\r\n//};\r\n\r\n}} // namespace boost::accumulators\r\n\r\n#endif\r\n", "meta": {"hexsha": "41b4fb286266c68ef91185bd0343b24dd9099c28", "size": 6634, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "windows/include/boost/accumulators/statistics/weighted_variance.hpp", "max_stars_repo_name": "jaredhoberock/gotham", "max_stars_repo_head_hexsha": "e3551cc355646530574d086d7cc2b82e41e8f798", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-12-29T07:21:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-29T10:47:38.000Z", "max_issues_repo_path": "windows/include/boost/accumulators/statistics/weighted_variance.hpp", "max_issues_repo_name": "jaredhoberock/gotham", "max_issues_repo_head_hexsha": "e3551cc355646530574d086d7cc2b82e41e8f798", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "windows/include/boost/accumulators/statistics/weighted_variance.hpp", "max_forks_repo_name": "jaredhoberock/gotham", "max_forks_repo_head_hexsha": "e3551cc355646530574d086d7cc2b82e41e8f798", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.0543478261, "max_line_length": 124, "alphanum_fraction": 0.6276756105, "num_tokens": 1461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.49851573387503045}}
{"text": "#ifndef QUADEIGS_H_\n#define QUADEIGS_H_\n\n#include <Eigen/Dense>\n#include <memory>\n\nclass QuadEigs {\npublic:\n  QuadEigs(const Eigen::Ref<const Eigen::MatrixXd> &matM,\n           const Eigen::Ref<const Eigen::MatrixXd> &matD,\n           const Eigen::Ref<const Eigen::MatrixXd> &matK);\n\n  Eigen::VectorXcd eigenvalues(int m);\n\nprivate:\n  const int ndim_;\n  Eigen::MatrixXd matM_, matD_, matK_;\n  Eigen::MatrixXd matA_, matB_;\n};\n\n#endif", "meta": {"hexsha": "315abbe05580daf371d7cab0b566f5641d26961e", "size": 433, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/quadeigs.hpp", "max_stars_repo_name": "pan3rock/QuadEigsSOAR", "max_stars_repo_head_hexsha": "6b4a2e939c8987773cd7990f665e9ebf57ecdbde", "max_stars_repo_licenses": ["MIT"], "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/quadeigs.hpp", "max_issues_repo_name": "pan3rock/QuadEigsSOAR", "max_issues_repo_head_hexsha": "6b4a2e939c8987773cd7990f665e9ebf57ecdbde", "max_issues_repo_licenses": ["MIT"], "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/quadeigs.hpp", "max_forks_repo_name": "pan3rock/QuadEigsSOAR", "max_forks_repo_head_hexsha": "6b4a2e939c8987773cd7990f665e9ebf57ecdbde", "max_forks_repo_licenses": ["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.619047619, "max_line_length": 58, "alphanum_fraction": 0.6951501155, "num_tokens": 122, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788903594354, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4985157226122263}}
{"text": "#include <Rcpp.h>\r\n#include <boost/multi_array.hpp>\r\n\r\nusing namespace Rcpp;\r\n\r\n// [[Rcpp::plugins(\"cpp11\")]]\r\n// [[Rcpp::depends(BH)]]\r\n\r\n//'Estep in girt.\r\n//'\r\n//'@param xall Item response matrix.\r\n//'@param t0 item parameter vector\r\n//'@param Xm node of theta dist.\r\n//'@param Wm weight of theta dist.\r\n//'@param group a vector.\r\n//'@param ind a design matrix for group.\r\n//'@param resp a design matrix for person.\r\n//'@param D factor constant.\r\n//'@param MLL a vector\r\n//'@export\r\n// [[Rcpp::export]]\r\n\r\nList Estep_irt(\r\n  IntegerMatrix xall,\r\n  NumericMatrix t0, // a, b, c\r\n  NumericVector Xm,\r\n  NumericMatrix Wm,\r\n  IntegerVector group,\r\n  IntegerMatrix ind, // design matrix\r\n  IntegerMatrix resp, // design matrix\r\n  double D,\r\n  NumericVector MLL\r\n){\r\n\r\n  int nj = xall.ncol();// item n\r\n  int ni = xall.nrow(); // subject n\r\n  int N  = Xm.length(); // node n\r\n  int ng = max(group); // group n\r\n\r\n  double a,b,c,t,tt,u,x;\r\n  int g,i,m,j;\r\n\r\n  boost::multi_array <double, 3> Lim (boost::extents[ng][ni][N]);\r\n  boost::multi_array <double, 3> Gim (boost::extents[ng][ni][N]);\r\n  boost::multi_array <double, 3> Njm (boost::extents[ng][nj][N]);\r\n  boost::multi_array <double, 3> rjm (boost::extents[ng][nj][N]);\r\n\r\n  for(g=0; g<ng; g++){\r\n    for(i=0; i<ni; i++){\r\n      if(group[i] != g+1) continue; // \u96c6\u56e3\u306b\u5c5e\u3055\u306a\u3044\u53d7\u9a13\u8005\u306e\u90e8\u5206\u306f\u30b9\u30ad\u30c3\u30d7\r\n      for(m=0; m<N; m++){\r\n        t = 1;\r\n        x = Xm[m];\r\n        tt = 0;\r\n        for(j=0; j<nj; j++){\r\n          //if(resp(i,j)==0) continue; // NA\u306e\u53cd\u5fdc\u30d1\u30bf\u30f3\u306e\u3068\u3053\u308d\u306f\u8a08\u7b97\u30eb\u30fc\u30d7\u304b\u3089\u5916\u308c\u308b\u3002\r\n          a = t0(j,0);\r\n          if(a == 0) continue;\r\n          b = t0(j,1);\r\n          c = t0(j,2);\r\n          u = xall(i,j);\r\n          if(u == 1){ // \u6b63\u7b54\u3057\u305f\u5834\u5408\u306e\u5c24\u5ea6\r\n            tt = c+(1.0-c)/(1.0+exp(-D*a*(x-b)));\r\n          } else if (u == 0) { // \u8aa4\u7b54\u3057\u305f\u5834\u5408\u306e\u5c24\u5ea6\r\n            tt = 1.0-(c+(1.0-c)/(1.0+exp(-D*a*(x-b))));\r\n          } else { // \u6b20\u6e2c\u5024\u306e\u5834\u5408\u306f\u5c24\u5ea6\u3092\u8a08\u7b97\u3057\u306a\u3044\u306e\u3067\uff0c1\r\n            tt = 1;\r\n          }\r\n          t = t * tt; // sum\r\n        }\r\n        Lim[g][i][m] = t;\r\n      }\r\n    }\r\n  }\r\n\r\n  // \u5404\u53d7\u691c\u8005\u306etheta\u3054\u3068\u306b\u4e8b\u5f8c\u5206\u5e03\u306e\u91cd\u307f\u3092\u8a08\u7b97\u3059\u308b\u3002\r\n  double uu;\r\n  double f = 0; // \u5468\u8fba\u5bfe\u6570\u5c24\u5ea6\u4ee3\u5165\u7528\r\n  double l,w;\r\n  for(int g=0; g<ng; g++){\r\n    for(int i=0; i<ni; i++){\r\n      if(group[i] != g+1) continue; // \u96c6\u56e3\u306b\u5c5e\u3055\u306a\u3044\u53d7\u9a13\u8005\u306e\u90e8\u5206\u306f\u30b9\u30ad\u30c3\u30d7\r\n      u = 0;\r\n      for(int m=0; m<N; m++){ // \u7dcf\u548c\u30921\u306b\u3059\u308b\u305f\u3081\u306e\u5206\u6bcd\u306e\u8a08\u7b97 // sum\r\n        l = Lim[g][i][m];\r\n        w = Wm(m,g);\r\n        uu = l*w;\r\n        u += uu;\r\n      }\r\n      f += log(u);\r\n      for(int m=0; m<N; m++){\r\n        l = Lim[g][i][m];\r\n        w = Wm(m,g);\r\n        Gim[g][i][m] =  l * w / u;\r\n      }\r\n\r\n    }\r\n  }\r\n  MLL.push_back(f);\r\n  if(traits::is_nan<REALSXP>(f)){\r\n    // \u5bfe\u6570\u5c24\u5ea6\u306e\u8a08\u7b97\u306b\u5931\u6557\u3057\u305f\u3089\uff0c\u8a08\u7b97\u3092\u4e2d\u6b62\u3059\u308b\u3002\r\n    stop(\"Can't calculate marginal log likelihood.\");\r\n  }\r\n\r\n  //Rcout<<\"expected frequency of subjects in each nodes calculation.\\n\";\r\n  double k,kk;\r\n  for(int g=0; g<ng; g++){\r\n    for(int j=0; j<nj; j++){ // \u5404\u5206\u70b9\u306e\u671f\u5f85\u5ea6\u6570\r\n      if(ind(g,j) == 0) continue;\r\n      for(int m=0; m<N; m++){\r\n        k = 0;\r\n        for(int i=0; i<ni; i++){ // \u6b20\u6e2c\u5024\u304c\u3042\u308b\u5834\u5408\uff0c\u9805\u76ee\u3054\u3068\u306b\u53d7\u691c\u8005\u6570\u304c\u7570\u306a\u308b\u3002\r\n          if(resp(i,j)==0) continue;\r\n          //double d = resp(i,j);\r\n          kk = Gim[g][i][m];\r\n          k += kk; //* d;\r\n        }\r\n        Njm[g][j][m]= k;\r\n      }\r\n    }\r\n  }\r\n\r\n  double h,gg,hh;\r\n  for(int g=0; g<ng; g++){\r\n    for(int j=0; j<nj; j++){ // \u5404\u5206\u70b9\u306e\u6b63\u7b54\u53d7\u691c\u8005\u306e\u671f\u5f85\u5ea6\u6570\r\n      if(ind(g,j) == 0) continue;\r\n      for(int m=0; m<N; m++){\r\n        h = 0;\r\n        for(int i=0; i<ni; i++){ // sum\r\n          //double d = resp(i,j);\r\n          if(resp(i,j) == 0) continue;\r\n          u = xall(i,j); // \u305d\u3082\u305d\u3082\u305d\u306e\u9805\u76ee\u306b\u56de\u7b54\u3057\u3066\u3044\u306a\u3044\u5834\u5408\u306f\uff0c\u5ea6\u6570\u306b\u6570\u3048\u4e0a\u3052\u306a\u3044\r\n          gg = Gim[g][i][m];\r\n          hh = u*gg;\r\n          h += hh;\r\n        }\r\n        rjm[g][j][m] = h;\r\n      }\r\n    }\r\n  }\r\n\r\n  return List::create(_[\"Njm\"]=Njm, _[\"rjm\"]=rjm, _[\"Lim\"]=Lim, _[\"Gim\"]=Gim, _[\"MLL\"]=MLL);\r\n\r\n}\r\n", "meta": {"hexsha": "72b1e93f61894129939a2dc1e1448106d9cfd2fb", "size": 3759, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Estep_irt.cpp", "max_stars_repo_name": "takuizum/irtfun2", "max_stars_repo_head_hexsha": "def9eac15a1150804f3702cf3f84df1c638a1c38", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Estep_irt.cpp", "max_issues_repo_name": "takuizum/irtfun2", "max_issues_repo_head_hexsha": "def9eac15a1150804f3702cf3f84df1c638a1c38", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Estep_irt.cpp", "max_forks_repo_name": "takuizum/irtfun2", "max_forks_repo_head_hexsha": "def9eac15a1150804f3702cf3f84df1c638a1c38", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.924137931, "max_line_length": 93, "alphanum_fraction": 0.467943602, "num_tokens": 1470, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.49850944111117207}}
{"text": "\n// Copyright Henrik Steffen Ga\u00dfmann 2020\n//\n// Distributed under the Boost Software License, Version 1.0.\n//         (See accompanying file LICENSE or copy at\n//           https://www.boost.org/LICENSE_1_0.txt)\n\n#pragma once\n\n#include <cstddef>\n\n#include <bit>\n#include <type_traits>\n\n#include <boost/endian/arithmetic.hpp>\n\n#include <dplx/cncr/math_supplement.hpp>\n#include <dplx/predef/compiler.h>\n\n#include <dplx/dp/detail/type_utils.hpp>\n#include <dplx/dp/detail/utils.hpp>\n\n#if defined DPLX_COMP_MSVC_AVAILABLE\n#include <intrin.h>\n#endif\n\nnamespace dplx::dp::detail\n{\n\ntemplate <typename T>\nconstexpr auto find_last_set_bit(T value) noexcept -> int\n{\n    static_assert(std::is_integral_v<T>);\n    static_assert(std::is_unsigned_v<T>);\n    static_assert(sizeof(T) <= sizeof(unsigned long long));\n\n    // #LangODR to be resolved after MSVC supports __cpp_lib_bitops\n#if __cpp_lib_bitops >= 201907L && __cpp_lib_is_constant_evaluated >= 201811L\n\n    if (std::is_constant_evaluated())\n    {\n        return (digits_v<T> - 1) - std::countl_zero(value);\n    }\n\n#endif\n\n#if defined(DPLX_COMP_GCC_AVAILABLE) || defined(DPLX_COMP_CLANG_AVAILABLE)\n\n    if constexpr (sizeof(T) <= sizeof(unsigned int))\n    {\n        return (digits_v<unsigned int> - 1)\n             ^ __builtin_clz(static_cast<unsigned int>(value));\n    }\n    else if constexpr (sizeof(T) <= sizeof(unsigned long))\n    {\n        return (digits_v<unsigned long> - 1)\n             ^ __builtin_clzl(static_cast<unsigned long>(value));\n    }\n    else /*if constexpr (sizeof(T) <= sizeof(unsigned long long))\n            see static_assert above */\n    {\n        return (digits_v<unsigned long long> - 1)\n             ^ __builtin_clzll(static_cast<unsigned long long>(value));\n    }\n\n#elif defined(DPLX_COMP_MSVC_AVAILABLE)\n\n    unsigned long result;\n    if constexpr (sizeof(T) <= sizeof(unsigned long))\n    {\n        _BitScanReverse(&result, static_cast<unsigned long>(value));\n        return static_cast<int>(result);\n    }\n    else if constexpr (sizeof(T) <= sizeof(unsigned long long))\n    {\n#if defined(_M_ARM64) || defined(_M_AMD64)\n\n        _BitScanReverse64(&result, static_cast<unsigned long long>(value));\n        return static_cast<int>(result);\n\n#else\n\n        static_assert(sizeof(unsigned long) * 2 == sizeof(unsigned long long));\n\n        if (_BitScanReverse(&result, static_cast<unsigned long>(\n                                             value >> digits_v<unsigned long>)))\n        {\n            return static_cast<int>(result + digits_v<unsigned long>);\n        }\n        else\n        {\n            _BitScanReverse(&result, static_cast<unsigned long>(value));\n            return static_cast<int>(result);\n        }\n#endif\n    }\n\n#else\n\n    return (digits_v<T> - 1) ^ std::countl_zero(value);\n\n#endif\n}\n\ntemplate <cncr::unsigned_integer T>\nconstexpr auto rotl(T const v, int n) noexcept -> T\n{\n    return (v << n) | (v >> (digits_v<T> - n));\n}\n\ntemplate <cncr::integer T, std::endian order>\nconstexpr auto load(std::byte const *const src) -> T\n{\n    // static_assert(order == std::endian::native);\n    static_assert(order == std::endian::big || order == std::endian::little);\n\n    if (std::is_constant_evaluated())\n    {\n        static_assert(sizeof(T) <= 8);\n        using uT = std::make_unsigned_t<T>;\n        if constexpr (order == std::endian::little)\n        {\n            uT acc = std::to_integer<uT>(src[0]);\n            if constexpr (sizeof(acc) >= 2)\n            {\n                acc |= std::to_integer<uT>(src[1]) << 8;\n            }\n            if constexpr (sizeof(acc) >= 4)\n            {\n                acc |= std::to_integer<uT>(src[2]) << 16\n                     | std::to_integer<uT>(src[3]) << 24;\n            }\n            if constexpr (sizeof(acc) == 8)\n            {\n                acc |= std::to_integer<uT>(src[4]) << 32\n                     | std::to_integer<uT>(src[5]) << 40\n                     | std::to_integer<uT>(src[6]) << 48\n                     | std::to_integer<uT>(src[7]) << 56;\n            }\n            return static_cast<T>(acc);\n        }\n        else\n        {\n            uT acc = std::to_integer<uT>(src[0]) << 56;\n            if constexpr (sizeof(acc) >= 2)\n            {\n                acc |= std::to_integer<uT>(src[1]) << 48;\n            }\n            if constexpr (sizeof(acc) >= 4)\n            {\n                acc |= std::to_integer<uT>(src[2]) << 40\n                     | std::to_integer<uT>(src[3]) << 32;\n            }\n            if constexpr (sizeof(acc) == 8)\n            {\n                acc |= std::to_integer<uT>(src[4]) << 24\n                     | std::to_integer<uT>(src[5]) << 16\n                     | std::to_integer<uT>(src[6]) << 8\n                     | std::to_integer<uT>(src[7]);\n            }\n            return static_cast<T>(acc >> (64 - digits_v<uT>));\n        }\n    }\n    else\n    {\n        constexpr auto boostOrder = order == std::endian::little\n                                          ? boost::endian::order::little\n                                          : boost::endian::order::big;\n        return boost::endian::endian_load<T, sizeof(T), boostOrder>(\n                reinterpret_cast<unsigned char const *>(src));\n        // T assembled;\n        // std::memcpy(&assembled, src, sizeof(assembled));\n        // return assembled;\n    }\n}\n\ntemplate <cncr::integer T, std::endian order>\nconstexpr auto load_partial(const std::byte *data, int num) -> T\n{\n    static_assert(sizeof(T) <= 8);\n    static_assert(order == std::endian::big || order == std::endian::little);\n\n    using uT = std::make_unsigned_t<T>;\n    if constexpr (order == std::endian::little)\n    {\n        uT assembled = 0;\n        switch (num)\n        {\n        case 7:\n            if constexpr (sizeof(assembled) == 8)\n            {\n                assembled |= std::to_integer<uT>(data[6]) << 48;\n            }\n            [[fallthrough]];\n        case 6:\n            if constexpr (sizeof(assembled) == 8)\n            {\n                assembled |= std::to_integer<uT>(data[5]) << 40;\n            }\n            [[fallthrough]];\n        case 5:\n            if constexpr (sizeof(assembled) == 8)\n            {\n                assembled |= std::to_integer<uT>(data[4]) << 32;\n            }\n            [[fallthrough]];\n\n        case 4:\n            if constexpr (sizeof(assembled) >= 4)\n            {\n                assembled |= std::to_integer<uT>(data[3]) << 24;\n            }\n            [[fallthrough]];\n        case 3:\n            if constexpr (sizeof(assembled) >= 4)\n            {\n                assembled |= std::to_integer<uT>(data[2]) << 16;\n            }\n            [[fallthrough]];\n\n        case 2:\n            if constexpr (sizeof(assembled) >= 2)\n            {\n                assembled |= std::to_integer<uT>(data[1]) << 8;\n            }\n            [[fallthrough]];\n\n        case 1:\n            assembled |= std::to_integer<uT>(data[0]);\n            [[fallthrough]];\n\n        case 0:\n            break;\n        }\n        return assembled;\n    }\n    else\n    {\n    }\n} // namespace dplx::dp::detail\n\nconstexpr auto byte_swap_u32(std::uint32_t const x) noexcept -> std::uint32_t\n{\n    if (std::is_constant_evaluated())\n    {\n        // byte_swap adapted from Boost.Endian\n        // Copyright 2019 Peter Dimov\n        //\n        // Distributed under the Boost Software License, Version 1.0.\n        // http://www.boost.org/LICENSE_1_0.txt\n        //\n        //  -- portable approach suggested by tymofey, with avoidance of\n        //     undefined behavior as suggested by Giovanni Piero Deretta,\n        //     with a further refinement suggested by Pyry Jahkola.\n\n        std::uint32_t const step16 = x << 16 | x >> 16;\n        return ((step16 << 8) & 0xff00ff00) | ((step16 >> 8) & 0x00ff00ff);\n    }\n    else\n    {\n        return boost::endian::endian_reverse(x);\n    }\n}\n\n} // namespace dplx::dp::detail\n", "meta": {"hexsha": "b1952fb1ede6e5425ef286d6b4d2196d767a517b", "size": 7852, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/dplx/dp/detail/bit.hpp", "max_stars_repo_name": "deeplex/deeppack", "max_stars_repo_head_hexsha": "0a94f61ee441eba7f0b280d2493505860c5b89cd", "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/dplx/dp/detail/bit.hpp", "max_issues_repo_name": "deeplex/deeppack", "max_issues_repo_head_hexsha": "0a94f61ee441eba7f0b280d2493505860c5b89cd", "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/dplx/dp/detail/bit.hpp", "max_forks_repo_name": "deeplex/deeppack", "max_forks_repo_head_hexsha": "0a94f61ee441eba7f0b280d2493505860c5b89cd", "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.5187969925, "max_line_length": 80, "alphanum_fraction": 0.5323484463, "num_tokens": 1963, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.49850943533582853}}
{"text": "#ifndef KMEANS_HPP_\n#define KMEANS_HPP_\n\n#include <iostream>\n#include <vector>\n// #include <Eigen/Eigen>\n#include <iostream>\n#include <string>\n#include <limits>\n#include <CGAL/Simple_cartesian.h>\n#include <CGAL/Point_set_3.h>\n#include <CGAL/IO/read_points.h>\n#include <CGAL/IO/io.h>\n#include <glog/logging.h>\n#include <limits>\n#include <CGAL/squared_distance_3.h>\n#include <CGAL/centroid.h>\n\n\nclass Kmeans\n{\n\ttypedef CGAL::Simple_cartesian<double> K;\n\ttypedef K::Point_3 Point_3;\n    typedef CGAL::Point_set_3<Point_3> Point_set;\n\npublic:\n\tKmeans();\n\t~Kmeans() {}\n\tKmeans(std::string file);\n\t/**\n\t * @brief Set the Input object\n\t * \n\t * @param source_path \n\t */\n\tbool setInput(std::string source);\n\n\tvoid setSimilarityModel(int flag);\n\t\n\t/**\n\t * @brief Set the Numberof Clusters and select init centers indices\n\t * \n\t * @param number_of_clusters the number of clusters\n\t */\n\tvoid setNumberofClusters(int number_of_clusters);\n\t/**\n\t * @brief Set the Init Cluster Center object\n\t * \n\t * @param init_centers the indices of init_centers point, if you should assign the init point,\n\t * \t\t\t\t\t   you should use this function\n\t */\n\tvoid setInitClusterCenter(const std::vector<Point_3> init_centers);\n\n\t/**\n\t * @brief Set the Max Iterations\n\t * \n\t * @param maxiter the max number of iteration\n\t */\n\tvoid setMaxIterations(int maxiter) {\n\t\tmaxiter_ = maxiter;\n\t};\n\n\t/**\n\t * @brief Set the Max Correspondence Distance \n\t * \n\t * @param maxcor \n\t */\n\tvoid setMaxCorrespondenceDistance(float maxcor) {\n\t\tmaxcor_ = maxcor;\n\t};\n\n\t/**\n\t * @brief execute kmean\n\t * \n\t * @return true \n\t * @return false \n\t */\n\tbool compute();\n\n\t/**\n\t * @brief get result\n\t * \n\t */\n\tbool save_clusters(std::string path, int minsize);\n\nprivate:\n\t/**\n\t * @brief input point cloud\n\t */\n\tPoint_set points_;\n\n\t/**\n\t * @brief the indices of point which is center\n\t * \n\t */\n\t// std::vector<int> centers_indices_;\n\tstd::vector<Point_3> centers_points_;\n\n\t/**\n\t * @brief indices of each clusters\n\t * \n\t */\n\tstd::vector<std::vector<int>> clusters_indices_;\n\n\t/**\n\t * @brief assign centers\n\t * \n\t */\n\tvoid assign_centers();\n\n\t/**\n\t * @brief compute threshold between centers and cluster center\n\t * \n\t * @return true meet the requirement\n\t * @return false \n\t */\n\tbool compute_threshold();\n\n\t/**\n\t * @brief some parameters\n\t * \n\t */\n\tint maxiter_;\n\tint finaliter_;\n\tfloat maxcor_;\n\tint number_of_clusters_;\n};\n\nKmeans::Kmeans()\n{\n\tLOG(INFO) << \"construct kmeans ...\";\n\tfinaliter_ = 0;\n\tmaxiter_ = 100;\n\tmaxcor_ = 10.0;\n\tnumber_of_clusters_ = 10;\n\tclusters_indices_.resize(number_of_clusters_);\n}\n\nKmeans::Kmeans(std::string file)\n{\n\tLOG(INFO) << \"construct kmeans ...\";\n\tsetInput(file);\n\n\tfinaliter_ = 0;\n\tmaxiter_ = 100;\n\tmaxcor_ = 1.0;\n\tnumber_of_clusters_ = 10;\n\tclusters_indices_.resize(number_of_clusters_);\n}\n\nbool Kmeans::setInput(std::string source)\n{\n\tLOG(INFO) << \"read data from file path\";\n\tCGAL::IO::read_XYZ(source, points_);\n\tif (points_.size() == 0) {\n\t\tLOG(INFO) << \"input data is zero\";\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nvoid Kmeans::setNumberofClusters(int number_of_clusters)\n{\n\tLOG(INFO) << \"set number of clusters\";\n\tnumber_of_clusters_ = number_of_clusters;\n    centers_points_.resize(number_of_clusters_);\n\n\tsrand((int)time(0));\n\t// selsect number_of_clusters different points\n\tfor (int i = 0; i < number_of_clusters_; i++) {\n\t\tcenters_points_[i] = points_.point(rand() % points_.size());\n\t}\n}\n\nvoid Kmeans::setInitClusterCenter(const std::vector<Point_3> init_centers)\n{\n\tnumber_of_clusters_ = init_centers.size();\n    centers_points_.resize(number_of_clusters_);\n\tfor (int i = 0; i < init_centers.size(); ++i)\n\t\tcenters_points_[i] = init_centers[i];\n}\n\nbool Kmeans::compute_threshold() {\n\t// get points from points_\n\tLOG(INFO) << \"computer center and updata centers\";\n\tbool isUpdate = false;\n\tfloat x = 0, y = 0, z = 0;\n\t// Point_set temp_points;\n\tstd::vector<Point_3> temp_points;\n\n\tfor (int i = 0; i < clusters_indices_.size(); i++)  {\n\t\tPoint_3 center = centers_points_[i];\n\t\tfor (int j = 0; j < clusters_indices_[i].size(); j++) {\n\t\t\tPoint_3 p = points_.point(j);\n\t\t\ttemp_points.push_back(p);\n\t\t}\n\t\tPoint_3 temp_centroid = CGAL::centroid(temp_points.begin(),\n\t\t\t\t\t\t\t\t\t\t\t   temp_points.end(),\n\t\t\t\t\t\t\t\t\t\t\t   CGAL::Dimension_tag<0>());\n\n\t\tfloat temp = CGAL::squared_distance(center, temp_centroid);\n\t\tif (temp > maxcor_) {\n\t\t\tcenters_points_[i] = Point_3(x, y, z);\n\t\t\tisUpdate = true;\n\t\t}\n\t}\n\tLOG(INFO) << \"compute_threshold && update center successful\";\n\treturn isUpdate;\n}\n\nvoid Kmeans::assign_centers() {\n\tLOG(INFO) << \"assign points to target centers\";\n\tfor (int i = 0; i < points_.size(); ++i) {\n\t\tfloat min_distance = std::numeric_limits<float>::max();\n\t\tint min_dis_clusters = -1;\n\t\tPoint_3 temp_p = points_.point(i);\n\t\tfor (int j = 0; j < number_of_clusters_; ++j) {\n\t\t\tfloat temp = CGAL::squared_distance(temp_p, centers_points_[j]);\n\t\t\tif (temp < min_distance) {\n\t\t\t\tmin_dis_clusters = j;\n\t\t\t\tmin_distance = temp;\n\t\t\t}\n\t\t}\n\t\tclusters_indices_[min_dis_clusters].push_back(i);\n\t}\n\tLOG(INFO) << \"assign_centers successful\";\n}\n\nbool Kmeans::compute() {\n\tLOG(INFO) << \"compute ... \";\n\tbool isUpdate = true;\n\tint iter = 0;\n\twhile (isUpdate) {\n\t\tassign_centers();\n\t\tisUpdate = compute_threshold();\n\t\titer ++;\n\t\tif (iter == maxiter_)\n\t\t\tbreak;\n\t}\n\tfinaliter_ = iter;\n    LOG(INFO) << \"compute successful \";\n\n\treturn true;\n}\n\n// @TODOS add\nbool Kmeans::save_clusters(std::string path, int minsize = std::numeric_limits<unsigned int>::min()) {\n    std::string output_file = \"\";\n    for (int i = 0; i < clusters_indices_.size(); ++i) {\n        output_file = path + \"/\" + std::to_string(i) + \".asc\";\n        LOG(INFO) << \"output_file = \" << output_file;\n        auto temp = clusters_indices_[i];\n        if (temp.size() > minsize) {\n            std::ofstream out(output_file);\n            for (int j = 0; j < temp.size(); j++)\n                out << points_.point(temp[j]).x() << \" \" \n\t\t\t\t\t<< points_.point(temp[j]).y() << \" \"\n\t\t\t\t\t<< points_.point(temp[j]).z() << std::endl;\n            out.close();\n        }        \n    }\n\n    return true;\n}\n\n\n#endif\n", "meta": {"hexsha": "180547e1fa593a6e7b60478cd43346fec4ac2dba", "size": 6030, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "kmeans.hpp", "max_stars_repo_name": "GreenAvocado92/Kmeans", "max_stars_repo_head_hexsha": "4a0f1f378f112c43c09614f1c38c1e3f53c14c2f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "kmeans.hpp", "max_issues_repo_name": "GreenAvocado92/Kmeans", "max_issues_repo_head_hexsha": "4a0f1f378f112c43c09614f1c38c1e3f53c14c2f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kmeans.hpp", "max_forks_repo_name": "GreenAvocado92/Kmeans", "max_forks_repo_head_hexsha": "4a0f1f378f112c43c09614f1c38c1e3f53c14c2f", "max_forks_repo_licenses": ["Apache-2.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.5842696629, "max_line_length": 102, "alphanum_fraction": 0.6538971808, "num_tokens": 1679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.49850943533582853}}
{"text": "#ifndef PYTHONIC_INCLUDE_NUMPY_EXPM1_HPP\n#define PYTHONIC_INCLUDE_NUMPY_EXPM1_HPP\n\n#include \"pythonic/include/utils/functor.hpp\"\n#include \"pythonic/include/types/ndarray.hpp\"\n#include \"pythonic/include/utils/numpy_traits.hpp\"\n\n#include <boost/simd/function/expm1.hpp>\n\nPYTHONIC_NS_BEGIN\n\nnamespace numpy\n{\n\n  namespace wrapper\n  {\n    template <class T>\n    std::complex<T> expm1(std::complex<T> const &val)\n    {\n      return exp(val) - 1;\n    }\n    template <class T>\n    auto expm1(T const &val) -> decltype(boost::simd::expm1(val))\n    {\n      return boost::simd::expm1(val);\n    }\n  }\n\n#define NUMPY_NARY_FUNC_NAME expm1\n#define NUMPY_NARY_FUNC_SYM wrapper::expm1\n#include \"pythonic/include/types/numpy_nary_expr.hpp\"\n}\nPYTHONIC_NS_END\n\n#endif\n", "meta": {"hexsha": "4fa853c8139cacaf4e34ec827f308ef06b586bdb", "size": 749, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pythran/pythonic/include/numpy/expm1.hpp", "max_stars_repo_name": "SylvainCorlay/pythran", "max_stars_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-03-24T00:33:03.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-24T00:33:03.000Z", "max_issues_repo_path": "pythran/pythonic/include/numpy/expm1.hpp", "max_issues_repo_name": "SylvainCorlay/pythran", "max_issues_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pythran/pythonic/include/numpy/expm1.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.8055555556, "max_line_length": 65, "alphanum_fraction": 0.7289719626, "num_tokens": 207, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478254, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4985094295604847}}
{"text": "#pragma once\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/poisson_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n\n// Provides a number of classes that encapsulate non-uniform probability\n// distributions (Normal, Poisson, etc).\nclass PoissonDistribution\n{\n  public:\n    PoissonDistribution(const int mean);\n\n    int next();\n\n  private:\n    boost::mt19937 mt;\n    boost::poisson_distribution<int> pdist;\n    boost::variate_generator<boost::mt19937, boost::poisson_distribution<int>> poisson_generator;\n};\n\n", "meta": {"hexsha": "7e2591090c898a2dfb8cc4841c0b10c35c18b336", "size": 545, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "engine/include/Random.hpp", "max_stars_repo_name": "sidav/shadow-of-the-wyrm", "max_stars_repo_head_hexsha": "747afdeebed885b1a4f7ab42f04f9f756afd3e52", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 60.0, "max_stars_repo_stars_event_min_datetime": "2019-08-21T04:08:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T13:48:04.000Z", "max_issues_repo_path": "engine/include/Random.hpp", "max_issues_repo_name": "cleancoindev/shadow-of-the-wyrm", "max_issues_repo_head_hexsha": "51b23e98285ecb8336324bfd41ebf00f67b30389", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-03-18T15:11:14.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-20T12:13:07.000Z", "max_forks_repo_path": "engine/include/Random.hpp", "max_forks_repo_name": "cleancoindev/shadow-of-the-wyrm", "max_forks_repo_head_hexsha": "51b23e98285ecb8336324bfd41ebf00f67b30389", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2019-11-16T06:29:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-23T17:33:43.000Z", "avg_line_length": 25.9523809524, "max_line_length": 97, "alphanum_fraction": 0.7633027523, "num_tokens": 124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8056321703143954, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.49850942378514085}}
{"text": "// Boost.Geometry\n// Unit Test\n\n// Copyright (c) 2016 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#include \"test_formula.hpp\"\n#include \"intersection_cases.hpp\"\n\n#include <boost/geometry/formulas/andoyer_inverse.hpp>\n#include <boost/geometry/formulas/gnomonic_intersection.hpp>\n#include <boost/geometry/formulas/sjoberg_intersection.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\nvoid check_inverse(expected_result const& result, expected_result const& expected, expected_result const& reference, double reference_error)\n{\n    check_one(result.lon, expected.lon, reference.lon, reference_error);\n    check_one(result.lat, expected.lat, reference.lat, reference_error);\n}\n\nvoid test_all(expected_results const& results)\n{\n    double const d2r = bg::math::d2r<double>();\n    double const r2d = bg::math::r2d<double>();\n\n    double lona1r = results.p1.lon * d2r;\n    double lata1r = results.p1.lat * d2r;\n    double lona2r = results.p2.lon * d2r;\n    double lata2r = results.p2.lat * d2r;\n    double lonb1r = results.q1.lon * d2r;\n    double latb1r = results.q1.lat * d2r;\n    double lonb2r = results.q2.lon * d2r;\n    double latb2r = results.q2.lat * d2r;\n\n    expected_result result;\n\n    // WGS84\n    bg::srs::spheroid<double> spheroid(6378137.0, 6356752.3142451793);\n\n    bg::formula::gnomonic_intersection<double, bg::formula::vincenty_inverse, bg::formula::vincenty_direct>\n        ::apply(lona1r, lata1r, lona2r, lata2r, lonb1r, latb1r, lonb2r, latb2r, result.lon, result.lat, spheroid);\n    result.lon *= r2d;\n    result.lat *= r2d;\n    check_inverse(result, results.gnomonic_vincenty, results.gnomonic_karney, 0.00000001);\n\n    bg::formula::gnomonic_intersection<double, bg::formula::thomas_inverse, bg::formula::thomas_direct>\n        ::apply(lona1r, lata1r, lona2r, lata2r, lonb1r, latb1r, lonb2r, latb2r, result.lon, result.lat, spheroid);\n    result.lon *= r2d;\n    result.lat *= r2d;\n    check_inverse(result, results.gnomonic_thomas, results.gnomonic_karney, 0.0000001);\n\n    bg::formula::sjoberg_intersection<double, bg::formula::vincenty_inverse, 4>\n        ::apply(lona1r, lata1r, lona2r, lata2r, lonb1r, latb1r, lonb2r, latb2r, result.lon, result.lat, spheroid);\n    result.lon *= r2d;\n    result.lat *= r2d;\n    check_inverse(result, results.sjoberg_vincenty, results.sjoberg_karney, 0.00000001);\n\n    bg::formula::sjoberg_intersection<double, bg::formula::thomas_inverse, 2>\n        ::apply(lona1r, lata1r, lona2r, lata2r, lonb1r, latb1r, lonb2r, latb2r, result.lon, result.lat, spheroid);\n    result.lon *= r2d;\n    result.lat *= r2d;\n    check_inverse(result, results.sjoberg_thomas, results.sjoberg_karney, 0.0000001);\n\n    bg::formula::sjoberg_intersection<double, bg::formula::andoyer_inverse, 1>\n        ::apply(lona1r, lata1r, lona2r, lata2r, lonb1r, latb1r, lonb2r, latb2r, result.lon, result.lat, spheroid);\n    result.lon *= r2d;\n    result.lat *= r2d;\n    check_inverse(result, results.sjoberg_andoyer, results.sjoberg_karney, 0.0001);\n}\n\nint test_main(int, char*[])\n{\n    for (size_t i = 0; i < expected_size; ++i)\n    {\n        test_all(expected[i]);\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "f0b1b49d7db8b5c6c6299f5fd2d5c92d7ef85158", "size": 3528, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/test/formulas/intersection.cpp", "max_stars_repo_name": "metux/boost", "max_stars_repo_head_hexsha": "e0157afdd519a2b14356cea62fcdac81829324cc", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-06-01T15:17:22.000Z", "max_stars_repo_stars_event_max_datetime": "2015-06-01T16:06:53.000Z", "max_issues_repo_path": "libs/geometry/test/formulas/intersection.cpp", "max_issues_repo_name": "metux/boost", "max_issues_repo_head_hexsha": "e0157afdd519a2b14356cea62fcdac81829324cc", "max_issues_repo_licenses": ["BSL-1.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": "libs/geometry/test/formulas/intersection.cpp", "max_forks_repo_name": "metux/boost", "max_forks_repo_head_hexsha": "e0157afdd519a2b14356cea62fcdac81829324cc", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-03-19T07:18:18.000Z", "max_forks_repo_forks_event_max_datetime": "2017-03-19T07:18:18.000Z", "avg_line_length": 40.0909090909, "max_line_length": 140, "alphanum_fraction": 0.7219387755, "num_tokens": 1117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4984785677583354}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2020 Mikhail Komarov <nemo@nil.foundation>\n//\n// Distributed under the Boost Software License, Version 1.0\n// See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt\n//---------------------------------------------------------------------------//\n\n#ifndef BOOST_MULTIPRECISION_MODULAR_BACKENDS_INVERSE_HPP\n#define BOOST_MULTIPRECISION_MODULAR_BACKENDS_INVERSE_HPP\n\n#include <boost/container/vector.hpp>\n#include <boost/type_traits/is_integral.hpp>\n\n#include <nil/crypto3/multiprecision/detail/default_ops.hpp>\n\n#include <nil/crypto3/multiprecision/cpp_int.hpp>\n#include <nil/crypto3/multiprecision/cpp_int/cpp_int_config.hpp>\n\nnamespace nil {\n    namespace crypto3 {\n        namespace multiprecision {\n            namespace backends {\n\n                template<typename Backend>\n                constexpr Backend eval_extended_euclidean_algorithm(Backend& a, Backend& b, Backend& x, Backend& y) {\n                    if (eval_is_zero(a)) {\n                        using ui_type = typename std::tuple_element<0, typename Backend::unsigned_types>::type;\n                        x = ui_type(0u);\n                        y = ui_type(1u);\n                        return b;\n                    }\n                    Backend x1, y1, tmp = b;\n                    eval_modulus(tmp, a);\n                    Backend d = eval_extended_euclidean_algorithm(tmp, a, x1, y1);\n                    tmp = b;\n                    eval_divide(tmp, a);\n                    eval_multiply(tmp, x1);\n                    x = y1;\n                    eval_subtract(x, tmp);\n                    y = x1;\n                    return d;\n                }\n\n                template<typename Backend>\n                constexpr Backend eval_inverse_extended_euclidean_algorithm(const Backend& a, const Backend& m) {\n                    using Backend_doubled = typename default_ops::double_precision_type<Backend>::type;\n\n                    Backend aa = a, mm = m, x, y, g;\n                    using ui_type = typename std::tuple_element<0, typename Backend::unsigned_types>::type;\n                    g = eval_extended_euclidean_algorithm(aa, mm, x, y);\n                    if (!eval_eq(g, ui_type(1u))) {\n                        // BOOST_THROW_EXCEPTION(std::invalid_argument(\"eval_inverse_with_gcd: no inverse element\"));\n                        return ui_type(0u);\n                    } else {\n                        eval_modulus(x, m);\n                        Backend_doubled tmp(x);\n                        eval_add(tmp, m);\n                        eval_modulus(tmp, m);\n                        return static_cast<Backend>(tmp);\n                    }\n                }\n\n                template<typename Backend>\n                constexpr typename std::tuple_element<0, typename Backend::signed_types>::type\n                    eval_monty_inverse(typename std::tuple_element<0, typename Backend::signed_types>::type a) {\n                    using si_type = typename std::tuple_element<0, typename Backend::signed_types>::type;\n\n                    if (a % 2 == 0) {\n                        throw std::invalid_argument(\"monty_inverse only valid for odd integers\");\n                    }\n\n                    /*\n                     * From \"A New Algorithm for Inversion mod p^k\" by \u00c7etin Kaya Ko\u00e7\n                     * https://eprint.iacr.org/2017/411.pdf sections 5 and 7.\n                     */\n\n                    si_type b = 1;\n                    si_type r = 0;\n\n                    for (size_t i = 0; i != sizeof(si_type) * CHAR_BIT; ++i) {\n                        const si_type bi = b % 2;\n                        r >>= 1;\n                        r += bi << (sizeof(si_type) * CHAR_BIT - 1);\n\n                        b -= a * bi;\n                        b >>= 1;\n                    }\n\n                    // Now invert in addition space\n                    r = (~static_cast<si_type>(0) - r) + 1;\n\n                    return r;\n                }\n\n                template<typename Backend>\n                constexpr void eval_monty_inverse(Backend& res, const Backend& a, const Backend& p, const Backend& k) {\n\n                    using default_ops::eval_abs;\n                    using default_ops::eval_gt;\n                    using default_ops::eval_modulus;\n                    using default_ops::eval_subtract;\n\n                    using ui_type = typename std::tuple_element<0, typename Backend::unsigned_types>::type;\n                    Backend zero = ui_type(0u);\n                    Backend one = ui_type(1u);\n                    Backend two = ui_type(2u);\n\n                    /*\n                     * From \"A New Algorithm for Inversion mod p^k\" by \u00c7etin Kaya Ko\u00e7\n                     * https://eprint.iacr.org/2017/411.pdf sections 5 and 7.\n                     */\n                    Backend c, tmp;\n\n                    // a^(-1) mod p:\n                    c = eval_inverse_extended_euclidean_algorithm(a, p);\n\n                    Backend bi = one, bt, i = zero, k_negone = k, xi, nextp = one;\n                    eval_subtract(k_negone, one);\n                    res = zero;\n\n                    // ui_type kn = cpp_int(k_negone);\n\n                    while (!eval_eq(i, k)) {\n                        // xi:\n                        xi = bi;\n                        eval_multiply(xi, c);\n                        eval_modulus(xi, p);\n\n                        if (eval_get_sign(xi) < 0) {\n                            tmp = xi;\n                            eval_abs(tmp, tmp);\n                            eval_modulus(tmp, p);\n                            xi = p;\n                            eval_subtract(xi, tmp);\n                        }\n\n                        // bi:\n                        tmp = a;\n                        eval_multiply(tmp, xi);\n                        eval_subtract(bi, tmp);\n                        eval_divide(bi, p);\n\n                        // res:\n                        tmp = xi;\n                        eval_multiply(tmp, nextp);\n                        eval_multiply(nextp, p);\n                        eval_add(res, tmp);\n                        eval_add(i, one);\n                    }\n                }\n\n                /*\n                                template <typename Backend>\n                                inline void bigint_shr1(typename boost::mpl::front<typename\n                   Backend::unsigned_types>::type x[], size_t x_size, size_t word_shift, size_t bit_shift)\n                                {\n                                   typedef typename boost::mpl::front<typename Backend::unsigned_types>::type ui_type;\n\n                                   const size_t top = x_size >= word_shift ? (x_size - word_shift) : 0;\n\n                                   if (top > 0)\n                                      copy_mem(x, x + word_shift, top);\n                                   clear_mem(x + top, std::min(word_shift, x_size));\n\n                                   const auto   carry_mask  = CT::Mask<ui_type>::expand(bit_shift);\n                                   const size_t carry_shift = carry_mask.if_set_return(BOTAN_MP_WORD_BITS - bit_shift);\n\n                                   ui_type carry = 0;\n\n                                   for (size_t i = 0; i != top; ++i)\n                                   {\n                                      const ui_type w = x[top - i - 1];\n                                      x[top - i - 1]  = (w >> bit_shift) | carry;\n                                      carry           = carry_mask.if_set_return(w << carry_shift);\n                                   }\n                                }\n\n                                template <typename Backend>\n                                inline typename boost::mpl::front<typename Backend::unsigned_types>::type\n                   bigint_add2_nc( typename boost::mpl::front<typename Backend::unsigned_types>::type x[], size_t\n                   x_size, const typename boost::mpl::front<typename Backend::unsigned_types>::type y[], size_t y_size)\n                                {\n                                   typedef typename boost::mpl::front<typename Backend::unsigned_types>::type ui_type;\n\n                                   ui_type carry = 0;\n\n                                   BOOST_ASSERT_MSG(x_size >= y_size, \"Expected sizes\");\n\n                                   const size_t blocks = y_size - (y_size % 8);\n\n                                   for (size_t i = 0; i != blocks; i += 8)\n                                      carry = word8_add2(x + i, y + i, carry);\n\n                                   for (size_t i = blocks; i != y_size; ++i)\n                                      x[i] = word_add(x[i], y[i], &carry);\n\n                                   for (size_t i = y_size; i != x_size; ++i)\n                                      x[i] = word_add(x[i], 0, &carry);\n\n                                   return carry;\n                                }\n\n                                template <typename Backend>\n                                inline typename boost::mpl::front<typename Backend::unsigned_types>::type\n                   bigint_cnd_sub( typename boost::mpl::front<typename Backend::unsigned_types>::type cnd, typename\n                   boost::mpl::front<typename Backend::unsigned_types>::type x[], size_t x_size, const typename\n                   boost::mpl::front<typename Backend::unsigned_types>::type y[], size_t y_size)\n                                {\n                                   BOOST_ASSERT_MSG(x_size >= y_size, \"Expected sizes\");\n\n                                   typedef typename boost::mpl::front<typename Backend::unsigned_types>::type ui_type;\n\n                                   const auto mask = CT::Mask<ui_type>::expand(cnd);\n\n                                   ui_type carry = 0;\n\n                                   const size_t blocks = y_size - (y_size % 8);\n                                   ui_type      z[8]   = {0};\n\n                                   for (size_t i = 0; i != blocks; i += 8)\n                                   {\n                                      carry = word8_sub3(z, x + i, y + i, carry);\n                                      mask.select_n(x + i, z, x + i, 8);\n                                   }\n\n                                   for (size_t i = blocks; i != y_size; ++i)\n                                   {\n                                      z[0] = word_sub(x[i], y[i], &carry);\n                                      x[i] = mask.select(z[0], x[i]);\n                                   }\n\n                                   for (size_t i = y_size; i != x_size; ++i)\n                                   {\n                                      z[0] = word_sub(x[i], 0, &carry);\n                                      x[i] = mask.select(z[0], x[i]);\n                                   }\n\n                                   return mask.if_set_return(carry);\n                                }\n\n                                template <typename Backend>\n                                inline typename boost::mpl::front<typename Backend::unsigned_types>::type\n                   bigint_cnd_add( typename boost::mpl::front<typename Backend::unsigned_types>::type       cnd,\n                                    typename boost::mpl::front<typename Backend::unsigned_types>::type       x[],\n                                    typename boost::mpl::front<typename Backend::unsigned_types>::type       x_size,\n                                    const typename boost::mpl::front<typename Backend::unsigned_types>::type y[], size_t\n                   y_size)\n                                {\n                                   BOTAN_ASSERT(x_size >= y_size, \"Expected sizes\");\n\n                                   typedef typename boost::mpl::front<typename Backend::unsigned_types>::type ui_type;\n\n                                   const auto mask = CT::Mask<ui_type>::expand(cnd);\n\n                                   ui_type carry = 0;\n\n                                   const size_t blocks = y_size - (y_size % 8);\n                                   ui_type      z[8]   = {0};\n\n                                   for (size_t i = 0; i != blocks; i += 8)\n                                   {\n                                      carry = word8_add3(z, x + i, y + i, carry);\n                                      mask.select_n(x + i, z, x + i, 8);\n                                   }\n\n                                   for (size_t i = blocks; i != y_size; ++i)\n                                   {\n                                      z[0] = word_add(x[i], y[i], &carry);\n                                      x[i] = mask.select(z[0], x[i]);\n                                   }\n\n                                   for (size_t i = y_size; i != x_size; ++i)\n                                   {\n                                      z[0] = word_add(x[i], 0, &carry);\n                                      x[i] = mask.select(z[0], x[i]);\n                                   }\n\n                                   return mask.if_set_return(carry);\n                                }\n\n                                template <typename Backend>\n                                inline void bigint_cnd_abs(typename boost::mpl::front<typename\n                   Backend::unsigned_types>::type cnd, typename boost::mpl::front<typename\n                   Backend::unsigned_types>::type x[], size_t size)\n                                {\n                                   typedef typename boost::mpl::front<typename Backend::unsigned_types>::type ui_type;\n                                   const auto                                                          mask =\n                                CT::Mask<ui_type>::expand(cnd);\n\n                                   ui_type carry = mask.if_set_return(1);\n                                   for (size_t i = 0; i != size; ++i)\n                                   {\n                                      const ui_type z = word_add(~x[i], 0, &carry);\n                                      x[i]            = mask.select(z, x[i]);\n                                   }\n                                }\n\n                                template <typename Backend>\n                                inline void bigint_cnd_swap(typename boost::mpl::front<typename\n                   Backend::unsigned_types>::type cnd, typename boost::mpl::front<typename\n                   Backend::unsigned_types>::type x[], typename boost::mpl::front<typename\n                   Backend::unsigned_types>::type y[], size_t size)\n                                {\n                                   typedef typename boost::mpl::front<typename Backend::unsigned_types>::type ui_type;\n                                   const auto                                                          mask =\n                                CT::Mask<ui_type>::expand(cnd);\n\n                                   for (size_t i = 0; i != size; ++i)\n                                   {\n                                      const ui_type a = x[i];\n                                      const ui_type b = y[i];\n                                      x[i]            = mask.select(b, a);\n                                      y[i]            = mask.select(a, b);\n                                   }\n                                }\n\n\n                                template <typename Backend>\n                                void eval_inverse_mod_odd_modulus(Backend& res, const Backend& n, const Backend& mod)\n                                {\n                                   typedef typename boost::mpl::front<typename Backend::signed_types>::type   si_type;\n                                   typedef typename boost::mpl::front<typename Backend::unsigned_types>::type ui_type;\n\n                                   // Caller should assure these preconditions:\n                                   BOOST_ASSERT(eval_gt(n, 0));\n                                   BOOST_ASSERT(eval_gt(mod, 0));\n                                   BOOST_ASSERT(eval_lt(n, mod));\n                                   BOOST_ASSERT(eval_ge(mod, 3) && eval_modulus(mod, 2) == 1);*/\n\n                /*\n                                This uses a modular inversion algorithm designed by Niels M\u00f6ller\n                                and implemented in Nettle. The same algorithm was later also\n                                adapted to GMP in mpn_sec_invert.\n                                It can be easily implemented in a way that does not depend on\n                                secret branches or memory lookups, providing resistance against\n                                some forms of side channel attack.\n                                There is also a description of the algorithm in Appendix 5 of \"Fast\n                                Software Polynomial Multiplication on ARM Processors using the NEON Engine\"\n                                by Danilo C\u00e2mara, Conrado P. L. Gouv\u00eaa, Julio L\u00f3pez, and Ricardo\n                                Dahab in LNCS 8182\n                                   https://conradoplg.cryptoland.net/files/2010/12/mocrysen13.pdf\n                                Thanks to Niels for creating the algorithm, explaining some things\n                                about it, and the reference to the paper.\n                                */\n                /*\n                                   const size_t mod_words = mod.size();\n                                   BOOST_ASSERT_MSG(mod_words > 0, \"Not empty\");\n\n                                   std::vector<ui_type> tmp_mem(5 * mod_words);\n\n                                   ui_type* v_w   = &tmp_mem[0];\n                                   ui_type* u_w   = &tmp_mem[1 * mod_words];\n                                   ui_type* b_w   = &tmp_mem[2 * mod_words];\n                                   ui_type* a_w   = &tmp_mem[3 * mod_words];\n                                   ui_type* mp1o2 = &tmp_mem[4 * mod_words];\n\n                                   //   ct::poison(tmp_mem.data(), tmp_mem.size());\n\n                                   copy_mem(a_w, n.data(), std::min(n.size(), mod_words));\n                                   copy_mem(b_w, mod.data(), std::min(mod.size(), mod_words));\n                                   u_w[0] = 1;\n                                   // v_w = 0\n\n                                   // compute (mod + 1) / 2 which [because mod is odd] is equal to\n                                   // (mod / 2) + 1\n                                   copy_mem(mp1o2, mod.data(), std::min(mod.size(), mod_words));\n                                   bigint_shr1(mp1o2, mod_words, 0, 1);\n                                   ui_type carry = bigint_add2_nc(mp1o2, mod_words, u_w, 1);\n                                   BOOST_ASSERT(carry == 0);\n\n                                   // Only n.bits() + mod.bits() iterations are required, but avoid leaking the size of\n                   n const size_t execs = 2 * eval_msb(mod);\n\n                                   for (size_t i = 0; i != execs; ++i)\n                                   {\n                                      const ui_type odd_a = a_w[0] & 1;\n\n                                      //if(odd_a) a -= b\n                                      ui_type underflow = bigint_cnd_sub(odd_a, a_w, b_w, mod_words);\n\n                                      //if(underflow) { b -= a; a = abs(a); swap(u, v); }\n                                      bigint_cnd_add(underflow, b_w, a_w, mod_words);\n                                      bigint_cnd_abs(underflow, a_w, mod_words);\n                                      bigint_cnd_swap(underflow, u_w, v_w, mod_words);\n\n                                      // a >>= 1\n                                      bigint_shr1(a_w, mod_words, 0, 1);\n\n                                      //if(odd_a) u -= v;\n                                      ui_type borrow = bigint_cnd_sub(odd_a, u_w, v_w, mod_words);\n\n                                      // if(borrow) u += p\n                                      bigint_cnd_add(borrow, u_w, mod.data(), mod_words);\n\n                                      const ui_type odd_u = u_w[0] & 1;\n\n                                      // u >>= 1\n                                      bigint_shr1(u_w, mod_words, 0, 1);\n\n                                      //if(odd_u) u += mp1o2;\n                                      bigint_cnd_add(odd_u, u_w, mp1o2, mod_words);\n                                   }\n\n                                   auto a_is_0 = CT::Mask<ui_type>::set();\n                                   for (size_t i = 0; i != mod_words; ++i)\n                                      a_is_0 &= CT::Mask<ui_type>::is_zero(a_w[i]);\n\n                                   auto b_is_1 = CT::Mask<ui_type>::is_equal(b_w[0], 1);\n                                   for (size_t i = 1; i != mod_words; ++i)\n                                      b_is_1 &= CT::Mask<ui_type>::is_zero(b_w[i]);\n\n                                   BOOST_ASSERT_MSG(a_is_0.is_set(), \"A is zero\");\n\n                                   // if b != 1 then gcd(n,mod) > 1 and inverse does not exist\n                                   // in which case zero out the result to indicate this\n                                   (~b_is_1).if_set_zero_out(v_w, mod_words);*/\n\n                /*\n                 * We've placed the result in the lowest words of the temp buffer.\n                 * So just clear out the other values and then give that buffer to a\n                 * BigInt.\n                 */\n                /*\n                                   clear_mem(&tmp_mem[mod_words], 4 * mod_words);\n\n                                   CT::unpoison(tmp_mem.data(), tmp_mem.size());\n\n                                   Backend r;\n                                   r.swap_reg(tmp_mem);\n                                   return r;\n                                }*/\n\n                /*\n                                template <typename Backend, expression_template_option ExpressionTemplates>\n                                void inverse_mod_odd_modulus(number<Backend, ExpressionTemplates>&       res,\n                                                             const number<Backend, ExpressionTemplates>& n,\n                                                             const number<Backend, ExpressionTemplates>& mod)\n                                {\n                                   eval_inverse_mod_odd_modulus(res.backend(), n.backend(), mod.backend());\n                                }\n                                 */\n\n                /*\n                                template <typename Backend>\n                                std::size_t eval_almost_montgomery_inverse(Backend& result, const Backend& a,\n                                                                           const Backend& p)\n                                {\n                                   size_t k = 0;\n\n                                   Backend u = p, v = a, r = 0, s = 1;\n\n                                   while (eval_gt(v, 0))\n                                   {\n                                      if (eval_integer_modulus(u, 2) == 0)\n                                      {\n                                         eval_right_shift(u, 1);\n                                         eval_left_shift(s, 1);\n                                      }\n                                      else if (eval_integer_modulus(v, 2) == 0)\n                                      {\n                                         eval_right_shift(v, 1);\n                                         eval_left_shift(r, 1);\n                                      }\n                                      else if (eval_gt(u, v))\n                                      {\n                                         eval_subtract(u, v);\n                                         eval_right_shift(u, 1);\n                                         eval_add(r, s);\n                                         eval_left_shift(s, 1);\n                                      }\n                                      else\n                                      {\n                                         eval_subtract(v, u);\n                                         eval_right_shift(v, 1);\n                                         eval_add(s, r);\n                                         eval_left_shift(r, 1);\n                                      }\n\n                                      k++;\n                                   }\n\n                                   if (!eval_gt(p, r))\n                                   {\n                                      eval_subtract(r, p);\n                                   }\n\n                                   result = p;\n\n                                   eval_subtract(result, r);\n\n                                   return k;\n                                }\n                                */\n\n                /*\n                                template <typename Backend, expression_template_option ExpressionTemplates>\n                                std::size_t almost_montgomery_inverse(number<Backend, ExpressionTemplates>& result,\n                                                                      const number<Backend, ExpressionTemplates>& a,\n                                                                      const number<Backend, ExpressionTemplates>& p)\n                                {\n                                   return eval_almost_montgomery_inverse(result.backend(), a.backend(), p.backend());\n                                }\n                                */\n\n                /*\n                                template <typename Backend>\n                                Backend eval_normalized_montgomery_inverse(const Backend& a, const Backend& p)\n                                {\n                                   Backend     r;\n                                   std::size_t k = eval_almost_montgomery_inverse(r, a, p);\n\n                                   for (std::size_t i = 0; i != k; ++i)\n                                   {\n                                      if (eval_integer_modulus(p, 2) == 1)\n                                      {\n                                         eval_add(r, p);\n                                      }\n                                      eval_right_shift(r, 1);\n                                   }\n\n                                   return r;\n                                }\n                                */\n\n                /*\n                                template <typename Backend, expression_template_option ExpressionTemplates>\n                                number<Backend, ExpressionTemplates> normalized_montgomery_inverse(\n                                    const number<Backend, ExpressionTemplates>& a,\n                                    const number<Backend, ExpressionTemplates>& p)\n                                {\n                                   return number<Backend, ExpressionTemplates>(\n                                       evaL_normalized_montgomery_inverse(a.backned(), p.backend()));\n                                }\n                                 */\n\n                /*\n                                template <typename Backend>\n                                Backend eval_inverse_mod_pow2(Backend& a1, size_t k)\n                                {\n                                   typedef typename boost::mpl::front<typename Backend::unsigned_types>::type ui_type;*/\n                /*\n                 * From \"A New Algorithm for Inversion mod p^k\" by \u00c7etin Kaya Ko\u00e7\n                 * https://eprint.iacr.org/2017/411.pdf sections 5 and 7.\n                 */\n                /*\n                                   if (eval_integer_modulus(a1, 2) == 0)\n                                      return 0;\n\n                                   Backend a = a1;\n                                   eval_bit_set(a, k);\n\n                                   Backend b = 1, X = 0, newb;\n\n                                   const std::size_t a_words = a.sig_words();\n\n                                   X.grow_to(round_up(k, sizeof(ui_type) * CHAR_BIT) / sizeof(ui_type) * CHAR_BIT);\n                                   b.grow_to(a_words);\n                                   */\n                /*\n                                Hide the exact value of k. k is anyway known to word length\n                                granularity because of the length of a, so no point in doing more\n                                than this.\n                                */\n                /*\n\n                                   const std::size_t iter = round_up(k, sizeof(ui_type) * CHAR_BIT);\n\n                                   for (std::size_t i = 0; i != iter; ++i)\n                                   {\n                                      const bool b0 = eval_bit_test(b, 0);\n                                      X.conditionally_set_bit(i, b0);\n                                      newb = b;\n                                      eval_subtract(newb, a);\n                                      b.ct_cond_assign(b0, newb);\n                                      eval_right_shift(b, 1);\n                                   }\n                                   eval_bit_set(X, k);\n                                   X.const_time_unpoison();\n                                   return X;\n                                }\n                                */\n\n                /*\n                                template <typename Backend, expression_template_option ExpressionTemplates>\n                                number<Backend, ExpressionTemplates> inverse_mod_pow2(\n                                    const number<Backend, ExpressionTemplates>& a1, size_t k)\n                                {\n                                   return number<Backend, ExpressionTemplates>(\n                                       eval_inverse_mod_pow2(a1.backend(), k.backend()));\n                                }\n                                */\n\n                /*\n                                template <typename Backend>\n                                Backend eval_inverse_mod(Backend& res, const Backend& n, const Backend& mod)\n                                {\n                                   if (eval_is_zero(mod))\n                                   {\n                                      BOOST_THROW_EXCEPTION(\n                                          std::invalid_argument(\"eval_inverse_mod: mod must be non zero\"));\n                                   }\n                                   if ((eval_get_sign(mod) < 0) || (eval_get_sign(n) < 0))\n                                   {\n                                      BOOST_THROW_EXCEPTION(\n                                          std::invalid_argument(\"eval_inverse_mod: arguments must be non-negative\"));\n                                   }\n                                   if (eval_is_zero(n) || (eval_integer_modulus(n, 2) == 0 && eval_integer_modulus(mod,\n                   2) == 0))\n                                   {\n                                      return 0;\n                                   }\n                                   if (eval_integer_modulus(n, 2) == 1)\n                                   {*/\n                /*\n                                Fastpath for common case. This leaks information if n > mod\n                                but we don't guarantee const time behavior in that case.\n                                */\n                /*\n                                      if (eval_gt(mod, n))\n                                         return eval_inverse_mod_odd_modulus(n, mod);\n                                      else\n                                         return eval_inverse_mod_odd_modulus(ct_modulo(n, mod), mod);\n                                   }\n\n                                   const std::size_t mod_lz = eval_lsb(mod);\n                                   BOOST_ASSERT(mod_lz > 0);\n                                   const std::size_t mod_bits = eval_msb(mod);\n                                   BOOST_ASSERT(mod_bits > mod_lz);\n\n                                   if (mod_lz == mod_bits - 1)\n                                   {\n                                      // In this case we are performing an inversion modulo 2^k\n                                      return eval_inverse_mod_pow2(n, mod_lz);\n                                   }*/\n\n                /*\n                 * In this case we are performing an inversion modulo 2^k*o for\n                 * some k > 1 and some odd (not necessarily prime) integer.\n                 * Compute the inversions modulo 2^k and modulo o, then combine them\n                 * using CRT, which is possible because 2^k and o are relatively prime.\n                 */\n                /*\n                                   Backend o = mod;\n\n                                   eval_right_shift(mod, mod_lz);\n\n                                   Backend n_redc = ct_modulo(n, o);\n                                   Backend inv_o  = eval_inverse_mod_odd_modulus(n_redc, o);\n                                   Backend inv_2k = eval_inverse_mod_pow2(n, mod_lz);\n\n                                   // No modular inverse in this case:\n                                   if (eval_is_zero(o) || eval_is_zero(inv_2k))\n                                      return 0;\n\n                                   Backend m2k = mod_lz;\n                                   eval_multiply(m2k, m2k);\n                                   // Compute the CRT parameter\n                                   Backend c = inverse_mod_pow2(o, mod_lz);\n\n                                   // Compute h = c*(inv_2k-inv_o) mod 2^k\n                                   Backend h = inv_2k;\n\n                                   eval_subtract(h, inv_o);\n                                   eval_multiply(h, c);\n\n                                   const bool h_neg = (eval_get_sign(h) < 0);\n\n                                   eval_abs(h); // h.set_sign(BigInt::Positive);\n                                   eval_bit_set(h, mod_lz);\n\n                                   const bool h_nonzero = !eval_is_zero(h);\n\n                                   eval_subtracr(m2k, h);\n                                   h.ct_cond_assign(h_nonzero && h_neg, m2k);\n\n                                   // Return result inv_o + h * o\n                                   eval_multiply(h, o);\n                                   eval_add(h, inv_o);\n\n                                   return h;\n                                }\n                                */\n            }    // namespace backends\n        }        // namespace multiprecision\n    }            // namespace crypto3\n}    // namespace nil\n\n#endif\n", "meta": {"hexsha": "7fd6918012764c416f82db47e0e413260ef343aa", "size": 35032, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/multiprecision/include/nil/crypto3/multiprecision/modular/inverse.hpp", "max_stars_repo_name": "Curryrasul/knapsack-snark", "max_stars_repo_head_hexsha": "633515a13906407338a81b9874d964869ddec624", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-14T18:09:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-14T18:09:38.000Z", "max_issues_repo_path": "libs/multiprecision/include/nil/crypto3/multiprecision/modular/inverse.hpp", "max_issues_repo_name": "Curryrasul/knapsack-snark", "max_issues_repo_head_hexsha": "633515a13906407338a81b9874d964869ddec624", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/multiprecision/include/nil/crypto3/multiprecision/modular/inverse.hpp", "max_forks_repo_name": "Curryrasul/knapsack-snark", "max_forks_repo_head_hexsha": "633515a13906407338a81b9874d964869ddec624", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-12T10:53:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-12T10:53:21.000Z", "avg_line_length": 50.7710144928, "max_line_length": 120, "alphanum_fraction": 0.3640956839, "num_tokens": 5820, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683105, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.49847856775833527}}
{"text": "/* Greg Anderson\n *\n * Wrapper classes for Apron abstractions.\n */\n\n#ifndef _ABSTRACT_H_\n#define _ABSTRACT_H_\n\n#include <ap_abstract0.h>\n#include <ap_disjunction.h>\n#include <t1p.h>\n#include <box.h>\n#include <pk.h>\n\n#include <cstdlib>\n#include <vector>\n#include <map>\n#include <memory>\n#include <iostream>\n#include <optional>\n#include <Eigen/Dense>\n\nclass ArithExpr {\n  private:\n    ap_texpr0_t* expr;\n\n  public:\n    ArithExpr();\n    ArithExpr(double constant);\n    ArithExpr(int ind);\n    ArithExpr(double lower, double upper);\n    ArithExpr(ap_texpr0_t* expr);\n    ArithExpr(const ArithExpr& other);\n    ArithExpr(ArithExpr&& other);\n    ArithExpr(const std::string& str);\n    ~ArithExpr();\n    ArithExpr& operator=(const ArithExpr& other);\n    ArithExpr& operator=(ArithExpr&& other);\n    ArithExpr negate() const;\n    ArithExpr operator+(const ArithExpr& other) const;\n    ArithExpr operator-(const ArithExpr& other) const;\n    ArithExpr operator*(const ArithExpr& other) const;\n    ArithExpr operator/(const ArithExpr& other) const;\n    // Be careful about the precedence of ^. C++ uses this operator for XOR so\n    // it has much lower precedence than you would expect for a power operator.\n    ArithExpr operator^(int power) const;\n\n    inline ap_texpr0_t* get_texpr() const {\n      return expr;\n    }\n};\n\n/**\n * A set of linear constraints. A point x satisfies these constraints if\n * `weights * x <= biases`.\n */\nclass LinCons {\n  public:\n    Eigen::MatrixXd weights;\n    Eigen::VectorXd biases;\n    LinCons();\n    LinCons(const Eigen::MatrixXd& ws, const Eigen::VectorXd& bs);\n    double distance_from(const Eigen::VectorXd& x) const;\n};\n\nenum class AbstractDomain { ZONOTOPE, INTERVAL, POLYHEDRA };\n\n/**\n * An abstract value over some underlying Apron value. This is just a\n * convenient wrapper class around Apron values.\n */\nclass AbstractVal {\n  protected:\n    ap_manager_t* man;\n    ap_abstract0_t* value;\n    virtual std::unique_ptr<AbstractVal> make_new(ap_abstract0_t* a) const;\n    AbstractDomain domain;\n\n  public:\n    AbstractVal();\n    AbstractVal(ap_manager_t* man, ap_abstract0_t* v);\n    // Construct a new abstract value in the given domain subject to the\n    // set of linear constraints a x <= b\n    AbstractVal(AbstractDomain dom, const std::vector<Eigen::VectorXd>& a,\n        const std::vector<double>& b);\n    AbstractVal(AbstractDomain dom, const LinCons& lc);\n\n    // Construct a new abstract value in the given domain from the given\n    // interval\n    AbstractVal(AbstractDomain dom, const Eigen::VectorXd& lowers,\n        const Eigen::VectorXd& uppers);\n    AbstractVal(const AbstractVal& other);\n    AbstractVal(AbstractVal&& other);\n    virtual ~AbstractVal();\n    AbstractVal& operator=(const AbstractVal& other) = delete;\n    AbstractVal& operator=(AbstractVal&& other) = delete;\n\n    inline ap_manager_t* get_manager() const {\n      return man;\n    }\n\n    inline ap_abstract0_t* get_value() const {\n      return value;\n    }\n\n    inline AbstractDomain get_domain() const {\n      return domain;\n    }\n\n    std::unique_ptr<AbstractVal> add_trailing_dimensions(int n) const;\n    std::unique_ptr<AbstractVal> add_leading_dimensions(int n) const;\n    std::unique_ptr<AbstractVal> remove_trailing_dimensions(int n) const;\n\n    /**\n     * Meet this value with the linear constraints a x <= b.\n     */\n    virtual std::unique_ptr<AbstractVal> meet_linear_constraint(\n        const Eigen::MatrixXd& a,\n        const Eigen::VectorXd& b) const;\n\n    /**\n     * Perform a specific affine transformation.\n     */\n    virtual std::unique_ptr<AbstractVal> scalar_affine(\n        const Eigen::MatrixXd& w,\n        const Eigen::VectorXd& b) const;\n\n    /**\n     * Perform an abstract transformation where each coefficient is an interval.\n     */\n    virtual std::unique_ptr<AbstractVal> interval_affine(\n        const Eigen::MatrixXd& wl,\n        const Eigen::MatrixXd& wu,\n        const Eigen::VectorXd& bl,\n        const Eigen::VectorXd& bu) const;\n\n    /**\n     * A relu is computed as follows: for each dimension i, compute\n     * x_l = meet(x, x_i < 0) and x_u = meet(x, x_i >= 0). Compute\n     * x'_l = x_l[x_i <- 0]. Let x = join(x'_l, x_u).\n     */\n    virtual std::unique_ptr<AbstractVal> relu() const;\n\n    virtual std::unique_ptr<AbstractVal> join(const AbstractVal& other) const;\n\n    virtual std::unique_ptr<AbstractVal> meet(const AbstractVal& other) const;\n\n    virtual std::unique_ptr<AbstractVal> widen(const AbstractVal& other) const;\n\n    virtual bool operator==(const AbstractVal& other) const;\n\n    /**\n     * Create an abstract value by adding each dimension of b to this and\n     * maintain the relations among variables in b.\n     */\n    virtual std::unique_ptr<AbstractVal> append(const AbstractVal& b) const;\n\n    virtual std::unique_ptr<AbstractVal> arith_computation(\n        const std::vector<ArithExpr>& exprs) const;\n\n    inline bool is_bottom() const {\n      return ap_abstract0_is_bottom(man, value);\n    }\n\n    inline bool is_top() const {\n      return ap_abstract0_is_top(man, value);\n    }\n\n    bool contains_point(const Eigen::VectorXd& x) const;\n    bool contains(const AbstractVal& x) const;\n    Eigen::VectorXd get_center() const;\n    virtual Eigen::VectorXd get_contained_point() const;\n\n    /**\n     * Get the number of dimensions of this abstract value.\n     */\n    inline size_t dims() const {\n      return ap_abstract0_dimension(man, value).realdim;\n    }\n\n    virtual std::unique_ptr<AbstractVal> clone() const;\n\n    virtual std::unique_ptr<AbstractVal> bottom() const;\n\n    LinCons get_lincons() const;\n\n    //virtual double distance_to_point(const Eigen::VectorXd& x) const;\n    void print(FILE* out) const;\n};\n\n/**\n * Powerset is used for a bounded powerset domain. It is based on Aprons\n * disjunctive domain, but applies a consolidation step after each join or\n * merge.\n */\nclass Powerset: public AbstractVal {\n  private:\n    size_t size;\n\n  protected:\n    std::unique_ptr<AbstractVal> make_new(ap_abstract0_t* a) const override;\n\n  public:\n    Powerset(ap_manager_t* m, ap_abstract0_t* v, size_t s);\n    Powerset(const Powerset& p);\n    Powerset(AbstractDomain dom, size_t size,\n        const std::vector<Eigen::VectorXd>& a,\n        const std::vector<double>& b);\n    Powerset(AbstractDomain dom, size_t size, const LinCons& lc);\n    Powerset(AbstractDomain dom, size_t size,\n        const Eigen::VectorXd& lowers,\n        const Eigen::VectorXd& uppers);\n    Powerset& operator=(const Powerset& other);\n    std::unique_ptr<AbstractVal> join(const AbstractVal& other) const override;\n    std::unique_ptr<AbstractVal> meet(const AbstractVal& other) const override;\n    std::unique_ptr<AbstractVal> arith_computation(\n        const std::vector<ArithExpr>& exprs) const override;\n    Eigen::VectorXd get_contained_point() const;\n    std::unique_ptr<AbstractVal> clone() const override;\n    std::unique_ptr<AbstractVal> bottom() const override;\n    //double distance_to_point(const Eigen::VectorXd& x) const;\n};\n\n//class Managers {\n//  private:\n//    ap_manager_t* t1p_man;\n//    ap_manager_t* box_man;\n//    std::map<ap_manager_t*, ap_manager_t*> disj_mans;\n//\n//  public:\n//    Managers(ap_manager_t*, ap_manager_t*);\n//    ~Managers();\n//    inline ap_manager_t* get_t1p_manager() const {\n//      return t1p_man;\n//    }\n//    inline ap_manager_t* get_box_manager() const {\n//      return box_man;\n//    }\n//    inline ap_manager_t* get_disj_manager(ap_manager_t* base) const {\n//      return disj_mans.at(base);\n//    }\n//};\n\n#endif\n", "meta": {"hexsha": "9e537a941e7343af29b6b671d375d2da27314d83", "size": 7511, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "abstract.hpp", "max_stars_repo_name": "gavlegoat/safe-learning", "max_stars_repo_head_hexsha": "614ad97834f1a96e6c9d7c8e6677277d9af4d816", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2020-10-27T14:52:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-01T16:33:03.000Z", "max_issues_repo_path": "abstract.hpp", "max_issues_repo_name": "gavlegoat/safe-learning", "max_issues_repo_head_hexsha": "614ad97834f1a96e6c9d7c8e6677277d9af4d816", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-11-13T19:09:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T02:23:23.000Z", "max_forks_repo_path": "abstract.hpp", "max_forks_repo_name": "gavlegoat/safe-learning", "max_forks_repo_head_hexsha": "614ad97834f1a96e6c9d7c8e6677277d9af4d816", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-03T13:52:10.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-08T01:36:17.000Z", "avg_line_length": 30.6571428571, "max_line_length": 80, "alphanum_fraction": 0.6860604447, "num_tokens": 1873, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872243177518, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.49845054848337517}}
{"text": "#include <gtest/gtest.h>\n\n#include \"mfem.hpp\"\nusing namespace mfem;\n\n#include <iostream>\n#include <Eigen/Core>\n\n#include \"../include/core/config.hpp\"\n#include \"../include/mymfem/utilities.hpp\"\n#include \"../include/uq/stats/pcells_hash_table.hpp\"\n\n\n//! Test creating a parallel cells hash table for a given mesh\n//! Unit Square Mesh, coarse\nTEST(ParCellsHashTable, test1)\n{\n    int nprocs, myrank;\n    MPI_Comm global_comm = MPI_COMM_WORLD;\n    MPI_Comm_size(global_comm, &nprocs);\n    MPI_Comm_rank(global_comm, &myrank);\n\n    int lx = 2;\n    const std::string mesh_file\n            = \"../input/poisson_smooth_unitSquare/mesh_lx\"\n            +std::to_string(lx);\n\n    int Nx = 4;\n    double xl = 0;\n    double xr = 1;\n\n    int Ny = 4;\n    double yl = 0;\n    double yr = 1;\n\n    //std::cout << mesh_file << std::endl;\n    std::shared_ptr<Mesh> mesh\n            = std::make_shared<Mesh>(mesh_file.c_str());\n\n    auto cellsHashTable\n            = make_hashTable(global_comm,\n                             mesh, Nx, xl, xr, Ny, yl, yr);\n    cellsHashTable->display();\n\n    int numElements = cellsHashTable->get_numElements();\n    int true_numElements = mesh->GetNE();\n    ASSERT_EQ(numElements, true_numElements);\n\n    Eigen::Vector2d coords;\n    coords(0) = 0.51;\n    coords(1) = 0.50;\n    int true_idx = 2;\n    int true_idy = 1;\n    int idx, idy;\n    std::tie(idx, idy) = cellsHashTable->search(coords);\n    if (myrank == 0) {\n        std::cout << \"Coords: \"\n                  << coords(0) << \",\" << coords(1)\n                  << \" are in cell \"\n                  << idx << \",\" << idy << std::endl;\n    }\n\n    ASSERT_EQ(idx, true_idx);\n    ASSERT_EQ(idy, true_idy);\n}\n\nTEST(ParCellsHashTable, test2)\n{\n    int nprocs, myrank;\n    MPI_Comm global_comm = MPI_COMM_WORLD;\n    MPI_Comm_size(global_comm, &nprocs);\n    MPI_Comm_rank(global_comm, &myrank);\n\n    const std::string mesh_file\n            = \"../meshes/channel_L1pt5/refined\"\n              \"/tri_mesh_l0.msh\";\n\n    int Nx = 10;\n    double xl = 0;\n    double xr = 1.5;\n\n    int Ny = 10;\n    double yl = 0;\n    double yr = 0.5;\n\n    //std::cout << mesh_file << std::endl;\n    std::shared_ptr<Mesh> mesh\n            = std::make_shared<Mesh>(mesh_file.c_str());\n\n    auto cellsHashTable\n            = make_hashTable(global_comm,\n                             mesh, Nx, xl, xr, Ny, yl, yr);\n\n    int numElements = cellsHashTable->get_numElements();\n    int true_numElements = mesh->GetNE();\n    ASSERT_EQ(numElements, true_numElements);\n}\n\n// End of file\n", "meta": {"hexsha": "3afab716a1be07708d4138d7cc4c12cbce0d9777", "size": 2503, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_phashTable.cpp", "max_stars_repo_name": "pratyuksh/NumHypSys", "max_stars_repo_head_hexsha": "29e03f9cc0572178701525210561b152d89999d4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/test_phashTable.cpp", "max_issues_repo_name": "pratyuksh/NumHypSys", "max_issues_repo_head_hexsha": "29e03f9cc0572178701525210561b152d89999d4", "max_issues_repo_licenses": ["MIT"], "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/test_phashTable.cpp", "max_forks_repo_name": "pratyuksh/NumHypSys", "max_forks_repo_head_hexsha": "29e03f9cc0572178701525210561b152d89999d4", "max_forks_repo_licenses": ["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.03, "max_line_length": 62, "alphanum_fraction": 0.5920894926, "num_tokens": 685, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.4984505447560699}}
{"text": "/**\n * @file\n * @brief NPDE homework CoupledSecondOrderBVP\n * @author Erick Schulz\n * @date 13/11/2019\n * @copyright Developed at ETH Zurich\n */\n\n#include <cmath>\n#include <iostream>\n#include <memory>\n#include <utility>\n\n#include <Eigen/Core>\n\n#include <lf/io/io.h>\n#include <lf/mesh/hybrid2d/hybrid2d.h>\n\n#include \"coupledsecondorderbvp.h\"\n\nusing namespace CoupledSecondOrderBVP;\n\nint main(int /*argc*/, const char ** /*argv*/) {\n  // Load mesh into a Lehrfem++ object\n  auto mesh_factory = std::make_unique<lf::mesh::hybrid2d::MeshFactory>(2);\n  const lf::io::GmshReader reader(std::move(mesh_factory),\n                                  CURRENT_SOURCE_DIR \"/../meshes/hex1.msh\");\n  auto mesh_p = reader.mesh();  // type shared_ptr< const lf::mesh::Mesh>\n\n  // Load finite element space\n  // We discretization by means of piecewise QUADRATIC lagrangian FE\n  auto fe_space = std::make_shared<FeSpaceLagrangeO2<double>>(mesh_p);\n  // Obtain local->global index mapping for current finite element space\n  const lf::assemble::DofHandler &dofh{fe_space->LocGlobMap()};\n  // Dimension of finite element space\n  const lf::uscalfe::size_type N_dofs(dofh.NumDofs());\n\n  /* Solve the coupled boundary value problem */\n  double gamma = 1.0;  // reaction coefficientS\n  // Right-hand side source function f\n  auto f = lf::mesh::utils::MeshFunctionGlobal(\n      [](Eigen::Vector2d x) -> double { return std::cos(x.norm()); });\n  Eigen::VectorXd sol_vec = solveCoupledBVP(fe_space, gamma, f);\n\n  /* Output results to vtk file */\n  // We store data by keeping only the coefficients of nodal basis functions\n  // In that sense, we are plotting the values of the solution at the vertices\n  lf::io::VtkWriter vtk_writer(\n      mesh_p, CURRENT_BINARY_DIR \"/CoupledSecondOrderBVP_solution.vtk\");\n  // Write nodal data taking the values of the discrete solution at the vertices\n  auto nodal_data = lf::mesh::utils::make_CodimMeshDataSet<double>(mesh_p, 2);\n  for (int global_idx = 0; global_idx < N_dofs; global_idx++) {\n    if (dofh.Entity(global_idx).RefEl() == lf::base::RefElType::kPoint) {\n      nodal_data->operator()(dofh.Entity(global_idx)) = sol_vec[global_idx];\n    }\n  };\n  vtk_writer.WritePointData(\"CoupledSecondOrderBVP_solution\", *nodal_data);\n  /* SAM_LISTING_END_1 */\n  std::cout << \"\\n The solution vector was written to:\" << std::endl;\n  std::cout << \">> CoupledSecondOrderBVP_solution.vtk\\n\" << std::endl;\n}\n", "meta": {"hexsha": "ad85ee82d380998e9bdaafa2ec9e0c82a79db257", "size": 2408, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/CoupledSecondOrderBVP/templates/coupledsecondorderbvp_main.cc", "max_stars_repo_name": "padomu/NPDECODES", "max_stars_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "homeworks/CoupledSecondOrderBVP/templates/coupledsecondorderbvp_main.cc", "max_issues_repo_name": "padomu/NPDECODES", "max_issues_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homeworks/CoupledSecondOrderBVP/templates/coupledsecondorderbvp_main.cc", "max_forks_repo_name": "padomu/NPDECODES", "max_forks_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_forks_repo_licenses": ["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.8387096774, "max_line_length": 80, "alphanum_fraction": 0.7034883721, "num_tokens": 663, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.7490872131147275, "lm_q1q2_score": 0.4984505410287645}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// Unit test\n\n// Copyright (c) 2015, Oracle and/or its affiliates.\n\n// Licensed under the Boost Software License version 1.0.\n// http://www.boost.org/users/license.html\n\n// Contributed and/or modified by Menelaos Karavelas, on behalf of Oracle\n\n#ifndef BOOST_TEST_MODULE\n#define BOOST_TEST_MODULE test_equals_on_spheroid\n#endif\n\n#include <iostream>\n\n#include <boost/test/included/unit_test.hpp>\n\n#include \"test_equals.hpp\"\n\n#include <boost/geometry/geometries/geometries.hpp>\n\n#include <boost/geometry/core/cs.hpp>\n\nnamespace bgm = bg::model;\n\ntemplate <typename P1, typename P2 = P1>\nstruct test_point_point\n{\n    static inline void apply(std::string const& header)\n    {\n        std::string const str = header + \"-\";\n\n        test_geometry<P1, P2>(str + \"pp_01\", \"POINT(0 0)\", \"POINT(0 0)\", true);\n        test_geometry<P1, P2>(str + \"pp_02\", \"POINT(0 0)\", \"POINT(10 0)\", false);\n\n        // points whose longitudes differ by 360 degrees\n        test_geometry<P1, P2>(str + \"pp_03\", \"POINT(0 0)\", \"POINT(360 0)\", true);\n        test_geometry<P1, P2>(str + \"pp_04\", \"POINT(10 0)\", \"POINT(370 0)\", true);\n        test_geometry<P1, P2>(str + \"pp_05\", \"POINT(10 0)\", \"POINT(-350 0)\", true);\n        test_geometry<P1, P2>(str + \"pp_06\", \"POINT(180 10)\", \"POINT(-180 10)\", true);\n        test_geometry<P1, P2>(str + \"pp_06a\", \"POINT(540 10)\", \"POINT(-540 10)\", true);\n\n#ifdef BOOST_GEOMETRY_NORMALIZE_LATITUDE\n        test_geometry<P1, P2>(str + \"pp_06b\", \"POINT(540 370)\", \"POINT(-540 -350)\", true);\n        test_geometry<P1, P2>(str + \"pp_06c\", \"POINT(1260 370)\", \"POINT(-1260 -350)\", true);\n        test_geometry<P1, P2>(str + \"pp_06d\", \"POINT(2340 370)\", \"POINT(-2340 -350)\", true);\n#endif\n\n        test_geometry<P1, P2>(str + \"pp_06e\", \"POINT(-180 10)\", \"POINT(-540 10)\", true);\n        test_geometry<P1, P2>(str + \"pp_06f\", \"POINT(180 10)\", \"POINT(-540 10)\", true);\n\n        // north & south pole\n        test_geometry<P1, P2>(str + \"pp_07\", \"POINT(0 90)\", \"POINT(0 90)\", true);\n\n#ifdef BOOST_GEOMETRY_NORMALIZE_LATITUDE\n        test_geometry<P1, P2>(str + \"pp_07a\", \"POINT(0 450)\", \"POINT(10 -270)\", true);\n        test_geometry<P1, P2>(str + \"pp_07b\", \"POINT(0 270)\", \"POINT(10 90)\", false);\n        test_geometry<P1, P2>(str + \"pp_07c\", \"POINT(0 -450)\", \"POINT(10 90)\", false);\n#endif\n\n        test_geometry<P1, P2>(str + \"pp_08\", \"POINT(0 90)\", \"POINT(10 90)\", true);\n        test_geometry<P1, P2>(str + \"pp_09\", \"POINT(0 90)\", \"POINT(0 -90)\", false);\n        test_geometry<P1, P2>(str + \"pp_10\", \"POINT(0 -90)\", \"POINT(0 -90)\", true);\n        test_geometry<P1, P2>(str + \"pp_11\", \"POINT(0 -90)\", \"POINT(10 -90)\", true);\n        test_geometry<P1, P2>(str + \"pp_11a\", \"POINT(0 -90)\", \"POINT(10 90)\", false);\n        test_geometry<P1, P2>(str + \"pp_12\", \"POINT(0 -90)\", \"POINT(0 -85)\", false);\n        test_geometry<P1, P2>(str + \"pp_13\", \"POINT(0 90)\", \"POINT(0 85)\", false);\n        test_geometry<P1, P2>(str + \"pp_14\", \"POINT(0 90)\", \"POINT(10 85)\", false);\n\n        // symmetric wrt prime meridian\n        test_geometry<P1, P2>(str + \"pp_15\", \"POINT(-10 45)\", \"POINT(10 45)\", false);\n        test_geometry<P1, P2>(str + \"pp_16\", \"POINT(-170 45)\", \"POINT(170 45)\", false);\n\n        // other points\n        test_geometry<P1, P2>(str + \"pp_17\", \"POINT(-10 45)\", \"POINT(10 -45)\", false);\n        test_geometry<P1, P2>(str + \"pp_18\", \"POINT(-10 -45)\", \"POINT(10 45)\", false);\n        test_geometry<P1, P2>(str + \"pp_19\", \"POINT(10 -135)\", \"POINT(10 45)\", false);\n\n#ifdef BOOST_GEOMETRY_NORMALIZE_LATITUDE\n        test_geometry<P1, P2>(str + \"pp_20\", \"POINT(190 135)\", \"POINT(10 45)\", true);\n        test_geometry<P1, P2>(str + \"pp_21\", \"POINT(190 150)\", \"POINT(10 30)\", true);\n        test_geometry<P1, P2>(str + \"pp_21a\", \"POINT(-170 150)\", \"POINT(10 30)\", true);\n        test_geometry<P1, P2>(str + \"pp_22\", \"POINT(190 -135)\", \"POINT(10 -45)\", true);\n        test_geometry<P1, P2>(str + \"pp_23\", \"POINT(190 -150)\", \"POINT(10 -30)\", true);\n        test_geometry<P1, P2>(str + \"pp_23a\", \"POINT(-170 -150)\", \"POINT(10 -30)\", true);\n#endif\n    }\n};\n\n\ntemplate <typename P1, typename P2 = P1>\nstruct test_point_point_with_height\n{\n    static inline void apply(std::string const& header)\n    {\n        std::string const str = header + \"-\";\n\n        test_geometry<P1, P2>(str + \"pp_01\",\n                              \"POINT(0 0 10)\",\n                              \"POINT(0 0 20)\",\n                              true);\n\n        test_geometry<P1, P2>(str + \"pp_02\",\n                              \"POINT(0 0 10)\",\n                              \"POINT(10 0 10)\",\n                              false);\n\n        // points whose longitudes differ by 360 degrees\n        test_geometry<P1, P2>(str + \"pp_03\",\n                              \"POINT(0 0 10)\",\n                              \"POINT(360 0 10)\",\n                              true);\n\n        // points whose longitudes differ by 360 degrees\n        test_geometry<P1, P2>(str + \"pp_04\",\n                              \"POINT(10 0 10)\",\n                              \"POINT(370 0 10)\",\n                              true);\n\n        test_geometry<P1, P2>(str + \"pp_05\",\n                              \"POINT(10 0 10)\",\n                              \"POINT(10 0 370)\",\n                              false);\n    }\n};\n\n\ntemplate <typename P>\nvoid test_segment_segment(std::string const& header)\n{\n    typedef bgm::segment<P> seg;\n\n    std::string const str = header + \"-\";\n\n    test_geometry<seg, seg>(str + \"ss_01\",\n                            \"SEGMENT(10 0,180 0)\",\n                            \"SEGMENT(10 0,-180 0)\",\n                            true);\n    test_geometry<seg, seg>(str + \"ss_02\",\n                            \"SEGMENT(0 90,180 0)\",\n                            \"SEGMENT(10 90,-180 0)\",\n                            true);\n    test_geometry<seg, seg>(str + \"ss_03\",\n                            \"SEGMENT(0 90,0 -90)\",\n                            \"SEGMENT(10 90,20 -90)\",\n                            true);\n    test_geometry<seg, seg>(str + \"ss_04\",\n                            \"SEGMENT(10 80,10 -80)\",\n                            \"SEGMENT(10 80,20 -80)\",\n                            false);\n    test_geometry<seg, seg>(str + \"ss_05\",\n                            \"SEGMENT(170 10,-170 10)\",\n                            \"SEGMENT(170 10,350 10)\",\n                            false);\n}\n\n\nBOOST_AUTO_TEST_CASE( equals_point_point_se )\n{\n    typedef bg::cs::spherical_equatorial<bg::degree> cs_type;\n\n    test_point_point<bgm::point<int, 2, cs_type> >::apply(\"se\");\n    test_point_point<bgm::point<double, 2, cs_type> >::apply(\"se\");\n    test_point_point<bgm::point<long double, 2, cs_type> >::apply(\"se\");\n\n    // mixed point types\n    test_point_point\n        <\n            bgm::point<double, 2, cs_type>, bgm::point<int, 2, cs_type>\n        >::apply(\"se\");\n\n    test_point_point\n        <\n            bgm::point<double, 2, cs_type>, bgm::point<long double, 2, cs_type>\n        >::apply(\"se\");\n}\n\nBOOST_AUTO_TEST_CASE( equals_point_point_with_height_se )\n{\n    typedef bg::cs::spherical_equatorial<bg::degree> cs_type;\n\n    test_point_point<bgm::point<int, 3, cs_type> >::apply(\"seh\");\n    test_point_point<bgm::point<double, 3, cs_type> >::apply(\"seh\");\n    test_point_point<bgm::point<long double, 3, cs_type> >::apply(\"seh\");\n\n    // mixed point types\n    test_point_point\n        <\n            bgm::point<double, 3, cs_type>, bgm::point<int, 3, cs_type>\n        >::apply(\"seh\");\n\n    test_point_point\n        <\n            bgm::point<double, 3, cs_type>, bgm::point<long double, 3, cs_type>\n        >::apply(\"seh\");\n}\n\nBOOST_AUTO_TEST_CASE( equals_point_point_geo )\n{\n    typedef bg::cs::geographic<bg::degree> cs_type;\n\n    test_point_point<bgm::point<int, 2, cs_type> >::apply(\"geo\");\n    test_point_point<bgm::point<double, 2, cs_type> >::apply(\"geo\");\n    test_point_point<bgm::point<long double, 2, cs_type> >::apply(\"geo\");\n\n    // mixed point types\n    test_point_point\n        <\n            bgm::point<double, 2, cs_type>, bgm::point<int, 2, cs_type>\n        >::apply(\"se\");\n\n    test_point_point\n        <\n            bgm::point<double, 2, cs_type>, bgm::point<long double, 2, cs_type>\n        >::apply(\"se\");\n}\n\nBOOST_AUTO_TEST_CASE( equals_segment_segment_se )\n{\n    typedef bg::cs::spherical_equatorial<bg::degree> cs_type;\n\n    test_segment_segment<bgm::point<int, 2, cs_type> >(\"se\");\n    test_segment_segment<bgm::point<double, 2, cs_type> >(\"se\");\n    test_segment_segment<bgm::point<long double, 2, cs_type> >(\"se\");\n}\n\nBOOST_AUTO_TEST_CASE( equals_segment_segment_geo )\n{\n    typedef bg::cs::geographic<bg::degree> cs_type;\n\n    test_segment_segment<bgm::point<int, 2, cs_type> >(\"geo\");\n    test_segment_segment<bgm::point<double, 2, cs_type> >(\"geo\");\n    test_segment_segment<bgm::point<long double, 2, cs_type> >(\"geo\");\n}\n", "meta": {"hexsha": "282cbebfe3bcd3a37730eac3409f0d18dedb229a", "size": 8851, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/algorithms/equals/equals_on_spheroid.cpp", "max_stars_repo_name": "jkerkela/geometry", "max_stars_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 326.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T13:47:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T02:13:59.000Z", "max_issues_repo_path": "test/algorithms/equals/equals_on_spheroid.cpp", "max_issues_repo_name": "jkerkela/geometry", "max_issues_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 623.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T23:45:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T11:15:23.000Z", "max_forks_repo_path": "test/algorithms/equals/equals_on_spheroid.cpp", "max_forks_repo_name": "jkerkela/geometry", "max_forks_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-01-14T15:50:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T03:58:36.000Z", "avg_line_length": 37.5042372881, "max_line_length": 92, "alphanum_fraction": 0.5550785222, "num_tokens": 2648, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.4984505360584438}}
{"text": "#ifdef STAN_OPENCL\n\n#include <stan/math/opencl/kernel_generator.hpp>\n#include <stan/math/opencl/matrix_cl.hpp>\n#include <stan/math/opencl/copy.hpp>\n#include <test/unit/math/opencl/kernel_generator/reference_kernel.hpp>\n#include <test/unit/util.hpp>\n#include <Eigen/Dense>\n#include <gtest/gtest.h>\n#include <string>\n\nTEST(KernelGenerator, indexing_test) {\n  using Eigen::MatrixXd;\n  using stan::math::matrix_cl;\n\n  std::string kernel_filename = \"indexing.cl\";\n  MatrixXd m = MatrixXd::Random(7, 9);\n\n  Eigen::MatrixXi col_idx(3, 2);\n  col_idx << 2, 5, 0, 1, 6, 3;\n  Eigen::MatrixXi row_idx(3, 2);\n  row_idx << 1, 2, 3, 4, 2, 0;\n\n  matrix_cl<double> m_cl(m);\n  matrix_cl<int> row_idx_cl(row_idx);\n  matrix_cl<int> col_idx_cl(col_idx);\n\n  auto tmp = stan::math::indexing(m_cl, row_idx_cl, col_idx_cl);\n\n  matrix_cl<double> res_cl;\n  std::string kernel_src = tmp.get_kernel_source_for_evaluating_into(res_cl);\n  stan::test::store_reference_kernel_if_needed(kernel_filename, kernel_src);\n  std::string expected_kernel_src\n      = stan::test::load_reference_kernel(kernel_filename);\n  EXPECT_EQ(expected_kernel_src, kernel_src);\n\n  res_cl = tmp;\n\n  MatrixXd res = stan::math::from_matrix_cl(res_cl);\n\n  MatrixXd correct(3, 2);\n  for (int i = 0; i < 3; i++) {\n    for (int j = 0; j < 2; j++) {\n      correct(i, j) = m(row_idx(i, j), col_idx(i, j));\n    }\n  }\n  EXPECT_MATRIX_EQ(res, correct);\n}\n\nTEST(KernelGenerator, indexing_multiple_operations_test) {\n  using Eigen::MatrixXd;\n  using Eigen::MatrixXi;\n  using stan::math::matrix_cl;\n\n  MatrixXd m = MatrixXd::Random(7, 9);\n\n  Eigen::MatrixXi col_idx(3, 2);\n  col_idx << 2, 5, 0, 1, 6, 3;\n  Eigen::MatrixXi row_idx(3, 2);\n  row_idx << 1, 2, 3, 4, 2, 0;\n\n  Eigen::MatrixXi col_idx2(2, 2);\n  col_idx2 << 0, 0, 1, 1;\n  Eigen::MatrixXi row_idx2(2, 2);\n  row_idx2 << 0, 1, 1, 2;\n\n  matrix_cl<double> m_cl(m);\n  matrix_cl<int> row_idx_cl(row_idx);\n  matrix_cl<int> col_idx_cl(col_idx);\n  matrix_cl<int> row_idx2_cl(row_idx2);\n  matrix_cl<int> col_idx2_cl(col_idx2);\n\n  matrix_cl<double> res_cl = stan::math::indexing(\n      stan::math::indexing(m_cl, row_idx_cl, col_idx_cl),\n      stan::math::indexing(row_idx2_cl, col_idx2_cl, col_idx2_cl), col_idx2_cl);\n\n  MatrixXd res = stan::math::from_matrix_cl(res_cl);\n\n  MatrixXd tmp(3, 2);\n  for (int i = 0; i < 3; i++) {\n    for (int j = 0; j < 2; j++) {\n      tmp(i, j) = m(row_idx(i, j), col_idx(i, j));\n    }\n  }\n\n  MatrixXd correct(2, 2);\n  for (int i = 0; i < 2; i++) {\n    for (int j = 0; j < 2; j++) {\n      int a = col_idx2(i, j);\n      correct(i, j) = tmp(row_idx2(a, a), a);\n    }\n  }\n  EXPECT_MATRIX_EQ(res, correct);\n}\n\nTEST(KernelGenerator, indexing_lhs_test) {\n  using Eigen::MatrixXd;\n  using Eigen::MatrixXi;\n  using stan::math::matrix_cl;\n\n  MatrixXd m = MatrixXd::Zero(7, 9);\n  MatrixXd m2 = MatrixXd::Random(3, 2);\n\n  Eigen::MatrixXi col_idx(3, 2);\n  col_idx << 2, 5, 0, 1, 6, 3;\n  Eigen::MatrixXi row_idx(3, 2);\n  row_idx << 1, 2, 3, 4, 2, 0;\n\n  matrix_cl<double> m_cl(m);\n  matrix_cl<double> m2_cl(m2);\n  matrix_cl<int> row_idx_cl(row_idx);\n  matrix_cl<int> col_idx_cl(col_idx);\n\n  stan::math::indexing(m_cl, row_idx_cl, col_idx_cl) = m2_cl;\n\n  MatrixXd res = stan::math::from_matrix_cl(m_cl);\n\n  MatrixXd correct = m;\n\n  for (int i = 0; i < 3; i++) {\n    for (int j = 0; j < 2; j++) {\n      correct(row_idx(i, j), col_idx(i, j)) = m2(i, j);\n    }\n  }\n  EXPECT_MATRIX_EQ(res, correct);\n}\n\nTEST(KernelGenerator, indexing_repeat_lhs_rhs_test) {\n  using Eigen::MatrixXd;\n  using Eigen::MatrixXi;\n  using stan::math::matrix_cl;\n\n  MatrixXd m = MatrixXd::Zero(7, 9);\n  MatrixXd correct = m;\n\n  Eigen::MatrixXi col_idx(3, 2);\n  col_idx << 2, 5, 0, 1, 6, 3;\n  Eigen::MatrixXi row_idx(3, 2);\n  row_idx << 1, 2, 3, 4, 2, 0;\n\n  matrix_cl<double> m_cl(m);\n  matrix_cl<int> row_idx_cl(row_idx);\n  matrix_cl<int> col_idx_cl(col_idx);\n\n  auto b = stan::math::indexing(m_cl, row_idx_cl, col_idx_cl);\n\n  b = b + 1;\n  MatrixXd res = stan::math::from_matrix_cl(m_cl);\n\n  for (int i = 0; i < 3; i++) {\n    for (int j = 0; j < 2; j++) {\n      correct(row_idx(i, j), col_idx(i, j)) += 1;\n    }\n  }\n  EXPECT_MATRIX_EQ(res, correct);\n}\n\n#endif\n", "meta": {"hexsha": "7474ed16866fd8cf3041901369bb3ce10dbdd892", "size": 4126, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/opencl/kernel_generator/indexing_test.cpp", "max_stars_repo_name": "yuzhangbit/math", "max_stars_repo_head_hexsha": "be482a212615b80319654108c9b1cf291de9a170", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-14T14:33:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-14T14:33:37.000Z", "max_issues_repo_path": "test/unit/math/opencl/kernel_generator/indexing_test.cpp", "max_issues_repo_name": "yuzhangbit/math", "max_issues_repo_head_hexsha": "be482a212615b80319654108c9b1cf291de9a170", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/unit/math/opencl/kernel_generator/indexing_test.cpp", "max_forks_repo_name": "yuzhangbit/math", "max_forks_repo_head_hexsha": "be482a212615b80319654108c9b1cf291de9a170", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-05-10T12:55:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-10T12:55:07.000Z", "avg_line_length": 25.9496855346, "max_line_length": 80, "alphanum_fraction": 0.6473582162, "num_tokens": 1437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.6654105454764746, "lm_q1q2_score": 0.498450531088123}}
{"text": "#include <scitbx/array_family/boost_python/flex_fwd.h>\n\n#include <scitbx/math/parabolic_cylinder_d.h>\n#include <scitbx/math/bessel.h>\n#include <scitbx/math/chebyshev.h>\n#include <scitbx/math/dihedral.h>\n#include <scitbx/math/erf.h>\n#include <scitbx/math/euler_angles.h>\n#include <scitbx/math/floating_point_epsilon.h>\n#include <scitbx/math/gamma.h>\n#include <scitbx/math/gcd.h>\n#include <scitbx/math/halton.h>\n#include <scitbx/math/lambertw.h>\n#include <scitbx/math/phase_error.h>\n#include <scitbx/math/resample.h>\n#include <scitbx/math/superpose.h>\n#include <scitbx/math/utils.h>\n#include <boost/rational.hpp> // for boost::gcd\n#include <scitbx/math/approx_equal.h>\n#include <scitbx/math/orthonormal_basis.h>\n#include <scitbx/math/gaussian_fit_1d_analytical.h>\n#include <scitbx/math/cubic_equation.h>\n#include <scitbx/math/distance_difference.h>\n#include <boost/python/module.hpp>\n#include <boost/python/def.hpp>\n#include <boost/python/class.hpp>\n#include <boost/python/args.hpp>\n#include <scitbx/math/fast_approx_math.h>\n#include <scitbx/math/g_function.h>\n\n\nnamespace scitbx { namespace math {\nnamespace boost_python {\n\n  void wrap_basic_statistics();\n  void wrap_gaussian();\n  void wrap_golay();\n  void wrap_minimum_covering_sphere();\n  void wrap_principal_axes_of_inertia();\n  void wrap_row_echelon();\n  void wrap_tensor_rank_2();\n  void wrap_icosahedron();\n  void wrap_chebyshev_base();\n  void wrap_chebyshev_polynome();\n  void wrap_chebyshev_fitter();\n  void wrap_chebyshev_lsq();\n  void wrap_slatec();\n  void wrap_line_search();\n  void wrap_r3_rotation();\n  void wrap_resample();\n  void wrap_quadrature();\n  void wrap_unimodular_generator();\n  void wrap_halton();\n  void wrap_least_squares_plane();\n  void wrap_continued_fraction();\n  void wrap_numeric_limits();\n  void wrap_distributions();\n  void wrap_exp_functions();\n  void wrap_zernike();\n  void wrap_zernike_mom();\n  void wrap_2d_zernike_mom();\n  void wrap_weighted_covariance();\n  void wrap_dmatrix();\n  void wrap_correlation();\n  void wrap_interpolation();\n  void wrap_tetrahedron();\n  void wrap_angle_derivative();\n\nnamespace {\n\n  int\n  time_gcd_int_boost(\n    int n)\n  {\n    int result = 0;\n    for(int a=0;a<n;a++) {\n      for(int b=0;b<n;b++) {\n        int c = boost::gcd(a, b);\n        if (result < c) result = c;\n      }\n    }\n    return result;\n  }\n\n  long\n  time_gcd_long_boost(\n    long n)\n  {\n    long result = 0;\n    for(long a=0;a<n;a++) {\n      for(long b=0;b<n;b++) {\n        long c = boost::gcd(a, b);\n        if (result < c) result = c;\n      }\n    }\n    return result;\n  }\n\n  int\n  time_gcd_int_simple(\n    int n)\n  {\n    int result = 0;\n    for(int a=0;a<n;a++) {\n      for(int b=0;b<n;b++) {\n        int c = gcd_int_simple(a, b);\n        if (result < c) result = c;\n      }\n    }\n    return result;\n  }\n\n  long\n  time_gcd_long_simple(\n    long n)\n  {\n    long result = 0;\n    for(long a=0;a<n;a++) {\n      for(long b=0;b<n;b++) {\n        long c = gcd_long_simple(a, b);\n        if (result < c) result = c;\n      }\n    }\n    return result;\n  }\n\n  long\n  time_gcd_unsigned_long_binary(\n    unsigned long n)\n  {\n    unsigned long result = 0;\n    for(unsigned long a=0;a<n;a++) {\n      for(unsigned long b=0;b<n;b++) {\n        unsigned long c = gcd_unsigned_long_binary(a, b);\n        if (result < c) result = c;\n      }\n    }\n    return result;\n  }\n\n  long\n  time_gcd_long_binary(\n    long n)\n  {\n    long result = 0;\n    for(long a=0;a<n;a++) {\n      for(long b=0;b<n;b++) {\n        long c = gcd_long_binary(a, b);\n        if (result < c) result = c;\n      }\n    }\n    return result;\n  }\n\n#if defined(SCITBX_MATH_GCD_USING_ASM)\n  int\n  time_gcd_int32_asm(\n    int n)\n  {\n    int result = 0;\n    for(int a=0;a<n;a++) {\n      for(int b=0;b<n;b++) {\n        int c = gcd_int32_asm(a, b);\n        if (result < c) result = c;\n      }\n    }\n    return result;\n  }\n\n# if defined(__x86_64__)\n  long\n  time_gcd_int64_asm(\n    long n)\n  {\n    long result = 0;\n    for(long a=0;a<n;a++) {\n      for(long b=0;b<n;b++) {\n        long c = gcd_int64_asm(a, b);\n        if (result < c) result = c;\n      }\n    }\n    return result;\n  }\n# endif\n#endif\n\n  template <typename SitesType>\n  boost::optional<double>\n  dihedral_angle(\n    SitesType const& sites,\n    bool deg)\n  {\n    return dihedral(sites).angle(deg);\n  }\n\n  mat3<double>\n  superpose_kearsley_rotation(\n    af::const_ref<vec3<double> > const& reference_sites,\n    af::const_ref<vec3<double> > const& other_sites)\n  {\n    return superpose::superposition<>::kearsley_rotation(\n      reference_sites, other_sites);\n  }\n\n  mat3< double >\n  euler_angles_xyz_matrix(\n      const double& ax,\n      const double& ay,\n      const double& az )\n  {\n    return euler_angles::xyz_matrix( ax, ay, az );\n  }\n\n  vec3< double >\n  euler_angles_xyz_angles(\n      const mat3< double >& m,\n      const double& eps = 1e-12 )\n  {\n    return euler_angles::xyz_angles( m, eps );\n  }\n\n  mat3< double >\n  euler_angles_yzx_matrix(\n      const double& ay,\n      const double& az,\n      const double& ax )\n  {\n    return euler_angles::yzx_matrix( ay, az, ax );\n  }\n\n  vec3< double >\n  euler_angles_yzx_angles(\n      const mat3< double >& m,\n      const double& eps = 1e-12 )\n  {\n    return euler_angles::yzx_angles( m, eps );\n  }\n\n  mat3< double >\n  euler_angles_zyz_matrix(\n      const double& az1,\n      const double& ay,\n      const double& az3 )\n  {\n    return euler_angles::zyz_matrix( az1, ay, az3 );\n  }\n\n  vec3< double >\n  euler_angles_zyz_angles(\n      const mat3< double >& m,\n      const double& eps = 1e-12 )\n  {\n    return euler_angles::zyz_angles( m, eps );\n  }\n\n  template <typename T>\n  struct approx_equal_relatively_wrapper\n  {\n    typedef math::approx_equal_relatively<T> wt;\n    typedef T arg_t;\n    typedef typename wt::amplitude_type amplitude_t;\n    static bool form_1(arg_t x, arg_t y, amplitude_t relative_error) {\n      wt p(relative_error);\n      return p(x, y);\n    }\n    static bool form_2(arg_t x, arg_t y, amplitude_t relative_error,\n                       amplitude_t near_zero_threshold)\n    {\n      wt p(relative_error, near_zero_threshold);\n      return p(x, y);\n    }\n\n    static void wrap() {\n      using namespace boost::python;\n      def(\"approx_equal_relatively\", form_1,\n          (arg(\"x\"), arg(\"y\"), arg(\"relative_error\")));\n      def(\"approx_equal_relatively\", form_2,\n          (arg(\"x\"), arg(\"y\"), arg(\"relative_error\"),\n           arg(\"near_zero_threshold\")));\n    }\n  };\n\n  void init_module()\n  {\n    using namespace boost::python;\n\n    def(\"time_gcd_int_boost\", time_gcd_int_boost);\n    def(\"time_gcd_long_boost\", time_gcd_long_boost);\n    def(\"gcd_int_simple\", gcd_int_simple, (arg(\"a\"), arg(\"b\")));\n    def(\"time_gcd_int_simple\", time_gcd_int_simple);\n    def(\"gcd_long_simple\", gcd_long_simple, (arg(\"a\"), arg(\"b\")));\n    def(\"time_gcd_long_simple\", time_gcd_long_simple);\n    def(\"time_gcd_unsigned_long_binary\", time_gcd_unsigned_long_binary);\n    def(\"gcd_long_binary\", gcd_long_binary, (arg(\"a\"), arg(\"b\")));\n    def(\"time_gcd_long_binary\", time_gcd_long_binary);\n#if defined(SCITBX_MATH_GCD_USING_ASM)\n    def(\"gcd_int32_asm\", gcd_int32_asm, (arg(\"a\"), arg(\"b\")));\n    def(\"time_gcd_int32_asm\", time_gcd_int32_asm);\n# if defined(__x86_64__)\n    def(\"gcd_int64_asm\", gcd_int64_asm, (arg(\"a\"), arg(\"b\")));\n    def(\"time_gcd_int64_asm\", time_gcd_int64_asm);\n# endif\n#endif\n\n    def(\"floating_point_epsilon_float_get\",\n      &floating_point_epsilon<float>::get);\n    def(\"floating_point_epsilon_double_get\",\n      &floating_point_epsilon<double>::get);\n\n    def(\"erf\", (double(*)(double const&)) erf);\n    def(\"erf\",\n      (scitbx::af::shared<double>(*)(\n        scitbx::af::const_ref<double> const&)) erf);\n    def(\"erfc\", (double(*)(double const&)) erfc);\n    def(\"erfcx\", (double(*)(double const&)) erfcx);\n\n    def(\"parabolic_cylinder_d\", (double(*)(double, double))\n      parabolic_cylinder_d::dv);\n\n    // G-function\n    def(\"GfuncOfRSsqr_approx\", (double(*)(double))\n      g_function::GfuncOfRSsqr_approx);\n\n    def(\"bessel_i1_over_i0\", (double(*)(double const&)) bessel::i1_over_i0);\n    def(\"bessel_i1_over_i0\",\n      (scitbx::af::shared<double>(*)(scitbx::af::const_ref<double> const&))\n        bessel::i1_over_i0);\n    def(\"bessel_inverse_i1_over_i0\",\n      (double(*)(double const&)) bessel::inverse_i1_over_i0);\n    def(\"inverse_bessel_i1_over_i0\", (scitbx::af::shared<double>(*)(\n         scitbx::af::const_ref<double> const&)) bessel::inverse_i1_over_i0);\n    def(\"bessel_i0\", (double(*)(double const&)) bessel::i0);\n    def(\"bessel_i1\", (double(*)(double const&)) bessel::i1);\n    def(\"bessel_ln_of_i0\", (double(*)(double const&)) bessel::ln_of_i0);\n    def(\"ei1\", (double(*)(double const&)) bessel::ei1);\n    def(\"ei0\", (double(*)(double const&)) bessel::ei0);\n\n    typedef return_value_policy<return_by_value> rbv;\n    namespace smg=scitbx::math::gaussian_fit_1d_analytical;\n    class_<smg::compute<> >(\"gaussian_fit_1d_analytical\")\n      .def(init<\n           af::const_ref<double> const&,\n           af::const_ref<double> const&,\n           af::const_ref<double> const& >(\n             (arg(\"x\"),\n              arg(\"y\"),\n              arg(\"z\"))))\n      .def(init<\n           af::const_ref<double> const&,\n           af::const_ref<double> const& >(\n             (arg(\"x\"),\n              arg(\"y\"))))\n      .add_property(\"a\", make_getter(&smg::compute<>::a, rbv()))\n      .add_property(\"b\", make_getter(&smg::compute<>::b, rbv()))\n    ;\n\n    //typedef return_value_policy<return_by_value> rbv;\n    namespace cueq=scitbx::math::cubic_equation;\n    class_<cueq::real<> >(\"cubic_equation_real\")\n      .def(init<\n           double const&,\n           double const&,\n           double const&,\n           double const& >(\n             (arg(\"a\"),\n              arg(\"b\"),\n              arg(\"c\"),\n              arg(\"d\"))))\n      .def(\"residual\", &cueq::real<>::residual)\n      .add_property(\"x\", make_getter(&cueq::real<>::x, rbv()))\n      .add_property(\"A\", make_getter(&cueq::real<>::A,  rbv()))\n      .add_property(\"B\", make_getter(&cueq::real<>::B,  rbv()))\n      .add_property(\"D\", make_getter(&cueq::real<>::D,  rbv()))\n    ;\n\n#if defined(SCITBX_MATH_BESSEL_HAS_SPHERICAL)\n    def(\"spherical_bessel\",\n      (double(*)(int const&, double const&))\n        bessel::spherical_bessel);\n    def(\"spherical_bessel_array\",\n      (scitbx::af::shared< double> (*)(\n        int const&, scitbx::af::shared<double> const&))\n          bessel::spherical_bessel_array);\n    def(\"bessel_J\",\n      (double(*)(int const&, double const&))\n        bessel::bessel_J);\n    def(\"bessel_J_array\",\n      (scitbx::af::shared< double> (*)(\n        int const&, scitbx::af::shared<double> const&))\n          bessel::bessel_J_array);\n    def (\"bessel_J_zeroes\",\n           (scitbx::af::shared< double> (*)(\n        double const&, int const&))\n        bessel::bessel_J_zeroes);\n    def (\"sph_bessel_j_zeroes\",\n           (scitbx::af::shared< double> (*)(\n        double const&, int const&))\n        bessel::sph_bessel_j_zeroes);\n\n\n#endif\n\n    def(\"gamma_complete\", (double(*)(double const&, bool))\n      gamma::complete, (\n        arg(\"x\"),\n        arg(\"minimax\")=true));\n    def(\"gamma_incomplete\", (double(*)(double const&,\n                                       double const&,\n                                       unsigned))\n      gamma::incomplete, (arg(\"a\"),\n        arg(\"x\"),\n        arg(\"max_iterations\")=500));\n    def(\"gamma_incomplete_complement\",(double(*)(double const&,\n                                                 double const&,\n                                                 unsigned))\n      gamma::incomplete_complement, (\n        arg(\"a\"),\n        arg(\"x\"),\n        arg(\"max_iterations\")=500));\n    def(\"exponential_integral_e1z\", (double(*)(double const&))\n         gamma::exponential_integral_e1z );\n\n    def(\"lambertw\", (double(*)(double const&, unsigned))\n      lambertw, (\n        arg(\"x\"),\n        arg(\"max_iterations\")=100));\n\n    wrap_basic_statistics();\n    wrap_gaussian();\n    wrap_golay();\n    wrap_minimum_covering_sphere();\n    wrap_principal_axes_of_inertia();\n    wrap_row_echelon();\n    wrap_tensor_rank_2();\n    wrap_icosahedron();\n    wrap_chebyshev_base();\n    wrap_chebyshev_polynome();\n    wrap_chebyshev_fitter();\n    wrap_chebyshev_lsq();\n    wrap_slatec();\n    wrap_line_search();\n    wrap_r3_rotation();\n    wrap_resample();\n    wrap_quadrature();\n    wrap_unimodular_generator();\n    wrap_halton();\n    wrap_least_squares_plane();\n    wrap_continued_fraction();\n    wrap_numeric_limits();\n    wrap_distributions();\n    wrap_exp_functions();\n    wrap_zernike();\n    wrap_zernike_mom();\n    wrap_2d_zernike_mom();\n    wrap_weighted_covariance();\n    wrap_dmatrix();\n    wrap_correlation();\n    wrap_interpolation();\n    wrap_tetrahedron();\n    wrap_angle_derivative();\n\n    def(\"superpose_kearsley_rotation\", superpose_kearsley_rotation, (\n      arg(\"reference_sites\"), arg(\"other_sites\")));\n\n    def(\"dihedral_angle\",\n      dihedral_angle<af::tiny<vec3<double>, 4> >, (\n        arg(\"sites\"), arg(\"deg\")=false));\n    def(\"dihedral_angle\",\n      dihedral_angle<af::const_ref<vec3<double> > >, (\n        arg(\"sites\"), arg(\"deg\")=false));\n\n    def( \"euler_angles_xyz_matrix\", euler_angles_xyz_matrix, (\n      arg(\"ax\"), arg(\"ay\"), arg(\"az\")));\n    def( \"euler_angles_xyz_angles\", euler_angles_xyz_angles, (\n      arg(\"m\"), arg(\"eps\")=1e-12));\n\n    def( \"euler_angles_yzx_matrix\", euler_angles_yzx_matrix, (\n      arg(\"ay\"), arg(\"az\"), arg(\"ax\")));\n    def( \"euler_angles_yzx_angles\", euler_angles_yzx_angles, (\n      arg(\"m\"), arg(\"eps\")=1e-12));\n\n    def( \"euler_angles_zyz_matrix\", euler_angles_zyz_matrix, (\n      arg(\"az1\"), arg(\"ay\"), arg(\"az3\")));\n    def( \"euler_angles_zyz_angles\", euler_angles_zyz_angles, (\n      arg(\"m\"), arg(\"eps\")=1e-12));\n\n    def(\"approx_sqrt\", math::approx_sqrt);\n\n    def(\"cos_table\",\n      (double(*)(\n         af::const_ref<double> const&,\n         double,\n         double const& ,\n         int const& ,\n         bool))\n           math::cos_table, (\n             arg(\"table\"), arg(\"arg\"), arg(\"step\"), arg(\"n\"),\n             arg(\"interpolate\")));\n\n    def(\"sin_table\",\n      (double(*)(\n         af::const_ref<double> const&,\n         double,\n         double const& ,\n         int const& ,\n         bool))\n           math::sin_table, (\n             arg(\"table\"), arg(\"arg\"), arg(\"step\"), arg(\"n\"),\n             arg(\"interpolate\")));\n\n    def(\"signed_phase_error\",\n      (double(*)(\n        double const&, double const&, bool))\n          math::signed_phase_error, (\n            arg(\"phi1\"), arg(\"phi2\"), arg(\"deg\")=false));\n    def(\"signed_phase_error\",\n      (af::shared<double>(*)(\n        af::const_ref<double> const&, af::const_ref<double> const&, bool))\n          math::signed_phase_error, (\n            arg(\"phi1\"), arg(\"phi2\"), arg(\"deg\")=false));\n    def(\"phase_error\",\n      (double(*)(\n        double const&, double const&, bool))\n          math::phase_error, (\n            arg(\"phi1\"), arg(\"phi2\"), arg(\"deg\")=false));\n    def(\"phase_error\",\n      (af::shared<double>(*)(\n        af::const_ref<double> const&, af::const_ref<double> const&, bool))\n          math::phase_error, (\n            arg(\"phi1\"), arg(\"phi2\"), arg(\"deg\")=false));\n    def(\"nearest_phase\",\n      (double(*)(\n        double const&, double const&, bool))\n          math::nearest_phase, (\n            arg(\"reference\"), arg(\"other\"), arg(\"deg\")=false));\n    def(\"nearest_phase\",\n      (af::shared<double>(*)(\n        af::const_ref<double> const&, af::const_ref<double> const&, bool))\n          math::nearest_phase, (\n            arg(\"reference\"), arg(\"other\"), arg(\"deg\")=false));\n    def(\"divmod\", math::divmod);\n    approx_equal_relatively_wrapper<double>::wrap();\n    approx_equal_relatively_wrapper<std::complex<double> >::wrap();\n    {\n      af::tiny<vec3<double>, 3> (*f1)(vec3<double> const &, vec3<double> const &,\n                                      bool) = &orthonormal_basis;\n      af::tiny<vec3<double>, 3> (*f2)(vec3<double> const &, int,\n                                      vec3<double> const &, int,\n                                      bool) = &orthonormal_basis;\n      def(\"orthonormal_basis\", f1, (arg(\"v0\"), arg(\"v1\"),\n                                    arg(\"right_handed\")=true));\n      def(\"orthonormal_basis\", f2, (arg(\"v0\"), arg(\"axis_index_1\"),\n                                    arg(\"v1\"), arg(\"axis_index_2\"),\n                                    arg(\"right_handed\")=true));\n    }\n    def(\"distance_difference_matrix\", distance_difference_matrix<double>, (\n      arg(\"sites1\"), arg(\"sites2\")));\n  }\n\n}}}} // namespace scitbx::math::boost_python::<anonymous>\n\nBOOST_PYTHON_MODULE(scitbx_math_ext)\n{\n  scitbx::math::boost_python::init_module();\n}\n", "meta": {"hexsha": "be2ee7bb1ef119df7682b6b25e106d6c4cccff57", "size": 16667, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "scitbx/math/boost_python/math_ext.cpp", "max_stars_repo_name": "rimmartin/cctbx_project", "max_stars_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 155.0, "max_stars_repo_stars_event_min_datetime": "2016-11-23T12:52:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:35:44.000Z", "max_issues_repo_path": "scitbx/math/boost_python/math_ext.cpp", "max_issues_repo_name": "rimmartin/cctbx_project", "max_issues_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": 590.0, "max_issues_repo_issues_event_min_datetime": "2016-12-10T11:31:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T23:10:09.000Z", "max_forks_repo_path": "scitbx/math/boost_python/math_ext.cpp", "max_forks_repo_name": "rimmartin/cctbx_project", "max_forks_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 115.0, "max_forks_repo_forks_event_min_datetime": "2016-11-15T08:17:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T15:30:14.000Z", "avg_line_length": 29.4469964664, "max_line_length": 81, "alphanum_fraction": 0.5971080578, "num_tokens": 4642, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152325073083131, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4984184590116949}}
{"text": "#include <Eigen/Dense>\n#include <boost/mpl/at.hpp>\n#include <boost/program_options.hpp>\n#include <chrono>\n#include <cmath>\n#include <cstdio>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <limits>\n#include \"bte_config.h\"\n#include \"aux/rdtsc_timer.hpp\"\n#include \"collision_tensor/collision_tensor_galerkin.hpp\"\n#include \"collision_tensor/dense/collision_tensor_zlastAM_eigen.hpp\"\n#include \"collision_tensor/dense/multi_slices_factory.hpp\"\n#include \"collision_tensor/dense/storage/vbcrs_sparsity.hpp\"\n#include \"collision_tensor/dense/cluster_vbcrs_sparsity.hpp\"\n#include \"aux/filtered_range.hpp\"\n#include \"spectral/basis/spectral_basis_factory_ks.hpp\"\n\nnamespace po = boost::program_options;\n\n#include <yaml-cpp/yaml.h>\n\nusing namespace std;\nusing namespace boltzmann;\n\ntypedef ct_dense::CollisionTensorZLastAMEigen ct_dense_t;\ntypedef SpectralBasisFactoryKS basis_factory_t;\ntypedef SpectralBasisFactoryKS::basis_type basis_type;\n\n\nint\nmain(int argc, char* argv[])\n{\n  std::string version_id = GIT_SHA1;\n  cout << \"VersionID: \" << version_id << \"@\" << GIT_BNAME << std::endl;\n\n  int K;\n  int min_blk_size;\n  if (argc < 3) {\n    cerr << \"usage: \" << argv[0] << \" K blksize\"\n         << \"\\nK: polynomial degree\"\n         << \"\\nblksize: minimum admissible block size\"\n         << \"\\n\";\n    return 1;\n  } else {\n    K = atoi(argv[1]);\n    min_blk_size = atoi(argv[2]);\n    cerr << \"K: \" << K << \"\\n\";\n  }\n\n  // create basis\n  basis_type basis;\n  SpectralBasisFactoryKS::create(basis, K);\n  unsigned int N = basis.n_dofs();\n\n  ct_dense::multi_slices_factory::container_t multi_slices;\n  ct_dense::multi_slices_factory::create(multi_slices, basis);\n\n  std::vector<ct_dense::VBCRSSparsity<>> vbcrs_sparsity_patterns(2 * K - 1);\n  int i = 0;\n  cout << setw(10) << \"slice id\" << setw(15) << \"msize\" << setw(15) << \"dimz\"\n       << \"\\n\";\n  for (auto& mslice : multi_slices) {\n    auto& vbcrs = vbcrs_sparsity_patterns[i++];\n    vbcrs.init(mslice.second.data(), K);\n    unsigned int msize = vbcrs.memsize();\n    cout << setw(10) << i << setw(15) << msize << setw(15) << vbcrs.dimz() << \"\\n\";\n  }\n  cout << \"----------------------------------------------------------------------\"\n       << \"\\n\";\n\n  typedef SpectralBasisFactoryKS::elem_t elem_t;\n  typedef typename boost::mpl::at_c<typename elem_t::types_t, 0>::type fa_type;\n  typename elem_t::Acc::template get<fa_type> fa_accessor;\n  // find elements to cluster (combine)\n struct block_t\n  {\n    int l;\n    enum TRIG t;\n    int index_first;\n    int index_last;\n  };\n auto cmp = [&fa_accessor](const elem_t& e, int l, enum TRIG t) {\n   auto id = fa_accessor(e).get_id();\n   return (id.l == l && TRIG(id.t) == t);\n };\n\n  std::vector<block_t> blocks;\n  int offset = 0;\n  for (int l = 0; l < K; ++l) {\n    for (auto t : {TRIG::COS, TRIG::SIN}) {\n      auto range_z =\n          filtered_range(basis.begin(), basis.end(), std::bind(cmp, std::placeholders::_1, l, t));\n      std::vector<elem_t> elemsz(std::get<0>(range_z), std::get<1>(range_z));\n      if (elemsz.size() == 0) continue;\n      int size = elemsz.size();\n      block_t block = {l, t, offset, offset + size};\n      blocks.push_back(block);\n      offset += size;\n    }\n  }\n\n\n  struct super_block_t\n  {\n    int extent = 0;\n    int index_first = std::numeric_limits<int>::max();\n    int index_last = -1;\n    std::vector<block_t> elems;\n    void insert(const block_t& block)\n    {\n      elems.push_back(block);\n      extent += block.index_last - block.index_first;\n      index_first = std::min(block.index_first, index_first);\n      index_last = std::max(block.index_last, index_last);\n    }\n  };\n\n  std::vector<super_block_t> super_blocks;\n\n  while (!blocks.empty()) {\n    auto elem = blocks.back();\n    int extent = elem.index_last - elem.index_first;\n    auto& last_super_block = super_blocks.back();\n    if (!super_blocks.empty() && last_super_block.extent < min_blk_size) {\n      last_super_block.insert(elem);\n    } else {\n      super_block_t sblock;\n      sblock.insert(elem);\n      super_blocks.push_back(sblock);\n    }\n    // remove last elem\n    blocks.pop_back();\n  }\n\n  std::sort(super_blocks.begin(),\n            super_blocks.end(),\n            [](const super_block_t& a, const super_block_t& b) {\n              return a.index_first < b.index_first;\n            });\n  cout << \"found \" << super_blocks.size() << \" super blocks\"\n       << \"\\n\";\n\n  for (auto sblock : super_blocks) {\n    cout << \"sblock.extent: \" << sblock.extent << \" count: \" << sblock.elems.size() << \", \"\n         << sblock.index_first << \" -> \" << sblock.index_last << \"\\n\";\n  }\n\n  ct_dense::MultiSlice::key_t k(4, TRIG::COS);\n  ct_dense::VBCRSSparsity<> vbcrs_blocked;\n  vbcrs_blocked.init(multi_slices[k].data(), super_blocks);\n  cout << \"memreq blocked: \"\n       << vbcrs_blocked.memsize() << \"\\n\"\n       << \"nblocks: \" << vbcrs_blocked.nblocks() << \"\\n\"\n       << \"nrows: \" << vbcrs_blocked.nblock_rows() << \"\\n\";\n\n  std::ofstream fout_blocked(\"vbcrs_blocked.dat\");\n  vbcrs_blocked.save(fout_blocked);\n  fout_blocked.close();\n\n  ct_dense::VBCRSSparsity<> vbcrs;\n  vbcrs.init(multi_slices[k].data(), K);\n  cout << \"memreq: \"\n       << vbcrs.memsize() << \"\\n\"\n       << \"nblocks: \" << vbcrs.nblocks() << \"\\n\"\n       << \"nrows: \" << vbcrs.nblock_rows() << \"\\n\";\n  std::ofstream fout(\"vbcrs.dat\");\n  vbcrs.save(fout);\n  fout.close();\n\n  // ==================================================\n  // use `cluster_vbcrs_sparsity`\n  std::vector<ct_dense::VBCRSSparsity<>> vb_blocked;\n  cluster_vbcrs_sparsity::cluster(vb_blocked, /* dst */\n                                  vbcrs_sparsity_patterns,\n                                  multi_slices,\n                                  basis,\n                                  min_blk_size);\n\n  return 0;\n}\n", "meta": {"hexsha": "3970f4623dc464f2b4ba49be8938830263e2ddba", "size": 5740, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/collision_tensor_dense/main_vbcrs.cpp", "max_stars_repo_name": "simonpintarelli/2dBoltzmann", "max_stars_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/collision_tensor_dense/main_vbcrs.cpp", "max_issues_repo_name": "simonpintarelli/2dBoltzmann", "max_issues_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/collision_tensor_dense/main_vbcrs.cpp", "max_forks_repo_name": "simonpintarelli/2dBoltzmann", "max_forks_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.1956521739, "max_line_length": 98, "alphanum_fraction": 0.6120209059, "num_tokens": 1576, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324893520001, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.49841844803352886}}
{"text": "#include \"PCE.h\"\n#include \"GeomCommonFunctions.h\"\n#include <Gui/Application.h>\n#include <BRepBuilderAPI_GTransform.hxx>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <tchar.h>\n#include <iostream>\n\nusing namespace PartDesignGui;\n\nLocalCS::LocalCS()\n{\n\torigin = Vector2d(0.0,0.0);\n\taxis_x = Vector2d(1.0,0.0);\n\taxis_y = Math::Functs::RotationAxis2d(axis_x, -Math::Math_PI / 2.0, Vector2d(0.0, 0.0));\n\tMath::Functs::SetVectorLength(axis_x, 1.0);\n\tMath::Functs::SetVectorLength(axis_y, 1.0);\n\tangle = Math::Functs::GetAngleBetween(axis_x, Vector2d(1.0, 0.0));\n\tif (axis_x[1] < 0.0) angle = 2 * M_PI - angle;\n\torigin_max_y = 0.0;\n\torigin_min_y = 0.0;\n\torigin_min_x = 0.0;\n\torigin_max_x = 0.0;\n\toffset_max_y = 0.0;\n\toffset_min_y = 0.0;\n\toffset_min_x = 0.0;\n\toffset_max_x = 0.0;\n}\nLocalCS::LocalCS(const Vector2d& o, const Vector2d& x)\n{\n\torigin = o;\n\taxis_x = x;\n\taxis_y = Math::Functs::RotationAxis2d(axis_x, -Math::Math_PI/2.0, Vector2d(0.0, 0.0));\n\tMath::Functs::SetVectorLength(axis_x, 1.0);\n\tMath::Functs::SetVectorLength(axis_y, 1.0);\n\tangle = Math::Functs::GetAngleBetween(axis_x, Vector2d(1.0, 0.0));\n\tif (axis_x[1] < 0.0) angle = 2 * M_PI - angle;\n\torigin_max_y = 0.0;\n\torigin_min_y = 0.0;\n\torigin_min_x = 0.0;\n\torigin_max_x = 0.0;\n\toffset_max_y = 0.0;\n\toffset_min_y = 0.0;\n\toffset_min_x = 0.0;\n\toffset_max_x = 0.0;\n}\n\nvoid LocalCS::SetCS(const Vector2d& o, const Vector2d& x)\n{\n\torigin = o;\n\taxis_x = x;\n\taxis_y = Math::Functs::RotationAxis2d(axis_x, -Math::Math_PI / 2.0, Vector2d(0.0, 0.0));\n\tMath::Functs::SetVectorLength(axis_x, 1.0);\n\tMath::Functs::SetVectorLength(axis_y, 1.0);\n\tangle = Math::Functs::GetAngleBetween(axis_x, Vector2d(1.0, 0.0));\n\tif (axis_x[1] < 0.0) angle = 2 * M_PI - angle;\n\torigin_max_y = 0.0;\n\torigin_min_y = 0.0;\n\torigin_min_x = 0.0;\n\torigin_max_x = 0.0;\n\toffset_max_y = 0.0;\n\toffset_min_y = 0.0;\n\toffset_min_x = 0.0;\n\toffset_max_x = 0.0;\n}\n\nVector2d LocalCS::GetLocal(const Vector2d& v) const\n{\n\tVector2d result = v - origin;\n\tresult = Math::Functs::RotationAxis2d(result, angle, Vector2d(0.0, 0.0));\n\treturn result;\n}\n\nVector2d1 LocalCS::GetLocal(const Vector2d1& points) const\n{\n\tVector2d1 results;\n\tfor (auto p : points)\n\t\tresults.emplace_back(GetLocal(p));\n\treturn results;\n}\n\n//need to check\nVector2d LocalCS::GetGlobalPos(const Vector2d& v) const\n{\n\tVector2d result = Math::Functs::RotationAxis2d(v, -angle, Vector2d(0.0, 0.0));\n\tresult = result + origin;\n\treturn result;\n}\n\nVector2d LocalCS::GetGlobalVec(const Vector2d& v) const\n{\n\tVector2d result = Math::Functs::RotationAxis2d(v, -angle, Vector2d(0.0, 0.0));\n\treturn result;\n}\n\nbool LocalCS::GetSegOrigin(const HMODULE& hModule, const double part_match_error, const Vector2d& s, const Vector2d& e, double& min_x, double& max_x) const\n{\n\tauto cgal_2d_inter_line_line = (CGAL_2D_Intersection_Line_Line)GetProcAddress(hModule, \"CGAL_2D_Intersection_Line_Line\");\n\tVector2d low_v = e;\n\tVector2d upper_v = s;\n\tif (s[1] <= e[1])\n\t{\n\t\tlow_v = s;\n\t\tupper_v = e;\n\t}\n\n\t//outside\n\tif (low_v[1] > origin_max_y || upper_v[1] < origin_min_y ||\n\t\tMath::Functs::IsAlmostZero_Double(low_v[1] - origin_max_y, part_match_error) || Math::Functs::IsAlmostZero_Double(upper_v[1] - origin_min_y, part_match_error))\n\t\treturn false;\n\n\t//all in\n\tif ((low_v[1] > origin_min_y||Math::Functs::IsAlmostZero_Double(low_v[1]- origin_min_y, part_match_error)) &&\n\t\t(upper_v[1] < origin_max_y||Math::Functs::IsAlmostZero_Double(upper_v[1]- origin_max_y, part_match_error)))\n\t{\n\t\tmin_x = low_v[0];\n\t\tmax_x = upper_v[0];\n\t\tif (low_v[0] > upper_v[0])\n\t\t{\n\t\t\tmin_x = upper_v[0];\n\t\t\tmax_x = low_v[0];\n\t\t}\n\t\treturn true;\n\t}\n\n\t//cutting lower\n\tif (low_v[1]< origin_min_y && upper_v[1]>origin_min_y && (upper_v[1] < origin_max_y||\n\t\tMath::Functs::IsAlmostZero_Double(upper_v[1]- origin_max_y, part_match_error)))\n\t{\n\t\tVector2d inter;\n\t\tif (cgal_2d_inter_line_line(low_v, upper_v, Vector2d(0.0, origin_min_y), Vector2d(1.0, origin_min_y), inter))\n\t\t{\n\t\t\tmin_x = inter[0];\n\t\t\tmax_x = upper_v[0];\n\t\t\tif (inter[0] > upper_v[0])\n\t\t\t{\n\t\t\t\tmin_x = upper_v[0];\n\t\t\t\tmax_x = inter[0];\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t}\n\n\t//cutting upper\n\tif (upper_v[1] > origin_max_y && (low_v[1] > origin_min_y||Math::Functs::IsAlmostZero_Double(low_v[1]- origin_min_y, part_match_error)) && low_v[1] < origin_max_y)\n\t{\n\t\tVector2d inter;\n\t\tif (cgal_2d_inter_line_line(low_v, upper_v, Vector2d(0.0, origin_max_y), Vector2d(1.0, origin_max_y), inter))\n\t\t{\n\t\t\tmin_x = low_v[0];\n\t\t\tmax_x = inter[0];\n\t\t\tif (low_v[0] > inter[0])\n\t\t\t{\n\t\t\t\tmin_x = inter[0];\n\t\t\t\tmax_x = low_v[0];\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t}\n\n\n\tif (upper_v[1] > origin_max_y && low_v[1] < origin_min_y)\n\t{\n\t\tVector2d inter_0;\n\t\tbool b0 = cgal_2d_inter_line_line(low_v, upper_v, Vector2d(0.0, origin_min_y), Vector2d(1.0, origin_min_y), inter_0);\n\t\tVector2d inter_1;\n\t\tbool b1 = cgal_2d_inter_line_line(low_v, upper_v, Vector2d(0.0, origin_max_y), Vector2d(1.0, origin_max_y), inter_1);\n\n\t\tif (b0 && b1)\n\t\t{\n\t\t\tmin_x = inter_0[0];\n\t\t\tmax_x = inter_1[0];\n\t\t\tif (inter_0[0] > inter_1[0])\n\t\t\t{\n\t\t\t\tmin_x = inter_1[0];\n\t\t\t\tmax_x = inter_0[0];\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\nbool LocalCS::GetSegOffset(const HMODULE& hModule, const double part_match_error, const Vector2d& s, const Vector2d& e, double& min_x, double& max_x) const\n{\n\tauto cgal_2d_inter_line_line = (CGAL_2D_Intersection_Line_Line)GetProcAddress(hModule, \"CGAL_2D_Intersection_Line_Line\");\n\n\tVector2d low_v = e;\n\tVector2d upper_v = s;\n\tif (s[1] <= e[1])\n\t{\n\t\tlow_v = s;\n\t\tupper_v = e;\n\t}\n\n\t//outside\n\tif (low_v[1] > offset_max_y || upper_v[1] < offset_min_y ||\n\t\tMath::Functs::IsAlmostZero_Double(low_v[1] - offset_max_y, part_match_error) ||\n\t\tMath::Functs::IsAlmostZero_Double(upper_v[1] - offset_min_y, part_match_error))\n\t\treturn false;\n\n\t//all in\n\tif (low_v[1] >= offset_min_y && upper_v[1] <= offset_max_y)\n\t{\n\t\tmin_x = low_v[0];\n\t\tmax_x = upper_v[0];\n\t\tif (low_v[0] > upper_v[0])\n\t\t{\n\t\t\tmin_x = upper_v[0];\n\t\t\tmax_x = low_v[0];\n\t\t}\n\t\treturn true;\n\t}\n\n\t//cutting lower\n\tif (low_v[1]< offset_min_y && upper_v[1]>offset_min_y && upper_v[1] <= offset_max_y)\n\t{\n\t\tVector2d inter;\n\t\tif (cgal_2d_inter_line_line(low_v, upper_v, Vector2d(0.0, offset_min_y), Vector2d(1.0, offset_min_y), inter))\n\t\t{\n\t\t\tmin_x = inter[0];\n\t\t\tmax_x = upper_v[0];\n\t\t\tif (inter[0] > upper_v[0])\n\t\t\t{\n\t\t\t\tmin_x = upper_v[0];\n\t\t\t\tmax_x = inter[0];\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t}\n\n\t//cutting upper\n\tif (upper_v[1] > offset_max_y && low_v[1] >= offset_min_y && low_v[1] < offset_max_y)\n\t{\n\t\tVector2d inter;\n\t\tif (cgal_2d_inter_line_line(low_v, upper_v, Vector2d(0.0, offset_max_y), Vector2d(1.0, offset_max_y), inter))\n\t\t{\n\t\t\tmin_x = low_v[0];\n\t\t\tmax_x = inter[0];\n\t\t\tif (low_v[0] > inter[0])\n\t\t\t{\n\t\t\t\tmin_x = inter[0];\n\t\t\t\tmax_x = low_v[0];\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t}\n\n\n\tif (upper_v[1] > offset_max_y && low_v[1] < offset_min_y)\n\t{\n\t\tVector2d inter_0;\n\t\tbool b0 = cgal_2d_inter_line_line(low_v, upper_v, Vector2d(0.0, offset_min_y), Vector2d(1.0, offset_min_y), inter_0);\n\t\tVector2d inter_1;\n\t\tbool b1 = cgal_2d_inter_line_line(low_v, upper_v, Vector2d(0.0, offset_max_y), Vector2d(1.0, offset_max_y), inter_1);\n\n\t\tif (b0 && b1)\n\t\t{\n\t\t\tmin_x = inter_0[0];\n\t\t\tmax_x = inter_1[0];\n\t\t\tif (inter_0[0] > inter_1[0])\n\t\t\t{\n\t\t\t\tmin_x = inter_1[0];\n\t\t\t\tmax_x = inter_0[0];\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\nVector2d1 LocalCS::SortX(const Vector2d1& segs) const\n{\n\tVector2d1 sort_segs;\n\tif (segs.size() == 0) return sort_segs;\n\tdouble minimal_x = segs[0][0];\n\tdouble maximal_x = segs[0][1];\n\n\tfor (int iter = 0; iter < segs.size(); iter++)\n\t{\n\t\tauto& seg = segs[iter];\n\t\tif (seg[0] >= minimal_x && seg[0] <= maximal_x)\n\t\t{\n\t\t\tif (seg[1] > maximal_x)\n\t\t\t\tmaximal_x = seg[1];\n\t\t}\n\t\telse\n\t\t{\n\t\t\tsort_segs.emplace_back(minimal_x, maximal_x);\n\t\t\tminimal_x = segs[iter][0];\n\t\t\tmaximal_x = segs[iter][1];\n\t\t}\n\n\t\tif (iter == segs.size() - 1)\n\t\t{\n\t\t\tsort_segs.emplace_back(minimal_x, maximal_x);\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn sort_segs;\n}\n\nVector2d1 LocalCS::EmptyX(const Vector2d1& sort_segs) const\n{\n\tVector2d1 empty_segs;\n\tfor (int i = 1; i < sort_segs.size(); i++)\n\t\tempty_segs.emplace_back(sort_segs[i - 1][1], sort_segs[i][0]);\n\treturn empty_segs;\n}", "meta": {"hexsha": "18e738ea586b8373f26ac80a06f24bb78ac7bf82", "size": 8079, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Gui/PCE_CS.cpp", "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/PCE_CS.cpp", "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/PCE_CS.cpp", "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": 26.0612903226, "max_line_length": 164, "alphanum_fraction": 0.6712464414, "num_tokens": 3063, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324893519999, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.49841844803352875}}
{"text": "/*\n   For more information, please see: http://software.sci.utah.edu\n\n   The MIT License\n\n   Copyright (c) 2015 Scientific Computing and Imaging Institute,\n   University of Utah.\n\n   \n   Permission is hereby granted, free of charge, to any person obtaining a\n   copy of this software and associated documentation files (the \"Software\"),\n   to deal in the Software without restriction, including without limitation\n   the rights to use, copy, modify, merge, publish, distribute, sublicense,\n   and/or sell copies of the Software, and to permit persons to whom the\n   Software is furnished to do so, subject to the following conditions:\n\n   The above copyright notice and this permission notice shall be included\n   in all copies or substantial portions of the Software.\n\n   THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n   DEALINGS IN THE SOFTWARE.\n*/\n/// @todo Documentation Core/Datatypes/Legacy/Matrix/DenseMatrix.cc\n\n#include <sci_defs/lapack_defs.h>\n#include <sci_defs/blas_defs.h>\n#include <Core/Datatypes/DenseMatrix.h>\n#include <cstdio>\n\n#include <iostream>\n#include <limits>\n#include <sstream>\n#include <stdexcept>\n#include <string.h>\n#include <vector>\n\n#include <Core/Datatypes/ColumnMatrix.h>\n#include <Core/Datatypes/SparseRowMatrix.h>\n\n#include <Core/Exceptions/DimensionMismatch.h>\n\n#include <boost/shared_array.hpp>\n\n#include <Core/Math/MiscMath.h>\n\nnamespace SCIRun {\n\n// NOTE: returns 1 if successful, or 0 if unsuccessful (i.e. ignore the solution vector)\nint\nLinearAlgebra::solve(const DenseMatrix& matrix, ColumnMatrix& sol)\n{\n  ColumnMatrix b(sol);\n  return solve(matrix, b, sol);\n}\n\n\n// NOTE: returns 1 if successful, or 0 if unsuccessful (i.e. ignore the solution vector)\nint\nLinearAlgebra::solve(const DenseMatrix& matrix, const ColumnMatrix& rhs, ColumnMatrix& lhs)\n{\n  ASSERT(matrix.nrows() == matrix.ncols());\n  ASSERT(rhs.nrows() == matrix.ncols());\n  lhs=rhs;\n\n  double **A;\n  double **cpy = 0;\n  double *lhsp = lhs.get_data_pointer();\n\t\n  cpy = new double*[matrix.nrows()]; \n\n  for (index_type j=0; j < matrix.nrows(); j++)\n    cpy[j] = matrix.get_raw_2D_pointer()[j];\n\n  A = cpy;\n\n  // Gauss-Jordan with partial pivoting\n  index_type i;\n  for (i=0; i < matrix.nrows(); i++)\n  {\n    double max=Abs(A[i][i]);\n    index_type row=i;\n    index_type j;\n    for (j=i+1; j < matrix.nrows(); j++)\n    {\n      if(Abs(A[j][i]) > max)\n      {\n        max=Abs(A[j][i]);\n        row=j;\n      }\n    }\n    //  ASSERT(Abs(max) > 1.e-12);\n    if (Abs(max) < 1.e-12)\n    {\n      lhs=rhs;\n      delete cpy;\n      return 0;\n    }\n    if(row != i)\n    {\n      // Switch rows (actually their pointers)\n      std::swap(A[i], A[row]);\n      std::swap(lhsp[i], lhsp[row]);\n    }\n    double denom=1./A[i][i];\n    double* r1=A[i];\n    double s1=lhsp[i];\n    for (j=i+1; j<matrix.nrows(); j++)\n    {\n      double factor=A[j][i]*denom;\n      double* r2=A[j];\n      for (int k=i; k<matrix.nrows(); k++)\n        r2[k]-=factor*r1[k];\n      lhsp[j]-=factor*s1;\n    }\n  }\n\n  // Back-substitution\n  for (i=1; i<matrix.nrows(); i++)\n  {\n    //  cout << \"Solve: \" << i << \" of \" << nr << endl;\n    //  ASSERT(Abs(A[i][i]) > 1.e-12);\n    if (Abs(A[i][i]) < 1.e-12)\n    {\n      lhs=rhs;\n      delete cpy;\n      return 0;\n    }\n    double denom=1./A[i][i];\n    double* r1=A[i];\n    double s1=lhsp[i];\n    for (index_type j=0;j<i;j++)\n    {\n      double factor=A[j][i]*denom;\n      double* r2=A[j];\n      for (index_type k=i; k<matrix.nrows(); k++)\n        r2[k] -= factor*r1[k];\n      lhsp[j] -= factor*s1;\n    }\n  }\n\n  // Normalize\n  for (i=0; i<matrix.nrows(); i++)\n  {\n    //  cout << \"Solve: \" << i << \" of \" << nr << endl;\n    //  ASSERT(Abs(A[i][i]) > 1.e-12);\n    if (Abs(A[i][i]) < 1.e-12)\n    {\n      lhs=rhs;\n      delete cpy;\n      return 0;\n    }\n    double factor=1./A[i][i];\n    for (index_type j=0; j<matrix.nrows(); j++)\n      A[i][j] *= factor;\n    lhsp[i] *= factor;\n  }\n  delete cpy;\n  return 1;\n}\n\n\n\n\n#if defined(HAVE_LAPACK)\n\nvoid\nLinearAlgebra::solve_lapack(const DenseMatrix& matrix, const ColumnMatrix& rhs, ColumnMatrix& lhs)\n{\n  if (matrix.nrows() != matrix.ncols())\n  {\n    SCI_THROW(DimensionMismatch(matrix.nrows(), matrix.ncols(), __FILE__, __LINE__));\n  }\n\n  if (rhs.nrows() != matrix.ncols())\n  {\n    SCI_THROW(DimensionMismatch(rhs.nrows(), matrix.ncols(), __FILE__, __LINE__));\n  }\n  \n  ColumnMatrix rhsCopy(rhs); //need to make a copy because \n  \n  try\n  {\n    lapacksolvelinearsystem(matrix.get_raw_2D_pointer(), matrix.nrows(), matrix.ncols(), rhsCopy.get_data_pointer(), rhs.nrows(), rhs.ncols());\n  }\n  catch (const SCIRun::LapackError& exception)\n  {\n    std::ostringstream oss;\n    oss << \"Caught LapackError exception: \" << exception.message();\n    // in the absence of a logging service\n    std::cerr << oss.str() << std::endl;\n    throw;\n  }\n  \n  lhs=rhsCopy;\n  \n}\n  \nvoid\nLinearAlgebra::svd(const DenseMatrix& matrix, DenseMatrix& U, SparseRowMatrixHandle& S, DenseMatrix& VT)\n{\n  ASSERTEQ(U.ncols(), U.nrows());\n  ASSERTEQ(VT.ncols(), VT.nrows());\n  ASSERTEQ(U.nrows(), matrix.nrows());\n  ASSERTEQ(VT.ncols(), matrix.ncols());\n\n  /*\n   * LAPACK function dgesvd argument S is a DOUBLE PRECISION array\n   * with dimension (min(M,N)).\n   */\n  const size_type SIGMA_LEN = std::min(matrix.nrows(), matrix.ncols());\n  boost::shared_array<double> sigma(new double[SIGMA_LEN]);\n\n  try\n  {\n    lapacksvd(matrix.get_raw_2D_pointer(), matrix.nrows(), matrix.ncols(), sigma.get(), U.get_raw_2D_pointer(), VT.get_raw_2D_pointer());\n  }\n  catch (const SCIRun::LapackError& exception)\n  {\n    std::ostringstream oss;\n    oss << \"Caught LapackError exception: \" << exception.message();\n    // in the absence of a logging service\n    std::cerr << oss.str() << std::endl;\n    throw;\n  }\n\n  size_type nnz = 0;\n  for (size_type i = 0; i < SIGMA_LEN; ++i)\n  {\n    if ( fabs(sigma[i]) >= std::numeric_limits<double>::epsilon() )\n    {\n      ++nnz;\n    }\n  }\n\n  SparseRowMatrix::Data sparseData(matrix.nrows() + 1, nnz);\n  const SparseRowMatrix::Rows& rows = sparseData.rows();\n  const SparseRowMatrix::Columns& columns = sparseData.columns();\n  const SparseRowMatrix::Storage& a = sparseData.data();\n  if (!sparseData.allocated())\n  {\n    std::cerr << \"Could not allocate memory for sparse matrix buffers \"\n    << __FILE__ << \": \" << __LINE__ << std::endl;\n\n    return;\n  }\n\n  // singular values on diagonal\n  index_type count = 0;\n  index_type i = 0;\n  const index_type NROWS = matrix.nrows();\n  for (index_type r = 0; r < NROWS; r++)\n  {\n    rows[r] = count;\n    if ( r < matrix.ncols() && i < SIGMA_LEN && fabs(sigma[i]) >= std::numeric_limits<double>::epsilon() )\n    {\n      columns[count] = r;\n      a[count] = sigma[i];\n      ++count;\n      ++i;\n    }\n  }\n  rows[matrix.nrows()] = count;\n  \n  S = new SparseRowMatrix(matrix.nrows(), matrix.ncols(), sparseData, nnz);\n}\n\nvoid\nLinearAlgebra::svd(const DenseMatrix& matrix, DenseMatrix& U, DenseMatrix& S, DenseMatrix& VT)\n{\n  ASSERTEQ(U.ncols(), U.nrows());\n  ASSERTEQ(VT.ncols(), VT.nrows());\n  ASSERTEQ(U.nrows(), matrix.nrows());\n  ASSERTEQ(VT.ncols(), matrix.ncols());\n  ASSERTEQ(S.nrows(), matrix.nrows());\n  ASSERTEQ(S.ncols(), matrix.ncols());\n\n  /*\n   * LAPACK function dgesvd argument S is a DOUBLE PRECISION array\n   * with dimension (min(M,N)).\n   */\n  const size_type SIGMA_LEN = std::min(matrix.nrows(), matrix.ncols());\n  boost::shared_array<double> sigma(new double[SIGMA_LEN]);\n\n  try\n  {\n    lapacksvd(matrix.get_raw_2D_pointer(), matrix.nrows(), matrix.ncols(), sigma.get(), U.get_raw_2D_pointer(), VT.get_raw_2D_pointer());\n  }\n  catch (const SCIRun::LapackError& exception)\n  {\n    std::ostringstream oss;\n    oss << \"Caught LapackError exception: \" << exception.message();\n    // in the absence of a logging service\n    std::cerr << oss.str() << std::endl;\n    throw;\n  }\n\n  // Put singular values on diagonal.\n  for (size_type i = 0; i < SIGMA_LEN; ++i)\n    S.put(i, i, sigma[i]);\n}\n\nvoid\nLinearAlgebra::svd(const DenseMatrix& matrix, DenseMatrix& U, ColumnMatrix& S, DenseMatrix& VT)\n{\n  // Check whether matrices are square\n  if (U.ncols() != U.nrows())\n  {\n    SCI_THROW(DimensionMismatch(U.ncols(), U.nrows(), __FILE__, __LINE__));\n  }\n  \n  if (VT.ncols() != VT.nrows())\n  {\n    SCI_THROW(DimensionMismatch(VT.ncols(), VT.nrows(), __FILE__, __LINE__));\n  }\n  \n  if (U.nrows())\n  {\n    if (U.nrows() != matrix.nrows())\n    {\n      SCI_THROW(DimensionMismatch(U.nrows(), matrix.nrows(), __FILE__, __LINE__));\n    }    \n  }\n  if (VT.ncols())\n  {\n    if (VT.ncols() != matrix.ncols())\n    {\n      SCI_THROW(DimensionMismatch(VT.ncols(), matrix.ncols(), __FILE__, __LINE__));\n    }\n  }\n  \n  if (matrix.nrows() < matrix.ncols())\n  {\n    if (S.nrows() != matrix.nrows())\n    {\n      SCI_THROW(DimensionMismatch(S.nrows(), matrix.nrows(), __FILE__, __LINE__));\n    }\n  }\n  else\n  {\n    if (S.nrows() != matrix.ncols())\n    {\n      SCI_THROW(DimensionMismatch(S.nrows(), matrix.ncols(), __FILE__, __LINE__));\n    }\n  }\n\n  try\n  {\n    if (U.nrows() == 0 && VT.nrows() == 0)\n      lapacksvd(matrix.get_raw_2D_pointer(), matrix.nrows(), matrix.ncols(), S.get_data_pointer(), 0, 0);\n    else if (U.nrows() != 0 && VT.nrows() == 0)\n      lapacksvd(matrix.get_raw_2D_pointer(), matrix.nrows(), matrix.ncols(), S.get_data_pointer(), U.get_raw_2D_pointer(), 0);\n    else if (U.nrows() == 0 && VT.nrows() != 0)\n      lapacksvd(matrix.get_raw_2D_pointer(), matrix.nrows(), matrix.ncols(), S.get_data_pointer(), 0, VT.get_raw_2D_pointer());\n    else  \n      lapacksvd(matrix.get_raw_2D_pointer(), matrix.nrows(), matrix.ncols(), S.get_data_pointer(), U.get_raw_2D_pointer(), VT.get_raw_2D_pointer());\n  }\n  catch (const SCIRun::LapackError& exception)\n  {\n    std::ostringstream oss;\n    oss << \"Caught LapackError exception: \" << exception.message();\n    // in the absence of a logging service\n    std::cerr << oss.str() << std::endl;\n    throw;\n  }\n}\n\nvoid\nLinearAlgebra::eigenvalues(const DenseMatrix& matrix, ColumnMatrix& R, ColumnMatrix& I)\n{\n  ASSERTEQ(matrix.ncols(), matrix.nrows());\n  ASSERTEQ(R.nrows(), I.nrows());\n  ASSERTEQ(matrix.ncols(), R.nrows());\n\n  boost::shared_array<double> Er(new double[matrix.nrows()]);\n  boost::shared_array<double> Ei(new double[matrix.nrows()]);\n\n  try\n  {\n    lapackeigen(matrix.get_raw_2D_pointer(), matrix.nrows(), Er.get(), Ei.get());\n  }\n  catch (const SCIRun::LapackError& exception)\n  {\n    std::ostringstream oss;\n    oss << \"Caught LapackError exception: \" << exception.message();\n    // in the absence of a logging service\n    std::cerr << oss.str() << std::endl;\n    throw;\n  }\n\n  for (index_type i = 0; i < matrix.nrows(); i++)\n  {\n    R[i] = Er[i];\n    I[i] = Ei[i];\n  }\n}\n\nvoid\nLinearAlgebra::eigenvectors(const DenseMatrix& matrix, ColumnMatrix& R, ColumnMatrix& I, DenseMatrix& Vecs)\n{\n  ASSERTEQ(matrix.ncols(), matrix.nrows());\n  ASSERTEQ(R.nrows(), I.nrows());\n  ASSERTEQ(matrix.ncols(), R.nrows());\n\n  boost::shared_array<double> Er(new double[matrix.nrows()]);\n  boost::shared_array<double> Ei(new double[matrix.nrows()]);\n\n  try\n  {\n    lapackeigen(matrix.get_raw_2D_pointer(), matrix.nrows(), Er.get(), Ei.get(), Vecs.get_raw_2D_pointer());\n  }\n  catch (const SCIRun::LapackError& exception)\n  {\n    std::ostringstream oss;\n    oss << \"Caught LapackError exception: \" << exception.message();\n    // in the absence of a logging service\n    std::cerr << oss.str() << std::endl;\n    throw;\n  }\n\n\n  for (index_type i = 0; i<matrix.nrows(); i++)\n  {\n    R[i] = Er[i];\n    I[i] = Ei[i];\n  }\n}\n\n\n#else\n\nvoid\nLinearAlgebra::solve_lapack(const DenseMatrix& matrix, const ColumnMatrix& rhs, ColumnMatrix& lhs)\n{\n  ASSERTFAIL(\"Build was not configured with LAPACK. LinearAlgebra::solve_lapack is not available.\");\n}\n\nvoid\nLinearAlgebra::svd(const DenseMatrix& matrix, DenseMatrix& U, SparseRowMatrixHandle& S, DenseMatrix& VT)\n{\n  ASSERTFAIL(\"Build was not configured with LAPACK LinearAlgebra::svd is not available.\");\n}\n\nvoid\nLinearAlgebra::svd(const DenseMatrix& matrix, DenseMatrix& U, ColumnMatrix& S, DenseMatrix& VT)\n{\n  ASSERTFAIL(\"Build was not configured with LAPACK LinearAlgebra::svd is not available.\");\n}\n\t\nvoid\nLinearAlgebra::svd(const DenseMatrix& matrix, DenseMatrix& U, DenseMatrix& S, DenseMatrix& VT)\n{\n  ASSERTFAIL(\"Build was not configured with LAPACK LinearAlgebra::svd is not available.\");\n}\n\t\nvoid\nLinearAlgebra::eigenvalues(const DenseMatrix& matrix, ColumnMatrix& R, ColumnMatrix& I)\n{\n  ASSERTFAIL(\"Build was not configured with LAPACK LinearAlgebra::svd is not available.\");\n}\n\nvoid\nLinearAlgebra::eigenvectors(const DenseMatrix& matrix, ColumnMatrix& R, ColumnMatrix& I, DenseMatrix& Vecs)\n{\n  ASSERTFAIL(\"Build was not configured with LAPACK LinearAlgebra::svd is not available.\");\n}\n\t\n#endif\n\n} // End namespace SCIRun\n", "meta": {"hexsha": "134f0b35787d9d1fccefe41c426731144504445c", "size": 13086, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/Core/Datatypes/Legacy/Matrix/DenseMatrix.cc", "max_stars_repo_name": "mhansen1/SCIRun", "max_stars_repo_head_hexsha": "9719c570a6d6911a9eb8df584bd2c4ad8b8cd2ba", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Core/Datatypes/Legacy/Matrix/DenseMatrix.cc", "max_issues_repo_name": "mhansen1/SCIRun", "max_issues_repo_head_hexsha": "9719c570a6d6911a9eb8df584bd2c4ad8b8cd2ba", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Core/Datatypes/Legacy/Matrix/DenseMatrix.cc", "max_forks_repo_name": "mhansen1/SCIRun", "max_forks_repo_head_hexsha": "9719c570a6d6911a9eb8df584bd2c4ad8b8cd2ba", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5494736842, "max_line_length": 148, "alphanum_fraction": 0.6432064802, "num_tokens": 3802, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.4984184480335287}}
{"text": "#include <Rodin/Mesh.h>\n#include <Rodin/Solver.h>\n#include <Rodin/Variational.h>\n#include <RodinExternal/MMG.h>\n#include <vector>\n#include <typeinfo>\n\n// Dependencies required for eigenvalue computation\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n#include <Spectra/GenEigsSolver.h>\n#include <Spectra/MatOp/SparseGenMatProd.h>\n#include <Spectra/SymGEigsShiftSolver.h>\n\nusing namespace Rodin;\nusing namespace Rodin::Variational;\nusing namespace Rodin::External;\n\nEigen::SparseMatrix<double> mfemToEigenSparse(mfem::SparseMatrix m)\n{\n  typedef Eigen::Triplet<double> Triplet;\n\n  int nonZero = m.NumNonZeroElems();\n  std::vector<Triplet> tripletList;\n\n  // Get the values (i,j, data)\n  int* m_I = m.GetI();\n  int* m_J = m.GetJ();\n  double* m_data = m.GetData();\n\n  for(int r = 0; r < m.NumRows(); ++r){\n    for(int j=m_I[r]; j<m_I[r+1]; ++j){\n      tripletList.push_back(Triplet(r, m_J[j], m_data[j])); // ???? Inverse row and column since Eigen is CSC\n    }\n  }\n  Eigen::SparseMatrix<double> m_sparse(m.NumRows(), m.NumCols());\n  m_sparse.setFromTriplets(tripletList.begin(), tripletList.end()); //SEGFAULT\n\n  return m_sparse;\n}\n\n\nclass EigenSolver{\n\n  public:\n    // Constructors\n    EigenSolver();\n\n    // Destructor\n    ~EigenSolver() = default;\n\n    // Accessors\n    GridFunction<H1>& getEigenFunction(int index);\n\n    double getEigenValue(int index);\n    std::vector<double> getEigenValues();\n\n    // Options\n    EigenSolver& setNumEV(unsigned int nev);\n    EigenSolver& setShift(double shift);\n\n    // Solves the problem\n    void solve(mfem::SparseMatrix A, mfem::SparseMatrix B, FiniteElementSpace<H1>& fes);\n\n  private:\n    std::vector<double> m_eigenvalues;\n    std::vector<GridFunction<H1>*> m_eigenfunctions;\n    unsigned int m_nev;\n    double m_shift;\n};\n\n\n\nint main(int argc, char** argv)\n{\n  const char* meshFile = \"../resources/mfem/levelset-cantilever2d-example.mesh\";\n\n  // Define interior and exterior for level set discretization\n  int Interior = 1, Exterior = 2;\n\n  // Define boundary attributes\n  int Gamma0 = 1, GammaD = 2, GammaN = 3, Gamma = 4;\n\n  // Load mesh\n  Mesh Omega;\n  Omega.load(meshFile);\n\n  // Solver for hilbertian regularization\n  auto solver = Solver::UMFPack();\n\n  // Optimization parameters\n  size_t maxIt = 100;\n  double eps = 1e-6;\n  double hmax = 0.05;\n  int k = 1; // The eigenvalue to optimize\n  auto alpha = ScalarFunction(4 * hmax * hmax); // Parameter for hilbertian regularization\n\n  std::vector<double> obj;\n\n  /*\n  // Scalar field finite element space over the whole domain\n  FiniteElementSpace<H1> Vh(Omega);\n\n  // Trim the exterior part of the mesh to solve the elasticity system\n  SubMesh trimmed = Omega.trim(Exterior, Gamma);\n\n  // Build a finite element space over the trimmed mesh\n  FiniteElementSpace<H1> VhInt(trimmed);\n\n  // Elasticity equation\n  TrialFunction uInt(VhInt);\n  TestFunction  vInt(VhInt);\n\n  // A\n  Problem stiffness(uInt, vInt);\n  stiffness = Integral(Grad(uInt), Grad(vInt));\n  stiffness.update().assemble();\n\n  // B\n  Problem mass(uInt, vInt);\n  mass = Integral(uInt, vInt);\n  mass.update().assemble();\n\n  auto& m1 = stiffness.getStiffnessMatrix();\n  auto& m2 = mass.getStiffnessMatrix();\n\n\n  // Solve eigenvalue problem\n  EigenSolver ES;\n  ES.setShift(1.0).setNumEV(k+4).solve(m1, m2, VhInt);\n\n  // Get solution and transfer to original domain\n  GridFunction u(Vh);\n  ES.getEigenFunction(k).transfer(u);\n  double mu = ES.getEigenValue(k);\n\n  // Save solution\n  u.save(\"u.gf\");\n  Omega.save(\"Omega.mesh\");\n  */\n\n  // Optimization loop\n  for (size_t i = 0; i < maxIt; i++)\n  {\n    // Scalar field finite element space over the whole domain\n    FiniteElementSpace<H1> Vh(Omega);\n\n    // Trim the exterior part of the mesh to solve the elasticity system\n    SubMesh trimmed = Omega.trim(Exterior, Gamma);\n\n    // Build a finite element space over the trimmed mesh\n    FiniteElementSpace<H1> VhInt(trimmed);\n\n    // Elasticity equation\n    TrialFunction uInt(VhInt);\n    TestFunction  vInt(VhInt);\n\n    // A\n    Problem stiffness(uInt, vInt);\n    stiffness = Integral(Grad(uInt), Grad(vInt));\n    stiffness.update().assemble();\n\n    // B\n    Problem mass(uInt, vInt);\n    mass = Integral(uInt, vInt);\n    mass.update().assemble();\n\n    auto& m1 = stiffness.getStiffnessMatrix();\n    auto& m2 = mass.getStiffnessMatrix();\n\n\n    // Solve eigenvalue problem\n    EigenSolver ES;\n    ES.setShift(1.0).setNumEV(k+4).solve(m1, m2, VhInt);\n\n    // Get solution and transfer to original domain\n    GridFunction u(Vh);\n    ES.getEigenFunction(k).transfer(u);\n    double mu = ES.getEigenValue(k);\n\n    // Compute the boundary shape gradientv\n    // Vector field finite element space over the whole domain\n    FiniteElementSpace<H1> Uh(Omega, 2);\n    auto n = Normal(2);\n\n    // GridFunction dJ(Uh);\n    //dJ = Omega.getVolume(Interior)*(Dot(Grad(u), Grad(u)) + mu*Dot(u,u))*n + mu*n; //  /Integral(Dot(u,u)) sur le sous-mesh\n    //std::cout << dJ.getFiniteElementSpace().getVectorDimension() << std::endl;\n\n    // Note from Carlos: 26/Avril/2022\n    // Salut !\n    // 1. I changed some things around, in particular I do not project the\n    // expression for dJ on a GridFunction. Instead I wrote the thing directly\n    // and hope that Rodin understands what I want hehe\n    // 2. I fixed the bug in the transfer function, thank you for testing this\n    // and narrowing down the problem! It helps a lot :)\n    // 3. I tried to run your code and it seems that the objective goes down\n    // but at one point the computation fails. I think due to parasitic\n    // components.\n    // 4. In the hilbertian procedure I removed the use of DirichletBC and used\n    // the usual expression.\n    //\n    // See you soon!\n\n    // Hilbert extension-regularization procedure\n    // This is bullshit\n    auto dJ = Dot(Grad(u).traceOf(Interior), Grad(u).traceOf(Interior)) * n;\n    TrialFunction g(Uh);\n    TestFunction  v(Uh);\n    Problem hilbert(g, v);\n    hilbert = Integral(alpha * Jacobian(g), Jacobian(v))\n            + Integral(g, v)\n            + BoundaryIntegral(dJ, v).over(Gamma);\n    solver.solve(hilbert);\n\n    // Save data to inspect\n    // Omega.save(\"Omegai.mesh\");\n    // g.getGridFunction().save(\"g.gf\");\n\n    // Update objective\n    obj.push_back(\n        mu * Omega.getVolume(Interior));\n    std::cout << \"[\" << i << \"] Objective: \" << obj.back() << std::endl;\n\n    // Convert data types to mmg types\n    auto mmgMesh = Cast(Omega).to<MMG::Mesh2D>();\n    auto mmgVel = Cast(g.getGridFunction()).to<MMG::VectorSolution2D>(mmgMesh);\n\n    // Generate signed distance function\n    auto mmgLs = MMG::Distancer2D().setInteriorDomain(Interior).distance(mmgMesh);\n\n    // Advect the level set function\n    double gInf = std::max(g.getGridFunction().max(), -g.getGridFunction().min());\n    double dt = hmax / gInf;\n    MMG::Advect2D(mmgLs, mmgVel).step(dt);\n\n    // Recover the implicit domain\n    auto mmgImplicit =\n      MMG::ImplicitDomainMesher2D().split(Interior, {Interior, Exterior})\n                                   .split(Exterior, {Interior, Exterior})\n                                   .setRMC(1e-3)\n                                   .setHMax(hmax)\n                                   .setBoundaryReference(Gamma)\n                                   .discretize(mmgLs);\n\n    // Convert back to Rodin data type\n    Omega = Cast(mmgImplicit).to<Rodin::Mesh<>>();\n\n    // Save mesh\n    Omega.save(\"Omega.mesh\");\n\n    // Test for convergence\n    if (obj.size() >= 2 && abs(obj[i] - obj[i - 1]) < eps)\n    {\n      std::cout << \"Convergence!\" << std::endl;\n      break;\n    }\n\n    std::ofstream plt(\"obj.txt\", std::ios::trunc);\n    for (size_t i = 0; i < obj.size(); i++)\n      plt << i << \",\" << obj[i] << \"\\n\";\n  }\n\n\n\n  return 0;\n}\n\n\n// Constructor\nEigenSolver::EigenSolver(){\n  m_nev = 0;\n  m_shift = 0.0;\n}\n\n// Accessors\nGridFunction<H1>& EigenSolver::getEigenFunction(int index){\n  return *m_eigenfunctions[index];\n}\n\ndouble EigenSolver::getEigenValue(int index){\n    return m_eigenvalues[index];\n}\n\nstd::vector<double> EigenSolver::getEigenValues(){\n  return m_eigenvalues;\n}\n\n// Options\nEigenSolver& EigenSolver::setNumEV(unsigned int nev){\n  m_nev = nev;\n  return *this;\n}\n\nEigenSolver& EigenSolver::setShift(double shift){\n  m_shift = shift;\n\n  return *this;\n}\n\nvoid EigenSolver::solve(mfem::SparseMatrix A,mfem::SparseMatrix B, FiniteElementSpace<H1>& fes){\n\n  // 1. CA and B to Eigen::SparseMatrix\n  //WARNING: MAY BE USELESS SINCE SPECTRA HANDLE OTHER MATRICES TYPES\n  //BUT MAY BE FASTER. IN FACT I DON'T HAVE A CLUE.\n  Eigen::SparseMatrix<double> A_sparse = mfemToEigenSparse(A);\n  Eigen::SparseMatrix<double> B_sparse = mfemToEigenSparse(B);\n\n  // 2. Use Spectra with the shift-inverse method to compute eigenvalue\n  // Define the shift-inverse and vector-multiplication operations\n  using OpType = Spectra::SymShiftInvert<double, Eigen::Sparse, Eigen::Sparse>;\n  using BOpType = Spectra::SparseSymMatProd<double>;\n  OpType op(A_sparse, B_sparse);\n  BOpType Bop(B_sparse);\n\n  // Construct the generalized eigensolver object\n  int ncv = 2*m_nev+1;\n  Spectra::SymGEigsShiftSolver<OpType, BOpType, Spectra::GEigsMode::ShiftInvert>\n    geigs(op, Bop, m_nev, ncv, m_shift);\n\n\n  // Initialize and compute\n  geigs.init();\n  int nconv = geigs.compute(Spectra::SortRule::LargestMagn); // UTILISER LARGESTMAGN ET PAS SMALLESTMAGN CAR ON EST EN SHIFT-INVERSE MODE\n\n  // Retrieve results\n  Eigen::VectorXd evalues;\n  Eigen::MatrixXd evecs;\n  if (geigs.info() == Spectra::CompInfo::Successful)\n  {\n      evalues = geigs.eigenvalues();\n      evecs = geigs.eigenvectors();\n  }\n\n\n  // Store in m_eigenvalues and m_eigenfunctions\n  // (and reverse the order to order from lowest to higest)\n  int dim = evecs.rows();\n\n  for(int i = 0; i < m_nev; i++){\n    m_eigenvalues.push_back(evalues[m_nev-i-1]);\n\n    std::unique_ptr<double[]> data(new double[dim]);\n    for(int j=0; j<dim; j++){\n      data[j] = evecs.col(m_nev-i-1)[j];\n    }\n    //std::copy(evecs.col(m_nev-i-1).data(), evecs.col(m_nev-i-1).data()+dim, data.get());\n\n    m_eigenfunctions.push_back(new GridFunction<H1>(fes));\n    m_eigenfunctions[i]->setData(std::move(data), dim);\n  }\n}\n", "meta": {"hexsha": "c99a9b661a119ab6f814dafb3325a23841d01a2c", "size": 10108, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/ShapeOptimization/LevelSetEigenvalue2D.cpp", "max_stars_repo_name": "carlos-brito-pacheco/rodin", "max_stars_repo_head_hexsha": "f2c946b290ebb2487a21c617de01be91a0692c72", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-02T19:04:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-02T19:04:38.000Z", "max_issues_repo_path": "examples/ShapeOptimization/LevelSetEigenvalue2D.cpp", "max_issues_repo_name": "cbritopacheco/rodin", "max_issues_repo_head_hexsha": "f2c946b290ebb2487a21c617de01be91a0692c72", "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/ShapeOptimization/LevelSetEigenvalue2D.cpp", "max_forks_repo_name": "cbritopacheco/rodin", "max_forks_repo_head_hexsha": "f2c946b290ebb2487a21c617de01be91a0692c72", "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.6345609065, "max_line_length": 137, "alphanum_fraction": 0.6612584092, "num_tokens": 2843, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.4984184480335287}}
{"text": "#ifndef TVMTL_MANIFOLD_SPD_HPP\n#define TVMTL_MANIFOLD_SPD_HPP\n\n#include <cmath>\n#include <complex>\n#include <iostream>\n\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n#include <Eigen/SVD>\n#include <unsupported/Eigen/MatrixFunctions>\n#include <unsupported/Eigen/KroneckerProduct>\n\n//own includes\n#include \"enumerators.hpp\"\n#include \"matrix_utils.hpp\"\n\nnamespace tvmtl {\n\n// Specialization SPD\ntemplate <int N>\nstruct Manifold< SPD, N> {\n    \n    public:\n\tstatic const MANIFOLD_TYPE MyType;\n\tstatic const int manifold_dim ;\n\tstatic const int value_dim; // TODO: maybe rename to embedding_dim \n\n\tstatic const bool non_isometric_embedding;\n\t\n\t// Scalar type of manifold\n\ttypedef double scalar_type;\n\ttypedef double dist_type;\n\ttypedef std::complex<double> complex_type;\n\ttypedef std::vector<double> weight_list; \n\n\t// Value Typedef\n\ttypedef Eigen::Matrix< scalar_type, N, N>\t\t\t\tvalue_type;\n\ttypedef value_type&\t\t\t\t\t\t\tref_type;\n\ttypedef const value_type&\t\t\t\t\t\tcref_type;\n\ttypedef std::vector<value_type, Eigen::aligned_allocator<value_type> >\tvalue_list; \n\t\n\t// Tangent space typedefs\n\ttypedef Eigen::Matrix <scalar_type, N * N, N * (N + 1) / 2>   tm_base_type;\n\ttypedef tm_base_type&\t\t\t\t\t    tm_base_ref_type;\n\n\t// Derivative Typedefs\n\ttypedef value_type\t\t\t     deriv1_type;\n\ttypedef deriv1_type&\t\t\t     deriv1_ref_type;\n\t\n\ttypedef Eigen::Matrix<scalar_type, N*N, N*N>\t\t\t\tderiv2_type;\n\ttypedef deriv2_type&\t\t\t\t\t\t\tderiv2_ref_type;\n\ttypedef\tEigen::Matrix<scalar_type, N * (N + 1) / 2, N * (N + 1) / 2>\trestricted_deriv2_type;\n\n\n\t// Manifold distance functions (for IRLS)\n\tinline static dist_type dist_squared(cref_type x, cref_type y);\n\tinline static void deriv1x_dist_squared(cref_type x, cref_type y, deriv1_ref_type result);\n\tinline static void deriv1y_dist_squared(cref_type x, cref_type y, deriv1_ref_type result);\n\n\tinline static void deriv2xx_dist_squared(cref_type x, cref_type y, deriv2_ref_type result);\n\tinline static void deriv2xy_dist_squared(cref_type x, cref_type y, deriv2_ref_type result);\n\tinline static void deriv2yy_dist_squared(cref_type x, cref_type y, deriv2_ref_type result);\n\n\n\t// Manifold exponentials und logarithms ( for Proximal point)\n\ttemplate <typename DerivedX, typename DerivedY>\n\tinline static void exp(const Eigen::MatrixBase<DerivedX>& x, const Eigen::MatrixBase<DerivedY>& y, Eigen::MatrixBase<DerivedX>& result);\n\tinline static void log(cref_type x, cref_type y, ref_type result);\n\n\tinline static void convex_combination(cref_type x, cref_type y, double t, ref_type result);\n\n\t// Implementations of the Karcher mean\n\t// Slow list version\n\tinline static void karcher_mean(ref_type x, const value_list& v, double tol=1e-10, int maxit=15);\n\tinline static void weighted_karcher_mean(ref_type x, const weight_list& w, const value_list& v, double tol=1e-10, int maxit=15);\n\t// Variadic templated version\n\ttemplate <typename V, class... Args>\n\tinline static void karcher_mean(V& x, const Args&... args);\n\ttemplate <typename V>\n\tinline static void variadic_karcher_mean_gradient(V& x, const V& y);\n\ttemplate <typename V, class... Args>\n\tinline static void variadic_karcher_mean_gradient(V& x, const V& y1, const Args&... args);\n\t\n\t// Basis transformation for restriction to tangent space\n\tinline static void tangent_plane_base(cref_type x, tm_base_ref_type result);\n\n\t// Projection\n\tinline static void projector(ref_type x);\n\n\t// Interpolation pre- and postprocessing\n\tinline static void interpolation_preprocessing(ref_type x);\n\tinline static void interpolation_postprocessing(ref_type x);\n\n};\n\n\n/*-----IMPLEMENTATION SPD----------*/\n\n// Static constants, Outside definition to avoid linker error\n\ntemplate <int N>\nconst MANIFOLD_TYPE Manifold < SPD, N>::MyType = SPD; \n\ntemplate <int N>\nconst int Manifold < SPD, N>::manifold_dim = N * (N + 1) / 2; \n\ntemplate <int N>\nconst int Manifold < SPD, N>::value_dim = N * N; \n\ntemplate <int N>\nconst bool Manifold < SPD, N>::non_isometric_embedding = true; \n\n\n// Squared SPD distance function\ntemplate <int N>\ninline typename Manifold < SPD, N>::dist_type Manifold < SPD, N>::dist_squared( cref_type x, cref_type y ){\n    #ifdef TV_SPD_DIST_DEBUG\n\tstd::cout << \"\\nDist2 function with x=\\n\" << x << \"\\nand y=\\n\" << y << std::endl;\n    #endif\n// NOTE: If x is not strictly spd, using LDLT completely halts the algorithm\n/*    value_type sqrtX = x.sqrt();\n    Eigen::LDLT<value_type> ldlt;\n    ldlt.compute(sqrtX);\n\n    value_type Z = ldlt.solve(y).transpose();\t\n    return ldlt.solve(Z).transpose().log().squaredNorm();\t*/\n    value_type invsqrt = x.sqrt().inverse();\n    return (invsqrt * y * invsqrt).log().squaredNorm();\n}\n\n\n// Derivative of Squared SPD distance w.r.t. first argument\n// TODO: Switch to solve() for N>4?\ntemplate <int N>\ninline void Manifold < SPD, N>::deriv1x_dist_squared( cref_type x, cref_type y, deriv1_ref_type result){\n    value_type invsqrt = x.sqrt().inverse();\n    result = -2.0 * invsqrt * (invsqrt * y * invsqrt).log() * invsqrt;\n}\n// Derivative of Squared SPD distance w.r.t. second argument\ntemplate <int N>\ninline void Manifold < SPD, N>::deriv1y_dist_squared( cref_type x, cref_type y, deriv1_ref_type result){\n    deriv1x_dist_squared(y, x, result);\n}\n\n\n// Second Derivative of Squared SPD distance w.r.t first argument\ntemplate <int N>\ninline void Manifold < SPD, N>::deriv2xx_dist_squared( cref_type x, cref_type y, deriv2_ref_type result){\n    value_type T2, T3, T4;\n    T2 = x.sqrt().inverse();\n    T3 = T2 * y * T2;\n    T4 = T3.log();\n\n    deriv2_type dlog, dsqrt;\n    KroneckerDLog(T3, dlog);\n    KroneckerDSqrt(x, dsqrt);\n\n    deriv2_type T2T4tId, IdT2T4, T2T2, T2yId, IdT2y;\n    T2T4tId = Eigen::kroneckerProduct(T2 * T4.transpose(), value_type::Identity());\n    IdT2T4 = Eigen::kroneckerProduct(value_type::Identity(), T2 * T4);\n    T2T2 = Eigen::kroneckerProduct(T2, T2);\n    T2yId = Eigen::kroneckerProduct(T2 * y, value_type::Identity());\n    IdT2y = Eigen::kroneckerProduct(value_type::Identity(), T2 * y);\n\n    result =  2 * (T2T4tId + IdT2T4 + T2T2 * dlog * (T2yId + IdT2y) ) * T2T2 * dsqrt;\n}\n// Second Derivative of Squared SPD distance w.r.t first and second argument\ntemplate <int N>\ninline void Manifold < SPD, N>::deriv2xy_dist_squared( cref_type x, cref_type y, deriv2_ref_type result){\n    value_type isqrtX, T1;\n    isqrtX = x.sqrt().eval().inverse();\n    T1 = isqrtX * y * isqrtX;\n\n    deriv2_type kp_isqrtX, dlog;\n    kp_isqrtX = Eigen::kroneckerProduct(isqrtX, isqrtX);\n    KroneckerDLog(T1, dlog);\n\n    result = -2 * kp_isqrtX * dlog * kp_isqrtX;\n}\n// Second Derivative of Squared SPD distance w.r.t second argument\ntemplate <int N>\ninline void Manifold < SPD, N>::deriv2yy_dist_squared( cref_type x, cref_type y, deriv2_ref_type result){\n    deriv2xx_dist_squared(y, x, result);\n}\n\n\n\n// Exponential and Logarithm Map\ntemplate <int N>\ntemplate <typename DerivedX, typename DerivedY>\ninline void Manifold <SPD, N>::exp(const Eigen::MatrixBase<DerivedX>& x, const Eigen::MatrixBase<DerivedY>& y, Eigen::MatrixBase<DerivedX>& result){\n    #ifdef TV_SPD_EXP_DEBUG\n\tstd::cout << \"\\nEXP function with x=\\n\" << x << \"\\nand y=\\n\" << y << std::endl;\n    #endif\n    value_type sqrtX = x.sqrt();\n    value_type Z = sqrtX.ldlt().solve(y).transpose();\t\n    result = sqrtX * sqrtX.transpose().ldlt().solve(Z).exp() * sqrtX;\t\n}\n\ntemplate <int N>\ninline void Manifold <SPD, N>::log(cref_type x, cref_type y, ref_type result){\n    #ifdef TV_SPD_LOG_DEBUG\n\tstd::cout << \"\\nLOG function with x=\\n\" << x << \"\\nand y=\\n\" << y << std::endl;\n    #endif\n    value_type sqrtX = x.sqrt();\n    value_type Z = sqrtX.ldlt().solve(y).transpose();\t\n    result = sqrtX * sqrtX.transpose().ldlt().solve(Z).log() * sqrtX;\t\n}\n\n// Tangent Plane restriction\ntemplate <int N>\ninline void Manifold <SPD, N>::tangent_plane_base(cref_type x, tm_base_ref_type result){\n    int d = value_type::RowsAtCompileTime;\n    int k = 0;\n    \n    value_type S, T;\n    S = x.sqrt();\n\n    for(int i=0; i<d; i++){\n\tT.setZero();\n\tT.col(i) = S.col(i);\n\tT = T * S;\n\n\tresult.col(k) = Eigen::Map<Eigen::VectorXd>(T.data(), T.size());\n\t++k;\n    }\n\n    for(int i=0; i<d-1; i++)\n\tfor(int j=i+1; j<d; j++){\n\t    T.setZero();\n\t    T.col(i) = S.col(j);\n\t    T.col(j) = S.col(i);\n\t    T = T * S;\n\n\t    result.col(k) = Eigen::Map<Eigen::VectorXd>(T.data(), T.size());\n\t    ++k;\n\t}\n}\n\ntemplate <int N>\ninline void Manifold <SPD, N>::projector(ref_type x){\n    // does not exist since SPD is an open set\n    // TODO: Eventually implement projection to semi positive definite matrices\n}\n\n// Convex geodesic combinations\ntemplate <int N>\ninline void Manifold <SPD, N>::convex_combination(cref_type x, cref_type y, double t, ref_type result){\n    value_type l;\n    log(x, y, l);\n    exp(x, l * t, result);\n}\n\n// Karcher mean implementations\ntemplate <int N>\ninline void Manifold<SPD, N>::karcher_mean(ref_type x, const value_list& v, double tol, int maxit){\n    value_type L, temp;\n   \n    int k = 0;\n    double error = 0.0;\n    do{\n\tscalar_type m1 = x.sum();\n\tL = value_type::Zero();\n\tfor(int i = 0; i < v.size(); ++i){\n\t    log(x, v[i], temp);\n\t    L += temp;\n\t}\n\texp(x, 0.5 / v.size() * (L + L.transpose()), temp);\n\tx = temp;\n\terror = std::abs(x.sum() - m1);\n\t++k;\n    } while(error > tol && k < maxit);\n\n}\n\ntemplate <int N>\ninline void Manifold<SPD, N>::weighted_karcher_mean(ref_type x, const weight_list& w, const value_list& v, double tol, int maxit){\n    value_type L, temp;\n   \n    int k = 0;\n    double error = 0.0;\n    do{\n\tscalar_type m1 = x.sum();\n\tL = value_type::Zero();\n\tfor(int i = 0; i < v.size(); ++i){\n\t    log(x, v[i], temp);\n\t    L += w[i] * temp;\n\t}\n\texp(x, 0.5 / v.size() * (L + L.transpose()), temp);\n\tx = temp;\n\terror = std::abs(x.sum() - m1);\n\t++k;\n    } while(error > tol && k < maxit);\n\n}\n\ntemplate <int N>\ntemplate <typename V, class... Args>\ninline void Manifold<SPD, N>::karcher_mean(V& x, const Args&... args){\n    V temp, sum;\n    \n    int numArgs = sizeof...(args);\n    int k = 0;\n    double error = 0.0;    \n    double tol = 1e-10;\n    int maxit = 15;\n    do{\n\tscalar_type m1 = x.sum();\n\tsum = x;\n\tvariadic_karcher_mean_gradient(sum, args...);\n\texp(x, 0.5 / numArgs * (sum + sum.transpose()), temp);\n\tx = temp;\n\terror = std::abs(x.sum() - m1);\n\t++k;\n    } while(error > tol && k < maxit);\n}\n\ntemplate <int N>\ntemplate <typename V>\ninline void Manifold<SPD, N>::variadic_karcher_mean_gradient(V& x, const V& y){\n    V temp;\n    log(x, y, temp);\n    x = temp;\n}\n\ntemplate <int N>\ntemplate <typename V, class... Args>\ninline void Manifold<SPD, N>::variadic_karcher_mean_gradient(V& x, const V& y1, const Args& ... args){\n    V temp1, temp2;\n    temp2 = x;\n    \n    log(x, y1, temp1);\n\n    variadic_karcher_mean_gradient(temp2, args...);\n    temp1 += temp2;\n    x = temp1;\n}\n\n\ntemplate <int N>\ninline void Manifold<SPD, N>::interpolation_preprocessing(ref_type x){\n    value_type t = x.log();\n    x = t;\n}\n\ntemplate <int N>\ninline void Manifold<SPD, N>::interpolation_postprocessing(ref_type x){\n    value_type t = ( 0.5 * (x + x.transpose()) ).exp();\n    x = t;\n}\n\n\n} // end namespace tvmtl\n\n\n\n\n\n\n\n\n#endif\n", "meta": {"hexsha": "8c9bebc1cc33ba368dd51922934834b95e9c6669", "size": 10996, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "mtvmtl/core/manifold_spd.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/manifold_spd.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/manifold_spd.hpp", "max_forks_repo_name": "pdebus/MTVMTL", "max_forks_repo_head_hexsha": "65a7754b34d1f6a1e86d15e3c2d4346b9418414f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2087912088, "max_line_length": 148, "alphanum_fraction": 0.6777009822, "num_tokens": 3273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324803738429, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.4984184425444453}}
{"text": "#include <iostream>\n#include <fstream>\n#include <string>\n#include <Eigen/Eigen>\n\nstruct PoseData {\n    Eigen::Vector3d p;\n    Eigen::Quaterniond q;\n    std::string filename;\n    int index;\n};\n\ninline Eigen::Vector3d logmap(const Eigen::Quaterniond &q) {\n    Eigen::AngleAxisd aa(q);\n    return aa.angle() * aa.axis();\n}\n\ninline std::vector<PoseData> read_7scenes_pose(const std::string &path, int pose_num, const std::string &pose_type) {\n    std::vector<PoseData> poses;\n    // printf(\"#idx px py pz qx qy qz qw\\n\");\n    for (int idx = 0; idx < pose_num; idx++) {\n        char filename[1024];\n        if (pose_type == \"gt\") {\n             sprintf(filename, \"%s/frame-%06d.pose.txt\", path.c_str(), idx);\n        } else if (pose_type == \"test\") {\n            sprintf(filename, \"%s/frame-%06d.txt\", path.c_str(), idx);\n        } else {\n            std::runtime_error(\"Unknown pose_type.\");\n        }\n        std::ifstream in(filename);\n        Eigen::Matrix4d e;\n        for (int r = 0; r < 4; r++) {\n            for (int c = 0; c < 4; c++) {\n                in >> e(r, c);\n            }\n        }\n        // origin: Twc\n        Eigen::Quaterniond qwc(e.block<3, 3>(0, 0));\n        Eigen::Vector3d pwc(e.block<3, 1>(0, 3));\n        if (std::abs(qwc.norm() - 1.0) > 1.0e-3) {\n           fprintf(stderr, \"Warning, rotation matrix may not be valid, qwc.norm() %.4e\", qwc.norm());\n        }\n        if (pose_type == \"gt\") {\n            pwc.x() += 0.0245;\n        } else if (pose_type == \"test\") {\n            pwc = -(qwc.conjugate() * pwc);\n            qwc = qwc.conjugate();\n        } else {\n            std::runtime_error(\"Unknown pose_type.\");\n        }\n        PoseData pose;\n        pose.q = qwc;\n        pose.p = pwc;\n        pose.filename = filename;\n        pose.index = idx;\n        poses.emplace_back(std::move(pose));\n        // printf(\"%05d %.9e %.9e %.9e %.9e %.9e %.9e %.9e\\n\", idx, pwc.x(), pwc.y(), pwc.z(), qwc.x(), qwc.y(), qwc.z(), qwc.w());\n    }\n    return poses;\n}\n\nint main(int argc, char **argv) {\n    std::string gt_dir = argv[1];\n    std::string pred_dir = argv[2];\n    const int pose_num = 1000;\n    auto gt_poses = read_7scenes_pose(gt_dir, pose_num, \"gt\");\n    auto pred_poses = read_7scenes_pose(pred_dir, pose_num, \"test\");\n    assert(pred_poses.size() == gt_poses.size());\n    double APE = 0, ARE = 0, Acount = 0;\n    std::vector<double> APEs, AREs;\n    for (int i = 0; i < pose_num; ++i) {\n        const auto &gt_pose = gt_poses[i];\n        const auto &pred_pose = pred_poses[i];\n        Eigen::Vector3d p_error = gt_pose.p - pred_pose.p;\n        Eigen::Vector3d q_error = logmap(gt_pose.q.conjugate() * pred_pose.q);\n        APE += p_error.squaredNorm();\n        ARE += q_error.squaredNorm();\n        APEs.push_back(p_error.norm() * 1e3);\n        AREs.push_back(q_error.norm() * 180 / M_PI);\n        Acount++;\n    }\n    Acount = std::max(Acount, 1.0);\n    APE = std::sqrt(APE / Acount) * 1e3;\n    ARE = std::sqrt(ARE / Acount) * 180 / M_PI;\n    printf(\"APE RMSE: %.3f [mm]\\nARE RMSE %.3f[DEG]\\n\", APE, ARE);\n    std::sort(APEs.begin(), APEs.end());\n    std::sort(AREs.begin(), AREs.end());\n    printf(\"APE median: %.3f [mm]\\nARE median %.3f[DEG]\\n\", APEs[APEs.size() / 2], AREs[AREs.size() / 2]);\n    return 0;\n}\n", "meta": {"hexsha": "7dee6e2b75d3b1b632c5f36d0e25a8d15604f4dd", "size": 3241, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/exec/evaluate_pose.cc", "max_stars_repo_name": "asdiuzd/lass", "max_stars_repo_head_hexsha": "a767f8bd68c46dadf8d74703fdf2058da9f17e53", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-06T09:04:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-06T09:04:46.000Z", "max_issues_repo_path": "src/exec/evaluate_pose.cc", "max_issues_repo_name": "asdiuzd/lass", "max_issues_repo_head_hexsha": "a767f8bd68c46dadf8d74703fdf2058da9f17e53", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/exec/evaluate_pose.cc", "max_forks_repo_name": "asdiuzd/lass", "max_forks_repo_head_hexsha": "a767f8bd68c46dadf8d74703fdf2058da9f17e53", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.6153846154, "max_line_length": 131, "alphanum_fraction": 0.5427337242, "num_tokens": 1017, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079209, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.49839821404413404}}
{"text": "#ifndef __PC_TO_SURFACES_HH__\n#define __PC_TO_SURFACES_HH__\n\n#include <vector>                                                                                                                                                                                              \n#include <iostream>\n\n#include <pcl/io/pcd_io.h>\n#include <pcl/point_types.h>\n\n#include <pcl/conversions.h>\n#include <pcl_conversions/pcl_conversions.h>\n#include <pcl/registration/ndt.h>\n#include <pcl/registration/icp.h>\n#include <pcl/registration/icp_nl.h>\n\n#include <pcl/features/normal_3d.h>\n#include <pcl/features/normal_3d_omp.h>\n#include <pcl/filters/voxel_grid.h>\n#include <pcl/octree/octree.h>\n#include <pcl/octree/octree_search.h>\n\n\n#include <pcl/visualization/pcl_visualizer.h>\n\n#include <Eigen/Eigenvalues> \n#include <Eigen/SVD>\n\n#include <utils.hh>\n\nstruct PC2SurfacesParams{\n  public:\n    PC2SurfacesParams();\n    void print();\n\n    int max_inner_iter;\n    int max_outer_iter;\n    int outlier_id;\n    int unclassified_id;\n    int object_id;\n    double term_perc_crit;\n    double normal_dev_thres1; // degrees\n    double normal_dev_thres2; \n    double contour_fit_thres; // ratio to radius\n    double sphere_r; // meters\n    double segment_len; // meters\n    double normal_search_radius;\n    int    num_segments;\n    string contour_type;\n    double voxel_leaf_size;\n    double curvature_thres;\n    double var_r;\n    double var_azimutal;\n    double var_elevation;\n    double max_segment_dist;\n    double max_segment_rot;\n};\n\nclass PC2Surfaces{\n  private:\n    PC2SurfacesParams _params;\n\n    // ------------ BOOKKEEPING --------------------------------------------------- //\n    // Segment ID of each point in '_pc_sphere'\n    vector<int> _segment_ids;\n    vector<int> _valid_segs;\n    // Outlier flags for points in '_pc_sphere'\n    vector<bool> _outliers;\n    // Mapping between segments and their corresponding \n    // coordinate triad, origin and contour equations.\n    std::map<int, Eigen::Matrix3d> _segment_triad_map;\n    std::map<int, Eigen::Vector3d> _segment_origin_map;\n    std::map<int, Eigen::VectorXd> _segment_contour_map;\n\n    // ------------ AXIS, CONTOUR & UNCERTAINTY ESTIMATION ------------------------ //\n    std::map<int, Eigen::Matrix3d> _segment_Mmatrix;\n    // Mapping between segments and eigenpairs of the 'M' matrix as \n    // stored in '_segment_Mmatrix'.\n    std::map<int, pair<Eigen::Vector3d, Eigen::Matrix3d> > _axis_eigenpairs;\n    // Mapping between segments and index of the smallest eigen value\n    // of the corresponding eigenpair.\n    std::map<int, int> _axis_min_eigval_ind;\n    // Mapping between segments and their corresponding axes's \n    // uncertainties.\n    std::map<int, Eigen::Matrix3d> _axis_uncertainties;\n    // Mapping between segments and the intermediate matrix-vector pairs\n    // calculated while estimating the contour the corresponding segment.\n    // This is a function of the form Ax=b.\n    std::map<int, pair<Eigen::MatrixXd, Eigen::VectorXd> > _segment_contour_equ;\n    // Mapping between segments and the derivative of the corresponding\n    // contour w.r.t. 'x' the solution to Ax=b explained above.\n    std::map<int, Eigen::MatrixXd> _segment_dcontour;\n    // Mapping between the segments and the corresponding contour \n    // uncertainties.\n    std::map<int, Eigen::MatrixXd> _contour_uncertainties;\n\n    // ------------ POINTCLOUDS --------------------------------------------------- //\n    // The original unfiltered point cloud.\n    pcl::PointCloud<pcl::PointXYZ>::Ptr _pc_orig;\n    // '_pc_orig' after filtered with voxel grid filter and radius filter.\n    pcl::PointCloud<pcl::PointXYZ>::Ptr _pc_sphere;\n    pcl::PointCloud<pcl::PointXYZ>::Ptr _pc_outliers;\n    pcl::PointCloud<pcl::PointXYZ>::Ptr _pc_objects;\n    // Normals of the points in '_pc_sphere'.\n    pcl::PointCloud<pcl::Normal>::Ptr _pc_sphere_normals;\n    // '_pc_sphere' written in the corresponding segment frame.\n    vector<Eigen::Vector3d> _pc_projections; \n\n    // ------------ NORMAL & UNCERTAINTY ESTIMATION ------------------------------- //\n    // Some intermediate variables used in estimating surface normals.\n    vector<vector<int  > > _nearest_neigh_inds;\n    vector<vector<float> > _nearest_neigh_sq_dists;\n    // Covariance and centroids for each point in '_pc_sphere' \n    vector<Eigen::Matrix3d> _normal_covs;\n    vector<Eigen::Vector4d> _normal_centroids;\n    // Eigenpairs of each '_normal_covs'\n    vector<pair<Eigen::Vector3d, Eigen::Matrix3d> > _normal_eigenpairs;\n    // Index of the smallest eigenvalue of the eigenpairs in '_normal_eigenpairs'\n    vector<int> _normal_min_eigval_ind;\n    // Uncertainties of each normals vector\n    vector<Eigen::Matrix3d> _normal_uncertainties;\n    // Uncertainties each point in '_pc_sphere' written in the sensor frame.\n    vector<Eigen::Matrix3d> _point_uncertainties;\n\n    // PCL's visualization toolbox\n    pcl::visualization::PCLVisualizer::Ptr _viewer;\n\n    // ---------------------------------------------------------------------------- //\n    // This fucntion estimates surface normals for each point in '_pc_sphere' as well\n    // as it estimates each normal's uncertainty.\n    int _fit_normals();\n    // This function initializes/refines the coordinate frame and the origin of the \n    // segment 'seg'. It also generates intermediate variables for later axis \n    // uncertainty estimation.\n    int _init_triad(int seg);\n    // This function iteratively filters for a segment, fits contour and eliminates\n    // outliers until convergence.\n    int _fit_segment(int seg);\n    // This function assigns points satisfying the criterion given in '_params' to 'seg'.\n    int _filter_segment(int seg);\n    // This function eliminates outliers of segment 'seg' with either using\n    // the 'normal' or 'contour' method.\n    int _eliminate_outliers(int seg, const std::string &method);\n    // This function transforms points of the segment 'seg' from the sensor\n    // frame to the corresponding segment frame.\n    int _project_pc(int seg);\n    // This function fits a contour to the projected points of the segment 'seg'\n    // using the method given in '_params'.\n    int _fit_contour(int seg);\n    // This function estimates axis and contour uncertainties of the segment 'seg'\n    int _estimate_uncertainties(int seg);\n  public:\n\n    PC2Surfaces();\n    PC2Surfaces(const PC2SurfacesParams &params);\n\n    int push_pc(const pcl::PointCloud<pcl::PointXYZ>::Ptr &pc);\n\n    inline int set_params(const PC2SurfacesParams &params){ \n      _params = params; \n      return 0;\n    }\n\n    inline int get_params(PC2SurfacesParams &params){ \n      params = _params; \n      return 0;\n    }\n\n    inline int get_segment_ids(vector<int> &ids, vector<bool> &outliers){\n      ids = _segment_ids;\n      outliers = _outliers;\n      return _segment_ids.size();\n    }\n\n    inline int get_segments( \n        map<int, Eigen::Vector3d> &segment_origins, \n        map<int, Eigen::Matrix3d> &segment_triads, \n        map<int, Eigen::VectorXd> &segment_contours){\n      segment_origins.clear();\n      segment_triads.clear();\n      segment_contours.clear();\n      for(int i = 0 ; i < (int)_valid_segs.size() ; i++){\n        int seg = _valid_segs[i];\n        segment_origins[seg]  = _segment_origin_map[seg];\n        segment_triads[seg]   = _segment_triad_map[seg];\n        segment_contours[seg] = _segment_contour_map[seg];\n      }\n      return segment_triads.size();\n    }\n\n    inline int get_orig_pc(pcl::PointCloud<pcl::PointXYZ>::Ptr &pc){\n      if(_pc_orig){\n        pc = pcl::PointCloud<pcl::PointXYZ>::Ptr(new pcl::PointCloud<pcl::PointXYZ>(*_pc_orig));\n        return pc->points.size();\n      } else {\n        pc = NULL;\n        return 0;\n      }\n    }\n\n    inline int get_pc_sphere(pcl::PointCloud<pcl::PointXYZ>::Ptr &pc){\n      if(_pc_sphere){\n        pc = pcl::PointCloud<pcl::PointXYZ>::Ptr(new pcl::PointCloud<pcl::PointXYZ>(*_pc_sphere));\n        return pc->points.size();\n      } else {\n        pc = NULL;\n        return 0;\n      }\n    }\n\n    inline int get_pc_outliers(pcl::PointCloud<pcl::PointXYZ>::Ptr &pc){\n      if(_pc_outliers){\n        pc = pcl::PointCloud<pcl::PointXYZ>::Ptr(new pcl::PointCloud<pcl::PointXYZ>(*_pc_outliers));\n        return pc->points.size();\n      } else {\n        pc = NULL;\n        return 0;\n      }\n    }\n\n    inline int get_pc_objects(pcl::PointCloud<pcl::PointXYZ>::Ptr &pc){\n      if(_pc_objects){\n        pc = pcl::PointCloud<pcl::PointXYZ>::Ptr(new pcl::PointCloud<pcl::PointXYZ>(*_pc_objects));\n        return pc->points.size();\n      } else {\n        pc = NULL;\n        return 0;\n      }\n    }\n\n\n\n    inline int get_normals(pcl::PointCloud<pcl::Normal>::Ptr &normals){\n      if(_pc_sphere_normals){\n        normals = pcl::PointCloud<pcl::Normal>::Ptr(new pcl::PointCloud<pcl::Normal>(*_pc_sphere_normals));\n        return normals->points.size();\n      } else {\n        normals = NULL;\n        return 0;\n      }\n    }\n\n    inline int get_uncertainties(\n        map<int, Eigen::Matrix3d> &axis_uncertainties, \n        map<int, Eigen::MatrixXd> &contour_uncertainties){\n      axis_uncertainties =  _axis_uncertainties;\n      contour_uncertainties =  _contour_uncertainties;\n      return axis_uncertainties.size();\n    }\n\n    inline int get_point_uncertainties(vector<Eigen::Matrix3d> &covs){\n      covs = _point_uncertainties;\n      return covs.size();\n    }\n\n    inline int get_normal_uncertainties(vector<Eigen::Matrix3d> &covs){\n      covs = _normal_uncertainties;\n      return covs.size();\n    }\n\n    int get_projections(int seg, vector<Eigen::Vector3d> &proj, vector<bool> &outliers);\n    int get_segment_pc(int seg, pcl::PointCloud<pcl::PointXYZ> &pc);\n\n    int visualize_fit();\n};\n\n\n\n#endif\n", "meta": {"hexsha": "dc4addaabdc5dc0789d347c63a4b37c17f95ee01", "size": 9699, "ext": "hh", "lang": "C++", "max_stars_repo_path": "tunnel_estimator/include/tunnel_estimator/pc_to_surfaces.hh", "max_stars_repo_name": "ozaslan/estimators", "max_stars_repo_head_hexsha": "ad78f2d395d4a6155f0b6d61541167a99959a1c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tunnel_estimator/include/tunnel_estimator/pc_to_surfaces.hh", "max_issues_repo_name": "ozaslan/estimators", "max_issues_repo_head_hexsha": "ad78f2d395d4a6155f0b6d61541167a99959a1c9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tunnel_estimator/include/tunnel_estimator/pc_to_surfaces.hh", "max_forks_repo_name": "ozaslan/estimators", "max_forks_repo_head_hexsha": "ad78f2d395d4a6155f0b6d61541167a99959a1c9", "max_forks_repo_licenses": ["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.0557620818, "max_line_length": 207, "alphanum_fraction": 0.6505825343, "num_tokens": 2318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079209, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.498398214044134}}
{"text": "/*************************************************************************\n\t> File Name: lqr_steer_control.cpp\n\t> Author: TAI Lei\n\t> Mail: ltai@ust.hk\n\t> Created Time: Wed Apr 17 11:48:46 2019\n ************************************************************************/\n\n#include <iostream>\n#include <limits>\n#include <vector>\n#include <opencv2/opencv.hpp>\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <sys/time.h>\n#include <Eigen/Eigen>\n#include \"cubic_spline.h\"\n#include \"motion_model.h\"\n#include \"cpprobotics_types.h\"\n\n#define DT 0.1\n#define L 0.5\n#define KP 1.0\n#define MAX_STEER 45.0/180*M_PI\n\nusing namespace cpprobotics;\n\ncv::Point2i cv_offset(\n    float x, float y, int image_width=2000, int image_height=2000){\n  cv::Point2i output;\n  output.x = int(x * 100) + 300;\n  output.y = image_height - int(y * 100) - image_height/2;\n  return output;\n};\n\nVec_f calc_speed_profile(Vec_f rx, Vec_f ry, Vec_f ryaw, float target_speed){\n\tVec_f speed_profile(ryaw.size(), target_speed);\n\n\tfloat direction = 1.0;\n\tfor(unsigned int i=0; i < ryaw.size()-1; i++){\n\t\tfloat dyaw = std::abs(ryaw[i+1] - ryaw[i]);\n\t\tfloat switch_point = (M_PI/4.0< dyaw) && (dyaw<M_PI/2.0);\n\n\t\tif (switch_point) direction = direction * -1;\n\t\tif (direction != 1.0) speed_profile[i]= target_speed * -1;\n\t\telse speed_profile[i]= target_speed;\n\n\t\tif (switch_point) speed_profile[i] = 0.0;\n\t}\n\n\tspeed_profile[speed_profile.size()-1] = 0.0;\n\treturn speed_profile;\n};\n\n\nfloat calc_nearest_index(State state, Vec_f cx, Vec_f cy, Vec_f cyaw, int &ind){\n\tfloat mind = std::numeric_limits<float>::max();\n\tfor(unsigned int i=0; i<cx.size(); i++){\n\t\tfloat idx = cx[i] - state.x; \n\t\tfloat idy = cy[i] - state.y; \n\t\tfloat d_e = idx*idx + idy*idy;\n\n\t\tif (d_e<mind){\n\t\t\tmind = d_e;\n\t\t\tind = i;\n\t\t}\n\t}\n\tfloat dxl = cx[ind] - state.x;\n\tfloat dyl = cy[ind] - state.y;\n\tfloat angle = YAW_P2P(cyaw[ind] - std::atan2(dyl, dxl));\n\tif (angle < 0) mind = mind * -1;\n\n\treturn mind;\n};\n\nEigen::Matrix4f solve_DARE(Eigen::Matrix4f A, Eigen::Vector4f B, Eigen::Matrix4f Q, float R){\n\tEigen::Matrix4f X = Q;\n\tint maxiter = 150;\n\tfloat eps = 0.01;\n\n\tfor(int i=0; i<maxiter; i++){\n\t\tEigen::Matrix4f Xn = A.transpose()*X*A-A.transpose()*X*B/(R+B.transpose()*X*B) * B.transpose()*X*A+Q;\n\t\tEigen::Matrix4f error = Xn - X;\n\t\tif (error.cwiseAbs().maxCoeff()<eps){\n\t\t\treturn Xn;\n\t\t}\n\t\tX = Xn;\n\t}\n\n\treturn X;\n};\n\nEigen::RowVector4f dlqr(Eigen::Matrix4f A, Eigen::Vector4f B, Eigen::Matrix4f Q, float R){\n\tEigen::Matrix4f X = solve_DARE(A, B ,Q, R);\n\tEigen::RowVector4f K = 1.0/(B.transpose()*X*B + R) * (B.transpose()*X*A);\n\treturn K;\t\n};\n\nfloat lqr_steering_control(State state, Vec_f cx, Vec_f cy, Vec_f cyaw, Vec_f ck, int& ind, float& pe, float& pth_e){\n\tfloat e = calc_nearest_index(state, cx, cy, cyaw, ind);\n\n\tfloat k = ck[ind];\n\tfloat th_e = YAW_P2P(state.yaw - cyaw[ind]);\n\n\tEigen::Matrix4f A = Eigen::Matrix4f::Zero();\n\tA(0, 0) = 1.0;\n\tA(0 ,1) = DT;\n\tA(1 ,2) = state.v;\n\tA(2 ,2) = 1.0;\n\tA(2 ,3) = DT;\n\n\tEigen::Vector4f B = Eigen::Vector4f::Zero();\n\tB(3) = state.v/L;\n\n\tEigen::Matrix4f Q = Eigen::Matrix4f::Identity();\n\tfloat R = 1;\n\n\t// gain of lqr\n\tEigen::RowVector4f K = dlqr(A, B, Q, R);\n\t\n\tEigen::Vector4f x = Eigen::Vector4f::Zero();\n\tx(0) = e;\n\tx(1) = (e-pe)/DT;\n\tx(2) = th_e;\n\tx(3) = (th_e-pth_e)/DT;\n\n\tfloat ff = std::atan2((L*k), (double)1.0);\n\tfloat fb = YAW_P2P((-K * x)(0));\n\tfloat delta = ff+fb;\n\n\tpe = e;\n\tpth_e = th_e;\n\treturn delta; \n};\n\n\nvoid update (State& state, float a, float delta){\n\n    if (delta >= MAX_STEER) delta = MAX_STEER;\n    if (delta <= - MAX_STEER) delta = - MAX_STEER;\n\n    state.x = state.x + state.v * std::cos(state.yaw) * DT;\n    state.y = state.y + state.v * std::sin(state.yaw) * DT;\n    state.yaw = state.yaw + state.v / L * std::tan(delta) * DT;\n    state.v = state.v + a * DT;\n\n};\n\nvoid closed_loop_prediction(Vec_f cx, Vec_f cy, Vec_f cyaw, Vec_f ck, Vec_f speed_profile, Poi_f goal){\n\tfloat T = 500.0;\n\tfloat goal_dis = 0.5;\n\tfloat stop_speed = 0.05;\n\n\tState state(-0.0, -0.0, 0.0, 0.0);\n\n\tfloat time_ = 0.0;\n\tVec_f x;\n\tx.push_back(state.x);\n\tVec_f y;\n\ty.push_back(state.y);\n\tVec_f yaw;\n\tyaw.push_back(state.yaw);\n\tVec_f v;\n\tv.push_back(state.v);\n\tVec_f t;\n\tt.push_back(0.0);\n\n\tfloat e = 0;\n\tfloat e_th = 0;\n\tint ind = 0;\n\n\n  cv::namedWindow(\"lqr\", cv::WINDOW_NORMAL);\n  int count = 0;\n\n\n\tcv::Mat bg(2000, 2000, CV_8UC3, cv::Scalar(255, 255, 255));\n\tfor(unsigned int i=1; i<cx.size(); i++){\n\t\tcv::line(\n\t\t\tbg,\n\t\t\tcv_offset(cx[i-1], cy[i-1], bg.cols, bg.rows),\n\t\t\tcv_offset(cx[i], cy[i], bg.cols, bg.rows),\n\t\t\tcv::Scalar(0, 0, 0),\n\t\t\t10);\n\t}\n\n\twhile (T >= time_){\n\t\tfloat di = lqr_steering_control(state, cx, cy, cyaw, ck, ind, e, e_th);\n\t\tfloat ai = KP * (speed_profile[ind]-state.v);\n\t  update(state, ai, di);\n\n\t\tif (std::abs(state.v) <= stop_speed) ind += 1;\n\n\t\tfloat dx = state.x - goal[0];\n\t\tfloat dy = state.y - goal[1];\n\t\tif (std::sqrt(dx*dx + dy*dy) <= goal_dis) {\n\t\t\tstd::cout<<(\"Goal\")<<std::endl;\n\t\t\tbreak;\n\t\t}\n\n\t\tcv::circle(\n\t\t\tbg,\n\t\t\tcv_offset(state.x, state.y, bg.cols, bg.rows),\n\t\t\t10, cv::Scalar(0, 0, 255), -1);\n\n\t\t//save image in build/bin/pngs\n\t\t// struct timeval tp;\n\t\t// gettimeofday(&tp, NULL);\n\t\t// long int ms = tp.tv_sec * 1000 + tp.tv_usec / 1000;\n\t\t// std::string int_count = std::to_string(ms);\n\t\t// cv::imwrite(\"./pngs/\"+int_count+\".png\", bg);\n\t\tcv::imshow(\"lqr\", bg);\n\t\tcv::waitKey(5);\n\t}\n};\n\nint main(){\n\tVec_f wx({0.0, 6.0,  12.5, 10.0, 7.5, 3.0, -1.0});\n\tVec_f wy({0.0, -3.0, -5.0,  6.5, 3.0, 5.0, -2.0});\n\n  Spline2D csp_obj(wx, wy);\n\tVec_f r_x;\n\tVec_f r_y;\n\tVec_f ryaw;\n\tVec_f rcurvature;\n\tVec_f rs;\n\tfor(float i=0; i<csp_obj.s.back(); i+=0.1){\n\t\tstd::array<float, 2> point_ = csp_obj.calc_postion(i);\n\t\tr_x.push_back(point_[0]);\n\t\tr_y.push_back(point_[1]);\n\t\tryaw.push_back(csp_obj.calc_yaw(i));\n\t\trcurvature.push_back(csp_obj.calc_curvature(i));\n\t\trs.push_back(i);\n\t}\n\tfloat target_speed = 10.0 / 3.6;\n\tVec_f speed_profile = calc_speed_profile(r_x, r_y, ryaw, target_speed);\n\tclosed_loop_prediction(r_x, r_y, ryaw, rcurvature, speed_profile, {{wx.back(), wy.back()}});\n\n}", "meta": {"hexsha": "8b1f1632d1854e604784d12c9807f19dd47c46f3", "size": 6027, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/lqr_steer_control.cpp", "max_stars_repo_name": "Singh-sid930/CppRobotics", "max_stars_repo_head_hexsha": "0e4ced2cf1c927156cd3745dee2b2e7250ce95d7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-06-27T07:09:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-17T07:54:34.000Z", "max_issues_repo_path": "src/lqr_steer_control.cpp", "max_issues_repo_name": "sweetquiet/CppRobotics", "max_issues_repo_head_hexsha": "c5a8cc9a958ee64ab80b9726dc70a3c11f499bd0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lqr_steer_control.cpp", "max_forks_repo_name": "sweetquiet/CppRobotics", "max_forks_repo_head_hexsha": "c5a8cc9a958ee64ab80b9726dc70a3c11f499bd0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-11T13:53:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-11T13:53:59.000Z", "avg_line_length": 25.3235294118, "max_line_length": 117, "alphanum_fraction": 0.612742658, "num_tokens": 2148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4983982081233217}}
{"text": "#define PY_ARRAY_UNIQUE_SYMBOL phist_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\n\n#include <vigra/numpy_array.hxx>\n#include <vigra/numpy_array_converters.hxx>\n\n#include \"seglib/histogram/histogram.hxx\"\n#include \"seglib/histogram/histogram_python.hxx\"\n\n\nnamespace python = boost::python;\n\nnamespace histogram {\n\n\n\n\n    vigra::NumpyAnyArray jointColorHistogram(\n\n        vigra::NumpyArray<2,  vigra::TinyVector<float,3>  >    img,\n        const vigra::TinyVector<float, 3> &                    min,\n        const vigra::TinyVector<float, 3> &                    max,\n        const vigra::TinyVector<float, 3> &                    bins,\n        const size_t                                           r,\n        //output\n        vigra::NumpyArray<5, float >                           res = vigra::NumpyArray<5, float >()\n\n\n    ){\n\n        // allocate output\n        typedef typename vigra::NumpyArray<5, float >::difference_type Shape5;\n        Shape5 shape(img.shape(0),img.shape(1),int(bins[0]),int(bins[1]),int(bins[2]));\n        res.reshapeIfEmpty(shape);\n        std::fill(res.begin(),res.end(),0.0);\n        // \n        Shape5 histCoord;\n        const vigra::TinyVector<uint,  3>  ones(1,1,1);\n        const vigra::TinyVector<float, 2>  radius(r,r);\n        const vigra::TinyVector<float, 2>  radius1(r+1,r+1);\n        const vigra::TinyVector<float, 3>  fac = ( (bins-ones) / (max-min) );\n\n\n        vigra::TinyVector<int,2>  start,end,c;\n\n        for(histCoord[0]=0;histCoord[0]<img.shape(0);++histCoord[0])\n        for(histCoord[1]=0;histCoord[1]<img.shape(1);++histCoord[1]){\n\n\n            for(int d=0;d<2;++d){\n                start[d]   = std::max(int(0),            int(histCoord[d]) - int(r));\n                end[d]     = std::min(int(img.shape(d)), int(histCoord[d] + (r+1) )); \n            }\n\n\n            for(c[0]=start[0];c[0]<end[0];++c[0])\n            for(c[1]=start[1];c[1]<end[1];++c[1]){\n\n                \n                // get the pixel value at c\n                vigra::TinyVector<float, 3>  pixelValue = img(c[0],c[1]);\n                pixelValue -= min;\n                pixelValue *= fac;\n\n                // (the first two coordinates of hist coord are filled)\n                histCoord[2]=int(pixelValue[0]);\n                histCoord[3]=int(pixelValue[1]);\n                histCoord[4]=int(pixelValue[2]);\n\n\n                PHIST_ASSERT_OP(histCoord[0],<,img.shape(0));\n                PHIST_ASSERT_OP(histCoord[1],<,img.shape(1));\n\n                PHIST_ASSERT_OP(histCoord[2],<,bins[0]);\n                PHIST_ASSERT_OP(histCoord[3],<,bins[1]);\n                PHIST_ASSERT_OP(histCoord[4],<,bins[2]);\n\n                // increment counter\n                res(histCoord[0],histCoord[1],histCoord[2],histCoord[3],histCoord[4])+=1.0;\n            }   \n        }   \n\n        // normalizes\n        for(histCoord[0]=0;histCoord[0]<img.shape(0);++histCoord[0])\n        for(histCoord[1]=0;histCoord[1]<img.shape(1);++histCoord[1]){\n\n            float sum=0;\n\n            for(histCoord[2]=0;histCoord[2]<res.shape(2);++histCoord[2])\n            for(histCoord[3]=0;histCoord[3]<res.shape(3);++histCoord[3])\n            for(histCoord[4]=0;histCoord[4]<res.shape(4);++histCoord[4]){\n\n                sum+=res(histCoord[0],histCoord[1],histCoord[2],histCoord[3],histCoord[4]);\n            }\n            for(histCoord[2]=0;histCoord[2]<res.shape(2);++histCoord[2])\n            for(histCoord[3]=0;histCoord[3]<res.shape(3);++histCoord[3])\n            for(histCoord[4]=0;histCoord[4]<res.shape(4);++histCoord[4]){\n\n                res(histCoord[0],histCoord[1],histCoord[2],histCoord[3],histCoord[4])/=sum;\n            }\n        }\n\n\n\n        return res;\n    }\n\n\n\n    vigra::NumpyAnyArray batchHistogram(\n        vigra::NumpyArray<3, vigra::Multiband<float>  >   img,\n        vigra::NumpyArray<1, float  >   min,\n        vigra::NumpyArray<1, float  >   max,\n        const size_t                    bins,\n        const size_t                    r,\n        //output\n        vigra::NumpyArray<4, float >    res = vigra::NumpyArray<4, float >()\n    ){ \n        const size_t nChannels=img.shape(2);\n        // allocate output\n        typedef typename vigra::NumpyArray<4, float >::difference_type Shape4;\n        Shape4 shape(img.shape(0),img.shape(1),nChannels,bins);\n        res.reshapeIfEmpty(shape);\n        std::fill(res.begin(),res.end(),0.0);\n\n\n        // coordinate in the res array (pixel wise histogram)\n        // (x,y,c,bin)\n        Shape4 histCoord;\n        const vigra::TinyVector<float, 2>  radius1(r+1,r+1);\n        // channel wise factor\n        std::vector<float> fac(nChannels);\n        for(size_t channel=0;channel<nChannels;++channel){\n            fac[channel]= float(bins-1) / (max(channel)-min(channel)); \n        }\n\n\n        vigra::TinyVector<int,2>  start,end,c;\n\n        for(histCoord[0]=0;histCoord[0]<img.shape(0);++histCoord[0])\n        for(histCoord[1]=0;histCoord[1]<img.shape(1);++histCoord[1]){\n\n\n            for(int d=0;d<2;++d){\n                start[d]   = std::max(int(0),            int(histCoord[d]) - int(r));\n                end[d]     = std::min(int(img.shape(d)), int(histCoord[d] + (r+1) )); \n            }\n\n\n            for(c[0]=start[0];c[0]<end[0];++c[0])\n            for(c[1]=start[1];c[1]<end[1];++c[1]){\n\n                // iterate over all channels\n                for(histCoord[2]=0;histCoord[2]<nChannels;++histCoord[2] ){\n\n                    const float value = img(c[0],c[1],histCoord[2]);\n\n                   \n\n\n                    histCoord[3] = static_cast<int>((value - min(histCoord[2]) )*fac[histCoord[2]]);\n\n                    /*\n                    std::cout<<\"\\n\\n\u201d channel \"<<histCoord[2]<<\"\\n\";\n                    std::cout<<\"value \"<< value<<\"\\n\";\n                    std::cout<<\"mi \" << min(histCoord[2])<<\"\\n\";\n                    std::cout<<\"ma \" << max(histCoord[2])<<\"\\n\";\n                    std::cout<<\"fa \" << fac[histCoord[2]]<<\"\\n\";\n                    */\n\n                    PHIST_ASSERT_OP(histCoord[3],<,bins);\n                    // increment hist\n                    res(histCoord[0],histCoord[1],histCoord[2],histCoord[3])+=1.0;\n                }\n            }\n        }\n\n        // normalize\n\n        for(histCoord[0]=0;histCoord[0]<img.shape(0);++histCoord[0])\n        for(histCoord[1]=0;histCoord[1]<img.shape(1);++histCoord[1])\n        for(histCoord[2]=0;histCoord[2]<img.shape(2);++histCoord[2]){\n\n            float sum=0.0;\n            for(histCoord[3]=0;histCoord[3]<bins;++histCoord[3]){\n                sum+=res(histCoord[0],histCoord[1],histCoord[2],histCoord[3]);\n            }\n            for(histCoord[3]=0;histCoord[3]<bins;++histCoord[3]){\n                res(histCoord[0],histCoord[1],histCoord[2],histCoord[3])/=sum;\n            }\n        }\n        return res;\n    }\n\n\n    /*\n\n    vigra::NumpyAnyArray labelMaskedHistogram(\n        // input data (for example an rgb image with xyc order)\n        vigra::NumpyArray<3, vigra::Multiband<float>  >         img,\n        // input labeling for which are used as mask images\n        vigra::NumpyArray<3, vigra::Multiband<vigra::UInt64> >  labelings,\n        vigra::NumpyArray<1, UInt64>                            numberOfLabels,\n        vigra::NumpyArray<1, float>                             weights\n    ){\n\n        const size_t numberOfInputLabelings = labelings.shape(2);\n        \n    }\n    */\n\n\n    void export_histogram(){\n\n        python::def(\"_jointColorHistogram_\",vigra::registerConverters(&jointColorHistogram),\n            (\n                python::arg(\"img\"),\n                python::arg(\"dmin\"),\n                python::arg(\"dmax\"),\n                python::arg(\"bins\"),\n                python::arg(\"r\"),\n                python::arg(\"out\")=python::object()\n            )\n        );\n\n        python::def(\"_batchHistogram_\",vigra::registerConverters(&batchHistogram),\n            (\n                python::arg(\"img\"),\n                python::arg(\"dmin\"),\n                python::arg(\"dmax\"),\n                python::arg(\"bins\"),\n                python::arg(\"r\"),\n                python::arg(\"out\")=python::object()\n            )\n        );\n\n    }\n\n}", "meta": {"hexsha": "7bb18c1d689668ebf2d99fa8e94f04d6fb3a3297", "size": 8237, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/python/histogram/py_histogram.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/histogram/py_histogram.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/histogram/py_histogram.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": 33.0803212851, "max_line_length": 100, "alphanum_fraction": 0.5108656064, "num_tokens": 2252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4983982081233217}}
{"text": "#include <boost/random/cauchy_distribution.hpp>\n", "meta": {"hexsha": "b8c3677a8213310c6f0eaf93a348db60157c2604", "size": 48, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_random_cauchy_distribution.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_random_cauchy_distribution.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_random_cauchy_distribution.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 24.0, "max_line_length": 47, "alphanum_fraction": 0.8333333333, "num_tokens": 10, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919830720203, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4983981962816964}}
{"text": "/*\n * Copyright Nick Thompson, 2020\n * Use, modification and distribution are subject to the\n * Boost Software License, Version 1.0. (See accompanying file\n * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#include \"math_unit_test.hpp\"\n#include <numeric>\n#include <utility>\n#include <array>\n#include <boost/random/uniform_real.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/math/interpolators/septic_hermite.hpp>\n#include <boost/math/special_functions/next.hpp>\n#ifdef BOOST_HAS_FLOAT128\n#include <boost/multiprecision/float128.hpp>\nusing boost::multiprecision::float128;\n#endif\n\n\nusing boost::math::interpolators::septic_hermite;\nusing boost::math::interpolators::cardinal_septic_hermite;\nusing boost::math::interpolators::cardinal_septic_hermite_aos;\n\ntemplate<typename Real>\nvoid test_constant()\n{\n\n    std::vector<Real> x{0,1,2,3, 9, 22, 81};\n    std::vector<Real> y(x.size());\n    std::vector<Real> dydx(x.size(), 0);\n    std::vector<Real> d2ydx2(x.size(), 0);\n    std::vector<Real> d3ydx3(x.size(), 0);\n    for (auto & t : y)\n    {\n        t = 7;\n    }\n\n    auto sh = septic_hermite(std::move(x), std::move(y), std::move(dydx), std::move(d2ydx2), std::move(d3ydx3));\n\n    for (Real t = 0; t <= 81; t += 0.25)\n    {\n        CHECK_ULP_CLOSE(Real(7), sh(t), 24);\n        CHECK_ULP_CLOSE(Real(0), sh.prime(t), 24);\n    }\n\n    Real x0 = 0;\n    Real dx = 1;\n    y.resize(128, 7);\n    dydx.resize(128, 0);\n    d2ydx2.resize(128, 0);\n    d3ydx3.resize(128, 0);\n    auto csh = cardinal_septic_hermite(std::move(y), std::move(dydx), std::move(d2ydx2), std::move(d3ydx3), x0, dx);\n    for (Real t = x0; t <= 127; t += 0.25)\n    {\n        CHECK_ULP_CLOSE(Real(7), csh(t), 24);\n        CHECK_ULP_CLOSE(Real(0), csh.prime(t), 24);\n        CHECK_ULP_CLOSE(Real(0), csh.double_prime(t), 24);\n    }\n\n    std::vector<std::array<Real, 4>> data(128);\n    for (size_t i = 0; i < data.size(); ++i)\n    {\n        data[i][0] = 7;\n        data[i][1] = 0;\n        data[i][2] = 0;\n        data[i][3] = 0;\n    }\n    auto csh_aos = cardinal_septic_hermite_aos(std::move(data), x0, dx);\n    for (Real t = x0; t <= 127; t += 0.25)\n    {\n        CHECK_ULP_CLOSE(Real(7), csh_aos(t), 24);\n        CHECK_ULP_CLOSE(Real(0), csh_aos.prime(t), 24);\n        CHECK_ULP_CLOSE(Real(0), csh_aos.double_prime(t), 24);\n    }\n\n    // Now check the boundaries:\n    auto [tlo, thi] = csh.domain();\n    int samples = 5000;\n    int i = 0;\n    while (i++ < samples)\n    {\n        CHECK_ULP_CLOSE(Real(7), csh(tlo), 2);\n        CHECK_ULP_CLOSE(Real(7), csh(thi), 2);\n        CHECK_ULP_CLOSE(Real(7), csh_aos(tlo), 2);\n        CHECK_ULP_CLOSE(Real(7), csh_aos(thi), 2);\n        CHECK_ULP_CLOSE(Real(0), csh.prime(tlo), 2);\n        CHECK_ULP_CLOSE(Real(0), csh.prime(thi), 2);\n        CHECK_ULP_CLOSE(Real(0), csh_aos.prime(tlo), 2);\n        CHECK_ULP_CLOSE(Real(0), csh_aos.prime(thi), 2);\n        CHECK_ULP_CLOSE(Real(0), csh.double_prime(tlo), 2);\n        CHECK_ULP_CLOSE(Real(0), csh.double_prime(thi), 2);\n        CHECK_ULP_CLOSE(Real(0), csh_aos.double_prime(tlo), 2);\n        CHECK_ULP_CLOSE(Real(0), csh_aos.double_prime(thi), 2);\n\n        tlo = boost::math::nextafter(tlo, std::numeric_limits<Real>::max());\n        thi = boost::math::nextafter(thi, std::numeric_limits<Real>::lowest());\n    }\n\n}\n\n\ntemplate<typename Real>\nvoid test_linear()\n{\n    std::vector<Real> x{0,1,2,3,4,5,6,7,8,9};\n    std::vector<Real> y = x;\n    std::vector<Real> dydx(x.size(), 1);\n    std::vector<Real> d2ydx2(x.size(), 0);\n    std::vector<Real> d3ydx3(x.size(), 0);\n\n    auto sh = septic_hermite(std::move(x), std::move(y), std::move(dydx), std::move(d2ydx2), std::move(d3ydx3));\n\n    for (Real t = 0; t <= 9; t += 0.25)\n    {\n        CHECK_ULP_CLOSE(Real(t), sh(t), 2);\n        CHECK_ULP_CLOSE(Real(1), sh.prime(t), 2);\n    }\n\n    boost::random::mt19937 rng;\n    boost::random::uniform_real_distribution<Real> dis(0.5,1);\n    x.resize(512);\n    x[0] = dis(rng);\n    Real xmin = x[0];\n    for (size_t i = 1; i < x.size(); ++i)\n    {\n        x[i] = x[i-1] + dis(rng);\n    }\n    Real xmax = x.back();\n\n    y = x;\n    dydx.resize(x.size(), 1);\n    d2ydx2.resize(x.size(), 0);\n    d3ydx3.resize(x.size(), 0);\n\n    sh = septic_hermite(std::move(x), std::move(y), std::move(dydx), std::move(d2ydx2), std::move(d3ydx3));\n\n    for (Real t = xmin; t <= xmax; t += 0.125)\n    {\n        CHECK_ULP_CLOSE(t, sh(t), 25);\n        CHECK_ULP_CLOSE(Real(1), sh.prime(t), 850);\n    }\n\n    Real x0 = 0;\n    Real dx = 1;\n    y.resize(10);\n    dydx.resize(10, 1);\n    d2ydx2.resize(10, 0);\n    d3ydx3.resize(10, 0);\n    for (size_t i = 0; i < y.size(); ++i)\n    {\n        y[i] = i;\n    }\n    auto csh = cardinal_septic_hermite(std::move(y), std::move(dydx), std::move(d2ydx2), std::move(d3ydx3), x0, dx);\n    for (Real t = 0; t <= 9; t += 0.125)\n    {\n        CHECK_ULP_CLOSE(t, csh(t), 15);\n        CHECK_ULP_CLOSE(Real(1), csh.prime(t), 15);\n        CHECK_ULP_CLOSE(Real(0), csh.double_prime(t), 15);\n    }\n\n    std::vector<std::array<Real, 4>> data(10);\n    for (size_t i = 0; i < data.size(); ++i)\n    {\n        data[i][0] = i;\n        data[i][1] = 1;\n        data[i][2] = 0;\n        data[i][3] = 0;\n    }\n    auto csh_aos = cardinal_septic_hermite_aos(std::move(data), x0, dx);\n    for (Real t = 0; t <= 9; t += 0.125)\n    {\n        CHECK_ULP_CLOSE(t, csh_aos(t), 15);\n        CHECK_ULP_CLOSE(Real(1), csh_aos.prime(t), 15);\n        CHECK_ULP_CLOSE(Real(0), csh_aos.double_prime(t), 15);\n    }\n\n    // Now check the boundaries:\n    auto [tlo, thi] = csh.domain();\n    int samples = 5000;\n    int i = 0;\n    while (i++ < samples)\n    {\n        CHECK_ULP_CLOSE(Real(tlo), csh(tlo), 2);\n        CHECK_ULP_CLOSE(Real(thi), csh(thi), 8);\n        CHECK_ULP_CLOSE(Real(tlo), csh_aos(tlo), 2);\n        CHECK_ULP_CLOSE(Real(thi), csh_aos(thi), 8);\n        CHECK_ULP_CLOSE(Real(1), csh.prime(tlo), 2);\n        CHECK_ULP_CLOSE(Real(1), csh.prime(thi), 700);\n        CHECK_ULP_CLOSE(Real(1), csh_aos.prime(tlo), 2);\n        CHECK_ULP_CLOSE(Real(1), csh_aos.prime(thi), 700);\n        CHECK_MOLLIFIED_CLOSE(Real(0), csh.double_prime(tlo), std::numeric_limits<Real>::epsilon());\n        CHECK_MOLLIFIED_CLOSE(Real(0), csh.double_prime(thi), 1200*std::numeric_limits<Real>::epsilon());\n        CHECK_MOLLIFIED_CLOSE(Real(0), csh_aos.double_prime(tlo), std::numeric_limits<Real>::epsilon());\n        CHECK_MOLLIFIED_CLOSE(Real(0), csh_aos.double_prime(thi), 1200*std::numeric_limits<Real>::epsilon());\n\n        tlo = boost::math::nextafter(tlo, std::numeric_limits<Real>::max());\n        thi = boost::math::nextafter(thi, std::numeric_limits<Real>::lowest());\n    }\n\n}\n\ntemplate<typename Real>\nvoid test_quadratic()\n{\n    std::vector<Real> x{0,1,2,3,4,5,6,7,8,9};\n    std::vector<Real> y(x.size());\n    for (size_t i = 0; i < y.size(); ++i)\n    {\n        y[i] = x[i]*x[i]/2;\n    }\n\n    std::vector<Real> dydx(x.size());\n    for (size_t i = 0; i < y.size(); ++i)\n    {\n        dydx[i] = x[i];\n    }\n\n    std::vector<Real> d2ydx2(x.size(), 1);\n    std::vector<Real> d3ydx3(x.size(), 0);\n\n    auto sh = septic_hermite(std::move(x), std::move(y), std::move(dydx), std::move(d2ydx2), std::move(d3ydx3));\n\n    for (Real t = 0; t <= 9; t += 0.0078125)\n    {\n        CHECK_ULP_CLOSE(t*t/2, sh(t), 100);\n        CHECK_ULP_CLOSE(t, sh.prime(t), 32);\n    }\n\n    boost::random::mt19937 rng;\n    boost::random::uniform_real_distribution<Real> dis(0.5,1);\n    x.resize(8);\n    x[0] = dis(rng);\n    Real xmin = x[0];\n    for (size_t i = 1; i < x.size(); ++i)\n    {\n        x[i] = x[i-1] + dis(rng);\n    }\n    Real xmax = x.back();\n\n    y.resize(x.size());\n    for (size_t i = 0; i < y.size(); ++i)\n    {\n        y[i] = x[i]*x[i]/2;\n    }\n\n    dydx.resize(x.size());\n    for (size_t i = 0; i < y.size(); ++i)\n    {\n        dydx[i] = x[i];\n    }\n\n    d2ydx2.resize(x.size(), 1);\n    d3ydx3.resize(x.size(), 0); \n\n    sh = septic_hermite(std::move(x), std::move(y), std::move(dydx), std::move(d2ydx2), std::move(d3ydx3));\n\n    for (Real t = xmin; t <= xmax; t += 0.125)\n    {\n        CHECK_ULP_CLOSE(t*t/2, sh(t), 50);\n        CHECK_ULP_CLOSE(t, sh.prime(t), 300);\n    }\n\n    y.resize(10);\n    for (size_t i = 0; i < y.size(); ++i)\n    {\n        y[i] = i*i/Real(2);\n    }\n\n    dydx.resize(y.size());\n    for (size_t i = 0; i < y.size(); ++i)\n    {\n        dydx[i] = i;\n    }\n\n    d2ydx2.resize(y.size(), 1);\n    d3ydx3.resize(y.size(), 0);\n\n    Real x0 = 0;\n    Real dx = 1;\n    auto csh = cardinal_septic_hermite(std::move(y), std::move(dydx), std::move(d2ydx2), std::move(d3ydx3), x0, dx);\n    for (Real t = x0; t <= 9; t += 0.125)\n    {\n        CHECK_ULP_CLOSE(t*t/2, csh(t), 24);\n        CHECK_ULP_CLOSE(t, csh.prime(t), 24);\n        CHECK_ULP_CLOSE(Real(1), csh.double_prime(t), 24);\n    }\n\n    std::vector<std::array<Real, 4>> data(10);\n    for (size_t i = 0; i < data.size(); ++i)\n    {\n        data[i][0] = i*i/Real(2);\n        data[i][1] = i;\n        data[i][2] = 1;\n        data[i][3] = 0;\n    }\n    auto csh_aos = cardinal_septic_hermite_aos(std::move(data), x0, dx);\n    for (Real t = x0; t <= 9; t += 0.125)\n    {\n        CHECK_ULP_CLOSE(t*t/2, csh_aos(t), 24);\n        CHECK_ULP_CLOSE(t, csh_aos.prime(t), 24);\n        CHECK_ULP_CLOSE(Real(1), csh_aos.double_prime(t), 24);\n    }\n}\n\n\n\ntemplate<typename Real>\nvoid test_cubic()\n{\n\n    std::vector<Real> x{0,1,2,3,4,5,6,7};\n    Real xmax = x.back();\n    std::vector<Real> y(x.size());\n    for (size_t i = 0; i < y.size(); ++i)\n    {\n        y[i] = x[i]*x[i]*x[i];\n    }\n\n    std::vector<Real> dydx(x.size());\n    for (size_t i = 0; i < y.size(); ++i)\n    {\n        dydx[i] = 3*x[i]*x[i];\n    }\n\n    std::vector<Real> d2ydx2(x.size());\n    for (size_t i = 0; i < y.size(); ++i)\n    {\n        d2ydx2[i] = 6*x[i];\n    }\n    std::vector<Real> d3ydx3(x.size(), 6);\n\n    auto sh = septic_hermite(std::move(x), std::move(y), std::move(dydx), std::move(d2ydx2), std::move(d3ydx3));\n\n    for (Real t = 0; t <= xmax; t += 0.0078125)\n    {\n        CHECK_ULP_CLOSE(t*t*t, sh(t), 151);\n        CHECK_ULP_CLOSE(3*t*t, sh.prime(t), 151);\n    }\n\n    Real x0 = 0;\n    Real dx = 1;\n    y.resize(8);\n    dydx.resize(8);\n    d2ydx2.resize(8);\n    d3ydx3.resize(8,6);\n    for (size_t i = 0; i < y.size(); ++i)\n    {\n        y[i] = i*i*i;\n        dydx[i] = 3*i*i;\n        d2ydx2[i] = 6*i;\n    }\n\n    auto csh = cardinal_septic_hermite(std::move(y), std::move(dydx), std::move(d2ydx2), std::move(d3ydx3), x0, dx);\n\n    for (Real t = 0; t <= xmax; t += 0.0078125)\n    {\n        CHECK_ULP_CLOSE(t*t*t, csh(t), 151);\n        CHECK_ULP_CLOSE(3*t*t, csh.prime(t), 151);\n        CHECK_ULP_CLOSE(6*t, csh.double_prime(t), 151);\n    }\n\n    std::vector<std::array<Real, 4>> data(8);\n    for (size_t i = 0; i < data.size(); ++i) {\n        data[i][0] = i*i*i;\n        data[i][1] = 3*i*i;\n        data[i][2] = 6*i;\n        data[i][3] = 6;\n    }\n\n    auto csh_aos = cardinal_septic_hermite_aos(std::move(data), x0, dx);\n\n    for (Real t = 0; t <= xmax; t += 0.0078125)\n    {\n        CHECK_ULP_CLOSE(t*t*t, csh_aos(t), 151);\n        CHECK_ULP_CLOSE(3*t*t, csh_aos.prime(t), 151);\n        CHECK_ULP_CLOSE(6*t, csh_aos.double_prime(t), 151);\n    }\n}\n\ntemplate<typename Real>\nvoid test_quartic()\n{\n\n    std::vector<Real> x{0,1,2,3,4,5,6,7,8,9};\n    Real xmax = x.back();\n    std::vector<Real> y(x.size());\n    for (size_t i = 0; i < y.size(); ++i)\n    {\n        y[i] = x[i]*x[i]*x[i]*x[i];\n    }\n\n    std::vector<Real> dydx(x.size());\n    for (size_t i = 0; i < y.size(); ++i)\n    {\n        dydx[i] = 4*x[i]*x[i]*x[i];\n    }\n\n    std::vector<Real> d2ydx2(x.size());\n    for (size_t i = 0; i < y.size(); ++i)\n    {\n        d2ydx2[i] = 12*x[i]*x[i];\n    }\n\n    std::vector<Real> d3ydx3(x.size());\n    for (size_t i = 0; i < y.size(); ++i)\n    {\n        d3ydx3[i] = 24*x[i];\n    }\n\n    auto sh = septic_hermite(std::move(x), std::move(y), std::move(dydx), std::move(d2ydx2), std::move(d3ydx3));\n\n    for (Real t = 1; t <= xmax; t += 0.0078125) {\n        CHECK_ULP_CLOSE(t*t*t*t, sh(t), 117);\n        CHECK_ULP_CLOSE(4*t*t*t, sh.prime(t), 117);\n    }\n\n    y.resize(10);\n    dydx.resize(10);\n    d2ydx2.resize(10);\n    d3ydx3.resize(10);\n    for (size_t i = 0; i < y.size(); ++i)\n    {\n        y[i] = i*i*i*i;\n        dydx[i] = 4*i*i*i;\n        d2ydx2[i] = 12*i*i;\n        d3ydx3[i] = 24*i;\n    }\n\n    auto csh = cardinal_septic_hermite(std::move(y), std::move(dydx), std::move(d2ydx2), std::move(d3ydx3), Real(0), Real(1));\n\n    for (Real t = 1; t <= xmax; t += 0.0078125)\n    {\n        CHECK_ULP_CLOSE(t*t*t*t, csh(t), 117);\n        CHECK_ULP_CLOSE(4*t*t*t, csh.prime(t), 117);\n        CHECK_ULP_CLOSE(12*t*t, csh.double_prime(t), 117);\n    }\n\n    std::vector<std::array<Real, 4>> data(10);\n    for (size_t i = 0; i < data.size(); ++i)\n    {\n        data[i][0] = i*i*i*i;\n        data[i][1] = 4*i*i*i;\n        data[i][2] = 12*i*i;\n        data[i][3] = 24*i;\n    }\n\n    auto csh_aos = cardinal_septic_hermite_aos(std::move(data), Real(0), Real(1));\n    for (Real t = 1; t <= xmax; t += 0.0078125)\n    {\n        CHECK_ULP_CLOSE(t*t*t*t, csh_aos(t), 117);\n        CHECK_ULP_CLOSE(4*t*t*t, csh_aos.prime(t), 117);\n        CHECK_ULP_CLOSE(12*t*t, csh_aos.double_prime(t), 117);\n    }\n}\n\n\ntemplate<typename Real>\nvoid test_interpolation_condition()\n{\n    for (size_t n = 4; n < 50; ++n) {\n        std::vector<Real> x(n);\n        std::vector<Real> y(n);\n        std::vector<Real> dydx(n);\n        std::vector<Real> d2ydx2(n);\n        std::vector<Real> d3ydx3(n);\n        boost::random::mt19937 rd; \n        boost::random::uniform_real_distribution<Real> dis(0,1);\n        Real x0 = dis(rd);\n        x[0] = x0;\n        y[0] = dis(rd);\n        for (size_t i = 1; i < n; ++i) {\n            x[i] = x[i-1] + dis(rd);\n            y[i] = dis(rd);\n            dydx[i] = dis(rd);\n            d2ydx2[i] = dis(rd);\n            d3ydx3[i] = dis(rd);\n        }\n\n        auto x_copy = x;\n        auto y_copy = y;\n        auto dydx_copy = dydx;\n        auto d2ydx2_copy = d2ydx2;\n        auto d3ydx3_copy = d3ydx3;\n        auto s = septic_hermite(std::move(x_copy), std::move(y_copy), std::move(dydx_copy), std::move(d2ydx2_copy), std::move(d3ydx3_copy));\n\n        for (size_t i = 0; i < x.size(); ++i)\n        {\n            CHECK_ULP_CLOSE(y[i], s(x[i]), 2);\n            CHECK_ULP_CLOSE(dydx[i], s.prime(x[i]), 2);\n        }\n    }\n}\n\n\nint main()\n{\n    test_constant<float>();\n    test_linear<float>();\n    test_quadratic<float>();\n    test_cubic<float>();\n    test_quartic<float>();\n    test_interpolation_condition<float>();\n\n    test_constant<double>();\n    test_linear<double>();\n    test_quadratic<double>();\n    test_cubic<double>();\n    test_quartic<double>();\n    test_interpolation_condition<double>();\n\n    test_constant<long double>();\n    test_linear<long double>();\n    test_quadratic<long double>();\n    test_cubic<long double>();\n    test_quartic<long double>();\n    test_interpolation_condition<long double>();\n\n#ifdef BOOST_HAS_FLOAT128\n    test_constant<float128>();\n    test_linear<float128>();\n    test_quadratic<float128>();\n    test_cubic<float128>();\n    test_quartic<float128>();\n    test_interpolation_condition<float128>();\n#endif\n\n    return boost::math::test::report_errors();\n}\n", "meta": {"hexsha": "cd60acbe2c429bba37ad26db03fc2da298c49dba", "size": 15135, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/math/test/septic_hermite_test.cpp", "max_stars_repo_name": "uosorio/heroku_face", "max_stars_repo_head_hexsha": "7d6465e71dba17a15d8edaef520adb2fcd09d91e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-12T13:52:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-12T13:52:18.000Z", "max_issues_repo_path": "3rdparty/boost_1_73_0/libs/math/test/septic_hermite_test.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-10-21T12:42:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-03T08:41:31.000Z", "max_forks_repo_path": "Libs/boost_1_76_0/libs/math/test/septic_hermite_test.cpp", "max_forks_repo_name": "Antd23rus/S2DE", "max_forks_repo_head_hexsha": "47cc7151c2934cd8f0399a9856c1e54894571553", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-11-03T14:12:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-22T19:20:54.000Z", "avg_line_length": 28.5028248588, "max_line_length": 140, "alphanum_fraction": 0.5503138421, "num_tokens": 5353, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.835483553488848, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.49831008445970304}}
{"text": "// Copyright (c) 2020-2021 Franz Alt\n// This code is licensed under MIT license (see LICENSE.txt for details).\n\n#include <libcvpg/imageproc/algorithms/hog.hpp>\n\n#include <cmath>\n#include <cstdint>\n#include <cstring>\n#include <exception>\n\n#include <boost/asynchronous/algorithm/then.hpp>\n\nnamespace {\n\ntemplate<class image_type>\ncvpg::histogram<double> calc_hog_cell(std::shared_ptr<image_type> image, std::size_t from_x, std::size_t to_x, std::size_t from_y, std::size_t to_y, bool l1_normalilze = true);\n\ntemplate<>\ncvpg::histogram<double> calc_hog_cell(std::shared_ptr<cvpg::image_gray_8bit> image, std::size_t from_x, std::size_t to_x, std::size_t from_y, std::size_t to_y, bool l1_normalize)\n{\n    cvpg::histogram<std::size_t> histogram(9);\n\n    const std::uint8_t * raw = image->data(0).get();\n    const std::size_t image_width = image->width();\n\n    std::int16_t gx = 0;\n    std::int16_t gy = 0;\n    double mag = 0.0;\n    double angle = 0.0;\n\n    // correct from/to-values to calculate the gradients up to the image borders\n    if (from_x > 1)\n    {\n        --from_x;\n    }\n    else\n    {\n        from_x = 1;\n    }\n\n    if (to_x < (image->width() - 2))\n    {\n        ++to_x;\n    }\n    else\n    {\n        to_x = image->width() - 2;\n    }\n\n    if (from_y > 1)\n    {\n        --from_y;\n    }\n    else\n    {\n        from_y = 1;\n    }\n\n    if (to_y < (image->height() - 2))\n    {\n        ++to_y;\n    }\n    else\n    {\n        to_y = image->height() - 2;\n    }\n\n    for (std::size_t y = from_y; y <= to_y; ++y)\n    {\n        for (std::size_t x = from_x; x <= to_x; ++x)\n        {\n            // calculate the x/y gradients\n            gx = static_cast<std::int16_t>(raw[y * image_width + (x + 1)]) - static_cast<std::int16_t>(raw[y * image_width + (x - 1)]);\n            gy = static_cast<std::int16_t>(raw[(y + 1) * image_width + x]) - static_cast<std::int16_t>(raw[(y - 1) * image_width + x]);\n\n            // calculate the gradient magnitude\n            mag = std::sqrt(static_cast<double>(gx * gx + gy * gy));\n\n            // calculate the absolute gradient angle\n            angle = std::fabs((gx == 0) ? 0.0 : atan(static_cast<double>(gy) / static_cast<double>(gx)) * 180.0 / M_PI);\n\n            const std::size_t bin = static_cast<std::size_t>(std::floor(angle / 20.0));\n\n            histogram.at(bin) += static_cast<decltype(histogram)::value_type>(mag);\n        }\n    }\n\n    cvpg::histogram<double> normalized_histogram(9);\n\n    if (l1_normalize)\n    {\n        // normalize histogram (L1 norm)\n        double sum = 0;\n\n        for (auto const & h : histogram)\n        {\n            sum += std::fabs(static_cast<double>(h));\n        }\n\n        for (std::size_t i = 0; i < histogram.bins(); ++i)\n        {\n            normalized_histogram.at(i) = static_cast<double>(histogram.at(i)) / sum;\n        }\n    }\n    else\n    {\n        // normalize histogram (L2 norm)\n        double sum = 0;\n\n        for (auto const & h : histogram)\n        {\n            auto h_ = std::fabs(static_cast<double>(h));\n            sum += h_ * h_;\n        }\n\n        sum = std::sqrt(sum);\n\n        for (std::size_t i = 0; i < histogram.bins(); ++i)\n        {\n            normalized_histogram.at(i) = std::min(1.0, static_cast<double>(histogram.at(i)) / sum);\n        }\n    }\n\n    return normalized_histogram;\n}\n\ntemplate<>\ncvpg::histogram<double> calc_hog_cell(std::shared_ptr<cvpg::image_rgb_8bit> image, std::size_t from_x, std::size_t to_x, std::size_t from_y, std::size_t to_y, bool l1_normalize)\n{\n    // TODO implement me!\n\n    return cvpg::histogram<double>(9);\n}\n\ntemplate<class image_type>\nstruct hog_col_task : public boost::asynchronous::continuation_task<std::vector<cvpg::histogram<double> > >\n{\n    hog_col_task(std::shared_ptr<image_type> image, std::size_t from_x, std::size_t to_x, std::size_t from_y, std::size_t to_y, std::size_t cell_dimension, std::size_t sequential_cells_per_row)\n        : boost::asynchronous::continuation_task<std::vector<cvpg::histogram<double> > >(\"hog_col\")\n        , m_image(image)\n        , m_from_x(from_x)\n        , m_to_x(to_x)\n        , m_from_y(from_y)\n        , m_to_y(to_y)\n        , m_cell_dimension(cell_dimension)\n        , m_sequential_cells_per_row(sequential_cells_per_row)\n    {}\n\n    void operator()()\n    {\n        auto task_res = this->this_task_result();\n\n        const std::size_t cells = (m_to_x - m_from_x + 1) / m_cell_dimension;\n\n        if (cells <= m_sequential_cells_per_row)\n        {\n            std::vector<cvpg::histogram<double> > hogs;\n            hogs.reserve(cells);\n\n            for (std::size_t i = 0; i < cells; ++i)\n            {\n                hogs.push_back(calc_hog_cell(m_image, m_from_x + i * m_cell_dimension, m_from_x + (i + 1) * m_cell_dimension - 1, m_from_y, m_to_y));\n            }\n\n            task_res.set_value(std::move(hogs));\n        }\n        else\n        {\n            // determine middle of x-range dependet on the cell dimension\n            const std::size_t x_half = m_from_x + (cells / 2) * m_cell_dimension;\n\n            boost::asynchronous::create_callback_continuation(\n                [task_res = std::move(task_res)](auto cont_res) mutable\n                {\n                    try\n                    {\n                        auto h = std::move(std::get<1>(cont_res).get());\n\n                        std::vector<cvpg::histogram<double> > hogs(std::move(std::get<0>(cont_res).get()));\n                        hogs.insert(hogs.end(), h.begin(), h.end());\n\n                        task_res.set_value(std::move(hogs));\n                    }\n                    catch (...)\n                    {\n                        task_res.set_exception(std::current_exception());\n                    }\n                },\n                hog_col_task<image_type>(m_image, m_from_x, x_half - 1, m_from_y, m_to_y, m_cell_dimension, m_sequential_cells_per_row),\n                hog_col_task<image_type>(m_image, x_half, m_to_x, m_from_y, m_to_y, m_cell_dimension, m_sequential_cells_per_row)\n            );\n        }\n    }\n\nprivate:\n    std::shared_ptr<image_type> m_image;\n\n    std::size_t m_from_x;\n    std::size_t m_to_x;\n    std::size_t m_from_y;\n    std::size_t m_to_y;\n\n    std::size_t m_cell_dimension;\n\n    std::size_t m_sequential_cells_per_row;\n};\n\ntemplate<class image_type>\nstruct hog_row_task : public boost::asynchronous::continuation_task<std::vector<cvpg::histogram<double> > >\n{\n    hog_row_task(std::shared_ptr<image_type> image, std::size_t from_x, std::size_t to_x, std::size_t from_y, std::size_t to_y, std::size_t cell_dimension, std::size_t sequential_cells_per_row)\n        : boost::asynchronous::continuation_task<std::vector<cvpg::histogram<double> > >(\"hog_row\")\n        , m_image(image)\n        , m_from_x(from_x)\n        , m_to_x(to_x)\n        , m_from_y(from_y)\n        , m_to_y(to_y)\n        , m_cell_dimension(cell_dimension)\n        , m_sequential_cells_per_row(sequential_cells_per_row)\n    {}\n\n    void operator()()\n    {\n        auto task_res = this->this_task_result();\n\n        const std::size_t cells = (m_to_y - m_from_y + 1) / m_cell_dimension;\n\n        if (cells <= 1)\n        {\n            boost::asynchronous::create_callback_continuation(\n                [task_res = std::move(task_res)](auto cont_res) mutable\n                {\n                    try\n                    {\n                        task_res.set_value(std::move(std::get<0>(cont_res).get()));\n                    }\n                    catch (...)\n                    {\n                        task_res.set_exception(std::current_exception());\n                    }\n                },\n                hog_col_task<image_type>(m_image, m_from_x, m_to_x, m_from_y, m_to_y, m_cell_dimension, m_sequential_cells_per_row)\n            );\n        }\n        else\n        {\n            // determine middle of y-range dependet on the cell dimension\n            const std::size_t y_half = m_from_y + (cells / 2) * m_cell_dimension;\n\n            boost::asynchronous::create_callback_continuation(\n                [task_res = std::move(task_res)](auto cont_res) mutable\n                {\n                    try\n                    {\n                        auto h = std::move(std::get<1>(cont_res).get());\n\n                        std::vector<cvpg::histogram<double> > hogs(std::move(std::get<0>(cont_res).get()));\n                        hogs.insert(hogs.end(), h.begin(), h.end());\n\n                        task_res.set_value(std::move(hogs));\n                    }\n                    catch (...)\n                    {\n                        task_res.set_exception(std::current_exception());\n                    }\n                },\n                hog_row_task<image_type>(m_image, m_from_x, m_to_x, m_from_y, y_half - 1, m_cell_dimension, m_sequential_cells_per_row),\n                hog_row_task<image_type>(m_image, m_from_x, m_to_x, y_half, m_to_y, m_cell_dimension, m_sequential_cells_per_row)\n            );\n        }\n    }\n\nprivate:\n    std::shared_ptr<image_type> m_image;\n\n    std::size_t m_from_x;\n    std::size_t m_to_x;\n    std::size_t m_from_y;\n    std::size_t m_to_y;\n\n    std::size_t m_cell_dimension;\n\n    std::size_t m_sequential_cells_per_row;\n};\n\ntemplate<class image_type>\nstruct hog_task : public boost::asynchronous::continuation_task<std::vector<cvpg::histogram<double> > >\n{\n    hog_task(image_type image, std::size_t cell_dimension, std::size_t sequential_cells_per_row = 4)\n        : boost::asynchronous::continuation_task<std::vector<cvpg::histogram<double> > >(\"hog\")\n        , m_image(std::make_shared<image_type>(std::forward<image_type>(image)))\n        , m_cell_dimension(cell_dimension)\n        , m_sequential_cells_per_row(sequential_cells_per_row)\n    {}\n\n    void operator()()\n    {\n        auto task_res = this->this_task_result();\n\n        // determine the amount of rows and columns dependent on the desired cell dimension\n        const std::size_t cols = m_image->width() / m_cell_dimension;\n        const std::size_t rows = m_image->height() / m_cell_dimension;\n\n        boost::asynchronous::create_callback_continuation(\n            [task_res = std::move(task_res)](auto cont_res) mutable\n            {\n                try\n                {\n                    task_res.set_value(std::move(std::get<0>(cont_res).get()));\n                }\n                catch (...)\n                {\n                    task_res.set_exception(std::current_exception());\n                }\n            },\n            hog_row_task<image_type>(m_image, 0, m_image->width() - 1, 0, m_image->height() - 1, m_cell_dimension, m_sequential_cells_per_row)\n        );\n    }\n\nprivate:\n    std::shared_ptr<image_type> m_image;\n\n    std::size_t m_cell_dimension;\n\n    std::size_t m_sequential_cells_per_row;\n};\n\nvoid paint_hog_cell(std::shared_ptr<cvpg::image_gray_8bit> image, cvpg::histogram<double> const & histogram, std::size_t from_x, std::size_t to_x, std::size_t from_y, std::size_t to_y)\n{\n    auto raw = image->data(0).get();\n    const std::size_t image_width = image->width();\n\n    const std::size_t half_x = from_x + (to_x - from_x) / 2;\n    const std::size_t half_y = from_y + (to_y - from_y) / 2;\n\n    auto draw_line_from_center =\n        [raw, image_width, h_x = half_x, h_y = half_y](std::int32_t dx, std::int32_t dy, double increment)\n        {\n            // calculate start point\n            const std::int32_t x_s = h_x - abs(dx);\n            const std::int32_t y_s = h_y - abs(dy);\n\n            // calculate end point\n            const std::int32_t x_e = h_x + abs(dx);\n            const std::int32_t y_e = h_y + abs(dy);\n\n            if (abs(dx) > abs(dy))\n            {\n                // calculate the slope of the line\n                const std::int32_t s = dy / dx;\n\n                std::size_t y = y_s;\n\n                for (std::size_t x = x_s; x <= x_e; ++x, y += s)\n                {\n                    std::uint8_t * r = raw + y * image_width + x;\n\n                    *r = std::min(\n                            static_cast<std::uint8_t>(255),\n                            static_cast<std::uint8_t>(*r + increment * 255.0)\n                         );\n                }\n            }\n            else\n            {\n                // calculate the slope of the line\n                const std::int32_t s = dx / dy;\n\n                std::size_t x = x_s;\n\n                for (std::size_t y = y_s; y <= y_e; ++y, x += s)\n                {\n                    std::uint8_t * r = raw + y * image_width + x;\n\n                    *r = std::min(\n                            static_cast<std::uint8_t>(255),\n                            static_cast<std::uint8_t>(*r + increment * 255.0)\n                         );\n                }\n            }\n        };\n\n    for (std::size_t i = 0; i < histogram.bins(); ++i)\n    {\n        auto const & h = histogram.at(i);\n\n        if (h != 0.0)\n        {\n            if (i == 0)\n            {\n                // case: angle is at range [0..20) degree\n                draw_line_from_center(0, 2, h);\n            }\n            else if (i == 1)\n            {\n                // case: angle it at range [20..40) degree\n                draw_line_from_center(1, 2, h);\n            }\n            else if (i == 2)\n            {\n                // case: angle it at range [40..60) degree\n                draw_line_from_center(2, 2, h);\n            }\n            else if (i == 3)\n            {\n                // case: angle it at range [60..80) degree\n                draw_line_from_center(2, 1, h);\n            }\n            else if (i == 4)\n            {\n                // case: angle it at range [80..100) degree\n                draw_line_from_center(2, 0, h);\n            }\n            else if (i == 5)\n            {\n                // case: angle it at range [100..120) degree\n                draw_line_from_center(2, -1, h);\n            }\n            else if (i == 6)\n            {\n                // case: angle it at range [120..140) degree\n                draw_line_from_center(2, -2, h);\n            }\n            else if (i == 7)\n            {\n                // case: angle it at range [140..160) degree\n                draw_line_from_center(1, -2, h);\n            }\n            else if (i == 8)\n            {\n                // case: angle it at range [160..180) degree\n                draw_line_from_center(0, -2, h);\n            }\n        }\n    }\n}\n\nstruct hog_image_col_task : public boost::asynchronous::continuation_task<void>\n{\n    hog_image_col_task(std::shared_ptr<cvpg::image_gray_8bit> image, std::shared_ptr<std::vector<cvpg::histogram<double> > > histograms, std::size_t from_cell_col, std::size_t to_cell_col, std::size_t from_cell_row, std::size_t to_cell_row, std::size_t cell_dimension)\n        : boost::asynchronous::continuation_task<void>(\"hog_image_col\")\n        , m_image(std::move(image))\n        , m_histograms(std::move(histograms))\n        , m_from_cell_col(from_cell_col)\n        , m_to_cell_col(to_cell_col)\n        , m_from_cell_row(from_cell_row)\n        , m_to_cell_row(to_cell_row)\n        , m_cell_dimension(cell_dimension)\n    {}\n\n    void operator()()\n    {\n        auto task_res = this->this_task_result();\n\n        const std::size_t cells = m_to_cell_col - m_from_cell_col + 1;\n\n        if (cells <= 1)\n        {\n            const std::size_t cells_per_row = m_image->width() / m_cell_dimension;\n\n            // determine histogram for current cell\n            cvpg::histogram<double> const & h = m_histograms->at(m_from_cell_row * cells_per_row + m_from_cell_col);\n\n            const std::size_t from_x = m_from_cell_col * m_cell_dimension;\n            const std::size_t to_x = from_x + m_cell_dimension - 1;\n            const std::size_t from_y = m_from_cell_row * m_cell_dimension;\n            const std::size_t to_y = from_y + m_cell_dimension - 1;\n\n            paint_hog_cell(m_image, h, from_x, to_x, from_y, to_y);\n\n            task_res.set_value();\n        }\n        else\n        {\n            // determine middle of col-range\n            const std::size_t col_half = m_from_cell_col + (cells / 2);\n\n            boost::asynchronous::create_callback_continuation(\n                [task_res = std::move(task_res)](auto cont_res) mutable\n                {\n                    try\n                    {\n                        std::get<0>(cont_res).get();\n                        std::get<1>(cont_res).get();\n\n                        task_res.set_value();\n                    }\n                    catch (...)\n                    {\n                        task_res.set_exception(std::current_exception());\n                    }\n                },\n                hog_image_col_task(m_image, m_histograms, m_from_cell_col, col_half - 1, m_from_cell_row, m_to_cell_row, m_cell_dimension),\n                hog_image_col_task(m_image, m_histograms, col_half, m_to_cell_col, m_from_cell_row, m_to_cell_row, m_cell_dimension)\n            );\n        }\n    }\n\nprivate:\n    std::shared_ptr<cvpg::image_gray_8bit> m_image;\n\n    std::shared_ptr<std::vector<cvpg::histogram<double> > > m_histograms;\n\n    std::size_t m_from_cell_col;\n    std::size_t m_to_cell_col;\n    std::size_t m_from_cell_row;\n    std::size_t m_to_cell_row;\n\n    std::size_t m_cell_dimension;\n};\n\nstruct hog_image_row_task : public boost::asynchronous::continuation_task<void>\n{\n    hog_image_row_task(std::shared_ptr<cvpg::image_gray_8bit> image, std::shared_ptr<std::vector<cvpg::histogram<double> > > histograms, std::size_t from_cell_col, std::size_t to_cell_col, std::size_t from_cell_row, std::size_t to_cell_row, std::size_t cell_dimension)\n        : boost::asynchronous::continuation_task<void>(\"hog_image_row\")\n        , m_image(std::move(image))\n        , m_histograms(std::move(histograms))\n        , m_from_cell_col(from_cell_col)\n        , m_to_cell_col(to_cell_col)\n        , m_from_cell_row(from_cell_row)\n        , m_to_cell_row(to_cell_row)\n        , m_cell_dimension(cell_dimension)\n    {}\n\n    void operator()()\n    {\n        auto task_res = this->this_task_result();\n\n        const std::size_t cells = m_to_cell_row - m_from_cell_row + 1;\n\n        if (cells <= 1)\n        {\n            boost::asynchronous::create_callback_continuation(\n                [task_res = std::move(task_res)](auto cont_res) mutable\n                {\n                    try\n                    {\n                        std::get<0>(cont_res).get();\n\n                        task_res.set_value();\n                    }\n                    catch (...)\n                    {\n                        task_res.set_exception(std::current_exception());\n                    }\n                },\n                hog_image_col_task(m_image, m_histograms, m_from_cell_col, m_to_cell_col, m_from_cell_row, m_to_cell_row, m_cell_dimension)\n            );\n        }\n        else\n        {\n            // determine middle of row-range\n            const std::size_t row_half = m_from_cell_row + (cells / 2);\n\n            boost::asynchronous::create_callback_continuation(\n                [task_res = std::move(task_res)](auto cont_res) mutable\n                {\n                    try\n                    {\n                        std::get<0>(cont_res).get();\n                        std::get<1>(cont_res).get();\n\n                        task_res.set_value();\n                    }\n                    catch (...)\n                    {\n                        task_res.set_exception(std::current_exception());\n                    }\n                },\n                hog_image_row_task(m_image, m_histograms, m_from_cell_col, m_to_cell_col, m_from_cell_row, row_half - 1, m_cell_dimension),\n                hog_image_row_task(m_image, m_histograms, m_from_cell_col, m_to_cell_col, row_half, m_to_cell_row, m_cell_dimension)\n            );\n        }\n    }\n\nprivate:\n    std::shared_ptr<cvpg::image_gray_8bit> m_image;\n\n    std::shared_ptr<std::vector<cvpg::histogram<double> > > m_histograms;\n\n    std::size_t m_from_cell_col;\n    std::size_t m_to_cell_col;\n    std::size_t m_from_cell_row;\n    std::size_t m_to_cell_row;\n\n    std::size_t m_cell_dimension;\n};\n\nstruct hog_image_task : public boost::asynchronous::continuation_task<cvpg::image_gray_8bit>\n{\n    hog_image_task(std::vector<cvpg::histogram<double> > histograms, std::size_t cells_per_row, std::size_t cell_dimension)\n        : boost::asynchronous::continuation_task<cvpg::image_gray_8bit>(\"hog_image\")\n        , m_histograms(std::make_shared<std::vector<cvpg::histogram<double> > >(std::move(histograms)))\n        , m_cells_per_row(cells_per_row)\n        , m_cell_dimension(cell_dimension)\n    {}\n\n    void operator()()\n    {\n        auto task_res = this->this_task_result();\n\n        const std::size_t cell_cols = m_cells_per_row;\n        const std::size_t cell_rows = m_histograms->size() / cell_cols;\n\n        // create a result image ...\n        auto image = std::make_shared<cvpg::image_gray_8bit>(cell_cols * m_cell_dimension, cell_rows * m_cell_dimension);\n\n        // ... and paint it black\n        memset(image->data(0).get(), 0, image->width() * image->height());\n\n        boost::asynchronous::create_callback_continuation(\n            [task_res = std::move(task_res), image](auto cont_res) mutable\n            {\n                try\n                {\n                    std::get<0>(cont_res).get();\n\n                    task_res.set_value(std::move(*image));\n                }\n                catch (...)\n                {\n                    task_res.set_exception(std::current_exception());\n                }\n            },\n            hog_image_row_task(image, m_histograms, 0, cell_cols - 1, 0, cell_rows - 1, m_cell_dimension)\n        );\n    }\n\nprivate:\n    std::shared_ptr<std::vector<cvpg::histogram<double> > > m_histograms;\n\n    std::size_t m_cells_per_row;\n\n    std::size_t m_cell_dimension;\n};\n\n}\n\nnamespace cvpg::imageproc::algorithms {\n\nboost::asynchronous::detail::callback_continuation<std::vector<histogram<double> > > hog(image_gray_8bit image, std::size_t cell_dimension)\n{\n    return boost::asynchronous::top_level_callback_continuation<std::vector<histogram<double> > >(\n               hog_task(std::move(image), cell_dimension)\n           );\n}\n\nboost::asynchronous::detail::callback_continuation<std::vector<histogram<double> > > hog(image_rgb_8bit image, std::size_t cell_dimension)\n{\n    return boost::asynchronous::top_level_callback_continuation<std::vector<histogram<double> > >(\n               hog_task(std::move(image), cell_dimension)\n           );\n}\n\nboost::asynchronous::detail::callback_continuation<image_gray_8bit> hog_image(std::vector<histogram<double> > histograms, std::size_t cells_per_row, std::size_t cell_dimension)\n{\n    return boost::asynchronous::top_level_callback_continuation<image_gray_8bit>(\n               hog_image_task(std::move(histograms), cells_per_row, cell_dimension)\n           );\n}\n\nboost::asynchronous::detail::callback_continuation<image_gray_8bit> hog_image(image_gray_8bit image)\n{\n    const std::size_t cell_dimension = 8;\n\n    auto cells_per_row = image.width() / cell_dimension;\n\n    return boost::asynchronous::then(\n             hog(std::move(image), cell_dimension),\n             [cells_per_row, cell_dimension](auto cont_res)\n             {\n                 return hog_image(std::move(cont_res.get()), cells_per_row, cell_dimension);\n             }\n           );\n}\n\nboost::asynchronous::detail::callback_continuation<image_gray_8bit> hog_image(image_rgb_8bit image)\n{\n    const std::size_t cell_dimension = 8;\n\n    auto cells_per_row = image.width() / cell_dimension;\n\n    return boost::asynchronous::then(\n             hog(std::move(image), cell_dimension),\n             [cells_per_row, cell_dimension](auto cont_res)\n             {\n                 return hog_image(std::move(cont_res.get()), cells_per_row, cell_dimension);\n             }\n           );\n}\n\n} // namespace cvpg::imageproc::algorithms\n", "meta": {"hexsha": "2cf4c3018e55b16e995e786def0c9ecbf4277536", "size": 23784, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/libcvpg/imageproc/algorithms/hog.cpp", "max_stars_repo_name": "franz-alt/cv-playground", "max_stars_repo_head_hexsha": "d6c3bbdb500bf121c28299d117e459730b2b912d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/libcvpg/imageproc/algorithms/hog.cpp", "max_issues_repo_name": "franz-alt/cv-playground", "max_issues_repo_head_hexsha": "d6c3bbdb500bf121c28299d117e459730b2b912d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libcvpg/imageproc/algorithms/hog.cpp", "max_forks_repo_name": "franz-alt/cv-playground", "max_forks_repo_head_hexsha": "d6c3bbdb500bf121c28299d117e459730b2b912d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.3203463203, "max_line_length": 268, "alphanum_fraction": 0.5598301379, "num_tokens": 5848, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961427, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.49831007957330203}}
{"text": "// Copyright Yamaha 2021\n// MIT License\n// https://github.com/yamaha-bps/cbr_control/blob/master/LICENSE\n\n#ifndef CBR_CONTROL__MPC__DLTV_OCP_HPP_\n#define CBR_CONTROL__MPC__DLTV_OCP_HPP_\n\n#include <Eigen/Dense>\n\n#include <cbr_utils/utils.hpp>\n\n#include <utility>\n\n#include \"ocp_common.hpp\"\n\nnamespace cbr\n{\n\n/* ---------------------------------------------------------------------------------------------- */\n/*               Continuous Time Varying Linear Optimal Control Problem Discretizer               */\n/* ---------------------------------------------------------------------------------------------- */\n\ntemplate<typename cltv_pb_t, std::size_t _nPts = 100, std::size_t exp_order = 4>\nclass DltvOcp\n{\npublic:\n  // Must be defined in ctlv_pb problem\n  constexpr static std::size_t nx = cltv_pb_t::nx;\n  constexpr static std::size_t nu = cltv_pb_t::nu;\n  constexpr static std::size_t nPts = _nPts;\n\n  using problem_t = cltv_pb_t;\n\n  // Create some useful aliases\n  using state_t = Eigen::Matrix<double, nx, 1>;\n  using input_t = Eigen::Matrix<double, nu, 1>;\n  using time_t = Eigen::Matrix<double, nPts, 1>;\n  using A_t = Eigen::Matrix<double, nx, nx>;\n  using B_t = Eigen::Matrix<double, nx, nu>;\n  using Q_t = Eigen::Matrix<double, nx, nx>;\n  using R_t = Eigen::Matrix<double, nu, nu>;\n\n  // Get return type of problem functions\n  using Ar_t = std::result_of_t<decltype(&cltv_pb_t::get_A)(cltv_pb_t, double)>;\n  using Br_t = std::result_of_t<decltype(&cltv_pb_t::get_B)(cltv_pb_t, double)>;\n  using Qr_t = std::result_of_t<decltype(&cltv_pb_t::get_Q)(cltv_pb_t, double)>;\n  using QTr_t = std::result_of_t<decltype(&cltv_pb_t::get_QT)(cltv_pb_t)>;\n  using Rr_t = std::result_of_t<decltype(&cltv_pb_t::get_R)(cltv_pb_t, double)>;\n\n  /* -------------------------------------------------------------------------- */\n  /*                                  Optionals                                 */\n  /* -------------------------------------------------------------------------- */\n\n  // Check existance of get_E function\n  constexpr static bool has_E_approx = std::experimental::is_detected_v<\n    ocp_detail::has_E_continuous, cltv_pb_t>;\n  constexpr static bool has_E = std::experimental::is_detected_exact_v<\n    state_t, ocp_detail::has_E_continuous, cltv_pb_t>||\n    std::experimental::is_detected_exact_v<\n    const state_t &, ocp_detail::has_E_continuous, cltv_pb_t>;\n  using Er_t = std::experimental::detected_or_t<\n    state_t, ocp_detail::has_E_continuous, cltv_pb_t>;\n  static_assert(\n    !(has_E_approx && !has_E),\n    \"Detected get_E function doesn't have a correct return type. \"\n    \"It must be an nx*1 Eigen::Matrix (or a const reference to one)\");\n\n  // Check existance of get_q function\n  constexpr static bool has_q_approx = std::experimental::is_detected_v<\n    ocp_detail::has_q_continuous, cltv_pb_t>;\n  constexpr static bool has_q = std::experimental::is_detected_exact_v<\n    state_t, ocp_detail::has_q_continuous, cltv_pb_t>||\n    std::experimental::is_detected_exact_v<\n    const state_t &, ocp_detail::has_q_continuous, cltv_pb_t>;\n  using qr_t = std::experimental::detected_or_t<\n    state_t, ocp_detail::has_q_continuous, cltv_pb_t>;\n  static_assert(\n    !(has_q_approx && !has_q),\n    \"Detected get_q function doesn't have a correct return type. \"\n    \"It must be an nx*1 Eigen::Matrix (or a const reference to one)\");\n\n  // Check existance of get_qT function\n  constexpr static bool has_qT_approx = std::experimental::is_detected_v<\n    ocp_detail::has_qT_continuous, cltv_pb_t>;\n  constexpr static bool has_qT = std::experimental::is_detected_exact_v<\n    state_t, ocp_detail::has_qT_continuous, cltv_pb_t>||\n    std::experimental::is_detected_exact_v<\n    const state_t &, ocp_detail::has_qT_continuous, cltv_pb_t>;\n\n  using qTr_t = std::experimental::detected_or_t<\n    state_t, ocp_detail::has_qT_continuous, cltv_pb_t>; \\\n  static_assert(\n    !(has_qT_approx && !has_qT),\n    \"Detected get_qT function doesn't have a correct return type. \"\n    \"It must be an nx*1 Eigen::Matrix (or a const reference to one)\");\n\n  // Check existance of get_r function\n  constexpr static bool has_r_approx = std::experimental::is_detected_v<\n    ocp_detail::has_r_continuous, cltv_pb_t>;\n  constexpr static bool has_r = std::experimental::is_detected_exact_v<\n    input_t, ocp_detail::has_r_continuous, cltv_pb_t>||\n    std::experimental::is_detected_exact_v<\n    const input_t &, ocp_detail::has_r_continuous, cltv_pb_t>;\n  using rr_t = std::experimental::detected_or_t<\n    input_t, ocp_detail::has_r_continuous, cltv_pb_t>;\n  static_assert(\n    !(has_r_approx && !has_r),\n    \"Detected get_r function doesn't have a correct return type. \"\n    \"It must be an nu*1 Eigen::Matrix (or a const reference to one)\");\n\n  // Check problem dimensions\n  static_assert(nx > 0, \"Number of states must be > 0.\");\n  static_assert(nu > 0, \"Number of inputs must be > 0.\");\n  static_assert(nPts > 1, \"Number of trajectory points must be > 1.\");\n  static_assert(exp_order < 20, \"Exponential order must be < 20.\");\n\n  // Check return type of problem functions\n  static_assert(\n    std::is_same_v<std::decay_t<Ar_t>, A_t>,\n    \"The get_A method of the problem must return an nx*nx Eigen::Matrix (or a reference to one).\");\n  static_assert(\n    std::is_same_v<std::decay_t<Br_t>, B_t>,\n    \"The get_B method of the problem must return an nx*nu Eigen::Matrix (or a reference to one).\");\n  static_assert(\n    std::is_same_v<std::decay_t<Qr_t>, Q_t>,\n    \"The get_Q method of the problem must return an nx*nx Eigen::Matrix (or a reference to one).\");\n  static_assert(\n    std::is_same_v<std::decay_t<qr_t>, state_t>,\n    \"The get_q method of the problem must return an nx*1 Eigen::Matrix (or a reference to one).\");\n  static_assert(\n    std::is_same_v<std::decay_t<QTr_t>, Q_t>,\n    \"The get_QT method of the problem must return an nx*nx Eigen::Matrix (or a reference to one).\");\n  static_assert(\n    std::is_same_v<std::decay_t<qTr_t>, state_t>,\n    \"The get_qT method of the problem must return an nx*1 Eigen::Matrix (or a reference to one).\");\n  static_assert(\n    std::is_same_v<std::decay_t<Rr_t>, R_t>,\n    \"The get_R method of the problem must return an nu*nu Eigen::Matrix (or a reference to one).\");\n  static_assert(\n    std::is_same_v<std::decay_t<rr_t>, input_t>,\n    \"The get_r method of the problem must return an nu*1 Eigen::Matrix (or a reference to one).\");\n\npublic:\n  DltvOcp() = delete;\n  DltvOcp(const DltvOcp &) = default;\n  DltvOcp(DltvOcp &&) = default;\n  DltvOcp & operator=(const DltvOcp &) = default;\n  DltvOcp & operator=(DltvOcp &&) = default;\n\n  explicit DltvOcp(const cltv_pb_t & pb)\n  : cltv_pb_(pb),\n    dt_{compute_dt()}\n  {}\n\n  explicit DltvOcp(cltv_pb_t && pb)\n  : cltv_pb_(std::move(pb)),\n    dt_{compute_dt()}\n  {}\n\n  template<typename T1>\n  DltvOcp(T1 && pb)\n  : cltv_pb_(std::forward<T1>(pb)),\n    dt_{compute_dt()}\n  {}\n\n  void get_x0(Eigen::Ref<state_t> x0) const\n  {\n    cltv_pb_.get_x0(x0);\n  }\n\n  void get_state_lb(std::size_t k, Eigen::Ref<state_t> state_lb) const\n  {\n    cltv_pb_.get_state_lb(indexToTime(k), state_lb);\n  }\n\n  void get_state_ub(std::size_t k, Eigen::Ref<state_t> state_ub) const\n  {\n    cltv_pb_.get_state_ub(indexToTime(k), state_ub);\n  }\n\n  void get_input_lb(std::size_t k, Eigen::Ref<input_t> input_lb) const\n  {\n    cltv_pb_.get_input_lb(indexToTime(k), input_lb);\n  }\n\n  void get_input_ub(std::size_t k, Eigen::Ref<input_t> input_ub) const\n  {\n    cltv_pb_.get_input_ub(indexToTime(k), input_ub);\n  }\n\n  A_t get_A(std::size_t k) const\n  {\n    // define identity for order = 0\n    A_t expA = A_t::Identity();\n\n    if constexpr (exp_order > 0) {\n      const A_t Adt = dt_ * cltv_pb_.get_A(indexToTime(k));\n      expA += Adt;\n      if constexpr (exp_order > 1) {\n        double c = 1.;\n        A_t Adtp = Adt;\n        for (std::size_t i = 2; i <= exp_order; i++) {\n          Adtp *= Adt;\n          c /= static_cast<double>(i);\n          expA += c * Adtp;\n        }\n      }\n    }\n\n    return expA;\n  }\n\n  B_t get_B(std::size_t k) const\n  {\n    // define identity for order = 0\n    A_t expA = A_t::Identity();\n\n    if constexpr (exp_order > 0) {\n      const A_t Adt = dt_ * cltv_pb_.get_A(indexToTime(k));\n      expA += Adt / 2.;\n      if constexpr (exp_order > 1) {\n        double c = 0.5;\n        A_t Adtp = Adt / 2.;\n        for (std::size_t i = 2; i <= exp_order; i++) {\n          Adtp *= Adt;\n          c /= static_cast<double>(i + 1);\n          expA += c * Adtp;\n        }\n      }\n    }\n\n    B_t expB = expA * cltv_pb_.get_B(indexToTime(k)) * dt_;\n\n    return expB;\n  }\n\n  template<typename T = std::size_t>\n  state_t get_E(std::enable_if_t<has_E, T> k)\n  {\n    // define identity for order = 0\n    A_t expA = A_t::Identity();\n\n    if constexpr (exp_order > 0) {\n      const A_t Adt = dt_ * cltv_pb_.get_A(indexToTime(k));\n      expA += Adt / 2.;\n      if constexpr (exp_order > 1) {\n        double c = 0.5;\n        A_t Adtp = Adt / 2.;\n        for (std::size_t i = 2; i <= exp_order; i++) {\n          Adtp *= Adt;\n          c /= static_cast<double>(i + 1);\n          expA += c * Adtp;\n        }\n      }\n    }\n\n    state_t expE = expA * cltv_pb_.get_E(indexToTime(k)) * dt_;\n    return expE;\n  }\n\n  Q_t get_Q(std::size_t k) const\n  {\n    return dt_ * cltv_pb_.get_Q(indexToTime(k));\n  }\n\n  template<typename T = std::size_t>\n  state_t get_q(std::enable_if_t<has_q, T> k) const\n  {\n    return dt_ * cltv_pb_.get_q(indexToTime(k));\n  }\n\n  R_t get_R(std::size_t k) const\n  {\n    return dt_ * cltv_pb_.get_R(indexToTime(k));\n  }\n\n  template<typename T = std::size_t>\n  input_t get_r(std::enable_if_t<has_r, T> k) const\n  {\n    return dt_ * cltv_pb_.get_r(indexToTime(k));\n  }\n\n  Q_t get_QT() const\n  {\n    double T;\n    cltv_pb_.get_T(T);\n    return cltv_pb_.get_QT();\n  }\n\n  template<typename T = void *>\n  state_t get_qT([[maybe_unused]] std::enable_if_t<has_qT, T> k = nullptr) const\n  {\n    double TT;\n    cltv_pb_.get_T(TT);\n    return cltv_pb_.get_qT();\n  }\n\n\n  cltv_pb_t & problem()\n  {\n    return cltv_pb_;\n  }\n\n  double indexToTime(std::size_t k) const\n  {\n    return static_cast<double>(k) * dt_;\n  }\n\nprotected:\n  double compute_dt()\n  {\n    double T;\n    cltv_pb_.get_T(T);\n    return T / static_cast<double>(nPts - 1);\n  }\n\nprotected:\n  cltv_pb_t cltv_pb_{};\n  double dt_{};\n};\n\n// Class template argument deduction guides\ntemplate<typename T>\nDltvOcp(T)->DltvOcp<T>;\n\ntemplate<typename T1, typename T2>\nDltvOcp(T1, T2)->DltvOcp<T1, T2::nPts, T2::expOrder>;\n\n}  // namespace cbr\n\n\n#endif  // CBR_CONTROL__MPC__DLTV_OCP_HPP_\n", "meta": {"hexsha": "b36bf0b0302f8f862f062a9927cf467ce40f091f", "size": 10503, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/cbr_control/mpc/dltv_ocp.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/dltv_ocp.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/dltv_ocp.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": 31.5405405405, "max_line_length": 100, "alphanum_fraction": 0.6406740931, "num_tokens": 3113, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835411997897, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4983100771301014}}
{"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 <iostream>\n#include <iomanip>\n#include <boost/ptr_container/ptr_vector.hpp>\n#include <boost/function.hpp>\n#include \"config/config.hpp\"\n#if HAVE_CBLAS\n\t#include \"cblas.h\"\n#endif\n#include \"Eigen/Core\"\n#include \"Eigen/Eigenvalues\"\n#include \"genfile/VariantIdentifyingData.hpp\"\n#include \"genfile/VariantDataReader.hpp\"\n#include \"genfile/vcf/get_set_eigen.hpp\"\n#include \"appcontext/get_current_time_as_string.hpp\"\n#include \"components/RelatednessComponent/PCALoadingComputer.hpp\"\n#include \"components/RelatednessComponent/LapackEigenDecomposition.hpp\"\n#include \"components/RelatednessComponent/mean_centre_genotypes.hpp\"\n\n// #define DEBUG_PCA_LOADING_COMPUTER 1\n\nnamespace {\n\ttemplate< typename Vector1, typename Vector2, typename NonMissingVector >\n\tdouble compute_correlation( Vector1 const& v1, Vector2 const& v2, NonMissingVector const& non_missingness_indicator ) {\n\t\tassert( v1.size() == v2.size() ) ;\n\t\tdouble non_missingness = non_missingness_indicator.sum() ;\n\t\tdouble mean1 = 0.0 ;\n\t\tdouble mean2 = 0.0 ;\n\t\tfor( int i = 0; i < v1.size(); ++i ) {\n\t\t\tif( non_missingness_indicator( i )) {\n\t\t\t\tmean1 += v1(i) / non_missingness ;\n\t\t\t\tmean2 += v2(i) / non_missingness ;\n\t\t\t}\n\t\t}\n\n\t\tdouble covariance = 0.0 ;\n\t\tdouble variance1 = 0.0 ;\n\t\tdouble variance2 = 0.0 ;\n\t\tfor( int i = 0; i < v1.size(); ++i ) {\n\t\t\tif( non_missingness_indicator( i )) {\n\t\t\t\tcovariance += ( v1(i) - mean1 ) * ( v2(i) - mean2 ) ;\n\t\t\t\tvariance1 += ( v1(i) - mean1 ) * ( v1(i) - mean1 ) ;\n\t\t\t\tvariance2 += ( v2(i) - mean2 ) * ( v2(i) - mean2 ) ;\n\t\t\t}\n\t\t}\n\t\t\n\t\t// We should divide the covariance by N-1 and also\n\t\t// divide each variance by the same quantity.\n\t\t// But this washes out in the ratio.\n\t\t\n\t\treturn covariance / std::sqrt( variance1 * variance2 ) ;\n\t}\n\t\n\tstd::string eigenvector_column_names( std::size_t N, std::string const& string1, std::string const& string2, std::size_t i ) {\n\t\tif( i < N ) {\n\t\t\treturn string1 + genfile::string_utils::to_string( i+1 ) ;\n\t\t}\n\t\telse {\n\t\t\treturn string2 + genfile::string_utils::to_string( i+1 -N ) ;\n\t\t}\n\t}\n}\n\nPCALoadingComputer::PCALoadingComputer( int number_of_loadings ):\n\tm_number_of_loadings( number_of_loadings ),\n\tm_number_of_snps( 1 )\n{}\n\nvoid PCALoadingComputer::set_UDUT( std::size_t number_of_snps, Matrix const& udut ) {\n\tassert( udut.cols() == udut.rows() + 1 ) ;\n\tint n = std::min( int( m_number_of_loadings ), int( udut.rows() ) ) ;\n\tm_D = udut.block( 0, 0, n, 1 ) ;\n\tm_sqrt_D_inverse = 1 / m_D.array().sqrt() ;\n\tm_U = udut.block( 0, 1, udut.rows(), n ) ;\n\tm_number_of_snps = number_of_snps ;\n}\n\nvoid PCALoadingComputer::begin_processing_snps( std::size_t number_of_samples, genfile::SNPDataSource::Metadata const& ) {\n\tassert( number_of_samples = std::size_t( m_U.rows() )) ;\n\tm_genotype_calls.resize( number_of_samples ) ;\n\tm_non_missingness.resize( number_of_samples ) ;\n}\n\nvoid PCALoadingComputer::processed_snp( genfile::VariantIdentifyingData const& snp, genfile::VariantDataReader& data_reader ) {\n\tdata_reader.get(\n\t\t\":genotypes:\",\n\t\tgenfile::vcf::get_threshholded_calls( m_genotype_calls, m_non_missingness, 0.9, 0, 0, 1, 2 )\n\t) ;\n\tassert( m_genotype_calls.size() == m_U.rows() ) ;\n\tassert( m_non_missingness.size() == m_U.rows() ) ;\n\t// setup the storage\n\tm_loading_vectors.resize( 2 * m_D.rows() ) ;\n\tm_loading_vectors.setConstant( std::numeric_limits< double >::quiet_NaN() ) ;\n\tdouble const allele_frequency = m_genotype_calls.sum() / ( 2.0 * m_non_missingness.sum() ) ;\n\tif( m_non_missingness.sum() > 0 && allele_frequency > 0.001 ) {\n\t\t//std::cerr << \"pre-mean genotypes are: \" << m_genotype_calls.head( 20 ).transpose() << \"...\\n\" ;\n\t\tpca::mean_centre_genotypes( &m_genotype_calls, m_non_missingness, allele_frequency ) ;\n\t\tm_genotype_calls /= std::sqrt( 2.0 * allele_frequency * ( 1.0 - allele_frequency ) ) ;\n\n#if DEBUG_PCA_LOADING_COMPUTER\n\t\t//std::cerr << \"                    SNP: \" << snp << \", allele frequency = \" << allele_frequency << \".\\n\" ;\n\t\t//std::cerr << std::resetiosflags( std::ios::floatfield ) << std::setprecision( 5 ) ;\n\t\t//std::cerr << \"pre-scale genotypes are: \" << m_genotype_calls.head( 20 ).transpose() << \"...\\n\" ;\n\t\tstd::cerr << \"          genotypes are: \" << m_genotype_calls.head( 20 ).transpose() << \"...\\n\" ;\n\t\tstd::cerr << \"     non-missingness is: \" << m_non_missingness.head( 20 ).transpose() << \"...\\n\" ;\n\t\tstd::cerr << \"                   U is: \" << m_U.block(0,0,10,10) << \"...\\n\" ;\n\t\tstd::cerr << \"                   D is: \" << m_D << \"...\\n\" ;\n#endif // DEBUG_PCA_LOADING_COMPUTER\n\t\n\n\t\t//\n\t\t// Let X  be the L\\times n matrix (L SNPs, n samples) of (mean-centred, scaled) genotypes.  We want\n\t\t// to compute the row of the matrix S of unit eigenvectors of the variance-covariance matrix\n\t\t// (1/L) X X^t that corresponds to the current SNP.\n\t\t// The matrix S is given by\n\t\t//               \n\t\t//       S = (1/\u221aL) X U D^{-\u00bd}\n\t\t//\n\t\t// where\n\t\t//       (1/L) X^t X = U D U^t\n\t\t// is the eigenvalue decomposition of (1/L) X^t X that we are passed in via set_UDUT (and L is the number of SNPs).\n\t\t//\n\t\t// This is true since then\n\t\t//\n\t\t// S^t S = D^{-\u00bd} U^t (1/L) X^t X U D^{-\u00bd} = id\n\t\t//\n\t\t// (so columns of S are orthogonal) while\n\t\t//\n\t\t// (1/L X X^t) S = (1/L\u221aL) X X^t X U D^{-\u00bd}\n\t\t//           = (1/\u221aL) X U D U^t U D^{-\u00bd}\n\t\t//           = (1/\u221aL) X U D^\u00bd\n\t\t//           = SD\n\t\t//\n\t\t// (so columns of S are eigenvectors with eigenvalues given by D.)\n\t\t//\n#if 0\n\t\tm_loading_vectors.segment( 0, m_U.cols() ) =\n\t\t\t( m_genotype_calls.transpose() * m_U ) * m_D.array().sqrt().matrix().asDiagonal()\n\t\t\t/ ( ( m_D.transpose().array() * m_number_of_snps ).sqrt() ) ;\n#else\n\t\tm_loading_vectors.segment( 0, m_U.cols() ) =\n\t\t\t( m_genotype_calls.transpose() * m_U ) * m_sqrt_D_inverse.asDiagonal() ;\n\t\tm_loading_vectors /= std::sqrt( m_number_of_snps ) ;\n#endif\n\t\t// We also wish to compute the correlation between the SNP and the PCA component.\n\t\t// With S as above, the PCA components are the projections of columns of X onto columns of S.\n\t\t// If we want samples to correspond to columns, this is\n\t\t//   S^t X \n\t\t// which can be re-written\n\t\t//   sqrt(L) U D^{1/2}\n\t\t// i.e. we may as well compute the correlation with columns of U.\n\t\tif( m_non_missingness.sum() > 10 ) {\n\t\t\tfor( int i = 0; i < m_U.cols(); ++i ) {\n\t\t\t\tm_loading_vectors( m_U.cols() + i ) = compute_correlation( m_genotype_calls, m_U.col( i ), m_non_missingness ) ;\n\t\t\t}\n\t\t}\n\t}\n\tsend_results(\n\t\tsnp,\n\t\tm_non_missingness.sum(),\n\t\tallele_frequency,\n\t\tm_loading_vectors,\n\t\tboost::bind(\n\t\t\t&eigenvector_column_names,\n\t\t\tm_U.cols(),\n\t\t\t\"eigenvector_\",\n\t\t\t\"correlation_\",\n\t\t\t_1\n\t\t)\n\t) ;\n}\n\nvoid PCALoadingComputer::send_results_to( ResultCallback callback ) {\n\tm_result_signal.connect( callback ) ;\n}\n\nvoid PCALoadingComputer::send_results( genfile::VariantIdentifyingData const& snp, double const N, double const frequency, Eigen::VectorXd const& data, GetNames get_names ) {\n\tm_result_signal( snp, N, frequency, data, get_names ) ;\n}\n\nstd::string PCALoadingComputer::get_metadata() const {\n\tusing namespace genfile::string_utils ;\n\treturn \"Number of SNPs: \" + to_string( m_number_of_snps ) + \"\\n\"\n\t\t+ \"Number of samples: \" + to_string( m_U.rows() ) + \"\\n\"\n\t\t+ \"These loadings represent unit eigenvectors of the variance-covariance matrix\\n\"\n\t\t+ \"    1/L X X^t\\n\"\n\t\t+ \"where X is the LxN matrix of genotypes at L SNPs and N samples (normalised across rows.)\" ;\n}\n\nvoid PCALoadingComputer::end_processing_snps() {}\n\n\n\n", "meta": {"hexsha": "7e78325e751419e7810949cd485fea5e68ead6ba", "size": 7582, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "components/RelatednessComponent/src/PCALoadingComputer.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/RelatednessComponent/src/PCALoadingComputer.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/RelatednessComponent/src/PCALoadingComputer.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": 38.1005025126, "max_line_length": 174, "alphanum_fraction": 0.6582695859, "num_tokens": 2384, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.49831006980049936}}
{"text": "#include <iostream>\n#include <string>\n#include <Eigen/Dense>\n#include <fstream>\n#include <sstream>\n#include <cstdlib>\n#include <string>\n#include <unistd.h>\n#include <sys/wait.h>\n#include \"H5Cpp.h\"\n#include \"rapidjson/document.h\"\n#include \"rapidjson/writer.h\"\n#include \"rapidjson/stringbuffer.h\"\n    \nusing std::cout;\nusing std::endl;\n\nusing namespace H5;\nusing namespace rapidjson;\nusing Eigen::tanh;\nusing Eigen::MatrixXd;\n\ninline double min(double a, double b) { return(((a)<(b))?(a):(b));}\ninline double max(double a, double b) { return(((a)>(b))?(a):(b));}\n\ndouble hard_sigmoid(double x){\n    return(max(0.0, min(1.0, x*0.2+0.5)));\n}\n\ndouble sigmoid(double x){\n    return 1.0 / (1.0 + exp(-x));\n}\n\ninline MatrixXd Mult(MatrixXd input1, MatrixXd input2){\n    return(input1.array() * input2.array());\n}\n\nchar* read_model(const char *filename)\n{\n    char *arch_json;\n    \n    H5File file(filename, H5F_ACC_RDWR);\n    Attribute attr(file.openAttribute(\"model_config\"));\n    DataType type(attr.getDataType());\n    \n    \n    attr.read(type, &arch_json);\n    return arch_json;\n}\n\n\ninline MatrixXd readCSV(const char* filename, int row_n, int col_n){\n    \n    std::ifstream file(filename);\n    int col_flag = 0;\n\n    MatrixXd m(row_n, col_n);\n    \n\n    if(row_n == 1){\n        col_flag = 1;\n        m.resize(col_n, row_n);\n    }\n\n    \n    std::string line;\n    \n    int row = 0;\n    int col = 0;\n    \n    \n    if(file.is_open()){\n        while(std::getline(file, line)){\n            char *ptr = (char *)line.c_str();\n            int len = line.length();\n            \n            col = 0;\n            \n            char *start = ptr;\n            for(int i = 0; i < len; i++){\n                if(ptr[i] == ','){\n                    m(row, col++) = atof(start);\n                    start = ptr + i + 1;\n                }\n            }\n            m(row, col) = atof(start);\n            \n            row++;\n        }\n        file.close();   \n    }\n    \n    if(col_flag)\n        return(m.transpose());\n\n    return(m);\n}\n\nclass Embedding{\n    public:\n        int row;\n        int col;\n        int out_size;\n        MatrixXd W;\n\n        Embedding(){\n\n        }\n\n        Embedding(const char* filename, int row, int col){\n            this->row = row;\n            this->col = col;\n            this->out_size = col;\n\n            W.resize(this->row, this->col);\n            this->W = readCSV(filename, this->row, this->col);\n        \n        }\n\n        MatrixXd operator()(MatrixXd input){\n            MatrixXd Out(input.cols(), this->out_size);\n            for(int t=0; t < Out.rows(); t++)\n                Out.row(t) = W.row( input(0, t) );\n\n            return(Out);\n        }\n};\n\nclass LSTM{\n    public:\n        int inp_size;\n        int out_size;\n        MatrixXd kernel;\n        MatrixXd recurrent_kernel;\n        MatrixXd bias;\n\n        LSTM(){\n\n        }\n\n        LSTM(const char* kernel_filename, const char* recurrent_kernel_filename, const char* bias_filename, int inp_size, int out_size){\n            this->inp_size = inp_size;\n            this->out_size = out_size;\n\n            kernel.resize(this->inp_size, this->out_size * 4);\n            kernel = readCSV(kernel_filename, this->inp_size, this->out_size * 4);\n\n            recurrent_kernel.resize(this->out_size, this->out_size * 4);\n            recurrent_kernel = readCSV(recurrent_kernel_filename, this->out_size, this->out_size * 4);      \n            \n            bias.resize(1, this->out_size * 4);\n            bias = readCSV(bias_filename, 1, this->out_size * 4);       \n\n        }\n\n        MatrixXd operator()(MatrixXd input){\n            int LSTM_OUT = this->out_size;\n            int MAXLEN   = input.rows();\n\n            MatrixXd C_t = MatrixXd::Zero(1, this->out_size);\n            MatrixXd h_t = MatrixXd::Zero(1, this->out_size);\n            \n            for(int t = 0; t < MAXLEN; t++){\n                MatrixXd tmp_out(1, 4*LSTM_OUT);\n                MatrixXd i_t(1, LSTM_OUT);\n                MatrixXd f_t(1, LSTM_OUT);\n                MatrixXd o_t(1, LSTM_OUT);\n                MatrixXd g_t(1, LSTM_OUT);\n                \n                // IFCO\n                tmp_out = input.row(t) * kernel + h_t * recurrent_kernel + bias;\n                \n                i_t = (tmp_out.block(0, 0*LSTM_OUT, 1, LSTM_OUT)).unaryExpr(&hard_sigmoid);\n                f_t = (tmp_out.block(0, 1*LSTM_OUT, 1, LSTM_OUT)).unaryExpr(&hard_sigmoid);\n                o_t = (tmp_out.block(0, 3*LSTM_OUT, 1, LSTM_OUT)).unaryExpr(&hard_sigmoid);\n                g_t = tanh((tmp_out.block(0, 2*LSTM_OUT, 1, LSTM_OUT)).array());\n                \n                C_t = f_t.array() * C_t.array() + i_t.array() * g_t.array();\n                h_t = o_t.array() * tanh(C_t.array());\n            }\n            return h_t; \n        }   \n};\n\nclass GRU{\n    public:\n        int inp_size;\n        int out_size;\n        MatrixXd kernel;\n        MatrixXd recurrent_kernel;\n        MatrixXd bias;\n\n        GRU(){\n\n        }\n\n        GRU(const char* kernel_filename, const char* recurrent_kernel_filename, const char* bias_filename, int inp_size, int out_size){\n            this->inp_size = inp_size;\n            this->out_size = out_size;\n\n            kernel.resize(this->inp_size, this->out_size * 4);\n            kernel = readCSV(kernel_filename, this->inp_size, this->out_size * 4);\n\n            recurrent_kernel.resize(this->out_size, this->out_size * 4);\n            recurrent_kernel = readCSV(recurrent_kernel_filename, this->out_size, this->out_size * 4);      \n            \n            bias.resize(1, this->out_size * 4);\n            bias = readCSV(bias_filename, 1, this->out_size * 4);       \n\n        }\n\n        MatrixXd operator()(MatrixXd input){\n            int LSTM_OUT = this->out_size;\n            int MAXLEN   = input.rows();\n\n            MatrixXd hh_t = MatrixXd::Zero(1,LSTM_OUT);\n            MatrixXd h_t = MatrixXd::Zero(1,LSTM_OUT);\n            MatrixXd one_arr = MatrixXd::Ones(1,LSTM_OUT);\n            \n            MatrixXd tmp_out(1, 3*LSTM_OUT);\n            MatrixXd tmp_W(1, LSTM_OUT);\n            MatrixXd tmp_U(LSTM_OUT, LSTM_OUT);\n            MatrixXd z_t(1, LSTM_OUT);\n            MatrixXd r_t(1, LSTM_OUT);\n            \n            tmp_U = recurrent_kernel.block(0, 2*LSTM_OUT, LSTM_OUT, LSTM_OUT);\n            \n            for(int t = 0; t < MAXLEN; t++){\n                \n                // IFCO\n                \n                tmp_W = input.row(t) * kernel + bias ;\n                tmp_out = tmp_W + h_t * recurrent_kernel;\n                    \n                z_t = (tmp_out.block(0, 0*LSTM_OUT, 1, LSTM_OUT)).unaryExpr(&hard_sigmoid);\n                r_t = (tmp_out.block(0, 1*LSTM_OUT, 1, LSTM_OUT)).unaryExpr(&hard_sigmoid);\n                r_t = r_t.array() * h_t.array();\n                \n                hh_t = tanh((r_t * tmp_U + tmp_W.block(0, 2*LSTM_OUT, 1, LSTM_OUT)).array() );\n                h_t = (one_arr - z_t).array() * hh_t.array() + z_t.array() * h_t.array(); \n            \n            }\n            return h_t;\n        }   \n};\n\nclass Dense{\n    public:\n        int inp_size;\n        int out_size;\n        string activation;\n        MatrixXd kernel;\n        MatrixXd bias;\n\n        Dense(){\n\n        }\n\n        Dense(const char* kernel_filename, const char* bias_filename, int inp_size, int out_size, string activation=\"linear\"){\n            this->inp_size = inp_size;\n            this->out_size = out_size;\n            this->activation = activation;\n\n            kernel.resize(this->inp_size, this->out_size);\n            kernel = readCSV(kernel_filename, this->inp_size, this->out_size);\n\n            bias.resize(1, this->out_size);\n            bias = readCSV(bias_filename, 1, this->out_size);\n        }\n\n        MatrixXd operator()(MatrixXd input){\n\n            if(this->activation == \"linear\")\n                return( input * kernel + bias );\n            else if(this->activation == \"sigmoid\")\n                return( (input * kernel + bias).unaryExpr(&sigmoid) );\n        }\n};\n", "meta": {"hexsha": "c45dce25572baf1d23d0cf5968cf779a781f4b87", "size": 7965, "ext": "cc", "lang": "C++", "max_stars_repo_path": "cc/module.cc", "max_stars_repo_name": "VishnuDuttSharma/KeLiPTo", "max_stars_repo_head_hexsha": "c5730fcb25dec199ce41b12e08ee442a00aa6c43", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-09-12T21:59:19.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-04T09:26:22.000Z", "max_issues_repo_path": "cc/module.cc", "max_issues_repo_name": "VishnuDuttSharma/KeLiPTo", "max_issues_repo_head_hexsha": "c5730fcb25dec199ce41b12e08ee442a00aa6c43", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cc/module.cc", "max_forks_repo_name": "VishnuDuttSharma/KeLiPTo", "max_forks_repo_head_hexsha": "c5730fcb25dec199ce41b12e08ee442a00aa6c43", "max_forks_repo_licenses": ["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": 136, "alphanum_fraction": 0.521908349, "num_tokens": 1979, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107309, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4983100698004993}}
{"text": "#include <NTL/ZZX.h>\n\nNTL_CLIENT\n\n\n#define TIME_IT(t, action) \\\ndo { \\\n   double _t0, _t1; \\\n   long _iter = 1; \\\n   long _cnt = 0; \\\n   do { \\\n      _t0 = GetTime(); \\\n      for (long _i = 0; _i < _iter; _i++) { action; _cnt++; } \\\n      _t1 = GetTime(); \\\n   } while ( _t1 - _t0 < 2 && (_iter *= 2)); \\\n   t = (_t1 - _t0)/_iter; \\\n} while(0)\n\nvoid FillRandom(ZZX& f, long n, long k)\n{\n   long sw = RandomBnd(2);\n   f.SetLength(n);\n   for (long i = 0; i < n; i++) {\n      if (sw) {\n         long kk = 1 + RandomBnd(k);\n         RandomBits(f[i], kk);\n      }\n      else {\n        long kk = RandomBnd(k);\n        SetBit(f[i], kk);\n      }\n      if (RandomBnd(2)) NTL::negate(f[i], f[i]);\n   }\n   f.normalize();\n}\n\nint main()\n{\n\n   for (long iter = 0; iter < 4000; iter++) {\n     if (iter % 100 == 0) cerr << \".\";\n     long na, nb, k;\n\n     long sw = RandomBnd(3);\n\n     if (sw == 0) {\n        na = RandomBnd(20) + 1;\n        nb = RandomBnd(20) + 1;\n        k = RandomBnd(20) + 1;\n     }\n     else if (sw == 1) {\n        na = RandomBnd(200) + 10;\n        nb = RandomBnd(200) + 10;\n        k = RandomBnd(200) + 10;\n     }\n     else {\n        na = RandomBnd(3000) + 100;\n        nb = RandomBnd(3000) + 100;\n        k = RandomBnd(3000) + 100;\n     }\n\n     ZZX a, b, c, c1;\n     FillRandom(a, na, k);\n     FillRandom(b, nb, k);\n    \n     if (RandomBnd(2)) {\n        SSMul(c, a, b);\n        KarMul(c1, a, b);\n        if (c != c1) Error(\"oops\");\n     }\n     else {\n        SSSqr(c, a);\n        KarSqr(c1, a);\n        if (c != c1) Error(\"oops\");\n     }\n   }\n\n   cerr << \"\\n\";\n}\n\n\n", "meta": {"hexsha": "9cd08b6e0a7f6a625e30cc77aa1e4b3cc73944b9", "size": 1571, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "homomorphic_evaluation/ntl-11.3.2/src/SSMulTest.cpp", "max_stars_repo_name": "dklee0501/PLDI_20_242_artifact_publication", "max_stars_repo_head_hexsha": "f2b73df9165c76e8b521d8ebd639d68321e3862b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 61.0, "max_stars_repo_stars_event_min_datetime": "2015-03-21T19:39:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-22T06:14:16.000Z", "max_issues_repo_path": "homomorphic_evaluation/ntl-11.3.2/src/SSMulTest.cpp", "max_issues_repo_name": "dklee0501/Lobster", "max_issues_repo_head_hexsha": "f2b73df9165c76e8b521d8ebd639d68321e3862b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 15.0, "max_issues_repo_issues_event_min_datetime": "2021-12-24T22:53:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-25T10:03:13.000Z", "max_forks_repo_path": "LibSource/ExtendedNTL/tests/SSMulTest.cpp", "max_forks_repo_name": "ekzyis/CrypTool-2", "max_forks_repo_head_hexsha": "1af234b4f74486fbfeb3b3c49228cc36533a8c89", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2016-01-16T07:59:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-17T10:27:23.000Z", "avg_line_length": 19.1585365854, "max_line_length": 63, "alphanum_fraction": 0.4322087842, "num_tokens": 588, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933535169629, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4982189941230373}}
{"text": "#ifndef STAN_MATH_PRIM_MAT_PROB_CATEGORICAL_LOGIT_LPMF_HPP\n#define STAN_MATH_PRIM_MAT_PROB_CATEGORICAL_LOGIT_LPMF_HPP\n\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/arr/fun/log_sum_exp.hpp>\n#include <stan/math/prim/mat/fun/log_softmax.hpp>\n#include <stan/math/prim/mat/fun/log_sum_exp.hpp>\n#include <stan/math/prim/mat/fun/sum.hpp>\n#include <stan/math/prim/scal/meta/include_summand.hpp>\n#include <boost/math/tools/promotion.hpp>\n#include <vector>\n\nnamespace stan {\n  namespace math {\n\n    // CategoricalLog(n|theta)  [0 < n <= N, theta unconstrained], no checking\n    template <bool propto,\n              typename T_prob>\n    typename boost::math::tools::promote_args<T_prob>::type\n    categorical_logit_lpmf(int n,\n                          const Eigen::Matrix<T_prob, Eigen::Dynamic, 1>&\n                          beta) {\n      static const char* function(\"categorical_logit_lpmf\");\n\n      check_bounded(function, \"categorical outcome out of support\", n,\n                    1, beta.size());\n      check_finite(function, \"log odds parameter\", beta);\n\n      if (!include_summand<propto, T_prob>::value)\n        return 0.0;\n\n      // FIXME:  wasteful vs. creating term (n-1) if not vectorized\n      return beta(n - 1) - log_sum_exp(beta);  // == log_softmax(beta)(n-1);\n    }\n\n    template <typename T_prob>\n    inline\n    typename boost::math::tools::promote_args<T_prob>::type\n    categorical_logit_lpmf(int n,\n                          const Eigen::Matrix<T_prob, Eigen::Dynamic, 1>&\n                          beta) {\n      return categorical_logit_lpmf<false>(n, beta);\n    }\n\n    template <bool propto,\n              typename T_prob>\n    typename boost::math::tools::promote_args<T_prob>::type\n    categorical_logit_lpmf(const std::vector<int>& ns,\n                          const Eigen::Matrix<T_prob, Eigen::Dynamic, 1>&\n                          beta) {\n      static const char* function(\"categorical_logit_lpmf\");\n\n      for (size_t k = 0; k < ns.size(); ++k)\n        check_bounded(function, \"categorical outcome out of support\",\n                      ns[k], 1, beta.size());\n      check_finite(function, \"log odds parameter\", beta);\n\n      if (!include_summand<propto, T_prob>::value)\n        return 0.0;\n\n      if (ns.size() == 0)\n        return 0.0;\n\n      Eigen::Matrix<T_prob, Eigen::Dynamic, 1> log_softmax_beta\n        = log_softmax(beta);\n\n      // FIXME:  replace with more efficient sum()\n      Eigen::Matrix<typename boost::math::tools::promote_args<T_prob>::type,\n                    Eigen::Dynamic, 1> results(ns.size());\n      for (size_t i = 0; i < ns.size(); ++i)\n        results[i] = log_softmax_beta(ns[i] - 1);\n      return sum(results);\n    }\n\n    template <typename T_prob>\n    inline\n    typename boost::math::tools::promote_args<T_prob>::type\n    categorical_logit_lpmf(const std::vector<int>& ns,\n                          const Eigen::Matrix<T_prob, Eigen::Dynamic, 1>&\n                          beta) {\n      return categorical_logit_lpmf<false>(ns, beta);\n    }\n\n  }\n}\n#endif\n", "meta": {"hexsha": "a26e5e9e1b8856012aacad2f0f13e4500a35aca0", "size": 3097, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/mat/prob/categorical_logit_lpmf.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/prim/mat/prob/categorical_logit_lpmf.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/prim/mat/prob/categorical_logit_lpmf.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.1931818182, "max_line_length": 78, "alphanum_fraction": 0.6193090087, "num_tokens": 796, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.49821898342608323}}
{"text": "/**\n * @file lsh_test.cpp\n *\n * Unit tests for the 'LSHSearch' class.\n */\n#include <mlpack/core.hpp>\n#include <mlpack/core/metrics/lmetric.hpp>\n#include <boost/test/unit_test.hpp>\n#include \"old_boost_test_definitions.hpp\"\n\n#include <mlpack/methods/lsh/lsh_search.hpp>\n\nusing namespace std;\nusing namespace mlpack;\nusing namespace mlpack::neighbor;\n\nBOOST_AUTO_TEST_SUITE(LSHTest);\n\nBOOST_AUTO_TEST_CASE(LSHSearchTest)\n{\n  // Force to specific random seed for these results.\n  math::RandomSeed(0);\n\n  // Precomputed hash width value.\n  const double hashWidth = 4.24777;\n\n  arma::mat rdata(2, 10);\n  rdata << 3 << 2 << 4 << 3 << 5 << 6 << 0 << 8 << 3 << 1 << arma::endr <<\n           0 << 3 << 4 << 7 << 8 << 4 << 1 << 0 << 4 << 3 << arma::endr;\n\n  arma::mat qdata(2, 3);\n  qdata << 3 << 2 << 0 << arma::endr << 5 << 3 << 4 << arma::endr;\n\n  // INPUT TO LSH:\n  // Number of points: 10\n  // Number of dimensions: 2\n  // Number of projections per table: 'numProj' = 3\n  // Number of hash tables: 'numTables' = 2\n  // hashWidth (computed): 'hashWidth' = 4.24777\n  // Second hash size: 'secondHashSize' = 11\n  // Size of the bucket: 'bucketSize' = 3\n\n  // Things obtained by random sampling listed in the sequences\n  // as they will be obtained in the 'LSHSearch::BuildHash()' private function\n  // in 'LSHSearch' class.\n  //\n  // 1. The weights of the second hash obtained as:\n  //    secondHashWeights = arma::floor(arma::randu(3) * 11.0);\n  //    COR.SOL.: secondHashWeights = [9, 4, 8];\n  //\n  // 2. The offsets for all the 3 projections in each of the 2 tables:\n  //    offsets.randu(3, 2)\n  //    COR.SOL.: [0.7984 0.3352; 0.9116 0.7682; 0.1976 0.2778]\n  //    offsets *= hashWidth\n  //    COR.SOL.: [3.3916 1.4240; 3.8725 3.2633; 0.8392 1.1799]\n  //\n  // 3. The  (2 x 3) projection matrices for the 2 tables:\n  //    projMat.randn(2, 3)\n  //    COR.SOL.: Proj. Mat 1: [2.7020 0.0187 0.4355; 1.3692 0.6933 0.0416]\n  //    COR.SOL.: Proj. Mat 2: [-0.3961 -0.2666 1.1001; 0.3895 -1.5118 -1.3964]\n  LSHSearch<> lsh_test(rdata, 3, 2, hashWidth, 11, 3);\n//   LSHSearch<> lsh_test(rdata, qdata, 3, 2, 0.0, 11, 3);\n\n  // Given this, the 'LSHSearch::bucketRowInHashTable' should be:\n  // COR.SOL.: [2 11 4 7 6 3 11 0 5 1 8]\n  //\n  // The 'LSHSearch::bucketContentSize' should be:\n  // COR.SOL.: [2 0 1 1 3 1 0 3 3 3 1]\n  //\n  // The final hash table 'LSHSearch::secondHashTable' should be\n  // of size (3 x 9) with the following content:\n  // COR.SOL.:\n  // [0 2 4; 1 7 8; 3 9 10; 5 10 10; 6 10 10; 0 5 6; 1 2 8; 3 10 10; 4 10 10]\n\n  arma::Mat<size_t> neighbors;\n  arma::mat distances;\n\n  lsh_test.Search(qdata, 2, neighbors, distances);\n\n  // The private function 'LSHSearch::ReturnIndicesFromTable(0, refInds)'\n  // should hash the query 0 into the following buckets:\n  // COR.SOL.: Table 1 Bucket 7, Table 2 Bucket 0, refInds = [0 2 3 4 9]\n  //\n  // The private function 'LSHSearch::ReturnIndicesFromTable(1, refInds)'\n  // should hash the query 1 into the following buckets:\n  // COR.SOL.: Table 1 Bucket 9, Table 2 Bucket 4, refInds = [1 2 7 8]\n  //\n  // The private function 'LSHSearch::ReturnIndicesFromTable(2, refInds)'\n  // should hash the query 2 into the following buckets:\n  // COR.SOL.: Table 1 Bucket 0, Table 2 Bucket 7, refInds = [0 2 3 4 9]\n\n  // After search\n  // COR.SOL.: 'neighbors' = [2 1 9; 3 8 2]\n  // COR.SOL.: 'distances' = [2 0 2; 4 2 16]\n\n  arma::Mat<size_t> true_neighbors(2, 3);\n  true_neighbors << 2 << 1 << 9 << arma::endr << 3 << 8 << 2 << arma::endr;\n  arma::mat true_distances(2, 3);\n  true_distances << 2 << 0 << 2 << arma::endr << 4 << 2 << 16 << arma::endr;\n\n  for (size_t i = 0; i < 3; i++)\n  {\n    for (size_t j = 0; j < 2; j++)\n    {\n//      BOOST_REQUIRE_EQUAL(neighbors(j, i), true_neighbors(j, i));\n//      BOOST_REQUIRE_CLOSE(distances(j, i), true_distances(j, i), 1e-5);\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE(LSHTrainTest)\n{\n  // This is a not very good test that simply checks that the re-trained LSH\n  // model operates on the correct dimensionality and returns the correct number\n  // of results.\n  arma::mat referenceData = arma::randu<arma::mat>(3, 100);\n  arma::mat newReferenceData = arma::randu<arma::mat>(10, 400);\n  arma::mat queryData = arma::randu<arma::mat>(10, 200);\n\n  LSHSearch<> lsh(referenceData, 3, 2, 2.0, 11, 3);\n\n  lsh.Train(newReferenceData, 4, 3, 3.0, 12, 4);\n\n  arma::Mat<size_t> neighbors;\n  arma::mat distances;\n\n  lsh.Search(queryData, 3, neighbors, distances);\n\n  BOOST_REQUIRE_EQUAL(neighbors.n_cols, 200);\n  BOOST_REQUIRE_EQUAL(neighbors.n_rows, 3);\n  BOOST_REQUIRE_EQUAL(distances.n_cols, 200);\n  BOOST_REQUIRE_EQUAL(distances.n_rows, 3);\n}\n\nBOOST_AUTO_TEST_CASE(EmptyConstructorTest)\n{\n  // If we create an empty LSH model and then call Search(), it should throw an\n  // exception.\n  LSHSearch<> lsh;\n\n  arma::mat dataset = arma::randu<arma::mat>(5, 50);\n  arma::mat distances;\n  arma::Mat<size_t> neighbors;\n  BOOST_REQUIRE_THROW(lsh.Search(dataset, 2, neighbors, distances),\n      std::invalid_argument);\n\n  // Now, train.\n  lsh.Train(dataset, 4, 3, 3.0, 12, 4);\n\n  lsh.Search(dataset, 3, neighbors, distances);\n\n  BOOST_REQUIRE_EQUAL(neighbors.n_cols, 50);\n  BOOST_REQUIRE_EQUAL(neighbors.n_rows, 3);\n  BOOST_REQUIRE_EQUAL(distances.n_cols, 50);\n  BOOST_REQUIRE_EQUAL(distances.n_rows, 3);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "70c132d142a269bc0d4826fcf1478e07d806ed92", "size": 5293, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/lsh_test.cpp", "max_stars_repo_name": "decltypeme/mlpack", "max_stars_repo_head_hexsha": "e3b418918fffce382ce9d8ceee9d9349ca199611", "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-08-17T11:59:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-17T11:59:28.000Z", "max_issues_repo_path": "src/mlpack/tests/lsh_test.cpp", "max_issues_repo_name": "decltypeme/mlpack", "max_issues_repo_head_hexsha": "e3b418918fffce382ce9d8ceee9d9349ca199611", "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/tests/lsh_test.cpp", "max_forks_repo_name": "decltypeme/mlpack", "max_forks_repo_head_hexsha": "e3b418918fffce382ce9d8ceee9d9349ca199611", "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": 33.2893081761, "max_line_length": 80, "alphanum_fraction": 0.6463253353, "num_tokens": 1893, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4982189834260831}}
{"text": "#pragma once\n\n#include <boost/mpl/identity.hpp>\n#include <Eigen/Dense>\n#include <algorithm>\n#include <boost/multi_array.hpp>\n#include <boost/multiprecision/mpfr.hpp>\n#include <fstream>\n#include <iomanip>\n#include <stdexcept>\n\n#include \"spectral/hermiten.hpp\"\n#include \"spectral/mpfr/import_std_math.hpp\"\n\nnamespace boltzmann {\n\n// ----------------------------------------------------------------------\nnamespace detail {\ntemplate <typename NUMERIC_T>\nclass sentry\n{\n public:\n  typedef NUMERIC_T numeric_t;\n\n private:\n  typedef std::vector<numeric_t> vec_t;\n\n public:\n  sentry(int n) { this->init(n); }\n\n  sentry() { /* empty */}\n\n  void init(int n)\n  {\n    n_ = n;\n    factors_.resize(6);\n    std::for_each(factors_.begin(), factors_.end(), [&](vec_t& v) { v.reserve(n + 1); });\n  }\n\n  NUMERIC_T coeff(int i, int j, int t);\n  NUMERIC_T operator()(int i, int j, numeric_t x);\n\n private:\n  int n_;\n  std::vector<vec_t> factors_;\n};\n\n// ----------------------------------------------------------------------\ntemplate <typename NUMERIC_T>\nNUMERIC_T\nsentry<NUMERIC_T>::coeff(int i, int j, int t)\n{\n  const int maxij = std::max(i, j);\n  const int minij = std::min(i, j);\n  // (min(i,j) ... 1)\n  auto& v0 = factors_[0];\n  v0.resize(minij);\n  for (int k = 0; k < minij; ++k) {\n    v0[k] = std::min(i, j) - k;\n  }\n\n  //  sqrt(max(i,j) .. min(i,j)+1)\n  auto& v1 = factors_[1];\n  v1.resize(maxij - minij);\n  for (int k = 0; k < maxij - minij; ++k) {\n    v1[k] = ::math::sqrt(numeric_t(maxij - k));\n  }\n\n  // (i-t)!\n  auto& v2 = factors_[2];\n  v2.resize(i - t);\n  for (int k = 0; k < i - t; ++k) {\n    v2[k] = 1 / numeric_t(i - t - k);\n  }\n\n  // (j-t)!\n  auto& v3 = factors_[3];\n  v3.resize(j - t);\n  for (int k = 0; k < j - t; ++k) {\n    v3[k] = 1 / numeric_t(j - t - k);\n  }\n\n  // t!\n  auto& v4 = factors_[4];\n  v4.resize(t);\n  for (int k = 0; k < t; ++k) {\n    v4[k] = 1 / numeric_t(t - k);\n  }\n\n  // 2^(t-(i+j)/2)\n  auto& v5 = factors_[5];\n  int exp2 = t - (i + j) / 2;\n  v5.resize(std::abs(exp2));\n  if (exp2 > 0)\n    for (unsigned int k = 0; k < v5.size(); ++k) {\n      v5[k] = 2;\n    }\n  else\n    for (unsigned int k = 0; k < v5.size(); ++k) {\n      v5[k] = 1 / numeric_t(2);\n    }\n  // cout << \"v5:\\t\";\n  // for_each(v5.begin(), v5.end(), [](numeric_t v) { cout << v << \"\\t\"; });\n  // cout << endl;\n\n  std::sort(factors_.begin(), factors_.end(), [](const vec_t& v1, const vec_t& v2) {\n    return v1.size() < v2.size();\n  });\n  std::vector<int> lengths;\n  std::for_each(\n      factors_.begin(), factors_.end(), [&](const vec_t& v) { lengths.push_back(v.size()); });\n\n  numeric_t f = (std::abs(i - t) % 2) ? -1 : 1;\n  // multiply\n  for (int jp = 0; jp < lengths[0]; ++jp) {\n    numeric_t loc = 1;\n    for (unsigned int fi = 0; fi < factors_.size(); ++fi) {\n      loc *= factors_[fi][jp];\n    }\n    f *= loc;\n  }\n  for (unsigned int l = 1; l < lengths.size(); ++l) {\n    for (int jp = lengths[l - 1]; jp < lengths[l]; ++jp) {  // loop over remaining positions\n      numeric_t loc = 1;\n      for (unsigned int fi = l; fi < factors_.size(); ++fi) {\n        loc *= factors_[fi][jp];\n      }\n      f *= loc;\n    }\n  }\n\n  // 2^(t-(i+j)/2) missing term\n  if ((i + j) % 2 && exp2 <= 0)\n    f /= ::math::sqrt(numeric_t(2));\n  else if ((i + j) % 2 && exp2 > 0)\n    f *= ::math::sqrt(numeric_t(2));\n\n  return f;\n}\n\n// ----------------------------------------------------------------------\ntemplate <typename NUMERIC_T>\nNUMERIC_T\nsentry<NUMERIC_T>::operator()(int i, int j, numeric_t x)\n{\n  numeric_t sum = 0;\n\n  // TOOD implement Horner's scheme\n  for (int l = std::abs(i - j); l <= i + j; l += 2) {\n    numeric_t loc = this->coeff(i, j, (i + j - l) / 2);\n\n    sum += loc * ::math::pow(x, l);\n  }\n\n  return sum * ::math::exp(numeric_t(-x * x / 4));\n  ;\n}\n\n/**\n * @brief polyval (Horner scheme)\n *\n * @param coeffs\n * @param x\n * @param N length of coeffs\n */\ntemplate <typename NUMERIC_T>\ninline NUMERIC_T\npolyval(NUMERIC_T* coeffs, NUMERIC_T x, int N)\n{\n  typedef NUMERIC_T numeric_t;\n  numeric_t b = coeffs[N - 1];\n  for (int i = 1; i < N - 1; ++i) {\n    b = coeffs[N - 1 - i] + b * x;\n  }\n  return x * b + coeffs[0];\n}\n\n}  // end namespace detail\n\n// ----------------------------------------------------------------------\n/**\n * @brief Assemble shift matrix \\f$ S^{\\bar{x}}\\f$.\n *\n * @tparam NUMERIC_T numeric type\n *\n */\ntemplate <typename NUMERIC_T>\nclass HShiftMatrix\n{\n private:\n  typedef NUMERIC_T numeric_t;\n  typedef std::vector<numeric_t> vec_t;\n\n public:\n  typedef Eigen::Matrix<numeric_t, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> matrix_t;\n\n public:\n  /**\n   *\n   * @param N  max polynomial degree\n   */\n  HShiftMatrix(int N) { this->init(N); }\n\n  HShiftMatrix() { /* empty */}\n\n  /**\n   * Compute polynomial coefficients of p(i,j;x)\n   *\n   */\n  void init(int N);\n\n  /**\n   * Create linear Operator S^x by evaluating the polynomial\n   *\n   * @param x\n   */\n  void setx(numeric_t x);\n\n  const matrix_t& get() const { return S_; }\n  void dump(std::string fname) const;\n\n private:\n  int size_;\n  boost::multi_array<numeric_t, 3> coeffs_;\n  /* compute coefficients of the S_-entry polynomial */\n  detail::sentry<numeric_t> G_;\n  matrix_t S_;\n};\n\n// ----------------------------------------------------------------------\ntemplate <typename NUMERIC_T>\nvoid\nHShiftMatrix<NUMERIC_T>::init(int N)\n{\n  size_ = N + 1;\n  G_.init(N + 1);\n  S_.resize(N + 1, N + 1);\n  coeffs_.resize(boost::extents[size_][size_][2 * size_ - 1]);\n\n  // std::fill(coeffs_.origin(), coeffs_.origin() + coeffs_.num_elements(), 0);\n  for (int i = 0; i < size_; ++i) {\n    for (int j = 0; j < size_; ++j) {\n      for (int l = std::abs(i - j); l <= i + j; l += 2) {\n        coeffs_[i][j][l] = G_.coeff(i, j, (i + j - l) / numeric_t(2));\n      }\n    }\n  }\n}\n\n// ----------------------------------------------------------------------\ntemplate <typename NUMERIC_T>\nvoid\nHShiftMatrix<NUMERIC_T>::setx(numeric_t x)\n{\n  // Hint: polyval can be further optimized by using knowledge\n  //       about which coefficients are zero.\n  numeric_t f = ::math::exp(numeric_t(-x * x / 4));\n  for (int i = 0; i < size_; ++i) {\n    for (int j = 0; j < size_; ++j) {\n      S_(i, j) = f * detail::polyval(coeffs_[i][j].origin(), x, coeffs_.shape()[2]);\n    }\n  }\n}\n\n// ----------------------------------------------------------------------\ntemplate <typename NUMERIC_T>\nvoid\nHShiftMatrix<NUMERIC_T>::dump(std::string fname) const\n{\n  std::ofstream fout(fname);\n  fout << std::setprecision(10);\n  fout << std::scientific;\n  fout << S_;\n  fout.close();\n}\n\n}  // end namespace boltzmann\n", "meta": {"hexsha": "0834262d0fd16b032f75b7a3bc6efd883292e3f3", "size": 6530, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "spectral/shift_hermite.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/shift_hermite.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/shift_hermite.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": 23.4892086331, "max_line_length": 94, "alphanum_fraction": 0.5234303216, "num_tokens": 2077, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.6477982247516797, "lm_q1q2_score": 0.4982088191233101}}
{"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_FUNCTION_DIVS_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_DIVS_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-arithmetic\n    Function object implementing divs capabilities\n\n    Computes  the truncated saturated division of its parameters.\n\n    @par semantic:\n    For any given value @c x,  @c y of type @c T:\n\n    @code\n    T r = divs(x, y);\n    @endcode\n\n    The code is similar to:\n\n    @code\n    T r = trunc(x/y);\n    @endcode\n\n    for integral types, if y is @ref Zero, it returns @ref Valmax (resp. @ref Valmin)\n    if x is positive (resp. negative) and @ref Zero if x is @ref Zero.\n\n    Saturated means that for signed integer types,\n    @c divs(Valmin,-1) returns @ref Valmax.\n\n    @par Alias\n\n    @c rdivide\n\n    @see  divides, rec, divfloor, divceil, divround, divround2even, divfix\n\n  **/\n  const boost::dispatch::functor<tag::divs_> divs = {};\n} }\n#endif\n\n#include <boost/simd/function/scalar/divs.hpp>\n#include <boost/simd/function/simd/divs.hpp>\n\n#endif\n", "meta": {"hexsha": "b96809f4511f2237bd289c6e046d0bc20ce8cc14", "size": 1461, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/divs.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/function/divs.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/function/divs.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": 24.35, "max_line_length": 100, "alphanum_fraction": 0.5954825462, "num_tokens": 356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.647798211152541, "lm_q1q2_score": 0.49820880866448114}}
{"text": "#include <boost/variant.hpp>\n#include <vector>\n#include <string>\n#include <iostream>\n\n// This typedefs and methods will be in header,\n// that wraps around native SQL interface.\ntypedef boost::variant<int, float, std::string> cell_t;\ntypedef std::vector<cell_t> db_row_t;\n\n// This is just an example, no actual work with database.\ndb_row_t get_row(const char* /*query*/) {\n    // See recipe \"Type 'reference to string'\"\n    // for a better type for 'query' parameter.\n    db_row_t row;\n    row.push_back(10);\n    row.push_back(10.1f);\n    row.push_back(\"hello again\");\n    return row;\n}\n\n// This is how code required to sum values\n// We can provide no template parameter\n// to boost::static_visitor<> if our visitor returns nothing.\nstruct db_sum_visitor: public boost::static_visitor<double> {\n    double operator()(int value) const {\n        return value;\n    }\n    double operator()(float value) const {\n        return value;\n    }\n    double operator()(const std::string& /*value*/) const {\n        return 0.0;\n    }\n};\n\nint main() {\n    db_row_t row = get_row(\"Query: Give me some row, please.\");\n    double res = 0.0;\n    for (db_row_t::const_iterator it = row.begin(), end = row.end(); it != end; ++it) {\n        res += boost::apply_visitor(db_sum_visitor(), *it);\n    }\n    std::cout << \"Sum of arithmetic types in database row is: \" << res << std::endl;\n}\n", "meta": {"hexsha": "04c859b7553ba476320c4f874d3d90ab1f450dbb", "size": 1364, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Chapter01/04_B_variant_db_example/main.cpp", "max_stars_repo_name": "PacktPublishing/Boost-Cpp-Application-Development-Cookbook-Second-Edition", "max_stars_repo_head_hexsha": "ffea2895138d3af1f4e35d657a726f6bd55b9030", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 33.0, "max_stars_repo_stars_event_min_datetime": "2017-10-29T23:05:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T09:36:42.000Z", "max_issues_repo_path": "Chapter01/04_B_variant_db_example/main.cpp", "max_issues_repo_name": "PacktPublishing/Boost-Cpp-Application-Development-Cookbook-Second-Edition", "max_issues_repo_head_hexsha": "ffea2895138d3af1f4e35d657a726f6bd55b9030", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter01/04_B_variant_db_example/main.cpp", "max_forks_repo_name": "PacktPublishing/Boost-Cpp-Application-Development-Cookbook-Second-Edition", "max_forks_repo_head_hexsha": "ffea2895138d3af1f4e35d657a726f6bd55b9030", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2017-09-07T18:47:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T09:37:39.000Z", "avg_line_length": 30.3111111111, "max_line_length": 87, "alphanum_fraction": 0.6554252199, "num_tokens": 345, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.49820879657777534}}
{"text": "#include <aslam/backend/ScalarDesignVariable.hpp>\n#include <aslam/backend/ErrorTermObservation.hpp>\n#include <aslam/backend/ErrorTermMotion.hpp>\n#include <aslam/backend/ErrorTermPrior.hpp>\n#include <aslam/backend/OptimizationProblem.hpp>\n#include <aslam/backend/Optimizer.hpp>\n#include <iostream>\n// Bring in some random number generation from Schweizer Messer.\n#include <sm/random.hpp>\n#include <vector>\n#include <algorithm>\n#include <boost/foreach.hpp>\n\n\nint main(int argc, char ** argv)\n{\n  if(argc != 2)\n    {\n      std::cout << \"Usage: example K\\n\";\n      std::cout << \"The argument K is the number of timesteps to include in the optimization\\n\";\n      return 1;\n    }\n\n  const int K = atoi(argv[1]);\n\n  try \n    {\n      // The true wall position\n      const double true_w = -5.0;\n      \n      // The noise properties.\n      const double sigma_n = 0.01;\n      const double sigma_u = 0.1;\n      const double sigma_x = 0.01;\n\n      // Create random odometry\n      std::vector<double> true_u_k(K);\n      BOOST_FOREACH(double & u, true_u_k)\n\t{\n\t  u = sm::random::uniform();\n\t}\n      \n      // Create the noisy odometry\n      std::vector<double> u_k(K);\n      for(int k = 0; k < K; ++k)\n\t{\n\t  u_k[k] = true_u_k[k] + sigma_u * sm::random::normal();\n\t}\n\n      // Create the states from noisy odometry.\n      std::vector<double> x_k(K);\n      std::vector<double> true_x_k(K);\n      x_k[0] = 0.0;\n      true_x_k[0] = 0.0;\n      for(int k = 1; k < K; ++k)\n\t{\n\t  true_x_k[k] = true_x_k[k-1] + true_u_k[k];\n\t  x_k[k] = x_k[k-1] + u_k[k];\n\t}\n\n\n      // Create the noisy measurments\n      std::vector<double> y_k(K);\n      for(int k = 0; k < K; ++k)\n\t{\n\t  y_k[k] = (1.0 / (true_w - true_x_k[k])) + sigma_n * sm::random::normal();\n\t}\n      \n      // Now we can build an optimization problem.\n      boost::shared_ptr<aslam::backend::OptimizationProblem> problem( new aslam::backend::OptimizationProblem);\n      \n      // First, create a design variable for the wall position.\n      boost::shared_ptr<aslam::backend::ScalarDesignVariable> dv_w(new aslam::backend::ScalarDesignVariable(true_w + sm::random::normal()));\n      // Setting this active means we estimate it.\n      dv_w->setActive(true);\n      // Add it to the optimization problem.\n      problem->addDesignVariable(dv_w);\n\n      // Now we add the initial state.\n      boost::shared_ptr<aslam::backend::ScalarDesignVariable> dv_x_km1(new aslam::backend::ScalarDesignVariable(x_k[0]));\n      // Setting this active means we estimate it.\n      dv_x_km1->setActive(true);\n      // Add it to the optimization problem.\n      problem->addDesignVariable(dv_x_km1);\n\n      // Now create a prior for this initial state.\n      boost::shared_ptr<aslam::backend::ErrorTermPrior> prior(new aslam::backend::ErrorTermPrior(dv_x_km1.get(), true_x_k[0], sigma_x * sigma_x));\n      // and add it to the problem.\n      problem->addErrorTerm(prior);\n      \n      // Now march through the states creating design variables,\n      // odometry error terms and measurement error terms.\n      for(int k = 1; k < K; ++k)\n\t{\n\t  boost::shared_ptr<aslam::backend::ScalarDesignVariable> dv_x_k(new aslam::backend::ScalarDesignVariable(x_k[k]));\n\t  dv_x_k->setActive(true);\n\t  problem->addDesignVariable(dv_x_k);\n\n\t  // Create odometry error\n\t  boost::shared_ptr<aslam::backend::ErrorTermMotion> em(new aslam::backend::ErrorTermMotion(dv_x_km1.get(), dv_x_k.get(), u_k[k], sigma_u * sigma_u));\n\t  problem->addErrorTerm(em);\n\t  \n\t  // Create observation error\n\t  boost::shared_ptr<aslam::backend::ErrorTermObservation> eo(new aslam::backend::ErrorTermObservation(dv_x_k.get(), dv_w.get(), y_k[k], sigma_n * sigma_n));\n\t  problem->addErrorTerm(eo);\n\t  \n\t  // Move this design variable to the x_{k-1} position for use in the next loop.\n\t  dv_x_km1 = dv_x_k;\n\t}\n\n      // Now we have a valid optimization problem full of design variables and error terms.\n      // Create some optimization options.\n      aslam::backend::OptimizerOptions options;\n      options.verbose = true;\n      options.linearSolver = \"cholmod\";\n      options.levenbergMarquardtLambdaInit = 10;\n      options.doSchurComplement = false;\n      options.doLevenbergMarquardt = true;\n      // Force it to over-optimize\n      options.convergenceDeltaX = 1e-12;\n      options.convergenceDeltaJ = 1e-12;\n      // Then create the optimizer and go!\n      aslam::backend::Optimizer optimizer(options);\n      optimizer.setProblem( problem );\n      optimizer.optimize();\n\n      \n    }\n  catch(const std::exception & e)\n    {\n      std::cout << \"Exception during processing: \" << e.what();\n      return 1;\n    }\n\n  std::cout << \"Processing completed successfully\\n\";\n  return 0;\n}\n", "meta": {"hexsha": "f78270df66cdb455b9014a26ef48bf35ae42a703", "size": 4649, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "aslam_backend_tutorial/src/example.cpp", "max_stars_repo_name": "ethz-asl/aslam_optimizer", "max_stars_repo_head_hexsha": "8e9dd18f9f0d8af461e88e108a3beda2003daf11", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 33.0, "max_stars_repo_stars_event_min_datetime": "2017-04-26T13:30:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T01:52:22.000Z", "max_issues_repo_path": "aslam_backend_tutorial/src/example.cpp", "max_issues_repo_name": "ethz-asl/aslam_optimizer", "max_issues_repo_head_hexsha": "8e9dd18f9f0d8af461e88e108a3beda2003daf11", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 15.0, "max_issues_repo_issues_event_min_datetime": "2017-02-14T16:02:31.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-12T06:07:22.000Z", "max_forks_repo_path": "aslam_backend_tutorial/src/example.cpp", "max_forks_repo_name": "ethz-asl/aslam_optimizer", "max_forks_repo_head_hexsha": "8e9dd18f9f0d8af461e88e108a3beda2003daf11", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-06-28T04:17:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-10T04:58:36.000Z", "avg_line_length": 33.6884057971, "max_line_length": 157, "alphanum_fraction": 0.6536889654, "num_tokens": 1249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.4981807732570775}}
{"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_ISQRT_HPP_INCLUDED\n#define BOOST_SIMD_ARITHMETIC_FUNCTIONS_SCALAR_ISQRT_HPP_INCLUDED\n\n#include <boost/simd/arithmetic/functions/isqrt.hpp>\n#include <boost/simd/include/functions/scalar/is_ltz.hpp>\n#include <boost/simd/include/functions/scalar/sqrt.hpp>\n#include <boost/simd/include/functions/scalar/toint.hpp>\n#include <boost/simd/include/constants/zero.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::isqrt_, tag::cpu_\n                            , (A0)\n                            , (scalar_< arithmetic_<A0> >)\n                            )\n  {\n    typedef typename  dispatch::meta::as_integer<A0>::type result_type;\n    BOOST_SIMD_FUNCTOR_CALL(1)\n    {\n      return itrunc(boost::simd::sqrt(a0));\n    }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::isqrt_, tag::cpu_\n                            , (A0)\n                            , (scalar_< uint_<A0> >)\n                            )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL(1)\n    {\n      return static_cast<A0>(boost::simd::sqrt(result_type(a0)));\n    }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::isqrt_, tag::cpu_\n                            , (A0)\n                            , (scalar_< int_<A0> >)\n                            )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL(1)\n    {\n      return (is_ltz(a0)) ?  Zero<A0>() : static_cast<A0>(boost::simd::sqrt(result_type(a0)));\n    }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "882c53652d62eb436ffc5e9a74801f9558230a88", "size": 2092, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/arithmetic/include/boost/simd/arithmetic/functions/scalar/isqrt.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/scalar/isqrt.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/scalar/isqrt.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": 34.8666666667, "max_line_length": 94, "alphanum_fraction": 0.5535372849, "num_tokens": 492, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.49818076215525053}}
{"text": "#include \"Common.h\"\n#include \"CPS3.h\"\n#include \"PropertiesHolder/PropertiesHolder.h\"\n#include \"Material.h\"\n#include <Eigen/Dense>\n\nvoid CPS3::SetIndices(const std::vector<int>& indices)\n{\n\tassert(indices.size() == 3);\n\tm_nodes[0] = indices[0];\n\tm_nodes[1] = indices[1];\n\tm_nodes[2] = indices[2];\n}\n\nstd::vector<int> CPS3::GetIndices() const\n{\n\tstd::vector<int> indices(3);\n\tindices[0] = m_nodes[0];\n\tindices[1] = m_nodes[1];\n\tindices[2] = m_nodes[2];\n\treturn indices;\n}\n\nstd::vector<Eigen::Vector3f> CPS3::GetFunctionValuesAtNodes(const Eigen::VectorXf& deforms)const\n{\n\tEigen::Matrix<float, 6, 1> uv;\n\tfor (int i = 0; i < 3; ++i)\n\t{\n\t\tuv[2 * i + 0] = deforms[2 * m_nodes[i] + 0];\n\t\tuv[2 * i + 1] = deforms[2 * m_nodes[i] + 1];\n\t}\n\n\tEigen::Vector3f strain = m_B * uv;\n\t\n\tstd::vector<Eigen::Vector3f> output;\n\tfor (int i = 0; i < 3; i++)\n\t{\n\t\toutput.push_back(strain);\n\t}\n\treturn output;\n}\n\nvoid CPS3::CalcK(const StrideDataArray& nodes, const tfem::MaterialPtr mat, std::vector<Eigen::Triplet<float> >& tripletVector)\n{\n\tm_mat = mat;\n\tEigen::Vector3f x;\n\tEigen::Vector3f y;\n\tfor (int i = 0; i < 3; ++i)\n\t{\n\t\tx[i] = nodes(m_nodes[i], 0);\n\t\ty[i] = nodes(m_nodes[i], 1);\n\t}\n\tEigen::Matrix3f C;\n\tC << Eigen::Vector3f(1.0f, 1.0f, 1.0f), x, y;\n\n\tfloat area = C.determinant() / 2.0f;\n\n\tEigen::Matrix3f IC = C.inverse();\n\t\n\tfor (int i = 0; i < 3; i++)\n\t{\n\t\tm_B(0, 2 * i + 0) = IC(1, i);\n\t\tm_B(0, 2 * i + 1) = 0.0f;\n\t\tm_B(1, 2 * i + 0) = 0.0f;\n\t\tm_B(1, 2 * i + 1) = IC(2, i);\n\t\tm_B(2, 2 * i + 0) = IC(2, i);\n\t\tm_B(2, 2 * i + 1) = IC(1, i);\n\t}\n\tEigen::Matrix<float, 6, 6> K = m_B.transpose() * mat->GetElasticityMatrix(fem::PT_FlatStress) * m_B * area;\n\tGrabTriplets(K, tripletVector);\n}\n\nvoid CPS3::GrabTriplets(const Eigen::Matrix<float, 6, 6>& K, std::vector<Eigen::Triplet<float> >& tripletVector) const\n{\n\tfor (int i = 0; i < 3; i++)\n\t{\n\t\tfor (int j = 0; j < 3; j++)\n\t\t{\n\t\t\tEigen::Triplet<float> trplt11(2 * m_nodes[i] + 0, 2 * m_nodes[j] + 0, K(2 * i + 0, 2 * j + 0));\n\t\t\tEigen::Triplet<float> trplt12(2 * m_nodes[i] + 0, 2 * m_nodes[j] + 1, K(2 * i + 0, 2 * j + 1));\n\t\t\tEigen::Triplet<float> trplt21(2 * m_nodes[i] + 1, 2 * m_nodes[j] + 0, K(2 * i + 1, 2 * j + 0));\n\t\t\tEigen::Triplet<float> trplt22(2 * m_nodes[i] + 1, 2 * m_nodes[j] + 1, K(2 * i + 1, 2 * j + 1));\n\n\t\t\ttripletVector.push_back(trplt11);\n\t\t\ttripletVector.push_back(trplt12);\n\t\t\ttripletVector.push_back(trplt21);\n\t\t\ttripletVector.push_back(trplt22);\n\t\t}\n\t}\n}\n\ntfem::Material* CPS3::GetMaterial()\n{\n\treturn m_mat.get();\n}\n\nIElement* CPS3::Create()\n{\n\treturn new CPS3;\n}\n\nCPS3::CPS3()\n{\n\n}", "meta": {"hexsha": "9eaa6598b8d194b51e60bfb8ddb86aedf0750184", "size": 2548, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sources/Elements/CPS3.cpp", "max_stars_repo_name": "podgorskiy/TinyFEM", "max_stars_repo_head_hexsha": "c1a5fedf21e6306fc11fa19afdaf48dab1b6740f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2017-11-05T14:01:04.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-11T15:24:54.000Z", "max_issues_repo_path": "sources/Elements/CPS3.cpp", "max_issues_repo_name": "podgorskiy/TinyFEM", "max_issues_repo_head_hexsha": "c1a5fedf21e6306fc11fa19afdaf48dab1b6740f", "max_issues_repo_licenses": ["MIT"], "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/Elements/CPS3.cpp", "max_forks_repo_name": "podgorskiy/TinyFEM", "max_forks_repo_head_hexsha": "c1a5fedf21e6306fc11fa19afdaf48dab1b6740f", "max_forks_repo_licenses": ["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.2666666667, "max_line_length": 127, "alphanum_fraction": 0.5973312402, "num_tokens": 1045, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4981663065862324}}
{"text": "#include <engine/Solver_Kernels.hpp>\n#include <utility/Constants.hpp>\n#include <Eigen/Dense>\n#include <engine/Backend_par.hpp>\n\nusing namespace Utility;\nusing Utility::Constants::Pi;\n\nnamespace Engine\n{\nnamespace Solver_Kernels\n{\n\n    void sib_transform(const vectorfield & spins, const vectorfield & force, vectorfield & out)\n    {\n        int n = spins.size();\n\n        auto s = spins.data();\n        auto f = force.data();\n        auto o = out.data();\n\n        Backend::par::apply( n, [s,f,o] SPIRIT_LAMBDA (int idx) {\n            Vector3 e1, a2, A;\n            scalar detAi;\n            e1 = s[idx];\n            A = 0.5 * f[idx];\n\n            // 1/determinant(A)\n            detAi = 1.0 / (1 + pow(A.norm(), 2.0));\n\n            // calculate equation witho the predictor?\n            a2 = e1 - e1.cross(A);\n\n            o[idx][0] = (a2[0] * (A[0] * A[0] + 1   ) + a2[1] * (A[0] * A[1] - A[2]) + a2[2] * (A[0] * A[2] + A[1])) * detAi;\n            o[idx][1] = (a2[0] * (A[1] * A[0] + A[2]) + a2[1] * (A[1] * A[1] + 1   ) + a2[2] * (A[1] * A[2] - A[0])) * detAi;\n            o[idx][2] = (a2[0] * (A[2] * A[0] - A[1]) + a2[1] * (A[2] * A[1] + A[0]) + a2[2] * (A[2] * A[2] + 1   )) * detAi;\n        } );\n    }\n\n    void oso_calc_gradients(vectorfield & grad, const vectorfield & spins, const vectorfield & forces)\n    {\n        const Matrix3 t = ( Matrix3() << 0,0,1,0,-1,0,1,0,0 ).finished();\n\n        auto g=grad.data();\n        auto s=spins.data();\n        auto f=forces.data();\n\n        Backend::par::apply( spins.size(), [g,s,f,t] SPIRIT_LAMBDA (int idx)\n            {\n                g[idx] = t * (-s[idx].cross(f[idx]));\n            }\n        );\n    }\n\n    void oso_rotate( std::vector<std::shared_ptr<vectorfield>> & configurations, std::vector<vectorfield> & searchdir)\n    {\n        int noi = configurations.size();\n        int nos = configurations[0]->size();\n        for(int img=0; img<noi; ++img)\n        {\n\n            auto s  = configurations[img]->data();\n            auto sd = searchdir[img].data();\n            \n            Backend::par::apply( nos, [s, sd] SPIRIT_LAMBDA (int idx) \n                {\n                    scalar theta = (sd[idx]).norm();\n                    scalar q = cos(theta), w = 1-q, \n                           x = -sd[idx][0]/theta, y = -sd[idx][1]/theta, z = -sd[idx][2]/theta,\n                           s1 = -y*z*w, s2 = x*z*w, s3 = -x*y*w,\n                           p1 = x*sin(theta), p2 = y*sin(theta), p3 = z*sin(theta);\n\n                    scalar t1, t2, t3;\n                    if(theta > 1.0e-20) // if theta is too small we do nothing\n                    {\n                        t1 = (q+z*z*w) * s[idx][0] + (s1+p1)   * s[idx][1] + (s2+p2)   * s[idx][2];\n                        t2 = (s1-p1)   * s[idx][0] + (q+y*y*w) * s[idx][1] + (s3+p3)   * s[idx][2];\n                        t3 = (s2-p2)   * s[idx][0] + (s3-p3)   * s[idx][1] + (q+x*x*w) * s[idx][2];\n                        s[idx][0] = t1;\n                        s[idx][1] = t2;\n                        s[idx][2] = t3;\n                    };\n                }\n            );\n        }\n    }\n\n    scalar maximum_rotation(const vectorfield & searchdir, scalar maxmove)\n    {\n        int nos = searchdir.size();\n        scalar theta_rms = 0;\n        theta_rms = sqrt( Backend::par::reduce(searchdir, [] SPIRIT_LAMBDA (const Vector3 & v){ return v.squaredNorm(); }) / nos );\n        scalar scaling = (theta_rms > maxmove) ? maxmove/theta_rms : 1.0;\n        return scaling;\n    }\n\n    void atlas_rotate(std::vector<std::shared_ptr<vectorfield>> & configurations, const std::vector<scalarfield> & a3_coords, const std::vector<vector2field> & searchdir)\n    {\n        int noi = configurations.size();\n        int nos = configurations[0]->size();\n        for(int img=0; img<noi; img++ )\n        {\n            auto spins = configurations[img]->data();\n            auto d     = searchdir[img].data();\n            auto a3    = a3_coords[img].data();\n            Backend::par::apply(nos, [nos, spins, d, a3] SPIRIT_LAMBDA (int idx) {\n                const scalar gamma = (1 + spins[idx][2] * a3[idx]);\n                const scalar denom = (spins[idx].head<2>().squaredNorm())/gamma + 2 * d[idx].dot( spins[idx].head<2>() ) + gamma * d[idx].squaredNorm();\n                spins[idx].head<2>() = 2*(spins[idx].head<2>() + d[idx]*gamma);\n                spins[idx][2] = a3[idx] * (gamma - denom);\n                spins[idx] *= 1/(gamma + denom);\n            } );\n        }\n    }\n\n    void atlas_calc_gradients(vector2field & residuals, const vectorfield & spins, const vectorfield & forces, const scalarfield & a3_coords)\n    {\n        auto s = spins.data();\n        auto a3 = a3_coords.data();\n        auto g = residuals.data();\n        auto f = forces.data();\n\n        Backend::par::apply(spins.size(), [s, a3, g, f] SPIRIT_LAMBDA (int idx) {\n\n            scalar J00 =  s[idx][1] * s[idx][1] + s[idx][2]*(s[idx][2] + a3[idx]);\n            scalar J10 = -s[idx][0] * s[idx][1];\n            scalar J01 = -s[idx][0] * s[idx][1];\n            scalar J11 =  s[idx][0] * s[idx][0]  + s[idx][2]*(s[idx][2] + a3[idx]);\n            scalar J02 = -s[idx][0] * (s[idx][2] + a3[idx]);\n            scalar J12 = -s[idx][1] * (s[idx][2] + a3[idx]);\n\n            g[idx][0] = -(J00 * f[idx][0] + J01 * f[idx][1] + J02 * f[idx][2]);\n            g[idx][1] = -(J10 * f[idx][0] + J11 * f[idx][1] + J12 * f[idx][2]);\n        });\n    }\n\n    bool ncg_atlas_check_coordinates(const std::vector<std::shared_ptr<vectorfield>> & spins, std::vector<scalarfield> & a3_coords, scalar tol)\n    {\n        int noi = spins.size();\n        int nos = (*spins[0]).size();\n\n        // We use `int` instead of `bool`, because somehow cuda does not like pointers to bool\n        // TODO: fix in future\n        field<int> result = field<int>(1, int(false));\n\n        for(int img=0; img<noi; img++)\n        {\n            auto s = spins[0]->data();\n            auto a3 = a3_coords[img].data();\n            int *res = &result[0];\n\n            Backend::par::apply( nos, [s, a3, tol, res] SPIRIT_LAMBDA (int idx) {\n                    if (s[idx][2]*a3[idx] < tol && res[0] == int(false))\n                        res[0] = int(true);\n            } );\n        }\n\n        return bool(result[0]);\n    }\n\n    void lbfgs_atlas_transform_direction(std::vector<std::shared_ptr<vectorfield>> & configurations, std::vector<scalarfield> & a3_coords, std::vector<field<vector2field>> & atlas_updates, std::vector<field<vector2field>> & grad_updates, std::vector<vector2field> & searchdir, std::vector<vector2field> & grad_pr, scalarfield & rho)\n    {\n        int noi = configurations.size();\n        int nos = configurations[0]->size();\n\n        for(int n=0; n<atlas_updates[0].size(); n++)\n        {\n            rho[n] = 1/rho[n];\n        }\n        \n        for(int img=0; img<noi; img++)\n        {\n            auto s = (*configurations[img]).data();\n            auto a3 = a3_coords[img].data();\n            auto sd = searchdir[img].data();\n            auto g_pr = grad_pr[img].data();\n            auto rh = rho.data();\n\n            auto n_mem = atlas_updates[img].size();\n\n            field<Vector2*> t1(n_mem), t2(n_mem);\n            for(int n=0; n<n_mem; n++)\n            {\n                t1[n] = (atlas_updates[img][n].data());\n                t2[n] = (grad_updates[img][n].data());\n            }\n\n            auto a_up = t1.data();\n            auto g_up = t2.data();\n\n            Backend::par::apply(nos, [s, a3, sd, g_pr, rh, a_up, g_up, n_mem] SPIRIT_LAMBDA (int idx) {\n                scalar factor = 1;\n                if( s[idx][2]*a3[idx] < 0 )\n                {\n                    // Transform coordinates to optimal map\n                    a3[idx] = (s[idx][2] > 0) ? 1 : -1;\n                    factor  = (1 - a3[idx] * s[idx][2]) / (1 + a3[idx] * s[idx][2]);\n                    sd[idx]   *= factor;\n                    g_pr[idx] *= factor;\n\n                    for(int n=0; n<n_mem; n++)\n                    {\n                        rh[n] = rh[n] + (factor*factor-1) * a_up[n][idx].dot(g_up[n][idx]);\n                        a_up[n][idx] *= factor;\n                        g_up[n][idx] *= factor;\n                    }\n                }\n            });\n        }\n\n        for(int n=0; n<atlas_updates[0].size(); n++)\n        {\n            rho[n] = 1/rho[n];\n        }\n    }\n}\n}", "meta": {"hexsha": "a2ff7296c8f0a65358d92138605bc513951ed92e", "size": 8331, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "core/src/engine/Solver_Kernels.cpp", "max_stars_repo_name": "bck2302000/spirit", "max_stars_repo_head_hexsha": "14ed7782bd23f4828bf23ab8136ae31a21037bb3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 92.0, "max_stars_repo_stars_event_min_datetime": "2016-10-02T16:17:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T11:23:49.000Z", "max_issues_repo_path": "core/src/engine/Solver_Kernels.cpp", "max_issues_repo_name": "bck2302000/spirit", "max_issues_repo_head_hexsha": "14ed7782bd23f4828bf23ab8136ae31a21037bb3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 590.0, "max_issues_repo_issues_event_min_datetime": "2016-09-24T12:46:36.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-24T18:27:18.000Z", "max_forks_repo_path": "core/src/engine/Solver_Kernels.cpp", "max_forks_repo_name": "bck2302000/spirit", "max_forks_repo_head_hexsha": "14ed7782bd23f4828bf23ab8136ae31a21037bb3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 46.0, "max_forks_repo_forks_event_min_datetime": "2016-09-26T07:20:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T19:55:17.000Z", "avg_line_length": 38.3917050691, "max_line_length": 332, "alphanum_fraction": 0.4627295643, "num_tokens": 2478, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424334245618, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.49816630429901476}}
{"text": "#include <NTL/GF2E.h>\n#include <NTL/GF2XFactoring.h>\n\n#include \"LHLExtractor.h\"\n\nuint32_t LHLExtractor::getInputLength() const {\n    return n_;\n}\n\nuint32_t LHLExtractor::getSeedLen() const {\n    return n_;\n}\n\nuint32_t LHLExtractor::getOutputLen() const {\n    return m_;\n}\n\ndouble LHLExtractor::getMinEntropy() const {\n    return k_;\n}\n\ndouble LHLExtractor::getError() const {\n    return error_;\n}\n\nBitstring LHLExtractor::extract(const WeakSource &input, const Bitstring &seed) const {\n    assert(input.getMinEntropy() >= k_);\n    assert(seed.size() == n_);\n    NTL::GF2EPush push;\n    NTL::GF2E::init(NTL::BuildSparseIrred_GF2X(n_));\n    auto x = input.getData().asGF2E();\n    auto y = seed.asGF2E();\n    return Bitstring((Bitstring(x) + Bitstring(y)).substr(0, m_));\n}\n\nLHLExtractor::LHLExtractor(uint32_t n, uint32_t k, double eps): n_(n), k_(k), error_(eps) {\n    m_ = ceil(k_ + n_ - 2 * log2(1. / error_));\n}\n", "meta": {"hexsha": "b4f75620807db7323d5892dc614910848de6c079", "size": 914, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "extractor/seeded/LHLExtractor.cpp", "max_stars_repo_name": "Skird/extractors", "max_stars_repo_head_hexsha": "3c55d2c8377f465a4960861b7f358b18214f5ac3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-06-11T17:19:48.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-11T17:19:48.000Z", "max_issues_repo_path": "extractor/seeded/LHLExtractor.cpp", "max_issues_repo_name": "Skird/extractors", "max_issues_repo_head_hexsha": "3c55d2c8377f465a4960861b7f358b18214f5ac3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "extractor/seeded/LHLExtractor.cpp", "max_forks_repo_name": "Skird/extractors", "max_forks_repo_head_hexsha": "3c55d2c8377f465a4960861b7f358b18214f5ac3", "max_forks_repo_licenses": ["Apache-2.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.4358974359, "max_line_length": 91, "alphanum_fraction": 0.6739606127, "num_tokens": 282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4981663020117971}}
{"text": "#include \"advent.hpp\"\n\n#include <cstdint>\n#include <fstream>\n#include <gsl/gsl_util>\n#include <iostream>\n#include <scn/scn.h>\n#include <Eigen/Dense>\n\nauto day05(int argc, char** argv) -> int\n{\n    std::ifstream infile(argv[1]); // NOLINT\n    std::string str;\n\n    using point = std::tuple<int64_t, int64_t>;\n    using line = std::pair<point, point>;\n    std::vector<line> lines;\n\n    while(std::getline(infile, str)) {\n        std::vector<std::string> tokens;\n        util::tokenize(str, ' ', tokens);\n        int x = 0;\n        int y = 0;\n        scn::scan(tokens[0], \"{},{}\", x, y);\n        point p1{x, y};\n        scn::scan(tokens[2], \"{},{}\", x, y);\n        point p2{x, y};\n        lines.emplace_back(p1, p2);\n    }\n\n    int64_t xmax = std::numeric_limits<int64_t>::min();\n    int64_t ymax = xmax;\n\n    for(auto [p1, p2] : lines) {\n        auto [x1, y1] = p1;\n        auto [x2, y2] = p2;\n        xmax = std::max({xmax, x1, x2});\n        ymax = std::max({ymax, y1, y2});\n    }\n\n    Eigen::Array<int, -1, -1> map = decltype(map)::Zero(xmax + 1, ymax + 1);\n    for (auto [p1, p2] : lines) {\n        auto [x1, y1] = p1;\n        auto [x2, y2] = p2;\n\n        if (x1 == x2 || y1 == y2 || std::abs(x1-x2) == std::abs(y1-y2)) {\n            auto dx = util::sgn(x2-x1);\n            auto dy = util::sgn(y2-y1);\n            for (auto x = x1, y = y1; (dx == 0 || x != x2) && (dy == 0 || y != y2); x += dx, y += dy) {\n                map(x, y) += 1;\n            }\n            map(x2, y2) += 1;\n        }\n    }\n    auto count = (map > 1).count();\n    fmt::print(\"count: {}\\n\", count);\n    \n    return 0;\n}\n", "meta": {"hexsha": "8b87abbdb560f6313cf6762e36c2156db4b28d9c", "size": 1594, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/day05.cpp", "max_stars_repo_name": "foolnotion/aoc2021", "max_stars_repo_head_hexsha": "e2bbcd8cab2a1a7b9922694daff7d289a905c133", "max_stars_repo_licenses": ["MIT"], "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/day05.cpp", "max_issues_repo_name": "foolnotion/aoc2021", "max_issues_repo_head_hexsha": "e2bbcd8cab2a1a7b9922694daff7d289a905c133", "max_issues_repo_licenses": ["MIT"], "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/day05.cpp", "max_forks_repo_name": "foolnotion/aoc2021", "max_forks_repo_head_hexsha": "e2bbcd8cab2a1a7b9922694daff7d289a905c133", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-29T23:05:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-29T23:05:48.000Z", "avg_line_length": 26.5666666667, "max_line_length": 103, "alphanum_fraction": 0.4755332497, "num_tokens": 543, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.4981461082042122}}
{"text": "/**TODO:  Add copyright*/\n\n#define BOOST_TEST_MODULE Preprocessing test suite \n#include <boost/test/included/unit_test.hpp>\n#include <EvoNet/core/Preprocessing.h>\n\nusing namespace EvoNet;\nusing namespace std;\n\nBOOST_AUTO_TEST_SUITE(preprocessing)\n\nBOOST_AUTO_TEST_CASE(P_selectRandomElement)\n{\n\t// [TODO: make test; currently, combined with selectRandomNode1]\n}\n\nBOOST_AUTO_TEST_CASE(P_UnitScaleFunctor)\n{\n\tEigen::Tensor<float, 2> data(2, 2);\n\tdata.setValues({{ 0, 2 }, { 3, 4 }});\n\tUnitScaleFunctor<float> unit_scale(data);\n\tBOOST_CHECK_CLOSE(unit_scale.getUnitScale(), 0.25, 1e-6);\n\n\tEigen::Tensor<float, 2> data_test = data.unaryExpr(UnitScaleFunctor<float>(data));\n\t\n\tBOOST_CHECK_CLOSE(data_test(0, 0), 0.0, 1e-6);\n\tBOOST_CHECK_CLOSE(data_test(1, 1), 1.0, 1e-6);\n}\n\nBOOST_AUTO_TEST_CASE(P_LinearScaleFunctor)\n{\n\tEigen::Tensor<float, 2> data(2, 2);\n\tdata.setValues({ { 0, 2 }, { 4, 8 } });\n\n\tEigen::Tensor<float, 2> data_test = data.unaryExpr(LinearScaleFunctor<float>(0, 8, -1, 1));\n\n\tBOOST_CHECK_CLOSE(data_test(0, 0), -1.0, 1e-6);\n\tBOOST_CHECK_CLOSE(data_test(0, 1), -0.5, 1e-6);\n\tBOOST_CHECK_CLOSE(data_test(1, 0), 0.0, 1e-6);\n\tBOOST_CHECK_CLOSE(data_test(1, 1), 1.0, 1e-6);\n}\n\nBOOST_AUTO_TEST_CASE(P_LinearScale)\n{\n  Eigen::Tensor<float, 3> data(2, 2, 2);\n  data.setValues({\n    {{ 0, 2 }, { 4, 8 }},\n    {{ 1, 1 }, { 3, 5 }}\n    });\n\n  // Test default initialization for the domain and setters\n  LinearScale<float, 3> linearScale1(-1, 1);\n  linearScale1.setDomain(0, 8);\n  Eigen::Tensor<float, 3> data_test = linearScale1(data);\n\n  BOOST_CHECK_CLOSE(data_test(0, 0, 0), -1.0, 1e-6);\n  BOOST_CHECK_CLOSE(data_test(0, 0, 1), -0.5, 1e-6);\n  BOOST_CHECK_CLOSE(data_test(0, 1, 0), 0.0, 1e-6);\n  BOOST_CHECK_CLOSE(data_test(0, 1, 1), 1.0, 1e-6);\n  BOOST_CHECK_CLOSE(data_test(1, 0, 0), -0.75, 1e-6);\n  BOOST_CHECK_CLOSE(data_test(1, 0, 1), -0.75, 1e-6);\n  BOOST_CHECK_CLOSE(data_test(1, 1, 0), -0.25, 1e-6);\n  BOOST_CHECK_CLOSE(data_test(1, 1, 1), 0.25, 1e-6);\n\n  // Test with manual domain and range initialization\n  LinearScale<float, 3> linearScale(0, 8, -1, 1);\n  data_test = linearScale(data);\n\n  BOOST_CHECK_CLOSE(data_test(0, 0, 0), -1.0, 1e-6);\n  BOOST_CHECK_CLOSE(data_test(0, 0, 1), -0.5, 1e-6);\n  BOOST_CHECK_CLOSE(data_test(0, 1, 0), 0.0, 1e-6);\n  BOOST_CHECK_CLOSE(data_test(0, 1, 1), 1.0, 1e-6);\n  BOOST_CHECK_CLOSE(data_test(1, 0, 0), -0.75, 1e-6);\n  BOOST_CHECK_CLOSE(data_test(1, 0, 1), -0.75, 1e-6);\n  BOOST_CHECK_CLOSE(data_test(1, 1, 0), -0.25, 1e-6);\n  BOOST_CHECK_CLOSE(data_test(1, 1, 1), 0.25, 1e-6);\n\n  // Test with domain calculation and range initialization\n  LinearScale<float, 3> linearScale2(data, -1, 1);\n  data_test = linearScale2(data);\n\n  BOOST_CHECK_CLOSE(data_test(0, 0, 0), -1.0, 1e-6);\n  BOOST_CHECK_CLOSE(data_test(0, 0, 1), -0.5, 1e-6);\n  BOOST_CHECK_CLOSE(data_test(0, 1, 0), 0.0, 1e-6);\n  BOOST_CHECK_CLOSE(data_test(0, 1, 1), 1.0, 1e-6);\n  BOOST_CHECK_CLOSE(data_test(1, 0, 0), -0.75, 1e-6);\n  BOOST_CHECK_CLOSE(data_test(1, 0, 1), -0.75, 1e-6);\n  BOOST_CHECK_CLOSE(data_test(1, 1, 0), -0.25, 1e-6);\n  BOOST_CHECK_CLOSE(data_test(1, 1, 1), 0.25, 1e-6);\n}\n\nBOOST_AUTO_TEST_CASE(P_Standardize)\n{\n  Eigen::Tensor<float, 3> data(2, 2, 2);\n  data.setValues({\n    {{ 0, 2 }, { 4, 8 }},\n    {{ 1, 3 }, { 3, 5 }}\n    });\n\n  // Test default initialization with setters and getters\n  Standardize<float, 3> standardize1;\n  standardize1.setMeanAndVar(1, 2);\n  BOOST_CHECK_CLOSE(standardize1.getMean(), 1, 1e-6);\n  BOOST_CHECK_CLOSE(standardize1.getVar(), 2, 1e-6);\n  standardize1.setMeanAndVar(data);\n  BOOST_CHECK_CLOSE(standardize1.getMean(), 3.25, 1e-6);\n  BOOST_CHECK_CLOSE(standardize1.getVar(), 6.21428585, 1e-6);\n\n  // Test with data initialization and getters\n  Standardize<float, 3> standardize(data);\n  BOOST_CHECK_CLOSE(standardize.getMean(), 3.25, 1e-6);\n  BOOST_CHECK_CLOSE(standardize.getVar(), 6.21428585, 1e-6);\n\n  // Test operator\n  Eigen::Tensor<float, 3> data_test = standardize(data);\n  BOOST_CHECK_CLOSE(data_test(0, 0, 0), -1.30373025, 1e-6);\n  BOOST_CHECK_CLOSE(data_test(0, 0, 1), -0.501434684, 1e-6);\n  BOOST_CHECK_CLOSE(data_test(0, 1, 0), 0.300860822, 1e-6);\n  BOOST_CHECK_CLOSE(data_test(0, 1, 1), 1.90545189, 1e-6);\n  BOOST_CHECK_CLOSE(data_test(1, 0, 0), -0.902582467, 1e-6);\n  BOOST_CHECK_CLOSE(data_test(1, 0, 1), -0.100286946, 1e-6);\n  BOOST_CHECK_CLOSE(data_test(1, 1, 0), -0.100286946, 1e-6);\n  BOOST_CHECK_CLOSE(data_test(1, 1, 1), 0.702008605, 1e-6);\n}\n\nBOOST_AUTO_TEST_CASE(P_MakeShuffleMatrix)\n{\n  const int shuffle_dim_size = 8;\n  std::vector<int> indices = { 0, 1, 2, 3, 4, 5, 6, 7 };\n\n  // Test default initialization with setters and getters\n  MakeShuffleMatrix<float> shuffle1;\n  shuffle1.setIndices(8);\n  BOOST_CHECK(shuffle1.getIndices() != indices);\n  for (int i = 0; i < shuffle_dim_size; ++i) {\n    BOOST_CHECK_GE(shuffle1.getIndices().at(i), 0);\n    BOOST_CHECK_LE(shuffle1.getIndices().at(i), 7);\n  }\n  shuffle1.setShuffleMatrix(true);\n  //std::cout << \"Shuffle_matrix\\n\" << shuffle1.getShuffleMatrix() << std::endl;\n  for (int i = 0; i < shuffle_dim_size; ++i) {\n    Eigen::Tensor<float, 0> row_sum = shuffle1.getShuffleMatrix().chip(i, 0).sum();\n    BOOST_CHECK_EQUAL(row_sum(0), 1);\n  }\n\n  // Test initialization with dim size\n  MakeShuffleMatrix<float> shuffle2(shuffle_dim_size, true);\n  BOOST_CHECK(shuffle2.getIndices() != indices);\n  for (int i = 0; i < shuffle_dim_size; ++i) {\n    BOOST_CHECK_GE(shuffle2.getIndices().at(i), 0);\n    BOOST_CHECK_LE(shuffle2.getIndices().at(i), 7);\n  }\n\n  // Test initialization with indices to use\n  MakeShuffleMatrix<float> shuffle3(indices, true);\n  BOOST_CHECK(shuffle3.getIndices() == indices);\n  //std::cout << \"Shuffle_matrix\\n\" << shuffle3.getShuffleMatrix() << std::endl;\n  for (int i = 0; i < shuffle_dim_size; ++i) {\n    BOOST_CHECK_EQUAL(shuffle3.getShuffleMatrix()(i, i), 1);\n    Eigen::Tensor<float, 0> row_sum = shuffle3.getShuffleMatrix().chip(i, 0).sum();\n    BOOST_CHECK_EQUAL(row_sum(0), 1);\n  }\n\n  // Test row/column shuffling on toy data\n  Eigen::Tensor<float, 2> data(2, 3);\n  data.setValues({ {1,2,3},{4,5,6} });\n  MakeShuffleMatrix<float> shuffle_col(std::vector<int>({1,2,0}), true);\n  Eigen::Tensor<float, 2> col_shuffle = data;\n  shuffle_col(col_shuffle, true);\n  BOOST_CHECK_EQUAL(col_shuffle(0, 0), 2);\n  BOOST_CHECK_EQUAL(col_shuffle(0, 1), 3);\n  BOOST_CHECK_EQUAL(col_shuffle(0, 2), 1);\n  BOOST_CHECK_EQUAL(col_shuffle(1, 0), 5);\n  BOOST_CHECK_EQUAL(col_shuffle(1, 1), 6);\n  BOOST_CHECK_EQUAL(col_shuffle(1, 2), 4);\n  MakeShuffleMatrix<float> shuffle_row(std::vector<int>({ 1,0 }), false);\n  Eigen::Tensor<float, 2> row_shuffle = data;\n  shuffle_row(row_shuffle, false);\n  BOOST_CHECK_EQUAL(row_shuffle(0, 0), 4);\n  BOOST_CHECK_EQUAL(row_shuffle(0, 1), 5);\n  BOOST_CHECK_EQUAL(row_shuffle(0, 2), 6);\n  BOOST_CHECK_EQUAL(row_shuffle(1, 0), 1);\n  BOOST_CHECK_EQUAL(row_shuffle(1, 1), 2);\n  BOOST_CHECK_EQUAL(row_shuffle(1, 2), 3);\n\n  // Test row/column shuffling on toy data\n  Eigen::Tensor<double, 2> data_db(2, 3);\n  data_db.setValues({ {1,2,3},{4,5,6} });\n  MakeShuffleMatrix<double> shuffle_col_db(std::vector<int>({ 1,2,0 }), true);\n  Eigen::Tensor<double, 2> col_shuffle_db = data_db;\n  shuffle_col_db(col_shuffle_db, true);\n  BOOST_CHECK_EQUAL(col_shuffle_db(0, 0), 2);\n  BOOST_CHECK_EQUAL(col_shuffle_db(0, 1), 3);\n  BOOST_CHECK_EQUAL(col_shuffle_db(0, 2), 1);\n  BOOST_CHECK_EQUAL(col_shuffle_db(1, 0), 5);\n  BOOST_CHECK_EQUAL(col_shuffle_db(1, 1), 6);\n  BOOST_CHECK_EQUAL(col_shuffle_db(1, 2), 4);\n  MakeShuffleMatrix<double> shuffle_row_db(std::vector<int>({ 1,0 }), false);\n  Eigen::Tensor<double, 2> row_shuffle_db = data_db;\n  shuffle_row_db(row_shuffle_db, false);\n  BOOST_CHECK_EQUAL(row_shuffle_db(0, 0), 4);\n  BOOST_CHECK_EQUAL(row_shuffle_db(0, 1), 5);\n  BOOST_CHECK_EQUAL(row_shuffle_db(0, 2), 6);\n  BOOST_CHECK_EQUAL(row_shuffle_db(1, 0), 1);\n  BOOST_CHECK_EQUAL(row_shuffle_db(1, 1), 2);\n  BOOST_CHECK_EQUAL(row_shuffle_db(1, 2), 3);\n}\n\nBOOST_AUTO_TEST_CASE(P_LabelSmoother)\n{\n\tEigen::Tensor<float, 1> data(2);\n\tdata.setValues({ 0, 1 });\n\n\tEigen::Tensor<float, 1> data_test = data.unaryExpr(LabelSmoother<float>(0.1, 0.2));\n\n\tBOOST_CHECK_CLOSE(data_test(0), 0.1, 1e-4);\n\tBOOST_CHECK_CLOSE(data_test(1), 0.8, 1e-4);\n}\n\nBOOST_AUTO_TEST_CASE(P_OneHotEncoder)\n{\n\t// TODO\n}\n\nBOOST_AUTO_TEST_CASE(SFcheckNan)\n{\n\tEigen::Tensor<float, 1> values(2);\n\tvalues.setConstant(5.0f);\n\tEigen::Tensor<float, 1> test(2);\n\n\t// control\n  test = values.unaryExpr([](float c) { return checkNan<float>(c); });\n\tBOOST_CHECK_CLOSE(test(0), 5.0, 1e-3);\n\tBOOST_CHECK_CLOSE(test(1), 5.0, 1e-3);\n\n\t// test\n\tvalues(0) = NAN; //NaN\n\tvalues(1) = INFINITY; //infinity\n  test = values.unaryExpr([](float c) { return checkNan<float>(c); });\n\tBOOST_CHECK_CLOSE(test(0), NAN, 1e-3);\n\tBOOST_CHECK_CLOSE(test(1), INFINITY, 1e-3);\n}\n\nBOOST_AUTO_TEST_CASE(SFsubstituteNanInf)\n{\n\tEigen::Tensor<float, 1> values(3);\n\tvalues.setConstant(5.0f);\n\tEigen::Tensor<float, 1> test(3);\n\n\t// control\n  test = values.unaryExpr([](float c) { return substituteNanInf<float>(c); });\n\tBOOST_CHECK_CLOSE(test(0), 5.0, 1e-3);\n\tBOOST_CHECK_CLOSE(test(1), 5.0, 1e-3);\n\n\t// test\n\tvalues(0) = NAN; //NaN\n\tvalues(1) = INFINITY; //infinity\n\tvalues(2) = -INFINITY; //infinity\n  test = values.unaryExpr([](float c) { return substituteNanInf<float>(c); });\n\tBOOST_CHECK_CLOSE(test(0), 0.0, 1e-3);\n\tBOOST_CHECK_CLOSE(test(1), 1e9, 1e-3);\n\tBOOST_CHECK_CLOSE(test(2), -1e9, 1e-3);\n}\n\nBOOST_AUTO_TEST_CASE(SFClipOp)\n{\n\tEigen::Tensor<float, 1> net_input(3);\n\tnet_input.setValues({ 0.0f, 1.0f, 0.5f });\n\n\t// test input\n\tEigen::Tensor<float, 1> result = net_input.unaryExpr(ClipOp<float>(0.1f, 0.0f, 1.0f));\n\tBOOST_CHECK_CLOSE(result(0), 0.1, 1e-3);\n\tBOOST_CHECK_CLOSE(result(1), 0.9, 1e-3);\n\tBOOST_CHECK_CLOSE(result(2), 0.5, 1e-3);\n}\n\nBOOST_AUTO_TEST_CASE(SFRandBinaryOp)\n{\n\tEigen::Tensor<float, 1> net_input(2);\n\tnet_input.setValues({ 2.0f, 2.0f });\n\tEigen::Tensor<float, 1> result;\n\n\t// test input\n\tresult = net_input.unaryExpr(RandBinaryOp<float>(0.0f));\n\tBOOST_CHECK_CLOSE(result(0), 2.0, 1e-3);\n\tBOOST_CHECK_CLOSE(result(1), 2.0, 1e-3);\n\tresult = net_input.unaryExpr(RandBinaryOp<float>(1.0f));\n\tBOOST_CHECK_CLOSE(result(0), 0.0, 1e-3);\n\tBOOST_CHECK_CLOSE(result(1), 0.0, 1e-3);\n}\n\nBOOST_AUTO_TEST_CASE(assertClose)\n{\n\tBOOST_CHECK(!assert_close<float>(1.1, 1.2, 1e-4, 1e-4));\n\tBOOST_CHECK(assert_close<float>(1.1, 1.2, 1, 1));\n}\n\nBOOST_AUTO_TEST_CASE(P_GaussianMixture)\n{\n\t// TODO\n}\n\nBOOST_AUTO_TEST_CASE(P_SwissRoll)\n{\n\t// TODO\n}\n\nBOOST_AUTO_TEST_CASE(P_GumbelSampler)\n{\n\tEigen::Tensor<float, 2> gumbel_samples = GumbelSampler<float>(2, 3);\n\tBOOST_CHECK_LE(gumbel_samples(0, 0), 10);\n\tBOOST_CHECK_GE(gumbel_samples(0, 0), -10);\n\tBOOST_CHECK_LE(gumbel_samples(1, 2), 10);\n\tBOOST_CHECK_GE(gumbel_samples(1, 2), -10);\n\tstd::cout << gumbel_samples << std::endl;\n}\n\nBOOST_AUTO_TEST_CASE(P_GaussianSampler)\n{\n\tEigen::Tensor<float, 2> gaussian_samples = GaussianSampler<float>(2, 3);\n\tBOOST_CHECK_LE(gaussian_samples(0, 0), 2);\n\tBOOST_CHECK_GE(gaussian_samples(0, 0), -2);\n\tBOOST_CHECK_LE(gaussian_samples(1, 2), 2);\n\tBOOST_CHECK_GE(gaussian_samples(1, 2), -2);\n\tstd::cout << gaussian_samples << std::endl;\n}\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "c91039be7df71ef51bfcfbe0011838632fff0ad3", "size": 11138, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tests/class_tests/evonet/source/Preprocessing_test.cpp", "max_stars_repo_name": "dmccloskey/smartPeak_cpp", "max_stars_repo_head_hexsha": "47a19a804b65daef712418b4e278704b340d20b9", "max_stars_repo_licenses": ["MIT"], "max_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/class_tests/evonet/source/Preprocessing_test.cpp", "max_issues_repo_name": "dmccloskey/smartPeak_cpp", "max_issues_repo_head_hexsha": "47a19a804b65daef712418b4e278704b340d20b9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2018-01-11T20:39:09.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-11T21:02:31.000Z", "max_forks_repo_path": "src/tests/class_tests/evonet/source/Preprocessing_test.cpp", "max_forks_repo_name": "dmccloskey/smartPeak_cpp", "max_forks_repo_head_hexsha": "47a19a804b65daef712418b4e278704b340d20b9", "max_forks_repo_licenses": ["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.9573170732, "max_line_length": 92, "alphanum_fraction": 0.694828515, "num_tokens": 4011, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.49814610308081025}}
{"text": "/* Boost test/mul.cpp\n * test multiplication, division, square and square root on some intervals\n *\n * Copyright 2002-2003 Guillaume Melquiond\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 <boost/numeric/interval.hpp>\n#include <boost/test/minimal.hpp>\n#include \"bugs.hpp\"\n\ntypedef boost::numeric::interval<double> I;\n\nstatic double min BOOST_PREVENT_MACRO_SUBSTITUTION (double a, double b, double c, double d) {\n  return (std::min)((std::min)(a, b), (std::min)(c, d));\n}\n\nstatic double max BOOST_PREVENT_MACRO_SUBSTITUTION (double a, double b, double c, double d) {\n  return (std::max)((std::max)(a, b), (std::max)(c, d));\n}\n\nstatic bool test_mul(double al, double au, double bl, double bu) {\n  I a(al, au), b(bl, bu);\n  I c = a * b;\n  return c.lower() == (min)(al*bl, al*bu, au*bl, au*bu)\n      && c.upper() == (max)(al*bl, al*bu, au*bl, au*bu);\n}\n\nstatic bool test_mul1(double ac, double bl, double bu) {\n  I a(ac), b(bl, bu);\n  I c = ac * b;\n  I d = b * ac;\n  I e = a * b;\n  return equal(c, d) && equal(d, e);\n}\n\nstatic bool test_div(double al, double au, double bl, double bu) {\n  I a(al, au), b(bl, bu);\n  I c = a / b;\n  return c.lower() == (min)(al/bl, al/bu, au/bl, au/bu)\n      && c.upper() == (max)(al/bl, al/bu, au/bl, au/bu);\n}\n\nstatic bool test_div1(double al, double au, double bc) {\n  I a(al, au), b(bc);\n  I c = a / bc;\n  I d = a / b;\n  return equal(c, d);\n}\n\nstatic bool test_div2(double ac, double bl, double bu) {\n  I a(ac), b(bl, bu);\n  I c = ac / b;\n  I d = a / b;\n  return equal(c, d);\n}\n\nstatic bool test_square(double al, double au) {\n  I a(al, au);\n  I b = square(a);\n  I c = a * a;\n  return b.upper() == c.upper() &&\n         (b.lower() == c.lower() || (c.lower() <= 0 && b.lower() == 0));\n}\n\nstatic bool test_sqrt(double al, double au) {\n  I a(al, au);\n  I b = square(sqrt(a));\n  return subset(abs(a), b);\n}\n\nint test_main(int, char*[]) {\n  BOOST_CHECK(test_mul(2, 3, 5, 7));\n  BOOST_CHECK(test_mul(2, 3, -5, 7));\n  BOOST_CHECK(test_mul(2, 3, -7, -5));\n  BOOST_CHECK(test_mul(-2, 3, 5, 7));\n  BOOST_CHECK(test_mul(-2, 3, -5, 7));\n  BOOST_CHECK(test_mul(-2, 3, -7, -5));\n  BOOST_CHECK(test_mul(-3, -2, 5, 7));\n  BOOST_CHECK(test_mul(-3, -2, -5, 7));\n  BOOST_CHECK(test_mul(-3, -2, -7, -5));\n\n  BOOST_CHECK(test_mul1(3, 5, 7));\n  BOOST_CHECK(test_mul1(3, -5, 7));\n  BOOST_CHECK(test_mul1(3, -7, -5));\n  BOOST_CHECK(test_mul1(-3, 5, 7));\n  BOOST_CHECK(test_mul1(-3, -5, 7));\n  BOOST_CHECK(test_mul1(-3, -7, -5));\n\n  BOOST_CHECK(test_div(30, 42, 2, 3));\n  BOOST_CHECK(test_div(30, 42, -3, -2));\n  BOOST_CHECK(test_div(-30, 42, 2, 3));\n  BOOST_CHECK(test_div(-30, 42, -3, -2));\n  BOOST_CHECK(test_div(-42, -30, 2, 3));\n  BOOST_CHECK(test_div(-42, -30, -3, -2));\n\n  BOOST_CHECK(test_div1(30, 42, 3));\n  BOOST_CHECK(test_div1(30, 42, -3));\n  BOOST_CHECK(test_div1(-30, 42, 3));\n  BOOST_CHECK(test_div1(-30, 42, -3));\n  BOOST_CHECK(test_div1(-42, -30, 3));\n  BOOST_CHECK(test_div1(-42, -30, -3));\n\n  BOOST_CHECK(test_div2(30, 2, 3));\n  BOOST_CHECK(test_div2(30, -3, -2));\n  BOOST_CHECK(test_div2(-30, 2, 3));\n  BOOST_CHECK(test_div2(-30, -3, -2));\n\n  BOOST_CHECK(test_square(2, 3));\n  BOOST_CHECK(test_square(-2, 3));\n  BOOST_CHECK(test_square(-3, 2));\n\n  BOOST_CHECK(test_sqrt(2, 3));\n  BOOST_CHECK(test_sqrt(5, 7));\n  BOOST_CHECK(test_sqrt(-1, 2));\n\n# ifdef __BORLANDC__\n  ::detail::ignore_warnings();\n# endif\n  return 0;\n}\n", "meta": {"hexsha": "118acf325ab06da76a93f5768b35cd0be60b9fc8", "size": 3471, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/numeric/interval/test/mul.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "boost/libs/numeric/interval/test/mul.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "boost/libs/numeric/interval/test/mul.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 27.768, "max_line_length": 93, "alphanum_fraction": 0.6145203111, "num_tokens": 1241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289836, "lm_q2_score": 0.6548947155710233, "lm_q1q2_score": 0.49814609994072384}}
{"text": "#pragma once\n\n#include \"craam/RMDP.hpp\"\n\n#include <Eigen/Dense>\n#include <rm/range.hpp>\n\nnamespace craam{namespace algorithms{\n\nusing namespace std;\nusing namespace Eigen;\n\n/// Internal helper functions\nnamespace internal{\n\n    /// Helper function to deal with variable indexing\n    template<class SType>\n    inline Transition mean_transition_state(const SType& state, long index, const pair<indvec,vector<numvec>>& policies){\n        return state.mean_transition(policies.first[index], policies.second[index]);\n    }\n\n    /// Helper function to deal with variable indexing\n    template<class SType>\n    inline Transition mean_transition_state(const SType& state, long index, const indvec& policy){\n        return state.mean_transition(policy[index]);\n    }\n\n    /// Helper function to deal with variable indexing\n    template<class SType>\n    inline prec_t mean_reward_state(const SType& state, long index, const pair<indvec,vector<numvec>>& policies){\n        return state.mean_reward(policies.first[index], policies.second[index]);\n    }\n\n    /// Helper function to deal with variable indexing\n    template<class SType>\n    inline prec_t mean_reward_state(const SType& state, long index, const indvec& policy){\n        return state.mean_reward(policy[index]);\n    }\n}\n\n/**\nConstructs the transition (or its transpose) matrix for the policy.\n\n\\tparam SType Type of the state in the MDP (regular vs robust)\n\\tparam Policy Type of the policy. Either a single policy for\n                the standard MDP evaluation, or a pair of a deterministic \n                policy and a randomized policy of the nature\n\\param rmdp Regular or robust MDP\n\\param policies The policy (indvec) or the pair of the policy and the policy\n        of nature (pair<indvec,vector<numvec> >). The nature is typically \n        a randomized policy\n\\param transpose (optional, false) Whether to return the transpose of the transition matrix. \n        This is useful for computing occupancy frequencies\n*/\ntemplate<typename SType, typename Policies> \ninline MatrixXd transition_mat(const GRMDP<SType>& rmdp, const Policies& policies, bool transpose = false) {\n    const size_t n = rmdp.state_count();\n    MatrixXd result = MatrixXd::Zero(n,n);\n\n    const auto& states = rmdp.get_states();\n    #pragma omp parallel for\n    for(size_t s = 0; s < n; s++){\n        const Transition&& t = internal::mean_transition_state(states[s], s, policies);\n\n        const auto& indexes = t.get_indices();\n        const auto& probabilities = t.get_probabilities();\n\n        if(!transpose){\n            for(size_t j=0; j < t.size(); j++)\n                result(s,indexes[j]) = probabilities[j];\n        }else{\n            for(size_t j=0; j < t.size(); j++)\n                result(indexes[j],s) = probabilities[j];\n        }\n    }\n    return result;\n}\n\n/**\nConstructs the rewards vector for each state for the RMDP.\n\n\\tparam Policy Type of the policy. Either a single policy for\n                the standard MDP evaluation, or a pair of a deterministic \n                policy and a randomized policy of the nature\n\\param rmdp Regular or robust MDP\n\\param policies The policy (indvec) or the pair of the policy and the policy\n        of nature (pair<indvec,vector<numvec> >). The nature is typically \n        a randomized policy\n */\ntemplate<typename SType, typename Policy>\ninline numvec rewards_vec(const GRMDP<SType>& rmdp, const Policy& policies){\n    \n    const auto n = rmdp.state_count();\n    numvec rewards(n);\n\n    #pragma omp parallel for\n    for(size_t s=0; s < n; s++){\n        const SType& state = rmdp[s];\n        if(state.is_terminal())\n            rewards[s] = 0;\n        else\n            rewards[s] = internal::mean_reward_state(state, s, policies);\n    }\n    return rewards;\n}\n\n/**\nComputes occupancy frequencies using matrix representation of transition\nprobabilities. This method may not scale well\n\n\n\\tparam SType Type of the state in the MDP (regular vs robust)\n\\tparam Policy Type of the policy. Either a single policy for\n                the standard MDP evaluation, or a pair of a deterministic \n                policy and a randomized policy of the nature\n\\param init Initial distribution (alpha)\n\\param discount Discount factor (gamma)\n\\param policies The policy (indvec) or the pair of the policy and the policy\n        of nature (pair<indvec,vector<numvec> >). The nature is typically \n        a randomized policy\n*/\ntemplate<typename SType, typename Policies>\ninline numvec \noccfreq_mat(const GRMDP<SType>& rmdp, const Transition& init, prec_t discount,\n                 const Policies& policies) {\n    const auto n = rmdp.state_count();\n\n    // initial distribution\n    const numvec& ivec = init.probabilities_vector(n);\n    const VectorXd initial_vec = Map<const VectorXd,Unaligned>(ivec.data(),ivec.size());\n\n    // get transition matrix and construct (I - gamma * P^T)\n    MatrixXd t_mat = MatrixXd::Identity(n,n)  - discount * transition_mat(rmdp, policies, true);\n\n    // solve set of linear equations\n    numvec result(n,0);\n    Map<VectorXd,Unaligned>(result.data(),result.size()) = HouseholderQR<MatrixXd>(t_mat).solve(initial_vec);\n\n    return result;\n}\n\n}}\n", "meta": {"hexsha": "02b75a82706ec586d3287a70158c77cff098e73e", "size": 5149, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "craam/algorithms/occupancies.hpp", "max_stars_repo_name": "marekpetrik/CRAAM", "max_stars_repo_head_hexsha": "62cc392e876b5383faa5cb15ab1f6b70b26ff395", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2015-09-28T14:41:00.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-03T00:16:19.000Z", "max_issues_repo_path": "craam/algorithms/occupancies.hpp", "max_issues_repo_name": "marekpetrik/CRAAM", "max_issues_repo_head_hexsha": "62cc392e876b5383faa5cb15ab1f6b70b26ff395", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2017-08-10T18:35:40.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-13T01:38:04.000Z", "max_forks_repo_path": "craam/algorithms/occupancies.hpp", "max_forks_repo_name": "marekpetrik/CRAAM", "max_forks_repo_head_hexsha": "62cc392e876b5383faa5cb15ab1f6b70b26ff395", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2016-09-19T18:31:07.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-05T08:59:45.000Z", "avg_line_length": 36.006993007, "max_line_length": 121, "alphanum_fraction": 0.6879005632, "num_tokens": 1154, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289836, "lm_q2_score": 0.6548947155710233, "lm_q1q2_score": 0.49814609994072384}}
{"text": "////////////////////////////////////////////////////////////////////////////////\n/// Copyright 2018-present Xinyan DAI<xinyan.dai@outlook.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\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 ofthe 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/// @version 0.1\n/// @author  Xinyan DAI\n/// @contact xinyan.dai@outlook.com\n//////////////////////////////////////////////////////////////////////////////\n#pragma once\n\n#include <eigen3/Eigen/Dense>\n\n#include <map>\n#include <vector>\n#include <random>\n#include <iostream>\n#include <functional>\n#include <boost/progress.hpp>\n\n#include \"index.hpp\"\n\nnamespace ss {\n    template<typename DataType>\n    class Node {\n    protected:\n        DataType                            _medians;\n        vector<DataType >                   _projector;\n        vector<int >                        _idx;\n        Node                                *_left;\n        Node                                *_right;\n        const u_int                         _depth;\n        const u_int                         _dim;\n        const u_int                         _max_depth;\n\n    public:\n        explicit Node(u_int dim, u_int depth, u_int max_depth) :\n            _depth(depth), _max_depth(max_depth), _dim(dim), _projector(dim) {\n        }\n\n        bool IsLeaf() {\n            return this->_depth == this->_max_depth;\n        }\n\n        void _GenerateProjector(const Matrix<DataType> &data, const vector<int> &idx) {\n            // TODO(Xinyan) choose the eigenvector as random projection vector\n            std::default_random_engine generator;\n            std::normal_distribution<DataType > distribution(0.0, 1.0);\n\n            for (int j=0; j<_dim; j++) {\n                this->_projector[j] = distribution(generator);\n            }\n        }\n\n        void MakeTree(const Matrix<DataType> &data, const vector<int > & idx) {\n            if (IsLeaf()) {\n                _idx = idx;\n                return;\n            }\n            int N = idx.size();\n            this->_GenerateProjector(data, idx);\n            vector <DataType> projected_value(idx.size());\n            for (int i = 0; i < idx.size(); ++i) {\n                projected_value[i] = ss::InnerProduct(data[idx[i]], _projector.data(), _projector.size());\n            }\n            vector<size_t > sorted_idx = ss::SortIndexes(projected_value);\n            vector<size_t > sorted_left_inx = vector<size_t>(sorted_idx.begin(), sorted_idx.begin() + N/2);\n            vector<size_t > sorted_right_inx = vector<size_t >(sorted_idx.begin() + N/2, sorted_idx.end());\n\n            this->_medians = (projected_value[sorted_idx[N/2-1]]+ projected_value[sorted_idx[N/2+1]]) / 2.0;\n\n            this->_left = new Node(_dim, _depth + 1, _max_depth);\n            this->_right = new Node(_dim, _depth + 1, _max_depth);\n\n            this->_left->MakeTree(data, ss::FancyIndex(idx, sorted_left_inx));\n            this->_right->MakeTree(data, ss::FancyIndex(idx, sorted_right_inx));\n        }\n\n        const vector<int>& ProbeLeaf(const DataType * query) {\n            if (IsLeaf()) {\n                return this->_idx;\n            }\n            DataType projected_value= ss::InnerProduct(query, _projector.data(), _projector.size());\n            if (projected_value < _medians) {\n                return this->_left->ProbeLeaf(query);\n            } else {\n                return this->_right->ProbeLeaf(query);\n            }\n        }\n\n        void LeafIdx(vector<vector<int > * > & leafIdx) {\n            if (IsLeaf()) {\n                leafIdx.push_back(&this->_idx);\n            } else {\n\n                this->_left->LeafIdx(leafIdx);\n                this->_right->LeafIdx(leafIdx);\n            }\n        }\n\n    };\n\n    template<typename DataType>\n    class RPTIndex: public Index<DataType > {\n    protected:\n        Node<DataType >             _root;\n    public:\n        explicit RPTIndex(const parameter & para) :\n                Index <DataType >(para),\n                _root(para.dim, 0, para.num_bit) {\n        }\n\n        ~RPTIndex() {}\n\n        void Train(const Matrix<DataType> & data) override {\n            this->_root.MakeTree(data, ss::Range<int>(0, data.getSize()));\n\n        }\n\n        void Add(const Matrix<DataType> &data) override {\n        }\n\n        vector<vector<int > * > LeafIdx() {\n            vector<vector<int > * > leafIdx;\n            leafIdx.reserve(1 << this->_para.num_bit);\n            this->_root.LeafIdx(leafIdx);\n            return leafIdx;\n        }\n\n        void Search(const DataType* query, const std::function<void (int)>& prober) override {\n            const vector<int >& idx = this->_root.ProbeLeaf(query);\n            for (int id : idx) {\n                prober(id);\n            }\n        }\n    };\n} // namespace ss\n\n\n// ------------------------- implementation -------------------------\n\n", "meta": {"hexsha": "4b33fe4081d9ac97d0bf573d25cf3513eb6d8f14", "size": 5794, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/include/index/rptree.hpp", "max_stars_repo_name": "xinyandai/similarity-search", "max_stars_repo_head_hexsha": "75dc71abdd7f79094475db734fe55d04358363fc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2018-11-17T00:51:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T22:51:56.000Z", "max_issues_repo_path": "src/include/index/rptree.hpp", "max_issues_repo_name": "xinyandai/similarity-search", "max_issues_repo_head_hexsha": "75dc71abdd7f79094475db734fe55d04358363fc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/include/index/rptree.hpp", "max_forks_repo_name": "xinyandai/similarity-search", "max_forks_repo_head_hexsha": "75dc71abdd7f79094475db734fe55d04358363fc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2018-11-14T08:08:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-08T02:42:58.000Z", "avg_line_length": 36.6708860759, "max_line_length": 108, "alphanum_fraction": 0.5495340007, "num_tokens": 1250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.4981460979574081}}
{"text": "/*\n For more information, please see: http://software.sci.utah.edu\n \n The MIT License\n \n Copyright (c) 2015 Scientific Computing and Imaging Institute,\n University of Utah.\n \n \n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and/or sell copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following conditions:\n \n The above copyright notice and this permission notice shall be included\n in all copies or substantial portions of the Software.\n \n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n*/\n\n#include <gtest/gtest.h>\n#include <boost/test/floating_point_comparison.hpp>\n\n#include <Testing/Util/MatrixTestUtilities.h>\n\n#include <Core/Math/sci_lapack.h>\n#include <Core/Datatypes/MatrixFwd.h>\n#include <Core/Datatypes/DenseMatrix.h>\n#include <Core/Datatypes/ColumnMatrix.h>\n#include <Core/Datatypes/MatrixOperations.h>\n#include <Core/Datatypes/MatrixTypeConverter.h>\n\n#include <Core/Exceptions/LapackError.h>\n\nusing namespace boost::assign; \nusing namespace SCIRun;\nusing namespace SCIRun::TestUtils;\n\nTEST(InvertMatrixTest, InvertZeroException)\n{\n  const int dim = 3;\n  DenseMatrix zero_matrix(dim, dim);\n  zero_matrix.zero();\n  \n  EXPECT_THROW(lapackinvert(zero_matrix.get_data_pointer(), dim), LapackError);\n}\n\nTEST(InvertMatrixTest, InvertArgException)\n{\n  const int dim = 5;\n  const int bad_dim = 4;\n  DenseMatrixHandle identity(DenseMatrix::identity(dim));\n  DenseMatrixHandle identityOriginal(DenseMatrix::identity(dim));\n  \n  EXPECT_THROW(lapackinvert(identity->get_data_pointer(), bad_dim), LapackError);\n  \n  EXPECT_FALSE(compare_exactly(*identity, *identityOriginal));\n}\n\nTEST(SolveLinSysWithLapackTest, SolveLinSysZeroException)\n{\n  const int dim = 6;\n  DenseMatrix zero_matrix(dim, dim);\n  zero_matrix.zero();\n  ColumnMatrix rhs = MAKE_COLUMN_MATRIX((107) (60) (71) (43) (82));\n\n  EXPECT_THROW(lapacksolvelinearsystem(zero_matrix.get_raw_2D_pointer(), dim, dim,\n                                       rhs.get_data_pointer(),  dim, 1),\n               LapackError);\n}\n\nTEST(InvertMatrixTest, CanInvertIdentity)\n{\n  const int dim = 3;\n  DenseMatrixHandle identity(DenseMatrix::identity(dim));\n  DenseMatrixHandle identityOriginal(DenseMatrix::identity(dim));\n  \n  EXPECT_NO_THROW(lapackinvert(identity->get_data_pointer(), dim));\n  \n  EXPECT_TRUE(compare_exactly(*identity, *identityOriginal));\n}\n\nTEST(SolveLinSysWithLapackTest, SolvingSimpleCase)\n{\n  DenseMatrix M = MAKE_DENSE_MATRIX(\n    (2, 4, 7, 9, 8)\n    (6, 9, 2, 5, 2)\n    (6, 3, 5, 1, 8)\n    (1, 5, 6, 1, 2)\n    (1, 2, 8, 2, 9));\n    \n   ColumnMatrix rhs = MAKE_COLUMN_MATRIX((107) (60) (71) (43) (82));\n   \n   EXPECT_NO_THROW(lapacksolvelinearsystem(M.get_raw_2D_pointer(), 5, 5, rhs.get_data_pointer(),  5, 1));\n   \n   EXPECT_COLUMN_MATRIX_EQ_TO(rhs,\n    (1.0)\n    (2.0)\n    (3.0)\n    (4.0)\n    (5.0));\n\n}\n\nTEST(InvertMatrixTest, CanInvertWithMemberFunction)\n{\n  const int rows = 3, cols = 3;\n\n  DenseMatrix m = MAKE_DENSE_MATRIX(\n    (1, 0, 1)\n    (0, 2, 0)\n    (0, 0, -1));\n\n  const MatrixHandle original(m.clone());\n  //std::cout << \"Matrix:\" << std::endl;\n  //std::cout << matrix_to_string(m) << std::endl;\n\n  EXPECT_TRUE(m.invert());\n  const MatrixHandle inverseFromMethod(m.clone());\n  //std::cout << \"Inverse from method:\" << std::endl;\n  //std::cout << to_string(inverseFromMethod) << std::endl;\n\n  EXPECT_TRUE(m.invert());\n  //std::cout << \"Back to original matrix:\" << std::endl;\n  //std::cout << matrix_to_string(m) << std::endl;\n\n  //std::cout << \"Inversion via direct call to lapack:\" << std::endl;\n\n  EXPECT_NO_THROW(lapackinvert(m.get_data_pointer(), rows));\n\n  //std::cout << matrix_to_string(m) << std::endl;\n  {\n    const MatrixHandle inverseFromDirectLapack(m.clone());\n\n    //std::cout << \"Difference matrix:\" << std::endl;\n    MatrixHandle diff = inverseFromDirectLapack - inverseFromMethod;\n    //std::cout << to_string(diff) << std::endl;\n\n    DenseMatrixHandle zero(DenseMatrix::zero_matrix(rows, cols));\n\n    EXPECT_TRUE(compare_exactly(*diff, *zero));\n  }\n\n  MatrixHandle id3(DenseMatrix::identity(rows));\n  MatrixHandle product = inverseFromMethod * original;\n  EXPECT_TRUE(compare_exactly(*id3, *product));\n}\n\n//Note: this test can be a template for further lapack function testing.\nTEST(SVDTest, ExampleFromWikiPage)\n{\n  const int rows = 4, cols = 5;\n\n  DenseMatrix m = MAKE_DENSE_MATRIX(\n    (1, 0, 0, 0, 2)\n    (0, 0, 3, 0, 0)\n    (0, 0, 0, 0, 0)\n    (0, 4, 0, 0, 0));\n\n  DenseMatrix u(rows, rows);\n  ColumnMatrix s(rows);\n  DenseMatrix v_transpose(cols, cols);\n\n  EXPECT_NO_THROW(lapacksvd(m.get_raw_2D_pointer(), rows, cols,\n                            s.get_data_pointer(),\n                            u.get_raw_2D_pointer(),\n                            v_transpose.get_raw_2D_pointer()));\n\n  EXPECT_MATRIX_EQ_TO(u, \n    (0,0,1,0)\n    (0,1,0,0)\n    (0,0,0,-1)\n    (1,0,0,0));\n\n  EXPECT_COLUMN_MATRIX_EQ_TO(s,\n    (4.0)\n    (3.0)\n    (2.23606798)\n    (0));\n\n  EXPECT_MATRIX_EQ_TO(v_transpose,\n    (0.0,1.0,0.0,0.0,0.0)\n    (0,  0,  1,  0,  0)\n    (sqrt(0.2), 0, 0, 0, sqrt(0.8))\n    (0, 0, 0, 1, 0)\n    (-sqrt(0.8), 0, 0, 0, sqrt(0.2)));\n\n  MatrixHandle U(u.clone());\n  MatrixHandle fullS(DenseMatrix::make_diagonal_from_column(s, rows, cols));\n  MatrixHandle V_transpose(v_transpose.clone());\n\n  EXPECT_MATRIX_EQ(m, *(U * fullS * V_transpose));\n}\n\n", "meta": {"hexsha": "624f5728a21e054986390d8c4b65516e4181d25f", "size": 5979, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/Core/Math/Tests/LapackWrapperTests.cc", "max_stars_repo_name": "mhansen1/SCIRun", "max_stars_repo_head_hexsha": "9719c570a6d6911a9eb8df584bd2c4ad8b8cd2ba", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Core/Math/Tests/LapackWrapperTests.cc", "max_issues_repo_name": "mhansen1/SCIRun", "max_issues_repo_head_hexsha": "9719c570a6d6911a9eb8df584bd2c4ad8b8cd2ba", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Core/Math/Tests/LapackWrapperTests.cc", "max_forks_repo_name": "mhansen1/SCIRun", "max_forks_repo_head_hexsha": "9719c570a6d6911a9eb8df584bd2c4ad8b8cd2ba", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4532019704, "max_line_length": 105, "alphanum_fraction": 0.6872386687, "num_tokens": 1711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.7606506418255928, "lm_q1q2_score": 0.49814609597409204}}
{"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#define BOOST_UBLAS_TYPE_CHECK_EPSILON (type_traits<real_type>::type_sqrt (boost::math::tools::epsilon <real_type>()))\n#define BOOST_UBLAS_TYPE_CHECK_MIN (type_traits<real_type>::type_sqrt ( boost::math::tools::min_value<real_type>()))\n#define BOOST_UBLAS_NDEBUG\n\n#include <boost/math/bindings/rr.hpp>\nnamespace std{\nusing boost::math::ntl::pow;\n} // workaround for spirit parser.\n#include <boost/math/tools/remez.hpp>\n#include <boost/math/tools/test.hpp>\n#include <boost/math/special_functions/binomial.hpp>\n#include <boost/spirit/include/classic_core.hpp>\n#include <boost/spirit/include/classic_actor.hpp>\n#include <boost/lexical_cast.hpp>\n#include <iostream>\n#include <iomanip>\n#include <string>\n#include <boost/test/included/test_exec_monitor.hpp> // for test_main\n\nextern boost::math::ntl::RR f(const boost::math::ntl::RR& x, int variant);\nextern void show_extra(\n   const boost::math::tools::polynomial<boost::math::ntl::RR>& n, \n   const boost::math::tools::polynomial<boost::math::ntl::RR>& d, \n   const boost::math::ntl::RR& x_offset, \n   const boost::math::ntl::RR& y_offset, \n   int variant);\n\nusing namespace boost::spirit::classic;\n\nboost::math::ntl::RR a(0), b(1);   // range to optimise over\nbool rel_error(true);\nbool pin(false);\nint orderN(3);\nint orderD(1);\nint target_precision = boost::math::tools::digits<long double>();\nint working_precision = target_precision * 2;\nbool started(false);\nint variant(0);\nint skew(0);\nint brake(50);\nboost::math::ntl::RR x_offset(0), y_offset(0), x_scale(1);\nbool auto_offset_y;\n\nboost::shared_ptr<boost::math::tools::remez_minimax<boost::math::ntl::RR> > p_remez;\n\nboost::math::ntl::RR the_function(const boost::math::ntl::RR& val)\n{\n   return f(x_scale * (val + x_offset), variant) + y_offset;\n}\n\nvoid step_some(unsigned count)\n{\n   try{\n      NTL::RR::SetPrecision(working_precision);\n      if(!started)\n      {\n         //\n         // If we have an automatic y-offset calculate it now:\n         //\n         if(auto_offset_y)\n         {\n            boost::math::ntl::RR fa, fb, fm;\n            fa = f(x_scale * (a + x_offset), variant);\n            fb = f(x_scale * (b + x_offset), variant);\n            fm = f(x_scale * ((a+b)/2 + x_offset), variant);\n            y_offset = -(fa + fb + fm) / 3;\n            NTL::RR::SetOutputPrecision(5);\n            std::cout << \"Setting auto-y-offset to \" << y_offset << std::endl;\n         }\n         //\n         // Truncate offsets to float precision:\n         //\n         x_offset = NTL::RoundToPrecision(x_offset.value(), 20);\n         y_offset = NTL::RoundToPrecision(y_offset.value(), 20);\n         //\n         // Construct new Remez state machine:\n         //\n         p_remez.reset(new boost::math::tools::remez_minimax<boost::math::ntl::RR>(\n            &the_function, \n            orderN, orderD, \n            a, b, \n            pin, \n            rel_error, \n            skew, \n            working_precision));\n         std::cout << \"Max error in interpolated form: \" << std::setprecision(3) << std::scientific << boost::math::tools::real_cast<double>(p_remez->max_error()) << std::endl;\n         //\n         // Signal that we've started:\n         //\n         started = true;\n      }\n      unsigned i;\n      for(i = 0; i < count; ++i)\n      {\n         std::cout << \"Stepping...\" << std::endl;\n         p_remez->set_brake(brake);\n         boost::math::ntl::RR r = p_remez->iterate();\n         NTL::RR::SetOutputPrecision(3);\n         std::cout \n            << \"Maximum Deviation Found:                     \" << std::setprecision(3) << std::scientific << boost::math::tools::real_cast<double>(p_remez->max_error()) << std::endl\n            << \"Expected Error Term:                         \" << std::setprecision(3) << std::scientific << boost::math::tools::real_cast<double>(p_remez->error_term()) << std::endl\n            << \"Maximum Relative Change in Control Points:   \" << std::setprecision(3) << std::scientific << boost::math::tools::real_cast<double>(r) << std::endl;\n      }\n   }\n   catch(const std::exception& e)\n   {\n      std::cout << \"Step failed with exception: \" << e.what() << std::endl;\n   }\n}\n\nvoid step(const char*, const char*)\n{\n   step_some(1);\n}\n\nvoid show(const char*, const char*)\n{\n   NTL::RR::SetPrecision(working_precision);\n   if(started)\n   {\n      boost::math::tools::polynomial<boost::math::ntl::RR> n = p_remez->numerator();\n      boost::math::tools::polynomial<boost::math::ntl::RR> d = p_remez->denominator();\n      std::vector<boost::math::ntl::RR> cn = n.chebyshev();\n      std::vector<boost::math::ntl::RR> cd = d.chebyshev();\n      int prec = 2 + (target_precision * 3010LL)/10000;\n      std::cout << std::scientific << std::setprecision(prec);\n      NTL::RR::SetOutputPrecision(prec);\n      boost::numeric::ublas::vector<boost::math::ntl::RR> v = p_remez->zero_points();\n      \n      std::cout << \"  Zeros = {\\n\";\n      unsigned i;\n      for(i = 0; i < v.size(); ++i)\n      {\n         std::cout << \"    \" << v[i] << std::endl;\n      }\n      std::cout << \"  }\\n\";\n\n      v = p_remez->chebyshev_points();\n      std::cout << \"  Chebeshev Control Points = {\\n\";\n      for(i = 0; i < v.size(); ++i)\n      {\n         std::cout << \"    \" << v[i] << std::endl;\n      }\n      std::cout << \"  }\\n\";\n\n      std::cout << \"X offset: \" << x_offset << std::endl;\n      std::cout << \"X scale:  \" << x_scale << std::endl;\n      std::cout << \"Y offset: \" << y_offset << std::endl;\n\n      std::cout << \"P = {\";\n      for(i = 0; i < n.size(); ++i)\n      {\n         std::cout << \"    \" << n[i] << \"L,\" << std::endl;\n      }\n      std::cout << \"  }\\n\";\n\n      std::cout << \"Q = {\";\n      for(i = 0; i < d.size(); ++i)\n      {\n         std::cout << \"    \" << d[i] << \"L,\" << std::endl;\n      }\n      std::cout << \"  }\\n\";\n\n      std::cout << \"CP = {\";\n      for(i = 0; i < cn.size(); ++i)\n      {\n         std::cout << \"    \" << cn[i] << \"L,\" << std::endl;\n      }\n      std::cout << \"  }\\n\";\n\n      std::cout << \"CQ = {\";\n      for(i = 0; i < cd.size(); ++i)\n      {\n         std::cout << \"    \" << cd[i] << \"L,\" << std::endl;\n      }\n      std::cout << \"  }\\n\";\n\n      show_extra(n, d, x_offset, y_offset, variant);\n   }\n   else\n   {\n      std::cerr << \"Nothing to display\" << std::endl;\n   }\n}\n\nvoid do_graph(unsigned points)\n{\n   NTL::RR::SetPrecision(working_precision);\n   boost::math::ntl::RR step = (b - a) / (points - 1);\n   boost::math::ntl::RR x = a;\n   while(points > 1)\n   {\n      NTL::RR::SetOutputPrecision(10);\n      std::cout << std::setprecision(10) << std::setw(30) << std::left \n         << boost::lexical_cast<std::string>(x) << the_function(x) << std::endl;\n      --points;\n      x += step;\n   }\n   std::cout << std::setprecision(10) << std::setw(30) << std::left \n      << boost::lexical_cast<std::string>(b) << the_function(b) << std::endl;\n}\n\nvoid graph(const char*, const char*)\n{\n   do_graph(3);\n}\n\ntemplate <class T>\nvoid do_test(T, const char* name)\n{\n   boost::math::ntl::RR::SetPrecision(working_precision);\n   if(started)\n   {\n      //\n      // We want to test the approximation at fixed precision:\n      // either float, double or long double.  Begin by getting the\n      // polynomials:\n      //\n      boost::math::tools::polynomial<T> n, d;\n      boost::math::tools::polynomial<boost::math::ntl::RR> nr, dr;\n      nr = p_remez->numerator();\n      dr = p_remez->denominator();\n      n = nr;\n      d = dr;\n\n      std::vector<boost::math::ntl::RR> cn1, cd1;\n      cn1 = nr.chebyshev();\n      cd1 = dr.chebyshev();\n      std::vector<T> cn, cd;\n      for(unsigned i = 0; i < cn1.size(); ++i)\n      {\n         cn.push_back(boost::math::tools::real_cast<T>(cn1[i]));\n      }\n      for(unsigned i = 0; i < cd1.size(); ++i)\n      {\n         cd.push_back(boost::math::tools::real_cast<T>(cd1[i]));\n      }\n      //\n      // We'll test at the Chebeshev control points which is where\n      // (in theory) the largest deviation should occur.  For good\n      // measure we'll test at the zeros as well:\n      //\n      boost::numeric::ublas::vector<boost::math::ntl::RR> \n         zeros(p_remez->zero_points()),\n         cheb(p_remez->chebyshev_points());\n\n      boost::math::ntl::RR max_error(0), cheb_max_error(0);\n\n      //\n      // Do the tests at the zeros:\n      //\n      std::cout << \"Starting tests at \" << name << \" precision...\\n\";\n      std::cout << \"Absissa        Error (Poly)   Error (Cheb)\\n\";\n      for(unsigned i = 0; i < zeros.size(); ++i)\n      {\n         boost::math::ntl::RR true_result = the_function(zeros[i]);\n         T absissa = boost::math::tools::real_cast<T>(zeros[i]);\n         boost::math::ntl::RR test_result = n.evaluate(absissa) / d.evaluate(absissa);\n         boost::math::ntl::RR cheb_result = boost::math::tools::evaluate_chebyshev(cn, absissa) / boost::math::tools::evaluate_chebyshev(cd, absissa);\n         boost::math::ntl::RR err, cheb_err;\n         if(rel_error)\n         {\n            err = boost::math::tools::relative_error(test_result, true_result);\n            cheb_err = boost::math::tools::relative_error(cheb_result, true_result);\n         }\n         else\n         {\n            err = fabs(test_result - true_result);\n            cheb_err = fabs(cheb_result - true_result);\n         }\n         if(err > max_error)\n            max_error = err;\n         if(cheb_err > cheb_max_error)\n            cheb_max_error = cheb_err;\n         std::cout << std::setprecision(6) << std::setw(15) << std::left << absissa\n            << std::setw(15) << std::left << boost::math::tools::real_cast<T>(err) << boost::math::tools::real_cast<T>(cheb_err) << std::endl;\n      }\n      //\n      // Do the tests at the Chebeshev control points:\n      //\n      for(unsigned i = 0; i < cheb.size(); ++i)\n      {\n         boost::math::ntl::RR true_result = the_function(cheb[i]);\n         T absissa = boost::math::tools::real_cast<T>(cheb[i]);\n         boost::math::ntl::RR test_result = n.evaluate(absissa) / d.evaluate(absissa);\n         boost::math::ntl::RR cheb_result = boost::math::tools::evaluate_chebyshev(cn, absissa) / boost::math::tools::evaluate_chebyshev(cd, absissa);\n         boost::math::ntl::RR err, cheb_err;\n         if(rel_error)\n         {\n            err = boost::math::tools::relative_error(test_result, true_result);\n            cheb_err = boost::math::tools::relative_error(cheb_result, true_result);\n         }\n         else\n         {\n            err = fabs(test_result - true_result);\n            cheb_err = fabs(cheb_result - true_result);\n         }\n         if(err > max_error)\n            max_error = err;\n         std::cout << std::setprecision(6) << std::setw(15) << std::left << absissa\n            << std::setw(15) << std::left << boost::math::tools::real_cast<T>(err) << \n            boost::math::tools::real_cast<T>(cheb_err) << std::endl;\n      }\n      std::string msg = \"Max Error found at \";\n      msg += name;\n      msg += \" precision = \";\n      msg.append(62 - 17 - msg.size(), ' ');\n      std::cout << msg << std::setprecision(6) << \"Poly: \" << std::setw(20) << std::left\n         << boost::math::tools::real_cast<T>(max_error) << \"Cheb: \" << boost::math::tools::real_cast<T>(cheb_max_error) << std::endl;\n   }\n   else\n   {\n      std::cout << \"Nothing to test: try converging an approximation first!!!\" << std::endl;\n   }\n}\n\nvoid test_float(const char*, const char*)\n{\n   do_test(float(0), \"float\");\n}\n\nvoid test_double(const char*, const char*)\n{\n   do_test(double(0), \"double\");\n}\n\nvoid test_long(const char*, const char*)\n{\n   do_test((long double)(0), \"long double\");\n}\n\nvoid test_all(const char*, const char*)\n{\n   do_test(float(0), \"float\");\n   do_test(double(0), \"double\");\n   do_test((long double)(0), \"long double\");\n}\n\ntemplate <class T>\nvoid do_test_n(T, const char* name, unsigned count)\n{\n   boost::math::ntl::RR::SetPrecision(working_precision);\n   if(started)\n   {\n      //\n      // We want to test the approximation at fixed precision:\n      // either float, double or long double.  Begin by getting the\n      // polynomials:\n      //\n      boost::math::tools::polynomial<T> n, d;\n      boost::math::tools::polynomial<boost::math::ntl::RR> nr, dr;\n      nr = p_remez->numerator();\n      dr = p_remez->denominator();\n      n = nr;\n      d = dr;\n\n      std::vector<boost::math::ntl::RR> cn1, cd1;\n      cn1 = nr.chebyshev();\n      cd1 = dr.chebyshev();\n      std::vector<T> cn, cd;\n      for(unsigned i = 0; i < cn1.size(); ++i)\n      {\n         cn.push_back(boost::math::tools::real_cast<T>(cn1[i]));\n      }\n      for(unsigned i = 0; i < cd1.size(); ++i)\n      {\n         cd.push_back(boost::math::tools::real_cast<T>(cd1[i]));\n      }\n\n      boost::math::ntl::RR max_error(0), max_cheb_error(0);\n      boost::math::ntl::RR step = (b - a) / count;\n\n      //\n      // Do the tests at the zeros:\n      //\n      std::cout << \"Starting tests at \" << name << \" precision...\\n\";\n      std::cout << \"Absissa        Error (poly)   Error (Cheb)\\n\";\n      for(boost::math::ntl::RR x = a; x <= b; x += step)\n      {\n         boost::math::ntl::RR true_result = the_function(x);\n         T absissa = boost::math::tools::real_cast<T>(x);\n         boost::math::ntl::RR test_result = n.evaluate(absissa) / d.evaluate(absissa);\n         boost::math::ntl::RR cheb_result = boost::math::tools::evaluate_chebyshev(cn, absissa) / boost::math::tools::evaluate_chebyshev(cd, absissa);\n         boost::math::ntl::RR err, cheb_err;\n         if(rel_error)\n         {\n            err = boost::math::tools::relative_error(test_result, true_result);\n            cheb_err = boost::math::tools::relative_error(cheb_result, true_result);\n         }\n         else\n         {\n            err = fabs(test_result - true_result);\n            cheb_err = fabs(cheb_result - true_result);\n         }\n         if(err > max_error)\n            max_error = err;\n         if(cheb_err > max_cheb_error)\n            max_cheb_error = cheb_err;\n         std::cout << std::setprecision(6) << std::setw(15) << std::left << boost::math::tools::real_cast<double>(absissa)\n            << (test_result < true_result ? \"-\" : \"\") << std::setw(20) << std::left \n            << boost::math::tools::real_cast<double>(err) \n            << boost::math::tools::real_cast<double>(cheb_err) << std::endl;\n      }\n      std::string msg = \"Max Error found at \";\n      msg += name;\n      msg += \" precision = \";\n      //msg.append(62 - 17 - msg.size(), ' ');\n      std::cout << msg << \"Poly: \" << std::setprecision(6) \n         //<< std::setw(15) << std::left \n         << boost::math::tools::real_cast<T>(max_error) \n         << \" Cheb: \" << boost::math::tools::real_cast<T>(max_cheb_error) << std::endl;\n   }\n   else\n   {\n      std::cout << \"Nothing to test: try converging an approximation first!!!\" << std::endl;\n   }\n}\n\nvoid test_n(unsigned n)\n{\n   do_test_n(boost::math::ntl::RR(), \"boost::math::ntl::RR\", n);\n}\n\nvoid test_float_n(unsigned n)\n{\n   do_test_n(float(0), \"float\", n);\n}\n\nvoid test_double_n(unsigned n)\n{\n   do_test_n(double(0), \"double\", n);\n}\n\nvoid test_long_n(unsigned n)\n{\n   do_test_n((long double)(0), \"long double\", n);\n}\n\nvoid rotate(const char*, const char*)\n{\n   if(p_remez)\n   {\n      p_remez->rotate();\n   }\n   else\n   {\n      std::cerr << \"Nothing to rotate\" << std::endl;\n   }\n}\n\nvoid rescale(const char*, const char*)\n{\n   if(p_remez)\n   {\n      p_remez->rescale(a, b);\n   }\n   else\n   {\n      std::cerr << \"Nothing to rescale\" << std::endl;\n   }\n}\n\nvoid graph_poly(const char*, const char*)\n{\n   int i = 50;\n   boost::math::ntl::RR::SetPrecision(working_precision);\n   if(started)\n   {\n      //\n      // We want to test the approximation at fixed precision:\n      // either float, double or long double.  Begin by getting the\n      // polynomials:\n      //\n      boost::math::tools::polynomial<boost::math::ntl::RR> n, d;\n      n = p_remez->numerator();\n      d = p_remez->denominator();\n\n      boost::math::ntl::RR max_error(0);\n      boost::math::ntl::RR step = (b - a) / i;\n\n      std::cout << \"Evaluating Numerator...\\n\";\n      boost::math::ntl::RR val;\n      for(val = a; val <= b; val += step)\n         std::cout << n.evaluate(val) << std::endl;\n      std::cout << \"Evaluating Denominator...\\n\";\n      for(val = a; val <= b; val += step)\n         std::cout << d.evaluate(val) << std::endl;\n   }\n   else\n   {\n      std::cout << \"Nothing to test: try converging an approximation first!!!\" << std::endl;\n   }\n}\n\nint test_main(int, char* [])\n{\n   std::string line;\n   real_parser<long double/*boost::math::ntl::RR*/ > const rr_p;\n   while(std::getline(std::cin, line))\n   {\n      if(parse(line.c_str(), str_p(\"quit\"), space_p).full)\n         return 0;\n      if(false == parse(line.c_str(), \n         (\n\n            str_p(\"range\")[assign_a(started, false)] && real_p[assign_a(a)] && real_p[assign_a(b)]\n      ||\n            str_p(\"relative\")[assign_a(started, false)][assign_a(rel_error, true)]\n      ||\n            str_p(\"absolute\")[assign_a(started, false)][assign_a(rel_error, false)]\n      ||\n            str_p(\"pin\")[assign_a(started, false)] && str_p(\"true\")[assign_a(pin, true)]\n      ||\n            str_p(\"pin\")[assign_a(started, false)] && str_p(\"false\")[assign_a(pin, false)]\n      ||\n            str_p(\"pin\")[assign_a(started, false)] && str_p(\"1\")[assign_a(pin, true)]\n      ||\n            str_p(\"pin\")[assign_a(started, false)] && str_p(\"0\")[assign_a(pin, false)]\n      ||\n            str_p(\"pin\")[assign_a(started, false)][assign_a(pin, true)]\n      ||\n            str_p(\"order\")[assign_a(started, false)] && uint_p[assign_a(orderN)] && uint_p[assign_a(orderD)]\n      ||\n            str_p(\"order\")[assign_a(started, false)] && uint_p[assign_a(orderN)]\n      ||\n            str_p(\"target-precision\") && uint_p[assign_a(target_precision)]\n      ||\n            str_p(\"working-precision\")[assign_a(started, false)] && uint_p[assign_a(working_precision)]\n      ||\n            str_p(\"variant\")[assign_a(started, false)] && int_p[assign_a(variant)]\n      ||\n            str_p(\"skew\")[assign_a(started, false)] && int_p[assign_a(skew)]\n      ||\n            str_p(\"brake\") && int_p[assign_a(brake)]\n      ||\n            str_p(\"step\") && int_p[&step_some]\n      ||\n            str_p(\"step\")[&step]\n      ||\n            str_p(\"poly\")[&graph_poly]\n      ||\n            str_p(\"info\")[&show]\n      ||\n            str_p(\"graph\") && uint_p[&do_graph]\n      ||\n            str_p(\"graph\")[&graph]\n      ||\n            str_p(\"x-offset\") && real_p[assign_a(x_offset)]\n      ||\n            str_p(\"x-scale\") && real_p[assign_a(x_scale)]\n      ||\n            str_p(\"y-offset\") && str_p(\"auto\")[assign_a(auto_offset_y, true)]\n      ||\n            str_p(\"y-offset\") && real_p[assign_a(y_offset)][assign_a(auto_offset_y, false)]\n      ||\n            str_p(\"test\") && str_p(\"float\") && uint_p[&test_float_n]\n      ||\n            str_p(\"test\") && str_p(\"float\")[&test_float]\n      ||\n            str_p(\"test\") && str_p(\"double\") && uint_p[&test_double_n]\n      ||\n            str_p(\"test\") && str_p(\"double\")[&test_double]\n      ||\n            str_p(\"test\") && str_p(\"long\") && uint_p[&test_long_n]\n      ||\n            str_p(\"test\") && str_p(\"long\")[&test_long]\n      ||\n            str_p(\"test\") && str_p(\"all\")[&test_all]\n      ||\n            str_p(\"test\") && uint_p[&test_n]\n      ||\n            str_p(\"rotate\")[&rotate]\n      ||\n            str_p(\"rescale\") && real_p[assign_a(a)] && real_p[assign_a(b)] && epsilon_p[&rescale]\n\n         ), space_p).full)\n      {\n         std::cout << \"Unable to parse directive: \\\"\" << line << \"\\\"\" << std::endl;\n      }\n      else\n      {\n         std::cout << \"Variant              = \" << variant << std::endl;\n         std::cout << \"range                = [\" << a << \",\" << b << \"]\" << std::endl;\n         std::cout << \"Relative Error       = \" << rel_error << std::endl;\n         std::cout << \"Pin to Origin        = \" << pin << std::endl;\n         std::cout << \"Order (Num/Denom)    = \" << orderN << \"/\" << orderD << std::endl;\n         std::cout << \"Target Precision     = \" << target_precision << std::endl;\n         std::cout << \"Working Precision    = \" << working_precision << std::endl;\n         std::cout << \"Skew                 = \" << skew << std::endl;\n         std::cout << \"Brake                = \" << brake << std::endl;\n         std::cout << \"X Offset             = \" << x_offset << std::endl;\n         std::cout << \"X scale              = \" << x_scale << std::endl;\n         std::cout << \"Y Offset             = \";\n         if(auto_offset_y)\n            std::cout << \"Auto (\";\n         std::cout << y_offset;\n         if(auto_offset_y)\n            std::cout << \")\";\n         std::cout << std::endl;\n     }\n   }\n   return 0;\n}\n", "meta": {"hexsha": "8d8ab324a89c3b7fa007c1fa022740f3f293d111", "size": 20787, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/minimax/main.cpp", "max_stars_repo_name": "ai-nikolaev/repo-cppboost", "max_stars_repo_head_hexsha": "218c4a977c6d8cd6f2864cdcea1b6ab53160d203", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2016-04-12T16:29:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-28T11:01:57.000Z", "max_issues_repo_path": "libs/math/minimax/main.cpp", "max_issues_repo_name": "ai-nikolaev/repo-cppboost", "max_issues_repo_head_hexsha": "218c4a977c6d8cd6f2864cdcea1b6ab53160d203", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-10-31T19:35:14.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-04T17:11:27.000Z", "max_forks_repo_path": "libs/math/minimax/main.cpp", "max_forks_repo_name": "ai-nikolaev/repo-cppboost", "max_forks_repo_head_hexsha": "218c4a977c6d8cd6f2864cdcea1b6ab53160d203", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-09-09T02:38:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-30T00:24:24.000Z", "avg_line_length": 34.1330049261, "max_line_length": 182, "alphanum_fraction": 0.5426468466, "num_tokens": 5826, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255927, "lm_q2_score": 0.6548947155710233, "lm_q1q2_score": 0.49814608572728786}}
{"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  InitializePose3.h\n *  @author Luca Carlone\n *  @author Frank Dellaert\n *  @date   August, 2014\n */\n\n#include <gtsam/slam/InitializePose3.h>\n#include <gtsam/slam/PriorFactor.h>\n#include <gtsam/slam/BetweenFactor.h>\n#include <gtsam/nonlinear/GaussNewtonOptimizer.h>\n#include <gtsam/inference/Symbol.h>\n#include <gtsam/geometry/Pose3.h>\n#include <gtsam/base/timing.h>\n\n#include <boost/math/special_functions.hpp>\n\nusing namespace std;\n\nnamespace gtsam {\nnamespace InitializePose3 {\n\nstatic const Matrix I9 = I_9x9;\nstatic const Vector zero9 = Vector::Zero(9);\nstatic const Matrix zero33 = Z_3x3;\n\nstatic const Key keyAnchor = symbol('Z', 9999999);\n\n/* ************************************************************************* */\nGaussianFactorGraph buildLinearOrientationGraph(const NonlinearFactorGraph& g) {\n\n  GaussianFactorGraph linearGraph;\n  noiseModel::Unit::shared_ptr model = noiseModel::Unit::Create(9);\n\n  for(const boost::shared_ptr<NonlinearFactor>& factor: g) {\n    Matrix3 Rij;\n\n    boost::shared_ptr<BetweenFactor<Pose3> > pose3Between =\n        boost::dynamic_pointer_cast<BetweenFactor<Pose3> >(factor);\n    if (pose3Between)\n      Rij = pose3Between->measured().rotation().matrix();\n    else\n      std::cout << \"Error in buildLinearOrientationGraph\" << std::endl;\n\n    const FastVector<Key>& keys = factor->keys();\n    Key key1 = keys[0], key2 = keys[1];\n    Matrix M9 = Z_9x9;\n    M9.block(0,0,3,3) = Rij;\n    M9.block(3,3,3,3) = Rij;\n    M9.block(6,6,3,3) = Rij;\n    linearGraph.add(key1, -I9, key2, M9, zero9, model);\n  }\n  // prior on the anchor orientation\n  linearGraph.add(keyAnchor, I9, (Vector(9) << 1.0, 0.0, 0.0,/*  */ 0.0, 1.0, 0.0, /*  */ 0.0, 0.0, 1.0).finished(), model);\n  return linearGraph;\n}\n\n/* ************************************************************************* */\n// Transform VectorValues into valid Rot3\nValues normalizeRelaxedRotations(const VectorValues& relaxedRot3) {\n  gttic(InitializePose3_computeOrientationsChordal);\n\n  Matrix ppm = Z_3x3; // plus plus minus\n  ppm(0,0) = 1; ppm(1,1) = 1; ppm(2,2) = -1;\n\n  Values validRot3;\n  for(const VectorValues::value_type& it: relaxedRot3) {\n    Key key = it.first;\n    if (key != keyAnchor) {\n      const Vector& rotVector = it.second;\n      Matrix3 rotMat;\n      rotMat(0,0) = rotVector(0); rotMat(0,1) = rotVector(1); rotMat(0,2) = rotVector(2);\n      rotMat(1,0) = rotVector(3); rotMat(1,1) = rotVector(4); rotMat(1,2) = rotVector(5);\n      rotMat(2,0) = rotVector(6); rotMat(2,1) = rotVector(7); rotMat(2,2) = rotVector(8);\n\n      Matrix U, V; Vector s;\n      svd(rotMat, U, s, V);\n      Matrix3 normalizedRotMat = U * V.transpose();\n\n      //      std::cout << \"rotMat \\n\" << rotMat << std::endl;\n      //      std::cout << \"U V' \\n\" << U * V.transpose() << std::endl;\n      //      std::cout << \"V \\n\" << V << std::endl;\n\n      if(normalizedRotMat.determinant() < 0)\n        normalizedRotMat = U * ppm * V.transpose();\n\n      Rot3 initRot = Rot3(normalizedRotMat);\n      validRot3.insert(key, initRot);\n    }\n  }\n  return validRot3;\n}\n\n/* ************************************************************************* */\n// Select the subgraph of betweenFactors and transforms priors into between wrt a fictitious node\nNonlinearFactorGraph buildPose3graph(const NonlinearFactorGraph& graph) {\n  gttic(InitializePose3_buildPose3graph);\n  NonlinearFactorGraph pose3Graph;\n\n  for(const boost::shared_ptr<NonlinearFactor>& factor: graph) {\n\n    // recast to a between on Pose3\n    boost::shared_ptr<BetweenFactor<Pose3> > pose3Between =\n        boost::dynamic_pointer_cast<BetweenFactor<Pose3> >(factor);\n    if (pose3Between)\n      pose3Graph.add(pose3Between);\n\n    // recast PriorFactor<Pose3> to BetweenFactor<Pose3>\n    boost::shared_ptr<PriorFactor<Pose3> > pose3Prior =\n        boost::dynamic_pointer_cast<PriorFactor<Pose3> >(factor);\n    if (pose3Prior)\n      pose3Graph.emplace_shared<BetweenFactor<Pose3> >(keyAnchor, pose3Prior->keys()[0],\n              pose3Prior->prior(), pose3Prior->noiseModel());\n  }\n  return pose3Graph;\n}\n\n/* ************************************************************************* */\n// Return the orientations of a graph including only BetweenFactors<Pose3>\nValues computeOrientationsChordal(const NonlinearFactorGraph& pose3Graph) {\n  gttic(InitializePose3_computeOrientationsChordal);\n\n  // regularize measurements and plug everything in a factor graph\n  GaussianFactorGraph relaxedGraph = buildLinearOrientationGraph(pose3Graph);\n\n  // Solve the LFG\n  VectorValues relaxedRot3 = relaxedGraph.optimize();\n\n  // normalize and compute Rot3\n  return normalizeRelaxedRotations(relaxedRot3);\n}\n\n/* ************************************************************************* */\n// Return the orientations of a graph including only BetweenFactors<Pose3>\nValues computeOrientationsGradient(const NonlinearFactorGraph& pose3Graph, const Values& givenGuess, const size_t maxIter, const bool setRefFrame) {\n  gttic(InitializePose3_computeOrientationsGradient);\n\n  // this works on the inverse rotations, according to Tron&Vidal,2011\n  Values inverseRot;\n  inverseRot.insert(keyAnchor, Rot3());\n  for(const Values::ConstKeyValuePair& key_value: givenGuess) {\n    Key key = key_value.key;\n    const Pose3& pose = givenGuess.at<Pose3>(key);\n    inverseRot.insert(key, pose.rotation().inverse());\n  }\n\n  // Create the map of edges incident on each node\n  KeyVectorMap adjEdgesMap;\n  KeyRotMap factorId2RotMap;\n\n  createSymbolicGraph(adjEdgesMap, factorId2RotMap, pose3Graph);\n\n  // calculate max node degree & allocate gradient\n  size_t maxNodeDeg = 0;\n  VectorValues grad;\n  for(const Values::ConstKeyValuePair& key_value: inverseRot) {\n    Key key = key_value.key;\n    grad.insert(key,Vector3::Zero());\n    size_t currNodeDeg = (adjEdgesMap.at(key)).size();\n    if(currNodeDeg > maxNodeDeg)\n      maxNodeDeg = currNodeDeg;\n  }\n\n  // Create parameters\n  double b = 1;\n  double f0 = 1/b - (1/b + M_PI) * exp(-b*M_PI);\n  double a = (M_PI*M_PI)/(2*f0);\n  double rho = 2*a*b;\n  double mu_max = maxNodeDeg * rho;\n  double stepsize = 2/mu_max; // = 1/(a b dG)\n\n  std::cout <<\" b \" << b <<\" f0 \" << f0 <<\" a \" << a <<\" rho \" << rho <<\" stepsize \" << stepsize << \" maxNodeDeg \"<< maxNodeDeg << std::endl;\n  double maxGrad;\n  // gradient iterations\n  size_t it;\n  for(it=0; it < maxIter; it++){\n    //////////////////////////////////////////////////////////////////////////\n    // compute the gradient at each node\n    //std::cout << \"it  \" << it <<\" b \" << b <<\" f0 \" << f0 <<\" a \" << a\n    //   <<\" rho \" << rho <<\" stepsize \" << stepsize << \" maxNodeDeg \"<< maxNodeDeg << std::endl;\n    maxGrad = 0;\n    for(const Values::ConstKeyValuePair& key_value: inverseRot) {\n      Key key = key_value.key;\n      //std::cout << \"---------------------------key  \" << DefaultKeyFormatter(key) << std::endl;\n      Vector gradKey = Vector3::Zero();\n      // collect the gradient for each edge incident on key\n      for(const size_t& factorId: adjEdgesMap.at(key)){\n        Rot3 Rij = factorId2RotMap.at(factorId);\n        Rot3 Ri = inverseRot.at<Rot3>(key);\n        if( key == (pose3Graph.at(factorId))->keys()[0] ){\n          Key key1 = (pose3Graph.at(factorId))->keys()[1];\n          Rot3 Rj = inverseRot.at<Rot3>(key1);\n          gradKey = gradKey + gradientTron(Ri, Rij  * Rj, a, b);\n          //std::cout << \"key1 \" << DefaultKeyFormatter(key1) << \" gradientTron(Ri, Rij  * Rj, a, b) \\n \" << gradientTron(Ri, Rij  * Rj, a, b) << std::endl;\n        }else if( key == (pose3Graph.at(factorId))->keys()[1] ){\n          Key key0 = (pose3Graph.at(factorId))->keys()[0];\n          Rot3 Rj = inverseRot.at<Rot3>(key0);\n          gradKey = gradKey + gradientTron(Ri, Rij.between(Rj), a, b);\n          //std::cout << \"key0 \" << DefaultKeyFormatter(key0) << \" gradientTron(Ri, Rij.inverse()  * Rj, a, b) \\n \" << gradientTron(Ri, Rij.between(Rj), a, b) << std::endl;\n        }else{\n          std::cout << \"Error in gradient computation\" << std::endl;\n        }\n      } // end of i-th gradient computation\n      grad.at(key) = stepsize *  gradKey;\n\n      double normGradKey = (gradKey).norm();\n      //std::cout << \"key  \" << DefaultKeyFormatter(key) <<\" \\n grad \\n\" << grad.at(key) << std::endl;\n      if(normGradKey>maxGrad)\n        maxGrad = normGradKey;\n    } // end of loop over nodes\n\n    //////////////////////////////////////////////////////////////////////////\n    // update estimates\n    inverseRot = inverseRot.retract(grad);\n\n    //////////////////////////////////////////////////////////////////////////\n    // check stopping condition\n    if (it>20 && maxGrad < 5e-3)\n      break;\n  } // enf of gradient iterations\n\n  std::cout << \"nr of gradient iterations \" << it << \"maxGrad \" << maxGrad <<  std::endl;\n\n  // Return correct rotations\n  const Rot3& Rref = inverseRot.at<Rot3>(keyAnchor); // This will be set to the identity as so far we included no prior\n  Values estimateRot;\n  for(const Values::ConstKeyValuePair& key_value: inverseRot) {\n    Key key = key_value.key;\n    if (key != keyAnchor) {\n      const Rot3& R = inverseRot.at<Rot3>(key);\n      if(setRefFrame)\n        estimateRot.insert(key, Rref.compose(R.inverse()));\n      else\n        estimateRot.insert(key, R.inverse());\n    }\n  }\n  return estimateRot;\n}\n\n/* ************************************************************************* */\nvoid createSymbolicGraph(KeyVectorMap& adjEdgesMap, KeyRotMap& factorId2RotMap, const NonlinearFactorGraph& pose3Graph){\n  size_t factorId = 0;\n  for(const boost::shared_ptr<NonlinearFactor>& factor: pose3Graph) {\n    boost::shared_ptr<BetweenFactor<Pose3> > pose3Between =\n        boost::dynamic_pointer_cast<BetweenFactor<Pose3> >(factor);\n    if (pose3Between){\n      Rot3 Rij = pose3Between->measured().rotation();\n      factorId2RotMap.insert(pair<Key, Rot3 >(factorId,Rij));\n\n      Key key1 = pose3Between->key1();\n      if (adjEdgesMap.find(key1) != adjEdgesMap.end()){  // key is already in\n        adjEdgesMap.at(key1).push_back(factorId);\n      }else{\n        vector<size_t> edge_id;\n        edge_id.push_back(factorId);\n        adjEdgesMap.insert(pair<Key, vector<size_t> >(key1, edge_id));\n      }\n      Key key2 = pose3Between->key2();\n      if (adjEdgesMap.find(key2) != adjEdgesMap.end()){  // key is already in\n        adjEdgesMap.at(key2).push_back(factorId);\n      }else{\n        vector<size_t> edge_id;\n        edge_id.push_back(factorId);\n        adjEdgesMap.insert(pair<Key, vector<size_t> >(key2, edge_id));\n      }\n    }else{\n      std::cout << \"Error in computeOrientationsGradient\" << std::endl;\n    }\n    factorId++;\n  }\n}\n\n/* ************************************************************************* */\nVector3 gradientTron(const Rot3& R1, const Rot3& R2, const double a, const double b) {\n  Vector3 logRot = Rot3::Logmap(R1.between(R2));\n\n  double th = logRot.norm();\n  if(th != th){ // the second case means that th = nan (logRot does not work well for +/-pi)\n    Rot3 R1pert = R1.compose( Rot3::Expmap(Vector3(0.01, 0.01, 0.01)) ); // some perturbation\n    logRot = Rot3::Logmap(R1pert.between(R2));\n    th = logRot.norm();\n  }\n  // exclude small or invalid rotations\n  if (th > 1e-5 && th == th){ // nonzero valid rotations\n    logRot = logRot / th;\n  }else{\n    logRot = Vector3::Zero();\n    th = 0.0;\n  }\n\n  double fdot = a*b*th*exp(-b*th);\n  return fdot*logRot;\n}\n\n/* ************************************************************************* */\nValues initializeOrientations(const NonlinearFactorGraph& graph) {\n\n  // We \"extract\" the Pose3 subgraph of the original graph: this\n  // is done to properly model priors and avoiding operating on a larger graph\n  NonlinearFactorGraph pose3Graph = buildPose3graph(graph);\n\n  // Get orientations from relative orientation measurements\n  return computeOrientationsChordal(pose3Graph);\n}\n\n///* ************************************************************************* */\nValues computePoses(NonlinearFactorGraph& pose3graph,  Values& initialRot) {\n  gttic(InitializePose3_computePoses);\n\n  // put into Values structure\n  Values initialPose;\n  for(const Values::ConstKeyValuePair& key_value: initialRot){\n    Key key = key_value.key;\n    const Rot3& rot = initialRot.at<Rot3>(key);\n    Pose3 initializedPose = Pose3(rot, Point3(0, 0, 0));\n    initialPose.insert(key, initializedPose);\n  }\n  // add prior\n  noiseModel::Unit::shared_ptr priorModel = noiseModel::Unit::Create(6);\n  initialPose.insert(keyAnchor, Pose3());\n  pose3graph.emplace_shared<PriorFactor<Pose3> >(keyAnchor, Pose3(), priorModel);\n\n  // Create optimizer\n  GaussNewtonParams params;\n  bool singleIter = true;\n  if(singleIter){\n    params.maxIterations = 1;\n  }else{\n    std::cout << \" \\n\\n\\n\\n  performing more than 1 GN iterations \\n\\n\\n\" <<std::endl;\n    params.setVerbosity(\"TERMINATION\");\n  }\n  GaussNewtonOptimizer optimizer(pose3graph, initialPose, params);\n  Values GNresult = optimizer.optimize();\n\n  // put into Values structure\n  Values estimate;\n  for(const Values::ConstKeyValuePair& key_value: GNresult) {\n    Key key = key_value.key;\n    if (key != keyAnchor) {\n      const Pose3& pose = GNresult.at<Pose3>(key);\n      estimate.insert(key, pose);\n    }\n  }\n  return estimate;\n}\n\n/* ************************************************************************* */\nValues initialize(const NonlinearFactorGraph& graph) {\n  gttic(InitializePose3_initialize);\n\n  // We \"extract\" the Pose3 subgraph of the original graph: this\n  // is done to properly model priors and avoiding operating on a larger graph\n  NonlinearFactorGraph pose3Graph = buildPose3graph(graph);\n\n  // Get orientations from relative orientation measurements\n  Values valueRot3 = computeOrientationsChordal(pose3Graph);\n\n  // Compute the full poses (1 GN iteration on full poses)\n  return computePoses(pose3Graph, valueRot3);\n}\n\n/* ************************************************************************* */\nValues initialize(const NonlinearFactorGraph& graph, const Values& givenGuess, bool useGradient) {\n  Values initialValues;\n\n  // We \"extract\" the Pose3 subgraph of the original graph: this\n  // is done to properly model priors and avoiding operating on a larger graph\n  NonlinearFactorGraph pose3Graph = buildPose3graph(graph);\n\n  // Get orientations from relative orientation measurements\n  Values orientations;\n  if(useGradient)\n    orientations = computeOrientationsGradient(pose3Graph, givenGuess);\n  else\n    orientations = computeOrientationsChordal(pose3Graph);\n\n//  orientations.print(\"orientations\\n\");\n\n  // Compute the full poses (1 GN iteration on full poses)\n  return computePoses(pose3Graph, orientations);\n\n  //  for(const Values::ConstKeyValuePair& key_value: orientations) {\n  //    Key key = key_value.key;\n  //    if (key != keyAnchor) {\n  //      const Point3& pos = givenGuess.at<Pose3>(key).translation();\n  //      const Rot3& rot = orientations.at<Rot3>(key);\n  //      Pose3 initializedPoses = Pose3(rot, pos);\n  //      initialValues.insert(key, initializedPoses);\n  //    }\n  //  }\n  //  return initialValues;\n}\n\n} // end of namespace lago\n} // end of namespace gtsam\n", "meta": {"hexsha": "58408e7e32d2915dcd43ed900b96d96e696f94c4", "size": 15436, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/slam/InitializePose3.cpp", "max_stars_repo_name": "colinxs/gtsam", "max_stars_repo_head_hexsha": "c6d9baf3ce4b5ced7fec4c52e304a31b8eadffd0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-04-10T03:25:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-01T12:10:54.000Z", "max_issues_repo_path": "gtsam/slam/InitializePose3.cpp", "max_issues_repo_name": "colinxs/gtsam", "max_issues_repo_head_hexsha": "c6d9baf3ce4b5ced7fec4c52e304a31b8eadffd0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-12-14T06:41:31.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-14T06:41:31.000Z", "max_forks_repo_path": "gtsam/slam/InitializePose3.cpp", "max_forks_repo_name": "colinxs/gtsam", "max_forks_repo_head_hexsha": "c6d9baf3ce4b5ced7fec4c52e304a31b8eadffd0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-08-16T17:47:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-19T10:36:57.000Z", "avg_line_length": 37.9262899263, "max_line_length": 172, "alphanum_fraction": 0.616934439, "num_tokens": 4111, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581741774411, "lm_q2_score": 0.6757646075489391, "lm_q1q2_score": 0.498145404274511}}
{"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  Pose3.cpp\n * @brief 3D Pose\n */\n\n#include <gtsam/geometry/Pose3.h>\n#include <gtsam/geometry/Pose2.h>\n#include <gtsam/geometry/concepts.h>\n#include <gtsam/base/Lie-inl.h>\n#include <boost/foreach.hpp>\n#include <iostream>\n#include <cmath>\n\nusing namespace std;\n\nnamespace gtsam {\n\n/** Explicit instantiation of base class to export members */\nINSTANTIATE_LIE(Pose3);\n\n/** instantiate concept checks */\nGTSAM_CONCEPT_POSE_INST(Pose3);\n\nstatic const Matrix3 I3 = eye(3), Z3 = zeros(3, 3), _I3 = -I3;\nstatic const Matrix6 I6 = eye(6);\n\n/* ************************************************************************* */\nPose3::Pose3(const Pose2& pose2) :\n    R_(Rot3::rodriguez(0, 0, pose2.theta())), t_(\n        Point3(pose2.x(), pose2.y(), 0)) {\n}\n\n/* ************************************************************************* */\n// Calculate Adjoint map\n// Ad_pose is 6*6 matrix that when applied to twist xi, returns Ad_pose(xi)\n// Experimental - unit tests of derivatives based on it do not check out yet\nMatrix6 Pose3::AdjointMap() const {\n  const Matrix3 R = R_.matrix();\n  const Vector3 t = t_.vector();\n  Matrix3 A = skewSymmetric(t) * R;\n  Matrix6 adj;\n  adj << R, Z3, A, R;\n  return adj;\n}\n\n/* ************************************************************************* */\nMatrix6 Pose3::adjointMap(const Vector& xi) {\n  Matrix3 w_hat = skewSymmetric(xi(0), xi(1), xi(2));\n  Matrix3 v_hat = skewSymmetric(xi(3), xi(4), xi(5));\n  Matrix6 adj;\n  adj << w_hat, Z3, v_hat, w_hat;\n\n  return adj;\n}\n\n/* ************************************************************************* */\nVector Pose3::adjoint(const Vector& xi, const Vector& y,\n    boost::optional<Matrix&> H) {\n  if (H) {\n    *H = zeros(6, 6);\n    for (int i = 0; i < 6; ++i) {\n      Vector dxi = zero(6);\n      dxi(i) = 1.0;\n      Matrix Gi = adjointMap(dxi);\n      (*H).col(i) = Gi * y;\n    }\n  }\n  return adjointMap(xi) * y;\n}\n\n/* ************************************************************************* */\nVector Pose3::adjointTranspose(const Vector& xi, const Vector& y,\n    boost::optional<Matrix&> H) {\n  if (H) {\n    *H = zeros(6, 6);\n    for (int i = 0; i < 6; ++i) {\n      Vector dxi = zero(6);\n      dxi(i) = 1.0;\n      Matrix GTi = adjointMap(dxi).transpose();\n      (*H).col(i) = GTi * y;\n    }\n  }\n  Matrix adjT = adjointMap(xi).transpose();\n  return adjointMap(xi).transpose() * y;\n}\n\n/* ************************************************************************* */\nMatrix6 Pose3::dExpInv_exp(const Vector& xi) {\n  // Bernoulli numbers, from Wikipedia\n  static const Vector B = (Vector(9) << 1.0, -1.0 / 2.0, 1. / 6., 0.0, -1.0 / 30.0,\n      0.0, 1.0 / 42.0, 0.0, -1.0 / 30);\n  static const int N = 5; // order of approximation\n  Matrix res = I6;\n  Matrix6 ad_i = I6;\n  Matrix6 ad_xi = adjointMap(xi);\n  double fac = 1.0;\n  for (int i = 1; i < N; ++i) {\n    ad_i = ad_xi * ad_i;\n    fac = fac * i;\n    res = res + B(i) / fac * ad_i;\n  }\n  return res;\n}\n\n/* ************************************************************************* */\nvoid Pose3::print(const string& s) const {\n  cout << s;\n  R_.print(\"R:\\n\");\n  t_.print(\"t: \");\n}\n\n/* ************************************************************************* */\nbool Pose3::equals(const Pose3& pose, double tol) const {\n  return R_.equals(pose.R_, tol) && t_.equals(pose.t_, tol);\n}\n\n/* ************************************************************************* */\n/** Modified from Murray94book version (which assumes w and v normalized?) */\nPose3 Pose3::Expmap(const Vector& xi) {\n\n  // get angular velocity omega and translational velocity v from twist xi\n  Point3 w(xi(0), xi(1), xi(2)), v(xi(3), xi(4), xi(5));\n\n  double theta = w.norm();\n  if (theta < 1e-10) {\n    static const Rot3 I;\n    return Pose3(I, v);\n  } else {\n    Point3 n(w / theta); // axis unit vector\n    Rot3 R = Rot3::rodriguez(n.vector(), theta);\n    double vn = n.dot(v); // translation parallel to n\n    Point3 n_cross_v = n.cross(v); // points towards axis\n    Point3 t = (n_cross_v - R * n_cross_v) / theta + vn * n;\n    return Pose3(R, t);\n  }\n}\n\n/* ************************************************************************* */\nVector6 Pose3::Logmap(const Pose3& p) {\n  Vector3 w = Rot3::Logmap(p.rotation()), T = p.translation().vector();\n  double t = w.norm();\n  if (t < 1e-10) {\n    Vector6 log;\n    log << w, T;\n    return log;\n  } else {\n    Matrix3 W = skewSymmetric(w / t);\n    // Formula from Agrawal06iros, equation (14)\n    // simplified with Mathematica, and multiplying in T to avoid matrix math\n    double Tan = tan(0.5 * t);\n    Vector3 WT = W * T;\n    Vector3 u = T - (0.5 * t) * WT + (1 - t / (2. * Tan)) * (W * WT);\n    Vector6 log;\n    log << w, u;\n    return log;\n  }\n}\n\n/* ************************************************************************* */\nPose3 Pose3::retractFirstOrder(const Vector& xi) const {\n  Vector3 omega(sub(xi, 0, 3));\n  Point3 v(sub(xi, 3, 6));\n  Rot3 R = R_.retract(omega); // R is done exactly\n  Point3 t = t_ + R_ * v; // First order t approximation\n  return Pose3(R, t);\n}\n\n/* ************************************************************************* */\n// Different versions of retract\nPose3 Pose3::retract(const Vector& xi, Pose3::CoordinatesMode mode) const {\n  if (mode == Pose3::EXPMAP) {\n    // Lie group exponential map, traces out geodesic\n    return compose(Expmap(xi));\n  } else if (mode == Pose3::FIRST_ORDER) {\n    // First order\n    return retractFirstOrder(xi);\n  } else {\n    // Point3 t = t_.retract(v.vector()); // Incorrect version retracts t independently\n    // Point3 t = t_ + R_ * (v+Point3(omega).cross(v)/2); // Second order t approximation\n    assert(false);\n    exit(1);\n  }\n}\n\n/* ************************************************************************* */\n// different versions of localCoordinates\nVector6 Pose3::localCoordinates(const Pose3& T,\n    Pose3::CoordinatesMode mode) const {\n  if (mode == Pose3::EXPMAP) {\n    // Lie group logarithm map, exact inverse of exponential map\n    return Logmap(between(T));\n  } else if (mode == Pose3::FIRST_ORDER) {\n    // R is always done exactly in all three retract versions below\n    Vector3 omega = R_.localCoordinates(T.rotation());\n\n    // Incorrect version\n    // Independently computes the logmap of the translation and rotation\n    // Vector v = t_.localCoordinates(T.translation());\n\n    // Correct first order t inverse\n    Point3 d = R_.unrotate(T.translation() - t_);\n\n    // TODO: correct second order t inverse\n    Vector6 local;\n    local << omega(0), omega(1), omega(2), d.x(), d.y(), d.z();\n    return local;\n  } else {\n    assert(false);\n    exit(1);\n  }\n}\n\n/* ************************************************************************* */\nMatrix4 Pose3::matrix() const {\n  const Matrix3 R = R_.matrix();\n  const Vector3 T = t_.vector();\n  Eigen::Matrix<double, 1, 4> A14;\n  A14 << 0.0, 0.0, 0.0, 1.0;\n  Matrix4 mat;\n  mat << R, T, A14;\n  return mat;\n}\n\n/* ************************************************************************* */\nPose3 Pose3::transform_to(const Pose3& pose) const {\n  Rot3 cRv = R_ * Rot3(pose.R_.inverse());\n  Point3 t = pose.transform_to(t_);\n  return Pose3(cRv, t);\n}\n\n/* ************************************************************************* */\nPoint3 Pose3::transform_from(const Point3& p, boost::optional<Matrix&> Dpose,\n    boost::optional<Matrix&> Dpoint) const {\n  if (Dpose) {\n    const Matrix R = R_.matrix();\n    Matrix DR = R * skewSymmetric(-p.x(), -p.y(), -p.z());\n    Dpose->resize(3, 6);\n    (*Dpose) << DR, R;\n  }\n  if (Dpoint)\n    *Dpoint = R_.matrix();\n  return R_ * p + t_;\n}\n\n/* ************************************************************************* */\nPoint3 Pose3::transform_to(const Point3& p, boost::optional<Matrix&> Dpose,\n    boost::optional<Matrix&> Dpoint) const {\n  const Point3 result = R_.unrotate(p - t_);\n  if (Dpose) {\n    const Point3& q = result;\n    Matrix DR = skewSymmetric(q.x(), q.y(), q.z());\n    Dpose->resize(3, 6);\n    (*Dpose) << DR, _I3;\n  }\n  if (Dpoint)\n    *Dpoint = R_.transpose();\n  return result;\n}\n\n/* ************************************************************************* */\nPose3 Pose3::compose(const Pose3& p2, boost::optional<Matrix&> H1,\n    boost::optional<Matrix&> H2) const {\n  if (H1)\n    *H1 = p2.inverse().AdjointMap();\n  if (H2)\n    *H2 = I6;\n  return (*this) * p2;\n}\n\n/* ************************************************************************* */\nPose3 Pose3::inverse(boost::optional<Matrix&> H1) const {\n  if (H1)\n    *H1 = -AdjointMap();\n  Rot3 Rt = R_.inverse();\n  return Pose3(Rt, Rt * (-t_));\n}\n\n/* ************************************************************************* */\n// between = compose(p2,inverse(p1));\nPose3 Pose3::between(const Pose3& p2, boost::optional<Matrix&> H1,\n    boost::optional<Matrix&> H2) const {\n  Pose3 result = inverse() * p2;\n  if (H1)\n    *H1 = -result.inverse().AdjointMap();\n  if (H2)\n    *H2 = I6;\n  return result;\n}\n\n/* ************************************************************************* */\ndouble Pose3::range(const Point3& point, boost::optional<Matrix&> H1,\n    boost::optional<Matrix&> H2) const {\n  if (!H1 && !H2)\n    return transform_to(point).norm();\n  Point3 d = transform_to(point, H1, H2);\n  double x = d.x(), y = d.y(), z = d.z(), d2 = x * x + y * y + z * z, n = sqrt(\n      d2);\n  Matrix D_result_d = (Matrix(1, 3) << x / n, y / n, z / n);\n  if (H1)\n    *H1 = D_result_d * (*H1);\n  if (H2)\n    *H2 = D_result_d * (*H2);\n  return n;\n}\n\n/* ************************************************************************* */\ndouble Pose3::range(const Pose3& point, boost::optional<Matrix&> H1,\n    boost::optional<Matrix&> H2) const {\n  double r = range(point.translation(), H1, H2);\n  if (H2) {\n    Matrix H2_ = *H2 * point.rotation().matrix();\n    *H2 = zeros(1, 6);\n    insertSub(*H2, H2_, 0, 3);\n  }\n  return r;\n}\n\n/* ************************************************************************* */\nboost::optional<Pose3> align(const vector<Point3Pair>& pairs) {\n  const size_t n = pairs.size();\n  if (n < 3)\n    return boost::none; // we need at least three pairs\n\n  // calculate centroids\n  Vector cp = zero(3), cq = zero(3);\n  BOOST_FOREACH(const Point3Pair& pair, pairs){\n  cp += pair.first.vector();\n  cq += pair.second.vector();\n}\n  double f = 1.0 / n;\n  cp *= f;\n  cq *= f;\n\n  // Add to form H matrix\n  Matrix H = zeros(3, 3);\n  BOOST_FOREACH(const Point3Pair& pair, pairs){\n  Vector dp = pair.first.vector() - cp;\n  Vector dq = pair.second.vector() - cq;\n  H += dp * dq.transpose();\n}\n\n// Compute SVD\n  Matrix U, V;\n  Vector S;\n  svd(H, U, S, V);\n\n  // Recover transform with correction from Eggert97machinevisionandapplications\n  Matrix UVtranspose = U * V.transpose();\n  Matrix detWeighting = eye(3, 3);\n  detWeighting(2, 2) = UVtranspose.determinant();\n  Rot3 R(Matrix(V * detWeighting * U.transpose()));\n  Point3 t = Point3(cq) - R * Point3(cp);\n  return Pose3(R, t);\n}\n\n/* ************************************************************************* */\nstd::ostream &operator<<(std::ostream &os, const Pose3& pose) {\n  os << pose.rotation() << \"\\n\" << pose.translation() << endl;\n  return os;\n}\n\n} // namespace gtsam\n", "meta": {"hexsha": "bfd2fcb9aed98a9b673d8911a898399d8502cb4f", "size": 11512, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/geometry/Pose3.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": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-05-10T08:07:42.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-26T19:11:18.000Z", "max_issues_repo_path": "gtsam/geometry/Pose3.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": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gtsam/geometry/Pose3.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": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-02-17T18:55:24.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-25T00:28:40.000Z", "avg_line_length": 30.7807486631, "max_line_length": 89, "alphanum_fraction": 0.5044301598, "num_tokens": 3215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799252, "lm_q2_score": 0.6757645944891558, "lm_q1q2_score": 0.49814537903890155}}
{"text": "/*cppimport\n<%\ncfg['include_dirs'] = ['../..','../extern']\ncfg['compiler_args'] = ['-std=c++17', '-w']\ncfg['dependencies'] = ['xbin.hpp', '../util/assertions.hpp',\n'../util/global_rng.hpp']\n\ncfg['parallel'] = False\nsetup_pybind11(cfg)\n%>\n*/\n\n#include <Eigen/Geometry>\n\n#include <random>\n#include <unordered_set>\n\n#include \"rpxdock/util/Timer.hpp\"\n#include \"rpxdock/util/assertions.hpp\"\n#include \"rpxdock/util/global_rng.hpp\"\n#include \"rpxdock/util/types.hpp\"\n#include \"rpxdock/xbin/xbin.hpp\"\n\n#include <pybind11/pybind11.h>\nnamespace py = pybind11;\n\nnamespace rpxdock {\nusing namespace util;\n\nnamespace xbin {\nnamespace test {\n\ntemplate <class F, int M, int O>\nvoid rand_xform(std::mt19937& rng, Eigen::Transform<F, 3, M, O>& x,\n                float max_cart = 512.0f) {\n  std::uniform_real_distribution<F> runif;\n  std::normal_distribution<F> rnorm;\n  Eigen::Quaternion<F> qrand(rnorm(rng), rnorm(rng), rnorm(rng), rnorm(rng));\n  qrand.normalize();\n  x.linear() = qrand.matrix();\n  x.translation() = V3<F>(runif(rng) * max_cart - max_cart / 2.0,\n                          runif(rng) * max_cart - max_cart / 2.0,\n                          runif(rng) * max_cart - max_cart / 2.0);\n}\n\ntemplate <class F>\nX3<F> rand_xform(F max_cart = 512.0) {\n  X3<F> x;\n  rand_xform(global_rng(), x, max_cart);\n  return x;\n}\n\nusing std::cout;\nusing std::endl;\n\ntypedef Eigen::Transform<double, 3, Eigen::AffineCompact> Xform;\n// typedef Eigen::Affine3d Xform;\n\ntemplate <template <class X> class XformHash>\nint get_num_ori_cells(int ori_nside, double& xcov) {\n  std::mt19937 rng((unsigned int)time(0) + 7693487);\n  XformHash<Xform> xh(1.0, ori_nside, 512.0);\n  int n_ori_bins;\n  {\n    std::unordered_set<size_t> idx_seen;\n    // idx_seen.set_empty_key(std::numeric_limits<uint64_t>::max());\n\n    int NSAMP = std::max(1000000, 500 * ori_nside * ori_nside * ori_nside);\n    Xform x;\n    for (int i = 0; i < NSAMP; ++i) {\n      rand_xform(rng, x, 512.0);\n      x.translation()[0] = x.translation()[1] = x.translation()[2] = 0;\n      idx_seen.insert(xh.get_key(x));\n    }\n    n_ori_bins = (int)idx_seen.size();\n    xcov = (double)NSAMP / n_ori_bins;\n  }\n  return n_ori_bins;\n}\n\ntemplate <template <class X> class XformHash>\nbool xform_hash_perf_test(double cart_resl, double ang_resl,\n                          int const N2 = 100 * 1000, unsigned int seed = 0) {\n  std::mt19937 rng((unsigned int)time(0) + seed);\n\n  double time_key = 0.0, time_cen = 0.0;\n\n  XformHash<Xform> xh(cart_resl, ang_resl, 512.0);\n  ang_resl = xh.ori_resl();\n  double cart_resl2 = cart_resl * cart_resl;\n  double ang_resl2 = ang_resl * ang_resl;\n\n  std::vector<Xform> samples(N2), centers(N2);\n\n  for (int i = 0; i < N2; ++i) rand_xform(rng, samples[i], 512.0);\n\n  util::Timer tk;\n  std::vector<uint64_t> keys(N2);\n  for (int i = 0; i < N2; ++i) {\n    keys[i] = xh.get_key(samples[i]);\n    // centers[i] = xh.get_center( keys[i] );\n    // cout << endl;\n  }\n  time_key += (double)tk.elapsed_nano();\n\n  util::Timer tc;\n  for (int i = 0; i < N2; ++i) centers[i] = xh.get_center(keys[i]);\n  time_cen += (double)tc.elapsed_nano();\n\n  std::unordered_set<size_t> idx_seen;\n  // idx_seen.set_empty_key(std::numeric_limits<uint64_t>::max());\n  for (int i = 0; i < N2; ++i) idx_seen.insert(keys[i]);\n\n  double covrad = 0, max_dt = 0, max_da = 0;\n  for (int i = 0; i < N2; ++i) {\n    Xform l = centers[i].inverse() * samples[i];\n    double dt = l.translation().norm();\n    Eigen::Matrix3d m;\n    for (int k = 0; k < 9; ++k) m.data()[k] = l.data()[k];\n    // cout << m << endl;\n    // cout << l.rotation() << endl;\n    double da = Eigen::AngleAxisd(m).angle() * 180.0 / M_PI;\n    // double da = Eigen::AngleAxisd(l.rotation()).angle()*180.0/M_PI;\n    double err = sqrt(da * da / ang_resl2 * cart_resl2 + dt * dt);\n    covrad = fmax(covrad, err);\n    max_dt = fmax(max_dt, dt);\n    max_da = fmax(max_da, da);\n  }\n  if (max_dt > cart_resl * 1.1 || max_dt < cart_resl * 0.8)\n    std::cout << \"TEST FAIL cart: \" << cart_resl << \" \" << max_dt << std::endl;\n  if (max_da > ang_resl * 1.1 || max_da < ang_resl * 0.8)\n    std::cout << \"TEST FAIL ang: \" << ang_resl << \" \" << max_da << \" \"\n              << xh.get_ori_resl(xh.ori_nside_) << std::endl;\n  ASSERT_GT(max_dt, cart_resl * 0.8)\n  ASSERT_LT(max_dt, cart_resl * 1.1)\n  ASSERT_GT(max_da, ang_resl * 0.8)\n  ASSERT_LT(max_da, ang_resl * 1.1)\n\n  double tot_cell_vol = covrad * covrad * covrad * covrad * covrad * covrad *\n                        xh.approx_nori() / (cart_resl * cart_resl * cart_resl);\n  // printf(\n  // \" %5.3f/%5.1f cr %5.3f dt %5.3f da %6.3f x2k: %7.3fns k2x: %7.3fns \"\n  // \"%9.3f \"\n  // \"%7lu\\n\",\n  // cart_resl, ang_resl, covrad, max_dt / cart_resl, max_da / ang_resl,\n  // time_key / N2, time_cen / N2, tot_cell_vol, xh.approx_nori());\n\n  // cout << \" rate \" << N1*N2/time_key << \"  \" << N1*N2/time_cen << endl;\n  return true;\n}\n\nbool TEST_XformHash_XformHash_bt24_BCC6() {\n  unsigned int s = 0;\n  int N = 10 * 1000;\n  bool pass = true;\n  // cout << \"  bt24_BCC6\";\n  pass &= xform_hash_perf_test<XformHash_bt24_BCC6>(4.00, 30.0, N, ++s);\n  // cout << \"  bt24_BCC6\";\n  pass &= xform_hash_perf_test<XformHash_bt24_BCC6>(2.00, 20.0, N, ++s);\n  // cout << \"  bt24_BCC6\";\n  pass &= xform_hash_perf_test<XformHash_bt24_BCC6>(1.00, 15.0, N, ++s);\n  // cout << \"  bt24_BCC6\";\n  pass &= xform_hash_perf_test<XformHash_bt24_BCC6>(0.50, 10.0, N, ++s);\n  // cout << \"  bt24_BCC6\";\n  pass &= xform_hash_perf_test<XformHash_bt24_BCC6>(0.25, 5.0, N, ++s);\n  // cout << \"  bt24_BCC6\";\n  pass &= xform_hash_perf_test<XformHash_bt24_BCC6>(0.11, 3.3, N, ++s);\n  return pass;\n}\n\nPYBIND11_MODULE(xbin_test, m) {\n  m.def(\"TEST_XformHash_XformHash_bt24_BCC6\",\n        &TEST_XformHash_XformHash_bt24_BCC6);\n}\n\n}  // namespace test\n}  // namespace xbin\n}  // namespace rpxdock\n", "meta": {"hexsha": "0c2a3ce2de05d7ab04d37fe7f569bd9e5b68c688", "size": 5764, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rpxdock/xbin/xbin_test.cpp", "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/xbin/xbin_test.cpp", "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/xbin/xbin_test.cpp", "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": 32.2011173184, "max_line_length": 79, "alphanum_fraction": 0.6221374046, "num_tokens": 2014, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799252, "lm_q2_score": 0.6757645879592642, "lm_q1q2_score": 0.49814537422533867}}
{"text": "/*-----------------------------------------------------------------------------+\nCopyright (c) 2007-2009: Joachim Faulhaber\n+------------------------------------------------------------------------------+\nCopyright (c) 1999-2006: Cortex Software GmbH, Kantstrasse 57, Berlin\n+------------------------------------------------------------------------------+\n   Distributed under the Boost Software License, Version 1.0.\n      (See accompanying file LICENCE.txt or copy at\n           http://www.boost.org/LICENSE_1_0.txt)\n+-----------------------------------------------------------------------------*/\n\n/*-----------------------------------------------------------------------------+\nitvset_shell.cpp provides  a simple test shells for interval sets.\nThe shell also gives you a good idea how interval container are working.\n+-----------------------------------------------------------------------------*/\n#include <iostream>\n\n#include <boost/icl/split_interval_set.hpp>\n#include <boost/icl/split_interval_map.hpp>\n\nusing namespace std;\nusing namespace boost;\nusing namespace boost::icl;\n\nvoid instructions()\n{\n    cout << \"+++++ Test shell for interval set +++++\\n\";\n    cout << \"Type: q e or 0  to quit\\n\";\n    cout << \"Type: +         for insertions\\n\";\n    cout << \"Type: -         for subtraction\\n\";\n    cout << \"Type: j         to join contiguous intervals\\n\";\n    cout << \"Type: s         to compute total size\\n\";\n}\n\nvoid wrongInput()\n{\n    cout << \"Wrong Input ------------------\\n\";\n    instructions();\n}\n\n\ntemplate <class SetTV>\nvoid setTestShell()\n{\n    SetTV m1;\n\n    try {\n        char cmd = 'b';\n        typename SetTV::domain_type lwb = typename SetTV::domain_type();\n        typename SetTV::domain_type upb = typename SetTV::domain_type();\n\n        instructions();\n\n        for(;;)\n        {\n            cout << \"> \";\n            cin >> cmd ;\n\n            switch(cmd)\n            {\n            case 'q':\n            case 'e':\n            case '0': cout << \"good bye\\n\"; return;\n            case '+':\n                {\n                    cout << \"input: lwb upb >> \";\n                    cin >> lwb >> upb;\n                    typename SetTV::interval_type itv\n                        = typename SetTV::interval_type(lwb,upb);\n                    // SetTV::IntervalTD itv = rightOpenInterval(lwb,upb);\n                    m1.insert(itv);\n\n                    cout << \"+\" << itv << \" =\" << endl;\n                    cout << \"{\" << m1 << \"}\" << endl;\n\n                }\n                break;\n            case '-':\n                {\n                    cout << \"input: lwb upb >> \";\n                    cin >> lwb >> upb;\n                    typename SetTV::interval_type itv\n                        = typename SetTV::interval_type(lwb,upb);\n                    // m1.subtract(itv);\n                    SetTV tmp;\n                    tmp.insert(itv);\n                    m1 -= tmp;\n\n                    cout << \"-\" << itv << \" =\" << endl;\n                    cout << \"{\" << m1 << \"}\" << endl;\n\n                }\n                break;\n            case 'j':\n                {\n                    icl::join(m1);\n                    cout << \"{\" << m1 << \"}\" << endl;\n                }\n                break;\n            case 's':\n                {\n                    cout << \"size = \" << m1.size() << endl;\n                }\n                break;\n\n            default: wrongInput();\n            }\n        }\n\n    }\n    catch (exception& e)\n    {\n        cout << \"itvset_shell: exception caught: \" << endl\n             << e.what() << endl;\n    }\n    catch (...)\n    {\n        cout << \"itvset_shell: unknown exception caught\" << endl;\n    }\n}\n\n\n\n\nint main()\n{\n    cout << \">>Interval Container Library: Test itvset_shell.cpp <<\\n\";\n    cout << \"------------------------------------------------------\\n\";\n    setTestShell< interval_set<int> >();\n\n    return 0;\n}\n", "meta": {"hexsha": "2286ff537f868cfb87d760c68aa9d845d22340ea", "size": 3871, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/libs/icl/example/itvset_shell_/itvset_shell.cpp", "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/libs/icl/example/itvset_shell_/itvset_shell.cpp", "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/libs/icl/example/itvset_shell_/itvset_shell.cpp", "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": 29.3257575758, "max_line_length": 80, "alphanum_fraction": 0.3849134591, "num_tokens": 789, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.4981325098866607}}
{"text": "/*\n * @file\n * @author University of Warwick\n * @version 1.0\n *\n * @section LICENSE\n *\n * @section DESCRIPTION\n *\n * Unit Tests for the concrete methods of the Triangle class\n */\n\n\n#define BOOST_TEST_MODULE Triangle\n#include <boost/test/unit_test.hpp>\n#include <boost/test/output_test_stream.hpp>\n#include <stdexcept>\n\n#include \"Triangle.h\"\n#include \"EuclideanPoint.h\"\n\nusing namespace cupcfd::geometry::shapes;\nnamespace euc = cupcfd::geometry::euclidean;\nnamespace utf = boost::unit_test;\n\n// === Constructor ===\n// Test 1: Constructor: 3 Defined Points - 2D\nBOOST_AUTO_TEST_CASE(constructor_test1)\n{\n\teuc::EuclideanPoint<double,2> p1(3.0, 4.0);\n\teuc::EuclideanPoint<double,2> p2(4.0, 12.0);\n\teuc::EuclideanPoint<double,2> p3(3.3, 15.0);\n\n\tTriangle<double,2> shape(p1, p2, p3);\n\n\tBOOST_CHECK_EQUAL(shape.a.cmp[0], p1.cmp[0]);\n\tBOOST_CHECK_EQUAL(shape.a.cmp[1], p1.cmp[1]);\n\tBOOST_CHECK_EQUAL(shape.b.cmp[0], p2.cmp[0]);\n\tBOOST_CHECK_EQUAL(shape.b.cmp[1], p2.cmp[1]);\n\tBOOST_CHECK_EQUAL(shape.c.cmp[0], p3.cmp[0]);\n\tBOOST_CHECK_EQUAL(shape.c.cmp[1], p3.cmp[1]);\n}\n\n// Test 2: Constructor: 3 Defined Points - 3D\nBOOST_AUTO_TEST_CASE(constructor_test2)\n{\n\teuc::EuclideanPoint<double,3> p1(3.0, 4.0, 5.0);\n\teuc::EuclideanPoint<double,3> p2(4.0, 12.0, 20.0);\n\teuc::EuclideanPoint<double,3> p3(3.3, 15.0, 21.0);\n\n\tTriangle<double,3> shape(p1, p2, p3);\n\tBOOST_CHECK_EQUAL(shape.a.cmp[0], p1.cmp[0]);\n\tBOOST_CHECK_EQUAL(shape.a.cmp[1], p1.cmp[1]);\n\tBOOST_CHECK_EQUAL(shape.a.cmp[2], p1.cmp[2]);\n\tBOOST_CHECK_EQUAL(shape.b.cmp[0], p2.cmp[0]);\n\tBOOST_CHECK_EQUAL(shape.b.cmp[1], p2.cmp[1]);\n\tBOOST_CHECK_EQUAL(shape.b.cmp[2], p2.cmp[2]);\n\tBOOST_CHECK_EQUAL(shape.c.cmp[0], p3.cmp[0]);\n\tBOOST_CHECK_EQUAL(shape.c.cmp[1], p3.cmp[1]);\n\tBOOST_CHECK_EQUAL(shape.c.cmp[2], p3.cmp[2]);\n}\n\n// === isPointInsideBarycentric (static, 2D) ===\nBOOST_AUTO_TEST_CASE(isPointInsideBarycentric_static_test1)\n{\n\t// Setup\n\teuc::EuclideanPoint<double,2> p1(3.0, 4.0);\n\teuc::EuclideanPoint<double,2> p2(4.0, 12.0);\n\teuc::EuclideanPoint<double,2> p3(3.3, 15.0);\n\n\t// Test and Check\n\teuc::EuclideanPoint<double,2> p4(3.1, 6.0);\n\n\tbool inside = Triangle<double,2>::isPointInsideBarycentric(p1,p2,p3,p4);\n\tBOOST_CHECK_EQUAL(inside, true);\n}\n\n// Test 2: Test a point on top of vertex a - 2D\nBOOST_AUTO_TEST_CASE(isPointInsideBarycentric_static_test2)\n{\n\t// Setup\n\teuc::EuclideanPoint<double,2> p1(3.0, 4.0);\n\teuc::EuclideanPoint<double,2> p2(4.0, 12.0);\n\teuc::EuclideanPoint<double,2> p3(3.3, 15.0);\n\n\teuc::EuclideanPoint<double,2> p4 = p1;\n\n\t// Test and Check\n\tbool inside = Triangle<double,2>::isPointInsideBarycentric(p1,p2,p3,p4);\n\tBOOST_CHECK_EQUAL(inside, true);\n}\n\n// Test 3: Test a point on top of vertex b - 2D\nBOOST_AUTO_TEST_CASE(isPointInsideBarycentric_static_test3)\n{\n\t// Setup\n\teuc::EuclideanPoint<double,2> p1(3.0, 4.0);\n\teuc::EuclideanPoint<double,2> p2(4.0, 12.0);\n\teuc::EuclideanPoint<double,2> p3(3.3, 15.0);\n\n\teuc::EuclideanPoint<double,2> p4 = p2;\n\n\t// Test and Check\n\tbool inside = Triangle<double,2>::isPointInsideBarycentric(p1,p2,p3,p4);\n\tBOOST_CHECK_EQUAL(inside, true);\n}\n\n// Test 4: Test a point on top of vertex c - 2D\nBOOST_AUTO_TEST_CASE(isPointInsideBarycentric_static_test4)\n{\n\t// Setup\n\teuc::EuclideanPoint<double,2> p1(3.0, 4.0);\n\teuc::EuclideanPoint<double,2> p2(4.0, 12.0);\n\teuc::EuclideanPoint<double,2> p3(3.3, 15.0);\n\n\teuc::EuclideanPoint<double,2> p4 = p3;\n\n\t// Test and Check\n\tbool inside = Triangle<double,2>::isPointInsideBarycentric(p1,p2,p3,p4);\n\tBOOST_CHECK_EQUAL(inside, true);\n}\n\n// Test 5: Test a point on edge ab - 2D\nBOOST_AUTO_TEST_CASE(isPointInsideBarycentric_static_test5)\n{\n\t// Setup\n\teuc::EuclideanPoint<double,2> p1(3.0, 4.0);\n\teuc::EuclideanPoint<double,2> p2(4.0, 12.0);\n\teuc::EuclideanPoint<double,2> p3(3.3, 15.0);\n\n\t// Test and Check\n\teuc::EuclideanPoint<double,2> p4(3.5, 8.0);\n\n\tbool inside = Triangle<double,2>::isPointInsideBarycentric(p1,p2,p3,p4);\n\tBOOST_CHECK_EQUAL(inside, true);\n}\n\n// Test 6: Test a point on edge ac - 2D\nBOOST_AUTO_TEST_CASE(isPointInsideBarycentric_static_test6)\n{\n\t// Setup\n\teuc::EuclideanPoint<double,2> p1(3.0, 4.0);\n\teuc::EuclideanPoint<double,2> p2(4.0, 12.0);\n\teuc::EuclideanPoint<double,2> p3(3.3, 15.0);\n\n\t// Test and Check\n\teuc::EuclideanPoint<double,2> p4(3.15, 9.5);\n\n\tbool inside = Triangle<double,2>::isPointInsideBarycentric(p1,p2,p3,p4);\n\tBOOST_CHECK_EQUAL(inside, true);\n}\n\n// Test 7: Test a point on edge bc - 2D\nBOOST_AUTO_TEST_CASE(isPointInsideBarycentric_static_test7)\n{\n\t// Setup\n\teuc::EuclideanPoint<double,2> p1(3.0, 4.0);\n\teuc::EuclideanPoint<double,2> p2(4.0, 12.0);\n\teuc::EuclideanPoint<double,2> p3(3.3, 15.0);\n\n\t// Test and Check\n\teuc::EuclideanPoint<double,2> p4(3.65, 13.5);\n\n\tbool inside = Triangle<double,2>::isPointInsideBarycentric(p1,p2,p3,p4);\n\tBOOST_CHECK_EQUAL(inside, true);\n}\n\n// Test 8: Test a point outside the Triangle - 2D\nBOOST_AUTO_TEST_CASE(isPointInsideBarycentric_static_test8)\n{\n\t// Setup\n\teuc::EuclideanPoint<double,2> p1(3.0, 4.0);\n\teuc::EuclideanPoint<double,2> p2(4.0, 12.0);\n\teuc::EuclideanPoint<double,2> p3(3.3, 15.0);\n\n\t// Test and Check\n\teuc::EuclideanPoint<double,2> p4(1.0, 1.34);\n\n\tbool inside = Triangle<double,2>::isPointInsideBarycentric(p1,p2,p3,p4);\n\tBOOST_CHECK_EQUAL(inside, false);\n}\n\n// Test 9: Test a point inside when a.cmp[1] == c.cmp[1] - 2D\nBOOST_AUTO_TEST_CASE(isPointInsideBarycentric_static_test9)\n{\n\t// Setup\n\teuc::EuclideanPoint<double,2> p1(3.0, 4.0);\n\teuc::EuclideanPoint<double,2> p2(3.15, 12.0);\n\teuc::EuclideanPoint<double,2> p3(3.3, 4.0);\n\n\t// Test and Check\n\teuc::EuclideanPoint<double,2> p4(3.15, 4.2);\n\n\tbool inside = Triangle<double,2>::isPointInsideBarycentric(p1,p2,p3,p4);\n\tBOOST_CHECK_EQUAL(inside, true);\n}\n\n// === heronsFormula ===\n// Test 1: Test the area is computed correctly - 2D\nBOOST_AUTO_TEST_CASE(heronsFormula_test1, * utf::tolerance(0.00001))\n{\n\t// Setup\n\teuc::EuclideanPoint<double,2> p1(3.0, 4.0);\n\teuc::EuclideanPoint<double,2> p2(3.15, 12.0);\n\teuc::EuclideanPoint<double,2> p3(3.3, 4.0);\n\n\t// Test and Check\n\tdouble area = Triangle<double,2>::heronsFormula(p1, p2, p3);\n\tBOOST_TEST(area == 1.2);\n}\n\n// Test 2: Test the area is computed correctly - 2D\nBOOST_AUTO_TEST_CASE(heronsFormula_test2, * utf::tolerance(0.00001))\n{\n\t// Setup\n\teuc::EuclideanPoint<double,2> p1(3.0, 4.0);\n\teuc::EuclideanPoint<double,2> p2(6.0, 4.0);\n\teuc::EuclideanPoint<double,2> p3(3.0, 12.0);\n\n\t// Test and Check\n\tdouble area = Triangle<double,2>::heronsFormula(p1, p2, p3);\n\tBOOST_TEST(area == 12.0);\n}\n\n// Test 3: Test the area is computed correctly - 3D\nBOOST_AUTO_TEST_CASE(areaHeronsFormula_test3,  * utf::tolerance(0.00001))\n{\n\t// Setup\n\teuc::EuclideanPoint<double,3> p1(3.0, 4.0, 8.0);\n\teuc::EuclideanPoint<double,3> p2(3.15, 12.0, 14.0);\n\teuc::EuclideanPoint<double,3> p3(3.3, 4.0, 9.0);\n\n\tTriangle<double,3> shape(p1, p2, p3);\n\n\t// Test and Check\n\tdouble area = Triangle<double,3>::heronsFormula(p1, p2, p3);\n\tBOOST_TEST(area == 4.25683);\n}\n\n// Test 4: Test the area is computed correctly - 3D\nBOOST_AUTO_TEST_CASE(areaHeronsFormula_test4,  * utf::tolerance(0.00001))\n{\n\t// Setup\n\teuc::EuclideanPoint<double,3> p1(3.0, 4.0, 8.9);\n\teuc::EuclideanPoint<double,3> p2(6.0, 4.0, 7.6);\n\teuc::EuclideanPoint<double,3> p3(3.0, 12.0, 15.4);\n\n\tTriangle<double,3> shape(p1, p2, p3);\n\n\t// Test and Check\n\tdouble area = Triangle<double,3>::heronsFormula(p1, p2, p3);\n\tBOOST_TEST(area == 16.3126);\n}\n\n// === getArea ===\n// Test 1: Test the area is computed correctly - 2D\nBOOST_AUTO_TEST_CASE(getArea_test1, * utf::tolerance(0.00001))\n{\n\t// Setup\n\teuc::EuclideanPoint<double,2> p1(3.0, 4.0);\n\teuc::EuclideanPoint<double,2> p2(3.15, 12.0);\n\teuc::EuclideanPoint<double,2> p3(3.3, 4.0);\n\n\t// Test and Check\n\tTriangle<double,2> shape(p1, p2, p3);\n\tdouble area = shape.getArea();\n\tBOOST_TEST(area == 1.2);\n}\n\n// Test 2: Test the area is computed correctly - 2D\nBOOST_AUTO_TEST_CASE(getArea_test2, * utf::tolerance(0.00001))\n{\n\t// Setup\n\teuc::EuclideanPoint<double,2> p1(3.0, 4.0);\n\teuc::EuclideanPoint<double,2> p2(6.0, 4.0);\n\teuc::EuclideanPoint<double,2> p3(3.0, 12.0);\n\n\t// Test and Check\n\tTriangle<double,2> shape(p1, p2, p3);\n\tdouble area = shape.getArea();\n\tBOOST_TEST(area == 12.0);\n}\n\n// Test 3: Test the area is computed correctly - 3D\nBOOST_AUTO_TEST_CASE(getArea_test3,  * utf::tolerance(0.00001))\n{\n\t// Setup\n\teuc::EuclideanPoint<double,3> p1(3.0, 4.0, 8.0);\n\teuc::EuclideanPoint<double,3> p2(3.15, 12.0, 14.0);\n\teuc::EuclideanPoint<double,3> p3(3.3, 4.0, 9.0);\n\n\t// Test and Check\n\tTriangle<double,3> shape(p1, p2, p3);\n\tdouble area = shape.getArea();\n\tBOOST_TEST(area == 4.25683);\n}\n\n// Test 4: Test the area is computed correctly - 3D\nBOOST_AUTO_TEST_CASE(getArea_test4,  * utf::tolerance(0.00001))\n{\n\t// Setup\n\teuc::EuclideanPoint<double,3> p1(3.0, 4.0, 8.9);\n\teuc::EuclideanPoint<double,3> p2(6.0, 4.0, 7.6);\n\teuc::EuclideanPoint<double,3> p3(3.0, 12.0, 15.4);\n\n\t// Test and Check\n\tTriangle<double,3> shape(p1, p2, p3);\n\tdouble area = shape.getArea();\n\tBOOST_TEST(area == 16.3126);\n}\n\n// === getNormal ===\n// Test 1: Compute the correct normal, and check that the direction is as expected for anticlockwise\n// vertices from origin\nBOOST_AUTO_TEST_CASE(getNormal_test1,  * utf::tolerance(0.00001))\n{\n\teuc::EuclideanPoint<double,3> p1(0.0, 0.0, 2.0);\n\teuc::EuclideanPoint<double,3> p2(5.0, 0.0, 2.0);\n\teuc::EuclideanPoint<double,3> p3(0.0, 5.0, 2.0);\n\n\tTriangle<double,3> shape(p1, p2, p3);\n\n\teuc::EuclideanVector<double,3> normalCmp(0.0,0.0,1.0);\n\teuc::EuclideanVector<double,3> normal = shape.getNormal();\n\n\tBOOST_TEST(normal.cmp[0] == normalCmp[0]);\n\tBOOST_TEST(normal.cmp[1] == normalCmp[1]);\n\tBOOST_TEST(normal.cmp[2] == normalCmp[2]);\n}\n\n// Test 2: Compute the correct normal, and check that the direction is as expected for clockwise vertices\n// from origin\nBOOST_AUTO_TEST_CASE(getNormal_test2,  * utf::tolerance(0.00001))\n{\n\teuc::EuclideanPoint<double,3> p1(0.0, 5.0, 2.0);\n\teuc::EuclideanPoint<double,3> p2(5.0, 0.0, 2.0);\n\teuc::EuclideanPoint<double,3> p3(0.0, 0.0, 2.0);\n\n\tTriangle<double,3> shape(p1, p2, p3);\n\n\teuc::EuclideanVector<double,3> normalCmp(0.0,0.0,-1.0);\n\teuc::EuclideanVector<double,3> normal = shape.getNormal();\n\n\tBOOST_TEST(normal.cmp[0] == normalCmp[0]);\n\tBOOST_TEST(normal.cmp[1] == normalCmp[1]);\n\tBOOST_TEST(normal.cmp[2] == normalCmp[2]);\n}\n\n// Test 3: Test correct normal for a 2D triangle translated into a 3D space with a Z component of 0.\nBOOST_AUTO_TEST_CASE(getNormal_test3,  * utf::tolerance(0.00001))\n{\n\n}\n", "meta": {"hexsha": "0d5cf9725be17d34e50ffce683395fe1f959c684", "size": 10400, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/geometry/shapes/implementation/component/TriangleTestsOld.cpp", "max_stars_repo_name": "thorbenlouw/CUP-CFD", "max_stars_repo_head_hexsha": "d06f7673a1ed12bef24de4f1b828ef864fa45958", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-06-24T10:20:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-18T14:43:19.000Z", "max_issues_repo_path": "tests/geometry/shapes/implementation/component/TriangleTestsOld.cpp", "max_issues_repo_name": "thorbenlouw/CUP-CFD", "max_issues_repo_head_hexsha": "d06f7673a1ed12bef24de4f1b828ef864fa45958", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-07-22T15:31:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-28T14:27:28.000Z", "max_forks_repo_path": "tests/geometry/shapes/implementation/component/TriangleTestsOld.cpp", "max_forks_repo_name": "thorbenlouw/CUP-CFD", "max_forks_repo_head_hexsha": "d06f7673a1ed12bef24de4f1b828ef864fa45958", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-07-22T15:24:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-22T15:24:24.000Z", "avg_line_length": 29.3785310734, "max_line_length": 105, "alphanum_fraction": 0.7010576923, "num_tokens": 3892, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850154599562, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.49813249241558066}}
{"text": "/*****************************************************************************\n*\n* Rokko: Integrated Interface for libraries of eigenvalue decomposition\n*\n* Copyright (C) 2012-2015 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#include <iostream>\n#include <boost/lexical_cast.hpp>\n#include <rokko/localized_matrix.hpp>\n#include <rokko/utility/frank_matrix.hpp>\n#include <rokko/utility/timer.hpp>\n\nint main(int argc, char **argv) {\n  int dim;\n  if (argc > 1) {\n    dim = boost::lexical_cast<int>(argv[1]);\n  } else {\n    std::cin >> dim;\n  }\n\n  rokko::timer timer;\n  timer.registrate(1, \"generate\");\n  timer.registrate(2, \"eigenvalue\");\n\n  rokko::global_timer::registrate(1, \"generate\");\n  rokko::global_timer::registrate(2, \"eigenvalue\");\n  timer.start(1);\n  rokko::global_timer::start(1);\n  rokko::localized_matrix<double, rokko::matrix_col_major> mat(dim, dim);\n  rokko::frank_matrix::generate(mat);\n  std::cout << \"dimension = \" << dim << std::endl;\n  std::cout << \"[elements of frank matrix]\" << std::endl;\n  std::cout << mat << std::endl;\n  timer.stop(1);\n  rokko::global_timer::stop(1);\n\n  timer.start(2);\n  rokko::global_timer::start(2);\n  std::cout << \"[eigenvalues of frank matrix]\" << std::endl;\n  double sum = 0;\n  for (int i = 0; i < dim; ++i) {\n    double ev = rokko::frank_matrix::eigenvalue(dim, i);\n    sum += ev;\n    std::cout << ev << \"  \";\n  }\n  std::cout << std::endl;\n  timer.stop(2);\n  rokko::global_timer::stop(2);\n\n  std::cout << \"[sum of eigenvalues of frank matrix]\" << std::endl;\n  std::cout << sum << std::endl;\n  \n  timer.summarize();\n  rokko::global_timer::summarize();\n}\n", "meta": {"hexsha": "f6189982dbe8aecb98829cd304eb6b20aa6538fa", "size": 1845, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/timer.cpp", "max_stars_repo_name": "wistaria/rokko", "max_stars_repo_head_hexsha": "7cd9d5155e82f038039a46c1dc8f382b3fe7e2b7", "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": "test/timer.cpp", "max_issues_repo_name": "wistaria/rokko", "max_issues_repo_head_hexsha": "7cd9d5155e82f038039a46c1dc8f382b3fe7e2b7", "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/timer.cpp", "max_forks_repo_name": "wistaria/rokko", "max_forks_repo_head_hexsha": "7cd9d5155e82f038039a46c1dc8f382b3fe7e2b7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2459016393, "max_line_length": 79, "alphanum_fraction": 0.6032520325, "num_tokens": 528, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850933, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.49810725275234036}}
{"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/gf/homogeneous.h\"\n\nusing namespace boost::python;\n\nPXR_NAMESPACE_USING_DIRECTIVE\n\nvoid wrapHomogeneous()\n{    \n    def(\"GetHomogenized\", (GfVec4d (*)(const GfVec4d &)) GfGetHomogenized);\n    def(\"GetHomogenized\", (GfVec4f (*)(const GfVec4f &)) GfGetHomogenized);\n\n    def(\"HomogeneousCross\", (GfVec4d (*)(const GfVec4d &, const GfVec4d &)) GfHomogeneousCross);\n    def(\"HomogeneousCross\", (GfVec4f (*)(const GfVec4f &, const GfVec4f &)) GfHomogeneousCross);\n\n    def(\"Project\", (GfVec3d (*)(const GfVec4d &)) GfProject);\n    def(\"Project\", (GfVec3f (*)(const GfVec4f &)) GfProject);\n}\n", "meta": {"hexsha": "fd70318aa842d7c0834a4bb72315642f757923a2", "size": 1740, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pxr/base/gf/wrapHomogeneous.cpp", "max_stars_repo_name": "DougRogers-DigitalFish/USD", "max_stars_repo_head_hexsha": "d8a405a1344480f859f025c4f97085143efacb53", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3680.0, "max_stars_repo_stars_event_min_datetime": "2016-07-26T18:28:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T09:55:05.000Z", "max_issues_repo_path": "pxr/base/gf/wrapHomogeneous.cpp", "max_issues_repo_name": "DougRogers-DigitalFish/USD", "max_issues_repo_head_hexsha": "d8a405a1344480f859f025c4f97085143efacb53", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1759.0, "max_issues_repo_issues_event_min_datetime": "2016-07-26T19:19:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T21:24:00.000Z", "max_forks_repo_path": "pxr/base/gf/wrapHomogeneous.cpp", "max_forks_repo_name": "DougRogers-DigitalFish/USD", "max_forks_repo_head_hexsha": "d8a405a1344480f859f025c4f97085143efacb53", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 904.0, "max_forks_repo_forks_event_min_datetime": "2016-07-26T18:33:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T09:55:16.000Z", "avg_line_length": 39.5454545455, "max_line_length": 96, "alphanum_fraction": 0.7270114943, "num_tokens": 467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.7025300573952052, "lm_q1q2_score": 0.4981072527523402}}
{"text": "#include <cmath>\n#include <iostream>\n#include <stdio.h>\n#include <vector>\n#include <sys/time.h>\n#include <chrono>\n#include <sys/resource.h>   // check the memory usage\n#include <stdio.h>\n#include <thread>\n#include <fstream>\n#include <sstream>\n\n#include <NTL/RR.h>\n#include <NTL/xdouble.h>\n#include <NTL/ZZ.h>\n#include <NTL/ZZX.h>\n#include <NTL/BasicThreadPool.h>\n\n\n#include \"../src/CZZ.h\"\n#include \"../src/Params.h\"\n#include \"../src/PubKey.h\"\n#include \"../src/Scheme.h\"\n#include \"../src/SchemeAlgo.h\"\n#include \"../src/SecKey.h\"\n#include \"../src/TestScheme.h\"\n#include \"../src/TimeUtils.h\"\n#include \"../src/Ring2Utils.h\"\n#include \"../src/StringUtils.h\"\n#include \"../src/EvaluatorUtils.h\"\n\n#include \"Database.h\"\n#include \"LRtest.h\"\n#include \"HELR.h\"\n\n\nusing namespace NTL;\nusing namespace std;\n\n\n\nint main(int Argc, char** Argv) {\n\n    \n    if(Argc != 3){\n        cout << \"-------------------------------------------------------------\" << endl;\n        cerr << \"Enter the File and degree of approximation \\t\"  << \"(e.g. $test edin.txt 3) \\n \";\n    }\n    \n    char* filename  =  Argv[1];\n    int polydeg = atoi(Argv[2]);  // degree of approximation polynomial\n    \n    \n    dMat  zData;\n    dMat* zTest = new dMat[5];\n    dMat* zTrain = new dMat[5];\n    \n    \n    int nLine= readData(zData, filename);\n    \n    cout << \"Sample the learning and test data ...\" << endl;\n    cvRandomSamplingData(zTrain, zTest, zData, filename);\n\n    \n    //----------------------------------------------------------------\n    // Parameters for Logistic regression\n    //----------------------------------------------------------------\n\n    long logN= 17;\n    long logp= 28;\n    long logl= 10;\n    long logq, cBit1, cBit2;\n    int max_iter;\n    \n    struct LRpar LRparams;\n    ReadLRparams(LRparams, max_iter, zTrain[0], polydeg, logp);\n    \n    SetNumThreads(LRparams.dim1);\n    //SetNumThreads(4);\n    \n    switch(polydeg){\n        case 3:\n            cBit1=  (LRparams.logn - LRparams.log2polyscale);          // 1st iteration\n            cBit2 =  (3*logp+ LRparams. logn - LRparams.log2polyscale);  // 2nd~ iteration\n            logq = cBit1 + (LRparams.max_iter-1)*(cBit2)+ logp + logl;                  // max-bitlength we need\n            break;\n            \n        case 7:\n            cBit1=  (LRparams.logn - LRparams.log2polyscale);          // 1st iteration\n            cBit2=  (4*logp+ LRparams.logn - LRparams.log2polyscale);\n            logq= cBit1 + (LRparams.max_iter-1)*(cBit2)+ logp + logl;\n            break;\n    }\n    \n \n    \n    \n    cout << \"Data dimension with dummy vectors: \" << LRparams.dim1 << \", Number of lines: \" << nLine << endl;\n    \n    cout << \"-------------------------------------------------------------\" << endl;\n    cout << \"Key Generation ... (logN,logp,logq, nslots)= (\" ;\n    cout << logN << \",\" << logp << \",\" << logq << \",\" << LRparams.nslots << \")\" <<endl;\n    \n    auto start= chrono::steady_clock::now();\n    \n    Params params(logN, logq);\n    SecKey secretKey(params);\n    PubKey publicKey(params, secretKey);\n    SchemeAux schemeaux(logN);\n    Scheme scheme(params, publicKey, schemeaux);\n    SchemeAlgo algo(scheme);\n    \n    auto end = std::chrono::steady_clock::now();\n    auto diff = end - start;\n    cout << \"KeyGen time= \" << chrono::duration <double, milli> (diff).count()/1000.0 << \" s\" << endl;\n\n    \n\n    \n    LogReg LR(scheme, secretKey, LRparams);\n    dMat HEtheta_list;\n    \n    ofstream fout;\n    fout.open(\"beta.txt\");\n\n    \n    for(int k = 0; k < 1; ++k){\n        \n        cout << \"-------------------------------------------------------------\" << endl;\n        cout << k << \"th Data Encryption ... \" << endl;\n        \n        struct rusage usage;\n        \n        start= chrono::steady_clock::now();\n        \n        Cipher* zTrainCipher = new Cipher[LRparams.dim1];\n        \n        LR.EncryptData(zTrainCipher, zTrain[k]);\n        \n        end = std::chrono::steady_clock::now();\n        diff = end - start;\n        cout << \"Enc time= \"  << chrono::duration <double, milli> (diff).count()/1000.0 << \"(s), \" ;\n        \n        int ret = getrusage(RUSAGE_SELF,&usage);\n        cout<< \"Mem: \" << usage.ru_maxrss/(1024)  << \"(MB)\" << endl;\n        \n    \n        cout << \"-------------------------------------------------------------\" << endl;\n        cout << \"HE Logistic Regression ... \"  << endl;\n        \n        Cipher* thetaCipher= new Cipher[LRparams.dim1];\n        \n        start= chrono::steady_clock::now();\n        \n        LR.HElogreg(thetaCipher, zTrainCipher, zTrain[k]);\n        \n        \n        end = std::chrono::steady_clock::now();\n        diff = end - start;\n        cout << \"Eval time= \"  << chrono::duration <double, milli> (diff).count()/1000.0 << \"(s), \" ;\n        \n        ret = getrusage(RUSAGE_SELF,&usage);\n        cout<< \"Mem: \" << usage.ru_maxrss/(1024)  << \"(MB)\" << endl;\n        \n        \n        cout << \"-------------------------------------------------------------\" << endl;\n        cout << \"Decryption ... \"  << endl;\n        \n        dVec HEtheta(LRparams.dim1, 0.0);\n\n        CZZ* dtheta = new CZZ[LRparams.dim1];\n    \n        for(int i=0; i< LRparams.dim1; ++i){\n            dtheta[i] = (scheme.decrypt(secretKey, thetaCipher[i]))[0];\n            \n            conv(HEtheta[i], dtheta[i].r);\n            HEtheta[i] = scaledown(HEtheta[i], LRparams.logp);\n            cout << \"[\" << HEtheta[i] << \"] \" ;\n        }\n        cout << \": enc \" << endl;\n        \n        getAUC(HEtheta, zTest[k]);\n        HEtheta_list.push_back(HEtheta);\n        \n        \n        cout << \"-------------------------------------------------------------\" << endl;\n        cout << \"Compare with unenc LR \" << endl;\n        dVec mtheta(LRparams.dim1, 0.0);\n        \n        for(int i= 0; i< LRparams.max_iter; i++){\n            LR_poly(mtheta, zTrain[k], LRparams);\n        }\n        \n        for(int i= 0; i< LRparams.dim1; i++)\n            cout << \"[\" << mtheta[i] << \"] \" ;\n        cout << \": unenc \" << endl;\n        \n        getAUC(mtheta, zTest[k]);\n        \n        cout << \"MSE (HELR/non-HELR): \" << getMSE(HEtheta, mtheta) << endl;\n        \n        \n        cout << \"-------------------------------------------------------------\" << endl;\n        cout << \"Compare with sigmoid LR \" << endl;\n        dVec mtheta_sig(LRparams.dim1, 0.0);\n        \n        for(int i= 0; i< LRparams.max_iter; i++){\n            LR_sigmoid(mtheta_sig, zTrain[k], LRparams);\n        }\n        \n        for(int i= 0; i< LRparams.dim1; i++)\n            cout << \"[\" << mtheta_sig[i] << \"] \" ;\n        cout << \": unenc \" << endl;\n        \n        getAUC(mtheta_sig, zTest[k]);\n        \n        cout << \"MSE (HELR/non-HELR): \" << getMSE(HEtheta, mtheta_sig) << endl;\n\n    }\n \n    \n    //! write the beta results in the text file\n    fout << \"-------------------------------------------------------------\" << endl;\n    fout << \"[\" << endl;\n    for(int i = 0; i < LRparams.dim1; ++i){\n        for(int k = 0; k < 4; ++k){\n            fout << HEtheta_list[k][i] << \",\" ;\n        }\n        fout << HEtheta_list[4][i] << \";\" << endl;\n    }\n    fout << \"];\" << endl;\n    fout.close();\n    \n \n    \n    delete[] zTest;\n    delete[] zTrain;\n\n    return 0;\n}\n\n\n\n\n\n\n", "meta": {"hexsha": "ee6ac088bbb0fcbc9ef20fd68682a2262fc6b81b", "size": 7190, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Test_HELR.cpp", "max_stars_repo_name": "K-miran/HELR", "max_stars_repo_head_hexsha": "c94951f2691d55defc82f95d3144c831eb6c8796", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2018-01-20T13:31:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T02:56:15.000Z", "max_issues_repo_path": "Test_HELR.cpp", "max_issues_repo_name": "yuejiayang/HELR", "max_issues_repo_head_hexsha": "5bc8ee66430e1e9a4f933a700260008ce35cb118", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-01-25T02:54:53.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-09T10:48:39.000Z", "max_forks_repo_path": "Test_HELR.cpp", "max_forks_repo_name": "yuejiayang/HELR", "max_forks_repo_head_hexsha": "5bc8ee66430e1e9a4f933a700260008ce35cb118", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2018-01-20T13:31:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-28T02:20:39.000Z", "avg_line_length": 29.1093117409, "max_line_length": 112, "alphanum_fraction": 0.4696801113, "num_tokens": 1887, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044095, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4980952262609611}}
{"text": "#ifndef LARGE\n#define LARGE\n\n#include <Eigen/Dense>\n#include <algorithm>\n#include <iostream>\n\n#include \"MiniDnn/layer.h\"\n#include \"MiniDnn/layer/conv.h\"\n#include \"MiniDnn/layer/fully_connected.h\"\n#include \"MiniDnn/layer/ave_pooling.h\"\n#include \"MiniDnn/layer/max_pooling.h\"\n#include \"MiniDnn/layer/relu.h\"\n#include \"MiniDnn/layer/sigmoid.h\"\n#include \"MiniDnn/layer/softmax.h\"\n#include \"MiniDnn/loss.h\"\n#include \"MiniDnn/loss/mse_loss.h\"\n#include \"MiniDnn/loss/cross_entropy_loss.h\"\n#include \"MiniDnn/mnist.h\"\n#include \"MiniDnn/network.h\"\n#include \"MiniDnn/optimizer.h\"\n#include \"MiniDnn/optimizer/sgd.h\"\n#include \"Enclave.h\"\n#include \"Enclave_t.h\"  /* print_string */\n\n\n\nusing namespace std;\n\n# define SIZE_CONTROLL 72\n# define CATEGORY 2\n\nclass RandData {\npublic:\n    Matrix train_data;\n    Matrix train_labels;\n\n    RandData(int size) {\n        train_data = Matrix::Random(SIZE_CONTROLL * SIZE_CONTROLL, size);\n        train_labels = Matrix::Ones(1, size);\n    }\n};\n\nvoid ecall_ml_large() {\n    // data\n//    MNIST dataset(\"/Users/rc/Study/Projects/mini-dnn/data/mnist/\");\n//    dataset.read();\n//    int n_train = dataset.train_data.cols();\n//    int dim_in = dataset.train_data.rows();\n//    std::cout << \"mnist train number: \" << n_train << std::endl;\n//    std::cout << \"mnist test number: \" << dataset.test_labels.cols() << std::endl;\n    RandData dataset(10240);\n//    dataset.read();\n    int n_train = dataset.train_data.cols();\n    int dim_in = dataset.train_data.rows();\n    // dnn\n    Network dnn;\n\n\n    // std::chrono::time_point<std::chrono::high_resolution_clock> start, end;\n    // std::chrono::duration<double> elapsed;\n\n\n    //------------------------------------------------------------\n\n    Layer *fc_fc1 = new FullyConnected(SIZE_CONTROLL * SIZE_CONTROLL, SIZE_CONTROLL * SIZE_CONTROLL);\n    Layer *fc_relu1 = new ReLU;\n\n    dnn.add_layer(fc_fc1);\n    dnn.add_layer(fc_relu1);\n\n    Layer *fc_fc2 = new FullyConnected(SIZE_CONTROLL * SIZE_CONTROLL, CATEGORY);\n    Layer *fc_relu2 = new Softmax;\n\n    dnn.add_layer(fc_fc2);\n    dnn.add_layer(fc_relu2);\n\n    // loss\n    Loss *loss = new CrossEntropy;\n    dnn.add_loss(loss);\n    // train & test\n    SGD opt(0.001, 5e-4, 0.9, true);\n    // SGD opt(0.001);\n    const int n_epoch = 3;\n    // const int batch_size = 3072;\n    for (int batch_size=8192; batch_size<=10240; batch_size+=1024){\n        printf(\"batch_size=%d\\n\", batch_size);\n        for (int epoch = 0; epoch < n_epoch; epoch++) {\n            shuffle_data(dataset.train_data, dataset.train_labels);\n            for (int start_idx = 0, rounds=0; start_idx < n_train && rounds < 1; start_idx += batch_size) {\n                int ith_batch = start_idx / batch_size;\n                Matrix x_batch = dataset.train_data.block(0, start_idx, dim_in,\n                                                          std::min(batch_size, n_train - start_idx));\n                Matrix label_batch = dataset.train_labels.block(0, start_idx, 1,\n                                                                std::min(batch_size, n_train - start_idx));\n                Matrix target_batch = one_hot_encode(label_batch, CATEGORY);\n\n\n                // start = std::chrono::high_resolution_clock::now();\n                ocall_start_clock();\n                dnn.forward(x_batch);\n                ocall_end_clock(\"Forward: %f  \");\n                // end = std::chrono::high_resolution_clock::now();\n                // elapsed = end - start;\n                // std::cout << \"Forward: \" << elapsed.count() << std::endl;\n\n                // start = std::chrono::high_resolution_clock::now();\n                ocall_start_clock();\n                dnn.backward(x_batch, target_batch);\n                // end = std::chrono::high_resolution_clock::now();\n                // elapsed = end - start;\n                // std::cout << \"Backward: \" << elapsed.count() << std::endl;\n\n                // optimize\n                // dnn.update(opt);\n                ocall_end_clock(\"Backward: %f\\n\");\n                rounds++;\n            }\n\n        }\n    }\n}\n\n#endif\n", "meta": {"hexsha": "d377f9f6800ebf2b18e84389123bf2a7bce53b66", "size": 4054, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Enclave/large.cpp", "max_stars_repo_name": "zeyu-zh/TrustFL", "max_stars_repo_head_hexsha": "9e05a7e160bbf4fa1e7a426767f69158ea89b22d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2020-09-11T18:06:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T11:16:59.000Z", "max_issues_repo_path": "Enclave/large.cpp", "max_issues_repo_name": "zeyu-zh/TrustFL", "max_issues_repo_head_hexsha": "9e05a7e160bbf4fa1e7a426767f69158ea89b22d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Enclave/large.cpp", "max_forks_repo_name": "zeyu-zh/TrustFL", "max_forks_repo_head_hexsha": "9e05a7e160bbf4fa1e7a426767f69158ea89b22d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-01-29T02:52:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-22T09:10:56.000Z", "avg_line_length": 32.432, "max_line_length": 107, "alphanum_fraction": 0.5878145042, "num_tokens": 1006, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044095, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4980952262609611}}
{"text": "//------------------------------------------------------------------------------\n/// \\file StateMonad_tests.cpp\n/// \\author Ernest Yeung\n//------------------------------------------------------------------------------\n#include \"Categories/Monads/OldStateMonad.h\"\n\n#include <boost/test/unit_test.hpp>\n#include <cmath>\n#include <type_traits> // std::underlying_type\n#include <utility> // std::pair\n\nBOOST_AUTO_TEST_SUITE(Categories)\nBOOST_AUTO_TEST_SUITE(Monads)\nBOOST_AUTO_TEST_SUITE(OldStateMonad_tests)\n\nusing Categories::Monads::OldStateMonad::StateObject;\nusing Categories::Monads::OldStateMonad::StateObjectAsPair;\nusing Categories::Monads::OldStateMonad::multiplication_component;\nusing Categories::Monads::OldStateMonad::unit;\n\nstruct TestInputs\n{\n  double x_;\n  bool yes_;\n};\n\nenum class TestEnumState: char\n{\n  a = 'a',\n  b = 'b',\n  c = 'c'\n};\n\nstruct TestStateAsEnum\n{\n  TestEnumState state_;\n\n  explicit TestStateAsEnum(const TestEnumState state):\n    state_{state}\n  {}\n\n  explicit TestStateAsEnum():\n    state_{TestEnumState::a}\n  {}  \n};\n\ntemplate <typename X, typename Function>\nStateObject<X, TestEnumState> test_T_morphism(\n  const StateObject<X, TestEnumState> tx, Function f)\n{\n  const auto y = f(tx.inputs());\n\n  TestEnumState state;\n\n  if (y == 0.0)\n  {\n    state = TestEnumState::a;\n  }\n  else if (y > 0.0)\n  {\n    state = TestEnumState::b;\n  }\n  else\n  {\n    state = TestEnumState::c;\n  }\n\n  return StateObject<X, TestEnumState>{y, state};\n}\n\nBOOST_AUTO_TEST_SUITE(CartesianProductDataType)\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(TestStatesDefaultConstructs)\n{\n  const TestEnumState enum_state {};\n\n  BOOST_TEST(\n    static_cast<std::underlying_type_t<TestEnumState>>(enum_state) == 0);\n\n  TestStateAsEnum state {};\n  BOOST_TEST(\n    static_cast<std::underlying_type_t<TestEnumState>>(state.state_) == 'a');  \n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(TestEnumStateConstructs)\n{\n  TestEnumState enum_state {TestEnumState::b};\n\n  BOOST_TEST(\n    static_cast<std::underlying_type_t<TestEnumState>>(enum_state) == 'b');\n\n  enum_state = TestEnumState::c;\n\n  BOOST_TEST(\n    static_cast<std::underlying_type_t<TestEnumState>>(enum_state) == 'c');\n\n  TestStateAsEnum state {TestEnumState::b};\n  BOOST_TEST(\n    static_cast<std::underlying_type_t<TestEnumState>>(state.state_) == 'b');\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(StateObjectConstructs)\n{\n  const StateObject<double, TestEnumState> state_object {\n    42.0,\n    TestEnumState::c};\n\n  BOOST_TEST(state_object.inputs() == 42.0);\n  BOOST_TEST((state_object.state() == TestEnumState::c));\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(StateObjectDefaultConstructs)\n{\n  {\n    const StateObject<double, TestEnumState> state_object {42.0};\n\n    BOOST_TEST(state_object.inputs() == 42.0);\n    BOOST_TEST((static_cast<std::underlying_type_t<TestEnumState>>(\n      state_object.state()) == 0));\n  }\n  {\n    const StateObject<double, TestStateAsEnum> state_object {42.0};\n\n    BOOST_TEST(state_object.inputs() == 42.0);\n    BOOST_TEST((static_cast<std::underlying_type_t<TestEnumState>>(\n      state_object.state().state_) == 'a'));\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END() // CartesianProductDataType\n\nBOOST_AUTO_TEST_SUITE(UnitComponent)\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(UnitCanReturnStateObject)\n{\n  const StateObject<double, TestEnumState> tx {\n    unit<double, TestEnumState>(6.022)};\n  BOOST_TEST(tx.inputs() == 6.022);\n  BOOST_TEST(\n    (static_cast<std::underlying_type_t<TestEnumState>>(tx.state()) == 0));\n}\n\nBOOST_AUTO_TEST_SUITE_END() // UnitComponent\n\nBOOST_AUTO_TEST_SUITE(MultiplicationComponent)\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(MultiplicationComponentReturnsStateObject)\n{\n  const std::pair<StateObject<double, TestEnumState>, TestEnumState> ttx {\n    StateObject<double, TestEnumState>{6.674, TestEnumState::c},\n    TestEnumState::b};\n\n  const auto result = multiplication_component(ttx);\n\n  BOOST_TEST(result.inputs() == 6.674);\n  BOOST_TEST((\n    static_cast<std::underlying_type_t<TestEnumState>>(result.state()) == 'c'));\n}\n\nBOOST_AUTO_TEST_SUITE_END() // MultiplicationComponent\n\nBOOST_AUTO_TEST_SUITE(TMorphisms) \n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(TestTMorphismTransitionsState)\n{\n  {\n    const StateObject<double, TestEnumState> tx {0.0};\n    const auto result = test_T_morphism(tx, sin);\n    BOOST_TEST(result.inputs() == 0.0);\n    BOOST_TEST((\n      static_cast<std::underlying_type_t<TestEnumState>>(result.state()) ==\n        'a'));\n  }\n  {\n    const StateObject<double, TestEnumState> tx {0.707};\n    const auto result = test_T_morphism(tx, sin);\n    BOOST_TEST(result.inputs() == 0.64955575555642242);\n    BOOST_TEST((\n      static_cast<std::underlying_type_t<TestEnumState>>(result.state()) ==\n        'b'));\n  }\n  {\n    const StateObject<double, TestEnumState> tx {-0.107};\n    const auto result = test_T_morphism(tx, sin);\n    BOOST_TEST(result.inputs() == -0.10679594301412187);\n    BOOST_TEST((\n      static_cast<std::underlying_type_t<TestEnumState>>(result.state()) ==\n        'c'));\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END() // TMorphisms\n\nBOOST_AUTO_TEST_SUITE_END() // StateMonad_tests\nBOOST_AUTO_TEST_SUITE_END() // Monads\nBOOST_AUTO_TEST_SUITE_END() // Categories", "meta": {"hexsha": "7e72862295280106be40de362b36e45473073a94", "size": 6185, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Voltron/Source/UnitTests/Categories/Monads/OldStateMonad_tests.cpp", "max_stars_repo_name": "ernestyalumni/HrdwCCppCUDA", "max_stars_repo_head_hexsha": "17ed937dea06431a4d5ca103f993ea69a6918734", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-02-09T19:44:51.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-09T19:44:51.000Z", "max_issues_repo_path": "Voltron/Source/UnitTests/Categories/Monads/OldStateMonad_tests.cpp", "max_issues_repo_name": "ernestyalumni/HrdwCCppCUDA", "max_issues_repo_head_hexsha": "17ed937dea06431a4d5ca103f993ea69a6918734", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Voltron/Source/UnitTests/Categories/Monads/OldStateMonad_tests.cpp", "max_forks_repo_name": "ernestyalumni/HrdwCCppCUDA", "max_forks_repo_head_hexsha": "17ed937dea06431a4d5ca103f993ea69a6918734", "max_forks_repo_licenses": ["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.4523809524, "max_line_length": 80, "alphanum_fraction": 0.5731608731, "num_tokens": 1292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.49803150364941984}}
{"text": "/*******************************************************************\n Module: BigInt unit test\n\n Author: Rafael S\u00e1 Menezes\n\n Date: December 2019\n\n Test Plan:\n   - Constructors\n   - Assignments\n   - Comparator\n   - Math Operations\n \\*******************************************************************/\n\n#define BOOST_TEST_MODULE \"Big Int\"\n\n#include <big-int/bigint.hh>\n#include <boost/test/included/unit_test.hpp>\nnamespace utf = boost::unit_test;\n\nnamespace\n{\nconst char *as_string(BigInt const &obj, std::vector<char> &vec)\n{\n  return obj.as_string(vec.data(), vec.size());\n}\n\nvoid check_bigint_str(BigInt const &obj, const char *expected, bool is_correct)\n{\n  std::vector<char> bigint_str(obj.digits());\n  const char *actual = as_string(obj, bigint_str);\n  if(is_correct)\n    BOOST_TEST(expected == actual);\n  else\n    BOOST_TEST(expected != actual);\n}\n\ntemplate <class T>\nstruct BigIntHelper\n{\n  BigInt obj;\n\n  BigIntHelper()\n  {\n  }\n  explicit BigIntHelper(T val) : obj(val)\n  {\n  }\n  BigIntHelper(char const *val, BigInt::onedig_t base) : obj(val, base)\n  {\n  }\n  void check_value(const char *expected, bool is_correct = true)\n  {\n    check_bigint_str(obj, expected, is_correct);\n  }\n};\n} // namespace\n\n#define binary_op_test(FIRST_OPERATOR, SECOND_OPERATOR, BIN_OP)                \\\n  BigInt obj(FIRST_OPERATOR);                                                  \\\n  int expected = FIRST_OPERATOR BIN_OP SECOND_OPERATOR;                        \\\n  int actual = obj BIN_OP SECOND_OPERATOR;                                     \\\n  BOOST_TEST(expected == actual);\n\n#define math_test(FIRST_OPERATOR, SECOND_OPERATOR, BIN_OP)                     \\\n  BigInt obj(FIRST_OPERATOR);                                                  \\\n  int expected_result = FIRST_OPERATOR BIN_OP SECOND_OPERATOR;                 \\\n  BigInt actual_result = obj BIN_OP SECOND_OPERATOR;                           \\\n  bool expected_equals_actual = actual_result == expected_result;              \\\n  BOOST_TEST(expected_equals_actual);\n\n#define math_test_signed_generator(NAME, OP)                                   \\\n  BOOST_AUTO_TEST_CASE(signed_1_##NAME){math_test(-255, -300, OP)};            \\\n  BOOST_AUTO_TEST_CASE(signed_2_##NAME){math_test(-255, 300, OP)};             \\\n  BOOST_AUTO_TEST_CASE(signed_3_##NAME){math_test(-255, 255, OP)};             \\\n  BOOST_AUTO_TEST_CASE(signed_4_##NAME){math_test(-255, 230, OP)};\n\n// ******************** TESTS ********************\n\n// ** Constructors\n// Check whether the object is initialized correctly\n\nBOOST_AUTO_TEST_SUITE(constructors)\nBOOST_AUTO_TEST_CASE(null_constructor_ok)\n{\n  BigIntHelper<int> obj;\n  obj.check_value(NULL);\n}\nBOOST_AUTO_TEST_CASE(null_constructor_fail)\n{\n  BigIntHelper<int> obj;\n  obj.check_value(\"32\", false);\n}\n\nBOOST_AUTO_TEST_CASE(signed_constructor_ok)\n{\n  const int input = -42;\n  BigIntHelper<int> obj(input);\n  obj.check_value(\"-42\");\n}\nBOOST_AUTO_TEST_CASE(signed_constructor_fail)\n{\n  const int input = -42;\n  BigIntHelper<int> obj(input);\n  obj.check_value(\"32\", false);\n}\n\nBOOST_AUTO_TEST_CASE(unsigned_constructor_ok)\n{\n  const unsigned input = 398;\n  BigIntHelper<int> obj(input);\n  obj.check_value(\"398\");\n}\nBOOST_AUTO_TEST_CASE(unsigned_constructor_fail)\n{\n  const unsigned input = 0;\n  BigIntHelper<int> obj(input);\n  obj.check_value(\"398\", false);\n}\n\nBOOST_AUTO_TEST_CASE(string_constructor_ok_1)\n{\n  const BigInt::onedig_t base = 10;\n  const char *input = \"42\";\n  BigIntHelper<int> obj(input, base);\n  obj.check_value(\"42\");\n}\nBOOST_AUTO_TEST_CASE(string_constructor_fail_1)\n{\n  const BigInt::onedig_t base = 10;\n  const char *input = \"42\";\n  BigIntHelper<int> obj(input, base);\n  obj.check_value(\"79\", false);\n}\n\nBOOST_AUTO_TEST_CASE(string_constructor_ok_2)\n{\n  const BigInt::onedig_t base = 16;\n  const char *input = \"FF\";\n  BigIntHelper<int> obj(input, base);\n  obj.check_value(\"255\");\n}\nBOOST_AUTO_TEST_CASE(string_constructor_fail_2)\n{\n  const BigInt::onedig_t base = 16;\n  const char *input = \"A\";\n  BigIntHelper<int> obj(input, base);\n  obj.check_value(\"100\", false);\n}\n\nBOOST_AUTO_TEST_CASE(string_constructor_ok_3)\n{\n  const BigInt::onedig_t base = 10;\n  const char *input = \"12345678987654321234567890\";\n  BigIntHelper<int> obj(input, base);\n  obj.check_value(\"12345678987654321234567890\");\n}\nBOOST_AUTO_TEST_CASE(string_constructor_fail_3)\n{\n  const BigInt::onedig_t base = 10;\n  const char *input = \"12345678987654321234567890\";\n  BigIntHelper<int> obj(input, base);\n  obj.check_value(\"1234567898765432123456789\", false);\n}\n\nBOOST_AUTO_TEST_CASE(bigint_constructor_ok)\n{\n  BigInt input(42);\n  BigIntHelper<BigInt> obj(input);\n  obj.check_value(\"42\");\n}\nBOOST_AUTO_TEST_CASE(bigint_constructor_fail)\n{\n  BigInt input(42);\n  BigIntHelper<BigInt> obj(input);\n  obj.check_value(NULL, false);\n}\nBOOST_AUTO_TEST_SUITE_END()\n\n// ** Assignment\n// Check whether the object is initialized correctly after an assignement\n\nBOOST_AUTO_TEST_SUITE(assignment)\nBOOST_AUTO_TEST_CASE(signed_assignment_ok)\n{\n  BigIntHelper<unsigned> obj(42);\n  obj.obj = -9090;\n  obj.check_value(\"-9090\");\n}\nBOOST_AUTO_TEST_CASE(signed_assignment_fail)\n{\n  BigIntHelper<int> obj(-42);\n  obj.obj = -9090;\n  obj.check_value(\"-42\", false);\n}\n\nBOOST_AUTO_TEST_CASE(unsigned_assignment_ok)\n{\n  BigIntHelper<int> obj(-255);\n  unsigned value = 400000;\n  obj.obj = value;\n  obj.check_value(\"400000\");\n}\nBOOST_AUTO_TEST_CASE(unsigned_assignment_fail)\n{\n  BigIntHelper<int> obj(40000);\n  obj.obj = 9090;\n  obj.check_value(\"40000\", false);\n}\n\nBOOST_AUTO_TEST_CASE(bigint_assignment_ok)\n{\n  BigIntHelper<int> obj(-255);\n  BigInt value(42);\n  obj.obj = value;\n  obj.check_value(\"42\");\n}\nBOOST_AUTO_TEST_CASE(bigint_assignment_fail)\n{\n  BigInt value(42);\n  BigIntHelper<BigInt> obj(value);\n  obj.obj = 9090;\n  obj.check_value(\"42\", false);\n}\n\nBOOST_AUTO_TEST_CASE(string_assignment_ok_1)\n{\n  const char *input = \"12345678987654321234567890\";\n  BigIntHelper<int> obj(-255);\n  obj.obj = input;\n  obj.check_value(input);\n}\n\nBOOST_AUTO_TEST_CASE(string_assignment_ok_2)\n{\n  BigIntHelper<int> obj(-255);\n  obj.obj = \"255\";\n  obj.check_value(\"255\");\n}\n\nBOOST_AUTO_TEST_CASE(string_assignment_ok_3)\n{\n  BigIntHelper<int> obj(255);\n  obj.obj = \"-255\";\n  obj.check_value(\"-255\");\n}\n\nBOOST_AUTO_TEST_CASE(string_assignment_ok_4)\n{\n  const BigInt::onedig_t base = 10;\n  const char *input = \"12345678987654321234567890\";\n  BigIntHelper<char> obj(input, base);\n  obj.obj = input;\n  obj.check_value(input);\n}\n\nBOOST_AUTO_TEST_CASE(string_assignment_fail_1)\n{\n  const BigInt::onedig_t base = 10;\n  const char *input = \"12345678987654321234567890\";\n  BigIntHelper<char> obj(input, base);\n  obj.obj = 255;\n  obj.check_value(input, false);\n}\n\nBOOST_AUTO_TEST_CASE(string_assignment_fail_2)\n{\n  const BigInt::onedig_t base = 10;\n  const char *input = \"255\";\n  BigIntHelper<char> obj(input, base);\n  obj.obj = -255;\n  obj.check_value(\"-255255\", false);\n}\nBOOST_AUTO_TEST_SUITE_END()\n\n// ** Comparator\n// Check whether comparations are working\n\nBOOST_AUTO_TEST_SUITE(compare)\n\nBOOST_AUTO_TEST_CASE(signed_cmp_lesser_ok_1){binary_op_test(-4567, -300, <)}\n\nBOOST_AUTO_TEST_CASE(signed_cmp_lesser_ok_2){binary_op_test(-1235, -2000, <)}\n\nBOOST_AUTO_TEST_CASE(signed_cmp_greater_ok_1){binary_op_test(-255, -300, >)}\n\nBOOST_AUTO_TEST_CASE(signed_cmp_greater_ok_2){binary_op_test(-255, -200, >)}\n\nBOOST_AUTO_TEST_CASE(signed_cmp_lesser_equal_ok_1){\n  binary_op_test(-4567, -300, <=)}\n\nBOOST_AUTO_TEST_CASE(signed_cmp_lesser_equal_ok_2){\n  binary_op_test(-4567, -4567, <=)}\n\nBOOST_AUTO_TEST_CASE(signed_cmp_lesser_equal_ok_3){\n  binary_op_test(-1235, -2000, <=)}\n\nBOOST_AUTO_TEST_CASE(signed_cmp_greater_equal_ok_1){\n  binary_op_test(-300, -4567, >=)}\n\nBOOST_AUTO_TEST_CASE(signed_cmp_greater_equal_ok_2){\n  binary_op_test(-4567, -4567, >=)}\n\nBOOST_AUTO_TEST_CASE(signed_cmp_greater_equal_ok_3){\n  binary_op_test(-4567, -4566, >=)}\n\nBOOST_AUTO_TEST_CASE(signed_cmp_equal_ok_1){binary_op_test(-255, -255, ==)}\n\nBOOST_AUTO_TEST_CASE(signed_cmp_equal_ok_2){binary_op_test(-255, 0, ==)}\n\nBOOST_AUTO_TEST_CASE(unsigned_cmp_lesser_ok_1){\n  binary_op_test(0, (unsigned)200, <)}\n\nBOOST_AUTO_TEST_CASE(unsigned_cmp_lesser_ok_2){\n  binary_op_test(200, (unsigned)0, <)}\n\nBOOST_AUTO_TEST_CASE(unsigned_cmp_greater_ok_1){\n  binary_op_test(300, (unsigned)200, >)}\n\nBOOST_AUTO_TEST_CASE(unsigned_cmp_greater_ok_2){\n  binary_op_test(0, (unsigned)200, >)}\n\nBOOST_AUTO_TEST_CASE(unsigned_cmp_lesser_equal_ok_1){\n  binary_op_test(0, (unsigned)200, <=)}\n\nBOOST_AUTO_TEST_CASE(unsigned_cmp_lesser_equal_ok_2){\n  binary_op_test(200, (unsigned)0, <=)}\n\nBOOST_AUTO_TEST_CASE(unsigned_cmp_lesser_equal_ok_4){\n  binary_op_test(20, (unsigned)20, <=)}\n\nBOOST_AUTO_TEST_CASE(unsigned_cmp_greater_equal_ok_1){\n  binary_op_test(300, (unsigned)0, >=)}\n\nBOOST_AUTO_TEST_CASE(unsigned_cmp_greater_equal_ok_3){\n  binary_op_test(400, (unsigned)600, >=)}\n\nBOOST_AUTO_TEST_CASE(unsigned_cmp_greater_equal_ok_4){\n  binary_op_test(400, (unsigned)400, >=)}\n\nBOOST_AUTO_TEST_CASE(unsigned_cmp_equal_ok_1){\n  binary_op_test(255, (unsigned)255, ==)}\n\nBOOST_AUTO_TEST_CASE(unsigned_cmp_equal_ok_2){\n  binary_op_test(-255, (unsigned)255, ==)}\n\nBOOST_AUTO_TEST_SUITE_END();\n\n// ** Math Operations\n// Check whether math operations are working\n\nBOOST_AUTO_TEST_SUITE(math);\n\nmath_test_signed_generator(addition, +);\nmath_test_signed_generator(subtraction, -);\nmath_test_signed_generator(multiplication, *);\nmath_test_signed_generator(division, /);\nmath_test_signed_generator(mod, %);\n\nBOOST_AUTO_TEST_CASE(floor_pow_ok_1){\n  BigInt obj(31);\n  unsigned expected = 4;\n  unsigned actual = obj.floorPow2();\n  BOOST_TEST(expected == actual);\n};\n\nBOOST_AUTO_TEST_CASE(floor_pow_ok_2){\n  BigInt obj(-31);\n  unsigned expected = 4;\n  unsigned actual = obj.floorPow2();\n  BOOST_TEST(expected == actual);\n}\n\nBOOST_AUTO_TEST_CASE(floor_pow_ok_3){\n  BigInt obj(32);\n  unsigned expected = 5;\n  unsigned actual = obj.floorPow2();\n  BOOST_TEST(expected == actual);\n}\n\nBOOST_AUTO_TEST_CASE(floor_pow_ok_4){\n  BigInt obj(-32);\n  unsigned expected = 5;\n  unsigned actual = obj.floorPow2();\n  BOOST_TEST(expected == actual);\n}\n\nBOOST_AUTO_TEST_CASE(set_pow_ok_1){\n  BigInt obj;\n  obj.setPower2(5);\n  unsigned expected = 32;\n  int expected_is_equal_to_actual = obj == expected;\n  BOOST_TEST(expected_is_equal_to_actual);\n};\n\nBOOST_AUTO_TEST_CASE(set_pow_ok_2){\n  BigInt obj;\n  obj.setPower2(0);\n  unsigned expected = 1;\n  int expected_is_equal_to_actual = obj == expected;\n  BOOST_TEST(expected_is_equal_to_actual);\n};\n\nBOOST_AUTO_TEST_SUITE_END()\n\n#undef binary_op_test\n#undef math_test", "meta": {"hexsha": "4200b3905b98dcf381db664df8a85d2e60200091", "size": 10523, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit/big-int/bigint.test.cpp", "max_stars_repo_name": "alecs184/esbmc", "max_stars_repo_head_hexsha": "ec70901e554b8fdcfaa82b85a7050fa042168ca7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-26T22:03:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-26T22:03:18.000Z", "max_issues_repo_path": "unit/big-int/bigint.test.cpp", "max_issues_repo_name": "alecs184/esbmc", "max_issues_repo_head_hexsha": "ec70901e554b8fdcfaa82b85a7050fa042168ca7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unit/big-int/bigint.test.cpp", "max_forks_repo_name": "alecs184/esbmc", "max_forks_repo_head_hexsha": "ec70901e554b8fdcfaa82b85a7050fa042168ca7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-15T14:14:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-15T14:14:27.000Z", "avg_line_length": 25.855036855, "max_line_length": 80, "alphanum_fraction": 0.7171909151, "num_tokens": 2714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321720225278, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.4980314951070347}}
{"text": "#include <cmath>\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n#include <TList.h>\n\n#include \"ProcessMain.hpp\"\n#include \"../export_tree/TreeExportHook.hpp\"\n\nusing namespace boost::numeric;\n\ntemplate<typename T>\nublas::vector<T>    cross( const ublas::vector<T> &a, const ublas::vector<T> &b )\n{\n\tBOOST_ASSERT(a.size() == 3);\n\tBOOST_ASSERT(b.size() == 3);\n\n\tublas::vector<T>\tresult(3);\n\tresult(0) = a(1) * b(2) - a(2) * b(1);\n\tresult(1) = a(2) * b(0) - a(0) * b(2);\n\tresult(2) = a(0) * b(1) - a(1) * b(0);\n\treturn result;\n}\n\nenum cham_group_t {prop_2nd, drift_left, drift_right};\n\ndouble  Psi_L = 1.0447;\ndouble  Psi_R = -1.0209;\n\ntemplate<cham_group_t cham_group>\ntrack3d_t make_track( int event_id, TrackGroup &tg_X, TrackGroup &tg_Y )\n{\n\tstatic ublas::matrix<double> m1(3, 3), m2(3, 3), A(3, 3);\n\n\tm1(0, 0) = 1; m1(1, 0) = 0;  m1(2, 0) = 0;\n\tm1(0, 1) = 0; m1(1, 1) = 0;  m1(2, 1) = 1;\n\tm1(0, 2) = 0; m1(1, 2) = -1; m1(2, 2) = 0;\n\n\tdouble Psi;\n\tif (cham_group == cham_group_t::drift_left)\n\t{\n\t\tPsi = Psi_L;\n\t}\n\telse if (cham_group == cham_group_t::drift_right)\n\t{\n\t\tPsi = Psi_R;\n\t}\n\telse if (cham_group == cham_group_t::prop_2nd)\n\t{\n\t\tPsi = 0;\n\t}\n\telse\n\t{\n\t\tthrow;\n\t}\n\n\tm2(0, 0) = cos(Psi); m2(1, 0) = 0; m2(2, 0) = -sin(Psi);\n\tm2(0, 1) = 0;        m2(1, 1) = 1; m2(2, 1) = 0;\n\tm2(0, 2) = sin(Psi); m2(1, 2) = 0; m2(2, 2) = cos(Psi);\n\n\tA = ublas::prod(m1, m2);\n\n\tublas::vector<double> o(3), a(3), b(3);\n\n\tif (cham_group == cham_group_t::drift_left)\n\t{\n\t\to(0) = 165.2;\n\t\to(1) = 512.4;\n\t\to(2) = 0.3;\n\t}\n\telse if (cham_group == cham_group_t::drift_right)\n\t{\n\t\to(0) = 159.7;\n\t\to(1) = -524.0;\n\t\to(2) = -2.8;\n\t}\n\telse if (cham_group == cham_group_t::prop_2nd)\n\t{\n\t\to(0) = -1486.0;\n\t\to(1) = 0;\n\t\to(2) = 2;\n\t}\n\telse\n\t{\n\t\tthrow;\n\t}\n\n\tb(0) = 1;\n\tb(1) = tg_Y.c1[0];\n\tb(2) = tg_X.c1[0];\n\tb = ublas::prod(A, b);\n\n\tublas::unit_vector<double> xk(3, 1);\n\tublas::unit_vector<double> xl(3, 2);\n\ta = o + ublas::prod(A, xk) * tg_Y.c0[0] + ublas::prod(A, xl) * tg_X.c0[0];\n\n\treturn track3d_t({a, b});\n}\n\nvoid\tfind_intersection_points(\n\tconst track3d_t &t1, const track3d_t &t2,\n\tintersection_t *i1, intersection_t *i2\n\t)\n{\n\tauto cr = cross(t1.b, t2.b);\n\tdouble cr_norm = norm_2(cr);\n\n\t// Following code solves linear system\n\t// (t1.b, t2.b, cr) * x = t1.a - t2.a\n\tublas::matrix<double>\tB(3, 3);\n\tublas::vector<double>\tx;\n\tublas::permutation_matrix<>\tpm(B.size1());\n\n\tfor(unsigned int row = 0; row < B.size1(); row++)\n\t{\n\t\tB(row, 0) = t1.b(row);\n\t\tB(row, 1) = t2.b(row);\n\t\tB(row, 2) = cr(row);\n\t}\n\tx = t1.a - t2.a; // put RHS into x\n\n\tint\tsingular = ublas::lu_factorize(B, pm);\n\tif(singular)\n\t{\n\t\tthrow \"lu_factorize()==0\";\n\t}\n\n\tublas::lu_substitute(B, pm, x);\n\n\tx(2) -= ublas::inner_prod(cr, t1.a - t2.a) / cr_norm;\n\tublas::vector<double>\tiv1 = t1.a - x(0) * t1.b;\n\tublas::vector<double>\tiv2 = t2.a + x(1) * t2.b;\n\n\ti1->x = iv1(0); i1->y = iv1(1); i1->z = iv1(2);\n\ti2->x = iv2(0); i2->y = iv2(1); i2->z = iv2(2);\n}\n\ndouble\tcalc_theta(track3d_t track)\n{\n\tdouble\tcos_theta =\n\t    ublas::inner_prod(track.b, ublas::unit_vector<double>(3, 0))\n\t    / norm_2(track.b);\n\treturn acos(cos_theta);\n}\n\ndouble\tcalc_phi(track3d_t track)\n{\n\treturn atan2(\n\t\tublas::inner_prod(track.b, ublas::unit_vector<double>(3, 1)),\n\t\tublas::inner_prod(track.b, ublas::unit_vector<double>(3, 2))\n\t\t);\n}\n\ndouble\tcalc_incident_momentum(double beam_momentum, intersection_t &i1, intersection_t &i2)\n{\n\tconst double\tTARGET_START = -130; // mm\n\tdouble\tz = (i1.x + i2.x) / 2 - TARGET_START; // mm\n\tconst double\tdE_over_dx = 4; // MeV g^-1 cm^2\n\tconst double\tlih2_density = 0.0708; // g cm^-3\n\n\treturn beam_momentum - dE_over_dx * lih2_density * (z/10);\n}\n\nvoid\tTTree_UnfriendAll(TTree *tree)\n{\n\tTList *friends = tree->GetListOfFriends();\n\n\twhile(friends->GetSize() != 0)\n\t{\n\t\tfriends->RemoveLast();\n\t}\n}\n\nTTree*\tProcess( TTree *events, TTree *cycle_efficiency, Geometry &geom, double central_momentum, intersection_set_t *s )\n{\n\tTTree\t*events_new;\n\tuint32_t\tevent_cause, timestamp;\n\tdouble\ttheta_l, theta_r, phi_l, phi_r;\n\tdouble\tbeam_momentum, incident_momentum_l, incident_momentum_r;\n\tTrackGroup\ttg_F1X, tg_F1Y, tg_F2X, tg_F2Y, tg_LX, tg_LY, tg_RX, tg_RY;\n\tconst double\tF1_length = geom.normal_pos[1][DEV_AXIS_X].back();\n\n\tevents->GetBranch(\"event_cause\")->SetAddress(&event_cause);\n\tevents->GetBranch(\"timestamp\")->SetAddress(&timestamp);\n\tevents->GetBranch(\"t1X_track_count\")->SetAddress(&tg_F1X.track_count);\n\tevents->GetBranch(\"t1Y_track_count\")->SetAddress(&tg_F1Y.track_count);\n\tevents->GetBranch(\"t2X_track_count\")->SetAddress(&tg_F2X.track_count);\n\tevents->GetBranch(\"t2Y_track_count\")->SetAddress(&tg_F2Y.track_count);\n\tevents->GetBranch(\"t3X_track_count\")->SetAddress(&tg_LX.track_count);\n\tevents->GetBranch(\"t3Y_track_count\")->SetAddress(&tg_LY.track_count);\n\tevents->GetBranch(\"t4X_track_count\")->SetAddress(&tg_RX.track_count);\n\tevents->GetBranch(\"t4Y_track_count\")->SetAddress(&tg_RY.track_count);\n\n\tevents->SetBranchAddress(\"t1X_c0\", &tg_F1X.c0_ptr);\n\tevents->SetBranchAddress(\"t1X_c1\", &tg_F1X.c1_ptr);\n\tevents->SetBranchAddress(\"t1X_hits_count\", &tg_F1X.hits_count_ptr);\n\tevents->SetBranchAddress(\"t1Y_c0\", &tg_F1Y.c0_ptr);\n\tevents->SetBranchAddress(\"t1Y_c1\", &tg_F1Y.c1_ptr);\n\tevents->SetBranchAddress(\"t1Y_hits_count\", &tg_F1Y.hits_count_ptr);\n\n\tevents->SetBranchAddress(\"t2X_c0\", &tg_F2X.c0_ptr);\n\tevents->SetBranchAddress(\"t2X_c1\", &tg_F2X.c1_ptr);\n\tevents->SetBranchAddress(\"t2X_hits_count\", &tg_F2X.hits_count_ptr);\n\tevents->SetBranchAddress(\"t2Y_c0\", &tg_F2Y.c0_ptr);\n\tevents->SetBranchAddress(\"t2Y_c1\", &tg_F2Y.c1_ptr);\n\tevents->SetBranchAddress(\"t2Y_hits_count\", &tg_F2Y.hits_count_ptr);\n\n\tevents->SetBranchAddress(\"t3X_c0\", &tg_LX.c0_ptr);\n\tevents->SetBranchAddress(\"t3X_c1\", &tg_LX.c1_ptr);\n\tevents->SetBranchAddress(\"t3X_hits_count\", &tg_LX.hits_count_ptr);\n\tevents->SetBranchAddress(\"t3Y_c0\", &tg_LY.c0_ptr);\n\tevents->SetBranchAddress(\"t3Y_c1\", &tg_LY.c1_ptr);\n\tevents->SetBranchAddress(\"t3Y_hits_count\", &tg_LY.hits_count_ptr);\n\n\tevents->SetBranchAddress(\"t4X_c0\", &tg_RX.c0_ptr);\n\tevents->SetBranchAddress(\"t4X_c1\", &tg_RX.c1_ptr);\n\tevents->SetBranchAddress(\"t4X_hits_count\", &tg_RX.hits_count_ptr);\n\tevents->SetBranchAddress(\"t4Y_c0\", &tg_RY.c0_ptr);\n\tevents->SetBranchAddress(\"t4Y_c1\", &tg_RY.c1_ptr);\n\tevents->SetBranchAddress(\"t4Y_hits_count\", &tg_RY.hits_count_ptr);\n\n\t// select branches to work with\n\tevents->SetBranchStatus(\"*\", 0);\n\tevents->SetBranchStatus(\"event_cause\", 1);\n\tevents->SetBranchStatus(\"timestamp\", 1);\n\tevents->SetBranchStatus(\"*_track_count\", 1);\n\tevents->SetBranchStatus(\"*_hits_count\", 1);\n\tevents->SetBranchStatus(\"*_used_chambers_mask\", 1);\n\tevents->SetBranchStatus(\"*_c0\", 1);\n\tevents->SetBranchStatus(\"*_c1\", 1);\n\t// clone tree headers\n\t// this also copies branches addresses\n\tevents_new = events->CloneTree(0);\n\tTTree_UnfriendAll(events_new);\n\n\tdouble min_cycle_efficiency;\n\tcycle_efficiency->SetBranchStatus(\"min_cycle_efficiency\", 1);\n\tcycle_efficiency->SetBranchAddress(\"min_cycle_efficiency\", &min_cycle_efficiency);\n\tevents_new->Branch(\"min_cycle_efficiency\", &min_cycle_efficiency, \"min_cycle_efficiency/D\");\n\n\ts->br_lr = events_new->Branch(\"LR\", &s->i_lr, \"LR_x/D:LR_y/D:LR_z/D\");\n\ts->br_rl = events_new->Branch(\"RL\", &s->i_rl, \"RL_x/D:RL_y/D:RL_z/D\");\n\ts->br_f2r = events_new->Branch(\"F2R\", &s->i_f2r, \"F2R_x/D:F2R_y/D:F2R_z/D\");\n\ts->br_f2l = events_new->Branch(\"F2L\", &s->i_f2l, \"F2L_x/D:F2L_y/D:F2L_z/D\");\n\ts->br_rf2 = events_new->Branch(\"RF2\", &s->i_rf2, \"RF2_x/D:RF2_y/D:RF2_z/D\");\n\ts->br_lf2 = events_new->Branch(\"LF2\", &s->i_lf2, \"LF2_x/D:LF2_y/D:LF2_z/D\");\n\n\tevents_new->Branch(\"theta_l\", &theta_l, \"theta_l/D\");\n\tevents_new->Branch(\"theta_r\", &theta_r, \"theta_r/D\");\n\tevents_new->Branch(\"phi_l\", &phi_l, \"phi_l/D\");\n\tevents_new->Branch(\"phi_r\", &phi_r, \"phi_r/D\");\n\tevents_new->Branch(\"beam_momentum\", &beam_momentum, \"beam_momentum/D\");\n\tevents_new->Branch(\"incident_momentum_l\", &incident_momentum_l, \"incident_momentum_l/D\");\n\tevents_new->Branch(\"incident_momentum_r\", &incident_momentum_r, \"incident_momentum_r/D\");\n\n\tfor(int i = 0; i < events->GetEntries(); i++)\n\t{\n\t\ttrack3d_t\tt_L, t_R, t_F2;\n\t\tevents->GetEntry(i);\n\t\tcycle_efficiency->GetEntry(i);\n\n\t\tbool\tleft_arm = (tg_LX.track_count == 1) && (tg_LY.track_count == 1);\n\t\tbool\tright_arm = (tg_RX.track_count == 1) && (tg_RY.track_count == 1);\n\t\tbool\tincident =\n\t\t    (tg_F1X.track_count == 1) && (tg_F1Y.track_count == 1) &&\n\t\t    (tg_F2X.track_count == 1) && (tg_F2Y.track_count == 1);\n\n\t\tif (!incident)\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\n\t\tt_F2 = make_track<cham_group_t::prop_2nd>(i, tg_F2X, tg_F2Y);\n\n\t\tdouble\tF1_x = tg_F1X.c0[0] + F1_length * tg_F1X.c1[0];\n\t\tconst double\tDISPERSION = (1.0 / 55) * 0.01; // 55 mm/%\n\t\tbeam_momentum = (1 + F1_x * DISPERSION) * central_momentum;\n\n\t\tif (left_arm)\n\t\t{\n\t\t\tt_L = make_track<cham_group_t::drift_left>(i, tg_LX, tg_LY);\n\t\t\ttheta_l = calc_theta(t_L);\n\t\t\tphi_l = calc_phi(t_L);\n\t\t\tfind_intersection_points(t_F2, t_L, &s->i_f2l, &s->i_lf2);\n\t\t\tincident_momentum_l = calc_incident_momentum(beam_momentum, s->i_f2l, s->i_lf2);\n\t\t}\n\t\telse\n\t\t{\n\t\t\ttheta_l = NAN;\n\t\t\tphi_l = NAN;\n\t\t\ts->i_f2l.x = NAN; s->i_f2l.y = NAN; s->i_f2l.z = NAN;\n\t\t\ts->i_lf2.x = NAN; s->i_lf2.y = NAN; s->i_lf2.z = NAN;\n\t\t\tincident_momentum_l = NAN;\n\t\t}\n\t\tif (right_arm)\n\t\t{\n\t\t\tt_R = make_track<cham_group_t::drift_right>(i, tg_RX, tg_RY);\n\t\t\ttheta_r = calc_theta(t_R);\n\t\t\tphi_r = calc_phi(t_R);\n\t\t\tfind_intersection_points(t_F2, t_R, &s->i_f2r, &s->i_rf2);\n\t\t\tincident_momentum_r = calc_incident_momentum(beam_momentum, s->i_f2r, s->i_rf2);\n\t\t}\n\t\telse\n\t\t{\n\t\t\ttheta_r = NAN;\n\t\t\tphi_r = NAN;\n\t\t\ts->i_f2r.x = NAN; s->i_f2r.y = NAN; s->i_f2r.z = NAN;\n\t\t\ts->i_rf2.x = NAN; s->i_rf2.y = NAN; s->i_rf2.z = NAN;\n\t\t\tincident_momentum_r = NAN;\n\t\t}\n\n\t\tif (left_arm && right_arm)\n\t\t{\n\t\t\tfind_intersection_points(t_L, t_R, &s->i_lr, &s->i_rl);\n\t\t}\n\t\telse\n\t\t{\n\t\t\ts->i_lr.x = NAN; s->i_lr.y = NAN; s->i_lr.z = NAN;\n\t\t\ts->i_rl.x = NAN; s->i_rl.y = NAN; s->i_rl.z = NAN;\n\t\t}\n\n\t\tevents_new->Fill();\n\t}\n\n\treturn events_new;\n}\n", "meta": {"hexsha": "63471b8ed7133465aa994db881cd8ec66f25555f", "size": 9967, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/utils/process/ProcessMain.cpp", "max_stars_repo_name": "veprbl/libepecur", "max_stars_repo_head_hexsha": "83167ac6220e69887c03b556f1a7ffc518cbb227", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-25T13:41:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-25T13:41:19.000Z", "max_issues_repo_path": "src/utils/process/ProcessMain.cpp", "max_issues_repo_name": "veprbl/libepecur", "max_issues_repo_head_hexsha": "83167ac6220e69887c03b556f1a7ffc518cbb227", "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/utils/process/ProcessMain.cpp", "max_forks_repo_name": "veprbl/libepecur", "max_forks_repo_head_hexsha": "83167ac6220e69887c03b556f1a7ffc518cbb227", "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.2948328267, "max_line_length": 120, "alphanum_fraction": 0.6700110364, "num_tokens": 3713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026641072386, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.49796993590014127}}
{"text": "/*    Copyright (c) 2010-2019, Delft University of Technology\n *    All rigths reserved\n *\n *    This file is part of the Tudat. Redistribution and use in source and\n *    binary forms, with or without modification, are permitted exclusively\n *    under the terms of the Modified BSD license. You should have received\n *    a copy of the license with this file. If not, please or visit:\n *    http://tudat.tudelft.nl/LICENSE.\n *\n */\n\n#include <cmath>\n\n#include <Eigen/Core>\n\n#include \"tudat/math/basic/sphericalHarmonics.h\"\n#include \"tudat/math/basic/basicMathematicsFunctions.h\"\n\nnamespace tudat\n{\nnamespace basic_mathematics\n{\n\n//! Update maximum degree and order of cache\nvoid SphericalHarmonicsCache::resetMaximumDegreeAndOrder( const int maximumDegree, const int maximumOrder )\n{\n    maximumDegree_ = maximumDegree;\n    maximumOrder_ = maximumOrder;\n\n    if( maximumOrder_ > maximumDegree_ )\n    {\n        maximumOrder_ = maximumDegree_;\n    }\n    legendreCache_->resetMaximumDegreeAndOrder( maximumDegree_, maximumOrder_ );\n\n    sinesOfLongitude_.resize( maximumOrder_ + 1 );\n    cosinesOfLongitude_.resize( maximumOrder_ + 1 );\n    referenceRadiusRatioPowers_.resize( maximumDegree_ + 2 );\n}\n\n\n//! Compute the gradient of a single term of a spherical harmonics potential field.\nEigen::Vector3d computePotentialGradient(\n        const double distance,\n        const double radiusPowerTerm,\n        const double cosineOfOrderLongitude,\n        const double sineOfOrderLongitude,\n        const double cosineOfLatitude,\n        const double preMultiplier,\n        const int degree,\n        const int order,\n        const double cosineHarmonicCoefficient,\n        const double sineHarmonicCoefficient,\n        const double legendrePolynomial,\n        const double legendrePolynomialDerivative )\n{\n    // Return result.\n    return ( Eigen::Vector3d( ) <<\n             - preMultiplier / distance\n             * radiusPowerTerm\n             * ( static_cast< double >( degree ) + 1.0 ) * legendrePolynomial\n             * ( cosineHarmonicCoefficient * cosineOfOrderLongitude\n                 + sineHarmonicCoefficient * sineOfOrderLongitude ),\n             preMultiplier * radiusPowerTerm\n             * legendrePolynomialDerivative * cosineOfLatitude * (\n                 cosineHarmonicCoefficient * cosineOfOrderLongitude\n                 + sineHarmonicCoefficient * sineOfOrderLongitude ),\n             preMultiplier * radiusPowerTerm\n             * static_cast< double >( order ) * legendrePolynomial\n             * ( sineHarmonicCoefficient * cosineOfOrderLongitude\n                 - cosineHarmonicCoefficient * sineOfOrderLongitude ) ).finished( );\n}\n\n//! Compute the gradient of a single term of a spherical harmonics potential field.\nEigen::Vector3d computePotentialGradient(\n        const Eigen::Vector3d& sphericalPosition,\n        const double referenceRadius,\n        const double preMultiplier,\n        const int degree,\n        const int order,\n        const double cosineHarmonicCoefficient,\n        const double sineHarmonicCoefficient,\n        const double legendrePolynomial,\n        const double legendrePolynomialDerivative )\n{\n    return computePotentialGradient(\n                sphericalPosition( radiusIndex ),\n                basic_mathematics::raiseToIntegerPower\n                ( referenceRadius / sphericalPosition( radiusIndex ), static_cast< double >( degree ) + 1.0 ),\n                std::cos( static_cast< double >( order ) * sphericalPosition( longitudeIndex ) ),\n                std::sin( static_cast< double >( order ) * sphericalPosition( longitudeIndex ) ),\n                std::cos( sphericalPosition( latitudeIndex ) ), preMultiplier, degree, order,\n                cosineHarmonicCoefficient, sineHarmonicCoefficient, legendrePolynomial,legendrePolynomialDerivative );\n}\n\n//! Compute the gradient of a single term of a spherical harmonics potential field.\nEigen::Vector3d computePotentialGradient( const Eigen::Vector3d& sphericalPosition,\n                                          const double preMultiplier,\n                                          const int degree,\n                                          const int order,\n                                          const double cosineHarmonicCoefficient,\n                                          const double sineHarmonicCoefficient,\n                                          const double legendrePolynomial,\n                                          const double legendrePolynomialDerivative,\n                                          const std::shared_ptr< SphericalHarmonicsCache > sphericalHarmonicsCache )\n{\n    return computePotentialGradient(\n                sphericalPosition( radiusIndex ),\n                sphericalHarmonicsCache->getReferenceRadiusRatioPowers( degree + 1 ),\n                sphericalHarmonicsCache->getCosineOfMultipleLongitude( order ),\n                sphericalHarmonicsCache->getSineOfMultipleLongitude( order ),\n                sphericalHarmonicsCache->getLegendreCache( )->getCurrentPolynomialParameterComplement( ),\n                preMultiplier, degree, order,\n                cosineHarmonicCoefficient, sineHarmonicCoefficient, legendrePolynomial,legendrePolynomialDerivative );\n}\n\n} // namespace basic_mathematics\n} // namespace tudat\n", "meta": {"hexsha": "246ecbc0c2be172f5f11b2eb0531a54a1025613d", "size": 5269, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/math/basic/sphericalHarmonics.cpp", "max_stars_repo_name": "kimonito98/tudat", "max_stars_repo_head_hexsha": "c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/math/basic/sphericalHarmonics.cpp", "max_issues_repo_name": "kimonito98/tudat", "max_issues_repo_head_hexsha": "c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/math/basic/sphericalHarmonics.cpp", "max_forks_repo_name": "kimonito98/tudat", "max_forks_repo_head_hexsha": "c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.2773109244, "max_line_length": 118, "alphanum_fraction": 0.6612260391, "num_tokens": 1038, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026550642018, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.49796993099100867}}
{"text": "//=======================================================================\n// Copyright (c) 2014 Piotr Smulewicz\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n#include \"test_utils/sample_graph.hpp\"\n#include \"test_utils/logger.hpp\"\n\n#include \"paal/local_search/k_median/k_median.hpp\"\n\n#include <boost/test/unit_test.hpp>\n\nBOOST_AUTO_TEST_CASE(kmedian_test) {\n    // sample data\n    typedef sample_graphs_metrics SGM;\n    auto gm = SGM::get_graph_metric_small();\n\n    // define voronoi and solution\n    const int k = 2;\n    typedef paal::data_structures::voronoi<decltype(gm)> VorType;\n    typedef paal::data_structures::k_median_solution<VorType> Sol;\n    typedef paal::data_structures::voronoi_traits<VorType> VT;\n    typedef typename VT::GeneratorsSet GSet;\n    typedef typename VT::VerticesSet VSet;\n    typedef typename Sol::UnchosenFacilitiesSet USet;\n\n    // create voronoi and solution\n    VorType voronoi(GSet{ SGM::B, SGM::D },\n                    VSet{ SGM::A, SGM::B, SGM::C, SGM::D, SGM::E }, gm);\n    Sol sol(std::move(voronoi), USet{ SGM::A, SGM::C }, k);\n\n    // create facility location local search components\n    paal::local_search::default_k_median_components swap;\n\n    // search\n    paal::local_search::facility_location_first_improving(sol, swap);\n\n    // print result\n    ON_LOG(auto const &ch = ) sol.get_chosen_facilities();\n    LOGLN(\"Solution:\");\n    LOG_COPY_RANGE_DEL(ch, \",\");\n}\n", "meta": {"hexsha": "f590abab6dade6e83dd07a6aa331f9c7243f47fd", "size": 1594, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/local_search/k_median/k_median_test.cpp", "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": "test/local_search/k_median/k_median_test.cpp", "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": "test/local_search/k_median/k_median_test.cpp", "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.4222222222, "max_line_length": 73, "alphanum_fraction": 0.639272271, "num_tokens": 405, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.49796617169690405}}
{"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\u00e4nkt), 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_CGS_INCLUDE\n#define ITL_CGS_INCLUDE\n\n#include <boost/numeric/mtl/concept/collection.hpp>\n#include <boost/numeric/mtl/operation/resource.hpp>\n#include <boost/numeric/mtl/operation/dot.hpp>\n#include <boost/numeric/mtl/interface/vpt.hpp>\n\n#include <boost/numeric/itl/krylov/base_solver.hpp>\n\nnamespace itl {\n\n/// Conjugate Gradient Squared\ntemplate < typename LinearOperator, typename Vector, \n\t   typename Preconditioner, typename Iteration >\nint cgs(const LinearOperator &A, Vector &x, const Vector &b,\n\tconst Preconditioner &M, Iteration& iter)\n{\n    mtl::vampir_trace<7007> tracer;\n    typedef typename mtl::Collection<Vector>::value_type Scalar;\n    Scalar     rho_1(0), rho_2(0), alpha(0), beta(0);\n    Vector     p(resource(x)), phat(resource(x)), q(resource(x)), qhat(resource(x)), vhat(resource(x)),\n\t       u(resource(x)), uhat(resource(x)), r(b - A * x), rtilde= r;\n\n    while (! iter.finished(r)) {\n\t++iter;\n\trho_1= dot(rtilde, r);\n\n\tif (rho_1 == 0.) iter.fail(2, \"cgs breakdown\");\n\n\tif (iter.first())\n\t    p= u= r;\n\telse {\n\t    beta = rho_1 / rho_2;\n\t    u= r + beta * q;\n\t    p= u + beta * (q + beta * p);\n\t}\n\n        vhat= A * Vector(solve(M, p));\n\talpha = rho_1 / dot(rtilde, vhat);\n\tq= u - alpha * vhat;\n\n\tu+= q;\n\tuhat= solve(M, u);\n\t\n\tx+= alpha * uhat;\n\tqhat= A * uhat;\n\tr-= alpha * qhat;\n\n\trho_2= rho_1;\n    }\n    return iter;\n}\n\n/// Solver class for CGS method; right preconditioner ignored (prints warning if not identity)\n/** Methods inherited from \\ref base_solver. **/\ntemplate < typename LinearOperator, typename Preconditioner= pc::identity<LinearOperator>, \n\t   typename RightPreconditioner= pc::identity<LinearOperator> >\nclass cgs_solver\n  : public base_solver< cgs_solver<LinearOperator, Preconditioner, RightPreconditioner>, LinearOperator >\n{\n    typedef base_solver< cgs_solver<LinearOperator, Preconditioner, RightPreconditioner>, LinearOperator > base;\n  public:\n    /// Construct solver from a linear operator; generate (left) preconditioner from it\n    explicit cgs_solver(const LinearOperator& A) : base(A), L(A) \n    {\n\tif (!pc::static_is_identity<RightPreconditioner>::value)\n\t    std::cerr << \"Right Preconditioner ignored!\" << std::endl;\n    }\n\n    /// Construct solver from a linear operator and (left) preconditioner\n    cgs_solver(const LinearOperator& A, const Preconditioner& L) : base(A), L(L) \n    {\n\tif (!pc::static_is_identity<RightPreconditioner>::value)\n\t    std::cerr << \"Right Preconditioner ignored!\" << std::endl;\n    }\n\n    /// Solve linear system approximately as specified by \\p iter\n    template < typename HilbertSpaceX, typename HilbertSpaceB, typename Iteration >\n    int solve(HilbertSpaceX& x, const HilbertSpaceB& b, Iteration& iter) const\n    {\n\treturn cgs(this->A, x, b, L, iter);\n    }\n\n  private:\n    Preconditioner        L;\n};\n\n} // namespace itl\n\n#endif // ITL_CGS_INCLUDE\n\n\n\n", "meta": {"hexsha": "4fc55c57581dee7d5e804f67c0eb0c0b323f55dd", "size": 3303, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/itl/krylov/cgs.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/krylov/cgs.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/krylov/cgs.hpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 30.8691588785, "max_line_length": 112, "alphanum_fraction": 0.6863457463, "num_tokens": 907, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.49796617169690394}}
{"text": "#pragma once\n\n#include \"../geometry/LineSegment/LineSegment2/linesegment2.hh\"\n#include <Eigen/Core>\n#include <Eigen/LU>\n\nnamespace bold\n{\n  class IncrementalRegression\n  {\n  public:\n    IncrementalRegression()\n      : d_xxSum{Eigen::Matrix2f::Zero()},\n      d_xySum{Eigen::Vector2f::Zero()},\n      d_nPoints{0},\n      d_sqErrorSum{0.0f},\n      d_dirty{false}\n    {}\n    \n    void setSqError(float sqError)\n    {\n      d_sqErrorSum = sqError;\n    }\n\n    Eigen::Vector2f head() const\n    {\n      return d_head;\n    }\n\n    float getY(float x) const\n    {\n      return d_beta.dot(Eigen::Vector2f{x, 1});\n    }\n\n    float fit(Eigen::Vector2f const& point)\n    {\n      if (d_nPoints == 1)\n        return (point - head()).norm();\n      else if (d_xStart == d_xEnd)\n      {\n        return std::abs(point.x() - d_xStart);\n      }\n      else\n      {\n        solve();\n        auto sigma = sigmaAt(point.x());\n        auto yPred = getY(point.x());\n        auto error = std::abs(yPred - point.y());\n        return sigma == 0 ? error : error / sigma;\n      }\n    }\n\n    float sigmaAt(float x)\n    {\n      auto _x = Eigen::Vector2f{x, 1};\n      return sqrt(_x.transpose() * (1.0 / d_sqErrorSum * d_xxSum).inverse() * _x);\n    }\n\n    bool isVertical() const\n    {\n      return d_xStart == d_xEnd;\n    }\n\n    void addPoint(Eigen::Vector2f const& point)\n    {\n      d_points.push_back(point);\n\n      auto x = Eigen::Vector2f{point.x(), 1};\n      d_xxSum += x * x.transpose();\n      d_xySum += x * point.y();\n      d_xEnd = point.x();\n      ++d_nPoints;\n\n      if (d_nPoints == 1)\n      {\n        d_xStart = point.x();\n        d_head = point;\n      }\n      else if (d_nPoints == 2)\n        d_head = point;\n      else\n      {\n        d_head = Eigen::Vector2f{point.x(), getY(point.x())};\n      }\n      d_dirty = true;\n    }\n    \n    void solve()\n    {\n      if (d_dirty && d_nPoints > 1)\n      {\n        d_beta = (d_xxSum / d_nPoints).inverse() * d_xySum / d_nPoints;\n        d_dirty = false;\n      }\n    }\n    \n    Eigen::Vector2f getBeta() const\n    {\n      return d_beta;\n    }\n\n    LineSegment2f getLineSegment()\n    {\n      solve();\n      Eigen::Vector2f p1{d_xStart, getY(d_xStart)};\n      Eigen::Vector2f p2{d_xEnd, getY(d_xEnd)};\n      return LineSegment2f{p1, p2};\n    }\n\n    unsigned getNPoints() const\n    {\n      return d_nPoints;\n    }\n\n    float determineStandardError() const\n    {\n      auto X = Eigen::MatrixXf(2, d_points.size());\n      auto y = Eigen::VectorXf(d_points.size());\n      unsigned idx = 0;\n      for (auto const& point : d_points)\n      {\n        X.col(idx) = Eigen::Vector2f{point.x(), 1};\n        y(idx) = point.y();\n        ++idx;\n      }\n      auto res = y - X.transpose() * d_beta;\n      return sqrt(res.dot(res) / (d_points.size() - 2));\n    }\n\n    void merge(IncrementalRegression const& other)\n    {\n      d_xxSum += other.d_xxSum;\n      d_xySum += other.d_xySum;\n      d_nPoints += other.d_nPoints;\n      d_xStart = std::min(d_xStart, other.d_xStart);\n      d_xEnd = std::max(d_xEnd, other.d_xEnd);\n      solve();\n    }\n\nprivate:\n    std::vector<Eigen::Vector2f> d_points;\n\n    Eigen::Matrix2f d_xxSum;\n    Eigen::Vector2f d_xySum;\n    unsigned d_nPoints;\n    Eigen::Vector2f d_beta;\n    unsigned d_xStart;\n    unsigned d_xEnd;\n    Eigen::Vector2f d_head;\n    float d_sqErrorSum;\n\n    bool d_dirty;\n  };\n}\n", "meta": {"hexsha": "930ae8ddc7581daf1b3fe5a9f2e6ea780b9c6319", "size": 3327, "ext": "hh", "lang": "C++", "max_stars_repo_path": "IncrementalRegression/incrementalregression.hh", "max_stars_repo_name": "drewnoakes/bold-humanoid", "max_stars_repo_head_hexsha": "6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "IncrementalRegression/incrementalregression.hh", "max_issues_repo_name": "drewnoakes/bold-humanoid", "max_issues_repo_head_hexsha": "6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "IncrementalRegression/incrementalregression.hh", "max_forks_repo_name": "drewnoakes/bold-humanoid", "max_forks_repo_head_hexsha": "6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335", "max_forks_repo_licenses": ["Apache-2.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.464516129, "max_line_length": 82, "alphanum_fraction": 0.5494439435, "num_tokens": 970, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.49796616636374313}}
{"text": "#include <omp.h>\n#include <Eigen/Sparse>\n#include <boost/lexical_cast.hpp>\n#include <boost/multi_array.hpp>\n#include <boost/program_options.hpp>\n#include <boost/filesystem.hpp>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n// own includes ------------------------------------------------------------\n#include \"aux/message.hpp\"\n#include \"aux/timer.hpp\"\n//#include \"base/numbers.hpp\"\n\n#include <mpi.h>\n\n#include \"spectral/basis/spectral_basis_factory_ks.hpp\"\n#include \"collision_tensor/collision_tensor_galerkin.hpp\"\n\nusing namespace std;\nusing namespace boltzmann;\nnamespace po = boost::program_options;\n\n\nint main(int argc, char* argv[])\n{\n  MPI_Init(&argc, &argv);\n  int K;\n  string tensor_file;\n\n  po::options_description options(\"options\");\n  options.add_options()\n      (\"help\", \"produce help message\")\n      (\"K\", po::value<int>(&K), \"K\")\n      (\"tensor\", po::value<string>(&tensor_file), \"/path/to/tensor/h5\")\n      ;\n\n  po::variables_map vm;\n  po::store(po::parse_command_line(argc, argv, options), vm);\n  po::notify(vm);\n\n  if (vm.count(\"help\")) {\n    cout << options << \"\\n\";\n    return 0;\n  }\n\n  if (!boost::filesystem::exists(tensor_file)) {\n    throw std::runtime_error(\"path not found: \" + tensor_file);\n  }\n\n  typedef typename SpectralBasisFactoryKS::basis_type basis_type;\n  // trial space\n  basis_type trial_basis;\n  SpectralBasisFactoryKS::create(trial_basis, K);\n\n  CollisionTensorGalerkin ct(trial_basis);\n  ct.read_hdf5(tensor_file.c_str());\n\n  MPI_Finalize();\n  return 0;\n}\n", "meta": {"hexsha": "ccdcbbd3d8a3a159f6bc7155813bc5bcfbebe0dd", "size": 1510, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/collision_tensor_load_from_file/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": "test/collision_tensor_load_from_file/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": "test/collision_tensor_load_from_file/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": 24.3548387097, "max_line_length": 76, "alphanum_fraction": 0.6728476821, "num_tokens": 374, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.4979661610305824}}
{"text": "// BSD 3-Clause License\n\n// Copyright (c) 2021, 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, this\n//    list of conditions and the following disclaimer.\n\n// 2. Redistributions in binary form must reproduce the above copyright notice,\n//    this list of conditions and the following disclaimer in the documentation\n//    and/or other materials provided with the distribution.\n\n// 3. Neither the name of the copyright holder nor the names of its\n//    contributors may be used to endorse or promote products derived from\n//    this software without specific prior written permission.\n\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"rotation_averaging/hybrid_rotation_estimator.h\"\n\n#include <ceres/rotation.h>\n#include <glog/logging.h>\n#include <omp.h>\n\n#include <Eigen/Eigenvalues>\n#include <Eigen/QR>\n#include <algorithm>\n#include <cmath>\n#include <iomanip>\n#include <limits>\n\n#include \"Spectra/MatOp/SparseSymMatProd.h\"\n#include \"Spectra/SymEigsSolver.h\"\n\n#include \"rotation_averaging/internal/rotation_estimator_util.h\"\n#include \"solver/bcm_sdp_solver.h\"\n#include \"solver/rbr_sdp_solver.h\"\n#include \"solver/rank_restricted_sdp_solver.h\"\n#include \"solver/riemannian_staircase.h\"\n\nnamespace gopt {\n\nHybridRotationEstimator::HybridRotationEstimator(\n    const int N, const int dim)\n    : HybridRotationEstimator(N, dim, HybridRotationEstimatorOptions()) {}\n\nHybridRotationEstimator::HybridRotationEstimator(\n    const int N, const int dim,\n    const HybridRotationEstimator::HybridRotationEstimatorOptions& options)\n    : options_(options),\n      images_num_(N),\n      dim_(dim),\n      ld_rotation_estimator_(new LagrangeDualRotationEstimator(\n          N, dim, options.sdp_solver_options)),\n      irls_rotation_refiner_(nullptr) {}\n\nbool HybridRotationEstimator::EstimateRotations(\n    const std::unordered_map<ImagePair, TwoViewGeometry>& view_pairs,\n    std::unordered_map<image_t, Eigen::Vector3d>* global_rotations) {\n  const int N = images_num_;\n\n  CHECK_NOTNULL(global_rotations);\n  CHECK_GT(N, 0);\n  CHECK_EQ(N, (*global_rotations).size());\n  CHECK_GT(view_pairs.size(), 0);\n\n  irls_rotation_refiner_.reset(\n      new IRLSRotationLocalRefiner(N, view_pairs.size(), options_.irls_options));\n  \n  internal::ViewIdToAscentIndex(*global_rotations, &view_id_to_index_);\n  ld_rotation_estimator_->SetViewIdToIndex(view_id_to_index_);\n\n  Eigen::SparseMatrix<double> sparse_matrix;\n  internal::SetupLinearSystem(\n      view_pairs, (*global_rotations).size(),\n      view_id_to_index_, &sparse_matrix);\n  irls_rotation_refiner_->SetViewIdToIndex(view_id_to_index_);\n  irls_rotation_refiner_->SetSparseMatrix(sparse_matrix);\n\n  // Estimate global rotations that resides within the cone of \n  // convergence for IRLS.\n  LOG(INFO) << \"Estimating Rotations Using LagrangeDual\";\n  ld_rotation_estimator_->EstimateRotations(view_pairs, global_rotations);\n\n  // Refine the globally optimal result by IRLS.\n  Eigen::VectorXd tangent_space_step;\n  GlobalRotationsToTangentSpace(*global_rotations, &tangent_space_step);\n  irls_rotation_refiner_->SetInitTangentSpaceStep(tangent_space_step);\n\n  LOG(INFO) << \"Refining Global Rotations\";\n  irls_rotation_refiner_->SolveIRLS(view_pairs, global_rotations);\n\n  return true;\n}\n\nvoid HybridRotationEstimator::GlobalRotationsToTangentSpace(\n    const std::unordered_map<image_t, Eigen::Vector3d>& global_rotations,\n    Eigen::VectorXd* tangent_space_step) {\n  (*tangent_space_step).resize((global_rotations.size() - 1) * 3);\n\n  for (const auto& rotation : global_rotations) {\n    const int view_index = FindOrDie(view_id_to_index_, rotation.first) - 1;\n\n    if (view_index == IRLSRotationLocalRefiner::kConstantRotationIndex) {\n      continue;\n    }\n\n    (*tangent_space_step).segment<3>(3 * view_index) = rotation.second;\n  }\n}\n\n}  // namespace gopt\n", "meta": {"hexsha": "b32e33c4044c4c5f47b76a30ddbc0b87d089f84a", "size": 4743, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/rotation_averaging/hybrid_rotation_estimator.cc", "max_stars_repo_name": "AIBluefisher/GraphOptim", "max_stars_repo_head_hexsha": "0c32f945cba0c158c58b14b4e146e91911738357", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 82.0, "max_stars_repo_stars_event_min_datetime": "2021-04-18T16:34:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T12:08:36.000Z", "max_issues_repo_path": "src/rotation_averaging/hybrid_rotation_estimator.cc", "max_issues_repo_name": "whuaegeanse/GraphOptim", "max_issues_repo_head_hexsha": "0c32f945cba0c158c58b14b4e146e91911738357", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2021-04-19T15:09:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-01T15:01:06.000Z", "max_forks_repo_path": "src/rotation_averaging/hybrid_rotation_estimator.cc", "max_forks_repo_name": "whuaegeanse/GraphOptim", "max_forks_repo_head_hexsha": "0c32f945cba0c158c58b14b4e146e91911738357", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2021-04-19T02:14:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-22T05:53:00.000Z", "avg_line_length": 37.944, "max_line_length": 81, "alphanum_fraction": 0.770187645, "num_tokens": 1126, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568417, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.49796615442059805}}
{"text": "// This file is part of libigl, a simple c++ geometry processing library.\n//\n// Copyright (C) 2016 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 \"bbw.h\"\n#include \"min_quad_with_fixed.h\"\n#include \"harmonic.h\"\n#include \"parallel_for.h\"\n#include <Eigen/Sparse>\n#include <iostream>\n#include <mutex>\n#include <cstdio>\n\nigl::BBWData::BBWData():\n  partition_unity(false),\n  W0(),\n  active_set_params(),\n  verbosity(0)\n{\n  // We know that the Bilaplacian is positive semi-definite\n  active_set_params.Auu_pd = true;\n}\n\nvoid igl::BBWData::print()\n{\n  using namespace std;\n  cout<<\"partition_unity: \"<<partition_unity<<endl;\n  cout<<\"W0=[\"<<endl<<W0<<endl<<\"];\"<<endl;\n}\n\n\ntemplate <\n  typename DerivedV,\n  typename DerivedEle,\n  typename Derivedb,\n  typename Derivedbc,\n  typename DerivedW>\nIGL_INLINE bool igl::bbw(\n  const Eigen::PlainObjectBase<DerivedV> & V,\n  const Eigen::PlainObjectBase<DerivedEle> & Ele,\n  const Eigen::PlainObjectBase<Derivedb> & b,\n  const Eigen::PlainObjectBase<Derivedbc> & bc,\n  igl::BBWData & data,\n  Eigen::PlainObjectBase<DerivedW> & W\n  )\n{\n  using namespace std;\n  using namespace Eigen;\n  assert(!data.partition_unity && \"partition_unity not implemented yet\");\n  // number of domain vertices\n  int n = V.rows();\n  // number of handles\n  int m = bc.cols();\n  // Build biharmonic operator\n  Eigen::SparseMatrix<typename DerivedV::Scalar> Q;\n  harmonic(V,Ele,2,Q);\n  W.derived().resize(n,m);\n  // No linear terms\n  VectorXd c = VectorXd::Zero(n);\n  // No linear constraints\n  SparseMatrix<typename DerivedW::Scalar> A(0,n),Aeq(0,n),Aieq(0,n);\n  VectorXd Beq(0,1),Bieq(0,1);\n  // Upper and lower box constraints (Constant bounds)\n  VectorXd ux = VectorXd::Ones(n);\n  VectorXd lx = VectorXd::Zero(n);\n  active_set_params eff_params = data.active_set_params;\n  if(data.verbosity >= 1)\n  {\n    cout<<\"BBW: max_iter: \"<<data.active_set_params.max_iter<<endl;\n    cout<<\"BBW: eff_max_iter: \"<<eff_params.max_iter<<endl;\n  }\n  if(data.verbosity >= 1)\n  {\n    cout<<\"BBW: Computing initial weights for \"<<m<<\" handle\"<<\n      (m!=1?\"s\":\"\")<<\".\"<<endl;\n  }\n  min_quad_with_fixed_data<typename DerivedW::Scalar > mqwf;\n  min_quad_with_fixed_precompute(Q,b,Aeq,true,mqwf);\n  min_quad_with_fixed_solve(mqwf,c,bc,Beq,W);\n  // decrement\n  eff_params.max_iter--;\n  bool error = false;\n  // Loop over handles\n  std::mutex critical;\n  const auto & optimize_weight = [&](const int i)\n  {\n    // Quicker exit for paralle_for\n    if(error)\n    {\n      return;\n    }\n    if(data.verbosity >= 1)\n    {\n      std::lock_guard<std::mutex> lock(critical);\n      cout<<\"BBW: Computing weight for handle \"<<i+1<<\" out of \"<<m<<\n        \".\"<<endl;\n    }\n    VectorXd bci = bc.col(i);\n    VectorXd Wi;\n    // use initial guess\n    Wi = W.col(i);\n    SolverStatus ret = active_set(\n        Q,c,b,bci,Aeq,Beq,Aieq,Bieq,lx,ux,eff_params,Wi);\n    switch(ret)\n    {\n      case SOLVER_STATUS_CONVERGED:\n        break;\n      case SOLVER_STATUS_MAX_ITER:\n        cerr<<\"active_set: max iter without convergence.\"<<endl;\n        break;\n      case SOLVER_STATUS_ERROR:\n      default:\n        cerr<<\"active_set error.\"<<endl;\n        error = true;\n    }\n    W.col(i) = Wi;\n  };\n#ifdef WIN32\n  for (int i = 0; i < m; ++i)\n    optimize_weight(i);\n#else\n  parallel_for(m,optimize_weight,2);\n#endif\n  if(error)\n  {\n    return false;\n  }\n\n#ifndef NDEBUG\n  const double min_rowsum = W.rowwise().sum().array().abs().minCoeff();\n  if(min_rowsum < 0.1)\n  {\n    cerr<<\"bbw.cpp: Warning, minimum row sum is very low. Consider more \"\n      \"active set iterations or enforcing partition of unity.\"<<endl;\n  }\n#endif\n\n  return true;\n}\n\n#ifdef IGL_STATIC_LIBRARY\n// Explicit template instantiation\ntemplate bool igl::bbw<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<double, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -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> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, igl::BBWData&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&);\n#endif\n\n", "meta": {"hexsha": "8193ed223554ab4912f4d5bb93a5d06cef3b3a82", "size": 4478, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "igl/bbw.cpp", "max_stars_repo_name": "aviadtzemah/animation2", "max_stars_repo_head_hexsha": "9a3f980fbe27672fe71f8f61f73b5713f2af5089", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2392.0, "max_stars_repo_stars_event_min_datetime": "2016-12-17T14:14:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T19:40:40.000Z", "max_issues_repo_path": "igl/bbw.cpp", "max_issues_repo_name": "aviadtzemah/animation2", "max_issues_repo_head_hexsha": "9a3f980fbe27672fe71f8f61f73b5713f2af5089", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 106.0, "max_issues_repo_issues_event_min_datetime": "2018-04-19T17:47:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-01T19:44:11.000Z", "max_forks_repo_path": "igl/bbw.cpp", "max_forks_repo_name": "aviadtzemah/animation2", "max_forks_repo_head_hexsha": "9a3f980fbe27672fe71f8f61f73b5713f2af5089", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 184.0, "max_forks_repo_forks_event_min_datetime": "2017-11-15T09:55:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T16:30:46.000Z", "avg_line_length": 30.0536912752, "max_line_length": 597, "alphanum_fraction": 0.6536400179, "num_tokens": 1371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568416, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.497966154420598}}
{"text": "// This file is part of libigl, a simple c++ geometry processing library.\n//\n// Copyright (C) 2014 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 \"harmonic.h\"\n#include \"adjacency_matrix.h\"\n#include \"cotmatrix.h\"\n#include \"diag.h\"\n#include \"invert_diag.h\"\n#include \"isdiag.h\"\n#include \"massmatrix.h\"\n#include \"min_quad_with_fixed.h\"\n#include \"speye.h\"\n#include \"sum.h\"\n#include <Eigen/Sparse>\n\ntemplate <\n  typename DerivedV,\n  typename DerivedF,\n  typename Derivedb,\n  typename Derivedbc,\n  typename DerivedW>\nIGL_INLINE bool igl::harmonic(\n  const Eigen::PlainObjectBase<DerivedV> & V,\n  const Eigen::PlainObjectBase<DerivedF> & F,\n  const Eigen::PlainObjectBase<Derivedb> & b,\n  const Eigen::PlainObjectBase<Derivedbc> & bc,\n  const int k,\n  Eigen::PlainObjectBase<DerivedW> & W)\n{\n  using namespace Eigen;\n  typedef typename DerivedV::Scalar Scalar;\n  SparseMatrix<Scalar> L,M;\n  cotmatrix(V,F,L);\n  massmatrix(V,F,MASSMATRIX_TYPE_DEFAULT,M);\n  return harmonic(L,M,b,bc,k,W);\n}\n\ntemplate <\n  typename DerivedF,\n  typename Derivedb,\n  typename Derivedbc,\n  typename DerivedW>\nIGL_INLINE bool igl::harmonic(\n  const Eigen::PlainObjectBase<DerivedF> & F,\n  const Eigen::PlainObjectBase<Derivedb> & b,\n  const Eigen::PlainObjectBase<Derivedbc> & bc,\n  const int k,\n  Eigen::PlainObjectBase<DerivedW> & W)\n{\n  using namespace Eigen;\n  typedef typename Derivedbc::Scalar Scalar;\n  SparseMatrix<Scalar> A;\n  adjacency_matrix(F,A);\n  // sum each row\n  SparseVector<Scalar> Asum;\n  sum(A,1,Asum);\n  // Convert row sums into diagonal of sparse matrix\n  SparseMatrix<Scalar> Adiag;\n  diag(Asum,Adiag);\n  SparseMatrix<Scalar> L = A-Adiag;\n  SparseMatrix<Scalar> M;\n  speye(L.rows(),M);\n  return harmonic(L,M,b,bc,k,W);\n}\n\ntemplate <\n  typename DerivedL,\n  typename DerivedM,\n  typename Derivedb,\n  typename Derivedbc,\n  typename DerivedW>\nIGL_INLINE bool igl::harmonic(\n  const Eigen::SparseMatrix<DerivedL> & L,\n  const Eigen::SparseMatrix<DerivedM> & M,\n  const Eigen::PlainObjectBase<Derivedb> & b,\n  const Eigen::PlainObjectBase<Derivedbc> & bc,\n  const int k,\n  Eigen::PlainObjectBase<DerivedW> & W)\n{\n  const int n = L.rows();\n  assert(n == L.cols() && \"L must be square\");\n  assert(n == M.cols() && \"M must be same size as L\");\n  assert(n == M.rows() && \"M must be square\");\n  assert(igl::isdiag(M) && \"Mass matrix should be diagonal\");\n\n  Eigen::SparseMatrix<DerivedL> Q;\n  igl::harmonic(L,M,k,Q);\n\n  typedef DerivedL Scalar;\n  min_quad_with_fixed_data<Scalar> data;\n  min_quad_with_fixed_precompute(Q,b,Eigen::SparseMatrix<Scalar>(),true,data);\n  W.resize(n,bc.cols());\n  typedef Eigen::Matrix<Scalar,Eigen::Dynamic,1> VectorXS;\n  const VectorXS B = VectorXS::Zero(n,1);\n  for(int w = 0;w<bc.cols();w++)\n  {\n    const VectorXS bcw = bc.col(w);\n    VectorXS Ww;\n    if(!min_quad_with_fixed_solve(data,B,bcw,VectorXS(),Ww))\n    {\n      return false;\n    }\n    W.col(w) = Ww;\n  }\n  return true;\n}\n\ntemplate <\n  typename DerivedL,\n  typename DerivedM,\n  typename DerivedQ>\nIGL_INLINE void igl::harmonic(\n  const Eigen::SparseMatrix<DerivedL> & L,\n  const Eigen::SparseMatrix<DerivedM> & M,\n  const int k,\n  Eigen::SparseMatrix<DerivedQ> & Q)\n{\n  assert(L.rows() == L.cols()&&\"L should be square\");\n  assert(M.rows() == M.cols()&&\"M should be square\");\n  assert(L.rows() == M.rows()&&\"L should match M's dimensions\");\n  Eigen::SparseMatrix<DerivedM> Mi;\n  invert_diag(M,Mi);\n  Q = -L;\n  for(int p = 1;p<k;p++)\n  {\n    Q = (Q*Mi*-L).eval();\n  }\n}\n\ntemplate <\n  typename DerivedV,\n  typename DerivedF,\n  typename DerivedQ>\nIGL_INLINE void igl::harmonic(\n  const Eigen::PlainObjectBase<DerivedV> & V,\n  const Eigen::PlainObjectBase<DerivedF> & F,\n  const int k,\n  Eigen::SparseMatrix<DerivedQ> & Q)\n{\n  Eigen::SparseMatrix<DerivedQ> L,M;\n  cotmatrix(V,F,L);\n  massmatrix(V,F,MASSMATRIX_TYPE_DEFAULT,M);\n  return harmonic(L,M,k,Q);\n}\n\n#ifdef IGL_STATIC_LIBRARY\n// Explicit template specialization\ntemplate bool igl::harmonic<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<double, -1, 1, 0, -1, 1>, Eigen::Matrix<double, -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> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> > const&, int, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> >&);\ntemplate bool igl::harmonic<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<double, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -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> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, int, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&);\ntemplate bool igl::harmonic<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<double, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -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> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, int, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&);\n\ntemplate bool igl::harmonic<Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<double, -1, 1, 0, -1, 1>, Eigen::Matrix<double, -1, 1, 0, -1, 1> >(Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> > const&, int, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> >&);\ntemplate bool igl::harmonic<Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, -1, 0, -1, -1> >(Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, int, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&);\ntemplate bool igl::harmonic<Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, -1, 0, -1, -1> >(Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, int, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&);\ntemplate void igl::harmonic<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, double>(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, int, Eigen::SparseMatrix<double, 0, int>&);\n#endif\n", "meta": {"hexsha": "a1a28804163a7fda532d96d084aa171aecf784f1", "size": 7609, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Source/SprueEngine/Libs/igl/harmonic.cpp", "max_stars_repo_name": "Qt-Widgets/TexGraph", "max_stars_repo_head_hexsha": "8fe72cea1afcf5e235c810003bf4ee062bb3fc13", "max_stars_repo_licenses": ["MIT"], "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": "Source/SprueEngine/Libs/igl/harmonic.cpp", "max_issues_repo_name": "Qt-Widgets/TexGraph", "max_issues_repo_head_hexsha": "8fe72cea1afcf5e235c810003bf4ee062bb3fc13", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-04-13T17:43:54.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-15T04:17:37.000Z", "max_forks_repo_path": "Source/SprueEngine/Libs/igl/harmonic.cpp", "max_forks_repo_name": "Qt-Widgets/TexGraph", "max_forks_repo_head_hexsha": "8fe72cea1afcf5e235c810003bf4ee062bb3fc13", "max_forks_repo_licenses": ["MIT"], "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": 47.2608695652, "max_line_length": 596, "alphanum_fraction": 0.6526481798, "num_tokens": 2695, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998560157665, "lm_q2_score": 0.6406358479787609, "lm_q1q2_score": 0.4979661523924293}}
{"text": "#include \"engine/douglas_peucker.hpp\"\n#include \"util/coordinate_calculation.hpp\"\n\n#include <boost/assert.hpp>\n#include \"osrm/coordinate.hpp\"\n\n#include <cmath>\n#include <algorithm>\n#include <iterator>\n#include <stack>\n#include <utility>\n\nnamespace osrm\n{\nnamespace engine\n{\n\nnamespace\n{\nstruct CoordinatePairCalculator\n{\n    CoordinatePairCalculator(const util::FixedPointCoordinate coordinate_a,\n                             const util::FixedPointCoordinate coordinate_b)\n    {\n        // initialize distance calculator with two fixed coordinates a, b\n        first_lat = (coordinate_a.lat / COORDINATE_PRECISION) * util::RAD;\n        first_lon = (coordinate_a.lon / COORDINATE_PRECISION) * util::RAD;\n        second_lat = (coordinate_b.lat / COORDINATE_PRECISION) * util::RAD;\n        second_lon = (coordinate_b.lon / COORDINATE_PRECISION) * util::RAD;\n    }\n\n    int operator()(const util::FixedPointCoordinate other) const\n    {\n        // set third coordinate c\n        const float float_lat1 = (other.lat / COORDINATE_PRECISION) * util::RAD;\n        const float float_lon1 = (other.lon / COORDINATE_PRECISION) * util::RAD;\n\n        // compute distance (a,c)\n        const float x_value_1 = (first_lon - float_lon1) * cos((float_lat1 + first_lat) / 2.f);\n        const float y_value_1 = first_lat - float_lat1;\n        const float dist1 = std::hypot(x_value_1, y_value_1) * util::EARTH_RADIUS;\n\n        // compute distance (b,c)\n        const float x_value_2 = (second_lon - float_lon1) * cos((float_lat1 + second_lat) / 2.f);\n        const float y_value_2 = second_lat - float_lat1;\n        const float dist2 = std::hypot(x_value_2, y_value_2) * util::EARTH_RADIUS;\n\n        // return the minimum\n        return static_cast<int>(std::min(dist1, dist2));\n    }\n\n    float first_lat;\n    float first_lon;\n    float second_lat;\n    float second_lon;\n};\n}\n\nvoid douglasPeucker(std::vector<SegmentInformation>::iterator begin,\n                    std::vector<SegmentInformation>::iterator end,\n                    const unsigned zoom_level)\n{\n    using Iter = decltype(begin);\n    using GeometryRange = std::pair<Iter, Iter>;\n\n    std::stack<GeometryRange> recursion_stack;\n\n    const auto size = std::distance(begin, end);\n    if (size < 2)\n    {\n        return;\n    }\n\n    begin->necessary = true;\n    std::prev(end)->necessary = true;\n\n    {\n        BOOST_ASSERT_MSG(zoom_level < detail::DOUGLAS_PEUCKER_THRESHOLDS_SIZE,\n                         \"unsupported zoom level\");\n        auto left_border = begin;\n        auto right_border = std::next(begin);\n        // Sweep over array and identify those ranges that need to be checked\n        do\n        {\n            // traverse list until new border element found\n            if (right_border->necessary)\n            {\n                // sanity checks\n                BOOST_ASSERT(left_border->necessary);\n                BOOST_ASSERT(right_border->necessary);\n                recursion_stack.emplace(left_border, right_border);\n                left_border = right_border;\n            }\n            ++right_border;\n        } while (right_border != end);\n    }\n\n    // mark locations as 'necessary' by divide-and-conquer\n    while (!recursion_stack.empty())\n    {\n        // pop next element\n        const GeometryRange pair = recursion_stack.top();\n        recursion_stack.pop();\n        // sanity checks\n        BOOST_ASSERT_MSG(pair.first->necessary, \"left border must be necessary\");\n        BOOST_ASSERT_MSG(pair.second->necessary, \"right border must be necessary\");\n        BOOST_ASSERT_MSG(std::distance(pair.second, end) > 0, \"right border outside of geometry\");\n        BOOST_ASSERT_MSG(std::distance(pair.first, pair.second) >= 0,\n                         \"left border on the wrong side\");\n\n        int max_int_distance = 0;\n        auto farthest_entry_it = pair.second;\n        const CoordinatePairCalculator dist_calc(pair.first->location, pair.second->location);\n\n        // sweep over range to find the maximum\n        for (auto it = std::next(pair.first); it != pair.second; ++it)\n        {\n            const int distance = dist_calc(it->location);\n            // found new feasible maximum?\n            if (distance > max_int_distance &&\n                distance > detail::DOUGLAS_PEUCKER_THRESHOLDS[zoom_level])\n            {\n                farthest_entry_it = it;\n                max_int_distance = distance;\n            }\n        }\n\n        // check if maximum violates a zoom level dependent threshold\n        if (max_int_distance > detail::DOUGLAS_PEUCKER_THRESHOLDS[zoom_level])\n        {\n            //  mark idx as necessary\n            farthest_entry_it->necessary = true;\n            if (1 < std::distance(pair.first, farthest_entry_it))\n            {\n                recursion_stack.emplace(pair.first, farthest_entry_it);\n            }\n            if (1 < std::distance(farthest_entry_it, pair.second))\n            {\n                recursion_stack.emplace(farthest_entry_it, pair.second);\n            }\n        }\n    }\n}\n} // ns engine\n} // ns osrm\n", "meta": {"hexsha": "2685b4a2a7cfc9780bcf4fb15093fcddcde8a253", "size": 5029, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/engine/douglas_peucker.cpp", "max_stars_repo_name": "mortada/osrm-backend", "max_stars_repo_head_hexsha": "aae02cd1be7e99eb75117c7d8c9f39b858ad9019", "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/engine/douglas_peucker.cpp", "max_issues_repo_name": "mortada/osrm-backend", "max_issues_repo_head_hexsha": "aae02cd1be7e99eb75117c7d8c9f39b858ad9019", "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/engine/douglas_peucker.cpp", "max_forks_repo_name": "mortada/osrm-backend", "max_forks_repo_head_hexsha": "aae02cd1be7e99eb75117c7d8c9f39b858ad9019", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-09-20T00:55:14.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-20T00:55:14.000Z", "avg_line_length": 34.4452054795, "max_line_length": 98, "alphanum_fraction": 0.6176178167, "num_tokens": 1122, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4979188082435052}}
{"text": "#include <boost/math/special_functions/zeta.hpp>\n", "meta": {"hexsha": "c8a70787617d55d518a33793c5d3a0f8d6f5bc46", "size": 49, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_special_functions_zeta.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_special_functions_zeta.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_special_functions_zeta.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 24.5, "max_line_length": 48, "alphanum_fraction": 0.8163265306, "num_tokens": 11, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4979188082435052}}
{"text": "// BSD 3-Clause License\n\n// Copyright (c) 2021, 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// edited by Steffen Urban (urbste@googlemail.com), August 2021\n\n#include \"theia/math/rank_restricted_sdp_solver.h\"\n\n#include <glog/logging.h>\n#include <limits>\n\n#include <Eigen/Eigenvalues>\n#include <Eigen/QR>\n\nnamespace theia {\nnamespace math {\n\nRankRestrictedSDPSolver::RankRestrictedSDPSolver(const size_t n,\n                                                 const size_t block_dim)\n    : RankRestrictedSDPSolver(n, block_dim, math::SDPSolverOptions()) {}\n\nRankRestrictedSDPSolver::RankRestrictedSDPSolver(\n    const size_t n,\n    const size_t block_dim,\n    const math::SDPSolverOptions& options)\n    : BCMSDPSolver(n, block_dim, options), rank_(3) {\n  Y_ = Eigen::MatrixXd::Zero(rank_, dim_ * n_);\n}\n\nvoid RankRestrictedSDPSolver::Solve(math::Summary& summary) {\n  Eigen::MatrixXd G = Eigen::MatrixXd::Zero(rank_, dim_ * n_);\n\n#pragma omp parallel for num_threads(sdp_solver_options_.num_threads)\n  // Compute inital G according to Equ.(3)\n  for (size_t i = 0; i < n_; i++) {\n    const std::vector<size_t>& adjs = adj_edges_[i];\n    for (auto j : adjs) {\n      G.block(0, i * dim_, rank_, dim_) +=\n          Y_.block(0, j * dim_, rank_, dim_) *\n          Q_.block(j * dim_, i * dim_, dim_, dim_);\n    }\n  }\n\n  double prev_func_val = std::numeric_limits<double>::max();\n  double cur_func_val = this->EvaluateFuncVal();\n  double duration = 0.0;\n  double error = 0.0;\n\n  summary.begin_time = std::chrono::high_resolution_clock::now();\n  while (summary.total_iterations_num < sdp_solver_options_.max_iterations) {\n    if (sdp_solver_options_.verbose) {\n      LogToStd(summary.total_iterations_num,\n               prev_func_val,\n               cur_func_val,\n               error,\n               duration);\n    }\n\n    if (IsConverge(prev_func_val,\n                   cur_func_val,\n                   sdp_solver_options_.tolerance,\n                   &error)) {\n      break;\n    }\n\n    for (size_t i = 0; i < n_; i++) {\n      const Eigen::MatrixXd G_block = G.block(0, i * dim_, rank_, dim_);\n      Eigen::JacobiSVD<Eigen::MatrixXd> jacobi_svd(\n          -G_block, Eigen::ComputeThinU | Eigen::ComputeThinV);\n\n      const Eigen::MatrixXd prev_Y = Y_.block(0, i * dim_, rank_, dim_).eval();\n      Y_.block(0, i * dim_, rank_, dim_) =\n          jacobi_svd.matrixU() * jacobi_svd.matrixV().transpose();\n\n      const std::vector<size_t>& adjs = adj_edges_[i];\n#pragma omp parallel for num_threads(sdp_solver_options_.num_threads)\n      for (size_t idx = 0; idx < adjs.size(); ++idx) {\n        const size_t j = adjs[idx];\n        G.block(0, j * dim_, rank_, dim_) +=\n            (Y_.block(0, i * dim_, rank_, dim_) - prev_Y) *\n            Q_.block(i * dim_, j * dim_, dim_, dim_);\n      }\n    }\n\n    summary.total_iterations_num++;\n    duration = summary.Duration();\n\n    // Update function value\n    prev_func_val = cur_func_val;\n    cur_func_val = this->EvaluateFuncVal();\n  }\n\n  summary.total_iterations_num++;\n  if (sdp_solver_options_.verbose) {\n    LogToStd(summary.total_iterations_num,\n             prev_func_val,\n             cur_func_val,\n             error,\n             duration);\n  }\n}\n\nEigen::MatrixXd RankRestrictedSDPSolver::GetSolution() const {\n  Eigen::MatrixXd solution = Eigen::MatrixXd(dim_, dim_ * n_);\n  for (size_t i = 0; i < n_; i++) {\n    solution.block(0, dim_ * i, dim_, dim_) =\n        Y_.block(0, 0, rank_, dim_).transpose() *\n        Y_.block(0, dim_ * i, rank_, dim_);\n  }\n  return solution;\n}\n\nconst Eigen::MatrixXd& RankRestrictedSDPSolver::GetYStar() const { return Y_; }\n\nconst Eigen::MatrixXd RankRestrictedSDPSolver::ComputeQYt(\n    const Eigen::MatrixXd& Y) const {\n  return Q_ * Y.transpose();\n}\n\nEigen::MatrixXd RankRestrictedSDPSolver::ComputeLambdaMatrix() const {\n  const Eigen::MatrixXd QYt = this->ComputeQYt(Y_);\n\n  const size_t rank = Y_.rows();\n  // \\Lambda = \\SymblockDiag(Q * Y^T * Y).\n  Eigen::MatrixXd Lambda = Eigen::MatrixXd::Zero(dim_, n_ * dim_);\n\n#pragma omp parallel for num_threads(sdp_solver_options_.num_threads)\n  for (size_t i = 0; i < n_; ++i) {\n    Eigen::MatrixXd P =\n        QYt.block(i * dim_, 0, dim_, rank) * Y_.block(0, i * dim_, rank, dim_);\n    Lambda.block(0, i * dim_, dim_, dim_) = 0.5 * (P + P.transpose());\n  }\n\n  return Lambda;\n}\n\ndouble RankRestrictedSDPSolver::EvaluateFuncVal() const {\n  // tr(Q * Y^T * Y) = tr(Y * Q * Y^T)\n  // return (Q_ * Y_.transpose() * Y_).trace();\n  return (Y_ * (Q_ * Y_.transpose())).trace();\n}\n\ndouble RankRestrictedSDPSolver::EvaluateFuncVal(\n    const Eigen::MatrixXd& Y) const {\n  return (Y * (Q_ * Y.transpose())).trace();\n}\n\nvoid RankRestrictedSDPSolver::AugmentRank() {\n  rank_++;\n  Y_.conservativeResize(Y_.rows() + 1, Y_.cols());\n  Y_.row(Y_.rows() - 1).setZero();\n}\n\nvoid RankRestrictedSDPSolver::SetOptimalY(const Eigen::MatrixXd& Y) {\n  CHECK_EQ(Y.rows(), Y_.rows());\n  CHECK_EQ(Y.cols(), Y_.cols());\n  Y_ = Y;\n}\n\nsize_t RankRestrictedSDPSolver::CurrentRank() const { return rank_; }\n\nEigen::MatrixXd RankRestrictedSDPSolver::Project(\n    const Eigen::MatrixXd& A) const {\n  // We use a generalization of the well-known SVD-based projection for the\n  // orthogonal and special orthogonal groups; see for example Proposition 7\n  // in the paper \"Projection-Like Retractions on Matrix Manifolds\" by Absil\n  // and Malick.\n\n  Eigen::MatrixXd P(rank_, dim_ * n_);\n\n#pragma omp parallel for num_threads(sdp_solver_options_.num_threads)\n  for (size_t i = 0; i < n_; ++i) {\n    // Compute the (thin) SVD of the ith block of A\n    Eigen::JacobiSVD<Eigen::MatrixXd> SVD(\n        A.block(0, i * dim_, rank_, dim_),\n        Eigen::ComputeThinU | Eigen::ComputeThinV);\n\n    // Set the ith block of P to the SVD-based projection of the ith block of A\n    P.block(0, i * dim_, rank_, dim_) =\n        SVD.matrixU() * SVD.matrixV().transpose();\n  }\n  return P;\n}\n\nEigen::MatrixXd RankRestrictedSDPSolver::Retract(\n    const Eigen::MatrixXd& Y, const Eigen::MatrixXd& V) const {\n  // We use projection-based retraction, as described in \"Projection-Like\n  // Retractions on Matrix Manifolds\" by Absil and Malick.\n  return Project(Y + V);\n}\n\nEigen::MatrixXd RankRestrictedSDPSolver::EuclideanGradient(\n    const Eigen::MatrixXd& Y) const {\n  return 2.0 * (Q_ * Y.transpose()).transpose();\n}\n\nEigen::MatrixXd RankRestrictedSDPSolver::RiemannianGradient(\n    const Eigen::MatrixXd& Y, const Eigen::MatrixXd& nablaF_Y) const {\n  return TangentSpaceProjection(Y, nablaF_Y);\n}\n\nEigen::MatrixXd RankRestrictedSDPSolver::RiemannianGradient(\n    const Eigen::MatrixXd& Y) const {\n  return TangentSpaceProjection(Y, EuclideanGradient(Y));\n}\n\nEigen::MatrixXd RankRestrictedSDPSolver::TangentSpaceProjection(\n    const Eigen::MatrixXd& Y, const Eigen::MatrixXd& dotY) const {\n  return dotY - SymBlockDiagProduct(Y, Y, dotY);\n}\n\nEigen::MatrixXd RankRestrictedSDPSolver::SymBlockDiagProduct(\n    const Eigen::MatrixXd& A,\n    const Eigen::MatrixXd& B,\n    const Eigen::MatrixXd& C) const {\n  // Preallocate result matrix\n  Eigen::MatrixXd R(rank_, dim_ * n_);\n\n#pragma omp parallel for num_threads(sdp_solver_options_.num_threads)\n  for (size_t i = 0; i < n_; ++i) {\n    // Compute block product Bi' * Ci.\n    Eigen::MatrixXd P = B.block(0, i * dim_, rank_, dim_).transpose() *\n                        C.block(0, i * dim_, rank_, dim_);\n    // Symmetrize this block.\n    Eigen::MatrixXd S = 0.5 * (P + P.transpose());\n    // Compute Ai * S and set corresponding block of R.\n    R.block(0, i * dim_, rank_, dim_) = A.block(0, i * dim_, rank_, dim_) * S;\n  }\n  return R;\n}\n\nEigen::MatrixXd RankRestrictedSDPSolver::Precondition(\n    const Eigen::MatrixXd& Y, const Eigen::MatrixXd& dotY) const {\n  switch (sdp_solver_options_.preconditioner_type) {\n    case PreconditionerType::None:\n      return dotY;\n      break;\n    case PreconditionerType::JACOBI:\n      /* code */\n      break;\n    case PreconditionerType::INCOMPLETE_CHOLESKY:\n      /* code */\n      break;\n    case PreconditionerType::REGULARIZED_CHOLESKY:\n    default:\n      break;\n  }\n}\n\n}  // namespace math\n}  // namespace theia\n", "meta": {"hexsha": "f36f75026dcdb71e89bc37804933ff8c24b0035a", "size": 9562, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/math/rank_restricted_sdp_solver.cc", "max_stars_repo_name": "urbste/TheiaSfM", "max_stars_repo_head_hexsha": "a92fa27e90b6182e2a2511a46d24283afad1a995", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T03:01:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-04T08:08:45.000Z", "max_issues_repo_path": "src/theia/math/rank_restricted_sdp_solver.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/math/rank_restricted_sdp_solver.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": 34.15, "max_line_length": 79, "alphanum_fraction": 0.6737084292, "num_tokens": 2537, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4979188030338384}}
{"text": "#include <armadillo>\n#include <cmath>\n#include <emissions.hpp>\n#include <HSMM.hpp>\n#include <iostream>\n#include <vector>\n\nusing namespace arma;\nusing namespace hsmm;\nusing namespace std;\n\n#define NDIM 2\n#define NDUR 70\n#define MINDUR 30\n#define NOISE_STDDEV 0.05\n\ndouble gaussianlogpdf_(double x, double mu, double sigma) {\n    double ret = ((x - mu)*(x - mu)) / (-2*sigma*sigma);\n    ret = ret - log(sqrt(2 * M_PI) * sigma);\n    return ret;\n}\n\nmat fieldToMat(int njoints, field<mat> &samples) {\n    mat ret(njoints, samples.n_elem);\n    for(int i = 0; i < samples.n_elem; i++)\n        ret.col(i) = samples(i);\n    return ret;\n}\n\nvoid fillDurationMatrix(mat& duration, const ivec& centers) {\n    assert(centers.n_elem == duration.n_rows);\n    duration.zeros();\n    //vec pmf_pattern = {0.1, 0.2, 0.4, 0.2, 0.1};\n    vec pmf_pattern(20);\n    pmf_pattern.fill(1.0/pmf_pattern.n_elem);\n    for(int i = 0; i < centers.n_elem; i++) {\n        int m = centers(i);\n        int half = pmf_pattern.n_elem / 2;\n        for(int j = 0; j < pmf_pattern.n_elem; j++)\n            duration(i, m - half + j) = pmf_pattern(j);\n    }\n}\n\nclass ToyEmission : public AbstractEmissionOnlineSetting {\n    public:\n        ToyEmission(vector<function<vec(double)>> states, int ndim,\n                double noise_stddev) : states_(states),\n                AbstractEmissionOnlineSetting(states.size(), ndim) {\n            output_gaussian_stddev_ = ones<mat>(getDimension(),\n                    getNumberStates()) * noise_stddev;\n        }\n\n        ToyEmission* clone() const {\n            return new ToyEmission(*this);\n        }\n\n        vec getSampleLocations(int length) const {\n            return linspace<vec>(0, 1.0, length);\n        }\n\n        double loglikelihood(int state, const field<mat>& obs) const {\n            vec t = getSampleLocations(obs.n_elem);\n            double ret = 0;\n            for(int i = 0; i < obs.n_elem; i++) {\n                // Making sure all the missing obs are at the end.\n                // Other missing obs patterns are not supported yet.\n                if (obs(i).is_empty()) {\n                    for(int j = i; j < obs.n_elem; j++)\n                        assert(obs(j).is_empty());\n                    break;\n                }\n                vec diff = obs(i) - states_.at(state)(t(i));\n                for(int j = 0; j < diff.n_elem; j++)\n                    ret += gaussianlogpdf_(diff(j), 0,\n                            output_gaussian_stddev_(j, state));\n            }\n            return ret;\n        }\n\n        void reestimate(int min_duration, const field<cube>& meta,\n                const field<field<mat>>& mobs ) {\n            throw logic_error(\"Not implemented yet\");\n        }\n\n        field<mat> sampleFromState(int state, int nsegments,\n                mt19937& rng) const {\n            vec t = getSampleLocations(nsegments);\n            field<mat> ret(nsegments);\n            for(int i = 0; i < nsegments; i++) {\n                ret(i) = randn<vec>(getDimension());\n                ret(i) = ret(i) % output_gaussian_stddev_.col(state);\n                ret(i) = ret(i) + states_.at(state)(t(i));\n            }\n            return ret;\n        }\n\n        field<mat> sampleNextObsGivenPastObs(int state, int seg_dur,\n                const field<mat>& past_obs, mt19937 &rng) const {\n            throw logic_error(\"Not implemented yet\");\n        }\n\n    private:\n        vector<function<vec(double)>> states_;\n        mat output_gaussian_stddev_;\n};\n\nvec halfsine1(double t) {\n    assert(t <= 1.0 && t >= 0);\n    t = t * M_PI;\n    vec ret = {sin(t), -sin(t)};\n    return ret;\n}\n\nvec halfsine2(double t) {\n    assert(t <= 1.0 && t >= 0);\n    t = t * M_PI;\n    vec ret = {-sin(t), sin(t)};\n    return ret;\n}\n\nvec halfsine3(double t) {\n    assert(t <= 1.0 && t >= 0);\n    t = t * M_PI;\n    vec ret = {0.5*sin(t), 0.25*sin(t)};\n    return ret;\n}\n\nvec halfsine4(double t) {\n    assert(t <= 1.0 && t >= 0);\n    t = t * M_PI;\n    vec ret = {-0.25*sin(t), -0.5*sin(t)};\n    return ret;\n}\n\nint main(int arc, char* argv[]) {\n    vector<function<vec(double)>> states = {halfsine1, halfsine2,\n            halfsine3, halfsine4};\n    shared_ptr<ToyEmission> ptr_emission(new ToyEmission(states, NDIM,\n            NOISE_STDDEV));\n    vec pi(states.size());\n    mat transition(states.size(), states.size());\n    mat duration(states.size(), NDUR, fill::zeros);\n\n    // Init the parameters.\n    pi.fill(1.0 / states.size());\n    transition.fill(1.0 / (states.size() - 1));\n    transition.diag().zeros();\n    ivec duration_centers = {15, 30, 45, 60};\n    fillDurationMatrix(duration, duration_centers);\n\n    OnlineHSMM online_toy_model(static_pointer_cast<\n            AbstractEmissionOnlineSetting>(ptr_emission), transition, pi,\n            duration, MINDUR);\n    int nsegments = 12;\n    ivec hs, hd;\n    field<mat> toy_seq = online_toy_model.sampleSegments(nsegments, hs, hd);\n    int nobs = toy_seq.n_elem;\n    imat vit_mat = join_horiz(hs, hd);\n    cout << \"vit file\" << endl << vit_mat << endl;\n\n    // Online inference.\n    mat state_marginals(states.size(), nobs);\n    mat runlength_marginals(MINDUR + NDUR, nobs);\n    mat implicit_remaining_marginals(MINDUR + NDUR, nobs);\n    mat duration_marginals(NDUR, nobs);\n    mat implicit_duration_marginals(NDUR, nobs);\n    for(int c = 0; c < nobs; c++) {\n        cout << \"time step: \" << c << endl;\n        online_toy_model.addNewObservation(toy_seq(c));\n        state_marginals.col(c) = online_toy_model.getStateMarginal();\n        runlength_marginals.col(c) = online_toy_model.getRunlengthMarginal();\n        duration_marginals.col(c) = online_toy_model.getDurationMarginal();\n        implicit_remaining_marginals.col(c) = online_toy_model.\n                getImplicitResidualTimeMarginal();\n        //implicit_duration_marginals.col(c) = online_toy_model.\n        //        getImplicitDurationMarginal();\n    }\n\n    // Saving everything.\n    string prefix = \"/local_data/dagudelo/paper_synth_experiment/\";\n    mat output = fieldToMat(NDIM, toy_seq);\n    output.save(prefix + \"paper_synth_obs.txt\", raw_ascii);\n    vit_mat.save(prefix + \"paper_synth_gt_vit_seq.txt\", raw_ascii);\n    state_marginals.save(prefix + \"paper_synth_mstates.txt\", raw_ascii);\n    runlength_marginals.save(prefix + \"paper_synth_runlength.txt\", raw_ascii);\n    duration_marginals.save(prefix + \"paper_synth_duration.txt\", raw_ascii);\n    implicit_remaining_marginals.save(prefix + \"paper_synth_remaining.txt\",\n            raw_ascii);\n    //implicit_duration_marginals.save(prefix + \"paper_synth_impli_duration.txt\",\n    //        raw_ascii);\n    return 0;\n}\n", "meta": {"hexsha": "e0f28f47c68b592b39fd753e44ea6877ae961d81", "size": 6594, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/paper_synth_exp.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/paper_synth_exp.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/paper_synth_exp.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": 34.1658031088, "max_line_length": 81, "alphanum_fraction": 0.5943281771, "num_tokens": 1752, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.49791880303383834}}
{"text": "#include <unsupported/Eigen/CXX11/Tensor>\n#include <Eigen/Dense>\n\nusing Eigen::Matrix;\nusing Eigen::Dynamic;\nusing Eigen::Tensor;\nusing Eigen::VectorXcf;\nusing Eigen::Vector3i;\nusing Eigen::Vector3f;\n\n#ifndef GRAVITYSOLVERS_H\n#define GRAVITYSOLVERS_H\n\n/*\n  MatrixData[:,j] = [m, x, y, z, vx, vy, vz, fx, fy, fz]\n*/\n#define MATRIX_DATA_ROWS 10\ntypedef Matrix<float, MATRIX_DATA_ROWS, Dynamic> MatrixData;\n\n#define FIELD_TENSOR_DIMENSIONS 3\ntypedef Tensor<std::complex<float>, FIELD_TENSOR_DIMENSIONS> FieldTensorCF;\ntypedef Tensor<float, FIELD_TENSOR_DIMENSIONS> FieldTensorF;\n\nnamespace Gravitysolver {\n  class DataIO\n  {\n  protected:\n    float epsilon;\n    MatrixData particles;\n  public:\n    DataIO();\n    bool readDataOld(const std::string &filename);\n    bool readData(const std::string &filename);\n    bool writeData(const std::string &filename);\n  };\n\n  class Direct : public DataIO\n  {\n  public:\n    Direct();\n    float softening();\n    void setSoftening(float eps);\n    void solve();\n    const MatrixData &data();\n  };\n\n  class PM : public DataIO\n  {\n  private:\n    int Ng; // number of cells per dimension\n    float h; // cell size\n    float worldLen; // the size of the smallest enclosing cube of the galaxy\n    FieldTensorCF density;\n    FieldTensorCF greenFunction;\n    FieldTensorCF potential;\n    FieldTensorF ax;\n    FieldTensorF ay;\n    FieldTensorF az;\n    Vector3i worldToGrid(float x, float y, float z);\n    Vector3f gridToWorld(int i, int j, int k);\n    void fft3d(FieldTensorCF &t);\n    void ifft3d(FieldTensorCF &t);\n    void conv3d(FieldTensorCF &out, FieldTensorCF &in, FieldTensorCF &kernel);\n  public:\n    PM(int numGridCells);\n    void solve();\n    const MatrixData &data();\n  };\n}\n\n#endif // GRAVITYSOLVERS_H\n", "meta": {"hexsha": "876919469edc033adecbf2308aaf4e6c1271af2c", "size": 1737, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/gravitysolvers.hpp", "max_stars_repo_name": "azurite/AST-245-N-Body", "max_stars_repo_head_hexsha": "cc3e3acd61f62415c1e5f40c8aba5b93703837fa", "max_stars_repo_licenses": ["MIT"], "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/gravitysolvers.hpp", "max_issues_repo_name": "azurite/AST-245-N-Body", "max_issues_repo_head_hexsha": "cc3e3acd61f62415c1e5f40c8aba5b93703837fa", "max_issues_repo_licenses": ["MIT"], "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/gravitysolvers.hpp", "max_forks_repo_name": "azurite/AST-245-N-Body", "max_forks_repo_head_hexsha": "cc3e3acd61f62415c1e5f40c8aba5b93703837fa", "max_forks_repo_licenses": ["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.125, "max_line_length": 78, "alphanum_fraction": 0.7046632124, "num_tokens": 466, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.49791879782417126}}
{"text": "#include <frovedis.hpp>\n#include <frovedis/matrix/blas_wrapper.hpp>\n#include <frovedis/matrix/lapack_wrapper.hpp>\n\n\n#define BOOST_TEST_MODULE FrovedisTest\n#include <boost/test/unit_test.hpp>\n\nusing namespace frovedis;\nusing namespace std;\n\nBOOST_AUTO_TEST_CASE( frovedis_test )\n{\n    int argc = 1;\n    char** argv = NULL;\n    use_frovedis use(argc, argv);\n\n    // creating a colmajor matrix local from file\n    colmajor_matrix_local<float> cm (\n           make_rowmajor_matrix_local_load<float>(\"./sample_3x3\"));\n    auto inv_cm = inv(cm);\n\n    std::vector<int> ipiv; // empty ipiv array\n    getrf<float> (cm,ipiv); // cm will be factorized and ipiv will contain pivoting info\n    getri<float> (cm,ipiv); // cm will be overwritten with inversed matrix\n\n    // checking whether the above operations successfully taken place \n    cm.to_rowmajor().save(\"./out_3x3_1\");\n    inv_cm.to_rowmajor().save(\"./out_3x3_2\");\n    BOOST_CHECK (system(\"diff ./out_3x3_1 ./ref_3x3\") == 0);\n    BOOST_CHECK (system(\"diff ./out_3x3_2 ./ref_3x3\") == 0);\n    system(\"rm -f ./out_3x3_1\");\n    system(\"rm -f ./out_3x3_2\");\n}\n\n", "meta": {"hexsha": "1bd5d1cfc6707bdd378f3ea6e4b9aca4102e4e41", "size": 1103, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/matrix/test7.1-1/test.cc", "max_stars_repo_name": "XpressAI/frovedis", "max_stars_repo_head_hexsha": "bda0f2c688fb832671c5b542dd8df1c9657642ff", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 63.0, "max_stars_repo_stars_event_min_datetime": "2018-06-21T14:11:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T11:24:36.000Z", "max_issues_repo_path": "test/matrix/test7.1-1/test.cc", "max_issues_repo_name": "XpressAI/frovedis", "max_issues_repo_head_hexsha": "bda0f2c688fb832671c5b542dd8df1c9657642ff", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2018-09-22T14:01:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-27T16:11:05.000Z", "max_forks_repo_path": "test/matrix/test7.1-1/test.cc", "max_forks_repo_name": "XpressAI/frovedis", "max_forks_repo_head_hexsha": "bda0f2c688fb832671c5b542dd8df1c9657642ff", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2018-08-23T15:59:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T06:47:22.000Z", "avg_line_length": 30.6388888889, "max_line_length": 88, "alphanum_fraction": 0.69356301, "num_tokens": 331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.49791879782417126}}
{"text": "#include <boost/math/complex/atan.hpp>\n", "meta": {"hexsha": "9b62807ee1ef17283bc4017a53530689626884a0", "size": 39, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_complex_atan.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_complex_atan.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_complex_atan.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 19.5, "max_line_length": 38, "alphanum_fraction": 0.7692307692, "num_tokens": 10, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619091240701, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.49791879261450406}}
{"text": "#include <iostream>\n#include <cfloat>\n\n#include <armadillo>\n\n#include <glm/models/glm_model.hpp>\n#include <glm/models/links/glm_link.hpp>\n#include <glm/irls.hpp>\n#include <dcdflib/libdcdf.hpp>\n\nusing namespace arma;\n\nvoid\nset_missing_to_zero(const uvec &missing, vec &w)\n{   \n    for(int i = 0; i < w.size( ); i++)\n    {\n        if( missing[ i ] == 1 )\n        {\n            w[ i ] = 0.0;\n        }\n    }\n}\n\nvec\nchi_square_cdf(const vec &x, unsigned int df)\n{\n    vec p = ones<vec>( x.n_elem );\n    for(int i = 0; i < x.n_elem; i++)\n    {\n        p[ i ] = chi_square_cdf( x[ i ], df );\n    }\n\n    return p;\n}\n\nvec\nweighted_least_squares(const mat &X, const vec &y, const vec &w, bool fast_inversion)\n{\n    /* A = sqrt( w ) * X */\n    mat A = diagmat( sqrt( w ) ) * X;\n\n    /* ty = sqrt( w ) * y */\n    vec ty = y % sqrt( w );\n\n    vec beta;\n    if( fast_inversion )\n    {\n        if( solve( beta, A, ty, solve_opts::fast + solve_opts::no_approx ) )\n        {\n            return beta;\n        }\n        else\n        {\n            return vec( );\n        }\n    }\n    else\n    {\n        if( solve( beta, A, ty ) )\n        {\n            return beta;\n        }\n        else\n        {\n            return vec( );\n        }\n    }\n}\n\nvec\ncompute_z(const vec &eta, const vec &mu, const vec &mu_eta, const vec &y)\n{\n    return eta + mu_eta % ( y - mu );\n}\n\nvec\ncompute_w(const vec &var, const vec& mu_eta)\n{\n    return 1.0 / ( var % ( mu_eta % mu_eta ) );\n}\n\nvec\ninit_beta(const mat &X, const vec&y, const uvec &missing, const glm_model &model, bool fast_inversion = false)\n{\n    vec eta = model.get_link( ).eta( (y + 0.5) / 3.0 );\n\n    return weighted_least_squares( X, eta, ones<vec>( missing.n_elem ) - missing, fast_inversion );\n}\n\nvec\nirls(const mat &X, const vec &y, const uvec &missing, const glm_model &model, glm_info &output, bool fast_inversion)\n{\n    const glm_link &link = model.get_link( );\n    vec b = init_beta( X, y, missing, model );\n    vec w( X.n_rows );\n    vec z( X.n_rows );\n    vec eta = X * b;\n    vec mu = link.mu( eta );\n\n    vec mu_eta = link.mu_eta( mu );\n\n    int num_iter = 0;\n    double old_logl = -DBL_MAX;\n    double logl = model.likelihood( mu, y, missing );\n    bool invalid_mu = false;\n    bool inverse_fail = false;\n    vec b_old = b;\n    bool first_attempt = true;\n    while( num_iter < IRLS_MAX_ITERS && ! ( fabs( logl - old_logl ) / ( 0.1 + fabs( logl ) ) < IRLS_TOLERANCE ) )\n    {\n        w = compute_w( model.var( mu ), mu_eta );\n        z = compute_z( eta, mu, mu_eta, y );\n        set_missing_to_zero( missing, w );\n        b = weighted_least_squares( X, z, w, fast_inversion );\n        if( b.n_elem <= 0 )\n        {\n            inverse_fail = true;\n            break;\n        }\n\ncompute_eta: \n        eta = X * b;\n        mu = link.mu( eta );\n        mu_eta = link.mu_eta( mu );\n\n        if( !model.valid_mu( mu ) )\n        {\n            if( first_attempt )\n            {\n                /* Try a smaller step */\n                b = 0.5*b_old + 0.5*b;\n                first_attempt = false;\n                goto compute_eta;\n            }\n            else\n            {\n                invalid_mu = true;\n                break;\n            }\n        }\n\n        old_logl = logl;\n        b_old = b;\n        logl = model.likelihood( mu, y, missing );\n\n        num_iter++;\n    }\n\n    if( num_iter < IRLS_MAX_ITERS && !invalid_mu && !inverse_fail )\n    {\n        mat I = X.t( ) * diagmat( w ) * X;\n        mat C;\n        if( I.is_finite( ) && inv( C, I ) )\n        {\n            float dispersion = model.dispersion( mu, y, missing, b.n_elem );\n            output.se_beta = sqrt( model.dispersion( mu, y, missing, dispersion ) * diagvec( C ) );\n            output.num_iters = num_iter;\n            output.converged = true;\n            output.success = true;\n            output.mu = mu;\n            output.logl = model.likelihood( mu, y, missing, dispersion );\n            \n            vec wald_z = b / output.se_beta;\n            vec chi2_value = wald_z % wald_z;\n            output.p_value = -1.0 * ones<vec>( chi2_value.n_elem );\n            for(int i = 0; i < chi2_value.n_elem; i++)\n            {\n                try\n                {\n                    output.p_value[ i ] = 1.0 - chi_square_cdf( chi2_value[ i ], 1 );\n                }\n                catch(bad_domain_value &e)\n                {\n                    continue;\n                }\n            }\n        }\n        else\n        {\n            output.success = false;\n        }\n    }\n    else\n    {   \n        output.num_iters = num_iter;\n        output.converged = false;\n        output.success = false;\n    }\n\n    return b;\n}\n\nvec\nirls(const mat &X, const vec &y, const glm_model &model, glm_info &output, bool fast_inversion)\n{\n    uvec missing = zeros<uvec>( y.n_elem );\n    return irls( X, y, missing, model, output );\n}\n", "meta": {"hexsha": "9a65d08074b09d26d237fea5b653bd1c67b632da", "size": 4822, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/glm/irls.cpp", "max_stars_repo_name": "hoehleatsu/besiq", "max_stars_repo_head_hexsha": "94959e2819251805e19311ce377919e6bccb7bf9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-10-21T14:22:12.000Z", "max_stars_repo_stars_event_max_datetime": "2015-10-21T14:22:12.000Z", "max_issues_repo_path": "libs/glm/irls.cpp", "max_issues_repo_name": "hoehleatsu/besiq", "max_issues_repo_head_hexsha": "94959e2819251805e19311ce377919e6bccb7bf9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-05-26T20:52:31.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-28T16:19:49.000Z", "max_forks_repo_path": "libs/glm/irls.cpp", "max_forks_repo_name": "hoehleatsu/besiq", "max_forks_repo_head_hexsha": "94959e2819251805e19311ce377919e6bccb7bf9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2016-11-06T14:58:37.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-26T14:03:13.000Z", "avg_line_length": 24.11, "max_line_length": 116, "alphanum_fraction": 0.4981335545, "num_tokens": 1347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619091240701, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.49791879261450406}}
{"text": "#include <cstdio>\n#include <iterator>\n#include <iostream>\n#include <iomanip>\n#include <algorithm>\n#include <vector>\n\n#include <boost/timer.hpp>\n#include <boost/lexical_cast.hpp>\n\n#include <CGAL/Simple_cartesian.h>\n#include <CGAL/point_generators_2.h>\n#include <CGAL/compiler_config.h>\n\n\n\nint format_output(const char* lib, const char* generator, int n, float time) {\n  return std::printf(\"| %s || %s || %d || %.4fM items/sec\\n\", lib, generator, n, time);\n}\n\ntypedef CGAL::Simple_cartesian<double>         R;\ntypedef R::Point_2                             Point;\ntypedef CGAL::Creator_uniform_2<double,Point>  Creator;\ntypedef std::vector<Point>                     Vector;\n\nint main(int argc, char* argv[]) {\n  int n = 10000000;\n  int repeats = 10;\n\n  if(argc > 1)\n    n = boost::lexical_cast<int>(argv[1]);\n\n  if(argc > 2)\n    repeats = boost::lexical_cast<int>(argv[2]);\n\n  Vector points(n, Point());\n\n  CGAL::Random_points_in_disc_2<Point,Creator> g( 1000.0);\n  boost::timer timer;\n  const char* generator = \"Random_points_in_disc_2\";\n  float time;\n\n  std::cout << \n    \"{| \\n\"\n    \"! Library !! Generator !! #Elements !! items/sec \\n\"\n    \"|- \\n\";\n  \n  timer.restart();\n  for (int i = 0; i < repeats; ++i) { CGAL::copy_n( g, n, points.begin()); }\n  time = (double)n*repeats/timer.elapsed()/1.0E6;\n  format_output(\"CGAL\", generator , n, time);\n  std::cout << \"|- \\n\";\n  \n#ifndef CGAL_CFG_NO_CPP0X_COPY_N\n  timer.restart();\n  for (int i = 0; i < repeats; ++i) { std::copy_n( g, n, points.begin()); }\n  time = (double)n*repeats/timer.elapsed()/1.0E6;\n  format_output(\"stdlib\", generator, n, time);\n#endif\n\n  //wiki markup footer\n  std::cout << \"|}\" << std::endl;\n}\n", "meta": {"hexsha": "7c6a298ee2a4c43bd9bf316764d7662e8ee99286", "size": 1666, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "graphics/cgal/STL_Extension/benchmark/copy_n_benchmark/copy_n_use_case_benchmark.cpp", "max_stars_repo_name": "hlzz/dotfiles", "max_stars_repo_head_hexsha": "0591f71230c919c827ba569099eb3b75897e163e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-03-30T14:31:52.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-02T05:01:32.000Z", "max_issues_repo_path": "graphics/cgal/STL_Extension/benchmark/copy_n_benchmark/copy_n_use_case_benchmark.cpp", "max_issues_repo_name": "hlzz/dotfiles", "max_issues_repo_head_hexsha": "0591f71230c919c827ba569099eb3b75897e163e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "graphics/cgal/STL_Extension/benchmark/copy_n_benchmark/copy_n_use_case_benchmark.cpp", "max_forks_repo_name": "hlzz/dotfiles", "max_forks_repo_head_hexsha": "0591f71230c919c827ba569099eb3b75897e163e", "max_forks_repo_licenses": ["BSD-3-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.03125, "max_line_length": 87, "alphanum_fraction": 0.6284513806, "num_tokens": 493, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.6959583376458152, "lm_q1q2_score": 0.4979052948173927}}
{"text": "/**\n * @file IndexGraph.hpp\n * @author bwu\n * @brief Model of index graph concept and graph related algorithms\n * @version 0.1\n * @date 2022-02-22\n */\n#ifndef GENERIC_TOPOLOGY_INDEXGRAPH_HPP\n#define GENERIC_TOPOLOGY_INDEXGRAPH_HPP\n#include \"generic/common/Exception.hpp\"\n#include \"generic/common/Archive.hpp\"\n#include \"Common.hpp\"\n#include <boost/graph/connected_components.hpp>\n#include <boost/graph/breadth_first_search.hpp>\n#include <boost/graph/topological_sort.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/functional/hash.hpp>\n#include <boost/graph/graphviz.hpp>\n#include <boost/graph/visitors.hpp>\n#include <unordered_set>\n\nnamespace generic  {\nnamespace topology {\n\n///@brief represents model of undirected index edge concept\nstruct UndirectedIndexEdge\n{\n    ///@brief constructs an invalid edge\n    UndirectedIndexEdge()\n    {\n        m_vertices = std::make_pair(noIndex, noIndex);\n    }\n\n    ///@brief constructs an undirected edge with vertex `iv1` and `iv2`\n    UndirectedIndexEdge(index_t iv1, index_t iv2)\n    {\n       SetVertices(iv1, iv2);\n    }\n\n    ///@brief checks if this edge equals to `e`\n    bool operator==(const UndirectedIndexEdge & e) const { return m_vertices == e.m_vertices; }\n    ///@brief checks if this edge not equals to `e`\n    bool operator!=(const UndirectedIndexEdge & e) const { return !(*this == e); }\n\n    ///@brief set two vertices index of this edges\n    void SetVertices(index_t iv1, index_t iv2) { m_vertices.first = std::min(iv1, iv2); m_vertices.second = std::max(iv1, iv2); }\n\n    ///@brief returns the smaller vertex index of this edge\n    index_t v1() const { return m_vertices.first ; }\n    ///@brief returns the bigger vertex index of this edge\n    index_t v2() const { return m_vertices.second; }\n\n    ///@brief chechks if this edge contains vertex `iv`\n    bool hasVertex(index_t iv) const { return iv == m_vertices.first || iv == m_vertices.second; }\n\nprivate:\n    std::pair<index_t, index_t> m_vertices;\n\n#ifdef BOOST_SERIALIZATION_SUPPORT\nprivate:\n    friend class boost::serialization::access;\n    template <typename Archive>\n    void serialize(Archive & ar, const unsigned int)\n    {\n        ar & m_vertices;\n    }\n#endif\n};\n\nstruct UndirectedIndexEdgeHash\n{\n    size_t operator() (const UndirectedIndexEdge & edge) const noexcept\n    {\n        size_t seed(0);\n        boost::hash_combine(seed, edge.v1());\n        boost::hash_combine(seed, edge.v2());\n        return seed;\n    }\n};\n\nstruct UndirectedIndexEdgeCompare\n{\n    bool operator() (const UndirectedIndexEdge & e1, const UndirectedIndexEdge & e2) const noexcept { return e1 == e2; }\n};\n\nusing UndirectedIndexEdgeSet = std::unordered_set<UndirectedIndexEdge, UndirectedIndexEdgeHash, UndirectedIndexEdgeCompare>;\n\ntemplate <typename T>\nusing UndirectedIndexEdgeMap = std::unordered_map<UndirectedIndexEdge, T, UndirectedIndexEdgeHash, UndirectedIndexEdgeCompare>;\n\n///@brief represents model of sparse undirect index graph concept\nusing SparseIndexGraph = boost::adjacency_list<\n                         boost::setS,\n                         boost::vecS,\n                         boost::undirectedS,\n                         boost::property<boost::vertex_index_t, index_t >\n                         >;\n\nusing SIGEdge = boost::graph_traits<SparseIndexGraph>::edge_descriptor; \nusing SIGEdgeIter = boost::graph_traits<SparseIndexGraph>::edge_iterator;\nusing SIGVertex = boost::graph_traits<SparseIndexGraph>::vertex_descriptor;\n\ninline void AddEdge(index_t i, index_t j, SparseIndexGraph & g)\n{\n    boost::add_edge(i, j, g);\n}\n\ninline std::pair<SIGEdgeIter, SIGEdgeIter> Edges(const SparseIndexGraph & g)\n{\n    return boost::edges(g);\n}\n\ninline SIGVertex Source(const SIGEdge & e, const SparseIndexGraph & g)\n{\n    return boost::source(e, g);\n}\n\ninline SIGVertex Target(const SIGEdge & e, const SparseIndexGraph & g)\n{\n    return boost::target(e, g);\n}\n\n/**\n * @brief gets connected component by BFS\n * \n * @param[in] g the connection graph\n * @param[in] v the source vertex\n * @param[out] c contains the vertices connected to source v\n */\ninline void ConnectedComponent(const SparseIndexGraph & g, const index_t v, std::list<index_t> & c)\n{\n    using namespace boost;\n    GENERIC_ASSERT(v < num_vertices(g))\n\n    class BFSVisitor : public default_bfs_visitor\n    {\n    public:\n        std::list<index_t> & visited;\n        BFSVisitor(std::list<index_t> & _visited) : visited(_visited) {}\n        void discover_vertex(index_t s, const SparseIndexGraph &) { visited.push_back(s); }\n    };\n\n    c.clear();\n    BFSVisitor vis(c);\n    breadth_first_search(g, v, visitor(vis));\n}\n\n/**\n * @brief gets all connected components from graph\n * \n * @param[in] g the connection graph\n * @param[out] cc connected components\n */\ninline void ConnectedComponents(const SparseIndexGraph & g, std::vector<std::list<index_t> > & cc)\n{\n    using namespace boost;\n    std::vector<index_t> c(num_vertices(g));\n    auto numComp = connected_components(g, make_iterator_property_map(c.begin(), get(vertex_index, g)));\n\n    cc.clear();\n    cc.resize(numComp);\n    for(size_t i = 0; i < c.size(); ++i)\n        cc[c[i]].push_back(i);\n}\n\ninline UndirectedIndexEdgeSet EdgeSet(const SparseIndexGraph & g)\n{\n    UndirectedIndexEdgeSet edgeSet;\n    auto [begin, end] = topology::Edges(g);\n    for(auto iter = begin; iter != end; ++iter){\n        auto u = topology::Source(*iter, g);\n        auto v = topology::Target(*iter, g);\n        edgeSet.insert(UndirectedIndexEdge{u, v});\n    }\n    return edgeSet;\n}\n\n}//namespace topology\n}//namespace generic\n#endif//GENERIC_TOPOLOGY_INDEXGRAPH_HPP", "meta": {"hexsha": "b5d28f83b5cb17f43a5305c21db7499ef262521e", "size": 5629, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "topology/IndexGraph.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": "topology/IndexGraph.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": "topology/IndexGraph.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": 31.0994475138, "max_line_length": 129, "alphanum_fraction": 0.6931959495, "num_tokens": 1383, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583376458152, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.49790529059464506}}
{"text": "/*\n * util.hh\n *\n *  Created on: May 3, 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\n//In this file we implement some of the utility functions necessary for\n//the classes WorkModel, ErrorEstimate and the main integrate function of the class EulerSDC.\n\n#ifndef KASKADE_TIMESTEPPING_EULERSDC_UTIL_HH_\n#define KASKADE_TIMESTEPPING_EULERSDC_UTIL_HH_\n\n#include \"norm.hh\"\n\n#include <cmath>          //std::abs\n#include <functional>     //std::function\n#include <vector>\n\n#include <boost/timer/timer.hpp>\n\n#include \"dune/common/dynmatrix.hh\"\n#include \"dune/common/dynvector.hh\"\n\n#include \"fem/fixdune.hh\"\n#include \"timestepping/sdc.hh\"\n\nnamespace Kaskade {\n  /**\n   * \\ingroup eulerSDC\n   * \\brief Some utility functions.\n   */\n//=================================================================================================\n//  Utility function to find norm of a difference of vector of two Vectors\n//=================================================================================================\n\n/**\n * \\ingroup eulerSDC\n * \\brief Function to compute the norm of the difference of two vector of Vectors.\n *\n * @param y0  : A vector of Vectors, usually of type std::vector<Vector>\n * @param y1  : A vector of Vectors, usually of type std::vector<Vector>\n * @param norm  : A type of norm, in this case an object of type Kaskade::Norm\n * @return An object of type Vector::value_type is returned, it is usually a double.\n */\ntemplate<class Vector, class Norm>\ntypename Vector::value_type normVecDiff(std::vector<Vector> const& y0, std::vector<Vector> const& y1, Norm norm);\n\n\n//=================================================================================================\n//  Implementation for single sdc iteration step based on explicit Euler method.\n//=================================================================================================\n /**\n  * \\ingroup eulerSDC\n  * This function performs one spectral defect correction (SDC) iteration for a system of ODE's of the form:\n  * \\f$ y'(t) = f(y(t)) \\f$, \\f$ y(0) = y_0\\f$ and \\f$ t \\in [0, T] \\f$,\n  * using the explicit Euler method on a given time grid. Here SDC is interpreted as fixed point iteration.\n  * Given an approximate solution \\f$ y^{[j]} \\in \\mathbb{P}_N \\f$, the error function\n  * \\f[ \\delta^{[j]} = y - y^{[j]} \\f]\n  * satisfies the defect equation\n  * \\f[ \\delta^{[j]'}(t) = y'(t) - y^{[j]'}(t) = f(y(t)) - y^{[j]'}(t). \\f]\n  * The equivalent Picard equation is\n  * \\f[ \\delta^{[j]}(t) = \\int_{\\tau=0}^t \\left( f(y^{[j]}(\\tau)+\\delta^{[j]}(\\tau)) - y^{[j]'}(\\tau) \\,d\\tau\\right)\\f]\n  * Evaluated at the grid nodes \\f$ t_i\\f$ we obtain\n  * \\f{eqnarray*}{\n  * \\delta^{[j]}_i & = & \\delta^{[j]}_{i-1} + \\int_{\\tau=t_{i-1}}^{t_i} \\left( f(y^{[j]}(\\tau)+\\delta^{[j]}(\\tau)) - {y^{[j]}}'(\\tau) \\right) \\,d\\tau \\\\\n  *                & = & \\delta^{[j]}_{i-1} + \\int_{\\tau=t_{i-1}}^{t_i} \\left( f(y^{[j]}(\\tau)+\\delta^{[j]}(\\tau)) - f(y^{[j]}(\\tau))\\right) \\,d\\tau\n  *               + \\int_{\\tau=t_{i-1}}^{t_i} \\hspace{-0.5em}f(y^{[j]}(\\tau)) \\,d\\tau - ( y^{[j]}_i-y^{[j]}_{i-1})\n  * \\f}\n  * starting at \\f$ \\delta_0^{[j]} = 0. \\f$ Using left looking rectangular rule for approximating the first integral, and the canonical quadrature by\n  * polynomial interpolation on the nodes \\f$ t_1,\\ldots t_N \\f$ for second integral, approximate values \\f$ \\hat{\\delta}_i^{[j]} \\f$ for\n  * \\f$ \\delta_i^{[j]} \\f$ can be evaluated. With the left looking rectangular rule, we obtain the explicit scheme\n  * \\f{eqnarray*}{\n  *  \\hat\\delta^{[j]}_i & = &  \\hat\\delta^{[j]}_{i-1}\n  * + (t_i-t_{i-1}) \\left( f(y^{[j]}_{i-1}+\\hat{\\delta}^{[j]}_{i-1}) - f(y^{[j]}_{i-1})\\right)\n  * +  \\sum_{k=1}^N S_{ik} f(y^{[j]}_k) - y^{[j]}_i+y^{[j]}_{i-1},\n  * \\f}\n  * where the entries of the spectral quadrature matrix \\f$ S \\in \\mathbb{R}^{N \\times N} \\f$ are defined in terms of the Lagrange polynomials\n  * \\f$ L_k \\in \\mathbb{P}_N \\f$ satisfying \\f$ L_k(t_i) = \\delta_{ik} \\f$ as\n  * \\f{eqnarray*}{\n  *   S_{ik} & = & \\int_{\\tau=t_{i-1}}^{t_i} L_k(\\tau) \\,d\\tau, \\quad i,k =1,\\dots, N.\n  * \\f}\n  * An improved approximation \\f$ y^{[j+1]} \\f$ is then obtained by polynomial interpolation of \\f$ \\hat \\delta^{[j]}_i \\f$,\n  * \\f{eqnarray*}{\n  * y^{[j+1]} = y^{[j]} + \\hat\\delta^{[j]}.\n  * \\f}\n  *\n  *\\tparam Vector  a vector type, usually Dune::DenseVector.\n  *\n  * \\param[in] grid the collocation time grid\n  * \\param[in] rhsFunc is the function which represents the right hand side \\f$ f \\f$ and is used in the computation of \\f$ \\delta y \\f$.\n  * \\param[out] yi stores the current iterate of the solution \\f$ y \\f$.\n  * \\param[out] dyi is the approximate correction \\f$ \\delta y \\f$\n  * \\param[in] verbose a boolean used to print out the iterates of \\f$ y \\f$.\n  *\n  */\n\n  template<class Vector>\n  void sdcExplicitEulerIterationStep(Kaskade::SDCTimeGrid const& grid,\n                                     std::function<Vector(typename Vector::value_type, Vector const&)> rhsFunc,\n                                     std::vector<Vector> & yi, std::vector<Vector> & dyi,\n                                     bool verbose = false)\n  {\n    //extract time points from the grid\n    auto const& pts = grid.points();\n    //extracting values of the integration matrix corresponding to the time grid.\n    auto const& integ = grid.integrationMatrix();\n    //number of intervals\n    int const n = pts.size() - 1;\n\n    //including starting point for yi and dyi\n    assert(yi.size() == n+1);\n    assert(dyi.size() == n+1);\n\n    //initialize all elements of dyi to zero.\n    for (int i = 0; i <= n; ++i)\n    {\n      dyi[i] = Vector(0.0);\n    }\n\n    //declare Vector total to be used inside the for loop\n    Vector total(0.0);\n\n    //the SDC step for explicit Euler\n    //perform n Euler steps\n    boost::timer::cpu_timer timer;\n    for (auto i = 1; i <= n; ++i)\n    {\n      //Initialize all the entries of total to zero\n      total = Vector(0.0);\n      //computation of the Lagrange interpolation\n      for (int k = 0; k <= n; ++k)\n      {\n        total += integ[i-1][k] * rhsFunc(pts[k], yi[k]);\n      }\n      //approximate correction computation\n      dyi[i] = dyi[i-1] + (pts[i] - pts[i-1]) *(rhsFunc(pts[i-1],yi[i-1]+dyi[i-1]) - rhsFunc(pts[i-1],yi[i-1])) + total - yi[i] + yi[i-1];\n    }\n\n    //Compute the next iteration of yi.\n    for (auto i = 0; i <= n; ++i)\n    {\n      yi[i] += dyi[i];\n      if (verbose)\n        std::cout << \"yi[\" << i << \"] = \" << yi[i] << \"\\n\";\n    }\n\n  }\n\n  //=================================================================================================\n   //  Implementation for single inexact sdc iteration step based on explicit Euler method.\n   //=================================================================================================\n\n\n   template<class Vector, class RealVector>\n   void inexactSDCExplicitEulerIterationStep(Kaskade::SDCTimeGrid const& grid,\n                                             std::function<Vector(typename Vector::value_type, Vector const&)> rhsFunc,\n                                             RealVector const& toleranceVector, typename Vector::value_type rho,\n                                             Kaskade::NormType norm_t,\n                                             std::vector<Vector> & yi, std::vector<Vector> & dyi,\n                                             bool verbose = false)\n     {\n       //extract time points from the grid\n       auto const& tpts = grid.points();\n       //extracting values of the integration matrix corresponding to the time grid.\n       auto const& integ = grid.integrationMatrix();\n       //number of intervals\n       unsigned int const n = tpts.size() - 1;\n\n       //including starting point for yi and dyi\n       assert(yi.size() == n+1);\n       assert(dyi.size() == n+1);\n\n       //initialize all elements of dyi to zero.\n       for (auto i = 0u; i <= n; ++i)\n       {\n         dyi[i] = Vector(0.0);\n       }\n\n       //declare Vector total to be used inside the for loop\n       Vector total(0.0);\n\n       //convert the toleranceVector which is a vector of doubles to a vector of Vectors.\n       std::vector<Vector> errVector(n+1, Vector(0.0));\n       //depending on the normType fill in err vector. This step is taken since the tolerance vector is a vector of scalars\n       switch(norm_t)\n       {\n       case Kaskade::NormType::ONE_NORM:\n       {\n         auto sz = dyi[0].size();\n         for (auto i = 1u; i <= n; ++i)\n           errVector[i] = Vector(toleranceVector[i]/sz);\n         break;\n       }\n       case Kaskade::NormType::MAX_NORM:\n       {\n         for (auto i = 1u; i <= n; ++i)\n           errVector[i] = Vector(toleranceVector[i]);\n         break;\n        }\n       }\n\n       //the perturbed SDC step for explicit Euler\n       //perform n Euler steps\n       boost::timer::cpu_timer timer;\n       for (auto i = 1u; i <= n; ++i)\n       {\n         //Initialize all the entries of total to zero\n         total = Vector(0.0);\n\n         //computation of the Lagrange interpolation\n         for (auto k = 0u; k <= n; ++k)\n         {\n           total += integ[i-1][k] * (rhsFunc(tpts[k], yi[k]) + errVector[k]);\n         }\n         //approximate correction computation\n         dyi[i] = dyi[i-1] + (tpts[i] - tpts[i-1]) *((rhsFunc(tpts[i-1],yi[i-1]+dyi[i-1]) - rhsFunc(tpts[i-1],yi[i-1]))- (1 - rho)*errVector[i-1]) + total - yi[i] + yi[i-1];\n       }\n\n       //Compute the next iteration of yi.\n       for (auto i = 0u; i <= n; ++i)\n       {\n         yi[i] += dyi[i];\n         if (verbose)\n           std::cout << \"yi[\" << i << \"] = \" << yi[i] << \"\\n\";\n       }\n     }\n\n\n  //===================================================================================================\n  //   Implementation of the abstract base class SDCUtil for all utility methods depending on the norms.\n  //===================================================================================================\n\n  template <class Vector, class Norm>\n  class SDCUtil\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    //virtual function\n    /**\n     * \\ingroup eulerSDC\n     * This function computes an estimate of the SDC contraction factor (\\f$ \\rho \\f$) given three consecutive iterations of \\f$ y \\f$ and\n     * depends on the given norm.\n     * The estimate of \\f$ \\rho \\f$ is given by:\n     * \\f{eqnarray*}{\n     *  \\rho & = & \\frac{\\|y^{[j+1]} - y^{[j]}\\|}{\\|y^{[j]} - y^{[j-1]}\\| + \\|y^{[j+1]} - y^{[j]}\\|}\n     * \\f}\n     *\n     * \\param[in] yPrev a Vector denoting previous iterate of \\f$ y \\f$.\n     * \\param[in] yCurrent a Vector denoting current iterate of \\f$ y \\f$.\n     * \\param[in] yNext a Vector denoting next iterate of \\f$ y \\f$   as obtained from SDC iteration step.\n     * \\param[in] norm an object of abstract base class type Norm, where we can provide the specific norm we consider for a problem.\n     *\n     * \\return \\f$ \\rho \\f$ an estimate of the SDC contraction factor. Return type is Vector::field_type\n     */\n    field_type sdcContractionFactor(std::vector<Vector> const& yPrev,\n                                    std::vector<Vector> const& yCurrent,\n                                    std::vector<Vector> const& yNext,\n                                    Norm& norm);\n\n    //pure virtual functions\n    /**\n     * \\ingroup eulerSDC\n     * The function definition changes with the associated norm. For derivation details for the vectors \\f$ \\alpha \\f$\n     * and \\f$ \\Gamma \\f$ see M. Weiser, S. Ghosh: Adaptive inexact SDC Methods.\n     * The vector \\f$ \\alpha \\f$ is given by \\f$  \\alpha = \\{\\alpha_1, \\ldots , \\alpha_N \\}\\f$, where\n     * \\f{eqnarray*}{\n     * \\alpha_i & = & \\sum_{k=1}^N |S_{ki}| + (1 - \\delta_{i,N})\\,(t_{i+1} - t_i)\\,(1 + \\rho),\n     * \\f}\n     * this is computed in case of \\f$ 1\\f$-norm and in the case of \\f$ \\max\\f$-norm we have\n     * \\f$ \\Gamma = \\{\\Gamma_1, \\ldots, \\Gamma_N \\} \\f$, where\n     *  \\f{eqnarray*}{\n     *    \\Gamma_i & = & \\max_{1\\leq n \\leq N} \\alpha_{n,i}, \\textrm{ such that } \\\\\n     *    \\alpha_{n,i} & = & |S_{ni}| + \\delta_{i,n-1}\\,(t_i - t_{i-1})\\,(1+\\rho)\n     *  \\f}\n     * @param[in] timePoints : Time points generated using the points() method of SDCTimeGrid.\n     * @param[in] integrationMatrix : Integration matrix generated using the integrationMatrix() method of SDCTimeGrid.\n     *                            Computed once for a given time grid.\n     * @param[in] yPrev : Estimate of exact solution \\f$ y \\f$ using SDC iteration step\n     * @param[in] yCurrent : The following estimate of \\f$ y \\f$ using SDC iteration step\n     * @param[in] yNext : The next estimate of \\f$ y \\f$ after yCurrent using SDC iteration step\n     *\n     * \\return Reference to a Vector, where the vector is \\f$ \\alpha \\f$ or \\f$ \\Gamma \\f$ depending on the norm.\n     */\n\n    virtual RealVector const& computeAlphaVec(RealVector const& timePoints,\n                                              RealMatrix const& integrationMatrix,\n                                              std::vector<Vector> const& yPrev,\n                                              std::vector<Vector> const& yCurrent,\n                                              std::vector<Vector> const& yNext) = 0;\n\n\n    //virtual destructor\n    virtual ~SDCUtil(){}\n  };\n\n  //===================================================================================================\n  //   Implementation of the derived class SDCUtilOneNorm w.r.t. 1-norm.\n  //===================================================================================================\n  template<class Vector, class Norm>\n  class SDCUtilOneNorm : public SDCUtil<Vector, Norm>\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     * @param timePts : Represents a vector of time points\n     * @param integrationMatrix\n     * @param yPrev\n     * @param yCurrent\n     * @param yNext\n     * @return\n     */\n\n    virtual RealVector const& computeAlphaVec(RealVector const& timePts,\n                                              RealMatrix const& integrationMatrix,\n                                              std::vector<Vector> const& yPrev,\n                                              std::vector<Vector> const& yCurrent,\n                                              std::vector<Vector> const& yNext)\n    {\n      //number of collocation points\n      auto nCollocationPts = timePts.size();\n      alphaVec = RealVector(nCollocationPts-1, 0.0);\n\n      //create one norm object\n      Kaskade::OneNorm<Vector> on;\n      //compute sdc contraction rate\n      auto rho = Kaskade::SDCUtil<Vector, Norm>::sdcContractionFactor(yPrev, yCurrent, yNext, on);\n      for (auto i = 0u; i < nCollocationPts-1; ++i)\n      {\n        field_type total = 0.0;\n        for (auto k = 0u; k < nCollocationPts-1; ++k)\n          total += std::abs(integrationMatrix[k][i]);\n        if (i != nCollocationPts-2)\n          alphaVec[i] = (total + (timePts[i+1] - timePts[i]) * (1 + rho));\n        else\n          alphaVec[i] = total;\n      }\n      return alphaVec;\n    }\n\n\n    virtual ~SDCUtilOneNorm(){}\n\n  private:\n    RealVector alphaVec;\n    RealMatrix alphaMat;\n  };\n\n  //===================================================================================================\n  //   Implementation of the derived class SDCUtilMaxNorm w.r.t. max-norm.\n  //===================================================================================================\n  template<class Vector, class Norm>\n    class SDCUtilMaxNorm : public SDCUtil<Vector, Norm>\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      //TODO: Doc me\n      /**\n       *\n       * @param timePts\n       * @param integrationMatrix\n       * @param yPrev\n       * @param yCurrent\n       * @param yNext\n       * @return\n       */\n      virtual RealVector const& computeAlphaVec(RealVector const& timePts,\n                                                RealMatrix const& integrationMatrix,\n                                                std::vector<Vector> const& yPrev,\n                                                std::vector<Vector> const& yCurrent,\n                                                std::vector<Vector> const& yNext)\n      {\n        //number of collocation points.\n        auto nCollocationPts = timePts.size();\n        gamma = RealVector(nCollocationPts, 0.0);\n\n        //initialize the matrix alpha with size (nCollocationPts - 1) x nCollocationPts\n        auto alphaMat = computeAlphaMat(timePts, integrationMatrix, yPrev, yCurrent, yNext, nCollocationPts);\n        //Compute the vector Gamma.\n        for (int i = 0; i < nCollocationPts -1; ++i)\n        {\n          for (int j = 0; j < nCollocationPts; ++j)\n          {\n            if (alphaMat[i][j] > gamma[j])\n              gamma[j] = alphaMat[i][j];\n          }\n        }\n        return gamma;\n       }\n\n\n\n      virtual ~SDCUtilMaxNorm() {};\n    private:\n      RealVector gamma;\n      RealMatrix alphaMat;\n\n      /**\n       *\n       * @param timePts\n       * @param integrationMatrix\n       * @param yPrev\n       * @param yCurrent\n       * @param yNext\n       * @param nCollocationPts\n       * @return\n       */\n      RealMatrix const& computeAlphaMat(RealVector const& timePts,\n                                        RealMatrix const& integrationMatrix,\n                                        std::vector<Vector> const& yPrev,\n                                        std::vector<Vector> const& yCurrent,\n                                        std::vector<Vector> const& yNext,\n                                        int nCollocationPts);\n\n\n    };\n\n\n  //=================================================================================================\n  //   FUNCTION DEFINITION BEGINS FROM HERE\n  //=================================================================================================\n\n  //=================================================================================================\n  //  Utility function to find norm of a difference of vector of two Vectors\n  //=================================================================================================\n\n  template<class Vector, class Norm>\n  typename Vector::value_type normVecDiff(std::vector<Vector> const& y0, std::vector<Vector> const& y1, Norm norm)\n   {\n     //Initialize the all the entries of dy to 0.0\n     std::vector<Vector> dy(y0.size(), Vector(0.0));\n     for (auto i = 0u; i < y0.size(); ++i)\n     {\n       dy[i] = y1[i] - y0[i];\n     }\n     return norm.value(dy);\n   }\n\n  //===================================================================================================\n  //   Implementation of the abstract base class SDCUtil for all utility methods depending on the norms.\n  //===================================================================================================\n\n  template <class Vector, class Norm>\n  typename Vector::value_type SDCUtil<Vector, Norm>::sdcContractionFactor(std::vector<Vector> const& yPrev,\n                                                                          std::vector<Vector> const& yCurrent,\n                                                                          std::vector<Vector> const& yNext,\n                                                                          Norm& norm)\n   {\n    size_t n = yPrev.size();\n    //Compute the differences: yPrev - yCurrent and yCurrent - yNext\n    std::vector<Vector> y01(n, Vector(0.0));\n    std::vector<Vector> y12(n, Vector(0.0));\n    for (auto i = 0u; i < n; ++i)\n    {\n      y01[i] = yCurrent[i] - yPrev[i] ;\n      y12[i] = yNext[i] - yCurrent[i];\n    }\n    auto val01 = norm.value(y01);\n    auto val12 = norm.value(y12);\n    auto beta = val12/(val01 + val12);\n    auto val = val12/val01;\n    if (val > 1 || val != val) //check if val > 1 or val is NaN.\n    {\n      if (beta != beta) //check if beta = NaN\n        val = 0.70;\n      else\n        val = beta;\n    }\n    return val;\n   }\n\n\n  //===================================================================================================\n  //   Implementation of the private method computeAlphaMat for the derived class SDCUtilMaxNorm\n  //===================================================================================================\n  using RealVector = Dune::DynamicVector<double>;\n  using RealMatrix = Dune::DynamicMatrix<double>;\n\n  template<class Vector, class Norm>\n  RealMatrix const& SDCUtilMaxNorm<Vector, Norm>::computeAlphaMat(RealVector const& timePts,\n                                                                  RealMatrix const& integrationMatrix,\n                                                                  std::vector<Vector> const& yPrev,\n                                                                  std::vector<Vector> const& yCurrent,\n                                                                  std::vector<Vector> const& yNext,\n                                                                  int nCollocationPts)\n    {\n    //create max norm object\n    Kaskade::MaxNorm<Vector> mn;\n    //compute sdc contraction rate\n    auto rho = Kaskade::SDCUtil<Vector, Norm>::sdcContractionFactor(yPrev, yCurrent, yNext, mn);\n    alphaMat = RealMatrix(nCollocationPts-1, nCollocationPts, 0.0);\n    for (auto i = 0; i < nCollocationPts-1; ++i)\n    {\n      for (auto k = 0; k < nCollocationPts; ++k)\n      {\n        if (i == k)\n          alphaMat[i][k] = std::abs(integrationMatrix[i][k]) + (timePts[i+1] - timePts[i]) * (1 + rho);\n        else\n          alphaMat[i][k] = std::abs(integrationMatrix[i][k]);\n      }\n    }\n    return alphaMat;\n    }\n\n\n}//end namespace Kaskade\n\n\n\n\n#endif /* KASKADE_TIMESTEPPING_EULERSDC_UTIL_HH_ */\n", "meta": {"hexsha": "c539733e0e99e5fc9e899fa71bf13e1061faabfb", "size": 22743, "ext": "hh", "lang": "C++", "max_stars_repo_path": "Kaskade/timestepping/eulerSDC/util.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/util.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/util.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.5898876404, "max_line_length": 173, "alphanum_fraction": 0.4932946401, "num_tokens": 5821, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.49790529030579933}}
{"text": "#include <cstdlib>\n#include <cmath>\n#include <iostream>\n#include <random>\n\n#include \"mkl.h\"\n\n#include <boost/timer.hpp>\n\n#include \"level0.hpp\"\n#include \"level1.hpp\"\n#include \"solver.hpp\"\n#include \"make_csr.hpp\"\n#include \"matrix.hpp\"\n\nint main(int argc, char **argv) {\n  auto spm = math::make_csr();\n  int m;\n  std::cin >> m;\n  math::Vector vec(m);\n  for (int i = 0; i < m; ++i) {\n    std::cin >> vec[i];\n  }\n  std::cerr << \"start\" << std::endl;\n  std::cerr << spm.row_size << ',' << spm.col_size << ',' << spm.elems.size() << std::endl;\n  boost::timer t;\n  math::Vector res = math::CGLSMethod(spm, vec);\n  math::Vector diff = spm * res - vec;\n  std::cerr << \"time: \" << t.elapsed() << std::endl;\n  for (math::Real val : res) {\n    std::printf(\"%f\\n\", val);\n  }\n  double error = math::abs(diff);\n  std::cerr << \"error: \" << error << std::endl;\n  std::cerr << \"standard deviation: \" << (error/std::sqrt(spm.row_size)) << std::endl;\n  std::cerr << \"average absolute prediction error: \" << math::average(diff) << std::endl;\n  return 0;\n}\n", "meta": {"hexsha": "7f7ddfb534ca7fdd6b2a48974da8e2c3a931c0c2", "size": 1034, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "primenumber/LSmethod", "max_stars_repo_head_hexsha": "3f0f2ac216ce16f0cbb22a4ea8d86befddb4b773", "max_stars_repo_licenses": ["MIT"], "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": "primenumber/LSmethod", "max_issues_repo_head_hexsha": "3f0f2ac216ce16f0cbb22a4ea8d86befddb4b773", "max_issues_repo_licenses": ["MIT"], "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": "primenumber/LSmethod", "max_forks_repo_head_hexsha": "3f0f2ac216ce16f0cbb22a4ea8d86befddb4b773", "max_forks_repo_licenses": ["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.5128205128, "max_line_length": 91, "alphanum_fraction": 0.5909090909, "num_tokens": 324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181874, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.49788120302544087}}
{"text": "#ifndef MMTBX_GEOMETRY_INDEXING_H\n#define MMTBX_GEOMETRY_INDEXING_H\n\n#include <mmtbx/geometry/flattening.hpp>\n#include <scitbx/math/cartesian_product_fixed_size.hpp>\n\n#include <boost/iterator/counting_iterator.hpp>\n#include <boost/range/iterator_range.hpp>\n\n#include <boost/numeric/conversion/converter.hpp>\n#include <boost/unordered_map.hpp>\n#include <boost/unordered_set.hpp>\n\n#include <boost/fusion/container/vector.hpp>\n#include <boost/fusion/include/vector.hpp>\n#include <boost/fusion/container/vector/vector_fwd.hpp>\n#include <boost/fusion/include/vector_fwd.hpp>\n#include <boost/fusion/sequence/intrinsic/at_c.hpp>\n#include <boost/fusion/include/at_c.hpp>\n#include <boost/fusion/algorithm/iteration/fold.hpp>\n\n#include <boost/mpl/vector.hpp>\n\n#include <vector>\n\nnamespace mmtbx\n{\n\nnamespace geometry\n{\n\nnamespace indexing\n{\n\ntemplate< typename Object, typename Vector >\nclass Linear\n{\npublic:\n  typedef Object object_type;\n  typedef Vector vector_type;\n  typedef std::vector< object_type > storage_type;\n  typedef boost::iterator_range< typename storage_type::const_iterator > range_type;\n\nprivate:\n  storage_type objects_;\n\npublic:\n  Linear();\n  ~Linear();\n\n  inline void add(const object_type& object, const vector_type& position);\n  inline range_type close_to(const vector_type& centre) const;\n  inline size_t size() const;\n};\n\ntemplate< typename Continuous, typename Discrete >\nclass Discretizer\n{\npublic:\n  typedef Continuous continuous_type;\n  typedef Discrete discrete_type;\n  typedef boost::numeric::converter<\n    Discrete,\n    Continuous,\n    boost::numeric::conversion_traits< Discrete, Continuous >,\n    boost::numeric::def_overflow_handler,\n    boost::numeric::Floor< Continuous >\n    > converter_type;\n\nprivate:\n  continuous_type base_;\n  continuous_type unit_;\n\npublic:\n  Discretizer(const continuous_type& base, const continuous_type& unit);\n  ~Discretizer();\n\n  continuous_type const& base() const;\n  discrete_type operator ()(const continuous_type& value) const;\n};\n\ntemplate< typename Vector, typename Voxel, typename Discrete >\nclass Voxelizer\n{\npublic:\n  typedef Vector vector_type;\n  typedef Voxel voxel_type;\n  typedef typename vector_type::value_type continuous_type;\n  typedef Discrete discrete_type;\n  typedef Discretizer< continuous_type, discrete_type > discretizer_type;\n  typedef boost::fusion::vector3<\n    discretizer_type, discretizer_type, discretizer_type\n    > discretizer_vector_type;\n\nprivate:\n  discretizer_vector_type discretizers_;\n\npublic:\n  Voxelizer(const vector_type& base, const vector_type& step);\n  ~Voxelizer();\n\n  vector_type base() const;\n  voxel_type operator ()(const vector_type& vector) const;\n};\n\nstruct HashCombine\n{\n  typedef std::size_t result_type;\n\n  template< typename T >\n  result_type operator ()(const T& arg, result_type current) const;\n};\n\ntemplate< typename FusionVector >\nstruct FusionVectorHasher\n{\n  typedef std::size_t result_type;\n  result_type operator ()(const FusionVector& myvector) const;\n};\n\ntemplate< typename Object, typename Vector, typename Discrete >\nclass Hash\n{\npublic:\n  typedef Object object_type;\n  typedef Vector vector_type;\n  typedef Discrete discrete_type;\n\nprivate:\n  typedef boost::counting_iterator< discrete_type > itercount;\n  typedef boost::mpl::vector< itercount, itercount, itercount > itercount_list;\n  typedef scitbx::math::cartesian_product::fixed_size_iterator< itercount_list >\n    cartesian_type;\n\npublic:\n  typedef typename vector_type::value_type distance_type;\n  typedef typename cartesian_type::value_type voxel_type;\n  typedef Voxelizer< vector_type, voxel_type, discrete_type > voxelizer_type;\n  typedef std::vector< object_type > bucket_type;\n  typedef FusionVectorHasher< voxel_type > hasher_type;\n  typedef boost::unordered_map< voxel_type, bucket_type, hasher_type > storage_type;\n  typedef boost::iterator_range< typename bucket_type::const_iterator >\n    bucket_range_type;\n  typedef utility::flattening_range< bucket_range_type > range_type;\n\nprivate:\n  voxelizer_type voxelizer_;\n  storage_type objects_;\n  discrete_type margin_;\n\npublic:\n  Hash(const voxelizer_type& voxelizer, const discrete_type& margin);\n  ~Hash();\n\n  inline void add(const object_type& object, const vector_type& position);\n  inline range_type close_to(const vector_type& centre) const;\n  inline range_type approx_within_sphere(\n    const vector_type& centre,\n    const distance_type& radius\n    ) const;\n  inline size_t size() const;\n  inline size_t cubes() const;\n\nprivate:\n  cartesian_type make_cartesian_iterator_around(\n    const voxel_type& voxel,\n    const voxel_type& margin\n    ) const;\n};\n\n#include \"indexing.hxx\"\n\n} // namespace indexing\n} // namespace geometry\n} // namespace mmtbx\n\n#endif // MMTBX_GEOMETRY_INDEXING_H\n", "meta": {"hexsha": "0878ab2e65f43f6994e6e4551c08bacfbfd42828", "size": 4731, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "mmtbx/geometry/indexing.hpp", "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": "mmtbx/geometry/indexing.hpp", "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": "mmtbx/geometry/indexing.hpp", "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.5786516854, "max_line_length": 84, "alphanum_fraction": 0.7784823505, "num_tokens": 1072, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4978811996314368}}
{"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_TRIGONOMETRIC_FUNCTIONS_SCALAR_REM_PIO2_MEDIUM_HPP_INCLUDED\n#define NT2_TOOLBOX_TRIGONOMETRIC_FUNCTIONS_SCALAR_REM_PIO2_MEDIUM_HPP_INCLUDED\n#include <nt2/toolbox/trigonometric/functions/rem_pio2_medium.hpp>\n#include <nt2/toolbox/trigonometric/constants.hpp>\n#include <nt2/include/functions/scalar/round.hpp>\n#include <nt2/include/functions/scalar/fast_toint.hpp>\n#include <nt2/sdk/meta/as_integer.hpp>\n#include <boost/fusion/tuple.hpp>\n\nnamespace nt2 { namespace ext\n{\n  NT2_FUNCTOR_IMPLEMENTATION(nt2::tag::rem_pio2_medium_, tag::cpu_,\n                             (A0),\n                             (scalar_ < floating_<A0> > )\n                             )\n  {\n    typedef boost::fusion::tuple<A0,A0,nt2::int32_t>           result_type;\n\n    inline result_type operator()(A0 const& a0) const\n    {\n      result_type res;\n      boost::fusion::at_c<2>(res) =\n      nt2::rem_pio2_medium(a0,\n                           boost::fusion::at_c<0>(res),\n                           boost::fusion::at_c<1>(res)\n                          );\n      return res;\n    }\n  };\n\n  /////////////////////////////////////////////////////////////////////////////\n  // reference based Implementation when real\n  /////////////////////////////////////////////////////////////////////////////\n  NT2_FUNCTOR_IMPLEMENTATION(nt2::tag::rem_pio2_medium_, tag::cpu_,\n                             (A0),\n                             (scalar_ < floating_<A0> > )\n                             (scalar_ < floating_<A0> > )\n                             (scalar_ < floating_<A0> > )\n                             )\n  {\n    typedef typename meta::as_integer<A0>::type result_type;\n    inline result_type operator()(A0 const& t, A0 & xr, A0& xc) const\n    {\n      const A0 fn = nt2::round(t*Invpio_2<A0>());\n      A0 r  = t-fn*Pio2_1<A0>();\n      A0 w  = fn*Pio2_1t<A0>();\n      A0 t2 = r;\n      w  = fn*Pio2_2<A0>();\n      r  = t2-w;\n      w  = fn*Pio2_2t<A0>()-((t2-r)-w);\n      t2 = r;\n      w  = fn*Pio2_3<A0>();\n      r  = t2-w;\n      w  = fn*Pio2_3t<A0>()-((t2-r)-w);\n      xr = r-w;\n      xc = (r-xr)-w;\n      return  fast_toint(fn)&3;\n    }\n  };\n} }\n#endif\n", "meta": {"hexsha": "89be380b193ec980466398a6c3d63c2ccface1fd", "size": 2648, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/trigonometric/include/nt2/toolbox/trigonometric/functions/scalar/rem_pio2_medium.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/rem_pio2_medium.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/rem_pio2_medium.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": 37.8285714286, "max_line_length": 80, "alphanum_fraction": 0.4856495468, "num_tokens": 684, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397349, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.4978559382836563}}
{"text": "//headers for stl\n#include <sstream>\n//headers for gazebo\n#include <gazebo/gazebo.hh>\n#include <gazebo/physics/Model.hh>\n#include <gazebo/physics/Link.hh>\n#include <gazebo/physics/physics.hh>\n#include <gazebo/common/common.hh>\n#include <gazebo/math/gzmath.hh>\n//headers for sdf\n#include <sdf/Param.hh>\n#include <sdf/sdf.hh>\n//headers fot boost\n#include <boost/bind.hpp>\n#include <boost/lexical_cast.hpp>\n//headers for ROS\n#include <ros/ros.h>\n#include <std_msgs/Float32.h>\n#include <geometry_msgs/Twist.h>\n\nnamespace gazebo\n{\n  class simple_driving_force_plugin : public ModelPlugin\n  {\n    public: void Load(physics::ModelPtr _parent, sdf::ElementPtr sdf)\n    {\n      // Store the pointer to the model\n      this->model = _parent;\n      this->LoadParams(sdf,\"target_link\",this->target_link);\n      this->LoadParams(sdf,\"target_joint\",this->target_joint);\n      std::string default_joint_states_topic = \"/joint_states\";\n      this->LoadParams(sdf,\"joint_state_topic\",this->joint_state_topic,default_joint_states_topic);\n      this->LoadParams(sdf,\"driving_force_controller\",this->driving_force_controller);\n      nh.getParam(this->driving_force_controller+\"/propeller/k0\", k0);\n      nh.getParam(this->driving_force_controller+\"/propeller/k1\", k1);\n      nh.getParam(this->driving_force_controller+\"/propeller/k2\", k2);\n      nh.getParam(this->driving_force_controller+\"/propeller/fluid_density\",fluid_density);\n      nh.getParam(this->driving_force_controller+\"/propeller/turning_radius\", turning_radius);\n      //nh.getParam(this->driving_force_controller+\"/propeller/twist_topic\",twist_topic);\n      this->joint = this->model->GetJoint(this->target_joint);\n      this->link = this->model->GetLink(target_link);\n      driving_force_pub = nh.advertise<std_msgs::Float32>(\"/\"+this->target_link+\"/driving_force\", 1);\n      //twist_sub = nh.subscribe(twist_topic, 1, &simple_driving_force_plugin::twist_callback,this);\n      this->updateConnection = event::Events::ConnectWorldUpdateBegin(boost::bind(&simple_driving_force_plugin::OnUpdate, this, _1));\n    }\n\n    double get_thrust(double rotational_speed,double inflow_rate)\n    {\n      if(rotational_speed == 0)\n      {\n        return 0;\n      }\n      if(rotational_speed > 0)\n      {\n        double Js = inflow_rate/rotational_speed*turning_radius;\n        double Kt = k2*Js*Js + k1*Js + k0;\n        double thrust = fluid_density*std::pow(rotational_speed,2)*std::pow(turning_radius,4)*Kt;\n        return thrust;\n      }\n      if(rotational_speed < 0)\n      {\n        double Js = inflow_rate/rotational_speed*turning_radius;\n        double Kt = k2*Js*Js + k1*Js + k0;\n        double thrust = -fluid_density*std::pow(rotational_speed,2)*std::pow(turning_radius,4)*Kt;\n        return thrust;\n      }\n    }\n\n    // Called by the world update start event\n    public: void OnUpdate(const common::UpdateInfo & /*_info*/)\n    {\n      inflow_rate = model->GetWorldLinearVel().x;\n      std_msgs::Float32 driving_force_msg;\n      double velocity = this->joint->GetVelocity(0);\n      double driving_force = get_thrust(velocity,this->inflow_rate);\n      this->link->AddForce(math::Vector3(driving_force, 0, 0));\n      driving_force_msg.data = driving_force;\n      driving_force_pub.publish(driving_force_msg);\n    }\n\n    template <typename T>\n    bool LoadParams(sdf::ElementPtr sdf,std::string key,T& param)\n    {\n      std::string param_str;\n      if(!sdf->HasElement(key))\n      {\n        ROS_WARN_STREAM(\"failed to get \" << key);\n        return false;\n      }\n      else\n      {\n        param_str = sdf->GetElement(key)->GetValue()->GetAsString();\n      }\n      try\n      {\n        param = boost::lexical_cast<T>(param_str);\n      }\n      catch(boost::bad_lexical_cast &)\n      {\n        ROS_WARN_STREAM(\"failed to casting \" << key);\n      }\n      return true;\n    }\n\n    template <typename T>\n    bool LoadParams(sdf::ElementPtr sdf,std::string key,T& param, T default_param)\n    {\n      std::string param_str;\n      if(!sdf->HasElement(key))\n      {\n        param = default_param;\n        ROS_INFO_STREAM(\"unable to get \" << key << \" ,set default_value = \" << default_param);\n        return false;\n      }\n      else\n      {\n        param_str = sdf->GetElement(key)->GetValue()->GetAsString();\n      }\n      try\n      {\n        param = boost::lexical_cast<T>(param_str);\n      }\n      catch(boost::bad_lexical_cast &)\n      {\n        ROS_WARN_STREAM(\"failed to casting \" << key);\n        param = default_param;\n      }\n      return true;\n    }\n    private: double rotational_speed_effort;\n    private: std::string target_link,target_joint,joint_state_topic;\n    private: physics::JointPtr joint;\n    private: physics::ModelPtr model;\n    private: physics::LinkPtr link;\n\n    //ros publishers\n    private: ros::NodeHandle nh;\n    private: ros::Publisher driving_force_pub;\n    //private: ros::Subscriber twist_sub;\n\n    // Pointer to the update event connection\n    private: event::ConnectionPtr updateConnection;\n\n    //propeller params\n    std::string driving_force_controller;//,twist_topic;\n    double k0,k1,k2;\n    double fluid_density,turning_radius,inflow_rate;\n  };\n  // Register this plugin with the simulator\n  GZ_REGISTER_MODEL_PLUGIN(simple_driving_force_plugin)\n}\n", "meta": {"hexsha": "b3ef4df89c85c6fbd337ea9f658fb7fcc87da924", "size": 5221, "ext": "cc", "lang": "C++", "max_stars_repo_path": "ros_ship_gazebo_plugins/src/simple_driving_force_plugin.cc", "max_stars_repo_name": "weilunwc/ros_ship_packages", "max_stars_repo_head_hexsha": "3abc92020cf338f1ecc1b85d216d67e7d4543fbd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 76.0, "max_stars_repo_stars_event_min_datetime": "2017-12-07T11:44:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T07:01:41.000Z", "max_issues_repo_path": "ros_ship_gazebo_plugins/src/simple_driving_force_plugin.cc", "max_issues_repo_name": "qycqycqyc/ros_ship_packages", "max_issues_repo_head_hexsha": "3abc92020cf338f1ecc1b85d216d67e7d4543fbd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2017-12-10T14:13:42.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-04T07:51:28.000Z", "max_forks_repo_path": "ros_ship_gazebo_plugins/src/simple_driving_force_plugin.cc", "max_forks_repo_name": "qycqycqyc/ros_ship_packages", "max_forks_repo_head_hexsha": "3abc92020cf338f1ecc1b85d216d67e7d4543fbd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 36.0, "max_forks_repo_forks_event_min_datetime": "2018-01-04T14:40:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-05T07:27:37.000Z", "avg_line_length": 34.3486842105, "max_line_length": 133, "alphanum_fraction": 0.6705611952, "num_tokens": 1316, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.6297746143530798, "lm_q1q2_score": 0.49785592657461175}}
{"text": "#include <vector>\n#include <algorithm>\n\n#include <boost/numeric/ublas/storage.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n#include \"MODI.hpp\"\n#include \"Helper.hpp\"\n\nnamespace ublas = boost::numeric::ublas;\nusing namespace std;\n\nnamespace t_simplex\n{\n\t/**********************\n\tVogel's initialization method\n\t**********************/\n\tvoid _initVogel(\n\t\tvector<double> &bi,\n\t\tvector<double> dj,\n\t\tTsBasic * basicsEnd,\n\t\tTsBasic ** facBasics,\n\t\tTsBasic ** cusBasics,\n\t\tbool ** isBasic,\n\t\tint m,\n\t\tint n,\n\t\tublas::matrix<double> &cij,\n\t\tdouble &_tsMaxW)\n\t{\n\t\tint i, j;\n\t\tTsVogPen *srcPens = NULL;\n\t\tTsVogPen *snkPens = NULL;\n\t\tTsVogPen *pitra = NULL, *pitrb = NULL;  //iterators\n\t\tTsVogPen *maxPen = NULL;\n\t\tTsVogPen srcPenHead, snkPenHead;\n\t\tbool maxIsSrc = false;\n\t\tdouble lowVal = 0.0;\n\n\t\ttry\n\t\t{\n\t\t\tsrcPens = new TsVogPen[m];\n\t\t\tsnkPens = new TsVogPen[n];\n\t\t}\n\t\tcatch (std::bad_alloc)\n\t\t{\n\t\t\tdelete[] srcPens;\n\t\t\tdelete[] snkPens;\n\t\t\tthrow;\n\t\t}\n\n\t\tsrcPenHead.next = pitra = srcPens;\n\t\tfor (i = 0; i < m; i++)\n\t\t{\n\t\t\tpitra->i = i;\n\t\t\tpitra->next = pitra + 1;\n\t\t\tpitra->prev = pitra - 1;\n\t\t\tpitra->one = pitra->two = 0;\n\t\t\tpitra->oneCost = pitra->twoCost = TSINFINITY;\n\t\t\tpitra++;\n\t\t}\n\t\t(--pitra)->next = NULL;\n\t\tsrcPens[0].prev = &srcPenHead;\n\n\t\tsnkPenHead.next = pitra = snkPens;\n\t\tfor (i = 0; i < n; i++)\n\t\t{\n\t\t\tpitra->i = i;\n\t\t\tpitra->next = pitra + 1;\n\t\t\tpitra->prev = pitra - 1;\n\t\t\tpitra->one = pitra->two = 0;\n\t\t\tpitra->oneCost = pitra->twoCost = TSINFINITY;\n\t\t\tpitra++;\n\t\t}\n\t\t(--pitra)->next = NULL;\n\t\tsnkPens[0].prev = &snkPenHead;\n\n\n\t\tfor (pitra = srcPenHead.next, i = 0; pitra != NULL; pitra = pitra->next, i++)\n\t\t{\n\t\t\tfor (pitrb = snkPenHead.next, j = 0; pitrb != NULL; pitrb = pitrb->next, j++)\n\t\t\t{\n\t\t\t\t//initialize Source Penalties;\n\t\t\t\taddPenalty(pitra, cij(i, j), j);\n\t\t\t\taddPenalty(pitrb, cij(i, j), i);\n\t\t\t}\n\t\t}\n\n\t\twhile (srcPenHead.next != NULL && snkPenHead.next != NULL)\n\t\t{\n\t\t\tmaxIsSrc = true;\n\t\t\tfor (maxPen = pitra = srcPenHead.next; pitra != NULL; pitra = pitra->next)\n\t\t\t\tif ((pitra->twoCost - pitra->oneCost) > (maxPen->twoCost - maxPen->oneCost))\n\t\t\t\t\tmaxPen = pitra;\n\n\t\t\tfor (pitra = snkPenHead.next; pitra != NULL; pitra = pitra->next)\n\t\t\t\tif ((pitra->twoCost - pitra->oneCost) > (maxPen->twoCost - maxPen->oneCost))\n\t\t\t\t{\n\t\t\t\t\tmaxPen = pitra;\n\t\t\t\t\tmaxIsSrc = false;\n\t\t\t\t}\n\n\t\t\tif (maxIsSrc)\n\t\t\t{\n\t\t\t\ti = maxPen->i;\n\t\t\t\tj = maxPen->one;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tj = maxPen->i;\n\t\t\t\ti = maxPen->one;\n\t\t\t}\n\n\t\t\tif (dj[j] - bi[i] > _tsMaxW * TSEPSILON \n\t\t\t\t|| (srcPenHead.next->next != NULL\n\t\t\t\t&& fabs(dj[i] - bi[j]) < _tsMaxW * TSEPSILON))\n\t\t\t{\n\t\t\t\t//delete source\n\t\t\t\tlowVal = bi[i];\n\t\t\t\tmaxPen = srcPens + i;\n\t\t\t\tmaxPen->prev->next = maxPen->next;\n\t\t\t\tif (maxPen->next != NULL)\n\t\t\t\t\tmaxPen->next->prev = maxPen->prev;\n\n\t\t\t\tfor (pitra = snkPenHead.next; pitra != NULL; pitra = pitra->next)\n\t\t\t\t{\n\t\t\t\t\tif (pitra->one == i || pitra->two == i)\n\t\t\t\t\t{\n\t\t\t\t\t\tpitra->oneCost = TSINFINITY;\n\t\t\t\t\t\tpitra->twoCost = TSINFINITY;\n\t\t\t\t\t\tfor (pitrb = srcPenHead.next; pitrb != NULL; pitrb = pitrb->next)\n\t\t\t\t\t\t\taddPenalty(pitra, cij(pitrb->i, pitra->i), pitrb->i);\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\t//delete sink\n\t\t\t\tlowVal = dj[j];\n\t\t\t\tmaxPen = snkPens + j;\n\t\t\t\tmaxPen->prev->next = maxPen->next;\n\t\t\t\tif (maxPen->next != NULL)\n\t\t\t\t\tmaxPen->next->prev = maxPen->prev;\n\n\t\t\t\tfor (pitra = srcPenHead.next; pitra != NULL; pitra = pitra->next)\n\t\t\t\t{\n\t\t\t\t\tif (pitra->one == j || pitra->two == j) {\n\t\t\t\t\t\tpitra->oneCost = TSINFINITY;\n\t\t\t\t\t\tpitra->twoCost = TSINFINITY;\n\t\t\t\t\t\tfor (pitrb = snkPenHead.next; pitrb != NULL; pitrb = pitrb->next)\n\t\t\t\t\t\t\taddPenalty(pitra, cij(pitra->i, pitrb->i), pitrb->i);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tbi[i] -= lowVal;\n\t\t\tdj[j] -= lowVal;\n\n\t\t\tisBasic[i][j] = 1;\n\t\t\tbasicsEnd->val = lowVal;\n\t\t\tbasicsEnd->i = i;\n\t\t\tbasicsEnd->j = j;\n\n\t\t\tbasicsEnd->nextCus = cusBasics[j];\n\t\t\tif (cusBasics[j] != NULL) cusBasics[j]->prevCus = basicsEnd;\n\t\t\tbasicsEnd->nextFac = facBasics[i];\n\t\t\tif (facBasics[i] != NULL) facBasics[i]->prevFac = basicsEnd;\n\n\t\t\tfacBasics[i] = basicsEnd;\n\t\t\tbasicsEnd->prevCus = NULL;\n\t\t\tcusBasics[j] = basicsEnd;\n\t\t\tbasicsEnd->prevFac = NULL;\n\n\t\t\tbasicsEnd++;\n\t\t}\n\n\t\tdelete[] srcPens;\n\t\tsrcPens = NULL;\n\t\tdelete[] snkPens;\n\t\tsnkPens = NULL;\n\t}\n\n\t/**********************\n\tNW-Corner initialization method\n\t**********************/\n\tvoid _initNW(\n\t\tdouble *bi,\n\t\tdouble *dj,\n\t\tTsBasic * basicsEnd,\n\t\tTsBasic ** facBasics,\n\t\tTsBasic ** cusBasics,\n\t\tbool ** isBasic,\n\t\tint m,\n\t\tint n)\n\t{\n\t\tunsigned int i = 0, j = 0;\n\t\tdouble lowVal = 0.0;\n\n\t\twhile (i < m && j < n)\n\t\t{\n\t\t\t// More capacity than Demand\n\t\t\tif (bi[i] >= dj[j] && dj[j] != 0.0)\n\t\t\t{\n\t\t\t\tlowVal = dj[j];\n\t\t\t\tbi[i] -= dj[j];\n\t\t\t\tdj[j] = 0.0;\n\n\t\t\t\tisBasic[i][j] = 1;\n\t\t\t\tbasicsEnd->val = lowVal;\n\t\t\t\tbasicsEnd->i = i;\n\t\t\t\tbasicsEnd->j = j;\n\n\t\t\t\tbasicsEnd->nextCus = cusBasics[j];\n\t\t\t\tif (cusBasics[j] != NULL) cusBasics[j]->prevCus = basicsEnd;\n\t\t\t\tbasicsEnd->nextFac = facBasics[i];\n\t\t\t\tif (facBasics[i] != NULL) facBasics[i]->prevFac = basicsEnd;\n\n\t\t\t\tfacBasics[i] = basicsEnd;\n\t\t\t\tbasicsEnd->prevCus = NULL;\n\t\t\t\tcusBasics[j] = basicsEnd;\n\t\t\t\tbasicsEnd->prevFac = NULL;\n\n\t\t\t\tbasicsEnd++;\n\n\t\t\t\t// Test on Degeneration\n\t\t\t\tif (bi[i] == 0.0 && dj[j] == 0.0  && i < m - 1 && j < n - 1)\n\t\t\t\t{\n\t\t\t\t\tisBasic[i][j + 1] = 1;\n\t\t\t\t\tbasicsEnd->val = lowVal;\n\t\t\t\t\tbasicsEnd->i = i;\n\t\t\t\t\tbasicsEnd->j = j + 1;\n\n\t\t\t\t\tbasicsEnd->nextCus = cusBasics[j + 1];\n\t\t\t\t\tif (cusBasics[j + 1] != NULL) cusBasics[j + 1]->prevCus = basicsEnd;\n\t\t\t\t\tbasicsEnd->nextFac = facBasics[i];\n\t\t\t\t\tif (facBasics[i] != NULL) facBasics[i]->prevFac = basicsEnd;\n\n\t\t\t\t\tfacBasics[i] = basicsEnd;\n\t\t\t\t\tbasicsEnd->prevCus = NULL;\n\t\t\t\t\tcusBasics[j + 1] = basicsEnd;\n\t\t\t\t\tbasicsEnd->prevFac = NULL;\n\n\t\t\t\t\tbasicsEnd++;\n\n\t\t\t\t\ti++;\n\t\t\t\t\tj++;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t// Skip to next Customer\n\t\t\t\t\tj++;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Less Capacity than Demand\n\t\t\telse if (bi[i] < dj[j] && bi[i] != 0.0)\n\t\t\t{\n\t\t\t\tlowVal = bi[i];\n\t\t\t\tdj[j] -= bi[i];\n\t\t\t\tbi[i] = 0.0;\n\n\t\t\t\tisBasic[i][j] = 1;\n\t\t\t\tbasicsEnd->val = lowVal;\n\t\t\t\tbasicsEnd->i = i;\n\t\t\t\tbasicsEnd->j = j;\n\n\t\t\t\tbasicsEnd->nextCus = cusBasics[j];\n\t\t\t\tif (cusBasics[j] != NULL) cusBasics[j]->prevCus = basicsEnd;\n\t\t\t\tbasicsEnd->nextFac = facBasics[i];\n\t\t\t\tif (facBasics[i] != NULL) facBasics[i]->prevFac = basicsEnd;\n\n\t\t\t\tfacBasics[i] = basicsEnd;\n\t\t\t\tbasicsEnd->prevCus = NULL;\n\t\t\t\tcusBasics[j] = basicsEnd;\n\t\t\t\tbasicsEnd->prevFac = NULL;\n\n\t\t\t\tbasicsEnd++;\n\n\t\t\t\t// Test on Degeneration\n\t\t\t\tif (bi[i] == 0.0 && dj[j] == 0.0 && i < m - 1 && j < n - 1)\n\t\t\t\t{\n\t\t\t\t\tisBasic[i][j+1] = 1;\n\t\t\t\t\tbasicsEnd->val = lowVal;\n\t\t\t\t\tbasicsEnd->i = i;\n\t\t\t\t\tbasicsEnd->j = j+1;\n\n\t\t\t\t\tbasicsEnd->nextCus = cusBasics[j+1];\n\t\t\t\t\tif (cusBasics[j+1] != NULL) cusBasics[j+1]->prevCus = basicsEnd;\n\t\t\t\t\tbasicsEnd->nextFac = facBasics[i];\n\t\t\t\t\tif (facBasics[i] != NULL) facBasics[i]->prevFac = basicsEnd;\n\n\t\t\t\t\tfacBasics[i] = basicsEnd;\n\t\t\t\t\tbasicsEnd->prevCus = NULL;\n\t\t\t\t\tcusBasics[j+1] = basicsEnd;\n\t\t\t\t\tbasicsEnd->prevFac = NULL;\n\n\t\t\t\t\tbasicsEnd++;\n\n\t\t\t\t\ti++;\n\t\t\t\t\tj++;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t// Skip to next Customer\n\t\t\t\t\ti++;\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\t}\n\n\t/**********************\n\tLCM initialization method\n\t**********************/\n\tvoid _initLCM(\n\t\tdouble *bi,\n\t\tdouble *dj,\n\t\tTsBasic *basicsEnd,\n\t\tTsBasic **facBasics,\n\t\tTsBasic **cusBasics,\n\t\tbool ** isBasic,\n\t\tint m,\n\t\tint n,\n\t\tublas::matrix<unsigned int> &cij_column_sorted,\n\t\tint *facilities)\n\t{\n\t\tunsigned int i = 0, j = 0;\n\t\tunsigned int indx_i = 0;\n\t\tdouble lowVal = 0.0;\n\n\t\twhile (j < cij_column_sorted.size2())\n\t\t{\n\t\t\tindx_i = cij_column_sorted(i, j);\n\n\t\t\t// Can shift Capacity to fullfill Customer Demand\n\t\t\tif (bi[indx_i] != 0.0 && dj[j] != 0.0)\n\t\t\t{\n\t\t\t\t// More capacity than Demand\n\t\t\t\tif (bi[i] >= dj[j] && dj[j] != 0.0)\n\t\t\t\t{\n\t\t\t\t\tlowVal = dj[j];\n\t\t\t\t\tbi[i] -= dj[j];\n\t\t\t\t\tdj[j] = 0.0;\n\n\t\t\t\t\tisBasic[i][j] = 1;\n\t\t\t\t\tbasicsEnd->val = lowVal;\n\t\t\t\t\tbasicsEnd->i = i;\n\t\t\t\t\tbasicsEnd->j = j;\n\n\t\t\t\t\tbasicsEnd->nextCus = cusBasics[j];\n\t\t\t\t\tif (cusBasics[j] != NULL) cusBasics[j]->prevCus = basicsEnd;\n\t\t\t\t\tbasicsEnd->nextFac = facBasics[i];\n\t\t\t\t\tif (facBasics[i] != NULL) facBasics[i]->prevFac = basicsEnd;\n\n\t\t\t\t\tfacBasics[i] = basicsEnd;\n\t\t\t\t\tbasicsEnd->prevCus = NULL;\n\t\t\t\t\tcusBasics[j] = basicsEnd;\n\t\t\t\t\tbasicsEnd->prevFac = NULL;\n\n\t\t\t\t\tbasicsEnd++;\n\n\t\t\t\t\t// Skip to next Customer\n\t\t\t\t\tj++;\n\t\t\t\t\ti = 0;\n\t\t\t\t}\n\t\t\t\t// Less Capacity than Demand\n\t\t\t\telse if (bi[i] < dj[j] && bi[i] != 0.0)\n\t\t\t\t{\n\t\t\t\t\tlowVal = bi[i];\n\t\t\t\t\tdj[j] -= bi[i];\n\t\t\t\t\tbi[i] = 0.0;\n\n\t\t\t\t\tisBasic[i][j] = 1;\n\t\t\t\t\tbasicsEnd->val = lowVal;\n\t\t\t\t\tbasicsEnd->i = i;\n\t\t\t\t\tbasicsEnd->j = j;\n\n\t\t\t\t\tbasicsEnd->nextCus = cusBasics[j];\n\t\t\t\t\tif (cusBasics[j] != NULL) cusBasics[j]->prevCus = basicsEnd;\n\t\t\t\t\tbasicsEnd->nextFac = facBasics[i];\n\t\t\t\t\tif (facBasics[i] != NULL) facBasics[i]->prevFac = basicsEnd;\n\n\t\t\t\t\tfacBasics[i] = basicsEnd;\n\t\t\t\t\tbasicsEnd->prevCus = NULL;\n\t\t\t\t\tcusBasics[j] = basicsEnd;\n\t\t\t\t\tbasicsEnd->prevFac = NULL;\n\n\t\t\t\t\tbasicsEnd++;\n\n\t\t\t\t\t// Skip to next Customer\n\t\t\t\t\ti++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// If its in the fictional Column\n\t\tif (n > cij_column_sorted.size2() && j == cij_column_sorted.size2())\n\t\t{\n\t\t\tfor (i = 0; i != cij_column_sorted.size1(); ++i)\n\t\t\t{\n\t\t\t\t// If Capacity is not empty ship to customer\n\t\t\t\tif (bi[i] != 0.0)\n\t\t\t\t{\n\t\t\t\t\tlowVal = bi[i];\n\t\t\t\t\tbi[i] = 0.0;\n\t\t\t\t\t\n\t\t\t\t\tisBasic[i][j] = 1;\n\t\t\t\t\tbasicsEnd->val = lowVal;\n\t\t\t\t\tbasicsEnd->i = i;\n\t\t\t\t\tbasicsEnd->j = j;\n\n\t\t\t\t\tbasicsEnd->nextCus = cusBasics[j];\n\t\t\t\t\tif (cusBasics[j] != NULL) cusBasics[j]->prevCus = basicsEnd;\n\t\t\t\t\tbasicsEnd->nextFac = facBasics[i];\n\t\t\t\t\tif (facBasics[i] != NULL) facBasics[i]->prevFac = basicsEnd;\n\n\t\t\t\t\tfacBasics[i] = basicsEnd;\n\t\t\t\t\tbasicsEnd->prevCus = NULL;\n\t\t\t\t\tcusBasics[j] = basicsEnd;\n\t\t\t\t\tbasicsEnd->prevFac = NULL;\n\n\t\t\t\t\tbasicsEnd++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "meta": {"hexsha": "252cf9cb6700493992921ee16d75e18072cb20cc", "size": 9749, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "VNS Implementierung/VNS Implementierung/InitialMODI.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/InitialMODI.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/InitialMODI.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": 22.831381733, "max_line_length": 80, "alphanum_fraction": 0.5585188224, "num_tokens": 3586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.4978559258518293}}
{"text": "#include <iostream>\n#include \"raisim/World.hpp\"\n#include <Eigen/Core>\n\n#include <iostream>\n#include <fstream>\n#include <time.h>\n\nusing std::cout; using std::ofstream;\nusing std::endl; using std::string;\nusing std::fstream;\n#define OUT_FILE false\n#define SWEEP false\n\nusing namespace std;\n\nint main(int argc, char *argv[]) {\n\n    // Hyper Parameter defination\n     float inertia = 6*6*103E-6;     // joint inertia\n//     float inertia = 0.008966;     // joint inertia\n//    float inertia = 0.003708;\n    float kp = 80.0f;//80.0f;           // joint stiffness\n    float kd = 1.0f;//1.0f;            // joint damping\n    float omega = 8.0f;//10.0f;        // pTarget swing frequency\n    float dt = 2e-3;            // time step of calculation\n//    float total_time = 15.0f * 10.0f;    // total simulation time\n    float total_time = 20.0;    // total simulation time\n\n//    raisim::World::setActivationKey(raisim::Path(\"./activation.raisim\").getString());\n    raisim::World::setActivationKey(raisim::Path(\"activation.raisim\").getString());\n    raisim::World world;\n\n    Eigen::VectorXd jointDgain;\n    Eigen::VectorXd jointPgain;\n    Eigen::VectorXd Ptarget;\n    Eigen::VectorXd Dtarget;\n    Eigen::VectorXd gc_;\n    Eigen::VectorXd gv_;\n    raisim::VecDyn RotorInertia_;\n    RotorInertia_.setZero(1);\n    RotorInertia_[0] = inertia;\n\n    time_t timep;\n\n    auto nunchucks = world.addArticulatedSystem(\"test.urdf\");\n//    auto nunchucks = world.addArticulatedSystem(\"BlackPanther_2d.urdf\");\n    nunchucks->setControlMode(raisim::ControlMode::PD_PLUS_FEEDFORWARD_TORQUE);\n\n    // nunchucks->setMass(2, inertia);\n    nunchucks->setRotorInertia(RotorInertia_);\n    nunchucks->updateMassInfo();\n    cout << nunchucks->getMassMatrix() <<endl;\n    world.setTimeStep(dt);\n\n    int gcDim_ = nunchucks->getGeneralizedCoordinateDim();\n    int gvDim_ = nunchucks->getDOF();\n\n    jointDgain.setZero(gvDim_);\n    jointPgain.setZero(gvDim_);\n    gc_.setZero(gcDim_);\n    gv_.setZero(gvDim_);\n    Ptarget.setZero(gcDim_);\n    Dtarget.setZero(gvDim_);\n\n    jointDgain.tail(1) << kd;\n    jointPgain.tail(1) << kp;\n\n    nunchucks->setPdGains(jointPgain, jointDgain);\n    nunchucks->setPdTarget(Ptarget, Dtarget);\n    nunchucks->getState(gc_, gv_);\n    gv_.tail(1) << 0;\n    gc_.tail(1) << 0;\n    nunchucks->setState(gc_, gv_);\n\n    float current_time = 0.0;\n    float pTarget_last = 0.0f;\n    float pTarget_next = 0.0f;\n    float ratio = 0.0;\n\n#if SWEEP\n#if OUT_FILE\n    time(&timep);\n    char filename[256] = {0};\n    strftime( filename, sizeof(filename), \"%Y.%m.%d %H-%M-%S.xls\",localtime(&timep) );\n    fstream file_out;\n//    file_out.open(\"/home/wooden/Desktop/0322-0328_research_plan/data/\"+std::string(filename), std::ios_base::out);\n    file_out.open(\"/home/wooden/Desktop/0329-0411/data/\"+std::string(filename), std::ios_base::out);\n    file_out << \"des_q0\"<< \"\\t\" << \"raw_q0\" << \"\\t\" << \"raw_dq0\" << endl;\n    for(int i=0; i<int(total_time/dt); i++){\n        // omega = int(current_time/15.0f)+1.0f;  // change omega\n        omega = 8;\n        Ptarget.tail(1) << sin(2*3.1415926*omega*floor(current_time/0.001)*0.001);\n        nunchucks->setPdTarget(Ptarget, Dtarget);\n        nunchucks->setPdGains(jointPgain, jointDgain);\n        world.integrate();\n        file_out << Ptarget.tail(1) << \"\\t\" << nunchucks->getGeneralizedCoordinate() << \"\\t\" << nunchucks->getGeneralizedVelocity() << endl;\n        current_time += dt;\n    }\n    file_out.close();\n#else\n\n#endif\n\n#else\n#if OUT_FILE\n    time(&timep);\n    char filename[256] = {0};\n    strftime( filename, sizeof(filename), \"%Y.%m.%d %H-%M-%S.txt\",localtime(&timep) );\n    fstream file_out;\n    file_out.open(\"/home/wooden/Desktop/0322-0328_research_plan/data/\"+std::string(filename), std::ios_base::out);\n    file_out << \"inertia \" << inertia << \" kp \" << kp << \" kd \" << kd << \" omega \" << omega << \" dt \" << dt << endl;\n    for (int i = 0; i < int(total_time / dt); i++) {\n        file_out << \"t: \" << current_time << \" q \" << nunchucks->getGeneralizedCoordinate() << \" dq \" << nunchucks->getGeneralizedVelocity() << endl;\n        // Ptarget.tail(1) << sin(2*3.14*omega*current_time);\n        Ptarget.tail(1) << sin(2*3.1415926*omega*floor(current_time/0.002)*0.002);\n//        if(fmod(current_time,0.002)<1e-6){\n//            pTarget_last = pTarget_next;\n//            pTarget_next = sin(2*3.1415926*omega*floor(current_time/0.002)*0.002);\n//        }\n//        ratio = fmod(current_time,0.002)/0.002;\n//        Ptarget.tail(1) <<  ratio*pTarget_next+(1.0-ratio)*pTarget_last;\n        nunchucks->setPdTarget(Ptarget, Dtarget);\n        nunchucks->setPdGains(jointPgain, jointDgain);\n        world.integrate();\n        current_time += dt;\n//        cout << nunchucks->getGeneralizedCoordinate() << \" \" << (nunchucks->getGeneralizedForce()) << endl;\n//        cout << nunchucks->getMassMatrix() <<endl;\n    }\n    file_out.close();\n\n    // M(u+-u-)=dt(-kd((u++u-)/2-u_ref))\n    //\n#else\n    for (int i = 0; i < int(total_time / dt); i++) {\n//        file_out << \"t: \" << current_time << \" q \" << nunchucks->getGeneralizedCoordinate() << \" dq \" << nunchucks->getGeneralizedVelocity() << endl;\n        // Ptarget.tail(1) << sin(2 * 3.14 * omega * current_time);\n        Ptarget.tail(1) << sin(2*3.1415926*omega*floor(current_time/0.002)*0.002);\n        nunchucks->setPdTarget(Ptarget, Dtarget);\n        nunchucks->setPdGains(jointPgain, jointDgain);\n        world.integrate();\n        current_time += dt;\n//        cout << \"target\" << Ptarget.tail(1) <<\n//        \" \" << nunchucks->getGeneralizedCoordinate() <<\n//        \" \" << (nunchucks->getGeneralizedVelocity()) <<\n//        \" \"<< nunchucks->getGeneralizedForce()<<endl;\n//        cout << nunchucks->getMassMatrix() <<endl;\n    }\n#endif\n#endif\n\n\n    std::cout << \"Finished!\" << std::endl;\n    return 0;\n}\n", "meta": {"hexsha": "7988c5b7c6752083ff53a28d8994959caac5f7b5", "size": 5796, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "model_raisim/LISM_1D/urdf/raisim_damping_test/main.cpp", "max_stars_repo_name": "Stylite-Y/XArm-Simulation", "max_stars_repo_head_hexsha": "654dca390e635b6294a8b5066727d0f4d6736eb1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "model_raisim/LISM_1D/urdf/raisim_damping_test/main.cpp", "max_issues_repo_name": "Stylite-Y/XArm-Simulation", "max_issues_repo_head_hexsha": "654dca390e635b6294a8b5066727d0f4d6736eb1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "model_raisim/LISM_1D/urdf/raisim_damping_test/main.cpp", "max_forks_repo_name": "Stylite-Y/XArm-Simulation", "max_forks_repo_head_hexsha": "654dca390e635b6294a8b5066727d0f4d6736eb1", "max_forks_repo_licenses": ["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.1538461538, "max_line_length": 151, "alphanum_fraction": 0.6212905452, "num_tokens": 1789, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.4978559210814802}}
{"text": "#ifndef STAN_OPTIMIZATION_BFGS_LINESEARCH_HPP\r\n#define STAN_OPTIMIZATION_BFGS_LINESEARCH_HPP\r\n\r\n#include <boost/math/special_functions/fpclassify.hpp>\r\n#include <algorithm>\r\n#include <cmath>\r\n#include <cstdlib>\r\n#include <string>\r\n#include <limits>\r\n\r\nnamespace stan {\r\n  namespace optimization {\r\n    /**\r\n     * Find the minima in an interval [loX, hiX] of a cubic function which\r\n     * interpolates the points, function values and gradients provided.\r\n     *\r\n     * Implicitly, this function constructs an interpolating polynomial\r\n     *     g(x) = a_3 x^3 + a_2 x^2 + a_1 x + a_0\r\n     * such that g(0) = 0, g(x1) = f1, g'(0) = df0, g'(x1) = df1 where\r\n     *     g'(x) = 3 a_3 x^2 + 2 a_2 x + a_1\r\n     * is the derivative of g(x).  It then computes the roots of g'(x) and\r\n     * finds the minimal value of g(x) on the interval [loX,hiX] including\r\n     * the end points.\r\n     *\r\n     * This function implements the full parameter version of CubicInterp().\r\n     *\r\n     * @param df0 First derivative value, f'(x0)\r\n     * @param x1 Second point\r\n     * @param f1 Second function value, f(x1)\r\n     * @param df1 Second derivative value, f'(x1)\r\n     * @param loX Lower bound on the interval of solutions\r\n     * @param hiX Upper bound on the interval of solutions\r\n     **/\r\n    template<typename Scalar>\r\n    Scalar CubicInterp(const Scalar &df0,\r\n                       const Scalar &x1, const Scalar &f1, const Scalar &df1,\r\n                       const Scalar &loX, const Scalar &hiX) {\r\n      const Scalar c3((-12*f1 + 6*x1*(df0 + df1))/(x1*x1*x1));\r\n      const Scalar c2(-(4*df0 + 2*df1)/x1 + 6*f1/(x1*x1));\r\n      const Scalar &c1(df0);\r\n\r\n      const Scalar t_s = std::sqrt(c2*c2 - 2.0*c1*c3);\r\n      const Scalar s1 = - (c2 + t_s)/c3;\r\n      const Scalar s2 = - (c2 - t_s)/c3;\r\n\r\n      Scalar tmpF;\r\n      Scalar minF, minX;\r\n\r\n      // Check value at lower bound\r\n      minF = loX*(loX*(loX*c3/3.0 + c2)/2.0 + c1);\r\n      minX = loX;\r\n\r\n      // Check value at upper bound\r\n      tmpF = hiX*(hiX*(hiX*c3/3.0 + c2)/2.0 + c1);\r\n      if (tmpF < minF) {\r\n        minF = tmpF;\r\n        minX = hiX;\r\n      }\r\n\r\n      // Check value of first root\r\n      if (loX < s1 && s1 < hiX) {\r\n        tmpF = s1*(s1*(s1*c3/3.0 + c2)/2.0 + c1);\r\n        if (tmpF < minF) {\r\n          minF = tmpF;\r\n          minX = s1;\r\n        }\r\n      }\r\n\r\n      // Check value of second root\r\n      if (loX < s2 && s2 < hiX) {\r\n        tmpF = s2*(s2*(s2*c3/3.0 + c2)/2.0 + c1);\r\n        if (tmpF < minF) {\r\n          minF = tmpF;\r\n          minX = s2;\r\n        }\r\n      }\r\n\r\n      return minX;\r\n    }\r\n\r\n    /**\r\n     * Find the minima in an interval [loX, hiX] of a cubic function which\r\n     * interpolates the points, function values and gradients provided.\r\n     *\r\n     * Implicitly, this function constructs an interpolating polynomial\r\n     *     g(x) = a_3 x^3 + a_2 x^2 + a_1 x + a_0\r\n     * such that g(x0) = f0, g(x1) = f1, g'(x0) = df0, g'(x1) = df1 where\r\n     *     g'(x) = 3 a_3 x^2 + 2 a_2 x + a_1\r\n     * is the derivative of g(x).  It then computes the roots of g'(x) and\r\n     * finds the minimal value of g(x) on the interval [loX,hiX] including\r\n     * the end points.\r\n     *\r\n     * @param x0 First point\r\n     * @param f0 First function value, f(x0)\r\n     * @param df0 First derivative value, f'(x0)\r\n     * @param x1 Second point\r\n     * @param f1 Second function value, f(x1)\r\n     * @param df1 Second derivative value, f'(x1)\r\n     * @param loX Lower bound on the interval of solutions\r\n     * @param hiX Upper bound on the interval of solutions\r\n     **/\r\n    template<typename Scalar>\r\n    Scalar CubicInterp(const Scalar &x0, const Scalar &f0, const Scalar &df0,\r\n                       const Scalar &x1, const Scalar &f1, const Scalar &df1,\r\n                       const Scalar &loX, const Scalar &hiX) {\r\n      return x0 + CubicInterp(df0, x1-x0, f1-f0, df1, loX-x0, hiX-x0);\r\n    }\r\n\r\n    /**\r\n     * An internal utility function for implementing WolfeLineSearch()\r\n     **/\r\n    template<typename FunctorType, typename Scalar, typename XType>\r\n    int WolfLSZoom(Scalar &alpha, XType &newX, Scalar &newF, XType &newDF,\r\n                   FunctorType &func,\r\n                   const XType &x, const Scalar &f, const Scalar &dfp,\r\n                   const Scalar &c1dfp, const Scalar &c2dfp, const XType &p,\r\n                   Scalar alo, Scalar aloF, Scalar aloDFp,\r\n                   Scalar ahi, Scalar ahiF, Scalar ahiDFp,\r\n                   const Scalar &min_range) {\r\n      Scalar d1, d2, newDFp;\r\n      int itNum(0);\r\n\r\n      while (1) {\r\n        itNum++;\r\n\r\n        if (std::fabs(alo-ahi) < min_range)\r\n          return 1;\r\n\r\n        if (itNum%5 == 0) {\r\n          alpha = 0.5*(alo+ahi);\r\n        } else {\r\n          // Perform cubic interpolation to determine next point to try\r\n          d1 = aloDFp + ahiDFp - 3*(aloF-ahiF)/(alo-ahi);\r\n          d2 = std::sqrt(d1*d1 - aloDFp*ahiDFp);\r\n          if (ahi < alo)\r\n            d2 = -d2;\r\n          alpha = ahi\r\n            - (ahi - alo) * (ahiDFp + d2 - d1) / (ahiDFp - aloDFp + 2*d2);\r\n          if (!boost::math::isfinite(alpha) ||\r\n              alpha < std::min(alo, ahi) + 0.01 * std::fabs(alo - ahi) ||\r\n              alpha > std::max(alo, ahi) - 0.01 * std::fabs(alo - ahi))\r\n            alpha = 0.5 * (alo + ahi);\r\n        }\r\n\r\n        newX = x + alpha * p;\r\n        while (func(newX, newF, newDF)) {\r\n          alpha = 0.5 * (alpha + std::min(alo, ahi));\r\n          if (std::fabs(std::min(alo, ahi) - alpha) < min_range)\r\n            return 1;\r\n          newX = x + alpha * p;\r\n        }\r\n        newDFp = newDF.dot(p);\r\n        if (newF > (f + alpha * c1dfp) || newF >= aloF) {\r\n          ahi = alpha;\r\n          ahiF = newF;\r\n          ahiDFp = newDFp;\r\n        } else {\r\n          if (std::fabs(newDFp) <= -c2dfp)\r\n            break;\r\n          if (newDFp*(ahi-alo) >= 0) {\r\n            ahi = alo;\r\n            ahiF = aloF;\r\n            ahiDFp = aloDFp;\r\n          }\r\n          alo = alpha;\r\n          aloF = newF;\r\n          aloDFp = newDFp;\r\n        }\r\n      }\r\n      return 0;\r\n    }\r\n\r\n    /**\r\n     * Perform a line search which finds an approximate solution to:\r\n     * \\f[\r\n     *       \\min_\\alpha f(x_0 + \\alpha p)\r\n     * \\f]\r\n     * satisfying the strong Wolfe conditions:\r\n     *  1) \\f$ f(x_0 + \\alpha p) \\leq f(x_0) + c_1 \\alpha p^T g(x_0) \\f$\r\n     *  2) \\f$ \\vert p^T g(x_0 + \\alpha p) \\vert \\leq c_2 \\vert p^T g(x_0) \\vert \\f$\r\n     * where \\f$g(x) = \\frac{\\partial f}{\\partial x}\\f$ is the gradient of f(x).\r\n     *\r\n     * @tparam FunctorType A type which supports being called as\r\n     *        ret = func(x,f,g)\r\n     * where x is the input point, f and g are the function value and\r\n     * gradient at x and ret is non-zero if function evaluation fails.\r\n     *\r\n     * @param func Function which is being minimized.\r\n     *\r\n     * @param alpha First value of \\f$ \\alpha \\f$ to try.  Upon return this\r\n     * contains the final value of the \\f$ \\alpha \\f$.\r\n     *\r\n     * @param x1 Final point, equal to \\f$ x_0 + \\alpha p \\f$.\r\n     *\r\n     * @param f1 Final point function value, equal to \\f$ f(x_0 + \\alpha p) \\f$.\r\n     *\r\n     * @param gradx1 Final point gradient, equal to \\f$ g(x_0 + \\alpha p) \\f$.\r\n     *\r\n     * @param p Search direction.  It is assumed to be a descent direction such\r\n     * that \\f$ p^T g(x_0) < 0 \\f$.\r\n     *\r\n     * @param x0 Value of starting point, \\f$ x_0 \\f$.\r\n     *\r\n     * @param f0 Value of function at starting point, \\f$ f(x_0) \\f$.\r\n     *\r\n     * @param gradx0 Value of function gradient at starting point,\r\n     *    \\f$ g(x_0) \\f$.\r\n     *\r\n     * @param c1 Parameter of the Wolfe conditions. \\f$ 0 < c_1 < c_2 < 1 \\f$\r\n     * Typically c1 = 1e-4.\r\n     *\r\n     * @param c2 Parameter of the Wolfe conditions. \\f$ 0 < c_1 < c_2 < 1 \\f$\r\n     * Typically c2 = 0.9.\r\n     *\r\n     * @param minAlpha Smallest allowable step-size.\r\n     *\r\n     * @param maxLSIts Maximum number line search iterations.\r\n     *\r\n     * @param maxLSRestarts Maximum number of times line search will\r\n     * restart with \\f$ f() \\f$ failing.\r\n     *\r\n     * @return Returns zero on success, non-zero otherwise.\r\n     **/\r\n    template<typename FunctorType, typename Scalar, typename XType>\r\n    int WolfeLineSearch(FunctorType &func,\r\n                        Scalar &alpha,\r\n                        XType &x1, Scalar &f1, XType &gradx1,\r\n                        const XType &p,\r\n                        const XType &x0, const Scalar &f0, const XType &gradx0,\r\n                        const Scalar &c1, const Scalar &c2,\r\n                        const Scalar &minAlpha, const Scalar &maxLSIts,\r\n                        const Scalar &maxLSRestarts) {\r\n      const Scalar dfp(gradx0.dot(p));\r\n      const Scalar c1dfp(c1*dfp);\r\n      const Scalar c2dfp(c2*dfp);\r\n\r\n      Scalar alpha0(minAlpha);\r\n      Scalar alpha1(alpha);\r\n\r\n      Scalar prevF(f0);\r\n      XType prevDF(gradx0);\r\n      Scalar prevDFp(dfp);\r\n      Scalar newDFp;\r\n\r\n      int retCode = 0, nits = 0, lsRestarts = 0, ret;\r\n\r\n      while (1) {\r\n        if (nits >= maxLSIts) {\r\n          retCode = 1;\r\n          break;\r\n        }\r\n\r\n        x1.noalias() = x0 + alpha1 * p;\r\n        ret = func(x1, f1, gradx1);\r\n        if (ret != 0) {\r\n          if (lsRestarts >= maxLSRestarts) {\r\n            retCode = 1;\r\n            break;\r\n          }\r\n\r\n          alpha1 = 0.5 * (alpha0 + alpha1);\r\n          lsRestarts++;\r\n          continue;\r\n        }\r\n        lsRestarts = 0;\r\n\r\n        newDFp = gradx1.dot(p);\r\n        if ((f1 > f0 + alpha * c1dfp) || (f1 >= prevF && nits > 0)) {\r\n          retCode = WolfLSZoom(alpha, x1, f1, gradx1,\r\n                               func,\r\n                               x0, f0, dfp,\r\n                               c1dfp, c2dfp, p,\r\n                               alpha0, prevF, prevDFp,\r\n                               alpha1, f1, newDFp,\r\n                               1e-16);\r\n          break;\r\n        }\r\n        if (std::fabs(newDFp) <= -c2dfp) {\r\n          alpha = alpha1;\r\n          break;\r\n        }\r\n        if (newDFp >= 0) {\r\n          retCode = WolfLSZoom(alpha, x1, f1, gradx1,\r\n                               func,\r\n                               x0, f0, dfp,\r\n                               c1dfp, c2dfp, p,\r\n                               alpha1, f1, newDFp,\r\n                               alpha0, prevF, prevDFp,\r\n                               1e-16);\r\n          break;\r\n        }\r\n\r\n        alpha0 = alpha1;\r\n        prevF = f1;\r\n        std::swap(prevDF, gradx1);\r\n        prevDFp = newDFp;\r\n\r\n        alpha1 *= 10.0;\r\n\r\n        nits++;\r\n      }\r\n      return retCode;\r\n    }\r\n  }\r\n}\r\n\r\n#endif\r\n", "meta": {"hexsha": "132e5a246f95499cca8424b50fbe002c73b00bdb", "size": 10648, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "archive/stan/src/stan/optimization/bfgs_linesearch.hpp", "max_stars_repo_name": "alashworth/stan-monorepo", "max_stars_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-06T15:53:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-06T15:53:17.000Z", "max_issues_repo_path": "archive/stan/src/stan/optimization/bfgs_linesearch.hpp", "max_issues_repo_name": "alashworth/stan-monorepo", "max_issues_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-01-17T18:51:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-17T18:51:39.000Z", "max_forks_repo_path": "archive/stan/src/stan/optimization/bfgs_linesearch.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.5714285714, "max_line_length": 85, "alphanum_fraction": 0.4968069121, "num_tokens": 3187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.4978559210814802}}
{"text": "//\n// Created by yanhang on 4/21/16.\n//\n\n#include \"warping.h\"\n#include \"gridenergy.h\"\n#include \"utility.h\"\n#include <Eigen/Sparse>\n#include <Eigen/SPQRSupport>\n#include <fstream>\n\nusing namespace std;\nusing namespace Eigen;\nusing namespace cv;\n\nnamespace substab{\n\n\tGridWarpping::GridWarpping(const int w, const int h, const int gw, const int gh) : width(w), height(h), gridW(gw), gridH(gh) {\n\t\tblockW = (double) width / gridW;\n\t\tblockH = (double) height / gridH;\n\t\tgridLoc.resize((size_t) (gridW + 1) * (gridH + 1));\n\t\tfor (auto x = 0; x <= gridW; ++x) {\n\t\t\tfor (auto y = 0; y <= gridH; ++y) {\n\t\t\t\tgridLoc[y * (gridW + 1) + x] = Eigen::Vector2d(blockW * x, blockH * y);\n\t\t\t\tif (x == gridW)\n\t\t\t\t\tgridLoc[y * (gridW + 1) + x][0] -= 1.1;\n\t\t\t\tif (y == gridH)\n\t\t\t\t\tgridLoc[y * (gridW + 1) + x][1] -= 1.1;\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid GridWarpping::getGridIndAndWeight(const Eigen::Vector2d &pt, Eigen::Vector4i &ind,\n\t\t\t\t\t\t\t\t\t\t   Eigen::Vector4d &w) const {\n\t\tCHECK_LE(pt[0], width - 1);\n\t\tCHECK_LE(pt[1], height - 1);\n\t\tint x = (int) floor(pt[0] / blockW);\n\t\tint y = (int) floor(pt[1] / blockH);\n\n\t\t//////////////\n\t\t// 1--2\n\t\t// |  |\n\t\t// 4--3\n\t\t/////////////\n\t\tind = Vector4i(y * (gridW + 1) + x, y * (gridW + 1) + x + 1, (y + 1) * (gridW + 1) + x + 1,\n\t\t\t\t\t   (y + 1) * (gridW + 1) + x);\n\n\t\tconst double &xd = pt[0];\n\t\tconst double &yd = pt[1];\n\t\tconst double xl = gridLoc[ind[0]][0];\n\t\tconst double xh = gridLoc[ind[2]][0];\n\t\tconst double yl = gridLoc[ind[0]][1];\n\t\tconst double yh = gridLoc[ind[2]][1];\n\n\t\tw[0] = (xh - xd) * (yh - yd);\n\t\tw[1] = (xd - xl) * (yh - yd);\n\t\tw[2] = (xd - xl) * (yd - yl);\n\t\tw[3] = (xh - xd) * (yd - yl);\n\n\t\tdouble s = w[0] + w[1] + w[2] + w[3];\n\t\tCHECK_GT(s, 0) << pt[0] << ' '<< pt[1];\n\t\tw = w / s;\n\n\t\tVector2d pt2 =\n\t\t\t\tgridLoc[ind[0]] * w[0] + gridLoc[ind[1]] * w[1] + gridLoc[ind[2]] * w[2] + gridLoc[ind[3]] * w[3];\n\t\tdouble error = (pt2 - pt).norm();\n\t\tCHECK_LT(error, 0.0001) << pt[0] << ' ' << pt[1] << ' ' << pt2[0] << ' ' << pt2[1];\n\t}\n\n\n\tvoid GridWarpping::visualizeGrid(const std::vector<Eigen::Vector2d>& grid, cv::Mat &img) const {\n\t\tCHECK_EQ(grid.size(), gridLoc.size());\n\t\tCHECK_EQ(img.cols, width);\n\t\tCHECK_EQ(img.rows, height);\n\t\t//img = Mat(height, width, CV_8UC3, Scalar(0,0,0));\n\t\tfor(auto gy=0; gy<gridH; ++gy) {\n\t\t\tfor (auto gx = 0; gx < gridW; ++gx){\n\t\t\t\tconst int gid1 = gy * (gridW+1) + gx;\n\t\t\t\tconst int gid2 = (gy+1) * (gridW+1) + gx;\n\t\t\t\tconst int gid3 = (gy+1)*(gridW+1)+gx+1;\n\t\t\t\tconst int gid4= gy * (gridW+1) + gx+1;\n\t\t\t\tif(grid[gid1][0] > 0 && grid[gid2][0] > 0)\n\t\t\t\t\tcv::line(img, cv::Point(grid[gid1][0], grid[gid1][1]), cv::Point(grid[gid2][0], grid[gid2][1]), Scalar(255,255,255));\n\t\t\t\tif(grid[gid2][0] > 0 && grid[gid3][0] > 0)\n\t\t\t\t\tcv::line(img, cv::Point(grid[gid2][0], grid[gid2][1]), cv::Point(grid[gid3][0], grid[gid3][1]), Scalar(255,255,255));\n\t\t\t\tif(grid[gid3][0] > 0 && grid[gid4][0] > 0)\n\t\t\t\t\tcv::line(img, cv::Point(grid[gid3][0], grid[gid3][1]), cv::Point(grid[gid4][0], grid[gid4][1]), Scalar(255,255,255));\n\t\t\t\tif(grid[gid4][0] > 0 && grid[gid1][0] > 0)\n\t\t\t\t\tcv::line(img, cv::Point(grid[gid4][0], grid[gid4][1]), cv::Point(grid[gid1][0], grid[gid1][1]), Scalar(255,255,255));\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid GridWarpping::computeSimilarityWeight(const cv::Mat &input, std::vector<double>& saliency) const {\n\t\tsaliency.resize((size_t)(gridW*gridH));\n\t\tfor(auto y=0; y<gridH; ++y){\n\t\t\tfor(auto x=0; x<gridW; ++x){\n\t\t\t\tconst int gid = gridInd(x,y);\n\t\t\t\tvector<vector<double> > pixs(3);\n\t\t\t\tfor(auto x1=(int)gridLoc[gridInd(x,y)][0]; x1<gridLoc[gridInd(x+1,y+1)][0]; ++x1){\n\t\t\t\t\tfor(auto y1=(int)gridLoc[gridInd(x,y)][1]; y1<gridLoc[gridInd(x+1,y+1)][1]; ++y1){\n\t\t\t\t\t\tVec3b pix = input.at<Vec3b>(y1,x1);\n\t\t\t\t\t\tpixs[0].push_back((double)pix[0] / 255.0);\n\t\t\t\t\t\tpixs[1].push_back((double)pix[1] / 255.0);\n\t\t\t\t\t\tpixs[2].push_back((double)pix[2] / 255.0);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tVector3d vars(math_util::variance(pixs[0]),math_util::variance(pixs[1]),math_util::variance(pixs[2]));\n\t\t\t\tsaliency[gid] = vars.norm();\n\t\t\t}\n\t\t}\n\t}\n\n\n\tvoid GridWarpping::warpImageCloseForm(const cv::Mat &input, cv::Mat &output, const vector<Vector2d>& pts1, const vector<Vector2d>& pts2, const int id) const {\n\t\tCHECK_EQ(pts1.size(), pts2.size());\n\n\t\tchar buffer[1024] = {};\n\n\t\tvector<Vector2d> resGrid(gridLoc.size());\n\t\tconst int kDataTerm = (int)pts1.size() * 2;\n\t\tconst int kSimTerm = (gridW-1)*(gridH-1)*8;\n\t\tconst int kVar = (int)gridLoc.size() * 2;\n\n\t\tvector<Eigen::Triplet<double> > triplets;\n\t\tVectorXd B(kDataTerm+kSimTerm);\n\t\t//add data constraint\n\t\tconst double wdata = 1.0;\n\t\tconst double wsimilarity = 20;\n\t\tint cInd = 0;\n\t\tfor(auto i=0; i<pts2.size(); ++i) {\n\t\t\tif (pts2[i][0] < 0 || pts2[i][1] < 0 || pts2[i][0] >= width - 1 || pts2[i][1] >= height - 1)\n\t\t\t\tcontinue;\n\t\t\tVector4i indRef;\n\t\t\tVector4d bwRef;\n\t\t\tCHECK_LT(cInd + 1, B.rows());\n\n\t\t\tgetGridIndAndWeight(pts2[i], indRef, bwRef);\n\t\t\tfor (auto j = 0; j < 4; ++j) {\n\t\t\t\tCHECK_LT(indRef[j]*2+1, kVar);\n\t\t\t\ttriplets.push_back(Triplet<double>(cInd, indRef[j] * 2, wdata * bwRef[j]));\n\t\t\t\ttriplets.push_back(Triplet<double>(cInd + 1, indRef[j] * 2 + 1, wdata * bwRef[j]));\n\t\t\t}\n\t\t\tB[cInd] = wdata * pts1[i][0];\n\t\t\tB[cInd + 1] = wdata * pts1[i][1];\n\t\t\tcInd += 2;\n\t\t}\n\n\t\t// Mat inputOutput = input.clone();\n\t\t// visualizeGrid(gridLoc, inputOutput);\n\t\t// for(const auto& pt: pts1)\n\t\t// \tcv::circle(inputOutput, cv::Point2d(pt[0], pt[1]), 1, Scalar(0,0,255), 2);\n\t\t// sprintf(buffer, \"vis_input%05d.jpg\", id);\n\t\t// imwrite(buffer, inputOutput);\n\n//\t\tvector<double> saliency;\n//\t\tcomputeSimilarityWeight(input, saliency);\n\n\t\tauto getLocalCoord = [](const Vector2d& p1, const Vector2d& p2, const Vector2d& p3){\n\t\t\tVector2d axis1 = p3 - p2;\n\t\t\tVector2d axis2(-1*axis1[1], axis1[0]);\n\t\t\tVector2d v = p1 - p2;\n\t\t\treturn Vector2d(v.dot(axis1)/axis1.squaredNorm(), v.dot(axis2)/axis2.squaredNorm());\n\t\t};\n\t\t{\n\t\t\t//test for local coord\n//\t\t\tVector2d p1(0,0), p2(0,-1), p3(1,0);\n//\t\t\tVector2d uv = getLocalCoord(p1,p2,p3);\n//\t\t\tprintf(\"(%.2f,%.2f)\\n\", uv[0], uv[1]);\n\t\t}\n\t\tfor(auto y=1; y< gridH; ++y) {\n\t\t\tfor (auto x = 1; x < gridW; ++x) {\n\t\t\t\tvector<Vector2i> gids{\n\t\t\t\t\t\tVector2i(gridInd(x - 1, y), gridInd(x, y - 1)),\n\t\t\t\t\t\tVector2i(gridInd(x, y - 1), gridInd(x + 1, y)),\n\t\t\t\t\t\tVector2i(gridInd(x + 1, y), gridInd(x, y + 1)),\n\t\t\t\t\t\tVector2i(gridInd(x, y + 1), gridInd(x - 1, y))\n\t\t\t\t};\n\t\t\t\tconst int cgid = gridInd(x, y);\n//\t\t\t\tprintf(\"-----------------------\\n\");\n\t\t\t\tfor (const auto &gid: gids) {\n\t\t\t\t\tVector2d refUV = getLocalCoord(gridLoc[cgid], gridLoc[gid[0]], gridLoc[gid[1]]);\n//\t\t\t\t\tprintf(\"(%.2f,%.2f),(%.2f,%.2f),(%.2f,%.2f), u:%.2f,v:%.2f\\n\", gridLoc[cgid][0], gridLoc[cgid][1],\n//\t\t\t\t\t\t   gridLoc[gid[0]][0], gridLoc[gid[0]][1], gridLoc[gid[1]][0], gridLoc[gid[1]][1], refUV[0],\n//\t\t\t\t\t\t   refUV[1]);\n\t\t\t\t\t//x coordinate\n\t\t\t\t\ttriplets.push_back(Triplet<double>(cInd, cgid * 2, wsimilarity));\n\t\t\t\t\ttriplets.push_back(Triplet<double>(cInd, gid[0]*2, -1 * wsimilarity));\n\t\t\t\t\ttriplets.push_back(Triplet<double>(cInd, gid[0] * 2, refUV[0] * wsimilarity));\n\t\t\t\t\ttriplets.push_back(Triplet<double>(cInd, gid[1] * 2, -1 * refUV[0] * wsimilarity));\n\n\t\t\t\t\ttriplets.push_back(Triplet<double>(cInd, gid[0] * 2 + 1, -1 * refUV[1] * wsimilarity));\n\t\t\t\t\ttriplets.push_back(Triplet<double>(cInd, gid[1] * 2 + 1, refUV[1] * wsimilarity));\n\t\t\t\t\tB[cInd] = 0;\n\n\t\t\t\t\t//y coordinate\n\t\t\t\t\ttriplets.push_back(Triplet<double>(cInd + 1, cgid * 2 + 1, wsimilarity));\n\t\t\t\t\ttriplets.push_back(Triplet<double>(cInd + 1, gid[0] * 2 + 1, -1 * wsimilarity));\n\t\t\t\t\ttriplets.push_back(Triplet<double>(cInd + 1, gid[0] * 2 + 1, refUV[0] * wsimilarity));\n\t\t\t\t\ttriplets.push_back(Triplet<double>(cInd + 1, gid[1] * 2 + 1, -1 * refUV[0] * wsimilarity));\n\t\t\t\t\ttriplets.push_back(Triplet<double>(cInd + 1, gid[0] * 2, refUV[1] * wsimilarity));\n\t\t\t\t\ttriplets.push_back(Triplet<double>(cInd + 1, gid[1] * 2, -1 * refUV[1] * wsimilarity));\n\t\t\t\t\tB[cInd + 1] = 0;\n\t\t\t\t\tcInd += 2;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n//\t\tconst double wregular = 0.1;\n//\t\tfor(auto x=0; x<=gridW; ++x){\n//\t\t\tfor(auto y=0; y<=gridH; ++y){\n//\t\t\t\tint gid = gridInd(x,y);\n//\t\t\t\ttriplets.push_back(Triplet<double>(cInd, gid*2, wregular));\n//\t\t\t\ttriplets.push_back(Triplet<double>(cInd+1, gid*2+1, wregular));\n//\t\t\t\tB[cInd] = wregular * gridLoc[gid][0];\n//\t\t\t\tB[cInd+1] = wregular * gridLoc[gid][1];\n//\t\t\t\tcInd +=2;\n//\t\t\t}\n//\t\t}\n\t\tCHECK_LE(cInd, kDataTerm+kSimTerm);\n\t\tSparseMatrix<double> A(cInd, kVar);\n\t\tA.setFromTriplets(triplets.begin(), triplets.end());\n\n\t\tEigen::SPQR<SparseMatrix<double> > solver(A);\n\t\tVectorXd res = solver.solve(B.block(0,0,cInd,1));\n\t\tCHECK_EQ(res.rows(), kVar);\n\n\t\tvector<Vector2d> vars(gridLoc.size());\n\t\tfor(auto i=0; i<vars.size(); ++i){\n\t\t\tvars[i][0] = res[2*i];\n\t\t\tvars[i][1] = res[2*i+1];\n\t\t}\n\n\t\toutput = Mat(height, width, CV_8UC3, Scalar::all(0));\n\t\tfor(auto y=0; y<height; ++y){\n\t\t\tfor(auto x=0; x<width; ++x){\n\t\t\t\tVector4i ind;\n\t\t\t\tVector4d w;\n\t\t\t\tgetGridIndAndWeight(Vector2d(x,y), ind, w);\n\t\t\t\tVector2d pt(0,0);\n\t\t\t\tfor(auto i=0; i<4; ++i){\n\t\t\t\t\tpt[0] += vars[ind[i]][0] * w[i];\n\t\t\t\t\tpt[1] += vars[ind[i]][1] * w[i];\n\t\t\t\t}\n\t\t\t\tif(pt[0] < 0 || pt[1] < 0 || pt[0] > width - 1 || pt[1] > height - 1)\n\t\t\t\t\tcontinue;\n\t\t\t\tVector3d pixO = interpolation_util::bilinear<uchar,3>(input.data, input.cols, input.rows, pt);\n\t\t\t\toutput.at<Vec3b>(y,x) = Vec3b((uchar) pixO[0], (uchar)pixO[1], (uchar)pixO[2]);\n\t\t\t}\n\t\t}\n\n\t\t// Mat outputOutput = input.clone();\n\t\t// visualizeGrid(vars, outputOutput);\n\t\t// for(const auto& pt: pts2)\n\t\t// \tcv::circle(outputOutput, cv::Point2d(pt[0], pt[1]), 1, Scalar(0,0,255), 2);\n\t\t// sprintf(buffer, \"vis_output%05d.jpg\", id);\n\t\t// imwrite(buffer, outputOutput);\n\t}\n\n}//namespace substablas\n", "meta": {"hexsha": "739ac504279c9c704869fb443d3a7e13b5188f7c", "size": 9557, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/warping.cpp", "max_stars_repo_name": "ishank-juneja/SubspaceStab", "max_stars_repo_head_hexsha": "3c4ee8c001a7c4864870f30c880d389790500ea0", "max_stars_repo_licenses": ["MIT"], "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/warping.cpp", "max_issues_repo_name": "ishank-juneja/SubspaceStab", "max_issues_repo_head_hexsha": "3c4ee8c001a7c4864870f30c880d389790500ea0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-05-29T17:19:37.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-12T17:03:13.000Z", "max_forks_repo_path": "code/warping.cpp", "max_forks_repo_name": "ishank-juneja/SubspaceStab", "max_forks_repo_head_hexsha": "3c4ee8c001a7c4864870f30c880d389790500ea0", "max_forks_repo_licenses": ["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.6168582375, "max_line_length": 159, "alphanum_fraction": 0.5770639322, "num_tokens": 3749, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.4978559210814802}}
{"text": "// Parse memory specifications like \"100 MB\" orr \"100MiB\"\n// Authors: Adrien Barral, Max Schwarz\n\n#include \"bytes_parser.h\"\n\n#include <boost/spirit/include/classic.hpp>\n#include <boost/spirit/include/phoenix_core.hpp>\n#include <boost/spirit/include/phoenix_operator.hpp>\n#include <boost/spirit/include/qi.hpp>\n\n#include <ros/console.h>\n\nnamespace rosmon\n{\nnamespace launch\n{\n\nstd::tuple<uint64_t, bool> parseMemory(const std::string& memory)\n{\n\tusing boost::phoenix::ref;\n\tusing boost::spirit::qi::_1;\n\tusing boost::spirit::qi::double_;\n\tusing boost::spirit::qi::no_case;\n\tusing boost::spirit::qi::phrase_parse;\n\n\tstruct bytes_decades_ : boost::spirit::qi::symbols<char, uint64_t>\n\t{\n\t\tbytes_decades_(){\n\t\t\tadd(\"kB\", 1e3)(\"mB\", 1e6)(\"gB\", 1e9)(\"tB\", 1e12)(\"KB\", 1e3)(\"MB\", 1e6)(\"GB\", 1e9)(\n\t\t\t\t\"TB\", 1e12)(\"B\", 1)(\"KiB\", static_cast<uint64_t>(1ull<<10))(\"MiB\",\n\t\t\t\tstatic_cast<uint64_t>(1ull<<20))(\"GiB\", static_cast<uint64_t>(1ull<<30))(\"TiB\",\n\t\t\t\tstatic_cast<uint64_t>(1ull<<40));\n\t\t}\n\t} byte_decades;\n\n\tauto it = memory.begin();\n\tdouble res = 0.0;\n\tbool ok = phrase_parse(it, memory.end(),\n\t\t(double_[ref(res) = _1] >> -(byte_decades[ref(res) *= _1])),\n\t\tboost::spirit::ascii::space\n\t);\n\n\treturn std::make_tuple(static_cast<uint64_t>(res), ok);\n}\n\n}\n}\n", "meta": {"hexsha": "93cbf15ff6c4c1bd8f9da13b4acb413df69cdac2", "size": 1255, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rosmon_core/src/launch/bytes_parser.cpp", "max_stars_repo_name": "Rogerpi/rosmon", "max_stars_repo_head_hexsha": "abdae1f8bb4f8684ea45fb36f4fe7730bcd102ea", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 134.0, "max_stars_repo_stars_event_min_datetime": "2017-06-17T23:05:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T11:48:15.000Z", "max_issues_repo_path": "rosmon_core/src/launch/bytes_parser.cpp", "max_issues_repo_name": "Rogerpi/rosmon", "max_issues_repo_head_hexsha": "abdae1f8bb4f8684ea45fb36f4fe7730bcd102ea", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 129.0, "max_issues_repo_issues_event_min_datetime": "2015-07-31T12:23:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-20T10:21:32.000Z", "max_forks_repo_path": "rosmon_core/src/launch/bytes_parser.cpp", "max_forks_repo_name": "Rogerpi/rosmon", "max_forks_repo_head_hexsha": "abdae1f8bb4f8684ea45fb36f4fe7730bcd102ea", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 59.0, "max_forks_repo_forks_event_min_datetime": "2015-12-15T13:17:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-27T18:09:16.000Z", "avg_line_length": 26.1458333333, "max_line_length": 85, "alphanum_fraction": 0.6796812749, "num_tokens": 399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.49785591486556674}}
{"text": "//============================================================================\n//\n// This file is part of the Thea toolkit.\n//\n// This software is distributed under the BSD license, as detailed in the\n// accompanying LICENSE.txt file. Portions are derived from other works:\n// their respective licenses and copyright information are reproduced in\n// LICENSE.txt and/or in the relevant source files.\n//\n// Author: Siddhartha Chaudhuri\n// First version: 2019\n//\n//============================================================================\n\n#ifndef __Thea_MatVec_hpp__\n#define __Thea_MatVec_hpp__\n\n#include \"Common.hpp\"\n#include \"MatrixFormat.hpp\"\n\n// Resolve a conflict between X.h (which #defines Success) and Eigen (which has an enum called Success). Fortunately both\n// headers currently assign the same value to Success (0) so the #undef should be all that's needed.\n// https://stackoverflow.com/questions/22400905/eigen-and-cimg-compatibility-issues\n#ifdef Success\n#  undef Success\n#endif\n#include <Eigen/Core>\n#include <Eigen/Geometry>  // for Quaternion, and because for some weird reason Eigen defines cross() here\n\n#include <complex>\n\nnamespace Thea {\n\n#ifdef THEA_ROW_MAJOR\n  int const DEFAULT_MATRIX_LAYOUT = MatrixLayout::ROW_MAJOR;\n#else  // nothing provided or THEA_COLUMN_MAJOR defined\n  int const DEFAULT_MATRIX_LAYOUT = MatrixLayout::COLUMN_MAJOR;\n#endif\n\n// Typedef common instantiations. These are fully instantiated and have no further template parameters.\n// Alignment is DISABLED for fixed-size vectorizable types (Vector4f, Matrix4f, Vector2d etc). These require special handling\n// for every class which directly or indirectly has such a member, and could lead to unexpected bugs and considerably less ease\n// of use.\n//\n// See:\n// - http://eigen.tuxfamily.org/dox/group__TopicStructHavingEigenMembers.html\n// - https://eigen.tuxfamily.org/dox/group__TopicStlContainers.html\n// - http://eigen.tuxfamily.org/dox/group__TopicFixedSizeVectorizable.html\n// - https://stackoverflow.com/q/41087043\n//\n#define THEA_DECL_MATRIX_TYPEDEFS(scalar, suffix)                                                                             \\\n    typedef Eigen::Matrix< scalar, 2, 2,              DEFAULT_MATRIX_LAYOUT      | Eigen::DontAlign >  Matrix2    ## suffix;  \\\n    typedef Eigen::Matrix< scalar, 3, 3,              DEFAULT_MATRIX_LAYOUT      | Eigen::DontAlign >  Matrix3    ## suffix;  \\\n    typedef Eigen::Matrix< scalar, 4, 4,              DEFAULT_MATRIX_LAYOUT      | Eigen::DontAlign >  Matrix4    ## suffix;  \\\n    typedef Eigen::Matrix< scalar, 2, 1,              MatrixLayout::COLUMN_MAJOR | Eigen::DontAlign >  Vector2    ## suffix;  \\\n    typedef Eigen::Matrix< scalar, 3, 1,              MatrixLayout::COLUMN_MAJOR | Eigen::DontAlign >  Vector3    ## suffix;  \\\n    typedef Eigen::Matrix< scalar, 4, 1,              MatrixLayout::COLUMN_MAJOR | Eigen::DontAlign >  Vector4    ## suffix;  \\\n    typedef Eigen::Matrix< scalar, 1, 2,              MatrixLayout::ROW_MAJOR    | Eigen::DontAlign >  RowVector2 ## suffix;  \\\n    typedef Eigen::Matrix< scalar, 1, 3,              MatrixLayout::ROW_MAJOR    | Eigen::DontAlign >  RowVector3 ## suffix;  \\\n    typedef Eigen::Matrix< scalar, 1, 4,              MatrixLayout::ROW_MAJOR    | Eigen::DontAlign >  RowVector4 ## suffix;  \\\n    typedef Eigen::Matrix< scalar, 2, Eigen::Dynamic, DEFAULT_MATRIX_LAYOUT                         >  Matrix2X   ## suffix;  \\\n    typedef Eigen::Matrix< scalar, 3, Eigen::Dynamic, DEFAULT_MATRIX_LAYOUT                         >  Matrix3X   ## suffix;  \\\n    typedef Eigen::Matrix< scalar, 4, Eigen::Dynamic, DEFAULT_MATRIX_LAYOUT                         >  Matrix4X   ## suffix;  \\\n    typedef Eigen::Matrix< scalar, Eigen::Dynamic, 2, DEFAULT_MATRIX_LAYOUT                         >  MatrixX2   ## suffix;  \\\n    typedef Eigen::Matrix< scalar, Eigen::Dynamic, 3, DEFAULT_MATRIX_LAYOUT                         >  MatrixX3   ## suffix;  \\\n    typedef Eigen::Matrix< scalar, Eigen::Dynamic, 4, DEFAULT_MATRIX_LAYOUT                         >  MatrixX4   ## suffix;\n\nTHEA_DECL_MATRIX_TYPEDEFS(Real, )\nTHEA_DECL_MATRIX_TYPEDEFS(float, f)\nTHEA_DECL_MATRIX_TYPEDEFS(double, d)\nTHEA_DECL_MATRIX_TYPEDEFS(std::complex<float>, cf)\nTHEA_DECL_MATRIX_TYPEDEFS(std::complex<double>, cd)\nTHEA_DECL_MATRIX_TYPEDEFS(int, i)\n\n#undef THEA_DECL_MATRIX_TYPEDEFS\n\n// Typedef additional instantiations of fully resizable matrices, NOT including the \"plain X\" versions which will be declared\n// below with (fully optional) template arguments to avoid having to repeatedly type\n// <code>Matrix<Eigen::Dynamic, Eigen::Dynamic, T></code> in templated code.\n#define THEA_DECL_RESIZABLE_MATRIX_TYPEDEFS(scalar, suffix)                                                                   \\\n    typedef Eigen::Matrix< scalar, Eigen::Dynamic, Eigen::Dynamic, DEFAULT_MATRIX_LAYOUT      >  MatrixX    ## suffix;        \\\n    typedef Eigen::Matrix< scalar, Eigen::Dynamic, 1             , MatrixLayout::COLUMN_MAJOR >  VectorX    ## suffix;        \\\n    typedef Eigen::Matrix< scalar, 1,              Eigen::Dynamic, MatrixLayout::ROW_MAJOR    >  RowVectorX ## suffix;\n\nTHEA_DECL_RESIZABLE_MATRIX_TYPEDEFS(float, f)\nTHEA_DECL_RESIZABLE_MATRIX_TYPEDEFS(double, d)\nTHEA_DECL_RESIZABLE_MATRIX_TYPEDEFS(std::complex<float>, cf)\nTHEA_DECL_RESIZABLE_MATRIX_TYPEDEFS(std::complex<double>, cd)\nTHEA_DECL_RESIZABLE_MATRIX_TYPEDEFS(int, i)\n\n#undef THEA_DECL_RESIZABLE_MATRIX_TYPEDEFS\n\n/**\n * General 2D dense matrix template, alias for <code>Eigen::Matrix</code> with a custom default layout (row or column major) and\n * alignment preference.\n *\n * This alias currently <b>disables alignment</b> for all fixed-size types: fixed-size vectorizable types (Vector4f, Matrix4f,\n * Vector2d etc) require special handling for every class which directly or indirectly has such a member, and could lead to\n * unexpected bugs and considerably less ease of use.\n *\n * @see\n *   - http://eigen.tuxfamily.org/dox/group__TopicStructHavingEigenMembers.html\n *   - https://eigen.tuxfamily.org/dox/group__TopicStlContainers.html\n *   - http://eigen.tuxfamily.org/dox/group__TopicFixedSizeVectorizable.html\n *   - https://stackoverflow.com/q/41087043\n */\ntemplate <int Rows, int Cols, typename T = Real,\n          int Options = DEFAULT_MATRIX_LAYOUT,\n          int MaxRowsAtCompileTime = Rows,\n          int MaxColsAtCompileTime = Cols>\nusing Matrix = Eigen::Matrix<T, Rows, Cols,\n                             Options | ((Options & Eigen::DontAlign) == 0 && (Rows == Eigen::Dynamic || Cols == Eigen::Dynamic)\n                                      ? Eigen::AutoAlign : Eigen::DontAlign),\n                             MaxRowsAtCompileTime, MaxColsAtCompileTime>;\n\n/**\n * General 2D dense matrix template with dynamic resizing, alias for <code>Eigen::Matrix</code> with Eigen::Dynamic and a custom\n * default layout (row or column major).\n */\ntemplate <typename T = Real,\n          int Options = DEFAULT_MATRIX_LAYOUT,\n          int MaxRowsAtCompileTime = Eigen::Dynamic,\n          int MaxColsAtCompileTime = Eigen::Dynamic>\nusing MatrixX = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Options, MaxRowsAtCompileTime, MaxColsAtCompileTime>;\n\n/**\n * General 1D dense column vector template, alias for <code>Eigen::Matrix<T, Size, 1,...></code>, with a custom alignment\n * preference.\n *\n * This alias currently <b>disables alignment</b> for all fixed-size types: fixed-size vectorizable types (Vector4f, Vector2d\n * etc) require special handling for every class which directly or indirectly has such a member, and could lead to unexpected\n * bugs and considerably less ease of use.\n *\n * @see\n *   - http://eigen.tuxfamily.org/dox/group__TopicStructHavingEigenMembers.html\n *   - https://eigen.tuxfamily.org/dox/group__TopicStlContainers.html\n *   - http://eigen.tuxfamily.org/dox/group__TopicFixedSizeVectorizable.html\n *   - https://stackoverflow.com/q/41087043\n */\ntemplate <int Size, typename T = Real,\n          int Options = MatrixLayout::COLUMN_MAJOR,\n          int MaxRowsAtCompileTime = Size>\nusing Vector = Eigen::Matrix<T, Size, 1,\n                             Options | ((Options & Eigen::DontAlign) == 0 && Size == Eigen::Dynamic\n                                      ? Eigen::AutoAlign : Eigen::DontAlign),\n                             MaxRowsAtCompileTime, 1>;\n\n/**\n * General 1D dense column vector template with dynamic resizing, alias for <code>Eigen::Matrix<T, Eigen::Dynamic, 1,...></code>\n * with a custom default layout (row or column major).\n */\ntemplate <typename T = Real,\n          int Options = MatrixLayout::COLUMN_MAJOR,\n          int MaxRowsAtCompileTime = Eigen::Dynamic>\nusing VectorX = Eigen::Matrix<T, Eigen::Dynamic, 1, Options, MaxRowsAtCompileTime, 1>;\n\n/**\n * General 1D dense row vector template, alias for <code>Eigen::Matrix<T, 1, Size,...></code>, with a custom alignment\n * preference.\n *\n * This alias currently <b>disables alignment</b> for all fixed-size types: fixed-size vectorizable types (RowVector4f,\n * RowVector2d etc) require special handling for every class which directly or indirectly has such a member, and could lead to\n * unexpected bugs and considerably less ease of use.\n *\n * @see\n *   - http://eigen.tuxfamily.org/dox/group__TopicStructHavingEigenMembers.html\n *   - https://eigen.tuxfamily.org/dox/group__TopicStlContainers.html\n *   - http://eigen.tuxfamily.org/dox/group__TopicFixedSizeVectorizable.html\n *   - https://stackoverflow.com/q/41087043\n */\ntemplate <int Size, typename T = Real,\n          int Options = MatrixLayout::ROW_MAJOR,\n          int MaxColsAtCompileTime = Size>\nusing RowVector = Eigen::Matrix<T, 1, Size,\n                                Options | ((Options & Eigen::DontAlign) == 0 && Size == Eigen::Dynamic\n                                         ? Eigen::AutoAlign : Eigen::DontAlign),\n                                1, MaxColsAtCompileTime>;\n\n/**\n * General 1D dense row vector template with dynamic resizing, alias for <code>Eigen::Matrix<T, 1, Eigen::Dynamic,...></code>\n * with a custom default layout (row or column major).\n */\ntemplate <typename T = Real,\n          int Options = MatrixLayout::ROW_MAJOR,\n          int MaxColsAtCompileTime = Eigen::Dynamic>\nusing RowVectorX = Eigen::Matrix<T, 1, Eigen::Dynamic, Options, 1, MaxColsAtCompileTime>;\n\n//=============================================================================================================================\n// Typedef Eigen::Map wrappers for interpreting raw data as common Eigen types.\n//=============================================================================================================================\n\n#define THEA_DECL_MATRIX_MAP_TYPEDEFS(suffix)                                 \\\n    typedef Eigen::Map< Matrix2    ## suffix >  Matrix2    ## suffix ## Map;  \\\n    typedef Eigen::Map< Matrix3    ## suffix >  Matrix3    ## suffix ## Map;  \\\n    typedef Eigen::Map< Matrix4    ## suffix >  Matrix4    ## suffix ## Map;  \\\n    typedef Eigen::Map< Vector2    ## suffix >  Vector2    ## suffix ## Map;  \\\n    typedef Eigen::Map< Vector3    ## suffix >  Vector3    ## suffix ## Map;  \\\n    typedef Eigen::Map< Vector4    ## suffix >  Vector4    ## suffix ## Map;  \\\n    typedef Eigen::Map< RowVector2 ## suffix >  RowVector2 ## suffix ## Map;  \\\n    typedef Eigen::Map< RowVector3 ## suffix >  RowVector3 ## suffix ## Map;  \\\n    typedef Eigen::Map< RowVector4 ## suffix >  RowVector4 ## suffix ## Map;  \\\n    typedef Eigen::Map< Matrix2X   ## suffix >  Matrix2X   ## suffix ## Map;  \\\n    typedef Eigen::Map< Matrix3X   ## suffix >  Matrix3X   ## suffix ## Map;  \\\n    typedef Eigen::Map< Matrix4X   ## suffix >  Matrix4X   ## suffix ## Map;  \\\n    typedef Eigen::Map< MatrixX2   ## suffix >  MatrixX2   ## suffix ## Map;  \\\n    typedef Eigen::Map< MatrixX3   ## suffix >  MatrixX3   ## suffix ## Map;  \\\n    typedef Eigen::Map< MatrixX4   ## suffix >  MatrixX4   ## suffix ## Map;  \\\n    \\\n    typedef Eigen::Map< Matrix2    ## suffix const >  Matrix2    ## suffix ## ConstMap;  \\\n    typedef Eigen::Map< Matrix3    ## suffix const >  Matrix3    ## suffix ## ConstMap;  \\\n    typedef Eigen::Map< Matrix4    ## suffix const >  Matrix4    ## suffix ## ConstMap;  \\\n    typedef Eigen::Map< Vector2    ## suffix const >  Vector2    ## suffix ## ConstMap;  \\\n    typedef Eigen::Map< Vector3    ## suffix const >  Vector3    ## suffix ## ConstMap;  \\\n    typedef Eigen::Map< Vector4    ## suffix const >  Vector4    ## suffix ## ConstMap;  \\\n    typedef Eigen::Map< RowVector2 ## suffix const >  RowVector2 ## suffix ## ConstMap;  \\\n    typedef Eigen::Map< RowVector3 ## suffix const >  RowVector3 ## suffix ## ConstMap;  \\\n    typedef Eigen::Map< RowVector4 ## suffix const >  RowVector4 ## suffix ## ConstMap;  \\\n    typedef Eigen::Map< Matrix2X   ## suffix const >  Matrix2X   ## suffix ## ConstMap;  \\\n    typedef Eigen::Map< Matrix3X   ## suffix const >  Matrix3X   ## suffix ## ConstMap;  \\\n    typedef Eigen::Map< Matrix4X   ## suffix const >  Matrix4X   ## suffix ## ConstMap;  \\\n    typedef Eigen::Map< MatrixX2   ## suffix const >  MatrixX2   ## suffix ## ConstMap;  \\\n    typedef Eigen::Map< MatrixX3   ## suffix const >  MatrixX3   ## suffix ## ConstMap;  \\\n    typedef Eigen::Map< MatrixX4   ## suffix const >  MatrixX4   ## suffix ## ConstMap;\n\nTHEA_DECL_MATRIX_MAP_TYPEDEFS()\nTHEA_DECL_MATRIX_MAP_TYPEDEFS(f)\nTHEA_DECL_MATRIX_MAP_TYPEDEFS(d)\nTHEA_DECL_MATRIX_MAP_TYPEDEFS(cf)\nTHEA_DECL_MATRIX_MAP_TYPEDEFS(cd)\nTHEA_DECL_MATRIX_MAP_TYPEDEFS(i)\n\n#undef THEA_DECL_MATRIX_MAP_TYPEDEFS\n\n#define THEA_DECL_RESIZABLE_MATRIX_MAP_TYPEDEFS(suffix)                       \\\n    typedef Eigen::Map< MatrixX    ## suffix >  MatrixX    ## suffix ## Map;  \\\n    typedef Eigen::Map< VectorX    ## suffix >  VectorX    ## suffix ## Map;  \\\n    typedef Eigen::Map< RowVectorX ## suffix >  RowVectorX ## suffix ## Map;  \\\n    \\\n    typedef Eigen::Map< MatrixX    ## suffix const >  MatrixX    ## suffix ## ConstMap;  \\\n    typedef Eigen::Map< VectorX    ## suffix const >  VectorX    ## suffix ## ConstMap;  \\\n    typedef Eigen::Map< RowVectorX ## suffix const >  RowVectorX ## suffix ## ConstMap;\n\nTHEA_DECL_RESIZABLE_MATRIX_MAP_TYPEDEFS(f)\nTHEA_DECL_RESIZABLE_MATRIX_MAP_TYPEDEFS(d)\nTHEA_DECL_RESIZABLE_MATRIX_MAP_TYPEDEFS(cf)\nTHEA_DECL_RESIZABLE_MATRIX_MAP_TYPEDEFS(cd)\nTHEA_DECL_RESIZABLE_MATRIX_MAP_TYPEDEFS(i)\n\n#undef THEA_DECL_RESIZABLE_MATRIX_MAP_TYPEDEFS\n\n/** Alias for Eigen::Map< Matrix<...> >. */\ntemplate < int Rows, int Cols, typename T = Real,\n           int Options = DEFAULT_MATRIX_LAYOUT,\n           typename StrideType = Eigen::Stride<0, 0>,\n           int MapOptions = Eigen::Unaligned,\n           int MaxRowsAtCompileTime = Rows,\n           int MaxColsAtCompileTime = Cols >\nusing MatrixMap = Eigen::Map< Matrix<Rows, Cols, T, Options, MaxRowsAtCompileTime, MaxColsAtCompileTime>,\n                              MapOptions, StrideType >;\n\n/** Alias for Eigen::Map< Matrix<...> const >. */\ntemplate < int Rows, int Cols, typename T = Real,\n           int Options = DEFAULT_MATRIX_LAYOUT,\n           typename StrideType = Eigen::Stride<0, 0>,\n           int MapOptions = Eigen::Unaligned,\n           int MaxRowsAtCompileTime = Rows,\n           int MaxColsAtCompileTime = Cols >\nusing MatrixConstMap = Eigen::Map< Matrix<Rows, Cols, T, Options, MaxRowsAtCompileTime, MaxColsAtCompileTime> const,\n                                   MapOptions, StrideType >;\n\n/** Alias for Eigen::Map< Vector<...> >. */\ntemplate < int Size, typename T = Real,\n           typename StrideType = Eigen::Stride<0, 0>,\n           int MapOptions = Eigen::Unaligned,\n           int Options = MatrixLayout::COLUMN_MAJOR,\n           int MaxRowsAtCompileTime = Size >\nusing VectorMap = Eigen::Map< Vector<Size, T, Options, MaxRowsAtCompileTime>, MapOptions, StrideType >;\n\n/** Alias for Eigen::Map< Vector<...> const >. */\ntemplate < int Size, typename T = Real,\n           typename StrideType = Eigen::Stride<0, 0>,\n           int MapOptions = Eigen::Unaligned,\n           int Options = MatrixLayout::COLUMN_MAJOR,\n           int MaxRowsAtCompileTime = Size >\nusing VectorConstMap = Eigen::Map< Vector<Size, T, Options, MaxRowsAtCompileTime> const, MapOptions, StrideType >;\n\n/** Alias for Eigen::Map< RowVector<...> >. */\ntemplate < int Size, typename T = Real,\n           typename StrideType = Eigen::Stride<0, 0>,\n           int MapOptions = Eigen::Unaligned,\n           int Options = MatrixLayout::ROW_MAJOR,\n           int MaxColsAtCompileTime = Size >\nusing RowVectorMap = Eigen::Map< RowVector<Size, T, Options, MaxColsAtCompileTime>, MapOptions, StrideType >;\n\n/** Alias for Eigen::Map< RowVector<...> const >. */\ntemplate < int Size, typename T = Real,\n           typename StrideType = Eigen::Stride<0, 0>,\n           int MapOptions = Eigen::Unaligned,\n           int Options = MatrixLayout::ROW_MAJOR,\n           int MaxColsAtCompileTime = Size >\nusing RowVectorConstMap = Eigen::Map< RowVector<Size, T, Options, MaxColsAtCompileTime> const, MapOptions, StrideType >;\n\n/** Alias for Eigen::Map< MatrixX<...> >. */\ntemplate < typename T = Real,\n           int Options = DEFAULT_MATRIX_LAYOUT,\n           typename StrideType = Eigen::Stride<0, 0>,\n           int MapOptions = Eigen::Unaligned,\n           int MaxRowsAtCompileTime = Eigen::Dynamic,\n           int MaxColsAtCompileTime = Eigen::Dynamic >\nusing MatrixXMap = Eigen::Map< MatrixX<T, Options, MaxRowsAtCompileTime, MaxColsAtCompileTime>, MapOptions, StrideType >;\n\n/** Alias for Eigen::Map< MatrixX<...> const >. */\ntemplate < typename T = Real,\n           int Options = DEFAULT_MATRIX_LAYOUT,\n           typename StrideType = Eigen::Stride<0, 0>,\n           int MapOptions = Eigen::Unaligned,\n           int MaxRowsAtCompileTime = Eigen::Dynamic,\n           int MaxColsAtCompileTime = Eigen::Dynamic >\nusing MatrixXConstMap = Eigen::Map< MatrixX<T, Options, MaxRowsAtCompileTime, MaxColsAtCompileTime> const,\n                                    MapOptions, StrideType >;\n\n/** Alias for Eigen::Map< VectorX<...> >. */\ntemplate < typename T = Real,\n           typename StrideType = Eigen::Stride<0, 0>,\n           int MapOptions = Eigen::Unaligned,\n           int Options = MatrixLayout::COLUMN_MAJOR,\n           int MaxRowsAtCompileTime = Eigen::Dynamic >\nusing VectorXMap = Eigen::Map< VectorX<T, Options, MaxRowsAtCompileTime>, MapOptions, StrideType >;\n\n/** Alias for Eigen::Map< VectorX<...> const >. */\ntemplate < typename T = Real,\n           typename StrideType = Eigen::Stride<0, 0>,\n           int MapOptions = Eigen::Unaligned,\n           int Options = MatrixLayout::COLUMN_MAJOR,\n           int MaxRowsAtCompileTime = Eigen::Dynamic >\nusing VectorXConstMap = Eigen::Map< VectorX<T, Options, MaxRowsAtCompileTime> const, MapOptions, StrideType >;\n\n/** Alias for Eigen::Map< RowVectorX<...> >. */\ntemplate < typename T = Real,\n           typename StrideType = Eigen::Stride<0, 0>,\n           int MapOptions = Eigen::Unaligned,\n           int Options = MatrixLayout::ROW_MAJOR,\n           int MaxColsAtCompileTime = Eigen::Dynamic >\nusing RowVectorXMap = Eigen::Map< RowVectorX<T, Options, MaxColsAtCompileTime>, MapOptions, StrideType >;\n\n/** Alias for Eigen::Map< RowVectorX<...> const >. */\ntemplate < typename T = Real,\n           typename StrideType = Eigen::Stride<0, 0>,\n           int MapOptions = Eigen::Unaligned,\n           int Options = MatrixLayout::ROW_MAJOR,\n           int MaxColsAtCompileTime = Eigen::Dynamic >\nusing RowVectorXConstMap = Eigen::Map< RowVectorX<T, Options, MaxColsAtCompileTime> const, MapOptions, StrideType >;\n\n//=============================================================================================================================\n// Typedef other useful Eigen classes.\n//=============================================================================================================================\n\n/** Alias for Eigen::Quaternion<...>. */\ntemplate <typename T = Real> using Quaternion = Eigen::Quaternion<T>;\n\n} // namespace Thea\n\n#include \"MatrixUtil.hpp\"\n\n#endif\n", "meta": {"hexsha": "783155fabd9bfa55f06cd8fe6e09ba6662e3a88e", "size": 19984, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Code/Source/MatVec.hpp", "max_stars_repo_name": "sidch/Thea", "max_stars_repo_head_hexsha": "d5ea3e3f1bd7389255cfabf1d55a6fe88c3c7db7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 77.0, "max_stars_repo_stars_event_min_datetime": "2016-11-06T17:25:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T16:30:34.000Z", "max_issues_repo_path": "Code/Source/MatVec.hpp", "max_issues_repo_name": "sidch/Thea", "max_issues_repo_head_hexsha": "d5ea3e3f1bd7389255cfabf1d55a6fe88c3c7db7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-04-22T16:47:04.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-22T16:47:04.000Z", "max_forks_repo_path": "Code/Source/MatVec.hpp", "max_forks_repo_name": "sidch/Thea", "max_forks_repo_head_hexsha": "d5ea3e3f1bd7389255cfabf1d55a6fe88c3c7db7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 20.0, "max_forks_repo_forks_event_min_datetime": "2015-10-17T20:38:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T09:56:27.000Z", "avg_line_length": 54.6010928962, "max_line_length": 128, "alphanum_fraction": 0.6408126501, "num_tokens": 4903, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.49785591486556674}}
{"text": "#include <assert.h>\n#include <boost/algorithm/string/classification.hpp>\n#include <boost/algorithm/string/split.hpp>\n#include <iostream>\n#include <vector>\n\n\nstruct Point\n{\n    constexpr Point() = default;\n    constexpr Point(long _id, std::vector<long>&& l)\n        : id(_id)\n    {\n        assert(l.size() == 9);\n        auto it = l.begin();\n        x = *it++;\n        y = *it++;\n        z = *it++;\n        v_x = *it++;\n        v_y = *it++;\n        v_z = *it++;\n        a_x = *it++;\n        a_y = *it++;\n        a_z = *it++;\n    }\n\n    long id = 0;\n    long x = 0, y = 0, z = 0;\n    long v_x = 0, v_y = 0, v_z = 0;\n    long a_x = 0, a_y = 0, a_z = 0;\n    long len = 0;\n    long acc = 0;\n\n    void step() noexcept\n    {\n        v_x += a_x;\n        v_y += a_y;\n        v_z += a_z;\n        x += v_x;\n        y += v_y;\n        z += v_z;\n        len = std::abs(x) + std::abs(y) + std::abs(z);\n        acc = std::abs(a_x) + std::abs(a_y) + std::abs(a_z);\n    }\n\n    bool operator<(const Point& b) const noexcept {\n        return std::tie(len, acc) < std::tie(b.len, b.acc);\n    }\n};\n\nint main()\n{\n    // p=<-4897,3080,2133>, v=<-58,-15,-78>, a=<17,-7,0>\n    // -4897,3080,2133,-58,-15,-78,17,-7,0\n    std::vector<Point> points;\n    std::string line;\n    long id = 0;\n    while (std::getline(std::cin, line)) {\n        std::vector<std::string> words;\n        boost::algorithm::split(\n            words, line, boost::is_any_of(\", \"), boost::algorithm::token_compress_on);\n        std::vector<long> nums;\n        for (const auto& word : words) {\n            nums.push_back(atol(&word[0]));\n        }\n        points.emplace_back(Point(id++, std::move(nums)));\n    }\n\n    for (int i = 0; i < 500; ++i) {\n        std::sort(points.begin(), points.end());\n        for (int j =0; j < 10; ++j) {\n            std::cout << points[j].id << \", \";\n        }\n        std::cout << \"\\n\";\n        for (auto& p : points) {\n            p.step();\n        }\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "078df81d729c8480a8a601dd338259e8e0c72712", "size": 1952, "ext": "cc", "lang": "C++", "max_stars_repo_path": "puzzle_20_1.cc", "max_stars_repo_name": "mody/Advent-of-Code-2017", "max_stars_repo_head_hexsha": "446300f2562ad56c3da14644111d06ea4d0303f8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "puzzle_20_1.cc", "max_issues_repo_name": "mody/Advent-of-Code-2017", "max_issues_repo_head_hexsha": "446300f2562ad56c3da14644111d06ea4d0303f8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "puzzle_20_1.cc", "max_forks_repo_name": "mody/Advent-of-Code-2017", "max_forks_repo_head_hexsha": "446300f2562ad56c3da14644111d06ea4d0303f8", "max_forks_repo_licenses": ["Apache-2.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.8048780488, "max_line_length": 86, "alphanum_fraction": 0.4620901639, "num_tokens": 616, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905302989295534, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.49785590864965307}}
{"text": "/*\n * 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 *    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 *          Erik Nelson            ( eanelson@eecs.berkeley.edu )\n */\n\n///////////////////////////////////////////////////////////////////////////////\n//\n// This header defines a set of functions for converting a fundamental matrix\n// and a pair of camera intrinsics into an essential matrix, and from an\n// essential matrix to and a set of camera extrinsics.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"essential_matrix_solver.h\"\n\n#include <Eigen/Core>\n#include <Eigen/LU>\n#include <gflags/gflags.h>\n#include <glog/logging.h>\n#include <vector>\n\n#include \"point_3d.h\"\n#include \"triangulation.h\"\n#include \"../camera/camera.h\"\n\nDEFINE_double(min_points_visible_ratio, 0.3,\n              \"Fraction of keypoint matches whose triangulation must be \"\n              \"visible from both cameras. This value should be lowered if you \"\n              \"expect lots of noisy matches.\");\n\nnamespace bsfm {\n\n// Compute the essential matrix from a fundamental matrix and camera intrinsics.\nMatrix3d EssentialMatrixSolver::ComputeEssentialMatrix(\n    const Matrix3d& F, const CameraIntrinsics& intrinsics1,\n    const CameraIntrinsics& intrinsics2) {\n  // Extract intrinsics matrices.\n  Matrix3d K1(intrinsics1.K());\n  Matrix3d K2(intrinsics2.K());\n\n  // Calculate the essential matrix.\n  return K2.transpose() * F * K1;\n}\n\n// Compute the relative transformation between two cameras from an essential\n// matrix and a list of keypoint matches. Note that translation can only be\n// computed up to a scale factor.\n// NOTE: this implementation is based on Hartley & Zisserman's MVG, pg. 258.\nbool EssentialMatrixSolver::ComputeExtrinsics(\n    const Matrix3d& E, const FeatureMatchList& matches,\n    const CameraIntrinsics& intrinsics1, const CameraIntrinsics& intrinsics2,\n    Pose& relative_pose) {\n  // Initialize the W matrix.\n  Matrix3d W;\n  W << 0.0, -1.0, 0.0,\n       1.0,  0.0, 0.0,\n       0.0,  0.0, 1.0;\n\n  // Perform an SVD on the essential matrix.\n  Eigen::JacobiSVD<Matrix3d> svd;\n  svd.compute(E, Eigen::ComputeFullU | Eigen::ComputeFullV);\n  if (!svd.computeU() || !svd.computeV()) {\n    VLOG(1) << \"Failed to compute a singular value decomposition of \"\n            << \"the essential matrix.\";\n    return false;\n  }\n\n  // The essential matrix must satisfy E = U * diag(1, 1, 0) * V^T. Use U and V\n  // to get a new E, run another SVD, and get the normalized U and V.\n  Matrix3d sigma(Matrix3d::Identity());\n  sigma(2, 2) = 0;\n  Matrix3d E_augmented = svd.matrixU() * sigma * svd.matrixV().transpose();\n\n  svd.compute(E_augmented, Eigen::ComputeFullU | Eigen::ComputeFullV);\n  if (!svd.computeU() || !svd.computeV()) {\n    VLOG(1) << \"Failed to compute a singular value decomposition of \"\n            << \"the essential matrix.\";\n    return false;\n  }\n\n  // Compute two possibilities for rotation.\n  Matrix3d R1 = svd.matrixU() * W * svd.matrixV().transpose();\n  Matrix3d R2 = svd.matrixU() * W.transpose() * svd.matrixV().transpose();\n\n  // Ensure positive determinants.\n  if (R1.determinant() < 0)\n    R1 = -R1;\n  if (R2.determinant() < 0)\n    R2 = -R2;\n\n  // Compute two possibilities for translation\n  Vector3d t1, t2;\n  t1 = svd.matrixU().col(2);\n  t2 = -t1;\n\n  // Build four possible Poses.\n  std::vector<Pose> poses;\n  poses.push_back(Pose(R1, t1));\n  poses.push_back(Pose(R1, t2));\n  poses.push_back(Pose(R2, t1));\n  poses.push_back(Pose(R2, t2));\n\n  // Set the first camera's position to identity in rotation and translation.\n  CameraExtrinsics extrinsics1;\n  extrinsics1.SetWorldToCamera(Pose());\n\n  Camera camera1;\n  camera1.SetExtrinsics(extrinsics1);\n  camera1.SetIntrinsics(intrinsics1);\n\n  // Test how many points are in front of each pose and the identity pose.\n  Pose best_pose;\n  int best_num_points = -1;\n\n  double u = 0.0, v = 0.0;\n  for (int ii = 0; ii < poses.size(); ii++) {\n    int num_points = 0;\n\n    CameraExtrinsics extrinsics2;\n    extrinsics2.SetWorldToCamera(poses[ii]);\n\n    Camera camera2;\n    camera2.SetExtrinsics(extrinsics2);\n    camera2.SetIntrinsics(intrinsics2);\n\n    for (int jj = 0; jj < matches.size(); jj++) {\n      // Triangulate points and test if the 3D estimate is in front of both\n      // cameras.\n      Point3D point;\n      double unused = 0.0;\n      if (!Triangulate(matches[jj], camera1, camera2, point, unused)) {\n        continue;\n      }\n\n      num_points++;\n    }\n\n    // Update best_num_points and best_pose.\n    if (num_points > best_num_points) {\n      best_num_points = num_points;\n      best_pose = poses[ii];\n    }\n  }\n\n  // Return with false if not enough points found in front of the cameras.\n  if (best_num_points < FLAGS_min_points_visible_ratio * matches.size()) {\n    VLOG(1) << \"Did not find enough points in front of both cameras.\";\n    return false;\n  }\n\n  relative_pose = best_pose;\n\n  return true;\n}\n\n}  //\\namespace bsfm\n", "meta": {"hexsha": "c8fd141453f579090f8a3035b9c2da8a9b0b89d1", "size": 6630, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cpp/geometry/essential_matrix_solver.cpp", "max_stars_repo_name": "jamesdsmith/berkeley_sfm", "max_stars_repo_head_hexsha": "de3ae6b104602c006d939b1f3da8c497b86d39ff", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 21.0, "max_stars_repo_stars_event_min_datetime": "2016-01-14T13:52:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-03T19:30:33.000Z", "max_issues_repo_path": "src/cpp/geometry/essential_matrix_solver.cpp", "max_issues_repo_name": "jamesdsmith/berkeley_sfm", "max_issues_repo_head_hexsha": "de3ae6b104602c006d939b1f3da8c497b86d39ff", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-10-17T17:01:46.000Z", "max_issues_repo_issues_event_max_datetime": "2015-10-22T20:59:43.000Z", "max_forks_repo_path": "src/cpp/geometry/essential_matrix_solver.cpp", "max_forks_repo_name": "erik-nelson/berkeley_sfm", "max_forks_repo_head_hexsha": "5bf0b45fac176ff7abfca0ff690893c1afc73c51", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2016-01-22T06:23:59.000Z", "max_forks_repo_forks_event_max_datetime": "2018-01-16T03:54:33.000Z", "avg_line_length": 35.0793650794, "max_line_length": 80, "alphanum_fraction": 0.6790346908, "num_tokens": 1687, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597971, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.4977743254984408}}
{"text": "#ifndef TEST_UNIT_MATH_FWD_MAT_VECTORIZE_EXPECT_FWD_ROW_VECTOR_VALUE_HPP\n#define TEST_UNIT_MATH_FWD_MAT_VECTORIZE_EXPECT_FWD_ROW_VECTOR_VALUE_HPP\n\n#include <stan/math/fwd/mat.hpp>\n#include <math/fwd/mat/vectorize/build_fwd_matrix.hpp>\n#include <math/fwd/mat/vectorize/expect_val_deriv_eq.hpp>\n#include <Eigen/Dense>\n#include <vector>\n\ntemplate <typename F, typename T>\nvoid expect_fwd_row_vector_value() {\n  using stan::math::fvar;\n  using std::vector;\n  typedef Eigen::Matrix<T, 1, Eigen::Dynamic> row_vector_t;\n\n  size_t num_inputs = F::valid_inputs().size();\n  row_vector_t template_rv(num_inputs);\n\n  for (size_t i = 0; i < num_inputs; ++i) {\n    row_vector_t b = build_fwd_matrix<F>(template_rv, i);\n    row_vector_t fb = F::template apply<row_vector_t>(b);\n    EXPECT_EQ(b.size(), fb.size());\n    expect_val_deriv_eq(F::apply_base(b(i)), fb(i));\n  }\n\n  size_t vector_vector_size = 2;\n  for (size_t i = 0; i < vector_vector_size; ++i) {\n    for (size_t j = 0; j < num_inputs; ++j) {\n      vector<row_vector_t> c;\n      for (size_t k = 0; k < vector_vector_size; ++k)\n        if (k == i)\n          c.push_back(build_fwd_matrix<F>(template_rv, j));\n        else\n          c.push_back(build_fwd_matrix<F>(template_rv));\n      vector<row_vector_t> fc = F::template apply<vector<row_vector_t> >(c);\n      EXPECT_EQ(c.size(), fc.size());\n      EXPECT_EQ(c[i].size(), fc[i].size());\n      expect_val_deriv_eq(F::apply_base(c[i](j)), fc[i](j));\n    }\n  }\n}\n\n#endif\n", "meta": {"hexsha": "781313efd3fca6d7b04f03a789efbe736529500e", "size": 1462, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "tests/math_unit/math/fwd/mat/vectorize/expect_fwd_row_vector_value.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": "tests/math_unit/math/fwd/mat/vectorize/expect_fwd_row_vector_value.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": "tests/math_unit/math/fwd/mat/vectorize/expect_fwd_row_vector_value.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": 33.2272727273, "max_line_length": 76, "alphanum_fraction": 0.6819425445, "num_tokens": 413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125848754472, "lm_q2_score": 0.661922862511608, "lm_q1q2_score": 0.4977743228255096}}
{"text": "#include \"cnn/nodes.h\"\n#include \"cnn/cnn.h\"\n#include \"cnn/training.h\"\n#include \"cnn/timing.h\"\n#include \"cnn/rnn.h\"\n#include \"cnn/gru.h\"\n#include \"cnn/lstm.h\"\n#include \"cnn/dglstm.h\"\n#include \"cnn/dict.h\"\n#include \"cnn/expr.h\"\n#include \"cnn/cnn-helper.h\"\n#include \"cnn/expr-xtra.h\"\n#include \"cnn/grad-check.h\"\n#include \"cnn/math.h\"\n#include <iostream>\n#include <fstream>\n#include <sstream>\n\n#include <boost/archive/text_iarchive.hpp>\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/archive/text_iarchive.hpp>\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/program_options/parsers.hpp>\n#include <boost/program_options/variables_map.hpp>\n\nusing namespace std;\nusing namespace cnn;\n\nunsigned int LAYERS = 2;\nunsigned int INPUT_DIM = 8;  //256\nunsigned int HIDDEN_DIM = 24;  // 1024\nunsigned int VOCAB_SIZE = 0;\n\nint verbose = 0; \ncnn::Dict d;\nint kSOS;\nint kEOS;\n\ntemplate <class Builder>\nstruct RNNLanguageModel {\n  LookupParameters* p_c;\n  Parameters* p_R;\n  Parameters* p_bias;\n  Builder builder;\n  explicit RNNLanguageModel(Model& model) : builder(LAYERS, vector<unsigned>{INPUT_DIM, HIDDEN_DIM}, &model) {\n      if (verbose)\n          cout << \"building RNNLanguageModel\" << endl;\n    p_c = model.add_lookup_parameters(VOCAB_SIZE, {INPUT_DIM}); \n\tp_R = model.add_parameters({ VOCAB_SIZE, HIDDEN_DIM });\n\tp_bias = model.add_parameters({ VOCAB_SIZE });\n  }\n\n  // return Expression of total loss\n  Expression BuildLMGraph(const vector<int>& sent, ComputationGraph& cg) {\n    const unsigned slen = (unsigned int) sent.size() - 1;\n    if (verbose)\n        cout << \"start building builder graph\" << endl;\n    builder.new_graph(cg);  // reset RNN builder for new graph\n    if (verbose)\n        cout << \"start new_seuence for the builder graph\" << endl;\n    builder.start_new_sequence();\n    Expression i_R = parameter(cg, p_R); // hidden -> word rep parameter\n    Expression i_bias = parameter(cg, p_bias);  // word bias\n\tif (verbose)\n\t\tdisplay_value(i_R, cg, \"IR at \");\n\tif (verbose)\n\t\tdisplay_value(i_bias, cg, \"ibias at \");\n\tvector<Expression> errs;\n    for (unsigned t = 0; t < slen; ++t) {\n      Expression i_x_t = lookup(cg, p_c, sent[t]);\n      // y_t = RNN(x_t)\n      Expression i_y_t = builder.add_input(i_x_t);\n      Expression i_r_t =  i_bias + i_R * i_y_t;\n\t  if (verbose)\n\t\t  display_value(i_r_t, cg, \"response at \" + t);\n      // we can easily look at intermidiate values\n//      std::vector<cnn::real> r_t = as_vector(i_r_t.value());\n  //    for (cnn::real f : r_t) cout << f << \" \"; cout << endl;\n    //  cout << \"[\" << as_scalar(pick(i_r_t, sent[t+1]).value()) << \"]\" << endl;\n\n      // LogSoftmax followed by PickElement can be written in one step\n      // using PickNegLogSoftmax\n#if 1\n      Expression i_ydist = log_softmax(i_r_t);\n      errs.push_back(pick(i_ydist, sent[t+1]));\n#if 0\n      Expression i_ydist = softmax(i_r_t);\n      i_ydist = log(i_ydist)\n      errs.push_back(pick(i_ydist, sent[t+1]));\n#endif\n#else\n      Expression i_err = pickneglogsoftmax(i_r_t, sent[t+1]);\n      errs.push_back(i_err);\n#endif\n    }\n    Expression i_nerr = sum(errs);\n#if 1\n    return -i_nerr;\n#else\n    return i_nerr;\n#endif\n  }\n\n  // return Expression for total loss\n  void RandomSample(int max_len = 150) {\n    cerr << endl;\n    ComputationGraph cg;\n    builder.new_graph(cg);  // reset RNN builder for new graph\n    builder.start_new_sequence();\n    \n    Expression i_R = parameter(cg, p_R);\n    Expression i_bias = parameter(cg, p_bias);\n    vector<Expression> errs;\n    int len = 0;\n    int cur = kSOS;\n    while(len < max_len && cur != kEOS) {\n      ++len;\n      Expression i_x_t = lookup(cg, p_c, cur);\n      // y_t = RNN(x_t)\n      Expression i_y_t = builder.add_input(i_x_t);\n      Expression i_r_t = i_bias + i_R * i_y_t;\n      \n      Expression ydist = softmax(i_r_t);\n      \n      unsigned w = 0;\n      while (w == 0 || (int)w == kSOS) {\n        auto dist = as_vector(cg.incremental_forward());\n        cnn::real p = rand01();\n        for (; w < dist.size(); ++w) {\n          p -= dist[w];\n          if (p < 0.0) { break; }\n        }\n        if (w == dist.size()) w = kEOS;\n      }\n      cerr << (len == 1 ? \"\" : \" \") << d.Convert(w);\n      cur = w;\n    }\n    cerr << endl;\n  }\n};\n\ntemplate <class LM_t>\nvoid train(Model &model, LM_t &lm,\n    const vector<vector<int>>& training,\n    const vector<vector<int>>& dev,\n    Trainer *sgd, const string& fname,\n    bool randomSample, bool checkgrad)\n{\n    cnn::real best = 9e+99;\n    unsigned report_every_i = 50;\n    unsigned dev_every_i_reports = 500;\n    unsigned si = (unsigned int) training.size();\n    vector<unsigned> order(training.size());\n    for (unsigned i = 0; i < order.size(); ++i) order[i] = i;\n    bool first = true;\n    int report = 0;\n    unsigned lines = 0;\n    unsigned total_epoch = 40;\n\n    if (verbose)\n        cout << \"saving model at \" << fname << endl;\n    ofstream out(fname, ofstream::out);\n    boost::archive::text_oarchive oa(out);\n    oa << model;\n    out.close();\n\n    size_t i_epoch = 0;\n    while (sgd->epoch < total_epoch) {\n        Timer iteration(\"completed in\");\n        cnn::real loss = 0;\n        unsigned chars = 0;\n        for (unsigned i = 0; i < report_every_i; ++i) {\n            if (si == training.size()) {\n                si = 0;\n                if (first) { first = false; }\n                else { sgd->update_epoch(); }\n                cerr << \"**SHUFFLE\\n\";\n                shuffle(order.begin(), order.end(), *rndeng);\n            }\n\n            // build graph for this instance\n            ComputationGraph cg;\n            auto& sent = training[order[si]];\n            chars += sent.size() - 1;\n            ++si;\n            lm.BuildLMGraph(sent, cg);\n            loss += as_scalar(cg.forward());\n            cg.backward();\n            if (checkgrad)\n                CheckGrad(model, cg);\n            sgd->update();\n            ++lines;\n        }\n        sgd->status();\n        cerr << \" report = \" << report << \" E = \" << (loss / chars) << \" ppl=\" << exp(loss / chars) << ' ';\n\n        if (randomSample)\n            lm.RandomSample();\n\n        // show score on dev data?\n        report++;\n        if (report % dev_every_i_reports == 0) {\n            cnn::real dloss = 0;\n            int dchars = 0;\n            for (auto& sent : dev) {\n                ComputationGraph cg;\n                lm.BuildLMGraph(sent, cg);\n                dloss += as_scalar(cg.forward());\n                dchars += sent.size() - 1;\n            }\n            if (dloss < best) {\n                best = dloss;\n                ofstream out(fname, ofstream::out);\n                boost::archive::text_oarchive oa(out);\n                oa << model;\n                out.close();\n            }\n            else{\n                sgd->eta *= 0.5;\n            }\n            cerr << \"\\n***TEST E = \" << (dloss / dchars) << \" ppl=\" << exp(dloss / dchars) << ' ';\n        }\n\n        i_epoch++;\n    }\n}\n\ntemplate <class LM_t>\nvoid testcorpus(Model &model, LM_t &lm,\n    const vector<vector<int>>& dev)\n{\n    unsigned lines = 0;\n    cnn::real dloss = 0;\n    int dchars = 0;\n    for (auto& sent : dev) {\n        ComputationGraph cg;\n        lm.BuildLMGraph(sent, cg);\n        dloss += as_scalar(cg.forward());\n        dchars += sent.size() - 1;\n    }\n\n    cerr << \"\\n***DEV [epoch=\" << (lines / (cnn::real)dev.size()) << \"] E = \" << (dloss / dchars) << \" ppl=\" << exp(dloss / dchars) << ' ';\n}\n\nvoid initialise(Model &model, const string &filename)\n{\n    cerr << \"Initialising model parameters from file: \" << filename << endl;\n    ifstream in(filename, ifstream::in);\n    boost::archive::text_iarchive ia(in);\n    ia >> model;\n}\n\nint main(int argc, char** argv) {\n  cnn::Initialize(argc, argv);\n\n  // command line processing\n  using namespace boost::program_options;\n  variables_map vm;\n  options_description opts(\"Allowed options\");\n  opts.add_options()\n      (\"help\", \"print help message\")\n      (\"seed,s\", value<int>()->default_value(217), \"random seed number\")\n      (\"train,t\", value<string>(), \"file containing training sentences\")\n      (\"devel,d\", value<string>(), \"file containing development sentences.\")\n      (\"test,T\", value<string>(), \"file containing testing source sentences\")\n      (\"initialise,i\", value<string>(), \"load initial parameters from file\")\n      (\"parameters,p\", value<string>(), \"save best parameters to this file\")\n      (\"layers,l\", value<int>()->default_value(LAYERS), \"use <num> layers for RNN components\")\n      (\"hidden,h\", value<int>()->default_value(HIDDEN_DIM), \"use <num> dimensions for recurrent hidden states\")\n      (\"gru\", \"use Gated Recurrent Unit (GRU) for recurrent structure; default RNN\")\n      (\"lstm\", \"use Long Short Term Memory (GRU) for recurrent structure; default RNN\")\n      (\"dglstm\", \"use depth-gated LSTM for recurrent structure; default RNN\")\n      (\"verbose,v\", \"be extremely chatty\")\n      (\"generate,g\", value<bool>()->default_value(false), \"generate random samples\")\n      (\"checkgrad\", value<bool>()->default_value(false), \"whether check gradient\")\n      ;\n  store(parse_command_line(argc, argv, opts), vm);\n\n  string flavour;\n  if (vm.count(\"gru\"))\tflavour = \"gru\";\n  else if (vm.count(\"lstm\"))\tflavour = \"lstm\";\n  else if (vm.count(\"rnnem\"))\tflavour = \"rnnem\";\n  else if (vm.count(\"dglstm\")) flavour = \"dglstm\";\n  else if (vm.count(\"nmn\")) flavour = \"nmn\";\n  else\t\t\tflavour = \"rnn\";\n\n  if (vm.count(\"verbose\") > 0)\n  {\n      verbose = 1;\n      cout << \"extrememly chatty\" << endl;\n  }\n\n  LAYERS = vm[\"layers\"].as<int>();\n  HIDDEN_DIM = vm[\"hidden\"].as<int>();\n\n  bool generateSample = false;\n  generateSample = vm[\"generate\"].as<bool>();\n\n  string fname;\n  if (vm.count(\"parameters\")) {\n      fname = vm[\"parameters\"].as<string>();\n  }\n  else {\n      ostringstream os;\n      os << \"lm\"\n          << '_' << LAYERS\n          << '_' << HIDDEN_DIM\n          << '_' << flavour\n          << \"-pid\" << getpid() << \".params\";\n      fname = os.str();\n  }\n\n  cerr << \"Parameters will be written to: \" << fname << endl;\n\n  if (vm.count(\"help\") || vm.count(\"train\") != 1 || (vm.count(\"devel\") != 1 && vm.count(\"test\") != 1)) {\n      cout << opts << \"\\n\";\n      return 1;\n  }\n\n  kSOS = d.Convert(\"<s>\");\n  kEOS = d.Convert(\"</s>\");\n  vector<vector<int>> training, dev, test;\n  string line;\n  int tlc = 0;\n  int ttoks = 0;\n\n  string infile = vm[\"train\"].as<string>();\n  cerr << \"Reading training data from \" << infile << \"...\\n\";\n\n  {\n    ifstream in(infile);\n    assert(in);\n    while(getline(in, line)) {\n      ++tlc;\n      training.push_back(ReadSentence(line, &d));\n      ttoks += training.back().size();\n      if (training.back().front() != kSOS && training.back().back() != kEOS) {\n\t\t  throw(\"Training sentence in %s : %d didnt start or end with <s>, </s>\", infile.c_str(), tlc );\n      }\n    }\n    cerr << tlc << \" lines, \" << ttoks << \" tokens, \" << d.size() << \" types\\n\";\n  }\n  d.Freeze(); // no new word types allowed\n  VOCAB_SIZE = d.size();\n\n  if (vm.count(\"devel\") > 0)\n  {\n      int dlc = 0;\n      int dtoks = 0;\n      string devfile = vm[\"devel\"].as<string>();\n      cerr << \"Reading training data from \" << devfile << \"...\\n\";\n      {\n          ifstream in(devfile);\n          assert(in);\n          while (getline(in, line)) {\n              ++dlc;\n              dev.push_back(ReadSentence(line, &d));\n              dtoks += dev.back().size();\n\t\t\t  if (dev.back().front() != kSOS && dev.back().back() != kEOS) {\n\t\t\t\t  throw(\"Dev sentence in %s : %d didn't start or end with <s>, </s> \", devfile.c_str(), tlc);\n\t\t\t  }\n          }\n          cerr << dlc << \" lines, \" << dtoks << \" tokens\\n\";\n      }\n  }\n\n  Model model;\n  bool use_momentum = false;\n  Trainer* sgd = nullptr;\n  if (use_momentum)\n    sgd = new MomentumSGDTrainer(&model);\n  else\n    sgd = new SimpleSGDTrainer(&model);\n\n  if (vm.count(\"test\") == 0)\n  {\n      if (vm.count(\"lstm\")) {\n          cerr << \"%% Using LSTM recurrent units\" << endl;\n          RNNLanguageModel<LSTMBuilder> lm(model);\n          train(model, lm, training, dev, sgd, fname, generateSample, vm[\"checkgrad\"].as<bool>());\n      }\n      else if (vm.count(\"dglstm\")) {\n          cerr << \"%% Using DGLSTM recurrent units\" << endl;\n          RNNLanguageModel<DGLSTMBuilder> lm(model);\n          train(model, lm, training, dev, sgd, fname, generateSample, vm[\"checkgrad\"].as<bool>());\n      }\n  }\n  else\n  {\n      string testfile = vm[\"test\"].as<string>();\n      int dlc = 0;\n      int dtoks = 0;\n      cerr << \"Reading training data from \" << testfile << \"...\\n\";\n      {\n          ifstream in(testfile);\n          assert(in);\n          while (getline(in, line)) {\n              ++dlc;\n              test.push_back(ReadSentence(line, &d));\n              dtoks += test.back().size();\n\t\t\t  if (test.back().front() != kSOS && test.back().back() != kEOS) {\n\t\t\t\t  throw(\"Dev sentence in %s : %d didnt start or end with <s>, </s> \", testfile.c_str(), tlc);\n\t\t\t  }\n          }\n          cerr << dlc << \" lines, \" << dtoks << \" tokens\\n\";\n      }\n\n      if (vm.count(\"test\"))\n      {\n          if (vm.count(\"lstm\")){\n              cerr << \"%% using LSTM recurrent units\" << endl;\n              RNNLanguageModel<LSTMBuilder> lm(model);\n              if (vm.count(\"initialise\"))\n                  initialise(model, vm[\"initialise\"].as<string>());\n              testcorpus(model, lm, test);\n          }\n          if (vm.count(\"dglstm\")){\n              cerr << \"%% using DGLSTM recurrent units\" << endl;\n              RNNLanguageModel<DGLSTMBuilder> lm(model);\n              if (vm.count(\"initialise\"))\n                  initialise(model, vm[\"initialise\"].as<string>());\n              testcorpus(model, lm, test);\n          }\n      }\n  }\n\n  //RNNLanguageModel<SimpleRNNBuilder> lm(model);\n  if (argc == 4) {\n    string fname = argv[3];\n    ifstream in(fname);\n    boost::archive::text_iarchive ia(in);\n    ia >> model;\n  }\n\n  delete sgd;\n}\n\n", "meta": {"hexsha": "70f511014ff5041240bd4a4d5430a02b8475bcf4", "size": 13829, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/rnnlm2.cc", "max_stars_repo_name": "kaishengyao/cnn", "max_stars_repo_head_hexsha": "a034b837e88f82bd8adf2c5b0a5defb26fd52096", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2015-09-10T07:50:50.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-17T03:02:38.000Z", "max_issues_repo_path": "examples/rnnlm2.cc", "max_issues_repo_name": "kaishengyao/cnn", "max_issues_repo_head_hexsha": "a034b837e88f82bd8adf2c5b0a5defb26fd52096", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/rnnlm2.cc", "max_forks_repo_name": "kaishengyao/cnn", "max_forks_repo_head_hexsha": "a034b837e88f82bd8adf2c5b0a5defb26fd52096", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2015-09-08T12:43:13.000Z", "max_forks_repo_forks_event_max_datetime": "2018-09-26T07:32:47.000Z", "avg_line_length": 31.5730593607, "max_line_length": 139, "alphanum_fraction": 0.5606334514, "num_tokens": 3752, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.752012562644147, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.4977743181407377}}
{"text": "/*\n * Copyright 2016 Maikel Nadolski\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 \"hidden-markov-models.t.h\"\n\n#include <tuple>\n#include <vector>\n#include <Eigen/Dense>\n#include \"maikel/hmm/hidden_markov_model.h\"\n#include \"maikel/hmm/algorithm.h\"\n\nnamespace {\n\nCASE ( \"Do we see if a bijective map is bijective onto values?\" ) {\n  using Index = uint8_t;\n  std::map<int, Index> bijective_map_int { {0,0}, {1,1} };\n  std::map<std::string, Index> bijective_map_string { {\"foo\",1}, {\"bar\",0} };\n  std::map<int, Index> not_bijective_map_int1 { {0,1}, {1,2} };\n  std::map<int, Index> not_bijective_map_int2 { {0,1}, {2,1} };\n\n  EXPECT(maikel::is_bijective_index_map(bijective_map_int));\n  EXPECT(maikel::is_bijective_index_map(bijective_map_string));\n  EXPECT_NOT(maikel::is_bijective_index_map(not_bijective_map_int1));\n  EXPECT_NOT(maikel::is_bijective_index_map(not_bijective_map_int2));\n}\n\nCASE (\"convert symbols to indicies\") {\n  using Index = int;\n  std::vector<std::string> symbols { \"foo\", \"bar\" };\n  auto symbols_to_index = maikel::map_from_symbols<Index>(ranges::view::all(symbols));\n  EXPECT(symbols_to_index[\"foo\"] == 0);\n  EXPECT(symbols_to_index[\"bar\"] == 1);\n\n  std::vector<int> symbols_2 { 1, 2 };\n  auto sti = maikel::map_from_symbols<Index>(symbols_2);\n  EXPECT(sti[1] == 0);\n  EXPECT(sti[2] == 1);\n}\n\nCASE ( \"Test forward algorithm for test case in Rabiners Paper\" ) {\n  Eigen::Matrix3f A;\n  A << 0.4, 0.3, 0.3,\n       0.2, 0.6, 0.2,\n       0.1, 0.1, 0.8;\n  Eigen::Matrix3f B;\n  B << 1.0, 0.0, 0.0,\n       0.0, 1.0, 0.0,\n       0.0, 0.0, 1.0;\n  Eigen::Vector3f pi;\n  pi << 0.0, 0.0, 1.0;\n  std::vector<int> sequence { 2, 2, 2, 0, 0, 2, 1, 2 };\n//\n  std::vector<float> scaling;\n  std::vector<Eigen::VectorXf> alphas;\n  maikel::hmm::hidden_markov_model<float> hmm(A, B, pi);\n  for (auto&& alpha : maikel::hmm::forward(begin(sequence), end(sequence), hmm)) {\n    scaling.push_back(alpha.first);\n  }\n  float probability = std::accumulate(scaling.begin(), scaling.end(), 1.0, std::multiplies<float>());\n  probability = 1/probability;\n  EXPECT(maikel::almost_equal(probability, 1.536f /10000));\n}\n\n\n//\n//CASE ( \"Test forward and backward algorithms for test case in Rabiners Paper\" ) {\n//  Eigen::Matrix3f A;\n//  A << 0.4, 0.3, 0.3,\n//       0.2, 0.6, 0.2,\n//       0.1, 0.1, 0.8;\n//  Eigen::Matrix3f B;\n//  B << 1.0, 0.0, 0.0,\n//       0.0, 1.0, 0.0,\n//       0.0, 0.0, 1.0;\n//  Eigen::Vector3f pi;\n//  pi << 0.0, 0.0, 1.0;\n//  std::vector<int> sequence { 2, 2, 2, 0, 0, 2, 1, 2 };\n//\n//  maikel::hmm::hidden_markov_model<float> hmm(A, B, pi);\n//\n//  using vector_type = decltype(hmm)::vector_type;\n//  std::vector<float> scaling;\n//  std::vector<vector_type> alphas;\n//  maikel::hmm::forward(hmm, sequence.begin(), sequence.end(), std::back_inserter(alphas), std::back_inserter(scaling));\n//  float probability = std::accumulate(scaling.begin(), scaling.end(), 1.0, std::multiplies<float>());\n//  probability = 1/probability;\n//  EXPECT(maikel::almost_equal<float>(probability,(1.536/10000),1));\n//\n//  std::vector<vector_type> betas_ranges;\n//  maikel::hmm::backward(hmm,\n//      sequence | ranges::view::reverse,\n//       scaling | ranges::view::reverse,\n//      std::back_inserter(betas_ranges));\n//  std::vector<vector_type> betas_not_ranges;\n//  maikel::hmm::backward(hmm,\n//      sequence.rbegin(), sequence.rend(),\n//      scaling.rbegin(), scaling.rend(),\n//      std::back_inserter(betas_not_ranges));\n//}\n//\n//CASE ( \"baum-welch algorithm for test case in Rabiners Paper\" ) {\n//  Eigen::Matrix3f A;\n//  A << 0.4, 0.3, 0.3,\n//       0.2, 0.6, 0.2,\n//       0.1, 0.1, 0.8;\n//  Eigen::Matrix3f B;\n//  B << 1.0, 0.0, 0.0,\n//       0.0, 1.0, 0.0,\n//       0.0, 0.0, 1.0;\n//  Eigen::Vector3f pi;\n//  pi << 0.0, 0.0, 1.0;\n//  std::vector<int> sequence { 2, 2, 2, 0, 0, 2, 1, 2 };\n//\n//  maikel::hmm::hidden_markov_model<float> initial_hmm(A, B, pi);\n//  EXPECT_NO_THROW (\n//      auto new_hmm = maikel::hmm::naive::baum_welch(initial_hmm, sequence);\n////      std::cerr << \"A\\n\" << new_hmm.A << \"\\nB\\n\" << new_hmm.B << \"\\npi\\n\" << new_hmm.pi << std::endl;\n//  );\n//}\n\n\n}\n\n\n", "meta": {"hexsha": "ddc6b22149d3ab2f78bbc75e070a086bbbb15ea2", "size": 4609, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/algorithm.t.cpp", "max_stars_repo_name": "maikel/hidden-markov-model", "max_stars_repo_head_hexsha": "db97cd0344a3cb55afdd2d341fd2c5c326f6476a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-14T07:16:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-14T07:16:01.000Z", "max_issues_repo_path": "tests/algorithm.t.cpp", "max_issues_repo_name": "maikel/Hidden-Markov-Model", "max_issues_repo_head_hexsha": "db97cd0344a3cb55afdd2d341fd2c5c326f6476a", "max_issues_repo_licenses": ["Apache-2.0"], "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/algorithm.t.cpp", "max_forks_repo_name": "maikel/Hidden-Markov-Model", "max_forks_repo_head_hexsha": "db97cd0344a3cb55afdd2d341fd2c5c326f6476a", "max_forks_repo_licenses": ["Apache-2.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.3985507246, "max_line_length": 121, "alphanum_fraction": 0.6341939683, "num_tokens": 1620, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708562, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.4977286496989647}}
{"text": "#include <boost/test/unit_test.hpp>\n#include <complex>\n#include \"../../JeanBaptiste/include/AlgorithmFactory.h\"\n#include \"../include/AlgorithmFixture.h\"\n#include <string>\n\nnamespace ut = boost::unit_test;\nnamespace jb = jeanbaptiste;\nnamespace jbo = jeanbaptiste::options;\n\nclass Radix2Fixture\n    : public AlgorithmFixture\n{\nprotected:\n    bool initialized_;\n\npublic:\n    Radix2Fixture()\n        : AlgorithmFixture(),\n          initialized_(false)\n    {\n        BOOST_TEST_MESSAGE(\"Setup fixture: square pulse of 64 samples.\");\n        BOOST_TEST((initialized_ = algorithmResult_.initialize(\"../../test cases/square pulse (n=64).xml\", \"fft.in\", workingSet_, expectedOutIFFT_, \"fft.out\", expectedOutFFT_)), \"Loading test data failed.\");\n    }\n\n    ~Radix2Fixture()\n    {}\n};\n\n\nBOOST_FIXTURE_TEST_SUITE(Radix2TestSuite, Radix2Fixture)\n\n    BOOST_AUTO_TEST_CASE(fft_radix_2_dif)\n    {\n        if (!initialized_)\n            return;\n\n        BOOST_TEST_MESSAGE(\"Running radix 2 DIF FFT and IFFT.\");\n\n        // Create Radix-2 DIF FFT algorithms for sample counts 2 ... 256.\n        jb::AlgorithmFactory<1, 8, jbo::Radix_2, jbo::Decimation_In_Frequency, jbo::Direction_Forward, jbo::Window_None,\n            jbo::Normalization_Square_Root, std::complex<double>> fftFactory;\n\n        // Create Radix-2 DIF IFFT algorithms for sample counts 2 ... 256.\n        jb::AlgorithmFactory<1, 8, jbo::Radix_2, jbo::Decimation_In_Frequency, jbo::Direction_Backward, jbo::Window_None,\n            jbo::Normalization_Square_Root, std::complex<double>> ifftFactory;\n\n        runAlgorithms(fftFactory.getAlgorithm(6), ifftFactory.getAlgorithm(6));\n    }\n\n    BOOST_AUTO_TEST_CASE(fft_radix_2_dit)\n    {\n        if (!initialized_)\n            return;\n\n        BOOST_TEST_MESSAGE(\"Running radix 2 DIT FFT and IFFT.\");\n\n        // Create Radix-2 DIT FFT algorithms for sample counts 2 ... 256.\n        jb::AlgorithmFactory<1, 8, jbo::Radix_2, jbo::Decimation_In_Time, jbo::Direction_Forward, jbo::Window_None,\n            jbo::Normalization_Square_Root, std::complex<double>> fftFactory;\n\n        // Create Radix-2 DIT IFFT algorithms for sample counts 2 ... 256.\n        jb::AlgorithmFactory<1, 8, jbo::Radix_2, jbo::Decimation_In_Time, jbo::Direction_Backward, jbo::Window_None,\n            jbo::Normalization_Square_Root, std::complex<double>> ifftFactory;\n\n        runAlgorithms(fftFactory.getAlgorithm(6), ifftFactory.getAlgorithm(6));\n    }\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "21c7f97335a7360417bf31d24c42766c84e90559", "size": 2452, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "JeanBaptiste.Test/src/FixtureRadix2.cpp", "max_stars_repo_name": "JoergWarthemann/jeanbaptiste", "max_stars_repo_head_hexsha": "cda9f5e80c126fa8612ce1515b2f904056c09fda", "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": "JeanBaptiste.Test/src/FixtureRadix2.cpp", "max_issues_repo_name": "JoergWarthemann/jeanbaptiste", "max_issues_repo_head_hexsha": "cda9f5e80c126fa8612ce1515b2f904056c09fda", "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": "JeanBaptiste.Test/src/FixtureRadix2.cpp", "max_forks_repo_name": "JoergWarthemann/jeanbaptiste", "max_forks_repo_head_hexsha": "cda9f5e80c126fa8612ce1515b2f904056c09fda", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.5362318841, "max_line_length": 207, "alphanum_fraction": 0.69045677, "num_tokens": 645, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943805178139, "lm_q2_score": 0.6926419958239132, "lm_q1q2_score": 0.4977286459097071}}
{"text": "#include \"attribute.hpp\"\n\n#include <boost/format.hpp>\n\n#include <iostream>\n#include <sstream>\n\nnamespace ocv{\n\nstd::ostream& operator<<(std::ostream &out, contour_attribute const &attr)\n{\n    std::ostringstream ostr;\n    ostr<<boost::format(\"%=11.2f|%=11.2f|%=11.2f|%=11.2f|\"\n                        \"%=11.2f|%=11.2f|%=11.2f\")\n          %attr.contour_area_%attr.bounding_area_%attr.perimeter_\n          %attr.aspect_ratio_%attr.extent_%attr.solidity_\n          %attr.poly_size_;\n    out<<ostr.str()<<std::endl;\n\n    return out;\n}\n\nvoid print_contour_attribute(std::vector<cv::Point> const &contour,\n                             double epsillon,\n                             std::ostream &out)\n{    \n    contour_attribute const ca = contour_analyzer().analyze(contour, epsillon);\n    out<<ca;\n}\n\nvoid print_contour_attribute_name(std::ostream &out)\n{\n    std::ostringstream ostr;\n    ostr<<boost::format(\"%=11s|%=11s|%=11s|%=11s|\"\n                        \"%=11s|%=11s|%=11s\")\n          % \"CArea\" % \"BArea\" %\"Perimeter\" % \"Aspect\"\n          % \"Extent\" % \"Solidity\" % \"PolySize\";\n    out<<ostr.str()<<std::endl;\n}\n\ncontour_attribute contour_analyzer::\nanalyze(std::vector<cv::Point> const &contour,\n        double epsillon)\n{      \n    return analyze(contour, epsillon, buffer_);\n}\n\ncontour_attribute contour_analyzer::\nanalyze(std::vector<cv::Point> const &contour,\n        double epsillon) const\n{\n    std::vector<cv::Point> buffer;\n    return analyze(contour, epsillon, buffer);\n}\n\ncontour_attribute contour_analyzer::\nanalyze(std::vector<cv::Point> const &contour,\n        double epsillon,\n        std::vector<cv::Point> &buffer) const\n{\n    contour_attribute ca;\n\n    ca.contour_area_ = cv::contourArea(contour);\n    ca.bounding_rect_ = cv::boundingRect(contour);\n    ca.bounding_area_ = static_cast<double>(ca.bounding_rect_.area());\n    ca.aspect_ratio_ = ca.bounding_rect_.width /\n            static_cast<double>(ca.bounding_rect_.height);\n    ca.perimeter_ = cv::arcLength(contour, true);\n    ca.extent_ = ca.contour_area_/ca.bounding_area_;\n\n    cv::convexHull(contour, buffer);\n    ca.solidity_ = ca.contour_area_/cv::contourArea(buffer);\n\n    cv::approxPolyDP(contour, buffer, ca.perimeter_ * epsillon, true);\n    ca.poly_size_ = buffer.size();\n\n    return ca;\n}\n\n}\n", "meta": {"hexsha": "42599a4a39f1767a76a1a4c8dd4178cdb9084cf1", "size": 2275, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "core/attribute.cpp", "max_stars_repo_name": "stereomatchingkiss/ocv_libs", "max_stars_repo_head_hexsha": "1424ac2f8a2c034513483b3050d8138ca0a0ae3f", "max_stars_repo_licenses": ["FSFAP"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2015-12-17T05:28:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-21T02:59:29.000Z", "max_issues_repo_path": "core/attribute.cpp", "max_issues_repo_name": "stereomatchingkiss/ocv_libs", "max_issues_repo_head_hexsha": "1424ac2f8a2c034513483b3050d8138ca0a0ae3f", "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": "core/attribute.cpp", "max_forks_repo_name": "stereomatchingkiss/ocv_libs", "max_forks_repo_head_hexsha": "1424ac2f8a2c034513483b3050d8138ca0a0ae3f", "max_forks_repo_licenses": ["FSFAP"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-05-10T11:20:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-19T17:06:06.000Z", "avg_line_length": 28.0864197531, "max_line_length": 79, "alphanum_fraction": 0.6408791209, "num_tokens": 611, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.6926419704455588, "lm_q1q2_score": 0.49772863602140716}}
{"text": "#include <boost/math/special_functions/jacobi_zeta.hpp>\n", "meta": {"hexsha": "7abbd8a0eab30a9b7ba1b4acb8fee7481115b2d7", "size": 56, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_special_functions_jacobi_zeta.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_special_functions_jacobi_zeta.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_special_functions_jacobi_zeta.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 28.0, "max_line_length": 55, "alphanum_fraction": 0.8392857143, "num_tokens": 14, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.5926665999540697, "lm_q1q2_score": 0.4976822802404063}}
{"text": "/*\n *  mesher_tester.cpp\n *  Mesh_3_applications\n *\n *  Created by Jane Tournois on 02/12/09.\n *  Copyright 2009 INRIA. All rights reserved.\n */\n\n//#include <debug.h>\n#include <CGAL/AABB_intersections.h>\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n\n#include <CGAL/Mesh_triangulation_3.h>\n#include <CGAL/Mesh_complex_3_in_triangulation_3.h>\n#include <CGAL/Mesh_criteria_3.h>\n// Implicit domain\n#include <CGAL/Implicit_to_labeling_function_wrapper.h>\n#include <CGAL/Labeled_mesh_domain_3.h>\n\n#include <CGAL/make_mesh_3.h>\n#include \"../examples/Mesh_3/implicit_functions.h\"\n#include <CGAL/refine_mesh_3.h>\n#include <CGAL/Mesh_3/Mesh_global_optimizer.h>\n\n/* INPUTS */\n// Polyhedral domain\n#include <CGAL/Mesh_3/Robust_intersection_traits_3.h>\n#include <CGAL/Polyhedral_mesh_domain_3.h>\n#include <CGAL/IO/Polyhedron_iostream.h>\n// Implicit domain is above\n// 3D Image\n#include <CGAL/Labeled_image_mesh_domain_3.h>\n#include <CGAL/make_mesh_3.h>\n#include <CGAL/Image_3.h>\n\n/* OUTPUT */\n#include <CGAL/IO/File_medit.h>\n\n/* tools */\n#include <sstream>\n#include <stdlib.h>\n#include <algorithm>\n\n/* OPTIONS and PARAMETERS */\n#include <boost/program_options.hpp>\nnamespace po = boost::program_options;\n\nusing namespace CGAL::parameters; //to avoid verbose function and named parameters call\n\n/* FILE SYSTEM */\n#include <iostream>\n#include <boost/filesystem.hpp>\n#include <boost/filesystem/path.hpp>\n#include <boost/filesystem/operations.hpp>\n#include <boost/filesystem/convenience.hpp>\nnamespace fs = boost::filesystem; \n\n/* DOMAIN */\nstruct K: public CGAL::Exact_predicates_inexact_constructions_kernel {};\n// Polyhedral domain\ntypedef CGAL::Mesh_3::Robust_intersection_traits_3<K> Geom_traits; // exact constructions here\ntypedef CGAL::Polyhedron_3<Geom_traits> Polyhedron;\ntypedef CGAL::Polyhedral_mesh_domain_3<Polyhedron, Geom_traits> Polyhedral_domain; \n// Implicit domain\ntypedef FT_to_point_function_wrapper<K::FT, K::Point_3> I_Function;\ntypedef CGAL::Implicit_multi_domain_to_labeling_function_wrapper<I_Function> I_Function_wrapper;\ntypedef I_Function_wrapper::Function_vector I_Function_vector;\ntypedef CGAL::Labeled_mesh_domain_3<I_Function_wrapper, K> Implicit_domain;\n// 3D Image\ntypedef CGAL::Image_3 Image;\ntypedef CGAL::Labeled_image_mesh_domain_3<Image,K> Image_domain;\n\n/* TRIANGULATION */\n//Polyhedral domain\ntypedef CGAL::Mesh_triangulation_3<Polyhedral_domain>::type Tr_polyhedron;\ntypedef CGAL::Mesh_complex_3_in_triangulation_3<Tr_polyhedron> C3t3_polyhedron;\n//Implicit domain\ntypedef CGAL::Mesh_triangulation_3<Implicit_domain>::type Tr_implicit;\ntypedef CGAL::Mesh_complex_3_in_triangulation_3<Tr_implicit> C3t3_implicit;\n//3D Image\ntypedef CGAL::Mesh_triangulation_3<Image_domain>::type Tr_image;\ntypedef CGAL::Mesh_complex_3_in_triangulation_3<Tr_image> C3t3_image;\n\n/* MESHING CRITERIA */\n//Polyhedral domain\ntypedef CGAL::Mesh_criteria_3<Tr_polyhedron>       Mesh_criteria_polyhedron;\n//typedef Mesh_criteria_polyhedron::Facet_criteria   Facet_criteria_polyhedron;\n//typedef Mesh_criteria_polyhedron::Cell_criteria    Cell_criteria_polyhedron;\n//Implicit domain\ntypedef CGAL::Mesh_criteria_3<Tr_implicit>         Mesh_criteria_implicit;\n//typedef Mesh_criteria_implicit::Facet_criteria     Facet_criteria_implicit;\n//typedef Mesh_criteria_implicit::Cell_criteria      Cell_criteria_implicit;\n//3D Image\ntypedef CGAL::Mesh_criteria_3<Tr_image>            Mesh_criteria_image;\n//typedef Mesh_criteria_image::Facet_criteria        Facet_criteria_image;\n//typedef Mesh_criteria_image::Cell_criteria         Cell_criteria_image;\n\n\ntemplate <typename T>\nT set_arg(const std::string& param_name,\n\t\t  const std::string& param_string,\n\t\t  const po::variables_map& vm)\n{\n\tif(vm.count(param_name))\n\t{\n\t\tT param_value = vm[param_name].as<T>();\n\t\t//std::cout << param_string << \": \" << param_value << \"\\n\";\n\t\treturn param_value;\n\t}\n\telse\n\t{\n\t\t//std::cout << param_string << \" ignored.\\n\";\n\t\treturn T();\n\t}\n}\n\nvoid set_implicit_function(I_Function_vector& v,\n\t\t\t\t\t\t   I_Function& f,\n\t\t\t\t\t\t   const std::string& function_name,\n\t\t\t\t\t\t   const po::variables_map& vm)\n{\n\tif(vm.count(function_name))\n\t{\n\t\tv.push_back(f);\n\t\tstd::cout << function_name << \" \";\n\t}\n}\n\nstd::vector<std::string> split_line(const std::string& str)\n{\n\tstd::vector<std::string> args;\n\t\n\tstd::string::size_type lastPos = str.find_first_not_of(\" \", 0);\n\tstd::string::size_type pos = str.find_first_of(\" \", lastPos);\n\twhile(pos != std::string::npos || lastPos != std::string::npos)\n\t{\n\t\targs.push_back(str.substr(lastPos, pos-lastPos));\n\t\tlastPos = str.find_first_not_of(\" \", pos);\n\t\tpos = str.find_first_of(\" \", lastPos);\n\t}\n\treturn args;\n}\n\ntemplate<typename C3t3>\nvoid save_histogram(std::string& filename, \n\t\t\t\t\tconst C3t3& c3t3)\n{\n\tstd::vector<int> histo(181,0);\n\n\tfor (typename C3t3::Cell_iterator cit = c3t3.cells_begin() ;\n\t\t cit != c3t3.cells_end() ;\n\t\t ++cit)\n\t{\n\t\tif( !c3t3.is_in_complex(cit))\n\t\t\tcontinue;\n\t\t\n\t\ttypedef typename K::Point_3 Point_3;\n\t\tconst Point_3& p0 = cit->vertex(0)->point();\n\t\tconst Point_3& p1 = cit->vertex(1)->point();\n\t\tconst Point_3& p2 = cit->vertex(2)->point();\n\t\tconst Point_3& p3 = cit->vertex(3)->point();\n\t\t\n\t\tdouble a = CGAL::to_double(CGAL::abs(CGAL::Mesh_3::dihedral_angle(p0,p1,p2,p3)));\n\t\thisto[std::floor(a)] += 1;\n\t\ta = CGAL::to_double(CGAL::abs(CGAL::Mesh_3::dihedral_angle(p0, p2, p1, p3)));\n\t\thisto[std::floor(a)] += 1;\n\t\ta = CGAL::to_double(CGAL::abs(CGAL::Mesh_3::dihedral_angle(p0, p3, p1, p2)));\n\t\thisto[std::floor(a)] += 1;\n\t\ta = CGAL::to_double(CGAL::abs(CGAL::Mesh_3::dihedral_angle(p1, p2, p0, p3)));\n\t\thisto[std::floor(a)] += 1;\n\t\ta = CGAL::to_double(CGAL::abs(CGAL::Mesh_3::dihedral_angle(p1, p3, p0, p2)));\n\t\thisto[std::floor(a)] += 1;\n\t\ta = CGAL::to_double(CGAL::abs(CGAL::Mesh_3::dihedral_angle(p2, p3, p0, p1)));\n\t\thisto[std::floor(a)] += 1;\n\t}\n\tstd::ofstream file(filename.c_str());\n\tstd::copy(histo.begin(), histo.end(), std::ostream_iterator<int>(file, \"\\n\"));\t\n}\n\n\ntemplate<typename MeshingCriteria>\nMeshingCriteria get_parameters(const std::string& param_line,\n\t\t\t\t\t\t\t   po::variables_map& vm)\n{\n\tpo::options_description mesh(\"Mesh generation parameters\");\n\tmesh.add_options()\n  (\"mesh\", \"Generate mesh\")\n\t(\"facet_angle\", po::value<double>(), \"Set facet angle bound\")\n\t(\"facet_size\", po::value<double>(), \"Set facet size bound\")\n\t(\"facet_error\", po::value<double>(), \"Set approximation error bound\")\n\t(\"tet_shape\", po::value<double>(), \"Set tet radius-edge bound\")\n\t(\"tet_size\", po::value<double>(), \"Set tet size bound\");\n\t\n\tpo::options_description implicit_functions(\"Implicit functions\");\n\timplicit_functions.add_options()\n\t(\"torus\", \"Mesh torus function\")\n\t(\"sphere\", \"Mesh sphere function\")\n\t(\"chair\", \"Mesh chair function\")\n\t(\"tanglecube\", \"Mesh tanglecube function\")\n\t(\"cube\", \"Mesh cube function\")\n\t(\"ellipsoid\", \"Mesh ellipsoid function\")\n\t(\"heart\", \"Mesh heart function\")\n\t(\"octic\", \"Mesh octic function\");\n\t\n\tpo::options_description optim(\"Optimization parameters\");\n\toptim.add_options()\n\t(\"exude\", \"Exude mesh after refinement\")\n\t(\"perturb\", po::value<double>(), \"Perturb mesh after refinement (sliver removal)\")\n\t(\"lloyd\", po::value<int>(), \"Lloyd smoothing after refinement. arg is max nb iterations\")\n\t(\"odt\", po::value<int>(), \"ODT smoothing after refinement. arg is max nb iterations\");\n\t\n\tpo::options_description additional_options(\"Options\");\n\tadditional_options.add_options()\n\t(\"off_vertices\", po::value<int>(), \"Use polyhedron vertices as initialization step\")\n\t(\"no_label_rebind\", \"Don't rebind cell labels in medit output\")\n\t(\"show_patches\", \"Show surface patches in medit output\");\n\t\n\tpo::options_description cmdline_options(\"Usage\", 1);\n\tcmdline_options.add(mesh).add(implicit_functions).add(optim).add(additional_options);\n\t\n\tstd::vector<std::string> args = split_line(param_line);\n\tpo::store(po::command_line_parser(args).options(cmdline_options).run(), vm);\n\tpo::notify(vm);\n\n\tdouble facet_angle = set_arg<double>(\"facet_angle\", \"Facet angle\", vm);\n\tdouble facet_size  = set_arg<double>(\"facet_size\", \"Facet size\", vm);\n\tdouble facet_error = set_arg<double>(\"facet_error\", \"Facet approximation error\", vm);\n\tdouble tet_shape = set_arg<double>(\"tet_shape\",\"Tet shape (radius-edge)\", vm);\n\tdouble tet_size = set_arg<double>(\"tet_size\",\"Tet size\", vm);\n\n\ttypename MeshingCriteria::Facet_criteria fc(facet_angle, facet_size, facet_error);\n\ttypename MeshingCriteria::Cell_criteria cc(tet_shape, tet_size);\n\treturn MeshingCriteria(fc, cc);\t\n}\n\nvoid get_implicit_function(const po::variables_map& vm,\n\t\t\t\t\t\t   I_Function_vector& fv)\n{\n\t// Define functions\n\tI_Function f1( &torus_function);\n\tI_Function f2( &sphere_function<3>);\n\tI_Function f3( &chair_function);\n\tI_Function f4( &tanglecube_function);\n\tI_Function f5( &cube_function);\n\tI_Function f6( &ellipsoid_function);\n\tI_Function f7( &heart_function);\n\tI_Function f8( &octic_function);\n\t\n\tstd::cout << \"Function(s): \";\n\tset_implicit_function(fv, f1, \"torus\", vm);\n\tset_implicit_function(fv, f2, \"sphere\", vm);\n\tset_implicit_function(fv, f3, \"chair\", vm);\n\tset_implicit_function(fv, f4, \"tanglecube\", vm);\n\tset_implicit_function(fv, f5, \"cube\", vm);\n\tset_implicit_function(fv, f6, \"ellipsoid\", vm);\n\tset_implicit_function(fv, f7, \"heart\", vm);\n\tset_implicit_function(fv, f8, \"octic\", vm);\n\tstd::cout << \"\\n\\n\";\n\t\n\tif(fv.empty())\n\t\tstd::cout << \"Warning: No implicit function set.\\n\";\t\n}\n\n\ntemplate <class Domain>\nclass Domain_builder\n{\npublic:\n  /*void build(const std::string& str);\n  Domain domain();*/\n};\n\ntemplate <>\nclass Domain_builder<Polyhedral_domain>\n{\n  typedef Polyhedral_domain Domain;\npublic:\n  Domain_builder(const std::string& str)\n  : domain_(NULL)\n  {\n    std::ifstream input(str.c_str());\n    input >> polyhedron_;\n    domain_ = new Domain(polyhedron_);\n  }\n  \n  ~Domain_builder() { delete domain_; }\n  \n  Domain& domain() { return *domain_; }\n\nprivate:\n  Domain* domain_;\n  Polyhedron polyhedron_;\n};\n\ntemplate <>\nclass Domain_builder<Image_domain>\n{\n  typedef Image_domain Domain;\npublic:\n  Domain_builder(const std::string& str)\n  : domain_(NULL)\n  {\n    image_.read(str.c_str());\n    domain_ = new Domain(image_, 1e-6);\n  }\n  \n  ~Domain_builder() { delete domain_; }\n  \n  Domain& domain() { return *domain_; }\n  \nprivate:\n  Domain* domain_;\n  Image image_;\n};\n\n//template <>\n//class Domain_builder<Implicit_domain>\n//{\n//  typedef Implicit_domain Domain;\n//public:\n//  Domain_builder()\n//  :\tf1_( &torus_function);\n//\t, f2_( &sphere_function<3>);\n//\t, f3_( &chair_function);\n//\t, f4_( &tanglecube_function);\n//\t, f5_( &cube_function);\n//  , f6_( &ellipsoid_function);\n//\t, f7_( &heart_function);\n//\t, f8_( &octic_function);\n//  \n//  void build(const std::string& str)\n//  {\n//    Image image;\n//    image.read(str.c_str());\n//    delete domain_;\n//    domain_ = new Domain(image, 1e-6);\n//  }\n//  \n//  Domain& domain() { return *domain_; }\n//  \n//private:\n//  Domain* domain_;\n//  \n//  // Define functions\n//\tI_Function f1_;\n//\tI_Function f2_;\n//\tI_Function f3_;\n//\tI_Function f4_;\n//\tI_Function f5_;\n//\tI_Function f6_;\n//\tI_Function f7_;\n//\tI_Function f8_;\n//};\n\n\n\ntemplate <class C3T3, class Mesh_criteria, class Domain>\nvoid mesh(const std::string& data, const po::variables_map& vm)\n{\n  if(!fs::is_directory(data))\n    std::cout << \"!! Problem while reading \" << data << \"\\n\";\n\t\n  std::string output_dir;\n  if(vm.count(\"outdir\"))\n    output_dir = vm[\"outdir\"].as<std::string>();\n  else output_dir = data + \"output\";\n  if(!fs::is_directory(output_dir) && !fs::create_directory(output_dir))\n    std::cout << \"!! Problem while creating \" << output_dir << \"\\n\";\n  \n  fs::path path(data);\n  for(fs::directory_iterator it(path); it != fs::directory_iterator(); ++it)\n  {\n    if(fs::is_directory(*it)\n       || (fs::extension(*it) != \".off\" && (fs::extension(*it) != \".inr\" && ( fs::extension(fs::basename(*it)) != \".inr\" || fs::extension(*it) != \".gz\"))) )\n      continue;\n    \n    std::string line_param;\n    std::string filename(fs::basename(*it));\n    if ( fs::extension(*it) == \".gz\" )\n      filename = fs::basename(fs::basename(*it));\n    std::string filename_param(data + filename + \".txt\");\n    \n    std::ifstream file_param(filename_param.data()); //parameters\n    if(!file_param) \n    {\n      std::cout << \"Could not read parameters in : '\" << filename_param << \"'. Next file.\" << std::endl;\n      continue;\n    }\n    unsigned int i = 1;\n    \n    // Timer\n    CGAL::Timer timer;\n    timer.start();\n    \n    // we keep c3t3 between lines\n    C3T3 c3t3_save;\n    \n    //Load the domain\n    std::cout << \"****** [\" << filename << \"] Create domain...\";\n    std::flush(std::cout);\n    Domain_builder<Domain> domain_builder(it->path().string());\n    std::cout <<\"done (\" << timer.time() << \"s) ******\\n\\n\";\n    \n    while(std::getline(file_param,line_param))\n    {\n      std::cout << \"*** Meshing \" << filename << \"[\" << i << \"] with : \" << line_param << std::endl;\n\n      po::variables_map vm_p;\n      Mesh_criteria mcp = get_parameters<Mesh_criteria>(line_param, vm_p);\n      \n      //Mesh generation (reload domain and rebuild c3t3)\n      if ( vm_p.count(\"mesh\") )\n      {\n        timer.stop();\n        timer.reset();\n        timer.start();\n        std::cout << \"  Generate mesh...\";\n        std::flush(std::cout);\n        c3t3_save = CGAL::make_mesh_3<C3T3>(domain_builder.domain(), mcp, no_exude(), no_perturb());\n        std::cout << \"done (\" << timer.time() << \"s - \"\n                  << c3t3_save.triangulation().number_of_vertices() << \" vertices, \"\n                  << c3t3_save.number_of_cells() << \" cells)\\n\";\n      }\n      \n      C3T3 c3t3 = c3t3_save;\n      \n      //Optimization\n      timer.stop();\n      timer.reset();\n      timer.start();\n      if(vm_p.count(\"lloyd\"))\n      {\n        std::cout << \"  Lloyd optimization...\";\n        std::flush(std::cout);\n        CGAL::lloyd_optimize_mesh_3(c3t3, domain_builder.domain(), max_iteration_number=vm_p[\"lloyd\"].as<int>());\n        std::cout << \"done (\" << timer.time() << \"s)\\n\";\n      }\n      timer.stop();\n      timer.reset();\n      timer.start();\n      if(vm_p.count(\"odt\"))\n      {\n        std::cout << \"  Odt optimization...\";\n        std::flush(std::cout);\n        CGAL::odt_optimize_mesh_3(c3t3, domain_builder.domain(), max_iteration_number=vm_p[\"odt\"].as<int>());\n        std::cout << \"done (\" << timer.time() << \"s)\\n\";\n      }\t\n      timer.stop();\n      timer.reset();\n      timer.start();\n      if(vm_p.count(\"perturb\"))\n      {\n        std::cout << \"  Perturbation...\";\n        std::flush(std::cout);\n        CGAL::perturb_mesh_3(c3t3, domain_builder.domain(), time_limit=vm_p[\"perturb\"].as<double>());\n        std::cout << \"done (\" << timer.time() << \"s)\\n\";\n      }\n      timer.stop();\n      timer.reset();\n      timer.start();\n      if(vm_p.count(\"exude\"))\n      {\n        std::cout << \"  Exudation...\";\n        std::flush(std::cout);\n        CGAL::exude_mesh_3(c3t3);\n        std::cout << \"done (\" << timer.time() << \"s)\\n\";\n      }\n      timer.stop();\n      timer.reset();\n      timer.start();\n      \n      //save mesh\n      std::cout << \"  Save mesh...\";\n      std::stringstream ssout;\n      ssout << i;\t\t\t\t\n      std::string output_filename = output_dir +\"/\" + filename + \"-out-\" + ssout.str().c_str() + \".mesh\";\n      std::ofstream medit_file(output_filename.c_str());\n      c3t3.output_to_medit(medit_file, !vm_p.count(\"no_label_rebind\"), vm_p.count(\"show_patches\"));\n      \n      //save histogram\n      std::cout << \"done. \\n  Save histogram...\";\n      std::string histo_filename = output_dir +\"/\" + filename + \"-histo-\" + ssout.str().c_str() + \".txt\";\n      save_histogram<C3T3>(histo_filename, c3t3);\n      i++;\n      std::cout << \"done.\\n\\n\\n\";\n    }\n  }\n}\n\n\nint main(int argc, char** argv)\n{\n\t// options\n\tpo::options_description generic(\"Options\");\n\tgeneric.add_options()(\"help\", \"Produce help message\")\n\t(\"polyhedron\", \"Test the polyhedral domain mesher\")\n\t(\"implicit\",   \"Test the implicit domain mesher\")\n\t(\"image\",      \"Test the 3D image domain mesher\")\n\t(\"outdir\", po::value<std::string>(), \"Output directory. arg is location\");\n\t\n\tpo::options_description cmdline_options(\"Usage\", 1);\n\tcmdline_options.add(generic);//.add(others);\n\t\n\tpo::variables_map vm;\n\tpo::store(po::parse_command_line(argc, argv, cmdline_options), vm);\n\tpo::notify(vm);\n\t\n\tif(vm.count(\"help\") || argc < 2)\n\t{\n\t\tstd::cout << cmdline_options << std::endl;\n\t\tstd::cout << \"* Polyhedra: .off files should be in applications/data/Polyhedra\\n\";\n\t\tstd::cout << \"* Images:    .inr.gz files should be in applications/data/3D_images\\n\";\n\t\tstd::cout << \"  Note: for each file toto.domain, add a toto.txt file with meshing parameters\\n\\n\";\n\t\treturn 1;\n\t}\n\t\n\t//what are we testing\n\tbool mesh_polyhedra = vm.count(\"polyhedron\");\n\tbool mesh_implicit = vm.count(\"implicit\");\n\tbool mesh_images = vm.count(\"image\");\n\t\n\t// iterate on data files\n\tstd::string data_dir(\"data\"); // or a user defined path...\n\tfs::path data_path(data_dir); \n\t\n\tif(mesh_polyhedra)\n\t{\n\t\tstd::string data_poly = data_dir + \"/Polyhedra/\";\n    mesh<C3t3_polyhedron,Mesh_criteria_polyhedron,Polyhedral_domain>(data_poly,vm); \n\t}\n\n\tif(mesh_images)\n\t{\n\t\tstd::string data_img = data_dir + \"/3D_images/\";\n    mesh<C3t3_image,Mesh_criteria_image,Image_domain>(data_img,vm); \n  }\n\t\n\tif(mesh_implicit)\n\t{\n\t\tstd::string data_imp = data_dir + \"/Implicit/\";\n\t\t//mesh<C3t3_implicit,Mesh_criteria_implicit>(data_imp,vm); \n\t}\n\treturn 0;\n}\n", "meta": {"hexsha": "ee09c482d570601606b5a638361cc8d5716a3c00", "size": 17314, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "graphics/cgal/Mesh_3/applications/mesher_tester.cpp", "max_stars_repo_name": "hlzz/dotfiles", "max_stars_repo_head_hexsha": "0591f71230c919c827ba569099eb3b75897e163e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-03-30T14:31:52.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-02T05:01:32.000Z", "max_issues_repo_path": "graphics/cgal/Mesh_3/applications/mesher_tester.cpp", "max_issues_repo_name": "hlzz/dotfiles", "max_issues_repo_head_hexsha": "0591f71230c919c827ba569099eb3b75897e163e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "graphics/cgal/Mesh_3/applications/mesher_tester.cpp", "max_forks_repo_name": "hlzz/dotfiles", "max_forks_repo_head_hexsha": "0591f71230c919c827ba569099eb3b75897e163e", "max_forks_repo_licenses": ["BSD-3-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.7688073394, "max_line_length": 156, "alphanum_fraction": 0.6699780524, "num_tokens": 4840, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505964, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.497682270732087}}
{"text": "// -*-coding: mule-utf-8-unix; fill-column: 58; -*-\n\n/**\n * @file\n * A retarget algo abstraction\n *\n * @author Sergei Lodyagin <serg@kogorta.dp.ua>\n */\n\n#include <algorithm>\n#include <iterator>\n#include <numeric>\n#include <boost/thread.hpp>\n#include \"types/fixed.h\"\n#include \"types/abstract_iterator.h\"\n#include \"algos/retarget.h\"\n#include \"log.h\"\n#include \"util.h\"\n#include \"pars.h\"\n#include \"btc_time.h\"\n#include \"checkpoints.h\"\n#include \"main.h\"\n#include \"types.h\"\n\nusing namespace types;\n\nextern std::map<uint256, CBlockIndex*> mapBlockIndex; \nextern CBlockIndex* pindexGenesisBlock;\n\nnamespace retarget {\n\ntemplate<class Algo>\nclass difficulty_impl;\n\n//! Allows change difficulty only by 2 or 1/2\ntemplate<>\nclass difficulty_impl<pars::twice_and_half>\n  : public difficulty\n{\npublic:\n  compact_bignum_t next_block_difficulty(\n    const duration desired_timespan,\n    const iterator& rbegin,\n    const iterator& rend\n  ) override\n  {\n    if (rbegin == rend)\n      return min_difficulty_by_design;\n\n    assert(height_diff(rbegin, rend) > 0);\n\n    auto prev = rbegin;\n    ++prev;\n    const auto actual_timespan = \n      rbegin->time - prev->time;\n    return (\n      (actual_timespan < desired_timespan)\n        ? rbegin->difficulty >> 1\n        : rbegin->difficulty << 1\n    ).GetCompact();\n  }\n\n  compact_bignum_t dos_min_difficulty(\n    compact_bignum_t last_reliable_block_difficulty,\n    coin::times::block::clock::duration past\n  ) const override\n  {\n    return min_difficulty_by_design;\n  }\n};\n\ntemplate<>\nclass difficulty_impl<pars::digishield>\n  : public difficulty\n{\npublic:\n  //! The limit parameter for dos_min_difficulty()\n  const percent_t adjustment_by_design = 110.0_pct;\n\n  compact_bignum_t next_block_difficulty(\n    const duration desired_timespan,\n    const iterator& rbegin,\n    const iterator& rend\n  ) override\n  {\n    if (rbegin == rend)\n      return min_difficulty_by_design;\n\n    auto prev = rbegin;\n    ++prev;\n    auto nActualTimespan = rbegin->time - prev->time;\n\n    LOG() << \"  nActualTimespan = \" \n          << nActualTimespan\n          << \"  before bounds\\n\";\n\n    // thanks to RealSolid & WDC for this code \n     \n    if ( pars::digishield::limit_steps() ) //switch off for development purposes\n    {\n      //Amplitude Filter by daft27\n      nActualTimespan = desired_timespan \n        + (nActualTimespan - desired_timespan)/8;\n    \n      //Guts of DigiShield Retarget\n      if (nActualTimespan < desired_timespan * 3/4)\n        nActualTimespan = desired_timespan * 3/4;\n      \n      if (nActualTimespan > desired_timespan * 3/2) \n        nActualTimespan = desired_timespan * 3/2;\n    }\n\n    if ( coin::times::block::zero_duration == nActualTimespan )\n    {\n        nActualTimespan = coin::times::block::seconds(1);\n    }\n\n    // Retarget\n    const auto last_block_difficulty =\n      rbegin->difficulty;\n    CBigNum bnNew = last_block_difficulty;\n    bnNew *= to_fixed(nActualTimespan);\n    bnNew /= to_fixed(desired_timespan);\n  \n    if (bnNew > min_difficulty_by_design)\n      bnNew = min_difficulty_by_design;\n\n    LOG() \n      << \"GetNextWorkRequired [DigiShield] RETARGET \\n\"\n      << \"retargetTimespan = \" << desired_timespan\n      << \" nActualTimespan = \" << nActualTimespan\n      << \"\\nBefore: \" << last_block_difficulty << ' '\n      << CBigNum(last_block_difficulty).getuint256()\n      << \"\\nAfter: \" << bnNew.GetCompact() << ' '\n      << bnNew.getuint256() << '\\n';\n  \n    return bnNew.GetCompact();\n  }\n\n  compact_bignum_t dos_min_difficulty(\n    compact_bignum_t last_reliable_block_difficulty,\n    coin::times::block::clock::duration past\n  ) const override\n  {\n    if (past < coin::times::block::zero_duration)\n    throw types::exception<coin::except::invalid_timestamp>(\n        \"block with timestamp before last checkpoint\"\n        );\n  \n    return std::min(\n      CBigNum(last_reliable_block_difficulty)\n      * past / block_period_by_design\n      * adjustment_by_design,\n      CBigNum(min_difficulty_by_design)\n      ).GetCompact();\n  }\n};\n\ntemplate<>\nclass difficulty_impl<pars::kgw> : public difficulty\n{\npublic:\n  const int past_blocks_min = \n    pars::kgw::past_min() / block_period_by_design;\n  const int past_blocks_max = \n    pars::kgw::past_max() / block_period_by_design;\n\n  compact_bignum_t next_block_difficulty(\n    const duration desired_timespan,\n    const iterator& rbegin,\n    const iterator& rend\n  ) override\n  {\n    using namespace coin::times::block;\n\n    // TODO don't use floating point\n    using float_duration = std::chrono::duration<double>;\n\n    // early blocks rule\n    if (height_diff(rbegin, rend) < past_blocks_min)\n      return min_difficulty_by_design;\n\n    iterator start = rbegin;\n    std::advance(start, past_blocks_min - 1);\n\n    int64_t mass = past_blocks_min - 1;\n    const auto breaking_el = std::find_if(\n      start,\n      rend,\n      [\n        this,\n        desired_timespan,\n        &rbegin,\n        &mass\n      ]\n        (const block::info_type& bi)\n      {\n        // != 0: fixes the same-time blocks retargetting\n        // exploit\n        constexpr auto min_duration = seconds(1);\n\n        if (++mass > past_blocks_max)\n          return true;\n\n        const clock::duration desired_passed = \n          desired_timespan * mass;\n        const clock::duration actual_passed = \n          // the timewrap fix (part 1)\n          (rbegin->time <= bi.time)\n            ? min_duration\n            : rbegin->time - bi.time;\n        \n\n        assert(actual_passed != zero_duration);\n        const double PastRateAdjustmentRatio =\n          (desired_passed != zero_duration)\n        ?\n          std::chrono::duration_cast<float_duration>(\n            desired_passed\n          )\n          / std::chrono::duration_cast<float_duration>(\n              actual_passed\n          ) \n        :\n          1.0;\n\n        // TODO tabulate it as fixed point values\n        const double EventHorizonDeviation = \n          1 + (0.7084 \n            * pow((double(mass)/double(past_blocks_min)), \n                  -1.228));\n\n        const double EventHorizonDeviationFast = \n          EventHorizonDeviation;\n        const double EventHorizonDeviationSlow = \n          1.0 / EventHorizonDeviation;\n                \n        return PastRateAdjustmentRatio <= \n          EventHorizonDeviationSlow \n          || PastRateAdjustmentRatio >= \n          EventHorizonDeviationFast;\n      }\n    );\n\n    const auto distance = height_diff(rbegin, breaking_el);\n    assert(distance >= 0);\n\n    const CBigNum PastDifficultyAverage = \n      std::accumulate(\n        rbegin, \n        breaking_el, \n        CBigNum(0),\n        [](const CBigNum& acc, const block::info_type& bi)\n        {\n          return acc + bi.difficulty;\n        }\n      ) / (distance + 1);\n\n    // != 0: fixes the same-time blocks retargetting\n    // exploit\n    constexpr auto min_duration = seconds(1);\n\n    const auto range_desired_timespan = \n      desired_timespan * (distance + 1);\n    const auto range_actual_timespan =\n      // the timewrap fix (part 2)\n      (rbegin->time <= breaking_el->time)\n      ? min_duration \n      : rbegin->time - breaking_el->time;\n\n    assert(range_actual_timespan != zero_duration);\n    CBigNum bnNew(PastDifficultyAverage);\n    if (range_desired_timespan != zero_duration)\n    {\n      // actual time passed\n      bnNew *= to_fixed(range_actual_timespan); \n      // desired\n      bnNew /= to_fixed(range_desired_timespan);\n    }\n    if (bnNew > min_difficulty_by_design)\n      bnNew = min_difficulty_by_design;\n  \n    LOG() \n      << \"GetNextWorkRequired [KGW] RETARGET [\"\n      << height_diff(rbegin, breaking_el)\n      << \" last blocks analysed]\"\n      << \"\\navg difficulty: \" \n      << PastDifficultyAverage.GetCompact()\n      << \"\\ndesired timespan for the range = \" \n      << range_desired_timespan\n      << \"\\nactual timespan for the range = \" \n      << range_actual_timespan\n      << \"\\nBefore: \" \n      << rbegin->difficulty << ' '\n      << CBigNum(rbegin->difficulty)\n           . getuint256()\n      << \"\\nAfter: \" << bnNew.GetCompact() << ' '\n      << bnNew.getuint256() << std::endl;\n  \n    return bnNew.GetCompact();\n  }\n\n  compact_bignum_t dos_min_difficulty(\n    compact_bignum_t last_reliable_block_difficulty,\n    coin::times::block::clock::duration past\n  ) const override\n  {\n    return min_difficulty_by_design;\n  }\n};\n\ndifficulty& difficulty::instance()\n{\n  static boost::once_flag of = BOOST_ONCE_INIT;\n  static difficulty* instance = nullptr;\n  boost::call_once([]()\n  { \n    instance = new difficulty_impl\n      <pars::retarget_algorithm>();\n  }, of);\n\n  assert(instance);\n  return *instance;\n}\n\ncompact_bignum_t difficulty\n::next_block_difficulty(const CBlockIndex* pindexLast)\n{\n  using namespace types;\n\n  // Genesis block\n  if (!pindexLast) \n    return min_difficulty_by_design;\n  \n  // Limit adjustment step\n  const auto pindexFirst = pindexLast->pprev;\n  if (!pindexFirst)\n    return pindexLast->nBits; // slod\n\n  return next_block_difficulty(\n    block_period_by_design,\n    block::const_iterator<CBlockIndex>(pindexLast),\n    block::const_iterator<CBlockIndex>(pindexGenesisBlock)\n  );\n}\n\ndifficulty::difficulty()\n  : min_difficulty_by_design(\n      pars::testnet_switch(pars::min_difficulty_by_design)\n    ),\n    block_period_by_design(\n      pars::testnet_switch(pars::block_period_by_design)\n    )\n{\n}\n\nconst CBlockIndex* difficulty\n::dos_last_reliable_block()\n{\n  static const CBlockIndex* last_checkpointed_block =\n    Checkpoints::GetLastCheckpoint(mapBlockIndex);\n\n  if (last_checkpointed_block)\n    return last_checkpointed_block;\n  else\n  {\n    assert(pindexGenesisBlock);\n    return pindexGenesisBlock;\n  }\n}\n\n} // retarget\n", "meta": {"hexsha": "2f3cc958f91a25a5cd9647b154511688c261189a", "size": 9628, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/algos/retarget.cpp", "max_stars_repo_name": "coinkeeper/2015-04-19_21-26_umbrella-ltc", "max_stars_repo_head_hexsha": "8793c46ec070c01204b3838818e2c0dbad0c8185", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/algos/retarget.cpp", "max_issues_repo_name": "coinkeeper/2015-04-19_21-26_umbrella-ltc", "max_issues_repo_head_hexsha": "8793c46ec070c01204b3838818e2c0dbad0c8185", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/algos/retarget.cpp", "max_forks_repo_name": "coinkeeper/2015-04-19_21-26_umbrella-ltc", "max_forks_repo_head_hexsha": "8793c46ec070c01204b3838818e2c0dbad0c8185", "max_forks_repo_licenses": ["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.8123324397, "max_line_length": 80, "alphanum_fraction": 0.6477980889, "num_tokens": 2437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339516289534, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4976822659779271}}
{"text": "//\n//  dt_util.h\n//  Classifer_RF\n//\n//  Created by jimmy on 2017-02-16.\n//  Copyright (c) 2017 Nowhere Planet. All rights reserved.\n//\n\n#ifndef __Classifer_RF__dt_util__\n#define __Classifer_RF__dt_util__\n\n// decision tree util\n#include <stdio.h>\n#include <vector>\n#include <Eigen/Dense>\n#include <unordered_map>\n#include <string>\n\nusing std::vector;\nusing std::string;\nusing Eigen::VectorXf;\nusing Eigen::VectorXd;\nusing Eigen::VectorXi;\n\nusing std::vector;\n\nnamespace dt {\n    // randomly generate a subset of dimensions\n    template<class intType>\n    vector<intType> randomDimension(const intType dim, const intType num);\n    \n    template <class intType>\n    vector<intType> range(int start, int end, int step)\n    {\n        assert((end - start) * step >= 0);\n        vector<intType> ret;\n        for (int i = start; i < end; i += step) {\n            ret.push_back((intType)i);\n        }\n        return ret;\n    }\n    \n    // mean and standard deviation\n    template <class vectorType>\n    void meanStd(const vector<vectorType> & labels, vectorType & mean, vectorType & sigma);\n    \n    template<class vectorType, class intType>\n    void meanStd(const vector<vectorType> & labels, const vector<intType> & indices,\n                 vectorType & mean, vectorType & sigma);\n    \n    // balance examples in each category\n    // return: example indices with balanced training examples\n    template<class intType>\n    vector<intType> balanceSamples(const vector<intType> & example_indices,\n                                   const vector<intType> & labels, const int category_num);\n    \n    // regression loss\n    template<class VectorType, class IntType>\n    double sumOfVariance(const vector<VectorType> & labels, const vector<IntType> & indices);\n    \n    // find most common number in the vector\n    template<class intType>\n    intType mostCommon(const vector<intType> & data);\n    \n    template <class VectorType>\n    void meanMedianError(const vector<VectorType> & errors, VectorType & mean, VectorType & median);\n    \n}  // namespace\n\nclass DTUtil\n{\npublic:\n    // randomly generate a subset of dimensions\n    static vector<unsigned int> randomDimensions(const int dimension, const int ccandidate_dimension);\n    \n    template <class T>\n    static double spatialVariance(const vector<T> & labels, const vector<unsigned int> & indices);\n    \n    // full variance of Gaussian model\n    template <class T>\n    static double fullVariance(const vector<T>& labels, const vector<unsigned int> & indices);\n    \n    template <class MatrixType>\n    static double sumOfVariance(const vector<MatrixType> & labels, const int row_index,\n                                const vector<unsigned int> & indices);\n    \n    template <class Type1, class Type2>\n    static double spatialVariance(const vector<Type1> & labels,\n                                  const vector<unsigned int> & indices, const vector<Type2> & wt);\n    \n    template <class T>\n    static void meanStddev(const vector<T> & labels, const vector<unsigned int> & indices, T & mean, T & sigma);\n    \n    template <class vectorT, class indexT>\n    static vectorT mean(const vector<vectorT> & data, const vector<indexT> & indices);\n    \n    template <class T>\n    static T mean(const vector<T> & data);\n    \n    // mean and standard of particular row\n    template <class matrixType, class vectorType>\n    static void rowMeanStddev(const vector<matrixType> & labels, const vector<unsigned int> & indices,\n                              const int row_index, vectorType & mean,   vectorType & sigma);\n    \n   \n    \n    // https://en.wikipedia.org/wiki/Quartile\n    // q1, q2, q3: first, second and third quartile. The second quartile is median\n    template <class vectorT>\n    static void quartileError(const vector<vectorT> & errors, vectorT & q1, vectorT& q2, vectorT& q3);\n    \n    // mean error of each row of a list of matrixes\n    template <class MatrixType>\n    static void matrixMeanError(const vector<MatrixType> & errors, MatrixType & mean);\n    \n   \n    static double crossEntropy(const Eigen::VectorXd& prob);\n    \n    static double crossEntropy(const Eigen::VectorXf& prob);   \n    \n    \n    static double balanceLoss(const int leftNodeSize, const int rightNodeSize);\n    \n    static bool isSameLabel(const vector<unsigned int> & labels, const vector<unsigned int> & indices);\n    static bool isSameLabel(const vector<int>& labels, const vector<int>& indices);\n    \n    // minimum number of examples in all category\n    static int minLabelNumber(const vector<unsigned int> & labels,\n                              const vector<unsigned int> & indices,\n                              const int num_category);\n    \n    // label is a sequential data\n    static int minLabelNumber(const vector<VectorXi> & labels,\n                              const vector<unsigned int> & indices,\n                              const int time_step,\n                              const int num_category);\n    \n    template <class integerType>\n    static Eigen::MatrixXd confusionMatrix(const vector<integerType> & predictions,\n                                           const vector<integerType> & labels,\n                                           const int category_num,\n                                           bool normalize);\n    \n    // accuracy (should be precision) of each category and average\n    static Eigen::VectorXd accuracyFromConfusionMatrix(const Eigen::MatrixXd & conf);\n    static Eigen::VectorXd precisionFromConfusionMatrix(const Eigen::MatrixXd & conf);\n    \n    template <class T>\n    static vector<T> range(int start, int end, int step)\n    {\n        assert((end - start) * step >= 0);\n        vector<T> ret;\n        for (int i = start; i < end; i += step) {\n            ret.push_back((T)i);\n        }\n        return ret;\n    }\n\n    \n};\n\n#endif /* defined(__Classifer_RF__dt_util__) */\n", "meta": {"hexsha": "5f6d5b6264545d151ece9009df809ac641f83480", "size": 5850, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/pan_tilt_forest/dt_util/dt_util.hpp", "max_stars_repo_name": "lood339/two_point_calib", "max_stars_repo_head_hexsha": "b4b861429c92368e8e4accecc986272070fb19bc", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 45.0, "max_stars_repo_stars_event_min_datetime": "2018-04-22T10:12:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T07:35:07.000Z", "max_issues_repo_path": "src/pan_tilt_forest/dt_util/dt_util.hpp", "max_issues_repo_name": "lood339/two_point_calib", "max_issues_repo_head_hexsha": "b4b861429c92368e8e4accecc986272070fb19bc", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-01-18T06:33:03.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-02T06:11:14.000Z", "max_forks_repo_path": "src/pan_tilt_forest/dt_util/dt_util.hpp", "max_forks_repo_name": "lood339/two_point_calib", "max_forks_repo_head_hexsha": "b4b861429c92368e8e4accecc986272070fb19bc", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2018-03-07T07:25:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T06:16:42.000Z", "avg_line_length": 35.8895705521, "max_line_length": 112, "alphanum_fraction": 0.6398290598, "num_tokens": 1287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743735019594, "lm_q2_score": 0.6723317123102955, "lm_q1q2_score": 0.49764270394477256}}
{"text": "// Copyright 2019 Bold Hearts\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 \"imu_fusion_madgwick/imu_fusion_madgwick.hpp\"\n\n#include <rclcpp/rclcpp.hpp>\n#include <Eigen/Geometry>\n\n#include <gtest/gtest.h>\n#include <memory>\n\ntemplate<typename T, int N>\ninline ::testing::AssertionResult VectorsEqual(\n  Eigen::Matrix<T, N, 1> const & expected,\n  Eigen::Matrix<T, N, 1> const & actual,\n  const double delta = 0.00001)\n{\n  double d = (expected - actual).norm();\n  if (d < delta) {\n    return ::testing::AssertionSuccess();\n  } else {\n    return ::testing::AssertionFailure() << \"Actual: \" << actual.transpose() << \", expected: \" <<\n           expected.transpose() << \" d = \" << d;\n  }\n}\n\ninline ::testing::AssertionResult MatricesEqual(\n  Eigen::MatrixXd const & expected,\n  Eigen::MatrixXd const & actual,\n  double delta = 0.000001)\n{\n  double d = (expected - actual).array().abs().sum();\n  if (d < delta) {\n    return ::testing::AssertionSuccess();\n  } else {\n    return ::testing::AssertionFailure() << \"Actual: \" << std::endl << actual << std::endl <<\n           \"Expected: \" << std::endl << expected << std::endl << \" d = \" << d;\n  }\n}\n\nTEST(OrientationTests, construction)\n{\n  imu_fusion_madgwick::IMUFusionMadgwick orientation;\n  auto quaternion = orientation.getEigenQuaternion();\n\n  EXPECT_EQ(1.0, quaternion.w() );\n  EXPECT_EQ(Eigen::Vector3d::Zero(), quaternion.vec() );\n}\n\nTEST(OrientationTests, gyro_halfPiXHighFreq)\n{\n  imu_fusion_madgwick::IMUFusionMadgwick orientation;\n\n  for (unsigned i = 0; i < 512; ++i) {\n    orientation.integrate(Eigen::Vector3d{0.5 * M_PI, 0, 0}, 1.0 / 512);\n  }\n\n  auto quaternion = orientation.getEigenQuaternion();\n\n  EXPECT_TRUE(\n    MatricesEqual(\n      Eigen::AngleAxisd(0.5 * M_PI, Eigen::Vector3d::UnitX()).matrix(),\n      quaternion.matrix()));\n}\n\nTEST(OrientationTests, gyro_halfPiX)\n{\n  imu_fusion_madgwick::IMUFusionMadgwick orientation;\n\n  orientation.integrate(Eigen::Vector3d{0.5 * M_PI, 0, 0}, 1.0);\n\n  EXPECT_TRUE(\n    MatricesEqual(\n      Eigen::AngleAxisd(0.5 * M_PI, Eigen::Vector3d::UnitX()).matrix(),\n      orientation.getEigenQuaternion().matrix()));\n}\n\nTEST(OrientationTests, gyro_halfPiY)\n{\n  imu_fusion_madgwick::IMUFusionMadgwick orientation;\n\n  orientation.integrate(Eigen::Vector3d{0, 0.5 * M_PI, 0}, 1.0);\n\n  EXPECT_TRUE(\n    MatricesEqual(\n      Eigen::AngleAxisd(0.5 * M_PI, Eigen::Vector3d::UnitY()).matrix(),\n      orientation.getEigenQuaternion().matrix()));\n}\n\nTEST(OrientationTests, gyro_halfPiZ)\n{\n  imu_fusion_madgwick::IMUFusionMadgwick orientation;\n  orientation.integrate(Eigen::Vector3d{0, 0, 0.5 * M_PI}, 1.0);\n\n  EXPECT_TRUE(\n    MatricesEqual(\n      Eigen::AngleAxisd(0.5 * M_PI, Eigen::Vector3d::UnitZ()).matrix(),\n      orientation.getEigenQuaternion().matrix()));\n}\n\nTEST(OrientationTests, gyro_piX)\n{\n  imu_fusion_madgwick::IMUFusionMadgwick orientation;\n  orientation.integrate(Eigen::Vector3d{0.5 * M_PI, 0, 0}, 2.0);\n\n  EXPECT_TRUE(\n    MatricesEqual(\n      Eigen::AngleAxisd(M_PI, Eigen::Vector3d::UnitX()).matrix(),\n      orientation.getEigenQuaternion().matrix()));\n}\n\nTEST(OrientationTests, gyro_piY)\n{\n  imu_fusion_madgwick::IMUFusionMadgwick orientation;\n  orientation.integrate(Eigen::Vector3d{0, 0.5 * M_PI, 0}, 2.0);\n\n  EXPECT_TRUE(\n    MatricesEqual(\n      Eigen::AngleAxisd(M_PI, Eigen::Vector3d::UnitY()).matrix(),\n      orientation.getEigenQuaternion().matrix()));\n}\n\nTEST(OrientationTests, gyro_piZ)\n{\n  imu_fusion_madgwick::IMUFusionMadgwick orientation;\n  orientation.integrate(Eigen::Vector3d{0, 0, 0.5 * M_PI}, 2.0);\n\n  EXPECT_TRUE(\n    MatricesEqual(\n      Eigen::AngleAxisd(M_PI, Eigen::Vector3d::UnitZ()).matrix(),\n      orientation.getEigenQuaternion().matrix()));\n}\n\nTEST(OrientationTests, gyro_quartPiX)\n{\n  imu_fusion_madgwick::IMUFusionMadgwick orientation;\n  orientation.integrate(Eigen::Vector3d{0.5 * M_PI, 0, 0}, .5);\n\n  EXPECT_TRUE(\n    MatricesEqual(\n      Eigen::AngleAxisd(0.25 * M_PI, Eigen::Vector3d::UnitX()).matrix(),\n      orientation.getEigenQuaternion().matrix()));\n}\n\nTEST(OrientationTests, gyro_quartPiY)\n{\n  imu_fusion_madgwick::IMUFusionMadgwick orientation;\n  orientation.integrate(Eigen::Vector3d{0, 0.5 * M_PI, 0}, .5);\n\n  EXPECT_TRUE(\n    MatricesEqual(\n      Eigen::AngleAxisd(0.25 * M_PI, Eigen::Vector3d::UnitY()).matrix(),\n      orientation.getEigenQuaternion().matrix()));\n}\n\nTEST(OrientationTests, gyro_quartPiZ)\n{\n  imu_fusion_madgwick::IMUFusionMadgwick orientation;\n  orientation.integrate(Eigen::Vector3d{0, 0, 0.5 * M_PI}, .5);\n\n  EXPECT_TRUE(\n    MatricesEqual(\n      Eigen::AngleAxisd(0.25 * M_PI, Eigen::Vector3d::UnitZ()).matrix(),\n      orientation.getEigenQuaternion().matrix()));\n}\n\nTEST(OrientationTests, gyro_multiAxis)\n{\n  imu_fusion_madgwick::IMUFusionMadgwick orientation;\n  orientation.integrate(Eigen::Vector3d{1.0, 1.0, 1.0}.normalized() * 2.0 / 3.0 * M_PI, 1.0);\n\n  EXPECT_TRUE(\n    MatricesEqual(\n      Eigen::AngleAxisd(\n        2.0 / 3.0 * M_PI,\n        Eigen::Vector3d(1.0, 1.0, 1.0).normalized()).matrix(),\n      orientation.getEigenQuaternion().matrix()));\n}\n\nTEST(OrientationTests, gyro_zero)\n{\n  imu_fusion_madgwick::IMUFusionMadgwick orientation;\n  Eigen::Vector4d oldCoeffs = orientation.getEigenQuaternion().coeffs();\n  orientation.integrate(Eigen::Vector3d::Zero(), 0.008);\n\n  EXPECT_TRUE(MatricesEqual(oldCoeffs, orientation.getEigenQuaternion().coeffs()));\n}\n\nTEST(OrientationTests, gyro_chained)\n{\n  imu_fusion_madgwick::IMUFusionMadgwick orientation;\n  orientation.integrate(Eigen::Vector3d{0.5 * M_PI, 0, 0}, 1.0);\n  orientation.integrate(Eigen::Vector3d{0, 0, 0.5 * M_PI}, 1.0);\n\n  EXPECT_TRUE(\n    MatricesEqual(\n      (Eigen::AngleAxisd(0.5 * M_PI, Eigen::Vector3d::UnitX()) *\n      Eigen::AngleAxisd(0.5 * M_PI, Eigen::Vector3d::UnitZ())).matrix(),\n      orientation.getEigenQuaternion().matrix()));\n}\n\nTEST(OrientationTests, merged_no_error)\n{\n  imu_fusion_madgwick::IMUFusionMadgwick orientation;\n  auto q0 = orientation.getEigenQuaternion();\n  orientation.integrate(Eigen::Vector3d::Zero(), 1.0, Eigen::Vector3d{0.0, 0.0, 1.0}, 0.1);\n\n  EXPECT_TRUE(VectorsEqual(q0.coeffs(), orientation.getEigenQuaternion().coeffs()));\n}\n\nTEST(OrientationTests, merged_turned_no_error)\n{\n  imu_fusion_madgwick::IMUFusionMadgwick orientation;\n  // Turn 90 deg around x axis\n  orientation.integrate(Eigen::Vector3d{0.5 * M_PI, 0, 0}, 1.0);\n  auto q1 = orientation.getEigenQuaternion();\n  // Gravity is now along y axis\n  orientation.integrate(Eigen::Vector3d::Zero(), 1.0, Eigen::Vector3d{0.0, 1.0, 0.0}, 0.1);\n\n  EXPECT_TRUE(VectorsEqual(q1.coeffs(), orientation.getEigenQuaternion().coeffs()));\n}\n\nTEST(OrientationTests, merged_90deg_error)\n{\n  imu_fusion_madgwick::IMUFusionMadgwick orientation;\n\n  // Gravity is now along y axis\n  orientation.integrate(Eigen::Vector3d::Zero(), 1.0, Eigen::Vector3d{0.0, 1.0, 0.0}, 0.1);\n\n  EXPECT_FLOAT_EQ(1.0, orientation.getEigenQuaternion().norm());\n  EXPECT_LT(0.0, orientation.getEigenQuaternion().x());\n\n  // Test convergence after 20 seconds\n  for (unsigned i = 0; i < 10000; ++i) {\n    orientation.integrate(Eigen::Vector3d::Zero(), 1.0 / 500, Eigen::Vector3d{0.0, 1.0, 0.0}, 0.1);\n  }\n\n  // Quaternion element is sin(theta / 2)\n  EXPECT_NEAR(sin(.25 * M_PI), orientation.getEigenQuaternion().coeffs().x(), 0.00002);\n}\n\n\nint main(int argc, char ** argv)\n{\n  testing::InitGoogleTest(&argc, argv);\n\n  rclcpp::init(argc, argv);\n\n  return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "afa06a3791e9554af5d7ae450543e91e70c000ac", "size": 7893, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "imu_fusion_madgwick/test/imu_fusion_madgwick_tests.cpp", "max_stars_repo_name": "yushijinhun/ros2_imu_tools", "max_stars_repo_head_hexsha": "3a001170b07c104c49aad67299d9c14a6af27fbb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "imu_fusion_madgwick/test/imu_fusion_madgwick_tests.cpp", "max_issues_repo_name": "yushijinhun/ros2_imu_tools", "max_issues_repo_head_hexsha": "3a001170b07c104c49aad67299d9c14a6af27fbb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "imu_fusion_madgwick/test/imu_fusion_madgwick_tests.cpp", "max_forks_repo_name": "yushijinhun/ros2_imu_tools", "max_forks_repo_head_hexsha": "3a001170b07c104c49aad67299d9c14a6af27fbb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-13T12:01:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T12:01:28.000Z", "avg_line_length": 30.1259541985, "max_line_length": 99, "alphanum_fraction": 0.6994805524, "num_tokens": 2380, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743735019595, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.49764269908515435}}
{"text": "/*\n@copyright Louis Dionne 2015\nDistributed under the Boost Software License, Version 1.0.\n(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n */\n\n#include <boost/hana/assert.hpp>\n#include <boost/hana/config.hpp>\n#include <boost/hana/integral_constant.hpp>\n#include <boost/hana/maybe.hpp>\n#include <boost/hana/set.hpp>\n#include <boost/hana/string.hpp>\n#include <boost/hana/type.hpp>\nusing namespace boost::hana;\n\n\nint main() {\n\n{\n\n//! [comparable]\nBOOST_HANA_CONSTANT_CHECK(\n    set(int_<0>, type<char>, int_<1>) == set(int_<1>, int_<0>, type<char>)\n);\n\nBOOST_HANA_CONSTEXPR_CHECK(set(1, '2', 3.3) == set('2', 1, 3.3));\nBOOST_HANA_CONSTANT_CHECK(set(1, '2', 3.3) != set('2', 1));\n//! [comparable]\n\n}{\n\n//! [searchable]\nconstexpr auto xs = set(int_<0>, int_<1>, int_<2>);\nBOOST_HANA_CONSTANT_CHECK(find(xs, int_<0>) == just(int_<0>));\nBOOST_HANA_CONSTANT_CHECK(find(xs, int_<3>) == nothing);\n//! [searchable]\n\n}{\n\n//! [foldable]\nconstexpr auto xs = set(int_<0>, int_<1>, int_<2>);\nstatic_assert(minimum(xs) == int_<0>, \"\");\nstatic_assert(maximum(xs) == int_<2>, \"\");\nstatic_assert(sum(xs) == int_<3>, \"\");\n\n// folding is not really meaningful since the order of the\n// elements is unspecified.\n//! [foldable]\n\n}{\n\n//! [insert]\nconstexpr auto xs = set(int_<0>, type<int>);\nBOOST_HANA_CONSTANT_CHECK(\n    insert(xs, BOOST_HANA_STRING(\"abc\")) ==\n    set(int_<0>, type<int>, BOOST_HANA_STRING(\"abc\"))\n);\n\nBOOST_HANA_CONSTANT_CHECK(\n    insert(xs, int_<0>) == set(int_<0>, type<int>)\n);\n//! [insert]\n\n}\n\n}\n", "meta": {"hexsha": "096eddd49b1f869bd17e00184138111cbebb99d7", "size": 1528, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/set.cpp", "max_stars_repo_name": "josephwinston/hana", "max_stars_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/set.cpp", "max_issues_repo_name": "josephwinston/hana", "max_issues_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/set.cpp", "max_forks_repo_name": "josephwinston/hana", "max_forks_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.8059701493, "max_line_length": 78, "alphanum_fraction": 0.6708115183, "num_tokens": 441, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743735019594, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.49764269908515424}}
{"text": "\n// BLAS level 3 -- complex numbers\n\n//#define BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n\n#include <iostream>\n#include <complex>\n#include <boost/numeric/bindings/blas/level3.hpp>\n#include <boost/numeric/bindings/ublas/matrix.hpp>\n#include <boost/numeric/bindings/conj.hpp>\n#ifdef F_USE_STD_VECTOR\n#include <vector>\n#include <boost/numeric/bindings/std/vector.hpp> \n#endif \n#include \"utils.h\" \n\nnamespace ublas = boost::numeric::ublas;\nnamespace blas = boost::numeric::bindings::blas;\nnamespace bindings = boost::numeric::bindings;\n\nusing std::cout;\nusing std::endl; \n\ntypedef double real_t;\ntypedef std::complex<real_t> cmplx_t; \n\n#ifndef F_USE_STD_VECTOR\ntypedef ublas::matrix<cmplx_t, ublas::row_major> m_t;\n#else\ntypedef ublas::matrix<cmplx_t, ublas::column_major, std::vector<cmplx_t> > m_t;\n#endif \n\nint main() {\n\n  cout << endl; \n\n  m_t a (2, 2);\n  a (0, 0) = cmplx_t (1., 0.);\n  a (0, 1) = cmplx_t (2., 0.);\n  a (1, 0) = cmplx_t (3., 0.);\n  a (1, 1) = cmplx_t (4., 0.);\n  print_m (a, \"A\"); \n  cout << endl; \n\n  m_t b (2, 3);\n  b (0, 0) = cmplx_t (1., 0.);\n  b (0, 1) = cmplx_t (2., 0.);\n  b (0, 2) = cmplx_t (3., 0.);\n  b (1, 0) = cmplx_t (1., 0.);\n  b (1, 1) = cmplx_t (2., 0.);\n  b (1, 2) = cmplx_t (3., 0.);\n  print_m (b, \"B\"); \n  cout << endl; \n  \n  m_t c (2, 3);\n\n  // c = a b\n  blas::gemm ( 1.0, a, b, 0.0, c); \n  print_m (c, \"A B\"); \n  cout << endl; \n\n  a (0, 0) = cmplx_t (0., 1.);\n  a (0, 1) = cmplx_t (0., 2.);\n  a (1, 0) = cmplx_t (0., 3.);\n  a (1, 1) = cmplx_t (0., 4.);\n  print_m (a, \"A\"); \n  cout << endl; \n  \n  // c = a b\n  blas::gemm (1.0, a, b, 0.0, c); \n  print_m (c, \"A B\"); \n  cout << endl; \n\n  // c = a^T b\n  blas::gemm ( 1.0, bindings::trans(a), b, 0.0, c); \n  print_m (c, \"A^T B\"); \n  cout << endl; \n\n  // c = a^H b\n  blas::gemm (1.0, bindings::conj(a), b, 0.0, c); \n  print_m (c, \"A^H B\"); \n\n  cout << endl; \n\n}\n", "meta": {"hexsha": "2d336ac2c8303a5067b24f515093b2344ddf1485", "size": 1837, "ext": "cc", "lang": "C++", "max_stars_repo_path": "externals/numeric_bindings/libs/numeric/bindings/atlas/ublas_cmatr3.cc", "max_stars_repo_name": "ljktest/siconos", "max_stars_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 137.0, "max_stars_repo_stars_event_min_datetime": "2015-06-16T15:55:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T06:01:59.000Z", "max_issues_repo_path": "externals/numeric_bindings/libs/numeric/bindings/atlas/ublas_cmatr3.cc", "max_issues_repo_name": "ljktest/siconos", "max_issues_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 381.0, "max_issues_repo_issues_event_min_datetime": "2015-09-22T15:31:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-14T09:05:23.000Z", "max_forks_repo_path": "externals/numeric_bindings/libs/numeric/bindings/atlas/ublas_cmatr3.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": 21.3604651163, "max_line_length": 79, "alphanum_fraction": 0.5645073489, "num_tokens": 755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743735019595, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.4976426893659175}}
{"text": "/*\n * Tools.hpp\n *\n *  Created on: Feb 19, 2012\n *      Author: david\n */\n\n#ifndef POINTSANDNORMALS_HPP_\n#define POINTSANDNORMALS_HPP_\n\n#include <Slimage/Slimage.hpp>\n#include <eigen3/Eigen/Dense>\n#include <eigen3/Eigen/Eigenvalues>\n#include <boost/math/constants/constants.hpp>\n#include <vector>\n#include <cmath>\n#include <ctype.h>\n#include <ostream>\n\nnamespace dasp {\n\ntemplate<typename K>\nK Square(K x) {\n\treturn x*x;\n}\n\ntemplate<typename K>\nstd::ostream& operator<<(std::ostream& os, const std::vector<K>& v)\n{\n\tos << \"{\";\n\tfor(unsigned int i=0; i<v.size(); i++) {\n\t\tos << v[i];\n\t\tif(i + 1 != v.size()) {\n\t\t\tos << \", \";\n\t\t}\n\t}\n\tos << \"}\";\n\treturn os;\n}\n\ntemplate<typename K,typename U=unsigned int>\nstruct Histogram\n{\n\tHistogram()\n\t: min_(0), max_(1) {}\n\tHistogram(unsigned int bin_count, K min, K max)\n\t: min_(min), max_(max), bins_(bin_count) {}\n\tvoid add(K x, U v=U(1)) {\n\t\tfloat p = float(x - min_) * float(bins_.size()) / float(max_ - min_);\n\t\tint i = std::round(p);\n\t\tif(i < 0) i = 0;\n\t\tif(i >= int(bins_.size())) i = bins_.size() - 1;\n\t\tbins_[i] += v;\n\t}\n\tconst std::vector<U>& bins() const {\n\t\treturn bins_;\n\t}\n\tconst U operator[](unsigned int i) const {\n\t\treturn bins_[i];\n\t}\n\tfriend std::ostream& operator<<(std::ostream& os, const Histogram<K,U>& h) {\n\t\tos << h.bins();\n\t\treturn os;\n\t}\nprivate:\n\tK min_, max_;\n\tstd::vector<U> bins_;\n};\n\n/***\n *\n */\nstruct Camera\n{\n\tfloat cx, cy;\n        float crx;\n        float cry;\n\tfloat focal;\n\tfloat z_slope;\n\n\t/** Projects a 3D point into the image plane */\n\tEigen::Vector2f project(const Eigen::Vector3f& p) const {\n\t\treturn Eigen::Vector2f(p[0] / p[2] * focal + cx - crx, p[1] / p[2] * focal + cy - cry);\n\t}\n\n\t/** Computes a 3D point from pixel position and z/focal */\n\tEigen::Vector3f unprojectImpl(float px, float py, float z_over_f) const {\n\t\treturn z_over_f * Eigen::Vector3f(px - cx + crx, py - cy + cry, focal);\n\t}\n\t\n\t/** Computes a 3D point from pixel position and depth */\n\tEigen::Vector3f unproject(int x, int y, uint16_t depth) const {\n\t\treturn unprojectImpl(\n\t\t\tstatic_cast<float>(x), static_cast<float>(y),\n\t\t\tconvertKinectToMeter(depth) / focal\n\t\t);\n\t}\n\n\t/** Gets kinect depth for a 3D point */\n\tuint16_t depth(const Eigen::Vector3f& p) const {\n\t\treturn convertMeterToKinect(p[2]);\n\t}\n\n\t/** Convert kinect depth to meter */\n\tfloat convertKinectToMeter(uint16_t d) const {\n\t\treturn static_cast<float>(d) * z_slope;\n\t}\n\n\tfloat convertKinectToMeter(int d) const {\n\t\treturn static_cast<float>(d) * z_slope;\n\t}\n\n\tfloat convertKinectToMeter(float d) const {\n\t\treturn d * z_slope;\n\t}\n\n\t/** Convert meter to kinect depth */\n\tuint16_t convertMeterToKinect(float z) const {\n\t\treturn static_cast<uint16_t>(z / z_slope);\n\t}\n\n\tfloat computeOpenGLFOV(unsigned int height) const {\n\t\treturn 2.0f * std::atan(static_cast<float>(height)/focal*0.5f) / boost::math::constants::pi<float>() * 180.0f;\n\t}\n\n};\n\ntemplate<typename K>\ninline float LocalFiniteDifferencesKinect(K v0, K v1, K v2, K v3, K v4)\n{\n\tif(v0 == 0 && v4 == 0 && v1 != 0 && v3 != 0) {\n\t\treturn float(v3 - v1);\n\t}\n\n\tbool left_invalid = (v0 == 0 || v1 == 0);\n\tbool right_invalid = (v3 == 0 || v4 == 0);\n\tif(left_invalid && right_invalid) {\n\t\treturn 0.0f;\n\t}\n\telse if(left_invalid) {\n\t\treturn float(v4 - v2);\n\t}\n\telse if(right_invalid) {\n\t\treturn float(v2 - v0);\n\t}\n\telse {\n\t\tfloat a = static_cast<float>(std::abs(v2 + v0 - static_cast<K>(2)*v1));\n\t\tfloat b = static_cast<float>(std::abs(v4 + v2 - static_cast<K>(2)*v3));\n\t\tfloat p, q;\n\t\tif(a + b == 0.0f) {\n\t\t\tp = q = 0.5f;\n\t\t}\n\t\telse {\n\t\t\tp = a / (a + b);\n\t\t\tq = b / (a + b);\n\t\t}\n\t\treturn q * static_cast<float>(v2 - v0) + p * static_cast<float>(v4 - v2);\n\t}\n}\n\ntemplate<typename K>\ninline K LocalFiniteDifferencesKinectSimple(K v0, K v1, K v2, K v3, K v4)\n{\n\tif(v0 == 0 && v4 == 0 && v1 != 0 && v3 != 0) {\n\t\treturn v3 - v1;\n\t}\n\n\tbool left_invalid = (v0 == 0 || v1 == 0);\n\tbool right_invalid = (v3 == 0 || v4 == 0);\n\tif(left_invalid && right_invalid) {\n\t\treturn 0;\n\t}\n\telse if(left_invalid) {\n\t\treturn v4 - v2;\n\t}\n\telse if(right_invalid) {\n\t\treturn v2 - v0;\n\t}\n\telse {\n\t\tK a = std::abs(v2 + v0 - static_cast<K>(2)*v1);\n\t\tK b = std::abs(v4 + v2 - static_cast<K>(2)*v3);\n\t\tif(a < b) {\n\t\t\treturn v2 - v0;\n\t\t}\n\t\telse {\n\t\t\treturn v4 - v2;\n\t\t}\n\t}\n}\n\ninline Eigen::Vector2f LocalDepthGradient(const slimage::Image1ui16& depth, unsigned int j, unsigned int i, float z_over_f, float window, const Camera& camera)\n{\n\t// compute w = base_scale*f/d\n\tunsigned int w = std::max(static_cast<unsigned int>(window + 0.5f), 4u);\n\tif(w % 2 == 1) w++;\n\n\t// can not compute the gradient at the border, so return 0\n\tif(i < w || depth.height() - w <= i || j < w || depth.width() - w <= j) {\n\t\treturn Eigen::Vector2f::Zero();\n\t}\n\n\tfloat dx = LocalFiniteDifferencesKinect<int>(\n\t\tdepth(j-w,i),\n\t\tdepth(j-w/2,i),\n\t\tdepth(j,i),\n\t\tdepth(j+w/2,i),\n\t\tdepth(j+w,i)\n\t);\n\n\tfloat dy = LocalFiniteDifferencesKinect<int>(\n\t\tdepth(j,i-w),\n\t\tdepth(j,i-w/2),\n\t\tdepth(j,i),\n\t\tdepth(j,i+w/2),\n\t\tdepth(j,i+w)\n\t);\n\n\t// Theoretically scale == base_scale, but w must be an integer, so we\n\t// compute scale from the actually used w.\n\n\t// compute 1 / scale = 1 / (w*d/f)\n\tfloat scl = 1.0f / (float(w) * z_over_f);\n\n\treturn scl * Eigen::Vector2f(camera.convertKinectToMeter(dx), camera.convertKinectToMeter(dy));\n}\n\ninline Eigen::Vector2f LocalDepthGradient(const slimage::Image1ui16& depth, unsigned int j, unsigned int i, float base_radius_m, const Camera& camera)\n{\n\tuint16_t d00 = depth(j,i);\n\tif(d00 == 0) {\n\t\treturn Eigen::Vector2f::Zero();\n\t}\n\tfloat z_over_f = camera.convertKinectToMeter(d00) / camera.focal;\n\tfloat window = base_radius_m/z_over_f;\n\treturn LocalDepthGradient(depth, j, i, z_over_f, window, camera);\n}\n\ntemplate<typename T, typename F>\nEigen::Matrix3f PointCovariance(const std::vector<T>& points, F f)\n{\n//\tEigen::Matrix3f A = Eigen::Matrix3f::Zero();\n//\tfor(const Eigen::Vector3f& p : points) {\n//\t\tA += p * p.transpose();\n//\t}\n\tfloat xx=0.0f, xy=0.0f, xz=0.0f, yy=0.0f, yz=0.0f, zz=0.0f;\n\tfor(auto it=points.begin(); it!=points.end(); ++it) {\n\t\tconst Eigen::Vector3f& p = f(*it);\n\t\tfloat x = p[0];\n\t\tfloat y = p[1];\n\t\tfloat z = p[2];\n\t\txx += x*x;\n\t\txy += x*y;\n\t\txz += x*z;\n\t\tyy += y*y;\n\t\tyz += y*z;\n\t\tzz += z*z;\n\t}\n\tEigen::Matrix3f A; A << xx, xy, xz, xy, yy, yz, xz, yz, zz;\n\tA /= static_cast<float>(points.size());\n\treturn A;\n}\n\ntemplate<typename T, typename F>\nEigen::Matrix<float,6,1> Shape(const std::vector<T>& points, F f)\n{\n\ttypedef double K;\n\tconst K SCL = 100.0f;\n\ttypedef Eigen::Matrix<K,6,6> Mat6;\n\ttypedef Eigen::Matrix<K,6,1> Vec6;\n\tK Sx=0, Sy=0;\n\tK Sxx=0, Sxy=0, Syy=0;\n\tK Sxxx=0, Sxxy=0, Sxyy=0, Syyy=0;\n\tK Sxxxx=0, Sxxxy=0, Sxxyy=0, Sxyyy=0, Syyyy=0;\n\tK Sz=0, Szx=0, Szy=0, Szxx=0, Szxy=0, Szyy=0;\n\tfor(auto it=points.begin(); it!=points.end(); ++it) {\n\t\tconst Eigen::Vector3f& p = f(*it);\n\t\tK x = SCL*p[0];\n\t\tK y = SCL*p[1];\n\t\tK z = SCL*p[2];\n\t\tK xx = x*x;\n\t\tK xy = x*y;\n\t\tK yy = y*y;\n\t\tSx += x;\n\t\tSy += y;\n\t\tSxx += xx;\n\t\tSxy += xy;\n\t\tSyy += yy;\n\t\tSxxx += x*xx;\n\t\tSxxy += x*xy;\n\t\tSxyy += x*yy;\n\t\tSyyy += y*yy;\n\t\tSxxxx += xx*xx;\n\t\tSxxxy += xx*xy;\n\t\tSxxyy += xx*yy;\n\t\tSxyyy += xy*yy;\n\t\tSyyyy += yy*yy;\n\t\tSz += z;\n\t\tSzx += z*x;\n\t\tSzy += z*y;\n\t\tSzxx += z*xx;\n\t\tSzxy += z*xy;\n\t\tSzyy += z*yy;\n\t}\n\tK S0 = points.size();\n\tMat6 A;\n\tA << S0, Sx, Sy, Sxy, Sxx, Syy,\n\t\t Sx, Sxx, Sxy, Sxxy, Sxxx, Sxyy,\n\t\t Sy, Sxy, Syy, Sxyy, Sxxy, Syyy,\n\t\t Sxy, Sxxy, Sxyy, Sxxyy, Sxxxy, Sxyyy,\n\t\t Sxx, Sxxx, Sxxy, Sxxxy, Sxxxx, Sxxyy,\n\t\t Syy, Sxyy, Syyy, Sxyyy, Sxxyy, Syyyy;\n\tVec6 b;\n\tb << Sz, Szx, Szy, Szxy, Szxx, Szyy;\n\tVec6 r = A.colPivHouseholderQr().solve(b);\n\tr[0] /= SCL;\n\tr[3] *= SCL;\n\tr[4] *= SCL;\n\tr[5] *= SCL;\n\treturn r.cast<float>();\n}\n\n/** Fits a plane into points and returns the plane normal */\ntemplate<typename T, typename F>\nEigen::Vector3f FitNormal(const std::vector<T>& points, F f)\n{\n//\t\treturn Eigen::Vector3f(0.0f, 0.0f, 1.0f);\n\t// compute covariance matrix\n\tEigen::Matrix3f A = PointCovariance(points, f);\n\t// compute eigenvalues/-vectors\n\tEigen::SelfAdjointEigenSolver<Eigen::Matrix3f> solver;\n\tsolver.compute(A);\n\t// take eigenvector (first eigenvalue is smallest!)\n\treturn solver.eigenvectors().col(0).normalized();\n}\n\n}\n\n#endif\n", "meta": {"hexsha": "94ba3efb3ac4397fd07ba5070fd743e27c884598", "size": 8092, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib_dasp/lib_dasp/Tools.hpp", "max_stars_repo_name": "jbellis/superpixel-benchmark", "max_stars_repo_head_hexsha": "81a45649d426751d1ae450ef8ea0d2d9c7b3545f", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 344.0, "max_stars_repo_stars_event_min_datetime": "2016-12-16T10:11:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T06:08:14.000Z", "max_issues_repo_path": "lib_dasp/lib_dasp/Tools.hpp", "max_issues_repo_name": "jbellis/superpixel-benchmark", "max_issues_repo_head_hexsha": "81a45649d426751d1ae450ef8ea0d2d9c7b3545f", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2018-02-15T19:34:19.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-31T17:04:48.000Z", "max_forks_repo_path": "lib_dasp/lib_dasp/Tools.hpp", "max_forks_repo_name": "jbellis/superpixel-benchmark", "max_forks_repo_head_hexsha": "81a45649d426751d1ae450ef8ea0d2d9c7b3545f", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 111.0, "max_forks_repo_forks_event_min_datetime": "2016-12-08T07:19:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T06:08:16.000Z", "avg_line_length": 23.8702064897, "max_line_length": 159, "alphanum_fraction": 0.6183885319, "num_tokens": 2899, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.49764268165901754}}
{"text": "#include <math.h>\n#include <algorithm>\n#include <boost/graph/iteration_macros.hpp>\n#include <boost/graph/bc_clustering.hpp>\n#include <boost/graph/copy.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <boost/graph/johnson_all_pairs_shortest.hpp>\n#include <boost/bind.hpp>\n#include <iomanip>\n#include <time.h>\n#include <socialgraph.h>\n\n\nvoid SocialGraph::setGraph(std::ifstream &fin){\n\t//read file\n\tfacebook::Data data = facebook::readFile(fin, name);\n\n\t//create map for name and id\n\tmap = facebook::createMap(data);\n\n\t//create graph\n\tg = facebook::createGraph(data, map);\n\n\tfor(int i=0; i<num_vertices(g); i++){\n\t\tput(vertex_name, g, i, name[i]);\n\t}\n\n\tforces.resize(num_vertices(g));\n\n\t//create centrality graph\n\tcg = g;\n}\n\nvoid SocialGraph::setGraph2(std::ifstream &fin){\n\tfacebook::Name t_name;\n\tfacebook::Data data = facebook::readFile(fin, t_name);\n\n\tmap2 = facebook::createMap(data);\n\n\tg2 = facebook::createGraph(data, map2);\n}\n\nvoid SocialGraph::setWeightedGraph(){\n\tWeightedGraph twg(num_vertices(g));\n\t\n\tproperty_map<WeightedGraph, edge_weight_t>::type weightmap = get(edge_weight, twg);\n\tEdgeIterator e, e_end;\n\tfor(tie(e, e_end) = edges(cg); e != e_end; e++){\n\t\tWeightedEdgeDescriptor e1; bool inserted;\n\t\ttie(e1, inserted) = add_edge(source(*e, cg), target(*e, cg), twg);\n\t\tweightmap[e1] = 1;\n\t}\n\t\n\twg = twg;\n}\n\nvoid SocialGraph::setNodes(){\n\tnodes.resize(num_vertices(g));\n\tfor(int i=0; i<num_vertices(g); i++){\n\t\tnodes[i].x = (rand() % 200) -100;\n\t\tnodes[i].y = (rand() % 200) -100;\n\t\tnodes[i].dx = 0;\n\t\tnodes[i].dy = 0;\n\t}\n}\n\nvoid SocialGraph::setNode(int i, int x, int y){\n\tnodes[i].x = x;\n\tnodes[i].y = y;\n}\n\nGraph SocialGraph::getGraph(){\n\treturn g;\n}\n\nGraph SocialGraph::getGraph2(){\n\treturn g2;\n}\n\nWeightedGraph SocialGraph::getWeightedGraph(){\n\treturn wg;\n}\n\nfacebook::Name SocialGraph::getName(){\n\treturn name;\n}\n\nGraph SocialGraph::getClusterGraph(){\n\treturn cg;\n}\n\nGraph SocialGraph::getClusterGraph2(){\n\treturn cg2;\n}\n\nNodes SocialGraph::getNodes(){\n\treturn nodes;\n}\n\nvoid SocialGraph::repF(int i){\n\tfor(int j=i+1; j<nodes.size(); j++){\n\t\tfloat nx = nodes[i].x - nodes[j].x;\n\t\tfloat ny = nodes[i].y - nodes[j].y;\n\t\tfloat r = sqrt(pow(nx, 2) + pow(ny, 2));\n\t\tif(r > 0){\n\t\t\tfloat f = 900 / (r * r);\n\t\t\tforces[i].x += f * nx / r;\n\t\t\tforces[i].y += f * ny / r;\n\t\t\tforces[j].x -= f * nx / r;\n\t\t\tforces[j].y -= f * ny / r;\n\t\t}\n\t}\n}\n\nvoid SocialGraph::repulsiveForce(){\n\tfor(int i=0; i<nodes.size(); i++){\n\t\trepF(i);\n\t}\n}\n\nvoid SocialGraph::attractiveForce(Graph temp_g){\n\tEdgeIterator e, e_end;\n\tfor(tie(e, e_end) = edges(temp_g); e != e_end; e++){\n\t\tint s = source(*e, temp_g);\n\t\tint t = target(*e, temp_g);\n\t\tfloat nx = nodes[s].x - nodes[t].x;\n\t\tfloat ny = nodes[s].y - nodes[t].y;\n\t\tfloat r = sqrt(pow(nx, 2) + pow(ny, 2));\n\t\tif(r > 0){\n\t\t\tfloat f = -(r * r) / 30;\n\t\t\tforces[s].x += f * nx / r;\n\t\t\tforces[s].y += f * ny / r;\n\t\t\tforces[t].x -= f * nx / r;\n\t\t\tforces[t].y -= f * ny / r;\n\n\t\t\t/*\n\t\t\tforces[s].x += f * nx / (r * out_degree(s,temp_g));\n\t\t\tforces[s].y += f * ny / (r * out_degree(s,temp_g));\n\t\t\tforces[t].x -= f * nx / (r * out_degree(t,temp_g));\n\t\t\tforces[t].y -= f * ny / (r * out_degree(t,temp_g));\n\t\t\t*/\n\t\t}\n\t}\n}\n\nfloat SocialGraph::limitForce(){\n\tfloat dt = .2;\n\tfloat damping = 0.01;\n\tfloat kinetic = 0.0;\n\n\tfor(int i=0; i<nodes.size(); i++){\n\t\tnodes[i].dx = (nodes[i].dx + dt * forces[i].x) * damping;\n\t\tnodes[i].dy = (nodes[i].dy + dt * forces[i].y) * damping;\n\t\t\n\t\tforces[i].x = 0;\n\t\tforces[i].y = 0;\n\n\t\tif(nodes[i].dx > 1) nodes[i].dx = 1;\n\t\tif(nodes[i].dx < -1) nodes[i].dx = -1;\n\t\tif(nodes[i].dy > 1) nodes[i].dy = 1;\n\t\tif(nodes[i].dy < -1) nodes[i].dy = -1;\n\n/*\n\t\tif(nodes[i].dx > 10) nodes[i].dx = 10;\n\t\tif(nodes[i].dx < -10) nodes[i].dx = -10;\n\t\tif(nodes[i].dy > 10) nodes[i].dy = 10;\n\t\tif(nodes[i].dy < -10) nodes[i].dy = -10;\n*/\n\n\t\tnodes[i].x = nodes[i].x + dt * nodes[i].dx;\n\t\tnodes[i].y = nodes[i].y + dt * nodes[i].dy;\n\n\t\tkinetic += sqrt(pow(nodes[i].dx, 2) + pow(nodes[i].dy, 2));\n\t}\n\n\treturn kinetic;\n}\n\nfloat SocialGraph::springModel(Graph temp_g){\n\tfloat kinetic = 0.0;\n\n\trepulsiveForce();\n\tattractiveForce(temp_g);\n\t\n\tkinetic = limitForce();\n\n\treturn kinetic;\n}\n\nvoid changeColor(float &r, float &g, float &b){\n\tif(r < 1.0){\n\t\tr += .5;\n\t}\n\telse{\n\t\tr = 0.0;\n\t\tif(g < 1.0){\n\t\t\tg += .5;\n\t\t}\n\t\telse{\n\t\t\tg = 0.0;\n\t\t\tif(b < .5){\n\t\t\t\tb += .5;\n\t\t\t}\n\t\t\telse\n\t\t\t\tb = 0.0;\n\t\t}\n\t}\n}\n\nvoid SocialGraph::clusterColor(Graph tempg){\n\tfloat r = 0.0;\n\tfloat g = 0.0;\n\tfloat b = 0.0;\n\n\twg = ::createWeightedGraph(tempg);\n\n\tfor(int i=0; i<num_vertices(wg); i++){\n\t\tfor(int j=i+1; j<num_vertices(wg); j++){\n\t\t\tif(edge(i,j,wg).second == 0 && edge(j,i,wg).second != 0)\n\t\t\t\tremove_edge(j,i,wg);\n\t\t\telse if(edge(i,j,wg).second != 0 && edge(j,i,wg).second == 0)\n\t\t\t\tremove_edge(i,j,wg);\n\t\t}\n\t}\n\n\tstd::vector<int> visited(num_vertices(wg), 0);\n\tint cluster = 0;\n\tfor(int i=0; i<num_vertices(wg); i++){\n\t\tif(visited[i] == 0){\n\t\t\tcluster++;\n\n\t\t\tstd::vector<WeightedVertexDescriptor> p(num_vertices(wg));\n\t\t\tstd::vector<int> d(num_vertices(wg));\n\t\t\tdijkstra_shortest_paths(wg, i, predecessor_map(&p[0]).distance_map(&d[0]));\n\n\t\t\tchangeColor(r,g,b);\n\t\t\t//std::cout << r << \" \" << g << \" \" << b << std::endl;\n\t\t\tfor(int j=0; j<num_vertices(wg); j++){\n\t\t\t\tif(d[j] != INT_MAX){\n\t\t\t\t\tvisited[j] = 1;\n\t\t\t\t\tnodes[j].r = r;\n\t\t\t\t\tnodes[j].g = g;\n\t\t\t\t\tnodes[j].b = b;\n\t\t\t\t\tnodes[j].cluster = cluster;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tstd::cout << \"number of clusters: \" << cluster << std::endl;\n}\n\nbool ContainsNode(std::vector<int> visited, int node){\n\tfor(int i=0; i<visited.size(); i++){\n\t\tif(visited[i] == node)\n\t\t\treturn true;\n\t}\n\treturn false;\n}\n\nvoid SocialGraph::DepthFirst(std::vector<int> &visited, int max, std::vector<int> &hits, int &max_short, int t){\n\tint back = visited.back();\n\tgraph_traits<WeightedGraph>::out_edge_iterator e, e_end;\n\n\tfor(tie(e, e_end) = out_edges(back, wg); e != e_end; e++){\n\t\tint node = target(*e, wg);\n\t\t\n\t\tif(ContainsNode(visited, node)) continue;\n\n\t\tif(node == t){\n\t\t\tvisited.push_back(node);\n\t\t\tfor(int i=1; i<visited.size()-1; i++){\n\t\t\t\thits[visited[i]]++;\n\t\t\t}\n\t\t\tmax_short++;\n\t\t\t\n\t\t\tint n = (int) visited.size() -1;\n\t\t\tvisited.erase(visited.begin() + n);\n\n\t\t\tbreak;\n\t\t}\n\n\t\tvisited.push_back(node);\n\n\t\tif(visited.size() <= max)\n\t\t\tDepthFirst(visited, max, hits, max_short, t);\n\n\t\tint n = (int)visited.size() - 1;\n\t\tvisited.erase(visited.begin() + n);\n\t}\n}\n\nvoid SocialGraph::ShortestPaths(int s, std::vector<double> &centrality){\n\tstd::vector<WeightedVertexDescriptor> p(num_vertices(wg));\n\tstd::vector<int> d(num_vertices(wg));\n\tdijkstra_shortest_paths(wg, s, predecessor_map(&p[0]).distance_map(&d[0]));\n\n\tfor(int i=0; i<num_vertices(wg); i++){\n\t\t//std::cout << i << \" \" << d[i] << std::endl;\n\t\tif(d[i] > 1 && d[i] != INT_MAX){\n\t\t\tstd::vector<int> hits(num_vertices(wg), 0);\n\t\t\tint max_short = 0;\n\n\t\t\tstd::vector<int> visited;\n\t\t\tvisited.push_back(s);\n\t\t\tDepthFirst(visited, d[i], hits, max_short, i);\n\n\t\t\tfor(int j=0; j<num_vertices(wg); j++){\n\t\t\t\tif(max_short > 0)\n\t\t\t\t\tcentrality[j] += (double)hits[j]/(double)max_short;\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid SocialGraph::setMatrix(){\n\tMatrix matrix(num_vertices(g));\n\n\tfor(int i=0; i<num_vertices(g); i++){\n\t\tstd::vector<int> list(num_vertices(g));\n\t\tfor(int j=0; j<num_vertices(g); j++){\n\t\t\tif(edge(i, j, g).second == 1)\n\t\t\t\tlist[j] = 1;\n\t\t\telse\n\t\t\t\tlist[j] = 0;\n\t\t}\n\t\tmatrix[i] = list;\n\t}\n\n\tmatrixlist.push_back(matrix);\n}\n\nvoid SocialGraph::addMatrix(){\n\tMatrix matrix1 = matrixlist[0];\n\tMatrix matrix2 = matrixlist[matrixlist.size() -1];\n\tMatrix temp(num_vertices(g));\n\t\n\tfor(int i=0; i<num_vertices(g); i++){\n\t\tstd::vector<int> list(num_vertices(g), 0);\n\t\tfor(int j=0; j<num_vertices(g); j++){\n\t\t\tfor(int k=0; k<num_vertices(g); k++){\n\t\t\t\tlist[j] += matrix1[i][k] * matrix2[k][j];\n\t\t\t}\n\t\t}\n\t\ttemp[i] = list;\n\t}\n\n\tmatrixlist.push_back(temp);\n}\n\nvoid SocialGraph::printMatrix(){\n\tMatrix matrix = matrixlist[matrixlist.size() -1];\n\n\tfor(int i=0; i<num_vertices(g); i++){\n\t\tfor(int j=0; j<num_vertices(g); j++)\n\t\t\tstd::cout << matrix[i][j] << \" \";\n\t\tstd::cout << std::endl;\n\t}\n}\n\nstd::vector<double> SocialGraph::Dependency(int s){\n\tstd::vector<WeightedVertexDescriptor> p(num_vertices(wg));\n\tstd::vector<int> d(num_vertices(wg));\n\tdijkstra_shortest_paths(wg, s, predecessor_map(&p[0]).distance_map(&d[0]));\n\n\tstd::vector<double> centrality(num_vertices(g), 0.0);\n\n\tfor(int i=0; i<num_vertices(g); i++){\n\t\t//if(d[i] > 1 && d[i] != INT_MAX){\n\t\tif(d[i] > 1 && d[i] < 4){\n\t\t\twhile(d[i] > matrixlist.size())\n\t\t\t\taddMatrix();\n\n\t\t\t//number of shortest paths\n\t\t\tint num = matrixlist[d[i]-1][s][i];\n\n\t\t\tstd::vector<double> temp(num_vertices(g), 0.0);\n\t\t\tfor(int j=1; j<d[i]; j++){\n\t\t\t\tfor(int k=0; k<num_vertices(g); k++)\n\t\t\t\t\ttemp[k] += matrixlist[j-1][s][k] * matrixlist[d[i]-1-j][k][i];\n\t\t\t}\n\t\t\tfor(int k=0; k<num_vertices(g); k++)\n\t\t\t\tcentrality[k] += (double)temp[k] / (double)num;\n\t\t}\n\t}\n\n\treturn centrality;\n}\n\nMatrixScore SocialGraph::AllDependency(){\n\tMatrixScore all_centrality;\n\t\n\tfor(int i=0; i<num_vertices(g); i++){\n\t\tstd::vector<double> centrality = Dependency(i);\n\t\tall_centrality.push_back(centrality);\n\t}\n\n\tfor(int i=0; i<num_vertices(g); i++){\n\t\tfor(int j=0; j<num_vertices(g); j++){\n\t\t\tif(edge(i, j, g).second == 1)\n\t\t\t\tall_centrality[i][j] = 0;\n\t\t}\n\t}\n\n\treturn all_centrality;\n}\n\nint SocialGraph::convertNode(int s){\n\tstd::string source = map.left.find(s)->second;\n\tint t = map2.right.find(source)->second;\n\treturn t;\n}\n\nMatrix SocialGraph::getDistance(){\n\treturn distance;\n}\n\nvoid SocialGraph::setAvgDegree(){\n\tfloat avg=0.0;\n\n\tfor(int i=0; i<num_vertices(g); i++){\n\t\tavg += out_degree(i, g);\n\t}\n\tavg = avg / num_vertices(g);\n\n\tavgDegree = avg;\n}\n\nfloat SocialGraph::getAvgDegree(){\n\treturn avgDegree;\n}\n\nEdges SocialGraph::newEdgesList(){\n\tEdges edges;\n\tfor(int i=0; i<num_vertices(g); i++){\n\t\tfor(int j=i+1; j<num_vertices(g); j++){\n\t\t\tif(edge(i, j, g).second == 0){\n\t\t\t\tstd::string source = map.left.find(i)->second;\n\t\t\t\tstd::string target = map.left.find(j)->second;\n\t\t\t\tint s = map2.right.find(source)->second;\n\t\t\t\tint t = map2.right.find(target)->second;\n\t\t\t\tif(s > 0 && t > 0 && s < num_vertices(g2) + 1 && t < num_vertices(g2)){\n\t\t\t\t\tif(edge(s, t, g2).second == 1){\n\t\t\t\t\t\tEdge e(i, j);\n\t\t\t\t\t\tedges.push_back(e);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn edges;\n}\n\nvoid SocialGraph::setNewEdges(){\n\tEdges edges = newEdgesList();\n\t\n\tfor(int i=0; i<edges.size(); i++){\n\t\tint s = edges[i].first;\n\t\tint t = edges[i].second;\n\n\t\tEdge e; e.first = s; e.second = t;\n\t\tif(distance[s][t] < num_vertices(g) && distance[s][t] > 0){\n\t\t\twhile(newEdges.size() <= distance[s][t]){\n\t\t\t\tEdges es;\n\t\t\t\tnewEdges.push_back(es);\n\t\t\t}\n\t\t\tnewEdges[distance[s][t]].push_back(e);\n\t\t}\n\t\telse\n\t\t\tnewEdges[0].push_back(e);\n\t}\n\n\tint count = 0;\n\tfloat allavg=0.0;\n\tfor(int i=0; i<newEdges.size(); i++){\n\t\tcount += newEdges[i].size();\n\t\tfor(int j=0; j<newEdges[i].size(); j++){\n\t\t\tint s = newEdges[i][j].first;\n\t\t\tint t = newEdges[i][j].second;\n\t\t\tallavg += out_degree(s, g) + out_degree(t, g);\n\t\t}\n\t}\n\tstd::cout << \"new edges(all_new) = \" << count << std::endl;\n\tnumNewEdges = count;\n\tallavg = allavg/(count*2);\n\tstd::cout << \"avg degree(all_new) = \" << allavg << std::endl;\n\tstd::cout << std::endl;\n\n\tfor(int i=0; i<newEdges.size(); i++){\n\t\tstd::cout << \"new edges (\" << i << \") = \" << newEdges[i].size() << std::endl;\n\t\tfloat avgnew = 0.0;\n\t\tfor(int j=0; j<newEdges[i].size(); j++){\n\t\t\tint s = newEdges[i][j].first;\n\t\t\tint t = newEdges[i][j].second;\n\t\t\tavgnew += out_degree(s, g) + out_degree(t, g);\n\t\t}\n\t\tavgnew = avgnew/(newEdges[i].size()*2);\n\t\tstd::cout << \"avg degree (\" << i << \") = \" << avgnew << std::endl;\n\t}\n\tstd::cout << std::endl;\n\n\n\tcount = 0;\n\tint count2 = 0;\n\tfloat avg=0.0;\n\tfloat avg2=0.0;\n\tfor(int i=0; i<newEdges[3].size(); i++){\n\t\tint flag = 0;\n\t\tint s = newEdges[3][i].first;\n\t\tint t = newEdges[3][i].second;\n\t\tfor(int j=0; j<newEdges[2].size(); j++){\n\t\t\tint s2 = newEdges[2][j].first;\n\t\t\tint t2 = newEdges[2][j].second;\n\t\t\tif(s2 == s){\n\t\t\t\tif(distance[t2][t] == 1){\n\t\t\t\t\tflag = 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(t2 == s){\n\t\t\t\tif(distance[s2][t] == 1){\n\t\t\t\t\tflag = 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(s2 == t){\n\t\t\t\tif(distance[t2][s] == 1){\n\t\t\t\t\tflag = 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(t2 == t){\n\t\t\t\tif(distance[s2][s] == 1){\n\t\t\t\t\tflag = 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(flag == 1){\n\t\t\t\tcount++;\n\t\t\t\tavg += out_degree(s,g) + out_degree(t, g);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif(flag == 0){\n\t\t\tcount2++;\n\t\t\tavg2 += out_degree(s, g) + out_degree(t, g);\n\t\t}\n\t}\n\tstd::cout << \"new edges(3)<-(2) = \" << count << std::endl;\n\tavg = avg / (count * 2);\n\tstd::cout << \"avg degree of (3)<-(2) = \" << avg << std::endl;\n\n\tstd::cout << \"new edges(3)!(2) = \" << count2 << std::endl;\n\tavg2 = avg2 / (count2 * 2);\n\tstd::cout << \"avg degree of (3)!(2) = \" << avg2 << std::endl;\n}\n\nstd::vector<Edges> SocialGraph::getNewEdges(){\n\treturn newEdges;\n}\n\n\n//new functions\nvoid SocialGraph::initialize(int argc, char *argv[]){\n\tstd::ifstream fin;\n\tfin.open(argv[1]);\n\tfacebook::Data data = facebook::readFile(fin, name);\n\tmap = facebook::createMap(data);\n\tg = facebook::createGraph(data, map);\n\tfor(int i=0; i<num_vertices(g); i++){\n\t\tput(vertex_name, g, i, name[i]);\n\t}\n\tforces.resize(num_vertices(g));\n\tfin.close();\n\n\tdistance = ::createAllPairsShortestPaths(::createWeightedGraph(g));\n\tsetAvgDegree();\n\n\n\t//initialize graph for t+1\n\tfin.open(argv[2]);\n\tGraph temp_g = ::createGraph(fin);\n\tg2 = g;\n\tfin.close();\n\n\tnew_edges = ::newEdgeList(g, temp_g);\n\tnew_matrix = ::newList2Matrix(g, new_edges);\n\tcountd2=0;\n\tfor(int i=0; i<new_edges.size(); i++){\n\t\tif(distance[new_edges[i].first][new_edges[i].second] < num_vertices(g)){\n\t\t\tif(distance[new_edges[i].first][new_edges[i].second] == 2){\n\t\t\t\tcountd2++;\n\t\t\t}\n\t\t\tadd_edge(new_edges[i].first, new_edges[i].second, g2);\n\t\t\tadd_edge(new_edges[i].second, new_edges[i].first, g2);\n\t\t}\n\t}\n\n\tdistance2 = ::createAllPairsShortestPaths(::createWeightedGraph(g2));\n\n\tsetNodes();\n\tsetAvgDegree();\n\n\tstd::cout << \"number of vertices: \" << num_vertices(g) << std::endl;\n\tstd::cout << \"number of edges: \" << num_edges(g)/2 << std::endl;\n\tstd::cout << \"number of new edges: \" << new_edges.size() << std::endl;\n\tstd::cout << \"number of new edges at disance 2: \" << countd2 << std::endl;\n\n\t#pragma omp parallel for\n\tfor(int i=0; i<2; i++){\n\t\tif(i == 0)\n\t\t\tcg = ::ClusterEdgeCentrality(g, num_vertices(g));\n\t\tif(i == 1)\n\t\t\tcg2 = ::ClusterEdgeCentrality(g2, num_vertices(g2));\n\t}\n\n\tsg = g;\n}\n\nvoid SocialGraph::test(){\n\tScores q;\n\n\tprobabilityAA = ::AdamicAdar(g);\n\tq = ::SortScores(probabilityAA);\n\n\t//use this to count how many were the same as\n\t//betweenness centrality based method\n\tEdges daa;\n\tEdges dbc;\n\t\n\tint a=0;\n\tfor(int i=0; i<new_edges.size(); i++){\n\t//for(int i=0; i<countd2; i++){\n\t\tint s = q[i].second.first;\n\t\tint t = q[i].second.second;\n\t\tif(edge(s, t, g2).second == 1){\n\t\t\ta++;\n\t\t\tdaa.push_back(Edge(s,t));\n\t\t}\n\t}\n\tstd::cout << \"adamic-adar:\" << a << std::endl;\n\n\tstd::cout << \"new edges of distance > 2: \" << a << std::endl;\n\tstd::cout << \"average node degree: \" << avgDegree << std::endl;\n\n\tstd::vector<double> vbc(num_vertices(g), 0.0);\n\tstd::vector<double> ebc(num_edges(g), 0.0);\n\t::VertexBetweennessCentrality(g, vbc, ebc);\n\n\n\tfloat beta = 0;\n\tprobability = ::BCBasedLP(g, distance, vbc, beta);\n\tScores sbc = ::SortScores(probability);\n\ta=0;\n\tint b=0;\n\tfor(int i=0; i<new_edges.size(); i++){\n\t//for(int i=0; i<countd2; i++){\n\t\tint s = sbc[i].second.first;\n\t\tint t = sbc[i].second.second;\n\t\tif(edge(s, t, g2).second == 1 && (probability[s][t] > 0 || probability[t][s] > 0)){\n\t\t\tdetected_edges.push_back(Edge(s,t));\n\t\t\ta++;\n\t\t\tdbc.push_back(Edge(s,t));\n\t\t\tif(distance[s][t] > 2)\n\t\t\t\tb++;\n\t\t}\n\t}\n\tstd::cout << a << \":\" << b << std::endl;\n\n\t//check how many were the same\n\tint overlap=0;\n\tfor(int i=0; i<dbc.size(); i++){\n\t\tint s = dbc[i].first;\n\t\tint t = dbc[i].second;\n\t\tfor(int j=0; j<daa.size(); j++){\n\t\t\tint s1 = daa[j].first;\n\t\t\tint t1 = daa[j].second;\n\t\t\tif((s1 == s && t1 == t) || (s1 == t && t1 == s))\n\t\t\t\toverlap++;\n\t\t}\n\t}\n\tstd::cout << \"overlap: \" << overlap << \"/\" << dbc.size() << \" = \" << (float)overlap/dbc.size() << std::endl;\n\n\tvertex_bc = vbc;\n\n\t//calculate number of paths at what distance\n\tstd::vector<int> count;\n\tfor(int x=0; x<num_vertices(g); x++){\n\t\tfor(int y=x+1; y<num_vertices(g); y++){\n\t\t\tif(distance[x][y] < num_vertices(g)){\n\t\t\t\twhile(count.size() <= distance[x][y]){\n\t\t\t\t\tcount.push_back(0);\n\t\t\t\t}\n\t\t\t\tcount[distance[x][y]]++;\n\t\t\t}\n\t\t}\n\t}\n\tfor(int i=0; i<count.size(); i++){\n\t\tstd::cout << i << \":\" << count[i] << std::endl;\n\t}\n\n\t::NormalizePr(probability, distance);\n\t::NormalizePr(probabilityAA, distance);\n\n\tedge_bc = ::EdgeCentrality(g, ebc);\n\n\t//finds probability of correct new edges detected\n\t//based on how many new edges detected of one individual\n\tstd::vector<int> nEdges(num_vertices(g),0);\n\tfor(int i=0; i<new_edges.size(); i++){\n\t\tint s = new_edges[i].first;\n\t\tint t = new_edges[i].second;\n\t\tif(distance[s][t] == 2){\n\t\t\tnEdges[s]++;\n\t\t\tnEdges[t]++;\n\t\t}\n\t}\n\tint necount=0; int necorrect=0;\n\tfor(int i=0; i<num_vertices(g); i++){\n\t\tnecount += nEdges[i];\n\t\tif(nEdges[i] > 0){\n\t\t\tScores nscores = SortIndividualScores(probability, i);\n\n\t\t\tfor(int j=0; j<nEdges[i]; j++){\n\t\t\t\tint s = nscores[j].second.first;\n\t\t\t\tint t = nscores[j].second.second;\n\t\t\t\tif(edge(s,t,g2).second == 1)\n\t\t\t\t\tnecorrect++;\n\t\t\t}\n\t\t}\n\t}\n\tstd::cout << necorrect << \"/\" << necount << std::endl;\n\n\n\t//change size of vertex and edge betweenness centrality\n\t//for visualization\n\tvbc = sortDouble(vertex_bc);\n\tdouble minbc = vbc[0.05*vbc.size()];\n\tdouble maxbc = vbc[0.95*vbc.size()];\n\tdouble diff = maxbc - minbc;\n\tfor(int i=0; i<num_vertices(g); i++){\n\t\tif(vertex_bc[i] < minbc)\n\t\t\tvertex_bc[i] = 10;\n\t\telse if(vertex_bc[i] > maxbc)\n\t\t\tvertex_bc[i] = 25;\n\t\telse\n\t\t\tvertex_bc[i] = 10 + 15 * (vertex_bc[i] - minbc)/diff;\n\t}\n\n\tebc = sortDouble(ebc);\n\tminbc = ebc[0];\n\tmaxbc = ebc[ebc.size()*.5];\n\tdiff = maxbc - minbc;\n\n\tfor(int i=0; i<num_vertices(g); i++){\n\t\tfor(int j=i+1; j<num_vertices(g); j++){\n\t\t\tif(edge(i,j,g).second == 1){\n\t\t\tif(edge_bc[i][j] < minbc){\n\t\t\t\tedge_bc[i][j] = 5;\n\t\t\t\tedge_bc[j][i] = 5;\n\t\t\t}\n\t\t\telse if(edge_bc[i][j] > maxbc){\n\t\t\t\tedge_bc[i][j] = 1;\n\t\t\t\tedge_bc[j][i] = 1;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tedge_bc[i][j] = 5.0 - 4.0 * (edge_bc[i][j] - minbc)/diff;\n\t\t\t\tedge_bc[j][i] = edge_bc[i][j];\n\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t//copy of above for future graph\n\tstd::vector<double> vbc2(num_vertices(g2), 0.0);\n\tstd::vector<double> ebc2(num_edges(g2), 0.0);\n\t::VertexBetweennessCentrality(g2, vbc2, ebc2);\n\tvertex_bc2 = vbc2;\n\tedge_bc2 = ::EdgeCentrality(g2, ebc2);\n\n\tvbc2 = sortDouble(vertex_bc2);\n\tminbc = vbc2[0.05*vbc2.size()];\n\tmaxbc = vbc2[0.95*vbc2.size()];\n\tdiff = maxbc - minbc;\n\tfor(int i=0; i<num_vertices(g); i++){\n\t\tif(vertex_bc2[i] < minbc)\n\t\t\tvertex_bc2[i] = 10;\n\t\telse if(vertex_bc2[i] > maxbc)\n\t\t\tvertex_bc2[i] = 25;\n\t\telse\n\t\t\tvertex_bc2[i] = 10 + 15 * (vertex_bc2[i] - minbc)/diff;\n\t}\n\n\tebc2 = sortDouble(ebc2);\n\tminbc = ebc2[0];\n\tmaxbc = ebc2[ebc2.size()*.5];\n\tdiff = maxbc - minbc;\n\n\tfor(int i=0; i<num_vertices(g); i++){\n\t\tfor(int j=i+1; j<num_vertices(g); j++){\n\t\t\tif(edge(i,j,g2).second == 1){\n\t\t\tif(edge_bc2[i][j] < minbc){\n\t\t\t\tedge_bc2[i][j] = 5;\n\t\t\t\tedge_bc2[j][i] = 5;\n\t\t\t}\n\t\t\telse if(edge_bc2[i][j] > maxbc){\n\t\t\t\tedge_bc2[i][j] = 1;\n\t\t\t\tedge_bc2[j][i] = 1;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tedge_bc2[i][j] = 5.0 - 4.0 * (edge_bc2[i][j] - minbc)/diff;\n\t\t\t\tedge_bc2[j][i] = edge_bc2[i][j];\n\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n}\n\nvoid SocialGraph::showDetected(){\n\tstatic int k=0;\n\n\tfor(int i=0; i<num_vertices(g); i++){\n\t\tnodes[i].r = 0; nodes[i].g = 0; nodes[i].b = 0;\n\t}\n\tvizN.clear();\n\n\tk++;\n\tif(k == detected_edges.size())\n\t\tk = 0;\n\t\n\tint s = detected_edges[k].first;\n\tint t = detected_edges[k].second;\n\tnodes[s].b = 1.0; nodes[t].b = 1.0;\n\n\tvizN.push_back(s); vizN.push_back(t);\n\n\tfor(int i=0; i<num_vertices(g); i++){\n\t\tif(distance[s][i] + distance[i][t] == distance[s][t]\n\t\t&& s != i && t != i){\n\t\t\tnodes[i].g = 1.0;\n\t\t\tvizN.push_back(i);\n\t\t}\n\t}\n\n\tstd::cout << \"changed \" << k << \", normalized bc score = \" << probability[s][t] << std::endl;\n}\n\nGraph SocialGraph::getSG(){\n\treturn sg;\n}\n\nGraph SocialGraph::getSG2(){\n\treturn sg2;\n}\n\nvoid SocialGraph::selectSG(int s){\n\tif(s != -1){\n\n\tGraph tempg(num_vertices(g));\n\n\tstd::vector<int> nhbr;\n\tnhbr.push_back(s);\n\tfor(int t=0; t<num_vertices(g); t++){\n\t\tif(distance[s][t] == 2 || distance[s][t] == 1){\n\t\t\tnhbr.push_back(t);\n\n\t\t\t//make nodes closer to selected node\n\t\t\t//for visualization\n\t\t\t/*\n\t\t\tnodes[t].x = nodes[s].x + (20.0*rand()/RAND_MAX - 10.0);\n\t\t\tnodes[t].y = nodes[s].y + (20.0*rand()/RAND_MAX - 10.0);\n\t\t\t*/\n\t\t}\n\t}\n\t\n\tfor(int x=0; x<nhbr.size()-1; x++){\n\t\tfor(int y=x+1; y<nhbr.size(); y++){\n\t\t\tint i = nhbr[x];\n\t\t\tint j = nhbr[y];\n\t\t\tif(edge(i,j,g).second == 1 && edge(i,j,tempg).second != 1){\n\t\t\t\tadd_edge(i,j,tempg);\n\t\t\t\tadd_edge(j,i,tempg);\n\t\t\t}\n\t\t}\n\t}\n\n\tsg = tempg;\n\n\t/*\n\tfor(int i=0; i<num_vertices(g); i++){\n\t\tif(i == s){\n\t\t\tnodes[i].r = 1; nodes[i].g = 0; nodes[i].b = 0;\n\t\t}\n\t\telse{\n\t\t\tnodes[i].r = 0; nodes[i].g = 0; nodes[i].b = 0;\n\t\t}\n\t}\n\t*/\n\n\t}\n}\n\nvoid SocialGraph::selectFutureSG(int s){\n\tsg2 = sg;\n\tsgEdges.clear();\n\n\tint count=0;\n\tfor(int i=0; i<num_vertices(g); i++){\n\t\tif(distance[s][i] == 2 && edge(s,i,g2).second == 1){\n\t\t\tadd_edge(s,i,sg2);\n\t\t\tadd_edge(i,s,sg2);\n\t\t\tcount++;\n\t\t\tsgEdges.push_back(Edge(s,i));\n\t\t}\n\t}\n\tstd::cout << count << \" new edges\" << std::endl;\n}\n\nfloat SocialGraph::SpringSG(int s, char flag){\n\tfloat kinetic = 0.0;\n\n\tif(s !=  -1){\n\n\trepulsiveForce();\n\tif(flag == 0)\n\t\tattractiveForce(sg);\n\telse if(flag == 1 || flag == 2){\n\t\tattractiveForce(sg);\n\t\tfor(int i=0; i<num_vertices(g); i++){\n\t\t\tif(distance[s][i] == 2){\n\t\t\t\tfloat nx = nodes[s].x - nodes[i].x;\n\t\t\t\tfloat ny = nodes[s].y - nodes[i].y;\n\t\t\t\tfloat r = sqrt(pow(nx,2) + pow(ny,2));\n\t\t\t\tnx = nx / r;\n\t\t\t\tny = ny / r;\n\t\t\t\tif(r>0 &&\n\t\t\t\t((flag==1)?(probability[s][i]):(probabilityAA[s][i])) >= 1){\n\t\t\t\t//if(r > 0 && (probability[s][i] >= 1)){\n\t\t\t\t\tfloat f = -2 * (r*r)/30;\n\t\t\t\t\tforces[s].x += f * nx;\n\t\t\t\t\tforces[s].y += f * ny;\n\t\t\t\t\tforces[i].x -= f * nx;\n\t\t\t\t\tforces[i].y -= f * ny;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\telse if(flag == 3)\n\t\tattractiveForce(sg2);\n\n\t\n\tfloat dt = 1.0;\n\tfloat damping = 0.01;\n\n\tfor(int i=0; i<nodes.size(); i++){\n\t\tnodes[i].dx = (nodes[i].dx + dt * forces[i].x) * damping;\n\t\tnodes[i].dy = (nodes[i].dy + dt * forces[i].y) * damping;\n\t\t\n\t\tforces[i].x = 0;\n\t\tforces[i].y = 0;\n\n\t\tif(nodes[i].dx > 1) nodes[i].dx = 1;\n\t\tif(nodes[i].dx < -1) nodes[i].dx = -1;\n\t\tif(nodes[i].dy > 1) nodes[i].dy = 1;\n\t\tif(nodes[i].dy < -1) nodes[i].dy = -1;\n\n\n\t\tif(i != s){\n\t\t\tnodes[i].x = nodes[i].x + dt * nodes[i].dx;\n\t\t\tnodes[i].y = nodes[i].y + dt * nodes[i].dy;\n\t\t}\n\n\t\tkinetic += sqrt(pow(nodes[i].dx, 2) + pow(nodes[i].dy, 2));\n\t}\n\n\t}\n\n\n\treturn kinetic;\n\n}\n\nEdges SocialGraph::getSGEdges(){\n\treturn sgEdges;\n}\n\nstd::vector<double> SocialGraph::getVBC(){\n\treturn vertex_bc;\n}\n\nstd::vector<double> SocialGraph::getVBC2(){\n\treturn vertex_bc2;\n}\n\nMatrixScore SocialGraph::getEBC(){\n\treturn edge_bc;\n}\n\nMatrixScore SocialGraph::getEBC2(){\n\treturn edge_bc2;\n}\n\nMatrixScore SocialGraph::getProbability(){\n\treturn probability;\n}\n\nMatrixScore SocialGraph::getProbabilityAA(){\n\treturn probabilityAA;\n}\n", "meta": {"hexsha": "60529c78edf1ba9b143722c12a8daac203da93fc", "size": 22926, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/socialgraph.cpp", "max_stars_repo_name": "yishihara/Social-Network", "max_stars_repo_head_hexsha": "505c08f544a03bbd32ea1c48a437f5de63c51523", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/socialgraph.cpp", "max_issues_repo_name": "yishihara/Social-Network", "max_issues_repo_head_hexsha": "505c08f544a03bbd32ea1c48a437f5de63c51523", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/socialgraph.cpp", "max_forks_repo_name": "yishihara/Social-Network", "max_forks_repo_head_hexsha": "505c08f544a03bbd32ea1c48a437f5de63c51523", "max_forks_repo_licenses": ["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.7892644135, "max_line_length": 112, "alphanum_fraction": 0.5861903516, "num_tokens": 7907, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382236515259, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.49753433108917355}}
{"text": "/*\n * lstmlayer.cpp\n *\n * Feed-forward:\n *    x(t) -- inputs\n *    h(t-1) -- hidden state, aka outputs on prev timestep\n *    c(t) -- cell state\n *\n *    Phase 1: I/O gates\n *      zz_a(t) = ww_xa*x(t) + ww_ha * h(t-1) + bb_a  -- input\n *      zz_i(t) = ww_xi*x(t) + ww_hi * h(t-1) + bb_i  -- input gate\n *      zz_f(t) = ww_xf*x(t) + ww_hf * h(t-1) + bb_g  -- forget gate\n *      zz_o(t) = ww_xo*x(t) + ww_ho * h(t-1) + bb_o  -- output gate\n *\n *      a(t) = activ1 (zz_a(t))\n *      i(t) = activ2 (zz_i(t))\n *      f(t) = activ2 (zz_f(t))\n *      o(t) = activ2 (zz_o(t))\n *\n *    Phase 2: State\n *      c(t) = elem_prod(i(t), a(t)) + elem_prod(f(t), c(t-1))\n *\n *    Phase 3: Output\n *      h(t) = elem_prod(o(t), activ1(c(t))\n *\n * Back propagation:\n *\n */\n#include <boost/assert.hpp>\n\n#include \"core/utils.h\"\n#include \"core/random.h\"\n#include \"core/functions.h\"\n#include \"lstmlayer.h\"\n\nusing namespace std;\nusing namespace boost;\nusing namespace yann;\n\n\nnamespace yann {\n\n// prefixes for read/write\nstatic const char g_ltsm_names_suffix[LstmLayer::Gate_Max + 1] = \"aifo\";\n\n////////////////////////////////////////////////////////////////////////////////////////////////\n//\n// LstmLayer_Context implementation\n//\nclass LstmLayer_Context :\n    public Layer::Context\n{\n  typedef Layer::Context Base;\n\n  friend class LstmLayer;\n\npublic:\n  LstmLayer_Context(\n      const MatrixSize & output_size,\n      const MatrixSize & max_batch_size) :\n    Base(output_size, max_batch_size),\n    _pos(0)\n  {\n    init();\n  }\n\n  LstmLayer_Context(\n      const RefVectorBatch & output) :\n    Base(output),\n    _pos(0)\n  {\n    init();\n  }\n\n  // Layer::Context overwrites\n  virtual void reset_state()\n  {\n    Base::reset_state();\n\n    _pos = 0;\n  }\n\nprivate:\n  void init()\n  {\n    for(auto & zz_gate: _zz_gate) {\n      zz_gate.resize(get_batch_size(), get_output_size());\n    }\n    for(auto & gate: _gate) {\n      gate.resize(get_batch_size(), get_output_size());\n    }\n\n    _cc.resize(get_batch_size(), get_output_size());\n    _activ_cc.resize(get_batch_size(), get_output_size());\n\n    _hh.resize(get_batch_size(), get_output_size());\n  }\n\nprotected:\n  MatrixSize  _pos;\n  VectorBatch _zz_gate[LstmLayer::Gate_Max]; // pre-activation function results for each gate\n  VectorBatch _gate[LstmLayer::Gate_Max];    // post-activation function results for each gate\n  VectorBatch _cc;                      // cell state (save it for each step)\n  VectorBatch _activ_cc;                // activ1(c(t))\n  VectorBatch _hh;                      // hidden state aka output (save it for each step)\n}; // class LstmLayer_Context\n\n////////////////////////////////////////////////////////////////////////////////////////////////\n//\n// LstmLayer_TrainingContext implementation\n//\nclass LstmLayer_TrainingContext :\n    public LstmLayer_Context\n{\n  typedef LstmLayer_Context Base;\n  friend class LstmLayer;\n\npublic:\n  LstmLayer_TrainingContext(\n      const MatrixSize & input_size,\n      const MatrixSize & output_size,\n      const MatrixSize & batch_size,\n      const unique_ptr<Layer::Updater> & updater) :\n    Base(output_size, batch_size)\n  {\n    init(updater, input_size);\n  }\n\n  LstmLayer_TrainingContext(\n      const MatrixSize & input_size,\n      const RefVectorBatch & output,\n      const unique_ptr<Layer::Updater> & updater) :\n    Base(output)\n  {\n    init(updater, input_size);\n  }\n\n  // Layer::Context overwrites\n  virtual void start_epoch()\n  {\n    Base::start_epoch();\n\n    for(auto & ww_x_updater: _ww_x_updater) {\n      YANN_SLOW_CHECK(ww_x_updater);\n      ww_x_updater->start_epoch();\n    }\n    for(auto & ww_h_updater: _ww_h_updater) {\n      YANN_SLOW_CHECK(ww_h_updater);\n      ww_h_updater->start_epoch();\n    }\n    for(auto & bb_updater: _bb_updater) {\n      YANN_SLOW_CHECK(bb_updater);\n      bb_updater->start_epoch();\n    }\n  }\n\n  virtual void reset_state()\n  {\n    Base::reset_state();\n\n    for(auto & delta_ww_x: _delta_ww_x) {\n      delta_ww_x.setZero();\n    }\n    for(auto & delta_ww_h: _delta_ww_h) {\n      delta_ww_h.setZero();\n    }\n    for(auto & delta_bb: _delta_bb) {\n      delta_bb.setZero();\n    }\n\n    for(auto & ww_x_updater: _ww_x_updater) {\n      YANN_SLOW_CHECK(ww_x_updater);\n      ww_x_updater->reset();\n    }\n    for(auto & ww_h_updater: _ww_h_updater) {\n      YANN_SLOW_CHECK(ww_h_updater);\n      ww_h_updater->reset();\n    }\n    for(auto & bb_updater: _bb_updater) {\n      YANN_SLOW_CHECK(bb_updater);\n      bb_updater->reset();\n    }\n\n    _gradient_hh.setZero();\n    _gradient_cc.setZero();\n  }\n\nprivate:\n  void init(\n      const unique_ptr<Layer::Updater> & updater,\n      const MatrixSize & input_size)\n  {\n    YANN_CHECK_GT(updater, 0);\n    YANN_CHECK_GT(input_size, 0);\n\n    // deltas\n    for(auto & delta_ww_x: _delta_ww_x) {\n      delta_ww_x.resize(input_size, get_output_size());\n    }\n    for(auto & delta_ww_h: _delta_ww_h) {\n      delta_ww_h.resize(get_output_size(), get_output_size());\n    }\n    for(auto & delta_bb: _delta_bb) {\n      delta_bb.resize(get_output_size());\n    }\n\n    // updaters\n    for(auto & ww_x_updater: _ww_x_updater) {\n      ww_x_updater = updater->copy();\n      YANN_SLOW_CHECK(ww_x_updater);\n      ww_x_updater->init(input_size, get_output_size());\n    }\n    for(auto & ww_h_updater: _ww_h_updater) {\n      ww_h_updater = updater->copy();\n      YANN_SLOW_CHECK(ww_h_updater);\n      ww_h_updater->init(get_output_size(), get_output_size());\n    }\n    for(auto & bb_updater: _bb_updater) {\n      bb_updater = updater->copy();\n      YANN_SLOW_CHECK(bb_updater);\n      bb_updater->init(1, get_output_size()); // RowMajor\n    }\n\n    // gate radients\n    _gradient_hh.resize(get_output_size());\n    _gradient_cc.resize(get_output_size());\n    _gradient_gate.resize(get_output_size());\n    _gradient_zz_gate.resize(get_output_size());\n    _tmp_derivative.resize(get_output_size());\n  }\n\nprivate:\n  Matrix _delta_ww_x[LstmLayer::Gate_Max];\n  Matrix _delta_ww_h[LstmLayer::Gate_Max];\n  Vector _delta_bb[LstmLayer::Gate_Max];\n\n  unique_ptr<Layer::Updater> _ww_x_updater[LstmLayer::Gate_Max];\n  unique_ptr<Layer::Updater> _ww_h_updater[LstmLayer::Gate_Max];\n  unique_ptr<Layer::Updater> _bb_updater[LstmLayer::Gate_Max];\n\n  Vector _gradient_hh;\n  Vector _gradient_cc;\n  Vector _gradient_gate;\n  Vector _gradient_zz_gate;\n  Vector _tmp_derivative;\n}; // class LstmLayer_TrainingContext\n\n}; // namespace yann\n\n////////////////////////////////////////////////////////////////////////////////////////////////\n//\n// yann::LstmLayer implementation\n//\nyann::LstmLayer::LstmLayer(\n    const MatrixSize & input_size,\n    const MatrixSize & output_size) :\n    _gate_activation_function(new SigmoidFunction()),\n    _io_activation_function(new TanhFunction())\n{\n  YANN_CHECK_GT(input_size, 0);\n\n  for(auto & ww_x: _ww_x) {\n    ww_x.resize(input_size, output_size);\n  }\n  for(auto & ww_h: _ww_h) {\n    ww_h.resize(output_size, output_size);\n  }\n  for(auto & bb: _bb) {\n    bb.resize(output_size);\n  }\n}\n\nyann::LstmLayer::~LstmLayer()\n{\n}\n\nvoid yann::LstmLayer::set_values(\n    const Matrix (& ww_x)[Gate_Max],\n    const Matrix (& ww_h)[Gate_Max],\n    const Vector (& bb)[Gate_Max])\n{\n  for(auto ii = 0; ii < Gate_Max; ++ii) {\n    YANN_CHECK(is_same_size(ww_x[ii], _ww_x[ii]));\n    YANN_CHECK(is_same_size(ww_h[ii], _ww_h[ii]));\n    YANN_CHECK(is_same_size(bb[ii], _bb[ii]));\n\n    _ww_x[ii] = ww_x[ii];\n    _ww_h[ii] = ww_h[ii];\n    _bb[ii] = bb[ii];\n  }\n}\n\nvoid yann::LstmLayer::set_activation_functions(\n    const std::unique_ptr<ActivationFunction> & gate_activation_function,\n    const std::unique_ptr<ActivationFunction> & io_activation_function)\n{\n  YANN_CHECK(gate_activation_function);\n  YANN_CHECK(io_activation_function);\n  _gate_activation_function = gate_activation_function->copy();\n  _io_activation_function = io_activation_function->copy();\n}\n\n// Layer overwrites\nbool yann::LstmLayer::is_valid() const\n{\n  if(!Base::is_valid()) {\n    return false;\n  }\n  if(!_io_activation_function || !_gate_activation_function) {\n    return false;\n  }\n  for(auto ii = 0; ii < Gate_Max; ++ii) {\n    if(!is_same_size(_ww_x[0], _ww_x[ii])) {\n      return false;\n    }\n    if(!is_same_size(_ww_h[0], _ww_h[ii])) {\n      return false;\n    }\n    if(!is_same_size(_bb[0], _bb[ii])) {\n      return false;\n    }\n  }\n\n  return true;\n}\n\nstd::string yann::LstmLayer::get_name() const\n{\n  return \"LstmLayer\";\n}\n\nstring yann::LstmLayer::get_info() const\n{\n  YANN_CHECK(is_valid());\n\n  ostringstream oss;\n  oss << Base::get_info()\n      << \", state activation: \" << _io_activation_function->get_info()\n      << \", output activation: \" << _gate_activation_function->get_info()\n      ;\n  return oss.str();\n}\n\nbool yann::LstmLayer::is_equal(const Layer & other, double tolerance) const\n{\n  if(!Base::is_equal(other, tolerance)) {\n    return false;\n  }\n  auto the_other = dynamic_cast<const LstmLayer*>(&other);\n  if(the_other == nullptr) {\n    return false;\n  }\n  // TOOD: add deep compare\n  if(_io_activation_function->get_info() != the_other->_io_activation_function->get_info()) {\n    return false;\n  }\n  if(_gate_activation_function->get_info() != the_other->_gate_activation_function->get_info()) {\n    return false;\n  }\n  for(auto ii = 0; ii < Gate_Max; ++ii) {\n    if(!_ww_x[ii].isApprox(the_other->_ww_x[ii], tolerance)) {\n      return false;\n    }\n    if(!_ww_h[ii].isApprox(the_other->_ww_h[ii], tolerance)) {\n      return false;\n    }\n    if(!_bb[ii].isApprox(the_other->_bb[ii], tolerance)) {\n      return false;\n    }\n  }\n  return true;\n}\n\nMatrixSize yann::LstmLayer::get_input_size() const\n{\n  YANN_SLOW_CHECK(is_valid());\n  return _ww_x[Gate_A].rows();\n}\n\nMatrixSize yann::LstmLayer::get_output_size() const\n{\n  YANN_SLOW_CHECK(is_valid());\n  return _ww_x[Gate_A].cols();\n}\n\nunique_ptr<Layer::Context> yann::LstmLayer::create_context(const MatrixSize & batch_size) const\n{\n  YANN_CHECK(is_valid());\n  return make_unique<LstmLayer_Context>(get_output_size(), batch_size);\n}\nunique_ptr<Layer::Context> yann::LstmLayer::create_context(const RefVectorBatch & output) const\n{\n  YANN_CHECK(is_valid());\n  return make_unique<LstmLayer_Context>(output);\n}\nunique_ptr<Layer::Context> yann::LstmLayer::create_training_context(\n    const MatrixSize & batch_size, const std::unique_ptr<Layer::Updater> & updater) const\n{\n  YANN_CHECK(is_valid());\n  YANN_CHECK(updater);\n  return make_unique<LstmLayer_TrainingContext>(\n      get_input_size(), get_output_size(), batch_size, updater);\n}\nunique_ptr<Layer::Context> yann::LstmLayer::create_training_context(\n    const RefVectorBatch & output, const std::unique_ptr<Layer::Updater> & updater) const\n{\n  YANN_CHECK(is_valid());\n  YANN_CHECK(updater);\n  return make_unique<LstmLayer_TrainingContext>(\n      get_input_size(), output, updater);\n}\n\ntemplate<typename InputType>\nvoid yann::LstmLayer::feedforward_internal(\n    const InputType & input,\n    Context * context,\n    enum OperationMode mode) const\n{\n  auto ctx = dynamic_cast<LstmLayer_Context *>(context);\n  YANN_CHECK(ctx);\n  YANN_CHECK(is_valid());\n  YANN_CHECK_LE(get_batch_size(input) + ctx->_pos, ctx->get_batch_size());\n  YANN_CHECK_LE(get_batch_size(input), get_batch_size(ctx->get_output()));\n  YANN_CHECK_EQ(get_batch_item_size(input), get_input_size());\n\n  for(MatrixSize ii = 0; ii < get_batch_size(input); ++ii, ++ctx->_pos) {\n    // Phase 1: I/O gates\n    //  zz_a(t) = ww_xa*x(t) + ww_ha * h(t-1) + bb_a  -- input\n    //  zz_i(t) = ww_xi*x(t) + ww_hi * h(t-1) + bb_i  -- input gate\n    //  zz_f(t) = ww_xf*x(t) + ww_hf * h(t-1) + bb_g  -- forget gate\n    //  zz_o(t) = ww_xo*x(t) + ww_ho * h(t-1) + bb_o  -- output gate\n    auto in  = get_batch(input, ii);\n    auto out = get_batch(ctx->get_output(), ctx->_pos);\n    auto hh  = get_batch(ctx->_hh, ctx->_pos);\n    if(ctx->_pos > 0) {\n      const auto & hh_prev = get_batch(ctx->_hh, ctx->_pos - 1);\n      for(auto jj = 0; jj < Gate_Max; ++jj) {\n        auto zz_gate = get_batch(ctx->_zz_gate[jj], ctx->_pos);\n        zz_gate.noalias() = MatrixFunctions<InputType>::product(in, _ww_x[jj]);\n        zz_gate.noalias() += MatrixFunctions<RefConstMatrix>::product(hh_prev, _ww_h[jj]) + _bb[jj];\n      }\n    } else {\n      for(auto jj = 0; jj < Gate_Max; ++jj) {\n        auto zz_gate = get_batch(ctx->_zz_gate[jj], ctx->_pos);\n        zz_gate.noalias() = MatrixFunctions<InputType>::product(in, _ww_x[jj]);\n        zz_gate.noalias() += _bb[jj];\n      }\n    }\n\n    //  a(t) = activ1 (zz_a(t))\n    //  i(t) = activ2 (zz_i(t))\n    //  f(t) = activ2 (zz_f(t))\n    //  o(t) = activ2 (zz_o(t))\n    for(auto jj = 0; jj < Gate_Max; ++jj) {\n      const auto zz_gate = get_batch(ctx->_zz_gate[jj], ctx->_pos);\n      auto gate = get_batch(ctx->_gate[jj], ctx->_pos);\n      if(jj > 0) {\n        _gate_activation_function->f(zz_gate, gate, Operation_Assign);\n      } else {\n        _io_activation_function->f(zz_gate, gate, Operation_Assign);\n      }\n    }\n\n    // Phase 2: State\n    //  c(t) = elem_prod(i(t), a(t)) + elem_prod(f(t), c(t-1))\n    const auto gate_aa = get_batch(ctx->_gate[Gate_A], ctx->_pos);\n    const auto gate_ii = get_batch(ctx->_gate[Gate_I], ctx->_pos);\n    const auto gate_ff = get_batch(ctx->_gate[Gate_F], ctx->_pos);\n    auto cc = get_batch(ctx->_cc, ctx->_pos);\n    if(ctx->_pos > 0) {\n      const auto & cc_prev = get_batch(ctx->_cc, ctx->_pos - 1);\n      cc.array() = gate_ii.array() * gate_aa.array() + gate_ff.array() * cc_prev.array();\n    } else {\n      cc.array() = gate_ii.array() * gate_aa.array();\n    }\n\n    // Phase 3: Output\n    //  h(t) = elem_prod(o(t), activ1(c(t))\n    const auto gate_oo = get_batch(ctx->_gate[Gate_O], ctx->_pos);\n    auto activ_cc = get_batch(ctx->_activ_cc, ctx->_pos);\n    _io_activation_function->f(cc, activ_cc, Operation_Assign);\n    hh.array() = gate_oo.array() * activ_cc.array();\n\n    // done!\n    switch(mode) {\n    case Operation_Assign:\n      out.noalias() = hh;\n      break;\n    case Operation_PlusEqual:\n      out.noalias() += hh;\n      break;\n    }\n  }\n}\n\nvoid yann::LstmLayer::feedforward(\n    const RefConstVectorBatch & input,\n    Context * context,\n    enum OperationMode mode) const\n{\n  feedforward_internal(input, context, mode);\n}\n\nvoid yann::LstmLayer::feedforward(\n    const RefConstSparseVectorBatch & input,\n    Context * context,\n    enum OperationMode mode) const\n{\n  feedforward_internal<RefConstSparseMatrix>(input, context, mode);\n}\n\ntemplate<\n  typename MainInputType,\n  typename InputType,\n  typename GradientInputType,\n  typename ContextType\n>\nvoid yann::LstmLayer::backprop_gate(\n    enum IOGates gate,\n    const std::unique_ptr<ActivationFunction> & activation_function,\n    const RefConstVector & gradient_gate,\n    const InputType & input,\n    boost::optional<GradientInputType> gradient_in,\n    ContextType * ctx) const\n{\n  YANN_SLOW_CHECK(activation_function);\n  YANN_SLOW_CHECK(ctx);\n\n  const auto zz_gate = get_batch(ctx->_zz_gate[gate], ctx->_pos);\n  const auto & ww_x = _ww_x[gate];\n  const auto & ww_h = _ww_h[gate];\n  auto & gradient_zz_gate = ctx->_gradient_zz_gate;\n  auto & tmp_derivative = ctx->_tmp_derivative;\n\n  // gate(t) = activ(zz_gate(t))\n  //\n  // grad(zz_gate) = grad(gate) * activ'(zz_gate)\n  activation_function->derivative(zz_gate, tmp_derivative);\n  gradient_zz_gate.array() = gradient_gate.array() * tmp_derivative.array();\n\n  // zz_gate(t) = ww_x_gate*x(t) + ww_h_gate * h(t-1) + bb_gate\n  //\n  // grad(ww_x_gate) = grad(zz_gate) * d zz_gate/dww_x_gate = grad(zz_gate) * x(t)\n  // grad(ww_h_gate) = grad(zz_gate) * d zz_gate/dww_h_gate = grad(zz_gate) * h(t-1)\n  // grad(b) = grad(zz_gate) * d zz_gate/db = grad(zz_gate)\n  YANN_SLOW_CHECK(is_same_size(ctx->_delta_ww_x[gate], _ww_x[gate]));\n  YANN_SLOW_CHECK(is_same_size(ctx->_delta_ww_h[gate], _ww_h[gate]));\n  YANN_SLOW_CHECK(is_same_size(ctx->_delta_bb[gate], _bb[gate]));\n  ctx->_delta_ww_x[gate] += MatrixFunctions<MainInputType>::product(input.transpose(), gradient_zz_gate);\n  if(ctx->_pos > 0) {\n    auto prev_hh = get_batch(ctx->_hh, ctx->_pos - 1);\n    ctx->_delta_ww_h[gate] += MatrixFunctions<RefConstMatrix>::product(prev_hh.transpose(), gradient_zz_gate);\n  }\n  ctx->_delta_bb[gate].noalias() += gradient_zz_gate;\n\n  // zz_gate(t) = ww_x_gate*x(t) + ww_h_gate * h(t-1) + bb_gate\n  //\n  // grad(h) = grad(zz_gate) * d zz_gate/dh = grad(zz_gate) * transp(ww_h_gate)\n  if(ctx->_pos > 0) {\n    auto & gradient_hh = ctx->_gradient_hh;\n    gradient_hh.noalias() += MatrixFunctions<RefConstMatrix>::product(gradient_zz_gate, ww_h.transpose());\n  }\n\n  // zz_gate(t) = ww_x_gate*x(t) + ww_h_gate * h(t-1) + bb_gate\n  //\n  //  grad(x) = grad(zz_gate) * d zz_gate/dx = grad(zz_gate) * transp(ww_x_gate)\n  if(gradient_in) {\n    (*gradient_in).noalias() += MatrixFunctions<RefConstMatrix>::product(gradient_zz_gate, ww_x.transpose());\n  }\n}\n\ntemplate<typename InputType>\nvoid yann::LstmLayer::backprop_internal(\n    const RefConstVectorBatch & gradient_output,\n    const InputType & input,\n    optional<RefVectorBatch> gradient_input,\n    Context * context) const\n{\n  auto ctx = dynamic_cast<LstmLayer_TrainingContext *>(context);\n  YANN_CHECK(ctx);\n  YANN_CHECK(is_valid());\n  YANN_CHECK_GT(get_batch_size(gradient_output), 0);\n  YANN_CHECK_LE(get_batch_size(gradient_output), ctx->_pos);\n  YANN_CHECK_EQ(get_batch_item_size(gradient_output), get_output_size());\n  YANN_CHECK_EQ(get_batch_size(input), get_batch_size(gradient_output));\n  YANN_CHECK_EQ(get_batch_item_size(input), get_input_size());\n  YANN_CHECK_EQ(get_batch_item_size(input), get_input_size());\n  YANN_CHECK(!gradient_input || is_same_size(input, *gradient_input));\n\n  // Zero out since we will be adding to it\n  if(gradient_input) {\n    gradient_input->setZero();\n  }\n\n  for(MatrixSize ii = get_batch_size(gradient_output) - 1; ii >= 0 && (--ctx->_pos) >= 0; --ii) {\n    const auto in = get_batch(input, ii);\n    auto gradient_in = gradient_input ? make_optional(get_batch(*gradient_input, ii)) : boost::none;\n    const auto gate_aa  = get_batch(ctx->_gate[Gate_A], ctx->_pos);\n    const auto gate_ii  = get_batch(ctx->_gate[Gate_I], ctx->_pos);\n    const auto gate_ff  = get_batch(ctx->_gate[Gate_F], ctx->_pos);\n    const auto gate_oo  = get_batch(ctx->_gate[Gate_O], ctx->_pos);\n    auto & gradient_gate = ctx->_gradient_gate;\n\n    // note that output gradient also has the internal feedback loop\n    auto & gradient_hh = ctx->_gradient_hh;\n    gradient_hh += get_batch(gradient_output, ii);\n\n    // State cell\n    //\n    //  h(t) = elem_prod(o(t), activ1(c(t))\n    //  grad(c) = grad(h) * d h/dactiv1(c) * activ1'(c) = elem_prod(grad(h), o, activ1(c)\n    const auto cc = get_batch(ctx->_cc, ctx->_pos);\n    auto & gradient_cc = ctx->_gradient_cc;\n    auto & tmp_derivative = ctx->_tmp_derivative;\n    _io_activation_function->derivative(cc, tmp_derivative);\n    // add to the gradient from previous step\n    gradient_cc.array() += gradient_hh.array() * gate_oo.array() * tmp_derivative.array();\n\n\n    // Gate O: Output gate:\n    //\n    //  h(t) = elem_prod(o(t), activ1(c(t))\n    //  grad(o) = grad(h) * dh/do = elem_prod(grad(h), activ1(c))\n    const auto activ_cc = get_batch(ctx->_activ_cc, ctx->_pos);\n    gradient_gate.array() = gradient_hh.array() * activ_cc.array();\n    gradient_hh.setZero(); // we will update it in backprop_gate for next step\n    backprop_gate<InputType>(Gate_O, _gate_activation_function, gradient_gate, in, gradient_in, ctx);\n\n    // Gate A\n    //\n    //  c(t) = elem_prod(i(t), a(t)) + elem_prod(f(t), c(t-1))\n    //  grad(a) = grad(c) * dc/da = elem_prod(grad(c), i(t))\n    gradient_gate.array() = gradient_cc.array() * gate_ii.array();\n    backprop_gate<InputType>(Gate_A, _io_activation_function, gradient_gate, in, gradient_in, ctx);\n\n    // Gate I: Input gate\n    //\n    //  c(t) = elem_prod(i(t), a(t)) + elem_prod(f(t), c(t-1))\n    //  grad(i) = grad(c) * dc/di = elem_prod(grad(c), a(t))\n    gradient_gate.array() = gradient_cc.array() * gate_aa.array();\n    backprop_gate<InputType>(Gate_I, _gate_activation_function, gradient_gate, in, gradient_in, ctx);\n\n    // Gate F: Forget gate\n    //\n    //  c(t) = elem_prod(i(t), a(t)) + elem_prod(f(t), c(t-1))\n    //  grad(f) = grad(c) * dc/df = elem_prod(grad(c), c(t-1))\n    if(ctx->_pos > 0) {\n      const auto prev_cc = get_batch(ctx->_activ_cc, ctx->_pos - 1);\n      gradient_gate.array() = gradient_cc.array() * prev_cc.array();\n    } else {\n      gradient_gate.setZero();\n    }\n    backprop_gate<InputType>(Gate_F, _gate_activation_function, gradient_gate, in, gradient_in, ctx);\n\n    // State gradient for prev step\n    //\n    //  c(t) = elem_prod(i(t), a(t)) + elem_prod(f(t), c(t-1))\n    //  grad(c(t-1)) = grad(c) * dc(t)/dc(t-1) = elem_prod(grad(c(t)), f(t))\n    if(ctx->_pos > 0) {\n      gradient_cc.array() = gradient_cc.array() * gate_ff.array();\n    }\n  }\n}\n\nvoid yann::LstmLayer::backprop(\n    const RefConstVectorBatch & gradient_output,\n    const RefConstVectorBatch & input,\n    optional<RefVectorBatch> gradient_input,\n    Context * context) const\n{\n  backprop_internal(gradient_output, input, gradient_input, context);\n}\n\nvoid yann::LstmLayer::backprop(\n    const RefConstVectorBatch & gradient_output,\n    const RefConstSparseVectorBatch & input,\n    optional<RefVectorBatch> gradient_input,\n    Context * context) const\n{\n  // <RefConstSparseMatrix> is required for MatrixFunctions<>::product\n  backprop_internal<RefConstSparseMatrix>(gradient_output, input, gradient_input, context);\n}\n\nvoid yann::LstmLayer::init(enum InitMode mode, boost::optional<InitContext> init_context)\n{\n  switch (mode) {\n  case InitMode_Zeros:\n    for(auto & ww_x: _ww_x) {\n      ww_x.setZero();\n    }\n    for(auto & ww_h: _ww_h) {\n      ww_h.setZero();\n    }\n    for(auto & bb: _bb) {\n      bb.setZero();\n    }\n    break;\n  case InitMode_Random:\n    {\n      unique_ptr<RandomGenerator> gen01 = RandomGenerator::normal_distribution(0, 1,\n          init_context ? optional<Value>(init_context->seed()) : boost::none);\n      for(auto & ww_x: _ww_x) {\n        gen01->generate(ww_x);\n      }\n      for(auto & ww_h: _ww_h) {\n        gen01->generate(ww_h);\n      }\n      for(auto & bb: _bb) {\n        gen01->generate(bb);\n      }\n    }\n    break;\n  }\n}\n\nvoid yann::LstmLayer::update(Context * context, const size_t & tests_num)\n{\n  auto ctx = dynamic_cast<LstmLayer_TrainingContext *>(context);\n  YANN_CHECK(ctx);\n\n  for(auto ii = 0; ii < Gate_Max; ++ii) {\n    YANN_SLOW_CHECK(ctx->_ww_x_updater[ii]);\n    YANN_SLOW_CHECK(ctx->_ww_h_updater[ii]);\n    YANN_SLOW_CHECK(ctx->_bb_updater[ii]);\n\n    ctx->_ww_x_updater[ii]->update(ctx->_delta_ww_x[ii], tests_num, _ww_x[ii]);\n    ctx->_ww_h_updater[ii]->update(ctx->_delta_ww_h[ii], tests_num, _ww_h[ii]);\n    ctx->_bb_updater[ii]->update(ctx->_delta_bb[ii], tests_num, _bb[ii]);\n  }\n}\n\n// the format is (no new lines):\n// (wxa:<_ww_x[Gate_A]>,wxh:<_ww_h[Gate_A]>,ba:<_bb[Gate_A]>,\n//  wxi:<_ww_x[Gate_I]>,wxi:<_ww_h[Gate_I]>,bi:<_bb[Gate_I]>,\n//  wxf:<_ww_x[Gate_F]>,wxf:<_ww_h[Gate_F]>,bf:<_bb[Gate_F]>,\n//  wxo:<_ww_x[Gate_O]>,wxo:<_ww_h[Gate_O]>,bo:<_bb[Gate_O]>)\nvoid yann::LstmLayer::read(std::istream & is)\n{\n  Base::read(is);\n\n  read_char(is, '(');\n\n  for(auto ii = 0; ii < Gate_Max; ++ii) {\n    const char & suffix =  g_ltsm_names_suffix[ii];\n    if(ii > 0) {\n      read_char(is, ',');\n    }\n    read_object(is, string(\"wx\") + suffix, _ww_x[ii]);\n    read_char(is, ',');\n    read_object(is, string(\"wh\") + suffix, _ww_h[ii]);\n    read_char(is, ',');\n    read_object(is, string(\"b\") + suffix, _bb[ii]);\n  }\n  read_char(is, ')');\n}\n\n// the format is (no new lines):\n// (wxa:<_ww_x[Gate_A]>,wxh:<_ww_h[Gate_A]>,ba:<_bb[Gate_A]>,\n//  wxi:<_ww_x[Gate_I]>,wxi:<_ww_h[Gate_I]>,bi:<_bb[Gate_I]>,\n//  wxf:<_ww_x[Gate_F]>,wxf:<_ww_h[Gate_F]>,bf:<_bb[Gate_F]>,\n//  wxo:<_ww_x[Gate_O]>,wxo:<_ww_h[Gate_O]>,bo:<_bb[Gate_O]>)\nvoid yann::LstmLayer::write(std::ostream & os) const\n{\n  Base::write(os);\n\n  os << \"(\";\n  for(auto ii = 0; ii < Gate_Max; ++ii) {\n    const char & suffix =  g_ltsm_names_suffix[ii];\n    if(ii > 0) {\n      os << \",\";\n    }\n    write_object(os, string(\"wx\") + suffix, _ww_x[ii]);\n    os << \",\";\n    write_object(os, string(\"wh\") + suffix, _ww_h[ii]);\n    os << \",\";\n    write_object(os, string(\"b\") + suffix, _bb[ii]);\n  }\n  os << \")\";\n}\n", "meta": {"hexsha": "8f02e66c1432ee837cdb2e7c0398fc0eaf0f000e", "size": 24090, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/layers/lstmlayer.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/layers/lstmlayer.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/layers/lstmlayer.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": 30.8846153846, "max_line_length": 110, "alphanum_fraction": 0.6468659195, "num_tokens": 7015, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382236515259, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.49753433108917355}}
{"text": "#ifndef TRIUMF_BNMR_SLR_STR_EXP_HPP\n#define TRIUMF_BNMR_SLR_STR_EXP_HPP\n\n#include <boost/math/quadrature/tanh_sinh.hpp>\n#include <cmath>\n#include <triumf/bnmr/slr/common.hpp>\n\n// TRIUMF: Canada's particle accelerator centre\nnamespace triumf {\n\n// \u03b2-detected nuclear magnetic resonance (\u03b2-NMR)\nnamespace bnmr {\n\n// spin-lattice relaxation (SLR)\nnamespace slr {\n\n/// pulsed stretched exponential integral (from 0 to time_p)\ntemplate <typename T = double>\nT pulsed_str_exp_integral(T time, T time_p, T nuclear_lifetime, T slr_rate,\n                          T beta) {\n  // integrand for the numeric integral\n  auto integrand = [=](T t_p) {\n    return std::exp(-(time - t_p) / nuclear_lifetime) *\n           std::exp(-std::pow(slr_rate * (time - t_p), beta));\n  };\n  // create the integrator for tanh-sinh quadrature\n  static boost::math::quadrature::tanh_sinh<T> integrator;\n  // evaluate the integral from 0 to time_p\n  T Q = integrator.integrate(integrand, 0.0, time_p);\n  return Q;\n}\n\n/// pulsed stretched exponential\ntemplate <typename T = double>\nT pulsed_str_exp(T time, T nuclear_lifetime, T pulse_length, T asymmetry,\n                 T slr_rate, T beta) {\n  if (time == 0.0) {\n    return asymmetry;\n  } else if (time > 0.0 and time <= pulse_length) {\n    return asymmetry *\n           pulsed_str_exp_integral<T>(time, time, nuclear_lifetime, slr_rate,\n                                      beta) /\n           normalization<T>(time, nuclear_lifetime);\n  } else if (time > pulse_length) {\n    return (asymmetry *\n            pulsed_str_exp_integral<T>(time, pulse_length, nuclear_lifetime,\n                                       slr_rate, beta) /\n            normalization<T>(pulse_length, nuclear_lifetime)) /\n           std::exp(-(time - pulse_length) / nuclear_lifetime);\n  } else {\n    return 0.0;\n  }\n}\n\n/// pulsed stretched exponential (ROOT)\ntemplate <typename T = double> T pulsed_str_exp(const T *x, const T *par) {\n  return pulsed_str_exp<T>(*x, par[0], par[1], par[2], par[3], par[4]);\n}\n\n} // namespace slr\n\n} // namespace bnmr\n\n} // namespace triumf\n\n#endif // TRIUMF_BNMR_SLR_STR_EXP_HPP", "meta": {"hexsha": "5741dd59170455335b3202c061faa0a227879055", "size": 2105, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/triumf/bnmr/slr/str_exp.hpp", "max_stars_repo_name": "rmlmcfadden/triumfpp", "max_stars_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_stars_repo_licenses": ["MIT"], "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/triumf/bnmr/slr/str_exp.hpp", "max_issues_repo_name": "rmlmcfadden/triumfpp", "max_issues_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_issues_repo_licenses": ["MIT"], "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/triumf/bnmr/slr/str_exp.hpp", "max_forks_repo_name": "rmlmcfadden/triumfpp", "max_forks_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_forks_repo_licenses": ["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.8939393939, "max_line_length": 77, "alphanum_fraction": 0.6541567696, "num_tokens": 567, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412809, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.49753432698303995}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// common.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_INCLUDE_PEARSON_CHISQ_COMMON_HPP_ER_2010\n#define BOOST_STATISTICS_DETAIL_NON_PARAMETRIC_CONTINGENCY_TABLE_INCLUDE_PEARSON_CHISQ_COMMON_HPP_ER_2010\n\n#include <boost/statistics/detail/non_parametric/contingency_table/pearson_chisq/common/df_formula.hpp>\n#include <boost/statistics/detail/non_parametric/contingency_table/pearson_chisq/common/asy_distribution.hpp>\n#include <boost/statistics/detail/non_parametric/contingency_table/pearson_chisq/common/chisq_summand_formula.hpp>\n\n#endif\n", "meta": {"hexsha": "70ed14f1b6cb357fbb2249ba60d52ad946f43efa", "size": 1110, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "non_parametric/boost/statistics/detail/non_parametric/backup_once_in_trunk/non_parametric/contingency_table/include/pearson_chisq/common.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/include/pearson_chisq/common.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/include/pearson_chisq/common.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": 69.375, "max_line_length": 114, "alphanum_fraction": 0.5882882883, "num_tokens": 207, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8289387914176258, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4975194131480821}}
{"text": "#include \"./include/rsa.h\"\n#include <boost/multiprecision/cpp_int.hpp>\n#include <iostream>\n#include <string>\n\nint main(int argc, char const *argv[])\n{\n    RSA::key_generator key_gen(100);\n    auto k1 = key_gen.get_public_key_1();\n    auto k2 = key_gen.get_public_key_2();\n    auto k3 = key_gen.get_private_key();\n\n    std::cout << \"Chave p\u00fablica 1:\\t\\t\" << k1 << std::endl;\n    std::cout << \"Chave p\u00fablica 2:\\t\\t\" << k2 << std::endl;\n    std::cout << \"Chave privada:\\t\\t\\t\" << k3 << std::endl;\n    \n    std::cout << \"Chave privada (BRUTADA):\\t\" << RSA::brent_key_breaker(k1, k2) << std::endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "865dfa43bc9f8bd6c535242f4befdb1314a2dba6", "size": 610, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "break.cpp", "max_stars_repo_name": "RafaelGranza/RSA", "max_stars_repo_head_hexsha": "7600c458a5477237b577de24c9b7d60a091d6c92", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "break.cpp", "max_issues_repo_name": "RafaelGranza/RSA", "max_issues_repo_head_hexsha": "7600c458a5477237b577de24c9b7d60a091d6c92", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "break.cpp", "max_forks_repo_name": "RafaelGranza/RSA", "max_forks_repo_head_hexsha": "7600c458a5477237b577de24c9b7d60a091d6c92", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-17T19:28:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-17T19:28:57.000Z", "avg_line_length": 29.0476190476, "max_line_length": 93, "alphanum_fraction": 0.6213114754, "num_tokens": 195, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511616741041, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4975089254126826}}
{"text": "// This file is part of Eigen, a lightweight C++ template library\n// for linear algebra.\n//\n// Copyright (C) 2018 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 \"main.h\"\n#include <Eigen/SparseCore>\n\ntemplate<int ExpectedDim,typename Xpr>\nvoid check_dim(const Xpr& ) {\n  STATIC_CHECK( Xpr::NumDimensions == ExpectedDim );\n}\n\n#if EIGEN_HAS_CXX11\ntemplate<template <typename,int,int> class Object>\nvoid map_num_dimensions()\n{\n  typedef Object<double, 1, 1> ArrayScalarType;\n  typedef Object<double, 2, 1> ArrayVectorType;\n  typedef Object<double, 1, 2> TransposeArrayVectorType;\n  typedef Object<double, 2, 2> ArrayType;\n  typedef Object<double, Eigen::Dynamic, 1> DynamicArrayVectorType;\n  typedef Object<double, 1, Eigen::Dynamic> DynamicTransposeArrayVectorType;\n  typedef Object<double, Eigen::Dynamic, Eigen::Dynamic> DynamicArrayType;\n\n  STATIC_CHECK(ArrayScalarType::NumDimensions == 0);\n  STATIC_CHECK(ArrayVectorType::NumDimensions == 1);\n  STATIC_CHECK(TransposeArrayVectorType::NumDimensions == 1);\n  STATIC_CHECK(ArrayType::NumDimensions == 2);\n  STATIC_CHECK(DynamicArrayVectorType::NumDimensions == 1);\n  STATIC_CHECK(DynamicTransposeArrayVectorType::NumDimensions == 1);\n  STATIC_CHECK(DynamicArrayType::NumDimensions == 2);\n\n  typedef Eigen::Map<ArrayScalarType> ArrayScalarMap;\n  typedef Eigen::Map<ArrayVectorType> ArrayVectorMap;\n  typedef Eigen::Map<TransposeArrayVectorType> TransposeArrayVectorMap;\n  typedef Eigen::Map<ArrayType> ArrayMap;\n  typedef Eigen::Map<DynamicArrayVectorType> DynamicArrayVectorMap;\n  typedef Eigen::Map<DynamicTransposeArrayVectorType> DynamicTransposeArrayVectorMap;\n  typedef Eigen::Map<DynamicArrayType> DynamicArrayMap;\n\n  STATIC_CHECK(ArrayScalarMap::NumDimensions == 0);\n  STATIC_CHECK(ArrayVectorMap::NumDimensions == 1);\n  STATIC_CHECK(TransposeArrayVectorMap::NumDimensions == 1);\n  STATIC_CHECK(ArrayMap::NumDimensions == 2);\n  STATIC_CHECK(DynamicArrayVectorMap::NumDimensions == 1);\n  STATIC_CHECK(DynamicTransposeArrayVectorMap::NumDimensions == 1);\n  STATIC_CHECK(DynamicArrayMap::NumDimensions == 2);\n}\n\ntemplate<typename Scalar, int Rows, int Cols>\nusing TArray = Array<Scalar,Rows,Cols>;\n\ntemplate<typename Scalar, int Rows, int Cols>\nusing TMatrix = Matrix<Scalar,Rows,Cols>;\n\n#endif\n\nvoid test_num_dimensions()\n{\n  int n = 10;\n  ArrayXXd A(n,n);\n  CALL_SUBTEST( check_dim<2>(A) );\n  CALL_SUBTEST( check_dim<2>(A.block(1,1,2,2)) );\n  CALL_SUBTEST( check_dim<1>(A.col(1)) );\n  CALL_SUBTEST( check_dim<1>(A.row(1)) );\n\n  MatrixXd M(n,n);\n  CALL_SUBTEST( check_dim<0>(M.row(1)*M.col(1)) );\n\n  SparseMatrix<double> S(n,n);\n  CALL_SUBTEST( check_dim<2>(S) );\n  CALL_SUBTEST( check_dim<2>(S.block(1,1,2,2)) );\n  CALL_SUBTEST( check_dim<1>(S.col(1)) );\n  CALL_SUBTEST( check_dim<1>(S.row(1)) );\n\n  SparseVector<double> s(n);\n  CALL_SUBTEST( check_dim<1>(s) );\n  CALL_SUBTEST( check_dim<1>(s.head(2)) );\n  \n\n  #if EIGEN_HAS_CXX11\n  CALL_SUBTEST( map_num_dimensions<TArray>() );\n  CALL_SUBTEST( map_num_dimensions<TMatrix>() );\n  #endif\n}\n", "meta": {"hexsha": "f5209283d4e957c2e7c4fb76c3f6fc8bac9dff2e", "size": 3204, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/RePlAce/module/eigen-git-mirror/test/num_dimensions.cpp", "max_stars_repo_name": "gessfred/Parallel-RePlAce", "max_stars_repo_head_hexsha": "e2fdc6a585976daee21991b4fbec96a04cc62d5a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 52.0, "max_stars_repo_stars_event_min_datetime": "2018-11-12T06:39:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T05:31:27.000Z", "max_issues_repo_path": "tensorflow/lite/tools/make/downloads/eigen/test/num_dimensions.cpp", "max_issues_repo_name": "c3motion/kendryte-tensorflow", "max_issues_repo_head_hexsha": "e31097afd93c2d33880a7fb818e151d24caa0950", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-12-04T08:35:40.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-22T16:17:39.000Z", "max_forks_repo_path": "tensorflow/lite/tools/make/downloads/eigen/test/num_dimensions.cpp", "max_forks_repo_name": "c3motion/kendryte-tensorflow", "max_forks_repo_head_hexsha": "e31097afd93c2d33880a7fb818e151d24caa0950", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2019-03-11T01:17:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T00:44:47.000Z", "avg_line_length": 35.2087912088, "max_line_length": 85, "alphanum_fraction": 0.7487515605, "num_tokens": 896, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.689305616785446, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.49750165010330233}}
{"text": "// Group E - Excel Visualization\r\n//\r\n// by Scott Sidoli\r\n//\r\n// 6-15-19\r\n//\r\n// Main.cpp\r\n//\r\n// In this work we use the excel visualization functionality to produce spreadsheet output for the \r\n// four batches. It should be noted that some of the includes need to have the path adjusted to work\r\n// other machines. We describe the four batches, create row labels for the S value and column labels\r\n// are the call/put prices for a given batch. We use an if-else loop inside a for-loop to produce the\r\n// matrix output and then send the output to an excel spreadsheet. We include all our option class \r\n// functionality.\r\n\r\n#include \"C:\\Users\\ssido\\OneDrive\\Desktop\\Level9\\Level9\\Level9Code\\Level9Code\\UtilitiesDJD\\ExcelDriver\\ExcelDriverLite.hpp\"\r\n#include \"C:\\Users\\ssido\\OneDrive\\Desktop\\Level9\\Level9\\Level9Code\\Level9Code\\UtilitiesDJD\\ExcelDriver\\Utilities.hpp\"\r\n#include \"C:\\Users\\ssido\\OneDrive\\Desktop\\Level9\\Level9\\Level9Code\\Level9Code\\UtilitiesDJD\\VectorsAndMatrices\\Vector.hpp\"\r\n#include \"C:\\Users\\ssido\\OneDrive\\Desktop\\Level9\\Level9\\Level9Code\\Level9Code\\UtilitiesDJD\\ExceptionClasses\\DatasimException.hpp\"\r\n#include <iostream>\r\n#include \"EuropeanOption.hpp\"\r\n#include \"MeshArray.hpp\"\r\n#include <boost/tuple/tuple_io.hpp>\r\n#include <iostream>\r\n#include <string>\r\n#include <vector>\r\n#include <list>\r\n#include <fstream>\r\n#include <cmath>\r\n#include <boost/numeric/ublas/matrix.hpp>\r\n#include \"C:\\Users\\ssido\\OneDrive\\Desktop\\Level9\\Level9\\Level9Code\\Level9Code\\UtilitiesDJD\\VectorsAndMatrices\\NestedMatrix.hpp\" \r\n\r\n\r\nusing NumericMatrix = boost::numeric::ublas::matrix<double>; // using NumericMatrix = NestedMatrix<double>; \r\n \r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n\tcurr_stock_price S_start = (curr_stock_price) 10.0;\r\n\tcurr_stock_price S_end = (curr_stock_price) 50.0;\r\n\tcurr_stock_price S_interval = (curr_stock_price) 1.0;\r\n\r\n\tvector<curr_stock_price> S_array = MeshArray(S_start, S_end, S_interval);\r\n\r\n\t// Batch 1\r\n\tTime T1 = (Time) 0.25;\r\n\tStrike_Price K1 = (Strike_Price)65;\r\n\tVolatility sig1 = (Volatility) 0.30;\r\n\trate r1 = (rate) 0.08;\r\n\tcost_of_carry b1 = (cost_of_carry) 0.08;\r\n\tcurr_stock_price S1 = (curr_stock_price) 60.0;\r\n\r\n\t// Create option and set parameters\r\n\tEuropeanOption option1;\r\n\toption1.SetOption(T1, K1, sig1, r1, b1, S1);\r\n\r\n\t// Batch 2\r\n\tTime T2 = (Time) 1.0;\r\n\tStrike_Price K2 = (Strike_Price) 100.0;\r\n\tVolatility sig2 = (Volatility) 0.2;\r\n\trate r2 = (rate) 0.00;\r\n\tcost_of_carry b2 = (cost_of_carry) 0.00;\r\n\tcurr_stock_price S2 = (curr_stock_price) 100.0;\r\n\r\n\t// Create option and set parameters\r\n\tEuropeanOption option2;\r\n\toption2.SetOption(T2, K2, sig2, r2, b2, S2);\r\n\r\n\t// Batch 3\r\n\tTime T3 = (Time) 1.0;\r\n\tStrike_Price K3 = (Strike_Price) 10.0;\r\n\tVolatility sig3 = (Volatility) 0.50;\r\n\trate r3 = (rate) 0.12;\r\n\tcost_of_carry b3 = (cost_of_carry) 0.12;\r\n\tcurr_stock_price S3 = (curr_stock_price) 5.0;\r\n\r\n\t// Create option and set parameters\r\n\tEuropeanOption option3;\r\n\toption3.SetOption(T3, K3, sig3, r3, b3, S3);\r\n\r\n\t// Batch 4\r\n\tTime T4 = (Time) 30.0;\r\n\tStrike_Price K4 = (Strike_Price) 100.0;\r\n\tVolatility sig4 = (Volatility) 0.30;\r\n\trate r4 = (rate) 0.08;\r\n\tcost_of_carry b4 = (cost_of_carry) 0.08;\r\n\tcurr_stock_price S4 = (curr_stock_price) 100.0;\r\n\r\n\t// Create option and set parameters\r\n\tEuropeanOption option4;\r\n\toption4.SetOption(T4, K4, sig4, r4, b4, S4);\r\n\r\n\t// Now we create Row and column labels Rows labeled by S-value, column by Batch num call/put\r\n\tstringstream ss;\r\n\tstring str;\r\n\tlist<string> rowLabels;\r\n\tfor (unsigned int i = 0; i < S_array.size(); ++i)\r\n\t{\r\n\t\tss << i + 10;\r\n\t\tss >> str;\r\n\t\trowLabels.push_back(str);\r\n\t\tss.clear();\r\n\t}\r\n\r\n\tlist<string> colLabels{ \"Batch 1 Call\", \"Batch 1 Put\", \"Batch 2 Call\", \"Batch 2 Put\", \"Batch 3 Call\", \"Batch 3 Put\",\r\n\t\"Batch 4 Call\", \"Batch 4 Put\"};\r\n\r\n\t// Now we write the sheet name\r\n\tstring sheetName(\"Option Prices\");\r\n\r\n\t\r\n\tNumericMatrix PriceMatrix(rowLabels.size(), colLabels.size());\r\n\tfor (unsigned int i = 0; i < PriceMatrix.size1(); i++)\r\n\t{\r\n\t\tfor (unsigned int j = 0; j < PriceMatrix.size2(); j++)\r\n\t\t{\r\n\t\t\tif (j == 0)\r\n\t\t\t{\r\n\t\t\t\toption1.SetOption(S_array[i]);\r\n\t\t\t\tPriceMatrix(i, j) = option1.CallPriceEuro();\r\n\t\t\t}\r\n\t\t\telse if ( j == 1)\r\n\t\t\t{\r\n\t\t\t\toption1.SetOption(S_array[i]);\r\n\t\t\t\tPriceMatrix(i, j) = option1.PutPriceEuro();\r\n\t\t\t}\r\n\t\t\telse if (j == 2)\r\n\t\t\t{\r\n\t\t\t\toption2.SetOption(S_array[i]);\r\n\t\t\t\tPriceMatrix(i, j) = option2.CallPriceEuro();\r\n\t\t\t}\r\n\t\t\telse if (j == 3)\r\n\t\t\t{\r\n\t\t\t\toption2.SetOption(S_array[i]);\r\n\t\t\t\tPriceMatrix(i, j) = option2.PutPriceEuro();\r\n\t\t\t}\r\n\t\t\telse if (j == 4)\r\n\t\t\t{\r\n\t\t\t\toption3.SetOption(S_array[i]);\r\n\t\t\t\tPriceMatrix(i, j) = option3.CallPriceEuro();\r\n\t\t\t}\r\n\t\t\telse if (j == 5)\r\n\t\t\t{\r\n\t\t\t\toption3.SetOption(S_array[i]);\r\n\t\t\t\tPriceMatrix(i, j) = option3.PutPriceEuro();\r\n\t\t\t}\r\n\t\t\telse if (j == 6)\r\n\t\t\t{\r\n\t\t\t\toption4.SetOption(S_array[i]);\r\n\t\t\t\tPriceMatrix(i, j) = option4.CallPriceEuro();\r\n\t\t\t}\r\n\t\t\telse if (j == 7)\r\n\t\t\t{\r\n\t\t\t\toption4.SetOption(S_array[i]);\r\n\t\t\t\tPriceMatrix(i, j) = option4.PutPriceEuro();\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tExcelDriver& excel = ExcelDriver::Instance();\r\n\texcel.MakeVisible(true);\r\n\r\n\tlong row = 1;\r\n\tlong col = 1;\r\n\texcel.AddMatrix<NumericMatrix>(PriceMatrix, sheetName, rowLabels, colLabels, row, col);\r\n\treturn 0;\r\n}", "meta": {"hexsha": "12e6bbf14445639be03d278daae51fd528df2ed1", "size": 5197, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "GroupE/Level9/Level9/Level9Code/Level9Code/Projects/ExcelVisualisation/ExcelVisualisation/Main.cpp", "max_stars_repo_name": "scottsidoli/C-for-Financial-Engineering---Baruch-Pre-MFE-Certificate", "max_stars_repo_head_hexsha": "79c2fb297a85c914d5f0b8671bb17636801e3ce7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-05T08:14:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-05T08:14:37.000Z", "max_issues_repo_path": "GroupE/Level9/Level9/Level9Code/Level9Code/Projects/ExcelVisualisation/ExcelVisualisation/Main.cpp", "max_issues_repo_name": "scottsidoli/C-for-Financial-Engineering---Baruch-Pre-MFE-Certificate", "max_issues_repo_head_hexsha": "79c2fb297a85c914d5f0b8671bb17636801e3ce7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GroupE/Level9/Level9/Level9Code/Level9Code/Projects/ExcelVisualisation/ExcelVisualisation/Main.cpp", "max_forks_repo_name": "scottsidoli/C-for-Financial-Engineering---Baruch-Pre-MFE-Certificate", "max_forks_repo_head_hexsha": "79c2fb297a85c914d5f0b8671bb17636801e3ce7", "max_forks_repo_licenses": ["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.9345238095, "max_line_length": 130, "alphanum_fraction": 0.6769289975, "num_tokens": 1605, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432182679956, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.49750164962235965}}
{"text": "#include \"matrix_utils.h\"\n#include <Eigen/SparseCholesky>\n#include <Eigen/LU>\n\nnamespace rsurfaces\n{\n    namespace MatrixUtils\n    {\n        void TripleTriplets(const std::vector<Triplet> &orig, std::vector<Triplet> &output)\n        {\n            for (const Triplet &t : orig)\n            {\n                output.push_back(Triplet(3 * t.row(), 3 * t.col(), t.value()));\n                output.push_back(Triplet(3 * t.row() + 1, 3 * t.col() + 1, t.value()));\n                output.push_back(Triplet(3 * t.row() + 2, 3 * t.col() + 2, t.value()));\n            }\n        }\n\n        void TripleMatrix(const Eigen::MatrixXd &M, Eigen::MatrixXd &out)\n        {\n            for (int i = 0; i < M.rows(); i++)\n            {\n                for (int j = 0; j < M.cols(); j++)\n                {\n                    out(3 * i, 3 * j) = M(i, j);\n                    out(3 * i + 1, 3 * j + 1) = M(i, j);\n                    out(3 * i + 2, 3 * j + 2) = M(i, j);\n                }\n            }\n        }\n\n        void MatrixIntoColumn(const Eigen::MatrixXd &M, Eigen::VectorXd &out)\n        {\n            int rows = M.rows();\n            int cols = M.cols();\n\n            for (int i = 0; i < rows; i++)\n            {\n                for (int j = 0; j < cols; j++)\n                {\n                    int ind = cols * i + j;\n                    out(ind) = M(i, j);\n                }\n            }\n        }\n\n        void ColumnIntoMatrix(const Eigen::VectorXd &v, Eigen::MatrixXd &out)\n        {\n            int rows = out.rows();\n            int cols = out.cols();\n\n            for (int i = 0; i < rows; i++)\n            {\n                for (int j = 0; j < cols; j++)\n                {\n                    int ind = cols * i + j;\n                    out(i, j) = v(ind);\n                }\n            }\n        }\n\n        void SolveSparseSystem(const Eigen::SparseMatrix<double> &M, Eigen::VectorXd &rhs, Eigen::VectorXd &output)\n        {\n            Eigen::SimplicialLDLT<Eigen::SparseMatrix<double>> solver;\n            solver.compute(M);\n            if (solver.info() != Eigen::Success)\n            {\n                // decomposition failed\n                std::cout << \"Sparse decomposition failed. Exiting.\" << std::endl;\n                std::exit(1);\n            }\n            Eigen::VectorXd x = solver.solve(rhs);\n            if (solver.info() != Eigen::Success)\n            {\n                // solving failed\n                std::cout << \"Sparse solve failed. Exiting.\" << std::endl;\n                std::exit(1);\n            }\n            output = x;\n        }\n\n        void SolveDenseSystem(const Eigen::MatrixXd &M, Eigen::VectorXd &rhs, Eigen::VectorXd &output)\n        {\n            Eigen::PartialPivLU<Eigen::MatrixXd> solver = M.partialPivLu();\n            output = solver.solve(rhs);\n        }\n\n        void SolveDenseSystem(Eigen::PartialPivLU<Eigen::MatrixXd> &solver, const Eigen::MatrixXd &M, Eigen::VectorXd &rhs, Eigen::VectorXd &output)\n        {\n            solver.compute(M);\n            output = solver.solve(rhs);\n        }\n\n    } // namespace MatrixUtils\n} // namespace rsurfaces", "meta": {"hexsha": "f0d2053873fdef03748756046cd5ebf03d46f354", "size": 3100, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/matrix_utils.cpp", "max_stars_repo_name": "Conrekatsu/repulsive-surfaces", "max_stars_repo_head_hexsha": "74d6a16e6ca55c8296fa5a49757c2318bea62a84", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 35.0, "max_stars_repo_stars_event_min_datetime": "2021-12-13T09:58:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T11:03:01.000Z", "max_issues_repo_path": "src/matrix_utils.cpp", "max_issues_repo_name": "Conrekatsu/repulsive-surfaces", "max_issues_repo_head_hexsha": "74d6a16e6ca55c8296fa5a49757c2318bea62a84", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/matrix_utils.cpp", "max_forks_repo_name": "Conrekatsu/repulsive-surfaces", "max_forks_repo_head_hexsha": "74d6a16e6ca55c8296fa5a49757c2318bea62a84", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2022-02-25T06:46:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T05:46:53.000Z", "avg_line_length": 32.6315789474, "max_line_length": 148, "alphanum_fraction": 0.4396774194, "num_tokens": 758, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056040203136, "lm_q2_score": 0.7217432182679956, "lm_q1q2_score": 0.49750164501578575}}
{"text": "#define EIGEN_YES_I_KNOW_SPARSE_MODULE_IS_NOT_STABLE_YET\r\n//#define EIGEN_SUPERLU_SUPPORT\r\n\r\n\r\n#include \"Debug.h\"\r\n#include \"SolverEigen.h\"\r\n#include \"SolverTime.h\"\r\n#include \"ComputerTime.h\"\r\n#include \"util.h\"\r\n#include <chrono>\r\n\r\n//#include <Eigen/SuperLUSupport>\r\n#include <Eigen/SparseExtra>\r\n#include <Eigen/IterativeSolvers>\r\n\r\nextern SolverTime      solverTime;\r\nextern ComputerTime    computerTime;\r\n\r\n\r\nusing namespace std;\r\nusing namespace Eigen;\r\n\r\n\r\n\r\nSolverEigen::SolverEigen()\r\n{\r\n  STABILISED = false;\r\n  \r\n  update_precond = 1;\r\n\r\n  if (debug) cout << \" SolverEigen constructor\\n\\n\";\r\n}\r\n\r\n\r\nSolverEigen::~SolverEigen()\r\n{\r\n  if (debug)  cout << \" SolverEigen destructor\\n\\n\";\r\n\r\n  free();\r\n}\r\n\r\n\r\nint SolverEigen::initialise(int p1, int p2, int p3)\r\n{\r\n   nRow = nCol = p3;\r\n\r\n   //cout << \" nRow = \" << nRow << endl;\r\n\r\n   soln.resize(nRow);\r\n   soln.setZero();\r\n\r\n   rhsVec   = soln;\r\n   solnPrev = soln;\r\n\r\n  return 0;\r\n}\r\n\r\n\r\nint SolverEigen::setSolverAndParameters()\r\n{\r\n    ///////////////////////\r\n    // Create the linear solver and set various options\r\n    ///////////////////////\r\n\r\n\r\n    ///////////////////////\r\n    //Set operators. Here the matrix that defines the linear system\r\n    //also serves as the preconditioning matrix.\r\n    ///////////////////////\r\n\r\n    return 0;\r\n}\r\n\r\n\r\nvoid SolverEigen::zeroMtx()\r\n{\r\n  //cout << \" nRow = \" << nRow << endl;\r\n  //printVector(rhsVec);\r\n\r\n  //cout << \" nRow = \" << nRow << endl;\r\n  //cout << mtx << endl;\r\n  //mtx.setZero();\r\n  mtx *= 0.0;\r\n  rhsVec.setZero();\r\n\r\n  matB *= 0.0;\r\n  rhsVec2.setZero();\r\n\r\n  //cout << \" nRow = \" << nRow << endl;\r\n\r\n  return;\r\n}\r\n\r\n\r\n\r\nint SolverEigen::free()\r\n{\r\n  return 0;\r\n}\r\n\r\n\r\nvoid SolverEigen::printInfo()\r\n{\r\n  //cout << \"Eigen solver:  nRow = \" << nRow << \"\\n\";\r\n  //cout << \"               nnz  = \" <<  << \"\\n\\n\"; \r\n  //printVector(rhsVec);\r\n  //rhsVec.setZero();\r\n  //cout << \" nRow = \" << nRow << endl;\r\n  //cout << mtx << endl;\r\n\r\n  return;\r\n}\r\n\r\n\r\nvoid SolverEigen::printMatrixPatternToFile()\r\n{\r\n    /*\r\n    ofstream fout(\"matrix-pattern2.dat\");\r\n\r\n    if(fout.fail())\r\n    {\r\n      cout << \" Could not open the Output file\" << endl;\r\n      exit(1);\r\n    }\r\n\r\n    fout << totalDOF << setw(10) << totalDOF << endl;\r\n\r\n    for(int k=0; k<mtx.outerSize(); ++k)\r\n    for(SparseMatrixXd::InnerIterator it(mtx,k); it; ++it)\r\n      printf(\"%9d \\t %9d \\n\", it.row(), it.col());\r\n\r\n    //for(int ii=0;ii<nRow;ii++)\r\n      //for(int jj=0;jj<nRow;jj++)\r\n        //printf(\"%5d \\t %5d \\t %12.6f \\n\",mtx.coeffRef(ii,jj));\r\n\r\n    fout.close();\r\n    */\r\n\r\n   FILE * pFile;\r\n   int n;\r\n   char name [100];\r\n\r\n   cout << mtx.nonZeros() << endl;\r\n   //pFile = fopen (\"Stokes.dat\",\"w\");\r\n   pFile = fopen (\"Poisson.dat\",\"w\");\r\n\r\n    fprintf(pFile, \"%9d \\t %9d \\t %9d \\n\", nRow, nCol, 0 );\r\n\r\n    for(int k=0; k<mtx.outerSize(); ++k)\r\n    {\r\n      for(SparseMatrixXd::InnerIterator it(mtx,k); it; ++it)\r\n      {\r\n        if(it.row() == it.col())\r\n          fprintf(pFile, \"%9d \\t %9d \\t %20.16f \\n\", it.row(), it.col(), it.value());\r\n      }\r\n    }\r\n\r\n   fclose (pFile);\r\n\r\n   pFile = fopen (\"rhsVec.dat\",\"w\");\r\n\r\n    for(int k=0; k<nRow; ++k)\r\n      fprintf(pFile, \"%9d \\t %14.8f \\n\", k, rhsVec(k));\r\n\r\n   fclose (pFile);\r\n\r\n   pFile = fopen (\"refsoln.dat\",\"w\");\r\n\r\n    for(int k=0; k<nRow; ++k)\r\n      fprintf(pFile, \"%9d \\t %14.8f \\n\", k, soln(k));\r\n\r\n   fclose (pFile);\r\n  return;\r\n}\r\n\r\n  \r\n\r\nvoid SolverEigen::printMatrix(int dig, int dig2, bool gfrmt, int indent, bool interactive)\r\n{\r\n  printInfo();\r\n  \r\n  cout << mtx << endl;\r\n  printf(\"\\n\\n\");\r\n\r\n  return;\r\n}\r\n\r\ndouble SolverEigen::giveMatrixCoefficient(int row, int col)\r\n{ \r\n  return  mtx.coeff(row,col);\r\n}\r\n\r\n\r\n\r\nint SolverEigen::factorise()\r\n{\r\n  char fct[] = \"SolverEigen::factorise\";\r\n\r\n  if (currentStatus != ASSEMBLY_OK) { prgWarning(1,fct,\"assemble matrix first!\"); return 1; }\r\n\r\n  if (checkIO)\r\n  {\r\n    // search for \"nan\" entries in matrix coefficients\r\n\r\n    //if (prgNAN(mtx.x.x,NE)) prgError(1,fct,\"nan matrix coefficient!\");\r\n  }\r\n\r\n  computerTime.go(fct);\r\n\r\n  currentStatus = FACTORISE_OK;\r\n  \r\n  solverTime.total     -= solverTime.factorise;\r\n  solverTime.factorise += computerTime.stop(fct);\r\n  solverTime.total     += solverTime.factorise;\r\n\r\n  return 0;\r\n}\r\n\r\n\r\nint  SolverEigen::solve()\r\n{\r\n  char fct[] = \"SolverEigen::solve\";\r\n\r\n  time_t tstart, tend;\r\n\r\n  if (currentStatus != FACTORISE_OK) { prgWarning(1,fct,\"factorise matrix first!\"); return 1; }\r\n\r\n\r\n  //algoType = 1;\r\n\r\n  if(algoType == 1)\r\n  {\r\n    //cout << \" Solving with Eigen::SimplicialLDLT \" << endl;\r\n\r\n    SimplicialLDLT<SparseMatrix<double> > solver;\r\n\r\n    //cout << mtx << endl;\r\n    //printVector(rhsVec);\r\n\r\n    printf(\"nnz =  %d \\n \", mtx.nonZeros() );\r\n\r\n    tstart = time(0);\r\n  \r\n    solver.compute(mtx);\r\n\r\n    soln = solver.solve(rhsVec);\r\n\r\n    //printVector(soln);\r\n    //\r\n    //computeConditionNumber();\r\n\r\n    //VectorXd x0 = VectorXd::LinSpaced(nRow, 0.0, 1.0);\r\n\r\n    //double  cond = myCondNum(mtx, x0, 50, solver);\r\n\r\n    //printf(\"\\n Matrix condition number = %12.6E \\n\\n\\n\", cond);\r\n\r\n    //soln = solver.solveWithGuess(rhsVec, soln);\r\n    //cout << solver.info() << '\\t' << solver.error() << '\\t' << solver.iterations() << endl;\r\n    tend = time(0);\r\n    printf(\"It took %8.4f second(s) \\n \", difftime(tend, tstart) );\r\n  }\r\n \r\n  if( algoType == 2 )\r\n  {\r\n    cout << \" Solving with Eigen::BiCGSTAB \" << endl;\r\n\r\n    //ConjugateGradient<SparseMatrixXd, Lower|Upper >   solver;\r\n    //ConjugateGradient<SparseMatrixXd>   solver;\r\n\r\n    BiCGSTAB<SparseMatrixXd, IncompleteLUT<double> > solver;\r\n\r\n    //BiCGSTAB<SparseMatrixXd > solver;\r\n\r\n    //ConjugateGradient<SparseMatrixXd, Lower, IncompleteLUT<double> >   solver;\r\n\r\n    solver.preconditioner().setDroptol(1.0e-3);\r\n    solver.preconditioner().setFillfactor(2);\r\n\r\n    //BiCGSTAB<SparseMatrixXd> solver;\r\n\r\n    //GMRES<SparseMatrixXd, IncompleteLUT<double> > solver;\r\n\r\n    //GMRES<SparseMatrixXd> solver;\r\n\r\n    //solver.set_restart(100);\r\n    //solver.setEigenv(10);\r\n\r\n    solver.setMaxIterations(1000);\r\n    solver.setTolerance(1.0e-8);\r\n\r\n    //tstart = time(0);\r\n    auto  time1 = chrono::steady_clock::now();\r\n\r\n    //cout << \" iiiiiiiiiiiiiii \" << endl;\r\n    solver.compute(mtx);\r\n    //cout << \" iiiiiiiiiiiiiii \" << endl;\r\n \r\n    //printf(\"\\n\\n\");\r\n    //printVector(rhsVec);\r\n\r\n    //soln = solver.solveWithGuess(rhsVec, solnGuess);\r\n    soln = solver.solve(rhsVec);\r\n  \r\n    //printf(\"\\n\\n\");\r\n    //printVector(soln);\r\n\r\n    //tend = time(0); \r\n    //printf(\"It took %8.4f second(s) \\n \", difftime(tend, tstart) );\r\n\r\n    auto  time2 = chrono::steady_clock::now();\r\n    auto  duration = chrono::duration_cast<chrono::milliseconds>(time2-time1).count();\r\n\r\n    cout << \" Error       = \" << solver.error() << endl;\r\n    cout << \" Iterations  = \" << solver.iterations() << endl;\r\n    cout << \" Time (ms)   = \" << duration << endl;\r\n    //cout << solver.info() << '\\t' << solver.error() << '\\t' << solver.iterations() << endl;\r\n  }\r\n\r\n  solnPrev = soln;\r\n\r\n  //printf(\"\\n\\n\");\r\n  //printVector(soln);\r\n\r\n  //cout << \"SolverEigen::solve()  took \"<< difftime(tend, tstart) <<\" second(s).\"<< endl;\r\n\r\n  if(checkIO)\r\n  {\r\n    // search for \"nan\" entries in solution vector\r\n\r\n    //if (prgNAN(RHS,N)) prgError(1,fct,\"nan entry in solution vector!\");\r\n  }\r\n\r\n  return 0;\r\n}\r\n\r\n\r\n\r\n\r\n\r\n\r\nint SolverEigen::factoriseAndSolve()\r\n{\r\n  if(currentStatus != ASSEMBLY_OK)\r\n  {\r\n    cerr << \" assemble matrix first! \" << endl;\r\n    return 1;\r\n  }\r\n  \r\n  factorise();\r\n\r\n  return solve();\r\n}\r\n\r\n\r\n\r\nint SolverEigen::assembleMatrixAndVector(vector<int>& row, vector<int>& col, MatrixXd& Klocal, VectorXd& Flocal)\r\n{\r\n  int ii, jj;\r\n  for(ii=0;ii<row.size();ii++)\r\n  {\r\n    rhsVec[row[ii]] += Flocal(ii);\r\n    for(jj=0;jj<col.size();jj++)\r\n    {\r\n      mtx.coeffRef(row[ii], col[jj]) += Klocal(ii,jj);\r\n    }\r\n  }\r\n\r\n  return 0;\r\n}\r\n\r\n\r\n\r\n\r\nint SolverEigen::assembleMatrixAndVector(int start, int c1, vector<int>& vec1, vector<int>& vec2, MatrixXd& Klocal, VectorXd& Flocal)\r\n{\r\n  // subroutine for mixed formulation\r\n  // vec1 - for variable 'u'\r\n  // vec2 - for variable 'p'\r\n\r\n  int ii, jj, aa, bb, size1, size2;\r\n\r\n  //printVector(vec1);\r\n  //printVector(vec2);\r\n  \r\n  size1 = vec1.size();\r\n  size2 = vec2.size();\r\n\r\n  for(ii=0;ii<size1;ii++)\r\n  {\r\n    rhsVec[vec1[ii]] += Flocal(ii);\r\n    for(jj=0;jj<size1;jj++)\r\n       mtx.coeffRef(vec1[ii], vec1[jj]) += Klocal(ii, jj);\r\n\r\n    for(jj=0;jj<size2;jj++)\r\n    {\r\n       aa = start + vec2[jj];\r\n       bb = size1 + jj;\r\n       mtx.coeffRef(vec1[ii], aa) += Klocal(ii, bb);\r\n       mtx.coeffRef(aa, vec1[ii]) += Klocal(bb, ii);\r\n    }\r\n  }\r\n\r\n  for(ii=0;ii<size2;ii++)\r\n  {\r\n    aa = start + vec2[ii];\r\n    rhsVec[aa] += Flocal(size1+ii);\r\n  }\r\n\r\n  if(STABILISED)\r\n  {\r\n    for(ii=0;ii<size2;ii++)\r\n    {\r\n      aa = start + vec2[ii];\r\n      bb = size1 + ii;\r\n      for(jj=0;jj<size2;jj++)\r\n      {\r\n        mtx.coeffRef(aa, start+vec2[jj]) += Klocal(bb, size1+jj);\r\n      }\r\n    }\r\n  }\r\n\r\n  return 0;\r\n}\r\n\r\n\r\n\r\n\r\nint SolverEigen::assembleMatrixAndVector(int start, int c1, vector<int>& forAssy, MatrixXd& Klocal, VectorXd& Flocal)\r\n{\r\n  int ii, jj, aa, bb, size1, r, c;\r\n\r\n  //printVector(forAssy);\r\n\r\n  size1 = forAssy.size();\r\n\r\n  for(ii=0; ii<size1; ii++)\r\n  {\r\n    aa = forAssy[ii];\r\n    if( aa != -1 )\r\n    {\r\n      r = start + aa;\r\n      rhsVec[r] += Flocal(ii);\r\n\r\n      //cout << ii << '\\t' << aa << '\\t' << r << endl;\r\n\r\n      for(jj=0; jj<size1; jj++)\r\n      {\r\n        bb = forAssy[jj];\r\n        if( bb != -1 )\r\n          mtx.coeffRef(r, start+bb) += Klocal(ii,jj);\r\n      }\r\n    }\r\n  }\r\n\r\n  //cout << \" start = \" << start << '\\t' << c1 << endl;\r\n\r\n  return 0;\r\n}\r\n\r\n\r\nint SolverEigen::assembleMatrixAndVectorMixed(int var2_offset, vector<int>& forAssyVar1, vector<int>& forAssyVar2, MatrixXd& Kuu, MatrixXd& Kup, MatrixXd& Kpu, MatrixXd& Kpp, VectorXd& Fu, VectorXd& Fp)\r\n{\r\n  int ii, jj, row, col;\r\n\r\n  int size1 = forAssyVar1.size();\r\n  int size2 = forAssyVar2.size();\r\n\r\n  for(ii=0; ii<size1; ii++)\r\n  {\r\n    row = forAssyVar1[ii];\r\n    if( row != -1 )\r\n    {\r\n      rhsVec[row] += Fu(ii);\r\n\r\n      for(jj=0; jj<size1; jj++)\r\n      {\r\n        col = forAssyVar1[jj];\r\n        if( col != -1 )\r\n          mtx.coeffRef(row, col) += Kuu(ii,jj);\r\n      }\r\n\r\n      for(jj=0; jj<size2; jj++)\r\n      {\r\n        col = forAssyVar2[jj];\r\n        if( col != -1 )\r\n        {\r\n          col += var2_offset;\r\n          mtx.coeffRef(row, col) += Kup(ii,jj);\r\n        }\r\n      }\r\n    }\r\n  }\r\n\r\n  for(ii=0; ii<size2; ii++)\r\n  {\r\n    row = forAssyVar2[ii];\r\n    if( row != -1 )\r\n    {\r\n      row += var2_offset;\r\n\r\n      rhsVec[row] += Fp(ii);\r\n\r\n      for(jj=0; jj<size1; jj++)\r\n      {\r\n        col = forAssyVar1[jj];\r\n        if( col != -1 )\r\n        {\r\n          mtx.coeffRef(row, col) += Kpu(ii,jj);\r\n        }\r\n      }\r\n\r\n      for(jj=0; jj<size2; jj++)\r\n      {\r\n        col = forAssyVar2[jj];\r\n        if( col != -1 )\r\n        {\r\n          col += var2_offset;\r\n          mtx.coeffRef(row, col) += Kpp(ii,jj);\r\n        }\r\n      }\r\n    }\r\n  }\r\n\r\n  return 0;\r\n}\r\n\r\n\r\n\r\nint SolverEigen::assembleMatrixAndVectorMixed2(int var2_offset, vector<int>& forAssyVar1, vector<int>& forAssyVar2, MatrixXd& Kup, MatrixXd& Kpu, MatrixXd& Kpp, VectorXd& Fu, VectorXd& Fp)\r\n{\r\n  int ii, jj, row, col;\r\n\r\n  int size1 = forAssyVar1.size();\r\n  int size2 = forAssyVar2.size();\r\n\r\n  for(ii=0; ii<size1; ii++)\r\n  {\r\n    row = forAssyVar1[ii];\r\n    if( row != -1 )\r\n    {\r\n      rhsVec[row] += Fu(ii);\r\n\r\n      for(jj=0; jj<size2; jj++)\r\n      {\r\n        col = forAssyVar2[jj];\r\n        if( col != -1 )\r\n        {\r\n          //cout << ii << '\\t' << row << '\\t' << jj << '\\t' << col << endl;\r\n          matB.coeffRef(row, col) += Kup(ii,jj);\r\n          //matC.coeffRef(col, row) += Kpu(jj,ii);\r\n          //cout << \"collllllll\" << endl;\r\n        }\r\n      }\r\n    }\r\n  }\r\n\r\n  for(ii=0; ii<size2; ii++)\r\n  {\r\n    row = forAssyVar2[ii];\r\n    if( row != -1 )\r\n    {\r\n      rhsVec2[row] += Fp(ii);\r\n\r\n      for(jj=0; jj<size1; jj++)\r\n      {\r\n        col = forAssyVar1[jj];\r\n        if( col != -1 )\r\n        {\r\n          matC.coeffRef(row, col) += Kpu(ii,jj);\r\n        }\r\n      }\r\n\r\n      for(jj=0; jj<size2; jj++)\r\n      {\r\n        col = forAssyVar2[jj];\r\n        if( col != -1 )\r\n        {\r\n          //cout << ii << '\\t' << row << '\\t' << jj << '\\t' << col << endl;\r\n          matD.coeffRef(row, col) += Kpp(ii,jj);\r\n          //cout << \"rowwwwwwwww\" << endl;\r\n        }\r\n      }\r\n\r\n    }\r\n  }\r\n\r\n  return 0;\r\n}\r\n\r\n\r\nint SolverEigen::assembleVector(int start, int c1, vector<int>& vec1, VectorXd& Flocal)\r\n{\r\n  int ii, jj;\r\n\r\n  for(ii=0;ii<vec1.size();ii++)\r\n  {\r\n    rhsVec[vec1[ii]] += Flocal(ii);\r\n  }\r\n\r\n  return 0;\r\n}\r\n\r\n\r\n\r\n", "meta": {"hexsha": "9b8d17216f781abf5ccc5941e1ce0daa417685fe", "size": 12682, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mySolvers/SolverEigen.cpp", "max_stars_repo_name": "chennachaos/stabfem", "max_stars_repo_head_hexsha": "b3d1f44c45e354dc930203bda22efc800c377c6f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/mySolvers/SolverEigen.cpp", "max_issues_repo_name": "chennachaos/stabfem", "max_issues_repo_head_hexsha": "b3d1f44c45e354dc930203bda22efc800c377c6f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mySolvers/SolverEigen.cpp", "max_forks_repo_name": "chennachaos/stabfem", "max_forks_repo_head_hexsha": "b3d1f44c45e354dc930203bda22efc800c377c6f", "max_forks_repo_licenses": ["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.9273927393, "max_line_length": 203, "alphanum_fraction": 0.5213688693, "num_tokens": 3842, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.49750164137109737}}
{"text": "// #include <iostream>\n// #include <boost/random/mersenne_twister.hpp>\n// #include <boost/random/uniform_int.hpp>\n// #include <boost/random/uniform_real.hpp>\n// \n// #include \"ParticleFilter.h\"\n// \n// using std::cout;\n// using std::endl;\n// \n// /// Randomly initialize all particles\n// int ParticleFilter::init(int num_particles, double x_min, double x_max, \n// \t      double y_min, double y_max,\n// \t      double heading_min, double heading_max,\n// \t      double velocity_min, double velocity_max)\n// {\n//      num_particles_ = num_particles;\n// \n//      x_min_ = x_min;\n//      x_max_ = x_max;\n//      y_min_ = y_min;\n//      y_max_ = y_max;\n//      heading_min_ = heading_min;\n//      heading_max_ = heading_max;\n//      velocity_min_ = velocity_min;\n//      velocity_max_ = velocity_max;\n//      \n//      boost::uniform_int<> x_dist(x_min_, x_max_);\n//      boost::uniform_int<> y_dist(y_min_, y_max_);\n//      boost::uniform_int<> heading_dist(heading_min_, heading_max_);\n//      boost::uniform_int<> x_velocity_dist(velocity_min_, velocity_max_);\n//      boost::uniform_int<> y_velocity_dist(velocity_min_, velocity_max_);\n//      \n//      for (int i = 0 ; i < num_particles_ ; i++) {\n// \t  double x=0, y=0, heading=0, x_velocity=0, y_velocity;\n// \n// \t  x = x_dist(gen_);\n// \t  y = y_dist(gen_);\n// \t  heading = heading_dist(gen_);\n// \t  x_velocity = x_velocity_dist(gen_);\n// \t  y_velocity = y_velocity_dist(gen_);\n// \t  \n// \t  cv::Point center(x,y);\n// \t  cv::Point2d velocity(x_velocity,y_velocity);\n// \n// \t  Particle particle(center,heading,velocity,1.0/num_particles_); \n// \t  particles_.push_back(particle);\n//      }\n// \n//      return 0;\n// }\n// \n// /// Use motion model to update particles\n// int ParticleFilter::kinematic_step()\n// {\n//      std::vector<Particle>::iterator it;\n//      for (it = particles_.begin(); it != particles_.end(); it++) {\n// \t  it->kinematic_step();\n//      }\n//      return 0;\n// }\n// \n// int ParticleFilter::importance_weight_update(cv::Point target) \n// {\n//      double champ = -9999;\n//      double wNorm = 0;\n//      std::vector<Particle>::iterator it;\n//      for (it = particles_.begin(); it != particles_.end(); it++) {\n// \t  double w = it->importance_weight_update(target);\n// \t  wNorm += w;\n// \n// \t  if (w > champ) {\n// \t       champ = w;\n// \t  }\n//      }\n// \n//      wMax_ = champ;\n// \n//      for (it = particles_.begin(); it != particles_.end(); it++) {\n// \t  it->normalize_importance_weight(wNorm);\n//      }\n// \n//      return 0;\n// }\n// \n// int ParticleFilter::importance_weight_update(cv::Point target, cv::Point2d velocity) \n// {\n//      double champ = -9999;\n//      double wNorm = 0;\n//      std::vector<Particle>::iterator it;\n//      for (it = particles_.begin(); it != particles_.end(); it++) {\n// \t  double w = it->importance_weight_update(target, velocity);\n// \t  wNorm += w;\n// \n// \t  if (w > champ) {\n// \t       champ = w;\n// \t  }\n//      }\n// \n//      wMax_ = champ;\n// \n//      for (it = particles_.begin(); it != particles_.end(); it++) {\n// \t  it->normalize_importance_weight(wNorm);\n//      }\n// \n//      return 0;\n// }\n// \n// \n// \n// int ParticleFilter::resample_wheel()\n// {\n//      boost::uniform_int<> index_select(0, particles_.size()-1);\n//      boost::uniform_real<> beta_select(0, 2*wMax_);\n//      \n//      std::vector<Particle> newParticles;\n// \n//      int index = index_select(gen_);\n//      double beta = 0;\n// \n//      //std::vector<Particle>::iterator it;\n//      //for (it = particles_.begin(); it != particles_.end(); it++) {\n//      for (int i = 0 ; i < num_particles_; i++) {\n// \t  beta += beta_select(gen_);\n// \t  while (beta > particles_[index].not_normalized_weight()) {\n// \t       beta -= particles_[index].not_normalized_weight();\n// \t       index = (index + 1) % particles_.size(); \n// \t  }\n// \t  \n// \t  Particle part1 = particles_[index];\n// \t  Particle part2 = part1;\n// \n// \t  boost::uniform_int<> x1_velocity_dist(velocity_min_, velocity_max_);\n// \t  boost::uniform_int<> y1_velocity_dist(velocity_min_, velocity_max_);\n// \n// \t  boost::uniform_int<> x2_velocity_dist(velocity_min_, velocity_max_);\n// \t  boost::uniform_int<> y2_velocity_dist(velocity_min_, velocity_max_);\n//      \n// \t  cv::Point2d velocity1, velocity2;\n// \t  velocity1.x = x1_velocity_dist(gen_);\n// \t  velocity1.y = y1_velocity_dist(gen_);\n// \n// \t  velocity2.x = x2_velocity_dist(gen_);\n// \t  velocity2.y = y2_velocity_dist(gen_);\n// \n// \t  part1.set_velocity(velocity1);\n// \t  part2.set_velocity(velocity2);\n//      \n// \t  newParticles.push_back(part1);\n// \t  newParticles.push_back(part2);\n//      }\n//      particles_ = newParticles;\n//      return 0;\n// }\n// \n// \n// int ParticleFilter::getParticles(std::vector<Particle> &particles)\n// {\n//      particles = particles_;\n//      return 0;\n// }\n", "meta": {"hexsha": "e3deb9a0b8a7344776d807bb6d8675a9aa54c972", "size": 4778, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/filter/ParticleFilter.cpp", "max_stars_repo_name": "SyllogismRXS/openmht", "max_stars_repo_head_hexsha": "a29ae04907f88618a938a5eb58a950b0efcde849", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2017-01-09T12:21:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-12T16:50:02.000Z", "max_issues_repo_path": "src/filter/ParticleFilter.cpp", "max_issues_repo_name": "SyllogismRXS/openmht", "max_issues_repo_head_hexsha": "a29ae04907f88618a938a5eb58a950b0efcde849", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-05-27T14:55:44.000Z", "max_issues_repo_issues_event_max_datetime": "2016-05-27T14:55:44.000Z", "max_forks_repo_path": "src/filter/ParticleFilter.cpp", "max_forks_repo_name": "SyllogismRXS/openmht", "max_forks_repo_head_hexsha": "a29ae04907f88618a938a5eb58a950b0efcde849", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2016-12-09T15:52:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-29T14:02:06.000Z", "avg_line_length": 29.4938271605, "max_line_length": 88, "alphanum_fraction": 0.5939723734, "num_tokens": 1316, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.6334102775181399, "lm_q1q2_score": 0.4974225261574915}}
{"text": "#include <std_msgs/Bool.h>\n#include <std_msgs/Float32.h>\n#include <std_srvs/Empty.h>\n#include <aquacore/StateMsg.h>\n#include <dynamic_reconfigure/server.h>\n#include <aqua_utils/DepthFilterConfig.h>\n#include <aquacore/EmptyBool.h>\n#include <boost/thread/mutex.hpp>\n#include <list>\n#include <algorithm>\n#include <cmath>\n\ntypedef std::pair<ros::Time, float> EntryType;\ntypedef dynamic_reconfigure::Server<aqua_utils::DepthFilterConfig> ReconfigureServer;\n\n\n/**\n * A re-implementation of depth_filter.py\n *\n * NOTE: cannot find easy way to implement waitTillConstantDepth in roscpp,\n *       since this service handler must be isolated from others, so that\n *       node does not block. This might be doable with multi-threaded spinners,\n *       or with service server that has a dedicated handler thread, but\n *       good luck figuring out kinks with the former or the syntax of the latter:\n *\n *       http://www.ros.org/wiki/roscpp/Overview/Callbacks%20and%20Spinning\n */\nclass DepthFilter {\npublic:\n#ifdef ENABLE_WAIT_TILL_CONSTANT_DEPTH\n  bool waitTillConstantDepth(std_srvs::Empty::Request& req,\n      std_srvs::Empty::Response& res) {\n    // WARNING: may likely block subsequent ROS callbacks!\n    constant_depth_off_mutex.lock();\n    constant_depth_off_mutex.unlock();\n    return true;\n  };\n#endif\n\n  bool hasReachedConstantDepth(aquacore::EmptyBool::Request& req,\n      aquacore::EmptyBool::Response& res) {\n    res.result = has_reached_constant_depth;\n    has_reached_constant_depth = false;\n    return true;\n  };\n\n  void dyncfgCB(aqua_utils::DepthFilterConfig& config, uint32_t level) {\n    min_window_entries = config.min_window_entries;\n    window_size_sec = ros::Duration(config.window_size_sec);\n    cutoff_sigma_multiplier = config.cutoff_sigma_multiplier;\n    N_sigma_cutoff_m = config.N_sigma_cutoff_m;\n  };\n\n  void stateCB(const aquacore::StateMsg::ConstPtr& data) {\n    state_mutex.lock();\n    \n    EntryType curr_entry = std::make_pair(data->header.stamp, data->Depth);\n\n    // Remove outdated entries from sliding window\n    if (window.size() > 0) {\n      std::list<EntryType>::iterator outdated_i = window.end();\n      std::list<EntryType>::iterator i = window.begin();\n      for (; i != window.end(); i++) {\n        // Stop loop when found entry within sliding window\n        if (curr_entry.first - i->first <= window_size_sec) {\n          outdated_i = i;\n          break;\n        }\n      }\n      window.erase(window.begin(), outdated_i);\n    }\n\n    // Compute mean and standard deviation of depth values\n    window.push_back(curr_entry);\n    size_t num_entries = window.size();\n    if ((int) num_entries > min_window_entries) {\n      double sum = 0.0;\n      double sum_sqrd = 0.0;\n      for (std::list<EntryType>::iterator v = window.begin(); v != window.end(); v++) {\n        sum += v->second;\n        sum_sqrd += v->second * v->second;\n      }\n      double mean_depth = sum/num_entries;\n      double stdev_depth = sqrt(sum_sqrd/num_entries - mean_depth*mean_depth);\n      constant_depth = (stdev_depth * cutoff_sigma_multiplier < N_sigma_cutoff_m);\n      //ROS_INFO(\"n: %d, u: %.4f, s: %.4f, c: %d\", (int) num_entries, mean_depth, stdev_depth, constant_depth);\n\n      // Publish mean depth (a.k.a. filtered depth)\n      filtered_depth_msg.data = mean_depth;\n      filtered_depth_pub.publish(filtered_depth_msg);\n\n      // Publish flag indicating whether depth is constant or not\n      constant_depth_msg.data = constant_depth;\n      constant_depth_pub.publish(constant_depth_msg);\n\n#ifdef ENABLE_WAIT_TILL_CONSTANT_DEPTH\n      // Update constant-depth-OFF mutex\n      if (!has_prev_constant_depth) {\n        if (!constant_depth) {\n          constant_depth_off_mutex.lock();\n        }\n      } else if (constant_depth && !prev_constant_depth) {\n        constant_depth_off_mutex.unlock();\n      } else if (!constant_depth && prev_constant_depth) {\n        constant_depth_off_mutex.lock();\n      }\n      prev_constant_depth = constant_depth;\n      has_prev_constant_depth = true;\n#endif\n\n      if (constant_depth) {\n        has_reached_constant_depth = true;\n      }\n    } // if (num_entries > min_window_entries)\n    \n    state_mutex.unlock();\n  };\n  \n  bool resetHandler(std_srvs::Empty::Request& req,\n      std_srvs::Empty::Response& res) {\n    reset();\n    return true;\n  };\n  \n  void reset() {\n    state_mutex.lock();\n    \n    constant_depth = false;\n#ifdef ENABLE_WAIT_TILL_CONSTANT_DEPTH\n    prev_constant_depth = false;\n    has_prev_constant_depth = false;\n#endif\n    has_reached_constant_depth = false;\n  \n    window.clear();\n    \n    state_mutex.unlock();\n  };\n\n  DepthFilter() : nh(\"~\"),\n      constant_depth(false),\n#ifdef ENABLE_WAIT_TILL_CONSTANT_DEPTH\n      prev_constant_depth(false), has_prev_constant_depth(false),\n#endif\n      has_reached_constant_depth(false) {\n    double _window_size_sec;\n    nh.param<int>(\"min_window_entries\", min_window_entries, 4);\n    nh.param<double>(\"window_size_sec\", _window_size_sec, 2.0);\n    nh.param<double>(\"cutoff_sigma_multiplier\", cutoff_sigma_multiplier, 3);\n    nh.param<double>(\"N_sigma_cutoff_m\", N_sigma_cutoff_m, 0.15);\n    window_size_sec = ros::Duration(_window_size_sec);\n\n    filtered_depth_pub = nh.advertise<std_msgs::Float32>(\"/aqua/filtered_depth\", 100);\n    constant_depth_pub = nh.advertise<std_msgs::Bool>(\"/aqua/constant_depth_flag\", 100);\n    constant_depth_query_svc = nh.advertiseService(\n        \"/aqua/has_reached_constant_depth\", &DepthFilter::hasReachedConstantDepth, this);\n    state_sub = nh.subscribe(\"/aqua/state\", 100, &DepthFilter::stateCB, this);\n\n    reset_svc = nh.advertiseService(\"reset\", &DepthFilter::resetHandler, this);\n\n#ifdef ENABLE_WAIT_TILL_CONSTANT_DEPTH\n    constant_depth_blocking_svc = nh.advertiseService(\n        \"/aqua/wait_till_constant_depth\", &DepthFilter::waitTillConstantDepth, this);\n#endif\n\n    dyncfg_server = new ReconfigureServer(dyncfg_mutex, nh);\n    dyncfg_server->setCallback(bind(&DepthFilter::dyncfgCB, this, _1, _2));\n    \n    reset();\n  };\n\n\nprotected:\n  ros::NodeHandle nh;\n\n  bool constant_depth;\n#ifdef ENABLE_WAIT_TILL_CONSTANT_DEPTH\n  bool prev_constant_depth;\n  bool has_prev_constant_depth;\n#endif\n  bool has_reached_constant_depth;\n\n  int min_window_entries;\n  ros::Duration window_size_sec;\n  double cutoff_sigma_multiplier;\n  double N_sigma_cutoff_m;\n\n  std::list<EntryType> window;\n#ifdef ENABLE_WAIT_TILL_CONSTANT_DEPTH\n  boost::mutex constant_depth_off_mutex;\n#endif\n\n  boost::mutex state_mutex;\n\n  ros::Publisher filtered_depth_pub;\n  ros::Publisher constant_depth_pub;\n  ros::ServiceServer reset_svc;\n#ifdef ENABLE_WAIT_TILL_CONSTANT_DEPTH\n  ros::ServiceServer constant_depth_blocking_svc;\n#endif\n  ros::ServiceServer constant_depth_query_svc;\n  ros::Subscriber state_sub;\n\n  std_msgs::Float32 filtered_depth_msg;\n  std_msgs::Bool constant_depth_msg;\n\n  ReconfigureServer* dyncfg_server;\n  boost::recursive_mutex dyncfg_mutex;\n};\n\n\nint main(int argc, char** argv) {\n  ros::init(argc, argv, \"depth_filter\");\n  DepthFilter filter;\n  ros::spin();\n  return 0;\n};\n", "meta": {"hexsha": "aebd473e25eeeb960f52bd2415c7f476e48d8580", "size": 7020, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/aqua_utils/src/DepthFilterNode.cpp", "max_stars_repo_name": "newphew92/robotAss2", "max_stars_repo_head_hexsha": "25260d5c953aa3d2987a973f99131991cad3d0b7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/aqua_utils/src/DepthFilterNode.cpp", "max_issues_repo_name": "newphew92/robotAss2", "max_issues_repo_head_hexsha": "25260d5c953aa3d2987a973f99131991cad3d0b7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/aqua_utils/src/DepthFilterNode.cpp", "max_forks_repo_name": "newphew92/robotAss2", "max_forks_repo_head_hexsha": "25260d5c953aa3d2987a973f99131991cad3d0b7", "max_forks_repo_licenses": ["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.2018348624, "max_line_length": 111, "alphanum_fraction": 0.7116809117, "num_tokens": 1694, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384736, "lm_q2_score": 0.6334102567576902, "lm_q1q2_score": 0.49742250348881234}}
{"text": "// Copyright (C) 2004-2006 The Trustees of Indiana University.\n\n// Use, modification and distribution is subject to the Boost Software\n// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n//  Authors: Douglas Gregor\n//           Andrew Lumsdaine\n#ifndef BOOST_GRAPH_RANDOM_LAYOUT_HPP\n#define BOOST_GRAPH_RANDOM_LAYOUT_HPP\n\n#include <boost/graph/graph_traits.hpp>\n#include <boost/random/uniform_int.hpp>\n#include <boost/random/uniform_01.hpp>\n#include <boost/random/uniform_real.hpp>\n#include <boost/type_traits/is_integral.hpp>\n#include <boost/mpl/if.hpp>\n#include <boost/graph/point_traits.hpp>\n\nnamespace boost {\n\ntemplate<typename Graph, typename PositionMap, \n         typename RandomNumberGenerator>\nvoid\nrandom_graph_layout\n (const Graph& g, PositionMap position_map,\n  typename property_traits<PositionMap>::value_type const& origin,\n  typename property_traits<PositionMap>::value_type const& extent,\n  RandomNumberGenerator& gen)\n{\n  typedef typename property_traits<PositionMap>::value_type Point;\n  typedef typename graph::point_traits<Point>::component_type Dimension;\n\n  typedef typename mpl::if_<is_integral<Dimension>,\n                            uniform_int<Dimension>,\n                            uniform_real<Dimension> >::type distrib_t;\n  typedef typename mpl::if_<is_integral<Dimension>,\n                            RandomNumberGenerator&,\n                            uniform_01<RandomNumberGenerator, Dimension> >\n    ::type gen_t;\n\n  gen_t my_gen(gen);\n  distrib_t x(origin[0], origin[0] + extent[0]);\n  distrib_t y(origin[1], origin[1] + extent[1]);\n  typename graph_traits<Graph>::vertex_iterator vi, vi_end;\n  for(tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi) {\n    position_map[*vi][0] = x(my_gen);\n    position_map[*vi][1] = y(my_gen);\n  }\n}\n\n} // end namespace boost\n\n#endif // BOOST_GRAPH_RANDOM_LAYOUT_HPP\n", "meta": {"hexsha": "0dd3a355cd8198a165da5fe1d248435e31c469b1", "size": 1905, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/graph/random_layout.hpp", "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": "boost/graph/random_layout.hpp", "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": "boost/graph/random_layout.hpp", "max_forks_repo_name": "erwinvaneijk/bgl-python", "max_forks_repo_head_hexsha": "6731d1e0e9681e99f1ad0a876b2adb8139d93027", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2015-07-13T07:50:49.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-26T15:08:03.000Z", "avg_line_length": 34.6363636364, "max_line_length": 74, "alphanum_fraction": 0.7144356955, "num_tokens": 441, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384736, "lm_q2_score": 0.6334102567576901, "lm_q1q2_score": 0.4974225034888123}}
{"text": "// Modified from NetKet source for YANNQ Project\n// <Chae-Yeun Park>(chae.yeun.park@gmail.com)\n// 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 YANNQ_ACTIVATIONLAYER_HH\n#define YANNQ_ACTIVATIONLAYER_HH\n\n#include <complex>\n#include <fstream>\n#include <random>\n#include <vector>\n#include <tuple>\n#include <type_traits>\n\n#include <Eigen/Dense>\n\n#include \"AbstractLayer.hpp\"\n#include \"activations.hpp\"\n\n/**\n * Misc: Because of bugs in Intel C compiler (ICC), constexpr static member \n * variable of template class does not work. If there's any update in ICC \n * regarding this bug, one may update name function to return such a member\n * variable.\n * */\n\nnamespace yannq {\n\ntemplate <typename T, class Activation>\nclass ActivationLayer\n\t: public AbstractLayer<T> \n{\npublic:\n\tusing Scalar = T;\n\tusing Vector = typename AbstractLayer<T>::Vector;\n\tusing Matrix = typename AbstractLayer<T>::Matrix;\n\tusing VectorRef = typename AbstractLayer<T>::VectorRef;\n\tusing VectorConstRef = typename AbstractLayer<T>::VectorConstRef;\n\nprivate:\n\n\tActivation f_;  \n\npublic:\n\tActivationLayer()\n\t{\n\t}\n\n\ttemplate<typename ...Ts, \n\t\ttypename disable_if<\n            std::is_same<\n                typename std::remove_reference<typename get_nth_type<0, Ts...>::type>::type,\n                ActivationLayer<T, Activation>\n\t\t\t>::value, int>::type = 0>\n\tActivationLayer(Ts&&... args)\n\t\t: f_(std::forward<Ts>(args)...)\n\t{\n\t}\n\n\tActivationLayer(const ActivationLayer&) = default;\n\tActivationLayer(ActivationLayer&&) = default;\n\t\n\tActivationLayer& operator=(const ActivationLayer&) = default;\n\tActivationLayer& operator=(ActivationLayer&&) = default;\n\t\n\tstd::string name() const override \n\t{\n\t\treturn std::string(\"Activation Layer\");\n\t}\n\t\n\tbool operator==(const ActivationLayer& rhs) const\n\t{\n\t\treturn f_.name() == rhs.f_.name();\n\t}\n\n\tuint32_t paramDim() const override { return 0; }\n\n\tVector getParams() const override\n\t{\n\t\treturn Vector{};\n\t}\n\n\tvoid setParams(VectorConstRef pars) override\n\t{\n\t\t(void)pars;\n\t}\n\n\tuint32_t outputDim(uint32_t inputDim) const override \n\t{\n\t\treturn inputDim; \n\t}\n\n\t// Feedforward\n\tvoid forward(const VectorConstRef& input, VectorRef output) override \n\t{\n\t\tassert(input.size() == output.size());\n\t\tf_.operator()(input, output);\n\t}\n\n\t// Computes derivative.\n\tvoid backprop(const VectorConstRef& prev_layer_output,\n\t\t\tconst VectorConstRef& this_layer_output,\n\t\t\tconst VectorConstRef& dout,\n\t\t\tVectorRef din, VectorRef /*der*/) override \n\t{\n\t\tdin.resize(prev_layer_output.size());\n\t\tf_.ApplyJacobian(prev_layer_output, this_layer_output, dout, din);\n\t}\n\n\tnlohmann::json desc() const override\n\t{\n\t\tnlohmann::json layerpar;\n\t\tlayerpar[\"name\"] = name();\n\t\tlayerpar[\"activation\"] = f_.name();\n\n\t\treturn layerpar;\n\t}\n\n\ttemplate<class Archive>\n\tvoid serialize(Archive& ar)\n\t{\n\t\tar(f_);\n\t}\n};\n\ntemplate<typename T>\nusing Identity = ActivationLayer<T, activation::Identity<T> >;\n\ntemplate<typename T>\nusing LnCosh = ActivationLayer<T, activation::LnCosh<T> >;\n\ntemplate<typename T>\nusing Tanh = ActivationLayer<T, activation::Tanh<T> >;\n\ntemplate<typename T>\nusing WeakTanh = ActivationLayer<T, activation::WeakTanh<T> >;\n\ntemplate<typename T>\nusing Sigmoid = ActivationLayer<T, activation::Sigmoid<T> >;\n\ntemplate<typename T>\nusing ReLU = ActivationLayer<T, activation::ReLU<T> >;\n\ntemplate<typename T>\nusing LeakyReLU = ActivationLayer<T, activation::LeakyReLU<T> >;\n\ntemplate<typename T>\nusing HardTanh = ActivationLayer<T, activation::HardTanh<T> >;\n\ntemplate<typename T>\nusing SoftShrink = ActivationLayer<T, activation::SoftShrink<T> >;\n\ntemplate<typename T>\nusing LeakyHardTanh = ActivationLayer<T, activation::LeakyHardTanh<T> >;\n\ntemplate<typename T>\nusing SoftSign = ActivationLayer<T, activation::SoftSign<T> >;\n\ntemplate<typename T>\nusing Cos = ActivationLayer<T, activation::Cos<T> >;\n\n}  // namespace yannq\n\n#endif\n", "meta": {"hexsha": "08c743cc910e68501ff06541e636d6852db89eb8", "size": 4401, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Yannq/Machines/layers/ActivationLayer.hpp", "max_stars_repo_name": "cecri/yannq", "max_stars_repo_head_hexsha": "b78c1f86a255059f06b34dd5e538449e7261d0ee", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Yannq/Machines/layers/ActivationLayer.hpp", "max_issues_repo_name": "cecri/yannq", "max_issues_repo_head_hexsha": "b78c1f86a255059f06b34dd5e538449e7261d0ee", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Yannq/Machines/layers/ActivationLayer.hpp", "max_forks_repo_name": "cecri/yannq", "max_forks_repo_head_hexsha": "b78c1f86a255059f06b34dd5e538449e7261d0ee", "max_forks_repo_licenses": ["BSD-3-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.8644067797, "max_line_length": 92, "alphanum_fraction": 0.7252897069, "num_tokens": 1090, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.6513548782017746, "lm_q1q2_score": 0.4972988738189386}}
{"text": "//////////////////////////////////////////////////////////////////\n// (c) Copyright 2008-  by Jeongnim Kim\n//////////////////////////////////////////////////////////////////\n//////////////////////////////////////////////////////////////////\n//   National Center for Supercomputing Applications &\n//   Materials Computation Center\n//   University of Illinois, Urbana-Champaign\n//   Urbana, IL 61801\n//   e-mail: jnkim@ncsa.uiuc.edu\n//\n// Supported by\n//   National Center for Supercomputing Applications, UIUC\n//   Materials Computation Center, UIUC\n//////////////////////////////////////////////////////////////////\n// -*- C++ -*-\n/**@file radfunc.cpp\n * @brief Implement a code to debug radial functors for Jastrow orbitals.\n *\n * Currently, the test uses pade and wm functors.\n */\n#include <iostream>\n#include <iomanip>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <string>\n#include <boost/random.hpp>\nusing namespace std;\n#include \"Utilities/OhmmsInfo.h\"\n#include \"Message/Communicate.h\"\n#include \"Message/OpenMP.h\"\n#include \"QMCWaveFunctions/Jastrow/WMFunctor.h\"\n#include \"QMCWaveFunctions/Jastrow/DerivWMFunctor.h\"\n#include \"QMCWaveFunctions/Jastrow/DerivPadeFunctors.h\"\nusing namespace qmcplusplus;\n\n\ntemplate<typename FT, typename DFT>\nstruct RadFunctorTest\n{\n  FT&  u;\n  DFT& ub;\n  FT& up;\n  FT& um;\n  RadFunctorTest(FT& u_in, DFT& ub_in, FT& up_in, FT& um_in)\n    : u(u_in), ub(ub_in), up(up_in), um(um_in) {}\n\n  void run(double r, double delta)\n  {\n    double v=u.f(r);\n    double dv=u.df(r);\n    double ub_p=up.evaluate(r);\n    double ub_m=um.evaluate(r);\n    cout << \"checking derivative functor \";\n    cout <<  (ub_p-ub_m)/(2*delta)-ub.f(r) << endl;\n    double du,d2udr2;\n    cout << \"checking Functor::evaulate \";\n    double e=u.evaluate(r,du,d2udr2);\n    double dv_p=u.f(r+delta);\n    double dv_m=u.f(r-delta);\n    cout << \"  dudr = \" << (dv_p-dv_m)/(2*delta)-du;\n    cout << \" d2udr2 = \" << (dv_p+dv_m-2.0*v)/(delta*delta)-d2udr2 << endl;\n    cout << \"checking DFunctor::evaulate \";\n    e=ub.evaluate(r,du,d2udr2);\n    v=ub.f(r);\n    dv=ub.df(r);\n    dv_p=ub.f(r+delta);\n    dv_m=ub.f(r-delta);\n    cout << \" dudr = \" << (dv_p-dv_m)/(2*delta)-du;\n    cout << \" d2udr2 = \" << (dv_p+dv_m-2.0*v)/(delta*delta)-d2udr2 << endl;\n  }\n};\n\nint main(int argc, char** argv)\n{\n  //histograms<boost::mt19937>();\n  //histograms<boost::lagged_fibonacci607>();\n  OHMMS::Controller->initialize(argc,argv);\n  OhmmsInfo Welcome(argc,argv,OHMMS::Controller->rank());\n  const double delta=0.001;\n  double rc=5.0;\n  double r=3.5;\n  double b=3.0;\n  if(argc>3)\n  {\n    b=atof(argv[1]);\n    r=atof(argv[2]);\n    rc=atof(argv[3]);\n  }\n  else\n  {\n    cout << \"Using default values\" << endl;\n    cout << \"Usage : radfunc B distance cutoff-distance \" << endl;\n  }\n  cout << \"rc= \" << rc << \" distance= \" << r << endl;\n  cout << \"Printing differences: small numbers are good.\" << endl;\n  //test WMFunctors\n  {\n    typedef WMFunctor<double> RadFunctor;\n    typedef DWMDBFunctor<double> DerivRadFunctor;\n    RadFunctor u(b,rc);\n    RadFunctor up(b+delta,rc);\n    RadFunctor um(b-delta,rc);\n    DerivRadFunctor ub(b,rc);\n    cout << endl << \"Testing WM functors \" << endl;\n    RadFunctorTest<RadFunctor,DerivRadFunctor> test(u,ub,up,um);\n    test.run(r,delta);\n  }\n  //test PadeFunctors\n  {\n    typedef PadeFunctor<double> RadFunctor;\n    typedef DPadeDBFunctor<double> DerivRadFunctor;\n    RadFunctor u(-0.5,b);\n    RadFunctor up(-0.5,b+delta);\n    RadFunctor um(-0.5,b-delta);\n    DerivRadFunctor ub(-0.5,b);\n    cout << endl << \"Testing pade functors \" << endl;\n    RadFunctorTest<RadFunctor,DerivRadFunctor> test(u,ub,up,um);\n    test.run(r,delta);\n  }\n  OHMMS::Controller->finalize();\n  return 0;\n}\n\n/***************************************************************************\n * $RCSfile$   $Author: jnkim $\n * $Revision: 1770 $   $Date: 2007-02-17 17:45:38 -0600 (Sat, 17 Feb 2007) $\n * $Id: OrbitalBase.h 1770 2007-02-17 23:45:38Z jnkim $\n ***************************************************************************/\n", "meta": {"hexsha": "2e58ee1729b6eac57a2eff1a4883ed2359caa06d", "size": 4028, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/performance-regression/full-apps/qmcpack/src/SandBox/radfunc.cpp", "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/SandBox/radfunc.cpp", "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/SandBox/radfunc.cpp", "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": 30.9846153846, "max_line_length": 77, "alphanum_fraction": 0.5794438928, "num_tokens": 1222, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.4972988634846359}}
{"text": "#ifndef INCLUDE_SLAM_HPP\n#define INCLUDE_SLAM_HPP\n\n#include <iostream>\n#include <iomanip>\n#include <ctime>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <pangolin/pangolin.h>\n\n#define MATRIX_SIZE 50\n\nstruct RotationMatrix {\n    Eigen::Matrix3d matrix = Eigen::Matrix3d::Identity();\n};\n\nstruct TranslationVector {\n    Eigen::Vector3d trans = Eigen::Vector3d(0, 0, 0);\n};\n\nstruct QuaternionDraw {\n    Eigen::Quaterniond q;\n};\n\nstd::ostream &operator<<(std::ostream &out, const RotationMatrix &r);\nstd::istream &operator>>(std::istream &in, RotationMatrix &r);\n\nstd::ostream &operator<<(std::ostream &out, const TranslationVector &t);\nstd::istream &operator>>(std::istream &in, TranslationVector &t);\n\nstd::ostream &operator<<(std::ostream &out, const QuaternionDraw quat);\nstd::istream &operator>>(std::istream &in, const QuaternionDraw quat);\n\n\nvoid eigenMatrix();\nvoid eigenGeometry();\nvoid visualizeGeometry();\n\n#endif // !", "meta": {"hexsha": "b88f92292334f4ac5fcf5aa718a863a25420a5ed", "size": 932, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ch03/include/slam.hpp", "max_stars_repo_name": "j32u4ukh/SLAM13", "max_stars_repo_head_hexsha": "d2f0a993831e2b5f724be1e666c854be42914654", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ch03/include/slam.hpp", "max_issues_repo_name": "j32u4ukh/SLAM13", "max_issues_repo_head_hexsha": "d2f0a993831e2b5f724be1e666c854be42914654", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch03/include/slam.hpp", "max_forks_repo_name": "j32u4ukh/SLAM13", "max_forks_repo_head_hexsha": "d2f0a993831e2b5f724be1e666c854be42914654", "max_forks_repo_licenses": ["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.8974358974, "max_line_length": 72, "alphanum_fraction": 0.7274678112, "num_tokens": 230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.4972988634846359}}
{"text": "#include <dice.hpp>\n\n#include <boost/program_options.hpp>\n#include <boost/program_options/options_description.hpp>\n#include <boost/program_options/variables_map.hpp>\n\n#include <iostream>\n#include <string>\n#include <regex>\n#include <vector>\n#include <thread>\n#include <chrono>\n\nnamespace po = boost::program_options;\n\nconst std::string BAD_ROLL_MSG = \"Please specify number and type of dice. Format: #d#\";\n\nbool dieSort(diceutil::Die d1, diceutil::Die d2) { return d1.getVal() < d2.getVal(); }\n\nvoid parseRoll(std::string rollStr, unsigned int keepHighest, unsigned int keepLowest) {\n    std::regex dieRollRegex(\"[0-9]+d[0-9]+\");\n    if (std::regex_match(rollStr, dieRollRegex)) {\n        // Parse the roll string\n        auto dLoc = rollStr.find('d');\n        uint nDice = std::stoi( rollStr.substr(0, dLoc) );\n        uint nSides = std::stoi( rollStr.substr(dLoc + 1) );\n        printf(\"Rolling %d Dice w/ %d Sides Each...\\n\\n\", nDice, nSides);\n        std::this_thread::sleep_for(std::chrono::seconds(1));\n\n        // Vector to hold dice\n        std::vector<diceutil::Die> dice;\n        \n        for (int i = 0; i < nDice; i++) {\n            diceutil::Die d{nSides};\n            d.roll();\n            dice.push_back(d);\n        }\n\n        std::sort(dice.begin(), dice.end(), dieSort);\n        int total = 0;\n        int numElements = dice.size();\n\n        if (keepHighest) {\n            // only print highest n\n            std::cout << \"KEPT: \";\n            for (int i = numElements - 1; i > numElements - 1 - keepHighest; i--) {\n                std::cout << dice[i].getVal() << \"  \";\n                total += dice[i].getVal();\n            }\n            std::cout << std::endl;\n\n            std::cout << \"DISCARDED: \";\n            for (int j = numElements - 1 - keepHighest; j >= 0; j--) {\n                std::cout << dice[j].getVal() << \"  \";\n            }\n        } else if (keepLowest) {\n            // only print lowest n\n            std::cout << \"KEPT: \";\n            for (int i = 0; i < keepLowest; i++) {\n                std::cout << dice[i].getVal() << \"  \";\n                total += dice[i].getVal();\n            }\n            std::cout << std::endl;\n\n            std::cout << \"DISCARDED: \";\n            for (int j = keepLowest; j < numElements; j++) {\n                std::cout << dice[j].getVal() << \"  \";\n            }\n        } else {\n            // print 'em all\n            for (diceutil::Die d: dice) {\n                std::cout << d.getVal() << \"  \";\n                total += d.getVal();\n            }\n        }\n        std::cout << std::endl << std::endl << \"TOTAL: \" << total << std::endl;\n        std::cout << std::endl << std::endl;\n\n    } else {\n        std::cout << BAD_ROLL_MSG << std::endl;\n        exit(1);\n    }\n}\n\nint main(int argc, char* argv[]) {\n    // Set up the command line arguments\n    po::options_description desc(\"Available Options\");\n    desc.add_options()\n        (\"help\", \"Help Message\")\n        (\"highest,h\", po::value<unsigned int>(), \"only take highest n rolls\")\n        (\"lowest,l\", po::value<unsigned int>(), \"only take lowest n rolls\")\n        (\"dice\", po::value<std::string>(), \"dice to roll\")\n    ;\n    po::positional_options_description p;\n    p.add(\"dice\", 1);\n\n    po::variables_map vars;\n    po::store(po::command_line_parser(argc, argv).\n          options(desc).positional(p).run(), vars);\n    po::notify(vars);\n    ////////////////////////////////////////\n\n    // Grab the values for the high / low args\n    const unsigned int keepHighest = (vars.count(\"highest\") ? vars[\"highest\"].as<unsigned int>() : 0);\n    const unsigned int keepLowest = (vars.count(\"lowest\") ? vars[\"lowest\"].as<unsigned int>() : 0);\n\n    // If both provided, notify and exit\n    if (keepLowest && keepHighest) {\n        std::cout << \"Please only provide either -h [ --highest ] OR -l [ --lowest ], not both\" << std::endl;\n        return 1;\n    }\n\n    if (vars.count(\"dice\")) {\n        // Make sure the dice arg is actually supplied\n        const std::string diceRollStr(vars[\"dice\"].as<std::string>());\n\n        parseRoll(diceRollStr, keepHighest, keepLowest);\n\n        return 0;\n    } else {\n        std::cout << BAD_ROLL_MSG << std::endl;\n        std::cout << desc << std::endl;\n        return 1;\n    }\n}\n", "meta": {"hexsha": "0fd541adb7ab7ceaaf2e565eb61146b907c2f834", "size": 4239, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "Jbowman353/dice-util", "max_stars_repo_head_hexsha": "cbcc22bafc74d92fd07a2b5aace2b73f4b438f4c", "max_stars_repo_licenses": ["MIT"], "max_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": "Jbowman353/dice-util", "max_issues_repo_head_hexsha": "cbcc22bafc74d92fd07a2b5aace2b73f4b438f4c", "max_issues_repo_licenses": ["MIT"], "max_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": "Jbowman353/dice-util", "max_forks_repo_head_hexsha": "cbcc22bafc74d92fd07a2b5aace2b73f4b438f4c", "max_forks_repo_licenses": ["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.6428571429, "max_line_length": 109, "alphanum_fraction": 0.5265392781, "num_tokens": 1111, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.4972988634846358}}
{"text": "#ifndef STAN_MATH_PRIM_MAT_FUN_MDIVIDE_LEFT_TRI_HPP\n#define STAN_MATH_PRIM_MAT_FUN_MDIVIDE_LEFT_TRI_HPP\n\n#include <boost/math/tools/promotion.hpp>\n#include <stan/math/prim/mat/fun/Eigen.hpp>\n#include <stan/math/prim/mat/fun/promote_common.hpp>\n#include <stan/math/prim/mat/err/check_multiplicable.hpp>\n#include <stan/math/prim/mat/err/check_square.hpp>\n#ifdef STAN_OPENCL\n#include <stan/math/opencl/opencl_context.hpp>\n#include <stan/math/opencl/multiply.hpp>\n#include <stan/math/opencl/tri_inverse.hpp>\n#include <stan/math/opencl/transpose.hpp>\n#include <stan/math/opencl/copy.hpp>\n#endif\nnamespace stan {\nnamespace math {\n\n/**\n * Returns the solution of the system Ax=b when A is triangular.\n * @tparam TriView Specifies whether A is upper (Eigen::Upper)\n * or lower triangular (Eigen::Lower).\n * @tparam T1 type of elements in A\n * @tparam T2 type of elements in b\n * @tparam R1 number of rows in A\n * @tparam C1 number of columns in A\n * @tparam R2 number of rows in b\n * @tparam C2 number of columns in b\n * @param A Triangular matrix.\n * @param b Right hand side matrix or vector.\n * @return x = A^-1 b, solution of the linear system.\n * @throws std::domain_error if A is not square or the rows of b don't\n * match the size of A.\n */\ntemplate <int TriView, typename T1, typename T2, int R1, int C1, int R2, int C2>\ninline Eigen::Matrix<typename boost::math::tools::promote_args<T1, T2>::type,\n                     R1, C2>\nmdivide_left_tri(const Eigen::Matrix<T1, R1, C1> &A,\n                 const Eigen::Matrix<T2, R2, C2> &b) {\n  check_square(\"mdivide_left_tri\", \"A\", A);\n  check_multiplicable(\"mdivide_left_tri\", \"A\", A, \"b\", b);\n  return promote_common<Eigen::Matrix<T1, R1, C1>, Eigen::Matrix<T2, R1, C1> >(\n             A)\n      .template triangularView<TriView>()\n      .solve(\n          promote_common<Eigen::Matrix<T1, R2, C2>, Eigen::Matrix<T2, R2, C2> >(\n              b));\n}\n\n/**\n * Returns the solution of the system Ax=b when A is triangular and b=I.\n * @tparam T type of elements in A\n * @tparam R1 number of rows in A\n * @tparam C1 number of columns in A\n * @param A Triangular matrix.\n * @return x = A^-1 .\n * @throws std::domain_error if A is not square\n */\ntemplate <int TriView, typename T, int R1, int C1>\ninline Eigen::Matrix<T, R1, C1> mdivide_left_tri(\n    const Eigen::Matrix<T, R1, C1> &A) {\n  check_square(\"mdivide_left_tri\", \"A\", A);\n  int n = A.rows();\n  Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> b;\n  b.setIdentity(n, n);\n  A.template triangularView<TriView>().solveInPlace(b);\n  return b;\n}\n\n/**\n * Returns the solution of the system Ax=b when A is triangular\n * and A and b are matrices of doubles.\n * @tparam TriView Specifies whether A is upper (Eigen::Upper)\n * or lower triangular (Eigen::Lower).\n * @tparam R1 number of rows in A\n * @tparam C1 number of columns in A\n * @tparam R2 number of rows in b\n * @tparam C2 number of columns in b\n * @param A Triangular matrix.\n * @param b Right hand side matrix or vector.\n * @return x = A^-1 b, solution of the linear system.\n * @throws std::domain_error if A is not square or the rows of b don't\n * match the size of A.\n */\ntemplate <int TriView, int R1, int C1, int R2, int C2>\ninline Eigen::Matrix<double, R1, C2> mdivide_left_tri(\n    const Eigen::Matrix<double, R1, C1> &A,\n    const Eigen::Matrix<double, R2, C2> &b) {\n  check_square(\"mdivide_left_tri\", \"A\", A);\n  check_multiplicable(\"mdivide_left_tri\", \"A\", A, \"b\", b);\n#ifdef STAN_OPENCL\n  if (A.rows()\n      >= opencl_context.tuning_opts().tri_inverse_size_worth_transfer) {\n    matrix_cl A_cl(A);\n    matrix_cl b_cl(b);\n    matrix_cl A_inv_cl(A.rows(), A.cols());\n    if (TriView == Eigen::Lower) {\n      A_inv_cl = tri_inverse<TriangularViewCL::Lower>(A_cl);\n    } else {\n      A_inv_cl = tri_inverse<TriangularViewCL::Upper>(A_cl);\n    }\n    matrix_cl C_cl = A_inv_cl * b_cl;\n    return from_matrix_cl(C_cl);\n  } else {\n#endif\n    return A.template triangularView<TriView>().solve(b);\n#ifdef STAN_OPENCL\n  }\n#endif\n}\n\n/**\n * Returns the solution of the system Ax=b when A is triangular, b=I and\n * both are matrices of doubles.\n * @tparam TriView Specifies whether A is upper (Eigen::Upper)\n * or lower triangular (Eigen::Lower).\n * @tparam R1 number of rows in A\n * @tparam C1 number of columns in A\n * @param A Triangular matrix.\n * @return x = A^-1 .\n * @throws std::domain_error if A is not square\n */\ntemplate <int TriView, int R1, int C1>\ninline Eigen::Matrix<double, R1, C1> mdivide_left_tri(\n    const Eigen::Matrix<double, R1, C1> &A) {\n  check_square(\"mdivide_left_tri\", \"A\", A);\n  const int n = A.rows();\n#ifdef STAN_OPENCL\n  if (A.rows()\n      >= opencl_context.tuning_opts().tri_inverse_size_worth_transfer) {\n    matrix_cl A_cl(A);\n    if (TriView == Eigen::Lower) {\n      A_cl = tri_inverse<TriangularViewCL::Lower>(A_cl);\n    } else {\n      A_cl = tri_inverse<TriangularViewCL::Upper>(A_cl);\n    }\n    return from_matrix_cl(A_cl);\n  } else {\n#endif\n    Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> b;\n    b.setIdentity(n, n);\n    A.template triangularView<TriView>().solveInPlace(b);\n    return b;\n#ifdef STAN_OPENCL\n  }\n#endif\n}\n\n}  // namespace math\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "336b4fa6bb374487d1c6e2e1bd8fbeae6f2e5b4e", "size": 5161, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/prim/mat/fun/mdivide_left_tri.hpp", "max_stars_repo_name": "riddell-stan/math", "max_stars_repo_head_hexsha": "d84ee0d991400d6cf4b08a07a4e8d86e0651baea", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-07-23T14:57:41.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-23T14:57:41.000Z", "max_issues_repo_path": "stan/math/prim/mat/fun/mdivide_left_tri.hpp", "max_issues_repo_name": "Capri2014/math", "max_issues_repo_head_hexsha": "d4042bdf8623bba5a1633b557227325a324e32e9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-09-23T19:58:36.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-24T12:03:41.000Z", "max_forks_repo_path": "stan/math/prim/mat/fun/mdivide_left_tri.hpp", "max_forks_repo_name": "riddell-stan/math", "max_forks_repo_head_hexsha": "d84ee0d991400d6cf4b08a07a4e8d86e0651baea", "max_forks_repo_licenses": ["BSD-3-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.9539473684, "max_line_length": 80, "alphanum_fraction": 0.6828134083, "num_tokens": 1499, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.49724097013060015}}
{"text": "/*\n * Copyright (c) 2019, The Robot Studio\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 * * 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/**\n * @file arm_transform.cpp\n * @author Cyril Jourdan\n * @date Sep 26, 2017\n * @version 0.1.0\n * @brief Implementation file for the arm transform\n *\n * Contact: contact@therobotstudio.com\n * Created on : Jul 17, 2012\n */\n\n#include <ros/ros.h>\n#include <string>\n#include <sensor_msgs/JointState.h>\n#include <tf/transform_listener.h>\n//#include <boost/lexical_cast.hpp>\n#include \"std_msgs/Int16.h\"\n#include <std_msgs/Float32.h>\n\n#include <math.h>\n\nusing namespace std;\n\ndouble calculateAlpha(tf::StampedTransform tf_hand, tf::StampedTransform tf_elbow, tf::StampedTransform tf_shoulder)\n{\n\tdouble rightHand[3] = {tf_hand.getOrigin().x(), tf_hand.getOrigin().y(), tf_hand.getOrigin().z()};\n\tdouble rightElbow[3] = {tf_elbow.getOrigin().x(), tf_elbow.getOrigin().y(), tf_elbow.getOrigin().z()};\n\tdouble rightShoulder[3] = {tf_shoulder.getOrigin().x(), tf_shoulder.getOrigin().y(), tf_shoulder.getOrigin().z()};\n\n\t//Al-Kashi triangle formula\n\tdouble num =  pow(rightHand[0]-rightElbow[0], 2) + pow(rightHand[1]-rightElbow[1], 2) + pow(rightHand[2]-rightElbow[2], 2)\n\t\t\t\t+ pow(rightShoulder[0]-rightElbow[0], 2) + pow(rightShoulder[1]-rightElbow[1], 2) + pow(rightShoulder[2]-rightElbow[2], 2)\n\t\t\t\t- pow(rightShoulder[0]-rightHand[0], 2) - pow(rightShoulder[1]-rightHand[1], 2) - pow(rightShoulder[2]-rightHand[2], 2);\n\n\tdouble den = 2 * sqrt(pow(rightHand[0]-rightElbow[0], 2) + pow(rightHand[1]-rightElbow[1], 2) + pow(rightHand[2]-rightElbow[2], 2)) * sqrt(pow(rightShoulder[0]-rightElbow[0], 2) + pow(rightShoulder[1]-rightElbow[1], 2) + pow(rightShoulder[2]-rightElbow[2], 2));\n\n\treturn acos(num/den);\n}\n\ndouble calculateBeta(tf::StampedTransform tf_elbow, tf::StampedTransform tf_neck, tf::StampedTransform tf_shoulder)\n{\n\tdouble rightElbow[3] = {tf_elbow.getOrigin().x(), tf_elbow.getOrigin().y(), tf_elbow.getOrigin().z()};\n\tdouble neck[3] = {tf_neck.getOrigin().x(), tf_neck.getOrigin().y(), tf_neck.getOrigin().z()};\n\tdouble rightShoulder[3] = {tf_shoulder.getOrigin().x(), tf_shoulder.getOrigin().y(), tf_shoulder.getOrigin().z()};\n\n\t//Al-Kashi triangle formula\n\tdouble num =  pow(rightElbow[0]-rightShoulder[0], 2) + pow(rightElbow[1]-rightShoulder[1], 2) + pow(rightElbow[2]-rightShoulder[2], 2)\n\t\t\t\t\t\t+ pow(rightShoulder[0]-neck[0], 2) + pow(rightShoulder[1]-neck[1], 2) + pow(rightShoulder[2]-neck[2], 2)\n\t\t\t\t\t\t- pow(neck[0]-rightElbow[0], 2) - pow(neck[1]-rightElbow[1], 2) - pow(neck[2]-rightElbow[2], 2);\n\n\tdouble den = 2 * sqrt(pow(rightElbow[0]-rightShoulder[0], 2) + pow(rightElbow[1]-rightShoulder[1], 2) + pow(rightElbow[2]-rightShoulder[2], 2)) * sqrt(pow(rightShoulder[0]-neck[0], 2) + pow(rightShoulder[1]-neck[1], 2) + pow(rightShoulder[2]-neck[2], 2));\n\n\treturn acos(num/den);\n}\n\ndouble calculateTheta(tf::StampedTransform tf_elbow, tf::StampedTransform tf_neck, tf::StampedTransform tf_shoulder,  tf::StampedTransform tf_torso)\n{\n\tdouble rightElbow[3] = {tf_elbow.getOrigin().x(), tf_elbow.getOrigin().y(), tf_elbow.getOrigin().z()};\n\tdouble neck[3] = {tf_neck.getOrigin().x(), tf_neck.getOrigin().y(), tf_neck.getOrigin().z()};\n\tdouble rightShoulder[3] = {tf_shoulder.getOrigin().x(), tf_shoulder.getOrigin().y(), tf_shoulder.getOrigin().z()};\n\tdouble torso[3] = {tf_torso.getOrigin().x(), tf_torso.getOrigin().y(), tf_torso.getOrigin().z()};\n\n\t////Theta is the angle between two planes : TNE and SNE\n\tdouble a1 = (rightShoulder[1]-torso[1])*(neck[2]-torso[2]) - (rightShoulder[2]-torso[2])*(neck[1]-torso[1]);\n\tdouble b1 = (rightShoulder[2]-torso[2])*(neck[0]-torso[0]) - (rightShoulder[0]-torso[0])*(neck[2]-torso[2]);\n\tdouble c1 = (rightShoulder[0]-torso[0])*(neck[1]-torso[1]) - (rightShoulder[1]-torso[1])*(neck[0]-torso[0]);\n\n\tdouble a2 = (rightShoulder[1]-rightElbow[1])*(neck[2]-rightElbow[2]) - (rightShoulder[2]-rightElbow[2])*(neck[1]-rightElbow[1]);\n\tdouble b2 = (rightShoulder[2]-rightElbow[2])*(neck[0]-rightElbow[0]) - (rightShoulder[0]-rightElbow[0])*(neck[2]-rightElbow[2]);\n\tdouble c2 = (rightShoulder[0]-rightElbow[0])*(neck[1]-rightElbow[1]) - (rightShoulder[1]-rightElbow[1])*(neck[0]-rightElbow[0]);\n\n\tdouble num = a1*a2 + b1*b2 + c1*c2;\n\n\tdouble den = sqrt((a1*a1+b1*b1+c1*c1)*(a2*a2+b2*b2+c2*c2));\n\n\treturn acos(num/den);\n}\n\ndouble calculatePhi(tf::StampedTransform tf_hand, tf::StampedTransform tf_neck, tf::StampedTransform tf_shoulder,  tf::StampedTransform tf_elbow)\n{\n\tdouble H[3] = {tf_hand.getOrigin().x(), tf_hand.getOrigin().y(), tf_hand.getOrigin().z()};\n\tdouble N[3] = {tf_neck.getOrigin().x(), tf_neck.getOrigin().y(), tf_neck.getOrigin().z()};\n\tdouble S[3] = {tf_shoulder.getOrigin().x(), tf_shoulder.getOrigin().y(), tf_shoulder.getOrigin().z()};\n\tdouble E[3] = {tf_elbow.getOrigin().x(), tf_elbow.getOrigin().y(), tf_elbow.getOrigin().z()};\n\n\t//Phi is the angle between two planes : SNE and SHE\n\tfloat n1[3] = {(N[1]-S[1])*(E[2]-S[2])-(N[2]-S[2])*(E[1]-S[1]),\n\t\t\t\t\t(N[2]-S[2])*(E[0]-S[0])-(N[0]-S[0])*(E[2]-S[2]),\n\t\t\t\t\t(N[0]-S[0])*(E[1]-S[1])-(N[1]-S[1])*(E[0]-S[0])}; //normal plane vector : SNE\n\n\tfloat n2[3] = {(H[1]-S[1])*(E[2]-S[2])-(H[2]-S[2])*(E[1]-S[1]),\n\t\t\t\t\t\t(H[2]-S[2])*(E[0]-S[0])-(H[0]-S[0])*(E[2]-S[2]),\n\t\t\t\t\t\t(H[0]-S[0])*(E[1]-S[1])-(H[1]-S[1])*(E[0]-S[0])}; //normal plane vector : SHE\n\n\tfloat a1,b1,c1;\n\ta1 = n1[0];\n\tb1 = n1[1];\n\tc1 = n1[2];\n\n\tfloat a2,b2,c2;\n\ta2 = n2[0];\n\tb2 = n2[1];\n\tc2 = n2[2];\n\n\tdouble angle_phi = acos(fabs((a1*a2 + b1*b2 + c1*c2)/(sqrt((a1*a1+b1*b1+c1*c1)*(a2*a2+b2*b2+c2*c2)))));\n\n\t//std::cerr << \"angle_phi\" << angle_phi << std::endl;\n\n\treturn angle_phi;\n\n\t//right\n\t/*\n\tdouble a1 = (rightShoulder[1]-rightHand[1])*(rightElbow[2]-rightHand[2]) - (rightShoulder[2]-rightHand[2])*(rightElbow[1]-rightHand[1]);\n\tdouble b1 = (rightShoulder[2]-rightHand[2])*(rightElbow[0]-rightHand[0]) - (rightShoulder[0]-rightHand[0])*(rightElbow[2]-rightHand[2]);\n\tdouble c1 = (rightShoulder[0]-rightHand[0])*(rightElbow[1]-rightHand[1]) - (rightShoulder[1]-rightHand[1])*(rightElbow[0]-rightHand[0]);\n\n\tdouble a2 = (rightShoulder[1]-rightHand[1])*(neck[2]-rightHand[2]) - (rightShoulder[2]-rightHand[2])*(neck[1]-rightHand[1]);\n\tdouble b2 = (rightShoulder[2]-rightHand[2])*(neck[0]-rightHand[0]) - (rightShoulder[0]-rightHand[0])*(neck[2]-rightHand[2]);\n\tdouble c2 = (rightShoulder[0]-rightHand[0])*(neck[1]-rightHand[1]) - (rightShoulder[1]-rightHand[1])*(neck[0]-rightHand[0]);\n\n\tdouble num = a1*a2 + b1*b2 + c1*c2;\n\n\tdouble den = sqrt((a1*a1+b1*b1+c1*c1)*(a2*a2+b2*b2+c2*c2));\n\n\treturn acos(num/den);\n\t*/\n}\n/*\ndouble calculateLambda(tf::StampedTransform tf_hand, tf::StampedTransform tf_elbow, tf::StampedTransform tf_shoulder)\n{\n\tdouble leftHand[3] = {tf_hand.getOrigin().x(), tf_hand.getOrigin().y(), tf_hand.getOrigin().z()};\n\tdouble leftElbow[3] = {tf_elbow.getOrigin().x(), tf_elbow.getOrigin().y(), tf_elbow.getOrigin().z()};\n\tdouble leftShoulder[3] = {tf_shoulder.getOrigin().x(), tf_shoulder.getOrigin().y(), tf_shoulder.getOrigin().z()};\n\n\t//Al-Kashi triangle formula\n\tdouble num =  pow(rightHand[0]-rightElbow[0], 2) + pow(rightHand[1]-rightElbow[1], 2) + pow(rightHand[2]-rightElbow[2], 2)\n\t\t\t\t+ pow(rightShoulder[0]-rightElbow[0], 2) + pow(rightShoulder[1]-rightElbow[1], 2) + pow(rightShoulder[2]-rightElbow[2], 2)\n\t\t\t\t- pow(rightShoulder[0]-rightHand[0], 2) - pow(rightShoulder[1]-rightHand[1], 2) - pow(rightShoulder[2]-rightHand[2], 2);\n\n\tdouble den = 2 * sqrt(pow(rightHand[0]-rightElbow[0], 2) + pow(rightHand[1]-rightElbow[1], 2) + pow(rightHand[2]-rightElbow[2], 2)) * sqrt(pow(rightShoulder[0]-rightElbow[0], 2) + pow(rightShoulder[1]-rightElbow[1], 2) + pow(rightShoulder[2]-rightElbow[2], 2));\n\n\treturn acos(num/den);\n}\n*/\n//sensor_msgs::JointState prev_joint_state;\n/*\nstring playerNb_str = \"1\";\nstring frame_str = \"/openni_depth_frame\";\n*/\nstring playerNb_str = \"0\";\nstring frame_str = \"/camera_depth_optical_frame\";\n/*\nvoid playerNumber_cb(const std_msgs::Int16ConstPtr& number)\n{\n\tplayerNb_str = boost::lexical_cast<string>(number->data);\n\n\t//ROS_INFO(\"Player Number is %s\", playerNb_str);\n\t//cout << \"number = \" << playerNb_str << endl;\n\tROS_INFO(\"number = %d\", number->data);\n\n\tif(number->data == 0)\n\t{\n\t\tframe_str = \"/camera_depth_optical_frame\";\n\t}\n\telse\n\t{\n\t\tframe_str = \"/openni_depth_frame\";\n\t}\n}\n*/\nint main(int argc, char** argv)\n{\n\tros::init(argc, argv, \"arm_transform\");\n\tros::NodeHandle n;\n\tros::Publisher joint_pub = n.advertise<sensor_msgs::JointState>(\"joint_states_kinect\", 100);\n\tros::Publisher test_pub = n.advertise<std_msgs::Float32>(\"/test\", 1);\n\n\tros::Rate loop_rate(50);\n\t//ros::Rate loop_rate(10);\n\n\ttf::TransformListener listener_neck, listener_torso, listener_shoulder, listener_elbow, listener_hand;\n\ttf::StampedTransform transform_neck, transform_torso, transform_shoulder, transform_elbow, transform_hand;\n\n\t//left part\n\ttf::TransformListener listener_leftShoulder, listener_leftElbow, listener_leftHand;\n\ttf::StampedTransform transform_leftShoulder, transform_leftElbow, transform_leftHand;\n\n\t//read the player number : 0 used for the posture generated by IR markers, other numbers used by openni_tracker\n\t//ros::Subscriber sub_playerNumber = n.subscribe(\"/playerNumber\", 1, &playerNumber_cb);\n\n\tbool error = false;\n\n\t//tf::TransformBroadcaster transform;\n\t//transform.sendTransform(tf::StampedTransform(null, ros::Time::now(), ));\n\n\t// message declarations\n\tsensor_msgs::JointState joint_state;\n/*\n\t//init joint state\n\t//update joint_state\n\tjoint_state.header.stamp = ros::Time::now();\n\tjoint_state.name.resize(6);\n\tjoint_state.position.resize(6);\n\tjoint_state.name[0] =\"elbow_alpha_joint\";\n\tjoint_state.position[0] = M_PI/2;\n\tjoint_state.name[1] =\"shoulder_beta_joint\";\n\tjoint_state.position[1] = M_PI/2;\n\tjoint_state.name[2] =\"shoulder_theta_joint\";\n\tjoint_state.position[2] = M_PI/2;\n\tjoint_state.name[3] =\"shoulder_phi_joint\";\n\tjoint_state.position[3] = 3*M_PI/4;\n\tjoint_state.name[4] =\"elbow_twist_joint\";\n\tjoint_state.position[4] = M_PI/2;\n\tjoint_state.name[5] =\"wrist_joint\";\n\tjoint_state.position[5] = M_PI/2;\n\n\tprev_joint_state = joint_state;\n*/\n\t//uint32_t begin, end, loopTime;\n\n\twhile (ros::ok())\n\t{/*\n\t\tbegin = ros::WallTime::now().nsec;\n\t\terror = false;\n*/\n\n\n\t\t//grab tf skeleton joints\n\t\ttry\n\t\t{\n\t\t\tlistener_neck.lookupTransform(frame_str, \"/neck_\" + playerNb_str, ros::Time(0), transform_neck);\n\t\t}\n\t\tcatch (tf::TransformException ex)\n\t\t{\n\t\t\t//ROS_ERROR(\"%s\",ex.what());\n\t\t\terror = true;\n\t\t}\n\n\t\ttry\n\t\t{\n\t\t\tlistener_torso.lookupTransform(frame_str, \"/torso_\" + playerNb_str, ros::Time(0), transform_torso);\n\t\t}\n\t\tcatch (tf::TransformException ex)\n\t\t{\n\t\t\t//ROS_ERROR(\"%s\",ex.what());\n\t\t\terror = true;\n\t\t}\n\n\t\ttry\n\t\t{\n\t\t\tlistener_shoulder.lookupTransform(frame_str, \"/left_shoulder_\" + playerNb_str, ros::Time(0), transform_shoulder);\n\t\t}\n\t\tcatch (tf::TransformException ex)\n\t\t{\n\t\t\t//ROS_ERROR(\"%s\",ex.what());\n\t\t\terror = true;\n\t\t}\n\n\t\ttry\n\t\t{\n\t\t\tlistener_elbow.lookupTransform(frame_str, \"/left_elbow_\" + playerNb_str, ros::Time(0), transform_elbow);\n\t\t}\n\t\tcatch (tf::TransformException ex)\n\t\t{\n\t\t\t//ROS_ERROR(\"%s\",ex.what());\n\t\t\terror = true;\n\t\t}\n\n\t\ttry\n\t\t{\n\t\t\tlistener_hand.lookupTransform(frame_str, \"/left_hand_\" + playerNb_str, ros::Time(0), transform_hand);\n\t\t}\n\t\tcatch (tf::TransformException ex)\n\t\t{\n\t\t\t//ROS_ERROR(\"%s\",ex.what());\n\t\t\terror = true;\n\t\t}\n/*\n\t\t//get the left arm transform\n\t\ttry\n\t\t{\n\t\t\tlistener_leftShoulder.lookupTransform(frame_str, \"/right_shoulder_\" + playerNb_str, ros::Time(0), transform_leftShoulder);\n\t\t}\n\t\tcatch (tf::TransformException ex)\n\t\t{\n\t\t\t//ROS_ERROR(\"%s\",ex.what());\n\t\t\terror = true;\n\t\t}\n\n\t\ttry\n\t\t{\n\t\t\tlistener_leftElbow.lookupTransform(frame_str, \"/right_elbow_\" + playerNb_str, ros::Time(0), transform_leftElbow);\n\t\t}\n\t\tcatch (tf::TransformException ex)\n\t\t{\n\t\t\t//ROS_ERROR(\"%s\",ex.what());\n\t\t\terror = true;\n\t\t}\n\n\t\ttry\n\t\t{\n\t\t\tlistener_leftHand.lookupTransform(frame_str, \"/right_hand_\" + playerNb_str, ros::Time(0), transform_leftHand);\n\t\t}\n\t\tcatch (tf::TransformException ex)\n\t\t{\n\t\t\t//ROS_ERROR(\"%s\",ex.what());\n\t\t\terror = true;\n\t\t}\n*/\n\t\t//ROS_INFO(\"transform_han %f\", transform_hand.getOrigin().x());\n\n\t\t//update joint_state\n\t\tjoint_state.header.stamp = ros::Time::now();\n\t\tjoint_state.name.resize(4);//6\n\t\tjoint_state.position.resize(4);//6\n\t\tjoint_state.name[0] =\"elbow_alpha_joint\";\n\t\tjoint_state.position[0] = M_PI - calculateAlpha(transform_hand, transform_elbow, transform_shoulder);\n\t\tjoint_state.name[1] =\"shoulder_beta_joint\";\n\t\tjoint_state.position[1] = M_PI - calculateBeta(transform_elbow, transform_neck, transform_shoulder);\n\t\tjoint_state.name[2] =\"shoulder_theta_joint\";\n\t\tjoint_state.position[2] = calculateTheta(transform_elbow, transform_neck, transform_shoulder, transform_torso) - M_PI/2;\n\t\tjoint_state.name[3] =\"shoulder_phi_joint\";\n\t\tjoint_state.position[3] = calculatePhi(transform_hand, transform_neck, transform_shoulder, transform_elbow);\n\n\t\t/*\n\t\tjoint_state.name[4] =\"elbow_twist_joint\";\n\t\tjoint_state.position[4] = 2*calculatePhi(transform_leftHand, transform_neck, transform_leftShoulder, transform_leftElbow) - 3*M_PI/4;\n\t\tjoint_state.name[5] =\"wrist_joint\";\n\t\tjoint_state.position[5] = M_PI - calculateAlpha(transform_leftHand, transform_leftElbow, transform_leftShoulder);\n*/\n\t\t//test\n\t\tstd_msgs::Float32 test;\n\t\ttest.data = M_PI;//(float)transform_hand.getOrigin().x();\n\n\t\ttest_pub.publish(test);\n\n\t\t//send the joint state and transform\n\t\tjoint_pub.publish(joint_state);\n/*\n\t\t\tprev_joint_state = joint_state;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t//std::cerr << \"Error\" << std::endl;\n\t\t\tjoint_pub.publish(prev_joint_state);\n\t\t}\n*/\n\n\t\tros::spinOnce(); //reasign a new player if need\n\n\t\t// This will adjust as needed per iteration\n\t\tloop_rate.sleep();\n\n\t\t//if(error) ROS_INFO(\"Error !!!\");\n/*\n\t\tend = ros::WallTime::now().nsec;\n\t\tloopTime = end - begin;\n\t\tROS_INFO(\"loopTime =  %d\", loopTime);\n\t*/\n\t}\n\n\treturn 0;\n}\n\n", "meta": {"hexsha": "6db5d903f138ed4d0a824611c505d67576259a99", "size": 15208, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/arm_transform.cpp", "max_stars_repo_name": "TheRobotStudio/osa_control", "max_stars_repo_head_hexsha": "cab89793ae64b9c5b49c2b0b31a84fe2ec3b7f5c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/arm_transform.cpp", "max_issues_repo_name": "TheRobotStudio/osa_control", "max_issues_repo_head_hexsha": "cab89793ae64b9c5b49c2b0b31a84fe2ec3b7f5c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/arm_transform.cpp", "max_forks_repo_name": "TheRobotStudio/osa_control", "max_forks_repo_head_hexsha": "cab89793ae64b9c5b49c2b0b31a84fe2ec3b7f5c", "max_forks_repo_licenses": ["BSD-3-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.5989847716, "max_line_length": 262, "alphanum_fraction": 0.6949631773, "num_tokens": 4910, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390746, "lm_q2_score": 0.6442251201477015, "lm_q1q2_score": 0.4972409701306}}
{"text": "#ifndef STAN_MATH_PRIM_MAT_PROB_CATEGORICAL_LPMF_HPP\n#define STAN_MATH_PRIM_MAT_PROB_CATEGORICAL_LPMF_HPP\n\n#include <stan/math/prim/mat/err/check_simplex.hpp>\n#include <stan/math/prim/scal/err/check_bounded.hpp>\n#include <stan/math/prim/scal/fun/value_of.hpp>\n#include <stan/math/prim/mat/fun/sum.hpp>\n#include <stan/math/prim/mat/meta/index_type.hpp>\n#include <stan/math/prim/scal/fun/constants.hpp>\n#include <stan/math/prim/scal/meta/include_summand.hpp>\n#include <stan/math/prim/scal/meta/is_constant_struct.hpp>\n#include <boost/random/uniform_01.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <cmath>\n#include <vector>\n\nnamespace stan {\n  namespace math {\n\n    // Categorical(n|theta)  [0 < n <= N;   0 <= theta[n] <= 1;  SUM theta = 1]\n    template <bool propto,\n              typename T_prob>\n    typename boost::math::tools::promote_args<T_prob>::type\n    categorical_lpmf(int n,\n                    const Eigen::Matrix<T_prob, Eigen::Dynamic, 1>& theta) {\n      static const char* function(\"categorical_lpmf\");\n\n      using boost::math::tools::promote_args;\n      using std::log;\n\n      int lb = 1;\n\n      check_bounded(function, \"Number of categories\", n, lb, theta.size());\n      check_simplex(function, \"Probabilities parameter\", theta);\n\n      if (include_summand<propto, T_prob>::value)\n        return log(theta(n - 1));\n      return 0.0;\n    }\n\n    template <typename T_prob>\n    inline\n    typename boost::math::tools::promote_args<T_prob>::type\n    categorical_lpmf(const typename\n                    math::index_type<Eigen::Matrix<T_prob,\n                    Eigen::Dynamic, 1> >::type n,\n                    const Eigen::Matrix<T_prob, Eigen::Dynamic, 1>& theta) {\n      return categorical_lpmf<false>(n, theta);\n    }\n\n    template <bool propto,\n              typename T_prob>\n    typename boost::math::tools::promote_args<T_prob>::type\n    categorical_lpmf(const std::vector<int>& ns,\n                    const Eigen::Matrix<T_prob, Eigen::Dynamic, 1>& theta) {\n      static const char* function(\"categorical_lpmf\");\n\n      using boost::math::tools::promote_args;\n      using std::log;\n\n      int lb = 1;\n\n      for (size_t i = 0; i < ns.size(); ++i)\n        check_bounded(function, \"element of outcome array\", ns[i],\n                      lb, theta.size());\n\n      check_simplex(function, \"Probabilities parameter\", theta);\n\n      if (!include_summand<propto, T_prob>::value)\n        return 0.0;\n\n      if (ns.size() == 0)\n        return 0.0;\n\n      Eigen::Matrix<T_prob, Eigen::Dynamic, 1> log_theta(theta.size());\n      for (int i = 0; i < theta.size(); ++i)\n        log_theta(i) = log(theta(i));\n\n      Eigen::Matrix<typename boost::math::tools::promote_args<T_prob>::type,\n                    Eigen::Dynamic, 1> log_theta_ns(ns.size());\n      for (size_t i = 0; i < ns.size(); ++i)\n        log_theta_ns(i) = log_theta(ns[i] - 1);\n\n      return sum(log_theta_ns);\n    }\n\n    template <typename T_prob>\n    inline\n    typename boost::math::tools::promote_args<T_prob>::type\n    categorical_lpmf(const std::vector<int>& ns,\n                    const Eigen::Matrix<T_prob, Eigen::Dynamic, 1>& theta) {\n      return categorical_lpmf<false>(ns, theta);\n    }\n\n  }\n}\n#endif\n", "meta": {"hexsha": "bd8459f26fe4bdfebe8bb49b0e9e0f8bc7e2859a", "size": 3205, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/mat/prob/categorical_lpmf.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/prim/mat/prob/categorical_lpmf.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/prim/mat/prob/categorical_lpmf.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": 32.7040816327, "max_line_length": 79, "alphanum_fraction": 0.631825273, "num_tokens": 847, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435083355188, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.49724096634826276}}
{"text": "/** nonfinite_num_facet.cpp\n *\n * Copyright (c) 2011 Francois Mauger\n * Copyright (c) 2011 Paul A. Bristow\n *\n * Distributed under the Boost Software License, Version 1.0.\n * (See accompanying file LICENSE_1_0.txt\n * or copy at http://www.boost.org/LICENSE_1_0.txt)\n *\n * This simple program illustrates how to use the\n * `boost/math/nonfinite_num_facets.hpp' material from the original\n * Floating Point  Utilities contribution by Johan Rade.\n * Floating Point Utility library has been accepted into Boost,\n * but the utilities have been/will be incorporated into Boost.Math library.\n *\n\\file\n\n\\brief A fairly simple example of using non_finite_num facet for\nC99 standard output of infinity and NaN.\n\n\\detail  This program illustrates how to use the\n `boost/math/nonfinite_num_facets.hpp' material from the original\n  Floating Point  Utilities contribution by Johan Rade.\n  Floating Point Utility library has been accepted into Boost,\n  but the utilities have been/will be incorporated into Boost.Math library.\n\n  Based on an example from Francois Mauger.\n\n  Double and float variables are assigned ordinary finite values (pi),\n  and nonfinite like infinity and NaN.\n\n  These values are then output and read back in, and then redisplayed.\n\n*/\n\n#ifdef _MSC_VER\n#   pragma warning(disable : 4127) // conditional expression is constant.\n#endif\n\n#include <iostream>\n#include <iomanip>\nusing std::cout;\nusing std::endl;\n\n#include <limits> // numeric_limits\nusing std::numeric_limits;\n\n#include <boost/cstdint.hpp>\n\n#include <boost/math/special_functions/nonfinite_num_facets.hpp>\n\nstatic const char sep = ','; // Separator of bracketed float and double values.\n\n// Use max_digits10 (or equivalent) to obtain\n// all potentially significant decimal digits for the floating-point types.\n\n#ifdef BOOST_NO_CXX11_NUMERIC_LIMITS\n  std::streamsize  max_digits10_float = 2 + std::numeric_limits<float>::digits * 30103UL / 100000UL;\n  std::streamsize  max_digits10_double = 2 + std::numeric_limits<double>::digits * 30103UL / 100000UL;\n#else\n  // Can use new C++0X max_digits10 (the maximum potentially significant digits).\n  std::streamsize  max_digits10_float = std::numeric_limits<float>::max_digits10;\n  std::streamsize  max_digits10_double = std::numeric_limits<double>::max_digits10;\n#endif\n\n\n/* A class with a float and a double */\nstruct foo\n{\n  foo () : fvalue (3.1415927F), dvalue (3.1415926535897931)\n  {\n  }\n  // Set both the values to -infinity :\n  void minus_infinity ()\n  {\n    fvalue = -std::numeric_limits<float>::infinity ();\n    dvalue = -std::numeric_limits<double>::infinity ();\n    return;\n  }\n  // Set the values to +infinity :\n  void plus_infinity ()\n  {\n    fvalue = +std::numeric_limits<float>::infinity ();\n    dvalue = +std::numeric_limits<double>::infinity ();\n    return;\n  }\n  // Set the values to NaN :\n  void nan ()\n  {\n    fvalue = +std::numeric_limits<float>::quiet_NaN ();\n    dvalue = +std::numeric_limits<double>::quiet_NaN ();\n    return;\n  }\n  // Print a foo:\n  void print (std::ostream & a_out, const std::string & a_title)\n  {\n    if (a_title.empty ()) a_out << \"foo\";\n    else a_out << a_title;\n    a_out << \" : \" << std::endl;\n    a_out << \"|-- \" << \"fvalue = \";\n\n    a_out.precision (max_digits10_float);\n    a_out << fvalue << std::endl;\n    a_out << \"`-- \" << \"dvalue = \";\n    a_out.precision (max_digits10_double);\n    a_out << dvalue << std::endl;\n    return;\n  }\n\n  // I/O operators for a foo structure of a float and a double :\n  friend std::ostream & operator<< (std::ostream & a_out, const foo & a_foo);\n  friend std::istream & operator>> (std::istream & a_in, foo & a_foo);\n\n  // Attributes :\n  float  fvalue; // Single precision floating number.\n  double dvalue; // Double precision floating number.\n};\n\nstd::ostream & operator<< (std::ostream & a_out, const foo & a_foo)\n{ // Output bracketed FPs, for example \"(3.1415927,3.1415926535897931)\"\n  a_out.precision (max_digits10_float);\n  a_out << \"(\" << a_foo.fvalue << sep ;\n  a_out.precision (max_digits10_double);\n  a_out << a_foo.dvalue << \")\";\n  return a_out;\n}\n\nstd::istream & operator>> (std::istream & a_in, foo & a_foo)\n{ // Input bracketed floating-point values into a foo structure,\n  // for example from \"(3.1415927,3.1415926535897931)\"\n  char c = 0;\n  a_in.get (c);\n  if (c != '(')\n  {\n    std::cerr << \"ERROR: operator>> No ( \" << std::endl;\n    a_in.setstate(std::ios::failbit);\n    return a_in;\n  }\n  float f;\n  a_in >> std::ws >> f;\n  if (! a_in)\n  {\n    return a_in;\n  }\n  a_in >> std::ws;\n  a_in.get (c);\n  if (c != sep)\n  {\n    std::cerr << \"ERROR: operator>> c='\" << c << \"'\" << std::endl;\n    std::cerr << \"ERROR: operator>> No '\" << sep << \"'\" << std::endl;\n    a_in.setstate(std::ios::failbit);\n    return a_in;\n  }\n  double d;\n  a_in >> std::ws >> d;\n  if (! a_in)\n  {\n    return a_in;\n  }\n  a_in >> std::ws;\n  a_in.get (c);\n  if (c != ')')\n  {\n    std::cerr << \"ERROR: operator>> No ) \" << std::endl;\n    a_in.setstate(std::ios::failbit);\n    return a_in;\n  }\n  a_foo.fvalue = f;\n  a_foo.dvalue = d;\n  return a_in;\n} // std::istream & operator>> (std::istream & a_in, foo & a_foo)\n\nint main ()\n{\n  std::cout << \"nonfinite_num_facet simple example.\" << std::endl;\n\n   if((std::numeric_limits<double>::has_infinity == false) || (std::numeric_limits<double>::infinity() == 0))\n  {\n    std::cout << \"Infinity not supported on this platform.\" << std::endl;\n    return 0;\n  }\n\n  if((std::numeric_limits<double>::has_quiet_NaN == false) || (std::numeric_limits<double>::quiet_NaN() == 0))\n  {\n    std::cout << \"NaN not supported on this platform.\" << std::endl;\n    return 0;\n  }\n\n#ifdef BOOST_NO_CXX11_NUMERIC_LIMITS\n  cout << \"BOOST_NO_CXX11_NUMERIC_LIMITS is defined, so no max_digits10 available either:\"\n     \"\\n we'll have to calculate our own version.\" << endl;\n#endif\n  std::cout << \"std::numeric_limits<float>::max_digits10 is \" << max_digits10_float << endl;\n  std::cout << \"std::numeric_limits<double>::max_digits10 is \" << max_digits10_double << endl;\n\n   std::locale the_default_locale (std::locale::classic ());\n\n  {\n    std::cout << \"Write to a string buffer (using default locale) :\" << std::endl;\n    foo f0; // pi\n    foo f1; f1.minus_infinity ();\n    foo f2; f2.plus_infinity ();\n    foo f3; f3.nan ();\n\n    f0.print (std::cout, \"f0\"); // pi\n    f1.print (std::cout, \"f1\"); // +inf\n    f2.print (std::cout, \"f2\"); // -inf\n    f3.print (std::cout, \"f3\"); // NaN\n\n    std::ostringstream oss;\n    std::locale C99_out_locale (the_default_locale, new boost::math::nonfinite_num_put<char>);\n    oss.imbue (C99_out_locale);\n    oss.precision (15);\n    oss << f0 << f1 << f2 << f3;\n    std::cout << \"Output in C99 format is: \\\"\" << oss.str () << \"\\\"\" << std::endl;\n    std::cout << \"Output done.\" << std::endl;\n  }\n\n  {\n    std::string the_string = \"(3.1415927,3.1415926535897931)(-inf,-inf)(inf,inf)(nan,nan)\"; // C99 format\n    // Must have correct separator!\n    std::cout << \"Read C99 format from a string buffer containing \\\"\" << the_string << \"\\\"\"<< std::endl;\n\n    std::locale C99_in_locale (the_default_locale, new boost::math::nonfinite_num_get<char>);\n    std::istringstream iss (the_string);\n    iss.imbue (C99_in_locale);\n\n    foo f0, f1, f2, f3;\n    iss >> f0 >> f1 >> f2 >> f3;\n    if (! iss)\n    {\n       std::cerr << \"Input Format error !\" << std::endl;\n    }\n    else\n    {\n      std::cerr << \"Input OK.\" << std::endl;\n      cout << \"Display in default locale format \" << endl;\n      f0.print (std::cout, \"f0\");\n      f1.print (std::cout, \"f1\");\n      f2.print (std::cout, \"f2\");\n      f3.print (std::cout, \"f3\");\n    }\n    std::cout << \"Input done.\" << std::endl;\n  }\n\n  std::cout << \"End nonfinite_num_facet.cpp\" << std::endl;\n  return 0;\n} // int main()\n\n // end of test_nonfinite_num_facets.cpp\n\n/*\n\nOutput:\n\nnonfinite_num_facet simple example.\n  std::numeric_limits<float>::max_digits10 is 8\n  std::numeric_limits<double>::max_digits10 is 17\n  Write to a string buffer (using default locale) :\n  f0 :\n  |-- fvalue = 3.1415927\n  `-- dvalue = 3.1415926535897931\n  f1 :\n  |-- fvalue = -1.#INF\n  `-- dvalue = -1.#INF\n  f2 :\n  |-- fvalue = 1.#INF\n  `-- dvalue = 1.#INF\n  f3 :\n  |-- fvalue = 1.#QNAN\n  `-- dvalue = 1.#QNAN\n  Output in C99 format is: \"(3.1415927,3.1415926535897931)(-inf,-inf)(inf,inf)(nan,nan)\"\n  Output done.\n  Read C99 format from a string buffer containing \"(3.1415927,3.1415926535897931)(-inf,-inf)(inf,inf)(nan,nan)\"\n  Display in default locale format\n  f0 :\n  |-- fvalue = 3.1415927\n  `-- dvalue = 3.1415926535897931\n  f1 :\n  |-- fvalue = -1.#INF\n  `-- dvalue = -1.#INF\n  f2 :\n  |-- fvalue = 1.#INF\n  `-- dvalue = 1.#INF\n  f3 :\n  |-- fvalue = 1.#QNAN\n  `-- dvalue = 1.#QNAN\n  Input done.\n  End nonfinite_num_facet.cpp\n\n*/\n", "meta": {"hexsha": "a38d04528143a2d052093d469269534fb0e9141b", "size": 8680, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/libs/math/example/nonfinite_num_facet.cpp", "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/libs/math/example/nonfinite_num_facet.cpp", "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/libs/math/example/nonfinite_num_facet.cpp", "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": 29.7260273973, "max_line_length": 111, "alphanum_fraction": 0.6435483871, "num_tokens": 2585, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251064863698, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.49724095958619}}
{"text": "#define BOOST_TEST_MODULE pcraster mathx dir_conv\n#include <boost/test/unit_test.hpp>\n#include \"stddefx.h\"\n#include \"mathx.h\"\n\n\nBOOST_AUTO_TEST_CASE(scale_deg)\n{\n  BOOST_CHECK(ScaleDeg(45) == 45);\n  BOOST_CHECK(ScaleDeg(-300) == 60);\n\n  BOOST_CHECK(ScaleDeg(0) == 0);\n  BOOST_CHECK(ScaleDeg(-360) == 0);\n  BOOST_CHECK(ScaleDeg(360) == 0);\n\n  // sin bug in pcrcalc Mon Aug 14 10:14:28 CEST 2000:\n  BOOST_CHECK(ScaleDeg(-80640) == 0);\n}\n", "meta": {"hexsha": "24eabf93f7f474066a34b7bcecad6cb7a6cf3d52", "size": 435, "ext": "cc", "lang": "C++", "max_stars_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/mathx/dirconvtest.cc", "max_stars_repo_name": "quanpands/wflow", "max_stars_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/mathx/dirconvtest.cc", "max_issues_repo_name": "quanpands/wflow", "max_issues_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/mathx/dirconvtest.cc", "max_forks_repo_name": "quanpands/wflow", "max_forks_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.8947368421, "max_line_length": 54, "alphanum_fraction": 0.7011494253, "num_tokens": 144, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390746, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.49724094904177946}}
{"text": "// MIT License\n//\n// Copyright (c) 2020 Lennart Braun\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 \"tensor_op.h\"\n\n#include <boost/functional/hash.hpp>\n#include <cassert>\n\nnamespace MOTION::tensor {\n\nbool Conv2DOp::verify() const noexcept {\n  bool result = true;\n  result = result && (output_shape_ == compute_output_shape());\n  result = result && strides_[0] > 0 && strides_[1] > 0;\n  // maybe add more checks here\n  return result;\n}\n\nstd::array<std::size_t, 3> Conv2DOp::compute_output_shape() const noexcept {\n  const auto compute_output_dimension = [](auto input_size, auto kernel_size, auto padding_begin,\n                                           auto padding_end, auto stride) {\n    assert(stride != 0);\n    return (input_size - kernel_size + padding_begin + padding_end + stride) / stride;\n  };\n\n  std::array<std::size_t, 3> output_shape;\n  output_shape[0] = kernel_shape_[0];\n  output_shape[1] =\n      compute_output_dimension(input_shape_[1], kernel_shape_[2], pads_[0], pads_[2], strides_[0]);\n  output_shape[2] =\n      compute_output_dimension(input_shape_[2], kernel_shape_[3], pads_[1], pads_[3], strides_[1]);\n  return output_shape;\n}\n\nstd::size_t Conv2DOp::compute_output_size() const noexcept {\n  assert(verify());\n  auto output_shape = compute_output_shape();\n  return output_shape[0] * output_shape[1] * output_shape[2];\n}\n\nstd::size_t Conv2DOp::compute_input_size() const noexcept {\n  assert(verify());\n  return input_shape_[0] * input_shape_[1] * input_shape_[2];\n}\n\nstd::size_t Conv2DOp::compute_kernel_size() const noexcept {\n  assert(verify());\n  return kernel_shape_[0] * kernel_shape_[1] * kernel_shape_[2] * kernel_shape_[3];\n}\n\nstd::size_t Conv2DOp::compute_bias_size() const noexcept {\n  assert(verify());\n  return kernel_shape_[0];\n}\n\nstd::pair<std::size_t, std::size_t> Conv2DOp::compute_input_matrix_shape() const noexcept {\n  assert(verify());\n  std::size_t num_rows = kernel_shape_[1] * kernel_shape_[2] * kernel_shape_[3];\n  std::size_t num_columns = output_shape_[1] * output_shape_[2];\n  return {num_rows, num_columns};\n}\n\nstd::pair<std::size_t, std::size_t> Conv2DOp::compute_kernel_matrix_shape() const noexcept {\n  assert(verify());\n  std::size_t num_rows = kernel_shape_[0];\n  std::size_t num_columns = kernel_shape_[1] * kernel_shape_[2] * kernel_shape_[3];\n  return {num_rows, num_columns};\n}\n\nstd::pair<std::size_t, std::size_t> Conv2DOp::compute_output_matrix_shape() const noexcept {\n  assert(verify());\n  std::size_t num_rows = kernel_shape_[0];\n  std::size_t num_columns = output_shape_[1] * output_shape_[2];\n  return {num_rows, num_columns};\n}\n\nTensorDimensions Conv2DOp::get_input_tensor_dims() const noexcept {\n  assert(verify());\n  return {.batch_size_ = 1,\n          .num_channels_ = input_shape_[0],\n          .height_ = input_shape_[1],\n          .width_ = input_shape_[2]};\n}\n\nTensorDimensions Conv2DOp::get_kernel_tensor_dims() const noexcept {\n  assert(verify());\n  return {.batch_size_ = kernel_shape_[0],\n          .num_channels_ = kernel_shape_[1],\n          .height_ = kernel_shape_[2],\n          .width_ = kernel_shape_[3]};\n}\n\nTensorDimensions Conv2DOp::get_output_tensor_dims() const noexcept {\n  assert(verify());\n  return {.batch_size_ = 1,\n          .num_channels_ = output_shape_[0],\n          .height_ = output_shape_[1],\n          .width_ = output_shape_[2]};\n}\n\nbool Conv2DOp::operator==(const Conv2DOp& other) const noexcept {\n  assert(verify());\n  assert(other.verify());\n  bool result = true;\n  result = result && kernel_shape_ == other.kernel_shape_;\n  result = result && input_shape_ == other.input_shape_;\n  result = result && output_shape_ == other.output_shape_;\n  result = result && dilations_ == other.dilations_;\n  result = result && pads_ == other.pads_;\n  result = result && strides_ == other.strides_;\n  return result;\n}\n\nbool GemmOp::verify() const noexcept {\n  bool result = true;\n  std::size_t m = input_A_shape_[0];\n  std::size_t k = input_A_shape_[1];\n  if (transA_) {\n    std::swap(m, k);\n  }\n  std::size_t n = input_B_shape_[transB_ ? 0 : 1];\n  result = result && (k == input_B_shape_[transB_ ? 1 : 0]);\n  result = result && (m == output_shape_[0]);\n  result = result && (n == output_shape_[1]);\n  // maybe add more checks here\n  return result;\n}\n\nstd::array<std::size_t, 2> GemmOp::compute_output_shape() const noexcept {\n  return {input_A_shape_[transA_ ? 1 : 0], input_B_shape_[transB_ ? 0 : 1]};\n}\n\nstd::size_t GemmOp::compute_output_size() const noexcept {\n  assert(verify());\n  auto output_shape = compute_output_shape();\n  return output_shape[0] * output_shape[1];\n}\n\nstd::size_t GemmOp::compute_input_A_size() const noexcept {\n  assert(verify());\n  return input_A_shape_[0] * input_A_shape_[1];\n}\n\nstd::size_t GemmOp::compute_input_B_size() const noexcept {\n  assert(verify());\n  return input_B_shape_[0] * input_B_shape_[1];\n}\n\nTensorDimensions GemmOp::get_input_A_tensor_dims() const noexcept {\n  assert(verify());\n  return {.batch_size_ = 1,\n          .num_channels_ = 1,\n          .height_ = input_A_shape_[0],\n          .width_ = input_A_shape_[1]};\n}\n\nTensorDimensions GemmOp::get_input_B_tensor_dims() const noexcept {\n  assert(verify());\n  return {.batch_size_ = 1,\n          .num_channels_ = 1,\n          .height_ = input_B_shape_[0],\n          .width_ = input_B_shape_[1]};\n}\n\nTensorDimensions GemmOp::get_output_tensor_dims() const noexcept {\n  assert(verify());\n  return {.batch_size_ = 1,\n          .num_channels_ = 1,\n          .height_ = output_shape_[0],\n          .width_ = output_shape_[1]};\n}\n\nbool GemmOp::operator==(const GemmOp& other) const noexcept {\n  assert(verify());\n  assert(other.verify());\n  bool result = true;\n  result = result && input_A_shape_ == other.input_A_shape_;\n  result = result && input_B_shape_ == other.input_B_shape_;\n  result = result && output_shape_ == other.output_shape_;\n  return result;\n}\n\nTensorDimensions flatten(const TensorDimensions& dims, std::size_t axis) {\n  std::size_t height = 1;\n  std::size_t width = 1;\n  switch (axis) {\n    case 0:\n      width *= dims.batch_size_;\n      [[fallthrough]];\n    case 1:\n      width *= dims.num_channels_;\n      [[fallthrough]];\n    case 2:\n      width *= dims.height_;\n      [[fallthrough]];\n    case 3:\n      width *= dims.width_;\n  }\n  switch (axis) {\n    case 4:\n      height *= dims.width_;\n      [[fallthrough]];\n    case 3:\n      height *= dims.height_;\n      [[fallthrough]];\n    case 2:\n      height *= dims.num_channels_;\n      [[fallthrough]];\n    case 1:\n      height *= dims.batch_size_;\n  }\n  return {.batch_size_ = 1, .num_channels_ = 1, .height_ = height, .width_ = width};\n}\n\nbool MaxPoolOp::verify() const noexcept {\n  bool result = true;\n  result = result && (output_shape_ == compute_output_shape());\n  result = result && strides_[0] > 0 && strides_[1] > 0;\n  result = kernel_shape_[0] <= input_shape_[1] && kernel_shape_[1] <= input_shape_[2];\n  // maybe add more checks here\n  return result;\n}\n\nstd::array<std::size_t, 3> MaxPoolOp::compute_output_shape() const noexcept {\n  const auto compute_output_dimension = [](auto input_size, auto kernel_size, auto stride) {\n    assert(stride != 0);\n    return (input_size - kernel_size + stride) / stride;\n  };\n\n  std::array<std::size_t, 3> output_shape;\n  output_shape[0] = input_shape_[0];\n  output_shape[1] =\n      compute_output_dimension(input_shape_[1], kernel_shape_[2], strides_[0]);\n  output_shape[2] =\n      compute_output_dimension(input_shape_[2], kernel_shape_[3], strides_[1]);\n  return output_shape;\n}\n\nstd::size_t MaxPoolOp::compute_kernel_size() const noexcept {\n  assert(verify());\n  return kernel_shape_[0] * kernel_shape_[1];\n}\n\nstd::size_t MaxPoolOp::compute_input_size() const noexcept {\n  assert(verify());\n  return input_shape_[0] * input_shape_[1] * input_shape_[2];\n}\n\nstd::size_t MaxPoolOp::compute_output_size() const noexcept {\n  assert(verify());\n  return output_shape_[0] * output_shape_[1] * output_shape_[2];\n}\n\nTensorDimensions MaxPoolOp::get_input_tensor_dims() const noexcept {\n  assert(verify());\n  return {.batch_size_ = 1,\n          .num_channels_ = input_shape_[0],\n          .height_ = input_shape_[1],\n          .width_ = input_shape_[2]};\n}\n\nTensorDimensions MaxPoolOp::get_output_tensor_dims() const noexcept {\n  assert(verify());\n  return {.batch_size_ = 1,\n          .num_channels_ = output_shape_[0],\n          .height_ = output_shape_[1],\n          .width_ = output_shape_[2]};\n}\n\n}  // namespace MOTION::tensor\n\nnamespace std {\n\nstd::size_t std::hash<MOTION::tensor::Conv2DOp>::operator()(\n    const MOTION::tensor::Conv2DOp& op) const noexcept {\n  std::size_t seed = 0;\n  boost::hash_combine(seed,\n                      boost::hash_range(std::begin(op.kernel_shape_), std::end(op.kernel_shape_)));\n  boost::hash_combine(seed,\n                      boost::hash_range(std::begin(op.input_shape_), std::end(op.input_shape_)));\n  boost::hash_combine(seed, boost::hash_range(std::begin(op.dilations_), std::end(op.dilations_)));\n  boost::hash_combine(seed, boost::hash_range(std::begin(op.pads_), std::end(op.pads_)));\n  boost::hash_combine(seed, boost::hash_range(std::begin(op.strides_), std::end(op.strides_)));\n  return seed;\n}\n\nstd::size_t std::hash<MOTION::tensor::GemmOp>::operator()(\n    const MOTION::tensor::GemmOp& op) const noexcept {\n  std::size_t seed = 0;\n  boost::hash_combine(\n      seed, boost::hash_range(std::begin(op.input_A_shape_), std::end(op.input_A_shape_)));\n  boost::hash_combine(\n      seed, boost::hash_range(std::begin(op.input_B_shape_), std::end(op.input_B_shape_)));\n  return seed;\n}\n\n}  // namespace std\n", "meta": {"hexsha": "114dc794caef2757764992ef7f2f153ebf2173e7", "size": 10587, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/motioncore/tensor/tensor_op.cpp", "max_stars_repo_name": "Udbhavbisarya23/MOTION2NX", "max_stars_repo_head_hexsha": "eb26f639d8c1729cebfa85dd3bf41b770cebe92b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2021-11-05T00:39:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-26T16:42:55.000Z", "max_issues_repo_path": "src/motioncore/tensor/tensor_op.cpp", "max_issues_repo_name": "Udbhavbisarya23/MOTION2NX", "max_issues_repo_head_hexsha": "eb26f639d8c1729cebfa85dd3bf41b770cebe92b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2021-11-07T06:53:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T11:46:40.000Z", "max_forks_repo_path": "src/motioncore/tensor/tensor_op.cpp", "max_forks_repo_name": "Udbhavbisarya23/MOTION2NX", "max_forks_repo_head_hexsha": "eb26f639d8c1729cebfa85dd3bf41b770cebe92b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2021-11-04T12:01:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T12:15:23.000Z", "avg_line_length": 33.3974763407, "max_line_length": 99, "alphanum_fraction": 0.6865967696, "num_tokens": 2787, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.6442250996557036, "lm_q1q2_score": 0.4972409475519118}}
{"text": "/*\n * ex5.cpp\n *\n * \t\\brief     5. und 7. Aufgabe\n *  \\details   Liesst eine .gph Datei ein und berechnet den laengsten kuerzesten pfad von jeder Ecke zum Root des Graphen.\n *  \\author    Christopher Wyczisk\n *  \\date      20.07.2017\n */\n\n#include <fstream>\n#include <iostream>\n#include <vector>\n#include <string>\n#include <sstream>\n#include \"dijkstra.h\"\n\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <boost/graph/named_function_params.hpp>\n#include <boost/timer/timer.hpp>\n\nusing namespace std;\nusing namespace boost::timer;\n\n// helper\nvector<pair<int, int>> kanten;\nvector<int> gewichte;\nunsigned int anzahlEckenGlobal;\n\n/**\n *\\typedef Adjancen des Graphen\n */\ntypedef boost::adjacency_list<boost::listS, boost::vecS,\n\tboost::undirectedS, boost::no_property,\n\tboost::property<boost::edge_weight_t, int>> graph;\n\n/**\n * \\typedef Die Informationen ueber die Ecken des Graphen\n */\ntypedef boost::graph_traits <graph>::vertex_descriptor eckenDto;\n\n/**\n * Einlesen der Graph Datei und Fehlerbehandlung.\n * \n * \\param argc\n * \\param argv\n * \\param infile input Graph-File\n */\nbool graphEinlesen(int argc, char** argv, ifstream& file) {\n\tif(argc <= 1) {\n\t\tcout << \"Sie haben keinen Pfad zu einer .gph Datei angegeben.\" << endl;\n\t\treturn false;\n\t} else {\n\t\tfile.open(argv[1], ios::in);\n\t}\n\n\tif (!file) {\n\t\tcout << \"Die von Ihnen angegebene Datei konnte nicht geoeffnet werden.\" << endl;\n\t\treturn false;\n\t}\n\t\n\treturn true;\n}\n\n/**\n * Konsolen-Ausgabe der Anzahl an Ecken und des Gewichts.\n * \n * \\param anzahlEcken\n * \\param laegsterKuerzesterPfadGewicht\n */\nvoid ergebnisAusgabe(int anzahlEcken, int laegsterKuerzesterPfadGewicht) {\n\tcout << \"RESULT VERTEX \" << anzahlEcken << endl;\n\tcout << \"RESULT DIST \" << laegsterKuerzesterPfadGewicht << endl;\n}\n\n/**\n * Erstellt den Graphen.\n * \n * \\param file\n */\nbool graphErstellen(ifstream& file) {\n\tstringstream str;\n\tstring zeile;\n\tint anzahlKanten;\n\tint start;\n\tint end;\n\tint gewicht;\n\n\tif (getline(file, zeile)) {\n\t\tstr.str(zeile);\n\t\tstr >> anzahlEckenGlobal >> anzahlKanten;\n\t\tanzahlEckenGlobal++;\n\t} else {\n\t\tcerr << \"Das .gph File ist leer.\" << endl;\n\t\treturn false;\n\t}\n\n\twhile (getline(file, zeile)) {\n\t\tstr.clear();\n\t\tstr.str(zeile);\n\t\tstr >> start >> end >> gewicht;\n\t\tkanten.push_back(make_pair(start, end));\n\t\tgewichte.push_back(gewicht);\n\t}\n\t\n\treturn true;\n}\n\n/**\n * Berechnet das Gewicht des longest-shortest Pfad.\n * \n * \\param graph der graph\n * \\param anzahlEcken\n * \\param laengsterKuerzesterPfadGewicht\n */\nvoid berechneLongesteShortesWeigth(graph graph, int& anzahlEcken, int& laegsterKuerzesterPfadGewicht) {\n\tvector<eckenDto> pfadRichtungen(anzahlEckenGlobal);\n\tvector<int> gewichteList(anzahlEckenGlobal);\n\n\tboost::dijkstra_shortest_paths(\n\t\tgraph, 1,\n\t\tboost::predecessor_map(\tboost::make_iterator_property_map(pfadRichtungen.begin(), get(boost::vertex_index, graph)))\n\t\t\t.distance_map(\n\t\t\t\t\tboost::make_iterator_property_map(gewichteList.begin(), get(boost::vertex_index, graph\n\t\t\t\t\t))));\n\n\t// berechnet das Gewicht\n\tfor(int i = 1; i < anzahlEckenGlobal; i++) {\n\t\tif (gewichteList[i + 1] > laegsterKuerzesterPfadGewicht) {\n\t\t\tlaegsterKuerzesterPfadGewicht = gewichteList[i + 1];\n\t\t\tanzahlEcken = i + 1;\n\t\t}\n\t}\n}\n\nstring konsolenabfrageWelcheMethode() {\n\tstring eingabe = \"\";\n\twhile(eingabe.compare(\"a\") && eingabe.compare(\"b\")) {\n\t\tcout << \"Geben Sie ein, welcher Algorithmus verwendet werden soll (a=Boots, b=eigene Impelementierung):\" << endl;\n\t\tcin >> eingabe;\n\t}\n\treturn eingabe;\n}\n\n/**\n * Main.\n */\nint main(int argc, char* argv[]) {\n\tifstream file;\n\tbool fileEingelesen = graphEinlesen(argc, argv, file);\n\t\n\tstring eingabe = konsolenabfrageWelcheMethode();\n\t\n\tboost::timer::cpu_timer t;\n\tif(fileEingelesen) {\n\t\t//erstelle den Graph\n\t\tbool erstellt = graphErstellen(file);\n\t\tif(erstellt && !eingabe.compare(\"a\")) {\n\t\t\tgraph graph{kanten.begin(), kanten.end(), gewichte.begin(), anzahlEckenGlobal};\n\t\t\n\t\t\t// berechnen des gewichts des longesten shortesten pfad\n\t\t\tint laegsterKuerzesterPfadGewicht = -1;\n\t\t\tint anzahlEcken = -1;\n\t\t\tberechneLongesteShortesWeigth(graph, anzahlEcken, laegsterKuerzesterPfadGewicht);\n\t\t\t\n\t\t\tergebnisAusgabe(anzahlEcken, laegsterKuerzesterPfadGewicht);\n\t\t}\n\t\telse if(erstellt) {\n\t\t\tvector<int> mapGewichte(anzahlEckenGlobal);\n\t    \tdijkstra dijkstra(gewichte, kanten, anzahlEckenGlobal);\n\t\t\tmapGewichte = dijkstra.berechneKuerzestenPfad(1);\n\t\t\t\n\t\t\t// berechnen des gewichts des longesten shortesten pfad\n\t\t\tint laegsterKuerzesterPfadGewicht = -1;\n\t\t\tint anzahlEcken = -1;\n\t\t\tint absGewichte;\n\t\t\tfor(unsigned int i = 2; i < anzahlEckenGlobal; i++) {\n\t\t\t\tabsGewichte = mapGewichte[i];\n\t\t\t\tif (absGewichte > laegsterKuerzesterPfadGewicht) {\n\t\t\t\t\tlaegsterKuerzesterPfadGewicht = absGewichte;\n\t\t\t\t\tanzahlEcken = i;\n\t\t\t\t}\n\t\t\t}\n\t\t\n\t\t\tergebnisAusgabe(anzahlEcken, laegsterKuerzesterPfadGewicht);\n\t\t}\n\t}\n\t\n\tboost::timer::cpu_times zeit = t.elapsed();\n\tstd::cout << \"WALL-CLOCK \" << zeit.wall / 1e9 << \"s\" << std::endl;\n\tstd::cout << \"USER TIME \" << zeit.user / 1e9 << \"s\" << std::endl;\n\treturn 0;\n}\n\n\n\n\n", "meta": {"hexsha": "661f59a792e8ce8b96e5d462a7114effc4acc9ae", "size": 5045, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "christopher_wyczisk/ex5/ex5.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": "christopher_wyczisk/ex5/ex5.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": "christopher_wyczisk/ex5/ex5.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": 25.4797979798, "max_line_length": 122, "alphanum_fraction": 0.703666997, "num_tokens": 1596, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768249, "lm_q2_score": 0.685949467848392, "lm_q1q2_score": 0.4972243802026099}}
{"text": "#define BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n#include \"../jngen.h\"\n\nBOOST_AUTO_TEST_SUITE(geometry)\n\nBOOST_AUTO_TEST_CASE(comparators) {\n    using namespace jngen;\n\n    BOOST_CHECK(lt(0.0, 1e-5));\n    BOOST_CHECK(lt((long double)0.0, 1e-5));\n    BOOST_CHECK(lt(0, 1e-5));\n    BOOST_CHECK(!eq(0, 1e-5));\n    BOOST_CHECK(eq(1 + 1e-10, 1 - 1e-10));\n}\n\nBOOST_AUTO_TEST_CASE(points_generation) {\n    auto a = rnda.randomfAll([]() { return rndg.point(3); });\n    BOOST_TEST(a.size() == 16);\n\n    auto b = rnda.randomfAll([]() { return rndg.point(2, 3); });\n    BOOST_TEST(b.size() == 4);\n\n    auto c = rnda.randomf(100, []() { return rndg.pointf(1); });\n    BOOST_TEST(c.size() == 100);\n\n    auto d = rnda.randomfAll([]() { return rndg.point(-2, 2); });\n    BOOST_TEST(d.size() == 25);\n}\n\nBOOST_AUTO_TEST_CASE(polygon) {\n    rnd.seed(123);\n    auto p = rndg.convexPolygon(10, 100);\n    // TODO: check that it is convex\n    BOOST_TEST(p.size() == 10);\n}\n\nBOOST_AUTO_TEST_CASE(points_in_general_position) {\n    rnd.seed(123);\n\n    int n = 5;\n    for (int test = 0; test < 10; ++test) {\n        n += 5;\n        auto pts = rndg.pointsInGeneralPosition(n, n);\n        for (int i = 0; i < n; ++i) {\n            for (int j = 0; j < i; ++j) {\n                for (int k = 0; k < j; ++k) {\n                    BOOST_CHECK((pts[i] - pts[j]) % (pts[i] - pts[k]) != 0);\n                }\n            }\n        }\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "617b925afa512dabe5f87e3714c5a14482b09e33", "size": 1450, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/geometry.cpp", "max_stars_repo_name": "landcold7/jngen", "max_stars_repo_head_hexsha": "c7cfb26cd21009efbb736a75147da550c699b545", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 197.0, "max_stars_repo_stars_event_min_datetime": "2017-04-07T20:57:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T18:06:36.000Z", "max_issues_repo_path": "tests/geometry.cpp", "max_issues_repo_name": "zekiriabd/jngen", "max_issues_repo_head_hexsha": "ca646e2f4df9b63c14380157d3911a0182149f94", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2017-07-14T01:42:44.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-31T11:25:40.000Z", "max_forks_repo_path": "tests/geometry.cpp", "max_forks_repo_name": "zekiriabd/jngen", "max_forks_repo_head_hexsha": "ca646e2f4df9b63c14380157d3911a0182149f94", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 29.0, "max_forks_repo_forks_event_min_datetime": "2017-07-05T21:31:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-04T09:36:51.000Z", "avg_line_length": 25.8928571429, "max_line_length": 76, "alphanum_fraction": 0.555862069, "num_tokens": 467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702880639791, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.497224379049118}}
{"text": "#pragma once\n\n#include <boost/random/discrete_distribution.hpp>\n\nnamespace calotypes\n{\n\n/*! \\brief Weighted sampling with replacement. */\ntemplate <class Engine>\nclass NaiveWeightedSampling\n{\npublic:\n\t\n\tNaiveWeightedSampling() {}\n\t\n\tstatic void Sample( const std::vector<double>& weights, unsigned int numDraws,\n\t\t\t\t\t\tstd::vector<unsigned int>& inds, Engine& engine )\n\t{\n\t\tinds.resize( numDraws );\n\t\tboost::random::discrete_distribution<> dist( weights );\n\t\tfor( unsigned int i = 0; i < numDraws; i++ )\n\t\t{\n\t\t\tinds[i] = dist( engine );\n\t\t}\n\t}\n};\n\ntemplate <class Engine>\nclass LowVarianceWeightedSampling\n{\npublic:\n\t\n\tLowVarianceWeightedSampling() {}\n\t\n\tstatic void Sample( const std::vector<double>& weights, unsigned int numDraws,\n\t\t\t\t\t\tstd::vector<unsigned int>& inds, Engine& engine )\n\t{\n\t\tinds.resize( numDraws );\n\t\tinds.clear();\n\t\t\n\t\tdouble totalWeight = 0;\n\t\tfor( unsigned int i = 0; i < weights.size(); i++ ) { totalWeight += weights[i]; }\n\t\t\n\t\tdouble stride = totalWeight/( numDraws + 1 );\n\t\t\n\t\tboost::random::uniform_01<> dist;\n\t\tdouble currentPoint = stride*dist( engine );\n\t\t\n\t\tdouble accumulatedWeights = weights[0];\n\t\t\n\t\tunsigned int ind = 0;\n\t\twhile( inds.size() < numDraws )\n\t\t{\n\t\t\tif( accumulatedWeights >= currentPoint )\n\t\t\t{\n\t\t\t\tinds.push_back( ind );\n\t\t\t\tcurrentPoint += stride;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t// Sometimes numerical precision errors cause the last element to not get added\n\t\t\t\tif( ind == weights.size()-1 ) { \n\t\t\t\t\tinds.push_back( ind );\n\t\t\t\t\tbreak; \n\t\t\t\t}\n\t\t\t\tind++;\n\t\t\t\taccumulatedWeights += weights[ind];\n\t\t\t}\n\t\t}\n\t}\n};\n\t\n} // end namespace calotypes\n", "meta": {"hexsha": "56d6fa9c16e8dbfc211528b117b79f2d3263f242", "size": 1582, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/calotypes/WeightedSamplers.hpp", "max_stars_repo_name": "Humhu/calotypes", "max_stars_repo_head_hexsha": "a05a809b3b27983332c24d8fb04cb71f47e96763", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-18T14:59:39.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-18T14:59:39.000Z", "max_issues_repo_path": "include/calotypes/WeightedSamplers.hpp", "max_issues_repo_name": "Humhu/calotypes", "max_issues_repo_head_hexsha": "a05a809b3b27983332c24d8fb04cb71f47e96763", "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/calotypes/WeightedSamplers.hpp", "max_forks_repo_name": "Humhu/calotypes", "max_forks_repo_head_hexsha": "a05a809b3b27983332c24d8fb04cb71f47e96763", "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": 21.3783783784, "max_line_length": 83, "alphanum_fraction": 0.6554993679, "num_tokens": 433, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.49722437554887045}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2015 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//==================================================================================================\n#ifndef BOOST_SIMD_IEEE_HPP_INCLUDED\n#define BOOST_SIMD_IEEE_HPP_INCLUDED\n\nnamespace boost { namespace simd\n{\n  /*!\n    @ingroup group-functions\n    @defgroup group-ieee Ieee functions\n\n      Those functions provides scalar and SIMD algorithms for inspecting, generating or\n      decomposing IEEE 754 floating point numbers. Operations like exponent and mantissa\n      extraction, floating point modulo, IEEE bit patterns manipulation and magnitude comparison\n      are provided.\n\n  **/\n\n  /*!\n    @ingroup group-callable\n    @defgroup group-callable-ieee Ieee Callable Objects\n    Callable objects version of @ref group-ieee\n\n    Their specific semantic limitations are similar to those of their function\n    equivalents as described in the @ref group-ieee section.\n  **/\n} }\n\n#include <boost/simd/function/bitfloating.hpp>\n#include <boost/simd/function/bitinteger.hpp>\n#include <boost/simd/function/bitofsign.hpp>\n#include <boost/simd/function/copysign.hpp>\n#include <boost/simd/function/eps.hpp>\n#include <boost/simd/function/exponentbits.hpp>\n#include <boost/simd/function/exponent.hpp>\n#include <boost/simd/function/fmax.hpp>\n#include <boost/simd/function/fmin.hpp>\n#include <boost/simd/function/fpclassify.hpp>\n#include <boost/simd/function/frac.hpp>\n#include <boost/simd/function/frexp.hpp>\n#include <boost/simd/function/ilogb.hpp>\n#include <boost/simd/function/ldexp.hpp>\n#include <boost/simd/function/mantissa.hpp>\n#include <boost/simd/function/maxmag.hpp>\n#include <boost/simd/function/maxnum.hpp>\n#include <boost/simd/function/maxnummag.hpp>\n#include <boost/simd/function/minmag.hpp>\n#include <boost/simd/function/minnum.hpp>\n#include <boost/simd/function/minnummag.hpp>\n#include <boost/simd/function/modf.hpp>\n#include <boost/simd/function/negate.hpp>\n#include <boost/simd/function/negatenz.hpp>\n#include <boost/simd/function/nextafter.hpp>\n#include <boost/simd/function/next.hpp>\n#include <boost/simd/function/nextpow2.hpp>\n#include <boost/simd/function/predecessor.hpp>\n#include <boost/simd/function/prev.hpp>\n#include <boost/simd/function/safe_max.hpp>\n#include <boost/simd/function/safe_min.hpp>\n#include <boost/simd/function/saturate.hpp>\n#include <boost/simd/function/sbits.hpp>\n#include <boost/simd/function/sign.hpp>\n#include <boost/simd/function/signnz.hpp>\n#include <boost/simd/function/splat.hpp>\n#include <boost/simd/function/successor.hpp>\n#include <boost/simd/function/ulpdist.hpp>\n#include <boost/simd/function/ulp.hpp>\n\n#endif\n", "meta": {"hexsha": "211e77ae0dff5506258c49a9f839e0b02c5f5be8", "size": 2849, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/ieee.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/ieee.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/ieee.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": 36.0632911392, "max_line_length": 100, "alphanum_fraction": 0.7184977185, "num_tokens": 629, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702642896702, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.4972243627411437}}
{"text": "#include <Eigen/Dense>\n#include \"DepthCamera.h\"\n#include \"PointCloud.h\"\n#include \"PassThroughFilter.h\"\n#include \"RadiusOutlierFilter.h\"\n#include \"PointCloudRecorder.h\"\n#include \"PointCloudInterface.h\"\n#include \"Transform.h\"\n\nusing namespace std;\n\nint main()\n{\n\n\t//! Init Recorder\n\tPointCloudRecorder pclRecorder;\n\t//! Set the fileName\n\tpclRecorder.setFileName(\"cloud.txt\");\n\n\t//! Init camera\n\tDepthCamera camera1, camera2;\n\t//! Set fileNames\n\tcamera1.setfileName(\"camera1.txt\");\n\tcamera2.setfileName(\"camera2.txt\");\n\n\t//! Init RadiusFilter\n\tRadiusOutlierFilter rof;\n\t//! Set the radius\n\trof.setRadius(25.0);\n\n\t//! Init ConstraitFilter\n\tPassThroughFilter filter1, filter2;\n\t//! Set upper lower boundaries for Camera1\n\tfilter1.setlowerLimitX(0.0);\n\tfilter1.setupperLimitX(400.0);\n\tfilter1.setlowerLimitY(0.0);\n\tfilter1.setupperLimitY(400.0);\n\tfilter1.setlowerLimitZ(-45.0);\n\tfilter1.setupperLimitZ(45.0);\n\t\n\t//! Set upper lower boundaries for Camera2\n\tfilter2.setlowerLimitX(0.0);\n\tfilter2.setupperLimitX(500.0);\n\tfilter2.setlowerLimitY(0.0);\n\tfilter2.setupperLimitY(500.0);\n\tfilter2.setlowerLimitZ(-45.0);\n\tfilter2.setupperLimitZ(45.0);\n\n\t//! Init FilterPipe\n\tFilterPipe fp1, fp2;\n\t//! Add filters\n\tfp1.addFilter(&rof);\n\tfp1.addFilter(&filter1);\n\n\t//! Add filters\n\tfp2.addFilter(&rof);\n\tfp2.addFilter(&filter2);\n\n\t//! Assign filters to DepthCameras\n\tcamera1.setFilterPipe(&fp1);\n\tcamera2.setFilterPipe(&fp2);\n\n\t//! Init Transform\n\tTransform tr1, tr2;\n\n\t//! Declare the angles and coordinates for translation\n\tEigen::Vector3d angles1(0, 0, -90);\n\tEigen::Vector3d angles2(0, 0, 90);\n\tEigen::Vector3d trans1(100, 500, 50);\n\tEigen::Vector3d trans2(550, 150, 50);\n\n\t//! Set data for Camera1\n\ttr1.setRotation(angles1);\n\ttr1.setTranslation(trans1);\n\t//! Initialize the transform matrix\n\ttr1.initialize();\n\n\t//! Set data for Camera2\n\ttr2.setRotation(angles2);\n\ttr2.setTranslation(trans2);\n\t//! Initialize the transform matrix\n\ttr2.initialize();\n\n\t//! Assign transform object to DepthCameras\n\tcamera1.setTransform(&tr1);\n\tcamera2.setTransform(&tr2);\n\n\t//! Init PointCloudInterfase\n\tPointCloudInterface pci1;\n\t//! Add generators\n\tpci1.addGenerator(&camera1);\n\tpci1.addGenerator(&camera2);\n\t//! Set recorder\n\tpci1.setRecorder(&pclRecorder);\n\n\t//! Generate result\n\tpci1.generate();\n\n\t//! Record result using given recorder\n\tpci1.record();\n\n\t//! EXIT\n\treturn 0;\n}", "meta": {"hexsha": "9449989c7041422ad04b4c9f50451534e0eec991", "size": 2349, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/App.cpp", "max_stars_repo_name": "mrfade/oop-project", "max_stars_repo_head_hexsha": "70af96884cd9c4990f833745b277c61c85b4ccc9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/App.cpp", "max_issues_repo_name": "mrfade/oop-project", "max_issues_repo_head_hexsha": "70af96884cd9c4990f833745b277c61c85b4ccc9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/App.cpp", "max_forks_repo_name": "mrfade/oop-project", "max_forks_repo_head_hexsha": "70af96884cd9c4990f833745b277c61c85b4ccc9", "max_forks_repo_licenses": ["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.5865384615, "max_line_length": 55, "alphanum_fraction": 0.7339293316, "num_tokens": 671, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.49722436158765193}}
{"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 * @file\n * @ingroup tests\n * @brief  Test for the PrecondType::HB preconditioner with simple heat transfer equation.\n * \n * Testprogram for Kaskade: tests wether the error between calculated and exact solution behaves as expected. \n * This test was built by changing the stationary heat transfer example. \n * \n * Variational functional, boundary conditions and f are adapted in hbPrec.hh. \n * Only uses ansatz functions of order 1.\n */\n\n#include <iostream>\n\n#include <boost/timer/timer.hpp>\n\n#include \"dune/grid/config.h\"\n#include \"dune/grid/uggrid.hh\"\n\n#include \"fem/assemble.hh\"\n#include \"fem/hierarchicErrorEstimator.hh\"\n#include \"fem/lagrangespace.hh\"\n//#include \"fem/hierarchicspace.hh\"\n#include \"fem/norms.hh\"\n#include \"linalg/direct.hh\"\n#include \"linalg/jacobiPreconditioner.hh\"\n#include \"linalg/cg.hh\"\n#include \"utilities/enums.hh\"\n#include \"utilities/kaskopt.hh\"\n#include \"mg/hb.hh\"\n\n#include \"utilities/kaskopt.hh\"\n\nusing namespace Kaskade;\n#include \"hbPrec.hh\"\n\n/**\n * @brief  This represents the known exact solution. \n * It is \\f$ u = \\cos (2 \\pi x) + \\exp (4(y-0.5)^2) \\f$.\n */\nstruct HBPrecSolution\n{\n   using Scalar = double;\n   static int const components = 1;\n   using ValueType = Dune::FieldVector<Scalar,components>;\n\n   template <class Cell> int order(Cell const&) const { return std::numeric_limits<int>::max(); }\n\n   template <class Cell>\n   ValueType value(Cell const& cell,Dune::FieldVector<typename Cell::Geometry::ctype,Cell::dimension> const& localCoordinate) const\n   {\n     Dune::FieldVector<typename Cell::Geometry::ctype,Cell::Geometry::coorddimension> x = cell.geometry().global(localCoordinate);\n     return std::cos(2*PI*x[0]) + std::exp(4*(x[1]-0.5)*(x[1]-0.5));\n   }\n};\n\n\nint main(int argc, char *argv[])\n{\n  using namespace boost::fusion;\n\n  std::cout << \"Start heat transfer test program\" << std::endl;\n\n  boost::timer::cpu_timer totalTimer;\n\n  int verbosityOpt = 0;\n  bool dump = false; \n  constexpr int dim=2; \n  using Grid = Dune::UGGrid<dim>;\n  using LeafView = Grid::LeafGridView;\n  using H1Space = FEFunctionSpace<ContinuousLagrangeMapper<double,LeafView> >;\n  //using H1Space = FEFunctionSpace<ContinuousHierarchicMapper<double,LeafView> >;\n  using Spaces = boost::fusion::vector<H1Space const*>;\n  using VariableDescriptions = boost::fusion::vector<Variable<SpaceIndex<0>,Components<1>,VariableId<0> > >;\n  using VariableSet = VariableSetDescription<Spaces,VariableDescriptions>;\n  using Functional = HBPrecFunctional<double,VariableSet>;\n  constexpr int nvars = Functional::AnsatzVars::noOfVariables;\n  constexpr int neq = Functional::TestVars::noOfVariables;\n  using Assembler = VariationalFunctionalAssembler<LinearizationAt<Functional> >;\n  using CoefficientVectors = VariableSet::CoefficientVectorRepresentation<0,neq>::type;\n  using LinearSpace = VariableSet::CoefficientVectorRepresentation<0,neq>::type;\n\n  std::unique_ptr<boost::property_tree::ptree> pt = getKaskadeOptions(argc, argv, verbosityOpt, dump);\n  \n  //ansatz orders to be tested\n  int order = 1;\n  constexpr int maxRefSteps = 9;\n  //error values for corresponding refinement\n  double errors[maxRefSteps] = {0.65,0.13,0.034,0.0086,0.0021,5.4e-4,1.35e-4,3.4e-5,8.4e-6};\n  bool valid = true;\n  std::stringstream message(\"Test succeeded\", std::stringstream::out);\n  \n  int verbosity   = getParameter(pt, \"verbosity\", 1);\n  // if true, then the test result will be written in a file\n  bool result = getParameter(pt, \"result\",0);\n  int onlyLowerTriangle = false;\n    \n  MatrixProperties property = MatrixProperties::SYMMETRIC;\n  \n  int blocks = getParameter(pt,\"blocks\",40);\n  int nthreads = getParameter(pt,\"threads\",4);\n  double rowBlockFactor = getParameter(pt,\"rowBlockFactor\",2.0);\n\n  property = MatrixProperties::SYMMETRIC;\n  \n\n  if(verbosity > 0) {\n    std::cout << \"original mesh shall be refined : \" << maxRefSteps << \" times\" << std::endl;\n    std::cout << \"discretization order           : \" << order << std::endl;\n    std::cout << \"output level (verbosity)       : \" << verbosity << std::endl;\n  }\n      \n  Dune::GridFactory<Grid> factory;\n\n  // vertex coordinates v[0], v[1]\n  Dune::FieldVector<double,dim> v;    \n  v[0]=0; v[1]=0; factory.insertVertex(v);\n  v[0]=1; v[1]=0; factory.insertVertex(v);\n  v[0]=1; v[1]=1; factory.insertVertex(v);\n  v[0]=0; v[1]=1; factory.insertVertex(v);\n  // triangle defined by 3 vertex indices\n  std::vector<unsigned int> vid(3);\n  Dune::GeometryType gt(Dune::GeometryType::simplex,2);\n  vid[0]=0; vid[1]=1; vid[2]=2; factory.insertElement(gt,vid);\n  vid[0]=0; vid[1]=2; vid[2]=3; factory.insertElement(gt,vid);\n  std::unique_ptr<Grid> grid( factory.createGrid() ) ;\n  // the coarse grid will be refined three times\n  grid->globalRefine(0);\n  // some information on the refined mesh\n  std::cout << std::endl << \"Grid: \" << grid->size(0) << \" triangles, \" << std::endl;\n  std::cout << \"      \" << grid->size(1) << \" edges, \" << std::endl;\n  std::cout << \"      \" << grid->size(2) << \" points\" << std::endl;\n\n  // a gridmanager is constructed \n  // as connector between geometric and algebraic information\n  GridManager<Grid> gridManager(std::move(grid));\n    \n    \n  // construction of finite element space for the scalar solution T.\n  H1Space temperatureSpace(gridManager,gridManager.grid().leafGridView(),order);\n    \n  Spaces spaces(&temperatureSpace);\n    \n  // construct variable list.\n  // VariableDescription<int spaceId, int components, int Id>\n  // spaceId: number of associated FEFunctionSpace\n  // components: number of components in this variable\n  // Id: number of this variable\n  \n  std::string varNames[1] = { \"u\" };\n    \n  VariableSet variableSet(spaces,varNames);\n\n  // construct variational functional\n  Functional F;\n  if(verbosity > 0) {\n    std::cout << std::endl << \"no of variables = \" << nvars << std::endl;\n    std::cout << \"no of equations = \" << neq   << std::endl;\n    size_t dofs = variableSet.degreesOfFreedom(0,nvars);\n    std::cout << \"number of degrees of freedom = \" << dofs   << std::endl;\n  }\n\n    \n  //construct Galerkin representation\n  Assembler assembler(gridManager,spaces);\n  \n  gridManager.enforceConcurrentReads(true);\n  assembler.setNSimultaneousBlocks(blocks);\n  assembler.setRowBlockFactor(rowBlockFactor);\n  \n  for(int refSteps = 0;refSteps<maxRefSteps;refSteps++) {\n    gridManager.globalRefine(1);\n    \n    boost::timer::cpu_timer assembTimer;\n    VariableSet::VariableSet u(variableSet);\n    \n    size_t nnz = assembler.nnz(0,1,0,1,onlyLowerTriangle);\n    if(verbosity > 0) {\n      std::cout << \"number of nonzero elements in the stiffness matrix: \" << nnz << std::endl << std::endl;\n    }\n    \n    CoefficientVectors solution(VariableSet::CoefficientVectorRepresentation<0,1>::init(spaces));\n    solution = 0;\n    \n    assembler.assemble(linearization(F,u),assembler.MATRIX|assembler.RHS|assembler.VALUE,nthreads,verbosity);\n    if(verbosity > 0) {\n      std::cout << \"computing time for assemble: \" << boost::timer::format(assembTimer.elapsed()) << \"\\n\";\n    }\n    \n    CoefficientVectors rhs(assembler.rhs());\n    AssembledGalerkinOperator<Assembler,0,1,0,1> A(assembler, onlyLowerTriangle);\n    \n    boost::timer::cpu_timer iteTimer;\n    int iteSteps = getParameter(pt, \"solver.iteMax\", 1000);\n    double iteEps = getParameter(pt, \"solver.iteEps\", 1.0e-10);\n    Dune::InverseOperatorResult res;\n    const DefaultDualPairing<LinearSpace,LinearSpace> defaultScalarProduct{};\n    StrakosTichyPTerminationCriterion<double> termination(iteEps,iteSteps);\n    int lookAhead = getParameter(pt, \"solver.lookAhead\", 50);\n    termination.setLookAhead(lookAhead);\n\n    HierarchicalBasisPreconditioner<Grid,AssembledGalerkinOperator<Assembler,0,1,0,1>::range_type, AssembledGalerkinOperator<Assembler,0,1,0,1>::range_type > hb(gridManager.grid());\n    CG<LinearSpace,LinearSpace> cg(A,hb,defaultScalarProduct,termination,verbosity);\n    cg.apply(solution,rhs,res);\n  \n    solution *= -1.0;\n    u.data = solution.data;\n    \n    if(verbosity > 0) {\n      std::cout << \"iterative solve eps= \" << iteEps << \": \" \n    << (res.converged?\"converged\":\"failed\") << \" after \"\n    << res.iterations << \" steps, rate=\"\n    << res.conv_rate << \", computing time=\" << (double)(iteTimer.elapsed().user)/1e9 << \"s\\n\";\n    }\n    \n    //calculate error in l2norm\n    VariableSet::VariableSet func( variableSet ) ;\n    interpolateGloballyWeak<PlainAverage>(boost::fusion::at_c<0>(func.data),HBPrecSolution());\n    u -= func;\n    L2Norm l2 ;\n    double nrm2 = l2( boost::fusion::at_c<0>(u.data) ) ;\n    if(verbosity > 0) {\n      std::cout << \"error in l2norm: \" << nrm2 << std::endl;\n    }\n    // query whether error is low enough\n    if(!(nrm2<=errors[refSteps])) {\n      valid = false;\n      message << \"Test failed: The error after \" << refSteps << \" refinements was too high at the test with ansatz functions of order 1.\";\n    }\n  }\n       \n  std::cout << \"total computing time: \" << boost::timer::format(totalTimer.elapsed()) << \"\\n\";\n  std::cout << message.str() << std::endl;\n  if(result) {\n    std::string description = \"Test with example stationary heat transfer, 2D. Used iterate solver IterateType::CG, PrecondType::HB preconditioner:\";\n    std::ofstream outfile(\"../testResult.txt\", std::ofstream::out | std::ofstream::app);\n    outfile << description << std::endl << message.str() << std::endl << std::endl;\n    outfile.close();\n  }\n}\n", "meta": {"hexsha": "151b8bd58ed189c51c570cfa7c8f8f5afdf2b17d", "size": 10213, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Kaskade/tests/hbPrec/hbPrec.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/hbPrec/hbPrec.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/hbPrec/hbPrec.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": 40.5277777778, "max_line_length": 181, "alphanum_fraction": 0.6464310193, "num_tokens": 2787, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.685949442167993, "lm_q2_score": 0.7248702702332476, "lm_q1q2_score": 0.4972243575106585}}
{"text": "/**\n * @file dcgan_test.cpp\n * @author Shikhar Jaiswal\n *\n * Tests the DCGAN network.\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#include <mlpack/core.hpp>\n\n#include <mlpack/methods/ann/init_rules/gaussian_init.hpp>\n#include <mlpack/methods/ann/loss_functions/sigmoid_cross_entropy_error.hpp>\n#include <mlpack/methods/ann/gan/gan.hpp>\n#include <mlpack/methods/ann/ffn.hpp>\n#include <mlpack/methods/ann/layer/layer.hpp>\n#include <mlpack/methods/softmax_regression/softmax_regression.hpp>\n\n#include <ensmallen.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n#include \"serialization.hpp\"\n\nusing namespace mlpack;\nusing namespace mlpack::ann;\nusing namespace mlpack::math;\nusing namespace mlpack::regression;\nusing namespace std::placeholders;\n\nBOOST_AUTO_TEST_SUITE(DCGANNetworkTest);\n\n/*\n * Tests the DCGAN implementation on the MNIST dataset.\n * It's not viable to train on bigger parameters due to time constraints.\n * Please refer mlpack/models repository for the tutorial.\n */\nBOOST_AUTO_TEST_CASE(DCGANMNISTTest)\n{\n  size_t dNumKernels = 32;\n  size_t discriminatorPreTrain = 5;\n  size_t batchSize = 5;\n  size_t noiseDim = 100;\n  size_t generatorUpdateStep = 1;\n  size_t numSamples = 10;\n  double stepSize = 0.0003;\n  double eps = 1e-8;\n  size_t numEpoches = 1;\n  double tolerance = 1e-5;\n  int datasetMaxCols = 10;\n  bool shuffle = true;\n  double multiplier = 10;\n\n  Log::Info << std::boolalpha\n      << \" batchSize = \" << batchSize << std::endl\n      << \" generatorUpdateStep = \" << generatorUpdateStep << std::endl\n      << \" noiseDim = \" << noiseDim << std::endl\n      << \" numSamples = \" << numSamples << std::endl\n      << \" stepSize = \" << stepSize << std::endl\n      << \" numEpoches = \" << numEpoches << std::endl\n      << \" tolerance = \" << tolerance << std::endl\n      << \" shuffle = \" << shuffle << std::endl;\n\n  arma::mat trainData;\n  trainData.load(\"mnist_first250_training_4s_and_9s.arm\");\n  Log::Info << arma::size(trainData) << std::endl;\n\n  trainData = trainData.cols(0, datasetMaxCols - 1);\n\n  size_t numIterations = trainData.n_cols * numEpoches;\n  numIterations /= batchSize;\n\n  Log::Info << \"Dataset loaded (\" << trainData.n_rows << \", \"\n            << trainData.n_cols << \")\" << std::endl;\n  Log::Info << trainData.n_rows << \"--------\" << trainData.n_cols << std::endl;\n\n  // Create the Discriminator network.\n  FFN<SigmoidCrossEntropyError<> > discriminator;\n  discriminator.Add<Convolution<> >(1, dNumKernels, 4, 4, 2, 2, 1, 1, 28, 28);\n  discriminator.Add<LeakyReLU<> >(0.2);\n  discriminator.Add<Convolution<> >(dNumKernels, 2 * dNumKernels, 4, 4, 2, 2,\n      1, 1, 14, 14);\n  discriminator.Add<LeakyReLU<> >(0.2);\n  discriminator.Add<Convolution<> >(2 * dNumKernels, 4 * dNumKernels, 4, 4,\n      2, 2, 1, 1, 7, 7);\n  discriminator.Add<LeakyReLU<> >(0.2);\n  discriminator.Add<Convolution<> >(4 * dNumKernels, 8 * dNumKernels, 4, 4,\n      2, 2, 2, 2, 3, 3);\n  discriminator.Add<LeakyReLU<> >(0.2);\n  discriminator.Add<Convolution<> >(8 * dNumKernels, 1, 4, 4, 1, 1,\n      1, 1, 2, 2);\n\n  // Create the Generator network.\n  FFN<SigmoidCrossEntropyError<> > generator;\n  generator.Add<TransposedConvolution<> >(noiseDim, 8 * dNumKernels, 2, 2,\n      1, 1, 0, 0, 1, 1, 2, 2);\n  generator.Add<BatchNorm<> >(1024);\n  generator.Add<ReLULayer<> >();\n  generator.Add<TransposedConvolution<> >(8 * dNumKernels, 4 * dNumKernels,\n      2, 2, 1, 1, 0, 0, 2, 2, 3, 3);\n  generator.Add<BatchNorm<> >(1152);\n  generator.Add<ReLULayer<> >();\n  generator.Add<TransposedConvolution<> >(4 * dNumKernels, 2 * dNumKernels,\n      5, 5, 2, 2, 1, 1, 3, 3, 7, 7);\n  generator.Add<BatchNorm<> >(3136);\n  generator.Add<ReLULayer<> >();\n  generator.Add<TransposedConvolution<> >(2 * dNumKernels, dNumKernels, 4, 4,\n      2, 2, 1, 1, 7, 7, 14, 14);\n  generator.Add<BatchNorm<> >(6272);\n  generator.Add<ReLULayer<> >();\n  generator.Add<TransposedConvolution<> >(dNumKernels, 1, 4, 4, 2, 2, 1, 1,\n      14, 14, 28, 28);\n  generator.Add<TanHLayer<> >();\n\n  // Create DCGAN.\n  GaussianInitialization gaussian(0, 1);\n  ens::Adam optimizer(stepSize, batchSize, 0.9, 0.999, eps, numIterations,\n      tolerance, shuffle);\n  std::function<double()> noiseFunction = [] () {\n      return math::RandNormal(0, 1);};\n  GAN<FFN<SigmoidCrossEntropyError<> >, GaussianInitialization,\n      std::function<double()>, DCGAN> dcgan(generator, discriminator, gaussian,\n      noiseFunction, noiseDim, batchSize, generatorUpdateStep,\n      discriminatorPreTrain, multiplier);\n\n  Log::Info << \"Training...\" << std::endl;\n  double objVal = dcgan.Train(trainData, optimizer);\n\n  // Test that objective value returned by GAN::Train() is finite.\n  BOOST_REQUIRE_EQUAL(std::isfinite(objVal), true);\n\n  // Generate samples.\n  Log::Info << \"Sampling...\" << std::endl;\n  arma::mat noise(noiseDim, batchSize);\n  size_t dim = std::sqrt(trainData.n_rows);\n  arma::mat generatedData(2 * dim, dim * numSamples);\n\n  for (size_t i = 0; i < numSamples; i++)\n  {\n    arma::mat samples;\n    noise.imbue( [&]() { return noiseFunction(); } );\n\n    dcgan.Generator().Forward(noise, samples);\n    samples.reshape(dim, dim);\n    samples = samples.t();\n\n    generatedData.submat(0, i * dim, dim - 1, i * dim + dim - 1) = samples;\n\n    samples = trainData.col(math::RandInt(0, trainData.n_cols));\n    samples.reshape(dim, dim);\n    samples = samples.t();\n\n    generatedData.submat(dim,\n        i * dim, 2 * dim - 1, i * dim + dim - 1) = samples;\n  }\n\n  Log::Info << \"Output generated!\" << std::endl;\n\n  // Check that Serialization is working correctly.\n  arma::mat orgPredictions;\n  dcgan.Predict(noise, orgPredictions);\n\n  GAN<FFN<SigmoidCrossEntropyError<> >, GaussianInitialization,\n      std::function<double()>, DCGAN> dcganText(generator, discriminator,\n      gaussian, noiseFunction, noiseDim, batchSize, generatorUpdateStep,\n      discriminatorPreTrain, multiplier);\n\n  GAN<FFN<SigmoidCrossEntropyError<> >, GaussianInitialization,\n      std::function<double()>, DCGAN> dcganXml(generator, discriminator,\n      gaussian, noiseFunction, noiseDim, batchSize, generatorUpdateStep,\n      discriminatorPreTrain, multiplier);\n\n  GAN<FFN<SigmoidCrossEntropyError<> >, GaussianInitialization,\n      std::function<double()>, DCGAN> dcganBinary(generator, discriminator,\n      gaussian, noiseFunction, noiseDim, batchSize, generatorUpdateStep,\n      discriminatorPreTrain, multiplier);\n\n  SerializeObjectAll(dcgan, dcganXml, dcganText, dcganBinary);\n\n  arma::mat predictions, xmlPredictions, textPredictions, binaryPredictions;\n  dcgan.Predict(noise, predictions);\n  dcganXml.Predict(noise, xmlPredictions);\n  dcganText.Predict(noise, textPredictions);\n  dcganBinary.Predict(noise, binaryPredictions);\n\n  CheckMatrices(orgPredictions, predictions);\n  CheckMatrices(orgPredictions, xmlPredictions);\n  CheckMatrices(orgPredictions, textPredictions);\n  CheckMatrices(orgPredictions, binaryPredictions);\n}\n\n\n/*\n * Tests the DCGAN implementation with minibatch layer on the MNIST dataset.\n * It's not viable to train on bigger parameters due to time constraints.\n\nBOOST_AUTO_TEST_CASE(DCGANMNISTTest)\n{\n  size_t dNumKernels = 32;\n  size_t discriminatorPreTrain = 5;\n  size_t batchSize = 5;\n  size_t noiseDim = 100;\n  size_t generatorUpdateStep = 1;\n  size_t numSamples = 1000;\n  double stepSize = 0.0003;\n  double eps = 1e-8;\n  size_t numEpoches = 5;\n  double tolerance = 1e-5;\n  int datasetMaxCols = 10;\n  bool shuffle = true;\n  double multiplier = 10;\n\n  Log::Info << std::boolalpha\n      << \" batchSize = \" << batchSize << std::endl\n      << \" generatorUpdateStep = \" << generatorUpdateStep << std::endl\n      << \" noiseDim = \" << noiseDim << std::endl\n      << \" numSamples = \" << numSamples << std::endl\n      << \" stepSize = \" << stepSize << std::endl\n      << \" numEpoches = \" << numEpoches << std::endl\n      << \" tolerance = \" << tolerance << std::endl\n      << \" shuffle = \" << shuffle << std::endl;\n\n  arma::mat trainData;\n  trainData.load(\"mnist_first250_training_4s_and_9s.arm\");\n  Log::Info << arma::size(trainData) << std::endl;\n\n  // trainData = trainData.cols(0, datasetMaxCols - 1);\n\n  size_t numIterations = trainData.n_cols * numEpoches;\n  // numIterations /= batchSize;\n\n  Log::Info << \"Dataset loaded (\" << trainData.n_rows << \", \"\n            << trainData.n_cols << \")\" << std::endl;\n  Log::Info << trainData.n_rows << \"--------\" << trainData.n_cols << std::endl;\n\n  // Create the Discriminator network\n  FFN<SigmoidCrossEntropyError<> > discriminator;\n  discriminator.Add<Convolution<> >(1, dNumKernels, 4, 4, 2, 2, 1, 1, 28, 28);\n  discriminator.Add<LeakyReLU<> >(0.2);\n  discriminator.Add<Convolution<> >(dNumKernels, 2 * dNumKernels, 4, 4, 2, 2,\n      1, 1, 14, 14);\n  discriminator.Add<LeakyReLU<> >(0.2);\n  discriminator.Add<Convolution<> >(2 * dNumKernels, 4 * dNumKernels, 4, 4,\n      2, 2, 1, 1, 7, 7);\n  discriminator.Add<MiniBatchDiscrimination<> >(4 * dNumKernels, 4 * dNumKernels + 10, 100);\n  discriminator.Add<Linear<> >(4 * dNumKernels + 10, 1);\n\n  // Create the Generator network\n  FFN<SigmoidCrossEntropyError<> > generator;\n  generator.Add<TransposedConvolution<> >(noiseDim, 8 * dNumKernels, 2, 2,\n      1, 1, 1, 1, 1, 1);\n  generator.Add<BatchNorm<> >(1024);\n  generator.Add<ReLULayer<> >();\n  generator.Add<TransposedConvolution<> >(8 * dNumKernels, 4 * dNumKernels,\n      2, 2, 1, 1, 0, 0, 2, 2);\n  generator.Add<BatchNorm<> >(1152);\n  generator.Add<ReLULayer<> >();\n  generator.Add<TransposedConvolution<> >(4 * dNumKernels, 2 * dNumKernels,\n      5, 5, 2, 2, 1, 1, 3, 3);\n  generator.Add<BatchNorm<> >(3136);\n  generator.Add<ReLULayer<> >();\n  generator.Add<TransposedConvolution<> >(2 * dNumKernels, dNumKernels, 8, 8,\n      1, 1, 1, 1, 7, 7);\n  generator.Add<BatchNorm<> >(6272);\n  generator.Add<ReLULayer<> >();\n  generator.Add<TransposedConvolution<> >(dNumKernels, 1, 15, 15, 1, 1, 1, 1,\n      14, 14);\n  generator.Add<TanHLayer<> >();\n\n  // Create DCGAN\n  GaussianInitialization gaussian(0, 1);\n  ens::Adam optimizer(stepSize, batchSize, 0.9, 0.999, eps, numIterations,\n      tolerance, shuffle);\n  std::function<double()> noiseFunction = [] () {\n      return math::RandNormal(0, 1);};\n  GAN<FFN<SigmoidCrossEntropyError<> >, GaussianInitialization,\n      std::function<double()>, DCGAN> dcgan(trainData, generator, discriminator,\n      gaussian, noiseFunction, noiseDim, batchSize, generatorUpdateStep,\n      discriminatorPreTrain, multiplier);\n\n  Log::Info << \"Training...\" << std::endl;\n  double objVal = dcgan.Train(optimizer);\n\n  // Test that objective value returned by GAN::Train() is finite.\n  BOOST_REQUIRE_EQUAL(std::isfinite(objVal), true);\n\n  // Generate samples\n  Log::Info << \"Sampling...\" << std::endl;\n  arma::mat noise(noiseDim, 1);\n  size_t dim = std::sqrt(trainData.n_rows);\n  arma::mat generatedData(2 * dim, dim * numSamples);\n\n  for (size_t i = 0; i < numSamples; i++)\n  {\n    arma::mat samples;\n    noise.imbue( [&]() { return noiseFunction(); } );\n\n    dcgan.Generator().Forward(noise, samples);\n    samples.reshape(dim, dim);\n    samples = samples.t();\n\n    generatedData.submat(0, i * dim, dim - 1, i * dim + dim - 1) = samples;\n\n    samples = trainData.col(math::RandInt(0, trainData.n_cols));\n    samples.reshape(dim, dim);\n    samples = samples.t();\n\n    generatedData.submat(dim,\n        i * dim, 2 * dim - 1, i * dim + dim - 1) = samples;\n  }\n\n  // CNN digit recogniser model from mlpack/model respository.\n  model.Add<Convolution<> >(1,6,5,5,1,1,0,0,28,28);\n\n  // Add first ReLU.\n  model.Add<LeakyReLU<> >();\n\n  // Add first pooling layer. Pools over 2x2 fields in the input.\n  model.Add<MaxPooling<> >(2,2,2,2,true);\n\n  // Add the second convolution layer.\n  model.Add<Convolution<> >(6,16,5,5,1,1,0,0,12,12);\n  // Add the second ReLU.\n  model.Add<LeakyReLU<> >();\n\n  // Add the second pooling layer.\n  model.Add<MaxPooling<> >(2, 2, 2, 2, true);\n\n  // Add the final dense layer.\n  model.Add<Linear<> >(16*4*4, 10);\n  model.Add<LogSoftMax<> >();\n\n  arma::mat labels = arma::zeros(1, trainData.n_cols);\n  labels.submat(0, labels.n_cols / 2, 0, labels.n_cols - 1).fill(1);\n  labels += 1;\n\n  ens::SGD<AdamUpdate> optimizer2(1.2e-3, 50, 40 * 10000, 1e-8, true,\n        ens::AdamUpdate(1e-8, 0.9, 0.999));\n  model.Train(trainData, labels, optimizer2);\n\n  Log::Info << InceptionScore(model, generatedData, 50) << std::endl;\n  Log::Info << \"Output generated!\" << std::endl;\n}\n*/\n\n/*\n * Tests the DCGAN implementation on the CelebA dataset.\n * It's currently not possible to run this every time due to time constraints.\n * Please refer mlpack/models repository for the tutorial.\n\nBOOST_AUTO_TEST_CASE(DCGANCelebATest)\n{\n  size_t dNumKernels = 64;\n  size_t discriminatorPreTrain = 300;\n  size_t batchSize = 1;\n  size_t noiseDim = 100;\n  size_t generatorUpdateStep = 1;\n  size_t numSamples = 10;\n  double stepSize = 0.0003;\n  double eps = 1e-8;\n  size_t numEpoches = 20;\n  double tolerance = 1e-5;\n  int datasetMaxCols = -1;\n  bool shuffle = true;\n  double multiplier = 10;\n\n  Log::Info << std::boolalpha\n      << \" batchSize = \" << batchSize << std::endl\n      << \" generatorUpdateStep = \" << generatorUpdateStep << std::endl\n      << \" noiseDim = \" << noiseDim << std::endl\n      << \" numSamples = \" << numSamples << std::endl\n      << \" stepSize = \" << stepSize << std::endl\n      << \" numEpoches = \" << numEpoches << std::endl\n      << \" tolerance = \" << tolerance << std::endl\n      << \" shuffle = \" << shuffle << std::endl;\n\n  arma::mat trainData;\n  trainData.load(\"celeba.csv\");\n  Log::Info << arma::size(trainData) << std::endl;\n\n  if (datasetMaxCols > 0)\n    trainData = trainData.cols(0, datasetMaxCols - 1);\n\n  size_t numIterations = trainData.n_cols * numEpoches;\n  numIterations /= batchSize;\n\n  Log::Info << \"Dataset loaded (\" << trainData.n_rows << \", \"\n            << trainData.n_cols << \")\" << std::endl;\n  Log::Info << trainData.n_rows << \"--------\" << trainData.n_cols << std::endl;\n\n  // Create the Discriminator network.\n  FFN<SigmoidCrossEntropyError<> > discriminator;\n  discriminator.Add<Convolution<> >(3, dNumKernels, 4, 4, 2, 2, 1, 1, 64, 64);\n  discriminator.Add<LeakyReLU<> >(0.2);\n  discriminator.Add<Convolution<> >(dNumKernels, 2 * dNumKernels, 4, 4, 2, 2,\n      1, 1, 32, 32);\n  discriminator.Add<LeakyReLU<> >(0.2);\n  discriminator.Add<Convolution<> >(2 * dNumKernels, 4 * dNumKernels, 4, 4,\n      2, 2, 1, 1, 16, 16);\n  discriminator.Add<LeakyReLU<> >(0.2);\n  discriminator.Add<Convolution<> >(4 * dNumKernels, 8 * dNumKernels, 4, 4,\n      2, 2, 1, 1, 8, 8);\n  discriminator.Add<LeakyReLU<> >(0.2);\n  discriminator.Add<Convolution<> >(8 * dNumKernels, 1, 4, 4, 1, 1,\n      0, 0, 4, 4);\n\n  // Create the Generator network.\n  FFN<SigmoidCrossEntropyError<> > generator;\n  generator.Add<TransposedConvolution<> >(noiseDim, 8 * dNumKernels, 4, 4,\n      1, 1, 2, 2, 1, 1);\n  generator.Add<BatchNorm<> >(4096);\n  generator.Add<ReLULayer<> >();\n  generator.Add<TransposedConvolution<> >(8 * dNumKernels, 4 * dNumKernels,\n      5, 5, 1, 1, 1, 1, 4, 4);\n  generator.Add<BatchNorm<> >(8192);\n  generator.Add<ReLULayer<> >();\n  generator.Add<TransposedConvolution<> >(4 * dNumKernels, 2 * dNumKernels,\n      9, 9, 1, 1, 1, 1, 8, 8);\n  generator.Add<BatchNorm<> >(16384);\n  generator.Add<ReLULayer<> >();\n  generator.Add<TransposedConvolution<> >(2 * dNumKernels, dNumKernels, 17, 17,\n      1, 1, 1, 1, 16, 16);\n  generator.Add<BatchNorm<> >(32768);\n  generator.Add<ReLULayer<> >();\n  generator.Add<TransposedConvolution<> >(dNumKernels, 3, 33, 33, 1, 1, 1, 1,\n      32, 32);\n  generator.Add<TanHLayer<> >();\n\n  // Create DCGAN.\n  GaussianInitialization gaussian(0, 1);\n  ens::Adam optimizer(stepSize, batchSize, 0.9, 0.999, eps, numIterations,\n      tolerance, shuffle);\n  std::function<double()> noiseFunction = [] () {\n      return math::RandNormal(0, 1);};\n  GAN<FFN<SigmoidCrossEntropyError<> >, GaussianInitialization,\n      std::function<double()>, DCGAN> dcgan(trainData, generator, discriminator,\n      gaussian, noiseFunction, noiseDim, batchSize, generatorUpdateStep,\n      discriminatorPreTrain, multiplier);\n\n  Log::Info << \"Training...\" << std::endl;\n  dcgan.Train(optimizer);\n\n  // Generate samples.\n  Log::Info << \"Sampling...\" << std::endl;\n  arma::mat noise(noiseDim, 1);\n  size_t dim = std::sqrt(trainData.n_rows);\n  arma::mat generatedData(2 * dim, dim * numSamples);\n\n  for (size_t i = 0; i < numSamples; i++)\n  {\n    arma::mat samples;\n    noise.imbue( [&]() { return noiseFunction(); } );\n\n    dcgan.Generator().Forward(noise, samples);\n    samples.reshape(dim, dim);\n    samples = samples.t();\n\n    generatedData.submat(0, i * dim, dim - 1, i * dim + dim - 1) = samples;\n\n    samples = trainData.col(math::RandInt(0, trainData.n_cols));\n    samples.reshape(dim, dim);\n    samples = samples.t();\n\n    generatedData.submat(dim,\n        i * dim, 2 * dim - 1, i * dim + dim - 1) = samples;\n  }\n\n  Log::Info << \"Output generated!\" << std::endl;\n}\n*/\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "c843aca60e9227af7a041e641f915f89df779a5e", "size": 17109, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/dcgan_test.cpp", "max_stars_repo_name": "tomjpsun/mlpack", "max_stars_repo_head_hexsha": "39b9a852c58b648ddb9b87a3d87aa3db2bacbf0a", "max_stars_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-11T14:14:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-11T14:14:30.000Z", "max_issues_repo_path": "src/mlpack/tests/dcgan_test.cpp", "max_issues_repo_name": "tomjpsun/mlpack", "max_issues_repo_head_hexsha": "39b9a852c58b648ddb9b87a3d87aa3db2bacbf0a", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-10T17:39:50.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-11T14:56:25.000Z", "max_forks_repo_path": "src/mlpack/tests/dcgan_test.cpp", "max_forks_repo_name": "tomjpsun/mlpack", "max_forks_repo_head_hexsha": "39b9a852c58b648ddb9b87a3d87aa3db2bacbf0a", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.0189473684, "max_line_length": 92, "alphanum_fraction": 0.6583084926, "num_tokens": 5390, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4971094644145567}}
{"text": "#ifndef TYPES_HPP\n#define TYPES_HPP\n\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n\nnamespace eigenml {\n\n    // general type of matrices\n    typedef Eigen::MatrixXd Matrix;\n    typedef Eigen::VectorXd Vector;\n\n    // integer type of matrices\n    typedef Eigen::MatrixXi MatrixI;\n    typedef Eigen::VectorXi VectorI;\n\n    // typedef for histogram types\n    typedef std::map<double, double> Histogram;\n\n    // value that the split criterion should return\n    typedef std::pair<double, double> ValueAndWeight;\n\n    // sorted X columns by values\n    typedef std::vector<size_t> IdxVector;\n\n    // types of model\n    // allows to specialize types of variables using traits\n    enum ModelType {\n        kSupervisedClassifier,\n        kSupervisedRegressor\n    };\n}\n\n\n#endif // TYPES_HPP\n", "meta": {"hexsha": "a8b8107c6ac7369432e91c7635de75ce99b916bd", "size": 781, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/eigenml/core/types.hpp", "max_stars_repo_name": "guillempalou/eigenml", "max_stars_repo_head_hexsha": "3991ddbfd01032cbbe698f6ec35eecbfe127e9b4", "max_stars_repo_licenses": ["Apache-2.0"], "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/eigenml/core/types.hpp", "max_issues_repo_name": "guillempalou/eigenml", "max_issues_repo_head_hexsha": "3991ddbfd01032cbbe698f6ec35eecbfe127e9b4", "max_issues_repo_licenses": ["Apache-2.0"], "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/eigenml/core/types.hpp", "max_forks_repo_name": "guillempalou/eigenml", "max_forks_repo_head_hexsha": "3991ddbfd01032cbbe698f6ec35eecbfe127e9b4", "max_forks_repo_licenses": ["Apache-2.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.6944444444, "max_line_length": 59, "alphanum_fraction": 0.695262484, "num_tokens": 173, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743168019989179, "lm_q2_score": 0.6688802669716106, "lm_q1q2_score": 0.49709042361512534}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\nCopyright (C) 2005, 2007, 2009, 2014 Klaus Spanderen\nCopyright (C) 2015 CompatibL\n\nThis file is part of QuantLib, a free-software/open-source library\nfor financial quantitative analysts and developers - http://quantlib.org/\n\nQuantLib is free software: you can redistribute it and/or modify it\nunder the terms of the QuantLib license.  You should have received a\ncopy of the license along with this program; if not, please email\n<quantlib-dev@lists.sf.net>. The license is also available online at\n<http://quantlib.org/license.shtml>.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT\nANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\nFOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n#ifndef cl_adjoint_heston_process_impl_hpp\n#define cl_adjoint_heston_process_impl_hpp\n#pragma once\n\n\n#include \"adjointhestonprocesstest.hpp\"\n#include \"utilities.hpp\"\n#include \"adjointtestutilities.hpp\"\n#include \"adjointtestbase.hpp\"\n#include <ql/quotes/simplequote.hpp>\n#include <ql/math/modifiedbessel.hpp>\n#include <ql/processes/hestonprocess.hpp>\n#include <ql/time/daycounters/actualactual.hpp>\n#include <ql/time/schedule.hpp>\n#include <boost/make_shared.hpp>\n\nusing namespace QuantLib;\nusing namespace boost::unit_test_framework;\n\n\n#define OUTPUT_FOLDER_NAME \"AdjointHestonProcess\"\n\n/*!\nAdjointHestonProcessTest is tested using adjoint differentiation for the class hestonprocess.\n\nHeston model describes the evolution of the volatility of an underlying asset.\nIt is a stochastic volatility model: such a model assumes that the\nvolatility of the asset is neither constant, nor even deterministic,\nbut is a random process.\n\nThis class describes the square root stochastic volatility\nprocess governed by\n\\f[\n\\begin{array}{rcl}\ndS(t, S)  &=& \\mu S dt + \\sqrt{v} S dW_1 \\\\\ndv(t, S)  &=& \\kappa (\\theta - v) dt + \\sigma \\sqrt{v} dW_2 \\\\\ndW_1 dW_2 &=& \\rho dt\n\\end{array}\n\\f]\n\nTested functions are expectation, evolve, phi, drift, stdDeviation, covariance.\n\nPhi is the continuous version of a characteristic function\nfor the exact sampling of the Heston process, s. page 8, formula 13,\nM. Broadie, O. Kaya, Exact Simulation of Stochastic Volatility and\nother Affine Jump Diffusion Processes\nhttp://finmath.stanford.edu/seminars/documents/Broadie.pdf\nOutput of function Phi is value of haracteristic function.\nInputs are process, value of variable, start and finish variance distibution, and delta time.\nPhi is obtained from fourier transform, so Phi has complex derivative with respect to input variable.\n\nOutput of fuction expectation is Expectation\n\\f$ E(\\mathrm{x}_{t_0 + \\Delta t}\n| \\mathrm{x}_{t_0} = \\mathrm{x}_0) \\f$\nof the process after a time interval \\f$ \\Delta t \\f$\naccording to the given discretization.\nInputs are time, start value, and delta time.\nExpectation is differentiated with respect to delta time.\n\nOutput of fuction evolve is Evolve,\nwhich returns the asset value after a time interval \\f$ \\Delta t\n\\f$ according to the given discretization. By default, it\nreturns\n\\f[\nE(x_0,t_0,\\Delta t) + S(x_0,t_0,\\Delta t) \\cdot \\Delta w\n\\f]\nwhere \\f$ E \\f$ is the expectation and \\f$ S \\f$ the\nstandard deviation.\nInputs are time, start value, and delta time.\nEvolve is differentiated with respect to delta time.\n\nOutput of fuction drift is Drift (the change of the average value)\nInputs are time, array of average values.\nDrift is differentiated with respect to average values.\n\nOutput of fuction stdDeviation is Standart Deviation.\nInputs are time, array of average values, and delta time.\nStdDeviation is differentiated with respect to delta time.\n\nOutput of fuction covariance is covariances matrix\nInputs are time, array of average values, and delta time.\nCovariance is differentiated with respect to delta time.\n*/\n\n\nnamespace\n{\n    enum\n    {\n#if defined CL_GRAPH_GEN\n        // Number of points for dependency plots.\n        pointNo = 100,\n        // Number of points for performance plot.\n        iterNo = 30,\n        // Step for portfolio size for performance testing .\n        step = 1,\n#else\n        // Number of points for dependency plots.\n        pointNo = 0,\n        // Number of points for performance plot.\n        iterNo = 0,\n        // Step for portfolio size for performance testing .\n        step = 1,\n#endif\n        // Defines performance accuracy. Its value is a minimum number\n        // of calling of O(1) complexity methods per one performance test.\n        iterNumFactor = 1000,\n    };\n\n    // copy of function Phi from hestonprocess.hpp\n    // This is the continuous version of a characteristic function\n    // for the exact sampling of the Heston process, s. page 8, formula 13,\n    // M. Broadie, O. Kaya, Exact Simulation of Stochastic Volatility and\n    // other Affine Jump Diffusion Processes\n    // http://finmath.stanford.edu/seminars/documents/Broadie.pdf\n    std::complex<Real> Phi1(const HestonProcess& process,\n        const std::complex<Real>& a,\n        Real nu_0, Real nu_t, Time dt) {\n        const Real theta = process.theta();\n        const Real kappa = process.kappa();\n        const Real sigma = process.sigma();\n\n        const Volatility sigma2 = sigma*sigma;\n        const std::complex<Real> ga = std::sqrt(\n            kappa*kappa - 2 * sigma2*a*std::complex<Real>(0.0, 1.0));\n        const Real d = 4 * theta*kappa / sigma2;\n\n        const Real nu = 0.5*d - 1;\n        const std::complex<Real> z\n            = ga*std::exp(-0.5*ga*dt) / (1.0 - std::exp(-ga*dt));\n        const std::complex<Real> log_z\n            = -0.5*ga*dt + std::log(ga / (1.0 - std::exp(-ga*dt)));\n\n        const std::complex<Real> alpha\n            = 4.0*ga*std::exp(-0.5*ga*dt) / (sigma2*(1.0 - std::exp(-ga*dt)));\n\n        const std::complex<Real> beta = 4.0*kappa*std::exp(-0.5*kappa*dt)\n            / (sigma2*(1.0 - std::exp(-kappa*dt)));\n\n        return ga*std::exp(-0.5*(ga - kappa)*dt)*(1 - std::exp(-kappa*dt))\n            / (kappa*(1.0 - std::exp(-ga*dt)))\n            *std::exp((nu_0 + nu_t) / sigma2 * (\n            kappa*(1.0 + std::exp(-kappa*dt)) / (1.0 - std::exp(-kappa*dt))\n            - ga*(1.0 + std::exp(-ga*dt)) / (1.0 - std::exp(-ga*dt))))\n            *std::exp(nu*log_z) / std::pow(z, nu)\n            *((nu_t > 1e-8)\n            ? modifiedBesselFunction_i(\n            nu, std::sqrt(nu_0*nu_t)*alpha)\n            / modifiedBesselFunction_i(\n            nu, std::sqrt(nu_0*nu_t)*beta)\n            : std::pow(alpha / beta, nu)\n            );\n    }\n\n    struct CommonVars0\n    {\n        CommonVars0()\n        : dayCounter_()\n        {\n            dayCounter_ = ActualActual();\n        }\n        DayCounter dayCounter_;\n\n    };\n\n    struct CommonVars : public CommonVars0\n    {\n        explicit CommonVars()\n        : CommonVars0()\n        , s0_(boost::make_shared<SimpleQuote>(SimpleQuote(1.05)))\n        , process_(Handle<YieldTermStructure>(flatRate(0.04, dayCounter_)), Handle<YieldTermStructure>(flatRate(0.5, dayCounter_)), s0_, 0.3, 1.16, 0.2, 0.8, 0.8,\n        HestonProcess::QuadraticExponentialMartingale)\n        {\n        }\n\n        Handle<Quote> s0_;\n        HestonProcess process_;\n    };\n\n    enum VariableName { expectation, evolve, phi, drift, stdDeviation, covariance };\n\n    std::string toString(VariableName name)\n    {\n        switch (name)\n        {\n        case expectation:\n            return \"Expectation\";\n        case evolve:\n            return \"Evolve\";\n        case phi:\n            return \"Phi\";\n        case drift:\n            return \"Drift\";\n        case stdDeviation:\n            return \"stdDeviation\";\n        case covariance:\n            return \"covariance\";\n        default:\n            return \"\";\n        }\n    }\n\n    struct HestonProcessTestData : public CommonVars\n    {\n        explicit HestonProcessTestData(VariableName type)\n        : CommonVars()\n        , type_(type)\n        , t(0.5)\n        , x(2, 0.3, 0.2)\n        , dw(2, 0.1, 0.4)\n        {}\n\n        // Calculate the an expectation in case of test of function Expectation\n        // and an evolve in case of test of function Evolve.\n        Real calculateRealFromDeltaTime(Real deltaTimes)\n        {\n            if (type_ == expectation)\n            {\n                return process_.expectation(t, x, deltaTimes)[0];\n            }\n\n            if (type_ == evolve)\n            {\n                return process_.evolve(t, x, deltaTimes, dw)[0];\n            }\n\n            return Real(0.0);\n        }\n\n        Matrix calculateMatrixFromDeltaTime(Real deltaTimes)\n        {\n            if (type_ == stdDeviation)\n            {\n                return process_.stdDeviation(t, x, deltaTimes);\n            }\n\n            if (type_ == covariance)\n            {\n                return process_.covariance(t, x, deltaTimes);\n            }\n\n            return Matrix();\n        }\n\n        VariableName type_;\n        Real t;\n        Array x;\n        Array dw;\n    };\n\n    // Test of functions expectation and evolve.\n    // Testing derivative with respect to delta time.\n    struct HestonProcessRespectToDeltaTimeTest\n        : public cl::AdjointTest<HestonProcessRespectToDeltaTimeTest>\n    {\n        explicit HestonProcessRespectToDeltaTimeTest(HestonProcessTestData* data, Size size, cl::tape_empty_test_output* logger = nullptr, double shift = 1e-10)\n        : AdjointTest()\n        , data_(data)\n        , size_(size)\n        , shift_(shift)\n        , deltaTimes_(size)\n        , Variables_(size)\n        , SumVariables_(1)\n        {\n            setLogger(logger);\n            for (int i = 0; i < size_; i++)\n            {\n                deltaTimes_[i] = (i + 1) * 0.2 / double(size);\n            }\n        }\n\n        Size indepVarNumber() { return size_; }\n\n        Size depVarNumber() { return 1; }\n\n        Size minPerfIteration() { return iterNumFactor; }\n\n        double absTol() const { return 1e-5; }\n\n        void calcAnalytical()\n        {\n            analyticalResults_.resize(size_);\n            for (int i = 0; i < size_; i++)\n            {\n                double deltaTimeUp = double(deltaTimes_[i]) + shift_;\n                double deltaTimeDown = double(deltaTimes_[i]) - shift_;\n                double varUp = double(data_->calculateRealFromDeltaTime(deltaTimeUp));\n                double varDown = double(data_->calculateRealFromDeltaTime(deltaTimeDown));\n                analyticalResults_[i] = (varUp - varDown) / 2 / shift_;\n            }\n        }\n\n        void calculateVariables()\n        {\n            SumVariables_[0] = 0.0;\n            for (int i = 0; i < size_; i++)\n            {\n                Variables_[i] = data_->calculateRealFromDeltaTime(deltaTimes_[i]);\n                SumVariables_[0] += Variables_[i];\n            }\n        }\n\n        void recordTape()\n        {\n            Independent(deltaTimes_);\n            calculateVariables();\n            f_ = std::make_unique<cl::tape_function<double>>(deltaTimes_, SumVariables_);\n        }\n\n        HestonProcessTestData* data_;\n        Size size_;\n        double shift_;\n        std::vector<Real> deltaTimes_;\n        std::vector<Real> Variables_;\n        std::vector<Real> SumVariables_;\n    };\n\n    // Test of matrix functions stdDeviation and covariance.\n    struct HestonProcessMatrixFunctionsTest :\n        public cl::AdjointTest<HestonProcessMatrixFunctionsTest>\n    {\n        static const CalcMethod default_method = other;\n\n        explicit HestonProcessMatrixFunctionsTest(HestonProcessTestData* data, cl::tape_empty_test_output* logger = nullptr, double shift = 1e-10)\n        : AdjointTest()\n        , data_(data)\n        , shift_(shift)\n        , deltaTimes_(1, 0.1)\n        , size_(4)\n        {}\n\n        Size indepVarNumber() { return 1; }\n\n        Size depVarNumber() { return size_; }\n\n        Size minPerfIteration() { return iterNumFactor; }\n\n        double absTol() const { return 1e-6; }\n\n        void calculateMatrixRes()\n        {\n            Matrix StdDeviation = data_->calculateMatrixFromDeltaTime(deltaTimes_[0]);\n            Results_.assign(StdDeviation.begin(), StdDeviation.end());\n        }\n\n        void recordTape()\n        {\n            Independent(deltaTimes_);\n            calculateMatrixRes();\n            f_ = std::make_unique<cl::tape_function<double>>(deltaTimes_, Results_);\n        }\n\n        void calcAdjoint()\n        {\n            int num = Results_.size();\n            std::vector<double> w(1, 1);\n            adjointResults_ = f_->Forward(1, w);\n        }\n\n        void calcAnalitical()\n        {\n            Time dtUp = deltaTimes_[0] + shift_;\n            Time dtDown = deltaTimes_[0] - shift_;\n\n            Matrix ResUp = data_->calculateMatrixFromDeltaTime(dtUp);\n            Matrix ResDown = data_->calculateMatrixFromDeltaTime(dtDown);\n\n            for (int i = 0; i < ResUp.columns(); i++)\n            {\n                for (int j = 0; j < ResUp.rows(); j++)\n                {\n                    double analyticalRes = double((ResUp[i][j] - ResDown[i][j]) / 2 / shift_);\n                    analyticalResults_.push_back(analyticalRes);\n                }\n            }\n        }\n\n        HestonProcessTestData* data_;\n        double shift_;\n        std::vector<Real> deltaTimes_;\n        std::vector<Real> Results_;\n        Size size_;\n    };\n\n    struct HestonProcessDriftTest : public cl::AdjointTest<HestonProcessDriftTest>\n    {\n        static const CalcMethod default_method = other;\n\n        explicit HestonProcessDriftTest(CommonVars* data, cl::tape_empty_test_output* logger = nullptr, double shift = 1e-10)\n            : AdjointTest()\n            , data_(data)\n            , shift_(shift)\n            , size_(2)\n            , values_(size_)\n            , x_(size_)\n            , drift_(2)\n            , t_(0.5)\n            , indepDouble_(2)\n        {\n            for (int i = 0; i < size_; i++)\n            {\n                indepDouble_[i] = 0.3 + 0.2 * i;\n                values_[i] = indepDouble_[i];\n            }\n        }\n\n        Size indepVarNumber() { return size_; }\n\n        Size depVarNumber() { return size_; }\n\n        Size minPerfIteration() { return iterNumFactor; }\n\n        double absTol() const { return 1e-6; }\n\n        void calculateDrift()\n        {\n            for (int i = 0; i < size_; i++)\n            {\n                x_[i] = values_[i];\n            }\n            Array drift = data_->process_.drift(t_, x_);\n            for (int i = 0; i < size_; i++)\n            {\n                drift_[i] = drift[i];\n            }\n        }\n\n        void recordTape()\n        {\n            cl::Independent(values_);\n            calculateDrift();\n            f_ = std::make_unique<cl::tape_function<double>>(values_, drift_);\n        }\n\n        void calcAdjoint()\n        {\n            adjointResults_ = f_->Jacobian(indepDouble_);\n        }\n\n        void calcAnalitical()\n        {\n            analyticalResults_.resize(size_ * size_);\n            Array xUp = x_;\n            Array xDown = x_;\n            for (int i = 0; i < size_; i++)\n            {\n                xUp[i] += shift_;\n                Array DriftUp = data_->process_.drift(t_, xUp);\n                xUp[i] -= shift_;\n\n                xDown[i] -= shift_;\n                Array DriftDown = data_->process_.drift(t_, xDown);\n                xDown[i] += shift_;\n\n                for (int j = 0; j < size_; j++)\n                {\n                    analyticalResults_[i + size_ * j] = (DriftUp[j] - DriftDown[j]) / 2 / shift_;\n                }\n            }\n        }\n\n        CommonVars* data_;\n        double shift_;\n        Size size_;\n        std::vector<Real> values_;\n        Array x_;\n        std::vector<Real> drift_;\n        Time t_;\n        std::vector<double> indepDouble_;\n    };\n\n\n    // Struct for plots recording.\n    struct DeltaTimeResult\n    {\n        static std::deque<std::string > get_columns()\n        {\n            static std::deque<std::string > columns =\n            {\n                \"Delta time\", \"\"\n            };\n\n            return columns;\n        }\n\n        template <typename stream_type>\n        friend inline stream_type&\n            operator << (stream_type& stm, DeltaTimeResult& v)\n        {\n                stm << v.deltaTime_\n                    << \";\" << v.result_\n                    << std::endl;\n                return stm;\n            }\n\n        Real deltaTime_;\n        Real result_;\n    };\n\n\n    struct TestDataRespectDeltaTime\n        : public HestonProcessTestData\n    {\n        explicit TestDataRespectDeltaTime(VariableName name)\n        : HestonProcessTestData(name)\n        , outPerform_title_(\"Swaption \" + toString(name) + \" differentiation performance with respect to delta time\")\n        , outAdjoint_title_(\"Swaption \" + toString(name) + \" adjoint differentiation with respect to fixed delta time\")\n        , out_title_(toString(name) + \" dependence on delta time\")\n        , out_ylabel_(toString(name))\n        , outPerform_(OUTPUT_FOLDER_NAME \"//\" + toString(name), {\n            { \"title\", outPerform_title_ }\n            , { \"not_clear\", \"Not\" }\n            , { \"ylabel\", \"Time (s)\" }\n            , { \"xlabel\", \"Number of delta times\" }\n            , { \"line_box_width\", \"-5\" }\n            , { \"cleanlog\", \"true\" }\n            , { \"smooth\", \"default\" }\n        })\n            , outAdjoint_(OUTPUT_FOLDER_NAME \"//\" + toString(name), {\n                { \"title\", outAdjoint_title_ }\n            , { \"filename\", \"Adjoint\" }\n            , { \"not_clear\", \"Not\" }\n            , { \"ylabel\", \"Time (s)\" }\n            , { \"xlabel\", \"Number of delta times\" }\n            , { \"cleanlog\", \"false\" }\n            , { \"smooth\", \"default\" }\n        })\n            , outSize_(OUTPUT_FOLDER_NAME \"//\" + toString(name), {\n                { \"title\", \"Tape size dependence on number of delta time\" }\n            , { \"filename\", \"TapeSize\" }\n            , { \"not_clear\", \"Not\" }\n            , { \"ylabel\", \"Memory (MB)\" }\n            , { \"cleanlog\", \"false\" }\n        })\n\n            , out_(OUTPUT_FOLDER_NAME \"//\" + toString(name) + \"//output\", {\n                { \"filename\", \"DeltaTimeDependence\" }\n            , { \"not_clear\", \"Not\" }\n            , { \"title\", out_title_ }\n            , { \"ylabel\", out_ylabel_ }\n            , { \"xlabel\", \"delta time\" }\n            , { \"cleanlog\", \"false\" }\n        })\n        { }\n\n        bool makeOutput()\n        {\n            bool ok = true;\n\n            if (pointNo > 0)\n            {\n                ok &= recordDependencePlot();\n            }\n            ok &= cl::recordPerformance(*this, iterNo, step);\n\n            return ok;\n        }\n\n\n\n        std::shared_ptr<HestonProcessRespectToDeltaTimeTest> getTest(size_t size)\n        {\n            return std::make_shared<HestonProcessRespectToDeltaTimeTest>(this, size, &outPerform_);\n        }\n\n        // Makes plots for derivative of blackVariance dependence.\n        bool recordDependencePlot()\n        {\n            std::vector<DeltaTimeResult> outData(pointNo);\n            auto test = getTest(pointNo);\n            bool ok = test->testReverse();\n            for (Size i = 0; i < pointNo; i++)\n            {\n                outData[i] = { test->deltaTimes_[i], test->Variables_[i] };\n            }\n\n            out_ << outData;\n            return ok;\n\n            return true;\n        }\n\n        std::string outPerform_title_;\n        std::string outAdjoint_title_;\n        std::string out_title_;\n        std::string out_ylabel_;\n        cl::tape_empty_test_output outPerform_;\n        cl::tape_empty_test_output outAdjoint_;\n        cl::tape_empty_test_output outSize_;\n        cl::tape_empty_test_output out_;\n    };\n\n\n}\n\n#endif", "meta": {"hexsha": "88a830091d5bb9f15b04157e9bd3c44264ba6ab8", "size": 19589, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test-suite-adjoint/adjointhestonprocessimpl.hpp", "max_stars_repo_name": "fduffy/QuantLibAdjoint", "max_stars_repo_head_hexsha": "d9d355db4f46824bb5e607e28381943aef994ed4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 41.0, "max_stars_repo_stars_event_min_datetime": "2016-03-19T02:31:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T13:23:20.000Z", "max_issues_repo_path": "test-suite-adjoint/adjointhestonprocessimpl.hpp", "max_issues_repo_name": "fduffy/QuantLibAdjoint", "max_issues_repo_head_hexsha": "d9d355db4f46824bb5e607e28381943aef994ed4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test-suite-adjoint/adjointhestonprocessimpl.hpp", "max_forks_repo_name": "fduffy/QuantLibAdjoint", "max_forks_repo_head_hexsha": "d9d355db4f46824bb5e607e28381943aef994ed4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2016-03-17T14:14:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T10:33:19.000Z", "avg_line_length": 31.8003246753, "max_line_length": 162, "alphanum_fraction": 0.5694522436, "num_tokens": 4793, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680199891789, "lm_q2_score": 0.6688802537704064, "lm_q1q2_score": 0.49709041380441243}}
{"text": "/**\n * @file tests/hyperplane_test.cpp\n *\n * Tests for Hyperplane and ProjVector implementations.\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#include <mlpack/core.hpp>\n#include <mlpack/core/tree/space_split/hyperplane.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n\nusing namespace mlpack;\nusing namespace mlpack::math;\nusing namespace mlpack::tree;\nusing namespace mlpack::metric;\nusing namespace mlpack::bound;\n\nBOOST_AUTO_TEST_SUITE(HyperplaneTest);\n\n/**\n * Ensure that a hyperplane, by default, consider all points to the left.\n */\nBOOST_AUTO_TEST_CASE(HyperplaneEmptyConstructor)\n{\n  Hyperplane<EuclideanDistance> h1;\n  AxisOrthogonalHyperplane<EuclideanDistance> h2;\n\n  arma::mat dataset;\n  dataset.randu(3, 20); // 20 points in 3 dimensions.\n\n  for (size_t i = 0; i < dataset.n_cols; ++i)\n  {\n    BOOST_REQUIRE(h1.Left(dataset.col(i)));\n    BOOST_REQUIRE(h2.Left(dataset.col(i)));\n    BOOST_REQUIRE(!h1.Right(dataset.col(i)));\n    BOOST_REQUIRE(!h2.Right(dataset.col(i)));\n  }\n}\n\n/**\n * Ensure that we get the correct hyperplane given the projection vector.\n */\nBOOST_AUTO_TEST_CASE(ProjectionTest)\n{\n  // General hyperplane.\n  ProjVector projVect1(arma::vec(\"1 1\"));\n  Hyperplane<EuclideanDistance> h1(projVect1, 0);\n\n  BOOST_REQUIRE_EQUAL(h1.Project(arma::vec(\"1 -1\")), 0);\n  BOOST_REQUIRE(h1.Left(arma::vec(\"1 -1\")));\n  BOOST_REQUIRE(!h1.Right(arma::vec(\"1 -1\")));\n\n  BOOST_REQUIRE_EQUAL(h1.Project(arma::vec(\"-1 1\")), 0);\n  BOOST_REQUIRE(h1.Left(arma::vec(\"-1 1\")));\n  BOOST_REQUIRE(!h1.Right(arma::vec(\"-1 1\")));\n\n  BOOST_REQUIRE_EQUAL(h1.Project(arma::vec(\"1 0\")),\n      h1.Project(arma::vec(\"0 1\")));\n  BOOST_REQUIRE(h1.Right(arma::vec(\"1 0\")));\n  BOOST_REQUIRE(!h1.Left(arma::vec(\"1 0\")));\n\n  BOOST_REQUIRE_EQUAL(h1.Project(arma::vec(\"-1 -1\")),\n      h1.Project(arma::vec(\"-2 0\")));\n  BOOST_REQUIRE(h1.Left(arma::vec(\"-1 -1\")));\n  BOOST_REQUIRE(!h1.Right(arma::vec(\"-1 -1\")));\n\n  // A simple 2-dimensional bound.\n  BallBound<EuclideanDistance> b1(2);\n\n  b1.Center() = arma::vec(\"-1 -1\");\n  b1.Radius() = 1.41;\n  BOOST_REQUIRE(h1.Left(b1));\n  BOOST_REQUIRE(!h1.Right(b1));\n\n  b1.Center() = arma::vec(\"1 1\");\n  b1.Radius() = 1.41;\n  BOOST_REQUIRE(h1.Right(b1));\n  BOOST_REQUIRE(!h1.Left(b1));\n\n  b1.Center() = arma::vec(\"0 0\");\n  b1.Radius() = 1.41;\n  BOOST_REQUIRE(!h1.Right(b1));\n  BOOST_REQUIRE(!h1.Left(b1));\n}\n\n/**\n * Ensure that we get the correct AxisOrthogonalHyperplane given the\n * AxisParallelProjVector.\n */\nBOOST_AUTO_TEST_CASE(AxisOrthogonalProjectionTest)\n{\n  // AxisParallel hyperplane.\n  AxisParallelProjVector projVect2(1);\n  AxisOrthogonalHyperplane<EuclideanDistance> h2(projVect2, 1);\n\n  BOOST_REQUIRE_EQUAL(h2.Project(arma::vec(\"0 0\")), -1);\n  BOOST_REQUIRE(h2.Left(arma::vec(\"0 0\")));\n  BOOST_REQUIRE(!h2.Right(arma::vec(\"0 0\")));\n\n  BOOST_REQUIRE_EQUAL(h2.Project(arma::vec(\"0 1\")), 0);\n  BOOST_REQUIRE(h2.Left(arma::vec(\"0 1\")));\n  BOOST_REQUIRE(!h2.Right(arma::vec(\"0 1\")));\n\n  BOOST_REQUIRE_EQUAL(h2.Project(arma::vec(\"0 2\")), 1);\n  BOOST_REQUIRE(h2.Right(arma::vec(\"0 2\")));\n  BOOST_REQUIRE(!h2.Left(arma::vec(\"0 2\")));\n\n  BOOST_REQUIRE_EQUAL(h2.Project(arma::vec(\"1 2\")), 1);\n  BOOST_REQUIRE(h2.Right(arma::vec(\"1 2\")));\n  BOOST_REQUIRE(!h2.Left(arma::vec(\"1 2\")));\n\n  BOOST_REQUIRE_EQUAL(h2.Project(arma::vec(\"1 0\")), -1);\n  BOOST_REQUIRE(h2.Left(arma::vec(\"1 0\")));\n  BOOST_REQUIRE(!h2.Right(arma::vec(\"1 0\")));\n\n  // A simple 2-dimensional bound.\n  HRectBound<EuclideanDistance> b2(2);\n\n  b2[0] = Range(-1.0, 1.0);\n  b2[1] = Range(-1.0, 1.0);\n  BOOST_REQUIRE(h2.Left(b2));\n  BOOST_REQUIRE(!h2.Right(b2));\n\n  b2[0] = Range(-1.0, 1.0);\n  b2[1] = Range(1.001, 2.0);\n  BOOST_REQUIRE(h2.Right(b2));\n  BOOST_REQUIRE(!h2.Left(b2));\n\n  b2[0] = Range(-1.0, 1.0);\n  b2[1] = Range(0, 2.0);\n  BOOST_REQUIRE(!h2.Right(b2));\n  BOOST_REQUIRE(!h2.Left(b2));\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "748d9577efaacd03aebea55e0b8ad1d2a9d8a0f6", "size": 4090, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/hyperplane_test.cpp", "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/tests/hyperplane_test.cpp", "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/tests/hyperplane_test.cpp", "max_forks_repo_name": "R-Aravind/mlpack", "max_forks_repo_head_hexsha": "99d11a9b4d379885cf7f8160d8c71fb792fa1bbc", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-09-17T21:33:59.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-17T21:33:59.000Z", "avg_line_length": 29.0070921986, "max_line_length": 78, "alphanum_fraction": 0.6782396088, "num_tokens": 1279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680199891789, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.4970904138044124}}
{"text": "/*\n * TriangleElement.hpp\n *\n *  Created on: Nov 18, 2012\n *      Author: petr\n */\n#pragma once\n#ifndef TRIANGLEELEMENT_HPP_\n#define TRIANGLEELEMENT_HPP_\n\n#undef max\n#undef min\n\n#include <cmath>\n#include <limits>\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#include <Eigen/StdVector>\n#include <vector>\n#include <iostream>\n#include \"BoundingBox.hpp\"\n#include \"utility.h\"\n#include \"tribox3.hpp\"\n\n// #include <boost/archive/basic_binary_oarchive.hpp>\n// #include <boost/archive/basic_binary_iarchive.hpp>\n\n\ntemplate<typename type>\nstruct SignedDistance {\n\ttype            dist;\n\ttype            angle;\n\tint             sign;\n\tEigen::Vector3d minPoint;\n};\n\n\ntemplate <typename type>\nclass TriangleElement {\n\n\npublic:\n\n\t/// Stores vertices of an element. \n\t/// This implementation uses triangle element, but in future, there will be support for multiple element types.\n\tstd::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d> > vertices;\n\t\n\t/// Face normal\n\tEigen::Vector3d normal;\n\n\t\n\n\t/// element ID used to identify element\n\tlong int ID;\n\n\tTriangleElement(): ID(-1) {};\n\n\t/// Triangle element contructor, triangle normal is computed automaticaly\n\t/// Normal is computed standard way : n = (v1 - v0) x (v2 - v0), where x is cross product\n\tTriangleElement(Eigen::Vector3d& v0, Eigen::Vector3d& v1, Eigen::Vector3d& v2, long int id);\n\n\tTriangleElement(const Eigen::Vector3d& v) {\n\t\tthis->vertices.reserve(3);\n\n\t\tthis->vertices.push_back(v);\n\t\tthis->vertices.push_back(v);\n\t\tthis->vertices.push_back(v);\n\n\t\tthis->ID = -1;\n\t}\n\n\t/// Constructor to create the triangle element from complete list of vertices with an ID\n\tTriangleElement(std::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d> >& vertices, long int id);\n\n\tTriangleElement(const TriangleElement<type> & element) : vertices(element.vertices), normal(element.normal), ID(element.ID) {};\n\n\t/// Test whether element is inside the rectangular! region\n\tbool isInsideRegion(const Box<type, 3>& bb) const;\n\n\t/// Test whether element is partly inside the rectangular! region\n\tbool isPartlyInRegion(const Box<type, 3>& bb) const;\n\n\t/// Return centroid of element\n\tEigen::Vector3d centroid();\n\n\tstatic SignedDistance<type> computeDistance(const TriangleElement<type>& el, const Eigen::Vector3d& point);\n\n\tstatic type computePerpendicularDistance(const TriangleElement<type>& el, const Eigen::Vector3d& point);\n\n\t/// Return tight Axis Aligned Bounding Box around element\n\tBoundingBox<type, 3, TriangleElement<double> > getBoundingBox() const;\n\n};\n\ntemplate<typename type> \nTriangleElement<type>::TriangleElement(Eigen::Vector3d& v0, Eigen::Vector3d& v1, Eigen::Vector3d& v2, long int id) {\n\n\tthis->vertices.reserve(3);\n\n\tthis->vertices.push_back(v0);\n\tthis->vertices.push_back(v1);\n\tthis->vertices.push_back(v2);\n\n\tEigen::Vector3d e0 = v1 - v0;\n\tEigen::Vector3d e1 = v2 - v0;\n\n\tthis->normal = e0.cross(e1);\n\tthis->normal.normalize();\n\n\tthis->ID = id;\n\n}\n\ntemplate<typename type> \nTriangleElement<type>::TriangleElement(std::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d> >& vertices, long int id) {\n\n\tthis->vertices = vertices;\n\n\tEigen::Vector3d e0 = vertices[1] - vertices[0];\n\tEigen::Vector3d e1 = vertices[2] - vertices[0];\n\n\tthis->normal = e0.cross(e1);\n\tthis->normal.normalize();\n\n\tthis->ID = id;\n\n}\n\ntemplate<typename type> \ninline BoundingBox<type, 3, TriangleElement<double> > TriangleElement<type>::getBoundingBox() const {\n\n\tdouble minX[3], maxX[3];\n\tminX[0] =  std::numeric_limits<type>::max();\n\tminX[1] =  std::numeric_limits<type>::max();\n\tminX[2] =  std::numeric_limits<type>::max();\n\n\tmaxX[0] = -std::numeric_limits<type>::max();\n\tmaxX[1] = -std::numeric_limits<type>::max();\n\tmaxX[2] = -std::numeric_limits<type>::max();\n\n\n\tfor (auto vertex: vertices) {\n\n\t\t// find lower bound\n\t\tif ( vertex[0] < minX[0] ) // for x\n\t\t\tminX[0] = vertex[0];\n\t\tif ( vertex[1] < minX[1] ) // for y\n\t\t\tminX[1] = vertex[1];\n\t\tif ( vertex[2] < minX[2] ) // for z\n\t\t\tminX[2] = vertex[2];\n\n\t\t// find upper bound\n\t\tif ( vertex[0] > maxX[0] ) // for x\n\t\t\tmaxX[0] = vertex[0];\n\t\tif ( vertex[1] > maxX[1] ) // for y\n\t\t\tmaxX[1] = vertex[1];\n\t\tif ( vertex[2] > maxX[2] ) // for z\n\t\t\tmaxX[2] = vertex[2];\n\n\t}\n\n\treturn BoundingBox<type, 3, TriangleElement<double> >(minX, maxX, this);\n\n}\n\ntemplate<typename type> \ninline bool TriangleElement<type>::isInsideRegion(const Box<type, 3>& bb) const {\n\n\tbool vertex_0 = bb.pointInside(vertices[0].array());\n\tbool vertex_1 = bb.pointInside(vertices[1].array());\n\tbool vertex_2 = bb.pointInside(vertices[2].array());\n\t\n\treturn vertex_0 && vertex_1 && vertex_2;\n\n}\n\n\n\n/// \\brief Detects if triangle element collide with cuboid region. Tests for partial collisions\n///        which could pose a tricky problem: long thin triangles, one vertex collision,\n///        one edge collision, edge to edge collision.\n///\n/// The algorithm is taken from book: (Morgan Kaufmann series in  Interactive 3d technology)\n///                                   Realtime collision detection - Christer Ericson\n///\ntemplate<typename type>\ninline bool TriangleElement<type>::isPartlyInRegion(const Box<type, 3>& bb) const {\n\n\tfloat trivert[3][3] = { {(float)vertices[0][0], (float)vertices[0][1], (float)vertices[0][2]},\n\t\t\t\t\t\t\t{(float)vertices[1][0], (float)vertices[1][1], (float)vertices[1][2]},\n\t\t\t\t\t\t\t{(float)vertices[2][0], (float)vertices[2][1], (float)vertices[2][2]}};\n\n\tfloat center[3] = {(float)bb.center(0), (float)bb.center(1), (float)bb.center(2)};\n\n\tfloat extent[3] = {(float)bb.extent(0), (float)bb.extent(1), (float)bb.extent(2)};\n\n\t// utilizes code I found on the internet, check the functionality\n\treturn triBoxOverlap(center, extent, trivert);\n\n}\n\ntemplate<typename type> \ninline SignedDistance<type> TriangleElement<type>::computeDistance(const TriangleElement<type>& el, const Eigen::Vector3d &point) {\n\t// point is supposed to have right dimension, so do it nice and clear :)\n\t// this function computed the distance between triangle element and point in 3D\n\t// complete description of a method could be found here :\n\t//  \thttp://www.geometrictools.com/Documentation/DistancePoint3Triangle3.pdf\n\t// sample implementation could be found here :\n\t//\t\thttp://www.geometrictools.com/LibMathematics/Distance/Wm5DistPoint3Triangle3.cpp\n\t// and here :\n\t// \t\thttp://www.mathworks.com/matlabcentral/fileexchange/22857-distance-between-a-point-and-a-triangle-in-3d/\n\n\t//double E0[3] = {el.vertex_x[1] - el.vertex_x[0], el.vertex_y[1] - el.vertex_y[0], el.vertex_z[1] - el.vertex_z[0]};\n\t//double E1[3] = {el.vertex_x[2] - el.vertex_x[0], el.vertex_y[2] - el.vertex_y[0], el.vertex_z[2] - el.vertex_z[0]};\n\n\tEigen::Vector3d E0 = el.vertices[1] - el.vertices[0];\n\tEigen::Vector3d E1 = el.vertices[2] - el.vertices[0];\n\n\t//double D[3]  = {el.vertex_x[0] - point[0], el.vertex_y[0] - point[1], el.vertex_z[0] - point[2]};\n\n\tEigen::Vector3d D = el.vertices[0] - point;\n\n//\tdouble a00_ = E0[0]*E0[0] + E0[1]*E0[1] + E0[2]*E0[2];\n\ttype a00 = E0.dot(E0);\n\t\n//\tstd::cout << (a00_ - a00) << std::endl;\n\n//\tdouble a01_ = E0[0]*E1[0] + E0[1]*E1[1] + E0[2]*E1[2];\n\ttype a01 = E0.dot(E1);\n\n//\tstd::cout << (a01_ - a01) << std::endl;\n\n//\tdouble a11_ = E1[0]*E1[0] + E1[1]*E1[1] + E1[2]*E1[2];\n\ttype a11 = E1.dot(E1);\n\t\n//\tstd::cout << (a11_ - a11) << std::endl;\n\n//\tdouble b0_  = E0[0]*D[0]  + E0[1]*D[1]  + E0[2]*D[2];\n\ttype b0 = E0.dot(D);\n\n//\tstd::cout << (b0_ - b0) << std::endl;\n\n//\tdouble b1_  = E1[0]*D[0]  + E1[1]*D[1]  + E1[2]*D[2];\n\ttype b1 = E1.dot(D);\n\n//\tstd::cout << (b0_ - b0) << std::endl;\n\n//\tdouble c_   = D[0]*D[0]   + D[1]*D[1]   + D[2]*D[2];\n\ttype c = D.dot(D);\n\n//\tstd::cout << (c_ - c) << std::endl;\n\n\ttype det = std::abs(a00*a11 - a01*a01);\n\n\ttype s   = a01*b1 - a11*b0;\n\ttype t   = a01*b0 - a00*b1;\n\n\ttype sqrDistance = 0;\n\n\n\tif ( (s+t) <= det ) {\n\t\tif ( s < 0 ) {\n\t\t\tif ( t < 0 ) {\n\t\t\t\t// region 4\n\t\t\t\tif ( b0 < 0 ) {\n\t\t\t\t\tt = 0;\n\t\t\t\t\tif ( -b0 >= a00 ) {\n\t\t\t\t\t\ts = 1;\n\t\t\t\t\t\tsqrDistance = a00 + 2*b0 + c;\n\t\t\t\t\t} else {\n\t\t\t\t\t\ts = -b0/a00;\n\t\t\t\t\t\tsqrDistance = b0*s + c;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\ts = 0;\n\t\t\t\t\tif ( b1 >= 0 ) {\n\t\t\t\t\t\tt = 0;\n\t\t\t\t\t\tsqrDistance = c;\n\t\t\t\t\t} else if ( -b1 >= a11 ) {\n\t\t\t\t\t\tt = 1;\n\t\t\t\t\t\tsqrDistance = a11 + 2*b1 + c;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tt = -b1/a11;\n\t\t\t\t\t\tsqrDistance = b1*t + c;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// end of region 4\n\t\t\t} else {\n\t\t\t\t// region 3\n\t\t\t\ts = 0;\n\t\t\t\tif ( b1 >= 0 ) {\n\t\t\t\t\tt = 0;\n\t\t\t\t\tsqrDistance = c;\n\t\t\t\t} else if ( -b1 >= a11 ) {\n\t\t\t\t\tt = 1;\n\t\t\t\t\tsqrDistance = a11 + 2*b1 + c;\n\t\t\t\t} else {\n\t\t\t\t\tt = -b1/a11;\n\t\t\t\t\tsqrDistance = b1*t + c;\n\t\t\t\t}\n\t\t\t\t// end of region 3\n\t\t\t}\n\t\t} else if ( t < 0) {\n\t\t\t// region 5\n\t\t\tt = 0;\n\t\t\tif ( b0 >= 0 ) {\n\t\t\t\ts = 0;\n\t\t\t\tsqrDistance = c;\n\t\t\t} else if ( -b0 >= a00 ) {\n\t\t\t\ts = 1;\n\t\t\t\tsqrDistance = a00 + 2*b0 + c;\n\t\t\t} else {\n\t\t\t\ts = -b0/a00;\n\t\t\t\tsqrDistance = b0*s + c;\n\t\t\t}\n\t\t\t// end of region 5\n\t\t} else {\n\t\t\t// region 0\n\t\t\tdouble invDet = 1 / det;\n\t\t\ts *= invDet;\n\t\t\tt *= invDet;\n\t\t\tsqrDistance = s*(a00*s + a01*t + 2*b0) + t*(a01*s + a11*t + 2*b1) + c;\n\t\t\t// end of region 0\n\t\t}\n\t} else {\n\t\tif ( s < 0 ) {\n\t\t\t// region 2\n\t\t\tdouble tmp0 = a01 + b0;\n\t\t\tdouble tmp1 = a11 + b1;\n\t\t\tif ( tmp1 > tmp0 ) { // minimum on edge s+t=1\n\t\t\t\tdouble numer = tmp1 - tmp0;\n\t\t\t\tdouble denom = a00 - 2*a01 + a11;\n\t\t\t\tif ( numer >= denom ) {\n\t\t\t\t\ts = 1;\n\t\t\t\t\tt = 0;\n\t\t\t\t\tsqrDistance = a00 + 2*b0 + c;\n\t\t\t\t} else {\n\t\t\t\t\ts = numer/denom;\n\t\t\t\t\tt = 1 - s;\n\t\t\t\t\tsqrDistance = s*(a00*s + a01*t + 2*b0) + t*(a01*s + a11*t + 2*b1) + c;\n\t\t\t\t}\n\t\t\t} else { // minimum on edge s=0\n\t\t\t\ts = 0;\n\t\t\t\tif ( tmp1 <= 0 ) {\n\t\t\t\t\tt = 1;\n\t\t\t\t\tsqrDistance = a11 + 2*b1 + c;\n\t\t\t\t} else if ( b1 >= 0 ) {\n\t\t\t\t\tt = 0;\n\t\t\t\t\tsqrDistance = c;\n\t\t\t\t} else {\n\t\t\t\t\tt = -b1/a11;\n\t\t\t\t\tsqrDistance = b1*t + c;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// end of region 2\n\t\t} else if ( t < 0 ) {\n\t\t\t// region 6\n\t\t\tdouble tmp0 = a01 + b1;\n\t\t\tdouble tmp1 = a00 + b0;\n\t\t\tif ( tmp1 > tmp0 ) {\n\t\t\t\tdouble numer = tmp1 - tmp0;\n\t\t\t\tdouble denom = a00 - 2*a01 + a11;\n\t\t\t\tif ( numer >= denom ) {\n\t\t\t\t\tt = 1;\n\t\t\t\t\ts = 0;\n\t\t\t\t\tsqrDistance = a11 + 2*b1 + c;\n\t\t\t\t} else {\n\t\t\t\t\tt = numer/denom;\n\t\t\t\t\ts = 1 - t;\n\t\t\t\t\tsqrDistance = s*(a00*s + a01*t + 2*b0) + t*(a01*s + a11*t + 2*b1) + c;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tt = 0;\n\t\t\t\tif ( tmp1 <= 0 ) {\n\t\t\t\t\ts = 1;\n\t\t\t\t\tsqrDistance = a00 + 2*b0 + c;\n\t\t\t\t} else if ( b0 >= 0 ) {\n\t\t\t\t\ts = 0;\n\t\t\t\t\tsqrDistance = c;\n\t\t\t\t} else {\n\t\t\t\t\ts = -b0/a00;\n\t\t\t\t\tsqrDistance = b0*s + c;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// end of region 6\n\t\t} else {\n\t\t\t// region 1\n\t\t\tdouble numer = a11 + b1 - a01 - b0;\n\t\t\tif ( numer <= 0 ) {\n\t\t\t\ts = 0;\n\t\t\t\tt = 1;\n\t\t\t\tsqrDistance = a11 + 2*b1 + c;\n\t\t\t} else {\n\t\t\t\tdouble denom = a00 - 2*a01 + a11;\n\t\t\t\tif ( numer >= denom ) {\n\t\t\t\t\ts = 1;\n\t\t\t\t\tt = 0;\n\t\t\t\t\tsqrDistance = a00 + 2*b0 + c;\n\t\t\t\t} else {\n\t\t\t\t\ts = numer / denom;\n\t\t\t\t\tt = 1 - s;\n\t\t\t\t\tsqrDistance = s*(a00*s + a01*t + 2*b0) + t*(a01*s + a11*t + 2*b1) + c;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// end of region 1\n\t\t}\n\t}\n\n\tdouble eeps = my_eps;\n\n\tif (sqrDistance <= eeps)\n\t\tsqrDistance = 0.0;\n\n\tSignedDistance<type> dist;\n\n\tdist.dist = std::sqrt(sqrDistance);\n\n\tdist.minPoint = el.vertices[0] + s*E0 + t*E1;\n\n//\tdist.minPoint[0] = (el.vertex_x[0] + s*E0[0] + t*E1[0]);\n//\tdist.minPoint[1] = (el.vertex_y[0] + s*E0[1] + t*E1[1]);\n//\tdist.minPoint[2] = (el.vertex_z[0] + s*E0[2] + t*E1[2]);\n\n\n//\tdouble PP0[3] = { point[0] - dist.minPoint[0],\n//\t\t\t\t\t  point[1] - dist.minPoint[1],\n//\t\t\t\t\t  point[2] - dist.minPoint[2] };\n\n//\tdouble nrm = sqrt(PP0[0]*PP0[0] + PP0[1]*PP0[1] + PP0[2]*PP0[2]);\n\n\t// compute on which side of the triangle we are\n\tEigen::Vector3d PP0 = point - dist.minPoint;\n\t\n\tif ( PP0.isZero(eeps) ) {\n\t\t// PP0 = Eigen::Vector3d::Zero();\n\t} else {\n\t\tPP0.normalize();\n\t}\n\n\n\t//double nrm_normal = sqrt(el.normal_x*el.normal_x + el.normal_y*el.normal_y + el.normal_z*el.normal_z);\n\n//\tdouble dprod = (el.normal_x/nrm_normal) * (PP0[0]/nrm) +\n//\t\t\t\t   (el.normal_y/nrm_normal) * (PP0[1]/nrm) +\n//\t\t\t\t   (el.normal_z/nrm_normal) * (PP0[2]/nrm);\n\n\n\n\ttype dprod = el.normal.dot(PP0);\n\n//\tstd::cout << el.normal.transpose() << \" DOT \" << PP0.transpose() << \" = \" << dprod << std::endl;\n\n\tint sgn = 0;\n\tif (dprod > eeps)\n\t\tsgn = 1;\n\telse if (dprod < -eeps)\n\t\tsgn = -1;\n\n\tdist.angle = dprod;\n\tdist.sign  = sgn;\n\n\treturn dist;\n\n}\n\ntemplate<typename type>\ninline Eigen::Vector3d TriangleElement<type>::centroid() {\n\n\tEigen::Vector3d c;\n\n\tfor (auto vertex: vertices) {\n\t\tc += vertex;\n\t}\n\n\treturn c*(1.0/3.0);\n\n}\n\ntemplate<typename type> \ninline type TriangleElement<type>::computePerpendicularDistance(const TriangleElement& el, const Eigen::Vector3d& point) {\n\t// compute projection onto surface defined by the triangle element\n\tEigen::Vector3d vec;\n\tvec << point - el.vertices[0];\n\t\n\ttype ortDist = std::abs( vec.dot(el.normal) );\n\t\n\treturn ortDist;\n}\n\n\n// ostream operators\n\ntemplate <typename type>\nstd::ostream& operator<<(std::ostream& os, const TriangleElement<type>& el) {\n\tos << \"vert_0: \" << el.vertices[0].transpose() << std::endl;\n\tos << \"vert_1: \" << el.vertices[1].transpose() << std::endl;\n\tos << \"vert_2: \" << el.vertices[2].transpose() << std::endl;\n\tos << \"normal: \" << el.normal.transpose();\n\n    return os;\n}\n\n\n\n\n\nstruct TriangleCompare {\n\n\tbool operator() (spatial::dimension_type dim, const TriangleElement<double>& a, const TriangleElement<double>& b) const {\n\n\t\tswitch (dim) {\n\t\t\tcase 0:\n//\t\t\t\ta.vertices[0]\n\t\t\t\treturn (a.vertices[0][0] < b.vertices[0][0]) &&\n\t\t\t\t\t   (a.vertices[1][0] < b.vertices[1][0]) &&\n\t\t\t\t\t   (a.vertices[2][0] < b.vertices[2][0]);\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\treturn (a.vertices[0][1] < b.vertices[0][1]) &&\n\t\t\t\t\t   (a.vertices[1][1] < b.vertices[1][1]) &&\n\t\t\t\t\t   (a.vertices[2][1] < b.vertices[2][1]);\n//\t\t\t\treturn (a._tr[0] < b._tr[0]);\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\treturn (a.vertices[0][2] < b.vertices[0][2]) &&\n\t\t\t\t\t   (a.vertices[1][2] < b.vertices[1][2]) &&\n\t\t\t\t\t   (a.vertices[2][2] < b.vertices[2][2]);\n//\t\t\t\treturn (a._bl[1] < b._bl[1]);\n\t\t\t\tbreak;\n\n\t\t}\n\n\t\treturn false;\n\t}\n\n};\n\nstruct TrianglePredicate {\n\tconst Box<double, 3>& box;\n\n\tTrianglePredicate(const Box<double, 3>& b) : box(b) {}\n\n\tspatial::relative_order\n\toperator() (spatial::dimension_type dim, spatial::dimension_type, const TriangleElement<double>& t ) const {\n\n\t\tBox<double, 3> b = t.getBoundingBox();\n\n\t\tswitch (dim) {\n\t\t\tcase 0:\n\t\t\t\treturn (b._bl[0] > box._tr[0] && b._tr[0] > box._tr[0]) ? spatial::above :\n\t\t\t\t\t   (b._tr[0] < box._bl[0] && b._bl[0] < box._bl[0]) ? spatial::below :\n\t\t\t\t\t\tspatial::matching;\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\treturn (b._bl[1] > box._tr[1] && b._tr[1] > box._tr[1]) ? spatial::above :\n\t\t\t\t\t   (b._tr[1] < box._bl[1] && b._bl[1] < box._bl[1]) ? spatial::below :\n\t\t\t\t\t\tspatial::matching;\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\treturn (b._bl[2] > box._tr[2] && b._tr[2] > box._tr[2]) ? spatial::above :\n\t\t\t\t\t   (b._tr[2] < box._bl[2] && b._bl[2] < box._bl[2]) ? spatial::below :\n\t\t\t\t\t\tspatial::matching;\n\t\t\t\tbreak;\n\t\t}\n\n\t}\n};\n\nstruct TriangleMetric {\n    // Check that DistanceType is a fundamental floating point type\n    typedef double distance_type;\n\n\n    /**\n     *  Compute the distance between the point of \\c origin and the \\c key.\n     *  \\return The resulting square distance.\n     */\n    distance_type\n    distance_to_key(spatial::dimension_type rank,\n                    const TriangleElement<double>& origin,\n                    const TriangleElement<double>& key) const {\n\n    \tdistance_type result = distance_type(0.0);\n\n//    \tstd::cout << \"===============================================\" << std::endl;\n//    \tstd::cout << origin << std::endl;\n//    \tstd::cout << \"--------------\" << std::endl;\n//    \tstd::cout << key << std::endl;\n//    \tstd::cout << \"--------------\" << std::endl;\n\n    \tEigen::Array3d co = (origin.vertices[0] + origin.vertices[1] + origin.vertices[2]).array() / 3.0;\n    \tEigen::Array3d ck = (key.vertices[0] + key.vertices[1] + key.vertices[2]).array() / 3.0;\n    \t\n    \t// distance_type tmp = 0.0\n    \t\n\t\tfor (int ii = 0; ii < 3; ++ii) {\n\t\t\tdouble d = std::numeric_limits<double>::max();\n\t\t\tfor (spatial::dimension_type i = 0; i < rank; ++i) {\n\t\t\t\tdouble tmp = std::abs( key.vertices[i][ii] - origin.vertices[i][ii] );\n\t\t\t\td = (tmp < d) ? tmp : d;\n\t\t\t}\n\n\t\t\tresult += d * d;\n\t\t}\n    \t\n//    \tstd::cout << \"dist = \" << result << std::endl;\n//    \tstd::cout << \"===============================================\" << std::endl;\n    \treturn result;\n\n    }\n\n    /**\n     *  The distance between the point of \\c origin and the closest point to\n     *  the plane orthogonal to the axis of dimension \\c dim and crossing \\c\n     *  key.\n     *  \\return The resulting square distance.\n     */\n    distance_type\n    distance_to_plane(spatial::dimension_type,\n    \t\t\t      spatial::dimension_type dim,\n                      const TriangleElement<double>& origin,\n                      const TriangleElement<double>& key) const {\n\n    \tdistance_type d = std::numeric_limits<double>::max();\n\t\tfor (spatial::dimension_type i = 0; i < 3; ++i) {\n\t\t\tdouble tmp = std::abs( key.vertices[i][dim] - origin.vertices[i][dim] );\n\t\t\td = (tmp < d) ? tmp : d;\n\t\t}\n\t\t    \t\n\t\treturn d * d;\n\n    }\n\n\n};\n\n\n\n\n\n\n\n\n\n\n\n#endif /* TRIANGLEELEMENT_HPP_ */\n", "meta": {"hexsha": "5acd08633347ceb2d51a658f11907eed242b7d7a", "size": 16944, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/TriangleElement.hpp", "max_stars_repo_name": "petrkotas/libLS", "max_stars_repo_head_hexsha": "eb57365bfb0be486a4e8c564ff831ad358993268", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/TriangleElement.hpp", "max_issues_repo_name": "petrkotas/libLS", "max_issues_repo_head_hexsha": "eb57365bfb0be486a4e8c564ff831ad358993268", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/TriangleElement.hpp", "max_forks_repo_name": "petrkotas/libLS", "max_forks_repo_head_hexsha": "eb57365bfb0be486a4e8c564ff831ad358993268", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.1481481481, "max_line_length": 137, "alphanum_fraction": 0.5865203022, "num_tokens": 5651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.49709041110012037}}
{"text": "#include <pybind11/pybind11.h>\n#include <pybind11/eigen.h>\n#include <Eigen/Dense>\n\nnamespace py=pybind11;\ntypedef Eigen::MatrixXd Matrix;\ntypedef Eigen::VectorXd Vector;\n\nEigen::Ref<Matrix> distance_table(\n  Eigen::Ref<const Matrix>& pos, double lbox)\n{\n  const int natom = pos.rows();\n  const int ndim = pos.cols();\n  Matrix dtable = Matrix::Zero(natom, natom);\n  Vector drij(ndim);\n  for (int i=0;i<natom;i++)\n  {\n    for (int j=i; j<natom; j++)\n    {\n      drij = pos.row(i) - pos.row(j);\n      for (int idim=0;idim<ndim;idim++)\n      {\n        drij(idim) -= lbox*std::round(drij(idim)/lbox);\n      }\n      dtable(i, j) = drij.norm();\n    }\n  }\n  return dtable;\n}\n\nPYBIND11_MODULE(example, m)\n{\n  //m.def(\"distance_table\", &distance_table, \"PBC distances\");\n  m.def(\"distance_table\", &distance_table, \"PBC distances\",\n        py::return_value_policy::reference_internal);\n}\n", "meta": {"hexsha": "f468fd6821dc570215883c0476b87125f370e794", "size": 877, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "4_dtable/cpplib/example.cpp", "max_stars_repo_name": "Paul-St-Young/thw-python-as-glue", "max_stars_repo_head_hexsha": "491fab54eaa5a621a9641c15a121be49097add5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-04-17T17:03:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-17T17:03:12.000Z", "max_issues_repo_path": "4_dtable/cpplib/example.cpp", "max_issues_repo_name": "Paul-St-Young/thw-python-as-glue", "max_issues_repo_head_hexsha": "491fab54eaa5a621a9641c15a121be49097add5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "4_dtable/cpplib/example.cpp", "max_forks_repo_name": "Paul-St-Young/thw-python-as-glue", "max_forks_repo_head_hexsha": "491fab54eaa5a621a9641c15a121be49097add5b", "max_forks_repo_licenses": ["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.7027027027, "max_line_length": 62, "alphanum_fraction": 0.6374002281, "num_tokens": 266, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743167997235783, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.4970904083958278}}
{"text": "#include <QTime>\n#include <QApplication>\n#include <QAction>\n#include <QMainWindow>\n#include <QStringList>\n\n#include \"opengl_tools.h\"\n#include \"Scene_polyhedron_item.h\"\n#include \"Scene_surface_mesh_item.h\"\n#include \"Scene_points_with_normal_item.h\"\n#include \"Scene_polylines_item.h\"\n#include \"Scene_polyhedron_selection_item.h\"\n#include \"Polyhedron_type.h\"\n\n#include <CGAL/Three/Polyhedron_demo_plugin_interface.h>\n\n#include <CGAL/convex_hull_3.h>\n#include <CGAL/boost/graph/copy_face_graph.h>\n#include <boost/iterator/transform_iterator.hpp>\nusing namespace CGAL::Three;\nclass Polyhedron_demo_convex_hull_plugin : \n  public QObject,\n  public Polyhedron_demo_plugin_interface\n{\n  Q_OBJECT\n  Q_INTERFACES(CGAL::Three::Polyhedron_demo_plugin_interface)\n  Q_PLUGIN_METADATA(IID \"com.geometryfactory.PolyhedronDemo.PluginInterface/1.0\")\npublic:\n    void init(QMainWindow*mw,\n              Scene_interface* scene_interface,\n              Messages_interface*)\n    {\n        scene = scene_interface;\n        this->mw = mw;\n        QAction *actionConvexHull = new QAction(\"Convex Hull\", mw);\n        actionConvexHull->setProperty(\"subMenuName\",\"3D Convex Hulls\");\n        connect(actionConvexHull, SIGNAL(triggered()), this, SLOT(on_actionConvexHull_triggered()));\n        _actions <<actionConvexHull;\n    }\n\n  QList<QAction*> actions()const {return _actions;}\n\n  bool applicable(QAction*) const {\n    return \n      qobject_cast<Scene_polyhedron_item*>(scene->item(scene->mainSelectionIndex())) ||\n      qobject_cast<Scene_surface_mesh_item*>(scene->item(scene->mainSelectionIndex())) ||\n      qobject_cast<Scene_polylines_item*>(scene->item(scene->mainSelectionIndex())) ||\n      qobject_cast<Scene_points_with_normal_item*>(scene->item(scene->mainSelectionIndex())) ||\n      qobject_cast<Scene_polyhedron_selection_item*>(scene->item(scene->mainSelectionIndex()));\n  }\n\npublic Q_SLOTS:\n  void on_actionConvexHull_triggered();\nprivate:\n  QList<QAction*> _actions;\n  Scene_interface* scene;\n  QMainWindow* mw;\n}; // end Polyhedron_demo_convex_hull_plugin\n\n// for transform iterator\nstruct Get_point {\n  typedef const Polyhedron::Point_3& result_type;\n  result_type operator()(const Polyhedron::Vertex_handle v) const\n  { return v->point(); }\n};\n\nvoid Polyhedron_demo_convex_hull_plugin::on_actionConvexHull_triggered()\n{\n  const CGAL::Three::Scene_interface::Item_id index = scene->mainSelectionIndex();\n  \n  Scene_polyhedron_item* poly_item = \n    qobject_cast<Scene_polyhedron_item*>(scene->item(index));\n\n  Scene_points_with_normal_item* pts_item =\n    qobject_cast<Scene_points_with_normal_item*>(scene->item(index));\n  \n  Scene_polylines_item* lines_item = \n    qobject_cast<Scene_polylines_item*>(scene->item(index));\n  \n  Scene_polyhedron_selection_item* selection_item = \n    qobject_cast<Scene_polyhedron_selection_item*>(scene->item(index));\n\n  Scene_surface_mesh_item* sm_item = \n    qobject_cast<Scene_surface_mesh_item*>(scene->item(index));\n\n  if(poly_item || pts_item || lines_item || selection_item || sm_item)\n  {\n    // wait cursor\n    QApplication::setOverrideCursor(Qt::WaitCursor);\n    \n    QTime time;\n    time.start();\n    std::cout << \"Convex hull...\";\n\n    // add convex hull as new polyhedron\n    SMesh *pConvex_hull  = new SMesh;\n    if(selection_item) {\n      CGAL::convex_hull_3(\n        boost::make_transform_iterator(selection_item->selected_vertices.begin(), Get_point()),\n        boost::make_transform_iterator(selection_item->selected_vertices.end(), Get_point()),\n        *pConvex_hull);\n    }\n    else if ( poly_item ){\n      Polyhedron* pMesh = poly_item->polyhedron();  \n      CGAL::convex_hull_3(pMesh->points_begin(),pMesh->points_end(),*pConvex_hull);\n    }\n    else if ( sm_item ){\n      SMesh* pMesh = sm_item->polyhedron();\n      typedef boost::property_map<SMesh,CGAL::vertex_point_t>::type Vpmap;\n      \n      typedef CGAL::Property_map_to_unary_function<Vpmap> Vpmap_fct;\n      Vpmap vpm = get(CGAL::vertex_point,*pMesh);\n      \n      Vpmap_fct v2p(vpm);\n      boost::graph_traits<SMesh>::vertex_iterator b,e;\n      boost::tie(b,e) = vertices(*pMesh);\n      \n      CGAL::convex_hull_3(boost::make_transform_iterator(b,v2p),\n                          boost::make_transform_iterator(e,v2p),\n                          *pConvex_hull);\n                          \n    }\n    else{\n      if (pts_item)\n        CGAL::convex_hull_3(pts_item->point_set()->points().begin(),\n                            pts_item->point_set()->points().end(),\n                            *pConvex_hull);\n      else{\n        std::size_t nb_points=0;\n        for(std::list<std::vector<Kernel::Point_3> >::const_iterator it = lines_item->polylines.begin();\n            it != lines_item->polylines.end();\n            ++it)  nb_points+=it->size();\n\n        std::vector<Kernel::Point_3> all_points;\n        all_points.reserve( nb_points );\n\n        for(std::list<std::vector<Kernel::Point_3> >::const_iterator it = lines_item->polylines.begin();\n            it != lines_item->polylines.end();\n            ++it)  std::copy(it->begin(), it->end(),std::back_inserter( all_points ) );\n        \n        CGAL::convex_hull_3(all_points.begin(),all_points.end(),*pConvex_hull);\n      }\n    }\n    std::cout << \"ok (\" << time.elapsed() << \" ms)\" << std::endl;\n\n    if(mw->property(\"is_polyhedron_mode\").toBool()){\n      Polyhedron *poly = new Polyhedron;\n      CGAL::copy_face_graph(*pConvex_hull,*poly);\n      delete pConvex_hull;\n\n      Scene_polyhedron_item* new_item = new Scene_polyhedron_item(poly);\n      new_item->setName(tr(\"%1 (convex hull)\").arg(scene->item(index)->name()));\n      new_item->setColor(Qt::magenta);\n      new_item->setRenderingMode(FlatPlusEdges);\n      scene->addItem(new_item);\n    } else {\n       Scene_surface_mesh_item* new_item = new Scene_surface_mesh_item(pConvex_hull);\n       new_item->setName(tr(\"%1 (convex hull)\").arg(scene->item(index)->name()));\n       new_item->setColor(Qt::magenta);\n       new_item->setRenderingMode(FlatPlusEdges);\n       scene->addItem(new_item);\n    }\n\n    // default cursor\n    QApplication::restoreOverrideCursor();\n  }\n\n\n}\n\n#include \"Convex_hull_plugin.moc\"\n", "meta": {"hexsha": "5d2e487337e4c1bdb9aa7cf145f2c1b7343181a4", "size": 6118, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ext/libigl/external/cgal/src/CGAL_Project/demo/Polyhedron/Plugins/Convex_hull/Convex_hull_plugin.cpp", "max_stars_repo_name": "liminchen/OptCuts", "max_stars_repo_head_hexsha": "cb85b06ece3a6d1279863e26b5fd17a5abb0834d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 187.0, "max_stars_repo_stars_event_min_datetime": "2019-01-23T04:07:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T03:44:58.000Z", "max_issues_repo_path": "ext/libigl/external/cgal/src/CGAL_Project/demo/Polyhedron/Plugins/Convex_hull/Convex_hull_plugin.cpp", "max_issues_repo_name": "xiaoxie5002/OptCuts", "max_issues_repo_head_hexsha": "1f4168fc867f47face85fcfa3a572be98232786f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-03-22T13:27:38.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-18T13:23:23.000Z", "max_forks_repo_path": "ext/libigl/external/cgal/src/CGAL_Project/demo/Polyhedron/Plugins/Convex_hull/Convex_hull_plugin.cpp", "max_forks_repo_name": "xiaoxie5002/OptCuts", "max_forks_repo_head_hexsha": "1f4168fc867f47face85fcfa3a572be98232786f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 34.0, "max_forks_repo_forks_event_min_datetime": "2019-02-13T01:11:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T03:29:40.000Z", "avg_line_length": 35.5697674419, "max_line_length": 104, "alphanum_fraction": 0.6829029094, "num_tokens": 1556, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.49709040128940746}}
{"text": "#include <boost/program_options.hpp>\n#include <PDBClient.h>\n#include <GenericWork.h>\n#include \"sharedLibraries/headers/MatrixBlock.h\"\n#include \"sharedLibraries/headers/MatrixScanner.h\"\n#include \"sharedLibraries/headers/MatrixMultiplyJoin.h\"\n#include \"sharedLibraries/headers/MatrixMultiplyAggregation.h\"\n#include \"sharedLibraries/headers/MatrixWriter.h\"\n\nusing namespace pdb;\nusing namespace pdb::matrix;\nnamespace po = boost::program_options;\n\nvoid initMatrix(\n    pdb::PDBClient &pdbClient,\n    const std::string &set,\n    const size_t &blockSize,\n    const uint32_t &matrixRows,\n    const uint32_t &matrixColumns,\n    const uint32_t &numRows,\n    const uint32_t &numCols) {\n  // A matrix consists of numRows x numCols grid of chunks and each\n  // chunk consists of the appropriate number of values to make the whole\n  // matrix matrixRows x matrixColumns.\n\n  // For each chunk, add the MatrixBlocks. Once the allocation block is full\n  // or the all MatrixBlocks have been created, send the data to pdbClient.\n  uint32_t numChunks = numRows*numCols;\n  uint32_t chunk = 0;\n  while(chunk != numChunks) {\n\n    // make the allocation block\n    const pdb::UseTemporaryAllocationBlock tempBlock{blockSize * 1024 * 1024};\n\n    // put the chunks here\n    Handle<Vector<Handle<MatrixBlock>>> data = pdb::makeObject<Vector<Handle<MatrixBlock>>>();\n\n    try {\n      for(; chunk != numChunks; chunk++) {\n        uint32_t r = chunk % numRows;\n        uint32_t c = chunk / numRows;\n\n        uint32_t numRowsInChunk = matrixRows    / numRows + (r < matrixRows    % numRows ? 1 : 0);\n        uint32_t numColsInChunk = matrixColumns / numCols + (c < matrixColumns % numCols ? 1 : 0);\n\n        // allocate a matrix block\n        Handle<MatrixBlock> myInt = makeObject<MatrixBlock>(r, c, numRowsInChunk, numColsInChunk);\n\n        // init the values\n        float *vals = myInt->data->data->c_ptr();\n        for (int v = 0; v < numRowsInChunk*numColsInChunk; ++v) {\n          vals[v] = 1.0f * (float) v;\n        }\n\n        data->push_back(myInt);\n      }\n    } catch (pdb::NotEnoughSpace &n) {\n    }\n\n    // init the records\n    getRecord(data);\n\n    // send the data\n    pdbClient.sendData<MatrixBlock>(\"myData\", set, data);\n  }\n}\n\nvoid printMatrix(\n    pdb::PDBClient& pdbClient,\n    std::string const& dbName,\n    std::string const& setName) {\n\n  auto it = pdbClient.getSetIterator<MatrixBlock>(dbName, setName);\n\n  while(it->hasNextRecord()) {\n\n        // grab the record\n        auto r = it->getNextRecord();\n\n        // write out the values\n        float *values = r->data->data->c_ptr();\n        for(int i = 0; i < r->data->numRows; ++i) {\n            for(int j = 0; j < r->data->numCols; ++j) {\n                std::cout << values[i * r->data->numCols + j] << \", \";\n            }\n            std::cout << \"\\n\";\n        }\n\n        std::cout << \"\\n\\n\";\n    }\n}\n\nint main(int argc, char* argv[]) {\n\n  po::options_description desc{\"Options\"};\n\n  size_t blockSize;\n  uint32_t matrixRowsA, matrixRowsB, matrixColumnsB;\n  uint32_t numRowsA, numRowsB, numColumnsB;\n\n  // specify the options\n  desc.add_options()(\"help,h\", \"Help screen\");\n  desc.add_options()(\"blockSize\", po::value<size_t>(&blockSize)->default_value(1024),\n      \"Block size for allocation\");\n  desc.add_options()(\"matrixRowsA\", po::value<uint32_t>(&matrixRowsA)->default_value(10000),\n      \"Number of rows in matrix A\");\n  desc.add_options()(\"matrixRowsB\", po::value<uint32_t>(&matrixRowsB)->default_value(10000),\n      \"Number of columns in matrix A and number of rows in matrix B\");\n  desc.add_options()(\"matrixColumnsB\", po::value<uint32_t>(&matrixColumnsB)->default_value(10000),\n      \"Number of columns in matrix B\");\n  desc.add_options()(\"numRowsA\", po::value<uint32_t>(&numRowsA)->default_value(200),\n      \"Number of rows in each chunk of matrix A\");\n  desc.add_options()(\"numRowsB\", po::value<uint32_t>(&numRowsB)->default_value(200),\n      \"Number of columns in each chunk of matrix A and number of rows in each chunk of matrix B\");\n  desc.add_options()(\"numColumnsB\", po::value<uint32_t>(&numColumnsB)->default_value(200),\n      \"Number of columns in each chunk of matrix B\");\n\n  // grab the options\n  po::variables_map vm;\n  store(parse_command_line(argc, argv, desc), vm);\n  notify(vm);\n\n  // did somebody ask for help?\n  if (vm.count(\"help\")) {\n    std::cout << desc << '\\n';\n    return 0;\n  }\n\n  // make a client\n  pdb::PDBClient pdbClient(8108, \"localhost\");\n\n  /// 1. Register the classes\n\n  // now, register a type for user data\n  pdbClient.registerType(\"libraries/libMatrixBlock.so\");\n  pdbClient.registerType(\"libraries/libMatrixBlockData.so\");\n  pdbClient.registerType(\"libraries/libMatrixBlockMeta.so\");\n  pdbClient.registerType(\"libraries/libMatrixMultiplyAggregation.so\");\n  pdbClient.registerType(\"libraries/libMatrixMultiplyJoin.so\");\n  pdbClient.registerType(\"libraries/libMatrixScanner.so\");\n  pdbClient.registerType(\"libraries/libMatrixWriter.so\");\n\n  /// 2. Create the set\n\n  // now, create a new database\n  pdbClient.createDatabase(\"myData\");\n\n  // now, create the input and output sets\n  pdbClient.createSet<MatrixBlock>(\"myData\", \"A\");\n  pdbClient.createSet<MatrixBlock>(\"myData\", \"B\");\n  pdbClient.createSet<MatrixBlock>(\"myData\", \"C\");\n\n  /// 3. Fill in the data (single threaded)\n\n  initMatrix(pdbClient, \"A\", blockSize, matrixRowsA, matrixRowsB,    numRowsA, numRowsB);\n  initMatrix(pdbClient, \"B\", blockSize, matrixRowsB, matrixColumnsB, numRowsB, numColumnsB);\n\n  /// 4. Make query graph an run query\n\n  // for allocations\n  const UseTemporaryAllocationBlock tempBlock{blockSize * 1024 * 1024};\n\n  Handle <Computation> readA = makeObject <MatrixScanner>(\"myData\", \"A\");\n  Handle <Computation> readB = makeObject <MatrixScanner>(\"myData\", \"B\");\n  Handle <Computation> join = makeObject <MatrixMultiplyJoin>();\n  join->setInput(0, readA);\n  join->setInput(1, readB);\n  Handle<Computation> myAggregation = makeObject<MatrixMultiplyAggregation>();\n  myAggregation->setInput(join);\n  Handle<Computation> myWriter = makeObject<MatrixWriter>(\"myData\", \"C\");\n  myWriter->setInput(myAggregation);\n\n  //TODO this is just a preliminary version of the execute computation before we add back the TCAP generation\n  pdbClient.executeComputations({ myWriter });\n\n  /// 5. Get the set and print\n  printMatrix(pdbClient, \"myData\", \"C\");\n\n  // shutdown the server\n  pdbClient.shutDownServer();\n\n  return 0;\n}\n", "meta": {"hexsha": "1e8bf602756b04b9ec63e49f7a13a97572ccc9d5", "size": 6382, "ext": "cc", "lang": "C++", "max_stars_repo_path": "applications/TestMatrixMultiply/TestMatrixMultiply.cc", "max_stars_repo_name": "SeraphL/plinycompute", "max_stars_repo_head_hexsha": "7788bc2b01d83f4ff579c13441d0ba90734b54a2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-05-04T05:17:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-21T05:01:59.000Z", "max_issues_repo_path": "applications/TestMatrixMultiply/TestMatrixMultiply.cc", "max_issues_repo_name": "dcbdan/plinycompute", "max_issues_repo_head_hexsha": "a6f1c8ac8f75c09615f08752c82179f33cfc6d89", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-02-20T19:50:46.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-25T14:31:51.000Z", "max_forks_repo_path": "applications/TestMatrixMultiply/TestMatrixMultiply.cc", "max_forks_repo_name": "dcbdan/plinycompute", "max_forks_repo_head_hexsha": "a6f1c8ac8f75c09615f08752c82179f33cfc6d89", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-02-19T23:17:24.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-03T01:08:04.000Z", "avg_line_length": 34.6847826087, "max_line_length": 109, "alphanum_fraction": 0.6827013475, "num_tokens": 1700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743167997235783, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.4970903936797587}}
{"text": "#ifndef constraint_hpp\n#define constraint_hpp\n\n#include <memory>\n#include <vector>\n#include <Eigen/Core>\n\nnamespace elasty\n{\n    struct Particle;\n\n    enum class ConstraintType { Bilateral, Unilateral };\n\n    class Constraint\n    {\n    public:\n\n        Constraint(const std::vector<std::shared_ptr<Particle>>& particles,\n                   const double stiffness) :\n        m_stiffness(stiffness),\n        m_particles(particles)\n        {\n        }\n\n        /// \\brief Calculates the constraint function value C(x).\n        virtual double calculateValue() = 0;\n\n        /// \\brief Calculate the derivative of the constraint function\n        /// grad C(x).\n        /// \\details As constraints can have different vector sizes, it will\n        /// store the result to the passed raw buffer that should be allocated\n        /// in the caller, rather than returning a dynamically allocated\n        /// variable-length vector. This method does not check whether the\n        /// buffer is adequately allocated, or not.\n        virtual void calculateGrad(double* grad_C) = 0;\n\n        /// \\brief Manipulate the associated particles by projecting them to the\n        /// constraint manifold.\n        /// \\details This method should be called by the core engine. As this\n        /// method directly updates the predicted positions of the associated\n        /// particles, it is intended to be used in a Gauss-Seidel-style solver.\n        virtual void projectParticles() = 0;\n\n        /// \\brief Return the constraint type (i.e., either unilateral or\n        /// bilateral).\n        virtual ConstraintType getType() = 0;\n\n        /// \\brief Stiffness of this constraint, which should be in [0, 1].\n        double m_stiffness;\n\n    protected:\n\n        /// \\brief Associated particles.\n        /// \\details The number of particles is (in most cases) solely\n        /// determined in each constraint. For example, a distance constraint\n        /// need to have exactly two particles. Some special constraints\n        /// (e.g., shape-matching constraint) could have a variable number of\n        /// particles.\n        std::vector<std::shared_ptr<Particle>> m_particles;\n    };\n\n    class BendingConstraint final : public Constraint\n    {\n    public:\n\n        BendingConstraint(const std::shared_ptr<Particle> p_0,\n                          const std::shared_ptr<Particle> p_1,\n                          const std::shared_ptr<Particle> p_2,\n                          const std::shared_ptr<Particle> p_3,\n                          const double stiffness,\n                          const double dihedral_angle);\n\n        double calculateValue() override;\n        void calculateGrad(double* grad_C) override;\n        void projectParticles() override;\n        ConstraintType getType() override { return ConstraintType::Bilateral; }\n\n    private:\n\n        const Eigen::Matrix<double, 12, 1> m_inv_M;\n        const double m_dihedral_angle;\n    };\n\n    class DistanceConstraint final : public Constraint\n    {\n    public:\n\n        DistanceConstraint(const std::shared_ptr<Particle> p_0,\n                           const std::shared_ptr<Particle> p_1,\n                           const double stiffness,\n                           const double d);\n        \n        double calculateValue() override;\n        void calculateGrad(double* grad_C) override;\n        void projectParticles() override;\n        ConstraintType getType() override { return ConstraintType::Bilateral; }\n\n    private:\n\n        const Eigen::Matrix<double, 6, 1> m_inv_M;\n        const double m_d;\n    };\n\n    class EnvironmentalCollisionConstraint final : public Constraint\n    {\n    public:\n\n        EnvironmentalCollisionConstraint(const std::shared_ptr<Particle> p_0,\n                                         const double stiffness,\n                                         const Eigen::Vector3d& n,\n                                         const double d);\n\n        double calculateValue() override;\n        void calculateGrad(double* grad_C) override;\n        void projectParticles() override;\n        ConstraintType getType() override { return ConstraintType::Unilateral; }\n\n    private:\n\n        const Eigen::Matrix<double, 3, 1> m_inv_M;\n        const Eigen::Vector3d m_n;\n        const double m_d;\n    };\n\n    class FixedPointConstraint final : public Constraint\n    {\n    public:\n\n        FixedPointConstraint(const std::shared_ptr<Particle> p_0,\n                             const double stiffness,\n                             const Eigen::Vector3d& point);\n\n        double calculateValue() override;\n        void calculateGrad(double* grad_C) override;\n        void projectParticles() override;\n        ConstraintType getType() override { return ConstraintType::Bilateral; }\n\n    private:\n\n        const Eigen::Matrix<double, 3, 1> m_inv_M;\n        const Eigen::Vector3d m_point;\n    };\n\n    class IsometricBendingConstraint final : public Constraint\n    {\n    public:\n\n        IsometricBendingConstraint(const std::shared_ptr<Particle> p_0,\n                                   const std::shared_ptr<Particle> p_1,\n                                   const std::shared_ptr<Particle> p_2,\n                                   const std::shared_ptr<Particle> p_3,\n                                   const double stiffness);\n\n        double calculateValue() override;\n        void calculateGrad(double* grad_C) override;\n        void projectParticles() override;\n        ConstraintType getType() override { return ConstraintType::Bilateral; }\n\n    private:\n\n        const Eigen::Matrix<double, 12, 1> m_inv_M;\n        Eigen::Matrix4d m_Q;\n    };\n}\n\n#endif /* constraint_hpp */\n", "meta": {"hexsha": "c8f962ca119790b41954e5ed84b227469c1e4213", "size": 5628, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/elasty/constraint.hpp", "max_stars_repo_name": "0x0c/elasty", "max_stars_repo_head_hexsha": "3995cacbefa8d7f39249e9f75fa291828e2e7c2d", "max_stars_repo_licenses": ["MIT"], "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/elasty/constraint.hpp", "max_issues_repo_name": "0x0c/elasty", "max_issues_repo_head_hexsha": "3995cacbefa8d7f39249e9f75fa291828e2e7c2d", "max_issues_repo_licenses": ["MIT"], "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/elasty/constraint.hpp", "max_forks_repo_name": "0x0c/elasty", "max_forks_repo_head_hexsha": "3995cacbefa8d7f39249e9f75fa291828e2e7c2d", "max_forks_repo_licenses": ["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.7005988024, "max_line_length": 80, "alphanum_fraction": 0.605366027, "num_tokens": 1116, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.49704924384987675}}
{"text": "#include <blitz/array.h>\n\nint main() {\n  using namespace blitz;\n  Array<int,2> A(7, 7);\n  firstIndex i;\n  secondIndex j;\n  A=i+10*j;\n  cout << A << endl << A.base() << endl << A.ubound() << endl << endl;\n  A.reindexSelf(TinyVector<int,2>(2,3));\n  cout << A << endl << A.base() << endl << A.ubound() << endl << endl;\n}\n\n", "meta": {"hexsha": "f594455a096e8a4aa72e613f69a030787cbecb5e", "size": 319, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depspawn-blitz-0.10/testsuite/mattias-lindstroem-1.cpp", "max_stars_repo_name": "fraguela/depspawn", "max_stars_repo_head_hexsha": "b5760f4c0d38a1b245ee5274e2ccc5c5fe2d3d45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-04-12T11:05:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T11:10:27.000Z", "max_issues_repo_path": "ibtk/third_party/blitz-0.10/testsuite/mattias-lindstroem-1.cpp", "max_issues_repo_name": "MSV-Project/IBAMR", "max_issues_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ibtk/third_party/blitz-0.10/testsuite/mattias-lindstroem-1.cpp", "max_forks_repo_name": "MSV-Project/IBAMR", "max_forks_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_forks_repo_licenses": ["BSD-3-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.7857142857, "max_line_length": 70, "alphanum_fraction": 0.5579937304, "num_tokens": 109, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.49704923878993956}}
{"text": "#include \"dynet/nodes.h\"\n#include \"dynet/dynet.h\"\n#include \"dynet/training.h\"\n#include \"dynet/gpu-ops.h\"\n#include \"dynet/expr.h\"\n#include \"dynet/mp.h\"\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/archive/text_iarchive.hpp>\n\n#include <iostream>\n#include <fstream>\n\nusing namespace std;\nusing namespace dynet;\nusing namespace dynet::mp;\n\nstruct Datum {\n  Datum() {}\n  Datum(const vector<dynet::real>& x, const dynet::real y) : x(x), y(y) {}\n\n  vector<dynet::real> x;\n  dynet::real y;\n};\n\nclass XorModel {\npublic:\n  XorModel(const unsigned hidden_size, Model& dynet_model) : pcg(nullptr) {\n    p_W = dynet_model.add_parameters({hidden_size, 2});\n    p_b = dynet_model.add_parameters({hidden_size});\n    p_V = dynet_model.add_parameters({1, hidden_size});\n    p_a = dynet_model.add_parameters({1});\n  }\n\n  void new_graph(ComputationGraph& cg) {\n    W = parameter(cg, p_W);\n    b = parameter(cg, p_b);\n    V = parameter(cg, p_V);\n    a = parameter(cg, p_a);\n    pcg = &cg;\n  }\n\n  Expression compute_loss(const Datum& datum) {\n    Expression x = input(*pcg, {2}, &datum.x);\n    Expression y = input(*pcg, &datum.y);\n\n    Expression h = tanh(W*x + b);\n    Expression y_pred = V*h + a;\n    Expression loss_expr = squared_distance(y_pred, y);\n    return loss_expr;\n  }\n\nprivate:\n  XorModel() : pcg(nullptr) {}\n\n  Parameter p_W, p_b, p_V, p_a;\n  Expression W, b, V, a;\n  ComputationGraph* pcg;\n\n  friend class boost::serialization::access;\n  template<class Archive>\n  void serialize(Archive& ar, const unsigned int) {\n    ar & p_W & p_b & p_V & p_a;\n  }\n};\n\nvoid serialize(const XorModel* const xor_model, const Model& dynet_model, const Trainer* const trainer) {\n  // Remove existing stdout output\n  int r = ftruncate(fileno(stdout), 0);\n  if (r != 0) {}\n\n  // Move the cursor to the beginning of the stdout stream\n  fseek(stdout, 0, SEEK_SET);\n\n  // Dump the model to stdout\n  boost::archive::text_oarchive oa(cout);\n  oa & dynet_model;\n  oa & xor_model;\n  oa & trainer;\n}\n\nvoid deserialize(const string& filename, XorModel* xor_model, Model& dynet_model, Trainer* trainer) {\n  ifstream in(filename.c_str());\n  boost::archive::text_iarchive ia(in);\n  ia & dynet_model;\n  ia & xor_model;\n  ia & trainer;\n  in.close();\n}\n\nclass SufficientStats {\npublic:\n  dynet::real loss;\n  unsigned example_count;\n\n  SufficientStats() : loss(), example_count() {}\n\n  SufficientStats(dynet::real loss, unsigned example_count) : loss(loss), example_count(example_count) {}\n\n  SufficientStats& operator+=(const SufficientStats& rhs) {\n    loss += rhs.loss;\n    example_count += rhs.example_count;\n    return *this;\n  }\n\n  friend SufficientStats operator+(SufficientStats lhs, const SufficientStats& rhs) {\n    lhs += rhs;\n    return lhs;\n  }\n\n  bool operator<(const SufficientStats& rhs) {\n    return loss < rhs.loss;\n  }\n\n  friend std::ostream& operator<< (std::ostream& stream, const SufficientStats& stats) {\n    return stream << exp(stats.loss / stats.example_count) << \" (\" << stats.loss << \" over \" << stats.example_count << \" examples)\";\n  }\n};\n\nclass Learner : public ILearner<Datum, SufficientStats> {\npublic:\n  Learner(XorModel* xor_model, Model& dynet_model, const Trainer* const trainer, bool quiet) : xor_model(xor_model), dynet_model(dynet_model), trainer(trainer), quiet(quiet) {}\n  ~Learner() {}\n  SufficientStats LearnFromDatum(const Datum& datum, bool learn) {\n    ComputationGraph cg;\n    xor_model->new_graph(cg);\n    Expression loss_expr = xor_model->compute_loss(datum);\n    dynet::real loss = as_scalar(loss_expr.value());\n\n    if (learn) {\n      cg.backward(loss_expr);\n    }\n    return SufficientStats(loss, 1);\n  }\n\n  void SaveModel() {\n    if (!quiet) {\n      serialize(xor_model, dynet_model, trainer);\n    }\n  }\n\nprivate:\n  XorModel* xor_model;\n  Model& dynet_model; \n  const Trainer* const trainer;\n  bool quiet;\n};\n\nint main(int argc, char** argv) {\n  dynet::initialize(argc, argv, true);\n\n  // parameters\n  const unsigned num_cores = 4;\n  const unsigned ITERATIONS = 1000;\n  Model dynet_model;\n  XorModel* xor_model = nullptr;\n  Trainer* trainer = nullptr;\n\n  if (argc == 2) {\n    // Load the model and parameters from file if given.\n    deserialize(argv[1], xor_model, dynet_model, trainer);\n  }\n  else {\n    // Otherwise, just create a new model.\n    const unsigned HIDDEN_SIZE = 8;\n    xor_model = new XorModel(HIDDEN_SIZE, dynet_model);\n    trainer = new SimpleSGDTrainer(dynet_model);\n  }\n\n  vector<Datum> data(4);\n  data[0] = Datum({0, 0}, 0);\n  data[1] = Datum({0, 1}, 1);\n  data[2] = Datum({1, 0}, 1);\n  data[3] = Datum({1, 1}, 0);\n\n  Learner learner(xor_model, dynet_model, trainer, false);\n  for (unsigned i = 0; i < ITERATIONS; ++i) {\n    SufficientStats ss = run_mp_minibatch<Datum>(num_cores, &learner, data);\n    trainer->update(1.0 / data.size());\n    cout << ss << endl;\n  }\n}\n", "meta": {"hexsha": "a9151f6283bae45f6a985fb39e07a740a4fd7de7", "size": 4812, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/cpp/xor-simple-mp/train_xor-simple-mp.cc", "max_stars_repo_name": "MalcolmSun/dynet", "max_stars_repo_head_hexsha": "9b2df1e74dafe13072af0c2d4ce7424539d29ac9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-10T17:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-10T17:40:09.000Z", "max_issues_repo_path": "examples/cpp/xor-simple-mp/train_xor-simple-mp.cc", "max_issues_repo_name": "MalcolmSun/dynet", "max_issues_repo_head_hexsha": "9b2df1e74dafe13072af0c2d4ce7424539d29ac9", "max_issues_repo_licenses": ["Apache-2.0"], "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/cpp/xor-simple-mp/train_xor-simple-mp.cc", "max_forks_repo_name": "MalcolmSun/dynet", "max_forks_repo_head_hexsha": "9b2df1e74dafe13072af0c2d4ce7424539d29ac9", "max_forks_repo_licenses": ["Apache-2.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.4395604396, "max_line_length": 176, "alphanum_fraction": 0.671446384, "num_tokens": 1362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.754914997895581, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.4970492359310618}}
{"text": "/**\n * @file tests/augmented_rnns_tasks_test.cpp\n * @author Konstantin Sidorov\n *\n * Tests the rtasks for augmented network models.\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#include <vector>\n#include <algorithm>\n#include <utility>\n\n#include <mlpack/core.hpp>\n\n#include <mlpack/core/data/binarize.hpp>\n\n#include <mlpack/methods/ann/augmented/tasks/copy.hpp>\n#include <mlpack/methods/ann/augmented/tasks/sort.hpp>\n#include <mlpack/methods/ann/augmented/tasks/add.hpp>\n#include <mlpack/methods/ann/augmented/tasks/score.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n\nusing std::vector;\nusing std::pair;\nusing std::make_pair;\n\nusing namespace mlpack::ann::augmented;\nusing namespace mlpack::ann::augmented::tasks;\nusing namespace mlpack::ann::augmented::scorers;\n\nusing mlpack::data::Binarize;\n\n// The dummy model that simply copies the sequence\n// the required number of times\n// (yes, no ML here, we're unit testing :)\nclass HardCodedCopyModel\n{\n public:\n  HardCodedCopyModel() : nRepeats(1) {}\n\n  void Train(arma::field<arma::mat>& predictors,\n             arma::field<arma::mat>& labels)\n  {\n    arma::mat input = predictors.at(0);\n    arma::mat output = labels.at(0);\n    size_t zeroCnt = 0, oneCnt = 0;\n    for (size_t i = 1; i < input.n_rows; i += 2)\n    {\n      size_t& addVar = (input.at(i, 0) == 0) ? zeroCnt : oneCnt;\n      ++addVar;\n    }\n    assert(oneCnt % zeroCnt == 0);\n    nRepeats = oneCnt / zeroCnt;\n  }\n\n  void Predict(arma::mat& predictors,\n               arma::mat& labels)\n  {\n    size_t seqLen = (predictors.n_rows / 2) / (nRepeats + 1);\n    size_t outputLen = nRepeats * seqLen;\n    assert(2 * (seqLen + outputLen) == predictors.n_rows);\n    labels.zeros(predictors.n_rows / 2, 1);\n    for (size_t i = 0; i < outputLen; ++i)\n    {\n      labels.at(seqLen+i) = predictors.at(2 * (i % seqLen));\n    }\n  }\n\n  void Predict(arma::field<arma::mat>& predictors,\n               arma::field<arma::mat>& labels)\n  {\n    size_t sz = predictors.n_elem;\n    labels = arma::field<arma::mat>(sz);\n    for (size_t i = 0; i < sz; ++i)\n    {\n      Predict(predictors.at(i), labels.at(i));\n    }\n  }\n\n private:\n  size_t nRepeats;\n};\n\n// The dummy model that simply sorts the sequence.\nclass HardCodedSortModel\n{\n public:\n  HardCodedSortModel(size_t bitLen) : bitLen(bitLen) {}\n\n  void Train(arma::field<arma::mat>& predictors,\n             arma::field<arma::mat>& labels)\n  {\n    mlpack::Log::Assert(predictors.n_elem == labels.n_elem);\n  }\n\n  void Predict(arma::mat& predictors,\n               arma::mat& labels)\n  {\n    predictors = predictors.t();\n    predictors.reshape(bitLen, predictors.n_elem / bitLen);\n    size_t len = predictors.n_cols;\n    labels.zeros(bitLen, len);\n    vector<pair<int, int>> vals(len);\n    for (size_t j = 0; j < len; ++j)\n    {\n      int val = 0;\n      for (size_t k = 0; k < bitLen; ++k)\n      {\n        val <<= 1;\n        val += predictors.at(k, j);\n      }\n      vals[j] = make_pair(val, j);\n    }\n    sort(vals.begin(), vals.end());\n    for (size_t j = 0; j < len; ++j)\n    {\n      labels.col(j) = predictors.col(vals[j].second);\n    }\n    labels.reshape(predictors.n_elem, 1);\n  }\n\n  void Predict(arma::field<arma::mat>& predictors,\n               arma::field<arma::mat>& labels)\n  {\n    size_t sz = predictors.n_elem;\n    labels = arma::field<arma::mat>(sz);\n    for (size_t i = 0; i < sz; ++i)\n    {\n      Predict(predictors.at(i), labels.at(i));\n    }\n  }\n\n private:\n  size_t bitLen;\n};\n\n// The dummy model that simply add two binary numbers.\nclass HardCodedAddModel\n{\n public:\n  HardCodedAddModel() {}\n\n  void Train(arma::field<arma::mat>& /* predictors */,\n             arma::field<arma::mat>& /* labels */)\n  {\n    return;\n  }\n\n  void Predict(arma::mat& predictors,\n               arma::mat& labels)\n  {\n    assert(predictors.n_elem % 3 == 0);\n    predictors = predictors.t();\n    predictors.reshape(3, predictors.n_elem / 3);\n    assert(predictors.n_rows == 3);\n    int num_A = 0, num_B = 0;\n    bool num = false; // True iff we have already seen the separating symbol.\n    size_t cnt = 0;\n    for (size_t i = 0; i < predictors.n_cols; ++i)\n    {\n      double digit = arma::as_scalar(arma::find(1 == predictors.col(i), 1));\n      if (digit != 0 && digit != 1)\n      {\n        // We should not see two separators\n        // since we are adding *two* numbers in the task\n        assert(!num);\n        num = true;\n        cnt = 0;\n      }\n      else\n      {\n        if (num)\n        {\n          num_B += static_cast<int>(digit) << cnt;\n        }\n        else\n        {\n          num_A += static_cast<int>(digit) << cnt;\n        }\n        ++cnt;\n      }\n    }\n    int total = num_A + num_B;\n    vector<int> binary_seq;\n    while (total > 0)\n    {\n      binary_seq.push_back(total & 1);\n      total >>= 1;\n    }\n    if (binary_seq.empty())\n    {\n      assert(num_A + num_B == 0);\n      binary_seq.push_back(0);\n    }\n    size_t totLen = binary_seq.size();\n    labels = arma::zeros(3, totLen);\n    for (size_t j = 0; j < totLen; ++j)\n    {\n      labels.at(binary_seq[j], j) = 1;\n    }\n    labels.reshape(predictors.n_elem, 1);\n  }\n\n  void Predict(\n      arma::field<arma::mat>& predictors,\n      arma::field<arma::mat>& labels)\n  {\n    size_t sz = predictors.n_elem;\n    labels = arma::field<arma::mat>(sz);\n    for (size_t i = 0; i < sz; ++i)\n    {\n      Predict(predictors.at(i), labels.at(i));\n    }\n  }\n};\n\nBOOST_AUTO_TEST_SUITE(AugmentedRNNsTasks);\n\n// Test of CopyTask instance generator.\n// The data from generator is fed to the dummy hard-coded model above\n// that should be able to solve the task perfectly.\nBOOST_AUTO_TEST_CASE(CopyTaskTest)\n{\n  // Check the setup on various lengths...\n  for (size_t maxLen = 2; maxLen <= 16; ++maxLen)\n  {\n    // .. and various numbers of repetitions.\n    for (size_t nRepeats = 1; nRepeats <= 10; ++nRepeats)\n    {\n      CopyTask task(maxLen, nRepeats);\n      arma::field<arma::mat> trainPredictor, trainResponse;\n      task.Generate(trainPredictor, trainResponse, 8);\n      arma::field<arma::mat> testPredictor, testResponse;\n      task.Generate(testPredictor, testResponse, 8);\n      HardCodedCopyModel model;\n      model.Train(trainPredictor, trainResponse);\n      arma::field<arma::mat> predResponse;\n      model.Predict(testPredictor, predResponse);\n      // A single failure is a failure.\n      BOOST_REQUIRE_GE(SequencePrecision<arma::mat>(testResponse, predResponse),\n                       0.99);\n    }\n  }\n}\n\n// Test of SortTask instance generator.\n// The data from generator is fed to the dummy hard-coded model above\n// that should be able to solve the task perfectly.\nBOOST_AUTO_TEST_CASE(SortTaskTest)\n{\n  size_t bitLen = 5;\n  for (size_t maxLen = 2; maxLen <= 16; ++maxLen)\n  {\n    SortTask task(maxLen, bitLen);\n    arma::field<arma::mat> trainPredictor, trainResponse;\n    task.Generate(trainPredictor, trainResponse, 8);\n    arma::field<arma::mat> testPredictor, testResponse;\n    task.Generate(testPredictor, testResponse, 8);\n    HardCodedSortModel model(bitLen);\n    model.Train(trainPredictor, trainResponse);\n    arma::field<arma::mat> predResponse;\n    model.Predict(testPredictor, predResponse);\n    // A single failure is a failure.\n    BOOST_REQUIRE_GE(SequencePrecision<arma::mat>(testResponse, predResponse),\n                     0.99);\n  }\n}\n\n// Test of AddTask instance generator.\n// The data from generator is fed to the dummy hard-coded model above\n// that should be able to solve the task perfectly.\nBOOST_AUTO_TEST_CASE(AddTaskTest)\n{\n  for (size_t bitLen = 2; bitLen <= 16; ++bitLen)\n  {\n    AddTask task(bitLen);\n    arma::field<arma::mat> trainPredictor, trainResponse;\n    task.Generate(trainPredictor, trainResponse, 8);\n    arma::field<arma::mat> testPredictor, testResponse;\n    task.Generate(testPredictor, testResponse, 8);\n    HardCodedAddModel model;\n    model.Train(trainPredictor, trainResponse);\n    arma::field<arma::mat> predResponse;\n    model.Predict(testPredictor, predResponse);\n    // A single failure is a failure.\n    BOOST_REQUIRE_GE(SequencePrecision<arma::mat>(testResponse, predResponse),\n                     0.99);\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "c8856a7570d60e3f71db4006be37546d2a023346", "size": 8373, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/augmented_rnns_tasks_test.cpp", "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/tests/augmented_rnns_tasks_test.cpp", "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/tests/augmented_rnns_tasks_test.cpp", "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": 28.1919191919, "max_line_length": 80, "alphanum_fraction": 0.6303594888, "num_tokens": 2333, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.6584174938590245, "lm_q1q2_score": 0.49704923373000226}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#include \"Framework/TestingFramework.hpp\"\n\n#include <array>\n#include <boost/rational.hpp>\n#include <cstddef>\n#include <vector>\n\n#include \"Domain/Structure/ElementId.hpp\"  // IWYU pragma: keep\n#include \"Domain/Structure/InitialElementIds.hpp\"\n#include \"Helpers/Domain/DomainTestHelpers.hpp\"\n#include \"Utilities/ConstantExpressions.hpp\"\n#include \"Utilities/Gsl.hpp\"\n\nnamespace {\ntemplate <size_t VolumeDim>\nvoid test_initial_element_ids(\n    const std::vector<ElementId<VolumeDim>>& element_ids,\n    const std::vector<std::array<size_t, VolumeDim>>& initial_refinement_levels,\n    size_t grid_index) {\n  size_t expected_number_of_elements = 0;\n  for (const auto& initial_refinement_levels_of_block :\n       initial_refinement_levels) {\n    size_t expected_number_of_elements_in_block = 1;\n    for (size_t d = 0; d < VolumeDim; ++d) {\n      expected_number_of_elements_in_block *=\n          two_to_the(gsl::at(initial_refinement_levels_of_block, d));\n    }\n    expected_number_of_elements += expected_number_of_elements_in_block;\n  }\n  CHECK(expected_number_of_elements == element_ids.size());\n  const boost::rational<size_t> expected_logical_volume_of_blocks(\n      initial_refinement_levels.size());\n  boost::rational<size_t> logical_volume_of_blocks(0);\n  for (const auto& element_id : element_ids) {\n    logical_volume_of_blocks += fraction_of_block_volume(element_id);\n    CHECK(element_id.grid_index() == grid_index);\n  }\n  CHECK(expected_logical_volume_of_blocks == logical_volume_of_blocks);\n}\n}  // namespace\n\nSPECTRE_TEST_CASE(\"Unit.Domain.Structure.InitialElementIds\", \"[Domain][Unit]\") {\n  const std::vector<std::array<size_t, 1>> initial_refinement_levels_1d{{{2}},\n                                                                        {{3}}};\n  const auto element_ids_1d = initial_element_ids(initial_refinement_levels_1d);\n  test_initial_element_ids(element_ids_1d, initial_refinement_levels_1d, 0);\n  test_initial_element_ids(initial_element_ids(initial_refinement_levels_1d, 3),\n                           initial_refinement_levels_1d, 3);\n\n  const std::vector<std::array<size_t, 2>> initial_refinement_levels_2d{\n      {{2, 0}}, {{3, 1}}};\n  const auto element_ids_2d = initial_element_ids(initial_refinement_levels_2d);\n  test_initial_element_ids(element_ids_2d, initial_refinement_levels_2d, 0);\n  test_initial_element_ids(initial_element_ids(initial_refinement_levels_2d, 3),\n                           initial_refinement_levels_2d, 3);\n\n  const std::vector<std::array<size_t, 3>> initial_refinement_levels_3d{\n      {{4, 2, 1}}, {{0, 3, 2}}};\n  const auto element_ids_3d = initial_element_ids(initial_refinement_levels_3d);\n  test_initial_element_ids(element_ids_3d, initial_refinement_levels_3d, 0);\n  test_initial_element_ids(initial_element_ids(initial_refinement_levels_3d, 3),\n                           initial_refinement_levels_3d, 3);\n}\n", "meta": {"hexsha": "174882409bc74adf67c8b7b4418b6594154066e7", "size": 2937, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/Unit/Domain/Structure/Test_InitialElementIds.cpp", "max_stars_repo_name": "nilsvu/spectre", "max_stars_repo_head_hexsha": "1455b9a8d7e92db8ad600c66f54795c29c3052ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 117.0, "max_stars_repo_stars_event_min_datetime": "2017-04-08T22:52:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T07:23:36.000Z", "max_issues_repo_path": "tests/Unit/Domain/Structure/Test_InitialElementIds.cpp", "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": "tests/Unit/Domain/Structure/Test_InitialElementIds.cpp", "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": 43.8358208955, "max_line_length": 80, "alphanum_fraction": 0.7398706163, "num_tokens": 712, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.49704923152894226}}
{"text": "\n/** \\file oaunittest.cpp\n\nC++ program: oaunittest\n\noaunittest: run some tests on the code\n\nAuthor: Pieter Eendebak <pieter.eendebak@gmail.com>\nCopyright: See LICENSE.txt file that comes with this distribution\n*/\n\n#include <algorithm>\n#include <iostream>\n#include <stdio.h>\n#include <stdlib.h>\n\n#include \"lmc.h\"\n#include \"Deff.h\"\n#include \"anyoption.h\"\n#include \"arrayproperties.h\"\n#include \"arraytools.h\"\n#include \"conference.h\"\n#include \"extend.h\"\n#include \"tools.h\"\n\n#include \"graphtools.h\"\n#include \"unittests.h\"\n\n#include \"Eigen/Dense\"\n\n#ifdef HAVE_BOOST\n#include <boost/filesystem.hpp>\n#include <string>\n#endif\n\n\n// functions with no public header\narray_link createJdtable(const array_link &al);\n\n\nenum { UNITTEST_SUCCESS, UNITTEST_FAIL };\n\n/** unittest for oapackage\n *\n * Returns UNITTEST_SUCCESS if all tests are ok.\n *\n */\nint oaunittest (int verbose, int writetests = 0, int randval = 0) {\n        double t0 = get_time_ms ();\n        const char *bstr = \"OA unittest\";\n        cprintf (verbose, \"%s: start\\n\", bstr);\n\n        srand (randval);\n\n        int allgood = UNITTEST_SUCCESS;\n\n        Combinations::initialize_number_combinations (20);\n\n        /* constructors */\n        {\n                cprintf (verbose, \"%s: interaction matrices\\n\", bstr);\n\n                array_link al = exampleArray (2);\n                Eigen::MatrixXd m1 = array2xfeigen (al);\n                Eigen::MatrixXd m2 = arraylink2eigen (array2xf (al));\n\n                Eigen::MatrixXd dm = m1 - m2;\n                int sum = dm.sum ();\n\n                myassert (sum == 0, \"unittest error: construction of interaction matrices\\n\");\n        }\n\n\t\tcprintf(verbose, \"%s: reduceConferenceTransformation\\n\", bstr);\n\t\tmyassert(unittest_reduceConferenceTransformation()==0, \"unittest unittest_reduceConferenceTransformation failed\");\n\n        /* constructors */\n        {\n                cprintf (verbose, \"%s: array manipulation operations\\n\", bstr);\n\n                test_array_manipulation (verbose);\n        }\n\n        /* double conference matrices */\n        {\n                cprintf (verbose, \"%s: double conference matrices\\n\", bstr);\n\n                array_link al = exampleArray (36, verbose);\n                myassert (al.is_conference (2), \"check on double conference design type\");\n\n                myassert (testLMC0checkDC (al, verbose >= 2), \"testLMC0checkDC\");\n\n        }\n\n        /* conference matrices */\n        {\n                cprintf (verbose, \"%s: conference matrices\\n\", bstr);\n\n                int N = 4;\n                conference_t ctype (N, N, 0);\n\n                arraylist_t kk;\n                array_link al = ctype.create_root ();\n                kk.push_back (al);\n\n                for (int extcol = 2; extcol < N; extcol++) {\n                        kk = extend_conference (kk, ctype, 0);\n                }\n                myassert (kk.size () == 1, \"unittest error: conference matrices for N=4\\n\");\n        }\n\n        {\n                cprintf (verbose, \"%s: generators for conference matrix extensions\\n\", bstr);\n                test_conference_candidate_generators (verbose);\n        }\n\n        {\n                cprintf(verbose, \"%s: conference matrix Fvalues\\n\", bstr);\n                std::vector< int > jj5 = Jcharacteristics_conference(exampleArray(18, 0), 5);\n                myassert(jj5 == std::vector<int>{ -1, -1, -1, -5, 11, -3, 3, 3, -1, -1, 1, -1, 3, -1, 1, 7, 3, 5, -1, 1, 1}, \"Jcharacteristics_conference result incorrect\");\n\n                array_link al = exampleArray (22, 0);\n                if (verbose >= 2)\n                        al.show ();\n                std::vector< int > jj3 = Jcharacteristics_conference(al, 3);\n                myassert(jj3 == std::vector<int> { 0, 0, 0, 0 }, \"Jcharacteristics_conference result incorrect\");\n\n                const int N = al.n_rows;\n                jstructconference_t js (N, 4);\n                std::vector< int > f4 = al.FvaluesConference (4);\n                std::vector< int > j4 = js.Jvalues ();\n\n                if (verbose >= 2) {\n                        printf (\"j4: \");\n                        display_vector (j4);\n                        printf (\"\\n\");\n                        printf (\"F4: \");\n                        display_vector (f4);\n                        printf (\"\\n\");\n                }\n\n                myassert (j4[0] == 28, \"unittest error: conference matricex F values: j4[0]\\n\");\n                myassert (f4[0] == 0, \"unittest error: conference matricex F values: f4[0] \\n\");\n                myassert (f4[1] == 0, \"unittest error: conference matricex F values: j4[1]\\n\");\n        }\n\n        {\n                cprintf (verbose, \"%s: LMC0 check for arrays in C(4, 3)\\n\", bstr);\n\n                array_link al = exampleArray (28, 1);\n                if (verbose >= 2)\n                        al.showarray ();\n                lmc_t r = LMC0check (al, verbose);\n                if (verbose >= 2)\n                        printf (\"LMC0check: result %d\\n\", r);\n                myassert (r >= LMC_EQUAL, \"LMC0 check\\n\");\n\n                al = exampleArray (29, 1);\n                if (verbose >= 2)\n                        al.showarray ();\n                r = LMC0check (al, verbose);\n                if (verbose >= 2)\n                        printf (\"LMC0check: result %d (LMC_LESS %d)\\n\", r, LMC_LESS);\n                myassert (r == LMC_LESS, \"LMC0 check of example array 29\\n\");\n        }\n\n        {\n                cprintf (verbose, \"%s: LMC0 check\\n\", bstr);\n\n                array_link al = exampleArray (31, 1);\n                if (verbose >= 2)\n                        al.showarray ();\n                conference_transformation_t T (al);\n\n                for (int i = 0; i < 80; i++) {\n                        T.randomize ();\n                        array_link alx = T.apply (al);\n\n                        lmc_t r = LMC0check (alx, verbose);\n\n                        if (verbose >= 2) {\n                                printfd (\"%d: transformed array: r %d\\n\", i, r);\n                                alx.showarray ();\n                        }\n                        if (alx == al)\n                                myassert (r >= LMC_EQUAL, \"result should be LMC_MORE\\n\");\n                        else {\n                                myassert (r == LMC_LESS, \"result should be LMC_LESS\\n\");\n                        }\n                }\n        }\n\n        {\n                cprintf (verbose, \"%s: random transformation for conference matrices\\n\", bstr);\n\n                array_link al = exampleArray (19, 1);\n                conference_transformation_t T (al);\n                // T.randomizerowflips();\n                T.randomize ();\n\n                conference_transformation_t Ti = T.inverse ();\n                array_link alx = Ti.apply (T.apply (al));\n\n                myassert (alx == al, \"transformation of conference matrix\\n\");\n        }\n\n        /* constructors */\n        {\n                cprintf (verbose, \"%s: constructors\\n\", bstr);\n\n                array_transformation_t t;\n                conference_transformation_t ct;\n        }\n\n        /* J-characteristics */\n        {\n                cprintf (verbose, \"%s: J-characteristics\\n\", bstr);\n\n                array_link al = exampleArray (8, 1);\n\n                const int mm[] = {-1, -1, 0, 0, 8, 16, 0, -1};\n\n                for (int jj = 2; jj < 7; jj++) {\n                        std::vector< int > jx = al.Jcharacteristics (jj);\n                        int j5max = vectormax (jx, 0);\n                        if (verbose >= 2) {\n                                printf (\"oaunittest: jj %d: j5max %d\\n\", jj, j5max);\n                        }\n\n                        if (j5max != mm[jj]) {\n                                printfd (\"j5max %d (should be %d)\\n\", j5max, mm[jj]);\n                                allgood = UNITTEST_FAIL;\n                                return allgood;\n                        }\n                }\n        }\n        {\n                cprintf (verbose, \"%s: array transformations\\n\", bstr);\n\n                const int N = 9;\n                const int t = 3;\n                arraydata_t adataX (3, N, t, 4);\n\n                array_link al (adataX.N, adataX.ncols, -1);\n                al.create_root (adataX);\n\n                if (checkTransformationInverse (al))\n                        allgood = UNITTEST_FAIL;\n\n                if (checkTransformationComposition (al, verbose >= 2))\n                        allgood = UNITTEST_FAIL;\n\n                al = exampleArray (5, 1);\n                if (checkTransformationInverse (al))\n                        allgood = UNITTEST_FAIL;\n\n                if (checkTransformationComposition (al))\n                        allgood = UNITTEST_FAIL;\n\n                for (int i = 0; i < 15; i++) {\n                        al = exampleArray (18, 0);\n                        if (checkConferenceComposition (al))\n                                allgood = UNITTEST_FAIL;\n                        if (checkConferenceInverse (al))\n                                allgood = UNITTEST_FAIL;\n                        al = exampleArray (19, 0);\n                        if (checkConferenceComposition (al))\n                                allgood = UNITTEST_FAIL;\n                        if (checkConferenceInverse (al))\n                                allgood = UNITTEST_FAIL;\n                }\n        }\n\n        {\n                cprintf (verbose, \"%s: rank \\n\", bstr);\n\n                const int idx[10] = {0, 1, 2, 3, 4, 6, 7, 8, 9};\n                const int rr[10] = {4, 11, 13, 18, 16, 4, 4, 29, 29};\n                for (int ii = 0; ii < 9; ii++) {\n                        array_link al = exampleArray (idx[ii], 0);\n                        myassert (al.is2level (), \"unittest error: input array is not 2-level\\n\");\n\n                        int r = arrayrankColPivQR (array2xf (al));\n\n                        int r3 = (array2xf (al)).rank ();\n                        myassert (r == r3, \"unittest error: rank of array\");\n\n                        if (verbose >= 2) {\n                                al.showarray ();\n                                printf (\"unittest: rank of array %d: %d\\n\", idx[ii], r);\n                        }\n\n                        myassert (rr[ii] == r, \"unittest error: rank of example matrix\\n\");\n                }\n        }\n\n        {\n                cprintf (verbose, \"%s: Doptimize \\n\", bstr);\n                const int N = 40;\n                const int t = 0;\n                arraydata_t arrayclass (2, N, t, 6);\n                std::vector< double > alpha (3);\n                alpha[0] = 1;\n                alpha[1] = 1;\n                alpha[2] = 0;\n                int niter = 5000;\n                double t00 = get_time_ms ();\n                DoptimReturn rr = Doptimize (arrayclass, 10, alpha, 0, DOPTIM_AUTOMATIC, niter);\n\n                array_t ss[7] = {3, 3, 2, 2, 2, 2, 2};\n                arraydata_t arrayclassmixed (ss, 36, t, 5);\n                rr = Doptimize (arrayclassmixed, 10, alpha, 0, DOPTIM_AUTOMATIC, niter);\n\n                cprintf (verbose, \"%s: Doptimize time %.3f [s] \\n\", bstr, get_time_ms () - t00);\n        }\n\n        {\n                cprintf (verbose, \"%s: J-characteristics for conference matrix\\n\", bstr);\n\n                array_link al = exampleArray (19, 0);\n                std::vector< int > j2 = Jcharacteristics_conference (al, 2);\n                std::vector< int > j3 = Jcharacteristics_conference (al, 3);\n\n                myassert (j2[0] == 0, \"j2 value incorrect\");\n                myassert (j2[1] == 0, \"j2 value incorrect\");\n                myassert (std::abs (j3[0]) == 1, \"j3 value incorrect\");\n\n                if (verbose >= 2) {\n                        al.showarray ();\n                        printf (\"j2: \");\n                        display_vector (j2);\n                        printf (\"\\n\");\n                        printf (\"j3: \");\n                        display_vector (j3);\n                        printf (\"\\n\");\n                }\n        }\n\n        {\n                // test PEC sequence\n                cprintf (verbose, \"%s: PEC sequence\\n\", bstr);\n                for (int ii = 0; ii < 5; ii++) {\n                        array_link al = exampleArray (ii, 0);\n                        std::vector< double > pec = PECsequence (al);\n                        printf (\"oaunittest: PEC for array %d: \", ii);\n                        display_vector (pec);\n                        printf (\" \\n\");\n                }\n        }\n\n        {\n                cprintf (verbose, \"%s: D-efficiency test\\n\", bstr);\n                //  D-efficiency near-zero test\n                {\n                        array_link al = exampleArray (14);\n                        double D = al.Defficiency ();\n                        std::vector< double > dd = al.Defficiencies ();\n                        printf (\"D %f, D (method 2) %f\\n\", D, dd[0]);\n                        assert (fabs (D - dd[0]) < 1e-4);\n                }\n                {\n                        array_link al = exampleArray (15);\n                        double D = al.Defficiency ();\n                        std::vector< double > dd = al.Defficiencies ();\n                        printf (\"D %f, D (method 2) %f\\n\", D, dd[0]);\n                        assert (fabs (D - dd[0]) < 1e-4);\n                        assert (fabs (D - 0.335063) < 1e-3);\n                }\n        }\n\n        arraydata_t adata (2, 20, 2, 6);\n        OAextend oaextendx;\n        oaextendx.setAlgorithm ((algorithm_t)MODE_ORIGINAL, &adata);\n\n        std::vector< arraylist_t > aa (adata.ncols + 1);\n        printf (\"OA unittest: create root array\\n\");\n        create_root (&adata, aa[adata.strength]);\n\n        /** Test extend of arrays **/\n        {\n                cprintf (verbose, \"%s: extend arrays\\n\", bstr);\n\n                setloglevel (SYSTEM);\n\n                for (int kk = adata.strength; kk < adata.ncols; kk++) {\n                        aa[kk + 1] = extend_arraylist (aa[kk], adata, oaextendx);\n                        printf (\"  extend: column %d->%d: %ld->%ld arrays\\n\", kk, kk + 1, aa[kk].size (),\n                                aa[kk + 1].size ());\n                }\n\n                if (aa[adata.ncols].size () != 75) {\n                        printf (\"extended ?? to %d arrays\\n\", (int)aa[adata.ncols].size ());\n                }\n                myassert (aa[adata.ncols].size () == 75, \"number of arrays is incorrect\");\n\n                aa[adata.ncols].size ();\n                setloglevel (QUIET);\n        }\n\n        {\n                cprintf (verbose, \"%s: test LMC check\\n\", bstr);\n\n                array_link al = exampleArray (1, 1);\n\n                lmc_t r = LMCcheckOriginal (al);\n\n                myassert (r != LMC_LESS, \"LMC check of array in normal form\");\n\n                for (int i = 0; i < 20; i++) {\n                        array_link alx = al.randomperm ();\n                        if (alx == al)\n                                continue;\n                        lmc_t r = LMCcheckOriginal (alx);\n\n                        myassert (r == LMC_LESS, \"randomized array cannot be in minimal form\");\n                }\n        }\n\n        {\n                /** Test dof **/\n                cprintf (verbose, \"%s: test delete-one-factor reduction\\n\", bstr);\n\n                array_link al = exampleArray (4);\n                cprintf (verbose >= 2, \"LMC: \\n\");\n                al.reduceLMC ();\n                cprintf (verbose >= 2, \"DOP: \\n\");\n                al.reduceDOP ();\n        }\n\n        arraylist_t lst;\n\n        {\n                /** Test different methods **/\n                cprintf (verbose, \"%s: test 2 different methods\\n\", bstr);\n\n                const int s = 2;\n                arraydata_t adata (s, 32, 3, 10);\n                arraydata_t adata2 (s, 32, 3, 10);\n                OAextend oaextendx;\n                oaextendx.setAlgorithm ((algorithm_t)MODE_ORIGINAL, &adata);\n                OAextend oaextendx2;\n                oaextendx2.setAlgorithm ((algorithm_t)MODE_LMC_2LEVEL, &adata2);\n\n                printf (\"OA unittest: test 2-level algorithm on %s\\n\", adata.showstr ().c_str ());\n                std::vector< arraylist_t > aa (adata.ncols + 1);\n                create_root (&adata, aa[adata.strength]);\n                std::vector< arraylist_t > aa2 (adata.ncols + 1);\n                create_root (&adata, aa2[adata.strength]);\n\n                setloglevel (SYSTEM);\n\n                for (int kk = adata.strength; kk < adata.ncols; kk++) {\n                        aa[kk + 1] = extend_arraylist (aa[kk], adata, oaextendx);\n                        aa2[kk + 1] = extend_arraylist (aa2[kk], adata2, oaextendx2);\n                        printf (\"  extend: column %d->%d: %ld->%ld arrays, 2-level method %ld->%ld arrays\\n\", kk,\n                                kk + 1, (long) aa[kk].size (), (long)aa[kk + 1].size (), aa2[kk].size (), aa2[kk + 1].size ());\n\n                        if (aa[kk + 1] != aa2[kk + 1]) {\n                                printf (\"oaunittest: error: 2-level algorithm unequal to original algorithm\\n\");\n                                exit (1);\n                        }\n                }\n                setloglevel (QUIET);\n\n                lst = aa[8];\n        }\n\n        {\n                cprintf (verbose, \"%s: rank calculation using rankStructure\\n\", bstr);\n\n                for (int i = 0; i < 27; i++) {\n                        array_link al = exampleArray (i, 0);\n                        if (al.n_columns < 5)\n                                continue;\n                        al = exampleArray (i, 1);\n\n                        rankStructure rs;\n                        rs.verbose = 0;\n                        int r = array2xf (al).rank ();\n                        int rc = rs.rankxf (al);\n                        if (verbose >= 2) {\n                                printf (\"rank of example array %d: %d %d\\n\", i, r, rc);\n                                if (verbose >= 3) {\n                                        al.showproperties ();\n                                }\n                        }\n                        myassert (r == rc, \"rank calculations\");\n                }\n        }\n        {\n                cprintf (verbose, \"%s: test dtable creation\\n\", bstr);\n\n                for (int i = 0; i < 4; i++) {\n                        array_link al = exampleArray (5);\n                        array_link dtable = createJdtable (al);\n                }\n        }\n\n        {\n                cprintf (verbose, \"%s: test Pareto calculation\\n\", bstr);\n                double t0x = get_time_ms ();\n\n                int nn = lst.size ();\n                for (int k = 0; k < 5; k++) {\n                        for (int i = 0; i < nn; i++) {\n                                lst.push_back (lst[i]);\n                        }\n                }\n                Pareto< mvalue_t< long >, long > r = parsePareto (lst, 1);\n                cprintf (verbose, \"%s: test Pareto %d/%d: %.3f [s]\\n\", bstr, r.number (), r.numberindices (),\n                         (get_time_ms () - t0x));\n        }\n\n        {\n                cprintf (verbose, \"%s: check reduction transformation\\n\", bstr);\n                array_link al = exampleArray (6).reduceLMC ();\n\n                arraydata_t adata = arraylink2arraydata (al);\n                LMCreduction_t reduction (&adata);\n                reduction.mode = OA_REDUCE;\n\n                reduction.init_state = COPY;\n                OAextend oaextend;\n                oaextend.setAlgorithm (MODE_ORIGINAL, &adata);\n                array_link alr = al.randomperm ();\n\n                array_link al2 = reduction.transformation->apply (al);\n\n                lmc_t tmp = LMCcheck (alr, adata, oaextend, reduction);\n\n                array_link alx = reduction.transformation->apply (alr);\n\n                bool c = alx == al;\n                if (!c) {\n                        printf (\"oaunittest: error: reduction of randomized array failed!\\n\");\n                        printf (\"-- al \\n\");\n                        al.showarraycompact ();\n                        printf (\"-- alr \\n\");\n                        alr.showarraycompact ();\n                        printf (\"-- alx \\n\");\n                        alx.showarraycompact ();\n                        allgood = UNITTEST_FAIL;\n                }\n        }\n\n        {\n                cprintf (verbose, \"%s: reduce randomized array\\n\", bstr);\n                array_link al = exampleArray (3);\n\n                arraydata_t adata = arraylink2arraydata (al);\n                LMCreduction_t reduction (&adata);\n\n                for (int ii = 0; ii < 50; ii++) {\n                        reduction.transformation->randomize ();\n                        array_link al2 = reduction.transformation->apply (al);\n\n                        array_link alr = al2.reduceLMC ();\n\n                        bool c = (al == alr);\n                        if (!c) {\n                                printf (\"oaunittest: error: reduction of randomized array failed!\\n\");\n                                allgood = UNITTEST_FAIL;\n                        }\n                }\n        }\n\n        /* Calculate symmetry group */\n        {\n                cprintf (verbose, \"%s: calculate symmetry group\\n\", bstr);\n\n                array_link al = exampleArray (2);\n                symmetry_group sg = al.row_symmetry_group ();\n                assert (sg.permsize () == sg.permsize_large ().toLong ());\n\n                // symmetry_group\n                std::vector< int > vv;\n                vv.push_back (0);\n                vv.push_back (0);\n                vv.push_back (1);\n                symmetry_group sg2 (vv);\n                assert (sg2.permsize () == 2);\n                if (verbose >= 2)\n                        printf (\"sg2: %ld\\n\", sg2.permsize ());\n                assert (sg2.ngroups == 2);\n        }\n\n        /* Test efficiencies */\n        {\n                cprintf (verbose, \"%s: efficiencies\\n\", bstr);\n\n                std::vector< double > d;\n                int vb = 1;\n\n                array_link al;\n                if (1) {\n                        al = exampleArray (9, vb);\n                        al.showproperties ();\n                        d = al.Defficiencies (0, 1);\n                        if (verbose >= 2)\n                                printf (\"  efficiencies: D %f Ds %f D1 %f Ds0 %f\\n\", d[0], d[1], d[2], d[3]);\n                        if (fabs (d[0] - al.Defficiency ()) > 1e-10) {\n                                printf (\"oaunittest: error: Defficiency not good!\\n\");\n                                allgood = UNITTEST_FAIL;\n                        }\n                }\n                al = exampleArray (8, vb);\n                al.showproperties ();\n                d = al.Defficiencies ();\n                if (verbose >= 2)\n                        printf (\"  efficiencies: D %f Ds %f D1 %f\\n\", d[0], d[1], d[2]);\n                if (fabs (d[0] - al.Defficiency ()) > 1e-10) {\n                        printf (\"oaunittest: error: Defficiency of examlple array 8 not good!\\n\");\n                }\n\n                al = exampleArray (13, vb);\n                if (verbose >= 3) {\n                        al.showarray ();\n                        al.showproperties ();\n                }\n                d = al.Defficiencies (0, 1);\n                if (verbose >= 2)\n                        printf (\"  efficiencies: D %f Ds %f D1 %f\\n\", d[0], d[1], d[2]);\n\n                if ((fabs (d[0] - 0.939014) > 1e-4) || (fabs (d[3] - 0.896812) > 1e-4) || (fabs (d[2] - 1) > 1e-4)) {\n                        printf (\"ERROR: D-efficiencies of example array 13 incorrect! \\n\");\n                        d = al.Defficiencies (2, 1);\n                        printf (\"  efficiencies: D %f Ds %f D1 %f Ds0 %f\\n\", d[0], d[1], d[2], d[3]);\n\n                        allgood = UNITTEST_FAIL;\n                        exit (1);\n                }\n\n                for (int ii = 11; ii < 12; ii++) {\n                        printf (\"ii %d: \", ii);\n                        al = exampleArray (ii, vb);\n                        al.showarray ();\n                        al.showproperties ();\n\n                        d = al.Defficiencies ();\n                        if (verbose >= 2)\n                                printf (\"  efficiencies: D %f Ds %f D1 %f\\n\", d[0], d[1], d[2]);\n                }\n        }\n        {\n                cprintf (verbose, \"%s: test robustness\\n\", bstr);\n\n                array_link A (0, 8, 0);\n                printf (\"should return an error\\n  \");\n                A.Defficiencies ();\n\n                A = array_link (1, 8, 0);\n                printf (\"should return an error\\n  \");\n                A.at (0, 0) = -2;\n                A.Defficiencies ();\n        }\n\n        {\n                cprintf (verbose, \"%s: test nauty\\n\", bstr);\n\n                array_link alr = exampleArray (7, 0);\n                if (unittest_nautynormalform (alr, 1) == 0) {\n                        printf (\"oaunittest: error: unittest_nautynormalform returns an error!\\n\");\n                }\n        }\n\n#ifdef HAVE_BOOST\n        if (writetests) {\n                cprintf (verbose, \"OA unittest: reading and writing of files\\n\");\n\n                boost::filesystem::path tmpdir = boost::filesystem::temp_directory_path ();\n                boost::filesystem::path temp = boost::filesystem::unique_path (\"test-%%%%%%%.oa\");\n\n                const std::string tempstr = (tmpdir / temp).native ();\n\n                if (verbose >= 2)\n                        printf (\"generate text OA file: %s\\n\", tempstr.c_str ());\n\n                int nrows = 16;\n                int ncols = 8;\n                int narrays = 10;\n                arrayfile_t afile (tempstr.c_str (), nrows, ncols, narrays, ATEXT);\n                for (int i = 0; i < narrays; i++) {\n                        array_link al (nrows, ncols, array_link::INDEX_DEFAULT);\n                        afile.append_array (al);\n                }\n                afile.closefile ();\n\n                arrayfile_t af (tempstr.c_str (), 0);\n                std::cout << \"  \" << af.showstr () << std::endl;\n                af.closefile ();\n\n                // check read/write of binary file\n\n                arraylist_t ll0;\n                ll0.push_back (exampleArray (7));\n                ll0.push_back (exampleArray (7).randomcolperm ());\n                writearrayfile (tempstr.c_str (), ll0, ABINARY);\n                arraylist_t ll = readarrayfile (tempstr.c_str ());\n                myassert (ll0.size () == ll.size (), \"read and write of arrays: size of list\");\n                for (size_t i = 0; i < ll0.size (); i++) {\n                        myassert (ll0[i] == ll[i], \"read and write of arrays: array unequal\");\n                }\n\n                ll0.resize (0);\n                ll0.push_back (exampleArray (24));\n                writearrayfile (tempstr.c_str (), ll0, ABINARY_DIFFZERO);\n                ll = readarrayfile (tempstr.c_str ());\n                myassert (ll0.size () == ll.size (), \"read and write of arrays: size of list\");\n                for (size_t i = 0; i < ll0.size (); i++) {\n                        myassert (ll0[i] == ll[i], \"read and write of arrays: array unequal\");\n                }\n        }\n\n#endif\n\n        {\n                cprintf (verbose, \"OA unittest: test nauty\\n\");\n                array_link al = exampleArray (5, 2);\n                arraydata_t arrayclass = arraylink2arraydata (al);\n\n                for (int i = 0; i < 20; i++) {\n                        array_link alx = al;\n                        alx.randomperm ();\n                        array_transformation_t t1 = reduceOAnauty (al);\n                        array_link alr1 = t1.apply (al);\n\n                        array_transformation_t t2 = reduceOAnauty (alx);\n                        array_link alr2 = t2.apply (alx);\n\n                        if (alr1 != alr2)\n                                printf (\"oaunittest: error: Nauty reductions unequal!\\n\");\n                        allgood = UNITTEST_FAIL;\n                }\n        }\n\n        cprintf (verbose, \"OA unittest: complete %.3f [s]!\\n\", (get_time_ms () - t0));\n        cprintf (verbose, \"OA unittest: also run ptest.py to perform checks!\\n\");\n\n        if (allgood) {\n                printf (\"OA unittest: all tests ok\\n\");\n                return UNITTEST_SUCCESS;\n        } else {\n                printf (\"OA unittest: ERROR!\\n\");\n                return UNITTEST_FAIL;\n        }\n}\n\n/**\n* @brief Read in files with arrays and join them into a single file\n* @param argc\n* @param argv[]\n* @return\n*/\nint main (int argc, char *argv[]) {\n\n        AnyOption opt;\n        opt.setFlag (\"help\", 'h'); /* a flag (takes no argument), supporting long and short form */\n        opt.setOption (\"verbose\", 'v');\n        opt.setOption (\"random\", 'r');\n\n        opt.addUsage (\"OA: unittest: Perform some checks on the code\");\n        opt.addUsage (\"Usage: unittest [OPTIONS]\");\n        opt.addUsage (\"\");\n        opt.addUsage (\" -v  --verbose  \t\t\tPrint documentation\");\n        opt.addUsage (\" -r  --random  \t\t\tSeed for random number generator\");\n\n        opt.processCommandArgs (argc, argv);\n        int verbose = opt.getIntValue ('v', 1);\n        int random = opt.getIntValue ('r', 0);\n\n        if (opt.getFlag (\"help\") || opt.getFlag ('h')) {\n                opt.printUsage ();\n                exit (0);\n        }\n\n        if (verbose) {\n                print_copyright ();\n        }\n        if (verbose >= 2) {\n                print_options (std::cout);\n        }\n\n        oaunittest (verbose, 1, random);\n\n        return 0;\n}\n// kate: indent-mode cstyle; indent-width 5; replace-tabs on;\n", "meta": {"hexsha": "2c62bc009e858026654ad32da27c3fc3612ea2db", "size": 29565, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "utils/oaunittest.cpp", "max_stars_repo_name": "eendebakpt/oapackage", "max_stars_repo_head_hexsha": "5bb10654f0b1d584d69004dc7251ba9f16525520", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2015-11-06T07:24:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T22:02:19.000Z", "max_issues_repo_path": "utils/oaunittest.cpp", "max_issues_repo_name": "eendebakpt/oapackage", "max_issues_repo_head_hexsha": "5bb10654f0b1d584d69004dc7251ba9f16525520", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 37.0, "max_issues_repo_issues_event_min_datetime": "2015-11-06T07:25:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T01:33:47.000Z", "max_forks_repo_path": "utils/oaunittest.cpp", "max_forks_repo_name": "eendebakpt/oapackage", "max_forks_repo_head_hexsha": "5bb10654f0b1d584d69004dc7251ba9f16525520", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2016-08-16T15:09:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-06T11:48:55.000Z", "avg_line_length": 37.5667090216, "max_line_length": 173, "alphanum_fraction": 0.435210553, "num_tokens": 6858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.49704923152894226}}
{"text": "/*\n * EllipseIterator.hpp\n *\n *  Created on: Dec 2, 2015\n *      Author: P\u00e9ter Fankhauser\n *   Institute: ETH Zurich, Autonomous Systems Lab\n */\n\n#include \"grid_map_core/iterators/EllipseIterator.hpp\"\n#include \"grid_map_core/GridMapMath.hpp\"\n\n#include <math.h>\n#include <Eigen/Geometry>\n\nusing namespace std;\n\nnamespace grid_map {\n\nEllipseIterator::EllipseIterator(const GridMap& gridMap, const Position& center, const Length& length, const double rotation)\n    : center_(center)\n{\n  semiAxisSquare_ = (0.5 * length).square();\n  double sinRotation = sin(rotation);\n  double cosRotation = cos(rotation);\n  transformMatrix_ << cosRotation, sinRotation, sinRotation, -cosRotation;\n  mapLength_ = gridMap.getLength();\n  mapPosition_ = gridMap.getPosition();\n  resolution_ = gridMap.getResolution();\n  bufferSize_ = gridMap.getSize();\n  bufferStartIndex_ = gridMap.getStartIndex();\n  Index submapStartIndex;\n  Index submapBufferSize;\n  findSubmapParameters(center, length, rotation, submapStartIndex, submapBufferSize);\n  internalIterator_ = std::shared_ptr<SubmapIterator>(new SubmapIterator(gridMap, submapStartIndex, submapBufferSize));\n  if(!isInside()) ++(*this);\n}\n\nEllipseIterator& EllipseIterator::operator =(const EllipseIterator& other)\n{\n  center_ = other.center_;\n  semiAxisSquare_ = other.semiAxisSquare_;\n  transformMatrix_ = other.transformMatrix_;\n  internalIterator_ = other.internalIterator_;\n  mapLength_ = other.mapLength_;\n  mapPosition_ = other.mapPosition_;\n  resolution_ = other.resolution_;\n  bufferSize_ = other.bufferSize_;\n  bufferStartIndex_ = other.bufferStartIndex_;\n  return *this;\n}\n\nbool EllipseIterator::operator !=(const EllipseIterator& other) const\n{\n  return (internalIterator_ != other.internalIterator_);\n}\n\nconst Eigen::Array2i& EllipseIterator::operator *() const\n{\n  return *(*internalIterator_);\n}\n\nEllipseIterator& EllipseIterator::operator ++()\n{\n  ++(*internalIterator_);\n  if (internalIterator_->isPastEnd()) return *this;\n\n  for ( ; !internalIterator_->isPastEnd(); ++(*internalIterator_)) {\n    if (isInside()) break;\n  }\n\n  return *this;\n}\n\nbool EllipseIterator::isPastEnd() const\n{\n  return internalIterator_->isPastEnd();\n}\n\nbool EllipseIterator::isInside()\n{\n  Position position;\n  getPositionFromIndex(position, *(*internalIterator_), mapLength_, mapPosition_, resolution_, bufferSize_, bufferStartIndex_);\n  double value = ((transformMatrix_ * (position - center_)).array().square() / semiAxisSquare_).sum();\n  return (value <= 1);\n}\n\nvoid EllipseIterator::findSubmapParameters(const Position& center, const Length& length, const double rotation,\n                                           Index& startIndex, Size& bufferSize) const\n{\n  const Eigen::Rotation2Dd rotationMatrix(rotation);\n  Eigen::Vector2d u = rotationMatrix * Eigen::Vector2d(length(0), 0.0);\n  Eigen::Vector2d v = rotationMatrix * Eigen::Vector2d(0.0, length(1));\n  const Length boundingBoxHalfLength = (u.cwiseAbs2() + v.cwiseAbs2()).array().sqrt();\n  Position topLeft = center.array() + boundingBoxHalfLength;\n  Position bottomRight = center.array() - boundingBoxHalfLength;\n  limitPositionToRange(topLeft, mapLength_, mapPosition_);\n  limitPositionToRange(bottomRight, mapLength_, mapPosition_);\n  getIndexFromPosition(startIndex, topLeft, mapLength_, mapPosition_, resolution_, bufferSize_, bufferStartIndex_);\n  Index endIndex;\n  getIndexFromPosition(endIndex, bottomRight, mapLength_, mapPosition_, resolution_, bufferSize_, bufferStartIndex_);\n  bufferSize = endIndex - startIndex + Eigen::Array2i::Ones();\n}\n\n} /* namespace grid_map */\n\n", "meta": {"hexsha": "1313e6327b838473e4ee008e90d4d28b779c72c0", "size": 3565, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "grid_map_core/src/iterators/EllipseIterator.cpp", "max_stars_repo_name": "EricLYang/grid_map", "max_stars_repo_head_hexsha": "4c0defae8b2860060679d914bce969a38a478e9b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-08-29T01:29:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-17T08:29:27.000Z", "max_issues_repo_path": "grid_map_core/src/iterators/EllipseIterator.cpp", "max_issues_repo_name": "ycb88/grid_map", "max_issues_repo_head_hexsha": "93ca546f48012b7b0c500c730bd7d878c9a4e47e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "grid_map_core/src/iterators/EllipseIterator.cpp", "max_forks_repo_name": "ycb88/grid_map", "max_forks_repo_head_hexsha": "93ca546f48012b7b0c500c730bd7d878c9a4e47e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-17T08:29:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-17T08:29:30.000Z", "avg_line_length": 33.6320754717, "max_line_length": 127, "alphanum_fraction": 0.747545582, "num_tokens": 860, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672320414787, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4970323408691968}}
{"text": "\n\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <math.h>\n\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/properties.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <boost/program_options.hpp>\n\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <boost/graph/depth_first_search.hpp>\n#include <boost/graph/prim_minimum_spanning_tree.hpp>\n#include <boost/graph/kruskal_min_spanning_tree.hpp>\n\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Delaunay_triangulation_3.h>\n#include <CGAL/Triangulation_data_structure_3.h>\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\ntypedef CGAL::Delaunay_triangulation_3<K>                   Triangulation;\ntypedef Triangulation::Point                                Point;\n\n// using a global for this is not good. I really should be passing it\n// some other way.\ndouble scale_z=1.0;\n\n// these two functions are for my readvtk function.\nTriangulation::Vertex_handle\nadd_vertex(Triangulation &T, std::string& vname, double x, double y, double z)\n{\n  // the exp(z) scaling shouldn't be done here.\n  // max value of z is 1000. in that case, z/1000 =1.\n  // which leaves us with exp(log(1000) which == 1000\n  double newz = scale_z*exp(log(1000.0)*z/1000.0);;\n  return T.insert(Point(x,y,newz));\n}\n\nvoid add_edge(Triangulation &T,\n               Triangulation::Vertex_handle s,\n               Triangulation::Vertex_handle t)\n{\n  // no edges to add. CGAL does that.\n}\n\n#include <readvtk.hxx>\n\nstruct VertexData {\n  std::string name;\n  double x,y,z;\n};\n\nstruct EdgeData {\n  double distance;\n};\n\ntypedef boost::adjacency_list<boost::vecS, boost::vecS,\n                              boost::undirectedS,\n                              VertexData,\n                              boost::property<boost::edge_weight_t, double, EdgeData>\n                              > MyGraphType;\n\n\n\n// these are needed by readvtk\ntypedef typename boost::graph_traits<MyGraphType>::vertex_descriptor vertex_descriptor;\ntypedef typename boost::graph_traits<MyGraphType>::edge_descriptor   edge_descriptor;\ntypename boost::graph_traits<MyGraphType>::vertex_descriptor\nadd_vertex(MyGraphType &G, std::string& vname, double x, double y, double z)\n{\n  typedef typename boost::graph_traits<MyGraphType>::vertex_descriptor vertex_descriptor;\n  vertex_descriptor v = add_vertex(G);\n  G[v].x = x;\n  G[v].y = y;\n  G[v].z = z;\n  return v;\n}\n\ninline\ndouble distance(MyGraphType &G,\n                typename boost::graph_traits<MyGraphType>::vertex_descriptor v1,\n                typename boost::graph_traits<MyGraphType>::vertex_descriptor v2)\n{\n  return sqrt((G[v1].x - G[v2].x)*(G[v1].x - G[v2].x) +\n              (G[v1].y - G[v2].y)*(G[v1].y - G[v2].y) +\n              (G[v1].z - G[v2].z)*(G[v1].z - G[v2].z));\n}\n\n\ntypename boost::graph_traits<MyGraphType>::edge_descriptor\nadd_edge(MyGraphType &G,\n         typename boost::graph_traits<MyGraphType>::vertex_descriptor v1,\n         typename boost::graph_traits<MyGraphType>::vertex_descriptor v2)\n{\n  typedef typename boost::graph_traits<MyGraphType>::edge_descriptor edge_descriptor;\n  edge_descriptor e = add_edge(v1, v2, G).first;\n  boost::property_map<MyGraphType, boost::edge_weight_t>::type weightmap = get(boost::edge_weight, G);\n  weightmap[e] = distance(G, v1, v2);\n  return e;\n}\n\n\n\n#include <readvtk.hxx>\n\n\nenum MSTAlgorithm { PRIM, KRUSKAL };\nstd::istream& operator>>(std::istream& in, MSTAlgorithm &format)\n{\n    std::string token;\n    in >> token;\n    if (token == \"prim\")\n        format = PRIM;\n    else if (token == \"kruskal\")\n        format = KRUSKAL;\n    else \n        in.setstate(std::ios_base::failbit);\n    return in;\n}\n\n\nint\nmain(int argc,char* argv[])\n{\n\n  namespace po = boost::program_options;\n  po::options_description desc(\"Usage\");\n\n  std::string filename;\n  desc.add_options()\n    (\"help\", \"produce help message\")\n    (\"filename\", po::value<std::string>(&filename)->default_value(\"\"),\n     \"filename containing input points\");\n\n  MSTAlgorithm mst_algorithm;\n    desc.add_options()\n        (\"algorithm\", po::value<MSTAlgorithm>(&mst_algorithm)->default_value(KRUSKAL),\n         \"which output format\");    \n\n    desc.add_options()\n        (\"scale\", po::value<double>(&scale_z)->default_value(1.0),\n         \"scale factor\");\n        \n    \n  po::variables_map opts;\n  po::store(po::parse_command_line(argc, argv, desc), opts);\n\n  try {\n    po::notify(opts);\n  } catch (std::exception& e) {\n    std::cerr << \"Error: \" << e.what() << \"\\n\";\n    return 1;\n  }\n\n  if (filename == \"\") {\n    std::cerr << \"please provide a vtk file with the --filename <file> option\" << std::endl;\n    exit(-1);\n  }\n  std::ifstream input(filename.c_str());\n\n  std::cerr << \"using scale factor \" << scale_z << std::endl;\n  \n  Triangulation T;\n  readvtk<Triangulation,Triangulation::Vertex_handle>(input, T);\n  assert( T.is_valid() ); // checking validity of T\n\n  // at this point, the points have been loaded and the triangulation is done.\n  \n  MyGraphType G;\n\n  std::map<Point, MyGraphType::vertex_descriptor> vertex_map;\n\n  Triangulation::Finite_vertices_iterator viter;\n  for (viter =  T.finite_vertices_begin();\n       viter != T.finite_vertices_end();\n       viter++) {\n    Triangulation::Triangulation_data_structure::Vertex v = *viter;\n    Point p = v.point();\n    double x = CGAL::to_double(p.x());\n    double y = CGAL::to_double(p.y());\n    double z = CGAL::to_double(p.z());\n    std::string d(\"\");\n    auto boost_vertex = vertex_map[v.point()] = add_vertex(G, d, x,y,z);\n    \n  }\n\n  Triangulation::Finite_edges_iterator iter;\n  for(iter =  T.finite_edges_begin();\n      iter != T.finite_edges_end();\n      iter++) {\n    // edges are not represented as edges in CGAL triangulation graphs.\n    // Instead, they are stored in faces/cells.\n\n    Triangulation::Triangulation_data_structure::Edge e = *iter;\n    Triangulation::Triangulation_data_structure::Cell_handle c = e.first;\n    int i = e.second;\n    int j = e.third;\n    auto boost_edge = add_edge(G, vertex_map[c->vertex(i)->point()], vertex_map[c->vertex(j)->point()]);\n  }\n\n\n  \n  \n  std::cerr << \"running prim\" << std::endl;\n  std::vector<vertex_descriptor> mst_prim(num_vertices(G));\n\n  std::cout << \"# vtk DataFile Version 1.0\\n\";\n  std::cout << \"3D triangulation data\\n\";\n  std::cout << \"ASCII\\n\";\n  std::cout << std::endl;\n  std::cout << \"DATASET POLYDATA\\n\";\n\n  std::cout << \"POINTS \" << num_vertices(G) << \" float\\n\";\n  for(int i=0; i<num_vertices(G); i++) {\n    std::cout << G[i].x  << \" \" << G[i].y << \" \" << G[i].z << std::endl;\n  }\n\n  std::cout << \"LINES \" << (num_vertices(G)-1) << \" \" << (num_vertices(G)-1)*3 << std::endl;\n  if (mst_algorithm == PRIM) {\n  \n    // the not particularly helpful doc for iterator_property_map:\n    // http://www.boost.org/doc/libs/1_64_0/libs/property_map/doc/iterator_property_map.html\n    // iterator_property_map<RandomAccessIterator, OffsetMap, T, R>\n    //\n    typedef boost::property_map<MyGraphType, boost::vertex_index_t>::type IdMap;\n    boost::iterator_property_map<std::vector<vertex_descriptor>::iterator,\n                                 IdMap,\n                                 vertex_descriptor,\n                                 vertex_descriptor&>\n      predmap(mst_prim.begin(), get(boost::vertex_index, G));\n                                       \n    boost::prim_minimum_spanning_tree(G, predmap);\n\n    for(int i=0; i<num_vertices(G); i++) {\n      if (i == mst_prim[i]) {\n        std::cerr << \"skipping \" << i << std::endl;\n        continue;\n      }\n      std::cout << \"2 \" << i << \" \" << mst_prim[i] << std::endl;\n    }\n  }\n\n  if (mst_algorithm == KRUSKAL) {\n    std::cerr << \"running kruskal\" << std::endl;\n    std::list<boost::graph_traits<MyGraphType>::edge_descriptor> mst_kruskal;\n    boost::kruskal_minimum_spanning_tree(G, std::back_inserter(mst_kruskal));\n\n    for(auto iter=mst_kruskal.begin();\n        iter != mst_kruskal.end();\n        iter++) {\n      std::cout << \"2 \" << source(*iter, G) << \" \" << target(*iter, G) <<std::endl;\n    }\n  }\n  \n}\n", "meta": {"hexsha": "35b260c706374eb63defc94d37438f05b920cef8", "size": 8029, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "delaunay_mst_3d/delaunay_mst_3d.cxx", "max_stars_repo_name": "mmccoo/nerd_mmccoo", "max_stars_repo_head_hexsha": "dc5a152105d65673679ef37ea5d1f7607e4f3b2c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 45.0, "max_stars_repo_stars_event_min_datetime": "2017-06-21T07:46:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T01:39:02.000Z", "max_issues_repo_path": "delaunay_mst_3d/delaunay_mst_3d.cxx", "max_issues_repo_name": "zxh1986123/nerd_mmccoo", "max_issues_repo_head_hexsha": "dc5a152105d65673679ef37ea5d1f7607e4f3b2c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2018-02-08T19:29:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-14T09:27:18.000Z", "max_forks_repo_path": "delaunay_mst_3d/delaunay_mst_3d.cxx", "max_forks_repo_name": "zxh1986123/nerd_mmccoo", "max_forks_repo_head_hexsha": "dc5a152105d65673679ef37ea5d1f7607e4f3b2c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 23.0, "max_forks_repo_forks_event_min_datetime": "2018-02-12T21:18:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-21T23:04:51.000Z", "avg_line_length": 31.1201550388, "max_line_length": 104, "alphanum_fraction": 0.6409266409, "num_tokens": 2133, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971212, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4970323351831048}}
{"text": "/**************************************************************************\n** This file is a part of our work (Siggraph'16 paper, binary, code and dataset):\n**\n** Roto++: Accelerating Professional Rotoscoping using Shape Manifolds\n** Wenbin Li, Fabio Viola, Jonathan Starck, Gabriel J. Brostow and Neill D.F. Campbell\n**\n** w.li AT cs.ucl.ac.uk\n** http://visual.cs.ucl.ac.uk/pubs/rotopp\n**\n** Copyright (c) 2016, Wenbin Li\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 and data must retain the above\n**    copyright notice, this list of conditions and the following disclaimer.\n** -- Redistributions in binary form must reproduce the above copyright\n**    notice, this list of conditions and the following disclaimer in the\n**    documentation and/or other materials provided with the distribution.\n**\n** THIS WORK AND THE RELATED SOFTWARE, SOURCE CODE AND DATA IS PROVIDED BY\n** THE COPYRIGHT 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 DISCLAIMED. IN\n** NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n** INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n** BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n** USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n** 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,\n** EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***************************************************************************/\n\n#ifndef TRANSFORMATIONS_H\n#define TRANSFORMATIONS_H\n\n#include \"ceres/ceres.h\"\n#include \"glog/logging.h\"\n#include \"ceres/solver.h\"\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/SparseCore>\n#include <Eigen/Eigenvalues>\n\ntypedef Eigen::MatrixXd Matrix;\ntypedef Eigen::VectorXd Vector;\n\n#include \"baseDefs.hpp\"\n\ntemplate <typename T>\nEigen::Matrix<T, 2, 2> RotationMatrixFromAngle(const T& alpha)\n{\n    Eigen::Matrix<T, 2, 2> Q;\n    Q << cos(alpha), -sin(alpha), sin(alpha), cos(alpha);\n    return Q;\n}\n\ntemplate <typename T>\nEigen::Matrix<T, 2, 2> RotationMatrixDerivativeFromAngle(const T& alpha)\n{\n    Eigen::Matrix<T, 2, 2> Q;\n    Q << -sin(alpha), -cos(alpha), cos(alpha), -sin(alpha);\n    return Q;\n}\n\nstruct RigidMotionEstimator\n{\nprivate:\n    Eigen::MatrixXd _Y;\n    Eigen::MatrixXd _translations;\n    Eigen::VectorXd _rotations;\n    Eigen::MatrixXd _referencePoints;\n    int _numPoints;\n\npublic:\n    RigidMotionEstimator(const Eigen::MatrixXd& Y);\n\n    Eigen::MatrixXd CalcNormalisedY() const;\n\n    void SaveToFile(const std::string matlabFilename) const;\n\n    const Eigen::MatrixXd& translations() const\n    {\n        return _translations;\n    }\n\n    const Eigen::VectorXd& rotations() const\n    {\n        return _rotations;\n    }\n\n    const Eigen::MatrixXd& referencePoints() const\n    {\n        return _referencePoints;\n    }\n\n    int numPoints() //const\n    {\n        return _numPoints;\n    }\n\n    Eigen::Matrix2d GetRotationMatrix(int index) const\n    {\n        nassert ((index >=0) && (index < _Y.rows()));\n\n        return Eigen::Matrix2d(RotationMatrixFromAngle(_rotations[index]));\n    }\n\nprivate:\n    void Initialise();\n\n    bool Solve();\n\n    void testRotation() const\n    {\n        const double alpha = 0.5;\n        Eigen::Matrix2d Q(RotationMatrixFromAngle(alpha));\n        vdbg(Q);\n    }\n\n};\n\n#endif // TRANSFORMATIONS_H\n", "meta": {"hexsha": "d08452e07f01ac8a5dde7fab58a893c90f70f36c", "size": 3737, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/rotoSolver/transformations.hpp", "max_stars_repo_name": "vinben/Rotopp", "max_stars_repo_head_hexsha": "f0c25db5bd25074c55ff0f67539a2452d92aaf72", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 47.0, "max_stars_repo_stars_event_min_datetime": "2016-07-27T07:22:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-17T13:08:19.000Z", "max_issues_repo_path": "include/rotoSolver/transformations.hpp", "max_issues_repo_name": "vinben/Rotopp", "max_issues_repo_head_hexsha": "f0c25db5bd25074c55ff0f67539a2452d92aaf72", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-09-24T06:04:39.000Z", "max_issues_repo_issues_event_max_datetime": "2016-09-25T10:34:19.000Z", "max_forks_repo_path": "include/rotoSolver/transformations.hpp", "max_forks_repo_name": "vinben/Rotopp", "max_forks_repo_head_hexsha": "f0c25db5bd25074c55ff0f67539a2452d92aaf72", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2016-07-27T10:44:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-01T21:08:33.000Z", "avg_line_length": 29.6587301587, "max_line_length": 86, "alphanum_fraction": 0.6783516189, "num_tokens": 860, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527631, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4970323294970124}}
{"text": "#include <iostream>\n#include <stdio.h>\n#include <sstream>\n#include <deque>\n#include <boost/multiprecision/gmp.hpp>\n\nvoid require(bool cond, const char* msg)\n{\n    if (!cond) {\n        std::cerr << \"ERROR: \" << msg << \"!\" << std::endl;\n        exit(1);\n    }\n}\n\nenum Op { LEQ, LT, GT, GEQ, EQ, ADD, SUB, MUL, DIV, AND, OR, NOT };\n\nstruct StackItem\n{\n    typedef boost::multiprecision::mpq_rational val_t;\n\n    enum Kind { OP, VAL, BV } kind;\n    Op op;\n    val_t val;\n    bool bv;\n\n    StackItem(Op o) : kind(OP), op(o) {}\n    StackItem(val_t v) : kind(VAL), val(v) {}\n    StackItem(bool b) : kind(BV), bv(b) {}\n\n    friend std::ostream& operator<< (std::ostream& stream, const StackItem& si);\n};\n\nstd::ostream& operator<< (std::ostream& stream, const StackItem& si)\n{\n    switch (si.kind) {\n        case StackItem::OP:\n            stream << \"op: \" << si.op;\n            break;\n        case StackItem::VAL:\n            stream << si.val;\n            break;\n        case StackItem::BV:\n            stream << (si.bv ? \"true\" : \"false\");\n            break;\n    }\n    return stream;\n}\n\n#define CHECK_BIN(type)\\\n            require(operands.size() == 2, \"Invalid number of arguments for binary operator\");\\\n            require(operands[0].kind == StackItem::type, \"Invalid first argument type\");\\\n            require(operands[1].kind == StackItem::type, \"Invalid second argument type\");\n\n#define CHECK_UN(type)\\\n            require(operands.size() == 1, \"Invalid number of arguments for unary operator\");\\\n            require(operands[0].kind == StackItem::type, \"Invalid argument type\");\n\nStackItem eval(Op o, const std::deque<StackItem>& operands)\n{\n    switch  (o) {\n        case LEQ: CHECK_BIN(VAL);\n            return StackItem(operands[0].val <= operands[1].val);\n        case GEQ: CHECK_BIN(VAL);\n            return StackItem(operands[0].val >= operands[1].val);\n        case LT: CHECK_BIN(VAL);\n            return StackItem(operands[0].val < operands[1].val);\n        case GT: CHECK_BIN(VAL);\n            return StackItem(operands[0].val > operands[1].val);\n        case EQ: CHECK_BIN(VAL);\n            return StackItem(operands[0].val == operands[1].val);\n        case ADD: CHECK_BIN(VAL);\n            return StackItem(operands[0].val + operands[1].val);\n        case SUB:\n            if (operands.size() == 1) {\n                CHECK_UN(VAL);\n                return StackItem(- operands[0].val);\n            } else if (operands.size() == 2) {\n                CHECK_BIN(VAL);\n                return StackItem(operands[0].val - operands[1].val);\n            } else {\n                require(false, \"Invalid number of arguments for operator '-'\");\n            }\n        case MUL: CHECK_BIN(VAL);\n            return StackItem(operands[0].val * operands[1].val);\n        case DIV: CHECK_BIN(VAL);\n            require(operands[1].val != 0, \"Division by zero\");\n            return StackItem(operands[0].val / operands[1].val);\n        case AND: CHECK_BIN(BV);\n            return StackItem(operands[0].bv && operands[1].bv);\n        case OR: CHECK_BIN(BV);\n            return StackItem(operands[0].bv || operands[1].bv);\n        case NOT: CHECK_UN(BV);\n            return StackItem(!operands[0].bv);\n        default:\n            require(false, \"Invalid operation!\");\n    }\n}\n\n#define EXPECT(x) require(std::getchar() == x, \"Expected \" #x);\n\nint main(int argc, char *argv[])\n{\n    std::deque<StackItem> stack;\n    char chr = std::getchar();\n    while (chr != EOF) {\n        switch (chr) {\n            case '<':\n                chr = std::getchar();\n                if (chr == '=') {\n                    stack.emplace_back(Op::LEQ);\n                } else {\n                    stack.emplace_back(Op::LT);\n                    continue;\n                }\n                break;\n            case '>':\n                chr = std::getchar();\n                if (chr == '=') {\n                    stack.emplace_back(Op::GEQ);\n                } else {\n                    stack.emplace_back(Op::GT);\n                    continue;\n                }\n                break;\n            case '=':\n                stack.emplace_back(Op::EQ);\n                break;\n            case 'a': EXPECT('n'); EXPECT('d');\n                stack.emplace_back(Op::AND);\n                break;\n            case 'o': EXPECT('r');\n                stack.emplace_back(Op::OR);\n                break;\n            case 'n': EXPECT('o'); EXPECT('t');\n                stack.emplace_back(Op::NOT);\n                break;\n            case '+':\n                stack.emplace_back(Op::ADD);\n                break;\n            case '-':\n                stack.emplace_back(Op::SUB);\n                break;\n            case '*':\n                stack.emplace_back(Op::MUL);\n                break;\n            case '/':\n                stack.emplace_back(Op::DIV);\n                break;\n            case '0': case '1': case '2': case '3': case '4':\n            case '5': case '6': case '7': case '8': case '9': {\n                    std::stringstream sb;\n                    sb << chr;\n                    chr = getchar();\n                    while (chr >= '0' && chr <= '9') {\n                        sb << chr;\n                        chr = getchar();\n                    }\n                    stack.emplace_back(StackItem::val_t(sb.str()));\n                    continue;\n                }\n                break;\n            case ')': {\n                    std::deque<StackItem> v;\n                    while (stack.back().kind != StackItem::OP) {\n                        v.push_front(stack.back());\n                        stack.pop_back();\n                    }\n                    auto o = stack.back().op;\n                    stack.pop_back();\n                    stack.push_back(eval(o, v));\n                }\n                break;\n            case ' ': case '\\n': case '\\t': case '(':\n                break;\n            default:\n                require(false, \"Invalid input\");\n        }\n        chr = getchar();\n    }\n\n    for (const auto& si : stack) {\n        std::cout << \"> \" << si << std::endl;\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "c7576492fd159beb84237d0fcad60a3c3f34a33f", "size": 6085, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/fLispEval.cpp", "max_stars_repo_name": "fabian-r/fLispEval", "max_stars_repo_head_hexsha": "ca6a7ccaa579a4d1277d1a2790de504ee6a4ff28", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/fLispEval.cpp", "max_issues_repo_name": "fabian-r/fLispEval", "max_issues_repo_head_hexsha": "ca6a7ccaa579a4d1277d1a2790de504ee6a4ff28", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/fLispEval.cpp", "max_forks_repo_name": "fabian-r/fLispEval", "max_forks_repo_head_hexsha": "ca6a7ccaa579a4d1277d1a2790de504ee6a4ff28", "max_forks_repo_licenses": ["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.5401069519, "max_line_length": 94, "alphanum_fraction": 0.4599835661, "num_tokens": 1395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.808067204308405, "lm_q2_score": 0.6150878555160666, "lm_q1q2_score": 0.49703232381092005}}
{"text": "/*----------------------------------------------------------------------------*/\n/* Copyright (c) 2019-2020 FIRST. All Rights Reserved.                        */\n/* Open Source Software - may be modified and shared by FRC teams. The code   */\n/* must be accompanied by the FIRST BSD license file in the root directory of */\n/* the project.                                                               */\n/*----------------------------------------------------------------------------*/\n\n#include <jni.h>\n\n#include <iostream>\n\n#include <Eigen/Core>\n#include <unsupported/Eigen/MatrixFunctions>\n\n#include \"drake/math/discrete_algebraic_riccati_equation.h\"\n#include \"edu_wpi_first_wpiutil_math_DrakeJNI.h\"\n#include \"wpi/jni_util.h\"\n\nusing namespace wpi::java;\n\nextern \"C\" {\n\n/*\n * Class:     edu_wpi_first_wpiutil_math_DrakeJNI\n * Method:    discreteAlgebraicRiccatiEquation\n * Signature: ([D[D[D[DII[D)V\n */\nJNIEXPORT void JNICALL\nJava_edu_wpi_first_wpiutil_math_DrakeJNI_discreteAlgebraicRiccatiEquation\n  (JNIEnv* env, jclass, jdoubleArray A, jdoubleArray B, jdoubleArray Q,\n   jdoubleArray R, jint states, jint inputs, jdoubleArray S)\n{\n  jdouble* nativeA = env->GetDoubleArrayElements(A, nullptr);\n  jdouble* nativeB = env->GetDoubleArrayElements(B, nullptr);\n  jdouble* nativeQ = env->GetDoubleArrayElements(Q, nullptr);\n  jdouble* nativeR = env->GetDoubleArrayElements(R, nullptr);\n\n  Eigen::Map<\n      Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>\n      Amat{nativeA, states, states};\n  Eigen::Map<\n      Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>\n      Bmat{nativeB, states, inputs};\n  Eigen::Map<\n      Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>\n      Qmat{nativeQ, states, states};\n  Eigen::Map<\n      Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>\n      Rmat{nativeR, inputs, inputs};\n\n  Eigen::MatrixXd result =\n      drake::math::DiscreteAlgebraicRiccatiEquation(Amat, Bmat, Qmat, Rmat);\n\n  env->ReleaseDoubleArrayElements(A, nativeA, 0);\n  env->ReleaseDoubleArrayElements(B, nativeB, 0);\n  env->ReleaseDoubleArrayElements(Q, nativeQ, 0);\n  env->ReleaseDoubleArrayElements(R, nativeR, 0);\n\n  env->SetDoubleArrayRegion(S, 0, states * states, result.data());\n}\n\n}  // extern \"C\"\n", "meta": {"hexsha": "8e5f4da4f98aa8ecef8e4ee1b93321a17ef5df9f", "size": 2297, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "wpiutil/src/main/native/cpp/jni/DrakeJNI.cpp", "max_stars_repo_name": "carbotaniuman/allwpilib", "max_stars_repo_head_hexsha": "5cf4c16f5b2d3ae0ba49d928f4285e400d05497a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "wpiutil/src/main/native/cpp/jni/DrakeJNI.cpp", "max_issues_repo_name": "carbotaniuman/allwpilib", "max_issues_repo_head_hexsha": "5cf4c16f5b2d3ae0ba49d928f4285e400d05497a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "wpiutil/src/main/native/cpp/jni/DrakeJNI.cpp", "max_forks_repo_name": "carbotaniuman/allwpilib", "max_forks_repo_head_hexsha": "5cf4c16f5b2d3ae0ba49d928f4285e400d05497a", "max_forks_repo_licenses": ["BSD-3-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.4603174603, "max_line_length": 80, "alphanum_fraction": 0.6478014802, "num_tokens": 589, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080671950640463, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.49703231812482723}}
{"text": "#include \"globals.hpp\"\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/boykov_kolmogorov_max_flow.hpp>\n#include <boost/graph/connected_components.hpp>\n// #include <iostream>\n#include <vector>\n\n// #include <boost/graph/graphviz.hpp>\n\nusing namespace boost;\n\ntypedef adjacency_list_traits<vecS, vecS, directedS> Traits;\n\n// typedef adjacency_list<vecS, vecS, directedS,\n//                        property<vertex_name_t, std::string>,\n//                        property<edge_capacity_t, int,\n//                                 property<edge_residual_capacity_t, int,\n//                                          property<edge_reverse_t,\n//                                          Traits::edge_descriptor>>>>\n//     Graph;\n\ntypedef adjacency_list<\n    vecS, vecS, directedS,\n    property<vertex_name_t, std::string,\n             property<vertex_index_t, long,\n                      property<vertex_color_t, boost::default_color_type,\n                               property<vertex_distance_t, long,\n                                        property<vertex_predecessor_t,\n                                                 Traits::edge_descriptor>>>>>,\n    property<edge_capacity_t, double,\n             property<edge_residual_capacity_t, double,\n                      property<edge_reverse_t, Traits::edge_descriptor>>>>\n    Graph;\n\n// Prepare to do multiple min cuts (cache graphs etc.)\nvoid prepareForMinCuts() {\n  totalClasses = 0;\n  for (int i = 0; i < classPoints.size(); i++) {\n    if (classPoints[i].cls + 1 > totalClasses) {\n      totalClasses = classPoints[i].cls + 1;\n    }\n    if (verboseMode) {\n      printf(\"clspt %d: (%d, %d)\\n\", classPoints[i].cls, classPoints[i].ri,\n             classPoints[i].ci);\n    }\n  }\n  clsMasks = vector<vector<int>>(numClusters, vector<int>(totalClasses, 0));\n}\n\n// Perform a min cut against a cls\nvoid minCutCls(int targetCls) {\n  Traits::vertex_descriptor s, t;\n\n  Graph g;\n\n  property_map<Graph, edge_capacity_t>::type capacity = get(edge_capacity, g);\n  property_map<Graph, edge_reverse_t>::type rev = get(edge_reverse, g);\n  property_map<Graph, edge_residual_capacity_t>::type residual_capacity =\n      get(edge_residual_capacity, g);\n\n  double flow;\n\n  std::vector<Traits::vertex_descriptor> verts;\n\n  verts.reserve(numClusters + 2);\n  for (int i = 0; i < numClusters + 2; i++) {\n    verts.push_back(add_vertex(g));\n  }\n\n  for (auto &sp1 : spAdjMap) {\n    const int vi1 = sp1.first.first, vi2 = sp1.first.second;\n    Traits::edge_descriptor e1, e2;\n    bool in1, in2;\n    boost::tie(e1, in1) = add_edge(verts[vi1], verts[vi2], g);\n    boost::tie(e2, in2) = add_edge(verts[vi2], verts[vi1], g);\n    if (!in1 || !in2) {\n      // std::cerr << \"unable to add edge\" << std::endl;\n      continue;\n    }\n    capacity[e1] = sp1.second;\n    capacity[e2] = sp1.second;\n    rev[e1] = e2;\n    rev[e2] = e1;\n    // for (auto &sp2 : sp1.second) {\n    //   const int vi1 = sp1.first, vi2 = sp2.first;\n    //   if (vi1 >= vi2)\n    //     continue;\n    //   Traits::edge_descriptor e1, e2;\n    //   bool in1, in2;\n    //   boost::tie(e1, in1) = add_edge(verts[vi1], verts[vi2], g);\n    //   boost::tie(e2, in2) = add_edge(verts[vi2], verts[vi1], g);\n    //   if (!in1 || !in2) {\n    //     // std::cerr << \"unable to add edge\" << std::endl;\n    //     continue;\n    //   }\n    //   capacity[e1] = sp2.second;\n    //   capacity[e2] = sp2.second;\n    //   rev[e1] = e2;\n    //   rev[e2] = e1;\n    // }\n  }\n\n  s = verts[numClusters];\n  t = verts[numClusters + 1];\n\n  std::unordered_set<int> visitedSP;\n  // Add source/target edges\n  for (int cpi = 0; cpi < classPoints.size(); cpi++) {\n    const ClassPoint cp = classPoints[cpi];\n    const int cci = clusters[cp.ri][cp.ci];\n    if (visitedSP.find(cci) != visitedSP.end())\n      continue;\n    visitedSP.insert(cci);\n    const auto v = verts[cci];\n\n    Traits::vertex_descriptor *sourceorsink;\n    if (cp.cls == targetCls) {\n      sourceorsink = &s;\n    } else {\n      sourceorsink = &t;\n    }\n\n    Traits::edge_descriptor e1, e2;\n    bool in1, in2;\n    boost::tie(e1, in1) = add_edge(v, *sourceorsink, g);\n    boost::tie(e2, in2) = add_edge(*sourceorsink, v, g);\n    if (!in1 || !in2) {\n      continue;\n    }\n\n    rev[e1] = e2;\n    rev[e2] = e1;\n\n    capacity[e1] = 1000;\n    capacity[e2] = 1000;\n  }\n\n  // write_graphviz(std::cout, g, default_writer(),\n  // make_label_writer(capacity));\n\n  flow = boykov_kolmogorov_max_flow(g, s, t);\n\n  if (verboseMode) {\n    printf(\"flow: %f\\n\", flow);\n  }\n\n  // remove edges with zero residual capacity\n\n  // auto epair = edges(g);\n  // for (auto ei = epair.first; ei != epair.second; ei++)\n  // {\n  //     std::cout << \"edge: \" << source(*ei, g) << \"-\" << target(*ei, g) << \"\n  //     \" << residual_capacity[*ei] << std::endl;\n  // }\n\n  // write_graphviz(std::cout, g, default_writer());\n\n  auto eiter = edges(g);\n  std::vector<Traits::edge_descriptor> edgesToRemove;\n  for (auto ei = eiter.first; ei != eiter.second; ei++) {\n    if (residual_capacity[*ei] == 0) {\n      edgesToRemove.push_back(*ei);\n      edgesToRemove.push_back(rev[*ei]);\n    }\n  }\n\n  for (auto edge : edgesToRemove) {\n    remove_edge(edge, g);\n  }\n\n  // write_graphviz(std::cout, g, default_writer(),\n  // make_label_writer(residual_capacity));\n\n  // std::cout << \"edges remaining...\" << std::endl;\n\n  // auto epair = edges(g);\n  // for (auto ei = epair.first; ei != epair.second; ei++)\n  // {\n  //     std::cout << \"edge: \" << source(*ei, g) << \"-\" << target(*ei, g) <<\n  //     std::endl;\n  //     // remove_edge(*ei, g);\n  // }\n\n  // write_graphviz(std::cout, g, default_writer());\n\n  std::vector<int> components(num_vertices(g));\n  int totalConnectedComponents = connected_components(g, &components[0]);\n\n  // for (int i = 0; i < components.size(); i++)\n  // {\n  //     std::cout << \"Vertex \" << i << \" is in component \" << components[i] <<\n  //     std::endl;\n  // }\n\n  int clsComponentIndex = components[numClusters];\n  int othComponentIndex = components[numClusters + 1];\n\n  for (int cci = 0; cci < numClusters; cci++) {\n    clsMasks[cci][targetCls] = std::numeric_limits<int>::max();\n  }\n\n  for (int cci = 0; cci < numClusters; cci++) {\n    if (components[cci] == clsComponentIndex) {\n      // If connected to source, take distance\n      clsMasks[cci][targetCls] = get(vertex_distance, g)[verts[cci]];\n    } else {\n      // If connected to sink, take inverse distance\n      clsMasks[cci][targetCls] =\n          maxClusters - get(vertex_distance, g)[verts[cci]];\n    }\n  }\n\n  // std::cout << clsMasks << std::endl;\n}\n\nvoid resolveMasks() {\n  vector<int> resolvedMasks(numClusters);\n  for (int cci = 0; cci < numClusters; cci++) {\n    int smallestCls = -1;\n    int smallestDist = std::numeric_limits<int>::max();\n    for (int cls = 0; cls < totalClasses; cls++) {\n      if (clsMasks[cci][cls] < smallestDist) {\n        smallestDist = clsMasks[cci][cls];\n        smallestCls = cls;\n      }\n    }\n    resolvedMasks[cci] = smallestCls;\n  }\n  if (verboseMode) {\n    for (int cci = 0; cci < numClusters; cci++) {\n      printf(\"cci %d: %d\\n\", cci, resolvedMasks[cci]);\n    }\n  }\n  coloredMask = std::vector<uint32_t>(width * height);\n  for (int ri = 0; ri < height; ri++) {\n    for (int ci = 0; ci < width; ci++) {\n      const int imgi = ri * width + ci;\n      const int cci = clusters[ri][ci];\n      const int cls = resolvedMasks[cci];\n\n      if (cls == -1) {\n        coloredMask[imgi] = 0xffffff88;\n      } else {\n        coloredMask[imgi] = classToColor[cls];\n      }\n    }\n  }\n}\n", "meta": {"hexsha": "ebbd75d4ecf5ab66be2e2d6bc31d2acf00b893b9", "size": 7480, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "min_cut.cpp", "max_stars_repo_name": "UniversalDataTool/autoseg", "max_stars_repo_head_hexsha": "dfeffe332f558171bac62a92e5a1d07f8ec2e96c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2020-07-27T15:15:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-06T08:19:09.000Z", "max_issues_repo_path": "min_cut.cpp", "max_issues_repo_name": "UniversalDataTool/autoseg", "max_issues_repo_head_hexsha": "dfeffe332f558171bac62a92e5a1d07f8ec2e96c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-07-27T15:14:56.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-31T20:56:14.000Z", "max_forks_repo_path": "min_cut.cpp", "max_forks_repo_name": "UniversalDataTool/autoseg", "max_forks_repo_head_hexsha": "dfeffe332f558171bac62a92e5a1d07f8ec2e96c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-10-04T22:26:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-26T10:12:12.000Z", "avg_line_length": 30.0401606426, "max_line_length": 79, "alphanum_fraction": 0.579144385, "num_tokens": 2168, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120234, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.49702241024164584}}
{"text": "#pragma once\r\n\r\n#include <skynet/utility/tag.hpp>\r\n#include <skynet/ublas.hpp>\r\n\r\n#include <random>\r\n#include <boost/numeric/ublas/symmetric.hpp>\r\n\r\nnamespace skynet{namespace nn{\r\n\r\n\ttemplate <typename T>\r\n\tclass boltzmann_machine;\r\n\r\n\r\n\ttemplate <>\r\n\tclass boltzmann_machine<full_connected> {\r\n\tpublic:\r\n\t\tboltzmann_machine(size_t visible_num, size_t hidden_num)    \r\n\t\t\t: _visible_num(visible_num), _hidden_num(visible_num), _T(10), _c(0.99), _cycles_num(10),\r\n\t\t\t_eta(1.0), _k(10){\r\n\r\n\t\t}\r\n\r\n\t\ttemplate <typename T>\r\n\t\tvoid learn(const ublas::matrix_expression<T> &patterns){\r\n\t\t\tinit(patterns);\r\n\r\n\t\t\tstd::uniform_real_distribution<double> rand_energe(0, 1.0);\r\n\t\t\tstd::mt19937\t\t\t\t\t\t   mt1(std::time(nullptr));\r\n\t\t\tstd::uniform_int_distribution<size_t> rand_row(0, _clamped_signals.size1()-1);\r\n\t\t\tstd::mt19937\t\t\t\t\t\t   mt2(std::time(nullptr));\r\n\r\n\t\t\tfor (size_t k = 0; k < k(); ++k){\r\n\t\t\t\twhile (_T > 1.0){\r\n\t\t\t\t\tauto Xf = ublas::prod(_W, _free_signals);\r\n\t\t\t\t\tfor (size_t col = 0; col < pf.size2(); ++col){\r\n\t\t\t\t\t\tfor (size_t i = 0; i < _cycles_num; ++i){\r\n\t\t\t\t\t\t\tauto row = rand_row(mt2);\r\n\t\t\t\t\t\t\tauto probability = 1.0 / (1.0 + exp(-Xf(row, col)/_T));\r\n\t\t\t\t\t\t\tif (rand_energe(mt1) < probability)\r\n\t\t\t\t\t\t\t\t_free_signals(row, col) = 1;\r\n\t\t\t\t\t\t\telse\r\n\t\t\t\t\t\t\t\t_free_signals(row, col) = -1;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tauto Xc = ublas::prod(_W, _clamped_signals);\r\n\t\t\t\t\tfor (size_t col = 0; col < pf.size2(); ++col){\r\n\t\t\t\t\t\tfor (size_t i = 0; i < _cycles_num; ++i){\r\n\t\t\t\t\t\t\tauto row = rand_row(mt2);\r\n\t\t\t\t\t\t\t//if the state is clamped, do none\r\n\t\t\t\t\t\t\tif (row < _visible_num)\tcontinue;\r\n\r\n\t\t\t\t\t\t\tauto probability = 1.0 / (1.0 + exp(-Xc(row, col)/_T));\r\n\t\t\t\t\t\t\tif (rand_energe(mt1) < probability)\r\n\t\t\t\t\t\t\t\t_clamped_signals(row, col) = 1;\r\n\t\t\t\t\t\t\telse\r\n\t\t\t\t\t\t\t\t_clamped_signals(row, col) = -1;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\t_T *= _c;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tauto rep_num = _clamped_signals.size2();\r\n\t\t\t\t//update the weights\r\n\t\t\t\tublas::matrix<double> Expc =\r\n\t\t\t\t\t(1.0/rep_num) * ublas::prod(ublas::trans(_clamped_signals), _clamped_signals);\r\n\t\t\t\tublas::matrix<double> Expf =\r\n\t\t\t\t\t(1.0/rep_num) * ublas::prod(ublas::trans(_free_signals), _free_signals);\r\n\t\t\t\tauto deltaW = Expc - Expf;\r\n\t\t\t\t_W = _W + (_eta/_T) * deltaW;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tsize_t cycles_num() const\t\t\t\t\t\t{ return _cycles_num; }\r\n\t\tvoid cycles_num(size_t v)\t\t\t\t\t\t{ _cycles_num = v; }\r\n\r\n\t\tdouble T() const\t\t\t\t\t\t\t\t{ return _T; }\r\n\t\tvoid T(double v)\t\t\t\t\t\t\t\t{ _T = v; }\r\n\r\n\t\tdouble c() const\t\t\t\t\t\t\t\t{ return _c; }\r\n\t\tvoid c(double v)\t\t\t\t\t\t\t\t{ _c = v; }\r\n\r\n\t\tdouble eta() const\t\t\t\t\t\t\t\t{ return _eta; }\r\n\t\tvoid eta(double v)\t\t\t\t\t\t\t\t{ _eta = v; }\r\n\r\n\t\tdouble k() const\t\t\t\t\t\t\t\t{ return _k; }\r\n\t\tvoid k(size_t v)\t\t\t\t\t\t\t\t{ _k = v; }\r\n\r\n\tprivate:\r\n\t\ttemplate <typename T>\r\n\t\tvoid init(const ublas::matrix_expression<T> &patterns){\r\n\t\t\tASSERT(patterns.size1() == _visible_num; \"The size is not matched!\");\r\n\t\t\t//initialize weights\r\n\t\t\t_W.resize(_visible_num+_hidden_num+1);\r\n\t\t\tfor (size_t i = 0; i < _W.size1(); ++i){\r\n\t\t\t\tfor (size_t j = 0; j < _W.size2(); ++j){\r\n\t\t\t\t\t_W(i, j) = 0;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\t//random initialize the state\r\n\t\t\t_free_signals.resize(_visible_num + _hidden_num + 1, patterns().size2());\r\n\t\t\t_clamped_signals.resize(_visible_num + _hidden_num + 1, patterns().size2());\r\n\t\t\tstd::uniform_int_distribution<int> rand(0, 1);\r\n\t\t\tstd::mt19937 mt(std::time(nullptr));\r\n\t\t\tfor (int col = 0; col < _free_signals.size2(); ++col){\r\n\t\t\t\tfor (int row = 0; row < _free_signals.size1(); ++row){\r\n\t\t\t\t\t_free_signals(row, col) = rand(mt) == 0 ? -1 : 1;\r\n\t\t\t\t\t_clamped_signals(row, col) = rand(mt) == 0 ? -1 : 1;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tfor (int col = 0; col < _clamped_signals.size2(); ++col){\r\n\t\t\t\t_clamped_signals(_clamped_signals.size1()-1, col) = -1;\r\n\t\t\t}\r\n\r\n\t\t\t//set the  visible state \r\n\t\t\tfor (int col = 0; col _clamped_signals.size2(); ++col){\r\n\t\t\t\tfor (int row = 0; row < _visible_num; ++row){\r\n\t\t\t\t\t_clamped_signals(row, col) = patterns()(row, col);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\tprivate:\r\n\t\tublas::matrix<double> _free_signals;\r\n\t\tublas::matrix<double> _clamped_signals;\r\n\r\n\t\tublas::symmetric_matrix<double> _W;\r\n\r\n\t\tsize_t _visible_num;\r\n\t\tsize_t _hidden_num;\r\n\r\n\t\tdouble _T;\r\n\t\tdouble _c;\r\n\t\tdouble _eta;\r\n\t\tsize_t _cycles_num;\r\n\t\tsize_t _k;\r\n\t};\r\n\r\n}}\r\n", "meta": {"hexsha": "e7222bbc3f5c6b8086ddde2e33e1dfbdac53f91f", "size": 4197, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "skynet/neuralnetworks/boltzmann_machine.hpp", "max_stars_repo_name": "zhangzhimin/skynet", "max_stars_repo_head_hexsha": "a311b86433821a071002dd279d57333baba1f973", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2015-08-02T03:10:26.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-16T01:07:55.000Z", "max_issues_repo_path": "skynet/neuralnetworks/boltzmann_machine.hpp", "max_issues_repo_name": "zhangzhimin/skynet", "max_issues_repo_head_hexsha": "a311b86433821a071002dd279d57333baba1f973", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "skynet/neuralnetworks/boltzmann_machine.hpp", "max_forks_repo_name": "zhangzhimin/skynet", "max_forks_repo_head_hexsha": "a311b86433821a071002dd279d57333baba1f973", "max_forks_repo_licenses": ["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.3496503497, "max_line_length": 93, "alphanum_fraction": 0.5851798904, "num_tokens": 1330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.49702241024164584}}
{"text": "#define BOOST_TEST_MODULE robust_ea_solver_unit_tests\n\n#include <boost/test/included/unit_test.hpp>\n#include <armadillo>\n#include \"../src/numerical/evolutionary_algorithm/robust_ea_solver.h\"\n#include \"test_utils.cpp\"\n#include \"../src/logging/easylogging++.h\"\n\nINITIALIZE_EASYLOGGINGPP\n\nusing namespace arma;\n\nRobustEASolver solver = RobustEASolver(SIGNALS, 500, 1000, 0.0001, 100, 100);\n\nBOOST_AUTO_TEST_CASE(test_common_cases)\n{\n    auto tester = SolverTester<RobustEASolver>(solver);\n    tester.test_common(0.1);\n}\n\nBOOST_AUTO_TEST_CASE(fit_random_signals_with_outliers)\n{\n    mat weights = {-10, 1, 500};\n    mat signals = arma::randu(3, 100);\n    RobustEASolver solver = RobustEASolver(signals, 500, 1000, 0.0001, 100, 100);\n    mat signal = sum_signal(weights, signals);\n    signal[10] -= 1000;\n    signal[20] += 1000;\n    mat result = solver.solve(signal);\n    BOOST_CHECK(is_equal(weights, result, 0.1));\n}", "meta": {"hexsha": "8fa23ee9e87daa97dc791109ab147f75031c523a", "size": 913, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/robust_ea_solver_test.cpp", "max_stars_repo_name": "omyllymaki/math", "max_stars_repo_head_hexsha": "05c44762aae43268fa965104c19ba86c4284c549", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-11-04T03:43:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-05T09:12:24.000Z", "max_issues_repo_path": "tests/robust_ea_solver_test.cpp", "max_issues_repo_name": "omyllymaki/math", "max_issues_repo_head_hexsha": "05c44762aae43268fa965104c19ba86c4284c549", "max_issues_repo_licenses": ["MIT"], "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/robust_ea_solver_test.cpp", "max_forks_repo_name": "omyllymaki/math", "max_forks_repo_head_hexsha": "05c44762aae43268fa965104c19ba86c4284c549", "max_forks_repo_licenses": ["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.4516129032, "max_line_length": 81, "alphanum_fraction": 0.73932092, "num_tokens": 272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4970224102416458}}
{"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#ifdef _MSC_VER\n# pragma warning (disable : 4305) // 'initializing' : truncation from 'long double' to 'const eval_type'\n# pragma warning (disable : 4244) // 'conversion' : truncation from 'long double' to 'const eval_type'\n#endif\n\n//[policy_ref_snip4\n\n#include <boost/math/distributions/normal.hpp>\nusing boost::math::normal_distribution;\n\nusing namespace boost::math::policies;\n\n// Define a policy:\ntypedef policy<\n      promote_float<false>\n      > my_policy;\n\n// Define the new normal distribution using my_policy:\ntypedef normal_distribution<float, my_policy> my_norm;\n\n// Get a quantile:\nfloat q = quantile(my_norm(), 0.05f);\n\n//] [policy_ref_snip4]\n\n#include <iostream>\nusing std::cout; using std::endl;\n\nint main()\n{\n   cout << \" quantile(my_norm(), 0.05f) = \" << q << endl; //   -1.64485\n}\n", "meta": {"hexsha": "7df35be1cd7705e5331fe458e583cb6a7367242c", "size": 1194, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/math/example/policy_ref_snip4.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "boost/libs/math/example/policy_ref_snip4.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "boost/libs/math/example/policy_ref_snip4.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 28.4285714286, "max_line_length": 104, "alphanum_fraction": 0.7177554439, "num_tokens": 321, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245787544825, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.49702240036617973}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// statistics::model::algorithm::log_posteriors2.hpp                         //\n//                                                                           //\n//  Copyright 2009 Erwann Rogard. Distributed under the Boost                //\n//  Software License, Version 1.0. (See accompanying file                    //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)         //\n///////////////////////////////////////////////////////////////////////////////\n#ifndef BOOST_MODEL_ALGORITHM_LOG_POSTERIORS2_HPP_ER_2009\n#define BOOST_MODEL_ALGORITHM_LOG_POSTERIORS2_HPP_ER_2009\n#include <algorithm>\n#include <boost/iterator/iterator_traits.hpp>\n#include <boost/lambda/lambda.hpp>\n#include <boost/statistics/model/wrap/aggregate/prior_model_dataset.hpp>\n#include <boost/statistics/model/functional/log_prior_evaluator.hpp>\n#include <boost/statistics/model/functional/log_likelihood_evaluator.hpp>\n\nnamespace boost{\nnamespace statistics{\nnamespace model{   \n\n// Evaluates the log-postetior for each parameter in [b_p,e_p)\n// Also see log_posteriors\ntemplate<\n    typename T,typename D,typename M,typename Rx,typename Ry,typename ItP,\n    typename ItLw\n>\nItLw\nlog_posteriors2(\n    boost::statistics::model::prior_model_dataset_<D,M,Rx,Ry> pmd,\n    ItP b_p,\n    ItP e_p,\n    ItLw o_lw\n){\n    typedef log_prior_evaluator<T,D>            eval0_;\n    typedef log_likelihood_evaluator<T,M,Rx,Ry> eval_;\n    return std::transform(\n        b_p,\n        e_p,\n        o_lw,\n        boost::lambda::bind(\n            eval0_(pmd),\n            boost::lambda::_1\n        ) + boost::lambda::bind(\n            eval_(pmd),\n            boost::lambda::_1\n        )\n    );\n}\n\n// log-pdf_Q --> log_pdf P + log_pdf L - log_pdf_Q\ntemplate<\n    typename T,\n    typename D,\n    typename M,\n    typename Rx,\n    typename Ry,\n    typename ItP,\n    typename ItLw,\n    typename ItLw2\n>\nItLw2\nlog_posteriors2(\n    prior_model_dataset_<D,M,Rx,Ry> pmd,\n    ItP b_p,\n    ItP e_p,\n    ItLw b_lw,   \n    ItLw2 o_lw   // lw <- (log_posterior - lw)\n){\n    typedef log_prior_evaluator<T,D> eval0_;\n    typedef log_likelihood_evaluator<T,M,Rx,Ry> eval_;\n    eval0_ e0(pmd);\n    eval_ e(pmd);\n\n    return std::transform(\n        b_p,    //1\n        e_p,\n        b_lw,   //2\n        o_lw,\n        boost::lambda::bind(\n            e,\n            boost::lambda::_1\n        ) + \n        ( \n            boost::lambda::bind(\n                e0,\n                boost::lambda::_1\n            )\n            - boost::lambda::_2\n        )\n    );\n}\n\n}// model\n}// statistics\n}// boost\n\n#endif", "meta": {"hexsha": "09c315f93f5d5e0506205088ae31254594952d2d", "size": 2636, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "model copy/boost/statistics/model/algorithm/log_posteriors2.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": "model copy/boost/statistics/model/algorithm/log_posteriors2.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": "model copy/boost/statistics/model/algorithm/log_posteriors2.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": 27.175257732, "max_line_length": 79, "alphanum_fraction": 0.5561456753, "num_tokens": 660, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795403, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.49698823591196273}}
{"text": "//stdlib\n#include <iostream>\n\n//libraries\n#include <Eigen/Eigen>\n#include <boost/python.hpp>\n#include <boost/shared_ptr.hpp>\n\n//local\n#include <lsf_config.h>\n#include \"math/typedefs.hpp\"\n#include \"python_export/eigen_numpy.hpp\"\n#include \"python_export/math.hpp\"\n#include \"python_export/slavcheva_optimizer.hpp\"\n#include \"python_export/hierarchical_optimizer.hpp\"\n#include \"python_export/tsdf.hpp\"\n#include \"python_export/conversion_tests.hpp\"\n#include \"python_export/telemetry.hpp\"\n#include \"python_export/sdf_2_sdf_optimizer.hpp\"\n\nnamespace bp = boost::python;\nnamespace pe = python_export;\n\n\n\nBOOST_PYTHON_MODULE ( MODULE_NAME )\n{\n\tsetup_Eigen_matrix_converters();\n\tsetup_Eigen_tensor_converters();\n\tsetup_Eigen_list_converters();\n\n\tpe::export_conversion_tests();\n\n\tpe::export_math_types();\n\tpe::export_math_functions();\n\n\tpe::tsdf::export_algorithms();\n\n\tpe::export_telemetry_utilities<math::Vector2i, eig::MatrixXf, math::MatrixXv2f>(\"2d\");\n\tpe::export_telemetry_utilities<math::Vector3i, math::Tensor3f, math::Tensor3v3f>(\"3d\");\n\n\tpe::slavcheva::export_auxiliary_functions();\n\tpe::slavcheva::export_setting_singletons();\n\tpe::slavcheva::export_algorithms();\n\n\tpe::hierarchical_optimizer::export_algorithms<eig::MatrixXf, math::MatrixXv2f>(\"2d\");\n\tpe::hierarchical_optimizer::export_algorithms<math::Tensor3f, math::Tensor3v3f>(\"3d\");\n\n\tpe::sdf_2_sdf_optimizer::export_algorithms();\n}\n", "meta": {"hexsha": "028716fd961c90213f6535ad7629088965064aaa", "size": 1389, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/module.cpp", "max_stars_repo_name": "Algomorph/LevelSetFusionExperimentsCPP", "max_stars_repo_head_hexsha": "f56962f0ad5c62e6706f818062782a2e1660afda", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2019-01-07T14:12:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T01:48:03.000Z", "max_issues_repo_path": "src/module.cpp", "max_issues_repo_name": "Algomorph/LevelSetFusionExperimentsCPP", "max_issues_repo_head_hexsha": "f56962f0ad5c62e6706f818062782a2e1660afda", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2018-12-19T16:43:33.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-06T19:50:22.000Z", "max_forks_repo_path": "src/module.cpp", "max_forks_repo_name": "Algomorph/LevelSetFusionExperimentsCPP", "max_forks_repo_head_hexsha": "f56962f0ad5c62e6706f818062782a2e1660afda", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-01-07T14:12:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-06T06:30:24.000Z", "avg_line_length": 27.2352941176, "max_line_length": 88, "alphanum_fraction": 0.7832973362, "num_tokens": 371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4969882300814182}}
{"text": "#ifndef AHTLP_HPP_\n#define AHTLP_HPP_\n\n#include <NTL/ZZ.h>\n#include <assert.h>\n#include <openssl/sha.h>\n#include <vector>\n#include <sstream>\n\n#include \"HTLP.hpp\"\n#include \"Puzzle.hpp\"\n\n#ifndef RSA_\n#define RSA_\ntypedef struct RSA\n{\n    NTL::ZZ p;\n    NTL::ZZ q;\n} RSA;\n#endif\n\nclass AHTLP : public HTLP\n{\n\npublic:\n    AHTLP(const long modulus_len, const long T, const long kappa);\n    AHTLP(const NTL::ZZ &n, const NTL::ZZ &g, const NTL::ZZ &h, const long T, const long kappa);\n    AHTLP(const long modulus_len, const long T, const long kappa, bool cheeting_mode);\n\n    APuzzle GeneratePuzzle(const NTL::ZZ &s);\n    APuzzle GeneratePuzzle(const NTL::ZZ &s, const NTL::ZZ &r);\n    NTL::ZZ SolvePuzzle(const APuzzle &Z);\n    NTL::ZZ QuickSolvePuzzle(const APuzzle &Z);\n\n    std::tuple<NTL::ZZ, NTL::ZZ, NTL::ZZ, NTL::ZZ> GenerateAValidProof(const APuzzle &Z, const NTL::ZZ &s, const NTL::ZZ &r);\n    bool VerifyAValidProof(const APuzzle &Z, const std::tuple<NTL::ZZ, NTL::ZZ, NTL::ZZ, NTL::ZZ> &proof);\n\n    std::tuple<NTL::ZZ, NTL::ZZ, NTL::ZZ> SolvePuzzleWithProof(const long k, const long gamma, const APuzzle &Z);\n    std::tuple<NTL::ZZ, NTL::ZZ, NTL::ZZ> QuickSolvePuzzleWithProof(const APuzzle &Z);\n\n    int VerifyProofOfSol(const APuzzle Z, const std::tuple<NTL::ZZ, NTL::ZZ, NTL::ZZ> &proof);\n};\n\n#endif", "meta": {"hexsha": "668e3951da2e9779806a4acb00c45a3ec11e0699", "size": 1309, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/AHTLP.hpp", "max_stars_repo_name": "liu-yi/HTLP", "max_stars_repo_head_hexsha": "c66a0c8b126c52e6ac74dbba9b7be0828bb8ef45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/AHTLP.hpp", "max_issues_repo_name": "liu-yi/HTLP", "max_issues_repo_head_hexsha": "c66a0c8b126c52e6ac74dbba9b7be0828bb8ef45", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/AHTLP.hpp", "max_forks_repo_name": "liu-yi/HTLP", "max_forks_repo_head_hexsha": "c66a0c8b126c52e6ac74dbba9b7be0828bb8ef45", "max_forks_repo_licenses": ["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.75, "max_line_length": 125, "alphanum_fraction": 0.6844919786, "num_tokens": 434, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737775116229, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.49698821842032853}}
{"text": "<<<<<<< HEAD\n/*    Copyright (c) 2010-2018, Delft University of Technology\n=======\n/*    Copyright (c) 2010-2019, Delft University of Technology\n>>>>>>> origin/master\n *    All rigths reserved\n *\n *    This file is part of the Tudat. Redistribution and use in source and\n *    binary forms, with or without modification, are permitted exclusively\n *    under the terms of the Modified BSD license. You should have received\n *    a copy of the license with this file. If not, please or visit:\n *    http://tudat.tudelft.nl/LICENSE.\n */\n\n#include <boost/random.hpp>\n#include <boost/make_shared.hpp>\n\n#include \"Tudat/Mathematics/Statistics/boostProbabilityDistributions.h\"\n\nnamespace tudat\n{\n\nnamespace statistics\n{\n\n//! Function to create a random variable class of BoostContinuousProbabilityDistribution type\nstd::shared_ptr< InvertibleContinuousProbabilityDistribution< double > > createBoostRandomVariable(\n        const ContinuousBoostStatisticalDistributions boostDistribution, const std::vector< double >& parameters )\n{\n    using namespace boost::math;\n\n    std::shared_ptr< InvertibleContinuousProbabilityDistribution< double > > continuousRandomVariable;\n\n    // Check which distribution type is requested\n    switch( boostDistribution )\n    {\n    case uniform_boost_distribution:\n    {\n        // Check number of provided parameters\n        if ( parameters.size( ) != 2 )\n        {\n            throw std::runtime_error( \"Uniform distribution requires two parameters.\" );\n        }\n        else\n        {\n            // Create uniform distribution. parameters 0: lower bound, 1: upper bound\n            uniform_distribution< > uniformDistribution( parameters.at( 0 ), parameters.at( 1 ) );\n            continuousRandomVariable =\n                    std::make_shared< BoostContinuousProbabilityDistribution< uniform_distribution< > > >(\n                        uniformDistribution );\n        }\n        break;\n    }\n    case normal_boost_distribution:\n    {\n        // Check number of provided parameters\n        if ( parameters.size( ) != 2 )\n        {\n            throw std::runtime_error( \"Normal distribution requires two parameters.\" );\n        }\n        else\n        {\n            // Create uniform distribution. parameters 0: mean, 1: standard deviation\n            normal_distribution< > normalDistribution( parameters.at( 0 ), parameters.at( 1 ) );\n            continuousRandomVariable =\n                    std::make_shared< BoostContinuousProbabilityDistribution< normal_distribution< > > >(\n                        normalDistribution );\n        }\n        break;\n    }\n    case exponential_boost_distribution:\n    {\n        // Check number of provided parameters\n        if ( parameters.size( ) != 1 )\n        {\n            throw std::runtime_error( \"Exponential distribution requires one parameter.\" );\n        }\n        else\n        {\n            // Create uniform distribution. parameters 0: lambda parameter\n            exponential_distribution< > exponentialDistribution( parameters.at( 0 ) );\n            continuousRandomVariable =\n                    std::make_shared< BoostContinuousProbabilityDistribution< exponential_distribution< > > >(\n                        exponentialDistribution );\n        }\n        break;\n    }\n    case gamma_boost_distribution:\n    {\n        // Check number of provided parameters\n        if ( parameters.size( ) != 2 )\n        {\n            throw std::runtime_error( \"Gamma distribution requires two parameters.\" );\n        }\n        else\n        {\n            // Create uniform distribution. parameters 0: shape parameter, parameter 1: scale parameter\n            gamma_distribution< > gammaDistribution( parameters.at( 0 ), parameters.at( 1 ) );\n            continuousRandomVariable =\n                    std::make_shared< BoostContinuousProbabilityDistribution< gamma_distribution< > > >(\n                        gammaDistribution );\n        }\n        break;\n    }\n    case lognormal_boost_distribution:\n    {\n        // Check number of provided parameters\n        if ( parameters.size( ) != 2 )\n        {\n            throw std::runtime_error( \"Log-normal distribution requires two parameters.\" );\n        }\n        else\n        {\n            // Create uniform distribution. parameters 0: location parameter, parameter 1: scale parameter\n            lognormal_distribution< > logNormalDistribution( parameters.at( 0 ), parameters.at( 1 ) );\n            continuousRandomVariable =\n                    std::make_shared< BoostContinuousProbabilityDistribution< lognormal_distribution< > > >(\n                        logNormalDistribution );\n        }\n        break;\n    }\n    case beta_boost_distribution:\n    {\n        // Check number of provided parameters\n        if ( parameters.size( ) != 2 )\n        {\n            throw std::runtime_error( \"Beta distribution requires two parameters.\" );\n        }\n        else\n        {\n            // Create uniform distribution. parameters 0: alpha parameter, parameter 1: beta parameter\n            beta_distribution< > betaDistribution( parameters.at( 0 ), parameters.at( 1 ) );\n            continuousRandomVariable =\n                    std::make_shared< BoostContinuousProbabilityDistribution< beta_distribution< > > >(\n                        betaDistribution );\n        }\n        break;\n    }\n    default:\n        throw std::runtime_error( \"Boost distribution not recognized.\" );\n    }\n    return continuousRandomVariable;\n}\n\n}\n\n}\n", "meta": {"hexsha": "293bec07764a90fe5082a426fccca8007d4fb834", "size": 5434, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Mathematics/Statistics/boostProbabilityDistributions.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/Mathematics/Statistics/boostProbabilityDistributions.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/Mathematics/Statistics/boostProbabilityDistributions.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": 36.7162162162, "max_line_length": 114, "alphanum_fraction": 0.6198012514, "num_tokens": 1051, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392848011834, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4969861117751128}}
{"text": "#include <CGAL/trace.h>\n#include <CGAL/Timer.h>\n#include <iostream>\n#include <string>\n#include <fstream>\n\n\n#include <Eigen/Eigen>\n\n// #define USE_SCALAR_IMPLEMENTATION\n#define USE_SSE_IMPLEMENTATION\n#define COMPUTE_V_AS_MATRIX\n#define COMPUTE_U_AS_MATRIX\n\n#include <CGAL/internal/Surface_mesh_deformation/auxiliary/Singular_Value_Decomposition_Preamble.hpp>\n\nint main() {\n\n  std::ifstream file;\n  file.open(\"SVD_benchmark\");\n  if (!file) \n  {\n    CGAL_TRACE_STREAM << \"Error loading file!\\n\";\n    return 0;\n  }\n\n  int ite = 200000;\n  Eigen::JacobiSVD<Eigen::Matrix3d> svd;\n  Eigen::Matrix3d u, v, m, r;         \n  Eigen::Vector3d w;   \n\n  int matrix_idx = rand()%200;\n  for (int i = 0; i < matrix_idx; i++)\n  {\n    for (int j = 0; j < 3; j++)\n    {\n      for (int k = 0; k < 3; k++)\n      {\n        file >> m(j, k);\n      }\n    }\n  }\n\n\n  CGAL::Timer task_timer; \n\n  std::cout << \"Start SVD decomposition...\";\n  task_timer.start();\n  for (int i = 0; i < ite; i++)\n  {\n    \n    #include <CGAL/internal/Surface_mesh_deformation/auxiliary/Singular_Value_Decomposition_Kernel_Declarations.hpp>\n\n    ENABLE_SCALAR_IMPLEMENTATION(Sa11.f=m(0,0);) \n    ENABLE_SCALAR_IMPLEMENTATION(Sa21.f=m(1,0);) \n    ENABLE_SCALAR_IMPLEMENTATION(Sa31.f=m(2,0);) \n    ENABLE_SCALAR_IMPLEMENTATION(Sa12.f=m(0,1);) \n    ENABLE_SCALAR_IMPLEMENTATION(Sa22.f=m(1,1);) \n    ENABLE_SCALAR_IMPLEMENTATION(Sa32.f=m(2,1);) \n    ENABLE_SCALAR_IMPLEMENTATION(Sa13.f=m(0,2);) \n    ENABLE_SCALAR_IMPLEMENTATION(Sa23.f=m(1,2);) \n    ENABLE_SCALAR_IMPLEMENTATION(Sa33.f=m(2,2);) \n\n    ENABLE_SSE_IMPLEMENTATION(Va11=_mm_set1_ps(m(0,0));)\n    ENABLE_SSE_IMPLEMENTATION(Va21=_mm_set1_ps(m(1,0));)\n    ENABLE_SSE_IMPLEMENTATION(Va31=_mm_set1_ps(m(2,0));)\n    ENABLE_SSE_IMPLEMENTATION(Va12=_mm_set1_ps(m(0,1));)\n    ENABLE_SSE_IMPLEMENTATION(Va22=_mm_set1_ps(m(1,1));)\n    ENABLE_SSE_IMPLEMENTATION(Va32=_mm_set1_ps(m(2,1));)\n    ENABLE_SSE_IMPLEMENTATION(Va13=_mm_set1_ps(m(0,2));)\n    ENABLE_SSE_IMPLEMENTATION(Va23=_mm_set1_ps(m(1,2));)\n    ENABLE_SSE_IMPLEMENTATION(Va33=_mm_set1_ps(m(2,2));)\n\n    #include <CGAL/internal/Surface_mesh_deformation/auxiliary/Singular_Value_Decomposition_Main_Kernel_Body.hpp>\n    \n    std::pair<Eigen::Matrix3d, Eigen::Matrix3d> solver;\n\n#ifdef USE_SCALAR_IMPLEMENTATION\n    solver.first(0,0) = Su11.f;\n    solver.first(1,0) = Su21.f;\n    solver.first(2,0) = Su31.f;\n    solver.first(0,1) = Su12.f;\n    solver.first(1,1) = Su22.f;\n    solver.first(2,1) = Su32.f;\n    solver.first(0,2) = Su13.f;\n    solver.first(1,2) = Su23.f;\n    solver.first(2,2) = Su33.f;\n\n    solver.second(0,0) = Sv11.f;\n    solver.second(1,0) = Sv21.f;\n    solver.second(2,0) = Sv31.f;\n    solver.second(0,1) = Sv12.f;\n    solver.second(1,1) = Sv22.f;\n    solver.second(2,1) = Sv32.f;\n    solver.second(0,2) = Sv13.f;\n    solver.second(1,2) = Sv23.f;\n    solver.second(2,2) = Sv33.f;\n#endif\n\n#ifdef USE_SSE_IMPLEMENTATION\n    float buf[4];\n    _mm_storeu_ps(buf,Vu11);solver.first(0,0)=buf[0];\n    _mm_storeu_ps(buf,Vu21);solver.first(1,0)=buf[0];\n    _mm_storeu_ps(buf,Vu31);solver.first(2,0)=buf[0];\n    _mm_storeu_ps(buf,Vu12);solver.first(0,1)=buf[0];\n    _mm_storeu_ps(buf,Vu22);solver.first(1,1)=buf[0];\n    _mm_storeu_ps(buf,Vu32);solver.first(2,1)=buf[0];\n    _mm_storeu_ps(buf,Vu13);solver.first(0,2)=buf[0];\n    _mm_storeu_ps(buf,Vu23);solver.first(1,2)=buf[0];\n    _mm_storeu_ps(buf,Vu33);solver.first(2,2)=buf[0];\n\n    _mm_storeu_ps(buf,Vv11);solver.second(0,0)=buf[0];\n    _mm_storeu_ps(buf,Vv21);solver.second(1,0)=buf[0];\n    _mm_storeu_ps(buf,Vv31);solver.second(2,0)=buf[0];\n    _mm_storeu_ps(buf,Vv12);solver.second(0,1)=buf[0];\n    _mm_storeu_ps(buf,Vv22);solver.second(1,1)=buf[0];\n    _mm_storeu_ps(buf,Vv32);solver.second(2,1)=buf[0];\n    _mm_storeu_ps(buf,Vv13);solver.second(0,2)=buf[0];\n    _mm_storeu_ps(buf,Vv23);solver.second(1,2)=buf[0];\n    _mm_storeu_ps(buf,Vv33);solver.second(2,2)=buf[0];\n#endif\n\n    r = solver.first * solver.second.transpose();\n  }\n  task_timer.stop();\n  file.close();\n\n  std::cout << \"done: \" << task_timer.time() << \"s\\n\";\n  return 0;\n}", "meta": {"hexsha": "137c8ddf245e7201a5ac93e3a0224b1fc0d8219a", "size": 4056, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "graphics/cgal/Surface_mesh_deformation/benchmark/Surface_mesh_deformation/optimal_rotation/optimal_rotation_svd_SSE.cpp", "max_stars_repo_name": "hlzz/dotfiles", "max_stars_repo_head_hexsha": "0591f71230c919c827ba569099eb3b75897e163e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-03-30T14:31:52.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-02T05:01:32.000Z", "max_issues_repo_path": "graphics/cgal/Surface_mesh_deformation/benchmark/Surface_mesh_deformation/optimal_rotation/optimal_rotation_svd_SSE.cpp", "max_issues_repo_name": "hlzz/dotfiles", "max_issues_repo_head_hexsha": "0591f71230c919c827ba569099eb3b75897e163e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "graphics/cgal/Surface_mesh_deformation/benchmark/Surface_mesh_deformation/optimal_rotation/optimal_rotation_svd_SSE.cpp", "max_forks_repo_name": "hlzz/dotfiles", "max_forks_repo_head_hexsha": "0591f71230c919c827ba569099eb3b75897e163e", "max_forks_repo_licenses": ["BSD-3-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.2, "max_line_length": 116, "alphanum_fraction": 0.6725838264, "num_tokens": 1431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392848011834, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4969861117751128}}
{"text": "#include \"multiindex.hpp\"\n#include \"potgen.hpp\"\n#include \"fft.hpp\"\n#include \"dynamic_grid.hpp\"\n\n#include <boost/test/unit_test.hpp>\n\ncomplex_grid discretizeFunctionForFFT(std::vector<std::size_t> gridsize, std::vector<double>, correlation_fn F);\n\nstatic const std::vector<double> vec_1{1.0};\nstatic const std::vector<double> vec_2{1.0, 1.0};\nstatic const std::vector<double> vec_3{1.0, 1.0, 1.0};\n\nBOOST_AUTO_TEST_SUITE(potgen_internals_test)\n\n// test discretize function\nBOOST_AUTO_TEST_CASE( discretizeFunctionForFFT_1d )\n{\n\tstd::function<double(const gen_vect&)> f = [](const gen_vect& x) { return std::exp(-x[0]*x[0]*10); };\n\n\tauto dgrid = discretizeFunctionForFFT(std::vector<size_t>{64}, vec_1, f);\n\n\tgen_vect s(1);\n\tfor(int i=0; i < 64; ++i)\n\t{\n\t\t// compare with shifted: this is required to make FT real\n\t\ts[0] = ((i+32)%64 - 32) / 64.0;\n\t\tBOOST_CHECK_EQUAL(dgrid.getContainer().at<complex_t>(i), f(s));\n\t}\n\n\t// check symmetry\n\t/// \\todo this is not symmetric. why is this correct?\n\t/*for(int i = 0; i < 32; ++i)\n\t{\n\t\tBOOST_CHECK_EQUAL(dgrid.getContainer().at<double>(i), dgrid.getContainer().at<double>(63-i));\n\t}*/\n}\n\nBOOST_AUTO_TEST_CASE( discretize_1d_identity )\n{\n\tconstexpr std::size_t size = 64;\n\tstd::function<double(const gen_vect&)> f = [=](const gen_vect& x) { return x[0] * size; };\n\n\tauto dgrid = discretizeFunctionForFFT(std::vector<size_t>{size}, vec_1, f);\n\n\tgen_vect s(1);\n\t/// \\todo is there any need for the complicated index calculations here?\n\tfor(unsigned i=0; i < size; ++i)\n\t{\n\t\tBOOST_REQUIRE_EQUAL((int)((dgrid.getContainer().at<complex_t>(i)).real()), (i+size/2)%size - size/2);\n\t}\n}\n\nBOOST_AUTO_TEST_CASE( discretizeFunctionForFFT_2d )\n{\n\t// first check target range\n\tstd::function<double(const gen_vect&)> f = [](const gen_vect&) { return 1; };\n\tauto dgrid = discretizeFunctionForFFT(std::vector<size_t>{8,8}, vec_2, f);\n\n\tfor(int i=0; i < 64; ++i)\n\t{\n\t\tBOOST_REQUIRE_EQUAL(dgrid.getContainer().at<complex_t>(i), 1.0);\n\t}\n\n\tstd::function<double(const gen_vect&)> f2 = [](const gen_vect& g) { return std::exp((-g[0]*g[0]-g[1]*g[1])*100); };\n\tauto dgrid2 = discretizeFunctionForFFT(std::vector<size_t>{32, 32}, vec_2, f2);\n\n\t// check that fft phases make it completely real\n\tstd::vector<complex_t> ct;\n\tct.assign(dgrid2.begin(), dgrid2.end());\n\n\tfft( ct, std::vector<int>({32, 32}) );\n\n\tfor(unsigned i = 0; i < ct.size(); ++i)\n\t{\n\t\tBOOST_REQUIRE_SMALL(std::imag(ct[i]), 1e-10);\n\t\tBOOST_REQUIRE_GE(std::real(ct[i]), -1e-10);\n\t}\n\n\t/// \\todo check general positions for general function\n}\n\nBOOST_AUTO_TEST_CASE( discretizeFunctionForFFT_error )\n{\n\tstd::function<double(const gen_vect&)> f = [](const gen_vect&) { return 1; };\n\t// odd_sized grids are unsupported\n\tBOOST_CHECK_THROW( (discretizeFunctionForFFT(std::vector<size_t>{3}, vec_1, f)), std::invalid_argument);\n\t// incompatible dimensions between grid size and support\n\tBOOST_CHECK_THROW( (discretizeFunctionForFFT(std::vector<size_t>{2, 2}, vec_1, f)), std::invalid_argument);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "5648c90c35c7517034b14f98a6d1b0ac0bef7898", "size": 2997, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/potgen/test/discretize_test.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/potgen/test/discretize_test.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/potgen/test/discretize_test.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": 32.2258064516, "max_line_length": 116, "alphanum_fraction": 0.6966966967, "num_tokens": 917, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042768, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.49697243034907856}}
{"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#include <boost/numeric/odeint.hpp>\n#include <smooth/bundle.hpp>\n#include <smooth/compat/odeint.hpp>\n#include <smooth/feedback/asif.hpp>\n#include <smooth/feedback/mpc.hpp>\n#include <smooth/se2.hpp>\n#include <smooth/se3.hpp>\n\n#include <chrono>\n\n#ifdef ENABLE_PLOTTING\n#include <matplot/matplot.h>\n#endif\n\n#ifdef ENABLE_ROS\n#include <gazebo_msgs/srv/set_entity_state.hpp>\n#include <geometry_msgs/msg/accel.hpp>\n#include <rclcpp/rclcpp.hpp>\n#include <smooth/compat/ros.hpp>\n#endif\n\nusing namespace std::chrono_literals;\nusing namespace boost::numeric::odeint;\n\nusing Time = std::chrono::duration<double>;\n\ntemplate<typename S>\nusing X = smooth::Bundle<smooth::SE2<S>, Eigen::Matrix<S, 3, 1>>;\ntemplate<typename S>\nusing U = Eigen::Matrix<S, 2, 1>;\n\nusing Xd = X<double>;\nusing Ud = U<double>;\n\nusing Tangentd = smooth::Tangent<Xd>;\n\nint main()\n{\n  // dynamics\n  auto f = []<typename S>(const X<S> & x, const U<S> & u) -> smooth::Tangent<X<S>> {\n    return {\n      x.template part<1>().x(),\n      x.template part<1>().y(),\n      x.template part<1>().z(),\n      -S(0.2) * x.template part<1>().x() + u.x(),\n      S(0),\n      -S(0.4) * x.template part<1>().z() + u.y(),\n    };\n  };\n\n  auto cr = []<typename S>(const X<S> &, const U<S> & u) -> Eigen::Vector<S, 2> { return u; };\n  Eigen::Vector2d crl{-0.5, -0.5};\n  Eigen::Vector2d cru{0.5, 0.5};\n\n  // simulation time step\n  const auto dt = 25ms;\n\n  ////////////////////\n  //// SET UP MPC ////\n  ////////////////////\n\n  smooth::feedback::MPC<Time, Xd, Ud, decltype(f), decltype(cr)> mpc{\n    f,\n    cr,\n    crl,\n    cru,\n    {.K = 30, .tf = 5},\n  };\n\n  // define desired trajectory\n  auto xdes = []<typename S>(S t) -> X<S> {\n    const Eigen::Vector3d vdes{1, 0, 0.4};\n    return X<S>{\n      smooth::SE2<S>(smooth::SO2<S>(M_PI_2), Eigen::Vector2<S>(2.5, 0)) + (t * vdes),\n      vdes,\n    };\n  };\n\n  mpc.set_weights({\n    .Q   = Eigen::Matrix<double, 6, 6>::Identity(),\n    .Qtf = 0.1 * Eigen::Matrix<double, 6, 6>::Identity(),\n    .R   = Eigen::Matrix2d::Identity(),\n  });\n\n  // set desired trajectory in MPC\n  mpc.set_xdes_rel(xdes);\n  mpc.set_udes_rel([]<typename S>(S) -> U<S> { return U<S>::Zero(); });\n\n  /////////////////////\n  //// SET UP ASIF ////\n  /////////////////////\n\n  // safe set\n  auto h = []<typename S>(S, const X<S> & x) -> Eigen::Matrix<S, 1, 1> {\n    const Eigen::Vector2<S> dir = x.template part<0>().r2() - Eigen::Vector2<S>{0, -2.3};\n    const Eigen::Vector2d e_dir = dir.template cast<double>().normalized();\n    return Eigen::Matrix<S, 1, 1>(dir.dot(e_dir) - 0.7);\n  };\n\n  // backup controller\n  auto bu = []<typename S>(S, const X<S> & x) -> U<S> {\n    return {0.2 * x.template part<1>().x(), -0.5};\n  };\n\n  const smooth::feedback::ManifoldBounds<Ud> ulim{\n    .A = Eigen::Matrix2d{{1, 0}, {0, 1}},\n    .c = Ud::Zero(),\n    .l = Eigen::Vector2d(-0.2, -0.5),\n    .u = Eigen::Vector2d(0.5, 0.5),\n  };\n\n  // parameters\n  smooth::feedback::ASIFilterParams<Ud> asif_prm{\n    .T        = 2.5,\n    .nh       = 1,\n    .u_weight = Eigen::Vector2d{20, 1},\n    .ulim     = ulim,\n    .asif =\n      {\n        .K          = 200,\n        .alpha      = 5,\n        .dt         = 0.01,\n        .relax_cost = 100,\n      },\n    .qp =\n      {\n        .polish = false,\n      },\n  };\n\n  smooth::feedback::ASIFilter<Xd, Ud, decltype(f)> asif(f, asif_prm);\n\n  /////////////////////////\n  //// CREATE ROS NODE ////\n  /////////////////////////\n\n#ifdef ENABLE_ROS\n  rclcpp::init(0, nullptr);\n  auto node       = std::make_shared<rclcpp::Node>(\"se2_example\");\n  auto ses_client = node->create_client<gazebo_msgs::srv::SetEntityState>(\"/set_entity_state\");\n  auto u_mpc_pub =\n    node->create_publisher<geometry_msgs::msg::Accel>(\"u_mpc\", rclcpp::SystemDefaultsQoS{});\n  auto u_asif_pub =\n    node->create_publisher<geometry_msgs::msg::Accel>(\"u_asif\", rclcpp::SystemDefaultsQoS{});\n\n  rclcpp::Rate rate(25ms);\n#endif\n\n  /////////////////////////////////////\n  //// SIMULATE CLOSED-LOOP SYSTEM ////\n  /////////////////////////////////////\n\n  // system variables\n  Xd x = Xd::Identity();\n  Ud u;\n\n  // prepare for integrating the closed-loop system\n  runge_kutta4<Xd, double, Tangentd, double, vector_space_algebra> stepper{};\n  const auto ode = [&f, &u](const Xd & x, Tangentd & d, double) { d = f(x, u); };\n  std::vector<double> tvec, xvec, yvec, u1vec, u2vec, u1mpcvec, u2mpcvec;\n\n  // integrate closed-loop system\n  for (std::chrono::milliseconds t = 0s; t < 30s; t += dt) {\n    // compute MPC input\n    const auto [u_mpc, mpc_code] = mpc(t, x);\n    if (mpc_code != smooth::feedback::QPSolutionStatus::Optimal) {\n      std::cerr << \"MPC failed with mpc_code \" << static_cast<int>(mpc_code) << std::endl;\n    }\n\n    // filter input with ASIF\n    const auto [u_asif, asif_code] = asif(x, u_mpc, h, bu);\n    if (asif_code != smooth::feedback::QPSolutionStatus::Optimal) {\n      std::cerr << \"ASIF solver failed with asif_code \" << static_cast<int>(asif_code) << std::endl;\n    }\n\n    // select input\n    u = u_asif;\n\n    // store data\n    tvec.push_back(duration_cast<Time>(t).count());\n    xvec.push_back(x.template part<0>().r2().x());\n    yvec.push_back(x.template part<0>().r2().y());\n\n    u1mpcvec.push_back(u_mpc(0));\n    u2mpcvec.push_back(u_mpc(1));\n    u1vec.push_back(u_asif(0));\n    u2vec.push_back(u_asif(1));\n\n#ifdef ENABLE_ROS\n    auto req        = std::make_shared<gazebo_msgs::srv::SetEntityState::Request>();\n    req->state.name = \"bus::link\";\n    smooth::Map<geometry_msgs::msg::Pose>(req->state.pose) = x.template part<0>().lift_se3();\n    req->state.pose.position.x                             = 8 * req->state.pose.position.x;\n    req->state.pose.position.y                             = 8 * req->state.pose.position.y;\n    ses_client->async_send_request(req);\n\n    geometry_msgs::msg::Accel u_mpc_msg;\n    u_mpc_msg.linear.x  = u_mpc.x();\n    u_mpc_msg.angular.z = u_mpc.y();\n    u_mpc_pub->publish(u_mpc_msg);\n\n    geometry_msgs::msg::Accel u_asif_msg;\n    u_asif_msg.linear.x  = u_asif.x();\n    u_asif_msg.angular.z = u_asif.y();\n    u_asif_pub->publish(u_asif_msg);\n\n    rate.sleep();\n#endif\n    // step dynamics\n    stepper.do_step(\n      ode, x, 0, std::chrono::duration_cast<std::chrono::duration<double>>(dt).count());\n  }\n\n#ifdef ENABLE_PLOTTING\n  matplot::figure();\n  matplot::hold(matplot::on);\n  matplot::title(\"Path\");\n\n  matplot::plot(xvec, yvec)->line_width(2);\n  matplot::plot(\n    matplot::transform(tvec, [&](auto t) { return xdes(t).template part<0>().r2().x(); }),\n    matplot::transform(tvec, [&](auto t) { return xdes(t).template part<0>().r2().y(); }),\n    \"k--\")\n    ->line_width(2);\n  matplot::legend({\"actual\", \"desired\"});\n\n  matplot::figure();\n  matplot::hold(matplot::on);\n  matplot::title(\"Inputs\");\n  matplot::plot(tvec, u1vec, \"r\")->line_width(2);\n  matplot::plot(tvec, u2vec, \"b\")->line_width(2);\n  matplot::plot(tvec, u1mpcvec, \"--r\")->line_width(2);\n  matplot::plot(tvec, u2mpcvec, \"--b\")->line_width(2);\n  matplot::legend({\"u1\", \"u2\", \"u1des\", \"u2des\"});\n\n  matplot::show();\n#else\n  std::cout << \"TRAJECTORY:\" << std::endl;\n  for (auto i = 0u; i != tvec.size(); ++i) {\n    std::cout << \"t=\" << tvec[i] << \": x=\" << xvec[i] << \", y=\" << yvec[i] << std::endl;\n  }\n#endif\n\n#ifdef ENABLE_ROS\n  rclcpp::shutdown();\n#endif\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "8d2a09e7d8c1bd41c87dbac2a59cbf437aaf92d8", "size": 8525, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/mpc_asif_vehicle.cpp", "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": "examples/mpc_asif_vehicle.cpp", "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": "examples/mpc_asif_vehicle.cpp", "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": 31.0, "max_line_length": 100, "alphanum_fraction": 0.6062170088, "num_tokens": 2610, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.49697243034907845}}
{"text": "#include <bits/types/FILE.h>\n#include <fstream>\n#include <iostream>\n#include <stdio.h>\n#include <vector>\n#include <string>\n#include <tgmath.h>\n#include \"image_ppm.h\"\n#include <filesystem>\n#include <Eigen/Dense>\n\n\n\nusing namespace std;\nusing namespace Eigen;\n\ntypedef Matrix<u_char, Dynamic, Dynamic> MatrixImg;\ntypedef Matrix<double, Dynamic, Dynamic> TempMatrixImg;\ntypedef Vector<u_char,Dynamic> ImgLine;\ntypedef Vector<double,Dynamic> TempImgLine;\n\nauto max(auto a, auto b){\n    if (a<b) return b;\n    else return a;\n}\n\nauto min(auto a, auto b){\n    if (a>b) return b;\n    else return a;\n}\n\nvector<double> projectOnEigenSpace(vector<TempImgLine> eigenfaces, TempImgLine imToProj,int K){\n    vector<double> res = vector<double>();\n    for (int i=0;i<K;i++){\n        res.push_back(eigenfaces[i].dot(imToProj));\n    }\n    return res;\n}\n\nImgLine octToVec(OCTET* im, int nH, int nW){\n    ImgLine res(nH*nW);\n    for (int i=0; i<nH*nW;i++){\n        res(i)=im[i];\n    }\n    return res;\n}\n\ndouble eigenProjsDistance(vector<double> proj1, vector<double> proj2){\n\n    double res =0.0;\n    for (int i=0; i<min(proj1.size(),proj2.size());i++){\n        res+=(proj1[i]-proj2[i])*(proj1[i]-proj2[i]);\n    }\n    return res;\n}\n\n\n//db is fileName ; names is labels ; values : values[person][imN][doubleM]\nvoid processDB(string db, vector<string>& names, vector<vector<vector<double>>>& values){\n    ifstream file;\n    file.open(db);\n    values = vector<vector<vector<double>>>();\n    string line ;\n    while(getline(file, line)){\n        size_t exclam = line.find('!');\n        if (exclam != std::string::npos){\n            names.push_back(line.substr(exclam+1));\n            values.push_back(vector<vector<double>>());\n        }\n        else{\n            if (line.size()>1){\n                vector<double> res;\n                stringstream ss(line);\n                \n                double num;\n                while(ss>>num){\n                    res.push_back(num);\n                }\n                values[values.size()-1].push_back(res);\n            }\n        }\n    }\n}\n\nint main(int argc, char* argv[]){\n\n    if (argc<3){\n        cout<<\"usage : eigenfaces im.pgm\"<<endl;\n    }\n\n    vector<TempImgLine> eigenfaces;\n    int K =42; int nH,nW;\n\n    for (int i=0; i<K;i++){\n        OCTET* im;\n        char name[100];\n        \n        sprintf(name,\"/im%d.pgm\",i);\n        string eigenFolder = string(string(argv[1])+string(name));\n        \n        lire_nb_lignes_colonnes_image_pgm(eigenFolder.c_str(),&nH,&nW);\n        allocation_tableau(im,OCTET,nH*nW);\n        lire_image_pgm(eigenFolder.c_str(),im,nH*nW);\n        TempImgLine eigenFace(nH*nW) ;\n        double sum=0.0;\n        for (int j=0;j<nH*nW;j++){\n            eigenFace(j)=im[j]-127;\n            sum+=(double)(im[j]-127)*(double)(im[j]-127);\n        }\n        for (int j=0;j<nH*nW;j++){\n            eigenFace(j)=eigenFace(j)/sqrt(sum);\n            }\n        eigenfaces.push_back(eigenFace);\n        free(im);\n    }\n\n    \n\n    OCTET* img; \n    lire_nb_lignes_colonnes_image_pgm(argv[2],&nH,&nW);\n    TempImgLine imgLine(nH*nW);            \n    allocation_tableau(img,OCTET, nH*nW);\n    lire_image_pgm(argv[2],img,nH*nW);\n    double sumIm=0.0;\n    for (int i=0;i<nH*nW;i++){sumIm+=(double)(img[i]-127)*(double)(img[i]-127);}\n    for (int i=0; i<nH*nW;i++){imgLine(i)=(double)(img[i]-127)/sumIm;}\n\n    //registre[countDirs].push_back(projectOnEigenSpace(eigenfaces,imgLine,K));\n    vector<double> imProj = projectOnEigenSpace(eigenfaces,imgLine,K);\n\n    vector<string> labels; \n    vector<vector<vector<double>>> values;\n    processDB(\"DBEigen.txt\", labels, values);\n    double minDist=INFINITY; \n    int closestMatch = -1;\n    for (int i=0;i<values.size();i++){\n        for (int j=0; j<values[i].size();j++){\n            double dist = eigenProjsDistance(imProj, values[i][j]);\n            //cout<<labels[i]<<\" \"<<dist<<endl;\n            if (dist<minDist){\n                //cout<<dist<<\" \"<<i<<endl;\n                minDist=dist;\n                closestMatch=i;\n                \n            }\n        }\n    }\n\n     if (closestMatch>=0){cout<<\"\\n **************** \\nCLOSEST MATCH FOUND : \"<<labels[closestMatch]<<\"\\n ****************\"<<endl;}\n    else {cout<<\"No match found !\"<<endl;}\n    \n}", "meta": {"hexsha": "dc4b0ef43952c67a858dcad1b27b32cbd7301eb4", "size": 4233, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Code/eigenMatching.cpp", "max_stars_repo_name": "JPhilippot/FaceRecognition", "max_stars_repo_head_hexsha": "12a657d05f0103b0193a28a6347d1f41f466f0d0", "max_stars_repo_licenses": ["MIT"], "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/eigenMatching.cpp", "max_issues_repo_name": "JPhilippot/FaceRecognition", "max_issues_repo_head_hexsha": "12a657d05f0103b0193a28a6347d1f41f466f0d0", "max_issues_repo_licenses": ["MIT"], "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/eigenMatching.cpp", "max_forks_repo_name": "JPhilippot/FaceRecognition", "max_forks_repo_head_hexsha": "12a657d05f0103b0193a28a6347d1f41f466f0d0", "max_forks_repo_licenses": ["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.8486842105, "max_line_length": 131, "alphanum_fraction": 0.5643751476, "num_tokens": 1153, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.49697243034907845}}
{"text": "//!\n//! @file       TestHEmatrix.cpp, cpp file\n//! @brief      defining functions for testing homomorphic matrix computation\n//!\n//! @author     Miran Kim\n//! @date       Dec. 1, 2017\n//! @copyright  GNU Pub License\n//!\n\n#include <cmath>\n#include <iostream>\n#include <stdio.h>\n#include <vector>\n#include <sys/time.h>\n#include <chrono>\n\n#include <NTL/RR.h>\n#include <NTL/xdouble.h>\n#include <NTL/ZZ.h>\n#include <NTL/ZZX.h>\n#include \"NTL/RR.h\"\n#include \"NTL/vec_RR.h\"\n#include \"NTL/mat_RR.h\"\n#include <NTL/BasicThreadPool.h>\n#include <NTL/mat_ZZ.h>\n\n\n#include \"../src/Context.h\"\n#include \"../src/Scheme.h\"\n#include \"../src/SecretKey.h\"\n#include \"../src/TimeUtils.h\"\n\n#include \"matrix.h\"\n#include \"HEmatrix.h\"\n#include \"TestHEmatrix.h\"\n\nusing namespace std;\nusing namespace chrono;\n\n\nvoid TestHEmatrix::testHEAAN(long logN, long logQ) {\n\n    long pBits = 25;   // scaling factor for message\n    long cBits = 15;   // scaling factor for constant\n    \n    long h = 64;\n    \n    long ntrial = 10;\n    /*---------------------------------------*/\n    //  Key Generation\n    /*---------------------------------------*/\n    \n    TimeUtils timeutils;\n    timeutils.start(\"Scheme generating...\");\n    Context context(logN, logQ);\n    SecretKey secretKey(logN, h);\n    Scheme scheme(secretKey, context);\n    scheme.addLeftRotKeys(secretKey);\n    scheme.addRightRotKeys(secretKey);\n    timeutils.stop(\"Scheme generation\");\n    \n\n    /*---------------------------------------*/\n    //  Encryption\n    /*---------------------------------------*/\n    \n    auto start= chrono::steady_clock::now();\n    \n    long nslots = (1<<(logN-1));\n    \n    double* msg1 = new double[nslots];\n    double* msg2 = new double[nslots];\n    \n    complex<double>* cmsg1 = new complex<double>[nslots];\n    complex<double>* cmsg2 = new complex<double>[nslots];\n    \n    double* dmsg1 = new double[nslots];\n    double* dmsg2 = new double[nslots];\n    \n    for(long i = 0; i < nslots; ++i){\n        msg1[i] = 1.0/(i+1);\n        msg2[i] = 1.0/(2*i+1);\n        \n        cmsg1[i].real(msg1[i]);\n        cmsg2[i].real(msg2[i]);\n    }\n    \n    Ciphertext ct1 = scheme.encrypt(cmsg1, nslots, pBits, logQ);\n    Ciphertext ct2 = scheme.encrypt(cmsg2, nslots, pBits, logQ);\n    \n\n    auto end = std::chrono::steady_clock::now();\n    auto diff = end - start;\n    double timeElapsed = chrono::duration <double, milli> (diff).count()/1000.0;\n    cout << \"Enc time= \" << timeElapsed/2 << \" s\" << endl;\n    cout << \"------------------\" << endl;\n    \n    \n    /*---------------------------------------*/\n    //  Rotation\n    /*---------------------------------------*/\n    long nshift = 1;\n    Ciphertext ctrot;\n    \n    start= chrono::steady_clock::now();\n    for(long i = 0; i < ntrial; ++i){\n        ctrot = ct1;\n        scheme.leftRotateAndEqual(ctrot, nshift);\n    }\n\n    end = std::chrono::steady_clock::now();\n    diff = end - start;\n    timeElapsed = chrono::duration <double, milli> (diff).count()/1000.0;\n    cout << \"Rot time= \" << timeElapsed/ntrial << \" s\" << endl;\n    cout << \"------------------\" << endl;\n    \n    \n    /*---------------------------------------*/\n    //  Decryption\n    /*---------------------------------------*/\n    \n    cmsg1 = scheme.decrypt(secretKey, ctrot);\n    for(long i = 0; i < nslots; ++i){\n        dmsg1[i] = cmsg1[i].real();\n    }\n    \n    double* msgrot = new double[nslots];\n    long k = nslots - nshift;\n    for(long j = 0; j < k; ++j){\n        msgrot[j] = msg1[j + nshift];\n    }\n    for(long j = k; j < nslots; ++j){\n        msgrot[j] = msg1[j - k];\n    }\n   \n    for(long i = 0 ; i < 20; ++i){\n        cout << i << \": \" << msgrot[i] << \", \" << dmsg1[i] << endl;\n    }\n     cout << \"------------------\" << endl;\n    \n    /*---------------------------------------*/\n    //  Multiplication\n    /*---------------------------------------*/\n    \n    Ciphertext ctmult;\n    \n    start= chrono::steady_clock::now();\n    for(long i = 0; i < ntrial; ++i){\n        ctmult = ct1;\n        scheme.multAndEqual(ctmult, ct2);\n    }\n    \n    end = std::chrono::steady_clock::now();\n    diff = end - start;\n    timeElapsed = chrono::duration <double, milli> (diff).count()/1000.0;\n    cout << \"Mult time= \" << timeElapsed/ntrial << \" s\" << endl;\n    cout << \"------------------\" << endl;\n    \n    scheme.reScaleByAndEqual(ctmult, pBits);\n    \n    /*---------------------------------------*/\n    //  Decryption\n    /*---------------------------------------*/\n    \n    cmsg1 = scheme.decrypt(secretKey, ctmult);\n    for(long i = 0; i < nslots; ++i){\n        dmsg1[i] = cmsg1[i].real();\n    }\n    \n    double* msgmult = new double[nslots];\n    for(long i = 0; i < nslots; ++i){\n        msgmult[i] = msg1[i] * msg2[i];\n    }\n    \n    for(long i = 0 ; i < 20; ++i){\n        cout << i << \": \" << msgmult[i] << \", \" << dmsg1[i] << endl;\n    }\n     cout << \"------------------\" << endl;\n}\n\n\nvoid TestHEmatrix::testEnc(long nrows) {\n    \n    long logN = 13;\n    \n    long ncols = nrows;\n    long pBits = 25;   // scaling factor for message\n    long cBits = 15;   // scaling factor for constant\n    long lBits = pBits + 5;\n    long logQ = lBits;\n    \n    long h = 64;\n    long keydist = 1;\n    \n    struct HEMatpar HEmatpar;\n    readHEMatpar(HEmatpar, nrows, ncols, pBits, cBits, logQ);\n\n    cout << \"------------------\" << endl;\n    cout << \"(dim,po2dim, nslots) = (\" << nrows << \",\" << HEmatpar.dim  << \",\" << HEmatpar.sqrdim << \",\" << HEmatpar.nslots << \")\" << endl;\n    cout << \"HEAAN PARAMETER logQ: \" << logQ << endl;\n    cout << \"HEAAN PARAMETER logN: \" << logN << endl;\n    \n    \n    /*---------------------------------------*/\n    //  Key Generation\n    /*---------------------------------------*/\n    \n    TimeUtils timeutils;\n    timeutils.start(\"Scheme generating...\");\n    Context context(logN, logQ);\n    SecretKey secretKey(logN, h);\n    Scheme scheme(secretKey, context);\n    \n    scheme.addLeftRotKeys(secretKey);\n    scheme.addRightRotKeys(secretKey);\n    timeutils.stop(\"Scheme generation\");\n    \n    HEmatrix HEmatrix(scheme, secretKey, HEmatpar);\n    \n    /*---------------------------------------*/\n    //  Generate a random matrix\n    /*---------------------------------------*/\n    Mat<RR> Amat;\n    Amat.SetDims(nrows, ncols);\n    \n    for(long i = 0; i < nrows ; i++){\n        for(long j = 0; j < ncols; j++){\n            Amat[i][j]= to_RR((((i* 2 + ncols * j)%3)/10.0));\n        }\n    }\n    \n    /*---------------------------------------*/\n    //  Encryption\n    /*---------------------------------------*/\n    \n    auto start= chrono::steady_clock::now();\n    Ciphertext Actxt;\n    HEmatrix.encryptRmat(Actxt, Amat, HEmatpar.pBits);\n    \n    auto end = std::chrono::steady_clock::now();\n    auto diff = end - start;\n    double timeElapsed = chrono::duration <double, milli> (diff).count()/1000.0;\n    cout << \"Enc time= \" << timeElapsed << \" s\" << endl;\n    cout << \"------------------\" << endl;\n    \n    /*---------------------------------------*/\n    //  Decryption\n    /*---------------------------------------*/\n    Mat<RR> resmat;\n    HEmatrix.decryptRmat(resmat, Actxt);\n    \n    /*---------------------------------------*/\n    //  Error\n    /*---------------------------------------*/\n    \n    RR error = getError(Amat, resmat, nrows, ncols);\n    cout << \"Error (enc): \" << error << endl;\n    \n    cout << \"------------------\" << endl;\n    cout << \"Plaintext\" << endl;\n    printRmatrix(Amat, 4);\n    cout << \"------------------\" << endl;\n    cout << \"Encryption\" << endl;\n    printRmatrix(resmat, 4);\n    cout << \"------------------\" << endl;\n}\n\nvoid TestHEmatrix::testAdd(long nrows) {\n    \n    long logN = 13;\n    \n    long ncols = nrows;\n    long pBits = 25;   // scaling factor for message\n    long cBits = 15;   // scaling factor for constant\n    long lBits = pBits + 5;\n    long logQ = lBits;\n    \n    long h = 64;\n    long keydist = 1;\n    \n    struct HEMatpar HEmatpar;\n    readHEMatpar(HEmatpar, nrows, ncols, pBits, cBits, logQ);\n    \n    cout << \"------------------\" << endl;\n    cout << \"(dim,po2dim, nslots) = (\" << nrows << \",\" << HEmatpar.dim  << \",\" << HEmatpar.sqrdim << \",\" << HEmatpar.nslots << \")\" << endl;\n    cout << \"HEAAN PARAMETER logQ: \" << logQ << endl;\n    cout << \"HEAAN PARAMETER logN: \" << logN << endl;\n    \n    \n    /*---------------------------------------*/\n    //  Key Generation\n    /*---------------------------------------*/\n    \n    TimeUtils timeutils;\n    timeutils.start(\"Scheme generating...\");\n    Context context(logN, logQ);\n    SecretKey secretKey(logN, h);\n    Scheme scheme(secretKey, context);\n    \n    scheme.addLeftRotKeys(secretKey);\n    scheme.addRightRotKeys(secretKey);\n    timeutils.stop(\"Scheme generation\");\n    \n    HEmatrix HEmatrix(scheme, secretKey, HEmatpar);\n    \n    /*---------------------------------------*/\n    //  Generate a random matrix\n    /*---------------------------------------*/\n    Mat<RR> Amat;\n    Mat<RR> Bmat;\n    \n    Amat.SetDims(nrows, ncols);\n    Bmat.SetDims(nrows, ncols);\n    \n    for(long i = 0; i < nrows ; i++){\n        for(long j = 0; j < ncols; j++){\n            Amat[i][j]= to_RR((((i* 2 + ncols * j) % 3) / 1.0));\n            Bmat[i][j]= to_RR((((i*ncols + j ) % 3) / 1.0));\n        }\n    }\n    \n    /*---------------------------------------*/\n    //  Encryption\n    /*---------------------------------------*/\n    \n    auto start = chrono::steady_clock::now();\n    Ciphertext Actxt;\n    HEmatrix.encryptRmat(Actxt, Amat, HEmatpar.pBits);\n    \n    Ciphertext Bctxt;\n    HEmatrix.encryptRmat(Bctxt, Bmat, HEmatpar.pBits);\n    \n    auto end = std::chrono::steady_clock::now();\n    auto diff = end - start;\n    double timeElapsed = chrono::duration <double, milli> (diff).count()/1000.0;\n    cout << \"Enc time= \" << timeElapsed << \" s\" << endl;\n    cout << \"------------------\" << endl;\n    \n    \n    /*---------------------------------------*/\n    //  Addition\n    /*---------------------------------------*/\n    \n    start = chrono::steady_clock::now();\n    scheme.addAndEqual(Actxt, Bctxt);\n    \n    end = std::chrono::steady_clock::now();\n    diff = end - start;\n    timeElapsed = chrono::duration <double, milli> (diff).count()/1000.0;\n    cout << \"Add time= \" << timeElapsed << \" s\" << endl;\n    \n    /*---------------------------------------*/\n    //  Decryption\n    /*---------------------------------------*/\n    Mat<RR> HEresmat;\n    HEmatrix.decryptRmat(HEresmat, Actxt);\n    \n    /*---------------------------------------*/\n    //  Error\n    /*---------------------------------------*/\n    Mat<RR> resmat;\n    add(resmat, Amat, Bmat);\n    \n    RR error = getError(resmat, HEresmat, nrows, ncols);\n    cout << \"Error (add): \" << error << endl;\n    \n    cout << \"------------------\" << endl;\n    cout << \"Plaintext\" << endl;\n    printRmatrix(resmat, 4);\n    cout << \"------------------\" << endl;\n    cout << \"Encryption\" << endl;\n    printRmatrix(HEresmat, 4);\n    cout << \"------------------\" << endl;\n}\n\nvoid TestHEmatrix::testTrans(long nrows) {\n    \n    long logN = 13;\n    \n    long ncols = nrows;\n    long pBits = 35;   // scaling factor for message\n    long cBits = 15;   // scaling factor for constant\n    long lBits = pBits + 5;\n    long logQ = lBits + cBits;\n    \n    long h = 64;\n    long keydist = 1;\n    \n    struct HEMatpar HEmatpar;\n    readHEMatpar(HEmatpar, nrows, ncols, pBits, cBits, logQ);\n    \n    cout << \"------------------\" << endl;\n    cout << \"(dim,po2dim, nslots) = (\" << nrows << \",\" << HEmatpar.dim  << \",\" << HEmatpar.sqrdim << \",\" << HEmatpar.nslots << \")\" << endl;\n    cout << \"HEAAN PARAMETER logQ: \" << logQ << endl;\n    cout << \"HEAAN PARAMETER logN: \" << logN << endl;\n    \n    \n    /*---------------------------------------*/\n    //  Key Generation\n    /*---------------------------------------*/\n    \n    TimeUtils timeutils;\n    timeutils.start(\"Scheme generating...\");\n    Context context(logN, logQ);\n    SecretKey secretKey(logN, h);\n    Scheme scheme(secretKey, context);\n    \n    scheme.addLeftRotKeys(secretKey);\n    scheme.addRightRotKeys(secretKey);\n    timeutils.stop(\"Scheme generation\");\n    \n    HEmatrix HEmatrix(scheme, secretKey, HEmatpar);\n    \n    /*---------------------------------------*/\n    //  Generate a random matrix\n    /*---------------------------------------*/\n    Mat<RR> Amat;\n    Amat.SetDims(nrows, ncols);\n    \n    for(long i = 0; i < nrows ; i++){\n        for(long j = 0; j < ncols; j++){\n            Amat[i][j]= to_RR((((i* 2 + ncols * j)%3)/10.0));\n        }\n        Amat[i][i] += to_RR(\"2.0\");\n    }\n    \n    /*---------------------------------------*/\n    //  Encryption\n    /*---------------------------------------*/\n    \n    auto start= chrono::steady_clock::now();\n    Ciphertext Actxt;\n    HEmatrix.encryptRmat(Actxt, Amat, HEmatpar.pBits);\n    \n    auto end = std::chrono::steady_clock::now();\n    auto diff = end - start;\n    double timeElapsed = chrono::duration <double, milli> (diff).count()/1000.0;\n    cout << \"Enc time= \" << timeElapsed << \" s\" << endl;\n    cout << \"------------------\" << endl;\n    \n    /*---------------------------------------*/\n    //  Transposition\n    /*---------------------------------------*/\n    \n    ZZX* transpoly;\n    HEmatrix.genTransPoly(transpoly);\n    \n    Ciphertext Tctxt;\n    \n    start= chrono::steady_clock::now();\n    \n    HEmatrix.transpose(Tctxt, Actxt, transpoly);\n    \n    end = std::chrono::steady_clock::now();\n    diff = end - start;\n    timeElapsed = chrono::duration <double, milli> (diff).count()/1000.0;\n    cout << \"Trans time= \" << timeElapsed << \" s\" << endl;\n    \n    /*---------------------------------------*/\n    //  Decryption\n    /*---------------------------------------*/\n    Mat<RR> HEresmat;\n    HEmatrix.decryptRmat(HEresmat, Tctxt);\n    \n    /*---------------------------------------*/\n    //  Error\n    /*---------------------------------------*/\n    Mat<RR> resmat;\n    transpose(resmat, Amat);\n    \n    RR error = getError(resmat, HEresmat, nrows, ncols);\n    cout << \"Error (trans): \" << error << endl;\n    \n    cout << \"------------------\" << endl;\n    cout << \"Plaintext\" << endl;\n    printRmatrix(resmat, 4);\n    cout << \"------------------\" << endl;\n    cout << \"Encryption\" << endl;\n    printRmatrix(HEresmat, 4);\n    cout << \"------------------\" << endl;\n}\n\n\nvoid TestHEmatrix::testShift(long nrows, long k) {\n    \n    long logN = 13;\n    \n    long ncols = nrows;\n    long pBits = 25;   // scaling factor for message\n    long cBits = 15;   // scaling factor for constant\n    long lBits = pBits + 5;\n    long logQ = lBits + cBits;\n    \n    long h = 64;\n    long keydist = 1;\n    \n    struct HEMatpar HEmatpar;\n    readHEMatpar(HEmatpar, nrows, ncols, pBits, cBits, logQ);\n    \n    cout << \"------------------\" << endl;\n    cout << \"(dim,po2dim, nslots) = (\" << nrows << \",\" << HEmatpar.dim  << \",\" << HEmatpar.sqrdim << \",\" << HEmatpar.nslots << \")\" << endl;\n    cout << \"HEAAN PARAMETER logQ: \" << logQ << endl;\n    cout << \"HEAAN PARAMETER logN: \" << logN << endl;\n    \n    \n    /*---------------------------------------*/\n    //  Key Generation\n    /*---------------------------------------*/\n    \n    TimeUtils timeutils;\n    timeutils.start(\"Scheme generating...\");\n    Context context(logN, logQ);\n    SecretKey secretKey(logN, h);\n    Scheme scheme(secretKey, context);\n    \n    scheme.addLeftRotKeys(secretKey);\n    scheme.addRightRotKeys(secretKey);\n    timeutils.stop(\"Scheme generation\");\n    \n    HEmatrix HEmatrix(scheme, secretKey, HEmatpar);\n    \n    /*---------------------------------------*/\n    //  Generate a random matrix\n    /*---------------------------------------*/\n    Mat<RR> Amat;\n    Amat.SetDims(nrows, ncols);\n    \n    for(long i = 0; i < nrows ; i++){\n        for(long j = 0; j < ncols; j++){\n            Amat[i][j]= to_RR((((i* 2 + ncols * j)%3)/10.0));\n        }\n    }\n    \n    /*---------------------------------------*/\n    //  Encryption\n    /*---------------------------------------*/\n    \n    auto start= chrono::steady_clock::now();\n    Ciphertext Actxt;\n    HEmatrix.encryptRmat(Actxt, Amat, HEmatpar.pBits);\n    \n    auto end = std::chrono::steady_clock::now();\n    auto diff = end - start;\n    double timeElapsed = chrono::duration <double, milli> (diff).count()/1000.0;\n    cout << \"Enc time= \" << timeElapsed << \" s\" << endl;\n    cout << \"------------------\" << endl;\n    \n    /*---------------------------------------*/\n    //  Transposition\n    /*---------------------------------------*/\n    \n    ZZX* shiftpoly;\n    HEmatrix.genShiftPoly(shiftpoly);\n    \n    Ciphertext Sctxt;\n    \n    start= chrono::steady_clock::now();\n    \n    HEmatrix.shiftBycols(Sctxt, Actxt, k, shiftpoly);\n    \n    end = std::chrono::steady_clock::now();\n    diff = end - start;\n    timeElapsed = chrono::duration <double, milli> (diff).count()/1000.0;\n    cout << \"Shift by\" << k << \" time= \" << timeElapsed << \" s\" << endl;\n    \n    /*---------------------------------------*/\n    //  Decryption\n    /*---------------------------------------*/\n    Mat<RR> HEresmat;\n    HEmatrix.decryptRmat(HEresmat, Sctxt);\n    \n    /*---------------------------------------*/\n    //  Error\n    /*---------------------------------------*/\n    cout << \"------------------\" << endl;\n    cout << \"Plaintext (before shifting)\" << endl;\n    printRmatrix(Amat, nrows);\n    cout << \"------------------\" << endl;\n    \n    cout << \"------------------\" << endl;\n    cout << \"Encryption\" << endl;\n    printRmatrix(HEresmat, nrows);\n    cout << \"------------------\" << endl;\n}\n\n\nvoid TestHEmatrix::testMult(long nrows) {\n    \n    long logN = 13;\n    \n    long ncols = nrows;\n    long pBits = 25;   // scaling factor for message\n    long cBits = 14;   // scaling factor for constant\n    long lBits = pBits + 8;\n    long logQ = (2*cBits) + pBits + lBits;\n    \n    long h = 64;\n    long keydist = 1;\n    \n    struct HEMatpar HEmatpar;\n    readHEMatpar(HEmatpar, nrows, ncols, pBits, cBits, logQ);\n    \n    cout << \"------------------\" << endl;\n    cout << \"(dim,po2dim, nslots) = (\" << nrows << \",\" << HEmatpar.dim  << \",\" << HEmatpar.sqrdim << \",\" << HEmatpar.nslots << \")\" << endl;\n    cout << \"HEAAN PARAMETER logQ: \" << logQ << endl;\n    cout << \"HEAAN PARAMETER logN: \" << logN << endl;\n    \n    \n    /*---------------------------------------*/\n    //  Key Generation\n    /*---------------------------------------*/\n    \n    TimeUtils timeutils;\n    timeutils.start(\"Scheme generating...\");\n    Context context(logN, logQ);\n    SecretKey secretKey(logN, h);\n    Scheme scheme(secretKey, context);\n    \n    scheme.addLeftRotKeys(secretKey);\n    scheme.addRightRotKeys(secretKey);\n    timeutils.stop(\"Scheme generation\");\n    \n    HEmatrix HEmatrix(scheme, secretKey, HEmatpar);\n    \n    /*---------------------------------------*/\n    //  Generate a random matrix\n    /*---------------------------------------*/\n    Mat<RR> Amat;\n    Mat<RR> Bmat;\n    \n    Amat.SetDims(nrows, ncols);\n    Bmat.SetDims(nrows, ncols);\n    \n    for(long i = 0; i < nrows ; i++){\n        for(long j = 0; j < ncols; j++){\n            Amat[i][j]= to_RR((((i* 2 + ncols * j)%3) / 1.0));\n            Bmat[i][j]= to_RR((((i*ncols + j )%3) / 1.0));\n        }\n    }\n    cout << \"Amat: \" << Amat << endl;\n    cout << \"Bmat: \" << Bmat << endl;\n    /*---------------------------------------*/\n    //  Encryption\n    /*---------------------------------------*/\n    \n    auto start= chrono::steady_clock::now();\n    Ciphertext Actxt;\n    HEmatrix.encryptRmat(Actxt, Amat, HEmatpar.pBits);\n    \n    Ciphertext Bctxt;\n    HEmatrix.encryptRmat(Bctxt, Bmat, HEmatpar.pBits);\n    \n    auto end = std::chrono::steady_clock::now();\n    auto diff = end - start;\n    double timeElapsed = chrono::duration <double, milli> (diff).count()/1000.0;\n    cout << \"Enc time= \" << timeElapsed << \" s\" << endl;\n    cout << \"------------------\" << endl;\n    \n    /*---------------------------------------*/\n    //  GenPoly\n    /*---------------------------------------*/\n    \n    start= chrono::steady_clock::now();\n    \n    ZZX** Initpoly;\n    HEmatrix.genMultPoly(Initpoly);\n    \n    ZZX* shiftpoly;\n    HEmatrix.genShiftPoly(shiftpoly);\n    \n    end = std::chrono::steady_clock::now();\n    diff = end - start;\n    timeElapsed = chrono::duration <double, milli> (diff).count()/1000.0;\n    cout << \"GenPoly time= \" << timeElapsed << \" s\" << endl;\n    cout << \"---------------------------\" << endl;\n    \n    /*---------------------------------------*/\n    //  Mult\n    /*---------------------------------------*/\n    \n    start= chrono::steady_clock::now();\n    Ciphertext Cctxt;\n    HEmatrix.HEmatmul(Cctxt, Actxt, Bctxt, Initpoly, shiftpoly);\n    \n    end = std::chrono::steady_clock::now();\n    diff = end - start;\n    timeElapsed = chrono::duration <double, milli> (diff).count()/1000.0;\n    cout << \"Mult time= \" << timeElapsed << \" s\" << endl;\n    \n    /*---------------------------------------*/\n    //  Decryption\n    /*---------------------------------------*/\n    Mat<RR> HEresmat;\n    HEmatrix.decryptRmat(HEresmat, Cctxt);\n    \n    /*---------------------------------------*/\n    //  Error\n    /*---------------------------------------*/\n    Mat<RR> resmat;\n    mul(resmat, Amat, Bmat);\n    \n    RR error = getError(resmat, HEresmat, nrows, ncols);\n    cout << \"Error (mul): \" << error << endl;\n    \n    cout << \"------------------\" << endl;\n    cout << \"Plaintext\" << endl;\n    printRmatrix(resmat, 4);\n    cout << \"------------------\" << endl;\n    cout << \"Encryption\" << endl;\n    printRmatrix(HEresmat, 4);\n    cout << \"------------------\" << endl;\n}\n\n\nvoid TestHEmatrix::testRMult(long nrows, long subdim) {\n  \n    long logN = 13;\n    \n    long ncols = nrows;\n    long pBits = 25;   // scaling factor for message\n    long cBits = 14;   // scaling factor for constant\n    long lBits = pBits + 8;\n    long logQ = (2*cBits) + pBits + lBits;\n    \n    long h = 64;\n    long keydist = 1;\n    \n    struct HEMatpar HEmatpar;\n    readHEMatpar(HEmatpar, nrows, ncols, pBits, cBits, logQ, subdim);\n    \n    cout << \"------------------\" << endl;\n    cout << \"(dim,po2dim, nslots) = (\" << nrows << \",\" << HEmatpar.dim  << \",\" << HEmatpar.sqrdim << \",\" << HEmatpar.nslots << \")\" << endl;\n    cout << \"HEAAN PARAMETER logQ: \" << logQ << endl;\n    cout << \"HEAAN PARAMETER logN: \" << logN << endl;\n    \n    \n    /*---------------------------------------*/\n    //  Key Generation\n    /*---------------------------------------*/\n    \n    TimeUtils timeutils;\n    timeutils.start(\"Scheme generating...\");\n    Context context(logN, logQ);\n    SecretKey secretKey(logN, h);\n    Scheme scheme(secretKey, context);\n    \n    scheme.addLeftRotKeys(secretKey);\n    scheme.addRightRotKeys(secretKey);\n    timeutils.stop(\"Scheme generation\");\n    \n    HEmatrix HEmatrix(scheme, secretKey, HEmatpar);\n    \n    /*---------------------------------------*/\n    //  Generate a random matrix\n    /*---------------------------------------*/\n    Mat<RR> rAmat;\n    rAmat.SetDims(subdim, ncols);\n    \n    Mat<RR> Bmat;\n    Bmat.SetDims(nrows, ncols);\n    \n    for(long i = 0; i < subdim; i++){\n        for(long j = 0; j < ncols; j++){\n            rAmat[i][j]= to_RR((((i + ncols * j)%3)/10.0));\n        }\n    }\n    \n    for(long i = 0; i < nrows ; i++){\n        for(long j = 0; j < ncols; j++){\n            Bmat[i][j]= to_RR((((i*ncols + j )%3)/10.0));\n        }\n    }\n    \n    // replicate\n    Mat<RR> rAmat1;\n    rAmat1.SetDims(nrows, ncols);\n    for(long i = 0; i < nrows/subdim; ++i){\n        for(long j = 0; j < subdim; ++j){\n            for(long k = 0; k< ncols; k++){\n                rAmat1[i*subdim + j][k] = rAmat[j][k];\n            }\n        }\n    }\n    \n    /*---------------------------------------*/\n    //  Encryption\n    /*---------------------------------------*/\n    \n    auto start= chrono::steady_clock::now();\n    Ciphertext Actxt;\n    HEmatrix.encryptRmat(Actxt, rAmat1, HEmatpar.pBits);\n    \n    Ciphertext Bctxt;\n    HEmatrix.encryptRmat(Bctxt, Bmat, HEmatpar.pBits);\n    \n    auto end = std::chrono::steady_clock::now();\n    auto diff = end - start;\n    double timeElapsed = chrono::duration <double, milli> (diff).count()/1000.0;\n    cout << \"Enc time= \" << timeElapsed << \" s\" << endl;\n    cout << \"------------------\" << endl;\n    \n    /*---------------------------------------*/\n    //  GenPoly\n    /*---------------------------------------*/\n    \n    start= chrono::steady_clock::now();\n    \n    ZZX** Initpoly;\n    HEmatrix.genMultPoly(Initpoly);\n    \n    ZZX* shiftpoly;\n    HEmatrix.genShiftPoly(shiftpoly);\n    \n    end = std::chrono::steady_clock::now();\n    diff = end - start;\n    timeElapsed = chrono::duration <double, milli> (diff).count()/1000.0;\n    cout << \"GenPoly time= \" << timeElapsed << \" s\" << endl;\n    cout << \"---------------------------\" << endl;\n    \n    /*---------------------------------------*/\n    //  Mult\n    /*---------------------------------------*/\n    \n    start= chrono::steady_clock::now();\n    Ciphertext Cctxt;\n    HEmatrix.HErmatmul(Cctxt, Actxt, Bctxt, Initpoly, shiftpoly);\n    \n    end = std::chrono::steady_clock::now();\n    diff = end - start;\n    timeElapsed = chrono::duration <double, milli> (diff).count()/1000.0;\n    cout << \"R-Mult time= \" << timeElapsed << \" s\" << endl;\n    \n    /*---------------------------------------*/\n    //  Decryption\n    /*---------------------------------------*/\n    Mat<RR> HEresmat;\n    HEmatrix.decryptRmat(HEresmat, Cctxt);\n    \n    /*---------------------------------------*/\n    //  Error\n    /*---------------------------------------*/\n    Mat<RR> resmat;\n    mul(resmat, rAmat, Bmat);\n    \n    RR error = getError(resmat, HEresmat, subdim, ncols);\n    cout << \"Error (mul): \" << error << endl;\n    \n    cout << \"------------------\" << endl;\n    cout << \"Plaintext\" << endl;\n    printRmatrix(resmat, 4);\n    cout << \"------------------\" << endl;\n    cout << \"Encryption\" << endl;\n    printRmatrix(HEresmat, 4);\n    cout << \"------------------\" << endl;\n}\n\n// If Amat is given in plaintext\n\nvoid TestHEmatrix::testMult_preprocessing(long nrows) {\n    \n    long logN = 13;\n    \n    long ncols = nrows;\n    long pBits = 25;   // scaling factor for message\n    long cBits = 14;   // scaling factor for constant\n    long lBits = pBits + 8;\n    long logQ = cBits + pBits + lBits;\n    \n    long h = 64;\n    long keydist = 1;\n    \n    struct HEMatpar HEmatpar;\n    readHEMatpar(HEmatpar, nrows, ncols, pBits, cBits, logQ);\n    \n    cout << \"------------------\" << endl;\n    cout << \"(dim,po2dim, nslots) = (\" << nrows << \",\" << HEmatpar.dim  << \",\" << HEmatpar.sqrdim << \",\" << HEmatpar.nslots << \")\" << endl;\n    cout << \"HEAAN PARAMETER logQ: \" << logQ << endl;\n    cout << \"HEAAN PARAMETER logN: \" << logN << endl;\n    \n    \n    /*---------------------------------------*/\n    //  Key Generation\n    /*---------------------------------------*/\n    \n    TimeUtils timeutils;\n    timeutils.start(\"Scheme generating...\");\n    Context context(logN, logQ);\n    SecretKey secretKey(logN, h);\n    Scheme scheme(secretKey, context);\n    \n    scheme.addLeftRotKeys(secretKey);\n    scheme.addRightRotKeys(secretKey);\n    timeutils.stop(\"Scheme generation\");\n    \n    HEmatrix HEmatrix(scheme, secretKey, HEmatpar);\n    \n    /*---------------------------------------*/\n    //  Generate a random matrix\n    /*---------------------------------------*/\n    Mat<RR> Amat;\n    Mat<RR> Bmat;\n    \n    Amat.SetDims(nrows, ncols);\n    Bmat.SetDims(nrows, ncols);\n    \n    for(long i = 0; i < nrows ; i++){\n        for(long j = 0; j < ncols; j++){\n            Amat[i][j]= to_RR((((i* 2 + ncols * j)%3)/10.0));\n            Bmat[i][j]= to_RR((((i*ncols + j )%3)/10.0));\n        }\n    }\n    \n    /*---------------------------------------*/\n    //  Encryption\n    /*---------------------------------------*/\n    \n    auto start= chrono::steady_clock::now();\n    Ciphertext* Actxts;\n    HEmatrix.genInitActxt(Actxts, Amat);\n    \n    Ciphertext Bctxt;\n    HEmatrix.encryptRmat(Bctxt, Bmat, HEmatpar.pBits);\n    \n    auto end = std::chrono::steady_clock::now();\n    auto diff = end - start;\n    double timeElapsed = chrono::duration <double, milli> (diff).count()/1000.0;\n    cout << \"Enc time= \" << timeElapsed << \" s\" << endl;\n    cout << \"------------------\" << endl;\n    \n    /*---------------------------------------*/\n    //  GenPoly\n    /*---------------------------------------*/\n    \n    start= chrono::steady_clock::now();\n    \n    ZZX* Initpoly;\n    HEmatrix.genMultBPoly(Initpoly);\n    \n    end = std::chrono::steady_clock::now();\n    diff = end - start;\n    timeElapsed = chrono::duration <double, milli> (diff).count()/1000.0;\n    cout << \"GenPoly time= \" << timeElapsed << \" s\" << endl;\n    cout << \"---------------------------\" << endl;\n    \n    /*---------------------------------------*/\n    //  Mult\n    /*---------------------------------------*/\n    \n    start= chrono::steady_clock::now();\n    Ciphertext Cctxt;\n    HEmatrix.HEmatmul_preprocessing(Cctxt, Actxts, Bctxt, Initpoly);\n    \n    end = std::chrono::steady_clock::now();\n    diff = end - start;\n    timeElapsed = chrono::duration <double, milli> (diff).count()/1000.0;\n    cout << \"Mult time (preprocessing)= \" << timeElapsed << \" s\" << endl;\n    \n    /*---------------------------------------*/\n    //  Decryption\n    /*---------------------------------------*/\n    Mat<RR> HEresmat;\n    HEmatrix.decryptRmat(HEresmat, Cctxt);\n    \n    /*---------------------------------------*/\n    //  Error\n    /*---------------------------------------*/\n    Mat<RR> resmat;\n    mul(resmat, Amat, Bmat);\n    \n    RR error = getError(resmat, HEresmat, nrows, ncols);\n    cout << \"Error (mul): \" << error << endl;\n    \n    cout << \"------------------\" << endl;\n    cout << \"Plaintext\" << endl;\n    printRmatrix(resmat, 4);\n    cout << \"------------------\" << endl;\n    cout << \"Encryption\" << endl;\n    printRmatrix(HEresmat, 4);\n    cout << \"------------------\" << endl;\n}\n\nvoid TestHEmatrix::testRMult_preprocessing(long nrows, long subdim) {\n    \n    long logN = 13;\n    \n    long ncols = nrows;\n    long pBits = 25;   // scaling factor for message\n    long cBits = 14;   // scaling factor for constant\n    long lBits = pBits + 8;\n    long logQ = (cBits) + pBits + lBits;\n    \n    long h = 64;\n    long keydist = 1;\n    \n    struct HEMatpar HEmatpar;\n    readHEMatpar(HEmatpar, nrows, ncols, pBits, cBits, logQ, subdim);\n    \n    cout << \"------------------\" << endl;\n    cout << \"(dim,po2dim, nslots) = (\" << nrows << \",\" << HEmatpar.dim  << \",\" << HEmatpar.sqrdim << \",\" << HEmatpar.nslots << \")\" << endl;\n    cout << \"HEAAN PARAMETER logQ: \" << logQ << endl;\n    cout << \"HEAAN PARAMETER logN: \" << logN << endl;\n    \n    \n    /*---------------------------------------*/\n    //  Key Generation\n    /*---------------------------------------*/\n    \n    TimeUtils timeutils;\n    timeutils.start(\"Scheme generating...\");\n    Context context(logN, logQ);\n    SecretKey secretKey(logN, h);\n    Scheme scheme(secretKey, context);\n    \n    scheme.addLeftRotKeys(secretKey);\n    scheme.addRightRotKeys(secretKey);\n    timeutils.stop(\"Scheme generation\");\n    \n    HEmatrix HEmatrix(scheme, secretKey, HEmatpar);\n    \n    /*---------------------------------------*/\n    //  Generate a random matrix\n    /*---------------------------------------*/\n    Mat<RR> rAmat;\n    rAmat.SetDims(subdim, ncols);\n    \n    Mat<RR> Bmat;\n    Bmat.SetDims(nrows, ncols);\n    \n    for(long i = 0; i < subdim; i++){\n        for(long j = 0; j < ncols; j++){\n            rAmat[i][j]= to_RR((((i + ncols * j)%3)/10.0));\n        }\n    }\n    \n    for(long i = 0; i < nrows ; i++){\n        for(long j = 0; j < ncols; j++){\n            Bmat[i][j]= to_RR((((i*ncols + j )%3)/10.0));\n        }\n    }\n\n    \n    /*---------------------------------------*/\n    //  Encryption\n    /*---------------------------------------*/\n    \n    auto start= chrono::steady_clock::now();\n    Ciphertext* Actxts;\n    HEmatrix.genInitRecActxt(Actxts, rAmat);\n    \n    Ciphertext Bctxt;\n    HEmatrix.encryptRmat(Bctxt, Bmat, HEmatpar.pBits);\n    \n    auto end = std::chrono::steady_clock::now();\n    auto diff = end - start;\n    double timeElapsed = chrono::duration <double, milli> (diff).count()/1000.0;\n    cout << \"Enc time= \" << timeElapsed << \" s\" << endl;\n    cout << \"------------------\" << endl;\n    \n    /*---------------------------------------*/\n    //  GenPoly\n    /*---------------------------------------*/\n    \n    start= chrono::steady_clock::now();\n    \n    ZZX* Initpoly;\n    HEmatrix.genMultBPoly(Initpoly);\n    \n    end = std::chrono::steady_clock::now();\n    diff = end - start;\n    timeElapsed = chrono::duration <double, milli> (diff).count()/1000.0;\n    cout << \"GenPoly time= \" << timeElapsed << \" s\" << endl;\n    cout << \"---------------------------\" << endl;\n    \n    /*---------------------------------------*/\n    //  Mult\n    /*---------------------------------------*/\n    \n    start= chrono::steady_clock::now();\n    Ciphertext Cctxt;\n    HEmatrix.HErmatmul_preprocessing(Cctxt, Actxts, Bctxt, Initpoly);\n    \n    end = std::chrono::steady_clock::now();\n    diff = end - start;\n    timeElapsed = chrono::duration <double, milli> (diff).count()/1000.0;\n    cout << \"R-Mult time= \" << timeElapsed << \" s\" << endl;\n    \n    /*---------------------------------------*/\n    //  Decryption\n    /*---------------------------------------*/\n    Mat<RR> HEresmat;\n    HEmatrix.decryptRmat(HEresmat, Cctxt);\n    \n    /*---------------------------------------*/\n    //  Error\n    /*---------------------------------------*/\n    Mat<RR> resmat;\n    mul(resmat, rAmat, Bmat);\n    \n    RR error = getError(resmat, HEresmat, subdim, ncols);\n    cout << \"Error (mul): \" << error << endl;\n    \n    cout << \"------------------\" << endl;\n    cout << \"Plaintext\" << endl;\n    printRmatrix(resmat, 4);\n    cout << \"------------------\" << endl;\n    cout << \"Encryption\" << endl;\n    printRmatrix(HEresmat, 4);\n    cout << \"------------------\" << endl;\n}\n\n//----------------------------------------------------\n// SIMD (parallel computation)\n\nvoid TestHEmatrix::testSIMDAdd(long nrows, long nbatching, const long niter) {\n    \n    long logN = 13;\n    \n    long ncols = nrows;\n    \n    if(nrows * ncols * nbatching > (1<< (logN-1))){\n        cout << \"Cannot support the parallism \" << endl;\n    }\n    \n    long pBits = 25;   // scaling factor for message\n    long cBits = 15;   // scaling factor for constant\n    long lBits = pBits + 5;\n    long logQ = lBits;\n    \n    long h = 64;\n    long keydist = 1;\n    \n    struct HEMatpar HEmatpar;\n    readHEMatpar(HEmatpar, nrows, ncols, pBits, cBits, logQ, 0, nbatching);\n    \n    cout << \"------------------\" << endl;\n    cout << \"(dim, nslots, nbatching) = (\" << nrows << \",\"  << HEmatpar.nslots << \",\"  << HEmatpar.nbatching << \")\" << endl;\n    cout << \"HEAAN PARAMETER logQ: \" << logQ << endl;\n    cout << \"HEAAN PARAMETER logN: \" << logN << endl;\n    \n    \n    /*---------------------------------------*/\n    //  Key Generation\n    /*---------------------------------------*/\n    \n    TimeUtils timeutils;\n    timeutils.start(\"Scheme generating...\");\n    Context context(logN, logQ);\n    SecretKey secretKey(logN, h);\n    Scheme scheme(secretKey, context);\n    \n    scheme.addLeftRotKeys(secretKey);\n    scheme.addRightRotKeys(secretKey);\n    timeutils.stop(\"Scheme generation\");\n    \n    HEmatrix HEmatrix(scheme, secretKey, HEmatpar);\n    \n    /*---------------------------------------*/\n    //  Generate a random matrix\n    /*---------------------------------------*/\n    Mat<RR>* Amat = new Mat<RR>[nbatching];\n    Mat<RR>* Bmat = new Mat<RR>[nbatching];\n    \n    for(long k = 0; k < nbatching; ++k){\n        Amat[k].SetDims(nrows, ncols);\n        Bmat[k].SetDims(nrows, ncols);\n        \n        for(long i = 0; i < nrows ; i++){\n            for(long j = 0; j < ncols; j++){\n                //Amat[k][i][j] = to_RR((((i*2 + ncols * j + 1)%3)/10.0));\n                Amat[k][i][j] = to_RR(((i*ncols + j)%3/10.0));\n                Bmat[k][i][j] = to_RR(((i*ncols + j)%3/10.0));\n            }\n        }\n    }\n    \n    double totalEnctime = 0.0;\n    double totalEvaltime = 0.0;\n    double amortizedtime = 0.0;\n    double totalDectime = 0.0;\n    \n    for(long l = 0; l < niter; ++l){\n        /*---------------------------------------*/\n        //  Encryption\n        /*---------------------------------------*/\n        \n        auto start= chrono::steady_clock::now();\n        Ciphertext Actxt;\n        HEmatrix.encryptParallelRmat(Actxt, Amat, HEmatpar.pBits, nbatching);\n        \n        Ciphertext Bctxt;\n        HEmatrix.encryptParallelRmat(Bctxt, Bmat, HEmatpar.pBits, nbatching);\n        \n        auto end = std::chrono::steady_clock::now();\n        auto diff = end - start;\n        double timeElapsed = chrono::duration <double, milli> (diff).count()/1000.0;\n        totalEnctime += timeElapsed;\n        \n        cout << \"Encryption\" << endl;\n        \n        /*---------------------------------------*/\n        //  Addition\n        /*---------------------------------------*/\n        \n        start= chrono::steady_clock::now();\n        \n        scheme.addAndEqual(Actxt, Bctxt);\n        \n        end = std::chrono::steady_clock::now();\n        diff = end - start;\n        timeElapsed = chrono::duration <double, milli> (diff).count()/1000.0;\n        \n        totalEvaltime += timeElapsed;\n        amortizedtime += timeElapsed/nbatching;\n        \n        /*---------------------------------------*/\n        //  Decryption\n        /*---------------------------------------*/\n        start= chrono::steady_clock::now();\n        \n        Mat<RR>* HEresmat;\n        HEmatrix.decryptParallelRmat(HEresmat, Actxt);\n        \n        end = std::chrono::steady_clock::now();\n        diff = end - start;\n        timeElapsed = chrono::duration <double, milli> (diff).count()/1000.0;\n        totalDectime += timeElapsed;\n        \n        /*---------------------------------------*/\n        //  Error\n        /*---------------------------------------*/\n        RR avgerror_add = to_RR(\"0\");\n        \n        Mat<RR>* resmat = new Mat<RR>[nbatching];\n        for(long k = 0; k < nbatching; ++k){\n            add(resmat[k], Amat[k], Bmat[k]);\n            avgerror_add += getError(resmat[k], HEresmat[k], nrows, ncols);\n        }\n        avgerror_add /= nbatching;\n        \n        if(l == niter -1) cout << \"Error (add): \" << avgerror_add << endl;\n    }\n    \n    cout << \"------------------\" << endl;\n    cout << \"Enc time= \" << totalEnctime/niter << \" s\" << endl;\n    cout << \"Add time= \" << totalEvaltime/niter << \" s/ \" ;\n    cout << \"Amortized time= \" << amortizedtime/niter << \" s\" << endl;\n    cout << \"Dec time= \" <<  totalDectime/niter << \" s\" << endl;\n    \n}\n\nvoid TestHEmatrix::testSIMDTrans(long nrows, long nbatching, const long niter) {\n    \n    long logN = 13;\n    \n    long ncols = nrows;\n    \n    if(nrows * ncols * nbatching > (1<< (logN-1))){\n        cout << \"Cannot support the parallism \" << endl;\n    }\n    \n    long pBits = 25;   // scaling factor for message\n    long cBits = 15;   // scaling factor for constant\n    long lBits = pBits + 5;\n    long logQ = cBits + lBits;\n    \n    long h = 64;\n    long keydist = 1;\n    \n    struct HEMatpar HEmatpar;\n    readHEMatpar(HEmatpar, nrows, ncols, pBits, cBits, logQ, 0, nbatching);\n    \n    cout << \"------------------\" << endl;\n    cout << \"(dim, nslots, nbatching) = (\" << nrows << \",\"  << HEmatpar.nslots << \",\"  << HEmatpar.nbatching << \")\" << endl;\n    cout << \"HEAAN PARAMETER logQ: \" << logQ << endl;\n    cout << \"HEAAN PARAMETER logN: \" << logN << endl;\n    \n    \n    /*---------------------------------------*/\n    //  Key Generation\n    /*---------------------------------------*/\n    \n    TimeUtils timeutils;\n    timeutils.start(\"Scheme generating...\");\n    Context context(logN, logQ);\n    SecretKey secretKey(logN, h);\n    Scheme scheme(secretKey, context);\n    \n    scheme.addLeftRotKeys(secretKey);\n    scheme.addRightRotKeys(secretKey);\n    timeutils.stop(\"Scheme generation\");\n    \n    HEmatrix HEmatrix(scheme, secretKey, HEmatpar);\n    \n    /*---------------------------------------*/\n    //  Generate a random matrix\n    /*---------------------------------------*/\n    Mat<RR>* Amat = new Mat<RR>[nbatching];\n   \n    for(long k = 0; k < nbatching; ++k){\n        Amat[k].SetDims(nrows, ncols);\n        for(long i = 0; i < nrows ; i++){\n            for(long j = 0; j < ncols; j++){\n                Amat[k][i][j] = to_RR(((i*ncols + j)%3/10.0));\n            }\n        }\n    }\n    \n    double totalEnctime = 0.0;\n    double totalEvaltime = 0.0;\n    double amortizedtime = 0.0;\n    double totalDectime = 0.0;\n    \n    for(long l = 0; l < niter; ++l){\n        /*---------------------------------------*/\n        //  Encryption\n        /*---------------------------------------*/\n        \n        auto start= chrono::steady_clock::now();\n        Ciphertext Actxt;\n        HEmatrix.encryptParallelRmat(Actxt, Amat, HEmatpar.pBits, nbatching);\n        \n        \n        auto end = std::chrono::steady_clock::now();\n        auto diff = end - start;\n        double timeElapsed = chrono::duration <double, milli> (diff).count()/1000.0;\n        totalEnctime += timeElapsed;\n        \n        \n        /*---------------------------------------*/\n        //  Transpose\n        /*---------------------------------------*/\n        ZZX* transpoly;\n        HEmatrix.genTransPoly_Parallel(transpoly);\n        \n        start= chrono::steady_clock::now();\n        Ciphertext Tctxt;\n        HEmatrix.transpose_Parallel(Tctxt, Actxt, transpoly);\n        \n        end = std::chrono::steady_clock::now();\n        diff = end - start;\n        timeElapsed = chrono::duration <double, milli> (diff).count()/1000.0;\n        \n        totalEvaltime += timeElapsed;\n        amortizedtime += timeElapsed/nbatching;\n        \n        /*---------------------------------------*/\n        //  Decryption\n        /*---------------------------------------*/\n        start= chrono::steady_clock::now();\n        \n        Mat<RR>* HEresmat;\n        HEmatrix.decryptParallelRmat(HEresmat, Tctxt);\n        \n        end = std::chrono::steady_clock::now();\n        diff = end - start;\n        timeElapsed = chrono::duration <double, milli> (diff).count()/1000.0;\n        totalDectime += timeElapsed;\n        \n        /*---------------------------------------*/\n        //  Error\n        /*---------------------------------------*/\n        RR avgerror = to_RR(\"0\");\n        Mat<RR>* resmat = new Mat<RR>[nbatching];\n        for(long k = 0; k < nbatching; ++k){\n            transpose(resmat[k], Amat[k]);\n            avgerror += getError(HEresmat[k], resmat[k], nrows, ncols);\n        }\n        avgerror /= nbatching;\n        \n        if(l == niter -1) cout << \"Error (trans): \" << avgerror << endl;\n    }\n    \n    cout << \"------------------\" << endl;\n    cout << \"Enc time= \" << totalEnctime/niter << \" s\" << endl;\n    cout << \"Trans time= \" << totalEvaltime/niter << \" s/ \" ;\n    cout << \"Amortized time= \" << amortizedtime/niter << \" s\" << endl;\n    cout << \"Dec time= \" <<  totalDectime/niter << \" s\" << endl;\n    \n}\n\n\nvoid TestHEmatrix::testSIMDMult(long nrows, long nbatching, const long niter) {\n    \n    long logN = 13;\n    \n    long ncols = nrows;\n    \n    if(nrows * ncols * nbatching > (1<< (logN-1))){\n        cout << \"Cannot support the parallism \" << endl;\n    }\n    \n    long pBits = 25;   // scaling factor for message\n    long cBits = 15;   // scaling factor for constant\n    long lBits = pBits + 5;\n    long logQ = (2*cBits + pBits) + lBits;\n    \n    long h = 64;\n    long keydist = 1;\n    \n    struct HEMatpar HEmatpar;\n    readHEMatpar(HEmatpar, nrows, ncols, pBits, cBits, logQ, 0, nbatching);\n    \n    cout << \"------------------\" << endl;\n    cout << \"(dim, nslots, nbatching) = (\" << nrows << \",\"  << HEmatpar.nslots << \",\"  << HEmatpar.nbatching << \")\" << endl;\n    cout << \"HEAAN PARAMETER logQ: \" << logQ << endl;\n    cout << \"HEAAN PARAMETER logN: \" << logN << endl;\n    \n    \n    /*---------------------------------------*/\n    //  Key Generation\n    /*---------------------------------------*/\n    \n    TimeUtils timeutils;\n    timeutils.start(\"Scheme generating...\");\n    Context context(logN, logQ);\n    SecretKey secretKey(logN, h);\n    Scheme scheme(secretKey, context);\n    \n    scheme.addLeftRotKeys(secretKey);\n    scheme.addRightRotKeys(secretKey);\n    timeutils.stop(\"Scheme generation\");\n    \n    HEmatrix HEmatrix(scheme, secretKey, HEmatpar);\n    \n    /*---------------------------------------*/\n    //  Generate a random matrix\n    /*---------------------------------------*/\n    Mat<RR>* Amat = new Mat<RR>[nbatching];\n    Mat<RR>* Bmat = new Mat<RR>[nbatching];\n    \n    for(long k = 0; k < nbatching; ++k){\n        Amat[k].SetDims(nrows, ncols);\n        Bmat[k].SetDims(nrows, ncols);\n        \n        for(long i = 0; i < nrows ; i++){\n            for(long j = 0; j < ncols; j++){\n                //Amat[k][i][j] = to_RR((((i*2 + ncols * j + 1)%3)/10.0));\n                Amat[k][i][j] = to_RR(((i*ncols + j)%3/10.0));\n                Bmat[k][i][j] = to_RR(((i*ncols + j)%3/10.0));\n            }\n        }\n    }\n    \n    double totalEnctime = 0.0;\n    double totalEvaltime = 0.0;\n    double amortizedtime = 0.0;\n    double totalDectime = 0.0;\n    double genpolytime = 0.0;\n    \n    for(long l = 0; l < niter; ++l){\n        /*---------------------------------------*/\n        //  Encryption\n        /*---------------------------------------*/\n        \n        auto start= chrono::steady_clock::now();\n        Ciphertext Actxt;\n        HEmatrix.encryptParallelRmat(Actxt, Amat, HEmatpar.pBits, nbatching);\n        \n        Ciphertext Bctxt;\n        HEmatrix.encryptParallelRmat(Bctxt, Bmat, HEmatpar.pBits, nbatching);\n        \n        auto end = std::chrono::steady_clock::now();\n        auto diff = end - start;\n        double timeElapsed = chrono::duration <double, milli> (diff).count()/1000.0;\n        totalEnctime += timeElapsed;\n        \n        /*---------------------------------------*/\n        //  Genpoly\n        /*---------------------------------------*/\n        \n        start= chrono::steady_clock::now();\n        \n        ZZX** Initpoly;\n        HEmatrix.genMultPoly_Parallel(Initpoly);\n        \n        ZZX* shiftpoly;\n        HEmatrix.genShiftPoly_Parallel(shiftpoly);\n        \n        end = std::chrono::steady_clock::now();\n        diff = end - start;\n        timeElapsed = chrono::duration <double, milli> (diff).count()/1000.0;\n        genpolytime += timeElapsed;\n        \n        /*---------------------------------------*/\n        //  Mult\n        /*---------------------------------------*/\n        \n        start= chrono::steady_clock::now();\n        \n        Ciphertext Cctxt;\n        HEmatrix.HEmatmul_Parallel(Cctxt, Actxt, Bctxt, Initpoly, shiftpoly);\n        \n        end = std::chrono::steady_clock::now();\n        diff = end - start;\n        timeElapsed = chrono::duration <double, milli> (diff).count()/1000.0;\n        \n        totalEvaltime += timeElapsed;\n        amortizedtime += timeElapsed/nbatching;\n        \n        /*---------------------------------------*/\n        //  Decryption\n        /*---------------------------------------*/\n        start= chrono::steady_clock::now();\n        \n        Mat<RR>* HEresmat;\n        HEmatrix.decryptParallelRmat(HEresmat, Cctxt);\n        \n        end = std::chrono::steady_clock::now();\n        diff = end - start;\n        timeElapsed = chrono::duration <double, milli> (diff).count()/1000.0;\n        totalDectime += timeElapsed;\n        \n        /*---------------------------------------*/\n        //  Error\n        /*---------------------------------------*/\n        RR avgerror_mult = to_RR(\"0\");\n        Mat<RR>* resmat = new Mat<RR>[nbatching];\n        for(long k = 0; k < nbatching; ++k){\n            mul(resmat[k], Amat[k], Bmat[k]);\n            avgerror_mult += getError(HEresmat[k], resmat[k], nrows, ncols);\n        }\n        avgerror_mult /= nbatching;\n        \n        if(l == niter -1) cout << \"Error (mult): \" << avgerror_mult << endl;\n    }\n    \n    cout << \"------------------\" << endl;\n    cout << \"Enc time= \" << totalEnctime/niter << \" s\" << endl;\n    cout << \"Mult time= \" << totalEvaltime/niter << \" s/ \" ;\n    cout << \"Amortized time= \" << amortizedtime/niter << \" s\" << endl;\n    cout << \"Dec time= \" <<  totalDectime/niter << \" s\" << endl;\n    \n}\n\nvoid TestHEmatrix::testSIMDMult_Huang(long Arows, long Acols, long Brows, long Bcols, long nbatching)\n{\n\n    long logN = 13;\n    \n    long ncols = Bcols;\n    long nrows = Bcols;\n\n    if(nrows * ncols * nbatching > (1<< (logN-1)))\n    {\n        cout << \"Cannot support the parallism \" << endl;\n    }\n    \n    long pBits = 25;   // scaling factor for message\n    long cBits = 15;   // scaling factor for constant\n    long lBits = pBits + 5;\n    long logQ = (2*cBits + pBits) + lBits;\n    \n    long h = 64;\n    long keydist = 1;\n    \n    struct HEMatpar HEmatpar;\n    readHEMatpar(HEmatpar, nrows, ncols, pBits, cBits, logQ, 0, nbatching);\n    \n    cout << \"------------------\" << endl;\n    cout << \"(dim, nslots, nbatching) = (\" << nrows << \",\"  << HEmatpar.nslots << \",\"  << HEmatpar.nbatching << \")\" << endl;\n    cout << \"HEAAN PARAMETER logQ: \" << logQ << endl;\n    cout << \"HEAAN PARAMETER logN: \" << logN << endl;\n    \n    /*---------------------------------------*/\n    //  Initialization random seed\n    /*---------------------------------------*/\n    srand(time(NULL));\n    /*---------------------------------------*/\n    //  Key Generation\n    /*---------------------------------------*/\n    \n    TimeUtils timeutils;\n    timeutils.start(\"Scheme generating...\");\n    Context context(logN, logQ);\n    SecretKey secretKey(logN, h);\n    Scheme scheme(secretKey, context);\n    \n    scheme.addLeftRotKeys(secretKey);\n    scheme.addRightRotKeys(secretKey);\n    timeutils.stop(\"Scheme generation\");\n    \n    HEmatrix HEmatrix(scheme, secretKey, HEmatpar);\n    \n    /*---------------------------------------*/\n    //  Generate a random matrix\n    /*---------------------------------------*/\n    Mat<RR>* Mat_Vertical_Stack = new Mat<RR>[2];\n    Mat_Vertical_Stack[0].SetDims(Acols, Acols);Mat_Vertical_Stack[1].SetDims(Acols, Acols);\n    Mat<RR>* Mat_Horizontal_Stack = new Mat<RR>[2];\n    Mat_Horizontal_Stack[0].SetDims(Brows, Brows);Mat_Horizontal_Stack[1].SetDims(Brows, Brows);\n\n    Mat<RR> vertical_Amat, Amat, Random_Amat;\n    vertical_Amat.SetDims(2 * Arows, Acols);Amat.SetDims(Acols, Acols);Random_Amat.SetDims(Acols, Acols);\n    Mat<RR> horizontal_Bmat_trans,Bmat, Random_Bmat;\n    horizontal_Bmat_trans.SetDims(2 * Brows, Brows);Bmat.SetDims(Brows, Brows);Random_Bmat.SetDims(Brows, Brows);\n    \n    for(long i = 0; i < Acols; i++)\n    {\n        for(long j = 0; j < Acols; j++)\n        {\n            Amat[i][j] = to_RR(rand() % 5);\n            Random_Amat[i][j] = to_RR(rand() % 5);\n        }\n        vertical_Amat[i] = Amat[i];\n        vertical_Amat[i + Acols] = Random_Amat[i];\n    }\n\n    cout << \"Amat : \" << endl;\n    cout << Amat << endl;\n    cout << \"Random_Amat : \" << endl;\n    cout << Random_Amat << endl;\n    cout << \"vertical_Amat : \" << endl;\n    cout << vertical_Amat << endl;\n\n    for(long i = 0; i < Bcols; i++)\n    {\n        for(long j = 0; j < Bcols; j++)\n        {\n            Bmat[i][j] = to_RR(rand() % 5);\n            Random_Bmat[i][j] = to_RR(rand() % 5);\n        }\n    }\n    Mat<RR> Bmat_trans = transpose(Bmat);\n    Mat<RR> Random_Bmat_trans = transpose(Random_Bmat);\n    for(long j = 0; j < Bcols; j++)\n    {\n        horizontal_Bmat_trans[j] = Bmat_trans[j];\n        horizontal_Bmat_trans[j + Bcols] = Random_Bmat_trans[j];\n    }\n\n    cout << \"Bmat : \" << endl;\n    cout << Bmat << endl;\n    cout << \"Random_Bmat : \" << endl;\n    cout << Random_Bmat << endl;\n    cout << \"horizontal_Bmat : \" << endl;\n    cout << horizontal_Bmat_trans << endl;\n\n    Mat<RR> permutation_Amat, permutation_Bmat;\n    permutation_Amat.SetDims(2 * Arows, 2 * Arows);\n    permutation_Bmat.SetDims(2 * Bcols, 2 * Bcols);\n    generate_random_permutation_matrix(permutation_Amat);   // ??? \n    generate_random_permutation_matrix(permutation_Bmat);\n\n    cout << \"permutation_Amat : \" << endl;\n    cout << permutation_Amat << endl;\n\n    cout << \"permutation_Bmat : \" << endl;\n    cout << permutation_Bmat << endl;\n\n    Mat<RR> vertical_Amat_mul = permutation_Amat * vertical_Amat;\n    Mat<RR> horizontal_Bmat_mul = transpose(horizontal_Bmat_trans) * permutation_Bmat;\n\n\n    for(long i = 0; i < Arows; i++)\n    {\n        Mat_Vertical_Stack[0][i] = vertical_Amat_mul[i];\n        Mat_Vertical_Stack[1][i] = vertical_Amat_mul[i + Arows];\n    }\n    for(long i = 0; i < Arows; i++)\n    {\n        for(long j = 0; j < Arows; j++)\n        {\n            Mat_Horizontal_Stack[0][i][j] = horizontal_Bmat_mul[i][j];\n            Mat_Horizontal_Stack[1][i][j] = horizontal_Bmat_mul[i][j + Arows];\n        }\n    }\n\n\n    cout << \"Mat_Vertical_Stack[0] : \" << endl;\n    cout << Mat_Vertical_Stack[0] << endl;\n    cout << \"Mat_Vertical_Stack[1] : \" << endl;\n    cout << Mat_Vertical_Stack[1] << endl;\n\n    cout << \"transpose Mat_Horizontal_Stack[0] : \" << endl;\n    cout << Mat_Horizontal_Stack[0] << endl;\n\n    cout << \"transpose Mat_Horizontal_Stack[1] : \" << endl;\n    cout << Mat_Horizontal_Stack[1] << endl;\n\n    /* 0th diagonal multiply vector */\n    Ciphertext Actxt;\n    HEmatrix.encryptParallelRmat(Actxt, Mat_Vertical_Stack, HEmatpar.pBits, nbatching);\n\n    Ciphertext Bctxt;\n    HEmatrix.encryptParallelRmat(Bctxt, Mat_Horizontal_Stack, HEmatpar.pBits, nbatching);\n    \n    ZZX** Initpoly;\n    HEmatrix.genMultPoly_Parallel_Huang(Initpoly, 0);\n\n    ZZX* shiftpoly;\n    HEmatrix.genShiftPoly_Parallel(shiftpoly);\n\n    Ciphertext* res = new Ciphertext[nbatching];\n    HEmatrix.HEmatmul_Parallel_Huang(res[0], Actxt, Bctxt, Initpoly, shiftpoly);\n\n    /* 1th diagonal multiply vector */\n    Ciphertext Bctxt_rot_one = scheme.leftRotate(Bctxt, 1);\n\n    HEmatrix.genMultPoly_Parallel_Huang(Initpoly, 1);\n\n    HEmatrix.HEmatmul_Parallel_Huang(res[1], Actxt, Bctxt_rot_one, Initpoly, shiftpoly);\n\n    /*---------------------------------------*/\n    //  Decryption\n    /*---------------------------------------*/\n    Mat<RR> DecryptionRes;DecryptionRes.SetDims(2 * Arows, 2 * Arows);\n    Mat<RR>** HEresmat = new Mat<RR>*[nbatching];\n    for(long i = 0; i < nbatching; i++)\n    {\n        HEmatrix.decryptParallelRmat(HEresmat[i], res[i]);\n        cout << \"(\" << i << \",0)\" << endl;\n        cout << HEresmat[i][0] << endl;\n        cout << \"(\" << i << \",1)\" << endl;\n        cout << HEresmat[i][1] << endl;\n        for(long j = 0; j < nbatching; j++)\n        {\n            for(long k = 0; k < Arows; k++)\n            {\n                for(long l = 0; l < Arows; l++)\n                {\n                    DecryptionRes[(k + j * Arows)][(l + (i + j) * Arows) % (2 * Arows)] = HEresmat[i][j][k][l];\n                }\n            }\n            \n        }\n    }\n    cout << \"DecryptionRes : \" << endl;\n    cout << DecryptionRes << endl;\n    // plaintext random matrix multiplication\n\n    Mat<RR> permutation_res = transpose(permutation_Amat) * DecryptionRes * transpose(permutation_Bmat);\n    Mat<RR> random_matrix_multiplication = Random_Amat * Random_Bmat;\n\n    cout << \"permutation_res : \" << endl;\n    cout << permutation_res << endl;\n    cout << \"random_matrix_multiplication : \" << endl;\n    cout << random_matrix_multiplication << endl;\n    bool flag = false; \n    for(long i = Arows; i < 2 * Arows; i++)\n    {\n        for(long j = Arows; j < 2 * Arows; j++)\n        {\n            if(abs(permutation_res[i][j] - random_matrix_multiplication[i - Arows][j - Arows]) > to_RR(0.01))\n            {\n                flag = true;\n                cout << \"The result is not correct !!!\" << endl;\n                break;\n            }\n        }\n    }\n    if(!flag)\n    {\n        cout << \"The result is correct\" << endl;\n    }\n}\n", "meta": {"hexsha": "0712b602a5ed3ebfbefbcddb7bc77327ec94d9ad", "size": 55798, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "HEMat/TestHEmatrix.cpp", "max_stars_repo_name": "pwnmelife/HEMat", "max_stars_repo_head_hexsha": "1ce4fdfa0ed83ebf59709ddc3e2e7cd6215666d9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "HEMat/TestHEmatrix.cpp", "max_issues_repo_name": "pwnmelife/HEMat", "max_issues_repo_head_hexsha": "1ce4fdfa0ed83ebf59709ddc3e2e7cd6215666d9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HEMat/TestHEmatrix.cpp", "max_forks_repo_name": "pwnmelife/HEMat", "max_forks_repo_head_hexsha": "1ce4fdfa0ed83ebf59709ddc3e2e7cd6215666d9", "max_forks_repo_licenses": ["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.7756264237, "max_line_length": 139, "alphanum_fraction": 0.4692999749, "num_tokens": 15256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4969724248058595}}
{"text": "//  (C) Copyright Matt Borland 2021.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n//\n\n#ifndef BOOST_MATH_CCMATH_HPP\n#define BOOST_MATH_CCMATH_HPP\n\n#include <boost/math/ccmath/sqrt.hpp>\n#include <boost/math/ccmath/isinf.hpp>\n#include <boost/math/ccmath/isnan.hpp>\n#include <boost/math/ccmath/abs.hpp>\n#include <boost/math/ccmath/fabs.hpp>\n#include <boost/math/ccmath/isfinite.hpp>\n#include <boost/math/ccmath/isnormal.hpp>\n#include <boost/math/ccmath/fpclassify.hpp>\n#include <boost/math/ccmath/frexp.hpp>\n#include <boost/math/ccmath/div.hpp>\n#include <boost/math/ccmath/logb.hpp>\n#include <boost/math/ccmath/ilogb.hpp>\n#include <boost/math/ccmath/scalbn.hpp>\n#include <boost/math/ccmath/scalbln.hpp>\n#include <boost/math/ccmath/floor.hpp>\n#include <boost/math/ccmath/ceil.hpp>\n#include <boost/math/ccmath/trunc.hpp>\n#include <boost/math/ccmath/modf.hpp>\n#include <boost/math/ccmath/round.hpp>\n#include <boost/math/ccmath/fmod.hpp>\n#include <boost/math/ccmath/remainder.hpp>\n#include <boost/math/ccmath/copysign.hpp>\n\n#endif // BOOST_MATH_CCMATH_HPP\n", "meta": {"hexsha": "73e30c0b11f66bea9d3b38eac9009e4988a09add", "size": 1195, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/boost_1.78.0/boost/math/ccmath/ccmath.hpp", "max_stars_repo_name": "LaudateCorpus1/math", "max_stars_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-22T11:10:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-22T11:10:19.000Z", "max_issues_repo_path": "lib/boost_1.78.0/boost/math/ccmath/ccmath.hpp", "max_issues_repo_name": "LaudateCorpus1/math", "max_issues_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-12-07T22:56:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-17T22:13:37.000Z", "max_forks_repo_path": "lib/boost_1.78.0/boost/math/ccmath/ccmath.hpp", "max_forks_repo_name": "LaudateCorpus1/math", "max_forks_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2018-07-30T12:45:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-10T11:18:30.000Z", "avg_line_length": 35.1470588235, "max_line_length": 68, "alphanum_fraction": 0.769874477, "num_tokens": 317, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4969724248058595}}
{"text": "/**\n * \\Description:\n * this node is used to implement the Extended kalman Filter equations, its input are the prediction and the measurement, and its output is final estimation.\n * It subscribes to:\n * - /odom2D: this topic contains the 2D pose (x,y,theta) of the turtlrbot and their covariance.\n * - /beacon distances : this topic contains three distance from the robot to each beacon in order \"blue, orange/red, green\".\n * It publishes to:\n * - /robot_pose ekf: it publishes the 2D pose (x,y,theta) of the turtlrbot and their corresponding covariance after modifying the predicted pose using the measurement.\n *\n * ALI&SERRANO_ECN_M1_2017\n */\n\n\n//Cpp\n#include <sstream>\n#include <stdio.h>\n#include <vector>\n#include <iostream>\n#include <stdlib.h>\n#include <math.h>\n#include <Eigen/Dense>\n\nusing namespace Eigen;\nusing namespace std;\nusing Eigen::MatrixXd;\n\n//ROS\n#include \"ros/ros.h\"\n\n// Include here the \".h\" files corresponding to the topic type you use.\n#include <nav_msgs/Odometry.h>\n#include \"tf/transform_datatypes.h\"\n\n#include \"std_msgs/MultiArrayLayout.h\"\n#include \"std_msgs/MultiArrayDimension.h\"\n#include <std_msgs/Float64MultiArray.h>\n\n#include <geometry_msgs/Point.h>\n#include <geometry_msgs/Pose2D.h>\n#include <turtle_ekf/Pose2DWithCovariance.h>\n\n//#include <geometry_msgs/PoseWithCovariance.h>\n//#include <std_msgs/Float32.h>\n\n// global variables...\nturtle_ekf::Pose2DWithCovariance odom2D;\nstd_msgs::Float64MultiArray dist;\nbool is_odom_available= false, is_dist_available=false;\n\n\n// Callback functions...\nvoid odom_Callback( turtle_ekf::Pose2DWithCovariance odom2D_msg) {\n    is_odom_available= true;\n    odom2D = odom2D_msg;\n}\n\nvoid msurmnt_Callback ( std_msgs::Float64MultiArray  dist_msg) {\n    is_dist_available= true;\n    dist = dist_msg;\n}\n\n\nint main (int argc, char** argv){\n\n    //ROS Initialization\n    ros::init(argc, argv, \"ekf_node\");\n\n    // Define your node handles\n    ros::NodeHandle nh_loc(\"~\"), nh_glob;\n\n    // Read the node parameters if any\n\n    // Declare your node's subscriptions and service clients\n    ros::Subscriber odom2D_sub = nh_glob.subscribe<turtle_ekf::Pose2DWithCovariance>(\"/odom2D\",1, odom_Callback) ;\n    ros::Subscriber msurmnt_sub = nh_glob.subscribe<std_msgs::Float64MultiArray>(\"/beacon_distances\",1, msurmnt_Callback) ;\n\n    // Declare you publishers and service servers\n    ros::Publisher  pose_pub = nh_glob.advertise<turtle_ekf::Pose2DWithCovariance>(\"/robot_pose_ekf\",1) ;\n\n    // node initilization\n    MatrixXd Q_alpha =  MatrixXd::Zero(3,3);\n    MatrixXd Q_gamma =  MatrixXd::Zero(3,3);\n    MatrixXd P =  MatrixXd::Zero(3,3);\n    MatrixXd C =  MatrixXd::Zero(3,3);\n    MatrixXd D =  MatrixXd::Zero(3,3);\n    MatrixXd K =  MatrixXd::Zero(3,3);\n    MatrixXd I =  MatrixXd::Zero(3,3);\n    I(0,0)= 1;   I(1,1)= 1;     I(2,2)= 1;\n\n    VectorXd X(3);\n    VectorXd Y(3);\n    VectorXd Y_hat(3);\n\n    geometry_msgs::Point B1, B2, B3;\n    B1.x=0;  B1.y=0; B3.x=4.40; B3.y=3.20; B2.x=0;  B2.y=5.20;\n\n    // Init\n    X(0)=1;   X(1)=1;   X(2)= 0; //M_PI/2;\n// init matrices\n//    for (int i=0; i++; i<3){\n//        for(int j=0; j++; j<3){\n//            P(i,j)= 0;\n//            C(i,j)= 0;\n//            D(i,j)= 0;\n//            K(i,j)= 0;\n//        }\n//    }\n\n\n    ros::Rate rate(10);\n\n    while (ros::ok()){\n\n        ros::spinOnce();\n                if( ! is_dist_available || !is_odom_available ){\n                    ROS_INFO(\"Waiting for odom2D and/or dist\") ;\n                    rate.sleep() ;\n                    continue ;\n                }\n\n        // odometry part:\n        // Prediction step: predicted_state Xk+1/k \"extract pose from odom\"\n        X(0)= odom2D.pose.x;\n        X(1)= odom2D.pose.y;\n        X(2)= odom2D.pose.theta;\n\n        // state_trans_uncertainty_noise: Q_alpha \"extract covariance matrix from odom\"\n        Q_alpha(0,0)= odom2D.Covariance[0];\n        Q_alpha(1,1)= odom2D.Covariance[4];\n        Q_alpha(2,2)= odom2D.Covariance[8];\n\n        // jacobian_matrix: A = I\n\n        // pred_covariance_est: Pk+1/k = A. PK/k. A^T + Q_alpha  \"P= A*P*A.transpose() + Q_alpha;\" but A=I\n        P=P+Q_alpha;\n\n        // measurement part:\n\n        // Actual measurement  Y\n        Y(0)= dist.data[0]/100;\n        Y(1)= dist.data[1]/100;\n        Y(2)= dist.data[2]/100;\n\n        // Expected measurement Y_hat\n        Y_hat(0)= sqrt( (B1.x-X(0))*(B1.x-X(0)) + (B1.y-X(1))*(B1.y-X(1)) );\n        Y_hat(1)= sqrt( (B2.x-X(0))*(B2.x-X(0)) + (B2.y-X(1))*(B2.y-X(1)) );\n        Y_hat(2)= sqrt( (B3.x-X(0))*(B3.x-X(0)) + (B3.y-X(1))*(B3.y-X(1)) );\n\n\ncout<< \"Y:  \"<< Y(0) << \", \" << Y(1) << \", \" <<  Y(2) << endl<< endl;\ncout<< \"Y_hat:  \" << Y_hat(0) << \", \" << Y_hat(1) << \", \" <<  Y_hat(2) <<  endl ;\n\n        // Measurement jacobian C_matrix\n        C(0,0)= 2*(X(0) - B1.x) / Y_hat(0);\n        C(0,1)= 2*(X(1) - B1.y) / Y_hat(0);\n        C(1,0)= 2*(X(0) - B1.x) / Y_hat(1);\n        C(1,1)= 2*(X(1) - B1.y) / Y_hat(1);\n        C(2,0)= 2*(X(0) - B1.x) / Y_hat(2);\n        C(2,1)= 2*(X(1) - B1.y) / Y_hat(2);\n\n        // measurement covariance Q_gamma\n        Q_gamma(0,0)= 10;\n        Q_gamma(1,1)= 10;\n        Q_gamma(2,2)= 10;\n\n        if (Y(0)> 0.3 && Y(0)< 6)\n        Q_gamma(0,0)= (.0000842*Y(0))+0.0158;\n        if (Y(1)> 0.3 && Y(1)< 6)\n        Q_gamma(1,1)= (.0000842*Y(1))+0.0158;\n        if (Y(2)> 0.3 && Y(2)< 6)\n        Q_gamma(2,2)= (.0000842*Y(2))+0.0158;\n\n\nif (Y(0)> 0.3 && Y(0)< 6 && Y(1)> 0.3 && Y(1)< 6 && Y(2)> 0.3 && Y(2)< 6 ){\n\n       // Residual covariance D is Q_(Y-Y_hat)\n       D= ( C*P*C.transpose() + Q_gamma );\n\n       // Correction propotional gain  K= P*C.transpose() * (C*P*C.transpose() + Q_gamma )^-1\n        K= P*C.transpose() * D.reverse();\n\n\n        // Estimation Step: estimated_state Xk+1/k+1 = Xk+1/k + Kk (Yk - Yk_hat)\n        X = X + K*(Y-Y_hat);\n\n        // Estimated_covariance_est: Pk+1/k+1 = ( I - Kk*Ck ) * Pk+1/k\n        P= ( I - K*C ) * P;\n}\n        std::cout<<  \"P\" << P << endl << endl;\n        std::cout<<  \"C\" << C << endl << endl;\n        std::cout<<  \"D\" << D << endl << endl;\n        std::cout<<  \"K\" << K << endl << endl;\n\n        // publish the final pose ........................................................................................................\n        turtle_ekf::Pose2DWithCovariance pose_ekf;\n        pose_ekf.pose.x = X(0);\n        pose_ekf.pose.y = X(1);\n        pose_ekf.pose.theta =  X(2);\n\n        pose_ekf.Covariance[0] =  P(0,0);\n        pose_ekf.Covariance[1] =  0;\n        pose_ekf.Covariance[2] =  0;\n        pose_ekf.Covariance[3] =  0;\n        pose_ekf.Covariance[4] =  P(1,1);\n        pose_ekf.Covariance[5] =  0;\n        pose_ekf.Covariance[6] =  0;\n        pose_ekf.Covariance[7] =  0;\n        pose_ekf.Covariance[8] =  P(2,2);\n\n        pose_pub.publish(pose_ekf);\n\n\n\n\n        rate.sleep();\n    }\n\n\n}\n", "meta": {"hexsha": "ea2fdfabcb2b8f667fc979d75168d5f6562122b4", "size": 6759, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/turtle_ekf/src/ekf_node.cpp", "max_stars_repo_name": "mahmoud-a-ali/TurtleBot_M1_Project", "max_stars_repo_head_hexsha": "a848c5b16fc2521acf265256cfbf9b7206f549d8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-08-18T05:59:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-11T07:47:44.000Z", "max_issues_repo_path": "src/turtle_ekf/src/ekf_node.cpp", "max_issues_repo_name": "mahmoud-a-ali/TurtleBot_M1_Project", "max_issues_repo_head_hexsha": "a848c5b16fc2521acf265256cfbf9b7206f549d8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/turtle_ekf/src/ekf_node.cpp", "max_forks_repo_name": "mahmoud-a-ali/TurtleBot_M1_Project", "max_forks_repo_head_hexsha": "a848c5b16fc2521acf265256cfbf9b7206f549d8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-11-11T07:47:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-11T07:47:45.000Z", "avg_line_length": 30.7227272727, "max_line_length": 168, "alphanum_fraction": 0.5620653943, "num_tokens": 2286, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.49697242480585946}}
{"text": "// Copyright (c) 2018 Evan S Weinberg\n// Thick restarted and deflated Lanczos.\n// Finds some number of exterior largest or\n// smallest values, NOT in magnitude.\n// (Doesn't try solve the interior problem,\n// though there is a way to trick it with the \n// operator (A-sigma)^2 ...)\n// Based on arXiv:1512:08135\n\n#include <iostream>\n#include <iomanip>\n#include <cmath>\n#include <string>\n#include <sstream>\n#include <complex>\n#include <random>\n#include <vector>\n#include <functional>\n\n// Borrow dense matrix eigenvalue routines.\n#include <Eigen/Dense>\n\n#include \"blas/generic_vector.h\"\n\n#include \"../square_laplace.h\"\n\n// Operator class\n#include \"../operator.h\"\n#include \"../poly_operator.h\"\n\n// Lanczos\n#include \"../lanczos.h\"\n#include \"../thick_deflate_lanczos.h\"\n\nusing namespace std; \nusing namespace Eigen;\n\ntypedef Matrix<double, Dynamic, Dynamic, ColMajor> dMatrix;\ntypedef Matrix<std::complex<double>, Dynamic, Dynamic, ColMajor> cMatrix;\n\nint main(int argc, char** argv)\n{  \n  complex<double> *rhs_cplx;\n\n  // Set output precision to be long.\n  cout << setprecision(10);\n\n  // RNG related things.\n  std::mt19937 generator (1337u); // RNG, 1337u is the seed. \n\n  ///////////////////////////////////\n  // Properties of Linear operator //\n  ///////////////////////////////////\n  double inv_variance = 6.0; // inverse of variance for gaussian non-compact U(1) links.\n\n  // Basic information about the lattice.\n  int length = 24;\n  double m_sq = 0.001;\n  \n  // Some start-up.\n  int volume = length*length;\n  \n  // Create a random compact U(1) link.\n  complex<double>* gauge_links = allocate_vector<complex<double>>(2*length*length);\n  gaussian_real(gauge_links, 2*length*length, generator, 1.0/inv_variance);\n  polar(gauge_links, 2*length*length);\n  \n  // Vectors.\n  rhs_cplx = allocate_vector<complex<double>>(volume);\n\n  // Zero out the vector.\n  zero_vector(rhs_cplx, length*length);\n\n  // Structure which gets passed to the function.\n  laplace_gauged_struct lapstr_gauged;\n  lapstr_gauged.length = length;\n  lapstr_gauged.m_sq = m_sq;\n  lapstr_gauged.gauge_links = gauge_links; \n\n  // Uncomment this to get the free field.\n  //constant_vector(gauge_links, 1.0, 2*volume);\n  //std::cout << \"Free case.\\n\\n\";\n\n  std::cout << \"Interacting case.\\n\\n\";\n\n\n  //////////////////////////////////////\n  // Create a linear operator object. //\n  //////////////////////////////////////\n\n  FunctionWrapper<complex<double>> lap_fcn(square_laplacian_gauged, &lapstr_gauged, volume);\n\n\n  //////////////////////////////////////\n  // Properties for Lanczos algorithm //\n  //////////////////////////////////////\n\n  // Fill a struct\n  TRCLStruct lanc_props;\n  lanc_props.n_ev = 10; // get 10 eigenvalues\n  lanc_props.m = 30; // subspace size of 20\n  lanc_props.tol = 1e-10; // lock at a tolerance of 1e-8\n  lanc_props.max_restarts = 500; // maximum of 10 restarts\n  lanc_props.preserved_space = 10; // space preserved after restart,\n                                  // set to -1 to default to m/4+1\n  lanc_props.deflate = false; // don't deflate locked eigenvalues\n  lanc_props.generator = &generator; // passed by reference\n  lanc_props.verbose = false;\n\n  // Get the smallest eigenvalues\n  ThickRestartComplexLanczos<double,std::less<double>> lanczos(&lap_fcn, lanc_props);\n\n  //////////////\n  // Compute! //\n  //////////////\n\n  lanczos.compute();\n\n  // Get number of converged eigenvalues\n  int n_converged = lanczos.num_converged();\n\n  // Get the eigenvalues\n  double* eigenvalues = new double[n_converged];\n  lanczos.ritzvalues(eigenvalues);\n\n  // Print the Ritz values\n  std::cout << \"The \" << n_converged << \" converged eigenvalues are:\\n\";\n  for (int i = 0; i < n_converged; i++) {\n    std::cout << eigenvalues[i] << \"\\n\";\n  }\n\n  // Get converged eigenvectors\n  complex<double>** eigenvectors = new complex<double>*[n_converged];\n  for (int i = 0; i < n_converged; i++) {\n    eigenvectors[i] = allocate_vector<complex<double>>(volume);\n  }\n\n  // Get the Ritz vectors\n  lanczos.ritzvectors(eigenvectors);\n\n  ///////////////////////////////////////////\n  // Do the polynomial accelerated version //\n  ///////////////////////////////////////////\n\n  std::cout << \"\\nPolynomial Accleration\\n\";\n\n  // Get approximate bounds from a small Lanczos\n  const int m_mini = 6;\n  SimpleComplexLanczos<double> simp_lanczos(&lap_fcn, m_mini, generator);\n  simp_lanczos.compute();\n  double approx_eigs[m_mini];\n  simp_lanczos.ritzvalues((double*)approx_eigs);\n  // print the approximate eigenvalues\n  std::cout << \"The \" << m_mini << \" Ritz values are:\\n\";\n  for (int i = 0; i < m_mini; i++) {\n    std::cout << approx_eigs[i] << \"\\n\";\n  }\n  std::cout << \"\\n\";\n  double approx_min = approx_eigs[0]; // get the approximate min\n  double approx_max = approx_eigs[m_mini-1]*1.2; // and overshoot the max\n  std::cout << \"The linear op window is \" << approx_min << \" to \" << approx_max << \"\\n\\n\";\n\n  // Make a linear interpolation of the laplace op.\n  LinearMapToUnit<complex<double>,double> linear_lap(&lap_fcn, approx_min, approx_max);\n\n  // And make the 20th order poly accelerated form\n  OneOverOnePlusX<complex<double> > poly_accel(&linear_lap, 50);\n\n\n  // Fill a struct\n  TRCLStruct poly_lanc_props;\n  poly_lanc_props.n_ev = 10; // get 10 eigenvalues\n  poly_lanc_props.m = 30; // subspace size of 20\n  poly_lanc_props.tol = 1e-10; // lock at a tolerance of 1e-8\n  poly_lanc_props.max_restarts = 20; // maximum of 10 restarts\n  poly_lanc_props.preserved_space = 10; // space preserved after restart,\n                                  // set to -1 to default to m/4+1\n  poly_lanc_props.deflate = true; // deflate locked eigenvalues\n  poly_lanc_props.generator = &generator; // passed by reference\n  poly_lanc_props.verbose = false;\n\n  // Get the largest eigenvalues, since we're poly acceling\n  ThickRestartComplexLanczos<double,std::greater<double>> poly_lanczos(&poly_accel, poly_lanc_props);\n  poly_lanczos.compute();\n  int n_poly_converged = poly_lanczos.num_converged();\n  std::cout << n_poly_converged << \"\\n\";\n\n  // Get the poly eigenvalues\n  double* poly_eigenvalues = new double[n_poly_converged];\n  poly_lanczos.ritzvalues(poly_eigenvalues);\n\n  // Print the Ritz values\n  std::cout << \"The \" << n_poly_converged << \" converged eigenvalues are:\\n\";\n  for (int i = 0; i < n_poly_converged; i++) {\n    std::cout << poly_eigenvalues[i] << \"\\n\";\n  }\n\n  // Get the poly eigenvectors\n  complex<double>** poly_eigenvectors = new complex<double>*[n_poly_converged];\n  for (int i = 0; i < n_poly_converged; i++) {\n    poly_eigenvectors[i] = allocate_vector<complex<double>>(volume);\n  }\n\n  // Get the Ritz vectors\n  poly_lanczos.ritzvectors(poly_eigenvectors);\n\n  // Get eigenvalues of original system\n  complex<double>* intermediate = allocate_vector<complex<double>>(volume);\n  std::cout << \"\\nThe \" << n_poly_converged << \" reconstructed eigenvalues are:\\n\";\n  for (int i = 0; i < n_poly_converged; i++) {\n    zero_vector(intermediate, volume);\n    lap_fcn(intermediate, poly_eigenvectors[i]);\n    double rec_eval = re_dot(poly_eigenvectors[i], intermediate, volume);\n    std::cout << rec_eval << \"\\n\";\n  }\n  \n\n  //////////////////////////\n  // Get all eigenvalues! //\n  //////////////////////////\n\n\n  if (volume <= 256) {\n\n    // Let's get the eigenvalues of the full operator!\n\n    // Allocate a sufficiently gigantic matrix.\n    cMatrix mat_cplx = cMatrix::Zero(volume, volume);\n\n    // Form matrix elements. This is where it's important that\n    // dMatrix and cMatrix are column major.\n    // I should probably make this safer by using a \"Map\".\n    for (int i = 0; i < volume; i++)\n    {\n      // Set a point on the rhs for a matrix element.\n      zero_vector(rhs_cplx, volume);\n      rhs_cplx[i] = 1.0;\n\n      // Where we put the result of the matrix element.\n      complex<double>* mptr = &(mat_cplx(i*volume));\n\n      square_laplacian_gauged(mptr, rhs_cplx, &lapstr_gauged);\n    }\n\n    // Get the eigenvalues.\n    SelfAdjointEigenSolver<cMatrix> eigsolve_cplx(volume);\n    eigsolve_cplx.compute(mat_cplx);\n\n    std::cout << \"The eigenvalues are:\\n\" << eigsolve_cplx.eigenvalues() << \"\\n\";\n\n    ////////////////////////////////\n    // COMPARE LOWEST EIGENVECTOR //\n    ////////////////////////////////\n\n    std::cout << \"Compare results:\\n\\n\";\n    std::cout << \"Lanczos Exact Ratio\\n\";\n    for (int i = 0; i < volume; i++) {\n      std::cout << eigenvectors[0][i] << \" \" << eigsolve_cplx.eigenvectors().col(0)(i)\n                << \" \" << eigenvectors[0][i]/eigsolve_cplx.eigenvectors().col(0)(i) << \"\\n\";\n    }\n  }\n\n  //////////////\n  // CLEAN UP //\n  //////////////\n\n  delete[] eigenvalues;\n  delete[] poly_eigenvalues;\n  for (int i = 0; i < n_converged; i++) {\n    deallocate_vector(&eigenvectors[i]);\n  }\n  delete[] eigenvectors;\n  for (int i = 0; i < n_poly_converged; i++) {\n    deallocate_vector(&poly_eigenvectors[i]);\n  }\n  delete[] poly_eigenvectors;\n  deallocate_vector(&intermediate);\n\n  deallocate_vector(&rhs_cplx);\n  deallocate_vector(&gauge_links);\n  return 0;\n}\n\n\n", "meta": {"hexsha": "c7d8b1f1b293833a569eb1f0d4de6bc51cdf43e6", "size": 8962, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/lanczos_tests/lanczos_thick_deflate/lanczos.cpp", "max_stars_repo_name": "weinbe2/quantum-linalg", "max_stars_repo_head_hexsha": "ce852dc459c8a5010f777f219c0dc6623ec918e0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/lanczos_tests/lanczos_thick_deflate/lanczos.cpp", "max_issues_repo_name": "weinbe2/quantum-linalg", "max_issues_repo_head_hexsha": "ce852dc459c8a5010f777f219c0dc6623ec918e0", "max_issues_repo_licenses": ["MIT"], "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/lanczos_tests/lanczos_thick_deflate/lanczos.cpp", "max_forks_repo_name": "weinbe2/quantum-linalg", "max_forks_repo_head_hexsha": "ce852dc459c8a5010f777f219c0dc6623ec918e0", "max_forks_repo_licenses": ["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.4456140351, "max_line_length": 101, "alphanum_fraction": 0.6420441866, "num_tokens": 2465, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.496960653402575}}
{"text": "#include \"AnalysisGraph.hpp\"\n#include <range/v3/all.hpp>\n#include <unsupported/Eigen/MatrixFunctions>\n#include <boost/range/adaptors.hpp>\n#include <tqdm.hpp>\n\nusing namespace std;\nusing Eigen::VectorXd, Eigen::MatrixXd;\nusing fmt::print, fmt::format;\nnamespace rs = ranges;\nusing boost::adaptors::transformed;\n\nusing fmt::print;\n/*\n ============================================================================\n Private: Prediction\n ============================================================================\n*/\n\nvoid AnalysisGraph::generate_latent_state_sequences(\n    double initial_prediction_step) {\n\n  // Allocate memory for prediction_latent_state_sequences\n  this->predicted_latent_state_sequences.clear();\n  this->predicted_latent_state_sequences = vector<vector<VectorXd>>(\n      this->res,\n      vector<VectorXd>(this->pred_timesteps, VectorXd(this->num_vertices() * 2)));\n\n  cout << \"\\nPredicting for \" << this->pred_timesteps << \" time steps...\" << endl;\n  for (int samp : tq::trange(this->res)) {\n      // The sampled transition matrices would be either of matrix exponential\n      // (continuous) version or discretized version depending on whether the\n      // matrix exponential (continuous) version or the discretized transition\n      // matrix version had been used to train the model. This allows us to\n      // make the prediction routine common for both the versions, except for\n      // the exponentiation of the matrix exponential (continuous) transition\n      // matrices.\n      MatrixXd A;\n\n      this->generate_head_node_latent_sequences(\n          samp, initial_prediction_step + this->pred_timesteps);\n\n      if (this->continuous) {\n//          // Here A = Ac = this->transition_matrix_collection[samp] (continuous)\n//\n//          // Evolving the system till the initial_prediction_step\n//          A = (this->transition_matrix_collection[samp] *\n//                   initial_prediction_step).exp();\n//\n//          this->predicted_latent_state_sequences[samp][0] =\n//                               A * this->initial_latent_state_collection[samp];\n//\n//          // After jumping to time step ips - 1, we take one step of length \u0394t\n//          // at a time.\n//          // So compute the transition matrix for a single step.\n//          // Computing the matrix exponential for a \u0394t time step.\n//          // By default we are using \u0394t = 1\n//          // A = e^{Ac * \u0394t)\n//          A = (this->transition_matrix_collection[samp] * this->delta_t).exp();\n\n          /////////////////\n          A = this->transition_matrix_collection[samp].exp();\n\n          // Evolving the system till the initial_prediction_step\n          this->current_latent_state = this->initial_latent_state_collection[samp];\n\n          for (int ts = 0; ts < initial_prediction_step; ts++) {\n            this->update_latent_state_with_generated_derivatives(ts, ts + 1);\n\n            // Set derivatives for frozen nodes\n            for (const auto & [ v, deriv_func ] : this->external_concepts) {\n              const Indicator& ind = this->graph[v].indicators[0];\n              this->current_latent_state[2 * v + 1] = deriv_func(ts, ind.mean);\n            }\n\n            this->current_latent_state = A * this->current_latent_state;\n          }\n          //this->update_latent_state_with_generated_derivatives(0, initial_prediction_step);\n          //this->current_latent_state = A * this->current_latent_state;\n\n          this->update_latent_state_with_generated_derivatives(\n              initial_prediction_step, initial_prediction_step + 1);\n\n          // Set derivatives for frozen nodes\n          for (const auto & [ v, deriv_func ] : this->external_concepts) {\n            const Indicator& ind = this->graph[v].indicators[0];\n            this->current_latent_state[2 * v + 1] =\n                deriv_func(initial_prediction_step, ind.mean);\n          }\n\n          this->predicted_latent_state_sequences[samp][0] = this->current_latent_state;\n          /////////////////\n      } else {\n          // Here A = Ad = this->transition_matrix_collection[samp] (discrete)\n          // This is the discrete transition matrix to take a single step of\n          // length \u0394t\n          A = this->transition_matrix_collection[samp];\n\n          // Evolving the system till the initial_prediction_step\n          this->current_latent_state = this->initial_latent_state_collection[samp];\n\n          for (int ts = 0; ts < initial_prediction_step; ts++) {\n            this->update_latent_state_with_generated_derivatives(ts, ts + 1);\n\n            // Set derivatives for frozen nodes\n            for (const auto & [ v, deriv_func ] : this->external_concepts) {\n              const Indicator& ind = this->graph[v].indicators[0];\n              this->current_latent_state[2 * v + 1] = deriv_func(ts, ind.mean);\n            }\n\n            this->current_latent_state = A * this->current_latent_state;\n          }\n\n          this->update_latent_state_with_generated_derivatives(\n              initial_prediction_step, initial_prediction_step + 1);\n\n          // Set derivatives for frozen nodes\n          for (const auto & [ v, deriv_func ] : this->external_concepts) {\n            const Indicator& ind = this->graph[v].indicators[0];\n            this->current_latent_state[2 * v + 1] =\n                                  deriv_func(initial_prediction_step, ind.mean);\n          }\n\n          this->predicted_latent_state_sequences[samp][0] = this->current_latent_state;\n      }\n\n      // Clear out perpetual constraints residual from previous sample\n      this->perpetual_constraints.clear();\n\n      if (this->clamp_at_derivative) {\n          // To clamp a latent state value to x_c at prediction step 1 via\n          // clamping the derivative, we have to perturb the derivative at\n          // prediction step 0, before evolving it to prediction time step 1.\n          // So we have to look one time step ahead whether we have to clamp\n          // at 1.\n          //\n          if (delphi::utils::in(this->one_off_constraints, 1)) {\n              this->perturb_predicted_latent_state_at(1, samp);\n          }\n      }\n\n      // Since we used ts = 0 for the initial_prediction_step - 1, this loop is\n      // one ahead of the prediction time steps. That is, index 1 in the\n      // prediction data structures is the 0th index for the requested\n      // prediction sequence. Hence, when we are at time step ts, we should\n      // check whether there are any constconstraints\n        // time step index is 1\n      for (int ts = 1; ts < this->pred_timesteps; ts++) {\n          // When continuous: The standard matrix exponential equation is,\n          //                        s_{t+\u0394t} = e^{Ac * \u0394t } * s_t\n          //                  Since vector indices are integral values, and in\n          //                  the implementation s is the vector, to index into\n          //                  the vector we uses consecutive integers. Thus in\n          //                  the implementation, the matrix exponential\n          //                  equation becomes,\n          //                      s_{t+1} = e^{Ac * \u0394t } * s_t\n          //                  What this equation says is that although vector\n          //                  indices advance by 1, the duration between two\n          //                  predictions stored in two adjacent vector cells\n          //                  need not be 1. The time duration is actually \u0394t.\n          //                  The actual line of code represents,\n          //                        s_t = e^{Ac * \u0394t } * s_{t-1}\n          // When discrete  : s_t = Ad * s_{t-1}\n          this->current_latent_state = A * this->predicted_latent_state_sequences[samp][ts - 1];\n          this->update_latent_state_with_generated_derivatives(\n              initial_prediction_step + ts, initial_prediction_step + ts + 1);\n          this->predicted_latent_state_sequences[samp][ts] = this->current_latent_state;\n\n          // Set derivatives for frozen nodes\n          for (const auto & [ v, deriv_func ] : this->external_concepts) {\n            const Indicator& ind = this->graph[v].indicators[0];\n            this->predicted_latent_state_sequences[samp][ts][2 * v + 1] =\n                            deriv_func(initial_prediction_step + ts, ind.mean);\n          }\n\n          if (this->clamp_at_derivative ) {\n              if (ts == this->rest_derivative_clamp_ts) {\n                  // We have perturbed the derivative at ts - 1. If we do not\n                  // take any action, that clamped derivative will be in effect\n                  // until another clamping or end of prediction. This is where\n                  // we take the necessary actions.\n\n                  if (is_one_off_constraints) {\n                      // We should revert the derivative to its original value\n                      // at this time step so that clamping does not affect\n                      // time step ts + 1.\n                      for (auto constraint : this->one_off_constraints.at(ts)) {\n                          int node_id = constraint.first;\n\n                          this->predicted_latent_state_sequences[samp][ts]\n                              (2 * node_id + 1) =\n                              this->initial_latent_state_collection[samp]\n                              (2 * node_id + 1);\n                  }\n                  } else {\n                      for (auto [node_id, value]: this->one_off_constraints.at(ts)) {\n                          this->predicted_latent_state_sequences[samp][ts]\n                                                        (2 * node_id + 1) = 0;\n                      }\n                  }\n              }\n\n              // To clamp a latent state value to x_c at prediction step ts + 1\n              // via clamping the derivative, we have to perturb the derivative\n              // at prediction step ts, before evolving it to prediction time\n              // step ts + 1. So we have to look one time step ahead whether we\n              // have to clamp at ts + 1 and clamp the derivative now.\n              //\n              if (delphi::utils::in(this->one_off_constraints, ts + 1) ||\n                      !this->perpetual_constraints.empty()) {\n                  this->perturb_predicted_latent_state_at(ts + 1, samp);\n              }\n          } else {\n              // Apply constraints to latent state if any\n              // Logic of this condition:\n              //    Initially perpetual_constraints = \u2205\n              //\n              //    one_off_constraints.at(ts) = \u2205 => Unconstrained \u2200 ts\n              //\n              //    one_off_constraints.at(ts) \u2021 \u2205\n              //        => \u2203 some constraints (But we do not know what kind)\n              //        => Perturb latent state\n              //           Call perturb_predicted_latent_state_at()\n              //           one_off_constraints == true\n              //                => We are applying One-off constraints\n              //           one_off_constraints == false\n              //                => We are applying perpetual constraints\n              //                => We add constraints to perpetual_constraints\n              //                => perpetual_constraints \u2021 \u2205\n              //                => The if condition is true \u2200 subsequent time steps\n              //                   after ts (the first time step s.t.\n              //                   one_off_constraints.at(ts) \u2021 \u2205\n              //                => Constraints are perpetual\n              //\n              if (delphi::utils::in(this->one_off_constraints, ts) ||\n                      !this->perpetual_constraints.empty()) {\n                  this->perturb_predicted_latent_state_at(ts, samp);\n              }\n          }\n      }\n  }\n}\n\n/*\n * Applying constraints (interventions) to latent states\n * Check the data structure definition to get more descriptions\n *\n * Clamping at time step ts for value v\n * Two methods work in tandem to achieve this. Let us label them as follows:\n *      glss  : generate_latent_state_sequences()\n *      ppls@ : perturb_predicted_latent_state_at()\n *                                 \u250d\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2511\n *                                 \u2502           How          \u2503\n *                                 \u251d\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2533\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u252b\n *                                 \u2502 One-off  \u2503  Perpetual  \u2503\n * \u2501\u2501\u2501\u2501\u2501\u2501\u2533\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u252f\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u253f\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u253b\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u252b\n *       \u2503            \u2502 Clamp at   \u2502           v - x_{ts-1} \u2503\n *       \u2503            \u2502 (by ppls@) \u2502   ts-1 to \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 \u2503\n *       \u2503            \u2502            \u2502               \u0394t       \u2503\n *       \u2503 Derivative \u251c\u2508\u2508\u2508\u2508\u2508\u2508\u2508\u2508\u2508\u2508\u2508\u2508\u253c\u2508\u2508\u2508\u2508\u2508\u2508\u2508\u2508\u2508\u2508\u2530\u2508\u2508\u2508\u2508\u2508\u2508\u2508\u2508\u2508\u2508\u2508\u2508\u2508\u2528\n * Where \u2503            \u2502 Reset at   \u2502 ts to \u1e8b\u2080 \u2503 ts to 0     \u2503\n *       \u2503            \u2502 (by glss)  \u2502 from S\u2080  \u2503             \u2503\n *       \u2523\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u253f\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u253f\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u254b\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u252b\n *       \u2503 Value      \u2502 Clamp at   \u2502 ts to v  \u2503 \u2200 t\u2265ts to v \u2503\n *       \u2503            \u2502 (by ppls@) \u2502          \u2503             \u2503\n * \u2501\u2501\u2501\u2501\u2501\u2501\u253b\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2537\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2537\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u253b\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u251b\n */\nvoid AnalysisGraph::perturb_predicted_latent_state_at(int timestep, int sample_number) {\n    // Let vertices of the CAG be v = 0, 1, 2, 3, ...\n    // Then,\n    //    indices 2*v keeps track of the state of each variable v\n    //    indices 2*v+1 keeps track of the state of \u2202v/\u2202t\n\n    if (this->clamp_at_derivative) {\n        for (auto [node_id, value]: this->one_off_constraints.at(timestep)) {\n            // To clamp the latent state value to x_c at time step t via\n            // clamping the derivative, we have to clamp the derivative\n            // appropriately at time step t-1.\n            // Example:\n            //      Say we want to clamp the latent state at t=6 to value\n            //      x_c (i.e. we want x\u2086 = x_c. So we have to set the\n            //      derivative at t=6-1=5, \u1e8b\u2085, as follows:\n            //                  x_c - x\u2085\n            //             \u1e8b\u2085 = --------- ........... (1)\n            //                     \u0394t\n            //             x\u2086 = x\u2085 + (\u1e8b\u2085 \u00d7 \u0394t)\n            //                = x_c\n            //      Thus clamping \u1e8b\u2085 (at t = 5) as described in (1) gives\n            //      us the desired clamping at t = 5 + 1 = 6\n            double clamped_derivative = (value -\n                    this->predicted_latent_state_sequences[sample_number]\n                    [timestep - 1](2 * node_id)) / this->delta_t;\n\n            this->predicted_latent_state_sequences[sample_number]\n                [timestep - 1](2 * node_id + 1) = clamped_derivative;\n        }\n\n        // Clamping the derivative at t-1 changes the value at t.\n        // According to our model, derivatives never chance. So if we\n        // do not revert it, clamped derivative stays till another\n        // clamping or the end of prediction. Since this is a one-off\n        // clamping, we have to return the derivative back to its\n        // original value at time step t, before we use it to evolve\n        // time step t + 1. Thus we remember the time step at which we\n        // have to perform this.\n        this->rest_derivative_clamp_ts = timestep;\n\n        return;\n    }\n\n    if (this->is_one_off_constraints) {\n\n        for (auto [node_id, value]: this->one_off_constraints.at(timestep)) {\n            this->predicted_latent_state_sequences[sample_number][timestep](2 * node_id) = value;\n        }\n    } else { // Perpetual constraints\n        if (delphi::utils::in(this->one_off_constraints, timestep)) {\n            // Update any previous perpetual constraints\n            for (auto [node_id, value]: this->one_off_constraints.at(timestep)) {\n\n                this->perpetual_constraints[node_id] = value;\n            }\n        }\n\n        // Apply perpetual constraints\n        for (auto [node_id, value]: this->perpetual_constraints) {\n\n            this->predicted_latent_state_sequences[sample_number][timestep](2 * node_id) = value;\n        }\n    }\n}\n\nvoid AnalysisGraph::generate_observed_state_sequences() {\n  using rs::to, rs::views::transform;\n\n  // Allocate memory for observed_state_sequences\n  this->predicted_observed_state_sequences.clear();\n  this->predicted_observed_state_sequences =\n      vector<PredictedObservedStateSequence>(\n          this->res,\n          PredictedObservedStateSequence(this->pred_timesteps,\n                                         vector<vector<double>>()));\n\n  for (int samp = 0; samp < this->res; samp++) {\n    vector<VectorXd>& sample = this->predicted_latent_state_sequences[samp];\n\n    this->predicted_observed_state_sequences[samp] =\n        sample | transform([this](VectorXd latent_state) {\n          return this->generate_observed_state(latent_state);\n        }) |\n        to<vector>();\n  }\n}\n\nvector<vector<double>>\nAnalysisGraph::generate_observed_state(VectorXd latent_state) {\n  using rs::to, rs::views::transform;\n\n  int num_verts = this->num_vertices();\n\n  vector<vector<double>> observed_state(num_verts);\n\n  for (int v = 0; v < num_verts; v++) {\n    vector<Indicator>& indicators = (*this)[v].indicators;\n\n    observed_state[v] = vector<double>(indicators.size());\n\n    observed_state[v] = indicators | transform([&](Indicator ind) {\n                          return ind.mean * latent_state[2 * v];\n                        }) |\n                        to<vector>();\n  }\n\n  return observed_state;\n}\n\nFormattedPredictionResult AnalysisGraph::format_prediction_result() {\n\n  // NOTE: To facilitate clamping derivatives, we start prediction one time\n  //       step before the requested prediction start time. We are omitting\n  //       that additional time step from the results returned to the user.\n  this->pred_timesteps--;\n\n  // Access\n  // [ sample ][ time_step ][ vertex_name ][ indicator_name ]\n  auto result = FormattedPredictionResult(\n      this->res,\n      vector<unordered_map<string, unordered_map<string, double>>>(\n          this->pred_timesteps));\n\n  for (int samp = 0; samp < this->res; samp++) {\n    // NOTE: To facilitate clamping derivatives, we start prediction one time\n    //       step before the requested prediction start time. We are omitting\n    //       that additional time step from the results returned to the user.\n    for (int ts = 1; ts <= this->pred_timesteps; ts++) {\n      for (auto [vert_name, vert_id] : this->name_to_vertex) {\n        for (auto [ind_name, ind_id] : (*this)[vert_id].nameToIndexMap) {\n          result[samp][ts - 1][vert_name][ind_name] =\n              this->predicted_observed_state_sequences[samp][ts][vert_id]\n                                                      [ind_id];\n        }\n      }\n    }\n  }\n\n  return result;\n}\n\nvoid AnalysisGraph::run_model(int start_year,\n                              int start_month,\n                              int end_year,\n                              int end_month) {\n  if (!this->trained) {\n    print(\"Passed untrained Causal Analysis Graph (CAG) Model. \\n\",\n          \"Try calling <CAG>.train_model(...) first!\");\n    throw \"Model not yet trained\";\n  }\n\n  // Check for sensible prediction time step ranges.\n  // NOTE: To facilitate clamping derivatives, we start prediction one time\n  //       step before the requested prediction start time. Therefor, the\n  //       possible valid earliest prediction time step is one time step after\n  //       the training start time.\n  if (start_year < this->training_range.first.first ||\n      (start_year == this->training_range.first.first &&\n       start_month <= this->training_range.first.second)) {\n    print(\"The initial prediction date can't be before the \"\n         \"initial training date. Defaulting initial prediction date \"\n         \"to initial training date + 1 month.\");\n    start_month = this->training_range.first.second + 1;\n    if (start_month == 13) {\n        start_year = this->training_range.first.first + 1;\n        start_month = 1;\n    } else {\n        start_year = this->training_range.first.first;\n    }\n  }\n\n  /*\n   *              total_timesteps\n   *   ____________________________________________\n   *  |                                            |\n   *  v                                            v\n   * start training                          end prediction\n   *  |--------------------------------------------|\n   *  :           |--------------------------------|\n   *  :         start prediction                   :\n   *  ^           ^                                ^\n   *  |___________|________________________________|\n   *      diff              pred_timesteps\n   */\n  int total_timesteps =\n      this->calculate_num_timesteps(this->training_range.first.first,\n                                    this->training_range.first.second,\n                                    end_year,\n                                    end_month);\n\n  this->pred_timesteps = this->calculate_num_timesteps(\n      start_year, start_month, end_year, end_month);\n\n  int pred_init_timestep = total_timesteps - pred_timesteps;\n\n  int year = start_year;\n  int month = start_month;\n\n  this->pred_range.clear();\n  this->pred_range = vector<string>(this->pred_timesteps);\n\n  for (int t = 0; t < this->pred_timesteps; t++) {\n    this->pred_range[t] = to_string(year) + \"-\" + to_string(month);\n\n    if (month == 12) {\n      year++;\n      month = 1;\n    }\n    else {\n      month++;\n    }\n  }\n\n  // NOTE: To facilitate clamping derivatives, we start prediction one time\n  //       step before the requested prediction start time. When we are\n  //       returning results, we have to remove the predictions at the 0th\n  //       index of each predicted observed state sequence.\n  //       Adding that additional time step.\n  // t     = Requested prediction start time step\n  //       = pred_init_timestep\n  // t - 1 = Prediction start time step\n  //       = pred_init_timestep - 1\n  pred_init_timestep--;\n  this->pred_timesteps++;\n\n  this->generate_latent_state_sequences(pred_init_timestep);\n  this->generate_observed_state_sequences();\n}\n\nvoid AnalysisGraph::add_constraint(int step, string concept_name, string indicator_name,\n                                                double indicator_clamp_value) {\n    // When constraining latent state derivatives, to reach the\n    // prescribed value for an observation at projection step t, we have\n    // to  clamp the derivative at projection step t-1 appropriately.\n    // Therefor, to constrain at projection step 0, we have to clamp the\n    // derivative at projection step -1.\n    // To facilitate this, we start projection one time step before the\n    // requested projection start time.\n    // To correct for that and make internal vector indexing easier,\n    // nicer and less error prone, we shift all the constraints by one\n    // step up.\n    step++;\n\n    // Check whether this concept is in the CAG\n    if (!delphi::utils::in(this->name_to_vertex, concept_name)) {\n        print(\"Concept \\\"{0}\\\" not in CAG!\\n\", concept_name);\n        return;\n    }\n\n    int concept_id = this->name_to_vertex.at(concept_name);\n    Node& n = (*this)[concept_id];\n\n    if (n.indicators.size() <= 0) {\n        // This concept does not have any indicators attached.\n        print(\"Concept \\\"{0}\\\" does not have any indicators attached!\\n\", concept_name);\n        print(\"\\tCannot set constraint\\n\");\n        return;\n    }\n\n    // If the indicator name is empty we clamp the first indicator attached to\n    // this concept\n    int ind_id = 0;\n\n    if (!indicator_name.empty()) {\n        if (!delphi::utils::in(this->indicators_in_CAG, indicator_name)) {\n            print(\"Indicator \\\"{0}\\\" is not in CAG!\\n\", indicator_name);\n            return;\n        }\n\n        if (!delphi::utils::in(n.nameToIndexMap, indicator_name)) {\n            print(\"Indicator \\\"{0}\\\" is not attached to {1} in CAG!\\n\",\n                    indicator_name,\n                    concept_name);\n            return;\n        }\n\n        ind_id = n.nameToIndexMap.at(indicator_name);\n    }\n\n    Indicator& ind = n.indicators[ind_id];\n\n    // We have to clamp the latent state value corresponding to this\n    // indicator such that the probability where the emission Gaussian\n    // emitting the requested indicator value is the highest. For a\n    // Gaussian emission function, the highest probable value is its\n    // mean. So we have to set:\n    //      \u03bc = ind_value\n    //      latent_clamp_value * scaling_factor = ind_value\n    //      latent_clamp_value = ind_value / scaling_factor\n    // NOTE: In our code we incorrectly call scaling_factor as\n    //       indicator mean. To avoid confusion here, I am using the\n    //       correct terminology.\n    //       (Gosh, when we have incorrect terminology and we know it\n    //       and we have not fixed it, I have to type a lot of\n    //       comments)\n    double latent_clamp_value = indicator_clamp_value / ind.get_mean();\n\n    if (this->head_nodes.find(concept_id) == this->head_nodes.end()) {\n      if (!delphi::utils::in(this->one_off_constraints, step)) {\n        this->one_off_constraints[step] = vector<pair<int, double>>();\n      }\n\n      this->one_off_constraints[step].push_back(\n          make_pair(concept_id, latent_clamp_value));\n    } else {\n      step += this->pred_start_timestep;\n      if (!delphi::utils::in(this->head_node_one_off_constraints, step)) {\n        this->head_node_one_off_constraints[step] = vector<pair<int, double>>();\n      }\n\n      this->head_node_one_off_constraints[step].push_back(\n          make_pair(concept_id, latent_clamp_value));\n    }\n}\n\n/*\n ============================================================================\n Public: Prediction\n ============================================================================\n*/\n\nPrediction AnalysisGraph::generate_prediction(int start_year,\n                                              int start_month,\n                                              int end_year,\n                                              int end_month,\n                                              ConstraintSchedule constraints,\n                                              bool one_off,\n                                              bool clamp_deri) {\n  this->is_one_off_constraints = one_off;\n  this->clamp_at_derivative = clamp_deri;\n  this->one_off_constraints.clear();\n  this->head_node_one_off_constraints.clear();\n\n  for (auto [step, const_vec] : constraints) {\n      for (auto constraint : const_vec) {\n          string concept_name = get<0>(constraint);\n          string indicator_name = get<1>(constraint);\n          double value = get<2>(constraint);\n\n          this->add_constraint(step, concept_name, indicator_name, value);\n      }\n  }\n\n  this->run_model(start_year, start_month, end_year, end_month);\n\n  return make_tuple(\n      this->training_range, this->pred_range, this->format_prediction_result());\n}\n\nvoid AnalysisGraph::generate_prediction(int pred_start_timestep,\n                                        int pred_timesteps,\n                                        ConstraintSchedule constraints,\n                                        bool one_off,\n                                        bool clamp_deri) {\n  this->is_one_off_constraints = one_off;\n  this->clamp_at_derivative = clamp_deri;\n  this->one_off_constraints.clear();\n  this->head_node_one_off_constraints.clear();\n\n  this->pred_start_timestep = pred_start_timestep - 1;\n  this->pred_timesteps = pred_timesteps + 1;\n\n  for (auto [step, const_vec] : constraints) {\n    for (auto constraint : const_vec) {\n      string concept_name = get<0>(constraint);\n      string indicator_name = get<1>(constraint);\n      double value = get<2>(constraint);\n\n      this->add_constraint(step, concept_name, indicator_name, value);\n    }\n  }\n\n  this->generate_latent_state_sequences(this->pred_start_timestep);\n  this->generate_observed_state_sequences();\n}\n\nvector<vector<double>> AnalysisGraph::prediction_to_array(string indicator) {\n  int vert_id = -1;\n  int ind_id = -1;\n\n  auto result =\n      vector<vector<double>>(this->res, vector<double>(this->pred_timesteps));\n\n  // Find the vertex id the indicator is attached to and\n  // the indicator id of it.\n  // TODO: We can make this more efficient by making indicators_in_CAG\n  // a map from indicator names to vertices they are attached to.\n  // This is just a quick and dirty implementation\n  for (auto [v_name, v_id] : this->name_to_vertex) {\n    for (auto [i_name, i_id] : (*this)[v_id].nameToIndexMap) {\n      if (indicator.compare(i_name) == 0) {\n        vert_id = v_id;\n        ind_id = i_id;\n        goto indicator_found;\n      }\n    }\n  }\n  // Program will reach here only if the indicator is not found\n  throw IndicatorNotFoundException(format(\n      \"AnalysisGraph::prediction_to_array - indicator \\\"{}\\\" not found!\\n\",\n      indicator));\n\nindicator_found:\n\n  for (int samp = 0; samp < this->res; samp++) {\n    for (int ts = 0; ts < this->pred_timesteps; ts++) {\n      result[samp][ts] =\n          this->predicted_observed_state_sequences[samp][ts][vert_id][ind_id];\n    }\n  }\n\n  return result;\n}\n", "meta": {"hexsha": "db37520756aa75761c00e023aace30dc045b2d96", "size": 28904, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/prediction.cpp", "max_stars_repo_name": "ml4ai/delphi", "max_stars_repo_head_hexsha": "9294d2d491f10c297c84f1cd5fdc9b55b6f866d9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2018-03-03T11:57:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-16T21:19:54.000Z", "max_issues_repo_path": "lib/prediction.cpp", "max_issues_repo_name": "ml4ai/delphi", "max_issues_repo_head_hexsha": "9294d2d491f10c297c84f1cd5fdc9b55b6f866d9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 385.0, "max_issues_repo_issues_event_min_datetime": "2018-02-21T16:52:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-17T07:44:56.000Z", "max_forks_repo_path": "lib/prediction.cpp", "max_forks_repo_name": "ml4ai/delphi", "max_forks_repo_head_hexsha": "9294d2d491f10c297c84f1cd5fdc9b55b6f866d9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 19.0, "max_forks_repo_forks_event_min_datetime": "2018-03-20T01:08:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-29T01:04:49.000Z", "avg_line_length": 42.4434654919, "max_line_length": 97, "alphanum_fraction": 0.5672917243, "num_tokens": 6517, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.49696064877856627}}
{"text": "//=====================================================\n// Copyright (C) 2008 Gael Guennebaud <g.gael@free.fr>\n//=====================================================\n//\n// This program is free software; you can redistribute it and/or\n// modify it under the terms of the GNU General Public License\n// as published by the Free Software Foundation; either version 2\n// of the License, or (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n// GNU General Public License for more details.\n// You should have received a copy of the GNU General Public License\n// along with this program; if not, write to the Free Software\n// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.\n//\n#ifndef MTL4_INTERFACE_HH\n#define MTL4_INTERFACE_HH\n\n#include <boost/numeric/mtl/mtl.hpp>\n#include <boost/numeric/mtl/operation/cholesky.hpp>\n#include <vector>\n\nusing namespace mtl;\n\ntemplate<class real>\nclass mtl4_interface {\n\npublic :\n\n  typedef real real_type ;\n\n  typedef std::vector<real>  stl_vector;\n  typedef std::vector<stl_vector > stl_matrix;\n\n  typedef mtl::dense2D<real, mtl::matrix::parameters<mtl::tag::col_major> > gene_matrix;\n  typedef mtl::dense_vector<real>  gene_vector;\n\n  static inline std::string name() { return \"mtl4\"; }\n\n  static void free_matrix(gene_matrix & A, int N){\n    return ;\n  }\n\n  static void free_vector(gene_vector & B){\n    return ;\n  }\n\n  static inline void matrix_from_stl(gene_matrix & A, stl_matrix & A_stl){\n    A.change_dim(A_stl[0].size(), A_stl.size());\n\n    for (int j=0; j<A_stl.size() ; j++){\n      for (int i=0; i<A_stl[j].size() ; i++){\n        A(i,j) = A_stl[j][i];\n      }\n    }\n  }\n\n  static inline void vector_from_stl(gene_vector & B, stl_vector & B_stl){\n    B.change_dim(B_stl.size());\n    for (int i=0; i<B_stl.size() ; i++){\n      B[i] = B_stl[i];\n    }\n  }\n\n  static inline void vector_to_stl(gene_vector & B, stl_vector & B_stl){\n    for (int i=0; i<B_stl.size() ; i++){\n      B_stl[i] = B[i];\n    }\n  }\n\n  static inline void matrix_to_stl(gene_matrix & A, stl_matrix & A_stl){\n    int N=A_stl.size();\n    for (int j=0;j<N;j++){\n      A_stl[j].resize(N);\n      for (int i=0;i<N;i++){\n        A_stl[j][i] = A(i,j);\n      }\n    }\n  }\n\n  static inline void matrix_matrix_product(const gene_matrix & A, const gene_matrix & B, gene_matrix & X, int N){\n    X = (A*B);\n//     morton_dense<double, doppled_64_row_mask> C(N,N);\n//     C = B;\n//     X = (A*C);\n  }\n\n  static inline void transposed_matrix_matrix_product(const gene_matrix & A, const gene_matrix & B, gene_matrix & X, int N){\n    X = (trans(A)*trans(B));\n  }\n\n  static inline void ata_product(const gene_matrix & A, gene_matrix & X, int N){\n    X = (trans(A)*A);\n  }\n\n  static inline void aat_product(const gene_matrix & A, gene_matrix & X, int N){\n    X = (A*trans(A));\n  }\n\n  static inline void matrix_vector_product(gene_matrix & A, gene_vector & B, gene_vector & X, int N){\n    X = (A*B);\n  }\n\n  static inline void atv_product(gene_matrix & A, gene_vector & B, gene_vector & X, int N){\n    X = (trans(A)*B);\n  }\n\n  static inline void axpy(const real coef, const gene_vector & X, gene_vector & Y, int N){\n    Y += coef * X;\n  }\n\n  static inline void axpby(real a, const gene_vector & X, real b, gene_vector & Y, int N){\n    Y = a*X + b*Y;\n  }\n\n  static inline void cholesky(const gene_matrix & X, gene_matrix & C, int N){\n    C = X;\n    recursive_cholesky(C);\n  }\n\n//   static inline void lu_decomp(const gene_matrix & X, gene_matrix & R, int N){\n//     R = X;\n//     std::vector<int> ipvt(N);\n//     lu_factor(R, ipvt);\n//   }\n\n  static inline void trisolve_lower(const gene_matrix & L, const gene_vector& B, gene_vector & X, int N){\n    X = lower_trisolve(L, B);\n  }\n\n  static inline void copy_matrix(const gene_matrix & source, gene_matrix & cible, int N){\n    cible = source;\n  }\n\n  static inline void copy_vector(const gene_vector & source, gene_vector & cible, int N){\n    cible = source;\n  }\n\n};\n\n#endif\n", "meta": {"hexsha": "c08b356459deb5e9ed2eeaca5daaf8f194bc29be", "size": 4119, "ext": "hh", "lang": "C++", "max_stars_repo_path": "volna_init/external/eigen2/bench/btl/libs/mtl4/mtl4_interface.hh", "max_stars_repo_name": "Devaraj-G/volna", "max_stars_repo_head_hexsha": "f4a25c19ae041c81442fc0461ea3ff2d7d8f95ba", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-07-08T23:53:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T11:55:28.000Z", "max_issues_repo_path": "volna_init/external/eigen2/bench/btl/libs/mtl4/mtl4_interface.hh", "max_issues_repo_name": "Devaraj-G/volna", "max_issues_repo_head_hexsha": "f4a25c19ae041c81442fc0461ea3ff2d7d8f95ba", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-12-02T17:31:28.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-02T17:31:28.000Z", "max_forks_repo_path": "volna_init/external/eigen2/bench/btl/libs/mtl4/mtl4_interface.hh", "max_forks_repo_name": "Devaraj-G/volna", "max_forks_repo_head_hexsha": "f4a25c19ae041c81442fc0461ea3ff2d7d8f95ba", "max_forks_repo_licenses": ["BSD-2-Clause"], "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": 28.6041666667, "max_line_length": 124, "alphanum_fraction": 0.6358339403, "num_tokens": 1177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.4968969207202411}}
{"text": "/*\r\n * Random.cpp\r\n *\r\n *  Created on: Feb 22, 2009\r\n *      Author: Tim Babb\r\n */\r\n\r\n#include <boost/static_assert.hpp>\r\n#include <assert.h>\r\n#include <algorithm>\r\n#include <limits>\r\n\r\n#include <geomc/random/Random.h>\r\n\r\n#define INT_SIGNBIT       (1 << std::numeric_limits<int>::digits)\r\n#define LONG_SIGNBIT      (1L << std::numeric_limits<long>::digits)\r\n#define LONG_LONG_SIGNBIT (1LL << std::numeric_limits<long long>::digits)\r\n\r\nusing namespace std;\r\nusing namespace geom;\r\n\r\ntypedef union fpbox {\r\n    uint32_t i;\r\n    float f;\r\n    uint64_t l;\r\n    double d;\r\n} FPBox;\r\n\r\n/**********************************\r\n * Structors                      *\r\n **********************************/\r\n\r\nRandom::Random():_bitpool(0),\r\n                 _bitsleft(0) {}\r\n\r\nRandom::~Random() {}\r\n\r\n/**********************************\r\n * Elementary Specializations     *\r\n **********************************/\r\n\r\nnamespace geom {\r\n\r\n    \r\ntemplate <> bool Random::rand<bool>() {\r\n    if (_bitsleft == 0) {\r\n        _bitpool = this->rand32();\r\n        _bitsleft = 32;\r\n    }\r\n    int bit = _bitpool & 1;\r\n    _bitpool = _bitpool >> 1;\r\n    _bitsleft--;\r\n    return bit;\r\n}\r\n\r\n\r\ntemplate <> unsigned int Random::rand<unsigned int>() {\r\n    unsigned int bits = 0;\r\n    const int chunks = (std::numeric_limits<unsigned int>::digits + 32 - 1) / 32; //ceiling(x/y) = (x + y - 1) / y\r\n#if UINT_MAX > (1LL << 32) - 1\r\n    for (int i = 0; i < chunks; i++) {\r\n        bits = (bits << 32) | rand32();\r\n    }\r\n#else\r\n    bits =(unsigned int)rand32();\r\n#endif\r\n    return bits;\r\n}\r\n\r\n\r\ntemplate <> int Random::rand<int>() {\r\n    return rand<unsigned int>(); //MSB is now a sign bit; covers the entire range of <int> type. might we want to change this? \r\n}\r\n\r\n\r\ntemplate <> unsigned long Random::rand<unsigned long>() {\r\n    unsigned long bits = 0;\r\n    const int chunks = (std::numeric_limits<unsigned long>::digits + 32 - 1) / 32; //ceiling(x/y) = (x + y - 1) / y\r\n#if ULONG_MAX > (1LL << 32) - 1\r\n    for (int i = 0; i < chunks; i++) {\r\n        bits = (bits << 32) | rand32();\r\n    }\r\n#else\r\n    bits = (unsigned long)rand32();\r\n#endif\r\n    return bits;\r\n}\r\n\r\n\r\ntemplate <> long Random::rand<long>() {\r\n    return rand<unsigned long>();\r\n}\r\n\r\n\r\ntemplate <> unsigned long long Random::rand<unsigned long long>() {\r\n    unsigned long long bits = 0;\r\n    const int chunks = (std::numeric_limits<unsigned long long>::digits + 32 - 1) / 32; //ceiling(x/y) = (x + y - 1) / y\r\n    for (int i = 0; i < chunks; i++) {\r\n        bits = (bits << 32) | rand32();\r\n    }\r\n    return bits;\r\n}\r\n\r\n\r\ntemplate <> long long Random::rand<long long>() {\r\n    return rand<unsigned long long>();\r\n}\r\n\r\n/* From the unpublished paper by Allen B. Downey.\r\n *\r\n * The conventional method of dividing a random number\r\n * by a constant excludes about 93% of the representable\r\n * floating point values between 0.0 and 1.0. Instead\r\n * we pick the bits of our number explicitly, but must\r\n * be careful to do so such that the distribution is\r\n * uniform. This method is fast, and makes efficient\r\n * use of our pseudorandom bits.\r\n *\r\n * The gist: Pick the mantissa, then pick the exponent\r\n * by iterative coin-flipping.\r\n */\r\n\r\n//TODO: use numeric_limits instead of hard-coded masks\r\n//see: boost::integer's int_t<bits>\r\n\r\ntemplate <> float Random::rand<float>() {\r\n    // without IEEE754, our bit twiddling will not work.\r\n    // generally this will only fail for \"exotic\" systems:\r\n    BOOST_STATIC_ASSERT(std::numeric_limits<float>::is_iec559);\r\n    \r\n    uint32_t mant;\r\n    int exp, hi_exp, lo_exp;\r\n    FPBox lo, hi, ans;\r\n\r\n    lo.f = 0.0;\r\n    hi.f = 1.0;\r\n\r\n    lo_exp = (lo.i >> 23) & 0xFF;\r\n    hi_exp = (hi.i >> 23) & 0xFF;\r\n\r\n    //not >= because exp is decremented at the end of the last loop\r\n    for (exp = hi_exp - 1; exp > lo_exp; exp--) {\r\n        if (rand<bool>()) break;\r\n    }\r\n\r\n    mant = (rand32() & 0xFFFFFE00) >> 9; //use the high quality bits\r\n\r\n    if (mant == 0 && rand<bool>()) exp++; //border values must not be skewed towards 1\r\n\r\n    ans.i = (((uint32_t)exp) << 23) | mant; //combine exp and mantissa\r\n    return ans.f;\r\n}\r\n\r\n\r\ntemplate <> double Random::rand<double>() {\r\n    // without IEEE754, our bit twiddling will not work.\r\n    // generally this will only fail for \"exotic\" systems:\r\n    BOOST_STATIC_ASSERT(std::numeric_limits<double>::is_iec559);\r\n    \r\n    int exp, hi_exp, lo_exp;\r\n    uint64_t mant;\r\n    FPBox lo, hi, ans;\r\n\r\n    lo.d = 0.0;\r\n    hi.d = 1.0;\r\n\r\n    lo_exp = (lo.l >> 52) & 0x7FF;\r\n    hi_exp = (hi.l >> 52) & 0x7FF;\r\n\r\n    //not >= because exp is decremented at the end of the last loop\r\n    for (exp = hi_exp - 1; exp > lo_exp; exp--) {\r\n        if (rand<bool>()) break;\r\n    }\r\n    \r\n    mant = ((uint64_t)rand32() << 32) | rand32();\r\n    mant = (mant & 0xFFFFFFFFFFFFF000LL) >> 12; //use the high quality bits\r\n\r\n    if (mant == 0 && rand<bool>()) exp++; //border values must not be skewed towards 1\r\n\r\n    ans.l = (((uint64_t)exp) << 52) | mant; //combine exp and mantissa\r\n    return ans.d;\r\n}\r\n\r\n/**********************************\r\n * Positive Range Specializations *\r\n **********************************/\r\n\r\n\r\ntemplate <> unsigned int Random::rand<unsigned int>(unsigned int hi) {\r\n    unsigned int bits, val, lo;\r\n\r\n    do {\r\n        bits = rand<unsigned int>();\r\n        val = bits % hi;\r\n        lo = bits - val;\r\n        //while this chunk wraps around to zero:\r\n        //i.e. lo sign bit is 1, end-of-chunk sign bit is 0\r\n    } while ( (lo & INT_SIGNBIT) & ~(lo+(hi-1)) );\r\n    return val;\r\n}\r\n\r\n\r\ntemplate <> int Random::rand<int>(int hi) {\r\n    if (hi < 0) {\r\n        return -rand<unsigned int>(-hi);\r\n    } else {\r\n        return rand<unsigned int>(hi);\r\n    }\r\n}\r\n\r\n\r\ntemplate <> unsigned long Random::rand<unsigned long>(unsigned long hi) {\r\n    unsigned long bits, val, lo;\r\n\r\n    do {\r\n        bits = rand<unsigned long>();\r\n        val = bits % hi;\r\n        lo = bits - val;\r\n        //while this chunk wraps around to zero:\r\n        //i.e. lo sign bit is 1, end-of-chunk sign bit is 0\r\n    } while ( (lo & LONG_SIGNBIT) & ~(lo+(hi-1)) );\r\n    return val;\r\n}\r\n\r\n\r\ntemplate <> long Random::rand<long>(long hi) {\r\n    if (hi < 0) {\r\n        return -rand<unsigned long>(-hi);\r\n    } else {\r\n        return rand<unsigned long>(hi);\r\n    }\r\n}\r\n\r\n\r\ntemplate <> unsigned long long Random::rand<unsigned long long>(unsigned long long hi) {\r\n    unsigned long long bits, val, lo;\r\n\r\n    do {\r\n        bits = rand<unsigned long long>();\r\n        val = bits % hi;\r\n        lo = bits - val;\r\n        //while this chunk wraps around to zero:\r\n        //i.e. lo sign bit is 1, end-of-chunk sign bit is 0\r\n    } while ( (lo & LONG_LONG_SIGNBIT) & ~(lo+(hi-1)) );\r\n    return val;\r\n}\r\n\r\n\r\ntemplate <> long long Random::rand<long long>(long long hi) {\r\n    if (hi < 0) {\r\n        return -rand<unsigned long long>(-hi);\r\n    } else {\r\n        return rand<unsigned long long>(hi);\r\n    }\r\n}\r\n\r\n\r\ntemplate <> float Random::rand<float>(float hi) {\r\n    return hi * rand<float>();\r\n}\r\n\r\n\r\ntemplate <> double Random::rand<double>(double hi) {\r\n    return hi * rand<double>();\r\n}\r\n\r\n/**********************************\r\n * Full Range Specializations     *\r\n **********************************/\r\n\r\n// todo: some of these will fail for ranges crossing zero where lo - hi is\r\n// greater than INT_MAX.\r\n\r\n\r\ntemplate <> int Random::rand<int>(int lo, int hi) {\r\n    int lo1 = min(hi,lo);\r\n    return rand<int>(max(hi,lo) - lo1) + lo1;\r\n}\r\n\r\n\r\ntemplate <> long long Random::rand<long long>(long long lo, long long hi) {\r\n    long long lo1 = min(hi,lo);\r\n    return rand<long long>(max(hi,lo) - lo1) + lo1;\r\n}\r\n\r\n\r\ntemplate <> float Random::rand<float>(float lo, float hi) {\r\n    return (hi-lo)*rand<float>() + lo;\r\n}\r\n\r\n\r\ntemplate <> double Random::rand<double>(double lo, double hi) {\r\n    return (hi-lo)*rand<double>() + lo;\r\n}\r\n\r\n/// @} //ingroup random\r\n\r\n} //end namespace geom\r\n", "meta": {"hexsha": "854c15e4795476607e29d30542ee9c74a941ea7b", "size": 7886, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "geomc/random/Random.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": "geomc/random/Random.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": "geomc/random/Random.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": 26.3745819398, "max_line_length": 128, "alphanum_fraction": 0.5526249049, "num_tokens": 2097, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059775, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.4968969160195765}}
{"text": "#include <iostream>\n#include <ojlibs/bignum.hpp>\n#include <gtest/gtest.h>\n#include <random>\n#include <boost/multiprecision/gmp.hpp>\n\nusing namespace boost::multiprecision;\nusing namespace ojlibs::bignum;\n\nstd::mt19937 gen;\nstd::uniform_int_distribution<uint32_t> dist(0, ~0u);\n\nbool SameNumber(const mpz_int &mpz, const nat &bnat) {\n    auto mpz_inner = mpz.backend().data();\n\n    size_t mpz_sz = mpz_size(mpz_inner);\n    size_t nat_sz = bnat.nlimb();\n\n    size_t gcd = std::min(sizeof(mp_limb_t), sizeof(WORD));\n\n    size_t mpz_k = sizeof(mp_limb_t) / gcd;\n    size_t nat_k = sizeof(WORD) / gcd;\n\n    size_t cnt = std::max(mpz_sz * mpz_k, nat_sz * nat_k);\n\n    const mp_limb_t *mpz_data = mpz_limbs_read(mpz_inner);\n    const WORD *nat_data = bnat.limbs.data();\n\n    uint64_t mask = (1ULL << (8 * gcd)) - 1;\n\n    for (int i = 0; i < cnt; ++i) {\n        uint64_t mpz_part = 0;\n        uint64_t nat_part = 0;\n        if (i / mpz_k < mpz_sz)\n            mpz_part = (mpz_data[i / mpz_k] >> (8 * gcd * (i % mpz_k))) & mask;\n        if (i / nat_k < nat_sz)\n            nat_part = (nat_data[i / nat_k] >> (8 * gcd * (i % nat_k))) & mask;\n        if (mpz_part != nat_part) return false;\n    }\n    return true;\n}\nbool SameNumber(WORD n, nat nn) {\n    if (n == 0) return nn.nlimb() == 0;\n    return nn.nlimb() == 1 && nn.limbs[0] == n;\n}\nstd::vector<WORD> random_limbs(int nlimb) {\n    std::vector<WORD> ret(nlimb);\n    for (int i = 0; i < nlimb; ++i)\n        ret[i] = dist(gen);\n\n    if (nlimb && ret[nlimb - 1] == 0) ret[nlimb - 1] = 1; // should be norm\n    return ret;\n}\nmpz_int limbs_to_mpz(std::vector<WORD> vec) {\n    mpz_int ret = 0;\n    for (int i = vec.size(); i-- > 0; ) {\n        ret = (ret << WBITS) + vec[i];\n    }\n    return ret;\n}\n\nTEST(SANITY, SameNumber) {\n    ASSERT_TRUE(SameNumber(mpz_int(34), nat(34u)));\n    ASSERT_FALSE(SameNumber(mpz_int(34), nat(35u)));\n\n    for (int tgroup = 0; tgroup < 100; ++tgroup) {\n        auto lb = random_limbs(10);\n        EXPECT_TRUE(SameNumber(limbs_to_mpz(lb), nat(lb)));\n    }\n}\n\nTEST(ADD, VW) {\n    for (int tgroup = 0; tgroup < 100; ++tgroup) {\n        uint32_t r = dist(gen);\n        mpz_int mp = r;\n        nat nt(r);\n\n        ASSERT_TRUE(SameNumber(mp, nt));\n\n        for (int titer = 0; titer < 100; ++titer) {\n            uint32_t r = dist(gen);\n            mpz_int mpx = r;\n            nat     ntx(r);\n\n            mp = mp + mpx;\n            nt = nt + ntx;\n\n            ASSERT_TRUE(SameNumber(mp, nt));\n        }\n    }\n\n}\nTEST(ADD, VV) {\n    static const size_t TSIZE = KARA_THRES * 2;\n    for (int tgroup = 0; tgroup < 1; ++tgroup) {\n        auto lb1 = random_limbs(TSIZE), lb2 = random_limbs(TSIZE);\n\n        nat nt1(lb1), nt2(lb2);\n        mpz_int mp1 = limbs_to_mpz(lb1), mp2 = limbs_to_mpz(lb2);\n\n        nat nt = nt1 + nt2;\n        mpz_int mp = mp1 + mp2;\n\n        EXPECT_TRUE(SameNumber(mp, nt));\n    }\n}\n\nTEST(SUB, VV) {\n    static const size_t TSIZE = 100;\n    std::uniform_int_distribution<int> dist_sz(0, TSIZE);\n    for (int tgroup = 0; tgroup < 1; ++tgroup) {\n        auto lb1 = random_limbs(dist_sz(gen)), lb2 = random_limbs(dist_sz(gen));\n\n        nat nt1(lb1), nt2(lb2);\n        mpz_int mp1 = limbs_to_mpz(lb1), mp2 = limbs_to_mpz(lb2);\n\n        if (mp1 < mp2) std::swap(nt1, nt2), std::swap(mp1, mp2);\n\n        nat nt = nt1 - nt2;\n        mpz_int mp = mp1 - mp2;\n\n        EXPECT_TRUE(SameNumber(mp, nt));\n    }\n}\n\nTEST(MUL, VW) {\n    for (int tgroup = 0; tgroup < 100; ++tgroup) {\n        uint32_t r = dist(gen);\n        mpz_int mp = r;\n        nat     nt(r);\n\n        ASSERT_TRUE(SameNumber(mp, nt));\n\n        for (int titer = 0; titer < 100; ++titer) {\n            uint32_t r = dist(gen);\n            mpz_int mpx = r;\n            nat     ntx(r);\n\n            mp = mp * mpx;\n            nt = nt * ntx;\n\n\n            ASSERT_TRUE(SameNumber(mp, nt));\n        }\n\n    }\n}\nTEST(MUL, BASIC) {\n    static const size_t TSIZE = KARA_THRES / 2;\n    for (int tgroup = 0; tgroup < 100; ++tgroup) {\n        auto lb1 = random_limbs(TSIZE), lb2 = random_limbs(TSIZE);\n        nat nt1(lb1), nt2(lb2);\n        mpz_int mp1 = limbs_to_mpz(lb1), mp2 = limbs_to_mpz(lb2);\n\n        // nat nt = nt1 * nt2;\n        nat nt;\n        nt.limbs.resize(2 * TSIZE);\n        basicMul(nt.to_span(), nt1.to_cspan(), nt2.to_cspan());\n        nt.norm();\n\n        mpz_int mp = mp1 * mp2;\n\n        EXPECT_TRUE(SameNumber(mp, nt));\n        EXPECT_EQ(0, nt.cmp(nt1 * nt2));\n    }\n}\nTEST(MUL, LEADING) {\n    static const size_t TSIZE = KARA_THRES;\n    VEC lb1(TSIZE, 0), lb2(TSIZE, 0);\n    lb1[TSIZE - 1] = 1;\n    lb2[TSIZE - 1] = 1;\n\n    nat nt1(lb1), nt2(lb2);\n    mpz_int mp1 = limbs_to_mpz(lb1), mp2 = limbs_to_mpz(lb2);\n\n    nat nt = nt1 * nt2;\n    mpz_int mp = mp1 * mp2;\n    EXPECT_TRUE(SameNumber(mp, nt));\n}\nTEST(MUL, VV) {\n    static const size_t TSIZE = KARA_THRES * 50;\n    std::uniform_int_distribution<int> dist_sz(0, TSIZE);\n    for (int tgroup = 0; tgroup < 50; ++tgroup) {\n        auto lb1 = random_limbs(dist_sz(gen)), lb2 = random_limbs(dist_sz(gen));\n\n        nat nt1(lb1), nt2(lb2);\n        mpz_int mp1 = limbs_to_mpz(lb1), mp2 = limbs_to_mpz(lb2);\n\n        nat nt = nt1 * nt2;\n        mpz_int mp = mp1 * mp2;\n\n        // FIXME: EXPECT\n        EXPECT_TRUE(SameNumber(mp, nt));\n        // fprintf(stderr, \"PASS\\n\");\n    }\n}\nTEST(DIV, VW) {\n    static const size_t TSIZE = KARA_THRES * 5;\n    std::uniform_int_distribution<int> dist_sz(1, TSIZE);\n    for (int tgroup = 0; tgroup < 100; ++tgroup) {\n        auto lb1 = random_limbs(dist_sz(gen));\n        mpz_int mp1 = limbs_to_mpz(lb1);\n        nat nt1{lb1};\n\n        WORD b = dist(gen);\n        mpz_int mp2 = b;\n        nat nt2{b};\n\n        nat nt3 = nt1 / nt2;\n        nat nt4 = nt1 % nt2;\n\n        mpz_int mp3 = mp1 / mp2;\n        mpz_int mp4 = mp1 % mp2;\n\n        EXPECT_TRUE(SameNumber(mp3, nt3));\n        EXPECT_TRUE(SameNumber(mp4, nt4));\n    }\n}\nTEST(DIV, VVsmall) {\n    VEC lb1 = {0, 1, 1, 2};\n    mpz_int mp1 = limbs_to_mpz(lb1);\n    nat nt1{lb1};\n\n    VEC lb2 = {1, 100, 1, 100};\n    mpz_int mp2 = limbs_to_mpz(lb2);\n    nat nt2{lb2};\n\n    nat nt3 = nt1 / nt2;\n    nat nt4 = nt1 % nt2;\n\n    mpz_int mp3 = mp1 / mp2;\n    mpz_int mp4 = mp1 % mp2;\n\n    ASSERT_TRUE(SameNumber(mp3, nt3));\n    ASSERT_TRUE(SameNumber(mp4, nt4));\n}\nTEST(DIV, VV) {\n    static const size_t TSIZE = KARA_THRES * 5;\n    std::uniform_int_distribution<int> dist_sz(1, TSIZE);\n    // std::uniform_int_distribution<int> dist_sz(6, 6);\n    for (int tgroup = 0; tgroup < 100; ++tgroup) {\n        auto lb1 = random_limbs(dist_sz(gen));\n        mpz_int mp1 = limbs_to_mpz(lb1);\n        nat nt1{lb1};\n\n        auto lb2 = random_limbs(dist_sz(gen));\n        mpz_int mp2 = limbs_to_mpz(lb2);\n        nat nt2{lb2};\n\n        nat nt3 = nt1 / nt2;\n        nat nt4 = nt1 % nt2;\n\n        mpz_int mp3 = mp1 / mp2;\n        mpz_int mp4 = mp1 % mp2;\n\n        ASSERT_TRUE(SameNumber(mp4, nt4));\n        ASSERT_TRUE(SameNumber(mp3, nt3));\n    }\n}\nTEST(STRCONV, UTOA) {\n    static const size_t TSIZE = 500;\n    std::uniform_int_distribution<int> dist_sz(1, TSIZE);\n    // std::uniform_int_distribution<int> dist_sz(6, 6);\n    for (int tgroup = 0; tgroup < 100; ++tgroup) {\n        auto lb1 = random_limbs(dist_sz(gen));\n        mpz_int mp1 = limbs_to_mpz(lb1);\n        nat nt1{lb1};\n\n        auto mps = mp1.str();\n        auto nts = utoa(nt1, 10);\n\n        ASSERT_EQ(mps, nts);\n    }\n}\nTEST(STRCONV, BACKFORTH) {\n    static const size_t TSIZE = 50;\n    std::uniform_int_distribution<int> dist_sz(1, TSIZE);\n    // std::uniform_int_distribution<int> dist_sz(6, 6);\n    for (int base = 2; base <= 62; ++base) {\n        for (int tgroup = 0; tgroup < 100; ++tgroup) {\n            auto lb1 = random_limbs(dist_sz(gen));\n\n            nat nt(lb1);\n            std::string s = utoa(nt, base);\n            nat nt2 = str_to_nat(s.c_str(), base);\n\n            ASSERT_TRUE(nt == nt2);\n        }\n    }\n}\n", "meta": {"hexsha": "addaa46601e332310dad4172d031dcab899fc6be", "size": 7853, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/bignum_test.cpp", "max_stars_repo_name": "georeth/OJLIBS", "max_stars_repo_head_hexsha": "de59d4fd21255cc2f0a580db7726b634449e6885", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2017-03-26T03:54:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-04T13:10:43.000Z", "max_issues_repo_path": "test/bignum_test.cpp", "max_issues_repo_name": "georeth/OJLIBS", "max_issues_repo_head_hexsha": "de59d4fd21255cc2f0a580db7726b634449e6885", "max_issues_repo_licenses": ["MIT"], "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/bignum_test.cpp", "max_forks_repo_name": "georeth/OJLIBS", "max_forks_repo_head_hexsha": "de59d4fd21255cc2f0a580db7726b634449e6885", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-03-06T09:59:14.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-06T09:59:14.000Z", "avg_line_length": 26.9862542955, "max_line_length": 80, "alphanum_fraction": 0.5573666115, "num_tokens": 2628, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754371026367, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.49689690796292607}}
{"text": "/*\n * sdf2sdf_optimizer2d.cpp\n *\n *  Created on: Mar 05, 2019\n *      Author: Fei Shan\n */\n\n//libraries\n#include <boost/python.hpp>\n#include <iostream>\n\n// local\n#include \"../math/transformation.hpp\"\n#include \"sdf_2_sdf_optimizer2d.hpp\"\n#include \"sdf_gradient_wrt_transformation2d.hpp\"\n\nnamespace ropt = rigid_optimization;\nnamespace eig = Eigen;\n\nnamespace rigid_optimization {\n\nSdf2SdfOptimizer2d::Sdf2SdfOptimizer2d(\n\t\tfloat rate,\n\t\tint maximum_iteration_count,\n\t\ttsdf::Parameters2d tsdf_generation_parameters,\n\t\tVerbosityParameters verbosity_parameters) :\n\t\trate(rate),\n\t\t\t\tmaximum_iteration_count(maximum_iteration_count),\n\t\t\t\ttsdf_generator(tsdf_generation_parameters),\n\t\t\t\tverbosity_parameters(verbosity_parameters)\n{\n}\n;\n\nSdf2SdfOptimizer2d::~Sdf2SdfOptimizer2d()\n{\n}\n;\n\nSdf2SdfOptimizer2d::VerbosityParameters::VerbosityParameters(\n\t\tbool print_iteration_max_warp_update,\n\t\tbool print_iteration_energy) :\n\t\tprint_iteration_max_warp_update(print_iteration_max_warp_update),\n\t\t\t\tprint_iteration_energy(print_iteration_energy),\n\t\t\t\tprint_per_iteration_info(\n\t\t\t\t\t\tprint_iteration_max_warp_update ||\n\t\t\t\t\t\t\t\tprint_iteration_energy\n\t\t\t\t\t\t\t\t)\n{\n}\n;\n\neig::Matrix3f Sdf2SdfOptimizer2d::optimize(int image_y_coordinate,\n\t\tconst eig::MatrixXf canonical_field,\n\t\tconst eig::Matrix<unsigned short, eig::Dynamic, eig::Dynamic>& live_depth_image,\n\t\tfloat eta,\n\t\tconst eig::Matrix4f& initial_camera_pose) {\n\n\teig::MatrixXf canonical_weight = canonical_field.replicate(1, 1);\n\tfor (int i = 0; i < canonical_weight.rows(); ++i) { // Determine weight based on thickness\n\t\tfor (int j = 0; j < canonical_weight.cols(); ++j) {\n\t\t\tcanonical_weight(i, j) = (canonical_field(i, j) <= -eta) ? 0.0f : 1.0f;\n\t\t}\n\t}\n\n\teig::Vector3f twist = eig::Vector3f(0.0f, 0.0f, 0.0f);\n\n\tfor (int iteration_count = 0; iteration_count < maximum_iteration_count; ++iteration_count) {\n\t\teig::Matrix3f matrix_A = eig::Matrix3f::Zero(); // from sdf2sdf paper,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// used for calculating the optimal transformation.\n\t\teig::Vector3f vector_b = eig::Vector3f::Zero(); // from sdf2sdf paper,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// used to calculating the optimal transformation.\n\n\t\teig::Matrix<float, 6, 1> twist3d;\n\t\ttwist3d << twist(0), 0.0f, twist(1), 0.0f, twist(2), 0.0f;\n\t\teig::Matrix4f twist_matrix3d = math::transformation_vector_to_matrix3d(twist3d);\n\t\teig::MatrixXf live_field = this->tsdf_generator.generate(live_depth_image,\n\t\t\t\ttwist_matrix3d,\n\t\t\t\timage_y_coordinate);\n\t\teig::MatrixXf live_weight = live_field.replicate(1, 1);\n\t\tfor (int j = 0; j < live_weight.cols(); ++j) { // Determine weight based on thickness\n\t\t\tfor (int i = 0; i < live_weight.rows(); ++i) {\n\t\t\t\tlive_weight(i, j) = (live_field(i, j) <= -eta) ? 0.0f : 1.0f;\n\t\t\t}\n\t\t}\n\t\teig::Matrix<eig::Vector3f, eig::Dynamic, eig::Dynamic> live_gradient(canonical_field.rows(),\n\t\t\t\tcanonical_field.cols());\n\t\teig::Vector3i offset(tsdf_generator.parameters.array_offset.x,\n\t\t\t\t0,\n\t\t\t\ttsdf_generator.parameters.array_offset.y);\n\t\tropt::gradient_wrt_twist(live_field,\n\t\t\t\ttwist,\n\t\t\t\toffset,\n\t\t\t\ttsdf_generator.parameters.voxel_size,\n\t\t\t\tlive_gradient);\n\n\t\tfor (int j = 0; j < live_field.cols(); ++j) {\n\t\t\tfor (int i = 0; i < live_field.rows(); ++i) {\n\t\t\t\tmatrix_A += live_gradient(i, j) * live_gradient(i, j).transpose();\n\t\t\t\tvector_b += (canonical_field(i, j) - live_field(i, j) + live_gradient(i, j).transpose() * twist)\n\t\t\t\t\t\t* live_gradient(i, j);\n\t\t\t}\n\t\t}\n\n\t\tfloat energy = .5f * (canonical_field.cwiseProduct(canonical_weight) -\n\t\t\t\tlive_field.cwiseProduct(live_weight)).array().pow(2.f).sum();\n\t\teig::Vector3f optimal_twist = matrix_A.inverse() * vector_b;\n\t\ttwist = twist + this->rate * (optimal_twist - twist);\n\t\tif (this->verbosity_parameters.print_per_iteration_info) {\n\t\t\tstd::cout << \"[ITERATION \" << iteration_count << \" COMPLETED]\\n\";\n\t\t\tif (this->verbosity_parameters.print_iteration_max_warp_update) {\n\t\t\t\tstd::cout << \" [optimize twist:\" << optimal_twist.transpose() << \"]\\n\";\n\t\t\t\tstd::cout << \" [twist:\" << twist.transpose() << \"]\\n\";\n\t\t\t}\n\t\t\tif (this->verbosity_parameters.print_iteration_energy) {\n\t\t\t\tstd::cout << \" [energy: \" << energy << \"]\\n\\n\" << std::endl;\n\t\t\t}\n\n\t\t}\n\t}\n\n\n    eig::Matrix3f twist_matrix2d = math::transformation_vector_to_matrix2d(twist);\n\treturn twist_matrix2d;\n}\n\n}\n", "meta": {"hexsha": "221f533ac726e3a0e433d7e187a9d8a77aac1ee6", "size": 4226, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/rigid_optimization/sdf_2_sdf_optimizer2d.cpp", "max_stars_repo_name": "Algomorph/LevelSetFusionExperimentsCPP", "max_stars_repo_head_hexsha": "f56962f0ad5c62e6706f818062782a2e1660afda", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2019-01-07T14:12:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T01:48:03.000Z", "max_issues_repo_path": "src/rigid_optimization/sdf_2_sdf_optimizer2d.cpp", "max_issues_repo_name": "Algomorph/LevelSetFusionExperimentsCPP", "max_issues_repo_head_hexsha": "f56962f0ad5c62e6706f818062782a2e1660afda", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2018-12-19T16:43:33.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-06T19:50:22.000Z", "max_forks_repo_path": "src/rigid_optimization/sdf_2_sdf_optimizer2d.cpp", "max_forks_repo_name": "Algomorph/LevelSetFusionExperimentsCPP", "max_forks_repo_head_hexsha": "f56962f0ad5c62e6706f818062782a2e1660afda", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-01-07T14:12:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-06T06:30:24.000Z", "avg_line_length": 33.015625, "max_line_length": 100, "alphanum_fraction": 0.7035021297, "num_tokens": 1241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825007, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.4968795142035482}}
{"text": "/*\n * Software License Agreement (BSD License)\n *\n *  Copyright (c) 2015, Thomas M\u00f6rwald\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions\n *  are met:\n *\n *   * Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *   * Redistributions in binary form must reproduce the above\n *     copyright notice, this list of conditions and the following\n *     disclaimer in the documentation and/or other materials provided\n *     with the distribution.\n *   * Neither the name of the copyright holder(s) nor the names of its\n *     contributors may be used to endorse or promote products derived\n *     from this software without specific prior written permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n *  \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n *  POSSIBILITY OF SUCH DAMAGE.\n *\n *\n *\n */\n\n#include \"patch.h\"\n#include <stdexcept>\n\n#undef Success\n#include <Eigen/Dense>\n\nusing namespace nurbsfit;\n\nvoid FitPatch::initSurface(int dims, int order0, int order1, int cps0, int cps1, Domain roi)\n{\n  if( cps0 < order0 )\n    cps0 = order0;\n\n  if( cps1 < order1 )\n    cps1 = order1;\n\n  m_nurbs = ON_NurbsSurface (dims, false, order0, order1, cps0, cps1);\n\n  double ddx = roi.width  / (m_nurbs.KnotCount(0) - 2*(order0-2) - 1);\n  double ddy = roi.height / (m_nurbs.KnotCount(1) - 2*(order1-2) - 1);\n\n  m_nurbs.MakeClampedUniformKnotVector (0, ddx);\n  m_nurbs.MakeClampedUniformKnotVector (1, ddy);\n\n  for (int i = 0; i < m_nurbs.KnotCount(0); i++)\n  {\n    double k = m_nurbs.Knot (0, i);\n    m_nurbs.SetKnot (0, i, k + roi.x);\n  }\n\n  for (int i = 0; i < m_nurbs.KnotCount(1); i++)\n  {\n    double k = m_nurbs.Knot (1, i);\n    m_nurbs.SetKnot (1, i, k + roi.y);\n  }\n\n  m_x = Eigen::VectorXd(m_nurbs.CVCount()*dims,1);\n  m_x.setZero();\n  for (int i = 0; i < m_nurbs.CVCount(0); i++)\n  {\n    for (int j = 0; j < m_nurbs.CVCount(1); j++)\n    {\n      m_nurbs.SetCV (i, j, ON_3dPoint(m_nurbs.Knot(0, i),m_nurbs.Knot(1, j),0));\n    }\n  }\n}\n\nvoid FitPatch::initSolver(const Eigen::VectorXd& param0, const Eigen::VectorXd& param1)\n{\n  if(param0.rows()!=param1.rows())\n    throw std::runtime_error(\"[FitPatch::initSolver] Error, param vectors must be of same length.\");\n\n  if(m_nurbs.CVCount() <= 0)\n    throw std::runtime_error(\"[FitPatch::initSolver] Error, surface not initialized (initSurface).\");\n\n  int dim = m_nurbs.Dimension();\n  m_A = SparseMatrix( param0.rows()*dim, m_nurbs.CVCount()*dim );\n\n  typedef Eigen::Triplet<double> Tri;\n  std::vector<Tri> tripletList;\n  tripletList.resize( 3*param0.rows() * m_nurbs.Order(0) * m_nurbs.Order(1) );\n\n  if(!m_quiet)\n    printf(\"[FitPatch::initSolver] entries: %lu  rows: %lu  cols: %d\\n\",\n           param0.rows()* m_nurbs.Order(0) * m_nurbs.Order(1),\n           param0.rows(),\n           m_nurbs.CVCount());\n\n  double *N0 = new double[m_nurbs.Order (0) * m_nurbs.Order (0)];\n  double *N1 = new double[m_nurbs.Order (1) * m_nurbs.Order (1)];\n  int E,F;\n  int ti(0);\n\n  for(Eigen::MatrixXd::Index row=0; row<param0.rows(); row++)\n  {\n    E = ON_NurbsSpanIndex (m_nurbs.m_order[0], m_nurbs.m_cv_count[0], m_nurbs.m_knot[0], param0(row), 0, 0);\n    F = ON_NurbsSpanIndex (m_nurbs.m_order[1], m_nurbs.m_cv_count[1], m_nurbs.m_knot[1], param1(row), 0, 0);\n\n    ON_EvaluateNurbsBasis (m_nurbs.Order (0), m_nurbs.m_knot[0] + E, param0(row), N0);\n    ON_EvaluateNurbsBasis (m_nurbs.Order (1), m_nurbs.m_knot[1] + F, param1(row), N1);\n\n    for (int i = 0; i < m_nurbs.Order (0); i++)\n    {\n      for (int j = 0; j < m_nurbs.Order (1); j++)\n      {\n        tripletList[ti] = Tri( dim*row, dim*lrc2gl(E, F, i, j), N0[i] * N1[j] );\n        if(dim>1)\n          tripletList[ti+1] = Tri( dim*row+1, dim*lrc2gl(E, F, i, j)+1, N0[i] * N1[j] );\n        if(dim>2)\n          tripletList[ti+2] = Tri( dim*row+2, dim*lrc2gl(E, F, i, j)+2, N0[i] * N1[j] );\n        ti+=dim;\n      } // j\n    } // i\n\n  } // row\n\n  delete [] N1;\n  delete [] N0;\n\n  m_A.setFromTriplets(tripletList.begin(), tripletList.end());\n\n  if(m_solver==NULL)\n    m_solver = new SPQR();\n  m_solver->compute(m_A);\n  if(m_solver->info()!=Eigen::Success)\n    throw std::runtime_error(\"[FitPatch::initSolver] decomposition failed.\");\n\n  if(!m_quiet)\n    printf(\"[FitPatch::initSolver] decomposition done\\n\");\n}\n\nvoid FitPatch::solve(const Eigen::VectorXd& values)\n{\n  m_x = m_solver->solve(values);\n\n  updateSurf();\n}\n\nvoid FitPatch::updateSurf()\n{\n  int ncp = m_nurbs.CVCount ();\n\n  if(m_x.rows()!=ncp*m_nurbs.Dimension())\n    throw std::runtime_error(\"[FitPatch::updateSurf] Error, number of control points does not match.\");\n\n  for (int i = 0; i < ncp; i++)\n  {\n    ON_3dPoint cp;\n\n    if(m_nurbs.Dimension()==1)\n    {\n      cp.x = m_x(i);\n    }\n\n    if(m_nurbs.Dimension()==2)\n    {\n      cp.x = m_x(2*i+0);\n      cp.y = m_x(2*i+1);\n    }\n\n    if(m_nurbs.Dimension()==3)\n    {\n      cp.x = m_x(3*i+0);\n      cp.y = m_x(3*i+1);\n      cp.z = m_x(3*i+2);\n    }\n\n    m_nurbs.SetCV(gl2gr(i), gl2gc(i), cp);\n  }\n}\n\nEigen::VectorXd FitPatch::getError(const Eigen::VectorXd& values)\n{\n  // compute A*x (i.e. points on surface)\n  Eigen::VectorXd Ax(values.rows(),1);\n  Ax.setZero();\n  for (int k=0; k<m_A.outerSize(); ++k)\n  for (SparseMatrix::InnerIterator it(m_A,k); it; ++it)\n    Ax(it.row()) += it.value() * m_x(it.col());\n\n  // return (A*x-b)\n  return (Ax-values);\n}\n\nEigen::Vector2d FitPatch::reparameterize(const Eigen::VectorXd &value, const Eigen::Vector2d &hint,\n                                         int& steps, double &accuracy, int maxSteps, double minAccuracy)\n{\n  if(m_nurbs.CVCount() <= 0)\n    throw std::runtime_error(\"[FitPatch::reparameterize] Error, surface not initialized (initSurface).\");\n\n  int nder = 1; // number of derivatives\n  int dims = m_nurbs.Dimension();\n  int nvals = dims*(nder+1)*(nder+2)/2;\n  double pointAndTangents[nvals];\n\n  Eigen::Vector2d current, delta, b, c;\n  Eigen::Matrix2d A, I;\n  Eigen::VectorXd p(dims), tu(dims), tv(dims), r(dims);\n  I = Eigen::Matrix2d::Identity();\n\n  double minU = m_nurbs.Knot(0,0);\n  double minV = m_nurbs.Knot(1,0);\n  double maxU = m_nurbs.Knot(0,m_nurbs.KnotCount(0)-1);\n  double maxV = m_nurbs.Knot(1,m_nurbs.KnotCount(1)-1);\n  double nu = 0.5;\n  double lambda = 1.0;\n  double accuracy_old(DBL_MAX);\n\n  current = hint;\n\n  for (steps = 0; steps < maxSteps; steps++)\n  {\n\n    m_nurbs.Evaluate (current(0), current(1), nder, dims, pointAndTangents);\n\n    if(dims==1)\n    {\n      p(0) = pointAndTangents[0];\n      tu(0) = pointAndTangents[1];\n      tv(0) = pointAndTangents[2];\n    }\n\n    if(dims==2)\n    {\n      p(0) = pointAndTangents[0];\n      p(1) = pointAndTangents[1];\n      tu(0) = pointAndTangents[2];\n      tu(1) = pointAndTangents[3];\n      tv(0) = pointAndTangents[4];\n      tv(1) = pointAndTangents[5];\n    }\n\n    if(dims==3)\n    {\n      p(0) = pointAndTangents[0];\n      p(1) = pointAndTangents[1];\n      p(2) = pointAndTangents[2];\n      tu(0) = pointAndTangents[3];\n      tu(1) = pointAndTangents[4];\n      tu(2) = pointAndTangents[5];\n      tv(0) = pointAndTangents[6];\n      tv(1) = pointAndTangents[7];\n      tv(2) = pointAndTangents[8];\n    }\n\n    r = p - value;\n\n    b(0) = -r.dot (tu);\n    b(1) = -r.dot (tv);\n\n    A(0, 0) = tu.dot (tu);\n    A(0, 1) = tu.dot (tv);\n    A(1, 0) = A (0, 1);\n    A(1, 1) = tv.dot (tv);\n\n    delta = A.ldlt().solve(b);\n\n    accuracy = delta.norm();\n    if (accuracy < minAccuracy)\n      return current;\n\n    // step width control (quite heuristic)\n    if(accuracy>accuracy_old*nu)\n      lambda *= nu;\n    accuracy_old = accuracy;\n\n    // make step\n    c = current + lambda * delta;\n\n    // clamp to domain borders\n    if (c(0) < minU)\n      c(0) = minU;\n    else if (c (0) > maxU)\n      c(0) = maxU;\n    if (c(1) < minV)\n      c(1) = minV;\n    else if (c(1) > maxV)\n      c(1) = maxV;\n\n    // compute real step\n    delta = c - current;\n    current = c;\n\n    accuracy = delta.norm();\n    if (accuracy < minAccuracy)\n      return current;\n  }\n\n  printf (\"[FitPatch::reparameterize] Warning: Method did not converge (%e %e %d)\\n\",\n          accuracy, minAccuracy, maxSteps);\n  printf (\"[FitPatch::reparameterize]   (0: %f %f) (1: %f %f) %f %f ... %f %f\\n\",\n          minU, maxU, minV, maxV,\n          hint (0), hint (1), current (0), current (1));\n\n  return current;\n}\n\n//int nvals = nurbs.m_dim*(nder+1)*(nder+2)/2;\n//double P[nvals];\n//nurbs.Evaluate (u, v, nder, nurbs.m_dim, P);\n\n//// positions\n//xx = P[0];    xy = P[1];    xz = P[2];\n\n//// 1st derivatives (for normals)\n//xu(0) = P[3];    xu(1) = P[4];    xu(2) = P[5];\n//xv(0) = P[6];    xv(1) = P[7];    xv(2) = P[8];\n\n//n = xu.cross(xv);\n//n.normalize();\n//v.normal = TomGine::vec3(n(0),n(1),n(2));\n\n//// 2nd derivatives (for curvature)\n//xuu(0) = P[9];     xuu(1) = P[10];    xuu(2) = P[11];\n//xuv(0) = P[12];    xuv(1) = P[13];    xuv(2) = P[14];\n//xvv(0) = P[15];    xvv(1) = P[16];    xvv(2) = P[17];\n\n//#include <unsupported/Eigen/NumericalDiff>\n//#include <unsupported/Eigen/NonLinearOptimization>\n\n//struct SurfaceFunctor\n//{\n//  const Eigen::VectorXd& m_residuals;\n//  const ON_NurbsSurface& m_nurbs;\n\n//  SurfaceFunctor(const Eigen::VectorXd& residuals, const ON_NurbsSurface& nurbs)\n//    : m_residuals(residuals), m_nurbs(nurbs){}\n\n//  int operator()(const Eigen::VectorXd& x, Eigen::VectorXd& residuals) const\n//  {\n\n\n//    return 0;\n//  }\n\n//  int dx(const Eigen::VectorXd& x, Eigen::MatrixXd& jacobian)\n//  {\n\n//    return 0;\n//  }\n\n//  int inputs() const { return m_nurbs.CVCount(); }\n//  int values() const { return m_residuals.rows(); }\n//};\n\n//Eigen::Vector2d FitPatch::reparameterizeLM(const Eigen::VectorXd &value, const Eigen::Vector2d &hint,\n//                                         int& steps, double &accuracy, int maxSteps, double minAccuracy)\n//{\n//  if(m_nurbs.CVCount() <= 0)\n//    throw std::runtime_error(\"[FitPatch::reparameterize] Error, surface not initialized (initSurface).\");\n\n//  int nder = 1; // number of derivatives\n//  int dims = m_nurbs.Dimension();\n//  int nvals = dims*(nder+1)*(nder+2)/2;\n//  double pointAndTangents[nvals];\n\n//  Eigen::Vector2d current, delta, b, c;\n//  Eigen::Matrix2d A, I;\n//  Eigen::VectorXd p(dims), tu(dims), tv(dims), r(dims);\n//  I = Eigen::Matrix2d::Identity();\n\n//  double minU = m_nurbs.Knot(0,0);\n//  double minV = m_nurbs.Knot(1,0);\n//  double maxU = m_nurbs.Knot(0,m_nurbs.KnotCount(0)-1);\n//  double maxV = m_nurbs.Knot(1,m_nurbs.KnotCount(1)-1);\n\n//  current = hint;\n\n//  SurfaceFunctor func;\n//  Eigen::LevenbergMarquardt<Eigen::NumericalDiff<my_functor>,double> lm(numDiff);\n\n//  for (steps = 0; steps < maxSteps; steps++)\n//  {\n\n//    m_nurbs.Evaluate (current(0), current(1), nder, dims, pointAndTangents);\n\n//    if(dims==1)\n//    {\n//      p(0) = pointAndTangents[0];\n//      tu(0) = pointAndTangents[1];\n//      tv(0) = pointAndTangents[2];\n//    }\n\n//    if(dims==2)\n//    {\n//      p(0) = pointAndTangents[0];\n//      p(1) = pointAndTangents[1];\n//      tu(0) = pointAndTangents[2];\n//      tu(1) = pointAndTangents[3];\n//      tv(0) = pointAndTangents[4];\n//      tv(1) = pointAndTangents[5];\n//    }\n\n//    if(dims==3)\n//    {\n//      p(0) = pointAndTangents[0];\n//      p(1) = pointAndTangents[1];\n//      p(2) = pointAndTangents[2];\n//      tu(0) = pointAndTangents[3];\n//      tu(1) = pointAndTangents[4];\n//      tu(2) = pointAndTangents[5];\n//      tv(0) = pointAndTangents[6];\n//      tv(1) = pointAndTangents[7];\n//      tv(2) = pointAndTangents[8];\n//    }\n\n//    r = p - value;\n\n//    b(0) = -r.dot (tu);\n//    b(1) = -r.dot (tv);\n\n//    A(0, 0) = tu.dot (tu);\n//    A(0, 1) = tu.dot (tv);\n//    A(1, 0) = A (0, 1);\n//    A(1, 1) = tv.dot (tv);\n\n//    delta = A.ldlt().solve(b);\n\n//    accuracy = delta.norm();\n//    if (accuracy < minAccuracy)\n//      return current;\n\n//    // make step\n//    c = current + delta;\n\n//    // clamp to domain borders\n//    if (c(0) < minU)\n//      c(0) = minU;\n//    else if (c (0) > maxU)\n//      c(0) = maxU;\n//    if (c(1) < minV)\n//      c(1) = minV;\n//    else if (c(1) > maxV)\n//      c(1) = maxV;\n\n//    // compute real step\n//    delta = c - current;\n//    current = c;\n\n//    accuracy = delta.norm();\n//    if (accuracy < minAccuracy)\n//      return current;\n//  }\n\n//  printf (\"[FitPatch::reparameterize] Warning: Method did not converge (%e %e %d)\\n\",\n//          accuracy, minAccuracy, maxSteps);\n//  printf (\"[FitPatch::reparameterize]   (0: %f %f) (1: %f %f) %f %f ... %f %f\\n\",\n//          minU, maxU, minV, maxV,\n//          hint (0), hint (1), current (0), current (1));\n\n//  return current;\n//}\n\n", "meta": {"hexsha": "e71cba52d7a36fb23a25c450ff9e207cbed66916", "size": 13284, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "NurbsFit/patch.cpp", "max_stars_repo_name": "OpenNurbsFit/OpenNurbsFit", "max_stars_repo_head_hexsha": "d1ca01437a6da6bbf921466013ff969def5dfe65", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-07-06T13:04:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T10:09:05.000Z", "max_issues_repo_path": "NurbsFit/patch.cpp", "max_issues_repo_name": "OpenNurbsFit/OpenNurbsFit", "max_issues_repo_head_hexsha": "d1ca01437a6da6bbf921466013ff969def5dfe65", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-12-07T03:26:39.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-07T03:26:39.000Z", "max_forks_repo_path": "NurbsFit/patch.cpp", "max_forks_repo_name": "OpenNurbsFit/OpenNurbsFit", "max_forks_repo_head_hexsha": "d1ca01437a6da6bbf921466013ff969def5dfe65", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2015-07-06T13:04:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T10:57:04.000Z", "avg_line_length": 28.2038216561, "max_line_length": 108, "alphanum_fraction": 0.5955284553, "num_tokens": 4542, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.4968795076877462}}
{"text": "#include \"nnw_hierarchy.h\"\n\n#include <google/protobuf/stubs/casts.h>\n\n#include <Eigen/Dense>\n#include <stan/math/prim/prob.hpp>\n\n#include \"hierarchy_prior.pb.h\"\n#include \"ls_state.pb.h\"\n#include \"marginal_state.pb.h\"\n#include \"matrix.pb.h\"\n#include \"src/utils/distributions.h\"\n#include \"src/utils/eigen_utils.h\"\n#include \"src/utils/proto_utils.h\"\n#include \"src/utils/rng.h\"\n\n//! \\param prec_ Value to set to prec\nvoid NNWHierarchy::set_prec_and_utilities(const Eigen::MatrixXd &prec_) {\n  state.prec = prec_;\n\n  // Update prec utilities\n  prec_chol = Eigen::LLT<Eigen::MatrixXd>(prec_).matrixL().transpose();\n  Eigen::VectorXd diag = prec_chol.diagonal();\n  prec_logdet = 2 * log(diag.array()).sum();\n}\n\nvoid NNWHierarchy::initialize() {\n  if (prior == nullptr) {\n    throw std::invalid_argument(\"Hierarchy prior was not provided\");\n  }\n  state.mean = hypers->mean;\n  set_prec_and_utilities(hypers->var_scaling *\n                         Eigen::MatrixXd::Identity(dim, dim));\n  clear_data();\n}\n\nvoid NNWHierarchy::clear_data() {\n  data_sum = Eigen::VectorXd::Zero(dim);\n  data_sum_squares = Eigen::MatrixXd::Zero(dim, dim);\n  card = 0;\n  cluster_data_idx = std::set<int>();\n}\n\nvoid NNWHierarchy::update_summary_statistics(const Eigen::VectorXd &datum,\n                                             bool add) {\n  if (add) {\n    data_sum += datum;\n    data_sum_squares += datum * datum.transpose();\n  } else {\n    data_sum -= datum;\n    data_sum_squares -= datum * datum.transpose();\n  }\n}\n\n//! \\param data                    Matrix of row-vectorial data points\n//! \\param mu0, lambda0, tau0, nu0 Original values for hyperparameters\n//! \\return                        Vector of updated values for hyperparameters\nNNWHierarchy::Hyperparams NNWHierarchy::normal_wishart_update() {\n  // Initialize relevant objects\n  Hyperparams post_params;\n\n  // Compute updated hyperparameters\n  post_params.var_scaling = hypers->var_scaling + card;\n  post_params.deg_free = hypers->deg_free + 0.5 * card;\n\n  Eigen::VectorXd mubar = data_sum.array() / card;  // sample mean\n  post_params.mean = (hypers->var_scaling * hypers->mean + card * mubar) /\n                     (hypers->var_scaling + card);\n  // Compute tau_n\n  Eigen::MatrixXd tau_temp =\n      data_sum_squares - card * mubar * mubar.transpose();\n  tau_temp += (card * hypers->var_scaling / (card + hypers->var_scaling)) *\n              (mubar - hypers->mean) * (mubar - hypers->mean).transpose();\n  tau_temp = 0.5 * tau_temp + hypers->scale_inv;\n  post_params.scale = stan::math::inverse_spd(tau_temp);\n  return post_params;\n}\n\nvoid NNWHierarchy::update_hypers(\n    const std::vector<bayesmix::MarginalState::ClusterState> &states) {\n  auto &rng = bayesmix::Rng::Instance().get();\n  if (prior->has_fixed_values()) {\n    return;\n  }\n\n  else if (prior->has_normal_mean_prior()) {\n    // Get hyperparameters\n    Eigen::VectorXd mu00 =\n        bayesmix::to_eigen(prior->normal_mean_prior().mean_prior().mean());\n    Eigen::MatrixXd sigma00 =\n        bayesmix::to_eigen(prior->normal_mean_prior().mean_prior().var());\n    double lambda0 = prior->normal_mean_prior().var_scaling();\n    // Compute posterior hyperparameters\n    Eigen::MatrixXd sigma00inv = stan::math::inverse_spd(sigma00);\n    Eigen::MatrixXd prec = Eigen::MatrixXd::Zero(dim, dim);\n    Eigen::VectorXd num = Eigen::MatrixXd::Zero(dim, 1);\n    for (auto &st : states) {\n      Eigen::MatrixXd prec_i = bayesmix::to_eigen(st.multi_ls_state().prec());\n      prec += prec_i;\n      num += prec_i * bayesmix::to_eigen(st.multi_ls_state().mean());\n    }\n    prec = hypers->var_scaling * prec + sigma00inv;\n    num = hypers->var_scaling * num + sigma00inv * mu00;\n    Eigen::VectorXd mu_n = prec.llt().solve(num);\n    // Update hyperparameters with posterior sampling\n    hypers->mean = stan::math::multi_normal_prec_rng(mu_n, prec, rng);\n  }\n\n  else if (prior->has_ngiw_prior()) {\n    // Get hyperparameters:\n    // for mu0\n    Eigen::VectorXd mu00 =\n        bayesmix::to_eigen(prior->ngiw_prior().mean_prior().mean());\n    Eigen::MatrixXd sigma00 =\n        bayesmix::to_eigen(prior->ngiw_prior().mean_prior().var());\n    // for lambda0\n    double alpha00 = prior->ngiw_prior().var_scaling_prior().shape();\n    double beta00 = prior->ngiw_prior().var_scaling_prior().rate();\n    // for tau0\n    double nu00 = prior->ngiw_prior().scale_prior().deg_free();\n    Eigen::MatrixXd tau00 =\n        bayesmix::to_eigen(prior->ngiw_prior().scale_prior().scale());\n    // Compute posterior hyperparameters\n    Eigen::MatrixXd sigma00inv = stan::math::inverse_spd(sigma00);\n    Eigen::MatrixXd tau_n = Eigen::MatrixXd::Zero(dim, dim);\n    Eigen::VectorXd num = Eigen::MatrixXd::Zero(dim, 1);\n    double beta_n = 0.0;\n    for (auto &st : states) {\n      Eigen::VectorXd mean = bayesmix::to_eigen(st.multi_ls_state().mean());\n      Eigen::MatrixXd prec = bayesmix::to_eigen(st.multi_ls_state().prec());\n      tau_n += prec;\n      num += prec * mean;\n      beta_n +=\n          (hypers->mean - mean).transpose() * prec * (hypers->mean - mean);\n    }\n    Eigen::MatrixXd prec_n = hypers->var_scaling * tau_n + sigma00inv;\n    tau_n += tau00;\n    num = hypers->var_scaling * num + sigma00inv * mu00;\n    beta_n = beta00 + 0.5 * beta_n;\n    Eigen::MatrixXd sig_n = stan::math::inverse_spd(prec_n);\n    Eigen::VectorXd mu_n = sig_n * num;\n    double alpha_n = alpha00 + 0.5 * states.size();\n    double nu_n = nu00 + states.size() * hypers->deg_free;\n    // Update hyperparameters with posterior random Gibbs sampling\n    hypers->mean = stan::math::multi_normal_rng(mu_n, sig_n, rng);\n    hypers->var_scaling = stan::math::gamma_rng(alpha_n, beta_n, rng);\n    hypers->scale = stan::math::inv_wishart_rng(nu_n, tau_n, rng);\n    hypers->scale_inv = stan::math::inverse_spd(hypers->scale);\n  }\n\n  else {\n    throw std::invalid_argument(\"Unrecognized hierarchy prior\");\n  }\n}\n\n//! \\param data Matrix of row-vectorial single data point\n//! \\return     Log-Likehood vector evaluated in data\ndouble NNWHierarchy::like_lpdf(const Eigen::RowVectorXd &datum) const {\n  // Initialize relevant objects\n  return bayesmix::multi_normal_prec_lpdf(datum, state.mean, prec_chol,\n                                          prec_logdet);\n}\n\n//! \\param data Matrix of row-vectorial a single data point\n//! \\return     Marginal distribution vector evaluated in data\ndouble NNWHierarchy::marg_lpdf(const Eigen::RowVectorXd &datum) const {\n  // Compute dof and scale of marginal distribution\n  double nu_n = 2 * hypers->deg_free - dim + 1;\n  Eigen::MatrixXd sigma_n = hypers->scale_inv *\n                            (hypers->deg_free - 0.5 * (dim - 1)) *\n                            hypers->var_scaling / (hypers->var_scaling + 1);\n\n  // TODO: chec if this is optimized as our bayesmix::multi_normal_prec_lpdf\n  return stan::math::multi_student_t_lpdf(datum, nu_n, hypers->mean, sigma_n);\n}\n\nvoid NNWHierarchy::draw() {\n  // Generate new state values from their prior centering distribution\n  auto &rng = bayesmix::Rng::Instance().get();\n  Eigen::MatrixXd tau_new =\n      stan::math::wishart_rng(hypers->deg_free, hypers->scale, rng);\n\n  // Update state\n  state.mean = stan::math::multi_normal_prec_rng(\n      hypers->mean, tau_new * hypers->var_scaling, rng);\n  set_prec_and_utilities(tau_new);\n}\n\n//! \\param data Matrix of row-vectorial data points\nvoid NNWHierarchy::sample_given_data() {\n  // Update values\n  Hyperparams params = normal_wishart_update();\n\n  // Generate new state values from their prior centering distribution\n  auto &rng = bayesmix::Rng::Instance().get();\n  Eigen::MatrixXd tau_new =\n      stan::math::wishart_rng(params.deg_free, params.scale, rng);\n  state.mean = stan::math::multi_normal_prec_rng(\n      params.mean, tau_new * params.var_scaling, rng);\n\n  // Update state\n  set_prec_and_utilities(tau_new);\n}\n\nvoid NNWHierarchy::sample_given_data(const Eigen::MatrixXd &data) {\n  data_sum = Eigen::VectorXd::Zero(data.cols());\n  data_sum_squares = Eigen::MatrixXd::Zero(data.cols(), data.cols());\n\n  for (int i = 0; i < data.rows(); i++) {\n    data_sum += data.row(i);\n    data_sum_squares += data.row(i).transpose() * data.row(i);\n  }\n  card = data.rows();\n  log_card = std::log(card);\n  sample_given_data();\n}\n\nvoid NNWHierarchy::set_state_from_proto(\n    const google::protobuf::Message &state_) {\n  auto &statecast = google::protobuf::internal::down_cast<\n      const bayesmix::MarginalState::ClusterState &>(state_);\n  state.mean = to_eigen(statecast.multi_ls_state().mean());\n  set_prec_and_utilities(to_eigen(statecast.multi_ls_state().prec()));\n  set_card(statecast.cardinality());\n}\n\nvoid NNWHierarchy::set_prior(const google::protobuf::Message &prior_) {\n  auto &priorcast =\n      google::protobuf::internal::down_cast<const bayesmix::NNWPrior &>(\n          prior_);\n  prior = std::make_shared<bayesmix::NNWPrior>(priorcast);\n  hypers = std::make_shared<Hyperparams>();\n  if (prior->has_fixed_values()) {\n    // Set values\n    hypers->mean = bayesmix::to_eigen(prior->fixed_values().mean());\n    dim = hypers->mean.size();\n    hypers->var_scaling = prior->fixed_values().var_scaling();\n    hypers->scale = bayesmix::to_eigen(prior->fixed_values().scale());\n    hypers->scale_inv = stan::math::inverse_spd(hypers->scale);\n    hypers->deg_free = prior->fixed_values().deg_free();\n    // Check validity\n    if (hypers->var_scaling <= 0) {\n      throw std::invalid_argument(\"Variance-scaling parameter must be > 0\");\n    }\n    if (dim != hypers->scale.rows()) {\n      throw std::invalid_argument(\n          \"Hyperparameters dimensions are not consistent\");\n    }\n    if (hypers->deg_free <= dim - 1) {\n      throw std::invalid_argument(\"Degrees of freedom parameter is not valid\");\n    }\n  }\n\n  else if (prior->has_normal_mean_prior()) {\n    // Get hyperparameters\n    Eigen::VectorXd mu00 =\n        bayesmix::to_eigen(prior->normal_mean_prior().mean_prior().mean());\n    dim = mu00.size();\n    Eigen::MatrixXd sigma00 =\n        bayesmix::to_eigen(prior->normal_mean_prior().mean_prior().var());\n    double lambda0 = prior->normal_mean_prior().var_scaling();\n    Eigen::MatrixXd tau0 =\n        bayesmix::to_eigen(prior->normal_mean_prior().scale());\n    double nu0 = prior->normal_mean_prior().deg_free();\n    // Check validity\n    unsigned int dim = mu00.size();\n    if (sigma00.rows() != dim or tau0.rows() != dim) {\n      throw std::invalid_argument(\n          \"Hyperparameters dimensions are not consistent\");\n    }\n    bayesmix::check_spd(sigma00);\n    if (lambda0 <= 0) {\n      throw std::invalid_argument(\"Variance-scaling parameter must be > 0\");\n    }\n    bayesmix::check_spd(tau0);\n    if (nu0 <= dim - 1) {\n      throw std::invalid_argument(\"Degrees of freedom parameter is not valid\");\n    }\n    // Set initial values\n    hypers->mean = mu00;\n    hypers->var_scaling = lambda0;\n    hypers->scale = tau0;\n    hypers->scale_inv = stan::math::inverse_spd(tau0);\n    hypers->deg_free = nu0;\n  }\n\n  else if (prior->has_ngiw_prior()) {\n    // Get hyperparameters:\n    // for mu0\n    Eigen::VectorXd mu00 =\n        bayesmix::to_eigen(prior->ngiw_prior().mean_prior().mean());\n    dim = mu00.size();\n    Eigen::MatrixXd sigma00 =\n        bayesmix::to_eigen(prior->ngiw_prior().mean_prior().var());\n    // for lambda0\n    double alpha00 = prior->ngiw_prior().var_scaling_prior().shape();\n    double beta00 = prior->ngiw_prior().var_scaling_prior().rate();\n    // for tau0\n    double nu00 = prior->ngiw_prior().scale_prior().deg_free();\n    Eigen::MatrixXd tau00 =\n        bayesmix::to_eigen(prior->ngiw_prior().scale_prior().scale());\n    // for nu0\n    double nu0 = prior->ngiw_prior().deg_free();\n    // Check validity:\n    // dimensionality\n    if (sigma00.rows() != dim or tau00.rows() != dim) {\n      throw std::invalid_argument(\n          \"Hyperparameters dimensions are not consistent\");\n    }\n    // for mu0\n    bayesmix::check_spd(sigma00);\n    // for lambda0\n    if (alpha00 <= 0) {\n      throw std::invalid_argument(\"Shape parameter must be > 0\");\n    }\n    if (beta00 <= 0) {\n      throw std::invalid_argument(\"Rate parameter must be > 0\");\n    }\n    // for tau0\n    if (nu00 <= 0) {\n      throw std::invalid_argument(\"Degrees of freedom parameter must be > 0\");\n    }\n    bayesmix::check_spd(tau00);\n    // check nu0\n    if (nu0 <= dim - 1) {\n      throw std::invalid_argument(\"Degrees of freedom parameter is not valid\");\n    }\n    // Set initial values\n    hypers->mean = mu00;\n    hypers->var_scaling = alpha00 / beta00;\n    hypers->scale = tau00 / (nu00 + dim + 1);\n    hypers->scale_inv = stan::math::inverse_spd(hypers->scale);\n    hypers->deg_free = nu0;\n  }\n\n  else {\n    throw std::invalid_argument(\"Unrecognized hierarchy prior\");\n  }\n}\n\nvoid NNWHierarchy::write_state_to_proto(google::protobuf::Message *out) const {\n  bayesmix::MultiLSState state_;\n  bayesmix::to_proto(state.mean, state_.mutable_mean());\n  bayesmix::to_proto(state.prec, state_.mutable_prec());\n  auto *out_cast = google::protobuf::internal::down_cast<\n      bayesmix::MarginalState::ClusterState *>(out);\n  out_cast->mutable_multi_ls_state()->CopyFrom(state_);\n  out_cast->set_cardinality(card);\n}\n\nvoid NNWHierarchy::write_hypers_to_proto(\n    google::protobuf::Message *out) const {\n  bayesmix::NNWPrior hypers_;\n  bayesmix::to_proto(hypers->mean,\n                     hypers_.mutable_fixed_values()->mutable_mean());\n  hypers_.mutable_fixed_values()->set_var_scaling(hypers->var_scaling);\n  hypers_.mutable_fixed_values()->set_deg_free(hypers->deg_free);\n  bayesmix::to_proto(hypers->scale,\n                     hypers_.mutable_fixed_values()->mutable_scale());\n\n  google::protobuf::internal::down_cast<bayesmix::NNWPrior *>(out)\n      ->mutable_fixed_values()\n      ->CopyFrom(hypers_.fixed_values());\n}\n", "meta": {"hexsha": "dc69da79bc08607a73ffd9cbae591dc7e74bb597", "size": 13686, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/hierarchies/nnw_hierarchy.cc", "max_stars_repo_name": "JoaoHenriqueOliveira/bayesmix", "max_stars_repo_head_hexsha": "8ebc95c5188d236796593dd21b72436f903bf5e5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/hierarchies/nnw_hierarchy.cc", "max_issues_repo_name": "JoaoHenriqueOliveira/bayesmix", "max_issues_repo_head_hexsha": "8ebc95c5188d236796593dd21b72436f903bf5e5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/hierarchies/nnw_hierarchy.cc", "max_forks_repo_name": "JoaoHenriqueOliveira/bayesmix", "max_forks_repo_head_hexsha": "8ebc95c5188d236796593dd21b72436f903bf5e5", "max_forks_repo_licenses": ["BSD-3-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.495890411, "max_line_length": 79, "alphanum_fraction": 0.6663743972, "num_tokens": 3593, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.4968795076877462}}
{"text": "// Standard Libraries\n#include <iostream>\n\n// 3rd Parties Libraries\n//PCL\n#include <pcl/common/common_headers.h>\n\n//Eigen\n#include <Eigen/Dense>\n\n//Local Libraries\n#include <point_cloud_utils.h>\n#include <distance_geometry_registration.h>\n\n\nint main(int argc, char** argv)\t{\n\tif(argc < 4)\t{\n\t\tstd::cerr << \"Usage: distance_geometry_registration <SourceCorrespondence> <SourcePointCloud> <TargetCorrespondence>\\n\";\n\t\treturn -1;\n\t}\n\n\tpcl::PointCloud<pcl::PointXYZRGB>::Ptr sourceCorrespondence(new pcl::PointCloud<pcl::PointXYZRGB>);\n\tpcl::PointCloud<pcl::PointXYZRGB>::Ptr sourcePointCloud(new pcl::PointCloud<pcl::PointXYZRGB>);\n\tpcl::PointCloud<pcl::PointXYZRGB>::Ptr targetCorrespondence(new pcl::PointCloud<pcl::PointXYZRGB>);\n\n\n\t// Import Point Cloud\n\timportPointCloud<pcl::PointXYZRGB>(argv[1], sourceCorrespondence);\n\timportPointCloud<pcl::PointXYZRGB>(argv[2], sourcePointCloud);\n\timportPointCloud<pcl::PointXYZRGB>(argv[3], targetCorrespondence);\n\n\tDistanceGeometryRegistration<pcl::PointXYZRGB>* dgr = new DistanceGeometryRegistration<pcl::PointXYZRGB>();\n\tdgr->pointCloudRegistration(sourceCorrespondence, targetCorrespondence, sourcePointCloud, THREAD_MODE::THREAD_DISABLE);\n\tstd::cout << \"Transformation Error: \" << dgr->estimateError(sourceCorrespondence, targetCorrespondence);\n\n\texportPointCloud<pcl::PointXYZRGB>(\"transformatedPointCloud.txt\", sourcePointCloud);\n\n\tdelete dgr;\n\treturn 0;\n}", "meta": {"hexsha": "8b2ece02d8c9595fdde9cc7922fad790be511f5f", "size": 1405, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/example_distance_geometry_registration.cpp", "max_stars_repo_name": "hyu1834/Point-Cloud-Registration-API", "max_stars_repo_head_hexsha": "951713210f756d2fa491e1a006cb17fc5ca84ba1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-07-28T14:50:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-16T13:03:10.000Z", "max_issues_repo_path": "example/example_distance_geometry_registration.cpp", "max_issues_repo_name": "hyu1834/Point-Cloud-Registration-API", "max_issues_repo_head_hexsha": "951713210f756d2fa491e1a006cb17fc5ca84ba1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/example_distance_geometry_registration.cpp", "max_forks_repo_name": "hyu1834/Point-Cloud-Registration-API", "max_forks_repo_head_hexsha": "951713210f756d2fa491e1a006cb17fc5ca84ba1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-04-24T02:07:37.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-02T12:23:24.000Z", "avg_line_length": 35.125, "max_line_length": 122, "alphanum_fraction": 0.7814946619, "num_tokens": 324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825006, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.4968795034537337}}
{"text": "#include <stan/math/mix/scal.hpp>\n#include <gtest/gtest.h>\n#include <boost/math/special_functions/digamma.hpp>\n#include <test/unit/math/rev/scal/fun/util.hpp>\n#include <test/unit/math/mix/scal/fun/nan_util.hpp>\n\n\n\nTEST(AgradFwdBinomialCoefficientLog,FvarVar_Double_1stDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using stan::math::binomial_coefficient_log;\n  using boost::math::digamma;\n\n  fvar<var> x(2004.0,1.0);\n  double z(1002);\n  fvar<var> a = binomial_coefficient_log(x,z);\n\n  EXPECT_FLOAT_EQ(binomial_coefficient_log(2004.0,1002.0), a.val_.val());\n  EXPECT_FLOAT_EQ(0.69289774, a.d_.val());\n\n  AVEC y = createAVEC(x.val_);\n  VEC g;\n  a.val_.grad(y,g);\n  EXPECT_FLOAT_EQ(0.69289774, g[0]);\n}\nTEST(AgradFwdBinomialCoefficientLog,Double_FvarVar_1stDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using stan::math::binomial_coefficient_log;\n  using boost::math::digamma;\n\n  double x(2004.0);\n  fvar<var> z(1002.0,2.0);\n  fvar<var> a = binomial_coefficient_log(x,z);\n\n  EXPECT_FLOAT_EQ(binomial_coefficient_log(2004.0,1002.0), a.val_.val());\n  EXPECT_NEAR(0, a.d_.val(),1e-8);\n\n  AVEC y = createAVEC(z.val_);\n  VEC g;\n  a.val_.grad(y,g);\n  EXPECT_NEAR(0, g[0],1e-8);\n}\nTEST(AgradFwdBinomialCoefficientLog,FvarVar_Double_2ndDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using stan::math::binomial_coefficient_log;\n  using boost::math::digamma;\n\n  fvar<var> x(2004.0,1.0);\n  double z(1002);\n  fvar<var> a = binomial_coefficient_log(x,z);\n\n  EXPECT_FLOAT_EQ(binomial_coefficient_log(2004.0,1002.0), a.val_.val());\n  EXPECT_FLOAT_EQ(0.69289774, a.d_.val());\n\n  AVEC y = createAVEC(x.val_);\n  VEC g;\n  a.d_.grad(y,g);\n  EXPECT_FLOAT_EQ(-0.00049862865, g[0]);\n}\nTEST(AgradFwdBinomialCoefficientLog,Double_FvarVar_2ndDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using stan::math::binomial_coefficient_log;\n  using boost::math::digamma;\n\n  double x(2004.0);\n  fvar<var> z(1002.0,2.0);\n  fvar<var> a = binomial_coefficient_log(x,z);\n\n  EXPECT_FLOAT_EQ(binomial_coefficient_log(2004.0,1002.0), a.val_.val());\n  EXPECT_NEAR(0, a.d_.val(),1e-8);\n\n  AVEC y = createAVEC(z.val_);\n  VEC g;\n  a.d_.grad(y,g);\n  EXPECT_FLOAT_EQ(-0.00399002460681026, g[0]);\n}\n\n\nTEST(AgradFwdBinomialCoefficientLog,FvarVar_FvarVar_1stDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using stan::math::binomial_coefficient_log;\n  using boost::math::digamma;\n\n  fvar<var> x(2004.0,1.0);\n  fvar<var> z(1002.0,2.0);\n  fvar<var> a = binomial_coefficient_log(x,z);\n\n  EXPECT_FLOAT_EQ(binomial_coefficient_log(2004.0,1002.0), a.val_.val());\n  EXPECT_FLOAT_EQ(0.69289774, a.d_.val());\n\n  AVEC y = createAVEC(x.val_,z.val_);\n  VEC g;\n  a.val_.grad(y,g);\n  EXPECT_FLOAT_EQ(0.69289774, g[0]);\n  EXPECT_NEAR(0, g[1],1e-8);\n}\nTEST(AgradFwdBinomialCoefficientLog,FvarVar_FvarVar_2ndDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using stan::math::binomial_coefficient_log;\n  using boost::math::digamma;\n\n  fvar<var> x(2004.0,1.0);\n  fvar<var> z(1002.0,2.0);\n  fvar<var> a = binomial_coefficient_log(x,z);\n\n  EXPECT_FLOAT_EQ(binomial_coefficient_log(2004.0,1002.0), a.val_.val());\n  EXPECT_FLOAT_EQ(0.69289774, a.d_.val());\n\n  AVEC y = createAVEC(x.val_,z.val_);\n  VEC g;\n  a.d_.grad(y,g);\n  EXPECT_FLOAT_EQ(0.0014963837, g[0]);\n  EXPECT_FLOAT_EQ(-0.0029925184551076781, g[1]);\n}\n\n\n\nTEST(AgradFwdBinomialCoefficientLog,FvarFvarVar_FvarFvarVar_1stDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using stan::math::binomial_coefficient_log;\n  using stan::math::binomial_coefficient_log;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 2004.0;\n  x.val_.d_ = 1.0;\n\n  fvar<fvar<var> > y;\n  y.val_.val_ = 1002.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = binomial_coefficient_log(x,y);\n\n  EXPECT_FLOAT_EQ(binomial_coefficient_log(2004.0,1002.0), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(0.69289774, a.val_.d_.val());\n  EXPECT_NEAR(0, a.d_.val_.val(),1e-8);\n  EXPECT_FLOAT_EQ(0.0009975062, a.d_.d_.val());\n\n  AVEC p = createAVEC(x.val_.val_,y.val_.val_);\n  VEC g;\n  a.val_.val_.grad(p,g);\n  EXPECT_FLOAT_EQ(0.69289774, g[0]);\n  EXPECT_NEAR(0, g[1],1e-8);\n}\nTEST(AgradFwdBinomialCoefficientLog,FvarFvarVar_Double_1stDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using stan::math::binomial_coefficient_log;\n  using stan::math::binomial_coefficient_log;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 2004.0;\n  x.val_.d_ = 1.0;\n\n  double y(1002.0);\n\n  fvar<fvar<var> > a = binomial_coefficient_log(x,y);\n\n  EXPECT_FLOAT_EQ(binomial_coefficient_log(2004.0,1002.0), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(0.69289774, a.val_.d_.val());\n  EXPECT_NEAR(0, a.d_.val_.val(),1e-8);\n  EXPECT_FLOAT_EQ(0, a.d_.d_.val());\n\n  AVEC p = createAVEC(x.val_.val_);\n  VEC g;\n  a.val_.val_.grad(p,g);\n  EXPECT_FLOAT_EQ(0.69289774, g[0]);\n}\nTEST(AgradFwdBinomialCoefficientLog,Double_FvarFvarVar_1stDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using stan::math::binomial_coefficient_log;\n  using stan::math::binomial_coefficient_log;\n\n  double x(2004.0);\n\n  fvar<fvar<var> > y;\n  y.val_.val_ = 1002.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = binomial_coefficient_log(x,y);\n\n  EXPECT_FLOAT_EQ(binomial_coefficient_log(2004.0,1002.0), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(0, a.val_.d_.val());\n  EXPECT_NEAR(0, a.d_.val_.val(),1e-8);\n  EXPECT_FLOAT_EQ(0, a.d_.d_.val());\n\n  AVEC p = createAVEC(y.val_.val_);\n  VEC g;\n  a.val_.val_.grad(p,g);\n  EXPECT_NEAR(0, g[0],1e-8);\n}\n\nTEST(AgradFwdBinomialCoefficientLog,FvarFvarVar_FvarFvarVar_2ndDeriv_x) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using stan::math::binomial_coefficient_log;\n  using stan::math::binomial_coefficient_log;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 2004.0;\n  x.val_.d_ = 1.0;\n\n  fvar<fvar<var> > y;\n  y.val_.val_ = 1002.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = binomial_coefficient_log(x,y);\n\n  EXPECT_FLOAT_EQ(binomial_coefficient_log(2004.0,1002.0), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(0.69289774, a.val_.d_.val());\n  EXPECT_NEAR(0, a.d_.val_.val(),1e-8);\n  EXPECT_FLOAT_EQ(0.0009975062, a.d_.d_.val());\n\n  AVEC p = createAVEC(x.val_.val_,y.val_.val_);\n  VEC g;\n  a.val_.d_.grad(p,g);\n  EXPECT_FLOAT_EQ(-0.00049862865, g[0]);\n  EXPECT_FLOAT_EQ(0.00099750615170258105, g[1]);\n}\nTEST(AgradFwdBinomialCoefficientLog,FvarFvarVar_FvarFvarVar_2ndDeriv_y) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using stan::math::binomial_coefficient_log;\n  using stan::math::binomial_coefficient_log;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 2004.0;\n  x.val_.d_ = 1.0;\n\n  fvar<fvar<var> > y;\n  y.val_.val_ = 1002.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = binomial_coefficient_log(x,y);\n\n  EXPECT_FLOAT_EQ(binomial_coefficient_log(2004.0,1002.0), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(0.69289774, a.val_.d_.val());\n  EXPECT_NEAR(0, a.d_.val_.val(),1e-8);\n  EXPECT_FLOAT_EQ(0.0009975062, a.d_.d_.val());\n\n  AVEC p = createAVEC(x.val_.val_,y.val_.val_);\n  VEC g;\n  a.d_.val_.grad(p,g);\n  EXPECT_FLOAT_EQ(0.0009975062, g[0]);\n  EXPECT_FLOAT_EQ(-0.0019950123034051291, g[1]);\n}\nTEST(AgradFwdBinomialCoefficientLog,Double_FvarFvarVar_2ndDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using stan::math::binomial_coefficient_log;\n  using stan::math::binomial_coefficient_log;\n\n  double x(2004.0);\n\n  fvar<fvar<var> > y;\n  y.val_.val_ = 1002.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = binomial_coefficient_log(x,y);\n\n  EXPECT_FLOAT_EQ(binomial_coefficient_log(2004.0,1002.0), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(0, a.val_.d_.val());\n  EXPECT_NEAR(0, a.d_.val_.val(),1e-8);\n  EXPECT_FLOAT_EQ(0, a.d_.d_.val());\n\n  AVEC p = createAVEC(y.val_.val_);\n  VEC g;\n  a.d_.val_.grad(p,g);\n  EXPECT_NEAR(-0.00199501230340513, g[0],1e-8);\n}\nTEST(AgradFwdBinomialCoefficientLog,FvarFvarVar_Double_2ndDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using stan::math::binomial_coefficient_log;\n  using stan::math::binomial_coefficient_log;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 2004.0;\n  x.val_.d_ = 1.0;\n\n  double y(1002.0);\n\n  fvar<fvar<var> > a = binomial_coefficient_log(x,y);\n\n  EXPECT_FLOAT_EQ(binomial_coefficient_log(2004.0,1002.0), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(0.69289774, a.val_.d_.val());\n  EXPECT_NEAR(0, a.d_.val_.val(),1e-8);\n  EXPECT_FLOAT_EQ(0, a.d_.d_.val());\n\n  AVEC p = createAVEC(x.val_.val_);\n  VEC g;\n  a.val_.d_.grad(p,g);\n  EXPECT_FLOAT_EQ(-0.00049862863648177515, g[0]);\n}\nTEST(AgradFwdBinomialCoefficientLog,FvarFvarVar_FvarFvarVar_3rdDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using stan::math::binomial_coefficient_log;\n  using stan::math::binomial_coefficient_log;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 2004.0;\n  x.val_.d_ = 1.0;\n\n  fvar<fvar<var> > y;\n  y.val_.val_ = 1002.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = binomial_coefficient_log(x,y);\n\n  EXPECT_FLOAT_EQ(binomial_coefficient_log(2004.0,1002.0), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(0.69289774, a.val_.d_.val());\n  EXPECT_NEAR(0, a.d_.val_.val(),1e-8);\n  EXPECT_FLOAT_EQ(0.0009975062, a.d_.d_.val());\n\n  AVEC p = createAVEC(x.val_.val_,y.val_.val_);\n  VEC g;\n  a.d_.d_.grad(p,g);\n  EXPECT_FLOAT_EQ(-9.9501847e-07, g[0]);\n  EXPECT_FLOAT_EQ(9.9501847e-07, g[1]);\n}\nTEST(AgradFwdBinomialCoefficientLog,Double_FvarFvarVar_3rdDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using stan::math::binomial_coefficient_log;\n  using stan::math::binomial_coefficient_log;\n\n  double x(2004.0);\n\n  fvar<fvar<var> > y;\n  y.val_.val_ = 1002.0;\n  y.d_.val_ = 1.0;\n  y.val_.d_ = 1.0;\n\n  fvar<fvar<var> > a = binomial_coefficient_log(x,y);\n\n  EXPECT_FLOAT_EQ(binomial_coefficient_log(2004.0,1002.0), a.val_.val_.val());\n  EXPECT_NEAR(0, a.val_.d_.val(),1e-8);\n  EXPECT_NEAR(0, a.d_.val_.val(),1e-8);\n  EXPECT_FLOAT_EQ(-0.0019950124, a.d_.d_.val());\n\n  AVEC p = createAVEC(y.val_.val_);\n  VEC g;\n  a.d_.d_.grad(p,g);\n  EXPECT_NEAR(0, g[0],1e-8);\n}\nTEST(AgradFwdBinomialCoefficientLog,FvarFvarVar_Double_3rdDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using stan::math::binomial_coefficient_log;\n  using stan::math::binomial_coefficient_log;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 2004.0;\n  x.val_.d_ = 1.0;\n  x.d_.val_ = 1.0;\n\n  double y(1002.0);\n\n  fvar<fvar<var> > a = binomial_coefficient_log(x,y);\n\n  EXPECT_FLOAT_EQ(binomial_coefficient_log(2004.0,1002.0), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(0.69289774, a.val_.d_.val());\n  EXPECT_FLOAT_EQ(0.69289774181268948, a.d_.val_.val());\n  EXPECT_FLOAT_EQ(-0.00049862865, a.d_.d_.val());\n\n  AVEC p = createAVEC(x.val_.val_);\n  VEC g;\n  a.d_.d_.grad(p,g);\n  EXPECT_FLOAT_EQ(7.4613968e-07, g[0]);\n}\n\nstruct binomial_coefficient_log_fun {\n  template <typename T0, typename T1>\n  inline \n  typename boost::math::tools::promote_args<T0,T1>::type\n  operator()(const T0 arg1,\n             const T1 arg2) const {\n    return binomial_coefficient_log(arg1,arg2);\n  }\n};\n\nTEST(AgradFwdBinomialCoefficientLog, nan) {\n  binomial_coefficient_log_fun binomial_coefficient_log_;\n  test_nan_mix(binomial_coefficient_log_,3.0,5.0,false);\n}\n", "meta": {"hexsha": "ad2fcac4baccedd572e3a7b114bb1bb26935761e", "size": 10941, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/mix/scal/fun/binomial_coefficient_log_test.cpp", "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/test/unit/math/mix/scal/fun/binomial_coefficient_log_test.cpp", "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/test/unit/math/mix/scal/fun/binomial_coefficient_log_test.cpp", "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": 27.769035533, "max_line_length": 78, "alphanum_fraction": 0.700941413, "num_tokens": 4094, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257126, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.4968795011719439}}
{"text": "// boost\\math\\distributions\\poisson.hpp\r\n\r\n// Copyright John Maddock 2006.\r\n// Copyright Paul A. Bristow 2007.\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// Poisson distribution is a discrete probability distribution.\r\n// It expresses the probability of a number (k) of\r\n// events, occurrences, failures or arrivals occurring in a fixed time,\r\n// assuming these events occur with a known average or mean rate (lambda)\r\n// and are independent of the time since the last event.\r\n// The distribution was discovered by Simeon-Denis Poisson (1781-1840).\r\n\r\n// Parameter lambda is the mean number of events in the given time interval.\r\n// The random variate k is the number of events, occurrences or arrivals.\r\n// k argument may be integral, signed, or unsigned, or floating point.\r\n// If necessary, it has already been promoted from an integral type.\r\n\r\n// Note that the Poisson distribution\r\n// (like others including the binomial, negative binomial & Bernoulli)\r\n// is strictly defined as a discrete function:\r\n// only integral values of k are envisaged.\r\n// However because the method of calculation uses a continuous gamma function,\r\n// it is convenient to treat it as if a continous function,\r\n// and permit non-integral values of k.\r\n// To enforce the strict mathematical model, users should use floor or ceil functions\r\n// on k outside this function to ensure that k is integral.\r\n\r\n// See http://en.wikipedia.org/wiki/Poisson_distribution\r\n// http://documents.wolfram.com/v5/Add-onsLinks/StandardPackages/Statistics/DiscreteDistributions.html\r\n\r\n#ifndef BOOST_MATH_SPECIAL_POISSON_HPP\r\n#define BOOST_MATH_SPECIAL_POISSON_HPP\r\n\r\n#include <boost/math/distributions/fwd.hpp>\r\n#include <boost/math/special_functions/gamma.hpp> // for incomplete gamma. gamma_q\r\n#include <boost/math/special_functions/trunc.hpp> // for incomplete gamma. gamma_q\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> // isnan.\r\n#include <boost/math/special_functions/factorials.hpp> // factorials.\r\n#include <boost/math/tools/roots.hpp> // for root finding.\r\n#include <boost/math/distributions/detail/inv_discrete_quantile.hpp>\r\n\r\n#include <utility>\r\n\r\nnamespace boost\r\n{\r\n  namespace math\r\n  {\r\n     namespace detail{\r\n      template <class Dist>\r\n      inline typename Dist::value_type\r\n         inverse_discrete_quantile(\r\n            const Dist& dist,\r\n            const typename Dist::value_type& p,\r\n            const typename Dist::value_type& guess,\r\n            const typename Dist::value_type& multiplier,\r\n            const typename Dist::value_type& adder,\r\n            const policies::discrete_quantile<policies::integer_round_nearest>&,\r\n            boost::uintmax_t& max_iter);\r\n      template <class Dist>\r\n      inline typename Dist::value_type\r\n         inverse_discrete_quantile(\r\n            const Dist& dist,\r\n            const typename Dist::value_type& p,\r\n            const typename Dist::value_type& guess,\r\n            const typename Dist::value_type& multiplier,\r\n            const typename Dist::value_type& adder,\r\n            const policies::discrete_quantile<policies::integer_round_up>&,\r\n            boost::uintmax_t& max_iter);\r\n      template <class Dist>\r\n      inline typename Dist::value_type\r\n         inverse_discrete_quantile(\r\n            const Dist& dist,\r\n            const typename Dist::value_type& p,\r\n            const typename Dist::value_type& guess,\r\n            const typename Dist::value_type& multiplier,\r\n            const typename Dist::value_type& adder,\r\n            const policies::discrete_quantile<policies::integer_round_down>&,\r\n            boost::uintmax_t& max_iter);\r\n      template <class Dist>\r\n      inline typename Dist::value_type\r\n         inverse_discrete_quantile(\r\n            const Dist& dist,\r\n            const typename Dist::value_type& p,\r\n            const typename Dist::value_type& guess,\r\n            const typename Dist::value_type& multiplier,\r\n            const typename Dist::value_type& adder,\r\n            const policies::discrete_quantile<policies::integer_round_outwards>&,\r\n            boost::uintmax_t& max_iter);\r\n      template <class Dist>\r\n      inline typename Dist::value_type\r\n         inverse_discrete_quantile(\r\n            const Dist& dist,\r\n            const typename Dist::value_type& p,\r\n            const typename Dist::value_type& guess,\r\n            const typename Dist::value_type& multiplier,\r\n            const typename Dist::value_type& adder,\r\n            const policies::discrete_quantile<policies::integer_round_inwards>&,\r\n            boost::uintmax_t& max_iter);\r\n      template <class Dist>\r\n      inline typename Dist::value_type\r\n         inverse_discrete_quantile(\r\n            const Dist& dist,\r\n            const typename Dist::value_type& p,\r\n            const typename Dist::value_type& guess,\r\n            const typename Dist::value_type& multiplier,\r\n            const typename Dist::value_type& adder,\r\n            const policies::discrete_quantile<policies::real>&,\r\n            boost::uintmax_t& max_iter);\r\n     }\r\n    namespace poisson_detail\r\n    {\r\n      // Common error checking routines for Poisson distribution functions.\r\n      // These are convoluted, & apparently redundant, to try to ensure that\r\n      // checks are always performed, even if exceptions are not enabled.\r\n\r\n      template <class RealType, class Policy>\r\n      inline bool check_mean(const char* function, const RealType& mean, RealType* result, const Policy& pol)\r\n      {\r\n        if(!(boost::math::isfinite)(mean) || (mean < 0))\r\n        {\r\n          *result = policies::raise_domain_error<RealType>(\r\n            function,\r\n            \"Mean argument is %1%, but must be >= 0 !\", mean, pol);\r\n          return false;\r\n        }\r\n        return true;\r\n      } // bool check_mean\r\n\r\n      template <class RealType, class Policy>\r\n      inline bool check_mean_NZ(const char* function, const RealType& mean, RealType* result, const Policy& pol)\r\n      { // mean == 0 is considered an error.\r\n        if( !(boost::math::isfinite)(mean) || (mean <= 0))\r\n        {\r\n          *result = policies::raise_domain_error<RealType>(\r\n            function,\r\n            \"Mean argument is %1%, but must be > 0 !\", mean, pol);\r\n          return false;\r\n        }\r\n        return true;\r\n      } // bool check_mean_NZ\r\n\r\n      template <class RealType, class Policy>\r\n      inline bool check_dist(const char* function, const RealType& mean, RealType* result, const Policy& pol)\r\n      { // Only one check, so this is redundant really but should be optimized away.\r\n        return check_mean_NZ(function, mean, result, pol);\r\n      } // bool check_dist\r\n\r\n      template <class RealType, class Policy>\r\n      inline bool check_k(const char* function, const RealType& k, RealType* result, const Policy& pol)\r\n      {\r\n        if((k < 0) || !(boost::math::isfinite)(k))\r\n        {\r\n          *result = policies::raise_domain_error<RealType>(\r\n            function,\r\n            \"Number of events k argument is %1%, but must be >= 0 !\", k, pol);\r\n          return false;\r\n        }\r\n        return true;\r\n      } // bool check_k\r\n\r\n      template <class RealType, class Policy>\r\n      inline bool check_dist_and_k(const char* function, RealType mean, RealType k, RealType* result, const Policy& pol)\r\n      {\r\n        if((check_dist(function, mean, result, pol) == false) ||\r\n          (check_k(function, k, result, pol) == false))\r\n        {\r\n          return false;\r\n        }\r\n        return true;\r\n      } // bool check_dist_and_k\r\n\r\n      template <class RealType, class Policy>\r\n      inline bool check_prob(const char* function, const RealType& p, RealType* result, const Policy& pol)\r\n      { // Check 0 <= p <= 1\r\n        if(!(boost::math::isfinite)(p) || (p < 0) || (p > 1))\r\n        {\r\n          *result = policies::raise_domain_error<RealType>(\r\n            function,\r\n            \"Probability argument is %1%, but must be >= 0 and <= 1 !\", p, pol);\r\n          return false;\r\n        }\r\n        return true;\r\n      } // bool check_prob\r\n\r\n      template <class RealType, class Policy>\r\n      inline bool check_dist_and_prob(const char* function, RealType mean,  RealType p, RealType* result, const Policy& pol)\r\n      {\r\n        if((check_dist(function, mean, result, pol) == false) ||\r\n          (check_prob(function, p, result, pol) == false))\r\n        {\r\n          return false;\r\n        }\r\n        return true;\r\n      } // bool check_dist_and_prob\r\n\r\n    } // namespace poisson_detail\r\n\r\n    template <class RealType = double, class Policy = policies::policy<> >\r\n    class poisson_distribution\r\n    {\r\n    public:\r\n      typedef RealType value_type;\r\n      typedef Policy policy_type;\r\n\r\n      poisson_distribution(RealType mean = 1) : m_l(mean) // mean (lambda).\r\n      { // Expected mean number of events that occur during the given interval.\r\n        RealType r;\r\n        poisson_detail::check_dist(\r\n           \"boost::math::poisson_distribution<%1%>::poisson_distribution\",\r\n          m_l,\r\n          &r, Policy());\r\n      } // poisson_distribution constructor.\r\n\r\n      RealType mean() const\r\n      { // Private data getter function.\r\n        return m_l;\r\n      }\r\n    private:\r\n      // Data member, initialized by constructor.\r\n      RealType m_l; // mean number of occurrences.\r\n    }; // template <class RealType, class Policy> class poisson_distribution\r\n\r\n    typedef poisson_distribution<double> poisson; // Reserved name of type double.\r\n\r\n    // Non-member functions to give properties of the distribution.\r\n\r\n    template <class RealType, class Policy>\r\n    inline const std::pair<RealType, RealType> range(const poisson_distribution<RealType, Policy>& /* dist */)\r\n    { // Range of permissible values for random variable k.\r\n       using boost::math::tools::max_value;\r\n       return std::pair<RealType, RealType>(static_cast<RealType>(0), max_value<RealType>()); // Max integer?\r\n    }\r\n\r\n    template <class RealType, class Policy>\r\n    inline const std::pair<RealType, RealType> support(const poisson_distribution<RealType, Policy>& /* dist */)\r\n    { // Range of supported values for random variable k.\r\n       // This is range where cdf rises from 0 to 1, and outside it, the pdf is zero.\r\n       using boost::math::tools::max_value;\r\n       return std::pair<RealType, RealType>(static_cast<RealType>(0),  max_value<RealType>());\r\n    }\r\n\r\n    template <class RealType, class Policy>\r\n    inline RealType mean(const poisson_distribution<RealType, Policy>& dist)\r\n    { // Mean of poisson distribution = lambda.\r\n      return dist.mean();\r\n    } // mean\r\n\r\n    template <class RealType, class Policy>\r\n    inline RealType mode(const poisson_distribution<RealType, Policy>& dist)\r\n    { // mode.\r\n      BOOST_MATH_STD_USING // ADL of std functions.\r\n      return floor(dist.mean());\r\n    }\r\n\r\n    //template <class RealType, class Policy>\r\n    //inline RealType median(const poisson_distribution<RealType, Policy>& dist)\r\n    //{ // median = approximately lambda + 1/3 - 0.2/lambda\r\n    //  RealType l = dist.mean();\r\n    //  return dist.mean() + static_cast<RealType>(0.3333333333333333333333333333333333333333333333)\r\n    //   - static_cast<RealType>(0.2) / l;\r\n    //} // BUT this formula appears to be out-by-one compared to quantile(half)\r\n    // Query posted on Wikipedia.\r\n    // Now implemented via quantile(half) in derived accessors.\r\n\r\n    template <class RealType, class Policy>\r\n    inline RealType variance(const poisson_distribution<RealType, Policy>& dist)\r\n    { // variance.\r\n      return dist.mean();\r\n    }\r\n\r\n    // RealType standard_deviation(const poisson_distribution<RealType, Policy>& dist)\r\n    // standard_deviation provided by derived accessors.\r\n\r\n    template <class RealType, class Policy>\r\n    inline RealType skewness(const poisson_distribution<RealType, Policy>& dist)\r\n    { // skewness = sqrt(l).\r\n      BOOST_MATH_STD_USING // ADL of std functions.\r\n      return 1 / sqrt(dist.mean());\r\n    }\r\n\r\n    template <class RealType, class Policy>\r\n    inline RealType kurtosis_excess(const poisson_distribution<RealType, Policy>& dist)\r\n    { // skewness = sqrt(l).\r\n      return 1 / dist.mean(); // kurtosis_excess 1/mean from Wiki & MathWorld eq 31.\r\n      // http://mathworld.wolfram.com/Kurtosis.html explains that the kurtosis excess\r\n      // is more convenient because the kurtosis excess of a normal distribution is zero\r\n      // whereas the true kurtosis is 3.\r\n    } // RealType kurtosis_excess\r\n\r\n    template <class RealType, class Policy>\r\n    inline RealType kurtosis(const poisson_distribution<RealType, Policy>& dist)\r\n    { // kurtosis is 4th moment about the mean = u4 / sd ^ 4\r\n      // http://en.wikipedia.org/wiki/Curtosis\r\n      // kurtosis can range from -2 (flat top) to +infinity (sharp peak & heavy tails).\r\n      // http://www.itl.nist.gov/div898/handbook/eda/section3/eda35b.htm\r\n      return 3 + 1 / dist.mean(); // NIST.\r\n      // http://mathworld.wolfram.com/Kurtosis.html explains that the kurtosis excess\r\n      // is more convenient because the kurtosis excess of a normal distribution is zero\r\n      // whereas the true kurtosis is 3.\r\n    } // RealType kurtosis\r\n\r\n    template <class RealType, class Policy>\r\n    RealType pdf(const poisson_distribution<RealType, Policy>& dist, const RealType& k)\r\n    { // Probability Density/Mass Function.\r\n      // Probability that there are EXACTLY k occurrences (or arrivals).\r\n      BOOST_FPU_EXCEPTION_GUARD\r\n\r\n      BOOST_MATH_STD_USING // for ADL of std functions.\r\n\r\n      RealType mean = dist.mean();\r\n      // Error check:\r\n      RealType result = 0;\r\n      if(false == poisson_detail::check_dist_and_k(\r\n        \"boost::math::pdf(const poisson_distribution<%1%>&, %1%)\",\r\n        mean,\r\n        k,\r\n        &result, Policy()))\r\n      {\r\n        return result;\r\n      }\r\n\r\n      // Special case of mean zero, regardless of the number of events k.\r\n      if (mean == 0)\r\n      { // Probability for any k is zero.\r\n        return 0;\r\n      }\r\n      if (k == 0)\r\n      { // mean ^ k = 1, and k! = 1, so can simplify.\r\n        return exp(-mean);\r\n      }\r\n      return boost::math::gamma_p_derivative(k+1, mean, Policy());\r\n    } // pdf\r\n\r\n    template <class RealType, class Policy>\r\n    RealType cdf(const poisson_distribution<RealType, Policy>& dist, const RealType& k)\r\n    { // Cumulative Distribution Function Poisson.\r\n      // The random variate k is the number of occurrences(or arrivals)\r\n      // k argument may be integral, signed, or unsigned, or floating point.\r\n      // If necessary, it has already been promoted from an integral type.\r\n      // Returns the sum of the terms 0 through k of the Poisson Probability Density or Mass (pdf).\r\n\r\n      // But note that the Poisson distribution\r\n      // (like others including the binomial, negative binomial & Bernoulli)\r\n      // is strictly defined as a discrete function: only integral values of k are envisaged.\r\n      // However because of the method of calculation using a continuous gamma function,\r\n      // it is convenient to treat it as if it is a continous function\r\n      // and permit non-integral values of k.\r\n      // To enforce the strict mathematical model, users should use floor or ceil functions\r\n      // outside this function to ensure that k is integral.\r\n\r\n      // The terms are not summed directly (at least for larger k)\r\n      // instead the incomplete gamma integral is employed,\r\n\r\n      BOOST_MATH_STD_USING // for ADL of std function exp.\r\n\r\n      RealType mean = dist.mean();\r\n      // Error checks:\r\n      RealType result = 0;\r\n      if(false == poisson_detail::check_dist_and_k(\r\n        \"boost::math::cdf(const poisson_distribution<%1%>&, %1%)\",\r\n        mean,\r\n        k,\r\n        &result, Policy()))\r\n      {\r\n        return result;\r\n      }\r\n      // Special cases:\r\n      if (mean == 0)\r\n      { // Probability for any k is zero.\r\n        return 0;\r\n      }\r\n      if (k == 0)\r\n      { // return pdf(dist, static_cast<RealType>(0));\r\n        // but mean (and k) have already been checked,\r\n        // so this avoids unnecessary repeated checks.\r\n       return exp(-mean);\r\n      }\r\n      // For small integral k could use a finite sum -\r\n      // it's cheaper than the gamma function.\r\n      // BUT this is now done efficiently by gamma_q function.\r\n      // Calculate poisson cdf using the gamma_q function.\r\n      return gamma_q(k+1, mean, Policy());\r\n    } // binomial cdf\r\n\r\n    template <class RealType, class Policy>\r\n    RealType cdf(const complemented2_type<poisson_distribution<RealType, Policy>, RealType>& c)\r\n    { // Complemented Cumulative Distribution Function Poisson\r\n      // The random variate k is the number of events, occurrences or arrivals.\r\n      // k argument may be integral, signed, or unsigned, or floating point.\r\n      // If necessary, it has already been promoted from an integral type.\r\n      // But note that the Poisson distribution\r\n      // (like others including the binomial, negative binomial & Bernoulli)\r\n      // is strictly defined as a discrete function: only integral values of k are envisaged.\r\n      // However because of the method of calculation using a continuous gamma function,\r\n      // it is convenient to treat it as is it is a continous function\r\n      // and permit non-integral values of k.\r\n      // To enforce the strict mathematical model, users should use floor or ceil functions\r\n      // outside this function to ensure that k is integral.\r\n\r\n      // Returns the sum of the terms k+1 through inf of the Poisson Probability Density/Mass (pdf).\r\n      // The terms are not summed directly (at least for larger k)\r\n      // instead the incomplete gamma integral is employed,\r\n\r\n      RealType const& k = c.param;\r\n      poisson_distribution<RealType, Policy> const& dist = c.dist;\r\n\r\n      RealType mean = dist.mean();\r\n\r\n      // Error checks:\r\n      RealType result = 0;\r\n      if(false == poisson_detail::check_dist_and_k(\r\n        \"boost::math::cdf(const poisson_distribution<%1%>&, %1%)\",\r\n        mean,\r\n        k,\r\n        &result, Policy()))\r\n      {\r\n        return result;\r\n      }\r\n      // Special case of mean, regardless of the number of events k.\r\n      if (mean == 0)\r\n      { // Probability for any k is unity, complement of zero.\r\n        return 1;\r\n      }\r\n      if (k == 0)\r\n      { // Avoid repeated checks on k and mean in gamma_p.\r\n         return -boost::math::expm1(-mean, Policy());\r\n      }\r\n      // Unlike un-complemented cdf (sum from 0 to k),\r\n      // can't use finite sum from k+1 to infinity for small integral k,\r\n      // anyway it is now done efficiently by gamma_p.\r\n      return gamma_p(k + 1, mean, Policy()); // Calculate Poisson cdf using the gamma_p function.\r\n      // CCDF = gamma_p(k+1, lambda)\r\n    } // poisson ccdf\r\n\r\n    template <class RealType, class Policy>\r\n    inline RealType quantile(const poisson_distribution<RealType, Policy>& dist, const RealType& p)\r\n    { // Quantile (or Percent Point) Poisson function.\r\n      // Return the number of expected events k for a given probability p.\r\n      static const char* function = \"boost::math::quantile(const poisson_distribution<%1%>&, %1%)\";\r\n      RealType result = 0; // of Argument checks:\r\n      if(false == poisson_detail::check_prob(\r\n        function,\r\n        p,\r\n        &result, Policy()))\r\n      {\r\n        return result;\r\n      }\r\n      // Special case:\r\n      if (dist.mean() == 0)\r\n      { // if mean = 0 then p = 0, so k can be anything?\r\n         if (false == poisson_detail::check_mean_NZ(\r\n         function,\r\n         dist.mean(),\r\n         &result, Policy()))\r\n        {\r\n          return result;\r\n        }\r\n      }\r\n      if(p == 0)\r\n      {\r\n         return 0; // Exact result regardless of discrete-quantile Policy\r\n      }\r\n      if(p == 1)\r\n      {\r\n         return policies::raise_overflow_error<RealType>(function, 0, Policy());\r\n      }\r\n      typedef typename Policy::discrete_quantile_type discrete_type;\r\n      boost::uintmax_t max_iter = policies::get_max_root_iterations<Policy>();\r\n      RealType guess, factor = 8;\r\n      RealType z = dist.mean();\r\n      if(z < 1)\r\n         guess = z;\r\n      else\r\n         guess = boost::math::detail::inverse_poisson_cornish_fisher(z, p, RealType(1-p), Policy());\r\n      if(z > 5)\r\n      {\r\n         if(z > 1000)\r\n            factor = 1.01f;\r\n         else if(z > 50)\r\n            factor = 1.1f;\r\n         else if(guess > 10)\r\n            factor = 1.25f;\r\n         else\r\n            factor = 2;\r\n         if(guess < 1.1)\r\n            factor = 8;\r\n      }\r\n\r\n      return detail::inverse_discrete_quantile(\r\n         dist,\r\n         p,\r\n         1-p,\r\n         guess,\r\n         factor,\r\n         RealType(1),\r\n         discrete_type(),\r\n         max_iter);\r\n   } // quantile\r\n\r\n    template <class RealType, class Policy>\r\n    inline RealType quantile(const complemented2_type<poisson_distribution<RealType, Policy>, RealType>& c)\r\n    { // Quantile (or Percent Point) of Poisson function.\r\n      // Return the number of expected events k for a given\r\n      // complement of the probability q.\r\n      //\r\n      // Error checks:\r\n      static const char* function = \"boost::math::quantile(complement(const poisson_distribution<%1%>&, %1%))\";\r\n      RealType q = c.param;\r\n      const poisson_distribution<RealType, Policy>& dist = c.dist;\r\n      RealType result = 0;  // of argument checks.\r\n      if(false == poisson_detail::check_prob(\r\n        function,\r\n        q,\r\n        &result, Policy()))\r\n      {\r\n        return result;\r\n      }\r\n      // Special case:\r\n      if (dist.mean() == 0)\r\n      { // if mean = 0 then p = 0, so k can be anything?\r\n         if (false == poisson_detail::check_mean_NZ(\r\n         function,\r\n         dist.mean(),\r\n         &result, Policy()))\r\n        {\r\n          return result;\r\n        }\r\n      }\r\n      if(q == 0)\r\n      {\r\n         return policies::raise_overflow_error<RealType>(function, 0, Policy());\r\n      }\r\n      if(q == 1)\r\n      {\r\n         return 0;  // Exact result regardless of discrete-quantile Policy\r\n      }\r\n      typedef typename Policy::discrete_quantile_type discrete_type;\r\n      boost::uintmax_t max_iter = policies::get_max_root_iterations<Policy>();\r\n      RealType guess, factor = 8;\r\n      RealType z = dist.mean();\r\n      if(z < 1)\r\n         guess = z;\r\n      else\r\n         guess = boost::math::detail::inverse_poisson_cornish_fisher(z, RealType(1-q), q, Policy());\r\n      if(z > 5)\r\n      {\r\n         if(z > 1000)\r\n            factor = 1.01f;\r\n         else if(z > 50)\r\n            factor = 1.1f;\r\n         else if(guess > 10)\r\n            factor = 1.25f;\r\n         else\r\n            factor = 2;\r\n         if(guess < 1.1)\r\n            factor = 8;\r\n      }\r\n\r\n      return detail::inverse_discrete_quantile(\r\n         dist,\r\n         1-q,\r\n         q,\r\n         guess,\r\n         factor,\r\n         RealType(1),\r\n         discrete_type(),\r\n         max_iter);\r\n   } // quantile complement.\r\n\r\n  } // namespace math\r\n} // namespace boost\r\n\r\n// This include must be at the end, *after* the accessors\r\n// for this distribution have been defined, in order to\r\n// keep compilers that support two-phase lookup happy.\r\n#include <boost/math/distributions/detail/derived_accessors.hpp>\r\n#include <boost/math/distributions/detail/inv_discrete_quantile.hpp>\r\n\r\n#endif // BOOST_MATH_SPECIAL_POISSON_HPP\r\n\r\n\r\n\r\n", "meta": {"hexsha": "0f9677039265b0d78e7d221ee2e13c0b807921a4", "size": 23636, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/math/distributions/poisson.hpp", "max_stars_repo_name": "PXLVision/opengv", "max_stars_repo_head_hexsha": "e48f77da4db7b8cee36ec677ed4ff5c5354571bb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-10-30T09:36:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T17:00:06.000Z", "max_issues_repo_path": "third_party/boost/math/distributions/poisson.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": "third_party/boost/math/distributions/poisson.hpp", "max_forks_repo_name": "PXLVision/opengv", "max_forks_repo_head_hexsha": "e48f77da4db7b8cee36ec677ed4ff5c5354571bb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2015-03-09T09:03:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-05T15:08:41.000Z", "avg_line_length": 40.0610169492, "max_line_length": 125, "alphanum_fraction": 0.62155187, "num_tokens": 5439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257127, "lm_q2_score": 0.6370308082623216, "lm_q1q2_score": 0.4968795011719439}}
{"text": "/**\n * @file upwindfinitevolume.cc\n * @brief NPDE homework UpwindFiniteVolume code\n * @author Philipp Egg\n * @date 08.09.2020\n * @copyright Developed at ETH Zurich\n */\n\n#include \"upwindfinitevolume.h\"\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <cmath>\n#include <stdexcept>\n\nnamespace UpwindFiniteVolume {\n\n/* SAM_LISTING_BEGIN_1 */\nEigen::Matrix<double, 2, 3> gradbarycoordinates(\n    const Eigen::Matrix<double, 2, 3> &triangle) {\n  Eigen::Matrix3d X;\n  // Solve for the coefficients of the barycentric coordinate functions\n  X.block<3, 1>(0, 0) = Eigen::Vector3d::Ones();\n  X.block<3, 2>(0, 1) = triangle.transpose();\n  return X.inverse().block<2, 3>(1, 0);\n}\n/* SAM_LISTING_END_1 */\n\n/* SAM_LISTING_BEGIN_2 */\nEigen::Vector2d computeCircumcenters(const Eigen::Vector2d &a1,\n                                     const Eigen::Vector2d &a2,\n                                     const Eigen::Vector2d &a3) {\n  //====================\n  // Your code goes here\n  //====================\n  return Eigen::Vector2d::Zero();\n}\n/* SAM_LISTING_END_2 */\n\n}  // namespace UpwindFiniteVolume\n", "meta": {"hexsha": "5f75201ab28c47dcca0f8289cdce93325bdbd51a", "size": 1093, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/UpwindFiniteVolume/templates/upwindfinitevolume.cc", "max_stars_repo_name": "kryo4096/NPDECODES", "max_stars_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/UpwindFiniteVolume/templates/upwindfinitevolume.cc", "max_issues_repo_name": "kryo4096/NPDECODES", "max_issues_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/UpwindFiniteVolume/templates/upwindfinitevolume.cc", "max_forks_repo_name": "kryo4096/NPDECODES", "max_forks_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 26.6585365854, "max_line_length": 71, "alphanum_fraction": 0.6285452882, "num_tokens": 307, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.496879496937932}}
{"text": "/**\n * \\ file DerivativeFilter.cpp\n */\n\n#include <array>\n#include <fstream>\n\n#include <ATK/config.h>\n\n#include <ATK/Tools/DerivativeFilter.h>\n#include <ATK/Mock/SimpleSinusGeneratorFilter.h>\n\n#include <boost/math/constants/constants.hpp>\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_NO_MAIN\n#include <boost/test/unit_test.hpp>\n\nconstexpr gsl::index PROCESSSIZE = 1000;\nconstexpr gsl::index SAMPLING_RATE = 2*1024*1024;\nconstexpr gsl::index freq = 1024;\nconstexpr gsl::index offset = SAMPLING_RATE / (4 * freq);\n\nBOOST_AUTO_TEST_CASE( DerivativeFilter_const_sin1k )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(SAMPLING_RATE);\n  generator.set_amplitude(1);\n  generator.set_frequency(freq);\n  \n  ATK::DerivativeFilter<double> filter;\n  filter.set_input_sampling_rate(SAMPLING_RATE);\n  filter.set_output_sampling_rate(SAMPLING_RATE);\n  \n  filter.set_input_port(0, generator, 0);\n  filter.process(PROCESSSIZE);\n  \n  auto sin = generator.get_output_array(0);\n  auto array = filter.get_output_array(0);\n  \n  auto coeff = 2 * freq * boost::math::constants::pi<double>() / SAMPLING_RATE;\n  \n  for(size_t i = 1; i < PROCESSSIZE - offset; ++i)\n  {\n    BOOST_CHECK_CLOSE(array[i], coeff * sin[i + offset], 5);\n  }\n}\n", "meta": {"hexsha": "c088843412d2b145f0e4d5a49968e196f0f160bd", "size": 1255, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/Tools/DerivativeFilter.cpp", "max_stars_repo_name": "D-J-Roberts/AudioTK", "max_stars_repo_head_hexsha": "accf009d7238f32702eb1d5ee23c5148fc68e3bd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 249.0, "max_stars_repo_stars_event_min_datetime": "2015-01-05T13:36:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T18:47:46.000Z", "max_issues_repo_path": "tests/Tools/DerivativeFilter.cpp", "max_issues_repo_name": "D-J-Roberts/AudioTK", "max_issues_repo_head_hexsha": "accf009d7238f32702eb1d5ee23c5148fc68e3bd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 22.0, "max_issues_repo_issues_event_min_datetime": "2015-07-28T15:20:24.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-11T14:18:19.000Z", "max_forks_repo_path": "tests/Tools/DerivativeFilter.cpp", "max_forks_repo_name": "D-J-Roberts/AudioTK", "max_forks_repo_head_hexsha": "accf009d7238f32702eb1d5ee23c5148fc68e3bd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 48.0, "max_forks_repo_forks_event_min_datetime": "2015-08-15T12:08:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-07T02:33:07.000Z", "avg_line_length": 26.1458333333, "max_line_length": 79, "alphanum_fraction": 0.7450199203, "num_tokens": 330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.49687949693793193}}
{"text": "#include <Eigen/Geometry>\n#include <pybind11/eigen.h>\n#include <pybind11/pybind11.h>\n\nnamespace py = pybind11;\n\ntemplate <typename T>\nvoid initEigenQuaternion(py::module &m, const char *name) {\n  // TODO: Make this useful, not just a fancy tuple\n  using QuaternionT = Eigen::Quaternion<T>;\n  using Vector3T = Eigen::Vector3<T>;\n  py::class_<QuaternionT>(m, name, py::module_local())\n      .def(py::init<const T &, const T &, const T &, const T &>())\n      .def_property(\"w\", [](const QuaternionT &self) { return self.w(); },\n                    [](QuaternionT &self, T val) { self.w() = val; })\n      .def_property(\"x\", [](const QuaternionT &self) { return self.x(); },\n                    [](QuaternionT &self, T val) { self.x() = val; })\n      .def_property(\"y\", [](const QuaternionT &self) { return self.y(); },\n                    [](QuaternionT &self, T val) { self.y() = val; })\n      .def_property(\"z\", [](const QuaternionT &self) { return self.z(); },\n                    [](QuaternionT &self, T val) { self.z() = val; })\n      .def(\"to_rotation_matrix\", &QuaternionT::toRotationMatrix)\n      .def_static(\"from_two_vectors\", [](const Vector3T &a, const Vector3T &b) {\n        return QuaternionT::FromTwoVectors(a, b);\n      });\n}\n\nvoid initEigenGeometry(py::module &m) {\n  initEigenQuaternion<float>(m, \"Quaternionf\");\n  initEigenQuaternion<double>(m, \"Quaterniond\");\n}\n", "meta": {"hexsha": "441055bd0b0fe61fa80d15465933489433272de0", "size": 1378, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/python_bindings/py_eigen_geometry.cpp", "max_stars_repo_name": "ONLYA/RoboGrammar", "max_stars_repo_head_hexsha": "4b9725739b24dc9df4049866c177db788b1e458f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 156.0, "max_stars_repo_stars_event_min_datetime": "2020-10-02T14:33:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T22:30:30.000Z", "max_issues_repo_path": "examples/python_bindings/py_eigen_geometry.cpp", "max_issues_repo_name": "ONLYA/RoboGrammar", "max_issues_repo_head_hexsha": "4b9725739b24dc9df4049866c177db788b1e458f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2020-12-14T01:24:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T10:01:16.000Z", "max_forks_repo_path": "examples/python_bindings/py_eigen_geometry.cpp", "max_forks_repo_name": "ONLYA/RoboGrammar", "max_forks_repo_head_hexsha": "4b9725739b24dc9df4049866c177db788b1e458f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 43.0, "max_forks_repo_forks_event_min_datetime": "2020-10-02T00:01:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-06T17:02:38.000Z", "avg_line_length": 43.0625, "max_line_length": 80, "alphanum_fraction": 0.6044992743, "num_tokens": 369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541067, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.4968794969379318}}
{"text": "/**\n * @copyright   Copyright (c) 2021, Swift Engineering Inc.\n * @license     Licensed under the MIT license. See LICENSE for details.\n */\n#include <gtest/gtest.h>\n\n#include <string>\n#include <sstream>\n#include <boost/array.hpp>\n#include <stdio.h>\n#include <ignition/math/Pose3.hh>\n#include <ignition/math/Vector3.hh>\n#include <ignition/math/Quaternion.hh>\n\n#include \"Coordinate_Utils.hpp\"\n\n// #define ASSERT_PERCENT_NEAR(value, tolerance)\n\nTEST(CoordUtilsTest, RotationFromBasis) {\n    // Given\n    ignition::math::Vector3d forward(0, 0, 1);\n    ignition::math::Vector3d upward(-1, 0, 0);\n\n    ignition::math::Vector3d aVec(0.81165, -0.90368, 9.9767);\n\n    ignition::math::Quaterniond rotAtoB = avionics_sim::Coordinate_Utils::QuatFromBasis(forward, upward);\n\n    ignition::math::Vector3d bVec = rotAtoB.RotateVector(aVec);\n\n    ignition::math::Vector3d expectedBVec(-0.81165, 0.90368, 9.9767);\n\n    for (int i = 0; i < 3; i++) {\n        EXPECT_NEAR(bVec[i], expectedBVec[i], 0.01);\n    }\n}\n\nstruct CoordUtilsParams {\n    std::string case_name;\n    ignition::math::Pose3d poseInWorld;\n    ignition::math::Vector3d vecToRotate;\n    ignition::math::Vector3d vecExpected;\n};\n\nclass CoordUtilsParamTest : public ::testing::TestWithParam<CoordUtilsParams> {\n  protected:\n    // Some expensive resource shared by all tests.\n    // static T* shared_resource_;\n\n    /**\n     * Sets up the test suite, called before all test cases are run\n     */\n    static void SetUpTestSuite() {\n    }\n\n    /**\n     * Tears down the test suite, called after all test cases are run\n     */\n    static void TearDownTestSuite() {\n    }\n\n    // You can define per-test set-up logic as usual.\n    virtual void SetUp() {\n    }\n\n    // You can define per-test tear-down logic as usual.\n    virtual void TearDown() {\n    }\n};\n\nTEST_P(CoordUtilsParamTest, ProjectVectorGlobalTest) {\n    CoordUtilsParams params = GetParam();\n\n    ignition::math::Vector3d vecResult;\n    avionics_sim::Coordinate_Utils::project_vector_global(params.poseInWorld, params.vecToRotate, &vecResult);\n\n    for (int i = 0; i < 3; i++) {\n        EXPECT_NEAR(vecResult[i], params.vecExpected[i], 0.01);\n    }\n}\n\nconst std::vector<CoordUtilsParams> params{\n    {\n        \"Test 1\",\n        ignition::math::Pose3d(0, 0, 0, -0.09, 1.48, 0.1),\n        ignition::math::Vector3d(10, 1, 0.1),\n        ignition::math::Vector3d(0.81165, -0.90368, 9.97673)\n    }\n};\n\nINSTANTIATE_TEST_CASE_P(CoordUtilsTest,\n                        CoordUtilsParamTest,\n                        ::testing::ValuesIn(params));\n", "meta": {"hexsha": "314a5742442971583c43d3e8451240070a902c9a", "size": 2538, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/CoordUtilsTest.cpp", "max_stars_repo_name": "SwiftEngineering/avionics_sim", "max_stars_repo_head_hexsha": "8fa3ef497137dd54966ff9de43cbcf2bfbf82d96", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/unit/CoordUtilsTest.cpp", "max_issues_repo_name": "SwiftEngineering/avionics_sim", "max_issues_repo_head_hexsha": "8fa3ef497137dd54966ff9de43cbcf2bfbf82d96", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/unit/CoordUtilsTest.cpp", "max_forks_repo_name": "SwiftEngineering/avionics_sim", "max_forks_repo_head_hexsha": "8fa3ef497137dd54966ff9de43cbcf2bfbf82d96", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.2903225806, "max_line_length": 110, "alphanum_fraction": 0.6591804571, "num_tokens": 713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257127, "lm_q2_score": 0.6370308013713525, "lm_q1q2_score": 0.496879495797037}}
{"text": "#include <iostream>\n#include <cmath>\n#include <stdlib.h>\n#include <vector>\n\n#include <Eigen/Core>\n#include <gtest/gtest.h>\n\n#include \"test/utils.hpp\"\n\n#include \"ldaplusplus/optimization/MultinomialLogisticRegression.hpp\"\n#include \"ldaplusplus/optimization/GradientDescent.hpp\"\n#include \"ldaplusplus/optimization/SecondOrderLogisticRegressionApproximation.hpp\"\n\nusing namespace Eigen;\nusing namespace ldaplusplus::optimization;\n\n\ntemplate <typename T>\nclass TestSecondOrderMultinomialLogisticRegression : public ParameterizedTest<T> {};\n\nTYPED_TEST_CASE(TestSecondOrderMultinomialLogisticRegression, ForFloatAndDouble);\n\n/**\n  * In this test we check if the gradient is correct by appling\n  * a finite difference method.\n  */\nTYPED_TEST(TestSecondOrderMultinomialLogisticRegression, Gradient) {\n    // Gradient checking should only be made with a double type\n    if (is_float<TypeParam>::value) {\n        return;\n    }\n\n    // eta is typically of size KxC, where K is the number of topics and C the\n    // number of different classes.\n    // Here we choose randomly for conviency K=10 and C=5\n    MatrixX<TypeParam> eta = MatrixX<TypeParam>::Random(10, 5);\n    // X is of size KxD, where D is the total number of documents.\n    // In our case we have chosen D=15\n    MatrixX<TypeParam> X = MatrixX<TypeParam>::Random(10, 1);\n    // y is vector of size Dx1\n    VectorXi y(1);\n    for (int i=0; i<1; i++) {\n        y(i) = rand() % (int)5; \n    }\n    std::vector<MatrixX<TypeParam> > X_var = {MatrixX<TypeParam>::Random(10, 10).array().abs()};\n\n    TypeParam L = 1;\n    SecondOrderLogisticRegressionApproximation<TypeParam> mlr(X, X_var, y, L);\n\n    // grad is the gradient according to the equation\n    // implemented in MultinomialLogisticRegression.cpp \n    // gradient function\n    // grad is of same size as eta, which is KxC\n    MatrixX<TypeParam> grad(10, 5);\n\n    // Calculate the gradients\n    mlr.gradient(eta, grad);\n\n    // Grad's approximation\n    TypeParam grad_hat;\n    TypeParam t = 1e-6;\n\n    for (int i=0; i < eta.rows(); i++) {\n        for (int j=0; j < eta.cols(); j++) {\n            eta(i, j) += t;\n            TypeParam ll1 = mlr.value(eta);\n            eta(i, j) -= 2*t;\n            TypeParam ll2 = mlr.value(eta);\n\n            // Compute gradients approximation\n            grad_hat = (ll1 - ll2) / (2 * t);\n\n            auto absolute_error = std::abs(grad(i, j) - grad_hat);\n            if (grad_hat != 0) {\n                auto relative_error = absolute_error / std::abs(grad_hat);\n                EXPECT_TRUE(\n                    relative_error < 1e-4 ||\n                    absolute_error < 1e-5\n                ) << relative_error << \" \" << absolute_error;\n            }\n            else {\n                EXPECT_LT(absolute_error, 1e-5);\n            }\n        }\n    }\n}\n\n\nTYPED_TEST(TestSecondOrderMultinomialLogisticRegression, MinimizerOverfitSmall) {\n    MatrixX<TypeParam> X(2, 10);\n    VectorXi y(10);\n\n    X << 0.6097662 ,  0.53395565,  0.9499446 ,  0.67289898,  0.94173948,\n         0.56675891,  0.80363783,  0.85303565,  0.15903886,  0.99518533,\n         0.41655682,  0.29256121,  0.36103228,  0.29899503,  0.4957268 ,\n         -0.04277318, -0.28038614, -0.12334621, -0.17497722,  0.1492248;\n    y << 0, 0, 0, 0, 0, 1, 1, 1, 1, 1;\n    std::vector<MatrixX<TypeParam> > X_var;\n    for (int i=0; i<10; i++) {\n        //X_var.push_back(MatrixX<TypeParam>::Random(2, 2).array().abs() * 0.01);\n        //X_var.push_back(MatrixX<TypeParam>::Zero(2, 2));\n        VectorX<TypeParam> a = VectorX<TypeParam>::Random(2).array() * 0.01;\n        X_var.push_back(\n            a * a.transpose()\n        );\n    }\n\n    SecondOrderLogisticRegressionApproximation<TypeParam> mlr(X, X_var, y, 0);\n    MatrixX<TypeParam> eta = MatrixX<TypeParam>::Zero(2, 3);\n\n    GradientDescent<SecondOrderLogisticRegressionApproximation<TypeParam>, MatrixX<TypeParam>> minimizer(\n        std::make_shared<\n            ArmijoLineSearch<\n                SecondOrderLogisticRegressionApproximation<TypeParam>,\n                MatrixX<TypeParam>\n            >\n        >(),\n        [](TypeParam value, TypeParam gradNorm, size_t iterations) {\n            return iterations < 5000;\n        }\n    );\n    minimizer.minimize(mlr, eta);\n\n    EXPECT_GT(0.1, mlr.value(eta));\n}\n", "meta": {"hexsha": "e9e5d06ebba76b80d9bd6c051c458980a31c3bad", "size": 4264, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_second_order_mlr_approximation.cpp", "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": "test/test_second_order_mlr_approximation.cpp", "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": "test/test_second_order_mlr_approximation.cpp", "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": 33.5748031496, "max_line_length": 105, "alphanum_fraction": 0.623358349, "num_tokens": 1234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257126, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.49687949042212987}}
{"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_NEXTPOW2_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_NEXTPOW2_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n    @ingroup group-ieee\n    This function object returns the smallest integer n such that\n    `saturated_(abs)(x)` is less or equal to \\f$2^n\\f$\n\n\n\n    @par Header <boost/simd/function/nextpow2.hpp>\n\n    @par Example:\n\n      @snippet nextpow2.cpp nextpow2\n\n    @par Possible output:\n\n      @snippet nextpow2.txt nextpow2\n\n  **/\n  as_integer_t<Value> nextpow2(Value const& x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/nextpow2.hpp>\n#include <boost/simd/function/simd/nextpow2.hpp>\n\n#endif\n", "meta": {"hexsha": "f4154192a4567f2d3c7ab7aa8bd89517ff35bd46", "size": 1059, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/nextpow2.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/nextpow2.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/nextpow2.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": 24.0681818182, "max_line_length": 100, "alphanum_fraction": 0.5882908404, "num_tokens": 237, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186787341014, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4968388138224445}}
{"text": "#include <frovedis.hpp>\n#include <frovedis/matrix/pca.hpp>\n\n#include <boost/program_options.hpp>\n\nusing namespace boost;\nusing namespace frovedis;\nusing namespace std;\n\nvoid do_pca(const string& input_matrix,\n            const string& pca_directions_file,\n            const string& pca_scores_file,\n            const string& eigen_values_file,\n            const string& explained_variance_ratio_file,\n            const string& singular_values_file,\n            int k,\n            bool to_standardize,\n            bool binary) {\n  time_spent t(DEBUG);\n  rowmajor_matrix<double> matrix;\n  if(binary) {\n    matrix = make_rowmajor_matrix_loadbinary<double>(input_matrix);\n  } else {\n    matrix = make_rowmajor_matrix_load<double>(input_matrix);\n  }\n  t.show(\"load time: \");\n  colmajor_matrix<double> pca_directions;\n  colmajor_matrix<double> pca_scores;\n  std::vector<double> eigen_values;\n  std::vector<double> explained_variance_ratio;\n  std::vector<double> singular_values;\n  std::vector<double> mean; // not used\n  double noise_variance; // not used\n\n  pca(std::move(matrix), pca_directions, pca_scores, eigen_values,\n      explained_variance_ratio, singular_values, mean, noise_variance,\n      k, to_standardize);\n  t.show(\"PCA: \");\n  if(binary) {\n    pca_directions.savebinary(pca_directions_file);\n    if(pca_scores_file != \"\") {\n      pca_scores.savebinary(pca_scores_file);\n    }\n    if(eigen_values_file != \"\") {\n      make_dvector_scatter(eigen_values).savebinary(eigen_values_file);\n    }\n    if(explained_variance_ratio_file != \"\") {\n      make_dvector_scatter(explained_variance_ratio).\n        savebinary(explained_variance_ratio_file);\n    }\n    if(singular_values_file != \"\") {\n      make_dvector_scatter(singular_values).\n        savebinary(singular_values_file);\n    }\n  } else {\n    pca_directions.save(pca_directions_file);\n    if(pca_scores_file != \"\") {\n      pca_scores.save(pca_scores_file);\n    }\n    if(eigen_values_file != \"\") {\n      make_dvector_scatter(eigen_values).saveline(eigen_values_file);\n    }\n    if(explained_variance_ratio_file != \"\") {\n      make_dvector_scatter(explained_variance_ratio).\n        saveline(explained_variance_ratio_file);\n    }\n    if(singular_values_file != \"\") {\n      make_dvector_scatter(singular_values).\n        saveline(singular_values_file);\n    }\n  }\n  t.show(\"save time: \");\n}\n\nint main(int argc, char* argv[]) {\n  use_frovedis use(argc, argv);\n\n  using namespace boost::program_options;\n\n  options_description opt(\"option\");\n  opt.add_options()\n    (\"help,h\", \"print help\")\n    (\"input,i\", value<string>(), \"input matrix\")\n    (\"pca_directions,d\", value<string>(),\n     \"PCA directions (components in scikit-learn)\")\n    (\"pca_scores,c\", value<string>(),\n     \"PCA score (no counter part in scikit-learn) [option]\")\n    (\"eigen_values,e\", value<string>(),\n     \"eigen values (explained_variance in scikit-learn) [option]\")\n    (\"explained_variance_ratio,r\", value<string>(),\n     \"explained variance ratio [option]\")\n    (\"singular_values,s\", value<string>(), \"singular values [option]\")\n    (\"to_standardize,t\", \"standardize the input [default: false]\")\n    (\"k,k\", value<int>(), \"number of principal components to compute\")\n    (\"verbose\", \"set loglevel DEBUG\")\n    (\"verbose2\", \"set loglevel TRACE\")\n    (\"binary,b\", \"use binary input/output\");\n\n  variables_map argmap;\n  store(command_line_parser(argc,argv).options(opt).allow_unregistered().\n        run(), argmap);\n  notify(argmap);\n  string input, pca_directions, pca_scores, eigen_values,\n    explained_variance_ratio, singular_values;\n  int k;\n  bool binary = false;\n  bool to_standardize = false;\n  \n  if(argmap.count(\"help\")){\n    cerr << opt << endl;\n    return 1;\n  }\n\n  if(argmap.count(\"input\")){\n    input = argmap[\"input\"].as<string>();\n  } else {\n    cerr << \"input is not specified\" << endl;\n    cerr << opt << endl;\n    return 1;\n  }\n\n  if(argmap.count(\"pca_directions\")){\n    pca_directions = argmap[\"pca_directions\"].as<string>();\n  } else {\n    cerr << \"file to store PCA directions is not specified\" << endl;\n    cerr << opt << endl;\n    return 1;\n  }\n\n  if(argmap.count(\"pca_scores\")){\n    pca_scores = argmap[\"pca_scores\"].as<string>();\n  }\n\n  if(argmap.count(\"eigen_values\")){\n    eigen_values = argmap[\"eigen_values\"].as<string>();\n  }\n\n  if(argmap.count(\"explained_variance_ratio\")){\n    explained_variance_ratio = argmap[\"explained_variance_ratio\"].as<string>();\n  }\n\n  if(argmap.count(\"singular_values\")){\n    singular_values = argmap[\"singular_values\"].as<string>();\n  }\n\n  if(argmap.count(\"to_standardize\")){\n    to_standardize = true;\n  }\n\n  if(argmap.count(\"k\")){\n    k = argmap[\"k\"].as<int>();\n  } else {\n    cerr << \"number of singular value to compute is not specified\" << endl;\n    cerr << opt << endl;\n    return 1;\n  }\n\n  if(argmap.count(\"binary\")){\n    binary = true;\n  }\n\n  if(argmap.count(\"verbose\")){\n    set_loglevel(DEBUG);\n  }\n\n  if(argmap.count(\"verbose2\")){\n    set_loglevel(TRACE);\n  }\n\n  try {\n    do_pca(input, pca_directions, pca_scores, eigen_values,\n           explained_variance_ratio, singular_values, k, to_standardize, binary);\n  } catch (std::exception& e) {\n    cerr << e.what() << endl;\n    return 1;\n  }\n}\n", "meta": {"hexsha": "bc93207a301e03b693e2c8b4e9d41977310059e1", "size": 5186, "ext": "cc", "lang": "C++", "max_stars_repo_path": "samples/pca/pca.cc", "max_stars_repo_name": "XpressAI/frovedis", "max_stars_repo_head_hexsha": "bda0f2c688fb832671c5b542dd8df1c9657642ff", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 63.0, "max_stars_repo_stars_event_min_datetime": "2018-06-21T14:11:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T11:24:36.000Z", "max_issues_repo_path": "samples/pca/pca.cc", "max_issues_repo_name": "XpressAI/frovedis", "max_issues_repo_head_hexsha": "bda0f2c688fb832671c5b542dd8df1c9657642ff", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2018-09-22T14:01:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-27T16:11:05.000Z", "max_forks_repo_path": "samples/pca/pca.cc", "max_forks_repo_name": "XpressAI/frovedis", "max_forks_repo_head_hexsha": "bda0f2c688fb832671c5b542dd8df1c9657642ff", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2018-08-23T15:59:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T06:47:22.000Z", "avg_line_length": 29.1348314607, "max_line_length": 81, "alphanum_fraction": 0.6639028153, "num_tokens": 1284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186787341014, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4968388138224445}}
{"text": "\n/******************************************************************************\n\n  Computation of a convex hull in 3D for a point cloud.\n\n  Copyright (c) 2013\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 CONVEX_HULL_3D_HPP_1CB416FB_1F43_4159_A19B_202B43247622_\n#define CONVEX_HULL_3D_HPP_1CB416FB_1F43_4159_A19B_202B43247622_\n\n#include <set>\n#include <map>\n#include <complex>\n#include <algorithm>\n#include <boost/assert.hpp>\n\n#include \"bo/core/vector.hpp\"\n#include \"bo/core/mesh.hpp\"\n#include \"bo/core/triangle.hpp\"\n\nnamespace bo {\nnamespace surfaces {\n\n// Computes the convex hull of the given points using the incremental algorithm (Michael Kallay,\n// \"The Complexity of Incremental Convex Hull Algorithms in Rd\" Inf. Process. Lett. 19(4): 197 (1984)).\n// The input points must be not coplanar.\ntemplate <typename RealType>\nclass IncrementalConvexHull3D\n{\npublic:\n    typedef bo::Vector<RealType, 3> Point3D;\n    typedef std::vector<Point3D> Points3D;\n    typedef bo::Triangle<Point3D> Face3D;\n    typedef std::vector<Face3D> Faces3D;\n    typedef bo::Mesh<RealType> Mesh;\n\n    IncrementalConvexHull3D(const Points3D &points)\n    {\n        // Remove all duplicate points.\n        std::set<Point3D> uniq(points.begin(), points.end());\n        points_ = Points3D(uniq.begin(), uniq.end());\n\n        // Compute the convex hull.\n        initialize_convex_hull();\n        expand_convex_hull();\n    }\n\n    // Returns the convex hull as a mesh.\n    Mesh get_mesh()\n    {\n        Mesh mesh(faces_.size());\n\n        // Create a reference map (Point3D -> indices of the mesh vertices).\n        std::map<Point3D, std::size_t> mymap;\n\n        // Fill in the mesh.\n        for (typename FaceSet3D::const_iterator it = faces_.begin(); it != faces_.end(); ++it)\n        {\n            Face3D f = *it;\n\n            // Add the vertices.\n            for (std::size_t i = 0; i < 3; ++i)\n            {\n                Point3D p = f[i];\n\n                // If the current vertex was not used before, add it.\n                if (mymap.find(p) == mymap.end())\n                {\n                    std::size_t index = mesh.add_vertex(p);\n                    mymap[p] = index;\n                }\n            }\n\n            // Add the face.\n            mesh.add_face(typename Mesh::Face(mymap[f.A()], mymap[f.B()], mymap[f.C()]));\n        }\n\n        return mesh;\n    }\n\n    // Returns the convex hull as the collection of faces.\n    Faces3D get_faces()\n    {\n        return Faces3D(faces_.begin(), faces_.end());\n    }\n\n    // Computes the volume of the convex hull using the discrete case\n    // of the Gauss-Ostrogradsky's Divergence theorem.\n    RealType get_volume()\n    {\n        RealType v = 0;\n\n        Point3D mass = centroid();\n\n        for (typename FaceSet3D::const_iterator it = faces_.begin();\n             it != faces_.end(); ++it)\n        {\n            Face3D f = *it;\n\n            // Normal vector must be normalized.\n            Point3D n = normal(f);\n            n /= n.euclidean_norm();\n\n            // Face barycenter.\n            Point3D c = (f.A() + f.B() + f.C()) / 3;\n\n            // Direct the face normal outside the volume.\n            Point3D in_direction = mass - c;\n            if (n * in_direction > 0)\n                n = -n;\n\n            RealType a = area(f);\n\n            BOOST_ASSERT(a >= 0);\n\n            v += (n * c) * a;\n        }\n\n        BOOST_ASSERT(v >= 0);\n\n        return v / 3;\n    }\n\nprivate:\n\n    // Faces comparator used for the set container.\n    struct FaceCompare\n    {\n        bool operator()(const Face3D &f1, const Face3D &f2) const\n        {\n            typedef std::set<Point3D> PointSet3D;\n\n            // Sort the vertices using the sorted set.\n            PointSet3D fs1;\n            fs1.insert(f1.A());\n            fs1.insert(f1.B());\n            fs1.insert(f1.C());\n\n            PointSet3D fs2;\n            fs2.insert(f2.A());\n            fs2.insert(f2.B());\n            fs2.insert(f2.C());\n\n            BOOST_ASSERT(fs1.size() == fs2.size());\n\n            typename PointSet3D::const_iterator it1 = fs1.begin();\n            typename PointSet3D::const_iterator it2 = fs2.begin();\n\n            while (it1 != fs1.end() && it2 != fs2.end())\n            {\n                if (*it1 < *it2)\n                    return true;\n                if (*it2 < *it1)\n                    return false;\n\n                ++it1;\n                ++it2;\n            }\n\n            return false;\n        }\n    };\n\n    typedef std::set<Face3D, FaceCompare> FaceSet3D;\n\n    // Finds the initial tetrahedron.\n    void initialize_convex_hull()\n    {\n        const RealType kEpsilon(0.001);\n\n        if (points_.size() >= 4)\n        {\n            typedef typename Points3D::iterator Iterator;\n\n            for (Iterator it1 = points_.begin(); it1 != points_.end() - 3; ++it1)\n                for (Iterator it2 = it1 + 1; it2 != points_.end() - 2; ++it2)\n                    for (Iterator it3 = it2 + 1; it3 != points_.end() - 1; ++it3)\n                    {\n                        Point3D v1 = *it2 - *it1;\n                        Point3D v2 = *it3 - *it1;\n\n                        // Only if non-collinear.\n                        if (std::abs(std::abs(v1 * v2) -\n                                     v1.euclidean_norm() * v2.euclidean_norm()) > kEpsilon)\n                        {\n                            Point3D c = v1.cross_product(v2);\n\n                            for (Iterator it4 = it3 + 1; it4 != points_.end(); ++it4)\n                            {\n                                Point3D v3 = *it4 - *it1;\n\n                                // Only if non-planar.\n                                if (std::abs(c * v3) > kEpsilon)\n                                {\n                                    // Create faces of the initial tetrahedron.\n                                    insert_tetrahedron(*it1, *it2, *it3, *it4);\n\n                                    // Remove the points from the list.\n                                    points_.erase(it4);\n                                    points_.erase(it3);\n                                    points_.erase(it2);\n                                    points_.erase(it1);\n\n                                    return;\n                                }\n                            }\n                        }\n                    }\n        }\n    }\n\n    // Inserts faces of the tetrahedron.\n    void insert_tetrahedron(const Point3D &p1, const Point3D &p2, const Point3D &p3, const Point3D &p4)\n    {\n        process_face(Face3D(p1, p2, p3));\n        process_face(Face3D(p1, p2, p4));\n        process_face(Face3D(p2, p3, p4));\n        process_face(Face3D(p3, p1, p4));\n    }\n\n    // Inserts the face if it is not in the set yet, otherwise deletes it from the set.\n    void process_face(const Face3D &f)\n    {\n        typename FaceSet3D::iterator it = faces_.find(f);\n\n        if (it == faces_.end())\n        {\n            faces_.insert(f);\n        }\n        else\n        {\n            faces_.erase(it);\n        }\n    }\n\n    // Incremental expansion of the convex hull.\n    void expand_convex_hull()\n    {\n        const RealType kEpsilon(0.0001);\n\n        if (faces_.size() > 3)\n        {\n            for (typename Points3D::const_iterator itp = points_.begin(); itp != points_.end(); ++itp)\n            {\n                Point3D p = *itp;\n\n                Point3D c = centroid();\n\n                Faces3D visible_faces;\n\n                // Find the \"visible\" faces.\n                for (typename FaceSet3D::const_iterator it = faces_.begin(); it != faces_.end(); ++it)\n                {\n                    Face3D f = *it;\n                    Point3D v_c = c - f.A();\n                    v_c = v_c / v_c.euclidean_norm();\n                    Point3D v_p = p - f.A();\n                    v_p = v_p / v_p.euclidean_norm();\n\n                    Point3D n = normal(f);\n                    n = n / n.euclidean_norm();\n\n                    RealType dot_c = n * v_c;\n                    RealType dot_p = n * v_p;\n\n                    // If the face is \"visible\" from point p.\n                    if (dot_c * dot_p < -kEpsilon)\n                    {\n                        visible_faces.push_back(f);\n                    }\n                }\n\n                // Expand the hull and remove the \"visible\" faces.\n                for (typename Faces3D::const_iterator it = visible_faces.begin();\n                     it != visible_faces.end(); ++it)\n                {\n                    Face3D f = *it;\n\n                    // Add new faces and remove the \"visible\" face.\n                    insert_tetrahedron(f.A(), f.B(), f.C(), p);\n                }\n            }\n        }\n    }\n\n    Point3D centroid()\n    {\n        Point3D center(0);\n        std::size_t count = 0;\n\n        for (typename FaceSet3D::const_iterator it = faces_.begin(); it != faces_.end(); ++it)\n        {\n            center += (it->A() + it->B() + it->C());\n            count += 3;\n        }\n\n        return center / count;\n    }\n\n    inline Point3D normal(const Face3D &f)\n    {\n        return (f.B() - f.A()).cross_product(f.C() - f.A());\n    }\n\n    inline RealType area(const Face3D &f)\n    {\n        return normal(f).euclidean_norm() / 2;\n    }\n\n    Points3D points_;\n    FaceSet3D faces_;\n};\n\n\n} // namespace surfaces\n} // namespace bo\n\n#endif // CONVEX_HULL_3D_HPP_1CB416FB_1F43_4159_A19B_202B43247622_\n", "meta": {"hexsha": "94f5d6c9daf4d59deacc761816f44c4c8dd566d7", "size": 10712, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Bo/surfaces/convex_hull_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/surfaces/convex_hull_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/surfaces/convex_hull_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": 31.1395348837, "max_line_length": 103, "alphanum_fraction": 0.5085884989, "num_tokens": 2568, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.49683880784596796}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n//  Copyright 2014 Anton Bikineev\n//  Copyright 2014 Christopher Kormanyos\n//  Copyright 2014 John Maddock\n//  Copyright 2014 Paul Bristow\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_2F0_HPP\n#define BOOST_MATH_HYPERGEOMETRIC_2F0_HPP\n\n#include <boost/math/policies/policy.hpp>\n#include <boost/math/policies/error_handling.hpp>\n#include <boost/math/special_functions/detail/hypergeometric_series.hpp>\n#include <boost/math/special_functions/laguerre.hpp>\n#include <boost/math/special_functions/hermite.hpp>\n#include <boost/math/tools/fraction.hpp>\n\nnamespace boost { namespace math { namespace detail {\n\n   template <class T>\n   struct hypergeometric_2F0_cf\n   {\n      //\n      // We start this continued fraction at b on index -1\n      // and treat the -1 and 0 cases as special cases.\n      // We do this to avoid adding the continued fraction result\n      // to 1 so that we can accurately evaluate for small results\n      // as well as large ones.  See  http://functions.wolfram.com/07.31.10.0002.01\n      //\n      T a1, a2, z;\n      int k;\n      hypergeometric_2F0_cf(T a1_, T a2_, T z_) : a1(a1_), a2(a2_), z(z_), k(-2) {}\n      typedef std::pair<T, T> result_type;\n\n      result_type operator()()\n      {\n         ++k;\n         if (k <= 0)\n            return std::make_pair(z * a1 * a2, 1);\n         return std::make_pair(-z * (a1 + k) * (a2 + k) / (k + 1), 1 + z * (a1 + k) * (a2 + k) / (k + 1));\n      }\n   };\n\n   template <class T, class Policy>\n   T hypergeometric_2F0_cf_imp(T a1, T a2, T z, const Policy& pol, const char* function)\n   {\n      using namespace boost::math;\n      hypergeometric_2F0_cf<T> evaluator(a1, a2, z);\n      boost::uintmax_t max_iter = policies::get_max_series_iterations<Policy>();\n      T cf = tools::continued_fraction_b(evaluator, policies::get_epsilon<T, Policy>(), max_iter);\n      policies::check_series_iterations<T>(function, max_iter, pol);\n      return cf;\n   }\n\n\n   template <class T, class Policy>\n   inline T hypergeometric_2F0_imp(T a1, T a2, const T& z, const Policy& pol, bool asymptotic = false)\n   {\n      //\n      // The terms in this series go to infinity unless one of a1 and a2 is a negative integer.\n      //\n      using std::swap;\n      BOOST_MATH_STD_USING\n\n      static const char* const function = \"boost::math::hypergeometric_2F0<%1%,%1%,%1%>(%1%,%1%,%1%)\";\n\n      if (z == 0)\n         return 1;\n\n      bool is_a1_integer = (a1 == floor(a1));\n      bool is_a2_integer = (a2 == floor(a2));\n\n      if (!asymptotic && !is_a1_integer && !is_a2_integer)\n         return boost::math::policies::raise_overflow_error<T>(function, 0, pol);\n      if (!is_a1_integer || (a1 > 0))\n      {\n         swap(a1, a2);\n         swap(is_a1_integer, is_a2_integer);\n      }\n      //\n      // At this point a1 must be a negative integer:\n      //\n      if(!asymptotic && (!is_a1_integer || (a1 > 0)))\n         return boost::math::policies::raise_overflow_error<T>(function, 0, pol);\n      //\n      // Special cases first:\n      //\n      if (a1 == 0)\n         return 1;\n      if ((a1 == a2 - 0.5f) && (z < 0))\n      {\n         // http://functions.wolfram.com/07.31.03.0083.01\n         int n = static_cast<int>(static_cast<boost::uintmax_t>(boost::math::lltrunc(-2 * a1)));\n         T smz = sqrt(-z);\n         return pow(2 / smz, -n) * boost::math::hermite(n, 1 / smz);\n      }\n\n      if (is_a1_integer && is_a2_integer)\n      {\n         if ((a1 < 1) && (a2 <= a1))\n         {\n            const unsigned int n = static_cast<unsigned int>(static_cast<boost::uintmax_t>(boost::math::lltrunc(-a1)));\n            const unsigned int m = static_cast<unsigned int>(static_cast<boost::uintmax_t>(boost::math::lltrunc(-a2 - n)));\n\n            return (pow(z, T(n)) * boost::math::factorial<T>(n, pol)) *\n               boost::math::laguerre(n, m, -(1 / z), pol);\n         }\n         else if ((a2 < 1) && (a1 <= a2))\n         {\n            // function is symmetric for a1 and a2\n            const unsigned int n = static_cast<unsigned int>(static_cast<boost::uintmax_t>(boost::math::lltrunc(-a2)));\n            const unsigned int m = static_cast<unsigned int>(static_cast<boost::uintmax_t>(boost::math::lltrunc(-a1 - n)));\n\n            return (pow(z, T(n)) * boost::math::factorial<T>(n, pol)) *\n               boost::math::laguerre(n, m, -(1 / z), pol);\n         }\n      }\n\n      if ((a1 * a2 * z < 0) && (a2 < -5) && (fabs(a1 * a2 * z) > 0.5))\n      {\n         // Series is alternating and maybe divergent at least for the first few terms\n         // (until a2 goes positive), try the continued fraction:\n         return hypergeometric_2F0_cf_imp(a1, a2, z, pol, function);\n      }\n\n      return detail::hypergeometric_2F0_generic_series(a1, a2, z, pol);\n   }\n\n} // namespace detail\n\ntemplate <class T1, class T2, class T3, class Policy>\ninline typename tools::promote_args<T1, T2, T3>::type hypergeometric_2F0(T1 a1, T2 a2, T3 z, const Policy& /* pol */)\n{\n   BOOST_FPU_EXCEPTION_GUARD\n      typedef typename tools::promote_args<T1, T2, T3>::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   return policies::checked_narrowing_cast<result_type, Policy>(\n      detail::hypergeometric_2F0_imp<value_type>(\n         static_cast<value_type>(a1),\n         static_cast<value_type>(a2),\n         static_cast<value_type>(z),\n         forwarding_policy()),\n      \"boost::math::hypergeometric_2F0<%1%>(%1%,%1%,%1%)\");\n}\n\ntemplate <class T1, class T2, class T3>\ninline typename tools::promote_args<T1, T2, T3>::type hypergeometric_2F0(T1 a1, T2 a2, T3 z)\n{\n   return hypergeometric_2F0(a1, a2, z, policies::policy<>());\n}\n\n\n  } } // namespace boost::math\n\n#endif // BOOST_MATH_HYPERGEOMETRIC_HPP\n", "meta": {"hexsha": "d6ee71667f67ff361d98ef7a95f97884ea2607b2", "size": 6127, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/math/special_functions/hypergeometric_2F0.hpp", "max_stars_repo_name": "cpp-pm/boost", "max_stars_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_stars_repo_licenses": ["BSL-1.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": "boost/math/special_functions/hypergeometric_2F0.hpp", "max_issues_repo_name": "cpp-pm/boost", "max_issues_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_issues_repo_licenses": ["BSL-1.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": "boost/math/special_functions/hypergeometric_2F0.hpp", "max_forks_repo_name": "cpp-pm/boost", "max_forks_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_forks_repo_licenses": ["BSL-1.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": 37.3597560976, "max_line_length": 123, "alphanum_fraction": 0.6110657744, "num_tokens": 1799, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4968388078459679}}
{"text": "#include <catch2/catch.hpp>\n\n#include \"CollisionConstraints.hpp\"\n#include \"CTCD.h\"\n\n#include <Eigen/Dense>\n#include <finitediff.hpp>\n\nconst std::vector<std::string> constraintNames = {\n    \"VOLUME\", \"GRAPHICS\", \"NONSMOOTH_NEWMARK\", \"GAP_FUNCTION\", \"CMR\",\n    \"VERSCHOOR\"\n};\n\nTEST_CASE(\"Test Point-Triangle Collision Constraints\",\n    \"[collision-constraints][sqp]\")\n{\n    // point\n    Eigen::Vector3d v0(0, 1, -0.5);\n    // triangle = (v1, v2, v3) in counter-clockwise order\n    Eigen::Vector3d v1(-1, 0, 1);\n    Eigen::Vector3d v2(1, 0, 1);\n    Eigen::Vector3d v3(0, 0, -1);\n\n    // displacements\n    double u0y = GENERATE(-1.1, 0.0, 1.1);\n    Eigen::Vector3d u0(0, u0y, 0);\n    double u1y = GENERATE(-1.1, 0.0, 1.1);\n    Eigen::Vector3d u1(0, u1y, 0);\n\n    bool intersects = (-u0y + u1y >= 1);\n\n    double toi;\n    bool ccd_intersects = CTCD::vertexFaceCTCD(\n        v0, v1, v3, v2, v0 + u0, v1 + u1, v3 + u1, v2 + u1, 0, toi);\n    REQUIRE(ccd_intersects == intersects);\n\n    IPC::CollisionConstraintType constraintType = GENERATE(\n        IPC::CollisionConstraintType::VOLUME,\n        IPC::CollisionConstraintType::GRAPHICS,\n        IPC::CollisionConstraintType::VERSCHOOR);\n    double c;\n    IPC::compute_collision_constraint(\n        v0, v1, v3, v2,\n        v0 + u0, v1 + u1, v3 + u1, v2 + u1,\n        constraintType, /*is_edge_edge=*/false, toi,\n        c);\n\n    CAPTURE(u0y, u1y, c, constraintNames[constraintType]);\n    CHECK((c < 0) == intersects);\n\n    Eigen::Vector12d grad_c;\n    IPC::compute_collision_constraint_gradient(\n        v0, v1, v3, v2,\n        v0 + u0, v1 + u1, v3 + u1, v2 + u1,\n        constraintType, /*is_edge_edge=*/false, toi,\n        grad_c);\n\n    Eigen::VectorXd x(12);\n    x.segment<3>(0) = v0 + u0;\n    x.segment<3>(3) = v1 + u1;\n    x.segment<3>(6) = v3 + u1; // Swap order to match compute_collision_constraint\n    x.segment<3>(9) = v2 + u1; // Swap order to match compute_collision_constraint\n    std::function<double(const Eigen::VectorXd&)> f = [&](const Eigen::VectorXd& x) {\n        assert(x.size() == 12);\n        double c;\n        IPC::compute_collision_constraint(\n            v0, v1, v3, v2,\n            x.segment<3>(0), x.segment<3>(3), x.segment<3>(6), x.segment<3>(9),\n            constraintType, /*is_edge_edge=*/false, toi,\n            c);\n        return c;\n    };\n    Eigen::VectorXd finite_grad_c(12);\n    fd::finite_gradient(x, f, finite_grad_c);\n    CAPTURE(grad_c.transpose(), finite_grad_c.transpose());\n    CHECK(fd::compare_gradient(grad_c, finite_grad_c));\n}\n\nTEST_CASE(\"Test Edge-Edge Collision Constraints\",\n    \"[collision-constraints][sqp]\")\n{\n    // e0 = (v0, v1)\n    Eigen::Vector3d v0(-1, -1, 0);\n    Eigen::Vector3d v1(1, -1, 0);\n    // e2 = (v2, v3)\n    Eigen::Vector3d v2(0, 1, -1);\n    Eigen::Vector3d v3(0, 1, 1);\n\n    // displacements\n    double y_displacement = GENERATE(-2, 0, 2);\n    Eigen::Vector3d u0(0, y_displacement, 0);\n    Eigen::Vector3d u1(0, -y_displacement, 0);\n\n    bool intersects = y_displacement >= 1.0;\n    double toi;\n    bool ccd_intersects = CTCD::edgeEdgeCTCD(\n        v0, v1, v2, v3, v0 + u0, v1 + u0, v2 + u1, v3 + u1, 0, toi);\n    CAPTURE(y_displacement);\n    REQUIRE(ccd_intersects == intersects);\n\n    IPC::CollisionConstraintType constraintType = GENERATE(\n        IPC::CollisionConstraintType::VOLUME,\n        IPC::CollisionConstraintType::GRAPHICS,\n        IPC::CollisionConstraintType::VERSCHOOR);\n\n    double c;\n    IPC::compute_collision_constraint(\n        v0, v1, v2, v3,\n        v0 + u0, v1 + u0, v2 + u1, v3 + u1,\n        constraintType, /*is_edge_edge=*/true, toi,\n        c);\n\n    CAPTURE(y_displacement, c, constraintNames[constraintType]);\n    CHECK((c < 0) == intersects);\n\n    typedef Eigen::Matrix<double, 12, 1> Vector12d;\n    Vector12d grad_c;\n    IPC::compute_collision_constraint_gradient(\n        v0, v1, v2, v3,\n        v0 + u0, v1 + u0, v2 + u1, v3 + u1,\n        constraintType, /*is_edge_edge=*/true, toi,\n        grad_c);\n\n    Eigen::VectorXd x(12);\n    x.segment<3>(0) = v0 + u0;\n    x.segment<3>(3) = v1 + u0;\n    x.segment<3>(6) = v2 + u1;\n    x.segment<3>(9) = v3 + u1;\n    std::function<double(const Eigen::VectorXd&)> f = [&](const Eigen::VectorXd& x) {\n        assert(x.size() == 12);\n        double c;\n        IPC::compute_collision_constraint(\n            v0, v1, v2, v3,\n            x.segment<3>(0), x.segment<3>(3), x.segment<3>(6), x.segment<3>(9),\n            constraintType, /*is_edge_edge=*/true, toi,\n            c);\n        return c;\n    };\n    Eigen::VectorXd finite_grad_c(12);\n    fd::finite_gradient(x, f, finite_grad_c);\n    CAPTURE(grad_c.transpose(), finite_grad_c.transpose());\n    CHECK(fd::compare_gradient(grad_c, finite_grad_c));\n}\n\nTEST_CASE(\"Barycentric coordinates\", \"[barycentric]\")\n{\n    // Create random triangle\n    Eigen::Vector3d a = Eigen::Vector3d::Random();\n    Eigen::Vector3d b = Eigen::Vector3d::Random();\n    Eigen::Vector3d c = Eigen::Vector3d::Random();\n    // Create random point\n    Eigen::Vector3d barycentric_coords = Eigen::Vector3d::Random();\n    barycentric_coords(0) = 1 - barycentric_coords(1) - barycentric_coords(2);\n    Eigen::Vector3d p = barycentric_coords(0) * a + barycentric_coords(1) * b + barycentric_coords(2) * c;\n\n    Eigen::Vector3d computed_barycentric_coords;\n    IPC::barycentric_coordinates(p.transpose(), a.transpose(), b.transpose(), c.transpose(), computed_barycentric_coords);\n    Eigen::Vector3d computed_p = computed_barycentric_coords(0) * a + computed_barycentric_coords(1) * b + computed_barycentric_coords(2) * c;\n\n    CAPTURE(barycentric_coords, computed_barycentric_coords);\n    CHECK((computed_barycentric_coords - barycentric_coords).norm() < 1e-12);\n    CAPTURE(p, computed_p);\n    CHECK((computed_p - p).norm() < 1e-12);\n}\n", "meta": {"hexsha": "4cc2346e75603a44f0a5c872fbfc6ff2168a6a58", "size": 5739, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/Collisions/CollisionConstraintTests.cpp", "max_stars_repo_name": "vincentkslim/IPC", "max_stars_repo_head_hexsha": "eb702ead6f23a1dc0be39c9f5a0fd62c80abeb98", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 344.0, "max_stars_repo_stars_event_min_datetime": "2020-07-03T14:08:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T14:01:11.000Z", "max_issues_repo_path": "tests/Collisions/CollisionConstraintTests.cpp", "max_issues_repo_name": "vincentkslim/IPC", "max_issues_repo_head_hexsha": "eb702ead6f23a1dc0be39c9f5a0fd62c80abeb98", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 25.0, "max_issues_repo_issues_event_min_datetime": "2020-07-05T15:56:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T20:56:39.000Z", "max_forks_repo_path": "tests/Collisions/CollisionConstraintTests.cpp", "max_forks_repo_name": "vincentkslim/IPC", "max_forks_repo_head_hexsha": "eb702ead6f23a1dc0be39c9f5a0fd62c80abeb98", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 46.0, "max_forks_repo_forks_event_min_datetime": "2020-07-04T05:04:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T02:09:23.000Z", "avg_line_length": 34.7818181818, "max_line_length": 142, "alphanum_fraction": 0.6229308242, "num_tokens": 1841, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4968388078459679}}
{"text": "#include <iostream>\n#include <numeric>\n#include <boost/assign.hpp>\n#include \"SketchRing.h\"\n\n\nusing namespace std;\nusing namespace boost;\n\nunsigned hashf(int value) {\n    unsigned temp = ((value % 3451) + 1) * (value ^ 0x238bc1) + (1 + value * 13);\n    return temp ^ std::hash<int>{}(value);\n}\n\nint SketchRing::size() const {\n    return cms.begin()->second.size() * cms.size();\n}\n\nvoid SketchRing::update(unsigned int item, int diff) {\n    auto hash   = hashf(item) % domainMax;\n    auto bucket = buckets.find(hash)->second;\n//    cout << item << \" bucket:\" << bucket << endl;\n    cms.at(bucket).update(item, diff);\n}\n\nint SketchRing::estimate(unsigned int item) const {\n    auto hash = hashf(item) % domainMax;\n    return cms.at(buckets.find(hash)->second).estimate(item);\n}\n\nSketchRing::SketchRing(int width, int depth, int n,\n                       Point domainMax) : buckets(make_pair(0, 0)), domainMax(domainMax) {\n    auto interval = double(domainMax) / n;\n\n    for (Point high = interval, low = 1; low < domainMax; low = high, high += interval) {\n\n//        std::cout << \"I:\" << high << \":\" << buckets.iterative_size() << std::endl;\n        cms.emplace(piecewise_construct,\n                    forward_as_tuple(low),\n                    forward_as_tuple(width, depth, 1));\n        buckets.insert(make_pair(icl::interval<Point>::type(low, high), low));\n    }\n}\n\nauto erase(SketchRing::IntervalMap& buckets, SketchRing::IntervalMap::const_iterator it) {\n    bool       isFirst  = it == buckets.begin();\n    const auto erasedIv = it->first;\n\n    auto prevBucket = isFirst ? buckets.rbegin()->second : (--it)->second;\n\n    buckets.set(make_pair(erasedIv, prevBucket));\n\n    return prevBucket;\n}\n\nvoid SketchRing::shrink() {\n    // find least loaded sketch\n    unsigned  minLoad = 0;\n    auto      minIter = cms.begin();\n    for (auto it      = cms.begin(); it != cms.end(); ++it) {\n        auto load = it->second.load();\n        if (load > minLoad) {\n            minLoad = load;\n            minIter = it;\n        }\n    }\n\n    // now we have the min\n    const auto& sketch = minIter->second;\n    const auto location = minIter->first;\n    const auto& hh = sketch.heavyHitters(.6);\n\n    auto toAdd = erase(buckets, buckets.find(location));\n\n    for (auto[hitter, freq]: hh)\n        cms.at(toAdd).update(hitter, freq);\n\n    cms.erase(minIter);\n}\n\nvoid SketchRing::expand() {\n    throw std::bad_function_call();\n    // find most loaded sketch\n    unsigned  maxLoad = 0;\n    auto      maxIter = cms.begin();\n    for (auto it      = cms.begin(); it != cms.end(); ++it) {\n        auto load = it->second.load();\n        if (load > maxLoad) {\n            maxLoad = load;\n            maxIter = it;\n        }\n    }\n\n    // now we have the max\n    const auto& sketch = maxIter->second;\n    const auto location = maxIter->first;\n    const auto& hh = sketch.heavyHitters(.4);\n\n    auto toAdd = erase(buckets, buckets.find(location));\n\n    for (auto[hitter, freq]: hh)\n        cms.at(toAdd).update(hitter, freq);\n\n    cms.erase(maxIter);\n\n    throw std::exception();\n}\n\nvoid SketchRing::resize(int n) {\n    if (n <= 2) throw out_of_range(\"can't shrink below 2\");\n\n    while (cms.size() > n) {\n        shrink();\n    }\n    while (cms.size() < n) {\n        expand();\n    }\n}\n\nstd::vector<std::pair<int, int> > SketchRing::heavyHitters(int threshold) const {\n    std::vector<std::pair<int, int> > res;\n\n    for (const auto&[p, cm] : cms) {\n        const auto& hh = cm.heavyHitters(threshold);\n        res.insert(res.end(), hh.begin(), hh.end());\n    }\n\n    return res;\n}\n\n\nextern \"C\" {\n#include \"SketchRingC.h\"\n\nSK_type* SK_init(int width, int depth, int n, int domainMax) {\n    return new SketchRing(width, depth, n, domainMax);\n}\n\nvoid SK_destroy(SK_type* sr) {\n    delete sr;\n}\n\nint SK_size(const SK_type* sr) {\n    return sr->size();\n}\n\nvoid SK_update(SK_type* sr, unsigned int item, int diff) {\n    sr->update(item, diff);\n}\n\nint SK_estimate(const SK_type* sr, unsigned int item) {\n    return sr->estimate(item);\n}\n\nvoid SK_resize(SK_type* sr, int n) {\n    sr->resize(n);\n}\n\n//void HH_free(HH* hh) {\n//    free(hh->freq);\n//    free(hh->items);\n//    *hh = {0, 0, 0};\n//}\n//\n//HH SK_heavyHitters(const SK_type* sk, int threshold) {\n//    HH res;\n//    const auto& hh = sk->heavyHitters(threshold);\n//\n//    res.size = hh.size();\n//    res.items = static_cast<int*>(malloc(sizeof(int) * res.size));\n//    res.freq = static_cast<int*>(malloc(sizeof(int) * res.size));\n//\n//    for (int i = 0; i < res.size; ++i) {\n//        res.items[i] = hh[i].first;\n//        res.freq[i] = hh[i].second;\n//    }\n//\n//    return res;\n//}\nint* SK_heavyHitters(const SK_type* sk, int threshold) {\n    const auto& hh = sk->heavyHitters(threshold);\n    unsigned size = hh.size();\n    int* res = static_cast<int*>(calloc(size+1, (sizeof(int))));\n\n    res[0] = size;\n\n    for (int i = 1; i <= res[0]; ++i) {\n        res[i] = hh[i-1].first;\n    }\n\n    return res;\n}\n\n}", "meta": {"hexsha": "9fb7ba455d4ba30c484c14a27f9a3e110ffb79ed", "size": 4931, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "SketchRing.cxx", "max_stars_repo_name": "avi1mizrahi/DynamicSketchError", "max_stars_repo_head_hexsha": "9e90977cce7f5edd4c3414d8704b9b9724e577df", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SketchRing.cxx", "max_issues_repo_name": "avi1mizrahi/DynamicSketchError", "max_issues_repo_head_hexsha": "9e90977cce7f5edd4c3414d8704b9b9724e577df", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SketchRing.cxx", "max_forks_repo_name": "avi1mizrahi/DynamicSketchError", "max_forks_repo_head_hexsha": "9e90977cce7f5edd4c3414d8704b9b9724e577df", "max_forks_repo_licenses": ["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.4175257732, "max_line_length": 90, "alphanum_fraction": 0.5877104036, "num_tokens": 1353, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867585368343, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.49683879589301405}}
{"text": "#include \"faasm/faasm.h\"\n\n#include <Eigen/Dense>\n\n#include \"ndpapi.h\"\n\n#include <stdio.h>\n#include <string.h>\n\n#include <regex>\n#include <string_view>\n#include <vector>\n\n#include \"util/kmeansrex.cpp\"\n\nusing std::string_view;\n\nstring_view objKey;\n\nuint32_t endswap32(uint32_t x)\n{\n    return ((x & 0xFFu) << 24u) | ((x & 0xFF00u) << 8u) |\n           ((x & 0xFF0000u) >> 8u) | ((x & 0xFF000000u) >> 24u);\n}\n\nEigen::MatrixXf pcaReducedData;\n\nint work()\n{\n    uint32_t fetchedLength{};\n    uint8_t* objData =\n      __faasmndp_getMmap(reinterpret_cast<const uint8_t*>(objKey.data()),\n                         objKey.size(),\n                         1 * 1024 * 1024 * 1024,\n                         &fetchedLength);\n    if (objData == nullptr || fetchedLength < 64) {\n        const string_view output{\n            \"FAILED - no object found with the given key\"\n        };\n        faasmSetOutput(reinterpret_cast<const uint8_t*>(output.data()),\n                       output.size());\n        return 1;\n    }\n    const uint32_t magic = endswap32(*reinterpret_cast<uint32_t*>(objData));\n    const uint32_t nImages =\n      endswap32(*reinterpret_cast<uint32_t*>(objData + 4));\n    const uint32_t nRows = endswap32(*reinterpret_cast<uint32_t*>(objData + 8));\n    const uint32_t nCols =\n      endswap32(*reinterpret_cast<uint32_t*>(objData + 12));\n    const uint8_t* pixelDataStart = objData + 16;\n    if (magic != 0x00000803) {\n        const string_view output{ \"FAILED - bad magic number\" };\n        faasmSetOutput(reinterpret_cast<const uint8_t*>(output.data()),\n                       output.size());\n        return 2;\n    }\n    const uint32_t pixelsPerImage = nRows * nCols;\n    if (pixelsPerImage * nImages > fetchedLength - 16) {\n        const string_view output{ \"FAILED - missing image data\" };\n        faasmSetOutput(reinterpret_cast<const uint8_t*>(output.data()),\n                       output.size());\n        return 3;\n    }\n    Eigen::MatrixXf imageData(nImages, pixelsPerImage);\n    const float fmul = 1.0f / 255.0f;\n    for (uint32_t image = 0; image < nImages; image++) {\n        const uint8_t* imageStart = pixelDataStart + (nRows * nCols) * image;\n        for (uint32_t pixel = 0; pixel < nRows * nCols; pixel++) {\n            imageData(image, pixel) = float(imageStart[pixel]) * fmul;\n        }\n    }\n    // normalize data\n    {\n        Eigen::VectorXf mins = imageData.colwise().minCoeff();\n        Eigen::VectorXf maxs = imageData.colwise().maxCoeff();\n        Eigen::VectorXf scaleCoeff = maxs - mins;\n        for (auto& val : scaleCoeff) {\n            val = (val == 0) ? 1.0f : 1.0f / val;\n        }\n        imageData.rowwise() -= mins.transpose();\n        imageData.array().rowwise() *= scaleCoeff.transpose().array();\n    }\n    // center on means\n    {\n        Eigen::VectorXf means = imageData.colwise().mean();\n        imageData.rowwise() -= means.transpose();\n    }\n    Eigen::MatrixXf covarianceMat = imageData.adjoint() * imageData;\n    covarianceMat = covarianceMat / (imageData.rows() - 1);\n    Eigen::SelfAdjointEigenSolver<Eigen::MatrixXf> eigensolver(covarianceMat);\n    Eigen::VectorXf eigenvalues = eigensolver.eigenvalues();\n    eigenvalues /= eigenvalues.sum();\n    Eigen::MatrixXf eigenvectors = eigensolver.eigenvectors();\n    Eigen::MatrixXf pcaTransform = eigenvectors.rightCols(32);\n    pcaReducedData = imageData * pcaTransform;\n    return 0;\n}\n\nint main(int argc, char* argv[])\n{\n    long inputSz = faasmGetInputSize();\n    std::vector<uint8_t> inputBuf(inputSz);\n    faasmGetInput(inputBuf.data(), inputBuf.size());\n    string_view inputStr(reinterpret_cast<char*>(inputBuf.data()),\n                         inputBuf.size());\n    if (inputStr.size() < 1) {\n        const string_view output{\n            \"FAILED - no key/value pair. Usage: grep with input 'key regex'\"\n        };\n        faasmSetOutput(reinterpret_cast<const uint8_t*>(output.data()),\n                       output.size());\n        return 0;\n    }\n    objKey = inputStr;\n\n    if (__faasmndp_storageCallAndAwait(work) != 0) {\n        return 1;\n    }\n\n    const int K = 10;\n    const int n_features = pcaReducedData.cols();\n    const int n_iters = 25;\n    const int seed = 1234567;\n    const int n_examples = pcaReducedData.rows();\n\n    Eigen::ArrayXXd dblData = pcaReducedData.array().cast<double>();\n    Eigen::ArrayXXd mu = Eigen::ArrayXXd::Zero(K, n_features);\n    Eigen::ArrayXd z = Eigen::ArrayXd::Zero(n_examples);\n    RunKMeans(dblData.data(),\n              n_examples,\n              n_features,\n              K,\n              n_iters,\n              seed,\n              \"plusplus\",\n              mu.data(),\n              z.data());\n\n    std::string output;\n    output.reserve(z.rows() * 4);\n    for (auto& el : z) {\n        output += std::to_string(int(el));\n        output.push_back(' ');\n    }\n    output.push_back('\\n');\n\n    faasmSetOutput(reinterpret_cast<uint8_t*>(output.data()), output.size());\n    return 0;\n}\n", "meta": {"hexsha": "66ada8a88a98aebafdb7e7547aa8975802285c08", "size": 4927, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "func/ndp/pcakmm.cpp", "max_stars_repo_name": "auto-ndp/faasm-cpp", "max_stars_repo_head_hexsha": "68ec74135575a9b5cce6afb000b2e1d0e42bbb08", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "func/ndp/pcakmm.cpp", "max_issues_repo_name": "auto-ndp/faasm-cpp", "max_issues_repo_head_hexsha": "68ec74135575a9b5cce6afb000b2e1d0e42bbb08", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "func/ndp/pcakmm.cpp", "max_forks_repo_name": "auto-ndp/faasm-cpp", "max_forks_repo_head_hexsha": "68ec74135575a9b5cce6afb000b2e1d0e42bbb08", "max_forks_repo_licenses": ["Apache-2.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.8466666667, "max_line_length": 80, "alphanum_fraction": 0.598132738, "num_tokens": 1285, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744939732856, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4968099085823291}}
{"text": "/*\r\n * @Author: tom: https://github.com/TOMsworkspace \r\n * @Date: 2021-09-03 15:32:52 \r\n * @Last Modified by: tom: https://github.com/TOMsworkspace\r\n * @Last Modified time: 2021-09-03 19:17:13\r\n */\r\n\r\n#include <algorithm>\r\n#include <sstream>\r\n#include <iostream>\r\n\r\n#include <Eigen\\\\Dense>\r\nusing namespace std;\r\nusing namespace Eigen;\r\n\r\n\r\n//#include <gl/GL.h>\r\n//#include <glad/glad.h>\r\n//#include <GLFW/glfw3.h>\r\n\r\n\r\n//#include <irrklang/irrKlang.h>\r\n//using namespace irrklang;\r\n\r\n#include \"dtkFemSimulation.h\"\r\n\r\n#include \"GL/freeglut.h\"\r\n\r\n//#include \"resource_manager.h\"\r\n//#include \"sprite_renderer.h\"\r\n\r\n\r\nint dim = 2;\r\nint n_node_x = 50;\r\nint n_node_y = 6;\r\nfloat node_mass = 1.0f;\r\nint n_node = n_node_x * n_node_y;\r\nint n_fem_element = (n_node_x - 1) * (n_node_y - 1) * 2;\r\nfloat deltat = 3e-4;\r\nfloat deltax = (1.0 / 32);\r\n\r\nfloat Young_E = 1000.0f; /**< \u6768\u6c0f\u6a21\u91cf */\r\nfloat Poisson_r = 0.3f; /**< \u6cca\u677e\u6bd4 [0 - 0.5] */\r\nfloat Lame_parameter_1 = Young_E / (2 * (1 + Poisson_r));\r\nfloat Lame_parameter_2 = Young_E * Poisson_r / ((1 + Poisson_r) * (1 - 2 * Poisson_r));\r\nfloat element_v = 0.01f; /**< \u5fae\u5143\u4f53\u79ef */\r\n\r\nfloat radius = 0.05;\r\n\r\nint iterate_time = 3;\r\n\r\ninline int mesh(int i, int j) {\r\n    return i * n_node_y + j;\r\n}\r\n\r\n\r\ndtkFemSimulation::dtkFemSimulation(unsigned int width, unsigned int height)\r\n: dtkScene(width, height),\r\npoints(n_node),pre_points(n_node),points_v(n_node),points_force(n_node),B(n_fem_element),\r\nMeshTable(n_fem_element,std::vector<int>(3,0)),sphere(dtk::dtkGraphicsKernel::Point2(0.5,0.25), radius),\r\ntotal_energy(0),pre_total_energy(0),spherecenter(0.5,0.25)\r\n{ \r\n\r\n}\r\n\r\nMatrix2f dtkFemSimulation::compute_D(int i){\r\n    int a = MeshTable[i][0];\r\n    int b = MeshTable[i][1];\r\n    int c = MeshTable[i][2];\r\n\r\n    Matrix2f ans;\r\n    ans(0,0) = points[a][0] - points[c][0];\r\n    ans(0,1) = points[b][0] - points[c][0];\r\n    ans(1,0) = points[a][1] - points[c][1];\r\n    ans(1,1) = points[b][1] - points[c][1];\r\n    return ans;\r\n}\r\n\r\n\r\nvoid dtkFemSimulation::compute_B(){\r\n    for(int i = 0; i < n_fem_element; ++i){\r\n        this->B[i] = compute_D(i).inverse();\r\n        //cout << setw(6) << B[i] << endl;\r\n    }\r\n}\r\n\r\nMatrix2f dtkFemSimulation::compute_P(int i){\r\n    Matrix2f D = compute_D(i);\r\n    Matrix2f F = D * B[i];\r\n\r\n    Matrix2f F_T = F.transpose().inverse();\r\n\r\n    float J = max(0.5f, F.determinant()); /**< \u5f62\u53d8\u7387 */\r\n\r\n    return Lame_parameter_1 * (F - F_T) + Lame_parameter_2 * log(J) * F_T ;\r\n    //Matrix2f ans = D * this->B[i];\r\n}\r\n\r\nvoid dtkFemSimulation::compute_total_energy(){\r\n\r\n    //this->total_energy = 0.0f;\r\n    for(int i = 0; i < n_fem_element; ++i){\r\n        Matrix2f D = compute_D(i);\r\n        Matrix2f F = D * B[i];\r\n\r\n        //NeoHooken\r\n        float I1 = (F * F.transpose()).trace();\r\n        float J = max(0.2f, (float)F.determinant()); /**< \u5f62\u53d8\u7387 */\r\n\r\n        //cout << J << endl;\r\n        \r\n        float element_energy_density = 0.5 * Lame_parameter_1 * (I1 - dim) - Lame_parameter_1 * log(J) + 0.5 * Lame_parameter_2 * log(J) * log(J);\r\n        this->total_energy += element_energy_density * element_v;\r\n    }\r\n}\r\n\r\ndtkFemSimulation::~dtkFemSimulation()\r\n{\r\n}\r\n\r\nvoid dtkFemSimulation::Init()\r\n{\r\n    dtkScene::Init();\r\n    //TODO: load shaders\r\n\r\n    //TODO: configure shaders\r\n\r\n    //TODO: load textures\r\n    \r\n    //TODO: set render-specific controls\r\n\r\n    //TODO: configure Scene objects\r\n\r\n    //build mesh\r\n    for(int i = 0; i < n_node_x; ++i){\r\n        for(int j = 0; j < n_node_y; ++j){\r\n            int idx = mesh(i,j);\r\n            //this->points[idx][0] = -14 + i * deltax * 0.5;\r\n            //this->points[idx][1] = 8 + j * deltax * 0.5 + i * deltax * 0.05;\r\n\r\n            this->points[idx][0] = 0.1f + i * deltax * 0.5f;\r\n            this->points[idx][1] = 0.5f + j * deltax * 0.5f + i * deltax * 0.1f;\r\n            this->points_v[idx][0] = 0.0f;\r\n            this->points_v[idx][1] = -1.0f; \r\n        }\r\n    }\r\n\r\n    //this->pre_points = points;\r\n\r\n    for(int i = 0; i < n_node_x - 1; ++i ){ \r\n        for(int j = 0; j < n_node_y - 1; ++j){\r\n            //element id\r\n            int eidx = (i * (n_node_y - 1) + j) * 2;\r\n            this->MeshTable[eidx][0] = mesh(i,j);\r\n            this->MeshTable[eidx][1] = mesh(i + 1, j);\r\n            this->MeshTable[eidx][2] = mesh(i,j + 1);\r\n\r\n            eidx = (i * (n_node_y - 1) + j) * 2 + 1;\r\n            this->MeshTable[eidx][0] = mesh(i,j + 1);\r\n            this->MeshTable[eidx][1] = mesh(i + 1,j + 1);\r\n            this->MeshTable[eidx][2] = mesh(i + 1,j);\r\n        }\r\n    }\r\n\r\n    compute_B();\r\n    \r\n    //TODO: audio\r\n}\r\n\r\nvoid dtkFemSimulation::compute_force(){\r\n    for(int i = 0; i < n_node ; ++i){\r\n        this->points_force[i] = Vector2f(0.0f, - 10.0f * node_mass);\r\n    }\r\n\r\n    for(int i = 0; i < n_fem_element; ++i){\r\n\r\n        Matrix2f P = compute_P(i);\r\n        Matrix2f H = - element_v * (P * (this->B[i].transpose()));\r\n\r\n        Vector2f h1 = Vector2f(H(0,0), H(1,0));\r\n        Vector2f h2 = Vector2f(H(0,1), H(1,1));\r\n\r\n        int a = this->MeshTable[i][0];\r\n        int b = this->MeshTable[i][1];\r\n        int c = this->MeshTable[i][2];\r\n\r\n        this->points_force[a] += h1;\r\n        this->points_force[b] += h2;\r\n        this->points_force[c] += -(h1 + h2);\r\n    }\r\n}\r\n\r\nvoid dtkFemSimulation::Update(float dt)\r\n{\r\n    //TODO: update objects\r\n    //TODO: check for object collisions\r\n    if(this->State == SCENE_ACTIVE){\r\n        \r\n        // \u8fed\u4ee3\u591a\u8f6e, \u9632\u6b62\u7a7f\u900f\r\n        for(int i = 0; i < iterate_time ; ++i){\r\n            //this->pre_total_energy = total_energy; \r\n            compute_total_energy();\r\n            DoCollisions();\r\n            compute_force();\r\n\r\n            //cout << total_energy << endl;\r\n        \r\n            //float deltaU = this->total_energy - this->pre_total_energy;\r\n            //deltaU = abs(deltaU) < 1e-9 ? 0 : deltaU; \r\n            for(int i = 0; i < n_node; ++i){\r\n                // update points\r\n\r\n                //Vector2f deltaX = this->points[i] - this->pre_points[i];\r\n\r\n                //Vector2f diffUtoX = Vector2f(deltaU / deltaX[0], deltaU / deltaX[1]);\r\n\r\n            \r\n               // Vector2f diffUtoX = Vector2f(abs(deltaX[0]) > 1e-4 ? deltaU / deltaX[0] : 0.0f, abs(deltaX[1]) > 1e-4 ? deltaU / deltaX[1] : 0.0f);\r\n\r\n                //diffUtoX = Vector2f(0.0f,0.0f);\r\n\r\n                //cout << diffUtoX << endl;\r\n\r\n               // this->points_v[i] = (this->points_v[i] + ((- diffUtoX / node_mass) + Vector2f(0.0f, -10.0f)) * deltat) * exp(deltat * -6);\r\n\r\n                this->points_v[i] = (this->points_v[i] + (this->points_force[i] / node_mass) * deltat) * exp(deltat * -3); \r\n                //this->pre_points[i] = this->points[i];\r\n\r\n                this->points[i] += deltat * this->points_v[i];\r\n            }\r\n\r\n            \r\n           // this->pre_points = this->points;\r\n           // this->pre_total_energy = this->total_energy;\r\n        }\r\n    }\r\n}\r\n\r\n\r\nvoid dtkFemSimulation::ProcessInput(float dt)\r\n{   \r\n    dtkScene::ProcessInput(dt);\r\n    //TODO: process input(keys)\r\n    \r\n}\r\n\r\n\r\nvoid dtkFemSimulation::Render()\r\n{\r\n    //if(this->State == SCENE_ACTIVE){\r\n        //TODO: draw circle\r\n\r\n        Vector2f center = spherecenter;\r\n        //Vector2f(this->sphere.center()[0], this->sphere.center()[1]);\r\n\r\n        glColor3f(0x06 * 1.0 / 0xff, 0x85 * 1.0 / 0xff, 0x87 * 1.0 / 0xff);\r\n        glBegin(GL_POLYGON);\r\n\r\n        int n = 100;\r\n        for (int i = 0; i < n; i++)\r\n        {\r\n            glVertex2f(center[0] + radius * cos(2 * dtk::dtkPI / n * i), center[1] + radius * sin(2 * dtk::dtkPI / n * i));\t\t\r\n        }\r\n        glEnd();\r\n        \r\n\r\n        //TODO: draw fem element(triangles here)\r\n        glColor3f(0x4f * 1.0 / 0xff, 0xb9 * 1.0 / 0xff, 0x9f * 1.0 / 0xff);\r\n        glBegin(GL_LINES);\r\n        for(int i = 0; i < n_fem_element; ++i){\r\n            for(int j = 0 ; j < 3; ++j){\r\n                int a = this->MeshTable[i][j];\r\n                int b = this->MeshTable[i][(j  + 1) % 3];\r\n\r\n                //draw line from a to b;\r\n                glVertex2f(this->points[a][0] , this->points[a][1] );\r\n                glVertex2f(this->points[b][0], this->points[b][1] );\r\n            }\r\n        }\r\n        //glEnd();\r\n\r\n        glColor3f(1.0, 1.0, 1.0);\r\n        //glBegin(GL_LINES);\r\n        glVertex2f(0.0f, 0.2f);\r\n        glVertex2f(1.0f, 0.2f);\r\n\r\n        glVertex2f(1.0f, 0.85f);\r\n        glVertex2f(1.0f, 0.2f);\r\n\r\n        glVertex2f(1.0f, 0.85f);\r\n        glVertex2f(0.0f, 0.85f);\r\n\r\n        glVertex2f(0.0f, 0.85f);\r\n        glVertex2f(0.0f, 0.2f);\r\n        glEnd();\r\n   // }\r\n}\r\n\r\n// collision detection\r\n\r\nvoid dtkFemSimulation::DoCollisions()\r\n{\r\n    if(this->State == SCENE_ACTIVE){\r\n        Vector2f center = spherecenter;\r\n        //Vector2f(this->sphere.center()[0], this->sphere.center()[1]);\r\n        float radius = this->sphere.squared_radius();\r\n        \r\n        for(int i = 0; i < n_node; ++i){\r\n            //# Collide with sphere\r\n            \r\n            Vector2f dis = this->points[i] - center;\r\n            if((float)(dis.dot(dis)) < radius * radius)\r\n            {\r\n                Vector2f normal = dis.normalized();\r\n                \r\n                this->points[i] = center + radius * normal;\r\n                this->points_v[i] -=  (this->points_v[i].dot(normal)) *  normal;\r\n            }\r\n            \r\n            \r\n            // Collide with ground\r\n\r\n            if(this->points[i][1] < 0.2f) {\r\n                this->points[i][1] = 0.2f;\r\n                this->points_v[i][1] = 0.0f;\r\n            }\r\n\r\n            if(this->points[i][1] > 0.9f) {\r\n                this->points[i][1] = 0.9f;\r\n                this->points_v[i][1] = 0.0f;\r\n            }\r\n\r\n            if(this->points[i][0] < 0.0f) {\r\n                this->points[i][0] = 0.0f;\r\n                this->points_v[i][0] = 0.0f;\r\n            }\r\n\r\n            if(this->points[i][0] > 1.0f) {\r\n                this->points[i][0] = 1.0f;\r\n                this->points_v[i][0] = 0.0f;\r\n            }\r\n        }\r\n        \r\n    }\r\n}\r\n\r\nvoid dtkFemSimulation::moveBall(int x, int y){\r\n\r\n    //this->spherecenter = Vector2f((x) * 1.0 / 800 , (600 - y) * 1.0 / 600 );\r\n}\r\n\r\nfloat dtkFemSimulation::getEnergy(){\r\n    return this->total_energy;\r\n}", "meta": {"hexsha": "526d5a876c8f42ef125be54541c85bc5fb9fd606", "size": 10186, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "demo/FEMsimulation/dtkFemSimulation.cpp", "max_stars_repo_name": "Deformable-Toolkit/dtk", "max_stars_repo_head_hexsha": "6fdfe2be9e2b1a11effc93db4dc946420ed023d6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2021-03-08T08:51:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T16:58:00.000Z", "max_issues_repo_path": "demo/FEMsimulation/dtkFemSimulation.cpp", "max_issues_repo_name": "TOMsworkspace/dtk", "max_issues_repo_head_hexsha": "6fdfe2be9e2b1a11effc93db4dc946420ed023d6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-03-05T07:25:41.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-05T07:25:41.000Z", "max_forks_repo_path": "demo/FEMsimulation/dtkFemSimulation.cpp", "max_forks_repo_name": "TOMsworkspace/dtk", "max_forks_repo_head_hexsha": "6fdfe2be9e2b1a11effc93db4dc946420ed023d6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-04-26T03:14:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-13T08:48:45.000Z", "avg_line_length": 28.7740112994, "max_line_length": 150, "alphanum_fraction": 0.5020616532, "num_tokens": 3241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834648, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.49680990318031243}}
{"text": "#ifndef EXPSUM_KERNEL_FUNCTIONS_BESSEL_KERNEL_HPP\n#define EXPSUM_KERNEL_FUNCTIONS_BESSEL_KERNEL_HPP\n\n#include <cassert>\n#include <cmath>\n\n#include <armadillo>\n\nnamespace expsum\n{\n\ntemplate <typename T>\nstruct bessel_j_kernel\n{\npublic:\n    using size_type   = arma::uword;\n    using real_type   = T;\n    using vector_type = arma::Col<T>;\n    using matrix_type = arma::Mat<T>;\n\nprivate:\n    vector_type exponent_;\n    vector_type weight_;\n    real_type v_;   // order of Bessel function Jv(x)\n    real_type eps_; // tolerance\n\npublic:\n    void compute(real_type v, real_type eps);\n\n    size_type size() const\n    {\n        return exponent_.size();\n    }\n\n    const vector_type& exponents() const\n    {\n        return exponent_;\n    }\n\n    const vector_type& weights() const\n    {\n        return weight_;\n    }\n\nprivate:\n};\n\ntemplate <typename T>\nvoid bessel_j_kernel<T>::compute(real_type v, real_type eps)\n{\n}\n\n} // namespace: expsum\n\n#endif /* EXPSUM_KERNEL_FUNCTIONS_BESSEL_KERNEL_HPP */\n", "meta": {"hexsha": "17c08e627e6042ebdfdfb5653dc3540a3253d546", "size": 989, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/expsum/kernel_functions/bessel_kernel.hpp", "max_stars_repo_name": "hide-ikeno/expsum", "max_stars_repo_head_hexsha": "7b1be33b7c342f875d6d5e5c0cd8df9ec62abbda", "max_stars_repo_licenses": ["MIT"], "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/expsum/kernel_functions/bessel_kernel.hpp", "max_issues_repo_name": "hide-ikeno/expsum", "max_issues_repo_head_hexsha": "7b1be33b7c342f875d6d5e5c0cd8df9ec62abbda", "max_issues_repo_licenses": ["MIT"], "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/expsum/kernel_functions/bessel_kernel.hpp", "max_forks_repo_name": "hide-ikeno/expsum", "max_forks_repo_head_hexsha": "7b1be33b7c342f875d6d5e5c0cd8df9ec62abbda", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.6607142857, "max_line_length": 60, "alphanum_fraction": 0.6865520728, "num_tokens": 243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936438, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.49680989777829554}}
{"text": "////////////////////////////////////////////////////////////////////////////////\n//  Copyright (c) 2011 Bryce Lelbach\n//  Copyright (C) 2010 Scott McMurray\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#if !defined(HPX_68441787_8A39_4DAC_9D9E_705B6FA19BCD)\n#define HPX_68441787_8A39_4DAC_9D9E_705B6FA19BCD\n\n#include <boost/cstdint.hpp>\n\nnamespace hpx { namespace util { namespace hardware\n{\n\ntemplate <typename T, typename U>\nbool has_bit_set(T value, U bit)\n{ return (value & (1 << bit)) != 0; }\n\ntemplate <std::size_t N, typename T>\nstruct unbounded_shifter\n{\n    static T shl(T x) { return unbounded_shifter<N-1, T>::shl(T(x << 1)); }\n    static T shr(T x) { return unbounded_shifter<N-1, T>::shr(T(x >> 1)); }\n};\n\ntemplate <typename T>\nstruct unbounded_shifter<0, T>\n{\n    static T shl(T x) { return x; }\n    static T shr(T x) { return x; }\n};\n\ntemplate <std::size_t N, typename T>\nT unbounded_shl(T x)\n{ return unbounded_shifter<N, T>::shl(x); }\n\ntemplate <std::size_t N, typename T>\nT unbounded_shr(T x)\n{ return unbounded_shifter<N, T>::shr(x); }\n\ntemplate <std::size_t Low, std::size_t High, typename Result, typename T>\nResult get_bit_range(T x)\n{\n    T highmask = unbounded_shl<High, T>(~T());\n    T lowmask = unbounded_shl<Low, T>(~T());\n    return static_cast<Result>\n        (unbounded_shr<Low, T>(T(x & (lowmask ^ highmask))));\n}\n\ntemplate <std::size_t Low, typename Result, typename T>\nResult pack_bits(T x)\n{ return unbounded_shl<Low, Result>(static_cast<Result>(x)); }\n\n}}}\n\n#endif // HPX_68441787_8A39_4DAC_9D9E_705B6FA19BCD\n\n", "meta": {"hexsha": "b7a5c730b7211ffc6fde5f0f6dbb245a733ba3ae", "size": 1738, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "hpx/util/hardware/bit_manipulation.hpp", "max_stars_repo_name": "kempj/hpx", "max_stars_repo_head_hexsha": "ffdbfed5dfa029a0f2e97e7367cb66d12103df67", "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": "hpx/util/hardware/bit_manipulation.hpp", "max_issues_repo_name": "kempj/hpx", "max_issues_repo_head_hexsha": "ffdbfed5dfa029a0f2e97e7367cb66d12103df67", "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": "hpx/util/hardware/bit_manipulation.hpp", "max_forks_repo_name": "kempj/hpx", "max_forks_repo_head_hexsha": "ffdbfed5dfa029a0f2e97e7367cb66d12103df67", "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.9666666667, "max_line_length": 80, "alphanum_fraction": 0.6317606444, "num_tokens": 524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.4965828283300225}}
{"text": "#pragma once\n\n#include <pcl/point_types.h>\n#include <pcl/features/normal_3d.h>\n#include <pcl/io/pcd_io.h>\n#include <pcl/io/ply_io.h>\n#include <pcl/filters/voxel_grid.h>\n#include <pcl/point_cloud.h>\n#include <Eigen/Dense>\n\n\nnamespace {\n\nEigen::Vector3f getRealSortedEigenValues(Eigen::Matrix<std::complex<float>, 3, 1> eigenValues)\n{\n  Eigen::Vector3f realEigenValues;\n  for (std::size_t i = 0; i < 3; i++){\n    realEigenValues(i) = std::real(eigenValues(i));\n  }\n  if (realEigenValues(0) > realEigenValues(1))\n    std::swap(realEigenValues(0), realEigenValues(1));\n  if (realEigenValues(1) > realEigenValues(2))\n    std::swap(realEigenValues(1), realEigenValues(2));\n  if (realEigenValues(0) > realEigenValues(1))\n    std::swap(realEigenValues(0), realEigenValues(1));\n  // std::cout << \"realEigenValues: \" << realEigenValues << \"\\n\";\n  return realEigenValues; \n}\n\n} // namespace\n\nnamespace pcl {\n\n// L: linearity, P: planarity, S: sphericality\nstruct PointXYZLPS\n{\n\tPCL_ADD_POINT4D;\n\t// union\n\t// {\n\t// \tfloat coordinate[3];\n\t// \tstruct\n\t// \t{\n\t// \t\tfloat x;\n\t// \t\tfloat y;\n\t// \t\tfloat z;\n\t// \t};\n\t// };\n\tfloat linearity;\n\tfloat planarity;\n\tfloat sphericity;\n\tEIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n} EIGEN_ALIGN16;\n\nstruct PointXYZILPS\n{\n    PCL_ADD_POINT4D;                  // preferred way of adding a XYZ+padding\n    float intensity;\n    float linearity;\n\tfloat planarity;\n\tfloat sphericity;\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW   // make sure our new allocators are aligned\n} EIGEN_ALIGN16;                    // enforce SSE padding for correct memory alignment\n\n\n// struct PointXYZILPS\n// {\n// \t// PCL_ADD_POINT4D;\n// \tunion\n// \t{\n// \t\tfloat coordinate[3];\n// \t\tstruct\n// \t\t{\n// \t\t\tfloat x;\n// \t\t\tfloat y;\n// \t\t\tfloat z;\n// \t\t};\n// \t};\n//     float intensity;\n// \tfloat linearity;\n// \tfloat planarity;\n// \tfloat sphericity;\n// \tEIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n// } EIGEN_ALIGN16;\n\ntemplate <typename PointInT, typename PointOutT>\nclass DescriptorEstimation : public Feature<PointInT, PointOutT>\n{\n    typedef typename DescriptorEstimation<PointInT, PointOutT>::PointCloudOut PointCloudOut;\n    using Feature<PointInT, PointOutT>::input_;\n    using Feature<PointInT, PointOutT>::search_parameter_;\n    using Feature<PointInT, PointOutT>::search_radius_;\n    typedef boost::shared_ptr<NormalEstimation<PointInT, PointOutT> > Ptr;\n    typedef boost::shared_ptr<const NormalEstimation<PointInT, PointOutT> > ConstPtr;\n\nprotected:\n\n    void computeFeature (PointCloudOut &output)\n    {\n        for (int i = 0; i < input_->size(); i++){\n            const PointInT& searchPoint = input_->points[i];\n            std::vector<int> pointIdxRadiusSearch;\n            std::vector<float> pointRadiusSquaredDistance;\n            // kdtree.radiusSearch (searchPoint, radius, pointIdxRadiusSearch, pointRadiusSquaredDistance);\n            \n            this->searchForNeighbors (i, search_parameter_, pointIdxRadiusSearch, pointRadiusSquaredDistance);\n            \n            if (pointIdxRadiusSearch.size() < 5) {\n                continue;\n            }\n            typename pcl::PointCloud<PointInT>::Ptr neighbours (new pcl::PointCloud<PointInT>);\n            for (std::size_t j = 0; j < pointIdxRadiusSearch.size (); ++j){\n                neighbours->points.push_back(input_->points[ pointIdxRadiusSearch[j]]);\n            }\n            \n            \n            Eigen::Matrix3f covariance_matrix;\n\n            // 16-bytes aligned placeholder for the XYZ centroid of a surface patch\n            Eigen::Vector4f xyz_centroid;\n            \n            pcl::compute3DCentroid (*neighbours, xyz_centroid);\n            // Compute the 3x3 covariance matrix\n            pcl::computeCovarianceMatrix (*neighbours, xyz_centroid, covariance_matrix);\n            // std::cout << \"CCCC\" << std::endl;\n            // std::cout << \"covariance_matrix: \\n\" << covariance_matrix << \"\\n\";\n            // std::cout << \"xyz_centroid: \\n\" << xyz_centroid << \"\\n\";\n\n            Eigen::EigenSolver<Eigen::Matrix3f> eig(covariance_matrix);     // [vec val] = eig(A)\n            // std::cout << \"DDDD\" << std::endl;\n            Eigen::Matrix<std::complex<float>, 3, 1> eigenComplexValues = eig.eigenvalues();\n            // std::cout << \"EEEE\" << std::endl;\n            // Eigen::Matrix3f D = eig.pseudoEigenvalueMatrix();\n\n            // int col_index, row_index;\n            // std::cout << D.maxCoeff(&row_index, &col_index) << endl;\n            // std::cout << row_index << \" \" << col_index << endl;\n            // std::cout << \"eigen value matrix: \" << getRealSortedEigenValues(eigenValues) << \"\\n\";\n            Eigen::Vector3f eigenValues = getRealSortedEigenValues(eigenComplexValues);\n            // std::cout << \"FFFF\" << std::endl;\n\n            PointOutT pointWithFeature;\n\n            pointWithFeature.x = searchPoint.x;\n            pointWithFeature.y = searchPoint.y;\n            pointWithFeature.z = searchPoint.z;\n            pointWithFeature.linearity = 1 - eigenValues[1] / eigenValues[2];\n            pointWithFeature.planarity = (eigenValues[1] - eigenValues[0]) / eigenValues[2];\n            pointWithFeature.sphericity = eigenValues[0] / eigenValues[2];\n            output.points.push_back(pointWithFeature);\n\n\n            // float linearity = 1 - eigenValues[1] / eigenValues[2];\n            // float planarity = (eigenValues[1] - eigenValues[0]) / eigenValues[2];\n            // float sphericity = eigenValues[0] / eigenValues[2];\n            // std::cout << \"(\" << linearity << \", \" << planarity << \", \" << sphericity << \")\" << std::endl;\n            // cloud->points[i].linearity = linearity;\n            // cloud->points[i].planarity = planarity;\n            // cloud->points[i].sphericity = sphericity;\n\n        }\n    }\n\n}; // class DescriptorEstimation\n\n} // namespace pcl\n\n \nPOINT_CLOUD_REGISTER_POINT_STRUCT(PointXYZLPS,// \u6ce8\u518c\u70b9\u7c7b\u578b\u5b8f\n\t(float, x, x)\n\t(float, y, y)\n\t(float, z, z)\n\t(float, linearity, linearity)\n\t(float, planarity, planarity)\n\t(float, sphericity, sphericity)\n)\n\nPOINT_CLOUD_REGISTER_POINT_STRUCT(PointXYZILPS,\n\t(float, x, x)\n\t(float, y, y)\n\t(float, z, z)\n    (float, intensity, intensity)\n\t(float, linearity, linearity)\n\t(float, planarity, planarity)\n\t(float, sphericity, sphericity)\n)\n\n// pcl::NormalEstimation<PointTypeIO, PointTypeFull> ne;\n// ne.setInputCloud (cloud_out);\n// ne.setSearchMethod (search_tree);\n// ne.setRadiusSearch (1);\n// ne.compute (*cloud_with_normals);\n\n\ntypedef pcl::PointXYZ PointIn;\ntypedef pcl::PointXYZLPS PointOut;\n\nint test_new(int argc, char** argv)\n{\n    pcl::PointCloud<PointIn>::Ptr cloud(new pcl::PointCloud<PointIn>);\n    pcl::PointCloud<PointOut>::Ptr cloud_out(new pcl::PointCloud<PointOut>);\n\n    pcl::io::loadPCDFile<PointIn> (argv[1], *cloud);\n    // pcl::io::loadPLYFile<PointT> (argv[1], *cloud);\n\n    pcl::VoxelGrid<PointIn> sor;\n\tsor.setInputCloud(cloud);\n\tsor.setLeafSize(0.1f, 0.1f, 0.1f);\n\tsor.filter(*cloud);\n\n    // pcl::KdTreeFLANN<PointIn> kdtree;\n    pcl::search::KdTree<PointIn>::Ptr search_tree (new pcl::search::KdTree<PointIn>);\n    search_tree->setInputCloud (cloud);\n\n    pcl::DescriptorEstimation<PointIn, PointOut> de;\n    de.setInputCloud(cloud);\n    de.setSearchMethod(search_tree);\n    de.setRadiusSearch(1);\n    de.compute (*cloud_out);\n\n    cloud_out->width = 1;\n    cloud_out->height = cloud_out->points.size();\n    pcl::io::savePCDFile (\"descriptors_output.pcd\", *cloud_out);\n\n    return 0;\n\n}\n\nint test_gt(int argc, char** argv)\n{\n    pcl::PointCloud<PointIn>::Ptr cloud (new pcl::PointCloud<PointIn>);\n    pcl::PointCloud<PointOut>::Ptr cloudOut (new pcl::PointCloud<PointOut>);\n\n    pcl::io::loadPCDFile<PointIn> (argv[1], *cloud);\n    // pcl::io::loadPLYFile<PointT> (argv[1], *cloud);\n\n    pcl::VoxelGrid<PointIn> sor;\n\tsor.setInputCloud(cloud);\n\tsor.setLeafSize(0.1f, 0.1f, 0.1f);\n\tsor.filter(*cloud);\n\n    // Placeholder for the 3x3 covariance matrix at each surface patch\n    Eigen::Matrix3f covariance_matrix;\n    // 16-bytes aligned placeholder for the XYZ centroid of a surface patch\n    Eigen::Vector4f xyz_centroid;\n\n    // Estimate the XYZ centroid\n    pcl::compute3DCentroid (*cloud, xyz_centroid);\n\n    // Compute the 3x3 covariance matrix\n    pcl::computeCovarianceMatrix (*cloud, xyz_centroid, covariance_matrix);\n\n    // std::cout << \"covariance_matrix: \\n\" << covariance_matrix << \"\\n\";\n    // std::cout << \"xyz_centroid: \\n\" << xyz_centroid << \"\\n\";\n\n    pcl::KdTreeFLANN<PointIn> kdtree;\n\n    kdtree.setInputCloud (cloud);\n\n    \n    float radius = 0.5f;\n\n    std::cout << \"Done\" << std::endl;\n\n    for (int i = 0; i < cloud->size(); i++){\n        PointIn searchPoint = cloud->points[i];\n        std::vector<int> pointIdxRadiusSearch;\n        std::vector<float> pointRadiusSquaredDistance;\n        kdtree.radiusSearch (searchPoint, radius, pointIdxRadiusSearch, pointRadiusSquaredDistance);\n        \n        pcl::PointCloud<PointIn>::Ptr neighbours (new pcl::PointCloud<PointIn>);\n        for (std::size_t j = 0; j < pointIdxRadiusSearch.size (); ++j){\n        neighbours->points.push_back(cloud->points[ pointIdxRadiusSearch[j]]);\n\n        }\n        if (neighbours->points.size() < 5) {\n            continue;\n        }\n        pcl::compute3DCentroid (*neighbours, xyz_centroid);\n        // std::cout << \"BBBB\" << std::endl;\n        // Compute the 3x3 covariance matrix\n        pcl::computeCovarianceMatrix (*neighbours, xyz_centroid, covariance_matrix);\n        // std::cout << \"CCCC\" << std::endl;\n        // std::cout << \"covariance_matrix: \\n\" << covariance_matrix << \"\\n\";\n        // std::cout << \"xyz_centroid: \\n\" << xyz_centroid << \"\\n\";\n\n        Eigen::EigenSolver<Eigen::Matrix3f> eig(covariance_matrix);     // [vec val] = eig(A)\n        // std::cout << \"DDDD\" << std::endl;\n        Eigen::Matrix<std::complex<float>, 3, 1> eigenComplexValues = eig.eigenvalues();\n        // std::cout << \"EEEE\" << std::endl;\n        // Eigen::Matrix3f D = eig.pseudoEigenvalueMatrix();\n\n        // int col_index, row_index;\n        // std::cout << D.maxCoeff(&row_index, &col_index) << endl;\n        // std::cout << row_index << \" \" << col_index << endl;\n        // std::cout << \"eigen value matrix: \" << getRealSortedEigenValues(eigenValues) << \"\\n\";\n        Eigen::Vector3f eigenValues = getRealSortedEigenValues(eigenComplexValues);\n        // std::cout << \"FFFF\" << std::endl;\n\n        PointOut pointWithFeature;\n\n        pointWithFeature.x = searchPoint.x;\n        pointWithFeature.y = searchPoint.y;\n        pointWithFeature.z = searchPoint.z;\n        pointWithFeature.linearity = 1 - eigenValues[1] / eigenValues[2];\n        pointWithFeature.planarity = (eigenValues[1] - eigenValues[0]) / eigenValues[2];\n        pointWithFeature.sphericity = eigenValues[0] / eigenValues[2];\n        cloudOut->points.push_back(pointWithFeature);\n\n\n        // float linearity = 1 - eigenValues[1] / eigenValues[2];\n        // float planarity = (eigenValues[1] - eigenValues[0]) / eigenValues[2];\n        // float sphericity = eigenValues[0] / eigenValues[2];\n        // std::cout << \"(\" << linearity << \", \" << planarity << \", \" << sphericity << \")\" << std::endl;\n        // cloud->points[i].linearity = linearity;\n        // cloud->points[i].planarity = planarity;\n        // cloud->points[i].sphericity = sphericity;\n\n    }\n\n    cloudOut->width = 1;\n    cloudOut->height = cloudOut->points.size();\n    pcl::io::savePCDFile (\"descriptors_output.pcd\", *cloudOut);\n    \n    return 0;\n}\n", "meta": {"hexsha": "e6b6744b543073052dc4c3ab54b17f8af3fcaee2", "size": 11366, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cloud_processing/cpp/descriptors.hpp", "max_stars_repo_name": "MinesNicaicai/large-scale-pointcloud-matching", "max_stars_repo_head_hexsha": "cfe140f2be1110ed75b6edd27538021e513a31c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-21T16:39:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-21T16:39:51.000Z", "max_issues_repo_path": "cloud_processing/cpp/descriptors.hpp", "max_issues_repo_name": "MinesNicaicai/large-scale-pointcloud-matching", "max_issues_repo_head_hexsha": "cfe140f2be1110ed75b6edd27538021e513a31c9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cloud_processing/cpp/descriptors.hpp", "max_forks_repo_name": "MinesNicaicai/large-scale-pointcloud-matching", "max_forks_repo_head_hexsha": "cfe140f2be1110ed75b6edd27538021e513a31c9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-13T14:51:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-13T14:51:44.000Z", "avg_line_length": 34.8650306748, "max_line_length": 110, "alphanum_fraction": 0.6323244765, "num_tokens": 3085, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.4965828172638058}}
{"text": "#include \"logit_sb_mixing.h\"\n\n#include <google/protobuf/stubs/casts.h>\n\n#include <Eigen/Dense>\n#include <memory>\n#include <numeric>\n#include <stan/math/prim.hpp>\n#include <vector>\n\n#include \"mixing_prior.pb.h\"\n#include \"mixing_state.pb.h\"\n#include \"src/hierarchies/abstract_hierarchy.h\"\n#include \"src/utils/proto_utils.h\"\n#include \"src/utils/rng.h\"\n\nvoid LogitSBMixing::initialize() {\n  if (prior == nullptr) {\n    throw std::invalid_argument(\"Mixing prior was not provided\");\n  }\n  auto priorcast = cast_prior();\n  num_components = priorcast->num_components();\n  initialize_state();\n  acceptance_rates = Eigen::VectorXd::Zero(num_components - 1);\n  n_iter = 0;\n}\n\nvoid LogitSBMixing::initialize_state() {\n  auto priorcast = cast_prior();\n  if (priorcast->has_normal_prior()) {\n    Eigen::VectorXd prior_vec =\n        bayesmix::to_eigen(priorcast->normal_prior().mean());\n    dim = prior_vec.size();\n    state.precision = stan::math::inverse_spd(\n        bayesmix::to_eigen(priorcast->normal_prior().var()));\n    if (dim != state.precision.cols()) {\n      throw std::invalid_argument(\n          \"Hyperparameters dimensions are not consisent\");\n    }\n    if (priorcast->step_size() <= 0) {\n      throw std::invalid_argument(\"Step size parameter must be > 0\");\n    }\n\n    state.regression_coeffs = Eigen::MatrixXd(dim, num_components - 1);\n    for (int i = 0; i < num_components - 1; i++) {\n      state.regression_coeffs.col(i) = prior_vec;\n    }\n\n  } else {\n    throw std::invalid_argument(\"Unrecognized mixing prior\");\n  }\n}\n\ndouble LogitSBMixing::full_cond_lpdf(\n    const Eigen::VectorXd &alpha, const unsigned int clust,\n    const std::vector<unsigned int> &allocations) {\n  auto priorcast = cast_prior();\n  Eigen::VectorXd prior_mean =\n      bayesmix::to_eigen(priorcast->normal_prior().mean());\n  double like = -0.5 * ((alpha - prior_mean).transpose() * state.precision *\n                        (alpha - prior_mean))(0);\n  for (int i = 0; i < allocations.size(); i++) {\n    if (allocations[i] >= clust) {\n      double is_curr_clus = (allocations[i] == clust);\n      double prob = sigmoid(covariates_ptr->row(i).dot(alpha));\n      like += is_curr_clus * std::log(prob) +\n              (1.0 - is_curr_clus) * std::log(1.0 - prob);\n    }\n  }\n  return like;\n}\n\nEigen::VectorXd LogitSBMixing::grad_full_cond_lpdf(\n    const Eigen::VectorXd &alpha, const unsigned int clust,\n    const std::vector<unsigned int> &allocations) {\n  auto priorcast = cast_prior();\n  Eigen::VectorXd prior_mean =\n      bayesmix::to_eigen(priorcast->normal_prior().mean());\n  Eigen::VectorXd grad = state.precision * (prior_mean - alpha);\n  for (int i = 0; i < allocations.size(); i++) {\n    if (allocations[i] >= clust) {\n      double is_curr_clus = (allocations[i] == clust);\n      double prob = sigmoid(covariates_ptr->row(i).dot(alpha));\n      grad += (is_curr_clus - prob) * covariates_ptr->row(i);\n    }\n  }\n  return grad;\n}\n\nvoid LogitSBMixing::update_state(\n    const std::vector<std::shared_ptr<AbstractHierarchy>> &unique_values,\n    const std::vector<unsigned int> &allocations) {\n  n_iter += 1;\n  // Langevin-Adjusted Metropolis-Hastings step\n  unsigned int n = allocations.size();\n  auto &rng = bayesmix::Rng::Instance().get();\n  auto priorcast = cast_prior();\n  Eigen::VectorXd prior_mean =\n      bayesmix::to_eigen(priorcast->normal_prior().mean());\n  double step = priorcast->step_size();\n  double prop_var = std::sqrt(2.0 * step);\n  // Loop over components\n  for (int h = 0; h < num_components - 1; h++) {\n    Eigen::VectorXd state_c = state.regression_coeffs.col(h);\n    // Draw proposed state from its distribution\n    Eigen::VectorXd prop_mean =\n        state_c + step * grad_full_cond_lpdf(state_c, h, allocations);\n    auto prop_covar = prop_var * Eigen::MatrixXd::Identity(dim, dim);\n    Eigen::VectorXd state_prop =\n        stan::math::multi_normal_rng(prop_mean, prop_covar, rng);\n    // Compute acceptance ratio\n    double full_cond_ratio = full_cond_lpdf(state_prop, h, allocations) -\n                             full_cond_lpdf(state_c, h, allocations);\n    double prop_ratio = (-0.5 / prop_var) *\n                        ((state_prop - prop_mean).dot(state_prop - prop_mean) -\n                         (state_c - prop_mean).dot(state_c - prop_mean));\n    double log_accept_ratio = full_cond_ratio - prop_ratio;\n    // Accept with probability ratio\n    double p = stan::math::uniform_rng(0.0, 1.0, rng);\n    if (p < std::exp(log_accept_ratio)) {\n      state.regression_coeffs.col(h) = state_prop;\n      acceptance_rates(h) += 1;\n    }\n  }\n}\n\nvoid LogitSBMixing::set_state_from_proto(\n    const google::protobuf::Message &state_) {\n  auto &statecast =\n      google::protobuf::internal::down_cast<const bayesmix::MixingState &>(\n          state_);\n  state.regression_coeffs =\n      bayesmix::to_eigen(statecast.log_sb_state().regression_coeffs());\n}\n\nvoid LogitSBMixing::write_state_to_proto(\n    google::protobuf::Message *out) const {\n  bayesmix::LogSBState state_;\n  bayesmix::to_proto(state.regression_coeffs,\n                     state_.mutable_regression_coeffs());\n  google::protobuf::internal::down_cast<bayesmix::MixingState *>(out)\n      ->mutable_log_sb_state()\n      ->CopyFrom(state_);\n}\n\nEigen::VectorXd LogitSBMixing::get_weights(\n    const bool log, const bool propto,\n    const Eigen::RowVectorXd &covariate /*= Eigen::RowVectorXd(0)*/) const {\n  // Compute eta\n  std::vector<double> eta(num_components);\n  for (int h = 0; h < num_components - 1; h++) {\n    eta[h] = covariate.dot(state.regression_coeffs.col(h));\n  }\n  eta[num_components - 1] = 1.0;\n  // Compute cumulative sums of logarithms\n  std::vector<double> cumsum(num_components + 1, 0.0);\n  for (int h = 1; h < num_components + 1; h++) {\n    cumsum[h] = cumsum[h - 1] + std::log(sigmoid(-eta[h - 1]));\n  }\n  // Compute weights\n  Eigen::VectorXd logweights(num_components);\n  for (int h = 0; h < num_components; h++) {\n    logweights(h) = std::log(sigmoid(eta[h])) + cumsum[h];\n  }\n  if (log) {\n    return logweights;\n  } else {\n    return logweights.array().exp();\n  }\n}\n", "meta": {"hexsha": "442e1149a5232950c0f2d5a58656d4e574efee74", "size": 6051, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/mixings/logit_sb_mixing.cc", "max_stars_repo_name": "bayesmix-dev/bayesmix", "max_stars_repo_head_hexsha": "b704b37a740b008f7c22527151026b041a5fe120", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2020-10-13T16:45:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T13:50:42.000Z", "max_issues_repo_path": "src/mixings/logit_sb_mixing.cc", "max_issues_repo_name": "bayesmix-dev/bayesmix", "max_issues_repo_head_hexsha": "b704b37a740b008f7c22527151026b041a5fe120", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 90.0, "max_issues_repo_issues_event_min_datetime": "2020-10-26T09:49:37.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T07:23:38.000Z", "max_forks_repo_path": "src/mixings/logit_sb_mixing.cc", "max_forks_repo_name": "bayesmix-dev/bayesmix", "max_forks_repo_head_hexsha": "b704b37a740b008f7c22527151026b041a5fe120", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2020-11-17T06:52:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-15T12:08:47.000Z", "avg_line_length": 35.3859649123, "max_line_length": 79, "alphanum_fraction": 0.6600561891, "num_tokens": 1624, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.6261241842048092, "lm_q1q2_score": 0.49658281667313137}}
{"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_FULLCONNLAYER_HH\n#define NETKET_FULLCONNLAYER_HH\n\n#include <Eigen/Dense>\n#include <complex>\n#include <fstream>\n#include <random>\n#include <vector>\n#include \"Lookup/lookup.hpp\"\n#include \"Utils/all_utils.hpp\"\n#include \"abstract_layer.hpp\"\n\nnamespace netket {\n\ntemplate <typename Activation, typename T>\nclass FullyConnected : public AbstractLayer<T> {\n  using VectorType = typename AbstractLayer<T>::VectorType;\n  using MatrixType = typename AbstractLayer<T>::MatrixType;\n\n  Activation activation_;  // activation function class\n\n  bool usebias_;\n\n  int in_size_;        // input size\n  int out_size_;       // output size\n  int npar_;           // number of parameters in layer\n  MatrixType weight_;  // Weight parameters, W(in_size x out_size)\n  VectorType bias_;    // Bias parameters, b(out_size x 1)\n                       // Note that input of this layer is also the output of\n                       // previous layer\n\n  std::size_t scalar_bytesize_;\n\n public:\n  using StateType = typename AbstractLayer<T>::StateType;\n  using LookupType = typename AbstractLayer<T>::LookupType;\n\n  /// Constructor\n  FullyConnected(const int input_size, const int output_size,\n                 const bool use_bias = false)\n      : activation_(),\n        usebias_(use_bias),\n        in_size_(input_size),\n        out_size_(output_size) {\n    Init();\n  }\n\n  explicit FullyConnected(const json &pars) : activation_() { Init(pars); }\n\n  void Init(const json &pars) {\n    in_size_ = FieldVal(pars, \"Inputs\");\n    out_size_ = FieldVal(pars, \"Outputs\");\n\n    usebias_ = FieldOrDefaultVal(pars, \"UseBias\", true);\n\n    scalar_bytesize_ = sizeof(std::complex<double>);\n\n    weight_.resize(in_size_, out_size_);\n    bias_.resize(out_size_);\n\n    npar_ = in_size_ * out_size_;\n\n    if (usebias_) {\n      npar_ += out_size_;\n    } else {\n      bias_.setZero();\n    }\n    std::string buffer = \"\";\n\n    InfoMessage(buffer) << \"Fully Connected Layer \" << in_size_ << \" --> \"\n                        << out_size_ << std::endl;\n    InfoMessage(buffer) << \"# # UseBias = \" << usebias_ << std::endl;\n  }\n\n  void Init() {\n    scalar_bytesize_ = sizeof(std::complex<double>);\n\n    weight_.resize(in_size_, out_size_);\n    bias_.resize(out_size_);\n\n    npar_ = in_size_ * out_size_;\n\n    if (usebias_) {\n      npar_ += out_size_;\n    } else {\n      bias_.setZero();\n    }\n\n    std::string buffer = \"\";\n\n    InfoMessage(buffer) << \"Fully Connected Layer \" << in_size_ << \" --> \"\n                        << out_size_ << std::endl;\n    InfoMessage(buffer) << \"# # UseBias = \" << usebias_ << std::endl;\n  }\n\n  void to_json(json &pars) const override {\n    json layerpar;\n    layerpar[\"Name\"] = \"FullyConnected\";\n    layerpar[\"UseBias\"] = usebias_;\n    layerpar[\"Inputs\"] = in_size_;\n    layerpar[\"Outputs\"] = out_size_;\n    layerpar[\"Bias\"] = bias_;\n    layerpar[\"Weight\"] = weight_;\n\n    pars[\"Machine\"][\"Layers\"].push_back(layerpar);\n  }\n\n  void from_json(const json &pars) override {\n    if (FieldExists(pars, \"Weight\")) {\n      weight_ = pars[\"Weight\"];\n    } else {\n      weight_.setZero();\n    }\n    if (FieldExists(pars, \"Bias\")) {\n      bias_ = pars[\"Bias\"];\n    } else {\n      bias_.setZero();\n    }\n  }\n\n  void InitRandomPars(int seed, double sigma) override {\n    VectorType par(npar_);\n\n    netket::RandomGaussian(par, seed, sigma);\n\n    SetParameters(par, 0);\n  }\n\n  int Npar() const override { return npar_; }\n\n  int Ninput() const override { return in_size_; }\n\n  int Noutput() const override { return out_size_; }\n\n  void GetParameters(VectorType &pars, int start_idx) const override {\n    int k = start_idx;\n\n    if (usebias_) {\n      std::memcpy(pars.data() + k, bias_.data(), out_size_ * scalar_bytesize_);\n      k += out_size_;\n    }\n\n    std::memcpy(pars.data() + k, weight_.data(),\n                in_size_ * out_size_ * scalar_bytesize_);\n  }\n\n  void SetParameters(const VectorType &pars, int start_idx) override {\n    int k = start_idx;\n\n    if (usebias_) {\n      std::memcpy(bias_.data(), pars.data() + k, out_size_ * scalar_bytesize_);\n\n      k += out_size_;\n    }\n\n    std::memcpy(weight_.data(), pars.data() + k,\n                in_size_ * out_size_ * scalar_bytesize_);\n  }\n\n  void InitLookup(const VectorType &v, LookupType &lt,\n                  VectorType &output) override {\n    lt.resize(1);\n    lt[0].resize(out_size_);\n\n    Forward(v, lt, output);\n  }\n\n  void UpdateLookup(const VectorType &input,\n                    const std::vector<int> &input_changes,\n                    const VectorType &new_input, LookupType &theta,\n                    const VectorType & /*output*/,\n                    std::vector<int> &output_changes,\n                    VectorType &new_output) override {\n    const int num_of_changes = input_changes.size();\n    if (num_of_changes == in_size_) {\n      output_changes.resize(out_size_);\n      new_output.resize(out_size_);\n      Forward(new_input, theta, new_output);\n    } else if (num_of_changes > 0) {\n      UpdateTheta(input, input_changes, new_input, theta);\n      output_changes.resize(out_size_);\n      new_output.resize(out_size_);\n      Forward(theta, new_output);\n    } else {\n      output_changes.resize(0);\n      new_output.resize(0);\n    }\n  }\n\n  void UpdateLookup(const Eigen::VectorXd &input,\n                    const std::vector<int> &tochange,\n                    const std::vector<double> &newconf, LookupType &theta,\n                    const VectorType & /*output*/,\n                    std::vector<int> &output_changes,\n                    VectorType &new_output) override {\n    const int num_of_changes = tochange.size();\n    if (num_of_changes > 0) {\n      UpdateTheta(input, tochange, newconf, theta);\n      output_changes.resize(out_size_);\n      new_output.resize(out_size_);\n      Forward(theta, new_output);\n    } else {\n      output_changes.resize(0);\n      new_output.resize(0);\n    }\n  }\n\n  // Feedforward\n  void Forward(const VectorType &prev_layer_output, LookupType &theta,\n               VectorType &output) override {\n    LinearTransformation(prev_layer_output, theta);\n    NonLinearTransformation(theta, output);\n  }\n\n  // Feedforward Using lookup\n  void Forward(const LookupType &theta, VectorType &output) override {\n    // Apply activation function\n    NonLinearTransformation(theta, output);\n  }\n\n  // Applies the linear transformation\n  inline void LinearTransformation(const VectorType &input, LookupType &theta) {\n    theta[0] = bias_;\n    theta[0].noalias() += weight_.transpose() * input;\n  }\n\n  // Applies the nonlinear transformation\n  inline void NonLinearTransformation(const LookupType &theta,\n                                      VectorType &output) {\n    activation_(theta[0], output);\n  }\n\n  // Updates theta given the input v, the change in the input (input_changes and\n  // prev_input)\n  inline void UpdateTheta(const VectorType &v,\n                          const std::vector<int> &input_changes,\n                          const VectorType &new_input, LookupType &theta) {\n    const int num_of_changes = input_changes.size();\n    for (int s = 0; s < num_of_changes; s++) {\n      const int sf = input_changes[s];\n      theta[0] += weight_.row(sf) * (new_input(s) - v(sf));\n    }\n  }\n\n  // Updates theta given the previous input prev_input and the change in the\n  // input (tochange and  newconf)\n  inline void UpdateTheta(const VectorType &prev_input,\n                          const std::vector<int> &tochange,\n                          const std::vector<double> &newconf,\n                          LookupType &theta) {\n    const int num_of_changes = tochange.size();\n    for (int s = 0; s < num_of_changes; s++) {\n      const int sf = tochange[s];\n      theta[0] += weight_.row(sf) * (newconf[s] - prev_input(sf));\n    }\n  }\n\n  // Computes derivative.\n  void Backprop(const VectorType &prev_layer_output,\n                const VectorType &this_layer_output,\n                const LookupType &this_layer_theta, const VectorType &dout,\n                VectorType &din, VectorType &der, int start_idx) override {\n    // After forward stage, m_z contains z = W' * in + b\n    // Now we need to calculate d(L) / d(z) = [d(a) / d(z)] * [d(L) / d(a)]\n    // d(L) / d(a) is computed in the next layer, contained in next_layer_data\n    // The Jacobian matrix J = d(a) / d(z) is determined by the activation\n    // function\n    VectorType dLz(out_size_);\n    activation_.ApplyJacobian(this_layer_theta[0], this_layer_output, dout,\n                              dLz);\n\n    // Now dLz contains d(L) / d(z)\n    // Derivative for bias, d(L) / d(b) = d(L) / d(z)\n    int k = start_idx;\n\n    if (usebias_) {\n      Eigen::Map<VectorType> der_b{der.data() + k, out_size_};\n\n      der_b.noalias() = dLz;\n      k += out_size_;\n    }\n\n    // Derivative for weights, d(L) / d(W) = [d(L) / d(z)] * in'\n    Eigen::Map<MatrixType> der_w{der.data() + k, in_size_, out_size_};\n\n    der_w.noalias() = prev_layer_output * dLz.transpose();\n\n    // Compute d(L) / d_in = W * [d(L) / d(z)]\n    din.noalias() = weight_ * dLz;\n  }\n};\n}  // namespace netket\n\n#endif\n", "meta": {"hexsha": "0af019a3d1728884aececfdbd2296e14e3f8ce78", "size": 9657, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "NetKet/Machine/fullconn_layer.hpp", "max_stars_repo_name": "stavros11/netket", "max_stars_repo_head_hexsha": "1cec25a4884bdbd2fddb5d24daae627cd89316d8", "max_stars_repo_licenses": ["Apache-2.0"], "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/fullconn_layer.hpp", "max_issues_repo_name": "stavros11/netket", "max_issues_repo_head_hexsha": "1cec25a4884bdbd2fddb5d24daae627cd89316d8", "max_issues_repo_licenses": ["Apache-2.0"], "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/fullconn_layer.hpp", "max_forks_repo_name": "stavros11/netket", "max_forks_repo_head_hexsha": "1cec25a4884bdbd2fddb5d24daae627cd89316d8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-09-15T17:24:23.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-15T17:24:23.000Z", "avg_line_length": 31.2524271845, "max_line_length": 80, "alphanum_fraction": 0.6234855545, "num_tokens": 2391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105941403651, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.4965828160824564}}
{"text": "#include <tiny_math_types.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n\nBOOST_AUTO_TEST_SUITE(tiny_quaternion_rotate);\n\nBOOST_AUTO_TEST_CASE(simple_test)\n{\n  typedef tiny::MathTypes<double> math_types;\n\n  typedef math_types::value_traits     value_traits;\n  typedef math_types::real_type        T;\n  typedef math_types::vector3_type     V;\n  typedef math_types::quaternion_type  Q;\n\n  BOOST_CHECK(  Q::accessor::stride()     == 1);\n  BOOST_CHECK(  Q::accessor::padding()    == 0);\n  BOOST_CHECK(  Q::accessor::J_padded()   == 4);\n  BOOST_CHECK(  Q::accessor::allocsize()  == 4);\n  \n  {\n    // Set up a test rotation\n    Q q;\n    T const phi = value_traits::pi_half();\n    V const m = V::make( 1.0, 0.0, 0.0 );\n    q = Q::Ru( phi, m);\n    BOOST_CHECK_CLOSE( tiny::norm( q ), value_traits::one(), 0.01 );\n    V const n = V::make( 0.0, 1.0, 0.0 );\n    // Try to rotate n-vector\n    V const k = tiny::rotate( q, n);\n    // Test if result is what we expect\n    BOOST_CHECK( fabs( k(0) ) < 10e-10 );\n    BOOST_CHECK( fabs( k(1) ) < 10e-10 );\n    BOOST_CHECK( fabs( 1.0 - k(2) ) < 10e-10 );\n  }\n  {\n    // Set up a test rotation\n    Q q;\n    T const phi = value_traits::pi_half();\n    V const m = V::make( 1.0, 0.0, 0.0 );\n    q = Q::Ru( phi, m);\n    BOOST_CHECK_CLOSE( tiny::norm( q ), value_traits::one(), 0.01 );\n    V const n = V::make( 0.0, 0.0, 1.0 );\n    // Try to rotate n-vector\n    V const k = tiny::rotate( q, n);\n    // Test if result is what we expect\n    BOOST_CHECK( fabs( k(0) ) < 10e-10 );\n    BOOST_CHECK( fabs( 1.0 + k(1) ) < 10e-10 );\n    BOOST_CHECK( fabs( k(2) ) < 10e-10 );\n  }\n  {\n    // Set up a test rotation\n    Q q;\n    T const phi = value_traits::pi_half();\n    V const m = V::make( 1.0, 0.0, 0.0 );\n    q = Q::Ru( phi, m);\n    BOOST_CHECK_CLOSE( tiny::norm( q ), value_traits::one(), 0.01 );\n    V const n = V::make( 0.0, -1.0, 0.0 );\n    // Try to rotate n-vector\n    V const k = tiny::rotate( q, n);\n    // Test if result is what we expect\n    BOOST_CHECK( fabs( k(0) ) < 10e-10 );\n    BOOST_CHECK( fabs( k(1) ) < 10e-10 );\n    BOOST_CHECK( fabs( 1.0 + k(2) ) < 10e-10 );\n  }\n  {\n    // Set up a test rotation\n    Q q;\n    T const phi = value_traits::pi_half();\n    V const m = V::make( 1.0, 0.0, 0.0 );\n    q = Q::Ru( phi, m);\n    BOOST_CHECK_CLOSE( tiny::norm( q ), value_traits::one(), 0.01 );\n    V const n = V::make( 0.0, 0.0, -1.0 );\n    // Try to rotate n-vector\n    V const k = tiny::rotate( q, n);\n    // Test if result is what we expect\n    BOOST_CHECK( fabs( k(0) ) < 10e-10 );\n    BOOST_CHECK( fabs( 1.0 - k(1) ) < 10e-10 );\n    BOOST_CHECK( fabs( k(2) ) < 10e-10 );\n  }\n  {\n    // Set up a test rotation\n    Q q;\n    T const phi = value_traits::pi_half();\n    V const m = V::make( 0.0, 1.0, 0.0 );\n    q = Q::Ru( phi, m);\n    BOOST_CHECK_CLOSE( tiny::norm( q ), value_traits::one(), 0.01 );\n    V const n = V::make( 1.0, 0.0, 0.0 );\n    // Try to rotate n-vector\n    V const k = tiny::rotate( q, n);\n    // Test if result is what we expect\n    BOOST_CHECK( fabs( k(0) ) < 10e-10 );\n    BOOST_CHECK( fabs( k(1) ) < 10e-10 );\n    BOOST_CHECK( fabs( 1.0 + k(2) ) < 10e-10 );\n  }\n  {\n    // Set up a test rotation\n    Q q;\n    T const phi = value_traits::pi_half();\n    V const m = V::make( 0.0, 0.0, 1.0 );\n    q = Q::Ru( phi, m);\n    BOOST_CHECK_CLOSE( tiny::norm( q ), value_traits::one(), 0.01 );\n    V const n = V::make( 1.0, 0.0, 0.0 );\n    // Try to rotate n-vector\n    V const k = tiny::rotate( q, n);\n    // Test if result is what we expect\n    BOOST_CHECK( fabs( k(0) ) < 10e-10 );\n    BOOST_CHECK( fabs( 1.0 - k(1) ) < 10e-10 );\n    BOOST_CHECK( fabs( k(2) ) < 10e-10 );\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "cbc41e4b75aad9cdc8987c28bb6d76250845c192", "size": 3812, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/FOUNDATION/TINY/unit_tests/tiny_quaternion_rotate/tiny_quaternion_rotate.cpp", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-11-27T09:44:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-13T00:24:21.000Z", "max_issues_repo_path": "PROX/FOUNDATION/TINY/unit_tests/tiny_quaternion_rotate/tiny_quaternion_rotate.cpp", "max_issues_repo_name": "erleben/matchstick", "max_issues_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_issues_repo_licenses": ["MIT"], "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/FOUNDATION/TINY/unit_tests/tiny_quaternion_rotate/tiny_quaternion_rotate.cpp", "max_forks_repo_name": "erleben/matchstick", "max_forks_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_forks_repo_licenses": ["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.3050847458, "max_line_length": 68, "alphanum_fraction": 0.5695173137, "num_tokens": 1383, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059414036511, "lm_q2_score": 0.6261241842048092, "lm_q1q2_score": 0.4965828105493483}}
{"text": "#include \"eigen-runtime.h\"\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n#include <Eigen/LU>\n\nusing namespace Eigen;\n\ntemplate <class T>\nMap< Matrix<T,Dynamic,Dynamic> > matrix(void* p, int r, int c) {\n    return Map< Matrix<T,Dynamic,Dynamic> >((T*)p, r, c);\n}\n\ntemplate <class T>\nMap< Matrix<T,Dynamic,Dynamic> > matrix(const void* p, int r, int c) {\n    return Map< Matrix<T,Dynamic,Dynamic> >((T*)p, r, c);\n}\n\ntemplate <class T>\nMap< SparseMatrix<T> > smatrix(void* val, void* outer,\n    void* inner, int r, int c, int s) {\n    return Map< SparseMatrix<T> >(r, c, s, (int*)outer, (int*)inner, (T*)val);\n}\n\ntemplate <class T>\nMap<SparseMatrix<T> > smatrix(const void* val, const void* outer,\n    const void* inner, int r, int c, int s) {\n    return Map< SparseMatrix<T> >(r, c, s, (int*)outer, (int*)inner, (T*)val);\n}\n\n// Matrix product\ntemplate <class T>\nRET dd_mul( void* p, int r, int c,\n    const void* p1, int r1, int c1,\n    const void* p2, int r2, int c2)\n{\n    matrix<T>(p,r,c) = matrix<T>(p1,r1,c1) * matrix<T>(p2,r2,c2);\n    return 0;\n}\nAPI(dd_mul, (int code,\n    void* p, int r, int c,\n    const void* p1, int r1, int c1,\n    const void* p2, int r2, int c2), (p,r,c,p1,r1,c1,p2,r2,c2));\n\ntemplate <class T>\nRET ds_mul( void* p, int r, int c,\n    const void* p1, int r1, int c1,\n    const void* val, const void* outer, const void* inner,\n    int r2, int c2, int s)\n{\n    matrix<T>(p,r,c) = matrix<T>(p1,r1,c1) * smatrix<T>(val, outer, inner, r2, c2, s);\n    return 0;\n}\nAPI(ds_mul, (int code,\n    void* p, int r, int c,\n    const void* p1, int r1, int c1,\n    const void* val, const void* outer, const void* inner,\n    int r2, int c2, int s), (p,r,c,p1,r1,c1,val,outer,inner,r2,c2,s));\n\ntemplate <class T>\nRET sd_mul( void* p, int r, int c,\n    const void* val, const void* outer, const void* inner,\n    int r2, int c2, int s,\n    const void* p1, int r1, int c1)\n{\n    matrix<T>(p,r,c) = smatrix<T>(val, outer, inner, r2, c2, s) * matrix<T>(p1,r1,c1);\n    return 0;\n}\nAPI(sd_mul, (int code,\n    void* p, int r, int c,\n    const void* val, const void* outer, const void* inner, int r2, int c2, int s,\n    const void* p1, int r1, int c1), (p,r,c,val,outer,inner,r2,c2,s,p1,r1,c1));\n\n\ntemplate <class T>\nRET ss_mul( void** v, void* o, void** i, int r, int c, int* s,\n    const void* v1, const void* o1, const void* i1, int r1, int c1, int s1,\n    const void* v2, const void* o2, const void* i2, int r2, int c2, int s2)\n{\n    typedef Map<SparseMatrix<T> > MapSparseMatrix;\n    MapSparseMatrix a(r1, c1, s1, (int*)o1, (int*)i1, (T*)v1);\n    MapSparseMatrix b(r2, c2, s2, (int*)o2, (int*)i2, (T*)v2);\n    SparseMatrix<T> M = (a * b).pruned();\n\n    memcpy(o, M.outerIndexPtr(), (c+1) * sizeof(int));\n\n    *s = M.nonZeros();\n    T* p1 = (T*) malloc((*s) * sizeof(T));\n    memcpy(p1, M.valuePtr(), (*s) * sizeof(T));\n    *v = p1;\n    int* p2 = (int*) malloc((*s) * sizeof(int));\n    memcpy(p2, M.innerIndexPtr(), (*s) * sizeof(int));\n    *i = p2;\n    return 0;\n}\nAPI(ss_mul, (int code,\n    void** v, void* o, void** i, int r, int c, int* s,\n    const void* v1, const void* o1, const void* i1, int r1, int c1, int s1,\n    const void* v2, const void* o2, const void* i2, int r2, int c2, int s2),\n    (v,o,i,r,c,s,v1,o1,i1,r1,c1,s1,v2,o2,i2,r2,c2,s2));\n\n\ntemplate <class T>\nRET ss_plus( void** v, void* o, void** i, int r, int c, int* s,\n    const void* v1, const void* o1, const void* i1, int r1, int c1, int s1,\n    const void* v2, const void* o2, const void* i2, int r2, int c2, int s2)\n{\n    typedef Map<SparseMatrix<T> > MapSparseMatrix;\n    MapSparseMatrix a(r1, c1, s1, (int*)o1, (int*)i1, (T*)v1);\n    MapSparseMatrix b(r2, c2, s2, (int*)o2, (int*)i2, (T*)v2);\n    SparseMatrix<T> M = a + b;\n\n    memcpy(o, M.outerIndexPtr(), (c+1) * sizeof(int));\n\n    *s = M.nonZeros();\n    T* p1 = (T*) malloc((*s) * sizeof(T));\n    memcpy(p1, M.valuePtr(), (*s) * sizeof(T));\n    *v = p1;\n    int* p2 = (int*) malloc((*s) * sizeof(int));\n    memcpy(p2, M.innerIndexPtr(), (*s) * sizeof(int));\n    *i = p2;\n    return 0;\n}\nAPI(ss_plus, (int code,\n    void** v, void* o, void** i, int r, int c, int* s,\n    const void* v1, const void* o1, const void* i1, int r1, int c1, int s1,\n    const void* v2, const void* o2, const void* i2, int r2, int c2, int s2),\n    (v,o,i,r,c,s,v1,o1,i1,r1,c1,s1,v2,o2,i2,r2,c2,s2));\n\ntemplate <class T>\nRET ss_cmul( void** v, void* o, void** i, int r, int c, int* s,\n    const void* v1, const void* o1, const void* i1, int r1, int c1, int s1,\n    const void* v2, const void* o2, const void* i2, int r2, int c2, int s2)\n{\n    typedef Map<SparseMatrix<T> > MapSparseMatrix;\n    MapSparseMatrix a(r1, c1, s1, (int*)o1, (int*)i1, (T*)v1);\n    MapSparseMatrix b(r2, c2, s2, (int*)o2, (int*)i2, (T*)v2);\n\n    SparseMatrix<T> M = a.cwiseProduct(b);\n\n    memcpy(o, M.outerIndexPtr(), (c+1) * sizeof(int));\n\n    *s = M.nonZeros();\n    T* p1 = (T*) malloc((*s) * sizeof(T));\n    memcpy(p1, M.valuePtr(), (*s) * sizeof(T));\n    *v = p1;\n    int* p2 = (int*) malloc((*s) * sizeof(int));\n    memcpy(p2, M.innerIndexPtr(), (*s) * sizeof(int));\n    *i = p2;\n    return 0;\n}\nAPI(ss_cmul, (int code,\n    void** v, void* o, void** i, int r, int c, int* s,\n    const void* v1, const void* o1, const void* i1, int r1, int c1, int s1,\n    const void* v2, const void* o2, const void* i2, int r2, int c2, int s2),\n    (v,o,i,r,c,s,v1,o1,i1,r1,c1,s1,v2,o2,i2,r2,c2,s2));\n\ntemplate <class T>\nRET sd_plus( void* p, int r, int c,\n    const void* val, const void* outer, const void* inner,\n    int r2, int c2, int s,\n    const void* p1, int r1, int c1)\n{\n    typedef Map< Matrix<T,Dynamic,Dynamic> > MapMatrix;\n    MapMatrix x((T*)p, r, c);\n    x = matrix<T>(p1,r1,c1);\n    x += smatrix<T>(val, outer, inner, r2, c2, s);\n    return 0;\n}\nAPI(sd_plus, (int code,\n    void* p, int r, int c,\n    const void* val, const void* outer, const void* inner, int r2, int c2, int s,\n    const void* p1, int r1, int c1), (p,r,c,val,outer,inner,r2,c2,s,p1,r1,c1));\n\n#define UNOP(name) \\\nextern \"C\" RET __attribute__((noinline)) eigen_##name(int code, void* p, int r, int c, const void* p1, int r1, int c1) {\\\n        GUARD_START\\\n        switch (code) {\\\n            case 0: matrix<T0>(p,r,c) = matrix<T0>(p1,r1,c1).name(); break;\\\n            case 1: matrix<T1>(p,r,c) = matrix<T1>(p1,r1,c1).name(); break;\\\n            case 2: matrix<T2>(p,r,c) = matrix<T2>(p1,r1,c1).name(); break;\\\n            case 3: matrix<T3>(p,r,c) = matrix<T3>(p1,r1,c1).name(); break;\\\n        }\\\n        GUARD_END\\\n    }\n\nUNOP(inverse);", "meta": {"hexsha": "6c348c6bb7b0e190189ac5e52b90773ff2cf6f8b", "size": 6495, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cbits/eigen-basic.cpp", "max_stars_repo_name": "kaizhang/matrix-sized", "max_stars_repo_head_hexsha": "aed69651b2da5ca4c9076c8c4d981b876932e5b8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cbits/eigen-basic.cpp", "max_issues_repo_name": "kaizhang/matrix-sized", "max_issues_repo_head_hexsha": "aed69651b2da5ca4c9076c8c4d981b876932e5b8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cbits/eigen-basic.cpp", "max_forks_repo_name": "kaizhang/matrix-sized", "max_forks_repo_head_hexsha": "aed69651b2da5ca4c9076c8c4d981b876932e5b8", "max_forks_repo_licenses": ["BSD-3-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.9193548387, "max_line_length": 121, "alphanum_fraction": 0.582448037, "num_tokens": 2479, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4965461945282449}}
{"text": "#include <boost/random/student_t_distribution.hpp>\n", "meta": {"hexsha": "86fbf16df39750bbbd65866d1967e9a8cd5812ae", "size": 51, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_random_student_t_distribution.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_random_student_t_distribution.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_random_student_t_distribution.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 25.5, "max_line_length": 50, "alphanum_fraction": 0.8431372549, "num_tokens": 9, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189121808099, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4965461840031006}}
{"text": "/**\n * Copyright (c) 2018, University Osnabr\u00fcck\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\u00fcck 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\u00fcck 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.cpp\n *\n *  @date Feb 21, 2014\n *  @author Thomas Wiemann\n */\n\n#include <Eigen/SVD>\n\nusing namespace Eigen;\n\nnamespace lvr2\n{\n\ntemplate<typename T, typename PointT>\nT EigenSVDPointAlign<T, PointT>::alignPoints(\n    SLAMScanPtr scan,\n    Point3** neighbors,\n    const Vec3& centroid_m,\n    const Vec3& centroid_d,\n    Mat4& align) const\n{\n    T error = 0.0;\n    size_t pairs = 0;\n\n    // Fill H matrix\n    Mat3 H = Matrix3d::Zero();\n\n    for (size_t i = 0; i < scan->numPoints(); i++)\n    {\n        if (neighbors[i] == nullptr)\n        {\n            continue;\n        }\n\n        Vec3 m = neighbors[i]->template cast<T>() - centroid_m;\n        Vec3 d = scan->point(i).template cast<T>() - centroid_d;\n\n        error += (m - d).squaredNorm();\n        pairs++;\n\n        // same as \"H += m * d.transpose();\" but faster\n        for (int j = 0; j < 3; j++)\n        {\n            for (int k = 0; k < 3; k++)\n            {\n                H(j, k) += d[j] * m[k];\n            }\n        }\n    }\n\n    error = sqrt(error / (T)pairs);\n\n    JacobiSVD<Mat3> svd(H, ComputeFullU | ComputeFullV);\n\n    Mat3 U = svd.matrixU();\n    Mat3 V = svd.matrixV();\n\n    Mat3 R = V * U.transpose();\n\n    align = Mat4::Identity();\n    align.template block<3, 3>(0, 0) = R;\n\n    // Calculate translation\n    Vec3 translation = centroid_m - R * centroid_d;\n    align.template block<3, 1>(0, 3) = translation;\n\n    return error;\n}\n\ntemplate<typename T, typename PointT>\nT EigenSVDPointAlign<T, PointT>::alignPoints(\n    PointPairVector& pairs,\n    const Vec3& centroid_m,\n    const Vec3& centroid_d,\n    Mat4& align) const\n{\n    T error = 0.0;\n    size_t n = pairs.size();\n\n    // Fill H matrix\n    Mat3 H = Mat3::Zero();\n\n    for (size_t i = 0; i < n; i++)\n    {\n        Vec3 m = pairs[i].first.template cast<T>() - centroid_m;\n        Vec3 d = pairs[i].second.template cast<T>() - centroid_d;\n\n        error += (m - d).squaredNorm();\n\n        // same as \"H += m * d.transpose();\" but faster\n        for (int j = 0; j < 3; j++)\n        {\n            for (int k = 0; k < 3; k++)\n            {\n                H(j, k) += d[j] * m[k];\n            }\n        }\n    }\n\n    error = sqrt(error / (T)n);\n\n    JacobiSVD<Mat3> svd(H, ComputeFullU | ComputeFullV);\n\n    Mat3 U = svd.matrixU();\n    Mat3 V = svd.matrixV();\n\n    Mat3 R = V * U.transpose();\n\n    align = Mat4::Identity();\n    align.template block<3, 3>(0, 0) = R;\n\n    // Calculate translation\n    Vec3 translation = centroid_m - R * centroid_d;\n    align.template block<3, 1>(0, 3) = translation;\n\n    return error;\n}\n\n} // namespace lvr2\n", "meta": {"hexsha": "98599952d5006b8bc4fb39acb0cc475e52482b17", "size": 4178, "ext": "tcc", "lang": "C++", "max_stars_repo_path": "include/lvr2/registration/EigenSVDPointAlign.tcc", "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.tcc", "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.tcc", "max_forks_repo_name": "uos/lvr", "max_forks_repo_head_hexsha": "9bb03a30441b027c39db967318877e03725112d5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2019-04-16T11:50:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-26T07:47:44.000Z", "avg_line_length": 28.2297297297, "max_line_length": 82, "alphanum_fraction": 0.6156055529, "num_tokens": 1104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891130942474, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4965461787405282}}
{"text": "/* Copyright (C) 2021 Intel Corporation\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *  http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#include \"bgv_common.h\"\n\n#include <NTL/BasicThreadPool.h>\n#include <helib/helib.h>\n#include \"../src/PrimeGenerator.h\" // Private header\n\n#include <benchmark/benchmark.h>\n#include <iostream>\n\nnamespace {\n\nstatic void helib_fft_forward(benchmark::State& state, Meta& meta)\n{\n  NTL::SetNumThreads(1);\n\n  long N = meta.data->ea.size();\n  long m = meta.data->context.getM();\n  auto zms = meta.data->context.getZMStar();\n\n  helib::PrimeGenerator prime_generator(49, m);\n\n  long q = prime_generator.next();\n  helib::Cmodulus cmod(zms, q, 0);\n\n  NTL::ZZX poly;\n  poly.SetLength(N);\n  for (long i = 0; i < N; ++i)\n    poly[i] = i;\n\n  NTL::vec_long transformed;\n  for (auto _ : state)\n    cmod.FFT(transformed, poly);\n}\n\nstatic void helib_fft_inverse(benchmark::State& state, Meta& meta)\n{\n  NTL::SetNumThreads(1);\n\n  long N = meta.data->ea.size();\n  long m = meta.data->context.getM();\n  auto zms = meta.data->context.getZMStar();\n\n  helib::PrimeGenerator prime_generator(49, m);\n\n  long q = prime_generator.next();\n  helib::Cmodulus cmod(zms, q, 0);\n\n  NTL::zz_pX inverse;\n  inverse.SetLength(N);\n\n  NTL::vec_long transformed(NTL::INIT_SIZE, N);\n  for (long i = 0; i < N; ++i)\n    transformed[i] = i;\n\n  for (auto _ : state)\n    cmod.iFFT(inverse, transformed);\n}\n\nMeta fn;\nParams hexl_F4_params(/*m=*/16384, /*p=*/65537, /*r=*/1, /*qbits=*/5800);\nHE_BENCH_CAPTURE(helib_fft_forward, hexl_F4_params, fn); //->Iterations(200);\nHE_BENCH_CAPTURE(helib_fft_inverse, hexl_F4_params, fn); //->Iterations(200);\n\nParams hexl_F3_params(/*m=*/16, /*p=*/257, /*r=*/1, /*qbits=*/5800);\nHE_BENCH_CAPTURE(helib_fft_forward, hexl_F3_params, fn); //->Iterations(200);\nHE_BENCH_CAPTURE(helib_fft_inverse, hexl_F3_params, fn); //->Iterations(200);\n\nParams hexl_F3d2_params(/*m=*/512, /*p=*/257, /*r=*/1, /*qbits=*/5800);\nHE_BENCH_CAPTURE(helib_fft_forward, hexl_F3d2_params, fn); //->Iterations(200);\nHE_BENCH_CAPTURE(helib_fft_inverse, hexl_F3d2_params, fn); //->Iterations(200);\n\n} // namespace\n", "meta": {"hexsha": "ff0b0e33173c2f996be544099207b0bc58c9f5fd", "size": 2562, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "benchmarks/fft_bench.cpp", "max_stars_repo_name": "fboemer/HElib", "max_stars_repo_head_hexsha": "1796a18949e74f53a35cdfae94aa923c9eb8d9c2", "max_stars_repo_licenses": ["Apache-2.0"], "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/fft_bench.cpp", "max_issues_repo_name": "fboemer/HElib", "max_issues_repo_head_hexsha": "1796a18949e74f53a35cdfae94aa923c9eb8d9c2", "max_issues_repo_licenses": ["Apache-2.0"], "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/fft_bench.cpp", "max_forks_repo_name": "fboemer/HElib", "max_forks_repo_head_hexsha": "1796a18949e74f53a35cdfae94aa923c9eb8d9c2", "max_forks_repo_licenses": ["Apache-2.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.1411764706, "max_line_length": 79, "alphanum_fraction": 0.7006245121, "num_tokens": 750, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891130942472, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.49654617874052803}}
{"text": "/*\n * Copyright 2017 MapD 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/**\n * @file\t\tPopulateTableRandom.cpp\n * @author\tWei Hong <wei@map-d.com>\n * @brief\t\tPopulate a table with random data\n *\n * Copyright (c) 2014 MapD Technologies, Inc.  All rights reserved.\n **/\n\n#include <boost/functional/hash.hpp>\n#include <cfloat>\n#include <cstdint>\n#include <cstdlib>\n#include <cstring>\n#include <exception>\n#include <iostream>\n#include <memory>\n#include <random>\n#include <string>\n\n#include \"../Catalog/Catalog.h\"\n#include \"../DataMgr/DataMgr.h\"\n#include \"../Fragmenter/Fragmenter.h\"\n#include \"../Shared/DateConverters.h\"\n#include \"../Shared/measure.h\"\n#include \"../Shared/sqltypes.h\"\n#include \"Logger/Logger.h\"\n\nusing namespace Catalog_Namespace;\nusing namespace Fragmenter_Namespace;\n\nsize_t random_fill_int16(int8_t* buf, size_t num_elems) {\n  std::default_random_engine gen;\n  std::uniform_int_distribution<int16_t> dist(INT16_MIN, INT16_MAX);\n  auto p = reinterpret_cast<int16_t*>(buf);\n  size_t hash = 0;\n  for (size_t i = 0; i < num_elems; i++) {\n    p[i] = dist(gen);\n    boost::hash_combine(hash, p[i]);\n  }\n  return hash;\n}\n\nsize_t random_fill_int32(int8_t* buf, size_t num_elems) {\n  std::default_random_engine gen;\n  std::uniform_int_distribution<int32_t> dist(INT32_MIN, INT32_MAX);\n  auto p = reinterpret_cast<int32_t*>(buf);\n  size_t hash = 0;\n  for (size_t i = 0; i < num_elems; i++) {\n    p[i] = dist(gen);\n    boost::hash_combine(hash, p[i]);\n  }\n  return hash;\n}\n\nsize_t random_fill_int64(int8_t* buf, size_t num_elems, int64_t min, int64_t max) {\n  std::default_random_engine gen;\n  std::uniform_int_distribution<int64_t> dist(min, max);\n  auto p = reinterpret_cast<int64_t*>(buf);\n  size_t hash = 0;\n  for (size_t i = 0; i < num_elems; i++) {\n    p[i] = dist(gen);\n    boost::hash_combine(hash, p[i]);\n  }\n  return hash;\n}\n\nsize_t random_fill_int64(int8_t* buf, size_t num_elems) {\n  return random_fill_int64(buf, num_elems, INT64_MIN, INT64_MAX);\n}\n\nsize_t random_fill_float(int8_t* buf, size_t num_elems) {\n  std::default_random_engine gen;\n  std::uniform_real_distribution<float> dist(FLT_MIN, FLT_MAX);\n  auto p = reinterpret_cast<float*>(buf);\n  size_t hash = 0;\n  for (size_t i = 0; i < num_elems; i++) {\n    p[i] = dist(gen);\n    boost::hash_combine(hash, p[i]);\n  }\n  return hash;\n}\n\nsize_t random_fill_double(int8_t* buf, size_t num_elems) {\n  std::default_random_engine gen;\n  std::uniform_real_distribution<double> dist(DBL_MIN, DBL_MAX);\n  auto p = reinterpret_cast<double*>(buf);\n  size_t hash = 0;\n  for (size_t i = 0; i < num_elems; i++) {\n    p[i] = dist(gen);\n    boost::hash_combine(hash, p[i]);\n  }\n  return hash;\n}\n\nsize_t random_fill_string(std::vector<std::string>& stringVec,\n                          size_t num_elems,\n                          int max_len,\n                          size_t& data_volumn) {\n  std::string chars(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890\");\n  std::default_random_engine gen;\n  std::uniform_int_distribution<> char_dist(0, chars.size() - 1);\n  std::uniform_int_distribution<> len_dist(0, max_len);\n  size_t hash = 0;\n  std::hash<std::string> string_hash;\n  for (size_t n = 0; n < num_elems; n++) {\n    int len = len_dist(gen);\n    std::string s(len, ' ');\n    for (int i = 0; i < len; i++) {\n      {\n        s[i] = chars[char_dist(gen)];\n      }\n    }\n    stringVec[n] = s;\n    boost::hash_combine(hash, string_hash(s));\n    data_volumn += len;\n  }\n  return hash;\n}\n\nsize_t random_fill_int8array(std::vector<std::vector<int8_t>>& stringVec,\n                             size_t num_elems,\n                             int max_len,\n                             size_t& data_volumn) {\n  std::default_random_engine gen;\n  std::uniform_int_distribution<int8_t> dist(INT8_MIN, INT8_MAX);\n  std::uniform_int_distribution<> len_dist(0, max_len);\n  size_t hash = 0;\n  for (size_t n = 0; n < num_elems; n++) {\n    int len = len_dist(gen);\n    std::vector<int8_t> s(len);\n    for (int i = 0; i < len; i++) {\n      s[i] = dist(gen);\n      boost::hash_combine(hash, s[i]);\n    }\n    stringVec[n] = s;\n    data_volumn += len * sizeof(int8_t);\n  }\n  return hash;\n}\n\nsize_t random_fill_int16array(std::vector<std::vector<int16_t>>& stringVec,\n                              size_t num_elems,\n                              int max_len,\n                              size_t& data_volumn) {\n  std::default_random_engine gen;\n  std::uniform_int_distribution<int16_t> dist(INT16_MIN, INT16_MAX);\n  std::uniform_int_distribution<> len_dist(0, max_len / 2);\n  size_t hash = 0;\n  for (size_t n = 0; n < num_elems; n++) {\n    int len = len_dist(gen);\n    std::vector<int16_t> s(len);\n    for (int i = 0; i < len; i++) {\n      s[i] = dist(gen);\n      boost::hash_combine(hash, s[i]);\n    }\n    stringVec[n] = s;\n    data_volumn += len * sizeof(int16_t);\n  }\n  return hash;\n}\n\nsize_t random_fill_int32array(std::vector<std::vector<int32_t>>& stringVec,\n                              size_t num_elems,\n                              int max_len,\n                              size_t& data_volumn) {\n  std::default_random_engine gen;\n  std::uniform_int_distribution<int32_t> dist(INT32_MIN, INT32_MAX);\n  std::uniform_int_distribution<> len_dist(0, max_len / 4);\n  size_t hash = 0;\n  for (size_t n = 0; n < num_elems; n++) {\n    int len = len_dist(gen);\n    std::vector<int32_t> s(len);\n    for (int i = 0; i < len; i++) {\n      s[i] = dist(gen);\n      boost::hash_combine(hash, s[i]);\n    }\n    stringVec[n] = s;\n    data_volumn += len * sizeof(int32_t);\n  }\n  return hash;\n}\n\nsize_t random_fill_dates(int8_t* buf, size_t num_elems) {\n  constexpr int64_t kDateMin = -185542587187200;\n  constexpr int64_t kDateMax = 185542587100800;\n  std::default_random_engine gen;\n  std::uniform_int_distribution<int64_t> dist(kDateMin, kDateMax);\n  auto p = reinterpret_cast<int64_t*>(buf);\n  size_t hash = 0;\n  for (size_t i = 0; i < num_elems; i++) {\n    p[i] = dist(gen);\n    boost::hash_combine(hash, DateConverters::get_epoch_days_from_seconds(p[i]));\n  }\n  return hash;\n}\n\n#define MAX_TEXT_LEN 255\n\nsize_t random_fill(const ColumnDescriptor* cd,\n                   DataBlockPtr p,\n                   size_t num_elems,\n                   size_t& data_volumn) {\n  size_t hash = 0;\n  switch (cd->columnType.get_type()) {\n    case kSMALLINT:\n      hash = random_fill_int16(p.numbersPtr, num_elems);\n      data_volumn += num_elems * sizeof(int16_t);\n      break;\n    case kINT:\n      hash = random_fill_int32(p.numbersPtr, num_elems);\n      data_volumn += num_elems * sizeof(int32_t);\n      break;\n    case kBIGINT:\n      hash = random_fill_int64(p.numbersPtr, num_elems, INT64_MIN, INT64_MAX);\n      data_volumn += num_elems * sizeof(int64_t);\n      break;\n    case kNUMERIC:\n    case kDECIMAL: {\n      int64_t max = std::pow((double)10, cd->columnType.get_precision());\n      int64_t min = -max;\n      hash = random_fill_int64(p.numbersPtr, num_elems, min, max);\n      data_volumn += num_elems * sizeof(int64_t);\n      break;\n    }\n    case kFLOAT:\n      hash = random_fill_float(p.numbersPtr, num_elems);\n      data_volumn += num_elems * sizeof(float);\n      break;\n    case kDOUBLE:\n      hash = random_fill_double(p.numbersPtr, num_elems);\n      data_volumn += num_elems * sizeof(double);\n      break;\n    case kVARCHAR:\n    case kCHAR:\n      if (cd->columnType.get_compression() == kENCODING_NONE) {\n        {\n          hash = random_fill_string(\n              *p.stringsPtr, num_elems, cd->columnType.get_dimension(), data_volumn);\n        }\n      }\n      break;\n    case kTEXT:\n      if (cd->columnType.get_compression() == kENCODING_NONE) {\n        {\n          hash = random_fill_string(*p.stringsPtr, num_elems, MAX_TEXT_LEN, data_volumn);\n        }\n      }\n      break;\n    case kDATE:\n    case kTIME:\n    case kTIMESTAMP:\n      hash = cd->columnType.get_type() == kDATE\n                 ? random_fill_dates(p.numbersPtr, num_elems)\n                 : random_fill_int64(p.numbersPtr, num_elems);\n      data_volumn += num_elems * sizeof(int64_t);\n      break;\n    default:\n      assert(false);\n  }\n  return hash;\n}\n\nstd::vector<size_t> populate_table_random(const std::string& table_name,\n                                          const size_t num_rows,\n                                          const Catalog& cat) {\n  const TableDescriptor* td = cat.getMetadataForTable(table_name);\n  const auto cds = cat.getAllColumnMetadataForTable(td->tableId, false, false, false);\n  InsertData insert_data;\n  insert_data.databaseId = cat.getCurrentDB().dbId;\n  insert_data.tableId = td->tableId;\n  for (const auto& cd : cds) {\n    insert_data.columnIds.push_back(cd->columnId);\n    insert_data.is_default.push_back(false);\n  }\n  insert_data.numRows = num_rows;\n  std::vector<std::vector<int8_t>> numbers_vec;\n  std::vector<std::unique_ptr<std::vector<std::string>>> strings_vec;\n\n  DataBlockPtr p{0};\n  // now allocate space for insert data\n  for (auto cd : cds) {\n    if (cd->columnType.is_varlen()) {\n      if (cd->columnType.get_compression() == kENCODING_NONE) {\n        strings_vec.push_back(std::make_unique<std::vector<std::string>>(num_rows));\n        p.stringsPtr = strings_vec.back().get();\n      } else {\n        CHECK(false);\n      }\n    } else {\n      numbers_vec.emplace_back(num_rows * cd->columnType.get_logical_size());\n      p.numbersPtr = numbers_vec.back().data();\n    }\n    insert_data.data.push_back(p);\n  }\n\n  // fill InsertData  with random data\n  std::vector<size_t> col_hashs(\n      cds.size());  // compute one hash per column for the generated data\n  int i = 0;\n  size_t data_volumn = 0;\n  for (auto cd : cds) {\n    col_hashs[i] = random_fill(cd, insert_data.data[i], num_rows, data_volumn);\n    i++;\n  }\n\n  // now load the data into table\n  auto ms = measure<>::execution([&]() { td->fragmenter->insertData(insert_data); });\n  std::cout << \"Loaded \" << num_rows << \" rows \" << data_volumn << \" bytes in \" << ms\n            << \" ms. at \" << (double)data_volumn / (ms / 1000.0) / 1e6 << \" MB/sec.\"\n            << std::endl;\n\n  return col_hashs;\n}\n", "meta": {"hexsha": "f5fc56af6f492e80141795ec28c20afa0a37cd4f", "size": 10559, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tests/PopulateTableRandom.cpp", "max_stars_repo_name": "weiting-chen/omniscidb", "max_stars_repo_head_hexsha": "380133c29d6390e3dfc59486f06407c27fcd5a3a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tests/PopulateTableRandom.cpp", "max_issues_repo_name": "weiting-chen/omniscidb", "max_issues_repo_head_hexsha": "380133c29d6390e3dfc59486f06407c27fcd5a3a", "max_issues_repo_licenses": ["Apache-2.0"], "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/PopulateTableRandom.cpp", "max_forks_repo_name": "weiting-chen/omniscidb", "max_forks_repo_head_hexsha": "380133c29d6390e3dfc59486f06407c27fcd5a3a", "max_forks_repo_licenses": ["Apache-2.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.996969697, "max_line_length": 89, "alphanum_fraction": 0.6358556682, "num_tokens": 2848, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891130942472, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.49654617874052803}}
{"text": "/*\n@copyright Louis Dionne 2014\nDistributed under the Boost Software License, Version 1.0.\n(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n */\n\n#include <boost/hana/list/mcd.hpp>\n\n#include <boost/hana/detail/assert.hpp>\n#include <boost/hana/detail/constexpr.hpp>\n#include <boost/hana/detail/minimal/list.hpp>\n#include <boost/hana/detail/minimal/product.hpp>\n\n#include <boost/hana/integral.hpp>\nusing namespace boost::hana;\n\n\nconstexpr auto prod = detail::minimal::product<>;\n\n// partition requires the predicate to return an Integral boolean, so we need\n// the comparison to be purely compile-time.\ntemplate <int i>\nBOOST_HANA_CONSTEXPR_LAMBDA auto x = int_<i>;\n\nBOOST_HANA_CONSTEXPR_LAMBDA auto neg = [](auto x) {\n    return x < int_<0>;\n};\n\ntemplate <typename mcd>\nvoid test() {\n    BOOST_HANA_CONSTEXPR_LAMBDA auto list = detail::minimal::list<mcd>;\n\n    BOOST_HANA_CONSTANT_ASSERT(partition(list(), neg) == prod(list(), list()));\n    BOOST_HANA_CONSTANT_ASSERT(partition(list(x<0>), neg) == prod(list(), list(x<0>)));\n    BOOST_HANA_CONSTANT_ASSERT(partition(list(x<0>, x<1>), neg) == prod(list(), list(x<0>, x<1>)));\n    BOOST_HANA_CONSTANT_ASSERT(partition(list(x<-1>), neg) == prod(list(x<-1>), list()));\n    BOOST_HANA_CONSTANT_ASSERT(partition(list(x<-1>, x<0>, x<2>), neg) == prod(list(x<-1>), list(x<0>, x<2>)));\n    BOOST_HANA_CONSTANT_ASSERT(partition(list(x<0>, x<-3>, x<2>, x<-5>, x<6>), neg) == prod(list(x<-3>, x<-5>), list(x<0>, x<2>, x<6>)));\n    BOOST_HANA_CONSTANT_ASSERT(partition(list(x<-1>, x<2>, x<-3>, x<0>, x<-3>, x<4>), neg) == prod(list(x<-1>, x<-3>, x<-3>), list(x<2>, x<0>, x<4>)));\n}\n\nint main() {\n    test<List::mcd<void>>();\n    (void)neg;\n}\n", "meta": {"hexsha": "54a724f51aabdd6bc4b888eb3da4f6b21d2d1ea3", "size": 1707, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/list/typeclass/partition.cpp", "max_stars_repo_name": "rbock/hana", "max_stars_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-05-07T14:29:13.000Z", "max_stars_repo_stars_event_max_datetime": "2015-07-04T10:59:46.000Z", "max_issues_repo_path": "test/list/typeclass/partition.cpp", "max_issues_repo_name": "rbock/hana", "max_issues_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/list/typeclass/partition.cpp", "max_forks_repo_name": "rbock/hana", "max_forks_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.1086956522, "max_line_length": 151, "alphanum_fraction": 0.6701816052, "num_tokens": 511, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585669110203, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.49651941599031607}}
{"text": "// Copyright (C) 2017 Vicente J. Botet Escriba\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// <experimental/strong_counter.hpp>\n\n/**\n * This example tries to see how close we can define std::chrono duration using strong_counter\n *\n * We need a specific Domain for durations to state how durations convert between them.\n */\n\n#include <experimental/strong_counter.hpp>\n#include <experimental/type_traits.hpp>\n#include <ratio>\n#include <chrono>\n#include <utility>\n#include <type_traits>\n#include <experimental/fundamental/v3/strong/mixins/is_compatible_with.hpp>\n\nnamespace stdex = std::experimental;\n\n// fixme: Shouldn't all the strong_counter domains require most of these conditions (except the Period related)?\n// todo generalize to dimension_1_domain<duration, Period>\n// todo generalize to dimensionless_domain<Tag>\n// fixme Shouldn't those have a Tag parameter to make them strongly typed?\ntemplate<class Period>\nstruct duration_domain\n{\n  template <class T, class P, class U\n          , typename std::enable_if <\n              std::conjunction <\n                std::is_convertible<U, T>, // no overflow\n                std::disjunction<\n                      std::chrono::treat_as_floating_point<T>,\n                      std::conjunction<\n                          std::integral_constant<bool, std::ratio_divide<P, Period>::den == 1>,\n                          std::negation< std::chrono::treat_as_floating_point<U> >\n                      >\n                  >\n              >::value\n          >::type* = nullptr\n  >\n  static T inter_domain_convert(duration_domain<P>, U const& u)\n  {\n    return T(\n        std::chrono::duration_cast<std::chrono::duration<T, Period>>(std::chrono::duration<U,P>(u)).count()\n        );\n  }\n  template <class T, class P, class U>\n  static T inter_domain_cast(duration_domain<P>, U const& u)\n  {\n    return T(\n        std::chrono::duration_cast<std::chrono::duration<T, Period>>(std::chrono::duration<U,P>(u)).count()\n    );\n  }\n  template <class T, class U\n          , typename std::enable_if <\n              std::conjunction <\n                std::is_convertible<U, T>,\n                std::disjunction<\n                      std::chrono::treat_as_floating_point<T>,\n                      std::negation< std::chrono::treat_as_floating_point<U> >\n                >\n              >::value\n          >::type* = nullptr\n          >\n  static T intra_domain_convert(U const& u) { return T(u); }\n};\n\n\n\ntemplate<\n    class Rep,\n    class Period = std::ratio<1>\n>\nusing duration = stdex::strong_counter<duration_domain<Period>, Rep>;\n\n// fixme: duration stream insertion/extraction can be more specialized.\n// Wondering if streamable, should be part of strong_counter.\n\nnamespace std {\n  template <class P1, class P2>\n  struct common_type<duration_domain<P1>, duration_domain<P2>>\n  {\n     using CP = typename common_type<std::chrono::duration<int,P1>,std::chrono::duration<int,P2>>::type::period;\n     using type = duration_domain<CP>;\n  };\n\nnamespace experimental {\ninline  namespace fundamental_v3{\nnamespace mixin {\n  template <class Domain1, class Domain2>\n  struct is_compatible_with<duration_domain<Domain1>, duration_domain<Domain2>> : std::true_type {};\n}\n\n  template <class Period>\n  struct domain_converter<duration_domain<Period>> : duration_domain<Period>  {  };\n}\n}\n}\n\nstatic_assert(std::is_same<\n                  std::common_type<\n                    duration_domain<std::ratio<1,10>>,\n                    duration_domain<std::ratio<1,100>>\n                  >::type\n                , duration_domain<std::ratio<1,100>>\n              >::value, \"\");\n\n#include <boost/detail/lightweight_test.hpp>\n#include <iostream>\n\ntemplate <class T> struct check;\nint main()\n{\n#if 0\n  {\n    using U = int;\n    using T = int;\n    using P = std::ratio<1,10>;\n    using Period = std::ratio<1,10>;\n\n  static_assert(\n      stdex::conjunction <\n                      std::is_convertible<U, T>, // no overflow\n                      stdex::disjunction<\n                            std::chrono::treat_as_floating_point<T>,\n                            stdex::conjunction<\n                                std::integral_constant<bool, std::ratio_divide<P, Period>::den == 1>,\n                                stdex::negation< std::chrono::treat_as_floating_point<U> >\n                            >\n                        >\n                    >::value\n      , \"\");\n  }\n\n  auto x1 = duration_domain<std::ratio<1,10>>::inter_domain_convert<int>(duration_domain<std::ratio<1,10>>{}, 1);\n  auto x2 = stdex::inter_domain_convert<duration_domain<std::ratio<1,10>>, int>(duration_domain<std::ratio<1,10>>{}, 1);\n#endif\n\n    {\n      duration<int, std::ratio<1,10>> d1 {30};\n      auto d2 = d1 ++;\n      BOOST_TEST(d1 != d2);\n      BOOST_TEST(d1.count() == 31);\n      BOOST_TEST(d2.count() == 30);\n    }\n    {\n      duration<int, std::ratio<1,10>> d1 {30};\n      auto d2 = ++d1;\n      BOOST_TEST(d1 == d2);\n      BOOST_TEST(d1.count() == 31);\n      BOOST_TEST(d2.count() == 31);\n    }\n    {\n      duration<int, std::ratio<1,10>> d1 {30};\n      duration<int, std::ratio<1,10>> d2{d1};\n      BOOST_TEST(d2.count() == 30);\n    }\n    {\n      duration<int, std::ratio<1,10>> d1 {30};\n      duration<int, std::ratio<1,10>> d2 =d1;\n      BOOST_TEST(d2.count() == 30);\n    }\n    {\n      duration<int, std::ratio<1,10>> d1 {30};\n      duration<int, std::ratio<1,10>> d2;\n      d2 = d1;\n      BOOST_TEST(d2.count() == 30);\n    }\n    {\n      duration<int, std::ratio<1,10>> d1 {300};\n      duration<int, std::ratio<1,100>> d2  = d1;\n\n      static_assert(\n          std::ratio_divide<std::ratio<1,10>, std::ratio<1,100>>::den == 1\n          , \"\");\n\n      static_assert(\n          stdex::detail::is_inter_domain_convertible<duration_domain<std::ratio<1,100>>, int, int, duration_domain<std::ratio<1,10>>>::value\n          , \"\");\n      static_assert(\n          std::ratio_divide<std::ratio<1,100>, std::ratio<1,10>>::den != 1\n          , \"\");\n\n\n      static_assert(\n          ! stdex::detail::is_inter_domain_convertible<duration_domain<std::ratio<1,10>>, int, int, duration_domain<std::ratio<1,100>>>::value\n          , \"ERROR\");\n\n#if defined __clang__ && (__clang_major__ < 4)\n      duration<int, std::ratio<1,10>> d3;\n      // fixme: This shouldn't compile - clang-3.9.1 BUG\n      std::cout << \"------- \\n\";\n      d3= d2; // calling move assignment :(\n      std::cout << \"------- \\n\";\n#endif\n#if ! defined __clang__\n      // fixme: this doesn't work for clang on travis\n      BOOST_TEST(d1 == d2);\n#endif\n      BOOST_TEST_EQ(d2.count() , 3000);\n    }\n    {\n      duration<int, std::ratio<1,100>> d1 {303};\n      duration<int, std::ratio<1,10>> d2  = stdex::strong_counter_cast<duration<int, std::ratio<1,10>>>(d1);\n#if defined __clang__ && (__clang_major__ < 4) // clang-3.9.1 BUG\n      // fixme: This should compile\n      //BOOST_TEST(d1 != d2);\n#endif\n#if ! defined __clang__\n      // fixme: this doesn't work for clang on travis\n      BOOST_TEST(d1 != d2);\n#endif\n      BOOST_TEST(d2.count() == 30);\n    }\n    {\n      duration<int, std::ratio<1,10>> d1 {300};\n      duration<int, std::ratio<1,10>> d2  = d1;\n      auto d = d1 + d2;\n      BOOST_TEST(d.count() == 600);\n    }\n    {\n      duration<int, std::ratio<1,10>> d1 {300};\n      duration<int, std::ratio<1,10>> d2  = d1;\n      auto d = d1 - d2;\n      BOOST_TEST(d.count() == 0);\n    }\n    {\n      duration<int, std::ratio<1,100>> d1 {3};\n      duration<int, std::ratio<1,10>> d2{1};\n      auto d =  d1 + d2;\n      BOOST_TEST_EQ(d.count() , 13);\n    }\n    {\n      duration<int, std::ratio<1,100>> d1 {3};\n      duration<int, std::ratio<1,10>> d2{1};\n      auto d =  d2 + d1;\n      BOOST_TEST_EQ(d.count() , 13);\n    }\n    {\n      duration<double, std::ratio<1,100>> d1 {3};\n      duration<double, std::ratio<1,10>> d2{1};\n      auto d =  d2 + d1;\n      BOOST_TEST((d == duration<double, std::ratio<1,100>>(13)));\n    }\n    return ::boost::report_errors();\n}\n\n", "meta": {"hexsha": "566aa7d431e5df117a40c61620d07b998ece4b80", "size": 8031, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/strong/duration_pass.cpp", "max_stars_repo_name": "jwakely/std-make", "max_stars_repo_head_hexsha": "f09d052983ace70cf371bb8ddf78d4f00330bccd", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 105.0, "max_stars_repo_stars_event_min_datetime": "2015-01-24T13:26:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T15:36:53.000Z", "max_issues_repo_path": "example/strong/duration_pass.cpp", "max_issues_repo_name": "jwakely/std-make", "max_issues_repo_head_hexsha": "f09d052983ace70cf371bb8ddf78d4f00330bccd", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 37.0, "max_issues_repo_issues_event_min_datetime": "2015-09-04T06:57:10.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-09T18:01:44.000Z", "max_forks_repo_path": "example/strong/duration_pass.cpp", "max_forks_repo_name": "jwakely/std-make", "max_forks_repo_head_hexsha": "f09d052983ace70cf371bb8ddf78d4f00330bccd", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 23.0, "max_forks_repo_forks_event_min_datetime": "2015-01-27T11:09:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-04T02:23:30.000Z", "avg_line_length": 31.869047619, "max_line_length": 142, "alphanum_fraction": 0.5788818329, "num_tokens": 2166, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.49651941445493847}}
{"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#include <boost/simd/pack.hpp>\n#include <boost/simd/function/expocvt.hpp>\n#include <boost/simd/function/is_even.hpp>\n#include <boost/simd/function/complement.hpp>\n#include <boost/simd/meta/cardinal_of.hpp>\n#include <boost/simd/detail/dispatch/meta/as_integer.hpp>\n#include <simd_test.hpp>\n#include <boost/simd/constant/minf.hpp>\n\ntemplate <typename T, std::size_t N, typename Env>\nvoid test(Env& $)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using p_t = bs::pack<T, N>;\n\n  T a1[N];\n  T b[N];\n  for(std::size_t i = 0; i < N; ++i)\n  {\n     a1[i] = T(i+1);\n     b[i]  = bs::expocvt(a1[i]);\n   }\n  p_t aa1(&a1[0], &a1[0]+N);\n  p_t bb(&b[0], &b[0]+N);\n  STF_EQUAL(bs::expocvt(aa1), bb);\n}\n\nSTF_CASE_TPL(\"Check expocvt on pack\",STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  using p_t = bs::pack<T>;\n  static const std::size_t N = bs::cardinal_of<p_t>::value;\n  test<T, N>($);\n  test<T, N/2>($);\n  test<T, N*2>($);\n}\n\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n\nSTF_CASE_TPL (\" expocvt real\",  STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using iT = bd::as_integer_t<T>;\n  using bs::expocvt;\n  using p_t = bs::pack<T>;\n  using r_t = decltype(expocvt(p_t()));\n\n\n  // return type conformity test\n  STF_TYPE_IS(r_t, p_t);\n\n  // specific values tests\n\n  for( iT i= bs::Minexponent<T>(); i < bs::Maxexponent<T>(); ++i)\n  {\n    p_t z1 = expocvt(p_t(i));\n    STF_EQUAL(z1, p_t(std::ldexp(T(1), i)));\n  }\n\n} // end of test for floating_\n", "meta": {"hexsha": "38a9d33de4dea6a53ff3f5034d1e0a1f17eb2774", "size": 1902, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/simd/expocvt.cpp", "max_stars_repo_name": "nickporubsky/boost-simd-clone", "max_stars_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_stars_repo_licenses": ["BSL-1.0"], "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": "test/function/simd/expocvt.cpp", "max_issues_repo_name": "nickporubsky/boost-simd-clone", "max_issues_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "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/function/simd/expocvt.cpp", "max_forks_repo_name": "nickporubsky/boost-simd-clone", "max_forks_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_forks_repo_licenses": ["BSL-1.0"], "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": 25.7027027027, "max_line_length": 100, "alphanum_fraction": 0.5767613039, "num_tokens": 568, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585669110202, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.4965194112429849}}
{"text": "\n#include <boost/algorithm/string.hpp>\n#include <boost/format.hpp>\n#include <algorithm>\n#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <string>\n#include <vector>\n#include <array>\n\n#include \"train_features.h\"\n\nusing namespace std;\n\ndouble expit(double x) {\n    if (x > 0) {\n        return 1. / (1. + exp(-x));\n    } else {\n        return 1. - 1. / (1. + exp(x));\n    }\n}\n\ndouble log1exp(double x) {\n    if (x > 0) {\n        return x + log1p(exp(-x));\n    } else {\n        return log1p(exp(x));\n    }\n}\n\nvoid train_with_features(string data_file_path,\n                         string features_file_path,\n                         string noise_file_path,\n                         int n_steps, double eta_0, double iter_power,\n                         size_t l_dimensions,\n                         string output_file_path) {\n    cout << data_file_path << endl;\n    cout << features_file_path << endl;\n    cout << noise_file_path << endl;\n\n    // Data loading\n    fstream data_file_input;\n    data_file_input.open(data_file_path, ios::in);\n    string line;\n    vector<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    vector<size_t> start_indexes(n_samples);\n    vector<size_t> permutation(n_samples);\n    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    fstream features_file_input;\n    features_file_input.open(features_file_path, ios::in);\n    getline(features_file_input, line);\n    boost::split(tokens, line, boost::is_any_of(\",\"));\n    size_t n_items = stoul(tokens[0]);\n    size_t m_features = stoul(tokens[1]);\n\n    auto index_features = [m_features](size_t i, size_t j) -> size_t {\n        return (i * m_features) + j;\n    };\n    vector<double> features(n_items * m_features);\n    for (size_t i = 0; i < n_items; ++i) {\n        getline(features_file_input, line);\n        boost::split(tokens, line, boost::is_any_of(\",\"));\n        for (size_t j = 0; j < m_features; ++j) {\n            features[index_features(i, j)] = stod(tokens[j]);\n        }\n    }\n\n    fstream noise_file_input;\n    noise_file_input.open(noise_file_path, ios::in);\n    getline(noise_file_input, line);\n    boost::split(tokens, line, boost::is_any_of(\",\"));\n    vector<double> noise_weights(m_features);\n    for (size_t i = 0; i < m_features; ++i) {\n        noise_weights[i] = stod(tokens[i]);\n    }\n    vector<double> noise_utilities(n_items);\n    for (size_t i = 0; i < n_items; ++i) {\n        noise_utilities[i] = 0;\n        for (size_t j = 0; j < m_features; ++j) {\n            noise_utilities[i] += features[index_features(i, j)] * noise_weights[j];\n        }\n    }\n\n\n    // Calculate constant quantities.\n    double log_nu = log(n_noise / n_data);\n    double logz_noise = 0;\n    for (size_t i = 0; i < n_items; ++i) {\n        logz_noise += log1exp(noise_utilities[i]);\n    }\n    cout << \"Log nu: \" << log_nu << endl;\n    cout << \"Log noise: \" << logz_noise << endl;\n\n    // Initialize parameters.\n    auto random_engine = default_random_engine{};\n    random_engine.seed(10000000);\n    uniform_real_distribution<double_t> udouble_dist(0, 1e-3);\n    vector<double> b_weights(m_features * l_dimensions);\n    vector<double> a_weights(m_features);\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    for (size_t i = 0; i < m_features; ++i) {\n        a_weights[i] = noise_weights[i];\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    }\n    for (size_t i = 0; i < n_items; ++i) {\n        n_logz -= log1exp(noise_utilities[i]);\n    }\n\n    vector<double> a_gradient(m_features);\n    for (size_t iter = 0; iter < n_steps; ++iter) {\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            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                    p_noise += features[index_features(data[i], j)] *\n                            noise_weights[j];\n                }\n            }\n\n            vector<double> max_weights(l_dimensions);\n            vector<int> max_weight_indexes(l_dimensions);\n            for (size_t j = 0; j < l_dimensions; ++j) {\n                max_weights[j] = -1;\n                max_weight_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_weights[j]) {\n                        max_weights[j] = weight;\n                        max_weight_indexes[j] = data[i];\n                    }\n                    p_model -= weight;\n                }\n                p_model += max_weights[j];\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 - expit(p_model - p_noise - log_nu));\n\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(max_weight_indexes[j], i)] -\n                                a_gradient[i]);\n                    if (b_weights[index_b_weights(i, j)] <= 0) {\n                        b_weights[index_b_weights(i, j)] =\n                                udouble_dist(random_engine);\n                    }\n                }\n            }\n            n_logz += factor;\n        }\n    }\n\n    fstream output_file(output_file_path, ios::out);\n\n    cout << n_logz << endl;\n    output_file << n_logz << endl;\n\n    for (size_t i = 0; i < m_features - 1; ++i) {\n        cout << a_weights[i] << \",\";\n        output_file << a_weights[i] << \",\";\n    }\n    cout << a_weights[m_features - 1] << endl;\n    output_file << a_weights[m_features - 1] << endl;\n\n    for (size_t i = 0; i < m_features; ++i) {\n        for (size_t j = 0; j < l_dimensions - 1; ++j) {\n            cout << b_weights[index_b_weights(i, j)] << \",\";\n            output_file << b_weights[index_b_weights(i, j)] << \",\";\n        }\n        output_file << b_weights[index_b_weights(i, l_dimensions - 1)] << endl;\n        cout << endl;\n    }\n\n}\n\nint main(int argc, char* argv[]) {\n    int fold_number = stoi(argv[1]);\n    int dim_number = stoi(argv[2]);\n    int feature_set = stoi(argv[3]);\n    for (int d = 1; d <= dim_number; ++d) {\n        for (int i = 1; i <= fold_number; ++i) {\n            train_with_features(\n                    (boost::format(\"/home/diegob/workspace/master-thesis-2015/data/path_set_nce_data_features_%1%_fold_%2%.csv\") % feature_set % i).str(),\n                    (boost::format(\"/home/diegob/workspace/master-thesis-2015/data/path_set_nce_features_%1%.csv\") % feature_set).str(),\n                    (boost::format(\"/home/diegob/workspace/master-thesis-2015/data/path_set_nce_noise_features_%1%_fold_%2%.csv\") % feature_set % i).str(),\n                    10, 0.01, 0.1, d,\n                    (boost::format(\"/home/diegob/workspace/master-thesis-2015/data/models/path_set_nce_out_features_%1%_dim_%2%_fold_%3%.csv\") % feature_set % d % i).str());\n        }\n    }\n\n}\n", "meta": {"hexsha": "a3c82d2476ac7cc3a5ef41388a8984b0adbcca50", "size": 8960, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/models/train_features.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": "src/models/train_features.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": "src/models/train_features.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": 36.1290322581, "max_line_length": 173, "alphanum_fraction": 0.5361607143, "num_tokens": 2285, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300048, "lm_q2_score": 0.6791786861878392, "lm_q1q2_score": 0.49651940496027575}}
{"text": "/* boost random/lagged_fibonacci.hpp header file\n *\n * Copyright Jens Maurer 2000-2001\n * Permission to use, copy, modify, sell, and distribute this software\n * is hereby granted without fee provided that the above copyright notice\n * appears in all copies and that both that copyright notice and this\n * permission notice appear in supporting documentation,\n *\n * Jens Maurer makes no representations about the suitability of this\n * software for any purpose. It is provided \"as is\" without express or\n * implied warranty.\n *\n * See http://www.boost.org for most recent version including documentation.\n *\n * $Id: lagged_fibonacci.hpp 13038 2002-03-03 09:13:57Z jmaurer $\n *\n * Revision history\n *  2001-02-18  moved to individual header files\n */\n\n#ifndef BOOST_RANDOM_LAGGED_FIBONACCI_HPP\n#define BOOST_RANDOM_LAGGED_FIBONACCI_HPP\n\n#include <iostream>\n#include <algorithm>     // std::max\n#include <boost/config.hpp>\n#include <boost/limits.hpp>\n#include <boost/cstdint.hpp>\n#include <boost/random/linear_congruential.hpp>\n#include <boost/random/uniform_01.hpp>\n\nnamespace boost {\nnamespace random {\n\n// lagged Fibonacci generator for the range [0..1)\n// contributed by Matthias Troyer\n// for p=55, q=24 originally by G. J. Mitchell and D. P. Moore 1958\n\ntemplate<class T, unsigned int p, unsigned int q>\nstruct fibonacci_validation\n{\n  BOOST_STATIC_CONSTANT(bool, is_specialized = false);\n  static T value() { return 0; }\n  static T tolerance() { return 0; }\n};\n\n#ifndef BOOST_NO_INCLASS_MEMBER_INITIALIZATION\n//  A definition is required even for integral static constants\ntemplate<class T, unsigned int p, unsigned int q>\nconst bool fibonacci_validation<T, p, q>::is_specialized;\n#endif\n\n#define BOOST_RANDOM_FIBONACCI_VAL(T,P,Q,V,E) \\\ntemplate<> \\\nstruct fibonacci_validation<T, P, Q>  \\\n{                                     \\\n  BOOST_STATIC_CONSTANT(bool, is_specialized = true);     \\\n  static T value() { return V; }      \\\n  static T tolerance()                \\\n    { return std::max(E, static_cast<T>(5*std::numeric_limits<T>::epsilon())); } \\\n};\n// (The extra static_cast<T> in the std::max call above is actually\n// unnecessary except for HP aCC 1.30, which claims that\n// numeric_limits<double>::epsilon() doesn't actually return a double.)\n\nBOOST_RANDOM_FIBONACCI_VAL(double, 607, 273, 0.4293817707235914, 1e-14)\nBOOST_RANDOM_FIBONACCI_VAL(double, 1279, 418, 0.9421630240437659, 1e-14)\nBOOST_RANDOM_FIBONACCI_VAL(double, 2281, 1252, 0.1768114046909004, 1e-14)\nBOOST_RANDOM_FIBONACCI_VAL(double, 3217, 576, 0.1956232694868209, 1e-14)\nBOOST_RANDOM_FIBONACCI_VAL(double, 4423, 2098, 0.9499762202147172, 1e-14)\nBOOST_RANDOM_FIBONACCI_VAL(double, 9689, 5502, 0.05737836943695162, 1e-14)\nBOOST_RANDOM_FIBONACCI_VAL(double, 19937, 9842, 0.5076528587449834, 1e-14)\nBOOST_RANDOM_FIBONACCI_VAL(double, 23209, 13470, 0.5414473810619185, 1e-14)\nBOOST_RANDOM_FIBONACCI_VAL(double, 44497,21034, 0.254135073399297, 1e-14)\n\n#undef BOOST_RANDOM_FIBONACCI_VAL\n\ntemplate<class FloatType, unsigned int p, unsigned int q>\nclass lagged_fibonacci\n{\npublic:\n  typedef FloatType result_type;\n  BOOST_STATIC_CONSTANT(bool, has_fixed_range = false);\n  BOOST_STATIC_CONSTANT(unsigned int, long_lag = p);\n  BOOST_STATIC_CONSTANT(unsigned int, short_lag = q);\n\n  result_type min() const { return 0.0; }\n  result_type max() const { return 1.0; }\n\n  lagged_fibonacci() { seed(); }\n  explicit lagged_fibonacci(uint32_t value) { seed(value); }\n  template<class Generator>\n  explicit lagged_fibonacci(Generator & gen) { seed(gen); }\n  // compiler-generated copy ctor and assignment operator are fine\n\n  void seed(uint32_t value = 331u)\n  {\n    minstd_rand0 intgen(value);\n    seed(intgen);\n  }\n\n  // For GCC, moving this function out-of-line prevents inlining, which may\n  // reduce overall object code size.  However, MSVC does not grok\n  // out-of-line template member functions.\n  template<class Generator>\n  void seed(Generator & gen)\n  {\n    uniform_01<Generator, FloatType> gen01(gen);\n    // I could have used std::generate_n, but it takes \"gen\" by value\n    for(unsigned int j = 0; j < long_lag; ++j)\n      x[j] = gen01();\n    i = long_lag;\n  }\n\n  result_type operator()()\n  {\n    if(i >= long_lag)\n      fill();\n    return x[i++];\n  }\n\n  bool validation(result_type x) const\n  {\n    result_type v = fibonacci_validation<result_type, p, q>::value();\n    result_type epsilon = fibonacci_validation<result_type, p, q>::tolerance();\n    // std::abs is a source of trouble: sometimes, it's not overloaded\n    // for double, plus the usual namespace std noncompliance -> avoid it\n    // using std::abs;\n    // return abs(x - v) < 5 * epsilon\n    return x > v - epsilon && x < v + epsilon;\n  }\n  \n#ifndef BOOST_NO_OPERATORS_IN_NAMESPACE\n  friend std::ostream& operator<<(std::ostream& os, const lagged_fibonacci& f)\n  {\n    os << f.i << \" \";\n    std::streamsize prec =\n      os.precision(std::numeric_limits<FloatType>::digits10);\n    for(unsigned int i = 0; i < long_lag; ++i)\n      os << f.x[i] << \" \";\n    os.precision(prec);\n    return os;\n  }\n  friend std::istream& operator>>(std::istream& is, lagged_fibonacci& f)\n  {\n    is >> f.i >> std::ws;\n    for(unsigned int i = 0; i < long_lag; ++i)\n      is >> f.x[i] >> std::ws;\n    return is;\n  }\n  friend bool operator==(const lagged_fibonacci& x, const lagged_fibonacci& y)\n  { return x.i == y.i && std::equal(x.x, x.x+long_lag, y.x); }\n#else\n  // Use a member function; Streamable concept not supported.\n  bool operator==(const lagged_fibonacci& rhs) const\n  { return i == rhs.i && std::equal(x, x+long_lag, rhs.x); }\n#endif\n\nprivate:\n  void fill();\n  unsigned int i;\n  FloatType x[long_lag];\n};\n\n#ifndef BOOST_NO_INCLASS_MEMBER_INITIALIZATION\n//  A definition is required even for integral static constants\ntemplate<class FloatType, unsigned int p, unsigned int q>\nconst bool lagged_fibonacci<FloatType, p, q>::has_fixed_range;\ntemplate<class FloatType, unsigned int p, unsigned int q>\nconst unsigned int lagged_fibonacci<FloatType, p, q>::long_lag;\ntemplate<class FloatType, unsigned int p, unsigned int q>\nconst unsigned int lagged_fibonacci<FloatType, p, q>::short_lag;\n\n#endif\n\ntemplate<class FloatType, unsigned int p, unsigned int q>\nvoid lagged_fibonacci<FloatType, p, q>::fill()\n{\n  // two loops to avoid costly modulo operations\n  {  // extra scope for MSVC brokenness w.r.t. for scope\n  for(unsigned int j = 0; j < short_lag; ++j) {\n    FloatType t = x[j] + x[j+(long_lag-short_lag)];\n    if(t >= 1.0)\n      t -= 1.0;\n    x[j] = t;\n  }\n  }\n  for(unsigned int j = short_lag; j < long_lag; ++j) {\n    FloatType t = x[j] + x[j-short_lag];\n    if(t >= 1.0)\n      t -= 1.0;\n    x[j] = t;\n  }\n  i = 0;\n}\n\n} // namespace random\n\ntypedef random::lagged_fibonacci<double, 607, 273> lagged_fibonacci607;\ntypedef random::lagged_fibonacci<double, 1279, 418> lagged_fibonacci1279;\ntypedef random::lagged_fibonacci<double, 2281, 1252> lagged_fibonacci2281;\ntypedef random::lagged_fibonacci<double, 3217, 576> lagged_fibonacci3217;\ntypedef random::lagged_fibonacci<double, 4423, 2098> lagged_fibonacci4423;\ntypedef random::lagged_fibonacci<double, 9689, 5502> lagged_fibonacci9689;\ntypedef random::lagged_fibonacci<double, 19937, 9842> lagged_fibonacci19937;\ntypedef random::lagged_fibonacci<double, 23209, 13470> lagged_fibonacci23209;\ntypedef random::lagged_fibonacci<double, 44497, 21034> lagged_fibonacci44497;\n\n\n// It is possible to partially specialize uniform_01<> on lagged_fibonacci<>\n// to help the compiler generate efficient code.  For GCC, this seems useless,\n// because GCC optimizes (x-0)/(1-0) to (x-0).  This is good enough for now.\n\n} // namespace boost\n\n#endif // BOOST_RANDOM_LAGGED_FIBONACCI_HPP\n", "meta": {"hexsha": "c0b9eb5f4e4b0f02c5a59006a20d2e1832df7779", "size": 7651, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "vegastrike/boost/1_28/boost/random/lagged_fibonacci.hpp", "max_stars_repo_name": "Ezeer/VegaStrike_win32FR", "max_stars_repo_head_hexsha": "75891b9ccbdb95e48e15d3b4a9cd977955b97d1f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "vegastrike/boost/1_28/boost/random/lagged_fibonacci.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/random/lagged_fibonacci.hpp", "max_forks_repo_name": "Ezeer/VegaStrike_win32FR", "max_forks_repo_head_hexsha": "75891b9ccbdb95e48e15d3b4a9cd977955b97d1f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.2580645161, "max_line_length": 82, "alphanum_fraction": 0.7152006274, "num_tokens": 2248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208004, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.4964887767186541}}
{"text": "/* Copyright (c) 2020 C. Pattison\r\n * All rights reserved.\r\n * \r\n * Redistribution and use in source and binary forms, with or without\r\n * modification, are permitted provided that the following conditions are met:\r\n * \r\n * 1. Redistributions of source code must retain the above copyright notice, this\r\n *    list of conditions and the following disclaimer.\r\n * 2. Redistributions in binary form must reproduce the above copyright notice,\r\n *    this list of conditions and the following disclaimer in the documentation\r\n *    and/or other materials provided with the distribution.\r\n * \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 THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\r\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\r\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\r\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\r\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\r\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n */\r\n \r\n#pragma once\r\n#include <cassert>\r\n#include <algorithm>\r\n#include <utility>\r\n#include <complex>\r\n#include <random>\r\n#include <cmath>\r\n\r\n#include <Eigen/Dense>\r\n#include \"syk_types.hpp\"\r\n\r\n// https://web.eecs.umich.edu/~rajnrao/Acta05rmt.pdf\r\n\r\nnamespace syk {\r\nusing namespace std::complex_literals;\r\n\r\ntemplate<typename rng_type>\r\nMatrixType RandomRealIidGauss(rng_type* rand_gen, int n, int m) {\r\n    MatrixType mat = MatrixType::Zero(n, m);\r\n    std::normal_distribution normal;\r\n\r\n    for(int j = 0; j < m; ++j) {\r\n        for(int i = 0; i < n; ++i) {\r\n            mat(i, j) = static_cast<MatrixType::Scalar>(normal(*rand_gen));\r\n        }\r\n    }\r\n    return mat;\r\n}\r\n\r\ntemplate<typename rng_type>\r\nMatrixType RandomGOE(rng_type* rand_gen, int n) {\r\n    MatrixType A = RandomRealIidGauss(rand_gen, n, n);\r\n    return (A + A.transpose()) / (2 * std::sqrt(n));\r\n}\r\n\r\ntemplate<typename rng_type>\r\nMatrixType RandomGUE(rng_type* rand_gen, int n) {\r\n    MatrixType A = RandomRealIidGauss(rand_gen, n, n) + 1.0i * RandomRealIidGauss(rand_gen, n, n);\r\n    return (A + A.adjoint()) / (2 * std::sqrt(n));\r\n}\r\n}", "meta": {"hexsha": "593d4519da611cd66eddfb060717f0e8373e0783", "size": 2496, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/random_matrix.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/random_matrix.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/random_matrix.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": 38.4, "max_line_length": 99, "alphanum_fraction": 0.7047275641, "num_tokens": 594, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.4964887717678952}}
{"text": "// This file is part of Eigen, a lightweight C++ template library\r\n// for linear algebra.\r\n//\r\n// Copyright (C) 2015 Eugene Brevdo <ebrevdo@google.com>\r\n//                    Benoit Steiner <benoit.steiner.goog@gmail.com>\r\n//\r\n// This Source Code Form is subject to the terms of the Mozilla\r\n// Public License v. 2.0. If a copy of the MPL was not distributed\r\n// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.\r\n\r\n#include \"main.h\"\r\n\r\n#include <Eigen/CXX11/Tensor>\r\n\r\nusing Eigen::Tensor;\r\nusing Eigen::array;\r\nusing Eigen::Tuple;\r\n\r\ntemplate <int DataLayout>\r\nstatic void test_simple_index_tuples()\r\n{\r\n  Tensor<float, 4, DataLayout> tensor(2,3,5,7);\r\n  tensor.setRandom();\r\n  tensor = (tensor + tensor.constant(0.5)).log();\r\n\r\n  Tensor<Tuple<DenseIndex, float>, 4, DataLayout> index_tuples(2,3,5,7);\r\n  index_tuples = tensor.index_tuples();\r\n\r\n  for (DenseIndex n = 0; n < 2*3*5*7; ++n) {\r\n    const Tuple<DenseIndex, float>& v = index_tuples.coeff(n);\r\n    VERIFY_IS_EQUAL(v.first, n);\r\n    VERIFY_IS_EQUAL(v.second, tensor.coeff(n));\r\n  }\r\n}\r\n\r\ntemplate <int DataLayout>\r\nstatic void test_index_tuples_dim()\r\n{\r\n  Tensor<float, 4, DataLayout> tensor(2,3,5,7);\r\n  tensor.setRandom();\r\n  tensor = (tensor + tensor.constant(0.5)).log();\r\n\r\n  Tensor<Tuple<DenseIndex, float>, 4, DataLayout> index_tuples(2,3,5,7);\r\n\r\n  index_tuples = tensor.index_tuples();\r\n\r\n  for (Eigen::DenseIndex n = 0; n < tensor.size(); ++n) {\r\n    const Tuple<DenseIndex, float>& v = index_tuples(n); //(i, j, k, l);\r\n    VERIFY_IS_EQUAL(v.first, n);\r\n    VERIFY_IS_EQUAL(v.second, tensor(n));\r\n  }\r\n}\r\n\r\ntemplate <int DataLayout>\r\nstatic void test_argmax_tuple_reducer()\r\n{\r\n  Tensor<float, 4, DataLayout> tensor(2,3,5,7);\r\n  tensor.setRandom();\r\n  tensor = (tensor + tensor.constant(0.5)).log();\r\n\r\n  Tensor<Tuple<DenseIndex, float>, 4, DataLayout> index_tuples(2,3,5,7);\r\n  index_tuples = tensor.index_tuples();\r\n\r\n  Tensor<Tuple<DenseIndex, float>, 0, DataLayout> reduced;\r\n  DimensionList<DenseIndex, 4> dims;\r\n  reduced = index_tuples.reduce(\r\n      dims, internal::ArgMaxTupleReducer<Tuple<DenseIndex, float> >());\r\n\r\n  Tensor<float, 0, DataLayout> maxi = tensor.maximum();\r\n\r\n  VERIFY_IS_EQUAL(maxi(), reduced(0).second);\r\n\r\n  array<DenseIndex, 3> reduce_dims;\r\n  for (int d = 0; d < 3; ++d) reduce_dims[d] = d;\r\n  Tensor<Tuple<DenseIndex, float>, 1, DataLayout> reduced_by_dims(7);\r\n  reduced_by_dims = index_tuples.reduce(\r\n      reduce_dims, internal::ArgMaxTupleReducer<Tuple<DenseIndex, float> >());\r\n\r\n  Tensor<float, 1, DataLayout> max_by_dims = tensor.maximum(reduce_dims);\r\n\r\n  for (int l = 0; l < 7; ++l) {\r\n    VERIFY_IS_EQUAL(max_by_dims(l), reduced_by_dims(l).second);\r\n  }\r\n}\r\n\r\ntemplate <int DataLayout>\r\nstatic void test_argmin_tuple_reducer()\r\n{\r\n  Tensor<float, 4, DataLayout> tensor(2,3,5,7);\r\n  tensor.setRandom();\r\n  tensor = (tensor + tensor.constant(0.5)).log();\r\n\r\n  Tensor<Tuple<DenseIndex, float>, 4, DataLayout> index_tuples(2,3,5,7);\r\n  index_tuples = tensor.index_tuples();\r\n\r\n  Tensor<Tuple<DenseIndex, float>, 0, DataLayout> reduced;\r\n  DimensionList<DenseIndex, 4> dims;\r\n  reduced = index_tuples.reduce(\r\n      dims, internal::ArgMinTupleReducer<Tuple<DenseIndex, float> >());\r\n\r\n  Tensor<float, 0, DataLayout> mini = tensor.minimum();\r\n\r\n  VERIFY_IS_EQUAL(mini(), reduced(0).second);\r\n\r\n  array<DenseIndex, 3> reduce_dims;\r\n  for (int d = 0; d < 3; ++d) reduce_dims[d] = d;\r\n  Tensor<Tuple<DenseIndex, float>, 1, DataLayout> reduced_by_dims(7);\r\n  reduced_by_dims = index_tuples.reduce(\r\n      reduce_dims, internal::ArgMinTupleReducer<Tuple<DenseIndex, float> >());\r\n\r\n  Tensor<float, 1, DataLayout> min_by_dims = tensor.minimum(reduce_dims);\r\n\r\n  for (int l = 0; l < 7; ++l) {\r\n    VERIFY_IS_EQUAL(min_by_dims(l), reduced_by_dims(l).second);\r\n  }\r\n}\r\n\r\ntemplate <int DataLayout>\r\nstatic void test_simple_argmax()\r\n{\r\n  Tensor<float, 4, DataLayout> tensor(2,3,5,7);\r\n  tensor.setRandom();\r\n  tensor = (tensor + tensor.constant(0.5)).log();\r\n  tensor(0,0,0,0) = 10.0;\r\n\r\n  Tensor<DenseIndex, 0, DataLayout> tensor_argmax;\r\n\r\n  tensor_argmax = tensor.argmax();\r\n\r\n  VERIFY_IS_EQUAL(tensor_argmax(0), 0);\r\n\r\n  tensor(1,2,4,6) = 20.0;\r\n\r\n  tensor_argmax = tensor.argmax();\r\n\r\n  VERIFY_IS_EQUAL(tensor_argmax(0), 2*3*5*7 - 1);\r\n}\r\n\r\ntemplate <int DataLayout>\r\nstatic void test_simple_argmin()\r\n{\r\n  Tensor<float, 4, DataLayout> tensor(2,3,5,7);\r\n  tensor.setRandom();\r\n  tensor = (tensor + tensor.constant(0.5)).log();\r\n  tensor(0,0,0,0) = -10.0;\r\n\r\n  Tensor<DenseIndex, 0, DataLayout> tensor_argmin;\r\n\r\n  tensor_argmin = tensor.argmin();\r\n\r\n  VERIFY_IS_EQUAL(tensor_argmin(0), 0);\r\n\r\n  tensor(1,2,4,6) = -20.0;\r\n\r\n  tensor_argmin = tensor.argmin();\r\n\r\n  VERIFY_IS_EQUAL(tensor_argmin(0), 2*3*5*7 - 1);\r\n}\r\n\r\ntemplate <int DataLayout>\r\nstatic void test_argmax_dim()\r\n{\r\n  Tensor<float, 4, DataLayout> tensor(2,3,5,7);\r\n  std::vector<int> dims {2, 3, 5, 7};\r\n\r\n  for (int dim = 0; dim < 4; ++dim) {\r\n    tensor.setRandom();\r\n    tensor = (tensor + tensor.constant(0.5)).log();\r\n\r\n    Tensor<DenseIndex, 3, DataLayout> tensor_argmax;\r\n    array<DenseIndex, 4> ix;\r\n    for (int i = 0; i < 2; ++i) {\r\n      for (int j = 0; j < 3; ++j) {\r\n        for (int k = 0; k < 5; ++k) {\r\n          for (int l = 0; l < 7; ++l) {\r\n            ix[0] = i; ix[1] = j; ix[2] = k; ix[3] = l;\r\n            if (ix[dim] != 0) continue;\r\n            // suppose dim == 1, then for all i, k, l, set tensor(i, 0, k, l) = 10.0\r\n            tensor(ix) = 10.0;\r\n          }\r\n        }\r\n      }\r\n    }\r\n\r\n    tensor_argmax = tensor.argmax(dim);\r\n\r\n    VERIFY_IS_EQUAL(tensor_argmax.size(),\r\n                    ptrdiff_t(2*3*5*7 / tensor.dimension(dim)));\r\n    for (ptrdiff_t n = 0; n < tensor_argmax.size(); ++n) {\r\n      // Expect max to be in the first index of the reduced dimension\r\n      VERIFY_IS_EQUAL(tensor_argmax.data()[n], 0);\r\n    }\r\n\r\n    for (int i = 0; i < 2; ++i) {\r\n      for (int j = 0; j < 3; ++j) {\r\n        for (int k = 0; k < 5; ++k) {\r\n          for (int l = 0; l < 7; ++l) {\r\n            ix[0] = i; ix[1] = j; ix[2] = k; ix[3] = l;\r\n            if (ix[dim] != tensor.dimension(dim) - 1) continue;\r\n            // suppose dim == 1, then for all i, k, l, set tensor(i, 2, k, l) = 20.0\r\n            tensor(ix) = 20.0;\r\n          }\r\n        }\r\n      }\r\n    }\r\n\r\n    tensor_argmax = tensor.argmax(dim);\r\n\r\n    VERIFY_IS_EQUAL(tensor_argmax.size(),\r\n                    ptrdiff_t(2*3*5*7 / tensor.dimension(dim)));\r\n    for (ptrdiff_t n = 0; n < tensor_argmax.size(); ++n) {\r\n      // Expect max to be in the last index of the reduced dimension\r\n      VERIFY_IS_EQUAL(tensor_argmax.data()[n], tensor.dimension(dim) - 1);\r\n    }\r\n  }\r\n}\r\n\r\ntemplate <int DataLayout>\r\nstatic void test_argmin_dim()\r\n{\r\n  Tensor<float, 4, DataLayout> tensor(2,3,5,7);\r\n  std::vector<int> dims {2, 3, 5, 7};\r\n\r\n  for (int dim = 0; dim < 4; ++dim) {\r\n    tensor.setRandom();\r\n    tensor = (tensor + tensor.constant(0.5)).log();\r\n\r\n    Tensor<DenseIndex, 3, DataLayout> tensor_argmin;\r\n    array<DenseIndex, 4> ix;\r\n    for (int i = 0; i < 2; ++i) {\r\n      for (int j = 0; j < 3; ++j) {\r\n        for (int k = 0; k < 5; ++k) {\r\n          for (int l = 0; l < 7; ++l) {\r\n            ix[0] = i; ix[1] = j; ix[2] = k; ix[3] = l;\r\n            if (ix[dim] != 0) continue;\r\n            // suppose dim == 1, then for all i, k, l, set tensor(i, 0, k, l) = -10.0\r\n            tensor(ix) = -10.0;\r\n          }\r\n        }\r\n      }\r\n    }\r\n\r\n    tensor_argmin = tensor.argmin(dim);\r\n\r\n    VERIFY_IS_EQUAL(tensor_argmin.size(),\r\n                    ptrdiff_t(2*3*5*7 / tensor.dimension(dim)));\r\n    for (ptrdiff_t n = 0; n < tensor_argmin.size(); ++n) {\r\n      // Expect min to be in the first index of the reduced dimension\r\n      VERIFY_IS_EQUAL(tensor_argmin.data()[n], 0);\r\n    }\r\n\r\n    for (int i = 0; i < 2; ++i) {\r\n      for (int j = 0; j < 3; ++j) {\r\n        for (int k = 0; k < 5; ++k) {\r\n          for (int l = 0; l < 7; ++l) {\r\n            ix[0] = i; ix[1] = j; ix[2] = k; ix[3] = l;\r\n            if (ix[dim] != tensor.dimension(dim) - 1) continue;\r\n            // suppose dim == 1, then for all i, k, l, set tensor(i, 2, k, l) = -20.0\r\n            tensor(ix) = -20.0;\r\n          }\r\n        }\r\n      }\r\n    }\r\n\r\n    tensor_argmin = tensor.argmin(dim);\r\n\r\n    VERIFY_IS_EQUAL(tensor_argmin.size(),\r\n                    ptrdiff_t(2*3*5*7 / tensor.dimension(dim)));\r\n    for (ptrdiff_t n = 0; n < tensor_argmin.size(); ++n) {\r\n      // Expect min to be in the last index of the reduced dimension\r\n      VERIFY_IS_EQUAL(tensor_argmin.data()[n], tensor.dimension(dim) - 1);\r\n    }\r\n  }\r\n}\r\n\r\nvoid test_cxx11_tensor_argmax()\r\n{\r\n  CALL_SUBTEST(test_simple_index_tuples<RowMajor>());\r\n  CALL_SUBTEST(test_simple_index_tuples<ColMajor>());\r\n  CALL_SUBTEST(test_index_tuples_dim<RowMajor>());\r\n  CALL_SUBTEST(test_index_tuples_dim<ColMajor>());\r\n  CALL_SUBTEST(test_argmax_tuple_reducer<RowMajor>());\r\n  CALL_SUBTEST(test_argmax_tuple_reducer<ColMajor>());\r\n  CALL_SUBTEST(test_argmin_tuple_reducer<RowMajor>());\r\n  CALL_SUBTEST(test_argmin_tuple_reducer<ColMajor>());\r\n  CALL_SUBTEST(test_simple_argmax<RowMajor>());\r\n  CALL_SUBTEST(test_simple_argmax<ColMajor>());\r\n  CALL_SUBTEST(test_simple_argmin<RowMajor>());\r\n  CALL_SUBTEST(test_simple_argmin<ColMajor>());\r\n  CALL_SUBTEST(test_argmax_dim<RowMajor>());\r\n  CALL_SUBTEST(test_argmax_dim<ColMajor>());\r\n  CALL_SUBTEST(test_argmin_dim<RowMajor>());\r\n  CALL_SUBTEST(test_argmin_dim<ColMajor>());\r\n}\r\n", "meta": {"hexsha": "29bef3caed484c48609a42286e22b86af49f605b", "size": 9436, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "packages/eigen-eigen-323c052e1731/unsupported/test/cxx11_tensor_argmax.cpp", "max_stars_repo_name": "k4rth33k/dnnc-operators", "max_stars_repo_head_hexsha": "a7fe3f1240c12b3438558def71fbfcd4520446c3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-08-16T14:35:17.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-11T23:59:22.000Z", "max_issues_repo_path": "packages/eigen-eigen-323c052e1731/unsupported/test/cxx11_tensor_argmax.cpp", "max_issues_repo_name": "k4rth33k/dnnc-operators", "max_issues_repo_head_hexsha": "a7fe3f1240c12b3438558def71fbfcd4520446c3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-08-12T04:38:14.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T16:32:13.000Z", "max_forks_repo_path": "packages/eigen-eigen-323c052e1731/unsupported/test/cxx11_tensor_argmax.cpp", "max_forks_repo_name": "k4rth33k/dnnc-operators", "max_forks_repo_head_hexsha": "a7fe3f1240c12b3438558def71fbfcd4520446c3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-08-15T13:29:00.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-09T17:08:04.000Z", "avg_line_length": 31.986440678, "max_line_length": 86, "alphanum_fraction": 0.6007842306, "num_tokens": 2893, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.4964887717678952}}
{"text": "/*\n * TypeDefs.hpp\n *\n *  Created on: March 18, 2014\n *      Author: P\u00e9ter Fankhauser\n *\t Institute: ETH Zurich, ANYbotics\n */\n\n// Eigen\n#define EIGEN_DENSEBASE_PLUGIN \"grid_map_core/eigen_plugins/DenseBasePlugin.hpp\"\n#define EIGEN_FUNCTORS_PLUGIN \"grid_map_core/eigen_plugins/FunctorsPlugin.hpp\"\n\n#include <Eigen/Core>\n\n#pragma once\n\nnamespace grid_map {\n\n  typedef Eigen::MatrixXf Matrix;\n  typedef Matrix::Scalar DataType;\n  typedef Eigen::Vector2d Position;\n  typedef Eigen::Vector2d Vector;\n  typedef Eigen::Vector3d Position3;\n  typedef Eigen::Vector3d Vector3;\n  typedef Eigen::Array2i Index;\n  typedef Eigen::Array2i Size;\n  typedef Eigen::Array2d Length;\n  typedef uint64_t Time;\n\n  enum class InterpolationMethods{\n      INTER_NEAREST, // nearest neighbor interpolation\n      INTER_LINEAR   // bilinear interpolation\n      // ToDo: INTER_CUBIC\n  };\n\n} /* namespace */\n", "meta": {"hexsha": "f3a3b463ae596884754cc575e7205b21f1972a41", "size": 878, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "grid_map_core/include/grid_map_core/TypeDefs.hpp", "max_stars_repo_name": "BeatScherrer/grid_map", "max_stars_repo_head_hexsha": "9a6ba1ef494cd3c5bbd9c0f050653bc50f758ecf", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "grid_map_core/include/grid_map_core/TypeDefs.hpp", "max_issues_repo_name": "BeatScherrer/grid_map", "max_issues_repo_head_hexsha": "9a6ba1ef494cd3c5bbd9c0f050653bc50f758ecf", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "grid_map_core/include/grid_map_core/TypeDefs.hpp", "max_forks_repo_name": "BeatScherrer/grid_map", "max_forks_repo_head_hexsha": "9a6ba1ef494cd3c5bbd9c0f050653bc50f758ecf", "max_forks_repo_licenses": ["BSD-3-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.7297297297, "max_line_length": 80, "alphanum_fraction": 0.7403189066, "num_tokens": 228, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.4964887692061359}}
{"text": "/**  \\file trace_ublas.hpp \\brief Trace computation for uBlas */\n/*\n-----------------------------------------------------------------------------\n   Copyright (C) 2011 Ruben Martinez-Cantin <rmcantin@unizar.es>\n \n   This program is free software: you can redistribute it and/or modify\n   it under the terms of the GNU Affero General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU Affero General Public License for more details.\n\n   You should have received a copy of the GNU Affero General Public License\n   along with this program.  If not, see <http://www.gnu.org/licenses/>.\n-----------------------------------------------------------------------------\n*/\n#ifndef __TRACE_UBLAS_HPP__\n#define __TRACE_UBLAS_HPP__\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n\nnamespace bayesopt\n{\n  namespace utils\n  {\n\n    template<class E>\n    typename E::value_type trace(const E &A)\n    {\n      const size_t n = (std::min)(A.size1(),A.size2());\n      typename E::value_type sum = 0;\n      for (size_t i=0; i<n; ++i)\n\tsum += A(i,i);\n\n      return sum; \n    }\n\n    template<class E>\n    typename E::value_type log_trace(const E &A)\n    {\n      const size_t n = (std::min)(A.size1(),A.size2());\n      typename E::value_type sum = 0;\n      for (size_t i=0; i<n; ++i)\n\tsum += std::log(A(i,i));\n\n      return sum; \n    }\n\n\n    template<class E1, class E2>\n    typename E1::value_type trace_prod(const E1 & A, const E2 & B )\n    {\n      namespace ublas = boost::numeric::ublas;\n\n      const size_t n = (std::min)(A.size1(),B.size2());\n      typename E1::value_type sum = 0;\n      for (size_t i=0; i<n; ++i)\n\tsum += ublas::inner_prod(ublas::row(A,i),ublas::column(B,i));\n\n      return sum; \n    }\n    \n  } //  namespace utils\n} //namespace bayesopt\n\n#endif\n", "meta": {"hexsha": "1a688d6032dfc75e1438ac02761f98bf37a20f4e", "size": 2082, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "external/bayesopt/utils/ublas_trace.hpp", "max_stars_repo_name": "pchrapka/brain-modelling", "max_stars_repo_head_hexsha": "f232b5a858e45f10b0b0735269010454129ab017", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-10-13T19:37:52.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-13T19:37:52.000Z", "max_issues_repo_path": "external/bayesopt/utils/ublas_trace.hpp", "max_issues_repo_name": "pchrapka/brain-modelling", "max_issues_repo_head_hexsha": "f232b5a858e45f10b0b0735269010454129ab017", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "external/bayesopt/utils/ublas_trace.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.323943662, "max_line_length": 78, "alphanum_fraction": 0.6099903939, "num_tokens": 536, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.6654105521116445, "lm_q1q2_score": 0.49648875930461855}}
{"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_ACSCPI_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_ACSCPI_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 inverse secant in \\f$\\pi\\f$ multiples:\n    \\f$(1/\\pi) \\arcsin(1/x)\\f$.\n\n    @par Header <boost/simd/function/acscpi.hpp>\n\n    @see acsc,  acscd\n\n    @par Example:\n\n      @snippet acscpi.cpp acscpi\n\n    @par Possible output:\n\n      @snippet acscpi.txt acscpi\n\n  **/\n  IEEEValue acscpi(IEEEValue const & x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/acscpi.hpp>\n#include <boost/simd/function/simd/acscpi.hpp>\n\n#endif\n", "meta": {"hexsha": "82a271f7981f700ad0b0aa8a30738bc522d11390", "size": 1051, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/acscpi.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/acscpi.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/acscpi.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 23.8863636364, "max_line_length": 100, "alphanum_fraction": 0.5746907707, "num_tokens": 246, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262966, "lm_q2_score": 0.5926665999540697, "lm_q1q2_score": 0.49642937091764927}}
{"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_TRIGONOMETRIC_CONSTANTS_PIX_4_HPP_INCLUDED\n#define NT2_TOOLBOX_TRIGONOMETRIC_CONSTANTS_PIX_4_HPP_INCLUDED\n/*!\n * \\file\n**/\n#include <boost/simd/sdk/constant/constant.hpp>\n#include <boost/simd/sdk/constant/register.hpp>\n\n/*!\n * \\ingroup trigo_constant\n * \\defgroup trigo_constant_pix_4 Pix_4\n *\n * \\par Description\n * Constant pix_4 : \\f$4\\pi\\f$.\n *\n * \\par Header file\n *\n * \\code\n * #include <nt2/include/functions/pix_4.hpp>\n * \\endcode\n *\n *\n * \\synopsis\n *\n * \\code\n * namespace boost::simd\n * {\n *   template <class T,class A0>\n *     meta::call<tag::_pix_4_(A0)>::type\n *     pix_4();\n * }\n * \\endcode\n *\n *\n * \\param T template parameter of Pix_4\n *\n * \\return type T value\n *\n **/\n\nnamespace nt2\n{\n  namespace tag\n  {\n    BOOST_SIMD_CONSTANT_REGISTER( Pix_4, double\n                                , 12, 0x41490fdb\n                                , 0x402921fb54442d18ll\n                                );\n  }\n\n  BOOST_SIMD_CONSTANT_IMPLEMENTATION(tag::Pix_4, Pix_4);\n}\n\n#endif\n", "meta": {"hexsha": "d1586542568d0c193e911a5962006d67ababe73f", "size": 1513, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/trigonometric/include/nt2/toolbox/trigonometric/constants/pix_4.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/constants/pix_4.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/constants/pix_4.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": 24.0158730159, "max_line_length": 80, "alphanum_fraction": 0.5492399207, "num_tokens": 394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.4964036495042199}}
{"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\n// This implements bilinear interpolation on a uniform grid.\n// If dx and dy are both positive, then the (x,y) = (x0, y0) is associated with data index 0 (herein referred to as f[0])\n// The point (x0 + dx, y0) is associated with f[1], and (x0 + i*dx, y0) is associated with f[i],\n// i.e., we are assuming traditional C row major order.\n// The y coordinate increases *downward*, as is traditional in 2D computer graphics.\n// This is *not* how people generally think in numerical analysis (although it *is* how they lay out matrices).\n// Providing the capability of a grid rotation is too expensive and not ergonomic; you'll need to perform any rotations at the call level.\n\n// For clarity, the value f(x0 + i*dx, y0 + j*dy) must be stored in the f[j*cols + i] position.\n\n#ifndef BOOST_MATH_INTERPOLATORS_BILINEAR_UNIFORM_HPP\n#define BOOST_MATH_INTERPOLATORS_BILINEAR_UNIFORM_HPP\n\n#include <utility>\n#include <memory>\n#include <boost/math/interpolators/detail/bilinear_uniform_detail.hpp>\n\nnamespace boost::math::interpolators {\n\ntemplate <class RandomAccessContainer>\nclass bilinear_uniform\n{\npublic:\n    using Real = typename RandomAccessContainer::value_type;\n    using Z = typename RandomAccessContainer::size_type;\n\n    bilinear_uniform(RandomAccessContainer && fieldData, Z rows, Z cols, Real dx = 1, Real dy = 1, Real x0 = 0, Real y0 = 0)\n    : m_imp(std::make_shared<detail::bilinear_uniform_imp<RandomAccessContainer>>(std::move(fieldData), rows, cols, dx, dy, x0, y0))\n    {\n    }\n\n    Real operator()(Real x, Real y) const\n    {\n        return m_imp->operator()(x,y);\n    }\n\n\n    friend std::ostream& operator<<(std::ostream& out, bilinear_uniform<RandomAccessContainer> const & bu) {\n        out << *bu.m_imp;\n        return out;\n    }\n\nprivate:\n    std::shared_ptr<detail::bilinear_uniform_imp<RandomAccessContainer>> m_imp;\n};\n\n}\n#endif\n", "meta": {"hexsha": "555204a875c0a55398a480b5f8f6b0f3b3e4506d", "size": 2074, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/math/interpolators/bilinear_uniform.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/bilinear_uniform.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/bilinear_uniform.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": 37.7090909091, "max_line_length": 138, "alphanum_fraction": 0.7246865959, "num_tokens": 539, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.4964036495042199}}
{"text": "#include <iostream>\n#include <fstream>\n\n#include <vector>\n#include <string>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <Eigen/StdVector>\n\n#include <iomanip>\n\n\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n\n\n\n\n\n\nusing namespace std;\n\n\nint loadPoses(string file_name, vector<Eigen::Matrix4d, Eigen::aligned_allocator<Eigen::Matrix4d> > &poses) {\n    FILE *fp = fopen(file_name.c_str(), \"r\");\n    if (!fp)\n        return  0;\n    while (!feof(fp)) {\n        double P[3] [4];\n        if (fscanf(fp, \"%lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf\",\n                   &P[0][0], &P[0][1], &P[0][2], &P[0][3],\n                   &P[1][0], &P[1][1], &P[1][2], &P[1][3],\n                   &P[2][0], &P[2][1], &P[2][2], &P[2][3] ) == 12) {\n            Eigen::Matrix4d T;\n            T << P[0][0], P[0][1], P[0][2], P[0][3],\n            P[1][0], P[1][1], P[1][2], P[1][3],\n            P[2][0], P[2][1], P[2][2], P[2][3],\n            0, 0, 0, 1;\n            poses.push_back(T);\n        }\n    }\n    fclose(fp);\n    return 1;\n\n}\n\nint loadStampPoses(string file_name, vector<double>& stamps,vector<Eigen::Matrix4d, Eigen::aligned_allocator<Eigen::Matrix4d> > &poses) {\n    FILE *fp = fopen(file_name.c_str(), \"r\");\n    if (!fp)\n        return  0;\n    while (!feof(fp)) {\n        double stamp;\n        double P[3] [4];\n        if(fscanf(fp,\"%lf\",&stamp)==1){\n            stamp/=1000;\n            stamps.push_back(stamp);\n        }\n        if (fscanf(fp, \"%lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf\",\n                   &P[0][0], &P[0][1], &P[0][2], &P[0][3],\n                   &P[1][0], &P[1][1], &P[1][2], &P[1][3],\n                   &P[2][0], &P[2][1], &P[2][2], &P[2][3] ) == 12) {\n            Eigen::Matrix4d T;\n            T << P[0][0], P[0][1], P[0][2], P[0][3],\n            P[1][0], P[1][1], P[1][2], P[1][3],\n            P[2][0], P[2][1], P[2][2], P[2][3],\n            0, 0, 0, 1;\n            poses.push_back(T);\n        }\n    }\n    fclose(fp);\n    return 1;\n\n}\n\n\nint loadNdtPoses(string file_name, vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d> > &pose_xyz,vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d> > &pose_rpy) {\n    FILE *fp = fopen(file_name.c_str(), \"r\");\n    if (!fp)\n        return  0;\n    while (!feof(fp)) {\n        double P[6];\n        if (fscanf(fp, \"%lf %lf %lf %lf %lf %lf\",\n                   &P[0], &P[1], &P[2], &P[3], &P[4], &P[5] ) == 6) {\n            Eigen::Vector3d xyz,rpy;\n            xyz<<P[0],P[1],P[2];\n            rpy<<P[3],P[4],P[5];\n            pose_rpy.push_back(rpy);\n            pose_xyz.push_back(xyz);\n        }\n    }\n    fclose(fp);\n    return 1;\n\n}\n\nvoid loadStamp(string file_name, vector<double>& stamp){\n    FILE *fp = fopen(file_name.c_str(), \"r\");\n    if (!fp){\n        cout<<\"open file fail: \"<<file_name<<endl;\n        return  ;\n    }\n    while (!feof(fp)) {\n        double timestamp;\n        if (fscanf(fp, \"%lf\", &timestamp ) == 1) {\n            stamp.push_back(timestamp);\n        }\n    }\n    fclose(fp);\n    return ;\n}\n\nint main(int argc, char** argv){\n//    vector<Eigen::Matrix4d,Eigen::aligned_allocator<Eigen::Matrix4d> > poses;\n//    loadPoses(\"/home/ywl/ourdata/data060502/cam_gt_pose.txt\",poses);\n//    for(int i=0;i<poses.size();i++){\n//        cout<<i<<endl;\n//        Eigen::Matrix4d p=poses[i].inverse();\n//        cout<<p<<endl;\n//    }\n\n\n#if 1\n    string stampfile=\"/media/ywl/samsungT5/velodyne_points.txt\";\n    string lvinsposefile=\"/home/ywl/ourdata/trajectory/mapping_pose.txt\";\n    string mapposefile=\"/media/ywl/samsungT5/061403/mapping_pose.txt\";\n    string gtfile=\"/home/ywl/ourdata/trajectory/gt_pose.txt\";\n    vector<double> stamp;\n    vector<double> mapstamp;\n    vector<Eigen::Matrix4d,Eigen::aligned_allocator<Eigen::Matrix4d> > lvinspose;\n    vector<Eigen::Matrix4d,Eigen::aligned_allocator<Eigen::Matrix4d> > mappose;\n    loadPoses(lvinsposefile,lvinspose);\n    loadStamp(stampfile,stamp);\n    mapstamp.push_back(stamp[0]);\n    mappose.push_back(lvinspose[0]);\n    loadStampPoses(mapposefile,mapstamp,mappose);\n//    int firstfram=10;\n//    for(int i=1;i<mapstamp.size();i++){\n//        mapstamp[i]+=stamp[firstfram];\n//    }\n//    cout<<fixed<<mapstamp[1]<<\" \"<<mapstamp[mapstamp.size()-1]<<endl;\n\n    int lastindex=0;\n    vector<Eigen::Matrix4d,Eigen::aligned_allocator<Eigen::Matrix4d> > gtpose;\n    //gtpose.push_back(mappose[0]);\n    for(int i=1;i<mapstamp.size();i++){\n        int index=0;\n        while(mapstamp[i]>stamp[index]){\n            index++;\n            if(index==stamp.size())\n                break;\n        }\n        for(int j=lastindex;j<index;j++){\n            Eigen::Matrix4d nowpose;\n            nowpose=mappose[i-1]*lvinspose[lastindex].inverse()*lvinspose[j];\n            gtpose.push_back(nowpose);\n        }\n        lastindex=index;\n    }\n    if(gtpose.size()<lvinspose.size()){\n        for(int i=gtpose.size();i<lvinspose.size();i++){\n            Eigen::Matrix4d nowpose;\n            nowpose=mappose[mappose.size()-1]*lvinspose[gtpose.size()].inverse()*lvinspose[i];\n            gtpose.push_back(nowpose);\n        }\n    }\n    ofstream ofs;\n    ofs.open(gtfile,std::ios::out);\n    for(int i=0;i<gtpose.size();i++){\n        Eigen::Matrix4d pose=gtpose[i];\n        ofs<<fixed<<setprecision(8)<<pose(0,0)<<\" \"<<pose(0,1)<<\" \"<<pose(0,2)<<\" \"<<pose(0,3)<<\" \"<<\n             pose(1,0)<<\" \"<<pose(1,1)<<\" \"<<pose(1,2)<<\" \"<<pose(1,3)<<\" \"<<\n             pose(2,0)<<\" \"<<pose(2,1)<<\" \"<<pose(2,2)<<\" \"<<pose(2,3)<<endl;\n    }\n\n#endif\n\n\n}\n", "meta": {"hexsha": "6639649a1a85f349b41fea3b07aab823608bc7cf", "size": 5515, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "convert/convertOurPose/getgt.cpp", "max_stars_repo_name": "jiexuan/evaluation_tools", "max_stars_repo_head_hexsha": "d8cab5cea2c859ef6067aaedc8cf11be102ad7f8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2019-05-13T10:20:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T03:40:47.000Z", "max_issues_repo_path": "convert/convertOurPose/getgt.cpp", "max_issues_repo_name": "michaelczhou/evaluation_tools", "max_issues_repo_head_hexsha": "1ef3f6d65869990eb35b6e69106a77e0baf2c0b4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "convert/convertOurPose/getgt.cpp", "max_forks_repo_name": "michaelczhou/evaluation_tools", "max_forks_repo_head_hexsha": "1ef3f6d65869990eb35b6e69106a77e0baf2c0b4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-04-24T02:33:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-13T08:33:38.000Z", "avg_line_length": 30.6388888889, "max_line_length": 193, "alphanum_fraction": 0.5211242067, "num_tokens": 1808, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.6477982043529716, "lm_q1q2_score": 0.4964036390832865}}
{"text": "#include \"NNModel.h\"\n#include <math.h>\n#include <stdio.h>\n#include <algorithm>\n#include <iostream>\n#include <stdlib.h>\n#include <string>\n#include \"IonErr.h\"\n#include <hdf5.h>\n\n\n#include <Eigen/Dense>\n\nusing namespace Eigen;\nusing namespace std;\n\n\nNN::NNModel::NNModel(const string &fname){\n\tlayerTypes_ = NULL;\n\tlayerNames_ = NULL;\n\tlayerDimIn_ = NULL;\n\tlayerDimOut_ = NULL;\n\tLoadWeights(fname);\n}\n\nNN::NNModel::~NNModel(){\n\tfor(unsigned int i = 0; i < m_Layers.size(); ++i) {\n\t\tdelete m_Layers[i];\n\t}\n\tdelete [] layerTypes_;\n\tdelete [] layerNames_;\n\tdelete [] layerDimIn_;\n\tdelete [] layerDimOut_;\n}\n\nvector<float> NN::NNModel::CalculateOutput(NN::DataChunk* pred){\n\t//cout << endl << \"Calculating output\" << endl;\n\tNN::DataChunk *input = pred;\n\tNN::DataChunk *output = NULL;\n\tfor(int i = 0; i < (int)m_Layers.size(); ++i){\n\t\t//cout << \"layer\" <<i <<endl;\n\t\toutput = m_Layers[i]->GetOutput(input);\n\t\tif(input != pred)\n\t\t\tdelete input;\n\t\tinput = NULL;\n\t\tinput = output;\n\t}\n\t// last layer\n\tvector<float> flat_out = output->GetData();\n\t// Default Activation - softmax\n\tcout << flat_out[0] <<endl;\n\tfloat sum = 0.0;\n\tfor(unsigned int j = 0; j < flat_out.size(); j++) {\n\t\tif (flat_out[j] < 10)\n\t\t\tflat_out[j] = exp(flat_out[j]);\n\t\telse\n\t\t\tflat_out[j] = exp(10);\n\t\tsum += flat_out[j];\n\t}\n\tfor(unsigned int j = 0; j < flat_out.size(); ++j) {\n\t\tflat_out[j] /= sum;\n\t}\n\tdelete output;\n\treturn flat_out;\n}\n\nvoid NN::NNModel::LoadWeights(const string &fname) {\n\tLayer *l = NULL;\n\n\tif(H5Fis_hdf5(fname.c_str()) > 0)\n\t{\n\t\tcout << endl << \"NNModel::Init... load model from \" << fname.c_str() << endl;\n\t\thid_t root = H5Fopen(fname.c_str(), H5F_ACC_RDONLY, H5P_DEFAULT);  // open file\n\t\tif(root < 0)\n\t\t{\n\t\t\tION_ABORT(\"ERROR: cannot open HDF5 file \" + fname);\n\t\t}\n\t\thid_t NNarch = H5Gopen(root, \"/arch\", H5P_DEFAULT);   //open group\n\t\tif (NNarch < 0)\n\t\t{\n\t\t\tH5Fclose(root);\n\t\t\tION_ABORT(\"ERROR: fail to open HDF5 group arch\");\n\t\t}\n\t\thid_t dstypes = H5Dopen(NNarch, \"types\", H5P_DEFAULT);  // open layer types\n\t\tif (dstypes < 0)\n\t\t{\n\t\t\tH5Gclose(NNarch);\n\t\t\tH5Fclose(root);\n\t\t\tION_ABORT(\"ERROR: fail to open HDF5 dataset types\");\n\t\t}\n\t\thsize_t dSize = H5Dget_storage_size(dstypes);\n\t\tdSize /= sizeof(H5T_NATIVE_UINT);\n\t\tlayerTypes_ = new unsigned int[dSize];\n\t\therr_t ret = H5Dread(dstypes, H5T_NATIVE_UINT, H5S_ALL, H5S_ALL, H5P_DEFAULT, layerTypes_);\n\t\tif (ret < 0)\n\t\t{\n\t\t\tdelete [] layerTypes_;\n\t\t\tlayerTypes_ = 0;\n\t\t\tION_ABORT(\"ERROR: fail to read HDF5 dataset types\");\n\t\t}\n\t\tH5Dclose(dstypes);\n\t\thid_t dsnames = H5Dopen(NNarch, \"names\", H5P_DEFAULT);  // open layer names\n\t\tif (dsnames < 0)\n\t\t{\n\t\t\tH5Gclose(NNarch);\n\t\t\tH5Fclose(root);\n\t\t\tION_ABORT(\"ERROR: fail to open HDF5 dataset names\");\n\t\t}\n\t\tlayerNames_ = new unsigned int[dSize];\n\t\tret = H5Dread(dsnames, H5T_NATIVE_UINT, H5S_ALL, H5S_ALL, H5P_DEFAULT, layerNames_);\n\t\tif (ret < 0)\n\t\t{\n\t\t\tdelete [] layerNames_;\n\t\t\tlayerNames_ = 0;\n\t\t\tION_ABORT(\"ERROR: fail to read HDF5 dataset names\");\n\t\t}\n\t\tH5Dclose(dsnames);\n\t\thid_t dsdimin = H5Dopen(NNarch, \"dimin\", H5P_DEFAULT);  // open layer input dimension\n\t\tif (dsdimin < 0)\n\t\t{\n\t\t\tH5Gclose(NNarch);\n\t\t\tH5Fclose(root);\n\t\t\tION_ABORT(\"ERROR: fail to open HDF5 dataset dimin\");\n\t\t}\n\t\tlayerDimIn_ = new unsigned int[dSize];\n\t\tret = H5Dread(dsdimin, H5T_NATIVE_UINT, H5S_ALL, H5S_ALL, H5P_DEFAULT, layerDimIn_);\n\t\tif (ret < 0)\n\t\t{\n\t\t\tdelete [] layerDimIn_;\n\t\t\tlayerDimIn_ = 0;\n\t\t\tION_ABORT(\"ERROR: fail to read HDF5 dataset dimin\");\n\t\t}\n\t\tH5Dclose(dsdimin);\n\t\thid_t dsdimout = H5Dopen(NNarch, \"dimout\", H5P_DEFAULT);  // open layer input dimension\n\t\tif (dsdimout < 0)\n\t\t{\n\t\t\tH5Gclose(NNarch);\n\t\t\tH5Fclose(root);\n\t\t\tION_ABORT(\"ERROR: fail to open HDF5 dataset dimout\");\n\t\t}\n\t\tlayerDimOut_ = new unsigned int[dSize];\n\t\tret = H5Dread(dsdimout, H5T_NATIVE_UINT, H5S_ALL, H5S_ALL, H5P_DEFAULT, layerDimOut_);\n\t\tif (ret < 0)\n\t\t{\n\t\t\tdelete [] layerDimOut_;\n\t\t\tlayerDimOut_ = 0;\n\t\t\tION_ABORT(\"ERROR: fail to read HDF5 dataset dimout\");\n\t\t}\n\t\tH5Dclose(dsdimout);\n\t\tH5Gclose(NNarch);\n\t\t// load weight\n\t\thid_t NNweight = H5Gopen(root, \"/weight\", H5P_DEFAULT);   //open group weight\n\t\tif (NNweight < 0)\n\t\t{\n\t\t\tH5Fclose(root);\n\t\t\tION_ABORT(\"ERROR: fail to open HDF5 group weight\");\n\t\t}\n\t\tH5Gclose(NNweight);\n\t\tH5Fclose(root);\n\n\t\tfor(unsigned int i = 0; i < dSize; i++){\n\t\t\tcout<< \"Reading layer: \"<< i<< endl;\n\t\t\tif((int)layerTypes_[i] == 1){  // \"Dense layer\"\n\t\t\t\tvector<int> dims(2); // support only two dimensions for now\n\t\t\t\tdims.at(0) = layerDimIn_[i];\n\t\t\t\tdims.at(1) = layerDimOut_[i];\n\t\t\t\tl = new DenseLayer();\n\t\t\t\tl->SetName((int)layerNames_[i]);\n\t\t\t\tl->SetDim(dims);\n\t\t\t\tl->LoadWeights(fname);\n\t\t\t}else if((int)layerTypes_[i] == 2) { // \"Dropout layer\"\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tm_Layers.push_back(l);\n\t\t}\n\t}else{\n\t\tION_ABORT(\"ERROR: The file is not an HDF5 file \" + fname);\n\t}\n}\n\n\nvoid NN::DenseLayer::LoadWeights(const string &fname){\n\thid_t root = H5Fopen(fname.c_str(), H5F_ACC_RDONLY, H5P_DEFAULT);  // open file\n\thid_t NNweight = H5Gopen(root, \"/weight\", H5P_DEFAULT);   //open group weight\n\tif (NNweight < 0)\n\t{\n\t\tH5Fclose(root);\n\t\tION_ABORT(\"ERROR: fail to open HDF5 group weight\");\n\t}\n\tchar buf[100];\n\tsprintf(buf, \"weight%d\", mName);\n\thid_t dsweight = H5Dopen(NNweight, buf, H5P_DEFAULT);  // open weight dataset\n\tif (dsweight < 0)\n\t{\n\t\tH5Gclose(NNweight);\n\t\tH5Fclose(root);\n\t\tION_ABORT(\"ERROR: fail to open HDF5 dataset weight\");\n\t}\n\thid_t filespace = H5Dget_space(dsweight);\n\tint dimension = H5Sget_simple_extent_ndims(filespace);\n\thsize_t dim[dimension];\n\tint status = H5Sget_simple_extent_dims ( filespace, dim, NULL );\n\tif ( status <0 )\n\t{\n\t\tH5Sclose ( filespace );\n\t    ION_ABORT ( \"Internal Error in H5Sget_simple_extent_dims - Read Weight\" );\n\t}\n\thsize_t size = H5Dget_storage_size(dsweight);\n\tsize /= sizeof(float);\n\tcout << \"Layer weight: \"<<(int)dim[0]<< \" * \" << (int)dim[1] <<endl;\n\tfloat* weight = new float[size];\n\therr_t ret = H5Dread(dsweight, H5T_NATIVE_FLOAT, H5S_ALL, H5S_ALL, H5P_DEFAULT, weight);\n\tH5Dclose(dsweight);\n\tif(ret < 0)\n\t{\n\t\tH5Gclose(NNweight);\n\t\tH5Fclose(root);\n\t\tION_ABORT(\"ERROR: fail to read HDF5 attribute weight\");\n\t}\n\tfor(unsigned int i = 0; i < dim[0]; i++){\n\t\tvector<float> v(size/dim[0]);\n\t\tcopy(weight + i * size/dim[0], weight + (i + 1) * size/dim[0], v.begin());\n\t\tmWeights.push_back(v);\n\t}\n\tdelete [] weight;\n \t// Load bias\n\tchar buf1[100];\n\tsprintf(buf1, \"bias%d\", mName);\n\thid_t dsbias = H5Dopen(NNweight, buf1, H5P_DEFAULT);  // open weight dataset\n\tif (dsbias < 0)\n\t{\n\t\tH5Gclose(NNweight);\n\t\tH5Fclose(root);\n\t\tION_ABORT(\"ERROR: fail to open HDF5 dataset bias\");\n\t}\n\tfilespace = H5Dget_space(dsbias);\n\tdimension = H5Sget_simple_extent_ndims(filespace);\n\tsize = H5Dget_storage_size(dsbias);\n\tsize /= sizeof(float);\n\tfloat* bias = new float[size];\n\tret = H5Dread(dsbias, H5T_NATIVE_FLOAT, H5S_ALL, H5S_ALL, H5P_DEFAULT, bias);\n\tH5Dclose(dsbias);\n\tmBias.resize(dim[1]);\n\tcopy(bias , bias + dim[1], mBias.begin());\n\tdelete [] bias;\n}\n\nNN::DataChunk* NN::DenseLayer::GetOutput(NN::DataChunk* pred){\n\tsize_t size = mWeights[0].size();\n\tsize_t size8 = size >> 3;\n\tNN::DataChunk *output = new NN::DataChunk(size, 0);\n\tfloat * x = pred->GetSetData().data();\n\tfloat * y = output->GetSetData().data();\n\tfor(unsigned int i = 0; i < mWeights.size(); ++i){\n\t\tconst float * w = mWeights[i].data();\n\t\tsize_t k = 0;\n\t\tfor(unsigned int j = 0; j < size8; ++j){\n\t\t\ty[k] += w[k] * x[i];\n\t\t\ty[k + 1] += w[k + 1] * x[i];\n\t\t\ty[k + 2] += w[k + 2] * x[i];\n\t\t\ty[k + 3] += w[k + 3] * x[i];\n\t\t\ty[k + 4] += w[k + 4] * x[i];\n\t\t\ty[k + 5] += w[k + 5] * x[i];\n\t\t\ty[k + 6] += w[k + 6] * x[i];\n\t\t\ty[k + 7] += w[k + 7] * x[i];\n\t\t\tk += 8;\n\t\t}\n\t\twhile (k < size) { y[k] += w[k] * x[i]; ++k; }  // leftovers\n\t}\n\n\tfor (unsigned int i = 0; i < size; ++i) {\n\t    y[i] += mBias[i];\n\t}\n\treturn output;\n}\n\nvoid NN::DenseLayer::SetDim(const vector<int> dims){\n\tmDim1 = dims.at(0);\n\tmDim2 = dims.at(1);\n}\n\nvoid NN::DenseLayer::SetName(int layerName){\n\tmName = layerName;\n}\n\n\n", "meta": {"hexsha": "238637163a45454e33bada8dff267f89381b1df9", "size": 7862, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Analysis/BaseCaller/NNModel.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/BaseCaller/NNModel.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/BaseCaller/NNModel.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": 27.393728223, "max_line_length": 93, "alphanum_fraction": 0.6418214195, "num_tokens": 2730, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517044, "lm_q2_score": 0.5813030906443134, "lm_q1q2_score": 0.4963821224314198}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n//\n// ParVoro++: A scalable parallel algorithm for constructing 3D Voronoi tessellations based on KD-tree decomposition\n//\n// Guoqing Wu\n// High Performance Computing Center, Institute of Applied Physics and Computational Mathematics, Beijing\n// wu_guoqing@iapcm.ac.cn\n//\n///////////////////////////////////////////////////////////////////////////////\n#ifndef __VORONOI_KD_H\n#define __VORONOI_KD_H\n\n#include \"StandardIncludes.h\"\n#include \"data/particle.hpp\"\n#include \"data/common.hpp\"\n#include <voro++/voro++.hh>\n#include <itree/avtIntervalTree.h>\n\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/convex_hull_3.h>\n#include <CGAL/Extreme_points_traits_adapter_3.h>\n\n#include <boost/iterator/counting_iterator.hpp>\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel       K;\n\ntemplate<typename RealType, unsigned NDIM>\nvoid \nconvex_hull(ParticleBlock<RealType, NDIM>* b_,\n            const diy::Master::ProxyWithLink& cp,\n\t    std::vector<std::set<size_t> >& ch_indices)\n{\n    typedef  diy::ContinuousBounds            Bounds;\n    typedef  ParticleBlock<RealType, NDIM>    Block;\n    typedef  diy::RegularContinuousLink       RCLink;\n\n    Block*  b  = static_cast<Block*>(b_);\n    RCLink* l  = dynamic_cast<RCLink*>(cp.link());\n    int index = b->lid;\n  \n    std::vector<K::Point_3> points;\n    for(size_t i = 0; i <  b->num_orig_particles; i++)\n    {\n        K::Point_3 p( b->particles[i][0],  b->particles[i][1],  b->particles[i][2]);\n        points.push_back(p);\n    }\n\n    //This will contain the extreme vertices\n    std::vector<size_t> extreme_point_indices;\n    //call the function with the traits adapter for vertices\n    CGAL::extreme_points_3(CGAL::make_range(boost::counting_iterator<size_t>(0),\n                                          boost::counting_iterator<size_t>(points.size())),\n                           std::back_inserter(extreme_point_indices),\n                           CGAL::make_extreme_points_traits_adapter(CGAL::make_property_map(points)));\n                                                         \n    std::copy(extreme_point_indices.begin(), extreme_point_indices.end(), std::inserter(ch_indices[index], ch_indices[index].begin()));\n    for(int i=0; i<l->size(); i++)\n    {        \n        for(std::set<size_t>::iterator it=ch_indices[index].begin(); it!=ch_indices[index].end(); ++it)\n        {\n            // send convex hull vertex to nearest block\n            RemoteParticle<RealType, NDIM> rp;\n            rp.particle[0] = (RealType)(b->particles[*it][0]);\n            rp.particle[1] = (RealType)(b->particles[*it][1]);\n            rp.particle[2] = (RealType)(b->particles[*it][2]);\n            rp.info.bid = b->bid;\n            rp.info.index = *it;\n            cp.enqueue(l->target(i), rp);    \n        }\n    }\n\n}\n\ntemplate<typename RealType, unsigned NDIM>\nint \nincomplete_cells(ParticleBlock<RealType, NDIM>* b,\n                 const diy::Master::ProxyWithLink& cp,\n\t         bool wrap,\n                 voro::container* con[],\n                 voro::particle_order* po[],\n\t         avtIntervalTree* itree_spatial,\n\t         diy::StaticAssigner& assigner,\n                 std::vector<std::set<size_t> >& ch_indices)\n{\n    typedef diy::RegularContinuousLink  RCLink;\n    RCLink* l = dynamic_cast<RCLink*>(cp.link());\n\n    std::vector<std::set<int> > to_send( b->num_orig_particles);\n\n    std::set<int> neighbors;\n    for(int i = 0; i < l->size(); i++)\n        neighbors.insert(l->target(i).gid);\n\n    int index = b->lid;\n    int pid;\n    voro::voronoicell c;\n    double x, y, z, r;\n    double center[3];\n    RemoteParticle<float, NDIM> rp;\n    voro::c_loop_order clo(*con[index],*po[index]);\n    if(clo.start()) do if((con[index]->compute_cell(c, clo)))\n    {\n        clo.pos(pid, x, y, z, r);\n\n        center[0] = x;\n        center[1] = y;\n        center[2] = z;\n\n        std::vector<double> v;\n        c.vertices(x,y,z,v);\n        for(int vi = 0; vi < c.p; vi++)\n        {\n            double verts[3];\n            verts[0] = v[3*vi];\n            verts[1] = v[3*vi+1];\n            verts[2] = v[3*vi+2];\n            double rad = distance(center, verts) + EPSILON;\n\n            // check if the circumsphere is too deep inside the block to be able to stick out\n\t    int j;\n            for(j = 0; j < 3; ++j)\n            {\n                if(verts[j] - b->bounds.min[j] <= rad) break;\n                if(b->bounds.max[j] - verts[j] <= rad) break;\n            }\n            if(j == 3)\t// the circumsphere is too deep inside the block\n                continue;\n\n\t    // computing bounding box of the circumsphere\n    \t    double min_vec[3], max_vec[3];\n            for(int i = 0; i < 3; i++)\n            {\n\t        min_vec[i] = verts[i] - rad;\n\t        max_vec[i] = verts[i] + rad;\n            }\n\n\t    // no wrap, NB: wrap case includes no wrap\n\t    {\n                std::vector<int> list;\n                itree_spatial->GetElementsListFromRange(min_vec, max_vec, list); //\u57fa\u4e8e\u533a\u95f4\u6811\u67e5\u627e\u76f8\u4ea4box\n                for(int i = 0; i < list.size(); ++i)\n                {\n\t\t    if(list[i] != b->bid.gid) // do not send to itself\n\t\t        to_send[pid].insert(list[i]);\n\t        }\n\t    }\n\n    \t    if(wrap)\n\t    { \n                std::vector<int> wrap_dir(3,0);\n\t\tint flag[3] = {0, 0, 0};\n\t  \tif(min_vec[0] <= b->global_bounds.min[0]) // -X\n\t\t{\n\t\t    wrap_dir[0] = 1;\n\t\t    flag[0]++;\n\t\t}\n\t  \tif(min_vec[1] <= b->global_bounds.min[1]) // -Y\n\t\t{\n\t\t    wrap_dir[1] = 1;\n\t\t    flag[1]++;\n\t\t}\n\t  \tif(min_vec[2] <= b->global_bounds.min[2]) // -Z\n\t\t{\n\t\t    wrap_dir[2] = 1;\n\t\t    flag[2]++;\n\t\t}\n\t  \tif(max_vec[0] >= b->global_bounds.max[0]) // +X\n\t\t{\n\t\t    wrap_dir[0] = -1;\n\t\t    flag[0]++;\n\t\t}\n\t  \tif(max_vec[1] >= b->global_bounds.max[1]) // +Y\n\t\t{\n\t\t    wrap_dir[1] = -1;\n\t\t    flag[1]++;\n\t\t}\n\t  \tif(max_vec[2] >= b->global_bounds.max[2]) // +Z\n\t\t{\n\t\t    wrap_dir[2] = -1;\t\t\n\t\t    flag[2]++;\n\t\t}\t\n\n                // handle the weird case, where the box intersects both sides\n\t        wrap_dir[0] = (flag[0]>1) ? 0 : wrap_dir[0];\n\t\twrap_dir[1] = (flag[1]>1) ? 0 : wrap_dir[1];\n\t\twrap_dir[2] = (flag[2]>1) ? 0 : wrap_dir[2];\n\n\t\tfor(int x = 0; x < 2; x++)\n\t\t    for(int y = 0; y < 2; y++)\n\t\t        for(int z = 0; z < 2; z++)\n\t\t\t{\n\t\t\t    if(x==0 && y==0 && z==0) // no wrap case\n\t\t\t\tcontinue;\n\n\t\t\t    std::vector<int> dir(3,0);\n\t\t\t    dir[0] = x * wrap_dir[0];\n\t\t\t    dir[1] = y * wrap_dir[1];\n\t\t\t    dir[2] = z * wrap_dir[2];\n\t\t\n    \t    \t\t    double min_[3], max_[3];\n            \t\t    for(int i = 0; i < 3; i++)\n            \t\t    {\n\t                        min_[i] = min_vec[i];\n\t                        max_[i] = max_vec[i];\n                            }\n\t\t\t    for(int i = 0; i < 3; ++i)\n                            {\n                                min_[i] += dir[i] * (b->global_bounds.max[i] - b->global_bounds.min[i]);\n                                max_[i] += dir[i] * (b->global_bounds.max[i] - b->global_bounds.min[i]);\n                            }\n                \t    std::vector<int> list;\n                            itree_spatial->GetElementsListFromRange(min_, max_, list); //\u57fa\u4e8e\u533a\u95f4\u6811\u67e5\u627e\u76f8\u4ea4box\n                            for(int i = 0; i < list.size(); ++i)\n                            {\n\t\t                if(list[i] != b->bid.gid) // do not send to itself\n\t\t                to_send[pid].insert(list[i]);\n\t                    }\n\t\t\t}\n\t    }//if(wrap)\t\n        }//for vi\n    }while(clo.inc());\n\n    // enqueue the particles\n    size_t enqueued = 0;\n    for(int p = 0; p <  b->num_orig_particles; p++)\n    {\n        for(std::set<int>::iterator it  = to_send[p].begin(); it != to_send[p].end(); it++)\n        {\n\t    if(ch_indices[b->lid].count(p) && neighbors.count(*it)) // already send as convex hull particle\n\t        continue;\t\t\n         \n            rp.particle =  b->particles[p];\n            rp.info.bid = b->bid;\n            rp.info.index = p;\n            diy::BlockID bid(*it, assigner.rank(*it));\n            cp.enqueue(bid, rp);\n            ++enqueued;\n        }\n    }\n\n    return enqueued;\n}\n\ntemplate<typename RealType, unsigned NDIM>\nvoid \nlocal_cells(ParticleBlock<RealType, NDIM>* b,\n            const diy::Master::ProxyWithLink& cp,\n            bool wrap,\n            voro::container* con[],\n            voro::particle_order* po[])\n{\n    int index = b->lid;\n    int nx,ny,nz;\n    voro::pre_container pcon(b->global_bounds.min[0], b->global_bounds.max[0], b->global_bounds.min[1], b->global_bounds.max[1], b->global_bounds.min[2], b->global_bounds.max[2], wrap, wrap, wrap); \n    for(int j = 0; j < b->num_orig_particles; j++)\n        pcon.put(j,  b->particles[j][0],  b->particles[j][1],  b->particles[j][2]);\n    pcon.guess_optimal(nx,ny,nz);\n    con[index] = new voro::container(b->global_bounds.min[0], b->global_bounds.max[0], b->global_bounds.min[1], b->global_bounds.max[1], b->global_bounds.min[2], b->global_bounds.max[2], 2*nx, 2*ny, 2*nz, wrap, wrap, wrap, 8);\n    po[index] = new voro::particle_order();\n    pcon.setup(*po[index], *con[index]);\n    \n    for(int j = b->num_orig_particles; j < b->num_particles; j++)\n        con[index]->put(j, b->particles[j][0], b->particles[j][1], b->particles[j][2]);\n}\n\ntemplate<typename RealType, unsigned NDIM>\nvoid \nupdate_cells(ParticleBlock<RealType, NDIM>* b,\n             const diy::Master::ProxyWithLink& cp,\n             bool wrap,\n             voro::container* con[],\n             voro::particle_order* po[],\n             bool test)\n{\n    int index = b->lid;\n    for(int j = con[index]->total_particles(); j < b->num_particles; j++)\n        con[index]->put(j, b->particles[j][0], b->particles[j][1], b->particles[j][2]);\n\n    // Add a wall to the container\n    //voro::wall_cylinder wall(15,15,15,0,0,1,10);\n    //voro::wall_sphere wall(15, 15, 15, 5);\n    //con[index]->add_wall(wall);\n\n    if(test) \n        con[index]->compute_all_cells();\n}\n\ntemplate<typename RealType, unsigned NDIM>\nvoid \nVoronoi_kd(diy::Master& master,                               \n           bool wrap,\n           voro::container* con[],\n           voro::particle_order* po[],\n\t   avtIntervalTree* itree_spatial,\n\t   diy::StaticAssigner& assigner,\n           bool test)\n{\n    std::vector<std::set<size_t> > ch_indices(master.size()); // NB: multi-blocks\n    master.foreach([&](ParticleBlock<RealType, NDIM>* b, const diy::Master::ProxyWithLink & cp)\n                  {convex_hull<RealType, NDIM>(b, cp, ch_indices);});\n    master.exchange();\n    master.foreach(&recv_particles<RealType, NDIM>);\n\n    master.foreach([&](ParticleBlock<RealType, NDIM>* b, const diy::Master::ProxyWithLink & cp)\n                  {local_cells<RealType, NDIM>(b, cp, wrap, con, po);});\n\n    master.foreach([&](ParticleBlock<RealType, NDIM>* b, const diy::Master::ProxyWithLink & cp)\n                  {incomplete_cells<RealType, NDIM>(b, cp, wrap, con, po, itree_spatial, assigner, ch_indices);});\n    bool remote = true;  // NB: (remote) exchange some data outside the links \n    master.exchange(remote);\n    master.foreach(&recv_particles<RealType, NDIM>);\n\n    master.foreach([&](ParticleBlock<RealType, NDIM>* b, const diy::Master::ProxyWithLink & cp)\n                  {update_cells<RealType, NDIM>(b, cp, wrap, con, po, test);});\n}\n\n#endif\n\n\n\n\n\n\n", "meta": {"hexsha": "1382a4f457da1b0b1eb1c5007f438f9a1387eda6", "size": 11234, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/analysis/voronoi/VoronoiKD.hpp", "max_stars_repo_name": "wgq-iapcm/Parvoro-", "max_stars_repo_head_hexsha": "9459e1081ff948628358c59207d5fcd8ce60ef8f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/analysis/voronoi/VoronoiKD.hpp", "max_issues_repo_name": "wgq-iapcm/Parvoro-", "max_issues_repo_head_hexsha": "9459e1081ff948628358c59207d5fcd8ce60ef8f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/analysis/voronoi/VoronoiKD.hpp", "max_forks_repo_name": "wgq-iapcm/Parvoro-", "max_forks_repo_head_hexsha": "9459e1081ff948628358c59207d5fcd8ce60ef8f", "max_forks_repo_licenses": ["BSD-3-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.6728395062, "max_line_length": 226, "alphanum_fraction": 0.5362293039, "num_tokens": 3135, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264639, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.49636036979495957}}
{"text": "// The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt\n/*\n\n    This is an example illustrating the use of the extract_fhog_features() routine from\n    the dlib C++ Library.\n\n    \n    The extract_fhog_features() routine performs the style of HOG feature extraction\n    described in the paper:\n        Object Detection with Discriminatively Trained Part Based Models by\n        P. Felzenszwalb, R. Girshick, D. McAllester, D. Ramanan\n        IEEE Transactions on Pattern Analysis and Machine Intelligence, Vol. 32, No. 9, Sep. 2010\n    This means that it takes an input image and outputs Felzenszwalb's\n    31 dimensional version of HOG features.  We show its use below.\n*/\n\n\n\n#include <dlib/gui_widgets.h>\n#include <dlib/image_io.h>\n#include <dlib/image_transforms.h>\n\n\nusing namespace std;\nusing namespace dlib;\n\n//  ----------------------------------------------------------------------------\n\n\n\n#if defined(BUILD_MONOLITHIC)\n#define main(cnt, arr)      dlib_fhog_ex_main(cnt, arr)\n#endif\n\nint main(int argc, const char** argv)\n{\n    try\n    {\n        // Make sure the user entered an argument to this program.  It should be the\n        // filename for an image.\n        if (argc != 2)\n        {\n            cout << \"error, you have to enter a BMP file as an argument to this program\" << endl;\n            return 1;\n        }\n\n        // Here we declare an image object that can store color rgb_pixels.    \n        array2d<rgb_pixel> img;\n\n        // Now load the image file into our image.  If something is wrong then\n        // load_image() will throw an exception.  Also, if you linked with libpng\n        // and libjpeg then load_image() can load PNG and JPEG files in addition\n        // to BMP files.\n        load_image(img, argv[1]);\n\n\n        // Now convert the image into a FHOG feature image.  The output, hog, is a 2D array\n        // of 31 dimensional vectors.\n        array2d<matrix<float,31,1> > hog;\n        extract_fhog_features(img, hog);\n\n        cout << \"hog image has \" << hog.nr() << \" rows and \" << hog.nc() << \" columns.\" << endl;\n\n        // Let's see what the image and FHOG features look like.\n        image_window win(img);\n        image_window winhog(draw_fhog(hog));\n\n        // Another thing you might want to do is map between the pixels in img and the\n        // cells in the hog image.  dlib provides the image_to_fhog() and fhog_to_image()\n        // routines for this.  Their use is demonstrated in the following loop which\n        // responds to the user clicking on pixels in the image img.\n        point p;  // A 2D point, used to represent pixel locations.\n        while (win.get_next_double_click(p))\n        {\n            point hp = image_to_fhog(p);\n            cout << \"The point \" << p << \" in the input image corresponds to \" << hp << \" in hog space.\" << endl;\n            cout << \"FHOG features at this point: \" << trans(hog[hp.y()][hp.x()]) << endl;\n        }\n\n        // Finally, sometimes you want to get a planar representation of the HOG features\n        // rather than the explicit vector (i.e. interlaced) representation used above.  \n        dlib::array<array2d<float> > planar_hog;\n        extract_fhog_features(img, planar_hog);\n        // Now we have an array of 31 float valued image planes, each representing one of\n        // the dimensions of the HOG feature vector.  \n    }\n    catch (exception& e)\n    {\n        cout << \"exception thrown: \" << e.what() << endl;\n    }\n}\n\n//  ----------------------------------------------------------------------------\n\n", "meta": {"hexsha": "865707784858d683f68c3a7b4bff06e4a9aabf5d", "size": 3554, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/fhog_ex.cpp", "max_stars_repo_name": "GerHobbelt/dlib", "max_stars_repo_head_hexsha": "d26e917abc626fb81f0b57ecf1f3be555bddf8de", "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/fhog_ex.cpp", "max_issues_repo_name": "GerHobbelt/dlib", "max_issues_repo_head_hexsha": "d26e917abc626fb81f0b57ecf1f3be555bddf8de", "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/fhog_ex.cpp", "max_forks_repo_name": "GerHobbelt/dlib", "max_forks_repo_head_hexsha": "d26e917abc626fb81f0b57ecf1f3be555bddf8de", "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.4105263158, "max_line_length": 113, "alphanum_fraction": 0.6091727631, "num_tokens": 845, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.49627554965388193}}
{"text": "//==================================================================================================\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#include <boost/simd/function/ifrexp.hpp>\n#include <boost/simd/function/pedantic.hpp>\n#include <boost/simd/detail/constant/minexponent.hpp>\n#include <boost/simd/constant/halfeps.hpp>\n#include <boost/simd/constant/valmax.hpp>\n#include <boost/simd/pack.hpp>\n#include <utility>\n\n#include <simd_test.hpp>\n\nnamespace bs = boost::simd;\nnamespace bd = boost::dispatch;\n\ntemplate <typename T, std::size_t N, typename Env>\nvoid test(Env& $)\n{\n  using iT   = bd::as_integer_t<T>;\n  using p_iT = bs::pack<iT, N>;\n  using p_T  = bs::pack< T, N>;\n\n  T a1[N], m[N];\n  iT e[N];\n\n  for(std::size_t i = 0; i < N; ++i)\n  {\n    a1[i] = (i%2) ? T(1+i) : -T(1+i);\n    std::tie(m[i], e[i])   = bs::pedantic_(bs::ifrexp)(a1[i]);\n  }\n\n  p_T  in(&a1[0], &a1[0]+N);\n  p_T  mm( &m[0],  &m[0]+N);\n  p_iT ee( &e[0],  &e[0]+N);\n\n  auto that = bs::pedantic_(bs::ifrexp)(in);\n\n  STF_EQUAL(that.first, mm);\n  STF_EQUAL(that.second, ee);\n}\n\nSTF_CASE_TPL(\"Check basic behavior of pedantic(ifrexp) on pack\" , STF_IEEE_TYPES)\n{\n  static const std::size_t N = bs::pack<T>::static_size;\n  test<T, N>($);\n  test<T, N/2>($);\n  test<T, N*2>($);\n}\n\nSTF_CASE_TPL(\"Check behavior of pedantic_(ifrexp) on Zero\", STF_IEEE_TYPES)\n{\n  using iT = bd::as_integer_t<T>;\n  auto r = bs::pedantic_(bs::ifrexp)(bs::pack<T>(0));\n\n  STF_EQUAL (r.first , bs::pack< T>(0));\n  STF_EQUAL (r.second, bs::pack<iT>(0));\n}\n\nSTF_CASE_TPL(\"Check behavior of pedantic_(ifrexp) on Valmax\", STF_IEEE_TYPES)\n{\n  auto r = bs::pedantic_(bs::ifrexp)(bs::Valmax<bs::pack<T>>());\n\n  STF_ULP_EQUAL (r.first , 1-bs::Halfeps<bs::pack<T>>(), 1);\n  STF_EQUAL (r.second, bs::Limitexponent<bs::pack<T>>());\n}\n\n#ifndef BOOST_SIMD_NO_INVALID\n#include <boost/simd/constant/nan.hpp>\nSTF_CASE_TPL(\"Check behavior of pedantic_(ifrexp) on NaN\", STF_IEEE_TYPES)\n{\n  using iT = bd::as_integer_t<T>;\n  auto r = bs::pedantic_(bs::ifrexp)(bs::Nan<bs::pack<T>>());\n\n  STF_IEEE_EQUAL(r.first , bs::Nan<bs::pack<T>>());\n  STF_EQUAL     (r.second, bs::pack<iT>(0));\n}\n#endif\n\n#ifndef BOOST_SIMD_NO_INFINITIES\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/minf.hpp>\n\nSTF_CASE_TPL(\"Check behavior of pedantic_(ifrexp) on infinites\", STF_IEEE_TYPES)\n{\n  using iT = bd::as_integer_t<T>;\n  auto r = bs::pedantic_(bs::ifrexp)(bs::Inf<bs::pack<T>>());\n  auto q = bs::pedantic_(bs::ifrexp)(bs::Minf<bs::pack<T>>());\n\n  STF_IEEE_EQUAL(r.first , bs::Inf<bs::pack<T>>());\n  STF_EQUAL     (r.second, bs::pack<iT>(0));\n\n  STF_IEEE_EQUAL(q.first , bs::Minf<bs::pack<T>>());\n  STF_EQUAL     (q.second, bs::pack<iT>(0));\n}\n\n#endif\n\n#ifndef BOOST_SIMD_NO_DENORMALS\n#include <boost/simd/detail/constant/minexponent.hpp>\n#include <boost/simd/constant/mindenormal.hpp>\n\nSTF_CASE_TPL(\"Check behavior of pedantic_(ifrexp) on denormals\", STF_IEEE_TYPES)\n{\n  auto r = bs::pedantic_(bs::ifrexp)(bs::Mindenormal<bs::pack<T>>());\n\n  STF_ULP_EQUAL(r.first , bs::pack<T>(0.5), 1);\n  STF_EQUAL     (r.second, bs::Minexponent<bs::pack<T>>()-bs::Nbmantissabits<bs::pack<T>>()+1);\n}\n\n#endif\n", "meta": {"hexsha": "6d1aa86647bf9bd549879c0d8bbfe9320f5d92fc", "size": 3364, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/simd/ifrexp.pedantic.cpp", "max_stars_repo_name": "nickporubsky/boost-simd-clone", "max_stars_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_stars_repo_licenses": ["BSL-1.0"], "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": "test/function/simd/ifrexp.pedantic.cpp", "max_issues_repo_name": "nickporubsky/boost-simd-clone", "max_issues_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "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/function/simd/ifrexp.pedantic.cpp", "max_forks_repo_name": "nickporubsky/boost-simd-clone", "max_forks_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_forks_repo_licenses": ["BSL-1.0"], "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": 28.7521367521, "max_line_length": 100, "alphanum_fraction": 0.6197978597, "num_tokens": 1119, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145998, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.4962755466100768}}
{"text": "/**\n * \\copyright\n * Copyright (c) 2012-2018, 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/LICENSE.txt\n */\n\n#include <gtest/gtest.h>\n\n#include <limits>\n#include <algorithm>\n#include <vector>\n#include <cmath>\n#include <memory>\n\n#include <Eigen/Eigen>\n\n#include \"GeoLib/AnalyticalGeometry.h\"\n#include \"MathLib/LinAlg/Dense/DenseMatrix.h\"\n\n#include \"MeshLib/CoordinateSystem.h\"\n#include \"MeshLib/Node.h\"\n#include \"MeshLib/Elements/Element.h\"\n#include \"MeshLib/Elements/Line.h\"\n#include \"MeshLib/Elements/Quad.h\"\n#include \"MeshLib/ElementCoordinatesMappingLocal.h\"\n\n#include \"Tests/TestTools.h\"\n\n\nnamespace\n{\n\nnamespace TestLine2\n{\nusing ElementType = MeshLib::Line;\nconst unsigned e_nnodes = ElementType::n_all_nodes;\n\nstd::unique_ptr<MeshLib::Line> createLine(std::array<double, 3> const& a,\n                                          std::array<double, 3> const& b)\n{\n    auto** nodes = new MeshLib::Node*[e_nnodes];\n    nodes[0] = new MeshLib::Node(a);\n    nodes[1] = new MeshLib::Node(b);\n    return std::make_unique<MeshLib::Line>(nodes);\n    }\n\n    std::unique_ptr<MeshLib::Line> createY()\n    {\n        return createLine({{0.0, -1.0, 0.0}}, {{0.0,  1.0, 0.0}});\n    }\n\n    std::unique_ptr<MeshLib::Line> createZ()\n    {\n        return createLine({{0.0, 0.0, -1.0}}, {{0.0, 0.0,  1.0}});\n    }\n\n    std::unique_ptr<MeshLib::Line> createXY()\n    {\n        // 45degree inclined\n        return createLine({{0.0, 0.0, 0.0}}, {{2./sqrt(2), 2./sqrt(2), 0.0}});\n    }\n\n    std::unique_ptr<MeshLib::Line> createXYZ()\n    {\n        return createLine({{0.0, 0.0, 0.0}}, {{2./sqrt(3), 2./sqrt(3), 2./sqrt(3)}});\n    }\n\n};\n\nnamespace TestQuad4\n{\n    // Element information\nusing ElementType = MeshLib::Quad;\nconst unsigned e_nnodes = ElementType::n_all_nodes;\n\nstd::unique_ptr<MeshLib::Quad> createQuad(std::array<double, 3> const& a,\n                                          std::array<double, 3> const& b,\n                                          std::array<double, 3> const& c,\n                                          std::array<double, 3> const& d)\n{\n    auto** nodes = new MeshLib::Node*[e_nnodes];\n    nodes[0] = new MeshLib::Node(a);\n    nodes[1] = new MeshLib::Node(b);\n    nodes[2] = new MeshLib::Node(c);\n    nodes[3] = new MeshLib::Node(d);\n    return std::make_unique<MeshLib::Quad>(nodes);\n    }\n\n    // 2.5D case: inclined\n    std::unique_ptr<MeshLib::Quad> createXYZ()\n    {\n        // rotate 45 degree around x axis\n        return createQuad(\n            {{ 1.0,  0.7071067811865475,  0.7071067811865475}},\n            {{-1.0,  0.7071067811865475,  0.7071067811865475}},\n            {{-1.0, -0.7071067811865475, -0.7071067811865475}},\n            {{ 1.0, -0.7071067811865475, -0.7071067811865475}});\n    }\n\n    // 2.5D case: inclined\n    std::unique_ptr<MeshLib::Quad> createXZ()\n    {\n        return createQuad(\n            {{ 1.0, 0.0,  1.0}},\n            {{-1.0, 0.0,  1.0}},\n            {{-1.0, 0.0, -1.0}},\n            {{ 1.0, 0.0, -1.0}});\n    }\n\n    // 2.5D case: inclined\n    std::unique_ptr<MeshLib::Quad> createYZ()\n    {\n        return createQuad(\n            {{0.0,  1.0,  1.0}},\n            {{0.0, -1.0,  1.0}},\n            {{0.0, -1.0, -1.0}},\n            {{0.0,  1.0, -1.0}});\n    }\n};\n\n#if 0\n// keep this function for debugging\nvoid debugOutput(MeshLib::Element *ele, MeshLib::ElementCoordinatesMappingLocal &mapping)\n{\n    std::cout.precision(12);\n    std::cout << \"original\" << std::endl;\n    for (unsigned i=0; i<ele->getNumberOfNodes(); i++)\n        std::cout << *ele->getNode(i) << std::endl;\n    std::cout << \"local coords=\" << std::endl;\n    for (unsigned i=0; i<ele->getNumberOfNodes(); i++)\n        std::cout << *mapping.getMappedCoordinates(i) << std::endl;\n    std::cout << \"R=\\n\" << mapping.getRotationMatrixToGlobal() << std::endl;\n    auto matR(mapping.getRotationMatrixToGlobal());\n    std::cout << \"global coords=\" << std::endl;\n    for (unsigned i=0; i<ele->getNumberOfNodes(); i++) {\n        double* raw = const_cast<double*>(&(*mapping.getMappedCoordinates(i))[0]);\n        Eigen::Map<Eigen::Vector3d> v(raw);\n        std::cout << (matR*v).transpose() << std::endl;\n    }\n}\n#endif\n\n// check if using the rotation matrix results in the original coordinates\n#define CHECK_COORDS(ele, mapping)\\\n    for (unsigned ii=0; ii<(ele)->getNumberOfNodes(); ii++) {\\\n        MathLib::Point3d global(matR*(mapping).getMappedCoordinates(ii));\\\n        const double eps(std::numeric_limits<double>::epsilon());\\\n        ASSERT_ARRAY_NEAR(&(*(ele)->getNode(ii))[0], global.getCoords(), 3u, eps);\\\n    }\n\n} //namespace\n\nTEST(MeshLib, CoordinatesMappingLocalLowerDimLineY)\n{\n    auto ele = TestLine2::createY();\n    MeshLib::ElementCoordinatesMappingLocal mapping(\n        *ele, MeshLib::CoordinateSystem(MeshLib::CoordinateSystemType::Y)\n                  .getDimension());\n    auto matR(mapping.getRotationMatrixToGlobal());\n    //debugOutput(ele, mapping);\n\n    double exp_R[3*3] = {0, -1, 0,\n                         1,  0, 0,\n                         0,  0, 1};\n    const double eps(std::numeric_limits<double>::epsilon());\n    ASSERT_ARRAY_NEAR(exp_R, matR.data(), matR.size(), eps);\n    CHECK_COORDS(ele,mapping);\n\n    for (std::size_t n = 0; n < ele->getNumberOfNodes(); ++n)\n        delete ele->getNode(n);\n}\n\nTEST(MeshLib, CoordinatesMappingLocalLowerDimLineZ)\n{\n    auto ele = TestLine2::createZ();\n    MeshLib::ElementCoordinatesMappingLocal mapping(\n        *ele,\n        MeshLib::CoordinateSystem(MeshLib::CoordinateSystemType::Z)\n            .getDimension());\n    auto matR(mapping.getRotationMatrixToGlobal());\n    //debugOutput(ele, mapping);\n\n    double exp_R[3*3] = {0, 0, -1, 0, 1, 0, 1, 0, 0};\n    const double eps(std::numeric_limits<double>::epsilon());\n    ASSERT_ARRAY_NEAR(exp_R, matR.data(), matR.size(), eps);\n    CHECK_COORDS(ele,mapping);\n\n    for (std::size_t n = 0; n < ele->getNumberOfNodes(); ++n)\n        delete ele->getNode(n);\n}\n\nTEST(MeshLib, CoordinatesMappingLocalLowerDimLineXY)\n{\n    auto ele = TestLine2::createXY();\n    MeshLib::ElementCoordinatesMappingLocal mapping(\n        *ele, MeshLib::CoordinateSystem(*ele).getDimension());\n    auto matR(mapping.getRotationMatrixToGlobal());\n    //debugOutput(ele, mapping);\n\n    double exp_R[3*3] = {0.70710678118654757, -0.70710678118654757, 0,\n                         0.70710678118654757,  0.70710678118654757, 0,\n                         0,                    0,                   1};\n    const double eps(std::numeric_limits<double>::epsilon());\n    ASSERT_ARRAY_NEAR(exp_R, matR.data(), matR.size(), eps);\n    CHECK_COORDS(ele,mapping);\n\n    for (std::size_t n = 0; n < ele->getNumberOfNodes(); ++n)\n        delete ele->getNode(n);\n}\n\nTEST(MeshLib, CoordinatesMappingLocalLowerDimLineXYZ)\n{\n    auto ele = TestLine2::createXYZ();\n    MeshLib::ElementCoordinatesMappingLocal mapping(\n        *ele, MeshLib::CoordinateSystem(*ele).getDimension());\n    auto matR(mapping.getRotationMatrixToGlobal());\n    //debugOutput(ele, mapping);\n\n    double exp_R[3*3] = {0.57735026918962584, -0.81649658092772626,  0,\n                         0.57735026918962584,  0.40824829046386313, -0.70710678118654757,\n                         0.57735026918962584,  0.40824829046386313,  0.70710678118654757};\n    const double eps(std::numeric_limits<double>::epsilon());\n    ASSERT_ARRAY_NEAR(exp_R, matR.data(), matR.size(), eps);\n    CHECK_COORDS(ele,mapping);\n\n    for (std::size_t n = 0; n < ele->getNumberOfNodes(); ++n)\n        delete ele->getNode(n);\n}\n\nTEST(MeshLib, CoordinatesMappingLocalLowerDimQuadXZ)\n{\n    auto ele = TestQuad4::createXZ();\n    MeshLib::ElementCoordinatesMappingLocal mapping(\n        *ele, MeshLib::CoordinateSystem(*ele).getDimension());\n    auto matR(mapping.getRotationMatrixToGlobal());\n    //debugOutput(ele, mapping);\n\n    // results when using GeoLib::ComputeRotationMatrixToXY()\n    double exp_R[3*3] = {  1, 0,  0,\n                           0, 0, -1,\n                           0, 1,  0};\n\n    const double eps(std::numeric_limits<double>::epsilon());\n    ASSERT_ARRAY_NEAR(exp_R, matR.data(), matR.size(), eps);\n    CHECK_COORDS(ele,mapping);\n\n    for (std::size_t n = 0; n < ele->getNumberOfNodes(); ++n)\n        delete ele->getNode(n);\n}\n\nTEST(MeshLib, CoordinatesMappingLocalLowerDimQuadYZ)\n{\n    auto ele = TestQuad4::createYZ();\n    MeshLib::ElementCoordinatesMappingLocal mapping(\n        *ele, MeshLib::CoordinateSystem(*ele).getDimension());\n    auto matR(mapping.getRotationMatrixToGlobal());\n    //debugOutput(ele, mapping);\n\n    // results when using GeoLib::ComputeRotationMatrixToXY()\n    double exp_R[3*3] = { 0, 0, 1,\n                          0, 1, 0,\n                         -1, 0, 0};\n\n    const double eps(std::numeric_limits<double>::epsilon());\n    ASSERT_ARRAY_NEAR(exp_R, matR.data(), matR.size(), eps);\n    CHECK_COORDS(ele,mapping);\n\n    for (std::size_t n = 0; n < ele->getNumberOfNodes(); ++n)\n        delete ele->getNode(n);\n}\n\nTEST(MeshLib, CoordinatesMappingLocalLowerDimQuadXYZ)\n{\n    auto ele = TestQuad4::createXYZ();\n    MeshLib::ElementCoordinatesMappingLocal mapping(\n        *ele, MeshLib::CoordinateSystem(*ele).getDimension());\n    auto matR(mapping.getRotationMatrixToGlobal());\n    //debugOutput(ele, mapping);\n\n    // results when using GeoLib::ComputeRotationMatrixToXY()\n    double exp_R[3*3] = {  1, 0, 0,\n                           0, 0.70710678118654757, -0.70710678118654757,\n                           0, 0.70710678118654757,  0.70710678118654757};\n\n    const double eps(std::numeric_limits<double>::epsilon());\n    ASSERT_ARRAY_NEAR(exp_R, matR.data(), matR.size(), eps);\n    CHECK_COORDS(ele,mapping);\n\n    for (std::size_t n = 0; n < ele->getNumberOfNodes(); ++n)\n        delete ele->getNode(n);\n}\n\n", "meta": {"hexsha": "70c7ade139f30cfc8332543619c79be1cf151b0f", "size": 9845, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tests/MeshLib/TestCoordinatesMappingLocal.cpp", "max_stars_repo_name": "hosseinsotudeh/ogs", "max_stars_repo_head_hexsha": "214afcb00af23e4393168a846c7ee8ce4f13e489", "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": "Tests/MeshLib/TestCoordinatesMappingLocal.cpp", "max_issues_repo_name": "hosseinsotudeh/ogs", "max_issues_repo_head_hexsha": "214afcb00af23e4393168a846c7ee8ce4f13e489", "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": "Tests/MeshLib/TestCoordinatesMappingLocal.cpp", "max_forks_repo_name": "hosseinsotudeh/ogs", "max_forks_repo_head_hexsha": "214afcb00af23e4393168a846c7ee8ce4f13e489", "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": 33.3728813559, "max_line_length": 90, "alphanum_fraction": 0.6071102082, "num_tokens": 2853, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.757794360334681, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.4962755424893599}}
{"text": "#include <iostream>\r\n#include <stdlib.h>\r\n#include <cmath>\r\n\r\n#include <boost/numeric/ublas/vector.hpp>\r\n#include <boost/numeric/ublas/matrix.hpp>\r\n#include <boost/numeric/ublas/matrix_sparse.hpp>\r\n#include <boost/numeric/ublas/triangular.hpp>\r\n#include <boost/numeric/ublas/io.hpp>\r\n\r\n#include <boost/timer/timer.hpp>\r\n\r\nnamespace ublas  = boost::numeric::ublas;\r\n\r\ntemplate<class mat, class vec>\r\ndouble diff(const mat& A, const vec& x, const vec& b) {\r\n  vec temp(prod(A, x) - b);\r\n  double result = 0;\r\n  for (typename vec::size_type i=0; i<temp.size(); ++i) {\r\n    result += temp(i)*temp(i);\r\n  }\r\n  return std::sqrt(result);\r\n}\r\n\r\ntemplate<class mat, class vec>\r\ndouble diff(const vec& x, const mat& A, const vec& b) {\r\n  return diff(trans(A), x, b);\r\n}\r\n\r\nnamespace ublas  = boost::numeric::ublas;\r\n\r\n\r\nint main() {\r\n  const int n=7000;\r\n#if 1\r\n  ublas::compressed_matrix<double, ublas::row_major>     mat_row_upp(n, n);\r\n  ublas::compressed_matrix<double, ublas::column_major>  mat_col_upp(n, n);\r\n  ublas::compressed_matrix<double, ublas::row_major>     mat_row_low(n, n);\r\n  ublas::compressed_matrix<double, ublas::column_major>  mat_col_low(n, n);\r\n#else\r\n  ublas::matrix<double, ublas::row_major>     mat_row_upp(n, n, 0);\r\n  ublas::matrix<double, ublas::column_major>  mat_col_upp(n, n, 0);\r\n  ublas::matrix<double, ublas::row_major>     mat_row_low(n, n, 0);\r\n  ublas::matrix<double, ublas::column_major>  mat_col_low(n, n, 0);\r\n#endif\r\n  ublas::vector<double>  b(n, 1);\r\n\r\n  std::cerr << \"Constructing...\" << std::endl;\r\n  for (int i=0; i<n; ++i) {\r\n    b(i) = std::rand() % 10;\r\n    double main = -10 + std::rand() % 20 ;\r\n    if (main == 0) main+=1;\r\n    double side = -10 + std::rand() % 20 ;\r\n    if (i-1>=0) {\r\n      mat_row_low(i, i-1) = side;\r\n    }\r\n    mat_row_low(i, i) = main;\r\n\r\n    mat_col_low(i, i) = main;\r\n    if (i+1<n) {\r\n      mat_col_low(i+1, i) = side;\r\n    }\r\n\r\n    mat_row_upp(i, i) = main;\r\n    if (i+1<n) {\r\n      mat_row_upp(i, i+1) = side;\r\n    }\r\n\r\n    if (i-1>=0) {\r\n      mat_col_upp(i-1, i) = side;\r\n    }\r\n    mat_col_upp(i, i) = main;\r\n  }\r\n\r\n  std::cerr << \"Starting...\" << std::endl;\r\n  {\r\n    boost::timer::auto_cpu_timer t(std::cerr, \"col_low x: %t sec CPU, %w sec real\\n\");\r\n    ublas::vector<double>  x(b);\r\n    ublas::inplace_solve(mat_col_low,  x, ublas::lower_tag());\r\n    std::cerr << \"delta: \" << diff(mat_col_low, x, b) << \"\\n\";\r\n  }\r\n  {\r\n    boost::timer::auto_cpu_timer t(std::cerr, \"row_low x: %t sec CPU, %w sec real\\n\");\r\n    ublas::vector<double>  x(b);\r\n    ublas::inplace_solve(mat_row_low, x, ublas::lower_tag());\r\n    std::cerr << \"delta: \" << diff(mat_row_low, x, b) << \"\\n\";\r\n  }\r\n\r\n  {\r\n    boost::timer::auto_cpu_timer t(std::cerr, \"col_upp x: %t sec CPU, %w sec real\\n\");\r\n    ublas::vector<double>  x(b);\r\n    ublas::inplace_solve(mat_col_upp,  x, ublas::upper_tag());\r\n    std::cerr << \"delta: \" << diff(mat_col_upp, x, b) << \"\\n\";\r\n  }\r\n  {\r\n    boost::timer::auto_cpu_timer t(std::cerr, \"row_upp x: %t sec CPU, %w sec real\\n\");\r\n    ublas::vector<double>  x(b);\r\n    ublas::inplace_solve(mat_row_upp, x, ublas::upper_tag());\r\n    std::cerr << \"delta: \" << diff(mat_row_upp, x, b) << \"\\n\";\r\n  }\r\n\r\n  {\r\n    boost::timer::auto_cpu_timer t(std::cerr, \"x col_low: %t sec CPU, %w sec real\\n\");\r\n    ublas::vector<double>  x(b);\r\n    ublas::inplace_solve(x, mat_col_low, ublas::lower_tag());\r\n    std::cerr << \"delta: \" << diff(x, mat_col_low, b) << \"\\n\";\r\n  }\r\n  {\r\n    boost::timer::auto_cpu_timer t(std::cerr, \"x row_low: %t sec CPU, %w sec real\\n\");\r\n    ublas::vector<double>  x(b);\r\n    ublas::inplace_solve(x, mat_row_low, ublas::lower_tag());\r\n    std::cerr << \"delta: \" << diff(x, mat_row_low, b) << \"\\n\";\r\n  }\r\n\r\n  {\r\n    boost::timer::auto_cpu_timer t(std::cerr, \"x col_upp: %t sec CPU, %w sec real\\n\");\r\n    ublas::vector<double>  x(b);\r\n    ublas::inplace_solve(x, mat_col_upp, ublas::upper_tag());\r\n    std::cerr << \"delta: \" << diff(x, mat_col_upp, b) << \"\\n\";\r\n  }\r\n  {\r\n    boost::timer::auto_cpu_timer t(std::cerr, \"x row_upp: %t sec CPU, %w sec real\\n\");\r\n    ublas::vector<double>  x(b);\r\n    ublas::inplace_solve(x, mat_row_upp, ublas::upper_tag());\r\n    std::cerr << \"delta: \" << diff(x, mat_row_upp, b) << \"\\n\";\r\n  }\r\n\r\n\r\n}\r\n", "meta": {"hexsha": "b15465ed3523e8a72986eb5f0d9bac5d16afcdc8", "size": 4222, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/numeric/ublas/test/test_triangular.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": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/numeric/ublas/test/test_triangular.cpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-04T18:00:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-04T18:00:00.000Z", "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/numeric/ublas/test/test_triangular.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 32.4769230769, "max_line_length": 87, "alphanum_fraction": 0.5866887731, "num_tokens": 1395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6548947290421276, "lm_q1q2_score": 0.4962755394455552}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// Unit Test\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\n#include <geometry_test_common.hpp>\n\n#include <boost/geometry/algorithms/transform.hpp>\n#include <boost/geometry/io/wkt/wkt.hpp>\n#include <boost/geometry/strategies/strategies.hpp>\n\n#include <boost/geometry/extensions/gis/latlong/point_ll.hpp>\n\n\n#include <test_common/test_point.hpp>\n\ntemplate <typename P>\nvoid test_all()\n{\n    typedef typename bg::coordinate_type<P>::type type;\n\n    P p1(bg::latitude<type>(bg::dms<bg::south, type>(12, 2, 36)),\n         bg::longitude<type>(bg::dms<bg::west, type>(77, 1, 42)));\n\n    // Check decimal/degree conversion\n    BOOST_CHECK_CLOSE(bg::get<0>(p1), type(-77.0283), 0.001);\n    BOOST_CHECK_CLOSE(bg::get<1>(p1), type(-12.0433), 0.001);\n\n    // Check degree/radian conversion\n    bg::model::ll::point<bg::radian, type> p2;\n    bg::transform(p1, p2);\n\n    BOOST_CHECK_CLOSE(bg::get<0>(p2), type(-1.3444), 0.001);\n    BOOST_CHECK_CLOSE(bg::get<1>(p2), type(-0.210196), 0.001);\n\n    // Check degree/radian conversion back\n    P p3;\n    bg::transform(p2, p3);\n    BOOST_CHECK_CLOSE(bg::get<0>(p3), type(-77.0283), 0.001);\n    BOOST_CHECK_CLOSE(bg::get<1>(p3), type(-12.0433), 0.001);\n\n\n    // Check decimal/degree conversion back\n    int d;\n    int m;\n    double s;\n    bool positive;\n    char cardinal;\n\n    bg::dms<bg::cd_lat, type> d1(bg::get<0>(p3));\n    d1.get_dms(d, m, s, positive, cardinal);\n\n    BOOST_CHECK(d == 77);\n    BOOST_CHECK(m == 1);\n    BOOST_CHECK_CLOSE(s, double(42), 0.1);\n    BOOST_CHECK(positive == false);\n    BOOST_CHECK(cardinal == 'S');\n\n    // Check dd conversion as string, back. We cannot do that always because of the precision.\n    // Only double gives correct results\n    //std::string st = d1.get_dms();\n    //std::cout << st << std::endl;\n    //BOOST_CHECK(st == \"77 1'42\\\" S\");\n}\n\nint test_main(int, char* [])\n{\n    test_all<bg::model::ll::point<bg::degree, float> >();\n    test_all<bg::model::ll::point<bg::degree, double> >();\n\n    return 0;\n}\n", "meta": {"hexsha": "4c274c36b698724608d7f1b32293b769b3364f5e", "size": 2515, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "extensions/test/gis/latlong/point_ll.cpp", "max_stars_repo_name": "jkerkela/geometry", "max_stars_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 326.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T13:47:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T02:13:59.000Z", "max_issues_repo_path": "extensions/test/gis/latlong/point_ll.cpp", "max_issues_repo_name": "jkerkela/geometry", "max_issues_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 623.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T23:45:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T11:15:23.000Z", "max_forks_repo_path": "extensions/test/gis/latlong/point_ll.cpp", "max_forks_repo_name": "jkerkela/geometry", "max_forks_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-01-14T15:50:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T03:58:36.000Z", "avg_line_length": 30.3012048193, "max_line_length": 94, "alphanum_fraction": 0.6644135189, "num_tokens": 770, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746404, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.496275539445555}}
{"text": "#pragma once\n#include <type_traits>\n\n#include <Eigen/Core>\n\nnamespace ubs {\nnamespace internal {\n/**\n * @brief The smoothness cost functor.\n *\n * This cost functor is used to calculate the smoothness of a spline during optimization. The operation for\n * uniform B-splines boils down to a matrix matrix product, where the first matrix is build by concatenating the\n * control points and the second one is the fixed smoothing matrix.\n *\n * @tparam N_ The number of control points the cost function depends on.\n */\ntemplate <int OutputDims_, int N_>\nclass SmoothnessCostFunctor {\nprivate:\n    /* @brief Flag, which indicates if dynamic sized matrices should be used.\n     *\n     * Due to stack limitation of the number of elements of the matrix use Eigen::Dynamic for big ones.\n     */\n    static constexpr bool UseDynamicSizedMatrix_ = (N_ * OutputDims_) > 16;\n    static constexpr int EigenN_ = UseDynamicSizedMatrix_ ? Eigen::Dynamic : N_;\n\n    /**\n     * @brief Helper function to create the control points matrix.\n     *\n     * This overload is picked if fixed size matrices are used.\n     *\n     * @tparam T The value type of the matrix.\n     * @return The control points matrix with the correct size.\n     */\n    template <typename T>\n    UBS_NO_DISCARD Eigen::Matrix<T, OutputDims_, EigenN_> makeControlPoints(std::false_type /* isDynamic */) const {\n        return {};\n    }\n\n    /**\n     * @brief Helper function to create the control points matrix.\n     *\n     * This overload is picked if dynamic sized matrices are used.\n     *\n     * @tparam T The value type of the matrix.\n     * @return The control points matrix with the correct size.\n     */\n    template <typename T>\n    UBS_NO_DISCARD Eigen::Matrix<T, OutputDims_, EigenN_> makeControlPoints(std::true_type /* isDynamic */) const {\n        return {OutputDims_, N_};\n    }\n\npublic:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n    /**\n     * @brief The constructor.\n     * @param[in] m The smoothness cost factors.\n     */\n    explicit SmoothnessCostFunctor(Eigen::Matrix<double, N_, N_> m) : m_{std::move(m)} {\n    }\n\n    /**\n     * @brief Cost function used in DynamicAutoDiffCostFunction.\n     * @param[in] controlPointsRaw The control points pointer.\n     * @param[out] residualRaw The residual pointer.\n     * @return True on success, otherwise false.\n     */\n    template <typename T>\n    bool operator()(T const* const* controlPointsRaw, T* residualRaw) const {\n        // Copy the control points to an Eigen matrix.\n        auto controlPoints = makeControlPoints<T>(std::integral_constant<bool, UseDynamicSizedMatrix_>());\n        for (int i = 0; i < N_; ++i) {\n            controlPoints.col(i) = Eigen::Map<const Eigen::Matrix<T, OutputDims_, 1>>(controlPointsRaw[i]);\n        }\n\n        // Evaluate smoothness values.\n        Eigen::Map<Eigen::Matrix<T, OutputDims_, N_>> residuals(residualRaw);\n        residuals = controlPoints * m_.template cast<T>();\n\n        return true;\n    }\n\n    /**\n     * @brief Cost function used in AutoDiffCostFunction.\n     *\n     * Enable if is necessary because other the wrong overload would be picked if it is used in a dynamic cost\n     * function.\n     *\n     * @param[in] controlPoint The control points.\n     * @param[in,out] ts The other control points and the residual pointer.\n     * @return True on success, otherwise false.\n     */\n    template <typename T, typename... Ts>\n    typename std::enable_if<!std::is_pointer<T>::value, bool>::type operator()(const T* controlPoint, Ts*... ts) const {\n        static_assert(N_ == sizeof...(Ts), \"Invalid number of control points specified.\");\n\n        // Build control points array.\n        std::array<const T*, sizeof...(Ts) + 1> controlPointsRaw{{controlPoint, ts...}};\n\n        // The last element of the control points is the place to store the output.\n        T* residualRaw = std::get<sizeof...(Ts)>(std::make_tuple(controlPoint, ts...));\n\n        return this->operator()(controlPointsRaw.data(), residualRaw);\n    }\n\nprivate:\n    /** @brief The smoothness matrix. */\n    Eigen::Matrix<double, EigenN_, EigenN_> m_;\n};\n\n} // namespace internal\n} // namespace ubs\n", "meta": {"hexsha": "fceaffd0a54c91f28b4c4b73cb02b6b901238f66", "size": 4124, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/uniform_bspline_ceres/internal/smoothness_cost_functor.hpp", "max_stars_repo_name": "KIT-MRT/uniform_bspline_ceres", "max_stars_repo_head_hexsha": "2953bf549c15d49b8a82c5331be3231852ff69b3", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-12-23T00:12:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-28T09:22:43.000Z", "max_issues_repo_path": "include/uniform_bspline_ceres/internal/smoothness_cost_functor.hpp", "max_issues_repo_name": "KIT-MRT/uniform_bspline_ceres", "max_issues_repo_head_hexsha": "2953bf549c15d49b8a82c5331be3231852ff69b3", "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/uniform_bspline_ceres/internal/smoothness_cost_functor.hpp", "max_forks_repo_name": "KIT-MRT/uniform_bspline_ceres", "max_forks_repo_head_hexsha": "2953bf549c15d49b8a82c5331be3231852ff69b3", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-01-16T15:14:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-28T09:22:44.000Z", "avg_line_length": 36.1754385965, "max_line_length": 120, "alphanum_fraction": 0.6653734239, "num_tokens": 969, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721305, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.4962258951265069}}
{"text": "#define BOOST_TEST_MODULE CNRTests\n\n#include <boost/test/unit_test.hpp>\n\n#include <bts/utilities/combinatorics.hpp>\n#include <fc/exception/exception.hpp>\n#include <fc/log/logger.hpp>\n#include <fc/thread/thread.hpp>\n#include <fc/filesystem.hpp>\n#include <fc/network/ip.hpp>\n#include <fc/io/json.hpp>\n\n#include <iostream>\n\nBOOST_AUTO_TEST_CASE( util_cnr )\n{\n    BOOST_CHECK_EQUAL(bts::utilities::cnr(5, 2), 10);\n    \n    auto res = bts::utilities::unranking( bts::utilities::cnr(5, 2) - 1, 2, 5);\n    \n    std::cout << res.size() << \" \"<< res[0] << \" \" << res[1] << \"\\n\";\n}\n", "meta": {"hexsha": "3e7681fc541f5c4d1c86d9ae634f172e8a354575", "size": 572, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/util_cnr_test.cpp", "max_stars_repo_name": "dacsunlimited/dacplay", "max_stars_repo_head_hexsha": "91e354c951cf137617f2593c895e009866923bed", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2015-03-30T23:41:06.000Z", "max_stars_repo_stars_event_max_datetime": "2017-03-30T02:20:14.000Z", "max_issues_repo_path": "tests/util_cnr_test.cpp", "max_issues_repo_name": "dacsunlimited/dacplay", "max_issues_repo_head_hexsha": "91e354c951cf137617f2593c895e009866923bed", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 112.0, "max_issues_repo_issues_event_min_datetime": "2015-01-01T13:45:59.000Z", "max_issues_repo_issues_event_max_datetime": "2015-08-05T09:16:10.000Z", "max_forks_repo_path": "tests/util_cnr_test.cpp", "max_forks_repo_name": "dacsunlimited/dacplay", "max_forks_repo_head_hexsha": "91e354c951cf137617f2593c895e009866923bed", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2015-06-06T08:09:50.000Z", "max_forks_repo_forks_event_max_datetime": "2017-12-13T07:34:15.000Z", "avg_line_length": 24.8695652174, "max_line_length": 79, "alphanum_fraction": 0.6643356643, "num_tokens": 171, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.49622589512650683}}
{"text": "// Copyright (c) 2018 by University Paris-Est Marne-la-Vallee\r\n// Geometric.hpp\r\n// This file is part of the Garamon for project_namespace.\r\n// Authors: Stephane Breuils and Vincent Nozick\r\n// Contact: vincent.nozick@u-pem.fr\r\n//\r\n// Licence MIT\r\n// A a copy of the MIT License is given along with this program\r\n\r\n/// \\file Geometric.hpp\r\n/// \\author Stephane Breuils, Vincent Nozick\r\n/// \\brief Recursive geometric product for project_namespace.\r\n\r\n\r\n#ifndef project_inclusion_guard\r\n#define project_inclusion_guard\r\n#pragma once\r\n\r\n#include <Eigen/Core>\r\n\r\n#include \"project_namespace/Mvec.hpp\"\r\n#include \"project_namespace/Constants.hpp\"\r\n\r\n/*!\r\n * @namespace project_namespace\r\n */\r\nnamespace project_namespace {\r\n\r\n    template<typename T> class Mvec;\r\n\r\n\r\n    /// \\brief Recursively compute the geometric product between two multivectors mv1 and mv2, the result is put into the multivector mv3\r\n    /// \\tparam the type of value that we manipulate, either float or double or something.\r\n    /// \\param mv1 - the first multivector\r\n    /// \\param mv2 - the second multivector\r\n    /// \\param mv3 - the multivector that will content the result of the operation mv3 = mv1 * mv2\r\n    /// \\param grade_mv1 - the grade of the first multivector\r\n    /// \\param grade_mv2 - the grade of the second multivector\r\n    /// \\param grade_mv3 - could be the grade of the result, however here it is useless due to the fact that the resulting multivector may not be homogeneous\r\n    /// \\param currentGradeMv1 - the current grade of the traversed tree of mv1\r\n    /// \\param currentGradeMv2 - the current grade of the traversed tree of mv2\r\n    /// \\param currentGradeMv3 - the current grade of the traversed tree of mv3\r\n    /// \\param sign - compute the sign of the geometric product between two blades\r\n    /// \\param complement - activate the flip of sign\r\n    /// \\param indexLastVector_mv1 - last vector traversed in the multivector mv1\r\n    /// \\param indexLastVector_mv2 - last vector traversed in the multivector mv2\r\n    /// \\param indexLastVector_mv3 - last vector traversed in the multivector mv3\r\n    /// \\param currentMetricCoefficient - coefficient that is used for handling the metric in the recursive formula\r\n    /// \\param depth - depth in the resulting multivector tree\r\n    template<typename T>\r\n    void geoProduct(const Eigen::Matrix<T, Eigen::Dynamic, 1> &mv1,\r\n                    const Eigen::Matrix<T, Eigen::Dynamic, 1> &mv2,\r\n                    Mvec<T> &mv3,          // multivectors to be processed\r\n                    const unsigned int grade_mv1,\r\n                    const unsigned int grade_mv2,\r\n                    const unsigned int grade_mv3,   // grade of the k-vectors\r\n                    unsigned int currentXorIdx1=0, unsigned int currentXorIdx2=0, unsigned int currentXorIdx3=0,    // position in the prefix tree\r\n                    unsigned int currentGradeMv1=0, unsigned int currentGradeMv2=0, unsigned int currentGradeMv3=0, // grade relative to the position in the prefix tree\r\n                    int sign=1, int complement=1,\r\n                    unsigned int indexLastVector_mv1=0, unsigned int indexLastVector_mv2=0, unsigned int indexLastVector_mv3=0,\r\n                    double currentMetricCoefficient=1.0, int depth=0) {\r\n\r\n        // sign updating\r\n        int tmpSign = sign;\r\n        if(complement == -1) {\r\n            tmpSign = -tmpSign;\r\n        }\r\n\r\n        // when we reach the grade of mv1 and mv2\r\n        if( (currentGradeMv1==grade_mv1) && (currentGradeMv2==grade_mv2) ){\r\n            // do the required computation\r\n            mv3.at(currentGradeMv3, xorIndexToHomogeneousIndex[currentXorIdx3]) += sign * currentMetricCoefficient * mv1(xorIndexToHomogeneousIndex[currentXorIdx1]) * mv2(xorIndexToHomogeneousIndex[currentXorIdx2]);\r\n        }else {\r\n            // if position in the tree for mv3 is not yet of grade of mv3, just call the recursive calls, without computation\r\n            // for each possible children of the current node whose index is given by depth\r\n            for (unsigned int i = (unsigned int) (1 << depth);\r\n                 i < (1 << algebraDimension); i *= 2) {\r\n\r\n                unsigned int xorIndexMv1Child = currentXorIdx1 + i; // xor index of the child of the first tree multivector\r\n                unsigned int xorIndexMv2Child = currentXorIdx2 + i; // xor index of the child of the second tree multivector\r\n                unsigned int xorIndexMv3Child = currentXorIdx3 + i; // xor index of the child of the third tree multivector\r\n\r\n                // if we reach neither the grade of mv1 nor the grade of mv2 AND if the child of the node of mv1 lead to at least one node whose grade is grade_mv1\r\n                // AND if the child of the node of mv2 lead to at least one node whose grade is grade_mv2\r\n                if ((currentGradeMv1 < grade_mv1) &&\r\n                    ((i << (grade_mv1 - (currentGradeMv1 + 1))) < (1 << algebraDimension)) &&\r\n                    (currentGradeMv2 < grade_mv2) &&\r\n                    ((i << (grade_mv2 - (currentGradeMv2 + 1))) < (1 << algebraDimension))) {\r\n                    geoProduct<T>(mv1, mv2, mv3,\r\n                                  grade_mv1, grade_mv2, grade_mv3,\r\n                                  xorIndexMv1Child, xorIndexMv2Child, currentXorIdx3,\r\n                                  currentGradeMv1 + 1, currentGradeMv2 + 1, currentGradeMv3,\r\n                                  tmpSign, -complement,\r\n                                  i, i << 1, indexLastVector_mv3,\r\n                                  diagonalMetric<T>(depth) * currentMetricCoefficient,\r\n                                  depth + 1); // scalar product part of the geometric product\r\n                }\r\n\r\n                // if we do not reach the grade of mv1 AND if the child of the node of mv1 lead to at least one node whose grade is grade_mv1\r\n                if ((currentGradeMv1 < grade_mv1) &&\r\n                    ((i << (grade_mv1 - (currentGradeMv1 + 1))) < (1 << algebraDimension))) {\r\n                    geoProduct<T>(mv1, mv2, mv3,\r\n                                  grade_mv1, grade_mv2, grade_mv3,\r\n                                  xorIndexMv1Child, currentXorIdx2, xorIndexMv3Child,\r\n                                  currentGradeMv1 + 1, currentGradeMv2, currentGradeMv3 + 1,\r\n                                  tmpSign, complement,\r\n                                  i, i << 1, indexLastVector_mv3,\r\n                                  currentMetricCoefficient, depth + 1); // outer part of the geometric product to CHECK\r\n                }\r\n\r\n                // if we do not reach the grade of mv2 AND if the child of the node of mv2 lead to at least one node whose grade is grade_mv2\r\n                if ((currentGradeMv2 < grade_mv2) &&\r\n                    ((i << (grade_mv2 - (currentGradeMv2 + 1))) < (1 << algebraDimension))) {\r\n                    geoProduct<T>(mv1, mv2, mv3,\r\n                                  grade_mv1, grade_mv2, grade_mv3,\r\n                                  currentXorIdx1, xorIndexMv2Child, xorIndexMv3Child,\r\n                                  currentGradeMv1, currentGradeMv2 + 1, currentGradeMv3 + 1,\r\n                                  sign, -complement,\r\n                                  indexLastVector_mv1, i << 1, i,\r\n                                  currentMetricCoefficient, depth + 1); // outer part of the geometric product\r\n                }\r\n                depth++;\r\n            }\r\n        }\r\n    }\r\n\r\n}/// End of Namespace\r\n\r\n#endif // project_inclusion_guard", "meta": {"hexsha": "371552c3035b7d54ee7ff09574ee849f426a3e89", "size": 7549, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "data/Geometric.hpp", "max_stars_repo_name": "hugohadfield/garamon", "max_stars_repo_head_hexsha": "0dc40c7790eac887d41532503cd5ac74ce5d3216", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 53.0, "max_stars_repo_stars_event_min_datetime": "2019-07-23T10:56:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T22:18:04.000Z", "max_issues_repo_path": "data/Geometric.hpp", "max_issues_repo_name": "hugohadfield/garamon", "max_issues_repo_head_hexsha": "0dc40c7790eac887d41532503cd5ac74ce5d3216", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2020-04-03T08:06:39.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-10T07:01:55.000Z", "max_forks_repo_path": "data/Geometric.hpp", "max_forks_repo_name": "hugohadfield/garamon", "max_forks_repo_head_hexsha": "0dc40c7790eac887d41532503cd5ac74ce5d3216", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2019-10-22T12:41:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-14T12:17:15.000Z", "avg_line_length": 58.519379845, "max_line_length": 216, "alphanum_fraction": 0.5946482978, "num_tokens": 1771, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.49622589512650683}}
{"text": "//  (C) Copyright John Maddock 2005.\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#ifdef TEST_STD_HEADERS\r\n#include <complex>\r\n#else\r\n#include <boost/tr1/complex.hpp>\r\n#endif\r\n\r\n#include \"verify_return.hpp\"\r\n\r\nint main()\r\n{\r\n   verify_return_type(std::arg(0), double(0));\r\n   verify_return_type(std::arg(0.0), double(0));\r\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\r\n   verify_return_type(std::arg(0.0L), (long double)(0));\r\n#endif\r\n   verify_return_type(std::arg(0.0F), float(0));\r\n   verify_return_type(std::norm(0), double(0));\r\n   verify_return_type(std::norm(0.0), double(0));\r\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\r\n   verify_return_type(std::norm(0.0L), (long double)(0));\r\n#endif\r\n   verify_return_type(std::norm(0.0F), float(0));\r\n   verify_return_type(std::conj(0), std::complex<double>(0));\r\n   verify_return_type(std::conj(0.0), std::complex<double>(0));\r\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\r\n   verify_return_type(std::conj(0.0L), std::complex<long double>(0));\r\n#endif\r\n   verify_return_type(std::conj(0.0F), std::complex<float>(0));\r\n   verify_return_type(std::imag(0), double(0));\r\n   verify_return_type(std::imag(0.0), double(0));\r\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\r\n   verify_return_type(std::imag(0.0L), (long double)(0));\r\n#endif\r\n   verify_return_type(std::imag(0.0F), float(0));\r\n   verify_return_type(std::real(0), double(0));\r\n   verify_return_type(std::real(0.0), double(0));\r\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\r\n   verify_return_type(std::real(0.0L), (long double)(0));\r\n#endif\r\n   verify_return_type(std::real(0.0F), float(0));\r\n   verify_return_type(std::polar(0), std::complex<double>(0));\r\n   verify_return_type(std::polar(0.0), std::complex<double>(0));\r\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\r\n   verify_return_type(std::polar(0.0L), std::complex<long double>(0));\r\n#endif\r\n   verify_return_type(std::polar(0.0F), std::complex<float>(0));\r\n   verify_return_type(std::polar(0, 0L), std::complex<double>(0));\r\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\r\n   verify_return_type(std::polar(0.0, 0.0L), std::complex<long double>(0));\r\n   verify_return_type(std::polar(0.0L, 0.0F), std::complex<long double>(0));\r\n#endif\r\n   verify_return_type(std::polar(0.0F, 0), std::complex<double>(0));\r\n\r\n   std::complex<float> f;\r\n   std::complex<double> d;\r\n   std::complex<long double> l;\r\n   float sf;\r\n   double sd;\r\n   long double sl;\r\n\r\n   verify_return_type(std::pow(f, f), f);\r\n   verify_return_type(std::pow(f, d), d);\r\n   verify_return_type(std::pow(d, f), d);\r\n   verify_return_type(std::pow(f, l), l);\r\n   verify_return_type(std::pow(l, f), l);\r\n   verify_return_type(std::pow(d, l), l);\r\n   verify_return_type(std::pow(l, d), l);\r\n\r\n   verify_return_type(std::pow(f, sf), f);\r\n   verify_return_type(std::pow(f, sd), d);\r\n   verify_return_type(std::pow(d, sf), d);\r\n   verify_return_type(std::pow(f, sl), l);\r\n   verify_return_type(std::pow(l, sf), l);\r\n   verify_return_type(std::pow(d, sl), l);\r\n   verify_return_type(std::pow(l, sd), l);\r\n   verify_return_type(std::pow(f, 0), f);\r\n   verify_return_type(std::pow(d, 0), d);\r\n   verify_return_type(std::pow(l, 0), l);\r\n   verify_return_type(std::pow(f, 0L), d);\r\n   verify_return_type(std::pow(d, 0L), d);\r\n   verify_return_type(std::pow(l, 0L), l);\r\n\r\n   verify_return_type(std::pow(sf, f), f);\r\n   verify_return_type(std::pow(sf, d), d);\r\n   verify_return_type(std::pow(sd, f), d);\r\n   verify_return_type(std::pow(sf, l), l);\r\n   verify_return_type(std::pow(sl, f), l);\r\n   verify_return_type(std::pow(sd, l), l);\r\n   verify_return_type(std::pow(sl, d), l);\r\n   verify_return_type(std::pow(2, f), d);\r\n   verify_return_type(std::pow(2, d), d);\r\n   verify_return_type(std::pow(2, l), l);\r\n   verify_return_type(std::pow(2L, f), d);\r\n   verify_return_type(std::pow(2L, d), d);\r\n   verify_return_type(std::pow(2L, l), l);\r\n\r\n   verify_return_type(std::tr1::acos(f), f);\r\n   verify_return_type(std::tr1::acos(d), d);\r\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\r\n   verify_return_type(std::tr1::acos(l), l);\r\n#endif\r\n   verify_return_type(std::tr1::asin(f), f);\r\n   verify_return_type(std::tr1::asin(d), d);\r\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\r\n   verify_return_type(std::tr1::asin(l), l);\r\n#endif\r\n   verify_return_type(std::tr1::atan(f), f);\r\n   verify_return_type(std::tr1::atan(d), d);\r\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\r\n   verify_return_type(std::tr1::atan(l), l);\r\n#endif\r\n   verify_return_type(std::tr1::asinh(f), f);\r\n   verify_return_type(std::tr1::asinh(d), d);\r\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\r\n   verify_return_type(std::tr1::asinh(l), l);\r\n#endif\r\n   verify_return_type(std::tr1::acosh(f), f);\r\n   verify_return_type(std::tr1::acosh(d), d);\r\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\r\n   verify_return_type(std::tr1::acosh(l), l);\r\n#endif\r\n   verify_return_type(std::tr1::atanh(f), f);\r\n   verify_return_type(std::tr1::atanh(d), d);\r\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\r\n   verify_return_type(std::tr1::atanh(l), l);\r\n#endif\r\n\r\n   //\r\n   // There is a bug in the TR text here, that means we can't always\r\n   // check these as we'd like:\r\n   //\r\n#if !(defined(__GNUC__) && defined(BOOST_HAS_TR1_COMPLEX_INVERSE_TRIG) && !defined(_GLIBCXX_INCLUDE_AS_CXX0X))\r\n   verify_return_type(std::tr1::fabs(f), sf);\r\n   verify_return_type(std::tr1::fabs(d), sd);\r\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\r\n   verify_return_type(std::tr1::fabs(l), sl);\r\n#endif\r\n#endif\r\n   return 0;\r\n}\r\n\r\n", "meta": {"hexsha": "60953989a7932ec595f8773120594f8656cdbad2", "size": 5672, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/tr1/test/test_complex.cpp", "max_stars_repo_name": "lijgame/boost", "max_stars_repo_head_hexsha": "ec2214a19cdddd1048058321a8105dd0231dac47", "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/tr1/test/test_complex.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/tr1/test/test_complex.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": 38.5850340136, "max_line_length": 111, "alphanum_fraction": 0.6879407616, "num_tokens": 1635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.4962258884592768}}
{"text": "#define DERIVE_TIMEDNESS_FROM_NUMBER_OF_TEMPLATE_ARGUMENTS 1\n#include <value_grid.hpp>\n#include <Eigen/Dense>\nvoid print_first(const multi_array<float, 3, 4, 5>& x){\n    std::cout << x[0][0][0] << \"\\n\";\n}\nint main(){\n    multi_array <float, 3> x(3,4,5);\n    multi_array <float, 3> y(10, 10, 20);\n    \n    for(size_t i = 0;i < x.m_im.extent<0>();i++){\n        for(size_t j = 0;j < x.m_im.extent<1>();j++){\n            for(size_t k = 0;k < x.m_im.extent<2>();k++){\n                //std::cout << x(i,j,k) << \", \";\n                x(i,j,k) = i + j + k;\n            }\n        }\n    }\n    //x.m_im.enumerate_index_combinations([&x](std::array<size_t, 3> indices){std::cout << x(indices[0], indices[1], indices[2]) << \", \";});\n    //\n    //std::cout << \"\\n\";\n    ////print_first(x);\n    //y[0][0][5] = 5;\n    //std::cout << y[0][0][5] << \"\\n\";\n    //std::cout << x.nDims() << \"\\n\";\n    //std::cout << reinterpret_cast<size_t>(x.data()) % 32 << \"\\n\";\n    value_grid<float, 8, 8, 8> grid;\n    value_grid<float, 8, 8, 8> grid2;\n    grid [0ul][0ul][0ul] = 5;\n    grid2[0ul][0ul][0ul] = 5;\n    grid = grid + grid2;\n    std::cout << grid(0ul,0ul,0ul) << \"\\n\";\n    //grid.extent<2>();\n}", "meta": {"hexsha": "907ff10f3e3e99a2934d5f2ad469a72140909850", "size": 1173, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test.cpp", "max_stars_repo_name": "manuel5975p/multi_array", "max_stars_repo_head_hexsha": "120395fe5b0c6072c798c8727b57ddf228b92c75", "max_stars_repo_licenses": ["MIT"], "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.cpp", "max_issues_repo_name": "manuel5975p/multi_array", "max_issues_repo_head_hexsha": "120395fe5b0c6072c798c8727b57ddf228b92c75", "max_issues_repo_licenses": ["MIT"], "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.cpp", "max_forks_repo_name": "manuel5975p/multi_array", "max_forks_repo_head_hexsha": "120395fe5b0c6072c798c8727b57ddf228b92c75", "max_forks_repo_licenses": ["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.5, "max_line_length": 140, "alphanum_fraction": 0.4995737425, "num_tokens": 425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.4962258884592768}}
{"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#include <boost/graph/successive_shortest_path_nonnegative_weights.hpp>\n#include <boost/graph/find_flow_cost.hpp>\n\n#include \"../test/min_cost_max_flow_utils.hpp\"\n\n\nint main() {\n    boost::SampleGraph::vertex_descriptor s,t;\n    boost::SampleGraph::Graph g;\n    boost::SampleGraph::getSampleGraph(g, s, t);\n\n    boost::successive_shortest_path_nonnegative_weights(g, s, t);\n\n    int cost =  boost::find_flow_cost(g);\n    assert(cost == 29);\n\n    return 0;\n}\n", "meta": {"hexsha": "a3d05d5add898e62c24c293175c7cb6771ee383f", "size": 831, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/libs/graph/example/successive_shortest_path_nonnegative_weights_example.cpp", "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/libs/graph/example/successive_shortest_path_nonnegative_weights_example.cpp", "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/libs/graph/example/successive_shortest_path_nonnegative_weights_example.cpp", "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": 29.6785714286, "max_line_length": 73, "alphanum_fraction": 0.5992779783, "num_tokens": 184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.49622587783023114}}
{"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\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include <iostream>\n#include <utility>\n#include <cmath>\n// #include <boost/test/minimal.hpp>\n\n#include <boost/numeric/mtl/mtl.hpp>\n#include <boost/numeric/itl/itl.hpp>\n\nusing namespace std;  \n   \ntemplate <typename Vector>\nstruct f_test\n{\n    f_test() : s(3)\n    {\n\tmtl::vec::inserter<Vector> ins(s);\n\tins[0] << 1; ins[1] << 2; ins[2] << 2; \n    }\n\n    typename mtl::Collection<Vector>::value_type \n    operator() (const Vector& x) const\n    {\n\treturn dot(s, Vector(ele_prod(x, x)));\n    }\n    Vector s;\n};\n\n\ntemplate <typename Vector>\nstruct grad_f_test\n{\n    grad_f_test() : s(3)\n    {\n\tmtl::vec::inserter<Vector> ins(s);\n\tins[0] << 2; ins[1] << 4; ins[2] << 4; \n    }\n\n    Vector operator() (const Vector& x) const {  return Vector(ele_prod(s, x)); }\n    Vector s;\n};\n\n\nint main(int, char**)\n{\n    using namespace mtl;\n    using mtl::io::tout;\n\n    mtl::dense_vector<double>       x(3, 8);\n    tout << \"x= \" << x << \"\\n\";\n\n    grad_f_test<mtl::dense_vector<double> > grad_f;\n    f_test<mtl::dense_vector<double> >      f;\n        \n    itl::cyclic_iteration<double>  iter(grad_f(x), 1000, 0, 1e-4, 100);\n    itl::cyclic_iteration<double> iter1(grad_f(x), 1000, 0, 1e-4, 100);\n    itl::cyclic_iteration<double> iter2(grad_f(x), 1000, 0, 1e-4, 100);\n    itl::cyclic_iteration<double> iter3(grad_f(x), 1000, 0, 1e-4, 100);\n    itl::cyclic_iteration<double> iter4(grad_f(x), 1000, 0, 1e-4, 100);\n    \n    quasi_newton(x, f, grad_f, itl::wolf<>(), itl::bfgs(), iter);\n    iter.error_code();    \n\n   // tout << \"x= \" << x << \"\\n\";\n    tout << \"grad_f(x)= \" << grad_f(x) << \"\\n\\n\";\n    if (two_norm(x) > 10 * iter.atol()) throw \"x should be 0.\";\n    x= 8;\n    quasi_newton(x, f, grad_f, itl::wolf<>(), itl::dfp(), iter1);\n    iter1.error_code();    \n\n   // tout << \"dfp x= \" << x << \"\\n\";\n    tout << \"grad_f(x)= \" << grad_f(x) << \"\\n\\n\";\n    if (two_norm(x) > 10 * iter1.atol()) throw \"x should be 0.\";\n    \n    x= 8;\n    quasi_newton(x, f, grad_f, itl::wolf<>(), itl::broyden(), iter2);\n    iter2.error_code();    \n\n    tout << \"broyden x= \" << x << \"\\n\";\n    tout << \"grad_f(x)= \" << grad_f(x) << \"\\n\\n\";\n    if (two_norm(x) > 10 * iter2.atol()) throw \"x should be 0.\";\n    \n #if 0  //bad condition on some compiler\n    x= 8;\n    quasi_newton(x, f, grad_f, itl::wolf<>(), itl::sr1(), iter3);\n    iter3.error_code();    \n\n    tout << \"sr1 x= \" << x << \"\\n\";\n    tout << \"grad_f(x)= \" << grad_f(x) << \"\\n\";\n    if (two_norm(x) > 10 * iter3.atol())\n\tthrow \"x should be 0.\";\n#endif     \n\n    x= 8;\n    quasi_newton(x, f, grad_f, itl::wolf<>(), itl::psb(), iter4);\n    iter4.error_code();\n\n    tout << \"psb x= \" << x << \"\\n\";\n    tout << \"grad_f(x)= \" << grad_f(x) << \"\\n\\n\";\n    if (two_norm(x) > 10 * iter4.atol()) throw \"x should be 0.\";\n\n\n    return 0;\n}\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "93268758995b9a2e129b7119157e1dbb001c95a2", "size": 3212, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/itl/test/quasi_newton_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/itl/test/quasi_newton_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/itl/test/quasi_newton_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": 24.5190839695, "max_line_length": 94, "alphanum_fraction": 0.5638231631, "num_tokens": 1098, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.49622587116300104}}
{"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#include \"main.hxx\"\n\n#include <dune/stuff/common/validation.hh>\n#include <dune/stuff/common/type_utils.hh>\n#include <dune/stuff/common/math.hh>\n#include <dune/stuff/common/random.hh>\n#include <dune/common/tuples.hh>\n#include <dune/common/tupleutility.hh>\n#include <dune/common/exceptions.hh>\n#include <dune/common/bigunsignedint.hh>\n#include <limits>\n#include <iostream>\n\n#include <boost/utility/enable_if.hpp>\n#include <boost/type_traits/is_integral.hpp>\n#include <boost/assign/list_of.hpp>\n#include <boost/array.hpp>\n\nusing namespace Dune::Stuff::Common;\n\ntypedef testing::Types<double, float, // Dune::bigunsignedint,\n                       int, unsigned int, unsigned long, long long, char> MathTestTypes;\n\ntemplate <class T>\nstruct ValidationTest : public testing::Test\n{\n  typedef DefaultRNG<T> RNGType;\n  static const T eps;\n  /** for some weird reason my compiler thinks ValidationTest is an abstract class\n   * if I don't implement \"void TestBody();\"\n   * \\see common_math.cc testcases for why I think it's weird\n   **/\n  void TestBody()\n  {\n    using namespace boost::assign;\n    const int samples = 100000;\n    std::cout << \"\\tTesting Validators for type \" << Typename<T>::value() << \"\\n\\t\\t\" << samples\n              << \" random numbers ...\" << std::endl;\n    {\n      const T lower = std::numeric_limits<T>::min() + eps;\n      const T upper = std::numeric_limits<T>::max() - eps;\n      RNGType rng(lower, upper);\n      for (int i = samples; i > 0; --i) {\n        const T arg = rng();\n        test(lower, upper, arg);\n      }\n      boost::array<T, 10> ar = list_of<T>().repeat_fun(9, rng);\n      ValidateInList<T, boost::array<T, 10>> validator(ar);\n      for (T t : ar) {\n        EXPECT_TRUE(validator(t));\n      }\n      std::vector<T> a;\n      EXPECT_FALSE(ValidateInList<T>(a)(rng()));\n    }\n    std::cout << \"\\t\\tfixed interval\" << std::endl;\n    {\n      const T lower = T(0);\n      const T upper = T(2);\n      const T arg = T(1);\n      test(lower, upper, arg);\n      EXPECT_FALSE(ValidateLess<T>(upper)(lower));\n      EXPECT_FALSE(ValidateGreater<T>(lower)(upper));\n      EXPECT_FALSE(ValidateGreaterOrEqual<T>(lower)(upper + Epsilon<T>::value));\n    }\n    std::cout << \"\\t\\tdone.\" << std::endl;\n  }\n\n  void test(const T lower, const T upper, const T arg) const\n  {\n\n    const T clamped_arg = clamp(arg, T(lower + eps), T(upper - eps));\n    EXPECT_TRUE(ValidateAny<T>()(arg));\n    EXPECT_TRUE(ValidateLess<T>(clamped_arg)(upper));\n    EXPECT_TRUE(ValidateGreaterOrEqual<T>(arg)(lower));\n    EXPECT_TRUE(ValidateGreater<T>(clamped_arg)(lower));\n    EXPECT_TRUE(ValidateInterval<T>(lower, upper)(arg));\n    EXPECT_FALSE(ValidateNone<T>()(arg));\n  }\n};\n\ntemplate <typename T>\nconst T ValidationTest<T>::eps = Epsilon<T>::value;\n\nTYPED_TEST_CASE(ValidationTest, MathTestTypes);\nTYPED_TEST(ValidationTest, All)\n{\n  ValidationTest<TypeParam> k;\n  k.TestBody();\n}\n", "meta": {"hexsha": "576c8a74c2c4a0cdd272c4254364f77aa197c8db", "size": 3097, "ext": "cc", "lang": "C++", "max_stars_repo_path": "dune/stuff/test/common_validation.cc", "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/test/common_validation.cc", "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/test/common_validation.cc", "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": 32.6, "max_line_length": 96, "alphanum_fraction": 0.6577332903, "num_tokens": 822, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.78793120560257, "lm_q2_score": 0.6297746143530797, "lm_q1q2_score": 0.49621907114511565}}
{"text": "#ifndef STAN_MATH_PRIM_MAT_PROB_CATEGORICAL_LOGIT_LPMF_HPP\n#define STAN_MATH_PRIM_MAT_PROB_CATEGORICAL_LOGIT_LPMF_HPP\n\n#include <stan/math/prim/meta.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/arr/fun/log_sum_exp.hpp>\n#include <stan/math/prim/mat/fun/log_softmax.hpp>\n#include <stan/math/prim/mat/fun/log_sum_exp.hpp>\n#include <stan/math/prim/mat/fun/sum.hpp>\n#include <boost/math/tools/promotion.hpp>\n#include <vector>\n\nnamespace stan {\nnamespace math {\n\n// CategoricalLog(n|theta)  [0 < n <= N, theta unconstrained], no checking\ntemplate <bool propto, typename T_prob>\nreturn_type_t<T_prob> categorical_logit_lpmf(\n    int n, const Eigen::Matrix<T_prob, Eigen::Dynamic, 1>& beta) {\n  static const char* function = \"categorical_logit_lpmf\";\n\n  check_bounded(function, \"categorical outcome out of support\", n, 1,\n                beta.size());\n  check_finite(function, \"log odds parameter\", beta);\n\n  if (!include_summand<propto, T_prob>::value) {\n    return 0.0;\n  }\n\n  // FIXME:  wasteful vs. creating term (n-1) if not vectorized\n  return beta(n - 1) - log_sum_exp(beta);  // == log_softmax(beta)(n-1);\n}\n\ntemplate <typename T_prob>\ninline return_type_t<T_prob> categorical_logit_lpmf(\n    int n, const Eigen::Matrix<T_prob, Eigen::Dynamic, 1>& beta) {\n  return categorical_logit_lpmf<false>(n, beta);\n}\n\ntemplate <bool propto, typename T_prob>\nreturn_type_t<T_prob> categorical_logit_lpmf(\n    const std::vector<int>& ns,\n    const Eigen::Matrix<T_prob, Eigen::Dynamic, 1>& beta) {\n  static const char* function = \"categorical_logit_lpmf\";\n\n  for (const auto& x : ns) {\n    check_bounded(function, \"categorical outcome out of support\", x, 1,\n                  beta.size());\n  }\n  check_finite(function, \"log odds parameter\", beta);\n\n  if (!include_summand<propto, T_prob>::value) {\n    return 0.0;\n  }\n\n  if (ns.empty()) {\n    return 0.0;\n  }\n\n  Eigen::Matrix<T_prob, Eigen::Dynamic, 1> log_softmax_beta = log_softmax(beta);\n\n  // FIXME:  replace with more efficient sum()\n  Eigen::Matrix<return_type_t<T_prob>, Eigen::Dynamic, 1> results(ns.size());\n  for (size_t i = 0; i < ns.size(); ++i) {\n    results[i] = log_softmax_beta(ns[i] - 1);\n  }\n  return sum(results);\n}\n\ntemplate <typename T_prob>\ninline return_type_t<T_prob> categorical_logit_lpmf(\n    const std::vector<int>& ns,\n    const Eigen::Matrix<T_prob, Eigen::Dynamic, 1>& beta) {\n  return categorical_logit_lpmf<false>(ns, beta);\n}\n\n}  // namespace math\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "eb7c907a1db99fcbbfd3674e2594ce09786989e9", "size": 2538, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/prim/mat/prob/categorical_logit_lpmf.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/mat/prob/categorical_logit_lpmf.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/mat/prob/categorical_logit_lpmf.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": 31.3333333333, "max_line_length": 80, "alphanum_fraction": 0.706855792, "num_tokens": 731, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.49621905939769406}}
{"text": "#pragma once\n\n#include <Eigen/Cholesky>\n#include <Eigen/Core>\n#include <Eigen/Eigenvalues>\n#include <iostream>\n#include <vector>\n\ntemplate <typename State, typename Input, typename ProcessNoiseVec>\nclass ManifoldCDKF\n{\n public:\n  using Scalar = typename State::Scalar;\n\n  template <int N>\n  using Vec = Eigen::Matrix<Scalar, N, 1>;\n\n  template <int N, int M>\n  using Mat = Eigen::Matrix<Scalar, N, M>;\n\n  using StateCov = Mat<State::tangent_dim_, State::tangent_dim_>;\n\n  using ProcessModelFunc = std::function<State(\n      State const &state, Input const &u, ProcessNoiseVec const &w, Scalar dt)>;\n\n  ManifoldCDKF(State const &state, StateCov const &state_covariance,\n               ProcessModelFunc const &process_model)\n      : state_{state},\n        state_cov_{state_covariance},\n        process_model_{process_model}\n  {\n    if(!process_model_)\n    {\n      throw std::invalid_argument(\"Invalid process_model\");\n    }\n  }\n\n  /// Get current state\n  State getState() const { return state_; }\n  /// Set current state\n  void setState(State const &state) { state_ = state; }\n\n  /// Get current state covariance\n  StateCov getStateCovariance() const { return state_cov_; }\n  /// Set current state covariance\n  void setStateCovariance(StateCov const &cov) { state_cov_ = cov; }\n\n  /**\n   * Set the CDKF sigma point spread parameter. The sigma points are generated\n   * as \\f$ x \\pm h \\sqrt{P} \\f$. The recommended value for gaussian noise is\n   * \\f$ \\sqrt{3} \\f$.\n   *\n   * @param[in] h Sigma point spread parameter\n   */\n  void setParameter(Scalar h) { h_ = h; }\n\n  void setSigmaPointMeanParameters(Scalar threshold,\n                                   unsigned int max_iterations)\n  {\n    sigma_points_mean_threshold_ = threshold;\n    sigma_points_mean_max_iterations_ = max_iterations;\n  }\n\n  /**\n   * Run the process update using the provided process model, input and input\n   * covariance.\n   *\n   * @param[in] dt Time duration since last processUpdate\n   * @param[in] u Input\n   * @param[in] Q Input covariance\n   * @param[in] debug Flag indicating whether to print internal debug messages\n   *\n   * @return True if the process update was successful else false\n   */\n  template <typename InputCov>\n  bool processUpdate(Scalar const dt, Input const &u, InputCov const &Q,\n                     bool debug = false);\n\n  /**\n   * Run the measurement update using the provided measurement model , current\n   * measurement and measurement covariance.\n   *\n   * @param[in] measurement_func takes in the state and returns the expected\n   * measurement with type MeasurementType\n   * @param[in] z Current measurement\n   * @param[in] R Measurement covariance\n   * @param[in] debug Flag indicating whether to print internal debug messages\n   *\n   * @return True if the measurement update was successful else false\n   */\n  template <typename MeasurementFunc, typename MeasurementType,\n            typename MeasCovType>\n  bool measurementUpdate(MeasurementFunc const &measurement_func,\n                         MeasurementType const &z, MeasCovType const &R,\n                         bool debug = false);\n\n  // TODO(Kartik): Add a MeasurementUpdateLinear function\n\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n private:\n  /**\n   * Generate weights for the CDKF equations\n   *\n   * @param[in] L Number of sigma points that would be used\n   *\n   * @return Array containing the 4 weights, [wm0, wm1, wc1, wc2]\n   */\n  std::array<Scalar, 4> generateWeights(unsigned int L) const\n  {\n    Scalar const h_sq = h_ * h_;\n    Scalar const wm0 = (h_sq - L) / h_sq;\n    Scalar const wm1 = 1 / (2 * h_sq);\n    Scalar const wc1 = 1 / (4 * h_sq);\n    Scalar const wc2 = (h_sq - 1) / (4 * h_sq * h_sq);\n    return {wm0, wm1, wc1, wc2};\n  }\n\n  /**\n   * Compute the mean of the sigma points\n   *\n   * @param[in] sigma_points Input sigma points\n   * @param[in] wm0 Weight wm0 for CDKF\n   * @param[in] wm1 Weight wm1 for CDKF\n   *\n   * @return Mean of the sigma points\n   */\n  template <typename T>\n  T meanOfSigmaPoints(\n      std::vector<T, Eigen::aligned_allocator<T>> const &sigma_points,\n      Scalar wm0, Scalar wm1) const\n  {\n    T mean = sigma_points[0];\n    unsigned int iterations = 0;\n    typename T::TangentVec dx;\n    do\n    {\n      dx = wm0 * (sigma_points[0] - mean);\n      for(unsigned int i = 1; i < sigma_points.size(); ++i)\n      {\n        dx += wm1 * (sigma_points[i] - mean);\n      }\n      mean = mean + dx;\n      iterations += 1;\n      // std::cout << \"meanOfSigmaPoints: dx.norm(): \" << dx.norm()\n      //           << \", iterations: \" << iterations << \"\\n\";\n    } while((dx.squaredNorm() >\n             sigma_points_mean_threshold_ * sigma_points_mean_threshold_) &&\n            (iterations < sigma_points_mean_max_iterations_));\n\n    return mean;\n  }\n\n  /**\n   * Calculate the matrix square root of a positive (semi-)definite matrix.\n   *\n   * @param[in] mat The positive (semi-)definite matrix\n   *\n   * @return The square root of the input matrix which satisfies \\f$ret *\n   * ret^{T} = mat\\f$\n   */\n  template <typename Derived>\n  static typename Derived::PlainObject matrixSquareRoot(\n      Eigen::MatrixBase<Derived> const &mat)\n  {\n    // Try LLT first\n    {\n      Eigen::LLT<typename Derived::PlainObject> const cov_chol{mat};\n      if(cov_chol.info() == Eigen::Success)\n      {\n        return cov_chol.matrixL();\n      }\n    }\n    // If not successful, try LDLT\n    {\n      Eigen::LDLT<typename Derived::PlainObject> const cov_chol{mat};\n      if(cov_chol.info() == Eigen::Success)\n      {\n        typename Derived::PlainObject const L = cov_chol.matrixL();\n        auto const &P = cov_chol.transpositionsP();\n        auto const D = cov_chol.vectorD().array();\n        if((D >= 0).all())\n        {\n          auto const D2 = D.sqrt().matrix().asDiagonal();\n          return P.transpose() * L * D2;\n        }\n      }\n    }\n    // If not successful, try eigen-decomposition with slightly inflated\n    // eigenvalues\n    {\n      Eigen::SelfAdjointEigenSolver<typename Derived::PlainObject> const cov_es{\n          mat};\n      auto eigvals = cov_es.eigenvalues().array().eval();\n      auto const lowest_eval = eigvals(0);\n      if(lowest_eval < 0)\n      {\n        eigvals -= lowest_eval;\n      }\n      return cov_es.eigenvectors() * eigvals.sqrt().matrix().asDiagonal() *\n             cov_es.eigenvectors().transpose();\n    }\n  }\n\n  /// State\n  State state_;\n\n  /// State Covariance\n  StateCov state_cov_;\n\n  /// Process model\n  ProcessModelFunc const process_model_;\n\n  /// CDKF Parameter\n  Scalar h_ = std::sqrt(Scalar(3));\n\n  /// Threshold for change in state during sigma point mean computation\n  Scalar sigma_points_mean_threshold_ =\n      10 * std::numeric_limits<Scalar>::epsilon();\n\n  /// Maximum number of iterations for sigma point mean computation\n  unsigned int sigma_points_mean_max_iterations_ = 10;\n};\n\ntemplate <typename State, typename Input, typename ProcNoiseVec>\ntemplate <typename InputCov>\nbool ManifoldCDKF<State, Input, ProcNoiseVec>::processUpdate(Scalar const dt,\n                                                             Input const &u,\n                                                             InputCov const &Q,\n                                                             bool debug)\n{\n  if(dt < 0)\n  {\n    return false;\n  }\n\n  if(debug) // For debugging\n  {\n    std::cout << std::string(32, '=') << \" Process Update \"\n              << std::string(32, '=') << \"\\n\";\n    std::cout << \"State:\\n\" << state_ << std::endl;\n    std::cout << \"state_cov:\\n\" << state_cov_ << std::endl;\n  }\n\n  auto const proc_noise_count = static_cast<unsigned int>(Q.rows());\n  auto const L = State::tangent_dim_ + proc_noise_count;\n\n  // Generate sigma points\n  auto const X = (h_ * matrixSquareRoot(state_cov_)).eval();\n  auto const W = (h_ * matrixSquareRoot(Q)).eval();\n  auto const weights = generateWeights(L);\n  auto const wm0 = weights[0], wm1 = weights[1], wc1 = weights[2],\n             wc2 = weights[3];\n  // auto const [wm0, wm1, wc1, wc2] = generateWeights(L); // In C++17\n\n  std::vector<State, Eigen::aligned_allocator<State>> Xa(2 * L + 1);\n\n  // Apply process model\n  Xa[0] = process_model_(state_, u, ProcNoiseVec::Zero(), dt);\n  for(unsigned int k = 1; k <= State::tangent_dim_; ++k)\n  {\n    Xa[k] = process_model_(state_ + X.col(k - 1), u, ProcNoiseVec::Zero(), dt);\n    Xa[L + k] =\n        process_model_(state_ + -X.col(k - 1), u, ProcNoiseVec::Zero(), dt);\n  }\n  for(unsigned int k = 1; k <= proc_noise_count; ++k)\n  {\n    Xa[State::tangent_dim_ + k] = process_model_(state_, u, W.col(k - 1), dt);\n    Xa[L + State::tangent_dim_ + k] =\n        process_model_(state_, u, -W.col(k - 1), dt);\n  }\n\n  state_ = meanOfSigmaPoints(Xa, wm0, wm1);\n\n  // Covariance\n  state_cov_.setZero();\n  for(unsigned int k = 1; k <= L; ++k)\n  {\n    auto const x1 = Xa[k] - Xa[0];\n    auto const x2 = Xa[L + k] - Xa[0];\n    auto const d1 = (x1 - x2).eval();\n    auto const d2 = (x1 + x2).eval();\n    state_cov_ += wc1 * d1 * d1.transpose() + wc2 * d2 * d2.transpose();\n  }\n\n  if(debug)\n  {\n    std::cout << std::string(80, '=') << \"\\n\";\n  }\n\n  return true;\n}\n\ntemplate <typename State, typename Input, typename ProcessNoiseVec>\ntemplate <typename MeasurementFunc, typename MeasurementType,\n          typename MeasCovType>\nbool ManifoldCDKF<State, Input, ProcessNoiseVec>::measurementUpdate(\n    MeasurementFunc const &measurement_func, MeasurementType const &z,\n    MeasCovType const &R, bool debug)\n{\n  if(debug)\n  {\n    std::cout << std::string(30, '=') << \" Measurement Update \"\n              << std::string(30, '=') << \"\\n\";\n  }\n\n  constexpr unsigned int L = State::tangent_dim_;\n\n  // Generate sigma points\n  auto const X = (h_ * matrixSquareRoot(state_cov_)).eval();\n  auto const weights = generateWeights(L);\n  auto const wm0 = weights[0], wm1 = weights[1], wc1 = weights[2],\n             wc2 = weights[3];\n  // auto const [wm0, wm1, wc1, wc2] = generateWeights(L); // In C++17\n\n  if(debug)\n  {\n    std::cout << \"Pa:\\n\" << state_cov_ << std::endl;\n    std::cout << \"X:\\n\" << X << std::endl;\n  }\n\n  // Apply measurement model\n  std::vector<MeasurementType, Eigen::aligned_allocator<MeasurementType>> Zaa(\n      2 * L + 1);\n\n  Zaa[0] = measurement_func(state_);\n  for(unsigned int k = 1; k <= L; k++)\n  {\n    Zaa[k] = measurement_func(state_ + X.col(k - 1));\n    Zaa[L + k] = measurement_func(state_ + -X.col(k - 1));\n  }\n  if(debug)\n  {\n    for(unsigned int k = 0; k < 2 * L + 1; ++k)\n    {\n      std::cout << \"Z[\" << k << \"]:\\n\" << Zaa[k] << std::endl;\n    }\n  }\n\n  auto const z_pred = meanOfSigmaPoints(Zaa, wm0, wm1);\n\n  // Covariance\n  auto Pzz = MeasCovType::Zero(R.rows(), R.cols()).eval();\n  auto Pxz =\n      Mat<State::tangent_dim_, MeasurementType::tangent_dim_>::Zero().eval();\n  for(unsigned int k = 1; k <= L; k++)\n  {\n    auto const z1 = Zaa[k] - Zaa[0];\n    auto const z2 = Zaa[L + k] - Zaa[0];\n    auto const dz1 = (z1 - z2).eval();\n    auto const dz2 = (z1 + z2).eval();\n    Pzz += wc1 * dz1 * dz1.transpose() + wc2 * dz2 * dz2.transpose();\n    Pxz += wm1 * X.col(k - 1) * dz1.transpose();\n  }\n  Pzz += R;\n\n  // Innovation\n  auto const inno = decltype(z_pred){z} - z_pred;\n  if(debug)\n  {\n    std::cout << \"z:\\n\" << z << \"\\n\";\n    std::cout << \"z_pred:\\n\" << z_pred << \"\\n\";\n    std::cout << \"Pxz:\\n\" << Pxz << \"\\n\";\n    std::cout << \"Pzz:\\n\" << Pzz << \"\\n\";\n    // Kalman Gain;\n    auto const K = Pxz * Pzz.inverse();\n    std::cout << \"K:\\n\" << K << \"\\n\";\n    std::cout << \"inno: \" << inno.transpose() << \"\\n\";\n  }\n\n  auto dx = State::TangentVec::Zero().eval();\n\n  auto const Pzz_llt = Pzz.llt();\n  if(Pzz_llt.info() == Eigen::Success) // Pzz is positive-definite\n  {\n    dx = Pxz * Pzz_llt.solve(inno);\n    // Covariance around the old mean\n    state_cov_ -= Pxz * Pzz_llt.solve(Pxz.transpose());\n  }\n  else\n  {\n    // Pzz is not positive definite, try LDLT\n    auto const Pzz_ldlt = Pzz.ldlt();\n    if(Pzz_ldlt.info() == Eigen::Success) // Pzz is positive semi-definite\n    {\n      dx = Pxz * Pzz_ldlt.solve(inno);\n      // Covariance around the old mean\n      state_cov_ -= Pxz * Pzz_ldlt.solve(Pxz.transpose());\n    }\n  }\n\n  // Make sure that diagonal elements of state_cov_ are non-negative\n  for(unsigned int i = 0; i < State::tangent_dim_; ++i)\n  {\n    if(state_cov_(i, i) < 0)\n    {\n      for(unsigned int j = 0; j < State::tangent_dim_; ++j)\n      {\n        state_cov_(i, j) = 0;\n        state_cov_(j, i) = 0;\n      }\n    }\n  }\n\n  if(debug)\n  {\n    std::cout << \"dx: \" << dx.transpose() << \"\\n\";\n    std::cout << \"state_cov:\\n\" << state_cov_ << \"\\n\";\n  }\n\n  // Compute the mean and move the covariance to be around the new mean\n  auto const X_new = (h_ * matrixSquareRoot(state_cov_)).eval();\n  if(debug)\n  {\n    std::cout << \"X_new:\\n\" << X_new << \"\\n\";\n  }\n\n  std::vector<State, Eigen::aligned_allocator<State>> Xa(2 * L + 1);\n  Xa[0] = state_ + dx;\n  for(unsigned int k = 1; k <= L; k++)\n  {\n    Xa[k] = state_ + (dx + X_new.col(k - 1));\n    Xa[L + k] = state_ + (dx - X_new.col(k - 1));\n  }\n\n  // Get mean\n  state_ = meanOfSigmaPoints(Xa, wm0, wm1);\n\n  // Calculate covariance around the new mean\n  state_cov_.setZero();\n  for(unsigned int k = 1; k <= L; ++k)\n  {\n    auto const x1 = Xa[k] - Xa[0];\n    auto const x2 = Xa[L + k] - Xa[0];\n    auto const d1 = x1 - x2;\n    auto const d2 = x1 + x2;\n    state_cov_ += wc1 * d1 * d1.transpose() + wc2 * d2 * d2.transpose();\n  }\n\n  if(debug)\n  {\n    std::cout << std::string(80, '=') << \"\\n\";\n  }\n\n  return true;\n}\n", "meta": {"hexsha": "6b87c58f3645de136e92e5b8e7aee3850554242a", "size": 13394, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/manifold_cdkf/manifold_cdkf.hpp", "max_stars_repo_name": "kartikmohta/manifold_cdkf", "max_stars_repo_head_hexsha": "e000ca7ab24721f300ab2d0737e2a2d9cc0db912", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-03-04T03:29:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-11T12:58:20.000Z", "max_issues_repo_path": "include/manifold_cdkf/manifold_cdkf.hpp", "max_issues_repo_name": "kartikmohta/manifold_cdkf", "max_issues_repo_head_hexsha": "e000ca7ab24721f300ab2d0737e2a2d9cc0db912", "max_issues_repo_licenses": ["Apache-2.0"], "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/manifold_cdkf/manifold_cdkf.hpp", "max_forks_repo_name": "kartikmohta/manifold_cdkf", "max_forks_repo_head_hexsha": "e000ca7ab24721f300ab2d0737e2a2d9cc0db912", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-11-12T13:04:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-10T23:04:34.000Z", "avg_line_length": 29.9642058166, "max_line_length": 80, "alphanum_fraction": 0.6013886815, "num_tokens": 3866, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.49621905939769395}}
{"text": "#include <boost/math/distributions/rayleigh.hpp>\n", "meta": {"hexsha": "b05f4ba2bae1461ca3e76b484517a53ba5f78601", "size": 49, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_distributions_rayleigh.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_distributions_rayleigh.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_distributions_rayleigh.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 24.5, "max_line_length": 48, "alphanum_fraction": 0.8163265306, "num_tokens": 11, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095992, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4961828003893018}}
{"text": "#include <boost/math/special_functions/owens_t.hpp>\n", "meta": {"hexsha": "ea4ccc321de7625edf69341f681991cfff943780", "size": 52, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_special_functions_owens_t.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_special_functions_owens_t.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_special_functions_owens_t.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 26.0, "max_line_length": 51, "alphanum_fraction": 0.8269230769, "num_tokens": 13, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.49618280038930174}}
{"text": "/**\n * @file nbc_test.cpp\n *\n * Test for the Naive Bayes classifier.\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#include <mlpack/core.hpp>\n#include <mlpack/methods/naive_bayes/naive_bayes_classifier.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n\nusing namespace mlpack;\nusing namespace naive_bayes;\n\nBOOST_AUTO_TEST_SUITE(NBCTest);\n\nBOOST_AUTO_TEST_CASE(NaiveBayesClassifierTest)\n{\n  const char* trainFilename = \"trainSet.csv\";\n  const char* testFilename = \"testSet.csv\";\n  const char* trainResultFilename = \"trainRes.csv\";\n  const char* testResultFilename = \"testRes.csv\";\n  const char* testResultProbsFilename = \"testResProbs.csv\";\n  size_t classes = 2;\n\n  arma::mat trainData, trainRes, calcMat;\n  data::Load(trainFilename, trainData, true);\n  data::Load(trainResultFilename, trainRes, true);\n\n  // Get the labels out.\n  arma::Row<size_t> labels(trainData.n_cols);\n  for (size_t i = 0; i < trainData.n_cols; ++i)\n    labels[i] = trainData(trainData.n_rows - 1, i);\n  trainData.shed_row(trainData.n_rows - 1);\n\n  NaiveBayesClassifier<> nbcTest(trainData, labels, classes);\n\n  size_t dimension = nbcTest.Means().n_rows;\n  calcMat.zeros(2 * dimension + 1, classes);\n\n  for (size_t i = 0; i < dimension; i++)\n  {\n    for (size_t j = 0; j < classes; j++)\n    {\n      calcMat(i, j) = nbcTest.Means()(i, j);\n      calcMat(i + dimension, j) = nbcTest.Variances()(i, j);\n    }\n  }\n\n  for (size_t i = 0; i < classes; i++)\n    calcMat(2 * dimension, i) = nbcTest.Probabilities()(i);\n\n  for (size_t i = 0; i < calcMat.n_rows; i++)\n    for (size_t j = 0; j < classes; j++)\n      BOOST_REQUIRE_CLOSE(trainRes(i, j) + .00001, calcMat(i, j), 0.01);\n\n  arma::mat testData;\n  arma::Mat<size_t> testRes;\n  arma::mat testResProbs;\n  arma::Row<size_t> calcVec;\n  arma::mat calcProbs;\n  data::Load(testFilename, testData, true);\n  data::Load(testResultFilename, testRes, true);\n  data::Load(testResultProbsFilename, testResProbs, true);\n\n  testData.shed_row(testData.n_rows - 1); // Remove the labels.\n\n  nbcTest.Classify(testData, calcVec, calcProbs);\n\n  for (size_t i = 0; i < testData.n_cols; i++)\n    BOOST_REQUIRE_EQUAL(testRes(i), calcVec(i));\n\n  for (size_t i = 0; i < testResProbs.n_cols; ++i)\n  {\n    for (size_t j = 0; j < testResProbs.n_rows; ++j)\n    {\n      BOOST_REQUIRE_CLOSE(testResProbs(j, i) + 0.0001, calcProbs(j, i) + 0.0001,\n          0.01);\n    }\n  }\n}\n\n// The same test, but this one uses the incremental algorithm to calculate\n// variance.\nBOOST_AUTO_TEST_CASE(NaiveBayesClassifierIncrementalTest)\n{\n  const char* trainFilename = \"trainSet.csv\";\n  const char* testFilename = \"testSet.csv\";\n  const char* trainResultFilename = \"trainRes.csv\";\n  const char* testResultFilename = \"testRes.csv\";\n  const char* testResultProbsFilename = \"testResProbs.csv\";\n  size_t classes = 2;\n\n  arma::mat trainData, trainRes, calcMat;\n  data::Load(trainFilename, trainData, true);\n  data::Load(trainResultFilename, trainRes, true);\n\n  // Get the labels out.\n  arma::Row<size_t> labels(trainData.n_cols);\n  for (size_t i = 0; i < trainData.n_cols; ++i)\n    labels[i] = trainData(trainData.n_rows - 1, i);\n  trainData.shed_row(trainData.n_rows - 1);\n\n  NaiveBayesClassifier<> nbcTest(trainData, labels, classes, true);\n\n  size_t dimension = nbcTest.Means().n_rows;\n  calcMat.zeros(2 * dimension + 1, classes);\n\n  for (size_t i = 0; i < dimension; i++)\n  {\n    for (size_t j = 0; j < classes; j++)\n    {\n      calcMat(i, j) = nbcTest.Means()(i, j);\n      calcMat(i + dimension, j) = nbcTest.Variances()(i, j);\n    }\n  }\n\n  for (size_t i = 0; i < classes; i++)\n    calcMat(2 * dimension, i) = nbcTest.Probabilities()(i);\n\n  for (size_t i = 0; i < calcMat.n_cols; i++)\n    for (size_t j = 0; j < classes; j++)\n      BOOST_REQUIRE_CLOSE(trainRes(j, i) + .00001, calcMat(j, i), 0.01);\n\n  arma::mat testData;\n  arma::Mat<size_t> testRes;\n  arma::mat testResProba;\n  arma::Row<size_t> calcVec;\n  arma::mat calcProbs;\n  data::Load(testFilename, testData, true);\n  data::Load(testResultFilename, testRes, true);\n  data::Load(testResultProbsFilename, testResProba, true);\n\n  testData.shed_row(testData.n_rows - 1); // Remove the labels.\n\n  nbcTest.Classify(testData, calcVec, calcProbs);\n\n  for (size_t i = 0; i < testData.n_cols; i++)\n    BOOST_REQUIRE_EQUAL(testRes(i), calcVec(i));\n\n  for (size_t i = 0; i < testResProba.n_cols; ++i)\n    for (size_t j = 0; j < testResProba.n_rows; ++j)\n    {\n      BOOST_REQUIRE_CLOSE(\n          testResProba(j, i) + .00001, calcProbs(j, i) + .00001, 0.01);\n    }\n}\n\n/**\n * Ensure that separate training gives the same model.\n */\nBOOST_AUTO_TEST_CASE(SeparateTrainTest)\n{\n  const char* trainFilename = \"trainSet.csv\";\n  const char* trainResultFilename = \"trainRes.csv\";\n  size_t classes = 2;\n\n  arma::mat trainData, trainRes, calcMat;\n  data::Load(trainFilename, trainData, true);\n  data::Load(trainResultFilename, trainRes, true);\n\n  // Get the labels out.\n  arma::Row<size_t> labels(trainData.n_cols);\n  for (size_t i = 0; i < trainData.n_cols; ++i)\n    labels[i] = trainData(trainData.n_rows - 1, i);\n  trainData.shed_row(trainData.n_rows - 1);\n\n  NaiveBayesClassifier<> nbc(trainData, labels, classes, true);\n  NaiveBayesClassifier<> nbcTrain(trainData.n_rows, classes);\n  nbcTrain.Train(trainData, labels, classes, false);\n\n  BOOST_REQUIRE_EQUAL(nbc.Means().n_rows, nbcTrain.Means().n_rows);\n  BOOST_REQUIRE_EQUAL(nbc.Means().n_cols, nbcTrain.Means().n_cols);\n  BOOST_REQUIRE_EQUAL(nbc.Variances().n_rows, nbcTrain.Variances().n_rows);\n  BOOST_REQUIRE_EQUAL(nbc.Variances().n_cols, nbcTrain.Variances().n_cols);\n  BOOST_REQUIRE_EQUAL(nbc.Probabilities().n_elem,\n                      nbcTrain.Probabilities().n_elem);\n\n  for (size_t i = 0; i < nbc.Means().n_elem; ++i)\n  {\n    if (std::abs(nbc.Means()[i]) < 1e-5)\n      BOOST_REQUIRE_SMALL(nbcTrain.Means()[i], 1e-5);\n    else\n      BOOST_REQUIRE_CLOSE(nbc.Means()[i], nbcTrain.Means()[i], 1e-5);\n  }\n\n  for (size_t i = 0; i < nbc.Variances().n_elem; ++i)\n  {\n    if (std::abs(nbc.Variances()[i]) < 1e-5)\n      BOOST_REQUIRE_SMALL(nbcTrain.Variances()[i], 1e-5);\n    else\n      BOOST_REQUIRE_CLOSE(nbc.Variances()[i], nbcTrain.Variances()[i], 1e-5);\n  }\n\n  for (size_t i = 0; i < nbc.Probabilities().n_elem; ++i)\n  {\n    if (std::abs(nbc.Probabilities()[i]) < 1e-5)\n      BOOST_REQUIRE_SMALL(nbcTrain.Probabilities()[i], 1e-5);\n    else\n      BOOST_REQUIRE_CLOSE(nbc.Probabilities()[i], nbcTrain.Probabilities()[i],\n          1e-5);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(SeparateTrainIncrementalTest)\n{\n  const char* trainFilename = \"trainSet.csv\";\n  const char* trainResultFilename = \"trainRes.csv\";\n  size_t classes = 2;\n\n  arma::mat trainData, trainRes, calcMat;\n  data::Load(trainFilename, trainData, true);\n  data::Load(trainResultFilename, trainRes, true);\n\n  // Get the labels out.\n  arma::Row<size_t> labels(trainData.n_cols);\n  for (size_t i = 0; i < trainData.n_cols; ++i)\n    labels[i] = trainData(trainData.n_rows - 1, i);\n  trainData.shed_row(trainData.n_rows - 1);\n\n  NaiveBayesClassifier<> nbc(trainData, labels, classes, true);\n  NaiveBayesClassifier<> nbcTrain(trainData.n_rows, classes);\n  nbcTrain.Train(trainData, labels, classes, true);\n\n  BOOST_REQUIRE_EQUAL(nbc.Means().n_rows, nbcTrain.Means().n_rows);\n  BOOST_REQUIRE_EQUAL(nbc.Means().n_cols, nbcTrain.Means().n_cols);\n  BOOST_REQUIRE_EQUAL(nbc.Variances().n_rows, nbcTrain.Variances().n_rows);\n  BOOST_REQUIRE_EQUAL(nbc.Variances().n_cols, nbcTrain.Variances().n_cols);\n  BOOST_REQUIRE_EQUAL(nbc.Probabilities().n_elem,\n                      nbcTrain.Probabilities().n_elem);\n\n  for (size_t i = 0; i < nbc.Means().n_elem; ++i)\n  {\n    if (std::abs(nbc.Means()[i]) < 1e-5)\n      BOOST_REQUIRE_SMALL(nbcTrain.Means()[i], 1e-5);\n    else\n      BOOST_REQUIRE_CLOSE(nbc.Means()[i], nbcTrain.Means()[i], 1e-5);\n  }\n\n  for (size_t i = 0; i < nbc.Variances().n_elem; ++i)\n  {\n    if (std::abs(nbc.Variances()[i]) < 1e-5)\n      BOOST_REQUIRE_SMALL(nbcTrain.Variances()[i], 1e-5);\n    else\n      BOOST_REQUIRE_CLOSE(nbc.Variances()[i], nbcTrain.Variances()[i], 1e-5);\n  }\n\n  for (size_t i = 0; i < nbc.Probabilities().n_elem; ++i)\n  {\n    if (std::abs(nbc.Probabilities()[i]) < 1e-5)\n      BOOST_REQUIRE_SMALL(nbcTrain.Probabilities()[i], 1e-5);\n    else\n      BOOST_REQUIRE_CLOSE(nbc.Probabilities()[i], nbcTrain.Probabilities()[i],\n          1e-5);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(SeparateTrainIndividualIncrementalTest)\n{\n  const char* trainFilename = \"trainSet.csv\";\n  const char* trainResultFilename = \"trainRes.csv\";\n  size_t classes = 2;\n\n  arma::mat trainData, trainRes, calcMat;\n  data::Load(trainFilename, trainData, true);\n  data::Load(trainResultFilename, trainRes, true);\n\n  // Get the labels out.\n  arma::Row<size_t> labels(trainData.n_cols);\n  for (size_t i = 0; i < trainData.n_cols; ++i)\n    labels[i] = trainData(trainData.n_rows - 1, i);\n  trainData.shed_row(trainData.n_rows - 1);\n\n  NaiveBayesClassifier<> nbc(trainData, labels, classes, true);\n  NaiveBayesClassifier<> nbcTrain(trainData.n_rows, classes);\n  for (size_t i = 0; i < trainData.n_cols; ++i)\n    nbcTrain.Train(trainData.col(i), labels[i]);\n\n  BOOST_REQUIRE_EQUAL(nbc.Means().n_rows, nbcTrain.Means().n_rows);\n  BOOST_REQUIRE_EQUAL(nbc.Means().n_cols, nbcTrain.Means().n_cols);\n  BOOST_REQUIRE_EQUAL(nbc.Variances().n_rows, nbcTrain.Variances().n_rows);\n  BOOST_REQUIRE_EQUAL(nbc.Variances().n_cols, nbcTrain.Variances().n_cols);\n  BOOST_REQUIRE_EQUAL(nbc.Probabilities().n_elem,\n                      nbcTrain.Probabilities().n_elem);\n\n  for (size_t i = 0; i < nbc.Means().n_elem; ++i)\n  {\n    if (std::abs(nbc.Means()[i]) < 1e-5)\n      BOOST_REQUIRE_SMALL(nbcTrain.Means()[i], 1e-5);\n    else\n      BOOST_REQUIRE_CLOSE(nbc.Means()[i], nbcTrain.Means()[i], 1e-5);\n  }\n\n  for (size_t i = 0; i < nbc.Variances().n_elem; ++i)\n  {\n    if (std::abs(nbc.Variances()[i]) < 1e-5)\n      BOOST_REQUIRE_SMALL(nbcTrain.Variances()[i], 1e-5);\n    else\n      BOOST_REQUIRE_CLOSE(nbc.Variances()[i], nbcTrain.Variances()[i], 1e-5);\n  }\n\n  for (size_t i = 0; i < nbc.Probabilities().n_elem; ++i)\n  {\n    if (std::abs(nbc.Probabilities()[i]) < 1e-5)\n      BOOST_REQUIRE_SMALL(nbcTrain.Probabilities()[i], 1e-5);\n    else\n      BOOST_REQUIRE_CLOSE(nbc.Probabilities()[i], nbcTrain.Probabilities()[i],\n          1e-5);\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "c8f26d03b63d4791e47e477409c2ed9be427935e", "size": 10513, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/nbc_test.cpp", "max_stars_repo_name": "RMaron/mlpack", "max_stars_repo_head_hexsha": "a179a2708d9555ab7ee4b1e90e0c290092edad2e", "max_stars_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-01-04T04:20:29.000Z", "max_stars_repo_stars_event_max_datetime": "2016-07-21T23:30:34.000Z", "max_issues_repo_path": "src/mlpack/tests/nbc_test.cpp", "max_issues_repo_name": "RMaron/mlpack", "max_issues_repo_head_hexsha": "a179a2708d9555ab7ee4b1e90e0c290092edad2e", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2017-01-23T18:39:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-15T13:58:34.000Z", "max_forks_repo_path": "src/mlpack/tests/nbc_test.cpp", "max_forks_repo_name": "RMaron/mlpack", "max_forks_repo_head_hexsha": "a179a2708d9555ab7ee4b1e90e0c290092edad2e", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-01-20T00:54:34.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-16T05:34:32.000Z", "avg_line_length": 33.0597484277, "max_line_length": 80, "alphanum_fraction": 0.6740226386, "num_tokens": 3319, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.49618280038930174}}
{"text": "#include \"highgui.h\"\n#include \"imgproc.h\"\n#include \"feature.h\"\n#include <armadillo>\n#include <vector>\n#include <cmath>\n#include <cassert>\n\nusing namespace arma;\nusing namespace std;\n\nstatic void mergesort(vec &keys, uvec &values);\nstatic mat atan2(const mat &Y, const mat &X);\n\n// try to get adaptive thresholding working\nmat edge2(const mat &F, int op) {\n  switch (op) {\n    case EDGE_SOBEL:\n      return sobel_edge2(F);\n    case EDGE_CANNY:\n      return canny2(F);\n    case EDGE_DOG:\n      return dog2(F);\n    case EDGE_LOG:\n      return log2(F);\n    default:\n      return mat();\n  }\n}\n\ncube edge2(const cube &F, int op) {\n  return gray2rgb(edge2(rgb2gray(F), op));\n}\n\nmat sobel_edge2(const mat &F, uword n, double sigma2) {\n  // smooth first\n  mat H = conv2(F, gauss2(n, sigma2));\n  mat DX, DY;\n  gradient2(DX, DY, H);\n  mat G = sqrt(DX % DX + DY % DY);\n  return G;\n}\n\nmat canny2(const mat &F, double low, double high, uword n, double sigma2) { // not the complete canny\n  // filter\n  mat H = conv2(F, gauss2(n, sigma2));\n  // intensity gradient\n  mat DX, DY;\n  gradient2(DX, DY, H);\n  // non-maximal suppression\n  mat G = sqrt(DX % DX + DY % DY);\n  mat T = atan2(DY, DX);\n  H = nmm2(G, T);\n  G /= G.max(); // normalise\n  // double threshold\n  mat strong = (G >= high) % H;\n  mat weak = (low < G && G < high) % H;\n  // hysteresis edge-tracking\n//  mat K = strong + weak;\n//  K /= K;\n  return strong;\n}\n\nmat dog2(const mat &F, double alpha, uword n, double sigma2) {\n  return F - alpha * conv2(F, gauss2(n, sigma2));\n}\n\nmat log2(const mat &F, uword n, double sigma2) {\n  return conv2(F, laplace_gauss2(n, sigma2));\n}\n\nvoid blob2(const mat &F, vector<vec> &centroids) {\n  mat visited(F.n_rows, F.n_cols, fill::zeros);\n  vector<ivec> tovisit;\n  size_t nvisited = 0;\n  centroids.clear();\n  ivec pt;\n  vec mid(2);\n  int npts;\n  for (uword i = 0; i < F.n_rows; i++) {\n    for (uword j = 0; j < F.n_cols; j++) {\n      if (!visited(i, j)) {\n        mid.zeros();\n        npts = 0;\n        tovisit.push_back(ivec({(sword)i,(sword)j}));\n        visited(i,j) = 1;\n        while (tovisit.size() > nvisited) {\n          pt = tovisit[nvisited];\n          if (pt(0)-1>=0 && !visited(pt(0)-1,pt(1)) && F(pt(0)-1,pt(1)) == F(pt(0),pt(1))) {\n            visited(pt(0)-1,pt(1)) = 1;\n            tovisit.push_back(ivec({pt(0)-1,pt(1)}));\n          }\n          if (pt(0)+1<F.n_rows && !visited(pt(0)+1,pt(1)) && F(pt(0)+1,pt(1)) == F(pt(0),pt(1))) {\n            visited(pt(0)+1,pt(1)) = 1;\n            tovisit.push_back(ivec({pt(0)+1,pt(1)}));\n          }\n          if (pt(1)-1>=0 && !visited(pt(0),pt(1)-1) && F(pt(0),pt(1)-1) == F(pt(0),pt(1))) {\n            visited(pt(0),pt(1)-1) = 1;\n            tovisit.push_back(ivec({pt(0),pt(1)-1}));\n          }\n          if (pt(1)+1<F.n_cols && !visited(pt(0),pt(1)+1) && F(pt(0),pt(1)+1) == F(pt(0),pt(1))) {\n            visited(pt(0),pt(1)+1) = 1;\n            tovisit.push_back(ivec({pt(0),pt(1)+1}));\n          }\n          mid += vec({(double)pt(0), (double)pt(1)});\n          npts++;\n          nvisited++;\n        }\n        if (npts > 24) {\n          centroids.push_back(mid/npts);\n        }\n      }\n    }\n  }\n}\n\nmat corner2(const mat &I, int op) {\n  switch (op) {\n    case CORNER_SOBEL:\n      return sobel_corner2(I);\n    case CORNER_HARRIS:\n      return harris2(I, reshape(mat({1,2,1,2,4,2,1,2,1}),3,3)/16.0);\n    default:\n      return mat();\n  }\n}\n\nmat sobel_corner2(const mat &F, uword n, double sigma2) {\n  mat H = reshape(mat({\n    1, -2, 1,\n    -2, 4, -2,\n    1, -2, 1\n  }), 3, 3).t();\n  mat G = conv2(F, gauss2(n, sigma2));\n  G = conv2(G, H);\n}\n\nmat harris2(const mat &I, const mat &W) {\n  assert(W.n_rows == W.n_cols);\n  mat DX, DY;\n  gradient2(DX, DY, I); // grab the gradients\n  // place gradients into padded matrix\n  mat wIxx = conv2(DX % DX, W);\n  mat wIxy = conv2(DX % DY, W);\n  mat wIyy = conv2(DY % DY, W);\n  // find the taylor expansion-based corner detector\n  //double k = 0.07;\n  //return ((wIxx % wIyy) - (wIxy % wIxy)) - (k * ((wIxx + wIyy) % (wIxx + wIyy)));\n  double eps = 0.05;\n  return 2.0 * ((wIxx % wIyy) - (wIxy % wIxy)) / (wIxx + wIyy + eps);\n}\n\nmat lines2(const mat &I, const vector<vec> &pts, int op) {\n  assert(op == LINE_RANSAC || op == LINE_HOUGH);\n  switch (op) {\n    case LINE_RANSAC:\n      return ransac(pts, 10.0, (int)pts.size());\n    case LINE_HOUGH:\n      return hough_line(pts, 0.5, I.n_rows, I.n_cols);\n    default:\n      return mat();\n  }\n}\n\nmat ransac(const vector<vec> &pts, double sigma2, int k) {\n  int consensus = 0;\n  vec pt1, pt2;\n  int i1, i2;\n  int ind1 = 0, ind2 = 0;\n  for (int i = 0; i < k; i++) {\n    // choose two random points\n    i1 = i;\n    i2 = rand() % pts.size();\n    while (i1 == i2) {\n      i2 = rand() % pts.size();\n    }\n\n    // fit a particular model\n    vec u_i2_i1 = normalise(pts[i2] - pts[i1]);\n\n    // get the set of inliers that are close enough to the line\n    int hyp_consensus = 0;\n    for (int j = 0; j < k; j++) {\n      // compute the distance from the point\n      vec v_j_i1 = pts[j] - pts[i1];\n      vec para = dot(v_j_i1.t(), u_i2_i1) * u_i2_i1;\n      vec perp = v_j_i1 - para;\n      double distance = sqrt(dot(perp, perp));\n      if (distance < sigma2) {\n        hyp_consensus++;\n      }\n    }\n\n    // compare the consensus to the known consensus\n    // if larger, then replace\n    if (hyp_consensus > consensus) {\n      pt1 = pts[i1];\n      pt2 = pts[i2];\n      consensus = hyp_consensus;\n      ind1 = i1;\n      ind2 = i2;\n    } else if (consensus == 0) {\n      i = 0; // keep repeating until a consensus is reached\n    }\n  }\n\n  mat ans(2, 2);\n  ans.col(0) = pt1;\n  ans.col(1) = pt2;\n  return ans;\n}\n\nmat hough_line(const vector<vec> &pts, double sigma2, size_t n_rows, size_t n_cols) {\n  // create an accumulator\n  mat accumulator(2 * (n_rows + n_cols), 180, fill::zeros); // radius, degrees\n  for (const vec &pt : pts) {\n    for (uword theta = 0; theta < accumulator.n_cols; theta++) {\n      double rad = (double)theta * M_PI / 180.0;\n      double y = pt(0);\n      double x = pt(1);\n      uword r = (uword)(y * sin(rad) + x * cos(rad)) + n_rows + n_cols;\n      if (r < accumulator.n_rows && r != (n_rows + n_cols)) { // error otherwise\n        accumulator(r, theta) += 1.0;\n      }\n    }\n  }\n  // find the approximate gradient of the accumulator\n  mat DX, DY;\n  gradient2(DX, DY, accumulator);\n  mat theta = atan2(DY, DX);\n  mat radius = sqrt(DX % DX + DY % DY);\n  accumulator = nmm2(accumulator, theta, 2);\n  accumulator /= accumulator.max(); // normalized\n\n  mat II = imresize2(accumulator, 500, accumulator.n_cols);\n  II /= II.max();\n  disp_image(\"accumulator\", II);\n  disp_wait();\n\n  // now grab all the local maximums\n  uvec ind = find(accumulator > 0.0);\n  vec votes(ind.n_elem);\n  mat rt(3, ind.n_elem);\n  for (uword i = 0; i < ind.n_elem; i++) {\n    rt.col(i) = vec({ 0.0,\n        (double)(ind(i) % accumulator.n_rows),\n        (double)(ind(i) / accumulator.n_rows) });\n    uword radius = rt(1, i);\n    uword theta = rt(2, i);\n    votes(i) = accumulator(radius, theta);\n    rt(0, i) = votes(i);\n  }\n\n  // sort them to get the best matches\n  uvec vv = cumsum(ones<uvec>(votes.n_elem)) - 1;\n  mergesort(votes, vv);\n  mat hlines(3, ind.n_elem);\n  for (uword i = 0; i < vv.n_elem; i++) {\n    uword j = vv(i);\n    hlines.col(i) = rt.col(j);\n  }\n  hlines.row(1) -= (n_rows + n_cols);\n\n  return hlines;\n}\n\n// TODO\nmat hough_circle(const vector<vec> &pts, double sigma2, size_t n_rows, size_t n_cols) {\n  cube accumulator(n_rows, n_cols, 2 * (n_rows + n_cols), fill::zeros);\n  for (uword R = 0; R < accumulator.n_slices; R++) {\n    for (vec pt : pts) {\n      accumulator(pt(0), pt(1), R) += 1.0;\n    }\n  }\n  return accumulator;\n}\n\n// STATIC\n\nstatic void mergesort(vec &keys, uvec &values) {\n  if (keys.size() == 1) {\n    return;\n  }\n  uword mid = keys.n_elem/2;\n  vec keys1 = keys(span(0,mid-1));\n  vec keys2 = keys(span(mid,keys.n_elem-1));\n  uvec values1 = values(span(0,mid-1));\n  uvec values2 = values(span(mid,keys.n_elem-1));\n  mergesort(keys1, values1);\n  mergesort(keys2, values2);\n  uword i = 0, j = 0, k = 0;\n  while (k < keys.n_elem) {\n    if (i == keys1.n_elem) {\n      keys(k) = keys2(j);\n      values(k) = values2(j);\n      j++;\n      k++;\n    } else if (j == keys2.n_elem || keys1(i) > keys2(j)) {\n      keys(k) = keys1(i);\n      values(k) = values1(i);\n      i++;\n      k++;\n    } else {\n      keys(k) = keys2(j);\n      values(k) = values2(j);\n      j++;\n      k++;\n    }\n  }\n}\n\nstatic mat atan2(const mat &Y, const mat &X) {\n  assert(Y.n_rows == X.n_rows && Y.n_cols == X.n_cols);\n  mat ans(Y.n_rows, Y.n_cols);\n  for (uword i = 0; i < ans.n_rows; i++) {\n    for (uword j = 0; j < ans.n_cols; j++) {\n      ans(i, j) = atan2(Y(i, j), X(i, j));\n    }\n  }\n  return ans;\n}\n", "meta": {"hexsha": "6db02c8348c7ab0acc056b1c0ce880cdba4fee19", "size": 8703, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "visual/test_cpu/feature.cpp", "max_stars_repo_name": "timrobot/Tachikoma-Project", "max_stars_repo_head_hexsha": "c7af70f2c58fe43f25331fd03589845480ae0f16", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-11-11T19:04:33.000Z", "max_stars_repo_stars_event_max_datetime": "2016-11-11T19:04:33.000Z", "max_issues_repo_path": "visual/test_cpu/feature.cpp", "max_issues_repo_name": "TimothyYong/Tachikoma-Project", "max_issues_repo_head_hexsha": "c7af70f2c58fe43f25331fd03589845480ae0f16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "visual/test_cpu/feature.cpp", "max_forks_repo_name": "TimothyYong/Tachikoma-Project", "max_forks_repo_head_hexsha": "c7af70f2c58fe43f25331fd03589845480ae0f16", "max_forks_repo_licenses": ["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.0279503106, "max_line_length": 101, "alphanum_fraction": 0.5546363323, "num_tokens": 3009, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.6001883592602049, "lm_q1q2_score": 0.4961828003893016}}
{"text": "#include \"fa_hierarchy.h\"\n\n#include <google/protobuf/stubs/casts.h>\n\n#include <Eigen/Dense>\n#include <cassert>\n#include <iostream>\n#include <stan/math/prim/prob.hpp>\n#include <vector>\n\n#include \"algorithm_state.pb.h\"\n#include \"hierarchy_prior.pb.h\"\n#include \"ls_state.pb.h\"\n#include \"src/utils/proto_utils.h\"\n#include \"src/utils/rng.h\"\n\ndouble FAHierarchy::like_lpdf(const Eigen::RowVectorXd& datum) const {\n  using stan::math::NEG_LOG_SQRT_TWO_PI;\n  double base = (Eigen::MatrixXd(state.cov_chol.matrixL()))\n                    .diagonal()\n                    .array()\n                    .log()\n                    .sum() -\n                NEG_LOG_SQRT_TWO_PI * dim;\n  double exp =\n      0.5 * ((datum.transpose() - state.mu)\n                 .dot(state.cov_chol.solve((datum.transpose() - state.mu))));\n  return -(base + exp);\n}\n\nFA::State FAHierarchy::draw(const FA::Hyperparams& params) {\n  auto& rng = bayesmix::Rng::Instance().get();\n  FA::State out;\n  out.mu = params.mutilde;\n  out.psi = params.beta / (params.alpha0 + 1.);\n  out.eta = Eigen::MatrixXd::Zero(card, params.q);\n  out.lambda = Eigen::MatrixXd::Zero(dim, params.q);\n\n  for (size_t j = 0; j < dim; j++) {\n    out.mu[j] =\n        stan::math::normal_rng(params.mutilde[j], sqrt(params.phi), rng);\n\n    out.psi[j] = stan::math::inv_gamma_rng(params.alpha0, params.beta[j], rng);\n\n    for (size_t i = 0; i < params.q; i++) {\n      out.lambda(j, i) = stan::math::normal_rng(0, 1, rng);\n    }\n  }\n\n  for (size_t i = 0; i < card; i++) {\n    for (size_t j = 0; j < params.q; j++) {\n      out.eta(i, j) = stan::math::normal_rng(0, 1, rng);\n    }\n  }\n\n  out.psi_inverse = out.psi.cwiseInverse().asDiagonal();\n  out.cov_chol = (out.lambda * out.lambda.transpose() +\n                  Eigen::MatrixXd(out.psi.asDiagonal()))\n                     .llt();\n\n  return out;\n}\n\nvoid FAHierarchy::initialize_state() {\n  state.mu = hypers->mutilde;\n  state.psi = hypers->beta / (hypers->alpha0 + 1.);\n  state.eta = Eigen::MatrixXd::Zero(card, hypers->q);\n  state.lambda = Eigen::MatrixXd::Zero(dim, hypers->q);\n  state.psi_inverse = state.psi.cwiseInverse().asDiagonal();\n  state.cov_chol = (state.lambda * state.lambda.transpose() +\n                    Eigen::MatrixXd(state.psi.asDiagonal()))\n                       .llt();\n}\n\nvoid FAHierarchy::initialize_hypers() {\n  if (prior->has_fixed_values()) {\n    // Set values\n    hypers->mutilde = bayesmix::to_eigen(prior->fixed_values().mutilde());\n    dim = hypers->mutilde.size();\n    hypers->beta = bayesmix::to_eigen(prior->fixed_values().beta());\n    hypers->phi = prior->fixed_values().phi();\n    hypers->alpha0 = prior->fixed_values().alpha0();\n    hypers->q = prior->fixed_values().q();\n\n    // Automatic initialization\n    if (dim == 0) {\n      hypers->mutilde = dataset_ptr->colwise().mean();\n      dim = hypers->mutilde.size();\n    }\n    if (hypers->beta.size() == 0) {\n      Eigen::MatrixXd centered =\n          dataset_ptr->rowwise() - dataset_ptr->colwise().mean();\n      auto cov_llt = ((centered.transpose() * centered) /\n                      double(dataset_ptr->rows() - 1.))\n                         .llt();\n      Eigen::MatrixXd precision_matrix(\n          cov_llt.solve(Eigen::MatrixXd::Identity(dim, dim)));\n      hypers->beta =\n          (hypers->alpha0 - 1) * precision_matrix.diagonal().cwiseInverse();\n      if (hypers->alpha0 == 1) {\n        throw std::invalid_argument(\n            \"Scale parameter must be different than 1 when automatic \"\n            \"initialization is used\");\n      }\n    }\n    // Check validity\n    if (dim != hypers->beta.rows()) {\n      throw std::invalid_argument(\n          \"Hyperparameters dimensions are not consistent\");\n    }\n    for (size_t j = 0; j < dim; j++) {\n      if (hypers->beta[j] <= 0) {\n        throw std::invalid_argument(\"Shape parameter must be > 0\");\n      }\n    }\n    if (hypers->alpha0 <= 0) {\n      throw std::invalid_argument(\"Scale parameter must be > 0\");\n    }\n    if (hypers->phi <= 0) {\n      throw std::invalid_argument(\"Diffusion parameter must be > 0\");\n    }\n    if (hypers->q <= 0) {\n      throw std::invalid_argument(\"Number of factors must be > 0\");\n    }\n  }\n\n  else {\n    throw std::invalid_argument(\"Unrecognized hierarchy prior\");\n  }\n}\n\nvoid FAHierarchy::update_hypers(\n    const std::vector<bayesmix::AlgorithmState::ClusterState>& states) {\n  auto& rng = bayesmix::Rng::Instance().get();\n  if (prior->has_fixed_values()) {\n    return;\n  }\n\n  else {\n    throw std::invalid_argument(\"Unrecognized hierarchy prior\");\n  }\n}\n\nvoid FAHierarchy::update_summary_statistics(const Eigen::RowVectorXd& datum,\n                                            bool add) {\n  if (add) {\n    data_sum += datum;\n  } else {\n    data_sum -= datum;\n  }\n}\n\nvoid FAHierarchy::clear_summary_statistics() {\n  data_sum = Eigen::VectorXd::Zero(dim);\n}\n\nvoid FAHierarchy::set_state_from_proto(\n    const google::protobuf::Message& state_) {\n  auto& statecast = downcast_state(state_);\n  state.mu = bayesmix::to_eigen(statecast.fa_state().mu());\n  state.psi = bayesmix::to_eigen(statecast.fa_state().psi());\n  state.eta = bayesmix::to_eigen(statecast.fa_state().eta());\n  state.lambda = bayesmix::to_eigen(statecast.fa_state().lambda());\n  state.psi_inverse = state.psi.cwiseInverse().asDiagonal();\n  state.cov_chol = (state.lambda * state.lambda.transpose() +\n                    Eigen::MatrixXd(state.psi.asDiagonal()))\n                       .llt();\n  set_card(statecast.cardinality());\n}\n\nstd::shared_ptr<bayesmix::AlgorithmState::ClusterState>\nFAHierarchy::get_state_proto() const {\n  bayesmix::FAState state_;\n  bayesmix::to_proto(state.mu, state_.mutable_mu());\n  bayesmix::to_proto(state.psi, state_.mutable_psi());\n  bayesmix::to_proto(state.eta, state_.mutable_eta());\n  bayesmix::to_proto(state.lambda, state_.mutable_lambda());\n\n  auto out = std::make_shared<bayesmix::AlgorithmState::ClusterState>();\n  out->mutable_fa_state()->CopyFrom(state_);\n  return out;\n}\n\nvoid FAHierarchy::set_hypers_from_proto(\n    const google::protobuf::Message& hypers_) {\n  auto& hyperscast = downcast_hypers(hypers_).fa_state();\n  hypers->mutilde = bayesmix::to_eigen(hyperscast.mutilde());\n  hypers->alpha0 = hyperscast.alpha0();\n  hypers->beta = bayesmix::to_eigen(hyperscast.beta());\n  hypers->phi = hyperscast.phi();\n  hypers->q = hyperscast.q();\n}\n\nstd::shared_ptr<bayesmix::AlgorithmState::HierarchyHypers>\nFAHierarchy::get_hypers_proto() const {\n  bayesmix::FAPriorDistribution hypers_;\n  bayesmix::to_proto(hypers->mutilde, hypers_.mutable_mutilde());\n  bayesmix::to_proto(hypers->beta, hypers_.mutable_beta());\n  hypers_.set_alpha0(hypers->alpha0);\n  hypers_.set_phi(hypers->phi);\n  hypers_.set_q(hypers->q);\n\n  auto out = std::make_shared<bayesmix::AlgorithmState::HierarchyHypers>();\n  out->mutable_fa_state()->CopyFrom(hypers_);\n  return out;\n}\n\nvoid FAHierarchy::sample_full_cond(bool update_params) {\n  if (this->card == 0) {\n    // No posterior update possible\n    sample_prior();\n  } else {\n    sample_eta();\n    sample_mu();\n    sample_psi();\n    sample_lambda();\n  }\n}\n\nvoid FAHierarchy::sample_eta() {\n  auto& rng = bayesmix::Rng::Instance().get();\n  auto sigma_eta_inv_llt =\n      (Eigen::MatrixXd::Identity(hypers->q, hypers->q) +\n       state.lambda.transpose() * state.psi_inverse * state.lambda)\n          .llt();\n  if (state.eta.rows() != card) {\n    state.eta = Eigen::MatrixXd::Zero(card, state.eta.cols());\n  }\n  Eigen::MatrixXd temp_product(\n      sigma_eta_inv_llt.solve(state.lambda.transpose() * state.psi_inverse));\n  auto iterator = cluster_data_idx.begin();\n  for (size_t i = 0; i < card; i++, iterator++) {\n    Eigen::VectorXd tempvector(dataset_ptr->row(\n        *iterator));  // TODO use slicing when Eigen is updated to v3.4\n    state.eta.row(i) = (bayesmix::multi_normal_prec_chol_rng(\n        temp_product * (tempvector - state.mu), sigma_eta_inv_llt, rng));\n  }\n}\n\nvoid FAHierarchy::sample_mu() {\n  auto& rng = bayesmix::Rng::Instance().get();\n  Eigen::DiagonalMatrix<double, Eigen::Dynamic> sigma_mu;\n\n  sigma_mu.diagonal() =\n      (card * state.psi_inverse.diagonal().array() + hypers->phi)\n          .cwiseInverse();\n\n  Eigen::VectorXd sum = (state.eta.colwise().sum());\n\n  Eigen::VectorXd mumean =\n      sigma_mu * (hypers->phi * hypers->mutilde +\n                  state.psi_inverse * (data_sum - state.lambda * sum));\n\n  state.mu = bayesmix::multi_normal_diag_rng(mumean, sigma_mu, rng);\n}\n\nvoid FAHierarchy::sample_lambda() {\n  auto& rng = bayesmix::Rng::Instance().get();\n\n  Eigen::MatrixXd temp_etateta(state.eta.transpose() * state.eta);\n\n  for (size_t j = 0; j < dim; j++) {\n    auto sigma_lambda_inv_llt =\n        (Eigen::MatrixXd::Identity(hypers->q, hypers->q) +\n         temp_etateta / state.psi[j])\n            .llt();\n    Eigen::VectorXd tempsum(card);\n    const Eigen::VectorXd& data_col = dataset_ptr->col(j);\n    auto iterator = cluster_data_idx.begin();\n    for (size_t i = 0; i < card; i++, iterator++) {\n      tempsum[i] = data_col(\n          *iterator);  // TODO use slicing when Eigen is updated to v3.4\n    }\n    tempsum = tempsum.array() - state.mu[j];\n    tempsum = tempsum.array() / state.psi[j];\n\n    state.lambda.row(j) = bayesmix::multi_normal_prec_chol_rng(\n        sigma_lambda_inv_llt.solve(state.eta.transpose() * tempsum),\n        sigma_lambda_inv_llt, rng);\n  }\n}\n\nvoid FAHierarchy::sample_psi() {\n  auto& rng = bayesmix::Rng::Instance().get();\n\n  for (size_t j = 0; j < dim; j++) {\n    double sum = 0;\n    auto iterator = cluster_data_idx.begin();\n    for (size_t i = 0; i < card; i++, iterator++) {\n      sum += std::pow(\n          ((*dataset_ptr)(*iterator, j) -\n           state.mu[j] -  // TODO use slicing when Eigen is updated to v3.4\n           state.lambda.row(j).dot(state.eta.row(i))),\n          2);\n    }\n    state.psi[j] = stan::math::inv_gamma_rng(hypers->alpha0 + card / 2,\n                                             hypers->beta[j] + sum / 2, rng);\n  }\n  state.psi_inverse = state.psi.cwiseInverse().asDiagonal();\n  state.cov_chol = (state.lambda * state.lambda.transpose() +\n                    Eigen::MatrixXd(state.psi.asDiagonal()))\n                       .llt();\n}\n", "meta": {"hexsha": "aa395262b43f7ec42d7fe2a187f5a72b99290b64", "size": 10122, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/hierarchies/fa_hierarchy.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/hierarchies/fa_hierarchy.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/hierarchies/fa_hierarchy.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": 33.2960526316, "max_line_length": 79, "alphanum_fraction": 0.625074096, "num_tokens": 2736, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.49618279013937394}}
{"text": "/*\n@copyright Louis Dionne 2015\nDistributed under the Boost Software License, Version 1.0.\n(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n */\n\n#include <boost/hana/ext/boost/mpl/integral_c.hpp>\n\n#include <boost/hana/tuple.hpp>\n\n#include <laws/enumerable.hpp>\n#include <laws/group.hpp>\n#include <laws/integral_domain.hpp>\n#include <laws/monoid.hpp>\n#include <laws/ring.hpp>\n\n#include <boost/mpl/int.hpp>\n#include <boost/mpl/integral_c.hpp>\nusing namespace boost::hana;\nnamespace mpl = boost::mpl;\n\n\nint main() {\n    auto int_constants = make<Tuple>(\n        mpl::int_<-10>{}, mpl::int_<-2>{}, mpl::integral_c<int, 0>{},\n        mpl::integral_c<int, 1>{}, mpl::integral_c<int, 3>{}\n    );\n\n    //////////////////////////////////////////////////////////////////////////\n    // Enumerable, Monoid, Group, Ring, IntegralDomain\n    //////////////////////////////////////////////////////////////////////////\n    {\n        // laws\n        test::TestEnumerable<ext::boost::mpl::IntegralC<int>>{int_constants};\n        test::TestMonoid<ext::boost::mpl::IntegralC<int>>{int_constants};\n        test::TestGroup<ext::boost::mpl::IntegralC<int>>{int_constants};\n        test::TestRing<ext::boost::mpl::IntegralC<int>>{int_constants};\n        test::TestIntegralDomain<ext::boost::mpl::IntegralC<int>>{int_constants};\n    }\n}\n", "meta": {"hexsha": "695c451eb558d14a8843709a566a31f6dd16d489", "size": 1342, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/ext/boost/mpl/integral_c/integral_domain.cpp", "max_stars_repo_name": "josephwinston/hana", "max_stars_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/ext/boost/mpl/integral_c/integral_domain.cpp", "max_issues_repo_name": "josephwinston/hana", "max_issues_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/ext/boost/mpl/integral_c/integral_domain.cpp", "max_forks_repo_name": "josephwinston/hana", "max_forks_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.7317073171, "max_line_length": 81, "alphanum_fraction": 0.5983606557, "num_tokens": 330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.49618279013937394}}
{"text": "// Copyright \u00a9 2016-2019 Thomas Nagler and Thibault Vatter\n//\n// This file is part of the vinecopulib library and licensed under the terms of\n// the MIT license. For a copy, see the LICENSE file in the root directory of\n// vinecopulib or https://vinecopulib.github.io/vinecopulib/.\n\n#include <cmath>\n#include <boost/math/special_functions/digamma.hpp>\n#include <boost/math/special_functions/expm1.hpp>\n#include <boost/math/special_functions/log1p.hpp>\n#include <boost/math/special_functions/fpclassify.hpp> // isnan\n#include <vinecopulib/misc/tools_eigen.hpp>\n\nnamespace vinecopulib {\ninline JoeBicop::JoeBicop()\n{\n    family_ = BicopFamily::joe;\n    parameters_ = Eigen::VectorXd(1);\n    parameters_lower_bounds_ = Eigen::VectorXd(1);\n    parameters_upper_bounds_ = Eigen::VectorXd(1);\n    parameters_ << 1;\n    parameters_lower_bounds_ << 1;\n    parameters_upper_bounds_ << 30;\n}\n\ninline double JoeBicop::generator(const double &u)\n{\n    return (-1) * boost::math::log1p(-std::pow(1 - u, parameters_(0)));\n}\n\ninline double JoeBicop::generator_inv(const double &u)\n{\n    return 1 - std::pow(-boost::math::expm1(-u), 1 / parameters_(0));\n}\n\ninline double JoeBicop::generator_derivative(const double &u)\n{\n    double theta = double(parameters_(0));\n    return (-theta) * std::pow(1 - u, theta - 1) / (1 - std::pow(1 - u, theta));\n}\n\n//inline double JoeBicop::generator_derivative2(const double &u)\n//{\n//    double theta = double(parameters_(0));\n//    double res = theta * (theta - 1 + std::pow(1 - u, theta));\n//    return res * std::pow(1 - u, theta - 2) /\n//           std::pow(-1 + std::pow(1 - u, theta), 2);\n//}\n\ninline Eigen::VectorXd JoeBicop::pdf_raw(\n    const Eigen::Matrix<double, Eigen::Dynamic, 2> &u\n)\n{\n    double theta = static_cast<double>(parameters_(0));\n    auto f = [theta](const double &u1, const double &u2) {\n        double t1 = std::pow(1-u1,theta);\n        double t2 = std::pow(1-u2,theta);\n        return std::pow(t1 + t2 - t1 * t2,1/theta-2)\n               * std::pow(1-u1,theta-1)*std::pow(1-u2,theta-1)\n               * (theta-1 + t1 + t2 - t1 * t2);\n    };\n    return tools_eigen::binaryExpr_or_nan(u, f);\n}\n\n// inverse h-function\ninline Eigen::VectorXd JoeBicop::hinv1(\n    const Eigen::Matrix<double, Eigen::Dynamic, 2> &u\n)\n{\n    double theta = double(parameters_(0));\n    double u1, u2;\n    Eigen::VectorXd hinv = Eigen::VectorXd::Zero(u.rows());\n    for (int j = 0; j < u.rows(); ++j) {\n        u1 = u(j, 1);\n        u2 = u(j, 0);\n        if ((boost::math::isnan)(u1) | (boost::math::isnan)(u2)) {\n            hinv(j) = std::numeric_limits<double>::quiet_NaN();\n        } else {\n            hinv(j) = qcondjoe(&u1, &u2, &theta);\n        }\n    }\n\n    return hinv;\n}\n\n// link between Kendall's tau and the par_bicop parameter\ninline Eigen::MatrixXd JoeBicop::tau_to_parameters(const double &tau)\n{\n    Eigen::VectorXd tau0 = Eigen::VectorXd::Constant(1, std::fabs(tau));\n    auto f = [&](const Eigen::VectorXd &v) {\n        return Eigen::VectorXd::Constant(1, std::fabs(parameters_to_tau(v)));\n    };\n    return tools_eigen::invert_f(tau0,\n                                 f,\n                                 parameters_lower_bounds_(0) + 1e-6,\n                                 parameters_upper_bounds_(0) - 1e-6);\n}\n\ninline double JoeBicop::parameters_to_tau(const Eigen::MatrixXd &parameters)\n{\n    double par = parameters(0);\n    double tau = 2 / par + 1;\n    tau = boost::math::digamma(2.0) - boost::math::digamma(tau);\n    return 1 + 2 * tau / (2 - par);\n}\n\ninline Eigen::VectorXd JoeBicop::get_start_parameters(const double tau)\n{\n    Eigen::VectorXd par = tau_to_parameters(tau);\n    par = par.cwiseMax(parameters_lower_bounds_);\n    par = par.cwiseMin(parameters_upper_bounds_);\n    return par;\n}\n}\n\n// This is copy&paste from the VineCopula package\ninline double qcondjoe(double *q, double *u, double *de)\n{\n    double t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t13, t15, t16, t19, t23, t28, t31;\n    double c21, pdf;\n    int iter;\n    double diff, v, de1, dtem, de1inv, tem;\n\n    t1 = 1.0 - *u;\n    t2 = pow(t1, 1.0 * (*de));\n    t7 = 1. / (*de);\n    t10 = t2 * (*de);\n    t11 = 1. / t1;\n    t19 = (*de) * (*de);\n    de1 = *de - 1;  // may need better modification for large delta\n    dtem = -de1 / (1. + de1);\n    de1inv = -1. / de1;\n\n    // v = 0.5 * (q+u); // starting guess\n\n    // Use a better starting point based on reflected B4 copula\n    // A good starting point is crucial when delta is large because\n    //    C_{2|1} will be steep\n    // C_{R,2|1}(v|u)=1-C_{2|1}(1-v|1-u),\n    // C_{R,2|1}^{-1}(q|u)=1-C_{2|1}^{-1}(1-q|1-u)\n    tem = pow(1. - *q, dtem) - 1.;\n    tem = tem * pow(1. - *u, -de1) + 1.;\n    v = pow(tem, de1inv);\n    v = 1. - v;\n    diff = 1;\n    iter = 0;\n    while (fabs(diff) > 1.e-6 && iter < 20) {\n        t3 = 1. - v;\n        t4 = pow(t3, *de);\n        t5 = t2 * t4;\n        t6 = t2 + t4 - t5;\n        t8 = pow(t6, t7);\n        t9 = t7 * t8;\n        t13 = t11 * t4;\n        t15 = -t10 * t11 + t10 * t13;\n        t16 = 1. / t6;\n        t23 = 1. / t3;\n        t28 = t6 * t6;\n        t31 = (-t4 * (*de) * t23 + t5 * (*de) * t23) / t28 * t15;\n        c21 = -t9 * t15 * t16;\n        pdf = -t8 / t19 * t31 + t8 * (*de) * t2 * t13 * t23 * t16 + t9 * t31;\n        iter++;\n        if ((boost::math::isnan)(pdf) ||\n            (boost::math::isnan)(c21)) {\n            diff /= -2.;\n        }  // added for de>=30\n        else\n            diff = (c21 - *q) / pdf;\n        v -= diff;\n        int iter2 = 0;\n        while ((v <= 0 || v >= 1 || fabs(diff) > 0.25) & (iter2 < 20)) {\n            ++iter2;\n            diff /= 2.;\n            v += diff;\n        }\n    }\n\n    // make sure that boundaries are respected\n    if (v <= 0) {\n        v = 1e-10;\n    } else if (v >= 1) {\n        v = 1 - 1e-10;\n    }\n\n    return v;\n}\n", "meta": {"hexsha": "dbb7d269f850535ec94981405cbcbb11c7830a68", "size": 5786, "ext": "ipp", "lang": "C++", "max_stars_repo_path": "4.CalculatePairCopulas/include/vinecopulib/bicop/implementation/joe.ipp", "max_stars_repo_name": "covit2019/analysis_codes", "max_stars_repo_head_hexsha": "0c580c51f790723390676eef85422055007e2354", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "4.CalculatePairCopulas/include/vinecopulib/bicop/implementation/joe.ipp", "max_issues_repo_name": "covit2019/analysis_codes", "max_issues_repo_head_hexsha": "0c580c51f790723390676eef85422055007e2354", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "4.CalculatePairCopulas/include/vinecopulib/bicop/implementation/joe.ipp", "max_forks_repo_name": "covit2019/analysis_codes", "max_forks_repo_head_hexsha": "0c580c51f790723390676eef85422055007e2354", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-04-09T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-09T12:59:17.000Z", "avg_line_length": 30.9411764706, "max_line_length": 91, "alphanum_fraction": 0.5566885586, "num_tokens": 1926, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.49618279013937394}}
{"text": "#include <boost/math/special_functions/ellint_d.hpp>\n", "meta": {"hexsha": "ce76f676a4cac5b074ca09a377afc34da68a83c9", "size": 53, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_special_functions_ellint_d.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_special_functions_ellint_d.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_special_functions_ellint_d.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 26.5, "max_line_length": 52, "alphanum_fraction": 0.8301886792, "num_tokens": 13, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117769928211, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.49618278501440977}}
{"text": "//\n// Created by Zhongshi Jiang on 4/17/17.\n//\n\n#include <Eigen/Core>\n#include <igl/viewer/Viewer.h>\n#include <igl/triangle/triangulate.h>\n#include <igl/cat.h>\n#include <igl/writeOBJ.h>\n\nvoid bars_stack_construction(Eigen::MatrixXd w_uv, Eigen::MatrixXi w_F,\nint mv_num, int mf_num) {\n  using namespace Eigen;\n  using namespace std;\n\n  const double thick =  1;\n  const double space = 4; // vertical\n  const int length = 100;\n  const int layer = 400; // this is to be going to infinity!\n  const int num_hole = 1; // to prevent bug of triangle.\n  assert(num_hole < length);\n\n  auto v_num = 2 + length*2;\n  auto f_num = length*2;\n  Eigen::MatrixXd H(num_hole*layer,2);\n  Eigen::MatrixXd V(layer*v_num, 2);\n  Eigen::MatrixXi F(layer*f_num, 3);\n  Eigen::MatrixXi E(layer*v_num ,2);\n\n  for (auto l=0; l<layer; l++) {\n    auto start_v = l * v_num;\n    auto start_f = l * f_num;\n    for(int i=0; i<length+1; i++) {\n      V.row(start_v + 2 * i) << i * thick, l * space;\n      V.row(start_v + 2 * i + 1) << i * thick, l * space + thick;\n    }\n    for(int i=0; i<length; i++) {\n      F.row(start_f + 2*i) = Eigen::Array3i(2*i, 2*i+2,2*i+1)+start_v;\n      F.row(start_f + 2*i+1) = Eigen::Array3i(2*i+1, 2*i+2,2*i+3)+start_v;\n    }\n\n    for(int i=0; i<length; i++) {\n      E.row(start_v+i) << start_v+ 2*i, start_v + 2*i+2;\n      E.row(start_v+length+i+1)<<start_v+2*i+3, start_v+2*i+1;\n    }\n    E.row(start_v+length) << start_v+2*length, start_v+2*length+1;\n    E.row(start_v+2*length+1) << start_v+1,start_v+0;\n\n    for(int i=0 ; i<num_hole; i++) {\n      RowVector2d hh(0,0);\n      for(auto v : {0,1,2})\n        hh += V.row(F(start_f + i, v));\n      H.row(l*num_hole + i) = hh/3;\n    }\n  }\n\n  Matrix2d ob;// = rect_corners;\n  {\n    VectorXd uv_max = V.colwise().maxCoeff();\n    VectorXd uv_min = V.colwise().minCoeff();\n    VectorXd uv_mid = (uv_max + uv_min) / 2.;\n    ob.row(0) = uv_mid;\n    ob.row(1) = uv_mid;\n\n    double scaf_range = 3;\n    Array2d scaf_scale(2,1.5);\n    ob.row(0) += (scaf_scale * (uv_min - uv_mid).array()).matrix();\n    ob.row(1) += (scaf_scale * (uv_max - uv_mid).array()).matrix();\n  }\n  Vector2d rect_len;\n  rect_len << ob(1, 0) - ob(0, 0), ob(1, 1) - ob(0, 1);\n\n  int rect_side = 6;\n  MatrixXd V_rect(2*rect_side,2);\n  MatrixXi E_rect(2*rect_side,2);\n  for(int i=0; i<rect_side; i++) {\n    V_rect.row(i) << ob(0, 0) + i * rect_len(0) / (rect_side-1), ob(0, 1);\n    V_rect.row(rect_side + i) << ob(0, 0) + i * rect_len(0) / (rect_side-1),\n        ob(1, 1);\n\n    E_rect.row(i) << i, i + 1;\n    E_rect.row(rect_side + i) << 2 * rect_side - 1 - i, 2 * rect_side - 2 - i;\n  }\n  E_rect.row(rect_side - 1) << rect_side - 1, 2*rect_side - 1;\n  E_rect.row(2*rect_side - 1) << rect_side, 0;\n\n\n\n  MatrixXd whole_V;\n  igl::cat(1, V, V_rect, whole_V);\n  MatrixXi whole_E(V.rows() + V_rect.rows(), 2);\n  whole_E.topRows(V.rows()) = E;\n  whole_E.bottomRows(V_rect.rows()) = E_rect.array() + V.rows();\n\n  MatrixXd s_uv; MatrixXi s_F;\n  igl::triangle::triangulate(whole_V,whole_E, H, \"qQ\", s_uv, s_F);\n//  cout<<V<<endl<<E_rect<<endl;\n  mesh_cat(V,F,s_uv,s_F, w_uv,w_F);\n\n  mv_num = V.rows();\n  mf_num = F.rows();\n\n  igl::viewer::Viewer v_;\n  v_.data.set_mesh(w_uv,w_F);\n  v_.data.add_points(H,Eigen::RowVector3d(1,0,0) );\n  MatrixXd mesh_color(w_F.rows(),3);\n  for (int i = 0; i < mf_num; i++)\n    mesh_color.row(i) << 148/255., 195/255., 128/255.;\n\n  for (int i = mf_num; i < w_F.rows(); i++)\n    mesh_color.row(i) << 0.86, 0.86, 0.86;\n  v_.data.set_colors(mesh_color);\n  MatrixXd w_uv3 =MatrixXd::Zero(w_uv.rows(),3);\n  w_uv3.leftCols(2) = w_uv;\n  igl::writeOBJ(\"400layer.obj\",w_uv3,w_F);\n  v_.launch();\n}", "meta": {"hexsha": "626e1efbe63d618c6dfdbd4476cd0db6b26bbb25", "size": 3610, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/demo/bars_stack_construction.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/demo/bars_stack_construction.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/demo/bars_stack_construction.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": 30.8547008547, "max_line_length": 78, "alphanum_fraction": 0.5980609418, "num_tokens": 1353, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4961469096579945}}
{"text": "/*\n*  @file \t\tex5.cpp\n*  @details  \tThis file is the solution to exercise 5.\n*  @author    \tAlexander Rettkowski\n*  @date      \t08.06.2017\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_object.hpp>\n#include <boost/fusion/include/adapt_struct.hpp>\n#include <boost/fusion/include/io.hpp>\n\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/dijkstra_shortest_paths_no_color_map.hpp>\n#include <boost/property_map/property_map.hpp>\n\n#include <iostream>\n#include <string>\n#include <complex>\n#include <fstream>\n\n\nusing namespace boost;\n\nnamespace exercise5\n{\n\tnamespace qi = boost::spirit::qi;\n\tnamespace ascii = boost::spirit::ascii;\n\tstruct edge\n\t{\n\t\tint startNode;\n\t\tint endNode;\n\t\tint length;\n\t};\n}\n\n\nBOOST_FUSION_ADAPT_STRUCT(\n\texercise5::edge,\n\t(int, startNode)\n\t(int, endNode)\n\t(int, length)\n)\n\nnamespace exercise5\n{\n\ttemplate <typename Iterator>\n\tstruct line_parser : qi::grammar<Iterator, edge()>\n\t{\n\t\tline_parser() : line_parser::base_type(start)\n\t\t{\n\t\t\tusing qi::int_;\n\t\t\tstart %= int_ >> ' ' >> int_ >> ' ' >> int_;\n\t\t}\n\n\t\tqi::rule<Iterator, edge()> start;\n\t};\n}\n\n/**\n* The main function that reads in a file and processes it.\n* @param argc Number of command line arguments.\n* @param *argv a pointer to the array of command line arguments.\n*/\nint main(int argc, char *argv[])\n{\n\ttypedef adjacency_list < listS, vecS, undirectedS, no_property, property < edge_weight_t, int > > graph_t;\n\ttypedef graph_traits < graph_t >::vertex_descriptor vertex_descriptor;\n\ttypedef std::pair<int, int> Edge;\n\n\tstd::vector<Edge> edges;\n\tstd::vector<int> weights;\n\t\n\tusing boost::spirit::ascii::space;\n\ttypedef std::string::const_iterator iterator_type;\n\ttypedef exercise5::line_parser<iterator_type> line_parser;\n\tline_parser parser;\n\tstd::string currentLine;\n\tstd::ifstream file(argv[1]);\n\n\t// get number of nodes\n\tchar delimiter = ' ';\n\tgetline(file, currentLine, delimiter);\n\tint numberOfNodes = std::stoi(currentLine);\n\tgetline(file, currentLine);\n\tint constSub = 1;\n\twhile (getline(file, currentLine))\n\t{\n\t\texercise5::edge parsedLine;\n\t\tstd::string::const_iterator currentPosition = currentLine.begin();\n\t\tstd::string::const_iterator lineEnd = currentLine.end();\n\t\tbool parsingSucceeded = phrase_parse(currentPosition, lineEnd, parser, space, parsedLine);\n\t\t\n\t\tif (parsingSucceeded && currentPosition == lineEnd)\n\t\t{\n\t\t\tedges.push_back(Edge(parsedLine.startNode-constSub, parsedLine.endNode-constSub));\n\t\t\tweights.push_back(parsedLine.length);\n\t\t}\n\t}\n\n\tfile.close();\n\n\tgraph_t g(edges.data(), edges.data() + edges.size(), weights.data(), numberOfNodes);\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\n\tdijkstra_shortest_paths_no_color_map(g, s, predecessor_map(make_iterator_property_map(p.begin(), get(vertex_index, g))).\n\t\t\tdistance_map(make_iterator_property_map(d.begin(), get(vertex_index, g))));\n\n\tgraph_traits < graph_t >::vertex_iterator vi, vend;\n\tsize_t vertex = -1;\n\tdouble distance = -1;\n\tfor (tie(vi, vend) = vertices(g); vi != vend; ++vi) {\n\t\tif (d[*vi] > distance)\n\t\t{\n\t\t\tdistance = d[*vi];\n\t\t\tvertex = *vi;\n\t\t}\n\t\tif ((d[*vi] == distance) && (*vi > vertex))\n\t\t{\n\t\t\tvertex = *vi;\n\t\t}\n\t}\n\n\tstd::cout << \"RESULT VERTEX \" << vertex << std::endl;\n\tstd::cout << \"RESULT DIST \" << distance << std::endl;\n\n\treturn 0;\n}\n", "meta": {"hexsha": "2e89d064a249c29fe51d57825a1b5a34c656d701", "size": 3612, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rettkowski/ex5.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": "rettkowski/ex5.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": "rettkowski/ex5.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": 26.5588235294, "max_line_length": 121, "alphanum_fraction": 0.711517165, "num_tokens": 932, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195385342971, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.49609200185163765}}
{"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/**\n * \\file\n * \\brief core fundamental matrix template implementations\n */\n\n#include \"fundamental_matrix.h\"\n\n#include <cmath>\n\n#include <vital/exceptions/math.h>\n\n#include <Eigen/SVD>\n\nnamespace kwiver {\nnamespace vital {\n\n/// Construct from a provided matrix\ntemplate <typename T>\nfundamental_matrix_<T>\n::fundamental_matrix_( Eigen::Matrix<T,3,3> const &mat )\n{\n  Eigen::JacobiSVD<matrix_t> svd(mat, Eigen::ComputeFullU |\n                                      Eigen::ComputeFullV);\n  auto S = svd.singularValues();\n  const matrix_t& U = svd.matrixU();\n  const matrix_t& V = svd.matrixV();\n\n  // clear the last singular value\n  S[2] = T(0);\n  S /= S.norm();\n  mat_ = U*S.asDiagonal()*V.transpose();\n}\n\n/// Conversion Copy constructor -- float specialization\ntemplate <>\ntemplate <>\nfundamental_matrix_<float>\n::fundamental_matrix_( fundamental_matrix_<float> const &other )\n  : mat_( other.mat_ )\n{\n}\n\n/// Conversion Copy constructor -- double specialization\ntemplate <>\ntemplate <>\nfundamental_matrix_<double>\n::fundamental_matrix_( fundamental_matrix_<double> const &other )\n  : mat_( other.mat_ )\n{\n}\n\n/// Construct from a generic fundamental_matrix\ntemplate <typename T>\nfundamental_matrix_<T>\n::fundamental_matrix_( fundamental_matrix const &base )\n  : mat_( base.matrix().template cast<T>() )\n{\n}\n\n/// Construct from a generic fundamental_matrix -- double specialization\ntemplate <>\nfundamental_matrix_<double>\n::fundamental_matrix_( fundamental_matrix const &base )\n  : mat_( base.matrix() )\n{\n}\n\n/// Create a clone of outself as a shared pointer\ntemplate <typename T>\nfundamental_matrix_sptr\nfundamental_matrix_<T>\n::clone() const\n{\n  return fundamental_matrix_sptr( new fundamental_matrix_<T>( *this ) );\n}\n\n/// Get a double-typed copy of the underlying matrix\ntemplate <typename T>\nEigen::Matrix<double,3,3>\nfundamental_matrix_<T>\n::matrix() const\n{\n  return this->mat_.template cast<double>();\n}\n\n/// Specialization for matrices with native double type\ntemplate <>\nEigen::Matrix<double,3,3>\nfundamental_matrix_<double>\n::matrix() const\n{\n  return this->mat_;\n}\n\n// ===========================================================================\n// Other Functions\n// ---------------------------------------------------------------------------\n\n/// Output stream operator for \\p fundamental_matrix instances\nstd::ostream&\noperator<<( std::ostream &s, fundamental_matrix const &f )\n{\n  s << f.matrix();\n  return s;\n}\n\n// ===========================================================================\n// Template class instantiation\n// ---------------------------------------------------------------------------\n/// \\cond DoxygenSuppress\n#define INSTANTIATE_FUNDAMENTAL_MATRIX(T) \\\n  template class fundamental_matrix_<T>;\n\nINSTANTIATE_FUNDAMENTAL_MATRIX(float);\nINSTANTIATE_FUNDAMENTAL_MATRIX(double);\n#undef INSTANTIATE_FUNDAMENTAL_MATRIX\n/// \\endcond\n\n} } // end vital namespace\n", "meta": {"hexsha": "30df7837f5a9eebe4119815b1e1419e957f6b00f", "size": 3085, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "vital/types/fundamental_matrix.cxx", "max_stars_repo_name": "mwoehlke-kitware/kwiver", "max_stars_repo_head_hexsha": "614a488bd2b7fe551ac75eec979766d882709791", "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": "vital/types/fundamental_matrix.cxx", "max_issues_repo_name": "mwoehlke-kitware/kwiver", "max_issues_repo_head_hexsha": "614a488bd2b7fe551ac75eec979766d882709791", "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": "vital/types/fundamental_matrix.cxx", "max_forks_repo_name": "mwoehlke-kitware/kwiver", "max_forks_repo_head_hexsha": "614a488bd2b7fe551ac75eec979766d882709791", "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.8790322581, "max_line_length": 78, "alphanum_fraction": 0.6544570502, "num_tokens": 673, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.734119526900183, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.49609199878343596}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\nCopyright (C) 2003 RiskMap srl\nCopyright (C) 2006, 2007 Ferdinando Ametrano\nCopyright (C) 2006 Marco Bianchetti\nCopyright (C) 2006 Cristina Duminuco\nCopyright (C) 2007, 2008 StatPro Italia srl\nCopyright (C) 2015 CompatibL\n\nThis file is part of QuantLib, a free-software/open-source library\nfor financial quantitative analysts and developers - http://quantlib.org/\n\nQuantLib is free software: you can redistribute it and/or modify it\nunder the terms of the QuantLib license.  You should have received a\ncopy of the license along with this program; if not, please email\n<quantlib-dev@lists.sf.net>. The license is also available online at\n<http://quantlib.org/license.shtml>.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT\nANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\nFOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n// based on swaption.cpp file from test-suite\n\n#ifndef cl_adjoint_swaption_impl_hpp\n#define cl_adjoint_swaption_impl_hpp\n#pragma once\n\n#include <ql/quantlib.hpp>\n#include \"utilities.hpp\"\n#include \"adjointswaptiontest.hpp\"\n#include \"adjointtestutilities.hpp\"\n#include \"adjointtestbase.hpp\"\n#include <boost/shared_ptr.hpp>\n\nusing namespace QuantLib;\nusing namespace boost::unit_test_framework;\n\n\n#define OUTPUT_FOLDER_NAME \"AdjointSwaption\"\n\nnamespace\n{\n    struct Variation\n    {\n        static std::deque<std::string > get_columns()\n        {\n            static std::deque<std::string > columns =\n            {\n                \"param\", \"\"\n            };\n\n            return columns;\n        }\n\n        template <typename stream_type>\n        friend inline stream_type& operator << (stream_type& stm, Variation& v)\n        {\n            stm << v.param_\n                << \";\" << v.swaptionNpv_\n                << std::endl;\n            return stm;\n        }\n\n        Real param_;\n        Real swaptionNpv_;\n    };\n\n    struct SwaptionData\n    {\n        SwaptionData()\n        : settlementDays_(2)\n        , nominal_(1000000.0)\n        , fixedConvention_(Unadjusted)\n        , fixedFrequency_(Annual)\n        , fixedDayCount_(Thirty360())\n        , type_(VanillaSwap::Payer)\n        {\n            index_ = boost::make_shared<Euribor6M>(termStructure_);\n            floatingTenor_ = index_->tenor();\n            floatingConvention_ = index_->businessDayConvention();\n            calendar_ = index_->fixingCalendar();\n            today_ = calendar_.adjust(Date::todaysDate());\n            Settings::instance().evaluationDate() = today_;\n            settlement_ = calendar_.advance(today_, settlementDays_, Days);\n            termStructure_.linkTo(flatRate(settlement_, 0.05, Actual365Fixed()));\n\n            exercises_ = { 1 * Years, 3 * Years, 7 * Years, 10 * Years };\n            lengths_ = { 1 * Years, 2 * Years, 5 * Years, 10 * Years, 20 * Years };\n        }\n\n        // Make swaption with given parameters.\n        boost::shared_ptr<Swaption> makeSwaption(const boost::shared_ptr<VanillaSwap>& swap\n                                                 , const Date& exercise\n                                                 , Volatility volatility\n                                                 , Settlement::Type settlementType = Settlement::Physical)\n        {\n            // Set volatility from simple quote.\n            Handle<Quote> vol(boost::make_shared<SimpleQuote>(volatility));\n\n            // Create pricing engine.\n            boost::shared_ptr<PricingEngine> engine(new BlackSwaptionEngine(termStructure_, vol));\n\n            // Create swaption using vanilla swap.\n            boost::shared_ptr<Swaption> result(new Swaption(swap\n                , boost::make_shared<EuropeanExercise>(exercise)\n                , settlementType));\n\n            // Set pricing engine in swaption.\n            result->setPricingEngine(engine);\n            return result;\n        }\n\n\n        // Calculate sum of swaption NPV for given spreads.\n        std::vector<Real> swaptionNpvOnSpreads(Real spread)\n        {\n            std::vector<Real> Y(1);\n            for (Size i = 0; i < exercises_.size(); i++)\n            {\n                for (Size j = 0; j < lengths_.size(); j++)\n                {\n                    // Set date of exercize.\n                    Date exerciseDate = calendar_.advance(today_, exercises_[i]);\n\n                    // Set start date.\n                    Date startDate = calendar_.advance(exerciseDate, settlementDays_, Days);\n\n                    // Create vanilla swap.\n                    boost::shared_ptr<VanillaSwap> swap =\n                        MakeVanillaSwap(lengths_[j], index_, 0.06)\n                        .withFixedLegTenor(1 * Years)\n                        .withFixedLegDayCount(fixedDayCount_)\n                        .withEffectiveDate(startDate)\n                        .withFloatingLegSpread(spread)\n                        .withType(type_);\n\n                    // Create swaption using vanilla swap.\n                    boost::shared_ptr<Swaption> swaption =\n                        makeSwaption(swap, exerciseDate, 0.20);\n\n                    Y[0] += swaption->NPV();\n                }\n            }\n            return Y;\n        }\n\n        // Calculate sum of swaption NPV for given spreads.\n        std::vector<Real> swaptionNpvWithSpreadCorrection(Real spread)\n        {\n            std::vector<Real> Y(4, 0);\n\n            for (Size i = 0; i < exercises_.size(); i++)\n            {\n                for (Size j = 0; j < lengths_.size(); j++)\n                {\n                    // Set date of exercize.\n                    Date exerciseDate = calendar_.advance(today_, exercises_[i]);\n\n                    // Set start date.\n                    Date startDate = calendar_.advance(exerciseDate, settlementDays_, Days);\n\n                    // Create vanilla swap.\n                    boost::shared_ptr<VanillaSwap> swap =\n                        MakeVanillaSwap(lengths_[j], index_, 0.06)\n                        .withFixedLegTenor(1 * Years)\n                        .withFixedLegDayCount(fixedDayCount_)\n                        .withEffectiveDate(startDate)\n                        .withFloatingLegSpread(spread)\n                        .withType(type_);\n\n                    // Calculate spread correction.\n                    Spread correction = spread *\n                        swap->floatingLegBPS() /\n                        swap->fixedLegBPS();\n\n                    // Create equivalent vanilla swap.\n                    boost::shared_ptr<VanillaSwap> equivalentSwap =\n                        MakeVanillaSwap(lengths_[j], index_, 0.06 + correction)\n                        .withFixedLegTenor(1 * Years)\n                        .withFixedLegDayCount(fixedDayCount_)\n                        .withEffectiveDate(startDate)\n                        .withFloatingLegSpread(0.0)\n                        .withType(type_);\n\n                    // Create swaption using vanilla swap.\n                    boost::shared_ptr<Swaption> swaption1 =\n                        makeSwaption(swap, exerciseDate, 0.20);\n\n                    Y[0] += swaption1->NPV();\n\n                    // Create swaption using equivalent vanilla swap.\n                    boost::shared_ptr<Swaption> swaption2 =\n                        makeSwaption(equivalentSwap, exerciseDate, 0.20);\n\n                    Y[1] += swaption2->NPV();\n\n                    // Create swaption with cash settlement using vanilla swap.\n                    boost::shared_ptr<Swaption> swaption1_cash =\n                        makeSwaption(swap, exerciseDate, 0.20,\n                        Settlement::Cash);\n\n                    Y[2] += swaption1_cash->NPV();\n\n                    // Create swaption with cash settlement using equivalent vanilla swap.\n                    boost::shared_ptr<Swaption> swaption2_cash =\n                        makeSwaption(equivalentSwap, exerciseDate, 0.20,\n                        Settlement::Cash);\n\n                    Y[3] += swaption2_cash->NPV();\n\n                    // Check swaption NPV and equivalent swaption NPV\n                    if (std::fabs(swaption1->NPV() - swaption2->NPV()) > 1.0e-6)\n                        BOOST_ERROR(\"wrong spread treatment:\" <<\n                        \"\\nexercise: \" << exerciseDate <<\n                        \"\\nlength:   \" << lengths_[j] <<\n                        \"\\ntype      \" << type_ <<\n                        \"\\nspread:   \" << io::rate(spread) <<\n                        \"\\noriginal swaption value:   \" << swaption1->NPV() <<\n                        \"\\nequivalent swaption value: \" << swaption2->NPV());\n\n                    if (std::fabs(swaption1_cash->NPV() - swaption2_cash->NPV()) > 1.0e-6)\n                        BOOST_ERROR(\"wrong spread treatment:\" <<\n                        \"\\nexercise date: \" << exerciseDate <<\n                        \"\\nlength: \" << lengths_[j] <<\n                        \"\\npay \" << (type_ ? \"fixed\" : \"floating\") <<\n                        \"\\nspread: \" << io::rate(spread) <<\n                        \"\\nvalue of original swaption:   \" << swaption1_cash->NPV() <<\n                        \"\\nvalue of equivalent swaption: \" << swaption2_cash->NPV());\n\n                }\n            }\n            return Y;\n        }\n\n        // Calculate sum of swaption NPV for given volatilities.\n        std::vector<Real> swaptionNpvOnCachedValues(Real volatility)\n        {\n            today_ = Date(13, March, 2002);\n            settlement_ = Date(15, March, 2002);\n            Settings::instance().evaluationDate() = today_;\n            termStructure_.linkTo(flatRate(settlement_, 0.05, Actual365Fixed()));\n\n            // Set date of exercize.\n            Date exerciseDate = calendar_.advance(settlement_, 5 * Years);\n\n            // Set start date.\n            Date startDate = calendar_.advance(exerciseDate,\n                                               settlementDays_, Days);\n\n            // Create vanilla swap.\n            boost::shared_ptr<VanillaSwap> swap =\n                MakeVanillaSwap(10 * Years, index_, 0.06)\n                .withEffectiveDate(startDate)\n                .withFixedLegTenor(1 * Years)\n                .withFixedLegDayCount(fixedDayCount_);\n\n            std::vector<Real> Y(1);\n            // Create swaption using vanilla swap.\n            boost::shared_ptr<Swaption> swaption =\n                makeSwaption(swap, exerciseDate, volatility);\n            Y[0] += swaption->NPV();\n\n            return Y;\n        }\n\n        template <class Func>\n        void calculateFinDiff(std::vector<Real>& X\n                              , Size dep_number\n                              , Real h\n                              , std::vector<Real>& sf_Finite\n                              , Func swaptionNpv)\n        {\n            Size sizeX = X.size();\n\n            std::vector<Real> swaptionPortfolioNpv(sizeX * dep_number);\n            for (int i = 0; i < sizeX; i++)\n            {\n                std::vector<Real> temp = swaptionNpv(X[i]);\n                for (int j = 0; j < dep_number; j++)\n                    swaptionPortfolioNpv[sizeX*j + i] = temp[j];\n            }\n\n            sf_Finite.resize(swaptionPortfolioNpv.size());\n\n            for (int i = 0; i < sizeX; i++)\n            {\n                std::vector<Real> temp = swaptionNpv(X[i] + h);\n                for (int j = 0; j < dep_number; j++)\n                {\n                    int curIndex = sizeX*j + i;\n                    sf_Finite[curIndex] = (temp[j] - swaptionPortfolioNpv[curIndex]) / h;\n                }\n            }\n        }\n\n        // Global data.\n        Date today_;\n        Date settlement_;\n        Real nominal_;\n        Calendar calendar_;\n\n        BusinessDayConvention fixedConvention_;\n        Frequency fixedFrequency_;\n        DayCounter fixedDayCount_;\n\n        BusinessDayConvention floatingConvention_;\n        Period floatingTenor_;\n        boost::shared_ptr<IborIndex> index_;\n\n        Natural settlementDays_;\n        RelinkableHandle<YieldTermStructure> termStructure_;\n\n        std::vector<Period> exercises_;\n        std::vector<Period> lengths_;\n        VanillaSwap::Type type_;\n\n        // Cleanup\n        SavedSettings backup_;\n\n    };\n\n    struct SpreadDependencyTestData\n        : public SwaptionData\n    {\n        struct Test\n        : public cl::AdjointTest<Test>\n        {\n            Test(Size size, SpreadDependencyTestData* data)\n            : size_(size)\n            , data_(data)\n            , swaptionNpv_(1)\n            , spread_(size)\n            , iterNumFactor_(1)\n            {\n                setLogger(&data_->outPerform_);\n\n                Real startSpread = -0.01;\n                Real maxSpread = 0.01;\n                Real step = (maxSpread - startSpread) / size_;\n\n                for (Size i = 0; i < size_; i++)\n                {\n                    spread_[i] = (startSpread + i*step == 0) ? 0.00001 : startSpread + i*step;\n                }\n\n            }\n\n            Size indepVarNumber() { return size_; }\n\n            Size depVarNumber() { return 1; }\n\n            Size minPerfIteration() { return iterNumFactor_; }\n\n            void recordTape()\n            {\n                cl::Independent(spread_);\n                calculateTotalSwaptionNpv();\n                f_ = std::make_unique<cl::tape_function<double>>(spread_, swaptionNpv_);\n            }\n\n            // Calculates total calibration error.\n            void calculateTotalSwaptionNpv()\n            {\n                for (int i = 0; i < size_; i++)\n                    swaptionNpv_[0] += data_->swaptionNpvOnSpreads(spread_[i])[0];\n            }\n\n            // Calculates derivatives using finite difference method.\n            void calcAnalytical()\n            {\n                double h = 1.0e-10;  // shift for finite diff. method\n                analyticalResults_.resize(size_);\n                data_->calculateFinDiff(spread_\n                                        , depVarNumber()\n                                        , h\n                                        , analyticalResults_\n                                        , [this] (Real v) -> std::vector<Real>\n                {\n                    return data_->swaptionNpvOnSpreads(v);\n                });\n            }\n\n            double relativeTol() const { return 1e-2; }\n\n            double absTol() const { return 1e-10; }\n\n            Size size_;\n            Size iterNumFactor_;\n            SpreadDependencyTestData* data_;\n            std::vector<cl::tape_double> spread_;\n            std::vector<cl::tape_double> swaptionNpv_;\n        };\n\n        SpreadDependencyTestData()\n            : SwaptionData()\n\n            , outPerform_(OUTPUT_FOLDER_NAME \"//SpreadDependency\"\n            , { { \"filename\", \"AdjointPerformance\" }\n        , { \"not_clear\", \"Not\" }\n        , { \"line_box_width\", \"-5\" }\n        , { \"title\", \"Swaption NPV differentiation performance with respect to spread\" }\n        , { \"ylabel\", \"Time (s)\" }\n        , { \"xlabel\", \"Number of spreads\" }\n        , { \"smooth\", \"default\" }\n        , { \"cleanlog\", \"true\" } })\n\n            , outAdjoint_(OUTPUT_FOLDER_NAME \"//SpreadDependency\"\n            , { { \"filename\", \"Adjoint\" }\n        , { \"not_clear\", \"Not\" }\n        , { \"smooth\", \"default\" }\n        , { \"title\", \"Swaption NPV adjoint differentiation performance with respect to spread\" }\n        , { \"cleanlog\", \"false\" }\n        , { \"ylabel\", \"Time (s)\" }\n        , { \"xlabel\", \"Number of spreads\" } })\n\n            , outSize_(OUTPUT_FOLDER_NAME \"//SpreadDependency\"\n            , { { \"filename\", \"TapeSize\" }\n        , { \"not_clear\", \"Not\" }\n        , { \"title\", \"Tape size dependence on number of spreads\" }\n        , { \"cleanlog\", \"false\" }\n        , { \"smooth\", \"default\" }\n        , { \"ylabel\", \"Size (MB)\" }\n        , { \"xlabel\", \"Number of spreads\" } })\n\n            , out_(OUTPUT_FOLDER_NAME \"//SpreadDependency//output\"\n            , { { \"filename\", \"SwaptNPVonSpreads\" }\n        , { \"ylabel\", \"Swaption NPV\" }\n        , { \"not_clear\", \"Not\" }\n        , { \"title\", \"Swaption NPV dependence on spread\" }\n        , { \"cleanlog\", \"false\" }\n        , { \"smooth\", \"default\" }\n        , { \"xlabel\", \"Spread\" } })\n\n#if defined CL_GRAPH_GEN\n            , pointNo_(50)\n            , iterNo_(10)\n            , step_(5)\n#else\n            , pointNo_(1)\n            , iterNo_(1)\n            , step_(1)\n#endif\n        {\n        }\n\n        bool makeOutput()\n        {\n            bool ok = true;\n            if (pointNo_ > 0)\n            {\n                ok &= recordDependencePlot();\n            }\n            ok &= cl::recordPerformance(*this, iterNo_, step_);\n            return ok;\n        }\n\n        std::shared_ptr<Test> getTest(size_t size)\n        {\n            return std::make_shared<Test>(size, this);\n        }\n\n        // Makes plots for strike sensitivity dependence.\n        bool recordDependencePlot()\n        {\n            std::vector<Variation> outData(pointNo_);\n            auto test = getTest(pointNo_);\n            for (Size i = 0; i < pointNo_; i++)\n            {\n                outData[i].param_ = test->spread_[i];\n                outData[i].swaptionNpv_ = test->data_->swaptionNpvOnSpreads(test->spread_[i])[0];\n            }\n            out_ << outData;\n            return true;\n        }\n\n        Size pointNo_;\n        Size iterNo_;\n        Size step_;\n\n        cl::tape_empty_test_output outPerform_;\n        cl::tape_empty_test_output outAdjoint_;\n        cl::tape_empty_test_output outSize_;\n        cl::tape_empty_test_output out_;\n    };\n    typedef SpreadDependencyTestData::Test SpreadDependencyTest;\n\n    struct SpreadCorrectionTestData\n        : public SwaptionData\n    {\n        struct Test\n        : public cl::AdjointTest<Test>\n        {\n            static const CalcMethod default_method = other;\n\n            Test(Size size, SpreadCorrectionTestData* data)\n                : size_(size)\n                , data_(data)\n                , spread_(size)\n                , doubleSpread_(size)\n                , iterNumFactor_(1)\n            {\n                setLogger(&data_->outPerform_);\n\n                double startSpread = -0.01;\n                double maxSpread = 0.01;\n                double step = (maxSpread - startSpread) / size_;\n\n                for (Size i = 0; i < size_; i++)\n                {\n                    doubleSpread_[i] = (startSpread + i*step == 0) ? 0.00001 : startSpread + i*step;\n                }\n\n                std::copy(doubleSpread_.begin(), doubleSpread_.end(), spread_.begin());\n            }\n\n            Size indepVarNumber() { return size_; }\n\n            Size depVarNumber() { return 4; }\n\n            Size minPerfIteration() { return iterNumFactor_; }\n\n            void recordTape()\n            {\n                cl::Independent(spread_);\n                calculateTotalSwaptionNpv();\n                f_ = std::make_unique<cl::tape_function<double>>(spread_, swaptionNpv_);\n            }\n\n            // Calculates total calibration error.\n            void calculateTotalSwaptionNpv()\n            {\n                swaptionNpv_.resize(depVarNumber());\n                for (int i = 0; i < size_; i++)\n                {\n                    std::vector<cl::tape_double> temp = data_->swaptionNpvWithSpreadCorrection(spread_[i]);\n                    for (int j = 0; j < depVarNumber(); j++)\n                        swaptionNpv_[j] += temp[j];\n                }\n            }\n\n            // Calculates derivatives using finite difference method.\n            void calcAnalytical()\n            {\n                double h = 1.0e-10;  // shift for finite diff. method\n                analyticalResults_.resize(size_ * depVarNumber());\n                data_->calculateFinDiff(spread_\n                                        , depVarNumber()\n                                        , h\n                                        , analyticalResults_\n                                        , [this] (Real v) -> std::vector<Real>\n                {\n                    return data_->swaptionNpvWithSpreadCorrection(v);\n                });\n            }\n\n            // Calculates derivatives using adjoint.\n            void calcAdjoint()\n            {\n                adjointResults_ = f_->Jacobian(doubleSpread_);\n            }\n\n\n            double relativeTol() const { return 1e-2; }\n\n            double absTol() const { return 1e-10; }\n\n            Size size_;\n            Size iterNumFactor_;\n            SpreadCorrectionTestData* data_;\n            std::vector<double> doubleSpread_;\n            std::vector<cl::tape_double> spread_;\n            std::vector<cl::tape_double> swaptionNpv_;\n        };\n\n        SpreadCorrectionTestData()\n            : SwaptionData()\n\n            , outPerform_(OUTPUT_FOLDER_NAME \"//SpreadCorrection\"\n            , { { \"filename\", \"AdjointPerformance\" }\n        , { \"not_clear\", \"Not\" }\n        , { \"line_box_width\", \"-5\" }\n        , { \"title\", \"Swaption NPV differentiation performance with respect to spread\" }\n        , { \"ylabel\", \"Time (s)\" }\n        , { \"xlabel\", \"Number of spreads\" }\n        , { \"smooth\", \"default\" }\n        , { \"cleanlog\", \"true\" } })\n\n            , outAdjoint_(OUTPUT_FOLDER_NAME \"//SpreadCorrection\"\n            , { { \"filename\", \"Adjoint\" }\n        , { \"not_clear\", \"Not\" }\n        , { \"smooth\", \"default\" }\n        , { \"title\", \"Swaption NPV adjoint differentiation performance with respect to spread\" }\n        , { \"cleanlog\", \"false\" }\n        , { \"ylabel\", \"Time (s)\" }\n        , { \"xlabel\", \"Number of spreads\" } })\n\n            , outSize_(OUTPUT_FOLDER_NAME \"//SpreadCorrection\"\n            , { { \"filename\", \"TapeSize\" }\n        , { \"not_clear\", \"Not\" }\n        , { \"title\", \"Tape size dependence on number of spreads\" }\n        , { \"cleanlog\", \"false\" }\n        , { \"smooth\", \"default\" }\n        , { \"ylabel\", \"Size (MB)\" }\n        , { \"xlabel\", \"Number of spreads\" } })\n\n            , out_(OUTPUT_FOLDER_NAME \"//SpreadCorrection//output\"\n            , { { \"filename\", \"SwaptNPVonSpreads\" }\n        , { \"ylabel\", \"Swaption NPV\" }\n        , { \"not_clear\", \"Not\" }\n        , { \"title\", \"Swaption NPV dependence on spread\" }\n        , { \"cleanlog\", \"false\" }\n        , { \"smooth\", \"default\" }\n        , { \"xlabel\", \"Spread\" } })\n\n#if defined CL_GRAPH_GEN\n            , pointNo_(20)\n            , iterNo_(20)\n            , step_(1)\n#else\n            , pointNo_(1)\n            , iterNo_(1)\n            , step_(1)\n#endif\n        {\n        }\n\n        bool makeOutput()\n        {\n            bool ok = true;\n            if (pointNo_ > 0)\n            {\n                ok &= recordDependencePlot();\n            }\n            ok &= cl::recordPerformance(*this, iterNo_, step_);\n            return ok;\n        }\n\n        std::shared_ptr<Test> getTest(size_t size)\n        {\n            return std::make_shared<Test>(size, this);\n        }\n\n        // Makes plots for strike sensitivity dependence.\n        bool recordDependencePlot()\n        {\n            std::vector<Variation> outData(pointNo_);\n            auto test = getTest(pointNo_);\n            for (Size i = 0; i < pointNo_; i++)\n            {\n                outData[i].param_ = test->spread_[i];\n                outData[i].swaptionNpv_ = test->data_->swaptionNpvWithSpreadCorrection(test->spread_[i])[0];\n            }\n            out_ << outData;\n            return true;\n        }\n\n        Size pointNo_;\n        Size iterNo_;\n        Size step_;\n\n        cl::tape_empty_test_output outPerform_;\n        cl::tape_empty_test_output outAdjoint_;\n        cl::tape_empty_test_output outSize_;\n        cl::tape_empty_test_output out_;\n    };\n    typedef SpreadCorrectionTestData::Test SpreadCorrectionTest;\n\n    struct CachedValueTestData\n        : public SwaptionData\n    {\n        struct Test\n        : public cl::AdjointTest<Test>\n        {\n\n            Test(Size size, CachedValueTestData* data)\n            : size_(size)\n            , data_(data)\n            , volatility_(size)\n            , swaptionNpv_(1)\n            , iterNumFactor_(1)\n            {\n                setLogger(&data_->outPerform_);\n\n                Real startVol = 0.15;\n                Real maxVol = 0.25;\n                Real step = (maxVol - startVol) / size_;\n\n                for (Size i = 0; i < size_; i++)\n                {\n                    volatility_[i] = startVol + i*step;\n                }\n\n\n            }\n\n            Size indepVarNumber() { return size_; }\n\n            Size depVarNumber() { return 1; }\n\n            Size minPerfIteration() { return iterNumFactor_; }\n\n            void recordTape()\n            {\n                cl::Independent(volatility_);\n                calculateTotalSwaptionNpv();\n                f_ = std::make_unique<cl::tape_function<double>>(volatility_, swaptionNpv_);\n            }\n\n            // Calculates total calibration error.\n            void calculateTotalSwaptionNpv()\n            {\n                for (int i = 0; i < size_; i++)\n                    swaptionNpv_[0] += data_->swaptionNpvOnCachedValues(volatility_[i])[0];\n            }\n\n            // Calculates derivatives using finite difference method.\n            void calcAnalytical()\n            {\n                double h = 1.0e-10;  // shift for finite diff. method\n                analyticalResults_.resize(size_ * depVarNumber());\n                data_->calculateFinDiff(volatility_\n                                        , depVarNumber()\n                                        , h\n                                        , analyticalResults_\n                                        , [this] (Real v) -> std::vector<Real>\n                {\n                    return data_->swaptionNpvOnCachedValues(v);\n                });\n            }\n\n            double relativeTol() const { return 1e-2; }\n\n            double absTol() const { return 1e-10; }\n\n            Size size_;\n            Size iterNumFactor_;\n            CachedValueTestData* data_;\n            std::vector<cl::tape_double> volatility_;\n            std::vector<cl::tape_double> swaptionNpv_;\n        };\n\n        CachedValueTestData()\n            : SwaptionData()\n\n            , outPerform_(OUTPUT_FOLDER_NAME \"//CachedValue\"\n            , { { \"filename\", \"AdjointPerformance\" }\n        , { \"not_clear\", \"Not\" }\n        , { \"line_box_width\", \"-5\" }\n        , { \"title\", \"Swaption NPV differentiation performance with respect to volatility\" }\n        , { \"ylabel\", \"Time (s)\" }\n        , { \"xlabel\", \"Number of volatilities\" }\n        , { \"smooth\", \"default\" }\n        , { \"cleanlog\", \"true\" } })\n\n            , outAdjoint_(OUTPUT_FOLDER_NAME \"//CachedValue\"\n            , { { \"filename\", \"Adjoint\" }\n        , { \"not_clear\", \"Not\" }\n        , { \"smooth\", \"default\" }\n        , { \"title\", \"Swaption NPV adjoint differentiation performance with respect to volatility\" }\n        , { \"cleanlog\", \"false\" }\n        , { \"ylabel\", \"Time (s)\" }\n        , { \"xlabel\", \"Number of volatilities\" } })\n\n            , outSize_(OUTPUT_FOLDER_NAME \"//CachedValue\"\n            , { { \"filename\", \"TapeSize\" }\n        , { \"not_clear\", \"Not\" }\n        , { \"title\", \"Tape size dependence on number of volatilities\" }\n        , { \"cleanlog\", \"false\" }\n        , { \"smooth\", \"default\" }\n        , { \"ylabel\", \"Size (MB)\" }\n        , { \"xlabel\", \"Number of volatilities\" } })\n\n            , out_(OUTPUT_FOLDER_NAME \"//CachedValue//output\"\n            , { { \"filename\", \"SwaptNPVonVol\" }\n        , { \"ylabel\", \"Swaption NPV\" }\n        , { \"not_clear\", \"Not\" }\n        , { \"title\", \"Swaption NPV dependence on volatilities\" }\n        , { \"cleanlog\", \"false\" }\n        , { \"smooth\", \"default\" }\n        , { \"xlabel\", \"Volatility\" } })\n\n#if defined CL_GRAPH_GEN\n            , pointNo_(400)\n            , iterNo_(16)\n            , step_(25)\n#else\n            , pointNo_(1)\n            , iterNo_(1)\n            , step_(1)\n#endif\n        {\n        }\n\n        bool makeOutput()\n        {\n            bool ok = true;\n            if (pointNo_ > 0)\n            {\n                ok &= recordDependencePlot();\n            }\n            ok &= cl::recordPerformance(*this, iterNo_, step_);\n            return ok;\n        }\n\n        std::shared_ptr<Test> getTest(size_t size)\n        {\n            return std::make_shared<Test>(size, this);\n        }\n\n        // Makes plots for strike sensitivity dependence.\n        bool recordDependencePlot()\n        {\n            std::vector<Variation> outData(pointNo_);\n            auto test = getTest(pointNo_);\n            for (Size i = 0; i < pointNo_; i++)\n            {\n                outData[i].param_ = test->volatility_[i];\n                outData[i].swaptionNpv_ = test->data_->swaptionNpvOnCachedValues(test->volatility_[i])[0];\n            }\n            out_ << outData;\n            return true;\n        }\n\n        Size pointNo_;\n        Size iterNo_;\n        Size step_;\n\n        cl::tape_empty_test_output outPerform_;\n        cl::tape_empty_test_output outAdjoint_;\n        cl::tape_empty_test_output outSize_;\n        cl::tape_empty_test_output out_;\n    };\n    typedef CachedValueTestData::Test CachedValueTest;\n}\n\n#endif", "meta": {"hexsha": "ada4664962599962b12631c8c643d9d5ddda376b", "size": 29075, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test-suite-adjoint/adjointswaptionimpl.hpp", "max_stars_repo_name": "fduffy/QuantLibAdjoint", "max_stars_repo_head_hexsha": "d9d355db4f46824bb5e607e28381943aef994ed4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 41.0, "max_stars_repo_stars_event_min_datetime": "2016-03-19T02:31:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T13:23:20.000Z", "max_issues_repo_path": "test-suite-adjoint/adjointswaptionimpl.hpp", "max_issues_repo_name": "fduffy/QuantLibAdjoint", "max_issues_repo_head_hexsha": "d9d355db4f46824bb5e607e28381943aef994ed4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test-suite-adjoint/adjointswaptionimpl.hpp", "max_forks_repo_name": "fduffy/QuantLibAdjoint", "max_forks_repo_head_hexsha": "d9d355db4f46824bb5e607e28381943aef994ed4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2016-03-17T14:14:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T10:33:19.000Z", "avg_line_length": 34.6543504172, "max_line_length": 108, "alphanum_fraction": 0.500361135, "num_tokens": 6492, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.734119526900183, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.4960919891959941}}
{"text": "/**\n *           c++11-only implementation of the L-BFGS-B algorithm\n *\n * Copyright (c) 2014 Patrick Wieschollek\n *               https://github.com/PatWie/LBFGSB\n * All rights reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n\n * The above copyright notice and this permission notice shall be included in 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 LBFGSB_H_\n#define LBFGSB_H_\n\n#include \"meta.h\"\n\n#include <list>\n#include <stdio.h>\n#include <iostream>\n#include <functional>\n#include <vector>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n/* coded from scratch !!!\n * based on the paper\n * A LIMITED MEMORY ALGORITHM FOR BOUND CONSTRAINED OPTIMIZATION\n * (Byrd, Lu, Nocedal, Zhu)\n */\n\nnamespace PatWieLBFGSB {\n\nclass LBFGSB {\n\n\t// contains options for optimization process\n\tOptions Options_;\n\n\t// oracles for function value and gradient\n\tFunctionOracleType FunctionObjectiveOracle_;\n\tGradientOracleType FunctionGradientOracle_;\n\n\tMatrix W, M;\n\tVector lb, ub;\n\tdouble theta;\n\tint DIM;\n\n\tstd::list<Vector> xHistory;\n\npublic:\n\n\tVector XOpt;\n\n\tLBFGSB(const Vector &l, const Vector &u) :\n\t\t\tlb(l), ub(u), theta(1.0), DIM(l.rows()) {\n\t\tlb = l;\n\t\tub = u;\n\t\ttheta = 1.0;\n\t\tDIM = l.rows();\n\t\tW = Matrix::Zero(DIM, 0);\n\t\tM = Matrix::Zero(0, 0);\n\t}\n\n\tLBFGSB(Options &Options, const Vector &l, const Vector &u) {\n\t\tOptions_ = Options;\n\t\tlb = l;\n\t\tub = u;\n\t\ttheta = 1.0;\n\t\tDIM = l.rows();\n\t\tW = Matrix::Zero(DIM, 0);\n\t\tM = Matrix::Zero(0, 0);\n\n\t}\n\n\t/// <summary>\n\t/// find cauchy point in x\n\t/// </summary>\n\t/// <parameter name=\"x\">start in x</parameter>\n\tvoid GetGeneralizedCauchyPoint(Vector &x, Vector &g, Vector &x_cauchy,\n\t\t\tVector &c) {\n\t\tconst int DIM = x.rows();\n\t\t// PAGE 8\n\t\t// Algorithm CP: Computation of the generalized Cauchy point\n\t\t// Given x,l,u,g, and B = \\theta I-WMW\n\n\t\t// {all t_i} = { (idx,value), ... }\n\t\t// TODO: use \"std::set\" ?\n\t\tstd::vector<std::pair<int, double> > SetOfT;\n\t\t// the feasible set is implicitly given by \"SetOfT - {t_i==0}\"\n\t\tVector d = Vector::Zero(DIM, 1);\n\n\t\t// n operations\n\t\tfor (int j = 0; j < DIM; j++) {\n\t\t\tif (g(j) == 0) {\n\t\t\t\tSetOfT.push_back(std::make_pair(j, INF));\n\t\t\t} else {\n\t\t\t\tdouble tmp = 0;\n\t\t\t\tif (g(j) < 0) {\n\t\t\t\t\ttmp = (x(j) - ub(j)) / g(j);\n\t\t\t\t} else {\n\t\t\t\t\ttmp = (x(j) - lb(j)) / g(j);\n\t\t\t\t}\n\t\t\t\td(j) = -g(j);\n\t\t\t\tSetOfT.push_back(std::make_pair(j, tmp));\n\t\t\t}\n\n\t\t}Debug(d.transpose());\n\n\t\t// paper: using heapsort\n\t\t// sortedindices [1,0,2] means the minimal element is on the 1th entry\n\t\tstd::vector<int> SortedIndices = sort_indexes(SetOfT);\n\n\t\tx_cauchy = x;\n\t\t// Initialize\n\t\t// p := \tW^T*p\n\t\tVector p = (W.transpose() * d);\t\t\t\t\t\t// (2mn operations)\n\t\t// c := \t0\n\t\tc = Eigen::MatrixXd::Zero(M.rows(), 1);\n\t\t// f' := \tg^T*d = -d^Td\n\t\tdouble f_prime = -d.dot(d);\t\t\t\t\t\t\t// (n operations)\n\t\t// f'' :=\t\\theta*d^T*d-d^T*W*M*W^T*d = -\\theta*f' - p^T*M*p\n\t\tdouble f_doubleprime = (double) (-1.0 * theta) * f_prime - p.dot(M * p);// (O(m^2) operations)\n\t\t// \\delta t_min :=\t-f'/f''\n\t\tdouble dt_min = -f_prime / f_doubleprime;\n\t\t// t_old := \t0\n\t\tdouble t_old = 0;\n\t\t// b := \targmin {t_i , t_i >0}\n\t\tint i = 0;\n\t\tfor (int j = 0; j < DIM; j++) {\n\t\t\ti = j;\n\t\t\tif (SetOfT[SortedIndices[j]].second != 0)\n\t\t\t\tbreak;\n\t\t}\n\t\tint b = SortedIndices[i];\n\t\t// see below\n\t\t// t        \t\t\t:= \tmin{t_i : i in F}\n\t\tdouble t = SetOfT[b].second;\n\t\t// \\delta t \t\t\t:= \tt - 0\n\t\tdouble dt = t - t_old;\n\n\t\t// examination of subsequent segments\n\t\twhile ((dt_min >= dt) && (i < DIM)) {\n\t\t\tif (d(b) > 0)\n\t\t\t\tx_cauchy(b) = ub(b);\n\t\t\telse if (d(b) < 0)\n\t\t\t\tx_cauchy(b) = lb(b);\n\n\t\t\t// z_b = x_p^{cp} - x_b\n\t\t\tdouble zb = x_cauchy(b) - x(b);\n\t\t\t// c   :=  c +\\delta t*p\n\t\t\tc += dt * p;\n\t\t\t// cache\n\t\t\tVector wbt = W.row(b);\n\n\t\t\tf_prime += dt * f_doubleprime + (double) g(b) * g(b)\n\t\t\t\t\t+ (double) theta * g(b) * zb\n\t\t\t\t\t- (double) g(b) * wbt.transpose() * (M * c);\n\t\t\tf_doubleprime += (double) -1.0 * theta * g(b) * g(b)\n\t\t\t\t\t- (double) 2.0 * (g(b) * (wbt.dot(M * p)))\n\t\t\t\t\t- (double) g(b) * g(b) * wbt.transpose() * (M * wbt);\n\t\t\tp += g(b) * wbt.transpose();\n\t\t\td(b) = 0;\n\t\t\tdt_min = -f_prime / f_doubleprime;\n\t\t\tt_old = t;\n\t\t\t++i;\n\t\t\tif (i < DIM) {\n\t\t\t\tb = SortedIndices[i];\n\t\t\t\tt = SetOfT[b].second;\n\t\t\t\tdt = t - t_old;\n\t\t\t}\n\n\t\t}\n\n\t\tdt_min = fmax(dt_min, 0.0);\n\t\tt_old += dt_min;\n\n\t\tDebug(SortedIndices[0]<< \" \"<< SortedIndices[1]);\n\n#pragma omp parallel for\n\t\tfor (int ii = i; ii < x_cauchy.rows(); ii++) {\n\t\t\tx_cauchy(SortedIndices[ii]) = x(SortedIndices[ii])\n\t\t\t\t\t+ t_old * d(SortedIndices[ii]);\n\t\t}Debug(x_cauchy.transpose());\n\n\t\tc += dt_min * p;\n\t\tDebug(c.transpose());\n\n\t}\n\n\t/// <summary>\n\t/// find valid alpha for (8.5)\n\t/// </summary>\n\t/// <parameter name=\"x_cp\">cauchy point</parameter>\n\t/// <parameter name=\"du\">unconstrained solution of subspace minimization</parameter>\n\t/// <parameter name=\"FreeVariables\">flag (1 if is free variable and 0 if is not free variable)</parameter>\n\tdouble FindAlpha(Vector &x_cp, Vector &du,\n\t\t\tstd::vector<int> &FreeVariables) {\n\t\t/* this returns\n\t\t * a* = max {a : a <= 1 and  l_i-xc_i <= a*d_i <= u_i-xc_i}\n\t\t */\n\t\tdouble alphastar = 1;\n\t\tconst unsigned int n = FreeVariables.size();\n\t\tfor (unsigned int i = 0; i < n; i++) {\n\t\t\tif (du(i) > 0) {\n\t\t\t\talphastar = fmin(alphastar,\n\t\t\t\t\t\t(ub(FreeVariables[i]) - x_cp(FreeVariables[i]))\n\t\t\t\t\t\t\t\t/ du(i));\n\t\t\t} else {\n\t\t\t\talphastar = fmin(alphastar,\n\t\t\t\t\t\t(lb(FreeVariables[i]) - x_cp(FreeVariables[i]))\n\t\t\t\t\t\t\t\t/ du(i));\n\t\t\t}\n\t\t}\n\t\treturn alphastar;\n\t}\n\n\t/// <summary>\n\t/// using linesearch to determine step width\n\t/// </summary>\n\t/// <parameter name=\"x\">start in x</parameter>\n\t/// <parameter name=\"dx\">direction</parameter>\n\t/// <parameter name=\"f\">current value of objective (will be changed)</parameter>\n\t/// <parameter name=\"g\">current gradient of objective (will be changed)</parameter>\n\t/// <parameter name=\"t\">step width (will be changed)</parameter>\n\tvoid LineSearch(Vector &x, Vector dx, double &f, Vector &g, double &t) {\n\n\t\tconst double alpha = 0.2;\n\t\tconst double beta = 0.8;\n\n\t\tconst double f_in = f;\n\t\tconst Vector g_in = g;\n\t\tconst double Cache = alpha * g_in.dot(dx);\n\n\t\tt = 1.0;\n\t\tf = FunctionObjectiveOracle_(x + t * dx);\n\t\twhile (f > f_in + t * Cache) {\n\t\t\tt *= beta;\n\t\t\tf = FunctionObjectiveOracle_(x + t * dx);\n\t\t}\n\t\tFunctionGradientOracle_(x + t * dx, g);\n\t\tx += t * dx;\n\n\t}\n\n\t/// <summary>\n\t/// direct primal approach\n\t/// </summary>\n\t/// <parameter name=\"x\">start in x</parameter>\n\tvoid SubspaceMinimization(Vector &x_cauchy, Vector &x, Vector &c, Vector &g,\n\t\t\tVector &SubspaceMin) {\n\n\t\t// cached value: ThetaInverse=1/theta;\n\t\tdouble theta_inverse = 1 / theta;\n\n\t\t// size of \"t\"\n\t\tstd::vector<int> FreeVariablesIndex;\n\t\tDebug(x_cauchy.transpose());\n\n\t\t//std::cout << \"free vars \" << FreeVariables.rows() << std::endl;\n\t\tfor (int i = 0; i < x_cauchy.rows(); i++) {\n\t\t\tDebug(x_cauchy(i) << \" \"<< ub(i) << \" \"<< lb(i));\n\t\t\tif ((x_cauchy(i) != ub(i)) && (x_cauchy(i) != lb(i))) {\n\t\t\t\tFreeVariablesIndex.push_back(i);\n\t\t\t}\n\t\t}\n\t\tconst int FreeVarCount = FreeVariablesIndex.size();\n\n\t\tMatrix WZ = Matrix::Zero(W.cols(), FreeVarCount);\n\n\t\tfor (int i = 0; i < FreeVarCount; i++)\n\t\t\tWZ.col(i) = W.row(FreeVariablesIndex[i]);\n\n\t\tDebug(WZ);\n\n\t\t// r=(g+theta*(x_cauchy-x)-W*(M*c));\n\t\tDebug(g);Debug(x_cauchy);Debug(x);\n\t\tVector rr = (g + theta * (x_cauchy - x) - W * (M * c));\n\t\t// r=r(FreeVariables);\n\t\tVector r = Matrix::Zero(FreeVarCount, 1);\n\t\tfor (int i = 0; i < FreeVarCount; i++)\n\t\t\tr.row(i) = rr.row(FreeVariablesIndex[i]);\n\n\t\tDebug(r.transpose());\n\n\t\t// STEP 2: \"v = w^T*Z*r\" and STEP 3: \"v = M*v\"\n\t\tVector v = M * (WZ * r);\n\t\t// STEP 4: N = 1/theta*W^T*Z*(W^T*Z)^T\n\t\tMatrix N = theta_inverse * WZ * WZ.transpose();\n\t\t// N = I - MN\n\t\tN = Matrix::Identity(N.rows(), N.rows()) - M * N;\n\t\t// STEP: 5\n\t\t// v = N^{-1}*v\n\t\tv = N.lu().solve(v);\n\t\t// STEP: 6\n\t\t// HERE IS A MISTAKE IN THE ORIGINAL PAPER!\n\t\tVector du = -theta_inverse * r\n\t\t\t\t- theta_inverse * theta_inverse * WZ.transpose() * v;\n\t\tDebug(du.transpose());\n\t\t// STEP: 7\n\t\tdouble alpha_star = FindAlpha(x_cauchy, du, FreeVariablesIndex);\n\n\t\t// STEP: 8\n\t\tVector dStar = alpha_star * du;\n\n\t\tSubspaceMin = x_cauchy;\n\t\tfor (int i = 0; i < FreeVarCount; i++) {\n\t\t\tSubspaceMin(FreeVariablesIndex[i]) = SubspaceMin(\n\t\t\t\t\tFreeVariablesIndex[i]) + dStar(i);\n\t\t}\n\t}\n\n\tvoid Solve(Vector &x0, const FunctionOracleType& FunctionValue,\n\t\t\tconst GradientOracleType& FunctionGradient) {\n\t\tFunctionObjectiveOracle_ = FunctionValue;\n\t\tFunctionGradientOracle_ = FunctionGradient;\n\n\t\tAssert(x0.rows() == lb.rows(), \"lower bound size incorrect\");\n\t\tAssert(x0.rows() == ub.rows(), \"upper bound size incorrect\");\n\n\t\tDebug(x0.transpose());Debug(lb.transpose());Debug(ub.transpose());\n\n\t\tAssert((x0.array() >= lb.array()).all(),\n\t\t\t\t\"seed is not feasible (violates lower bound)\");\n\t\tAssert((x0.array() <= ub.array()).all(),\n\t\t\t\t\"seed is not feasible (violates upper bound)\");\n\n\t\tconst int DIM = x0.rows();\n\n\t\txHistory.push_back(x0);\n\n\t\tMatrix yHistory = Matrix::Zero(DIM, 0);\n\t\tMatrix sHistory = Matrix::Zero(DIM, 0);\n\n\t\tVector x = x0, g;\n\t\tint k = 0;\n\n\t\tdouble f = FunctionObjectiveOracle_(x);\n\t\tFunctionGradientOracle_(x, g);\n\t\tDebug(f);Debug(g.transpose());\n\n\t\ttheta = 1.0;\n\n\t\tW = Matrix::Zero(DIM, 0);\n\t\tM = Matrix::Zero(0, 0);\n\n\t\tauto noConvergence =\n\t\t\t\t[&](Vector& x, Vector& g)->bool {\n\t\t\t\t\treturn (((x - g).cwiseMax(lb).cwiseMin(ub) - x).lpNorm<Eigen::Infinity>()>= Options_.tol);\n\t\t\t\t};\n\n\t\twhile (noConvergence(x, g) && (k < Options_.maxIter)) {\n\t\t\tDebug(\"iteration \"<<k)\n\t\t\tdouble f_old = f;\n\t\t\tVector x_old = x;\n\t\t\tVector g_old = g;\n\n\t\t\t// STEP 2: compute the cauchy point by algorithm CP\n\t\t\tVector CauchyPoint = Matrix::Zero(DIM, 1), c = Matrix::Zero(DIM, 1);\n\t\t\tGetGeneralizedCauchyPoint(x, g, CauchyPoint, c);\n\t\t\t// STEP 3: compute a search direction d_k by the primal method\n\t\t\tVector SubspaceMin;\n\t\t\tSubspaceMinimization(CauchyPoint, x, c, g, SubspaceMin);\n\n\t\t\tMatrix H;\n\t\t\tdouble Length = 0;\n\n\t\t\t// STEP 4: perform linesearch and STEP 5: compute gradient\n\t\t\tLineSearch(x, SubspaceMin - x, f, g, Length);\n\n\t\t\txHistory.push_back(x);\n\n\t\t\t// prepare for next iteration\n\t\t\tVector newY = g - g_old;\n\t\t\tVector newS = x - x_old;\n\n\t\t\t// STEP 6:\n\t\t\tdouble test = newS.dot(newY);\n\t\t\ttest = (test < 0) ? -1.0 * test : test;\n\n\t\t\tif (test > EPS * newY.squaredNorm()) {\n\t\t\t\tif (k < Options_.m) {\n\t\t\t\t\tyHistory.conservativeResize(DIM, k + 1);\n\t\t\t\t\tsHistory.conservativeResize(DIM, k + 1);\n\t\t\t\t} else {\n\n\t\t\t\t\tyHistory.leftCols(Options_.m - 1) = yHistory.rightCols(\n\t\t\t\t\t\t\tOptions_.m - 1).eval();\n\t\t\t\t\tsHistory.leftCols(Options_.m - 1) = sHistory.rightCols(\n\t\t\t\t\t\t\tOptions_.m - 1).eval();\n\t\t\t\t}\n\t\t\t\tyHistory.rightCols(1) = newY;\n\t\t\t\tsHistory.rightCols(1) = newS;\n\n\t\t\t\t// STEP 7:\n\t\t\t\ttheta = (double) (newY.transpose() * newY)\n\t\t\t\t\t\t/ (newY.transpose() * newS);\n\n\t\t\t\tW = Matrix::Zero(yHistory.rows(),\n\t\t\t\t\t\tyHistory.cols() + sHistory.cols());\n\n\t\t\t\tW << yHistory, (theta * sHistory);\n\n\t\t\t\tMatrix A = sHistory.transpose() * yHistory;\n\t\t\t\tMatrix L = A.triangularView<Eigen::StrictlyLower>();\n\t\t\t\tMatrix MM(A.rows() + L.rows(), A.rows() + L.cols());\n\t\t\t\tMatrix D = -1 * A.diagonal().asDiagonal();\n\t\t\t\tMM << D, L.transpose(), L, ((sHistory.transpose() * sHistory)\n\t\t\t\t\t\t* theta);\n\n\t\t\t\tM = MM.inverse();\n\t\t\t}\n\n\t\t\tVector ttt = Matrix::Zero(1, 1);\n\t\t\tttt(0) = f_old - f;\n\t\t\tDebug( \"--> \"<< ttt.norm());\n\t\t\tif (ttt.norm() < Options_.tol) {\n\t\t\t\t// successive function values too similar\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tk++;\n\n\t\t}\n\n\t\tXOpt = x;\n\t\tx0 = x;\n\n\t}\n};\n\n}\n\n#endif /* LBFGSB_H_ */\n", "meta": {"hexsha": "323428455ea5e7c503320881278edf68d5759f4a", "size": 12249, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/lbfgsb.hpp", "max_stars_repo_name": "NoahAmsel/LBFGSB", "max_stars_repo_head_hexsha": "753442cdc1453a7a04d7c0a45d496d135cf2b107", "max_stars_repo_licenses": ["MIT"], "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/lbfgsb.hpp", "max_issues_repo_name": "NoahAmsel/LBFGSB", "max_issues_repo_head_hexsha": "753442cdc1453a7a04d7c0a45d496d135cf2b107", "max_issues_repo_licenses": ["MIT"], "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/lbfgsb.hpp", "max_forks_repo_name": "NoahAmsel/LBFGSB", "max_forks_repo_head_hexsha": "753442cdc1453a7a04d7c0a45d496d135cf2b107", "max_forks_repo_licenses": ["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.4026845638, "max_line_length": 107, "alphanum_fraction": 0.6073965222, "num_tokens": 4007, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195152660688, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.4960919765403507}}
{"text": "#include <polyvec/api.hpp>\n\n#include <polyvec/mc/get_bounding_box.hpp>\n\n#include <Eigen/Geometry>\n\nNAMESPACE_BEGIN(polyfit)\nNAMESPACE_BEGIN(mc)\n\n\nEigen::AlignedBox<int, 2>\nget_bounding_box(const std::vector<Eigen::Matrix2Xi>& regions) {\n   Eigen::AlignedBox<int, 2> bbox;\n\n    for ( int i = 0; i < ( int ) regions.size(); ++i ) {\n        for ( int j = 0; j < ( int ) regions[i].cols(); ++j ) {\n            bbox.extend ( regions[i].col ( j ) );\n        }\n    }\n    return bbox;\n}\n\nNAMESPACE_END(mc)\nNAMESPACE_END(polyfit)\n", "meta": {"hexsha": "f9b4f515bdda8f155e92595f080205a3ec8c57ac", "size": 521, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/polyvec/mc/get_bounding_box.cpp", "max_stars_repo_name": "ShnitzelKiller/polyfit", "max_stars_repo_head_hexsha": "51ddc6365a794db1678459140658211cb78f65b1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2020-08-17T17:25:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T05:49:12.000Z", "max_issues_repo_path": "source/polyvec/mc/get_bounding_box.cpp", "max_issues_repo_name": "ShnitzelKiller/polyfit", "max_issues_repo_head_hexsha": "51ddc6365a794db1678459140658211cb78f65b1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-08-26T13:54:59.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-21T07:19:22.000Z", "max_forks_repo_path": "source/polyvec/mc/get_bounding_box.cpp", "max_forks_repo_name": "ShnitzelKiller/polyfit", "max_forks_repo_head_hexsha": "51ddc6365a794db1678459140658211cb78f65b1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-08-26T23:26:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-04T09:06:07.000Z", "avg_line_length": 20.84, "max_line_length": 64, "alphanum_fraction": 0.6199616123, "num_tokens": 147, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.7490872075132153, "lm_q1q2_score": 0.4958379586595889}}
{"text": "//=======================================================================\n// Copyright 2001 Jeremy G. Siek, Andrew Lumsdaine, Lie-Quan Lee, \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, Indiana University,\n// Bloomington, IN 47405.\n//\n// Permission to modify the code and to distribute the code is\n// granted, provided the text of this NOTICE is retained, a notice if\n// the code was modified is included with the above COPYRIGHT NOTICE\n// and with the COPYRIGHT NOTICE in the LICENSE file, and that the\n// LICENSE 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#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/kruskal_min_spanning_tree.hpp>\n#include <fstream>\n#include <iostream>\n\nint\nmain()\n{\n  using namespace boost;\n  typedef adjacency_list < vecS, vecS, undirectedS,\n    no_property, property < edge_weight_t, int > > Graph;\n  typedef graph_traits < Graph >::edge_descriptor Edge;\n  typedef graph_traits < Graph >::vertex_descriptor Vertex;\n  typedef std::pair<int, int> E;\n\n  const int num_nodes = 5;\n  E edge_array[] = { E(0, 2), E(1, 3), E(1, 4), E(2, 1), E(2, 3),\n    E(3, 4), E(4, 0), E(4, 1)\n  };\n  int weights[] = { 1, 1, 2, 7, 3, 1, 1, 1 };\n  int num_edges = sizeof(edge_array) / sizeof(E);\n#if defined(BOOST_MSVC) && BOOST_MSVC <= 1300\n  Graph g(num_nodes);\n  property_map<Graph, edge_weight_t>::type weightmap = get(edge_weight, g);\n  for (std::size_t j = 0; j < num_edges; ++j) {\n    Edge e; bool inserted;\n    tie(e, inserted) = add_edge(edge_array[j].first, edge_array[j].second, g);\n    weightmap[e] = weights[j];\n  }\n#else\n  Graph g(edge_array, edge_array + num_edges, weights, num_nodes);\n#endif\n  property_map < Graph, edge_weight_t >::type weight = get(edge_weight, g);\n  std::vector < Edge > spanning_tree;\n\n  kruskal_minimum_spanning_tree(g, std::back_inserter(spanning_tree));\n\n  std::cout << \"Print the edges in the MST:\" << std::endl;\n  for (std::vector < Edge >::iterator ei = spanning_tree.begin();\n       ei != spanning_tree.end(); ++ei) {\n    std::cout << source(*ei, g) << \" <--> \" << target(*ei, g)\n      << \" with weight of \" << weight[*ei]\n      << std::endl;\n  }\n\n  std::ofstream fout(\"figs/kruskal-eg.dot\");\n  fout << \"graph A {\\n\"\n    << \" rankdir=LR\\n\"\n    << \" size=\\\"3,3\\\"\\n\"\n    << \" ratio=\\\"filled\\\"\\n\"\n    << \" edge[style=\\\"bold\\\"]\\n\" << \" node[shape=\\\"circle\\\"]\\n\";\n  graph_traits<Graph>::edge_iterator eiter, eiter_end;\n  for (tie(eiter, eiter_end) = edges(g); eiter != eiter_end; ++eiter) {\n    fout << source(*eiter, g) << \" -- \" << target(*eiter, g);\n    if (std::find(spanning_tree.begin(), spanning_tree.end(), *eiter)\n        != spanning_tree.end())\n      fout << \"[color=\\\"black\\\"]\\n\";\n    else\n      fout << \"[color=\\\"gray\\\"]\\n\";\n  }\n  fout << \"}\\n\";\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "b7fbcc8de169027ead279e4a321c3ae412392712", "size": 3377, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "inst/boostExamples/kruskal-example.cpp", "max_stars_repo_name": "HenrikBengtsson/RBGL", "max_stars_repo_head_hexsha": "9e34efd0dcab3babe1cea49b060a643bee79931c", "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": "inst/boostExamples/kruskal-example.cpp", "max_issues_repo_name": "HenrikBengtsson/RBGL", "max_issues_repo_head_hexsha": "9e34efd0dcab3babe1cea49b060a643bee79931c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-09-05T02:26:35.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-30T20:28:53.000Z", "max_forks_repo_path": "inst/boostExamples/kruskal-example.cpp", "max_forks_repo_name": "HenrikBengtsson/RBGL", "max_forks_repo_head_hexsha": "9e34efd0dcab3babe1cea49b060a643bee79931c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-12-19T10:17:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-14T01:22:29.000Z", "avg_line_length": 38.816091954, "max_line_length": 78, "alphanum_fraction": 0.6339946698, "num_tokens": 931, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850402140659, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.4958352092059904}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// Unit Test\n\n// Copyright (c) 2007-2011 Barend Gehrels, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n\n#include <iostream>\n\n#include <geometry_test_common.hpp>\n\n\n#include <boost/foreach.hpp>\n\n#include <boost/geometry/algorithms/intersection.hpp>\n\n#include <boost/geometry/algorithms/detail/overlay/get_turn_info.hpp>\n#include <boost/geometry/algorithms/detail/overlay/get_relative_order.hpp>\n\n#include <boost/geometry/geometries/point_xy.hpp>\n\n#if defined(TEST_WITH_SVG)\n#  include <boost/geometry/extensions/io/svg/svg_mapper.hpp>\n#endif\n\n\ntemplate <typename P, typename T>\nvoid test_with_point(std::string const& caseid,\n                T pi_x, T pi_y, T pj_x, T pj_y,\n                T ri_x, T ri_y, T rj_x, T rj_y,\n                T si_x, T si_y, T sj_x, T sj_y,\n                int expected_order)\n{\n    P pi = bg::make<P>(pi_x, pi_y);\n    P pj = bg::make<P>(pj_x, pj_y);\n    P ri = bg::make<P>(ri_x, ri_y);\n    P rj = bg::make<P>(rj_x, rj_y);\n    P si = bg::make<P>(si_x, si_y);\n    P sj = bg::make<P>(sj_x, sj_y);\n\n    int order = bg::detail::overlay::get_relative_order<P>::apply(pi, pj, ri, rj, si, sj);\n\n    BOOST_CHECK_EQUAL(order, expected_order);\n\n\n\n\n    /*\n    std::cout << caseid\n        << (caseid.find(\"_\") == std::string::npos ? \"  \" : \"\")\n        << \" \" << method\n        << \" \" << detected\n        << \" \" << order\n        << std::endl;\n    */\n\n\n\n/*#if defined(TEST_WITH_SVG)\n    {\n        std::ostringstream filename;\n        filename << \"get_turn_info_\" << caseid\n            << \"_\" << string_from_type<typename bg::coordinate_type<P>::type>::name()\n            << \".svg\";\n\n        std::ofstream svg(filename.str().c_str());\n\n        bg::svg_mapper<P> mapper(svg, 500, 500);\n        mapper.add(bg::make<P>(0, 0));\n        mapper.add(bg::make<P>(10, 10));\n\n        bg::model::linestring<P> p; p.push_back(pi); p.push_back(pj); p.push_back(pk);\n        bg::model::linestring<P> q; q.push_back(qi); q.push_back(qj); q.push_back(qk);\n        mapper.map(p, \"opacity:0.8;stroke:rgb(0,192,0);stroke-width:3\");\n        mapper.map(q, \"opacity:0.8;stroke:rgb(0,0,255);stroke-width:3\");\n\n        std::string style =  \";font-family='Verdana';font-weight:bold\";\n        std::string align = \";text-anchor:end;text-align:end\";\n        int offset = 8;\n\n        mapper.text(pi, \"pi\", \"fill:rgb(0,192,0)\" + style, offset, offset);\n        mapper.text(pj, \"pj\", \"fill:rgb(0,192,0)\" + style, offset, offset);\n        mapper.text(pk, \"pk\", \"fill:rgb(0,192,0)\" + style, offset, offset);\n\n        mapper.text(qi, \"qi\", \"fill:rgb(0,0,255)\" + style + align, -offset, offset);\n        mapper.text(qj, \"qj\", \"fill:rgb(0,0,255)\" + style + align, -offset, offset);\n        mapper.text(qk, \"qk\", \"fill:rgb(0,0,255)\" + style + align, -offset, offset);\n\n\n        int factor = 1; // second info, if any, will go left by factor -1\n        int ch = '1';\n        for (typename tp_vector::const_iterator it = info.begin();\n            it != info.end();\n            ++it, factor *= -1, ch++)\n        {\n            bool at_j = it->method == bg::detail::overlay::method_crosses;\n            std::string op;\n            op += operation_char(it->operations[0].operation);\n            align = \";text-anchor:middle;text-align:center\";\n            mapper.text(at_j ? pj : pk, op, \"fill:rgb(255,128,0)\" + style + align, offset * factor, -offset);\n\n            op.clear();\n            op += operation_char(it->operations[1].operation);\n            mapper.text(at_j ? qj : qk, op, \"fill:rgb(255,128,0)\" + style + align, offset * factor, -offset);\n\n            // Map intersection point + method\n            mapper.map(it->point, \"opacity:0.8;fill:rgb(255,0,0);stroke:rgb(0,0,100);stroke-width:1\");\n\n            op.clear();\n            op += method_char(it->method);\n            if (info.size() != 1)\n            {\n                op += ch;\n                op += \" p:\"; op += operation_char(it->operations[0].operation);\n                op += \" q:\"; op += operation_char(it->operations[1].operation);\n            }\n            mapper.text(it->point, op, \"fill:rgb(255,0,0)\" + style, offset, -offset);\n        }\n    }\n#endif\n*/\n}\n\n\n\ntemplate <typename P>\nvoid test_all()\n{\n    test_with_point<P, double>(\"OLR1\",\n            5, 1,   5, 8, // p\n            3, 5,   7, 5, // r\n            3, 3,   7, 2, // s\n            1);\n    test_with_point<P, double>(\"OLR2\",\n            5, 1,   5, 8, // p\n            3, 5,   7, 5, // r\n            3, 7,   7, 6, // s\n            -1);\n    test_with_point<P, double>(\"OLR3\",\n            5, 1,   5, 8, // p\n            3, 5,   7, 5, // r\n            4, 2,   9, 6, // s\n            1);\n    test_with_point<P, double>(\"OLR4\",\n            5, 1,   5, 8, // p\n            3, 5,   7, 5, // r\n            3, 8,   9, 4, // s\n            -1);\n    test_with_point<P, double>(\"OLR5\",\n            5, 1,   5, 8, // p\n            3, 5,   7, 5, // r\n            4, 2,   8, 6, // s\n            1);\n    test_with_point<P, double>(\"OLR6\",\n            5, 1,   5, 8, // p\n            3, 5,   7, 5, // r\n            3, 7,   9, 4, // s\n            -1);\n    test_with_point<P, double>(\"OLR7\",\n            5, 1,   5, 8, // p\n            3, 5,   7, 5, // r\n            1, 4,   7, 7, // s\n            -1);\n    test_with_point<P, double>(\"OLR8\",\n            5, 1,   5, 8, // p\n            3, 5,   7, 5, // r\n            1, 6,   7, 3, // s\n            1);\n\n\n    test_with_point<P, double>(\"OD1\",\n            5, 1,   5, 8, // p\n            3, 5,   7, 5, // r\n            7, 2,   3, 3, // s\n            1);\n\n    test_with_point<P, double>(\"OD9\",\n            5, 1,   5, 8, // p\n            3, 5,   7, 5, // r\n            7, 5,   3, 3, // s\n            1);\n    test_with_point<P, double>(\"OD10\",\n            5, 1,   5, 8, // p\n            3, 5,   7, 5, // r\n            7, 5,   3, 7, // s\n            -1);\n    test_with_point<P, double>(\"OD11\",\n            5, 1,   5, 8, // p\n            7, 5,   3, 5, // r\n            3, 5,   7, 7, // s\n            -1);\n    test_with_point<P, double>(\"OD12\",\n            5, 1,   5, 8, // p\n            7, 5,   3, 5, // r\n            3, 5,   7, 3, // s\n            1);\n}\n\n\nint test_main(int, char* [])\n{\n    test_all<bg::model::d2::point_xy<double> >();\n    return 0;\n}\n", "meta": {"hexsha": "b8b7ec798430484458b1115aada750d65cbf136b", "size": 6402, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/test/algorithms/overlay/relative_order.cpp", "max_stars_repo_name": "olegshnitko/libboost", "max_stars_repo_head_hexsha": "548eb6365af3724d8f4b47ebbabf7eb3ad8e66a8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-10-31T00:40:22.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-31T00:40:22.000Z", "max_issues_repo_path": "libs/geometry/test/algorithms/overlay/relative_order.cpp", "max_issues_repo_name": "olegshnitko/libboost", "max_issues_repo_head_hexsha": "548eb6365af3724d8f4b47ebbabf7eb3ad8e66a8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-01-17T10:11:43.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-17T10:11:43.000Z", "max_forks_repo_path": "libs/geometry/test/algorithms/overlay/relative_order.cpp", "max_forks_repo_name": "olegshnitko/libboost", "max_forks_repo_head_hexsha": "548eb6365af3724d8f4b47ebbabf7eb3ad8e66a8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.7788461538, "max_line_length": 109, "alphanum_fraction": 0.4853170884, "num_tokens": 2136, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.49583520051073743}}
{"text": "// Boost.Geometry\n// Unit Test\n\n// Copyright (c) 2021 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#include <geometry_test_common.hpp>\n\n#include <boost/geometry/algorithms/detail/overlay/get_ring.hpp>\n\n#include <boost/geometry/algorithms/area.hpp>\n#include <boost/geometry/algorithms/is_valid.hpp>\n\n#include <boost/geometry/strategies/strategies.hpp>\n#include <boost/geometry/geometries/geometries.hpp>\n#include <boost/geometry/io/wkt/wkt.hpp>\n\nnamespace\n{\n\nbool g_debug = false;\n\nstd::string const simplex = \"POLYGON((0 2,1 2,1 1,0 1,0 2))\";\nstd::string const case_a = \"POLYGON((1 0,0 5,5 2,1 0),(2 1,3 2,1 3,2 1))\";\nstd::string const multi = \"MULTIPOLYGON(((0 0,0 5,5 5,5 0,0 0),(1 1,2 1,2 2,1 2,1 1),(3 3,4 3,4 4,3 4,3 3)),((6 6,6 10,10 10,10 6,6 6),(7 7,8 7,8 8,7 7)))\";\n}\n\ntemplate <typename Geometry>\nvoid test_get_ring(std::string const& case_id, std::string const& wkt,\n                   bg::ring_identifier const& ring_id,\n                   std::string const& expected_wkt)\n{\n    using tag = typename bg::tag<Geometry>::type;\n\n    Geometry geometry;\n    bg::read_wkt(wkt, geometry);\n\n    auto const ring = bg::detail::overlay::get_ring<tag>::apply(ring_id, geometry);\n\n    if (g_debug)\n    {\n        std::cout << case_id\n                  << \" valid: \" << bg::is_valid(geometry)\n                  << \" area: \" << bg::area(geometry)\n                  << \" area(ring): \" << bg::area(ring)\n                  << \" wkt(ring): \" << bg::wkt(ring)\n                  << std::endl;\n    }\n\n    std::ostringstream out;\n    out << bg::wkt(ring);\n    std::string const detected = out.str();\n    BOOST_CHECK_MESSAGE(detected == expected_wkt, \"get_ring: \" << case_id\n                        << \" expected: \" << expected_wkt\n                        << \" detected: \" << detected);\n}\n\ntemplate <typename Geometry>\nvoid test_segment_count_on_ring(std::string const& case_id, std::string const& wkt,\n                   bg::ring_identifier const& ring_id, bg::signed_size_type expected_count)\n{\n    Geometry geometry;\n    bg::read_wkt(wkt, geometry);\n\n    auto const detected_count = bg::detail::overlay::segment_count_on_ring(geometry, ring_id);\n\n    BOOST_CHECK_MESSAGE(detected_count == expected_count,\n                        \"test_get_ring: \" << case_id\n                        << \" expected: \" << expected_count\n                        << \" detected: \" << detected_count);\n}\n\ntemplate <typename Geometry>\nvoid test_segment_distance(std::string const& case_id, int line, std::string const& wkt,\n                           bg::segment_identifier const& id1,\n                           bg::segment_identifier const& id2,\n                           bg::signed_size_type expected_distance)\n{\n    Geometry geometry;\n    bg::read_wkt(wkt, geometry);\n\n    auto const detected_distance = bg::detail::overlay::segment_distance(geometry, id1, id2);\n\n    BOOST_CHECK_MESSAGE(detected_distance == expected_distance,\n                        \"segment_distance: \" << case_id << \" (\" << line << \")\"\n                        << \" expected: \" << expected_distance\n                        << \" detected: \" << detected_distance);\n}\n\ntemplate <typename Point, bool Closed>\nvoid test_get_ring()\n{\n    using ring = bg::model::ring<Point, Closed>;\n    using polygon = bg::model::polygon<Point, Closed>;\n    using multi_polygon = bg::model::multi_polygon<polygon>;\n\n    test_get_ring<ring>(\"ring_simplex\", simplex, {0, -1, -1}, simplex);\n    test_get_ring<polygon>(\"polygon_simplex\", simplex, {0, -1, -1}, simplex);\n    test_get_ring<polygon>(\"case_a_outer\", case_a, {0, -1, -1}, \"POLYGON((1 0,0 5,5 2,1 0))\");\n    test_get_ring<polygon>(\"case_a_0\", case_a, {0, -1, 0}, \"POLYGON((2 1,3 2,1 3,2 1))\");\n    test_get_ring<multi_polygon>(\"multi_0_outer\", multi, {0, 0, -1}, \"POLYGON((0 0,0 5,5 5,5 0,0 0))\");\n    test_get_ring<multi_polygon>(\"multi_0_0\", multi, {0, 0, 0}, \"POLYGON((1 1,2 1,2 2,1 2,1 1))\");\n    test_get_ring<multi_polygon>(\"multi_0_1\", multi, {0, 0, 1}, \"POLYGON((3 3,4 3,4 4,3 4,3 3))\");\n    test_get_ring<multi_polygon>(\"multi_1_outer\", multi, {0, 1, -1}, \"POLYGON((6 6,6 10,10 10,10 6,6 6))\");\n    test_get_ring<multi_polygon>(\"multi_1_1\", multi, {0, 1, 0}, \"POLYGON((7 7,8 7,8 8,7 7))\");\n}\n\ntemplate <typename Point, bool Closed>\nvoid test_segment_count_on_ring()\n{\n    using ring = bg::model::ring<Point, true, Closed>;\n    using polygon = bg::model::polygon<Point, true, Closed>;\n    using multi_polygon = bg::model::multi_polygon<polygon>;\n\n    test_segment_count_on_ring<ring>(\"ring_simplex\", simplex, {0, -1, -1}, 4);\n    test_segment_count_on_ring<polygon>(\"polygon_simplex\", simplex, {0, -1, -1}, 4);\n    test_segment_count_on_ring<polygon>(\"case_a_outer\", case_a, {0, -1, -1}, 3);\n    test_segment_count_on_ring<polygon>(\"case_a_0\", case_a, {0, -1, 0}, 3);\n    test_segment_count_on_ring<multi_polygon>(\"multi_0_outer\", multi, {0, 0, -1}, 4);\n    test_segment_count_on_ring<multi_polygon>(\"multi_0_0\", multi, {0, 0, 0}, 4);\n    test_segment_count_on_ring<multi_polygon>(\"multi_0_1\", multi, {0, 0, 1}, 4);\n    test_segment_count_on_ring<multi_polygon>(\"multi_1_outer\", multi, {0, 1, -1}, 4);\n    test_segment_count_on_ring<multi_polygon>(\"multi_1_1\", multi, {0, 1, 0}, 3);\n}\n\ntemplate <typename Point, bool Closed>\nvoid test_segment_distance()\n{\n    using ring = bg::model::ring<Point, true, Closed>;\n\n    std::string const case_id = \"ring_simplex\";\n\n    test_segment_distance<ring>(case_id, __LINE__, simplex, {0, -1, -1, 0}, {0, -1, -1, 0}, 0);\n    test_segment_distance<ring>(case_id, __LINE__, simplex, {0, -1, -1, 0}, {0, -1, -1, 1}, 1);\n    test_segment_distance<ring>(case_id, __LINE__, simplex, {0, -1, -1, 0}, {0, -1, -1, 2}, 2);\n    test_segment_distance<ring>(case_id, __LINE__, simplex, {0, -1, -1, 0}, {0, -1, -1, 3}, 3);\n\n    test_segment_distance<ring>(case_id, __LINE__, simplex, {0, -1, -1, 1}, {0, -1, -1, 0}, 3);\n    test_segment_distance<ring>(case_id, __LINE__, simplex, {0, -1, -1, 1}, {0, -1, -1, 1}, 0);\n    test_segment_distance<ring>(case_id, __LINE__, simplex, {0, -1, -1, 1}, {0, -1, -1, 2}, 1);\n    test_segment_distance<ring>(case_id, __LINE__, simplex, {0, -1, -1, 1}, {0, -1, -1, 3}, 2);\n\n    test_segment_distance<ring>(case_id, __LINE__, simplex, {0, -1, -1, 2}, {0, -1, -1, 0}, 2);\n    test_segment_distance<ring>(case_id, __LINE__, simplex, {0, -1, -1, 2}, {0, -1, -1, 1}, 3);\n    test_segment_distance<ring>(case_id, __LINE__, simplex, {0, -1, -1, 2}, {0, -1, -1, 2}, 0);\n    test_segment_distance<ring>(case_id, __LINE__, simplex, {0, -1, -1, 2}, {0, -1, -1, 3}, 1);\n\n    test_segment_distance<ring>(case_id, __LINE__, simplex, {0, -1, -1, 3}, {0, -1, -1, 0}, 1);\n    test_segment_distance<ring>(case_id, __LINE__, simplex, {0, -1, -1, 3}, {0, -1, -1, 1}, 2);\n    test_segment_distance<ring>(case_id, __LINE__, simplex, {0, -1, -1, 3}, {0, -1, -1, 2}, 3);\n    test_segment_distance<ring>(case_id, __LINE__, simplex, {0, -1, -1, 3}, {0, -1, -1, 3}, 0);\n}\n\nint test_main(int, char* [])\n{\n    using point = bg::model::point<default_test_type, 2, bg::cs::cartesian>;\n    test_get_ring<point, true>();\n    test_segment_count_on_ring<point, true>();\n    test_segment_count_on_ring<point, false>();\n    test_segment_distance<point, true>();\n    test_segment_distance<point, false>();\n    return 0;\n}\n", "meta": {"hexsha": "fd562c0b68671b9066987f90d7beeb4f8c8db0f4", "size": 7412, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "console/src/boost_1_78_0/libs/geometry/test/algorithms/overlay/get_ring.cpp", "max_stars_repo_name": "vany152/FilesHash", "max_stars_repo_head_hexsha": "39f282807b7f1abc56dac389e8259ee3bb557a8d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 326.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T13:47:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T02:13:59.000Z", "max_issues_repo_path": "console/src/boost_1_78_0/libs/geometry/test/algorithms/overlay/get_ring.cpp", "max_issues_repo_name": "vany152/FilesHash", "max_issues_repo_head_hexsha": "39f282807b7f1abc56dac389e8259ee3bb557a8d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 623.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T23:45:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T11:15:23.000Z", "max_forks_repo_path": "Libs/boost_1_76_0/libs/geometry/test/algorithms/overlay/get_ring.cpp", "max_forks_repo_name": "Antd23rus/S2DE", "max_forks_repo_head_hexsha": "47cc7151c2934cd8f0399a9856c1e54894571553", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-01-14T15:50:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T03:58:36.000Z", "avg_line_length": 44.3832335329, "max_line_length": 156, "alphanum_fraction": 0.6233135456, "num_tokens": 2421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.49583520051073743}}
{"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 *      101111    E. Iorfida        File created.\n *      101111    E. Iorfida        Implementation of all the equations up to the Newton method.\n *      101117    E. Iorfida        Velocities computations added.\n *      101126    E. Iorfida        Get/set codes deleted.\n *      101206    E. Iorfida        LambertTargetingElements class deleted,\n *                                  added setInitialState, modified punctuation. Set single\n *                                  variables, change variables names in more understandable ones.\n *      101209    E. Iorfida        Corrected some coding errors.\n *      101213    E. Iorfida        Deleted lambertAngle, added numberOfRevolution, modified\n *                                  implementation.\n *      101214    E. Iorfida        Implementation only for the case with numberOfRevolution = 0.\n *      110113    E. Iorfida        Added necessary elements to build pointer-to-member-function\n *                                  to RootFinderAlgorithms and NewtonRaphsonMethod classes.\n *      110124    E. Iorfida        Added necessary piece of code to be able to use the last\n *                                  version of Newton-Raphson code.\n *      110126    E. Iorfida        Initialized member functions.\n *      110130    J. Melman         Simplified variable names, e.g., 'normOfdeletVelocityVector'\n *                                  became 'speed'. Requested references to specific formulas. Also\n *                                  corrected 'transverse' to 'transverse'. Simplified computation\n *                                  of radial unit vector. Corrected computation of transverse\n *                                  heliocentric velocity.\n *      110201    E. Iorfida        Added pointerToCelestialBody and modified variable names (from\n *                                  heliocentric, to inertial). Added patch for negative case of\n *                                  initialLambertGuess. Added equations references.\n *      110206    E. Iorfida        Added unique function for Newton-Raphson method. Added\n *                                  computeAbsoluteValue to the initialLambertGuess for\n *                                  non-converging cases.\n *      110208    E. Iorfida        Added CartesianPositionElements objects as input and\n *                                  CartesianVelocityElements objects as output.\n *      110418    E. Iorfida        Added a new normal plane that take into account the case of two\n *                                  parallel position vector (with a relative angle of 180\n *                                  degrees). Better defined the pointers to the output\n *                                  CartesianVelocityElements.\n *      120326    D. Dirkx          Changed raw pointers to shared pointers.\n *      120619    T. Secretin       Converted to free functions. Added Izzo's approach.\n *      120704    P. Musegaas       Various small changes during code check.\n *      120713    P. Musegaas       Changed tolerance to relative tolerance in Gooding's rootfinder.\n *      120813    P. Musegaas       Changed code to new root finding structure.\n *\n *    References\n *      Battin, R.H. An Introduction to the Mathematics and Methods of Astrodynamics,\n *          AIAA Education Series, 1999.\n *      Izzo, D. lambert_problem.h, keptoolbox.\n *      Gooding, R.H. A procedure for the solution of Lambert's orbital boundary-value problem,\n *          Celestial Mechanics and Dynamical Astronomy, 48:145-165, 1990.\n *\n *    Notes\n *\n */\n\n#include <cmath>\n#include <iostream>\n#include <sstream>\n#include <stdexcept>\n\n#include <boost/bind.hpp>\n#include <boost/exception/all.hpp>\n#include <boost/make_shared.hpp>\n#include <boost/math/special_functions.hpp>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include \"Tudat/Mathematics/BasicMathematics/linearAlgebra.h\"\n#include \"Tudat/Mathematics/BasicMathematics/mathematicalConstants.h\"\n\n#include \"Tudat/Astrodynamics/MissionSegments/lambertRoutines.h\"\n#include \"Tudat/Mathematics/BasicMathematics/functionProxy.h\"\n\nnamespace tudat\n{\nnamespace mission_segments\n{\n\nusing namespace root_finders;\n\n//! Solve Lambert Problem using Izzo's algorithm.\nvoid solveLambertProblemIzzo( const Eigen::Vector3d& cartesianPositionAtDeparture,\n                              const Eigen::Vector3d& cartesianPositionAtArrival,\n                              const double timeOfFlight,\n                              const double gravitationalParameter,\n                              Eigen::Vector3d& cartesianVelocityAtDeparture,\n                              Eigen::Vector3d& cartesianVelocityAtArrival,\n                              const bool isRetrograde,\n                              const double convergenceTolerance,\n                              const unsigned int maximumNumberOfIterations )\n{\n    // Sanity check for specified time-of-flight.\n    if ( timeOfFlight <= 0.0 )\n    {\n        // Define error message.\n        std::stringstream errorMessage;\n        errorMessage << \"Specified time-of-flight must be strictly positive.\\n\"\n                     << \"Specified time-of-flight: \" << timeOfFlight << \" days.\" << std::endl;\n\n        // Throw exception.\n        boost::throw_exception( boost::enable_error_info(\n                                    std::runtime_error( errorMessage.str( ) ) ) );\n    }\n\n    // Compute normalizing values.\n    const double distanceNormalizingValue = cartesianPositionAtDeparture.norm( );\n    const double velocityNormalizingValue = std::sqrt( gravitationalParameter /\n                                                       distanceNormalizingValue );\n    const double timeNormalizingValue = distanceNormalizingValue / velocityNormalizingValue;\n\n    // Compute transfer geometry parameters in adimensional units.\n    // Cosine of transfer angle.\n    const double cosineOfTransferAngle =\n            cartesianPositionAtDeparture.dot( cartesianPositionAtArrival )\n            / (distanceNormalizingValue * cartesianPositionAtArrival.norm( ) );\n\n    // Normalized Cartesian position at arrival.\n    const double normalizedRadiusAtArrival = cartesianPositionAtArrival.norm( )\n            / distanceNormalizingValue;\n\n    // Chord.\n    const double chord = std::sqrt( 1.0 + normalizedRadiusAtArrival\n                                    * ( normalizedRadiusAtArrival - 2.0 * cosineOfTransferAngle ) );\n\n    // Semi-perimeter.\n    const double semiPerimeter = ( 1.0 + normalizedRadiusAtArrival + chord ) / 2.0;\n\n    // Assuming a prograde motion, determine whether the transfer corresponds to the long- or the\n    // short-way solution: longway if x1*y2 - x2*y1 < 0.\n    bool isLongway = false;\n    if ( cartesianPositionAtDeparture.x( ) * cartesianPositionAtArrival.y( )\n         - cartesianPositionAtDeparture.y( ) * cartesianPositionAtArrival.x( ) < 0.0 )\n    {\n        isLongway = true;\n    }\n\n    // If retrograde is true, switch longway flag.\n    if ( isRetrograde )\n    {\n        isLongway = !isLongway;\n    }\n\n    // Semi-major axis of the minimum energy ellipse.\n    const double semiMajorAxisOfTheMinimumEnergyEllipse = semiPerimeter / 2.0;\n\n    // Transfer angle.\n    double transferAngle = std::acos( cosineOfTransferAngle );\n    if ( isLongway )\n    {\n        transferAngle = 2.0 * mathematical_constants::PI - transferAngle;\n    }\n\n    // Lambda parameter.\n    const double lambdaParameter = std::sqrt( normalizedRadiusAtArrival )\n            * std::cos( transferAngle / 2.0 ) / semiPerimeter;\n\n    // Optimize log(t_spec).\n    const double normalizedSpecifiedTimeOfFlight = timeOfFlight / timeNormalizingValue;\n    const double logarithmOfTheSpecifiedTimeOfFlight = std::log( normalizedSpecifiedTimeOfFlight );\n\n    // Secant Method.\n    // Define initial guesses for abcissae (x) and ordinates (y).\n    double x1 = std::log( 0.5 ), x2 = std::log( 1.5 );\n\n    double y1 = std::log( computeTimeOfFlightIzzo( -0.5, semiPerimeter, chord, isLongway,\n                                                   semiMajorAxisOfTheMinimumEnergyEllipse ) )\n            - logarithmOfTheSpecifiedTimeOfFlight;\n\n    double y2 = std::log( computeTimeOfFlightIzzo( 0.5, semiPerimeter, chord, isLongway,\n                                                   semiMajorAxisOfTheMinimumEnergyEllipse ) )\n            - logarithmOfTheSpecifiedTimeOfFlight;\n\n    // Declare and initialize root-finding parameters.\n    double rootFindingError = 1.0, xNew = 0.0, yNew = 0.0;\n    unsigned int iterator = 0;\n\n\n    // Root-finding loop.\n    while ( ( rootFindingError > convergenceTolerance ) && (y1 != y2)\n            && ( iterator < maximumNumberOfIterations ) )\n    {\n        // Update iterator.\n        iterator++;\n\n        // Compute new x-value.\n        xNew = ( x1 * y2 - y1 * x2 ) / ( y2 - y1 );\n\n        // Compute corresponding y-value.\n        yNew = std::log( computeTimeOfFlightIzzo( std::exp( xNew ) - 1.0, semiPerimeter, chord,\n                                                  isLongway,\n                                                  semiMajorAxisOfTheMinimumEnergyEllipse ) )\n                - logarithmOfTheSpecifiedTimeOfFlight;\n\n        // Update abcissae and ordinates.\n        x1 = x2;\n        y1 = y2;\n        x2 = xNew;\n        y2 = yNew;\n\n        // Compute root-finding error.\n        rootFindingError = std::fabs( x1 - xNew );\n    }\n\n    // Verify that root-finder has converged.\n    if ( iterator == maximumNumberOfIterations )\n    {\n        std::cerr << \"Lambert Solver did not converge within the maximum number of iterations (\"\n                  << maximumNumberOfIterations << \").\" << std::endl;\n    }\n\n    // Revert to x parameter.\n    const double xParameter = std::exp( xNew ) - 1.0;\n\n    // Determine semi-major axis of the conic.\n    const double semiMajorAxis = semiMajorAxisOfTheMinimumEnergyEllipse\n            / ( 1.0 - xParameter * xParameter );\n\n    // Declare variables.\n    double etaParameter, etaParameterSquared, psiParameter;\n\n    // If x < 1, the solution is an ellipse.\n    if ( xParameter < 1.0 )\n    {\n        // Alpha parameter.\n        const double alphaParameter = 2.0 * std::acos( xParameter );\n\n        // Beta parameter.\n        double betaParameter = 2.0 * std::asin( std::sqrt( ( semiPerimeter - chord )\n                                                           / ( 2.0 * semiMajorAxis ) ) );\n\n        if ( isLongway )\n        {\n            betaParameter = -betaParameter;\n        }\n\n        // Psi parameter.\n        psiParameter = ( alphaParameter - betaParameter ) / 2.0;\n\n        // Eta parameter.\n        etaParameterSquared = 2.0 * semiMajorAxis * std::sin( psiParameter )\n                * std::sin( psiParameter ) / semiPerimeter;\n        etaParameter = std::sqrt( etaParameterSquared );\n    }\n\n    // Otherwise it is a hyperbola.\n    else\n    {\n        // Alpha parameter.\n        const double alphaParameter = 2.0 * boost::math::acosh( xParameter );\n\n        // Beta parameter.\n        double betaParameter = 2.0 * boost::math::asinh (\n                    std::sqrt( ( semiPerimeter - chord ) / ( -2.0 * semiMajorAxis ) ) );\n\n        if ( isLongway )\n        {\n            betaParameter = -betaParameter;\n        }\n\n        // Psi parameter.\n        psiParameter = (alphaParameter - betaParameter ) / 2.0;\n\n        // Eta parameter.\n        etaParameterSquared = -2.0 * semiMajorAxis * std::sinh( psiParameter )\n                * std::sinh( psiParameter ) / semiPerimeter;\n        etaParameter = std::sqrt( etaParameterSquared );\n    }\n\n    // Determine semi-latus rectum, p.\n    const double semiLatusRectum = ( normalizedRadiusAtArrival\n                                     / ( semiMajorAxisOfTheMinimumEnergyEllipse\n                                         * etaParameterSquared ) )\n            * std::sin( transferAngle / 2.0 )\n            * std::sin( transferAngle / 2.0 );\n\n    // Determine sigma.\n    const double sigmaParameter =\n            ( 1.0 / ( etaParameter * std::sqrt( semiMajorAxisOfTheMinimumEnergyEllipse ) ) )\n            * ( 2.0 * lambdaParameter * semiMajorAxisOfTheMinimumEnergyEllipse\n                - ( lambdaParameter + xParameter * etaParameter ) );\n\n    // Velocity components at departure.\n    const double radialVelocityAtDeparture = sigmaParameter;\n    const double transverseVelocityAtDeparture = std::sqrt( semiLatusRectum );\n\n    // Velocity components at arrival.\n    const double transverseVelocityAtArrival = transverseVelocityAtDeparture\n            / normalizedRadiusAtArrival;\n    const double radialVelocityAtArrival = ( transverseVelocityAtDeparture\n                                             - transverseVelocityAtArrival )\n                                           / std::tan( transferAngle / 2.0 )\n                                           - radialVelocityAtDeparture;\n\n    // Determine radial unit vectors.\n    const Eigen::Vector3d radialUnitVectorAtDeparture = cartesianPositionAtDeparture.normalized( );\n    const Eigen::Vector3d radialUnitVectorAtArrival = cartesianPositionAtArrival.normalized( );\n\n    // Determine plane of motion.\n    Eigen::Vector3d angularMomentumVector;\n\n    if ( isLongway )\n    {\n        angularMomentumVector = radialUnitVectorAtArrival.cross( radialUnitVectorAtDeparture );\n    }\n    else\n    {\n        angularMomentumVector = radialUnitVectorAtDeparture.cross( radialUnitVectorAtArrival );\n    }\n\n    // Compute normalized angular momentum vector.\n    const Eigen::Vector3d angularMomentumUnitVector = angularMomentumVector.normalized( );\n\n    // Compute transverse unit vectors.\n    const Eigen::Vector3d transverseUnitVectorAtDeparture =\n            radialUnitVectorAtDeparture.cross( angularMomentumUnitVector );\n    const Eigen::Vector3d transverseUnitVectorAtArrival =\n            radialUnitVectorAtArrival.cross( angularMomentumUnitVector );\n\n    // Reconstruct non-dimensional velocity vectors.\n    cartesianVelocityAtDeparture\n            << radialVelocityAtDeparture * radialUnitVectorAtDeparture.x( )\n               - transverseVelocityAtDeparture * transverseUnitVectorAtDeparture.x( ),\n            radialVelocityAtDeparture * radialUnitVectorAtDeparture.y( )\n            - transverseVelocityAtDeparture * transverseUnitVectorAtDeparture.y( ),\n            radialVelocityAtDeparture * radialUnitVectorAtDeparture.z( )\n            - transverseVelocityAtDeparture * transverseUnitVectorAtDeparture.z( );\n\n    cartesianVelocityAtArrival\n            << radialVelocityAtArrival * radialUnitVectorAtArrival.x( )\n               - transverseVelocityAtArrival * transverseUnitVectorAtArrival.x( ),\n            radialVelocityAtArrival * radialUnitVectorAtArrival.y( )\n            - transverseVelocityAtArrival * transverseUnitVectorAtArrival.y( ),\n            radialVelocityAtArrival * radialUnitVectorAtArrival.z( )\n            - transverseVelocityAtArrival * transverseUnitVectorAtArrival.z( );\n\n    // Return dimensions.\n    cartesianVelocityAtDeparture *= velocityNormalizingValue;\n    cartesianVelocityAtArrival *= velocityNormalizingValue;\n\n}\n\n//! Compute time-of-flight using Lagrange's equation.\ndouble computeTimeOfFlightIzzo( const double xParameter, const double semiPerimeter,\n                                const double chord, const bool isLongway,\n                                const double semiMajorAxisOfTheMinimumEnergyEllipse )\n{\n    // Determine semi-major axis.\n    const double semiMajorAxis = semiMajorAxisOfTheMinimumEnergyEllipse\n            / ( 1.0 - xParameter * xParameter );\n\n    // If x < 1, the solution is an ellipse.\n    if ( xParameter < 1.0 )\n    {\n        // Alpha parameter.\n        const double alphaParameter = 2.0 * std::acos( xParameter );\n\n        // Beta parameter.\n        double betaParameter = 2.0 * std::asin ( std::sqrt( ( semiPerimeter - chord )\n                                                            / ( 2.0 * semiMajorAxis ) ) );\n\n        if ( isLongway )\n        {\n            betaParameter = -betaParameter;\n        }\n\n        // Time-of-flight according to Lagrange.\n        const double timeOfFlight = semiMajorAxis * std::sqrt( semiMajorAxis ) *\n                ( ( alphaParameter - std::sin( alphaParameter ) )\n                  - ( betaParameter - std::sin( betaParameter ) ) );\n\n        return timeOfFlight;\n    }\n    // Otherwise it is a hyperbola.\n    else\n    {\n        // Alpha parameter.\n        const double alphaParameter = 2.0 * boost::math::acosh( xParameter );\n\n        // Beta parameter.\n        double betaParameter = 2.0 * boost::math::asinh(\n                    std::sqrt( ( semiPerimeter - chord ) / ( -2.0 * semiMajorAxis ) ) );\n\n        if ( isLongway )\n        {\n            betaParameter = -betaParameter;\n        }\n\n        // Time-of-flight according to Lagrange.\n        const double timeOfFlight = -semiMajorAxis * std::sqrt( -semiMajorAxis ) *\n                ( ( std::sinh( alphaParameter ) - alphaParameter )\n                  - ( std::sinh( betaParameter ) - betaParameter ) );\n\n        return timeOfFlight;\n    }\n\n\n}\n\n//! Solve Lambert Problem using Gooding's algorithm.\nvoid solveLambertProblemGooding( const Eigen::Vector3d& cartesianPositionAtDeparture,\n                                 const Eigen::Vector3d& cartesianPositionAtArrival,\n                                 const double timeOfFlight,\n                                 const double gravitationalParameter,\n                                 Eigen::Vector3d& cartesianVelocityAtDeparture,\n                                 Eigen::Vector3d& cartesianVelocityAtArrival,\n                                 RootFinderPointer rootFinder )\n{\n    if ( !rootFinder.get( ) )\n    {\n        rootFinder = boost::make_shared< root_finders::NewtonRaphson >( 1.0e-12, 1000 );\n    }\n\n    // Normalize positions.\n    const double radiusAtDeparture = cartesianPositionAtDeparture.norm( );\n    const double radiusAtArrival = cartesianPositionAtArrival.norm( );\n\n    // Compute angle between positions.\n    Eigen::Vector3d planeNormalPosition =\n            cartesianPositionAtDeparture.cross( cartesianPositionAtArrival ).normalized( );\n\n    double reducedLambertAngle = linear_algebra::computeAngleBetweenVectors(\n                cartesianPositionAtDeparture, cartesianPositionAtArrival );\n\n    if ( planeNormalPosition.z( ) < 0.0 )\n    {\n        reducedLambertAngle = 2.0 * mathematical_constants::PI\n                - reducedLambertAngle;\n    }\n\n    // Compute chord.\n    const double chord = std::sqrt( radiusAtDeparture * radiusAtDeparture +\n                                    radiusAtArrival * radiusAtArrival -\n                                    2.0 * radiusAtDeparture * radiusAtArrival *\n                                    std::cos( reducedLambertAngle ) );\n\n    // Compute semi-perimeter.\n    const double semiPerimeter = ( radiusAtDeparture + radiusAtArrival + chord ) / 2.0;\n\n    // Compute normalized time of flight.\n    // Formula (7) [3].\n    const double normalizedTimeOfFlight = std::sqrt( 8.0 * gravitationalParameter / semiPerimeter\n                                                     / semiPerimeter / semiPerimeter )\n                                          * timeOfFlight;\n\n    // Compute q-parameter.\n    // Formula (5) [3].\n    const double qParameter = ( std::sqrt( radiusAtDeparture * radiusAtArrival ) /\n                                semiPerimeter ) * cos( reducedLambertAngle / 2.0 );\n\n    // Compute values of parameters needed to compute the initial guess of x-parameter.\n    const double zParameterInitial = std::sqrt( 1.0 - qParameter * qParameter );\n\n    // Formula (6.11) [2].\n    const double lambertEccentricAnomalyInitial = -1.0;\n\n    // Formula (6.12) [2].\n    const double yParameterInitial = std::sqrt( std::fabs( lambertEccentricAnomalyInitial ) );\n\n    // Formula (6.14) [2].\n    const double fParameterInitial = yParameterInitial * zParameterInitial;\n\n    // Formula (6.15) [2].\n    const double gParameterInitial = -1.0 * qParameter * lambertEccentricAnomalyInitial;\n\n    // Page 47 [2].\n    const double dParameterInitial = atan( fParameterInitial / gParameterInitial );\n\n    // Value of T(x) for x=0.\n    // Formula (6.9) [2].\n    const double tFunctionInitial = -2.0 * ( qParameter * zParameterInitial +\n            dParameterInitial / yParameterInitial ) / lambertEccentricAnomalyInitial;\n\n    // Declare initial guess of x-parameter.\n    double initialLambertGuess;\n\n    // Determine initial Lambert guess.\n    if ( tFunctionInitial > normalizedTimeOfFlight )\n    {\n        // Formula (11) [3].\n        initialLambertGuess = tFunctionInitial *\n                ( tFunctionInitial - normalizedTimeOfFlight ) /\n                ( 4.0 * normalizedTimeOfFlight );\n    }\n    else\n    {\n        // Formula (13) [3].\n        const double x01 = -1.0 * ( normalizedTimeOfFlight - tFunctionInitial ) /\n                     ( normalizedTimeOfFlight - tFunctionInitial + 4.0 );\n\n        // Formula (15) [3].\n        const double x02 = -1.0 * std::sqrt( ( normalizedTimeOfFlight -\n                     tFunctionInitial ) / ( normalizedTimeOfFlight +\n                     0.5 * tFunctionInitial ) );\n\n        // Formula (20) [3].\n        const double phi = 2.0 * atan2( ( 1.0 - qParameter * qParameter ), 2.0 * qParameter );\n\n        // Formula (16) [3].\n        const double W = x01 + 1.7 * std::sqrt(\n                    2.0 - phi / mathematical_constants::PI );\n\n        // Formula (17) [3].\n        double x03;\n        if ( W >= 0.0 )\n        {\n           x03 = x01;\n        }\n        else\n        {\n           x03 = x01 + std::pow( -W , 1.0 / 16.0 ) * ( x02 - x01 );\n        }\n\n        // Formula (19) [3].\n        const double lambdax = 1.0 + 0.5 * x03 * ( 1.0 + x01 ) - 0.03 * x03 * x03\n                * std::sqrt( 1.0 + x01 );\n\n        // Formula (18) [3].\n        initialLambertGuess = lambdax * x03;\n    }\n\n    // Newton-Raphson method implementation.\n    // Set the class that contains the functions needed for Newton-Raphson.\n    LambertFunctionsGooding lambertFunctionsGooding( qParameter, normalizedTimeOfFlight );\n\n    // Create an object containing the function of which we whish to obtain the root from.\n    using basic_mathematics::UnivariateProxyPointer;\n    using basic_mathematics::UnivariateProxy;\n    UnivariateProxyPointer rootFunction = boost::make_shared< UnivariateProxy >(\n                boost::bind( &LambertFunctionsGooding::computeLambertFunctionGooding,\n                             lambertFunctionsGooding, _1 ) );\n\n    // Add the first derivative of the root function.\n    rootFunction->addBinding( -1, boost::bind( &LambertFunctionsGooding::\n                                               computeFirstDerivativeLambertFunctionGooding,\n                                               lambertFunctionsGooding, _1 ) );\n\n    // Initialize the xParameter.\n    double xParameter = TUDAT_NAN;\n\n    // Set initial guess of the variable computed in Newton-Rapshon method. A patch for negative\n    // initialLambertGuess is applied. This has not been stated in the paper by Gooding, but this\n    // patch has been found by trial and error.\n    if ( initialLambertGuess * initialLambertGuess - 1.0 < 0.0 )\n    {\n        // Set xParameter based on result of Newton-Raphson root-finding algorithm.\n        xParameter = rootFinder->execute( rootFunction, std::fabs( initialLambertGuess ) );\n    }\n    else\n    {\n        // Set xParameter based on result of Newton-Raphson root-finding algorithm.\n        xParameter = rootFinder->execute( rootFunction, initialLambertGuess );\n    }\n\n    // Compute velocities at departure and at arrival.\n\n    // Compute gamma, rho and sigma parameters, needed to compute the velocities.\n    // Formula (8) [3].\n    const double zParameter = std::sqrt( 1.0 - qParameter * qParameter +\n            qParameter * qParameter * xParameter * xParameter );\n\n    // Formula (6.23) [2].\n    const double lambertGamma = std::sqrt( gravitationalParameter * semiPerimeter / 2.0 );\n\n    // Formula (6.24) [2].\n    const double lambertRho = ( radiusAtDeparture - radiusAtArrival ) / chord;\n\n    // Formula (6.25) [2].\n    const double lambertSigma = 2.0 * ( std::sqrt(\n                                            radiusAtDeparture * radiusAtArrival / chord / chord ) )\n            * std::sin( reducedLambertAngle / 2.0 );\n\n    // Compute radial speeds at departure and at arrival.\n    // Formula (23) [3].\n    const double radialSpeedAtDeparture =\n            lambertGamma * ( qParameter * zParameter - xParameter -\n                             lambertRho * ( qParameter * zParameter + xParameter ) ) /\n            radiusAtDeparture;\n\n    // Formula (24) [3].\n    const double radialSpeedAtArrival =\n            -lambertGamma * ( qParameter * zParameter - xParameter +\n                              lambertRho * ( qParameter * zParameter + xParameter ) ) /\n            radiusAtArrival;\n\n    // Compute transverse speeds at departure and at arrival.\n    // Compute large part of formulas (25) and (26).\n    const double transverseSpeedHelper = lambertGamma * lambertSigma *\n            ( zParameter + qParameter * xParameter );\n\n    // Formula (25) [3].\n    const double transverseSpeedAtDeparture = transverseSpeedHelper / radiusAtDeparture;\n\n    // Formula (26) [3].\n    const double transverseSpeedAtArrival = transverseSpeedHelper / radiusAtArrival;\n\n    // Compute inertial velocities (those velocity are computed with respect to the central body,\n    // so they can be either heliocentric or planetocentric).\n\n    // Compute radial unit vectors at departure and at arrival.\n    const Eigen::Vector3d radialUnitVectorAtDeparture = cartesianPositionAtDeparture.normalized( );\n    const Eigen::Vector3d radialUnitVectorAtArrival = cartesianPositionAtArrival.normalized( );\n\n    Eigen::Vector3d unitZVector;\n    unitZVector.x( ) = 0.0;\n    unitZVector.y( ) = 0.0;\n    unitZVector.z( ) = 1.0;\n\n    Eigen::Vector3d planeNormal =\n            ( ( cartesianPositionAtDeparture.cross( unitZVector ) ).cross(\n                    cartesianPositionAtDeparture ) ).normalized( );\n\n    // Compute unit vector that is normal to the plane in which the trajectory takes place, and\n    // points in the positive z-direction.\n    if ( planeNormal.z( ) < 0.0 )\n    {\n        planeNormal = -planeNormal;\n    }\n\n    // Compute transverse unit vectors at departure and at arrival.\n    const Eigen::Vector3d transverseUnitVectorAtDeparture = planeNormal.cross(\n            cartesianPositionAtDeparture.normalized( ) );\n    const Eigen::Vector3d transverseUnitVectorAtArrival = planeNormal.cross(\n            cartesianPositionAtArrival.normalized( ) );\n\n    // Compute radial inertial velocities at departure and at arrival.\n    const Eigen::Vector3d radialInertialVelocityAtDeparture\n            = radialSpeedAtDeparture * radialUnitVectorAtDeparture;\n    const Eigen::Vector3d radialInertialVelocityAtArrival\n            = radialSpeedAtArrival * radialUnitVectorAtArrival;\n\n    // Compute transverse heliocentric velocities at departure and\n    // at arrival.\n    const Eigen::Vector3d transverseInertialVelocityAtDeparture\n            = transverseSpeedAtDeparture * transverseUnitVectorAtDeparture;\n    const Eigen::Vector3d transverseInertialVelocityAtArrival\n            = transverseSpeedAtArrival * transverseUnitVectorAtArrival;\n\n    // Compute heliocentric velocities at departure and at arrival.\n    // Define output velocities.\n    cartesianVelocityAtDeparture\n            = radialInertialVelocityAtDeparture + transverseInertialVelocityAtDeparture;\n    cartesianVelocityAtArrival\n            = radialInertialVelocityAtArrival + transverseInertialVelocityAtArrival;\n}\n\n//! Define general Lambert function.\ndouble LambertFunctionsGooding::computeLambertFunctionGooding( const double xParameter )\n{\n    const double lambertEccentricAnomaly = xParameter * xParameter - 1.0;\n\n    if ( lambertEccentricAnomaly > 0.0 )\n    {\n        return lambertFunctionPositiveGooding( xParameter );\n    }\n\n    else\n    {\n        return lambertFunctionNegativeGooding( xParameter );\n    }\n}\n\n//! Define first derivative of general Lambert function.\ndouble LambertFunctionsGooding::computeFirstDerivativeLambertFunctionGooding( const double xParameter )\n{\n    const double lambertEccentricAnomaly = xParameter * xParameter - 1.0;\n\n    if ( lambertEccentricAnomaly > 0.0 )\n    {\n        return lambertFirstDerivativeFunctionPositiveGooding( xParameter );\n    }\n\n    else\n    {\n        return lambertFirstDerivativeFunctionNegativeGooding( xParameter );\n    }\n}\n\n//! Define Lambert function for positive lambertEccentricAnomaly.\ndouble LambertFunctionsGooding::lambertFunctionPositiveGooding( const double xParameter )\n{\n    const double lambertEccentricAnomaly = xParameter * xParameter - 1.0;\n    const double yParameter = std::sqrt( std::fabs( lambertEccentricAnomaly ) );\n    const double zParameter = std::sqrt( 1.0 - qParameter * qParameter+\n                                         qParameter * qParameter * xParameter  * xParameter );\n    const double fParameter = yParameter * ( zParameter - qParameter * xParameter );\n    const double gParameter = xParameter * zParameter - qParameter * lambertEccentricAnomaly;\n    const double dParameter = log( fParameter + gParameter );\n\n    return normalizedTimeOfFlight - 2.0 * ( xParameter - qParameter * zParameter - dParameter /\n                                            yParameter ) / lambertEccentricAnomaly;\n}\n\n//! Define Lambert function for negative lambertEccentricAnomaly.\ndouble LambertFunctionsGooding::lambertFunctionNegativeGooding( const double xParameter )\n{\n    const double lambertEccentricAnomaly = xParameter * xParameter - 1.0;\n    const double yParameter = std::sqrt( std::fabs( lambertEccentricAnomaly ) );\n    const double zParameter = std::sqrt( 1.0 - qParameter * qParameter +\n                                         qParameter * qParameter * xParameter * xParameter );\n    const double fParameter = yParameter * ( zParameter - qParameter * xParameter );\n    const double gParameter = xParameter * zParameter - qParameter * lambertEccentricAnomaly;\n    const double dParameter = std::atan( fParameter / gParameter );\n\n    return normalizedTimeOfFlight - 2.0 * ( xParameter - qParameter * zParameter - dParameter\n                                            / yParameter ) / lambertEccentricAnomaly;\n}\n\n//! Define first derivative of Lambert function for positive lambertEccentricAnomaly.\ndouble LambertFunctionsGooding::lambertFirstDerivativeFunctionPositiveGooding(\n        const double xParameter )\n{\n    const double lambertEccentricAnomaly = xParameter * xParameter - 1.0;\n    const double yParameter = std::sqrt( std::fabs( lambertEccentricAnomaly ) );\n    const double zParameter = std::sqrt( 1.0 - qParameter * qParameter +\n                                         qParameter * qParameter * xParameter * xParameter );\n    const double fParameter = yParameter * ( zParameter - qParameter * xParameter );\n    const double gParameter = xParameter * zParameter - qParameter * lambertEccentricAnomaly;\n    const double dParameter = std::log( fParameter + gParameter );\n    const double lambertEccentricAnomalyDerivative = 2.0 * xParameter;\n    const double yParameterDerivative = xParameter / std::sqrt( xParameter * xParameter - 1.0 );\n    const double zParameterDerivative = qParameter * qParameter * xParameter / zParameter;\n    const double fParameterDerivative = yParameterDerivative  *\n            ( zParameter - xParameter * qParameter ) + yParameter *\n            ( zParameterDerivative - qParameter );\n    const double gParameterDerivative = zParameter + xParameter *\n            zParameterDerivative - qParameter * lambertEccentricAnomalyDerivative;\n    const double dParameterDerivative = ( fParameterDerivative + gParameterDerivative ) /\n            ( fParameter + gParameter );\n\n    return - 2.0 * ( lambertEccentricAnomaly\n                     * ( 1.0 - qParameter * zParameterDerivative\n                         - ( ( dParameterDerivative * yParameter\n                               - yParameterDerivative * dParameter )\n                             / ( yParameter * yParameter ) ) )\n                     - ( ( xParameter - qParameter * zParameter - ( dParameter / yParameter ) )\n                         * lambertEccentricAnomalyDerivative ) )\n            / ( lambertEccentricAnomaly * lambertEccentricAnomaly );\n}\n\n//! Define first derivative of Lambert function for negative lambertEccentricAnomaly.\ndouble LambertFunctionsGooding::lambertFirstDerivativeFunctionNegativeGooding(\n        const double xParameter )\n{\n    const double lambertEccentricAnomaly = xParameter * xParameter - 1.0;\n    const double yParameter = std::sqrt( std::fabs( lambertEccentricAnomaly ) );\n    const double zParameter = std::sqrt( 1.0 - qParameter * qParameter +\n                                         qParameter * qParameter * xParameter * xParameter );\n    const double fParameter = yParameter * ( zParameter - qParameter * xParameter );\n    const double gParameter = xParameter * zParameter - qParameter * lambertEccentricAnomaly;\n    const double dParameter = std::atan( fParameter / gParameter );\n    const double lambertEccentricAnomalyDerivative = 2.0 * xParameter;\n    const double yParameterDerivative = -1.0 * xParameter\n            / std::sqrt( 1.0 - xParameter * xParameter);\n    const double zParameterDerivative = qParameter * qParameter * xParameter / zParameter;\n    const double fParameterDerivative = yParameterDerivative *\n            ( zParameter - xParameter * qParameter ) + yParameter *\n            ( zParameterDerivative - qParameter );\n    const double gParameterDerivative = zParameter + xParameter *\n            zParameterDerivative - qParameter *  lambertEccentricAnomalyDerivative;\n    const double dParameterDerivative = ( fParameterDerivative * gParameter -\n                                          fParameter * gParameterDerivative ) /\n            ( fParameter * fParameter + gParameter * gParameter );\n\n    return - 2.0 * ( lambertEccentricAnomaly * ( 1.0 - qParameter * zParameterDerivative -\n                                                 ( ( dParameterDerivative * yParameter -\n                                                     yParameterDerivative * dParameter ) /\n                                                   yParameter / yParameter ) ) -\n                     ( ( xParameter - qParameter * zParameter - ( dParameter / yParameter ) ) *\n                       lambertEccentricAnomalyDerivative ) ) /\n            ( lambertEccentricAnomaly * lambertEccentricAnomaly );\n}\n\n} // namespace mission_segments\n} // namespace tudat\n", "meta": {"hexsha": "22991e2df74eeaf5d988103ea47f4334baf51861", "size": 36186, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/MissionSegments/lambertRoutines.cpp", "max_stars_repo_name": "JPelamatti/ThesisTUDAT", "max_stars_repo_head_hexsha": "b94ce35fb7c8fa44ae83238e296a979dfa3adfe8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tudat/Astrodynamics/MissionSegments/lambertRoutines.cpp", "max_issues_repo_name": "JPelamatti/ThesisTUDAT", "max_issues_repo_head_hexsha": "b94ce35fb7c8fa44ae83238e296a979dfa3adfe8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tudat/Astrodynamics/MissionSegments/lambertRoutines.cpp", "max_forks_repo_name": "JPelamatti/ThesisTUDAT", "max_forks_repo_head_hexsha": "b94ce35fb7c8fa44ae83238e296a979dfa3adfe8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-05-30T03:42:22.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-30T03:42:22.000Z", "avg_line_length": 45.4027603513, "max_line_length": 103, "alphanum_fraction": 0.636019455, "num_tokens": 8245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952052, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.49583519611501203}}
{"text": "#include <b0/node.h>\n#include <b0/publisher.h>\n#include <b0/subscriber.h>\n\n#include <boost/lexical_cast.hpp>\n\n/*! \\example remapping/operation.cpp\n * This node performs a mathematical operation on the data received on its two topics\n */\n\n//! \\cond HIDDEN_SYMBOLS\n\nclass Operation : public b0::Node\n{\npublic:\n    Operation(char op)\n        : b0::Node(\"operation\"),\n          op_(op),\n          sub_a_(this, \"a\", &Operation::callback_a, this),\n          sub_b_(this, \"b\", &Operation::callback_b, this),\n          pub_(this, \"out\"),\n          value_a_(0),\n          value_b_(0)\n    {\n        if(op != '+' && op != '-' && op != '*' && op != '/')\n            throw std::runtime_error(\"invalid operator\");\n    }\n\n    void callback_a(const std::string &msg)\n    {\n        value_a_ = boost::lexical_cast<int>(msg);\n        compute();\n    }\n\n    void callback_b(const std::string &msg)\n    {\n        value_b_ = boost::lexical_cast<int>(msg);\n        compute();\n    }\n\n    void compute()\n    {\n        int result = 0;\n        switch(op_)\n        {\n        case '+': result = value_a_ + value_b_; break;\n        case '-': result = value_a_ - value_b_; break;\n        case '*': result = value_a_ * value_b_; break;\n        case '/': result = value_a_ / value_b_; break;\n        }\n        pub_.publish(boost::lexical_cast<std::string>(result));\n    }\n\nprivate:\n    char op_;\n    b0::Subscriber sub_a_;\n    b0::Subscriber sub_b_;\n    b0::Publisher pub_;\n    int value_a_;\n    int value_b_;\n};\n\nint main(int argc, char **argv)\n{\n    b0::addOptionString(\"operator,o\", \"the mathematical operator\", nullptr, true);\n    b0::init(argc, argv);\n    Operation node(b0::getOptionString(\"operator\")[0]);\n    node.init();\n    node.spin();\n    node.cleanup();\n    return 0;\n}\n\n//! \\endcond\n\n", "meta": {"hexsha": "082350213191b658a7d45df1145a90f6616f2d2b", "size": 1764, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CoppeliaSim_Edu_V4_1_0_Ubuntu18_04/programming/bluezero/examples/remapping/operation.cpp", "max_stars_repo_name": "YueErro/ModernRobotics", "max_stars_repo_head_hexsha": "82345c04157c1322b24553bf00abd1f2b03281a5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2020-02-13T16:20:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T10:00:40.000Z", "max_issues_repo_path": "CoppeliaSim_Edu_V4_1_0_Ubuntu18_04/programming/bluezero/examples/remapping/operation.cpp", "max_issues_repo_name": "YueErro/ModernRobotics", "max_issues_repo_head_hexsha": "82345c04157c1322b24553bf00abd1f2b03281a5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-01-26T17:48:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-28T06:54:44.000Z", "max_forks_repo_path": "CoppeliaSim_Edu_V4_1_0_Ubuntu18_04/programming/bluezero/examples/remapping/operation.cpp", "max_forks_repo_name": "YueErro/ModernRobotics", "max_forks_repo_head_hexsha": "82345c04157c1322b24553bf00abd1f2b03281a5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-10-20T01:32:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-04T10:31:26.000Z", "avg_line_length": 23.2105263158, "max_line_length": 85, "alphanum_fraction": 0.5685941043, "num_tokens": 455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850154599563, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.49583519181548424}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// QuickBook Example\n\n// Copyright (c) 2011 Barend Gehrels, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n//[register_ring_templated\n//` Show the use of the macro BOOST_GEOMETRY_REGISTER_RING_TEMPLATED\n\n#include <iostream>\n#include <deque>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/register/ring.hpp>\n\n// Adapt any deque to Boost.Geometry Ring Concept\nBOOST_GEOMETRY_REGISTER_RING_TEMPLATED(std::deque) \n\nint main()\n{\n    std::deque<boost::geometry::model::d2::point_xy<double> > ring(3);\n    boost::geometry::assign_values(ring[0], 0, 0);\n    boost::geometry::assign_values(ring[2], 4, 1);\n    boost::geometry::assign_values(ring[1], 1, 4);\n    \n    // Boost.Geometry algorithms work on any deque now\n    boost::geometry::correct(ring);\n    std::cout << \"Area: \"  << boost::geometry::area(ring) << std::endl;\n    std::cout << \"Contents: \"  << boost::geometry::wkt(ring) << std::endl;\n    \n    return 0;\n}\n\n//]\n\n\n//[register_ring_templated_output\n/*`\nOutput:\n[pre\nArea: 7.5\nLine: ((0, 0), (1, 4), (4, 1), (0, 0))\n]\n*/\n//]\n", "meta": {"hexsha": "28a4d5d2f54b01cf877bd2a4a2c0c1b0eb487fe0", "size": 1322, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/doc/src/examples/geometries/register/ring_templated.cpp", "max_stars_repo_name": "olegshnitko/libboost", "max_stars_repo_head_hexsha": "548eb6365af3724d8f4b47ebbabf7eb3ad8e66a8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-10-31T00:40:22.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-31T00:40:22.000Z", "max_issues_repo_path": "libs/geometry/doc/src/examples/geometries/register/ring_templated.cpp", "max_issues_repo_name": "olegshnitko/libboost", "max_issues_repo_head_hexsha": "548eb6365af3724d8f4b47ebbabf7eb3ad8e66a8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-01-17T10:11:43.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-17T10:11:43.000Z", "max_forks_repo_path": "libs/geometry/doc/src/examples/geometries/register/ring_templated.cpp", "max_forks_repo_name": "olegshnitko/libboost", "max_forks_repo_head_hexsha": "548eb6365af3724d8f4b47ebbabf7eb3ad8e66a8", "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.44, "max_line_length": 79, "alphanum_fraction": 0.691376702, "num_tokens": 382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.7090191460821871, "lm_q1q2_score": 0.495784772513275}}
{"text": "#undef BOOST_UBLAS_NO_EXCEPTIONS\r\n#include \"common/testhelper.hpp\"\r\n#include <boost/numeric/ublas/vector.hpp>\r\n#include <boost/numeric/ublas/matrix.hpp>\r\n#include <boost/numeric/ublas/assignment.hpp>\r\n#include <boost/numeric/ublas/io.hpp>\r\n#include <string>\r\n#include <sstream>\r\n#include <complex>\r\n#include <iomanip>\r\n#include \"utils.hpp\"\r\n\r\n#ifdef BOOST_UBLAS_CPP_GE_2011\r\n\r\nusing namespace boost::numeric::ublas;\r\n\r\nusing std::cout;\r\nusing std::endl;\r\n\r\ntemplate < class T >\r\nbool test_vector( std::string type_name)\r\n{\r\n    std::stringstream stream;\r\n    stream << \"Testing for: \" << type_name;\r\n    BOOST_UBLAS_DEBUG_TRACE( stream.str() );\r\n\r\n    bool pass = true;\r\n\r\n    {\r\n        typedef fixed_vector<T, 1> vec1;\r\n\r\n        vec1 v1( 122.0 );\r\n\r\n        pass &= ( v1(0) == (T)122 );\r\n\r\n    }\r\n\r\n    {\r\n        typedef fixed_vector<T, 3> vec3;\r\n\r\n        vec3 v1((T)0.0, (T)0.0, (T)0.0);\r\n\r\n        pass &=(sizeof( vec3 )  == v1.size()*sizeof( T ) ) ;\r\n\r\n        vector<T> v( 3, 0 ) ;\r\n\r\n        pass &= compare( v1, v );\r\n\r\n        v1 <<= 10.0, 10, 33;\r\n        v  <<= 10.0, 10, 33;\r\n\r\n        //cout << std::setprecision(20) << v1 << '\\n' << v;\r\n\r\n        pass &= compare( v1, v );\r\n\r\n\r\n        vec3 v2;\r\n\r\n        v2( 0 ) = 10.0; v2( 1 ) = 10; v2( 2 ) = 33;\r\n        pass &= compare( v, v2 );\r\n\r\n        v2 += v;\r\n\r\n        pass &= compare( v2, 2*v );\r\n\r\n\r\n        v1 = 2*v1 + v - 6*v2;\r\n        pass &= compare( v1, (3-2*6)*v );\r\n\r\n\r\n        vec3 v3{ (T)-90.0, (T)-90.0, (T)-297.0 };\r\n        pass &= compare( v3, v1 );\r\n\r\n        vec3 v4 =  { (T)-90.0, (T)-90.0, (T)-297.0 };\r\n        pass &= compare( v4, v1 );\r\n\r\n        vec3 v5( (T)-90.0, (T)-90.0, (T)-297.0 );\r\n        pass &= compare( v5, v1 );\r\n\r\n        vec3 v6((T) 5.0, (T)8.0, (T)9.0);\r\n\r\n        matrix<T> M = outer_prod( v6, v6), L( 3, 3);\r\n\r\n        L <<= 25, 40, 45, 40, 64, 72, 45, 72, 81;\r\n\r\n        pass &= compare( M, L );\r\n\r\n        L  <<= 1, 2, 3, 4, 5, 6, 7, 8, 9;\r\n        v6 <<= 4, 5, 6;\r\n        vec3 v7 ( (T)32.0, (T)77.0, (T)122.0 );\r\n\r\n        pass &= compare( v7, prod(L, v6) );\r\n\r\n        vec3 v8;\r\n        noalias( v8 ) = prod(L, v6);\r\n\r\n        pass &= compare( v7, v8 );\r\n\r\n    }\r\n\r\n\r\n    {\r\n        const std::size_t N = 33;\r\n        typedef fixed_vector<T, N> vec33;\r\n\r\n        vec33 v1;\r\n        vector<T> v( N );\r\n\r\n        for ( std::size_t i = 0; i!= v1.size(); i++)\r\n        {\r\n            v1( i ) = 3.14159*i;\r\n            v ( i ) = 3.14159*i;\r\n        }\r\n\r\n        pass &= compare( v1, v );\r\n\r\n\r\n        auto ip = inner_prod( v, v);\r\n        auto ip1 = inner_prod( v1, v1);\r\n\r\n        pass &= (  ip == ip1 ) ;\r\n\r\n        T c = 0;\r\n        for (auto i = v1.begin(); i != v1.end(); i++)\r\n        {\r\n            *i = c;\r\n            c = c + 1;\r\n        }\r\n\r\n        c = 0;\r\n        for (auto i = v.begin(); i != v.end(); i++)\r\n        {\r\n            *i = c;\r\n            c = c + 1;\r\n        }\r\n\r\n        pass &= compare( v1, v );\r\n\r\n        // Check if bad index indeed works\r\n        try {\r\n            T a;\r\n            a=v1( 100 );\r\n            BOOST_UBLAS_NOT_USED( a );\r\n\r\n        } catch ( bad_index &e) {\r\n            std::cout << \" Caught (GOOD): \" << e.what() << endl;\r\n            pass &= true;\r\n        }\r\n\r\n\r\n    }\r\n    return pass;\r\n}\r\n\r\ntemplate < class T >\r\nbool test_matrix( std::string type_name)\r\n{\r\n    std::stringstream stream;\r\n    stream << \"Testing for: \" << type_name;\r\n    BOOST_UBLAS_DEBUG_TRACE( stream.str() );\r\n\r\n    bool pass = true;\r\n\r\n    typedef fixed_matrix<T, 3, 4> mat34;\r\n    typedef fixed_matrix<T, 4, 3> mat43;\r\n    typedef fixed_matrix<T, 3, 3> mat33;\r\n\r\n\r\n    {\r\n        typedef fixed_matrix<T, 1, 1> mat1;\r\n\r\n        mat1 m1( 122.0 );\r\n\r\n        pass &= ( m1(0, 0) == (T)122 );\r\n    }\r\n\r\n\r\n    {\r\n        mat34 m1( 3.0 );\r\n\r\n        pass &=(sizeof( mat34 )  == m1.size1()*m1.size2()*sizeof( T ) ) ;\r\n\r\n        matrix<T> m( 3.0, 4.0, 3.0 ) ;\r\n\r\n        pass &= compare( m1, m );\r\n\r\n        cout << m1 << endl;\r\n        cout << m << endl;\r\n\r\n\r\n        m1 <<= 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12;\r\n        m  <<= 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12;\r\n\r\n        pass &= compare( m1, m );\r\n\r\n        cout << m1 << endl;\r\n        cout << m << endl;\r\n\r\n        mat34 m2( 0.0 );\r\n\r\n        T count = 1 ;\r\n        for ( std::size_t i = 0; i != m2.size1(); i++)\r\n        {\r\n            for (std::size_t j = 0; j!= m2.size2(); j++)\r\n            {\r\n                m2( i, j ) = count;\r\n                count = count + 1;\r\n            }\r\n\r\n        }\r\n        pass &= compare( m2, m );\r\n        cout << m2 << endl;\r\n\r\n    }\r\n    {\r\n        mat34 m1 = { (T)1, (T)2, (T)3, (T)3, (T)3, (T)2, (T)5, (T)4, (T)2, (T)6, (T)5, (T)2 };\r\n        mat43 m2 = { (T)4, (T)5, (T)6, (T)3, (T)2, (T)2, (T)1, (T)4, (T)2, (T)6, (T)5, (T)2 };\r\n\r\n        mat33 m3 = prod(m1, m2);\r\n\r\n        matrix<T> m(3, 3);\r\n        m <<= 31,36,22,47,59,40,43,52,38;\r\n\r\n        pass &= compare(m ,m3);\r\n\r\n        mat33 m4;\r\n        m4 <<= (T)1, (T)2, (T)1, (T)2, (T)1, (T)3, (T)1, (T)2, (T) 5;\r\n        m3  = prod(m4, trans(m4));\r\n\r\n        m<<=6,7,10,7,14,19,10,19,30;\r\n\r\n        cout << m3 << endl;\r\n        pass &= compare(m ,m3);\r\n\r\n        m3 = 2 * m4 - 1 * m3;\r\n\r\n        cout << m3;\r\n\r\n        m <<= -4,-3,-8,-3,-12,-13,-8,-15,-20;\r\n\r\n        pass &= compare(m, m3);\r\n\r\n        m = m3;\r\n\r\n        m3 = trans(m);\r\n\r\n        pass &= compare(m3, trans(m));\r\n\r\n        // Check if bad index indeed works\r\n        try {\r\n            T a;\r\n            a=m1( 100, 100 );\r\n            BOOST_UBLAS_NOT_USED( a );\r\n\r\n        } catch ( bad_index &e) {\r\n            std::cout << \" Caught (GOOD): \" << e.what() << endl;\r\n            pass &= true;\r\n        }\r\n\r\n    }\r\n\r\n    return pass;\r\n\r\n}\r\n\r\nBOOST_UBLAS_TEST_DEF (test_fixed) {\r\n\r\n    BOOST_UBLAS_DEBUG_TRACE( \"Starting fixed container tests\" );\r\n\r\n    BOOST_UBLAS_TEST_CHECK(  test_vector< double >( \"double\") );\r\n    BOOST_UBLAS_TEST_CHECK(  test_vector< float >( \"float\") );\r\n    BOOST_UBLAS_TEST_CHECK(  test_vector< int >( \"int\") );\r\n\r\n    BOOST_UBLAS_TEST_CHECK(  test_vector< std::complex<double> >( \"std::complex<double>\") );\r\n    BOOST_UBLAS_TEST_CHECK(  test_vector< std::complex<float> >( \"std::complex<float>\") );\r\n    BOOST_UBLAS_TEST_CHECK(  test_vector< std::complex<int> >( \"std::complex<int>\") );\r\n\r\n    BOOST_UBLAS_TEST_CHECK(  test_matrix< double >( \"double\") );\r\n    BOOST_UBLAS_TEST_CHECK(  test_matrix< float >( \"float\") );\r\n    BOOST_UBLAS_TEST_CHECK(  test_matrix< int >( \"int\") );\r\n\r\n    BOOST_UBLAS_TEST_CHECK(  test_matrix< std::complex<double> >( \"std::complex<double>\") );\r\n    BOOST_UBLAS_TEST_CHECK(  test_matrix< std::complex<float> >( \"std::complex<float>\") );\r\n    BOOST_UBLAS_TEST_CHECK(  test_matrix< std::complex<int> >( \"std::complex<int>\") );\r\n}\r\n\r\n\r\nint main () {\r\n\r\n    BOOST_UBLAS_TEST_BEGIN();\r\n\r\n    BOOST_UBLAS_TEST_DO( test_fixed );\r\n\r\n    BOOST_UBLAS_TEST_END();\r\n    return EXIT_SUCCESS;\r\n\r\n}\r\n\r\n#else\r\n\r\nint main () {\r\n\r\n    BOOST_UBLAS_TEST_BEGIN();\r\n    BOOST_UBLAS_TEST_END();\r\n\r\n    return EXIT_SUCCESS;\r\n\r\n}\r\n#endif // BOOST_UBLAS_CPP_GE_2011\r\n", "meta": {"hexsha": "ef2465a8ed4310aecee0f0568325d0e44039cc43", "size": 7041, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/numeric/ublas/test/test_fixed_containers.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": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/numeric/ublas/test/test_fixed_containers.cpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-03-04T11:21:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-24T01:36:31.000Z", "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/numeric/ublas/test/test_fixed_containers.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 22.7129032258, "max_line_length": 95, "alphanum_fraction": 0.4534867206, "num_tokens": 2344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.49578476835815527}}
{"text": "//          Copyright Carl Philipp Reh 2009 - 2016.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n\n#include <fcppt/math/matrix/comparison.hpp>\n#include <fcppt/math/matrix/output.hpp>\n#include <fcppt/math/matrix/row.hpp>\n#include <fcppt/math/matrix/static.hpp>\n#include <fcppt/preprocessor/disable_gcc_warning.hpp>\n#include <fcppt/preprocessor/pop_warning.hpp>\n#include <fcppt/preprocessor/push_warning.hpp>\n#include <fcppt/config/external_begin.hpp>\n#include <boost/test/unit_test.hpp>\n#include <fcppt/config/external_end.hpp>\n\n\nnamespace\n{\n\ntypedef\nfcppt::math::matrix::static_<\n\tint,\n\t2,\n\t2\n>\nmatrix_type;\n\n}\n\nFCPPT_PP_PUSH_WARNING\nFCPPT_PP_DISABLE_GCC_WARNING(-Weffc++)\n\nBOOST_AUTO_TEST_CASE(\n\tmath_matrix_operators_add\n)\n{\nFCPPT_PP_POP_WARNING\n\n\tmatrix_type const first(\n\t\tfcppt::math::matrix::row(\n\t\t\t1, 2\n\t\t),\n\t\tfcppt::math::matrix::row(\n\t\t\t3, 4\n\t\t)\n\t);\n\n\tmatrix_type second(\n\t\tfcppt::math::matrix::row(\n\t\t\t2, 3\n\t\t),\n\t\tfcppt::math::matrix::row(\n\t\t\t4, 5\n\t\t)\n\t);\n\n\tsecond += first;\n\n\tBOOST_CHECK_EQUAL(\n\t\tsecond,\n\t\tmatrix_type(\n\t\t\tfcppt::math::matrix::row(\n\t\t\t\t3, 5\n\t\t\t),\n\t\t\tfcppt::math::matrix::row(\n\t\t\t\t7, 9\n\t\t\t)\n\t\t)\n\t);\n}\n\nFCPPT_PP_PUSH_WARNING\nFCPPT_PP_DISABLE_GCC_WARNING(-Weffc++)\n\nBOOST_AUTO_TEST_CASE(\n\tmath_matrix_operators_scalar\n)\n{\nFCPPT_PP_POP_WARNING\n\n\tmatrix_type first(\n\t\tfcppt::math::matrix::row(\n\t\t\t1, 2\n\t\t),\n\t\tfcppt::math::matrix::row(\n\t\t\t3, 4\n\t\t)\n\t);\n\n\tfirst *= 3;\n\n\tBOOST_CHECK_EQUAL(\n\t\tfirst,\n\t\tmatrix_type(\n\t\t\tfcppt::math::matrix::row(\n\t\t\t\t3, 6\n\t\t\t),\n\t\t\tfcppt::math::matrix::row(\n\t\t\t\t9, 12\n\t\t\t)\n\t\t)\n\t);\n}\n", "meta": {"hexsha": "fba32d36468267adc06766703a74e5748a9c9565", "size": 1655, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/math/matrix/operators.cpp", "max_stars_repo_name": "vinzenz/fcppt", "max_stars_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "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": "test/math/matrix/operators.cpp", "max_issues_repo_name": "vinzenz/fcppt", "max_issues_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "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/math/matrix/operators.cpp", "max_forks_repo_name": "vinzenz/fcppt", "max_forks_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "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": 15.6132075472, "max_line_length": 61, "alphanum_fraction": 0.6809667674, "num_tokens": 556, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587586, "lm_q2_score": 0.7090191337850933, "lm_q1q2_score": 0.4957847639144779}}
{"text": "#pragma once\n\n#include \"gtest/gtest.h\"\n\n#include \"../util/Maybe.hh\"\n#include \"../geometry/LineSegment/linesegment.hh\"\n\n#include <Eigen/Core>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <iostream>\n\ninline ::testing::AssertionResult VectorsEqual(Eigen::Vector3d const& expected, Eigen::Vector3d const& actual, const float delta = 0.00001) {\n  double d = (expected-actual).norm();\n  if (d < delta)\n    return ::testing::AssertionSuccess();\n  else\n    return ::testing::AssertionFailure() << \"Actual: \" << actual.transpose() << \", expected: \" << expected.transpose() << \" d = \" << d;\n}\n\ninline ::testing::AssertionResult VectorsEqual(Eigen::Vector2d const& expected, Eigen::Vector2d const& actual, const double delta = 0.00001) {\n  double d = (expected-actual).norm();\n  if (d < delta)\n    return ::testing::AssertionSuccess();\n  else\n    return ::testing::AssertionFailure() << \"Actual: \" << actual.transpose() << \", expected: \" << expected.transpose() << \" d = \" << d;\n}\n\ntemplate<typename T, int N>\ninline ::testing::AssertionResult VectorsEqual(Eigen::Matrix<T,N,1> const& expected, Eigen::Matrix<T,N,1> const& actual, const double delta = 0.00001) {\n  double d = (expected-actual).norm();\n  if (d < delta)\n    return ::testing::AssertionSuccess();\n  else\n    return ::testing::AssertionFailure() << \"Actual: \" << actual.transpose() << \", expected: \" << expected.transpose() << \" d = \" << d;\n}\n\ntemplate<int N>\ninline ::testing::AssertionResult VectorsEqual(Eigen::Matrix<int,N,1> const& expected, Eigen::Matrix<int,N,1> const& actual) {\n  double d = (expected-actual).norm();\n  if (d == 0)\n    return ::testing::AssertionSuccess();\n  else\n    return ::testing::AssertionFailure() << \"Actual: \" << actual.transpose() << \", expected: \" << expected.transpose() << \" d = \" << d;\n}\n\ninline ::testing::AssertionResult MatricesEqual(Eigen::MatrixXd const& expected, Eigen::MatrixXd const& actual, double delta = 0.000001) {\n  double d = (expected-actual).array().abs().sum();\n  if (d < delta)\n    return ::testing::AssertionSuccess();\n  else\n    return ::testing::AssertionFailure() << \"Actual: \" << std::endl << actual << std::endl << \"Expected: \" << std::endl << expected << std::endl << \" d = \" << d;\n}\n\ntemplate<typename T, int dim>\ninline ::testing::AssertionResult LinesEqual(bold::LineSegment<T,dim> const& expected, bold::LineSegment<T,dim> const& actual, const double delta = 0.000001) {\n  double d1 = (expected.p1()-actual.p1()).norm();\n  double d2 = (expected.p2()-actual.p2()).norm();\n  if (d1 <= delta && d2 <= delta)\n    return ::testing::AssertionSuccess();\n  else\n    return ::testing::AssertionFailure() << \"Actual: \" << actual << \", expected: \" << expected << \" d1=\" << d1 << \" d2=\" << d2;\n}\n\n//PrintTo(const T&, ostream*)\n\ninline std::ostream& operator<<(std::ostream& stream, Eigen::Vector2i const& v)\n{\n  return stream << \"(\" << v.x() << \", \" << v.y() << \")\";\n}\n\ninline std::ostream& operator<<(std::ostream& stream, Eigen::Vector2f const& v)\n{\n  return stream << \"(\" << v.x() << \", \" << v.y() << \")\";\n}\n\ninline std::ostream& operator<<(std::ostream& stream, Eigen::Vector2d const& v)\n{\n  return stream << \"(\" << v.x() << \", \" << v.y() << \")\";\n}\n\ninline std::ostream& operator<<(std::ostream& stream, Eigen::Vector3d const& v)\n{\n  return stream << \"(\" << v.x() << \", \" << v.y() << \", \" << v.z() << \")\";\n}\n\ninline bool operator==(Eigen::Vector2i const& expected, Eigen::Vector2i const& actual)\n{\n  return expected.x() == actual.x() && expected.y() == actual.y();\n}\n\n\n#define ASSERT_EMPTY(condition) \\\n  GTEST_TEST_BOOLEAN_(!(condition.hasValue()), #condition, Non-empty, Empty, \\\n                      GTEST_FATAL_FAILURE_) << *condition\n\n#define EXPECT_EMPTY(condition) \\\n  GTEST_TEST_BOOLEAN_(!(condition.hasValue()), #condition, Non-empty, Empty, \\\n                      GTEST_NONFATAL_FAILURE_) << *condition\n\n#define EXPECT_BETWEEN(lower, upper, val) \\\n  do { \\\n  EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val, lower); \\\n  EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val, upper); \\\n  } while (0)\n", "meta": {"hexsha": "6be80df6da1774003b644ee6d010758addf15944", "size": 4050, "ext": "hh", "lang": "C++", "max_stars_repo_path": "test/helpers.hh", "max_stars_repo_name": "drewnoakes/bold-humanoid", "max_stars_repo_head_hexsha": "6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335", "max_stars_repo_licenses": ["Apache-2.0"], "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/helpers.hh", "max_issues_repo_name": "drewnoakes/bold-humanoid", "max_issues_repo_head_hexsha": "6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335", "max_issues_repo_licenses": ["Apache-2.0"], "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/helpers.hh", "max_forks_repo_name": "drewnoakes/bold-humanoid", "max_forks_repo_head_hexsha": "6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335", "max_forks_repo_licenses": ["Apache-2.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.2075471698, "max_line_length": 161, "alphanum_fraction": 0.6372839506, "num_tokens": 1092, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850933, "lm_q2_score": 0.6992544147913993, "lm_q1q2_score": 0.49578475947080025}}
{"text": "//\n// Copyright (c) 2016 - 2017 Mesh Consultants Inc.\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n//\n\n#include \"Geomlib_PolylineIntersection.h\"\n#include \"Geomlib_BestFitPlane.h\"\n#include <vector>\n#include <algorithm>\n#include <Eigen/Core>\n#include \"Polyline.h\"\n\nusing Urho3D::Vector;\nusing Urho3D::Vector3;\nusing Urho3D::Vector2;\n\nusing namespace Urho3D;\n\n// [t1, t2] interval of real number line; no promise that t1 <= t2\n// [s1, s2] interval of real number line; no promise that s1 <= s2\n// Returns:\n//   1 if [t1, t2] and [s1, s2] have non-empty intersection\n//   0 otherwise\nint Geomlib::IntervalIntervalIntersection(\n\tdouble t1,\n\tdouble t2,\n\tdouble s1,\n\tdouble s2)\n{\n\tif (t1 > t2) {\n\t\tdouble x = t1;\n\t\tt1 = t2;\n\t\tt2 = x;\n\t}\n\tif (s1 > s2) {\n\t\tdouble y = s1;\n\t\ts1 = s2;\n\t\ts2 = y;\n\t}\n\n\tif (s1 <= t1 && t1 <= s2) {\n\t\treturn 1;\n\t}\n\telse if (s1 <= t2 && t2 <= s2) {\n\t\treturn 1;\n\t}\n\telse if (t1 <= s1 && s1 <= t2) {\n\t\treturn 1;\n\t}\n\n\treturn 0;\n}\n\n//   1 if (A,B) and (C,D) have non-empty intersection\n//   0 otherwise\nint Geomlib::SegmentSegmentIntersection2D(\n\tVector2& A,\n\tVector2& B,\n\tVector2& C,\n\tVector2& D)\n{\n\t// left & right half plane checks\n\tif (\n\t\t(A.x_ > 0 && B.x_ > 0) && // A,B in right half plane\n\t\t(C.x_ < 0 && D.x_ < 0)    // C,D in left half plane\n\t\t) {\n\t\treturn 0;\n\t}\n\tif (\n\t\t(A.x_ < 0 && B.y_ < 0) && // A,B in left half plane\n\t\t(C.x_ > 0 && D.y_ > 0)    // C,D in right half plane\n\t\t) {\n\t\treturn 0;\n\t}\n\t// upper & lower half plane checks\n\tif (\n\t\t(A.y_ > 0 && B.y_ > 0) && // A,B in upper half plane\n\t\t(C.y_ < 0 && D.y_ < 0)    // C,D in lower half plane\n\t\t) {\n\t\treturn 0;\n\t}\n\tif (\n\t\t(A.y_ < 0 && B.y_ < 0) && // A,B in lower half plane\n\t\t(C.y_ > 0 && D.y_ > 0)    // C,D in upper half plane\n\t\t) {\n\t\treturn 0;\n\t}\n\n\t// do C and D lie strictly on the same side of line through AB?\n\tdouble cval = (B.y_ - A.y_) * (C.x_ - A.x_) + (A.x_ - B.x_) * (C.y_ - A.y_);\n\tdouble dval = (B.y_ - A.y_) * (D.x_ - A.x_) + (A.x_ - B.x_) * (D.y_ - A.y_);\n\tif ((cval > 0 && dval > 0) || (cval < 0 && dval < 0)) {\n\t\treturn 0;\n\t}\n\t// do A and B lie strictly on the same side of line through CD?\n\tdouble aval = (D.y_ - C.y_) * (A.x_ - C.x_) + (C.x_ - D.x_) * (A.y_ - C.y_);\n\tdouble bval = (D.y_ - C.y_) * (B.x_ - C.x_) + (C.x_ - D.x_) * (B.y_ - C.y_);\n\tif ((aval > 0 && bval > 0) || (aval < 0 && bval < 0)) {\n\t\treturn 0;\n\t}\n\n\t// lines through AB and CD definitely intersect\n\tdouble k11 = B.x_ - A.x_;\n\tdouble k12 = C.x_ - D.x_;\n\tdouble k21 = B.y_ - A.y_;\n\tdouble k22 = C.y_ - D.y_;\n\tdouble z1 = C.x_ - A.x_;\n\tdouble z2 = C.y_ - A.y_;\n\tdouble prod1 = k11 * k22;\n\tdouble prod2 = k12 * k21;\n\tdouble prod3 = k22 * z1;\n\tdouble prod4 = k12 * z2;\n    if (std::abs(prod1) > 1e16 || std::abs(prod2) > 1e16 || std::abs(prod3) > 1e16 || std::abs(prod4) > 1e16) {\n\t\tdouble shrink = 1e-6;\n\t\tVector2 newA = shrink * A;\n\t\tVector2 newB = shrink * B;\n\t\tVector2 newC = shrink * C;\n\t\tVector2 newD = shrink * D;\n\t\treturn Geomlib::SegmentSegmentIntersection2D(newA, newB, newC, newD);\n\t}\n\tdouble denom = prod1 - prod2;\n\tdouble numer = prod3 - prod4;\n\tif (prod1 == prod2) {\n\t\tdenom = 0;\n\t}\n\n\tconst double eps = 1e-8;\n\n\tif (denom > eps || -denom > eps) {\n\t\t// there is unique point of intersection: does it lie in segment AB?\n\t\tdouble t = (k22 * z1 - k12 * z2) / denom;\n\t\treturn 0 <= t && t <= 1;\n\t}\n\telse {\n\t\t// lines through AB and CD coincide\n\t\tdouble rise = B.y_ - A.y_;\n\t\tdouble run = B.x_ - A.x_;\n\t\t// normal is (-rise, run)\n\t\tif (rise >= run) { // x-coord of normal is bigger, project segments to y-axis\n\t\t\treturn Geomlib::IntervalIntervalIntersection(A.y_, B.y_, C.y_, D.y_);\n\t\t}\n\t\telse { // y-coord of normal is bigger, project segments to x-axis\n\t\t\treturn Geomlib::IntervalIntervalIntersection(A.x_, B.x_, C.x_, D.x_);\n\t\t}\n\t}\n}\n\n\tint Geomlib::SegmentSegmentIntersection3D(\n\t\tVector3& A,\n\t\tVector3& B,\n\t\tVector3& C,\n\t\tVector3& D,\n\t\tVector3& normal)\n\t{\n\t\t\n\n\t\t// converting to regular vector to use max_element\n\t\tstd::vector<double> Nreg;\n\t\tNreg.push_back(std::abs(normal.x_));\n\t\tNreg.push_back(std::abs(normal.y_));\n\t\tNreg.push_back(std::abs(normal.z_));\n\n\t\t// find greatest coordinate from plane normal\n\t\t// projection plane will be the plane generate by the OTHER coordinate axes\n\t\t// e.g. if N.y is largest, project to xz-plane\n\t\tint maxCoord = std::max_element(Nreg.begin(), Nreg.end()) - Nreg.begin();\n\n\n\t\tVector<Vector3> startVerts;\n\t\tstartVerts.Push(A);\n\t\tstartVerts.Push(B);\n\t\tstartVerts.Push(C);\n\t\tstartVerts.Push(D);\n\n\t\t// project coords to the appropriate plane\n\t\t// NOTE SYNTAX!!!!!!!!!!! \n\t\tstd::vector<Eigen::RowVector2d, Eigen::aligned_allocator<Eigen::RowVector2d>> flatVerts;\n\t\t//Vector<Vector2> flatVerts;\n\t\tfor (int i = 0; i < startVerts.Size(); ++i)\n\t\t{\n\t\t\tint counter = 0;\n\t\t\tEigen::RowVector2d tmpCoords;\n\t\t\t//Vector2 tmpCoords;\n\t\t\tfor (int j = 0; j < 3; ++j)\n\t\t\t{\n\t\t\t\tif (j != maxCoord)\n\t\t\t\t{\n\t\t\t\t\t//std::cout << \"counter=\" << counter << \" j=\" << j << std::endl;\n\t\t\t\t\t//std::cout << \"startVerts[\" << i << \"](\" << j << \")=\" << startVerts[i](j) << std::endl;\n\t\t\t\t\tif (j == 0)\n\t\t\t\t\t\ttmpCoords(counter) = startVerts[i].x_;\n\t\t\t\t\telse if (j == 1)\n\t\t\t\t\t\ttmpCoords(counter) = startVerts[i].y_;\n\t\t\t\t\telse if (j == 2)\n\t\t\t\t\t\ttmpCoords(counter) = startVerts[i].z_;\n\t\t\t\t\t++counter;\n\t\t\t\t}\n\t\t\t}\n\t\t\t//std::cout << \"tmpCoords=\" << tmpCoords << std::endl;\n\t\t\tflatVerts.push_back(tmpCoords);\n\t\t}\n\n\t\tVector2 newA(flatVerts[0](0), flatVerts[0](1));\n\t\tVector2 newB(flatVerts[1](0), flatVerts[1](1));\n\t\tVector2 newC(flatVerts[2](0), flatVerts[2](1));\n\t\tVector2 newD(flatVerts[3](0), flatVerts[3](1));\n\n\t\tint ret = Geomlib::SegmentSegmentIntersection2D(\n\t\t\tnewA,\n\t\t\tnewB,\n\t\t\tnewC,\n\t\t\tnewD);\n\n\t\treturn ret;\n\n\t}\n\n\tbool Geomlib::HasSelfIntersection(const Urho3D::Variant polyline)\n\t{\n\t\tVariantVector verts = Polyline_ComputeSequentialVertexList(polyline);\n\n\t\t// This will only work for planar polylines!\n\t\tVector3 point, normal;\n\t\tGeomlib::BestFitPlane(Polyline_ComputePointCloud(polyline), point, normal);\n\n\t\tbool closed = Polyline_IsClosed(polyline);\n\t\tint counter = verts.Size()-4;\n\t\tif (counter < 4)\n\t\t\treturn false;\n\t\t\n\t\tfor (int i = 0; i < counter; ++i) {\n\t\t\tVector3 A = verts[i].GetVector3();\n\t\t\tVector3 B = verts[i + 1].GetVector3();\n\t\t\tfor (int j = i + 2; j < counter+2; ++j) {\n\t\t\t\tVector3 C = verts[j].GetVector3();\n\t\t\t\tVector3 D = verts[j + 1].GetVector3();\n\t\t\t\tint ret = Geomlib::SegmentSegmentIntersection3D(A, B, C, D, normal);\n\t\t\t\tif (ret == 1)\n\t\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tint Geomlib::GetSelfIntersections(const Urho3D::Variant polyline, Urho3D::Vector<Urho3D::Vector3>& intersections, Urho3D::Variant& revised_polyline)\n\t{\n\t\tVariantVector verts = Polyline_ComputeSequentialVertexList(polyline);\n\t\tVector<Vector3> revised_verts;\n\t\tfor (int i = 0; i < verts.Size(); ++i)\n\t\t\trevised_verts.Push(verts[i].GetVector3());\n\n\t\t// This will only work for planar polylines!\n\t\tVector3 point, normal;\n\t\tGeomlib::BestFitPlane(Polyline_ComputePointCloud(polyline), point, normal);\n\n\t\tbool closed = Polyline_IsClosed(polyline);\n\t\tint counter = verts.Size() - 4;\n\t\tif (counter < 4)\n\t\t\treturn 0;\n\n\t\tfor (int i = 0; i < counter; ++i) {\n\t\t\tVector3 A = verts[i].GetVector3();\n\t\t\tVector3 B = verts[i + 1].GetVector3();\n\t\t\tfor (int j = i + 2; j < counter + 2; ++j) {\n\t\t\t\tVector3 C = verts[j].GetVector3();\n\t\t\t\tVector3 D = verts[j + 1].GetVector3();\n\t\t\t\tint ret = Geomlib::SegmentSegmentIntersection3D(A, B, C, D, normal);\n\t\t\t\tif (ret == 1) {\n\t\t\t\t\tVector3 point;\n\t\t\t\t\tint success = GetPointOfIntersection(A, B, C, D, point);\n\t\t\t\t\tif (success) {\n\t\t\t\t\t\tintersections.Push(point);\n\t\t\t\t\t\tInsertSelfIntersectionsAsPoint(A, B, C, D, point, revised_verts);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\trevised_polyline = Geomlib::Polyline_Make_With_Intersections(revised_verts);\n\t\treturn 1;\n\t}\n\n\t// inserts the point into the vertex list between A, B and C, D \n\tint Geomlib::InsertSelfIntersectionsAsPoint(\n\t\tconst Urho3D::Vector3& A,\n\t\tconst Urho3D::Vector3& B,\n\t\tconst Urho3D::Vector3& C,\n\t\tconst Urho3D::Vector3& D,\n\t\tconst Urho3D::Vector3& point,\n\t\tUrho3D::Vector<Urho3D::Vector3>& verts)\n\t{\n\t\t// Assuming this inserts before the destination element?\n\t\tVector<Vector3>::Iterator it_D= verts.Find(D);\n\t\tverts.Insert(it_D, point);\n\n\t\tVector<Vector3>::Iterator it_B = verts.Find(B);\n\t\tverts.Insert(it_B, point);\n\n\t\treturn 0;\n\t}\n\n\tint Geomlib::GetPointOfIntersection( const Urho3D::Vector3 & A, const Urho3D::Vector3 & B, const Urho3D::Vector3 & C, const Urho3D::Vector3 & D, Urho3D::Vector3& point)\n\t{\n\t\tdouble ta, tb;\n\t\tbool success = Geomlib::ShortestDistance(A, B, C, D, ta, tb);\n\t\tif (ta < 0 || ta > 1 || tb < 0 || tb >1)\n\t\t\treturn 0;\n\n\t\t// find the points on the line segments\n\t\tVector3 pa = A + ta*(B - A);\n\t\tVector3 pb = C + tb*(D - C);\n\n\t\t// if the distance between the points is small, this is a true intersection\n\t\tdouble dist = (pb - pa).Length();\n\t\tif (dist < 0.0001) {\n\t\t\tpoint = pa;\n\t\t\treturn 1;\n\t\t}\n\t\t\n\t\treturn 0;\n\t}\n\n\t/// returns parameters on each line. If they are between 0-1, the closest point lies on the line. Otherwise,\n\t/// the point is on the ray defined by the line direction.\n\t/// if return is false, the closest point could not be calculated (probably due to the lines being parallel)\n\tbool Geomlib::ShortestDistance(\n\t\tconst Vector3& A,\n\t\tconst Vector3& B,\n\t\tconst Vector3& C,\n\t\tconst Vector3& D, \n\t\tdouble& ta, double& tb)\n\t{\n\n\t\tVector3 u = B - A;\n\t\tVector3 v = D - C;\n\t\tVector3 w = A - C;\n\n\t\tdouble dot = u.Normalized().DotProduct(v.Normalized());\n\n        if (std::abs(dot - 1.0) < 10e-7)\n\t\t\treturn false;\n\n\t\tdouble uu = u.DotProduct(u);\n\t\tdouble uv = u.DotProduct(v);\n\t\tdouble vv = v.DotProduct(v);\n\t\tdouble uw = u.DotProduct(w);\n\t\tdouble vw = v.DotProduct(w);\n\n\t\tdouble t = 1.0 / (uu * vv - uv * uv);\n\t\tta = (uv * vw - vv * uw) * t;\n\t\ttb = (uu * vw - uv * uw) * t;\n\n\t\treturn true;\n\n\t}\n\n\tUrho3D::Variant Geomlib::Polyline_Make_With_Intersections(const Urho3D::Vector<Urho3D::Vector3>& vertexList)\n\t{\n\t\tVariant earlyRet;\n\t\tif (vertexList.Size() < 2) {\n\t\t\treturn earlyRet;\n\t\t}\n\n\t\tVector<Variant> vertices;\n\t\tVector<Variant> edges;\n\n\t\tfor (int i = 0; i < vertexList.Size(); ++i) {\n\t\t\tvertices.Push(Variant(vertexList[i]));\n\t\t\tedges.Push(Variant(i));\n\t\t}\n\t\tVariantMap var_map;\n\t\tvar_map[\"type\"] = Variant(String(\"Polyline\"));\n\t\tvar_map[\"vertices\"] = Variant(vertices);\n\t\tvar_map[\"edges\"] = Variant(edges);\n\n\t\treturn Variant(var_map);\n\t}\n", "meta": {"hexsha": "adb0f10df2bbc91e8366ba5814f22852d44f3cd8", "size": 11253, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Geometry/Geomlib_PolylineIntersection.cpp", "max_stars_repo_name": "elix22/IogramSource", "max_stars_repo_head_hexsha": "3a4ce55d94920e060776b4aa4db710f57a4280bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28.0, "max_stars_repo_stars_event_min_datetime": "2017-03-01T04:09:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T13:33:50.000Z", "max_issues_repo_path": "Geometry/Geomlib_PolylineIntersection.cpp", "max_issues_repo_name": "elix22/IogramSource", "max_issues_repo_head_hexsha": "3a4ce55d94920e060776b4aa4db710f57a4280bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2017-03-09T05:22:49.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-02T18:38:05.000Z", "max_forks_repo_path": "Geometry/Geomlib_PolylineIntersection.cpp", "max_forks_repo_name": "elix22/IogramSource", "max_forks_repo_head_hexsha": "3a4ce55d94920e060776b4aa4db710f57a4280bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2017-03-01T14:00:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T06:36:54.000Z", "avg_line_length": 28.6335877863, "max_line_length": 169, "alphanum_fraction": 0.6346751977, "num_tokens": 3718, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191214879992, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.4957847553156804}}
{"text": "/*=============================================================================\n    Copyright (c) 2002-2003 Hartmut Kaiser\n    http://spirit.sourceforge.net/\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///////////////////////////////////////////////////////////////////////////////\n//\n//  Full calculator example\n//  [ demonstrating phoenix and subrules ]\n//\n//  [ Hartmut Kaiser 10/8/2002 ]\n//\n///////////////////////////////////////////////////////////////////////////////\n\n//#define BOOST_SPIRIT_DEBUG        // define this for debug output\n\n#include <boost/spirit/include/classic_core.hpp>\n#include <boost/spirit/include/classic_attribute.hpp>\n#include <iostream>\n#include <string>\n\n///////////////////////////////////////////////////////////////////////////////\nusing namespace std;\nusing namespace BOOST_SPIRIT_CLASSIC_NS;\nusing namespace phoenix;\n\n///////////////////////////////////////////////////////////////////////////////\n//\n//  Our calculator grammar using phoenix to do the semantics and subrule's\n//  as it's working horses\n//\n//  Note:   The top rule propagates the expression result (value) upwards\n//          to the calculator grammar self.val closure member which is\n//          then visible outside the grammar (i.e. since self.val is the\n//          member1 of the closure, it becomes the attribute passed by\n//          the calculator to an attached semantic action. See the\n//          driver code that uses the calculator below).\n//\n///////////////////////////////////////////////////////////////////////////////\nstruct calc_closure : BOOST_SPIRIT_CLASSIC_NS::closure<calc_closure, double>\n{\n    member1 val;\n};\n\nstruct calculator : public grammar<calculator, calc_closure::context_t>\n{\n    template <typename ScannerT>\n    struct definition\n    {\n        definition(calculator const& self)\n        {\n            top = (\n                expression =\n                    term[self.val = arg1]\n                    >> *(   ('+' >> term[self.val += arg1])\n                        |   ('-' >> term[self.val -= arg1])\n                        )\n                ,\n\n                term =\n                    factor[term.val = arg1]\n                    >> *(   ('*' >> factor[term.val *= arg1])\n                        |   ('/' >> factor[term.val /= arg1])\n                        )\n                ,\n\n                factor\n                    =    ureal_p[factor.val = arg1]\n                    |   '(' >> expression[factor.val = arg1] >> ')'\n                    |   ('-' >> factor[factor.val = -arg1])\n                    |   ('+' >> factor[factor.val = arg1])\n            );\n\n            BOOST_SPIRIT_DEBUG_NODE(top);\n            BOOST_SPIRIT_DEBUG_NODE(expression);\n            BOOST_SPIRIT_DEBUG_NODE(term);\n            BOOST_SPIRIT_DEBUG_NODE(factor);\n        }\n\n        subrule<0, calc_closure::context_t>  expression;\n        subrule<1, calc_closure::context_t>  term;\n        subrule<2, calc_closure::context_t>  factor;\n\n        rule<ScannerT> top;\n\n        rule<ScannerT> const&\n        start() const { return top; }\n    };\n};\n\n///////////////////////////////////////////////////////////////////////////////\n//\n//  Main program\n//\n///////////////////////////////////////////////////////////////////////////////\nint\nmain()\n{\n    cout << \"/////////////////////////////////////////////////////////\\n\\n\";\n    cout << \"\\t\\tExpression parser using Phoenix...\\n\\n\";\n    cout << \"/////////////////////////////////////////////////////////\\n\\n\";\n    cout << \"Type an expression...or [q or Q] to quit\\n\\n\";\n\n    calculator calc;    //  Our parser\n\n    string str;\n    while (getline(cin, str))\n    {\n        if (str.empty() || str[0] == 'q' || str[0] == 'Q')\n            break;\n\n        double n = 0;\n        parse_info<> info = parse(str.c_str(), calc[var(n) = arg1], space_p);\n\n        //  calc[var(n) = arg1] invokes the calculator and extracts\n        //  the result of the computation. See calculator grammar\n        //  note above.\n\n        if (info.full)\n        {\n            cout << \"-------------------------\\n\";\n            cout << \"Parsing succeeded\\n\";\n            cout << \"result = \" << n << endl;\n            cout << \"-------------------------\\n\";\n        }\n        else\n        {\n            cout << \"-------------------------\\n\";\n            cout << \"Parsing failed\\n\";\n            cout << \"stopped at: \\\": \" << info.stop << \"\\\"\\n\";\n            cout << \"-------------------------\\n\";\n        }\n    }\n\n    cout << \"Bye... :-) \\n\\n\";\n    return 0;\n}\n\n\n", "meta": {"hexsha": "9cdfdd04bfc6de75df2162b346d24c029e0dfb93", "size": 4712, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/spirit/classic/example/fundamental/more_calculators/phoenix_subrule_calc.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "boost/libs/spirit/classic/example/fundamental/more_calculators/phoenix_subrule_calc.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "boost/libs/spirit/classic/example/fundamental/more_calculators/phoenix_subrule_calc.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 32.951048951, "max_line_length": 79, "alphanum_fraction": 0.4229626486, "num_tokens": 919, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587586, "lm_q2_score": 0.7090191214879991, "lm_q1q2_score": 0.4957847553156804}}
{"text": "/*\nmatrix/MatrixRxC.hpp\n-----------------------\nCopyright (c) 2014, theJ89\n\nDescription:\n    Adds a generic matrix class, Matrix.\n    You can specify what type of data the matrix uses (int, float, etc) as well as the number of rows and columns in the matrix.\n    The code in this file handles rectangular matrices.\n    Common specializations of Matrix are provided in Matrix2x2.hpp, Matrix3x3.hpp, Matrix4x4.hpp, and MatrixNxN.hpp.\n*/\n#ifndef BS_MATRIX_MATRIXRXC_HPP\n#define BS_MATRIX_MATRIXRXC_HPP\n\n\n\n\n//Includes\n#include <iostream>                     //std::ostream\n#include <iomanip>                      //std::setw, std::setprecision\n\n#include <boost/format.hpp>             //boost::format\n\n#include <brimstone/util/Array.hpp>     //BS_ARRAY_DECLARE_METHODS, BS_ARRAY_DEFINE_METHODS, etc\n#include <brimstone/Vector.hpp>         //Vector\n#include <brimstone/util/MinMax.hpp>    //electMax\n\n\n\n\n//Macros\n#define BS_MATRIX_DECLARE_METHODS( R, C )                                   \\\n    Matrix();                                                               \\\n                                                                            \\\n    template< typename T2 >                                                 \\\n    Matrix( const Matrix< T2, R, C >& toCopy );                             \\\n                                                                            \\\n    bool isSquare() const;                                                  \\\n    size_t getRows() const;                                                 \\\n    size_t getColumns() const;                                              \\\n                                                                            \\\n    void zero();                                                            \\\n    bool isZero() const;                                                    \\\n    void identity();                                                        \\\n    bool isIdentity() const;                                                \\\n                                                                            \\\n    void setRow( const size_t row, const Vector< T, C >& values );          \\\n    void setColumn( const size_t col, const Vector< T, R >& values );       \\\n                                                                            \\\n    Vector< T, C > getRow( const size_t row ) const;                        \\\n    Vector< T, R > getColumn( const size_t col ) const;                     \\\n                                                                            \\\n    template< typename T2 >                                                 \\\n    Matrix& operator =( const Matrix< T2, R, C >& right );                  \\\n    Matrix& operator +=( const Matrix& right );                             \\\n    Matrix& operator -=( const Matrix& right );                             \\\n    Matrix& operator *=( const Matrix< T, C, C >& right );                  \\\n    Matrix& operator +=( const T right );                                   \\\n    Matrix& operator -=( const T right );                                   \\\n    Matrix& operator *=( const T right );                                   \\\n    Matrix& operator /=( const T right );                                   \\\n    T&      operator ()( const size_t row, const size_t col );              \\\n    T       operator ()( const size_t row, const size_t col ) const;\n\n#define BS_MATRIX_DEFINE_METHODS( R, C, tmpl, spec )                        \\\n    tmpl                                                                    \\\n    size_t Matrix spec::getRows() const {                                   \\\n        return R;                                                           \\\n    }                                                                       \\\n    tmpl                                                                    \\\n    size_t Matrix spec::getColumns() const {                                \\\n        return C;                                                           \\\n    }                                                                       \\\n    tmpl                                                                    \\\n    void Matrix spec::identity() {                                          \\\n        (*this) = m_identity;                                               \\\n    }                                                                       \\\n    tmpl                                                                    \\\n    bool Matrix spec::isIdentity() const {                                  \\\n        return (*this) == m_identity;                                       \\\n    }                                                                       \\\n    tmpl                                                                    \\\n    T& Matrix spec::operator()( const size_t row, const size_t col ) {      \\\n        BS_ASSERT_INDEX( row, R - 1 );                                      \\\n        BS_ASSERT_INDEX( col, C - 1 );                                      \\\n        return elem[row][col];                                              \\\n    }                                                                       \\\n    tmpl                                                                    \\\n    T Matrix spec::operator()( const size_t row, const size_t col ) const { \\\n        BS_ASSERT_INDEX( row, R - 1 );                                      \\\n        BS_ASSERT_INDEX( col, C - 1 );                                      \\\n        return elem[row][col];                                              \\\n    }\n\nnamespace Brimstone {\n\ntemplate< typename T, size_t R, size_t C >\nclass Matrix {\npublic:\n//C4201: nonstandard extension used : nameless struct/union\n//It's a non-standard feature, but VC++, G++, and LLVM support it so it shouldn't be too much of an issue\n#pragma warning( push )\n#pragma warning( disable: 4201 )\n\n    union {\n        T              data[ R * C ];\n        T              elem[R][C];\n        struct {\n            Vector< T, C > row[ R ];\n        };\n    };\n\n#pragma warning( pop )\npublic:\n    BS_ARRAY_DECLARE_INHERITED_METHODS( Matrix, T )\n    BS_ARRAY_DECLARE_METHODS( Matrix, T )\n    BS_MATRIX_DECLARE_METHODS( R, C )\nprivate:\n    struct ConstructIdentity {};\n    Matrix( const ConstructIdentity );\n    static const Matrix m_identity;\n};\nBS_ARRAY_DEFINE_GENERIC_METHODS( Matrix, T, data, BS_TMPL_3( typename T, size_t R, size_t C ), BS_SPEC_3( T, R, C ) )\nBS_ARRAY_DEFINE_METHODS( Matrix, T, data, BS_TMPL_3( typename T, size_t R, size_t C ), BS_SPEC_3( T, R, C ) )\nBS_MATRIX_DEFINE_METHODS( R, C, BS_TMPL_3( typename T, size_t R, size_t C ), BS_SPEC_3( T, R, C ) )\n\n\n\n\n//Forward declarations\ntemplate< typename T, size_t R, size_t C >\nMatrix< T, C, R > transpose( const Matrix< T, R, C >& matrix );\n\n\n\n\n//Note: We have a private constructor specifically for constructing\n//m_identity. To differentiate it from other constructors,\n//we pass an unused argument of type \"ConstructIdentity\",\n//ConstructIdentity is a private inner class in Matrix, which means that only something\n//belonging to Matrix can instantiate ConstructIdentity objects. Normally this\n//means \"a method in Matrix\", but this also works with statements that initialize\n//static members of Matrix as well.\ntemplate< typename T, size_t R, size_t C >\nconst Matrix< T, R, C > Matrix< T, R, C >::m_identity = Matrix< T, R, C >( ConstructIdentity() );\n\n//We could just put this in the default constructor, but the advantage of this approach\n//is that by copying a pre-built matrix, we can avoid using two loops and running a conditional\n//on each element of every matrix that is default-constructed, and instead only do this once\n//when constructing the identity matrix.\ntemplate< typename T, size_t R, size_t C >\nMatrix< T, R, C >::Matrix( const ConstructIdentity ) {\n    for( size_t r = 0; r < R; ++r )\n        for( size_t c = 0; c < C; ++c )\n            elem[r][c] = ( r == c ? static_cast< T >( 1 ) : static_cast< T >( 0 ) );\n}\n\ntemplate< typename T, size_t R, size_t C >\nMatrix< T, R, C >::Matrix()\n#ifdef BS_ZERO\n    : Matrix( m_identity )\n#endif //BS_ZERO\n{\n}\n\ntemplate< typename T, size_t R, size_t C >\ntemplate< typename T2 >\nMatrix< T, R, C >::Matrix( const Matrix< T2, R, C >& toCopy ) {\n    (*this) = toCopy;\n}\n\ntemplate< typename T, size_t R, size_t C >\nbool Matrix< T, R, C >::isSquare() const {\n    //This function always returns false because the generic case of Matrix handles rectangular matrices.\n    return false;\n}\n\ntemplate< typename T, size_t R, size_t C >\nvoid Matrix< T, R, C >::zero() {\n    T zero = static_cast< T >( 0 );\n    for( size_t i = 0; i < R * C; ++i )\n        data[i] = zero;\n}\n\ntemplate< typename T, size_t R, size_t C >\nbool Matrix< T, R, C >::isZero() const {\n    T zero = static_cast< T >( 0 );\n    for( size_t i = 0; i < R * C; ++i )\n        if( data[i] != zero )\n            return false;\n    return true;\n}\n\ntemplate< typename T, size_t R, size_t C >\nvoid Matrix< T, R, C >::setRow( const size_t row, const Vector< T, C >& values ) {\n    BS_ASSERT_INDEX( row, R - 1 );\n    for( size_t c = 0; c < C; ++c )\n        elem[row][c] = values.data[c];\n}\n\ntemplate< typename T, size_t R, size_t C >\nvoid Matrix< T, R, C >::setColumn( const size_t col, const Vector< T, R >& values ) {\n    BS_ASSERT_INDEX( col, C - 1 );\n    for( size_t r = 0; r < R; ++r )\n        elem[r][col] = values.data[r];\n}\n\ntemplate< typename T, size_t R, size_t C >\nVector< T, C > Matrix< T, R, C >::getRow( const size_t row ) const {\n    BS_ASSERT_INDEX( row, R - 1 );\n    Vector< T, C > out;\n\n    for( size_t c = 0; c < C; ++c )\n        out.data[c] = elem[row][c];\n\n    return out;\n}\n\ntemplate< typename T, size_t R, size_t C >\nVector< T, R > Matrix< T, R, C >::getColumn( const size_t col ) const {\n    BS_ASSERT_INDEX( col, C - 1 );\n    Vector< T, R > out;\n\n    for( size_t r = 0; r < R; ++r )\n        out.data[r] = elem[r][col];\n\n    return out;\n}\n\ntemplate< typename T, size_t R, size_t C >\ntemplate< typename T2 >\nMatrix< T, R, C >& Matrix< T, R, C >::operator =( const Matrix< T2, R, C >& right ) {\n    for( size_t i = 0; i < R * C; ++i )\n        data[i] = static_cast<T>( right.data[i] );\n\n    return (*this);\n}\n\ntemplate< typename T, size_t R, size_t C >\nMatrix< T, R, C >& Matrix< T, R, C >::operator +=( const Matrix& right ) {\n    for( size_t i = 0; i < R * C; ++i )\n        data[i] += right.data[i];\n\n    return ( *this );\n}\n\ntemplate< typename T, size_t R, size_t C >\nMatrix< T, R, C >& Matrix< T, R, C >::operator -=( const Matrix& right ) {\n    for( size_t i = 0; i < R * C; ++i )\n        data[i] -= right.data[i];\n\n    return ( *this );\n}\n\nnamespace Private {\n\n    //Note: You can only multiply an IxJ matrix with an JxK matrix.\n    //      The result is an IxK matrix.\n    //      Since this function multiplies in-place (i.e. it implements leftInOut *= right ),\n    //      the resulting matrix must be of size IxJ.\n    //      The only way this is possible is if K = J;\n    //      in other words, the given matrix must be a square JxJ matrix.\n    template< typename T, size_t R, size_t C >\n    void MatrixMultiplyInPlace( Matrix< T, R, C >& leftInOut, const Matrix< T, C, C >& right ) {\n        T oldRow[ C - 1 ];\n        T dot;\n        for( size_t r = 0; r < R; ++r ) {\n            //Store the old values for the current row we're working on\n            //We only need to store the first C-1 values, because we need to know\n            //their old values when setting their new values for all but the last\n            //element in the current row\n            for( size_t c = 0; c < C - 1; ++c )\n                oldRow[c] = leftInOut.elem[r][c];\n\n            //Update the values\n            for( size_t c = 0; c < C; ++c ) {\n                dot = static_cast< T >( 0 );\n\n                //Partially calculate the dot product between the current row in the left matrix,\n                //and the current column in the right matrix.\n                for( size_t c2 = 0; c2 < C - 1; ++c2 )\n                    dot += oldRow[ c2 ] * right.elem[c2][c];\n\n                //Finalize the dot product and update the element in the left matrix.\n                leftInOut.elem[r][c] = dot +\n                                       leftInOut.elem[r][C-1] * right.elem[C-1][c];\n            }\n        }\n    }\n}\n\ntemplate< typename T, size_t R, size_t C >\nMatrix< T, R, C >& Matrix< T, R, C >::operator *=( const Matrix< T, C, C >& right ) {\n    Private::MatrixMultiplyInPlace( *this, right );\n    return ( *this );\n}\n\ntemplate< typename T, size_t R, size_t C >\nMatrix< T, R, C >& Matrix< T, R, C >::operator +=( const T right ) {\n    for( size_t i = 0; i < R * C; ++i )\n        data[i] += right;\n\n    return ( *this );\n}\n\ntemplate< typename T, size_t R, size_t C >\nMatrix< T, R, C >& Matrix< T, R, C >::operator -=( const T right ) {\n    for( size_t i = 0; i < R * C; ++i )\n        data[i] -= right;\n\n    return ( *this );\n}\n\ntemplate< typename T, size_t R, size_t C >\nMatrix< T, R, C >& Matrix< T, R, C >::operator *=( const T right ) {\n    for( size_t i = 0; i < R * C; ++i )\n        data[i] *= right;\n\n    return ( *this );\n}\n\ntemplate< typename T, size_t R, size_t C >\nMatrix< T, R, C >& Matrix< T, R, C >::operator /=( const T right ) {\n    BS_ASSERT_NONZERO_DIVISOR( right )\n\n    for( size_t i = 0; i < R * C; ++i )\n        data[i] /= right;\n\n    return ( *this );\n}\n\ntemplate< typename T, size_t R, size_t C >\nstd::ostream& operator <<( std::ostream& left, const Matrix< T, R, C >& right ) {\n    size_t maxWidth = 1;\n    std::string str[ R * C ];\n    for( size_t i = 0; i < R * C; ++i ) {\n        str[ i ] = ( boost::format( \"%|.5f|\" ) % right.data[i] ).str();\n        electMax( maxWidth, str[ i ].size() );\n    }\n\n    for( size_t r = 0; r < R; ++r ) {\n        left << std::setw( maxWidth ) << str[r*C];\n        for( size_t c = 1; c < C; ++c )\n            left << \" \" << std::setw( maxWidth ) << str[r*C + c];\n        left << std::endl;\n    }\n    return left;\n}\n\ntemplate< typename T, size_t R, size_t C >\nbool operator ==( const Matrix< T, R, C >& left, const Matrix< T, R, C >& right ) {\n    for( size_t i = 0; i < R * C; ++i )\n        if( left.data[i] != right.data[i] )\n            return false;\n    return true;\n}\n\ntemplate< typename T, size_t R, size_t C >\nbool operator !=( const Matrix< T, R, C >& left, const Matrix< T, R, C >& right ) {\n    for( size_t i = 0; i < R * C; ++i )\n        if( left.data[i] != right.data[i] )\n            return true;\n    return false;\n}\n\ntemplate< typename T, size_t R, size_t C >\nMatrix< T, R, C > operator +( const Matrix< T, R, C >& right ) {\n    return right;\n}\n\ntemplate< typename T, size_t R, size_t C >\nMatrix< T, R, C > operator -( const Matrix< T, R, C >& right ) {\n    Matrix< T, R, C > out;\n\n    for( size_t i = 0; i < R * C; ++i )\n        out.data[i] = -right.data[i];\n\n    return out;\n}\n\ntemplate< typename T, size_t R, size_t C >\nMatrix< T, R, C > operator +( const Matrix< T, R, C >& left, const Matrix< T, R, C >& right ) {\n    Matrix< T, R, C > out;\n\n    for( size_t i = 0; i < R * C; ++i )\n        out.data[i] = left.data[i] + right.data[i];\n\n    return out;\n}\n\ntemplate< typename T, size_t R, size_t C >\nMatrix< T, R, C > operator -( const Matrix< T, R, C >& left, const Matrix< T, R, C >& right ) {\n    Matrix< T, R, C > out;\n\n    for( size_t i = 0; i < R * C; ++i )\n        out.data[i] = left.data[i] - right.data[i];\n\n    return out;\n}\n\ntemplate< typename T, size_t R, size_t C, size_t C2 >\nMatrix< T, R, C2 > operator *( const Matrix< T, R, C >& left, const Matrix< T, C, C2 >& right ) {\n    Matrix< T, R, C2 > out;\n\n    T dot;\n    for( size_t r = 0; r < R; ++r ) {\n        for( size_t c2 = 0; c2 < C2; ++c2 ) {\n            dot = static_cast< T >( 0 );\n\n            for( size_t c = 0; c < C; ++c )\n                dot += left.elem[r][c] * right.elem[c][c2];\n\n            out.elem[r][c2] = dot;\n        }\n    }\n\n    return out;\n}\n\n//R-vector (as a 1xR matrix) * RxC matrix = C-vector (as a 1xC matrix)\ntemplate< typename T, size_t R, size_t C >\nVector< T, C > operator *( const Vector< T, R >& left, const Matrix< T, R, C >& right ) {\n    Vector< T, C > out;\n\n    T dot;\n    for( size_t c = 0; c < C; ++c ) {\n        dot = static_cast< T >( 0 );\n\n        for( size_t r = 0; r < R; ++r )\n            dot += left[r] * right.elem[r][c];\n\n        out.data[c] = dot;\n    }\n\n    return out;\n}\n\n//RxC matrix * C-vector (as a Cx1 matrix) = R-vector (as a Rx1 matrix)\ntemplate< typename T, size_t R, size_t C >\nVector< T, R > operator *( const Matrix< T, R, C >& left, const Vector< T, C >& right ) {\n    Vector< T, R > out;\n\n    T dot;\n    for( size_t r = 0; r < R; ++r ) {\n        dot = static_cast< T >( 0 );\n\n        for( size_t c = 0; c < C; ++c )\n            dot += left.elem[r][c] * right[c];\n\n        out.data[r] = dot;\n    }\n\n    return out;\n}\n\ntemplate< typename T, size_t R, size_t C >\nMatrix< T, R, C > operator +( const T left, const Matrix< T, R, C >& right ) {\n    Matrix< T, R, C > out;\n\n    for( size_t i = 0; i < R * C; ++i )\n        out.data[i] = left + right.data[i];\n\n    return out;\n}\n\ntemplate< typename T, size_t R, size_t C >\nMatrix< T, R, C > operator +( const Matrix< T, R, C >& left, const T right ) {\n    Matrix< T, R, C > out;\n\n    for( size_t i = 0; i < R * C; ++i )\n        out.data[i] = left.data[i] + right;\n\n    return out;\n}\n\ntemplate< typename T, size_t R, size_t C >\nMatrix< T, R, C > operator -( const Matrix< T, R, C >& left, const T right ) {\n    Matrix< T, R, C > out;\n\n    for( size_t i = 0; i < R * C; ++i )\n        out.data[i] = left.data[i] - right;\n\n    return out;\n}\n\ntemplate< typename T, size_t R, size_t C >\nMatrix< T, R, C > operator *( const T left, const Matrix< T, R, C >& right ) {\n    Matrix< T, R, C > out;\n\n    for( size_t i = 0; i < R * C; ++i )\n        out.data[i] = left * right.data[i];\n\n    return out;\n}\n\ntemplate< typename T, size_t R, size_t C >\nMatrix< T, R, C > operator *( const Matrix< T, R, C >& left, const T right ) {\n    Matrix< T, R, C > out;\n\n    for( size_t i = 0; i < R * C; ++i )\n        out.data[i] = left.data[i] * right;\n\n    return out;\n}\n\ntemplate< typename T, size_t R, size_t C >\nMatrix< T, R, C > operator /( const Matrix< T, R, C >& left, const T right ) {\n    BS_ASSERT_NONZERO_DIVISOR( right );\n\n    Matrix< T, R, C > out;\n\n    for( size_t i = 0; i < R * C; ++i )\n        out.data[i] = left.data[i] / right;\n\n    return out;\n}\n\ntemplate< typename T, size_t R, size_t C >\nMatrix< T, C, R > transpose( const Matrix< T, R, C >& matrix ) {\n    Matrix< T, C, R > out;\n\n    for( size_t r = 0; r < R; ++r )\n        for( size_t c = 0; c < C; ++c )\n            out.elem[c][r] = matrix.elem[r][c];\n\n    return out;\n}\n\n}\n\n\n\n\n#endif //BS_MATRIX_MATRIXRXC_HPP", "meta": {"hexsha": "ebaf0f01b5f55081f22d100a47697b33dbe44137", "size": 18678, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/brimstone/matrix/MatrixRxC.hpp", "max_stars_repo_name": "theJ8910/Brimstone", "max_stars_repo_head_hexsha": "e28da7a995ab5533b78bf5e1664a59753d139fff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-12-31T05:49:39.000Z", "max_stars_repo_stars_event_max_datetime": "2015-12-31T05:49:39.000Z", "max_issues_repo_path": "include/brimstone/matrix/MatrixRxC.hpp", "max_issues_repo_name": "theJ8910/Brimstone", "max_issues_repo_head_hexsha": "e28da7a995ab5533b78bf5e1664a59753d139fff", "max_issues_repo_licenses": ["MIT"], "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/brimstone/matrix/MatrixRxC.hpp", "max_forks_repo_name": "theJ8910/Brimstone", "max_forks_repo_head_hexsha": "e28da7a995ab5533b78bf5e1664a59753d139fff", "max_forks_repo_licenses": ["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.9775280899, "max_line_length": 128, "alphanum_fraction": 0.4834564729, "num_tokens": 4913, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544085240401, "lm_q2_score": 0.7090191337850933, "lm_q1q2_score": 0.49578475502712266}}
{"text": "#include \"select_brir.hpp\"\n\n#include <Eigen/Geometry>\n#include <boost/math/constants/constants.hpp>\n\n#include \"utils.hpp\"\n\nnamespace bear {\nSelectBRIR::SelectBRIR(const SignalFlowContext &ctx,\n                       const char *name,\n                       CompositeComponent *parent,\n                       const ConfigImpl &config,\n                       std::shared_ptr<Panner> panner_)\n    : AtomicComponent(ctx, name, parent),\n      panner(std::move(panner_)),\n      views(panner->get_views()),\n      listener_in(\"listener_in\", *this, pml::EmptyParameterConfig()),\n      brir_index_out(\"brir_index_out\", *this, pml::EmptyParameterConfig()),\n      listener_out(\"listener_out\", *this, pml::EmptyParameterConfig())\n{\n  views.rowwise().normalize();\n\n  for (const auto &view : views.rowwise()) {\n    // calculate a rotation from the view vector, assuming it's a rotation around z\n    bear_assert(std::abs(view.z()) < 1e-6, \"expected BRIR rotations around z only\");\n    double z = std::sin(-std::atan2(view.x(), view.y()) / 2.0);\n    double w = std::sqrt(1.0 - z * z);\n    Eigen::Quaterniond rot(w, 0.0, 0.0, z);\n\n    view_rotations.push_back(rot);\n  }\n}\n\nvoid SelectBRIR::process()\n{\n  if (listener_in.changed()) {\n    Eigen::Vector3d look_vector = listener_in.data().look();\n\n    // find the closest BRIR view, by maximum dot-product\n    unsigned int max_dp_idx;\n    (views * look_vector).maxCoeff(&max_dp_idx);\n\n    brir_index_out.data() = max_dp_idx;\n    brir_index_out.swapBuffers();\n\n    // calculate the 'residual' listener with the BRIR rotation removed\n    Eigen::Vector3d front{0.0, 1.0, 0.0};\n    Eigen::Quaterniond brir_rot = Eigen::Quaterniond::FromTwoVectors(front, views.row(max_dp_idx));\n    listener_out.data().position = listener_in.data().position;\n    listener_out.data().orientation = view_rotations[max_dp_idx] * listener_in.data().orientation;\n    listener_out.swapBuffers();\n\n    listener_in.resetChanged();\n  }\n}\n}  // namespace bear\n", "meta": {"hexsha": "48126991da288c05156ef1bf967b0d99ba5cebed", "size": 1958, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "visr_bear/src/select_brir.cpp", "max_stars_repo_name": "ebu/bear", "max_stars_repo_head_hexsha": "0e4c4f33dfaea9b7c64991515177eb2099887a5a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2022-02-01T16:28:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T11:24:59.000Z", "max_issues_repo_path": "visr_bear/src/select_brir.cpp", "max_issues_repo_name": "ebu/bear", "max_issues_repo_head_hexsha": "0e4c4f33dfaea9b7c64991515177eb2099887a5a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-03-03T06:49:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-15T13:10:43.000Z", "max_forks_repo_path": "visr_bear/src/select_brir.cpp", "max_forks_repo_name": "ebu/bear", "max_forks_repo_head_hexsha": "0e4c4f33dfaea9b7c64991515177eb2099887a5a", "max_forks_repo_licenses": ["Apache-2.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.350877193, "max_line_length": 99, "alphanum_fraction": 0.6634320735, "num_tokens": 497, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.63341027059799, "lm_q1q2_score": 0.49574645258047384}}
{"text": "#include \"test-results.hpp\"\n#include <boost/range/irange.hpp>\n#include <cmath>\n#include <spdlog/fmt/fmt.h>\n#include <spdlog/spdlog.h>\n\n#define VALUES_RANGE irange(0, 10000, 1)\n\nfloat errorPForErrorInt(int e) { return (e / 1000000.0) * 20; }\n\nTestResults::TestResults(std::string protocolName)\n    : m_protocolName(protocolName) {}\nTestResults::~TestResults() {}\nvoid TestResults::addResult(int errorPropability, int trips,\n                            bool successfulTransmission,\n                            bool correctDiagnosis) {\n  m_results[errorPropability].trips(trips);\n  m_results[errorPropability].successfulTransmissions(\n      successfulTransmission ? 1 : 0);\n  m_results[errorPropability].correctDiagnosis(correctDiagnosis ? 1 : 0);\n}\n\nvoid TestResults::writeResults(std::ofstream &out) {\n  using namespace fmt;\n  using namespace boost;\n  using namespace boost::accumulators;\n\n  out << fmt::format(\n      \"p\\ttrips_min\\ttrips_max\\ttrips_mean\\ttrips_med\\ttrips_sd\\tsucc_mean\\t\"\n      \"succ_med\\tdiag_mean\\tdiag_med\\n\");\n  for (auto errorProp : VALUES_RANGE) {\n    auto &res = m_results[errorProp];\n    out << fmt::format(\n        \"{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\n\",\n        errorPForErrorInt(errorProp), min(res.trips), max(res.trips),\n        mean(res.trips), median(res.trips), sqrt(variance(res.trips)),\n        mean(res.successfulTransmissions), median(res.successfulTransmissions),\n        mean(res.correctDiagnosis), median(res.correctDiagnosis));\n  }\n}\n\nstd::string_view TestResults::name() { return m_protocolName; }\n\nstd::unique_ptr<TestResults>\nTestResults::startAutomatedTest(protocol::Protocol &protocol) {\n  std::unique_ptr<TestResults> results =\n      std::make_unique<TestResults>(protocol.name());\n\n  using namespace boost;\n\n  // Simulate 1 minute at 120 messages per second.\n  const int messageCount = 7200;\n  const std::size_t messageSize =\n      4; // Message size (in bytes) should be 4. This represents a single\n         // integer of data to be transmitted.\n\n  protocol.setMessageSize(messageSize);\n\n  protocol::Protocol::Message msg[2];\n\n  for (auto errorProp : VALUES_RANGE) {\n    float p = errorPForErrorInt(errorProp);\n    protocol.setErrorPropability(p);\n\n    if (errorProp % 100 == 0) {\n      spdlog::info(\"Currently at p={} for protocol \\\"{}\\\"\", p, results->name());\n    }\n\n    for (auto _msgNumber : irange(0, messageCount)) {\n      int trips = protocol.startTransfer(msg[0], msg[1]);\n      results->addResult(errorProp, trips,\n                         protocol.lastTransmissionSuccessful(),\n                         protocol.lastDiagnosisCorrect());\n    }\n  }\n\n  return results;\n}\n", "meta": {"hexsha": "8b8cdc71c48467dae1afbe0f491c6584e26d59fa", "size": 2631, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "testbench/test-results.cpp", "max_stars_repo_name": "maximaximal/protocol-testbench", "max_stars_repo_head_hexsha": "4684fa9b24345ca1f9c8d15f9a7537fe3da2548e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "testbench/test-results.cpp", "max_issues_repo_name": "maximaximal/protocol-testbench", "max_issues_repo_head_hexsha": "4684fa9b24345ca1f9c8d15f9a7537fe3da2548e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "testbench/test-results.cpp", "max_forks_repo_name": "maximaximal/protocol-testbench", "max_forks_repo_head_hexsha": "4684fa9b24345ca1f9c8d15f9a7537fe3da2548e", "max_forks_repo_licenses": ["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.3037974684, "max_line_length": 80, "alphanum_fraction": 0.6757886735, "num_tokens": 666, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.63341027059799, "lm_q1q2_score": 0.4957464461584127}}
{"text": "/* Copyright 2020 CNRS-AIST JRL */\n\n#include <Eigen/Cholesky>\n#include <Eigen/Core>\n#include <Eigen/QR>\n\n#include <benchmark/benchmark.h>\n\n#include \"common.h\"\n\nusing namespace Eigen;\n\n// A = B\nstatic void BM_Copy_MatrixXd(benchmark::State & state)\n{\n  MatrixXd source = MatrixXd::Random(state.range(0), state.range(0));\n  MatrixXd target(state.range(0), state.range(0));\n\n  for(auto _ : state) target = source;\n}\nMAT_BENCHMARK(BM_Copy_MatrixXd);\n\n// C = A*B\nstatic void BM_Mult_MatrixXd(benchmark::State & state)\n{\n  MatrixXd A = MatrixXd::Random(state.range(0), state.range(0));\n  MatrixXd B = MatrixXd::Random(state.range(0), state.range(0));\n  MatrixXd target(state.range(0), state.range(0));\n\n  for(auto _ : state) target.noalias() = A * B;\n}\nMAT_BENCHMARK(BM_Mult_MatrixXd);\n\n// LLT of A\nstatic void BM_LLT_Decomposition(benchmark::State & state)\n{\n  MatrixXd R = MatrixXd::Random(state.range(0), state.range(0));\n  MatrixXd A = R.transpose() * R;\n  LLT<MatrixXd> llt(state.range(0));\n  for(auto _ : state)\n  {\n    llt.compute(A);\n  }\n}\nMAT_BENCHMARK(BM_LLT_Decomposition);\n\n// QR of A\nstatic void BM_QR_Decomposition(benchmark::State & state)\n{\n  MatrixXd A = MatrixXd::Random(state.range(0), state.range(0));\n  HouseholderQR<MatrixXd> qr(state.range(0), state.range(0));\n  for(auto _ : state)\n  {\n    qr.compute(A);\n  }\n}\nMAT_BENCHMARK(BM_QR_Decomposition);\n\n// QR of A\nstatic void BM_QR_Decomposition_Inplace(benchmark::State & state)\n{\n  MatrixXd A = MatrixXd::Random(state.range(0), state.range(0));\n  HouseholderQR<Ref<MatrixXd>> qr(A);\n  for(auto _ : state)\n  {\n    qr.compute(A);\n  }\n}\nMAT_BENCHMARK(BM_QR_Decomposition_Inplace);\n\n// Col piv QR of A\nstatic void BM_ColPivQR_Decomposition(benchmark::State & state)\n{\n  MatrixXd A = MatrixXd::Random(state.range(0), state.range(0));\n  ColPivHouseholderQR<MatrixXd> qr(state.range(0), state.range(0));\n  for(auto _ : state)\n  {\n    qr.compute(A);\n  }\n}\nMAT_BENCHMARK(BM_ColPivQR_Decomposition);\n\n// Col piv QR of A in place\nstatic void BM_ColPivQR_Decomposition_Inplace(benchmark::State & state)\n{\n  MatrixXd A = MatrixXd::Random(state.range(0), state.range(0));\n  ColPivHouseholderQR<Ref<MatrixXd>> qr(A);\n  for(auto _ : state)\n  {\n    qr.compute(A);\n  }\n}\nMAT_BENCHMARK(BM_ColPivQR_Decomposition_Inplace);\n\n// Col piv QR of A^T\nstatic void BM_ColPivQR_Decomposition_Transpose(benchmark::State & state)\n{\n  MatrixXd A = MatrixXd::Random(state.range(0), state.range(0));\n  ColPivHouseholderQR<MatrixXd> qr(state.range(0), state.range(0));\n  for(auto _ : state)\n  {\n    qr.compute(A.transpose());\n  }\n}\nMAT_BENCHMARK(BM_ColPivQR_Decomposition_Transpose);\n\nBENCHMARK_MAIN();\n", "meta": {"hexsha": "6a5b1b123c0360db13efa263767782bb7bdcfa76", "size": 2633, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "benchmarks/Decomposition.cpp", "max_stars_repo_name": "mehdi-benallegue/jrl-qp", "max_stars_repo_head_hexsha": "b6d2268dcd1e91708585474b3f0f93c9104887c0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2020-08-20T09:06:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T03:42:58.000Z", "max_issues_repo_path": "benchmarks/Decomposition.cpp", "max_issues_repo_name": "mehdi-benallegue/jrl-qp", "max_issues_repo_head_hexsha": "b6d2268dcd1e91708585474b3f0f93c9104887c0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-11-21T10:29:57.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-21T11:13:41.000Z", "max_forks_repo_path": "benchmarks/Decomposition.cpp", "max_forks_repo_name": "mehdi-benallegue/jrl-qp", "max_forks_repo_head_hexsha": "b6d2268dcd1e91708585474b3f0f93c9104887c0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-09-04T12:11:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-04T12:11:44.000Z", "avg_line_length": 24.3796296296, "max_line_length": 73, "alphanum_fraction": 0.7071781238, "num_tokens": 786, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.4957464363320486}}
{"text": "#include <boost/gil/image_processing/numeric.hpp>\n#include <boost/gil/detail/math.hpp>\n#include <boost/core/lightweight_test.hpp>\n\n#include <algorithm>\n\nnamespace gil = boost::gil;\n\nvoid test_dx_sobel_kernel()\n{\n    const auto kernel = gil::generate_dx_sobel(1);\n    BOOST_TEST(std::equal(kernel.begin(), kernel.end(), gil::dx_sobel.begin()));\n}\n\nvoid test_dx_scharr_kernel()\n{\n    const auto kernel = gil::generate_dx_scharr(1);\n    BOOST_TEST(std::equal(kernel.begin(), kernel.end(), gil::dx_scharr.begin()));\n}\n\nvoid test_dy_sobel_kernel()\n{\n    const auto kernel = gil::generate_dy_sobel(1);\n    BOOST_TEST(std::equal(kernel.begin(), kernel.end(), gil::dy_sobel.begin()));\n}\n\nvoid test_dy_scharr_kernel()\n{\n    const auto kernel = gil::generate_dy_scharr(1);\n    BOOST_TEST(std::equal(kernel.begin(), kernel.end(), gil::dy_scharr.begin()));\n}\n\nint main()\n{\n    test_dx_sobel_kernel();\n    test_dx_scharr_kernel();\n    test_dy_sobel_kernel();\n    test_dy_scharr_kernel();\n    return boost::report_errors();\n}\n", "meta": {"hexsha": "50ecf3c78f6dd34192ac5c2ee233496f5327eb3a", "size": 1012, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/gil/test/core/image_processing/sobel_scharr.cpp", "max_stars_repo_name": "btzy/boost-1.72.0-mirror", "max_stars_repo_head_hexsha": "defad0f34b0abc884032b57dd4eb93f18f679bf1", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-01T03:04:05.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-01T03:04:05.000Z", "max_issues_repo_path": "libs/gil/test/core/image_processing/sobel_scharr.cpp", "max_issues_repo_name": "btzy/boost-1.72.0-mirror", "max_issues_repo_head_hexsha": "defad0f34b0abc884032b57dd4eb93f18f679bf1", "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/gil/test/core/image_processing/sobel_scharr.cpp", "max_forks_repo_name": "btzy/boost-1.72.0-mirror", "max_forks_repo_head_hexsha": "defad0f34b0abc884032b57dd4eb93f18f679bf1", "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.6829268293, "max_line_length": 81, "alphanum_fraction": 0.7065217391, "num_tokens": 265, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.4957464299099877}}
{"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 sigma_point_additive_prediction_policy.hpp\n * \\date July 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/traits.hpp>\n#include <fl/util/descriptor.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 SigmaPointPredictPolicy;\n\ntemplate <\n    typename SigmaPointQuadrature,\n    typename AdditiveTransitionFunction\n>\nclass SigmaPointPredictPolicy<\n          SigmaPointQuadrature,\n          Additive<AdditiveTransitionFunction>>\n    : public Descriptor\n{\npublic:\n    typedef typename AdditiveTransitionFunction::State State;\n    typedef typename AdditiveTransitionFunction::Input Input;\n\n    enum : signed int\n    {\n        NumberOfPoints = SigmaPointQuadrature\n                            ::number_of_points(SizeOf<State>::Value)\n    };\n\n    typedef PointSet<State, NumberOfPoints> StatePointSet;\n\n    template <\n        typename Belief\n    >\n    void operator()(const AdditiveTransitionFunction&\n                              additive_transition_function,\n                    const SigmaPointQuadrature& quadrature,\n                    const Belief& prior_belief,\n                    const Input& u,\n                    Belief& predicted_belief)\n    {\n        auto f = [&](const State& x)\n        {\n            return additive_transition_function.expected_state(x, u);\n        };\n\n        quadrature.propergate_gaussian(f, prior_belief, Y, Z);\n\n        /*\n         * Obtain the centered points matrix of the prediction. The columns of\n         * this matrix are the predicted points with zero mean. That is, the\n         * sum of the columns in P is zero.\n         *\n         * P = [X_r[1]-mu_r  X_r[2]-mu_r  ... X_r[n]-mu_r]\n         *\n         * with weighted mean\n         *\n         * mu_r = Sum w_mean[i] X_r[i]\n         */\n        auto X_c = Z.centered_points();\n\n        /*\n         * Obtain the weights of point as a vector\n         *\n         * W = [w_cov[1]  w_cov[2]  ... w_cov[n]]\n         *\n         * Note that the covariance weights are used.\n         */\n        auto W = Z.covariance_weights_vector();\n\n        /*\n         * Compute and set the moments\n         *\n         * The first moment is simply the weighted mean of points.\n         * The second centered moment is determined by\n         *\n         * C = Sum W[i,i] * (X_r[i]-mu_r)(X_r[i]-mu_r)^T\n         *   = P * W * P^T\n         *\n         * given that W is the diagonal matrix\n         */\n        predicted_belief.dimension(prior_belief.dimension());\n        predicted_belief.mean(Z.mean());\n        predicted_belief.covariance(\n            X_c * W.asDiagonal() * X_c.transpose()\n            + additive_transition_function.noise_covariance());\n    }\n\n    virtual std::string name() const\n    {\n        return \"SigmaPointPredictPolicy<\"\n                + this->list_arguments(\n                       \"SigmaPointQuadrature\",\n                       \"Additive<AdditiveTransitionFunction>\")\n                + \">\";\n    }\n\n    virtual std::string description() const\n    {\n        return \"Sigma Point based filter prediction policy for state \"\n               \"transition model with additive noise\";\n    }\n\nprotected:\n    StatePointSet Y;\n    StatePointSet Z;\n};\n\n}\n\n\n", "meta": {"hexsha": "930cdca38359b707e789773f8938f32174ea244e", "size": 3802, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/fl/filter/gaussian/prediction_policy/sigma_point_additive_prediction_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/prediction_policy/sigma_point_additive_prediction_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/prediction_policy/sigma_point_additive_prediction_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": 27.5507246377, "max_line_length": 79, "alphanum_fraction": 0.600999474, "num_tokens": 847, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.49574196899422485}}
{"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 <cmath>\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n#include <boost/program_options.hpp>\n#include <enoki/cuda.h>\n#include <enoki/dynamic.h>\n#include <enoki/autodiff.h>\n#include <enoki/special.h>\n#include <enoki/array_router.h>\n#include \"ifm/fft.h\"\n#include \"ifm/load_monoral.h\"\n#include \"ifm/spectrum_image.h\"\n\nusing i_t = enoki::DiffArray< enoki::CUDAArray< int > >;\nusing v_t = enoki::DiffArray< enoki::CUDAArray< float > >;\n\n\nfloat j1( float b, int n ) {\n  float prev = 0;\n  float width = 0.001;\n  float sum = 0;\n  for( float w = width; w < float( M_PI/2 ); w += width ) {\n    float cur = std::sin( b * std::sin( w ) ) * std::sin( n*w );\n    sum += ( cur + prev ) * width / 2;\n    prev = cur;\n  }\n  return 2.f / M_PI * sum;\n}\n\nfloat j0( float b, int n ) {\n  float prev = 1;\n  float width = 0.001;\n  float sum = 0;\n  for( float w = width; w < float( M_PI/2 ); w += width ) {\n    float cur = std::cos( b * std::sin( w ) ) * std::cos( n*w );\n    sum += ( cur + prev ) * width / 2;\n    prev = cur;\n  }\n  return 2.f / M_PI * sum;\n}\n\nfloat j( float b, int n ) {\n  if( n % 2 ) return j1( b, n );\n  else return j0( b, n );\n}\n\n\n\n\nint main( int argc, char* argv[] ) {\n  boost::program_options::options_description options(\"\u30aa\u30d7\u30b7\u30e7\u30f3\");\n  options.add_options()\n    (\"help,h\",    \"\u30d8\u30eb\u30d7\u3092\u8868\u793a\")\n    (\"input,i\", boost::program_options::value<std::string>(),  \"\u5165\u529b\u30d5\u30a1\u30a4\u30eb\")\n    (\"note,n\", boost::program_options::value<int>()->default_value(60),  \"\u97f3\u968e\")\n    (\"harmonic,H\", boost::program_options::value<int>()->default_value(0),  \"\u500d\u97f3\u306e\u307f\")\n    (\"match,m\", boost::program_options::value<bool>()->default_value(false),  \"\u6e1b\u8870\u66f2\u7dda\u3092\u30de\u30c3\u30c1\u3055\u305b\u308b\")\n    (\"resolution,r\", boost::program_options::value<int>()->default_value(13),  \"\u5206\u89e3\u80fd\");\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\") || !params.count(\"input\") ) {\n    std::cout << options << std::endl;\n    return 0;\n  }\n  const std::string input_filename = params[\"input\"].as<std::string>();\n  const auto [audio,sample_rate] = ifm::load_monoral( input_filename, true );\n  ifm::spectrum_image conv( params[\"note\"].as<int>(), sample_rate, 1 << params[\"resolution\"].as<int>() );\n  auto [image,delay] = conv( audio );\n  unsigned int width = conv.get_width();\n  float resolution = 1 << params[\"resolution\"].as<int>();\n  std::vector< float > envelope;\n\n\n\n  if( params[\"harmonic\"].as<int>() > 0 ) {\n    for( unsigned int y = 0; y != image.size() / width; ++y ) {\n      float sum = 0.f;\n      for( unsigned int x = 1; x < width; x += 24 )\n        sum += image[ x + y * width ];\n      envelope.push_back( sum );\n    }\n  }\n  else if( params[\"harmonic\"].as<int>() < 0 ) {\n    for( unsigned int y = 0; y != image.size() / width; ++y ) {\n      float sum = 0.f;\n      for( unsigned int x = 25; x < width; ++x ) {\n        unsigned int step =  x % 24;\n        if( step > 1 && step < 23 )\n          sum += image[ x + y * width ];\n      }\n      envelope.push_back( sum );\n    }\n  }\n  else {\n    for( unsigned int y = 0; y != image.size() / width; ++y ) {\n      float sum = std::accumulate( image.data() + y * width, image.data() + ( y + 1 ) * width, 0.f );\n      envelope.push_back( sum );\n    }\n  }\n  if( params[\"match\"].as<bool>() ) {\n    using v_t = enoki::DiffArray< enoki::CUDAArray< float > >;\n    const auto max = std::max_element( envelope.begin(), envelope.end() );\n    envelope.erase( envelope.begin(), max );\n    const auto min = std::find_if( envelope.begin(), envelope.end(), []( float v ) { return v < 0.01f; } );\n    envelope.erase( min, envelope.end() );\n    if( params[\"harmonic\"].as<int>() < 0 )\n      envelope.resize( std::min( size_t( 50 ), envelope.size() ) );\n    auto expected = v_t::copy( envelope.data(), envelope.size() );\n    float a = 1;\n    float b = 10;\n    float c = 0.3;\n    v_t beta1_ = 0.9;\n    v_t beta2_ = 0.999;\n    v_t alpha = 0.001;\n    v_t beta1 = 0.9;\n    v_t beta2 = 0.999;\n    v_t a_( a );\n    v_t b_( b );\n    v_t c_( c );\n    v_t m_a( 0 );\n    v_t m_b( 0 );\n    v_t m_c( 0 );\n    v_t v_a( 0 );\n    v_t v_b( 0 );\n    v_t v_c( 0 );\n    auto t = enoki::arange< v_t >( envelope.size() ) * v_t( 0.01 );\n    for( int i = 1; i != 100000; ++i ) {\n      a_ = a;\n      b_ = b;\n      c_ = c;\n      enoki::set_requires_gradient( a_ );\n      enoki::set_requires_gradient( b_ );\n      enoki::set_requires_gradient( c_ );\n      auto generated = a_ * enoki::exp( -t * b_ ) + c_;\n      auto diff = ( expected - generated );\n      //auto loss = enoki::hsum( diff * diff );\n      //std::cout << loss << \" \";\n      enoki::backward( diff * diff );\n     \n      v_t g_a = gradient( a_ );\n      v_t g_b = gradient( b_ );\n      v_t g_c = gradient( c_ );\n      auto ms = beta1;//enoki::pow( beta1, i_ );\n      auto vs = beta2;//enoki::pow( beta2, i_ );\n      beta1 *= beta1_; \n      beta2 *= beta2_; \n      m_a = beta1 * m_a + ( 1 - beta1 ) * g_a;\n      v_a = beta2 * v_a + ( 1 - beta2 ) * g_a * g_a;\n      auto mhat_a = m_a / ( 1 - ms );\n      auto vhat_a = v_a / ( 1 - vs );\n      a_ -= ( alpha * mhat_a / ( enoki::sqrt( vhat_a ) + 0.000001f ) );\n      \n      m_b = beta1 * m_b + ( 1 - beta1 ) * g_b;\n      v_b = beta2 * v_b + ( 1 - beta2 ) * g_b * g_b;\n      auto mhat_b = m_b / ( 1 - ms );\n      auto vhat_b = v_b / ( 1 - vs );\n      b_ -= ( alpha * mhat_b / ( enoki::sqrt( vhat_b ) + 0.000001f ) );\n      \n      m_c = beta1 * m_c + ( 1 - beta1 ) * g_c;\n      v_c = beta2 * v_c + ( 1 - beta2 ) * g_c * g_c;\n      auto mhat_c = m_c / ( 1 - ms );\n      auto vhat_c = v_c / ( 1 - vs );\n      c_ -= ( alpha * mhat_c / ( enoki::sqrt( vhat_c ) + 0.000001f ) );\n      a = a_[ 0 ];\n      b = b_[ 0 ];\n      c = c_[ 0 ];\n      if( !( i % 100 ) )\n        std::cout << enoki::hsum( diff * diff ) << \" \" << a_ << \" \" << b_ << \" \" << c_ << std::endl;\n      enoki::cuda_eval( true );\n      enoki::cuda_sync();\n\n    }\n  }\n  else {\n    for( unsigned int y = 0; y != envelope.size(); ++y ) {\n      std::cout << 0.01f * y << \" \" << envelope[ y ] << std::endl;\n    }\n  }\n}\n\n", "meta": {"hexsha": "6f0208ebfbbbda915367a5cb9a0279ab078d4d77", "size": 7182, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/freq2fm.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/freq2fm.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/freq2fm.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": 34.6956521739, "max_line_length": 109, "alphanum_fraction": 0.5799220273, "num_tokens": 2284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256313782276, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.49574196432040585}}
{"text": "/******************************************************************************\n * \u53cd\u5c04\u885b\u661f\u7832\u306e\u5b9f\u8a08\u7b97\u95a2\u6570\u7fa4\n *****************************************************************************/\n\n#ifndef __SATELLITE_REFLECTOR_HPP__\n#define __SATELLITE_REFLECTOR_HPP__\n\n#include <vector>\n#include <Eigen/Core>\n#include \"mathematic_utils.hpp\"\n#include \"coodinate_system.hpp\"\nVector3dSet find_impact_point(\n    const Eigen::Vector3d& P0,\n    const Eigen::Vector3d& P1, const Eigen::Vector3d& N,\n    const Eigen::Vector3d& O,  const Eigen::Vector3d& R);\n\nbool find_impact(const geodetic& P, geodetic* X,\n                 const std::string& tle_str, const time_t* t);\n\n#endif // __SATELLITE_REFLETCTOR_HPP__\n\n", "meta": {"hexsha": "93ee58d8227d0039dff6487ec06bef8475e63881", "size": 685, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/satellite_reflector.hpp", "max_stars_repo_name": "earth2001y/satellite-reflector-beam-solver", "max_stars_repo_head_hexsha": "3dba42e67c48295fcdcbe631c5a1b8330e36b5a3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/satellite_reflector.hpp", "max_issues_repo_name": "earth2001y/satellite-reflector-beam-solver", "max_issues_repo_head_hexsha": "3dba42e67c48295fcdcbe631c5a1b8330e36b5a3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/satellite_reflector.hpp", "max_forks_repo_name": "earth2001y/satellite-reflector-beam-solver", "max_forks_repo_head_hexsha": "3dba42e67c48295fcdcbe631c5a1b8330e36b5a3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-21T01:31:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-21T01:31:31.000Z", "avg_line_length": 31.1363636364, "max_line_length": 79, "alphanum_fraction": 0.5664233577, "num_tokens": 175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8311430562234877, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.49572126801937133}}
{"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_ASEC_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_ASEC_HPP_INCLUDED\n\n#include <boost/simd/constant/constant.hpp>\n#include <boost/simd/constant/ratio.hpp>\n#include <boost/simd/constant/nan.hpp>\n#include <boost/simd/constant/pi.hpp>\n#include <boost/simd/constant/pio_2.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/constant/ratio.hpp>\n#include <boost/simd/function/abs.hpp>\n#include <boost/simd/function/acsc.hpp>\n#include <boost/simd/function/is_equal.hpp>\n#include <boost/simd/function/is_eqz.hpp>\n#include <boost/simd/function/is_ltz.hpp>\n#include <boost/simd/function/dec.hpp>\n#include <boost/simd/function/sqrt.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 ( asec_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_< bd::double_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() (A0 a0) const BOOST_NOEXCEPT\n    {\n      if (is_equal(a0, One<A0>())) return Zero<A0>();\n      return (Pio_2<A0>()-acsc(a0)) +  Constant<A0, 0x3c91a62633145c07ll>();\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( asec_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_< bd::single_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() (A0 a0) const BOOST_NOEXCEPT\n    {\n      A0 ax =  bs::abs(a0);\n      if (ax <  One<A0>()) return Nan<A0>();\n      A0 ax1 =  dec(ax);\n\n      if (ax1 < 0.001f)\n      {\n        A0 tmp = sqrt(Two<A0>()*ax1)\n          *oneminus(ax1*(Ratio<A0, 5, 12>()\n                         +ax1*(Ratio<A0, 43, 160>()\n                               -ax1*(Ratio<A0, 177, 896>()\n                                     +ax1*Ratio<A0, 2867, 18432>()\n                                    )\n                              )\n                        )\n                   );\n\n        return (is_ltz(a0)) ? Pi<A0>()-tmp : tmp;\n      }\n\n      if (is_equal(a0, One<A0>())) return Zero<A0>();\n      return  (Pio_2<A0>()-acsc(a0));\n    }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "ce58e12c2422071f3d6dcabbebea07b733c4f9d7", "size": 2676, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/scalar/function/asec.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/asec.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/asec.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.2409638554, "max_line_length": 100, "alphanum_fraction": 0.5160687593, "num_tokens": 667, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234877, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4957212680193712}}
{"text": "#pragma once\n\n#include<vector>\n#include <Eigen/Geometry>\n#include \"NeuralNetwork.h\"\n#include \"Sample.h\"\n#include <fstream>\n#include <iterator>\n\n\n\nusing namespace Eigen;\n\nnamespace simulator {\n\t\n\tvoid NeuralNetwork::SetHiddenLayers(int numberOfHiddenLayers, int hiddenLayersLength, int numberOfOutputNode) {\n\n\t\t_net.add_layer(new FullyConnected<Identity>(3, hiddenLayersLength));//3 in input because there are 3 independant rotation speeds\n\t\t\t\t\t\t\t\t\t\t\t\n\t\tfor (int i = 0; i < numberOfHiddenLayers; i++) {\n\t\t\t_net.add_layer(new FullyConnected<Sigmoid>(hiddenLayersLength, hiddenLayersLength));\n\t\t}\n\t\t_net.add_layer(new FullyConnected<Identity>(hiddenLayersLength, numberOfOutputNode));\n\t\t_net.set_output(new RegressionMSE());\n\t}\n\tvoid NeuralNetwork::SetLearningRate(double learningRate) {\n\t\t_opt.m_lrate = learningRate;\n\t}\n\tScalar operator \"\"_eng(long double d) {\n\t\t// Add a cast here if the compiler still complains\n\t\treturn d;\n\t}\n\tvoid NeuralNetwork::Train(Sample &sample, int batchSize, int epoch) {\n\t\tVerboseCallback callback;\n\t\t_net.set_callback(callback);\n\t\t_net.init(NORMALDISTRIBUTIONMEAN, STANDARDDIVIATION, RANDOMSEED);\n\t\tMatrixXd input = sample.GetRotSpeed();\n\t\tMatrixXd output = sample.GetEnergy();\n\t\t_net.fit(_opt, input, output, batchSize, epoch, RANDOMSEED);\n\t}\n\tvoid NeuralNetwork::Save(string fileName) {\n\t\tvector<vector<Scalar>> parameters = _net.get_parameters();\n\t\tofstream output_file(fileName);\n\t\tostream_iterator<Scalar> output_iterator(output_file, \" \");\n\t\tfor (const auto& row : parameters) {\n\t\t\tcopy(row.cbegin(), row.cend(), output_iterator);\n\t\t\toutput_file << endl;\n\t\t}\n\t}\n\tvoid NeuralNetwork::LoadParameters(string fileName) {\n\t\tvector<vector<Scalar>> parameters;\n\t\tifstream file(fileName);\n\t\tstring line;\n\t\twhile (getline(file, line)) {\n\t\t\tstringstream linestream(line);\n\t\t\tstring item;\n\t\t\tvector<Scalar> tempVec;\n\t\t\twhile (getline(linestream, item, ' ')) {\n\t\t\t\ttempVec.push_back(stold(item));\n\t\t\t}\n\t\t\tparameters.push_back(tempVec);\n\t\t}\n\t\t_net.init(NORMALDISTRIBUTIONMEAN, STANDARDDIVIATION, RANDOMSEED);\n\t\t_net.set_parameters(parameters);\n\t}\n\tMatrixXd NeuralNetwork::Predict(MatrixXd &input) {\n\t\tMatrixXd pred = _net.predict(input);\n\t\treturn pred;\n\t}\n\t\n\t\n\t\n}\n", "meta": {"hexsha": "abcc094b469e74063ab967471356025edebf3e63", "size": 2186, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SatteliteSimulator/Controller/NeuralNetwork.cpp", "max_stars_repo_name": "avlo2000/DronMovementManager", "max_stars_repo_head_hexsha": "23f73a0824165e26f18717a917aeacc63853dc8f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-06-24T14:09:14.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-24T14:09:16.000Z", "max_issues_repo_path": "SatteliteSimulator/Controller/NeuralNetwork.cpp", "max_issues_repo_name": "avlo2000/DronMovementManager", "max_issues_repo_head_hexsha": "23f73a0824165e26f18717a917aeacc63853dc8f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SatteliteSimulator/Controller/NeuralNetwork.cpp", "max_forks_repo_name": "avlo2000/DronMovementManager", "max_forks_repo_head_hexsha": "23f73a0824165e26f18717a917aeacc63853dc8f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-02-09T13:23:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-09T13:23:28.000Z", "avg_line_length": 29.5405405405, "max_line_length": 130, "alphanum_fraction": 0.7387923147, "num_tokens": 544, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583169, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.4957212630301062}}
{"text": "#pragma once\n\n#include <utility>\n#include <vector>\n#include <Eigen/Dense>\n#include \"../linear_solver.h\"\n\nclass SmoothBoundaries\n{\n    const Eigen::MatrixXi& F;\n    LDLTSolver solver;\n    std::vector< std::vector<int> > adj;\n    \npublic:\n    \n    typedef std::vector< std::pair<int, Eigen::Vector3d> > ImplicitBoundary;\n    \n    SmoothBoundaries(const Eigen::MatrixXi& Fin);\n\n    void initGeometry(const Eigen::MatrixXd& V);\n    \n    ImplicitBoundary smooth(const std::vector<int>& loop,\n                            const Eigen::MatrixXd& V, const Eigen::MatrixXi& F);\n    \n    void getCoordinates(const Eigen::MatrixXd& V, const ImplicitBoundary& boudary, Eigen::MatrixXd& out);\n};\n", "meta": {"hexsha": "fe0c668d565ca20dc9228ddce604a415dc13ee06", "size": 682, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "toolbox/garmentcreation/smooth_boundaries.hpp", "max_stars_repo_name": "katjawolff/custom_fit_garments", "max_stars_repo_head_hexsha": "1d6f9dcba612010bb5552201f39595f7b288b8d5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-08-15T09:28:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T10:19:09.000Z", "max_issues_repo_path": "toolbox/garmentcreation/smooth_boundaries.hpp", "max_issues_repo_name": "katjawolff/custom_fit_garments", "max_issues_repo_head_hexsha": "1d6f9dcba612010bb5552201f39595f7b288b8d5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-24T07:16:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-24T07:16:34.000Z", "max_forks_repo_path": "toolbox/garmentcreation/smooth_boundaries.hpp", "max_forks_repo_name": "katjawolff/custom_fit_garments", "max_forks_repo_head_hexsha": "1d6f9dcba612010bb5552201f39595f7b288b8d5", "max_forks_repo_licenses": ["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.2592592593, "max_line_length": 105, "alphanum_fraction": 0.6598240469, "num_tokens": 162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.49572125804084066}}
{"text": "///////////////////////////////////////////////////////////////////////////////\r\n// weighted_covariance.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_COVARIANCE_HPP_DE_01_01_2006\r\n#define BOOST_ACCUMULATORS_STATISTICS_WEIGHTED_COVARIANCE_HPP_DE_01_01_2006\r\n\r\n#include <vector>\r\n#include <limits>\r\n#include <numeric>\r\n#include <functional>\r\n#include <complex>\r\n#include <boost/mpl/assert.hpp>\r\n#include <boost/mpl/bool.hpp>\r\n#include <boost/range.hpp>\r\n#include <boost/parameter/keyword.hpp>\r\n#include <boost/mpl/placeholders.hpp>\r\n#include <boost/numeric/ublas/io.hpp>\r\n#include <boost/numeric/ublas/matrix.hpp>\r\n#include <boost/type_traits/is_scalar.hpp>\r\n#include <boost/type_traits/is_same.hpp>\r\n#include <boost/accumulators/framework/accumulator_base.hpp>\r\n#include <boost/accumulators/framework/extractor.hpp>\r\n#include <boost/accumulators/numeric/functional.hpp>\r\n#include <boost/accumulators/framework/parameters/sample.hpp>\r\n#include <boost/accumulators/statistics_fwd.hpp>\r\n#include <boost/accumulators/statistics/count.hpp>\r\n#include <boost/accumulators/statistics/covariance.hpp> // for numeric::outer_product() and type traits\r\n#include <boost/accumulators/statistics/weighted_mean.hpp>\r\n\r\nnamespace boost { namespace accumulators\r\n{\r\n\r\nnamespace impl\r\n{\r\n    ///////////////////////////////////////////////////////////////////////////////\r\n    // weighted_covariance_impl\r\n    //\r\n    /**\r\n        @brief Weighted Covariance Estimator\r\n\r\n        An iterative Monte Carlo estimator for the weighted covariance \\f$\\mathrm{Cov}(X,X')\\f$, where \\f$X\\f$ is a sample\r\n        and \\f$X'\\f$ a variate, is given by:\r\n\r\n        \\f[\r\n            \\hat{c}_n = \\frac{\\bar{w}_n-w_n}{\\bar{w}_n} \\hat{c}_{n-1} + \\frac{w_n}{\\bar{w}_n-w_n}(X_n - \\hat{\\mu}_n)(X_n' - \\hat{\\mu}_n'),\r\n            \\quad n\\ge2,\\quad\\hat{c}_1 = 0,\r\n        \\f]\r\n\r\n        \\f$\\hat{\\mu}_n\\f$ and \\f$\\hat{\\mu}_n'\\f$ being the weighted means of the samples and variates and\r\n        \\f$\\bar{w}_n\\f$ the sum of the \\f$n\\f$ first weights \\f$w_i\\f$.\r\n    */\r\n    template<typename Sample, typename Weight, typename VariateType, typename VariateTag>\r\n    struct weighted_covariance_impl\r\n      : accumulator_base\r\n    {\r\n        typedef typename numeric::functional::multiplies<Weight, typename numeric::functional::average<Sample, std::size_t>::result_type>::result_type weighted_sample_type;\r\n        typedef typename numeric::functional::multiplies<Weight, typename numeric::functional::average<VariateType, std::size_t>::result_type>::result_type weighted_variate_type;\r\n        // for boost::result_of\r\n        typedef typename numeric::functional::outer_product<weighted_sample_type, weighted_variate_type>::result_type result_type;\r\n\r\n        template<typename Args>\r\n        weighted_covariance_impl(Args const &args)\r\n          : cov_(\r\n                numeric::outer_product(\r\n                    numeric::average(args[sample | Sample()], (std::size_t)1)\r\n                      * numeric::one<Weight>::value\r\n                  , numeric::average(args[parameter::keyword<VariateTag>::get() | VariateType()], (std::size_t)1)\r\n                      * numeric::one<Weight>::value\r\n                )\r\n            )\r\n        {\r\n        }\r\n\r\n        template<typename Args>\r\n        void operator ()(Args const &args)\r\n        {\r\n            std::size_t cnt = count(args);\r\n\r\n            if (cnt > 1)\r\n            {\r\n                extractor<tag::weighted_mean_of_variates<VariateType, VariateTag> > const some_weighted_mean_of_variates = {};\r\n\r\n                this->cov_ = this->cov_ * (sum_of_weights(args) - args[weight]) / sum_of_weights(args)\r\n                           + numeric::outer_product(\r\n                                 some_weighted_mean_of_variates(args) - args[parameter::keyword<VariateTag>::get()]\r\n                               , weighted_mean(args) - args[sample]\r\n                             ) * args[weight] / (sum_of_weights(args) - args[weight]);\r\n            }\r\n        }\r\n\r\n        result_type result(dont_care) const\r\n        {\r\n            return this->cov_;\r\n        }\r\n\r\n    private:\r\n        result_type cov_;\r\n    };\r\n\r\n} // namespace impl\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// tag::weighted_covariance\r\n//\r\nnamespace tag\r\n{\r\n    template<typename VariateType, typename VariateTag>\r\n    struct weighted_covariance\r\n      : depends_on<count, sum_of_weights, weighted_mean, weighted_mean_of_variates<VariateType, VariateTag> >\r\n    {\r\n        typedef accumulators::impl::weighted_covariance_impl<mpl::_1, mpl::_2, VariateType, VariateTag> impl;\r\n    };\r\n}\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// extract::weighted_covariance\r\n//\r\nnamespace extract\r\n{\r\n    extractor<tag::abstract_covariance> const weighted_covariance = {};\r\n\r\n    BOOST_ACCUMULATORS_IGNORE_GLOBAL(weighted_covariance)\r\n}\r\n\r\nusing extract::weighted_covariance;\r\n\r\n}} // namespace boost::accumulators\r\n\r\n#endif\r\n", "meta": {"hexsha": "fdb87c70de292f66d34d1e3017c3e25b30f189fb", "size": 5195, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "master/core/third/boost/accumulators/statistics/weighted_covariance.hpp", "max_stars_repo_name": "importlib/klib", "max_stars_repo_head_hexsha": "a59837857689d0e60d3df6d2ebd12c3160efa794", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 460.0, "max_stars_repo_stars_event_min_datetime": "2016-01-13T12:49:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-20T04:10:40.000Z", "max_issues_repo_path": "master/core/third/boost/accumulators/statistics/weighted_covariance.hpp", "max_issues_repo_name": "isuhao/klib", "max_issues_repo_head_hexsha": "a59837857689d0e60d3df6d2ebd12c3160efa794", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 197.0, "max_issues_repo_issues_event_min_datetime": "2017-07-06T16:53:59.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-31T17:57:51.000Z", "max_forks_repo_path": "master/core/third/boost/accumulators/statistics/weighted_covariance.hpp", "max_forks_repo_name": "isuhao/klib", "max_forks_repo_head_hexsha": "a59837857689d0e60d3df6d2ebd12c3160efa794", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 148.0, "max_forks_repo_forks_event_min_datetime": "2016-01-17T03:16:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T12:20:36.000Z", "avg_line_length": 38.7686567164, "max_line_length": 179, "alphanum_fraction": 0.6090471607, "num_tokens": 1167, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.49572125804084066}}
{"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//// Incompressible module (body solver)\n// Compute sources on the body surface from the updated  impermeability B.C. and solve for doublets on the body surface\n//\n// Ref: Katz & Plotkin (2001), Low-Speed Aerodynamics\n// 1) tau = - (U_inf + Usigma) \\cdot n\n// 2) mu = A \\ (B * tau)\n//\n// I/O:\n// - vInf: freestream velocity vector\n// - RHS: right-hand side of the linear system of equations\n// - vSigma: field source induced body velocity\n// - bPan: (network of) body panels (structure)\n// - b2bAIC: body to body AIC (structure)\n\n#include <iostream>\n#include <Eigen/Dense>\n#include \"solve_body.h\"\n\nusing namespace std;\nusing namespace Eigen;\n\nvoid solve_body(Vector3d &vInf, VectorXd &RHS, MatrixX3d &vSigma, Network &bPan, Body_AIC &b2bAIC) {\n\n    //// Begin\n    cout << \"Computing surface singularities... \" << flush;\n\n    //// Update B.C.\n    // BC: tau_i = n_i * V_inf + n_i * V_sigma\n    for (int i = 0; i < bPan.nP; ++i)\n        bPan.tau(i) = - bPan.n.row(i).dot(vInf.transpose()) - bPan.n.row(i).dot(vSigma.row(i));\n\n    //// Solve\n    // Compute RHS\n    RHS = - b2bAIC.B * bPan.tau;\n    // Solve: A*mu + B*sigma = 0 (Dirichlet: interior potential = 0)\n    #ifdef ON_UNIX\n        bPan.mu = b2bAIC.A.householderQr().solve(RHS);\n    #else\n        bPan.mu = b2bAIC.A.fullPivLu().solve(RHS);\n    #endif\n\n    //// Control display\n    cout << \"Done!\" << endl;\n    cout << \"Surface sources strength: \" << bPan.tau.norm() << endl;\n    #ifdef VERBOSE\n        cout << \"Sources min. value: \" << bPan.tau.minCoeff() << endl;\n        cout << \"Sources max. value: \" << bPan.tau.maxCoeff() << endl;\n        for (int i = 0; i < bPan.nP; ++i)\n            cout << i << ' ' << bPan.tau(i) << endl;\n    #endif\n    cout << \"Surface doublets strength: \" << bPan.mu.norm() << endl;\n    #ifdef VERBOSE\n        cout << \"Doublets min. value: \" << bPan.mu.minCoeff() << endl;\n        cout << \"Doublets max. value: \" << bPan.mu.maxCoeff() << endl;\n        for (int i = 0; i < bPan.nP; ++i)\n            cout << i << ' ' << bPan.mu(i) << endl;\n            cout << \"System solved with relative error: \" << (b2bAIC.A * bPan.mu - RHS).norm() / RHS.norm() << endl;\n    #endif\n    cout << endl;\n}\n", "meta": {"hexsha": "acdb280207675bfd8274593d1c25e47aeda97ea4", "size": 2811, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/solve_body.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/solve_body.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/solve_body.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": 35.1375, "max_line_length": 119, "alphanum_fraction": 0.6143721096, "num_tokens": 832, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.831143031127974, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.49572125305157516}}
{"text": "// Boost.Geometry Index\n//\n// n-dimensional content (hypervolume) - 2d area, 3d volume, ...\n//\n// Copyright (c) 2011-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_EXTENSIONS_NSPHERE_INDEX_DETAIL_ALGORITHMS_CONTENT_HPP\n#define BOOST_GEOMETRY_EXTENSIONS_NSPHERE_INDEX_DETAIL_ALGORITHMS_CONTENT_HPP\n\n#include <boost/geometry/index/detail/algorithms/content.hpp>\n\nnamespace boost { namespace geometry { namespace index { namespace detail {\n\nnamespace dispatch {\n\n// TODO replace it by comparable_content?\n// probably radius^Dimension would be sufficient\n// WARNING! this would work only if the same Geometries were compared\n// so it shouldn't be used in the case of Variants!\n// The same with margin()!\n\ntemplate <typename NSphere, size_t Dimension>\nstruct content_nsphere\n{\n    BOOST_STATIC_ASSERT(2 < Dimension);\n\n    typedef typename detail::default_content_result<NSphere>::type result_type;\n    \n    static inline result_type apply(NSphere const& s)\n    {\n        return (content_nsphere<NSphere, Dimension - 2>::apply(s)\n                    * 2 * get_radius<0>(s) * get_radius<0>(s)\n                    * ::boost::math::constants::pi<result_type>()) / Dimension;\n    }\n};\n\ntemplate <typename NSphere>\nstruct content_nsphere<NSphere, 2>\n{\n    typedef typename detail::default_content_result<NSphere>::type result_type;\n\n    static inline result_type apply(NSphere const& s)\n    {\n        return ::boost::math::constants::pi<result_type>() * get_radius<0>(s) * get_radius<0>(s);\n    }\n};\n\ntemplate <typename NSphere>\nstruct content_nsphere<NSphere, 1>\n{\n    typedef typename detail::default_content_result<NSphere>::type result_type;\n\n    static inline result_type apply(NSphere const& s)\n    {\n        return 2 * get_radius<0>(s);\n    }\n};\n\ntemplate <typename Indexable>\nstruct content<Indexable, nsphere_tag>\n{\n    static typename default_content_result<Indexable>::type apply(Indexable const& i)\n    {\n        return dispatch::content_nsphere<Indexable, dimension<Indexable>::value>::apply(i);\n    }\n};\n\n} // namespace dispatch\n\n}}}} // namespace boost::geometry::index::detail\n\n#endif // BOOST_GEOMETRY_EXTENSIONS_NSPHERE_INDEX_DETAIL_ALGORITHMS_CONTENT_HPP\n", "meta": {"hexsha": "b6fcdfad44423aa8bd0570c75156c83294cb271e", "size": 2366, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/geometry/extensions/nsphere/index/detail/algorithms/content.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/nsphere/index/detail/algorithms/content.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/nsphere/index/detail/algorithms/content.hpp", "max_forks_repo_name": "ballisticwhisper/boost", "max_forks_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-05-29T13:41:15.000Z", "max_forks_repo_forks_event_max_datetime": "2016-05-29T13:41:15.000Z", "avg_line_length": 30.7272727273, "max_line_length": 97, "alphanum_fraction": 0.7286559594, "num_tokens": 565, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869948899666, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.49571167199141447}}
{"text": "\n\n/* --------------------------------------------------------------------- \n * \n * Copyright (C) 2000 - 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 Texas at Austin, 2000, 2004, 2005, \n * Timo Heister, 2013 \n */ \n\n\n\n// \u9996\u5148\u662f\u901a\u5e38\u7684\u5934\u6587\u4ef6\u5217\u8868\uff0c\u8fd9\u4e9b\u6587\u4ef6\u5df2\u7ecf\u5728\u4ee5\u524d\u7684\u793a\u4f8b\u7a0b\u5e8f\u4e2d\u4f7f\u7528\u8fc7\u4e86\u3002\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/multithread_info.h> \n#include <deal.II/base/conditional_ostream.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/dynamic_sparsity_pattern.h> \n#include <deal.II/lac/petsc_vector.h> \n#include <deal.II/lac/petsc_sparse_matrix.h> \n#include <deal.II/lac/petsc_solver.h> \n#include <deal.II/lac/petsc_precondition.h> \n#include <deal.II/lac/affine_constraints.h> \n#include <deal.II/lac/sparsity_tools.h> \n#include <deal.II/distributed/shared_tria.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/manifold_lib.h> \n#include <deal.II/grid/grid_tools.h> \n#include <deal.II/dofs/dof_handler.h> \n#include <deal.II/dofs/dof_tools.h> \n#include <deal.II/dofs/dof_renumbering.h> \n#include <deal.II/fe/fe_values.h> \n#include <deal.II/fe/fe_system.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// \u8fd9\u91cc\u662f\u5934\u6587\u4ef6\u4e2d\u4ec5\u6709\u7684\u4e09\u4e2a\u65b0\u4e1c\u897f\uff1a\u4e00\u4e2a\u5305\u542b\u6587\u4ef6\uff0c\u5176\u4e2d\u5b9e\u73b0\u4e86\u7b49\u7ea7\u4e3a2\u548c4\u7684\u5bf9\u79f0\u5f20\u91cf\uff0c\u6b63\u5982\u4ecb\u7ecd\u4e2d\u6240\u4ecb\u7ecd\u7684\u90a3\u6837\u3002\n\n#include <deal.II/base/symmetric_tensor.h> \n\n// \u6700\u540e\u662f\u4e00\u4e2a\u5305\u542b\u4e00\u4e9b\u51fd\u6570\u7684\u5934\u6587\u4ef6\uff0c\u8fd9\u4e9b\u51fd\u6570\u5c06\u5e2e\u52a9\u6211\u4eec\u8ba1\u7b97\u57df\u4e2d\u7279\u5b9a\u70b9\u7684\u5c40\u90e8\u5750\u6807\u7cfb\u7684\u65cb\u8f6c\u77e9\u9635\u3002\n\n#include <deal.II/physics/transformations.h> \n\n// \u7136\u540e\uff0c\u8fd9\u53c8\u662f\u7b80\u5355\u7684C++\u3002\n\n#include <fstream> \n#include <iostream> \n#include <iomanip> \n\n// \u6700\u540e\u4e00\u6b65\u548c\u4ee5\u524d\u6240\u6709\u7684\u7a0b\u5e8f\u4e00\u6837\u3002\n\nnamespace Step18 \n{ \n  using namespace dealii; \n// @sect3{The <code>PointHistory</code> class}  \n\n// \u6b63\u5982\u4ecb\u7ecd\u4e2d\u63d0\u5230\u7684\uff0c\u6211\u4eec\u5fc5\u987b\u5728\u6b63\u4ea4\u70b9\u5b58\u50a8\u65e7\u7684\u5e94\u529b\uff0c\u8fd9\u6837\u6211\u4eec\u5c31\u53ef\u4ee5\u5728\u4e0b\u4e00\u4e2a\u65f6\u95f4\u6b65\u9aa4\u4e2d\u8ba1\u7b97\u8fd9\u4e00\u70b9\u7684\u6b8b\u4f59\u529b\u3002\u4ec5\u4ec5\u8fd9\u4e00\u70b9\u8fd8\u4e0d\u80fd\u4fdd\u8bc1\u53ea\u6709\u4e00\u4e2a\u6210\u5458\u7684\u7ed3\u6784\uff0c\u4f46\u5728\u66f4\u590d\u6742\u7684\u5e94\u7528\u4e2d\uff0c\u6211\u4eec\u8fd8\u5fc5\u987b\u5728\u6b63\u4ea4\u70b9\u4e0a\u5b58\u50a8\u66f4\u591a\u7684\u4fe1\u606f\uff0c\u6bd4\u5982\u5851\u6027\u7684\u5386\u53f2\u53d8\u91cf\u7b49\u3002\u4ece\u672c\u8d28\u4e0a\u8bb2\uff0c\u6211\u4eec\u5fc5\u987b\u5728\u8fd9\u91cc\u5b58\u50a8\u6240\u6709\u5f71\u54cd\u6750\u6599\u5f53\u524d\u72b6\u6001\u7684\u4fe1\u606f\uff0c\u5728\u5851\u6027\u4e2d\uff0c\u8fd9\u4e9b\u4fe1\u606f\u662f\u7531\u53d8\u5f62\u5386\u53f2\u53d8\u91cf\u51b3\u5b9a\u7684\u3002\n\n// \u9664\u4e86\u80fd\u591f\u5b58\u50a8\u6570\u636e\u4e4b\u5916\uff0c\u6211\u4eec\u4e0d\u4f1a\u7ed9\u8fd9\u4e2a\u7c7b\u4efb\u4f55\u6709\u610f\u4e49\u7684\u529f\u80fd\uff0c\u4e5f\u5c31\u662f\u8bf4\uff0c\u6ca1\u6709\u6784\u9020\u51fd\u6570\u3001\u6790\u6784\u51fd\u6570\u6216\u5176\u4ed6\u6210\u5458\u51fd\u6570\u3002\u5728\u8fd9\u79cd \"\u54d1\u5df4 \"\u7c7b\u7684\u60c5\u51b5\u4e0b\uff0c\u6211\u4eec\u901a\u5e38\u9009\u62e9\u5c06\u5176\u58f0\u660e\u4e3a  <code>struct</code> rather than <code>class</code>  \uff0c\u4ee5\u8868\u660e\u5b83\u4eec\u66f4\u63a5\u8fd1\u4e8eC\u8bed\u8a00\u98ce\u683c\u7684\u7ed3\u6784\u800c\u4e0d\u662fC++\u98ce\u683c\u7684\u7c7b\u3002\n\n  template <int dim> \n  struct PointHistory \n  { \n    SymmetricTensor<2, dim> old_stress; \n  }; \n// @sect3{The stress-strain tensor}  \n\n// \u63a5\u4e0b\u6765\uff0c\u6211\u4eec\u5b9a\u4e49\u5f39\u6027\u4e2d\u7684\u5e94\u529b\u548c\u5e94\u53d8\u7684\u7ebf\u6027\u5173\u7cfb\u3002\u5b83\u7531\u4e00\u4e2a\u7b49\u7ea7\u4e3a4\u7684\u5f20\u91cf\u7ed9\u51fa\uff0c\u901a\u5e38\u88ab\u5199\u6210  $C_{ijkl} = \\mu (\\delta_{ik} \\delta_{jl} + \\delta_{il} \\delta_{jk}) + \\lambda \\delta_{ij} \\delta_{kl}$  \u7684\u5f62\u5f0f\u3002\u8fd9\u4e2a\u5f20\u91cf\u5c06\u7b49\u7ea72\u7684\u5bf9\u79f0\u5f20\u91cf\u6620\u5c04\u5230\u7b49\u7ea72\u7684\u5bf9\u79f0\u5f20\u91cf\u3002\u5bf9\u4e8eLam&eacute;\u5e38\u6570 $\\lambda$ \u548c $\\mu$ \u7684\u7ed9\u5b9a\u503c\uff0c\u4e00\u4e2a\u5b9e\u73b0\u5176\u521b\u5efa\u7684\u51fd\u6570\u662f\u76f4\u63a5\u7684\u3002\n\n  template <int dim> \n  SymmetricTensor<4, dim> get_stress_strain_tensor(const double lambda, \n                                                   const double mu) \n  { \n    SymmetricTensor<4, dim> tmp; \n    for (unsigned int i = 0; i < dim; ++i) \n      for (unsigned int j = 0; j < dim; ++j) \n        for (unsigned int k = 0; k < dim; ++k) \n          for (unsigned int l = 0; l < dim; ++l) \n            tmp[i][j][k][l] = (((i == k) && (j == l) ? mu : 0.0) + \n                               ((i == l) && (j == k) ? mu : 0.0) + \n                               ((i == j) && (k == l) ? lambda : 0.0)); \n    return tmp; \n  } \n\n// \u901a\u8fc7\u8fd9\u4e2a\u51fd\u6570\uff0c\u6211\u4eec\u5c06\u5728\u4e0b\u9762\u7684\u4e3b\u7c7b\u4e2d\u5b9a\u4e49\u4e00\u4e2a\u9759\u6001\u6210\u5458\u53d8\u91cf\uff0c\u5728\u6574\u4e2a\u7a0b\u5e8f\u4e2d\u4f5c\u4e3a\u5e94\u529b-\u5e94\u53d8\u5f20\u91cf\u4f7f\u7528\u3002\u8bf7\u6ce8\u610f\uff0c\u5728\u66f4\u590d\u6742\u7684\u7a0b\u5e8f\u4e2d\uff0c\u8fd9\u53ef\u80fd\u662f\u67d0\u4e2a\u7c7b\u7684\u6210\u5458\u53d8\u91cf\uff0c\u6216\u8005\u662f\u4e00\u4e2a\u6839\u636e\u5176\u4ed6\u8f93\u5165\u8fd4\u56de\u5e94\u529b-\u5e94\u53d8\u5173\u7cfb\u7684\u51fd\u6570\u3002\u4f8b\u5982\uff0c\u5728\u635f\u4f24\u7406\u8bba\u6a21\u578b\u4e2d\uff0cLam&eacute;\u5e38\u6570\u88ab\u8ba4\u4e3a\u662f\u4e00\u4e2a\u70b9\u7684\u5148\u524d\u5e94\u529b/\u5e94\u53d8\u5386\u53f2\u7684\u51fd\u6570\u3002\u76f8\u53cd\uff0c\u5728\u5851\u6027\u4e2d\uff0c\u5982\u679c\u6750\u6599\u5728\u67d0\u4e00\u70b9\u8fbe\u5230\u4e86\u5c48\u670d\u5e94\u529b\uff0c\u90a3\u4e48\u5e94\u529b-\u5e94\u53d8\u5f20\u91cf\u7684\u5f62\u5f0f\u5c31\u4f1a\u88ab\u4fee\u6539\uff0c\u800c\u4e14\u53ef\u80fd\u8fd8\u53d6\u51b3\u4e8e\u5176\u5148\u524d\u7684\u5386\u53f2\u3002\n\n// \u7136\u800c\uff0c\u5728\u672c\u7a0b\u5e8f\u4e2d\uff0c\u6211\u4eec\u5047\u8bbe\u6750\u6599\u662f\u5b8c\u5168\u5f39\u6027\u548c\u7ebf\u6027\u7684\uff0c\u6052\u5b9a\u7684\u5e94\u529b-\u5e94\u53d8\u5f20\u91cf\u5bf9\u6211\u4eec\u76ee\u524d\u7684\u76ee\u7684\u6765\u8bf4\u662f\u8db3\u591f\u7684\u3002\n\n//  @sect3{Auxiliary functions}  \n\n// \u5728\u7a0b\u5e8f\u7684\u5176\u4ed6\u90e8\u5206\u4e4b\u524d\uff0c\u8fd9\u91cc\u6709\u51e0\u4e2a\u6211\u4eec\u9700\u8981\u7684\u51fd\u6570\u4f5c\u4e3a\u5de5\u5177\u3002\u8fd9\u4e9b\u662f\u5728\u5185\u5faa\u73af\u4e2d\u8c03\u7528\u7684\u5c0f\u51fd\u6570\uff0c\u6240\u4ee5\u6211\u4eec\u628a\u5b83\u4eec\u6807\u8bb0\u4e3a  <code>inline</code>  \u3002\n\n// \u7b2c\u4e00\u4e2a\u662f\u901a\u8fc7\u5f62\u6210\u8fd9\u4e2a\u5f62\u72b6\u51fd\u6570\u7684\u5bf9\u79f0\u68af\u5ea6\u6765\u8ba1\u7b97\u5f62\u72b6\u51fd\u6570 <code>shape_func</code> at quadrature point <code>q_point</code> \u7684\u5bf9\u79f0\u5e94\u53d8\u5f20\u91cf\u3002\u5f53\u6211\u4eec\u60f3\u5f62\u6210\u77e9\u9635\u65f6\uff0c\u6211\u4eec\u9700\u8981\u8fd9\u6837\u505a\uff0c\u6bd4\u5982\u8bf4\u3002\n\n// \u6211\u4eec\u5e94\u8be5\u6ce8\u610f\u5230\uff0c\u5728\u4ee5\u524d\u5904\u7406\u77e2\u91cf\u503c\u95ee\u9898\u7684\u4f8b\u5b50\u4e2d\uff0c\u6211\u4eec\u603b\u662f\u95ee\u6709\u9650\u5143\u5bf9\u8c61\u5728\u54ea\u4e2a\u77e2\u91cf\u5206\u91cf\u4e2d\u7684\u5f62\u72b6\u51fd\u6570\u5b9e\u9645\u4e0a\u662f\u4e0d\u4e3a\u96f6\u7684\uff0c\u4ece\u800c\u907f\u514d\u8ba1\u7b97\u4efb\u4f55\u6211\u4eec\u53cd\u6b63\u53ef\u4ee5\u8bc1\u660e\u4e3a\u96f6\u7684\u9879\u3002\u4e3a\u6b64\uff0c\u6211\u4eec\u4f7f\u7528\u4e86 <code>fe.system_to_component_index</code> \u51fd\u6570\u6765\u8fd4\u56de\u5f62\u72b6\u51fd\u6570\u5728\u54ea\u4e2a\u5206\u91cf\u4e2d\u4e3a\u96f6\uff0c\u540c\u65f6 <code>fe_values.shape_value</code> \u548c <code>fe_values.shape_grad</code> \u51fd\u6570\u53ea\u8fd4\u56de\u5f62\u72b6\u51fd\u6570\u7684\u5355\u4e2a\u975e\u96f6\u5206\u91cf\u7684\u503c\u548c\u68af\u5ea6\uff0c\u5982\u679c\u8fd9\u662f\u4e00\u4e2a\u77e2\u91cf\u503c\u5143\u7d20\u3002\n\n// \u8fd9\u662f\u4e00\u4e2a\u4f18\u5316\uff0c\u5982\u679c\u4e0d\u662f\u975e\u5e38\u5173\u952e\u7684\u65f6\u95f4\uff0c\u6211\u4eec\u53ef\u4ee5\u7528\u4e00\u4e2a\u66f4\u7b80\u5355\u7684\u6280\u672f\u6765\u89e3\u51b3\uff1a\u53ea\u9700\u5411 <code>fe_values</code> \u8be2\u95ee\u4e00\u4e2a\u7ed9\u5b9a\u5f62\u72b6\u51fd\u6570\u7684\u7ed9\u5b9a\u5206\u91cf\u5728\u7ed9\u5b9a\u6b63\u4ea4\u70b9\u7684\u503c\u6216\u68af\u5ea6\u3002\u8fd9\u5c31\u662f  <code>fe_values.shape_grad_component(shape_func,q_point,i)</code>  \u8c03\u7528\u7684\u4f5c\u7528\uff1a\u8fd4\u56de\u5f62\u72b6\u51fd\u6570  <code>shape_func</code>  \u7684\u7b2c  <code>q_point</code>  \u4e2a\u5206\u91cf\u5728\u6b63\u4ea4\u70b9\u7684\u5168\u90e8\u68af\u5ea6\u3002\u5982\u679c\u67d0\u4e2a\u5f62\u72b6\u51fd\u6570\u7684\u67d0\u4e2a\u5206\u91cf\u603b\u662f\u4e3a\u96f6\uff0c\u90a3\u4e48\u8fd9\u5c06\u7b80\u5355\u5730\u603b\u662f\u8fd4\u56de\u96f6\u3002\n\n// \u5982\u524d\u6240\u8ff0\uff0c\u4f7f\u7528 <code>fe_values.shape_grad_component</code> \u800c\u4e0d\u662f <code>fe.system_to_component_index</code> \u548c <code>fe_values.shape_grad</code> \u7684\u7ec4\u5408\u53ef\u80fd\u6548\u7387\u8f83\u4f4e\uff0c\u4f46\u5176\u5b9e\u73b0\u5df2\u9488\u5bf9\u8fd9\u79cd\u60c5\u51b5\u8fdb\u884c\u4e86\u4f18\u5316\uff0c\u5e94\u8be5\u4e0d\u4f1a\u6709\u5f88\u5927\u7684\u51cf\u6162\u3002\u6211\u4eec\u5728\u8fd9\u91cc\u6f14\u793a\u8fd9\u4e2a\u6280\u672f\uff0c\u56e0\u4e3a\u5b83\u662f\u5982\u6b64\u7684\u7b80\u5355\u548c\u76f4\u63a5\u3002\n\n  template <int dim> \n  inline SymmetricTensor<2, dim> get_strain(const FEValues<dim> &fe_values, \n                                            const unsigned int   shape_func, \n                                            const unsigned int   q_point) \n  { \n\n// \u58f0\u660e\u4e00\u4e2a\u5c06\u4fdd\u5b58\u8fd4\u56de\u503c\u7684\u6682\u5b58\u5668\u3002\n\n    SymmetricTensor<2, dim> tmp; \n\n// \u9996\u5148\uff0c\u586b\u5145\u5bf9\u89d2\u7ebf\u9879\uff0c\u8fd9\u53ea\u662f\u77e2\u91cf\u503c\u5f62\u72b6\u51fd\u6570\u7684\u65b9\u5411 <code>i</code> of the <code>i</code> \u5206\u91cf\u7684\u5bfc\u6570\u3002\n\n    for (unsigned int i = 0; i < dim; ++i) \n      tmp[i][i] = fe_values.shape_grad_component(shape_func, q_point, i)[i]; \n\n// \u7136\u540e\u586b\u5145\u5e94\u53d8\u5f20\u91cf\u7684\u5176\u4f59\u90e8\u5206\u3002\u6ce8\u610f\uff0c\u7531\u4e8e\u5f20\u91cf\u662f\u5bf9\u79f0\u7684\uff0c\u6211\u4eec\u53ea\u9700\u8981\u8ba1\u7b97\u4e00\u534a\uff08\u8fd9\u91cc\uff1a\u53f3\u4e0a\u89d2\uff09\u7684\u975e\u5bf9\u89d2\u7ebf\u5143\u7d20\uff0c <code>SymmetricTensor</code> \u7c7b\u7684\u5b9e\u73b0\u786e\u4fdd\u81f3\u5c11\u5230\u5916\u9762\u7684\u5bf9\u79f0\u6761\u76ee\u4e5f\u88ab\u586b\u5145\uff08\u5b9e\u9645\u4e0a\uff0c\u8fd9\u4e2a\u7c7b\u5f53\u7136\u53ea\u5b58\u50a8\u4e00\u4efd\uff09\u3002\u5728\u8fd9\u91cc\uff0c\u6211\u4eec\u9009\u62e9\u4e86\u5f20\u91cf\u7684\u53f3\u4e0a\u534a\u90e8\u5206\uff0c\u4f46\u662f\u5de6\u4e0b\u534a\u90e8\u5206\u4e5f\u4e00\u6837\u597d\u3002\n\n    for (unsigned int i = 0; i < dim; ++i) \n      for (unsigned int j = i + 1; j < dim; ++j) \n        tmp[i][j] = \n          (fe_values.shape_grad_component(shape_func, q_point, i)[j] + \n           fe_values.shape_grad_component(shape_func, q_point, j)[i]) / \n          2; \n\n    return tmp; \n  } \n\n// \u7b2c\u4e8c\u4e2a\u51fd\u6570\u505a\u4e86\u975e\u5e38\u7c7b\u4f3c\u7684\u4e8b\u60c5\uff08\u56e0\u6b64\u88ab\u8d4b\u4e88\u76f8\u540c\u7684\u540d\u5b57\uff09\uff1a\u4ece\u4e00\u4e2a\u77e2\u91cf\u503c\u573a\u7684\u68af\u5ea6\u8ba1\u7b97\u5bf9\u79f0\u5e94\u53d8\u5f20\u91cf\u3002\u5982\u679c\u4f60\u5df2\u7ecf\u6709\u4e86\u4e00\u4e2a\u89e3\u573a\uff0c <code>fe_values.get_function_gradients</code> \u51fd\u6570\u5141\u8bb8\u4f60\u5728\u4e00\u4e2a\u6b63\u4ea4\u70b9\u4e0a\u63d0\u53d6\u89e3\u573a\u7684\u6bcf\u4e2a\u5206\u91cf\u7684\u68af\u5ea6\u3002\u5b83\u8fd4\u56de\u7684\u662f\u4e00\u4e2a\u79e9-1\u5f20\u91cf\u7684\u77e2\u91cf\uff1a\u89e3\u7684\u6bcf\u4e2a\u77e2\u91cf\u5206\u91cf\u6709\u4e00\u4e2a\u79e9-1\u5f20\u91cf\uff08\u68af\u5ea6\uff09\u3002\u7531\u6b64\uff0c\u6211\u4eec\u5fc5\u987b\u901a\u8fc7\u8f6c\u6362\u6570\u636e\u5b58\u50a8\u683c\u5f0f\u548c\u5bf9\u79f0\u5316\u6765\u91cd\u5efa\uff08\u5bf9\u79f0\u7684\uff09\u5e94\u53d8\u5f20\u91cf\u3002\u6211\u4eec\u7528\u548c\u4e0a\u9762\u4e00\u6837\u7684\u65b9\u6cd5\u6765\u505a\uff0c\u4e5f\u5c31\u662f\u8bf4\uff0c\u6211\u4eec\u901a\u8fc7\u9996\u5148\u586b\u5145\u5bf9\u89d2\u7ebf\uff0c\u7136\u540e\u53ea\u586b\u5145\u5bf9\u79f0\u5f20\u91cf\u7684\u4e00\u534a\u6765\u907f\u514d\u4e00\u4e9b\u8ba1\u7b97\uff08 <code>SymmetricTensor</code> \u7c7b\u786e\u4fdd\u53ea\u5199\u4e24\u4e2a\u5bf9\u79f0\u5206\u91cf\u4e2d\u7684\u4e00\u4e2a\u5c31\u8db3\u591f\u4e86\uff09\u3002\n\n// \u4e0d\u8fc7\u5728\u6211\u4eec\u8fd9\u6837\u505a\u4e4b\u524d\uff0c\u6211\u4eec\u8981\u786e\u4fdd\u8f93\u5165\u6709\u6211\u4eec\u671f\u671b\u7684\u90a3\u79cd\u7ed3\u6784\uff1a\u5373\u6709 <code>dim</code> \u4e2a\u77e2\u91cf\u5206\u91cf\uff0c\u5373\u6bcf\u4e2a\u5750\u6807\u65b9\u5411\u6709\u4e00\u4e2a\u4f4d\u79fb\u5206\u91cf\u3002\u6211\u4eec\u7528 <code>Assert</code> \u5b8f\u6765\u6d4b\u8bd5\u8fd9\u4e00\u70b9\uff0c\u5982\u679c\u4e0d\u7b26\u5408\u6761\u4ef6\uff0c\u6211\u4eec\u7684\u7a0b\u5e8f\u5c31\u4f1a\u88ab\u7ec8\u6b62\u3002\n\n  template <int dim> \n  inline SymmetricTensor<2, dim> \n  get_strain(const std::vector<Tensor<1, dim>> &grad) \n  { \n    Assert(grad.size() == dim, ExcInternalError()); \n\n    SymmetricTensor<2, dim> strain; \n    for (unsigned int i = 0; i < dim; ++i) \n      strain[i][i] = grad[i][i]; \n\n    for (unsigned int i = 0; i < dim; ++i) \n      for (unsigned int j = i + 1; j < dim; ++j) \n        strain[i][j] = (grad[i][j] + grad[j][i]) / 2; \n\n    return strain; \n  } \n\n// \u6700\u540e\uff0c\u4e0b\u9762\u6211\u4eec\u5c06\u9700\u8981\u4e00\u4e2a\u51fd\u6570\u6765\u8ba1\u7b97\u67d0\u4e00\u70b9\u7684\u4f4d\u79fb\u6240\u5f15\u8d77\u7684\u65cb\u8f6c\u77e9\u9635\u3002\u5f53\u7136\uff0c\u4e8b\u5b9e\u4e0a\uff0c\u5355\u70b9\u7684\u4f4d\u79fb\u53ea\u6709\u4e00\u4e2a\u65b9\u5411\u548c\u4e00\u4e2a\u5e45\u5ea6\uff0c\u8bf1\u53d1\u65cb\u8f6c\u7684\u662f\u65b9\u5411\u548c\u5e45\u5ea6\u7684\u53d8\u5316\u3002\u5b9e\u9645\u4e0a\uff0c\u65cb\u8f6c\u77e9\u9635\u53ef\u4ee5\u901a\u8fc7\u4f4d\u79fb\u7684\u68af\u5ea6\u6765\u8ba1\u7b97\uff0c\u6216\u8005\u66f4\u5177\u4f53\u5730\u8bf4\uff0c\u901a\u8fc7\u5377\u66f2\u6765\u8ba1\u7b97\u3002\n\n// \u786e\u5b9a\u65cb\u8f6c\u77e9\u9635\u7684\u516c\u5f0f\u6709\u70b9\u7b28\u62d9\uff0c\u7279\u522b\u662f\u5728\u4e09\u7ef4\u4e2d\u3002\u5bf9\u4e8e2D\u6765\u8bf4\uff0c\u6709\u4e00\u4e2a\u66f4\u7b80\u5355\u7684\u65b9\u6cd5\uff0c\u6240\u4ee5\u6211\u4eec\u628a\u8fd9\u4e2a\u51fd\u6570\u5b9e\u73b0\u4e86\u4e24\u6b21\uff0c\u4e00\u6b21\u7528\u4e8e2D\uff0c\u4e00\u6b21\u7528\u4e8e3D\uff0c\u8fd9\u6837\u6211\u4eec\u5c31\u53ef\u4ee5\u5728\u4e24\u4e2a\u7a7a\u95f4\u7ef4\u5ea6\u4e0a\u7f16\u8bd1\u548c\u4f7f\u7528\u8fd9\u4e2a\u7a0b\u5e8f\uff0c\u5982\u679c\u9700\u8981\u7684\u8bdd--\u6bd5\u7adf\uff0cdeal.II\u662f\u5173\u4e8e\u72ec\u7acb\u7ef4\u5ea6\u7f16\u7a0b\u548c\u91cd\u590d\u4f7f\u7528\u7b97\u6cd5\u7684\uff0c\u57282D\u7684\u5ec9\u4ef7\u8ba1\u7b97\u4e2d\u7ecf\u8fc7\u6d4b\u8bd5\uff0c\u57283D\u7684\u66f4\u6602\u8d35\u7684\u8ba1\u7b97\u4e2d\u4f7f\u7528\u3002\u4e0b\u9762\u662f\u4e00\u79cd\u60c5\u51b5\uff0c\u6211\u4eec\u5fc5\u987b\u4e3a2D\u548c3D\u5b9e\u73b0\u4e0d\u540c\u7684\u7b97\u6cd5\uff0c\u4f46\u53ef\u4ee5\u7528\u72ec\u7acb\u4e8e\u7a7a\u95f4\u7ef4\u5ea6\u7684\u65b9\u5f0f\u6765\u7f16\u5199\u7a0b\u5e8f\u7684\u5176\u4f59\u90e8\u5206\u3002\n\n// \u6240\u4ee5\uff0c\u4e0d\u7528\u518d\u591a\u8bf4\u4e86\uff0c\u6765\u770b\u770b2D\u7684\u5b9e\u73b0\u3002\n\n  Tensor<2, 2> get_rotation_matrix(const std::vector<Tensor<1, 2>> &grad_u) \n  { \n\n// \u9996\u5148\uff0c\u6839\u636e\u68af\u5ea6\u8ba1\u7b97\u51fa\u901f\u5ea6\u573a\u7684\u5377\u66f2\u3002\u6ce8\u610f\uff0c\u6211\u4eec\u662f\u57282d\u4e2d\uff0c\u6240\u4ee5\u65cb\u8f6c\u662f\u4e00\u4e2a\u6807\u91cf\u3002\n\n    const double curl = (grad_u[1][0] - grad_u[0][1]); \n\n// \u7531\u6b64\u8ba1\u7b97\u51fa\u65cb\u8f6c\u7684\u89d2\u5ea6\u3002\n\n    const double angle = std::atan(curl); \n\n// \u7531\u6b64\uff0c\u5efa\u7acb\u53cd\u5bf9\u79f0\u7684\u65cb\u8f6c\u77e9\u9635\u3002\u6211\u4eec\u5e0c\u671b\u8fd9\u4e2a\u65cb\u8f6c\u77e9\u9635\u80fd\u591f\u4ee3\u8868\u672c\u5730\u5750\u6807\u7cfb\u76f8\u5bf9\u4e8e\u5168\u5c40\u76f4\u89d2\u5750\u6807\u7cfb\u7684\u65cb\u8f6c\uff0c\u6240\u4ee5\u6211\u4eec\u7528\u4e00\u4e2a\u8d1f\u7684\u89d2\u5ea6\u6765\u6784\u5efa\u5b83\u3002\u56e0\u6b64\uff0c\u8fd9\u4e2a\u65cb\u8f6c\u77e9\u9635\u4ee3\u8868\u4e86\u4ece\u672c\u5730\u5750\u6807\u7cfb\u79fb\u52a8\u5230\u5168\u5c40\u5750\u6807\u7cfb\u6240\u9700\u7684\u65cb\u8f6c\u3002\n\n    return Physics::Transformations::Rotations::rotation_matrix_2d(-angle); \n  } \n\n// \u4e09\u7ef4\u7684\u60c5\u51b5\u5c31\u6bd4\u8f83\u590d\u6742\u4e86\u3002\n\n  Tensor<2, 3> get_rotation_matrix(const std::vector<Tensor<1, 3>> &grad_u) \n  { \n\n// \u540c\u6837\u9996\u5148\u8ba1\u7b97\u901f\u5ea6\u573a\u7684\u5377\u66f2\u3002\u8fd9\u4e00\u6b21\uff0c\u5b83\u662f\u4e00\u4e2a\u5b9e\u6570\u5411\u91cf\u3002\n\n    const Point<3> curl(grad_u[2][1] - grad_u[1][2], \n                        grad_u[0][2] - grad_u[2][0], \n                        grad_u[1][0] - grad_u[0][1]); \n\n// \u4ece\u8fd9\u4e2a\u77e2\u91cf\u4e2d\uff0c\u5229\u7528\u5b83\u7684\u5927\u5c0f\uff0c\u8ba1\u7b97\u51fa\u65cb\u8f6c\u89d2\u5ea6\u7684\u6b63\u5207\u503c\uff0c\u5e76\u7531\u6b64\u8ba1\u7b97\u51fa\u76f8\u5bf9\u4e8e\u76f4\u89d2\u5750\u6807\u7cfb\u7684\u5b9e\u9645\u65cb\u8f6c\u89d2\u5ea6\u3002\n\n    const double tan_angle = std::sqrt(curl * curl); \n    const double angle     = std::atan(tan_angle); \n\n// \u73b0\u5728\uff0c\u8fd9\u91cc\u6709\u4e00\u4e2a\u95ee\u9898\uff1a\u5982\u679c\u65cb\u8f6c\u89d2\u5ea6\u592a\u5c0f\uff0c\u90a3\u5c31\u610f\u5473\u7740\u6ca1\u6709\u65cb\u8f6c\u53d1\u751f\uff08\u4f8b\u5982\u5e73\u79fb\u8fd0\u52a8\uff09\u3002\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0c\u65cb\u8f6c\u77e9\u9635\u5c31\u662f\u8eab\u4efd\u77e9\u9635\u3002\n\n// \u6211\u4eec\u5f3a\u8c03\u8fd9\u4e00\u70b9\u7684\u539f\u56e0\u662f\uff0c\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0c\u6211\u4eec\u6709  <code>tan_angle==0</code>  \u3002\u518d\u5f80\u4e0b\u770b\uff0c\u6211\u4eec\u5728\u8ba1\u7b97\u65cb\u8f6c\u8f74\u7684\u65f6\u5019\u9700\u8981\u9664\u4ee5\u8fd9\u4e2a\u6570\u5b57\uff0c\u8fd9\u6837\u505a\u9664\u6cd5\u7684\u65f6\u5019\u4f1a\u9047\u5230\u9ebb\u70e6\u3002\u56e0\u6b64\uff0c\u8ba9\u6211\u4eec\u8d70\u6377\u5f84\uff0c\u5982\u679c\u65cb\u8f6c\u89d2\u5ea6\u771f\u7684\u5f88\u5c0f\uff0c\u5c31\u7b80\u5355\u5730\u8fd4\u56de\u540c\u4e00\u77e9\u9635\u3002\n\n    if (std::abs(angle) < 1e-9) \n      { \n        static const double rotation[3][3] = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}; \n        static const Tensor<2, 3> rot(rotation); \n        return rot; \n      } \n\n// \u5426\u5219\u8ba1\u7b97\u771f\u5b9e\u7684\u65cb\u8f6c\u77e9\u9635\u3002\u4e3a\u6b64\uff0c\u6211\u4eec\u518d\u6b21\u4f9d\u9760\u4e00\u4e2a\u9884\u5b9a\u4e49\u7684\u51fd\u6570\u6765\u8ba1\u7b97\u672c\u5730\u5750\u6807\u7cfb\u7684\u65cb\u8f6c\u77e9\u9635\u3002\n\n    const Point<3> axis = curl / tan_angle; \n    return Physics::Transformations::Rotations::rotation_matrix_3d(axis, \n                                                                   -angle); \n  } \n\n//  @sect3{The <code>TopLevel</code> class}  \n\n// \u8fd9\u5c31\u662f\u7a0b\u5e8f\u7684\u4e3b\u7c7b\u3002\u7531\u4e8e\u547d\u540d\u7a7a\u95f4\u5df2\u7ecf\u8868\u660e\u4e86\u6211\u4eec\u8981\u89e3\u51b3\u7684\u95ee\u9898\uff0c\u8ba9\u6211\u4eec\u7528\u5b83\u7684\u4f5c\u7528\u6765\u79f0\u547c\u5b83\uff1a\u5b83\u5f15\u5bfc\u7740\u7a0b\u5e8f\u7684\u6d41\u7a0b\uff0c\u4e5f\u5c31\u662f\u8bf4\uff0c\u5b83\u662f\u9876\u5c42\u9a71\u52a8\u3002\n\n// \u8fd9\u4e2a\u7c7b\u7684\u6210\u5458\u53d8\u91cf\u57fa\u672c\u4e0a\u548c\u4ee5\u524d\u4e00\u6837\uff0c\u5373\u5b83\u5fc5\u987b\u6709\u4e00\u4e2a\u4e09\u89d2\u5f62\uff0c\u4e00\u4e2aDoF\u5904\u7406\u7a0b\u5e8f\u548c\u76f8\u5173\u7684\u5bf9\u8c61\uff0c\u5982\u7ea6\u675f\u6761\u4ef6\uff0c\u63cf\u8ff0\u7ebf\u6027\u7cfb\u7edf\u7684\u53d8\u91cf\u7b49\u3002\u73b0\u5728\u8fd8\u6709\u5f88\u591a\u6210\u5458\u51fd\u6570\uff0c\u6211\u4eec\u5c06\u5728\u4e0b\u9762\u89e3\u91ca\u3002\n\n// \u7136\u800c\uff0c\u8be5\u7c7b\u7684\u5916\u90e8\u63a5\u53e3\u662f\u4e0d\u53d8\u7684\uff1a\u5b83\u6709\u4e00\u4e2a\u516c\u5171\u7684\u6784\u9020\u51fd\u6570\u548c\u6790\u6784\u51fd\u6570\uff0c\u5e76\u4e14\u5b83\u6709\u4e00\u4e2a <code>run</code> \u51fd\u6570\u6765\u542f\u52a8\u6240\u6709\u7684\u5de5\u4f5c\u3002\n\n  template <int dim> \n  class TopLevel \n  { \n  public: \n    TopLevel(); \n    ~TopLevel(); \n    void run(); \n\n  private: \n\n// \u79c1\u6709\u63a5\u53e3\u6bd4  step-17  \u4e2d\u7684\u66f4\u52a0\u5e7f\u6cdb\u3002\u9996\u5148\uff0c\u6211\u4eec\u663e\u7136\u9700\u8981\u521b\u5efa\u521d\u59cb\u7f51\u683c\u7684\u51fd\u6570\uff0c\u8bbe\u7f6e\u63cf\u8ff0\u5f53\u524d\u7f51\u683c\u4e0a\u7684\u7ebf\u6027\u7cfb\u7edf\u7684\u53d8\u91cf\uff08\u5373\u77e9\u9635\u548c\u5411\u91cf\uff09\uff0c\u7136\u540e\u662f\u5b9e\u9645\u7ec4\u88c5\u7cfb\u7edf\u7684\u51fd\u6570\uff0c\u6307\u5bfc\u6bcf\u4e2a\u65f6\u95f4\u6b65\u957f\u4e2d\u5fc5\u987b\u89e3\u51b3\u7684\u95ee\u9898\uff0c\u4e00\u4e2a\u89e3\u51b3\u6bcf\u4e2a\u65f6\u95f4\u6b65\u957f\u4e2d\u51fa\u73b0\u7684\u7ebf\u6027\u7cfb\u7edf\u7684\u51fd\u6570\uff08\u5e76\u8fd4\u56de\u5b83\u7684\u8fed\u4ee3\u6b21\u6570\uff09\uff0c\u6700\u540e\u5728\u6b63\u786e\u7684\u7f51\u683c\u4e0a\u8f93\u51fa\u89e3\u5411\u91cf\u3002\n\n    void create_coarse_grid(); \n\n    void setup_system(); \n\n    void assemble_system(); \n\n    void solve_timestep(); \n\n    unsigned int solve_linear_problem(); \n\n    void output_results() const; \n\n// \u9664\u4e86\u524d\u4e24\u4e2a\uff0c\u6240\u6709\u8fd9\u4e9b\u51fd\u6570\u90fd\u5728\u6bcf\u4e2a\u65f6\u95f4\u6b65\u4e2d\u88ab\u8c03\u7528\u3002\u7531\u4e8e\u7b2c\u4e00\u4e2a\u65f6\u95f4\u6b65\u9aa4\u6709\u70b9\u7279\u6b8a\uff0c\u6211\u4eec\u6709\u5355\u72ec\u7684\u51fd\u6570\u6765\u63cf\u8ff0\u4e00\u4e2a\u65f6\u95f4\u6b65\u9aa4\u4e2d\u5fc5\u987b\u53d1\u751f\u7684\u4e8b\u60c5\uff1a\u4e00\u4e2a\u7528\u4e8e\u7b2c\u4e00\u4e2a\u65f6\u95f4\u6b65\u9aa4\uff0c\u4e00\u4e2a\u7528\u4e8e\u6240\u6709\u540e\u7eed\u65f6\u95f4\u6b65\u9aa4\u3002\n\n    void do_initial_timestep(); \n\n    void do_timestep(); \n\n// \u7136\u540e\u6211\u4eec\u9700\u8981\u4e00\u5927\u5806\u51fd\u6570\u6765\u505a\u5404\u79cd\u4e8b\u60c5\u3002\u7b2c\u4e00\u4e2a\u662f\u7ec6\u5316\u521d\u59cb\u7f51\u683c\uff1a\u6211\u4eec\u4ece\u539f\u59cb\u72b6\u6001\u7684\u7c97\u7f51\u683c\u5f00\u59cb\uff0c\u89e3\u51b3\u8fd9\u4e2a\u95ee\u9898\uff0c\u7136\u540e\u770b\u4e00\u4e0b\uff0c\u5e76\u76f8\u5e94\u5730\u7ec6\u5316\u7f51\u683c\uff0c\u7136\u540e\u91cd\u65b0\u5f00\u59cb\u540c\u6837\u7684\u8fc7\u7a0b\uff0c\u518d\u6b21\u4ee5\u539f\u59cb\u72b6\u6001\u3002\u56e0\u6b64\uff0c\u7ec6\u5316\u521d\u59cb\u7f51\u683c\u6bd4\u5728\u4e24\u4e2a\u8fde\u7eed\u7684\u65f6\u95f4\u6b65\u9aa4\u4e4b\u95f4\u7ec6\u5316\u7f51\u683c\u8981\u7b80\u5355\u4e00\u4e9b\uff0c\u56e0\u4e3a\u5b83\u4e0d\u6d89\u53ca\u5c06\u6570\u636e\u4ece\u65e7\u7684\u4e09\u89d2\u6d4b\u91cf\u8f6c\u79fb\u5230\u65b0\u7684\u4e09\u89d2\u6d4b\u91cf\uff0c\u7279\u522b\u662f\u5b58\u50a8\u5728\u6bcf\u4e2a\u6b63\u4ea4\u70b9\u7684\u5386\u53f2\u6570\u636e\u3002\n\n    void refine_initial_grid(); \n\n// \u5728\u6bcf\u4e2a\u65f6\u95f4\u6b65\u9aa4\u7ed3\u675f\u65f6\uff0c\u6211\u4eec\u8981\u6839\u636e\u8fd9\u4e2a\u65f6\u95f4\u6b65\u9aa4\u8ba1\u7b97\u7684\u589e\u91cf\u4f4d\u79fb\u6765\u79fb\u52a8\u7f51\u683c\u9876\u70b9\u3002\u8fd9\u5c31\u662f\u5b8c\u6210\u8fd9\u4e2a\u4efb\u52a1\u7684\u51fd\u6570\u3002\n\n    void move_mesh(); \n\n// \u63a5\u4e0b\u6765\u662f\u4e24\u4e2a\u5904\u7406\u5b58\u50a8\u5728\u6bcf\u4e2a\u6b63\u4ea4\u70b9\u7684\u5386\u53f2\u53d8\u91cf\u7684\u51fd\u6570\u3002\u7b2c\u4e00\u4e2a\u51fd\u6570\u5728\u7b2c\u4e00\u4e2a\u65f6\u95f4\u6b65\u957f\u4e4b\u524d\u88ab\u8c03\u7528\uff0c\u4e3a\u5386\u53f2\u53d8\u91cf\u8bbe\u7f6e\u4e00\u4e2a\u539f\u59cb\u72b6\u6001\u3002\u5b83\u53ea\u5bf9\u5c5e\u4e8e\u5f53\u524d\u5904\u7406\u5668\u7684\u5355\u5143\u4e0a\u7684\u6b63\u4ea4\u70b9\u8d77\u4f5c\u7528\u3002\n\n    void setup_quadrature_point_history(); \n\n// \u7b2c\u4e8c\u9879\u662f\u5728\u6bcf\u4e2a\u65f6\u95f4\u6bb5\u7ed3\u675f\u65f6\u66f4\u65b0\u5386\u53f2\u53d8\u91cf\u3002\n\n    void update_quadrature_point_history(); \n\n// \u8fd9\u662f\u65b0\u7684\u5171\u4eab\u4e09\u89d2\u6cd5\u3002\n\n    parallel::shared::Triangulation<dim> triangulation; \n\n    FESystem<dim> fe; \n\n    DoFHandler<dim> dof_handler; \n\n    AffineConstraints<double> hanging_node_constraints; \n\n// \u8fd9\u4e2a\u7a0b\u5e8f\u7684\u4e00\u4e2a\u4e0d\u540c\u4e4b\u5904\u5728\u4e8e\uff0c\u6211\u4eec\u5728\u7c7b\u58f0\u660e\u4e2d\u58f0\u660e\u4e86\u6b63\u4ea4\u516c\u5f0f\u3002\u539f\u56e0\u662f\u5728\u6240\u6709\u5176\u4ed6\u7a0b\u5e8f\u4e2d\uff0c\u5982\u679c\u6211\u4eec\u5728\u8ba1\u7b97\u77e9\u9635\u548c\u53f3\u624b\u8fb9\u65f6\u4f7f\u7528\u4e0d\u540c\u7684\u6b63\u4ea4\u516c\u5f0f\uff0c\u5e76\u6ca1\u6709\u4ec0\u4e48\u574f\u5904\uff0c\u6bd4\u5982\u8bf4\u3002\u7136\u800c\uff0c\u5728\u76ee\u524d\u7684\u60c5\u51b5\u4e0b\uff0c\u5b83\u786e\u5b9e\u5982\u6b64\uff1a\u6211\u4eec\u5728\u6b63\u4ea4\u70b9\u4e2d\u5b58\u50a8\u4e86\u4fe1\u606f\uff0c\u6240\u4ee5\u6211\u4eec\u5fc5\u987b\u786e\u4fdd\u7a0b\u5e8f\u7684\u6240\u6709\u90e8\u5206\u90fd\u540c\u610f\u5b83\u4eec\u7684\u4f4d\u7f6e\u4ee5\u53ca\u6bcf\u4e2a\u5355\u5143\u683c\u4e0a\u6709\u591a\u5c11\u4e2a\u3002\u56e0\u6b64\uff0c\u8ba9\u6211\u4eec\u9996\u5148\u58f0\u660e\u5c06\u5728\u6574\u4e2a\u7a0b\u5e8f\u4e2d\u4f7f\u7528\u7684\u6b63\u4ea4\u516c\u5f0f...\u3002\n\n    const QGauss<dim> quadrature_formula; \n\n// ......\u7136\u540e\u4e5f\u6709\u4e00\u4e2a\u5386\u53f2\u5bf9\u8c61\u7684\u5411\u91cf\uff0c\u5728\u6211\u4eec\u8d1f\u8d23\u7684\u90a3\u4e9b\u5355\u5143\u683c\u4e0a\u7684\u6bcf\u4e2a\u6b63\u4ea4\u70b9\u90fd\u6709\u4e00\u4e2a\uff08\u4e5f\u5c31\u662f\u8bf4\uff0c\u6211\u4eec\u4e0d\u4e3a\u5176\u4ed6\u5904\u7406\u5668\u62e5\u6709\u7684\u5355\u5143\u683c\u4e0a\u7684\u6b63\u4ea4\u70b9\u5b58\u50a8\u5386\u53f2\u6570\u636e\uff09\u3002\u8bf7\u6ce8\u610f\uff0c\u6211\u4eec\u53ef\u4ee5\u50cf\u5728  step-44  \u4e2d\u90a3\u6837\u4f7f\u7528 CellDataStorage \u7c7b\u6765\u4ee3\u66ff\u6211\u4eec\u81ea\u5df1\u5b58\u50a8\u548c\u7ba1\u7406\u8fd9\u4e9b\u6570\u636e\u3002\u7136\u800c\uff0c\u4e3a\u4e86\u6f14\u793a\u7684\u76ee\u7684\uff0c\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0c\u6211\u4eec\u624b\u52a8\u7ba1\u7406\u5b58\u50a8\u3002\n\n    std::vector<PointHistory<dim>> quadrature_point_history; \n\n// \u8fd9\u4e2a\u5bf9\u8c61\u7684\u8bbf\u95ee\u65b9\u5f0f\u662f\u901a\u8fc7\u6bcf\u4e2a\u5355\u5143\u683c\u3001\u9762\u6216\u8fb9\u6301\u6709\u7684 <code>user pointer</code> \uff1a\u5b83\u662f\u4e00\u4e2a <code>void*</code> \u6307\u9488\uff0c\u53ef\u4ee5\u88ab\u5e94\u7528\u7a0b\u5e8f\u7528\u6765\u5c06\u4efb\u610f\u7684\u6570\u636e\u4e0e\u5355\u5143\u683c\u3001\u9762\u6216\u8fb9\u8054\u7cfb\u8d77\u6765\u3002\u7a0b\u5e8f\u5bf9\u8fd9\u4e9b\u6570\u636e\u7684\u5b9e\u9645\u64cd\u4f5c\u5c5e\u4e8e\u81ea\u5df1\u7684\u804c\u8d23\u8303\u56f4\uff0c\u5e93\u53ea\u662f\u4e3a\u8fd9\u4e9b\u6307\u9488\u5206\u914d\u4e86\u4e00\u4e9b\u7a7a\u95f4\uff0c\u800c\u5e94\u7528\u7a0b\u5e8f\u53ef\u4ee5\u8bbe\u7f6e\u548c\u8bfb\u53d6\u8fd9\u4e9b\u5bf9\u8c61\u4e2d\u7684\u6bcf\u4e2a\u6307\u9488\u3002\n\n// \u8fdb\u4e00\u6b65\u8bf4\uff1a\u6211\u4eec\u9700\u8981\u5f85\u89e3\u7684\u7ebf\u6027\u7cfb\u7edf\u7684\u5bf9\u8c61\uff0c\u5373\u77e9\u9635\u3001\u53f3\u624b\u8fb9\u7684\u5411\u91cf\u548c\u89e3\u5411\u91cf\u3002\u7531\u4e8e\u6211\u4eec\u9884\u8ba1\u8981\u89e3\u51b3\u5927\u95ee\u9898\uff0c\u6211\u4eec\u4f7f\u7528\u4e86\u4e0e step-17 \u4e2d\u76f8\u540c\u7684\u7c7b\u578b\uff0c\u5373\u5efa\u7acb\u5728PETSc\u5e93\u4e4b\u4e0a\u7684\u5206\u5e03\u5f0f%\u5e76\u884c\u77e9\u9635\u548c\u5411\u91cf\u3002\u65b9\u4fbf\u7684\u662f\uff0c\u5b83\u4eec\u4e5f\u53ef\u4ee5\u5728\u53ea\u5728\u4e00\u53f0\u673a\u5668\u4e0a\u8fd0\u884c\u65f6\u4f7f\u7528\uff0c\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0c\u8fd9\u53f0\u673a\u5668\u6b63\u597d\u662f\u6211\u4eec\u7684%\u5e76\u884c\u5b87\u5b99\u4e2d\u552f\u4e00\u7684\u673a\u5668\u3002\n\n// \u7136\u800c\uff0c\u4e0e step-17 \u4e0d\u540c\u7684\u662f\uff0c\u6211\u4eec\u4e0d\u4ee5\u5206\u5e03\u5f0f\u65b9\u5f0f\u5b58\u50a8\u89e3\u5411\u91cf--\u8fd9\u91cc\u662f\u5728\u6bcf\u4e2a\u65f6\u95f4\u6b65\u9aa4\u4e2d\u8ba1\u7b97\u7684\u589e\u91cf\u4f4d\u79fb\u3002\u4e5f\u5c31\u662f\u8bf4\uff0c\u5728\u8ba1\u7b97\u65f6\u5b83\u5f53\u7136\u5fc5\u987b\u662f\u4e00\u4e2a\u5206\u5e03\u5f0f\u77e2\u91cf\uff0c\u4f46\u7d27\u63a5\u7740\u6211\u4eec\u786e\u4fdd\u6bcf\u4e2a\u5904\u7406\u5668\u90fd\u6709\u4e00\u4e2a\u5b8c\u6574\u7684\u526f\u672c\u3002\u539f\u56e0\u662f\u6211\u4eec\u5df2\u7ecf\u5728 step-17 \u4e2d\u770b\u5230\uff0c\u8bb8\u591a\u51fd\u6570\u9700\u8981\u4e00\u4e2a\u5b8c\u6574\u7684\u526f\u672c\u3002\u867d\u7136\u5f97\u5230\u5b83\u5e76\u4e0d\u96be\uff0c\u4f46\u8fd9\u9700\u8981\u5728\u7f51\u7edc\u4e0a\u8fdb\u884c\u901a\u4fe1\uff0c\u56e0\u6b64\u5f88\u6162\u3002\u6b64\u5916\uff0c\u8fd9\u4e9b\u90fd\u662f\u91cd\u590d\u7684\u76f8\u540c\u64cd\u4f5c\uff0c\u8fd9\u5f53\u7136\u662f\u4e0d\u53ef\u53d6\u7684\uff0c\u9664\u975e\u4e0d\u5fc5\u603b\u662f\u5b58\u50a8\u6574\u4e2a\u5411\u91cf\u7684\u6536\u76ca\u8d85\u8fc7\u4e86\u5b83\u3002\u5728\u7f16\u5199\u8fd9\u4e2a\u7a0b\u5e8f\u65f6\uff0c\u4e8b\u5b9e\u8bc1\u660e\uff0c\u6211\u4eec\u5728\u5f88\u591a\u5730\u65b9\u90fd\u9700\u8981\u4e00\u4efd\u5b8c\u6574\u7684\u89e3\u51b3\u65b9\u6848\uff0c\u4ee5\u81f3\u4e8e\u53ea\u5728\u5fc5\u8981\u65f6\u624d\u83b7\u5f97\u5b83\u4f3c\u4e4e\u4e0d\u503c\u5f97\u3002\u76f8\u53cd\uff0c\u6211\u4eec\u9009\u62e9\u4e00\u52b3\u6c38\u9038\u5730\u83b7\u5f97\u5b8c\u6574\u7684\u526f\u672c\uff0c\u800c\u7acb\u5373\u6446\u8131\u5206\u6563\u7684\u526f\u672c\u3002\u56e0\u6b64\uff0c\u8bf7\u6ce8\u610f\uff0c <code>incremental_displacement</code> \u7684\u58f0\u660e\u5e76\u6ca1\u6709\u50cf\u4e2d\u95f4\u547d\u540d\u7a7a\u95f4 <code>MPI</code> \u6240\u8868\u793a\u7684\u90a3\u6837\uff0c\u8868\u793a\u4e00\u4e2a\u5206\u5e03\u5f0f\u5411\u91cf\u3002\n\n    PETScWrappers::MPI::SparseMatrix system_matrix; \n\n    PETScWrappers::MPI::Vector system_rhs; \n\n    Vector<double> incremental_displacement; \n\n// \u63a5\u4e0b\u6765\u7684\u53d8\u91cf\u5757\u4e0e\u95ee\u9898\u7684\u65f6\u95f4\u4f9d\u8d56\u6027\u6709\u5173\uff1a\u5b83\u4eec\u8868\u793a\u6211\u4eec\u8981\u6a21\u62df\u7684\u65f6\u95f4\u95f4\u9694\u7684\u957f\u5ea6\uff0c\u73b0\u5728\u7684\u65f6\u95f4\u548c\u65f6\u95f4\u6b65\u6570\uff0c\u4ee5\u53ca\u73b0\u5728\u65f6\u95f4\u6b65\u6570\u7684\u957f\u5ea6\u3002\n\n    double       present_time; \n    double       present_timestep; \n    double       end_time; \n    unsigned int timestep_no; \n\n// \u7136\u540e\u662f\u51e0\u4e2a\u4e0e%\u5e76\u884c\u5904\u7406\u6709\u5173\u7684\u53d8\u91cf\uff1a\u9996\u5148\uff0c\u4e00\u4e2a\u53d8\u91cf\u8868\u793a\u6211\u4eec\u4f7f\u7528\u7684MPI\u901a\u4fe1\u5668\uff0c\u7136\u540e\u662f\u4e24\u4e2a\u6570\u5b57\uff0c\u544a\u8bc9\u6211\u4eec\u6709\u591a\u5c11\u4e2a\u53c2\u4e0e\u7684\u5904\u7406\u5668\uff0c\u4ee5\u53ca\u6211\u4eec\u5728\u8fd9\u4e2a\u4e16\u754c\u4e0a\u7684\u4f4d\u7f6e\u3002\u6700\u540e\uff0c\u4e00\u4e2a\u6d41\u5bf9\u8c61\uff0c\u786e\u4fdd\u53ea\u6709\u4e00\u4e2a\u5904\u7406\u5668\u5b9e\u9645\u4ea7\u751f\u8f93\u51fa\u5230\u63a7\u5236\u53f0\u3002\u8fd9\u4e0e  step-17  \u4e2d\u7684\u6240\u6709\u5185\u5bb9\u76f8\u540c\u3002\n\n    MPI_Comm mpi_communicator; \n\n    const unsigned int n_mpi_processes; \n\n    const unsigned int this_mpi_process; \n\n    ConditionalOStream pcout; \n\n// \u6211\u4eec\u6b63\u5728\u5b58\u50a8\u672c\u5730\u62e5\u6709\u7684\u548c\u672c\u5730\u76f8\u5173\u7684\u7d22\u5f15\u3002\n\n    IndexSet locally_owned_dofs; \n    IndexSet locally_relevant_dofs; \n\n// \u6700\u540e\uff0c\u6211\u4eec\u6709\u4e00\u4e2a\u9759\u6001\u53d8\u91cf\uff0c\u8868\u793a\u5e94\u529b\u548c\u5e94\u53d8\u4e4b\u95f4\u7684\u7ebf\u6027\u5173\u7cfb\u3002\u7531\u4e8e\u5b83\u662f\u4e00\u4e2a\u4e0d\u4f9d\u8d56\u4efb\u4f55\u8f93\u5165\u7684\u5e38\u91cf\u5bf9\u8c61\uff08\u81f3\u5c11\u5728\u8fd9\u4e2a\u7a0b\u5e8f\u4e2d\u4e0d\u4f9d\u8d56\uff09\uff0c\u6211\u4eec\u628a\u5b83\u4f5c\u4e3a\u4e00\u4e2a\u9759\u6001\u53d8\u91cf\uff0c\u5e76\u5c06\u5728\u6211\u4eec\u5b9a\u4e49\u8fd9\u4e2a\u7c7b\u7684\u6784\u9020\u51fd\u6570\u7684\u540c\u4e00\u4e2a\u5730\u65b9\u521d\u59cb\u5316\u5b83\u3002\n\n    static const SymmetricTensor<4, dim> stress_strain_tensor; \n  }; \n// @sect3{The <code>BodyForce</code> class}  \n\n// \u5728\u6211\u4eec\u8fdb\u5165\u8fd9\u4e2a\u7a0b\u5e8f\u7684\u4e3b\u8981\u529f\u80fd\u4e4b\u524d\uff0c\u6211\u4eec\u5fc5\u987b\u5b9a\u4e49\u54ea\u4e9b\u529b\u5c06\u4f5c\u7528\u5728\u6211\u4eec\u60f3\u8981\u7814\u7a76\u7684\u53d8\u5f62\u7684\u4f53\u4e0a\u3002\u8fd9\u4e9b\u529b\u53ef\u4ee5\u662f\u4f53\u529b\uff0c\u4e5f\u53ef\u4ee5\u662f\u8fb9\u754c\u529b\u3002\u4f53\u529b\u901a\u5e38\u662f\u7531\u56db\u79cd\u57fa\u672c\u7684\u7269\u7406\u529b\u7c7b\u578b\u4e4b\u4e00\u6240\u4ecb\u5bfc\u7684\uff1a\u91cd\u529b\u3001\u5f3a\u5f31\u76f8\u4e92\u4f5c\u7528\u548c\u7535\u78c1\u529b\u3002\u9664\u975e\u4eba\u4eec\u60f3\u8003\u8651\u4e9a\u539f\u5b50\u7269\u4f53\uff08\u5bf9\u4e8e\u8fd9\u4e9b\u7269\u4f53\uff0c\u65e0\u8bba\u5982\u4f55\u51c6\u9759\u6001\u53d8\u5f62\u662f\u4e0d\u76f8\u5173\u7684\uff0c\u4e5f\u662f\u4e0d\u5408\u9002\u7684\u63cf\u8ff0\uff09\uff0c\u5426\u5219\u53ea\u9700\u8981\u8003\u8651\u5f15\u529b\u548c\u7535\u78c1\u529b\u3002\u4e3a\u4e86\u7b80\u5355\u8d77\u89c1\uff0c\u8ba9\u6211\u4eec\u5047\u8bbe\u6211\u4eec\u7684\u8eab\u4f53\u6709\u4e00\u5b9a\u7684\u8d28\u91cf\u5bc6\u5ea6\uff0c\u4f46\u8981\u4e48\u662f\u975e\u78c1\u6027\u7684\uff0c\u4e0d\u5bfc\u7535\u7684\uff0c\u8981\u4e48\u5468\u56f4\u6ca1\u6709\u660e\u663e\u7684\u7535\u78c1\u573a\u3002\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0c\u8eab\u4f53\u7684\u529b\u53ea\u662f <code>rho g</code>, where <code>rho</code> \u662f\u6750\u6599\u5bc6\u5ea6\uff0c <code>g</code> \u662f\u4e00\u4e2a\u8d1fZ\u65b9\u5411\u7684\u77e2\u91cf\uff0c\u5927\u5c0f\u4e3a9.81\u7c73/\u79d2^2\u3002 \u5bc6\u5ea6\u548c <code>g</code> \u90fd\u662f\u5728\u51fd\u6570\u4e2d\u5b9a\u4e49\u7684\uff0c\u6211\u4eec\u628a7700 kg/m^3\u4f5c\u4e3a\u5bc6\u5ea6\uff0c\u8fd9\u662f\u5bf9\u94a2\u6750\u901a\u5e38\u5047\u5b9a\u7684\u503c\u3002\n\n// \u4e3a\u4e86\u66f4\u666e\u904d\u4e00\u70b9\uff0c\u4e5f\u4e3a\u4e86\u80fd\u591f\u57282d\u4e2d\u8fdb\u884c\u8ba1\u7b97\uff0c\u6211\u4eec\u610f\u8bc6\u5230\u4f53\u529b\u603b\u662f\u4e00\u4e2a\u8fd4\u56de <code>dim</code> \u7ef4\u77e2\u91cf\u7684\u51fd\u6570\u3002\u6211\u4eec\u5047\u8bbe\u91cd\u529b\u6cbf\u7740\u6700\u540e\u4e00\u4e2a\uff0c\u5373 <code>dim-1</code> \u4e2a\u5750\u6807\u7684\u8d1f\u65b9\u5411\u4f5c\u7528\u3002\u8003\u8651\u5230\u4ee5\u524d\u7684\u4f8b\u5b50\u7a0b\u5e8f\u4e2d\u7684\u7c7b\u4f3c\u5b9a\u4e49\uff0c\u8fd9\u4e2a\u51fd\u6570\u7684\u5176\u4f59\u5b9e\u73b0\u5e94\u8be5\u5927\u90e8\u5206\u662f\u4e0d\u8a00\u81ea\u660e\u7684\u3002\u8bf7\u6ce8\u610f\uff0c\u8eab\u4f53\u7684\u529b\u91cf\u4e0e\u4f4d\u7f6e\u65e0\u5173\uff1b\u4e3a\u4e86\u907f\u514d\u7f16\u8bd1\u5668\u5bf9\u672a\u4f7f\u7528\u7684\u51fd\u6570\u53c2\u6570\u53d1\u51fa\u8b66\u544a\uff0c\u6211\u4eec\u56e0\u6b64\u6ce8\u91ca\u4e86 <code>vector_value</code> \u51fd\u6570\u7684\u7b2c\u4e00\u4e2a\u53c2\u6570\u7684\u540d\u79f0\u3002\n\n  template <int dim> \n  class BodyForce : public Function<dim> \n  { \n  public: \n    BodyForce(); \n\n    virtual void vector_value(const Point<dim> &p, \n                              Vector<double> &  values) const override; \n\n    virtual void \n    vector_value_list(const std::vector<Point<dim>> &points, \n                      std::vector<Vector<double>> &  value_list) const override; \n  }; \n\n  template <int dim> \n  BodyForce<dim>::BodyForce() \n    : Function<dim>(dim) \n  {} \n\n  template <int dim> \n  inline void BodyForce<dim>::vector_value(const Point<dim> & /*p*/, \n                                           Vector<double> &values) const \n  { \n    Assert(values.size() == dim, ExcDimensionMismatch(values.size(), dim)); \n\n    const double g   = 9.81; \n    const double rho = 7700; \n\n    values          = 0; \n    values(dim - 1) = -rho * g; \n  } \n\n  template <int dim> \n  void BodyForce<dim>::vector_value_list( \n    const std::vector<Point<dim>> &points, \n    std::vector<Vector<double>> &  value_list) const \n  { \n    const unsigned int n_points = points.size(); \n\n    Assert(value_list.size() == n_points, \n           ExcDimensionMismatch(value_list.size(), n_points)); \n\n    for (unsigned int p = 0; p < n_points; ++p) \n      BodyForce<dim>::vector_value(points[p], value_list[p]); \n  } \n\n//  @sect3{The <code>IncrementalBoundaryValue</code> class}  \n\n// \u9664\u4e86\u8eab\u4f53\u7684\u529b\u4e4b\u5916\uff0c\u8fd0\u52a8\u8fd8\u53ef\u4ee5\u7531\u8fb9\u754c\u529b\u548c\u5f3a\u5236\u8fb9\u754c\u4f4d\u79fb\u5f15\u8d77\u3002\u540e\u4e00\u79cd\u60c5\u51b5\u76f8\u5f53\u4e8e\u4ee5\u8fd9\u6837\u7684\u65b9\u5f0f\u9009\u62e9\u529b\uff0c\u4f7f\u5176\u8bf1\u53d1\u67d0\u79cd\u4f4d\u79fb\u3002\n\n// \u5bf9\u4e8e\u51c6\u9759\u6001\u4f4d\u79fb\uff0c\u5178\u578b\u7684\u8fb9\u754c\u529b\u662f\u5bf9\u4e00\u4e2a\u4f53\u7684\u538b\u529b\uff0c\u6216\u8005\u5bf9\u53e6\u4e00\u4e2a\u4f53\u7684\u5207\u5411\u6469\u64e6\u3002\u6211\u4eec\u5728\u8fd9\u91cc\u9009\u62e9\u4e86\u4e00\u79cd\u66f4\u7b80\u5355\u7684\u60c5\u51b5\uff1a\u6211\u4eec\u89c4\u5b9a\u4e86\u8fb9\u754c\uff08\u90e8\u5206\uff09\u7684\u67d0\u79cd\u8fd0\u52a8\uff0c\u6216\u8005\u81f3\u5c11\u662f\u4f4d\u79fb\u77e2\u91cf\u7684\u67d0\u4e9b\u5206\u91cf\u3002\u6211\u4eec\u7528\u53e6\u4e00\u4e2a\u77e2\u91cf\u503c\u51fd\u6570\u6765\u63cf\u8ff0\uff0c\u5bf9\u4e8e\u8fb9\u754c\u4e0a\u7684\u67d0\u4e00\u70b9\uff0c\u8fd4\u56de\u89c4\u5b9a\u7684\u4f4d\u79fb\u3002\n\n// \u7531\u4e8e\u6211\u4eec\u6709\u4e00\u4e2a\u968f\u65f6\u95f4\u53d8\u5316\u7684\u95ee\u9898\uff0c\u8fb9\u754c\u7684\u4f4d\u79fb\u589e\u91cf\u7b49\u4e8e\u5728\u65f6\u95f4\u6bb5\u5185\u7d2f\u79ef\u7684\u4f4d\u79fb\u3002\u56e0\u6b64\uff0c\u8be5\u7c7b\u5fc5\u987b\u540c\u65f6\u77e5\u9053\u5f53\u524d\u65f6\u95f4\u548c\u5f53\u524d\u65f6\u95f4\u6b65\u957f\uff0c\u7136\u540e\u53ef\u4ee5\u5c06\u4f4d\u79fb\u589e\u91cf\u8fd1\u4f3c\u4e3a\u5f53\u524d\u901f\u5ea6\u4e58\u4ee5\u5f53\u524d\u65f6\u95f4\u6b65\u957f\u3002\n\n// \u5728\u672c\u7a0b\u5e8f\u4e2d\uff0c\u6211\u4eec\u9009\u62e9\u4e86\u4e00\u79cd\u7b80\u5355\u7684\u8fb9\u754c\u4f4d\u79fb\u5f62\u5f0f\uff1a\u6211\u4eec\u4ee5\u6052\u5b9a\u7684\u901f\u5ea6\u5411\u4e0b\u4f4d\u79fb\u9876\u90e8\u7684\u8fb9\u754c\u3002\u8fb9\u754c\u7684\u5176\u4f59\u90e8\u5206\u8981\u4e48\u662f\u56fa\u5b9a\u7684\uff08\u7136\u540e\u7528\u4e00\u4e2a <code>Functions::ZeroFunction</code> \u7c7b\u578b\u7684\u5bf9\u8c61\u6765\u63cf\u8ff0\uff09\uff0c\u8981\u4e48\u662f\u81ea\u7531\u7684\uff08Neumann\u7c7b\u578b\uff0c\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\u4e0d\u9700\u8981\u505a\u4efb\u4f55\u7279\u6b8a\u7684\u4e8b\u60c5\uff09\u3002 \u5229\u7528\u6211\u4eec\u5728\u524d\u9762\u6240\u6709\u7684\u4f8b\u5b50\u7a0b\u5e8f\u4e2d\u83b7\u5f97\u7684\u77e5\u8bc6\uff0c\u63cf\u8ff0\u6301\u7eed\u5411\u4e0b\u8fd0\u52a8\u7684\u7c7b\u7684\u5b9e\u73b0\u5e94\u8be5\u662f\u5f88\u660e\u663e\u7684\u3002\n\n  template <int dim> \n  class IncrementalBoundaryValues : public Function<dim> \n  { \n  public: \n    IncrementalBoundaryValues(const double present_time, \n                              const double present_timestep); \n\n    virtual void vector_value(const Point<dim> &p, \n                              Vector<double> &  values) const override; \n\n    virtual void \n    vector_value_list(const std::vector<Point<dim>> &points, \n                      std::vector<Vector<double>> &  value_list) const override; \n\n  private: \n    const double velocity; \n    const double present_time; \n    const double present_timestep; \n  }; \n\n  template <int dim> \n  IncrementalBoundaryValues<dim>::IncrementalBoundaryValues( \n    const double present_time, \n    const double present_timestep) \n    : Function<dim>(dim) \n    , velocity(.08) \n    , present_time(present_time) \n    , present_timestep(present_timestep) \n  {} \n\n  template <int dim> \n  void \n  IncrementalBoundaryValues<dim>::vector_value(const Point<dim> & /*p*/, \n                                               Vector<double> &values) const \n  { \n    Assert(values.size() == dim, ExcDimensionMismatch(values.size(), dim)); \n\n    values    = 0; \n    values(2) = -present_timestep * velocity; \n  } \n\n  template <int dim> \n  void IncrementalBoundaryValues<dim>::vector_value_list( \n    const std::vector<Point<dim>> &points, \n    std::vector<Vector<double>> &  value_list) const \n  { \n    const unsigned int n_points = points.size(); \n\n    Assert(value_list.size() == n_points, \n           ExcDimensionMismatch(value_list.size(), n_points)); \n\n    for (unsigned int p = 0; p < n_points; ++p) \n      IncrementalBoundaryValues<dim>::vector_value(points[p], value_list[p]); \n  } \n\n//  @sect3{Implementation of the <code>TopLevel</code> class}  \n\n// \u73b0\u5728\u662f\u4e3b\u7c7b\u7684\u5b9e\u73b0\u3002\u9996\u5148\uff0c\u6211\u4eec\u521d\u59cb\u5316\u5e94\u529b\u5e94\u53d8\u5f20\u91cf\uff0c\u6211\u4eec\u5c06\u5176\u58f0\u660e\u4e3a\u4e00\u4e2a\u9759\u6001\u5e38\u91cf\u53d8\u91cf\u3002\u6211\u4eec\u9009\u62e9\u4e86\u9002\u5408\u4e8e\u94a2\u94c1\u7684Lam&eacute;\u5e38\u6570\u3002\n\n  template <int dim> \n  const SymmetricTensor<4, dim> TopLevel<dim>::stress_strain_tensor = \n    get_stress_strain_tensor<dim>(\n      /*lambda = */ 9.695e10, \n      /*mu =  */  7.617e10)\n\n//  @sect4{The public interface}  \n\n// \u4e0b\u4e00\u6b65\u662f\u6784\u9020\u51fd\u6570\u548c\u6790\u6784\u51fd\u6570\u7684\u5b9a\u4e49\u3002\u8fd9\u91cc\u6ca1\u6709\u4ec0\u4e48\u60ca\u559c\uff1a\u6211\u4eec\u4e3a\u89e3\u7684\u6bcf\u4e2a <code>dim</code> \u77e2\u91cf\u5206\u91cf\u9009\u62e9\u7ebf\u6027\u548c\u8fde\u7eed\u7684\u6709\u9650\u5143\uff0c\u4ee5\u53ca\u6bcf\u4e2a\u5750\u6807\u65b9\u5411\u4e0a\u67092\u4e2a\u70b9\u7684\u9ad8\u65af\u6b63\u4ea4\u516c\u5f0f\u3002\u89e3\u6784\u5668\u5e94\u8be5\u662f\u663e\u800c\u6613\u89c1\u7684\u3002\n\n  template <int dim> \n  TopLevel<dim>::TopLevel() \n    : triangulation(MPI_COMM_WORLD) \n    , fe(FE_Q<dim>(1), dim) \n    , dof_handler(triangulation) \n    , quadrature_formula(fe.degree + 1) \n    , present_time(0.0) \n    , present_timestep(1.0) \n    , end_time(10.0) \n    , timestep_no(0) \n    , mpi_communicator(MPI_COMM_WORLD) \n    , n_mpi_processes(Utilities::MPI::n_mpi_processes(mpi_communicator)) \n    , this_mpi_process(Utilities::MPI::this_mpi_process(mpi_communicator)) \n    , pcout(std::cout, this_mpi_process == 0) \n  {} \n\n  template <int dim> \n  TopLevel<dim>::~TopLevel() \n  { \n    dof_handler.clear(); \n  } \n\n// \u6700\u540e\u4e00\u4e2a\u516c\u5171\u51fd\u6570\u662f\u6307\u5bfc\u6240\u6709\u5de5\u4f5c\u7684\u51fd\u6570\uff0c  <code>run()</code>  \u3002\u5b83\u521d\u59cb\u5316\u4e86\u63cf\u8ff0\u6211\u4eec\u76ee\u524d\u6240\u5904\u65f6\u95f4\u4f4d\u7f6e\u7684\u53d8\u91cf\uff0c\u7136\u540e\u8fd0\u884c\u7b2c\u4e00\u4e2a\u65f6\u95f4\u6b65\u9aa4\uff0c\u518d\u5faa\u73af\u6240\u6709\u5176\u4ed6\u65f6\u95f4\u6b65\u9aa4\u3002\u8bf7\u6ce8\u610f\uff0c\u4e3a\u4e86\u7b80\u5355\u8d77\u89c1\uff0c\u6211\u4eec\u4f7f\u7528\u4e00\u4e2a\u56fa\u5b9a\u7684\u65f6\u95f4\u6b65\u957f\uff0c\u800c\u4e00\u4e2a\u66f4\u590d\u6742\u7684\u7a0b\u5e8f\u5f53\u7136\u8981\u4ee5\u67d0\u79cd\u66f4\u5408\u7406\u7684\u65b9\u5f0f\u81ea\u9002\u5e94\u5730\u9009\u62e9\u5b83\u3002\n\n  template <int dim> \n  void TopLevel<dim>::run() \n  { \n    do_initial_timestep(); \n\n    while (present_time < end_time) \n      do_timestep(); \n  } \n// @sect4{TopLevel::create_coarse_grid}  \n\n// \u6309\u7167\u4e0a\u9762\u58f0\u660e\u7684\u987a\u5e8f\uff0c\u4e0b\u4e00\u4e2a\u51fd\u6570\u662f\u521b\u5efa\u7c97\u7565\u7f51\u683c\u7684\u51fd\u6570\uff0c\u6211\u4eec\u4ece\u8fd9\u91cc\u5f00\u59cb\u3002\u5728\u8fd9\u4e2a\u793a\u4f8b\u7a0b\u5e8f\u4e2d\uff0c\u6211\u4eec\u60f3\u8ba1\u7b97\u4e00\u4e2a\u5706\u67f1\u4f53\u5728\u8f74\u5411\u538b\u7f29\u4e0b\u7684\u53d8\u5f62\u3002\u56e0\u6b64\u7b2c\u4e00\u6b65\u662f\u751f\u6210\u4e00\u4e2a\u957f\u5ea6\u4e3a3\uff0c\u5185\u5916\u534a\u5f84\u5206\u522b\u4e3a0.8\u548c1\u7684\u5706\u67f1\u4f53\u7684\u7f51\u683c\u3002\u5e78\u8fd0\u7684\u662f\uff0c\u6709\u4e00\u4e2a\u5e93\u51fd\u6570\u53ef\u4ee5\u751f\u6210\u8fd9\u6837\u7684\u7f51\u683c\u3002\n\n// \u5728\u7b2c\u4e8c\u6b65\u4e2d\uff0c\u6211\u4eec\u5fc5\u987b\u5728\u5706\u67f1\u4f53\u7684\u4e0a\u8868\u9762\u548c\u4e0b\u8868\u9762\u5173\u8054\u8fb9\u754c\u6761\u4ef6\u3002\u6211\u4eec\u4e3a\u8fb9\u754c\u9762\u9009\u62e9\u4e00\u4e2a\u8fb9\u754c\u6307\u793a\u56680\uff0c\u8fd9\u4e9b\u8fb9\u754c\u9762\u7684\u4e2d\u70b9\u7684Z\u5750\u6807\u4e3a0\uff08\u5e95\u9762\uff09\uff0cZ=3\u7684\u6307\u793a\u5668\u4e3a1\uff08\u9876\u9762\uff09\uff1b\u6700\u540e\uff0c\u6211\u4eec\u5bf9\u5706\u67f1\u4f53\u5916\u58f3\u5185\u90e8\u7684\u6240\u6709\u9762\u4f7f\u7528\u8fb9\u754c\u6307\u793a\u56682\uff0c\u5916\u90e8\u4f7f\u75283\u3002\n\n  template <int dim> \n  void TopLevel<dim>::create_coarse_grid() \n  { \n    const double inner_radius = 0.8, outer_radius = 1; \n    GridGenerator::cylinder_shell(triangulation, 3, inner_radius, outer_radius); \n    for (const auto &cell : triangulation.active_cell_iterators()) \n      for (const auto &face : cell->face_iterators()) \n        if (face->at_boundary()) \n          { \n            const Point<dim> face_center = face->center(); \n\n            if (face_center[2] == 0) \n              face->set_boundary_id(0); \n            else if (face_center[2] == 3) \n              face->set_boundary_id(1); \n            else if (std::sqrt(face_center[0] * face_center[0] + \n                               face_center[1] * face_center[1]) < \n                     (inner_radius + outer_radius) / 2) \n              face->set_boundary_id(2); \n            else \n              face->set_boundary_id(3); \n          } \n\n// \u4e00\u65e6\u5b8c\u6210\u4e86\u8fd9\u4e9b\uff0c\u6211\u4eec\u5c31\u53ef\u4ee5\u5bf9\u7f51\u683c\u8fdb\u884c\u4e00\u6b21\u5168\u9762\u7684\u7ec6\u5316\u3002\n\n    triangulation.refine_global(1); \n\n// \u4f5c\u4e3a\u6700\u540e\u4e00\u6b65\uff0c\u6211\u4eec\u9700\u8981\u8bbe\u7f6e\u4e00\u4e2a\u5e72\u51c0\u7684\u6570\u636e\u72b6\u6001\uff0c\u6211\u4eec\u5c06\u8fd9\u4e9b\u6570\u636e\u5b58\u50a8\u5728\u76ee\u524d\u5904\u7406\u5668\u4e0a\u5904\u7406\u7684\u6240\u6709\u5355\u5143\u7684\u6b63\u4ea4\u70b9\u4e2d\u3002\n\n    setup_quadrature_point_history(); \n  } \n\n//  @sect4{TopLevel::setup_system}  \n\n// \u4e0b\u4e00\u4e2a\u51fd\u6570\u662f\u4e3a\u4e00\u4e2a\u7ed9\u5b9a\u7684\u7f51\u683c\u8bbe\u7f6e\u6570\u636e\u7ed3\u6784\u3002\u8fd9\u4e0e step-17 \u4e2d\u7684\u65b9\u6cd5\u57fa\u672c\u76f8\u540c\uff1a\u5206\u914d\u81ea\u7531\u5ea6\uff0c\u7136\u540e\u5bf9\u8fd9\u4e9b\u81ea\u7531\u5ea6\u8fdb\u884c\u6392\u5e8f\uff0c\u4f7f\u6bcf\u4e2a\u5904\u7406\u5668\u5f97\u5230\u4e00\u4e2a\u8fde\u7eed\u7684\u5757\u3002\u8bf7\u6ce8\u610f\uff0c\u6bcf\u4e2a\u5904\u7406\u5668\u7684\u7ec6\u5206\u5757\u662f\u5728\u521b\u5efa\u6216\u5b8c\u5584\u7f51\u683c\u7684\u51fd\u6570\u4e2d\u5904\u7406\u7684\uff0c\u4e0e\u4e4b\u524d\u7684\u4f8b\u5b50\u7a0b\u5e8f\u4e0d\u540c\uff08\u53d1\u751f\u8fd9\u79cd\u60c5\u51b5\u7684\u65f6\u95f4\u70b9\u4e3b\u8981\u662f\u53e3\u5473\u95ee\u9898\uff1b\u5728\u8fd9\u91cc\uff0c\u6211\u4eec\u9009\u62e9\u5728\u521b\u5efa\u7f51\u683c\u65f6\u8fdb\u884c\uff0c\u56e0\u4e3a\u5728 <code>do_initial_timestep</code> \u548c <code>do_timestep</code> \u51fd\u6570\u4e2d\uff0c\u6211\u4eec\u60f3\u5728\u8fd8\u6ca1\u6709\u8c03\u7528\u5f53\u524d\u51fd\u6570\u7684\u65f6\u5019\u8f93\u51fa\u6bcf\u4e2a\u5904\u7406\u5668\u4e0a\u7684\u5355\u5143\u6570\u91cf\uff09\u3002\n\n  template <int dim> \n  void TopLevel<dim>::setup_system() \n  { \n    dof_handler.distribute_dofs(fe); \n    locally_owned_dofs = dof_handler.locally_owned_dofs(); \n    DoFTools::extract_locally_relevant_dofs(dof_handler, locally_relevant_dofs); \n\n// \u4e0b\u4e00\u6b65\u662f\u8bbe\u7f6e\u7531\u4e8e\u60ac\u6302\u8282\u70b9\u800c\u4ea7\u751f\u7684\u7ea6\u675f\u3002\u8fd9\u5728\u4ee5\u524d\u5df2\u7ecf\u5904\u7406\u8fc7\u5f88\u591a\u6b21\u4e86\u3002\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// \u7136\u540e\u6211\u4eec\u8981\u8bbe\u7f6e\u77e9\u9635\u3002\u8fd9\u91cc\u6211\u4eec\u504f\u79bb\u4e86  step-17  \uff0c\u5728\u90a3\u91cc\u6211\u4eec\u7b80\u5355\u5730\u4f7f\u7528\u4e86PETSc\u7684\u80fd\u529b\uff0c\u5373\u53ea\u77e5\u9053\u77e9\u9635\u7684\u5927\u5c0f\uff0c\u968f\u540e\u5206\u914d\u90a3\u4e9b\u88ab\u5199\u5165\u7684\u975e\u96f6\u5143\u7d20\u3002\u867d\u7136\u4ece\u6b63\u786e\u6027\u7684\u89d2\u5ea6\u6765\u770b\uff0c\u8fd9\u6837\u505a\u5f88\u597d\uff0c\u4f46\u662f\u6548\u7387\u5374\u4e0d\u9ad8\uff1a\u5982\u679c\u6211\u4eec\u4e0d\u7ed9PETSc\u63d0\u4f9b\u5173\u4e8e\u54ea\u4e9b\u5143\u7d20\u88ab\u5199\u5165\u7684\u7ebf\u7d22\uff0c\u90a3\u4e48\u5f53\u6211\u4eec\u7b2c\u4e00\u6b21\u8bbe\u7f6e\u77e9\u9635\u4e2d\u7684\u5143\u7d20\u65f6\uff08\u5373\u5728\u7b2c\u4e00\u4e2a\u65f6\u95f4\u6b65\u4e2d\uff09\uff0c\u5b83\u7684\u901f\u5ea6\u4f1a\u6162\u5f97\u4ee4\u4eba\u96be\u4ee5\u5fcd\u53d7\u3002\u540e\u6765\uff0c\u5f53\u5143\u7d20\u88ab\u5206\u914d\u540e\uff0c\u4e00\u5207\u90fd\u5feb\u591a\u4e86\u3002\u5728\u6211\u4eec\u6240\u505a\u7684\u5b9e\u9a8c\u4e2d\uff0c\u5982\u679c\u6211\u4eec\u6307\u793aPETSc\u54ea\u4e9b\u5143\u7d20\u5c06\u88ab\u4f7f\u7528\uff0c\u54ea\u4e9b\u4e0d\u88ab\u4f7f\u7528\uff0c\u90a3\u4e48\u7b2c\u4e00\u4e2a\u65f6\u95f4\u6b65\u9aa4\u53ef\u4ee5\u52a0\u5feb\u8fd1\u4e24\u4e2a\u6570\u91cf\u7ea7\u3002\n\n// \u8981\u505a\u5230\u8fd9\u4e00\u70b9\uff0c\u6211\u4eec\u9996\u5148\u8981\u751f\u6210\u6211\u4eec\u8981\u5904\u7406\u7684\u77e9\u9635\u7684\u7a00\u758f\u6a21\u5f0f\uff0c\u5e76\u786e\u4fdd\u6d53\u7f29\u7684\u60ac\u6302\u8282\u70b9\u7ea6\u675f\u5728\u7a00\u758f\u6a21\u5f0f\u4e2d\u589e\u52a0\u5fc5\u8981\u7684\u989d\u5916\u6761\u76ee\u3002\n\n    DynamicSparsityPattern sparsity_pattern(locally_relevant_dofs); \n    DoFTools::make_sparsity_pattern(dof_handler, \n                                    sparsity_pattern, \n                                    hanging_node_constraints, \n                                    /*\u4fdd\u6301\u7ea6\u675f\u6027dofs  */ false)\n\n    SparsityTools::distribute_sparsity_pattern(sparsity_pattern, \n                                               locally_owned_dofs, \n                                               mpi_communicator, \n                                               locally_relevant_dofs); \n\n// \u6ce8\u610f\uff0c\u6211\u4eec\u5728\u8fd9\u91cc\u4f7f\u7528\u4e86\u5df2\u7ecf\u5728 step-11 \u4e2d\u4ecb\u7ecd\u8fc7\u7684 <code>DynamicSparsityPattern</code> \u7c7b\uff0c\u800c\u4e0d\u662f\u6211\u4eec\u5728\u6240\u6709\u5176\u4ed6\u60c5\u51b5\u4e0b\u4f7f\u7528\u7684 <code>SparsityPattern</code> \u7c7b\u3002\u5176\u539f\u56e0\u662f\uff0c\u4e3a\u4e86\u4f7f\u540e\u4e00\u4e2a\u7c7b\u53d1\u6325\u4f5c\u7528\uff0c\u6211\u4eec\u5fc5\u987b\u7ed9\u6bcf\u4e00\u884c\u7684\u6761\u76ee\u6570\u63d0\u4f9b\u4e00\u4e2a\u521d\u59cb\u7684\u4e0a\u9650\uff0c\u8fd9\u9879\u4efb\u52a1\u4f20\u7edf\u4e0a\u662f\u7531 <code>DoFHandler::max_couplings_between_dofs()</code> \u5b8c\u6210\u3002\u7136\u800c\uff0c\u8fd9\u4e2a\u51fd\u6570\u6709\u4e00\u4e2a\u4e25\u91cd\u7684\u95ee\u9898\uff1a\u5b83\u5fc5\u987b\u8ba1\u7b97\u6bcf\u4e00\u884c\u4e2d\u975e\u96f6\u9879\u7684\u6570\u91cf\u7684\u4e0a\u9650\uff0c\u800c\u8fd9\u662f\u4e00\u4e2a\u76f8\u5f53\u590d\u6742\u7684\u4efb\u52a1\uff0c\u7279\u522b\u662f\u57283D\u4e2d\u3002\u5b9e\u9645\u4e0a\uff0c\u867d\u7136\u5b83\u57282D\u4e2d\u76f8\u5f53\u51c6\u786e\uff0c\u4f46\u57283D\u4e2d\u7ecf\u5e38\u5f97\u51fa\u592a\u5927\u7684\u6570\u5b57\uff0c\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0c <code>SparsityPattern</code> \u4e00\u5f00\u59cb\u5c31\u5206\u914d\u4e86\u592a\u591a\u7684\u5185\u5b58\uff0c\u7ecf\u5e38\u662f\u51e0\u767eMB\u3002\u540e\u6765\u5f53 <code>DoFTools::make_sparsity_pattern</code> \u88ab\u8c03\u7528\u65f6\uff0c\u6211\u4eec\u610f\u8bc6\u5230\u6211\u4eec\u4e0d\u9700\u8981\u90a3\u4e48\u591a\u7684\u5185\u5b58\uff0c\u4f46\u8fd9\u65f6\u5df2\u7ecf\u592a\u665a\u4e86\uff1a\u5bf9\u4e8e\u5927\u95ee\u9898\uff0c\u4e34\u65f6\u5206\u914d\u592a\u591a\u7684\u5185\u5b58\u4f1a\u5bfc\u81f4\u5185\u5b58\u4e0d\u8db3\u7684\u60c5\u51b5\u3002\n\n// \u4e3a\u4e86\u907f\u514d\u8fd9\u79cd\u60c5\u51b5\uff0c\u6211\u4eec\u91c7\u7528\u4e86 <code>DynamicSparsityPattern</code> \u7c7b\uff0c\u8be5\u7c7b\u901f\u5ea6\u8f83\u6162\uff0c\u4f46\u4e0d\u9700\u8981\u9884\u5148\u4f30\u8ba1\u6bcf\u884c\u975e\u96f6\u6761\u76ee\u7684\u6570\u91cf\u3002\u56e0\u6b64\uff0c\u5b83\u5728\u4efb\u4f55\u65f6\u5019\u90fd\u53ea\u5206\u914d\u5b83\u6240\u9700\u8981\u7684\u5185\u5b58\uff0c\u800c\u4e14\u6211\u4eec\u751a\u81f3\u53ef\u4ee5\u4e3a\u5927\u578b\u7684\u4e09\u7ef4\u95ee\u9898\u5efa\u7acb\u5b83\u3002\n\n// \u503c\u5f97\u6ce8\u610f\u7684\u662f\uff0c\u7531\u4e8e parallel::shared::Triangulation, \u7684\u7279\u6b8a\u6027\uff0c\u6211\u4eec\u6784\u5efa\u7684\u7a00\u758f\u6a21\u5f0f\u662f\u5168\u5c40\u7684\uff0c\u5373\u5305\u62ec\u6240\u6709\u7684\u81ea\u7531\u5ea6\uff0c\u65e0\u8bba\u5b83\u4eec\u662f\u5c5e\u4e8e\u6211\u4eec\u6240\u5728\u7684\u5904\u7406\u5668\u8fd8\u662f\u53e6\u4e00\u4e2a\u5904\u7406\u5668\uff08\u5982\u679c\u8fd9\u4e2a\u7a0b\u5e8f\u662f\u901a\u8fc7MPI\u5e76\u884c\u8fd0\u884c\u7684\uff09\u3002\u8fd9\u5f53\u7136\u4e0d\u662f\u6700\u597d\u7684--\u5b83\u9650\u5236\u4e86\u6211\u4eec\u53ef\u4ee5\u89e3\u51b3\u7684\u95ee\u9898\u7684\u89c4\u6a21\uff0c\u56e0\u4e3a\u5728\u6bcf\u4e2a\u5904\u7406\u5668\u4e0a\u5b58\u50a8\u6574\u4e2a\u7a00\u758f\u6a21\u5f0f\uff08\u5373\u4f7f\u53ea\u662f\u77ed\u65f6\u95f4\uff09\u7684\u89c4\u6a21\u5e76\u4e0d\u5927\u3002\u7136\u800c\uff0c\u5728\u7a0b\u5e8f\u4e2d\u8fd8\u6709\u51e0\u4e2a\u5730\u65b9\u6211\u4eec\u662f\u8fd9\u6837\u505a\u7684\uff0c\u4f8b\u5982\uff0c\u6211\u4eec\u603b\u662f\u628a\u5168\u5c40\u4e09\u89d2\u6d4b\u91cf\u548cDoF\u5904\u7406\u5bf9\u8c61\u4fdd\u7559\u5728\u5468\u56f4\uff0c\u5373\u4f7f\u6211\u4eec\u53ea\u5bf9\u5b83\u4eec\u7684\u4e00\u90e8\u5206\u8fdb\u884c\u5de5\u4f5c\u3002\u76ee\u524d\uff0cdeal.II\u6ca1\u6709\u5fc5\u8981\u7684\u8bbe\u65bd\u6765\u5b8c\u5168\u5206\u914d\u8fd9\u4e9b\u5bf9\u8c61\uff08\u4e8b\u5b9e\u4e0a\uff0c\u8fd9\u9879\u4efb\u52a1\u5728\u81ea\u9002\u5e94\u7f51\u683c\u4e2d\u5f88\u96be\u5b9e\u73b0\uff0c\u56e0\u4e3a\u968f\u7740\u7f51\u683c\u7684\u81ea\u9002\u5e94\u7ec6\u5316\uff0c\u9886\u57df\u7684\u5747\u8861\u5206\u533a\u5f80\u5f80\u4f1a\u53d8\u5f97\u4e0d\u5747\u8861\uff09\u3002\n\n// \u6709\u4e86\u8fd9\u4e2a\u6570\u636e\u7ed3\u6784\uff0c\u6211\u4eec\u5c31\u53ef\u4ee5\u8fdb\u5165PETSc\u7a00\u758f\u77e9\u9635\uff0c\u544a\u8bc9\u5b83\u9884\u5148\u5206\u914d\u6240\u6709\u6211\u4eec\u4ee5\u540e\u8981\u5199\u5165\u7684\u6761\u76ee\u3002\n\n    system_matrix.reinit(locally_owned_dofs, \n                         locally_owned_dofs, \n                         sparsity_pattern, \n                         mpi_communicator); \n\n// \u5728\u8fd9\u4e00\u70b9\u4e0a\uff0c\u4e0d\u518d\u9700\u8981\u5bf9\u7a00\u758f\u6a21\u5f0f\u6709\u4efb\u4f55\u660e\u786e\u7684\u4e86\u89e3\uff0c\u6211\u4eec\u53ef\u4ee5\u8ba9 <code>sparsity_pattern</code> \u8fd9\u4e2a\u53d8\u91cf\u79bb\u5f00\u8303\u56f4\uff0c\u4e0d\u4f1a\u6709\u4efb\u4f55\u95ee\u9898\u3002\n\n// \u8fd9\u4e2a\u51fd\u6570\u7684\u6700\u540e\u4e00\u4e2a\u4efb\u52a1\u662f\u5c06\u53f3\u4fa7\u5411\u91cf\u548c\u6c42\u89e3\u5411\u91cf\u91cd\u7f6e\u4e3a\u6b63\u786e\u7684\u5927\u5c0f\uff1b\u8bb0\u4f4f\uff0c\u6c42\u89e3\u5411\u91cf\u662f\u4e00\u4e2a\u672c\u5730\u5411\u91cf\uff0c\u4e0d\u50cf\u53f3\u4fa7\u5411\u91cf\u662f\u4e00\u4e2a\u5206\u5e03\u5f0f\u7684%\u5e76\u884c\u5411\u91cf\uff0c\u56e0\u6b64\u9700\u8981\u77e5\u9053MPI\u901a\u4fe1\u5668\uff0c\u5b83\u5e94\u8be5\u901a\u8fc7\u8fd9\u4e2a\u901a\u4fe1\u5668\u6765\u4f20\u8f93\u6d88\u606f\u3002\n\n    system_rhs.reinit(locally_owned_dofs, mpi_communicator); \n    incremental_displacement.reinit(dof_handler.n_dofs()); \n  } \n\n//  @sect4{TopLevel::assemble_system}  \n\n// \u540c\u6837\uff0c\u7ec4\u88c5\u7cfb\u7edf\u77e9\u9635\u548c\u53f3\u624b\u8fb9\u7684\u7ed3\u6784\u4e0e\u4e4b\u524d\u8bb8\u591a\u4f8b\u5b50\u7a0b\u5e8f\u4e2d\u7684\u7ed3\u6784\u76f8\u540c\u3002\u7279\u522b\u662f\uff0c\u5b83\u4e3b\u8981\u7b49\u540c\u4e8e step-17 \uff0c\u9664\u4e86\u4e0d\u540c\u7684\u53f3\u624b\u8fb9\uff0c\u73b0\u5728\u53ea\u9700\u8981\u8003\u8651\u5230\u5185\u90e8\u5e94\u529b\u3002\u6b64\u5916\uff0c\u901a\u8fc7\u4f7f\u7528 <code>SymmetricTensor</code> \u7c7b\uff0c\u7ec4\u88c5\u77e9\u9635\u660e\u663e\u53d8\u5f97\u66f4\u52a0\u900f\u660e\uff1a\u8bf7\u6ce8\u610f\u5f62\u62102\u7ea7\u548c4\u7ea7\u5bf9\u79f0\u5f20\u91cf\u7684\u6807\u91cf\u79ef\u7684\u4f18\u96c5\u6027\u3002\u8fd9\u4e2a\u5b9e\u73b0\u4e5f\u66f4\u52a0\u901a\u7528\uff0c\u56e0\u4e3a\u5b83\u4e0e\u6211\u4eec\u53ef\u80fd\u4f7f\u7528\u6216\u4e0d\u4f7f\u7528\u5404\u5411\u540c\u6027\u7684\u5f39\u6027\u5f20\u91cf\u8fd9\u4e00\u4e8b\u5b9e\u65e0\u5173\u3002\n\n// \u6c47\u7f16\u7a0b\u5e8f\u7684\u7b2c\u4e00\u90e8\u5206\u548c\u4ee5\u5f80\u4e00\u6837\u3002\n\n  template <int dim> \n  void TopLevel<dim>::assemble_system() \n  { \n    system_rhs    = 0; \n    system_matrix = 0; \n\n    FEValues<dim> fe_values(fe, \n                            quadrature_formula, \n                            update_values | update_gradients | \n                              update_quadrature_points | 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\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    BodyForce<dim>              body_force; \n    std::vector<Vector<double>> body_force_values(n_q_points, \n                                                  Vector<double>(dim)); \n\n// \u5982\u540c\u5728  step-17  \u4e2d\u4e00\u6837\uff0c\u6211\u4eec\u53ea\u9700\u8981\u5728\u5c5e\u4e8e\u5f53\u524d\u5904\u7406\u5668\u7684\u6240\u6709\u5355\u5143\u4e2d\u8fdb\u884c\u5faa\u73af\u3002\n\n    for (const auto &cell : dof_handler.active_cell_iterators()) \n      if (cell->is_locally_owned()) \n        { \n          cell_matrix = 0; \n          cell_rhs    = 0; \n\n          fe_values.reinit(cell); \n\n// \u7136\u540e\u5728\u6240\u6709\u6307\u6570i,j\u548c\u6b63\u4ea4\u70b9\u4e0a\u5faa\u73af\uff0c\u5e76\u4ece\u8fd9\u4e2a\u5355\u5143\u4e2d\u7ec4\u5408\u51fa\u7cfb\u7edf\u77e9\u9635\u7684\u8d21\u732e\u3002 \u6ce8\u610f\u6211\u4eec\u5982\u4f55\u4ece <code>FEValues</code> \u5bf9\u8c61\u4e2d\u63d0\u53d6\u7ed9\u5b9a\u6b63\u4ea4\u70b9\u7684\u5f62\u72b6\u51fd\u6570\u7684\u5bf9\u79f0\u68af\u5ea6\uff08\u5e94\u53d8\uff09\uff0c\u4ee5\u53ca\u6211\u4eec\u5982\u4f55\u4f18\u96c5\u5730\u5f62\u6210\u4e09\u91cd\u6536\u7f29 <code>eps_phi_i : C : eps_phi_j</code> \uff1b\u540e\u8005\u9700\u8981\u4e0e step-17 \u4e2d\u9700\u8981\u7684\u7b28\u62d9\u8ba1\u7b97\u8fdb\u884c\u6bd4\u8f83\uff0c\u65e0\u8bba\u662f\u5728\u4ecb\u7ecd\u4e2d\u8fd8\u662f\u5728\u7a0b\u5e8f\u7684\u76f8\u5e94\u4f4d\u7f6e\u3002\n\n          for (unsigned int i = 0; i < dofs_per_cell; ++i) \n            for (unsigned int j = 0; j < dofs_per_cell; ++j) \n              for (unsigned int q_point = 0; q_point < n_q_points; ++q_point) \n                { \n                  const SymmetricTensor<2, dim> \n                    eps_phi_i = get_strain(fe_values, i, q_point), \n                    eps_phi_j = get_strain(fe_values, j, q_point); \n\n                  cell_matrix(i, j) += (eps_phi_i *            // \n                                        stress_strain_tensor * // \n                                        eps_phi_j              // \n                                        ) *                    // \n                                       fe_values.JxW(q_point); // \n                } \n\n// \u7136\u540e\u4e5f\u8981\u7ec4\u88c5\u672c\u5730\u7684\u53f3\u624b\u8fb9\u8d21\u732e\u3002\u4e3a\u6b64\uff0c\u6211\u4eec\u9700\u8981\u8bbf\u95ee\u8fd9\u4e2a\u6b63\u4ea4\u70b9\u7684\u5148\u9a8c\u5e94\u529b\u503c\u3002\u4e3a\u4e86\u5f97\u5230\u5b83\uff0c\u6211\u4eec\u4f7f\u7528\u8be5\u5355\u5143\u7684\u7528\u6237\u6307\u9488\uff0c\u8be5\u6307\u9488\u6307\u5411\u5168\u5c40\u6570\u7ec4\u4e2d\u4e0e\u5f53\u524d\u5355\u5143\u7684\u7b2c\u4e00\u4e2a\u6b63\u4ea4\u70b9\u76f8\u5bf9\u5e94\u7684\u6b63\u4ea4\u70b9\u6570\u636e\uff0c\u7136\u540e\u6dfb\u52a0\u4e00\u4e2a\u4e0e\u6211\u4eec\u73b0\u5728\u8003\u8651\u7684\u6b63\u4ea4\u70b9\u7684\u7d22\u5f15\u76f8\u5bf9\u5e94\u7684\u504f\u79fb\u91cf\u3002\n\n          const PointHistory<dim> *local_quadrature_points_data = \n            reinterpret_cast<PointHistory<dim> *>(cell->user_pointer()); \n\n// \u6b64\u5916\uff0c\u6211\u4eec\u8fd8\u9700\u8981\u8fd9\u4e2a\u5355\u5143\u4e0a\u7684\u6b63\u4ea4\u70b9\u7684\u5916\u4f53\u529b\u503c\u3002\n\n          body_force.vector_value_list(fe_values.get_quadrature_points(), \n                                       body_force_values); \n\n// \u7136\u540e\uff0c\u6211\u4eec\u53ef\u4ee5\u5faa\u73af\u8ba1\u7b97\u8fd9\u4e2a\u5355\u5143\u4e0a\u7684\u6240\u6709\u81ea\u7531\u5ea6\uff0c\u5e76\u8ba1\u7b97\u51fa\u5bf9\u53f3\u4fa7\u7684\u5c40\u90e8\u8d21\u732e\u3002\n\n          for (unsigned int i = 0; i < dofs_per_cell; ++i) \n            { \n              const unsigned int component_i = \n                fe.system_to_component_index(i).first; \n\n              for (unsigned int q_point = 0; q_point < n_q_points; ++q_point) \n                { \n                  const SymmetricTensor<2, dim> &old_stress = \n                    local_quadrature_points_data[q_point].old_stress; \n\n                  cell_rhs(i) += \n                    (body_force_values[q_point](component_i) * \n                       fe_values.shape_value(i, q_point) - \n                     old_stress * get_strain(fe_values, i, q_point)) * \n                    fe_values.JxW(q_point); \n                } \n            } \n\n// \u73b0\u5728\u6211\u4eec\u6709\u4e86\u5bf9\u7ebf\u6027\u7cfb\u7edf\u7684\u5c40\u90e8\u8d21\u732e\uff0c\u6211\u4eec\u9700\u8981\u5c06\u5176\u8f6c\u79fb\u5230\u5168\u5c40\u5bf9\u8c61\u4e2d\u3002\u8fd9\u4e0e  step-17  \u4e2d\u7684\u505a\u6cd5\u5b8c\u5168\u76f8\u540c\u3002\n\n          cell->get_dof_indices(local_dof_indices); \n\n          hanging_node_constraints.distribute_local_to_global(cell_matrix, \n                                                              cell_rhs, \n                                                              local_dof_indices, \n                                                              system_matrix, \n                                                              system_rhs); \n        } \n\n// \u73b0\u5728\u538b\u7f29\u77e2\u91cf\u548c\u7cfb\u7edf\u77e9\u9635\u3002\n\n    system_matrix.compress(VectorOperation::add); \n    system_rhs.compress(VectorOperation::add); \n\n// \u6700\u540e\u4e00\u6b65\u662f\u518d\u6b21\u4fee\u590d\u8fb9\u754c\u503c\uff0c\u5c31\u50cf\u6211\u4eec\u5728\u4ee5\u524d\u7684\u7a0b\u5e8f\u4e2d\u5df2\u7ecf\u505a\u7684\u90a3\u6837\u3002\u4e00\u4e2a\u7a0d\u5fae\u590d\u6742\u7684\u95ee\u9898\u662f\uff0c <code>apply_boundary_values</code> \u51fd\u6570\u5e0c\u671b\u6709\u4e00\u4e2a\u4e0e\u77e9\u9635\u548c\u53f3\u624b\u8fb9\u517c\u5bb9\u7684\u89e3\u5411\u91cf\uff08\u5373\u8fd9\u91cc\u662f\u4e00\u4e2a\u5206\u5e03\u5f0f\u7684%\u5e76\u884c\u5411\u91cf\uff0c\u800c\u4e0d\u662f\u6211\u4eec\u5728\u8fd9\u4e2a\u7a0b\u5e8f\u4e2d\u4f7f\u7528\u7684\u987a\u5e8f\u5411\u91cf\uff09\uff0c\u4ee5\u4fbf\u7528\u6b63\u786e\u7684\u8fb9\u754c\u503c\u9884\u8bbe\u89e3\u5411\u91cf\u7684\u6761\u76ee\u3002\u6211\u4eec\u4ee5\u4e34\u65f6\u5411\u91cf\u7684\u5f62\u5f0f\u63d0\u4f9b\u8fd9\u6837\u4e00\u4e2a\u517c\u5bb9\u5411\u91cf\uff0c\u7136\u540e\u5c06\u5176\u590d\u5236\u5230\u987a\u5e8f\u5411\u91cf\u4e2d\u3002\n\n// \u6211\u4eec\u901a\u8fc7\u5c55\u793a\u8fb9\u754c\u503c\u7684\u7075\u6d3b\u4f7f\u7528\u6765\u5f25\u8865\u8fd9\u79cd\u590d\u6742\u6027\uff1a\u6309\u7167\u6211\u4eec\u521b\u5efa\u4e09\u89d2\u5f62\u7684\u65b9\u5f0f\uff0c\u6709\u4e09\u4e2a\u4e0d\u540c\u7684\u8fb9\u754c\u6307\u6807\u7528\u6765\u63cf\u8ff0\u9886\u57df\uff0c\u5206\u522b\u5bf9\u5e94\u4e8e\u5e95\u9762\u548c\u9876\u9762\uff0c\u4ee5\u53ca\u5185/\u5916\u8868\u9762\u3002\u6211\u4eec\u5e0c\u671b\u65bd\u52a0\u4ee5\u4e0b\u7c7b\u578b\u7684\u8fb9\u754c\u6761\u4ef6\u3002\u5185\u5916\u5706\u67f1\u4f53\u8868\u9762\u6ca1\u6709\u5916\u529b\uff0c\u8fd9\u4e00\u4e8b\u5b9e\u5bf9\u5e94\u4e8e\u81ea\u7136\uff08\u8bfa\u4f0a\u66fc\u578b\uff09\u8fb9\u754c\u6761\u4ef6\uff0c\u6211\u4eec\u4e0d\u9700\u8981\u505a\u4efb\u4f55\u4e8b\u60c5\u3002\u5728\u5e95\u90e8\uff0c\u6211\u4eec\u5e0c\u671b\u5b8c\u5168\u6ca1\u6709\u8fd0\u52a8\uff0c\u5bf9\u5e94\u4e8e\u5706\u67f1\u4f53\u5728\u8fb9\u754c\u7684\u8fd9\u4e00\u90e8\u5206\u88ab\u5939\u4f4f\u6216\u7c98\u4f4f\u3002\u7136\u800c\uff0c\u5728\u9876\u90e8\uff0c\u6211\u4eec\u5e0c\u671b\u6709\u4e00\u4e2a\u89c4\u5b9a\u7684\u5782\u76f4\u5411\u4e0b\u7684\u8fd0\u52a8\u6765\u538b\u7f29\u5706\u67f1\u4f53\uff1b\u6b64\u5916\uff0c\u6211\u4eec\u53ea\u5e0c\u671b\u9650\u5236\u5782\u76f4\u8fd0\u52a8\uff0c\u800c\u4e0d\u662f\u6c34\u5e73\u8fd0\u52a8--\u53ef\u4ee5\u628a\u8fd9\u79cd\u60c5\u51b5\u770b\u4f5c\u662f\u4e00\u5757\u6cb9\u6027\u826f\u597d\u7684\u677f\u5750\u5728\u5706\u67f1\u4f53\u7684\u9876\u90e8\u5c06\u5176\u5411\u4e0b\u63a8\uff1a\u5706\u67f1\u4f53\u7684\u539f\u5b50\u88ab\u8feb\u5411\u4e0b\u79fb\u52a8\uff0c\u4f46\u5b83\u4eec\u53ef\u4ee5\u81ea\u7531\u5730\u6cbf\u7740\u677f\u6c34\u5e73\u6ed1\u52a8\u3002\n\n//\u63cf\u8ff0\u8fd9\u79cd\u60c5\u51b5\u7684\u65b9\u6cd5\u5982\u4e0b\uff1a\u5bf9\u4e8e\u8fb9\u754c\u6307\u6807\u4e3a\u96f6\uff08\u5e95\u9762\uff09\u7684\u8fb9\u754c\uff0c\u6211\u4eec\u4f7f\u7528\u4e00\u4e2a\u4e8c\u7ef4\u7684\u96f6\u51fd\u6570\uff0c\u4ee3\u8868\u5728\u4efb\u4f55\u5750\u6807\u65b9\u5411\u90fd\u6ca1\u6709\u8fd0\u52a8\u3002\u5bf9\u4e8e\u6307\u68071\uff08\u9876\u9762\uff09\u7684\u8fb9\u754c\uff0c\u6211\u4eec\u4f7f\u7528 <code>IncrementalBoundaryValues</code> \u7c7b\uff0c\u4f46\u6211\u4eec\u4e3a <code>VectorTools::interpolate_boundary_values</code> \u51fd\u6570\u6307\u5b9a\u4e00\u4e2a\u989d\u5916\u7684\u53c2\u6570\uff0c\u8868\u793a\u5b83\u5e94\u8be5\u9002\u7528\u4e8e\u54ea\u4e9b\u77e2\u91cf\u5206\u91cf\uff1b\u8fd9\u662f\u4e00\u4e2a\u9488\u5bf9\u6bcf\u4e2a\u77e2\u91cf\u5206\u91cf\u7684bools\u77e2\u91cf\uff0c\u7531\u4e8e\u6211\u4eec\u53ea\u60f3\u9650\u5236\u5782\u76f4\u8fd0\u52a8\uff0c\u5b83\u53ea\u6709\u6700\u540e\u4e00\u4e2a\u5206\u91cf\u7684\u8bbe\u7f6e\u3002\n\n    FEValuesExtractors::Scalar                z_component(dim - 1); \n    std::map<types::global_dof_index, double> boundary_values; \n    VectorTools::interpolate_boundary_values(dof_handler, \n                                             0, \n                                             Functions::ZeroFunction<dim>(dim), \n                                             boundary_values); \n    VectorTools::interpolate_boundary_values( \n      dof_handler, \n      1, \n      IncrementalBoundaryValues<dim>(present_time, present_timestep), \n      boundary_values, \n      fe.component_mask(z_component)); \n\n    PETScWrappers::MPI::Vector tmp(locally_owned_dofs, mpi_communicator); \n    MatrixTools::apply_boundary_values( \n      boundary_values, system_matrix, tmp, system_rhs, false); \n    incremental_displacement = tmp; \n  } \n\n//  @sect4{TopLevel::solve_timestep}  \n\n// \u4e0b\u4e00\u4e2a\u51fd\u6570\u662f\u63a7\u5236\u4e00\u4e2a\u65f6\u95f4\u6bb5\u5185\u5fc5\u987b\u53d1\u751f\u7684\u6240\u6709\u4e8b\u60c5\u7684\u51fd\u6570\u3002\u4ece\u51fd\u6570\u540d\u79f0\u4e0a\u770b\uff0c\u4e8b\u60c5\u7684\u987a\u5e8f\u5e94\u8be5\u662f\u76f8\u5bf9\u4e0d\u8a00\u81ea\u660e\u7684\u3002\n\n  template <int dim> \n  void TopLevel<dim>::solve_timestep() \n  { \n    pcout << \"    Assembling system...\" << std::flush; \n    assemble_system(); \n    pcout << \" norm of rhs is \" << system_rhs.l2_norm() << std::endl; \n\n    const unsigned int n_iterations = solve_linear_problem(); \n\n    pcout << \"    Solver converged in \" << n_iterations << \" iterations.\" \n          << std::endl; \n\n    pcout << \"    Updating quadrature point data...\" << std::flush; \n    update_quadrature_point_history(); \n    pcout << std::endl; \n  } \n\n//  @sect4{TopLevel::solve_linear_problem}  \n\n// \u518d\u6b21\u6c42\u89e3\u7ebf\u6027\u7cfb\u7edf\u7684\u5de5\u4f5c\u539f\u7406\u4e0e\u4e4b\u524d\u57fa\u672c\u76f8\u540c\u3002\u552f\u4e00\u4e0d\u540c\u7684\u662f\uff0c\u6211\u4eec\u53ea\u60f3\u4fdd\u7559\u4e00\u4efd\u5b8c\u6574\u7684\u672c\u5730\u89e3\u5411\u91cf\uff0c\u800c\u4e0d\u662f\u4ecePETSc\u7684\u6c42\u89e3\u7a0b\u5e8f\u4e2d\u5f97\u5230\u7684\u5206\u5e03\u5f0f\u5411\u91cf\u3002\u4e3a\u6b64\uff0c\u6211\u4eec\u4e3a\u5206\u5e03\u5f0f\u5411\u91cf\u58f0\u660e\u4e00\u4e2a\u672c\u5730\u4e34\u65f6\u53d8\u91cf\uff0c\u5e76\u7528\u672c\u5730\u53d8\u91cf\u7684\u5185\u5bb9\u5bf9\u5176\u8fdb\u884c\u521d\u59cb\u5316\uff08\u8bb0\u5f97 <code>apply_boundary_values</code> \u4e2d\u8c03\u7528\u7684 <code>assemble_system</code> \u51fd\u6570\u9884\u8bbe\u4e86\u8be5\u5411\u91cf\u4e2d\u8fb9\u754c\u8282\u70b9\u7684\u503c\uff09\uff0c\u7528\u5b83\u8fdb\u884c\u6c42\u89e3\uff0c\u5e76\u5728\u51fd\u6570\u7ed3\u675f\u65f6\u5c06\u5176\u518d\u6b21\u590d\u5236\u5230\u6211\u4eec\u58f0\u660e\u4e3a\u6210\u5458\u53d8\u91cf\u7684\u5b8c\u6574\u672c\u5730\u5411\u91cf\u4e2d\u3002\u7136\u540e\uff0c\u6302\u8d77\u7684\u8282\u70b9\u7ea6\u675f\u53ea\u5206\u5e03\u5728\u672c\u5730\u62f7\u8d1d\u4e0a\uff0c\u4e5f\u5c31\u662f\u8bf4\uff0c\u5728\u6bcf\u4e2a\u5904\u7406\u5668\u4e0a\u90fd\u662f\u72ec\u7acb\u7684\u3002\n\n  template <int dim> \n  unsigned int TopLevel<dim>::solve_linear_problem() \n  { \n    PETScWrappers::MPI::Vector distributed_incremental_displacement( \n      locally_owned_dofs, mpi_communicator); \n    distributed_incremental_displacement = incremental_displacement; \n\n    SolverControl solver_control(dof_handler.n_dofs(), \n                                 1e-16 * system_rhs.l2_norm()); \n\n    PETScWrappers::SolverCG cg(solver_control, mpi_communicator); \n\n    PETScWrappers::PreconditionBlockJacobi preconditioner(system_matrix); \n\n    cg.solve(system_matrix, \n             distributed_incremental_displacement, \n             system_rhs, \n             preconditioner); \n\n    incremental_displacement = distributed_incremental_displacement; \n\n    hanging_node_constraints.distribute(incremental_displacement); \n\n    return solver_control.last_step(); \n  } \n\n//  @sect4{TopLevel::output_results}  \n\n// \u8fd9\u4e2a\u51fd\u6570\u751f\u6210.vtu\u683c\u5f0f\u7684\u56fe\u5f62\u8f93\u51fa\uff0c\u6b63\u5982\u4ecb\u7ecd\u4e2d\u6240\u89e3\u91ca\u7684\u3002\u6bcf\u4e2a\u8fdb\u7a0b\u5c06\u53ea\u5bf9\u5176\u62e5\u6709\u7684\u5355\u5143\u683c\u8fdb\u884c\u5de5\u4f5c\uff0c\u7136\u540e\u5c06\u7ed3\u679c\u5199\u5165\u81ea\u5df1\u7684\u6587\u4ef6\u4e2d\u3002\u6b64\u5916\uff0c\u5904\u7406\u56680\u5c06\u5199\u4e0b\u5f15\u7528\u6240\u6709.vtu\u6587\u4ef6\u7684\u8bb0\u5f55\u6587\u4ef6\u3002\n\n// \u8fd9\u4e2a\u51fd\u6570\u7684\u5173\u952e\u90e8\u5206\u662f\u7ed9 <code>DataOut</code> \u7c7b\u63d0\u4f9b\u4e00\u79cd\u65b9\u6cd5\uff0c\u4f7f\u5176\u53ea\u5bf9\u5f53\u524d\u8fdb\u7a0b\u62e5\u6709\u7684\u5355\u5143\u683c\u8fdb\u884c\u5de5\u4f5c\u3002\n\n  template <int dim> \n  void TopLevel<dim>::output_results() const \n  { \n    DataOut<dim> data_out; \n    data_out.attach_dof_handler(dof_handler); \n//\u7136\u540e\uff0c\n//\u5c31\u50cf\u5728 step-17 \u4e2d\u4e00\u6837\uff0c\u5b9a\u4e49\u6c42\u89e3\u53d8\u91cf\u7684\u540d\u79f0\uff08\u8fd9\u91cc\u662f\u4f4d\u79fb\u589e\u91cf\uff09\u5e76\u6392\u961f\u8f93\u51fa\u6c42\u89e3\u5411\u91cf\u3002\u8bf7\u6ce8\u610f\u5728\u4e0b\u9762\u7684\u5f00\u5173\u4e2d\uff0c\u6211\u4eec\u5982\u4f55\u786e\u4fdd\u5982\u679c\u7a7a\u95f4\u7ef4\u5ea6\u5e94\u8be5\u4e0d\u88ab\u5904\u7406\uff0c\u6211\u4eec\u629b\u51fa\u4e00\u4e2a\u5f02\u5e38\uff0c\u8bf4\u6211\u4eec\u8fd8\u6ca1\u6709\u5b9e\u73b0\u8fd9\u79cd\u60c5\u51b5\uff08\u53e6\u4e00\u4e2a\u9632\u5fa1\u6027\u7f16\u7a0b\u7684\u6848\u4f8b\uff09\u3002\n\n    std::vector<std::string> solution_names; \n    switch (dim) \n      { \n        case 1: \n          solution_names.emplace_back(\"delta_x\"); \n          break; \n        case 2: \n          solution_names.emplace_back(\"delta_x\"); \n          solution_names.emplace_back(\"delta_y\"); \n          break; \n        case 3: \n          solution_names.emplace_back(\"delta_x\"); \n          solution_names.emplace_back(\"delta_y\"); \n          solution_names.emplace_back(\"delta_z\"); \n          break; \n        default: \n          Assert(false, ExcNotImplemented()); \n      } \n\n    data_out.add_data_vector(incremental_displacement, solution_names); \n\n// \u63a5\u4e0b\u6765\u7684\u4e8b\u60c5\u662f\uff0c\u6211\u4eec\u60f3\u8f93\u51fa\u7c7b\u4f3c\u4e8e\u6211\u4eec\u5728\u6bcf\u4e2a\u5355\u5143\u4e2d\u5b58\u50a8\u7684\u5e94\u529b\u7684\u5e73\u5747\u89c4\u8303\u3002\u8fd9\u770b\u8d77\u6765\u5f88\u590d\u6742\uff0c\u56e0\u4e3a\u5728\u76ee\u524d\u7684\u5904\u7406\u5668\u4e0a\uff0c\u6211\u4eec\u53ea\u5728\u90a3\u4e9b\u5b9e\u9645\u5c5e\u4e8e\u76ee\u524d\u8fdb\u7a0b\u7684\u5355\u5143\u683c\u4e0a\u5b58\u50a8\u6b63\u4ea4\u70b9\u7684\u5e94\u529b\u3002\u6362\u53e5\u8bdd\u8bf4\uff0c\u6211\u4eec\u4f3c\u4e4e\u65e0\u6cd5\u8ba1\u7b97\u51fa\u6240\u6709\u5355\u5143\u7684\u5e73\u5747\u5e94\u529b\u3002\u7136\u800c\uff0c\u8bf7\u8bb0\u4f4f\uff0c\u6211\u4eec\u6e90\u81ea <code>DataOut</code> \u7684\u7c7b\u53ea\u8fed\u4ee3\u90a3\u4e9b\u5b9e\u9645\u5c5e\u4e8e\u5f53\u524d\u5904\u7406\u5668\u7684\u5355\u5143\uff0c\u4e5f\u5c31\u662f\u8bf4\uff0c\u6211\u4eec\u4e0d\u5fc5\u4e3a\u6240\u6709\u5176\u4ed6\u5355\u5143\u8ba1\u7b97\u4efb\u4f55\u4e1c\u897f\uff0c\u56e0\u4e3a\u8fd9\u4e9b\u4fe1\u606f\u4e0d\u4f1a\u88ab\u89e6\u53ca\u3002\u4e0b\u9762\u7684\u5c0f\u5faa\u73af\u5c31\u662f\u8fd9\u6837\u505a\u7684\u3002\u6211\u4eec\u5c06\u6574\u4e2a\u533a\u5757\u5305\u56f4\u5728\u4e00\u5bf9\u5927\u62ec\u53f7\u4e2d\uff0c\u4ee5\u786e\u4fdd\u8fed\u4ee3\u5668\u53d8\u91cf\u4e0d\u4f1a\u5728\u5b83\u4eec\u88ab\u4f7f\u7528\u7684\u533a\u5757\u7ed3\u675f\u540e\u4ecd\u7136\u610f\u5916\u5730\u53ef\u89c1\u3002\n\n    Vector<double> norm_of_stress(triangulation.n_active_cells()); \n    { \n\n// \u5728\u6240\u6709\u7684\u5355\u5143\u683c\u4e0a\u5faa\u73af...\n\n      for (auto &cell : triangulation.active_cell_iterators()) \n        if (cell->is_locally_owned()) \n          { \n\n// \u5728\u8fd9\u4e9b\u5355\u5143\u4e0a\uff0c\u5c06\u6240\u6709\u6b63\u4ea4\u70b9\u7684\u5e94\u529b\u76f8\u52a0...\n\n            SymmetricTensor<2, dim> accumulated_stress; \n            for (unsigned int q = 0; q < quadrature_formula.size(); ++q) \n              accumulated_stress += \n                reinterpret_cast<PointHistory<dim> *>(cell->user_pointer())[q] \n                  .old_stress; \n\n// ...\u7136\u540e\u628a\u5e73\u5747\u503c\u7684\u5e38\u6570\u5199\u5230\u5b83\u4eec\u7684\u76ee\u7684\u5730\u3002\n\n            norm_of_stress(cell->active_cell_index()) = \n              (accumulated_stress / quadrature_formula.size()).norm(); \n          } \n\n// \u5728\u6211\u4eec\u4e0d\u611f\u5174\u8da3\u7684\u5355\u5143\u683c\u4e0a\uff0c\u5c06\u5411\u91cf\u4e2d\u5404\u81ea\u7684\u503c\u8bbe\u7f6e\u4e3a\u4e00\u4e2a\u5047\u503c\uff08\u89c4\u8303\u5fc5\u987b\u662f\u6b63\u503c\uff0c\u5927\u7684\u8d1f\u503c\u5e94\u8be5\u80fd\u5438\u5f15\u4f60\u7684\u773c\u7403\uff09\uff0c\u4ee5\u786e\u4fdd\u5982\u679c\u6211\u4eec\u7684\u5047\u8bbe\u6709\u8bef\uff0c\u5373\u8fd9\u4e9b\u5143\u7d20\u4e0d\u4f1a\u51fa\u73b0\u5728\u8f93\u51fa\u6587\u4ef6\u4e2d\uff0c\u6211\u4eec\u4f1a\u901a\u8fc7\u89c2\u5bdf\u56fe\u5f62\u8f93\u51fa\u53d1\u73b0\u3002\n\n        else \n          norm_of_stress(cell->active_cell_index()) = -1e+20; \n    } \n\n// \u6700\u540e\u628a\u8fd9\u4e2a\u5411\u91cf\u4e5f\u9644\u5728\u4e0a\u9762\uff0c\u4ee5\u4fbf\u8fdb\u884c\u8f93\u51fa\u5904\u7406\u3002\n\n    data_out.add_data_vector(norm_of_stress, \"norm_of_stress\"); \n\n// \u4f5c\u4e3a\u6700\u540e\u4e00\u4e2a\u6570\u636e\uff0c\u5982\u679c\u8fd9\u662f\u4e00\u4e2a\u5e76\u884c\u4f5c\u4e1a\uff0c\u8ba9\u6211\u4eec\u4e5f\u628a\u57df\u5212\u5206\u4e3a\u4e0e\u5904\u7406\u5668\u76f8\u5173\u7684\u5b50\u57df\u3002\u8fd9\u4e0e step-17 \u7a0b\u5e8f\u4e2d\u7684\u5de5\u4f5c\u65b9\u5f0f\u5b8c\u5168\u76f8\u540c\u3002\n\n    std::vector<types::subdomain_id> partition_int( \n      triangulation.n_active_cells()); \n    GridTools::get_subdomain_association(triangulation, partition_int); \n    const Vector<double> partitioning(partition_int.begin(), \n                                      partition_int.end()); \n    data_out.add_data_vector(partitioning, \"partitioning\"); \n\n// \u6700\u540e\uff0c\u6709\u4e86\u8fd9\u4e9b\u6570\u636e\uff0c\u6211\u4eec\u53ef\u4ee5\u6307\u793adeal.II\u5bf9\u4fe1\u606f\u8fdb\u884c\u6574\u5408\uff0c\u5e76\u4ea7\u751f\u4e00\u4e9b\u4e2d\u95f4\u6570\u636e\u7ed3\u6784\uff0c\u5176\u4e2d\u5305\u542b\u6240\u6709\u8fd9\u4e9b\u89e3\u51b3\u65b9\u6848\u548c\u5176\u4ed6\u6570\u636e\u5411\u91cf\u3002\n\n    data_out.build_patches(); \n\n// \u8ba9\u6211\u4eec\u8c03\u7528\u4e00\u4e2a\u51fd\u6570\uff0c\u6253\u5f00\u5fc5\u8981\u7684\u8f93\u51fa\u6587\u4ef6\uff0c\u5c06\u6211\u4eec\u751f\u6210\u7684\u6570\u636e\u5199\u5165\u5176\u4e2d\u3002\u8be5\u51fd\u6570\u6839\u636e\u7ed9\u5b9a\u7684\u76ee\u5f55\u540d\uff08\u7b2c\u4e00\u4e2a\u53c2\u6570\uff09\u548c\u6587\u4ef6\u540d\u57fa\u6570\uff08\u7b2c\u4e8c\u4e2a\u53c2\u6570\uff09\u81ea\u52a8\u6784\u5efa\u6587\u4ef6\u540d\u3002\u5b83\u901a\u8fc7\u7531\u65f6\u95f4\u6b65\u6570\u548c \"\u7247\u6570 \"\u4ea7\u751f\u7684\u7247\u65ad\u6765\u589e\u52a0\u6240\u4ea7\u751f\u7684\u5b57\u7b26\u4e32\uff0c\"\u7247\u6570 \"\u5bf9\u5e94\u4e8e\u6574\u4e2a\u57df\u7684\u4e00\u90e8\u5206\uff0c\u53ef\u4ee5\u7531\u4e00\u4e2a\u6216\u591a\u4e2a\u5b50\u57df\u7ec4\u6210\u3002\n\n// \u8be5\u51fd\u6570\u8fd8\u4e3aParaview\u5199\u4e86\u4e00\u4e2a\u8bb0\u5f55\u6587\u4ef6\uff08\u540e\u7f00\u4e3a`.pvd`\uff09\uff0c\u63cf\u8ff0\u4e86\u6240\u6709\u8fd9\u4e9b\u8f93\u51fa\u6587\u4ef6\u5982\u4f55\u7ec4\u5408\u6210\u8fd9\u4e2a\u5355\u4e00\u65f6\u95f4\u6b65\u9aa4\u7684\u6570\u636e\u3002\n\n    const std::string pvtu_filename = data_out.write_vtu_with_pvtu_record( \n      \"./\", \"solution\", timestep_no, mpi_communicator, 4); \n\n// \u8bb0\u5f55\u6587\u4ef6\u5fc5\u987b\u53ea\u5199\u4e00\u6b21\uff0c\u800c\u4e0d\u662f\u7531\u6bcf\u4e2a\u5904\u7406\u5668\u6765\u5199\uff0c\u6240\u4ee5\u6211\u4eec\u57280\u53f7\u5904\u7406\u5668\u4e0a\u505a\u8fd9\u4e2a\u3002\n\n    if (this_mpi_process == 0) \n      { \n\n// \u6700\u540e\uff0c\u6211\u4eec\u5199\u5165paraview\u8bb0\u5f55\uff0c\u5b83\u5f15\u7528\u4e86\u6240\u6709.pvtu\u6587\u4ef6\u548c\u5b83\u4eec\u5404\u81ea\u7684\u65f6\u95f4\u3002\u6ce8\u610f\uff0c\u53d8\u91cftimes_and_names\u88ab\u58f0\u660e\u4e3a\u9759\u6001\u7684\uff0c\u6240\u4ee5\u5b83\u5c06\u4fdd\u7559\u524d\u51e0\u4e2a\u65f6\u95f4\u6bb5\u7684\u6761\u76ee\u3002\n\n        static std::vector<std::pair<double, std::string>> times_and_names; \n        times_and_names.push_back( \n          std::pair<double, std::string>(present_time, pvtu_filename)); \n        std::ofstream pvd_output(\"solution.pvd\"); \n        DataOutBase::write_pvd_record(pvd_output, times_and_names); \n      } \n  } \n\n//  @sect4{TopLevel::do_initial_timestep}  \n\n// \u8fd9\u4e2a\u51fd\u6570\u548c\u4e0b\u4e00\u4e2a\u51fd\u6570\u5206\u522b\u5904\u7406\u7b2c\u4e00\u4e2a\u548c\u4e0b\u4e00\u4e2a\u65f6\u95f4\u6b65\u9aa4\u7684\u6574\u4f53\u7ed3\u6784\u3002\u7b2c\u4e00\u4e2a\u65f6\u95f4\u6b65\u9aa4\u7684\u5de5\u4f5c\u91cf\u7a0d\u5927\uff0c\u56e0\u4e3a\u6211\u4eec\u8981\u5728\u8fde\u7eed\u7ec6\u5316\u7684\u7f51\u683c\u4e0a\u591a\u6b21\u8ba1\u7b97\uff0c\u6bcf\u6b21\u90fd\u4ece\u4e00\u4e2a\u5e72\u51c0\u7684\u72b6\u6001\u5f00\u59cb\u3002\u5728\u8fd9\u4e9b\u8ba1\u7b97\u7684\u6700\u540e\uff0c\u6211\u4eec\u6bcf\u6b21\u90fd\u8ba1\u7b97\u589e\u91cf\u4f4d\u79fb\uff0c\u6211\u4eec\u4f7f\u7528\u6700\u540e\u5f97\u5230\u7684\u589e\u91cf\u4f4d\u79fb\u7684\u7ed3\u679c\u6765\u8ba1\u7b97\u4ea7\u751f\u7684\u5e94\u529b\u66f4\u65b0\u5e76\u76f8\u5e94\u5730\u79fb\u52a8\u7f51\u683c\u3002\u5728\u8fd9\u4e2a\u65b0\u7684\u7f51\u683c\u4e0a\uff0c\u6211\u4eec\u518d\u8f93\u51fa\u89e3\u51b3\u65b9\u6848\u548c\u4efb\u4f55\u6211\u4eec\u8ba4\u4e3a\u91cd\u8981\u7684\u9644\u52a0\u6570\u636e\u3002\n\n// \u6240\u6709\u8fd9\u4e9b\u90fd\u4f1a\u7a7f\u63d2\u7740\u4ea7\u751f\u8f93\u51fa\u5230\u63a7\u5236\u53f0\uff0c\u4ee5\u66f4\u65b0\u5c4f\u5e55\u4e0a\u7684\u4eba\u6b63\u5728\u53d1\u751f\u7684\u4e8b\u60c5\u3002\u5982\u540c\u5728 step-17 \u4e2d\u4e00\u6837\uff0c\u4f7f\u7528 <code>pcout</code> instead of <code>std::cout</code> \u53ef\u4ee5\u786e\u4fdd\u53ea\u6709\u4e00\u4e2a\u5e76\u884c\u8fdb\u7a0b\u5b9e\u9645\u5728\u5411\u63a7\u5236\u53f0\u5199\u6570\u636e\uff0c\u800c\u4e0d\u9700\u8981\u5728\u6bcf\u4e2a\u4ea7\u751f\u8f93\u51fa\u7684\u5730\u65b9\u660e\u786e\u5730\u7f16\u7801\u4e00\u4e2aif\u8bed\u53e5\u3002\n\n  template <int dim> \n  void TopLevel<dim>::do_initial_timestep() \n  { \n    present_time += present_timestep; \n    ++timestep_no; \n    pcout << \"Timestep \" << timestep_no << \" at time \" << present_time \n          << std::endl; \n\n    for (unsigned int cycle = 0; cycle < 2; ++cycle) \n      { \n        pcout << \"  Cycle \" << cycle << ':' << std::endl; \n\n        if (cycle == 0) \n          create_coarse_grid(); \n        else \n          refine_initial_grid(); \n\n        pcout << \"    Number of active cells:       \" \n              << triangulation.n_active_cells() << \" (by partition:\"; \n        for (unsigned int p = 0; p < n_mpi_processes; ++p) \n          pcout << (p == 0 ? ' ' : '+') \n                << (GridTools::count_cells_with_subdomain_association( \n                     triangulation, p)); \n        pcout << \")\" << std::endl; \n\n        setup_system(); \n\n        pcout << \"    Number of degrees of freedom: \" << dof_handler.n_dofs() \n              << \" (by partition:\"; \n        for (unsigned int p = 0; p < n_mpi_processes; ++p) \n          pcout << (p == 0 ? ' ' : '+') \n                << (DoFTools::count_dofs_with_subdomain_association(dof_handler, \n                                                                    p)); \n        pcout << \")\" << std::endl; \n\n        solve_timestep(); \n      } \n\n    move_mesh(); \n    output_results(); \n\n    pcout << std::endl; \n  } \n\n//  @sect4{TopLevel::do_timestep}  \n\n// \u540e\u7eed\u7684\u65f6\u95f4\u6b65\u9aa4\u6bd4\u8f83\u7b80\u5355\uff0c\u9274\u4e8e\u4e0a\u9762\u5bf9\u524d\u4e00\u4e2a\u51fd\u6570\u7684\u89e3\u91ca\uff0c\u53ef\u80fd\u4e0d\u9700\u8981\u66f4\u591a\u7684\u6587\u4ef6\u3002\n\n  template <int dim> \n  void TopLevel<dim>::do_timestep() \n  { \n    present_time += present_timestep; \n    ++timestep_no; \n    pcout << \"Timestep \" << timestep_no << \" at time \" << present_time \n          << std::endl; \n    if (present_time > end_time) \n      { \n        present_timestep -= (present_time - end_time); \n        present_time = end_time; \n      } \n\n    solve_timestep(); \n\n    move_mesh(); \n    output_results(); \n\n    pcout << std::endl; \n  } \n// @sect4{TopLevel::refine_initial_grid}  \n\n// \u5f53\u5728\u8fde\u7eed\u7ec6\u5316\u7684\u7f51\u683c\u4e0a\u6c42\u89e3\u7b2c\u4e00\u4e2a\u65f6\u95f4\u6b65\u9aa4\u65f6\uff0c\u8c03\u7528\u4ee5\u4e0b\u51fd\u6570\u3002\u6bcf\u6b21\u8fed\u4ee3\u540e\uff0c\u5b83\u90fd\u4f1a\u8ba1\u7b97\u4e00\u4e2a\u7ec6\u5316\u51c6\u5219\uff0c\u7ec6\u5316\u7f51\u683c\uff0c\u5e76\u5c06\u6bcf\u4e2a\u6b63\u4ea4\u70b9\u7684\u5386\u53f2\u53d8\u91cf\u518d\u6b21\u8bbe\u7f6e\u4e3a\u5e72\u51c0\u72b6\u6001\u3002\n\n  template <int dim> \n  void TopLevel<dim>::refine_initial_grid() \n  { \n\n// \u9996\u5148\uff0c\u8ba9\u6bcf\u4e2a\u8fdb\u7a0b\u8ba1\u7b97\u5176\u62e5\u6709\u7684\u5355\u5143\u683c\u7684\u8bef\u5dee\u6307\u6807\u3002\n\n    Vector<float> error_per_cell(triangulation.n_active_cells()); \n    KellyErrorEstimator<dim>::estimate( \n      dof_handler, \n      QGauss<dim - 1>(fe.degree + 1), \n      std::map<types::boundary_id, const Function<dim> *>(), \n      incremental_displacement, \n      error_per_cell, \n      ComponentMask(), \n      nullptr, \n      MultithreadInfo::n_threads(), \n      this_mpi_process); \n\n// \u7136\u540e\u5efa\u7acb\u4e00\u4e2a\u5168\u5c40\u5411\u91cf\uff0c\u6211\u4eec\u5c06\u6765\u81ea\u6bcf\u4e2a%\u5e76\u884c\u8fdb\u7a0b\u7684\u5c40\u90e8\u6307\u6807\u5408\u5e76\u5230\u5176\u4e2d\u3002\n\n    const unsigned int n_local_cells = \n      triangulation.n_locally_owned_active_cells(); \n\n    PETScWrappers::MPI::Vector distributed_error_per_cell( \n      mpi_communicator, triangulation.n_active_cells(), n_local_cells); \n\n    for (unsigned int i = 0; i < error_per_cell.size(); ++i) \n      if (error_per_cell(i) != 0) \n        distributed_error_per_cell(i) = error_per_cell(i); \n    distributed_error_per_cell.compress(VectorOperation::insert); \n\n// \u4e00\u65e6\u6211\u4eec\u6709\u4e86\u8fd9\u4e2a\uff0c\u5c31\u628a\u5b83\u590d\u5236\u56de\u6240\u6709\u5904\u7406\u5668\u4e0a\u7684\u672c\u5730\u526f\u672c\uff0c\u5e76\u76f8\u5e94\u5730\u5b8c\u5584\u7f51\u683c\u3002\n\n    error_per_cell = distributed_error_per_cell; \n    GridRefinement::refine_and_coarsen_fixed_number(triangulation, \n                                                    error_per_cell, \n                                                    0.35, \n                                                    0.03); \n    triangulation.execute_coarsening_and_refinement(); \n\n// \u6700\u540e\uff0c\u5728\u65b0\u7684\u7f51\u683c\u4e0a\u518d\u6b21\u8bbe\u7f6e\u6b63\u4ea4\u70b9\u6570\u636e\uff0c\u5e76\u4e14\u53ea\u5728\u90a3\u4e9b\u6211\u4eec\u5df2\u7ecf\u786e\u5b9a\u662f\u6211\u4eec\u7684\u5355\u5143\u4e0a\u8bbe\u7f6e\u3002\n\n    setup_quadrature_point_history(); \n  } \n\n//  @sect4{TopLevel::move_mesh}  \n\n// \u5728\u6bcf\u4e2a\u65f6\u95f4\u6b65\u9aa4\u7ed3\u675f\u65f6\uff0c\u6211\u4eec\u6839\u636e\u8fd9\u4e2a\u65f6\u95f4\u6b65\u9aa4\u8ba1\u7b97\u7684\u589e\u91cf\u4f4d\u79fb\u6765\u79fb\u52a8\u7f51\u683c\u7684\u8282\u70b9\u3002\u4e3a\u4e86\u505a\u5230\u8fd9\u4e00\u70b9\uff0c\u6211\u4eec\u4fdd\u7559\u4e00\u4e2a\u6807\u5fd7\u7684\u5411\u91cf\uff0c\u4e3a\u6bcf\u4e2a\u9876\u70b9\u6307\u793a\u6211\u4eec\u662f\u5426\u5df2\u7ecf\u79fb\u52a8\u8fc7\u5b83\uff0c\u7136\u540e\u5728\u6240\u6709\u5355\u5143\u4e2d\u5faa\u73af\uff0c\u79fb\u52a8\u90a3\u4e9b\u5c1a\u672a\u79fb\u52a8\u7684\u5355\u5143\u9876\u70b9\u3002\u503c\u5f97\u6ce8\u610f\u7684\u662f\uff0c\u6211\u4eec\u4ece\u67d0\u4e2a\u9876\u70b9\u76f8\u90bb\u7684\u5355\u5143\u4e2d\u79fb\u52a8\u8fd9\u4e2a\u9876\u70b9\u5e76\u4e0d\u91cd\u8981\uff1a\u56e0\u4e3a\u6211\u4eec\u4f7f\u7528\u8fde\u7eed\u6709\u9650\u5143\u8ba1\u7b97\u4f4d\u79fb\uff0c\u4f4d\u79fb\u573a\u4e5f\u662f\u8fde\u7eed\u7684\uff0c\u6211\u4eec\u53ef\u4ee5\u4ece\u6bcf\u4e2a\u76f8\u90bb\u7684\u5355\u5143\u4e2d\u8ba1\u7b97\u67d0\u4e2a\u9876\u70b9\u7684\u4f4d\u79fb\u3002\u6211\u4eec\u53ea\u9700\u8981\u786e\u4fdd\u6bcf\u4e2a\u8282\u70b9\u90fd\u7cbe\u786e\u5730\u79fb\u52a8\u4e00\u6b21\uff0c\u8fd9\u5c31\u662f\u4e3a\u4ec0\u4e48\u6211\u4eec\u8981\u4fdd\u7559\u6807\u5fd7\u7684\u77e2\u91cf\u3002\n\n// \u5728\u8fd9\u4e2a\u51fd\u6570\u4e2d\uff0c\u6709\u4e24\u4e2a\u503c\u5f97\u6ce8\u610f\u7684\u5730\u65b9\u3002\u9996\u5148\uff0c\u6211\u4eec\u5982\u4f55\u4f7f\u7528 <code>cell-@>vertex_dof_index(v,d)</code> \u51fd\u6570\u83b7\u5f97\u7ed9\u5b9a\u9876\u70b9\u7684\u4f4d\u79fb\u573a\uff0c\u8be5\u51fd\u6570\u8fd4\u56de\u7ed9\u5b9a\u5355\u5143\u7684 <code>d</code>th degree of freedom at vertex <code>v</code> \u7684\u7d22\u5f15\u3002\u5728\u672c\u4f8b\u4e2d\uff0ck-th\u5750\u6807\u65b9\u5411\u7684\u4f4d\u79fb\u5bf9\u5e94\u4e8e\u6709\u9650\u5143\u7684k-th\u5206\u91cf\u3002\u4f7f\u7528\u8fd9\u6837\u7684\u51fd\u6570\u6709\u4e00\u5b9a\u7684\u98ce\u9669\uff0c\u56e0\u4e3a\u5b83\u4f7f\u7528\u4e86\u6211\u4eec\u5728 <code>FESystem</code> \u5143\u7d20\u4e2d\u4e3a\u8fd9\u4e2a\u7a0b\u5e8f\u5171\u540c\u91c7\u53d6\u7684\u5143\u7d20\u987a\u5e8f\u7684\u77e5\u8bc6\u3002\u5982\u679c\u6211\u4eec\u51b3\u5b9a\u589e\u52a0\u4e00\u4e2a\u989d\u5916\u7684\u53d8\u91cf\uff0c\u4f8b\u5982\u7528\u4e8e\u7a33\u5b9a\u7684\u538b\u529b\u53d8\u91cf\uff0c\u5e76\u78b0\u5de7\u5c06\u5176\u4f5c\u4e3a\u5143\u7d20\u7684\u7b2c\u4e00\u4e2a\u53d8\u91cf\u63d2\u5165\uff0c\u90a3\u4e48\u4e0b\u9762\u7684\u8ba1\u7b97\u5c06\u5f00\u59cb\u4ea7\u751f\u65e0\u610f\u4e49\u7684\u7ed3\u679c\u3002\u6b64\u5916\uff0c\u8fd9\u79cd\u8ba1\u7b97\u8fd8\u4f9d\u8d56\u4e8e\u5176\u4ed6\u5047\u8bbe\uff1a\u9996\u5148\uff0c\u6211\u4eec\u4f7f\u7528\u7684\u5143\u7d20\u786e\u5b9e\u6709\u4e0e\u9876\u70b9\u76f8\u5173\u7684\u81ea\u7531\u5ea6\u3002\u5bf9\u4e8e\u76ee\u524d\u7684Q1\u5143\u7d20\u6765\u8bf4\u786e\u5b9e\u5982\u6b64\uff0c\u5bf9\u4e8e\u6240\u6709\u591a\u9879\u5f0f\u9636\u7684Qp\u5143\u7d20\u6765\u8bf4\u4e5f\u662f\u5982\u6b64  <code>p</code>  \u3002\u7136\u800c\uff0c\u8fd9\u5bf9\u4e0d\u8fde\u7eed\u7684\u5143\u7d20\u6216\u6df7\u5408\u516c\u5f0f\u7684\u5143\u7d20\u6765\u8bf4\u662f\u4e0d\u6210\u7acb\u7684\u3002\u5176\u6b21\uff0c\u5b83\u8fd8\u5efa\u7acb\u5728\u8fd9\u6837\u7684\u5047\u8bbe\u4e0a\uff1a\u4e00\u4e2a\u9876\u70b9\u7684\u4f4d\u79fb\u53ea\u7531\u4e0e\u8fd9\u4e2a\u9876\u70b9\u76f8\u5173\u7684\u81ea\u7531\u5ea6\u7684\u503c\u51b3\u5b9a\uff1b\u6362\u53e5\u8bdd\u8bf4\uff0c\u6240\u6709\u5bf9\u5e94\u4e8e\u5176\u4ed6\u81ea\u7531\u5ea6\u7684\u5f62\u72b6\u51fd\u6570\u5728\u8fd9\u4e2a\u7279\u5b9a\u7684\u9876\u70b9\u662f\u96f6\u3002\u540c\u6837\uff0c\u5bf9\u4e8e\u76ee\u524d\u7684\u5143\u7d20\u6765\u8bf4\u662f\u8fd9\u6837\u7684\uff0c\u4f46\u5bf9\u4e8e\u76ee\u524d\u5728deal.II\u4e2d\u7684\u6240\u6709\u5143\u7d20\u6765\u8bf4\u5e76\u975e\u5982\u6b64\u3002\u5c3d\u7ba1\u6709\u98ce\u9669\uff0c\u6211\u4eec\u8fd8\u662f\u9009\u62e9\u4f7f\u7528\u8fd9\u79cd\u65b9\u5f0f\uff0c\u4ee5\u4fbf\u63d0\u51fa\u4e00\u79cd\u67e5\u8be2\u4e0e\u9876\u70b9\u76f8\u5173\u7684\u5355\u4e2a\u81ea\u7531\u5ea6\u7684\u65b9\u6cd5\u3002\n\n// \u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0c\u6307\u51fa\u4e00\u79cd\u66f4\u666e\u904d\u7684\u65b9\u6cd5\u662f\u5f88\u6709\u610f\u4e49\u7684\u3002\u5bf9\u4e8e\u4e00\u822c\u7684\u6709\u9650\u5143\u6765\u8bf4\uff0c\u5e94\u8be5\u91c7\u7528\u6b63\u4ea4\u516c\u5f0f\uff0c\u5c06\u6b63\u4ea4\u70b9\u653e\u5728\u5355\u5143\u7684\u9876\u70b9\u4e0a\u3002\u68af\u5f62\u89c4\u5219\u7684 <code>QTrapezoid</code> \u516c\u5f0f\u6b63\u662f\u8fd9\u6837\u505a\u7684\u3002\u6709\u4e86\u8fd9\u4e2a\u6b63\u4ea4\u516c\u5f0f\uff0c\u6211\u4eec\u5c31\u53ef\u4ee5\u5728\u6bcf\u4e2a\u5355\u5143\u683c\u4e2d\u521d\u59cb\u5316\u4e00\u4e2a <code>FEValues</code> \u5bf9\u8c61\uff0c\u5e76\u4f7f\u7528 <code>FEValues::get_function_values</code> \u51fd\u6570\u6765\u83b7\u5f97\u6b63\u4ea4\u70b9\uff0c\u5373\u5355\u5143\u683c\u9876\u70b9\u7684\u89e3\u51fd\u6570\u503c\u3002\u8fd9\u4e9b\u662f\u6211\u4eec\u771f\u6b63\u9700\u8981\u7684\u552f\u4e00\u6570\u503c\uff0c\u4e5f\u5c31\u662f\u8bf4\uff0c\u6211\u4eec\u5bf9\u4e0e\u8fd9\u4e2a\u7279\u5b9a\u6b63\u4ea4\u516c\u5f0f\u76f8\u5173\u7684\u6743\u91cd\uff08\u6216 <code>JxW</code> \u503c\uff09\u5b8c\u5168\u4e0d\u611f\u5174\u8da3\uff0c\u8fd9\u53ef\u4ee5\u4f5c\u4e3a <code>FEValues</code> \u6784\u9020\u5668\u7684\u6700\u540e\u4e00\u4e2a\u53c2\u6570\u6765\u6307\u5b9a\u3002\u8fd9\u4e2a\u65b9\u6848\u4e2d\u552f\u4e00\u7684\u4e00\u70b9\u5c0f\u9ebb\u70e6\u662f\uff0c\u6211\u4eec\u5fc5\u987b\u5f04\u6e05\u695a\u54ea\u4e2a\u6b63\u4ea4\u70b9\u5bf9\u5e94\u4e8e\u6211\u4eec\u76ee\u524d\u8003\u8651\u7684\u9876\u70b9\uff0c\u56e0\u4e3a\u5b83\u4eec\u53ef\u80fd\u662f\u4ee5\u76f8\u540c\u7684\u987a\u5e8f\u6392\u5217\uff0c\u4e5f\u53ef\u80fd\u4e0d\u662f\u3002\n\n// \u5982\u679c\u6709\u9650\u5143\u5728\u9876\u70b9\u4e0a\u6709\u652f\u6301\u70b9\uff08\u8fd9\u91cc\u7684\u652f\u6301\u70b9\u662f\u6709\u7684\uff1b\u5173\u4e8e\u652f\u6301\u70b9\u7684\u6982\u5ff5\uff0c\u89c1 @ref GlossSupport \"\u652f\u6301\u70b9\"\uff09\uff0c\u8fd9\u79cd\u4e0d\u4fbf\u5c31\u53ef\u4ee5\u907f\u514d\u4e86\u3002\u5bf9\u4e8e\u8fd9\u79cd\u60c5\u51b5\uff0c\u6211\u4eec\u53ef\u4ee5\u4f7f\u7528 FiniteElement::get_unit_support_points(). \u6784\u5efa\u4e00\u4e2a\u81ea\u5b9a\u4e49\u7684\u6b63\u4ea4\u89c4\u5219\uff0c\u7136\u540e\u7b2c\u4e00\u4e2a <code>cell-&gt;n_vertices()*fe.dofs_per_vertex</code> \u6b63\u4ea4\u70b9\u5c06\u5bf9\u5e94\u4e8e\u5355\u5143\u683c\u7684\u9876\u70b9\uff0c\u5176\u987a\u5e8f\u4e0e <code>cell-@>vertex(i)</code> \u4e00\u81f4\uff0c\u540c\u65f6\u8003\u8651\u5230\u77e2\u91cf\u5143\u7d20\u7684\u652f\u6301\u70b9\u5c06\u88ab\u91cd\u590d <code>fe.dofs_per_vertex</code> \u6b21\u3002\n\n// \u5173\u4e8e\u8fd9\u4e2a\u77ed\u51fd\u6570\u503c\u5f97\u89e3\u91ca\u7684\u53e6\u4e00\u70b9\u662f\u4e09\u89d2\u5f62\u7c7b\u8f93\u51fa\u5176\u9876\u70b9\u4fe1\u606f\u7684\u65b9\u5f0f\uff1a\u901a\u8fc7 <code>Triangulation::n_vertices</code> \u51fd\u6570\uff0c\u5b83\u516c\u5e03\u4e86\u4e09\u89d2\u5f62\u4e2d\u6709\u591a\u5c11\u4e2a\u9876\u70b9\u3002\u5e76\u975e\u6240\u6709\u7684\u9876\u70b9\u90fd\u662f\u4e00\u76f4\u5728\u4f7f\u7528\u7684--\u6709\u4e9b\u662f\u4e4b\u524d\u88ab\u7c97\u5316\u7684\u5355\u5143\u7684\u9057\u7559\u7269\uff0c\u81ea\u4ecedeal.II\u4ee5\u6765\u4e00\u76f4\u5b58\u5728\uff0c\u4e00\u65e6\u4e00\u4e2a\u9876\u70b9\u51fa\u73b0\uff0c\u5373\u4f7f\u6570\u91cf\u8f83\u5c11\u7684\u9876\u70b9\u6d88\u5931\u4e86\uff0c\u4e5f\u4e0d\u4f1a\u6539\u53d8\u5b83\u7684\u7f16\u53f7\u3002\u5176\u6b21\uff0c <code>cell-@>vertex(v)</code> \u8fd4\u56de\u7684\u4f4d\u7f6e\u4e0d\u4ec5\u662f\u4e00\u4e2a\u7c7b\u578b\u4e3a <code>Point@<dim@></code> \u7684\u53ea\u8bfb\u5bf9\u8c61\uff0c\u800c\u4e14\u4e8b\u5b9e\u4e0a\u662f\u4e00\u4e2a\u53ef\u4ee5\u5199\u5165\u7684\u5f15\u7528\u3002\u8fd9\u5141\u8bb8\u76f8\u5bf9\u5bb9\u6613\u5730\u79fb\u52a8\u7f51\u683c\u7684\u8282\u70b9\uff0c\u4f46\u503c\u5f97\u6307\u51fa\u7684\u662f\uff0c\u4f7f\u7528\u8be5\u529f\u80fd\u7684\u5e94\u7528\u7a0b\u5e8f\u6709\u8d23\u4efb\u786e\u4fdd\u6240\u5f97\u5230\u7684\u5355\u5143\u4ecd\u7136\u6709\u7528\uff0c\u5373\u6ca1\u6709\u626d\u66f2\u5230\u5355\u5143\u9000\u5316\u7684\u7a0b\u5ea6\uff08\u4f8b\u5982\uff0c\u7528\u8d1f\u7684\u96c5\u5404\u5e03\u7cfb\u6570\u8868\u793a\uff09\u3002\u8bf7\u6ce8\u610f\uff0c\u6211\u4eec\u5728\u8fd9\u4e2a\u51fd\u6570\u4e2d\u6ca1\u6709\u4efb\u4f55\u89c4\u5b9a\u6765\u5b9e\u9645\u4fdd\u8bc1\u8fd9\u4e00\u70b9\uff0c\u6211\u4eec\u53ea\u662f\u6709\u4fe1\u5fc3\u3002\n\n// \u5728\u8fd9\u4e2a\u5197\u957f\u7684\u4ecb\u7ecd\u4e4b\u540e\uff0c\u4e0b\u9762\u662f\u5168\u90e820\u884c\u5de6\u53f3\u7684\u4ee3\u7801\u3002\n\n  template <int dim> \n  void TopLevel<dim>::move_mesh() \n  { \n    pcout << \"    Moving mesh...\" << std::endl; \n\n    std::vector<bool> vertex_touched(triangulation.n_vertices(), false); \n    for (auto &cell : dof_handler.active_cell_iterators()) \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                incremental_displacement(cell->vertex_dof_index(v, d)); \n\n            cell->vertex(v) += vertex_displacement; \n          } \n  } \n// @sect4{TopLevel::setup_quadrature_point_history}  \n\n// \u5728\u8ba1\u7b97\u7684\u5f00\u59cb\uff0c\u6211\u4eec\u9700\u8981\u8bbe\u7f6e\u5386\u53f2\u53d8\u91cf\u7684\u521d\u59cb\u503c\uff0c\u4f8b\u5982\u6750\u6599\u4e2d\u7684\u73b0\u6709\u5e94\u529b\uff0c\u6211\u4eec\u5c06\u5176\u5b58\u50a8\u5728\u6bcf\u4e2a\u6b63\u4ea4\u70b9\u4e2d\u3002\u5982\u4e0a\u6240\u8ff0\uff0c\u6211\u4eec\u4f7f\u7528\u6bcf\u4e2a\u5355\u5143\u4e2d\u90fd\u6709\u7684 <code>user_pointer</code> \u6765\u505a\u8fd9\u4e2a\u3002\n\n// \u4e3a\u4e86\u4ece\u66f4\u5927\u7684\u89d2\u5ea6\u770b\u8fd9\u4e2a\u95ee\u9898\uff0c\u6211\u4eec\u6ce8\u610f\u5230\uff0c\u5982\u679c\u6211\u4eec\u7684\u6a21\u578b\u4e2d\u6709\u5148\u524d\u53ef\u7528\u7684\u5e94\u529b\uff08\u4e3a\u4e86\u8fd9\u4e2a\u7a0b\u5e8f\u7684\u76ee\u7684\uff0c\u6211\u4eec\u5047\u5b9a\u8fd9\u4e9b\u5e94\u529b\u4e0d\u5b58\u5728\uff09\uff0c\u90a3\u4e48\u6211\u4eec\u5c31\u9700\u8981\u5c06\u5148\u524d\u5b58\u5728\u7684\u5e94\u529b\u573a\u63d2\u503c\u5230\u6b63\u4ea4\u70b9\u4e0a\u3002\u540c\u6837\uff0c\u5982\u679c\u6211\u4eec\u8981\u6a21\u62df\u5177\u6709\u786c\u5316/\u8f6f\u5316\u7684\u5f39\u5851\u6027\u6750\u6599\uff0c\u90a3\u4e48\u6211\u4eec\u5c31\u5fc5\u987b\u5728\u6bcf\u4e2a\u6b63\u4ea4\u70b9\u5b58\u50a8\u989d\u5916\u7684\u5386\u53f2\u53d8\u91cf\uff0c\u5982\u7d2f\u79ef\u5851\u6027\u5e94\u53d8\u7684\u5f53\u524d\u5c48\u670d\u5e94\u529b\u3002\u9884\u5148\u5b58\u5728\u7684\u786c\u5316\u6216\u5f31\u5316\u4e5f\u5c06\u901a\u8fc7\u5728\u5f53\u524d\u51fd\u6570\u4e2d\u63d2\u503c\u8fd9\u4e9b\u53d8\u91cf\u6765\u5b9e\u73b0\u3002\n\n  template <int dim> \n  void TopLevel<dim>::setup_quadrature_point_history() \n  { \n\n// \u4e3a\u4e86\u614e\u91cd\u8d77\u89c1\uff0c\u6211\u4eec\u628a\u6240\u6709\u5355\u5143\u683c\u7684\u7528\u6237\u6307\u9488\uff0c\u4e0d\u7ba1\u662f\u4e0d\u662f\u6211\u4eec\u7684\uff0c\u90fd\u8bbe\u7f6e\u4e3a\u7a7a\u6307\u9488\u3002\u8fd9\u6837\uff0c\u5982\u679c\u6211\u4eec\u8bbf\u95ee\u4e86\u4e0d\u5e94\u8be5\u8bbf\u95ee\u7684\u5355\u5143\u683c\u7684\u7528\u6237\u6307\u9488\uff0c\u4e00\u4e2a\u5206\u6bb5\u6545\u969c\u5c06\u8ba9\u6211\u4eec\u77e5\u9053\u8fd9\u4e0d\u5e94\u8be5\u53d1\u751f\u3002\n\n    triangulation.clear_user_data(); \n\n// \u63a5\u4e0b\u6765\uff0c\u5206\u914d\u5c5e\u4e8e\u8fd9\u4e2a\u5904\u7406\u5668\u804c\u8d23\u8303\u56f4\u5185\u7684\u6b63\u4ea4\u5bf9\u8c61\u3002\u5f53\u7136\uff0c\u8fd9\u7b49\u4e8e\u5c5e\u4e8e\u8fd9\u4e2a\u5904\u7406\u5668\u7684\u5355\u5143\u683c\u7684\u6570\u91cf\u4e58\u4ee5\u6211\u4eec\u7684\u6b63\u4ea4\u516c\u5f0f\u5728\u6bcf\u4e2a\u5355\u5143\u683c\u4e0a\u7684\u6b63\u4ea4\u70b9\u7684\u6570\u91cf\u3002\u7531\u4e8e`resize()`\u51fd\u6570\u5728\u8981\u6c42\u7684\u65b0\u5927\u5c0f\u5c0f\u4e8e\u65e7\u5927\u5c0f\u7684\u60c5\u51b5\u4e0b\uff0c\u5b9e\u9645\u4e0a\u5e76\u6ca1\u6709\u7f29\u5c0f\u5206\u914d\u7684\u5185\u5b58\u91cf\uff0c\u6240\u4ee5\u6211\u4eec\u91c7\u7528\u4e86\u4e00\u4e2a\u6280\u5de7\uff0c\u9996\u5148\u91ca\u653e\u6240\u6709\u7684\u5185\u5b58\uff0c\u7136\u540e\u518d\u91cd\u65b0\u5206\u914d\uff1a\u6211\u4eec\u58f0\u660e\u4e00\u4e2a\u7a7a\u5411\u91cf\u4f5c\u4e3a\u4e34\u65f6\u53d8\u91cf\uff0c\u7136\u540e\u4ea4\u6362\u65e7\u5411\u91cf\u548c\u8fd9\u4e2a\u4e34\u65f6\u53d8\u91cf\u7684\u5185\u5bb9\u3002\u8fd9\u5c31\u786e\u4fdd\u4e86`\u6b63\u4ea4\u70b9\u5386\u53f2'\u73b0\u5728\u786e\u5b9e\u662f\u7a7a\u7684\uff0c\u6211\u4eec\u53ef\u4ee5\u8ba9\u73b0\u5728\u4fdd\u5b58\u7740\u4ee5\u524d\u7684\u5411\u91cf\u5185\u5bb9\u7684\u4e34\u65f6\u53d8\u91cf\u8d85\u51fa\u8303\u56f4\u5e76\u88ab\u9500\u6bc1\u3002\u5728\u4e0b\u4e00\u6b65\u4e2d\uff0c\u6211\u4eec\u53ef\u4ee5\u6839\u636e\u9700\u8981\u91cd\u65b0\u5206\u914d\u5c3d\u53ef\u80fd\u591a\u7684\u5143\u7d20\uff0c\u77e2\u91cf\u9ed8\u8ba4\u521d\u59cb\u5316`PointHistory`\u5bf9\u8c61\uff0c\u8fd9\u5305\u62ec\u5c06\u538b\u529b\u53d8\u91cf\u8bbe\u7f6e\u4e3a\u96f6\u3002\n\n    { \n      std::vector<PointHistory<dim>> tmp; \n      quadrature_point_history.swap(tmp); \n    } \n    quadrature_point_history.resize( \n      triangulation.n_locally_owned_active_cells() * quadrature_formula.size()); \n\n// \u6700\u540e\u518d\u6b21\u5faa\u73af\u6240\u6709\u5355\u5143\uff0c\u5e76\u5c06\u5c5e\u4e8e\u672c\u5904\u7406\u5668\u7684\u5355\u5143\u7684\u7528\u6237\u6307\u9488\u8bbe\u7f6e\u4e3a\u6307\u5411\u6b64\u7c7b\u5bf9\u8c61\u7684\u5411\u91cf\u4e2d\u4e0e\u672c\u5355\u5143\u5bf9\u5e94\u7684\u7b2c\u4e00\u4e2a\u6b63\u4ea4\u70b9\u5bf9\u8c61\u3002\n\n    unsigned int history_index = 0; \n    for (auto &cell : triangulation.active_cell_iterators()) \n      if (cell->is_locally_owned()) \n        { \n          cell->set_user_pointer(&quadrature_point_history[history_index]); \n          history_index += quadrature_formula.size(); \n        } \n\n// \u6700\u540e\uff0c\u4e3a\u4e86\u614e\u91cd\u8d77\u89c1\uff0c\u786e\u4fdd\u6211\u4eec\u5bf9\u5143\u7d20\u7684\u8ba1\u6570\u662f\u6b63\u786e\u7684\uff0c\u800c\u4e14\u6211\u4eec\u5df2\u7ecf\u7528\u5b8c\u4e86\u4e4b\u524d\u5206\u914d\u7684\u6240\u6709\u5bf9\u8c61\uff0c\u5e76\u4e14\u6ca1\u6709\u6307\u5411\u4efb\u4f55\u8d85\u51fa\u5411\u91cf\u672b\u7aef\u7684\u5bf9\u8c61\u3002\u8fd9\u6837\u7684\u9632\u5fa1\u6027\u7f16\u7a0b\u7b56\u7565\u603b\u662f\u5f88\u597d\u7684\u68c0\u67e5\uff0c\u4ee5\u907f\u514d\u610f\u5916\u7684\u9519\u8bef\uff0c\u5e76\u9632\u6b62\u5c06\u6765\u5bf9\u8fd9\u4e2a\u51fd\u6570\u7684\u4fee\u6539\u5fd8\u8bb0\u540c\u65f6\u66f4\u65b0\u4e00\u4e2a\u53d8\u91cf\u7684\u6240\u6709\u7528\u9014\u3002\u56de\u987e\u4e00\u4e0b\uff0c\u4f7f\u7528 <code>Assert</code> \u5b8f\u7684\u6784\u9020\u5728\u4f18\u5316\u6a21\u5f0f\u4e0b\u88ab\u4f18\u5316\u6389\u4e86\uff0c\u6240\u4ee5\u4e0d\u5f71\u54cd\u4f18\u5316\u8fd0\u884c\u7684\u8fd0\u884c\u65f6\u95f4\u3002\n\n    Assert(history_index == quadrature_point_history.size(), \n           ExcInternalError()); \n  } \n\n//  @sect4{TopLevel::update_quadrature_point_history}  \n\n// \u5728\u6bcf\u4e2a\u65f6\u95f4\u6b65\u9aa4\u7ed3\u675f\u65f6\uff0c\u6211\u4eec\u5e94\u8be5\u8ba1\u7b97\u51fa\u4e00\u4e2a\u589e\u91cf\u7684\u4f4d\u79fb\u66f4\u65b0\uff0c\u4f7f\u6750\u6599\u5728\u5176\u65b0\u7684\u914d\u7f6e\u4e2d\u80fd\u591f\u5bb9\u7eb3\u8fd9\u4e2a\u65f6\u95f4\u6b65\u9aa4\u4e2d\u65bd\u52a0\u7684\u5916\u90e8\u4f53\u548c\u8fb9\u754c\u529b\u51cf\u53bb\u901a\u8fc7\u9884\u5148\u5b58\u5728\u7684\u5185\u90e8\u5e94\u529b\u65bd\u52a0\u7684\u529b\u4e4b\u95f4\u7684\u5dee\u5f02\u3002\u4e3a\u4e86\u5728\u4e0b\u4e00\u4e2a\u65f6\u95f4\u6b65\u9aa4\u4e2d\u83b7\u5f97\u9884\u5148\u5b58\u5728\u7684\u5e94\u529b\uff0c\u6211\u4eec\u5fc5\u987b\u7528\u672c\u65f6\u95f4\u6b65\u9aa4\u4e2d\u8ba1\u7b97\u7684\u589e\u91cf\u4f4d\u79fb\u5f15\u8d77\u7684\u5e94\u529b\u6765\u66f4\u65b0\u9884\u5148\u5b58\u5728\u7684\u5e94\u529b\u3002\u7406\u60f3\u60c5\u51b5\u4e0b\uff0c\u6240\u4ea7\u751f\u7684\u5185\u5e94\u529b\u4e4b\u548c\u5c06\u5b8c\u5168\u62b5\u6d88\u6240\u6709\u7684\u5916\u529b\u3002\u4e8b\u5b9e\u4e0a\uff0c\u4e00\u4e2a\u7b80\u5355\u7684\u5b9e\u9a8c\u53ef\u4ee5\u786e\u4fdd\u8fd9\u4e00\u70b9\uff1a\u5982\u679c\u6211\u4eec\u9009\u62e9\u8fb9\u754c\u6761\u4ef6\u548c\u4f53\u529b\u4e0e\u65f6\u95f4\u65e0\u5173\uff0c\u90a3\u4e48\u5f3a\u8feb\u9879\uff08\u5916\u529b\u548c\u5185\u5e94\u529b\u4e4b\u548c\uff09\u5e94\u8be5\u6b63\u597d\u662f\u96f6\u3002\u5982\u679c\u4f60\u505a\u4e86\u8fd9\u4e2a\u5b9e\u9a8c\uff0c\u4f60\u4f1a\u4ece\u6bcf\u4e2a\u65f6\u95f4\u6b65\u957f\u7684\u53f3\u624b\u8fb9\u7684\u89c4\u8303\u8f93\u51fa\u4e2d\u610f\u8bc6\u5230\u8fd9\u51e0\u4e4e\u662f\u4e8b\u5b9e\uff1a\u5b83\u5e76\u4e0d\u5b8c\u5168\u662f\u96f6\uff0c\u56e0\u4e3a\u5728\u7b2c\u4e00\u4e2a\u65f6\u95f4\u6b65\u957f\u4e2d\uff0c\u589e\u91cf\u4f4d\u79fb\u548c\u5e94\u529b\u7684\u66f4\u65b0\u662f\u76f8\u5bf9\u4e8e\u672a\u53d8\u5f62\u7684\u7f51\u683c\u8ba1\u7b97\u7684\uff0c\u7136\u540e\u518d\u8fdb\u884c\u53d8\u5f62\u3002\u5728\u7b2c\u4e8c\u4e2a\u65f6\u95f4\u6b65\u9aa4\u4e2d\uff0c\u6211\u4eec\u518d\u6b21\u8ba1\u7b97\u4f4d\u79fb\u548c\u5e94\u529b\u7684\u66f4\u65b0\uff0c\u4f46\u8fd9\u6b21\u662f\u5728\u53d8\u5f62\u7684\u7f51\u683c\u4e2d -- \u5728\u90a3\u91cc\uff0c\u7ed3\u679c\u7684\u66f4\u65b0\u975e\u5e38\u5c0f\u4f46\u4e0d\u5b8c\u5168\u662f\u96f6\u3002\u8fd9\u53ef\u4ee5\u8fed\u4ee3\uff0c\u5728\u6bcf\u4e00\u6b21\u8fed\u4ee3\u4e2d\uff0c\u6b8b\u5dee\uff0c\u5373\u53f3\u624b\u8fb9\u5411\u91cf\u7684\u6cd5\u7ebf\uff0c\u90fd\u4f1a\u51cf\u5c11\uff1b\u5982\u679c\u505a\u8fd9\u4e2a\u5c0f\u5b9e\u9a8c\uff0c\u5c31\u4f1a\u53d1\u73b0\u8fd9\u4e2a\u6b8b\u5dee\u7684\u6cd5\u7ebf\u4f1a\u968f\u7740\u8fed\u4ee3\u6b21\u6570\u7684\u589e\u52a0\u800c\u5448\u6307\u6570\u4e0b\u964d\uff0c\u5728\u6700\u521d\u7684\u5feb\u901f\u4e0b\u964d\u4e4b\u540e\uff0c\u6bcf\u6b21\u8fed\u4ee3\u5927\u7ea6\u4f1a\u51cf\u5c113.5\u500d\uff08\u5bf9\u4e8e\u6211\u770b\u7684\u4e00\u4e2a\u6d4b\u8bd5\u6848\u4f8b\uff0c\u5176\u4ed6\u6d4b\u8bd5\u6848\u4f8b\u548c\u5176\u4ed6\u672a\u77e5\u6570\u90fd\u4f1a\u6539\u53d8\u8fd9\u4e2a\u7cfb\u6570\uff0c\u4f46\u4e0d\u4f1a\u6539\u53d8\u6307\u6570\u4e0b\u964d\u7684\u60c5\u51b5\uff09\u3002\n\n// \u5728\u67d0\u79cd\u610f\u4e49\u4e0a\uff0c\u8fd9\u53ef\u4ee5\u88ab\u8ba4\u4e3a\u662f\u4e00\u4e2a\u51c6\u65f6\u5e8f\u65b9\u6848\uff0c\u4ee5\u89e3\u51b3\u5728\u4e00\u4e2a\u4ee5\u62c9\u683c\u6717\u65e5\u65b9\u5f0f\u79fb\u52a8\u7684\u7f51\u683c\u4e0a\u89e3\u51b3\u5927\u53d8\u5f62\u5f39\u6027\u7684\u975e\u7ebf\u6027\u95ee\u9898\u3002\n\n// \u53e6\u4e00\u4e2a\u590d\u6742\u7684\u95ee\u9898\u662f\uff0c\u73b0\u6709\u7684\uff08\u65e7\u7684\uff09\u5e94\u529b\u662f\u5728\u65e7\u7684\u7f51\u683c\u4e0a\u5b9a\u4e49\u7684\uff0c\u6211\u4eec\u5c06\u5728\u66f4\u65b0\u5e94\u529b\u540e\u79fb\u52a8\u8fd9\u4e2a\u7f51\u683c\u3002\u5982\u679c\u8fd9\u4e2a\u7f51\u683c\u7684\u66f4\u65b0\u6d89\u53ca\u5230\u5355\u5143\u7684\u65cb\u8f6c\uff0c\u90a3\u4e48\u6211\u4eec\u4e5f\u9700\u8981\u5bf9\u66f4\u65b0\u7684\u5e94\u529b\u8fdb\u884c\u65cb\u8f6c\uff0c\u56e0\u4e3a\u5b83\u662f\u76f8\u5bf9\u4e8e\u65e7\u5355\u5143\u7684\u5750\u6807\u7cfb\u8ba1\u7b97\u7684\u3002\n\n// \u56e0\u6b64\uff0c\u6211\u4eec\u9700\u8981\u7684\u662f\uff1a\u5728\u5f53\u524d\u5904\u7406\u5668\u62e5\u6709\u7684\u6bcf\u4e2a\u5355\u5143\u4e0a\uff0c\u6211\u4eec\u9700\u8981\u4ece\u6bcf\u4e2a\u6b63\u4ea4\u70b9\u5b58\u50a8\u7684\u6570\u636e\u4e2d\u63d0\u53d6\u65e7\u7684\u5e94\u529b\uff0c\u8ba1\u7b97\u5e94\u529b\u66f4\u65b0\uff0c\u5c06\u4e24\u8005\u76f8\u52a0\uff0c\u7136\u540e\u5c06\u7ed3\u679c\u4e0e\u4ece\u5f53\u524d\u6b63\u4ea4\u70b9\u7684\u589e\u91cf\u4f4d\u79fb\u8ba1\u7b97\u51fa\u6765\u7684\u589e\u91cf\u65cb\u8f6c\u4e00\u8d77\u65cb\u8f6c\u3002\u4e0b\u9762\u6211\u4eec\u5c06\u8be6\u7ec6\u4ecb\u7ecd\u8fd9\u4e9b\u6b65\u9aa4\u3002\n\n  template <int dim> \n  void TopLevel<dim>::update_quadrature_point_history() \n  { \n\n// \u9996\u5148\uff0c\u5efa\u7acb\u4e00\u4e2a <code>FEValues</code> \u5bf9\u8c61\uff0c\u6211\u4eec\u5c06\u901a\u8fc7\u5b83\u6765\u8bc4\u4f30\u6b63\u4ea4\u70b9\u7684\u589e\u91cf\u4f4d\u79fb\u53ca\u5176\u68af\u5ea6\uff0c\u8fd8\u6709\u4e00\u4e2a\u4fdd\u5b58\u8fd9\u4e9b\u4fe1\u606f\u7684\u5411\u91cf\u3002\n\n    FEValues<dim> fe_values(fe, \n                            quadrature_formula, \n                            update_values | update_gradients); \n\n    std::vector<std::vector<Tensor<1, dim>>> displacement_increment_grads( \n      quadrature_formula.size(), std::vector<Tensor<1, dim>>(dim)); \n\n// \u7136\u540e\u5728\u6240\u6709\u5355\u5143\u683c\u4e0a\u5faa\u73af\uff0c\u5728\u5c5e\u4e8e\u6211\u4eec\u5b50\u57df\u7684\u5355\u5143\u683c\u4e2d\u8fdb\u884c\u5de5\u4f5c\u3002\n\n    for (auto &cell : dof_handler.active_cell_iterators()) \n      if (cell->is_locally_owned()) \n        { \n\n// \u63a5\u4e0b\u6765\uff0c\u83b7\u5f97\u4e00\u4e2a\u6307\u5411\u5f53\u524d\u5355\u5143\u672c\u5730\u6b63\u4ea4\u70b9\u5386\u53f2\u6570\u636e\u7684\u6307\u9488\uff0c\u4f5c\u4e3a\u9632\u5fa1\u63aa\u65bd\uff0c\u786e\u4fdd\u8fd9\u4e2a\u6307\u9488\u5728\u5168\u5c40\u6570\u7ec4\u7684\u8303\u56f4\u5185\u3002\n\n          PointHistory<dim> *local_quadrature_points_history = \n            reinterpret_cast<PointHistory<dim> *>(cell->user_pointer()); \n          Assert(local_quadrature_points_history >= \n                   &quadrature_point_history.front(), \n                 ExcInternalError()); \n          Assert(local_quadrature_points_history <= \n                   &quadrature_point_history.back(), \n                 ExcInternalError()); \n\n// \u7136\u540e\u5728\u672c\u5355\u5143\u4e0a\u521d\u59cb\u5316 <code>FEValues</code> \u5bf9\u8c61\uff0c\u5e76\u63d0\u53d6\u6b63\u4ea4\u70b9\u4e0a\u7684\u4f4d\u79fb\u68af\u5ea6\uff0c\u4ee5\u4fbf\u4ee5\u540e\u8ba1\u7b97\u5e94\u53d8\u3002\n\n          fe_values.reinit(cell); \n          fe_values.get_function_gradients(incremental_displacement, \n                                           displacement_increment_grads); \n\n// \u7136\u540e\u5728\u8fd9\u4e2a\u5355\u5143\u7684\u6b63\u4ea4\u70b9\u4e0a\u5faa\u73af\u3002\n\n          for (unsigned int q = 0; q < quadrature_formula.size(); ++q) \n            { \n\n// \u5728\u6bcf\u4e2a\u6b63\u4ea4\u70b9\u4e0a\uff0c\u4ece\u68af\u5ea6\u4e2d\u8ba1\u7b97\u51fa\u5e94\u53d8\u589e\u91cf\uff0c\u5e76\u5c06\u5176\u4e58\u4ee5\u5e94\u529b-\u5e94\u53d8\u5f20\u91cf\uff0c\u5f97\u5230\u5e94\u529b\u66f4\u65b0\u3002\u7136\u540e\u5c06\u6b64\u66f4\u65b0\u6dfb\u52a0\u5230\u8be5\u70b9\u5df2\u6709\u7684\u5e94\u53d8\u4e2d\u3002\n\n              const SymmetricTensor<2, dim> new_stress = \n                (local_quadrature_points_history[q].old_stress + \n                 (stress_strain_tensor * \n                  get_strain(displacement_increment_grads[q]))); \n\n// \u6700\u540e\uff0c\u6211\u4eec\u8981\u5bf9\u7ed3\u679c\u8fdb\u884c\u65cb\u8f6c\u3002\u4e3a\u6b64\uff0c\u6211\u4eec\u9996\u5148\u8981\u4ece\u589e\u91cf\u4f4d\u79fb\u4e2d\u8ba1\u7b97\u51fa\u76ee\u524d\u6b63\u4ea4\u70b9\u7684\u65cb\u8f6c\u77e9\u9635\u3002\u4e8b\u5b9e\u4e0a\uff0c\u5b83\u53ef\u4ee5\u4ece\u68af\u5ea6\u4e2d\u8ba1\u7b97\u51fa\u6765\uff0c\u800c\u4e14\u6211\u4eec\u5df2\u7ecf\u6709\u4e00\u4e2a\u51fd\u6570\u7528\u4e8e\u8fd9\u4e2a\u76ee\u7684\u3002\n\n              const Tensor<2, dim> rotation = \n                get_rotation_matrix(displacement_increment_grads[q]); \n\n// \u6ce8\u610f\u8fd9\u4e2a\u7ed3\u679c\uff0c\u5373\u65cb\u8f6c\u77e9\u9635\uff0c\u4e00\u822c\u6765\u8bf4\u662f\u4e00\u4e2a\u7b49\u7ea7\u4e3a2\u7684\u53cd\u5bf9\u79f0\u5f20\u91cf\uff0c\u6240\u4ee5\u6211\u4eec\u5fc5\u987b\u628a\u5b83\u4f5c\u4e3a\u4e00\u4e2a\u5b8c\u6574\u7684\u5f20\u91cf\u6765\u5b58\u50a8\u3002\n\n// \u6709\u4e86\u8fd9\u4e2a\u65cb\u8f6c\u77e9\u9635\uff0c\u5728\u6211\u4eec\u5c06\u5bf9\u79f0\u5f20\u91cf <code>new_stress</code> \u6269\u5c55\u4e3a\u5168\u5f20\u91cf\u4e4b\u540e\uff0c\u6211\u4eec\u53ef\u4ee5\u901a\u8fc7\u4ece\u5de6\u548c\u53f3\u7684\u6536\u7f29\u6765\u8ba1\u7b97\u65cb\u8f6c\u7684\u5f20\u91cf\u3002\n\n              const SymmetricTensor<2, dim> rotated_new_stress = \n                symmetrize(transpose(rotation) * \n                           static_cast<Tensor<2, dim>>(new_stress) * rotation); \n\n// \u6ce8\u610f\uff0c\u867d\u7136\u8fd9\u4e09\u4e2a\u77e9\u9635\u7684\u4e58\u6cd5\u7ed3\u679c\u5e94\u8be5\u662f\u5bf9\u79f0\u7684\uff0c\u4f46\u7531\u4e8e\u6d6e\u70b9\u820d\u5165\u7684\u539f\u56e0\uff0c\u5b83\u5e76\u4e0d\u662f\u5bf9\u79f0\u7684\uff1a\u6211\u4eec\u5f97\u5230\u7684\u7ed3\u679c\u7684\u975e\u5bf9\u89d2\u7ebf\u5143\u7d20\u67091e-16\u7684\u4e0d\u5bf9\u79f0\u6027\u3002\u5f53\u628a\u7ed3\u679c\u8d4b\u7ed9\u4e00\u4e2a <code>SymmetricTensor</code> \u65f6\uff0c\u8be5\u7c7b\u7684\u6784\u9020\u51fd\u6570\u4f1a\u68c0\u67e5\u5bf9\u79f0\u6027\u5e76\u610f\u8bc6\u5230\u5b83\u4e0d\u662f\u5b8c\u5168\u5bf9\u79f0\u7684\uff1b\u7136\u540e\u5b83\u4f1a\u5f15\u53d1\u4e00\u4e2a\u5f02\u5e38\u3002\u4e3a\u4e86\u907f\u514d\u8fd9\u79cd\u60c5\u51b5\uff0c\u6211\u4eec\u660e\u786e\u5730\u5bf9\u7ed3\u679c\u8fdb\u884c\u5bf9\u79f0\uff0c\u4f7f\u5176\u5b8c\u5168\u5bf9\u79f0\u3002\n\n// \u6240\u6709\u8fd9\u4e9b\u64cd\u4f5c\u7684\u7ed3\u679c\u4f1a\u88ab\u5199\u56de\u5230\u539f\u6765\u7684\u5730\u65b9\u3002\n\n              local_quadrature_points_history[q].old_stress = \n                rotated_new_stress; \n            } \n        } \n  } \n\n// \u8fd9\u5c31\u7ed3\u675f\u4e86\u9879\u76ee\u7279\u5b9a\u7684\u547d\u540d\u7a7a\u95f4  <code>Step18</code>  \u3002\u5176\u4f59\u7684\u548c\u5f80\u5e38\u4e00\u6837\uff0c\u5e76\u4e14\u5728  step-17  \u4e2d\u5df2\u7ecf\u663e\u793a\uff1a\u4e00\u4e2a  <code>main()</code>  \u51fd\u6570\u521d\u59cb\u5316\u548c\u7ec8\u6b62 PETSc\uff0c\u8c03\u7528\u505a\u5b9e\u9645\u5de5\u4f5c\u7684\u7c7b\uff0c\u5e76\u786e\u4fdd\u6211\u4eec\u6355\u6349\u6240\u6709\u4f20\u64ad\u5230\u8fd9\u4e00\u70b9\u7684\u5f02\u5e38\u3002\n\n} // namespace Step18 \n\nint main(int argc, char **argv) \n{ \n  try \n    { \n      using namespace dealii; \n      using namespace Step18; \n\n      Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv, 1); \n\n      TopLevel<3> elastic_problem; \n      elastic_problem.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  return 0; \n} \n\n\n", "meta": {"hexsha": "2427a1bf23f51988859fb303076c9dc9bc5250fc", "size": 46702, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-18/step-18.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-18/step-18.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-18/step-18.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.9507923269, "max_line_length": 599, "alphanum_fraction": 0.6745107276, "num_tokens": 22198, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.49568391797785494}}
{"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 tanh-sinh quadrature on the real line.\n * Tanh-sinh quadrature is exponentially convergent for integrands in Hardy spaces,\n * (see https://en.wikipedia.org/wiki/Hardy_space for a formal definition), and is optimal for a random function from that class.\n *\n * The tanh-sinh quadrature is one of a class of so called \"double exponential quadratures\"-there is a large family of them,\n * but this one seems to be the most commonly used.\n *\n * As always, there are caveats: For instance, if the function you want to integrate is not holomorphic on the unit disk,\n * then the rapid convergence will be spoiled. In this case, a more appropriate quadrature is (say) Romberg, which does not\n * require the function to be holomorphic, only differentiable up to some order.\n *\n * In addition, if you are integrating a periodic function over a period, the trapezoidal rule is better.\n *\n * References:\n *\n * 1) Mori, Masatake. \"Quadrature formulas obtained by variable transformation and the DE-rule.\" Journal of Computational and Applied Mathematics 12 (1985): 119-130.\n * 2) Bailey, David H., Karthik Jeyabalan, and Xiaoye S. Li. \"A comparison of three high-precision quadrature schemes.\" Experimental Mathematics 14.3 (2005): 317-329.\n * 3) Press, William H., et al. \"Numerical recipes third edition: the art of scientific computing.\" Cambridge University Press 32 (2007): 10013-2473.\n *\n */\n\n#ifndef BOOST_MATH_QUADRATURE_TANH_SINH_HPP\n#define BOOST_MATH_QUADRATURE_TANH_SINH_HPP\n\n#include <cmath>\n#include <limits>\n#include <memory>\n#include <boost/math/quadrature/detail/tanh_sinh_detail.hpp>\n\nnamespace boost{ namespace math{ namespace quadrature {\n\ntemplate<class Real, class Policy = policies::policy<> >\nclass tanh_sinh\n{\npublic:\n    tanh_sinh(size_t max_refinements = 15, const Real& min_complement = tools::min_value<Real>() * 4)\n    : m_imp(std::make_shared<detail::tanh_sinh_detail<Real, Policy>>(max_refinements, min_complement)) {}\n\n    template<class F>\n    auto integrate(const F f, Real a, Real b, Real tolerance = tools::root_epsilon<Real>(), Real* error = nullptr, Real* L1 = nullptr, std::size_t* levels = nullptr) ->decltype(Real(std::declval<F>()(std::declval<Real>()))) const;\n    template<class F>\n    auto integrate(const F f, Real a, Real b, Real tolerance = tools::root_epsilon<Real>(), Real* error = nullptr, Real* L1 = nullptr, std::size_t* levels = nullptr) ->decltype(Real(std::declval<F>()(std::declval<Real>(), std::declval<Real>()))) const;\n\n    template<class F>\n    auto integrate(const F f, Real tolerance = tools::root_epsilon<Real>(), Real* error = nullptr, Real* L1 = nullptr, std::size_t* levels = nullptr) ->decltype(Real(std::declval<F>()(std::declval<Real>()))) const;\n    template<class F>\n    auto integrate(const F f, Real tolerance = tools::root_epsilon<Real>(), Real* error = nullptr, Real* L1 = nullptr, std::size_t* levels = nullptr) ->decltype(Real(std::declval<F>()(std::declval<Real>(), std::declval<Real>()))) const;\n\nprivate:\n    std::shared_ptr<detail::tanh_sinh_detail<Real, Policy>> m_imp;\n};\n\ntemplate<class Real, class Policy>\ntemplate<class F>\nauto tanh_sinh<Real, Policy>::integrate(const F f, Real a, Real b, Real tolerance, Real* error, Real* L1, std::size_t* levels) ->decltype(Real(std::declval<F>()(std::declval<Real>()))) const\n{\n    BOOST_MATH_STD_USING\n    using boost::math::constants::half;\n    using boost::math::quadrature::detail::tanh_sinh_detail;\n\n    static const char* function = \"tanh_sinh<%1%>::integrate\";\n\n    if (!(boost::math::isnan)(a) && !(boost::math::isnan)(b))\n    {\n\n       // Infinite limits:\n       if ((a <= -tools::max_value<Real>()) && (b >= tools::max_value<Real>()))\n       {\n          auto u = [&](const Real& t, const Real& tc)->Real \n          { \n             Real t_sq = t*t; \n             Real inv;\n             if (t > 0.5f)\n                inv = 1 / ((2 - tc) * tc);\n             else if(t < -0.5)\n                inv = 1 / ((2 + tc) * -tc);\n             else\n                inv = 1 / (1 - t_sq);\n             return f(t*inv)*(1 + t_sq)*inv*inv; \n          };\n          Real limit = sqrt(tools::min_value<Real>()) * 4;\n          return m_imp->integrate(u, error, L1, function, limit, limit, tolerance, levels);\n       }\n\n       // Right limit is infinite:\n       if ((boost::math::isfinite)(a) && (b >= tools::max_value<Real>()))\n       {\n          auto u = [&](const Real& t, const Real& tc)->Real \n          { \n             Real z, arg;\n             if (t > -0.5f)\n                z = 1 / (t + 1);\n             else\n                z = -1 / tc;\n             if (t < 0.5)\n                arg = 2 * z + a - 1;\n             else\n                arg = a + tc / (2 - tc);\n             return f(arg)*z*z; \n          };\n          Real left_limit = sqrt(tools::min_value<Real>()) * 4;\n          Real Q = 2 * m_imp->integrate(u, error, L1, function, left_limit, tools::min_value<Real>(), tolerance, levels);\n          if (L1)\n          {\n             *L1 *= 2;\n          }\n\n          return Q;\n       }\n\n       if ((boost::math::isfinite)(b) && (a <= -tools::max_value<Real>()))\n       {\n          auto v = [&](const Real& t, const Real& tc)->Real \n          { \n             Real z;\n             if (t > -0.5)\n                z = 1 / (t + 1);\n             else\n                z = -1 / tc;\n             Real arg;\n             if (t < 0.5)\n                arg = 2 * z - 1;\n             else\n                arg = tc / (2 - tc);\n             return f(b - arg) * z * z;\n          };\n\n          Real left_limit = sqrt(tools::min_value<Real>()) * 4;\n          Real Q = 2 * m_imp->integrate(v, error, L1, function, left_limit, tools::min_value<Real>(), tolerance, levels);\n          if (L1)\n          {\n             *L1 *= 2;\n          }\n          return Q;\n       }\n\n       if ((boost::math::isfinite)(a) && (boost::math::isfinite)(b))\n       {\n          if (b <= a)\n          {\n             return policies::raise_domain_error(function, \"Arguments to integrate are in wrong order; integration over [a,b] must have b > a.\", a, Policy());\n          }\n          Real avg = (a + b)*half<Real>();\n          Real diff = (b - a)*half<Real>();\n          Real avg_over_diff_m1 = a / diff;\n          Real avg_over_diff_p1 = b / diff;\n          bool have_small_left = fabs(a) < 0.5f;\n          bool have_small_right = fabs(b) < 0.5f;\n          Real left_min_complement = float_next(avg_over_diff_m1) - avg_over_diff_m1;\n          if (left_min_complement < tools::min_value<Real>())\n             left_min_complement = tools::min_value<Real>();\n          Real right_min_complement = avg_over_diff_p1 - float_prior(avg_over_diff_p1);\n          if (right_min_complement < tools::min_value<Real>())\n             right_min_complement = tools::min_value<Real>();\n          //\n          // These asserts will fail only if rounding errors on\n          // type Real have accumulated so much error that it's\n          // broken our internal logic.  Should that prove to be\n          // a persistent issue, we might need to add a bit of fudge\n          // factor to move left_min_complement and right_min_complement\n          // further from the end points of the range.\n          //\n          BOOST_ASSERT((left_min_complement * diff + a) > a);\n          BOOST_ASSERT((b - right_min_complement * diff) < b);\n          auto u = [&](Real z, Real zc)->Real\n          { \n             Real position;\n             if (z < -0.5)\n             {\n                if(have_small_left)\n                  return f(diff * (avg_over_diff_m1 - zc));\n                position = a - diff * zc;\n             }\n             if (z > 0.5)\n             {\n                if(have_small_right)\n                  return f(diff * (avg_over_diff_p1 - zc));\n                position = b - diff * zc;\n             }\n             else\n                position = avg + diff*z;\n             BOOST_ASSERT(position != a);\n             BOOST_ASSERT(position != b);\n             return f(position);\n          };\n          Real Q = diff*m_imp->integrate(u, error, L1, function, left_min_complement, right_min_complement, tolerance, levels);\n\n          if (L1)\n          {\n             *L1 *= diff;\n          }\n          return Q;\n       }\n    }\n    return policies::raise_domain_error(function, \"The domain of integration is not sensible; please check the bounds.\", a, Policy());\n}\n\ntemplate<class Real, class Policy>\ntemplate<class F>\nauto tanh_sinh<Real, Policy>::integrate(const F f, Real a, Real b, Real tolerance, Real* error, Real* L1, std::size_t* levels) ->decltype(Real(std::declval<F>()(std::declval<Real>(), std::declval<Real>()))) const\n{\n   BOOST_MATH_STD_USING\n      using boost::math::constants::half;\n   using boost::math::quadrature::detail::tanh_sinh_detail;\n\n   static const char* function = \"tanh_sinh<%1%>::integrate\";\n\n   if ((boost::math::isfinite)(a) && (boost::math::isfinite)(b))\n   {\n      if (b <= a)\n      {\n         return policies::raise_domain_error(function, \"Arguments to integrate are in wrong order; integration over [a,b] must have b > a.\", a, Policy());\n      }\n      auto u = [&](Real z, Real zc)->Real\n      {\n         if (z < 0)\n            return f((a - b) * zc / 2 + a, (b - a) * zc / 2);\n         else\n            return f((a - b) * zc / 2 + b, (b - a) * zc / 2);\n      };\n      Real diff = (b - a)*half<Real>();\n      Real left_min_complement = tools::min_value<Real>() * 4;\n      Real right_min_complement = tools::min_value<Real>() * 4;\n      Real Q = diff*m_imp->integrate(u, error, L1, function, left_min_complement, right_min_complement, tolerance, levels);\n\n      if (L1)\n      {\n         *L1 *= diff;\n      }\n      return Q;\n   }\n   return policies::raise_domain_error(function, \"The domain of integration is not sensible; please check the bounds.\", a, Policy());\n}\n\ntemplate<class Real, class Policy>\ntemplate<class F>\nauto tanh_sinh<Real, Policy>::integrate(const F f, Real tolerance, Real* error, Real* L1, std::size_t* levels) ->decltype(Real(std::declval<F>()(std::declval<Real>()))) const\n{\n   using boost::math::quadrature::detail::tanh_sinh_detail;\n   static const char* function = \"tanh_sinh<%1%>::integrate\";\n   Real min_complement = tools::epsilon<Real>();\n   return m_imp->integrate([&](const Real& arg, const Real&) { return f(arg); }, error, L1, function, min_complement, min_complement, tolerance, levels);\n}\n\ntemplate<class Real, class Policy>\ntemplate<class F>\nauto tanh_sinh<Real, Policy>::integrate(const F f, Real tolerance, Real* error, Real* L1, std::size_t* levels) ->decltype(Real(std::declval<F>()(std::declval<Real>(), std::declval<Real>()))) const\n{\n   using boost::math::quadrature::detail::tanh_sinh_detail;\n   static const char* function = \"tanh_sinh<%1%>::integrate\";\n   Real min_complement = tools::min_value<Real>() * 4;\n   return m_imp->integrate(f, error, L1, function, min_complement, min_complement, tolerance, levels);\n}\n\n}\n}\n}\n#endif\n", "meta": {"hexsha": "7305d93aa2be824c469edb1b3647aa28edd92605", "size": 11101, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/boost_1_68_0/boost/math/quadrature/tanh_sinh.hpp", "max_stars_repo_name": "KevinBoxuGao/Coordinate-Matcher-Commission", "max_stars_repo_head_hexsha": "5ec1a681cc9158d6eb72e6c802959eede329544a", "max_stars_repo_licenses": ["MIT"], "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": "lib/boost_1_68_0/boost/math/quadrature/tanh_sinh.hpp", "max_issues_repo_name": "KevinBoxuGao/Coordinate-Matcher-Commission", "max_issues_repo_head_hexsha": "5ec1a681cc9158d6eb72e6c802959eede329544a", "max_issues_repo_licenses": ["MIT"], "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": "deps/src/boost_1_68_0/boost/math/quadrature/tanh_sinh.hpp", "max_forks_repo_name": "ZeroInfinite/turicreate", "max_forks_repo_head_hexsha": "dd210c2563930881abd51fd69cb73007955b33fd", "max_forks_repo_licenses": ["BSD-3-Clause"], "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": 41.7330827068, "max_line_length": 252, "alphanum_fraction": 0.5917484911, "num_tokens": 2949, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.4956839179778548}}
{"text": "// This file is part of Eigen, a lightweight C++ template library\n// for linear algebra.\n//\n// Copyright (C) 2009 Benoit Jacob <jacob.benoit.1@gmail.com>\n//\n// Eigen 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 3 of the License, or (at your option) any later version.\n//\n// Alternatively, 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 2 of\n// the License, or (at your option) any later version.\n//\n// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY\n// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License and a copy of the GNU General Public License along with\n// Eigen. If not, see <http://www.gnu.org/licenses/>.\n\n#include \"main.h\"\n#include <Eigen/LU>\n#include <algorithm>\n\ntemplate<typename T> std::string type_name() { return \"other\"; }\ntemplate<> std::string type_name<float>() { return \"float\"; }\ntemplate<> std::string type_name<double>() { return \"double\"; }\ntemplate<> std::string type_name<int>() { return \"int\"; }\ntemplate<> std::string type_name<std::complex<float> >() { return \"complex<float>\"; }\ntemplate<> std::string type_name<std::complex<double> >() { return \"complex<double>\"; }\ntemplate<> std::string type_name<std::complex<int> >() { return \"complex<int>\"; }\n\n#define EIGEN_DEBUG_VAR(x) std::cerr << #x << \" = \" << x << std::endl;\n\ntemplate<typename T> inline typename NumTraits<T>::Real epsilon()\n{\n return std::numeric_limits<typename NumTraits<T>::Real>::epsilon();\n}\n\ntemplate<typename MatrixType> void inverse_permutation_4x4()\n{\n  typedef typename MatrixType::Scalar Scalar;\n  typedef typename MatrixType::RealScalar RealScalar;\n  Vector4i indices(0,1,2,3);\n  for(int i = 0; i < 24; ++i)\n  {\n    MatrixType m = MatrixType::Zero();\n    m(indices(0),0) = 1;\n    m(indices(1),1) = 1;\n    m(indices(2),2) = 1;\n    m(indices(3),3) = 1;\n    MatrixType inv = m.inverse();\n    double error = double( (m*inv-MatrixType::Identity()).norm() / epsilon<Scalar>() );\n    VERIFY(error == 0.0);\n    std::next_permutation(indices.data(),indices.data()+4);\n  }\n}\n\ntemplate<typename MatrixType> void inverse_general_4x4(int repeat)\n{\n  typedef typename MatrixType::Scalar Scalar;\n  typedef typename MatrixType::RealScalar RealScalar;\n  double error_sum = 0., error_max = 0.;\n  for(int i = 0; i < repeat; ++i)\n  {\n    MatrixType m;\n    RealScalar absdet;\n    do {\n      m = MatrixType::Random();\n      absdet = ei_abs(m.determinant());\n    } while(absdet < 10 * epsilon<Scalar>());\n    MatrixType inv = m.inverse();\n    double error = double( (m*inv-MatrixType::Identity()).norm() * absdet / epsilon<Scalar>() );\n    error_sum += error;\n    error_max = std::max(error_max, error);\n  }\n  std::cerr << \"inverse_general_4x4, Scalar = \" << type_name<Scalar>() << std::endl;\n  double error_avg = error_sum / repeat;\n  EIGEN_DEBUG_VAR(error_avg);\n  EIGEN_DEBUG_VAR(error_max);\n  VERIFY(error_avg < (NumTraits<Scalar>::IsComplex ? 8.0 : 1.25));\n  VERIFY(error_max < (NumTraits<Scalar>::IsComplex ? 64.0 : 20.0));\n}\n\nvoid test_eigen2_prec_inverse_4x4()\n{\n  CALL_SUBTEST_1((inverse_permutation_4x4<Matrix4f>()));\n  CALL_SUBTEST_1(( inverse_general_4x4<Matrix4f>(200000 * g_repeat) ));\n\n  CALL_SUBTEST_2((inverse_permutation_4x4<Matrix<double,4,4,RowMajor> >()));\n  CALL_SUBTEST_2(( inverse_general_4x4<Matrix<double,4,4,RowMajor> >(200000 * g_repeat) ));\n\n  CALL_SUBTEST_3((inverse_permutation_4x4<Matrix4cf>()));\n  CALL_SUBTEST_3((inverse_general_4x4<Matrix4cf>(50000 * g_repeat)));\n}\n", "meta": {"hexsha": "5117c8095ae751c0e5c5fa106ae7f461e9db510c", "size": 3892, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Plugins/SciberQuestToolKit/eigen-3.0.3/eigen-eigen-3.0.3/test/eigen2/eigen2_prec_inverse_4x4.cpp", "max_stars_repo_name": "mathstuf/ParaView", "max_stars_repo_head_hexsha": "e867e280545ada10c4ed137f6a966d9d2f3db4cb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2015-03-12T00:12:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-26T08:56:31.000Z", "max_issues_repo_path": "Plugins/SciberQuestToolKit/eigen-3.0.3/eigen-eigen-3.0.3/test/eigen2/eigen2_prec_inverse_4x4.cpp", "max_issues_repo_name": "mathstuf/ParaView", "max_issues_repo_head_hexsha": "e867e280545ada10c4ed137f6a966d9d2f3db4cb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-05-26T19:02:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-27T14:15:04.000Z", "max_forks_repo_path": "Plugins/SciberQuestToolKit/eigen-3.0.3/eigen-eigen-3.0.3/test/eigen2/eigen2_prec_inverse_4x4.cpp", "max_forks_repo_name": "mathstuf/ParaView", "max_forks_repo_head_hexsha": "e867e280545ada10c4ed137f6a966d9d2f3db4cb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2019-07-04T12:54:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T13:04:38.000Z", "avg_line_length": 38.92, "max_line_length": 96, "alphanum_fraction": 0.6993833505, "num_tokens": 1057, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.737158174177441, "lm_q2_score": 0.6723316991792861, "lm_q1q2_score": 0.4956148078086191}}
{"text": "//  Copyright Matt Borland 2021.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n//\n// Basic sanity check that header\n// #includes all the files that it needs to.\n#include <boost/math/differentiation/lanczos_smoothing.hpp>\n//\n// Note this header includes no other headers, this is\n// important if this test is to be meaningful:\n//\n#include \"test_compile_result.hpp\"\n\nvoid compile_and_link_test()\n{\n    float f_temp;\n    boost::math::differentiation::discrete_lanczos_derivative f_lanczos(f_temp);\n    check_result<float>(f_lanczos.get_spacing());\n\n    double d_temp;\n    boost::math::differentiation::discrete_lanczos_derivative d_lanczos(d_temp);\n    check_result<double>(d_lanczos.get_spacing());\n    \n    #ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n    long double ld_temp;\n    boost::math::differentiation::discrete_lanczos_derivative ld_lanczos(ld_temp);\n    check_result<long double>(ld_lanczos.get_spacing());\n    #endif\n}\n", "meta": {"hexsha": "38ba479b4bc6ec7132c527ae9c59dc6b7e4a5ea8", "size": 1078, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/compile_test/diff_lanczos_smoothing_incl_test.cpp", "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": "test/compile_test/diff_lanczos_smoothing_incl_test.cpp", "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": "test/compile_test/diff_lanczos_smoothing_incl_test.cpp", "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": 34.7741935484, "max_line_length": 82, "alphanum_fraction": 0.7578849722, "num_tokens": 266, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581741774411, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.49561480296880356}}
{"text": "#include <tiny_type_traits.h>\n#include <tiny_quaternion.h>\n#include <tiny_quaternion_functions.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n\nBOOST_AUTO_TEST_SUITE(tiny_quaternion_algebra);\n\nBOOST_AUTO_TEST_CASE(clear_test)\n{\t\n\ttypedef tiny::ScalarTraits<float>     T;\n  typedef tiny::Quaternion<T>           Q;\n  \n  Q A;\n  A.clear();\n  BOOST_CHECK_CLOSE( A.real() , 0.0f, 0.01f);\n  BOOST_CHECK_CLOSE( A.imag()(0) , 0.0f, 0.01f);\n  BOOST_CHECK_CLOSE( A.imag()(1) , 0.0f, 0.01f);\n  BOOST_CHECK_CLOSE( A.imag()(2) , 0.0f, 0.01f);  \n  BOOST_CHECK_CLOSE( A(0) , 0.0f, 0.01f);\n  BOOST_CHECK_CLOSE( A(1) , 0.0f, 0.01f);\n  BOOST_CHECK_CLOSE( A(2) , 0.0f, 0.01f);\n  BOOST_CHECK_CLOSE( A(3) , 0.0f, 0.01f);\n}\n\nBOOST_AUTO_TEST_CASE(component_indexing_test)\n{\t\n\ttypedef tiny::ScalarTraits<float>     T;\n  typedef tiny::Quaternion<T>           Q;\n  \n  Q A;\n  A.clear();\n  \n  A(0) = 1.0f;\n  A(1) = 2.0f;\n  A(2) = 3.0f;\n  A(3) = 4.0f;\n  \n  BOOST_CHECK_CLOSE( A(0) , 1.0f, 0.01f);\n  BOOST_CHECK_CLOSE( A(1) , 2.0f, 0.01f);\n  BOOST_CHECK_CLOSE( A(2) , 3.0f, 0.01f);\n  BOOST_CHECK_CLOSE( A(3) , 4.0f, 0.01f);\n \n}  \n\nBOOST_AUTO_TEST_CASE(scalar_mul_div_test)\n{\t\n\ttypedef tiny::ScalarTraits<float>     T;\n  typedef tiny::Quaternion<T>           Q;\n  \n  Q A( 4.0f, 1.0f, 2.0f, 3.0f);\n  \n  Q C;\n  C.clear();\n  \n  C = A*0.5f;\n  BOOST_CHECK_CLOSE( C(0) , 0.5f, 0.01f);\n  BOOST_CHECK_CLOSE( C(1) , 1.0f, 0.01f);\n  BOOST_CHECK_CLOSE( C(2) , 1.5f, 0.01f);\n  BOOST_CHECK_CLOSE( C(3) , 2.0f, 0.01f);\n    \n  C.clear();\n  C = 0.5f*A;\n  BOOST_CHECK_CLOSE( C(0) , 0.5f, 0.01f);\n  BOOST_CHECK_CLOSE( C(1) , 1.0f, 0.01f);\n  BOOST_CHECK_CLOSE( C(2) , 1.5f, 0.01f);\n  BOOST_CHECK_CLOSE( C(3) , 2.0f, 0.01f);\n  \n  C.clear();\n  C = A/2.0f;\n  BOOST_CHECK_CLOSE( C(0) , 0.5f, 0.01f);\n  BOOST_CHECK_CLOSE( C(1) , 1.0f, 0.01f);\n  BOOST_CHECK_CLOSE( C(2) , 1.5f, 0.01f);\n  BOOST_CHECK_CLOSE( C(3) , 2.0f, 0.01f);\n  \n}  \n\nBOOST_AUTO_TEST_CASE(diverse_ops_test)\n{\t\n\ttypedef tiny::ScalarTraits<float>     T;\n  typedef tiny::Quaternion<T>           Q;\n  typedef tiny::Matrix<3,3,T>           M;\n  typedef tiny::Vector<3,T>             V;\n  \n  Q A( 2.0f, 3.0f, 4.0f, 1.0f);\n  \n  Q C;\n  C = tiny::hat(A);\n  BOOST_CHECK_CLOSE( tiny::inner_prod(A,C), 0.0f, 0.01f);\n  \n  A   = Q::Ru( M::value_traits::pi_half(), V::i() );\n  Q B = Q::Rx( M::value_traits::pi_half() );\n  BOOST_CHECK_CLOSE( A(0) , B(0), 0.01f);\n  BOOST_CHECK_CLOSE( A(1) , B(1), 0.01f);\n  BOOST_CHECK_CLOSE( A(2) , B(2), 0.01f);\n  BOOST_CHECK_CLOSE( A(3) , B(3), 0.01f);\n  A = Q::Ru( M::value_traits::pi_half(), V::j() );\n  B = Q::Ry( M::value_traits::pi_half() );\n  BOOST_CHECK_CLOSE( A(0) , B(0), 0.01f);\n  BOOST_CHECK_CLOSE( A(1) , B(1), 0.01f);\n  BOOST_CHECK_CLOSE( A(2) , B(2), 0.01f);\n  BOOST_CHECK_CLOSE( A(3) , B(3), 0.01f);\n  A = Q::Ru( M::value_traits::pi_half(), V::k() );\n  B = Q::Rz( M::value_traits::pi_half() );\n  BOOST_CHECK_CLOSE( A(0) , B(0), 0.01f);\n  BOOST_CHECK_CLOSE( A(1) , B(1), 0.01f);\n  BOOST_CHECK_CLOSE( A(2) , B(2), 0.01f);\n  BOOST_CHECK_CLOSE( A(3) , B(3), 0.01f);\n  \n  A = tiny::make( M::Rx( M::value_traits::pi_half() ) );\n  B = Q::Rx( Q::value_traits::pi_half() );\n  BOOST_CHECK( std::fabs( A(0) - B(0) ) < 10e-7f);\n  BOOST_CHECK( std::fabs( A(1) - B(1) ) < 10e-7f);\n  BOOST_CHECK( std::fabs( A(2) - B(2) ) < 10e-7f);\n  BOOST_CHECK( std::fabs( A(3) - B(3) ) < 10e-7f);\n\n  A = tiny::make( M::Ry( M::value_traits::pi_half() ) );\n  B = Q::Ry( Q::value_traits::pi_half() );\n  BOOST_CHECK( std::fabs( A(0) - B(0) ) < 10e-7f);\n  BOOST_CHECK( std::fabs( A(1) - B(1) ) < 10e-7f);\n  BOOST_CHECK( std::fabs( A(2) - B(2) ) < 10e-7f);\n  BOOST_CHECK( std::fabs( A(3) - B(3) ) < 10e-7f);\n\n  A = tiny::make( M::Rz( M::value_traits::pi_half() ) );\n  B = Q::Rz( Q::value_traits::pi_half() );\n  BOOST_CHECK( std::fabs( A(0) - B(0) ) < 10e-7f);\n  BOOST_CHECK( std::fabs( A(1) - B(1) ) < 10e-7f);\n  BOOST_CHECK( std::fabs( A(2) - B(2) ) < 10e-7f);\n  BOOST_CHECK( std::fabs( A(3) - B(3) ) < 10e-7f);\n}  \n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "141f76da9213e8068ea320db17c916cacdcc64bc", "size": 4117, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/FOUNDATION/TINY/unit_tests/tiny_quaternion_algebra/tiny_quaternion_algebra.cpp", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-11-27T09:44:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-13T00:24:21.000Z", "max_issues_repo_path": "PROX/FOUNDATION/TINY/unit_tests/tiny_quaternion_algebra/tiny_quaternion_algebra.cpp", "max_issues_repo_name": "erleben/matchstick", "max_issues_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_issues_repo_licenses": ["MIT"], "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/FOUNDATION/TINY/unit_tests/tiny_quaternion_algebra/tiny_quaternion_algebra.cpp", "max_forks_repo_name": "erleben/matchstick", "max_forks_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_forks_repo_licenses": ["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.0510948905, "max_line_length": 57, "alphanum_fraction": 0.5936361428, "num_tokens": 1766, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799252, "lm_q2_score": 0.6723317123102956, "lm_q1q2_score": 0.4956148019590577}}
{"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_FMS_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_FMS_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n\n    @ingroup group-arithmetic\n    This function object computes the (fused) multiply substract of these three parameters.\n\n\n    @par Header <boost/simd/function/fms.hpp>\n\n    @par Notes\n    The call `fms(x, y, z)` is similar to `x*y-z`\n\n    But really conformant fused multiply/substract also implies\n\n    - only one rounding\n\n    - no \"intermediate\" overflow\n\n    fms provides this for all integral types and also each time it is reasonable\n    in terms of performance for floating ones (i.e. if the system has the hard\n    wired capability).\n\n    If you need pedantic fms capabilities in all circumstances in your own\n    code you can use the pedantic_ decorator (can be very expensive).\n\n    @par Decorators\n\n    - pedantic_ ensures the fms properties and allows SIMD acceleration if available.\n\n    @see fma, fnma, fnms\n\n    @par Example:\n\n      @snippet fms.cpp fms\n\n    @par Possible output:\n\n      @snippet fms.txt fms\n\n  **/\n  Value fms(Value const& x, Value const& y, Value const& z);\n} }\n#endif\n\n#include <boost/simd/function/scalar/fms.hpp>\n#include <boost/simd/function/simd/fms.hpp>\n\n#endif\n", "meta": {"hexsha": "14975ff1095cfc8816c3452936cba8848893a924", "size": 1658, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/fms.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/fms.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/fms.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": 25.5076923077, "max_line_length": 100, "alphanum_fraction": 0.6290711701, "num_tokens": 372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799252, "lm_q2_score": 0.6723317123102955, "lm_q1q2_score": 0.49561480195905766}}
{"text": "/*\r\n  y = freeDegreeTIEst(x,estLength,pen,maxPolyOrder);\r\n*/\r\n\r\n#include <math.h>\r\n#include <stdio.h>\r\n#include <stdlib.h>\r\n#include <iostream>\r\n#include <algorithm>\r\n\r\n#include <boost/python.hpp>\r\n#include <boost/python/suite/indexing/vector_indexing_suite.hpp>\r\n#include <boost/python/stl_iterator.hpp>\r\n\r\n\r\n//#include \"mex.h\"\r\n//#include \"matrix.h\"\r\n//#include \"mathHelper.c\"\r\n\r\n/* Code added by GV for compiling outside matlab */\r\n\r\ndouble realmax = 1e238 ;\r\ndouble realmin = 1e-307 ;\r\ndouble PI = 3.14159265359;\r\n\r\nusing namespace std;\r\n\r\n/* End of code added by GV */\r\n\r\nstruct tree\r\n{\r\n  struct tree *leftChild;\r\n  struct tree *rightChild;\r\n  int nObs, firstObsInInterval, maxPolyOrder, optPolyOrder;\r\n  double **polyCoeffs, *likelihoods;\r\n  double intervalLeft, intervalRight,optLikelihood;\r\n};\r\n\r\nvoid printTreeNode(struct tree *T, FILE *outfile)\r\n{\r\n  int i,k;\r\n  fprintf(outfile, \"Interval [%f,%f], polynomial order = %d\\n\",\r\n\t T->intervalLeft,T->intervalRight, T->optPolyOrder);\r\n  fprintf(outfile, \"\\tChebyshev polynomial coefficients:\\t\");\r\n  for (k = 0; k < T->optPolyOrder; k++) {\r\n    fprintf(outfile, \"%lf\\t\",T->polyCoeffs[T->optPolyOrder-1][k]);\r\n  }\r\n  fprintf(outfile,\"\\n\");\r\n}\r\n\r\nvoid printTree(struct tree *T, FILE *outFile)\r\n{\r\n  if (T == NULL) \r\n    return;\r\n  if (T->optPolyOrder > -1)\r\n    printTreeNode(T,outFile);\r\n  else {\r\n    printTree(T->leftChild,outFile);\r\n    printTree(T->rightChild,outFile);\r\n  }\r\n}\r\n\r\nvoid printTreeNodeDebug(struct tree *T, int level, double *x)\r\n{\r\n  int i,k;\r\n  printf(\"\\nLevel = %d, nObs = %d, left interval = %f, right interval = %f\\n\",\r\n\t level,T->nObs,\r\n\t T->intervalLeft,T->intervalRight);\r\n  printf(\"\\tmaxPolyOrder = %d, optPolyOrder = %d\\n\",\r\n\t T->maxPolyOrder,T->optPolyOrder);\r\n  for (i = 0; i < T->maxPolyOrder; i++) {\r\n    printf(\"%d order poly coeffs:\\t\",i+1);\r\n    for (k = 0; k <= i; k++) {\r\n      printf(\"\\t%lf\",T->polyCoeffs[i][k]);\r\n    }\r\n    printf(\"\\n\");\r\n  }\r\n  printf(\"Likelihoods\\n\");\r\n  for (i = 0; i < T->maxPolyOrder; i++) {\r\n    printf(\"\\t%lf\",T->likelihoods[i]);\r\n  }\r\n  printf(\"\\n\");\r\n  /*\r\n  for (i = 0; i < T->nObs; i++)\r\n  {\r\n    printf(\"\\t%lf\",x[i+T->firstObsInInterval]);\r\n  }\r\n  if (i > 0)\r\n    printf(\"\\n\");\r\n  */\r\n}\r\nvoid printTreeDebug(struct tree *T, int level, double *x)\r\n{\r\n  if (T == NULL) \r\n    return;\r\n  printTreeNodeDebug(T,level,x);\r\n  printTreeDebug(T->leftChild,level+1,x);\r\n  printTreeDebug(T->rightChild,level+1,x);\r\n}\r\n\r\nvoid freeTree(struct tree *T)\r\n{\r\n\tint i;\r\n\t/*printf(\"fT leftChild\\n\");*/\r\n  if (T->leftChild != NULL)   {\r\n    freeTree(T->leftChild);\r\n  }\r\n\t/*printf(\"fT rightChild\\n\");*/\r\n  if (T->rightChild != NULL)   {\r\n    freeTree(T->rightChild);\r\n  }\r\n\t/*printf(\"fT polyCoeffs\\n\");*/\r\n\tif (T->polyCoeffs != NULL) {\r\n\t\t/*printf(\"fT maxPolyOrder = %d\\n\",T->maxPolyOrder);*/\r\n\t\tfor (i = 0; i < T->maxPolyOrder; i++) {\r\n\t\t\tfree(T->polyCoeffs[i]);\r\n\t\t}\r\n\t\tfree(T->polyCoeffs);\r\n\t} \r\n\t/*printf(\"fT likelihoods\\n\");*/\r\n\tif (T->likelihoods != NULL) {\r\n\t\tfree(T->likelihoods);\r\n\t}\r\n\t/*printf(\"fT T\\n\");*/\r\n  free(T);\r\n}\r\n\r\n\r\nvoid coeffsToEval2(double *x, struct tree *T, int polyOrder, double *est) {\r\n  double *y, *da, *db, *dc;\r\n  int i,k;\r\n  int estLength = T->nObs;\r\n  double a,b;\r\n  \r\n  a = T->intervalLeft;\r\n  b = T->intervalRight;\r\n  y = (double *)malloc(sizeof(double)*estLength);\r\n  da = (double *)malloc(sizeof(double)*estLength);\r\n  db = (double *)malloc(sizeof(double)*estLength);\r\n  dc = (double *)malloc(sizeof(double)*estLength);\r\n  for (i = 0; i < T->nObs; i++) {\r\n    y[i] = (x[i+T->firstObsInInterval]-a)/(b-a)*2.0-1.0;\r\n    da[i] = 0.0;\r\n    db[i] = 0.0;\r\n    dc[i] = 0.0;\r\n  }\r\n  for (k = polyOrder-1; k>=1; k--) {\r\n    for (i = 0; i < T->nObs; i++) {\r\n      dc[i] = 2*y[i]*db[i]-da[i]+T->polyCoeffs[polyOrder-1][k];\r\n      da[i] = db[i];\r\n      db[i] = dc[i];\r\n    }\r\n  }\r\n  for (i = 0; i < T->nObs; i++) {\r\n    est[i] = y[i]*dc[i]-da[i]+T->polyCoeffs[polyOrder-1][0];\r\n  }\r\n  free(y);\r\n  free(da);\r\n  free(db);\r\n  free(dc);\r\n}\r\n\r\nvoid coeffsToEval(double *x, struct tree *T, int polyOrder, double *est) {\r\n  double *cheb, *chebPrev, *chebNext, *y;\r\n  int i,k;\r\n  int estLength = T->nObs;\r\n  double a,b;\r\n  \r\n  a = T->intervalLeft;\r\n  b = T->intervalRight;\r\n\r\n  y = (double *)malloc(sizeof(double)*estLength);\r\n  cheb = (double *)malloc(sizeof(double)*estLength);\r\n  chebNext = (double *)malloc(sizeof(double)*estLength);\r\n  chebPrev = (double *)malloc(sizeof(double)*estLength);\r\n  for (i = 0; i < T->nObs; i++) {\r\n    y[i] = (x[i+T->firstObsInInterval]-a)/(b-a)*2.0-1.0;\r\n    cheb[i] = 1.0;\r\n    est[i] = 0.0;\r\n  }\r\n  for (k = 0; k < polyOrder; k++) {\r\n    for (i = 0; i < estLength; i++) {\r\n      est[i] += cheb[i]*T->polyCoeffs[polyOrder-1][k];\r\n    }\r\n    if (k==0) {\r\n      for (i = 0; i < estLength; i++) {\r\n\tchebNext[i] = y[i];\r\n      }\r\n    }\r\n    else {\r\n      for (i = 0; i < estLength; i++) {\r\n\tchebNext[i] = 2.0*y[i]*cheb[i] - chebPrev[i];\r\n      }\r\n    }\r\n    \r\n    for (i = 0; i < estLength; i++) {\r\n      chebPrev[i] = cheb[i];\r\n      cheb[i] = chebNext[i];\r\n    }\r\n  }\r\n  free(y);\r\n  free(cheb);\r\n  free(chebPrev);\r\n  free(chebNext);\r\n}\r\n\r\nvoid coeffsToEst2(int estLength, int estStart, double *coeffs, \r\n\t\t int numCoeffs, double *est) {\r\n  double *y, *da, *db, *dc;\r\n  int i,k;\r\n  \r\n  y = (double *)malloc(sizeof(double)*estLength);\r\n  da = (double *)malloc(sizeof(double)*estLength);\r\n  db = (double *)malloc(sizeof(double)*estLength);\r\n  dc = (double *)malloc(sizeof(double)*estLength);\r\n  for (i = 0; i < estLength; i++) {\r\n    y[i] = (double)i/(double)estLength*2.0-1.0;\r\n    da[i] = 0.0;\r\n    db[i] = 0.0;\r\n    dc[i] = 0.0;\r\n  }\r\n  for (k = numCoeffs-1; k>=1; k--) {\r\n    for (i = 0; i < estLength; i++) {\r\n      dc[i] = 2*y[i]*db[i]-da[i]+coeffs[k];\r\n      da[i] = db[i];\r\n      db[i] = dc[i];\r\n    }\r\n  }\r\n  for (i = 0; i < estLength; i++) {\r\n    est[i+estStart] = y[i]*dc[i]-da[i]+coeffs[0];\r\n  }\r\n  free(y);\r\n  free(da);\r\n  free(db);\r\n  free(dc);\r\n}\r\n\r\nvoid coeffsToEst(int estLength, int estStart, double *coeffs, \r\n\t\t int numCoeffs, double *est) {\r\n  double *cheb, *chebPrev, *chebNext, *y;\r\n  int i,k;\r\n\r\n  cheb = (double *)malloc(sizeof(double)*estLength);\r\n  chebNext = (double *)malloc(sizeof(double)*estLength);\r\n  chebPrev = (double *)malloc(sizeof(double)*estLength);\r\n  y = (double *)malloc(sizeof(double)*estLength);\r\n\r\n  for (i = 0; i < estLength; i++) {\r\n    cheb[i] = 1.0;\r\n    est[i+estStart] = 0.0;\r\n    y[i] = (double)i/(double)estLength*2.0-1.0;\r\n  }\r\n  for (k = 0; k < numCoeffs; k++) {\r\n    for (i = 0; i < estLength; i++) {\r\n      est[i+estStart] += cheb[i]*coeffs[k];\r\n    }\r\n    if (k==0) {\r\n      for (i = 0; i < estLength; i++) {\r\n\tchebNext[i] = y[i];\r\n      }\r\n    }\r\n    else {\r\n      for (i = 0; i < estLength; i++) {\r\n\tchebNext[i] = 2*y[i]*cheb[i] - chebPrev[i];\r\n      }\r\n    }\r\n    \r\n    for (i = 0; i < estLength; i++) {\r\n      chebPrev[i] = cheb[i];\r\n      cheb[i] = chebNext[i];\r\n    }\r\n  }\r\n  free(y);\r\n  free(cheb);\r\n  free(chebPrev);\r\n  free(chebNext);\r\n}\r\n\r\nvoid treeToEst(struct tree *T, double *est, \r\n\t       int estLength, int estStart, int level)\r\n{\r\n  int breakpoint;\r\n  \r\n  if (T->optPolyOrder == -1){\r\n    /* split */\r\n    breakpoint = (int) floor(estLength/2);\r\n    treeToEst(T->leftChild, est, breakpoint, estStart,level+1);\r\n    treeToEst(T->rightChild, est, estLength-breakpoint, \r\n\t      estStart+breakpoint,level+1);\r\n  }\r\n  else {\r\n    /* prune */\r\n    coeffsToEst(estLength,estStart,T->polyCoeffs[T->optPolyOrder-1],\r\n\t\tT->optPolyOrder,est);\r\n  }\r\n}\r\n\r\nint countObsBelowThresh(double *x, int startingPoint,\r\n\t\t\tint n, double thresh)\r\n{\r\n  int i,count=0;\r\n  for (i=startingPoint; i < (n+startingPoint); i++)\r\n    {\r\n      if (x[i]<=thresh)\r\n\tcount++;\r\n      else\r\n\ti = n+startingPoint;\r\n    }\r\n  /*if ((x[startingPoint] < 83)&&(x[startingPoint] > 82))\r\n    {\r\n    printf(\"? x[sP] = %f <= %f, sP = %d, n = %d, count = %d\\n\",\r\n    x[startingPoint],thresh,startingPoint,n,count);\r\n    }*/\r\n  return count;\r\n}\r\n\r\nvoid fitPolysOnTree(struct tree *T, int r, double *x)\r\n{\r\n  double *cheb, *chebPrev, *chebNext, *estEval, *est, *y;\r\n  int i,k,estLength = 2000;\r\n  double a,b,sum,estMin,renorm, intLength, intLeft, intRight;\r\n\t\r\n  intLeft = T->intervalLeft;\r\n  intRight = T->intervalRight;\r\n  intLength = intRight-intLeft;\r\n  T->maxPolyOrder = max(1,min(r,T->nObs));\r\n\t\r\n  T->likelihoods = (double *)malloc(sizeof(double)*T->maxPolyOrder);\r\n  T->polyCoeffs = (double **)malloc(sizeof(double*)*T->maxPolyOrder);\r\n\t\r\n  if (T->maxPolyOrder == 1) {\r\n    T->polyCoeffs[0] = (double *)malloc(sizeof(double)*1);\r\n    T->polyCoeffs[0][0] = (double)T->nObs/intLength;\r\n    T->likelihoods[0] = T->nObs*(-log(T->polyCoeffs[0][0]));\r\n  }\r\n  else {\r\n    y = (double *)malloc(sizeof(double)*T->nObs);\r\n    cheb = (double *)malloc(sizeof(double)*T->nObs);\r\n    chebNext = (double *)malloc(sizeof(double)*T->nObs);\r\n    chebPrev = (double *)malloc(sizeof(double)*T->nObs);\r\n    estEval = (double *)malloc(sizeof(double)*T->nObs);\r\n    est = (double *)malloc(sizeof(double)*estLength);\r\n    for (i = 0; i < T->nObs; i++) {\r\n      y[i] = (x[i+T->firstObsInInterval]-intLeft)/intLength*2.0-1.0;\r\n      cheb[i] = 1.0;\r\n      estEval[i] = 0.0;\r\n    }\r\n    \r\n    /* calculate unconstrained coefficients */\r\n    for (k = 0; k < T->maxPolyOrder; k++) {\r\n\t\t\t\r\n      T->polyCoeffs[k] = (double *)malloc(sizeof(double)*(k+1));\r\n      if (k > 0) {\r\n\tfor (i = 0; i <= k; i++) {\r\n\t  T->polyCoeffs[k][i] = T->polyCoeffs[k-1][i];\r\n\t}\r\n      }\r\n      T->polyCoeffs[k][k] = 0.0;\r\n      for (i = 0; i < T->nObs; i++) {\r\n\tif (pow(y[i],2.0) != 1.0) {\r\n\t  T->polyCoeffs[k][k] += cheb[i]*pow(1-pow(y[i],2.0),-0.5);\r\n\t}\r\n      }\r\n      \r\n      if (T->nObs>0)\r\n\tT->polyCoeffs[k][k] *= 2.0/PI/T->nObs;\r\n      else\r\n\tT->polyCoeffs[k][k] = 0.0;\r\n      \r\n      if (k==0) {\r\n\tT->polyCoeffs[k][k] /= 2.0;\r\n\tfor (i = 0; i < T->nObs; i++) {\r\n\t  chebNext[i] = y[i];\r\n\t}\r\n      }\r\n      else {\r\n\tfor (i = 0; i < T->nObs; i++) {\r\n\t  chebNext[i] = 2*y[i]*cheb[i] - chebPrev[i];\r\n\t}\r\n      }\r\n      for (i = 0; i < T->nObs; i++) {\r\n\tchebPrev[i] = cheb[i];\r\n\tcheb[i] = chebNext[i];\r\n      }\r\n    }\r\n\t\t\r\n    /* renormalize coefficients */\r\n    if (T->nObs > 0) {\r\n      for (k=0; k < T->maxPolyOrder; k++) {\r\n\t/* compute min */\r\n\tcoeffsToEst2(estLength,0,T->polyCoeffs[k],k+1,est);\r\n\testMin = realmax;\r\n\tfor (i=0; i<estLength; i++) {\r\n\t  estMin = min(estMin,est[i]);\r\n\t}\r\n\t\t\t\t\r\n\t/* change min */\r\n\tif (estMin < 0) {\r\n\t  a = 1.0/(1.0-2.0*estMin);\r\n\t  b = (1.0-a)/2.0;\r\n\t  for (i=0; i<=k; i++) {\r\n\t    T->polyCoeffs[k][i] *= a;\r\n\t  }\r\n\t  T->polyCoeffs[k][0] += b;\r\n\t}\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t/* compute integral */\r\n\t/*\r\n\t  coeffsToEst(estLength,0,T->polyCoeffs[k],k+1,est);\r\n\t  sum = 0;\r\n\t  for (i=0; i<estLength; i++) {\r\n\t  sum += est[i]/((double)estLength);\r\n\t  }\r\n\t\t\t\t \r\n\t*/\r\n\tsum = T->polyCoeffs[k][0];\r\n\tfor (i=2; i < (k+1); i+=2) {\r\n\t  sum -= T->polyCoeffs[k][i]/((double)i+1)/((double)i-1);\r\n\t}\r\n\t\t\t\t\r\n\t/* change integral */\r\n\tif (sum > 0){\r\n\t  renorm = ((double)T->nObs/sum/intLength);\r\n\t  for (i=0; i<=k; i++) {\r\n\t    T->polyCoeffs[k][i] *= renorm;\r\n\t  }\r\n\t}\r\n\t\t\t\t\r\n\tif ((intLeft==0)&(intRight==1)) {\r\n\t  sum = T->polyCoeffs[k][0];\r\n\t  for (i=2; i < (k+1); i+=2) {\r\n\t    sum -= T->polyCoeffs[k][i]/((double)i+1)/((double)i-1);\r\n\t  }\r\n\t}\r\n\t/*coeffsToEval(x,T,k+1,estEval);*/\r\n\tcoeffsToEval2(x,T,k+1,estEval);\r\n\t\t\t\t\r\n\tT->likelihoods[k] = 0;\r\n\tfor (i = 0; i < T->nObs; i++) {\r\n\t  T->likelihoods[k] -= log(max(realmin,estEval[i]));\r\n\t}\r\n      }\r\n    }\r\n    else {\r\n      T->likelihoods[0] = 0.0;\r\n    }\r\n    free(cheb);\r\n    free(chebNext);\r\n    free(chebPrev);\r\n    free(estEval);\r\n    free(y);\r\n    free(est);\r\n  }\r\n\t\r\n  if (T->leftChild != NULL)\r\n    fitPolysOnTree(T->leftChild,r,x);\r\n  if (T->rightChild != NULL)\r\n    fitPolysOnTree(T->rightChild,r,x);\r\n\t\r\n}\r\n\r\n\r\n\r\nvoid addNode(double newIntervalLeft,\r\n\t     double newIntervalRight, int newNObs,\r\n\t     int newFirstObsInInterval, double minWidth,\r\n\t     double *x, struct tree *newNode)\r\n{\r\n  double breakpoint;\r\n  int nObsL, nObsR;\r\n\t\r\n  /*  newNode = (struct tree *) malloc(sizeof(struct tree));*/\r\n  newNode->intervalLeft = newIntervalLeft;\r\n  newNode->intervalRight = newIntervalRight;\r\n  newNode->nObs = newNObs;\r\n  newNode->firstObsInInterval = newFirstObsInInterval;\r\n  newNode->maxPolyOrder = 0;\r\n\t\r\n  if (((newIntervalRight-newIntervalLeft) >= minWidth)&&(newNObs>0))  {\r\n    breakpoint = (newIntervalRight-newIntervalLeft)/2.0+newIntervalLeft;\r\n    nObsL = countObsBelowThresh(x,newFirstObsInInterval,\r\n\t\t\t\tnewNObs,breakpoint);\r\n    nObsR = newNObs-nObsL;\r\n\t\t\r\n    newNode->leftChild = (struct tree *) malloc(sizeof(struct tree));\r\n    newNode->rightChild = (struct tree *) malloc(sizeof(struct tree));\r\n    //printf(\"add left\\n\");\r\n    addNode(newIntervalLeft,breakpoint,\r\n\t    nObsL,newFirstObsInInterval,\r\n\t    minWidth,x,newNode->leftChild);\r\n    //printf(\"add right\\n\");\r\n    addNode(breakpoint,newIntervalRight,\r\n\t    nObsR,newFirstObsInInterval+nObsL,\r\n\t    minWidth,x,newNode->rightChild);\r\n  }\r\n  else {\r\n    newNode->leftChild = NULL;\r\n    newNode->rightChild = NULL;\r\n  }\r\n  //printf(\"up \");\r\n  return;\r\n}\r\n\r\nvoid DensityEstGrowTree(struct tree *T, double *x, int n, \r\n\t\t\tint maxPolyOrder, int estLength)\r\n{\r\n  double minWidth = max(1.0/estLength,1.0/n);\r\n  /*double minWidth = 0.5;*/\r\n  \r\n  std::cout << \"Adding node..\" << std::endl;\r\n  \r\n  addNode(0.0,1.0,n,0,minWidth,x,T);\r\n  \r\n  std::cout << \"done\" << std::endl;\r\n  \r\n  std::cout << \"Fitting polynomial...\" << std::endl;\r\n  fitPolysOnTree(T, maxPolyOrder, x);\r\n  std::cout << \"done\" << std::endl;\r\n\t\r\n  /*printTree(T,0,x);*/\r\n}\t\r\n\r\nvoid DensityEstPruneTree(struct tree *T, double *x, \r\n\t\t\t int n, double pen, int level)\r\n{\r\n  double Lsplit = 0;\r\n  double L,Lmin = realmax;\r\n  int k,i,kmin = 0;\r\n\t\r\n  double *estEval;\r\n  \r\n  if (T == NULL) \r\n    return;\r\n  if (T->leftChild != NULL) {\r\n    DensityEstPruneTree(T->leftChild,x,n,pen,level+1);\r\n    Lsplit += T->leftChild->optLikelihood;\r\n  }\r\n  else {\r\n    Lsplit = realmax;\r\n  }\r\n  if (T->rightChild != NULL) {\r\n    DensityEstPruneTree(T->rightChild,x,n,pen,level+1);\r\n    Lsplit += T->rightChild->optLikelihood;\r\n  }\r\n  else {\r\n    Lsplit = realmax;\r\n  }\r\n\t\r\n  for (k = 0; k<T->maxPolyOrder; k++) {\r\n    L = T->likelihoods[k] + (pen*((double)(k+1)/2.0)+(2.0+(double)(k+1))*log(2.0));\r\n    if (L < Lmin) {\r\n      Lmin = L;\r\n      kmin = k;\r\n    }\r\n  }\r\n  \r\n  if (Lsplit < Lmin) {\r\n    T->optLikelihood = Lsplit;\r\n    T->optPolyOrder = -1;\r\n  }\r\n  else {\r\n    T->optLikelihood = Lmin;\r\n    T->optPolyOrder = kmin+1;\r\n  }\r\n}\t\r\n\r\n\r\nvoid computeDensity(double *x, int n, double *y, int estLength, double pen, int maxPolyOrder)\r\n{\r\n  double renorm;\r\n  int i;\r\n  struct tree *T;\r\n  \r\n  std::cout << \"Building tree...\" << std::endl;\r\n  \r\n  T = (struct tree *) malloc(sizeof(struct tree));\r\n  DensityEstGrowTree(T,x,n,maxPolyOrder,estLength);\r\n  \r\n  std::cout << \"Done building tree\" << std::endl;\r\n  \r\n  std::cout << \"Pruning tree...\" << std::endl;\r\n  DensityEstPruneTree(T,x,n,pen,0);\r\n  std::cout << \"done pruning tree\" << std::endl;\r\n  \r\n  treeToEst(T,y,estLength,0,0);\r\n  renorm = 1.0/T->nObs;\r\n  for (i = 0; i < estLength; i++) {\r\n    y[i] *= renorm;\r\n  }\r\n  freeTree(T);\r\n}\r\n\r\n//This ifdef/endif exclude the code meant for matlab\r\n\r\n#ifdef MATLAB_CODE\r\n\r\nvoid mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[])\r\n{\r\n  double *x, *y;\r\n  int m,n,i,nDim,estlength;\r\n  int estLength, maxPolyOrder;\r\n  double pen;\r\n  \r\n  /* check for correct # of input variables */\r\n  if (nrhs>4){\r\n    mexErrMsgTxt(\"There are at most 4 input parameters allowed!\");\r\n    return;\r\n  }\r\n  if (nrhs<1){\r\n    mexErrMsgTxt(\"There is at least 1 input parameter required!\");\r\n    return;\r\n  }\r\n  x = mxGetPr(prhs[0]);\r\n  nDim = mxGetNumberOfDimensions(prhs[0]);\r\n\t\r\n  if (nDim > 1) {\r\n    m = (int)(mxGetDimensions(prhs[0]))[0];\r\n    n = (int)(mxGetDimensions(prhs[0]))[1];\r\n    if ((m!=1)&&(n!=1)) {\r\n      mexErrMsgTxt(\"The input array cannot have more than one dimension.\");\r\n      return;\r\n    }\r\n  }\r\n\t\r\n  n = mxGetNumberOfElements(prhs[0]);\r\n\t\r\n  \r\n  if ((nrhs < 2)||(mxGetN(prhs[1])==0)) {\r\n    estLength = (double) pow(2.0,floor(log((double)n)/log(2.0)));\r\n  }\r\n  else {\r\n    estLength = (double) *mxGetPr(prhs[1]);\r\n  }\r\n\t\r\n\t\r\n\t\r\n  /* set penalty\r\n     default = log(n)/2 \r\n  */\r\n  if ((nrhs < 3)||(mxGetN(prhs[2])==0)) {\r\n    pen = (double) log(n)/2.0;\r\n  }\r\n  else {\r\n    pen = (double) *mxGetPr(prhs[2]);\r\n  }\r\n  if (pen < 0) {\r\n    mexErrMsgTxt(\"The penalty must be positive.\");\r\n  }\r\n\t\r\n  if ((nrhs < 4)||(mxGetN(prhs[3])==0)) {\r\n    maxPolyOrder = n;\r\n  }\r\n  else {\r\n    maxPolyOrder = (double) *mxGetPr(prhs[3]);\r\n  }\r\n\t\r\n  plhs[0] = mxCreateDoubleMatrix(estLength,1,mxREAL);\r\n  y = mxGetPr(plhs[0]);\r\n  computeDensity(x,n,y,estLength,pen,maxPolyOrder);\r\n}\r\n\r\n#endif\r\n\r\n/* Python wrapper by GV */\r\n\r\ntypedef std::vector<double> doubleArray;\r\n\r\ninline std::vector< double > to_std_vector( const boost::python::api::object& iterable )\r\n{\r\n    return std::vector< double >( boost::python::stl_input_iterator< double >( iterable ),\r\n                             boost::python::stl_input_iterator< double >( ) );\r\n}\r\n\r\ndoubleArray getDensity( boost::python::object& iterable, int n, int estLength, double pen, int maxPolyOrder)\r\n{\r\n  \r\n  doubleArray x = to_std_vector( iterable );\r\n  \r\n  double *xx = &x[0];\r\n    \r\n  doubleArray y( estLength, 0.0 );\r\n  \r\n  double *yy = &y[0];\r\n    \r\n  computeDensity(xx, n, yy, estLength, pen, maxPolyOrder);\r\n  \r\n  return y;\r\n\r\n}\r\n\r\n\r\nBOOST_PYTHON_MODULE(freeDegreeEst)\r\n{\r\n    using namespace boost::python;\r\n    \r\n    class_<doubleArray>(\"doubleArray\")\r\n        .def(vector_indexing_suite<doubleArray>() );\r\n    \r\n    def(\"getDensity\", getDensity);\r\n\r\n}\r\n\r\n", "meta": {"hexsha": "b14b9fc8fca7f457382eb371e0b825c7654c66ce", "size": 17621, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "freeDegreeEst/freeDegreeEst.cpp", "max_stars_repo_name": "giacomov/freeDegreeEst", "max_stars_repo_head_hexsha": "d6dd92537a6b42e6652a7cf9b971c334da28a72b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "freeDegreeEst/freeDegreeEst.cpp", "max_issues_repo_name": "giacomov/freeDegreeEst", "max_issues_repo_head_hexsha": "d6dd92537a6b42e6652a7cf9b971c334da28a72b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "freeDegreeEst/freeDegreeEst.cpp", "max_forks_repo_name": "giacomov/freeDegreeEst", "max_forks_repo_head_hexsha": "d6dd92537a6b42e6652a7cf9b971c334da28a72b", "max_forks_repo_licenses": ["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.0298295455, "max_line_length": 109, "alphanum_fraction": 0.5559275864, "num_tokens": 5905, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.4956147952042077}}
{"text": "// Copyright (C) 2013 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 <Eigen/Core>\n#include <Eigen/Geometry>\n#include <glog/logging.h>\n#include <cmath>\n\n#include \"gtest/gtest.h\"\n\n#include \"theia/math/util.h\"\n#include \"theia/sfm/pose/position_from_two_rays.h\"\n#include \"theia/sfm/pose/test_util.h\"\n#include \"theia/test/test_utils.h\"\n#include \"theia/util/random.h\"\n#include \"theia/util/util.h\"\n\nnamespace theia {\n\nusing Eigen::Map;\nusing Eigen::Quaterniond;\nusing Eigen::Vector2d;\nusing Eigen::Vector3d;\n\nnamespace {\n\nRandomNumberGenerator rng(58);\n\nvoid TestPositionFromTwoRaysWithNoise(\n    const Vector3d points_3d[2],\n    const double model_noise,\n    const double projection_noise,\n    const Vector3d& test_position,\n    const double max_difference_between_position) {\n  static const double kTolerance = 1e-4;\n\n  // Sets up the model points by transforming the points_3d by the inverse\n  // of the the test position.\n  Vector3d model_points[2];\n  Vector2d rotated_rays[2];\n  for (int i = 0; i < 2; ++i) {\n    model_points[i] = points_3d[i];\n    rotated_rays[i] = (points_3d[i] - test_position).hnormalized();\n  }\n\n  // Adds projection noise if required.\n  if (projection_noise) {\n    for (int i = 0; i < 2; ++i) {\n      AddNoiseToProjection(projection_noise, &rng, &rotated_rays[i]);\n    }\n  }\n\n  // Adds model noise if required.\n  if (model_noise) {\n    for (int i = 0; i < 2; ++i) {\n      AddNoiseToPoint(model_noise, &rng, &model_points[i]);\n    }\n  }\n\n  // Computes the pose.\n  Vector3d soln_position;\n  int num_solutions = PositionFromTwoRays(rotated_rays[0],\n                                          model_points[0],\n                                          rotated_rays[1],\n                                          model_points[1],\n                                          &soln_position);\n  EXPECT_LT((soln_position - test_position).norm(), kTolerance)\n      << \"Expected position: \" << test_position.transpose()\n      << \" vs estimated: \" << soln_position.transpose();\n}\n\n// Checks with several points, optionally adds model and projection noise.\nvoid ManyPointsTest(const double model_noise,\n                    const double projection_noise,\n                    const double max_difference_between_position) {\n  static const Vector3d kPositions[8] = {\n      Vector3d(1.0, 1.0, 1.0),\n      Vector3d(3.0, 2.0, 13.0),\n      Vector3d(4.0, 5.0, 11.0),\n      Vector3d(1.0, 2.0, 15.0),\n      Vector3d(3.0, 1.5, 91.0),\n      Vector3d(1.0, 7.0, 11.0),\n      Vector3d(0.0, 0.0, 0.0),  // Tests no position.\n      Vector3d(0.0, 0.0, 0.0)  // Tests no position and no rotation.\n  };\n\n  // Sets up some test points.\n  static const double kTestPoints[][6] = {\n      {-1.62, -2.99, 6.12, 4.42, -1.53, 9.83},\n      {1.45, -0.59, 5.29, 1.89, -1.10, 8.22},\n      {-0.21, 2.38, 5.63, 0.61, -0.97, 7.49},\n      {0.48, 0.70, 8.94, 1.65, -2.56, 8.63},\n      {2.44, -0.20, 7.78, 2.84, -2.58, 7.35},\n      {-1.35, -2.84, 7.33, -0.42, 1.54, 8.86},\n      {2.56, 1.72, 7.86, 1.75, -1.39, 5.73},\n      {2.08, -3.91, 8.37, -0.91, 1.36, 9.16},\n      {2.84, 1.54, 8.74, -1.01, 3.02, 8.18},\n      {-3.73, -0.62, 7.81, -2.98, -1.88, 6.23},\n      {2.39, -0.19, 6.47, -0.63, -1.05, 7.11},\n      {-1.76, -0.55, 5.18, -3.19, 3.27, 8.18},\n      {0.31, -2.77, 7.54, 0.54, -3.77, 9.77},\n  };\n\n  for (int i = 0; i < THEIA_ARRAYSIZE(kTestPoints); ++i) {\n    const Vector3d points_3d[2] = {\n      Vector3d(kTestPoints[i][0], kTestPoints[i][1], kTestPoints[i][2]),\n      Vector3d(kTestPoints[i][3], kTestPoints[i][4], kTestPoints[i][5]),\n    };\n\n    for (int transform_index = 0;\n         transform_index < THEIA_ARRAYSIZE(kPositions);\n         ++transform_index) {\n      TestPositionFromTwoRaysWithNoise(points_3d,\n                                       model_noise,\n                                       projection_noise,\n                                       kPositions[transform_index],\n                                       max_difference_between_position);\n    }\n  }\n}\n\n// Tests a single set of model to image correspondences and a single\n// transformation consisting of a position and a rotation around kAxis.\nvoid BasicTest() {\n  // Sets up some points in the 3D scene\n  const Vector3d points_3d[2] = { Vector3d(5.0, 20.0, 23.0),\n                                  Vector3d(-6.0, 16.0, 33.0) };\n\n  const Vector3d kAxis(0.0, 1.0, 0.0);\n  const Vector3d kExpectedPosition(-3.0, 1.5, 11.0);\n\n  static const double kModelNoise = 0.0;\n  static const double kProjectionNoise = 0.0 / 512;\n  static const double kMaxAllowedPositionDifference = 1.0e-5;\n  TestPositionFromTwoRaysWithNoise(points_3d,\n                                   kModelNoise,\n                                   kProjectionNoise,\n                                   kExpectedPosition,\n                                   kMaxAllowedPositionDifference);\n}\n\nTEST(PositionFromTwoRaysTest, BasicTest) {\n  BasicTest();\n}\n\n// Tests a single set of model to image correspondences and multiple\n// transformations consisting of position and rotations around different\n// axes.\nTEST(PositionFromTwoRaysTest, DifferentAxesTest) {\n  const Vector3d points_3d[2] = {\n      Vector3d(5.0, 20.0, 23.0),\n      Vector3d(-6.0, 16.0, 33.0)\n  };\n\n  static const Vector3d kPositions[8] = {\n      Vector3d(1.0, 1.0, 1.0),\n      Vector3d(3.0, 2.0, 13.0),\n      Vector3d(4.0, 5.0, 11.0),\n      Vector3d(1.0, 2.0, 15.0),\n      Vector3d(3.0, 1.5, 21.0),\n      Vector3d(1.0, 7.0, 11.0),\n      Vector3d(0.0, 0.0, 0.0),  // Tests no position.\n      Vector3d(0.0, 0.0, 0.0)  // Tests no position and no rotation.\n  };\n\n  for (int i = 0; i < THEIA_ARRAYSIZE(kPositions); ++i) {\n    static const double kModelNoise = 0.0;\n    static const double kProjectionNoise = 0.0 / 512;\n\n    static const double kMaxAllowedPositionDifference = 1.0e-5;\n    TestPositionFromTwoRaysWithNoise(points_3d,\n                                     kModelNoise,\n                                     kProjectionNoise,\n                                     kPositions[i],\n                                     kMaxAllowedPositionDifference);\n  }\n}\n\n// Tests many sets of model to image correspondences and multiple\n// transformations consisting of position and rotations around different\n// axes, does not add any noise.\nTEST(PositionFromTwoRaysTest, ManyPointsTest) {\n  static const double kModelNoise = 0.0;\n  static const double kProjectionNoise = 0.0;\n  static const double kMaxAllowedPositionDifference = 1.0e-5;\n\n  ManyPointsTest(kModelNoise, kProjectionNoise, kMaxAllowedPositionDifference);\n}\n\n}  // namespace\n}  // namespace theia\n", "meta": {"hexsha": "1b5eebf03a2e9fc4ad435c59852f19cb42a35ab3", "size": 8294, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/sfm/pose/position_from_two_rays_test.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": "src/theia/sfm/pose/position_from_two_rays_test.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": "src/theia/sfm/pose/position_from_two_rays_test.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": 37.0267857143, "max_line_length": 79, "alphanum_fraction": 0.6267181095, "num_tokens": 2418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.4956147952042077}}
{"text": "// Copyright (C) 2011  Davis E. King (davis@dlib.net)\r\n// License: Boost Software License   See LICENSE.txt for the full license.\r\n\r\n#include <sstream>\r\n#include <string>\r\n#include <cstdlib>\r\n#include <ctime>\r\n#include <dlib/svm.h>\r\n#include <dlib/matrix.h>\r\n\r\n#include \"tester.h\"\r\n\r\nnamespace  \r\n{\r\n    using namespace test;\r\n    using namespace dlib;\r\n    using namespace std;\r\n\r\n    logger dlog(\"test.kmeans\");\r\n\r\n    dlib::rand rnd;\r\n\r\n    template <typename sample_type>\r\n    void run_test(\r\n        const std::vector<sample_type>& seed_centers\r\n    )\r\n    {\r\n        print_spinner();\r\n\r\n\r\n        sample_type samp;\r\n\r\n        std::vector<sample_type> samples;\r\n\r\n\r\n        for (unsigned long j = 0; j < seed_centers.size(); ++j)\r\n        {\r\n            for (int i = 0; i < 250; ++i)\r\n            {\r\n                samp = randm(seed_centers[0].size(),1,rnd) - 0.5;\r\n                samples.push_back(samp + seed_centers[j]);\r\n            }\r\n        }\r\n\r\n        randomize_samples(samples);\r\n\r\n        std::vector<sample_type> centers;\r\n        pick_initial_centers(seed_centers.size(), centers, samples, linear_kernel<sample_type>());\r\n\r\n        find_clusters_using_kmeans(samples, centers);\r\n\r\n        DLIB_TEST(centers.size() == seed_centers.size());\r\n\r\n        std::vector<int> hits(centers.size(),0);\r\n        for (unsigned long i = 0; i < samples.size(); ++i)\r\n        {\r\n            unsigned long best_idx = 0;\r\n            double best_dist = 1e100;\r\n            for (unsigned long j = 0; j < centers.size(); ++j)\r\n            {\r\n                if (length(samples[i] - centers[j]) < best_dist)\r\n                {\r\n                    best_dist = length(samples[i] - centers[j]);\r\n                    best_idx = j;\r\n                }\r\n            }\r\n            hits[best_idx]++;\r\n        }\r\n\r\n        for (unsigned long i = 0; i < hits.size(); ++i)\r\n        {\r\n            DLIB_TEST(hits[i] == 250);\r\n        }\r\n    }\r\n\r\n\r\n    class test_kmeans : public tester\r\n    {\r\n    public:\r\n        test_kmeans (\r\n        ) :\r\n            tester (\"test_kmeans\",\r\n                    \"Runs tests on the find_clusters_using_kmeans() function.\")\r\n        {}\r\n\r\n        void perform_test (\r\n        )\r\n        {\r\n            {\r\n                dlog << LINFO << \"test dlib::vector<double,2>\";\r\n                typedef dlib::vector<double,2> sample_type;\r\n                std::vector<sample_type> seed_centers;\r\n                seed_centers.push_back(sample_type(10,10));\r\n                seed_centers.push_back(sample_type(10,-10));\r\n                seed_centers.push_back(sample_type(-10,10));\r\n                seed_centers.push_back(sample_type(-10,-10));\r\n\r\n                run_test(seed_centers);\r\n            }\r\n            {\r\n                dlog << LINFO << \"test dlib::vector<double,2>\";\r\n                typedef dlib::vector<float,2> sample_type;\r\n                std::vector<sample_type> seed_centers;\r\n                seed_centers.push_back(sample_type(10,10));\r\n                seed_centers.push_back(sample_type(10,-10));\r\n                seed_centers.push_back(sample_type(-10,10));\r\n                seed_centers.push_back(sample_type(-10,-10));\r\n\r\n                run_test(seed_centers);\r\n            }\r\n            {\r\n                dlog << LINFO << \"test dlib::matrix<double,3,1>\";\r\n                typedef dlib::matrix<double,3,1> sample_type;\r\n                std::vector<sample_type> seed_centers;\r\n                sample_type samp;\r\n                samp = 10,10,0; seed_centers.push_back(samp);\r\n                samp = -10,10,1; seed_centers.push_back(samp);\r\n                samp = -10,-10,2; seed_centers.push_back(samp);\r\n\r\n                run_test(seed_centers);\r\n            }\r\n\r\n\r\n        }\r\n    } a;\r\n\r\n\r\n\r\n}\r\n\r\n\r\n\r\n", "meta": {"hexsha": "612523b335c5d888c7a74008c20b21b365b597af", "size": 3744, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/dlib/test/kmeans.cpp", "max_stars_repo_name": "cpearce/HARM", "max_stars_repo_head_hexsha": "1e629099bbaa0203b19fe9007a71d9ab9c938be0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-10-11T18:37:52.000Z", "max_stars_repo_stars_event_max_datetime": "2016-10-11T18:37:52.000Z", "max_issues_repo_path": "src/dlib/test/kmeans.cpp", "max_issues_repo_name": "wsgan001/HARM", "max_issues_repo_head_hexsha": "1e629099bbaa0203b19fe9007a71d9ab9c938be0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-03-27T22:58:45.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-28T04:46:52.000Z", "max_forks_repo_path": "src/dlib/test/kmeans.cpp", "max_forks_repo_name": "wsgan001/HARM", "max_forks_repo_head_hexsha": "1e629099bbaa0203b19fe9007a71d9ab9c938be0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2016-04-19T06:15:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-02T11:11:57.000Z", "avg_line_length": 28.1503759398, "max_line_length": 99, "alphanum_fraction": 0.500267094, "num_tokens": 815, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799253, "lm_q2_score": 0.6723316991792861, "lm_q1q2_score": 0.4956147922794271}}
{"text": "/***************************** Made by Duarte Gon\u00e7alves *********************************/\n#ifndef STATION_LAYER_H_\n#define STATION_LAYER_H_\n\n#include <ros/ros.h>\n\n#include <costmap_2d/layer.h>\n#include <costmap_2d/layered_costmap.h>\n\n#include <dynamic_reconfigure/server.h>\n#include <stations_layer/StationLayerConfig.h>\n\n#include <human_aware_navigation/DetectedStations.h>\n\n#include <math.h>\n\n#include <angles/angles.h>\n#include <pluginlib/class_list_macros.h>\n\n#include <boost/thread.hpp>\n\ndouble gaussian(double x, double y, double x0, double y0, double A, double varx, double vary, double skew);\ndouble get_radius(double cutoff, double A, double var);\n\nnamespace stations_layer_namespace{\n\n  class StationLayer : public costmap_2d::Layer{\n\n  public:\n    StationLayer();\n\n    virtual void onInitialize();\n    virtual void updateBounds(double origin_x, double origin_y, double origin_z, double* min_x, double* min_y, double* max_x, double* max_y);\n    virtual void updateCosts(costmap_2d::Costmap2D& master_grid, int min_i, int min_j, int max_i, int max_j);\n\n  private:\n    void stationCallback(const human_aware_navigation::DetectedStations& stations_);\n\n    ros::Subscriber stations_sub_;\n    human_aware_navigation::DetectedStations stations_list_;\n\n    void configure(stations_layer::StationLayerConfig &config, uint32_t level);\n\n    double cutoff_, amplitude_, covar_, factor_;\n    dynamic_reconfigure::Server<stations_layer::StationLayerConfig>* server_;\n    dynamic_reconfigure::Server<stations_layer::StationLayerConfig>::CallbackType f_;\n\n    bool first_time_;    \n  };\n}\n\n#endif\n", "meta": {"hexsha": "106c9a4fc821480d0302f4e20e047320916450ee", "size": 1593, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/stations_layer/include/stations_layer/StationLayer.hpp", "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/stations_layer/include/stations_layer/StationLayer.hpp", "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/stations_layer/include/stations_layer/StationLayer.hpp", "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": 30.0566037736, "max_line_length": 141, "alphanum_fraction": 0.7419962335, "num_tokens": 373, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799252, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.49561478743961157}}
{"text": "//---------------------------------------------------------------------------//\r\n// Copyright (c) 2013 Kyle Lutz <kyle.r.lutz@gmail.com>\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://boostorg.github.com/compute for more information.\r\n//---------------------------------------------------------------------------//\r\n\r\n#define BOOST_TEST_MODULE TestPartialSum\r\n#include <boost/test/unit_test.hpp>\r\n\r\n#include <vector>\r\n#include <numeric>\r\n\r\n#include <boost/compute/system.hpp>\r\n#include <boost/compute/command_queue.hpp>\r\n#include <boost/compute/algorithm/copy.hpp>\r\n#include <boost/compute/algorithm/partial_sum.hpp>\r\n#include <boost/compute/container/vector.hpp>\r\n\r\n#include \"check_macros.hpp\"\r\n#include \"context_setup.hpp\"\r\n\r\nnamespace bc = boost::compute;\r\n\r\nBOOST_AUTO_TEST_CASE(partial_sum_int)\r\n{\r\n    int data[] = { 1, 2, 5, 3, 9, 1, 4, 2 };\r\n    bc::vector<int> a(8, context);\r\n    bc::copy(data, data + 8, a.begin(), queue);\r\n\r\n    bc::vector<int> b(a.size(), context);\r\n    bc::vector<int>::iterator iter =\r\n        bc::partial_sum(a.begin(), a.end(), b.begin(), queue);\r\n    BOOST_CHECK(iter == b.end());\r\n    CHECK_RANGE_EQUAL(int, 8, b, (1, 3, 8, 11, 20, 21, 25, 27));\r\n}\r\n\r\nBOOST_AUTO_TEST_SUITE_END()\r\n", "meta": {"hexsha": "2c5aad987bb74ce550c3d5bd809e20df2a5ba2ad", "size": 1349, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/compute/test/test_partial_sum.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": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/compute/test/test_partial_sum.cpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-03-04T11:21:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-24T01:36:31.000Z", "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/compute/test/test_partial_sum.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 32.119047619, "max_line_length": 80, "alphanum_fraction": 0.5922905856, "num_tokens": 330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799252, "lm_q2_score": 0.6723316860482763, "lm_q1q2_score": 0.49561478259979613}}
{"text": "#ifndef MAIA_RENDERER_MATRICES_H_INCLUDED\n#define MAIA_RENDERER_MATRICES_H_INCLUDED\n\n#include <Eigen/Geometry>\n\nnamespace Maia::Renderer\n{\n\tEigen::Matrix4f create_view_matrix(Eigen::Vector3f const& position, Eigen::Quaternionf const& rotation);\n\n\tEigen::Matrix4f create_orthographic_projection_matrix(float horizontal_magnification, float vertical_magnification, float near_z, float far_z);\n\n\tEigen::Matrix4f create_infinite_perspective_projection_matrix(float aspect_ratio, float vertical_field_of_view, float near_z);\n\tEigen::Matrix4f create_finite_perspective_projection_matrix(float aspect_ratio, float vertical_field_of_view, float near_z, float far_z);\n}\n\n#endif\n", "meta": {"hexsha": "8566555f5ed23f6b15bcb4b940a8fc368e6f1cf2", "size": 669, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Source/Maia/Renderer/Matrices.hpp", "max_stars_repo_name": "JPMMaia/Renderer", "max_stars_repo_head_hexsha": "3fd791b7093a575af6816129cab1f6d24b6f8790", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-02-01T16:25:40.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-01T16:25:40.000Z", "max_issues_repo_path": "Source/Maia/Renderer/Matrices.hpp", "max_issues_repo_name": "JPMMaia/Renderer", "max_issues_repo_head_hexsha": "3fd791b7093a575af6816129cab1f6d24b6f8790", "max_issues_repo_licenses": ["MIT"], "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/Maia/Renderer/Matrices.hpp", "max_forks_repo_name": "JPMMaia/Renderer", "max_forks_repo_head_hexsha": "3fd791b7093a575af6816129cab1f6d24b6f8790", "max_forks_repo_licenses": ["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.3529411765, "max_line_length": 144, "alphanum_fraction": 0.8535127055, "num_tokens": 153, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.49553458119607385}}
{"text": "//\n//  Scheduler_Tests.cpp\n//  \n//\n//  Created by Ben Lengerich on 1/27/16.\n//\n//\n\n#include \"gtest/gtest.h\"\n#include <Eigen/Dense>\n#include <memory>\n#include <stdio.h>\n#include <unordered_map>\n\n#include \"Scheduler/Scheduler.hpp\"\n#include \"Scheduler/Job.hpp\"\n#include \"Algorithms/AlgorithmOptions.hpp\"\n#include \"Models/ModelOptions.hpp\"\n\nusing namespace std;\nusing namespace Eigen;\n\nclass SchedulerTest : public testing::Test {\nprotected:\n    virtual void SetUp() {\n        alg_opts = AlgorithmOptions_t(\n            proximal_gradient_descent,\n            {{\"tolerance\", \"0.01\"}, {\"learning_rate\", \"0.01\"}});\n\n        model_opts = ModelOptions_t(\n            linear_regression,\n            {{\"lambda\", \"0.01\"}, {\"L2_lambda\", \"0.01\"}});\n\n        X = MatrixXf(10, 5);\n        X << 0.8147,    0.1576,    0.6557,    0.7060,    0.4387,\n        0.9058,    0.9706,    0.0357,    0.0318,    0.3816,\n        0.1270,    0.9572,    0.8491,    0.2769,    0.7655,\n        0.9134,    0.4854,    0.9340,    0.0462,    0.7952,\n        0.6324,    0.8003,    0.6787,    0.0971,    0.1869,\n        0.0975,    0.1419,    0.7577,    0.8235,    0.4898,\n        0.2785,    0.4218,    0.7431,    0.6948,    0.4456,\n        0.5469,    0.9157,    0.3922,    0.3171,    0.6463,\n        0.9575,    0.7922,    0.6555,    0.9502,    0.7094,\n        0.9649,    0.9595,    0.1712,    0.0344,    0.7547;\n    \ty = MatrixXf(10, 1);\n        y << 0.4173,\n        0.0497,\n        0.9027,\n        0.9448,\n        0.4909,\n        0.4893,\n        0.3377,\n        0.9001,\n        0.3692,\n        0.1112;\n\n        LargeX = MatrixXf(n_patients, n_markers);\n        for (int i = 0; i < n_patients; i++) {\n            for (int j = 0; j < n_markers; j++) {\n                LargeX(i,j) = rand();\n            }\n        }\n    \tLargeY = MatrixXf(n_patients, n_traits);\n        for (int i = 0; i < n_patients; i++) {\n            for (int j = 0; j < n_traits; j++) {\n                LargeY(i,j) = rand();\n            }\n        }\n    }\n\n    virtual void TearDown() {}\n\n    const int n_patients = 1000;\n    const int n_markers = 1000;\n    const int n_traits = 1;\n    AlgorithmOptions_t alg_opts;\n    MatrixXf X;\n    MatrixXf y;\n    MatrixXf LargeX;\n    MatrixXf LargeY;\n    ModelOptions_t model_opts;\n};\n\n\nTEST_F(SchedulerTest, Singleton) {\n\tASSERT_EQ(&(Scheduler::Instance()), &(Scheduler::Instance()));\n}\n\n\nTEST_F(SchedulerTest, getNewAlgorithmId) {\n    int alg_num1 = Scheduler::Instance().getNewAlgorithmId();\n    EXPECT_GE(alg_num1, 0);\n    int alg_num2 = Scheduler::Instance().getNewAlgorithmId();\n    EXPECT_GT(alg_num2, alg_num1);\n\n    // Since we aren't actually making any algorithms, we shouldn't run out of IDs.\n    for (int i = 0; i < 1000; i++) {\n        EXPECT_GE(Scheduler::Instance().getNewAlgorithmId(), 0);\n    }\n}\n\n\nTEST_F(SchedulerTest, newAlgorithm) {\n    int alg_num1 = Scheduler::Instance().newAlgorithm(alg_opts);\n    EXPECT_GE(alg_num1, 0);\n    EXPECT_TRUE(Scheduler::Instance().deleteAlgorithm(alg_num1));\n\n    AlgorithmOptions_t alg_opts2 = AlgorithmOptions_t(brent_search, \n        {{\"tolerance\", \"0.01\"}, {\"learning_rate\", \"0.01\"}});\n    int alg_num2 = Scheduler::Instance().newAlgorithm(alg_opts2);\n    EXPECT_GE(alg_num2, 0);\n    EXPECT_TRUE(Scheduler::Instance().deleteAlgorithm(alg_num2));\n\n    AlgorithmOptions_t alg_opts3 = AlgorithmOptions_t( grid_search, \n        {{\"tolerance\", \"0.01\"}, {\"learning_rate\", \"0.01\"}});\n    int alg_num3 = Scheduler::Instance().newAlgorithm(alg_opts3);\n    EXPECT_GE(alg_num3, 0);\n    EXPECT_TRUE(Scheduler::Instance().deleteAlgorithm(alg_num3));\n\n    AlgorithmOptions_t alg_opts4 = AlgorithmOptions_t(iterative_update,\n        {{\"tolerance\", \"0.01\"}, {\"learning_rate\", \"0.01\"}});\n    int alg_num4 = Scheduler::Instance().newAlgorithm(alg_opts4);\n    EXPECT_GE(alg_num4, 0);\n    EXPECT_TRUE(Scheduler::Instance().deleteAlgorithm(alg_num4));\n    \n    AlgorithmOptions_t alg_opts5 = AlgorithmOptions_t(hypo_test,\n        {{\"tolerance\", \"0.01\"}, {\"learning_rate\", \"0.01\"}});\n    int alg_num5 = Scheduler::Instance().newAlgorithm(alg_opts5);\n    EXPECT_GE(alg_num5, 0);\n    EXPECT_TRUE(Scheduler::Instance().deleteAlgorithm(alg_num5));\n}\n\n\nTEST_F(SchedulerTest, getNewModelId) {\n    int model_num1 = Scheduler::Instance().getNewModelId();\n    EXPECT_GE(model_num1, 0);\n    int model_num2 = Scheduler::Instance().getNewModelId();\n    EXPECT_GT(model_num2, model_num1);\n\n    // Since we aren't actually making any models, we shouldn't run out of IDs.\n    for (int i = 0; i < 1000; i++) {\n        EXPECT_GE(Scheduler::Instance().getNewModelId(), 0);\n    }\n}\n\n\nTEST_F(SchedulerTest, newModel) {\n    int model_num1 = Scheduler::Instance().newModel(model_opts);\n    EXPECT_GE(model_num1, 0);\n}\n\n\nTEST_F(SchedulerTest, SetX) {\n    job_id_t job_id = Scheduler::Instance().newJob(JobOptions_t(alg_opts, model_opts));\n    Eigen::MatrixXf m(2,3);\n    m << 1, 2,\n         3, 4,\n         5, 6;\n    EXPECT_EQ(true, Scheduler::Instance().setX(job_id, m));\n}\n\n\nTEST_F(SchedulerTest, SetY) {\n    job_id_t job_id = Scheduler::Instance().newJob(JobOptions_t(alg_opts, model_opts));\n    Eigen::MatrixXf m(2,3);\n    m << 1, 2,\n         3, 4,\n         5, 6;\n    EXPECT_EQ(true, Scheduler::Instance().setY(job_id, m));\n}\n\n\nTEST_F(SchedulerTest, getNewJobId) {\n    job_id_t job_id1 = Scheduler::Instance().getNewJobId();\n    EXPECT_GT(job_id1, 0);\n    job_id_t job_id2 = Scheduler::Instance().getNewJobId();\n    EXPECT_GT(job_id2, job_id1);\n\n    for (int i = 0; i < 1000; i++) {\n        EXPECT_GT(Scheduler::Instance().getNewJobId(), 0);\n    }\n}\n\n\nTEST_F(SchedulerTest, newJob) {\n    job_id_t job_id1 = Scheduler::Instance().newJob(JobOptions_t(alg_opts, model_opts));\n    ASSERT_GT(job_id1, 0);\n}\n\nTEST_F(SchedulerTest, ValidAlgorithmId) {\n    ASSERT_FALSE(Scheduler::Instance().ValidAlgorithmId(-1));\n    EXPECT_TRUE(Scheduler::Instance().ValidAlgorithmId(Scheduler::Instance().getNewAlgorithmId()));\n    const algorithm_id_t alg_num = Scheduler::Instance().newAlgorithm(alg_opts);\n    ASSERT_TRUE(Scheduler::Instance().ValidAlgorithmId(alg_num));\n}\n\n\nTEST_F(SchedulerTest, ValidModelId) {\n    ASSERT_FALSE(Scheduler::Instance().ValidModelId(-1));\n    EXPECT_TRUE(Scheduler::Instance().ValidModelId(Scheduler::Instance().getNewModelId()));\n    const model_id_t model_num1 = Scheduler::Instance().newModel(model_opts);\n    ASSERT_TRUE(Scheduler::Instance().ValidModelId(model_num1));\n}\n\n\nTEST_F(SchedulerTest, ValidJobId) {\n    ASSERT_FALSE(Scheduler::Instance().ValidJobId(-1));\n    EXPECT_TRUE(Scheduler::Instance().ValidJobId(Scheduler::Instance().getNewJobId()));\n    const job_id_t job_id1 = Scheduler::Instance().newJob(JobOptions_t(alg_opts, model_opts));\n    ASSERT_TRUE(Scheduler::Instance().ValidJobId(job_id1));\n    Scheduler::Instance().deleteJob(job_id1);\n    ASSERT_TRUE(Scheduler::Instance().ValidJobId(job_id1));\n}\n\n\nTEST_F(SchedulerTest, AlgorithmIdUsed) {\n    ASSERT_FALSE(Scheduler::Instance().AlgorithmIdUsed(-1));\n    EXPECT_FALSE(Scheduler::Instance().AlgorithmIdUsed(Scheduler::Instance().getNewAlgorithmId()));\n    const algorithm_id_t alg_num = Scheduler::Instance().newAlgorithm(alg_opts);\n    ASSERT_TRUE(Scheduler::Instance().AlgorithmIdUsed(alg_num));\n}\n\n\nTEST_F(SchedulerTest, ModelIdUsed) {\n    ASSERT_FALSE(Scheduler::Instance().ModelIdUsed(-1));\n    EXPECT_FALSE(Scheduler::Instance().ModelIdUsed(Scheduler::Instance().getNewModelId()));\n    const model_id_t model_num1 = Scheduler::Instance().newModel(model_opts);\n    ASSERT_TRUE(Scheduler::Instance().ModelIdUsed(model_num1));\n}\n\n\nTEST_F(SchedulerTest, JobIdUsed) {\n    ASSERT_FALSE(Scheduler::Instance().JobIdUsed(-1));\n    EXPECT_FALSE(Scheduler::Instance().JobIdUsed(Scheduler::Instance().getNewJobId()));\n    const job_id_t job_id1 = Scheduler::Instance().newJob(JobOptions_t(alg_opts, model_opts));\n    ASSERT_TRUE(Scheduler::Instance().JobIdUsed(job_id1));\n    Scheduler::Instance().deleteJob(job_id1);\n    ASSERT_FALSE(Scheduler::Instance().JobIdUsed(job_id1));\n}\n\n\nvoid NullFunc(uv_work_t* req, int status) {};\n\n\nTEST_F(SchedulerTest, Train_Not_Found) {\n    try {\n        Scheduler::Instance().startJob(-1, NullFunc);\n    } catch (const exception& e) {\n        EXPECT_STREQ(\"Job id must correspond to a job that has been created.\", e.what());\n    }\n}\n\n\nTEST_F(SchedulerTest, Train) {\n    job_id_t job_id = Scheduler::Instance().newJob(JobOptions_t(alg_opts, model_opts));\n    ASSERT_TRUE(Scheduler::Instance().setX(job_id, X));\n    ASSERT_TRUE(Scheduler::Instance().setY(job_id, y));\n    ASSERT_TRUE(Scheduler::Instance().startJob(job_id, NullFunc));\n}\n\nTEST_F(SchedulerTest, CheckJobProgress) {\n    EXPECT_EQ(-1, Scheduler::Instance().checkJobProgress(-1));\t// job progress == -1 for bad ID\n\n    // Large Job\n    job_id_t job_id = Scheduler::Instance().newJob(JobOptions_t(alg_opts, model_opts));\n    ASSERT_TRUE(Scheduler::Instance().setX(job_id, LargeX));\n    ASSERT_TRUE(Scheduler::Instance().setY(job_id, LargeY));\n    ASSERT_EQ(0, Scheduler::Instance().checkJobProgress(job_id));\t// job progress == 0 before being run\n    ASSERT_TRUE(Scheduler::Instance().startJob(job_id, NullFunc));\n    while(Scheduler::Instance().checkJobProgress(job_id) == 0) {\n    \tusleep(1);\n    }\n    float progress = Scheduler::Instance().checkJobProgress(job_id);\t// 0 < job progress < 1 before end of run\n    ASSERT_GE(progress, 0);\n    ASSERT_LT(progress, 1);\n    float progress_2 = Scheduler::Instance().checkJobProgress(job_id);\t// job progress monotonically increasing\n    ASSERT_GE(progress_2, progress);\n    while(Scheduler::Instance().checkJobProgress(job_id) < 1.0) {\n        usleep(1);\n    }\n    ASSERT_EQ(1.0, Scheduler::Instance().checkJobProgress(job_id));\t// job progress == 1 after run\n\n    // Everything should be the same for a second run (this small job only takes 1 iteration, though).\n    job_id_t job_id2 = Scheduler::Instance().newJob(JobOptions_t(alg_opts, model_opts));\n    Scheduler::Instance().setX(job_id2, X);\n    Scheduler::Instance().setY(job_id2, y);\n    ASSERT_TRUE(Scheduler::Instance().startJob(job_id2, NullFunc));\n\n    progress = Scheduler::Instance().checkJobProgress(job_id2);\n    ASSERT_GE(progress, 0);\n    progress_2 = Scheduler::Instance().checkJobProgress(job_id2);\n    ASSERT_GE(progress_2, progress);\n\n    while(Scheduler::Instance().checkJobProgress(job_id2) < 1.0) {\n        usleep(1);\n    }\n    ASSERT_EQ(1.0, Scheduler::Instance().checkJobProgress(job_id2));\n\n    // Run large job again\n    job_id_t job_id3 = Scheduler::Instance().newJob(JobOptions_t(alg_opts, model_opts));\n    ASSERT_NE(job_id, job_id3);\n    Scheduler::Instance().setX(job_id3, LargeX);\n    Scheduler::Instance().setY(job_id3, LargeY);\n    ASSERT_EQ(0, Scheduler::Instance().checkJobProgress(job_id3));\n    ASSERT_TRUE(Scheduler::Instance().startJob(job_id3, NullFunc));\n    while(Scheduler::Instance().checkJobProgress(job_id3) == 0) {\n    \tusleep(1);\n    }\n    progress = Scheduler::Instance().checkJobProgress(job_id3);\n    ASSERT_GE(progress, 0);\n    ASSERT_LT(progress, 1);\n    progress_2 = Scheduler::Instance().checkJobProgress(job_id3);\n    ASSERT_GE(progress_2, progress);\n    while(Scheduler::Instance().checkJobProgress(job_id3) < 1.0) {\n        usleep(1);\n    }\n    ASSERT_EQ(1.0, Scheduler::Instance().checkJobProgress(job_id3));\n\n    ASSERT_TRUE(Scheduler::Instance().deleteJob(job_id3));\n    ASSERT_EQ(Scheduler::Instance().checkJobProgress(job_id3), -1);\t// job progress == -1 after being deleted\n}\n\n\nTEST_F(SchedulerTest, DeleteJob) {\n    ASSERT_FALSE(Scheduler::Instance().deleteJob(-1));  // can't delete non-existent job\n\n    // Short job - delete after finishing\n    job_id_t job_id = Scheduler::Instance().newJob(JobOptions_t(alg_opts, model_opts));\n    Scheduler::Instance().setX(job_id, X);\n    Scheduler::Instance().setY(job_id, y);\n    ASSERT_TRUE(Scheduler::Instance().startJob(job_id, NullFunc));\n\n    float progress = Scheduler::Instance().checkJobProgress(job_id);\n    ASSERT_GE(progress, 0);\n    float progress_2 = Scheduler::Instance().checkJobProgress(job_id);\n    ASSERT_GE(progress_2, progress);\n    while(Scheduler::Instance().checkJobProgress(job_id) < 1.0) {\n        usleep(1);\n    }\n    ASSERT_EQ(1.0, Scheduler::Instance().checkJobProgress(job_id));\n    ASSERT_TRUE(Scheduler::Instance().deleteJob(job_id));\n    ASSERT_FALSE(Scheduler::Instance().deleteJob(job_id));  // can't delete job twice\n\n    // Large job - delete while it is running\n    job_id = Scheduler::Instance().newJob(JobOptions_t(alg_opts, model_opts));\n    ASSERT_TRUE(Scheduler::Instance().setX(job_id, LargeX));\n    ASSERT_TRUE(Scheduler::Instance().setY(job_id, LargeY));\n    ASSERT_EQ(0, Scheduler::Instance().checkJobProgress(job_id));   // job progress == 0 before being run\n    ASSERT_TRUE(Scheduler::Instance().startJob(job_id, NullFunc));\n    while(Scheduler::Instance().checkJobProgress(job_id) == 0) {\n        usleep(1);\n    }\n    progress = Scheduler::Instance().checkJobProgress(job_id);   // 0 < job progress < 1 before end of run\n    ASSERT_GE(progress, 0);\n    ASSERT_LT(progress, 1);\n    ASSERT_TRUE(Scheduler::Instance().deleteJob(job_id));   // should be able to safely delete a job while it's running (it gets cancelled)    \n    ASSERT_EQ(-1, Scheduler::Instance().checkJobProgress(job_id)); // deleted job has progress = -1\n\n    // Should be able to do it all again.\n    job_id = Scheduler::Instance().newJob(JobOptions_t(alg_opts, model_opts));\n    ASSERT_TRUE(Scheduler::Instance().setX(job_id, LargeX));\n    ASSERT_TRUE(Scheduler::Instance().setY(job_id, LargeY));\n    ASSERT_EQ(0, Scheduler::Instance().checkJobProgress(job_id));   // job progress == 0 before being run\n    ASSERT_TRUE(Scheduler::Instance().startJob(job_id, NullFunc));\n    while(Scheduler::Instance().checkJobProgress(job_id) == 0) {\n        usleep(1);\n    }\n    progress = Scheduler::Instance().checkJobProgress(job_id);   // 0 < job progress < 1 before end of run\n    ASSERT_GE(progress, 0);\n    ASSERT_LT(progress, 1);\n    ASSERT_TRUE(Scheduler::Instance().deleteJob(job_id));   // should be able to safely delete a job while it's running (it gets cancelled)    \n    ASSERT_EQ(-1, Scheduler::Instance().checkJobProgress(job_id)); // deleted job has progress = -1\n}\n\n\nTEST_F(SchedulerTest, GetJobResult) {\n    job_id_t job_id = Scheduler::Instance().newJob(JobOptions_t(alg_opts, model_opts));\n    Scheduler::Instance().setX(job_id, X);\n    Scheduler::Instance().setY(job_id, y);    \n    ASSERT_TRUE(Scheduler::Instance().startJob(job_id, NullFunc));\n\n    MatrixXf results = Scheduler::Instance().getJobResult(job_id);\n    while (Scheduler::Instance().checkJobProgress(job_id) < 1.0) {\n        usleep(1);\n    }\n    results = Scheduler::Instance().getJobResult(job_id);\n}\n", "meta": {"hexsha": "4c4319d088ebd58c4561ccdf9cc0ee96c428cc77", "size": 14654, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Scheduler/Scheduler_Tests.cpp", "max_stars_repo_name": "blengerich/jenkins_test", "max_stars_repo_head_hexsha": "512aec681577063e3d68f699d19f53374e59585a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2016-10-20T00:36:31.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-06T16:40:52.000Z", "max_issues_repo_path": "src/Scheduler/Scheduler_Tests.cpp", "max_issues_repo_name": "blengerich/jenkins_test", "max_issues_repo_head_hexsha": "512aec681577063e3d68f699d19f53374e59585a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 44.0, "max_issues_repo_issues_event_min_datetime": "2016-11-11T22:41:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-04T21:55:57.000Z", "max_forks_repo_path": "src/Scheduler/Scheduler_Tests.cpp", "max_forks_repo_name": "blengerich/jenkins_test", "max_forks_repo_head_hexsha": "512aec681577063e3d68f699d19f53374e59585a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-02-01T09:19:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-28T14:40:43.000Z", "avg_line_length": 37.7680412371, "max_line_length": 143, "alphanum_fraction": 0.6721714208, "num_tokens": 4118, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.49553458119607385}}
{"text": "#include <iostream>\n#include <fstream>\n#include <vector>\n#include <string>\n#include <map>\n#include <unordered_map>\n#include <cstdlib>\n\n#include <boost/algorithm/string.hpp>\n\n#include \"Day3.hpp\"\n\nstd::unordered_map<int, std::unordered_map<int, int>> fillMap(std::vector<std::string>& instructions);\nbool mapsOverlapAtCoordinate(std::unordered_map<int, std::unordered_map<int, int>>& map1, std::unordered_map<int, std::unordered_map<int, int>>& map2, int x, int y);\n\nvoid day3() {\n\tstd::ifstream inputFile(\"Data/Day3.txt\");\n\tstd::string line1, line2;\n\tstd::getline(inputFile, line1);\n\tstd::getline(inputFile, line2);\n\tstd::cout << line1 << std::endl << std::endl << line2 << std::endl << std::endl;\n\n\tstd::vector<std::string> instructionsLine1;\n\tstd::vector<std::string> instructionsLine2;\n\tboost::split(instructionsLine1, line1, boost::is_any_of(\",\"), boost::token_compress_on);\n\tboost::split(instructionsLine2, line2, boost::is_any_of(\",\"), boost::token_compress_on);\n\t\n\tauto map1 = fillMap(instructionsLine1);\n\tauto map2 = fillMap(instructionsLine2);\n\n\tstd::pair<int, int> closestIntersection(0, 0);\n\tint closestDistance = 99999999;\n\n\tfor (std::unordered_map<int, std::unordered_map<int, int>>::iterator it = map1.begin(); it != map1.end(); ++it) {\n\t\tint x = it->first;\n\t\tfor (std::unordered_map<int, int>::iterator it2 = it->second.begin(); it2 != it->second.end(); ++it2) {\n\t\t\tint y = it2->first;\n\n\t\t\tbool overlap = mapsOverlapAtCoordinate(map1, map2, x, y);\n\t\t\t\n\t\t\tif (overlap) {\n\t\t\t\t// Check for Part 1 (closest Manhattan Distance)\n\t\t\t\t//\tint distance = abs(x) + abs(y);\n\n\t\t\t\t// Check for Part 2 (shortest path)\n\t\t\t\tint distance1 = map1[x][y];\n\t\t\t\tint distance2 = map2[x][y];\n\t\t\t\tint distance = distance1 + distance2;\n\t\t\t\t//std::cout << distance << \" \";\n\t\t\t\tif (distance < closestDistance) {\n\t\t\t\t\tclosestIntersection.first = x;\n\t\t\t\t\tclosestIntersection.second = y;\n\t\t\t\t\tclosestDistance = distance;\n\t\t\t\t\tstd::cout << \"New closest : \" << closestIntersection.first << \",\" << closestIntersection.second << \" - Distance : \" << closestDistance << std::endl;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n}\n\nstd::unordered_map<int, std::unordered_map<int, int>> fillMap(std::vector<std::string>& instructions) {\n\tstd::unordered_map<int, std::unordered_map<int, int>> map;\n\tstd::pair<int, int> currentPosition(0, 0);\n\tint distance = 0;\n\n\tfor (auto instruction = instructions.begin(); instruction != instructions.end(); ++instruction) {\n\t\tchar direction = instruction->at(0);\n\t\tint number = std::stoi(instruction->substr(1));\n\t\t//std::cout << *instruction << \": \" << direction << \" \" << number << std::endl;\n\n\t\tswitch (direction)\n\t\t{\n\t\tcase 'U':\n\t\t\tfor (int y = 0; y < number; ++y) {\n\t\t\t\tcurrentPosition.second++;\n\t\t\t\tdistance++;\n\t\t\t\tmap[currentPosition.first][currentPosition.second] = distance;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 'R':\n\t\t\tfor (int x = 0; x < number; ++x) {\n\t\t\t\tcurrentPosition.first++;\n\t\t\t\tdistance++;\n\t\t\t\tmap[currentPosition.first][currentPosition.second] = distance;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 'D':\n\t\t\tfor (int y = 0; y < number; ++y) {\n\t\t\t\tcurrentPosition.second--;\n\t\t\t\tdistance++;\n\t\t\t\tmap[currentPosition.first][currentPosition.second] = distance;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 'L':\n\t\t\tfor (int x = 0; x < number; ++x) {\n\t\t\t\tcurrentPosition.first--;\n\t\t\t\tdistance++;\n\t\t\t\tmap[currentPosition.first][currentPosition.second] = distance;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn map;\n}\n\nbool mapsOverlapAtCoordinate(std::unordered_map<int, std::unordered_map<int, int>>& map1, std::unordered_map<int, std::unordered_map<int, int>>& map2, int x, int y) {\n\tif (map1.find(x) != map1.end() && map2.find(x) != map2.end()) {\n\t\tif (map1[x].find(y) != map1[x].end() && map2[x].find(y) != map2[x].end()) {\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}", "meta": {"hexsha": "8a083d969ac0f20649c588d53e765fb8eb567275", "size": 3686, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AdventOfCode2019/Src/Day3.cpp", "max_stars_repo_name": "Epono/AdventOfCode2019", "max_stars_repo_head_hexsha": "d035b8943a7e9b96491ed7a499e98101c08256c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AdventOfCode2019/Src/Day3.cpp", "max_issues_repo_name": "Epono/AdventOfCode2019", "max_issues_repo_head_hexsha": "d035b8943a7e9b96491ed7a499e98101c08256c1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AdventOfCode2019/Src/Day3.cpp", "max_forks_repo_name": "Epono/AdventOfCode2019", "max_forks_repo_head_hexsha": "d035b8943a7e9b96491ed7a499e98101c08256c1", "max_forks_repo_licenses": ["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.052173913, "max_line_length": 166, "alphanum_fraction": 0.6521975041, "num_tokens": 1022, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.49553458119607385}}
{"text": "#define BOOST_TEST_MODULE matrix\n\n#include <boost/test/unit_test.hpp>\n#include <boost/test/test_case_template.hpp>\n#include <boost/mpl/list.hpp>\n\n\n#include <mla/matrix/all.h++>\n#include <mla/vector/all.h++>\n#include <mla/matrix/convert.h++>\n\n#include <mla/operations/level2/gemv.h++>\n\n\ntypedef boost::mpl::list<\n\tmla::matrix::DenseRowMajor<float>,\n\tmla::matrix::DenseRowMajor<double>,\n\tmla::matrix::SparseCRS<float>,\n\tmla::matrix::SparseCRS<double>\n> matrix_type_list;\n\n\nBOOST_AUTO_TEST_SUITE(test_operations)\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( matrix_multiply, MatrixType, matrix_type_list )\n{\n\tsize_t matrix_size = 6;\n\n\ttypedef typename MatrixType::scalar_type Scalar;\n\n\tMatrixType A(matrix_size, matrix_size);\n\tA.setEye();\n\n\tmla::vector::Dense<Scalar> x(matrix_size), y(matrix_size);\n\n\tfor(unsigned int i = 0; i < matrix_size; i++)\n\t{\n\t\tx.setValue( i, (Scalar)1.0f);\n\t}\n\n\n\tScalar const alfa = 1.0;\n\tScalar const beta = 1.0;\n\tmla::gemv(alfa, A, x, beta, y);\n\n\tfor(unsigned int i = 0; i < matrix_size; i++)\n\t{\n\t\tBOOST_CHECK_CLOSE( x.getValue(i), y.getValue(i), 0.001f);\n\t}\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n\n", "meta": {"hexsha": "182c390eb53a4b1624c1221b0f21959e88b8531c", "size": 1105, "ext": "c++", "lang": "C++", "max_stars_repo_path": "unit_tests/test_blas_level2_gemv.c++", "max_stars_repo_name": "ruimaciel/mla", "max_stars_repo_head_hexsha": "b05f5913067af31a345cd2187de25871dbe31856", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "unit_tests/test_blas_level2_gemv.c++", "max_issues_repo_name": "ruimaciel/mla", "max_issues_repo_head_hexsha": "b05f5913067af31a345cd2187de25871dbe31856", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unit_tests/test_blas_level2_gemv.c++", "max_forks_repo_name": "ruimaciel/mla", "max_forks_repo_head_hexsha": "b05f5913067af31a345cd2187de25871dbe31856", "max_forks_repo_licenses": ["BSD-3-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.7321428571, "max_line_length": 78, "alphanum_fraction": 0.7185520362, "num_tokens": 322, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.49553457545519475}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2004, 2005, 2008 Klaus Spanderen\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/*! \\file analytichestonengine.hpp\n    \\brief analytic Heston-model engine\n*/\n\n#ifndef quantlib_analytic_heston_engine_hpp\n#define quantlib_analytic_heston_engine_hpp\n\n#include <ql/math/integrals/integral.hpp>\n#include <ql/math/integrals/gaussianquadratures.hpp>\n#include <ql/pricingengines/genericmodelengine.hpp>\n#include <ql/models/equity/hestonmodel.hpp>\n#include <ql/instruments/vanillaoption.hpp>\n\n#include <boost/function.hpp>\n#include <complex>\n\nnamespace QuantLib {\n\n    //! analytic Heston-model engine based on Fourier transform\n\n    /*! Integration detail:\n        Two algebraically equivalent formulations of the complex\n        logarithm of the Heston model exist. Gatherals [2005]\n        (also Duffie, Pan and Singleton [2000], and Schoutens,\n        Simons and Tistaert[2004]) version does not cause\n        discoutinuities whereas the original version (e.g. Heston [1993])\n        needs some sort of \"branch correction\" to work properly.\n        Gatheral's version does also work with adaptive integration\n        routines and should be preferred over the original Heston version.\n    */\n\n    /*! References:\n\n        Heston, Steven L., 1993. A Closed-Form Solution for Options\n        with Stochastic Volatility with Applications to Bond and\n        Currency Options.  The review of Financial Studies, Volume 6,\n        Issue 2, 327-343.\n\n        A. Sepp, Pricing European-Style Options under Jump Diffusion\n        Processes with Stochastic Volatility: Applications of Fourier\n        Transform (<http://math.ut.ee/~spartak/papers/stochjumpvols.pdf>)\n\n        R. Lord and C. Kahl, Why the rotation count algorithm works,\n        http://papers.ssrn.com/sol3/papers.cfm?abstract_id=921335\n\n        H. Albrecher, P. Mayer, W.Schoutens and J. Tistaert,\n        The Little Heston Trap, http://www.schoutens.be/HestonTrap.pdf\n\n        J. Gatheral, The Volatility Surface: A Practitioner's Guide,\n        Wiley Finance\n\n        \\ingroup vanillaengines\n\n        \\test the correctness of the returned value is tested by\n              reproducing results available in web/literature\n              and comparison with Black pricing.\n    */\n    class AnalyticHestonEngine\n        : public GenericModelEngine<HestonModel,\n                                    VanillaOption::arguments,\n                                    VanillaOption::results> {\n      public:\n        class Integration;\n        enum ComplexLogFormula { Gatheral, BranchCorrection };\n\n        // Simple to use constructor: Using adaptive\n        // Gauss-Lobatto integration and Gatheral's version of complex log.\n        // Be aware: using a too large number for maxEvaluations might result\n        // in a stack overflow as the Lobatto integration is a recursive\n        // algorithm.\n        AnalyticHestonEngine(const boost::shared_ptr<HestonModel>& model,\n                             Real relTolerance, Size maxEvaluations);\n\n        // Constructor using Laguerre integration\n        // and Gatheral's version of complex log.\n        AnalyticHestonEngine(const boost::shared_ptr<HestonModel>& model,\n                             Size integrationOrder = 144);\n\n        // Constructor giving full control\n        // over the Fourier integration algorithm\n        AnalyticHestonEngine(const boost::shared_ptr<HestonModel>& model,\n                             ComplexLogFormula cpxLog, const Integration& itg);\n\n\n        void calculate() const;\n        Size numberOfEvaluations() const;\n\n        static void doCalculation(Real riskFreeDiscount,\n                                             Real dividendDiscount,\n                                             Real spotPrice,\n                                             Real strikePrice,\n                                             Real term,\n                                             Real kappa, Real theta, Real sigma, Real v0, Real rho,\n                                             const TypePayoff& type,\n                                             const Integration& integration,\n                                             const ComplexLogFormula cpxLog,\n                                             const AnalyticHestonEngine* const enginePtr,\n                                             Real& value,\n                                             Size& evaluations);\n\n      protected:\n        // call back for extended stochastic volatility\n        // plus jump diffusion engines like bates model\n        virtual std::complex<Real> addOnTerm(Real phi,\n                                             Time t,\n                                             Size j) const;\n\n      private:\n        class Fj_Helper;\n\n        mutable Size evaluations_;\n        const ComplexLogFormula cpxLog_;\n        const boost::shared_ptr<Integration> integration_;\n\n\n\n    };\n\n\n    class AnalyticHestonEngine::Integration {\n      public:\n        // non adaptive integration algorithms based on Gaussian quadrature\n        static Integration gaussLaguerre    (Size integrationOrder = 128);\n        static Integration gaussLegendre    (Size integrationOrder = 128);\n        static Integration gaussChebyshev   (Size integrationOrder = 128);\n        static Integration gaussChebyshev2nd(Size integrationOrder = 128);\n\n        // for an adaptive integration algorithm Gatheral's version has to\n        // be used.Be aware: using a too large number for maxEvaluations might\n        // result in a stack overflow as the these integrations are based on\n        // recursive algorithms.\n        static Integration gaussLobatto(Real relTolerance, Real absTolerance,\n                                        Size maxEvaluations = 1000);\n\n        // usually these routine have a poor convergence behaviour.\n        static Integration gaussKronrod(Real absTolerance,\n                                        Size maxEvaluations = 1000);\n        static Integration simpson(Real absTolerance,\n                                   Size maxEvaluations = 1000);\n        static Integration trapezoid(Real absTolerance,\n                                     Size maxEvaluations = 1000);\n\n        Real calculate(Real c_inf,\n                       const boost::function1<Real, Real>& f) const;\n\n        Size numberOfEvaluations() const;\n        bool isAdaptiveIntegration() const;\n\n      private:\n        enum Algorithm\n            { GaussLobatto, GaussKronrod, Simpson, Trapezoid,\n              GaussLaguerre, GaussLegendre,\n              GaussChebyshev, GaussChebyshev2nd };\n\n        Integration(Algorithm intAlgo,\n                    const boost::shared_ptr<GaussianQuadrature>& quadrature);\n\n        Integration(Algorithm intAlgo,\n                    const boost::shared_ptr<Integrator>& integrator);\n\n        const Algorithm intAlgo_;\n        const boost::shared_ptr<Integrator> integrator_;\n        const boost::shared_ptr<GaussianQuadrature> gaussianQuadrature_;\n    };\n\n    // inline\n\n    inline \n    std::complex<Real> AnalyticHestonEngine::addOnTerm(Real,\n                                                       Time,\n                                                       Size) const {\n        return std::complex<Real>(0,0);\n    }\n\n}\n\n#endif\n", "meta": {"hexsha": "a357efcec4e731b6945026f83c2d9cdce9781b6e", "size": 7993, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "QuantLib/ql/pricingengines/vanilla/analytichestonengine.hpp", "max_stars_repo_name": "frannuca/quantlib", "max_stars_repo_head_hexsha": "63e66f5f767397e5b7c79fa78eaed4e3e0a6b7c6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "QuantLib/ql/pricingengines/vanilla/analytichestonengine.hpp", "max_issues_repo_name": "frannuca/quantlib", "max_issues_repo_head_hexsha": "63e66f5f767397e5b7c79fa78eaed4e3e0a6b7c6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "QuantLib/ql/pricingengines/vanilla/analytichestonengine.hpp", "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": 40.3686868687, "max_line_length": 99, "alphanum_fraction": 0.6162892531, "num_tokens": 1634, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.49553457545519475}}
{"text": "#include <cmath>\n#include <limits>\n#include <stdexcept>\n#include <iostream>\n#include <boost/filesystem.hpp>\n#include <sstream>\n#include <cstdlib>\n#include <fstream>\n#include <cfenv>\n#include <X11/xpm.h>\n#include <iomanip>\n#include <FL/x.H>\n#include \"utils.hpp\"\n#include \"florb.xpm\"\n\n#define CLIPLEFT   (1)  // 0001\n#define CLIPRIGHT  (2)  // 0010\n#define CLIPBOTTOM (4)  // 0100\n#define CLIPTOP    (8)  // 1000\n\n#define CIRCUMFERENCEKM (2*M_PI*6372.7982)\n\nflorb::point2d<double> florb::utils::wsg842merc(const florb::point2d<double> &wsg84)\n{\n    if ((wsg84.x() > 180.0) || (wsg84.x() < -180.0))\n        throw std::out_of_range(_(\"Invalid longitude\"));\n    if ((wsg84.y() > 90.0) || (wsg84.y() < -90.0))\n        throw std::out_of_range(_(\"Invalid latitude\"));\n\n    // Anything above 85 degrees N or S is infinity in the mercator projection,\n    // clip here.\n    double lat = wsg84.y();\n    if (lat > 85.0)\n        lat = 85.0;\n    else if (lat < -85)\n        lat = -85.0;\n\n    // Project to Mercator (360 by 360 square)\n    return florb::point2d<double>(\n            180.0 + wsg84.x(),\n            180.0 - ((180.0/M_PI) * log(tan(M_PI/4.0+lat*(M_PI/180.0)/2.0))));\n}\n\nflorb::point2d<unsigned long> florb::utils::merc2px(unsigned int z, const florb::point2d<double> &merc)\n{\n    unsigned long dimxy = dim(z);\n\n    return florb::point2d<unsigned long>(\n        (unsigned long)(((double)(dimxy-1)/360.0) * merc.x()),\n        (unsigned long)(((double)(dimxy-1)/360.0) * merc.y()));\n}\n\nflorb::point2d<unsigned long> florb::utils::wsg842px(unsigned int z, const florb::point2d<double> &wsg84)\n{\n    // Mercator projection\n    florb::point2d<double> merc(wsg842merc(wsg84));\n\n    // Unit conversion\n    return merc2px(z, merc);\n}\n\nflorb::point2d<double> florb::utils::px2wsg84(unsigned int z, const florb::point2d<unsigned long> &px)\n{\n    // Get map dimensions\n    unsigned long dimxy = dim(z);\n\n    // Make sure the coordinate is on the map\n    if ((px.x() > dimxy) || (px.y() > dimxy))\n        throw std::out_of_range(_(\"Invalid pixel position\"));\n\n    // Unit conversion\n    florb::point2d<double> mdeg(\n            (360.0/((double)dimxy/(double)px.x())),\n            (360.0/((double)dimxy/(double)px.y())));\n\n    // Convert mercator to GPS coordinate\n    return merc2wsg84(mdeg);\n}\n\nflorb::point2d<double> florb::utils::merc2wsg84(const florb::point2d<double>& wsg84)\n{\n    return florb::point2d<double>( \n            wsg84.x() - 180.0,\n            -((180.0/M_PI) * (2.0 * atan(exp((wsg84.y()-180.0)*M_PI/180.0)) - M_PI/2.0)));\n}\n\nflorb::point2d<double> florb::utils::px2merc(unsigned int z, const florb::point2d<unsigned long> &px)\n{\n    unsigned long dimxy = dim(z);\n\n    // Make sure the coordinate is on the map\n    if ((px.x() >= dimxy) || (px.y() >= dimxy))\n    {\n        throw std::out_of_range(_(\"Invalid pixel position\"));\n    }\n\n    double x = (px.x() == 0) ? 0.0 : (360.0/((double)(dimxy-1)/(double)px.x()));\n    double y = (px.y() == 0) ? 0.0 : (360.0/((double)(dimxy-1)/(double)px.y()));\n    return florb::point2d<double>(x,y);\n}\n\nunsigned long florb::utils::dim(unsigned int z)\n{\n    return pow(2.0, z) * 256;\n}\n\ndouble florb::utils::dist(const florb::point2d<double> &p1, const florb::point2d<double> &p2)\n{\n    if (p1 == p2)\n        return 0.0;\n\n    double d2r = (M_PI/180.0);\n    double lon1 = p1.x()*d2r;\n    double lat1 = p1.y()*d2r;\n    double lon2 = p2.x()*d2r;\n    double lat2 = p2.y()*d2r;\n\n    double ret = (6378.388 * acos(sin(lat1) * sin(lat2) + cos(lat1) * cos(lat2) * cos(lon2 - lon1)));\n\n    return (std::isnan(ret) > 0) ? 0.0 : ret;\n}\n\ndouble florb::utils::dist_merc(const florb::point2d<double> &p1, const florb::point2d<double> &p2)\n{\n    if (p1 == p2)\n        return 0.0;\n\n    double dstmerc = sqrt( pow(std::abs(p1.x()-p2.x()), 2.0) + pow(std::abs(p1.y()-p2.y()), 2.0)*0.9444444 );\n    return (dstmerc * (CIRCUMFERENCEKM/360.0));\n}\n\ndouble florb::utils::meters_per_pixel(unsigned int z, double lat)\n{\n    return (CIRCUMFERENCEKM * cos(lat*(M_PI/180.0)) / pow(2.0,(z+8))) * 1000.0;\n}\n\ntime_t florb::utils::iso8601_2timet(const std::string& iso)\n{\n    struct tm stm;\n    strptime(iso.c_str(), \"%FT%T%z\", &stm);\n\n    return mktime(&stm);\n}\n\nstd::string florb::utils::timet2iso8601(time_t t)\n{\n    char buf[sizeof \"2011-10-08T07:07:09Z\"];\n    strftime(buf, sizeof buf, \"%FT%TZ\", gmtime(&t));\n\n    return std::string(buf);\n}\n\nstd::string florb::utils::pathsep()\n{\n#if defined(WIN32) || defined(_WIN32) \nreturn std::string(\"\\\\\");\n#else \nreturn std::string(\"/\");\n#endif \n}\n\nstd::string florb::utils::userdir()\n{\n    char *home = getenv(\"HOME\");\n    if (!home)\n        throw 0;\n\n    return std::string(home);\n}\n\nstd::string florb::utils::appdir()\n{\n    std::ostringstream oss;\n    oss << userdir();\n    oss << pathsep();\n    oss << \".florb\";\n\n    return oss.str();\n}\n\nbool florb::utils::mkdir(const std::string& path)\n{\n    bool ret = true;\n\n    try {\n        boost::filesystem::create_directory(path);\n    } catch (...) {\n        ret = false;\n    }\n\n    return ret;\n}\n\nvoid florb::utils::rm(const std::string& path)\n{\n    boost::filesystem::remove_all(path);\n}\n\nbool florb::utils::exists(const std::string& path)\n{\n    return boost::filesystem::exists(path);\n}\n\nstd::string florb::utils::filestem(const std::string& path)\n{\n    return boost::filesystem::path(path).stem().string();\n}\n\nstd::string florb::utils::extension(const std::string& path)\n{\n    return boost::filesystem::path(path).extension().string();\n}\n\nvoid florb::utils::touch(const std::string& path)\n{\n    std::fstream f(path, std::ios::out|std::ios::app);\n\tf.close();\n}\n\nvoid florb::utils::set_window_icon(Fl_Window *w)\n{\n    fl_open_display();\n    Pixmap p, mask;\n    XpmCreatePixmapFromData(fl_display, DefaultRootWindow(fl_display), const_cast<char**>(florb_xpm), &p, &mask, NULL);\n    w->icon((char *)p);\n}\n\nstd::vector<std::string> florb::utils::str_split(const std::string& str, const std::string& delimiter)\n{\n    std::size_t offs = 0, p1 = 0, p2 = std::string::npos;\n    std::size_t len = str.length();\n\n    std::vector<std::string> ret;\n    while ((offs < len) && (p2 = str.find(delimiter, offs)) != std::string::npos)\n    {\n        std::string token(str.substr(p1, p2-p1));\n\n        if (token.length() > 0)\n            ret.push_back(str.substr(p1, p2-p1));\n    \n        p1 = p2 + delimiter.length();\n        offs = p1;\n    }\n\n    if ((p1 != len))\n        ret.push_back(str.substr(p1, len-p1));\n\n    return ret;\n}\n\nstd::size_t florb::utils::str_count(const std::string& str, const std::string& token)\n{\n    if (token.length() == 0)\n        return 0;\n\n    std::size_t ret = 0, offs = 0;\n\n    while ((offs = str.find(token, offs)) != std::string::npos)\n    {\n        offs += token.length();\n        ret++;\n    }\n\n    return ret;\n}\n\nvoid florb::utils::str_replace(std::string& str, const std::string& s, const std::string& r)\n{\n    std::size_t offs = 0;\n    while ((offs = str.find(s, 0)) != std::string::npos)\n    {\n        str.replace(offs, s.length(), r);\n    }\n}\n\n// Cohen\u2013Sutherland clipping algorithm\nbool florb::utils::clipline(\n        florb::point2d<double> &p1, \n        florb::point2d<double> &p2, \n        const florb::point2d<double> &r1, \n        const florb::point2d<double> &r2, \n        bool &p1clip, \n        bool &p2clip)\n{\n    bool ret = false;\n    double xmin, xmax, ymin, ymax;\n    p1clip = false;\n    p2clip = false;\n\n    if (r1.x() > r2.x())\n    {\n        xmin = r2.x();\n        xmax = r1.x();\n    }\n    else\n    {\n        xmin = r1.x();\n        xmax = r2.x();\n    }\n\n    if (r1.y() > r2.y())\n    {\n        ymin = r2.y();\n        ymax = r1.y();\n    }\n    else\n    {\n        ymin = r1.y();\n        ymax = r2.y();\n    } \n\n    bool overflowa = false;\n\n    // Catch arithmetic overflow when calculating m and n\n    double n = 0, m = 0;\n    for (;;)\n    {\n        std::feclearexcept(FE_OVERFLOW|FE_UNDERFLOW|FE_DIVBYZERO);\n        \n        m = (p2.y() - p1.y()) / (p2.x() - p1.x());\n        if (std::fetestexcept(FE_OVERFLOW|FE_UNDERFLOW|FE_DIVBYZERO) != 0)\n        {\n            overflowa = true;\n            break;\n        }\n\n        std::feclearexcept(FE_OVERFLOW|FE_UNDERFLOW|FE_DIVBYZERO);\n\n        n = p1.y() - (m * p1.x());\n        if (std::fetestexcept(FE_OVERFLOW|FE_UNDERFLOW|FE_DIVBYZERO) != 0)\n        {\n            overflowa = true;\n            break;\n        }\n\n        break;\n    }\n\n    // Max 2 clipping operations per point and one last check operation. \n    for (int i=0;i<5;i++)\n    {\n        // Compute code for both points\n        int code1 = 0, code2 = 0;\n        \n        if (p1.x() < xmin)\n            code1 |= CLIPLEFT;\n        if (p1.x() > xmax)\n            code1 |= CLIPRIGHT;\n        if (p1.y() < ymin)\n            code1 |= CLIPTOP;\n        if (p1.y() > ymax)\n            code1 |= CLIPBOTTOM;\n\n        if (p2.x() < xmin)\n            code2 |= CLIPLEFT;\n        if (p2.x() > xmax)\n            code2 |= CLIPRIGHT;\n        if (p2.y() < ymin)\n            code2 |= CLIPTOP;\n        if (p2.y() > ymax)\n            code2 |= CLIPBOTTOM;\n\n        // Both inside, draw line\n        if ((code1 | code2) == 0)\n        {\n            ret = true;\n            break;\n        }\n\n        // Both top, bottom, left or right outside, line need not be drawn\n        if ((code1 & code2) != 0)\n        {\n            ret = false;\n            break;\n        }\n\n        // Pick an endpoint for clipping\n        florb::point2d<double> &ptmp = (code1 != 0) ? p1 : p2;\n        int codetmp;\n        if (code1 != 0)\n        {\n            codetmp = code1;\n            p1clip = true;\n        }\n        else\n        {\n            codetmp = code2;\n            p2clip = true;\n        }\n\n        // Clip top\n        if (codetmp & CLIPTOP)\n        {\n            // This is what the following code does with just a little overflow\n            // protection:\n            // ptmp[0] = (ymin - n) / m; \n\n            double cx;\n            for (;!overflowa;)\n            {\n                std::feclearexcept(FE_OVERFLOW|FE_UNDERFLOW|FE_DIVBYZERO);\n                cx = (ymin - n) / m;\n\n                if (std::fetestexcept(FE_OVERFLOW|FE_UNDERFLOW|FE_DIVBYZERO) != 0)\n                {\n                    overflowa = true;\n                    break;\n                }\n\n                break;\n            }\n\n            // In case of an arithmetic exception we assume a vertical line and\n            // keep the original x coordinate\n            if (!overflowa)\n                ptmp[0] = cx;\n\n            ptmp[1] = ymin;\n        }\n        // Clip Bottom\n        else if (codetmp & CLIPBOTTOM)\n        {\n            // This is what the following code does with just a little overflow\n            // protection:\n            // ptmp[0] = (ymax - n) / m; \n\n            double cx;\n            for (;!overflowa;)\n            {\n                std::feclearexcept(FE_OVERFLOW|FE_UNDERFLOW|FE_DIVBYZERO);\n                cx = (ymax - n) / m;\n\n                if (std::fetestexcept(FE_OVERFLOW|FE_UNDERFLOW|FE_DIVBYZERO) != 0)\n                {\n                    overflowa = true;\n                    break;\n                }\n\n                break;\n            }\n\n            // In case of an arithmetic exception we assume a vertical line and\n            // keep the original x coordinate\n            if (!overflowa)\n                ptmp[0] = cx;\n\n            ptmp[1] = ymax;\n        }\n        // Clip Left\n        else if (codetmp & CLIPLEFT)\n        {\n            // Vertical line left outside\n            if (overflowa)\n            {\n                ret = false;\n                break;\n            }\n                \n            ptmp[0] = xmin; \n            ptmp[1] = m * xmin + n;\n        }\n        // Clip Right\n        else if (codetmp & CLIPRIGHT)\n        {\n            // Vertical line right outside\n            if (overflowa)\n            {\n                ret = false;\n                break;\n            }\n\n            ptmp[0] = xmax; \n            ptmp[1] = m * xmax + n;\n        }\n    }\n\n    return ret;\n}\n\n", "meta": {"hexsha": "aa5f9cc1f8746cd0c82483356444a55208fb06a7", "size": 11911, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/utils.cpp", "max_stars_repo_name": "shugaa/florb", "max_stars_repo_head_hexsha": "85d2be7d851f83db8a289fd2018832aec295d526", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2015-03-26T22:44:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-09T12:31:24.000Z", "max_issues_repo_path": "src/utils.cpp", "max_issues_repo_name": "pekdon/florb", "max_issues_repo_head_hexsha": "85d2be7d851f83db8a289fd2018832aec295d526", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-09-01T13:03:29.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-29T09:37:31.000Z", "max_forks_repo_path": "src/utils.cpp", "max_forks_repo_name": "pekdon/florb", "max_forks_repo_head_hexsha": "85d2be7d851f83db8a289fd2018832aec295d526", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-02-12T05:46:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-31T06:48:11.000Z", "avg_line_length": 24.8145833333, "max_line_length": 119, "alphanum_fraction": 0.5279153723, "num_tokens": 3559, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.49553457545519475}}
{"text": "#include \"include/MMVII_all.h\"\n\n// #include <Eigen/Dense>\n\nnamespace MMVII\n{\n\n\n/// Sigma of convol sqrt(A^2+B^2)\ndouble SomSigm(double  aS1,double aS2) {return sqrt(Square(aS1)+Square(aS2));}\n/// \"Inverse\" of SomSigm  sqrt(A^2-B^2)\ndouble DifSigm(double  aS1,double aS2) \n{\n   MMVII_INTERNAL_ASSERT_tiny(aS1>=aS2,\"DifSigm\");\n   return sqrt(Square(aS1)-Square(aS2));\n}\n\n\n\n\n/** We use a class essentially to be able to use typedef, most method will be static */\ntemplate <class Type> class cLinearFilter\n{\n    public :\n      // in comments, note @ for convolution\n      typedef Type                                  tVal;\n      typedef typename tNumTrait<Type>::tBase       tBase;\n      typedef typename tNumTrait<Type>::tFloatAssoc tFl;\n\n      static void FilterExp\n                  (\n                      bool Normalize,  // If true, limit size effect and Cste => Cste (else lowe close to border)\n                      cDataIm2D<Type> &,\n                      int aNbIter,\n                      const cRect2 &,\n                      const tFl &aFx,\n                      const  tFl &aFy\n                  );\n};\n\n\n/**\n     Convolution of aLineIm in place by expononential filter \"F^|x|\", use a buffer\n*/\ntemplate <class TBuf,class TIm,class TFact,class TyNorm> void  \n   OneLineFilterExp\n   (\n       int aNbIter,\n       TBuf *aDBuf,\n       TIm* aLineIm,\n       TFact aFact,\n       int anX0,\n       int anX1,\n       TyNorm * aDataNorm \n   )\n{\n   for (int aKIter=0 ; aKIter<aNbIter ; aKIter++)\n   {\n      aDBuf[anX0] = 0;\n      // left to right ,at end  aDBuf  contains \"I  @ (Fx^|x| * x<0)\"\n      for (int anX = anX0+1; anX<anX1 ; anX++)\n      {\n          aDBuf[anX] =  aFact *(aDBuf[anX-1] + aLineIm[anX-1]);\n      }\n      // right to left, full convolution\n      for (int anX = anX1-2; anX>=anX0 ; anX--)\n      {\n          aLineIm[anX]  +=(TIm)(aFact*aLineIm[anX+1] );  // now Line contains \"I @  (Fx^|x| * x>=0)\n          aLineIm[anX+1]+=(TIm)(aDBuf[anX+1] ); // now contains   I  @ Fx^|x|\n      }\n   }\n   if (aDataNorm)\n   {\n      for (int anX= anX0 ; anX<anX1 ; anX++)\n         aLineIm[anX] /= aDataNorm[anX];\n   }\n}\n\ntemplate <class Type> Type * ImNormal(int aNbIter,cDataIm1D<Type> & aRes,Type aFact,int aX0,int aX1)\n{\n   aRes.Resize(cPt1di(aX0),cPt1di(aX1));\n   aRes.InitCste(1.0);\n\n   cIm1D<Type>  aBuf(aX0,aX1);\n   OneLineFilterExp(aNbIter,aBuf.DIm().ExtractRawData1D(),aRes.ExtractRawData1D(),aFact,aX0,aX1,(float *)nullptr);\n \n   return aRes.ExtractRawData1D();\n}\n\ntemplate <class Type> void  cLinearFilter<Type>::FilterExp\n                            (\n                                 bool Normalise,\n                                 cDataIm2D<Type> & aIm,\n                                 int   aNbIter,\n                                 const cRect2 & aRect,\n                                 const tFl &aFx,\n                                 const  tFl &aFy\n                            )\n{\n   MMVII_INTERNAL_ASSERT_strong(aRect.IncludedIn(aIm),\"cLinearFilter Rect is outside\");\n\n   // Local copy to have quick access\n   Type  **  aDIm = aIm.ExtractRawData2D();\n   int anX0 = aRect.P0().x();\n   int anY0 = aRect.P0().y();\n   int anX1 = aRect.P1().x();\n   int anY1 = aRect.P1().y();\n\n   // Create a buf  to avoid sides effect\n   // int aNbBuf = Norm1(aRect.Sz());\n   cIm1D<tBase> aImBuf(Norm1(aRect.Sz()));\n   cIm1D<tVal> aBufDupCol(aRect.Sz().y());\n   \n   cIm1D<tFl>  aImNormal(Norm1(aRect.Sz()));\n   // tFl * aBufNorm = nullptr;\n\n       //  Filter the lines , I @  Fx^|x| \n   if (aFx != 0)\n   {\n      tBase * aDBuf = aImBuf.DIm().RawDataLin()-anX0;\n      tFl * aDataNorm = Normalise ? ImNormal(aNbIter,aImNormal.DIm(),aFx,anX0,anX1) : nullptr;\n      \n      for (int anY=anY0 ; anY<anY1 ; anY++)\n      {\n           OneLineFilterExp(aNbIter,aDBuf,aDIm[anY],aFx,anX0,anX1,aDataNorm);\n      }\n   }\n       //  Filter the Column , I @  Fy^|y| \n   if (aFy != 0)\n   {\n       tBase * aDBuf = aImBuf.DIm().RawDataLin()-anY0;\n       tVal  * aDupCol = aBufDupCol.DIm().RawDataLin()-anY0;\n       tFl * aDataNorm = Normalise ? ImNormal(aNbIter,aImNormal.DIm(),aFy,anY0,anY1) : nullptr;\n       for (int anX=anX0 ; anX<anX1 ; anX++)\n       {\n          // Transferate Column X in line buf aDupCol\n          for (int anY=anY0 ; anY<anY1 ; anY++)\n          {\n             aDupCol[anY] = aDIm[anY][anX];\n          }\n          // Filter dup col\n          OneLineFilterExp(aNbIter,aDBuf,aDupCol,aFy,anY0,anY1,aDataNorm);\n          // Inverse transfer\n          for (int anY=anY0 ; anY<anY1 ; anY++)\n          {\n             aDIm[anY][anX] = aDupCol[anY] ;\n          }\n       }\n   }\n}\n\ntemplate <class Type>\nvoid  ExponentialFilter(bool Normalise,cDataIm2D<Type> & aDIm,int  aNbIt,const cRect2 & aR2,double Fx,double Fy)\n{\n   cLinearFilter<Type>::FilterExp(Normalise,aDIm,aNbIt,aR2,Fx,Fy);\n}\n\ntemplate <class Type> \nvoid  ExponentialFilter(cDataIm2D<Type> & aIm,int   aNbIter,double aFact)\n{\n    ExponentialFilter(true,aIm,aNbIter,aIm,aFact,aFact);\n}\n\ntemplate <class Type> \nvoid  ExpFilterOfStdDev(cDataIm2D<Type> & aIm,int   aNbIter,double aStdDev)\n{\n     ExponentialFilter(aIm,aNbIter,FactExpFromSigma2(Square(aStdDev)/aNbIter));\n}\n\ntemplate <class Type> \nvoid  ExpFilterOfStdDev(cDataIm2D<Type> & aImOut,const cDataIm2D<Type> & aImIn,int   aNbIter,double aStdDev)\n{\n     aImIn.DupIn(aImOut);\n     ExponentialFilter(aImOut,aNbIter,FactExpFromSigma2(Square(aStdDev)/aNbIter));\n}\n\n/* ========================== */\n/*       cImGrad              */\n/* ========================== */\n\n\ntemplate <class Type> cImGrad<Type>::cImGrad(const cIm2D<Type> & aGx,const cIm2D<Type> &  aGy) :\n    mGx (aGx),\n    mGy (aGy)\n{\n}\ntemplate <class Type> cImGrad<Type>::   cImGrad(const cPt2di & aSz) :\n     cImGrad<Type>(cIm2D<Type>(aSz),cIm2D<Type>(aSz))\n{\n}\n\ntemplate <class Type> cImGrad<Type>::cImGrad(const cIm2D<Type> & aImIn) : \n   cImGrad<Type>(aImIn.DIm().Sz()) \n{\n}\n\n\n/* ========================== */\n/*     cDataGenUnTypedIm      */\n/* ========================== */\n\n\n#define MACRO_INSTANTIATE_ExpoFilter(Type)\\\ntemplate  class cImGrad<Type>;\\\ntemplate  class cLinearFilter<Type>;\\\ntemplate void ExponentialFilter(bool,cDataIm2D<Type> &,int,const cRect2 &,double,double);\\\ntemplate void  ExponentialFilter(cDataIm2D<Type> & aIm,int   aNbIter,double aFact);\\\ntemplate void  ExpFilterOfStdDev(cDataIm2D<Type> & aIm,int   aNbIter,double aStdDev);\\\ntemplate void  ExpFilterOfStdDev(cDataIm2D<Type> & aIm,const cDataIm2D<Type> & aImIn,int   aNbIter,double aStdDev);\\\n\nMACRO_INSTANTIATE_ExpoFilter(tREAL4);\nMACRO_INSTANTIATE_ExpoFilter(tREAL8);\nMACRO_INSTANTIATE_ExpoFilter(tREAL16);\nMACRO_INSTANTIATE_ExpoFilter(tINT4);\nMACRO_INSTANTIATE_ExpoFilter(tINT2);\nMACRO_INSTANTIATE_ExpoFilter(tINT1);\n\n/*\ntemplate class cDataTypedIm<aType,1>;\\\ntemplate class cDataTypedIm<aType,2>;\\\ntemplate class cDataTypedIm<aType,3>;\n\n\nMACRO_INSTANTIATE_cDataTypedIm(tINT1)\nMACRO_INSTANTIATE_cDataTypedIm(tINT2)\nMACRO_INSTANTIATE_cDataTypedIm(tINT4)\n\nMACRO_INSTANTIATE_cDataTypedIm(tU_INT1)\nMACRO_INSTANTIATE_cDataTypedIm(tU_INT2)\nMACRO_INSTANTIATE_cDataTypedIm(tU_INT4)\n\nMACRO_INSTANTIATE_cDataTypedIm(tREAL4)\nMACRO_INSTANTIATE_cDataTypedIm(tREAL8)\nMACRO_INSTANTIATE_cDataTypedIm(tREAL16)\n*/\n\n\n\n};\n", "meta": {"hexsha": "467d78f7eb82b9052f7530917c5e819f1e312006", "size": 7157, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "MMVII/src/ImagesFiltrLinear/ExpGaussFilter.cpp", "max_stars_repo_name": "rumenmitrev/micmac", "max_stars_repo_head_hexsha": "065de918bb963a1c0f472504862c3060e180d48b", "max_stars_repo_licenses": ["CECILL-B"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MMVII/src/ImagesFiltrLinear/ExpGaussFilter.cpp", "max_issues_repo_name": "rumenmitrev/micmac", "max_issues_repo_head_hexsha": "065de918bb963a1c0f472504862c3060e180d48b", "max_issues_repo_licenses": ["CECILL-B"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MMVII/src/ImagesFiltrLinear/ExpGaussFilter.cpp", "max_forks_repo_name": "rumenmitrev/micmac", "max_forks_repo_head_hexsha": "065de918bb963a1c0f472504862c3060e180d48b", "max_forks_repo_licenses": ["CECILL-B"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8208333333, "max_line_length": 116, "alphanum_fraction": 0.6043034791, "num_tokens": 2352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.49553457545519475}}
{"text": "\n\n/* --------------------------------------------------------------------- \n * \n * Copyright (C) 2003 - 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: Guido Kanschat, University of Heidelberg, 2003 \n *          Baerbel Janssen, University of Heidelberg, 2010 \n *          Wolfgang Bangerth, Texas A&M University, 2010 \n *          Timo Heister, Clemson University, 2018 \n */ \n\n\n// @sect3{Include files}  \n\n// \u540c\u6837\uff0c\u524d\u51e0\u4e2ainclude\u6587\u4ef6\u5df2\u7ecf\u77e5\u9053\u4e86\uff0c\u6240\u4ee5\u6211\u4eec\u4e0d\u4f1a\u5bf9\u5b83\u4eec\u8fdb\u884c\u8bc4\u8bba\u3002\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/utilities.h> \n\n#include <deal.II/lac/affine_constraints.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\n#include <deal.II/grid/tria.h> \n#include <deal.II/grid/grid_generator.h> \n#include <deal.II/grid/grid_refinement.h> \n\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/vector_tools.h> \n#include <deal.II/numerics/data_out.h> \n#include <deal.II/numerics/error_estimator.h> \n\n// \u73b0\u5728\uff0c\u8fd9\u4e9b\u662f\u591a\u7ea7\u65b9\u6cd5\u6240\u9700\u7684\u5305\u62ec\u3002\u7b2c\u4e00\u4e2a\u58f0\u660e\u4e86\u5982\u4f55\u5904\u7406\u591a\u7f51\u683c\u65b9\u6cd5\u6bcf\u4e2a\u5c42\u6b21\u4e0a\u7684Dirichlet\u8fb9\u754c\u6761\u4ef6\u3002\u5bf9\u4e8e\u81ea\u7531\u5ea6\u7684\u5b9e\u9645\u63cf\u8ff0\uff0c\u6211\u4eec\u4e0d\u9700\u8981\u4efb\u4f55\u65b0\u7684\u5305\u542b\u6587\u4ef6\uff0c\u56e0\u4e3aDoFHandler\u5df2\u7ecf\u5b9e\u73b0\u4e86\u6240\u6709\u5fc5\u8981\u7684\u65b9\u6cd5\u3002\u6211\u4eec\u53ea\u9700\u8981\u5c06\u81ea\u7531\u5ea6\u5206\u914d\u7ed9\u66f4\u591a\u7684\u5c42\u6b21\u3002\n\n// \u5176\u4f59\u7684\u5305\u542b\u6587\u4ef6\u6d89\u53ca\u5230\u4f5c\u4e3a\u7ebf\u6027\u7b97\u5b50\uff08\u6c42\u89e3\u5668\u6216\u9884\u5904\u7406\u5668\uff09\u7684\u591a\u91cd\u7f51\u683c\u7684\u529b\u5b66\u95ee\u9898\u3002\n\n#include <deal.II/multigrid/mg_constrained_dofs.h> \n#include <deal.II/multigrid/multigrid.h> \n#include <deal.II/multigrid/mg_transfer.h> \n#include <deal.II/multigrid/mg_tools.h> \n#include <deal.II/multigrid/mg_coarse.h> \n#include <deal.II/multigrid/mg_smoother.h> \n#include <deal.II/multigrid/mg_matrix.h> \n\n// \u6211\u4eec\u5c06\u4f7f\u7528 MeshWorker::mesh_loop \u6765\u5bf9\u5355\u5143\u683c\u8fdb\u884c\u5faa\u73af\uff0c\u6240\u4ee5\u5728\u8fd9\u91cc\u5305\u62ec\u5b83\u3002\n\n#include <deal.II/meshworker/mesh_loop.h> \n\n// \u8fd9\u5c31\u662fC++\u3002\n\n#include <iostream> \n#include <fstream> \n\nusing namespace dealii; \n\nnamespace Step16 \n{ \n// @sect3{The Scratch and Copy objects}  \n\n// \u6211\u4eec\u4f7f\u7528 MeshWorker::mesh_loop() \u6765\u7ec4\u88c5\u6211\u4eec\u7684\u77e9\u9635\u3002\u4e3a\u6b64\uff0c\u6211\u4eec\u9700\u8981\u4e00\u4e2aScratchData\u5bf9\u8c61\u6765\u5b58\u50a8\u6bcf\u4e2a\u5355\u5143\u7684\u4e34\u65f6\u6570\u636e\uff08\u8fd9\u53ea\u662fFEValues\u5bf9\u8c61\uff09\u548c\u4e00\u4e2aCopyData\u5bf9\u8c61\uff0c\u5b83\u5c06\u5305\u542b\u6bcf\u4e2a\u5355\u5143\u88c5\u914d\u7684\u8f93\u51fa\u3002\u5173\u4e8escratch\u548ccopy\u5bf9\u8c61\u7684\u7528\u6cd5\u7684\u66f4\u591a\u7ec6\u8282\uff0c\u8bf7\u53c2\u89c1WorkStream\u547d\u540d\u7a7a\u95f4\u3002\n\n  template <int dim> \n  struct ScratchData \n  { \n    ScratchData(const Mapping<dim> &      mapping, \n                const FiniteElement<dim> &fe, \n                const unsigned int        quadrature_degree, \n                const UpdateFlags         update_flags) \n      : fe_values(mapping, fe, QGauss<dim>(quadrature_degree), update_flags) \n    {} \n\n    ScratchData(const ScratchData<dim> &scratch_data) \n      : fe_values(scratch_data.fe_values.get_mapping(), \n                  scratch_data.fe_values.get_fe(), \n                  scratch_data.fe_values.get_quadrature(), \n                  scratch_data.fe_values.get_update_flags()) \n    {} \n\n    FEValues<dim> fe_values; \n  }; \n\n  struct CopyData \n  { \n    unsigned int                         level; \n    FullMatrix<double>                   cell_matrix; \n    Vector<double>                       cell_rhs; \n    std::vector<types::global_dof_index> local_dof_indices; \n\n    template <class Iterator> \n    void reinit(const Iterator &cell, unsigned int dofs_per_cell) \n    { \n      cell_matrix.reinit(dofs_per_cell, dofs_per_cell); \n      cell_rhs.reinit(dofs_per_cell); \n\n      local_dof_indices.resize(dofs_per_cell); \n      cell->get_active_or_mg_dof_indices(local_dof_indices); \n      level = cell->level(); \n    } \n  }; \n// @sect3{The <code>LaplaceProblem</code> class template}  \n\n// \u8fd9\u4e2a\u4e3b\u7c7b\u4e0e  step-6  \u4e2d\u7684\u540c\u4e00\u7c7b\u76f8\u4f3c\u3002\u5c31\u6210\u5458\u51fd\u6570\u800c\u8a00\uff0c\u552f\u4e00\u589e\u52a0\u7684\u662f\u3002\n\n// --  <code>assemble_multigrid</code> \u7684\u51fd\u6570\uff0c\u8be5\u51fd\u6570\u7ec4\u88c5\u4e86\u5bf9\u5e94\u4e8e\u4e2d\u95f4\u5c42\u79bb\u6563\u8fd0\u7b97\u7b26\u7684\u77e9\u9635\u3002\n\n// -  <code>cell_worker</code> \u51fd\u6570\uff0c\u5b83\u5c06\u6211\u4eec\u7684PDE\u96c6\u5408\u5728\u4e00\u4e2a\u5355\u5143\u4e0a\u3002\n\n  template <int dim> \n  class LaplaceProblem \n  { \n  public: \n    LaplaceProblem(const unsigned int degree); \n    void run(); \n\n  private: \n    template <class Iterator> \n    void cell_worker(const Iterator &  cell, \n                     ScratchData<dim> &scratch_data, \n                     CopyData &        copy_data); \n\n    void setup_system(); \n    void assemble_system(); \n    void assemble_multigrid(); \n    void solve(); \n    void refine_grid(); \n    void output_results(const unsigned int cycle) 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\n    AffineConstraints<double> constraints; \n\n    Vector<double> solution; \n    Vector<double> system_rhs; \n\n    const unsigned int degree; \n\n// \u4ee5\u4e0b\u6210\u5458\u662f\u591a\u7f51\u683c\u65b9\u6cd5\u7684\u57fa\u672c\u6570\u636e\u7ed3\u6784\u3002\u524d\u56db\u4e2a\u8868\u793a\u7a00\u758f\u6a21\u5f0f\u548c\u591a\u7ea7\u5c42\u6b21\u7ed3\u6784\u4e2d\u5404\u4e2a\u5c42\u6b21\u7684\u77e9\u9635\uff0c\u975e\u5e38\u7c7b\u4f3c\u4e8e\u4e0a\u9762\u7684\u5168\u5c40\u7f51\u683c\u7684\u5bf9\u8c61\u3002\n\n// \u7136\u540e\uff0c\u6211\u4eec\u6709\u4e24\u4e2a\u65b0\u7684\u77e9\u9635\uff0c\u53ea\u9700\u8981\u5728\u81ea\u9002\u5e94\u7f51\u683c\u4e0a\u8fdb\u884c\u5c40\u90e8\u5e73\u6ed1\u7684\u591a\u7f51\u683c\u65b9\u6cd5\u3002\u5b83\u4eec\u5728\u7ec6\u5316\u533a\u57df\u7684\u5185\u90e8\u548c\u7ec6\u5316\u8fb9\u7f18\u4e4b\u95f4\u4f20\u9012\u6570\u636e\uff0c\u5728 @ref mg_paper \"\u591a\u7f51\u683c\u8bba\u6587 \"\u4e2d\u8be6\u7ec6\u4ecb\u7ecd\u8fc7\u3002\n\n// \u6700\u540e\u4e00\u4e2a\u5bf9\u8c61\u5b58\u50a8\u4e86\u6bcf\u4e2a\u5c42\u6b21\u4e0a\u7684\u8fb9\u754c\u6307\u6570\u4fe1\u606f\u548c\u4f4d\u4e8e\u4e24\u4e2a\u4e0d\u540c\u7ec6\u5316\u5c42\u6b21\u4e4b\u95f4\u7684\u7ec6\u5316\u8fb9\u7f18\u4e0a\u7684\u6307\u6570\u4fe1\u606f\u3002\u56e0\u6b64\uff0c\u5b83\u7684\u4f5c\u7528\u4e0eAffineConstraints\u76f8\u4f3c\uff0c\u4f46\u5728\u6bcf\u4e2a\u5c42\u6b21\u4e0a\u3002\n\n    MGLevelObject<SparsityPattern> mg_sparsity_patterns; \n    MGLevelObject<SparsityPattern> mg_interface_sparsity_patterns; \n\n    MGLevelObject<SparseMatrix<double>> mg_matrices; \n    MGLevelObject<SparseMatrix<double>> mg_interface_matrices; \n    MGConstrainedDoFs                   mg_constrained_dofs; \n  }; \n// @sect3{The <code>LaplaceProblem</code> class implementation}  \n\n// \u5173\u4e8e\u4e09\u89d2\u5f62\u7684\u6784\u9020\u51fd\u6570\u53ea\u6709\u4e00\u4e2a\u7b80\u77ed\u7684\u8bc4\u8bba\uff1a\u6309\u7167\u60ef\u4f8b\uff0cdeal.II\u4e2d\u6240\u6709\u81ea\u9002\u5e94\u7cbe\u5316\u7684\u4e09\u89d2\u5f62\u5728\u5355\u5143\u683c\u4e4b\u95f4\u7684\u9762\u7684\u53d8\u5316\u4e0d\u4f1a\u8d85\u8fc7\u4e00\u4e2a\u7ea7\u522b\u3002\u7136\u800c\uff0c\u5bf9\u4e8e\u6211\u4eec\u7684\u591a\u7f51\u683c\u7b97\u6cd5\uff0c\u6211\u4eec\u9700\u8981\u4e00\u4e2a\u66f4\u4e25\u683c\u7684\u4fdd\u8bc1\uff0c\u5373\u7f51\u683c\u5728\u8fde\u63a5\u4e24\u4e2a\u5355\u5143\u7684\u9876\u70b9\u4e0a\u7684\u53d8\u5316\u4e5f\u4e0d\u8d85\u8fc7\u7ec6\u5316\u7ea7\u522b\u3002\u6362\u53e5\u8bdd\u8bf4\uff0c\u6211\u4eec\u5fc5\u987b\u9632\u6b62\u51fa\u73b0\u4ee5\u4e0b\u60c5\u51b5\u3002\n\n//  @image html limit_level_difference_at_vertices.png \"\"  \n\n// \u8fd9\u53ef\u4ee5\u901a\u8fc7\u5411\u4e09\u89d2\u5316\u7c7b\u7684\u6784\u9020\u51fd\u6570\u4f20\u9012 Triangulation::limit_level_difference_at_vertices \u6807\u5fd7\u6765\u5b9e\u73b0\u3002\n\n  template <int dim> \n  LaplaceProblem<dim>::LaplaceProblem(const unsigned int degree) \n    : triangulation(Triangulation<dim>::limit_level_difference_at_vertices) \n    , fe(degree) \n    , dof_handler(triangulation) \n    , degree(degree) \n  {} \n\n//  @sect4{LaplaceProblem::setup_system}  \n\n// \u9664\u4e86\u53ea\u662f\u5728DoFHandler\u4e2d\u5206\u914d\u81ea\u7531\u5ea6\u4e4b\u5916\uff0c\u6211\u4eec\u5728\u6bcf\u4e00\u5c42\u90fd\u505a\u540c\u6837\u7684\u4e8b\u60c5\u3002\u7136\u540e\uff0c\u6211\u4eec\u6309\u7167\u4e4b\u524d\u7684\u7a0b\u5e8f\uff0c\u5728\u53f6\u5b50\u7f51\u683c\u4e0a\u8bbe\u7f6e\u7cfb\u7edf\u3002\n\n  template <int dim> \n  void LaplaceProblem<dim>::setup_system() \n  { \n    dof_handler.distribute_dofs(fe); \n    dof_handler.distribute_mg_dofs(); \n\n    std::cout << \"   Number of degrees of freedom: \" << dof_handler.n_dofs() \n              << \" (by level: \"; \n    for (unsigned int level = 0; level < triangulation.n_levels(); ++level) \n      std::cout << dof_handler.n_dofs(level) \n                << (level == triangulation.n_levels() - 1 ? \")\" : \", \"); \n    std::cout << std::endl; \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, constraints); \n\n    std::set<types::boundary_id> dirichlet_boundary_ids = {0}; \n    Functions::ZeroFunction<dim> homogeneous_dirichlet_bc; \n    const std::map<types::boundary_id, const Function<dim> *> \n      dirichlet_boundary_functions = { \n        {types::boundary_id(0), &homogeneous_dirichlet_bc}}; \n    VectorTools::interpolate_boundary_values(dof_handler, \n                                             dirichlet_boundary_functions, \n                                             constraints); \n    constraints.close(); \n\n    { \n      DynamicSparsityPattern dsp(dof_handler.n_dofs(), dof_handler.n_dofs()); \n      DoFTools::make_sparsity_pattern(dof_handler, dsp, constraints); \n      sparsity_pattern.copy_from(dsp); \n    } \n    system_matrix.reinit(sparsity_pattern); \n\n// \u591a\u7f51\u683c\u7ea6\u675f\u5fc5\u987b\u88ab\u521d\u59cb\u5316\u3002\u4ed6\u4eec\u9700\u8981\u77e5\u9053\u5728\u54ea\u91cc\u89c4\u5b9a\u4e86Dirichlet\u8fb9\u754c\u6761\u4ef6\u3002\n\n    mg_constrained_dofs.clear(); \n    mg_constrained_dofs.initialize(dof_handler); \n    mg_constrained_dofs.make_zero_boundary_constraints(dof_handler, \n                                                       dirichlet_boundary_ids); \n\n// \u73b0\u5728\u662f\u5173\u4e8e\u591a\u7f51\u683c\u6570\u636e\u7ed3\u6784\u7684\u4e8b\u60c5\u3002\u9996\u5148\uff0c\u6211\u4eec\u8c03\u6574\u591a\u7ea7\u5bf9\u8c61\u7684\u5927\u5c0f\uff0c\u4ee5\u5bb9\u7eb3\u6bcf\u4e00\u7ea7\u7684\u77e9\u9635\u548c\u7a00\u758f\u6a21\u5f0f\u3002\u7c97\u7565\u7684\u7ea7\u522b\u662f\u96f6\uff08\u73b0\u5728\u662f\u5f3a\u5236\u6027\u7684\uff0c\u4f46\u5728\u672a\u6765\u7684\u4fee\u8ba2\u4e2d\u53ef\u80fd\u4f1a\u6539\u53d8\uff09\u3002\u6ce8\u610f\uff0c\u8fd9\u4e9b\u51fd\u6570\u5728\u8fd9\u91cc\u91c7\u53d6\u7684\u662f\u4e00\u4e2a\u5b8c\u6574\u7684\u3001\u5305\u5bb9\u7684\u8303\u56f4\uff08\u800c\u4e0d\u662f\u4e00\u4e2a\u8d77\u59cb\u7d22\u5f15\u548c\u5927\u5c0f\uff09\uff0c\u6240\u4ee5\u6700\u7ec6\u7684\u7ea7\u522b\u662f <code>n_levels-1</code>  \u3002\u6211\u4eec\u9996\u5148\u8981\u8c03\u6574\u5bb9\u7eb3SparseMatrix\u7c7b\u7684\u5bb9\u5668\u7684\u5927\u5c0f\uff0c\u56e0\u4e3a\u5b83\u4eec\u5fc5\u987b\u5728\u8c03\u6574\u5927\u5c0f\u65f6\u91ca\u653e\u5b83\u4eec\u7684SparsityPattern\u624d\u80fd\u88ab\u9500\u6bc1\u3002\n\n    const unsigned int n_levels = triangulation.n_levels(); \n\n    mg_interface_matrices.resize(0, n_levels - 1); \n    mg_matrices.resize(0, n_levels - 1); \n    mg_sparsity_patterns.resize(0, n_levels - 1); \n    mg_interface_sparsity_patterns.resize(0, n_levels - 1); \n\n// \u73b0\u5728\uff0c\u6211\u4eec\u5fc5\u987b\u5728\u6bcf\u4e2a\u7ea7\u522b\u4e0a\u63d0\u4f9b\u4e00\u4e2a\u77e9\u9635\u3002\u4e3a\u6b64\uff0c\u6211\u4eec\u9996\u5148\u4f7f\u7528 MGTools::make_sparsity_pattern \u51fd\u6570\u5728\u6bcf\u4e2a\u5c42\u6b21\u4e0a\u751f\u6210\u4e00\u4e2a\u521d\u6b65\u7684\u538b\u7f29\u7a00\u758f\u6a21\u5f0f\uff08\u5173\u4e8e\u8fd9\u4e2a\u4e3b\u9898\u7684\u66f4\u591a\u4fe1\u606f\uff0c\u8bf7\u53c2\u89c1 @ref Sparsity \u6a21\u5757\uff09\uff0c\u7136\u540e\u5c06\u5176\u590d\u5236\u5230\u6211\u4eec\u771f\u6b63\u60f3\u8981\u7684\u90a3\u4e00\u4e2a\u3002\u4e0b\u4e00\u6b65\u662f\u7528\u62df\u5408\u7684\u7a00\u758f\u5ea6\u6a21\u5f0f\u521d\u59cb\u5316\u63a5\u53e3\u77e9\u9635\u3002\n\n// \u503c\u5f97\u6307\u51fa\u7684\u662f\uff0c\u754c\u9762\u77e9\u9635\u53ea\u5305\u542b\u4f4d\u4e8e\u8f83\u7c97\u548c\u8f83\u7ec6\u7684\u7f51\u683c\u4e4b\u95f4\u7684\u81ea\u7531\u5ea6\u7684\u6761\u76ee\u3002\u56e0\u6b64\uff0c\u5b83\u4eec\u751a\u81f3\u6bd4\u6211\u4eec\u7684\u591a\u7f51\u683c\u5c42\u6b21\u7ed3\u6784\u4e2d\u7684\u5404\u4e2a\u5c42\u6b21\u7684\u77e9\u9635\u8fd8\u8981\u7a00\u758f\u3002\u56e0\u6b64\uff0c\u6211\u4eec\u4f7f\u7528\u4e00\u4e2a\u4e13\u95e8\u4e3a\u6b64\u76ee\u7684\u800c\u5efa\u7acb\u7684\u51fd\u6570\u6765\u751f\u6210\u5b83\u3002\n\n    for (unsigned int level = 0; level < n_levels; ++level) \n      { \n        { \n          DynamicSparsityPattern dsp(dof_handler.n_dofs(level), \n                                     dof_handler.n_dofs(level)); \n          MGTools::make_sparsity_pattern(dof_handler, dsp, level); \n\n          mg_sparsity_patterns[level].copy_from(dsp); \n          mg_matrices[level].reinit(mg_sparsity_patterns[level]); \n        } \n        { \n          DynamicSparsityPattern dsp(dof_handler.n_dofs(level), \n                                     dof_handler.n_dofs(level)); \n          MGTools::make_interface_sparsity_pattern(dof_handler, \n                                                   mg_constrained_dofs, \n                                                   dsp, \n                                                   level); \n          mg_interface_sparsity_patterns[level].copy_from(dsp); \n          mg_interface_matrices[level].reinit( \n            mg_interface_sparsity_patterns[level]); \n        } \n      } \n  } \n// @sect4{LaplaceProblem::cell_worker}  \n\n// cell_worker\u51fd\u6570\u7528\u4e8e\u5728\u7ed9\u5b9a\u7684\u5355\u5143\u4e0a\u7ec4\u88c5\u77e9\u9635\u548c\u53f3\u624b\u8fb9\u3002\u8fd9\u4e2a\u51fd\u6570\u7528\u4e8e\u6d3b\u52a8\u5355\u5143\u751f\u6210system_matrix\uff0c\u5e76\u5728\u6bcf\u4e2a\u5c42\u6b21\u4e0a\u5efa\u7acb\u5c42\u6b21\u77e9\u9635\u3002\n\n// \u6ce8\u610f\uff0c\u5f53\u4eceassemble_multigrid()\u8c03\u7528\u65f6\uff0c\u6211\u4eec\u4e5f\u4f1a\u7ec4\u88c5\u4e00\u4e2a\u53f3\u624b\u8fb9\uff0c\u5c3d\u7ba1\u5b83\u6ca1\u6709\u88ab\u4f7f\u7528\u3002\n\n  template <int dim> \n  template <class Iterator> \n  void LaplaceProblem<dim>::cell_worker(const Iterator &  cell, \n                                        ScratchData<dim> &scratch_data, \n                                        CopyData &        copy_data) \n  { \n    FEValues<dim> &fe_values = scratch_data.fe_values; \n    fe_values.reinit(cell); \n\n    const unsigned int dofs_per_cell = fe_values.get_fe().n_dofs_per_cell(); \n    const unsigned int n_q_points    = fe_values.get_quadrature().size(); \n\n    copy_data.reinit(cell, dofs_per_cell); \n\n    const std::vector<double> &JxW = fe_values.get_JxW_values(); \n\n    for (unsigned int q = 0; q < n_q_points; ++q) \n      { \n        const double coefficient = \n          (fe_values.get_quadrature_points()[q][0] < 0.0) ? 1.0 : 0.1; \n\n        for (unsigned int i = 0; i < dofs_per_cell; ++i) \n          { \n            for (unsigned int j = 0; j < dofs_per_cell; ++j) \n              { \n                copy_data.cell_matrix(i, j) += \n                  coefficient * \n                  (fe_values.shape_grad(i, q) * fe_values.shape_grad(j, q)) * \n                  JxW[q]; \n              } \n            copy_data.cell_rhs(i) += 1.0 * fe_values.shape_value(i, q) * JxW[q]; \n          } \n      } \n  } \n\n//  @sect4{LaplaceProblem::assemble_system}  \n\n// \u4e0b\u9762\u7684\u51fd\u6570\u5c06\u7ebf\u6027\u7cfb\u7edf\u96c6\u5408\u5728\u7f51\u683c\u7684\u6d3b\u52a8\u5355\u5143\u4e0a\u3002\u4e3a\u6b64\uff0c\u6211\u4eec\u5411Mesh_loop()\u51fd\u6570\u4f20\u9012\u4e24\u4e2alambda\u51fd\u6570\u3002cell_worker\u51fd\u6570\u91cd\u5b9a\u5411\u5230\u540c\u540d\u7684\u7c7b\u6210\u5458\u51fd\u6570\uff0c\u800ccopyer\u662f\u8fd9\u4e2a\u51fd\u6570\u7279\u6709\u7684\uff0c\u5b83\u4f7f\u7528\u7ea6\u675f\u6761\u4ef6\u5c06\u672c\u5730\u77e9\u9635\u548c\u5411\u91cf\u590d\u5236\u5230\u76f8\u5e94\u7684\u5168\u5c40\u77e9\u9635\u3002\n\n  template <int dim> \n  void LaplaceProblem<dim>::assemble_system() \n  { \n    MappingQ1<dim> mapping; \n\n    auto cell_worker = \n      [&](const typename DoFHandler<dim>::active_cell_iterator &cell, \n          ScratchData<dim> &                                    scratch_data, \n          CopyData &                                            copy_data) { \n        this->cell_worker(cell, scratch_data, copy_data); \n      }; \n\n    auto copier = [&](const CopyData &cd) { \n      this->constraints.distribute_local_to_global(cd.cell_matrix, \n                                                   cd.cell_rhs, \n                                                   cd.local_dof_indices, \n                                                   system_matrix, \n                                                   system_rhs); \n    }; \n\n    const unsigned int n_gauss_points = degree + 1; \n\n    ScratchData<dim> scratch_data(mapping, \n                                  fe, \n                                  n_gauss_points, \n                                  update_values | update_gradients | \n                                    update_JxW_values | \n                                    update_quadrature_points); \n\n    MeshWorker::mesh_loop(dof_handler.begin_active(), \n                          dof_handler.end(), \n                          cell_worker, \n                          copier, \n                          scratch_data, \n                          CopyData(), \n                          MeshWorker::assemble_own_cells); \n  } \n// @sect4{LaplaceProblem::assemble_multigrid}  \n\n// \u4e0b\u4e00\u4e2a\u51fd\u6570\u662f\u5efa\u7acb\u77e9\u9635\uff0c\u5b9a\u4e49\u6bcf\u4e00\u5c42\u7f51\u683c\u4e0a\u7684\u591a\u7f51\u683c\u65b9\u6cd5\u3002\u96c6\u6210\u7684\u6838\u5fc3\u4e0e\u4e0a\u9762\u7684\u76f8\u540c\uff0c\u4f46\u662f\u4e0b\u9762\u7684\u5faa\u73af\u5c06\u904d\u5386\u6240\u6709\u5df2\u5b58\u5728\u7684\u5355\u5143\uff0c\u800c\u4e0d\u4ec5\u4ec5\u662f\u6d3b\u52a8\u7684\u5355\u5143\uff0c\u5e76\u4e14\u5fc5\u987b\u5c06\u7ed3\u679c\u8f93\u5165\u6b63\u786e\u7684\u5c42\u77e9\u9635\u3002\u5e78\u8fd0\u7684\u662f\uff0cMeshWorker\u5bf9\u6211\u4eec\u9690\u85cf\u4e86\u5927\u90e8\u5206\u7684\u5185\u5bb9\uff0c\u56e0\u6b64\u8fd9\u4e2a\u51fd\u6570\u548c\u4e4b\u524d\u7684\u51fd\u6570\u7684\u533a\u522b\u53ea\u5728\u4e8e\u6c47\u7f16\u5668\u7684\u8bbe\u7f6e\u548c\u5faa\u73af\u4e2d\u7684\u4e0d\u540c\u8fed\u4ee3\u5668\u3002\n\n// \u6211\u4eec\u4e3a\u6bcf\u4e2a\u5c42\u6b21\u751f\u6210\u4e00\u4e2aAffineConstraints\u5bf9\u8c61\uff0c\u5176\u4e2d\u5305\u542b\u8fb9\u754c\u548c\u754c\u9762\u9053\u592b\u4f5c\u4e3a\u7ea6\u675f\u6761\u76ee\u3002\u7136\u540e\uff0c\u76f8\u5e94\u7684\u5bf9\u8c61\u88ab\u7528\u6765\u751f\u6210\u5c42\u6b21\u77e9\u9635\u3002\n\n  template <int dim> \n  void LaplaceProblem<dim>::assemble_multigrid() \n  { \n    MappingQ1<dim>     mapping; \n    const unsigned int n_levels = triangulation.n_levels(); \n\n    std::vector<AffineConstraints<double>> boundary_constraints(n_levels); \n    for (unsigned int level = 0; level < n_levels; ++level) \n      { \n        IndexSet dofset; \n        DoFTools::extract_locally_relevant_level_dofs(dof_handler, \n                                                      level, \n                                                      dofset); \n        boundary_constraints[level].reinit(dofset); \n        boundary_constraints[level].add_lines( \n          mg_constrained_dofs.get_refinement_edge_indices(level)); \n        boundary_constraints[level].add_lines( \n          mg_constrained_dofs.get_boundary_indices(level)); \n        boundary_constraints[level].close(); \n      } \n\n    auto cell_worker = \n      [&](const typename DoFHandler<dim>::level_cell_iterator &cell, \n          ScratchData<dim> &                                   scratch_data, \n          CopyData &                                           copy_data) { \n        this->cell_worker(cell, scratch_data, copy_data); \n      }; \n\n    auto copier = [&](const CopyData &cd) { \n      boundary_constraints[cd.level].distribute_local_to_global( \n        cd.cell_matrix, cd.local_dof_indices, mg_matrices[cd.level]); \n\n      const unsigned int dofs_per_cell = cd.local_dof_indices.size(); \n\n// \u63a5\u53e3\u6761\u76ee\u5728\u586b\u5145mg_matrices[cd.level]\u65f6\u88ab\u4e0a\u9762\u7684boundary_constraints\u5bf9\u8c61\u6240\u5ffd\u7565\u3002\u76f8\u53cd\uff0c\u6211\u4eec\u624b\u52a8\u5c06\u8fd9\u4e9b\u6761\u76ee\u590d\u5236\u5230\u5f53\u524d\u7ea7\u522b\u7684\u754c\u9762\u77e9\u9635\u4e2d\u3002\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 (mg_constrained_dofs.is_interface_matrix_entry( \n                cd.level, cd.local_dof_indices[i], cd.local_dof_indices[j])) \n            { \n              mg_interface_matrices[cd.level].add(cd.local_dof_indices[i], \n                                                  cd.local_dof_indices[j], \n                                                  cd.cell_matrix(i, j)); \n            } \n    }; \n\n    const unsigned int n_gauss_points = degree + 1; \n\n    ScratchData<dim> scratch_data(mapping, \n                                  fe, \n                                  n_gauss_points, \n                                  update_values | update_gradients | \n                                    update_JxW_values | \n                                    update_quadrature_points); \n\n    MeshWorker::mesh_loop(dof_handler.begin_mg(), \n                          dof_handler.end_mg(), \n                          cell_worker, \n                          copier, \n                          scratch_data, \n                          CopyData(), \n                          MeshWorker::assemble_own_cells); \n  } \n\n//  @sect4{LaplaceProblem::solve}  \n\n// \u8fd9\u662f\u53e6\u5916\u4e00\u4e2a\u5728\u652f\u6301\u591a\u6805\u6c42\u89e3\u5668\uff08\u6216\u8005\u8bf4\uff0c\u4e8b\u5b9e\u4e0a\uff0c\u6211\u4eec\u4f7f\u7528\u591a\u6805\u65b9\u6cd5\u7684\u524d\u63d0\u6761\u4ef6\uff09\u65b9\u9762\u6709\u660e\u663e\u4e0d\u540c\u7684\u51fd\u6570\u3002\n\n// \u8ba9\u6211\u4eec\u4ece\u5efa\u7acb\u591a\u5c42\u6b21\u65b9\u6cd5\u7684\u4e24\u4e2a\u7ec4\u6210\u90e8\u5206\u5f00\u59cb\uff1a\u5c42\u6b21\u95f4\u7684\u8f6c\u79fb\u8fd0\u7b97\u5668\u548c\u6700\u7c97\u5c42\u6b21\u4e0a\u7684\u6c42\u89e3\u5668\u3002\u5728\u6709\u9650\u5143\u65b9\u6cd5\u4e2d\uff0c\u8f6c\u79fb\u7b97\u5b50\u6765\u81ea\u6240\u6d89\u53ca\u7684\u6709\u9650\u5143\u51fd\u6570\u7a7a\u95f4\uff0c\u901a\u5e38\u53ef\u4ee5\u7528\u72ec\u7acb\u4e8e\u6240\u8003\u8651\u95ee\u9898\u7684\u901a\u7528\u65b9\u5f0f\u8ba1\u7b97\u3002\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0c\u6211\u4eec\u53ef\u4ee5\u4f7f\u7528MGTransferPrebuilt\u7c7b\uff0c\u7ed9\u5b9a\u6700\u7ec8\u7ebf\u6027\u7cfb\u7edf\u7684\u7ea6\u675f\u548cMGConstrainedDoFs\u5bf9\u8c61\uff0c\u8be5\u5bf9\u8c61\u77e5\u9053\u6bcf\u4e2a\u5c42\u6b21\u7684\u8fb9\u754c\u6761\u4ef6\u548c\u4e0d\u540c\u7ec6\u5316\u5c42\u6b21\u4e4b\u95f4\u63a5\u53e3\u7684\u81ea\u7531\u5ea6\uff0c\u53ef\u4ee5\u4ece\u5177\u6709\u5c42\u6b21\u81ea\u7531\u5ea6\u7684DoFHandler\u5bf9\u8c61\u4e2d\u5efa\u7acb\u8fd9\u4e9b\u8f6c\u79fb\u64cd\u4f5c\u7684\u77e9\u9635\u3002\n\n// \u4e0b\u9762\u51e0\u884c\u7684\u7b2c\u4e8c\u90e8\u5206\u662f\u5173\u4e8e\u7c97\u7565\u7f51\u683c\u6c42\u89e3\u5668\u7684\u3002\u7531\u4e8e\u6211\u4eec\u7684\u7c97\u7f51\u683c\u786e\u5b9e\u975e\u5e38\u7c97\uff0c\u6211\u4eec\u51b3\u5b9a\u91c7\u7528\u76f4\u63a5\u6c42\u89e3\u5668\uff08\u6700\u7c97\u5c42\u6b21\u77e9\u9635\u7684Householder\u5206\u89e3\uff09\uff0c\u5373\u4f7f\u5176\u5b9e\u73b0\u4e0d\u662f\u7279\u522b\u590d\u6742\u3002\u5982\u679c\u6211\u4eec\u7684\u7c97\u7f51\u683c\u6bd4\u8fd9\u91cc\u76845\u4e2a\u5355\u5143\u591a\u5f97\u591a\uff0c\u90a3\u4e48\u8fd9\u91cc\u663e\u7136\u9700\u8981\u66f4\u5408\u9002\u7684\u4e1c\u897f\u3002\n\n  template <int dim> \n  void LaplaceProblem<dim>::solve() \n  { \n    MGTransferPrebuilt<Vector<double>> mg_transfer(mg_constrained_dofs); \n    mg_transfer.build(dof_handler); \n\n    FullMatrix<double> coarse_matrix; \n    coarse_matrix.copy_from(mg_matrices[0]); \n    MGCoarseGridHouseholder<double, Vector<double>> coarse_grid_solver; \n    coarse_grid_solver.initialize(coarse_matrix); \n\n// \u591a\u7ea7\u6c42\u89e3\u5668\u6216\u9884\u5904\u7406\u5668\u7684\u4e0b\u4e00\u4e2a\u7ec4\u6210\u90e8\u5206\u662f\uff0c\u6211\u4eec\u9700\u8981\u5728\u6bcf\u4e00\u7ea7\u4e0a\u8bbe\u7f6e\u5e73\u6ed1\u5668\u3002\u8fd9\u65b9\u9762\u5e38\u89c1\u7684\u9009\u62e9\u662f\u4f7f\u7528\u677e\u5f1b\u65b9\u6cd5\u7684\u5e94\u7528\uff08\u5982SOR\u3001Jacobi\u6216Richardson\u65b9\u6cd5\uff09\u6216\u6c42\u89e3\u5668\u65b9\u6cd5\u7684\u5c11\u91cf\u8fed\u4ee3\uff08\u5982CG\u6216GMRES\uff09\u3002 mg::SmootherRelaxation \u548cMGSmootherPrecondition\u7c7b\u4e3a\u8fd9\u4e24\u79cd\u5e73\u6ed1\u5668\u63d0\u4f9b\u652f\u6301\u3002\u8fd9\u91cc\uff0c\u6211\u4eec\u9009\u62e9\u5e94\u7528\u5355\u4e00\u7684SOR\u8fed\u4ee3\u3002\u4e3a\u6b64\uff0c\u6211\u4eec\u5b9a\u4e49\u4e00\u4e2a\u9002\u5f53\u7684\u522b\u540d\uff0c\u7136\u540e\u8bbe\u7f6e\u4e00\u4e2a\u5e73\u6ed1\u5668\u5bf9\u8c61\u3002\n\n// \u6700\u540e\u4e00\u6b65\u662f\u7528\u6211\u4eec\u7684\u6c34\u5e73\u77e9\u9635\u521d\u59cb\u5316\u5e73\u6ed1\u5668\u5bf9\u8c61\uff0c\u5e76\u8bbe\u7f6e\u4e00\u4e9b\u5e73\u6ed1\u53c2\u6570\u3002 <code>initialize()</code> \u51fd\u6570\u53ef\u4ee5\u6709\u9009\u62e9\u5730\u63a5\u53d7\u989d\u5916\u7684\u53c2\u6570\uff0c\u8fd9\u4e9b\u53c2\u6570\u5c06\u88ab\u4f20\u9012\u7ed9\u6bcf\u4e00\u7ea7\u7684\u5e73\u6ed1\u5668\u5bf9\u8c61\u3002\u5728\u76ee\u524dSOR\u5e73\u6ed1\u5668\u7684\u60c5\u51b5\u4e0b\uff0c\u8fd9\u53ef\u80fd\u5305\u62ec\u4e00\u4e2a\u677e\u5f1b\u53c2\u6570\u3002\u7136\u800c\uff0c\u6211\u4eec\u5728\u8fd9\u91cc\u5c06\u8fd9\u4e9b\u53c2\u6570\u4fdd\u7559\u4e3a\u9ed8\u8ba4\u503c\u3002\u5bf9 <code>set_steps()</code> \u7684\u8c03\u7528\u8868\u660e\u6211\u4eec\u5c06\u5728\u6bcf\u4e2a\u7ea7\u522b\u4e0a\u4f7f\u7528\u4e24\u4e2a\u524d\u5e73\u6ed1\u6b65\u9aa4\u548c\u4e24\u4e2a\u540e\u5e73\u6ed1\u6b65\u9aa4\uff1b\u4e3a\u4e86\u5728\u4e0d\u540c\u7ea7\u522b\u4e0a\u4f7f\u7528\u53ef\u53d8\u6570\u91cf\u7684\u5e73\u6ed1\u5668\u6b65\u9aa4\uff0c\u53ef\u4ee5\u5728\u5bf9 <code>mg_smoother</code> \u5bf9\u8c61\u7684\u6784\u9020\u51fd\u6570\u8c03\u7528\u4e2d\u8bbe\u7f6e\u66f4\u591a\u9009\u9879\u3002\n\n// \u6700\u540e\u4e00\u6b65\u7684\u7ed3\u679c\u662f\u6211\u4eec\u4f7f\u7528SOR\u65b9\u6cd5\u4f5c\u4e3a\u5e73\u6ed1\u5668\u7684\u4e8b\u5b9e\n\n// --\u8fd9\u4e0d\u662f\u5bf9\u79f0\u7684\n\n// \u4f46\u6211\u4eec\u5728\u4e0b\u9762\u4f7f\u7528\u5171\u8f6d\u68af\u5ea6\u8fed\u4ee3\uff08\u9700\u8981\u5bf9\u79f0\u7684\u9884\u5904\u7406\uff09\uff0c\u6211\u4eec\u9700\u8981\u8ba9\u591a\u7ea7\u9884\u5904\u7406\u786e\u4fdd\u6211\u4eec\u5f97\u5230\u4e00\u4e2a\u5bf9\u79f0\u7684\u7b97\u5b50\uff0c\u5373\u4f7f\u662f\u975e\u5bf9\u79f0\u7684\u5e73\u6ed1\u5668\u3002\n\n    using Smoother = PreconditionSOR<SparseMatrix<double>>; \n    mg::SmootherRelaxation<Smoother, Vector<double>> mg_smoother; \n    mg_smoother.initialize(mg_matrices); \n    mg_smoother.set_steps(2); \n    mg_smoother.set_symmetric(true); \n\n// \u4e0b\u4e00\u4e2a\u51c6\u5907\u6b65\u9aa4\u662f\uff0c\u6211\u4eec\u5fc5\u987b\u5c06\u6211\u4eec\u7684\u6c34\u5e73\u548c\u63a5\u53e3\u77e9\u9635\u5305\u88f9\u5728\u4e00\u4e2a\u5177\u6709\u6240\u9700\u4e58\u6cd5\u51fd\u6570\u7684\u5bf9\u8c61\u4e2d\u3002\u6211\u4eec\u5c06\u4e3a\u4ece\u7c97\u5230\u7ec6\u7684\u63a5\u53e3\u5bf9\u8c61\u521b\u5efa\u4e24\u4e2a\u5bf9\u8c61\uff0c\u53cd\u4e4b\u4ea6\u7136\uff1b\u591a\u7f51\u683c\u7b97\u6cd5\u5c06\u5728\u540e\u9762\u7684\u64cd\u4f5c\u4e2d\u4f7f\u7528\u8f6c\u7f6e\u8fd0\u7b97\u5668\uff0c\u5141\u8bb8\u6211\u4eec\u7528\u5df2\u7ecf\u5efa\u7acb\u7684\u77e9\u9635\u521d\u59cb\u5316\u8be5\u8fd0\u7b97\u5668\u7684\u4e0a\u4e0b\u7248\u672c\u3002\n\n    mg::Matrix<Vector<double>> mg_matrix(mg_matrices); \n    mg::Matrix<Vector<double>> mg_interface_up(mg_interface_matrices); \n    mg::Matrix<Vector<double>> mg_interface_down(mg_interface_matrices); \n\n// \u73b0\u5728\uff0c\u6211\u4eec\u51c6\u5907\u8bbe\u7f6eV\u578b\u5faa\u73af\u7b97\u5b50\u548c\u591a\u7ea7\u9884\u5904\u7406\u7a0b\u5e8f\u3002\n\n    Multigrid<Vector<double>> mg( \n      mg_matrix, coarse_grid_solver, mg_transfer, mg_smoother, mg_smoother); \n    mg.set_edge_matrices(mg_interface_down, mg_interface_up); \n\n    PreconditionMG<dim, Vector<double>, MGTransferPrebuilt<Vector<double>>> \n      preconditioner(dof_handler, mg, mg_transfer); \n\n// \u6709\u4e86\u8fd9\u4e00\u5207\uff0c\u6211\u4eec\u7ec8\u4e8e\u53ef\u4ee5\u7528\u901a\u5e38\u7684\u65b9\u6cd5\u6765\u89e3\u51b3\u8fd9\u4e2a\u7ebf\u6027\u7cfb\u7edf\u4e86\u3002\n\n    SolverControl            solver_control(1000, 1e-12); \n    SolverCG<Vector<double>> solver(solver_control); \n\n    solution = 0; \n\n    solver.solve(system_matrix, solution, system_rhs, preconditioner); \n    std::cout << \"   Number of CG iterations: \" << solver_control.last_step() \n              << \"\\n\" \n              << std::endl; \n    constraints.distribute(solution); \n  } \n\n//  @sect4{Postprocessing}  \n\n// \u4ee5\u4e0b\u4e24\u4e2a\u51fd\u6570\u5728\u8ba1\u7b97\u51fa\u89e3\u51b3\u65b9\u6848\u540e\u5bf9\u5176\u8fdb\u884c\u540e\u5904\u7406\u3002\u7279\u522b\u662f\uff0c\u7b2c\u4e00\u4e2a\u51fd\u6570\u5728\u6bcf\u4e2a\u5468\u671f\u5f00\u59cb\u65f6\u7ec6\u5316\u7f51\u683c\uff0c\u7b2c\u4e8c\u4e2a\u51fd\u6570\u5728\u6bcf\u4e2a\u5468\u671f\u7ed3\u675f\u65f6\u8f93\u51fa\u7ed3\u679c\u3002\u8fd9\u4e9b\u51fd\u6570\u4e0e  step-6  \u4e2d\u7684\u51fd\u6570\u51e0\u4e4e\u6ca1\u6709\u53d8\u5316\u3002\n\n  template <int dim> \n  void LaplaceProblem<dim>::refine_grid() \n  { \n    Vector<float> estimated_error_per_cell(triangulation.n_active_cells()); \n\n    KellyErrorEstimator<dim>::estimate( \n      dof_handler, \n      QGauss<dim - 1>(degree + 2), \n      std::map<types::boundary_id, const Function<dim> *>(), \n      solution, \n      estimated_error_per_cell); \n    GridRefinement::refine_and_coarsen_fixed_number(triangulation, \n                                                    estimated_error_per_cell, \n                                                    0.3, \n                                                    0.03); \n    triangulation.execute_coarsening_and_refinement(); \n  } \n\n  template <int dim> \n  void LaplaceProblem<dim>::output_results(const unsigned int cycle) const \n  { \n    DataOut<dim> data_out; \n\n    data_out.attach_dof_handler(dof_handler); \n    data_out.add_data_vector(solution, \"solution\"); \n    data_out.build_patches(); \n\n    std::ofstream output(\"solution-\" + std::to_string(cycle) + \".vtk\"); \n    data_out.write_vtk(output); \n  } \n// @sect4{LaplaceProblem::run}  \n\n// \u548c\u4e0a\u9762\u7684\u51e0\u4e2a\u51fd\u6570\u4e00\u6837\uff0c\u8fd9\u51e0\u4e4e\u662f\u5bf9  step-6  \u4e2d\u76f8\u5e94\u51fd\u6570\u7684\u590d\u5236\u3002\u552f\u4e00\u7684\u533a\u522b\u662f\u5bf9 <code>assemble_multigrid</code> \u7684\u8c03\u7528\uff0c\u5b83\u8d1f\u8d23\u5f62\u6210\u6211\u4eec\u5728\u591a\u7f51\u683c\u65b9\u6cd5\u4e2d\u9700\u8981\u7684\u6bcf\u4e00\u5c42\u7684\u77e9\u9635\u3002\n\n  template <int dim> \n  void LaplaceProblem<dim>::run() \n  { \n    for (unsigned int cycle = 0; cycle < 8; ++cycle) \n      { \n        std::cout << \"Cycle \" << cycle << std::endl; \n\n        if (cycle == 0) \n          { \n            GridGenerator::hyper_ball(triangulation); \n            triangulation.refine_global(2); \n          } \n        else \n          refine_grid(); \n\n        std::cout << \"   Number of active cells:       \" \n                  << triangulation.n_active_cells() << std::endl; \n\n        setup_system(); \n\n        assemble_system(); \n        assemble_multigrid(); \n\n        solve(); \n        output_results(cycle); \n      } \n  } \n} // namespace Step16 \n// @sect3{The main() function}  \n\n// \u8fd9\u53c8\u662f\u4e0e step-6 \u4e2d\u76f8\u540c\u7684\u51fd\u6570\u3002\n\nint main() \n{ \n  try \n    { \n      using namespace Step16; \n\n      LaplaceProblem<2> laplace_problem(1); \n      laplace_problem.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  return 0; \n} \n\n\n\n", "meta": {"hexsha": "00248e5ed01474eb72ca2f3419fcdd40d9fbec8e", "size": 21661, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-16/step-16.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-16/step-16.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-16/step-16.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": 35.9220563847, "max_line_length": 270, "alphanum_fraction": 0.6153917178, "num_tokens": 7179, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154240079185319, "lm_q2_score": 0.6926419958239132, "lm_q1q2_score": 0.49553271270503496}}
{"text": "// Copyright (C) 2011  Davis E. King (davis@dlib.net)\r\n// License: Boost Software License   See LICENSE.txt for the full license.\r\n\r\n\r\n#include <dlib/optimization.h>\r\n#include <sstream>\r\n#include <string>\r\n#include <cstdlib>\r\n#include <ctime>\r\n#include <vector>\r\n#include \"../rand.h\"\r\n\r\n#include \"tester.h\"\r\n\r\n\r\nnamespace  \r\n{\r\n\r\n    using namespace test;\r\n    using namespace dlib;\r\n    using namespace std;\r\n\r\n    logger dlog(\"test.max_cost_assignment\");\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\n    std::vector<std::vector<long> > permutations (\r\n        matrix<long,1,0> vals\r\n    )\r\n    {\r\n        if (vals.size() == 0)\r\n        {\r\n            return std::vector<std::vector<long> >();\r\n        }\r\n        else if (vals.size() == 1)\r\n        {\r\n            return std::vector<std::vector<long> >(1,std::vector<long>(1,vals(0)));\r\n        }\r\n\r\n\r\n        std::vector<std::vector<long> > temp;\r\n\r\n\r\n        for (long i = 0; i < vals.size(); ++i)\r\n        {\r\n            const std::vector<std::vector<long> >& res = permutations(remove_col(vals,i));       \r\n\r\n            for (unsigned long j = 0; j < res.size(); ++j)\r\n            {\r\n                temp.resize(temp.size()+1);\r\n                std::vector<long>& part = temp.back();\r\n                part.push_back(vals(i));\r\n                part.insert(part.end(), res[j].begin(), res[j].end());\r\n            }\r\n        }\r\n\r\n\r\n        return temp;\r\n    }\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\n    template <typename T>\r\n    std::vector<long> brute_force_max_cost_assignment (\r\n        matrix<T> cost\r\n    )\r\n    {\r\n        if (cost.size() == 0)\r\n            return std::vector<long>();\r\n\r\n        const std::vector<std::vector<long> >& perms = permutations(range(0,cost.nc()-1));\r\n\r\n        T best_cost = std::numeric_limits<T>::min();\r\n        unsigned long best_idx = 0;\r\n        for (unsigned long i = 0; i < perms.size(); ++i)\r\n        {\r\n            const T temp = assignment_cost(cost, perms[i]);\r\n            if (temp > best_cost)\r\n            {\r\n                best_idx = i;\r\n                best_cost = temp;\r\n            }\r\n        }\r\n\r\n        return perms[best_idx];\r\n    }\r\n\r\n// ----------------------------------------------------------------------------------------\r\n// ----------------------------------------------------------------------------------------\r\n// ----------------------------------------------------------------------------------------\r\n\r\n    class test_max_cost_assignment : public tester\r\n    {\r\n    public:\r\n        test_max_cost_assignment (\r\n        ) :\r\n            tester (\"test_max_cost_assignment\",\r\n                    \"Runs tests on the max_cost_assignment function.\")\r\n        {}\r\n\r\n        dlib::rand rnd;\r\n\r\n        template <typename T>\r\n        void test_hungarian()\r\n        {\r\n            long size = rnd.get_random_32bit_number()%7;\r\n            long range = rnd.get_random_32bit_number()%100;\r\n            matrix<T> cost = matrix_cast<T>(randm(size,size,rnd)*range) - range/2;\r\n\r\n            // use a uniform cost matrix sometimes\r\n            if ((rnd.get_random_32bit_number()%100) == 0)\r\n                cost = rnd.get_random_32bit_number()%100;\r\n\r\n            // negate the cost matrix every now and then\r\n            if ((rnd.get_random_32bit_number()%100) == 0)\r\n                cost = -cost;\r\n\r\n\r\n            std::vector<long> assign = brute_force_max_cost_assignment(cost);\r\n            T true_eval = assignment_cost(cost, assign);\r\n            assign = max_cost_assignment(cost);\r\n            DLIB_TEST(assignment_cost(cost,assign) == true_eval);\r\n            assign = max_cost_assignment(matrix_cast<signed char>(cost));\r\n            DLIB_TEST(assignment_cost(cost,assign) == true_eval);\r\n\r\n\r\n            cost = matrix_cast<T>(randm(size,size,rnd)*range);\r\n            assign = brute_force_max_cost_assignment(cost);\r\n            true_eval = assignment_cost(cost, assign);\r\n            assign = max_cost_assignment(cost);\r\n            DLIB_TEST(assignment_cost(cost,assign) == true_eval);\r\n            assign = max_cost_assignment(matrix_cast<unsigned char>(cost));\r\n            DLIB_TEST(assignment_cost(cost,assign) == true_eval);\r\n            assign = max_cost_assignment(matrix_cast<typename unsigned_type<T>::type>(cost));\r\n            DLIB_TEST(assignment_cost(cost,assign) == true_eval);\r\n        }\r\n\r\n        void perform_test (\r\n        )\r\n        {\r\n            for (long i = 0; i < 1000; ++i)\r\n            {\r\n                if ((i%100) == 0)\r\n                    print_spinner();\r\n\r\n                test_hungarian<short>();\r\n                test_hungarian<int>();\r\n                test_hungarian<long>();\r\n                test_hungarian<int64>();\r\n            }\r\n        }\r\n    } a;\r\n\r\n}\r\n\r\n\r\n\r\n", "meta": {"hexsha": "4bed9f6d2cb20e7d3777d93bade5fa494597916c", "size": 4840, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dlib/test/max_cost_assignment.cpp", "max_stars_repo_name": "ckproc/dlib-19.7", "max_stars_repo_head_hexsha": "0ca40f5e85de2436e557bee9a805d3987d2d9507", "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": "dlib/test/max_cost_assignment.cpp", "max_issues_repo_name": "ckproc/dlib-19.7", "max_issues_repo_head_hexsha": "0ca40f5e85de2436e557bee9a805d3987d2d9507", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2018-02-27T15:44:25.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-28T01:26:03.000Z", "max_forks_repo_path": "dlib/test/max_cost_assignment.cpp", "max_forks_repo_name": "ckproc/dlib-19.7", "max_forks_repo_head_hexsha": "0ca40f5e85de2436e557bee9a805d3987d2d9507", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6329113924, "max_line_length": 98, "alphanum_fraction": 0.4681818182, "num_tokens": 964, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154240079185319, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.49553269908782205}}
{"text": "#include \"gtest/gtest.h\"\n#include <Eigen/Core>\n#include \"Face2D.h\"\n#include <algorithm>\n\nnamespace {\n  using namespace Geotree;\n\n  class Loop2DTest : public ::testing::Test {\n  protected:\n  };\n\n  TEST_F(Loop2DTest, Basic)\n  {\n    Loop2D loop;\n\n    Point2D p0 = {0,0};\n    Point2D p1 = {1,0};\n    Point2D p2 = {0,1};\n\n    loop.points.push_back(p0);\n    loop.points.push_back(p1);\n    loop.points.push_back(p2);\n\n    Point2D p3 = {0.5,0.5};\n\n    EXPECT_TRUE(loop.contains(p3));\n  }\n}\n", "meta": {"hexsha": "d0c76c806e0f39d3ff6f5c7264bde148ed23e85f", "size": 482, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/loop2d.cc", "max_stars_repo_name": "untaugh/geotree", "max_stars_repo_head_hexsha": "4600a1cb4115094ed5c4c1500c6221a458e68be8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-07-27T00:58:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-20T22:26:10.000Z", "max_issues_repo_path": "test/loop2d.cc", "max_issues_repo_name": "untaugh/geotree", "max_issues_repo_head_hexsha": "4600a1cb4115094ed5c4c1500c6221a458e68be8", "max_issues_repo_licenses": ["MIT"], "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/loop2d.cc", "max_forks_repo_name": "untaugh/geotree", "max_forks_repo_head_hexsha": "4600a1cb4115094ed5c4c1500c6221a458e68be8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.0666666667, "max_line_length": 45, "alphanum_fraction": 0.622406639, "num_tokens": 155, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6926419958239132, "lm_q2_score": 0.7154239836484143, "lm_q1q2_score": 0.4955326958945323}}
{"text": "#include <stan/math/prim/mat.hpp>\n#include <gtest/gtest.h>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/math/distributions.hpp>\n#include <limits>\n#include <vector>\n\nusing Eigen::Dynamic;\nusing Eigen::Matrix;\nusing std::vector;\n\nTEST(ProbDistributionsMultiNormal, NotVectorized) {\n  Matrix<double, Dynamic, 1> y(3, 1);\n  y << 2.0, -2.0, 11.0;\n  Matrix<double, Dynamic, 1> mu(3, 1);\n  mu << 1.0, -1.0, 3.0;\n  Matrix<double, Dynamic, Dynamic> Sigma(3, 3);\n  Sigma << 9.0, -3.0, 0.0, -3.0, 4.0, 0.0, 0.0, 0.0, 5.0;\n  EXPECT_FLOAT_EQ(-11.73908, stan::math::multi_normal_log(y, mu, Sigma));\n}\n\nTEST(ProbDistributionsMultiNormal, Vectorized) {\n  vector<Matrix<double, Dynamic, 1> > vec_y(2);\n  vector<Matrix<double, 1, Dynamic> > vec_y_t(2);\n  Matrix<double, Dynamic, 1> y(3);\n  Matrix<double, 1, Dynamic> y_t(3);\n  y << 2.0, -2.0, 11.0;\n  vec_y[0] = y;\n  vec_y_t[0] = y;\n  y << 4.0, -2.0, 1.0;\n  vec_y[1] = y;\n  vec_y_t[1] = y;\n  y_t = y;\n\n  vector<Matrix<double, Dynamic, 1> > vec_mu(2);\n  vector<Matrix<double, 1, Dynamic> > vec_mu_t(2);\n  Matrix<double, Dynamic, 1> mu(3);\n  Matrix<double, 1, Dynamic> mu_t(3);\n  mu << 1.0, -1.0, 3.0;\n  vec_mu[0] = mu;\n  vec_mu_t[0] = mu;\n  mu << 2.0, -1.0, 4.0;\n  vec_mu[1] = mu;\n  vec_mu_t[1] = mu;\n  mu_t = mu;\n\n  Matrix<double, Dynamic, Dynamic> Sigma(3, 3);\n  Sigma << 10.0, -3.0, 0.0, -3.0, 5.0, 0.0, 0.0, 0.0, 5.0;\n\n  // y and mu vectorized\n  EXPECT_FLOAT_EQ(-11.928077 - 6.5378327,\n                  stan::math::multi_normal_log(vec_y, vec_mu, Sigma));\n  EXPECT_FLOAT_EQ(-11.928077 - 6.5378327,\n                  stan::math::multi_normal_log(vec_y_t, vec_mu, Sigma));\n  EXPECT_FLOAT_EQ(-11.928077 - 6.5378327,\n                  stan::math::multi_normal_log(vec_y, vec_mu_t, Sigma));\n  EXPECT_FLOAT_EQ(-11.928077 - 6.5378327,\n                  stan::math::multi_normal_log(vec_y_t, vec_mu_t, Sigma));\n\n  // y vectorized\n  EXPECT_FLOAT_EQ(-10.44027 - 6.537833,\n                  stan::math::multi_normal_log(vec_y, mu, Sigma));\n  EXPECT_FLOAT_EQ(-10.44027 - 6.537833,\n                  stan::math::multi_normal_log(vec_y_t, mu, Sigma));\n  EXPECT_FLOAT_EQ(-10.44027 - 6.537833,\n                  stan::math::multi_normal_log(vec_y, mu_t, Sigma));\n  EXPECT_FLOAT_EQ(-10.44027 - 6.537833,\n                  stan::math::multi_normal_log(vec_y_t, mu_t, Sigma));\n\n  // mu vectorized\n  EXPECT_FLOAT_EQ(-6.26954 - 6.537833,\n                  stan::math::multi_normal_log(y, vec_mu, Sigma));\n  EXPECT_FLOAT_EQ(-6.26954 - 6.537833,\n                  stan::math::multi_normal_log(y_t, vec_mu, Sigma));\n  EXPECT_FLOAT_EQ(-6.26954 - 6.537833,\n                  stan::math::multi_normal_log(y, vec_mu_t, Sigma));\n  EXPECT_FLOAT_EQ(-6.26954 - 6.537833,\n                  stan::math::multi_normal_log(y_t, vec_mu_t, Sigma));\n}\nTEST(ProbDistributionsMultiNormal, Sigma) {\n  Matrix<double, Dynamic, 1> y(2, 1);\n  y << 2.0, -2.0;\n  Matrix<double, Dynamic, 1> mu(2, 1);\n  mu << 1.0, -1.0;\n  Matrix<double, Dynamic, Dynamic> Sigma(2, 2);\n  Sigma << 9.0, -3.0, -3.0, 4.0;\n  EXPECT_NO_THROW(stan::math::multi_normal_log(y, mu, Sigma));\n\n  // non-symmetric\n  Sigma(0, 1) = -2.5;\n  EXPECT_THROW(stan::math::multi_normal_log(y, mu, Sigma), std::domain_error);\n}\nTEST(ProbDistributionsMultiNormal, Mu) {\n  Matrix<double, Dynamic, 1> y(3, 1);\n  y << 2.0, -2.0, 11.0;\n  Matrix<double, Dynamic, 1> mu(3, 1);\n  mu << 1.0, -1.0, 3.0;\n  Matrix<double, Dynamic, Dynamic> Sigma(3, 3);\n  Sigma << 9.0, -3.0, 0.0, -3.0, 4.0, 0.0, 0.0, 0.0, 5.0;\n  EXPECT_NO_THROW(stan::math::multi_normal_log(y, mu, Sigma));\n\n  mu(0) = std::numeric_limits<double>::infinity();\n  EXPECT_THROW(stan::math::multi_normal_log(y, mu, Sigma), std::domain_error);\n  mu(0) = -std::numeric_limits<double>::infinity();\n  EXPECT_THROW(stan::math::multi_normal_log(y, mu, Sigma), std::domain_error);\n  mu(0) = std::numeric_limits<double>::quiet_NaN();\n  EXPECT_THROW(stan::math::multi_normal_log(y, mu, Sigma), std::domain_error);\n}\nTEST(ProbDistributionsMultiNormal, MultiNormalOneRow) {\n  Matrix<double, 1, Dynamic> y(1, 3);\n  y << 2.0, -2.0, 11.0;\n  Matrix<double, Dynamic, 1> mu(3, 1);\n  mu << 1.0, -1.0, 3.0;\n  Matrix<double, Dynamic, Dynamic> Sigma(3, 3);\n  Sigma << 9.0, -3.0, 0.0, -3.0, 4.0, 0.0, 0.0, 0.0, 5.0;\n  EXPECT_FLOAT_EQ(-11.73908, stan::math::multi_normal_log(y, mu, Sigma));\n}\n\nTEST(ProbDistributionsMultiNormal, SigmaMultiRow) {\n  Matrix<double, 1, Dynamic> y(1, 2);\n  y << 2.0, -2.0;\n  Matrix<double, Dynamic, 1> mu(2, 1);\n  mu << 1.0, -1.0;\n  Matrix<double, Dynamic, Dynamic> Sigma(2, 2);\n  Sigma << 9.0, -3.0, -3.0, 4.0;\n  EXPECT_NO_THROW(stan::math::multi_normal_log(y, mu, Sigma));\n\n  // non-symmetric\n  Sigma(0, 1) = -2.5;\n  EXPECT_THROW(stan::math::multi_normal_log(y, mu, Sigma), std::domain_error);\n  Matrix<double, Dynamic, 1> z(2, 1);\n\n  // wrong dimensions\n  z << 2.0, -2.0;\n  EXPECT_THROW(stan::math::multi_normal_log(z, mu, Sigma), std::domain_error);\n}\nTEST(ProbDistributionsMultiNormal, MuMultiRow) {\n  Matrix<double, 1, Dynamic> y(1, 3);\n  y << 2.0, -2.0, 11.0;\n  Matrix<double, Dynamic, 1> mu(3, 1);\n  mu << 1.0, -1.0, 3.0;\n  Matrix<double, Dynamic, Dynamic> Sigma(3, 3);\n  Sigma << 9.0, -3.0, 0.0, -3.0, 4.0, 0.0, 0.0, 0.0, 5.0;\n  EXPECT_NO_THROW(stan::math::multi_normal_log(y, mu, Sigma));\n\n  mu(0) = std::numeric_limits<double>::infinity();\n  EXPECT_THROW(stan::math::multi_normal_log(y, mu, Sigma), std::domain_error);\n  mu(0) = -std::numeric_limits<double>::infinity();\n  EXPECT_THROW(stan::math::multi_normal_log(y, mu, Sigma), std::domain_error);\n  mu(0) = std::numeric_limits<double>::quiet_NaN();\n  EXPECT_THROW(stan::math::multi_normal_log(y, mu, Sigma), std::domain_error);\n}\nTEST(ProbDistributionsMultiNormal, SizeMismatch) {\n  Matrix<double, 1, Dynamic> y(1, 3);\n  y << 2.0, -2.0, 11.0;\n  Matrix<double, Dynamic, 1> mu(2, 1);\n  mu << 1.0, -1.0;\n  Matrix<double, Dynamic, Dynamic> Sigma(2, 3);\n  Sigma << 9.0, -3.0, 0.0, -3.0, 4.0, 0.0;\n  EXPECT_THROW(stan::math::multi_normal_log(y, mu, Sigma),\n               std::invalid_argument);\n}\n\nTEST(ProbDistributionsMultiNormal, error_check) {\n  boost::random::mt19937 rng;\n  Matrix<double, Dynamic, 1> mu(3, 1);\n  mu << 2.0, -2.0, 11.0;\n\n  Matrix<double, Dynamic, Dynamic> sigma(3, 3);\n  sigma << 9.0, -3.0, 0.0, -3.0, 4.0, 1.0, 0.0, 1.0, 3.0;\n  EXPECT_NO_THROW(stan::math::multi_normal_rng(mu, sigma, rng));\n\n  mu << stan::math::positive_infinity(), -2.0, 11.0;\n  EXPECT_THROW(stan::math::multi_normal_rng(mu, sigma, rng), std::domain_error);\n\n  mu << 2.0, -2.0, 11.0;\n  sigma << 9.0, -3.0, 0.0, 3.0, 4.0, 0.0, -2.0, 1.0, 3.0;\n  EXPECT_THROW(stan::math::multi_normal_rng(mu, sigma, rng), std::domain_error);\n}\n\nTEST(ProbDistributionsMultiNormal, marginalOneChiSquareGoodnessFitTest) {\n  boost::random::mt19937 rng;\n  Matrix<double, Dynamic, Dynamic> sigma(3, 3);\n  sigma << 9.0, -3.0, 0.0, -3.0, 4.0, 1.0, 0.0, 1.0, 3.0;\n  Matrix<double, Dynamic, 1> mu(3, 1);\n  mu << 2.0, -2.0, 11.0;\n  int N = 10000;\n  int K = boost::math::round(2 * std::pow(N, 0.4));\n  boost::math::normal_distribution<> dist(2.0, 3.0);\n  boost::math::chi_squared mydist(K - 1);\n\n  double loc[K - 1];\n  for (int i = 1; i < K; i++)\n    loc[i - 1] = quantile(dist, i * std::pow(K, -1.0));\n\n  int count = 0;\n  int bin[K];\n  double expect[K];\n  for (int i = 0; i < K; i++) {\n    bin[i] = 0;\n    expect[i] = N / K;\n  }\n  Eigen::VectorXd a(mu.rows());\n  while (count < N) {\n    a = stan::math::multi_normal_rng(mu, sigma, rng);\n    int i = 0;\n    while (i < K - 1 && a(0) > loc[i])\n      ++i;\n    ++bin[i];\n    count++;\n  }\n\n  double chi = 0;\n  for (int j = 0; j < K; j++)\n    chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) / expect[j]);\n\n  EXPECT_TRUE(chi < quantile(complement(mydist, 1e-6)));\n}\n\nTEST(ProbDistributionsMultiNormal, marginalTwoChiSquareGoodnessFitTest) {\n  boost::random::mt19937 rng;\n  Matrix<double, Dynamic, Dynamic> sigma(3, 3);\n  sigma << 9.0, -3.0, 0.0, -3.0, 4.0, 1.0, 0.0, 1.0, 3.0;\n  Matrix<double, Dynamic, 1> mu(3, 1);\n  mu << 2.0, -2.0, 11.0;\n  int N = 10000;\n  int K = boost::math::round(2 * std::pow(N, 0.4));\n  boost::math::normal_distribution<> dist(-2.0, 2.0);\n  boost::math::chi_squared mydist(K - 1);\n\n  double loc[K - 1];\n  for (int i = 1; i < K; i++)\n    loc[i - 1] = quantile(dist, i * std::pow(K, -1.0));\n\n  int count = 0;\n  int bin[K];\n  double expect[K];\n  for (int i = 0; i < K; i++) {\n    bin[i] = 0;\n    expect[i] = N / K;\n  }\n  Eigen::VectorXd a(mu.rows());\n  while (count < N) {\n    a = stan::math::multi_normal_rng(mu, sigma, rng);\n    int i = 0;\n    while (i < K - 1 && a(1) > loc[i])\n      ++i;\n    ++bin[i];\n    count++;\n  }\n\n  double chi = 0;\n  for (int j = 0; j < K; j++)\n    chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) / expect[j]);\n\n  EXPECT_TRUE(chi < quantile(complement(mydist, 1e-6)));\n}\n\nTEST(ProbDistributionsMultiNormal, marginalThreeChiSquareGoodnessFitTest) {\n  boost::random::mt19937 rng;\n  Matrix<double, Dynamic, Dynamic> sigma(3, 3);\n  sigma << 9.0, -3.0, 0.0, -3.0, 4.0, 1.0, 0.0, 1.0, 16.0;\n  Matrix<double, Dynamic, 1> mu(3, 1);\n  mu << 2.0, -2.0, 11.0;\n  int N = 10000;\n  int K = boost::math::round(2 * std::pow(N, 0.4));\n  boost::math::normal_distribution<> dist(11.0, 4.0);\n  boost::math::chi_squared mydist(K - 1);\n\n  double loc[K - 1];\n  for (int i = 1; i < K; i++)\n    loc[i - 1] = quantile(dist, i * std::pow(K, -1.0));\n\n  int count = 0;\n  int bin[K];\n  double expect[K];\n  for (int i = 0; i < K; i++) {\n    bin[i] = 0;\n    expect[i] = N / K;\n  }\n  Eigen::VectorXd a(mu.rows());\n  while (count < N) {\n    a = stan::math::multi_normal_rng(mu, sigma, rng);\n    int i = 0;\n    while (i < K - 1 && a(2) > loc[i])\n      ++i;\n    ++bin[i];\n    count++;\n  }\n\n  double chi = 0;\n  for (int j = 0; j < K; j++)\n    chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) / expect[j]);\n\n  EXPECT_TRUE(chi < quantile(complement(mydist, 1e-6)));\n}\n\nTEST(multiNormalRng, nonPosDefErrorTest) {\n  using stan::math::multi_normal_rng;\n  Eigen::MatrixXd S(2, 2);\n  S << 0, 1, 1, 0;  // not pos definite\n  Eigen::VectorXd mu(2);\n  mu << 1, 2;\n  boost::random::mt19937 rng;\n  EXPECT_THROW(multi_normal_rng(mu, S, rng), std::domain_error);\n}\n", "meta": {"hexsha": "73348a6aff4fa2c0222b318776f9d87772c761da", "size": 10054, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/prim/mat/prob/multi_normal_test.cpp", "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": "test/unit/math/prim/mat/prob/multi_normal_test.cpp", "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": "test/unit/math/prim/mat/prob/multi_normal_test.cpp", "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": 32.7491856678, "max_line_length": 80, "alphanum_fraction": 0.6019494728, "num_tokens": 3896, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4955122000936246}}
{"text": "/// \\file\n/// Maintainer: Felice Serena\n///\n///\n\n#include \"statistical_outlier_detection.h\"\n#include \"uniform_grid.h\"\n#include <set>\n\n#include <boost/test/unit_test.hpp>\n\nnamespace utf = boost::unit_test;\n\nusing namespace Eigen;\nusing namespace MouseTrack;\n\nBOOST_AUTO_TEST_CASE(outlier_2d) {\n  typedef UniformGrid2d UG;\n  UG::PointList all(2, 6);\n  all.col(0) = Vector2d(0.0, 0.0);\n  all.col(1) = Vector2d(2.0, 2.0);\n  all.col(2) = Vector2d(0.1, 0.0);\n  all.col(3) = Vector2d(-0.1, 0.0);\n  all.col(4) = Vector2d(0.0, 0.1);\n  all.col(5) = Vector2d(0.0, -0.1);\n\n  std::multiset<PointIndex> expected;\n  expected.insert(1);\n\n  UG oracle(10.0, 0.05);\n  oracle.compute(all);\n\n  std::vector<PointIndex> result =\n      statisticalOutlierDetection<UG::PointList, UG::Precision>(all, &oracle,\n                                                                2.0, 10);\n\n  std::multiset<PointIndex> received(result.begin(), result.end());\n\n  BOOST_CHECK_MESSAGE(\n      expected.size() == received.size(),\n      \"Expected and received sets have different cardinalities.\");\n  BOOST_CHECK_MESSAGE(\n      expected == received,\n      \"Expected and received set do not contain same elements.\");\n}\n", "meta": {"hexsha": "eb0b2645fab165b700fb66bfc48840dba4944ef3", "size": 1179, "ext": "cc", "lang": "C++", "max_stars_repo_path": "lib/spatial/statistical_outlier_detection.test.cc", "max_stars_repo_name": "itko/scanbox", "max_stars_repo_head_hexsha": "9a00c11eafb4cc2faa69bfcc76bdf0d8e295dcf3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-09T09:30:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-09T09:30:23.000Z", "max_issues_repo_path": "lib/spatial/statistical_outlier_detection.test.cc", "max_issues_repo_name": "itko/scanbox", "max_issues_repo_head_hexsha": "9a00c11eafb4cc2faa69bfcc76bdf0d8e295dcf3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 23.0, "max_issues_repo_issues_event_min_datetime": "2018-03-19T20:54:52.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-16T12:36:59.000Z", "max_forks_repo_path": "lib/spatial/statistical_outlier_detection.test.cc", "max_forks_repo_name": "itko/scanbox", "max_forks_repo_head_hexsha": "9a00c11eafb4cc2faa69bfcc76bdf0d8e295dcf3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-03-14T20:00:43.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-14T20:00:43.000Z", "avg_line_length": 25.6304347826, "max_line_length": 77, "alphanum_fraction": 0.6403731976, "num_tokens": 347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788995148792, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4955121888986788}}
{"text": "#include <boost/bind.hpp>\n\n#include <ql/time/date.hpp>\n#include <ql/time/daycounter.hpp>\n#include <ql/pricingengines/blackformula.hpp>\n#include <ql/math/solvers1d/brent.hpp>\n#include <ql/math/distributions/normaldistribution.hpp>\n#include <ql/math/integrals/segmentintegral.hpp>\n\n#include <calibrator/models/shortrate/twofactormodels/generalg2.hpp>\n\nnamespace HJCALIBRATOR\n{\n\tGeneralizedG2::GeneralizedG2( boost::shared_ptr<Gaussian2FactorDynamics> dynamics,\n\t\t\t\t\t\t\t\t  Real integralSignificance,\n\t\t\t\t\t\t\t\t  boost::shared_ptr<Integrator> integrator )\n\t\t: TwoFactorModel( 5 )\n\t\t, AffineModel()\n\t\t, TermStructureConsistentModel( dynamics->termStructure() )\n\t\t, a_( arguments_[0] ), sigma_( arguments_[1] )\n\t\t, b_( arguments_[2] ), eta_( arguments_[3] )\n\t\t, rho_( arguments_[4] )\n\t\t, integralSignificance_( integralSignificance )\n\t\t, integrator_( integrator )\n\t\t, dynamics_( dynamics )\n\t{\n\t\ta_ = dynamics->a(0);\n\t\tb_ = dynamics->a(1);\n\t\tsigma_ = dynamics->sigma(0);\n\t\teta_ = dynamics->sigma(1);\n\t\trho_ = dynamics->rho( 0, 1 );\n\n\t\tgenerateArguments();\n\n\t\tregisterWith( dynamics->termStructure() );\n\t}\n\n\tvoid GeneralizedG2::generateArguments() \n\t{\n\t\tdynamics_->a( a_, 0 );\n\t\tdynamics_->sigma( sigma_, 0 );\n\t\tdynamics_->a( b_, 1 );\n\t\tdynamics_->sigma( eta_, 1 );\n\t\tdynamics_->rho( rho_, 1, 0 );\n\t}\n\n\tReal GeneralizedG2::A( Time t, Time T ) const\n\t{\n\t\treturn dynamics_->A( t, T );\n\t}\n\n\tReal GeneralizedG2::discountBond( Time now,\n\t\t\t\t\t\t\t\t\t  Time maturity,\n\t\t\t\t\t\t\t\t\t  Array factors ) const\n\t{\n\t\tReal x = factors[0];\n\t\tReal y = factors[1];\n\n\t\tReal Bx = dynamics_->B( 0, now, maturity );\n\t\tReal By = dynamics_->B( 1, now, maturity );\n\n\t\treturn A( now, maturity ) * exp( - Bx * x - By * y );\n\t}\n\n\n\tReal GeneralizedG2::discountBondOption( Option::Type type,\n\t\t\t\t\t\t\t\t\t\t\tReal strike,\n\t\t\t\t\t\t\t\t\t\t\tTime maturity,\n\t\t\t\t\t\t\t\t\t\t\tTime bondMaturity ) const\n\t{\n\t\tauto dynamics = dynamics_;\n\n\t\tReal Bx = dynamics->B( 0, maturity, bondMaturity );\n\t\tReal By = dynamics->B( 1, maturity, bondMaturity );\n\t\tReal rho = dynamics->rho( 0, 1 )(0.0);\n\n\t\tReal Vpratio = 0;\n\n\t\tauto integrand00 = [maturity, dynamics]( Time u )\n\t\t{\n\t\t\tReal sigma = dynamics->sigma( 0 )(u);\n\t\t\tReal E = dynamics->E( 0, u, maturity );\n\t\t\t\n\t\t\treturn sigma * sigma / E / E;\n\t\t};\n\n\t\tVpratio += Bx * By * integrator_->operator()( integrand00, 0, maturity );\n\n\t\tauto integrand11 = [maturity, dynamics]( Time u )\n\t\t{\n\t\t\tReal sigma = dynamics->sigma( 1 )(u);\n\t\t\tReal E = dynamics->E( 1, u, maturity );\n\n\t\t\treturn sigma * sigma / E / E;\n\t\t};\n\n\t\tVpratio += Bx * By * integrator_->operator()( integrand11, 0, maturity );\n\n\t\tauto integrand01 = [maturity, dynamics]( Time u )\n\t\t{\n\t\t\treturn dynamics->sigma( 0 )(u) * dynamics->sigma( 1 )(u) \n\t\t\t\t/ dynamics->E( 0, u, maturity ) / dynamics->E( 1, u, maturity );\n\t\t};\n\n\t\tVpratio += 2 * Bx * Bx * rho * integrator_->operator()( integrand01, 0, maturity );\n\n\t\tReal stdDev = sqrt( std::max( Vpratio, 0.0 ) );\n\n\t\tReal f = termStructure()->discount( bondMaturity );\n\t\tReal k = termStructure()->discount( maturity )*strike;\n\n\t\treturn blackFormula( type, k, f, stdDev );\n\t}\n\n\n\tReal GeneralizedG2::discountBondOption( Option::Type type,\n\t\t\t\t\t\t\t\t\t\t\tReal strike,\n\t\t\t\t\t\t\t\t\t\t\tTime maturity,\n\t\t\t\t\t\t\t\t\t\t\tTime bondStart,\n\t\t\t\t\t\t\t\t\t\t\tTime bondMaturity ) const\n\t{\n\t\treturn discountBondOption( type, strike, bondStart, bondMaturity );\n\t}\n\n\t// Brigo Ch. 4.2\n\tReal GeneralizedG2::swaption( const Swaption::arguments& arg, Real strike ) const\n\t{\n\t\tDate settlement = termStructure()->referenceDate();\n\t\tDayCounter dayCounter = termStructure()->dayCounter();\n\t\tTime T = dayCounter.yearFraction( settlement,\n\t\t\t\t\t\t\t\t\t\t\t  arg.floatingResetDates[0] );\n\t\tReal w = (arg.type == VanillaSwap::Payer ? 1 : -1);\n\n\t\tstd::vector<Time> t;\n\t\tfor ( auto fixedPayDate : arg.fixedPayDates )\n\t\t{\n\t\t\tt.push_back( dayCounter.yearFraction( settlement,\n\t\t\t\t\t\t\t\t\t\t\t\t\tfixedPayDate ) );\n\t\t}\n\t\tSize N_timestep = t.size();\n\t\t\n\t\tArray cA( N_timestep );\n\t\tArray Bx( N_timestep );\n\t\tArray By( N_timestep );\n\n\t\tfor ( Size i = 0; i < N_timestep; i++ )\n\t\t{\n\t\t\tTime tau_i = i == 0 ? t[i] - T : t[i] - t[i - 1];\n\t\t\tReal c = i == N_timestep - 1 ? 1 + strike * tau_i : strike * tau_i;\n\t\t\tcA[i] = c * dynamics_->A( T, t[i] );\n\t\t\tBx[i] = dynamics_->B( 0, T, t[i] );\n\t\t\tBy[i] = dynamics_->B( 1, T, t[i]);\n\t\t}\n\n\t\tReal mu_x = dynamics_->meanTforward( 0, T, 0, T );\n\t\tReal mu_y = dynamics_->meanTforward( 1, T, 0, T );\n\t\tReal sigma_x = sqrt(dynamics_->variance( 0, 0, 0, T ));\n\t\tReal sigma_y = sqrt(dynamics_->variance( 1, 1, 0, T ));\n\t\tReal rho = dynamics_->rho( 0, 1 )(0.0);\n\t\tReal var = dynamics_->variance( 0, 1, 0, T );\n\t\tReal rho_xy = rho * var / sigma_x / sigma_y;\n\t\tReal rhosqrt = sqrt( 1 - rho_xy * rho_xy );\n\n\t\tauto integrand = [&, N_timestep, w, mu_x, mu_y, sigma_x, sigma_y, rho_xy, rhosqrt]( Real x )\n\t\t{\n\t\t\tReal dev = (x - mu_x) / sigma_x;\n\n\t\t\tArray lambda( N_timestep );\n\t\t\tArray kappa( N_timestep );\n\t\t\tfor ( Size i = 0; i < N_timestep; i++ )\n\t\t\t{\n\t\t\t\tlambda[i] = cA[i] * exp( -Bx[i] * x );\n\t\t\t\tkappa[i] = -By[i] * (mu_y - 0.5 * rhosqrt * rhosqrt * sigma_y * sigma_y * By[i]\n\t\t\t\t\t\t\t\t\t\t\t+ rho_xy * sigma_y * (x - mu_x) / sigma_x);\n\t\t\t}\n\n\t\t\tauto hyperplane = [N_timestep, &lambda, &By]( Real y )\n\t\t\t{\n\t\t\t\tReal value = 1.;\n\t\t\t\tfor ( Size i = 0; i < N_timestep; i++ )\n\t\t\t\t{\n\t\t\t\t\tReal val = lambda[i] * exp( -By[i] * y );\n\t\t\t\t\tvalue -= val;\n\t\t\t\t}\n\n\t\t\t\treturn value;\n\t\t\t};\n\n\t\t\tBrent solver;\n\t\t\tsolver.setMaxEvaluations( 1000 );\n\t\t\tReal ybar = solver.solve( hyperplane, 1e-6, 0.00, -100.0, 100.0 );\n\n\t\t\tReal h1 = (ybar - mu_y) / (sigma_y * rhosqrt)\n\t\t\t\t- rho_xy * (x - mu_x) / (sigma_x * rhosqrt);\n\n\t\t\tCumulativeNormalDistribution Phi;\n\t\t\tReal val = Phi( -w * h1 );\n\t\t\tfor ( Size i = 0; i < N_timestep; i++ )\n\t\t\t{\n\t\t\t\tReal h2 = h1 + By[i] * sigma_y * rhosqrt;\n\n\t\t\t\tval -= lambda[i] * exp( kappa[i] ) * Phi( -w * h2 );\n\t\t\t}\n\n\t\t\treturn exp( -0.5*dev*dev ) * val;\n\t\t};\n\n\t\tReal N = arg.nominal;\n\t\tReal P0T = termStructure()->discount( T );\n\t\tReal upper = mu_x + integralSignificance_ *sigma_x;\n\t\tReal lower = mu_x - integralSignificance_ *sigma_x;\n\n\t\tReal val = N * w * P0T * integrator_->operator()( integrand, lower, upper ) / sqrt( 2. * M_PI ) / sigma_x;\n\t\treturn val;\n\t}\n}", "meta": {"hexsha": "a9cb2ec6f8b2ce5c5e3276b7a56cd75d0c88942c", "size": 6090, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "calibrator/calibrator/models/shortrate/twofactormodels/generalg2.cpp", "max_stars_repo_name": "hanjin-kim/gaussian-n-factor", "max_stars_repo_head_hexsha": "0865fa115094e1f7f8e968eb8f7f123c2cc26c9f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-02-25T05:59:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-27T04:10:19.000Z", "max_issues_repo_path": "sources/calibrator/calibrator/models/shortrate/twofactormodels/generalg2.cpp", "max_issues_repo_name": "hanjin-kim/gaussian-n-factor", "max_issues_repo_head_hexsha": "0865fa115094e1f7f8e968eb8f7f123c2cc26c9f", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/calibrator/calibrator/models/shortrate/twofactormodels/generalg2.cpp", "max_forks_repo_name": "hanjin-kim/gaussian-n-factor", "max_forks_repo_head_hexsha": "0865fa115094e1f7f8e968eb8f7f123c2cc26c9f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-07-27T04:10:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-27T04:10:42.000Z", "avg_line_length": 28.1944444444, "max_line_length": 108, "alphanum_fraction": 0.6111658456, "num_tokens": 2057, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788995148792, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.49551218889867876}}
{"text": "/*\n * NormalVectorsFilter.hpp\n *\n *  Created on: May 05, 2015\n *      Author: Peter Fankhauser, Martin Wermelinger\n *   Institute: ETH Zurich, ANYbotics\n */\n\n#pragma once\n\n#include <filters/filter_base.hpp>\n#include <grid_map_core/grid_map_core.hpp>\n\n#include <Eigen/Core>\n#include <string>\n\nnamespace grid_map {\n\n/*!\n * Compute the normal vectors of a layer in a map.\n */\ntemplate <typename T>\nclass NormalVectorsFilter : public filters::FilterBase<T> {\n public:\n  /*!\n   * Constructor\n   */\n  NormalVectorsFilter();\n\n  /*!\n   * Destructor.\n   */\n  ~NormalVectorsFilter() override;\n\n  /*!\n   * Configures the filter from parameters on the Parameter Server.\n   * This comprehend in order:\n   *    1) algorithm, used for choosing between area and raster algorithm (default=area)\n   *    2)If algorithm is not raster estimationRadius_ is read an a basic check on its sign is made.\n   *      If something is wrong it switches to raster algorithm.\n   *    3) parallelization_enabled, used for choosing between serial and parallel algorithm (default=false)\n   *    4) thread_count, used to set the number of threads to be used in parallelization is enabled (default=auto)\n   * The parallelization_enabled and algorithm parameters allow to choose between the 4 different methods { AreaSerial, AreaParallel,\n   * RasterSerial, RasterParallel }\n   *    4) normal_vector_positive_axis, used to define the upward positive direction for the normals\n   *    5) input_layer, defines in which layer of the grid map lie the information needed (usually elevation or elevation_filtered)\n   *    6) output_layers_prefix, defines the prefix for the new 3 layers (x,y,z) that will define the normal vectors\n   * Those parameters have to be written in a .yaml file that will be processed as a sequence of filters.\n   * An example can be seen in grid_map_demos/config/normal_filter_comparison.yaml.\n   */\n  bool configure() override;\n\n  /*!\n   * Compute the normal vectors of a layer in a map and\n   * saves it as additional grid map layer.\n   * @param mapIn grid map containing the layer for which the normal vectors are computed for.\n   * @param mapOut grid map containing mapIn and the new layers for the normal vectors.\n   */\n  bool update(const T& mapIn, T& mapOut) override;\n\n private:\n  /*!\n   * Estimate the normal vector at each point of the input layer by using the areaSingleNormalComputation function.\n   * This function makes use of the area method and is the serial version of such normal vector computation using a\n   * simple for cycle to iterate over the whole map.\n   *\n   * @param map: grid map containing the layer for which the normal vectors are computed for.\n   * @param inputLayer: Layer the normal vector should be computed for.\n   * @param outputLayersPrefix: Output layer name prefix.\n   */\n  void computeWithAreaSerial(GridMap& map, const std::string& inputLayer, const std::string& outputLayersPrefix);\n\n  /*!\n   * Estimate the normal vector at each point of the input layer by using the areaSingleNormalComputation function.\n   * This function makes use of the area method and is the parallel version of such normal vector computation using\n   * a parallel_for cycle to iterate over the whole map. The parallel_for construct is provided by Intel TBB library.\n   *\n   * @param map: grid map containing the layer for which the normal vectors are computed for.\n   * @param inputLayer: Layer the normal vector should be computed for.\n   * @param outputLayersPrefix: Output layer name prefix.\n   */\n  void computeWithAreaParallel(GridMap& map, const std::string& inputLayer, const std::string& outputLayersPrefix);\n\n  /*!\n   * Estimate the normal vector at one point of the input layer, specified by the index parameter, by using points within\n   * a circle of specified radius.\n   *\n   * The eigen decomposition of the covariance matrix (3x3) of all data points is used to establish the normal direction.\n   * Four cases can be identified when the eigenvalues are ordered in ascending order:\n   *    1) The data is in a cloud -> all eigenvalues are non-zero\n   *    2) The data is on a plane -> The first eigenvalue is zero\n   *    3) The data is on a line -> The first two eigenvalues are zero.\n   *    4) The data is in one point -> All eigenvalues are zero\n   *\n   * Only case 1 & 2 provide enough information the establish a normal direction.\n   * The degenerate cases (3 or 4) are identified by checking if the second eigenvalue is zero.\n   *\n   * The numerical threshold (1e-8) for the eigenvalue being zero is given by the accuracy of the decomposition, as reported by Eigen:\n   * https://eigen.tuxfamily.org/dox/classEigen_1_1SelfAdjointEigenSolver.html\n   *\n   * Finally, the sign normal vector is correct to be in the same direction as the user defined \"normal vector positive axis\"\n   *\n   * @param map: grid map containing the layer for which the normal vectors are computed for.\n   * @param inputLayer: Layer the normal vector should be computed for.\n   * @param outputLayersPrefix: Output layer name prefix.\n   * @param index: Index of point in the grid map for which this function calculates the normal vector.\n   */\n  void areaSingleNormalComputation(GridMap& map, const std::string& inputLayer, const std::string& outputLayersPrefix,\n                                          const grid_map::Index& index);\n  /*!\n   * Estimate the normal vector at each point of the input layer by using the rasterSingleNormalComputation function.\n   * This function makes use of the raster method and is the serial version of such normal vector computation using a\n   * simple for cycle to iterate over the whole map.\n   *\n   * @param map: grid map containing the layer for which the normal vectors are computed for.\n   * @param inputLayer: Layer the normal vector should be computed for.\n   * @param outputLayersPrefix: Output layer name prefix.\n   */\n  void computeWithRasterSerial(GridMap& map, const std::string& inputLayer, const std::string& outputLayersPrefix);\n\n  /*!\n   * Estimate the normal vector at each point of the input layer by using the rasterSingleNormalComputation function.\n   * This function makes use of the raster method and is the parallel version of such normal vector computation using\n   * a parallel_for cycle to iterate over the whole map. The parallel_for construct is provided by Intel TBB library.\n   *\n   * @param map: grid map containing the layer for which the normal vectors are computed for.\n   * @param inputLayer: Layer the normal vector should be computed for.\n   * @param outputLayersPrefix: Output layer name prefix.\n   */\n  void computeWithRasterParallel(GridMap& map, const std::string& inputLayer, const std::string& outputLayersPrefix);\n\n  /*!\n   * Estimate the normal vector at one point of the input layer, specified by the index parameter, by using neighboring points\n   * around the point for which the normal vector is being calculated.\n   *\n   * The neighboring cells are used to linearly approximate the first derivative in both directions.\n   *\n   *   |T|   ^\n   * |L|C|R| | x Axis\n   *   |B|   |\n   * <-------|\n   * Y Axis\n   *\n   * Those values are then used to reconstruct the normal vector in the point of interest.\n   * This algorithm doesn't make use of the central cell if all the neighboring point heights are present.\n   * However, thanks to that, it can accommodate missing point heights, up to one in each direction, by using\n   * exactly the central height value.\n   * In this case, the resulting approximation, will suffer a loss of quality depending on the local surface shape.\n   * This implementation skips the outermost values in order to avoid checks on the validity of height values\n   * and therefore have a faster algorithm.\n   *\n   * Inspiration for algorithm: http://www.flipcode.com/archives/Calculating_Vertex_Normals_for_Height_Maps.shtml\n   *\n   * Finally, the sign normal vector is correct to be in the same direction as the user defined \"normal vector positive axis\"\n   *\n   * @param map: grid map containing the layer for which the normal vectors are computed for.\n   * @param inputLayer: Layer the normal vector should be computed for.\n   * @param outputLayersPrefix: Output layer name prefix.\n   * @param dataMap: Matrix containing the input layer of the grid map in question.\n   * @param index: Index of point in the grid map for which this function calculates the normal vector.\n   */\n  void rasterSingleNormalComputation(GridMap& map, const std::string& outputLayersPrefix, const grid_map::Matrix& dataMap,\n                                            const grid_map::Index& index);\n\n  enum class Method { AreaSerial, AreaParallel, RasterSerial, RasterParallel };\n\n  Method method_;\n\n  //! Radius of submap for normal vector estimation.\n  double estimationRadius_;\n\n  //! Parameter that specifies whether to parallelize or not.\n  bool parallelizationEnabled_;\n\n  //! Parameter that specifies the number of thread used.\n  int threadCount_;\n\n  //! Normal vector positive axis.\n  Eigen::Vector3d normalVectorPositiveAxis_;\n\n  //! Input layer name.\n  std::string inputLayer_;\n\n  //! Output layer name.\n  std::string outputLayersPrefix_;\n\n  //! Grid Map Resolution.\n  double gridMapResolution_;\n};\n\n}  // namespace grid_map\n", "meta": {"hexsha": "13c7fe3c346db616931e893b7b31bed448988d74", "size": 9212, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "grid_map_filters/include/grid_map_filters/NormalVectorsFilter.hpp", "max_stars_repo_name": "wep21/grid_map", "max_stars_repo_head_hexsha": "a2eb6b1757122c27028335c52654982d615e62fd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1305.0, "max_stars_repo_stars_event_min_datetime": "2018-08-06T14:40:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T17:44:18.000Z", "max_issues_repo_path": "grid_map_filters/include/grid_map_filters/NormalVectorsFilter.hpp", "max_issues_repo_name": "wep21/grid_map", "max_issues_repo_head_hexsha": "a2eb6b1757122c27028335c52654982d615e62fd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 174.0, "max_issues_repo_issues_event_min_datetime": "2018-08-06T21:41:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T04:45:09.000Z", "max_forks_repo_path": "grid_map_filters/include/grid_map_filters/NormalVectorsFilter.hpp", "max_forks_repo_name": "wep21/grid_map", "max_forks_repo_head_hexsha": "a2eb6b1757122c27028335c52654982d615e62fd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 423.0, "max_forks_repo_forks_event_min_datetime": "2018-08-07T13:37:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T08:07:26.000Z", "avg_line_length": 47.9791666667, "max_line_length": 134, "alphanum_fraction": 0.7330655667, "num_tokens": 2078, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.49546080444292034}}
{"text": "#include \"rice/Class.hpp\"\n#include \"rice/String.hpp\"\n#include \"rice/Constructor.hpp\"\n#include \"rice/Enum.hpp\"\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <Eigen/SVD>\n\nusing namespace Rice;\n\ntypedef Eigen::Matrix<double, 3, 1, Eigen::DontAlign>     Vector3d;\ntypedef Eigen::Matrix<double, 4, 4, Eigen::DontAlign>     Matrix4d;\ntypedef Eigen::Quaternion<double, Eigen::DontAlign>    Quaterniond;\ntypedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::DontAlign>\n                                                       MatrixXd;\ntypedef Eigen::Matrix<double, Eigen::Dynamic, 1, Eigen::DontAlign>\n                                                       VectorXd;\ntypedef Eigen::Transform< double, 3, Eigen::Isometry > Isometry3d;\ntypedef Eigen::Transform< double, 3, Eigen::Affine > Affine3d;\ntypedef Eigen::AngleAxis<double> AngleAxisd;\n\n/* \n * Document-class: Eigen::Vector3\n *\n * A 3-vector holding floating-point numbers\n *\n * @!method initialize(x = 0, y = 0, z = 0)\n *   Creates a new vector\n *   @param [Numeric] x\n *   @param [Numeric] y\n *   @param [Numeric] z\n * @!method norm\n *   The vector's norm\n *   @return [Numeric]\n * @!method normalize!\n *   Normalizes self\n *   @return [void]\n * @!method normalize\n *   Returns a normalized self\n *   @return [Vector3]\n * @!method [](index)\n *   Returns an element\n *   @param [Integer] index the element index (0, 1 or 2)\n *   @return [Numeric]\n * @!method x\n *   Returns X\n *   @return [Numeric]\n * @!method y\n *   Returns Y\n *   @return [Numeric]\n * @!method z\n *   Returns Z\n *   @return [Numeric]\n * @!method x=(value)\n *   Sets X\n *   @param [Numeric] value\n *   @return [Numeric]\n * @!method y=(value)\n *   Sets Y\n *   @param [Numeric] value\n *   @return [Numeric]\n * @!method z=(value)\n *   Sets Z\n *   @param [Numeric] value\n *   @return [Numeric]\n * @!method []=(index, value)\n *   Sets an element\n *   @param [Integer] index the element index (0, 1 or 2)\n *   @param [Numeric] value\n *   @return [Numeric]\n * @!method +(v)\n *    Sum\n *    @param [Vector3] v\n *    @return [Vector3] the sum\n * @!method -(v)\n *    Subtracts\n *    @param [Vector3] v\n *    @return [Vector3] the subtraction\n * @!method *(scalar)\n *    Multiplies by a scalar\n *    @param [Numeric] scalar the scalar\n *    @return [Vector3] the result\n * @!method /(scalar)\n *    Divides by a scalar\n *    @param [Numeric] scalar the scalar\n *    @return [Vector3] the result\n * @!method -@()\n *    Negation\n *    @return [Vector3] the result\n * @!method cross(v)\n *    Cross product\n *    @param [VectorX] v\n *    @return [VectorX] the result\n * @!method dot(v)\n *    Dot product\n *    @param [VectorX] v\n *    @return [VectorX] the result\n * @!method approx?(v, threshold = dummy_precision)\n *    Verifies that two vectors are within threshold of each other, elementwise\n *    @param [Vector3]\n *    @return [Boolean]\n */\n\nstruct Vector3\n{\n    Vector3d* v;\n\n    Vector3(double x, double y, double z)\n        : v(new Vector3d(x, y, z)) {}\n    Vector3(Vector3d const& _v)\n        : v(new Vector3d(_v)) {}\n    ~Vector3()\n    { delete v; }\n\n    double x() const { return v->x(); }\n    double y() const { return v->y(); }\n    double z() const { return v->z(); }\n    void setX(double value) { v->x() = value; }\n    void setY(double value) { v->y() = value; }\n    void setZ(double value) { v->z() = value; }\n\n\n    double norm() const { return v->norm(); }\n    Vector3* normalize() const { return new Vector3(v->normalized()); }\n    void normalizeBang() const { v->normalize(); }\n\n    double get(int i) const { return (*v)[i]; }\n    void set(int i, double value) { (*v)[i] = value; }\n\n    Vector3* operator + (Vector3 const& other) const\n    { return new Vector3(*v + *other.v); }\n    Vector3* operator - (Vector3 const& other) const\n    { return new Vector3(*v - *other.v); }\n\n    Vector3* operator / (double scalar) const\n    { return new Vector3(*v / scalar); }\n\n    Vector3* negate() const\n    { return new Vector3(-*v); }\n    Vector3* scale(double value) const\n    { return new Vector3(*v * value); }\n    double dot(Vector3 const& other) const\n    { return this->v->dot(*other.v); }\n    Vector3* cross(Vector3 const& other) const\n    { return new Vector3(this->v->cross(*other.v)); }\n    bool operator ==(Vector3 const& other) const\n    { return (*this->v) == (*other.v); }\n    bool isApprox(Vector3 const& other, double tolerance)\n    { return v->isApprox(*other.v, tolerance); }\n};\n\n/* \n * Document-class: Eigen::VectorX\n *\n * A variable-length vector holding floating-point numbers\n *\n * @!method initialize(size = 0)\n *   Creates a new vector\n *   @param [Numeric] size\n * @!method resize(new_size)\n *   Changes the vector's size\n *   @param [Integer] new_size\n *   @return [Numeric]\n * @!method norm\n *   The vector's norm\n *   @return [Numeric]\n * @!method normalize!\n *   Normalizes self\n *   @return [void]\n * @!method normalize\n *   Returns a normalized self\n *   @return [VectorX]\n * @!method size\n *   Returns the vector's size\n *   @return [Integer]\n * @!method [](index)\n *   Returns an element\n *   @param [Integer] index the element index (0, 1 or 2)\n *   @return [Numeric]\n * @!method []=(index, value)\n *   Sets an element\n *   @param [Integer] index the element index (0, 1 or 2)\n *   @param [Numeric] value\n *   @return [Numeric]\n * @!method +(v)\n *    Sum\n *    @param [VectorX] v\n *    @return [VectorX] the sum\n * @!method -(v)\n *    Subtracts\n *    @param [VectorX] v\n *    @return [VectorX] the subtraction\n * @!method *(scalar)\n *    Multiplies by a scalar\n *    @param [Numeric] scalar the scalar\n *    @return [VectorX] the result\n * @!method /(scalar)\n *    Divides by a scalar\n *    @param [Numeric] scalar the scalar\n *    @return [VectorX] the result\n * @!method -@()\n *    Negation\n *    @return [VectorX] the result\n * @!method dot(v)\n *    Dot product\n *    @param [VectorX] v\n *    @return [VectorX] the result\n * @!method approx?(v, threshold = dummy_precision)\n *    Verifies that two vectors are within threshold of each other, elementwise\n *    @param [VectorX]\n *    @return [Boolean]\n */\nstruct VectorX {\n\n    VectorXd* v;\n    \n    VectorX()\n        : v(new VectorXd()) {}\n    VectorX(VectorX const& v)\n        : v(new VectorXd(*v.v)) {}\n    VectorX(int n)\n        : v(new VectorXd(n)) {}\n    VectorX(VectorXd const& _v)\n        : v(new VectorXd(_v)) {}\n    ~VectorX()\n    { delete v; }\n    \n    void resize(int n) { v->resize(n); }\n    void conservativeResize(int n) { v->conservativeResize(n); }\n\n    double norm() const { return v->norm(); }\n    VectorX* normalize() const { return new VectorX(v->normalized()); }\n    void normalizeBang() const { v->normalize(); }\n\n    unsigned int size() { return v->size(); }\n\n    double get(int i) const { return (*v)[i]; }\n    void set(int i, double value) { (*v)[i] = value; }\n\n    VectorX* operator + (VectorX const& other) const\n    { return new VectorX(*v + *other.v); }\n    VectorX* operator - (VectorX const& other) const\n    { return new VectorX(*v - *other.v); }\n\n    VectorX* operator / (double scalar) const\n    { return new VectorX(*v / scalar); }\n    \n    VectorX* negate() const\n    { return new VectorX(-*v); }\n\n    VectorX* scale(double value) const\n    { return new VectorX(*v * value); }\n\n    double dot(VectorX const& other) const\n    { return this->v->dot(*other.v); }\n\n    bool operator ==(VectorX const& other) const\n    { return (*this->v) == (*other.v); }\n\n    bool isApprox(VectorX const& other, double tolerance)\n    { return v->isApprox(*other.v, tolerance); }\n\n};\n\n/* \n * Document-class: Eigen::Matrix4\n *\n * A 4x4 matrix holding floating-point numbers\n *\n * @!method rows\n *    @return [Integer] the number of rows\n * @!method cols\n *    @return [Numeric] the number of columns\n * @!method size\n *    @return [Numeric] the number of elements\n * @!method [](row, col)\n *    Accesses an element\n *    @param [Integer] row the element's row\n *    @param [Integer] col the element's column\n *    @return [Numeric] the required element\n * @!method []=(row, col, value)\n *    Sets an element\n *    @param [Integer] row the element's row\n *    @param [Integer] col the element's column\n *    @param [Numeric] value the new value\n *    @return [Numeric] the value\n * @!method +(m)\n *    Sums two matrices\n *    @param [Matrix4] m the matrix to add\n *    @return [Matrix4] the sum\n * @!method -(m)\n *    Subtracts two matrices\n *    @param [Matrix4] m the matrix to subtract to self\n *    @return [Matrix4] the subtraction\n * @!method *(v)\n *    Multiplies by a scalar\n *    @param [Numeric] v the scalar\n *    @return [Matrix4] the result\n * @!method /(v)\n *    Divides this matrix by a scalar\n *    @param [Numeric] v the scalar\n *    @return [Matrix4] the result\n * @!method -@(v)\n *    Returns this matrix' negation\n *    @return [Matrix4] the result\n * @!method T\n *    Returns the transposed matrix\n *    @return [Matrix4]\n * @!method norm\n *    Returns the matrix' norm\n *    @return [Numeric]\n * @!method dotM(m)\n *    Matrix multiplication\n *    @param [Matrix4]\n *    @return [Numeric]\n * @!method approx?(m, threshold = dummy_precision)\n *    Verifies that two matrices are within threshold of each other, elementwise\n *    @param [Matrix4]\n *    @return [Boolean]\n */\nstruct Matrix4\n{\n    Matrix4d* mx;\n\n    Matrix4() : mx(new Matrix4d()) {}\n\n    Matrix4(Matrix4d const& _mx)\n        : mx(new Matrix4d(_mx)) {}\n\n    ~Matrix4()\n    { delete mx; }\n\n    double norm() const { return mx->norm(); }\n\n    int rows() const { return mx->rows(); }\n    int cols() const { return mx->cols(); }\n    int size() const { return mx->size(); }\n\n    double get(int i, int j ) const { return (*mx)(i,j); }\n    void set(int i, int j, double value) { (*mx)(i,j) = value; }\n\n    Matrix4* transpose() const\n    { return new Matrix4(mx->transpose()); }\n\n    Matrix4* operator + (Matrix4 const& other) const\n    { return new Matrix4(*mx + *other.mx); }\n\n    Matrix4* operator - (Matrix4 const& other) const\n    { return new Matrix4(*mx - *other.mx); }\n\n    Matrix4* operator / (double scalar) const\n    { return new Matrix4(*mx / scalar); }\n\n    Matrix4* negate() const\n    { return new Matrix4(-*mx); }\n\n    Matrix4* scale(double value) const\n    { return new Matrix4(*mx * value); }\n\n    Matrix4* dotM (Matrix4 const& other) const\n    { return new Matrix4(*mx * (*other.mx)); }\n\n    bool operator ==(Matrix4 const& other) const\n    { return (*this->mx) == (*other.mx); }\n\n    bool isApprox(Matrix4 const& other, double tolerance)\n    { return mx->isApprox(*other.mx, tolerance); }\n};\n\n/* \n * Document-class: Eigen::JacobiSVD\n *\n * Linear problem solver\n *\n * This is not constructed directly. Use {Eigen::MatrixX#jacobiSvd} instead.\n *\n * @!method solve(vector)\n *   Solves the linear problem for a given vector\n *   @param [VectorX] vector\n *   @return [VectorX] the result\n */\nstruct JacobiSVD {\n    typedef Eigen::JacobiSVD<Eigen::MatrixXd::PlainObject> EigenT;\n    EigenT* j;\n\n    JacobiSVD( EigenT const& j )\n    : j(new EigenT(j)) {}\n    JacobiSVD( JacobiSVD const& j )\n    : j(new EigenT(*j.j)) {}\n    ~JacobiSVD()\n    { delete j; }\n\n    VectorX* solve(VectorX* y)\n    { return new VectorX(j->solve(*y->v)); }\n};\n\n/* \n * Document-class: Eigen::MatrixX\n *\n * A variable-size matrix holding floating-point numbers\n *\n * @!method resize(rows, cols)\n *    Resizes the matrix\n *    @param [Integer] rows the new number of rows\n *    @param [Integer] cols the new number of columns\n * @!method rows\n *    @return [Integer] the number of rows\n * @!method cols\n *    @return [Numeric] the number of columns\n * @!method size\n *    @return [Numeric] the number of elements\n * @!method [](row, col)\n *    Accesses an element\n *    @param [Integer] row the element's row\n *    @param [Integer] col the element's column\n *    @return [Numeric] the required element\n * @!method []=(row, col, value)\n *    Sets an element\n *    @param [Integer] row the element's row\n *    @param [Integer] col the element's column\n *    @param [Numeric] value the new value\n *    @return [Numeric] the value\n * @!method setRow(row, vector)\n *    Sets a whole matrix row\n *    @param [Integer] row the row index\n *    @param [VectorX] vector the row values\n * @!method setColumn(column, vector)\n *    Sets a whole matrix column\n *    @param [Integer] row the column index\n *    @param [VectorX] vector the column values\n * @!method +(m)\n *    Sums two matrices\n *    @param [MatrixX] m the matrix to add\n *    @return [MatrixX] the sum\n * @!method -(m)\n *    Subtracts two matrices\n *    @param [MatrixX] m the matrix to subtract to self\n *    @return [MatrixX] the subtraction\n * @!method *(v)\n *    Multiplies by a scalar\n *    @param [Numeric] v the scalar\n *    @return [MatrixX] the result\n * @!method /(v)\n *    Divides this matrix by a scalar\n *    @param [Numeric] v the scalar\n *    @return [MatrixX] the result\n * @!method -@(v)\n *    Returns this matrix' negation\n *    @return [MatrixX] the result\n * @!method T\n *    Returns the transposed matrix\n *    @return [MatrixX]\n * @!method norm\n *    Returns the matrix' norm\n *    @return [Numeric]\n * @!method dotV(m)\n *    Matrix/vector multiplication\n *    @param [VectorX]\n *    @return [Numeric]\n * @!method dotM(m)\n *    Matrix multiplication\n *    @param [Matrix4]\n *    @return [Numeric]\n * @!method approx?(m, threshold = dummy_precision)\n *    Verifies that two matrices are within threshold of each other, elementwise\n *    @param [Matrix4]\n *    @return [Boolean]\n * @!method jacobiSvd(flags = 0)\n *    Returns a SVD solver to find V from W in self.dotV(V) = W\n *    @param [Integer] flags solver flags, as OR-ed values of Eigen::ComputeFullU,\n *      Eigen::ComputeThinU and Eigen::ComputeThinV. See Eigen documentation\n *    @return [JacobiSVD]\n */\nstruct MatrixX {\n\n    MatrixXd* m;\n\n    MatrixX() : m(new MatrixXd()) {}\n    MatrixX(const MatrixX& m) : m(new MatrixXd(*m.m)) {}\n    MatrixX(int rows, int cols) : m(new MatrixXd(rows,cols)) {}\n    MatrixX(const MatrixXd& _m) : m(new MatrixXd(_m)) {}\n    ~MatrixX() { delete m; }\n\n    void resize(int rows, int cols) { m->resize(rows,cols); }\n    void conservativeResize(int rows, int cols) { m->conservativeResize(rows,cols); }\n\n    double norm() const { return m->norm(); }\n\n    unsigned int rows() const { return m->rows(); }\n    unsigned int cols() const { return m->cols(); }\n    unsigned int size() const { return m->size(); }\n\n    double get(int i, int j ) const { return (*m)(i,j); }\n    void set(int i, int j, double value) { (*m)(i,j) = value; }\n    \n    VectorX* getRow(int i) const { return new VectorX(m->row(i)); }\n    void setRow(int i, const VectorX& v) { m->row(i) = *(v.v); }\n\n    VectorX* getColumn(int j) const { return new VectorX(m->col(j)); }\n    void setColumn(int j, const VectorX& v) { m->col(j) = *(v.v); }\n\n    MatrixX* transpose() const\n    { return new MatrixX(m->transpose()); }\n\n    MatrixX* operator + (MatrixX const& other) const\n    { return new MatrixX(*m + *other.m); }\n\n    MatrixX* operator - (MatrixX const& other) const\n    { return new MatrixX(*m - *other.m); }\n\n    MatrixX* operator / (double scalar) const\n    { return new MatrixX(*m / scalar); }\n\n    MatrixX* negate() const\n    { return new MatrixX(-*m); }\n    \n    MatrixX* scale (double scalar) const\n    { return new MatrixX(*m * scalar); }\n\n    VectorX* dotV (VectorX const& other) const\n    { return new VectorX(*m * *other.v); }\n    \n    MatrixX* dotM (MatrixX const& other) const\n    { return new MatrixX(*m * (*other.m)); }\n\n    JacobiSVD* jacobiSvd(int flags = 0) const\n    { return new JacobiSVD(m->jacobiSvd(flags)); }\n\n    bool operator ==(MatrixX const& other) const\n    { return (*this->m) == (*other.m); }\n\n    bool isApprox(MatrixX const& other, double tolerance)\n    { return m->isApprox(*other.m, tolerance); }\n};\n\n/*\n * Document-class: Eigen::Quaternion\n *\n * A floating-point valued quaternion\n *\n * @!method w\n *   The real part of the quaternion\n *   @return [Numeric]\n * @!method x\n *   The first element of the imaginary part of the quaternion\n *   @return [Numeric]\n * @!method y\n *   The second element of the imaginary part of the quaternion\n *   @return [Numeric]\n * @!method z\n *   The third element of the imaginary part of the quaternion\n *   @return [Numeric]\n * @!method w=(value)\n *   Sets the real part of the quaternion\n *   @param [Numeric] value\n *   @return [Numeric]\n * @!method x=(value)\n *   Sets the first element of the imaginary part of the quaternion\n *   @param [Numeric] value\n *   @return [Numeric]\n * @!method y=(value)\n *   Sets the second element of the imaginary part of the quaternion\n *   @param [Numeric] value\n *   @return [Numeric]\n * @!method z=(value)\n *   Sets the third element of the imaginary part of the quaternion\n *   @param [Numeric] value\n *   @return [Numeric]\n * @!method norm\n *   The norm\n *   @return [Numeric]\n * @!method concatenate(q)\n *   Quaternion multiplication\n *   @param [Quaternion] q\n *   @return [Quaternion] self * q\n * @!method inverse\n *   The quaternion inverse\n *   @return [Quaternion]\n * @!method transform(v)\n *   Transform a vector-3 by this quaternion\n *   @param [Vector3] v\n *   @return [Vector3]\n * @!method matrix\n *   The rotation matrix equivalent to this unit quaternion\n *   @return [MatrixX]\n * @!method normalize!\n *   Normalizes self\n *   @return [void]\n * @!method normalize\n *   Returns the self normalized\n *   @return [Quaternion]\n * @!method approx?(q, threshold = dummy_precision)\n *   Verifies that two quaternions are within threshold of each other, elementwise\n *   @param [Quaternion]\n *   @return [Boolean]\n * @!method to_euler\n *   Converts this quaternion into Euler-Bryant angles\n *   @return [Vector3] a 3-vector where .x is roll (rotation around X), .y is\n *     pitch and .z yaw\n * @!method from_euler(v)\n *   Initializes from euler angles\n *   @param [Vector3] v a 3-vector where .x is roll (rotation around X), .y is\n *     pitch and .z yaw\n *   @return [void]\n * @!method from_angle_axis(angle_axis)\n *   Initializes from an angle-axis representation\n *   @param [AngleAxis] an angle-axis representation of a rotation\n *   @return [void]\n * @!method from_matrix(matrix)\n *   Initializes from a rotation matrix\n *   @param [MatrixX]\n *   @return [void]\n */\nstruct Quaternion\n{\n    Quaterniond* q;\n    Quaternion(double w, double x, double y, double z)\n        : q(new Quaterniond(w, x, y, z)) { }\n    Quaternion(Quaternion const& q)\n        : q(new Quaterniond(*q.q)) { }\n    Quaternion(Quaterniond const& _q)\n        : q(new Quaterniond(_q)) {}\n\n    ~Quaternion()\n    { delete q; }\n\n    double w() const { return q->w(); }\n    double x() const { return q->x(); }\n    double y() const { return q->y(); }\n    double z() const { return q->z(); }\n    void setW(double value) { q->w() = value; }\n    void setX(double value) { q->x() = value; }\n    void setY(double value) { q->y() = value; }\n    void setZ(double value) { q->z() = value; }\n\n    double norm() const { return q->norm(); }\n\n    bool operator ==(Quaternion const& other) const\n    { return x() == other.x() && y() == other.y() && z() == other.z() && w() == other.w(); }\n\n    Quaternion* concatenate(Quaternion const& other) const\n    { return new Quaternion((*q) * (*other.q)); }\n    Vector3* transform(Vector3 const& v) const\n    { return new Vector3((*q) * (*v.v)); }\n    Quaternion* inverse() const\n    { return new Quaternion(q->inverse()); }\n    void normalizeBang()\n    { q->normalize(); }\n    Quaternion* normalize() const\n    { \n        Quaterniond q = *this->q;\n        q.normalize();\n        return new Quaternion(q);\n    }\n    MatrixX* matrix() const\n    {\n        return new MatrixX(q->matrix());\n    }\n\n    void fromAngleAxis(double angle, Vector3 const& axis)\n    {\n\t*(this->q) = \n            Eigen::AngleAxisd(angle, *axis.v);\n    }\n\n    void fromEuler(Vector3 const& angles, int axis0, int axis1, int axis2)\n    {\n        *(this->q) =\n            Eigen::AngleAxisd(angles.x(), Eigen::Vector3d::Unit(axis0)) *\n            Eigen::AngleAxisd(angles.y(), Eigen::Vector3d::Unit(axis1)) *\n            Eigen::AngleAxisd(angles.z(), Eigen::Vector3d::Unit(axis2));\n    }\n\n    void fromMatrix(MatrixX const& matrix)\n    {\n\t*(this->q) = \n            Quaterniond(Eigen::Matrix3d(*matrix.m));\n    }\n\n    bool isApprox(Quaternion const& other, double tolerance)\n    {\n        return q->isApprox(*other.q, tolerance);\n    }\n\n    Vector3* toEuler()\n    {\n        const Eigen::Matrix3d m = q->toRotationMatrix();\n        double i = Eigen::Vector2d(m.coeff(2,2) , m.coeff(2,1)).norm();\n        double y = atan2(-m.coeff(2,0), i);\n        double x=0,z=0;\n        if (i > Eigen::NumTraits<double>::dummy_precision()){\n            x = ::atan2(m.coeff(1,0), m.coeff(0,0));\n            z = ::atan2(m.coeff(2,1), m.coeff(2,2));\n        }else{\n            z = (m.coeff(2,0)>0?1:-1)* ::atan2(-m.coeff(0,1), m.coeff(1,1));\n        }\n        return new Vector3(x,y,z);\n    }\n};\n\n\n/*\n * Document-class: Eigen::AngleAxis\n *\n * A rotation represented by an axis and angle\n *\n * @!method angle\n *   The angle (in radians)\n *   @return [Numeric]\n * @!method axis\n *   The rotation axis\n *   @return [Vector3]\n * @!method concatenate(aa)\n *   Combine this rotation with another rotation\n *   @param [AngleAxis] aa\n *   @return [AngleAxis]\n * @!method inverse\n *   The inverse rotation\n *   @return [AngleAxis]\n * @!method transform(v)\n *   Apply this rotation on a 3-vector\n *   @param [Vector3] v\n *   @return [Vector3]\n * @!method matrix\n *   The rotation matrix equivalent to this unit quaternion\n *   @return [MatrixX]\n * @!method approx?(aa, threshold = dummy_precision)\n *    Verifies that two angle-axis are within threshold of each other, elementwise\n *    @param [AngleAxis]\n *    @return [Boolean]\n * @!method to_euler\n *    Converts this quaternion into Euler-Bryant angles\n *    @return [Vector3] a 3-vector where .x is roll (rotation around X), .y is\n *      pitch and .z yaw\n * @!method from_euler(v)\n *    Initializes from euler angles\n *    @param [Vector3] v a 3-vector where .x is roll (rotation around X), .y is\n *      pitch and .z yaw\n * @!method from_quaternion(q)\n *    Initializes from a quaternion\n *    @param [Quaternion] q\n * @!method from_matrix(matrix)\n *    Initializes from a rotation matrix\n *    @param [MatrixX]\n */\nstruct AngleAxis\n{\n    AngleAxisd* aa;\n    AngleAxis(double angle, Vector3 const& axis)\n        : aa(new AngleAxisd(angle, Eigen::Vector3d(*axis.v))){}\n    AngleAxis(AngleAxis const& aa)\n        : aa(new AngleAxisd(*aa.aa)) { }\n    AngleAxis(AngleAxisd const& _aa)\n        : aa(new AngleAxisd(_aa)) {}\n\n    ~AngleAxis()\n    { delete aa; }\n\n    bool operator ==(AngleAxis const& other) const\n    { return angle() == other.angle() && axis() == other.axis(); }\n\n    double angle() const { return aa->angle(); }\n    Vector3* axis() const { return new Vector3(aa->axis()); }\n\n    AngleAxis* concatenate(AngleAxis const& other) const\n    { return new AngleAxis(static_cast<AngleAxisd>((*aa) * (*other.aa))); }\n\n    Vector3* transform(Vector3 const& v) const\n    { return new Vector3((*aa) * (*v.v)); }\n\n    AngleAxis* inverse() const\n    { return new AngleAxis(aa->inverse()); }\n\n    MatrixX* matrix() const\n    {\n        return new MatrixX(aa->matrix());\n    }\n\n    void fromQuaternion(Quaternion const& q)\n    {\n        *(this->aa) = Eigen::Quaterniond(q.w(), q.x(), q.y(), q.z());\n    }\n\n    void fromEuler(Vector3 const& angles, int axis0, int axis1, int axis2)\n    {\n        *(this->aa) =\n            Eigen::AngleAxisd(angles.x(), Eigen::Vector3d::Unit(axis0)) *\n            Eigen::AngleAxisd(angles.y(), Eigen::Vector3d::Unit(axis1)) *\n            Eigen::AngleAxisd(angles.z(), Eigen::Vector3d::Unit(axis2));\n    }\n\n    void fromMatrix(MatrixX const& matrix)\n    {\n\t    *(this->aa) =\n            AngleAxisd(Eigen::Matrix3d(*matrix.m));\n    }\n\n    bool isApprox(AngleAxis const& other, double tolerance)\n    {\n        return aa->isApprox(*other.aa, tolerance);\n    }\n\n    Vector3* toEuler()\n    {\n        const Eigen::Matrix3d m = aa->toRotationMatrix();\n        double i = Eigen::Vector2d(m.coeff(2,2) , m.coeff(2,1)).norm();\n        double y = atan2(-m.coeff(2,0), i);\n        double x=0,z=0;\n        if (i > Eigen::NumTraits<double>::dummy_precision()){\n            x = ::atan2(m.coeff(1,0), m.coeff(0,0));\n            z = ::atan2(m.coeff(2,1), m.coeff(2,2));\n        }else{\n            z = (m.coeff(2,0)>0?1:-1)* ::atan2(-m.coeff(0,1), m.coeff(1,1));\n        }\n        return new Vector3(x,y,z);\n    }\n};\n\n#include <iostream>\n\n/*\n * Document-class: Eigen::Isometry3\n *\n * An isometry\n *\n * @!method approx?(v, threshold = dummy_precision)\n *    Verifies that two isometries are within threshold of each other, elementwise\n *    @param [Isometry3]\n *    @return [Boolean]\n * @!method inverse\n *    The inverse transformation\n *    @return [Isometry3]\n * @!method translation\n *    The translation part of this transformation\n *    @return [Vector3]\n * @!method rotation\n *    The rotation part of this transformation\n *    @return [Quaternion]\n * @!method concatenate(is)\n *    Concatenate self and another transformation\n *    @param [Isometry3] is\n *    @return [Isometry3]\n * @!method translate(v)\n *    Add a new translation after the rotation\n *    @param [Vector3] v the translation\n *    @return [void]\n * @!method rotate(q)\n *    Add a new rotation after the translation\n *    @param [Quaternion] q the rotation\n *    @return [void]\n * @!method pretranslate(v)\n *    Add a new translation before the rotation\n *    @param [Vector3] v the translation\n *    @return [void]\n * @!method prerotate(q)\n *    Add a new rotation before the translation\n *    @param [Quaternion] q the rotation\n *    @return [void]\n * @!method matrix\n *    The transformation matrix equivalent to self\n *    @return [MatrixX]\n */\nstruct Isometry3\n{\n    Isometry3d *t;\n\n    Isometry3() : t(new Isometry3d()) { t->setIdentity(); }\n    Isometry3(const Isometry3& _m) : t(new Isometry3d(*_m.t)) {}\n    Isometry3(const Isometry3d& _m) : t(new Isometry3d(_m)) {}\n    ~Isometry3() { delete t; }\n\n    Isometry3* inverse() const\n    { return new Isometry3( t->inverse() ); }\n\n    Vector3* translation() const\n    { return new Vector3( t->translation() ); }\n\n    Quaternion* rotation() const\n    { return new Quaternion( Eigen::Quaterniond(t->linear()) ); }\n\n    Isometry3* concatenate(Isometry3 const& other) const\n    { return new Isometry3( *t * *other.t ); }\n\n    Vector3* transform(Vector3 const& other) const\n    { return new Vector3( *t * *other.v ); }\n\n    MatrixX* matrix() const\n    { return new MatrixX( t->matrix() ); }\n\n    void translate( Vector3 const& other ) const\n    { t->translate( *other.v ); }\n\n    void pretranslate( Vector3 const& other ) const\n    { t->pretranslate( *other.v ); }\n\n    void rotate( Quaternion const& other ) const\n    { t->rotate( *other.q ); }\n\n    void prerotate( Quaternion const& other ) const\n    { t->prerotate( *other.q ); }\n\n    bool operator ==(Isometry3 const& other) const\n    { return (*this->t).matrix() == (*other.t).matrix(); }\n\n    bool isApprox(Isometry3 const& other, double tolerance)\n    { return t->isApprox(*other.t, tolerance); }\n};\n\n\n/*\n * Document-class: Eigen::Affine3\n *\n * An affine transformation\n *\n * @!method approx?(v, threshold = dummy_precision)\n *    Verifies that two transformations are within threshold of each other, elementwise\n *    @param [Isometry3]\n *    @return [Boolean]\n * @!method inverse\n *    The inverse transformation\n *    @return [Affine3]\n * @!method translation\n *    The translation part of this transformation\n *    @return [Vector3]\n * @!method rotation\n *    The rotation part of this transformation\n *    @return [Quaternion]\n * @!method concatenate(is)\n *    Concatenate self and another transformation\n *    @param [Affine3] is\n *    @return [Affine3]\n * @!method translate(v)\n *    Add a new translation after the rotation\n *    @param [Vector3] v the translation\n *    @return [void]\n * @!method rotate(q)\n *    Add a new rotation after the translation\n *    @param [Quaternion] q the rotation\n *    @return [void]\n * @!method pretranslate(v)\n *    Add a new translation before the rotation\n *    @param [Vector3] v the translation\n *    @return [void]\n * @!method prerotate(q)\n *    Add a new rotation before the translation\n *    @param [Quaternion] q the rotation\n *    @return [void]\n * @!method matrix\n *    The transformation matrix equivalent to self\n *    @return [MatrixX]\n */\nstruct Affine3\n{\n    Affine3d *t;\n\n    Affine3() : t(new Affine3d()) { t->setIdentity(); }\n    Affine3(const Affine3& _m) : t(new Affine3d(*_m.t)) {}\n    Affine3(const Affine3d& _m) : t(new Affine3d(_m)) {}\n    ~Affine3() { delete t; }\n\n    Affine3* inverse() const\n    { return new Affine3( t->inverse() ); }\n\n    Vector3* translation() const\n    { return new Vector3( t->translation() ); }\n\n    Quaternion* rotation() const\n    { return new Quaternion( Eigen::Quaterniond(t->linear()) ); }\n\n    Affine3* concatenate(Affine3 const& other) const\n    { return new Affine3( *t * *other.t ); }\n\n    Vector3* transform(Vector3 const& other) const\n    { return new Vector3( *t * *other.v ); }\n\n    MatrixX* matrix() const\n    { return new MatrixX( t->matrix() ); }\n\n    void translate( Vector3 const& other ) const\n    { t->translate( *other.v ); }\n\n    void pretranslate( Vector3 const& other ) const\n    { t->pretranslate( *other.v ); }\n\n    void rotate( Quaternion const& other ) const\n    { t->rotate( *other.q ); }\n\n    void prerotate( Quaternion const& other ) const\n    { t->prerotate( *other.q ); }\n\n    bool operator ==(Affine3 const& other) const\n    { return (*this->t).matrix() == (*other.t).matrix(); }\n\n    bool isApprox(Affine3 const& other, double tolerance)\n    { return t->isApprox(*other.t, tolerance); }\n};\n\n\nextern \"C\" void Init_eigen()\n{\n     Rice::Module rb_mEigen = define_module(\"Eigen\");\n\n     Data_Type<Vector3> rb_Vector3 = define_class_under<Vector3>(rb_mEigen, \"Vector3\")\n       .define_constructor(Constructor<Vector3,double,double,double>(),\n               (Arg(\"x\") = static_cast<double>(0),\n               Arg(\"y\") = static_cast<double>(0),\n               Arg(\"z\") = static_cast<double>(0)))\n       .define_method(\"__equal__\",  &Vector3::operator ==)\n       .define_method(\"norm\",  &Vector3::norm)\n       .define_method(\"normalize!\",  &Vector3::normalizeBang)\n       .define_method(\"normalize\",  &Vector3::normalize)\n       .define_method(\"[]\",  &Vector3::get)\n       .define_method(\"[]=\",  &Vector3::set)\n       .define_method(\"x\",  &Vector3::x)\n       .define_method(\"y\",  &Vector3::y)\n       .define_method(\"z\",  &Vector3::z)\n       .define_method(\"x=\", &Vector3::setX)\n       .define_method(\"y=\", &Vector3::setY)\n       .define_method(\"z=\", &Vector3::setZ)\n       .define_method(\"+\",  &Vector3::operator +)\n       .define_method(\"-\",  &Vector3::operator -)\n       .define_method(\"/\",  &Vector3::operator /)\n       .define_method(\"-@\", &Vector3::negate)\n       .define_method(\"*\",  &Vector3::scale)\n       .define_method(\"cross\", &Vector3::cross)\n       .define_method(\"dot\",  &Vector3::dot)\n       .define_method(\"approx?\", &Vector3::isApprox, (Arg(\"v\"), Arg(\"tolerance\") = Eigen::NumTraits<double>::dummy_precision()));\n\n     Data_Type<Quaternion> rb_Quaternion = define_class_under<Quaternion>(rb_mEigen, \"Quaternion\")\n       .define_constructor(Constructor<Quaternion,double,double,double,double>())\n       .define_method(\"__equal__\", &Quaternion::operator ==)\n       .define_method(\"w\",  &Quaternion::w)\n       .define_method(\"x\",  &Quaternion::x)\n       .define_method(\"y\",  &Quaternion::y)\n       .define_method(\"z\",  &Quaternion::z)\n       .define_method(\"w=\", &Quaternion::setW)\n       .define_method(\"x=\", &Quaternion::setX)\n       .define_method(\"y=\", &Quaternion::setY)\n       .define_method(\"z=\", &Quaternion::setZ)\n       .define_method(\"norm\", &Quaternion::norm)\n       .define_method(\"concatenate\", &Quaternion::concatenate)\n       .define_method(\"inverse\", &Quaternion::inverse)\n       .define_method(\"transform\", &Quaternion::transform)\n       .define_method(\"matrix\", &Quaternion::matrix)\n       .define_method(\"normalize!\", &Quaternion::normalizeBang)\n       .define_method(\"normalize\", &Quaternion::normalize)\n       .define_method(\"approx?\", &Quaternion::isApprox, (Arg(\"q\"), Arg(\"tolerance\") = Eigen::NumTraits<double>::dummy_precision()))\n       .define_method(\"to_euler\", &Quaternion::toEuler)\n       .define_method(\"from_euler\", &Quaternion::fromEuler)\n       .define_method(\"from_angle_axis\", &Quaternion::fromAngleAxis)\n       .define_method(\"from_matrix\", &Quaternion::fromMatrix);\n\n     Data_Type<AngleAxis> rb_AngleAxis = define_class_under<AngleAxis>(rb_mEigen, \"AngleAxis\")\n       .define_constructor(Constructor<AngleAxis,double,Vector3 const&>())\n       .define_method(\"__equal__\", &AngleAxis::operator ==)\n       .define_method(\"angle\",  &AngleAxis::angle)\n       .define_method(\"axis\",  &AngleAxis::axis)\n       .define_method(\"concatenate\", &AngleAxis::concatenate)\n       .define_method(\"inverse\", &AngleAxis::inverse)\n       .define_method(\"transform\", &AngleAxis::transform)\n       .define_method(\"matrix\", &AngleAxis::matrix)\n       .define_method(\"approx?\", &AngleAxis::isApprox, (Arg(\"q\"), Arg(\"tolerance\") = Eigen::NumTraits<double>::dummy_precision()))\n       .define_method(\"to_euler\", &AngleAxis::toEuler)\n       .define_method(\"from_euler\", &AngleAxis::fromEuler)\n       .define_method(\"from_quaternion\", &AngleAxis::fromQuaternion)\n       .define_method(\"from_matrix\", &AngleAxis::fromMatrix);\n\n     Data_Type<VectorX> rb_VectorX = define_class_under<VectorX>(rb_mEigen, \"VectorX\")\n       .define_constructor(Constructor<VectorX,int>(),\n               (Arg(\"rows\") = static_cast<int>(0)))\n       .define_method(\"resize\", &VectorX::resize)\n       .define_method(\"__equal__\",  &VectorX::operator ==)\n       .define_method(\"norm\",  &VectorX::norm)\n       .define_method(\"normalize!\",  &VectorX::normalizeBang)\n       .define_method(\"normalize\",  &VectorX::normalize)\n       .define_method(\"size\", &VectorX::size)\n       .define_method(\"[]\",  &VectorX::get)\n       .define_method(\"[]=\",  &VectorX::set)\n       .define_method(\"+\",  &VectorX::operator +)\n       .define_method(\"-\",  &VectorX::operator -)\n       .define_method(\"/\",  &VectorX::operator /)\n       .define_method(\"-@\", &VectorX::negate)\n       .define_method(\"*\",  &VectorX::scale)\n       .define_method(\"dot\",  &VectorX::dot)\n       .define_method(\"approx?\", &VectorX::isApprox, (Arg(\"v\"), Arg(\"tolerance\") = Eigen::NumTraits<double>::dummy_precision()));\n\n     Data_Type<Matrix4> rb_Matrix4 = define_class_under<Matrix4>(rb_mEigen, \"Matrix4\")\n       .define_constructor(Constructor<Matrix4>())\n       .define_method(\"__equal__\",  &Matrix4::operator ==)\n       .define_method(\"T\", &Matrix4::transpose)\n       .define_method(\"norm\",  &Matrix4::norm)\n       .define_method(\"rows\", &Matrix4::rows)\n       .define_method(\"cols\", &Matrix4::cols)\n       .define_method(\"size\", &Matrix4::size)\n       .define_method(\"[]\",  &Matrix4::get)\n       .define_method(\"[]=\",  &Matrix4::set)\n       .define_method(\"+\",  &Matrix4::operator +)\n       .define_method(\"-\",  &Matrix4::operator -)\n       .define_method(\"/\",  &Matrix4::operator /)\n       .define_method(\"-@\", &Matrix4::negate)\n       .define_method(\"*\",  &Matrix4::scale)\n       .define_method(\"dotM\",  &Matrix4::dotM)\n       .define_method(\"approx?\", &Matrix4::isApprox, (Arg(\"m\"), Arg(\"tolerance\") = Eigen::NumTraits<double>::dummy_precision()));\n\n     rb_mEigen.const_set(\"ComputeFullU\", INT2FIX(Eigen::ComputeFullU));\n     rb_mEigen.const_set(\"ComputeThinU\", INT2FIX(Eigen::ComputeThinU));\n     rb_mEigen.const_set(\"ComputeThinV\", INT2FIX(Eigen::ComputeThinV));\n\n     Data_Type<JacobiSVD> rb_JacobiSVD = define_class_under<JacobiSVD>(rb_mEigen, \"JacobiSVD\")\n        .define_method(\"solve\", &JacobiSVD::solve);\n\n     Data_Type<MatrixX> rb_MatrixX = define_class_under<MatrixX>(rb_mEigen, \"MatrixX\")\n       .define_constructor(Constructor<MatrixX,int,int>(),\n               (Arg(\"rows\") = static_cast<int>(0),\n                Arg(\"cols\") = static_cast<int>(0)))\n       .define_method(\"resize\", &MatrixX::resize)\n       .define_method(\"__equal__\",  &MatrixX::operator ==)\n       .define_method(\"T\", &MatrixX::transpose)\n       .define_method(\"norm\",  &MatrixX::norm)\n       .define_method(\"rows\", &MatrixX::rows)\n       .define_method(\"cols\", &MatrixX::cols)\n       .define_method(\"size\", &MatrixX::size)\n       .define_method(\"[]\",  &MatrixX::get)\n       .define_method(\"[]=\",  &MatrixX::set)\n       .define_method(\"row\", &MatrixX::getRow)\n       .define_method(\"setRow\", &MatrixX::setRow)\n       .define_method(\"col\", &MatrixX::getColumn)\n       .define_method(\"setCol\", &MatrixX::setColumn)\n       .define_method(\"+\",  &MatrixX::operator +)\n       .define_method(\"-\",  &MatrixX::operator -)\n       .define_method(\"/\",  &MatrixX::operator /)\n       .define_method(\"-@\", &MatrixX::negate)\n       .define_method(\"*\",  &MatrixX::scale)\n       .define_method(\"dotV\",  &MatrixX::dotV)\n       .define_method(\"dotM\",  &MatrixX::dotM)\n       .define_method(\"jacobiSvd\", &MatrixX::jacobiSvd, (Arg(\"flags\") = 0))\n       .define_method(\"approx?\", &MatrixX::isApprox, (Arg(\"m\"), Arg(\"tolerance\") = Eigen::NumTraits<double>::dummy_precision()));\n\n     Data_Type<Isometry3> rb_Isometry3 = define_class_under<Isometry3>(rb_mEigen, \"Isometry3\")\n       .define_constructor(Constructor<Isometry3>())\n       .define_method(\"__equal__\",  &Isometry3::operator ==)\n       .define_method(\"approx?\", &Isometry3::isApprox, (Arg(\"i\"), Arg(\"tolerance\") = Eigen::NumTraits<double>::dummy_precision()))\n       .define_method(\"inverse\", &Isometry3::inverse)\n       .define_method(\"translation\", &Isometry3::translation)\n       .define_method(\"rotation\", &Isometry3::rotation)\n       .define_method(\"concatenate\", &Isometry3::concatenate)\n       .define_method(\"transform\", &Isometry3::transform)\n       .define_method(\"matrix\", &Isometry3::matrix)\n       .define_method(\"translate\", &Isometry3::translate)\n       .define_method(\"pretranslate\", &Isometry3::pretranslate)\n       .define_method(\"rotate\", &Isometry3::rotate)\n       .define_method(\"prerotate\", &Isometry3::prerotate);\n\n     Data_Type<Affine3> rb_Affine3 = define_class_under<Affine3>(rb_mEigen, \"Affine3\")\n       .define_constructor(Constructor<Affine3>())\n       .define_method(\"__equal__\",  &Affine3::operator ==)\n       .define_method(\"approx?\", &Affine3::isApprox, (Arg(\"i\"), Arg(\"tolerance\") = Eigen::NumTraits<double>::dummy_precision()))\n       .define_method(\"inverse\", &Affine3::inverse)\n       .define_method(\"translation\", &Affine3::translation)\n       .define_method(\"rotation\", &Affine3::rotation)\n       .define_method(\"concatenate\", &Affine3::concatenate)\n       .define_method(\"transform\", &Affine3::transform)\n       .define_method(\"matrix\", &Affine3::matrix)\n       .define_method(\"translate\", &Affine3::translate)\n       .define_method(\"pretranslate\", &Affine3::pretranslate)\n       .define_method(\"rotate\", &Affine3::rotate)\n       .define_method(\"prerotate\", &Affine3::prerotate);\n}\n\n", "meta": {"hexsha": "81c2070c2d1aabff9266b9fead8a07f9eed79a0b", "size": 39045, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ext/eigen/eigen.cpp", "max_stars_repo_name": "rock-core/base-ruby_eigen", "max_stars_repo_head_hexsha": "20a1bbd4da2f58e51cd3b2cf75682562b05a6fc6", "max_stars_repo_licenses": ["MIT"], "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/eigen/eigen.cpp", "max_issues_repo_name": "rock-core/base-ruby_eigen", "max_issues_repo_head_hexsha": "20a1bbd4da2f58e51cd3b2cf75682562b05a6fc6", "max_issues_repo_licenses": ["MIT"], "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/eigen/eigen.cpp", "max_forks_repo_name": "rock-core/base-ruby_eigen", "max_forks_repo_head_hexsha": "20a1bbd4da2f58e51cd3b2cf75682562b05a6fc6", "max_forks_repo_licenses": ["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.3432963279, "max_line_length": 131, "alphanum_fraction": 0.6213599693, "num_tokens": 11067, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.49546080444292034}}
{"text": "// Copyright Louis Dionne 2013-2017\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#include <boost/hana/assert.hpp>\n#include <boost/hana/equal.hpp>\n#include <boost/hana/fold_left.hpp>\n#include <boost/hana/integral_constant.hpp>\n#include <boost/hana/plus.hpp>\n#include <boost/hana/string.hpp>\n#include <boost/hana/value.hpp>\nnamespace hana = boost::hana;\n\n\nint main() {\n    auto sum_string = [](auto str) {\n        return hana::fold_left(str, hana::int_c<0>, [](auto sum, auto c) {\n            constexpr int i = hana::value(c) - 48; // convert character to decimal\n            return sum + hana::int_c<i>;\n        });\n    };\n\n    BOOST_HANA_CONSTANT_CHECK(\n        sum_string(BOOST_HANA_STRING(\"1234\")) == hana::int_c<1 + 2 + 3 + 4>\n    );\n}\n", "meta": {"hexsha": "d1d4661ec27ca42968ecb1aed1d6e0cea4ae08d5", "size": 839, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/libs/hana/example/string/foldable.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/hana/example/string/foldable.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/hana/example/string/foldable.cpp", "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": 31.0740740741, "max_line_length": 82, "alphanum_fraction": 0.6615017878, "num_tokens": 232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.769080247656264, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.49546080444292023}}
{"text": "#include <Eigen/Eigen>\n#include <gtest/gtest.h>\n\n#include <aslam/common/entrypoint.h>\n#include <aslam/common/memory.h>\n#include <aslam/common/pose-types.h>\n#include <aslam/triangulation/test/triangulation-fixture.h>\n\nconstexpr size_t kNumObservations = 20;\n\n\nTYPED_TEST(TriangulationFixture, LinearTriangulateFromNViews) {\n  this->setLandmark(kGPoint);\n  this->fillMeasurements(kNumObservations);\n  this->expectSuccess();\n}\n\nclass TriangulationMultiviewTest : public TriangulationFixture<Vector2dList> {};\n\nTEST_F(TriangulationMultiviewTest, linearTriangulateFromNViewsMultiCam) {\n  Aligned<std::vector, Eigen::Vector2d> measurements;\n  Aligned<std::vector, aslam::Transformation> T_G_I;\n  Aligned<std::vector, aslam::Transformation> T_I_C;\n  std::vector<size_t> measurement_camera_indices;\n  Eigen::Vector3d G_point;\n\n  // To make the test simple to write, create 2 cameras and fill observations\n  // for both, then simply append the vectors together.\n  const unsigned int num_cameras = 2;\n  T_I_C.resize(num_cameras);\n\n  for (size_t i = 0; i < T_I_C.size(); ++i) {\n    T_I_C[i].setRandom(0.2, 0.1);\n    Aligned<std::vector, Eigen::Vector2d> cam_measurements;\n    Aligned<std::vector, aslam::Transformation> cam_T_G_I;\n    fillObservations(kNumObservations, T_I_C[i], &cam_measurements, &cam_T_G_I);\n\n    // Append to the end of the vectors.\n    measurements.insert(measurements.end(), cam_measurements.begin(),\n                        cam_measurements.end());\n    T_G_I.insert(T_G_I.end(), cam_T_G_I.begin(), cam_T_G_I.end());\n\n    // Fill in the correct size of camera indices also.\n    measurement_camera_indices.resize(measurements.size(), i);\n  }\n\n  aslam::linearTriangulateFromNViewsMultiCam(measurements,\n      measurement_camera_indices, T_G_I, T_I_C, &G_point);\n\n  EXPECT_TRUE(EIGEN_MATRIX_NEAR(kGPoint, G_point, kDoubleTolerance));\n}\n\nTEST_F(TriangulationMultiviewTest, iterativeGaussNewtonTriangulateFromNViews) {\n  Aligned<std::vector, Eigen::Vector2d> measurements;\n  Aligned<std::vector, aslam::Transformation> T_G_B;\n  Aligned<std::vector, aslam::Transformation> T_B_C;\n  std::vector<size_t> measurement_camera_indices;\n  Eigen::Vector3d G_point;\n\n  // To make the test simple to write, create 1 camera and fill observations,\n  // then simply append the vectors together.\n  const unsigned int num_cameras = 1;\n  T_B_C.resize(num_cameras);\n\n  for (size_t i = 0; i < T_B_C.size(); ++i) {\n    T_B_C[i].setRandom(0.2, 0.1);\n    Aligned<std::vector, Eigen::Vector2d> cam_measurements;\n    Aligned<std::vector, aslam::Transformation> cam_T_G_B;\n    fillObservations(kNumObservations, T_B_C[i], &cam_measurements, &cam_T_G_B);\n\n    // Append to the end of the vectors.\n    measurements.insert(measurements.end(), cam_measurements.begin(),\n                        cam_measurements.end());\n    T_G_B.insert(T_G_B.end(), cam_T_G_B.begin(), cam_T_G_B.end());\n\n    // Fill in the correct size of camera indices also.\n    measurement_camera_indices.resize(measurements.size(), i);\n  }\n\n  aslam::iterativeGaussNewtonTriangulateFromNViews(measurements, T_G_B, T_B_C[0], &G_point);\n\n  EXPECT_TRUE(EIGEN_MATRIX_NEAR(kGPoint, G_point, kDoubleTolerance));\n}\n\nTYPED_TEST(TriangulationFixture, RandomPoses) {\n  constexpr size_t kNumCameraPoses = 5;\n  this->setNMeasurements(kNumCameraPoses);\n\n  // Create a landmark.\n  const double depth = 5.0;\n  this->setLandmark(Eigen::Vector3d(1.0, 1.0, depth));\n\n  // Generate some random camera poses and project the landmark into it.\n  constexpr double kRandomTranslationNorm = 0.1;\n  constexpr double kRandomRotationAngleRad = 20 / 180.0 * M_PI;\n\n  for (size_t pose_idx = 0; pose_idx < kNumCameraPoses; ++pose_idx) {\n    this->T_G_I_[pose_idx].setRandom(kRandomTranslationNorm, kRandomRotationAngleRad);\n  }\n\n  this->inferMeasurements();\n  this->expectSuccess();\n}\n\nTYPED_TEST(TriangulationFixture, TwoParallelRays) {\n  constexpr size_t kNumCameraPoses = 3;\n  this->setNMeasurements(kNumCameraPoses);\n\n  // Create a landmark.\n  const double depth = 5.0;\n  this->setLandmark(Eigen::Vector3d(1.0, 1.0, depth));\n\n  for (size_t pose_idx = 0; pose_idx < kNumCameraPoses; ++pose_idx) {\n    this->T_G_I_[pose_idx].setIdentity();\n  }\n\n  this->inferMeasurements();\n  this->expectFailue();\n}\n\nTYPED_TEST(TriangulationFixture, TwoNearParallelRays) {\n  constexpr size_t kNumCameraPoses = 2;\n  this->setNMeasurements(kNumCameraPoses);\n\n  // Create a landmark.\n  const double depth = 5.0;\n  this->setLandmark(Eigen::Vector3d(1.0, 1.0, depth));\n\n  // Create near parallel rays.\n  aslam::Transformation noise;\n  const double disparity_angle_rad = 0.1 / 180.0 * M_PI;\n\n  const double camera_shift = std::atan(disparity_angle_rad) * depth;\n  noise.setRandom(camera_shift, 0.0);\n  this->T_G_I_[1] = this->T_G_I_[1] * noise;\n\n  this->inferMeasurements();\n  this->expectFailue();\n}\n\nTYPED_TEST(TriangulationFixture, CombinedParallelAndGoodRays) {\n  constexpr size_t kNumCameraPoses = 3;\n  this->setNMeasurements(kNumCameraPoses);\n\n  // Create near parallel rays.\n  aslam::Transformation noise;\n  noise.setRandom(0.01, 0.1);\n  this->T_G_I_[1] = this->T_G_I_[1] * noise;\n\n  this->T_G_I_[2].setRandom(0.5, 0.2);\n\n  // Create a landmark.\n  const double depth = 5.0;\n  this->setLandmark(Eigen::Vector3d(1.0, 1.0, depth));\n\n  this->inferMeasurements();\n  this->expectSuccess();\n}\n\nASLAM_UNITTEST_ENTRYPOINT\n", "meta": {"hexsha": "6a0f791b347705102ec2f9998112cee7c56ee882", "size": 5316, "ext": "cc", "lang": "C++", "max_stars_repo_path": "aslam_cv_triangulation/test/test-triangulation.cc", "max_stars_repo_name": "shuhannod/aslam_cv2", "max_stars_repo_head_hexsha": "4dd48916b9e5b9d5aa56e28894a04d4a25a87348", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 173.0, "max_stars_repo_stars_event_min_datetime": "2017-09-19T18:14:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-20T09:11:15.000Z", "max_issues_repo_path": "aslam_cv_triangulation/test/test-triangulation.cc", "max_issues_repo_name": "shuhannod/aslam_cv2", "max_issues_repo_head_hexsha": "4dd48916b9e5b9d5aa56e28894a04d4a25a87348", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 30.0, "max_issues_repo_issues_event_min_datetime": "2017-11-16T12:46:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-20T04:38:41.000Z", "max_forks_repo_path": "aslam_cv_triangulation/test/test-triangulation.cc", "max_forks_repo_name": "shuhannod/aslam_cv2", "max_forks_repo_head_hexsha": "4dd48916b9e5b9d5aa56e28894a04d4a25a87348", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 58.0, "max_forks_repo_forks_event_min_datetime": "2017-10-24T17:31:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T03:23:24.000Z", "avg_line_length": 33.0186335404, "max_line_length": 92, "alphanum_fraction": 0.7332580888, "num_tokens": 1555, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.49546079762345235}}
{"text": "#include <Eigen/Dense>\n\n#include <ancse/config.hpp>\n#include <ancse/cfl_condition.hpp>\n#include <ancse/fvm_rate_of_change.hpp>\n#include <ancse/snapshot_writer.hpp>\n#include <ancse/time_loop.hpp>\n\nstatic int n_vars = 3;\n\ntemplate<class F>\nEigen::MatrixXd ic(const F &f, const Grid &grid) {\n    Eigen::MatrixXd u0(n_vars, grid.n_cells);\n    for(int i = 0; i < grid.n_cells; ++i) {\n        u0.col(i) = f(cell_center(grid, i));\n    }\n\n    return u0;\n}\n\nTimeLoop make_fvm(const nlohmann::json &config,\n                  const Grid &grid,\n                  std::shared_ptr<Model> &model)\n{\n    double t_end = config[\"t_end\"];\n    double cfl_number = config[\"cfl_number\"];\n\n    auto n_ghost = grid.n_ghost;\n    auto n_cells = grid.n_cells;\n\n    auto n_vars = model->get_nvars();\n\n    auto simulation_time = std::make_shared<SimulationTime>(t_end);\n    auto fvm_rate_of_change\n            = make_fvm_rate_of_change(config, grid, model,\n                                      simulation_time);\n    auto boundary_condition\n            = make_boundary_condition(n_ghost,\n                                      config[\"boundary_condition\"]);\n    auto time_integrator = make_runge_kutta(config,\n                                            fvm_rate_of_change,\n                                            boundary_condition,\n                                            n_vars, n_cells);\n    auto cfl_condition = make_cfl_condition(grid, model, cfl_number);\n    auto snapshot_writer = std::make_shared< JSONSnapshotWriter<FVM> >\n            (grid, model, simulation_time,\n             std::string(config[\"output_dir\"]),\n             std::string(config[\"output_file\"]));\n\n    return TimeLoop(simulation_time, time_integrator,\n                    cfl_condition, snapshot_writer);\n}\n\nvoid sod_shock_tube_test(const nlohmann::json &config)\n{\n    double gamma = 7./5.;\n    std::shared_ptr<Model> model = std::make_shared<Euler>();\n    auto model_euler = dynamic_cast<Euler*>(model.get());\n    model_euler->set_gamma(gamma);\n\n    auto fn = [gamma](double x) {\n        Eigen::VectorXd u(n_vars);\n        if (x <= 0.5) { // left state\n            u(0) = 1;\n            u(1) = 0;\n            u(2) = 1/(gamma-1);\n        } else {        // right state\n            u(0) = 0.125;\n            u(1) = 0;\n            u(2) = 0.1/(gamma-1);\n        }\n        return u;\n    };\n\n    int n_ghost = config[\"n_ghost\"];\n    int n_cells = int(config[\"n_interior_cells\"]) + n_ghost * 2;\n\n    auto grid = Grid({0.0, 1.0}, n_cells, n_ghost);\n    auto u0 = ic(fn, grid);\n\n    auto fvm = make_fvm(config, grid, model);\n    fvm(u0);\n}\n\nvoid vacuum_test(const nlohmann::json &config)\n{\n    double gamma = 7./5.;\n    std::shared_ptr<Model> model = std::make_shared<Euler>();\n    auto model_euler = dynamic_cast<Euler*>(model.get());\n    model_euler->set_gamma(gamma);\n\n    auto fn = [](double x) {\n        Eigen::VectorXd u(n_vars);\n        if (x <= 0.5) { // left state\n            u(0) = 1;\n            u(1) = -2;\n            u(2) = 4.5;\n        } else {        // right state\n            u(0) = 1;\n            u(1) = 2;\n            u(2) = 4.5;\n        }\n        return u;\n    };\n\n    int n_ghost = config[\"n_ghost\"];\n    int n_cells = int(config[\"n_interior_cells\"]) + n_ghost * 2;\n\n    auto grid = Grid({0.0, 1.0}, n_cells, n_ghost);\n    auto u0 = ic(fn, grid);\n\n    auto fvm = make_fvm(config, grid, model);\n    fvm(u0);\n}\n\nvoid lax_shock_tube_test(const nlohmann::json &config)\n{\n    double gamma = 7./5.;\n    std::shared_ptr<Model> model = std::make_shared<Euler>();\n    auto model_euler = dynamic_cast<Euler*>(model.get());\n    model_euler->set_gamma(gamma);\n\n    auto fn = [](double x) {\n        Eigen::VectorXd u(n_vars);\n        if (x <= 0.5) { // left state\n            u(0) = 0.445;\n            u(1) = 0.311;\n            u(2) = 8.928;\n        } else {        // right state\n            u(0) = 0.5;\n            u(1) = 0;\n            u(2) = 1.4275;\n        }\n        return u;\n    };\n\n    int n_ghost = config[\"n_ghost\"];\n    int n_cells = int(config[\"n_interior_cells\"]) + n_ghost * 2;\n\n    auto grid = Grid({0.0, 1.0}, n_cells, n_ghost);\n    auto u0 = ic(fn, grid);\n\n    auto fvm = make_fvm(config, grid, model);\n    fvm(u0);\n}\n\nvoid smooth_test(const nlohmann::json &config)\n{\n    double gamma = 7./5.;\n    std::shared_ptr<Model> model = std::make_shared<Euler>();\n    auto model_euler = dynamic_cast<Euler*>(model.get());\n    model_euler->set_gamma(gamma);\n\n    double a = 0.1;\n    double sigma = 0.1;\n    auto fn = [gamma, a, sigma](double x) {\n        Eigen::VectorXd u(n_vars);\n        u(0) = 1;\n        u(1) = 0;\n        u(2) = (1 + a*exp(-x*x/(sigma*sigma)))/(gamma-1);\n        return u;\n    };\n\n    int n_ghost = config[\"n_ghost\"];\n    int n_cells = int(config[\"n_interior_cells\"]) + n_ghost * 2;\n\n    auto grid = Grid({-1.0, +1.0}, n_cells, n_ghost);\n    auto u0 = ic(fn, grid);\n\n    auto fvm = make_fvm(config, grid, model);\n    fvm(u0);\n}\n\nint main(int argc, char* const argv[])\n{\n    nlohmann::json config;\n    std::string fileName;\n    if (argc == 2) {\n        fileName = argv[1];\n    } else {\n        fileName = \"../config.json\";\n    }\n    config = get_config (fileName);\n\n    std::string ic_key = config[\"initial_conditions\"];\n    if (ic_key == \"sod_shock_tube\") {\n        sod_shock_tube_test(config);\n    } else if (ic_key == \"vacuum\") {\n    vacuum_test(config);\n    } else if (ic_key == \"lax_shock_tube\") {\n        lax_shock_tube_test(config);\n    } else if (ic_key == \"smooth\") {\n        smooth_test(config);\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "4a364aa754764a8a3a3cca57dd249639fa112de4", "size": 5513, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "series2_workbench/hyp_sys_1d/src/fvm_euler.cpp", "max_stars_repo_name": "BeatHubmann/19H-AdvNCSE", "max_stars_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-05T22:38:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-05T22:38:47.000Z", "max_issues_repo_path": "series2_handout/hyp_sys_1d/src/fvm_euler.cpp", "max_issues_repo_name": "BeatHubmann/19H-AdvNCSE", "max_issues_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "series2_handout/hyp_sys_1d/src/fvm_euler.cpp", "max_forks_repo_name": "BeatHubmann/19H-AdvNCSE", "max_forks_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-12-08T20:43:27.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-08T20:43:27.000Z", "avg_line_length": 27.8434343434, "max_line_length": 70, "alphanum_fraction": 0.5470705605, "num_tokens": 1568, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.49546079762345235}}
{"text": "//\n//  ComputeHausdorffDistance.cpp\n//  Elasticity\n//\n//  Created by Wim van Rees on 12/28/16.\n//  Copyright \u00a9 2016 Wim van Rees. All rights reserved.\n//\n\n#include \"ComputeHausdorffDistance.hpp\"\n\n#include <igl/hausdorff.h>\n#include <Eigen/Geometry>\n#include \"WriteVTK.hpp\"\n\n\nReal ComputeHausdorffDistance::compute(const Eigen::Ref<const Eigen::MatrixXd> vertices_A, const Eigen::Ref<const Eigen::MatrixXd> vertices_B, const Eigen::Ref<const Eigen::MatrixXi> faces, const Real rescale) const\n{\n    // compute the least-squares transformation between two point sets\n    //https://eigen.tuxfamily.org/dox/group__Geometry__Module.html#gab3f5a82a24490b936f8694cf8fef8e60\n    \n    const Eigen::MatrixXd trafo = Eigen::umeyama(vertices_A.transpose(), vertices_B.transpose(), rescale);\n    const Eigen::Matrix3d rotmat = trafo.block<3,3>(0,0);\n    const Eigen::Vector3d transv = trafo.block<3,1>(0,3);\n    // now we have the rotation and scaling matrices to transform vertices_A into vertices_B\n    \n    // apply the transform\n    const int nVertices = vertices_A.rows();\n    Eigen::MatrixXd vertices_A_trafo(nVertices,3);\n    for(int i=0;i<nVertices;++i)\n    {\n        const Eigen::Vector3d vertA = vertices_A.row(i);\n        const Eigen::Vector3d vertA_trafo = rotmat * vertA + transv;\n        vertices_A_trafo.row(i) = vertA_trafo;\n    }\n    \n    if(bDump)\n    {\n        WriteVTK writerA(vertices_A, faces);\n        writerA.write(\"haussdorf_A\");\n        \n        WriteVTK writerB(vertices_B, faces);\n        writerB.write(\"haussdorf_B\");\n        \n        WriteVTK writerA_trafo(vertices_A_trafo, faces);\n        writerA_trafo.write(\"haussdorf_A_trafo\");\n    }\n    \n    // compute the distance\n    Real retval;\n//    igl::hausdorff<Eigen::MatrixXd, Eigen::MatrixXi, Eigen::MatrixXd, Eigen::MatrixXi, Real>(vertices_A_trafo, faces, vertices_B, faces, retval);\n    \n    // IGL does not handle Eigen::Ref well -- need to define a reference explicitly\n    const Eigen::MatrixXd & ref_vertices_B = vertices_B;\n    const Eigen::MatrixXi & ref_faces = faces;\n    igl::hausdorff(vertices_A_trafo, ref_faces, ref_vertices_B, ref_faces, retval);\n    \n    return retval;\n}\n", "meta": {"hexsha": "86c838a47f3cfcb33be4bf38a7a818f605c27e1f", "size": 2156, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/libshell/ComputeHausdorffDistance.cpp", "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/ComputeHausdorffDistance.cpp", "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/ComputeHausdorffDistance.cpp", "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": 36.5423728814, "max_line_length": 215, "alphanum_fraction": 0.6957328386, "num_tokens": 590, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.49546079762345224}}
{"text": "#ifndef __POLYNOMIAL_H__\n#define __POLYNOMIAL_H__\n\n#include <iostream>\n#include <vector>\n#include <math.h>\n#include <NTL/ZZ_p.h>\n\n#include \"src/utils/math.hpp\"\n\n// TODO : REFACTOR -> use recursive polynomials\n// TODO : Templatize the class\n\ntypedef std::vector<unsigned int> monomial;\n\nclass MultiVariatePolynomial\n{\npublic:\n    MultiVariatePolynomial(unsigned int arity, unsigned int degree, unsigned int order) : arity(arity), degree(degree), order(order), maxNbElements(binomialCoefficient(degree + arity, degree)), coefficients(maxNbElements)\n    {\n        NTL::ZZ p((long)order);\n        NTL::ZZ_p::init(p);\n    }\n    MultiVariatePolynomial(unsigned int arity, unsigned int degree, unsigned int order, std::vector<NTL::ZZ_p> values) : MultiVariatePolynomial(arity, degree, order)\n    {\n        if (values.size() != this->getMaxNbElements())\n            throw std::invalid_argument(\"Incorrect number of values provided\");\n        coefficients = values;\n    }\n    MultiVariatePolynomial() = delete;\n\n    unsigned int getArity() const\n    {\n        return this->arity;\n    };\n    void setArity(unsigned int arity)\n    {\n        this->arity = arity;\n    };\n    unsigned int getDegree() const\n    {\n        return this->degree;\n    };\n    void setDegree(unsigned int degree)\n    {\n        this->degree = degree;\n    };\n    unsigned int getOrder() const\n    {\n        return this->order;\n    };\n    void setOrder(unsigned int order)\n    {\n        this->order = order;\n    };\n\n    unsigned int getMaxNbElements() const\n    {\n        return this->maxNbElements;\n    };\n\n    void setElement(std::vector<unsigned int>& monomial, NTL::ZZ_p value);\n\n    void setElement(unsigned int index, NTL::ZZ_p value);\n\n    NTL::ZZ_p getElement(std::vector<unsigned int>& monomial) const;\n\n    NTL::ZZ_p getElement(unsigned int index) const;\n\n    void print() const;\n\n    std::string to_string() const;\n\n    MultiVariatePolynomial add(const MultiVariatePolynomial& other) const;\n    MultiVariatePolynomial operator+(const MultiVariatePolynomial& other) const;\n\n    MultiVariatePolynomial sub(const MultiVariatePolynomial& other) const;\n    MultiVariatePolynomial operator-(const MultiVariatePolynomial& other) const;\n\n    NTL::ZZ_p evaluate(std::vector<NTL::ZZ_p>& point) const;\n\n    static MultiVariatePolynomial interpolate(std::vector<std::vector<NTL::ZZ_p>>& known_values, int degree, int arity, int order);\n\nprivate:\n    unsigned int arity;\n    unsigned int degree;\n    unsigned int order;\n    unsigned int maxNbElements;\n    std::vector<NTL::ZZ_p> coefficients;\n};\n\n#endif // __POLYNOMIAL_H__\n", "meta": {"hexsha": "799a1c61f7b8ae61ff3c348c6f862c563881494f", "size": 2581, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/polynomial/polynomial.hpp", "max_stars_repo_name": "pierreeliseeflory/PANDA", "max_stars_repo_head_hexsha": "871ac4db92e3ed0a769b1a1f69c67d8ccdaf911d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/polynomial/polynomial.hpp", "max_issues_repo_name": "pierreeliseeflory/PANDA", "max_issues_repo_head_hexsha": "871ac4db92e3ed0a769b1a1f69c67d8ccdaf911d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/polynomial/polynomial.hpp", "max_forks_repo_name": "pierreeliseeflory/PANDA", "max_forks_repo_head_hexsha": "871ac4db92e3ed0a769b1a1f69c67d8ccdaf911d", "max_forks_repo_licenses": ["Apache-2.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.752688172, "max_line_length": 221, "alphanum_fraction": 0.6850058117, "num_tokens": 637, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.49546079762345224}}
{"text": "/* -*-c++-*--------------------------------------------------------------------\n * 2018 Bernd Pfrommer bernd.pfrommer@gmail.com\n */\n\n#include \"tagslam/yaml_utils.h\"\n#include <boost/range/irange.hpp>\n#include <XmlRpcException.h>\n#include <Eigen/Geometry>\n#include <cmath>\n\nnamespace tagslam {\n  using boost::irange;\n  using std::sqrt;\n  using std::fixed;\n  using std::setw;\n  using std::setprecision;\n\n#define FMT(X, Y) fixed << setw(X) << setprecision(Y)\n\n  namespace yaml_utils {\n    static void write_vec(std::ostream &of,\n                          const string &prefix,\n                          double x, double y, double z) {\n      const int p(8);\n      of.precision(p);\n      of << prefix << \"x: \" << std::fixed << x << std::endl;\n      of << prefix << \"y: \" << std::fixed << y << std::endl;\n      of << prefix << \"z: \" << std::fixed << z << std::endl;\n    }\n\n\n    void write_pose(std::ostream &of, const string &prefix,\n                    const Transform &pose,\n                    const PoseNoise &n, bool writeNoise) {\n      Eigen::AngleAxisd aa(pose.linear());\n      Point3d r = aa.angle() * aa.axis();\n      Point3d t(pose.translation());\n      const string pps = prefix + \"  \";\n      of << prefix << \"position:\" << std::endl;\n      write_vec(of, pps, t(0), t(1), t(2));\n      of << prefix << \"rotation:\" << std::endl;\n      write_vec(of, pps, r(0), r(1), r(2));\n      if (writeNoise) {\n        Eigen::Matrix<double, 6, 1> diag = n.getDiagonal();\n        of << prefix << \"position_noise:\" << std::endl;\n        write_vec(of, pps, sqrt(diag(3)),sqrt(diag(4)),sqrt(diag(5)));\n        of << prefix << \"rotation_noise:\" << std::endl;\n        write_vec(of, pps, sqrt(diag(0)),sqrt(diag(1)),sqrt(diag(2)));\n      }\n    }\n\n    void write_matrix(std::ostream &of, const string &prefix,\n                      const Transform &pose) {\n      const auto m = pose.matrix();\n      for (const auto i: irange(0, 4)) {\n        of << prefix << \"- [\";\n        for (const auto j: irange(0, 3)) {\n          of << FMT(12,8) << m(i, j) << \",\";\n        }\n        of << FMT(12,8) << m(i, 3) << \"]\" << std::endl;\n      }\n    }\n  \n    void write_pose_with_covariance(std::ostream &of,\n                                    const string &prefix,\n                                    const Transform &pose,\n                                    const PoseNoise &n) {\n      Eigen::AngleAxisd aa;\n      aa.fromRotationMatrix(pose.rotation());\n      Eigen::Vector3d r = aa.angle() * aa.axis();\n      Eigen::Vector3d t = pose.translation();\n      const string pps = prefix + \"  \";\n      of << prefix << \"position:\" << std::endl;\n      write_vec(of, pps, t(0), t(1), t(2));\n      of << prefix << \"rotation:\" << std::endl;\n      write_vec(of, pps, r(0), r(1), r(2));\n      of << prefix << \"R:\" << std::endl;\n      const auto R = n.convertToR();\n      of << prefix << \"  [ \";\n      for (const auto i: irange(0l, R.rows())) {\n        for (const auto j: irange(0l, R.cols())) {\n          of << R(i, j);\n          if (i != R.rows() - 1 || j != R.cols() - 1) {\n            of << \", \";\n          }\n        }\n        if (i != R.rows() - 1) {\n          of << std::endl << prefix << \"    \";\n        }\n      }\n      of << \" ]\" << std::endl;\n    }\n  }\n}  // namespace\n", "meta": {"hexsha": "fd72ba3942ff5e0772f380cee616a851821a3ec7", "size": 3229, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/yaml_utils.cpp", "max_stars_repo_name": "Shuhei-YOSHIDA/tagslam", "max_stars_repo_head_hexsha": "1fa3bef064696b289fece0c98b92001b3fb84fae", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 210.0, "max_stars_repo_stars_event_min_datetime": "2018-04-04T12:34:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T03:49:46.000Z", "max_issues_repo_path": "src/yaml_utils.cpp", "max_issues_repo_name": "Shuhei-YOSHIDA/tagslam", "max_issues_repo_head_hexsha": "1fa3bef064696b289fece0c98b92001b3fb84fae", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2018-11-05T22:05:29.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-01T02:30:57.000Z", "max_forks_repo_path": "src/yaml_utils.cpp", "max_forks_repo_name": "Shuhei-YOSHIDA/tagslam", "max_forks_repo_head_hexsha": "1fa3bef064696b289fece0c98b92001b3fb84fae", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 58.0, "max_forks_repo_forks_event_min_datetime": "2018-04-30T02:43:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-28T16:48:55.000Z", "avg_line_length": 33.9894736842, "max_line_length": 79, "alphanum_fraction": 0.475069681, "num_tokens": 900, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851919, "lm_q2_score": 0.6442251133170357, "lm_q1q2_score": 0.49546079605731425}}
{"text": "\n\n\n\n#include <stdlib.h>\n#include <assert.h>\n#include <stdint.h>\n#include <string.h>\n#include <iostream>\n\n#include <boost/array.hpp>\n\n#include \"tools/debug.hpp\"\n#include \"tools/get_char.hpp\"\n#include \"tools/insertion_sort.hpp\"\n#include \"tools/losertree.hpp\"\n#include \"../tools/contest.hpp\"\n\nnamespace rantala {\n\nvoid mergesort_4way(unsigned char**, size_t, unsigned char**);\n\ntemplate <unsigned K>\nstatic void\nmergesort_losertree(unsigned char** strings, size_t n, unsigned char** tmp)\n{\n\tif (n < 0x10000) {\n\t\tmergesort_4way(strings, n, tmp);\n\t\treturn;\n\t}\n\tdebug() << __func__ << \"(), n=\"<<n<<\"\\n\";\n\tconst size_t split = size_t(double(n) / double(K));\n\tboost::array<std::pair<unsigned char**, size_t>, K> ranges;\n\tfor (unsigned i=0; i < K-1; ++i) {\n\t\tranges[i] = std::make_pair(strings+i*split, split);\n\t}\n\tranges[K-1] = std::make_pair(strings+(K-1)*split, n-(K-1)*split);\n\tfor (unsigned i=0; i < K; ++i) {\n\t\tmergesort_losertree<K>(ranges[i].first, ranges[i].second,\n\t\t\t\ttmp+(ranges[i].first-strings));\n\t}\n\tunsigned char** result = tmp;\n\tloser_tree<unsigned char*> tree(ranges.begin(), ranges.end());\n\twhile (tree._nonempty_streams) { *result++ = tree.min(); }\n\t(void) memcpy(strings, tmp, n*sizeof(unsigned char*));\n}\n\nvoid mergesort_losertree_64way(unsigned char** strings, size_t n)\n{\n\tunsigned char** tmp = static_cast<unsigned char**>(\n\t\t\tmalloc(n*sizeof(unsigned char*)));\n\tmergesort_losertree<64>(strings, n, tmp);\n\tfree(tmp);\n}\nvoid mergesort_losertree_128way(unsigned char** strings, size_t n)\n{\n\tunsigned char** tmp = static_cast<unsigned char**>(\n\t\t\tmalloc(n*sizeof(unsigned char*)));\n\tmergesort_losertree<128>(strings, n, tmp);\n\tfree(tmp);\n}\nvoid mergesort_losertree_256way(unsigned char** strings, size_t n)\n{\n\tunsigned char** tmp = static_cast<unsigned char**>(\n\t\t\tmalloc(n*sizeof(unsigned char*)));\n\tmergesort_losertree<256>(strings, n, tmp);\n\tfree(tmp);\n}\nvoid mergesort_losertree_512way(unsigned char** strings, size_t n)\n{\n\tunsigned char** tmp = static_cast<unsigned char**>(\n\t\t\tmalloc(n*sizeof(unsigned char*)));\n\tmergesort_losertree<512>(strings, n, tmp);\n\tfree(tmp);\n}\nvoid mergesort_losertree_1024way(unsigned char** strings, size_t n)\n{\n\tunsigned char** tmp = static_cast<unsigned char**>(\n\t\t\tmalloc(n*sizeof(unsigned char*)));\n\tmergesort_losertree<1024>(strings, n, tmp);\n\tfree(tmp);\n}\n\nPSS_CONTESTANT(mergesort_losertree_64way,\n               \"rantala/mergesort_losertree_64way\",\n               \"mergesort 64way loser tree based\")\nPSS_CONTESTANT(mergesort_losertree_128way,\n               \"rantala/mergesort_losertree_128way\",\n               \"mergesort 128way loser tree based\")\nPSS_CONTESTANT(mergesort_losertree_256way,\n               \"rantala/mergesort_losertree_256way\",\n               \"mergesort 256way loser tree based\")\nPSS_CONTESTANT(mergesort_losertree_512way,\n               \"rantala/mergesort_losertree_512way\",\n               \"mergesort 512way loser tree based\")\nPSS_CONTESTANT(mergesort_losertree_1024way,\n               \"rantala/mergesort_losertree_1024way\",\n               \"mergesort 1024way loser tree based\")\n\nvoid mergesort_4way_parallel(unsigned char**, size_t, unsigned char**);\n\ntemplate <unsigned K>\nstatic void\nmergesort_losertree_parallel(unsigned char** strings, size_t n, unsigned char** tmp)\n{\n\tif (n < 0x10000) {\n\t\tmergesort_4way_parallel(strings, n, tmp);\n\t\treturn;\n\t}\n\tdebug() << __func__ << \"(), n=\"<<n<<\"\\n\";\n\tconst size_t split = size_t(double(n) / double(K));\n\tboost::array<std::pair<unsigned char**, size_t>, K> ranges;\n\tfor (unsigned i=0; i < K-1; ++i) {\n\t\tranges[i] = std::make_pair(strings+i*split, split);\n\t}\n\tranges[K-1] = std::make_pair(strings+(K-1)*split, n-(K-1)*split);\n#pragma omp parallel for\n\tfor (unsigned i=0; i < K; ++i) {\n\t\tmergesort_losertree_parallel<K>(ranges[i].first, ranges[i].second,\n\t\t\t\ttmp+(ranges[i].first-strings));\n\t}\n\tunsigned char** result = tmp;\n\tloser_tree<unsigned char*> tree(ranges.begin(), ranges.end());\n\twhile (tree._nonempty_streams) { *result++ = tree.min(); }\n\t(void) memcpy(strings, tmp, n*sizeof(unsigned char*));\n}\n\nvoid mergesort_losertree_64way_parallel(unsigned char** strings, size_t n)\n{\n\tunsigned char** tmp = static_cast<unsigned char**>(\n\t\t\tmalloc(n*sizeof(unsigned char*)));\n\tmergesort_losertree_parallel<64>(strings, n, tmp);\n\tfree(tmp);\n}\nvoid mergesort_losertree_128way_parallel(unsigned char** strings, size_t n)\n{\n\tunsigned char** tmp = static_cast<unsigned char**>(\n\t\t\tmalloc(n*sizeof(unsigned char*)));\n\tmergesort_losertree_parallel<128>(strings, n, tmp);\n\tfree(tmp);\n}\nvoid mergesort_losertree_256way_parallel(unsigned char** strings, size_t n)\n{\n\tunsigned char** tmp = static_cast<unsigned char**>(\n\t\t\tmalloc(n*sizeof(unsigned char*)));\n\tmergesort_losertree_parallel<256>(strings, n, tmp);\n\tfree(tmp);\n}\nvoid mergesort_losertree_512way_parallel(unsigned char** strings, size_t n)\n{\n\tunsigned char** tmp = static_cast<unsigned char**>(\n\t\t\tmalloc(n*sizeof(unsigned char*)));\n\tmergesort_losertree_parallel<512>(strings, n, tmp);\n\tfree(tmp);\n}\nvoid mergesort_losertree_1024way_parallel(unsigned char** strings, size_t n)\n{\n\tunsigned char** tmp = static_cast<unsigned char**>(\n\t\t\tmalloc(n*sizeof(unsigned char*)));\n\tmergesort_losertree_parallel<1024>(strings, n, tmp);\n\tfree(tmp);\n}\n\nPSS_CONTESTANT_PARALLEL(mergesort_losertree_64way_parallel,\n                        \"rantala/mergesort_losertree_64way_parallel\",\n                        \"mergesort parallel 64way loser tree based\")\nPSS_CONTESTANT_PARALLEL(mergesort_losertree_128way_parallel,\n                        \"rantala/mergesort_losertree_128way_parallel\",\n                        \"mergesort parallel 128way loser tree based\")\nPSS_CONTESTANT_PARALLEL(mergesort_losertree_256way_parallel,\n                        \"rantala/mergesort_losertree_256way_parallel\",\n                        \"mergesort parallel 256way loser tree based\")\nPSS_CONTESTANT_PARALLEL(mergesort_losertree_512way_parallel,\n                        \"rantala/mergesort_losertree_512way_parallel\",\n                        \"mergesort parallel 512way loser tree based\")\nPSS_CONTESTANT_PARALLEL(mergesort_losertree_1024way_parallel,\n                        \"rantala/mergesort_losertree_1024way_parallel\",\n                        \"mergesort parallel 1024way loser tree based\")\n\n} \n", "meta": {"hexsha": "aa29ffb7f8eb6ec1d3cc645e942858ae383a74b9", "size": 6215, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "datasets/github_cpp_10/7/137.cpp", "max_stars_repo_name": "yijunyu/demo-fast", "max_stars_repo_head_hexsha": "11c0c84081a3181494b9c469bda42a313c457ad2", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-05-03T19:27:45.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-03T19:27:45.000Z", "max_issues_repo_path": "datasets/github_cpp_10/7/137.cpp", "max_issues_repo_name": "yijunyu/demo-vscode-fast", "max_issues_repo_head_hexsha": "11c0c84081a3181494b9c469bda42a313c457ad2", "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": "datasets/github_cpp_10/7/137.cpp", "max_forks_repo_name": "yijunyu/demo-vscode-fast", "max_forks_repo_head_hexsha": "11c0c84081a3181494b9c469bda42a313c457ad2", "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.3370165746, "max_line_length": 84, "alphanum_fraction": 0.6989541432, "num_tokens": 1759, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289836, "lm_q2_score": 0.6513548714339145, "lm_q1q2_score": 0.49545351514904284}}
{"text": "/*\n * fclayer.cpp\n *\n * Feed-forward:\n *    z(l) = a(l-1) * w + b // where * (vector, matrix) multiplication\n *    a(l) = activation(z(l))\n *\n * Back propagation:\n *    delta(l) = elem_prod(gradient(C, a(l)), activation_derivative(z(l)))\n *    dC/db(l) = delta(l)\n *    dC/dw(l) = a(l-1) * delta(l)\n *    gradient(C, a(l - 1)) = transp(w) * delta(l)\n */\n#include <boost/assert.hpp>\n\n#include \"core/utils.h\"\n#include \"core/random.h\"\n#include \"core/functions.h\"\n#include \"fclayer.h\"\n\nusing namespace std;\nusing namespace boost;\nusing namespace yann;\n\n\nnamespace yann {\n\n////////////////////////////////////////////////////////////////////////////////////////////////\n//\n// FullyConnectedLayer_Context implementation\n//\nclass FullyConnectedLayer_Context :\n    public Layer::Context\n{\n  typedef Layer::Context Base;\n\n  friend class FullyConnectedLayer;\n\npublic:\n  FullyConnectedLayer_Context(const MatrixSize & output_size,\n                              const MatrixSize & batch_size) :\n    Base(output_size, batch_size)\n  {\n    YANN_CHECK_GT(output_size, 0);\n    YANN_CHECK_GT(batch_size, 0);\n    _zz.resize(get_batch_size(), get_output_size());\n  }\n\n  FullyConnectedLayer_Context(const RefVectorBatch & output) :\n    Base(output)\n  {\n    YANN_CHECK_GT(yann::get_batch_size(output), 0);\n    YANN_CHECK_GT(yann::get_batch_item_size(output), 0);\n\n    _zz.resize(get_batch_size(), get_output_size());\n  }\n\nprotected:\n  VectorBatch              _zz;\n}; // class FullyConnectedLayer_Context\n\n////////////////////////////////////////////////////////////////////////////////////////////////\n//\n// FullyConnectedLayer_TrainingContext implementation\n//\nclass FullyConnectedLayer_TrainingContext :\n    public FullyConnectedLayer_Context\n{\n  typedef FullyConnectedLayer_Context Base;\n\n  typedef vector<pair<MatrixSize, Value>> SamplingSortingVector;\n  typedef vector<MatrixSize> SamplingCounterVector;\n\n  friend class FullyConnectedLayer;\n\npublic:\n  FullyConnectedLayer_TrainingContext(\n      const MatrixSize & input_size,\n      const MatrixSize & output_size,\n      const MatrixSize & batch_size,\n      const unique_ptr<Layer::Updater> & updater,\n      bool is_sampled) :\n    Base(output_size, batch_size),\n    _ww_updater(updater->copy()),\n    _bb_updater(updater->copy())\n  {\n    YANN_CHECK_GT(input_size, 0);\n\n    _delta_ww.resize(input_size, get_output_size());\n    _delta_bb.resize(get_output_size());\n    _delta.resizeLike(_zz);\n\n    _sigma_derivative_zz.resizeLike(_zz);\n    _collapse_vector = Vector::Ones(get_batch_size());\n\n    _ww_updater->init(input_size, get_output_size());\n    _bb_updater->init(1, get_output_size()); // RowMajor\n\n    if(is_sampled) {\n      _sampling_gradient_out_sorting = SamplingSortingVector(get_output_size());\n      _sampling_counter = SamplingCounterVector(get_output_size(), 0);\n    }\n  }\n\n  FullyConnectedLayer_TrainingContext(\n      const MatrixSize & input_size,\n      const RefVectorBatch & output,\n      const unique_ptr<Layer::Updater> & updater,\n      bool is_sampled) :\n    Base(output),\n    _ww_updater(updater->copy()),\n    _bb_updater(updater->copy())\n  {\n    YANN_CHECK_GT(input_size, 0);\n\n    _delta_ww.resize(input_size, get_output_size());\n    _delta_bb.resize(get_output_size());\n    _delta.resizeLike(_zz);\n\n    _sigma_derivative_zz.resizeLike(_zz);\n    _collapse_vector = Vector::Ones(get_batch_size());\n\n    _ww_updater->init(input_size, get_output_size());\n    _bb_updater->init(1, get_output_size()); // RowMajor\n\n    if(is_sampled) {\n      _sampling_gradient_out_sorting = SamplingSortingVector(get_output_size());\n      _sampling_counter = SamplingCounterVector(get_output_size(), 0);\n    }\n  }\n\n  // Layer::Context overwrites\n  virtual void start_epoch()\n  {\n    YANN_SLOW_CHECK(_ww_updater);\n    YANN_SLOW_CHECK(_bb_updater);\n\n    Base::start_epoch();\n\n    _ww_updater->start_epoch();\n    _bb_updater->start_epoch();\n  }\n\n  virtual void reset_state()\n  {\n    YANN_SLOW_CHECK(_ww_updater);\n    YANN_SLOW_CHECK(_bb_updater);\n\n    Base::reset_state();\n\n    _delta_ww.setZero();\n    _delta_bb.setZero();\n\n    _ww_updater->reset();\n    _bb_updater->reset();\n\n    if(_sampling_counter) {\n      fill(_sampling_counter->begin(), _sampling_counter->end(), 0);\n    }\n  }\n\nprivate:\n  Matrix _delta_ww;\n  Vector _delta_bb;\n  VectorBatch _delta;\n\n  VectorBatch _sigma_derivative_zz;\n  Vector _collapse_vector;\n\n  unique_ptr<Layer::Updater> _ww_updater;\n  unique_ptr<Layer::Updater> _bb_updater;\n\n  // sampling support\n  optional<SamplingSortingVector> _sampling_gradient_out_sorting;\n  optional<SamplingCounterVector> _sampling_counter;\n}; // class FullyConnectedLayer_TrainingContext\n\n}; // namespace yann\n\n////////////////////////////////////////////////////////////////////////////////////////////////\n//\n// yann::FullyConnectedLayer implementation\n//\nyann::FullyConnectedLayer::FullyConnectedLayer(const MatrixSize & input_size,\n                                               const MatrixSize & output_size) :\n    _ww(input_size, output_size),\n    _bb(output_size),\n    _fixed_bias(false),\n    _sampling_rate(2.0), // bigger than 1.0\n    _activation_function(new SigmoidFunction())\n{\n}\n\nyann::FullyConnectedLayer::~FullyConnectedLayer()\n{\n}\n\nvoid yann::FullyConnectedLayer::set_activation_function(\n    const unique_ptr<ActivationFunction> & activation_function)\n{\n  YANN_CHECK(activation_function);\n  _activation_function = activation_function->copy();\n}\n\nvoid yann::FullyConnectedLayer::set_values(const Matrix & ww, const Vector & bb)\n{\n  YANN_CHECK(is_same_size(ww, _ww));\n  YANN_CHECK(is_same_size(bb, _bb));\n  _ww = ww;\n  _bb = bb;\n}\n\nvoid yann::FullyConnectedLayer::set_fixed_bias(const Value & val)\n{\n  _bb.setConstant(val);\n  _fixed_bias = true;\n}\n\nvoid yann::FullyConnectedLayer::set_sampling_rate(const double & sampling_rate)\n{\n  YANN_CHECK_GE(sampling_rate, 0.0);\n  YANN_CHECK_LE(sampling_rate, 1.0);\n  _sampling_rate = sampling_rate;\n}\n\nbool yann::FullyConnectedLayer::is_sampled() const\n{\n  return 0 < _sampling_rate && _sampling_rate < 1.0;\n}\n\n// Layer overwrites\nbool yann::FullyConnectedLayer::is_valid() const\n{\n  if(!Base::is_valid()) {\n    return false;\n  }\n  if(!_activation_function) {\n    return false;\n  }\n  if(_ww.cols() != _bb.size()) {\n    return false;\n  }\n  return true;\n}\n\nstd::string yann::FullyConnectedLayer::get_name() const\n{\n  return \"FullyConnectedLayer\";\n}\n\nstring yann::FullyConnectedLayer::get_info() const\n{\n  YANN_CHECK(is_valid());\n\n  ostringstream oss;\n  oss << Base::get_info()\n      << \" activation: \" << _activation_function->get_info()\n      ;\n  return oss.str();\n}\n\nbool yann::FullyConnectedLayer::is_equal(const Layer & other, double tolerance) const\n{\n  if(!Base::is_equal(other, tolerance)) {\n    return false;\n  }\n  auto the_other = dynamic_cast<const FullyConnectedLayer*>(&other);\n  if(the_other == nullptr) {\n    return false;\n  }\n  // TOOD: add deep compare\n  if(_activation_function->get_info() != the_other->_activation_function->get_info()) {\n    return false;\n  }\n  if(_fixed_bias != the_other->_fixed_bias) {\n    return false;\n  }\n  if(!_ww.isApprox(the_other->_ww, tolerance)) {\n    return false;\n  }\n  if(!_bb.isApprox(the_other->_bb, tolerance)) {\n    return false;\n  }\n  return true;\n}\n\nMatrixSize yann::FullyConnectedLayer::get_input_size() const\n{\n  return _ww.rows();\n}\n\nMatrixSize yann::FullyConnectedLayer::get_output_size() const\n{\n  return _ww.cols();\n}\n\nunique_ptr<Layer::Context> yann::FullyConnectedLayer::create_context(const MatrixSize & batch_size) const\n{\n  YANN_CHECK(is_valid());\n  return make_unique<FullyConnectedLayer_Context>(get_output_size(), batch_size);\n}\nunique_ptr<Layer::Context> yann::FullyConnectedLayer::create_context(const RefVectorBatch & output) const\n{\n  YANN_CHECK(is_valid());\n  return make_unique<FullyConnectedLayer_Context>(output);\n}\nunique_ptr<Layer::Context> yann::FullyConnectedLayer::create_training_context(\n    const MatrixSize & batch_size, const std::unique_ptr<Layer::Updater> & updater) const\n{\n  YANN_CHECK(is_valid());\n  YANN_CHECK(updater);\n  return make_unique<FullyConnectedLayer_TrainingContext>(\n      get_input_size(), get_output_size(), batch_size, updater, is_sampled());\n}\nunique_ptr<Layer::Context> yann::FullyConnectedLayer::create_training_context(\n    const RefVectorBatch & output, const std::unique_ptr<Layer::Updater> & updater) const\n{\n  YANN_CHECK(is_valid());\n  YANN_CHECK(updater);\n  return make_unique<FullyConnectedLayer_TrainingContext>(\n      get_input_size(), output, updater, is_sampled());\n}\n\ntemplate<typename InputType>\nvoid yann::FullyConnectedLayer::feedforward_internal(\n    const InputType & input,\n    Context * context,\n    enum OperationMode mode) const\n{\n  auto ctx = dynamic_cast<FullyConnectedLayer_Context *>(context);\n  YANN_CHECK(ctx);\n  YANN_CHECK(is_valid());\n  YANN_CHECK_EQ(get_batch_size(input), ctx->get_batch_size());\n  YANN_CHECK_EQ(get_batch_item_size(input), get_input_size());\n\n  // z(l) = a(l-1)*w + b\n  ctx->_zz.noalias() = MatrixFunctions<InputType>::product(input, _ww);\n  plus_batches(ctx->_zz, _bb);\n\n  // a(l) = activation(z(l))\n  YANN_CHECK(is_same_size(ctx->_zz, ctx->get_output()));\n  _activation_function->f(ctx->_zz, ctx->get_output(), mode);\n}\n\nvoid yann::FullyConnectedLayer::feedforward(\n    const RefConstVectorBatch & input,\n    Context * context,\n    enum OperationMode mode) const\n{\n  feedforward_internal(input, context, mode);\n}\n\nvoid yann::FullyConnectedLayer::feedforward(\n    const RefConstSparseVectorBatch & input,\n    Context * context,\n    enum OperationMode mode) const\n{\n  feedforward_internal(input, context, mode);\n}\n\ntemplate<typename InputType>\nvoid yann::FullyConnectedLayer::backprop_internal(\n    const RefConstVectorBatch & gradient_output,\n    const InputType & input,\n    optional<RefVectorBatch> gradient_input,\n    Context * context) const\n{\n  auto ctx = dynamic_cast<FullyConnectedLayer_TrainingContext *>(context);\n  YANN_CHECK(ctx);\n  YANN_CHECK(is_valid());\n  YANN_CHECK_GT(get_batch_size(gradient_output), 0);\n  YANN_CHECK_EQ(get_batch_item_size(gradient_output), get_output_size());\n  YANN_CHECK_EQ(get_batch_size(input), get_batch_size(gradient_output));\n  YANN_CHECK_EQ(get_batch_item_size(input), get_input_size());\n  YANN_CHECK_EQ(get_batch_item_size(input), get_input_size());\n  YANN_CHECK(!gradient_input || is_same_size(input, *gradient_input));\n\n  // just to make it easier to read\n  const auto & zz = ctx->_zz;\n  auto & sigma_derivative_zz = ctx->_sigma_derivative_zz;\n  auto & delta = ctx->_delta;\n  const auto & collapse_vector = ctx->_collapse_vector;\n  auto & delta_ww = ctx->_delta_ww;\n  auto & delta_bb = ctx->_delta_bb;\n  const auto batch_size = get_batch_size(input);\n\n  // delta(l) = elem_prod(gradient(C, a(l)), activation_derivative(z(l)))\n  YANN_CHECK(is_same_size(zz, sigma_derivative_zz));\n  YANN_CHECK(is_same_size(zz, gradient_output));\n  _activation_function->derivative(zz, sigma_derivative_zz);\n  delta.array() = gradient_output.array() * sigma_derivative_zz.array();\n\n  // update deltas\n  // dC/db(l) = delta(l)\n  // dC/dw(l) = a(l-1) * delta(l)\n  YANN_CHECK_EQ(collapse_vector.size(), get_batch_size(delta));\n  YANN_CHECK_EQ(delta_bb.size(), get_output_size());\n  YANN_CHECK_EQ(batch_size,  get_batch_size(gradient_output));\n  YANN_CHECK(is_same_size(delta_ww, _ww));\n  YANN_CHECK(is_same_size(delta_bb, _bb));\n  delta_ww.noalias() += MatrixFunctions<InputType>::product(input.transpose(), delta);\n  if(!_fixed_bias) {\n    delta_bb.noalias() += MatrixFunctions<InputType>::product(collapse_vector, delta);\n  }\n\n  // we don't need to calculate the gradient(C, a(l)) for the \"first\" layer (actual inputs)\n  // gradient(C, a(l - 1)) = transp(w) * delta(l)\n  if(gradient_input) {\n    (*gradient_input).noalias() = MatrixFunctions<InputType>::product(delta, _ww.transpose());\n  }\n}\n\n\ntemplate<typename InputType>\nvoid yann::FullyConnectedLayer::backprop_with_sampling_internal(\n    const RefConstVectorBatch & gradient_output,\n    const InputType & input,\n    optional<RefVectorBatch> gradient_input,\n    Context * context) const\n{\n  auto ctx = dynamic_cast<FullyConnectedLayer_TrainingContext *>(context);\n  YANN_CHECK(ctx);\n  YANN_CHECK(ctx->_sampling_gradient_out_sorting);\n  YANN_CHECK(ctx->_sampling_counter);\n  YANN_CHECK(is_valid());\n  YANN_CHECK(is_sampled());\n  YANN_CHECK_GT(get_batch_size(gradient_output), 0);\n  YANN_CHECK_EQ(get_batch_item_size(gradient_output), get_output_size());\n  YANN_CHECK_EQ(get_batch_size(input), get_batch_size(gradient_output));\n  YANN_CHECK_EQ(get_batch_item_size(input), get_input_size());\n  YANN_CHECK_EQ(get_batch_item_size(input), get_input_size());\n  YANN_CHECK(!gradient_input || is_same_size(input, *gradient_input));\n\n  // one row at a time\n  const auto batch_size = get_batch_size(input);\n  const auto output_size = get_output_size();\n  const MatrixSize sampled_num = get_output_size() * _sampling_rate;\n  auto & delta_ww = ctx->_delta_ww;\n  auto & delta_bb = ctx->_delta_bb;\n  YANN_SLOW_CHECK_EQ(delta_bb.size(), get_output_size());\n  auto & sampling_gradient_out_sorting = *(ctx->_sampling_gradient_out_sorting);\n  auto & sampling_counter = *(ctx->_sampling_counter);\n\n  YANN_SLOW_CHECK(is_same_size(delta_ww, _ww));\n  YANN_SLOW_CHECK(is_same_size(delta_bb, _bb));\n\n  if(gradient_input) {\n    gradient_input->setZero();\n  }\n\n  for(MatrixSize batch_pos = 0; batch_pos < batch_size; ++batch_pos) {\n    // just to make it easier to read\n    const auto in = get_batch(input, batch_pos);\n    const auto gradient_out = get_batch(gradient_output, batch_pos);\n    const auto zz = get_batch(ctx->_zz, batch_pos);\n    const auto sigma_derivative_zz = get_batch(ctx->_sigma_derivative_zz, batch_pos);\n\n    YANN_CHECK(is_same_size(zz, sigma_derivative_zz));\n    YANN_CHECK(is_same_size(zz, gradient_out));\n\n    // prepare sampling\n    for(MatrixSize ii = 0, out_size = output_size; ii < out_size; ++ii) {\n      sampling_gradient_out_sorting[ii].first = ii;\n      sampling_gradient_out_sorting[ii].second = std::abs(gradient_out(ii));\n    }\n    sort(sampling_gradient_out_sorting.begin(), sampling_gradient_out_sorting.end(),\n        [](const auto & left, const auto & right) -> bool\n        {\n          return left.second > right.second; // sort in descending order\n        }\n    );\n    // TODO: we don't need to calculate it for all values\n    _activation_function->derivative(zz, sigma_derivative_zz);\n\n    for(MatrixSize ii = 0; ii < sampled_num; ++ii) {\n      const auto out_pos = sampling_gradient_out_sorting[ii].first;\n      YANN_SLOW_CHECK_GE(out_pos, 0);\n      YANN_SLOW_CHECK_LT(out_pos, output_size);\n      ++sampling_counter[out_pos];\n\n      // delta(l) = elem_prod(gradient(C, a(l)), activation_derivative(z(l)))\n      const auto delta = gradient_out(out_pos) * sigma_derivative_zz(out_pos);\n\n      // update deltas\n      // dC/db(l) = delta(l)\n      // dC/dw(l) = a(l-1) * delta(l)\n      delta_ww.col(out_pos) += in * delta;\n      if(!_fixed_bias) {\n        delta_bb(out_pos) += delta;\n      }\n      // we don't need to calculate the gradient(C, a(l)) for the \"first\" layer (actual inputs)\n      // // gradient(C, a(l - 1)) = transp(w) * delta(l)\n      if(gradient_input) {\n        auto gradient_in = get_batch(*gradient_input, batch_pos);\n        gradient_in.noalias() += delta * _ww.col(out_pos);\n      }\n    }\n  }\n}\n\nvoid yann::FullyConnectedLayer::backprop(\n    const RefConstVectorBatch & gradient_output,\n    const RefConstVectorBatch & input,\n    optional<RefVectorBatch> gradient_input,\n    Context * context) const\n{\n  if(is_sampled()) {\n    backprop_with_sampling_internal(gradient_output, input, gradient_input, context);\n  } else {\n    backprop_internal(gradient_output, input, gradient_input, context);\n  }\n}\n\nvoid yann::FullyConnectedLayer::backprop(\n    const RefConstVectorBatch & gradient_output,\n    const RefConstSparseVectorBatch & input,\n    optional<RefVectorBatch> gradient_input,\n    Context * context) const\n{\n  // <RefConstSparseMatrix> is required for MatrixFunctions<>::product\n  if(is_sampled()) {\n    backprop_with_sampling_internal<RefConstSparseMatrix>(gradient_output, input, gradient_input, context);\n  } else {\n    backprop_internal<RefConstSparseMatrix>(gradient_output, input, gradient_input, context);\n  }\n}\n\nvoid yann::FullyConnectedLayer::init(enum InitMode mode, boost::optional<InitContext> init_context)\n{\n  switch (mode) {\n  case InitMode_Zeros:\n    _ww.setZero();\n    if(!_fixed_bias) {\n      _bb.setZero();\n    }\n    break;\n  case InitMode_Random:\n    {\n      unique_ptr<RandomGenerator> gen01 = RandomGenerator::normal_distribution(0, 1,\n          init_context ? optional<Value>(init_context->seed()) : boost::none);\n      gen01->generate(_ww);\n      if(!_fixed_bias) {\n        gen01->generate(_bb);\n      }\n    }\n    break;\n  }\n}\n\nvoid yann::FullyConnectedLayer::update(Context * context, const size_t & tests_num)\n{\n  auto ctx = dynamic_cast<FullyConnectedLayer_TrainingContext *>(context);\n  YANN_CHECK(ctx);\n  YANN_CHECK(ctx->_ww_updater);\n  YANN_CHECK(ctx->_bb_updater);\n  YANN_CHECK(is_same_size(_ww, ctx->_delta_ww));\n  YANN_CHECK(is_same_size(_bb, ctx->_delta_bb));\n\n  if(!is_sampled()) {\n    ctx->_ww_updater->update(ctx->_delta_ww, tests_num, _ww);\n    if(!_fixed_bias) {\n      ctx->_bb_updater->update(ctx->_delta_bb, tests_num, _bb);\n    }\n  } else {\n    const auto & sampling_counter = *(ctx->_sampling_counter);\n    const auto & delta_ww = ctx->_delta_ww;\n    const auto & delta_bb = ctx->_delta_bb;\n    const auto rows = delta_ww.rows();\n\n    YANN_CHECK_EQ((MatrixSize)sampling_counter.size(), delta_ww.cols());\n    for(MatrixSize ii = 0; ii < delta_ww.cols(); ++ii) {\n      if(sampling_counter[ii] <= 0) {\n        continue;\n      }\n      // can't use delta_ww.col(ii) and _ww.col(ii) here\n      ctx->_ww_updater->update(\n          delta_ww.block(0, ii, rows, 1),\n          sampling_counter[ii],\n          _ww.block(0, ii, rows, 1));\n      if(!_fixed_bias) {\n        ctx->_bb_updater->update(delta_bb(ii), sampling_counter[ii], _bb(ii));\n      }\n    }\n  }\n}\n\n// the format is (w:<weights>,b:<biases>)\nvoid yann::FullyConnectedLayer::read(std::istream & is)\n{\n  Base::read(is);\n\n  read_char(is, '(');\n  read_object(is, \"w\", _ww);\n  read_char(is, ',');\n  read_object(is, \"b\", _bb);\n  read_char(is, ')');\n}\n\n// the format is (w:<weights>,b:<biases>)\nvoid yann::FullyConnectedLayer::write(std::ostream & os) const\n{\n  Base::write(os);\n\n  os << \"(\";\n  write_object(os, \"w\", _ww);\n  os << \",\";\n  write_object(os, \"b\", _bb);\n  os << \")\";\n}\n\n", "meta": {"hexsha": "5098260bea6b8e4add0a3a32f09691300a8109de", "size": 18440, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/layers/fclayer.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/layers/fclayer.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/layers/fclayer.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": 30.1800327332, "max_line_length": 107, "alphanum_fraction": 0.6961496746, "num_tokens": 4683, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289836, "lm_q2_score": 0.6513548714339145, "lm_q1q2_score": 0.49545351514904284}}
{"text": "#pragma once\n\n\n#include <boost/iterator/counting_iterator.hpp>\n\n\nnamespace nifty{\n    namespace graph{\n\n        ///\\cond\n        namespace detail_complete_graph{\n            template<class NODE_TYPE>\n            uint64_t n_complete_dgraph_edges(const NODE_TYPE && n_nodes, const bool self_loops){\n                if(n_nodes == 0){\n                    return 0;\n                }\n                else{\n                    const auto from_self_loop = static_cast<NODE_TYPE>(self_loops) * n_nodes;\n                    return ((n_nodes*(n_nodes-1))/2) + from_self_loop;\n                }\n            }\n        }\n        ///\\endcond\n\n        template<class NODE_INTEGER_TYPE, bool SELF_LOOPS = false>\n        class CompleteGraph{\n        public:\n\n\n\n\n            typedef NODE_INTEGER_TYPE   NodeType;\n            typedef uint64_t            EdgeType;\n\n            typedef NodeType NodeConstRef;\n            typedef EdgeType EdgeConstRef;\n\n\n\n            boost::counting_iterator<NodeType> NodeIter;\n            boost::counting_iterator<EdgeType> EdgeIter;\n\n\n\n            CompleteGraph(const NodeType & n_nodes = 0)\n            :   n_nodes_(n_nodes),\n                n_edges_(detail_complete_graph::n_complete_dgraph_edges(n_nodes, SELF_LOOPS))\n            {\n            }\n\n\n            NodeType n_edges()const{\n                return n_edges_;\n            }\n            NodeType n_nodes()const{\n                return n_nodes_;\n            }\n\n            NodeIter nodes_begin()const{\n                return NodeIter(NodeType(0));\n            }\n            NodeIter nodes_end()const{\n                return NodeIter(NodeType(n_nodes_));\n            }\n            EdgeIter edges_begin()const{\n                return EdgeIter(EdgeType(0));\n            }\n            EdgeIter edges_end()const{\n                return EdgeIter(EdgeType(n_edges_));\n            }\n\n\n\n\n        private:\n            NodeType n_nodes_;\n            EdgeType n_edges_;\n\n\n        };\n\n\n    }\n}", "meta": {"hexsha": "d6dbb3c8e49bf9e035cb21466272b965f52ad6cc", "size": 1955, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/nifty/graph/graphs/complete_ugraph.hpp", "max_stars_repo_name": "DerThorsten/nifty_graph", "max_stars_repo_head_hexsha": "9e4b4cf683238ceb38d678272e29bbea2e8df0e4", "max_stars_repo_licenses": ["MIT"], "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/graphs/complete_ugraph.hpp", "max_issues_repo_name": "DerThorsten/nifty_graph", "max_issues_repo_head_hexsha": "9e4b4cf683238ceb38d678272e29bbea2e8df0e4", "max_issues_repo_licenses": ["MIT"], "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/graphs/complete_ugraph.hpp", "max_forks_repo_name": "DerThorsten/nifty_graph", "max_forks_repo_head_hexsha": "9e4b4cf683238ceb38d678272e29bbea2e8df0e4", "max_forks_repo_licenses": ["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.2738095238, "max_line_length": 96, "alphanum_fraction": 0.5166240409, "num_tokens": 379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.49545351322871545}}
{"text": "#include <boost/test/unit_test.hpp>\n\n#include <crave/utils/Evaluator.hpp>\n#include <crave/ir/UserConstraint.hpp>\n#include <crave/ir/UserExpression.hpp>\n\n#include <set>\n#include <iostream>\n\n// using namespace std;\nusing namespace crave;\n\nBOOST_FIXTURE_TEST_SUITE(Evaluations_t, Context_Fixture)\n\nBOOST_AUTO_TEST_CASE(logical_not_t1) {\n  crv_variable<unsigned int> a;\n  Evaluator evaluator;\n\n  evaluator.assign(a(), 0u);\n\n  BOOST_REQUIRE(evaluator.evaluate(!(a() != 0)));\n  BOOST_REQUIRE(evaluator.result<bool>());\n\n  evaluator.assign(a(), 42u);\n\n  BOOST_REQUIRE(evaluator.evaluate(!(a() == 0)));\n  BOOST_REQUIRE(evaluator.result<bool>());\n}\n\nBOOST_AUTO_TEST_CASE(logical_not_t2) {\n  crv_variable<unsigned char> a;\n  crv_variable<unsigned int> b;\n  Evaluator eval;\n  expression expr = make_expression(if_then_else(!(a() % 2 == 0), b() > 0 && b() <= 50, b() > 50 && b() <= 100));\n\n  eval.assign(a(), 1u);\n\n  BOOST_REQUIRE(!eval.evaluate(expr));\n\n  eval.assign(b(), 35u);\n\n  BOOST_REQUIRE(eval.evaluate(expr));\n  BOOST_REQUIRE(eval.result<bool>());\n\n  eval.assign(a(), 2u);\n  eval.assign(b(), 75u);\n\n  BOOST_REQUIRE(eval.evaluate(expr));\n  BOOST_REQUIRE(eval.result<bool>());\n\n  eval.assign(a(), 1u);\n\n  BOOST_REQUIRE(eval.evaluate(expr));\n  BOOST_REQUIRE(!eval.result<bool>());\n}\n\nBOOST_AUTO_TEST_CASE(logical_and_t1) {\n  crv_variable<bool> a;\n  crv_variable<bool> b;\n  crv_variable<bool> c;\n  Evaluator eval;\n\n  eval.assign(a(), true);\n  eval.assign(b(), true);\n\n  BOOST_REQUIRE(eval.evaluate(a() && b()));\n  BOOST_REQUIRE(eval.result<bool>());\n\n  eval.assign(c(), false);\n\n  BOOST_REQUIRE(eval.evaluate(c() == (a() && b())));\n  BOOST_REQUIRE(!eval.result<bool>());\n\n  eval.assign(a(), false);\n  eval.assign(b(), false);\n\n  BOOST_REQUIRE(eval.evaluate(c() == (a() && b())));\n  BOOST_REQUIRE(eval.result<bool>());\n}\n\nBOOST_AUTO_TEST_CASE(logical_or_t1) {\n  crv_variable<bool> a;\n  crv_variable<bool> b;\n  crv_variable<bool> c;\n  Evaluator eval;\n\n  eval.assign(a(), false);\n  eval.assign(b(), false);\n\n  BOOST_REQUIRE(eval.evaluate(a() || b()));\n  BOOST_REQUIRE(!eval.result<bool>());\n\n  eval.assign(c(), false);\n\n  BOOST_REQUIRE(eval.evaluate(c() == (a() || b())));\n  BOOST_REQUIRE(eval.result<bool>());\n\n  eval.assign(a(), true);\n  eval.assign(c(), true);\n\n  BOOST_REQUIRE(eval.evaluate(c() == (a() || b())));\n  BOOST_REQUIRE(eval.result<bool>());\n}\n\nBOOST_AUTO_TEST_CASE(equal_t1) {\n  crv_variable<unsigned int> a;\n  crv_variable<unsigned int> b;\n  Evaluator eval;\n\n  eval.assign(a(), 65535);\n\n  BOOST_REQUIRE(eval.evaluate(a()));\n  BOOST_REQUIRE_EQUAL(eval.result<unsigned int>(), 65535);\n  BOOST_REQUIRE(eval.evaluate(a() == 65535));\n  BOOST_REQUIRE(eval.result<bool>());\n\n  eval.assign(b(), 5);\n\n  BOOST_REQUIRE(eval.evaluate(a() == b()));\n  BOOST_REQUIRE(!eval.result<bool>());\n}\n\nBOOST_AUTO_TEST_CASE(not_equal_t1) {\n  crv_variable<unsigned int> a;\n  crv_variable<unsigned int> b;\n  Evaluator eval;\n\n  eval.assign(a(), 25u);\n\n  for (unsigned int i = 0; i < 50u; ++i) {\n    eval.assign(b(), i);\n    BOOST_REQUIRE(eval.evaluate(a() != b()));\n\n    if (i != 25u)\n      BOOST_REQUIRE(eval.result<bool>());\n    else\n      BOOST_REQUIRE(!eval.result<bool>());\n  }\n}\n\nBOOST_AUTO_TEST_CASE(less) {\n  crv_variable<unsigned> a;\n  crv_variable<unsigned> b;\n  Evaluator eval;\n\n  for (unsigned int i = 0u; i < 50u; ++i) {\n    eval.assign(a(), i);\n    BOOST_REQUIRE(eval.evaluate(a() < 50u));\n    BOOST_REQUIRE(eval.result<bool>());\n\n    eval.assign(b(), i);\n    BOOST_REQUIRE(eval.evaluate(b() < 50u));\n    BOOST_REQUIRE(eval.result<bool>());\n  }\n}\n\nBOOST_AUTO_TEST_CASE(less_equal) {\n  crv_variable<unsigned> a;\n  crv_variable<unsigned> b;\n  Evaluator eval;\n\n  for (unsigned int i = 0u; i <= 50u; ++i) {\n    eval.assign(a(), i);\n    BOOST_REQUIRE(eval.evaluate(a() <= 50u));\n    BOOST_REQUIRE(eval.result<bool>());\n\n    eval.assign(b(), i);\n    BOOST_REQUIRE(eval.evaluate(b() <= 50u));\n    BOOST_REQUIRE(eval.result<bool>());\n  }\n}\n\nBOOST_AUTO_TEST_CASE(greater) {\n  crv_variable<unsigned> a;\n  crv_variable<unsigned> b;\n  Evaluator eval;\n\n  for (int i = 50; i > 0; --i) {\n    eval.assign(a(), i);\n    BOOST_REQUIRE(eval.evaluate(a() > 0u));\n    BOOST_REQUIRE(eval.result<bool>());\n\n    eval.assign(b(), i);\n    BOOST_REQUIRE(eval.evaluate(b() > 0u));\n    BOOST_REQUIRE(eval.result<bool>());\n  }\n}\n\nBOOST_AUTO_TEST_CASE(greater_equal) {\n  crv_variable<unsigned> a;\n  crv_variable<unsigned> b;\n  Evaluator eval;\n\n  for (int i = 50; i >= 0; --i) {\n    eval.assign(a(), i);\n    BOOST_REQUIRE(eval.evaluate(a() >= 0u));\n    BOOST_REQUIRE(eval.result<bool>());\n\n    eval.assign(b(), i);\n    BOOST_REQUIRE(eval.evaluate(b() >= 0u));\n    BOOST_REQUIRE(eval.result<bool>());\n  }\n}\n\nBOOST_AUTO_TEST_CASE(neg_t1) {\n  crv_variable<int> a;\n  crv_variable<int> b;\n  Evaluator eval;\n\n  eval.assign(a(), 1337);\n  BOOST_REQUIRE(eval.evaluate(-a() == 1337));\n  BOOST_REQUIRE(!eval.result<bool>());\n\n  eval.assign(b(), -1337);\n  BOOST_REQUIRE(eval.evaluate(a() == -b()));\n  BOOST_REQUIRE(eval.result<bool>());\n}\n\nBOOST_AUTO_TEST_CASE(neg_t2) {\n  int a = 1337;\n  crv_variable<int> b;\n  Evaluator eval;\n\n  eval.assign(b(), -a);\n  BOOST_REQUIRE(eval.evaluate(b()));\n  BOOST_REQUIRE_EQUAL(eval.result<int>(), -1337);\n}\n\nBOOST_AUTO_TEST_CASE(complement_t1) {\n  crv_variable<int> a;\n  crv_variable<int> b;\n  Evaluator eval;\n\n  eval.assign(a(), 0);\n  eval.assign(b(), -1);\n  BOOST_REQUIRE(eval.evaluate(~a() == b()));\n  BOOST_REQUIRE(eval.result<bool>());\n}\n\nBOOST_AUTO_TEST_CASE(complement_t2) {\n  int a = 42;\n  crv_variable<int> b;\n  Evaluator eval;\n\n  eval.assign(b(), a);\n  BOOST_REQUIRE(eval.evaluate(~b()));\n  BOOST_REQUIRE_EQUAL(eval.result<int>(), -43);\n}\n\nBOOST_AUTO_TEST_CASE(bitwise_and_t1) {\n  crv_variable<unsigned int> a;\n  crv_variable<unsigned int> b;\n  Evaluator eval;\n\n  eval.assign(a(), 42);\n  eval.assign(b(), 1337);\n\n  BOOST_REQUIRE(eval.evaluate(a() & b()));\n  BOOST_REQUIRE_EQUAL(eval.result<unsigned int>(), 40);\n}\n\nBOOST_AUTO_TEST_CASE(bitwise_or_t1) {\n  crv_variable<unsigned int> a;\n  crv_variable<unsigned int> b;\n  Evaluator eval;\n\n  eval.assign(a(), 42);\n  eval.assign(b(), 1337);\n\n  BOOST_REQUIRE(eval.evaluate(a() | b()));\n  BOOST_REQUIRE_EQUAL(eval.result<unsigned int>(), 1339);\n}\n\nBOOST_AUTO_TEST_CASE(xor_t1) {\n  crv_variable<bool> a;\n  crv_variable<bool> b;\n  Evaluator eval;\n\n  eval.assign(a(), false);\n  eval.assign(b(), false);\n\n  BOOST_REQUIRE(eval.evaluate(a() ^ b()));\n  BOOST_REQUIRE_EQUAL(eval.result<bool>(), false);\n\n  eval.assign(b(), true);\n\n  BOOST_REQUIRE(eval.evaluate(a() ^ b()));\n  BOOST_REQUIRE_EQUAL(eval.result<bool>(), true);\n}\n\nBOOST_AUTO_TEST_CASE(xor_t2) {\n  crv_variable<unsigned int> a;\n  crv_variable<unsigned int> b;\n  Evaluator eval;\n\n  eval.assign(a(), 65535);\n  eval.assign(b(), 4080);\n\n  BOOST_REQUIRE(eval.evaluate(a() ^ b()));\n  BOOST_REQUIRE_EQUAL(eval.result<unsigned int>(), 61455);\n}\n\nBOOST_AUTO_TEST_CASE(shiftleft) {\n  crv_variable<unsigned> a;\n  crv_variable<char> b;\n  Evaluator eval;\n\n  int count = 0;\n  while (++count < 256) {\n    eval.assign(a(), count);\n    eval.assign(b(), count % (sizeof(unsigned) << 3u));\n\n    BOOST_REQUIRE(eval.evaluate(a() << b()));\n    BOOST_REQUIRE_EQUAL(eval.result<unsigned>(), count << (count % (sizeof(unsigned) << 3u)));\n  }\n}\n\nBOOST_AUTO_TEST_CASE(shiftright) {\n  crv_variable<unsigned> a;\n  crv_variable<char> b;\n  Evaluator eval;\n\n  int count = 0;\n  while (256 > ++count) {\n    eval.assign(a(), count + 256);\n    eval.assign(b(), count % 8);\n\n    BOOST_REQUIRE(eval.evaluate(a() >> b()));\n    BOOST_REQUIRE_EQUAL(eval.result<unsigned>(), (count + 256) >> (count % 8));\n  }\n}\n\nBOOST_AUTO_TEST_CASE(plus_minus) {\n  crv_variable<unsigned int> a;\n  crv_variable<unsigned int> b;\n  Evaluator eval;\n\n  unsigned int cnt = 0;\n  while (cnt++ < 300) {\n    eval.assign(a(), cnt * cnt);\n    eval.assign(b(), cnt + cnt);\n\n    BOOST_REQUIRE(eval.evaluate(a() + b()));\n    BOOST_REQUIRE_EQUAL(eval.result<unsigned>(), (cnt * cnt) + (cnt + cnt));\n\n    BOOST_REQUIRE(eval.evaluate(a() - b()));\n    BOOST_REQUIRE_EQUAL(eval.result<unsigned>(), (cnt * cnt) - (cnt + cnt));\n  }\n}\n\nBOOST_AUTO_TEST_CASE(mult_mod) {\n  crv_variable<int> a;\n  crv_variable<int> b;\n  Evaluator eval;\n\n  for (int i = -3; i <= 3; i++) {\n    for (int j = -3; j <= 3; j++) {\n      eval.assign(a(), i);\n      eval.assign(b(), j);\n\n      BOOST_REQUIRE(eval.evaluate(a() * b() % 6));\n      BOOST_REQUIRE_EQUAL(eval.result<int>(), i * j % 6);\n    }\n  }\n\n  eval.assign(b(), 0);\n\n  BOOST_REQUIRE(!eval.evaluate(a() % b()));\n}\n\nBOOST_AUTO_TEST_CASE(divide) {\n  crv_variable<short> a;\n  crv_variable<short> b;\n  Evaluator eval;\n\n  unsigned int cnt = 1;\n  while (cnt++ < 256) {\n    eval.assign(a(), cnt * cnt);\n    eval.assign(b(), cnt + cnt);\n\n    BOOST_REQUIRE(eval.evaluate(a() / b()));\n    BOOST_REQUIRE_EQUAL(eval.result<short>(), (cnt * cnt) / (cnt + cnt));\n\n    BOOST_REQUIRE(eval.evaluate(a() % b()));\n    BOOST_REQUIRE_EQUAL(eval.result<short>(), (cnt * cnt) % (cnt + cnt));\n  }\n\n  eval.assign(b(), 0u);\n  BOOST_REQUIRE(!eval.evaluate(a() / b()));\n}\n\nBOOST_AUTO_TEST_CASE(element_inside_set) {\n  std::set<unsigned> s;\n  s.insert(1);\n  s.insert(7);\n  s.insert(9);\n\n  crv_variable<unsigned> x;\n  Evaluator eval;\n\n  eval.assign(x(), 1);\n\n  BOOST_REQUIRE(eval.evaluate(inside(x(), s)));\n  BOOST_REQUIRE(eval.result<bool>());\n\n  eval.assign(x(), 5);\n\n  BOOST_REQUIRE(eval.evaluate(inside(x(), s)));\n  BOOST_REQUIRE(!eval.result<bool>());\n}\n\nBOOST_AUTO_TEST_CASE(element_inside_vec) {\n  std::vector<unsigned> v;\n  v.push_back(1);\n  v.push_back(7);\n  v.push_back(9);\n\n  crv_variable<unsigned> x;\n  Evaluator eval;\n\n  eval.assign(x(), 7u);\n\n  BOOST_REQUIRE(eval.evaluate(inside(x(), v)));\n  BOOST_REQUIRE(eval.result<bool>());\n\n  eval.assign(x(), 5u);\n\n  BOOST_REQUIRE(eval.evaluate(inside(x(), v)));\n  BOOST_REQUIRE(!eval.result<bool>());\n}\n\nBOOST_AUTO_TEST_CASE(element_inside_array) {\n  unsigned a[3];\n  a[0] = 1;\n  a[1] = 7;\n  a[2] = 9;\n\n  crv_variable<unsigned> x;\n  Evaluator eval;\n\n  eval.assign(x(), 9);\n\n  BOOST_REQUIRE(eval.evaluate(inside(x(), a)));\n  BOOST_REQUIRE(eval.result<bool>());\n\n  eval.assign(x(), 5u);\n\n  BOOST_REQUIRE(eval.evaluate(inside(x(), a)));\n  BOOST_REQUIRE(!eval.result<bool>());\n}\n\nBOOST_AUTO_TEST_CASE(element_inside_list) {\n  std::list<unsigned> l;\n  l.push_back(1);\n  l.push_back(7);\n  l.push_back(9);\n\n  crv_variable<unsigned> x;\n  Evaluator eval;\n\n  eval.assign(x(), 7u);\n\n  BOOST_REQUIRE(eval.evaluate(inside(x(), l)));\n  BOOST_REQUIRE(eval.result<bool>());\n\n  eval.assign(x(), 5u);\n\n  BOOST_REQUIRE(eval.evaluate(inside(x(), l)));\n  BOOST_REQUIRE(!eval.result<bool>());\n}\n\nBOOST_AUTO_TEST_CASE(element_not_inside) {\n  Evaluator eval;\n  {\n    std::set<unsigned> s;\n    crv_variable<unsigned> x;\n    eval.assign(x(), 1u);\n\n    BOOST_REQUIRE(eval.evaluate(inside(x(), s)));\n    BOOST_REQUIRE(!eval.result<bool>());\n\n    s.insert(1u);\n\n    BOOST_REQUIRE(eval.evaluate(inside(x(), s)));\n    BOOST_REQUIRE(eval.result<bool>());\n  }\n  {\n    std::vector<unsigned> v;\n\n    crv_variable<unsigned> x;\n    eval.assign(x(), 1u);\n\n    BOOST_REQUIRE(eval.evaluate(inside(x(), v)));\n    BOOST_REQUIRE(!eval.result<bool>());\n\n    v.push_back(1u);\n\n    BOOST_REQUIRE(eval.evaluate(inside(x(), v)));\n    BOOST_REQUIRE(eval.result<bool>());\n  }\n  {\n    std::vector<unsigned> l;\n    crv_variable<unsigned> x;\n    eval.assign(x(), 1u);\n\n    BOOST_REQUIRE(eval.evaluate(inside(x(), l)));\n    BOOST_REQUIRE(!eval.result<bool>());\n\n    l.push_back(1u);\n\n    BOOST_REQUIRE(eval.evaluate(inside(x(), l)));\n    BOOST_REQUIRE(eval.result<bool>());\n  }\n}\n\nBOOST_AUTO_TEST_CASE(if_then_else_t1) {\n  crv_variable<unsigned int> a;\n  crv_variable<unsigned int> b;\n  Evaluator eval;\n  expression expr = make_expression(if_then_else(a()<5, b()> 0 && b() <= 50, b() > 50 && b() <= 100));\n\n  for (int i = 0; i < 10; ++i) {\n    eval.assign(a(), i);\n    eval.assign(b(), 25);\n    BOOST_REQUIRE(eval.evaluate(expr));\n\n    if (i < 5) {\n      BOOST_REQUIRE(eval.result<bool>());\n    } else {\n      BOOST_REQUIRE(!eval.result<bool>());\n    }\n    eval.assign(b(), 75);\n    BOOST_REQUIRE(eval.evaluate(expr));\n\n    if (i < 5) {\n      BOOST_REQUIRE(!eval.result<bool>());\n    } else {\n      BOOST_REQUIRE(eval.result<bool>());\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE(if_then_t1) {\n  crv_variable<unsigned int> a;\n  crv_variable<unsigned int> b;\n  Evaluator eval;\n  expression expr = make_expression(if_then(a()<5, b()> 0 && b() <= 100));\n\n  for (int i = 0; i < 10; ++i) {\n    eval.assign(a(), i);\n    eval.assign(b(), 25u);\n    BOOST_REQUIRE(eval.evaluate(expr));\n    BOOST_REQUIRE(eval.result<bool>());\n\n    eval.assign(b(), 705u);\n    BOOST_REQUIRE(eval.evaluate(expr));\n\n    if (i < 5) {\n      BOOST_REQUIRE(!eval.result<bool>());\n    } else {\n      BOOST_REQUIRE(eval.result<bool>());\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE(equal_t2) {\n  crv_variable<unsigned int> a;\n  crv_variable<unsigned int> b;\n  Evaluator eval;\n\n  eval.assign(a(), 1);\n  eval.assign(b(), 2);\n\n  BOOST_REQUIRE(eval.evaluate(a() == b()));\n  BOOST_REQUIRE(!eval.result<bool>());\n}\n\nBOOST_AUTO_TEST_CASE(equal_t3) {\n  crv_variable<unsigned int> a;\n  crv_variable<unsigned int> b;\n  crv_variable<unsigned int> c;\n  Evaluator eval;\n\n  eval.assign(a(), 1);\n  eval.assign(b(), 2);\n  eval.assign(c(), 3);\n\n  BOOST_REQUIRE(eval.evaluate(a() + b() == c()));\n  BOOST_REQUIRE(eval.result<bool>());\n}\n\nBOOST_AUTO_TEST_SUITE_END()  // Evaluations\n", "meta": {"hexsha": "98790089dd0c24f08cf29cfafd1c859b8b8ce0fc", "size": 13321, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/experimental/test_ExperimentalEvaluations.cpp", "max_stars_repo_name": "quadric-io/crave", "max_stars_repo_head_hexsha": "8096d8b151cbe0d2ba437657f42d8bb0e05f5436", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2015-05-11T02:38:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T07:31:26.000Z", "max_issues_repo_path": "tests/experimental/test_ExperimentalEvaluations.cpp", "max_issues_repo_name": "quadric-io/crave", "max_issues_repo_head_hexsha": "8096d8b151cbe0d2ba437657f42d8bb0e05f5436", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2018-06-08T14:44:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-19T16:07:21.000Z", "max_forks_repo_path": "tests/experimental/test_ExperimentalEvaluations.cpp", "max_forks_repo_name": "quadric-io/crave", "max_forks_repo_head_hexsha": "8096d8b151cbe0d2ba437657f42d8bb0e05f5436", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2019-05-29T21:40:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-01T09:31:15.000Z", "avg_line_length": 22.4637436762, "max_line_length": 113, "alphanum_fraction": 0.6428946776, "num_tokens": 3600, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.49545351322871545}}
{"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\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n// #include <boost/test/minimal.hpp>\n#include <boost/numeric/mtl/mtl.hpp>\n#include <boost/numeric/itl/itl.hpp>\n\ntemplate <typename Matrix>\nvoid setup(Matrix& A)\n{\n    const std::size_t n= num_rows(A);\n    A= 1.0;\n    mtl::mat::inserter<Matrix, mtl::update_plus<double> > ins(A);\n\n    for (std::size_t i= 0; i < 2 * n; i++) {\n\tint r= rand()%n, c= rand()%n;\n\tins[r][c] << -1;\n\tins[r][r] << 1;\n    }\n}\n\n\ntemplate <typename At, typename Lt, typename Ut>\nvoid dense_ilu_0(const At& As, const Lt& Ls, const Ut& Us)\n{\n    mtl::dense2D<double> LU(As);\n     \n    const std::size_t n= num_rows(LU);\n    for (std::size_t i= 1; i < n; i++) \n\tfor (std::size_t k= 0; k < i; k++) {\n\t    LU[i][k]/= LU[k][k];\n\t    for (std::size_t j= k + 1; j < n; j++)\n\t\tif (LU[i][j] != 0)\n\t\t    LU[i][j]-= LU[i][k] * LU[k][j];\n\t}\n    std::cout << \"Factorizing A = \\n\" << As << \"-> LU = \\n\" << LU;\n    // std::cout << \"L = \\n\" << Ls << \"\\nU = \\n\" << Us;\n\n    if (std::abs(LU[0][0] - Ls[0][0]) > 0.001) throw \"Wrong value in L for sparse ILU(0) factorization\";\n\n    if (std::abs(LU[0][1] - Us[0][1]) > 0.001) throw \"Wrong value in U for sparse ILU(0) factorization\";\n}\n\n\nint main(int, char**)\n{\n    // For a more realistic example set sz to 1000 or larger\n    const int N = 5;\n\n    typedef mtl::dense2D<double>       matrix_type;\n    typedef mtl::dense_vector<double>  vector_type;\n    matrix_type                        A(N, N);\n    setup(A);\n       \n    itl::pc::ilu_0<matrix_type>        P(A);\n    \n    mtl::dense_vector<double> x(N), x2(N), Px(N), x3(N), x4(N), x5(N);\n\n    for (unsigned i= 0; i < num_rows(x); i++)\n\tx[i]= i+1;\n\n    std::cout << \"A is\\n\" << A;\n    x2= A * x;\n    std::cout << \"x2= A * x = \" << x2 << \"\\n\";\n\n    x3= solve(P, x2);\n    std::cout << \"solve(P, x2) = \" << x3 << \" (should be [1,2,..,N])\\n\";\n    if (two_norm(vector_type(x - x3)) > 0.00001) throw \"Wrong result\";\n\n    // Now test adjoint solve\n    x4= trans(A) * x;\n    std::cout << \"x4= adjoint(A) * x = \" << x4 << \"\\n\";\n\n    x5= adjoint_solve(P, x4);\n    std::cout << \"adjoint_solve(P, x4) = \" << x5 << \" (should be [1,2,..,N])\\n\";\n    if (two_norm(vector_type(x - x5)) > 0.00001) throw \"Wrong result\";\n    \n    \n    matrix_type LU(A), L(N,N), U(N,N);\n    lu(LU, x5);\n    L= lower(LU);\n    U= upper(LU);\n    std::cout<< \"L=\" << L << \"\\n\";\n    std::cout<< \"U=\" << U << \"\\n\";\n    dense_ilu_0(A, L, U);\n    \n    \n    return 0;\n}\n", "meta": {"hexsha": "14e41fccb396574d42a05f7e5881f3b13e713989", "size": 2820, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/itl/test/ilu_0_dispatch_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/itl/test/ilu_0_dispatch_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/itl/test/ilu_0_dispatch_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.4848484848, "max_line_length": 104, "alphanum_fraction": 0.5390070922, "num_tokens": 1009, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289836, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.4954535100010654}}
{"text": "// Copyright (c) 2015-2018, LAAS-CNRS\n// Authors: Joseph Mirabel (joseph.mirabel@laas.fr)\n//\n// This file is part of gepetto-viewer-corba.\n// gepetto-viewer-corba is free software: you can redistribute it\n// and/or modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation, either version\n// 3 of the License, or (at your option) any later version.\n//\n// gepetto-viewer-corba is distributed in the hope that it will be\n// useful, but WITHOUT ANY WARRANTY; without even the implied warranty\n// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// General Lesser Public License for more details. You should have\n// received a copy of the GNU Lesser General Public License along with\n// gepetto-viewer-corba. If not, see <http://www.gnu.org/licenses/>.\n\n#ifndef __se3_se3_hpp__\n#define __se3_se3_hpp__\n#include <Eigen/Geometry>\n\nnamespace se3\n{\n/* Type returned by the \"se3Action\" and \"se3ActionInverse\" functions. */\nnamespace internal\n{\ntemplate<typename D>\nstruct ActionReturn { typedef D Type; };\n}\n/** The rigid transform aMb can be seen in two ways:\n*\n* - given a point p expressed in frame B by its coordinate vector Bp, aMb\n* computes its coordinates in frame A by Ap = aMb Bp.\n* - aMb displaces a solid S centered at frame A into the solid centered in\n* B. In particular, the origin of A is displaced at the origin of B: $^aM_b\n* ^aA = ^aB$.\n* The rigid displacement is stored as a rotation matrix and translation vector by:\n* aMb (x) = aRb*x + aAB\n* where aAB is the vector from origin A to origin B expressed in coordinates A.\n*/\ntemplate<typename _Scalar, int _Options>\nclass SE3Tpl\n{\npublic:\ntypedef _Scalar Scalar;\nenum { Options = _Options };\ntypedef Eigen::Matrix<Scalar,3,1,Options> Vector3;\ntypedef Eigen::Matrix<Scalar,4,1,Options> Vector4;\ntypedef Eigen::Matrix<Scalar,3,3,Options> Matrix3;\ntypedef Eigen::Matrix<Scalar,6,1,Options> Vector6;\ntypedef Eigen::Matrix<Scalar,4,4,Options> Matrix4;\ntypedef Eigen::Matrix<Scalar,6,6,Options> Matrix6;\ntypedef Eigen::Quaternion<Scalar,Options> Quaternion;\n//typedef MotionTpl<Scalar,Options> Motion;\n//typedef ForceTpl<Scalar,Options> Force;\n//typedef ActionTpl<Scalar,Options> Action;\nenum { LINEAR = 0, ANGULAR = 3 };\npublic:\n// Constructors\nSE3Tpl() : rot(), trans() {}\ntemplate<typename M3,typename v3>\nSE3Tpl(const Eigen::MatrixBase<M3> & R, const Eigen::MatrixBase<v3> & p)\n: rot(R), trans(p) {}\nSE3Tpl(int) : rot(Matrix3::Identity()), trans(Vector3::Zero()) {}\ntemplate<typename S2, int O2>\nSE3Tpl( const SE3Tpl<S2,O2> clone )\n: rot(clone.rotation()),trans(clone.translation()) {}\ntemplate<typename S2, int O2>\nSE3Tpl & operator= (const SE3Tpl<S2,O2> & other)\n{\nrot = other.rotation ();\ntrans = other.translation ();\nreturn *this;\n}\nconst Matrix3 & rotation() const { return rot; }\nconst Vector3 & translation() const { return trans; }\nMatrix3 & rotation() { return rot; }\nVector3 & translation() { return trans; }\nvoid rotation(const Matrix3 & R) { rot=R; }\nvoid translation(const Vector3 & p) { trans=p; }\nstatic SE3Tpl Identity()\n{\nreturn SE3Tpl(1);\n}\nstatic SE3Tpl Random()\n{\nEigen::Quaternion<Scalar,Options> q(Vector4::Random());\nq.normalize();\nreturn SE3Tpl(q.matrix(),Vector3::Random());\n}\nEigen::Matrix<Scalar,4,4,Options> toHomogeneousMatrix() const\n{\nEigen::Matrix<Scalar,4,4,Options> M;\nM.template block<3,3>(0,0) = rot;\nM.template block<3,1>(0,3) = trans;\nM.template block<1,3>(3,0).setZero();\nM(3,3) = 1;\nreturn M;\n}\n/// Vb.toVector() = bXa.toMatrix() * Va.toVector()\nMatrix6 toActionMatrix() const\n{\nMatrix6 M;\nM.template block<3,3>(ANGULAR,ANGULAR)\n= M.template block<3,3>(LINEAR,LINEAR) = rot;\nM.template block<3,3>(ANGULAR,LINEAR).setZero();\nM.template block<3,3>(LINEAR,ANGULAR)\n= skew(trans) * M.template block<3,3>(ANGULAR,ANGULAR);\nreturn M;\n}\n/// aXb = bXa.inverse()\nSE3Tpl inverse() const\n{\nreturn SE3Tpl(rot.transpose(), -rot.transpose()*trans);\n}\nvoid disp(std::ostream & os) const\n{\nos << \" R =\\n\" << rot << std::endl\n<< \" p =\\n\" << trans.transpose() << std::endl;\n}\n/* --- GROUP ACTIONS ON M6, F6 and I6 --- */\n/// ay = aXb.act(by)\ntemplate<typename D> typename internal::ActionReturn<D>::Type act (const D & d) const\n{ return d.se3Action(*this); }\n/// by = aXb.actInv(ay)\ntemplate<typename D> typename internal::ActionReturn<D>::Type actInv(const D & d) const\n{ return d.se3ActionInverse(*this); }\nVector3 act (const Vector3& p) const { return (rot*p+trans).eval(); }\nVector3 actInv(const Vector3& p) const { return (rot.transpose()*(p-trans)).eval(); }\nSE3Tpl act (const SE3Tpl& m2) const { return SE3Tpl( rot*m2.rot,trans+rot*m2.trans);}\nSE3Tpl actInv (const SE3Tpl& m2) const { return SE3Tpl( rot.transpose()*m2.rot,\nrot.transpose()*(m2.trans-trans));}\n/* --- OPERATORS -------------------------------------------------------- */\noperator Matrix4() const { return toHomogeneousMatrix(); }\noperator Matrix6() const { return toActionMatrix(); }\nSE3Tpl operator*(const SE3Tpl & m2) const { return this->act(m2); }\nfriend std::ostream & operator << (std::ostream & os,const SE3Tpl & X)\n{ X.disp(os); return os; }\npublic:\nprivate:\nMatrix3 rot;\nVector3 trans;\n};\ntypedef SE3Tpl<float,0> SE3;\n} // namespace se3\n#endif // ifndef __se3_se3_hpp__\n\n", "meta": {"hexsha": "41019809e748e3c3c01d8ac12f52a62330d6432f", "size": 5212, "ext": "hh", "lang": "C++", "max_stars_repo_path": "include/gepetto/viewer/corba/se3.hh", "max_stars_repo_name": "andreadelprete/gepetto-viewer-corba", "max_stars_repo_head_hexsha": "7116c02e8c8b33d55e952a326bc8e15d5fd770d2", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/gepetto/viewer/corba/se3.hh", "max_issues_repo_name": "andreadelprete/gepetto-viewer-corba", "max_issues_repo_head_hexsha": "7116c02e8c8b33d55e952a326bc8e15d5fd770d2", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/gepetto/viewer/corba/se3.hh", "max_forks_repo_name": "andreadelprete/gepetto-viewer-corba", "max_forks_repo_head_hexsha": "7116c02e8c8b33d55e952a326bc8e15d5fd770d2", "max_forks_repo_licenses": ["BSD-3-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.4557823129, "max_line_length": 87, "alphanum_fraction": 0.7066385265, "num_tokens": 1490, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255928, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.4954535061604106}}
{"text": "/*******************************************************************************\n * Reverse Polish Notation calculator.                                         *\n * Copyright (c) 2007-2009, Samuel Fredrickson <kinghajj@gmail.com>            *\n * All rights reserved.                                                        *\n *                                                                             *\n * Redistribution and use in source and binary forms, with or without          *\n * modification, are permitted provided that the following conditions are met: *\n *     * Redistributions of source code must retain the above copyright        *\n *       notice, this list of conditions and the following disclaimer.         *\n *     * Redistributions in binary form must reproduce the above copyright     *\n *       notice, this list of conditions and the following disclaimer in the   *\n *       documentation and/or other materials provided with the distribution.  *\n *                                                                             *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ``AS IS'' AND ANY EXPRESS *\n * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED           *\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE      *\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY        *\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES  *\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR          *\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 SUCH *\n * DAMAGE.                                                                     *\n ******************************************************************************/\n\n/*******************************************************************************\n * Calculator.cpp - non-command Calculator methods.                            *\n ******************************************************************************/\n\n#include \"rpn.h\"\n#include <boost/tokenizer.hpp>\n#include <sstream>\nusing namespace boost;\nusing namespace std;\nusing namespace RPN;\n\nvoid Calculator::Eval(string s)\n{\n    typedef tokenizer< char_separator<char> > Tokens;\n    char_separator<char> sep(\" \\t\\n\");\n    Tokens tokens(s, sep);\n\n    if(!HasStack()) return;\n\n    for(Tokens::iterator tok = tokens.begin();\n        tok != tokens.end() && status == Continue;\n        ++tok)\n    {\n        Commands::iterator  foundCommand   = commands.find(*tok);\n        Operators::iterator foundOperator  = operators.find(*tok);\n        Variables::iterator foundVariable  = variables.find(*tok);\n        Value val;\n\n        // if the token is a number, push it.\n        if(istringstream(*tok) >> val)\n            CurrentStack().push_front(val);\n\n        // if the token is a command, perform it.\n        else if(foundCommand != commands.end())\n        {\n            const Command& command = foundCommand->second;\n            vector<string> args;\n            args.reserve(command.NumArgs());\n\n            // collect a the tokens that will be the arguments to the command.\n            while(tok != tokens.end() && args.size() != command.NumArgs())\n                args.push_back(*++tok);\n\n            // only perform a command if we can give it enough arguments.\n            if(args.size() == command.NumArgs())\n                command.Perform(*this, args);\n        }\n\n        // if the token is an operator and that stack has at least two items,\n        // then perform that operator.\n        else if(foundOperator != operators.end() && StackSize() > 1)\n        {\n            Value b = TopmostItem(); CurrentStack().pop_front();\n            Value a = TopmostItem(); CurrentStack().pop_front();\n            CurrentStack().push_front(foundOperator->second(a, b));\n        }\n\n        // if the token is a variable, push the variable onto the stack.\n        else if(foundVariable != variables.end())\n            CurrentStack().push_front(foundVariable->second);\n\n        // otherwise, if the stack has at least one item, set a new variable \n        // whose name is the token and value is the top item.\n        else variables[*tok] = TopmostItem();\n    }\n}\n\n// displays the top item of the stack if there is one.\n// I tried to write this as a friend operator<<(), but I got errors for\n// accessing private data, which is what friend functions are supposed to be\n// able to do!\nvoid Calculator::Display() const\n{\n    Print(TopmostItem());\n}\n", "meta": {"hexsha": "ba08595a300a1f1a6e27faa911253a1cab6dfcad", "size": 4745, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Calculator.cpp", "max_stars_repo_name": "kinghajj/rpn", "max_stars_repo_head_hexsha": "733cb5c8bef84a1724fed7ac876c5da06ec57ff1", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-05-08T09:42:59.000Z", "max_stars_repo_stars_event_max_datetime": "2016-05-08T09:42:59.000Z", "max_issues_repo_path": "src/Calculator.cpp", "max_issues_repo_name": "kinghajj/rpn", "max_issues_repo_head_hexsha": "733cb5c8bef84a1724fed7ac876c5da06ec57ff1", "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/Calculator.cpp", "max_forks_repo_name": "kinghajj/rpn", "max_forks_repo_head_hexsha": "733cb5c8bef84a1724fed7ac876c5da06ec57ff1", "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": 46.5196078431, "max_line_length": 80, "alphanum_fraction": 0.5527924131, "num_tokens": 867, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.495453502932761}}
{"text": "//\n// Copyright (c) 2015-2017, Deutsches Forschungszentrum f\u00fcr K\u00fcnstliche Intelligenz GmbH.\n// Copyright (c) 2015-2017, University of Bremen\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are met:\n//\n// * Redistributions of source code must retain the above copyright notice, this\n//   list of conditions and the following disclaimer.\n//\n// * Redistributions in binary form must reproduce the above copyright notice,\n//   this list of conditions and the following disclaimer in the documentation\n//   and/or other materials provided with the distribution.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n#ifndef __MAPS_OCCUPANCY_PATCH_HPP_\n#define __MAPS_OCCUPANCY_PATCH_HPP_\n\n\n#include <cmath>\n\n#include <boost/serialization/access.hpp>\n#include <boost/serialization/nvp.hpp>\n\n\nnamespace maps { namespace grid \n{   \n\nclass OccupancyPatch\n{\n    float log_odds;\n\npublic:\n    OccupancyPatch(double initial_probability) : log_odds(logodds(initial_probability)) {}\n    OccupancyPatch(float initial_log_odds = 0.f) : log_odds(initial_log_odds) {}\n    virtual ~OccupancyPatch() {}\n\n    double getPropability() const\n    {\n\treturn probability(log_odds);\n    }\n\n    float getLogOdds() const\n    {\n\treturn log_odds;\n    }\n\n    bool isOccupied(double occupied_tresshold = 0.8) const\n    {\n\treturn probability(log_odds) >= occupied_tresshold;\n    }\n\n    bool isFreeSpace(double not_occupied_tresshold = 0.3) const\n    {\n\treturn probability(log_odds) < not_occupied_tresshold;\n    }\n\n    void updatePropability(double update_prob, double min_prob = 0.1192, double max_prob = 0.971)\n    {\n\tupdateLogOdds(logodds(update_prob), logodds(min_prob), logodds(max_prob));\n    }\n\n    void updateLogOdds(float update_logodds, float min = -2.f, float max = 3.5f)\n    {\n\tlog_odds += update_logodds;\n\tif(log_odds < min)\n\t    log_odds = min;\n\telse if(log_odds > max)\n\t    log_odds = max;\n    }\n\n    bool operator==(const OccupancyPatch& other) const\n    {\n\treturn this == &other;\n    }\n\n    // compute log-odds from probability\n    static inline float logodds(double probability)\n    {\n\treturn (float)log(probability / (1.0 - probability));\n    }\n\n    // compute probability from log-odds\n    static inline double probability(double logodds)\n    {\n\treturn 1.0 - ( 1.0 / (1.0 + exp(logodds)));\n    }\n\nprotected:\n\n    /** Grants access to boost serialization */\n    friend class boost::serialization::access;\n\n    /** Serializes the members of this class*/\n    template <typename Archive>\n    void serialize(Archive &ar, const unsigned int version)\n    {\n\tar & BOOST_SERIALIZATION_NVP(log_odds);\n    }\n};\n\t\n}  //namespace grid\n}  //namespace maps\n\n#endif  //__MAPS_OCCUPANCY_PATCH_HPP_", "meta": {"hexsha": "bc45f4acd0c0c7676b943a54720207c287254e39", "size": 3521, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/grid/OccupancyPatch.hpp", "max_stars_repo_name": "skasperski/slam-maps", "max_stars_repo_head_hexsha": "916c2ab77573162a17df2567cf6df16c300538bc", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2016-05-20T05:21:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-21T02:34:18.000Z", "max_issues_repo_path": "src/grid/OccupancyPatch.hpp", "max_issues_repo_name": "skasperski/slam-maps", "max_issues_repo_head_hexsha": "916c2ab77573162a17df2567cf6df16c300538bc", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2016-06-22T18:43:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-28T15:20:31.000Z", "max_forks_repo_path": "src/grid/OccupancyPatch.hpp", "max_forks_repo_name": "skasperski/slam-maps", "max_forks_repo_head_hexsha": "916c2ab77573162a17df2567cf6df16c300538bc", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2017-03-10T10:19:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-04T05:50:10.000Z", "avg_line_length": 30.3534482759, "max_line_length": 97, "alphanum_fraction": 0.7259301335, "num_tokens": 856, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289836, "lm_q2_score": 0.6513548511303336, "lm_q1q2_score": 0.4954534997051106}}
{"text": "/* test_fisher_f_distribution.cpp\n *\n * Copyright Steven Watanabe 2011\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: test_fisher_f_distribution.cpp 71018 2011-04-05 21:27:52Z steven_watanabe $\n *\n */\n\n#include <boost/random/fisher_f_distribution.hpp>\n#include <limits>\n\n#define BOOST_RANDOM_DISTRIBUTION boost::random::fisher_f_distribution<>\n#define BOOST_RANDOM_ARG1 m\n#define BOOST_RANDOM_ARG2 n\n#define BOOST_RANDOM_ARG1_DEFAULT 1.0\n#define BOOST_RANDOM_ARG2_DEFAULT 1.0\n#define BOOST_RANDOM_ARG1_VALUE 7.5\n#define BOOST_RANDOM_ARG2_VALUE 0.25\n\n#define BOOST_RANDOM_DIST0_MIN 0.0\n#define BOOST_RANDOM_DIST0_MAX (std::numeric_limits<double>::infinity)()\n#define BOOST_RANDOM_DIST1_MIN 0.0\n#define BOOST_RANDOM_DIST1_MAX (std::numeric_limits<double>::infinity)()\n#define BOOST_RANDOM_DIST2_MIN 0.0\n#define BOOST_RANDOM_DIST2_MAX (std::numeric_limits<double>::infinity)()\n\n#define BOOST_RANDOM_TEST1_PARAMS (1.0, 2.1)\n#define BOOST_RANDOM_TEST2_PARAMS (10.0, 10.0)\n\n#include \"test_distribution.ipp\"\n", "meta": {"hexsha": "b40700492bc33405e258b748d179519ef8698daf", "size": 1121, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/random/test/test_fisher_f_distribution.cpp", "max_stars_repo_name": "ai-nikolaev/repo-cppboost", "max_stars_repo_head_hexsha": "218c4a977c6d8cd6f2864cdcea1b6ab53160d203", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2016-04-12T16:29:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-28T11:01:57.000Z", "max_issues_repo_path": "libs/random/test/test_fisher_f_distribution.cpp", "max_issues_repo_name": "ai-nikolaev/repo-cppboost", "max_issues_repo_head_hexsha": "218c4a977c6d8cd6f2864cdcea1b6ab53160d203", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-10-31T19:35:14.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-04T17:11:27.000Z", "max_forks_repo_path": "libs/random/test/test_fisher_f_distribution.cpp", "max_forks_repo_name": "ai-nikolaev/repo-cppboost", "max_forks_repo_head_hexsha": "218c4a977c6d8cd6f2864cdcea1b6ab53160d203", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-09-09T02:38:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-30T00:24:24.000Z", "avg_line_length": 32.9705882353, "max_line_length": 83, "alphanum_fraction": 0.8037466548, "num_tokens": 305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255927, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.4954534958644563}}
{"text": "//  ================================================================\n//  Created by Gregory Kramida on 1/30/19.\n//  Copyright (c) 2019 Gregory Kramida\n//  Licensed under the Apache License, Version 2.0 (the \"License\");\n//  you may not use this file except in compliance with the License.\n//  You may obtain a copy of the License at\n\n//  http://www.apache.org/licenses/LICENSE-2.0\n\n//  Unless required by applicable law or agreed to in writing, software\n//  distributed under the License is distributed on an \"AS IS\" BASIS,\n//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//  See the License for the specific language governing permissions and\n//  limitations under the License.\n//  ================================================================\n#pragma once\n\n//stdlib\n\n//libs\n#include <Eigen/Eigen>\n#include <unsupported/Eigen/CXX11/Tensor>\n\n//local\n#include \"../math/typedefs.hpp\"\n\nnamespace eig = Eigen;\n\nnamespace tsdf {\n\n\nmath::MatrixXuc generate_TSDF_3D_EWA_image_visualization(\n\t\tconst eig::Matrix<unsigned short, eig::Dynamic, eig::Dynamic>& depth_image,\n\t\tfloat depth_unit_ratio,\n\t\tconst eig::Tensor<float, 3>& field,\n\t\tconst eig::Matrix3f& camera_intrinsic_matrix,\n\t\tconst eig::Matrix4f& camera_pose = eig::Matrix4f::Identity(4, 4),\n\t\tconst eig::Vector3i& array_offset =\n\t\t\t\t[] {eig::Vector3i default_offset; default_offset << -64, -64, 64; return default_offset;}(),\n\t\tfloat voxel_size = 0.004,\n\t\tint scale=20,\n\t\tfloat tsdf_threshold = 0.1f,\n\t\tfloat gaussian_covariance_scale = 1.0f);\n\neig::MatrixXf sampling_area_heatmap_2D_EWA_image(int image_y_coordinate,\n\t\tconst eig::Matrix<unsigned short, eig::Dynamic, eig::Dynamic>& depth_image,\n\t\tfloat depth_unit_ratio,\n\t\tconst eig::Matrix3f& camera_intrinsic_matrix,\n\t\tconst eig::Matrix4f& camera_pose,\n\t\tconst eig::Vector3i& array_offset,\n\t\tint field_size,\n\t\tfloat voxel_size,\n\t\tint narrow_band_width_voxels,\n\t\tfloat gaussian_covariance_scale);\n\n} // namespace tsdf\n", "meta": {"hexsha": "fa0c2a9138d1544996c4f86726aa3ddd479d5a70", "size": 1952, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/tsdf/ewa_viz.hpp", "max_stars_repo_name": "Algomorph/LevelSetFusionExperimentsCPP", "max_stars_repo_head_hexsha": "f56962f0ad5c62e6706f818062782a2e1660afda", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2019-01-07T14:12:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T01:48:03.000Z", "max_issues_repo_path": "src/tsdf/ewa_viz.hpp", "max_issues_repo_name": "Algomorph/LevelSetFusionExperimentsCPP", "max_issues_repo_head_hexsha": "f56962f0ad5c62e6706f818062782a2e1660afda", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2018-12-19T16:43:33.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-06T19:50:22.000Z", "max_forks_repo_path": "src/tsdf/ewa_viz.hpp", "max_forks_repo_name": "Algomorph/LevelSetFusionExperimentsCPP", "max_forks_repo_head_hexsha": "f56962f0ad5c62e6706f818062782a2e1660afda", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-01-07T14:12:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-06T06:30:24.000Z", "avg_line_length": 34.2456140351, "max_line_length": 96, "alphanum_fraction": 0.6967213115, "num_tokens": 495, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079208, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.49545255023798507}}
{"text": "#ifndef __MECHANISM_KALMAN_ALGORITHM__\n#define __MECHANISM_KALMAN_ALGORITHM__\n\n#include <ros/ros.h>\n#include <Eigen/Dense>\n#include <math.h>\n#include <pr2_algorithms/algorithm_base.hpp>\n#include <limits>\n#include <stdexcept>\n\nnamespace manipulation_algorithms{\ntypedef Eigen::Matrix<double, 6, 1> Vector6d;\n\n  /**\n    Class that implements the joint position estimator used\n    in the mechanism identification problem.\n  **/\n  class KalmanEstimator : public AlgorithmBase\n  {\n  public:\n    KalmanEstimator();\n    ~KalmanEstimator();\n\n    /**\n      Estimate the joint location from the measured reaction forces.\n      Neglects inertial effects and friction.\n\n      @param p_e1 The position of the rod piece end-effector.\n      @param x_dot_e1 The rod piece end-effector twist.\n      @param p_e2 The position of the surface piece end-effector.\n      @param wrench_e2 The measured wrench of the surface piece end-effector.\n      @param dt The elapsed time between estimate steps.\n      @output The joint position estimate pc.\n    **/\n    Eigen::Vector3d estimate(const Eigen::Vector3d &p_e1, const Vector6d &x_dot_e1, const Eigen::Vector3d &p_e2, const Vector6d &wrench_e2, double dt);\n\n    /**\n      Use a constant gain instead of computing the Kalman gain, effectively becoming a simple linear observer.\n      Not executing the integration steps in the Kalman gain computation might help when the measurements are affected by bias.\n\n      @param p_e1 The position of the rod piece end-effector.\n      @param x_dot_e1 The rod piece end-effector twist.\n      @param p_e2 The position of the surface piece end-effector.\n      @param wrench_e2 The measured wrench of the surface piece end-effector.\n      @param dt The elapsed time between estimate steps.\n      @output The joint position estimate pc.\n    **/\n    Eigen::Vector3d estimateConstant(const Eigen::Vector3d &p_e1, const Vector6d &x_dot_e1, const Eigen::Vector3d &p_e2, const Vector6d &wrench_e2, double dt);\n\n    /**\n      Initialize the estimator\n\n      @param pc The initial joint position estimate.\n    **/\n    void initialize(const Eigen::Vector3d &pc);\n    void setObserverGain(double gain) {constant_gain_ = gain;}\n    virtual bool getParams(const ros::NodeHandle &n);\n\n  private:\n    Eigen::Vector3d pc_;\n    Eigen::Matrix3d P_, Q_, R_;\n    double constant_gain_;\n  };\n}\n#endif\n", "meta": {"hexsha": "50423985036aa5920d680199f062d023d595d384", "size": 2342, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pr2_algorithms/include/pr2_algorithms/mechanism_identification/kalman_filter.hpp", "max_stars_repo_name": "diogoalmeida/pr2_controller_framework", "max_stars_repo_head_hexsha": "852240638d8da439485d69fb1f627db5845c6820", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pr2_algorithms/include/pr2_algorithms/mechanism_identification/kalman_filter.hpp", "max_issues_repo_name": "diogoalmeida/pr2_controller_framework", "max_issues_repo_head_hexsha": "852240638d8da439485d69fb1f627db5845c6820", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pr2_algorithms/include/pr2_algorithms/mechanism_identification/kalman_filter.hpp", "max_forks_repo_name": "diogoalmeida/pr2_controller_framework", "max_forks_repo_head_hexsha": "852240638d8da439485d69fb1f627db5845c6820", "max_forks_repo_licenses": ["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.4848484848, "max_line_length": 159, "alphanum_fraction": 0.7245943638, "num_tokens": 565, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079208, "lm_q2_score": 0.61878043374385, "lm_q1q2_score": 0.49545255023798496}}
{"text": "#include <vi/ea.h>\n\n#include <boost/lexical_cast.hpp>\n#include <boost/program_options.hpp>\n\n#include <cstdio>\n#include <iostream>\n#include <random>\n#include <string>\n\n// Merciful C++ gods, please absolve me of these sins\n\n#define BUILD_SYSTEM(PARENT_SELECTION, ADULT_SELECTION) \\\n    vi::ea::build_system( \\\n        std::default_random_engine{std::random_device{}()}, \\\n        vi::ea::dynamic_bit_vector_creator{ \\\n            variables[\"problem_size\"].as<unsigned>(), \\\n            variables[\"problem_size\"].as<unsigned>()}, \\\n        PARENT_SELECTION, \\\n        vi::ea::reproduction::sexual{ \\\n            variables[\"mutation_rate\"].as<double>(), \\\n            variables[\"crossover_rate\"].as<double>(), \\\n            variables[\"crossover_points\"].as<unsigned>()}, \\\n        ADULT_SELECTION, \\\n        variables[\"population_size\"].as<unsigned>(), \\\n        [] (const auto& genotype) \\\n        { \\\n            unsigned sum = 0; \\\n            for (vi::ea::dynamic_bit_vector::size_type i = 0; i != target_value.size(); ++i) \\\n            { \\\n                if (target_value[i] == genotype[i]) \\\n                { \\\n                    ++sum; \\\n                } \\\n            } \\\n            if (sum == genotype.size()) \\\n            { \\\n                solution_found = true; \\\n            } \\\n            return static_cast<double>(sum) / static_cast<double>(genotype.size()); \\\n        })\n\nnamespace po = boost::program_options;\npo::variables_map variables{};\n\nvi::ea::dynamic_bit_vector target_value{};\nbool solution_found = false;\n\ntemplate <typename system_type>\nvoid run_system(system_type&& system)\n{\n    unsigned generation;\n    double fitness_mean, fitness_std_dev;\n    typename system_type::individual_type const* best_individual;\n\n    while (true)\n    {\n        std::tie(generation, fitness_mean, fitness_std_dev, best_individual) = system.stats();\n\n        std::printf(\"%d %f %f %f %s\\n\",\n                    generation,\n                    best_individual->fitness,\n                    fitness_mean,\n                    fitness_std_dev,\n                    boost::lexical_cast<std::string>(best_individual->genotype).c_str());\n\n        if (generation >= variables[\"generations\"].as<unsigned>())\n        {\n            break;\n        }\n\n        system.evolve();\n    }\n}\n\nint main(int argc, char** argv)\n{\n    try\n    {\n        po::options_description description{\"Options\"};\n        description.add_options()\n            (\"adult_selection\", po::value<std::string>()->default_value(\"full\"), \"Adult selection (full/mixed/over)\")\n            (\"child_count\", po::value<unsigned>()->default_value(150), \"Child count used in mixed/over adult selection\")\n            (\"crossover_points\", po::value<unsigned>()->default_value(1), \"Crossover points\")\n            (\"crossover_rate\", po::value<double>()->default_value(1.0), \"Crossover rate\")\n            (\"epsilon\", po::value<double>()->default_value(0.1), \"Tournament probability of selecting random winner\")\n            (\"generations\", po::value<unsigned>()->default_value(1000), \"Generation count\")\n            (\"group_size\", po::value<unsigned>()->default_value(10), \"Tournament group size\")\n            (\"mutation_rate\", po::value<double>()->default_value(0.001), \"Mutation rate\")\n            (\"parent_selection\", po::value<std::string>()->default_value(\"proportionate\"), \"Parent selection (proportionate/rank/sigma/tournament)\")\n            (\"population_size\", po::value<unsigned>()->default_value(100), \"Population size\")\n            (\"problem_size\", po::value<unsigned>()->default_value(40), \"Problem size\")\n            (\"random_target\", \"Random target string\")\n            (\"rank_max\", po::value<double>()->default_value(1.5), \"Rank selection pressure ('max')\");\n\n        po::store(po::parse_command_line(argc, argv, description), variables);\n\n        target_value = vi::ea::dynamic_bit_vector{variables[\"problem_size\"].as<unsigned>()};\n\n        if (variables.count(\"random_target\"))\n        {\n            auto random_generator   = std::default_random_engine{std::random_device{}()};\n            auto value_distribution = std::bernoulli_distribution{};\n\n            for (vi::ea::dynamic_bit_vector::size_type i = 0; i != target_value.size(); ++i)\n            {\n                target_value[i] = value_distribution(random_generator);\n            }\n        }\n        else\n        {\n            target_value.set();\n        }\n\n        const auto adult_selection  = variables[\"adult_selection\"].as<std::string>();\n        const auto parent_selection = variables[\"parent_selection\"].as<std::string>();\n\n        if (adult_selection == \"full\" and parent_selection == \"proportionate\")\n        {\n            run_system(BUILD_SYSTEM(\n                vi::ea::parent_selection::fitness_proportionate{},\n                vi::ea::adult_selection::full_generational_replacement{}));\n        }\n        else if (adult_selection == \"full\" and parent_selection == \"rank\")\n        {\n            run_system(BUILD_SYSTEM(\n                vi::ea::parent_selection::rank{variables[\"rank_max\"].as<double>()},\n                vi::ea::adult_selection::full_generational_replacement{}));\n        }\n        else if (adult_selection == \"full\" and parent_selection == \"sigma\")\n        {\n            run_system(BUILD_SYSTEM(\n                vi::ea::parent_selection::sigma{},\n                vi::ea::adult_selection::full_generational_replacement{}));\n        }\n        else if (adult_selection == \"full\" and parent_selection == \"tournament\")\n        {\n            auto parent_selection = vi::ea::parent_selection::tournament{\n                variables[\"group_size\"].as<unsigned>(),\n                variables[\"epsilon\"].as<double>()};\n\n            run_system(BUILD_SYSTEM(parent_selection, vi::ea::adult_selection::full_generational_replacement{}));\n        }\n        else if (adult_selection == \"mixed\" and parent_selection == \"proportionate\")\n        {\n            run_system(BUILD_SYSTEM(\n                vi::ea::parent_selection::fitness_proportionate{},\n                vi::ea::adult_selection::generational_mixing{variables[\"child_count\"].as<unsigned>()}));\n        }\n        else if (adult_selection == \"mixed\" and parent_selection == \"rank\")\n        {\n            run_system(BUILD_SYSTEM(\n                vi::ea::parent_selection::rank{variables[\"rank_max\"].as<double>()},\n                vi::ea::adult_selection::generational_mixing{variables[\"child_count\"].as<unsigned>()}));\n        }\n        else if (adult_selection == \"mixed\" and parent_selection == \"sigma\")\n        {\n            run_system(BUILD_SYSTEM(\n                vi::ea::parent_selection::sigma{},\n                vi::ea::adult_selection::generational_mixing{variables[\"child_count\"].as<unsigned>()}));\n        }\n        else if (adult_selection == \"mixed\" and parent_selection == \"tournament\")\n        {\n            auto parent_selection = vi::ea::parent_selection::tournament{\n                variables[\"group_size\"].as<unsigned>(),\n                variables[\"epsilon\"].as<double>()};\n\n            run_system(BUILD_SYSTEM(\n                parent_selection,\n                vi::ea::adult_selection::generational_mixing{variables[\"child_count\"].as<unsigned>()}));\n        }\n        else if (adult_selection == \"over\" and parent_selection == \"proportionate\")\n        {\n            run_system(BUILD_SYSTEM(\n                vi::ea::parent_selection::fitness_proportionate{},\n                vi::ea::adult_selection::overproduction{variables[\"child_count\"].as<unsigned>()}));\n        }\n        else if (adult_selection == \"over\" and parent_selection == \"rank\")\n        {\n            run_system(BUILD_SYSTEM(\n                vi::ea::parent_selection::rank{variables[\"rank_max\"].as<double>()},\n                vi::ea::adult_selection::overproduction{variables[\"child_count\"].as<unsigned>()}));\n        }\n        else if (adult_selection == \"over\" and parent_selection == \"sigma\")\n        {\n            run_system(BUILD_SYSTEM(\n                vi::ea::parent_selection::sigma{},\n                vi::ea::adult_selection::overproduction{variables[\"child_count\"].as<unsigned>()}));\n        }\n        else if (adult_selection == \"over\" and parent_selection == \"tournament\")\n        {\n            auto parent_selection = vi::ea::parent_selection::tournament{\n                variables[\"group_size\"].as<unsigned>(),\n                variables[\"epsilon\"].as<double>()};\n\n            run_system(BUILD_SYSTEM(\n                parent_selection,\n                vi::ea::adult_selection::overproduction{variables[\"child_count\"].as<unsigned>()}));\n        }\n    }\n    catch (const po::error& error)\n    {\n        std::cerr << \"error: \" << error.what() << std::endl;\n        return EXIT_FAILURE;\n    }\n\n    return solution_found ? 1 : 0;\n}\n\n", "meta": {"hexsha": "18508bfd936b8b5c0b5c490f17644f56d2b6a4f8", "size": 8720, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "project_2/program/onemax.cpp", "max_stars_repo_name": "pveierland/permve-ntnu-it3708", "max_stars_repo_head_hexsha": "1066d5c1af5c953dbaf129d7e05ce32f2d4292aa", "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": "project_2/program/onemax.cpp", "max_issues_repo_name": "pveierland/permve-ntnu-it3708", "max_issues_repo_head_hexsha": "1066d5c1af5c953dbaf129d7e05ce32f2d4292aa", "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": "project_2/program/onemax.cpp", "max_forks_repo_name": "pveierland/permve-ntnu-it3708", "max_forks_repo_head_hexsha": "1066d5c1af5c953dbaf129d7e05ce32f2d4292aa", "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": 41.5238095238, "max_line_length": 148, "alphanum_fraction": 0.5838302752, "num_tokens": 1824, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.49545254435216635}}
{"text": "#include \"CALPHADConcSolverBinary.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    printf(\"Compiled by an OpenMP-compliant implementation.\\n\");\n#endif\n\n    std::cout << \"Run test with \" << omp_get_max_threads() << \" threads\"\n              << std::endl;\n\n    std::cout << \" Read CALPHAD database...\" << std::endl;\n    pt::ptree calphad_db;\n    try\n    {\n        pt::read_json(\"../thermodynamic_data/calphadAuNi.json\", calphad_db);\n    }\n    catch (std::exception& e)\n    {\n        std::cerr << \"exception caught: \" << e.what() << std::endl;\n    }\n\n    double temperature = 1450.;\n\n    CalphadDataType LmixPhaseL[4][MAX_POL_T_INDEX];\n    CalphadDataType LmixPhaseA[4][MAX_POL_T_INDEX];\n\n    {\n        std::string dbnamemixL(\"LmixPhaseL\");\n        pt::ptree Lmix0_db = calphad_db.get_child(dbnamemixL);\n        Thermo4PFM::readLmixBinary(Lmix0_db, LmixPhaseL);\n    }\n    {\n        std::string dbnamemixA(\"LmixPhaseA\");\n        pt::ptree Lmix1_db = calphad_db.get_child(dbnamemixA);\n        Thermo4PFM::readLmixBinary(Lmix1_db, LmixPhaseA);\n    }\n\n    Thermo4PFM::CALPHADSpeciesPhaseGibbsEnergy g_species_phaseL[2];\n    Thermo4PFM::CALPHADSpeciesPhaseGibbsEnergy g_species_phaseA[2];\n\n    {\n        pt::ptree& species0_db = calphad_db.get_child(\"SpeciesA\");\n        std::string dbnameL(\"PhaseL\");\n        std::string dbnameA(\"PhaseA\");\n\n        g_species_phaseL[0].initialize(\"L0\", species0_db.get_child(dbnameL));\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\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 Lmix_L[4];\n    for (int i = 0; i < 4; i++)\n        Lmix_L[i] = LmixPhaseL[i][0] + temperature * LmixPhaseL[i][1];\n    // for(int i=0;i<4;i++)std::cout<<\"Lmix_L[\"<<i<<\"]=\"<<Lmix_L[i]<<std::endl;\n\n    CalphadDataType Lmix_A[4];\n    for (int i = 0; i < 4; i++)\n        Lmix_A[i] = LmixPhaseA[i][0] + temperature * LmixPhaseA[i][1];\n    // for(int i=0;i<4;i++)std::cout<<\"Lmix_A[\"<<i<<\"]=\"<<Lmix_A[i]<<std::endl;\n\n    const double RTinv\n        = 1.0 / (Thermo4PFM::gas_constant_R_JpKpmol * temperature);\n\n    double sol[2] = { 0.5, 0.5 };\n\n    double deviation = 1.e-4;\n\n    double* xhost = new double[2 * N];\n    for (int i = 0; i < 2 * 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            if (!omp_is_initial_device()) abort();\n\n            xhost[2 * i]     = sol[0];\n            xhost[2 * i + 1] = sol[1];\n            double hphi      = 0.5 + (i % 100) * deviation;\n            double c0        = 0.3;\n            Thermo4PFM::CALPHADConcSolverBinary solver;\n            solver.setup(c0, hphi, RTinv, Lmix_L, Lmix_A, fA, fB);\n            nits[i] = solver.ComputeConcentration(&xhost[2 * 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\n        int n = N > 20 ? 20 : N;\n\n        for (int i = 0; i < n; i++)\n        {\n            std::cout << \"Host: x=\" << xhost[2 * i] << \",\" << xhost[2 * i + 1]\n                      << std::endl;\n            std::cout << \"nits=\" << nits[i] << std::endl;\n        }\n        delete[] nits;\n    }\n\n    // Device solve\n    {\n        double* xdev = new double[2 * N];\n        for (int i = 0; i < 2 * N; i++)\n        {\n            xdev[i] = -1;\n        }\n\n        short* nits = new short[N];\n\n        auto t1 = Clock::now();\n\n// clang-format off\n#pragma omp target map(to : sol) \\\n                   map(tofrom : xdev) \\\n                   map(to : fA, fB, Lmix_L, Lmix_A) \\\n                   map(to : RTinv) \\\n                   map(from : nits)                                                     \\\n// clang-format on\n        {\n#pragma omp teams distribute parallel for\n            for (int i = 0; i < N; i++)\n            {\n                // if( omp_is_initial_device() ) abort();\n                xdev[2 * i]     = sol[0];\n                xdev[2 * i + 1] = sol[1];\n\n                double hphi = 0.5 + (i % 100) * deviation;\n                double c0   = 0.3;\n                class Thermo4PFM::CALPHADConcSolverBinary solver;\n                solver.setup(c0, hphi, RTinv, Lmix_L, Lmix_A, fA, fB);\n                nits[i] = solver.ComputeConcentration(&xdev[2 * i], 1.e-8, 50);\n            }\n        }\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 << \"Device time/us/solve: \" << (double)usec / (double)N\n                  << std::endl;\n\n        double tol = 1.e-8;\n        for (int i = 0; i < N; i++)\n        {\n            if (std::abs(xdev[2 * i] - xhost[2 * i]) > tol\n                || std::abs(xdev[2 * i + 1] - xhost[2 * i + 1]) > tol || N < 20)\n            {\n                std::cout << \"Device: x=\" << xdev[2 * i] << \",\"\n                          << xdev[2 * i + 1] << std::endl;\n                std::cout << \"Difference: \" << xdev[2 * i] - xhost[2 * i]\n                          << \", \" << xdev[2 * i + 1] - xhost[2 * i + 1]\n                          << std::endl;\n                std::cout << \"nits[\" << i << \"]=\" << nits[i] << std::endl;\n            }\n        }\n        delete[] nits;\n        delete[] xdev;\n    }\n\n    delete[] xhost;\n}\n", "meta": {"hexsha": "a091718107476954348f850672be2173f2658774", "size": 6567, "ext": "cc", "lang": "C++", "max_stars_repo_path": "drivers/loopCALPHADConcSolverBinary.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": "drivers/loopCALPHADConcSolverBinary.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": "drivers/loopCALPHADConcSolverBinary.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": 31.4210526316, "max_line_length": 89, "alphanum_fraction": 0.5136287498, "num_tokens": 2045, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.800691997339971, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4954525414092569}}
{"text": "#include \"SW.hpp\"\n\n#include \"union_find.hpp\"\n\n#include <cmath>\n#include <boost/math/special_functions/expm1.hpp>\n#include <boost/foreach.hpp>\n#define foreach BOOST_FOREACH\n#include <boost/timer/timer.hpp>\n\nnamespace ising{\n\nWorker::Worker(alps::Parameters const& params):\n  SuperClass(params),\n  mcs_(params),\n  T_(evaluate(\"T\", params)),\n  beta_(1.0/T_),\n  J_(params.value_or_default(\"J\", 1.0)),\n  nsites_(num_sites()),\n  nbonds_(num_bonds()),\n  spins_(nsites_, 1),\n  V2_(nsites_*nsites_)\n{\n  init(params);\n}\n\nvoid Worker::init(alps::Parameters const& params)\n{\n  if(params.defined(\"MODEL\")){\n    std::string modelname = params[\"MODEL\"];\n    if(modelname ==  std::string(\"Ising\")){\n      ene_const_ = nbonds_ * J_;\n      q_ = 2;\n      J_ *= 2;\n    }else if(modelname == std::string(\"Potts\")){\n      q_ = evaluate(\"q\", params);\n      ene_const_ = 0.0;\n    }else{\n      std::cerr << modelname << \" model is not implemented.\";\n      exit(127);\n    }\n  }else{\n    std::cerr << \"parameter \\\"MODEL\\\" is not defined.\";\n    exit(127);\n  }\n  negspin_ = 1.0 / (q_-1);\n  p_ = -boost::math::expm1(-beta_*J_);\n  m2_coeff_ = negspin_;\n  m4_coeff_ = (1.0 + negspin_*negspin_*negspin_)/q_;\n  ene_coeff_ = J_ / p_;\n}\n\nvoid Worker::init_observables(alps::Parameters const&, alps::ObservableSet& obs)\n{\n  obs << alps::RealObservable(\"Time\");\n  obs << alps::RealObservable(\"Speed\");\n  obs << alps::RealObservable(\"Number of Sites\");\n  obs << alps::RealObservable(\"Magnetization^2\");\n  obs << alps::RealObservable(\"Magnetization^4\");\n  obs << alps::RealObservable(\"|Magnetization|\");\n  obs << alps::RealObservable(\"Energy\");\n  obs << alps::RealObservable(\"Susceptibility\");\n  obs << alps::RealObservable(\"Activated Bonds\");\n  obs << alps::RealObservable(\"Activated Bonds^2\");\n}\n\n\nvoid Worker::run(alps::ObservableSet& obs)\n{\n  boost::timer::cpu_timer tm;\n\n  ++mcs_;\n\n  // make clusters\n\n  int activated = 0;\n  std::vector<union_find::Node> nodes(nsites_);\n  foreach(bond_descriptor b, bonds()){\n    const int lsite = source(b);\n    const int rsite = target(b);\n    if( spins_[lsite] == spins_[rsite] && random_01() < p_){\n      union_find::unify(nodes, lsite, rsite);\n      ++activated;\n    }\n  }\n\n  // flip spins\n\n  double ma = 0.0;\n  std::vector<int> cluster_size2;\n  std::vector<int> cluster_spin;\n  int id = 0;\n  for(int site=0; site<nsites_; ++site){\n    int ri = union_find::root_index(nodes, site);\n    union_find::Node &root = nodes[ri];\n    if(root.id == -1){\n      root.id = id++;\n      cluster_size2.push_back(root.size*root.size);\n      cluster_spin.push_back(q_ * random_01());\n    }\n    spins_[site] = cluster_spin[root.id];\n    ma += spins_[site] == 0 ? 1.0 : -negspin_;\n  }\n\n  if(!is_thermalized()){\n    return;\n  }\n\n  // measure \n\n  const int nc = cluster_size2.size();\n  double m2 = 0.0;\n  double m4 = 0.0;\n  for(int ci=0; ci < nc; ++ci){\n    m4 += m4_coeff_ * cluster_size2[ci] * cluster_size2[ci];\n    m4 += 6 * cluster_size2[ci] * m2;\n    m2 += m2_coeff_ * cluster_size2[ci];\n  }\n  const double V2 = nsites_ * nsites_;\n  m2 /= V2;\n  m4 /= (V2*V2);\n\n  double ene = ene_const_ - ene_coeff_ * activated;\n\n  obs[\"Magnetization^2\"] << m2;\n  obs[\"Magnetization^4\"] << m4;\n  obs[\"|Magnetization|\"] << std::abs(ma) / nsites_;\n  obs[\"Susceptibility\"] << m2 * nsites_ *  beta_;\n  obs[\"Number of Sites\"] << 1.0 * nsites_;\n  obs[\"Energy\"] << ene;\n  obs[\"Activated Bonds\"] << 1.0*activated;\n  obs[\"Activated Bonds^2\"] << 1.0*activated*activated;\n\n  const double sec = tm.elapsed().wall * 1.0e-9;\n  obs[\"Time\"] << sec;\n  obs[\"Speed\"] << 1.0/sec;\n}\n\nvoid Evaluator::evaluate(alps::ObservableSet& obs) const\n{\n  const double T = alps::evaluate(\"T\", params_);\n  const double beta = 1.0/T;\n\n  alps::RealObsevaluator m2 = obs[\"Magnetization^2\"];\n  alps::RealObsevaluator m4 = obs[\"Magnetization^4\"];\n  alps::RealObsevaluator ma = obs[\"|Magnetization|\"];\n  alps::RealObsevaluator nsites = obs[\"Number of Sites\"];\n  alps::RealObsevaluator n = obs[\"Activated Bonds\"];\n  alps::RealObsevaluator n2 = obs[\"Activated Bonds^2\"];\n\n  alps::RealObsevaluator binder = m4 / (m2*m2);\n  binder.rename(\"Binder Ratio\");\n  obs.addObservable(binder);\n\n  alps::RealObsevaluator csus = (m2 - ma * ma) * nsites * beta;\n  csus.rename(\"Connected Susceptibility\");\n  obs.addObservable(csus);\n\n  const double J = static_cast<double>(params_.value_or_default(\"J\", 1.0)) * (params_[\"MODEL\"]==std::string(\"Ising\") ? 2.0:1.0);\n\n  const double bj = -beta*J;\n  const double coeff = bj / (boost::math::expm1(bj));\n  alps::RealObsevaluator spec = (n2 - n*n + std::exp(bj)*n) * coeff * coeff;\n  spec.rename(\"Specific Heat\");\n  obs.addObservable(spec);\n}\n\n} // end of namespace ising\n\n", "meta": {"hexsha": "2a0c03e8854472be84cd33b49ed78cfecb651d1c", "size": 4631, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/SW.cpp", "max_stars_repo_name": "yomichi/Ising-SW", "max_stars_repo_head_hexsha": "91631721ca89c2b06e1ca9ad5ea9cece4c8edba2", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/SW.cpp", "max_issues_repo_name": "yomichi/Ising-SW", "max_issues_repo_head_hexsha": "91631721ca89c2b06e1ca9ad5ea9cece4c8edba2", "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/SW.cpp", "max_forks_repo_name": "yomichi/Ising-SW", "max_forks_repo_head_hexsha": "91631721ca89c2b06e1ca9ad5ea9cece4c8edba2", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.2411764706, "max_line_length": 128, "alphanum_fraction": 0.6378751889, "num_tokens": 1482, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.800691997339971, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4954525414092569}}
{"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_TREVC_HPP\n#define BOOST_NUMERIC_BINDINGS_LAPACK_TREVC_HPP\n\n#include <complex>\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/traits/detail/array.hpp>\n// #include <boost/numeric/bindings/traits/std_vector.hpp>\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n#  include <boost/static_assert.hpp>\n#  include <boost/type_traits.hpp>\n#endif \n\n\nnamespace boost { namespace numeric { namespace bindings { \n\n  namespace lapack {\n\n    ///////////////////////////////////////////////////////////////////\n    //\n    // Compute eigenvectors of Schur matrix (computed by gees).\n    // \n    ///////////////////////////////////////////////////////////////////\n\n    /* \n     * trevc() computes the eigenvectors using the Schur factorization\n     *\n     * Let  A = U * S * herm(U), then trecv computes the eigenvectors of\n     * S, and may optionally apply them to U.\n     *\n     * To compute the Schur factorization, see gees.\n     */ \n\n    namespace detail {\n      inline \n      void trevc (char const side, char const howmny, const logical_t* select, int const n,\n                 float* t, int const ldt, float* vl, int const ldvl, float* vr, int const ldvr,\n\t\t int const mm, int& m, float* work, int& info) \n      {\n        LAPACK_STREVC (&side, &howmny, select, &n, t, &ldt, vl, &ldvl, vr, &ldvr, &mm, &m, work, &info);\n      }\n\n      inline \n      void trevc (char const side, char const howmny, const logical_t* select, int const n,\n                 double* t, int const ldt, double* vl, int const ldvl, double* vr, int const ldvr,\n\t\t int const mm, int& m, double* work, int& info) \n      {\n        LAPACK_DTREVC (&side, &howmny, select, &n, t, &ldt, vl, &ldvl, vr, &ldvr, &mm, &m, work, &info);\n      }\n\n      inline \n      void trevc (char const side, char const howmny, const logical_t* select, int const n,\n                 traits::complex_f* t, int const ldt, traits::complex_f* vl, int const ldvl, traits::complex_f* vr, int const ldvr,\n                 int const mm, int& m, traits::complex_f* work, int& info) \n      {\n        LAPACK_CTREVC (&side, &howmny, select, &n, traits::complex_ptr(t), &ldt, traits::complex_ptr(vl), &ldvl,\n\t\t\ttraits::complex_ptr(vr), &ldvr, &mm, &m, traits::complex_ptr(work+n), traits::complex_ptr(work), &info);\n      }\n\n      inline \n      void trevc (char const side, char const howmny, const logical_t* select, int const n,\n                  traits::complex_d* t, int const ldt, traits::complex_d* vl, int const ldvl, traits::complex_d* vr, int const ldvr,\n\t\t  int const mm, int& m, traits::complex_d* work, int& info)\n      {\n        LAPACK_ZTREVC (&side, &howmny, select, &n, traits::complex_ptr(t), &ldt,\n      \t               traits::complex_ptr(vl), &ldvl, traits::complex_ptr(vr), &ldvr,\n\t\t       &mm, &m, traits::complex_ptr(work+n), traits::complex_ptr(work), &info);\n      }\n\n    } \n\n    // Compute Schur factorization with Schur vectors\n    template <typename MatrT, typename VL, typename VR, typename Work>\n    inline\n    int trevc (char const side, char const howmny, MatrT& t, VL& vl, VR& vr, Work& work) {\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrT>::matrix_structure, \n        traits::general_t\n      >::value)); \n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<VL>::matrix_structure, \n        traits::general_t\n      >::value)); \n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<VR>::matrix_structure, \n        traits::general_t\n      >::value)); \n#endif \n\n      int const n = traits::matrix_size1 (t);\n      assert (n == traits::matrix_size2 (t)); \n      assert (n == traits::matrix_size1 (vl)); \n      assert (n == traits::matrix_size2 (vl)); \n      assert (n == traits::matrix_size1 (vr)); \n      assert (n == traits::matrix_size2 (vr)); \n      assert (3*n <= traits::vector_size (work)); \n\n      logical_t* select=0;\n\n      int mm=n;\n      int m;\n      int info; \n      detail::trevc (side, howmny, select, n,\n                    traits::matrix_storage (t), \n                    traits::leading_dimension (t),\n                    traits::matrix_storage (vl),\n                    traits::leading_dimension (vl),\n                    traits::matrix_storage (vr),\n                    traits::leading_dimension (vr),\n\t\t    mm,\n\t\t    m,\n                    traits::vector_storage (work),\n                    info);\n      return info; \n    }\n\n  }\n\n}}}\n\n#endif \n", "meta": {"hexsha": "f89914811a4570423ab1c2cfa2b91aa82000d324", "size": 4986, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/bindings/lapack/trevc.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/trevc.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/trevc.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": 35.8705035971, "max_line_length": 132, "alphanum_fraction": 0.6040914561, "num_tokens": 1326, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.49545253846634735}}
{"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_ATANPI_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_ATANPI_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 inverse tangent in \\f$\\pi\\f$ multiples.\n\n\n    @par Header <boost/simd/function/atanpi.hpp>\n\n    @par Note\n\n      For every parameter of floating type `atanpi(x)`\n      returns the arc @c r in the interval  \\f$[-0.5, 0.5[\\f$\n      such that <tt>tanpi(r) == x</tt>.\n\n    @see atan2, atan2d, atand, atan, tanpi\n\n\n    @par Example:\n\n      @snippet atanpi.cpp atanpi\n\n    @par Possible output:\n\n      @snippet atanpi.txt atanpi\n\n  **/\n  IEEEValue atanpi(IEEEValue const& x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/atanpi.hpp>\n#include <boost/simd/function/simd/atanpi.hpp>\n\n#endif\n", "meta": {"hexsha": "2fedcc0b7c44aaac7bbb8516f1e46bb4a15c0392", "size": 1215, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/atanpi.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/atanpi.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/atanpi.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 23.8235294118, "max_line_length": 100, "alphanum_fraction": 0.5810699588, "num_tokens": 286, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.49545253846634735}}
{"text": "/**\n * \\ file Chebyshev2Filter.cpp\n */\n\n#include <ATK/EQ/Chebyshev2Filter.h>\n#include <ATK/EQ/IIRFilter.h>\n\n#include <ATK/Mock/FFTCheckerFilter.h>\n#include <ATK/Mock/SimpleSinusGeneratorFilter.h>\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_NO_MAIN\n#include <boost/test/unit_test.hpp>\n\n#define PROCESSSIZE (1024*64)\n\nBOOST_AUTO_TEST_CASE( IIRFilter_Chebyshev2LowPassCoefficients_1k_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(1000);\n  \n  ATK::IIRFilter<ATK::Chebyshev2LowPassCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_cut_frequency(100);\n  filter.set_ripple(3);\n  filter.set_order(3);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(100, 0));\n  frequency_checks.push_back(std::make_pair(1000, 0.533158264494777));\n  frequency_checks.push_back(std::make_pair(10000, 0));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_Chebyshev2LowPassCoefficients_100_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(100);\n  \n  ATK::IIRFilter<ATK::Chebyshev2LowPassCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_cut_frequency(100);\n  filter.set_ripple(3);\n  filter.set_order(3);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(10, 0));\n  frequency_checks.push_back(std::make_pair(100, 0.8413951416367915));\n  frequency_checks.push_back(std::make_pair(1000, 0));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_Chebyshev2LowPassCoefficients_2k_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(2000);\n  \n  ATK::IIRFilter<ATK::Chebyshev2LowPassCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_cut_frequency(100);\n  filter.set_ripple(3);\n  filter.set_order(3);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(100, 0));\n  frequency_checks.push_back(std::make_pair(1000, 0));\n  frequency_checks.push_back(std::make_pair(2000, 0.38439870861360015));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_Chebyshev2LowPassCoefficients_200_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(200);\n  \n  ATK::IIRFilter<ATK::Chebyshev2LowPassCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_cut_frequency(100);\n  filter.set_ripple(3);\n  filter.set_order(3);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(100, 0));\n  frequency_checks.push_back(std::make_pair(200, 0.8411929081798066));\n  frequency_checks.push_back(std::make_pair(1000, 0));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_Chebyshev2HighPassCoefficients_1k_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(1000);\n  \n  ATK::IIRFilter<ATK::Chebyshev2HighPassCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_cut_frequency(100);\n  filter.set_ripple(3);\n  filter.set_order(3);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(100, 0));\n  frequency_checks.push_back(std::make_pair(1000, 0.9999904942771862));\n  frequency_checks.push_back(std::make_pair(10000, 0));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_Chebyshev2HighPassCoefficients_100_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(100);\n  \n  ATK::IIRFilter<ATK::Chebyshev2HighPassCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_cut_frequency(100);\n  filter.set_ripple(3);\n  filter.set_order(3);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(10, 0));\n  frequency_checks.push_back(std::make_pair(100, 0.8413951415475837));\n  frequency_checks.push_back(std::make_pair(1000, 0));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_Chebyshev2HighPassCoefficients_2k_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(2000);\n  \n  ATK::IIRFilter<ATK::Chebyshev2HighPassCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_cut_frequency(100);\n  filter.set_ripple(3);\n  filter.set_order(3);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(100, 0));\n  frequency_checks.push_back(std::make_pair(1000, 0));\n  frequency_checks.push_back(std::make_pair(2000, 0.9999976499956404));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_Chebyshev2HighPassCoefficients_200_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(200);\n  \n  ATK::IIRFilter<ATK::Chebyshev2HighPassCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_cut_frequency(100);\n  filter.set_ripple(3);\n  filter.set_order(3);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(100, 0));\n  frequency_checks.push_back(std::make_pair(200, 0.9993415485050974));\n  frequency_checks.push_back(std::make_pair(1000, 0));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_Chebyshev2BandPassCoefficients_1k_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(1000);\n  \n  ATK::IIRFilter<ATK::Chebyshev2BandPassCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_cut_frequencies(std::make_pair(200, 1000));\n  filter.set_ripple(3);\n  filter.set_order(3);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(100, 0));\n  frequency_checks.push_back(std::make_pair(1000, 0.8413951423132554));\n  frequency_checks.push_back(std::make_pair(10000, 0));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_Chebyshev2BandPassCoefficients_100_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(100);\n  \n  ATK::IIRFilter<ATK::Chebyshev2BandPassCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_cut_frequencies(std::make_pair(200, 1000));\n  filter.set_ripple(3);\n  filter.set_order(3);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(10, 0));\n  frequency_checks.push_back(std::make_pair(100, 0.8337339391384047));\n  frequency_checks.push_back(std::make_pair(1000, 0));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_Chebyshev2BandPassCoefficients_2k_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(2000);\n  \n  ATK::IIRFilter<ATK::Chebyshev2BandPassCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_cut_frequencies(std::make_pair(200, 1000));\n  filter.set_ripple(3);\n  filter.set_order(3);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(100, 0));\n  frequency_checks.push_back(std::make_pair(1000, 0));\n  frequency_checks.push_back(std::make_pair(2000, 0.8335118338740579));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_Chebyshev2BandPassCoefficients_200_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(200);\n  \n  ATK::IIRFilter<ATK::Chebyshev2BandPassCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_cut_frequencies(std::make_pair(200, 1000));\n  filter.set_ripple(3);\n  filter.set_order(3);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(100, 0));\n  frequency_checks.push_back(std::make_pair(200, 0.8413950585465586));\n  frequency_checks.push_back(std::make_pair(1000, 0));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_Chebyshev2BandStopCoefficients_1k_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(1000);\n  \n  ATK::IIRFilter<ATK::Chebyshev2BandStopCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_cut_frequencies(std::make_pair(200, 1000));\n  filter.set_ripple(3);\n  filter.set_order(3);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(100, 0));\n  frequency_checks.push_back(std::make_pair(1000, 0.8413951519207091));\n  frequency_checks.push_back(std::make_pair(10000, 0));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_Chebyshev2BandStopCoefficients_100_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(100);\n  \n  ATK::IIRFilter<ATK::Chebyshev2BandStopCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_cut_frequencies(std::make_pair(200, 1000));\n  filter.set_ripple(3);\n  filter.set_order(3);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(10, 0));\n  frequency_checks.push_back(std::make_pair(100, 0.9998108684766274));\n  frequency_checks.push_back(std::make_pair(1000, 0));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_Chebyshev2BandStopCoefficients_2k_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(2000);\n  \n  ATK::IIRFilter<ATK::Chebyshev2BandStopCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_cut_frequencies(std::make_pair(200, 1000));\n  filter.set_ripple(3);\n  filter.set_order(3);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(100, 0));\n  frequency_checks.push_back(std::make_pair(1000, 0));\n  frequency_checks.push_back(std::make_pair(2000, 0.999863033497463));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_Chebyshev2BandStopCoefficients_200_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(200);\n  \n  ATK::IIRFilter<ATK::Chebyshev2BandStopCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_cut_frequencies(std::make_pair(200, 1000));\n  filter.set_ripple(3);\n  filter.set_order(3);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(100, 0));\n  frequency_checks.push_back(std::make_pair(200, 0.8413938019260473));\n  frequency_checks.push_back(std::make_pair(1000, 0));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n", "meta": {"hexsha": "4b06414f95cd9ff50e8076fc5c3b4e1d23a6d69b", "size": 16494, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/EQ/Chebyshev2Filter.cpp", "max_stars_repo_name": "apohl79/AudioTK", "max_stars_repo_head_hexsha": "05ac241b0bc6a8f841d93257b4d81e5961b1f627", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-05-17T15:29:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T22:26:08.000Z", "max_issues_repo_path": "tests/EQ/Chebyshev2Filter.cpp", "max_issues_repo_name": "apohl79/AudioTK", "max_issues_repo_head_hexsha": "05ac241b0bc6a8f841d93257b4d81e5961b1f627", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/EQ/Chebyshev2Filter.cpp", "max_forks_repo_name": "apohl79/AudioTK", "max_forks_repo_head_hexsha": "05ac241b0bc6a8f841d93257b4d81e5961b1f627", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-04-21T13:43:57.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-28T19:10:14.000Z", "avg_line_length": 33.2540322581, "max_line_length": 73, "alphanum_fraction": 0.7734327634, "num_tokens": 4685, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324983301567, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4953867640860905}}
{"text": "/*\n    Copyright 2012 Chung-Lin Wen, Davide Anastasia\n    Use, modification and distribution are subject to the Boost Software License,\n    Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n    http://www.boost.org/LICENSE_1_0.txt).\n*/\n\n/*************************************************************************************************/\n\n#ifndef BOOST_GIL_EXTENSION_TOOLBOX_COLOR_SPACES_XYZ_HPP\n#define BOOST_GIL_EXTENSION_TOOLBOX_COLOR_SPACES_XYZ_HPP\n\n////////////////////////////////////////////////////////////////////////////////////////\n/// \\file xyz.hpp\n/// \\brief Support for CIE XYZ color space\n/// \\author Chung-Lin Wen, Davide Anastasia \\n\n///\n/// \\date 2012 \\n\n///\n////////////////////////////////////////////////////////////////////////////////////////\n\n#include <boost/cast.hpp>\n\nnamespace boost{ namespace gil {\n\n/// \\addtogroup ColorNameModel\n/// \\{\nnamespace xyz_color_space\n{\n/// \\brief x Color Component\nstruct x_t {};    \n/// \\brief y Color Component\nstruct y_t {};\n/// \\brief z Color Component\nstruct z_t {}; \n}\n/// \\}\n\n/// \\ingroup ColorSpaceModel\ntypedef mpl::vector3< xyz_color_space::x_t\n                    , xyz_color_space::y_t\n                    , xyz_color_space::z_t\n                    > xyz_t;\n\n/// \\ingroup LayoutModel\ntypedef layout<xyz_t> xyz_layout_t;\n\nGIL_DEFINE_ALL_TYPEDEFS( 32f, xyz );\n\n/// \\ingroup ColorConvert\n/// \\brief RGB to XYZ\n/// <a href=\"http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html\">Link</a> \n/// \\note rgb_t is assumed to be sRGB D65\ntemplate <>\nstruct default_color_converter_impl< rgb_t, xyz_t >\n{\nprivate:\n    GIL_FORCEINLINE\n    bits32f inverse_companding(bits32f sample) const\n    {\n        if ( sample > 0.04045f )\n        {\n            return powf((( sample + 0.055f ) / 1.055f ), 2.4f);\n        }\n        else\n        {\n            return ( sample / 12.92f );\n        }\n    }\n\npublic:\n    template <typename P1, typename P2>\n    void operator()( const P1& src, P2& dst ) const\n    {\n        using namespace xyz_color_space;\n\n        bits32f red(\n                    inverse_companding(\n                        channel_convert<bits32f>( get_color( src, red_t() ))\n                        )\n                    );\n        bits32f green(\n                    inverse_companding(\n                        channel_convert<bits32f>( get_color( src, green_t() ))\n                        )\n                    );\n        bits32f blue(\n                    inverse_companding(\n                        channel_convert<bits32f>( get_color( src, blue_t() ))\n                        )\n                    );\n\n        get_color( dst, x_t() ) =\n                red * 0.4124564f +\n                green * 0.3575761f +\n                blue * 0.1804375f;\n        get_color( dst, y_t() ) =\n                red * 0.2126729f +\n                green * 0.7151522f +\n                blue * 0.0721750f;\n        get_color( dst, z_t() ) =\n                red * 0.0193339f +\n                green * 0.1191920f +\n                blue * 0.9503041f;\n    }\n};\n\n/// \\ingroup ColorConvert\n/// \\brief XYZ to RGB\ntemplate <>\nstruct default_color_converter_impl<xyz_t,rgb_t>\n{\nprivate:\n    GIL_FORCEINLINE\n    bits32f companding(bits32f sample) const\n    {\n        if ( sample > 0.0031308f )\n        {\n            return ( 1.055f * powf( sample, 1.f/2.4f ) - 0.055f );\n        }\n        else\n        {\n            return ( 12.92f * sample );\n        }\n    }\n\npublic:\n    template <typename P1, typename P2>\n    void operator()( const P1& src, P2& dst) const\n    {\n        using namespace xyz_color_space;\n\n        // Note: ideally channel_convert should be compiled out, because xyz_t\n        // is bits32f natively only\n        bits32f x( channel_convert<bits32f>( get_color( src, x_t() ) ) );\n        bits32f y( channel_convert<bits32f>( get_color( src, y_t() ) ) );\n        bits32f z( channel_convert<bits32f>( get_color( src, z_t() ) ) );\n\n        get_color(dst,red_t())  =\n                channel_convert<typename color_element_type<P2, red_t>::type>(\n                    companding( x *  3.2404542f +\n                                y * -1.5371385f +\n                                z * -0.4985314f )\n                    );\n        get_color(dst,green_t()) =\n                channel_convert<typename color_element_type<P2, green_t>::type>(\n                    companding( x * -0.9692660f +\n                                y *  1.8760108f +\n                                z *  0.0415560f )\n                    );\n        get_color(dst,blue_t()) =\n                channel_convert<typename color_element_type<P2, blue_t>::type>(\n                    companding( x *  0.0556434f +\n                                y * -0.2040259f +\n                                z *  1.0572252f )\n                    );\n    }\n};\n\n} // namespace gil\n} // namespace boost\n\n#endif // BOOST_GIL_EXTENSION_TOOLBOX_COLOR_SPACES_XYZ_HPP\n", "meta": {"hexsha": "2977c739bd34289cdf8c2317669350f8ec2b9a6c", "size": 4870, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/gil/extension/toolbox/color_spaces/xyz.hpp", "max_stars_repo_name": "smart-make/boost", "max_stars_repo_head_hexsha": "46509a094f8a844eefd5bb8a0030b739a04d79e1", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-12-15T19:55:56.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-15T19:55:56.000Z", "max_issues_repo_path": "boost/gil/extension/toolbox/color_spaces/xyz.hpp", "max_issues_repo_name": "smart-make/boost", "max_issues_repo_head_hexsha": "46509a094f8a844eefd5bb8a0030b739a04d79e1", "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/gil/extension/toolbox/color_spaces/xyz.hpp", "max_forks_repo_name": "smart-make/boost", "max_forks_repo_head_hexsha": "46509a094f8a844eefd5bb8a0030b739a04d79e1", "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.6951219512, "max_line_length": 99, "alphanum_fraction": 0.4991786448, "num_tokens": 1185, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324938410783, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.49538676135824294}}
{"text": "#pragma once\n\n#include <Eigen/Core>\n#include <autodiff/autodiff_types.hpp>\n\nnamespace ccd {\nnamespace autogen {\n\n    template <typename T>\n    using Vector2T = Eigen::Matrix<T, 2, 1>;\n\n    /**\n    * Compute the volume of intersection for an edge given a time\n    * of intersection (toi) and position of intersection (alpha)\n    *\n    * \\f$V = (1-\\tau_I)\\sqrt{\\epsilon^2 \\|e(\\tau_I)\\|^2 + (U_{ij} \\cdot\n    * e(\\tau_I)^\\perp)^2}\\f$\n    *\n    *     @param V_{ijk}          : Vertices positions.\n    *     @param U_{ijk}          : Vertices displacements.\n    *     @param epsilon          : The time scale used for minimal volume.\n    *\n    * @return                     : The space-time interference volume.\n    */\n    template <typename T>\n    T space_time_collision_volume(\n        const Eigen::Vector2d& Vi,\n        const Eigen::Vector2d& Vj,\n        const Vector2T<T>& Ui,\n        const Vector2T<T>& Uj,\n        const T& toi, const T& alpha,\n        const double epsilon);\n\n}\n}\n\n#include \"auto_collision_volume.ipp\"\n", "meta": {"hexsha": "f2355a0f0d87bbb0d3ff7a62a13ad26ec1200ecc", "size": 1019, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "comparisons/STIV/src/autogen/collision_volume.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": "comparisons/STIV/src/autogen/collision_volume.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": "comparisons/STIV/src/autogen/collision_volume.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": 26.8157894737, "max_line_length": 75, "alphanum_fraction": 0.5858684985, "num_tokens": 277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324713956854, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4953867477190043}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2020 Ilias Khairullin <ilias@nil.foundation>\n// Copyright (c) 2020 Mikhail Komarov <nemo@nil.foundation>\n//\n// Distributed under the Boost Software License, Version 1.0\n// See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt\n//---------------------------------------------------------------------------//\n\n#ifndef CRYPTO3_HASH_POSEIDON_MDS_MATRIX_HPP\n#define CRYPTO3_HASH_POSEIDON_MDS_MATRIX_HPP\n\n#include <nil/crypto3/algebra/matrix/matrix.hpp>\n#include <nil/crypto3/algebra/matrix/math.hpp>\n#include <nil/crypto3/algebra/matrix/operators.hpp>\n#include <nil/crypto3/algebra/vector/vector.hpp>\n#include <nil/crypto3/algebra/vector/math.hpp>\n#include <nil/crypto3/algebra/vector/operators.hpp>\n\n#include <nil/crypto3/hash/detail/poseidon/poseidon_policy.hpp>\n\n#include <boost/assert.hpp>\n\nnamespace nil {\n    namespace crypto3 {\n        namespace hashes {\n            namespace detail {\n                template<typename FieldType, std::size_t Arity, std::size_t PartRounds>\n                struct poseidon_mds_matrix {\n                    typedef poseidon_policy<FieldType, Arity, PartRounds> policy_type;\n                    typedef typename FieldType::value_type element_type;\n\n                    constexpr static const std::size_t state_words = policy_type::state_words;\n                    constexpr static const std::size_t half_full_rounds = policy_type::half_full_rounds;\n                    constexpr static const std::size_t part_rounds = policy_type::part_rounds;\n\n                    typedef algebra::matrix<element_type, state_words, state_words> mds_matrix_type;\n                    typedef algebra::vector<element_type, state_words> state_vector_type;\n                    typedef algebra::vector<element_type, state_words - 1> substate_vector_type;\n                    typedef algebra::matrix<element_type, state_words - 1, state_words - 1> mds_submatrix_type;\n\n                    inline void product_with_mds_matrix(state_vector_type &A_vector) const {\n                        A_vector = algebra::vectmatmul(A_vector, mds_matrix);\n                    }\n\n                    constexpr void product_with_inverse_mds_matrix_noalias(const state_vector_type &A_vector_in,\n                                                                           state_vector_type &A_vector_out) const {\n                        A_vector_out = algebra::vectmatmul(A_vector_in, mds_matrix_inverse);\n                    }\n\n                    inline void product_with_equivalent_mds_matrix_init(state_vector_type &A_vector,\n                                                                        std::size_t round_number) const {\n                        BOOST_ASSERT_MSG(round_number == half_full_rounds,\n                                         \"wrong using: product_with_equivalent_mds_matrix_init\");\n                        A_vector = algebra::vectmatmul(A_vector, get_M_i());\n                    }\n\n                    inline void product_with_equivalent_mds_matrix(state_vector_type &A_vector,\n                                                                   std::size_t round_number) const {\n                        BOOST_ASSERT_MSG(round_number >= half_full_rounds &&\n                                             round_number < half_full_rounds + part_rounds,\n                                         \"wrong using: product_with_equivalent_mds_matrix\");\n                        const std::size_t matrix_number_base = part_rounds - (round_number - half_full_rounds) - 1;\n                        const substate_vector_type &v = get_v(matrix_number_base);\n                        state_vector_type temp_vector;\n                        element_type A_0 = A_vector[0];\n                        temp_vector[0] = get_M_0_0();\n                        for (std::size_t i = 1; i < state_words; i++) {\n                            temp_vector[i] = get_w_hat(matrix_number_base)[i - 1];\n                        }\n                        A_vector[0] = algebra::dot(A_vector, temp_vector);\n                        for (std::size_t i = 1; i < state_words; i++) {\n                            A_vector[i] = A_0 * v[i - 1] + A_vector[i];\n                        }\n                    }\n\n                    // private:\n#ifdef CRYPTO3_HASH_POSEIDON_COMPILE_TIME\n                    constexpr\n#endif\n                    inline mds_matrix_type generate_mds_matrix() {\n                        mds_matrix_type new_mds_matrix;\n                        for (std::size_t i = 0; i < state_words; i++) {\n                            for (std::size_t j = 0; j < state_words; j++) {\n                                new_mds_matrix[i][j] = element_type(i + j + state_words).inversed();\n                            }\n                        }\n                        return new_mds_matrix;\n                    }\n\n                    struct equivalent_mds_matrix_type {\n                        typedef std::array<substate_vector_type, part_rounds> subvectors_array;\n\n#ifdef CRYPTO3_HASH_POSEIDON_COMPILE_TIME\n                        constexpr\n#endif\n                        equivalent_mds_matrix_type(const mds_matrix_type &mds_matrix) :\n                            M_i(algebra::get_identity<element_type, state_words>()), w_hat_list(), v_list(), M_0_0() {\n                            mds_matrix_type M_mul(mds_matrix);\n                            mds_submatrix_type M_hat_inverse;\n                            substate_vector_type M_mul_column_slice;\n\n                            for (std::size_t i = 0; i < part_rounds; i++) {\n                                M_hat_inverse =\n                                    algebra::inverse(algebra::submat<state_words - 1, state_words - 1>(M_mul, 1, 1));\n                                w_hat_list[i] = algebra::matvectmul(\n                                    M_hat_inverse, algebra::slice<state_words - 1>(M_mul.column(0), 1));\n                                v_list[i] = algebra::slice<state_words - 1>(M_mul.row(0), 1);\n                                for (std::size_t j = 1; j < state_words; j++) {\n                                    for (std::size_t k = 1; k < state_words; k++) {\n                                        M_i[j][k] = M_mul[j][k];\n                                    }\n                                }\n                                M_mul = algebra::matmul(mds_matrix, M_i);\n                            }\n                            M_0_0 = mds_matrix[0][0];\n                        }\n\n                        mds_matrix_type M_i;\n                        subvectors_array w_hat_list;\n                        subvectors_array v_list;\n                        element_type M_0_0;\n                    };\n\n                    inline const substate_vector_type &get_w_hat(std::size_t w_hat_number) const {\n                        return equivalent_mds_matrix.w_hat_list[w_hat_number];\n                    }\n                    inline const substate_vector_type &get_v(std::size_t v_number) const {\n                        return equivalent_mds_matrix.v_list[v_number];\n                    }\n                    inline const element_type &get_M_0_0() const {\n                        return equivalent_mds_matrix.M_0_0;\n                    }\n                    inline const mds_matrix_type &get_M_i() const {\n                        return equivalent_mds_matrix.M_i;\n                    }\n\n#ifdef CRYPTO3_HASH_POSEIDON_COMPILE_TIME\n                    constexpr\n#endif\n                    poseidon_mds_matrix() :\n                        mds_matrix(generate_mds_matrix()), mds_matrix_inverse(algebra::inverse(mds_matrix)),\n                        equivalent_mds_matrix(mds_matrix) {\n                    }\n\n                    mds_matrix_type mds_matrix;\n                    mds_matrix_type mds_matrix_inverse;\n                    equivalent_mds_matrix_type equivalent_mds_matrix;\n                };\n            }    // namespace detail\n        }        // namespace hashes\n    }            // namespace crypto3\n}    // namespace nil\n\n#endif    // CRYPTO3_HASH_POSEIDON_MDS_MATRIX_HPP\n", "meta": {"hexsha": "fb31bad42499fcb1e356fda22fa7e6f98cf7c7c5", "size": 8134, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/nil/crypto3/hash/detail/poseidon/poseidon_mds_matrix.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/detail/poseidon/poseidon_mds_matrix.hpp", "max_issues_repo_name": "JasonCoombs/crypto3-hash", "max_issues_repo_head_hexsha": "a4f330d14029b0b0330a5697ef24e825137ffded", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 46.0, "max_issues_repo_issues_event_min_datetime": "2019-06-07T23:11:49.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-12T00:09:30.000Z", "max_forks_repo_path": "include/nil/crypto3/hash/detail/poseidon/poseidon_mds_matrix.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": 52.141025641, "max_line_length": 118, "alphanum_fraction": 0.5118023113, "num_tokens": 1564, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681013541613, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.4953571029362617}}
{"text": "#include <cmath>\n#include <cstdio>\n#include <vector>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <Eigen/SVD>\n\n#include <geometry_msgs/Pose.h>\n#include <geometry_msgs/PoseArray.h>\n#include <ros/ros.h>\n\n#include <simple_fiducial_mapping/mapping.h>\n#include <simple_fiducial_mapping/ceres_backend.h>\n\nnamespace simple_fiducial_mapping\n{\nbool areObservationsGoodForSlam(const std::map<size_t, Eigen::Vector3d>& observations)\n{\n  if (observations.size() < 3)\n  {\n    ROS_ERROR_STREAM(\"We got less than 3 observations.\");\n    return false;\n  }\n\n  // Project observations onto ideal image plane.\n  std::vector<Eigen::Vector2d> ideal_image_plane_points;\n  for (const auto& observation_pair : observations)\n  {\n    const Eigen::Vector3d& position = observation_pair.second;\n    if (position.z() >= OBSERVATION_MIN_DISTANCE)\n      // Throw out any observations too close to the camera (they have high error after reprojection).\n      ideal_image_plane_points.push_back(Eigen::Vector2d(position.x() / position.z(), position.y() / position.z()));\n  }\n\n  if (ideal_image_plane_points.size() < 3)\n  {\n    ROS_ERROR_STREAM(\"The number of ideal image plane points is less than 3.\");\n    return false;\n  }\n\n  // Unit vectors along which we'll check point spread.\n  const std::vector<Eigen::Vector2d> direction_vectors{\n    { cos(0.0), sin(0.0) }, { cos(M_PI / 4.0), sin(M_PI / 4.0) }, { cos(M_PI / 2.0), sin(M_PI / 2.0) },\n  };\n\n  // Spread must be large enough along all of our direction vectors.\n  for (const auto direction : direction_vectors)\n  {\n    double min_val = direction.dot(ideal_image_plane_points[0]);\n    double max_val = direction.dot(ideal_image_plane_points[0]);\n    for (const auto& point : ideal_image_plane_points)\n    {\n      double dot_val = direction.dot(point);\n      if (dot_val < min_val)\n        min_val = dot_val;\n      if (dot_val > max_val)\n        max_val = dot_val;\n    }\n    double spread = max_val - min_val;\n    // Intentionally written as a negative check so that a spread of NaN will return false.\n    if (!(spread > OBSERVATION_MIN_SPREAD))\n    {\n      ROS_ERROR_STREAM(\n          \"The current spread: \" << spread << \" is less than the observation min spread: \" << OBSERVATION_MIN_SPREAD);\n      return false;\n    }\n  }\n\n  return true;\n}\n\nstd::map<size_t, Eigen::Vector3d>\ntagDetectionsToObservations(const apriltags2_ros::AprilTagDetectionArray& detections_msg)\n{\n  std::map<size_t, Eigen::Vector3d> observations;\n  for (const auto& detection : detections_msg.detections)\n  {\n    assert(detection.id.size() == 1);\n    size_t fiducial_id = detection.id[0];\n    const auto& position_msg = detection.pose.pose.pose.position;\n    observations[fiducial_id] = Eigen::Vector3d(position_msg.x, position_msg.y, position_msg.z);\n  }\n  return observations;\n}\n\nbool localize(const std::map<size_t, Eigen::Vector3d>& observations, const Eigen::Isometry3d& camera_pose_guess,\n              double max_rmse, Eigen::Isometry3d* computed_camera_pose, MapGraph* map_graph)\n{\n  if (!areObservationsGoodForSlam(observations))\n  {\n    ROS_ERROR(\"Observations are not spread out; not localizing\");\n    return false;\n  }\n\n  Eigen::Quaterniond orientation_guess(camera_pose_guess.rotation());\n  Eigen::Vector3d position_guess = camera_pose_guess.translation();\n\n  ROS_DEBUG_STREAM(\"Localizing from \" << observations.size() << \" observations\");\n\n  size_t camera_pose_id =\n      addCameraPose(0, CameraPose{ position_guess, orientation_guess, false /* is_constant */ }, map_graph);\n  for (const auto& observation_pair : observations)\n  {\n    size_t fiducial_id = observation_pair.first;\n    Eigen::Vector3d fiducial_position = observation_pair.second;\n    addObservation(camera_pose_id, fiducial_id, fiducial_position, map_graph);\n  }\n  OptimizationInfo localization_optimization_info = bundleAdjust(20, map_graph);\n  double rmse = sqrt(computeCartesianMeanSquareError(localization_optimization_info));\n  ROS_INFO(\"Localized with RMSE of %f\", rmse);\n  if (rmse > max_rmse)\n  {\n    return false;\n  }\n\n  const CameraPose& camera_pose = map_graph->camera_poses.at(camera_pose_id);\n  *computed_camera_pose = Eigen::Translation3d(camera_pose.position) * camera_pose.orientation;\n\n  removeCameraPose(camera_pose_id, map_graph);\n\n  return true;\n}\n\n}  // namespace simple_fiducial_mapping\n", "meta": {"hexsha": "7f95761c76a64cd2d1928e87f3b897b883008254", "size": 4292, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mapping.cpp", "max_stars_repo_name": "iron-ox/simple_fiducial_mapping", "max_stars_repo_head_hexsha": "ff940b184349bff3d66e8da33b2c31fee5ce0db7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-08-12T20:54:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T10:35:38.000Z", "max_issues_repo_path": "src/mapping.cpp", "max_issues_repo_name": "iron-ox/simple_fiducial_mapping", "max_issues_repo_head_hexsha": "ff940b184349bff3d66e8da33b2c31fee5ce0db7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mapping.cpp", "max_forks_repo_name": "iron-ox/simple_fiducial_mapping", "max_forks_repo_head_hexsha": "ff940b184349bff3d66e8da33b2c31fee5ce0db7", "max_forks_repo_licenses": ["Apache-2.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.0634920635, "max_line_length": 118, "alphanum_fraction": 0.722972973, "num_tokens": 1073, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.4953502741706093}}
{"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\u2019s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n#pragma once\n\n#include \"../public/KMeans.hpp\"\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 <string>\n\nnamespace fluid {\nnamespace algorithm {\n\nclass SKMeans : public KMeans\n{\n\npublic:\n  void train(const FluidDataSet<std::string, double, 1>& dataset, index k,\n             index maxIter)\n  {\n    using namespace Eigen;\n    using namespace _impl;\n    assert(!mTrained || (dataset.pointSize() == mDims && mK == k));\n    MatrixXd dataPoints = asEigen<Matrix>(dataset.getData());\n    MatrixXd dataPointsT = dataPoints.transpose();\n    if (mTrained) { mAssignments = assignClusters(dataPointsT);}\n    else\n    {\n      mK = k;\n      mDims = dataset.pointSize();\n      initMeans(dataPoints);\n    }\n\n    while (maxIter-- > 0)\n    {\n      mEmbedding = mMeans.matrix() * dataPointsT;\n      auto assignments = assignClusters(mEmbedding);\n      if (!changed(assignments)) { break; }\n      else\n        mAssignments = assignments;\n      updateEmbedding();\n      computeMeans(dataPoints);\n    }\n    mTrained = true;\n  }\n\n\n  void encode(RealMatrixView data, RealMatrixView out,\n                 double alpha = 0.25) const\n  {\n    using namespace Eigen;\n    MatrixXd points = _impl::asEigen<Matrix>(data).transpose();\n    MatrixXd embedding = (mMeans.matrix() * points).array() - alpha;\n    embedding = (embedding.array() > 0).select(embedding, 0).transpose();\n    out <<= _impl::asFluid(embedding);\n  }\n\nprivate:\n\n  void initMeans(Eigen::MatrixXd& dataPoints)\n  {\n    using namespace Eigen;\n    mMeans = ArrayXXd::Zero(mK, mDims);\n    mAssignments =\n        ((0.5 + (0.5 * ArrayXd::Random(dataPoints.rows()))) * (mK - 1))\n            .round()\n            .cast<int>();\n    mEmbedding = MatrixXd::Zero(mK, dataPoints.rows());\n    for (index i = 0; i < dataPoints.rows(); i++)\n      mEmbedding(mAssignments(i), i) = 1;\n    computeMeans(dataPoints);\n  }\n\n  void updateEmbedding()\n  {\n    for (index i = 0; i < mAssignments.cols(); i++)\n    {\n      double val = mEmbedding(mAssignments(i), i);\n      mEmbedding.col(i).setZero();\n      mEmbedding(mAssignments(i), i) = val;\n    }\n  }\n\n\n  Eigen::VectorXi assignClusters(Eigen::MatrixXd& embedding) const\n  {\n    Eigen::VectorXi assignments = Eigen::VectorXi::Zero(embedding.cols());\n    for (index i = 0; i < embedding.cols(); i++)\n    {\n      Eigen::VectorXd::Index maxIndex;\n      embedding.col(i).maxCoeff(&maxIndex);\n      assignments(i) = static_cast<int>(maxIndex);\n    }\n    return assignments;\n  }\n\n\n  void computeMeans(Eigen::MatrixXd& dataPoints)\n  {\n    mMeans = mEmbedding * dataPoints;\n    mMeans.matrix().rowwise().normalize();\n  }\n\n\nprivate:\n  Eigen::MatrixXd mEmbedding;\n};\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "8c66614f98c83dd7a33b788667007ad7ed980328", "size": 3269, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/public/SKMeans.hpp", "max_stars_repo_name": "jamesb93/flucoma-core", "max_stars_repo_head_hexsha": "3e964dd569f6fff15bd5249a705dc0da8f7b2ad8", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/algorithms/public/SKMeans.hpp", "max_issues_repo_name": "jamesb93/flucoma-core", "max_issues_repo_head_hexsha": "3e964dd569f6fff15bd5249a705dc0da8f7b2ad8", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/algorithms/public/SKMeans.hpp", "max_forks_repo_name": "jamesb93/flucoma-core", "max_forks_repo_head_hexsha": "3e964dd569f6fff15bd5249a705dc0da8f7b2ad8", "max_forks_repo_licenses": ["BSD-3-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.7950819672, "max_line_length": 74, "alphanum_fraction": 0.6500458856, "num_tokens": 832, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093946927837, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.49531367542882565}}
{"text": "#include \"tracker.hpp\"\n\n#include <Eigen/Dense>\n\nusing khmot::Observation;\nusing khmot::Tracker;\n\nint main()\n{\n  Observation obs;\n  obs.kalmanObs.state << 0.1, 0.2, 0.3, 0.0, 0.0, 0.0;\n  obs.kalmanObs.covariance = Eigen::MatrixXd::Identity(6, 6);\n  obs.kalmanObs.timestamp = 0.0;\n  std::vector<Observation> v;\n  v.push_back(obs);\n\n  Tracker t;\n  for (int i = 0; i < 10; ++i) {\n    t.update(v, static_cast<double>(i));\n    v[0].kalmanObs.state(0) += 0.001;\n    v[0].kalmanObs.timestamp += 1.0;\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "7ade67e9c3c550c827bae0d7709349c7572bde2f", "size": 511, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "khmot/main.cpp", "max_stars_repo_name": "r7vme/khmot", "max_stars_repo_head_hexsha": "2920ed01c66e906d9099a80bbfd3e5adbbac6633", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-11-08T11:05:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T20:01:37.000Z", "max_issues_repo_path": "khmot/main.cpp", "max_issues_repo_name": "r7vme/khmot", "max_issues_repo_head_hexsha": "2920ed01c66e906d9099a80bbfd3e5adbbac6633", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2019-10-12T02:10:48.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-25T15:35:58.000Z", "max_forks_repo_path": "khmot/main.cpp", "max_forks_repo_name": "r7vme/khmot", "max_forks_repo_head_hexsha": "2920ed01c66e906d9099a80bbfd3e5adbbac6633", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-15T06:01:26.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-15T06:01:26.000Z", "avg_line_length": 19.6538461538, "max_line_length": 61, "alphanum_fraction": 0.626223092, "num_tokens": 194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916240341031, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.4953091318837203}}
{"text": "/**\n * @file    SchurComplementDenseSolver.cpp\n * @brief   Abstract linear solver class of Ax = b\n * @author  Jing Dong\n * @date    Jun 24, 2019\n */\n\n#include <minisam/linear/SchurComplementDenseSolver.h>\n#include <minisam/utils/Timer.h>\n\n#include <Eigen/Cholesky>\n\nnamespace minisam {\n\n/* ************************************************************************** */\nLinearSolverStatus SchurComplementDenseSolver::solve(\n    const Eigen::SparseMatrix<double>& AtA, const Eigen::VectorXd& Atb,\n    Eigen::VectorXd& x) {\n  // static auto sr_timer = global_timer().getTimer(\"* Schur solve reduced\");\n  // static auto se_timer = global_timer().getTimer(\"* Schur solve elimiated\");\n\n  const int rs_until_idx = sc_ordering_->reducedSysUntilIndex();\n\n  Eigen::MatrixXd H_reduced_lower;\n  Eigen::SparseMatrix<double> Her;\n  Eigen::SparseMatrix<double> He_inv_lower;\n  Eigen::VectorXd g_reduced;\n\n  // build reduced system  H_reduced * x_reduced = g_reduced\n  LinearSolverStatus build_status = buildReducedSystem_(\n      AtA, Atb, H_reduced_lower, Her, He_inv_lower, g_reduced);\n\n  if (build_status != LinearSolverStatus::SUCCESS) {\n    return build_status;\n  }\n\n  // sr_timer->tic();\n\n  // reduced solution\n  Eigen::VectorXd x_reduced;\n  LinearSolverStatus reduced_status =\n      reduced_solver_->solve(H_reduced_lower, g_reduced, x_reduced);\n\n  if (reduced_status != LinearSolverStatus::SUCCESS) {\n    return reduced_status;\n  }\n\n  // sr_timer->toc();\n  // se_timer->tic();\n\n  Eigen::VectorXd x_elimiated =\n      He_inv_lower.selfadjointView<Eigen::Lower>() *\n      (Atb.tail(AtA.rows() - rs_until_idx) - Her * x_reduced);\n\n  // se_timer->toc();\n\n  x = Eigen::VectorXd(x_reduced.size() + x_elimiated.size());\n  x << x_reduced, x_elimiated;\n\n  return LinearSolverStatus::SUCCESS;\n}\n\n/* ************************************************************************** */\nLinearSolverStatus SchurComplementDenseSolver::buildReducedSystem_(\n    const Eigen::SparseMatrix<double>& AtA_lower, const Eigen::VectorXd& Atb,\n    Eigen::MatrixXd& H_reduced_lower, Eigen::SparseMatrix<double>& Her,\n    Eigen::SparseMatrix<double>& He_inv_lower, Eigen::VectorXd& g_reduced) {\n  // static auto br1_timer = global_timer().getTimer(\"* Schur build reduced\");\n\n  const int rs_until_idx = sc_ordering_->reducedSysUntilIndex();\n\n  He_inv_lower = AtA_lower.block(rs_until_idx, rs_until_idx,\n                                 AtA_lower.rows() - rs_until_idx,\n                                 AtA_lower.rows() - rs_until_idx);\n  Her = AtA_lower.block(rs_until_idx, 0, AtA_lower.rows() - rs_until_idx,\n                        rs_until_idx);\n  He_inv_lower.makeCompressed();\n  Her.makeCompressed();\n\n  H_reduced_lower =\n      Eigen::MatrixXd(AtA_lower.block(0, 0, rs_until_idx, rs_until_idx));\n\n  // br1_timer->tic();\n\n  // block inversed based method\n  for (size_t i = 0; i < sc_ordering_->eliminatedVariableSize(); i++) {\n    const int var_pos = sc_ordering_->eliminatedVariablePosition(i);\n    const int var_dim = sc_ordering_->eliminatedVariableDim(i);\n\n    // br11_timer->tic();\n    const Eigen::LDLT<Eigen::MatrixXd, Eigen::Lower> ldlt(\n        He_inv_lower.block(var_pos, var_pos, var_dim, var_dim));\n    if (ldlt.info() != Eigen::Success) {\n      return LinearSolverStatus::RANK_DEFICIENCY;\n    }\n    const Eigen::MatrixXd Hs_block_inv =\n        ldlt.solve(Eigen::MatrixXd::Identity(var_dim, var_dim));\n    // br11_timer->toc();\n    // replace with inverse\n    // br12_timer->tic();\n    for (int ii = 0; ii < var_dim; ii++) {\n      for (int ij = 0; ij < var_dim - ii; ij++) {\n        double* value_ptr = He_inv_lower.valuePtr() +\n                            He_inv_lower.outerIndexPtr()[ii + var_pos] + ij;\n        *value_ptr = Hs_block_inv(ii, ii + ij);\n      }\n    }\n    // br12_timer->toc();\n  }\n\n  H_reduced_lower -=\n      Her.transpose() * (He_inv_lower.selfadjointView<Eigen::Lower>() * Her);\n\n  // br1_timer->toc();\n\n  g_reduced.noalias() =\n      Atb.head(rs_until_idx) -\n      Her.transpose() * (He_inv_lower.selfadjointView<Eigen::Lower>() *\n                         Atb.tail(AtA_lower.rows() - rs_until_idx));\n\n  return LinearSolverStatus::SUCCESS;\n}\n\n}  // namspace minisam\n", "meta": {"hexsha": "a36ecba9fec518725df7f29508ea62f70e4be8ca", "size": 4156, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "minisam/linear/SchurComplementDenseSolver.cpp", "max_stars_repo_name": "versatran01/minisam", "max_stars_repo_head_hexsha": "b3840d2629551fdfa287df8aac2e7956873d2b0e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 338.0, "max_stars_repo_stars_event_min_datetime": "2019-09-03T10:44:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:12:08.000Z", "max_issues_repo_path": "minisam/linear/SchurComplementDenseSolver.cpp", "max_issues_repo_name": "bhsphd/minisam", "max_issues_repo_head_hexsha": "ef84796fa11ac6e5e4d4aa9d60d9b94a99a973fb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 23.0, "max_issues_repo_issues_event_min_datetime": "2019-09-26T09:00:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-04T06:04:02.000Z", "max_forks_repo_path": "minisam/linear/SchurComplementDenseSolver.cpp", "max_forks_repo_name": "bhsphd/minisam", "max_forks_repo_head_hexsha": "ef84796fa11ac6e5e4d4aa9d60d9b94a99a973fb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 87.0, "max_forks_repo_forks_event_min_datetime": "2019-09-04T05:17:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T09:47:23.000Z", "avg_line_length": 33.248, "max_line_length": 80, "alphanum_fraction": 0.646053898, "num_tokens": 1074, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4953091238176168}}
{"text": "#ifndef PROMP_EMISSION_H\n#define PROMP_EMISSION_H\n\n#include <armadillo>\n#include <emissions.hpp>\n#include <iostream>\n#include <json.hpp>\n#include <ForwardBackward.hpp>\n#include <map>\n#include <memory>\n#include <robotics.hpp>\n\nusing namespace arma;\nusing namespace hsmm;\nusing namespace robotics;\nusing namespace std;\n\nnamespace hsmm {\n\n    class NormalInverseWishart {\n        public:\n            NormalInverseWishart(vec mu_0, double lambda, mat Phi, int dof) :\n                    Phi_(Phi), dof_(dof), mu_0_(mu_0), lambda_(lambda) {\n                assert(dof > Phi.n_rows + 1);\n                vec eigenvalues = eig_sym(Phi);\n                assert(eigenvalues(0) > 0);\n                assert(!(lambda < 0));\n                assert(mu_0.n_rows == Phi.n_rows);\n            }\n\n            // This constructor assumes there is no prior for the mean.\n            // (i.e. only the inverse-Wishart part).\n            NormalInverseWishart(mat Phi, int dof) : NormalInverseWishart(\n                    zeros<vec>(Phi.n_rows), 0.0, Phi, dof) {}\n\n            vec getMu0() {\n                return mu_0_;\n            }\n\n            double getLambda() {\n                return lambda_;\n            }\n\n            mat getPhi() {\n                return Phi_;\n            }\n\n            int getDof() {\n                return dof_;\n            }\n\n        private:\n            vec mu_0_;\n            double lambda_;\n            mat Phi_;\n            int dof_;\n    };\n\n    double zeroMeanGaussianLogLikelihood(const vec& x, const mat &precision) {\n        return -0.5 * as_scalar(x.t()*precision*x - log(det(precision)) +\n                x.n_elem * log(2*datum::pi));\n    }\n\n\n    class ProMPsEmission : public AbstractEmissionOnlineSetting {\n        public:\n            ProMPsEmission(vector<FullProMP> promps) :\n                    AbstractEmissionOnlineSetting(promps.size(),\n                    promps.at(0).get_num_joints()), promps_(promps),\n                    diagonal_sigma_y_(true) {\n                for(int i = 0; i < getNumberStates(); i++)\n                    assert(promps_.at(i).get_num_joints() == getDimension());\n            }\n\n            ProMPsEmission* clone() const {\n                return new ProMPsEmission(*this);\n            }\n\n            void resetMemCaches() {\n                cachePhis_.clear();\n                cacheInvS_.clear();\n                cacheK_.clear();\n                cachePosteriorSigma_.clear();\n            }\n\n            // TODO: remove this once this behavior is moved to a subclass.\n            void setDelta(double delta) {\n                //assert(delta > 0);\n                sample_locations_delta_ = delta;\n            }\n\n            // Derived classes could implement a different kinf of dependence\n            // on the segment duration. Default implementation normalizes\n            // the input to be between 0 and 1.\n            // TODO: Implement the segment independent in a subclass.\n            virtual vec getSampleLocations(int length) const {\n                if (sample_locations_delta_ < 0)\n                    return linspace<vec>(0, 1.0, length);\n                else\n                    return linspace<vec>(0, (length-1)*sample_locations_delta_,\n                            length);\n            }\n\n            // This initialization mechanism assumes all the hidden states\n            // share the same basis functions and their hyperparameters.\n            void init_params_from_data(int min_duration, int ndurations,\n                    const arma::field<arma::field<arma::mat>>& mobs) {\n                vector<pair<double, vec>> pairs;\n                vector<double> noise_vars;\n                for(auto &obs : mobs) {\n                    for(int t = 0; t < obs.n_elem; t++) {\n                        for(int d = 0; d < ndurations; d++) {\n                            if (t + min_duration + d > obs.n_elem)\n                                break;\n                            int end_idx = t + min_duration + d - 1;\n                            auto &segment = obs.rows(t, end_idx);\n                            vec lsq_omega = least_squares_omega(0, segment);\n                            double var = var_isotropic_gaussian_given_omega(0,\n                                    lsq_omega, segment);\n                            pairs.push_back(make_pair(var, lsq_omega));\n                            noise_vars.push_back(var);\n                        }\n                    }\n                }\n                sort(pairs.begin(), pairs.end(), [](const pair<double, vec>& a,\n                        const pair<double, vec>& b)\n                        {return a.first < b.first;});\n                int cutoff_index = (int)((pairs.size() - 1) *\n                        init_fraction_);\n                double threshold = pairs.at(cutoff_index).first;\n                cout << \"Cuttoff index for init: \" << cutoff_index <<\n                        \" var: \" << threshold << endl;\n\n                // Showing a histogram of the distribution of noise vars.\n                vec vars(noise_vars);\n                vec histogram_cutoffs = linspace<vec>(0, max(vars), 20);\n                uvec histogram = histc(vars, histogram_cutoffs);\n                cout << \"Hist. of noise vars:\" << endl << histogram << endl;\n\n                mat remaining_w(promps_.at(0).get_model().get_mu_w().n_rows,\n                        cutoff_index + 1);\n                for(int i = 0; i <= cutoff_index; i++)\n                    remaining_w.col(i) = pairs.at(i).second;\n                mat means;\n                kmeans(means, remaining_w, getNumberStates(), static_subset,\n                        10, false);\n\n                // Updating the means of the ProMPs based on the k-means.\n                for(int i = 0; i < getNumberStates(); i++) {\n                    ProMP promp = promps_.at(i).get_model();\n                    promp.set_mu_w(means.col(i));\n                    promps_.at(i).set_model(promp);\n                }\n            }\n\n            // Note that the method is returning the posterior covariance for\n            // the given state and duration which is independent of obs.\n            mat generateCachedMatrices(const pair<int, int> &p) const {\n                if (cacheInvS_.find(p) == cacheInvS_.end() ||\n                        cacheK_.find(p) == cacheK_.end()) {\n                    int state = p.first;\n                    int dur = p.second;\n                    const FullProMP& promp = promps_.at(state);\n                    const cube& Phis = getPhiCube(state, dur);\n                    mat Sigma(promp.get_model().get_Sigma_w());\n                    mat Sigma_y(promp.get_model().get_Sigma_y());\n                    field<mat> invS(dur);\n                    field<mat> K(dur);\n                    for(int i = 0; i < dur; i++) {\n                        const mat& Phi = Phis.slice(i);\n                        mat S = Phi * Sigma * Phi.t() + Sigma_y;\n                        invS(i) = inv_sympd(S);\n\n                        // Kalman updating (correcting) step.\n                        K(i) = Sigma * Phi.t() * inv(S);\n                        Sigma = Sigma - K(i) * S * K(i).t();\n                    }\n\n                    // Caching the matrices for faster likelihood evaluation.\n                    cacheInvS_[p] = invS;\n                    cacheK_[p] = K;\n                    cachePosteriorSigma_[p] = Sigma;\n                }\n                return cachePosteriorSigma_.at(p);\n            }\n\n            double loglikelihood(int state, const field<mat>& obs) const {\n\n                // Making sure all the required matrices are already\n                // precomputed.\n                pair<int, int> p = make_pair(state, obs.n_elem);\n                generateCachedMatrices(p);\n\n                const FullProMP& promp = promps_.at(state);\n                const cube& Phis = getPhiCube(state, obs.n_elem);\n                vec mu(promp.get_model().get_mu_w());\n                const field<mat>& invS = cacheInvS_[p];\n                const field<mat>& K = cacheK_[p];\n                double ret = 0;\n                for(int i = 0; i < obs.n_elem; i++) {\n                    const mat& Phi = Phis.slice(i);\n                    if (obs(i).is_empty()) {\n\n                        // Making sure all the missing obs are at the end.\n                        // Other missing obs patterns are not supported yet.\n                        for(int j = i; j < obs.n_elem; j++)\n                            assert(obs(j).is_empty());\n                        break;\n                    }\n                    vec diff = obs(i) - Phi * mu;\n\n                    // p(y_t | y_1, ..., y_{t-1}).\n                    ret += zeroMeanGaussianLogLikelihood(diff, invS(i));\n                    mu = mu + K(i) * diff;\n                }\n                return ret;\n            }\n\n            double informationFilterLoglikelihood(int state,\n                    const field<mat>& obs) const {\n                const FullProMP& promp = promps_.at(state);\n\n                // The samples are assumed to be equally spaced.\n                vec sample_locations = getSampleLocations(obs.n_elem);\n\n                // Moment based parameterization.\n                vec mu(promp.get_model().get_mu_w());\n                mat Sigma(promp.get_model().get_Sigma_w());\n                mat Sigma_y(promp.get_model().get_Sigma_y());\n\n                // Canonical parameterization.\n                mat information_matrix = inv_sympd(Sigma);\n                vec information_state = information_matrix * mu;\n                mat inv_obs_noise = inv_sympd(Sigma_y);\n\n                double ret = 0;\n                for(int i = 0; i < obs.n_elem; i++) {\n                    mat Phi = promp.get_phi_t(sample_locations(i));\n\n                    // Computing the likelihood under the current filtering\n                    // distribution.\n                    mat filtered_Sigma = inv_sympd(information_matrix);\n                    vec filtered_mu = filtered_Sigma * information_state;\n\n                    // p(y_t | y_{1:t-1}).\n                    random::NormalDist dist = random::NormalDist(\n                            Phi * filtered_mu,\n                            Phi * filtered_Sigma * Phi.t() + Sigma_y);\n                    ret = ret + log_normal_density(dist, obs(i));\n\n                    mat aux = Phi.t() * inv_obs_noise;\n                    mat I_k = aux * Phi;\n                    mat i_k = aux * obs(i);\n                    information_matrix = information_matrix + I_k;\n                    information_state = information_state + i_k;\n                }\n                return ret;\n            }\n\n            double loglikelihoodBatchVersion(int state, const arma::mat& obs) {\n                int dimension = obs.n_rows;\n                assert(dimension == getDimension());\n                random::NormalDist dist = getNormalDistForMultipleTimeSteps(state,\n                        obs.n_cols);\n                vec stacked_obs = vectorise(obs);\n                return random::log_normal_density(dist, stacked_obs);\n            }\n\n            void reestimate(int min_duration,\n                    const arma::field<arma::cube>& meta,\n                    const arma::field<arma::field<arma::mat>>& mobs) {\n                int nseq = mobs.n_elem;\n                for(int i = 0; i < getNumberStates(); i++) {\n                    ProMP promp = promps_.at(i).get_model();\n                    const mat inv_Sigma_w = inv_sympd(promp.get_Sigma_w());\n                    const mat inv_Sigma_y = inv_sympd(promp.get_Sigma_y());\n                    const vec mu_w = promp.get_mu_w();\n\n                    vector<double> mult_c;\n                    vector<double> denominator_Sigma_y;\n                    for(int s = 0; s < nseq; s++) {\n                        const cube& eta = meta(s);\n                        int nobs = mobs(s).n_elem;\n                        int ndurations = eta.n_cols;\n                        for(int t = min_duration - 1; t < nobs; t++) {\n                            for(int d = 0; d < ndurations; d++) {\n                                int first_idx_seg = t - min_duration - d + 1;\n                                if (first_idx_seg < 0)\n                                    break;\n                                mult_c.push_back(eta(i, d, t));\n                                denominator_Sigma_y.push_back(eta(i, d, t) +\n                                        log(min_duration + d));\n                            }\n                        }\n                    }\n\n                    // Computing the multiplicative constants for mu_w and\n                    // Sigma_w.\n                    vec mult_c_normalized(mult_c);\n                    mult_c_normalized -= logsumexp(mult_c_normalized);\n                    mult_c_normalized = exp(mult_c_normalized);\n\n                    // Computing the multiplicative constants for Sigma_y since\n                    // they have a different denominator.\n                    vec mult_c_Sigma_y_normalized(mult_c);\n                    vec den_Sigma_y(denominator_Sigma_y);\n                    mult_c_Sigma_y_normalized -= logsumexp(den_Sigma_y);\n                    mult_c_Sigma_y_normalized = exp(mult_c_Sigma_y_normalized);\n\n                    mat new_Sigma_y(size(promp.get_Sigma_y()), fill::zeros);\n\n                    // EM for ProMPs.\n                    vec weighted_sum_post_mean(size(mu_w), fill::zeros);\n                    mat weighted_sum_post_cov(size(inv_Sigma_w), fill::zeros);\n                    mat weighted_sum_post_mean_mean_T(size(inv_Sigma_w),\n                            fill::zeros);\n                    int idx_mult_c = 0;\n                    for(int s = 0; s < nseq; s++) {\n                        auto& obs = mobs(s);\n                        int nobs = obs.n_elem;\n                        int ndurations = meta(s).n_cols;\n                        for(int t = min_duration - 1; t < nobs; t++) {\n                            for(int d = 0; d < ndurations; d++) {\n                                int first_idx_seg = t - min_duration - d + 1;\n                                if (first_idx_seg < 0)\n                                    break;\n                                const int current_duration = min_duration + d;\n                                const cube& Phis = getPhiCube(i, current_duration);\n\n                                // E step for the emission hidden variables (Ws).\n                                // Computing the posterior of W given Y and Theta.\n\n                                // Computing the posterior covariance of the hidden\n                                // variable w for this segment.\n                                mat posterior_cov(size(inv_Sigma_w), fill::zeros);\n                                for(int step = 0; step < current_duration; step++) {\n                                    posterior_cov += Phis.slice(step).t() *\n                                        inv_Sigma_y * Phis.slice(step);\n                                }\n                                posterior_cov = (posterior_cov+posterior_cov.t())/2.0;\n                                posterior_cov = posterior_cov + inv_Sigma_w;\n                                posterior_cov = (posterior_cov+posterior_cov.t())/2.0;\n                                posterior_cov = inv_sympd(posterior_cov);\n                                posterior_cov = (posterior_cov+posterior_cov.t())/2.0;\n\n                                // Computing the posterior mean of the hidden\n                                // variable w for this segment.\n                                vec posterior_mean(size(mu_w), fill::zeros);\n                                for(int step = 0; step < current_duration; step++) {\n                                    const vec& ob = obs(first_idx_seg + step);\n                                    posterior_mean += Phis.slice(step).t() *\n                                        inv_Sigma_y * ob;\n                                }\n                                posterior_mean = inv_Sigma_w * mu_w + posterior_mean;\n                                posterior_mean = posterior_cov * posterior_mean;\n\n                                // Getting the multiplicative constants.\n                                double mult_constant = mult_c_normalized(idx_mult_c);\n                                double mult_constant_Sigma_y =\n                                        mult_c_Sigma_y_normalized(idx_mult_c);\n                                idx_mult_c++;\n\n                                // Statistics required for updating mu_w & Sigma_w.\n                                weighted_sum_post_mean += mult_constant *\n                                        posterior_mean;\n                                weighted_sum_post_cov += mult_constant *\n                                        posterior_cov;\n                                weighted_sum_post_mean_mean_T += mult_constant *\n                                        posterior_mean * posterior_mean.t();\n\n                                // Computing the new output noise covariance: Sigma_y.\n                                mat Sigma_y_term(size(new_Sigma_y), fill::zeros);\n                                for(int step = 0; step < current_duration; step++) {\n                                    const mat& phi = Phis.slice(step);\n                                    const vec& diff_y = obs(first_idx_seg + step) -\n                                        phi * posterior_mean;\n                                    Sigma_y_term += diff_y * diff_y.t() +\n                                        phi * posterior_cov * phi.t();\n                                }\n                                new_Sigma_y += mult_constant_Sigma_y * Sigma_y_term;\n                            }\n                        }\n                    }\n\n                    // Expected number of segments generated by the i-th state.\n                    double mle_den = exp(logsumexp(mult_c));\n\n                    // M step for the emission variables.\n                    vec new_mu_w_MLE(weighted_sum_post_mean);\n                    mat new_Sigma_w_MLE = weighted_sum_post_cov +\n                        weighted_sum_post_mean_mean_T - new_mu_w_MLE *\n                        new_mu_w_MLE.t();\n\n                    // If there is a prior then we do MAP instead.\n                    mat new_Sigma_w;\n                    mat new_mu_w;\n                    if (normal_inverse_prior_) {\n                        double v_0 = normal_inverse_prior_->getDof();\n                        double D = mu_w.n_rows;\n                        mat S_0 = normal_inverse_prior_->getPhi();\n                        new_Sigma_w = (S_0 + mle_den * new_Sigma_w_MLE) /\n                                (v_0 + mle_den + D + 2);\n\n                        double k_0 = normal_inverse_prior_->getLambda();\n                        vec m_0 = normal_inverse_prior_->getMu0();\n                        new_mu_w = (k_0 * m_0 + mle_den * new_mu_w_MLE) /\n                                (mle_den + k_0);\n                    }\n                    else {\n                        new_Sigma_w = new_Sigma_w_MLE;\n                        new_mu_w = new_mu_w_MLE;\n                    }\n\n                    cout << \"State \" << i << \" MLE Den: \" << mle_den << \" \";\n                    if (mle_den > epsilon_) {\n\n                        // Making sure the noise covariance is diagonal.\n                        if (diagonal_sigma_y_)\n                            new_Sigma_y = diagmat(new_Sigma_y.diag());\n\n                        // Checking that the new Sigma_w is a covariance matrix.\n                        vec eigenvalues_map = eig_sym(new_Sigma_w);\n                        assert(eigenvalues_map(0) > 0);\n\n                        // Setting the new parameters.\n                        promp.set_mu_w(new_mu_w);\n                        promp.set_Sigma_w(new_Sigma_w);\n                        promp.set_Sigma_y(new_Sigma_y);\n                        promps_.at(i).set_model(promp);\n                        resetMemCaches();\n                        cout << \". Updated.\" << endl;\n                    }\n                    else\n                        cout << \". Not updated.\" << endl;\n                }\n            }\n\n            // Unshadowing this method from the AbstractEmission class.\n            using AbstractEmission::sampleFromState;\n\n            field<mat> sampleFromState(int state, int size,\n                    mt19937 &rand_generator) const {\n                return sampleFromProMP(promps_.at(state), size, rand_generator);\n            }\n\n            field<mat> sampleFromProMP(const FullProMP& fpromp, int size,\n                    mt19937 &rand_generator) const {\n                const ProMP& model = fpromp.get_model();\n                assert(model.get_mu_w().n_rows == model.get_Sigma_w().n_rows);\n                vector<vec> w_samples = random::sample_multivariate_normal(\n                        rand_generator,\n                        {model.get_mu_w(), model.get_Sigma_w()}, 1);\n                vec w = w_samples.back();\n\n                vec noise_mean = zeros<vec>(getDimension());\n                vector<vec> output_noise = random::sample_multivariate_normal(\n                        rand_generator, {noise_mean, model.get_Sigma_y()}, size);\n\n                field<mat> ret(size);\n\n                // The samples are assumed to be equally spaced.\n                vec sample_locations = getSampleLocations(size);\n                for(int i = 0; i < size; i++) {\n                    double z = sample_locations(i);\n                    mat phi_z =fpromp.get_phi_t(z);\n                    ret(i) = phi_z * w + output_noise.at(i);\n                }\n                return ret;\n            }\n\n            // Equivalent to sampleFromState but uses conditioning.\n            field<mat> sampleFromState2(int state, int size,\n                    mt19937 &rand_generator) const {\n                field<mat> no_obs;\n                return sampleNextObsGivenPastObs(state, size, no_obs,\n                        rand_generator);\n            }\n\n            field<mat> sampleNextObsGivenPastObs(int state, int seg_dur,\n                    const field<mat>& past_obs, std::mt19937 &rng) const {\n                assert(past_obs.n_elem < seg_dur);\n\n                // Making sure all the required matrices are already computed.\n                pair<int, int> p = make_pair(state, seg_dur);\n                generateCachedMatrices(p);\n\n                field<mat> ret(seg_dur);\n                for(int i = 0; i < past_obs.n_elem; i++)\n                    ret(i) = past_obs(i);\n\n                const FullProMP& promp = promps_.at(state);\n                const cube& Phis = getPhiCube(state, seg_dur);\n                vec mu(promp.get_model().get_mu_w());\n\n                const field<mat>& invS = cacheInvS_.at(p);\n                const field<mat>& K = cacheK_.at(p);\n                int i;\n                for(i = 0; i < past_obs.n_elem; i++)\n                    mu = mu + K(i) * (past_obs(i) - Phis.slice(i) * mu);\n\n                // Now i indexes the offset we want to sample from.\n                for(; i < seg_dur; i++) {\n                    vector<vec> sample = random::sample_multivariate_normal(\n                            rng, {Phis.slice(i) * mu, inv(invS(i))}, 1);\n                    ret(i) = sample.at(0);\n                    mu = mu + K(i) * (ret(i) - Phis.slice(i) * mu);\n                }\n                return ret;\n            }\n\n            field<mat> sampleFirstSegmentObsGivenLastSegment(int curr_state,\n                    int curr_seg_dur, const field<mat> &last_segment,\n                    int last_state, std::mt19937 &rng) const {\n                mat last_obs = last_segment(last_segment.n_elem - 1);\n\n                // Making sure all the required matrices are already computed.\n                pair<int, int> p = make_pair(curr_state, curr_seg_dur);\n                pair<int, int> last_p = make_pair(last_state,\n                        last_segment.n_elem);\n                generateCachedMatrices(p);\n                mat last_p_Sigma = generateCachedMatrices(last_p);\n\n                // Finding the posterior omega mean for the last segment.\n                const cube& LPhis = getPhiCube(last_state, last_segment.n_elem);\n                vec last_p_mu(promps_.at(last_state).get_model().get_mu_w());\n                const field<mat>& last_K = cacheK_[last_p];\n                for(int i = 0; i < last_segment.n_elem; i++) {\n                    const mat& Phi = LPhis.slice(i);\n                    vec diff = last_segment(i) - Phi * last_p_mu;\n                    last_p_mu = last_p_mu + last_K(i) * diff;\n                }\n                FullProMP last_full_promp(promps_.at(last_state));\n                mat zeros_Sigma_y = zeros<mat>(getDimension(), getDimension());\n                ProMP last_p_promp(last_p_mu, last_p_Sigma, zeros_Sigma_y);\n                last_full_promp.set_model(last_p_promp);\n\n                // This gives the posterior distribution over q = (y, v) at the\n                // last time step of the last segment.\n                random::NormalDist last_pos_vel = last_full_promp.joint_dist(\n                        1.0, true, true, false);\n                vec last_p_pos = last_pos_vel.mean().head(getDimension());\n                vec last_p_vel = last_pos_vel.mean().tail(getDimension());\n\n                FullProMP promp = promps_.at(curr_state);\n                promp = promp.condition_current_position(0, 1.0, last_p_pos);\n                //promp = promp.condition_current_state(0, 1.0, last_p_pos,\n                //        last_p_vel);\n                return sampleFromProMP(promp, curr_seg_dur, rng);\n            }\n\n            nlohmann::json to_stream() const {\n                vector<nlohmann::json> array_emission_params;\n                for(int i = 0; i < getNumberStates(); i++) {\n                    const ProMP& promp = promps_.at(i).get_model();\n                    nlohmann::json whole_thing;\n                    nlohmann::json promp_params;\n                    promp_params[\"mu_w\"] = vec2json(promp.get_mu_w());\n                    promp_params[\"Sigma_w\"] = mat2json(promp.get_Sigma_w());\n                    promp_params[\"Sigma_y\"] = mat2json(promp.get_Sigma_y());\n                    whole_thing[\"model\"] = promp_params;\n                    whole_thing[\"num_joints\"] = getDimension();\n\n                    // Note that the information about the basis functions is not\n                    // serialized.\n                    array_emission_params.push_back(whole_thing);\n                }\n                nlohmann::json ret = array_emission_params;\n                return ret;\n            }\n\n            void from_stream(const nlohmann::json& emission_params) {\n                // Note that the given parameters need to be consistent with some\n                // of the preexisting settings. Moreover, part of the structure of\n                // this emission process is not read from the input json.\n                // (e.g. the used basis functions).\n                assert(emission_params.size() == getNumberStates());\n                for(int i = 0; i < getNumberStates(); i++) {\n                    const nlohmann::json& params = emission_params.at(i);\n                    promps_.at(i).set_model(json2basic_promp(params.at(\"model\")));\n                    assert(params.at(\"num_joints\") == getDimension());\n                }\n                resetMemCaches();\n                return;\n            }\n\n            // TODO: change the name of this method.\n            void set_Sigma_w_Prior(NormalInverseWishart prior) {\n                normal_inverse_prior_ = std::make_shared<NormalInverseWishart>(\n                        std::move(prior));\n                int size_cov = promps_.at(0).get_model().get_Sigma_w().n_rows;\n                assert(size_cov == normal_inverse_prior_->getPhi().n_rows);\n            }\n\n            void setParamsForInitialization(double fraction) {\n                assert(fraction > 0 && fraction < 1.0);\n                init_fraction_ = fraction;\n            }\n\n\n        protected:\n\n            // Returns the marginal distribution of a particular state (ProMP) and\n            // duration. Keep in mind that the covariance matrix grows quadratically\n            // with respect to the duration. This could be cached for efficiency\n            // but is mostly intended for debugging.\n            random::NormalDist getNormalDistForMultipleTimeSteps(int state, int duration) {\n                int nrows = getDimension();\n                const FullProMP& promp = promps_.at(state);\n                const mat stacked_Phi = getPhiStacked(state, duration);\n                vec mean = stacked_Phi * promp.get_model().get_mu_w();\n                mat cov = stacked_Phi * promp.get_model().get_Sigma_w() *\n                    stacked_Phi.t();\n\n                // Adding the noise variance.\n                mat noise_cov(size(cov), fill::zeros);\n                for(int i = 0; i < duration; i++)\n                    noise_cov.submat(i * nrows, i * nrows, (i + 1) * nrows - 1,\n                            (i + 1) * nrows - 1) = promp.get_model().get_Sigma_y();\n\n                cov = cov + noise_cov;\n                return random::NormalDist(mean, cov);\n            }\n\n            // Takes the covariance matrix for omega and returns it as if the\n            // joints were independent (blockdiag operator in Sebastian's paper).\n            mat getCovarianceIndependentJoints(const mat& cov) const {\n                mat ret(size(cov), fill::zeros);\n                assert(cov.n_rows == cov.n_cols);\n                int dim = cov.n_rows;\n                assert(dim % getDimension() == 0);\n                int blocklen = dim / getDimension();\n                for(int i = 0; i < dim; i++)\n                    for(int j = 0; j < dim; j++)\n                        if ((i/blocklen) == (j/blocklen))\n                            ret(i, j) = cov(i, j);\n                mat extra_term = eye<mat>(size(ret)) * 1e-4;\n                return ret + extra_term;\n            }\n\n            mat getPhiStacked(int state, int duration) {\n                cube Phis = getPhiCube(state, duration);\n                mat PhiStacked(Phis.n_rows * Phis.n_slices, Phis.n_cols);\n                for(int d = 0; d < duration; d++)\n                    PhiStacked.rows(d * Phis.n_rows, (d + 1) * Phis.n_rows - 1) =\n                        Phis.slice(d);\n                return PhiStacked;\n            }\n\n            cube getPhiCube(int state, int duration) const {\n                pair<int, int> p = make_pair(state, duration);\n                if (cachePhis_.find(p) != cachePhis_.end())\n                    return cachePhis_[p];\n                const FullProMP& promp = promps_.at(state);\n\n                // The samples are assumed to be equally spaced.\n                vec sample_locations = getSampleLocations(duration);\n                mat tmp = promp.get_phi_t(0);\n                int ncols = tmp.n_cols;\n                int nrows = tmp.n_rows;\n                cube stacked_Phi(nrows, ncols, duration, fill::zeros);\n                for(int i = 0; i < duration; i++)\n                    stacked_Phi.slice(i) = promp.get_phi_t(sample_locations(i));\n                cachePhis_[p] = stacked_Phi;\n                return stacked_Phi;\n            }\n\n            // Returns the least squares solution to the problem:\n            // y(t) = Phi(t) * w for a bunch of i.i.d. y's. Note that omega is\n            // not assumed to be a random variable.\n            vec least_squares_omega(int state,\n                    const field<mat>& segment) const {\n                int nobs = segment.n_elem;\n                const cube& Phis = getPhiCube(state, nobs);\n                mat A(size(Phis.slice(0).t() * Phis.slice(0)),\n                        fill::zeros);\n                vec b(A.n_rows, fill::zeros);\n                for(int t = 0; t < nobs; t++) {\n                    const mat& Phi = Phis.slice(t);\n                    A = A + Phi.t() * Phi;\n                    b = b + Phi.t() * segment(t);\n                }\n\n                // Solving A * w = b\n                vec lsq_omega = solve(A, b);\n                return lsq_omega;\n            }\n\n            // Compute the variance of an isotropic Gaussian noise model\n            // given omega.\n            double var_isotropic_gaussian_given_omega(int state, vec w,\n                    const field<mat>& segment) const {\n                int nobs = segment.n_elem;\n                const cube& Phis = getPhiCube(state, nobs);\n                double var = 0;\n                for(int t = 0; t < nobs; t++) {\n                    const mat& Phi = Phis.slice(t);\n                    vec diff = segment(t) - Phi * w;\n                    var += dot(diff, diff);\n                }\n                return var / (nobs * segment(0).n_rows);\n            }\n\n\n            vector<FullProMP> promps_;\n            std::shared_ptr<NormalInverseWishart> normal_inverse_prior_;\n            double epsilon_ = 1e-15;\n            bool diagonal_sigma_y_;\n\n            // Delta for emissions which are not dependent on the total\n            // duration.\n            double sample_locations_delta_ = -1;\n\n            // Fraction of the total least squares omega estimates that will be\n            // used for initialization.\n            double init_fraction_ = 0.1;\n\n            // Members for caching.\n            mutable map<pair<int, int>, cube> cachePhis_;\n            mutable map<pair<int, int>, field<mat>> cacheInvS_;\n            mutable map<pair<int, int>, field<mat>> cacheK_;\n            mutable map<pair<int, int>, mat> cachePosteriorSigma_;\n    };\n\n\n    // This version of the ProMP is specifically designed for HMMs where a\n    // single observation is a time series itself\n    class ProMPsEmissionHMM : public ProMPsEmission {\n        public:\n            ProMPsEmissionHMM(vector<FullProMP> promps) :\n                    ProMPsEmission(promps) {}\n\n            ProMPsEmission* clone() const {\n                return new ProMPsEmission(*this);\n            }\n\n            double loglikelihood(int state, const field<mat>& obs) const {\n\n                // Making sure that the duration is one.\n                assert(obs.n_elem == 1);\n                auto& sequence = obs(0);\n                const FullProMP& promp = promps_.at(state);\n\n                // The samples are assumed to be equally spaced.\n                vec sample_locations = getSampleLocations(sequence.n_cols);\n\n                vec mu(promp.get_model().get_mu_w());\n                mat Sigma(promp.get_model().get_Sigma_w());\n                mat Sigma_y(promp.get_model().get_Sigma_y());\n                double ret = 0;\n                for(int i = 0; i < sequence.n_cols; i++) {\n                    mat Phi = promp.get_phi_t(sample_locations(i));\n                    mat S = Phi * Sigma * Phi.t() + Sigma_y;\n\n                    // Required for the marginal likelihood p(y_t | y_{1:t-1}).\n                    random::NormalDist dist = random::NormalDist(Phi * mu, S);\n                    ret = ret + log_normal_density(dist, sequence.col(i));\n\n                    // Using the kalman updating step to compute this efficiently.\n                    mat K = Sigma * Phi.t() * inv(S);\n                    mu = mu + K * (sequence.col(i) - Phi * mu);\n                    Sigma = Sigma - K * S * K.t();\n                }\n                return ret;\n            }\n\n            void reestimate(int min_duration,\n                    const arma::field<arma::cube>& meta,\n                    const arma::field<arma::field<arma::mat>>& mobs) {\n                int nseq = mobs.n_elem;\n                for(int i = 0; i < getNumberStates(); i++) {\n                    ProMP promp = promps_.at(i).get_model();\n                    const mat inv_Sigma_w = inv_sympd(promp.get_Sigma_w());\n                    const mat inv_Sigma_y = inv_sympd(promp.get_Sigma_y());\n                    const vec mu_w = promp.get_mu_w();\n\n                    vector<double> mult_c;\n                    vector<double> denominator_Sigma_y;\n                    for(int s = 0; s < nseq; s++) {\n                        const cube& eta = meta(s);\n                        int nobs = mobs(s).n_elem;\n                        int ndurations = eta.n_cols;\n                        assert(ndurations == 1 && min_duration == 1);\n                        for(int t = 0; t < nobs; t++) {\n                            mult_c.push_back(eta(i, 0, t));\n                            int current_duration = mobs(s)(t).n_cols;\n                            denominator_Sigma_y.push_back(eta(i, 0, t) +\n                                    log(current_duration));\n                        }\n                    }\n\n                    // Computing the multiplicative constants for mu_w and\n                    // Sigma_w.\n                    vec mult_c_normalized(mult_c);\n                    mult_c_normalized -= logsumexp(mult_c_normalized);\n                    mult_c_normalized = exp(mult_c_normalized);\n\n                    // Computing the multiplicative constants for Sigma_y since\n                    // they have a different denominator.\n                    vec mult_c_Sigma_y_normalized(mult_c);\n                    vec den_Sigma_y(denominator_Sigma_y);\n                    mult_c_Sigma_y_normalized -= logsumexp(den_Sigma_y);\n                    mult_c_Sigma_y_normalized = exp(mult_c_Sigma_y_normalized);\n\n                    mat new_Sigma_y(size(promp.get_Sigma_y()), fill::zeros);\n\n                    // EM for ProMPs.\n                    vec weighted_sum_post_mean(size(mu_w), fill::zeros);\n                    mat weighted_sum_post_cov(size(inv_Sigma_w), fill::zeros);\n                    mat weighted_sum_post_mean_mean_T(size(inv_Sigma_w),\n                            fill::zeros);\n                    int idx_mult_c = 0;\n                    for(int s = 0; s < nseq; s++) {\n                        auto& obs = mobs(s);\n                        int nobs = obs.n_elem;\n                        int ndurations = meta(s).n_cols;\n                        for(int t = 0; t < nobs; t++) {\n\n                                // Length of the current observation\n                                const int current_duration = obs(t).n_cols;\n                                const cube& Phis = getPhiCube(i, current_duration);\n\n                                // E step for the emission hidden variables (Ws).\n                                // Computing the posterior of W given Y and Theta.\n\n                                // Computing the posterior covariance of the hidden\n                                // variable w for this segment.\n                                mat posterior_cov(size(inv_Sigma_w), fill::zeros);\n                                for(int step = 0; step < current_duration; step++) {\n                                    posterior_cov += Phis.slice(step).t() *\n                                        inv_Sigma_y * Phis.slice(step);\n                                }\n                                posterior_cov = (posterior_cov+posterior_cov.t())/2.0;\n                                posterior_cov = posterior_cov + inv_Sigma_w;\n                                posterior_cov = (posterior_cov+posterior_cov.t())/2.0;\n                                posterior_cov = inv_sympd(posterior_cov);\n                                posterior_cov = (posterior_cov+posterior_cov.t())/2.0;\n\n                                // Computing the posterior mean of the hidden\n                                // variable w for this segment.\n                                vec posterior_mean(size(mu_w), fill::zeros);\n                                for(int step = 0; step < current_duration; step++) {\n                                    const vec& ob = obs(t).col(step);\n                                    posterior_mean += Phis.slice(step).t() *\n                                        inv_Sigma_y * ob;\n                                }\n                                posterior_mean = inv_Sigma_w * mu_w + posterior_mean;\n                                posterior_mean = posterior_cov * posterior_mean;\n\n                                // Getting the multiplicative constants.\n                                double mult_constant = mult_c_normalized(idx_mult_c);\n                                double mult_constant_Sigma_y =\n                                        mult_c_Sigma_y_normalized(idx_mult_c);\n                                idx_mult_c++;\n\n                                // Statistics required for updating mu_w & Sigma_w.\n                                weighted_sum_post_mean += mult_constant *\n                                        posterior_mean;\n                                weighted_sum_post_cov += mult_constant *\n                                        posterior_cov;\n                                weighted_sum_post_mean_mean_T += mult_constant *\n                                        posterior_mean * posterior_mean.t();\n\n                                // Computing the new output noise covariance: Sigma_y.\n                                mat Sigma_y_term(size(new_Sigma_y), fill::zeros);\n                                for(int step = 0; step < current_duration; step++) {\n                                    const mat& phi = Phis.slice(step);\n                                    const vec& diff_y = obs(t).col(step) -\n                                        phi * posterior_mean;\n                                    Sigma_y_term += diff_y * diff_y.t() +\n                                        phi * posterior_cov * phi.t();\n                                }\n                                new_Sigma_y += mult_constant_Sigma_y * Sigma_y_term;\n                        }\n                    }\n\n                    // Expected number of segments generated by the i-th state.\n                    double mle_den = exp(logsumexp(mult_c));\n\n                    // M step for the emission variables.\n                    vec new_mu_w_MLE(weighted_sum_post_mean);\n                    mat new_Sigma_w_MLE = weighted_sum_post_cov +\n                        weighted_sum_post_mean_mean_T - new_mu_w_MLE *\n                        new_mu_w_MLE.t();\n\n                    // If there is a prior then we do MAP instead.\n                    mat new_Sigma_w;\n                    mat new_mu_w;\n                    if (normal_inverse_prior_) {\n                        double v_0 = normal_inverse_prior_->getDof();\n                        double D = mu_w.n_rows;\n                        mat S_0 = normal_inverse_prior_->getPhi();\n                        new_Sigma_w = (S_0 + mle_den * new_Sigma_w_MLE) /\n                                (v_0 + mle_den + D + 2);\n\n                        double k_0 = normal_inverse_prior_->getLambda();\n                        vec m_0 = normal_inverse_prior_->getMu0();\n                        new_mu_w = (k_0 * m_0 + mle_den * new_mu_w_MLE) /\n                                (mle_den + k_0);\n                    }\n                    else {\n                        new_Sigma_w = new_Sigma_w_MLE;\n                        new_mu_w = new_mu_w_MLE;\n                    }\n\n                    cout << \"State \" << i << \" MLE Den: \" << mle_den << \" \";\n                    if (mle_den > epsilon_) {\n\n                        // Making sure the noise covariance is diagonal.\n                        if (diagonal_sigma_y_)\n                            new_Sigma_y = diagmat(new_Sigma_y.diag());\n\n                        // Checking that the new Sigma_w is a covariance matrix.\n                        vec eigenvalues_map = eig_sym(new_Sigma_w);\n                        assert(eigenvalues_map(0) > 0);\n\n                        // Setting the new parameters.\n                        promp.set_mu_w(new_mu_w);\n                        promp.set_Sigma_w(new_Sigma_w);\n                        promp.set_Sigma_y(new_Sigma_y);\n                        promps_.at(i).set_model(promp);\n                        cout << \". Updated.\" << endl;\n                    }\n                    else\n                        cout << \". Not updated.\" << endl;\n                }\n            }\n\n            field<mat> sampleFromState(int state, int size,\n                    mt19937 &rand_generator) const {\n\n                // Since the segments are modeled as single observations.\n                assert(size == 1);\n                const ProMP& model = promps_.at(state).get_model();\n                vector<vec> w_samples = random::sample_multivariate_normal(\n                        rand_generator, {model.get_mu_w(), model.get_Sigma_w()}, 1);\n                vec w = w_samples.back();\n\n                // Getting the actual size of the segment.\n                size = getDurationForEachSegment(rand_generator);\n\n                vec noise_mean = zeros<vec>(getDimension());\n                vector<vec> output_noise = random::sample_multivariate_normal(\n                        rand_generator, {noise_mean, model.get_Sigma_y()}, size);\n\n                mat joint_sample(getDimension(), size);\n\n                // The samples are assumed to be equally spaced.\n                vec sample_locations = getSampleLocations(size);\n                for(int i = 0; i < size; i++) {\n                    double z = sample_locations(i);\n                    mat phi_z = promps_.at(state).get_phi_t(z);\n                    joint_sample.col(i) = phi_z * w + output_noise.at(i);\n                }\n                field<mat> ret = {joint_sample};\n                return ret;\n            }\n\n        private:\n\n            int getDurationForEachSegment(mt19937 &rand_generator) const {\n                return 20;\n            }\n\n    };\n\n};\n\n#endif\n", "meta": {"hexsha": "7553b2e956db71f18aeefa6c2fad532038eae8e4", "size": 45578, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ProMPs_emission.hpp", "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": "include/ProMPs_emission.hpp", "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": "include/ProMPs_emission.hpp", "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": 47.036119711, "max_line_length": 91, "alphanum_fraction": 0.4705120892, "num_tokens": 9051, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4953091238176168}}
{"text": "/*\n * Mipmaps.hpp\n *\n *  Created on: Feb 4, 2012\n *      Author: david\n */\n\n#ifndef INCLUDED_DENSITY_SCALEPYRAMID_HPP_\n#define INCLUDED_DENSITY_SCALEPYRAMID_HPP_\n\n#include <Slimage/Slimage.hpp>\n#include <Eigen/Dense>\n#include <stdexcept>\n#include <vector>\n#include <tuple>\n#include <cassert>\n\nnamespace density {\n\nEigen::MatrixXf SumMipMapWithBlackBorder(const Eigen::MatrixXf& img_big);\n\ntemplate<unsigned int Q>\nEigen::MatrixXf SumMipMap(const Eigen::MatrixXf& img_big)\n{\n\t// size of original image\n\tconst unsigned int w_big = img_big.rows();\n\tconst unsigned int h_big = img_big.cols();\n\t// size of reduced image\n\tconst unsigned int w_sma = w_big / Q;\n\tconst unsigned int h_sma = h_big / Q;\n\t// the computed mipmap will have 2^i size\n\tif(Q*w_sma != w_big || Q*h_sma != h_big) {\n\t\tthrow std::runtime_error(\"ERROR: Q and size does not match in function SumMipMap!\");\n\t}\n\tEigen::MatrixXf img_small(w_sma, h_sma);\n\tfor(unsigned int y=0; y<h_sma; ++y) {\n\t\tconst unsigned int y_big = Q*y;\n\t\tfor(unsigned int x=0; x<w_sma; ++x) {\n\t\t\tconst unsigned int x_big = Q*x;\n\t\t\tfloat sum = 0.0f;\n\t\t\tfor(unsigned int i=0; i<Q; ++i) {\n\t\t\t\tfor(unsigned int j=0; j<Q; ++j) {\n\t\t\t\t\tsum += img_big(x_big+j, y_big+i);\n\t\t\t\t}\n\t\t\t}\n\t\t\timg_small(x, y) = sum;\n\t\t}\n\t}\n\treturn img_small;\n}\n\nEigen::MatrixXf ScaleUp(const Eigen::MatrixXf& img_small, unsigned int S);\n\nstd::vector<Eigen::MatrixXf> ComputeMipmaps(const Eigen::MatrixXf& img, unsigned int min_size);\n\nstd::vector<Eigen::MatrixXf> ComputeMipmapsLevels(const Eigen::MatrixXf& img, unsigned int levels);\n\nstd::vector<Eigen::MatrixXf> ComputeMipmaps640x480(const Eigen::MatrixXf& img);\n\nstd::vector<std::pair<Eigen::MatrixXf,Eigen::MatrixXf>> ComputeMipmapsWithAbs(const Eigen::MatrixXf& img, unsigned int min_size);\n\n}\n\n#endif\n", "meta": {"hexsha": "ca0fabf4a9c96a3f689d01d752ac12bda8862cb1", "size": 1757, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib_dasp/lib_dasp_density/density/ScalePyramid.hpp", "max_stars_repo_name": "jbellis/superpixel-benchmark", "max_stars_repo_head_hexsha": "81a45649d426751d1ae450ef8ea0d2d9c7b3545f", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 344.0, "max_stars_repo_stars_event_min_datetime": "2016-12-16T10:11:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T06:08:14.000Z", "max_issues_repo_path": "lib_dasp/lib_dasp_density/density/ScalePyramid.hpp", "max_issues_repo_name": "jbellis/superpixel-benchmark", "max_issues_repo_head_hexsha": "81a45649d426751d1ae450ef8ea0d2d9c7b3545f", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2018-02-15T19:34:19.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-31T17:04:48.000Z", "max_forks_repo_path": "lib_dasp/lib_dasp_density/density/ScalePyramid.hpp", "max_forks_repo_name": "jbellis/superpixel-benchmark", "max_forks_repo_head_hexsha": "81a45649d426751d1ae450ef8ea0d2d9c7b3545f", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 111.0, "max_forks_repo_forks_event_min_datetime": "2016-12-08T07:19:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T06:08:16.000Z", "avg_line_length": 27.0307692308, "max_line_length": 129, "alphanum_fraction": 0.7085941946, "num_tokens": 535, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.6224593452091672, "lm_q1q2_score": 0.49526481997568095}}
{"text": "#include <boost/test/unit_test.hpp>\n#include \"functions/full_function_defs.hh\"\n#include \"functions/addition.hh\"\n#include \"functions/std_functions.hh\"\n#include \"functions/operators.hh\"\n#include \"functions/polynomial.hh\"\n#include \"functions/all_simplifications.hh\"\n\nBOOST_AUTO_TEST_CASE(simplify_test) {\n  using namespace manifolds;\n  typedef Addition<Sin, Cos> Type;\n  static_assert(std::is_same<SimplifiedType<Type>, Type>::value,\n                \"Failed to not simplify!\");\n  static_assert(std::is_same<SimplifiedType<Addition<Addition<Sin, Cos>, Tan> >,\n                             Addition<Sin, Cos, Tan> >::value,\n                \"Failed to collapse nested additions!\");\n  Addition<Addition<Sin, Cos>, Tan> t;\n\n  static_assert(\n      std::is_same<decltype(Sin() + Sin()),\n                   Composition<IntegralPolynomial<0, 2>, Sin> >::value,\n      \"Failed to make sin+sin == 2 * sin\");\n\n  auto ps = Sin() + Sin();\n  BOOST_CHECK_EQUAL(std::get<0>(ps.GetFunctions()).GetCoeffs()[0], 0);\n  BOOST_CHECK_EQUAL(std::get<0>(ps.GetFunctions()).GetCoeffs()[1], 2);\n\n  auto ms = Sin() * Sin();\n  BOOST_CHECK_EQUAL(std::get<0>(ms.GetFunctions()).GetCoeffs()[0], 0);\n  BOOST_CHECK_EQUAL(std::get<0>(ms.GetFunctions()).GetCoeffs()[1], 0);\n  BOOST_CHECK_EQUAL(std::get<0>(ms.GetFunctions()).GetCoeffs()[2], 1);\n\n  auto ss = Sin()(Sin());\n  auto mss = ss * ss;\n  static_assert(\n      std::is_same<decltype(mss),\n                   Composition<IntegralPolynomial<0, 0, 1>, Sin, Sin> >::value,\n      \"Failed to simplify multiplication of \"\n      \"composition of functions.\");\n}\n", "meta": {"hexsha": "78dcc89e6cb30b76f894474d8a193c38a639e31c", "size": 1568, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "functions/tests/test_simplify.cpp", "max_stars_repo_name": "GuylainGreer/manifolds", "max_stars_repo_head_hexsha": "96f996f67fc523c726f2edbc9705125c212bedae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "functions/tests/test_simplify.cpp", "max_issues_repo_name": "GuylainGreer/manifolds", "max_issues_repo_head_hexsha": "96f996f67fc523c726f2edbc9705125c212bedae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "functions/tests/test_simplify.cpp", "max_forks_repo_name": "GuylainGreer/manifolds", "max_forks_repo_head_hexsha": "96f996f67fc523c726f2edbc9705125c212bedae", "max_forks_repo_licenses": ["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.243902439, "max_line_length": 80, "alphanum_fraction": 0.6536989796, "num_tokens": 407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.49526480883064916}}
{"text": "#ifndef NAV_TYPES_HPP\n# define NAV_TYPES_HPP\n\n#include <Eigen/Dense>\n\nusing Eigen::Matrix;\nusing Eigen::DiagonalMatrix;\n\n#define NN 30\n\ntypedef Eigen::Matrix<double,NN,NN> Cov;\ntypedef Eigen::Matrix<double,NN,1>  State;\ntypedef Eigen::Matrix<double,1,NN>  StateT;\ntypedef Eigen::Matrix<double,9,9>   Matrix9d;\n\n\nconst double FILTER_SMALL = 1e-12;  /* (--) small number used for underflow and div by zero */\nconst double PROP_DT      = 0.0125; /* (s)  propagation time step */\nconst double TAU          = 600.0;  /* (s)  time constant for ECRVs */\nconst double Q_ACCEL_PSD  = 1e-7;   /* accelerometer noise power spectral density */\nconst double Q_GYRO_PSD   = 1e-12;  /* gyroscope noise power spectral density */\n\n#endif\n", "meta": {"hexsha": "9d09de41d059e29aee90f84851f31aed6b06d153", "size": 721, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/nav_types.hpp", "max_stars_repo_name": "openlunar/nav", "max_stars_repo_head_hexsha": "37240000c542f4d42979a83ac5bebb3ab2c01fe4", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/nav_types.hpp", "max_issues_repo_name": "openlunar/nav", "max_issues_repo_head_hexsha": "37240000c542f4d42979a83ac5bebb3ab2c01fe4", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/nav_types.hpp", "max_forks_repo_name": "openlunar/nav", "max_forks_repo_head_hexsha": "37240000c542f4d42979a83ac5bebb3ab2c01fe4", "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.0416666667, "max_line_length": 94, "alphanum_fraction": 0.7073509015, "num_tokens": 208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4952427924970901}}
{"text": "// Copyright 2008 Gautam Sewani\n// Copyright 2008 John Maddock\n// Copyright 2021 Paul A. Bristow\n//\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_MATH_DISTRIBUTIONS_HYPERGEOMETRIC_HPP\n#define BOOST_MATH_DISTRIBUTIONS_HYPERGEOMETRIC_HPP\n\n#include <boost/math/distributions/detail/common_error_handling.hpp>\n#include <boost/math/distributions/complement.hpp>\n#include <boost/math/distributions/detail/hypergeometric_pdf.hpp>\n#include <boost/math/distributions/detail/hypergeometric_cdf.hpp>\n#include <boost/math/distributions/detail/hypergeometric_quantile.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n\nnamespace boost { namespace math {\n\n   template <class RealType = double, class Policy = policies::policy<> >\n   class hypergeometric_distribution\n   {\n   public:\n      typedef RealType value_type;\n      typedef Policy policy_type;\n\n      hypergeometric_distribution(unsigned r, unsigned n, unsigned N) // Constructor. r=defective/failures/success, n=trials/draws, N=total population.\n         : m_n(n), m_N(N), m_r(r)\n      {\n         static const char* function = \"boost::math::hypergeometric_distribution<%1%>::hypergeometric_distribution\";\n         RealType ret;\n         check_params(function, &ret);\n      }\n      // Accessor functions.\n      unsigned total()const\n      {\n         return m_N;\n      }\n\n      unsigned defective()const // successes/failures/events\n      {\n         return m_r;\n      }\n\n      unsigned sample_count()const\n      {\n         return m_n;\n      }\n\n      bool check_params(const char* function, RealType* result)const\n      {\n         if(m_r > m_N)\n         {\n            *result = boost::math::policies::raise_domain_error<RealType>(\n               function, \"Parameter r out of range: must be <= N but got %1%\", static_cast<RealType>(m_r), Policy());\n            return false;\n         }\n         if(m_n > m_N)\n         {\n            *result = boost::math::policies::raise_domain_error<RealType>(\n               function, \"Parameter n out of range: must be <= N but got %1%\", static_cast<RealType>(m_n), Policy());\n            return false;\n         }\n         return true;\n      }\n      bool check_x(unsigned x, const char* function, RealType* result)const\n      {\n         if(x < static_cast<unsigned>((std::max)(0, (int)(m_n + m_r) - (int)(m_N))))\n         {\n            *result = boost::math::policies::raise_domain_error<RealType>(\n               function, \"Random variable out of range: must be > 0 and > m + r - N but got %1%\", static_cast<RealType>(x), Policy());\n            return false;\n         }\n         if(x > (std::min)(m_r, m_n))\n         {\n            *result = boost::math::policies::raise_domain_error<RealType>(\n               function, \"Random variable out of range: must be less than both n and r but got %1%\", static_cast<RealType>(x), Policy());\n            return false;\n         }\n         return true;\n      }\n\n   private:\n      // Data members:\n      unsigned m_n;  // number of items picked or drawn.\n      unsigned m_N; // number of \"total\" items.\n      unsigned m_r; // number of \"defective/successes/failures/events items.\n\n   }; // class hypergeometric_distribution\n\n   typedef hypergeometric_distribution<double> hypergeometric;\n\n   template <class RealType, class Policy>\n   inline const std::pair<unsigned, unsigned> range(const hypergeometric_distribution<RealType, Policy>& dist)\n   { // Range of permissible values for random variable x.\n#ifdef _MSC_VER\n#  pragma warning(push)\n#  pragma warning(disable:4267)\n#endif\n      unsigned r = dist.defective();\n      unsigned n = dist.sample_count();\n      unsigned N = dist.total();\n      unsigned l = static_cast<unsigned>((std::max)(0, (int)(n + r) - (int)(N)));\n      unsigned u = (std::min)(r, n);\n      return std::pair<unsigned, unsigned>(l, u);\n#ifdef _MSC_VER\n#  pragma warning(pop)\n#endif\n   }\n\n   template <class RealType, class Policy>\n   inline const std::pair<unsigned, unsigned> support(const hypergeometric_distribution<RealType, Policy>& d)\n   { \n      return range(d);\n   }\n\n   template <class RealType, class Policy>\n   inline RealType pdf(const hypergeometric_distribution<RealType, Policy>& dist, const unsigned& x)\n   {\n      static const char* function = \"boost::math::pdf(const hypergeometric_distribution<%1%>&, const %1%&)\";\n      RealType result = 0;\n      if(!dist.check_params(function, &result))\n         return result;\n      if(!dist.check_x(x, function, &result))\n         return result;\n\n      return boost::math::detail::hypergeometric_pdf<RealType>(\n         x, dist.defective(), dist.sample_count(), dist.total(), Policy());\n   }\n\n   template <class RealType, class Policy, class U>\n   inline RealType pdf(const hypergeometric_distribution<RealType, Policy>& dist, const U& x)\n   {\n      BOOST_MATH_STD_USING\n      static const char* function = \"boost::math::pdf(const hypergeometric_distribution<%1%>&, const %1%&)\";\n      RealType r = static_cast<RealType>(x);\n      unsigned u = itrunc(r, typename policies::normalise<Policy, policies::rounding_error<policies::ignore_error> >::type());\n      if(u != r)\n      {\n         return boost::math::policies::raise_domain_error<RealType>(\n            function, \"Random variable out of range: must be an integer but got %1%\", r, Policy());\n      }\n      return pdf(dist, u);\n   }\n\n   template <class RealType, class Policy>\n   inline RealType cdf(const hypergeometric_distribution<RealType, Policy>& dist, const unsigned& x)\n   {\n      static const char* function = \"boost::math::cdf(const hypergeometric_distribution<%1%>&, const %1%&)\";\n      RealType result = 0;\n      if(!dist.check_params(function, &result))\n         return result;\n      if(!dist.check_x(x, function, &result))\n         return result;\n\n      return boost::math::detail::hypergeometric_cdf<RealType>(\n         x, dist.defective(), dist.sample_count(), dist.total(), false, Policy());\n   }\n\n   template <class RealType, class Policy, class U>\n   inline RealType cdf(const hypergeometric_distribution<RealType, Policy>& dist, const U& x)\n   {\n      BOOST_MATH_STD_USING\n      static const char* function = \"boost::math::cdf(const hypergeometric_distribution<%1%>&, const %1%&)\";\n      RealType r = static_cast<RealType>(x);\n      unsigned u = itrunc(r, typename policies::normalise<Policy, policies::rounding_error<policies::ignore_error> >::type());\n      if(u != r)\n      {\n         return boost::math::policies::raise_domain_error<RealType>(\n            function, \"Random variable out of range: must be an integer but got %1%\", r, Policy());\n      }\n      return cdf(dist, u);\n   }\n\n   template <class RealType, class Policy>\n   inline RealType cdf(const complemented2_type<hypergeometric_distribution<RealType, Policy>, unsigned>& c)\n   {\n      static const char* function = \"boost::math::cdf(const hypergeometric_distribution<%1%>&, const %1%&)\";\n      RealType result = 0;\n      if(!c.dist.check_params(function, &result))\n         return result;\n      if(!c.dist.check_x(c.param, function, &result))\n         return result;\n\n      return boost::math::detail::hypergeometric_cdf<RealType>(\n         c.param, c.dist.defective(), c.dist.sample_count(), c.dist.total(), true, Policy());\n   }\n\n   template <class RealType, class Policy, class U>\n   inline RealType cdf(const complemented2_type<hypergeometric_distribution<RealType, Policy>, U>& c)\n   {\n      BOOST_MATH_STD_USING\n      static const char* function = \"boost::math::cdf(const hypergeometric_distribution<%1%>&, const %1%&)\";\n      RealType r = static_cast<RealType>(c.param);\n      unsigned u = itrunc(r, typename policies::normalise<Policy, policies::rounding_error<policies::ignore_error> >::type());\n      if(u != r)\n      {\n         return boost::math::policies::raise_domain_error<RealType>(\n            function, \"Random variable out of range: must be an integer but got %1%\", r, Policy());\n      }\n      return cdf(complement(c.dist, u));\n   }\n\n   template <class RealType, class Policy>\n   inline RealType quantile(const hypergeometric_distribution<RealType, Policy>& dist, const RealType& p)\n   {\n      BOOST_MATH_STD_USING // for ADL of std functions\n\n         // Checking function argument\n         RealType result = 0;\n      const char* function = \"boost::math::quantile(const hypergeometric_distribution<%1%>&, %1%)\";\n      if (false == dist.check_params(function, &result)) return result;\n      if(false == detail::check_probability(function, p, &result, Policy())) return result;\n\n      return static_cast<RealType>(detail::hypergeometric_quantile(p, RealType(1 - p), dist.defective(), dist.sample_count(), dist.total(), Policy()));\n   } // quantile\n\n   template <class RealType, class Policy>\n   inline RealType quantile(const complemented2_type<hypergeometric_distribution<RealType, Policy>, RealType>& c)\n   {\n      BOOST_MATH_STD_USING // for ADL of std functions\n\n      // Checking function argument\n      RealType result = 0;\n      const char* function = \"quantile(const complemented2_type<hypergeometric_distribution<%1%>, %1%>&)\";\n      if (false == c.dist.check_params(function, &result)) return result;\n      if(false == detail::check_probability(function, c.param, &result, Policy())) return result;\n\n      return static_cast<RealType>(detail::hypergeometric_quantile(RealType(1 - c.param), c.param, c.dist.defective(), c.dist.sample_count(), c.dist.total(), Policy()));\n   } // quantile\n\n   // https://www.wolframalpha.com/input/?i=kurtosis+hypergeometric+distribution \n\n   template <class RealType, class Policy>\n   inline RealType mean(const hypergeometric_distribution<RealType, Policy>& dist)\n   {\n      return static_cast<RealType>(dist.defective() * dist.sample_count()) / dist.total();\n   } // RealType mean(const hypergeometric_distribution<RealType, Policy>& dist)\n\n   template <class RealType, class Policy>\n   inline RealType variance(const hypergeometric_distribution<RealType, Policy>& dist)\n   {\n      RealType r = static_cast<RealType>(dist.defective());\n      RealType n = static_cast<RealType>(dist.sample_count());\n      RealType N = static_cast<RealType>(dist.total());\n      return n * r  * (N - r) * (N - n) / (N * N * (N - 1));\n   } // RealType variance(const hypergeometric_distribution<RealType, Policy>& dist)\n\n   template <class RealType, class Policy>\n   inline RealType mode(const hypergeometric_distribution<RealType, Policy>& dist)\n   {\n      BOOST_MATH_STD_USING\n      RealType r = static_cast<RealType>(dist.defective());\n      RealType n = static_cast<RealType>(dist.sample_count());\n      RealType N = static_cast<RealType>(dist.total());\n      return floor((r + 1) * (n + 1) / (N + 2));\n   }\n\n   template <class RealType, class Policy>\n   inline RealType skewness(const hypergeometric_distribution<RealType, Policy>& dist)\n   {\n      BOOST_MATH_STD_USING\n      RealType r = static_cast<RealType>(dist.defective());\n      RealType n = static_cast<RealType>(dist.sample_count());\n      RealType N = static_cast<RealType>(dist.total());\n      return (N - 2 * r) * sqrt(N - 1) * (N - 2 * n) / (sqrt(n * r * (N - r) * (N - n)) * (N - 2));\n   } // RealType skewness(const hypergeometric_distribution<RealType, Policy>& dist)\n\n   template <class RealType, class Policy>\n   inline RealType kurtosis_excess(const hypergeometric_distribution<RealType, Policy>& dist)\n   {\n      // https://www.wolframalpha.com/input/?i=kurtosis+hypergeometric+distribution shown as plain text:\n      //  mean | (m n)/N\n      //  standard deviation | sqrt((m n(N - m) (N - n))/(N - 1))/N\n      //  variance | (m n(1 - m/N) (N - n))/((N - 1) N)\n      //  skewness | (sqrt(N - 1) (N - 2 m) (N - 2 n))/((N - 2) sqrt(m n(N - m) (N - n)))\n      //  kurtosis | ((N - 1) N^2 ((3 m(N - m) (n^2 (-N) + (n - 2) N^2 + 6 n(N - n)))/N^2 - 6 n(N - n) + N(N + 1)))/(m n(N - 3) (N - 2) (N - m) (N - n))\n     // Kurtosis[HypergeometricDistribution[n, m, N]]\n      RealType m = static_cast<RealType>(dist.defective()); // Failures or success events. (Also symbols K or M are used).\n      RealType n = static_cast<RealType>(dist.sample_count()); // draws or trials.\n      RealType n2 = n * n; // n^2\n      RealType N = static_cast<RealType>(dist.total()); // Total population from which n draws or trials are made. \n      RealType N2 = N * N; // N^2\n      // result = ((N - 1) N^2 ((3 m(N - m) (n^2 (-N) + (n - 2) N^2 + 6 n(N - n)))/N^2 - 6 n(N - n) + N(N + 1)))/(m n(N - 3) (N - 2) (N - m) (N - n));\n      RealType result = ((N-1)*N2*((3*m*(N-m)*(n2*(-N)+(n-2)*N2+6*n*(N-n)))/N2-6*n*(N-n)+N*(N+1)))/(m*n*(N-3)*(N-2)*(N-m)*(N-n));\n      // Agrees with kurtosis hypergeometric distribution(50,200,500) kurtosis = 2.96917 \n      // N[kurtosis[hypergeometricdistribution(50,200,500)], 55]  2.969174035736058474901169623721804275002985337280263464\n      return result;\n   } // RealType kurtosis_excess(const hypergeometric_distribution<RealType, Policy>& dist)\n\n   template <class RealType, class Policy>\n   inline RealType kurtosis(const hypergeometric_distribution<RealType, Policy>& dist)\n   {\n      return kurtosis_excess(dist) + 3;\n   } // RealType kurtosis_excess(const hypergeometric_distribution<RealType, Policy>& dist)\n}} // namespaces\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 // include guard\n", "meta": {"hexsha": "8ec62ccc4692aeb59b0e9c7e9f9114a9f532f5ed", "size": 13526, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/math/distributions/hypergeometric.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/distributions/hypergeometric.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/distributions/hypergeometric.hpp", "max_forks_repo_name": "oleg-alexandrov/math", "max_forks_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 243.0, "max_forks_repo_forks_event_min_datetime": "2015-01-17T17:46:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T12:56:26.000Z", "avg_line_length": 44.2026143791, "max_line_length": 169, "alphanum_fraction": 0.6550347479, "num_tokens": 3535, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.495163958826304}}
{"text": "/* vim: set tabstop=4 expandtab shiftwidth=4 softtabstop=4: */\n\n/**\n * \\file boost/numeric/ublasx/operation/lu.hpp\n *\n * \\brief LU decomposition and solver.\n *\n * Computes an LU factorization of a general m-by-n matrix \\f$A\\f$ optionally\n * using partial pivoting with row interchanges.\n * The factorization has the form\n * \\f[\n *  A = L U\n * \\f]\n * or, if partial pivoting is used:\n * \\f[\n *  A = P L U\n * \\f]\n * where \\f$P\\f$ is a permutation matrix, \\f$L\\f$ is lower triangular with unit\n * diagonal elements (lower trapezoidal if \\f$m > n\\f$), and \\f$U\\f$ is upper\n * triangular (upper trapezoidal if \\f$m < n\\f$).\n * If matrix \\f$A\\f$ is rectangular \\f$L and \\f$P are square matrices each\n * having the same number of rows as \\f$A\\f$, while \\f$U\\f$ is exactly the same\n * shape as \\f$A\\f$.\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n *\n * <hr/>\n *\n * Copyright (c) 2010, Marco Guazzone\n * \n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#ifndef BOOST_NUMERIC_UBLASX_OPERATION_LU_HPP\n#define BOOST_NUMERIC_UBLASX_OPERATION_LU_HPP\n\n//TODO: Use LAPACK functions in order to handle different types of matrices.\n//TODO: How about full pivoting?\n//TODO: Create a \\c lu_decomposition class (e.g., \\sa qr.hpp).\n\n\n#include <boost/numeric/ublas/detail/temporary.hpp>\n#include <boost/numeric/ublas/exception.hpp>\n#include <boost/numeric/ublas/expression_types.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n#include <boost/numeric/ublas/traits.hpp>\n#include <boost/numeric/ublasx/operation/num_columns.hpp>\n#include <boost/numeric/ublasx/operation/num_rows.hpp>\n#include <boost/numeric/ublasx/operation/size.hpp>\n#include <boost/numeric/ublasx/traits/layout_type.hpp>\n\n\nnamespace boost { namespace numeric { namespace ublasx {\n\nusing namespace ::boost::numeric::ublas;\n\n\n/**\n * \\brief LU decomposition without pivoting of the given matrix \\a A.\n * \\param A The matrix to be decomposed.\n * \\return Zero if decomposition succeed; non-zero if decompositon fails (the\n *  value is 1 + the numer of the failing row). The input matrix \\a A is\n *  modified in order to contain the L*U matrix.\n *\n * Perform LU decomposition of matrix \\a A and replaces the strict lower\n * triangular part of \\a m with the computed matrix L and the upper triangular\n * part of \\a m is replaced by the computed matrix U.\n * For obtaining the single matrices L and U proceed as follows:\n * - for L: extract the strict lower-triangular part (i.e., without the main\n *   diagonal) from the computed matrix \\a m and add to it the identity matrix\n *   of the same order of \\a m;\n * - for U: extract the upper-triangular part (with the main diagonal) from the\n *   computer matrix \\a m.\n */\ntemplate <typename MatrixT>\nBOOST_UBLAS_INLINE\ntypename matrix_traits<MatrixT>::size_type lu_decompose_inplace(matrix_container<MatrixT>& A)\n{\n    return lu_factorize(A());\n}\n\n\n/**\n * \\brief LU decomposition with partial pivoting of the matrix \\a A.\n *\n * \\param A The matrix to be decomposed.\n * \\param P The permutation matrix reporting permutated rows of \\a A after\n *  the decomposition.\n * \\return Zero if decomposition succeed; non-zero if decompositon fails (the\n *  value is 1 + the numer of the failing row). The input matrix \\a A is\n *  modified in order to contain the L*U matrix.\n *\n * Perform LUP decomposition of matrix \\a A and replaces the strict lower\n * triangular part of \\a A with the computed matrix L and the upper triangular\n * part of \\a A is replaced by the computed matrix U.\n * For obtaining the single matrices L and U proceed as follows:\n * - for L: extract the strict lower-triangular part (i.e., without the main\n *   diagonal) from the computed matrix \\a m and add to it the identity matrix\n *   of the same order of \\a A;\n * - for U: extract the upper-triangular part (with the main diagonal) from the\n *   computer matrix \\a A.\n * .\n */\ntemplate <typename MatrixT, typename PermutationMatrixT>\nBOOST_UBLAS_INLINE\ntypename matrix_traits<MatrixT>::size_type lu_decompose_inplace(matrix_container<MatrixT>& A, PermutationMatrixT& P)\n{\n    typedef typename matrix_traits<MatrixT>::size_type size_type;\n\n    // Safety check: P is squared && size(P) == num_rows(A)\n    //BOOST_UBLAS_CHECK( size(P) == num_columns(P) && size(P) == num_rows(A), bad_size() );\n    size_type nr_A = num_rows(A);\n    if (size(P) != nr_A)\n    {\n        P.resize(nr_A, false);\n    }\n\n    return lu_factorize(A(), P);\n//\n//  // postcondition: P is squared && size(P) == num_rows(A)\n//  BOOST_UBLAS_CHECK( size(P) == num_columns(P) && size(P) == num_rows(A), bad_size() );\n}\n\n\n/**\n * \\brief LU decomposition without pivoting of the matrix \\a A.\n *\n * \\tparam MatrixT The type of the matrix to be decomposed.\n * \\param A The matrix to be decomposed.\n * \\return Zero if decomposition succeed; non-zero if decompositon fails (the\n *  value is 1 + the numer of the failing row). The input matrix \\a A is\n *  modified in order to contain the L*U matrix.\n *\n * Perform LU decomposition of matrix \\a A and replaces the strict lower\n * triangular part of \\a A with the computed matrix L and the upper triangular\n * part of \\a A is replaced by the computed matrix U.\n * For obtaining the single matrices L and U proceed as follows:\n * - for L: extract the strict lower-triangular part (i.e., without the main\n *   diagonal) from the computed matrix \\a A and add to it the identity matrix\n *   of the same order of \\a A;\n * - for U: extract the upper-triangular part (with the main diagonal) from the\n *   computer matrix \\a A.\n * .\n */\ntemplate <typename AMatrixExprT, typename LUMatrixT>\nBOOST_UBLAS_INLINE\ntypename matrix_traits<AMatrixExprT>::size_type lu_decompose(matrix_expression<AMatrixExprT> const& A, matrix_container<LUMatrixT>& LU)\n{\n    LU = A;\n\n    return lu_decompose_inplace(LU);\n}\n\n\n/**\n * \\brief LU decomposition with partial pivoting of the matrix \\a A.\n *\n * \\pre Matrix \\a A must be squared.\n * \\tparam MatrixT The type of the matrix to be decomposed.\n * \\param A The matrix to be decomposed.\n * \\param P The permutation matrix reporting permutated rows of \\a A after\n *  the decomposition.\n * \\return The LU matrix.\n *\n * Perform LUP decomposition of matrix \\a A and return the LU matrix.\n * For obtaining the single matrices L and U proceed as follows:\n * - for L: extract the strict lower-triangular part (i.e., without the main\n *   diagonal) from the computed matrix \\c LU and add to it the identity matrix\n *   of the same order of \\c LU;\n * - for U: extract the upper-triangular part (with the main diagonal) from the\n *   computer matrix \\c LU.\n * .\n */\ntemplate <typename AMatrixExprT, typename PermutationMatrixT, typename LUMatrixT>\nBOOST_UBLAS_INLINE\ntypename matrix_traits<AMatrixExprT>::size_type lu_decompose(matrix_expression<AMatrixExprT> const& A, PermutationMatrixT& P, matrix_container<LUMatrixT>& LU)\n{\n    typedef typename matrix_traits<AMatrixExprT>::size_type size_type;\n\n    // Safety check: size(P) == num_rows(A)\n    //BOOST_UBLAS_CHECK( size(P) == num_rows(A), bad_size() );\n    size_type nr_A = num_rows(A);\n    if (size(P) != nr_A)\n    {\n        P.resize(nr_A, false);\n    }\n\n    LU = A;\n\n    return lu_decompose_inplace(LU, P);\n}\n\n\n/**\n * \\brief Complete the LU forward/backward substitution for solving the system\n *  \\f$LUx=b\\f$.\n *\n * \\pre The size of \\a b must be the same as the number of rows of \\a LU.\n * \\tparam MatrixExprT The type of the matrix obtained by the LU decomposition.\n * \\tparam VectorT The type of the constant terms vector.\n * \\param LU A matrix representing an LU decomposition.\n * \\param b The vector of coefficients.\n * \\return Nothing. However, the vector \\a b is replaced with the value of\n *  unknowns \\f$x_i\\f$ satisfying the system \\f$LUx=b\\f$.\n *\n * An \\f$n \\times n\\f$ linear system \\f$Ax=b\\f$ can often be solved efficiently\n * by \\f$LU\\f$ decomposition (that is by decomposing matrix \\f$A\\f$ into a\n * product \\f$LU\\f$, where \\f$L\\f$ is a lower-triangular matrix with ones on the\n * diagonal, and \\f$U\\f$ is an upper-triangular matrix). Solving the system\n * \\f$Ax=b\\f$ is then equivalent to solving two simpler systems \\f$Ly=b\\f$ and\n * \\f$Ux=y\\f$. Since \\f$L\\f$ is lower-triangular, the system \\f$Ly=b\\f$ can be\n * solved by forward substitution. Moreover, since \\f$U\\f$ is upper-triangular,\n * the system \\f$Ux=y\\f$ can be solved by backward substitution.\n */\ntemplate <typename MatrixExprT, typename VectorT>\nBOOST_UBLAS_INLINE\nvoid lu_apply_inplace(matrix_expression<MatrixExprT> const& LU, vector_container<VectorT>& b)\n{\n    // pre: size(b) == size(P)\n    BOOST_UBLAS_CHECK( size(b) == num_rows(LU), bad_size() );\n\n    lu_substitute(LU(), b());\n}\n\n\n/**\n * \\brief Complete the LU forward/backward substitution for solving the system\n *  \\f$LUX=B\\f$.\n *\n * \\pre The number of rows of \\a LU and \\a b must be the same.\n * \\tparam LUMatrixExprT The type of the matrix obtained by the LU decomposition.\n * \\tparam BMatrixT The type of the constant terms vector.\n * \\param LU A matrix representing an LU decomposition.\n * \\param B The matrix of coefficients.\n * \\return Nothing. However, the matrix \\a B is replaced with the value of\n *  unknowns \\f$X_{ij}\\f$ satisfying the system \\f$LUX=B\\f$.\n *\n * An \\f$n \\times n\\f$ linear system \\f$Ax=B\\f$ can often be solved efficiently\n * by \\f$LU\\f$ decomposition (that is by decomposing matrix \\f$A\\f$ into a\n * product \\f$LU\\f$, where \\f$L\\f$ is a lower-triangular matrix with ones on the\n * diagonal, and \\f$U\\f$ is an upper-triangular matrix). Solving the system\n * \\f$AX=B\\f$ is then equivalent to solving two simpler systems \\f$LY=B\\f$ and\n * \\f$UX=Y\\f$. Since \\f$L\\f$ is lower-triangular, the system \\f$LY=B\\f$ can be\n * solved by forward substitution. Moreover, since \\f$U\\f$ is upper-triangular,\n * the system \\f$UX=Y\\f$ can be solved by backward substitution.\n */\ntemplate <typename LUMatrixExprT, typename BMatrixT>\nBOOST_UBLAS_INLINE\nvoid lu_apply_inplace(matrix_expression<LUMatrixExprT> const& LU, matrix_container<BMatrixT>& B)\n{\n    // pre: num_rows(B) == num_rows(LU)\n    BOOST_UBLAS_CHECK( num_rows(B) == num_rows(LU), bad_size() );\n\n    lu_substitute(LU(), B());\n}\n\n\n/**\n * \\brief Complete the LUP forward/backward substitution for solving the system\n *  \\f$LU*X=P*b\\f$.\n * \n * \\pre The size of \\a P must be the same as the number of rows of \\a LU.\n * \\pre The size of \\a b must be the same as the number of rows of \\a LU.\n * \\param LU A matrix representing an LU decomposition.\n * \\param P A permutation matrix.\n * \\param b The vector constant terms.\n * \\return Nothing. However, the vector \\a b is replaced with the value\n *  of unknowns \\f$x_i\\f$ satisfying the system \\f$LU*x=P*b\\f$.\n *\n * An \\f$n \\times n\\f$ linear system \\f$Ax=b\\f$ can often be solved efficiently\n * by \\f$LU\\f$ decomposition (that is by decomposing matrix \\f$A\\f$ into a\n * product \\f$LUP\\f$, where \\f$L\\f$ is a lower-triangular matrix with ones on\n * the diagonal, \\f$U\\f$ is an upper-triangular matrix, and \\f$P\\f$ is a row\n * permutation matrix that is used to rearrange the rows of \\f$A\\f$ before so\n * that it can be decomposed). Solving the system \\f$Ax=b\\f$ is then equivalent\n * to solving two simpler systems \\f$Ly=Pb\\f$ and \\f$Ux=y\\f$. Since \\f$L\\f$ is\n * lower-triangular, the system \\f$Ly=Pb\\f$ can be solved by forward\n * substitution. Moreover, since \\f$U\\f$ is upper-triangular, the system\n * \\f$Ux=y\\f$ can be solved by backward substitution.\n */\ntemplate <typename LUMatrixExprT, typename PermutationMatrixT, typename BVectorT>\nBOOST_UBLAS_INLINE\nvoid lu_apply_inplace(matrix_expression<LUMatrixExprT> const& LU, PermutationMatrixT const& P, vector_container<BVectorT>& b)\n{\n    // precondition: size(P) == num_rows(LU)\n    BOOST_UBLAS_CHECK( size(P) == num_rows(LU), bad_size() );\n    // precondition: size(b) == num_rows(LU)\n    BOOST_UBLAS_CHECK( size(b) == num_rows(LU), bad_size() );\n\n    lu_substitute(LU(), P, b());\n}\n\n\n/**\n * \\brief Complete the LUP forward/backward substitution for solving the system\n *  \\f$LU*X=P*B\\f$.\n * \n * \\pre The size of \\a P must be the same as the number of rows of \\a LU.\n * \\pre The number of rows of \\a LU and of \\a B must be the same.\n * \\param LU A matrix representing an LU decomposition.\n * \\param P A permutation matrix.\n * \\param B The matrix of constant terms.\n * \\return Nothing. However, the matrix \\a B is replaced with the value\n *  of unknowns \\f$X_{ij}\\f$ satisfying the system \\f$LU*X=P*B\\f$.\n *\n * An \\f$n \\times n\\f$ linear system \\f$AX=B\\f$ can often be solved efficiently\n * by \\f$LU\\f$ decomposition (that is by decomposing matrix \\f$A\\f$ into a\n * product \\f$LUP\\f$, where \\f$L\\f$ is a lower-triangular matrix with ones on\n * the diagonal, \\f$U\\f$ is an upper-triangular matrix, and \\f$P\\f$ is a row\n * permutation matrix that is used to rearrange the rows of \\f$A\\f$ before so\n * that it can be decomposed). Solving the system \\f$AX=B\\f$ is then equivalent\n * to solving two simpler systems \\f$LY=Pb\\f$ and \\f$UX=y\\f$. Since \\f$L\\f$ is\n * lower-triangular, the system \\f$LY=PB\\f$ can be solved by forward\n * substitution. Moreover, since \\f$U\\f$ is upper-triangular, the system\n * \\f$UX=Y\\f$ can be solved by backward substitution.\n */\ntemplate <typename LUMatrixExprT, typename PermutationMatrixT, typename BMatrixT>\nBOOST_UBLAS_INLINE\nvoid lu_apply_inplace(matrix_expression<LUMatrixExprT> const& LU, PermutationMatrixT const& P, matrix_container<BMatrixT>& B)\n{\n    // pre: size(P) == num_rows(LU)\n    BOOST_UBLAS_CHECK( size(P) == num_rows(LU), bad_size() );\n    // pre: num_rows(b) == num_rows(LU)\n    BOOST_UBLAS_CHECK( num_rows(B) == num_rows(LU), bad_size() );\n\n    lu_substitute(LU(), P, B());\n}\n\n\n/**\n * \\brief Complete the LU forward/backward substitution for solving the system\n *  \\f$LUx=b\\f$.\n *\n * \\param LU A matrix representing an LU decomposition.\n * \\param b The vector of coefficients.\n * \\return The vector of unknowns \\f$x\\f$ satisfying the system \\f$LUPx=b\\f$.\n *\n * An \\f$n \\times n\\f$ linear system \\f$Ax=b\\f$ can often be solved efficiently\n * by \\f$LU\\f$ decomposition (that is by decomposing matrix \\f$A\\f$ into a\n * product \\f$LU\\f$, where \\f$L\\f$ is a lower-triangular matrix with ones on the\n * diagonal, and \\f$U\\f$ is an upper-triangular matrix). Solving the system\n * \\f$Ax=b\\f$ is then equivalent to solving two simpler systems \\f$Ly=b\\f$ and\n * \\f$Ux=y\\f$. Since \\f$L\\f$ is lower-triangular, the system \\f$Ly=b\\f$ can be\n * solved by forward substitution. Moreover, since \\f$U\\f$ is upper-triangular,\n * the system \\f$Ux=y\\f$ can be solved by backward substitution.\n */\ntemplate <typename LUMatrixExprT, typename BVectorExprT>\nBOOST_UBLAS_INLINE\ntypename vector_temporary_traits<BVectorExprT>::type lu_apply(matrix_expression<LUMatrixExprT> const& LU, vector_expression<BVectorExprT> const& b)\n{\n    //  preconditions check delegated to lu_apply_inplace\n\n    typedef typename vector_temporary_traits<BVectorExprT>::type out_vector_type;\n\n    out_vector_type x(b);\n\n    lu_apply_inplace(LU, x);\n\n    return x;\n}\n\n\n/**\n * \\brief Complete the LU forward/backward substitution for solving the system\n *  \\f$LU*X=B\\f$.\n *\n * \\param LU A matrix representing an LU decomposition.\n * \\param B The matrix of constant terms.\n * \\return The matrix of unknowns \\f$X\\f$ satisfying the system \\f$LU*X=B\\f$.\n */\ntemplate <typename LUMatrixExprT, typename BMatrixExprT>\nBOOST_UBLAS_INLINE\ntypename matrix_temporary_traits<BMatrixExprT>::type lu_apply(matrix_expression<LUMatrixExprT> const& LU, matrix_expression<BMatrixExprT> const& B)\n{\n    //  preconditions check delegated to lu_apply_inplace\n\n    typedef typename matrix_temporary_traits<BMatrixExprT>::type out_matrix_type;\n\n    out_matrix_type X(B);\n\n    lu_apply_inplace(LU, X);\n\n    return X;\n}\n\n\n/**\n * \\brief Complete the LUP forward/backward substitution for solving the system\n *  \\f$LUx=b\\f$.\n *\n * \\param LU A matrix representing an LU decomposition.\n * \\param P A permutation matrix.\n * \\param b The vector of coefficients.\n * \\return The vector of unknowns \\f$x\\f$ satisfying the system \\f$LUPx=b\\f$.\n *\n * An \\f$n \\times n\\f$ linear system \\f$Ax=b\\f$ can often be solved efficiently\n * by \\f$LU\\f$ decomposition (that is by decomposing matrix \\f$A\\f$ into a\n * product \\f$LUP\\f$, where \\f$L\\f$ is a lower-triangular matrix with ones on\n * the diagonal, \\f$U\\f$ is an upper-triangular matrix, and \\f$P\\f$ is a row\n * permutation matrix that is used to rearrange the rows of A before so that it\n * can be decomposed). Solving the system \\f$Ax=b\\f$ is then equivalent to\n * solving two simpler systems \\f$Ly=Pb\\f$ and \\f$Ux=y\\f$. Since \\f$L\\f$ is\n * lower-triangular, the system \\f$Ly=Pb\\f$ can be solved by forward\n * substitution. Moreover, since \\f$U\\f$ is upper-triangular, the system\n * \\f$Ux=y\\f$ can be solved by backward substitution.\n */\ntemplate <typename LUMatrixExprT, typename PermutationMatrixT, typename BVectorExprT>\nBOOST_UBLAS_INLINE\ntypename vector_temporary_traits<BVectorExprT>::type lu_apply(matrix_expression<LUMatrixExprT> const& LU, PermutationMatrixT const& P, vector_expression<BVectorExprT> const& b)\n{\n    //  preconditions check delegated to lu_apply_inplace\n\n    typedef typename vector_temporary_traits<BVectorExprT>::type out_vector_type;\n\n    out_vector_type x(b);\n\n    lu_apply_inplace(LU, P, x);\n\n    return x;\n}\n\n\n/**\n * \\brief Complete the LUP forward/backward substitution for solving the system\n *  \\f$LUP*X=B\\f$.\n *\n * \\param LU A matrix representing an LU decomposition.\n * \\param P A permutation matrix.\n * \\param B The matrix of constant terms.\n * \\return The matrix of unknowns \\f$X\\f$ satisfying the system \\f$LUP*X=B\\f$.\n */\ntemplate <typename LUMatrixExprT, typename PermutationMatrixT, typename BMatrixExprT>\nBOOST_UBLAS_INLINE\ntypename matrix_temporary_traits<BMatrixExprT>::type lu_apply(matrix_expression<LUMatrixExprT> const& LU, PermutationMatrixT const& P, matrix_expression<BMatrixExprT> const& B)\n{\n    //  preconditions check delegated to lu_apply_inplace\n\n    typedef typename matrix_temporary_traits<BMatrixExprT>::type out_matrix_type;\n\n    out_matrix_type X(B);\n\n    lu_apply_inplace(LU, P, X);\n\n    return X;\n}\n\n\n/**\n * \\brief Solve the linear system \\f$Ax=b\\f$ by LUP decomposition.\n *\n * \\pre The size of \\a b must be the same as the number of rows of \\a A.\n * \\param A The input matrix representing the coefficients of the unknowns.\n * \\param b The vector of coefficients.\n * \\return A zero value if the system is solvable; a number greater than zero if\n *  it is not. Moreover, the vector \\a b is replaced with the value of unknowns\n *  \\f$x_i\\f$ satisfying the system \\f$Ax=b\\f$.\n *\n * An \\f$n \\times n\\f$ linear system \\f$Ax=b\\f$ can often be solved efficiently\n * by \\f$LU\\f$ decomposition (that is by decomposing matrix \\f$A\\f$ into a\n * product \\f$LUP\\f$, where \\f$L\\f$ is a lower-triangular matrix with ones on\n * the diagonal, \\f$U\\f$ is an upper-triangular matrix, and \\f$P\\f$ is a row\n * permutation matrix that is used to rearrange the rows of \\f$A\\f$ before so\n * that it can be decomposed). Solving the system \\f$Ax=b\\f$ is then equivalent\n * to solving two simpler systems \\f$Ly=Pb\\f$ and \\f$Ux=y\\f$. Since \\f$L\\f$ is\n * lower-triangular, the system \\f$Ly=Pb\\f$ can be solved by forward\n * substitution. Moreover, since \\f$U\\f$ is upper-triangular, the system\n * \\f$Ux=y\\f$ can be solved by backward substitution.\n */\ntemplate <typename MatrixExprT, typename VectorT>\nBOOST_UBLAS_INLINE\ntypename matrix_traits<MatrixExprT>::size_type lu_solve_inplace(matrix_expression<MatrixExprT> const& A, vector_container<VectorT>& b)\n{\n    // precondition: size(b) == num_rows(A)\n    BOOST_UBLAS_CHECK( size(b) == num_rows(A), bad_size() );\n\n    typedef typename matrix_traits<MatrixExprT>::size_type size_type;\n    typedef typename matrix_traits<MatrixExprT>::value_type value_type;\n    typedef typename layout_type<MatrixExprT>::type layout_type;\n\n    // Ax=b ==> LUx=b ==> Ly=b AND Ux=y\n\n    matrix<value_type, layout_type> LU(A);\n    permutation_matrix<size_type> P(num_rows(LU));\n\n    size_type singular;\n    singular = lu_decompose_inplace(LU, P);\n\n    if (!singular)\n    {\n        lu_apply_inplace(LU, P, b());\n    }\n\n    return singular;\n}\n\n\n/**\n * \\brief Solve the linear system \\f$AX=B\\f$ by LUP decomposition.\n *\n * \\pre The number of rows of \\a A and \\a B must be the same.\n * \\param A The input matrix representing the coefficients of the unknowns.\n * \\param B The matrix of coefficients.\n * \\return A zero value if the system is solvable; a number greater than zero if\n *  it is not. Moreover, the matrix \\a B is replaced with the value of unknowns\n *  \\f$X_{ij}\\f$ satisfying the system \\f$AX=B\\f$.\n *\n * An \\f$n \\times n\\f$ linear system \\f$AX=B\\f$ can often be solved efficiently\n * by \\f$LU\\f$ decomposition (that is by decomposing matrix \\f$A\\f$ into a\n * product \\f$LUP\\f$, where \\f$L\\f$ is a lower-triangular matrix with ones on\n * the diagonal, \\f$U\\f$ is an upper-triangular matrix, and \\f$P\\f$ is a row\n * permutation matrix that is used to rearrange the rows of \\f$A\\f$ before so\n * that it can be decomposed). Solving the system \\f$AX=B\\f$ is then equivalent\n * to solving two simpler systems \\f$LY=PB\\f$ and \\f$UX=Y\\f$. Since \\f$L\\f$ is\n * lower-triangular, the system \\f$LY=PB\\f$ can be solved by forward\n * substitution. Moreover, since \\f$U\\f$ is upper-triangular, the system\n * \\f$UX=Y\\f$ can be solved by backward substitution.\n */\ntemplate <typename AMatrixExprT, typename BMatrixExprT>\nBOOST_UBLAS_INLINE\ntypename matrix_traits<AMatrixExprT>::size_type lu_solve_inplace(matrix_expression<AMatrixExprT> const& A, matrix_container<BMatrixExprT>& B)\n{\n    // pre: num_rows(B) == num_rows(A)\n    BOOST_UBLAS_CHECK( num_rows(B) == num_rows(A), bad_size() );\n\n    typedef typename matrix_traits<AMatrixExprT>::size_type size_type;\n    typedef typename matrix_traits<AMatrixExprT>::value_type value_type;\n    typedef typename layout_type<AMatrixExprT>::type layout_type;\n\n    // Ax=B ==> LUx=B ==> Ly=B AND Ux=y\n\n    matrix<value_type, layout_type> LU(A());\n    permutation_matrix<size_type> P(num_rows(LU));\n\n    size_type singular;\n    singular = lu_decompose_inplace(LU, P);\n\n    if (!singular)\n    {\n        lu_apply_inplace(LU, P, B());\n    }\n\n    return singular;\n}\n\n\n/**\n * \\brief Solve the linear system \\f$Ax=b\\f$ by LUP decomposition.\n *\n * \\pre The size of \\a b must be the same as the number of rows of \\a A.\n * \\param A The input matrix representing the coefficients of the unknowns..\n * \\param b The vector of coefficients.\n * \\return The vector of unknowns \\f$x\\f$ satisfying the system \\f$Ax=b\\f$.\n *\n * An \\f$n \\times n\\f$ linear system \\f$Ax=b\\f$ can often be solved efficiently\n * by \\f$LU\\f$ decomposition (that is by decomposing matrix \\f$A\\f$ into a\n * product \\f$LUP\\f$, where \\f$L\\f$ is a lower-triangular matrix with ones on\n * the diagonal, \\f$U\\f$ is an upper-triangular matrix, and \\f$P\\f$ is a row\n * permutation matrix that is used to rearrange the rows of A before so that it\n * can be decomposed). Solving the system \\f$Ax=b\\f$ is then equivalent to\n * solving two simpler systems \\f$Ly=Pb\\f$ and \\f$Ux=y\\f$. Since \\f$L\\f$ is\n * lower-triangular, the system \\f$Ly=Pb\\f$ can be solved by forward\n * substitution. Moreover, since \\f$U\\f$ is upper-triangular, the system\n * \\f$Ux=y\\f$ can be solved by backward substitution.\n */\ntemplate <typename MatrixExprT, typename VectorExprT, typename OutVectorT>\nBOOST_UBLAS_INLINE\ntypename matrix_traits<MatrixExprT>::size_type lu_solve(matrix_expression<MatrixExprT> const& A, vector_expression<VectorExprT> const& b, OutVectorT& x)\n{\n    // precondition: size(b) == num_rows(A)\n    BOOST_UBLAS_CHECK( size(b) == num_rows(A), bad_size() );\n\n    // Ax=b ==> LUx=b ==> Ly=b AND Ux=y\n\n    typedef typename matrix_traits<MatrixExprT>::value_type size_type;\n    typedef typename matrix_traits<MatrixExprT>::value_type value_type;\n    typedef typename layout_type<MatrixExprT>::type layout_type;\n\n    matrix<value_type,layout_type> LU(A);\n    permutation_matrix<size_type> P(num_rows(LU));\n\n    size_type singular;\n    singular = lu_decompose_inplace(LU, P);\n\n    if (!singular)\n    {\n        x = b;\n\n        lu_apply_inplace(LU, P, x);\n    }\n\n    return singular;\n}\n\n/**\n * \\brief Solve the linear system \\f$Ax=b\\f$ by LUP decomposition.\n *\n * \\pre The size of \\a b must be the same as the number of rows of \\a A.\n * \\param A The input matrix representing the coefficients of the unknowns..\n * \\param b The vector of coefficients.\n * \\return The vector of unknowns \\f$x\\f$ satisfying the system \\f$Ax=b\\f$.\n *\n * An \\f$n \\times n\\f$ linear system \\f$Ax=b\\f$ can often be solved efficiently\n * by \\f$LU\\f$ decomposition (that is by decomposing matrix \\f$A\\f$ into a\n * product \\f$LUP\\f$, where \\f$L\\f$ is a lower-triangular matrix with ones on\n * the diagonal, \\f$U\\f$ is an upper-triangular matrix, and \\f$P\\f$ is a row\n * permutation matrix that is used to rearrange the rows of A before so that it\n * can be decomposed). Solving the system \\f$Ax=b\\f$ is then equivalent to\n * solving two simpler systems \\f$Ly=Pb\\f$ and \\f$Ux=y\\f$. Since \\f$L\\f$ is\n * lower-triangular, the system \\f$Ly=Pb\\f$ can be solved by forward\n * substitution. Moreover, since \\f$U\\f$ is upper-triangular, the system\n * \\f$Ux=y\\f$ can be solved by backward substitution.\n */\ntemplate <typename AMatrixExprT, typename BMatrixExprT, typename OutMatrixT>\nBOOST_UBLAS_INLINE\ntypename matrix_traits<AMatrixExprT>::size_type lu_solve(matrix_expression<AMatrixExprT> const& A, matrix_expression<BMatrixExprT> const& B, OutMatrixT& X)\n{\n    // precondition: size(b) == num_rows(A)\n    BOOST_UBLAS_CHECK( num_rows(B) == num_rows(A), bad_size() );\n\n    // Ax=b ==> LUx=b ==> Ly=b AND Ux=y\n\n    typedef typename matrix_traits<AMatrixExprT>::value_type size_type;\n    typedef typename matrix_traits<AMatrixExprT>::value_type value_type;\n    typedef typename layout_type<AMatrixExprT>::type layout_type;\n\n    matrix<value_type,layout_type> LU(A);\n    permutation_matrix<size_type> P(num_rows(LU));\n\n    size_type singular;\n    singular = lu_decompose_inplace(LU, P);\n\n    if (!singular)\n    {\n        X = B;\n\n        lu_apply_inplace(LU, P, X);\n    }\n\n    return singular;\n}\n\n}}} // Namespace boost::numeric::ublasx\n\n\n#endif // BOOST_NUMERIC_UBLASX_OPERATION_LU_HPP\n", "meta": {"hexsha": "025f44ec44c2404688dc1f4dbf58d62aa3683641", "size": 26246, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/ublasx/operation/lu.hpp", "max_stars_repo_name": "sguazt/boost-ublasx", "max_stars_repo_head_hexsha": "21c9b393d33a6ec2a8071ba8d48680073d766409", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2016-05-14T11:08:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-05T14:22:20.000Z", "max_issues_repo_path": "boost/numeric/ublasx/operation/lu.hpp", "max_issues_repo_name": "sguazt/boost-ublasx", "max_issues_repo_head_hexsha": "21c9b393d33a6ec2a8071ba8d48680073d766409", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-12-28T18:36:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-06T11:28:51.000Z", "max_forks_repo_path": "boost/numeric/ublasx/operation/lu.hpp", "max_forks_repo_name": "sguazt/boost-ublasx", "max_forks_repo_head_hexsha": "21c9b393d33a6ec2a8071ba8d48680073d766409", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-12-23T02:53:27.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-23T02:53:27.000Z", "avg_line_length": 40.5030864198, "max_line_length": 176, "alphanum_fraction": 0.7129467347, "num_tokens": 7361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998560157665, "lm_q2_score": 0.6370308082623216, "lm_q1q2_score": 0.49516395553990994}}
{"text": "//[hello\n\n#include <boost/simd/sdk/simd/pack.hpp>\n#include <boost/simd/sdk/simd/io.hpp>\n#include <boost/simd/include/functions/splat.hpp>\n#include <boost/simd/include/functions/plus.hpp>\n#include <boost/simd/include/functions/multiplies.hpp>\n#include <iostream>\n\nint main()\n{\n  typedef boost::simd::pack<float> p_t;\n\n  p_t res;\n  p_t u(10);\n  p_t r = boost::simd::splat<p_t>(11);\n\n  res = (u + r) * 2.f;\n\n  std::cout << res << std::endl;\n\n  return 0;\n}\n//]\n\n", "meta": {"hexsha": "c20dfbe54e42335bad30f8828f3a651edcf99e82", "size": 458, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "demo/helloworld/simd/helloworld_simd.cpp", "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": "demo/helloworld/simd/helloworld_simd.cpp", "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": "demo/helloworld/simd/helloworld_simd.cpp", "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": 17.6153846154, "max_line_length": 54, "alphanum_fraction": 0.6615720524, "num_tokens": 140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.4951639546863927}}
{"text": "#pragma once\n#include <cmath>\n#include <omp.h>\n#include <vector>\n#include <string>\n#include <cstdio>\n#include <random>\n#include <fstream>\n#include <algorithm>\n#include <unordered_set>\n#include <parallel/algorithm>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n#include \"n2/hnsw.h\"\n\n\nusing namespace std;\nusing namespace Eigen;\n\nnamespace parallel\n{\n\nstruct nn_t\n{\n    int key;\n    float val;\n    nn_t() : key(-1), val(-987654321.0) {}\n    bool operator < (const float& that){\n        return this->val > that;\n    }\n\n    bool operator < (const nn_t& that){\n        return this->val > that.val;\n    }\n};\n\nstruct topn_t\n{\n    nn_t* nns;\n    int K;\n    topn_t() : K(0) {}\n    void alloc(int _K){\n        K = _K;\n        nns = new nn_t[K];\n    }\n    void free() {\n        if(K){\n            delete[] nns;\n        }\n    }\n    void update(int& key, float& val){\n        nn_t* ptr = lower_bound(nns, nns + K, val);\n        int idx = (int)(ptr - nns);\n        if(idx >= K)\n            return;\n        if(idx + 1 == K){\n            nns[idx].key = key;\n            nns[idx].val = val;\n        }\n        else{\n            memmove((void*)&nns[idx + 1], (void*)&nns[idx], sizeof(nn_t) * (K - idx - 1));\n            nns[idx].key = key;\n            nns[idx].val = val;\n        }\n    }\n};\n\nvoid quickselect(float* scores, int rows, int cols, int32_t* result, int k, bool sorted, int num_threads){\n    Map<Matrix<float, Dynamic, Dynamic, RowMajor>> _scores(scores, rows, cols);\n    Map<Matrix<int, Dynamic, Dynamic, RowMajor>> _result(result, rows, k);\n    omp_set_num_threads(num_threads);\n    #pragma omp parallel for schedule(dynamic, 4)\n    for (int i=0; i<rows; ++i){\n        vector<int> ranks(cols);\n        iota(ranks.begin(), ranks.end(), 0);  // initialize ranks as {0, 1, 2, ...}\n        // high score has a priority\n        nth_element(ranks.begin(), ranks.begin() + k - 1, ranks.end(), \n                    [&](int lhs, int rhs){return _scores(i, lhs) > _scores(i, rhs);});\n        // sort ranks[: k], since it is not guaranteed to be sorted\n        if (sorted)\n            sort(ranks.begin(), ranks.begin() + k,\n                    [&](int lhs, int rhs){return _scores(i, lhs) > _scores(i, rhs);});\n        copy(ranks.begin(), ranks.begin() + k, &_result(i, 0));\n    }\n}\n\nvoid dot_topn(\n        int32_t* indexes, int num_queries,\n        float* _P, int p_rows, int p_cols,\n        float* _Q, int q_rows, int q_cols,\n        float* _Qb, int qb_rows,\n        int32_t* _out_keys, float* _out_scores,\n        int32_t* _pool, int pool_size,\n        int k, int num_threads)\n{\n    bool is_same = _P == _Q;\n    Map<Matrix<float, Dynamic, Dynamic, RowMajor>> P(_P, p_rows, p_cols);\n    Map<Matrix<float, Dynamic, Dynamic, RowMajor>> Q(_Q, q_rows, q_cols);\n    Map<Matrix<float, Dynamic, Dynamic, RowMajor>> Qb(_Qb, qb_rows, 1);\n    Map<Matrix<int, Dynamic, Dynamic, RowMajor>> out_keys(_out_keys, num_queries, k);\n    Map<Matrix<float , Dynamic, Dynamic, RowMajor>> out_scores(_out_scores, num_queries, k);\n\n    unordered_set<int32_t> pool;\n    for (int i=0; i < pool_size; ++i)\n        pool.insert(_pool[i]);\n\n    int correct_k = min(q_rows, k);\n    if (pool_size)\n        correct_k = min(pool_size, correct_k);\n\n    omp_set_num_threads(num_threads);\n    #pragma omp parallel for schedule(guided)\n    for (int i=0; i < num_queries; ++i){\n        topn_t topn;\n        topn.alloc(correct_k);\n        float last_one = -987654321.0f;\n        int q = indexes[i];\n        for (int j=0; j < q_rows; ++j) {\n            if (is_same and q == j)\n                continue;\n            if (pool_size and pool.find(j) == pool.end())\n                continue;\n            float score = P.row(q).dot(Q.row(j));\n            if (qb_rows)\n                score += Qb(j);\n            if (score > last_one) {\n                topn.update(j, score);\n                last_one = topn.nns[correct_k - 1].val;\n            }\n        }\n        for (int j=0; j < correct_k; ++j) {\n            out_keys(i, j) = topn.nns[j].key;\n            out_scores(i, j) = topn.nns[j].val;\n        }\n        for (int j=correct_k; j < k; ++j) {\n            out_keys(i, j) = -1;\n            out_scores(i, j) = 0.0;\n        }\n        topn.free();\n    }\n}\n\n\nvoid ann_search(\n        string index_path,\n        int ef_search,\n        bool use_mmap,\n        int32_t* indexes, int num_queries,\n        float* _P, int p_rows, int p_cols,\n        float* _Q, int q_rows, int q_cols,\n        float* _Qb, int qb_rows,\n        int32_t* _out_keys, float* _out_scores,\n        int32_t* _pool, int pool_size,\n        int k, int num_threads)\n{\n    Map<Matrix<float, Dynamic, Dynamic, RowMajor>> P(_P, p_rows, p_cols);\n    Map<Matrix<float, Dynamic, Dynamic, RowMajor>> Q(_Q, q_rows, q_cols);\n    Map<Matrix<float, Dynamic, Dynamic, RowMajor>> Qb(_Qb, qb_rows, 1);\n    Map<Matrix<int, Dynamic, Dynamic, RowMajor>> out_keys(_out_keys, num_queries, k);\n    Map<Matrix<float , Dynamic, Dynamic, RowMajor>> out_scores(_out_scores, num_queries, k);\n\n    unordered_set<int32_t> pool;\n    for (int i=0; i < pool_size; ++i)\n        pool.insert(_pool[i]);\n\n    int correct_k = min(q_rows, k);\n    if (pool_size)\n        correct_k = min(pool_size, correct_k);\n\n    omp_set_num_threads(num_threads);\n    n2::Hnsw hnsws[num_threads];\n    for (int i=0; i < num_threads; ++i) {\n        hnsws[i].LoadModel(index_path.c_str(), use_mmap);\n    }\n\n    #pragma omp parallel\n    {\n        int worker_id = omp_get_thread_num();\n        #pragma omp for schedule(guided)\n        for (int i=0; i < num_queries; ++i)\n        {\n            auto& hnsw = hnsws[worker_id];\n            int q = indexes[i];\n            vector<pair<int, float>> result;\n            hnsw.SearchById(q, correct_k, ef_search, result);\n            for (int j=0; j < (int)result.size(); ++j) {\n                out_keys(i, j) = result[j].first;\n                out_scores(i, j) = result[j].second;\n            }\n            for (int j=(int)result.size(); j < k; ++j) {\n                out_keys(i, j) = -1;\n                out_scores(i, j) = 0.0;\n            }\n        }\n    }\n    for (int i=0; i < num_threads; ++i) {\n        hnsws[i].UnloadModel();\n    }\n}\n\n}\n", "meta": {"hexsha": "a01af5009f81633c33096ab3a4be17714495a7d0", "size": 6131, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "buffalo/parallel/_core.hpp", "max_stars_repo_name": "awesome-archive/buffalo", "max_stars_repo_head_hexsha": "1bcb76b61161e74324ca71ed05ce0576598798b5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 577.0, "max_stars_repo_stars_event_min_datetime": "2019-08-28T19:56:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T19:44:58.000Z", "max_issues_repo_path": "buffalo/parallel/_core.hpp", "max_issues_repo_name": "awesome-archive/buffalo", "max_issues_repo_head_hexsha": "1bcb76b61161e74324ca71ed05ce0576598798b5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 35.0, "max_issues_repo_issues_event_min_datetime": "2019-08-28T23:48:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T02:13:47.000Z", "max_forks_repo_path": "buffalo/parallel/_core.hpp", "max_forks_repo_name": "awesome-archive/buffalo", "max_forks_repo_head_hexsha": "1bcb76b61161e74324ca71ed05ce0576598798b5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 128.0, "max_forks_repo_forks_event_min_datetime": "2019-08-28T21:41:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T17:46:17.000Z", "avg_line_length": 30.0539215686, "max_line_length": 106, "alphanum_fraction": 0.5483607894, "num_tokens": 1752, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.6370307875894138, "lm_q1q2_score": 0.4951639493300431}}
{"text": "#include <boost/numeric/odeint/stepper/adams_bashforth.hpp>\n", "meta": {"hexsha": "c8719adcc225f2aab320d7c7408e3b44d42af68b", "size": 60, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_numeric_odeint_stepper_adams_bashforth.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_numeric_odeint_stepper_adams_bashforth.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_numeric_odeint_stepper_adams_bashforth.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 30.0, "max_line_length": 59, "alphanum_fraction": 0.8333333333, "num_tokens": 18, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.4951639439736935}}
{"text": "#include <iostream>\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/core/optimization_algorithm_gauss_newton.h>\n#include <g2o/core/optimization_algorithm_dogleg.h>\n#include <g2o/core/robust_kernel_impl.h>\n#include <opencv2/core/core.hpp>\n#include <g2o/solvers/dense/linear_solver_dense.h>\n#include <Eigen/Core>\n#include <cmath>\n#include <chrono>\n#include <vector>\n\n\nusing namespace std;\n\n// \u66f2\u7ebf\u6a21\u578b\u7684\u9876\u70b9\uff0c\u6a21\u677f\u53c2\u6570\uff1a\u4f18\u5316\u53d8\u91cf\u7ef4\u5ea6\u548c\u6570\u636e\u7c7b\u578b\nclass CurveFittingVertex: public g2o::BaseVertex<6, Eigen::Matrix<double,6,1>>\n{\npublic:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    virtual void setToOriginImpl()\n    {\n\t\t_estimate << 1.0, 1.0, 1.0, 0.0, 0.0, 0.0;\n\t}\n    \n    virtual void oplusImpl( const double* update )\n    {\n        _estimate += Eigen::Matrix<double,6,1> (update);\n    }\n    // \u5b58\u76d8\u548c\u8bfb\u76d8\uff1a\u7559\u7a7a\n    virtual bool read( istream& in ) { return false; }\n    virtual bool write( ostream& out ) const { return false; }\n};\n\n// \u8bef\u5dee\u6a21\u578b \u6a21\u677f\u53c2\u6570\uff1a\u89c2\u6d4b\u503c\u7ef4\u5ea6\uff0c\u7c7b\u578b\uff0c\u8fde\u63a5\u9876\u70b9\u7c7b\u578b\nclass CurveFittingEdge: public g2o::BaseUnaryEdge<1,double,CurveFittingVertex>\n{\npublic:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    CurveFittingEdge( double ax, double ay, double az ): BaseUnaryEdge(), ax_(ax), ay_(ay), az_(az) {}\n    // \u8ba1\u7b97\u66f2\u7ebf\u6a21\u578b\u8bef\u5dee\n    virtual void computeError()\n    {\n    \t// para = [sx, sy, sz, bx, by, bz]\n        const CurveFittingVertex* v = static_cast<const CurveFittingVertex*> (_vertices[0]);\n        const Eigen::Matrix<double,6,1> para = v->estimate();\n        //cout<<para(0,0)<<\", \"<<para(1,0)<<\", \"<<para(2,0)<<\", \"<<para(3,0)<<\", \"<<para(4,0)<<\", \"<<para(5,0)<<endl;\n        _error(0,0) = _measurement - ( (para(0,0) * (ax_ + para(3,0))) * (para(0,0) * (ax_ + para(3,0))) +\n\t\t\t\t\t\t\t\t\t   (para(1,0) * (ay_ + para(4,0))) * (para(1,0) * (ay_ + para(4,0))) +\n\t\t\t\t\t\t\t\t\t   (para(2,0) * (az_ + para(5,0))) * (para(2,0) * (az_ + para(5,0)))\n   \t\t\t\t\t\t\t\t\t );\n\t\t// cout << _error(0,0) << endl;\n    }\n    \n    virtual void linearizeOplus()\n    {\n        const CurveFittingVertex* v = static_cast<const CurveFittingVertex*> (_vertices[0]);\n        const Eigen::Matrix<double,6,1> para = v->estimate();\n        _jacobianOplusXi[0] = -2.0*para(0,0)*( (ax_ + para(3,0)) * (ax_ + para(3,0)) );\n        _jacobianOplusXi[1] = -2.0*para(1,0)*( (ay_ + para(4,0)) * (ay_ + para(4,0)) );\n        _jacobianOplusXi[2] = -2.0*para(2,0)*( (az_ + para(5,0)) * (az_ + para(5,0)) );\n        _jacobianOplusXi[3] = -2.0*para(0,0)*para(0,0)*(ax_ + para(3,0));\n        _jacobianOplusXi[4] = -2.0*para(1,0)*para(1,0)*(ay_ + para(4,0));\n        _jacobianOplusXi[5] = -2.0*para(2,0)*para(2,0)*(az_ + para(5,0));\n        \n    }\n    \n    \n    virtual bool read( istream& in ) { return false; }\n    virtual bool write( ostream& out ) const { return false; }\npublic:\n    const double ax_, ay_, az_;  // acc \u503c\uff0c 9.8^2 \u503c\u4e3a _measurement\n};\n\nint main( int argc, char** argv )\n{\n\tvector<vector<double>> matrix;\n\t//readfile\n\tifstream file;\n\tcout << \"----- Fetching .csv file ...\" << endl;\n\tfile.open(\"../imu_data.csv\");\n\tif(!file.is_open()){\n\t\tcerr << \"ERROR: failed to open the file!\" << endl;\n\t\treturn 1;\n\t}\n\tstring line;\n\twhile (getline( file, line,'\\n'))  //\u8b80\u6a94\u8b80\u5230\u8df3\u884c\u5b57\u5143\n\t{\n\t\tvector<double> row_data;\n\t\tstringstream templine(line); // string \u8f49\u63db\u6210 stream\n\t\tstring data;\n\t\t while (getline( templine, data,',')) //\u8b80\u6a94\u8b80\u5230\u9017\u865f\n\t\t {\n\t\t\t row_data.push_back(stof(data));  //string \u8f49\u63db\u6210\u6578\u5b57\n\t\t }\n\t\tmatrix.push_back(row_data);\n\t}\n\tfile.close();\n\tcout << \"----- Finish!\" << endl << endl;\n\tcout << \"Whether to show the raw data on the SCREEN? 'y' or 'n': \";\n\tchar resp;\n\tcin >> resp;\n\tif(resp == 'y'){\n\t\tcout << \"row_data: \" << endl;\n\t\tfor(int i=0; i<matrix.size(); i++){\n\t\t\tfor(int j=0; j<matrix[i].size(); j++){\n\t\t\t\tcout << matrix[i][j] << \"  \";\n\t\t\t}\n\t\t\tcout << endl;\n\t\t}\n\t}\n\n\t// number of rows of the raw data\n\tint N = matrix.size();\n    \n    // \u6784\u5efa\u56fe\u4f18\u5316\uff0c\u5148\u8bbe\u5b9ag2o\n    typedef g2o::BlockSolver< g2o::BlockSolverTraits<6,1> > Block;  // \u6bcf\u4e2a\u8bef\u5dee\u9879\u4f18\u5316\u53d8\u91cf\u7ef4\u5ea6\u4e3a6\uff0c\u8bef\u5dee\u503c\u7ef4\u5ea6\u4e3a1\n    Block::LinearSolverType* linearSolver = new g2o::LinearSolverDense<Block::PoseMatrixType>(); // \u7ebf\u6027\u65b9\u7a0b\u6c42\u89e3\u5668\n    Block* solver_ptr = new Block( linearSolver );      // \u77e9\u9635\u5757\u6c42\u89e3\u5668\n    // \u68af\u5ea6\u4e0b\u964d\u65b9\u6cd5\uff0c\u4eceGN, LM, DogLeg \u4e2d\u9009\n    g2o::OptimizationAlgorithmLevenberg* solver = new g2o::OptimizationAlgorithmLevenberg( solver_ptr );\n    // g2o::OptimizationAlgorithmGaussNewton* solver = new g2o::OptimizationAlgorithmGaussNewton( solver_ptr );\n    // g2o::OptimizationAlgorithmDogleg* solver = new g2o::OptimizationAlgorithmDogleg( solver_ptr );\n    g2o::SparseOptimizer optimizer;     // \u56fe\u6a21\u578b\n    optimizer.setAlgorithm( solver );   // \u8bbe\u7f6e\u6c42\u89e3\u5668\n    optimizer.setVerbose( true );       // \u6253\u5f00\u8c03\u8bd5\u8f93\u51fa\n    \n    // \u5f80\u56fe\u4e2d\u589e\u52a0\u9876\u70b9\n    CurveFittingVertex* v = new CurveFittingVertex();\n\tEigen::Matrix<double,6,1> para_initial;\n\t//Vector6d << 1.05, 0.95, 0.98, 1.5, -1.2, 0.7;\n    para_initial << 1.0, 1.0, 1.0, 0.0, 0.0, 0.0;\n\tv->setEstimate( para_initial );\n    v->setId(0);\n    optimizer.addVertex( v );\n    \n    // \u5f80\u56fe\u4e2d\u589e\u52a0\u8fb9\n    for ( int i=0; i<N; i++ )\n    {\n        CurveFittingEdge* edge = new CurveFittingEdge( matrix[i][0], matrix[i][1], matrix[i][2] );\n        edge->setId(i);\n        edge->setVertex( 0, v );                // \u8bbe\u7f6e\u8fde\u63a5\u7684\u9876\u70b9\n        edge->setMeasurement( 9.8*9.8 );      // \u89c2\u6d4b\u6570\u503c\n        edge->setInformation( Eigen::Matrix<double,1,1>::Identity() ); // \u4fe1\u606f\u77e9\u9635\uff1a\u534f\u65b9\u5dee\u77e9\u9635\u4e4b\u9006\n        g2o::RobustKernelHuber* rk = new g2o::RobustKernelHuber;  // Huber function (kill outlier data)\n        // rk->setDelta(1.0);\n        cout << rk->delta() << endl;\n        edge->setRobustKernel(rk);\n        optimizer.addEdge( edge );\n    }\n    \n    // \u6267\u884c\u4f18\u5316\n    cout<<\"start optimization\"<<endl;\n    chrono::steady_clock::time_point t1 = chrono::steady_clock::now();\n    optimizer.initializeOptimization();\n    optimizer.optimize(50);\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<<\"solve time cost = \"<<time_used.count()<<\" seconds. \"<<endl;\n    \n    // \u8f93\u51fa\u4f18\u5316\u503c\n    Eigen::Matrix<double,6,1> para_estimate = v->estimate();\n    cout << \"----- Output the result:\" << endl;\n\tcout << \"\tThe mathematical model: \" << endl;\n\tcout << \"\tax_cal = sx * (ax_raw + ba)\" << endl\n\t\t << \"\tay_cal = sy * (ay_raw + by)\" << endl\n\t\t << \"\taz_cal = sz * (az_raw + bz)\" << endl << endl;\n\tcout << \"\tsx = \" << para_estimate(0,0) << endl;\n\tcout << \"\tsy = \" << para_estimate(1,0) << endl;\n\tcout << \"\tsz = \" << para_estimate(2,0) << endl;\n\tcout << \"\tbx = \" << para_estimate(3,0) << endl;\n\tcout << \"\tby = \" << para_estimate(4,0) << endl;\n\tcout << \"\tbz = \" << para_estimate(5,0) << endl;\n    \n    return 0;\n}\n\n\n\n\n\n\n", "meta": {"hexsha": "3d572207f3ce48a10cba743cead6524ea69e2fd8", "size": 6630, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "g2o_imu.cpp", "max_stars_repo_name": "JingJie-Huang/IMU-Calibration", "max_stars_repo_head_hexsha": "a599896d0d6f93d142608e2576ae3ef87770576e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-28T08:58:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T08:58:33.000Z", "max_issues_repo_path": "g2o_imu.cpp", "max_issues_repo_name": "JingJie-Huang/IMU-Calibration", "max_issues_repo_head_hexsha": "a599896d0d6f93d142608e2576ae3ef87770576e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "g2o_imu.cpp", "max_forks_repo_name": "JingJie-Huang/IMU-Calibration", "max_forks_repo_head_hexsha": "a599896d0d6f93d142608e2576ae3ef87770576e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-10T06:13:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-10T06:13:48.000Z", "avg_line_length": 35.6451612903, "max_line_length": 117, "alphanum_fraction": 0.6043740573, "num_tokens": 2350, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998560157665, "lm_q2_score": 0.6370307875894138, "lm_q1q2_score": 0.4951639394708616}}
{"text": "#ifndef SKYLARK_CONDEST_HPP\n#define SKYLARK_CONDEST_HPP\n\n#include <boost/math/special_functions/erf.hpp>\n\n#include \"../base/base.hpp\"\n#include \"../utility/typer.hpp\"\n#include \"../utility/external/print.hpp\"\n\nextern \"C\" {\n\nvoid EL_BLAS(dbdsqr)(const char *, const El::Int *, const El::Int *,\n    const El::Int *, const El::Int *, double *, double *, double *,\n    const El::Int *, double *, const El::Int *,\n    double *, const El::Int *, double *, El::Int *);\n\n}\n\nnamespace skylark {\nnamespace nla {\n\nstruct condest_params_t : public base::params_t {\n\n    int iter_lim;\n\n    // See paper for meaning of these.\n    int powerits;\n    double c1, c2, c3, c4, c1t;\n\n    condest_params_t(int iter_lim = 1000,\n        bool am_i_printing = 0,\n        int log_level = 0,\n        std::ostream &log_stream = std::cout,\n        std::string prefix = \"\",\n        int debug_level = 0) :\n        base::params_t(am_i_printing, log_level, log_stream, prefix, debug_level),\n        iter_lim(iter_lim) {\n\n        const double em = std::numeric_limits<double>::epsilon();\n        c1 = 8 * em; c2 = 1e-3; c3 = 64.0 / em;\n        c4 = std::sqrt(em); c1t = 4 * em;\n        powerits = 300;\n  }\n\n};\n\n/**\n * Estimates the condition number (with certificates) of a matrix\n * using an iterative algorith. Based on the following paper:\n *\n * Haim Avron, Alex Druinsky and Sivan Toledo\n * Spectral Condition-Number Estimation of Large Sparse Matrices\n *\n * \\param A Input matrix\n * \\param cond Output condition number estimation\n * \\param sigma_max,v_max,u_max Estiamte of largest singular value and\n *                               right, left certificates. That is,\n *                               sigma_max * u_max = A * v_max / sigma_max,\n *                               ||v_max|| = ||u_max|| = 1,\n * \\param sigma_min Best estimate for smallest singular value.\n * \\param sigma_min_c,v_min,u_min Estimate of smallest singular value with\n *                                certificate\n * \\param context Skylark context\n * \\param params Parameters.\n */\ntemplate<typename MatrixType, typename LeftType, typename RightType>\nint CondEst(const MatrixType& A, double &cond,\n    double &sigma_max, RightType &v_max, LeftType &u_max,\n    double &sigma_min, double &sigma_min_c, RightType &v_min, LeftType &u_min,\n    base::context_t &context, condest_params_t params = condest_params_t()) {\n\n    typedef typename utility::typer_t<MatrixType>::value_type value_t;\n    typedef typename utility::typer_t<MatrixType>::index_type index_t;\n\n    typedef MatrixType matrix_type;\n    typedef RightType right_type;        // Also serves as \"long\" vector type.\n    typedef LeftType left_type;        // Also serves as \"short\" vector type.\n\n    typedef utility::print_t<right_type> rhs_print_t;\n    typedef utility::print_t<left_type> sol_print_t;\n\n    bool log_lev1 = params.am_i_printing && params.log_level >= 1;\n    bool log_lev2 = params.am_i_printing && params.log_level >= 2;\n\n    /** Throughout, we will use m, n to denote the problem dimensions */\n    index_t m = base::Height(A);\n    index_t n = base::Width(A);\n\n    double c1 = params.c1, c2 = params.c2, c3 = params.c3;\n    double c4 = params.c4, c1t = params.c1t;\n\n    /** Estimate the largest singular vector using power-iteration */\n    base::GaussianMatrix(v_max, n, 1, context);\n    PowerIteration(El::NORMAL, El::NORMAL, El::NORMAL,\n        A, v_max, u_max, params.powerits, true);\n    sigma_max = El::Nrm2(u_max);\n    El::Scale(1.0 / sigma_max, u_max);\n\n    sigma_min = sigma_max;\n    u_min = u_max;\n    v_min = v_max;\n\n    if (log_lev2)\n        params.log_stream << params.prefix\n                          << \"CondEst: sigma_max = \" << sigma_max\n                          << std::endl;\n\n    /** Generate xhat, and figure out tau */\n    right_type xhat;\n    base::GaussianMatrix(xhat, n, 1, context);\n    double nrm_xhat = El::Nrm2(xhat);\n    double tau = std::sqrt(2) * boost::math::erf_inv(c2) / nrm_xhat;\n    El::Scale(1.0 / nrm_xhat, xhat);\n\n    if (log_lev2)\n        params.log_stream << params.prefix\n                          << \"CondEst: tau = \" << tau << std::endl;\n\n    /** Generate b, and iteration x */\n    left_type b(m, 1);\n    base::Gemm(El::NORMAL, El::NORMAL, 1.0, A, xhat, b);\n    right_type x(n, 1);\n    double nrm_b = El::Nrm2(b);\n\n    /** Initialize everything */\n    right_type u(b);\n    double beta, i_beta;\n    beta = El::Nrm2(u);\n    El::Scale(1.0 / beta, u);\n    rhs_print_t::apply(u, \"u Init\", params.am_i_printing, params.debug_level);\n\n    left_type v(n, 1);\n    base::Gemm(El::ADJOINT, El::NORMAL, 1.0, A, u, v);\n    double alpha;\n    alpha = El::Nrm2(v);\n    El::Scale(1.0 / alpha, v);\n    sol_print_t::apply(v, \"v Init\", params.am_i_printing, params.debug_level);\n\n    /* Create w=v and x=0 */\n    El::Zero(x);\n    left_type w(v);\n    double phibar = beta, rhobar = alpha, nrm_r;\n\n    /* Reset the iteration limit if none was specified */\n    if (0>params.iter_lim) params.iter_lim = std::max(20, 2*std::min(m,n));\n\n    /* More varaibles */\n    left_type Au(n, 1);\n    double minus_beta, rho;\n    double cs, sn, theta, phi;\n    double phi_by_rho, minus_theta_by_rho;\n    right_type d(n, 1);\n    left_type Ad(m, 1);\n    std::vector<double> Rdiag, Rsub;\n\n    /** Main iteration loop */\n    index_t T = params.iter_lim;\n    int retval = -6;\n    for (index_t itn=0; itn < T; ++itn) {\n\n        /** 1. Update u and beta */\n        alpha = -alpha;\n        El::Scale(alpha, u);\n        base::Gemm(El::NORMAL, El::NORMAL, 1.0, A, v, 1.0, u);\n        beta = El::Nrm2(u);\n        El::Scale(1.0 / beta, u);\n\n        /** 2. Update v */\n        minus_beta = -beta;\n        El::Scale(minus_beta, v);\n        base::Gemm(El::ADJOINT, El::NORMAL, 1.0, A, u, Au);\n        base::Axpy(1.0, Au, v);\n        alpha = El::Nrm2(v);\n        El::Scale(1.0 / alpha, v);\n\n       /** 3. Update variables, store parts of R */\n        rho = sqrt((rhobar*rhobar) + (beta*beta));\n\n        Rdiag.push_back(rho);\n        if (itn > 0)\n            Rsub.push_back(theta);\n\n        cs = rhobar/rho;\n        sn =  beta/rho;\n        theta = sn*alpha;\n        rhobar = -cs*alpha;\n        phi = cs*phibar;\n        phibar =  sn*phibar;\n\n        /** 4. Update x and w */\n        phi_by_rho = phi/rho;\n        base::Axpy(phi_by_rho, w, x);\n        sol_print_t::apply(x, \"x\", params.am_i_printing, params.debug_level);\n\n        minus_theta_by_rho = -theta/rho;\n        El::Scale(minus_theta_by_rho, w);\n        base::Axpy(1.0, v, w);\n        sol_print_t::apply(w, \"w\", params.am_i_printing, params.debug_level);\n\n        /** 5. Compute forward error */\n        d = xhat;\n        El::Axpy(-1.0, x, d);\n        double nrm_d = El::Nrm2(d);\n        if (nrm_d == 0.0) {\n            cond = 1.0;\n            sigma_min = sigma_max;\n            u_min = u_max;\n            v_min = v_max;\n            if (log_lev1)\n                params.log_stream << params.prefix\n                                  << \"CondEst: Detected condition number 1\"\n                                  << std::endl;\n            return -1;\n        }\n\n        /** 6. Compute current estimate of sigma_min using d, and compare it */\n        base::Gemm(El::NORMAL, El::NORMAL, 1.0, A, d, Ad);\n        double nrm_ad = El::Nrm2(Ad);\n        if (nrm_ad <= sigma_min * nrm_d) {\n            sigma_min = nrm_ad / nrm_d;\n            v_min = d;\n            u_min = Ad;\n            El::Scale(1.0 / nrm_ad, u_min);\n        }\n\n        /** 7. Check if parameters need to be tuned */\n        if (c1 != c1t && sigma_min / sigma_max <= c4 ) {\n            if (log_lev1)\n                params.log_stream\n                    << params.prefix\n                    << \"CondEst: Highly ill-conditioned, C1 adjusted (C4)\"\n                    << std::endl;\n            c1 = c1t;\n        }\n\n        /** 8. Test various stopping criteria */\n        double nrm_x = El::Nrm2(x);\n        if (T == params.iter_lim &&\n            nrm_ad <= c1 * (sigma_max * nrm_x + nrm_b)) {\n            if (log_lev1)\n                params.log_stream << params.prefix\n                                  << \"CondEst: Convergence detected (C1)\"\n                                  << std::endl;\n            T = 1.25 * itn + 1;\n            retval = -2;\n        }\n\n        if (T == params.iter_lim && nrm_d <= tau) {\n            if (log_lev1)\n                params.log_stream << params.prefix\n                                  << \"CondEst: Convergence detected (C2)\"\n                                  << std::endl;\n            T = 1.25 * itn + 1;\n            retval = -3;\n        }\n\n        if (T == params.iter_lim && sigma_max / sigma_min >= c3) {\n            if (log_lev1)\n                params.log_stream << params.prefix\n                                  << \"CondEst: Singular?, stopping (C3)\"\n                                  << std::endl;\n            T = 1.25 * itn + 1;\n            retval = -4;\n        }\n\n        if (log_lev2)\n            params.log_stream << params.prefix\n                              << \"CondEst: Iteration \" << itn\n                              << \" sigma_min = \" << sigma_min\n                              << \" cond = \" << sigma_max / sigma_min\n                              << \" nrm_d = \" << nrm_d\n                              << std::endl;\n    }\n\n\n\n    if (log_lev1 && retval == -6)\n        params.log_stream << params.prefix\n                          << \"CondEst: No convergence within iteration limit.\"\n                          << std::endl;\n\n    /** Estimate condition number using R */\n    El::Int N = Rdiag.size(), izero = 0, ione = 1, info = 0;\n    std::vector<double> workspace(4 * N);\n    EL_BLAS(dbdsqr)(\"Upper\", &N, &izero, &izero, &izero, &Rdiag[0], &Rsub[0],\n        nullptr, &ione, nullptr, &ione, nullptr, &ione, &workspace[0], &info);\n    double sigma_min_R = Rdiag[Rdiag.size() - 1];\n\n    if (log_lev2)\n        params.log_stream << params.prefix\n                          << \"CondEst: R sigma_min = \" << sigma_min_R\n                          << std::endl;\n\n    sigma_min_c = sigma_min;\n    if (sigma_min_R < sigma_min)\n        sigma_min = sigma_min_R;\n\n    cond = sigma_max / sigma_min;\n\n    return retval;\n}\n\n} } /** namespace skylark::nla */\n\n#endif // SKYLARK_NLA_HPP\n", "meta": {"hexsha": "8e924f684862e0d7e9371776d135a6f090958ba0", "size": 10136, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "nla/CondEst.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": "nla/CondEst.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": "nla/CondEst.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": 33.1241830065, "max_line_length": 82, "alphanum_fraction": 0.5403512234, "num_tokens": 2802, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.6370307806984445, "lm_q1q2_score": 0.49516393740090603}}
{"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#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MAIN\n\n#include <limits>\n#include <boost/test/tools/floating_point_comparison.hpp>\n#include <boost/test/unit_test.hpp>\n\n#include <Eigen/Core>\n\n#include \"tudat/basics/testMacros.h\"\n#include \"tudat/math/basic/linearAlgebra.h\"\n#include \"tudat/math/interpolators/lagrangeInterpolator.h\"\n#include \"tudat/astro/basic_astro/timeConversions.h\"\n#include \"tudat/astro/ephemerides/simpleRotationalEphemeris.h\"\n#include \"tudat/astro/ephemerides/tabulatedRotationalEphemeris.h\"\n#include \"tudat/astro/basic_astro/physicalConstants.h\"\n#include \"tudat/interface/spice/spiceInterface.h\"\n#include \"tudat/io/basicInputOutput.h\"\n\nnamespace tudat\n{\nnamespace unit_tests\n{\n\nusing namespace ephemerides;\n\nBOOST_AUTO_TEST_SUITE( test_rotational_ephemeris )\n\n// Test functions to calculate rotation matrix derivative from angular velocity vector and vice\n// versa.\nBOOST_AUTO_TEST_CASE( testRotationalEphemeris )\n{\n    // Define names of frames.\n    const std::string baseFrame = \"J2000\";\n    const std::string targetFrame = \"IAU_VENUS\";\n\n    // Set time at which rotational ephemeris it to be called for subsequent tests.\n\n    // Test rotation to target frame at specified time.\n    {\n\n        // The following code block can be used to retrieve the benchmark data from Spice.\n        //        spice_interface::loadSpiceKernelInTudat( input_output::getSpiceKernelPath( ) +\n        // \"pck00010.tpc\" );\n        //        const double secondsSinceJ2000 = 1.0E6;\n        //        Eigen::Quaterniond spiceRotationMatrixToFrame =\n        //                spice_interface::computeRotationQuaternionBetweenFrames(\n        // baseFrame, targetFrame, secondsSinceJ2000 );\n        //        Eigen::Matrix3d spiceRotationMatrixDerivativeToFrame =\n        //                spice_interface::computeRotationMatrixDerivativeBetweenFrames(\n        // baseFrame, targetFrame, secondsSinceJ2000 );\n        //        Eigen::Vector3d spiceRotationalVelocityVectorOfTargetFrameExpressedInBaseFrame =\n        //                spice_interface::getAngularVelocityVectorOfFrameInOriginalFrame(\n        // baseFrame, targetFrame, secondsSinceJ2000 );\n\n        // Set rotational characteristics at given time, as calculated with Spice\n        // (see above commented lines).\n        Eigen::Matrix3d spiceRotationMatrixDerivativeToFrame;\n        spiceRotationMatrixDerivativeToFrame <<\n                                                1.690407961416589e-07, 2.288121921543265e-07, 9.283170431475241e-08,\n                -2.468632444964533e-07, 1.540516111965609e-07, 6.981529179974795e-08,\n                0.0,           0.0,          0.0;\n\n        Eigen::Matrix3d spiceRotationMatrixToFrame;\n        spiceRotationMatrixToFrame << -0.8249537745726603, 0.5148010526833556, 0.2333048348715243,\n                -0.5648910720519699, -0.7646317780963481, -0.3102197940834743,\n                0.01869081416890206, -0.3877088083617987, 0.9215923900425707;\n\n        Eigen::Vector3d spiceRotationalVelocityVectorOfTargetFrameExpressedInBaseFrame;\n        spiceRotationalVelocityVectorOfTargetFrameExpressedInBaseFrame << -5.593131603532092e-09,\n                1.160198999048488e-07,\n                -2.75781861386115e-07;\n\n        // Calculate rotational velocity from SPICE rotation matrix derivative.\n        Eigen::Vector3d manualRotationalVelocityVectorOfTargetFrameExpressedInBaseFrame =\n                getRotationalVelocityVectorInBaseFrameFromMatrices(\n                    spiceRotationMatrixToFrame, spiceRotationMatrixDerivativeToFrame.transpose( ) );\n\n        // Calculate rotation matrix derivative from SPICE rotational velocity vector.\n        Eigen::Matrix3d rotationMatrixDerivative = getDerivativeOfRotationMatrixToFrame(\n                    spiceRotationMatrixToFrame, spiceRotationalVelocityVectorOfTargetFrameExpressedInBaseFrame );\n\n        // Calculate rotational velocity from previously calculated rotation matrix derivative.\n        Eigen::Matrix3d backCalculatedRotationMatrixDerivative =\n                getDerivativeOfRotationMatrixToFrame(\n                    spiceRotationMatrixToFrame,\n                    manualRotationalVelocityVectorOfTargetFrameExpressedInBaseFrame );\n\n        // Calculate rotation matrix derivative from previously calculated rotational velocity\n        // vector.\n        Eigen::Vector3d backCalculatedRotationalVelocityVector =\n                getRotationalVelocityVectorInBaseFrameFromMatrices(\n                    spiceRotationMatrixToFrame, rotationMatrixDerivative.transpose( ) );\n\n        // Check equivalence of results.\n        for( int i = 0; i < 3; i++ )\n        {\n            BOOST_CHECK_SMALL( manualRotationalVelocityVectorOfTargetFrameExpressedInBaseFrame( i ) -\n                               backCalculatedRotationalVelocityVector( i ), 2.0E-22 );\n            BOOST_CHECK_SMALL( manualRotationalVelocityVectorOfTargetFrameExpressedInBaseFrame( i ) -\n                               spiceRotationalVelocityVectorOfTargetFrameExpressedInBaseFrame( i ), 2.0E-22 );\n\n            for( int j = 0; j < 3; j++ )\n            {\n                BOOST_CHECK_SMALL( rotationMatrixDerivative( i, j ) -\n                                   backCalculatedRotationMatrixDerivative( i, j ), 2.0E-22 );\n                BOOST_CHECK_SMALL( rotationMatrixDerivative( i, j ) -\n                                   spiceRotationMatrixDerivativeToFrame( i, j ), 2.0E-22 );\n            }\n        }\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END( )\n\n} // namespace unit_tests\n} // namespace tudat\n", "meta": {"hexsha": "1d872ee886e53690e456c7e538fb2e8daad5f38a", "size": 5945, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/src/astro/ephemerides/unitTestRotationalEphemeris.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": "tests/src/astro/ephemerides/unitTestRotationalEphemeris.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": "tests/src/astro/ephemerides/unitTestRotationalEphemeris.cpp", "max_forks_repo_name": "kimonito98/tudat", "max_forks_repo_head_hexsha": "c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.4453125, "max_line_length": 116, "alphanum_fraction": 0.6918418839, "num_tokens": 1406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359876, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.495163422806201}}
{"text": "#include <NTL/ZZ.h>\n#include <cstdint>\n#include <cmath>\n\n#define NUM_BITS_REAL_MANTISSA 1024\n#define IGNORE_DECODING_COST 0\n// #define EXPLORE_REPRS\n\n#include \"binomials.hpp\"\n#include \"isd_cost_estimate.hpp\"\n#include <cmath>\n\nint main(int argc, char* argv[]){\n  if(argc != 6){\n     std::cout << \"Work factor computation for ISD\" << std::endl << \" Usage \" \n               << argv[0] << \" <codeword_size> <code_dimension> <number_of_errors> <qc_block_size> <is_kra>\" << std::endl << \n               \"<qc_block_size> = 1 implies a non QC code \" << std::endl << \n               \"<is_kra> = the attack is a key recovery attack on a QC-[L|M]DPC \" << std::endl;\n    return -1;\n  }\n\n  InitBinomials();\n  NTL::RR::SetPrecision(NUM_BITS_REAL_MANTISSA);\n  pi = NTL::ComputePi_RR();\n  uint32_t n = atoi(argv[1]);\n  uint32_t k = atoi(argv[2]);\n  uint32_t t = atoi(argv[3]);\n  uint32_t qc_block_size = atoi(argv[4]);\n  uint32_t is_kra = atoi(argv[5]);\n  \n  /* reduce by a factor matching the QC block size */\n  std::cout << \"Minimum classic cost :\" << c_isd_log_cost(n,k,t,qc_block_size,is_kra) << \" Minimum quantum cost :\" << q_isd_log_cost(n,k,t,qc_block_size,is_kra);\n  if(qc_block_size !=1) std::cout << \" (including qc_effects) \";\n  std::cout << std::endl;\n  return 0;\n}\n", "meta": {"hexsha": "0591c29fed3aad10c3dd68f6601067a043ba8212", "size": 1262, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "work_factor_computation.cpp", "max_stars_repo_name": "alexrow/LEDAtools", "max_stars_repo_head_hexsha": "f847707833650706519cc57f5956b8e1a17a157c", "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": "work_factor_computation.cpp", "max_issues_repo_name": "alexrow/LEDAtools", "max_issues_repo_head_hexsha": "f847707833650706519cc57f5956b8e1a17a157c", "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": "work_factor_computation.cpp", "max_forks_repo_name": "alexrow/LEDAtools", "max_forks_repo_head_hexsha": "f847707833650706519cc57f5956b8e1a17a157c", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-12T09:12:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-12T09:12:30.000Z", "avg_line_length": 34.1081081081, "max_line_length": 161, "alphanum_fraction": 0.6434231379, "num_tokens": 388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034369, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.49516318725269387}}
{"text": "#include <iostream>\n#include <boost/numeric/mtl/mtl.hpp>\n\nint main(int, char**)\n{\n    using namespace mtl;\n    \n    const unsigned n= 10;\n    compressed2D<double>                           A(n, n);\n    dense2D<float, mat::parameters<col_major> > B(n, n);\n    morton_dense<double, 0x55555555>               C(n, n);\n    morton_dense<double, 0x555555f0>               D(n, n);\n\n    mat::hessian_setup(B, 1.0);\n    mat::hessian_setup(C, 2.0);\n    mat::hessian_setup(D, 3.0);\n    \n    std::cout << \"one_norm(B) is \" << one_norm(B)<< \"\\n\";\n    std::cout << \"infinity_norm(B) is \" << infinity_norm(B)<< \"\\n\";\n    std::cout << \"frobenius_norm(B) is \" << frobenius_norm(B)<< \"\\n\";\n    \n    return 0;\n}\n", "meta": {"hexsha": "15c18ef74b7646feb0774d0412c46d46ed4bc009", "size": 694, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/examples/matrix_functions.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/matrix_functions.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/matrix_functions.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.9166666667, "max_line_length": 69, "alphanum_fraction": 0.5475504323, "num_tokens": 222, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4951631872526938}}
{"text": "#ifndef HEADER_Bezier\n#define HEADER_Bezier\n\n#include <armadillo>\n#include \"ControlPoint.hpp\"\n#include \"Element.hpp\"\n\n\n\n\n#include <boost/math/special_functions/factorials.hpp>\n#include <memory>\n#include <iostream>\n#include <RigidBodyKinematics.hpp>\n\n#include <set>\n#include <map>\n\n\nclass ControlPoint;\n\ntemplate <class PointType> \nclass ShapeModel;\n\nclass Bezier : public Element{\n\npublic:\n\n\t/**\n\tConstructor\n\t@param vertices pointer to vector storing the vertices owned by this facet\n\t*/\n\tBezier(std::vector<int> vertices,ShapeModel<ControlPoint> * owning_shape);\n\n\t/**\n\tGet neighbors\n\t@param if false, only return neighbors sharing an edge. Else, returns all neighbords\n\t@return Pointer to neighboring facets, plus the calling facet\n\t*/\n\tvirtual std::set< int > get_neighbors(bool all_neighbors) const;\n\n\n\tstd::set < int > get_neighbors(double u, double v) const;\n\n\n\t/**\n\tReturns pointer to the first vertex owned by $this that is\n\tneither $v0 and $v1. When $v0 and $v1 are on the same edge,\n\tthis method returns a pointer to the vertex of $this that is not\n\ton the edge but still owned by $this\n\t@param v0 Pointer to first vertex to exclude\n\t@param v1 Pointer to first vertex to exclude\n\t@return Pointer to the first vertex of $this that is neither $v0 and $v1\n\t*/\n\tint vertex_not_on_edge(\n\t\tint v0,\n\t\tint v1) const ;\n\n\t/**\n\tReturns patch degree\n\t@param degree\n\t*/\n\tunsigned int get_degree() const;\n\n\n\t\n\t/**\n\tEvaluates the bezier patch at the barycentric \n\tcoordinates (u,v). Note that 0<= u + v <= 1\n\t@param u first barycentric coordinate\n\t@param v second barycentric coordinate\n\t@return point at the surface of the bezier patch\n\t*/\n\tarma::vec::fixed<3> evaluate(const double u, const double v) const;\n\n\n\n\t/**\n\tEvaluates the normal of the bezier patch at the barycentric \n\tcoordinates (u,v). Note that 0<= u + v <= 1\n\t@param u first barycentric coordinate\n\t@param v second barycentric coordinate\n\t@return point at the surface of the bezier patch\n\t*/\n\tarma::vec get_normal_coordinates(const double u, const double v) const;\n\n\n\t/**\n\tGet index of the queried point\n\t@param i first index\n\t@param j second index\n\t@return local index to control point\n\t*/\n\tint get_point_local_index(unsigned int i, unsigned int j) const;\n\n\tint get_point_global_index(unsigned int i, unsigned int j) const;\n\n\n\n\t/**\n\tReturns the control point given its i and j indices (k = n - i - j)\n\t@param i first index\n\t@param j second index\n\t@return global index of control point\n\t*/\t\n\tint get_point(unsigned int i, unsigned int j) const;\n\n\t/**\n\tReturns the tuple of local indices (i,j,k) of a control point within a bezier patch\n\t@param local_index local index of considered point\n\t@return local_indices (i,j,k) \n\t*/\n\tstd::tuple<int,int,int> get_local_indices(int local_index) const;\n\n\n\t/**\n\tReturns the coordinates of a control point given its i and j indices (k = n - i - j)\n\t@param i first index\n\t@param j second index\n\t@return coordinats of contorl point\n\t*/\t\n\tconst arma::vec::fixed<3> & get_point_coordinates(unsigned int i, unsigned int j) const;\n\n\n\t/**\n\tReturns P_X\n\t@return P_X matrix\n\t*/\n\tarma::mat get_P_X() const;\n\n\n\t/**\n\tEvaluates the partial derivative of Sum( B^n_{i,j,k}C_{ijk}) with respect to (u,v) evaluated \n\tat (u,v)\n\t@param u first coordinate\n\t@param v second coordinate\n\t*/\n\tarma::mat::fixed<3,2> partial_bezier(const double u,const double v) const;\n\n\n\n\n\t/**\n\tReturns the 3x3 covariance matrix\n\ttracking the uncertainty in the location of\n\ta surface point given uncertainty in the patch's control\n\tpoints\n\t@param u mean of first coordinate\n\t@param v mean of second coordinate\n\t@param dir direction of ray\n\t@param P_X covariance on the position \n\tof the control points\n\t@return 3x3 covariance\n\t*/\n\tarma::mat covariance_surface_point_deprecated(\n\t\tconst double u,\n\t\tconst double v,\n\t\tconst arma::vec & dir,\n\t\tconst arma::mat & P_X);\n\n\n\t/**\t\n\tSets patch covariance to prescribed value\n\t@param P_X prescribed value of patch covariance\n\t*/\n\n\tvoid set_P_X(arma::mat P_X){this -> P_X = P_X;}\n\n\t/**\n\tReturns the 3x3 covariance matrix\n\ttracking the uncertainty in the location of\n\ta surface point given uncertainty in the patch's control\n\tpoints using an alternative formulation\n\t@param u mean of first coordinate\n\t@param v mean of second coordinate\n\t@param dir direction of ray\n\tof the control points\n\t@return 3x3 covariance\n\t*/\n\tarma::mat::fixed<3,3> covariance_surface_point(\n\t\tconst double u,\n\t\tconst double v,\n\t\tconst arma::vec & dir) const;\n\n\t/**\n\tReturns the 3x3 covariance matrix\n\ttracking the uncertainty in the location of\n\ta surface point given uncertainty in the patch's control\n\tpoints using an alternative formulation\n\t@param u mean of first coordinate\n\t@param v mean of second coordinate\n\t@param dir direction of ray\n\t@param P_X covariance on the position \n\tof the control points\n\t@return 3x3 covariance\n\t*/\n\tarma::mat::fixed<3,3> covariance_surface_point(\n\t\tconst double u,\n\t\tconst double v,\n\t\tconst arma::vec & dir,\n\t\tconst arma::mat & P_X) const;\n\n\t/**\n\tSets the covariance parametrization to the prescribed values\n\t@param covariance_param unique covariance parameters\n\t*/\n\tvoid set_patch_covariance(const std::vector<double> & covariance_param);\n\n\n\t/**\n\tReturns the triple product of points i_ = (i,j), j_ = = (k,l) and k_ = = (m,p), e.g Ci_^T(Cj_ x Ck_)\n\t@param i first index of first point\n\t@param j second index of first point\n\t@param k first index of second point\n\t@param l second index of second point\n\t@param m first index of third point\n\t@param p second index of third point\n\t*/\n\tdouble triple_product(const int i ,const int j ,const int k ,const int l ,const int m ,const int p ) const;\n\n\n\n\t/**\n\tReturns the triple product of points i_ = (i,j), j_ = = (k,l) and k_ = = (m,p), e.g Ci_^T(Cj_ x Ck_)\n\t@param i first index of first point\n\t@param j second index of first point\n\t@param k first index of second point\n\t@param l second index of second point\n\t@param m first index of third point\n\t@param p second index of third point\n\t*/\n\tdouble triple_product(const int i ,const int j ,const int k ,const int l ,const int m ,const int p ,\n\t\tconst arma::vec & deviation) const;\n\n\t/**\n\tComputes the quadruple product of points i_ = (i,j), j_ = (k,l), k_ = (m,p), l_ = (q,r)  e.g (Ci_^T Cj_) * (Ck_ x Cl_)\n\t@param result container storing result of computation\n\t@param i first index of first point\n\t@param j second index of first point\n\t@param k first index of second point\n\t@param l second index of second point\n\t@param m first index of third point\n\t@param p second index of third point\n\t@param q first index of fourth point\n\t@param r second index of fourth point\n\t*/\n\tvoid quadruple_product(double * result,const int i ,const int j ,const int k ,const int l ,const int m ,const int p, const int q, const int r ) const;\n\n\n\n\t// Returns the partial derivative d^2P/(dchi dv)\n\tarma::mat::fixed<3,2> partial_bezier_dv(const double u,const double v) const;\n\n\n\t// Returns the partial derivative d^2P/(dchi du)\n\tarma::mat::fixed<3,2> partial_bezier_du(const double u,const double v) const;\n\n\t/**\n\tEvaluates the Berstein polynomial\n\t@param u first barycentric coordinate\n\t@param v first barycentric coordinate\n\t@param i first index\n\t@param j second index\n\t@param n polynomial order\n\t@return evaluated bernstein polynomial\n\t*/\n\tstatic double bernstein(\n\t\tconst double u, \n\t\tconst double v,\n\t\tconst int i,\n\t\tconst int j,\n\t\tconst int n) ;\n\n\n\n\t/**\n\tComputes the partial derivative of the unit normal vector at the queried point\n\twith respect to a given control point\n\t@param u first barycentric coordinate\n\t@param v first barycentric coordinate\n\t@param i first index\n\t@param j second index\n\t@param n polynomial order\n\t*/\n\tarma::mat::fixed<3,3> partial_n_partial_Ck(\n\t\tconst double u, \n\t\tconst double v,\n\t\tconst int i ,  \n\t\tconst int j, \n\t\tconst int n) const;\n\n\n\n\t/**\n\tReturns the coefficient alpha_ijk for volume computation\n\t@param i first index of first triplet\n\t@param j second index of first triplet\n\t@param k first index of second triplet\n\t@param l second index of second triplet\n\t@param m first index of third triplet\n\t@param p second index of third triplet\n\t@param n patch degree\n\t@returm computed coefficient\n\t*/\n\tstatic double alpha_ijk(const int i, const int j, const int k, const int l, const int m, const int p,const int n);\n\n\t/**\n\tReturns the coefficient gamma_ijkl for center of mass computation\n\t@param i first index of first triplet\n\t@param j second index of first triplet\n\t@param k first index of second triplet\n\t@param l second index of second triplet\n\t@param m first index of third triplet\n\t@param p second index of third triplet\n\t@param q first index of fourth triplet\n\t@param r second index of fourth triplet\n\t@param n patch degree\n\t@returm computed coefficient\n\t*/\n\tstatic double gamma_ijkl(const int i, const int j, const int k, const int l, const int m, const int p,const int q, const int r, const int n);\n\n\n\t/**\n\tReturns the coefficient kappa_ijkl for inertia of mass computation\n\t@param i first index of first triplet\n\t@param j second index of first triplet\n\t@param k first index of second triplet\n\t@param l second index of second triplet\n\t@param m first index of third triplet\n\t@param p second index of third triplet\n\t@param q first index of fourth triplet\n\t@param r second index of fourth triplet\n\t@param s first index of fifth triplet\n\t@param t second index of fifth triplet\n\t@param n patch degree\n\t@returm computed coefficient\n\t*/\n\tstatic double kappa_ijklm(const int i, const int j, const int k, const int l, \n\t\tconst int m, const int p,const int q, const int r, \n\t\tconst int s, const int t, const int n);\n\n\n\t/**\n\tReturns the coefficient beta_ijkl for center of mass computation\n\t@param i first index of first triplet\n\t@param j second index of first triplet\n\t@param k first index of second triplet\n\t@param l second index of second triplet\n\t@param n patch degree\n\t@returm computed coefficient\n\t*/\n\tstatic double beta_ijkl( const int i,  const int j,  const int k, const  int l,  const int n);\n\n\n\n\t/**\n\tReturns the stacked crossed products\n\t@param i first index of first triplet\n\t@param j second index of first triplet\n\t@param k first index of second triplet\n\t@param l second index of second triplet\n\t@param m first index of third triplet\n\t@param p second index of third triplet\n\t@returm computed stacked cross-product\n\t*/\n\tarma::vec get_cross_products(const int i, const int j, const int k, const int l, const int m,const int p) const;\n\n\n\t/**\n\tReturns the augmented stacked crossed products\n\t@paran mat reference to matrix holding the stacked crossed products\n\t@param i first index of first triplet\n\t@param j second index of first triplet\n\t@param k first index of second triplet\n\t@param l second index of second triplet\n\t@param m first index of third triplet\n\t@param p second index of third triplet\n\t@param q first index of fourth triplet\n\t@param r second index of fourth triplet\n\t@returm computed stacked cross-product\n\t*/\n\tvoid get_augmented_cross_products(arma::mat::fixed<12,3> & mat,const int i, const int j, const int k, const int l, const int m,const int p,\n\t\tconst int q, const int r) const;\n\n\t/**\n\tGenerates the forward table associating a local index l to the corrsponding triplet (i,j,k) \n\t@param n degree\n\t@return forward look up table\n\t*/\n\tstatic std::vector<std::tuple< int,  int,  int> > forward_table( int n);\n\n\n\n\t/**\n\tGenerates the reverse table associating a local index triplet (i,j,k) to the corresponding\n\tglobal index l\n\t@param n degree\n\t@return reverse look up table\n\t*/\n\tstatic std::map< std::tuple< int,  int,  int> , int> reverse_table( int n);\n\n\n\t\n\t/**\n\tReturns the number of combinations of k items among n.\n\tReturns 0 if k < 0 or k > n\n\t@param k subset size\n\t@param n set size\n\t@return number of combinations\n\t*/\n\tstatic int combinations(int k, int n);\n\n\n\n\t/**\n\tReturns the vector parametrization of the element covariance\n\t@return parametrization of the element covariance\n\t*/\n\tconst arma::vec & get_P_X_param() const{return this -> P_X_param;}\n\nprotected:\n\n\tvirtual void compute_normal();\n\tvirtual void compute_area();\n\tvirtual void compute_center();\n\n\tstatic double Sa_b(const int a, const int b);\n\tstatic double bernstein_coef(const int i , const int j , const int n);\n\n\n\tvoid construct_index_tables();\n\n\n\n\t/**\n\tReturns the partial derivative of the Bernstein polynomial B^n_{i,j,k} evaluated \n\tat (u,v)\n\t@param u first coordinate\n\t@param v second coordinate\n\t@param i first index\n\t@param j second index\n\t@param n polynomial degree\n\t@return evaluated partial derivative of the Bernstein polynomial\n\t*/\n\tstatic arma::rowvec::fixed<2> partial_bernstein(\n\t\tconst double u,\n\t\tconst double v,\n\t\tconst int i,\n\t\tconst int j,\n\t\tconst int n) ;\n\n\n\tstatic arma::rowvec::fixed<2> partial_bernstein_dv( \n\t\tconst double u, \n\t\tconst double v,\n\t\tconst int i ,  \n\t\tconst int j, \n\t\tconst int n) ;\n\n\n\tstatic arma::rowvec::fixed<2> partial_bernstein_du( \n\t\tconst double u, \n\t\tconst double v,\n\t\tconst int i ,  \n\t\tconst int j, \n\t\tconst int n) ;\n\n\n\tint n;\n\tdouble fitting_residuals = 0;\n\tdouble fitting_residuals_mean = 0;\n\n\tstd::vector<std::tuple< int,  int,  int> > forw_table;\n\tstd::map< std::tuple< int,  int,  int> , int> rev_table;\n\n\n\tarma::mat P_X;\n\tstd::vector<double> epsilons;\n\tarma::vec P_X_param;\n\n};\n#endif", "meta": {"hexsha": "d5627e9d7603c16affc026ddcbc8d3873e8f2095", "size": 13146, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ShapeUQLib/Bezier.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/Bezier.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/Bezier.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": 27.2738589212, "max_line_length": 151, "alphanum_fraction": 0.7309447741, "num_tokens": 3385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835330070838, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.49516318482492216}}
{"text": "/***************************************************************************\nLibBandit - Multi-Armed Bandit Library\nWritten in 2015 by Tor Lattimore tor.lattimore@gmail.com\n\nTo the extent possible under law, the author(s) have dedicated all \ncopyright and related and neighboring rights to this software to the \npublic domain worldwide. This software is distributed without any warranty.\n\nYou should have received a copy of the CC0 Public Domain Dedication \nalong with this software. If not, \nsee http://creativecommons.org/publicdomain/zero/1.0/\n***************************************************************************/\n#include \"algs.h\"\n#include \"bandit.h\"\n#include \"arm.h\"\n#include \"gittins_table.h\"\n\n#include <cfloat>\n#include <cmath>\n#include <algorithm>\n#include <iostream>\n#include <limits>\n#include <queue>\n#include <list>\n\n#include <boost/math/special_functions/erf.hpp>\n\nusing namespace std;\n\n/*************************************************************\nGENERIC SIMULATOR\n*************************************************************/\ndouble IndexAlgorithm::sim(BanditProblem &bp, uint64_t horizon) {\n  K = bp.K;\n  n = horizon;\n\n  bp.reset();\n  arms.clear();\n\n  for (uint64_t i = 0;i != K;++i) {\n    arms.push_back(Arm(i, std::numeric_limits<double>::max()));\n    arms.rbegin()->max_idx = std::numeric_limits<double>::max();\n  }\n\n  uint64_t t = 0;\n  for (;t != K && t !=n;++t) {\n    arms[t].pull(bp.choose(arms[t].i));\n  }\n  \n  for (;t != n;++t) {\n    auto best_idx = -numeric_limits<double>::max();\n    auto best = arms.begin();\n    auto last = arms.begin();\n\n    for (auto a = arms.begin();a!=arms.end();++a) {\n      if (a->max_idx < best_idx) {\n        break;\n      }\n      last = a;\n      set_index(a, t);\n\n      if (a->idx > best_idx) {\n        best_idx = a->idx;\n        best = a;\n      }\n    }\n    best->max_idx = numeric_limits<double>::max();\n    best->pull(bp.choose(best->i));\n\n    update(best);\n\n    sort(arms.begin(), last+1, [](const Arm &a1, const Arm &a2) {return a1.max_idx > a2.max_idx;});\n    inplace_merge(arms.begin(), last+1, arms.end(), [](const Arm &a1, const Arm &a2) {return a1.max_idx > a2.max_idx;});\n  }\n  return bp.get_regret();\n}\n\n\nvoid UCB::set_index(vector<Arm>::iterator a, uint64_t t) {\n  a->idx = a->mean() + sqrt(alpha / a->T * log(t));\n  a->max_idx = a->mean() + sqrt(alpha / a->T * log(n));\n}\n\nvoid MOSS::set_index(vector<Arm>::iterator a, uint64_t t) {\n  a->idx = a->mean() + sqrt(2.0 / a->T * log(max(1.0, (double)n / (a->T * K))));\n  a->max_idx = a->idx;\n}\n\nvoid OCUCB::set_index(vector<Arm>::iterator a, uint64_t t) {\n  a->idx = a->mean() + sqrt(alpha / a->T * log(psi * (double)n / t));\n//  a->max_idx = std::numeric_limits<double>::max();\n  a->max_idx = a->idx;\n}\n\nvoid AnytimeOCUCB::set_index(vector<Arm>::iterator a, uint64_t t) {\n  const double EULER = exp(1.0);\n  a->idx =     a->mean() + sqrt(alpha / a->T * log(max(max(EULER, log(t+1.0)), log(t+1.0)  * (t+1.0) / lookup.lookup(a->i)))); \n  a->max_idx = a->mean() + sqrt(alpha / a->T * log(max(max(EULER, log(n+1.0)), log(n+1.0)  * (n+1.0) / lookup.lookup(a->i)))); \n}\n\nvoid AnytimeOCUCB::update(vector<Arm>::iterator a) {\n  lookup.update(a->i);\n}\n\nvoid OptAnytimeOCUCB::set_index(vector<Arm>::iterator a, uint64_t t) {\n  a->idx =     a->mean() + sqrt(alpha / a->T * log(max(1.0, (t+1.0) / lookup.lookup(a->i)))); \n  a->max_idx =     a->mean() + sqrt(alpha / a->T * log(max(1.0, (n+1.0) / lookup.lookup(a->i)))); \n}\n\nvoid OptAnytimeOCUCB::update(vector<Arm>::iterator a) {\n  lookup.update(a->i);\n}\n\n\nvoid AOCUCB::set_index(vector<Arm>::iterator a, uint64_t t) {\n  a->idx = a->mean() + sqrt(alpha / a->T * log((double)t / a->T));\n  a->max_idx = a->mean() + sqrt(alpha / a->T * log((double)n / a->T));\n}\n\nvoid GaussianTS::set_index(vector<Arm>::iterator a, uint64_t t) {\n  a->idx = a->mean() + dist(gen) / sqrt(a->T);\n  a->max_idx = std::numeric_limits<double>::max();\n}\n\nvoid GaussianGittins::set_index(vector<Arm>::iterator a, uint64_t t) {\n  a->idx = a->mean() + table.get_idx(n - t, a->T);\n  a->max_idx = a->idx;\n}\n\nvoid GaussianGittinsApprox::set_index(vector<Arm>::iterator a, uint64_t t) {\n  uint64_t m = n - t;\n  double beta = max(1.0, min(m / pow(log(m), 1.5) / 4.0, m / 4.0 / a->T / pow(log(m/a->T), 0.5)));\n  a->idx = a->mean() + sqrt(2.0 / a->T * log(beta));\n  a->max_idx = a->idx;\n}\n\n\n\n\n", "meta": {"hexsha": "f8f53ce1afafa47e692f8c2161f7fb91526c6a98", "size": 4313, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/algs.cc", "max_stars_repo_name": "Naereen/libbandit", "max_stars_repo_head_hexsha": "d3c482ffd77d37aff613b963c7c960219de09106", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 56.0, "max_stars_repo_stars_event_min_datetime": "2016-05-16T22:45:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T03:28:47.000Z", "max_issues_repo_path": "src/algs.cc", "max_issues_repo_name": "Naereen/libbandit", "max_issues_repo_head_hexsha": "d3c482ffd77d37aff613b963c7c960219de09106", "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/algs.cc", "max_forks_repo_name": "Naereen/libbandit", "max_forks_repo_head_hexsha": "d3c482ffd77d37aff613b963c7c960219de09106", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2016-05-21T19:52:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-25T15:45:10.000Z", "avg_line_length": 30.8071428571, "max_line_length": 127, "alphanum_fraction": 0.5701367957, "num_tokens": 1342, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.49516318239715057}}
{"text": "/*! @file pitts_tensortrain_from_dense_classical.hpp\n* @brief conversion of a dense tensor to the tensor-train format, classical TT-SVD algorithm\n* @author Melven Roehrig-Zoellner <Melven.Roehrig-Zoellner@DLR.de>\n* @date 2020-06-19\n* @copyright Deutsches Zentrum fuer Luft- und Raumfahrt e. V. (DLR), German Aerospace Center\n*\n**/\n\n// include guard\n#ifndef PITTS_TENSORTRAIN_FROM_DENSE_CLASSICAL_HPP\n#define PITTS_TENSORTRAIN_FROM_DENSE_CLASSICAL_HPP\n\n// includes\n#include <cstddef>\n#include <functional>\n#include <iterator>\n#include <numeric>\n#include <type_traits>\n#pragma GCC push_options\n#pragma GCC optimize(\"no-unsafe-math-optimizations\")\n#include <Eigen/Dense>\n#pragma GCC pop_options\n#include \"pitts_tensortrain.hpp\"\n#include \"pitts_timer.hpp\"\n\n//! namespace for the library PITTS (parallel iterative tensor train solvers)\nnamespace PITTS\n{\n  //! calculate tensor-train decomposition of a tensor stored in fully dense format (slow classical TT-SVD)\n  //!\n  //! @tparam Iter      contiguous input iterator to access the dense data\n  //! @tparam T         underlying data type (double, complex, ...)\n  //!\n  //! @param first          input iterator that points to the first index, e.g. std::begin(someContainer)\n  //! @param last           input iterator that points behind the last index, e.g. std::end(someContainer)\n  //! @param dimensions     tensor dimensions, input is interpreted in Fortran storage order (first index changes the fastest)\n  //! @param rankTolerance  approximation accuracy, used to reduce the TTranks of the resulting tensor train\n  //! @param maxRank        maximal TTrank (bond dimension), unbounded by default\n  //! @return               resulting tensor train\n  //!\n  template<class Iter, typename T = std::iterator_traits<Iter>::value_type>\n  TensorTrain<T> fromDense_classical(const Iter first, const Iter last, const std::vector<int>& dimensions, T rankTolerance = std::sqrt(std::numeric_limits<T>::epsilon()), int maxRank = -1)\n  {\n    // timer\n    const auto timer = PITTS::timing::createScopedTimer<TensorTrain<T>>();\n\n    // check that the input is contiguous in memory\n    //static_assert(std::is_base_of< std::contiguous_iterator_tag, typename std::iterator_traits<Iter>::iterator_category >::value, \"fromDense only works with contiguous iterators!\");\n    static_assert(std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits<Iter>::iterator_category >::value, \"fromDense only works with contiguous iterators!\");\n\n    // abort early for zero dimensions\n    if( dimensions.size() == 0 )\n    {\n      if( last - first != 0 )\n        throw std::out_of_range(\"Mismatching dimensions in TensorTrain<T>::fromDense\");\n      return TensorTrain<T>{dimensions};\n    }\n\n    const auto totalSize = std::accumulate(begin(dimensions), end(dimensions), (std::ptrdiff_t)1, std::multiplies<std::ptrdiff_t>());\n    if( totalSize != last - first )\n      throw std::out_of_range(\"Mismatching dimensions in TensorTrain<T>::fromDense\");\n\n    TensorTrain<T> result(dimensions);\n\n    using EigenMatrix = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>;\n    EigenMatrix tmp = Eigen::Map<const EigenMatrix>(&(*first), 1, totalSize);\n    for(int iDim = 0; iDim+1 < dimensions.size(); iDim++)\n    {\n      tmp.resize(tmp.rows()*dimensions[iDim], tmp.cols()/dimensions[iDim]);\n      Eigen::BDCSVD<EigenMatrix> svd(tmp, Eigen::ComputeThinU | Eigen::ComputeThinV);\n      svd.setThreshold(rankTolerance);\n      int rank = svd.rank();\n      if( maxRank > 0 )\n        rank = std::min(rank, maxRank);\n\n      auto& subT = result.editableSubTensors()[iDim];\n      subT.resize(tmp.rows()/dimensions[iDim], dimensions[iDim], rank);\n      for(int i = 0; i < subT.r1(); i++)\n        for(int j = 0; j < subT.n(); j++)\n          for(int k = 0; k < subT.r2(); k++)\n            subT(i,j,k) = svd.matrixU()(i+j*subT.r1(), k);\n\n      tmp.resize(rank, tmp.cols());\n      tmp = svd.singularValues().topRows(rank).asDiagonal() * svd.matrixV().leftCols(rank).adjoint();\n    }\n    int lastDim = dimensions.size()-1;\n    auto& lastSubT = result.editableSubTensors()[lastDim];\n    tmp.resize(tmp.size()/dimensions[lastDim], dimensions[lastDim]);\n    lastSubT.resize(tmp.rows(), tmp.cols(), 1);\n    for(int j = 0; j < tmp.cols(); j++)\n      for(int i = 0; i < tmp.rows(); i++)\n        lastSubT(i, j, 0) = tmp(i, j);\n\n    return result;\n  }\n\n}\n\n\n#endif // PITTS_TENSORTRAIN_FROM_DENSE_CLASSICAL_HPP\n", "meta": {"hexsha": "eb085a6e5ca7a66e42a04491c730e06e19060b45", "size": 4409, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/pitts_tensortrain_from_dense_classical.hpp", "max_stars_repo_name": "melven/pitts", "max_stars_repo_head_hexsha": "491f503a99a7d1161a27672955ae53ca6b5d3412", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-12-31T08:28:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T14:48:49.000Z", "max_issues_repo_path": "src/pitts_tensortrain_from_dense_classical.hpp", "max_issues_repo_name": "melven/pitts", "max_issues_repo_head_hexsha": "491f503a99a7d1161a27672955ae53ca6b5d3412", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pitts_tensortrain_from_dense_classical.hpp", "max_forks_repo_name": "melven/pitts", "max_forks_repo_head_hexsha": "491f503a99a7d1161a27672955ae53ca6b5d3412", "max_forks_repo_licenses": ["BSD-3-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.6534653465, "max_line_length": 189, "alphanum_fraction": 0.6872306645, "num_tokens": 1140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.49516318239715057}}
{"text": "#include <CGAL/Simple_cartesian.h>\n#include <CGAL/boost/graph/graph_traits_Linear_cell_complex_for_combinatorial_map.h>\n\n#include <iostream>\n#include <list>\n\n#include <boost/graph/kruskal_min_spanning_tree.hpp>\n\ntypedef CGAL::Simple_cartesian<double>              Kernel;\ntypedef Kernel::Point_3                             Point;\ntypedef CGAL::Linear_cell_complex_traits<3, Kernel> LCC_traits;\n\ntypedef CGAL::Linear_cell_complex_for_bgl_combinatorial_map_helper\n         <2, 3, LCC_traits>::type LCC;\n\ntypedef boost::graph_traits<LCC>::vertex_descriptor vertex_descriptor;\ntypedef boost::graph_traits<LCC>::vertex_iterator   vertex_iterator;\ntypedef boost::graph_traits<LCC>::edge_descriptor   edge_descriptor;\n\n\n\nvoid kruskal(const LCC& lcc)\n{\n  // We use the default edge weight which is the length of the edge\n  // This property map is defined in graph_traits_Linear_cell_complex_for_combinatorial_map.h\n\n  // This function call requires a vertex_index_map named parameter which\n  // when  ommitted defaults to \"get(vertex_index,graph)\".\n  // That default works here because the vertex type has an \"id()\" method\n  // field which is used by the vertex_index internal property.\n  std::list<edge_descriptor> mst;\n  boost::kruskal_minimum_spanning_tree(lcc,std::back_inserter(mst));\n\n  std::cout << \"#VRML V2.0 utf8\\n\"\n    \"Shape {\\n\"\n    \"appearance Appearance {\\n\"\n    \"material Material { emissiveColor 1 0 0}}\\n\"\n    \"geometry\\n\"\n    \"IndexedLineSet {\\n\"\n    \"coord Coordinate {\\n\"\n    \"point [ \\n\";\n\n  vertex_iterator vb, ve;\n  for(boost::tie(vb,ve) = vertices(lcc); vb!=ve; ++vb){\n    std::cout << (*vb)->point() << \"\\n\";\n  }\n\n  std::cout << \"]\\n\"\n    \"}\\n\"\n    \"coordIndex [\\n\";\n\n  for(std::list<edge_descriptor>::iterator it = mst.begin(); it != mst.end(); ++it){\n    std::cout << source(*it,lcc)->id()\n              << \", \" << target(*it,lcc)->id() <<  \", -1\\n\";\n  }\n\n  std::cout << \"]\\n\"\n    \"}#IndexedLineSet\\n\"\n    \"}# Shape\\n\";\n}\n\n\nint main()\n{\n  LCC lcc;\n\n  Point a(1,0,0);\n  Point b(0,1,0);\n  Point c(0,0,1);\n  Point d(0,0,0);\n\n  lcc.make_tetrahedron(a,b,c,d);\n  kruskal(lcc);\n\n  return 0;\n}\n", "meta": {"hexsha": "8975b32d76d1c1f8c845684e8eac936e2786d090", "size": 2107, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "BGL/examples/BGL_LCC/kruskal_lcc.cpp", "max_stars_repo_name": "ffteja/cgal", "max_stars_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 3227.0, "max_stars_repo_stars_event_min_datetime": "2015-03-05T00:19:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:20:35.000Z", "max_issues_repo_path": "BGL/examples/BGL_LCC/kruskal_lcc.cpp", "max_issues_repo_name": "ffteja/cgal", "max_issues_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 5574.0, "max_issues_repo_issues_event_min_datetime": "2015-03-05T00:01:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:08:11.000Z", "max_forks_repo_path": "BGL/examples/BGL_LCC/kruskal_lcc.cpp", "max_forks_repo_name": "ffteja/cgal", "max_forks_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1274.0, "max_forks_repo_forks_event_min_datetime": "2015-03-05T00:01:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:47:56.000Z", "avg_line_length": 27.3636363636, "max_line_length": 93, "alphanum_fraction": 0.6668248695, "num_tokens": 603, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933535169629, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.49515969644922486}}
{"text": "/* Copyright 2020 Oinam Romesh Meitei\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n */\n\n#include <pybind11/pybind11.h>\n#include <pybind11/stl.h>\n#include <pybind11/eigen.h>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <unsupported/Eigen/MatrixFunctions>\n#include <cmath>\n#include <vector>\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <iostream>\n#include <iomanip>\n\n#include \"getham.h\"\n\nnamespace py = pybind11;\n\nEigen::MatrixXcd solve_trotter(\t\t       \n\t\t\t       std::vector<double> &tlist,\n\t\t\t       std::vector<std::complex<double> > &ini_vec,\n\t\t\t       pulsec pobj,\n\t\t\t       std::vector< std::vector< Eigen::SparseMatrix<double,0,ptrdiff_t> > > hdrive,\n\t\t\t       std::vector< std::complex<double> > dsham){\n\n  Eigen::SparseMatrix<std::complex<double> > H_ ;\n  Eigen::MatrixXcd H1_;\n  int dsham_len = dsham.size();\n  Eigen::SparseMatrix<std::complex<double> >\n    matexp_(dsham_len, dsham_len);\n  \n  Eigen::Map<Eigen::VectorXcd> trot_(ini_vec.data(), ini_vec.size());\n  int tlen = tlist.size();\n  double tau = tlist[tlen-1] / tlen;\n  std::complex<double> im(0.0,-tau);\n\n  for (int t=0; t<tlen; t++){\n    H_ = getham(tlist[t], pobj, hdrive, dsham, dsham_len, matexp_);\n    H1_ = im * Eigen::MatrixXcd(H_);\n\n    trot_ = H1_.exp() * trot_;\n  }\n\n  return trot_;\n}  \n\nEigen::MatrixXcd solve_trotter2(\n\t\t\tstd::vector<double> &tlist,\n\t\t\tstd::vector<std::complex<double> > &ini_vec,\n\t\t\tpulsec pobj,\n\t\t\tstd::vector< std::vector< Eigen::SparseMatrix\n\t\t\t<double,0,ptrdiff_t> > > hdrive,\n\t\t\tstd::vector< std::complex<double> > dsham){\n  \n  Eigen::SparseMatrix<std::complex<double> > H_ ;\n  Eigen::MatrixXcd H1_;\n  \n  int dsham_len = dsham.size();\n  int tlen = tlist.size();\n  \n  Eigen::SparseMatrix<std::complex<double> > hamdr;\n  Eigen::SparseMatrix<std::complex<double> > hamdR;\n  std::complex<double> hcoef;\n\n  Eigen::SparseMatrix<std::complex<double> >\n    matexp_(dsham_len, dsham_len);\n  \n  Eigen::Map<Eigen::VectorXcd> trot_(ini_vec.data(), ini_vec.size());\n\n  \n  double tau = tlist[tlen-1] / tlen;\n  std::complex<double> im(0.0,-tau);\n\n  for (int t=0; t<tlen; t++){\n    H_ = getham3( tlist[t], t, pobj, hdrive, dsham, dsham_len, matexp_,\n\t\t  hamdr, hamdR, hcoef);\n    H1_ = im * Eigen::MatrixXcd(H_);\n    trot_ = H1_.exp() * trot_;\n  }\n  return trot_;\n}\n\nPYBIND11_MODULE(trotter,m){\n  m.def(\"solve_trotter\", &solve_trotter, \"trotter\");\n  m.def(\"solve_trotter2\", &solve_trotter2, \"trotter2\");\n}\n", "meta": {"hexsha": "071154bcb617f1bde83d08c59bb770aade42e9a6", "size": 2937, "ext": "cc", "lang": "C++", "max_stars_repo_path": "ctrlq/lib/trotter.cc", "max_stars_repo_name": "oimeitei/ctrlq", "max_stars_repo_head_hexsha": "7df76db0b3677447a2027c0a3a1176beb7267c45", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2020-09-25T14:50:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-09T17:36:53.000Z", "max_issues_repo_path": "ctrlq/lib/trotter.cc", "max_issues_repo_name": "oimeitei/ctrlq", "max_issues_repo_head_hexsha": "7df76db0b3677447a2027c0a3a1176beb7267c45", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-09-21T18:54:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-21T18:54:38.000Z", "max_forks_repo_path": "ctrlq/lib/trotter.cc", "max_forks_repo_name": "oimeitei/ctrlq", "max_forks_repo_head_hexsha": "7df76db0b3677447a2027c0a3a1176beb7267c45", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-09-18T18:19:41.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-26T13:48:44.000Z", "avg_line_length": 28.5145631068, "max_line_length": 87, "alphanum_fraction": 0.6734763364, "num_tokens": 892, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.495159685817955}}
{"text": "///////////////////////////////////////////////////////////////\n//  Copyright 2021 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\n#include <Eigen/Dense>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/multiprecision/eigen.hpp>\n\ntypedef boost::multiprecision::cpp_rational               NT;\ntypedef Eigen::Matrix<NT, Eigen::Dynamic, Eigen::Dynamic> M;\n\nvoid f(M& m1, M const& m2)\n{\n   m1 = m2 * m2;\n}\n", "meta": {"hexsha": "c5ed8e6c2c8e953e9e0cfbc206a3b2c4e34fad36", "size": 538, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/git_issue_393.cpp", "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": "test/git_issue_393.cpp", "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": "test/git_issue_393.cpp", "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": 29.8888888889, "max_line_length": 68, "alphanum_fraction": 0.626394052, "num_tokens": 137, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8198933271118221, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4951596805023196}}
{"text": "/* Copyright (C) 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/* Test_Permutations.cpp - Applying plaintext permutation to encrypted vector\n */\n#include <NTL/ZZ.h>\nNTL_CLIENT\n\n#include <helib/NumbTh.h>\n#include <helib/timing.h>\n#include <helib/permutations.h>\n#include <helib/EncryptedArray.h>\n#include <helib/ArgMap.h>\n\nusing namespace helib;\n\nstatic bool noPrint = true;\n\nvoid testCtxt(long m, long p, long depthBound, long L, long r)\n{\n  if (!noPrint)\n    std::cout << \"@testCtxt(m=\"<<m<<\",p=\"<<p<<\",depth=\"<<depthBound<< \",r=\"<<r<<\")\\n\";\n\n  Context context(m,p,r);\n  buildModChain(context, /*nLevels=*/L);\n\n  // Generate a sk/pk pair\n  SecKey secretKey(context);\n  secretKey.GenSecKey(); // A +-1/0 secret key\n  const PubKey& publicKey = secretKey;\n\n\n  long n = context.getNSlots();\n\n  std::cout << \"n=\" << n << \"\\n\";\n\n  PermIndepPrecomp pip(context, depthBound);\n\n  std::cout << \"depth=\" << pip.getDepth() << \"\\n\";;\n  std::cout << \"cost=\" << pip.getCost() << \"\\n\";;\n\n  Permut pi;\n  randomPerm(pi, n);\n\n  PermPrecomp pp(pip, pi);\n\n  addSome1DMatrices(secretKey);\n  // addMatrices4Network(secretKey, net); \n  // I can't remember if this is significantly better than \n  // addSome1DMatrices.  I mean, I *think* we always stuck to the\n  // convention of only having KS matrices for powers of generators.\n  // I guess I can play around and see...\n\n  Ctxt ctxt(publicKey);\n  PtxtArray v(context);\n  v.random();\n\n\n  if (p < 0)\n    v.encrypt(ctxt, n); // CKKS encryption\n  else\n    v.encrypt(ctxt);    // BGV encryption\n\n  pp.apply(ctxt);\n  pp.apply(v);\n\n  PtxtArray w(context);\n  w.decrypt(ctxt, secretKey);\n\n\n  if (w == Approx(v))\n    std::cout << \"GOOD\\n\";\n  else\n    std::cout << \"BAD\\n\";\n}\n\n\n\nint main(int argc, char *argv[])\n{\n  long p = 2;\n  long r = 0;\n  long m = 4369;\n  long L = 1000;\n  long depth = 5;\n\n  noPrint=0;\n\n  ArgMap amap;\n  amap.arg(\"p\", p);\n  amap.arg(\"r\", r);\n  amap.arg(\"m\", m);\n  amap.arg(\"L\", L);\n  amap.arg(\"depth\", depth);\n  amap.arg(\"noPrint\", noPrint);\n  amap.parse(argc, argv);\n\n  if (p < 0 && r == 0) r = 20; // CKKS default\n  if (p > 0 && r == 0) r = 1;  // BGV default\n\n\n  testCtxt(m,p,depth,L,r);\n}\n", "meta": {"hexsha": "535bc35bc634a39a3969c9eba413c1ed7119e61b", "size": 2700, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "misc/legacy_tests/tperms1.cpp", "max_stars_repo_name": "jatanloya/HElib-PSI", "max_stars_repo_head_hexsha": "b5ec2844216ac87f1e20542e31ebb98363c14a6f", "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": "misc/legacy_tests/tperms1.cpp", "max_issues_repo_name": "jatanloya/HElib-PSI", "max_issues_repo_head_hexsha": "b5ec2844216ac87f1e20542e31ebb98363c14a6f", "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": "misc/legacy_tests/tperms1.cpp", "max_forks_repo_name": "jatanloya/HElib-PSI", "max_forks_repo_head_hexsha": "b5ec2844216ac87f1e20542e31ebb98363c14a6f", "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.8938053097, "max_line_length": 86, "alphanum_fraction": 0.647037037, "num_tokens": 812, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597974, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.49513824928685074}}
{"text": "// This file is part of libigl, a simple c++ geometry processing library.\n// \n// Copyright (C) 2013 Alec Jacobson <alecjacobson@gmail.com>\n// \n// This Source Code Form is subject to the terms of the Mozilla Public License \n// v. 2.0. If a copy of the MPL was not distributed with this file, You can \n// obtain one at http://mozilla.org/MPL/2.0/.\n#include \"components.h\"\n#include <igl/adjacency_matrix.h>\n\n//#include <boost/graph/adjacency_matrix.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/connected_components.hpp>\n#include <iostream>\n#include <vector>\n#include <cassert>\n\ntemplate <typename AScalar, typename DerivedC>\nIGL_INLINE void igl::components(\n  const Eigen::SparseMatrix<AScalar> & A,\n  Eigen::PlainObjectBase<DerivedC> & C)\n{\n  assert(A.rows() == A.cols());\n  using namespace Eigen;\n  // THIS IS DENSE:\n  //boost::adjacency_matrix<boost::undirectedS> bA(A.rows());\n  boost::adjacency_list<boost::vecS,boost::vecS,boost::undirectedS> bA(A.rows());\n  for(int j=0; j<A.outerSize();j++)\n  {\n    // Iterate over inside\n    for(typename SparseMatrix<AScalar>::InnerIterator it (A,j); it; ++it)\n    {\n      if(0 != it.value())\n      {\n        boost::add_edge(it.row(),it.col(),bA);\n      }\n    }\n  }\n  C.resize(A.rows(),1);\n  boost::connected_components(bA,C.data());\r\n}\n\ntemplate <typename DerivedF, typename DerivedC>\nIGL_INLINE void igl::components(\n  const Eigen::PlainObjectBase<DerivedF> & F,\n  Eigen::PlainObjectBase<DerivedC> & C)\n{\n  Eigen::SparseMatrix<typename DerivedC::Scalar> A;\n  igl::adjacency_matrix(F,A);\n  return components(A,C);\n}\n\n#ifdef IGL_STATIC_LIBRARY\n// Explicit template specialization\ntemplate void igl::components<Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);\n#endif\n", "meta": {"hexsha": "15d180170bc398d6a071164331c618d6d73b06ba", "size": 1893, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/quadwild/libs/libigl/include/igl/boost/components.cpp", "max_stars_repo_name": "Pentacode-IAFA/Quad-Remeshing", "max_stars_repo_head_hexsha": "f8fd4c10abf1c54656b38a00b8a698b952a85fe2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/quadwild/libs/libigl/include/igl/boost/components.cpp", "max_issues_repo_name": "Pentacode-IAFA/Quad-Remeshing", "max_issues_repo_head_hexsha": "f8fd4c10abf1c54656b38a00b8a698b952a85fe2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/quadwild/libs/libigl/include/igl/boost/components.cpp", "max_forks_repo_name": "Pentacode-IAFA/Quad-Remeshing", "max_forks_repo_head_hexsha": "f8fd4c10abf1c54656b38a00b8a698b952a85fe2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.2105263158, "max_line_length": 241, "alphanum_fraction": 0.6862123613, "num_tokens": 554, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.495138239205884}}
{"text": "\n\n/* --------------------------------------------------------------------- \n * \n * Copyright (C) 2010 - 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: Andrea Bonito, Sebastian Pauletti. \n */ \n\n\n// @sect3{Include files}  \n\n// \u5982\u679c\u4f60\u8bfb\u8fc7 step-4 \u548c step-7 \uff0c\u4f60\u4f1a\u8ba4\u8bc6\u5230\u6211\u4eec\u5df2\u7ecf\u5728\u90a3\u91cc\u4f7f\u7528\u4e86\u4ee5\u4e0b\u6240\u6709\u7684\u5305\u542b\u6587\u4ef6\u3002\u56e0\u6b64\uff0c\u6211\u4eec\u4e0d\u4f1a\u5728\u8fd9\u91cc\u518d\u6b21\u89e3\u91ca\u5b83\u4eec\u7684\u542b\u4e49\u3002\n\n#include <deal.II/base/quadrature_lib.h> \n#include <deal.II/base/function.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_cg.h> \n#include <deal.II/lac/precondition.h> \n#include <deal.II/lac/sparse_matrix.h> \n#include <deal.II/lac/dynamic_sparsity_pattern.h> \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\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_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#include <deal.II/numerics/matrix_tools.h> \n\n#include <fstream> \n#include <iostream> \n\nnamespace Step38 \n{ \n  using namespace dealii; \n// @sect3{The <code>LaplaceBeltramiProblem</code> class template}  \n\n//\u8fd9\u4e2a\u7c7b\u51e0\u4e4e\u4e0e step-4 \u4e2d\u7684 <code>LaplaceProblem</code> \u7c7b\u5b8c\u5168\u76f8\u4f3c\u3002\n\n//\u672c\u8d28\u4e0a\u7684\u533a\u522b\u662f\u8fd9\u6837\u7684\u3002\n\n\n\n// - \u6a21\u677f\u53c2\u6570\u73b0\u5728\u8868\u793a\u5d4c\u5165\u7a7a\u95f4\u7684\u7ef4\u5ea6\uff0c\u5b83\u4e0d\u518d\u4e0e\u57df\u548c\u6211\u4eec\u8ba1\u7b97\u7684\u4e09\u89d2\u5f62\u7684\u7ef4\u5ea6\u76f8\u540c\u3002\u6211\u4eec\u901a\u8fc7\u8c03\u7528\u53c2\u6570 @p spacedim, \u5e76\u5f15\u5165\u4e00\u4e2a\u7b49\u4e8e\u57df\u7684\u7ef4\u5ea6\u7684\u5e38\u6570 @p dim \u6765\u8868\u660e\u8fd9\u4e00\u70b9--\u8fd9\u91cc\u7b49\u4e8e <code>spacedim-1</code>  \u3002\n\n// - \u6240\u6709\u5177\u6709\u51e0\u4f55\u7279\u5f81\u7684\u6210\u5458\u53d8\u91cf\u73b0\u5728\u90fd\u9700\u8981\u77e5\u9053\u5b83\u4eec\u81ea\u5df1\u7684\u7ef4\u5ea6\u4ee5\u53ca\u5d4c\u5165\u7a7a\u95f4\u7684\u7ef4\u5ea6\u3002\u56e0\u6b64\uff0c\u6211\u4eec\u9700\u8981\u6307\u5b9a\u5b83\u4eec\u7684\u6a21\u677f\u53c2\u6570\uff0c\u4e00\u4e2a\u662f\u7f51\u683c\u7684\u7ef4\u5ea6 @p dim, \uff0c\u53e6\u4e00\u4e2a\u662f\u5d4c\u5165\u7a7a\u95f4\u7684\u7ef4\u5ea6\uff0c @p spacedim.  \u8fd9\u6b63\u662f\u6211\u4eec\u5728 step-34 \u4e2d\u6240\u505a\u7684\uff0c\u8bf7\u770b\u90a3\u91cc\u6709\u66f4\u6df1\u7684\u89e3\u91ca\u3002\n\n// - \u6211\u4eec\u9700\u8981\u4e00\u4e2a\u5bf9\u8c61\u6765\u63cf\u8ff0\u4ece\u53c2\u8003\u5355\u5143\u5230\u4e09\u89d2\u5f62\u7ec4\u6210\u7684\u5355\u5143\u6240\u4f7f\u7528\u7684\u54ea\u79cd\u6620\u5c04\u3002\u4eceMapping\u57fa\u7c7b\u6d3e\u751f\u51fa\u6765\u7684\u7c7b\u6b63\u662f\u8fd9\u6837\u505a\u7684\u3002\u5728deal.II\u7684\u5927\u90e8\u5206\u65f6\u95f4\u91cc\uff0c\u5982\u679c\u4f60\u4e0d\u505a\u4efb\u4f55\u4e8b\u60c5\uff0c\u56fe\u4e66\u9986\u4f1a\u5047\u5b9a\u4f60\u60f3\u8981\u4e00\u4e2a\u4f7f\u7528\uff08\u53cc\uff0c\u4e09\uff09\u7ebf\u6027\u6620\u5c04\u7684MappingQ1\u5bf9\u8c61\u3002\u5728\u8bb8\u591a\u60c5\u51b5\u4e0b\uff0c\u8fd9\u5c31\u8db3\u591f\u4e86\uff0c\u8fd9\u5c31\u662f\u4e3a\u4ec0\u4e48\u8fd9\u4e9b\u5bf9\u8c61\u7684\u4f7f\u7528\u5927\u591a\u662f\u53ef\u9009\u7684\uff1a\u4f8b\u5982\uff0c\u5982\u679c\u4f60\u6709\u4e00\u4e2a\u4e8c\u7ef4\u7a7a\u95f4\u4e2d\u7684\u591a\u8fb9\u5f62\u4e8c\u7ef4\u57df\uff0c\u53c2\u8003\u5355\u5143\u5230\u4e09\u89d2\u5f62\u5355\u5143\u7684\u53cc\u7ebf\u6027\u6620\u5c04\u4f1a\u4ea7\u751f\u8be5\u57df\u7684\u7cbe\u786e\u8868\u793a\u3002\u5982\u679c\u4f60\u6709\u4e00\u4e2a\u5f2f\u66f2\u7684\u57df\uff0c\u4f60\u53ef\u80fd\u60f3\u5bf9\u90a3\u4e9b\u4f4d\u4e8e\u57df\u7684\u8fb9\u754c\u7684\u5355\u5143\u4f7f\u7528\u4e00\u4e2a\u9ad8\u9636\u6620\u5c04--\u4f8b\u5982\uff0c\u8fd9\u5c31\u662f\u6211\u4eec\u5728 step-11 \u4e2d\u6240\u505a\u7684\u3002\u7136\u800c\uff0c\u5728\u8fd9\u91cc\u6211\u4eec\u6709\u4e00\u4e2a\u5f2f\u66f2\u7684\u57df\uff0c\u800c\u4e0d\u4ec5\u4ec5\u662f\u4e00\u4e2a\u5f2f\u66f2\u7684\u8fb9\u754c\uff0c\u867d\u7136\u6211\u4eec\u53ef\u4ee5\u7528\u53cc\u7ebf\u6027\u6620\u5c04\u7684\u5355\u5143\u6765\u8fd1\u4f3c\u5b83\uff0c\u4f46\u5bf9\u6240\u6709\u5355\u5143\u4f7f\u7528\u9ad8\u9636\u6620\u5c04\u624d\u662f\u771f\u6b63\u8c28\u614e\u7684\u3002\u56e0\u6b64\uff0c\u8fd9\u4e2a\u7c7b\u6709\u4e00\u4e2aMappingQ\u7c7b\u578b\u7684\u6210\u5458\u53d8\u91cf\uff1b\u6211\u4eec\u5c06\u9009\u62e9\u6620\u5c04\u7684\u591a\u9879\u5f0f\u7a0b\u5ea6\u7b49\u4e8e\u8ba1\u7b97\u4e2d\u4f7f\u7528\u7684\u6709\u9650\u5143\u7684\u591a\u9879\u5f0f\u7a0b\u5ea6\uff0c\u4ee5\u786e\u4fdd\u6700\u4f73\u8fd1\u4f3c\uff0c\u5c3d\u7ba1\u8fd9\u79cd\u7b49\u53c2\u6570\u6027\u4e0d\u662f\u5fc5\u987b\u7684\u3002\n\n  template <int spacedim> \n  class LaplaceBeltramiProblem \n  { \n  public: \n    LaplaceBeltramiProblem(const unsigned degree = 2); \n    void run(); \n\n  private: \n    static constexpr unsigned int dim = spacedim - 1; \n\n    void make_grid_and_dofs(); \n    void assemble_system(); \n    void solve(); \n    void output_results() const; \n    void compute_error() const; \n\n    Triangulation<dim, spacedim> triangulation; \n    FE_Q<dim, spacedim>          fe; \n    DoFHandler<dim, spacedim>    dof_handler; \n    MappingQ<dim, spacedim>      mapping; \n\n    SparsityPattern      sparsity_pattern; \n    SparseMatrix<double> system_matrix; \n\n    Vector<double> solution; \n    Vector<double> system_rhs; \n  }; \n// @sect3{Equation data}  \n\n// \u63a5\u4e0b\u6765\uff0c\u8ba9\u6211\u4eec\u5b9a\u4e49\u63cf\u8ff0\u95ee\u9898\u7684\u7cbe\u786e\u89e3\u548c\u53f3\u624b\u8fb9\u7684\u7c7b\u3002\u8fd9\u4e0e step-4 \u548c step-7 \u76f8\u7c7b\u4f3c\uff0c\u5728\u90a3\u91cc\u6211\u4eec\u4e5f\u5b9a\u4e49\u4e86\u6b64\u7c7b\u5bf9\u8c61\u3002\u9274\u4e8e\u4ecb\u7ecd\u4e2d\u7684\u8ba8\u8bba\uff0c\u5b9e\u9645\u7684\u516c\u5f0f\u5e94\u8be5\u662f\u4e0d\u8a00\u81ea\u660e\u7684\u3002\u503c\u5f97\u5173\u6ce8\u7684\u4e00\u70b9\u662f\uff0c\u6211\u4eec\u662f\u5982\u4f55\u4f7f\u7528\u4e00\u822c\u6a21\u677f\u7684\u660e\u786e\u7279\u5316\uff0c\u5206\u522b\u5b9a\u4e492D\u548c3D\u60c5\u51b5\u4e0b\u7684\u503c\u548c\u68af\u5ea6\u51fd\u6570\u7684\u3002\u53e6\u4e00\u79cd\u65b9\u6cd5\u662f\u5b9a\u4e49\u901a\u7528\u6a21\u677f\uff0c\u5e76\u4e3a\u7a7a\u95f4\u7ef4\u5ea6\u7684\u6bcf\u4e2a\u53ef\u80fd\u7684\u503c\u8bbe\u7f6e\u4e00\u4e2a <code>switch</code> \u8bed\u53e5\uff08\u6216\u4e00\u4e32 <code>if</code> s\uff09\u3002\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 = 0) const override; \n\n    virtual Tensor<1, dim> \n    gradient(const Point<dim> & p, \n             const unsigned int component = 0) const override; \n  }; \n\n  template <> \n  double Solution<2>::value(const Point<2> &p, const unsigned int) const \n  { \n    return (-2. * p(0) * p(1)); \n  } \n\n  template <> \n  Tensor<1, 2> Solution<2>::gradient(const Point<2> &p, \n                                     const unsigned int) const \n  { \n    Tensor<1, 2> return_value; \n    return_value[0] = -2. * p(1) * (1 - 2. * p(0) * p(0)); \n    return_value[1] = -2. * p(0) * (1 - 2. * p(1) * p(1)); \n\n    return return_value; \n  } \n\n  template <> \n  double Solution<3>::value(const Point<3> &p, const unsigned int) const \n  { \n    return (std::sin(numbers::PI * p(0)) * std::cos(numbers::PI * p(1)) * \n            exp(p(2))); \n  } \n\n  template <> \n  Tensor<1, 3> Solution<3>::gradient(const Point<3> &p, \n                                     const unsigned int) const \n  { \n    using numbers::PI; \n\n    Tensor<1, 3> return_value; \n\n    return_value[0] = PI * cos(PI * p(0)) * cos(PI * p(1)) * exp(p(2)); \n    return_value[1] = -PI * sin(PI * p(0)) * sin(PI * p(1)) * exp(p(2)); \n    return_value[2] = sin(PI * p(0)) * cos(PI * p(1)) * exp(p(2)); \n\n    return return_value; \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 = 0) const override; \n  }; \n\n  template <> \n  double RightHandSide<2>::value(const Point<2> &p, \n                                 const unsigned int /*component*/) const \n  { \n    return (-8. * p(0) * p(1)); \n  } \n\n  template <> \n  double RightHandSide<3>::value(const Point<3> &p, \n                                 const unsigned int /*component*/) const \n  { \n    using numbers::PI; \n\n    Tensor<2, 3> hessian; \n\n    hessian[0][0] = -PI * PI * sin(PI * p(0)) * cos(PI * p(1)) * exp(p(2)); \n    hessian[1][1] = -PI * PI * sin(PI * p(0)) * cos(PI * p(1)) * exp(p(2)); \n    hessian[2][2] = sin(PI * p(0)) * cos(PI * p(1)) * exp(p(2)); \n\n    hessian[0][1] = -PI * PI * cos(PI * p(0)) * sin(PI * p(1)) * exp(p(2)); \n    hessian[1][0] = -PI * PI * cos(PI * p(0)) * sin(PI * p(1)) * exp(p(2)); \n\n    hessian[0][2] = PI * cos(PI * p(0)) * cos(PI * p(1)) * exp(p(2)); \n    hessian[2][0] = PI * cos(PI * p(0)) * cos(PI * p(1)) * exp(p(2)); \n\n    hessian[1][2] = -PI * sin(PI * p(0)) * sin(PI * p(1)) * exp(p(2)); \n    hessian[2][1] = -PI * sin(PI * p(0)) * sin(PI * p(1)) * exp(p(2)); \n\n    Tensor<1, 3> gradient; \n    gradient[0] = PI * cos(PI * p(0)) * cos(PI * p(1)) * exp(p(2)); \n    gradient[1] = -PI * sin(PI * p(0)) * sin(PI * p(1)) * exp(p(2)); \n    gradient[2] = sin(PI * p(0)) * cos(PI * p(1)) * exp(p(2)); \n\n    Point<3> normal = p; \n    normal /= p.norm(); \n\n    return (-trace(hessian) + 2 * (gradient * normal) + \n            (hessian * normal) * normal); \n  } \n// @sect3{Implementation of the <code>LaplaceBeltramiProblem</code> class}  \n\n// \u5982\u679c\u4f60\u77e5\u9053  step-4  \uff0c\u7a0b\u5e8f\u7684\u5176\u4f59\u90e8\u5206\u5b9e\u9645\u4e0a\u662f\u5f88\u4e0d\u5f15\u4eba\u6ce8\u76ee\u7684\u3002\u6211\u4eec\u7684\u7b2c\u4e00\u6b65\u662f\u5b9a\u4e49\u6784\u9020\u51fd\u6570\uff0c\u8bbe\u7f6e\u6709\u9650\u5143\u548c\u6620\u5c04\u7684\u591a\u9879\u5f0f\u7a0b\u5ea6\uff0c\u5e76\u5c06DoF\u5904\u7406\u7a0b\u5e8f\u4e0e\u4e09\u89d2\u5f62\u5173\u8054\u3002\n\n  template <int spacedim> \n  LaplaceBeltramiProblem<spacedim>::LaplaceBeltramiProblem( \n    const unsigned degree) \n    : fe(degree) \n    , dof_handler(triangulation) \n    , mapping(degree) \n  {} \n// @sect4{LaplaceBeltramiProblem::make_grid_and_dofs}  \n\n// \u4e0b\u4e00\u6b65\u662f\u521b\u5efa\u7f51\u683c\uff0c\u5206\u914d\u81ea\u7531\u5ea6\uff0c\u5e76\u8bbe\u7f6e\u63cf\u8ff0\u7ebf\u6027\u7cfb\u7edf\u7684\u5404\u79cd\u53d8\u91cf\u3002\u6240\u6709\u8fd9\u4e9b\u6b65\u9aa4\u90fd\u662f\u6807\u51c6\u7684\uff0c\u53ea\u6709\u5982\u4f55\u521b\u5efa\u4e00\u4e2a\u63cf\u8ff0\u66f2\u9762\u7684\u7f51\u683c\u9664\u5916\u3002\u6211\u4eec\u53ef\u4ee5\u4e3a\u6211\u4eec\u611f\u5174\u8da3\u7684\u9886\u57df\u751f\u6210\u4e00\u4e2a\u7f51\u683c\uff0c\u7528\u4e00\u4e2a\u7f51\u683c\u751f\u6210\u5668\u751f\u6210\u4e00\u4e2a\u4e09\u89d2\u5f62\uff0c\u7136\u540e\u7528GridIn\u7c7b\u5c06\u5176\u8bfb\u5165\u3002\u6216\u8005\uff0c\u5c31\u50cf\u6211\u4eec\u5728\u8fd9\u91cc\u505a\u7684\u90a3\u6837\uff0c\u6211\u4eec\u4f7f\u7528GridGenerator\u547d\u540d\u7a7a\u95f4\u7684\u8bbe\u65bd\u6765\u751f\u6210\u7f51\u683c\u3002\n\n// \u5177\u4f53\u6765\u8bf4\uff0c\u6211\u4eec\u8981\u505a\u7684\u662f\u8fd9\u6837\u7684\uff08\u5728\u4e0b\u9762\u7684\u5927\u62ec\u53f7\u4e2d\uff09\uff1a\u6211\u4eec\u4f7f\u7528 <code>spacedim</code> \u51fd\u6570\u4e3a\u534a\u5706\u76d8\uff082D\uff09\u6216\u534a\u7403\uff083D\uff09\u751f\u6210\u4e00\u4e2a GridGenerator::half_hyper_ball \u7ef4\u5ea6\u7684\u7f51\u683c\u3002\u8fd9\u4e2a\u51fd\u6570\u5c06\u4f4d\u4e8e\u5706\u76d8/\u7403\u5468\u8fb9\u7684\u6240\u6709\u9762\u7684\u8fb9\u754c\u6307\u6807\u8bbe\u7f6e\u4e3a\u96f6\uff0c\u800c\u5728\u5c06\u6574\u4e2a\u5706\u76d8/\u7403\u5206\u6210\u4e24\u534a\u7684\u76f4\u7ebf\u90e8\u5206\u8bbe\u7f6e\u4e3a\u96f6\u3002\u4e0b\u4e00\u6b65\u662f\u4e3b\u8981\u7684\u4e00\u70b9\u3002 GridGenerator::extract_boundary_mesh \u51fd\u6570\u521b\u5efa\u7684\u7f51\u683c\u662f\u7531\u90a3\u4e9b\u4f5c\u4e3a\u524d\u4e00\u4e2a\u7f51\u683c\u7684\u9762\u7684\u5355\u5143\u7ec4\u6210\u7684\uff0c\u4e5f\u5c31\u662f\u8bf4\uff0c\u5b83\u63cf\u8ff0\u4e86\u539f\u59cb\uff08\u4f53\u79ef\uff09\u7f51\u683c\u7684<i>surface</i>\u5355\u5143\u3002\u7136\u800c\uff0c\u6211\u4eec\u4e0d\u9700\u8981\u6240\u6709\u7684\u9762\uff1a\u53ea\u9700\u8981\u90a3\u4e9b\u5728\u5706\u76d8\u6216\u7403\u7684\u5468\u8fb9\uff0c\u8fb9\u754c\u6307\u793a\u5668\u4e3a\u96f6\u7684\u9762\uff1b\u6211\u4eec\u53ef\u4ee5\u4f7f\u7528\u4e00\u7ec4\u8fb9\u754c\u6307\u793a\u5668\u6765\u9009\u62e9\u8fd9\u4e9b\u5355\u5143\uff0c\u5e76\u4f20\u9012\u7ed9 GridGenerator::extract_boundary_mesh. \u3002\n\n// \u6709\u4e00\u70b9\u9700\u8981\u63d0\u53ca\u3002\u4e3a\u4e86\u5728\u6d41\u5f62\u662f\u5f2f\u66f2\u7684\u60c5\u51b5\u4e0b\u9002\u5f53\u5730\u7ec6\u5316\u8868\u9762\u7f51\u683c\uff08\u7c7b\u4f3c\u4e8e\u7ec6\u5316\u4e0e\u5f2f\u66f2\u8fb9\u754c\u76f8\u90bb\u7684\u5355\u5143\u9762\uff09\uff0c\u4e09\u89d2\u5f62\u5fc5\u987b\u8981\u6709\u4e00\u4e2a\u5bf9\u8c61\u9644\u52a0\u5728\u4e0a\u9762\uff0c\u63cf\u8ff0\u65b0\u9876\u70b9\u5e94\u8be5\u4f4d\u4e8e\u4f55\u5904\u3002\u5982\u679c\u4f60\u4e0d\u9644\u52a0\u8fd9\u6837\u7684\u8fb9\u754c\u5bf9\u8c61\uff0c\u5b83\u4eec\u5c06\u4f4d\u4e8e\u73b0\u6709\u9876\u70b9\u4e4b\u95f4\u7684\u4e2d\u95f4\u4f4d\u7f6e\uff1b\u5982\u679c\u4f60\u6709\u4e00\u4e2a\u5177\u6709\u76f4\u7ebf\u8fb9\u754c\u7684\u57df\uff08\u4f8b\u5982\u591a\u8fb9\u5f62\uff09\uff0c\u8fd9\u662f\u5f88\u5408\u9002\u7684\uff0c\u4f46\u5982\u679c\u50cf\u8fd9\u91cc\u4e00\u6837\uff0c\u6d41\u5f62\u5177\u6709\u66f2\u7387\uff0c\u5219\u4e0d\u5408\u9002\u3002\u56e0\u6b64\uff0c\u4e3a\u4e86\u8ba9\u4e8b\u60c5\u6b63\u5e38\u8fdb\u884c\uff0c\u6211\u4eec\u9700\u8981\u5c06\u6d41\u5f62\u5bf9\u8c61\u9644\u52a0\u5230\u6211\u4eec\u7684\uff08\u8868\u9762\uff09\u4e09\u89d2\u5f62\u4e0a\uff0c\u5176\u65b9\u5f0f\u4e0e\u6211\u4eec\u57281d\u4e2d\u4e3a\u8fb9\u754c\u6240\u505a\u7684\u5927\u81f4\u76f8\u540c\u3002\u6211\u4eec\u521b\u5efa\u8fd9\u6837\u4e00\u4e2a\u5bf9\u8c61\uff0c\u5e76\u5c06\u5176\u9644\u52a0\u5230\u4e09\u89d2\u5256\u9762\u4e0a\u3002\n\n// \u521b\u5efa\u7f51\u683c\u7684\u6700\u540e\u4e00\u6b65\u662f\u5bf9\u5176\u8fdb\u884c\u591a\u6b21\u7ec6\u5316\u3002\u8be5\u51fd\u6570\u7684\u5176\u4f59\u90e8\u5206\u4e0e\u4e4b\u524d\u7684\u6559\u7a0b\u7a0b\u5e8f\u4e2d\u76f8\u540c\u3002\n\n  template <int spacedim> \n  void LaplaceBeltramiProblem<spacedim>::make_grid_and_dofs() \n  { \n    { \n      Triangulation<spacedim> volume_mesh; \n      GridGenerator::half_hyper_ball(volume_mesh); \n\n      std::set<types::boundary_id> boundary_ids; \n      boundary_ids.insert(0); \n\n      GridGenerator::extract_boundary_mesh(volume_mesh, \n                                           triangulation, \n                                           boundary_ids); \n    } \n    triangulation.set_all_manifold_ids(0); \n    triangulation.set_manifold(0, SphericalManifold<dim, spacedim>()); \n\n    triangulation.refine_global(4); \n\n    std::cout << \"Surface mesh has \" << triangulation.n_active_cells() \n              << \" cells.\" << std::endl; \n\n    dof_handler.distribute_dofs(fe); \n\n    std::cout << \"Surface mesh has \" << dof_handler.n_dofs() \n              << \" degrees of freedom.\" << std::endl; \n\n    DynamicSparsityPattern dsp(dof_handler.n_dofs(), dof_handler.n_dofs()); \n    DoFTools::make_sparsity_pattern(dof_handler, dsp); \n    sparsity_pattern.copy_from(dsp); \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// @sect4{LaplaceBeltramiProblem::assemble_system}  \n\n// \u4e0b\u9762\u662f\u8fd9\u4e2a\u7a0b\u5e8f\u7684\u4e2d\u5fc3\u51fd\u6570\uff0c\u5373\u7ec4\u88c5\u4e0e\u8868\u9762\u62c9\u666e\u62c9\u65af\uff08Laplace-Beltrami\u7b97\u5b50\uff09\u76f8\u5bf9\u5e94\u7684\u77e9\u9635\u3002\u4e5f\u8bb8\u4ee4\u4eba\u60ca\u8bb6\u7684\u662f\uff0c\u5b83\u5b9e\u9645\u4e0a\u4e0e\u4f8b\u5982\u5728  step-4  \u4e2d\u8ba8\u8bba\u7684\u666e\u901a\u62c9\u666e\u62c9\u65af\u7b97\u5b50\u770b\u8d77\u6765\u5b8c\u5168\u4e00\u6837\u3002\u5173\u952e\u662f FEValues::shape_grad() \u51fd\u6570\u53d1\u6325\u4e86\u9b54\u529b\uff1a\u5b83\u8fd4\u56de $i$ \u7b2c1\u4e2a\u5f62\u72b6\u51fd\u6570\u5728 $q$ \u7b2c1\u4e2a\u6b63\u4ea4\u70b9\u7684\u8868\u9762\u68af\u5ea6 $\\nabla_K \\phi_i(x_q)$ \u3002\u5176\u4f59\u7684\u4e5f\u4e0d\u9700\u8981\u4efb\u4f55\u6539\u53d8\u3002\n\n  template <int spacedim> \n  void LaplaceBeltramiProblem<spacedim>::assemble_system() \n  { \n    system_matrix = 0; \n    system_rhs    = 0; \n\n    const QGauss<dim>       quadrature_formula(2 * fe.degree); \n    FEValues<dim, spacedim> fe_values(mapping, \n                                      fe, \n                                      quadrature_formula, \n                                      update_values | update_gradients | \n                                        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\n    FullMatrix<double> cell_matrix(dofs_per_cell, dofs_per_cell); \n    Vector<double>     cell_rhs(dofs_per_cell); \n\n    std::vector<double>                  rhs_values(n_q_points); \n    std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell); \n\n    RightHandSide<spacedim> rhs; \n\n    for (const auto &cell : dof_handler.active_cell_iterators()) \n      { \n        cell_matrix = 0; \n        cell_rhs    = 0; \n\n        fe_values.reinit(cell); \n\n        rhs.value_list(fe_values.get_quadrature_points(), rhs_values); \n\n        for (unsigned int i = 0; i < dofs_per_cell; ++i) \n          for (unsigned int j = 0; j < dofs_per_cell; ++j) \n            for (unsigned int q_point = 0; q_point < n_q_points; ++q_point) \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        for (unsigned int i = 0; i < dofs_per_cell; ++i) \n          for (unsigned int q_point = 0; q_point < n_q_points; ++q_point) \n            cell_rhs(i) += fe_values.shape_value(i, q_point) * \n                           rhs_values[q_point] * 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          { \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      } \n\n    std::map<types::global_dof_index, double> boundary_values; \n    VectorTools::interpolate_boundary_values( \n      mapping, dof_handler, 0, Solution<spacedim>(), boundary_values); \n\n    MatrixTools::apply_boundary_values( \n      boundary_values, system_matrix, solution, system_rhs, false); \n  } \n\n//  @sect4{LaplaceBeltramiProblem::solve}  \n\n// \u4e0b\u4e00\u4e2a\u51fd\u6570\u662f\u89e3\u51b3\u7ebf\u6027\u7cfb\u7edf\u7684\u51fd\u6570\u3002\u5728\u8fd9\u91cc\uff0c\u4e5f\u4e0d\u9700\u8981\u505a\u4efb\u4f55\u6539\u53d8\u3002\n\n  template <int spacedim> \n  void LaplaceBeltramiProblem<spacedim>::solve() \n  { \n    SolverControl solver_control(solution.size(), 1e-7 * system_rhs.l2_norm()); \n    SolverCG<Vector<double>> cg(solver_control); \n\n    PreconditionSSOR<SparseMatrix<double>> preconditioner; \n    preconditioner.initialize(system_matrix, 1.2); \n\n    cg.solve(system_matrix, solution, system_rhs, preconditioner); \n  } \n\n//  @sect4{LaplaceBeltramiProblem::output_result}  \n\n// \u8fd9\u662f\u4e00\u4e2a\u4ece\u89e3\u51b3\u65b9\u6848\u4e2d\u751f\u6210\u56fe\u5f62\u8f93\u51fa\u7684\u51fd\u6570\u3002\u5b83\u7684\u5927\u90e8\u5206\u90fd\u662f\u6a21\u677f\u4ee3\u7801\uff0c\u4f46\u6709\u4e24\u70b9\u503c\u5f97\u6307\u51fa\u3002\n\n\n\n// -  DataOut::add_data_vector() \u51fd\u6570\u53ef\u4ee5\u63a5\u53d7\u4e24\u79cd\u5411\u91cf\u3002  \u4e00\u79cd\u662f\u4e4b\u524d\u901a\u8fc7 DataOut::attach_dof_handler(); \u8fde\u63a5\u7684DoFHandler\u5bf9\u8c61\u5b9a\u4e49\u7684\u6bcf\u4e2a\u81ea\u7531\u5ea6\u6709\u4e00\u4e2a\u503c\u7684\u5411\u91cf\uff0c\u53e6\u4e00\u79cd\u662f\u4e09\u89d2\u6d4b\u91cf\u7684\u6bcf\u4e2a\u5355\u5143\u6709\u4e00\u4e2a\u503c\u7684\u5411\u91cf\uff0c\u4f8b\u5982\uff0c\u8f93\u51fa\u6bcf\u4e2a\u5355\u5143\u7684\u4f30\u8ba1\u8bef\u5dee\u3002\u901a\u5e38\uff0cDataOut\u7c7b\u77e5\u9053\u5982\u4f55\u533a\u5206\u8fd9\u4e24\u79cd\u5411\u91cf\uff1a\u81ea\u7531\u5ea6\u51e0\u4e4e\u603b\u662f\u6bd4\u5355\u5143\u683c\u591a\uff0c\u6240\u4ee5\u6211\u4eec\u53ef\u4ee5\u901a\u8fc7\u4e24\u79cd\u5411\u91cf\u7684\u957f\u5ea6\u6765\u533a\u5206\u3002\u6211\u4eec\u5728\u8fd9\u91cc\u4e5f\u53ef\u4ee5\u8fd9\u6837\u505a\uff0c\u4f46\u53ea\u662f\u56e0\u4e3a\u6211\u4eec\u5f88\u5e78\u8fd0\uff1a\u6211\u4eec\u4f7f\u7528\u4e86\u4e00\u4e2a\u534a\u7403\u4f53\u3002\u5982\u679c\u6211\u4eec\u7528\u6574\u4e2a\u7403\u4f53\u4f5c\u4e3a\u57df\u548c $Q_1$ \u5143\u7d20\uff0c\u6211\u4eec\u5c06\u6709\u76f8\u540c\u6570\u91cf\u7684\u5355\u5143\u683c\u4f5c\u4e3a\u9876\u70b9\uff0c\u56e0\u6b64\u8fd9\u4e24\u79cd\u5411\u91cf\u5c06\u6709\u76f8\u540c\u6570\u91cf\u7684\u5143\u7d20\u3002\u4e3a\u4e86\u907f\u514d\u7531\u6b64\u4ea7\u751f\u7684\u6df7\u4e71\uff0c\u6211\u4eec\u5fc5\u987b\u544a\u8bc9 DataOut::add_data_vector() \u51fd\u6570\u6211\u4eec\u6709\u54ea\u79cd\u77e2\u91cf\u3002DoF\u6570\u636e\u3002\u8fd9\u5c31\u662f\u8be5\u51fd\u6570\u7684\u7b2c\u4e09\u4e2a\u53c2\u6570\u7684\u4f5c\u7528\u3002\n\n// -  DataOut::build_patches() \u51fd\u6570\u53ef\u4ee5\u751f\u6210\u7ec6\u5206\u6bcf\u4e2a\u5355\u5143\u7684\u8f93\u51fa\uff0c\u8fd9\u6837\u53ef\u89c6\u5316\u7a0b\u5e8f\u53ef\u4ee5\u66f4\u597d\u5730\u89e3\u51b3\u5f2f\u66f2\u6d41\u5f62\u6216\u66f4\u9ad8\u7684\u591a\u9879\u5f0f\u7a0b\u5ea6\u7684\u5f62\u72b6\u51fd\u6570\u3002\u5728\u8fd9\u91cc\uff0c\u6211\u4eec\u5728\u6bcf\u4e2a\u5750\u6807\u65b9\u5411\u4e0a\u5bf9\u6bcf\u4e2a\u5143\u7d20\u8fdb\u884c\u7ec6\u5206\uff0c\u7ec6\u5206\u7684\u6b21\u6570\u4e0e\u4f7f\u7528\u7684\u6709\u9650\u5143\u7684\u591a\u9879\u5f0f\u7a0b\u5ea6\u76f8\u540c\u3002\n\n  template <int spacedim> \n  void LaplaceBeltramiProblem<spacedim>::output_results() const \n  { \n    DataOut<dim, spacedim> data_out; \n    data_out.attach_dof_handler(dof_handler); \n    data_out.add_data_vector(solution, \n                             \"solution\", \n                             DataOut<dim, spacedim>::type_dof_data); \n    data_out.build_patches(mapping, mapping.get_degree()); \n\n    const std::string filename = \n      \"solution-\" + std::to_string(spacedim) + \"d.vtk\"; \n    std::ofstream output(filename); \n    data_out.write_vtk(output); \n  } \n\n//  @sect4{LaplaceBeltramiProblem::compute_error}  \n\n// \u8fd9\u662f\u6700\u540e\u4e00\u5757\u529f\u80fd\uff1a\u6211\u4eec\u8981\u8ba1\u7b97\u6570\u503c\u89e3\u7684\u8bef\u5dee\u3002\u5b83\u662f\u4e4b\u524d\u5728  step-7  \u4e2d\u5c55\u793a\u548c\u8ba8\u8bba\u7684\u4ee3\u7801\u7684\u9010\u5b57\u590d\u5236\u3002\u6b63\u5982\u4ecb\u7ecd\u4e2d\u63d0\u5230\u7684\uff0c <code>Solution</code> \u7c7b\u63d0\u4f9b\u4e86\u89e3\u51b3\u65b9\u6848\u7684\uff08\u5207\u5411\uff09\u68af\u5ea6\u3002\u4e3a\u4e86\u907f\u514d\u53ea\u8bc4\u4f30\u8d85\u6536\u655b\u70b9\u7684\u8bef\u5dee\uff0c\u6211\u4eec\u9009\u62e9\u4e00\u4e2a\u8db3\u591f\u9ad8\u9636\u7684\u6b63\u4ea4\u89c4\u5219\u3002\n\n  template <int spacedim> \n  void LaplaceBeltramiProblem<spacedim>::compute_error() const \n  { \n    Vector<float> difference_per_cell(triangulation.n_active_cells()); \n    VectorTools::integrate_difference(mapping, \n                                      dof_handler, \n                                      solution, \n                                      Solution<spacedim>(), \n                                      difference_per_cell, \n                                      QGauss<dim>(2 * fe.degree + 1), \n                                      VectorTools::H1_norm); \n\n    double h1_error = VectorTools::compute_global_error(triangulation, \n                                                        difference_per_cell, \n                                                        VectorTools::H1_norm); \n    std::cout << \"H1 error = \" << h1_error << std::endl; \n  } \n\n//  @sect4{LaplaceBeltramiProblem::run}  \n\n// \u6700\u540e\u4e00\u4e2a\u51fd\u6570\u63d0\u4f9b\u4e86\u9876\u5c42\u7684\u903b\u8f91\u3002\u5b83\u7684\u5185\u5bb9\u662f\u4e0d\u8a00\u81ea\u660e\u7684\u3002\n\n  template <int spacedim> \n  void LaplaceBeltramiProblem<spacedim>::run() \n  { \n    make_grid_and_dofs(); \n    assemble_system(); \n    solve(); \n    output_results(); \n    compute_error(); \n  } \n} // namespace Step38 \n// @sect3{The main() function}  \n\n// \u8be5\u7a0b\u5e8f\u7684\u5176\u4f59\u90e8\u5206\u7531 <code>main()</code> \u51fd\u6570\u5360\u636e\u3002\u5b83\u5b8c\u5168\u9075\u5faa\u9996\u6b21\u5728 step-6 \u4e2d\u4ecb\u7ecd\u7684\u4e00\u822c\u5e03\u5c40\uff0c\u5e76\u5728\u968f\u540e\u7684\u6240\u6709\u6559\u7a0b\u7a0b\u5e8f\u4e2d\u4f7f\u7528\u3002\n\nint main() \n{ \n  try \n    { \n      using namespace Step38; \n\n      LaplaceBeltramiProblem<3> laplace_beltrami; \n      laplace_beltrami.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      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": "47d1d83c51379ca002c794afe5b2569dc65ad95a", "size": 16051, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-38/step-38.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-38/step-38.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-38/step-38.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": 35.7483296214, "max_line_length": 412, "alphanum_fraction": 0.6065665691, "num_tokens": 6137, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125793176222, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.49513823278428626}}
{"text": "#include \"robot_interface.hpp\"\n\n#include <iostream>\n#include <cmath>\n#include <ur5/rcg/declarations.h>\n#include <ur5/rcg/forward_dynamics.h>\n\n#include <boost/numeric/odeint/algebra/algebra_dispatcher.hpp>\n#include <boost/numeric/odeint/integrate/integrate.hpp>\n#include <boost/numeric/odeint/integrate/integrate_n_steps.hpp>\n#include <boost/numeric/odeint/stepper/runge_kutta4.hpp>\n#include <boost/numeric/odeint/external/eigen/eigen.hpp>\n\nusing namespace ur5;\nusing namespace ur5::rcg;\nnamespace odeint = boost::numeric::odeint;\n\n\n\nusing state = Eigen::Matrix<double, 12, 1>;\n#define X  block<6,1>(0,0)\n#define XD block<6,1>(6,0)\n\n/* define a structure for holding the block local state. By assigning an\n * instance of this struct to the block private_data pointer (see init), this\n * information becomes accessible within the hook functions.\n */\nstruct robot_interface_info\n{\n\tInertiaProperties ip;\n\tMotionTransforms xm;\n \tForwardDynamics fd;\n\t\n\trobot_interface_info() : ip(), xm(), fd(ip,xm) {\n\t    reset();\n\t}\n\n\tvoid reset() {\n\t    st0.setZero();\n\t    tau.setZero();\n\t    time = 0;\n\t}\n\t\n\tint joint_state_size = 0;\n\tstate st0;\n\tJointState tau;\n    \n    double time = 0;\n\n\t/* this is to have fast access to ports for reading and writing, without\n\t * needing a hash table lookup */\n\tstruct robot_interface_port_cache ports;\n\t\n\t/* The rhs of x' = f(x) */\n    void dyn( const state& st, state& dst_dt, const double time )\n    {\n        JointState qdd;\n        fd.fd(qdd, st.X, st.XD, tau);\n        dst_dt.X  = st.XD;\n        dst_dt.XD = qdd;\n    }\n};\n\ninline robot_interface_info& private_data(ubx_block_t *b)\n{\n\treturn *static_cast<robot_interface_info*>(b->private_data);\n}\n\n\n/* init */\nint robot_interface_init(ubx_block_t *b)\n{\n\tint ret = -1;\n\tlong len = 0;\n\trobot_interface_info *inf;\n\n\t/* allocate memory for the block local state */\n\tif ((inf = new robot_interface_info())  == NULL)\n\t{\n\t\tubx_err(b, \"robot_interface: failed to alloc memory\");\n\t\tret=EOUTOFMEM;\n\t\tgoto out;\n\t}\n\tb->private_data=inf;\n\tupdate_port_cache(b, &inf->ports);\n\t\n\n\tconst int* joint_state_size;\n\tlen = cfg_getptr_int(b, \"joint_state_size\", &joint_state_size);\n\tif (len < 0) goto out;\n\n\tinf->joint_state_size = (len > 0) ? *joint_state_size : 1;\n\n\t/* resize ports */\n\tif (\n\t    ubx_outport_resize(inf->ports.qd, inf->joint_state_size) ||\n\t    ubx_outport_resize(inf->ports.q , inf->joint_state_size) ||\n\t    ubx_inport_resize (inf->ports.tau,inf->joint_state_size) )\n\t{\n\t\tgoto out;\n\t}\n\n\tret=0;\nout:\n\treturn ret;\n}\n\n\nint robot_interface_start(ubx_block_t *b)\n{\n\tint ret = 0;\n\treturn ret;\n}\n\n\n\nvoid robot_interface_stop(ubx_block_t *b)\n{\n    robot_interface_info& data = private_data(b);\n    data.reset();\n}\n\n\n\nvoid robot_interface_cleanup(ubx_block_t *b)\n{\n\tdelete(static_cast<robot_interface_info*>(b->private_data));\n}\n\nvoid normalize_angle(double& angle)\n{\n    angle = atan2(sin(angle), cos(angle));\n}\n\nnamespace pl = std::placeholders;\nvoid robot_interface_step(ubx_block_t *b)\n{\n\trobot_interface_info& data = private_data(b);\n\n\tauto ptr_dyn = std::bind( &robot_interface_info::dyn , data , pl::_1 , pl::_2 , pl::_3 );\n    double dt = 0.001;\n\n    read_double_array(data.ports.tau, data.tau.data(), data.joint_state_size);\n    odeint::runge_kutta4<state> stepper;\n    /*size_t steps = */odeint::integrate_n_steps(stepper, ptr_dyn, data.st0, data.time, /*data.time+dt,*/ dt/10, 10);\n    //std::cout << steps << std::endl;\n    data.time += dt;\n    normalize_angle(data.st0.X(0));\n    normalize_angle(data.st0.X(1));\n    normalize_angle(data.st0.X(2));\n    normalize_angle(data.st0.X(3));\n    normalize_angle(data.st0.X(4));\n    normalize_angle(data.st0.X(5));\n    write_double_array(data.ports.q , data.st0.X.data() , data.joint_state_size);\n    write_double_array(data.ports.qd, data.st0.XD.data(), data.joint_state_size);\n\n    write_double(data.ports.time, &(data.time));\n}\n\n", "meta": {"hexsha": "d8d2a29b6788940ddb495705c8844ca4c9812860", "size": 3853, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "microblx/blocks/ur5-fwddyn/robot_interface.cpp", "max_stars_repo_name": "kmarkus/ublx-ur5_sim", "max_stars_repo_head_hexsha": "51efa12446a7ef9ab5e3e783ce2a6409a3db390f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-07T11:39:31.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-07T11:39:31.000Z", "max_issues_repo_path": "microblx/blocks/ur5-fwddyn/robot_interface.cpp", "max_issues_repo_name": "kmarkus/ublx-ur5_sim", "max_issues_repo_head_hexsha": "51efa12446a7ef9ab5e3e783ce2a6409a3db390f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-11-10T16:03:37.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-10T16:03:37.000Z", "max_forks_repo_path": "microblx/blocks/ur5-fwddyn/robot_interface.cpp", "max_forks_repo_name": "kmarkus/ublx-ur5_sim", "max_forks_repo_head_hexsha": "51efa12446a7ef9ab5e3e783ce2a6409a3db390f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-07T10:57:43.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-07T10:57:43.000Z", "avg_line_length": 24.08125, "max_line_length": 117, "alphanum_fraction": 0.6937451337, "num_tokens": 1084, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381843, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4951032420589439}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\nCopyright (C) 2015 CompatibL\n\nThis file is part of QuantLib, a free-software/open-source library\nfor financial quantitative analysts and developers - http://quantlib.org/\n\nQuantLib is free software: you can redistribute it and/or modify it\nunder the terms of the QuantLib license.  You should have received a\ncopy of the license along with this program; if not, please email\n<quantlib-dev@lists.sf.net>. The license is also available online at\n<http://quantlib.org/license.shtml>.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT\nANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\nFOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n#ifndef cl_adjoint_complex_differentiation_hpp\n#define cl_adjoint_complex_differentiation_hpp\n#pragma once\n\n#include <boost/test/unit_test.hpp>\n\nclass AdjointComplexTest\n{\npublic:\n    static bool testConstructor();\n    static bool testAssign();\n    static bool testImag();\n    static bool testReal();\n    static bool testConj();\n    static bool testAdd();\n    static bool testSub();\n    static bool testMul();\n    static bool testDiv();\n    static bool testAddReal();\n    static bool testSubReal();\n    static bool testMulReal();\n    static bool testDivReal();\n    static bool testArg();\n    static bool testPolar();\n    static bool testPow2();\n    static bool testPowReal();\n    static bool testPowComplex();\n    static bool testNorm();\n    static bool testAbs();\n    static bool testInverse();\n    static bool testSqrt();\n    static bool testExp();\n    static bool testLog();\n    static bool testLog10();\n    static bool testSin();\n    static bool testCos();\n    static bool testTan();\n    static bool testSinh();\n    static bool testCosh();\n    static bool testTanh();\n    static boost::unit_test_framework::test_suite* suite();\n};\n\n#endif", "meta": {"hexsha": "2705bdb6b4c055c72240d889932c8a093f4ca737", "size": 1927, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test-suite-adjoint/adjointcomplextest.hpp", "max_stars_repo_name": "fduffy/QuantLibAdjoint", "max_stars_repo_head_hexsha": "d9d355db4f46824bb5e607e28381943aef994ed4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 41.0, "max_stars_repo_stars_event_min_datetime": "2016-03-19T02:31:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T13:23:20.000Z", "max_issues_repo_path": "test-suite-adjoint/adjointcomplextest.hpp", "max_issues_repo_name": "fduffy/QuantLibAdjoint", "max_issues_repo_head_hexsha": "d9d355db4f46824bb5e607e28381943aef994ed4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test-suite-adjoint/adjointcomplextest.hpp", "max_forks_repo_name": "fduffy/QuantLibAdjoint", "max_forks_repo_head_hexsha": "d9d355db4f46824bb5e607e28381943aef994ed4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2016-03-17T14:14:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T10:33:19.000Z", "avg_line_length": 30.5873015873, "max_line_length": 79, "alphanum_fraction": 0.7192527244, "num_tokens": 437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.49508801233326577}}
{"text": "#define BOOST_TEST_MAIN\n#define BOOST_TEST_DYN_LINK\n\n#define BOOST_TEST_MODULE MatrixVectorTests\n#include <boost/test/unit_test.hpp>\n\n#include <acado/matrix_vector/matrix_vector.hpp>\n\nUSING_NAMESPACE_ACADO\n\nusing namespace std;\n\nBOOST_AUTO_TEST_CASE( vector_ctors )\n{\n\tdouble cc[ 3 ] = {1, 2};\n\tvector< double > dd( 2 ); dd[ 0 ] = -10; dd[ 1 ] = 99;\n\tDVector a, b( 5 ), c(2, cc), d( dd );\n\n    BOOST_REQUIRE( a.getDim() == 0 );\n    BOOST_REQUIRE( b.getDim() == 5 );\n    BOOST_REQUIRE( acadoIsEqual(b( 0 ), 0) );\n    BOOST_REQUIRE( c.getDim() == 2 );\n    BOOST_REQUIRE( acadoIsEqual(c( 1 ), 2) );\n    BOOST_REQUIRE( d.getDim() == 2 );\n    BOOST_REQUIRE( acadoIsEqual(d( 0 ), -10) && acadoIsEqual(d( 1 ), 99) );\n}\n", "meta": {"hexsha": "ad14e0ecf2f8cc5983e64237a2804073d2686b85", "size": 712, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mpc_controller/ros_acado_bridge/ACADOtoolkit/tests/matrix_vector.cpp", "max_stars_repo_name": "kurshakuz/graduation-project", "max_stars_repo_head_hexsha": "352a94c2d3e24ce714460446342b612fbb6d1f52", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-04-07T08:37:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-30T09:38:22.000Z", "max_issues_repo_path": "mpc_controller/ros_acado_bridge/ACADOtoolkit/tests/matrix_vector.cpp", "max_issues_repo_name": "kurshakuz/graduation-project", "max_issues_repo_head_hexsha": "352a94c2d3e24ce714460446342b612fbb6d1f52", "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": "mpc_controller/ros_acado_bridge/ACADOtoolkit/tests/matrix_vector.cpp", "max_forks_repo_name": "kurshakuz/graduation-project", "max_forks_repo_head_hexsha": "352a94c2d3e24ce714460446342b612fbb6d1f52", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-03-01T14:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-21T12:34:33.000Z", "avg_line_length": 26.3703703704, "max_line_length": 75, "alphanum_fraction": 0.6502808989, "num_tokens": 232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.685949467848392, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.49507937238857347}}
{"text": "#include \"linear_elasticity.h\"\n\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/fe/fe_tools.h>\n\n#include <deal.II/grid/grid_out.h>\n#include <deal.II/grid/grid_refinement.h>\n\n#include <deal.II/lac/sparse_direct.h>\n#include <deal.II/lac/trilinos_precondition.h>\n\n#include <deal.II/meshworker/copy_data.h>\n#include <deal.II/meshworker/scratch_data.h>\n\n#include <deal.II/numerics/error_estimator.h>\n\nusing namespace dealii;\n\ntemplate<int dim>\nLinearElasticity<dim>::LinearElasticity() :\n\t\tmpi_communicator(MPI_COMM_WORLD), pcout(std::cout,\n\t\t\t\t(Utilities::MPI::this_mpi_process(mpi_communicator) == 0)), timer(\n\t\t\t\tpcout, TimerOutput::summary, TimerOutput::cpu_and_wall_times), n_components(\n\t\t\t\tdim), triangulation(mpi_communicator,\n\t\t\t\ttypename Triangulation<dim>::MeshSmoothing(\n\t\t\t\t\t\tTriangulation<dim>::smoothing_on_refinement\n\t\t\t\t\t\t\t\t| Triangulation<dim>::smoothing_on_coarsening)), dof_handler(\n\t\t\t\ttriangulation), forcing_term(n_components), exact_solution(\n\t\t\t\tn_components), dirichlet_boundary_condition(n_components), neumann_boundary_condition(\n\t\t\t\tn_components), error_table(\n\t\t\t\tstd::vector<std::string>(n_components, \"u\")), solver_control(\n\t\t\t\t\"Solver control\", 1000, 1e-12, 1e-12), velocity(0) {\n\tTimerOutput::Scope timer_section(timer, \"constructor\");\n\tadd_parameter(\"Finite element space\", fe_name);\n\tadd_parameter(\"Mapping degree\", mapping_degree);\n\tadd_parameter(\"Number of global refinements\", n_refinements);\n\tadd_parameter(\"Output filename\", output_filename);\n\tadd_parameter(\"Forcing term expression\", forcing_term_expression);\n\tadd_parameter(\"Dirichlet boundary condition expression\",\n\t\t\tdirichlet_boundary_conditions_expression);\n\tadd_parameter(\"Coefficient expression\", coefficient_expression);\n\tadd_parameter(\"Number of threads\", number_of_threads);\n\tadd_parameter(\"Exact solution expression\", exact_solution_expression);\n\tadd_parameter(\"Neumann boundary condition expression\",\n\t\t\tneumann_boundary_conditions_expression);\n\n\tadd_parameter(\"Local pre-refinement grid size expression\",\n\t\t\tpre_refinement_expression);\n\n\tadd_parameter(\"Dirichlet boundary ids\", dirichlet_ids);\n\tadd_parameter(\"Neumann boundary ids\", neumann_ids);\n\n\tadd_parameter(\"Problem constants\", constants);\n\tadd_parameter(\"Grid generator function\", grid_generator_function);\n\tadd_parameter(\"Grid generator arguments\", grid_generator_arguments);\n\tadd_parameter(\"Number of refinement cycles\", n_refinement_cycles);\n\n\tadd_parameter(\"Estimator type\", estimator_type, \"\", this->prm,\n\t\t\tPatterns::Selection(\"exact|kelly|residual\"));\n\n\tadd_parameter(\"Marking strategy\", marking_strategy, \"\", this->prm,\n\t\t\tPatterns::Selection(\"global|fixed_fraction|fixed_number\"));\n\n\tadd_parameter(\"Coarsening and refinement factors\",\n\t\t\tcoarsening_and_refinement_factors);\n\n\tadd_parameter(\"Use direct solver\", use_direct_solver);\n\tadd_parameter(\"Linear elasticity mu\", mu);\n\tadd_parameter(\"Linear elasticity lambda\", lambda);\n\n\tthis->prm.enter_subsection(\"Error table\");\n\terror_table.add_parameters(this->prm);\n\tthis->prm.leave_subsection();\n}\n\ntemplate<int dim>\nvoid LinearElasticity<dim>::initialize(const std::string &filename) {\n\tTimerOutput::Scope timer_section(timer, \"initialize\");\n\tParameterAcceptor::initialize(filename, \"last_used_parameters.prm\",\n\t\t\tParameterHandler::Short);\n}\n\ntemplate<int dim>\nvoid LinearElasticity<dim>::parse_string(const std::string &parameters) {\n\tTimerOutput::Scope timer_section(timer, \"parse_string\");\n\tParameterAcceptor::prm.parse_input_from_string(parameters);\n\tParameterAcceptor::parse_all_parameters();\n}\n\ntemplate<int dim>\nvoid LinearElasticity<dim>::make_grid() {\n\tTimerOutput::Scope timer_section(timer, \"make_grid\");\n\n\tconstants[\"mu\"] = mu;\n\tconstants[\"lambda\"] = lambda;\n\n\tconst auto vars = dim == 1 ? \"x\" : dim == 2 ? \"x,y\" : \"x,y,z\";\n\tpre_refinement.initialize(vars, pre_refinement_expression, constants);\n\tGridGenerator::generate_from_name_and_arguments(triangulation,\n\t\t\tgrid_generator_function, grid_generator_arguments);\n\n\tfor (unsigned int i = 0; i < n_refinements; ++i) {\n\t\tfor (const auto &cell : triangulation.active_cell_iterators())\n\t\t\tif (pre_refinement.value(cell->center()) < cell->diameter())\n\t\t\t\tcell->set_refine_flag();\n\t\ttriangulation.execute_coarsening_and_refinement();\n\t}\n\n\tstd::cout << \"Number of active cells: \" << triangulation.n_active_cells()\n\t\t\t<< std::endl;\n}\n\ntemplate<int dim>\nvoid LinearElasticity<dim>::refine_grid() {\n\tTimerOutput::Scope timer_section(timer, \"refine_grid\");\n\t// Cells have been marked in the mark() method.\n\ttriangulation.execute_coarsening_and_refinement();\n}\n\ntemplate<int dim>\nvoid LinearElasticity<dim>::setup_system() {\n\tTimerOutput::Scope timer_section(timer, \"setup_system\");\n\tif (!fe) {\n\t\tfe = FETools::get_fe_by_name<dim>(fe_name);\n\t\tmapping = std::make_unique < MappingQGeneric < dim >> (mapping_degree);\n\t\tconst auto vars = dim == 1 ? \"x\" : dim == 2 ? \"x,y\" : \"x,y,z\";\n\t\tforcing_term.initialize(vars, forcing_term_expression, constants);\n\t\tcoefficient.initialize(vars, coefficient_expression, constants);\n\t\texact_solution.initialize(vars, exact_solution_expression, constants);\n\n\t\tdirichlet_boundary_condition.initialize(vars,\n\t\t\t\tdirichlet_boundary_conditions_expression, constants);\n\n\t\tneumann_boundary_condition.initialize(vars,\n\t\t\t\tneumann_boundary_conditions_expression, constants);\n\t}\n\n\tdof_handler.distribute_dofs(*fe);\n\n\tlocally_owned_dofs = dof_handler.locally_owned_dofs();\n\tDoFTools::extract_locally_relevant_dofs(dof_handler, locally_relevant_dofs);\n\n\tpcout << \"Number of degrees of freedom: \" << dof_handler.n_dofs()\n\t\t\t<< std::endl;\n\n\tconstraints.clear();\n\tconstraints.reinit(locally_relevant_dofs);\n\tDoFTools::make_hanging_node_constraints(dof_handler, constraints);\n\n\tfor (const auto &id : dirichlet_ids)\n\t\tVectorTools::interpolate_boundary_values(*mapping, dof_handler, id,\n\t\t\t\tdirichlet_boundary_condition, constraints);\n\tconstraints.close();\n\n\tDynamicSparsityPattern dsp(dof_handler.n_dofs());\n\tDoFTools::make_sparsity_pattern(dof_handler, dsp, constraints, false);\n\tSparsityTools::distribute_sparsity_pattern(dsp, locally_owned_dofs,\n\t\t\tmpi_communicator, locally_relevant_dofs);\n\n\tsystem_matrix.reinit(locally_owned_dofs, locally_owned_dofs, dsp,\n\t\t\tmpi_communicator);\n\n\tsolution.reinit(locally_owned_dofs, mpi_communicator);\n\tsystem_rhs.reinit(locally_owned_dofs, mpi_communicator);\n\n\tlocally_relevant_solution.reinit(locally_owned_dofs, locally_relevant_dofs,\n\t\t\tmpi_communicator);\n\n\terror_per_cell.reinit(triangulation.n_active_cells());\n}\n\ntemplate<int dim>\nvoid LinearElasticity<dim>::assemble_system_one_cell(\n\t\tconst typename DoFHandler<dim>::active_cell_iterator &cell,\n\t\tScratchData &scratch, CopyData &copy) {\n\tauto &cell_matrix = copy.matrices[0];\n\tauto &cell_rhs = copy.vectors[0];\n\n\tcell->get_dof_indices(copy.local_dof_indices[0]);\n\n\tconst auto &fe_values = scratch.reinit(cell);\n\tcell_matrix = 0;\n\tcell_rhs = 0;\n\n\tfor (const unsigned int q_index : fe_values.quadrature_point_indices()) {\n\t\tfor (const unsigned int i : fe_values.dof_indices()) {\n\t\t\tconst auto eps_v = fe_values[velocity].symmetric_gradient(i,\n\t\t\t\t\tq_index); // SymmetricTensor<2,dim>\n\t\t\tconst auto div_v = fe_values[velocity].divergence(i, q_index); // double\n\n\t\t\tfor (const unsigned int j : fe_values.dof_indices()) {\n\t\t\t\tconst auto eps_u = fe_values[velocity].symmetric_gradient(j,\n\t\t\t\t\t\tq_index); // SymmetricTensor<2,dim>\n\t\t\t\tconst auto div_u = fe_values[velocity].divergence(j, q_index); // double\n\n\t\t\t\tcell_matrix(i, j) += (mu * scalar_product(eps_v, eps_u)\n\t\t\t\t\t\t+ lambda * div_u * div_v) * fe_values.JxW(q_index); // dx\n\t\t\t}\n\t\t\tfor (const unsigned int i : fe_values.dof_indices()) {\n\t\t\t\tconst auto comp_i = this->fe->system_to_component_index(i).first;\n\t\t\t\tcell_rhs(i) += (fe_values.shape_value(i, q_index) * // phi_i(x_q)\n\t\t\t\t\t\tthis->forcing_term.value(\n\t\t\t\t\t\t\t\tfe_values.quadrature_point(q_index), comp_i) * // f(x_q)\n\t\t\t\t\t\tfe_values.JxW(q_index));           // dx\n\t\t\t}\n\t\t}\n\t}\n\n\tif (cell->at_boundary())\n\t\t//  for(const auto face: cell->face_indices())\n\t\tfor (unsigned int f = 0; f < GeometryInfo<dim>::faces_per_cell; ++f)\n\t\t\tif (neumann_ids.find(cell->face(f)->boundary_id())\n\t\t\t\t\t!= neumann_ids.end()) {\n\t\t\t\tauto &fe_face_values = scratch.reinit(cell, f);\n\t\t\t\tfor (const unsigned int q_index : fe_face_values.quadrature_point_indices())\n\t\t\t\t\tfor (const unsigned int i : fe_face_values.dof_indices())\n\t\t\t\t\t\tcell_rhs(i) += fe_face_values.shape_value(i, q_index)\n\t\t\t\t\t\t\t\t* neumann_boundary_condition.value(\n\t\t\t\t\t\t\t\t\t\tfe_face_values.quadrature_point(\n\t\t\t\t\t\t\t\t\t\t\t\tq_index))\n\t\t\t\t\t\t\t\t* fe_face_values.JxW(q_index);\n\t\t\t}\n}\n\ntemplate<int dim>\nvoid LinearElasticity<dim>::copy_one_cell(const CopyData &copy) {\n\tconstraints.distribute_local_to_global(copy.matrices[0], copy.vectors[0],\n\t\t\tcopy.local_dof_indices[0], system_matrix, system_rhs);\n}\n\ntemplate<int dim>\nvoid LinearElasticity<dim>::assemble_system_on_range(\n\t\tconst typename DoFHandler<dim>::active_cell_iterator &begin,\n\t\tconst typename DoFHandler<dim>::active_cell_iterator &end) {\n\tQGauss<dim> quadrature_formula(fe->degree + 1);\n\tQGauss<dim - 1> face_quadrature_formula(fe->degree + 1);\n\n\tScratchData scratch(*mapping, *fe, quadrature_formula,\n\t\t\tupdate_values | update_gradients | update_quadrature_points\n\t\t\t\t\t| update_JxW_values, face_quadrature_formula,\n\t\t\tupdate_values | update_quadrature_points | update_JxW_values);\n\n\tCopyData copy(fe->n_dofs_per_cell());\n\n\tstatic Threads::Mutex assemble_mutex;\n\n\tfor (auto cell = begin; cell != end; ++cell) {\n\t\tassemble_system_one_cell(cell, scratch, copy);\n\t\tassemble_mutex.lock();\n\t\tcopy_one_cell(copy);\n\t\tassemble_mutex.unlock();\n\t}\n}\n\ntemplate<int dim>\nvoid LinearElasticity<dim>::assemble_system() {\n\tTimerOutput::Scope timer_section(timer, \"assemble_system\");\n\tQGauss<dim> quadrature_formula(fe->degree + 1);\n\tQGauss<dim - 1> face_quadrature_formula(fe->degree + 1);\n\n\tScratchData scratch(*mapping, *fe, quadrature_formula,\n\t\t\tupdate_values | update_gradients | update_quadrature_points\n\t\t\t\t\t| update_JxW_values, face_quadrature_formula,\n\t\t\tupdate_values | update_quadrature_points | update_JxW_values);\n\n\tCopyData copy(fe->n_dofs_per_cell());\n\n\tfor (const auto &cell : dof_handler.active_cell_iterators())\n\t\tif (cell->is_locally_owned()) {\n\t\t\tassemble_system_one_cell(cell, scratch, copy);\n\t\t\tcopy_one_cell(copy);\n\t\t}\n\n\tsystem_matrix.compress(VectorOperation::add);\n\tsystem_rhs.compress(VectorOperation::add);\n}\n\ntemplate<int dim>\nvoid LinearElasticity<dim>::solve() {\n\tTimerOutput::Scope timer_section(timer, \"solve\");\n\t// if (use_direct_solver == true)\n\t//   {\n\t//     SparseDirectUMFPACK system_matrix_inverse;\n\t//     system_matrix_inverse.initialize(system_matrix);\n\t//     system_matrix_inverse.vmult(solution, system_rhs);\n\t//   }\n\t// else\n\t//   {\n\tSolverCG<LA::MPI::Vector> solver(solver_control);\n\tLA::MPI::PreconditionAMG amg;\n\tamg.initialize(system_matrix);\n\tsolver.solve(system_matrix, solution, system_rhs, amg);\n\tconstraints.distribute(solution);\n\n\tlocally_relevant_solution = solution;\n}\n\ntemplate<int dim>\nvoid LinearElasticity<dim>::estimate() {\n\tTimerOutput::Scope timer_section(timer, \"estimate\");\n\tif (estimator_type == \"exact\") {\n\t\terror_per_cell = 0;\n\t\tQGauss<dim> quad(fe->degree + 1);\n\t\tVectorTools::integrate_difference(*mapping, dof_handler,\n\t\t\t\tlocally_relevant_solution, exact_solution, error_per_cell, quad,\n\t\t\t\tVectorTools::H1_seminorm);\n\t} else if (estimator_type == \"kelly\") {\n\t\tstd::map<types::boundary_id, const Function<dim>*> neumann;\n\t\tfor (const auto id : neumann_ids)\n\t\t\tneumann[id] = &neumann_boundary_condition;\n\n\t\tQGauss<dim - 1> face_quad(fe->degree + 1);\n\t\tKellyErrorEstimator<dim>::estimate(*mapping, dof_handler, face_quad,\n\t\t\t\tneumann, locally_relevant_solution, error_per_cell,\n\t\t\t\tComponentMask(), &coefficient);\n\t} else if (estimator_type == \"residual\") {\n\t\t// h_T || f+\\Delta u_h ||_0,T\n\t\t// + \\sum over faces\n\t\t// 1/2 (h_F)^{1/2} || [n.\\nabla u_h] ||_0,F\n\n\t\tQGauss<dim - 1> face_quad(fe->degree + 1);\n\t\tQGauss<dim> quad(fe->degree + 1);\n\n\t\tstd::map<types::boundary_id, const Function<dim>*> neumann;\n\t\tfor (const auto id : neumann_ids)\n\t\t\tneumann[id] = &neumann_boundary_condition;\n\n\t\tKellyErrorEstimator<dim>::estimate(*mapping, dof_handler, face_quad,\n\t\t\t\tneumann, locally_relevant_solution, error_per_cell,\n\t\t\t\tComponentMask(), &coefficient);\n\n\t\tFEValues<dim> fe_values(*mapping, *fe, quad,\n\t\t\t\tupdate_hessians | update_JxW_values | update_quadrature_points);\n\n\t\tstd::vector<double> local_laplacians(quad.size());\n\n\t\tdouble residual_L2_norm = 0;\n\n\t\tunsigned int cell_index = 0;\n\t\tfor (const auto &cell : dof_handler.active_cell_iterators()) {\n\t\t\tfe_values.reinit(cell);\n\n\t\t\tfe_values.get_function_laplacians(locally_relevant_solution,\n\t\t\t\t\tlocal_laplacians);\n\t\t\tresidual_L2_norm = 0;\n\t\t\tfor (const auto q_index : fe_values.quadrature_point_indices()) {\n\t\t\t\tconst auto arg = (local_laplacians[q_index]\n\t\t\t\t\t\t+ forcing_term.value(\n\t\t\t\t\t\t\t\tfe_values.quadrature_point(q_index)));\n\t\t\t\tresidual_L2_norm += arg * arg * fe_values.JxW(q_index);\n\t\t\t}\n\t\t\terror_per_cell[cell_index] += cell->diameter()\n\t\t\t\t\t* std::sqrt(residual_L2_norm);\n\n\t\t\t++cell_index;\n\t\t}\n\t} else {\n\t\tAssertThrow(false, ExcNotImplemented());\n\t}\n\tauto global_estimator = error_per_cell.l2_norm();\n\terror_table.add_extra_column(\"estimator\", [global_estimator]() {\n\t\treturn global_estimator;\n\t});\n\terror_table.error_from_exact(*mapping, dof_handler,\n\t\t\tlocally_relevant_solution, exact_solution);\n}\n\ntemplate<int dim>\nvoid LinearElasticity<dim>::mark() {\n\tTimerOutput::Scope timer_section(timer, \"mark\");\n\tif (marking_strategy == \"global\") {\n\t\tfor (const auto &cell : triangulation.active_cell_iterators())\n\t\t\tcell->set_refine_flag();\n\t} else if (marking_strategy == \"fixed_fraction\") {\n\t\tparallel::distributed::GridRefinement::refine_and_coarsen_fixed_fraction(\n\t\t\t\ttriangulation, error_per_cell,\n\t\t\t\tcoarsening_and_refinement_factors.second,\n\t\t\t\tcoarsening_and_refinement_factors.first);\n\t} else if (marking_strategy == \"fixed_number\") {\n\t\tparallel::distributed::GridRefinement::refine_and_coarsen_fixed_number(\n\t\t\t\ttriangulation, error_per_cell,\n\t\t\t\tcoarsening_and_refinement_factors.second,\n\t\t\t\tcoarsening_and_refinement_factors.first);\n\t} else {\n\t\tAssert(false, ExcInternalError());\n\t}\n}\n\ntemplate<int dim>\nvoid LinearElasticity<dim>::output_results(const unsigned cycle) const {\n\tTimerOutput::Scope timer_section(timer, \"output_results\");\n\tDataOut<dim> data_out;\n\tDataOutBase::VtkFlags flags;\n\tflags.write_higher_order_cells = true;\n\tdata_out.set_flags(flags);\n\tdata_out.attach_dof_handler(dof_handler);\n\tstd::vector<std::string> names(n_components, \"u\");\n\tstd::vector<DataComponentInterpretation::DataComponentInterpretation> interpretation(\n\t\t\tn_components,\n\t\t\tDataComponentInterpretation::component_is_part_of_vector);\n\n\tdata_out.add_data_vector(locally_relevant_solution, names,\n\t\t\tDataOut<dim>::type_dof_data, interpretation);\n\t// auto interpolated_exact = solution;\n\t// VectorTools::interpolate(*mapping,\n\t//                          dof_handler,\n\t//                          exact_solution,\n\t//                          interpolated_exact);\n\t// auto locally_interpolated_exact = interpolated_exact;\n\n\t// data_out.add_data_vector(interpolated_exact, \"exact\");\n\tdata_out.add_data_vector(error_per_cell, \"estimator\");\n\tdata_out.build_patches(*mapping, std::max(mapping_degree, fe->degree),\n\t\t\tDataOut<dim>::curved_inner_cells);\n\tstd::string fname = output_filename + \"_\" + std::to_string(cycle) + \".vtu\";\n\tdata_out.write_vtu_in_parallel(fname, mpi_communicator);\n\n\tGridOut go;\n\tgo.write_mesh_per_processor_as_vtu(triangulation,\n\t\t\t\"tria_\" + std::to_string(cycle), false, true);\n}\n\ntemplate<int dim>\nvoid LinearElasticity<dim>::print_system_info() {\n\tif (number_of_threads != -1 && number_of_threads > 0)\n\t\tMultithreadInfo::set_thread_limit(\n\t\t\t\tstatic_cast<unsigned int>(number_of_threads));\n\n\tstd::cout << \"Number of cores  : \" << MultithreadInfo::n_cores()\n\t\t\t<< std::endl << \"Number of threads: \"\n\t\t\t<< MultithreadInfo::n_threads() << std::endl;\n}\n\ntemplate<int dim>\nvoid LinearElasticity<dim>::run() {\n\tprint_system_info();\n\tmake_grid();\n\tfor (unsigned int cycle = 0; cycle < n_refinement_cycles; ++cycle) {\n\t\tsetup_system();\n\t\tassemble_system();\n\t\tsolve();\n\t\testimate();\n\t\toutput_results(cycle);\n\t\tif (cycle < n_refinement_cycles - 1) {\n\t\t\tmark();\n\t\t\trefine_grid();\n\t\t}\n\t}\n\tif (pcout.is_active())\n\t\terror_table.output_table(std::cout);\n}\n\ntemplate class LinearElasticity<1> ;\ntemplate class LinearElasticity<2> ;\ntemplate class LinearElasticity<3> ;\n", "meta": {"hexsha": "8b017079663a109ba296c85c673afae542ef60ce", "size": 16468, "ext": "cc", "lang": "C++", "max_stars_repo_path": "source/linear_elasticity.cc", "max_stars_repo_name": "dealii-courses/sissa-mhpc-lab-09-fdrmrc", "max_stars_repo_head_hexsha": "680ef4ede8827a4846e0b556a7a307080931aa2c", "max_stars_repo_licenses": ["MIT"], "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/linear_elasticity.cc", "max_issues_repo_name": "dealii-courses/sissa-mhpc-lab-09-fdrmrc", "max_issues_repo_head_hexsha": "680ef4ede8827a4846e0b556a7a307080931aa2c", "max_issues_repo_licenses": ["MIT"], "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/linear_elasticity.cc", "max_forks_repo_name": "dealii-courses/sissa-mhpc-lab-09-fdrmrc", "max_forks_repo_head_hexsha": "680ef4ede8827a4846e0b556a7a307080931aa2c", "max_forks_repo_licenses": ["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.9563318777, "max_line_length": 90, "alphanum_fraction": 0.747874666, "num_tokens": 4196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975978, "lm_q2_score": 0.685949467848392, "lm_q1q2_score": 0.4950793682830294}}
{"text": "#pragma once\n\n#include <Eigen/Core>\n\nnamespace ipc {\n\n/// @brief Closest pair between a point and edge.\nenum class PointEdgeDistanceType {\n    P_E0, ///< The point is closest to edge vertex zero.\n    P_E1, ///< The point is closest to edge vertex one.\n    P_E   ///< The point is closest to the interior of the edge.\n};\n\n/// @brief Closest pair between a point and triangle.\nenum class PointTriangleDistanceType {\n    P_T0, ///< The point is closest to triangle vertex zero.\n    P_T1, ///< The point is closest to triangle vertex one.\n    P_T2, ///< The point is closest to triangle vertex two.\n    P_E0, ///< The point is closest to triangle edge zero (vertex zero to one).\n    P_E1, ///< The point is closest to triangle edge one (vertex one to two).\n    P_E2, ///< The point is closest to triangle edge two (vertex two to zero).\n    P_T   ///< The point is closest to the interior of the triangle.\n};\n\n/// @brief Closest pair between two edges.\nenum class EdgeEdgeDistanceType {\n    EA0_EB0, ///< The edges are closest at vertex 0 of edge A and 0 of edge B.\n    EA0_EB1, ///< The edges are closest at vertex 0 of edge A and 1 of edge B.\n    EA1_EB0, ///< The edges are closest at vertex 1 of edge A and 0 of edge B.\n    EA1_EB1, ///< The edges are closest at vertex 1 of edge A and 1 of edge B.\n    EA_EB0, ///< The edges are closest at the interior of edge A and vertex 0 of\n            ///< edge B.\n    EA_EB1, ///< The edges are closest at the interior of edge A and vertex 1 of\n            ///< edge B.\n    EA0_EB, ///< The edges are closest at vertex 0 of edge A and the interior of\n            ///< edge B.\n    EA1_EB, ///< The edges are closest at vertex 1 of edge A and the interior of\n            ///< edge B.\n    EA_EB   ///< The edges are closest at an interior point of edge A and B.\n};\n\n/// @brief Determine the closest pair between a point and edge.\n/// @param p The point.\n/// @param e0 The first vertex of the edge.\n/// @param e1 The second vertex of the edge.\n/// @return The distance type of the point-edge pair.\ntemplate <typename DerivedP, typename DerivedE0, typename DerivedE1>\nPointEdgeDistanceType point_edge_distance_type(\n    const Eigen::MatrixBase<DerivedP>& p,\n    const Eigen::MatrixBase<DerivedE0>& e0,\n    const Eigen::MatrixBase<DerivedE1>& e1);\n\n/// @brief Determine the closest pair between a point and triangle.\n/// @param p The point.\n/// @param t0 The first vertex of the triangle.\n/// @param t1 The second vertex of the triangle.\n/// @param t2 The third vertex of the triangle.\n/// @return The distance type of the point-triangle pair.\ntemplate <\n    typename DerivedP,\n    typename DerivedT0,\n    typename DerivedT1,\n    typename DerivedT2>\nPointTriangleDistanceType point_triangle_distance_type(\n    const Eigen::MatrixBase<DerivedP>& p,\n    const Eigen::MatrixBase<DerivedT0>& t0,\n    const Eigen::MatrixBase<DerivedT1>& t1,\n    const Eigen::MatrixBase<DerivedT2>& t2);\n\n/// @brief Determine the closest pair between two edges.\n/// @param ea0 The first vertex of the first edge.\n/// @param ea1 The second vertex of the first edge.\n/// @param eb0 The first vertex of the second edge.\n/// @param eb1 The second vertex of the second edge.\n/// @return The distance type of the edge-edge pair.\ntemplate <\n    typename DerivedEA0,\n    typename DerivedEA1,\n    typename DerivedEB0,\n    typename DerivedEB1>\nEdgeEdgeDistanceType edge_edge_distance_type(\n    const Eigen::MatrixBase<DerivedEA0>& ea0,\n    const Eigen::MatrixBase<DerivedEA1>& ea1,\n    const Eigen::MatrixBase<DerivedEB0>& eb0,\n    const Eigen::MatrixBase<DerivedEB1>& eb1);\n\n} // namespace ipc\n\n#include <ipc/distance/distance_type.tpp>\n", "meta": {"hexsha": "8feb9cdeeba1a7e3dd748029f0dc72af8383dd8e", "size": 3639, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/distance/distance_type.hpp", "max_stars_repo_name": "ipc-sim/ipc-toolk", "max_stars_repo_head_hexsha": "81873d0288810e30166d871419da4104329860e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 61.0, "max_stars_repo_stars_event_min_datetime": "2020-08-04T21:08:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T02:24:31.000Z", "max_issues_repo_path": "src/distance/distance_type.hpp", "max_issues_repo_name": "dbelgrod/ipc-toolkit", "max_issues_repo_head_hexsha": "0b7ca9b5f867db63bd68dd02ce54a9d00b0fc337", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-10-12T05:54:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-10T18:39:30.000Z", "max_forks_repo_path": "src/distance/distance_type.hpp", "max_forks_repo_name": "dbelgrod/ipc-toolkit", "max_forks_repo_head_hexsha": "0b7ca9b5f867db63bd68dd02ce54a9d00b0fc337", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2020-11-26T12:47:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T04:55:49.000Z", "avg_line_length": 40.4333333333, "max_line_length": 80, "alphanum_fraction": 0.6952459467, "num_tokens": 932, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432182679956, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.4950793672267906}}
{"text": "/**\n * \\ file TanhShaperFilter.cpp\n */\n\n#include <array>\n#include <fstream>\n\n#include <ATK/config.h>\n\n#include <ATK/Distortion/TanhShaperFilter.h>\n#include <ATK/Mock/SimpleSinusGeneratorFilter.h>\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_NO_MAIN\n#include <boost/test/unit_test.hpp>\n\nconstexpr gsl::index PROCESSSIZE = 1000;\n\nBOOST_AUTO_TEST_CASE( TanhShaperFilter_coeff_test )\n{\n  ATK::TanhShaperFilter<double> shaper;\n  shaper.set_coefficient(10);\n  BOOST_CHECK_EQUAL(shaper.get_coefficient(), 10);\n}\n\nBOOST_AUTO_TEST_CASE( TanhShaperFilter_coeff_range_test )\n{\n  ATK::TanhShaperFilter<double> shaper;\n  BOOST_CHECK_THROW(shaper.set_coefficient(0), std::out_of_range);\n}\n\nBOOST_AUTO_TEST_CASE( TanhShaperFilter_const_sin1k )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(1000);\n  \n  ATK::TanhShaperFilter<double> shaper;\n  shaper.set_input_sampling_rate(1024*64);\n  shaper.set_output_sampling_rate(1024*64);\n  \n  shaper.set_input_port(0, generator, 0);\n  shaper.process(PROCESSSIZE);\n  \n  auto sin = generator.get_output_array(0);\n  auto array = shaper.get_output_array(0);\n  \n  for(size_t i = 0; i < PROCESSSIZE; ++i)\n  {\n    BOOST_CHECK_CLOSE(array[i], std::tanh(sin[i]), 0.00001);\n  }\n}\n\nBOOST_AUTO_TEST_CASE( TanhShaperFilter_const_2_sin1k )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(1000);\n  \n  ATK::TanhShaperFilter<double> shaper;\n  shaper.set_input_sampling_rate(1024*64);\n  shaper.set_output_sampling_rate(1024*64);\n  shaper.set_coefficient(2);\n  \n  shaper.set_input_port(0, generator, 0);\n  shaper.process(PROCESSSIZE);\n  \n  auto sin = generator.get_output_array(0);\n  auto array = shaper.get_output_array(0);\n  \n  for(size_t i = 0; i < PROCESSSIZE; ++i)\n  {\n    BOOST_CHECK_CLOSE(array[i], std::tanh(2 * sin[i]) / 2, 0.00001);\n  }\n}\n", "meta": {"hexsha": "f8560ea041a5bd470ef1cfc4139f010bc04d26c0", "size": 1979, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/Distortion/TanhWaveShaperFilter.cpp", "max_stars_repo_name": "D-J-Roberts/AudioTK", "max_stars_repo_head_hexsha": "accf009d7238f32702eb1d5ee23c5148fc68e3bd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 249.0, "max_stars_repo_stars_event_min_datetime": "2015-01-05T13:36:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T18:47:46.000Z", "max_issues_repo_path": "tests/Distortion/TanhWaveShaperFilter.cpp", "max_issues_repo_name": "D-J-Roberts/AudioTK", "max_issues_repo_head_hexsha": "accf009d7238f32702eb1d5ee23c5148fc68e3bd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 22.0, "max_issues_repo_issues_event_min_datetime": "2015-07-28T15:20:24.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-11T14:18:19.000Z", "max_forks_repo_path": "tests/Distortion/TanhWaveShaperFilter.cpp", "max_forks_repo_name": "D-J-Roberts/AudioTK", "max_forks_repo_head_hexsha": "accf009d7238f32702eb1d5ee23c5148fc68e3bd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 48.0, "max_forks_repo_forks_event_min_datetime": "2015-08-15T12:08:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-07T02:33:07.000Z", "avg_line_length": 25.3717948718, "max_line_length": 68, "alphanum_fraction": 0.7529055078, "num_tokens": 574, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.4950793636493661}}
{"text": "#ifndef _MLES_ACTIVATION_HPP_\n#define _MLES_ACTIVATION_HPP_\n\n#include <Eigen/Dense>\n#include <string>\n#include <ostream>\n#include <istream>\n#include <memory>\n\nnamespace mles\n{\n    class Activation;\n    typedef std::shared_ptr<Activation> ActivationPtr;\n\n    class Activation\n    {\n        private:\n            std::string name;\n            int parametersSize;\n        public:\n            Activation(const std::string& name, int parametersSize = 0)\n            {\n                this->name = name;\n                this->parametersSize = parametersSize;\n            }\n\n            virtual ~Activation()\n            {\n                \n            }\n\n            std::string getName()\n            {\n                return name;\n            }\n\n            int getParametersSize()\n            {\n                return parametersSize;\n            }\n\n            bool is(const std::string& name)\n            {\n                return name == this->name;\n            }\n\n            virtual void getActivation(Eigen::MatrixXd& x, Eigen::MatrixXd& y)\n            {\n                y.resize(x.rows(), x.cols());\n                for(int i = 0; i < x.rows(); i++)\n                {\n                    for(int j = 0; j < x.cols(); j++)\n                        y(i,j) = this->getActivation(x(i,j));\n                }\n            }\n\n            virtual void getDerivative(Eigen::MatrixXd& x, Eigen::MatrixXd& y)\n            {\n                y.resize(x.rows(), x.cols());\n                for(int i = 0; i < x.rows(); i++)\n                {\n                    for(int j = 0; j < x.cols(); j++)\n                        y(i,j) = this->getDerivative(x(i,j));\n                }\n            }\n\n            virtual double getActivation(double x)\n            {\n                return x;\n            }\n\n            virtual double getDerivative(double x)\n            {\n                return 0;\n            }\n\n            virtual Activation* clone()\n            {\n                return new Activation(name);\n            }\n\n            virtual void load(std::istream& f)\n            {\n\n            }\n\n            virtual void write(std::ostream& f)\n            {\n\n            }\n    };\n}\n\n#endif\n", "meta": {"hexsha": "1fc2ba102a37de17085883a94416a680119283bb", "size": 2169, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/lib/mles/Activation.hpp", "max_stars_repo_name": "AlexanderSilvaB/mles", "max_stars_repo_head_hexsha": "e1bc81de8a0a4625343500a69ebd0001729ad654", "max_stars_repo_licenses": ["MIT"], "max_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/mles/Activation.hpp", "max_issues_repo_name": "AlexanderSilvaB/mles", "max_issues_repo_head_hexsha": "e1bc81de8a0a4625343500a69ebd0001729ad654", "max_issues_repo_licenses": ["MIT"], "max_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/mles/Activation.hpp", "max_forks_repo_name": "AlexanderSilvaB/mles", "max_forks_repo_head_hexsha": "e1bc81de8a0a4625343500a69ebd0001729ad654", "max_forks_repo_licenses": ["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.8315789474, "max_line_length": 78, "alphanum_fraction": 0.4130935915, "num_tokens": 422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.4950793543820394}}
{"text": "//#define BOOST_TEST_MAIN\n#include <boost/test/included/unit_test.hpp>\n#include <iostream>\n#include <sstream>\n\n#include \"auxiliary_functions.h\"\n#include \"combination_sum_3.h\"\n\n\nBOOST_AUTO_TEST_SUITE(combination_sum_3)\n\nBOOST_AUTO_TEST_CASE(combination_sum_1) {\n\tint k(3);\n\tint n(9);\n\tstd::vector<std::vector<int>> expected = { {1,2,6},{1,3,5},{2,3,4} };\n\tSolution sol;\n\n\tstd::vector<std::vector<int>> actual = sol.combinationSum3(k, n);\n\t\n\tBOOST_CHECK(expected == actual);\n}\n\nBOOST_AUTO_TEST_CASE(combination_sum_2) {\n\tint k(3);\n\tint n(7);\n\tstd::vector<std::vector<int>> expected = {{1,2,4}};\n\tSolution sol;\n\n\tstd::vector<std::vector<int>> actual = sol.combinationSum3(k, n);\n\t\n\tBOOST_CHECK(expected == actual);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "d02d84997c15c55dacf2c26c7fd1cda706602181", "size": 743, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test_XUnit/test_compination_sum_3.cpp", "max_stars_repo_name": "brigitteunger/katas_cpp", "max_stars_repo_head_hexsha": "b089db5f5581f50b8278e3838c70c750ad7b5427", "max_stars_repo_licenses": ["MIT"], "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_XUnit/test_compination_sum_3.cpp", "max_issues_repo_name": "brigitteunger/katas_cpp", "max_issues_repo_head_hexsha": "b089db5f5581f50b8278e3838c70c750ad7b5427", "max_issues_repo_licenses": ["MIT"], "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_XUnit/test_compination_sum_3.cpp", "max_forks_repo_name": "brigitteunger/katas_cpp", "max_forks_repo_head_hexsha": "b089db5f5581f50b8278e3838c70c750ad7b5427", "max_forks_repo_licenses": ["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.2285714286, "max_line_length": 70, "alphanum_fraction": 0.7146702557, "num_tokens": 209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081926, "lm_q2_score": 0.7217431943271999, "lm_q1q2_score": 0.49507935080461485}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2013 Kyle Lutz <kyle.r.lutz@gmail.com>\n//\n// Distributed under the Boost Software License, Version 1.0\n// See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt\n//\n// See http://kylelutz.github.com/compute for more information.\n//---------------------------------------------------------------------------//\n\n#define BOOST_TEST_MODULE TestCopyIf\n#include <boost/test/unit_test.hpp>\n\n#include <boost/compute/lambda.hpp>\n#include <boost/compute/algorithm/copy_if.hpp>\n#include <boost/compute/container/vector.hpp>\n\n#include \"check_macros.hpp\"\n#include \"context_setup.hpp\"\n\nnamespace bc = boost::compute;\nnamespace compute = boost::compute;\n\nBOOST_AUTO_TEST_CASE(copy_if_int)\n{\n    int data[] = { 1, 6, 3, 5, 8, 2, 4 };\n    bc::vector<int> input(data, data + 7);\n\n    bc::vector<int> output(input.size());\n    bc::fill(output.begin(), output.end(), -1);\n\n    using ::boost::compute::_1;\n\n    bc::vector<int>::iterator iter =\n        bc::copy_if(input.begin(), input.end(), output.begin(), _1 < 5);\n    BOOST_VERIFY(iter == output.begin() + 4);\n    CHECK_RANGE_EQUAL(int, 7, output, (1, 3, 2, 4, -1, -1, -1));\n\n    bc::fill(output.begin(), output.end(), 42);\n    iter =\n        bc::copy_if(input.begin(), input.end(), output.begin(), _1 * 2 >= 10);\n    BOOST_VERIFY(iter == output.begin() + 3);\n    CHECK_RANGE_EQUAL(int, 7, output, (6, 5, 8, 42, 42, 42, 42));\n}\n\nBOOST_AUTO_TEST_CASE(copy_if_odd)\n{\n    int data[] = { 1, 2, 3, 4, 5, 1, 2, 3, 4, 5 };\n    bc::vector<int> input(data, data + 10);\n\n    using ::boost::compute::_1;\n\n    bc::vector<int> odds(input.size());\n    bc::vector<int>::iterator odds_end =\n        bc::copy_if(input.begin(), input.end(), odds.begin(), _1 % 2 == 1);\n    BOOST_CHECK(odds_end == odds.begin() + 6);\n    CHECK_RANGE_EQUAL(int, 6, odds, (1, 3, 5, 1, 3, 5));\n\n    bc::vector<int> evens(input.size());\n    bc::vector<int>::iterator evens_end =\n        bc::copy_if(input.begin(), input.end(), evens.begin(), _1 % 2 == 0);\n    BOOST_CHECK(evens_end == evens.begin() + 4);\n    CHECK_RANGE_EQUAL(int, 4, evens, (2, 4, 2, 4));\n}\n\nBOOST_AUTO_TEST_CASE(clip_points_below_plane)\n{\n    float data[] = { 1.0f, 2.0f, 3.0f, 0.0f,\n                     -1.0f, 2.0f, 3.0f, 0.0f,\n                     -2.0f, -3.0f, 4.0f, 0.0f,\n                     4.0f, -3.0f, 2.0f, 0.0f };\n    bc::vector<bc::float4_> points(reinterpret_cast<bc::float4_ *>(data),\n                                   reinterpret_cast<bc::float4_ *>(data) + 4);\n\n    // create output vector filled with (0, 0, 0, 0)\n    bc::vector<bc::float4_> output(points.size());\n    bc::fill(output.begin(), output.end(), bc::float4_(0.0f, 0.0f, 0.0f, 0.0f));\n\n    // define the plane (at origin, +X normal)\n    bc::float4_ plane_origin(0.0f, 0.0f, 0.0f, 0.0f);\n    bc::float4_ plane_normal(1.0f, 0.0f, 0.0f, 0.0f);\n\n    using ::boost::compute::_1;\n    using ::boost::compute::lambda::dot;\n\n    bc::vector<bc::float4_>::const_iterator iter =\n        bc::copy_if(points.begin(),\n                    points.end(),\n                    output.begin(),\n                    dot(_1 - plane_origin, plane_normal) > 0.0f);\n    BOOST_CHECK(iter == output.begin() + 2);\n}\n\nBOOST_AUTO_TEST_CASE(copy_index_if_int)\n{\n    int data[] = { 1, 6, 3, 5, 8, 2, 4 };\n    compute::vector<int> input(data, data + 7);\n\n    compute::vector<int> output(input.size());\n    compute::fill(output.begin(), output.end(), -1);\n\n    using ::boost::compute::_1;\n    using ::boost::compute::detail::copy_index_if;\n\n    compute::vector<int>::iterator iter =\n        copy_index_if(input.begin(), input.end(), output.begin(), _1 < 5);\n    BOOST_VERIFY(iter == output.begin() + 4);\n    CHECK_RANGE_EQUAL(int, 7, output, (0, 2, 5, 6, -1, -1, -1));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "143b5b5cb3eb687675d5791c56a0f26fa62f9180", "size": 3834, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_copy_if.cpp", "max_stars_repo_name": "bastiankoe/compute", "max_stars_repo_head_hexsha": "57eec36d20e122a496d3fbfddf8bf4ad8d6f4a4f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-03-18T01:14:13.000Z", "max_stars_repo_stars_event_max_datetime": "2015-03-18T01:14:13.000Z", "max_issues_repo_path": "test/test_copy_if.cpp", "max_issues_repo_name": "bastiankoe/compute", "max_issues_repo_head_hexsha": "57eec36d20e122a496d3fbfddf8bf4ad8d6f4a4f", "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/test_copy_if.cpp", "max_forks_repo_name": "bastiankoe/compute", "max_forks_repo_head_hexsha": "57eec36d20e122a496d3fbfddf8bf4ad8d6f4a4f", "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.2321428571, "max_line_length": 80, "alphanum_fraction": 0.5740740741, "num_tokens": 1195, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494421679929, "lm_q2_score": 0.7217431943271998, "lm_q1q2_score": 0.495079341537288}}
{"text": "// Copyright (c) 2007\u20132018 The scikit-learn developers. All rights reserved.\n// 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 \"gaussian_process.h\"\n\n#include <cmath>\n#include <iostream>\n\n#include <Eigen/LU>\n\n#include \"LBFGS.h\"\n\nusing Eigen::VectorXd;\nusing Eigen::MatrixXd;\n\n\nnamespace horovod {\nnamespace common {\n\n// Returns true if any of the elements in the vectors is not a number.\nbool isnan(const VectorXd& x) {\n  for (int i = 0; i < x.size(); ++i) {\n    if (std::isnan(x[i])) {\n      return true;\n    }\n  }\n  return false;\n}\n\nGaussianProcessRegressor::GaussianProcessRegressor(double alpha) : alpha_(alpha) {}\n\nvoid GaussianProcessRegressor::Fit(MatrixXd* x_train, MatrixXd* y_train) {\n  // Cache the last used training inputs and outputs for later prediction\n  x_train_ = x_train;\n  y_train_ = y_train;\n\n  // This function will apply the natural logarithm element-wise to a matrix\n  auto ln = [](double x) {\n    return std::log(x);\n  };\n\n  // f(x): the objective function to be minimized by our optimizer.\n  // Computes the negative log-likelihood for training data x_train and y_train and given noise level.\n  double a2 = alpha_ * alpha_;\n  double d3 = 0.5 * x_train_->rows() * std::log(2 * M_PI);\n  auto f = [&, a2, d3](const VectorXd& x) {\n    int64_t m = x_train_->rows();\n    MatrixXd k = Kernel(*x_train_, *x_train_, x[0], x[1]) + (a2 * MatrixXd::Identity(m, m));\n    MatrixXd k_inv = k.inverse();\n\n    // Compute determinant via Cholesky decomposition\n    MatrixXd l = k.llt().matrixL().toDenseMatrix();\n    double d1 = l.diagonal().unaryExpr(ln).sum();\n    MatrixXd d2 = 0.5 * (y_train_->transpose() * (k_inv * (*y_train_)));\n    MatrixXd cov = d2.array() + (d1 + d3);\n\n    return cov(0, 0);\n  };\n\n  // We wish to minimize the negative log-likelihood of f(x) above by evaluating it at a given point, then\n  // empirically approximating the derivative to follow the gradient downwards.\n  double f_min = std::numeric_limits<double>::max();\n  VectorXd x_min;\n  auto nll_fn = [&](const VectorXd& x, VectorXd& grad) {\n    // f(x) computed at the current point x\n    double fx = f(x);\n\n    // Update the best value observed so far, if x is a valid point\n    if (!isnan(x) && fx < f_min) {\n      f_min = fx;\n      x_min = x;\n    }\n\n    // Update the gradient vector in place and return the f(x) value computed\n    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  // Find the kernel parameter values for length_ and sigma_f_ that maximize the likelihood of the training data.\n  VectorXd x = VectorXd::Ones(2);\n  double fx;\n  solver.minimize(nll_fn, x, fx);\n\n  // If the returned value is NaN, then we short-circuit the optimizer by returning the cached best values found\n  if (!isnan(x)) {\n    length_ = x[0];\n    sigma_f_ = x[1];\n  } else {\n    length_ = x_min[0];\n    sigma_f_ = x_min[1];\n  }\n}\n\nvoid GaussianProcessRegressor::Predict(const MatrixXd& x, VectorXd& mu, VectorXd* sigma) const {\n  MatrixXd cov;\n  PosteriorPrediction(x, *x_train_, *y_train_, mu, cov, length_, sigma_f_, alpha_);\n\n  // Only compute standard deviation if it was requested\n  if (sigma != nullptr) {\n    // Extract the standard deviation from the covariance matrix\n    auto sqrt = [](double x) {\n      return std::sqrt(x);\n    };\n    *sigma = cov.diagonal().unaryExpr(sqrt);\n  }\n}\n\nvoid GaussianProcessRegressor::PosteriorPrediction(\n    const MatrixXd& x_s, const MatrixXd& x_train, const MatrixXd& y_train, VectorXd& mu_s, MatrixXd& cov_s,\n    double l, double sigma_f, double sigma_y) const {\n  // With m training data and n new input data. sy2 is the noise term in the diagonal of k. It is set to 0 if\n  // observations are noisy.\n  int64_t n = x_s.rows();\n  int64_t m = x_train.rows();\n  double sy2 = sigma_y * sigma_y;\n\n  // The posterior predictive distribution is Gaussian with mean mu_s and covariance cov_s. By definition of the\n  // Gaussian Process, the joint distribution of observed data x_train and predictions y_train is distributed\n  // normally with mean 0 and standard deviation [[k, k_s], [k_s^T, k_ss]].\n  MatrixXd k = Kernel(x_train, x_train, l, sigma_f) + (sy2 * MatrixXd::Identity(m, m));\n  MatrixXd k_s = Kernel(x_train, x_s, l, sigma_f);\n  MatrixXd k_ss = Kernel(x_s, x_s, l, sigma_f) + (1e-8 * MatrixXd::Identity(n, n));\n  MatrixXd k_inv = k.inverse();\n\n  // Compute sufficient statistics of the posterior predictive distribution: mean and covariance.\n  mu_s = (k_s.transpose() * k_inv) * y_train;\n  cov_s = k_ss - (k_s.transpose() * k_inv) * k_s;\n}\n\nvoid GaussianProcessRegressor::ApproxFPrime(const VectorXd& x, const std::function<double(const VectorXd&)>& f,\n                                            double f0, VectorXd& grad, double epsilon) {\n  VectorXd ei = VectorXd::Zero(x.size());\n  for (int k = 0; k < x.size(); ++k) {\n    ei[k] = 1.0;\n    VectorXd d = epsilon * ei;\n    grad[k] = (f(x + d) - f0) / d[k];\n    ei[k] = 0.0;\n  }\n}\n\nMatrixXd GaussianProcessRegressor::Kernel(const MatrixXd& x1, const MatrixXd& x2,\n                                          double l, double sigma_f) const {\n  // Squared Exponential Kernel, also known as the Gaussian or RBF Kernel.\n  auto x1_vec = x1.cwiseProduct(x1).rowwise().sum();\n  auto x2_vec = x2.cwiseProduct(x2).rowwise().sum();\n  auto x1_x2 = x1_vec.replicate(1, x2_vec.size()).rowwise() + x2_vec.transpose();\n\n  auto& dot = x1 * x2.transpose();\n  auto sqdist = x1_x2 - (dot.array() * 2).matrix();\n\n  // The length parameter l controls the smoothness of the function and sigma_f the vertical variation. We use\n  // the same l for all input dimensions (isotropic kernel).\n  double sigma_f2 = sigma_f * sigma_f;\n  double l2 = l * l;\n  auto op = [sigma_f2, l2](double x) {\n    return sigma_f2 * std::exp(-0.5 / l2 * x);\n  };\n\n  return sqdist.unaryExpr(op);\n}\n\n} // namespace common\n} // namespace horovod\n", "meta": {"hexsha": "d658e2aa8bc733161ae7d494d9b5b2f9b0dc8da1", "size": 6802, "ext": "cc", "lang": "C++", "max_stars_repo_path": "horovod/common/optim/gaussian_process.cc", "max_stars_repo_name": "tonitick/horovod", "max_stars_repo_head_hexsha": "73d860f2396321761e0f5ef6fe934130afd69094", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-10-20T05:40:08.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-31T17:25:50.000Z", "max_issues_repo_path": "horovod/common/optim/gaussian_process.cc", "max_issues_repo_name": "tonitick/horovod", "max_issues_repo_head_hexsha": "73d860f2396321761e0f5ef6fe934130afd69094", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-07-29T10:08:33.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-29T10:08:33.000Z", "max_forks_repo_path": "horovod/common/optim/gaussian_process.cc", "max_forks_repo_name": "tonitick/horovod", "max_forks_repo_head_hexsha": "73d860f2396321761e0f5ef6fe934130afd69094", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-07T12:43:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-07T12:43:46.000Z", "avg_line_length": 36.7675675676, "max_line_length": 113, "alphanum_fraction": 0.6690679212, "num_tokens": 1857, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397349, "lm_q2_score": 0.6261241842048092, "lm_q1q2_score": 0.4949701570461013}}
{"text": "// *****************************************************************************\n//\n// Copyright (c) 2015, Southwest Research Institute\u00ae (SwRI\u00ae)\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are met:\n//     * Redistributions of source code must retain the above copyright\n//       notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above copyright\n//       notice, this list of conditions and the following disclaimer in the\n//       documentation and/or other materials provided with the distribution.\n//     * Neither the name of Southwest Research Institute\u00ae (SwRI\u00ae) nor the\n//       names of its contributors may be used to endorse or promote products\n//       derived from this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY\n// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// *****************************************************************************\n\n#include <swri_geometry_util/cubic_spline.h>\n\n#include <Eigen/Dense>\n\nnamespace swri_geometry_util\n{\n\n  bool CubicSplineInterpolation(\n    const std::vector<cv::Vec2d>& points,\n    double delta,\n    std::vector<std::vector<cv::Vec2d> >& splines)\n  {\n    if (delta <= 0)\n    {\n      return false;\n    }\n\n    size_t num_points = points.size();\n\n    splines.clear();\n    splines.resize(num_points - 1);\n\n    // Accumulated distance along linear path.\n    std::vector<double> s = std::vector<double>(num_points);\n\n    // Distance between consecutive points on path.\n    std::vector<double> ds = std::vector<double>(num_points);\n\n    s[0] = 0;\n    for (size_t i = 1; i < num_points; i++)\n    {\n      double dx = points[i][0] - points[i - 1][0];\n      double dy = points[i][1] - points[i - 1][1];\n\n      ds[i - 1] = std::sqrt(std::pow(dx, 2) + std::pow(dy, 2));\n      s[i] = s[i - 1] + ds[i - 1];\n    }\n\n    // Normalize s to be [0:1]\n    double totalDistance = s[num_points - 1];\n    for (size_t i = 0; i < num_points; i++)\n    {\n      s[i] /= totalDistance;\n    }\n\n    Eigen::MatrixX2d u(num_points, 2);\n    Eigen::MatrixXd A(num_points, num_points);\n    Eigen::MatrixX2d z(num_points, 2);\n\n    // Set up the z0 equation.\n    u(0, 0) = 0;\n    u(0, 1) = 0;\n    A(0, 0) = 1;\n    for (size_t i = 1; i < num_points; i++)\n    {\n      A(0, i) = 0;\n    }\n\n    // Set up the z1 to zn-1 equations.\n    for (size_t i = 1; i < num_points - 1; i++)\n    {\n      double hi = s[i + 1] - s[i];\n      double himl = s[i] - s[i - 1];\n\n      u(i, 0) = 6.0 * ((points[i + 1][0] - points[i][0]) / hi - (points[i][0]\n          - points[i - 1][0]) / himl);\n      u(i, 1) = 6.0 * ((points[i + 1][1] - points[i][1]) / hi - (points[i][1]\n          - points[i - 1][1]) / himl);\n\n      for (size_t j = 0; j < i - 1; j++)\n      {\n        A(i, j) = 0;\n      }\n      A(i, i - 1) = himl;\n      A(i, i) = 2 * (himl + hi);\n      A(i, i + 1) = hi;\n      for (size_t j = i + 2; j < num_points; j++)\n      {\n        A(i, j) = 0;\n      }\n    }\n\n    // Set up the zn equation\n    u(num_points - 1, 0) = 0;\n    u(num_points - 1, 1) = 0;\n    for (size_t j = 0; j < num_points - 1; j++)\n    {\n      A(num_points - 1, j) = 0;\n    }\n    A(num_points - 1, num_points - 1) = 1;\n\n    // Solve Az = u\n    z = A.colPivHouseholderQr().solve(u);\n\n    for (size_t i = 0; i < num_points - 1; i++)\n    {\n      std::vector<cv::Vec2d>& spline = splines[i];\n\n      spline.push_back(points[i]);\n\n      double hi = s[i + 1] - s[i];\n      double act_dist = ds[i];\n      int32_t num_to_add = static_cast<int32_t> (act_dist / delta);\n      double normalizedDelta = hi / (num_to_add + 1);\n\n      // Add the additional points between waypoints\n      for (int32_t j = 1; j <= num_to_add; j++)\n      {\n        // Calculate the (x,y) value of the interpolated point\n        double si = s[i] + j * normalizedDelta;\n        double xx = (z(i + 1, 0) * pow(si - s[i], 3) + z(i, 0) * pow(s[i + 1]\n            - si, 3)) / (6.0 * hi) + (points[i + 1][0] / hi - hi * z(i + 1, 0)\n            / 6.0) * (si - s[i]) + (points[i][0] / hi - hi * z(i, 0) / 6.0)\n            * (s[i + 1] - si);\n        double yy = (z(i + 1, 1) * pow(si - s[i], 3) + z(i, 1) * pow(s[i + 1]\n            - si, 3)) / (6.0 * hi) + (points[i + 1][1] / hi - hi * z(i + 1, 1)\n            / 6.0) * (si - s[i]) + (points[i][1] / hi - hi * z(i, 1) / 6.0)\n            * (s[i + 1] - si);\n\n        // Add the point to the interpolated array\n        spline.push_back(cv::Vec2d(xx, yy));\n      }\n\n      spline.push_back(points[i + 1]);\n    }\n\n    return true;\n  }\n\n  bool CubicSplineInterpolation(\n    const std::vector<tf::Vector3>& points,\n    double delta,\n    std::vector<std::vector<tf::Vector3> >& splines)\n  {\n    std::vector<cv::Vec2d> cv_points(points.size());\n    for (size_t i = 0; i < points.size(); i++)\n    {\n      cv_points[i] = cv::Vec2d(points[i].x(), points[i].y());\n    }\n\n    std::vector<std::vector<cv::Vec2d> > cv_splines;\n    bool result = CubicSplineInterpolation(cv_points, delta, cv_splines);\n\n    splines.resize(cv_splines.size());\n    for (size_t i = 0; i < cv_splines.size(); i++)\n    {\n      splines[i].resize(cv_splines[i].size());\n      for (size_t j = 0; j < cv_splines[i].size(); j++)\n      {\n        splines[i][j] = tf::Vector3(cv_splines[i][j][0], cv_splines[i][j][1], 0);\n      }\n    }\n\n    return result;\n  }\n}\n", "meta": {"hexsha": "b43ef4f61ab842bdc7339309e43530abdbe1360e", "size": 6110, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "swri_geometry_util/src/cubic_spline.cpp", "max_stars_repo_name": "rookie80/marti_common", "max_stars_repo_head_hexsha": "2866c243a0df11918fd727cd1c8fce41d67f2078", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2015-03-02T20:51:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-19T02:31:46.000Z", "max_issues_repo_path": "swri_geometry_util/src/cubic_spline.cpp", "max_issues_repo_name": "rookie80/marti_common", "max_issues_repo_head_hexsha": "2866c243a0df11918fd727cd1c8fce41d67f2078", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 206.0, "max_issues_repo_issues_event_min_datetime": "2015-01-31T16:43:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-02T01:15:26.000Z", "max_forks_repo_path": "swri_geometry_util/src/cubic_spline.cpp", "max_forks_repo_name": "rookie80/marti_common", "max_forks_repo_head_hexsha": "2866c243a0df11918fd727cd1c8fce41d67f2078", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 67.0, "max_forks_repo_forks_event_min_datetime": "2015-01-23T21:46:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T22:50:27.000Z", "avg_line_length": 32.8494623656, "max_line_length": 81, "alphanum_fraction": 0.5541734861, "num_tokens": 1877, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.4949701563813573}}
{"text": "#ifndef STAN_MATH_PRIM_FUN_MODIFIED_BESSEL_FIRST_KIND_HPP\n#define STAN_MATH_PRIM_FUN_MODIFIED_BESSEL_FIRST_KIND_HPP\n\n#include <stan/math/prim/meta.hpp>\n#include <stan/math/prim/err.hpp>\n#include <stan/math/prim/functor/apply_scalar_binary.hpp>\n#include <boost/math/special_functions/bessel.hpp>\n\nnamespace stan {\nnamespace math {\n\n/**\n *\n   \\f[\n   \\mbox{modified\\_bessel\\_first\\_kind}(v, z) =\n   \\begin{cases}\n     I_v(z) & \\mbox{if } -\\infty\\leq z \\leq \\infty \\\\[6pt]\n     \\textrm{error} & \\mbox{if } z = \\textrm{NaN}\n   \\end{cases}\n   \\f]\n\n   \\f[\n   \\frac{\\partial\\, \\mbox{modified\\_bessel\\_first\\_kind}(v, z)}{\\partial z} =\n   \\begin{cases}\n     \\frac{\\partial\\, I_v(z)}{\\partial z} & \\mbox{if } -\\infty\\leq z\\leq \\infty\n \\\\[6pt] \\textrm{error} & \\mbox{if } z = \\textrm{NaN} \\end{cases} \\f]\n\n   \\f[\n     {I_v}(z) = \\left(\\frac{1}{2}z\\right)^v\\sum_{k=0}^\\infty\n \\frac{\\left(\\frac{1}{4}z^2\\right)^k}{k!\\Gamma(v+k+1)} \\f]\n\n   \\f[\n   \\frac{\\partial \\, I_v(z)}{\\partial z} = I_{v-1}(z)-\\frac{v}{z}I_v(z)\n   \\f]\n *\n */\ntemplate <typename T2, require_arithmetic_t<T2>* = nullptr>\ninline T2 modified_bessel_first_kind(int v, const T2 z) {\n  check_not_nan(\"modified_bessel_first_kind\", \"z\", z);\n\n  return boost::math::cyl_bessel_i(v, z);\n}\n\n/**\n * This function exists because when z is of type integer,\n * cyl_bessel_i(v, z) returns an integer. This\n * results in overflow when the function value is large.\n */\ninline double modified_bessel_first_kind(int v, int z) {\n  check_not_nan(\"modified_bessel_first_kind\", \"z\", z);\n\n  return boost::math::cyl_bessel_i(v, static_cast<double>(z));\n}\n\n/**\n * Enables the vectorised application of the modified_bessel_first_kind\n * function, when the first and/or second arguments are containers.\n *\n * @tparam T1 type of first input\n * @tparam T2 type of second input\n * @param a First input\n * @param b Second input\n * @return modified_bessel_first_kind function applied to the two inputs.\n */\ntemplate <typename T1, typename T2, require_any_container_t<T1, T2>* = nullptr>\ninline auto modified_bessel_first_kind(const T1& a, const T2& b) {\n  return apply_scalar_binary(a, b, [&](const auto& c, const auto& d) {\n    return modified_bessel_first_kind(c, d);\n  });\n}\n\n}  // namespace math\n}  // namespace stan\n\n#endif\n", "meta": {"hexsha": "d01f789670402a609932da0b5b2cdb3c4dcecdba", "size": 2250, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/prim/fun/modified_bessel_first_kind.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/fun/modified_bessel_first_kind.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/fun/modified_bessel_first_kind.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": 29.6052631579, "max_line_length": 79, "alphanum_fraction": 0.6848888889, "num_tokens": 727, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.6261241842048092, "lm_q1q2_score": 0.494970150866218}}
{"text": "#include <Eigen/Dense>\n#include <mutex>\n\n#ifndef UTILS_EXPONENTIAL_FILTER_H\n#define UTILS_EXPONENTIAL_FILTER_H\n//https://gregstanleyandassociates.com/whitepapers/FaultDiagnosis/Filtering/Exponential-Filter/exponential-filter.htm\n\nnamespace utils\n{\n    class ExponentialFilter\n    {\n    private:\n        Eigen::VectorXd y_last_;\n        const double a_;\n\n    public:\n        /**\n         * Constructor for filter\n         * @param a: The filter value (usually between 0.8 and 0.99)\n         * @param y_0: The init value of the filter (usually 0)\n         */\n        ExponentialFilter(double a, const Eigen::VectorXd &y_0);\n\n        /**\n         * Predict the next value of the signal\n         * @param x: The to be filtered vector; return value is stored in same vector\n         */\n        void predict(Eigen::VectorXd &x);\n    };\n} // namespace utils\n\n#endif\n", "meta": {"hexsha": "9152e289b6fec0b756140a4f82fc750a24fc99bd", "size": 859, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "utils/src/exponential_filter.hpp", "max_stars_repo_name": "Krenol/CppUtils", "max_stars_repo_head_hexsha": "c2edd9ca845fc6975d4179733b39c4d34a4b0ea0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "utils/src/exponential_filter.hpp", "max_issues_repo_name": "Krenol/CppUtils", "max_issues_repo_head_hexsha": "c2edd9ca845fc6975d4179733b39c4d34a4b0ea0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "utils/src/exponential_filter.hpp", "max_forks_repo_name": "Krenol/CppUtils", "max_forks_repo_head_hexsha": "c2edd9ca845fc6975d4179733b39c4d34a4b0ea0", "max_forks_repo_licenses": ["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.0303030303, "max_line_length": 117, "alphanum_fraction": 0.6472642608, "num_tokens": 208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7905303087996144, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.4949701502014738}}
{"text": "/**\n * \\Description:\n * this node is used to estimate the absoulte location(x,y) of the robot using Trilteration.\n * It subscribe to:\n * - /beacon_distances\n * It publishes to:\n * - /pose\n *\n * ALI&SERRANO_ECN_M1_2017\n */\n\n\n//Cpp\n#include <sstream>\n#include <stdio.h>\n#include <vector>\n#include <iostream>\n#include <stdlib.h>\n#include <math.h>\n#include <Eigen/Dense>\n\nusing namespace Eigen;\nusing namespace std;\nusing Eigen::MatrixXd;\n\n//ROS\n#include \"ros/ros.h\"\n\n// Include here the \".h\" files corresponding to the topic type you use.\n#include <nav_msgs/Odometry.h>\n#include \"tf/transform_datatypes.h\"\n\n#include \"std_msgs/MultiArrayLayout.h\"\n#include \"std_msgs/MultiArrayDimension.h\"\n#include <std_msgs/Float64MultiArray.h>\n\n#include <geometry_msgs/Point.h>\n#include <geometry_msgs/Pose2D.h>\n\n//#include <geometry_msgs/PoseWithCovariance.h>\n//#include <std_msgs/Float32.h>\n\n// global variables...\nstd_msgs::Float64MultiArray dist;\nbool  is_dist_available=false;\n\n\nvoid msurmnt_Callback ( std_msgs::Float64MultiArray  dist_msg) {\n    is_dist_available= true;\n    dist = dist_msg;\n}\n\nint circle_circle_intersection(double x0, double y0, double r0,\n                               double x1, double y1, double r1,\n                               double &xi, double &yi,\n                               double &xi_prime, double &yi_prime)\n{\n    double a, dx, dy, d, h, rx, ry;\n    double x2, y2;\n\n    // dx and dy are the vertical and horizontal distances between the circle centers.\n    dx = x1 - x0;\n    dy = y1 - y0;\n\n    // Determine the straight-line distance between the centers.\n    //d = sqrt((dy*dy) + (dx*dx));\n    d = hypot(dx,dy); // Suggested by Keith Briggs\n\n    // Check for solvability.\n    if (d > (r0 + r1)) /* no solution. circles do not intersect. */\n        return 0;\n    if (d < fabs(r0 - r1)) /* no solution. one circle is contained in the other */\n        return 0;\n\n\n    /* 'point 2' is the point where the line through the circle\n   * intersection points crosses the line between the circle centers.\n   */\n\n    /* Determine the distance from point 0 to point 2. */\n    a = ((r0*r0) - (r1*r1) + (d*d)) / (2.0 * d) ;\n\n    /* Determine the coordinates of point 2. */\n    x2 = x0 + (dx * a/d);\n    y2 = y0 + (dy * a/d);\n\n    // Determine the distance from point 2 to either of the intersection points.\n    h = sqrt((r0*r0) - (a*a));\n\n    // Now determine the offsets of the intersection points from point 2.\n    rx = -dy * (h/d);\n    ry = dx * (h/d);\n\n    /* Determine the absolute intersection points. */\n    xi = x2 + rx;\n    xi_prime = x2 - rx;\n    yi = y2 + ry;\n    yi_prime = y2 - ry;\n\n    return 1;\n}\n\nvoid select_point(double p1x, double p1y, double p2x, double p2y, double bx, double by, double &px, double &py, double d){\n    double t1= fabs (sqrt( (bx- p1x)*(bx-p1x) + (by-p1y)*(by-p1y)) );\n    double t2= fabs (sqrt( (bx-p2x)*(bx-p2x) + (by-p2y)*(by-p2y)) );\n    if ( fabs(d-t1) < fabs(d-t2) )\n       { px= p1x;  py=p1y; }\n    else\n       { px= p2x;  py=p2y; }\n}\n\nvoid incircle(double p1x, double p1y, double p2x, double p2y, double p3x, double p3y, double &xc, double &yc){\n    double a1 =fabs (sqrt( (p3x-p2x)*(p3x-p2x) + (p3y-p2y)*(p3y-p2y)) );\n    double a2 =fabs (sqrt( (p1x-p3x)*(p1x-p3x) + (p1y-p3y)*(p1y-p3y)) );\n    double a3 =fabs (sqrt( (p1x-p2x)*(p1x-p2x) + (p1y-p2y)*(p1y-p2y)) );\n    xc= ( a1*p1x + a2*p2x + a3*p3x )/(a1+a2+a3);\n    yc= ( a1*p1y + a2*p2y + a3*p3y )/(a1+a2+a3);\n}\n\n\nint main (int argc, char** argv){\n\n    //ROS Initialization\n    ros::init(argc, argv, \"ekf_node\");\n\n    // Define your node handles\n    ros::NodeHandle nh_loc(\"~\"), nh_glob;\n\n    // Read the node parameters if any\n\n    // Declare your node's subscriptions and service clients\n    ros::Subscriber msurmnt_sub = nh_glob.subscribe<std_msgs::Float64MultiArray>(\"/beacon_distances\",1, msurmnt_Callback) ;\n\n    // Declare you publishers and service servers\n    ros::Publisher  pose_pub = nh_glob.advertise<geometry_msgs::Pose2D>(\"/pose\",1) ;\n\n    // node initilization\n\n    //geometry_msgs::Point B1, B2, B3;\n    //B1.x=0;  B1.y=10; B2.x=10;  B2.y=0; B3.x=20; B3.y=20;\n\n    //double x1=0, x2=0, x3=10, y1=5, y2=10, y3=10, x, y, d1, d2, d3;\n    double d1, d2, d3, xc, yc;\n    ros::Rate rate(10);\n\n    while (ros::ok()){\n\n        ros::spinOnce();\n                if( ! is_dist_available ){\n                    ROS_INFO(\"Waiting for odom/dist.\") ;\n                    rate.sleep() ;\n                    continue ;\n                }\n\n        // measurement part:\n\n        // Actual measurement  Y\n        d1= dist.data[0];\n        d2= dist.data[1];\n        d3= dist.data[2];\n\n        //double d1=5, d2=5, d3=1;\n        double b1x=0, b1y=0, b2x=0, b2y=190, b3x=350, b3y=0;\n        double ip12x1, ip12y1, ip12x2, ip12y2,   ip13x1, ip13y1, ip13x2, ip13y2,   ip23x1, ip23y1, ip23x2, ip23y2;\n\n        int t12= circle_circle_intersection(b1x, b1y, d1, b2x, b2y, d2, ip12x1, ip12y1, ip12x2, ip12y2); //12\n        int t13= circle_circle_intersection(b1x, b1y, d1, b3x, b3y, d3, ip13x1, ip13y1, ip13x2, ip13y2); //13\n        int t23= circle_circle_intersection(b2x, b2y, d2, b3x, b3y, d3, ip23x1, ip23y1, ip23x2, ip23y2); //23\n\n        if ( t12 && t13 && t23){\n            //std::cout<< \"point1: (\" << ip1x << \", \" << ip1y << \")\" << \")\"<< std::endl;\n            //std::cout<< \"point2: (\" << ip2x << \", \" << ip2y << \")\" << \")\"<< std::endl;\n            double ip1x, ip1y, ip2x, ip2y, ip3x, ip3y;\n\n            select_point(ip12x1, ip12y1, ip12x2, ip12y2, b3x, b3y, ip1x, ip1y, d3 );\n            select_point(ip13x1, ip13y1, ip13x2, ip13y2, b2x, b2y, ip2x, ip2y, d2 );\n            select_point(ip23x1, ip23y1, ip23x2, ip23y2, b1x, b1y, ip3x, ip3y, d1 );\n\n            std::cout<< \"point1: (\" << ip1x << \", \" << ip1y << \")\" << \")\"<< std::endl;\n            std::cout<< \"point2: (\" << ip2x << \", \" << ip2y << \")\" << \")\"<< std::endl;\n            std::cout<< \"point3: (\" << ip3x << \", \" << ip3y << \")\" << \")\"<< std::endl;\n\n            incircle(ip1x, ip1y, ip2x, ip2y, ip3x, ip3y, xc, yc);\n            std::cout<< \"center: (\" << xc << \", \" << yc << \")\" << \")\"<< std::endl;\n\n\n        }\n        else\n            std::cout<<\"no common intersection\"<<std::endl;\n\n\n\n//        float c1= (d1*d1) - (x1*x1) - (y1*y1);\n//        float c2= (d2*d2) - (x2*x2) - (y2*y2);\n//        float c3= (d3*d3) - (x3*x3) - (y3*y3);\n\n//        x= ( ((c1-c2)*(y3-y1)) - ((c1-c3)*(y2-y1)) ) / ( 2*( ( (x2-x1)*(y3-y1) ) - ((x3-x1)*(y2-y1)) ));\n//        y= ( c1 - c2 - (2*x*(x2-x1)) ) / (2 * (y2-y1) );\n        // measurement covariance Q_gamma\n        //Q_gamma(0,0)= .1;  Q_gamma(1,1)= .1;  Q_gamma(2,2)= .1;\n\n        // Estimated_covariance_est: Pk+1/k+1 = ( I - Kk*Ck ) * Pk+1/k\n        //P= ( I - K*C ) * P;\n\n        // publish the final pose ........................................................................................................\n        geometry_msgs::Pose2D pose;\n        pose.x = xc;\n        pose.y = yc;\n        pose.theta =  0;\n        pose_pub.publish(pose);\n\n\n\n        rate.sleep();\n    }\n\n\n}\n", "meta": {"hexsha": "61286cf13d3068250a824894b098c89dde91a6ca", "size": 6988, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/turtle_ekf/src/absolute_loc_node.cpp", "max_stars_repo_name": "mahmoud-a-ali/TurtleBot_M1_Project", "max_stars_repo_head_hexsha": "a848c5b16fc2521acf265256cfbf9b7206f549d8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-08-18T05:59:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-11T07:47:44.000Z", "max_issues_repo_path": "src/turtle_ekf/src/absolute_loc_node.cpp", "max_issues_repo_name": "mahmoud-a-ali/TurtleBot_M1_Project", "max_issues_repo_head_hexsha": "a848c5b16fc2521acf265256cfbf9b7206f549d8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/turtle_ekf/src/absolute_loc_node.cpp", "max_forks_repo_name": "mahmoud-a-ali/TurtleBot_M1_Project", "max_forks_repo_head_hexsha": "a848c5b16fc2521acf265256cfbf9b7206f549d8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-11-11T07:47:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-11T07:47:45.000Z", "avg_line_length": 31.9086757991, "max_line_length": 138, "alphanum_fraction": 0.5516599886, "num_tokens": 2427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397349, "lm_q2_score": 0.6261241702517975, "lm_q1q2_score": 0.49497014601582234}}
{"text": "#include \"DiffWristKinematics.h\"\n\n#include <Eigen/Dense>\n\nusing Eigen::Matrix2f;\nusing Eigen::Vector2f;\n\ngearpos_t::gearpos_t(const Vector2f& vec) : left(vec(0)), right(vec(1)) {}\ngearpos_t::gearpos_t(float left, float right) : left(left), right(right) {}\nVector2f gearpos_t::vec() const {\n\treturn Vector2f(left, right);\n}\n\njointpos_t::jointpos_t(const Vector2f& vec) : pitch(vec(0)), roll(vec(1)) {}\njointpos_t::jointpos_t(float pitch, float roll) : pitch(pitch), roll(roll) {}\nVector2f jointpos_t::vec() const {\n\treturn Vector2f(pitch, roll);\n}\n\nstatic Matrix2f createTransform() {\n\tMatrix2f ret;\n\tret <<\n\t\t0.5, 0.5,\n\t\t-0.5, 0.5;\n\treturn ret;\n}\n\nstatic const Matrix2f gearToJointPosTransform = createTransform();\nstatic const Matrix2f jointToGearPosTransform = gearToJointPosTransform.inverse();\n\n\njointpos_t DiffWristKinematics::gearPosToJointPos(const gearpos_t& gearPos) const {\n\tVector2f res = gearToJointPosTransform * gearPos.vec();\n\treturn res;\n}\n\ngearpos_t DiffWristKinematics::jointPosToGearPos(const jointpos_t &jointPos) const {\n\tVector2f res = jointToGearPosTransform * jointPos.vec();\n\treturn res;\n}\n\njointpos_t DiffWristKinematics::gearPowerToJointPower(const gearpos_t &gearPwr) const {\n\tVector2f jointPwr = gearToJointPosTransform * gearPwr.vec();\n\t// compute infinity norm; i.e. component with max absolute value\n\tfloat maxVal = jointPwr.lpNorm<Eigen::Infinity>();\n\t// if any component is absolutely greater than 1, divide by maximum component to scale\n\t// everything to the interval [-1,1]\n\tif(maxVal > 1){\n\t\tjointPwr /= maxVal;\n\t}\n\treturn jointPwr;\n}\n\ngearpos_t DiffWristKinematics::jointPowerToGearPower(const jointpos_t &jointPwr) const {\n    Vector2f gearPwr = jointToGearPosTransform * jointPwr.vec();\n\t// compute infinity norm; i.e. component with max absolute value\n\tfloat maxVal = gearPwr.lpNorm<Eigen::Infinity>();\n\t// if any component is absolutely greater than 1, divide by maximum component to scale\n\t// everything to the interval [-1,1]\n\tif(maxVal > 1){\n\t\tgearPwr /= maxVal;\n\t}\n\treturn gearPwr;\n}\n", "meta": {"hexsha": "33e5c37e927223ae79122c5f1db21a52d1ae3f83", "size": 2030, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/kinematics/DiffWristKinematics.cpp", "max_stars_repo_name": "huskyroboticsteam/Resurgence", "max_stars_repo_head_hexsha": "649f78103b6d76709fdf55bb38d08c0ff50da140", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-12-23T23:31:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T07:17:41.000Z", "max_issues_repo_path": "src/kinematics/DiffWristKinematics.cpp", "max_issues_repo_name": "huskyroboticsteam/Resurgence", "max_issues_repo_head_hexsha": "649f78103b6d76709fdf55bb38d08c0ff50da140", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-11-22T05:33:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-23T07:01:47.000Z", "max_forks_repo_path": "src/kinematics/DiffWristKinematics.cpp", "max_forks_repo_name": "huskyroboticsteam/Resurgence", "max_forks_repo_head_hexsha": "649f78103b6d76709fdf55bb38d08c0ff50da140", "max_forks_repo_licenses": ["Apache-2.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.2307692308, "max_line_length": 88, "alphanum_fraction": 0.7487684729, "num_tokens": 579, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.49497014535107864}}
{"text": "#define EIGEN_NO_DEBUG\n\n#include \"ccpca.hpp\"\n\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n#include <cmath>\n#include <iostream>\n#include <limits>\n#include <thread>\n\nCCPCA::CCPCA(Eigen::Index const nComponents, bool const standardize)\n    : cpca_(CPCA(nComponents, standardize)) {\n  featContribs_.resize(0);\n  concatMat_.resize(0, 0);\n}\n\nEigen::MatrixXf\nCCPCA::fitTransform(Eigen::MatrixXf const &K, Eigen::MatrixXf const &R,\n                    bool const autoAlphaSelection, float const alpha,\n                    float const varThresRatio, bool parallel,\n                    unsigned int const nAlphas, float const maxLogAlpha,\n                    bool const keepReports) {\n  fit(K, R, autoAlphaSelection, alpha, varThresRatio, parallel, nAlphas,\n      maxLogAlpha, keepReports);\n  return cpca_.transform(concatMat_);\n}\n\nvoid CCPCA::fit(Eigen::MatrixXf const &K, Eigen::MatrixXf const &R,\n                bool const autoAlphaSelection, float const alpha,\n                float const varThresRatio, bool parallel,\n                unsigned int const nAlphas, float const maxLogAlpha,\n                bool const keepReports) {\n  if (autoAlphaSelection) {\n    fitWithBestAlpha(K, R, varThresRatio, parallel, nAlphas, maxLogAlpha,\n                     keepReports);\n  } else {\n    fitWithManualAlpha(K, R, alpha);\n  }\n}\n\nvoid CCPCA::fitWithBestAlpha(Eigen::MatrixXf const &K, Eigen::MatrixXf const &R,\n                             float const varThresRatio, bool parallel,\n                             unsigned int const nAlphas,\n                             float const maxLogAlpha, bool const keepReports) {\n  bestAlpha(K, R, varThresRatio, parallel, nAlphas, maxLogAlpha, keepReports);\n  cpca_.updateComponents(bestAlpha_);\n  featContribs_ = cpca_.getLoading(0);\n}\n\nvoid CCPCA::fitWithManualAlpha(Eigen::MatrixXf const &K,\n                               Eigen::MatrixXf const &R, float const alpha) {\n  Eigen::Index nSamplesK = K.rows();\n  Eigen::Index nSamplesR = R.rows();\n\n  if (K.cols() != R.cols()) {\n    std::cerr << \"# of rows of K and all matrix in R must be the same.\"\n              << std::endl;\n  }\n\n  Eigen::MatrixXf concatMat_(nSamplesK + nSamplesR, K.cols());\n  concatMat_ << K, R;\n\n  cpca_.fit(concatMat_, R, alpha);\n  featContribs_ = cpca_.getLoading(0);\n}\n\nEigen::MatrixXf CCPCA::transform(Eigen::MatrixXf const &X) {\n  return cpca_.transform(X);\n}\n\nfloat CCPCA::bestAlpha(Eigen::MatrixXf const &K, Eigen::MatrixXf const &R,\n                       float const varThresRatio, bool parallel,\n                       unsigned int const nAlphas, float const maxLogAlpha,\n                       bool const keepReports) {\n  Eigen::Index nSamplesK = K.rows();\n  Eigen::Index nSamplesR = R.rows();\n\n  if (K.cols() != R.cols()) {\n    std::cerr << \"# of rows of K and all matrix in R must be the same.\"\n              << std::endl;\n  }\n\n  Eigen::MatrixXf concatMat_(nSamplesK + nSamplesR, K.cols());\n  concatMat_ << K, R;\n\n  cpca_.fit(concatMat_, R, 0.0f);\n\n  Eigen::VectorXf bestProjK = cpca_.transform(K).col(0);\n  Eigen::VectorXf bestProjR = cpca_.transform(R).col(0);\n\n  bestAlpha_ = 0.0f;\n  auto baseVarK = scaledVar(bestProjK, bestProjR).first;\n  auto bestDiscrepancy =\n      1.0f / std::max(float(histIntersect(bestProjK, bestProjR)),\n                      std::numeric_limits<float>::min());\n\n  reports_.clear();\n  if (keepReports) {\n    reports_.push_back(std::make_tuple(0.0, float(bestDiscrepancy), baseVarK,\n                                       bestProjK, bestProjR,\n                                       cpca_.getLoading(0)));\n    if (parallel) {\n      parallel = false;\n      std::cout << \"current version keepReports only support non-parallel \"\n                   \"running. parallel is turned off.\"\n                << std::endl;\n    }\n  }\n\n  auto alphas = cpca_.logspace(-1, maxLogAlpha, nAlphas - 1);\n\n  if (!parallel) {\n    // non-parallel ver\n    for (auto const &alpha : alphas) {\n      cpca_.updateComponents(alpha);\n\n      Eigen::VectorXf tmpProjK = cpca_.transform(K).col(0);\n      Eigen::VectorXf tmpProjR = cpca_.transform(R).col(0);\n\n      auto varK = scaledVar(tmpProjK, tmpProjR).first;\n      auto discrepancy =\n          1.0f / std::max(float(histIntersect(tmpProjK, tmpProjR)),\n                          std::numeric_limits<float>::min());\n\n      if (varK >= baseVarK * varThresRatio && discrepancy > bestDiscrepancy) {\n        bestDiscrepancy = discrepancy;\n        bestAlpha_ = alpha;\n      }\n\n      if (keepReports) {\n        reports_.push_back(std::make_tuple(alpha, float(bestDiscrepancy), varK,\n                                           tmpProjK, tmpProjR,\n                                           cpca_.getLoading(0)));\n      }\n    }\n  } else {\n    // parallel version\n    auto numWorkers = std::max(std::thread::hardware_concurrency(),\n                               1u); // obtain max thread num\n    std::vector<std::thread> worker;\n    auto n = alphas.size();\n    std::vector<std::pair<float, float>> varAndDiscpSet(n, {0.0f, 0.0f});\n\n    for (size_t i = 0; i < numWorkers; ++i) {\n      worker.emplace_back(\n          [&](size_t id) {\n            auto r0 = n / numWorkers * id + std::min(n % numWorkers, id);\n            auto r1 =\n                n / numWorkers * (id + 1) + std::min(n % numWorkers, id + 1);\n\n            for (auto j = r0; j < r1; ++j) {\n              Eigen::VectorXf component;\n              if (numWorkers > 4) {\n                // less mtx locks but more steps\n                mtx.lock();\n                auto alpha = alphas[j];\n                Eigen::MatrixXf diffCov = cpca_.getDiffCov(alpha);\n                mtx.unlock();\n\n                Eigen::SelfAdjointEigenSolver<Eigen::MatrixXf> es(diffCov);\n                component = es.eigenvectors().rightCols(1);\n              } else {\n                // less steps but more mtx locks\n                mtx.lock();\n                auto alpha = alphas[j];\n                cpca_.updateComponents(alpha);\n                component = cpca_.getComponent(0);\n                mtx.unlock();\n              }\n\n              Eigen::VectorXf tmpProjK = K * component;\n              Eigen::VectorXf tmpProjR = R * component;\n\n              auto varK = scaledVar(tmpProjK, tmpProjR).first;\n              auto discrepancy =\n                  1.0f / std::max(float(histIntersect(tmpProjK, tmpProjR)),\n                                  std::numeric_limits<float>::min());\n              mtx.lock();\n              varAndDiscpSet[j] = {varK, discrepancy};\n              mtx.unlock();\n            }\n          },\n          i);\n    }\n    for (auto &w : worker)\n      w.join();\n\n    for (size_t i = 0; i < n; ++i) {\n      auto var = varAndDiscpSet[i].first;\n      auto discrepancy = varAndDiscpSet[i].second;\n      if (var >= baseVarK * varThresRatio && discrepancy > bestDiscrepancy) {\n        bestDiscrepancy = discrepancy;\n        bestAlpha_ = alphas[i];\n      }\n    }\n  }\n\n  return bestAlpha_;\n}\n\nstd::pair<float, float> CCPCA::scaledVar(Eigen::VectorXf const &a,\n                                         Eigen::VectorXf const &b) {\n  float minVal = std::min(a.minCoeff(), b.minCoeff());\n  float maxVal = std::max(a.maxCoeff(), b.maxCoeff());\n  float range = std::max(maxVal - minVal, std::numeric_limits<float>::min());\n\n  float varA = ((a.array() - a.mean()) / range).array().square().mean();\n  float varB = ((b.array() - b.mean()) / range).array().square().mean();\n\n  return {varA, varB};\n}\n\nfloat CCPCA::binWidthScott(Eigen::VectorXf const &vals) {\n  auto n = vals.size();\n  float sd = 0.0f;\n  if (n > 1) {\n    sd = std::sqrt((vals.array() - vals.mean()).square().sum() / float(n - 1));\n  }\n  float denom = std::max(std::pow(float(n), 1.0f / 3.0f),\n                         std::numeric_limits<float>::min());\n  float binWidth = 3.5f * sd / denom;\n\n  return binWidth;\n}\n\nint CCPCA::histIntersect(Eigen::VectorXf const &a, Eigen::VectorXf const &b) {\n  float minVal = std::min(a.minCoeff(), b.minCoeff());\n  float maxVal = std::max(a.maxCoeff(), b.maxCoeff());\n  float range = std::max(maxVal - minVal, std::numeric_limits<float>::min());\n  auto nA = a.size();\n  auto nB = b.size();\n\n  Eigen::VectorXf tmpA = (a.array() - minVal) / range;\n  Eigen::VectorXf tmpB = (b.array() - minVal) / range;\n  Eigen::VectorXf tmpAB(nA + nB);\n  tmpAB << tmpA, tmpB;\n\n  float binW =\n      std::max(binWidthScott(tmpAB), std::numeric_limits<float>::min());\n  unsigned int nBins = static_cast<unsigned int>(1.0f / binW) + 1;\n\n  std::vector<int> countsA(nBins, 0);\n  std::vector<int> countsB(nBins, 0);\n\n  for (Eigen::Index i = 0; i < nA; ++i) {\n    int binIndex = int(tmpA(i) / binW);\n    countsA[binIndex]++;\n  }\n  for (Eigen::Index i = 0; i < nB; ++i) {\n    int binIndex = int(tmpB(i) / binW);\n    countsB[binIndex]++;\n  }\n\n  int histIntersect = 0;\n  for (unsigned int i = 0; i < nBins; ++i) {\n    histIntersect += std::min(countsA[i], countsB[i]);\n  }\n\n  return histIntersect;\n}\n", "meta": {"hexsha": "f3e27e6b3cfbfbdfdf731875534b4daa6f4032d7", "size": 8872, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ccpca/ccpca.cpp", "max_stars_repo_name": "takanori-fujiwara/ccpca", "max_stars_repo_head_hexsha": "e2a2f57ca5d9ada00bf91892f7f5c4fa570d6110", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2019-07-16T03:29:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-19T14:59:11.000Z", "max_issues_repo_path": "ccpca/ccpca.cpp", "max_issues_repo_name": "takanori-fujiwara/ccpca", "max_issues_repo_head_hexsha": "e2a2f57ca5d9ada00bf91892f7f5c4fa570d6110", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ccpca/ccpca.cpp", "max_forks_repo_name": "takanori-fujiwara/ccpca", "max_forks_repo_head_hexsha": "e2a2f57ca5d9ada00bf91892f7f5c4fa570d6110", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-07-16T03:35:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-30T05:41:07.000Z", "avg_line_length": 33.8625954198, "max_line_length": 80, "alphanum_fraction": 0.5740532011, "num_tokens": 2425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.4949701453510786}}
{"text": "/**\n * @file line_search_test.cpp\n * @author Chenzhe Diao\n *\n * Test file for line search optimizer.\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\n\n#include <mlpack/core.hpp>\n#include <mlpack/core/optimizers/line_search/line_search.hpp>\n#include <mlpack/core/optimizers/fw/test_func_fw.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n\nusing namespace std;\nusing namespace arma;\nusing namespace mlpack;\nusing namespace mlpack::optimization;\n\nBOOST_AUTO_TEST_SUITE(LineSearchTest);\n\n/**\n * Simple test of Line Search with TestFuncFW function.\n */\nBOOST_AUTO_TEST_CASE(FuncFWTest)\n{\n  vec x1 = zeros<vec>(3);\n  vec x2;\n  x2 << 0.2 << 0.4 << 0.6;\n\n  TestFuncFW f;\n  LineSearch s;\n\n  double result = s.Optimize(f, x1, x2);\n\n  BOOST_REQUIRE_SMALL(result, 1e-10);\n  BOOST_REQUIRE_SMALL(x2[0] - 0.1, 1e-10);\n  BOOST_REQUIRE_SMALL(x2[1] - 0.2, 1e-10);\n  BOOST_REQUIRE_SMALL(x2[2] - 0.3, 1e-10);\n}\n\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "688362e71b1c4d4c74aa3f98624cb9d6d0b8d755", "size": 1187, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/line_search_test.cpp", "max_stars_repo_name": "chigur/mlpack", "max_stars_repo_head_hexsha": "aff1eda03b7c279acb6d3e660d5c5a6f697d3735", "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/tests/line_search_test.cpp", "max_issues_repo_name": "chigur/mlpack", "max_issues_repo_head_hexsha": "aff1eda03b7c279acb6d3e660d5c5a6f697d3735", "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/tests/line_search_test.cpp", "max_forks_repo_name": "chigur/mlpack", "max_forks_repo_head_hexsha": "aff1eda03b7c279acb6d3e660d5c5a6f697d3735", "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": 23.74, "max_line_length": 78, "alphanum_fraction": 0.7228306655, "num_tokens": 349, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.6261241702517975, "lm_q1q2_score": 0.4949701398359392}}
{"text": "#pragma once\n\n#include <boost/multiprecision/gmp.hpp>\n#include <math.h>\n#include <time.h>\n\n#include \"FiniteFields.hpp\"\n#include \"FastFourierTransform.hpp\"\n#include \"NumberTheoreticTransform.hpp\"\n\nnamespace ligero {\n\nclass SecretSharingNTT {\n\tpublic:\n\t\t/* Constructors allowing some flexibility in the choice of domains */\n\t\t~SecretSharingNTT() {\n\t\t\tdelete _smallDomain;\n\t\t\tdelete _largeDomain;\n\t\t}\n\t\tSecretSharingNTT(size_t modulusIdx, size_t lSecretLength, size_t kDegree, size_t nShares, void (*computeSmall) (uint64_t*,uint64_t const*), void (*computeLarge) (uint64_t*,uint64_t const*)) : modulusIdx_(modulusIdx), lSecretLength_(lSecretLength), kDegree_(kDegree), nNumberShares_(nShares) {\n\t\t\tthis->dCompositeDomainSize_ = nShares;\n\n\t\t    _smallDomain = new NTT(modulusIdx, this->kDegree_, computeSmall);\n\t\t    _largeDomain = new NTT(modulusIdx, this->nNumberShares_, computeLarge);\n\t\t};\n\n\t\tint share(uint64_t *secret);\n\t\tint reconstruct(uint64_t *eval, bool exapnded = false);\n\n\t\tint padMany(uint64_t *secrets, size_t lrows);\n\t\tint shareMany(uint64_t *secrets, size_t lrows);\n\t\tint reconstructMany(uint64_t *secrets, size_t lrows);\n\n\t\tbool degreeTest(uint64_t *eval);\n\t\tbool zeroTest(uint64_t *eval, bool expanded = false);\n\t\tbool zeroSumTest(uint64_t *eval);\n\t\tbool zeroSumTestSigmaProtocol(uint64_t *eval, std::vector<uint64_t> beta);\n\n\tprotected:\n\t\tint padSecret(uint64_t *secret);\n\t\tint padPolynominal(uint64_t *secret);\n\t\tint padShares(uint64_t *secret);\n\t\tint padIntrablocRandomness(uint64_t *secret);\n\n\t\tsize_t  modulusIdx_;\n\t\tsize_t\tlSecretLength_;\n\t\tsize_t\tkDegree_;\n\t\tsize_t\tnNumberShares_;\n\t\tsize_t\tdCompositeDomainSize_;\n\n\t\tNTT \t*_smallDomain;\n\t\tNTT\t\t*_largeDomain;\n};\n\ntemplate<typename FieldT>\nclass SecretSharingInterface: SecretSharingNTT {\n\tpublic:\n\t\t/* Constructors allowing some flexibility in the choice of domains */\n\t\tSecretSharingInterface(size_t modulusIdx, size_t lSecretLength, size_t kDegree, size_t nShares, void (*computeSmall) (uint64_t*,uint64_t const*), void (*computeLarge) (uint64_t*,uint64_t const*)) : SecretSharingNTT(modulusIdx, lSecretLength, kDegree, nShares, computeSmall, computeLarge) {\n\t\t\tthis->dCompositeDomainSize_ = nShares;\n\t\t};\n\n\t\tusing SecretSharingNTT::degreeTest;\n\t\tusing SecretSharingNTT::zeroTest;\n\t\tusing SecretSharingNTT::zeroSumTest;\n\t\tusing SecretSharingNTT::share;\n\t\tusing SecretSharingNTT::reconstruct;\n\n\t\tint share(FieldT *secret);\n\t\tint reconstruct(FieldT *eval, bool expanded = false);\n\n\t\tint padMany(FieldT *secrets, size_t lrows);\n\t\tint padIntrablocRandomness(FieldT *secret);\n\t\tint shareMany(FieldT *secrets, size_t lrows);\n\t\tint reconstructMany(FieldT *secrets, size_t lrows);\n\n\t\tbool degreeTest(FieldT *eval);\n\t\tbool zeroTest(FieldT *eval, bool expanded = false);\n\t\tbool zeroSumTestSigmaProtocol(FieldT *eval, std::vector<uint64_t> beta);\n\t\tbool zeroSumTest(FieldT *eval);\n\t\tFieldT sumReconstruct(FieldT *eval);\n\n\tprotected:\n\t\tint padSecret(FieldT *secret);\n\t\tint padPolynominal(FieldT *secret);\n\t\tint padShares(FieldT *secret);\n\t\t\n\t\t// adapter\n\t\tstd::vector<uint64_t> demote(FieldT *eval, size_t length);\n\t\tvoid promote(uint64_t *eval, size_t length, FieldT *dest);\n};\n\n// Implementation\n// =============================================================================================\n\n// Secret Sharing Interface\ntemplate <typename FieldT>\ninline int SecretSharingInterface<FieldT>::padSecret(FieldT *secret) {\n\tFieldT::randomVector(secret + this->lSecretLength_, this->kDegree_ - this->lSecretLength_, true);\n\treturn 0;\n}\n\ntemplate <typename FieldT>\ninline int SecretSharingInterface<FieldT>::padIntrablocRandomness(FieldT *secret) {\n\tfor (size_t i = this->lSecretLength_; i < kDegree_ ;i++) {\n\t\tsecret[i] = FieldT(0); \n\t}\n\n\treturn 0;\n}\n\ntemplate <typename FieldT>\ninline int SecretSharingInterface<FieldT>::padPolynominal(FieldT *secret) {\n\tfor (size_t i = this->kDegree_; i < nNumberShares_;i++) {\n\t\tsecret[i] = FieldT(0);\n\t}\n\n\treturn 0;\n}\n\ntemplate <typename FieldT>\ninline int SecretSharingInterface<FieldT>::padShares(FieldT *secret) {\n\tfor (size_t i = this->nNumberShares_; i < dCompositeDomainSize_ ;i++) {\n\t\tsecret[i] = FieldT(0);\n\t}\n\n\treturn 0;\n}\n\ntemplate <typename FieldT>\nint SecretSharingInterface<FieldT>::padMany(FieldT *secret, size_t lrows) {\n\n\t// Add randomness for padding\n\tfor (size_t i = 0; i < lrows; i++) {\n\t\tthis->padSecret(secret + i * this->nNumberShares_);\n\t}\n\n\treturn 0;\n}\n\ntemplate <typename FieldT>\nint SecretSharingInterface<FieldT>::share(FieldT *secret) {\n\n\tstd::vector<uint64_t> secret64 = demote(secret, this->nNumberShares_); \n\tthis->share(&secret64[0]);\n\tpromote(&secret64[0], this->nNumberShares_, secret); \n\n\treturn 0;\n}\n\n// this method is used when the resulting degree of the polynomial is larger than the domain space of the secret\ntemplate <typename FieldT>\nint SecretSharingInterface<FieldT>::reconstruct(FieldT *eval, bool expandedDegree) {\n\tstd::vector<uint64_t> eval64 = demote(eval, this->nNumberShares_); \n\tthis->reconstruct(&eval64[0], expandedDegree);\n\tpromote(&eval64[0], this->kDegree_, eval); \n\n\treturn 0;\n}\n\ntemplate <typename FieldT>\nstd::vector<uint64_t> SecretSharingInterface<FieldT>::demote(FieldT *eval, size_t length) {\n\tstd::vector<uint64_t> temp(length);\n\tfor (size_t idx = 0; idx < length; idx++) {\n\t\ttemp[idx] = static_cast<uint64_t>(eval[idx].getValue());\n\t}\n\n\treturn temp;\n}\n\ntemplate <typename FieldT>\nvoid SecretSharingInterface<FieldT>::promote(uint64_t *eval, size_t length, FieldT *dest) {\n\tfor (size_t idx = 0; idx < length; idx++) {\n\t\tdest[idx] = FieldT(eval[idx]);\n\t}\n}\n\ntemplate <typename FieldT>\nbool SecretSharingInterface<FieldT>::degreeTest(FieldT *eval) {\n\n\tstd::vector<uint64_t> eval64 = demote(eval,this->nNumberShares_); \n\treturn this->degreeTest(&eval64[0]);\n}\n\ntemplate <typename FieldT>\nbool SecretSharingInterface<FieldT>::zeroTest(FieldT *eval, bool largerDegree) {\n\n\tstd::vector<FieldT> localCopy(eval, eval + this->nNumberShares_);\n\treconstruct(&localCopy[0], largerDegree);\n\n\tfor (size_t i = 0; i < this->lSecretLength_; i++) {\n\t\tif (!(localCopy[i] == FieldT(0))) return false;\n\t}\n\n\treturn true;\n}\n\ntemplate <typename FieldT>\nbool SecretSharingInterface<FieldT>::zeroSumTest(FieldT *eval) {\n\t\n\tstd::vector<FieldT> localCopy(eval, eval+ this->nNumberShares_);\n\treconstruct(&localCopy[0], true);\n\n\tFieldT sum = FieldT(0);\n\tfor (size_t i = 0; i < this->lSecretLength_; i++) {\n\t\tsum += localCopy[i];\n\t}\n\n\tif (sum == FieldT(0)) return true;\n\telse return false;\n}\n\ntemplate <typename FieldT>\nFieldT SecretSharingInterface<FieldT>::sumReconstruct(FieldT *eval) {\n\t\n\tstd::vector<FieldT> localCopy(eval, eval+ this->nNumberShares_);\n\treconstruct(&localCopy[0], true);\n\n\tFieldT sum = FieldT(0);\n\tfor (size_t i = 0; i < this->lSecretLength_; i++) {\n\t\tsum += localCopy[i];\n\t}\n\n\treturn sum;\n}\n\ntemplate <typename FieldT>\nint SecretSharingInterface<FieldT>::shareMany(FieldT *secret, size_t lrows) {\n\n\t// std::cout << \"Performing FFTs: \" << lrows << std::endl; \n\tfor (size_t i = 0; i < lrows; i++) {\n\t\tshare(secret + i * this->nNumberShares_);\n\t}\n\n\treturn 0;\n}\n\ntemplate <typename FieldT>\nint SecretSharingInterface<FieldT>::reconstructMany(FieldT *secret, size_t lrows) {\n\n\tfor (size_t i = 0; i < lrows; i++) {\n\t\treconstruct(secret + i * this->nNumberShares_);\n\t}\n\n\treturn 0;\n}\n\ntemplate <typename FieldT>\nbool SecretSharingInterface<FieldT>::zeroSumTestSigmaProtocol(FieldT *eval, std::vector<uint64_t> beta) {\n\tstd::vector<uint64_t> eval64 = demote(eval, this->nNumberShares_); \n\t\n\treturn true;\n}\n\n\n// Secret Sharing NTT\n\nint SecretSharingNTT::padSecret(uint64_t *secret) {\n\n\t// uint64_t::randomVector(secret + this->lSecretLength_, this->kDegree_ - this->lSecretLength_, true);\n\treturn 0;\n}\n\nint SecretSharingNTT::padIntrablocRandomness(uint64_t *secret) {\n\n\tfor (size_t i = this->lSecretLength_; i < kDegree_ ;i++) {\n\t\tsecret[i] = uint64_t(0); \n\t}\n\n\treturn 0;\n}\n\nint SecretSharingNTT::padPolynominal(uint64_t *secret) {\n\n\tfor (size_t i = this->kDegree_; i < nNumberShares_;i++) {\n\t\tsecret[i] = uint64_t(0);\n\t}\n\n\treturn 0;\n}\n\nint SecretSharingNTT::padShares(uint64_t *secret) {\n\n\tfor (size_t i = this->nNumberShares_; i < dCompositeDomainSize_ ;i++) {\n\t\tsecret[i] = uint64_t(0);\n\t}\n\n\treturn 0;\n}\n\nint SecretSharingNTT::padMany(uint64_t *secret, size_t lrows) {\n\n\t// Add randomness for padding\n\tfor (size_t i = 0; i < lrows; i++) {\n\t\tthis->padSecret(secret + i * this->nNumberShares_);\n\t}\n\n\treturn 0;\n}\n\nint SecretSharingNTT::share(uint64_t *data) {\n\n\t// Interpolate Poly from Secret\n\t_smallDomain->inv_ntt(data);\n\n\tthis->padPolynominal(data);\n\n\t// Evaluate Publicly Shared Data from Poly\n\t_largeDomain->ntt(data);\n\n\treturn 0;\n}\n\n// this method is used when the resulting degree of the polynomial is larger than the domain space of the secret\nint SecretSharingNTT::reconstruct(uint64_t *eval, bool expandedDegree) {\n\tsize_t degree = kDegree_;\n\n\t// Interpolate Poly from Publicly Shared Data\n\t_largeDomain->inv_ntt(eval);\n\n\t// if (expandedDegree) degree = kDegree_*2; \n\t// Because we evaluate on roots of unity, we can use coefs[i] + coefs[i+k]  \n\t// on k coefficients instead of a 2k evaluation\n\tif (expandedDegree) {\n\t\tfor (size_t i = 0; i < kDegree_; i++) {\n\t\t\t\tif (eval[i+kDegree_] > eval[i]) {\n\t\t\t\t\teval[i] = eval[i] - eval[i + kDegree_] + params<uint64_t>::P[this->modulusIdx_];\n\t\t\t\t} else {\n\t\t\t\t\teval[i] = eval[i] - eval[i + kDegree_];\n\t\t\t\t}\n\t\t\t}\n\t}\n\n\t// Evaluate Poly Into Secret\n\t_smallDomain->ntt(eval);\n\n\t// rebuild accounting for the stride implied by the larger degree\n\tsize_t stride = degree/this->kDegree_;\n\tfor (size_t col = 0; col < this->lSecretLength_; col++) {\n\t\teval[col] = eval[col*stride];\n\t}\n\n\treturn 0;\n}\n\nbool SecretSharingNTT::degreeTest(uint64_t *eval) {\n\n\t// Interpolate Poly from Publicly Shared Data\n\tstd::vector<uint64_t> localCopy(eval, eval + this->nNumberShares_);\n\t_largeDomain->inv_ntt(&localCopy[0]);\n\n\tfor (size_t i = kDegree_; i < nNumberShares_; i++) {\n\t\tif (!(localCopy[i] == uint64_t(0))) {\n\t\t\tDBG(\"val:\"<< localCopy[i] << \",degree>\" << i);\n\t\t\treturn false;\n\t\t}\n\t}\n\n\treturn true;\n}\n\nbool SecretSharingNTT::zeroTest(uint64_t *eval, bool largerDegree) {\n\n\tstd::vector<uint64_t> localCopy(eval, eval + this->nNumberShares_);\n\treconstruct(&localCopy[0], largerDegree);\n\n\tfor (size_t i = 0; i < this->lSecretLength_; i++) {\n\t\tif (!(localCopy[i] == uint64_t(0))) return false;\n\t}\n\n\treturn true;\n}\n\nbool SecretSharingNTT::zeroSumTest(uint64_t *eval) {\n\t\n\tstd::vector<uint64_t> localCopy(eval, eval+ this->nNumberShares_);\n\treconstruct(&localCopy[0], true);\n\n\tuint64_t sum = uint64_t(0);\n\tfor (size_t i = 0; i < this->lSecretLength_; i++) {\n\t\tsum += localCopy[i];\n\t}\n\n\tif (sum == uint64_t(0)) return true;\n\telse return false;\n}\n\nbool SecretSharingNTT::zeroSumTestSigmaProtocol(uint64_t *eval, std::vector<uint64_t> beta) {\n\n\tstd::vector<uint64_t> localCopy(eval, eval+ this->nNumberShares_);\n\treconstruct(&localCopy[0], true);\n\n\tfor (size_t i = 0; i < this->lSecretLength_; i++) {\n\t\tif (localCopy[i] != beta[i]) return false;\n\t}\n\n\treturn true;\n}\n\nint SecretSharingNTT::shareMany(uint64_t *secret, size_t lrows) {\n\n\t// std::cout << \"Performing FFTs: \" << lrows << std::endl; \n\tfor (size_t i = 0; i < lrows; i++) {\n\t\tshare(secret + i * this->nNumberShares_);\n\t}\n\n\treturn 0;\n}\n\nint SecretSharingNTT::reconstructMany(uint64_t *secret, size_t lrows) {\n\n\tfor (size_t i = 0; i < lrows; i++) {\n\t\treconstruct(secret + i * this->nNumberShares_);\n\t}\n\n\treturn 0;\n}\n\n}\n", "meta": {"hexsha": "91a01bb7fc9826448f11135beeb2bdcbe7b2f269", "size": 11347, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/SecretSharingNTT.hpp", "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": "include/SecretSharingNTT.hpp", "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": "include/SecretSharingNTT.hpp", "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": 27.0166666667, "max_line_length": 294, "alphanum_fraction": 0.7083810699, "num_tokens": 3278, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4949618964587064}}
{"text": "/**\n * \\file SD1OverdriveFilter.cpp\n */\n\n#include <ATK/Distortion/SD1OverdriveFilter.h>\n\n#include <stdexcept>\n\n#include <boost/math/special_functions/sign.hpp>\n\n#include <ATK/Utility/fmath.h>\n#include <ATK/Utility/ScalarNewtonRaphson.h>\n\nnamespace ATK\n{\n  template<typename DataType_>\n  class SD1OverdriveFilter<DataType_>::SD1OverdriveFunction\n  {\n  public:\n    using DataType = DataType_;\n  protected:\n    const DataType R;\n    const DataType R1;\n    const DataType C;\n    const DataType Q;\n    DataType drive = 0.5;\n    const DataType is;\n    const DataType vt;\n\n    DataType ieq = 0;\n    DataType i = 0;\n\n    DataType expdiode_y1_p = 1;\n    DataType expdiode_y1_m = 1;\n\n  public:\n    SD1OverdriveFunction(DataType dt, DataType R, DataType C, DataType R1, DataType Q, DataType is, DataType vt)\n      :R(R), R1(R1), C(2 * C / dt), Q(Q), is(is), vt(vt)\n    {\n    }\n    \n    void set_drive(DataType drive)\n    {\n      this->drive = (R1 + drive * Q);\n    }\n\n    std::pair<DataType, DataType> operator()(const DataType* ATK_RESTRICT input, DataType* ATK_RESTRICT output, DataType y1)\n    {\n      auto x1 = input[0];\n      y1 -= x1;\n      expdiode_y1_p = fmath::exp(y1 / vt);\n      expdiode_y1_m = 1 / expdiode_y1_p;\n\n      DataType diode1 = is * (expdiode_y1_p - 2 * expdiode_y1_m + 1);\n      DataType diode1_derivative = is * (expdiode_y1_p + 2 * expdiode_y1_m) / vt;\n\n      i = (C * x1 - ieq) / (1 + R * C);\n\n      return std::make_pair(y1 / drive + diode1 - i, 1 / drive + diode1_derivative);\n    }\n    \n    void update_state(const DataType* ATK_RESTRICT input, DataType* ATK_RESTRICT output)\n    {\n      auto x1 = input[0];\n      ieq = 2 * C * (x1 - i * R) - ieq;\n    }\n\n    DataType estimate(const DataType* ATK_RESTRICT input, DataType* ATK_RESTRICT output)\n    {\n      auto x0 = input[-1];\n      auto x1 = input[0];\n      auto y0 = output[-1];\n      return affine_estimate(x0, x1, y0);\n    }\n\n    DataType affine_estimate(DataType x0, DataType x1, DataType y0)\n    {\n      y0 -= x0;\n      auto sinh = is * (expdiode_y1_p - 2 * expdiode_y1_m + 1);\n      auto cosh = is * (expdiode_y1_p + 2 * expdiode_y1_m);\n      auto i = (C * x1 - ieq) / (1 + R * C);\n\n      return (i - (sinh - y0 / vt * cosh)) / (cosh / vt + (1 / drive)) + x1;\n    }\n  };\n  \n  template <typename DataType>\n  SD1OverdriveFilter<DataType>::SD1OverdriveFilter()\n    :TypedBaseFilter<DataType>(1, 1)\n  {\n    input_delay = 1;\n    output_delay = 1;\n  }\n\n  template <typename DataType>\n  SD1OverdriveFilter<DataType>::~SD1OverdriveFilter()\n  {\n  }\n\n  template <typename DataType>\n  void SD1OverdriveFilter<DataType>::setup()\n  {\n    Parent::setup();\n    optimizer = std::make_unique<ScalarNewtonRaphson<SD1OverdriveFunction, num_iterations, true>>(SD1OverdriveFunction(static_cast<DataType>(1. / input_sampling_rate),\n      static_cast<DataType>(4.7e3), static_cast<DataType>(0.047e-6), static_cast<DataType>(33e3),\n      static_cast<DataType>(1e6), static_cast<DataType>(1e-12), static_cast<DataType>(26e-3)));\n\n    optimizer->get_function().set_drive(drive);\n  }\n\n  template <typename DataType_>\n  void SD1OverdriveFilter<DataType_>::set_drive(DataType_ drive)\n  {\n    if(drive < 0 || drive > 1)\n    {\n      throw std::out_of_range(\"Drive must be a value between 0 and 1\");\n    }\n    this->drive = drive;\n    if(optimizer)\n    {\n        optimizer->get_function().set_drive(drive);\n    }\n  }\n\n  template <typename DataType_>\n  DataType_ SD1OverdriveFilter<DataType_>::get_drive() const\n  {\n    return drive;\n  }\n\n  template <typename DataType>\n  void SD1OverdriveFilter<DataType>::process_impl(gsl::index size) const\n  {\n    const DataType* ATK_RESTRICT input = converted_inputs[0];\n    DataType* ATK_RESTRICT output = outputs[0];\n    for(gsl::index i = 0; i < size; ++i)\n    {\n      optimizer->optimize(input + i, output + i);\n      optimizer->get_function().update_state(input + i, output + i);\n    }\n  }\n\n#if ATK_ENABLE_INSTANTIATION\n  template class SD1OverdriveFilter<float>;\n#endif\n  template class SD1OverdriveFilter<double>;\n}\n", "meta": {"hexsha": "a71c9f1d2d83a7b2b508e3064e4608056c02dabe", "size": 4003, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ATK/Distortion/SD1OverdriveFilter.cpp", "max_stars_repo_name": "D-J-Roberts/AudioTK", "max_stars_repo_head_hexsha": "accf009d7238f32702eb1d5ee23c5148fc68e3bd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 249.0, "max_stars_repo_stars_event_min_datetime": "2015-01-05T13:36:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T18:47:46.000Z", "max_issues_repo_path": "ATK/Distortion/SD1OverdriveFilter.cpp", "max_issues_repo_name": "D-J-Roberts/AudioTK", "max_issues_repo_head_hexsha": "accf009d7238f32702eb1d5ee23c5148fc68e3bd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 22.0, "max_issues_repo_issues_event_min_datetime": "2015-07-28T15:20:24.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-11T14:18:19.000Z", "max_forks_repo_path": "ATK/Distortion/SD1OverdriveFilter.cpp", "max_forks_repo_name": "D-J-Roberts/AudioTK", "max_forks_repo_head_hexsha": "accf009d7238f32702eb1d5ee23c5148fc68e3bd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 48.0, "max_forks_repo_forks_event_min_datetime": "2015-08-15T12:08:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-07T02:33:07.000Z", "avg_line_length": 27.0472972973, "max_line_length": 167, "alphanum_fraction": 0.6475143642, "num_tokens": 1195, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4949618919136958}}
{"text": "#include \"CEGO/CEGO.hpp\"\n#include <Eigen/Dense>\n#if defined(PYBIND11)\n#include <pybind11/embed.h>\n#include <pybind11/pybind11.h>\n#include <pybind11/numpy.h>\n#include <pybind11/stl.h>\n#include <pybind11/eigen.h>\nnamespace py = pybind11;\n#include <atomic>\n\nstd::atomic_size_t Ncalls(0);\n\ninline bool ValidNumber(double x)\n{\n    // Idea from http://www.johndcook.com/IEEE_exceptions_in_cpp.html\n    return (x <= DBL_MAX && x >= -DBL_MAX);\n};\n\nenum fitting_options{ FIT_P, FIT_RHOV, FIT_RHOL};\n\nclass RatPolyAncillary {\npublic:\n    double m_Tt, m_Tc, m_pc, m_Dc;\n    std::size_t m_Nnum, m_Nden;\n    Eigen::ArrayXd m_LHS, m_THETA, m_T;\n    std::string m_name;\n    fitting_options to_fit = FIT_RHOV;\n    RatPolyAncillary(const std::string &name, const std::size_t Nnum, const std::size_t Nden) : m_Nnum(Nnum), m_Nden(Nden), m_name(name)\n    {\n        py::module ct = py::module::import(\"ctREFPROP.ctREFPROP\"); // Import cytpes wrapper of REFPROP dll\n        std::string RPPREFIX(getenv(\"RPPREFIX\")); \n        auto R = ct.attr(\"REFPROPFunctionLibrary\")(RPPREFIX + \"/REFPRP64.DLL\");\n        auto version = R.attr(\"RPVersion\")().cast<std::string>();\n        auto setup_info = R.attr(\"SETUPdll\")(1, name+\".FLD\", \"HMX.BNC\",\"DEF\");\n        if (setup_info.attr(\"ierr\").cast<int>() != 0) {\n            throw std::invalid_argument( setup_info.attr(\"herr\").cast<std::string>() );\n        }\n        auto info = R.attr(\"INFOdll\")(1);\n        m_pc = info.attr(\"Pc\").cast<double>();\n        m_Tc = info.attr(\"Tc\").cast<double>();\n        m_Tt = info.attr(\"Ttrp\").cast<double>();\n        m_Dc = info.attr(\"Dc\").cast<double>();\n\n        std::size_t N = 300;\n        m_LHS.resize(N);\n        m_THETA.resize(N);\n        m_T.resize(N);\n        std::vector<double> z(1,1);\n        Eigen::ArrayXd Tvec = Eigen::ArrayXd::LinSpaced(N, m_Tc*0.999, 0.5*m_Tt);\n        Eigen::Index j = 0;\n\n        for (auto i = 0; i < Tvec.size(); ++i){\n            auto o = R.attr(\"TQFLSHdll\")(Tvec[i], 1, &z, 0);\n            int ierr = o.attr(\"ierr\").cast<int>();\n            if (ierr <= 100){\n                //std::cout << Tvec(i) << \" \" << o << std::endl;\n                if (to_fit == FIT_P){\n                    double p = o.attr(\"P\").cast<double>();\n                    if (!ValidNumber(p)){ continue; }\n                    m_LHS(j) = log(p/m_pc)*Tvec(i)/m_Tc;\n                }\n                else if (to_fit == FIT_RHOL) {\n                    double DL = o.attr(\"Dl\").cast<double>();\n                    if (!ValidNumber(DL)) { continue; }\n                    m_LHS(j) = DL/m_Dc;\n                }\n                else if (to_fit == FIT_RHOV) {\n                    double DV = o.attr(\"Dv\").cast<double>();\n                    if (!ValidNumber(DV)) { continue; }\n                    m_LHS(j) = log(DV / m_Dc);//*Tvec(i)/m_Tc;\n                }\n                else {\n                    throw std::invalid_argument(\"Argument for what to fit is invalid\");\n                }\n                m_THETA(j) = 1-(Tvec(i)/m_Tc);\n                m_T(j) = Tvec(i);\n                j++;\n            }\n        }\n        m_LHS.conservativeResize(j-1);\n        m_THETA.conservativeResize(j-1);\n        m_T.conservativeResize(j - 1);\n    }\n    void plot_curve(){\n        py::module plt = py::module::import(\"matplotlib.pyplot\"); // Import matplotlib\n        plt.attr(\"plot\")(m_THETA, m_LHS);\n        plt.attr(\"show\")();\n    }\n    void plot_deviation(const Eigen::ArrayXd &c) {\n\n        py::module plt = py::module::import(\"matplotlib.pyplot\"); // Import matplotlib\n        Eigen::ArrayXd T = m_Tc*(1+m_THETA), deviation;\n        std::string ylabel;\n        if (to_fit == FIT_P){\n            Eigen::ArrayXd pfit = eval_RHS(m_THETA, c).exp();\n            Eigen::ArrayXd peos = m_LHS.exp();\n            deviation = (pfit/peos-1)*100;\n            ylabel = \"Pressure deviation (%)\";\n        }\n        else if (to_fit == FIT_RHOV) {\n            Eigen::ArrayXd rhofit = eval_RHS(m_THETA, c).exp()*m_Dc;\n            Eigen::ArrayXd rhoeos = m_LHS.exp()*m_Dc;\n            deviation = (rhofit / rhoeos - 1) * 100;\n            ylabel = \"Density deviation (%)\";\n        }\n        else if (to_fit == FIT_RHOL) {\n            Eigen::ArrayXd rhofit = eval_RHS(m_THETA, c)*m_Dc;\n            Eigen::ArrayXd rhoeos = m_LHS;\n            deviation = (rhofit / rhoeos - 1) * 100;\n            ylabel = \"Density deviation (%)\";\n        }\n        using namespace pybind11::literals;\n        plt.attr(\"plot\")(1 / (m_THETA + 1), deviation);\n        plt.attr(\"ylabel\")(ylabel);\n        plt.attr(\"axvline\")(m_Tt / m_Tc, \"dashes\"_a = std::vector<double>(2, 2));\n        plt.attr(\"xlabel\")(\"$T/T_c$\");\n        plt.attr(\"savefig\")(m_name + \".pdf\"); \n        plt.attr(\"close\")();\n    }\n    Eigen::ArrayXd eval_RHS(const Eigen::ArrayXd& x, const Eigen::ArrayXd &c) {\n        Eigen::ArrayXd num = Eigen::ArrayXd::Zero(x.size()), den = Eigen::ArrayXd::Zero(x.size());\n        assert(m_Nnum + m_Nden == c.size());\n        for (auto i = 0; i < m_Nnum; ++i) {\n            num += c[i]*x.pow(i);\n        }\n        for (auto i = 0; i < m_Nden; ++i) {\n            den += c[m_Nnum+i]*x.pow(i+1);\n        }\n        return num/(1+den);\n    }\n    double objective(const CEGO::AbstractIndividual *pind) {\n        const std::vector<double> &c = static_cast<const CEGO::NumericalIndividual<double>*>(pind)->get_coefficients();\n        return objective(Eigen::Map<const Eigen::ArrayXd>(&(c[0]), c.size()) );\n    }\n    double objective(const Eigen::ArrayXd &c) {\n        //Ncalls++;\n        return (eval_RHS(m_THETA, c) - m_LHS).square().sum();\n    }\n    void plot_trace(const std::vector<double> &best_costs) {\n        py::module plt = py::module::import(\"matplotlib.pyplot\"); // Import matplotlib\n        plt.attr(\"plot\")(best_costs);\n        plt.attr(\"show\")();\n    }\n};\n\nint main()\n{\n    py::scoped_interpreter interp{};\n    std::srand((unsigned int)time(0));\n\n    std::size_t Nnum = 4, Nden = 4;\n\n    // Construct the bounds\n    std::vector<CEGO::Bound> bounds;\n    for (auto i = 0; i < Nnum; ++i) { \n        bounds.push_back(CEGO::Bound(std::pair<double, double>(-10000, 10000)));\n    }\n    for (auto i = 0; i < Nden; ++i){\n        bounds.push_back(CEGO::Bound(std::pair<double, double>(-10000, 10000))); \n    }    \n    RatPolyAncillary rp(\"PROPANE\", Nnum, Nden);\n    rp.plot_curve();\n   \n    auto Ncalls = 0;\n    CEGO::CostFunction cost_wrapper = std::bind((double (RatPolyAncillary::*)(const CEGO::AbstractIndividual *)) &RatPolyAncillary::objective, &rp, std::placeholders::_1);\n    auto Nlayers = 1;\n    auto layers = CEGO::Layers<double>(cost_wrapper, bounds.size(), 40, Nlayers, 5);\n    layers.parallel = true;\n    layers.set_bounds(bounds);\n\n    auto flags = layers.get_evolver_flags();\n    flags[\"Nelite\"] = 2;\n    flags[\"Fmin\"] = 0.5;\n    flags[\"Fmax\"] = 0.5;\n    flags[\"CR\"] = 0.9;\n    layers.set_evolver_flags(flags);\n\n    std::vector<double> best_costs; \n    std::vector<std::vector<double> > objs;\n    double VTR = 1e-6, best_cost = 999999.0;\n    auto startTime = std::chrono::system_clock::now();\n    for (auto counter = 0; counter < 50000; ++counter) {\n        layers.do_generation();\n\n        // Store the best objective function in each layer\n        std::vector<double> oo;\n        for (auto &&cost_coefficients : layers.get_best_per_layer()) {\n            oo.push_back(std::get<0>(cost_coefficients));\n        }\n        objs.push_back(oo);\n\n        // For the overall best result, print it, and write JSON to file\n        auto best_layer = layers.get_best();\n        best_cost = std::get<0>(best_layer); best_costs.push_back(best_cost);\n        if (counter % 50 == 0) {\n            std::cout << counter << \": best: \" << best_cost << \"\\n \";// << CEGO::vec2string(best_coeffs) << \"\\n\";\n            //auto c = std::get<1>(best_layer);\n            //rp.plot_deviation(Eigen::Map<const Eigen::ArrayXd>(&(c[0]), c.size()));\n        }\n        if (best_cost < VTR){ break; }\n    }\n    auto best_layer = layers.get_best();\n    auto c = std::get<1>(best_layer);\n    rp.plot_deviation(Eigen::Map<const Eigen::ArrayXd>(&(c[0]), c.size()));\n    auto endTime = std::chrono::system_clock::now();\n    double elap = std::chrono::duration<double>(endTime - startTime).count();\n    std::cout << \"run:\" << elap << \" s\\n\";\n    std::cout << \"NFE:\" << Ncalls << std::endl;\n\n}\n\n#else\nint main(){\n    std::cout << \"Due to missing support for pybind11, this file cannot be run\\n\";\n}\n#endif", "meta": {"hexsha": "ee6bea588d5809fa50f04aa62df36cf824257741", "size": 8381, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/fit_ratpoly_ancillary.cxx", "max_stars_repo_name": "jedbrown/CEGO", "max_stars_repo_head_hexsha": "60e39319e577cf63e844d0818387aa9e486878f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2018-12-27T23:16:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-01T02:23:40.000Z", "max_issues_repo_path": "src/fit_ratpoly_ancillary.cxx", "max_issues_repo_name": "jedbrown/CEGO", "max_issues_repo_head_hexsha": "60e39319e577cf63e844d0818387aa9e486878f1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-03-17T19:27:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-17T15:27:44.000Z", "max_forks_repo_path": "src/fit_ratpoly_ancillary.cxx", "max_forks_repo_name": "jedbrown/CEGO", "max_forks_repo_head_hexsha": "60e39319e577cf63e844d0818387aa9e486878f1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-02-27T18:01:58.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-29T19:44:15.000Z", "avg_line_length": 38.6221198157, "max_line_length": 171, "alphanum_fraction": 0.554349123, "num_tokens": 2418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619436290699, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.49483246121921104}}
{"text": "#include <omp.h>\n\n#include <Eigen/Dense>\n#include <bitset>\n#include <iostream>\n#include <tuple>\n\n#include \"qpp.h\"\n\nusing namespace qpp;\nusing uint = unsigned int;\n\nstruct SimState {\n  ket state = ket::Zero(1);\n  int num_qubits = 0;\n  SimState() { state << 1; }\n};\n\ntypedef SimState* state_t;\n\nextern \"C\" state_t empty() { return new SimState; }\n\nextern \"C\" void discard(state_t s) { delete s; }\n\nextern \"C\" int qinit(state_t s) {\n  s->state = kron(s->state, 0_ket);\n  return s->num_qubits++;\n}\n\nenum Gate : int {\n  X = 0,\n  Y = 1,\n  Z = 2,\n  H = 3,\n  CNOT = 4,\n  CZ = 5,\n  TOF = 6,\n  FRED = 7,\n  PHASE = 8,\n  CPHASE = 9\n};\n\nextern \"C\" void unitary1(state_t s, Gate g, uint q) {\n  cmat u;\n  switch (g) {\n    case X:\n      u = gt.X;\n      break;\n    case Y:\n      u = gt.Y;\n      break;\n    case Z:\n      u = gt.Z;\n      break;\n    case H:\n      u = gt.H;\n      break;\n    default:\n      abort();\n  }\n  s->state = apply(s->state, u, {q});\n}\n\nextern \"C\" void unitary2(state_t s, Gate g, uint q1, uint q2) {\n  cmat u;\n  switch (g) {\n    case CNOT:\n      u = gt.CNOT;\n      break;\n    case CZ:\n      u = gt.CZ;\n      break;\n    default:\n      abort();\n  }\n  s->state = apply(s->state, u, {q1, q2});\n}\n\nextern \"C\" void unitary3(state_t s, Gate g, uint q1, uint q2, uint q3) {\n  cmat u;\n  switch (g) {\n    case TOF:\n      u = gt.TOF;\n      break;\n    case FRED:\n      u = gt.FRED;\n      break;\n    default:\n      abort();\n  }\n  s->state = apply(s->state, u, {q1, q2, q3});\n}\n\nextern \"C\" void punitary1(state_t s, Gate g, uint q, double p) {\n  cmat u = std::polar(1.0, M_PI * p) * gt.RZ(2 * M_PI * p);\n  switch (g) {\n    case PHASE:\n      break;\n    default:\n      abort();\n  }\n  s->state = apply(s->state, u, {q});\n}\n\nextern \"C\" void punitary2(state_t s, Gate g, uint q1, uint q2, double p) {\n  cmat u = std::polar(1.0, M_PI * p) * gt.RZ(2 * M_PI * p);\n  switch (g) {\n    case CPHASE:\n      break;\n    default:\n      abort();\n  }\n  s->state = applyCTRL(s->state, u, {q1}, {q2});\n}\n\nextern \"C\" bool measure(state_t s, uint q) {\n  --s->num_qubits;\n  auto measured = measure_seq(s->state, {q});\n  s->state = std::get<ST>(measured);\n  return std::get<RES>(measured)[0];\n}\n\ninline uint swap_bits(uint x, uint p1, uint p2) {\n  const uint y = ((x >> p1) & 1) ^ ((x >> p2) & 1);\n  return x ^ ((y << p1) | (y << p2));\n}\n\ninline void swap(ket& state, const idx numdims, const uint* const qs, uint n) {\n  using namespace Eigen;\n  PermutationMatrix<Dynamic, Dynamic> perm(1UL << numdims);\n\n#ifdef HAS_OPENMP\n#pragma omp parallel for\n#endif\n  for (idx i = 0; i < 1UL << numdims; ++i) {\n    idx j = i;\n    for (uint k = 0; k < n; ++k) {\n      j = swap_bits(j, numdims - qs[n - k - 1] - 1, k);\n    }\n    perm.indices()[i] = j;\n  }\n\n  state = perm * state;\n}\n\nextern \"C\" bool separable(state_t s, const uint* const qs, uint n) {\n  ket k = s->state;\n  swap(k, s->num_qubits, qs, n);\n  const idx dim = 1UL << n;\n  const idx rem = 1UL << (s->num_qubits - n);\n  auto coeffs = schmidtcoeffs(k, {rem, dim});\n  return std::count_if(coeffs.data(), coeffs.data() + coeffs.size(),\n                       [](double coeff) { return fabs(coeff) > chop; }) == 1;\n}\n\nextern \"C\" void print(state_t s) {\n  if (s->state.size() < 2) {\n    std::cout << \"(empty)\" << std::endl;\n  } else {\n    for (idx i = 0; i < s->state.size(); ++i) {\n      std::bitset<32> bs(i);\n      std::cout << \"|\";\n      for (int j = s->num_qubits - 1; j >= 0; --j) {\n        std::cout << bs[j];\n      }\n      std::cout << \"> : \" << s->state[i].real() << \" + \" << s->state[i].imag()\n                << \"i\" << std::endl;\n    }\n  }\n}\n", "meta": {"hexsha": "e7f70e535bfd5f3cfad7130248d6d524ff288acc", "size": 3563, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "qpp_stub/stub.cpp", "max_stars_repo_name": "psg-mit/twist-popl22", "max_stars_repo_head_hexsha": "fa495479ff021fb8793ae20d8cf786ed048f503d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2022-01-22T20:12:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T18:25:53.000Z", "max_issues_repo_path": "qpp_stub/stub.cpp", "max_issues_repo_name": "psg-mit/twist-popl22", "max_issues_repo_head_hexsha": "fa495479ff021fb8793ae20d8cf786ed048f503d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "qpp_stub/stub.cpp", "max_forks_repo_name": "psg-mit/twist-popl22", "max_forks_repo_head_hexsha": "fa495479ff021fb8793ae20d8cf786ed048f503d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2022-01-26T02:27:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T07:48:28.000Z", "avg_line_length": 20.8362573099, "max_line_length": 79, "alphanum_fraction": 0.526241931, "num_tokens": 1261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4948324560418365}}
{"text": "#include <iostream>\n\n#include <Eigen/Core>  // Eigen \u6838\u5fc3\u90e8\u5206\n#include <Eigen/Dense>  // \u7a20\u5bc6\u77e9\u9635\u7684\u4ee3\u6570\u8fd0\u7b97\uff08\u9006\uff0c\u7279\u5f81\u503c\u7b49\uff09\n#include <Eigen/Geometry>  // Eigen/Geometry \u6a21\u5757\u63d0\u4f9b\u4e86\u5404\u79cd\u65cb\u8f6c\u548c\u5e73\u79fb\u7684\u8868\u793a\n\n#include \"sophus/se3.hpp\"\n\n#include <opencv2/core.hpp>  // \u6838\u5fc3\u529f\u80fd\uff0c\u5305\u62ec\u57fa\u672c\u6570\u636e\u7ed3\u6784\n#include <opencv2/opencv.hpp>\n#include <opencv2/highgui.hpp>  // \u9ad8\u5c42GUI\u56fe\u50cf\u4ea4\u4e92\n#include <opencv2/features2d.hpp>  // \u7279\u5f81\u63d0\u53d6\u3001\u63cf\u8ff0\u3001\u5339\u914d\n\n// \u76f8\u673a\u5185\u53c2\nconst double f = 521, cx = 325.1, cy = 249.7;\n\nbool ORBFeatureDetectAndMatch(\n    cv::Mat &img_1, cv::Mat &img_2,\n    std::vector<cv::KeyPoint> &kps_1, \n    std::vector<cv::KeyPoint> &kps_2,\n    std::vector<cv::DMatch> &good_matches\n);\n\n\n\nbool PoseEstimation2d2d(\n    std::vector<cv::KeyPoint> &kps_1, \n    std::vector<cv::KeyPoint> &kps_2,\n    std::vector<cv::DMatch> &good_matches,\n    cv::Mat &R,\n    cv::Mat &t\n){\n    std::vector<cv::Point2f> points_1;\n    std::vector<cv::Point2f> points_2;\n    for(size_t i = 0; i < good_matches.size(); i++){\n        points_1.push_back(kps_1[good_matches[i].queryIdx].pt);\n        points_2.push_back(kps_2[good_matches[i].trainIdx].pt);\n    }\n\n    cv::Mat fundamental_matrix;\n    fundamental_matrix = cv::findFundamentalMat(points_1, points_2, CV_FM_8POINT);\n    std::cout << \"fundamental matrix = \\n\" << fundamental_matrix << std::endl;\n\n    const cv::Point2d principal_point(cx, cy);\n    cv::Mat essential_matrix;\n    essential_matrix = cv::findEssentialMat(points_1, points_2, f, principal_point);\n    std::cout << \"essential matrix = \\n\" << essential_matrix << std::endl;\n\n    cv::recoverPose(essential_matrix, points_1, points_2, R, t, f, principal_point);\n}\n\n\n\n\n\n\nint main(int argc, char **argv){\n    std::string file_path_1 = argv[1];\n    std::string file_path_2 = argv[2];\n\n    cv::Mat img_1 = cv::imread(file_path_1, cv::IMREAD_COLOR);\n    cv::Mat img_2 = cv::imread(file_path_2, cv::IMREAD_COLOR);\n\n    if (img_1.empty() || img_2.empty()){\n        std::cerr << \"cannot find image: \" << file_path_1 << \" or \" << file_path_2 << std::endl;\n        return -1;\n    }\n\n    // ORB feature detection and match\n    std::vector<cv::KeyPoint> kps_1, kps_2;\n    std::vector<cv::DMatch> good_matches;\n    ORBFeatureDetectAndMatch(img_1, img_2, kps_1, kps_2, good_matches);\n\n    // show the keypoints and matches\n    cv::Mat img_matches;\n    cv::drawMatches(img_1, kps_1, img_2, kps_2, good_matches, img_matches);\n    cv::imshow(\"matches between img_1 & img_2\", img_matches);\n    \n    cv::Mat R, t;\n    PoseEstimation2d2d(kps_1, kps_2, good_matches, R, t);\n    std::cout << \"R = \\n\" << R << std::endl;\n    std::cout << \"t = \\n\" << t << std::endl;\n\n\n    cv::waitKey(0);\n    return 0;\n}\n\n\n\n\n\n\nbool ORBFeatureDetectAndMatch(\n    cv::Mat &img_1, cv::Mat &img_2,\n    std::vector<cv::KeyPoint> &kps_1, \n    std::vector<cv::KeyPoint> &kps_2,\n    std::vector<cv::DMatch> &good_matches\n    ){\n    // orb\u63d0\u53d6\u7279\u5f81\u70b9\u548c\u63cf\u8ff0\u5b50\n    cv::Mat descriptor_1, descriptor_2;\n    cv::Ptr<cv::ORB> orb = cv::ORB::create();\n    orb->detectAndCompute(img_1, cv::noArray(), kps_1, descriptor_1);\n    orb->detectAndCompute(img_2, cv::noArray(), kps_2, descriptor_2);\n\n    // cv::Ptr<cv::DescriptorMatcher> matcher = cv::DescriptorMatcher::create(\"BruteForce-Hamming\");\n    // std::vector<cv::DMatch> match;\n    // matcher->match(descriptor_1, descriptor_2, match);\n\n\n    // // --\u7b2c\u56db\u6b65\uff1a\u5339\u914d\u70b9\u5bf9 \u7b5b\u9009\n    // auto min_max = minmax_element(match.begin(), match.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\n    // for (int i=0; i<descriptor_1.rows; i++){\n    //     if(match[i].distance <= std::max(2*min_dist, 30.0)){\n    //         good_matches.push_back(match[i]);\n    //     }\n    // }\n\n\n    // \u8fdb\u884c\u5339\u914d\n    cv::Ptr<cv::DescriptorMatcher> matcher = \n        cv::DescriptorMatcher::create(\"BruteForce-Hamming\");\n    std::vector<cv::DMatch> matches;\n    matcher->match(descriptor_1, descriptor_2, matches);\n\n    double min_dist = 10000;\n    for (auto &m: matches){\n        if (m.distance < min_dist){\n            min_dist = m.distance;\n        }\n    }\n\n    std::cout << \"min_dist = \" << min_dist << std::endl;\n    \n    for(size_t i = 0; i < matches.size(); i++){\n        if (matches[i].distance <= std::max(2 * min_dist, 30.0)){\n            good_matches.push_back(matches[i]);\n        }\n    }\n    std::cout << \"have found \" << good_matches.size() << \" good matches. \" << std::endl;\n    return true;\n}", "meta": {"hexsha": "bf0c742db07fbc10beef38234f3d136e67d4f009", "size": 4424, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "my_implementation_2/ch7/poseEstimation2d2d/poseEstimation2d2d.cpp", "max_stars_repo_name": "Mingrui-Yu/slambook2", "max_stars_repo_head_hexsha": "d31273192bd9fb5ac618f147105082022c87a005", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-09T14:18:15.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-09T14:18:15.000Z", "max_issues_repo_path": "my_implementation_2/ch7/poseEstimation2d2d/poseEstimation2d2d.cpp", "max_issues_repo_name": "Mingrui-Yu/slambook2", "max_issues_repo_head_hexsha": "d31273192bd9fb5ac618f147105082022c87a005", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "my_implementation_2/ch7/poseEstimation2d2d/poseEstimation2d2d.cpp", "max_forks_repo_name": "Mingrui-Yu/slambook2", "max_forks_repo_head_hexsha": "d31273192bd9fb5ac618f147105082022c87a005", "max_forks_repo_licenses": ["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.301369863, "max_line_length": 104, "alphanum_fraction": 0.6268083183, "num_tokens": 1468, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765706, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4948324508644618}}
{"text": "#include <boost/thread.hpp>\n#include <iostream>\n#include <vector>\n#include <cstdlib>\n#include <ctime>\n#include <math.h>\n#include <c2_algorithm.h>\n\nusing namespace std;\n\nc2_algorithm::c2_algorithm()\n{\n    pos = 0;\n    t_pos = 0;\n    vel = 0;\n    t_vel = 0;\n    acc = 0;\n    t_acc = 0;\n    last_vel = 0;\n    last_acc = 0;\n}\nc2_algorithm::~c2_algorithm()\n{\n}\n\ndouble c2_algorithm::sign(double x)\n{\n    if (x > 0)\n    {\n        return 1;\n    }\n    else if (x == 0)\n    {\n        return 0;\n    }\n    else\n    {\n        return -1;\n    }\n}\n\ndouble c2_algorithm::power(double x, int n)\n{\n    double val = 1.0;\n    while (n--)\n        val *= x;\n    return val;\n}\n\nvoid c2_algorithm::prepare()\n{\n    ek = (pos - t_pos) / jeck;\n    ek1 = (vel - t_vel) / jeck;\n}\n\ndouble c2_algorithm::sat(double x)\n{\n    if (x < -1)\n    {\n        return -1;\n    }\n    else if (x >= -1 && x <= 1)\n    {\n        return x;\n    }\n    else\n    {\n        return 1;\n    }\n}\n\nvoid c2_algorithm::c2_function()\n{\n    double ts = (double)1 / frequency;\n    double zk = 1 / ts * (ek / ts + ek1 / 2);\n    double zk1 = ek1 / ts;\n    double m1 = 1 + 8 * abs(zk);\n    double m = floor((1 + sqrt(m1)) / 2);\n    double omk = zk1 + zk / m + (m - 1) / 2 * sign(zk);\n    double uk1 = vel * sign(omk) + max_vel - ts * jeck;\n    double uk2 = 1 + sign(uk1);\n    uk = -1 * jeck * sat(omk) * uk2 / 2;\n}\n\nvoid c2_algorithm::get_qk(double l_vel, double l_pos, double &vel_, double &pos_)\n{\n    prepare();\n    c2_function();\n    double ts = (double)1 / frequency;\n    qk1 = l_vel + ts * uk;\n    qk = l_pos + ts / 2 * (qk1 + l_vel);\n\n    vel = qk1;\n    pos = qk;\n\n    vel_ = qk1;\n    pos_ = qk;\n}\n\nvoid c2_algorithm::start(double c_pos, double target_pos, double c_vel, double target_vel)\n{\n    pos = c_pos;\n    t_pos = target_pos;\n    vel = c_vel;\n    t_vel = target_vel;\n}\n\nvoid c2_algorithm::init(double min_vel_, double max_vel_, double min_acc_, double max_acc_, double jeck_, int frequency_ = 100)\n{\n    min_vel = min_vel_;\n    max_vel = max_vel_;\n    min_acc = min_acc_;\n    max_acc = max_acc_;\n    jeck = jeck_;\n    frequency = frequency_;\n}", "meta": {"hexsha": "085770a679d998a0275ee51d904ecefe2067a7f8", "size": 2091, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "navigation_cli/src/c2_algorithm.cpp", "max_stars_repo_name": "l756302098/ros_practice", "max_stars_repo_head_hexsha": "4da8b4ddb25ada2e6f1adb3c0f8b34576aedf6b7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "navigation_cli/src/c2_algorithm.cpp", "max_issues_repo_name": "l756302098/ros_practice", "max_issues_repo_head_hexsha": "4da8b4ddb25ada2e6f1adb3c0f8b34576aedf6b7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "navigation_cli/src/c2_algorithm.cpp", "max_forks_repo_name": "l756302098/ros_practice", "max_forks_repo_head_hexsha": "4da8b4ddb25ada2e6f1adb3c0f8b34576aedf6b7", "max_forks_repo_licenses": ["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.025862069, "max_line_length": 127, "alphanum_fraction": 0.549976088, "num_tokens": 698, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503206, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.494832445687087}}
{"text": "#include <iostream>                    // std::cout, std::flush\n#include <fstream>                     // std::ifstream, std::ofstream\n#include <filesystem>                  // std::filesystem\n#include <string>                      // std::string\n#include <vector>                      // std::vector\n// For External Library\n#include <boost/program_options.hpp>   // boost::program_options\n\n#define NORMAL 0\n#define ANOMALY 1\n\n// Define Namespace\nnamespace fs = std::filesystem;\nnamespace po = boost::program_options;\n\n// Function Prototype\nbool judgement(double value, bool class_name, double threshold);\n\n\n// ----------------------------\n// Anomaly Detection Function\n// ----------------------------\nvoid anomaly_detection(po::variables_map &vm){\n\n    // (0) Initialization and Declaration\n    size_t i, j;\n    size_t TP, FP, TN, FN;\n    size_t total_data, idx;\n    double data_one;\n    double min, max, step, thresh;\n    double SED, SED_min, cutoff_idx, cutoff_th;\n    double TP_rate, FP_rate, TN_rate, FN_rate, pre_TP_rate, pre_FP_rate;\n    double precision, recall, specificity;\n    double accuracy, F, AUC;\n    std::ifstream ifs;\n    std::ofstream ofs;\n    std::string result_dir, result_path;\n    std::vector<double> data[2];\n\n    // (1) Set Directory and Path\n    result_dir = vm[\"AD_result_dir\"].as<std::string>();\n    result_path = vm[\"AD_result_dir\"].as<std::string>() + \"/accuracy.csv\";\n    fs::create_directories(result_dir);\n\n    // (2.1) Set Anomaly Data\n    ifs.open(vm[\"anomaly_path\"].as<std::string>());\n    ifs >> data_one;\n    min = data_one;\n    max = data_one;\n    data[ANOMALY].push_back(data_one);\n    while (true){\n        ifs >> data_one;\n        if (ifs.eof()) break;\n        if (data_one > max){\n            max = data_one;\n        }\n        else if (data_one < min){\n            min = data_one;\n        }\n        data[ANOMALY].push_back(data_one);\n    }\n    ifs.close();\n\n    // (2.2) Set Normal Data\n    ifs.open(vm[\"normal_path\"].as<std::string>());\n    while (true){\n        ifs >> data_one;\n        if (ifs.eof()) break;\n        if (data_one > max){\n            max = data_one;\n        }\n        else if (data_one < min){\n            min = data_one;\n        }\n        data[NORMAL].push_back(data_one);\n    }\n    ifs.close();\n\n    // (3) Pre-Processing\n    ofs.open(result_path);\n    ofs << \"threshold,TP,FP,TN,FN,TP rate,FP rate,TN rate,FN rate,SED,precision,recall,specificity,accuracy,F\" << std::endl;\n    total_data = data[NORMAL].size() + data[ANOMALY].size();\n    std::cout << \"total anomaly detection data : \" << total_data << std::endl;\n\n    // (4) Calculation of Step\n    step = (double)(max - min) / (double)(vm[\"n_thresh\"].as<size_t>() - 2);\n    if (step == 0.0){\n        step = 1.0;\n    }\n\n    // (5) Anomaly Detection\n    AUC = 0.0;\n    pre_TP_rate = 1.0;\n    pre_FP_rate = 1.0;\n    SED_min = 1.0;\n    idx = 1;\n    cutoff_idx = 1;\n    cutoff_th = min;\n    thresh = min;\n    for (i = 0; i < vm[\"n_thresh\"].as<size_t>(); i++){\n\n        thresh += step;\n        idx++;\n\n        // (5.1) Get TP, FN, TN and FP\n        TP = 0, FP = 0, TN = 0, FN = 0;\n        for (j = 0; j < data[ANOMALY].size(); j++){\n            if (judgement(data[ANOMALY][j], ANOMALY, thresh)){\n                TP++;\n            }\n            else{\n                FN++;\n            }\n        }\n        for (j = 0; j < data[NORMAL].size(); j++){\n            if (judgement(data[NORMAL][j], NORMAL, thresh)){\n                TN++;\n            }\n            else{\n                FP++;\n            }\n        }\n\n        // (5.2) Calculation of Accuracy\n        TP_rate = (double)TP / (double)data[ANOMALY].size();\n        FP_rate = (double)FP / (double)data[NORMAL].size();\n        TN_rate = (double)TN / (double)data[NORMAL].size();\n        FN_rate = (double)FN / (double)data[ANOMALY].size();\n        precision = (double)TP / (double)(TP + FP);\n        recall = (double)TP / (double)(TP + FN);\n        specificity = (double)TN / (double)(FP + TN);\n        accuracy = (double)(TP + TN) / (double)total_data;\n        F = (double)TP / ((double)TP + 0.5 * (double)(FP + FN));\n        AUC += (pre_TP_rate + TP_rate) * (pre_FP_rate - FP_rate) * 0.5;\n        pre_TP_rate = TP_rate;\n        pre_FP_rate = FP_rate;\n\n        // (5.3) Calculation of Cut-Off Value\n        SED = (1.0 - TP_rate) * (1.0 - TP_rate) + FP_rate * FP_rate;\n        if (SED < SED_min){\n            SED_min = SED;\n            cutoff_idx = idx;\n            cutoff_th = thresh;\n        }\n\n        // (5.4) File Output\n        ofs << thresh << \",\" << std::flush;\n        ofs << TP << \",\" << FP << \",\" << TN << \",\" << FN << \",\" << std::flush;\n        ofs << TP_rate << \",\" << FP_rate << \",\" << TN_rate << \",\" << FN_rate << \",\" << std::flush;\n        ofs << SED << \",\" << std::flush;\n        ofs << precision << \",\" << recall << \",\" << specificity << \",\" << std::flush;\n        ofs << accuracy << \",\" << F << std::endl;\n\n    }\n\n    // (6) File Output\n    ofs << std::endl;\n    ofs << \"ROC-AUC,\" << AUC << std::endl;\n    ofs << \"index(Cut-Off),\" << cutoff_idx << std::endl;\n    ofs << \"threshold(Cut-Off),\" << cutoff_th << std::endl;\n\n    // Post Processing\n    ofs.close();\n\n    // End Processing\n    return;\n\n}\n\n\n// ----------------------------\n// Anomaly Judgement Function\n// ----------------------------\nbool judgement(double value, bool class_name, double threshold){\n\n    bool judge;\n\n    if (value < threshold){\n        judge = false;\n    }\n    else{\n        judge = true;\n    }\n\n    if (class_name == NORMAL){\n        return !judge;\n    }\n\n    return judge;\n\n}\n", "meta": {"hexsha": "1753c81c58b44a288308968668eb877949d88a5a", "size": 5535, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Anomaly_Detection/EGBAD2d/src/anomaly_detection.cpp", "max_stars_repo_name": "abhiksark/pytorch_cpp", "max_stars_repo_head_hexsha": "cbd787f0e8b0bc17824dff34d0789a976191a494", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-18T18:08:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-18T18:08:12.000Z", "max_issues_repo_path": "Anomaly_Detection/Skip-GANomaly2d/src/anomaly_detection.cpp", "max_issues_repo_name": "abhiksark/pytorch_cpp", "max_issues_repo_head_hexsha": "cbd787f0e8b0bc17824dff34d0789a976191a494", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Anomaly_Detection/Skip-GANomaly2d/src/anomaly_detection.cpp", "max_forks_repo_name": "abhiksark/pytorch_cpp", "max_forks_repo_head_hexsha": "cbd787f0e8b0bc17824dff34d0789a976191a494", "max_forks_repo_licenses": ["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.828125, "max_line_length": 124, "alphanum_fraction": 0.5105691057, "num_tokens": 1518, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503206, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.494832445687087}}
{"text": "/*******\nedit_distance: STL and Boost compatible edit distance functions for C++\n\nCopyright (c) 2013 Erik Erlandson\n\nAuthor:  Erik Erlandson <erikerlandson@yahoo.com>\n\nDistributed under the Boost Software License, Version 1.0.\nSee accompanying file LICENSE or copy at\nhttp://www.boost.org/LICENSE_1_0.txt\n*******/\n\n#include \"edit_distance_common.hpp\"\n\n// get the edit_alignment() function\n#include <boost/algorithm/sequence/edit_distance.hpp>\nusing boost::algorithm::sequence::edit_distance;\nusing namespace boost::algorithm::sequence::parameter;\nusing boost::algorithm::sequence::unit_cost;\n\nint main(int argc, char** argv) {\n    char const* str1 = \"Oh, hello world.\";\n    char const* str2 = \"Hello world!!\";\n\n    // Generate the edit script from str1 to str2.\n    // The output object 'out' processes the edit script operations in sequence\n    // An output class must define types value_type and cost_type (similar to \n    // the cost function object for edit_distance), and the methods:\n    //   insertion(v, c)        // element v inserted, with insertion cost c\n    //   deletion(v, c)        // element v deleted, with deletion cost c\n    //   substitution(v1, v2, c)   // v1 subsituted with v2, subst cost c\n    //   equality(v1, v2)      // v1 == v2\n    //\n    // Defining substitution() is optional if substitution is compile-time disabled (the default)\n    // To enable, pass the optional _substitution=boost::true_type(), or _substitution=<bool-value>\n    stringstream_tuple_output<unit_cost, char const*> out;\n    unsigned dist = edit_distance(str1, str2, _script = out);\n    std::cout << \"dist= \" << dist << \"   edit operations= \" << out.ss.str() << \"\\n\";\n\n    return 0;\n}\n", "meta": {"hexsha": "5d7504c9c30ce5bed70c6ed33497149a9c5eca4f", "size": 1686, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/edit_script_example.cpp", "max_stars_repo_name": "xietian1/mpkix-judgement", "max_stars_repo_head_hexsha": "2cca8b509d2804c85bb39abc397f34ad4f2666b1", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2015-10-22T05:25:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-24T14:03:12.000Z", "max_issues_repo_path": "example/edit_script_example.cpp", "max_issues_repo_name": "xietian1/mpkix-judgement", "max_issues_repo_head_hexsha": "2cca8b509d2804c85bb39abc397f34ad4f2666b1", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-01-23T20:26:59.000Z", "max_issues_repo_issues_event_max_datetime": "2015-01-23T20:26:59.000Z", "max_forks_repo_path": "example/edit_script_example.cpp", "max_forks_repo_name": "xietian1/mpkix-judgement", "max_forks_repo_head_hexsha": "2cca8b509d2804c85bb39abc397f34ad4f2666b1", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-05-27T04:38:41.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-27T04:38:41.000Z", "avg_line_length": 40.1428571429, "max_line_length": 99, "alphanum_fraction": 0.6915776987, "num_tokens": 419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737473266735, "lm_q2_score": 0.7248702880639791, "lm_q1q2_score": 0.4947774288495955}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n  int array[24];\nfor(int i = 0; i < 24; ++i) array[i] = i;\ncout << Map<MatrixXi, 0, Stride<Dynamic,2> >\n         (array, 3, 3, Stride<Dynamic,2>(8, 2))\n     << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "db7f93733db392f746b6908a8657a279b4e02390", "size": 315, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_Map_general_stride.cpp", "max_stars_repo_name": "TANHAIYU/Self-calibration-using-Homography-Constraints", "max_stars_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-03-17T16:34:31.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-17T18:30:13.000Z", "max_issues_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_Map_general_stride.cpp", "max_issues_repo_name": "TANHAIYU/planecalib", "max_issues_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_Map_general_stride.cpp", "max_forks_repo_name": "TANHAIYU/planecalib", "max_forks_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.5, "max_line_length": 47, "alphanum_fraction": 0.6, "num_tokens": 109, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.6825737473266734, "lm_q1q2_score": 0.49477742073573594}}
{"text": "/*\n * Copyright Andrey Semashev 2020\n *\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/*!\n * \\file bit_width.hpp\n *\n * This header defines \\c bit_width algorithm, which produces the minimal number of\n * bits required to represent an integer value.\n */\n\n#ifndef BOOST_BIT_OPS_POW2_BIT_WIDTH_HPP_INCLUDED_\n#define BOOST_BIT_OPS_POW2_BIT_WIDTH_HPP_INCLUDED_\n\n#include <limits>\n#include <boost/bit_ops/detail/config.hpp>\n#include <boost/bit_ops/detail/type_traits/enable_if.hpp>\n#include <boost/bit_ops/detail/type_traits/is_integral.hpp>\n#include <boost/bit_ops/detail/type_traits/is_unsigned.hpp>\n#include <boost/bit_ops/count/countl_zero.hpp>\n\nnamespace boost {\nnamespace bit_ops {\n\n/*!\n * \\brief Returns the minimal number of bits required to represent \\a value\n *\n * \\pre \\a value must not be zero\n */\ntemplate< typename T >\ninline typename bit_ops::detail::enable_if<\n    bit_ops::detail::is_integral< T >::value && bit_ops::detail::is_unsigned< T >::value,\n    unsigned int\n>::type bit_width_nz(T value) BOOST_NOEXCEPT\n{\n    return static_cast< unsigned int >(std::numeric_limits< T >::digits - bit_ops::countl_zero_nz(value));\n}\n\n//! Returns the minimal number of bits required to represent \\a value or 0 if \\a value is zero\ntemplate< typename T >\ninline typename bit_ops::detail::enable_if<\n    bit_ops::detail::is_integral< T >::value && bit_ops::detail::is_unsigned< T >::value,\n    unsigned int\n>::type bit_width(T value) BOOST_NOEXCEPT\n{\n    return value == 0u ? 0u : bit_ops::bit_width_nz(value);\n}\n\n} // namespace bit_ops\n} // namespace boost\n\n#endif // BOOST_BIT_OPS_POW2_BIT_WIDTH_HPP_INCLUDED_\n", "meta": {"hexsha": "ded248cea1f6b284f4a3ec14c32a45835ea92d97", "size": 1723, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/bit_ops/pow2/bit_width.hpp", "max_stars_repo_name": "Lastique/bit_ops", "max_stars_repo_head_hexsha": "c0f8d03687affe2d4426d0ff623d6e511d5c1a5b", "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/bit_ops/pow2/bit_width.hpp", "max_issues_repo_name": "Lastique/bit_ops", "max_issues_repo_head_hexsha": "c0f8d03687affe2d4426d0ff623d6e511d5c1a5b", "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/bit_ops/pow2/bit_width.hpp", "max_forks_repo_name": "Lastique/bit_ops", "max_forks_repo_head_hexsha": "c0f8d03687affe2d4426d0ff623d6e511d5c1a5b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.7678571429, "max_line_length": 106, "alphanum_fraction": 0.747533372, "num_tokens": 430, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702880639792, "lm_q2_score": 0.6825737214979746, "lm_q1q2_score": 0.49477741012713916}}
{"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#define NT2_UNIT_MODULE \"nt2::sum1 function\"\n\n#include <nt2/table.hpp>\n#include <nt2/include/functions/idxy_bilinear.hpp>\n#include <nt2/include/functions/linspace.hpp>\n#include <nt2/include/functions/transpose.hpp>\n#include <nt2/include/functions/isequal.hpp>\n#include <nt2/sdk/unit/module.hpp>\n#include <nt2/sdk/unit/tests/relation.hpp>\n#include <nt2/sdk/unit/tests/basic.hpp>\n#include <boost/fusion/include/make_vector.hpp>\n\n\n// NT2_TEST_CASE_TPL( idxy_bilinear2, (float)(double))//NT2_TYPES )\n// {\n//   using nt2::_;\n//   nt2::table<T> x =  nt2::reshape(nt2::linspace(T(1),  T(16), 16), 4, 4);\n//   nt2::table<T> xi=  nt2::linspace(T(1),  T(4), 7);\n//   nt2::table<T> yi=  nt2::linspace(T(0),  T(6), 11);\n//   NT2_DISPLAY(x);\n//   NT2_DISPLAY(xi);\n//   nt2::table<T> r;\n//   r =nt2::idxy_bilinear(x, xi, xi, true);\n//   NT2_DISPLAY(r);\n//   r =nt2::idxy_bilinear(x, xi, yi, true);\n//   NT2_DISPLAY(r);\n//   r =nt2::idxy_bilinear(x, xi, yi);\n//   NT2_DISPLAY(r);\n//   r =nt2::idxy_bilinear(x, xi, yi, _, 1, 2);\n//   NT2_DISPLAY(r);\n\n//  }\nNT2_TEST_CASE_TPL( idxy_bilinear2b, (float))//(double))//NT2_TYPES )\n{\n  using nt2::_;\n  nt2::table<T> x =  nt2::reshape(nt2::linspace(T(1),  T(16), 16), 4, 4);\n  nt2::table<T> xi=  nt2::linspace(T(1),  T(4), 7);\n  nt2::table<T> yi=  nt2::linspace(T(1),  T(4), 11);\n  NT2_DISPLAY(x);\n  NT2_DISPLAY(xi);\n  NT2_DISPLAY(yi);\n  nt2::table<T> r, r0;\n  r =nt2::idxy_bilinear(x, xi, yi);\n  NT2_DISPLAY(r);\n  r0 =nt2::idxy_bilinear(x, xi, yi, true);\n  NT2_DISPLAY(r0);\n  NT2_TEST(isequal(r0, r));\n  r =nt2::idxy_bilinear(x, xi, yi, _, 2, 1);\n  NT2_DISPLAY(r);\n  NT2_TEST(isequal(r0, r));\n }\nNT2_TEST_CASE_TPL( idxy_bilinear2c, (float))//(double))//NT2_TYPES )\n{\n  using nt2::_;\n  nt2::table<T> x =  nt2::reshape(nt2::linspace(T(1),  T(16), 16), 4, 4);\n  nt2::table<T> xi=  nt2::linspace(T(0),  T(5), 7);\n  nt2::table<T> yi=  nt2::linspace(T(0),  T(5), 11);\n  NT2_DISPLAY(x);\n  NT2_DISPLAY(xi);\n  NT2_DISPLAY(yi);\n  nt2::table<T> r, r0;\n  r =nt2::idxy_bilinear(x, xi, yi);\n  NT2_DISPLAY(r);\n  r0 =nt2::idxy_bilinear(x, xi, yi, true);\n  NT2_DISPLAY(r0);\n  r =nt2::idxy_bilinear(x, xi, yi, _, 2, 1);\n  NT2_DISPLAY(r);\n  NT2_TEST_COMPLETE(\"idxy_bilinear2c\");\n }\n", "meta": {"hexsha": "2d0a7ea48b37cd0c185f360e00fd19cf950d6685", "size": 2699, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/core/interpol/unit/scalar/idxy_bilinear.cpp", "max_stars_repo_name": "pbrunet/nt2", "max_stars_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/core/interpol/unit/scalar/idxy_bilinear.cpp", "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/interpol/unit/scalar/idxy_bilinear.cpp", "max_forks_repo_name": "pbrunet/nt2", "max_forks_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 34.6025641026, "max_line_length": 80, "alphanum_fraction": 0.5857725083, "num_tokens": 967, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.494777406693894}}
{"text": "// die.cpp\r\n//\r\n// Copyright (c) 2009\r\n// 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//[die\r\n/*`\r\n    For the source of this example see\r\n    [@boost://libs/random/example/die.cpp die.cpp].\r\n    First we include the headers we need for __mt19937\r\n    and __uniform_int_distribution.\r\n*/\r\n#include <boost/random/mersenne_twister.hpp>\r\n#include <boost/random/uniform_int_distribution.hpp>\r\n\r\n/*`\r\n  We use __mt19937 with the default seed as a source of\r\n  randomness.  The numbers produced will be the same\r\n  every time the program is run.  One common method to\r\n  change this is to seed with the current time (`std::time(0)`\r\n  defined in ctime).\r\n*/\r\nboost::random::mt19937 gen;\r\n/*`\r\n  [note We are using a /global/ generator object here.  This\r\n  is important because we don't want to create a new [prng\r\n  pseudo-random number generator] at every call]\r\n*/\r\n/*`\r\n  Now we can define a function that simulates an ordinary\r\n  six-sided die.\r\n*/\r\nint roll_die() {\r\n    /*<< __mt19937 produces integers in the range [0, 2[sup 32]-1].\r\n        However, we want numbers in the range [1, 6].  The distribution\r\n        __uniform_int_distribution performs this transformation.\r\n        [warning Contrary to common C++ usage __uniform_int_distribution\r\n        does not take a /half-open range/.  Instead it takes a /closed range/.\r\n        Given the parameters 1 and 6, __uniform_int_distribution\r\n        can produce any of the values 1, 2, 3, 4, 5, or 6.]\r\n    >>*/\r\n    boost::random::uniform_int_distribution<> dist(1, 6);\r\n    /*<< A distribution is a function object.  We generate a random\r\n        number by calling `dist` with the generator.\r\n    >>*/\r\n    return dist(gen);\r\n}\r\n//]\r\n\r\n#include <iostream>\r\n\r\nint main() {\r\n    for(int i = 0; i < 10; ++i) {\r\n        std::cout << roll_die() << std::endl;\r\n    }\r\n}\r\n", "meta": {"hexsha": "fdce2b669f115c20143e6376e87104eea85758f9", "size": 1958, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/random/example/die.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": 85.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T20:36:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T20:38:31.000Z", "max_issues_repo_path": "libs/boost/libs/random/example/die.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/random/example/die.cpp", "max_forks_repo_name": "flingone/frameworks_base_cmds_remoted", "max_forks_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2015-01-28T16:33:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-12T05:04:39.000Z", "avg_line_length": 32.0983606557, "max_line_length": 79, "alphanum_fraction": 0.6583248212, "num_tokens": 513, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.6825737279551493, "lm_q1q2_score": 0.4947774066938939}}
{"text": "/*\n * This timing code is based on the benchmarking code as written in the Pinocchio repository\n * clang++-12 -std=c++11 -o timePinocchio.exe timePinocchio.cpp -O3 -DPINOCCHIO_URDFDOM_TYPEDEF_SHARED_PTR -DPINOCCHIO_WITH_URDFDOM -lboost_system -lpinocchio -lurdfdom_model -lpthread -ldl\n * eample usage: timePinocchio.exe urdfs/atlas.urdf\n */\n#include \"util/experiment_helpers.h\" // include constants and other experiment consistency helpers\n#include \"ReusableThreads/ReusableThreads.h\" // multi-threading wrapper\n\n#include \"pinocchio/algorithm/joint-configuration.hpp\"\n#include \"pinocchio/algorithm/kinematics.hpp\"\n#include \"pinocchio/algorithm/center-of-mass.hpp\"\n#include \"pinocchio/algorithm/centroidal.hpp\"\n#include \"pinocchio/algorithm/cholesky.hpp\"\n#include \"pinocchio/algorithm/jacobian.hpp\"\n#include \"pinocchio/algorithm/crba.hpp\"\n#include \"pinocchio/algorithm/aba.hpp\"\n#include \"pinocchio/algorithm/rnea.hpp\"\n#include \"pinocchio/algorithm/kinematics-derivatives.hpp\"\n#include \"pinocchio/algorithm/rnea-derivatives.hpp\"\n#include \"pinocchio/algorithm/aba-derivatives.hpp\"\n#include \"pinocchio/algorithm/compute-all-terms.hpp\"\n\n#include \"pinocchio/codegen/cppadcg.hpp\"\n#include \"pinocchio/codegen/code-generator-algo.hpp\"\n\n#include \"pinocchio/parsers/urdf.hpp\"\n#include \"pinocchio/parsers/sample-models.hpp\"\n\n#include \"pinocchio/container/aligned-vector.hpp\"\n\n#include <Eigen/StdVector>\n// EIGEN_DEFINE_STL_VECTOR_SPECIALIZATION(Eigen::VectorXd)\n\nusing namespace Eigen;\nusing namespace pinocchio;\n\n#define time_delta_us_timespec(start,end) (1e6*static_cast<double>(end.tv_sec - start.tv_sec)+1e-3*static_cast<double>(end.tv_nsec - start.tv_nsec))\n\ntemplate<typename T>\nvoid inverseDynamicsThreaded_codegen_inner(CodeGenRNEA<T> *rnea_code_gen, int nq, int nv, \\\n                                           Matrix<T, Dynamic, 1> *qs, Matrix<T, Dynamic, 1> *qds, int tid, int kStart, int kMax){\n    Matrix<T, Dynamic, 1> zeros = Matrix<T, Dynamic, 1>::Zero(nv);\n    for(int k = kStart; k < kMax; k++){\n        rnea_code_gen->evalFunction(qs[k],qds[k],zeros);\n    }\n}\n\ntemplate<typename T, int NUM_THREADS, int NUM_TIME_STEPS>\nvoid inverseDynamicsThreaded_codegen(CodeGenRNEA<T> **rnea_code_gen_arr, int nq, int nv, \\\n                                     Matrix<T, Dynamic, 1> *qs, Matrix<T, Dynamic, 1> *qds, ReusableThreads<NUM_THREADS> *threads){\n        for (int tid = 0; tid < NUM_THREADS; tid++){\n            int kStart = NUM_TIME_STEPS/NUM_THREADS*tid; int kMax = NUM_TIME_STEPS/NUM_THREADS*(tid+1); \n            if(tid == NUM_THREADS-1){kMax = NUM_TIME_STEPS;} \n            threads->addTask(tid, &inverseDynamicsThreaded_codegen_inner<T>, std::ref(rnea_code_gen_arr[tid]), nq, nv,\n                                                                             std::ref(qs), std::ref(qds), tid, kStart, kMax);\n        }\n        threads->sync();\n}\n\ntemplate<typename T>\nvoid minvThreaded_codegen_inner(CodeGenMinv<T> *minv_code_gen, int nq, int nv, Matrix<T, Dynamic, 1> *qs, int tid, int kStart, int kMax){\n    for(int k = kStart; k < kMax; k++){\n        minv_code_gen->evalFunction(qs[k]);\n    }\n}\n\ntemplate<typename T, int NUM_THREADS, int NUM_TIME_STEPS>\nvoid minvThreaded_codegen(CodeGenMinv<T> **minv_code_gen_arr, int nq, int nv, Matrix<T, Dynamic, 1> *qs, ReusableThreads<NUM_THREADS> *threads){\n        for (int tid = 0; tid < NUM_THREADS; tid++){\n            int kStart = NUM_TIME_STEPS/NUM_THREADS*tid; int kMax = NUM_TIME_STEPS/NUM_THREADS*(tid+1); \n            if(tid == NUM_THREADS-1){kMax = NUM_TIME_STEPS;} \n            threads->addTask(tid, &minvThreaded_codegen_inner<T>, std::ref(minv_code_gen_arr[tid]), nq, nv, std::ref(qs), tid, kStart, kMax);\n        }\n        threads->sync();\n}\n\ntemplate<typename T>\nvoid forwardDynamicsThreaded_codegen_inner(CodeGenMinv<T> *minv_code_gen, CodeGenRNEA<T> *rnea_code_gen, int nq, int nv, \\\n                                           Matrix<T, Dynamic, 1> *qs, Matrix<T, Dynamic, 1> *qds, Matrix<T, Dynamic, 1> *qdds, \\\n                                           Matrix<T, Dynamic, 1> *us, int tid, int kStart, int kMax){\n    Matrix<T, Dynamic, 1> zeros = Matrix<T, Dynamic, 1>::Zero(nv);\n    for(int k = kStart; k < kMax; k++){\n        minv_code_gen->evalFunction(qs[k]);\n        minv_code_gen->Minv.template triangularView<Eigen::StrictlyLower>() = \n            minv_code_gen->Minv.transpose().template triangularView<Eigen::StrictlyLower>();\n        rnea_code_gen->evalFunction(qs[k],qds[k],zeros);\n        qdds[k].noalias() = minv_code_gen->Minv*(us[k] - rnea_code_gen->res);\n    }\n}\n\ntemplate<typename T, int NUM_THREADS, int NUM_TIME_STEPS>\nvoid forwardDynamicsThreaded_codegen(CodeGenMinv<T> **minv_code_gen_arr, CodeGenRNEA<T> **rnea_code_gen_arr, int nq, int nv, \\\n                                     Matrix<T, Dynamic, 1> *qs, Matrix<T, Dynamic, 1> *qds, Matrix<T, Dynamic, 1> *qdds, \\\n                                     Matrix<T, Dynamic, 1> *us, ReusableThreads<NUM_THREADS> *threads){\n        for (int tid = 0; tid < NUM_THREADS; tid++){\n            int kStart = NUM_TIME_STEPS/NUM_THREADS*tid; int kMax = NUM_TIME_STEPS/NUM_THREADS*(tid+1); \n            if(tid == NUM_THREADS-1){kMax = NUM_TIME_STEPS;} \n            threads->addTask(tid, &forwardDynamicsThreaded_codegen_inner<T>, std::ref(minv_code_gen_arr[tid]), \n                                                                             std::ref(rnea_code_gen_arr[tid]), nq, nv,\n                                                                             std::ref(qs), std::ref(qds), std::ref(qdds), std::ref(us), \n                                                                             tid, kStart, kMax);\n        }\n        threads->sync();\n}\n\ntemplate<typename T>\nvoid inverseDynamicsGradientThreaded_codegen_inner(CodeGenRNEADerivatives<T> *rnea_derivatives_code_gen, \\\n                                                   int nq, int nv, Matrix<T, Dynamic, 1> *qs, Matrix<T, Dynamic, 1> *qds, \\\n                                                   int tid, int kStart, int kMax){\n    Matrix<T, Dynamic, 1> zeros = Matrix<T, Dynamic, 1>::Zero(nv);\n    for(int k = kStart; k < kMax; k++){\n        rnea_derivatives_code_gen->evalFunction(qs[k],qds[k],zeros);\n    }\n}\n\ntemplate<typename T, int NUM_THREADS, int NUM_TIME_STEPS>\nvoid inverseDynamicsGradientThreaded_codegen(CodeGenRNEADerivatives<T> **rnea_derivatives_code_gen_arr, \\\n                                             int nq, int nv, Matrix<T, Dynamic, 1> *qs, Matrix<T, Dynamic, 1> *qds, \n                                             ReusableThreads<NUM_THREADS> *threads){\n        for (int tid = 0; tid < NUM_THREADS; tid++){\n            int kStart = NUM_TIME_STEPS/NUM_THREADS*tid; int kMax = NUM_TIME_STEPS/NUM_THREADS*(tid+1); \n            if(tid == NUM_THREADS-1){kMax = NUM_TIME_STEPS;} \n            threads->addTask(tid, &inverseDynamicsGradientThreaded_codegen_inner<T>, std::ref(rnea_derivatives_code_gen_arr[tid]), \n                                                                                     nq, nv, std::ref(qs), std::ref(qds), tid, kStart, kMax);\n        }\n        threads->sync();\n}\n\ntemplate<typename T>\nvoid forwardDynamicsGradientThreaded_codegen_inner(CodeGenRNEADerivatives<T> *rnea_derivatives_code_gen, \\\n                                                   CodeGenMinv<T> *minv_code_gen, CodeGenRNEA<T> *rnea_code_gen, \\\n                                                   int nq, int nv, Matrix<T, Dynamic, Dynamic> *dqdd_dqs, Matrix<T, Dynamic, Dynamic> *dqdd_dvs, \\\n                                                   Matrix<T, Dynamic, 1> *qs, Matrix<T, Dynamic, 1> *qds, Matrix<T, Dynamic, 1> *us, \\\n                                                   int tid, int kStart, int kMax){\n    Matrix<T, Dynamic, 1> zeros = Matrix<T, Dynamic, 1>::Zero(nv);\n    for(int k = kStart; k < kMax; k++){\n        minv_code_gen->evalFunction(qs[k]);\n        minv_code_gen->Minv.template triangularView<Eigen::StrictlyLower>() = \n            minv_code_gen->Minv.transpose().template triangularView<Eigen::StrictlyLower>();\n        rnea_code_gen->evalFunction(qs[k],qds[k],zeros);\n        Matrix<T, Dynamic, 1> qdd = minv_code_gen->Minv*(us[k] - rnea_code_gen->res);\n        rnea_derivatives_code_gen->evalFunction(qs[k],qds[k],qdd);\n        dqdd_dqs[k].noalias() = -(minv_code_gen->Minv)*(rnea_derivatives_code_gen->dtau_dq);\n        dqdd_dvs[k].noalias() = -(minv_code_gen->Minv)*(rnea_derivatives_code_gen->dtau_dv);\n    }\n}\n\ntemplate<typename T, int NUM_THREADS, int NUM_TIME_STEPS>\nvoid forwardDynamicsGradientThreaded_codegen(CodeGenRNEADerivatives<T> **rnea_derivatives_code_gen_arr, \\\n                                             CodeGenMinv<T> **minv_code_gen_arr, CodeGenRNEA<T> **rnea_code_gen_arr, \\\n                                             int nq, int nv, Matrix<T, Dynamic, Dynamic> *dqdd_dqs, Matrix<T, Dynamic, Dynamic> *dqdd_dvs, \\\n                                             Matrix<T, Dynamic, 1> *qs, Matrix<T, Dynamic, 1> *qds, Matrix<T, Dynamic, 1> *us, \\\n                                             ReusableThreads<NUM_THREADS> *threads){\n        for (int tid = 0; tid < NUM_THREADS; tid++){\n            int kStart = NUM_TIME_STEPS/NUM_THREADS*tid; int kMax = NUM_TIME_STEPS/NUM_THREADS*(tid+1); \n            if(tid == NUM_THREADS-1){kMax = NUM_TIME_STEPS;} \n            threads->addTask(tid, &forwardDynamicsGradientThreaded_codegen_inner<T>, std::ref(rnea_derivatives_code_gen_arr[tid]), \n                                                                                     std::ref(minv_code_gen_arr[tid]), \n                                                                                     std::ref(rnea_code_gen_arr[tid]), nq, nv,\n                                                                                     std::ref(dqdd_dqs), std::ref(dqdd_dvs), \n                                                                                     std::ref(qs), std::ref(qds), std::ref(us),\n                                                                                     tid, kStart, kMax);\n    }\n        threads->sync();\n}\n\ntemplate<typename T, int TEST_ITERS, int NUM_THREADS, int NUM_TIME_STEPS>\nvoid test(std::string urdf_filepath){\n    // Setup timer\n    struct timespec start, end;\n\n    // Matrix typedefs\n    typedef Matrix<T, Dynamic, Dynamic> MatrixXT;\n    typedef Matrix<T, Dynamic, 1> VectorXT;\n\n    // Import URDF model and prepare pinnochio\n    Model model;\n    pinocchio::urdf::buildModel(urdf_filepath,model);\n    // model.gravity.setZero();\n    model.gravity.linear(Eigen::Vector3d(0,0,-9.81));\n    Data datas[NUM_THREADS]; \n    for(int i = 0; i < NUM_THREADS; i++){datas[i] = Data(model);}\n\n    // generate the code_gen\n    CodeGenRNEA<T> rnea_code_gen(model.cast<T>());\n    rnea_code_gen.initLib();\n    rnea_code_gen.loadLib();\n\n    CodeGenRNEA<T> *rnea_code_gen_arr[NUM_THREADS];\n    for (int i = 0; i < NUM_THREADS; i++){\n        rnea_code_gen_arr[i] = new CodeGenRNEA<T>(model.cast<T>());\n        rnea_code_gen_arr[i]->initLib();\n        rnea_code_gen_arr[i]->loadLib();\n    }\n\n    CodeGenMinv<T> minv_code_gen(model.cast<T>());\n    minv_code_gen.initLib();\n    minv_code_gen.loadLib();\n\n    CodeGenMinv<T> *minv_code_gen_arr[NUM_THREADS];\n    for (int i = 0; i < NUM_THREADS; i++){\n        minv_code_gen_arr[i] = new CodeGenMinv<T>(model.cast<T>());\n        minv_code_gen_arr[i]->initLib();\n        minv_code_gen_arr[i]->loadLib();\n    }\n\n    CodeGenRNEADerivatives<T> rnea_derivatives_code_gen(model.cast<T>());\n    rnea_derivatives_code_gen.initLib();\n    rnea_derivatives_code_gen.loadLib();\n\n    CodeGenRNEADerivatives<T> *rnea_derivatives_code_gen_arr[NUM_THREADS];\n    for (int i = 0; i < NUM_THREADS; i++){\n        rnea_derivatives_code_gen_arr[i] = new CodeGenRNEADerivatives<T>(model.cast<T>());\n        rnea_derivatives_code_gen_arr[i]->initLib();\n        rnea_derivatives_code_gen_arr[i]->loadLib();\n    }\n\n    // allocate and load on CPU\n    VectorXT qs[NUM_TIME_STEPS];\n    VectorXT qds[NUM_TIME_STEPS];\n    VectorXT qdds[NUM_TIME_STEPS];\n    VectorXT us[NUM_TIME_STEPS];\n    MatrixXT dqdd_dqs[NUM_TIME_STEPS];\n    MatrixXT dqdd_dvs[NUM_TIME_STEPS];\n    for(int i = 0; i < NUM_TIME_STEPS; i++){\n        qs[i] = VectorXT::Zero(model.nq);\n        qds[i] = VectorXT::Zero(model.nv);\n        qdds[i] = VectorXT::Zero(model.nv);\n        us[i] = VectorXT::Zero(model.nv);\n        dqdd_dqs[i] = MatrixXT::Zero(model.nv,model.nq);\n        dqdd_dvs[i] = MatrixXT::Zero(model.nv,model.nv);\n        for(int j = 0; j < model.nq; j++){qs[i][j] = getRand<T>(); qds[i][j] = getRand<T>(); us[i][j] = getRand<T>();}\n    }\n\n    #if TEST_FOR_EQUIVALENCE\n        std::cout << \"q,qd,u\" << std::endl;\n        std::cout << qs[0].transpose() << std::endl;\n        std::cout << qds[0].transpose() << std::endl;\n        std::cout << us[0].transpose() << std::endl;\n        // Minv\n        computeMinverse(model,datas[0],qs[0]); \n        std::cout << \"Minv\" << std::endl << datas[0].Minv << std::endl;\n        datas[0].Minv.template triangularView<Eigen::StrictlyLower>() = \n            datas[0].Minv.transpose().template triangularView<Eigen::StrictlyLower>();\n        MatrixXT Minv = datas[0].Minv;\n        // qdd\n        aba(model,datas[0],qs[0],qds[0],us[0]);\n        qdds[0] = datas[0].ddq;\n        std::cout << \"qdd\" << std::endl << qdds[0].transpose() << std::endl;\n        // dc/du with qdd=0\n        MatrixXT drnea_dq = MatrixXT::Zero(model.nq,model.nq);\n        MatrixXT drnea_dv = MatrixXT::Zero(model.nv,model.nv);\n        MatrixXT drnea_da = MatrixXT::Zero(model.nv,model.nv);\n        computeRNEADerivatives(model,datas[0],qs[0],qds[0],VectorXT::Zero(model.nv),drnea_dq,drnea_dv,drnea_da);\n        std::cout << \"dc_dq\" << std::endl << drnea_dq << std::endl;\n        std::cout << \"dc_dqd\" << std::endl << drnea_dv << std::endl;\n        // df/du (via dc/du with qdd)\n        computeRNEADerivatives(model,datas[0],qs[0],qds[0],qdds[0],drnea_dq,drnea_dv,drnea_da);\n        dqdd_dqs[0] = -Minv*drnea_dq;\n        dqdd_dvs[0] = -Minv*drnea_dv;\n        std::cout << \"df_dq\" << std::endl << dqdd_dqs[0] << std::endl;\n        std::cout << \"df_dqd\" << std::endl << dqdd_dvs[0] << std::endl;\n    #else\n        // Single call\n        if(NUM_TIME_STEPS == 1){\n            VectorXT zeros = VectorXT::Zero(model.nv);\n\n            clock_gettime(CLOCK_MONOTONIC,&start);\n            for(int i = 0; i < TEST_ITERS; i++){\n                rnea_code_gen.evalFunction(qs[0],qds[0],qdds[0]);\n            }\n            clock_gettime(CLOCK_MONOTONIC,&end);\n            printf(\"ID codegen %fus\\n\",time_delta_us_timespec(start,end)/static_cast<double>(TEST_ITERS));\n\n            clock_gettime(CLOCK_MONOTONIC,&start);\n            for(int i = 0; i < TEST_ITERS; i++){\n                minv_code_gen.evalFunction(qs[0]);\n            }\n            clock_gettime(CLOCK_MONOTONIC,&end);\n            printf(\"Minv codegen %fus\\n\",time_delta_us_timespec(start,end)/static_cast<double>(TEST_ITERS));\n\n            clock_gettime(CLOCK_MONOTONIC,&start);\n            for(int i = 0; i < TEST_ITERS; i++){\n                minv_code_gen.evalFunction(qs[0]);\n                minv_code_gen.Minv.template triangularView<Eigen::StrictlyLower>() = \n                    minv_code_gen.Minv.transpose().template triangularView<Eigen::StrictlyLower>();\n                rnea_code_gen.evalFunction(qs[0],qds[0],zeros);\n                qdds[0].noalias() = minv_code_gen.Minv*(us[0] - rnea_code_gen.res);\n            }\n            clock_gettime(CLOCK_MONOTONIC,&end);\n            printf(\"FD codegen %fus\\n\",time_delta_us_timespec(start,end)/static_cast<double>(TEST_ITERS));\n\n            clock_gettime(CLOCK_MONOTONIC,&start);\n            for(int i = 0; i < TEST_ITERS; i++){\n                rnea_derivatives_code_gen.evalFunction(qs[0],qds[0],qdds[0]);\n            }\n            clock_gettime(CLOCK_MONOTONIC,&end);\n            printf(\"ID_DU codegen %fus\\n\",time_delta_us_timespec(start,end)/static_cast<double>(TEST_ITERS));\n\n            clock_gettime(CLOCK_MONOTONIC,&start);\n            for(int i = 0; i < TEST_ITERS; i++){\n                minv_code_gen.evalFunction(qs[0]);\n                minv_code_gen.Minv.template triangularView<Eigen::StrictlyLower>() = \n                    minv_code_gen.Minv.transpose().template triangularView<Eigen::StrictlyLower>();\n                rnea_code_gen.evalFunction(qs[0],qds[0],zeros);\n                VectorXT qdd = minv_code_gen.Minv*(us[0] - rnea_code_gen.res);\n                rnea_derivatives_code_gen.evalFunction(qs[0],qds[0],qdd);\n                dqdd_dqs[0].noalias() = -minv_code_gen.Minv*rnea_derivatives_code_gen.dtau_dq;\n                dqdd_dvs[0].noalias() = -minv_code_gen.Minv*rnea_derivatives_code_gen.dtau_dv;\n            }\n            clock_gettime(CLOCK_MONOTONIC,&end);\n            printf(\"FD_DU codegen %fus\\n\",time_delta_us_timespec(start,end)/static_cast<double>(TEST_ITERS));\n\n        }\n        // multi call with threadPools\n        else{\n            ReusableThreads<NUM_THREADS> threads;\n            std::vector<double> times = {};\n\n            for(int iter = 0; iter < TEST_ITERS; iter++){\n                clock_gettime(CLOCK_MONOTONIC,&start);\n                inverseDynamicsThreaded_codegen<T,NUM_THREADS,NUM_TIME_STEPS>(rnea_code_gen_arr,\n                                                                              model.nq,model.nv,qs,qds,&threads);\n                clock_gettime(CLOCK_MONOTONIC,&end);\n                times.push_back(time_delta_us_timespec(start,end));\n            }\n            printf(\"[N:%d]: ID codegen: \",NUM_TIME_STEPS); printStats(&times); times.clear();\n            printf(\"----------------------------------------\\n\");\n\n            for(int iter = 0; iter < TEST_ITERS; iter++){\n                clock_gettime(CLOCK_MONOTONIC,&start);\n                minvThreaded_codegen<T,NUM_THREADS,NUM_TIME_STEPS>(minv_code_gen_arr,model.nq,model.nv,qs,&threads);\n                clock_gettime(CLOCK_MONOTONIC,&end);\n                times.push_back(time_delta_us_timespec(start,end));\n            }\n            printf(\"[N:%d]: Minv codegen: \",NUM_TIME_STEPS); printStats(&times); times.clear();\n            printf(\"----------------------------------------\\n\");\n\n            for(int iter = 0; iter < TEST_ITERS; iter++){\n                clock_gettime(CLOCK_MONOTONIC,&start);\n                forwardDynamicsThreaded_codegen<T,NUM_THREADS,NUM_TIME_STEPS>(minv_code_gen_arr,rnea_code_gen_arr,\n                                                                              model.nq,model.nv,qs,qds,qdds,us,&threads);\n                clock_gettime(CLOCK_MONOTONIC,&end);\n                times.push_back(time_delta_us_timespec(start,end));\n            }\n            printf(\"[N:%d]: FD codegen: \",NUM_TIME_STEPS); printStats(&times); times.clear();\n            printf(\"----------------------------------------\\n\");\n\n            for(int iter = 0; iter < TEST_ITERS; iter++){\n                clock_gettime(CLOCK_MONOTONIC,&start);\n                inverseDynamicsGradientThreaded_codegen<T,NUM_THREADS,NUM_TIME_STEPS>(rnea_derivatives_code_gen_arr,\n                                                                                      model.nq,model.nv,qs,qds,&threads);\n                clock_gettime(CLOCK_MONOTONIC,&end);\n                times.push_back(time_delta_us_timespec(start,end));\n            }\n            printf(\"[N:%d]: ID_DU codegen: \",NUM_TIME_STEPS); printStats(&times); times.clear();\n            printf(\"----------------------------------------\\n\");\n\n            for(int iter = 0; iter < TEST_ITERS; iter++){\n                clock_gettime(CLOCK_MONOTONIC,&start);\n                forwardDynamicsGradientThreaded_codegen<T,NUM_THREADS,NUM_TIME_STEPS>(rnea_derivatives_code_gen_arr,\n                                                                                    minv_code_gen_arr,rnea_code_gen_arr,\n                                                                                    model.nq,model.nv,dqdd_dqs,dqdd_dvs,\n                                                                                    qs,qds,us,&threads);\n                clock_gettime(CLOCK_MONOTONIC,&end);\n                times.push_back(time_delta_us_timespec(start,end));\n            }\n            printf(\"[N:%d]: FD_DU codegen: \",NUM_TIME_STEPS); printStats(&times); times.clear();\n            printf(\"----------------------------------------\\n\");\n        }\n    #endif\n\n    // make sure to delete objs\n    for (int i = 0; i < NUM_THREADS; i++){delete rnea_derivatives_code_gen_arr[i];}// delete rnea_code_gen_arr[i]; delete minv_code_gen_arr[i];}\n}\n\ntemplate<typename T, int TEST_ITERS, int CPU_THREADS>\nvoid run_all_tests(std::string urdf_filepath){\n    test<T,10*TEST_ITERS,CPU_THREADS,1>(urdf_filepath);\n    #if !TEST_FOR_EQUIVALENCE\n        test<T,TEST_ITERS,CPU_THREADS,16>(urdf_filepath);\n        test<T,TEST_ITERS,CPU_THREADS,32>(urdf_filepath);\n        test<T,TEST_ITERS,CPU_THREADS,64>(urdf_filepath);\n        test<T,TEST_ITERS,CPU_THREADS,128>(urdf_filepath);\n        test<T,TEST_ITERS,CPU_THREADS,256>(urdf_filepath);\n    #endif\n}\n\nint main(int argc, const char ** argv){\n    std::string urdf_filepath;\n    if(argc>1){urdf_filepath = argv[1];}\n    else{printf(\"Usage is: urdf_filepath\\n\"); return 1;}\n\n    run_all_tests<float,TEST_ITERS_GLOBAL,CPU_THREADS_GLOBAL>(urdf_filepath);\n    return 0;\n}", "meta": {"hexsha": "685f8f0bc934b11e4861c1887b7bfb9239e76698", "size": 21290, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "timePinocchio.cpp", "max_stars_repo_name": "robot-acceleration/GRiDBenchmarks", "max_stars_repo_head_hexsha": "889553106efdfdd7d05ee9ca911debbd9a6a22d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-16T02:12:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-16T02:12:33.000Z", "max_issues_repo_path": "timePinocchio.cpp", "max_issues_repo_name": "robot-acceleration/GRiDBenchmarks", "max_issues_repo_head_hexsha": "889553106efdfdd7d05ee9ca911debbd9a6a22d1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-09-18T11:33:00.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-18T16:16:31.000Z", "max_forks_repo_path": "timePinocchio.cpp", "max_forks_repo_name": "robot-acceleration/GRiDBenchmarks", "max_forks_repo_head_hexsha": "889553106efdfdd7d05ee9ca911debbd9a6a22d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 53.7626262626, "max_line_length": 189, "alphanum_fraction": 0.586895256, "num_tokens": 5571, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.6477982315512488, "lm_q1q2_score": 0.4945834318485624}}
{"text": "/* boost random/normal_distribution.hpp header file\n *\n * Copyright Jens Maurer 2000-2001\n * Copyright Steven Watanabe 2010-2011\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 * Revision history\n *  2001-02-18  moved to individual header files\n */\n\n#ifndef BOOST_RANDOM_NORMAL_DISTRIBUTION_HPP\n#define BOOST_RANDOM_NORMAL_DISTRIBUTION_HPP\n\n#include <boost/config/no_tr1/cmath.hpp>\n#include <istream>\n#include <iosfwd>\n#include <boost/assert.hpp>\n#include <boost/limits.hpp>\n#include <boost/static_assert.hpp>\n#include <boost/random/detail/config.hpp>\n#include <boost/random/detail/operators.hpp>\n#include <boost/random/uniform_01.hpp>\n\nnamespace boost {\nnamespace random {\n\n// deterministic Box-Muller method, uses trigonometric functions\n\n/**\n * Instantiations of class template normal_distribution model a\n * \\random_distribution. Such a distribution produces random numbers\n * @c x distributed with probability density function\n * \\f$\\displaystyle p(x) =\n *   \\frac{1}{\\sqrt{2\\pi\\sigma}} e^{-\\frac{(x-\\mu)^2}{2\\sigma^2}}\n * \\f$,\n * where mean and sigma are the parameters of the distribution.\n */\ntemplate<class RealType = double>\nclass normal_distribution\n{\npublic:\n    typedef RealType input_type;\n    typedef RealType result_type;\n\n    class param_type {\n    public:\n        typedef normal_distribution distribution_type;\n\n        /**\n         * Constructs a @c param_type with a given mean and\n         * standard deviation.\n         *\n         * Requires: sigma >= 0\n         */\n        explicit param_type(RealType mean_arg = RealType(0.0),\n                            RealType sigma_arg = RealType(1.0))\n          : _mean(mean_arg),\n            _sigma(sigma_arg)\n        {}\n\n        /** Returns the mean of the distribution. */\n        RealType mean() const { return _mean; }\n\n        /** Returns the standand deviation of the distribution. */\n        RealType sigma() const { return _sigma; }\n\n        /** Writes a @c param_type to a @c std::ostream. */\n        BOOST_RANDOM_DETAIL_OSTREAM_OPERATOR(os, param_type, parm)\n        { os << parm._mean << \" \" << parm._sigma ; return os; }\n\n        /** Reads a @c param_type from a @c std::istream. */\n        BOOST_RANDOM_DETAIL_ISTREAM_OPERATOR(is, param_type, parm)\n        { is >> parm._mean >> std::ws >> parm._sigma; return is; }\n\n        /** Returns true if the two sets of parameters are the same. */\n        BOOST_RANDOM_DETAIL_EQUALITY_OPERATOR(param_type, lhs, rhs)\n        { return lhs._mean == rhs._mean && lhs._sigma == rhs._sigma; }\n        \n        /** Returns true if the two sets of parameters are the different. */\n        BOOST_RANDOM_DETAIL_INEQUALITY_OPERATOR(param_type)\n\n    private:\n        RealType _mean;\n        RealType _sigma;\n    };\n\n    /**\n     * Constructs a @c normal_distribution object. @c mean and @c sigma are\n     * the parameters for the distribution.\n     *\n     * Requires: sigma >= 0\n     */\n    explicit normal_distribution(const RealType& mean_arg = RealType(0.0),\n                                 const RealType& sigma_arg = RealType(1.0))\n      : _mean(mean_arg), _sigma(sigma_arg),\n        _r1(0), _r2(0), _cached_rho(0), _valid(false)\n    {\n        BOOST_ASSERT(_sigma >= RealType(0));\n    }\n\n    /**\n     * Constructs a @c normal_distribution object from its parameters.\n     */\n    explicit normal_distribution(const param_type& parm)\n      : _mean(parm.mean()), _sigma(parm.sigma()),\n        _r1(0), _r2(0), _cached_rho(0), _valid(false)\n    {}\n\n    /**  Returns the mean of the distribution. */\n    RealType mean() const { return _mean; }\n    /** Returns the standard deviation of the distribution. */\n    RealType sigma() const { return _sigma; }\n\n    /** Returns the smallest value that the distribution can produce. */\n    RealType min BOOST_PREVENT_MACRO_SUBSTITUTION () const\n    { return -std::numeric_limits<RealType>::infinity(); }\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    /** Returns the parameters of the distribution. */\n    param_type param() const { return param_type(_mean, _sigma); }\n    /** Sets the parameters of the distribution. */\n    void param(const param_type& parm)\n    {\n        _mean = parm.mean();\n        _sigma = parm.sigma();\n        _valid = false;\n    }\n\n    /**\n     * Effects: Subsequent uses of the distribution do not depend\n     * on values produced by any engine prior to invoking reset.\n     */\n    void reset() { _valid = false; }\n\n    /**  Returns a normal variate. */\n    template<class Engine>\n    result_type operator()(Engine& eng)\n    {\n        using std::sqrt;\n        using std::log;\n        using std::sin;\n        using std::cos;\n\n        if(!_valid) {\n            _r1 = boost::uniform_01<RealType>()(eng);\n            _r2 = boost::uniform_01<RealType>()(eng);\n            _cached_rho = sqrt(-result_type(2) * log(result_type(1)-_r2));\n            _valid = true;\n        } else {\n            _valid = false;\n        }\n        // Can we have a boost::mathconst please?\n        const result_type pi = result_type(3.14159265358979323846);\n\n        return _cached_rho * (_valid ?\n                              cos(result_type(2)*pi*_r1) :\n                              sin(result_type(2)*pi*_r1))\n            * _sigma + _mean;\n    }\n\n    /** Returns a normal variate with parameters specified by @c param. */\n    template<class URNG>\n    result_type operator()(URNG& urng, const param_type& parm)\n    {\n        return normal_distribution(parm)(urng);\n    }\n\n    /** Writes a @c normal_distribution to a @c std::ostream. */\n    BOOST_RANDOM_DETAIL_OSTREAM_OPERATOR(os, normal_distribution, nd)\n    {\n        os << nd._mean << \" \" << nd._sigma << \" \"\n           << nd._valid << \" \" << nd._cached_rho << \" \" << nd._r1;\n        return os;\n    }\n\n    /** Reads a @c normal_distribution from a @c std::istream. */\n    BOOST_RANDOM_DETAIL_ISTREAM_OPERATOR(is, normal_distribution, nd)\n    {\n        is >> std::ws >> nd._mean >> std::ws >> nd._sigma\n           >> std::ws >> nd._valid >> std::ws >> nd._cached_rho\n           >> std::ws >> nd._r1;\n        return is;\n    }\n\n    /**\n     * Returns true if the two instances of @c normal_distribution will\n     * return identical sequences of values given equal generators.\n     */\n    BOOST_RANDOM_DETAIL_EQUALITY_OPERATOR(normal_distribution, lhs, rhs)\n    {\n        return lhs._mean == rhs._mean && lhs._sigma == rhs._sigma\n            && lhs._valid == rhs._valid\n            && (!lhs._valid || (lhs._r1 == rhs._r1 && lhs._r2 == rhs._r2));\n    }\n\n    /**\n     * Returns true if the two instances of @c normal_distribution will\n     * return different sequences of values given equal generators.\n     */\n    BOOST_RANDOM_DETAIL_INEQUALITY_OPERATOR(normal_distribution)\n\nprivate:\n    RealType _mean, _sigma;\n    RealType _r1, _r2, _cached_rho;\n    bool _valid;\n\n};\n\n} // namespace random\n\nusing random::normal_distribution;\n\n} // namespace boost\n\n#endif // BOOST_RANDOM_NORMAL_DISTRIBUTION_HPP\n", "meta": {"hexsha": "4d0c07edc4a8d5af83ddcbbf7c914ae4c76635b4", "size": 7247, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/boost/random/normal_distribution.hpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-08-07T16:21:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-17T10:58:37.000Z", "max_issues_repo_path": "boost/boost/random/normal_distribution.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/random/normal_distribution.hpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-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.3526785714, "max_line_length": 76, "alphanum_fraction": 0.6300538154, "num_tokens": 1740, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.49458341805549216}}
{"text": "#include <gtest/gtest.h>\n#include \"util/logger.hpp\"\n#include <ros/ros.h>\n#include \"collision_detection/MoveItCollisionHelper.h\"\n#include <moveit_visual_tools/moveit_visual_tools.h>\n#include \"opencv2/opencv.hpp\"\n#include \"planner/PlannerMethod.hpp\"\n#include <boost/thread/thread.hpp>\n#include <boost/thread/locks.hpp>\n#include <boost/thread/shared_mutex.hpp>\ninline bool collision_check(const state_space::Rn& test_state){\n    static cv::Mat environment{cv::imread(\"/home/xcy/Cspace/SampleBasedPlanningMethods/3.png\", 0)};\n    Eigen::Vector2d bounds{environment.cols,environment.rows};\n    return test_state.Vector().minCoeff()>=0&&\n           (test_state.Vector()-bounds).maxCoeff()<=0\n           &&environment.at<uchar>((int) test_state.Vector()[1], (int) test_state.Vector()[0]) == 255;\n}\ndouble vdc(int n,unsigned int bits) {\n    int reverse = 0;\n    while (n){\n        int pos = log2(n & -n) + 1;\n        reverse = reverse | (1 << (bits - pos));\n        n = n & (n - 1);\n    }\n    return reverse;\n}\nstd::size_t check_times;\nbool isPathValid_vdc(const state_space::Rn& from, const state_space::Rn& to){\n    const double min_distance=0.5;\n    check_times++;\n    if(!collision_check(to))\n        return false;\n    unsigned int K = ceil(log2(ceil(planner::distance(from,to)/min_distance)));\n    unsigned int bits = K;\n    K = 1<<K;\n    for(int k=0; k<K;++k){\n        check_times++;\n        auto intermediate_state = planner::interpolate(from, to, vdc(k,bits)/K);\n        if (!collision_check(intermediate_state))\n            return false;\n    }\n    return true;\n}\nbool isPathValid_incremental(const state_space::Rn& from, const state_space::Rn& to){\n    const double min_distance=0.5;\n    unsigned int K= ceil(planner::distance(from,to)/min_distance);\n    K = K? K:1;\n    for(int k=0;k<=K;++k) {\n        check_times++;\n        auto intermediate_state = planner::interpolate(from, to, (double)k/K);\n        if(!collision_check(intermediate_state))\n            return false;\n    }\n    return true;\n}\ntemplate<typename T>\nvoid _animate(cv::Mat& draw, planner::Vertex<T> * vertex)\n{\n    cv::circle(draw, cv::Point((int)vertex->state().Vector()[0], (int)vertex->state().Vector()[1]), 3, cv::Scalar{255, 0, 0}, 1);\n    for(auto & it : vertex->children())\n    {\n        cv::line(draw, cv::Point((int)vertex->state().Vector()[0], (int)vertex->state().Vector()[1]),\n                 cv::Point((int)it->state().Vector()[0], (int)it->state().Vector()[1]), cv::Scalar{255, 0, 0}, 2);\n        _animate(draw,it);\n    }\n}\ntemplate<typename T>\nvoid animate(cv::Mat &draw, const std::vector<planner::Vertex<T>*>& roots)\n{\n    boost::this_thread::interruption_enabled();\n    while(true){\n        boost::this_thread::interruption_point();\n        for(const auto& item: roots){\n            _animate(draw,item);\n        }\n        cv::Mat canvas;\n        cv::resize(draw,canvas,cv::Size{800,800});\n        cv::imshow(\"check: \",canvas);\n        cv::waitKey(10);\n    }\n\n}\n/*\ntemplate<typename SPCIFIC_STATE>\nvoid test_no_collision_func(int dimensions = -1, const Eigen::MatrixX2d *bounds_ptr = nullptr)\n{\n    auto start_state = planner::randomState<SPCIFIC_STATE>(dimensions, bounds_ptr);\n    auto goal_state = planner::randomState<SPCIFIC_STATE>(dimensions, bounds_ptr);\n\n    planner::RRT<SPCIFIC_STATE> rrt_2d(planner::hash<SPCIFIC_STATE>, start_state.Dimensions());\n\n\n    rrt_2d.constructPlan(planner::PLAN_REQUEST<SPCIFIC_STATE>(start_state, goal_state, 50,0.1,false, 0.1));\n    std::vector<SPCIFIC_STATE> path;\n    clock_t start(clock());\n    if (rrt_2d.planning()) {\n        clock_t end(clock());\n        LOG(INFO) << \"planning time consumption: \" << static_cast<double>(end - start) / CLOCKS_PER_SEC;\n        path = rrt_2d.GetPath();\n        for (const auto &it: path) {\n            LOG(INFO) << it;\n        }\n    }\n    EXPECT_TRUE(!path.empty()) << \"No path found\";\n}\n\ntemplate<typename SPCIFIC_STATE>\nvoid test_with_collision_func(int dimensions = -1, const Eigen::MatrixX2d *bounds_ptr = nullptr)\n{\n    ros::AsyncSpinner spinner(2);\n    spinner.start();\n    my_collision_detection::MoveItCollisionHelper moveItCollisionHelper(\"manipulator_i5\",\n                                                                        \"/home/xcy/WorkSpace/src/NursingRobot/config/aubo_i5.yaml\",\n                                                                        my_kinematics::aubo_i5_analytical_IK);\n\n\n    auto start_state = planner::randomState<SPCIFIC_STATE>(dimensions, bounds_ptr);\n    auto goal_state = planner::randomState<SPCIFIC_STATE>(dimensions, bounds_ptr);\n    clock_t start(clock());\n    double time{};\n    while (true) {\n        time = (double) (clock() - start) / CLOCKS_PER_SEC;\n        CHECK_LT(time, 5) << \"Generate valid state failed out of 5 s\";\n        start_state = planner::randomState<SPCIFIC_STATE>(dimensions, bounds_ptr);\n        goal_state = planner::randomState<SPCIFIC_STATE>(dimensions, bounds_ptr);\n        if (moveItCollisionHelper.isStateValid(start_state) && moveItCollisionHelper.isStateValid(goal_state))\n            break;\n    }\n\n    planner::RRT<SPCIFIC_STATE> rrt_2d(planner::hash<SPCIFIC_STATE>, start_state.Dimensions());\n\n\n    rrt_2d.setStateValidator(std::function<bool(const SPCIFIC_STATE &, const SPCIFIC_STATE &)>(\n            std::bind(&my_collision_detection::MoveItCollisionHelper::isPathValid<SPCIFIC_STATE>,\n                      &moveItCollisionHelper, std::placeholders::_1, std::placeholders::_2)\n    ));\n\n\n    rrt_2d.setStepLen(0.05);\n    rrt_2d.setGoalMaxDist(0.05);\n    rrt_2d.constructPlan(planner::PLAN_REQUEST<SPCIFIC_STATE>(start_state, goal_state, 10));\n    std::vector<SPCIFIC_STATE> path;\n    if (rrt_2d.planning()) {\n        clock_t end(clock());\n        LOG(INFO) << \"planning time consumption: \" << static_cast<double>(end - start) / CLOCKS_PER_SEC;\n        path = rrt_2d.GetPath();\n        for (const auto &it: path) {\n            LOG(INFO) << it;\n        }\n    }\n    EXPECT_TRUE(!path.empty()) << \"No path found\";\n    spinner.stop();\n}\n\n\nTEST(RRTTest, J6WithoutCollisionTest)\n{\n    test_no_collision_func<state_space::JointSpace>(6);\n}\n\nTEST(RRTTest, R2WithoutCollisionTest)\n{\n    test_no_collision_func<state_space::Rn>(2);\n}\n\nTEST(RRTTest, R3WithoutCollisionTest)\n{\n    test_no_collision_func<state_space::Rn>(3);\n}\n\nTEST(RRTTest, SE3WithoutCollisionTest)\n{\n    test_no_collision_func<state_space::SE3>();\n}\n\nTEST(RRTTest, SO3WithoutCollisionTest)\n{\n    test_no_collision_func<state_space::SO3>();\n}\n\nTEST(RRTTest, J6withCollisionTest)\n{\n    Eigen::MatrixX2d bounds;\n    bounds.resize(6, 2);\n    bounds << state_space::R6().setConstant(3.05),\n            state_space::R6().setConstant(-3.05);\n    test_with_collision_func<state_space::JointSpace>(1, nullptr);\n}\n\nTEST(RRTTest, SE3withCollisionTest)\n{\n    test_with_collision_func<state_space::SE3>();\n}*/\n\nTEST(RRTTest, R2WithAnimationTest)\n{\n    //load environment\n    cv::Mat img = cv::imread(\"/home/xcy/Cspace/SampleBasedPlanningMethods/map6.png\");\n    //set sample bounds\n    Eigen::MatrixX2d bounds;\n    bounds.resize(2, 2);\n    bounds << Eigen::Vector2d{img.cols, img.rows},\n            Eigen::Vector2d::Zero();\n\n    //set start state\n    state_space::Rn start_state{std::vector<double>{1,1}};\n    //set valid goal state\n    state_space::Rn goal_state{std::vector<double>{1990,1990}};\n    std::size_t i=0;\n    const std::size_t max_iterations=1e4;\n    const std::string base_path{\"/home/xcy/RRT_EXP2D/\"};\n    const std::string goal_list{\"Goals.txt\"};\n\n    std::string final_path = base_path+goal_list;\n    const std::vector<std::string> txt_names{{\"/time.txt\"},{\"/pathLength.txt\"},{\"/ccTimes.txt\"},\n                                             {\"/nodes.txt\"},{\"/invalidGoals.txt\"},{\"/performance.txt\"}};\n\n    std::size_t  iter_index=0;\n    std::size_t total_time{};\n    std::size_t valid_times=0;\n    double total_length{};\n    std::size_t total_path_size{};\n    std::size_t total_nodes{};\n    std::size_t total_ccTimes{};\n\n    std::ifstream goal_src(final_path.c_str());\n\n    auto rrt_based_planner_ptr = planner::createPlanner<state_space::Rn,flann::L2_Simple<double>>(planner::RRT_SIMPLE,start_state.Dimensions());\n\n    rrt_based_planner_ptr->setStateValidator(std::function<bool(const state_space::Rn &, const state_space::Rn &)>(\n            isPathValid_incremental));\n    rrt_based_planner_ptr->setSampleBounds(&bounds);\n\n    std::vector<std::ofstream> outfile_vector{};\n    outfile_vector.resize(txt_names.size());\n    for(int i=0;i<txt_names.size();++i){\n        outfile_vector[i].open(base_path+rrt_based_planner_ptr->getName()+txt_names[i],std::ios::out | std::ios::trunc);\n    }\n\n    while(iter_index++<max_iterations){\n        std::string s;getline(goal_src,s);\n        std::istringstream stringGet(s);\n        stringGet>>start_state[0]>>start_state[1]>>goal_state[0]>>goal_state[1];\n        rrt_based_planner_ptr->constructPlan(planner::PLAN_REQUEST<state_space::Rn,flann::L2_Simple<double>>(start_state, goal_state, 10,200,false,30,0));\n        std::vector<state_space::Rn> path;\n        clock_t start(clock());\n        if (rrt_based_planner_ptr->planning()) {\n            path = rrt_based_planner_ptr->GetPath();\n            //valid times\n            valid_times++;\n            //single time\n            outfile_vector[0]<<(double)(clock()-start)/CLOCKS_PER_SEC<<std::endl;\n            //single length\n            double path_length{};\n            for(int i=0; i<path.size()-1;++i){\n                path_length += planner::distance(path[i],path[i+1]);\n            }\n            outfile_vector[1]<<path.size()<<\" \"<<path_length<<std::endl;\n            //single cc times\n            outfile_vector[2]<<check_times<<std::endl;\n            //single iter times\n            outfile_vector[3]<<rrt_based_planner_ptr->getTotalNodes()<<std::endl;\n\n            //average usage\n            total_time += clock() - start;\n            total_length += path_length;\n            total_path_size += path.size();\n            total_ccTimes += check_times;\n            total_nodes+=rrt_based_planner_ptr->getTotalNodes();\n            check_times=0;\n        }\n        else{\n            outfile_vector[4]<<goal_state<<std::endl;\n        }\n    }\n    outfile_vector[5]<<\"average planning time: \"<<(double)total_time / valid_times / CLOCKS_PER_SEC<<\"s\"<<std::endl;\n    outfile_vector[5]<<\"average path length: \"<<total_length/valid_times<<std::endl;\n    outfile_vector[5]<<\"average path size: \"<<(double)total_path_size/valid_times<<std::endl;\n    outfile_vector[5]<<\"average cc Times: \"<<(long double)total_ccTimes/valid_times<<std::endl;\n    outfile_vector[5] << \"average nodes: \" << (long double)total_nodes / valid_times << std::endl;\n    outfile_vector[5]<<\"valid percent: \"<<valid_times<<\"/\"<<max_iterations<<\": \"<<(double)valid_times/max_iterations<<std::endl;\n\n    if(goal_src.is_open()) {\n        goal_src.close();\n    }\n    for(int i=0; i<txt_names.size();++i){\n        if(outfile_vector[i].is_open()){\n            outfile_vector[i].close();\n        }\n    }\n}\nTEST(RRTTest, R2SingleTest){\n    //load environment\n    std::shared_ptr<boost::thread> thread_ptr_;\n    cv::Mat img = cv::imread(\"/home/xcy/Cspace/SampleBasedPlanningMethods/3.png\");\n    //set sample bounds\n    Eigen::MatrixX2d bounds;\n    bounds.resize(2, 2);\n    bounds << Eigen::Vector2d{img.cols, img.rows},\n            Eigen::Vector2d::Zero();\n\n    state_space::Rn start_state{std::vector<double>{190,245}};\n    state_space::Rn goal_state{std::vector<double>{650,360}};\n\n    auto rrt_based_planner_ptr = planner::createPlanner<state_space::Rn,flann::L2_Simple<double>>(planner::RRT_SIMPLE,start_state.Dimensions());\n    rrt_based_planner_ptr->setStateValidator(std::function<bool(const state_space::Rn &, const state_space::Rn &)>(\n            isPathValid_vdc));\n    rrt_based_planner_ptr->setSampleBounds(&bounds);\n    rrt_based_planner_ptr->constructPlan(planner::PLAN_REQUEST<state_space::Rn,flann::L2_Simple<double>>(start_state, goal_state, 5000,60,false,30,0.05));\n    std::vector<state_space::Rn> path;\n    clock_t before{clock()};\n    //thread_ptr_.reset(new boost::thread(boost::bind(&animate<state_space::Rn>,img,rrt_based_planner_ptr->getRootVertex())));\n    if (rrt_based_planner_ptr->planning()) {\n        std::cout<<\"time: \"<<static_cast<double>((clock()-before))/CLOCKS_PER_SEC<<\"\"\n                                                                                   \"s\"<<std::endl;\n        path = rrt_based_planner_ptr->GetPath();\n        auto root_vertex=rrt_based_planner_ptr->getRootVertex();\n        //visualization\n        for(const auto& item: root_vertex){\n            _animate(img,item);\n        }\n        for (std::size_t i = 1; i < path.size(); ++i) {\n            cv::line(img, cv::Point(path[i].Vector()[0], path[i].Vector()[1]),\n                     cv::Point(path[i - 1].Vector()[0], path[i - 1].Vector()[1]), cv::Scalar{0, 0, 255}, 2);\n        }\n        double path_length{};\n        for(int i=0; i<path.size()-1;++i){\n            path_length += planner::distance(path[i],path[i+1]);\n        }\n        std::cout<<path.size()<<\" \"<<path_length<<std::endl;\n        std::cout<<\"nodes: \"<<rrt_based_planner_ptr->getTotalNodes()<<std::endl;\n        std::cout<<\"cc Times: \"<<check_times<<std::endl;\n        cv::resize(img,img,cv::Size{800,800});\n        cv::imshow(\"check: \",img);\n        cv::waitKey(0);\n        //cv::imwrite(\"/home/xcy/\"+rrt_based_planner_ptr->getName()+\".png\",img);\n    }\n    //thread_ptr_->interrupt();\n    //thread_ptr_->join();\n}\n\nint main(int argc, char **argv)\n{\n    logger lg(argv[0]);\n    testing::InitGoogleTest(&argc, argv);\n    ros::init(argc, argv, \"RRTTest\");\n    return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "0378d6674303392c91f173f4d8d9ea67c896b0b4", "size": 13610, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/rrt_test.cpp", "max_stars_repo_name": "ZhouYixuanRobtic/NursingRobot", "max_stars_repo_head_hexsha": "1372e4af40a3315b754d1b6273b5a00d09c4def6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-09T01:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-09T01:32:13.000Z", "max_issues_repo_path": "test/rrt_test.cpp", "max_issues_repo_name": "ZhouYixuanRobtic/NursingRobot", "max_issues_repo_head_hexsha": "1372e4af40a3315b754d1b6273b5a00d09c4def6", "max_issues_repo_licenses": ["MIT"], "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/rrt_test.cpp", "max_forks_repo_name": "ZhouYixuanRobtic/NursingRobot", "max_forks_repo_head_hexsha": "1372e4af40a3315b754d1b6273b5a00d09c4def6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-15T15:29:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-15T15:29:08.000Z", "avg_line_length": 38.9971346705, "max_line_length": 154, "alphanum_fraction": 0.6371050698, "num_tokens": 3622, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.647798211152541, "lm_q1q2_score": 0.49458341627448027}}
{"text": "/*\n@copyright Louis Dionne 2015\nDistributed under the Boost Software License, Version 1.0.\n(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n */\n\n#include <boost/hana/assert.hpp>\n#include <boost/hana/integral_constant.hpp>\nusing namespace boost::hana;\n\n\nint main() {\n\n{\n\n//! [rem]\nBOOST_HANA_CONSTANT_CHECK(rem(int_<6>, int_<4>) == int_<2>);\nBOOST_HANA_CONSTANT_CHECK(rem(int_<-6>, int_<4>) == int_<-2>);\nBOOST_HANA_CONSTEXPR_CHECK(rem(6, 4) == 2);\n//! [rem]\n\n}{\n\n//! [quot]\nBOOST_HANA_CONSTANT_CHECK(quot(int_<6>, int_<3>) == int_<2>);\nBOOST_HANA_CONSTANT_CHECK(quot(int_<6>, int_<4>) == int_<1>);\n\nBOOST_HANA_CONSTEXPR_CHECK(quot(6, 3) == 2);\nBOOST_HANA_CONSTEXPR_CHECK(quot(6, 4) == 1);\n//! [quot]\n\n}\n\n}\n", "meta": {"hexsha": "192162bf4790600225cb39d1dee0900ec47cc452", "size": 736, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/integral_domain.cpp", "max_stars_repo_name": "josephwinston/hana", "max_stars_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/integral_domain.cpp", "max_issues_repo_name": "josephwinston/hana", "max_issues_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/integral_domain.cpp", "max_forks_repo_name": "josephwinston/hana", "max_forks_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.0285714286, "max_line_length": 78, "alphanum_fraction": 0.6942934783, "num_tokens": 231, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7634837527911057, "lm_q2_score": 0.647798211152541, "lm_q1q2_score": 0.4945834093021071}}
{"text": "/*\r\nThis sample illustrates how to use the Fr\u00e9chet Range Queries Library from a\r\ntypical Boost::Geometry project.\r\n\r\ntwo versions are given:\r\n  one is vector_of_points, which models a trajectory as a vector of boost points\r\n  one is linestring, which models a trajectory as a linestring feature.\r\n\r\n*/\r\n#include <cmath>\r\n#include <functional>\r\n#include <iostream>\r\n#include <vector>\r\n\r\n#include <boost/geometry.hpp>\r\n#include <boost/geometry/geometries/geometries.hpp>\r\n#include <boost/geometry/geometries/linestring.hpp>\r\n\r\n#include \"../include/frechetrange/frechetrange.hpp\"\r\n\r\nusing std::cout;\r\nusing std::endl;\r\nnamespace bg = boost::geometry;\r\n\r\n// Declare Geometry\r\ntypedef bg::model::point<double, 2, bg::cs::cartesian> point_type;\r\ntypedef bg::model::linestring<point_type> linestring_type;\r\n\r\nstruct get_coordinate {\r\n    template <size_t dim>\r\n    static double get(const point_type &p) {\r\n        return p.get<dim>();\r\n    }\r\n};\r\n\r\nstruct squared_distance {\r\n    double operator()(const point_type &p, const point_type &q) const {\r\n        return bg::comparable_distance(p, q);\r\n    }\r\n};\r\n\r\nint main(int argc, char **argv) {\r\n    // Linestring version\r\n    linestring_type t1, t2;\r\n\r\n    // read from WKT\r\n    bg::read_wkt(\"LINESTRING(0 0 , 0 1, 0 2)\", t1);\r\n    bg::read_wkt(\"LINESTRING(1 1, 2 2, 1 3)\", t2);\r\n\r\n    // instantiate some decider, this time fully specified.\r\n    frechetrange::detail::dv::frechet_distance<2, get_coordinate,\r\n                                               squared_distance>\r\n        fd;\r\n\r\n    cout << std::fixed;\r\n    // a range scan\r\n    for (double d = 1; d < 5; d += 0.25)\r\n        cout << \"Reachable at \" << d << \":\\t\"\r\n             << (fd.is_bounded_by(t1, t2, d) ? \"yes\" : \"no\") << endl;\r\n\r\n    // estimate the distance by interval cutting\r\n    {\r\n        std::pair<double, double> interval = {0, 5};\r\n        while ((interval.second - interval.first) > 0.001) {\r\n            double m = (interval.first + interval.second) / 2;\r\n\r\n            if (fd.is_bounded_by(t1, t2, m)) {\r\n                interval.second = m;\r\n            } else {\r\n                interval.first = m;\r\n            }\r\n        }\r\n        cout << \"Final Interval: [\" << interval.first << \",\" << interval.second\r\n             << \"]\" << endl;\r\n    }\r\n\r\n    // Bringmann Baldus Case\r\n\r\n    frechetrange::detail::bb::frechet_distance<2, get_coordinate,\r\n                                               squared_distance>\r\n        fd2;\r\n\r\n    cout << std::fixed;\r\n    // a range scan\r\n    for (double d = 1; d < 5; d += 0.25)\r\n        cout << \"Reachable at \" << d << \":\\t\"\r\n             << (fd2.is_bounded_by(t1, t2, d) ? \"yes\" : \"no\") << endl;\r\n\r\n    // estimate the distance by interval cutting\r\n    {\r\n        std::pair<double, double> interval = {0, 5};\r\n        while ((interval.second - interval.first) > 0.001) {\r\n            double m = (interval.first + interval.second) / 2;\r\n\r\n            if (fd2.is_bounded_by(t1, t2, m)) {\r\n                interval.second = m;\r\n            } else {\r\n                interval.first = m;\r\n            }\r\n        }\r\n        cout << \"Final Interval: [\" << interval.first << \",\" << interval.second\r\n             << \"]\" << endl;\r\n    }\r\n\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "1ac25cb0f5f1f95e6ed5256409556f7bda36a22b", "size": 3211, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "samples/bg.cpp", "max_stars_repo_name": "TWTDIG/frechetrange", "max_stars_repo_head_hexsha": "b5b30708a7d2ec181ed6a870923542e286f894ab", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-03-24T02:40:36.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-31T02:50:49.000Z", "max_issues_repo_path": "samples/bg.cpp", "max_issues_repo_name": "TWTDIG/frechetrange", "max_issues_repo_head_hexsha": "b5b30708a7d2ec181ed6a870923542e286f894ab", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2017-11-22T11:09:52.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-03T09:55:01.000Z", "max_forks_repo_path": "samples/bg.cpp", "max_forks_repo_name": "TWTDIG/frechetrange", "max_forks_repo_head_hexsha": "b5b30708a7d2ec181ed6a870923542e286f894ab", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-11-21T07:29:32.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-22T15:50:47.000Z", "avg_line_length": 30.0093457944, "max_line_length": 81, "alphanum_fraction": 0.5499844285, "num_tokens": 808, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911056, "lm_q2_score": 0.647798211152541, "lm_q1q2_score": 0.49458340930210704}}
{"text": "// -------------- test the visual odometry -------------\n#ifndef SFMTEST_INCLUDE_H\n#define SFMTEST_INCLUDE_H\n#include <ceres/ceres.h>\n#include <ceres/rotation.h>\n#include <fstream>\n#include <Eigen/Dense>\n// #include \"myslam/common_include.h\"\n#include <boost/timer.hpp>\n#include <opencv2/imgcodecs.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/viz.hpp>\n#include <opencv2/core/core.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n\n#include <opencv2/opencv.hpp>\n#include <opencv2/core/eigen.hpp>\n\n#include <map>\n#include <opencv2/video/tracking.hpp>\n\n#include \"myslam/config.h\"\n#include \"myslam/visual_odometry.h\"\n\nusing namespace std;\nusing namespace cv;\nusing namespace Eigen;\nstruct SFMFeature\n{\n    bool state;\n    int id;\n    vector<pair<int, Vector2d>> observation;//\u8fd9\u4e2a\u5c31\u53ef\u4ee5\u8868\u793a\u5728\u6bcf\u5e27\u542c\u5230\u7684\u4f4d\u7f6e\n    double position[3];\n    double depth;\n};\nstruct FrameInfo\n{\n  int id;\n  Mat img;\n  vector<KeyPoint> frameKeypoints;\n  Mat FrameDescriptors;\n  vector<Point3d> depth;\n};\n// \u50cf\u7d20\u5750\u6807\u8f6c\u76f8\u673a\u5f52\u4e00\u5316\u5750\u6807\nPoint2f pixel2cam(const Point2d &p, const Mat &K);\n\nstruct ReprojectionError3D\n{\n    ReprojectionError3D(double observed_u, double observed_v)\n        : observed_u(observed_u), observed_v(observed_v)\n    {\n    }\n\n    template <typename T>\n    bool operator()(const T *const camera_R, const T *const camera_T, const T *point, T *residuals) const\n    {\n        T p[3];\n        ceres::QuaternionRotatePoint(camera_R, point, p);\n        p[0] += camera_T[0];\n        p[1] += camera_T[1];\n        p[2] += camera_T[2];\n        T xp = p[0] / p[2];\n        T yp = p[1] / p[2];\n        residuals[0] = xp - T(observed_u);\n        residuals[1] = yp - T(observed_v);\n        return true;\n    }\n\n    static ceres::CostFunction *Create(const double observed_x,\n                                       const double observed_y)\n    {\n        return (new ceres::AutoDiffCostFunction<\n                ReprojectionError3D, 2, 4, 3, 3>(\n            new ReprojectionError3D(observed_x, observed_y)));\n    }\n\n    double observed_u;\n    double observed_v;\n};\ntemplate <class T> void reduceVector(vector<T> &v, vector<uchar> status)\n{\n    int j = 0;\n    for (int i = 0; i < int(v.size()); i++)\n        if (status[i])\n            v[j++] = v[i];\n    v.resize(j);\n}\nvoid triangulatePoint(Eigen::Matrix<double, 3, 4> &Pose0, Eigen::Matrix<double, 3, 4> &Pose1,\n\t\t\t\t\t\tVector2d &point0, Vector2d &point1, Vector3d &point_3d);\n//\u627e\u5230\u4e24\u5e27\u4e4b\u95f4\u7684\u5171\u89c6\u70b9\nvoid triangulateTwoFrames(int frame0, Eigen::Matrix<double, 3, 4> &Pose0, \n\t\t\t\t\t\t\t\t\t int frame1, Eigen::Matrix<double, 3, 4> &Pose1,\n\t\t\t\t\t\t\t\t\t vector<SFMFeature> &sfm_f);\nbool relativePose(Matrix3d &relative_R, Vector3d &relative_T, int &l,int WINDOW_SIZE,vector<SFMFeature> &sfm_f);\n\nvoid rejectWithF(vector<cv::Point2f> &forw_pts, vector<cv::Point2f> &cur_pts)\n{\n\n        vector<uchar> status;\n        //Calculates a fundamental matrix from the corresponding points in two images.\n        //\u6839\u636e\u4e24\u961f\u70b9\u7b97F,\u4ee5\u53castatus\u518d\u6b21\u7b5b\u9664\u4e00\u4e9b\u70b9\n        cv::findFundamentalMat(forw_pts, cur_pts, cv::FM_RANSAC, 3.0, 0.99, status);\n        int size_a = cur_pts.size();\n        reduceVector(cur_pts, status);\n        reduceVector(forw_pts, status);\n        // ROS_DEBUG(\"FM ransac: %d -> %lu: %f\", size_a, forw_pts.size(), 1.0 * forw_pts.size() / size_a);\n        // ROS_DEBUG(\"FM ransac costs: %fms\", t_f.toc());\n    \n}\n\nvector<pair<Vector3d, Vector3d>> getCorresponding(int frame_count_l, int frame_count_r,vector<SFMFeature> &sfm_f);\n//5\u5e27\u6cd5\u6062\u590drt\uff0c\u662f\u4ece\u524d\u9762\u627e\u5230\u7684\u7279\u5f81\u70b9\nbool solveRelativeRT(const vector<pair<Vector3d, Vector3d>> &corres, Matrix3d &Rotation, Vector3d &Translation)\n{\n    if (corres.size() >= 15)\n    {\n      int ptCount = (int)corres.size();\n      Mat p1(ptCount, 2, CV_32F);\n      Mat p2(ptCount, 2, CV_32F);\n\n      \n\n      // \u628aKeypoint\u8f6c\u6362\u4e3aMat\n      for (int i=0; i<ptCount; i++)\n      {\n\n\t  p1.at<float>(i, 0) = corres[i].first(0);\n\t  p1.at<float>(i, 1) = corres[i].first(1);\n\n\t  p2.at<float>(i, 0) = corres[i].second(0);\n\t  p2.at<float>(i, 1) = corres[i].second(1);\n// \t  cout<<p1.at<float>(i, 0)<<\"----\"<<p1.at<float>(i, 1)<<endl;\n// \t  cout<<p2.at<float>(i, 0)<<\"----\"<<p2.at<float>(i, 1)<<endl;\t  \n      }      \n\n        cv::Mat mask;\n\n        //\u627e\u57fa\u7840\u8d28\u77e9\u9635\n        cv::Mat E = cv::findFundamentalMat(p1, p2, cv::FM_RANSAC, 3., 0.99, mask);\n\n        cv::Mat cameraMatrix =  ( Mat_<double> ( 3,3 ) << 520.9, 0, 325.1, 0, 521.0, 249.7, 0, 0, 1 );\n\n        cv::Mat rot, trans;\n        //\u5224\u65ad\u76f8\u4f4d\u7b26\u5408\u7684\u70b9\n\n        int inlier_cnt = cv::recoverPose(E, p1, p2, cameraMatrix, rot, trans, mask);\n        cout << \"inlier_cnt \" << inlier_cnt << endl;\n\n        Eigen::Matrix3d R;\n        Eigen::Vector3d T;\n        for (int i = 0; i < 3; i++)\n        {   \n            T(i) = trans.at<double>(i, 0);\n            for (int j = 0; j < 3; j++)\n                R(i, j) = rot.at<double>(i, j);\n        }\n\n        Rotation = R.transpose();\n        Translation = -R.transpose() * T;\n        if(inlier_cnt > 12)//\u5982\u679c\u70b9\u5408\u7b26\u8981\u6c42\uff0c\u5c31\u8fd4\u56de\n            return true;\n        else\n            return false;\n    }\n    return false;\n}\n\n\n\nbool solveFrameByPnP(Matrix3d &R_initial, Vector3d &P_initial, int i,vector<SFMFeature> &sfm_f);\n\n\nint WINDOWSIZE=15;\nint main(int argc, char **argv)\n{\n    // if ( argc != 2 )\n    // {\n    //     cout<<\"usage: run_vo parameter_file\"<<endl;\n    //     return 1;\n    // }\n\n    myslam::Config::setParameterFile ( \"../config/default.yaml\" );\n    myslam::VisualOdometry::Ptr vo ( new myslam::VisualOdometry );\n\n    string dataset_dir = myslam::Config::get<string> ( \"dataset_dir\" );\n    cout<<\"dataset: \"<<dataset_dir<<endl;\n    ifstream fin(dataset_dir + \"/associate.txt\");\n\n    if ( !fin )\n    {\n        cout<<\"please generate the associate file called associate.txt!\"<<endl;\n        return 1;\n    }\n\n    vector<string> rgb_files, depth_files;\n    vector<double> rgb_times, depth_times;\n    while ( !fin.eof() )\n    {\n        string rgb_time, rgb_file, depth_time, depth_file;\n        fin>>rgb_time>>rgb_file>>depth_time>>depth_file;\n        rgb_times.push_back ( atof ( rgb_time.c_str() ) );\n        depth_times.push_back ( atof ( depth_time.c_str() ) );\n        rgb_files.push_back ( dataset_dir+\"/\"+rgb_file );\n        depth_files.push_back ( dataset_dir+\"/\"+depth_file );\n\n        if ( fin.good() == false )\n            break;\n    }\n\n\n\n    // visualization\n    cv::viz::Viz3d vis ( \"Visual Odometry\" );\n    cv::viz::WCoordinateSystem world_coor ( 1.0 ), camera_coor ( 0.5 );\n    cv::Point3d cam_pos ( 0, -1.0, -1.0 ), cam_focal_point ( 0,0,0 ), cam_y_dir ( 0,1,0 );\n    cv::Affine3d cam_pose = cv::viz::makeCameraPose ( cam_pos, cam_focal_point, cam_y_dir );\n    vis.setViewerPose ( cam_pose );\n\n    world_coor.setRenderingProperty ( cv::viz::LINE_WIDTH, 2.0 );\n    camera_coor.setRenderingProperty ( cv::viz::LINE_WIDTH, 1.0 );\n    vis.showWidget ( \"World\", world_coor );\n    vis.showWidget ( \"Camera\", camera_coor );\n\n    cout<<\"read total \"<<rgb_files.size() <<\" entries\"<<endl;\n\n\n    Vector3d T[WINDOWSIZE + 1];\n    map<int, Vector3d> sfm_tracked_points;\n\n    \n    vector< cv::Point2f > keypoints;      // \u56e0\u4e3a\u8981\u5220\u9664\u8ddf\u8e2a\u5931\u8d25\u7684\u70b9\uff0c\u4f7f\u7528list\n    vector< SFMFeature > sfm_f;\n    cv::Mat color, depth, last_color;\n   \n    for(int index=0;index<WINDOWSIZE;index++)\n    {\n        color = imread(rgb_files[index], CV_LOAD_IMAGE_COLOR);\n\tcout<<\"read...\"<<endl;\n        if (index == 0 )\n        {\n            // \u5bf9\u7b2c\u4e00\u5e27\u63d0\u53d6FAST\u7279\u5f81\u70b9\n            vector<cv::KeyPoint> kps;\n            cv::Ptr<cv::FastFeatureDetector> detector = cv::FastFeatureDetector::create();\n            detector->detect( color, kps );\n\t    int first_count=0;\n            for ( auto kp:kps )\n\t    {\n                keypoints.push_back( kp.pt );\n\t\tSFMFeature tmpsfm;\n\t\ttmpsfm.state=false;\n\t\ttmpsfm.id=first_count;\n\t\ttmpsfm.observation.push_back(make_pair(index, Eigen::Vector2d{kp.pt.x, kp.pt.y}));\n\t\tfirst_count++;\n\t\tsfm_f.push_back(tmpsfm);\n\t    }\n            last_color = color;\n            continue;\n        }\n        if ( color.data==nullptr)\n            continue;\n        // \u5bf9\u5176\u4ed6\u5e27\u7528LK\u8ddf\u8e2a\u7279\u5f81\u70b9\n        vector<cv::Point2f> next_keypoints; \n        vector<cv::Point2f> prev_keypoints;\n        for ( auto kp:keypoints )\n            prev_keypoints.push_back(kp);\n\n        vector<unsigned char> status;\n        vector<float> error; \n//         chrono::steady_clock::time_point t1 = chrono::steady_clock::now();\n        cv::calcOpticalFlowPyrLK( last_color, color, prev_keypoints, next_keypoints, status, error );\n\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<<\"LK Flow use time\uff1a\"<<time_used.count()<<\" seconds.\"<<endl;\n        // \u628a\u8ddf\u4e22\u7684\u70b9\u5220\u6389\n\n        int keypoint_index = 0;\n        for ( auto kp:next_keypoints )\n\t{\n\t  sfm_f[keypoint_index].observation.push_back(make_pair(index, Eigen::Vector2d{kp.x, kp.y}));\n      ++keypoint_index;\n    }\n        reduceVector(keypoints,status);\n\treduceVector(sfm_f,status);\n\n\n    //Calculates a fundamental matrix from the corresponding points in two images.\n    //\u6839\u636e\u4e24\u961f\u70b9\u7b97F,\u4ee5\u53castatus\u518d\u6b21\u7b5b\u9664\u4e00\u4e9b\u70b9\n    cv::findFundamentalMat(prev_keypoints, next_keypoints, cv::FM_RANSAC, 1.0, 0.99, status);\n    reduceVector(keypoints, status);\n    reduceVector(sfm_f, status);\n\n    cout << \"tracked keypoints: \" << keypoints.size() << endl;\n    if (keypoints.size() == 0)\n    {\n        cout << \"all keypoints are lost.\" << endl;\n        break; \n        }\n        // \u753b\u51fa keypoints\n//         cv::Mat img_show = color.clone();\n//         for ( auto kp:keypoints )\n//             cv::circle(img_show, kp, 10, cv::Scalar(0, 240, 0), 1);\n//         cv::imshow(\"corners\", img_show);\n//         cv::waitKey(0);\n        last_color = color;\n\t\n    }        \n\n\n\n    int frame_num = WINDOWSIZE;\n    // //cout << \"set 0 and \" << l << \" as known \" << endl;\n    // // have relative_r relative_t\n    // // intial two view\n    // //\u786e\u5b9a\u6700\u540e\u4e00\u5e27\u7684\u76f8\u5bf9\u503c\n    // //\u8bbe\u7f6e\u521d\u59cb\u503c\uff0cql\u662f\u786e\u5b9a\u7684\u5e27\u7684\uff0ct\u3010-1\u3011\u5f53\u7136\u662f\u7ed9\u51fa\u8ba1\u7b97\u7684\u90a3\u4e2a\u90e8\u5206\uff0c\u4ee5l\u5e27\u4f5c\u4e3a\u8d77\u70b90\n    int l=0;\n\n    Eigen::Quaterniond q[frame_num];\n    q[l].w() = 1;\n    q[l].x() = 0;\n    q[l].y() = 0;\n    q[l].z() = 0;\n    T[l].setZero();\n    Matrix3d relative_R;\n    Vector3d relative_T;\n\n    if (!relativePose(relative_R, relative_T, l,WINDOWSIZE,sfm_f))\n    {\n        printf(\"Not enough features or parallax; Move device around\");\n        return false;\n    }    \n\n    q[frame_num - 1] = q[l] * Quaterniond(relative_R);\n    T[frame_num - 1] = relative_T;\n    // //cout << \"init q_l \" << q[l].w() << \" \" << q[l].vec().transpose() << endl;\n    // //cout << \"init t_l \" << T[l].transpose() << endl;\n\n    // //rotate to cam frame\n    // //\u4e3a\u5565\u8981\u5b9a\u4e49\u4e24\u4e2a\u90e8\u5206\u7684RT\n    Matrix3d c_Rotation[frame_num];\n    Vector3d c_Translation[frame_num];\n    Quaterniond c_Quat[frame_num];\n    double c_rotation[frame_num][4];\n    double c_translation[frame_num][3];\n    Eigen::Matrix<double, 3, 4> Pose[frame_num]; //\u4f4d\u59ff\u7528\u4e8e\u4e09\u89d2\u5316\n//\u7b2c\u4e00\u5e27\u7684\u503c\n    c_Quat[l] = q[l].inverse();//\u65cb\u8f6c\u662f\u4ec0\u4e48\u610f\u601d\uff1f\uff1f\uff1f\n    c_Rotation[l] = c_Quat[l].toRotationMatrix(); //\u6700\u540e\u4e00\u5e27\u5f53\u7136\u662f\u7b97\u51fa\u6765\u7684\u90a3\u4e2a\n    c_Translation[l] = -1 * (c_Rotation[l] * T[l]);//\u610f\u601d\u662f\u4ee5\u6700\u540e\u4e00\u5e27\u8f7d\u4f53\u7cfb\u5904\u7406\u5417\n    Pose[l].block<3, 3>(0, 0) = c_Rotation[l];\n    Pose[l].block<3, 1>(0, 3) = c_Translation[l];\n//\u6700\u540e\u4e00\u5e27\u7684\u503c\n    c_Quat[frame_num - 1] = q[frame_num - 1].inverse();\n    c_Rotation[frame_num - 1] = c_Quat[frame_num - 1].toRotationMatrix();\n    c_Translation[frame_num - 1] = -1 * (c_Rotation[frame_num - 1] * T[frame_num - 1]);\n    Pose[frame_num - 1].block<3, 3>(0, 0) = c_Rotation[frame_num - 1];\n    Pose[frame_num - 1].block<3, 1>(0, 3) = c_Translation[frame_num - 1];\n    \n\n    for (int i = l; i < WINDOWSIZE-1; i++)\n    {\n        // cout<<\"****** loop \"<<i<<\" ******\"<<rgb_files[i] <<endl;\n        // Mat color = cv::imread ( rgb_files[i] );\n        // solve pnp\u8df3\u8fc7\u524d\u9762\u90a3\u4e9b\u4e0d\u7528\u7684\u5e27\n\tif (i > l)\n        {\n            //\u5c31\u662f\u7528\u4e0a\u4e00\u5e27\u7684\u4f5c\u4e3a\u521d\u503c\u53bb\u6c42\u89e3pnp\n            Matrix3d R_initial = c_Rotation[i - 1];\n            Vector3d P_initial = c_Translation[i - 1];\n            if (!solveFrameByPnP(R_initial, P_initial, i, sfm_f))\n                return false;\n            c_Rotation[i] = R_initial;\n            c_Translation[i] = P_initial;\n            c_Quat[i] = c_Rotation[i];\n            Pose[i].block<3, 3>(0, 0) = c_Rotation[i];\n            Pose[i].block<3, 1>(0, 3) = c_Translation[i];\n        }\n\n    //     // triangulate point based on the solve pnp result\n    //     //\u524d\u9762\u6761\u4ef6\u4e0d\u6ee1\u8db3\uff0c\u5c31\u662f\u9996\u5148\u8fdb\u6765\u5f53i=l\u65f6\u7b2ci\u5e27\u548c\u6700\u540e\u4e00\u5e27\u4e4b\u95f4\u7684\u4e09\u89d2\u5316\uff0c\u5f97\u5230\u4e86\u8fd9\u4e24\u5e27\u4e4b\u95f4\u7684\u5171\u89c6\u70b9\n    //     //\u7136\u540e\u91cd\u590d\u8fdb\u884c\u4ecei+1\u5e27\u5230\u6700\u540e\u4e00\u5e27\u4e4b\u95f4\u7684\u4e09\u89d2\u5316\uff0csfm\u91cc\u5bf9\u5e94\u7684\u90e8\u5206\u7684\u4f4d\u59ff\n    //     //\u7ecf\u8fc7\u8fd9\u4e00\u6b65\uff0c\u53ef\u4ee5\u5728\u4e00\u5f00\u59cb\u5b9a\u4e49\u7684\u90a3\u4e9b\u5728l\u548c\u6700\u540e\u4e00\u5e27\u4e4b\u95f4\u7684\u5171\u89c6\u70b9\u4e0a\u52a0\u4e0a\u6df1\u5ea6\n        triangulateTwoFrames(i, Pose[i], frame_num - 1, Pose[frame_num - 1], sfm_f);\n      \n    }\t\n\n    for (int i = l + 1; i < frame_num-1; i++)\n    {  \n        triangulateTwoFrames(l, Pose[l], i, Pose[i], sfm_f);\n    }\n    //4: solve pnp l-1; triangulate l-1 ----- l\n    //             l-2              l-2 ----- l\n    //\u4e09\u89d2\u5316\u6240\u6709\u7a97\u53e3\u540e\u90e8\u5206\u7684\u5e27\u548c\u5730l\u5e27\n    //l\u5e27\u5df2\u7ecf\u88ab\u8ba4\u5b9a\u4e3a0\u4e86\uff0c\u90a3\u4e48\u5176\u4ed6\u5e27\u81ea\u7136\u5c31\u662f\u548c\u4ed6\u786e\u5b9a\n\n    for (int i = l - 1; i >= 0; i--)\n    {\n        //solve pnp\n        Matrix3d R_initial = c_Rotation[i + 1];\n        Vector3d P_initial = c_Translation[i + 1];\n        if (!solveFrameByPnP(R_initial, P_initial, i, sfm_f))\n            return false;\n        c_Rotation[i] = R_initial;\n        c_Translation[i] = P_initial;\n        c_Quat[i] = c_Rotation[i];\n        Pose[i].block<3, 3>(0, 0) = c_Rotation[i];\n        Pose[i].block<3, 1>(0, 3) = c_Translation[i];\n        //triangulate\n        triangulateTwoFrames(i, Pose[i], l, Pose[l], sfm_f);\n    }\n    //5: triangulate all other points\n    for (int j = 0; j < sfm_f.size(); j++)\n    {\n        if (sfm_f[j].state == true)\n            continue;\n        if ((int)sfm_f[j].observation.size() >= 2)\n        {\n            Vector2d point0, point1;\n            int frame_0 = sfm_f[j].observation[0].first;\n            point0 = sfm_f[j].observation[0].second;\n            int frame_1 = sfm_f[j].observation.back().first;\n            point1 = sfm_f[j].observation.back().second;\n            Vector3d point_3d;\n            triangulatePoint(Pose[frame_0], Pose[frame_1], point0, point1, point_3d);\n            sfm_f[j].state = true;\n            sfm_f[j].position[0] = point_3d(0);\n            sfm_f[j].position[1] = point_3d(1);\n            sfm_f[j].position[2] = point_3d(2);\n            //cout << \"trangulated : \" << frame_0 << \" \" << frame_1 << \"  3d point : \"  << j << \"  \" << point_3d.transpose() << endl;\n        }\n\n\n    }\n    //full BA\n    //full BA\n    //\u5168\u4f18\u5316\u65b9\u5f0f\n    ceres::Problem problem;\n    ceres::LocalParameterization *local_parameterization = new ceres::QuaternionParameterization();\n    //cout << \" begin full BA \" << endl;\n    for (int i = 0; i < frame_num; i++)\n    {\n        //double array for ceres\n        c_translation[i][0] = c_Translation[i].x();\n        c_translation[i][1] = c_Translation[i].y();\n        c_translation[i][2] = c_Translation[i].z();\n        c_rotation[i][0] = c_Quat[i].w();\n        c_rotation[i][1] = c_Quat[i].x();\n        c_rotation[i][2] = c_Quat[i].y();\n        c_rotation[i][3] = c_Quat[i].z();\n        problem.AddParameterBlock(c_rotation[i], 4, local_parameterization);\n        problem.AddParameterBlock(c_translation[i], 3);\n        if (i == l)\n        {\n            problem.SetParameterBlockConstant(c_rotation[i]);\n        }\n        if (i == l || i == frame_num - 1)\n        {\n            problem.SetParameterBlockConstant(c_translation[i]);\n        }\n    }\n\n    for (int i = 0; i < sfm_f.size(); i++)\n    {\n        if (sfm_f[i].state != true)\n            continue;\n        for (int j = 0; j < int(sfm_f[i].observation.size()); j++)\n        {\n            int l = sfm_f[i].observation[j].first;\n            ceres::CostFunction *cost_function = ReprojectionError3D::Create(\n                sfm_f[i].observation[j].second.x(),\n                sfm_f[i].observation[j].second.y());\n\n            problem.AddResidualBlock(cost_function, NULL, c_rotation[l], c_translation[l],\n                                     sfm_f[i].position);\n        }\n    }\n    ceres::Solver::Options options;\n    options.linear_solver_type = ceres::DENSE_SCHUR;\n    //options.minimizer_progress_to_stdout = true;\n    options.max_solver_time_in_seconds = 0.2;\n    ceres::Solver::Summary summary;\n    ceres::Solve(options, &problem, &summary);\n    //std::cout << summary.BriefReport() << \"\\n\";\n    if (summary.termination_type == ceres::CONVERGENCE || summary.final_cost < 5e-03)\n    {\n        cout << \"vision only BA converge\" << endl;\n    }\n    else\n    {\n        cout << \"vision only BA not converge \" << endl;\n        // return false;\n    }\n    for (int i = 0; i < frame_num; i++)\n    {\n        q[i].w() = c_rotation[i][0];\n        q[i].x() = c_rotation[i][1];\n        q[i].y() = c_rotation[i][2];\n        q[i].z() = c_rotation[i][3];\n        q[i] = q[i].inverse();\n        // cout << \"final  q\" << \" i \" << i <<\"  \" <<q[i].w() << \"  \" << q[i].vec().transpose() << endl;\n        cout<<\"final q  \"<<endl;\n        cout<<q[i].toRotationMatrix()<<endl;\n\n        T[i] = -1 * (q[i] * Vector3d(c_translation[i][0], c_translation[i][1], c_translation[i][2]));\n        cout << \"final t  \"<<endl;\n        cout << T[i](0) << \"  \" << T[i](1) << \"  \" << T[i](2) << endl;\n    }\n\n    for (int i = 0; i < (int)sfm_f.size(); i++)\n    {\n        if (sfm_f[i].state)\n            sfm_tracked_points[sfm_f[i].id] = Vector3d(sfm_f[i].position[0], sfm_f[i].position[1], sfm_f[i].position[2]);\n    }\n    // return true;\n\n\n    for(int i=0;i<frame_num;i++)\n    {\n      \n    //visual\n      Matrix3d newtmp=q[i].toRotationMatrix();\n      cv::Affine3d M(\n          cv::Affine3d::Mat3(\n              newtmp(0, 0), newtmp(0, 1), newtmp(0, 2),\n              newtmp(1, 0), newtmp(1, 1), newtmp(1, 2),\n              newtmp(2, 0), newtmp(2, 1), newtmp(2, 2)),\n          cv::Affine3d::Vec3(\n              T[i](0), T[i](1), T[i](2)));\n\n      cv::Mat img_show = imread(rgb_files[i], CV_LOAD_IMAGE_COLOR);\n      vector<KeyPoint> kp;\n      for (auto sfm : sfm_f)\n      {\n          for (unsigned sfmindex = 0; sfmindex < sfm.observation.size(); sfmindex++)\n          {\n              if (sfm.observation[sfmindex].first == i)\n              {\n                  cv::circle(img_show, Point(sfm.observation[sfmindex].second(0), sfm.observation[sfmindex].second(1)), 10, cv::Scalar(0, 240, 0), 1);\n              }\n          }\n\t    }\n        // cv::imshow(\"corners\", img_show);     \n        cv::imshow ( \"image\", img_show );\n     \n        cv::waitKey ( 0);\n        vis.setWidgetPose ( \"Camera\", M );\n        vis.spinOnce ( 10, false );\n        cout<<endl;\n    }\n\n    return 0;\n}\nvoid triangulatePoint(Eigen::Matrix<double, 3, 4> &Pose0, Eigen::Matrix<double, 3, 4> &Pose1,\n\t\t\t\t\t\tVector2d &point0, Vector2d &point1, Vector3d &point_3d)\n{\n\tMatrix4d design_matrix = Matrix4d::Zero();\n\tdesign_matrix.row(0) = point0[0] * Pose0.row(2) - Pose0.row(0);\n\tdesign_matrix.row(1) = point0[1] * Pose0.row(2) - Pose0.row(1);\n\tdesign_matrix.row(2) = point1[0] * Pose1.row(2) - Pose1.row(0);\n\tdesign_matrix.row(3) = point1[1] * Pose1.row(2) - Pose1.row(1);\n\tVector4d triangulated_point;\n\ttriangulated_point =\n\t\t      design_matrix.jacobiSvd(Eigen::ComputeFullV).matrixV().rightCols<1>();\n\tpoint_3d(0) = triangulated_point(0) / triangulated_point(3);\n\tpoint_3d(1) = triangulated_point(1) / triangulated_point(3);\n\tpoint_3d(2) = triangulated_point(2) / triangulated_point(3);\n}\n//\u627e\u5230\u4e24\u5e27\u4e4b\u95f4\u7684\u5171\u89c6\u70b9\nvoid triangulateTwoFrames(int frame0, Eigen::Matrix<double, 3, 4> &Pose0, \n\t\t\t\t\t\t\t\t\t int frame1, Eigen::Matrix<double, 3, 4> &Pose1,\n\t\t\t\t\t\t\t\t\t vector<SFMFeature> &sfm_f)\n{\n\tassert(frame0 != frame1);\n\tfor (int j = 0; j < sfm_f.size(); j++)\n\t{\n\t\tif (sfm_f[j].state == true)\n\t\t\tcontinue;\n\t\tbool has_0 = false, has_1 = false;\n\t\tVector2d point0;\n\t\tVector2d point1;\n\t\tfor (int k = 0; k < (int)sfm_f[j].observation.size(); k++)\n\t\t{\n\t\t\tif (sfm_f[j].observation[k].first == frame0)\n\t\t\t{\n\t\t\t\tpoint0 = sfm_f[j].observation[k].second;\n\t\t\t\thas_0 = true;\n\t\t\t}\n\t\t\tif (sfm_f[j].observation[k].first == frame1)\n\t\t\t{\n\t\t\t\tpoint1 = sfm_f[j].observation[k].second;\n\t\t\t\thas_1 = true;\n\t\t\t}\n\t\t}\n\t\t//\u5728\u6240\u6709\u7684\u70b9\u4e2d\uff0c\u8fd9\u4e24\u5e27\u4e4b\u95f4\u5b58\u5728\u5171\u89c6\u70b9\n\t\tif (has_0 && has_1)\n\t\t{\n\t\t\tVector3d point_3d;\n\t\t\ttriangulatePoint(Pose0, Pose1, point0, point1, point_3d);\n\t\t\tsfm_f[j].state = true;\n\t\t\tsfm_f[j].position[0] = point_3d(0);\n\t\t\tsfm_f[j].position[1] = point_3d(1);\n\t\t\tsfm_f[j].position[2] = point_3d(2);\n\t\t\t//cout << \"trangulated : \" << frame1 << \"  3d point : \"  << j << \"  \" << point_3d.transpose() << endl;\n\t\t}\t\t\t\t\t\t\t  \n\t}\n}\n//\u770b\u8d77\u6765\u521d\u59cb\u5316\u7684\u65f6\u5019\u8fd9\u91cc\u4e5f\u6ca1\u7528k\uff0c\uff54\nbool solveFrameByPnP(Matrix3d &R_initial, Vector3d &P_initial, int i,vector<SFMFeature> &sfm_f)\n{\n\tvector<cv::Point2f> pts_2_vector;\n\tvector<cv::Point3f> pts_3_vector;\n\tfor (int j = 0; j < sfm_f.size(); j++)\n\t{\n\t\tif (sfm_f[j].state != true)\n\t\t\tcontinue;\n\t\tVector2d point2d;\n\t\tfor (int k = 0; k < (int)sfm_f[j].observation.size(); k++)\n\t\t{\n\t\t\tif (sfm_f[j].observation[k].first == i)\n\t\t\t{\n\t\t\t\tVector2d img_pts = sfm_f[j].observation[k].second;\n\t\t\t\tcv::Point2f pts_2(img_pts(0), img_pts(1));\n\t\t\t\tpts_2_vector.push_back(pts_2);\n\t\t\t\tcv::Point3f pts_3(sfm_f[j].position[0], sfm_f[j].position[1], sfm_f[j].position[2]);\n\t\t\t\tpts_3_vector.push_back(pts_3);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tif (int(pts_2_vector.size()) < 15)\n\t{\n\t\tprintf(\"unstable features tracking, please slowly move you device!\\n\");\n\t\tif (int(pts_2_vector.size()) < 10)\n\t\t\treturn false;\n\t}\n\tcv::Mat r, rvec, t, D, tmp_r;\n\tcv::eigen2cv(R_initial, tmp_r);\n\n\n// int\u00a0\u00a0cvRodrigues2cvRodr (\u00a0const\u00a0CvMat*\u00a0src,\u00a0CvMat*\u00a0dst,\u00a0CvMat*\u00a0jacobian=0\u00a0);\n// \u00a0 \u00a0 \u00a0src\u4e3a\u8f93\u5165\u7684\u65cb\u8f6c\u5411\u91cf\uff083x1\u6216\u80051x3\uff09\u6216\u8005\u65cb\u8f6c\u77e9\u9635\uff083x3\uff09\u3002\n// \u00a0 \u00a0 \u00a0dst\u4e3a\u8f93\u51fa\u7684\u65cb\u8f6c\u77e9\u9635\uff083x3\uff09\u6216\u8005\u65cb\u8f6c\u5411\u91cf\uff083x1\u6216\u80051x3\uff09\u3002\n// \u00a0 \u00a0 \u00a0jacobian\u4e3a\u53ef\u9009\u7684\u8f93\u51fa\u96c5\u53ef\u6bd4\u77e9\u9635\uff083x9\u6216\u80059x3\uff09\uff0c\u662f\u8f93\u5165\u4e0e\u8f93\u51fa\u6570\u7ec4\u7684\u504f\u5bfc\u6570\u3002\n\n\n\n\tcv::Rodrigues(tmp_r, rvec);\n\tcv::eigen2cv(P_initial, t);\n    cv::Mat K = (Mat_<double>(3, 3) << 520.9, 0, 325.1, 0, 521.0, 249.7, 0, 0, 1);\n    bool pnp_succ;\n    //K\u5728\u8fd9\u91cc\u5185\u53c2\u9ed8\u8ba4\u662fI\u90fd\u53ef\u4ee5\u5417\uff1f\uff1f\n\tpnp_succ = cv::solvePnP(pts_3_vector, pts_2_vector, K, D, rvec, t, 1);\n\tif(!pnp_succ)\n\t{\n\t\treturn false;\n\t}\n\tcv::Rodrigues(rvec, r);\n\t//cout << \"r \" << endl << r << endl;\n\tMatrixXd R_pnp;\n\tcv::cv2eigen(r, R_pnp);\n\tMatrixXd T_pnp;\n\tcv::cv2eigen(t, T_pnp);\n\tR_initial = R_pnp;\n\tP_initial = T_pnp;\n\treturn true;\n\n}\n\n\nPoint2f pixel2cam(const Point2d &p, const Mat &K)\n{\n    return Point2f(\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//\u83b7\u5f97corres\u7126\u70b9\nvector<pair<Vector3d, Vector3d>> getCorresponding(int frame_count_l, int frame_count_r,vector<SFMFeature> &sfm_f)\n{\n    vector<pair<Vector3d, Vector3d>> corres;\n    for (auto &it : sfm_f)\n    {\n\n            Vector3d a , b ;\n\t    for(auto &frameId:it.observation)\t    \n\t    {\n\t      if(frameId.first==frame_count_l)\n\t      {\n\t\ta=Vector3d( frameId.second(0),frameId.second(1),0);\n\t      }\n\t      if(frameId.first==frame_count_r)\n\t      {\n\t\tb=Vector3d( frameId.second(0),frameId.second(1),0);\n\t      }\n\t    }\n            \n            corres.push_back(make_pair(a, b));\n        \n    }\n    return corres;\n}\n\nbool relativePose(Matrix3d &relative_R, Vector3d &relative_T, int &l,int WINDOW_SIZE,vector<SFMFeature> &sfm_f)\n{\n    //corres\u8003\u5bdf\u89c6\u5dee\n    // find previous frame which contians enough correspondance and parallex with newest frame\n    for (int i = 0; i < WINDOW_SIZE; i++)\n    {\n        vector<pair<Vector3d, Vector3d>> corres;\n        corres = getCorresponding(i, WINDOW_SIZE-1,sfm_f);\n        //\u5224\u65ad\u7a97\u53e3\u5185\u6240\u6709\u7684\u5e27\u548c\u6700\u540e\u7684\u5e27\u4e4b\u95f4\u7684\u4ea4\u70b9\u4e2a\u6570\n        //\u5224\u65ad\u4ea4\u70b9\u4e2a\u6570\uff0c\u8981\u6c42\u5927\u4e8e20\u4e2a\n\t\n        if (corres.size() > 20)\n        {\n            double sum_parallax = 0;\n            double average_parallax;\n            for (int j = 0; j < int(corres.size()); j++)\n            {\n                Vector2d pts_0(corres[j].first(0), corres[j].first(1));\n                Vector2d pts_1(corres[j].second(0), corres[j].second(1));\n                double parallax = (pts_0 - pts_1).norm();\n                sum_parallax = sum_parallax + parallax;\n\n            }\n            average_parallax = 1.0 * sum_parallax / int(corres.size());\n            //\u6ee1\u8db3\u7279\u5f81\u70b9\u4e4b\u95f4\u7684\u5e73\u5747\u8ddd\u79bb\u8981\u7b26\u5408\u4e00\u4e2a\u8981\u6c42\uff0c\u7136\u540e\u4f7f\u75285\u70b9\u6cd5\u6c42\u89e3RT\n            //\u8fd9\u91cc\u6c42\u51fa\u7684\u662f\u57fa\u4e8e\u7b2ci\u5e27\u7684\u4f4d\u59ff\n// \t    cout<<average_parallax<<endl;\n            if(average_parallax * 460 > 30 && solveRelativeRT(corres, relative_R, relative_T))\n            {\n\t      cout<<corres.size()<<endl;\n                l = i;\n//                 ROS_DEBUG(\"average_parallax %f choose l %d and newest frame to triangulate the whole structure\", average_parallax * 460, l);\n                return true;\n            }\n        }\n        \t\n    }\n    return false;\n}\n#endif", "meta": {"hexsha": "10d958af33955751b41f6b424edb013f29d723e1", "size": 24111, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/sfmtest.cpp", "max_stars_repo_name": "AAAAaron/MONOVisual", "max_stars_repo_head_hexsha": "732ad95dfe740a10b76169bb0c5e2f39f17efc39", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-04-03T15:41:08.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-12T10:38:52.000Z", "max_issues_repo_path": "test/sfmtest.cpp", "max_issues_repo_name": "AAAAaron/MONOVisual", "max_issues_repo_head_hexsha": "732ad95dfe740a10b76169bb0c5e2f39f17efc39", "max_issues_repo_licenses": ["MIT"], "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/sfmtest.cpp", "max_forks_repo_name": "AAAAaron/MONOVisual", "max_forks_repo_head_hexsha": "732ad95dfe740a10b76169bb0c5e2f39f17efc39", "max_forks_repo_licenses": ["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.4508748318, "max_line_length": 150, "alphanum_fraction": 0.5788644187, "num_tokens": 8007, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.6297746074044135, "lm_q1q2_score": 0.4945674032199049}}
{"text": "// Boost.Geometry\r\n\r\n// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.\r\n\r\n// This file was modified by Oracle on 2014.\r\n// Modifications copyright (c) 2014 Oracle and/or its affiliates.\r\n\r\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef BOOST_GEOMETRY_STRATEGIES_GEOGRAPHIC_VINCENTY_HPP\r\n#define BOOST_GEOMETRY_STRATEGIES_GEOGRAPHIC_VINCENTY_HPP\r\n\r\n\r\n#include <boost/geometry/core/coordinate_type.hpp>\r\n#include <boost/geometry/core/radian_access.hpp>\r\n\r\n#include <boost/geometry/strategies/distance.hpp>\r\n\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/algorithms/detail/vincenty_inverse.hpp>\r\n\r\nnamespace boost { namespace geometry\r\n{\r\n\r\nnamespace strategy { namespace distance\r\n{\r\n\r\n/*!\r\n\\brief Distance calculation formulae on latlong coordinates, after Vincenty, 1975\r\n\\ingroup distance\r\n\\tparam Spheroid The reference spheroid model\r\n\\tparam CalculationType \\tparam_calculation\r\n\\author See\r\n    - http://www.ngs.noaa.gov/PUBS_LIB/inverse.pdf\r\n    - http://www.icsm.gov.au/gda/gdav2.3.pdf\r\n\\author Adapted from various implementations to get it close to the original document\r\n    - http://www.movable-type.co.uk/scripts/LatLongVincenty.html\r\n    - http://exogen.case.edu/projects/geopy/source/geopy.distance.html\r\n    - http://futureboy.homeip.net/fsp/colorize.fsp?fileName=navigation.frink\r\n\r\n*/\r\ntemplate\r\n<\r\n    typename Spheroid,\r\n    typename CalculationType = void\r\n>\r\nclass vincenty\r\n{\r\npublic :\r\n    template <typename Point1, typename Point2>\r\n    struct calculation_type\r\n        : promote_floating_point\r\n          <\r\n              typename select_calculation_type\r\n                  <\r\n                      Point1,\r\n                      Point2,\r\n                      CalculationType\r\n                  >::type\r\n          >\r\n    {};\r\n\r\n    typedef Spheroid model_type;\r\n\r\n    inline vincenty()\r\n        : m_spheroid()\r\n    {}\r\n\r\n    explicit inline vincenty(Spheroid const& spheroid)\r\n        : m_spheroid(spheroid)\r\n    {}\r\n\r\n    template <typename Point1, typename Point2>\r\n    inline typename calculation_type<Point1, Point2>::type\r\n    apply(Point1 const& point1, Point2 const& point2) const\r\n    {\r\n        return geometry::detail::vincenty_inverse\r\n                <\r\n                    typename calculation_type<Point1, Point2>::type\r\n                >(get_as_radian<0>(point1),\r\n                  get_as_radian<1>(point1),\r\n                  get_as_radian<0>(point2),\r\n                  get_as_radian<1>(point2),\r\n                  m_spheroid).distance();\r\n    }\r\n\r\n    inline Spheroid const& model() const\r\n    {\r\n        return m_spheroid;\r\n    }\r\n\r\nprivate :\r\n    Spheroid m_spheroid;\r\n};\r\n\r\n#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\r\nnamespace services\r\n{\r\n\r\ntemplate <typename Spheroid, typename CalculationType>\r\nstruct tag<vincenty<Spheroid, CalculationType> >\r\n{\r\n    typedef strategy_tag_distance_point_point type;\r\n};\r\n\r\n\r\ntemplate <typename Spheroid, typename CalculationType, typename P1, typename P2>\r\nstruct return_type<vincenty<Spheroid, CalculationType>, P1, P2>\r\n    : vincenty<Spheroid, CalculationType>::template calculation_type<P1, P2>\r\n{};\r\n\r\n\r\ntemplate <typename Spheroid, typename CalculationType>\r\nstruct comparable_type<vincenty<Spheroid, CalculationType> >\r\n{\r\n    typedef vincenty<Spheroid, CalculationType> type;\r\n};\r\n\r\n\r\ntemplate <typename Spheroid, typename CalculationType>\r\nstruct get_comparable<vincenty<Spheroid, CalculationType> >\r\n{\r\n    static inline vincenty<Spheroid, CalculationType> apply(vincenty<Spheroid, CalculationType> const& input)\r\n    {\r\n        return input;\r\n    }\r\n};\r\n\r\ntemplate <typename Spheroid, typename CalculationType, typename P1, typename P2>\r\nstruct result_from_distance<vincenty<Spheroid, CalculationType>, P1, P2 >\r\n{\r\n    template <typename T>\r\n    static inline typename return_type<vincenty<Spheroid, CalculationType>, P1, P2>::type\r\n        apply(vincenty<Spheroid, CalculationType> const& , T const& value)\r\n    {\r\n        return value;\r\n    }\r\n};\r\n\r\n\r\n} // namespace services\r\n#endif // DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\r\n\r\n\r\n// We might add a vincenty-like strategy also for point-segment distance, but to calculate the projected point is not trivial\r\n\r\n\r\n\r\n}} // namespace strategy::distance\r\n\r\n\r\n}} // namespace boost::geometry\r\n\r\n\r\n#endif // BOOST_GEOMETRY_STRATEGIES_GEOGRAPHIC_VINCENTY_HPP\r\n", "meta": {"hexsha": "40be94170d10768d21bb303bf607ebda3f12646b", "size": 4650, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/geometry/strategies/geographic/distance_vincenty.hpp", "max_stars_repo_name": "Abce/boost", "max_stars_repo_head_hexsha": "2d7491a27211aa5defab113f8e2d657c3d85ca93", "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/geographic/distance_vincenty.hpp", "max_issues_repo_name": "Abce/boost", "max_issues_repo_head_hexsha": "2d7491a27211aa5defab113f8e2d657c3d85ca93", "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/geographic/distance_vincenty.hpp", "max_forks_repo_name": "Abce/boost", "max_forks_repo_head_hexsha": "2d7491a27211aa5defab113f8e2d657c3d85ca93", "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.7037037037, "max_line_length": 126, "alphanum_fraction": 0.6888172043, "num_tokens": 1093, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384736, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.49456739689112067}}
{"text": "/*!  @author Michael Brand\n*    @Excercise 10 - final\n*    @date 26.07.2017\n*\n*   Algorithm to find Steiner tree on a graph where primes count as termainals.\n*\n*   I decided to leave all code in one file since its mainly consistent of two bigger algorithms\n*   1. Dijkstra_mod\n*   2. Analyzing Dijkstra output in main-function\n*   I don't think it gets to complicated reading it from top to bottom.\n*\n*   Parallel computing \n*   Take #n random source nodes from parameter input and start the heurisitic parallely from these sources\n*/\n\n\n#include <iostream>\n#include <fstream>\n#include <stdexcept>\n#include <cstdio>\n#include <ctime>\n#include <chrono>\n#include <string>\n#include <vector>\n#include <climits>\n#include <utility>                          // for std::pair\n#include <random>\n\n#include <boost/graph/adjacency_list.hpp>\n\n#ifdef _OPENMP\n#include <omp.h>\n#endif\n\nusing namespace std;\n\nusing vertex_ = int;\nusing weight_ = int;\n\n/**Edge\n * pair of ints containing the weight and\n * the vertex pointed to. This is useful\n * for the adjacency list\n */\nusing Edge = pair<vertex_, weight_>;\n\n/**Graph\n * An adjacency list representing the graph.\n * graph[i] returns a list with Edge elements.\n *\n */\nusing Graph = vector< vector<Edge> >;\n\n\n/**struct pq_compare\n * compare structure for edges\n * allows me to compare two edges in a graph\n * this way I can sort edges for any vertex under consideration of their weight\n */   \nstruct pq_compare {\n    bool operator() (const Edge i, const Edge j) const{\n    return (i.second <= j.second); }\n};\n\n/*! \\fn bool isPrime(int number)\n    \\brief checks if number is a prime.\n    \\param number number to be checked.\n*/\nbool isPrime(int number){\n    if(number < 2) return false;\n    if(number == 2) return true;\n    if(number % 2 == 0) return false;\n    for(int i=3; (i*i)<=number; i+=2){\n        if(number % i == 0 ) return false;\n    }\n    return true;\n\n}\n\n/*! \\fn std::vector<int> getRequiredPrimes(int numV)\n *  \\brief lists all primes <= numV in a vector.\n *  \\param numV number to be checked.\n*/\nstd::vector<int> getRequiredPrimes(int numV){\n  std::vector<int> primes;\n  for(int i=2; i<=numV; i++){\n    if(isPrime(i)){\n      primes.push_back(i);\n    } \n  }\n  return primes;\n}\n\n/*! \\fn bool edgeInSteinerAlEx(Graph &stGph, vertex_ u, vertex_ v){\n*   \\brief Checks if Edge (u,v) already exists in SteinerGraph\n*\t  \\param stGph Steiner Tree Graph that is checked for existing edge\n*   \\param u source-vertex\n*   \\param v dest-vertex\n*/\nbool edgeInSteinerAlEx(Graph &stGph, vertex_ u, vertex_ v){\n\tfor(vector<Edge>::const_iterator ni = stGph[u].begin(); ni != stGph[u].end(); ni++){\n\t\tif(ni->first==v)\n\t\t\treturn true;\n\t}\n\treturn false;\n}\n/*! \\fn std::vector<vertex_> dijkstra_mod(const Graph &graph, vertex_ root, vector<int> &remPrimes)\n*   \\brief modified dijkstra algorithm used for steiner tree problem\n*   \\param &graph the graph we are working on.\n*   \\param &steinerGraph an empty graph of size(graph) that will be used to build steinerGraph\n*   \\param root root-vertex\n*   \\return objective Value of SteinerTree\n*/\nint dijkstra_mod(const Graph &graph, Graph &steinerGraph, vertex_ root) {\n  int wghtLocTree = 0; /*!< return value */\n  std::vector<int> remPrimes = getRequiredPrimes(graph.size());\n  std::vector<weight_> dist(graph.size(), INT_MAX);\n  /* A set helps insertion and insert/erase/find operations in logarithmic time.\n   * This set maintains Edge(distance,vertex number) sorted on basis of distance\n   */\n  set< Edge , pq_compare> pq;\n  set< Edge , pq_compare > ::iterator it;\n\n  vector<vertex_> pre(graph.size(), (-1)); /*!< vevtor of predecessors */\n  int u,v,wt;\n\n  dist[root] = 0;\n  pq.insert(Edge(root,0));\n  while(pq.size() != 0){\n  \tif(!(remPrimes.size()>0)) break;\n    bool pFound = false;\n    it = pq.begin();\n    u = it->first;\n    pq.erase(it);\n    if((u != root) && (isPrime(u+1))){\n      for(unsigned int chk=0; chk<remPrimes.size(); chk++){\n        if((remPrimes[chk])==(u+1)){\n          //NEW PRIME FOUND\n          pFound = true;\n          //delete u from remainingPrimes\n          remPrimes.erase(remPrimes.begin()+chk);\n          pq.insert(Edge(u,0));\n          dist[u]=0;\n          //Add Path to u to SteinerTree Structure\n          int lV = u;\n          do{\n            int preV = pre[lV];\n            for(unsigned int eIndx = 0; eIndx < graph[lV].size(); eIndx++){\n              if(graph[lV][eIndx].first==preV){\n              \tif(!(edgeInSteinerAlEx(steinerGraph, lV,preV))){\n            \t\t\tsteinerGraph[lV].push_back(Edge(preV, graph[lV][eIndx].second));\n\t                steinerGraph[preV].push_back(Edge(lV, graph[lV][eIndx].second));\n\t                wghtLocTree += graph[lV][eIndx].second;\n\t                pq.insert(Edge(preV,0));\n            \t\t}\n                else{\n                  //abort inserting edges since they are all part of graph\n                  break;\n                }\n              }\n            }\n\t          lV = pre[lV];\n          }while(dist[lV] != 0);\n          break;\n        }\n      }\n    }\n    if(pFound){\n      continue;\n    } \n    for(vector<Edge>::const_iterator ni = graph[u].begin(); ni != graph[u].end(); ni++){\n      v  = ni->first;\n      wt = ni->second;\n      if(dist[v] > dist[u] + wt){\n        pre[v] = u;\n        if(dist[v] != INT_MAX){\n        \tpq.erase(Edge(v,dist[v]));\n        }\n        dist[v] = dist[u] + wt;\n        pq.insert(Edge(v,dist[v]));\n      }\n    \n    }\n  }\n  return wghtLocTree;\n}\n\n/*! \\fn int validateStGraph(&gphToChk)\n*   \\brief tests if gphToChk is connected and inherits all primes\n*   \\param &grphToChk minimal SteinerTree found\n*   \\return 1 if successful, 0 if unsuccessful\n*/\nint validateStGraph(Graph &gphToChk){\n\n\tstd::vector<int> remPrimes = getRequiredPrimes(gphToChk.size());\n\tint totPrimes = remPrimes.size();\n\tint stTreePrimeCount = 0;\n\n\tbool visited[gphToChk.size()];\n\tfor(int i=0; i<gphToChk.size(); i++)\n\t\tvisited[i]=false;\n\t\n  if(!(gphToChk[1].empty())){\n\t\tset< Edge , pq_compare> pq;\n\t\tset< Edge , pq_compare > ::iterator it;\n\t\tint u,v,wt;\n\t\tpq.insert(Edge(1,0));\n\t\twhile(pq.size() != 0){\n\t    it = pq.begin();\n\t\t  u = it->first;\n\t\t  pq.erase(it);\n\t\t  if(visited[u]){\n\t\t  \treturn 0;\n\t\t  } \n\t\t\tvisited[u] = true;\n\t\t\tfor(vector<Edge>::const_iterator ni = gphToChk[u].begin(); ni != gphToChk[u].end(); ni++){\n\t\t\t\tv  = ni->first;\n\t     \twt = ni->second;\n\t     \tpq.insert(Edge(v,wt));\n\t     \t//Delete \u1e55arrallel edge from minSteinerGraph\n\t     \tfor(int k=0; k<gphToChk[v].size(); k++){\n\t     \t\tif(gphToChk[v][k].first == u){\n\t     \t\t\tgphToChk[v].erase(gphToChk[v].begin()+k);\n\t     \t\t}\n\t     \t}\n\t\t\t}\n    }\n\n    for(int j=1; j<gphToChk.size(); j++){\n    \tif(isPrime(j-1)){\n    \t\tif(!(gphToChk[j-1].empty()))\n    \t\t\tstTreePrimeCount++;\n    \t}\n    }\n\n    if(stTreePrimeCount = totPrimes){\n    \treturn 1;\n    }\n    else{\n    \treturn 0;\n    }\n  }\n  else{\n\t\treturn 0;\n\t}\n}\n\n/*!\n*\n*\t\tINPUT n_root_nodes gives an int-number that defines the number of chosen terminals\n*/\nint main (int argc, char* argv[]) {\n  /**\n  * start timers for cpu and wall time\n  */\n  clock_t cpu0 = clock();\n  bool output = false;\n\n  /*\n  *   Check input arguments\n  */\n  if( argc < 3){\n      fprintf(stderr, \"Call the program as: %s 'filename.gph' 'n_root_nodes' (-s)\\n\", argv[0]);\n      exit(EXIT_FAILURE);\n  }\n  if(std::string(argv[argc-1]) == \"-s\"){\n  \toutput=true;\n  }\n\n  ifstream    file(argv[1]);\n  string      line;\n\n  if(!file){\n    fprintf(stderr, \"Could not open file.\\n\");\n    return -1;\n  }\n\n  /**\n  * read number of vertices and edges\n  */\n  getline(file, line, ' ');\n  const int numV = stoi(line);\n  getline(file, line, '\\n');\n  const int numE = stoi(line);\n  \n  /**\n  *\tcheck if no nodes doesnt exceed vertices of graph\n  */\n  int n_nodes = 0;\n\n  try{\n  \tif((stoi(argv[2]) > 0) && (stoi(argv[2]) <= numV))\n  \t\tn_nodes = stoi(argv[2]);\n  \telse{\n  \t\tfprintf(stderr, \"Make sure parameter n_root_nodes is positive and does not exceed graph size.\\n\");\n      exit(EXIT_FAILURE);\n  \t}\n  }\n  catch(...){\n  \tfprintf(stderr, \"Call the program as: %s 'filename.gph' 'n_root_nodes' (-s)\\n\", argv[0]);\n    exit(EXIT_FAILURE);\n  }\n  \n  /*!\n  *   FILL UP sourceVert by random numbers in range 0<->graph.size())\n  */\n  vector<int> sourceVert;\n\tstd::random_device rd;     // only used once to initialise (seed) engine\n\tstd::mt19937 rng(rd());    // random-number engine used (Mersenne-Twister in this case)\n\tfor(int k=0; k<n_nodes; k++){\n\t\tstd::uniform_int_distribution<int> uni(0,numV-1);\n\t\tsourceVert.push_back(uni(rng));\n\t}\n\n  /**\n  * create graph\n  */\n  Graph graph(numV);\n\n  /**\n  * read \u00edn given gph file\n  */\n  while( getline(file, line) ){\n    stringstream linestream(line);\n    string       vertex1, vertex2, weight;\n    try{\n      getline(linestream, vertex1, ' ');\n      getline(linestream, vertex2, ' ');\n      getline(linestream, weight, '\\n');\n\n      /**\n      * add both directions of edge to the graph since undirected\n      * index switch applies: 1 --> 0, 1 --> 2, etc.\n      */\n      graph[stoi(vertex1)-1].push_back(Edge(stoi(vertex2)-1, stoi(weight)));\n      graph[stoi(vertex2)-1].push_back(Edge(stoi(vertex1)-1, stoi(weight)));\n    }catch (...){\n    \tfprintf(stderr, \"Corrupt data in .gph file.\");\n      exit(EXIT_FAILURE);\n    }\n\n  }\n  file.close();\n\n  //Input Done. Start Wall Time counter\n  auto   wall0 = chrono::system_clock::now(); \n\n  int minStVal = INT_MAX;\n  Graph minSteiner(numV);\n  int locStTrWght[sourceVert.size()];\n  \n  //Parallel section (ex10)\n  #pragma omp parallel for shared(locStTrWght, minStVal, minSteiner)\n  \n  for(unsigned int initroot=0; initroot<sourceVert.size(); initroot++){\n    //Create local SteinerGraph as emty Graph\n    Graph stGraph(numV);\n    //Check if initroot is in Graph-range\n    if(sourceVert[initroot]>=graph.size()){\n      fprintf(stderr, \"Invalid source node: %i. Please make sure that root node indices are lower than graph size!\\n\", sourceVert[initroot]+1);\n      exit(EXIT_FAILURE);\n    }\n    //Call Dijkstra with initroot-vertex as source\n    locStTrWght[initroot] = dijkstra_mod(graph, stGraph, sourceVert[initroot]);\n    \n    //If return value is new min, save SteinerGraph\n    if(locStTrWght[initroot]<minStVal){\n    \tminSteiner = stGraph;\n    \tminStVal = locStTrWght[initroot];\n    }\n  }\n  \n  //End Wall-Timer\n  chrono::duration<double> wallDur = (chrono::system_clock::now() - wall0);\n  double wallTime = wallDur.count();\n  \n  /*!\n  *   RUN EXTRA TEST\n  *   Checks if graph is a tree + if all primes are found in the tree\n  *   returns 1 if successful, 0 if unsuccessful\n  */\n  int validate = validateStGraph(minSteiner);\n\n  if(validate==0) fprintf(stdout, \"ERROR.\\nSteiner Graph is not a tree\\n\");\n  \n  /*\n  *   OUTPUT\n  */\n  int ocount=0;\n  fprintf(stdout, \"TLEN:\\t %i\\n\", minStVal);\n\n  //Output of MinSteiner-Edges (only in manual call (-s).)\n  if(output){\n  \tfprintf(stdout, \"TREE:\\t\");\n  \tfor(unsigned int i=0; i<minSteiner.size(); i++){\n  \t\tif(!(minSteiner[i].empty())){\n  \t\t\tfor(unsigned int j=0; j<minSteiner[i].size(); j++){\n  \t\t\t\tfprintf(stdout, \"(%i,%i), \", i+1, minSteiner[i][j].first+1);\n  \t\t\t\tocount++;\n  \t\t\t\tif((ocount%10)==0) fprintf(stdout, \"\\n\\t\");\n  \t\t\t}\n  \t\t}\n  \t}\n  \tfprintf(stdout, \"\\n\");\n  }\n  double cpuTime = (clock() - cpu0) / (double) CLOCKS_PER_SEC;\n  fprintf(stdout, \"TIME:\\t %f\\n\", cpuTime);\n  fprintf(stdout, \"WALL:\\t %f\\n\", wallTime);\n  return 0;\n}", "meta": {"hexsha": "d0de7a0165ac8884a70fe1532ba4f6a80d7a5f7e", "size": 11280, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Brand/ex10/ex10.cpp", "max_stars_repo_name": "appfs/appfs", "max_stars_repo_head_hexsha": "8cbbfa0e40e4d4a75a498ce8dd894bb2fbc3a9e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2017-04-21T11:39:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T20:25:18.000Z", "max_issues_repo_path": "Brand/ex10/ex10.cpp", "max_issues_repo_name": "appfs/appfs", "max_issues_repo_head_hexsha": "8cbbfa0e40e4d4a75a498ce8dd894bb2fbc3a9e3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 69.0, "max_issues_repo_issues_event_min_datetime": "2017-04-26T09:30:38.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-01T11:31:21.000Z", "max_forks_repo_path": "Brand/ex10/ex10.cpp", "max_forks_repo_name": "appfs/appfs", "max_forks_repo_head_hexsha": "8cbbfa0e40e4d4a75a498ce8dd894bb2fbc3a9e3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 53.0, "max_forks_repo_forks_event_min_datetime": "2017-04-20T16:16:11.000Z", "max_forks_repo_forks_event_max_datetime": "2017-07-19T12:53:01.000Z", "avg_line_length": 27.512195122, "max_line_length": 143, "alphanum_fraction": 0.6096631206, "num_tokens": 3284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384736, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.49456739689112067}}
{"text": "#ifndef _HASH_HPP\n#define _HASH_HPP\n#include <string>\n#include <vector>\n#include <stdint.h>\n#include <boost/multiprecision/gmp.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n\nnamespace usebitcoins {\nnamespace hash {\n\n// Generate BTC addresses deterministically by hashing the customer's ID\n// (e.g., an email address)\n\nusing email_address_t = std::string;\n\n/// Perform straightforward hash of arbitrary data\nstd::vector<uint8_t> blake2_hash(std::vector<uint8_t> src);\n\n// Hash an arbitrary string via blake2 to a byte array\nstd::vector<uint8_t> hash_string(std::string_view src);\n\n/// Hash email address to a 64-bit integer\nuint64_t hash_email(const email_address_t& email_address);\n\n/// Fit a byte array into a bignum\n/// Assumes that `src` is arranged in little-endian order\nboost::multiprecision::uint256_t pack_byte_array(const std::vector<uint8_t>& src);\n\n} // namespace hash\n} // namespace usebitcoins\n\n#endif // _HASH_HPP\n", "meta": {"hexsha": "2403ec08f1bc84824f316408f3f66fb21a7fa18c", "size": 931, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "usebitcoins/hash.hpp", "max_stars_repo_name": "fakecoinbase/proprietaryslashusebitcoins", "max_stars_repo_head_hexsha": "fcfa5c37ca1b037b45d09f5040eb1d79e72f62c6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-08-05T17:19:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-07T14:37:10.000Z", "max_issues_repo_path": "usebitcoins/hash.hpp", "max_issues_repo_name": "fakecoinbase/proprietaryslashusebitcoins", "max_issues_repo_head_hexsha": "fcfa5c37ca1b037b45d09f5040eb1d79e72f62c6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "usebitcoins/hash.hpp", "max_forks_repo_name": "fakecoinbase/proprietaryslashusebitcoins", "max_forks_repo_head_hexsha": "fcfa5c37ca1b037b45d09f5040eb1d79e72f62c6", "max_forks_repo_licenses": ["Apache-2.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.3823529412, "max_line_length": 82, "alphanum_fraction": 0.7647690655, "num_tokens": 226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7853085708384735, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.4945673859774261}}
{"text": "#ifndef BIN_PACKING\n#define BIN_PACKING\n\n#include <iostream>\n#include <fstream>\n#include <cassert>\n#include <vector>\n#include <deque>\n#include <iomanip>\n#include <cmath>\n#include <string>\n#include <cstring>\n#include <chrono>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/algorithms/overlaps.hpp>\n#include <boost/geometry/geometries/geometries.hpp>\n\nnamespace boost_geo = boost::geometry;\nnamespace trans = boost::geometry::strategy::transform;\n\ntypedef boost_geo::model::point<double, 2, boost_geo::cs::cartesian> Point;\ntypedef boost_geo::model::polygon<Point> Polygon;\ntypedef boost_geo::model::multi_polygon<Polygon> MultiPolygon;\ntypedef boost_geo::model::box<Point> Box;\ntypedef std::vector<std::pair<double, double>> PolygonInput;\ntypedef Point Vector;\n\n#define x get<0>()\n#define y get<1>()\n\nconst double EPS = 1e-8;\nconst double INF = 4e18;\nconst double PI = acos(-1);\n\nstatic int frameno;\n\n/**\n * customized geometry utility methods using boost\n * */\nnamespace boost_geo_util \n{\n    Polygon constructBGPolygon(PolygonInput &);\n    bool isPolygonIntersectPolygon(MultiPolygon &, MultiPolygon &);\n    bool isPointInsidePolygons(MultiPolygon &, Point &);\n    void visualize(MultiPolygon &, std::string);\n}; // namespace boost_geo_util\n\nnamespace bin_packing\n{\n    void runDataset(std::string, std::string, double);\n    std::vector<PolygonInput> readDataset(std::string, std::vector<int> &, double &);\n    void binPacking(std::vector<PolygonInput> &, double, double &, std::string);\n    void placeItem(MultiPolygon &, Polygon &, double, double &);\n    void normalize(PolygonInput &);\n    void normalizePolygon(Polygon &);\n    double getLength(Polygon &);\n    double getWidth(Polygon &);\n}; // namespace bin_packing\n\n#endif // BIN_PACKING\n", "meta": {"hexsha": "47d904e8dda2bc6154c5d2c569b5027eff438c80", "size": 1753, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/bin_packing.hpp", "max_stars_repo_name": "Oranged9922/2D-Irregular-Cutting-Stock-Algorithm", "max_stars_repo_head_hexsha": "c044c476f043e41dd5cecfe6b7d066e6a1cfb0c7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2020-10-19T11:48:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T13:19:17.000Z", "max_issues_repo_path": "include/bin_packing.hpp", "max_issues_repo_name": "Oranged9922/2D-Irregular-Cutting-Stock-Algorithm", "max_issues_repo_head_hexsha": "c044c476f043e41dd5cecfe6b7d066e6a1cfb0c7", "max_issues_repo_licenses": ["MIT"], "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/bin_packing.hpp", "max_forks_repo_name": "Oranged9922/2D-Irregular-Cutting-Stock-Algorithm", "max_forks_repo_head_hexsha": "c044c476f043e41dd5cecfe6b7d066e6a1cfb0c7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2020-09-09T15:31:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-04T10:03:27.000Z", "avg_line_length": 28.2741935484, "max_line_length": 85, "alphanum_fraction": 0.7364517969, "num_tokens": 410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.665410572017153, "lm_q1q2_score": 0.4945118497156796}}
{"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 *      131204    S. Hirsh          File created.\n *      140120    T. Roegiers       Codecheck small changes.\n *      140410    S. Hirsh          Minor revisions.\n *      140411    T. Roegiers       Minor textual changes during codecheck.\n *\n *    References\n *\n *\n *    Notes\n *\n */\n\n#include <cmath>\n\n#include <Eigen/Geometry>\n\n#include \"Tudat/Mathematics/BasicMathematics/rotationAboutArbitraryAxis.h\"\n\nnamespace tudat\n{\nnamespace basic_mathematics\n{\n\n//! Compute rotation of point about arbitrary axis\nEigen::Vector3d computeRotationOfPointAboutArbitraryAxis(\n        const Eigen::Vector3d& originOfRotation,\n        const double angleOfRotation,\n        const Eigen::Vector3d& axisOfRotation,\n        const Eigen::Vector3d& initialPositionOfPoint )\n{\n\n    //Declare and initialize rotation matrix\n    Eigen::Matrix3d rotationMatrix = Eigen::Matrix3d::Zero( );\n\n    // Compute rotation matrix using AngleAxis object.\n    rotationMatrix = Eigen::AngleAxisd( angleOfRotation, axisOfRotation.normalized( ) );\n\n    // Compute initial of position of point with respect to origin of rotation.\n    const Eigen::Vector3d initialPositionOfPointWithRespectToOriginOfRotation =\n            initialPositionOfPoint - originOfRotation;\n\n    // Compute rotation of point about axis of rotation with respect to origin of rotation.\n    const Eigen::Vector3d rotatedPositionWithRespectToOriginOfRotation =\n            rotationMatrix * initialPositionOfPointWithRespectToOriginOfRotation;\n\n    //Return position with respect to the chosen arbitrary origin after rotation about\n    //arbitrary axis.\n    return rotatedPositionWithRespectToOriginOfRotation + originOfRotation;\n\n}\n\n//! Compute rotation of vector about arbitrary axis\nEigen::Vector3d computeRotationOfVectorAboutArbitraryAxis(\n        const Eigen::Vector3d& originOfRotation,\n        const double angleOfRotation,\n        const Eigen::Vector3d& axisOfRotation,\n        const Eigen::Vector3d& initialPositionOfVectorTail,\n        const Eigen::Vector3d& initialVector )\n{\n\n    // Compute rotation of the tail of vector. Resulted position is with respect to the chosen\n    // arbitrary origin.\n    Eigen::Vector3d rotatedPositionOfVectorTail =\n            computeRotationOfPointAboutArbitraryAxis( originOfRotation, angleOfRotation,\n                                                      axisOfRotation, initialPositionOfVectorTail );\n\n    // Compute rotation of the head of vector. Resulted position is with respect to the chosen\n    // arbitrary origin.\n    Eigen::Vector3d rotatedPositionOfVectorHead =\n            computeRotationOfPointAboutArbitraryAxis( originOfRotation, angleOfRotation,\n                                                      axisOfRotation,\n                                                      initialPositionOfVectorTail + initialVector );\n\n    // Return rotated vector with respect to the chosen arbitrary origin\n    return rotatedPositionOfVectorHead - rotatedPositionOfVectorTail;\n\n}\n\n} // namespace basic_mathematics\n} // namespace tudat\n", "meta": {"hexsha": "9675b775667e1ede8df9deae73f356afe07c0945", "size": 4746, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Mathematics/BasicMathematics/rotationAboutArbitraryAxis.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/rotationAboutArbitraryAxis.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/rotationAboutArbitraryAxis.cpp", "max_forks_repo_name": "JPelamatti/ThesisTUDAT", "max_forks_repo_head_hexsha": "b94ce35fb7c8fa44ae83238e296a979dfa3adfe8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-05-30T03:42:22.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-30T03:42:22.000Z", "avg_line_length": 44.3551401869, "max_line_length": 100, "alphanum_fraction": 0.7142857143, "num_tokens": 981, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.4945118398535881}}
{"text": "#include <complex>\n#include <iostream>\n#include <string>\n#include <boost/spirit/include/qi.hpp>\n\n\n// parse complex number in the form of a + bi\nbool parse_complex_number(const std::string& str, std::complex<double>& val) {\n    namespace qi = boost::spirit::qi;\n    namespace ascii = boost::spirit::ascii;\n\n    using qi::double_;\n    using qi::phrase_parse;\n    using ascii::space;\n\n    // construct the grammar\n    auto real_part = double_;\n    auto imag_part = double_ >> 'i';\n    auto grammar = real_part >> -imag_part;\n\n    double real = 0;\n    double imag = 0;\n    auto begin = str.begin();\n    auto end = str.end();\n    bool r = phrase_parse(begin, end, grammar, space, real, imag);\n\n    // fail if we did not get a full match\n    if (begin != end)\n        return false;\n\n    // set the value if success\n    val = { real, imag };\n    return r;\n}\n\n\nint main() {\n    std::cout << \"Complex number parser.\\n\";\n    std::cout << \"Type 'quit' to quit.\\n\\n\";\n\n    for (std::string line; getline(std::cin, line);) {\n        if (line == \"quit\")\n            break;\n\n        std::complex<double> val;\n        if (parse_complex_number(line, val)) {\n            std::cout << \"Parsing succeeded.\\n\";\n            std::cout << \"You entered (\" << val.real() << \"; \" << val.imag() << \")\\n\\n\";\n        }\n        else {\n            std::cout << \"Parsing failed\\n\\n\";\n        }\n    }\n}\n", "meta": {"hexsha": "83310553b99b0efc9c29d292d214fbc6de429736", "size": 1369, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/ParseComplexNumber.cpp", "max_stars_repo_name": "so61pi/examples", "max_stars_repo_head_hexsha": "38e2831cd6517864fc05f499f72fbb4ff6ae27c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-05-01T07:23:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T00:05:06.000Z", "max_issues_repo_path": "cpp/ParseComplexNumber.cpp", "max_issues_repo_name": "so61pi/examples", "max_issues_repo_head_hexsha": "38e2831cd6517864fc05f499f72fbb4ff6ae27c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 16.0, "max_issues_repo_issues_event_min_datetime": "2020-02-24T13:04:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-26T10:19:48.000Z", "max_forks_repo_path": "cpp/ParseComplexNumber.cpp", "max_forks_repo_name": "so61pi/examples", "max_forks_repo_head_hexsha": "38e2831cd6517864fc05f499f72fbb4ff6ae27c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-03-30T07:29:58.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-30T07:29:58.000Z", "avg_line_length": 24.8909090909, "max_line_length": 88, "alphanum_fraction": 0.565376187, "num_tokens": 354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743168019989179, "lm_q2_score": 0.6654105454764747, "lm_q1q2_score": 0.4945118375616713}}
{"text": "#include <ctime>\n#include <string>\n#include <algorithm>\n#include <iostream>\n#include <random>\n#include <math.h>\n#include <vtkNew.h>\n#include <vtkPolyDataReader.h>\n#include <vtkPolyDataWriter.h>\n#include <vtkCellLocator.h>\n#include <vtkDelaunay3D.h>\n#include <vtkDataSetSurfaceFilter.h>\n#include <vtkPolyData.h>\n#include <vtkDoubleArray.h>\n#include <vtkPoints.h>\n#include <vtkIdFilter.h>\n#include <vtkPointData.h>\n#include <vtkCellArray.h>\n#include <vtkIdList.h>\n#include <vtkLinearSubdivisionFilter.h>\n#include <vtkGenericCell.h>\n#include <vtkVertexGlyphFilter.h>\n#include <vtkDataObject.h>\n#include <Eigen/Dense>\n\nextern \"C\" void shexpandlsq_wrapper_(double* cilm, double* d, double* lat,\n\tdouble* lon, int* N, int* lmax, double* chi2);\n\nextern \"C\" void makegridpoints_wrapper_(double* cilm, int* lmax, int* n,\n\tdouble* lat, double* lon, double* points, int* dealloc);\n\nextern \"C\" void glqgridcoord_wrapper_(double* latglq, double* longlq,\n\tint* lmax, int* nlat, int* nlong);\n\nextern \"C\" void shglq_wrapper_(int* lmax, double* zero, double* w,\n\tdouble* plx);\n\nextern \"C\" void shexpandglq_wrapper_(double* cilm, int* lmax, double* gridglq,\n\tdouble* w, double* plx);\n\nextern \"C\" void makegridglq_wrapper_(double* gridglq, double* cilm, int* lmax,\n\tdouble* plx);\n\nextern \"C\" void shexpanddh_wrapper_(double* grid, int* n, double* cilm,\n\tint* lmax);\n\nextern \"C\" void makegriddh_wrapper_(double* grid, int* n, double* cilm,\n\tint* lmax);\n\nextern \"C\" void shpowerspectrum_wrapper_(double* cilm, int* lmax,\n\tdouble* pspectrum);\n\nint main(){\n\n    // Read the polydata\n    vtkNew<vtkPolyDataReader> reader;\n    reader->SetFileName(\"T7.vtk\");\n    reader->Update();\n    auto pointCloud = reader->GetOutput();\n    int N = pointCloud->GetNumberOfPoints();\n\n    // Copy the point coordinates into a matrix\n    Eigen::Map<Eigen::Matrix3Xd> ptsMat((double_t*)pointCloud->GetPoints()\n\t    ->GetData()->GetVoidPointer(0),3,N);\n\n    // Calculate average radius\n    double_t R = ptsMat.colwise().norm().mean();\n\n    // Calculate points on a sphere of average radius and displacements\n    vtkNew<vtkPoints> spherePts;\n    vtkNew<vtkDoubleArray> displacements;\n    displacements->SetName(\"Displacements\");\n    displacements->SetNumberOfComponents(1);\n    for(auto i = 0; i < N; ++i){\n\tEigen::Vector3d p, q;\n\tpointCloud->GetPoint(i, &p(0));\n\tq =  R*p.normalized();\n\tspherePts->InsertNextPoint( &q(0) );\n\tdisplacements->InsertNextTuple1(p.norm() - R);\n    }\n\n    // Create a mesh on the sphere\n    vtkNew<vtkPolyData> sphere;\n    sphere->SetPoints( spherePts );\n    sphere->GetPointData()->AddArray( displacements );\n    vtkNew<vtkIdFilter> idf;\n    idf->SetIdsArrayName( \"OrigIds\" );\n    idf->PointIdsOn();\n    idf->SetInputData( sphere );\n    vtkNew<vtkDelaunay3D> d3D;\n    d3D->SetInputConnection( idf->GetOutputPort() );\n    vtkNew<vtkDataSetSurfaceFilter> dssf;\n    dssf->SetInputConnection(d3D->GetOutputPort());\n    dssf->Update();\n    auto final = dssf->GetOutput()->GetPolys();\n    auto idArray = dssf->GetOutput()->GetPointData()->GetArray( \"OrigIds\" );\n    final->InitTraversal();\n    vtkNew<vtkCellArray> triangles;\n    vtkNew<vtkIdList> ids;\n    while( final->GetNextCell( ids ) ){\n\ttriangles->InsertNextCell(3);\n\tfor( auto i = 0; i < 3; ++i )\n\t    triangles->InsertCellPoint( (vtkIdType)idArray->GetTuple1(\n\t\t\tids->GetId(i) ) );\n    }\n    sphere->SetPolys( triangles );\n    vtkNew<vtkPolyDataWriter> writer;\n    writer->SetFileName(\"AverageSphere.vtk\");\n    writer->SetInputData(sphere);\n    writer->Write();\n\n    // Create a locator to identify the cells that contain the Gauss quadrature\n    // points\n    vtkNew<vtkCellLocator> cellLoc;\n    cellLoc->SetDataSet( sphere );\n    cellLoc->BuildLocator();\n\n    //**********************************************************************//\n    // Create the Gauss-Lengendre grid\n    int nlat, nlong, lmax = 7;\n    Eigen::VectorXd latglq(lmax + 1);\n    Eigen::VectorXd longlq(2*lmax + 1);\n    glqgridcoord_wrapper_(latglq.data(), longlq.data(), &lmax, &nlat, &nlong);\n\n    // Find the cell to which each point of the grid belongs and set its value\n    // by linear interpolation\n    auto coords = [&R]( const double_t T, const double_t P ){\n\tEigen::Vector3d X;\n\tauto SinT = std::sin(T*M_PI/180.0);\n\tX << R*SinT*std::cos(P*M_PI/180.0), R*SinT*std::sin(P*M_PI/180.0),\n\t  R*std::cos( T*M_PI/180.0);\n\treturn X;\n    };\n    /*\n       vtkNew<vtkPoints> glqPoints;\n       vtkNew<vtkCellArray> glqVerts;\n       vtkNew<vtkDoubleArray> glqDisp;\n       glqDisp->SetName(\"GLQDisp\");\n       glqDisp->SetNumberOfComponents(3);\n       */\n    Eigen::VectorXd gridglq((lmax + 1)*(2*lmax + 1));\n    Eigen::VectorXd plx( (lmax + 1)*(lmax + 1)*(lmax + 2)/2 );\n    Eigen::VectorXd w( lmax + 1 ), zero( lmax + 1 );\n    Eigen::VectorXd cilm1( 2*(lmax + 1)*(lmax + 1) );\n    Eigen::VectorXd pspectrum1( lmax + 1 );\n    shglq_wrapper_(&lmax, zero.data(), w.data(), plx.data() );\n\n    clock_t t = clock();\n    for(auto z = 0; z < 1000; ++z){\n\tfor( auto j = 0; j < 2*lmax + 1; ++j ){\n\t    for( auto i = 0; i < lmax + 1; ++i ){\n\t\t// Get the spherical coordinate\n\t\tauto X = coords( 90.0 - latglq(i), longlq(j) );\n\t\t// Locate cell\n\t\tEigen::Vector3d closestPoint, pcoords, weights;\n\t\tvtkIdType cellId;\n\t\tint subId;\n\t\tdouble_t dist2;\n\t\tvtkNew<vtkGenericCell> genCell;\n\t\tcellLoc->FindClosestPoint( &X(0), &closestPoint(0), genCell,\n\t\t\tcellId, subId, dist2);\n\t\t// Get the parametric coordinates and weights\n\t\tgenCell->EvaluatePosition( &X(0), &closestPoint(0), subId,\n\t\t\t&pcoords(0), dist2, &weights(0) );\n\t\tvtkNew<vtkIdList> pointIds;\n\t\tsphere->GetCellPoints( cellId, pointIds );\n\t\t// Interpolate to find the displacement at quadrature point\n\t\tgridglq(i + (lmax + 1)*j) =\n\t\t    weights[0]*displacements->GetTuple1(pointIds->GetId(0)) +\n\t\t    weights[1]*displacements->GetTuple1(pointIds->GetId(1)) +\n\t\t    weights[2]*displacements->GetTuple1(pointIds->GetId(2));\n\t\t//glqPoints->InsertNextPoint( &X(0) );\n\t\t//Eigen::Vector3d disp;\n\t\t//disp = gridglq(i + (lmax + 1)*j)*X.normalized();\n\t\t//glqDisp->InsertNextTuple( &disp(0) );\n\t    }\n\t}\n\t/*\n\t   vtkNew<vtkPolyData> glqBody;\n\t   glqBody->SetPoints( glqPoints );\n\t   glqBody->GetPointData()->SetVectors( glqDisp );\n\t   writer->SetInputData( glqBody );\n\t   writer->SetFileName( \"GLQBody.vtk\" );\n\t   writer->Write();\n\t   */\n\n\t// Expand using Gauss-Legendre Quadrature and get the power spectrum\n\tshexpandglq_wrapper_( cilm1.data(), &lmax, gridglq.data(), w.data(),\n\t\tplx.data());\n    }\n    t = clock() - t;\n    std::cout<< \"Time for 1000 steps GLQ = \" << ((float)t)/CLOCKS_PER_SEC\n       \t<< std::endl;\n\n    shpowerspectrum_wrapper_( cilm1.data(), &lmax, pspectrum1.data() );\n    // Cross-check\n    Eigen::VectorXd gridglq_out( (lmax + 1)*(2*lmax + 1) );\n    makegridglq_wrapper_(gridglq_out.data(), cilm1.data(), &lmax, plx.data());\n    std::cout<< \"Error norm of GLQ = \" << (gridglq - gridglq_out).norm()\n\t<< std::endl;\n    //**********************************************************************//\n    // Expand using Driscol-Healy and get the power spectrum\n    int ndh = 2*(lmax + 1);\n    /*\n       vtkNew<vtkPoints> DHPoints;\n       vtkNew<vtkCellArray> DHVerts;\n       vtkNew<vtkDoubleArray> DHDisp;\n       DHDisp->SetName(\"DHGridDisp\");\n       DHDisp->SetNumberOfComponents(3);\n       */\n    Eigen::VectorXd gridDH( ndh*ndh );\n    Eigen::VectorXd cilm2( ndh*ndh/2 ), pspectrum2(lmax + 1);\n\n    t = clock();\n    for(auto z = 0; z < 1000; ++z){\n\tfor( auto i = 0; i < ndh; ++i ){\n\t    auto latDH = i*(180.0/ndh);\n\t    for( auto j = 0; j < ndh; ++j ){\n\t\t// Get the spherical coordinate\n\t\tauto lonDH = j*360.0/ndh;\n\t\tauto X = coords( latDH, lonDH );\n\t\t// Locate cell\n\t\tEigen::Vector3d closestPoint, pcoords, weights, dummy;\n\t\tvtkIdType cellId;\n\t\tint subId;\n\t\tdouble_t dist2;\n\t\tvtkNew<vtkGenericCell> genCell;\n\t\tcellLoc->FindClosestPoint( &X(0), &closestPoint(0), genCell,\n\t\t\tcellId, subId, dist2);\n\t\t// Get the parametric coordinates and weights\n\t\tauto out = genCell->EvaluatePosition( &closestPoint(0), &dummy(0),\n\t\t\tsubId, &pcoords(0), dist2, &weights(0) );\n\t\tvtkNew<vtkIdList> pointIds;\n\t\tsphere->GetCellPoints( cellId, pointIds );\n\t\t// Interpolate to find the displacement at quadrature point\n\t\tgridDH(i + ndh*j) =\n\t\t    weights[0]*displacements->GetTuple1(pointIds->GetId(0)) +\n\t\t    weights[1]*displacements->GetTuple1(pointIds->GetId(1)) +\n\t\t    weights[2]*displacements->GetTuple1(pointIds->GetId(2));\n\t\t//DHPoints->InsertNextPoint( &X(0) );\n\t\t//Eigen::Vector3d disp;\n\t\t//disp = gridDH(j + ndh*i)*X.normalized();\n\t\t//DHDisp->InsertNextTuple( &disp(0) );\n\t    }\n\t}\n\t/*\n\t   vtkNew<vtkPolyData> DHBody;\n\t   DHBody->SetPoints( DHPoints );\n\t   DHBody->GetPointData()->SetVectors( DHDisp );\n\t   writer->SetInputData( DHBody );\n\t   writer->SetFileName( \"DHBody.vtk\" );\n\t   writer->Write();\n\t   */\n\n\t// Finally expand using DH scheme\n\tshexpanddh_wrapper_(gridDH.data(), &ndh, cilm2.data(), &lmax);\n    }\n    t = clock() - t;\n    std::cout<< \"Time for 1000 steps DH = \" << ((float)t)/CLOCKS_PER_SEC\n       \t<< std::endl;\n\n    shpowerspectrum_wrapper_(cilm2.data(), &lmax, pspectrum2.data());\n    // Cross-check\n    Eigen::VectorXd gridDH_out( ndh*ndh );\n    makegriddh_wrapper_(gridDH_out.data(), &ndh, cilm2.data(), &lmax);\n    std::cout<< \"Error norm of DH = \" << (gridDH - gridDH_out).norm()\n\t<< std::endl;\n    //**********************************************************************//\n    //Now we will use LSQ\n    Eigen::VectorXd latLSQ(N), lonLSQ(N), gridLSQ(N);\n    Eigen::VectorXd cilm3(2*(lmax+1)*(lmax+1)), pspectrum3(lmax + 1);\n    double_t chi2;\n    t = clock();\n    for(auto z = 0; z < 1000; ++z){\n\tfor( auto i = 0; i < N; ++i ){\n\t    double_t X[3], x, y, z;\n\t    spherePts->GetPoint(i, X);\n\t    x = X[0]; y = X[1]; z = X[2];\n\t    // Calculate latitude and longitude for the points\n\t    latLSQ(i) = std::atan2(z, sqrt(x*x + y*y)) * 180.0/M_PI;\n\t    lonLSQ(i) = std::atan2(y, x) * 180.0/M_PI;\n\t    gridLSQ(i) = displacements->GetTuple1(i);\n\t}\n\tshexpandlsq_wrapper_(cilm3.data(), gridLSQ.data(), latLSQ.data(),\n\t\tlonLSQ.data(), &N, &lmax, &chi2);\n    }\n    t = clock() - t;\n    std::cout<< \"Time for 1000 steps LSQ = \" << ((float)t)/CLOCKS_PER_SEC\n       \t<< std::endl;\n\n    shpowerspectrum_wrapper_(cilm3.data(), &lmax, pspectrum3.data());\n    // Cross-check\n    Eigen::VectorXd gridLSQ_out(N);\n    int dealloc = 1;\n    makegridpoints_wrapper_(cilm3.data(), &lmax, &N, latLSQ.data(),\n\t    lonLSQ.data(), gridLSQ_out.data(), &dealloc);\n    std::cout<< \"Error norm of LSQ = \" << (gridLSQ_out - gridLSQ).norm()\n\t<< std::endl;\n\n    //**********************************************************************//\n    // Now let's print the power-spectrums\n    std::cout<< \" Power spectrum from GLQ = \" << std::endl\n\t<< pspectrum1.transpose() << std::endl;\n    std::cout<< \" Power spectrum from DH = \" << std::endl\n\t<< pspectrum2.transpose() << std::endl;\n    std::cout<< \" Power spectrum from LSQ = \" << std::endl\n\t<< pspectrum3.transpose() << std::endl;\n\n    //**********************************************************************//\n    // Now we will subdivide the sphere polydata and calculate the\n    // displacements at more points using the cilm calculated above. We will\n    // print all three vtk surfaces and see which is the best.\n    vtkNew<vtkLinearSubdivisionFilter> lsdf;\n    lsdf->SetInputData( sphere );\n    lsdf->SetNumberOfSubdivisions(2);\n    lsdf->Update();\n    auto sphere2 = lsdf->GetOutput();\n    int N2 = sphere2->GetNumberOfPoints();\n    Eigen::VectorXd lat2(N2), lon2(N2), grid2(N2);\n    for( auto i = 0; i < N2; ++i ){\n\tdouble_t X[3], x, y, z;\n\tsphere2->GetPoint(i, X);\n\tx = X[0]; y = X[1]; z = X[2];\n\t// Calculate latitude and longitude for the points\n\tlat2(i) = std::atan2(z, sqrt(x*x + y*y)) * 180.0/M_PI;\n\tlon2(i) = std::atan2(y, x) * 180.0/M_PI;\n    }\n    auto writeResult = [&](Eigen::VectorXd &C, std::string file){\n\t// First get the deformation vlaues\n\tmakegridpoints_wrapper_(C.data(), &lmax, &N2, lat2.data(),\n\t\tlon2.data(), grid2.data(), &dealloc);\n\t// Add the deformations to average radius along each point's direction\n\tvtkNew<vtkPoints> newPoints;\n\tfor( auto i = 0; i < N2; ++i ){\n\t    Eigen::Vector3d X, Xpd;\n\t    sphere2->GetPoint( i, &X(0) );\n\t    Xpd = (R + grid2(i))*X.normalized();\n\t    newPoints->InsertNextPoint( &Xpd(0) );\n\t}\n\tvtkNew<vtkPolyData> temp;\n\ttemp->SetPoints( newPoints );\n\tvtkNew<vtkVertexGlyphFilter> vgf;\n\tvgf->SetInputData( temp );\n\twriter->SetInputConnection( vgf->GetOutputPort() );\n\twriter->SetFileName( file.c_str() );\n\twriter->Update();\n\twriter->Write();\n    };\n\n    writeResult( cilm1, \"LSQ_Result.vtk\" );\n    writeResult( cilm2, \"GLQ_Result.vtk\" );\n    writeResult( cilm3, \"DH_Result.vtk\" );\n\n    return 0;\n}\n", "meta": {"hexsha": "c71f008c1804efe117c14843442dcd99128d852b", "size": 12629, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "PointCloudSH.cxx", "max_stars_repo_name": "amit112amit/ops-spherical-harmonics", "max_stars_repo_head_hexsha": "27a0d5e6ed4635d9b1cd6cb1d625d3cc4147beed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-31T13:42:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-31T13:42:53.000Z", "max_issues_repo_path": "PointCloudSH.cxx", "max_issues_repo_name": "amit112amit/ops-spherical-harmonics", "max_issues_repo_head_hexsha": "27a0d5e6ed4635d9b1cd6cb1d625d3cc4147beed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PointCloudSH.cxx", "max_forks_repo_name": "amit112amit/ops-spherical-harmonics", "max_forks_repo_head_hexsha": "27a0d5e6ed4635d9b1cd6cb1d625d3cc4147beed", "max_forks_repo_licenses": ["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.4747191011, "max_line_length": 79, "alphanum_fraction": 0.6276031356, "num_tokens": 3987, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743167997235783, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.4945118372144588}}
{"text": "#define BOOST_TEST_MODULE XOR Test\n#include <boost/test/included/unit_test.hpp>\n\n#include \"../network.h\"\n#include \"../gradient.h\"\n#include \"../evolution.h\"\n#include <memory>\n\n// Setup the test parameters\nstruct XORdata {\n  std::vector<boost::numeric::ublas::vector<double> > input;\n  std::vector<boost::numeric::ublas::vector<double> > expected;\n\n  XORdata() {\n    boost::numeric::ublas::vector<double> in1(2);\n    in1[0] = 0.0;\n    in1[1] = 0.0;\n    input.push_back(in1);\n\n    boost::numeric::ublas::vector<double> expv1(1);\n    expv1[0] = 0.0;\n    expected.push_back(expv1);\n\n    boost::numeric::ublas::vector<double> in2(2);\n    in2[0] = 0.0;\n    in2[1] = 1.0;\n    input.push_back(in2);\n\n    boost::numeric::ublas::vector<double> expv2(1);\n    expv2[0] = 1.0;\n    expected.push_back(expv2);\n\n    boost::numeric::ublas::vector<double> in3(2);\n    in3[0] = 1.0;\n    in3[1] = 0.0;\n    input.push_back(in3);\n\n    boost::numeric::ublas::vector<double> expv3(1);\n    expv3[0] = 1.0;\n    expected.push_back(expv3);\n\n    boost::numeric::ublas::vector<double> in4(2);\n    in4[0] = 1.0;\n    in4[1] = 1.0;\n    input.push_back(in4);\n\n    boost::numeric::ublas::vector<double> expv4(1);\n    expv4[0] = 0.0;\n    expected.push_back(expv4);\n  }\n};\n\nBOOST_AUTO_TEST_CASE(XOR_test_feed_forward)\n{\n  /*\n  * We test if the feed forward implementation is working by using known\n  * weights for an XOR network.\n  */\n\n  XORdata test;\n\n  std::vector<int> size;\n  size.push_back(2);\n  NeuralNetwork network(size, 2, 1, new SigmoidFunction());\n  network.initializeRandomWeights();\n\n  auto weights = network.getWeights();\n\n  // Weights which produce an XOR network with the sigmoid activation function\n  weights[0](0,0) = -10.0;\n  weights[0](0,1) = 20.0;\n  weights[0](0,2) = 20.0;\n\n  weights[0](1,0) = 30.0;\n  weights[0](1,1) = -20.0;\n  weights[0](1,2) = -20.0;\n\n  weights[1](0,0) = -30.0;\n  weights[1](0,1) = 20.0;\n  weights[1](0,2) = 20.0;\n\n  network.setWeights(weights);\n\n  // We test the inputs against the known outputs\n  for (int i = 0; i < test.input.size(); ++i) {\n    BOOST_CHECK_SMALL(network.feedForwardVector(test.input[i])[0] - test.expected[i][0], 0.01);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(XOR_test_train_SGD)\n{\n  /*\n  * We test the back propogation implementation by using stochastic gradient descent\n  * to learn the weights for an XOR network.\n  *\n  * This test may fail if poor initial conditions are randomly selected.\n  */\n\n  XORdata test;\n\n  std::vector<int> size;\n  size.push_back(2);\n\n  std::unique_ptr<NeuralNetwork> network(new NeuralNetwork(size, 2, 1, new SigmoidFunction()));\n  network->initializeRandomWeights();\n\n  StochasticGradientDescent SGD(network.get(), 0.1);\n  // We train the network using the above pairs of inputs and expected values.\n  std::cout << \"Before training J=\" << network->cost(test.input, test.expected) << std::endl;\n  // We use SGD to train the weights.\n  SGD.train(test.input, test.expected, 1e-3, 2);\n  std::cout << \"After training J=\" << network->cost(test.input, test.expected) << std::endl;\n\n  // We test the newly found weights\n  for (int i = 0; i < test.input.size(); ++i) {\n    std::cout << \"Output: \" << network->feedForwardVector(test.input[i])[0] << \" Expected: \" << test.expected[i][0] << std::endl;\n    BOOST_CHECK_SMALL(network->feedForwardVector(test.input[i])[0] - test.expected[i][0], 0.01);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(XOR_test_train_evo)\n{\n  /*\n  * We use the FEP implementation to learn weights for an XOR network.\n  */\n\n  XORdata test;\n\n  std::vector<int> size;\n  size.push_back(2);\n\n  std::unique_ptr<NeuralNetwork> network(new NeuralNetwork(size, 2, 1, new SigmoidFunction()));\n  network->initializeRandomWeights();\n\n  EvolutionaryProgramming FEP(network.get(), -20.0, 20.0, 100);\n  // We train the network using the above pairs of inputs and expected values.\n  std::cout << \"Before training J=\" << network->cost(test.input, test.expected) << std::endl;\n  std::cout << \"Maximum number of fitness evaluations: \" << 100000 << std::endl;\n\n  // We use FEP to train the weights\n  FEP.train(test.input, test.expected, 100000);\n  std::cout << \"After training J=\" << network->cost(test.input, test.expected) << std::endl;\n\n  // We test the newly found weights\n  for (int i = 0; i < test.input.size(); ++i) {\n    std::cout << \"Output: \" << network->feedForwardVector(test.input[i])[0] << \" Expected: \" << test.expected[i][0] << std::endl;\n    BOOST_CHECK_SMALL(network->feedForwardVector(test.input[i])[0] - test.expected[i][0], 0.01);\n  }\n}\n", "meta": {"hexsha": "b7252e023496be11c726bd00c1939a6168c0a19c", "size": 4478, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/XOR_test.cc", "max_stars_repo_name": "daminuk/ML", "max_stars_repo_head_hexsha": "10fc5992a584815d8531dfa207304aeb4efb7d5b", "max_stars_repo_licenses": ["MIT"], "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/XOR_test.cc", "max_issues_repo_name": "daminuk/ML", "max_issues_repo_head_hexsha": "10fc5992a584815d8531dfa207304aeb4efb7d5b", "max_issues_repo_licenses": ["MIT"], "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/XOR_test.cc", "max_forks_repo_name": "daminuk/ML", "max_forks_repo_head_hexsha": "10fc5992a584815d8531dfa207304aeb4efb7d5b", "max_forks_repo_licenses": ["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.8533333333, "max_line_length": 129, "alphanum_fraction": 0.6581062975, "num_tokens": 1368, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743167997235783, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.4945118372144588}}
{"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   testGaussianConditional.cpp\n *  @brief  Unit tests for Conditional gaussian\n *  @author Christian Potthast\n **/\n\n#include <CppUnitLite/TestHarness.h>\n#include <gtsam/base/TestableAssertions.h>\n\n#include <gtsam/base/Matrix.h>\n#include <gtsam/base/VerticalBlockMatrix.h>\n#include <gtsam/inference/Key.h>\n#include <gtsam/linear/JacobianFactor.h>\n#include <gtsam/linear/GaussianConditional.h>\n#include <gtsam/linear/GaussianBayesNet.h>\n\n#include <boost/assign/std/list.hpp>\n#include <boost/assign/std/vector.hpp>\n#include <boost/assign/list_inserter.hpp>\n#include <boost/make_shared.hpp>\n#include <boost/assign/list_of.hpp>\n\n#include <iostream>\n#include <sstream>\n#include <vector>\n\nusing namespace gtsam;\nusing namespace std;\nusing namespace boost::assign;\n\nstatic const double tol = 1e-5;\n\nstatic Matrix R = (Matrix(2, 2) <<\n    -12.1244,  -5.1962,\n          0.,   4.6904).finished();\n\n/* ************************************************************************* */\nTEST(GaussianConditional, constructor)\n{\n  Matrix S1 = (Matrix(2, 2) <<\n      -5.2786,  -8.6603,\n      5.0254,   5.5432).finished();\n  Matrix S2 = (Matrix(2, 2) <<\n      -10.5573,  -5.9385,\n      5.5737,   3.0153).finished();\n  Matrix S3 = (Matrix(2, 2) <<\n      -11.3820,  -7.2581,\n      -3.0153,  -3.5635).finished();\n\n  Vector d = Vector2(1.0, 2.0);\n  SharedDiagonal s = noiseModel::Diagonal::Sigmas(Vector2(3.0, 4.0));\n\n  vector<pair<Key, Matrix> > terms = pair_list_of\n      (1, R)\n      (3, S1)\n      (5, S2)\n      (7, S3);\n\n  GaussianConditional actual(terms, 1, d, s);\n\n  GaussianConditional::const_iterator it = actual.beginFrontals();\n  EXPECT(assert_equal(Key(1), *it));\n  EXPECT(assert_equal(R, actual.get_R()));\n  ++ it;\n  EXPECT(it == actual.endFrontals());\n\n  it = actual.beginParents();\n  EXPECT(assert_equal(Key(3), *it));\n  EXPECT(assert_equal(S1, actual.get_S(it)));\n\n  ++ it;\n  EXPECT(assert_equal(Key(5), *it));\n  EXPECT(assert_equal(S2, actual.get_S(it)));\n\n  ++ it;\n  EXPECT(assert_equal(Key(7), *it));\n  EXPECT(assert_equal(S3, actual.get_S(it)));\n\n  ++it;\n  EXPECT(it == actual.endParents());\n\n  EXPECT(assert_equal(d, actual.get_d()));\n  EXPECT(assert_equal(*s, *actual.get_model()));\n\n  // test copy constructor\n  GaussianConditional copied(actual);\n  EXPECT(assert_equal(d, copied.get_d()));\n  EXPECT(assert_equal(*s, *copied.get_model()));\n  EXPECT(assert_equal(R, copied.get_R()));\n}\n\n/* ************************************************************************* */\nTEST( GaussianConditional, equals )\n{\n  // create a conditional gaussian node\n  Matrix A1(2,2);\n  A1(0,0) = 1 ; A1(1,0) = 2;\n  A1(0,1) = 3 ; A1(1,1) = 4;\n\n  Matrix A2(2,2);\n  A2(0,0) = 6 ; A2(1,0) = 0.2;\n  A2(0,1) = 8 ; A2(1,1) = 0.4;\n\n  Matrix R(2,2);\n  R(0,0) = 0.1 ; R(1,0) = 0.3;\n  R(0,1) = 0.0 ; R(1,1) = 0.34;\n\n  SharedDiagonal model = noiseModel::Diagonal::Sigmas(Vector2(1.0, 0.34));\n\n  Vector d = Vector2(0.2, 0.5);\n\n  GaussianConditional\n    expected(1, d, R, 2, A1, 10, A2, model),\n    actual(1, d, R, 2, A1, 10, A2, model);\n\n  EXPECT( expected.equals(actual) );\n}\n\n/* ************************************************************************* */\nTEST( GaussianConditional, solve )\n{\n  //expected solution\n  Vector expectedX(2);\n  expectedX(0) = 20-3-11 ; expectedX(1) = 40-7-15;\n\n  // create a conditional Gaussian node\n  Matrix R = (Matrix(2, 2) <<  1., 0.,\n                            0., 1.).finished();\n\n  Matrix A1 = (Matrix(2, 2) << 1., 2.,\n                            3., 4.).finished();\n\n  Matrix A2 = (Matrix(2, 2) << 5., 6.,\n                            7., 8.).finished();\n\n  Vector d(2); d << 20.0, 40.0;\n\n  GaussianConditional cg(1, d, R, 2, A1, 10, A2);\n\n  Vector sx1(2); sx1 << 1.0, 1.0;\n  Vector sl1(2); sl1 << 1.0, 1.0;\n\n  VectorValues expected = map_list_of\n    (1, expectedX)\n    (2, sx1)\n    (10, sl1);\n\n  VectorValues solution = map_list_of\n    (2, sx1) // parents\n    (10, sl1);\n  solution.insert(cg.solve(solution));\n\n  EXPECT(assert_equal(expected, solution, tol));\n}\n\n/* ************************************************************************* */\nTEST( GaussianConditional, solve_simple )\n{\n  // 2 variables, frontal has dim=4\n  VerticalBlockMatrix blockMatrix(list_of(4)(2)(1), 4);\n  blockMatrix.matrix() <<\n      1.0, 0.0, 2.0, 0.0, 3.0, 0.0, 0.1,\n      0.0, 1.0, 0.0, 2.0, 0.0, 3.0, 0.2,\n      0.0, 0.0, 3.0, 0.0, 4.0, 0.0, 0.3,\n      0.0, 0.0, 0.0, 3.0, 0.0, 4.0, 0.4;\n\n  // solve system as a non-multifrontal version first\n  GaussianConditional cg(list_of(1)(2), 1, blockMatrix);\n\n  // partial solution\n  Vector sx1 = Vector2(9.0, 10.0);\n\n  // elimination order: 1, 2\n  VectorValues actual = map_list_of\n    (2, sx1); // parent\n\n  VectorValues expected = map_list_of<Key, Vector>\n    (2, sx1)\n    (1, (Vector(4) << -3.1,-3.4,-11.9,-13.2).finished());\n\n  // verify indices/size\n  EXPECT_LONGS_EQUAL(2, (long)cg.size());\n  EXPECT_LONGS_EQUAL(4, (long)cg.rows());\n\n  // solve and verify\n  actual.insert(cg.solve(actual));\n  EXPECT(assert_equal(expected, actual, tol));\n}\n\n/* ************************************************************************* */\nTEST( GaussianConditional, solve_multifrontal )\n{\n  // create full system, 3 variables, 2 frontals, all 2 dim\n  VerticalBlockMatrix blockMatrix(list_of(2)(2)(2)(1), 4);\n  blockMatrix.matrix() <<\n      1.0, 0.0, 2.0, 0.0, 3.0, 0.0, 0.1,\n      0.0, 1.0, 0.0, 2.0, 0.0, 3.0, 0.2,\n      0.0, 0.0, 3.0, 0.0, 4.0, 0.0, 0.3,\n      0.0, 0.0, 0.0, 3.0, 0.0, 4.0, 0.4;\n\n  // 3 variables, all dim=2\n  GaussianConditional cg(list_of(1)(2)(10), 2, blockMatrix);\n\n  EXPECT(assert_equal(Vector(blockMatrix.full().rightCols(1)), cg.get_d()));\n\n  // partial solution\n  Vector sl1 = Vector2(9.0, 10.0);\n\n  // elimination order; _x_, _x1_, _l1_\n  VectorValues actual = map_list_of\n    (10, sl1); // parent\n\n  VectorValues expected = map_list_of<Key, Vector>\n    (1, Vector2(-3.1,-3.4))\n    (2, Vector2(-11.9,-13.2))\n    (10, sl1);\n\n  // verify indices/size\n  EXPECT_LONGS_EQUAL(3, (long)cg.size());\n  EXPECT_LONGS_EQUAL(4, (long)cg.rows());\n\n  // solve and verify\n  actual.insert(cg.solve(actual));\n  EXPECT(assert_equal(expected, actual, tol));\n\n}\n\n/* ************************************************************************* */\nTEST( GaussianConditional, solveTranspose ) {\n  /** create small Chordal Bayes Net x <- y\n   * x y d\n   * 1 1 9\n   *   1 5\n   */\n  Matrix R11 = (Matrix(1, 1) << 1.0).finished(), S12 = (Matrix(1, 1) << 1.0).finished();\n  Matrix R22 = (Matrix(1, 1) << 1.0).finished();\n  Vector d1(1), d2(1);\n  d1(0) = 9;\n  d2(0) = 5;\n\n  // define nodes and specify in reverse topological sort (i.e. parents last)\n  GaussianBayesNet cbn = list_of\n    (GaussianConditional(1, d1, R11, 2, S12))\n    (GaussianConditional(1, d2, R22));\n\n  // x=R'*y, y=inv(R')*x\n  // 2 = 1    2\n  // 5   1 1  3\n\n  VectorValues\n    x = map_list_of<Key, Vector>\n      (1, (Vector(1) << 2.).finished())\n      (2, (Vector(1) << 5.).finished()),\n    y = map_list_of<Key, Vector>\n      (1, (Vector(1) << 2.).finished())\n      (2, (Vector(1) << 3.).finished());\n\n  // test functional version\n  VectorValues actual = cbn.backSubstituteTranspose(x);\n  CHECK(assert_equal(y, actual));\n}\n\n/* ************************************************************************* */\nTEST( GaussianConditional, information ) {\n\n  // Create R matrix\n  Matrix R(4,4); R <<\n      1, 2, 3, 4,\n      0, 5, 6, 7,\n      0, 0, 8, 9,\n      0, 0, 0, 10;\n\n  // Create conditional\n  GaussianConditional conditional(0, Vector::Zero(4), R);\n\n  // Expected information matrix (using permuted R)\n  Matrix IExpected = R.transpose() * R;\n\n  // Actual information matrix (conditional should permute R)\n  Matrix IActual = conditional.information();\n  EXPECT(assert_equal(IExpected, IActual));\n}\n\n/* ************************************************************************* */\nTEST( GaussianConditional, isGaussianFactor ) {\n\n  // Create R matrix\n  Matrix R(4,4); R <<\n      1, 2, 3, 4,\n      0, 5, 6, 7,\n      0, 0, 8, 9,\n      0, 0, 0, 10;\n\n  // Create a conditional\n  GaussianConditional conditional(0, Vector::Zero(4), R);\n\n  // Expected information matrix computed by conditional\n  Matrix IExpected = conditional.information();\n\n  // Expected information matrix computed by a factor\n  JacobianFactor jf = conditional;\n  Matrix IActual = jf.information();\n\n  EXPECT(assert_equal(IExpected, IActual));\n}\n\n/* ************************************************************************* */\nint main() { TestResult tr; return TestRegistry::runAllTests(tr);}\n/* ************************************************************************* */\n", "meta": {"hexsha": "60387694e1657f6f53dfd4154bcd40bdbc204b7c", "size": 8920, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/linear/tests/testGaussianConditional.cpp", "max_stars_repo_name": "karamach/gtsam", "max_stars_repo_head_hexsha": "35f9b710163a1d14d8dc4fcf50b8dce6e0bf7e5b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 105.0, "max_stars_repo_stars_event_min_datetime": "2017-12-02T14:39:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-19T18:20:25.000Z", "max_issues_repo_path": "trunk/gtsam/linear/tests/testGaussianConditional.cpp", "max_issues_repo_name": "shaolinbit/PPP-BayesTree", "max_issues_repo_head_hexsha": "6f469775277a1a33447bf4c19603c796c2c63c75", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2018-09-04T15:15:59.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-08T08:51:02.000Z", "max_forks_repo_path": "trunk/gtsam/linear/tests/testGaussianConditional.cpp", "max_forks_repo_name": "shaolinbit/PPP-BayesTree", "max_forks_repo_head_hexsha": "6f469775277a1a33447bf4c19603c796c2c63c75", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 31.0, "max_forks_repo_forks_event_min_datetime": "2018-01-10T03:21:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T06:18:35.000Z", "avg_line_length": 27.7881619938, "max_line_length": 88, "alphanum_fraction": 0.5531390135, "num_tokens": 2866, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743167997235783, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.4945118372144587}}
{"text": "#ifndef KOMUNA_VEKTORO_HPP\n#define KOMUNA_VEKTORO_HPP\n\n#include \"../torent/Torentu.hpp\"\n#include \"../trajtoj/numero.hpp\"\n#include <cmath>\n#include <boost/serialization/access.hpp>\n#ifdef \u0108U_UZAS_QT\n#include <QPoint>\n#include <QPointF>\n#endif\n\ntemplate<class T>\nclass Vektor2D\n{\npublic:\n    struct Ordiganto\n    {\n        Buleo operator()(const Vektor2D<T>& a, const Vektor2D<T>& b) const\n        {\n            eligu a.x < b.x a\u016d (a.x == b.x kaj a.y < b.y);\n        }\n    };\n    \n    Vektor2D() : x(0), y(0) {}\n    Vektor2D(T x, T y) : x(x), y(y) {}//-\u00ab\n    Nenio operator+=(const Vektor2D<T> alia) { x += alia.x; y += alia.y; }\n    Nenio operator-=(const Vektor2D<T> alia) { x -= alia.x; y -= alia.y; }  //\u00bb-\n    Buleo operator==(const Vektor2D<T> alia) const { eligu x == alia.x && y == alia.y; }\n    Buleo operator!=(const Vektor2D<T> alia) const { eligu x != alia.x || y != alia.y; }\n    Vektor2D<T> operator+(const Vektor2D<T> alia) const { eligu Vektor2D<T>(x + alia.x, y + alia.y); }\n    Vektor2D<T> operator-(const Vektor2D<T> alia) const { eligu Vektor2D<T>(x - alia.x, y - alia.y); }\n    Vektor2D<T> operator*(const Vektor2D<T> alia) const { eligu Vektor2D<T>(x * alia.x, y * alia.y); }\n    Vektor2D<T> operator/(const Vektor2D<T> alia) const { eligu Vektor2D<T>(x / alia.x, y / alia.y); }\n    Vektor2D<T> operator*(const T s) const { eligu Vektor2D<T>(x * s, y * s); }\n    Vektor2D<T> operator/(const T s) const { eligu Vektor2D<T>(x / s, y / s); }\n    Vektor2D<T> operator%(const T s) const { eligu Vektor2D<T>(x % s, y % s); }\n    T skalaranProduton(const Vektor2D<T> alia) const { eligu x * alia.x + y * alia.y; }; //-\u00ab\n    template<class K> Vektor2D<K> al() const { eligu Vektor2D<K>(\u015dan\u011du_al<K>(x), \u015dan\u011du_al<K>(y)); } //\u00bb-\n    \u211a normon() const { eligu sqrt((\u211a) (x * x + y * y)); }\n    Vektor2D<T> dikunNormo(T celnormo) const;\n\n#ifdef \u0108U_UZAS_QT\n    UZU_SE_(T, \u0109u_estas_\u2124<P1>)\n    Vektor2D(const QPoint& p) : x(p.x()), y(p.y()) {};\n    UZU_SE_(T, \u0109u_estas_\u211a_krom_\u2124<P1>)\n    Vektor2D(const QPointF& p) : x(p.x()), y(p.y()) {};\n    UZU_SE_(T, \u0109u_estas_\u2124<P1>)\n    operator QPoint() { eligu QPoint(x, y); }\n    UZU_SE_(T, \u0109u_estas_\u211a_krom_\u2124<P1>)\n    operator QPointF() { eligu QPointF(x, y); }\n#endif\n    \n    T x, y;\n    TORENTU { torento & x & y; }\n};\n\ntemplate<class T>\nclass Vektor\n{\npublic:\n    struct Ordiganto\n    {\n        Buleo operator()(const Vektor<T>& a, const Vektor<T>& b) const\n        {\n            eligu a.x < b.x a\u016d (a.x == b.x kaj (a.y < b.y a\u016d (a.y == b.y kaj a.z < b.z)));\n        }\n    };\n    \n    template<class K>\n    static Vektor<T> prenuEl(const K& k) { eligu Vektor<T>(k.x, k.y, k.z); };\n    Vektor() : x(0), y(0), z(0) {}\n    Vektor(T x, T y, T z) : x(x), y(y), z(z) {}\n    explicit Vektor(Vektor2D<T> xy, T z = 0) : x(xy.x), y(xy.y), z(z) {} //-\u00ab\n    Buleo operator==(const Vektor<T> alia) const { eligu x == alia.x && y == alia.y && z == alia.z; }\n    Buleo operator!=(const Vektor<T> alia) const { eligu x != alia.x || y != alia.y || z != alia.z; }\n    Nenio operator+=(const Vektor<T> alia) { x += alia.x; y += alia.y; z += alia.z; }\n    Nenio operator-=(const Vektor<T> alia) { x -= alia.x; y -= alia.y; z -= alia.z; } //\u00bb-\n    Vektor<T> operator+(const Vektor<T> alia) const { eligu Vektor<T>(x + alia.x, y + alia.y, z + alia.z); }\n    Vektor<T> operator-(const Vektor<T> alia) const { eligu Vektor<T>(x - alia.x, y - alia.y, z - alia.z); }\n    Vektor<T> operator*(const T s) const { eligu Vektor<T>(x * s, y * s, z * s); }\n    Vektor<T> operator/(const T s) const { eligu Vektor<T>(x / s, y / s, z / s); }\n    T skalaranProduton(const Vektor<T> alia) const { eligu x * alia.x + y * alia.y + z * alia.z; }; // -\u00ab\n    Vektor<T> ortanProduton(const Vektor<T> a) const { eligu {y * a.z - z * a.y, z * a.x - x * a.z, x * a.y - y * a.x};}\n    template<class K> Vektor<K> al() const { eligu Vektor<K>(\u015dan\u011du_al<K>(x), \u015dan\u011du_al<K>(y), \u015dan\u011du_al<K>(z)); }\n    Vektor2D<T> xy() const { eligu Vektor2D<T>(x, y); }\n    \u211a normon() const { eligu sqrt((\u211a)(x * x + y * y + z * z)); }\n    Vektor<T> dikunNormo(T celnormo) const { premisu (normon() != 0); eligu (*this * celnormo) / normon(); } //\u00bb-\n    \n    T x, y, z;\n    TORENTU { torento & x & y & z; }\n};\n\n//-\u00ab\ntemplate <class K> const Vektor2D<K> nulvektor2D = Vektor2D<K>(0, 0);\ntemplate <class K> const Vektor<K> nulvektor = Vektor<K>(0, 0, 0);\ntemplate <class K> const Vektor2D<K> nenie2D = Vektor2D<K>(maximumDe<K>, maximumDe<K>);\ntemplate <class K> const Vektor<K> nenie = Vektor<K>(maximumDe<K>, maximumDe<K>, maximumDe<K>);\n\ntemplate <class K> Vektor<K> operator*(const K s, Vektor<K> v) { eligu v * s; }\ntemplate <class K> Vektor2D<K> operator*(const K s, Vektor2D<K> v) { eligu v * s; }//\u00bb-\n\ntypedef Vektor<\u21152> BazaKoordinato;\ntypedef Vektor2D<\u21152> BazaKoordinato2D;\n//typedef Vektor<FiksitaKomo<\u21154, pow(2, bitojDen<\u21154> - bitojDen<\u21152>)>> BazaSubkoordinato;\n\ntemplate<class K>\nVektor2D<K> Vektor2D<K>::dikunNormo(K celnormo) const\n{\n    premisu (*this != nulvektor2D<K>);\n    eligu (*this * celnormo) / (K) normon();\n}\n\n#endif //KOMUNA_VEKTORO_HPP\n", "meta": {"hexsha": "1347da9f5273f02a22be14e0bf3c9c51d540c210", "size": 5038, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/komuna/geom/Vektor.hpp", "max_stars_repo_name": "cnsuhao/wortserchilo", "max_stars_repo_head_hexsha": "2788036dbcd754d68190514dd2df20d691309990", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-12T16:41:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-12T16:41:47.000Z", "max_issues_repo_path": "src/komuna/geom/Vektor.hpp", "max_issues_repo_name": "cnsuhao/wortserchilo", "max_issues_repo_head_hexsha": "2788036dbcd754d68190514dd2df20d691309990", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/komuna/geom/Vektor.hpp", "max_forks_repo_name": "cnsuhao/wortserchilo", "max_forks_repo_head_hexsha": "2788036dbcd754d68190514dd2df20d691309990", "max_forks_repo_licenses": ["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.8086956522, "max_line_length": 120, "alphanum_fraction": 0.5881302104, "num_tokens": 2090, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.4945118349225424}}
{"text": "///////////////////////////////////////////////////////////////\n//  Copyright 2011 John Maddock. Distributed under the Boost\n//  Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt\n\n//[mpfi_eg\n#include <boost/multiprecision/mpfi.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n#include <iostream>\n\nint main()\n{\n   using namespace boost::multiprecision;\n\n   // Operations at variable precision and no numeric_limits support:\n   mpfi_float a = 2;\n   mpfi_float::default_precision(1000);\n   std::cout << mpfi_float::default_precision() << std::endl;\n   std::cout << sqrt(a) << std::endl; // print root-2\n\n   // Operations at fixed precision and full numeric_limits support:\n   mpfi_float_100 b = 2;\n   std::cout << std::numeric_limits<mpfi_float_100>::digits << std::endl;\n   // We can use any C++ std lib function:\n   std::cout << log(b) << std::endl; // print log(2)\n\n   // Access the underlying data:\n   mpfi_t r;\n   mpfi_init(r);\n   mpfi_set(r, b.backend().data());\n\n   // Construct some explicit intervals and perform set operations:\n   mpfi_float_50 i1(1, 2), i2(1.5, 2.5);\n   std::cout << intersect(i1, i2) << std::endl;\n   std::cout << hull(i1, i2) << std::endl;\n   std::cout << overlap(i1, i2) << std::endl;\n   std::cout << subset(i1, i2) << std::endl;\n   mpfi_clear(r);\n   return 0;\n}\n//]\n\n", "meta": {"hexsha": "b36e22b5b69eaeea5d0e643396be5dfe0211a108", "size": 1375, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/libs/multiprecision/example/mpfi_snips.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/mpfi_snips.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/mpfi_snips.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": 31.976744186, "max_line_length": 73, "alphanum_fraction": 0.6356363636, "num_tokens": 391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431679972357831, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.49451182735236743}}
{"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 <dai/daialg.h>\n#include <dai/alldai.h>\n#include <strstream>\n\n\nusing namespace dai;\n\n\nconst double tol = 1e-8;\n\n\n#define BOOST_TEST_MODULE DAIAlgTest\n\n\n#include <boost/test/unit_test.hpp>\n\n\nBOOST_AUTO_TEST_CASE( calcMarginalTest ) {\n    Var v0( 0, 2 );\n    Var v1( 1, 2 );\n    Var v2( 2, 2 );\n    Var v3( 3, 2 );\n    VarSet v01( v0, v1 );\n    VarSet v02( v0, v2 );\n    VarSet v03( v0, v3 );\n    VarSet v12( v1, v2 );\n    VarSet v13( v1, v3 );\n    VarSet v23( v2, v3 );\n    std::vector<Factor> facs;\n    facs.push_back( createFactorIsing( v0, v1, 1.0 ) );\n    facs.push_back( createFactorIsing( v1, v2, 1.0 ) );\n    facs.push_back( createFactorIsing( v2, v3, 1.0 ) );\n    facs.push_back( createFactorIsing( v3, v0, 1.0 ) );\n    facs.push_back( createFactorIsing( v0, -1.0 ) );\n    facs.push_back( createFactorIsing( v1, -1.0 ) );\n    facs.push_back( createFactorIsing( v2, -1.0 ) );\n    facs.push_back( createFactorIsing( v3, 1.0 ) );\n    Factor joint = facs[0] * facs[1] * facs[2] * facs[3] * facs[4] * facs[5] * facs[6] * facs[7];\n    FactorGraph fg( facs );\n    ExactInf ei( fg, PropertySet()(\"verbose\",(size_t)0) );\n    ei.init();\n    ei.run();\n    VarSet vs;\n\n    vs = v0;        BOOST_CHECK( dist( calcMarginal( ei, vs, false ), joint.marginal( vs ), DISTTV ) < tol );\n    vs = v1;        BOOST_CHECK( dist( calcMarginal( ei, vs, false ), joint.marginal( vs ), DISTTV ) < tol );\n    vs = v2;        BOOST_CHECK( dist( calcMarginal( ei, vs, false ), joint.marginal( vs ), DISTTV ) < tol );\n    vs = v3;        BOOST_CHECK( dist( calcMarginal( ei, vs, false ), joint.marginal( vs ), DISTTV ) < tol );\n    vs = v01;       BOOST_CHECK( dist( calcMarginal( ei, vs, false ), joint.marginal( vs ), DISTTV ) < tol );\n    vs = v02;       BOOST_CHECK( dist( calcMarginal( ei, vs, false ), joint.marginal( vs ), DISTTV ) < tol );\n    vs = v03;       BOOST_CHECK( dist( calcMarginal( ei, vs, false ), joint.marginal( vs ), DISTTV ) < tol );\n    vs = v12;       BOOST_CHECK( dist( calcMarginal( ei, vs, false ), joint.marginal( vs ), DISTTV ) < tol );\n    vs = v13;       BOOST_CHECK( dist( calcMarginal( ei, vs, false ), joint.marginal( vs ), DISTTV ) < tol );\n    vs = v23;       BOOST_CHECK( dist( calcMarginal( ei, vs, false ), joint.marginal( vs ), DISTTV ) < tol );\n    vs = v01 | v2;  BOOST_CHECK( dist( calcMarginal( ei, vs, false ), joint.marginal( vs ), DISTTV ) < tol );\n    vs = v01 | v3;  BOOST_CHECK( dist( calcMarginal( ei, vs, false ), joint.marginal( vs ), DISTTV ) < tol );\n    vs = v02 | v3;  BOOST_CHECK( dist( calcMarginal( ei, vs, false ), joint.marginal( vs ), DISTTV ) < tol );\n    vs = v12 | v3;  BOOST_CHECK( dist( calcMarginal( ei, vs, false ), joint.marginal( vs ), DISTTV ) < tol );\n    vs = v01 | v23; BOOST_CHECK( dist( calcMarginal( ei, vs, false ), joint.marginal( vs ), DISTTV ) < tol );\n}\n\n\nBOOST_AUTO_TEST_CASE( calcPairBeliefsTest ) {\n    Var v0( 0, 2 );\n    Var v1( 1, 2 );\n    Var v2( 2, 2 );\n    Var v3( 3, 2 );\n    VarSet v01( v0, v1 );\n    VarSet v02( v0, v2 );\n    VarSet v03( v0, v3 );\n    VarSet v12( v1, v2 );\n    VarSet v13( v1, v3 );\n    VarSet v23( v2, v3 );\n    std::vector<Factor> facs;\n    facs.push_back( createFactorIsing( v0, v1, 1.0 ) );\n    facs.push_back( createFactorIsing( v1, v2, 1.0 ) );\n    facs.push_back( createFactorIsing( v2, v3, 1.0 ) );\n    facs.push_back( createFactorIsing( v3, v0, 1.0 ) );\n    facs.push_back( createFactorIsing( v0, -1.0 ) );\n    facs.push_back( createFactorIsing( v1, -1.0 ) );\n    facs.push_back( createFactorIsing( v2, -1.0 ) );\n    facs.push_back( createFactorIsing( v3, 1.0 ) );\n    Factor joint = facs[0] * facs[1] * facs[2] * facs[3] * facs[4] * facs[5] * facs[6] * facs[7];\n    FactorGraph fg( facs );\n    ExactInf ei( fg, PropertySet()(\"verbose\",(size_t)0) );\n    ei.init();\n    ei.run();\n    VarSet vs;\n\n    std::vector<Factor> pb = calcPairBeliefs( ei, v01 | v23, false, false );\n    BOOST_CHECK( dist( pb[0], joint.marginal( v01 ), DISTTV ) < tol );\n    BOOST_CHECK( dist( pb[1], joint.marginal( v02 ), DISTTV ) < tol );\n    BOOST_CHECK( dist( pb[2], joint.marginal( v03 ), DISTTV ) < tol );\n    BOOST_CHECK( dist( pb[3], joint.marginal( v12 ), DISTTV ) < tol );\n    BOOST_CHECK( dist( pb[4], joint.marginal( v13 ), DISTTV ) < tol );\n    BOOST_CHECK( dist( pb[5], joint.marginal( v23 ), DISTTV ) < tol );\n\n    pb = calcPairBeliefs( ei, v01 | v23, false, true );\n    BOOST_CHECK( dist( pb[0], joint.marginal( v01 ), DISTTV ) < tol );\n    BOOST_CHECK( dist( pb[1], joint.marginal( v02 ), DISTTV ) < tol );\n    BOOST_CHECK( dist( pb[2], joint.marginal( v03 ), DISTTV ) < tol );\n    BOOST_CHECK( dist( pb[3], joint.marginal( v12 ), DISTTV ) < tol );\n    BOOST_CHECK( dist( pb[4], joint.marginal( v13 ), DISTTV ) < tol );\n    BOOST_CHECK( dist( pb[5], joint.marginal( v23 ), DISTTV ) < tol );\n}\n", "meta": {"hexsha": "88db62abe03086521f87b36118237d81da373ba2", "size": 5032, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/unit/daialg_test.cpp", "max_stars_repo_name": "chang-liang/HadoopBNEM", "max_stars_repo_head_hexsha": "dd90a70786271ebf5b0beda2484f8e476ab4a97a", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 48.0, "max_stars_repo_stars_event_min_datetime": "2015-01-19T18:56:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-30T20:30:50.000Z", "max_issues_repo_path": "tests/unit/daialg_test.cpp", "max_issues_repo_name": "chang-liang/HadoopBNEM", "max_issues_repo_head_hexsha": "dd90a70786271ebf5b0beda2484f8e476ab4a97a", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2016-01-18T08:17:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-28T18:08:38.000Z", "max_forks_repo_path": "tests/unit/daialg_test.cpp", "max_forks_repo_name": "chang-liang/HadoopBNEM", "max_forks_repo_head_hexsha": "dd90a70786271ebf5b0beda2484f8e476ab4a97a", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 29.0, "max_forks_repo_forks_event_min_datetime": "2015-04-07T07:38:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-01T22:18:58.000Z", "avg_line_length": 44.1403508772, "max_line_length": 109, "alphanum_fraction": 0.6013513514, "num_tokens": 1799, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743167997235783, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.4945118273523673}}
{"text": "/**\n * @file   main_grid_transfer_test.cpp\n * @author  <simon@thinkpadX1>\n * @date   Tue Mar 31 15:27:16 2015\n *\n * @brief  Just for debugging purposes!\n *         GridTransfer (dh, dh) => should yield identity matrix\n *\n *\n */\n\n// 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// system includes -----------------------------------------------\n#include <hdf5.h>\n#include <yaml-cpp/yaml.h>\n#include <Eigen/Dense>\n#include <algorithm>\n#include <boost/filesystem.hpp>\n#include <boost/program_options.hpp>\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\n#include \"spectral/basis/indexer.hpp\"\n\n#include \"l2errors.hpp\"\n// class SimpleGridHandler, Solution\n#include \"grid/grid_tools.hpp\"\n#include \"solution_handler.hpp\"\n#include \"spectral_transfer_matrix.hpp\"\n\nconst int dim = 2;\n\nnamespace bf = boost::filesystem;\nnamespace po = boost::program_options;\n\nusing namespace boltzmann;\nusing namespace std;\n\nconst std::string spectral_basis_fname = \"spectral_basis.desc\";\n\ntypedef dealii::DoFHandler<dim> dh_t;\ntypedef dealii::Vector<double> vector_t;\n\nint main(int argc, char* argv[])\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  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  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  string str_input_solution = config[\"input\"][\"solution\"].as<string>();\n\n  string str_ref_grid = config[\"reference\"][\"grid\"].as<string>();\n  string str_ref_path = config[\"reference\"][\"path\"].as<string>();\n  string str_ref_solution = config[\"reference\"][\"solution\"].as<string>();\n\n  dealii::FE_Q<dim> fe(1);\n  shared_ptr<SimpleGridHandler> ref_grid_ptr =\n      make_shared<SimpleGridHandler>(str_ref_path, str_ref_grid);\n  shared_ptr<SimpleGridHandler> grid_ptr =\n      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  GridTransfer<dim> grid_transfer;\n  grid_transfer.init(ref_dh, ref_dh);\n  const auto& Tx = grid_transfer.get_transfer_matrix();\n\n  // output to hdf5\n  hid_t file;\n  file = H5Fcreate(\"transfer_matrix.h5\", H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);\n  eigen2hdf::save_sparse(file, \"Tx\", Tx);\n\n  // // load solution data\n  // typedef Solution<SimpleGridHandler> solution_t;\n  // solution_t input_solution(grid_ptr, str_input_path, str_input_solution);\n  // solution_t ref_solution(ref_grid_ptr, str_ref_path, str_ref_solution);\n\n  // auto& mu_input = input_solution.get_solution();\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(), \"make T\");\n\n  // timer.start();\n  // eigen2hdf::save_sparse(file, \"T\", T);\n  // print_timer(timer.stop(), \"save T\");\n\n  // timer.start();\n  // Eigen::VectorXd out = T*mu_input;\n  // print_timer(timer.stop(), \"interpolation to fine grid\");\n\n  // eigen2hdf::save(file, \"coeffs\", out);\n\n  // auto vertex2dofidx = vertex_to_dof_index(ref_dh);\n  // std::ofstream fout(\"v2d.dat\");\n  // for (auto it = vertex2dofidx.begin(); it != vertex2dofidx.end();\n  //      ++it) {\n  //   fout << it->first << \"\\t\" << it->second << endl;\n  // }\n  // fout.close();\n\n  // ------------------------------------------------------------------------------------------\n  // TODO load coefficients\n\n  // ------------------------------------------------------------------------------------------\n  // compute errors, global, cell-wise\n\n  // load basis file\n  H5Fclose(file);\n\n  return 0;\n}\n", "meta": {"hexsha": "83adce6274dd400963185dccec3db47e2a17b4d3", "size": 4538, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "applications/convergence_plots/main_grid_transfer_test.cpp", "max_stars_repo_name": "simonpintarelli/2dBoltzmann", "max_stars_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "applications/convergence_plots/main_grid_transfer_test.cpp", "max_issues_repo_name": "simonpintarelli/2dBoltzmann", "max_issues_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "applications/convergence_plots/main_grid_transfer_test.cpp", "max_forks_repo_name": "simonpintarelli/2dBoltzmann", "max_forks_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2533333333, "max_line_length": 99, "alphanum_fraction": 0.6472014103, "num_tokens": 1124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431679972357831, "lm_q2_score": 0.6654105454764747, "lm_q1q2_score": 0.4945118224213217}}
{"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_SWAR_FUNCTIONS_SIMD_SSE_SSE2_SORT_HPP_INCLUDED\n#define BOOST_SIMD_SWAR_FUNCTIONS_SIMD_SSE_SSE2_SORT_HPP_INCLUDED\n\n#ifdef BOOST_SIMD_HAS_SSE2_SUPPORT\n#include <boost/simd/swar/functions/sort.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/minimum.hpp>\n#include <boost/simd/include/functions/simd/maximum.hpp>\n#include <boost/simd/include/functions/simd/make.hpp>\n#include <boost/simd/swar/functions/shuffle.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT          ( sort_\n                                    , boost::simd::tag::sse2_\n                                    , (A0)\n                                    , ((simd_ < type32_<A0>\n                                              , boost::simd::tag::sse_\n                                              >\n                                      ))\n                                    )\n  {\n    typedef A0 result_type;\n    BOOST_FORCEINLINE result_type operator()(A0 const& a0) const\n    {\n      // half-permute\n      A0 p0 = shuffle<2,3,0,1>(a0);\n      A0 mn = min(a0,p0);\n      A0 mx = max(a0,p0);\n\n      // cross vector concatenation and reversal\n      A0 minmax = shuffle<0,1,6,7>(mn,mx);\n      A0 maxmin = shuffle<1,0,7,6>(mn,mx);\n\n      mn = min(minmax,maxmin);\n      mx = max(minmax,maxmin);\n\n      // rearrange partial max/min while keeping min and max in place\n         p0 = shuffle<0,2,5,7>(mn,mx);\n      A0 p1 = shuffle<0,2,1,3>(p0);\n\n      // Bring sorted min/max in the proper place\n      return shuffle<0,1,6,7>(min(p1,p0),max(p1,p0));\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT          ( sort_\n                                    , boost::simd::tag::sse2_\n                                    , (A0)\n                                    , ((simd_ < type64_<A0>\n                                              , boost::simd::tag::sse_\n                                              >\n                                      ))\n                                    )\n  {\n    typedef A0 result_type;\n    BOOST_FORCEINLINE result_type operator()(A0 const& a0) const\n    {\n      // Better latency\n      A0 p0 = shuffle<1,0>(a0);\n      return shuffle<0,2>(min(a0,p0),max(a0,p0));\n    }\n  };\n} } }\n\n#endif\n#endif\n", "meta": {"hexsha": "b78c2453faf54371641fe9602885d0fd3a9df424", "size": 2823, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/base/include/boost/simd/swar/functions/simd/sse/sse2/sort.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/swar/functions/simd/sse/sse2/sort.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/swar/functions/simd/sse/sse2/sort.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.6623376623, "max_line_length": 80, "alphanum_fraction": 0.4867162593, "num_tokens": 660, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339837155239, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.49451021574644366}}
{"text": "#include <NTL/GF2EX.h>\n#include <NTL/GF2XFactoring.h>\n\nnamespace NTL {\n\nvoid BuildPlain(GF2EXModulus& F, const GF2EX& f, bool plain);\n\n}\n\nNTL_CLIENT\n\n\n#define TIME_IT(t, action) \\\ndo { \\\n   double _t0, _t1; \\\n   long _iter = 1; \\\n   long _cnt = 0; \\\n   do { \\\n      _t0 = GetTime(); \\\n      for (long _i = 0; _i < _iter; _i++) { action; _cnt++; } \\\n      _t1 = GetTime(); \\\n   } while ( _t1 - _t0 < 2 && (_iter *= 2)); \\\n   t = (_t1 - _t0)/_iter; \\\n} while(0)\n\n\nlong test(long k)\n{\n   GF2X P;\n\n   BuildIrred(P, k);\n   GF2EPush push(P);\n\n   for (long n = 5; ; n+=5) {\n      cerr << \",\";\n      GF2EX a, r, f;\n      random(a, 2*n-1);\n      random(f, n);\n      SetCoeff(f, n);\n      GF2EXModulus F1, F2;\n      BuildPlain(F1, f, false);\n      BuildPlain(F2, f, true);\n      double t1, t2;\n      TIME_IT(t1, rem(r, a, F1));\n      TIME_IT(t2, rem(r, a, F2));\n      double t = t1/t2;\n      if (t <= 0.95) return n;\n   }\n}\n\nint main()\n{\n   cerr << \"0.5 \" << test(32) << \"\\n\";\n   for (long i = 1; i <= 40 ; i++) {\n      cerr << i << \" \" << test(64*i) << \"\\n\";\n   }\n}\n\n\n", "meta": {"hexsha": "fb85d191b83d57739d4a82e5bd7e267205597053", "size": 1059, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "homomorphic_evaluation/ntl-11.3.2/src/GF2EXModCross.cpp", "max_stars_repo_name": "dklee0501/PLDI_20_242_artifact_publication", "max_stars_repo_head_hexsha": "f2b73df9165c76e8b521d8ebd639d68321e3862b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 61.0, "max_stars_repo_stars_event_min_datetime": "2015-03-21T19:39:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-22T06:14:16.000Z", "max_issues_repo_path": "homomorphic_evaluation/ntl-11.3.2/src/GF2EXModCross.cpp", "max_issues_repo_name": "dklee0501/Lobster", "max_issues_repo_head_hexsha": "f2b73df9165c76e8b521d8ebd639d68321e3862b", "max_issues_repo_licenses": ["MIT"], "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": "homomorphic_evaluation/ntl-11.3.2/src/GF2EXModCross.cpp", "max_forks_repo_name": "dklee0501/Lobster", "max_forks_repo_head_hexsha": "f2b73df9165c76e8b521d8ebd639d68321e3862b", "max_forks_repo_licenses": ["MIT"], "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": 17.65, "max_line_length": 63, "alphanum_fraction": 0.477809254, "num_tokens": 415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722394, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.49451020629872783}}
{"text": "// This file is part of OpenCV project.\n// It is subject to the license terms in the LICENSE file found in the top-level directory\n// of this distribution and at http://opencv.org/license.html.\n\n#include \"precomp.hpp\"\n\n#include <Eigen/Sparse>\n\nusing namespace Eigen;\n\nnamespace cv { namespace alphamat {\n\nstatic\nvoid solve(SparseMatrix<double> Wcm, SparseMatrix<double> Wuu, SparseMatrix<double> Wl, SparseMatrix<double> Dcm,\n        SparseMatrix<double> Duu, SparseMatrix<double> Dl, SparseMatrix<double> T,\n        Mat& wf, Mat& alpha)\n{\n    float suu = 0.01, sl = 0.1, lamd = 100;\n\n    SparseMatrix<double> Lifm = ((Dcm - Wcm).transpose()) * (Dcm - Wcm) + sl * (Dl - Wl) + suu * (Duu - Wuu);\n\n    SparseMatrix<double> A;\n    int n = wf.rows;\n    VectorXd b(n), x(n);\n\n    Eigen::VectorXd wf_;\n    cv2eigen(wf, wf_);\n\n    A = Lifm + lamd * T;\n    b = (lamd * T) * (wf_);\n\n    ConjugateGradient<SparseMatrix<double>, Lower | Upper> cg;\n\n    cg.setMaxIterations(500);\n    cg.compute(A);\n    x = cg.solve(b);\n    CV_LOG_INFO(NULL, \"ALPHAMAT: #iterations:     \" << cg.iterations());\n    CV_LOG_INFO(NULL, \"ALPHAMAT: estimated error: \" << cg.error());\n\n    int nRows = alpha.rows;\n    int nCols = alpha.cols;\n    float pix_alpha;\n    for (int j = 0; j < nCols; ++j)\n    {\n        for (int i = 0; i < nRows; ++i)\n        {\n            pix_alpha = x(i + j * nRows);\n            if (pix_alpha < 0)\n                pix_alpha = 0;\n            if (pix_alpha > 1)\n                pix_alpha = 1;\n            alpha.at<uchar>(i, j) = uchar(pix_alpha * 255);\n        }\n    }\n}\n\nvoid infoFlow(InputArray image_ia, InputArray tmap_ia, OutputArray result)\n{\n    Mat image = image_ia.getMat();\n    Mat tmap = tmap_ia.getMat();\n\n    int64 begin = cv::getTickCount();\n\n    int nRows = image.rows;\n    int nCols = image.cols;\n    int N = nRows * nCols;\n\n    SparseMatrix<double> T(N, N);\n    typedef Triplet<double> Tr;\n    std::vector<Tr> triplets;\n\n    //Pre-process trimap\n    for (int i = 0; i < nRows; ++i)\n    {\n        for (int j = 0; j < nCols; ++j)\n        {\n            uchar& pix = tmap.at<uchar>(i, j);\n            if (pix <= 0.2f * 255)\n                pix = 0;\n            else if (pix >= 0.8f * 255)\n                pix = 255;\n            else\n                pix = 128;\n        }\n    }\n\n    Mat wf = Mat::zeros(nRows * nCols, 1, CV_8U);\n\n    // Column Major Interpretation for working with SparseMatrix\n    for (int i = 0; i < nRows; ++i)\n    {\n        for (int j = 0; j < nCols; ++j)\n        {\n            uchar pix = tmap.at<uchar>(i, j);\n\n            // collection of known pixels samples\n            triplets.push_back(Tr(i + j * nRows, i + j * nRows, (pix != 128) ? 1 : 0));\n\n            // foreground pixel\n            wf.at<uchar>(i + j * nRows, 0) = (pix > 200) ? 1 : 0;\n        }\n    }\n\n    SparseMatrix<double> Wl(N, N), Dl(N, N);\n    local_info(image, tmap, Wl, Dl);\n\n    SparseMatrix<double> Wcm(N, N), Dcm(N, N);\n    cm(image, tmap, Wcm, Dcm);\n\n    Mat new_tmap = tmap.clone();\n\n    SparseMatrix<double> Wuu(N, N), Duu(N, N);\n    Mat image_t = image.t();\n    Mat tmap_t = tmap.t();\n    UU(image, tmap, Wuu, Duu);\n\n    double elapsed_secs = ((double)(getTickCount() - begin)) / getTickFrequency();\n\n    T.setFromTriplets(triplets.begin(), triplets.end());\n\n    Mat alpha = Mat::zeros(nRows, nCols, CV_8UC1);\n    solve(Wcm, Wuu, Wl, Dcm, Duu, Dl, T, wf, alpha);\n\n    alpha.copyTo(result);\n\n    elapsed_secs = ((double)(getTickCount() - begin)) / getTickFrequency();\n    CV_LOG_INFO(NULL, \"ALPHAMAT: total time: \" << elapsed_secs);\n}\n\n}}  // namespace cv::alphamat\n", "meta": {"hexsha": "e85ed8db5d155752698bfc5ecac69193eea0a77c", "size": 3570, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/alphamat/src/infoflow.cpp", "max_stars_repo_name": "ptelang/opencv_contrib", "max_stars_repo_head_hexsha": "dd68e396c76f1db4d82e5aa7a6545580939f9b9d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 7158.0, "max_stars_repo_stars_event_min_datetime": "2016-07-04T22:19:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T07:54:32.000Z", "max_issues_repo_path": "modules/alphamat/src/infoflow.cpp", "max_issues_repo_name": "ptelang/opencv_contrib", "max_issues_repo_head_hexsha": "dd68e396c76f1db4d82e5aa7a6545580939f9b9d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2184.0, "max_issues_repo_issues_event_min_datetime": "2016-07-05T12:04:14.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T19:10:12.000Z", "max_forks_repo_path": "modules/alphamat/src/infoflow.cpp", "max_forks_repo_name": "ptelang/opencv_contrib", "max_forks_repo_head_hexsha": "dd68e396c76f1db4d82e5aa7a6545580939f9b9d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5535.0, "max_forks_repo_forks_event_min_datetime": "2016-07-06T12:01:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T03:13:24.000Z", "avg_line_length": 27.2519083969, "max_line_length": 113, "alphanum_fraction": 0.5571428571, "num_tokens": 1105, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809302, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.49447195549495276}}
{"text": "// Copyright (C) 2013  Davis E. King (davis@dlib.net)\r\n// License: Boost Software License   See LICENSE.txt for the full license.\r\n\r\n#include \"opaque_types.h\"\r\n#include <dlib/python.h>\r\n#include <dlib/matrix.h>\r\n#include <dlib/data_io.h>\r\n#include <dlib/sparse_vector.h>\r\n#include <dlib/optimization.h>\r\n#include <dlib/statistics/running_gradient.h>\r\n\r\nusing namespace dlib;\r\nusing namespace std;\r\nnamespace py = pybind11;\r\n\r\ntypedef std::vector<std::pair<unsigned long,double> > sparse_vect;\r\n\r\n\r\nvoid _make_sparse_vector (\r\n    sparse_vect& v\r\n)\r\n{\r\n    make_sparse_vector_inplace(v);\r\n}\r\n\r\nvoid _make_sparse_vector2 (\r\n    std::vector<sparse_vect>& v\r\n)\r\n{\r\n    for (unsigned long i = 0; i < v.size(); ++i)\r\n        make_sparse_vector_inplace(v[i]);\r\n}\r\n\r\npy::tuple _load_libsvm_formatted_data(\r\n    const std::string& file_name\r\n) \r\n{ \r\n    std::vector<sparse_vect> samples;\r\n    std::vector<double> labels;\r\n    load_libsvm_formatted_data(file_name, samples, labels); \r\n    return py::make_tuple(samples, labels);\r\n}\r\n\r\nvoid _save_libsvm_formatted_data (\r\n    const std::string& file_name,\r\n    const std::vector<sparse_vect>& samples,\r\n    const std::vector<double>& labels\r\n) \r\n{ \r\n    pyassert(samples.size() == labels.size(), \"Invalid inputs\");\r\n    save_libsvm_formatted_data(file_name, samples, labels); \r\n}\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\npy::list _max_cost_assignment (\r\n    const matrix<double>& cost\r\n)\r\n{\r\n    if (cost.nr() != cost.nc())\r\n        throw dlib::error(\"The input matrix must be square.\");\r\n\r\n    // max_cost_assignment() only works with integer matrices, so convert from\r\n    // double to integer.\r\n    const double scale = (std::numeric_limits<dlib::int64>::max()/1000)/max(abs(cost));\r\n    matrix<dlib::int64> int_cost = matrix_cast<dlib::int64>(round(cost*scale));\r\n    return vector_to_python_list(max_cost_assignment(int_cost));\r\n}\r\n\r\ndouble _assignment_cost (\r\n    const matrix<double>& cost,\r\n    const py::list& assignment\r\n)\r\n{\r\n    return assignment_cost(cost, python_list_to_vector<long>(assignment));\r\n}\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\nsize_t py_count_steps_without_decrease (\r\n    py::object arr,\r\n    double probability_of_decrease\r\n) \r\n{ \r\n    DLIB_CASSERT(0.5 < probability_of_decrease && probability_of_decrease < 1);\r\n    return count_steps_without_decrease(python_list_to_vector<double>(arr), probability_of_decrease); \r\n}\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\nsize_t py_count_steps_without_decrease_robust (\r\n    py::object arr,\r\n    double probability_of_decrease,\r\n    double quantile_discard\r\n) \r\n{ \r\n    DLIB_CASSERT(0.5 < probability_of_decrease && probability_of_decrease < 1);\r\n    DLIB_CASSERT(0 <= quantile_discard && quantile_discard <= 1);\r\n    return count_steps_without_decrease_robust(python_list_to_vector<double>(arr), probability_of_decrease, quantile_discard); \r\n}\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\ndouble probability_that_sequence_is_increasing (\r\n    py::object arr\r\n)\r\n{\r\n    DLIB_CASSERT(len(arr) > 2);\r\n    return probability_gradient_greater_than(python_list_to_vector<double>(arr), 0);\r\n}\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\nvoid hit_enter_to_continue()\r\n{\r\n    std::cout << \"Hit enter to continue\";\r\n    std::cin.get();\r\n}\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\nvoid bind_other(py::module &m)\r\n{\r\n    m.def(\"max_cost_assignment\", _max_cost_assignment, py::arg(\"cost\"),\r\n\"requires    \\n\\\r\n    - cost.nr() == cost.nc()    \\n\\\r\n      (i.e. the input must be a square matrix)    \\n\\\r\nensures    \\n\\\r\n    - Finds and returns the solution to the following optimization problem:    \\n\\\r\n    \\n\\\r\n        Maximize: f(A) == assignment_cost(cost, A)    \\n\\\r\n        Subject to the following constraints:    \\n\\\r\n            - The elements of A are unique. That is, there aren't any     \\n\\\r\n              elements of A which are equal.      \\n\\\r\n            - len(A) == cost.nr()    \\n\\\r\n    \\n\\\r\n    - Note that this function converts the input cost matrix into a 64bit fixed    \\n\\\r\n      point representation.  Therefore, you should make sure that the values in    \\n\\\r\n      your cost matrix can be accurately represented by 64bit fixed point values.    \\n\\\r\n      If this is not the case then the solution my become inaccurate due to    \\n\\\r\n      rounding error.  In general, this function will work properly when the ratio    \\n\\\r\n      of the largest to the smallest value in cost is no more than about 1e16.   \" \r\n        );\r\n\r\n    m.def(\"assignment_cost\", _assignment_cost, py::arg(\"cost\"),py::arg(\"assignment\"),\r\n\"requires    \\n\\\r\n    - cost.nr() == cost.nc()    \\n\\\r\n      (i.e. the input must be a square matrix)    \\n\\\r\n    - for all valid i:    \\n\\\r\n        - 0 <= assignment[i] < cost.nr()    \\n\\\r\nensures    \\n\\\r\n    - Interprets cost as a cost assignment matrix. That is, cost[i][j]     \\n\\\r\n      represents the cost of assigning i to j.      \\n\\\r\n    - Interprets assignment as a particular set of assignments. That is,    \\n\\\r\n      i is assigned to assignment[i].    \\n\\\r\n    - returns the cost of the given assignment. That is, returns    \\n\\\r\n      a number which is:    \\n\\\r\n        sum over i: cost[i][assignment[i]]   \" \r\n        );\r\n\r\n    m.def(\"make_sparse_vector\", _make_sparse_vector , \r\n\"This function modifies its argument so that it is a properly sorted sparse vector.    \\n\\\r\nThis means that the elements of the sparse vector will be ordered so that pairs    \\n\\\r\nwith smaller indices come first.  Additionally, there won't be any pairs with    \\n\\\r\nidentical indices.  If such pairs were present in the input sparse vector then    \\n\\\r\ntheir values will be added together and only one pair with their index will be    \\n\\\r\npresent in the output.   \" \r\n        );\r\n    m.def(\"make_sparse_vector\", _make_sparse_vector2 , \r\n        \"This function modifies a sparse_vectors object so that all elements it contains are properly sorted sparse vectors.\");\r\n\r\n    m.def(\"load_libsvm_formatted_data\",_load_libsvm_formatted_data, py::arg(\"file_name\"),\r\n\"ensures    \\n\\\r\n    - Attempts to read a file of the given name that should contain libsvm    \\n\\\r\n      formatted data.  The data is returned as a tuple where the first tuple    \\n\\\r\n      element is an array of sparse vectors and the second element is an array of    \\n\\\r\n      labels.    \" \r\n    );\r\n\r\n    m.def(\"save_libsvm_formatted_data\",_save_libsvm_formatted_data, py::arg(\"file_name\"), py::arg(\"samples\"), py::arg(\"labels\"),\r\n\"requires    \\n\\\r\n    - len(samples) == len(labels)    \\n\\\r\nensures    \\n\\\r\n    - saves the data to the given file in libsvm format   \" \r\n    );\r\n\r\n    m.def(\"hit_enter_to_continue\", hit_enter_to_continue, \r\n        \"Asks the user to hit enter to continue and pauses until they do so.\");\r\n\r\n\r\n\r\n\r\n    m.def(\"count_steps_without_decrease\",py_count_steps_without_decrease, py::arg(\"time_series\"), py::arg(\"probability_of_decrease\")=0.51,\r\n\"requires \\n\\\r\n    - time_series must be a one dimensional array of real numbers.  \\n\\\r\n    - 0.5 < probability_of_decrease < 1 \\n\\\r\nensures \\n\\\r\n    - If you think of the contents of time_series as a potentially noisy time \\n\\\r\n      series, then this function returns a count of how long the time series has \\n\\\r\n      gone without noticeably decreasing in value.  It does this by scanning along \\n\\\r\n      the elements, starting from the end (i.e. time_series[-1]) to the beginning, \\n\\\r\n      and checking how many elements you need to examine before you are confident \\n\\\r\n      that the series has been decreasing in value.  Here, \\\"confident of decrease\\\" \\n\\\r\n      means the probability of decrease is >= probability_of_decrease.   \\n\\\r\n    - Setting probability_of_decrease to 0.51 means we count until we see even a \\n\\\r\n      small hint of decrease, whereas a larger value of 0.99 would return a larger \\n\\\r\n      count since it keeps going until it is nearly certain the time series is \\n\\\r\n      decreasing. \\n\\\r\n    - The max possible output from this function is len(time_series). \\n\\\r\n    - The implementation of this function is done using the dlib::running_gradient \\n\\\r\n      object, which is a tool that finds the least squares fit of a line to the \\n\\\r\n      time series and the confidence interval around the slope of that line.  That \\n\\\r\n      can then be used in a simple statistical test to determine if the slope is \\n\\\r\n      positive or negative.\" \r\n    /*!\r\n        requires\r\n            - time_series must be a one dimensional array of real numbers. \r\n            - 0.5 < probability_of_decrease < 1\r\n        ensures\r\n            - If you think of the contents of time_series as a potentially noisy time\r\n              series, then this function returns a count of how long the time series has\r\n              gone without noticeably decreasing in value.  It does this by scanning along\r\n              the elements, starting from the end (i.e. time_series[-1]) to the beginning,\r\n              and checking how many elements you need to examine before you are confident\r\n              that the series has been decreasing in value.  Here, \"confident of decrease\"\r\n              means the probability of decrease is >= probability_of_decrease.  \r\n            - Setting probability_of_decrease to 0.51 means we count until we see even a\r\n              small hint of decrease, whereas a larger value of 0.99 would return a larger\r\n              count since it keeps going until it is nearly certain the time series is\r\n              decreasing.\r\n            - The max possible output from this function is len(time_series).\r\n            - The implementation of this function is done using the dlib::running_gradient\r\n              object, which is a tool that finds the least squares fit of a line to the\r\n              time series and the confidence interval around the slope of that line.  That\r\n              can then be used in a simple statistical test to determine if the slope is\r\n              positive or negative.\r\n    !*/\r\n    );\r\n\r\n    m.def(\"count_steps_without_decrease_robust\",py_count_steps_without_decrease_robust, py::arg(\"time_series\"), py::arg(\"probability_of_decrease\")=0.51, py::arg(\"quantile_discard\")=0.1,\r\n\"requires \\n\\\r\n    - time_series must be a one dimensional array of real numbers.  \\n\\\r\n    - 0.5 < probability_of_decrease < 1 \\n\\\r\n    - 0 <= quantile_discard <= 1 \\n\\\r\nensures \\n\\\r\n    - This function behaves just like \\n\\\r\n      count_steps_without_decrease(time_series,probability_of_decrease) except that \\n\\\r\n      it ignores values in the time series that are in the upper quantile_discard \\n\\\r\n      quantile.  So for example, if the quantile discard is 0.1 then the 10% \\n\\\r\n      largest values in the time series are ignored.\" \r\n    /*!\r\n        requires\r\n            - time_series must be a one dimensional array of real numbers. \r\n            - 0.5 < probability_of_decrease < 1\r\n            - 0 <= quantile_discard <= 1\r\n        ensures\r\n            - This function behaves just like\r\n              count_steps_without_decrease(time_series,probability_of_decrease) except that\r\n              it ignores values in the time series that are in the upper quantile_discard\r\n              quantile.  So for example, if the quantile discard is 0.1 then the 10%\r\n              largest values in the time series are ignored.\r\n    !*/\r\n    );\r\n\r\n    m.def(\"probability_that_sequence_is_increasing\",probability_that_sequence_is_increasing, py::arg(\"time_series\"),\r\n        \"returns the probability that the given sequence of real numbers is increasing in value over time.\");\r\n}\r\n\r\n", "meta": {"hexsha": "c495b6e8c22ca678069124d6e455202a20b1a9d7", "size": 11837, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tools/python/src/other.cpp", "max_stars_repo_name": "oms1226/dlib-19.13", "max_stars_repo_head_hexsha": "0bb55d112324edb700a42a3e6baca09c03967754", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tools/python/src/other.cpp", "max_issues_repo_name": "oms1226/dlib-19.13", "max_issues_repo_head_hexsha": "0bb55d112324edb700a42a3e6baca09c03967754", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tools/python/src/other.cpp", "max_forks_repo_name": "oms1226/dlib-19.13", "max_forks_repo_head_hexsha": "0bb55d112324edb700a42a3e6baca09c03967754", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.0037174721, "max_line_length": 186, "alphanum_fraction": 0.6341978542, "num_tokens": 2726, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6406358685621719, "lm_q2_score": 0.7718435083355188, "lm_q1q2_score": 0.4944706363565991}}
{"text": "/**\n * @author Andre Anjos <andre.anjos@idiap.ch>\n * @date Sun 27 Oct 09:02:32 2013\n *\n * @brief Uniform 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\n#include <boost/random.hpp>\n\nstatic auto uniform_doc = bob::extension::ClassDoc(\n  BOB_EXT_MODULE_PREFIX \".uniform\",\n  \"Models a random uniform distribution\",\n  \"On each invocation, it returns a random value uniformly distributed in the set of numbers [min, max] (integer) and [min, max[ (real-valued)\"\n)\n.add_constructor(bob::extension::FunctionDoc(\n  \"uniform\",\n  \"Constructs a new uniform distribution object\",\n  \"If the values ``min`` and ``max`` are not given, they are assumed to be ``min=0`` and ``max=9``, for integral distributions and ``min=0.0`` and ``max=1.0`` for real-valued distributions.\"\n)\n.add_prototype(\"dtype, [min], [max]\", \"\")\n.add_parameter(\"dtype\", \":py:class:`numpy.dtype` or anything that converts to a dtype\", \"The data type to get the distribution for\")\n.add_parameter(\"min\", \"dtype\", \"[Default: 0] The minimum value to draw\")\n.add_parameter(\"max\", \"dtype\", \"[Default: 1. (for real-valued ``dtype``) or 9 (for integral ``dtype``)] The maximum value to be drawn\")\n);\n\n/* How to create a new PyBoostUniformObject */\nstatic PyObject* PyBoostUniform_New(PyTypeObject* type, PyObject*, PyObject*) {\n\n  /* Allocates the python object itself */\n  PyBoostUniformObject* self = (PyBoostUniformObject*)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 PyBoostUniformObject */\nstatic void PyBoostUniform_Delete (PyBoostUniformObject* o) {\n  o->distro.reset();\n  Py_TYPE(o)->tp_free((PyObject*)o);\n}\n\nstatic boost::shared_ptr<void> make_uniform_bool() {\n  return boost::make_shared<boost::uniform_smallint<uint8_t>>(0, 1);\n}\n\ntemplate <typename T>\nboost::shared_ptr<void> make_uniform_int(PyObject* min, PyObject* max) {\n  T cmin = 0;\n  if (min) cmin = PyBlitzArrayCxx_AsCScalar<T>(min);\n  T cmax = 9;\n  if (max) cmax = PyBlitzArrayCxx_AsCScalar<T>(max);\n  return boost::make_shared<boost::uniform_int<T>>(cmin, cmax);\n}\n\ntemplate <typename T>\nboost::shared_ptr<void> make_uniform_real(PyObject* min, PyObject* max) {\n  T cmin = 0;\n  if (min) cmin = PyBlitzArrayCxx_AsCScalar<T>(min);\n  T cmax = 1;\n  if (max) cmax = PyBlitzArrayCxx_AsCScalar<T>(max);\n  return boost::make_shared<boost::uniform_real<T>>(cmin, cmax);\n}\n\nPyObject* PyBoostUniform_SimpleNew (int type_num, PyObject* min, PyObject* max) {\nBOB_TRY\n  if (type_num == NPY_BOOL && (min || max)) {\n    PyErr_Format(PyExc_ValueError, \"uniform distributions of boolean scalars cannot have a maximum or minimum\");\n    return 0;\n  }\n\n  PyBoostUniformObject* retval = (PyBoostUniformObject*)PyBoostUniform_New(&PyBoostUniform_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_BOOL:\n      retval->distro = make_uniform_bool();\n      break;\n    case NPY_UINT8:\n      retval->distro = make_uniform_int<uint8_t>(min, max);\n      break;\n    case NPY_UINT16:\n      retval->distro = make_uniform_int<uint16_t>(min, max);\n      break;\n    case NPY_UINT32:\n      retval->distro = make_uniform_int<uint32_t>(min, max);\n      break;\n    case NPY_UINT64:\n      retval->distro = make_uniform_int<uint64_t>(min, max);\n      break;\n    case NPY_INT8:\n      retval->distro = make_uniform_int<int8_t>(min, max);\n      break;\n    case NPY_INT16:\n      retval->distro = make_uniform_int<int16_t>(min, max);\n      break;\n    case NPY_INT32:\n      retval->distro = make_uniform_int<int32_t>(min, max);\n      break;\n    case NPY_INT64:\n      retval->distro = make_uniform_int<int64_t>(min, max);\n      break;\n    case NPY_FLOAT32:\n      retval->distro = make_uniform_real<float>(min, max);\n      break;\n    case NPY_FLOAT64:\n      retval->distro = make_uniform_real<double>(min, max);\n      break;\n    default:\n      PyErr_Format(PyExc_NotImplementedError, \"cannot create %s(T) with T having an unsupported numpy type number of %d\", 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 PyBoostUniform_Init(PyBoostUniformObject* self, PyObject *args, PyObject* kwds) {\nBOB_TRY\n  char** kwlist = uniform_doc.kwlist();\n\n  PyObject* min = 0;\n  PyObject* max = 0;\n\n  if (!PyArg_ParseTupleAndKeywords(args, kwds, \"O&|OO\", kwlist, &PyBlitzArray_TypenumConverter, &self->type_num, &min, &max)) return -1; ///< FAILURE\n\n  if (self->type_num == NPY_BOOL && (min || max)) {\n    PyErr_Format(PyExc_ValueError, \"uniform distributions of boolean scalars cannot have a maximum or minimum\");\n    return -1;\n  }\n\n  switch(self->type_num) {\n    case NPY_BOOL:\n      self->distro = make_uniform_bool();\n      break;\n    case NPY_UINT8:\n      self->distro = make_uniform_int<uint8_t>(min, max);\n      break;\n    case NPY_UINT16:\n      self->distro = make_uniform_int<uint16_t>(min, max);\n      break;\n    case NPY_UINT32:\n      self->distro = make_uniform_int<uint32_t>(min, max);\n      break;\n    case NPY_UINT64:\n      self->distro = make_uniform_int<uint64_t>(min, max);\n      break;\n    case NPY_INT8:\n      self->distro = make_uniform_int<int8_t>(min, max);\n      break;\n    case NPY_INT16:\n      self->distro = make_uniform_int<int16_t>(min, max);\n      break;\n    case NPY_INT32:\n      self->distro = make_uniform_int<int32_t>(min, max);\n      break;\n    case NPY_INT64:\n      self->distro = make_uniform_int<int64_t>(min, max);\n      break;\n    case NPY_FLOAT32:\n      self->distro = make_uniform_real<float>(min, max);\n      break;\n    case NPY_FLOAT64:\n      self->distro = make_uniform_real<double>(min, max);\n      break;\n    default:\n      PyErr_Format(PyExc_NotImplementedError, \"cannot create %s(T) with T having an unsupported numpy type number of %d\", 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 PyBoostUniform_Check(PyObject* o) {\n  if (!o) return 0;\n  return PyObject_IsInstance(o, reinterpret_cast<PyObject*>(&PyBoostUniform_Type));\n}\n\nint PyBoostUniform_Converter(PyObject* o, PyBoostUniformObject** a) {\n  if (!PyBoostUniform_Check(o)) return 0;\n  Py_INCREF(o);\n  (*a) = reinterpret_cast<PyBoostUniformObject*>(o);\n  return 1;\n}\n\n\nstatic auto min_doc = bob::extension::VariableDoc(\n  \"min\",\n  \"dtype\",\n  \"The smallest value that the distribution can produce\"\n);\ntemplate <typename T> PyObject* get_minimum_int(PyBoostUniformObject* self) {\n  return PyBlitzArrayCxx_FromCScalar(boost::static_pointer_cast<boost::uniform_int<T>>(self->distro)->min());\n}\n\ntemplate <typename T> PyObject* get_minimum_real(PyBoostUniformObject* self) {\n  return PyBlitzArrayCxx_FromCScalar(boost::static_pointer_cast<boost::uniform_real<T>>(self->distro)->min());\n}\n\n/**\n * Accesses the min value\n */\nstatic PyObject* PyBoostUniform_GetMin(PyBoostUniformObject* self) {\nBOB_TRY\n  switch (self->type_num) {\n    case NPY_BOOL:\n      Py_RETURN_FALSE;\n    case NPY_UINT8:\n      return get_minimum_int<uint8_t>(self);\n    case NPY_UINT16:\n      return get_minimum_int<uint16_t>(self);\n    case NPY_UINT32:\n      return get_minimum_int<uint32_t>(self);\n    case NPY_UINT64:\n      return get_minimum_int<uint64_t>(self);\n    case NPY_INT8:\n      return get_minimum_int<int8_t>(self);\n    case NPY_INT16:\n      return get_minimum_int<int16_t>(self);\n    case NPY_INT32:\n      return get_minimum_int<int32_t>(self);\n    case NPY_INT64:\n      return get_minimum_int<int64_t>(self);\n    case NPY_FLOAT32:\n      return get_minimum_real<float>(self);\n    case NPY_FLOAT64:\n      return get_minimum_real<double>(self);\n    default:\n      PyErr_Format(PyExc_NotImplementedError, \"cannot get minimum 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(\"min\", 0)\n}\n\n\nstatic auto max_doc = bob::extension::VariableDoc(\n  \"max\",\n  \"dtype\",\n  \"The largest value that the distributioncan produce\",\n  \"Integer uniform distributions are bound at [min, max], while real-valued distributions are bound at [min, max[.\"\n);\ntemplate <typename T> PyObject* get_maximum_int(PyBoostUniformObject* self) {\n  return PyBlitzArrayCxx_FromCScalar(boost::static_pointer_cast<boost::uniform_int<T>>(self->distro)->max());\n}\n\ntemplate <typename T> PyObject* get_maximum_real(PyBoostUniformObject* self) {\n  return PyBlitzArrayCxx_FromCScalar(boost::static_pointer_cast<boost::uniform_real<T>>(self->distro)->max());\n}\n\n/**\n * Accesses the max value\n */\nstatic PyObject* PyBoostUniform_GetMax(PyBoostUniformObject* self) {\nBOB_TRY\n  switch (self->type_num) {\n    case NPY_BOOL:\n      Py_RETURN_TRUE;\n    case NPY_UINT8:\n      return get_maximum_int<uint8_t>(self);\n    case NPY_UINT16:\n      return get_maximum_int<uint16_t>(self);\n    case NPY_UINT32:\n      return get_maximum_int<uint32_t>(self);\n    case NPY_UINT64:\n      return get_maximum_int<uint64_t>(self);\n    case NPY_INT8:\n      return get_maximum_int<int8_t>(self);\n    case NPY_INT16:\n      return get_maximum_int<int16_t>(self);\n    case NPY_INT32:\n      return get_maximum_int<int32_t>(self);\n    case NPY_INT64:\n      return get_maximum_int<int64_t>(self);\n    case NPY_FLOAT32:\n      return get_maximum_real<float>(self);\n    case NPY_FLOAT64:\n      return get_maximum_real<double>(self);\n    default:\n      PyErr_Format(PyExc_NotImplementedError, \"cannot get maximum 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(\"max\", 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 uniform distribution\"\n);\nstatic PyObject* PyBoostUniform_GetDtype(PyBoostUniformObject* self) {\nBOB_TRY\n  return Py_BuildValue(\"N\", PyArray_DescrFromType(self->type_num));\nBOB_CATCH_MEMBER(\"dtype\", 0)\n}\n\n\n\nstatic PyGetSetDef PyBoostUniform_getseters[] = {\n    {\n      dtype_doc.name(),\n      (getter)PyBoostUniform_GetDtype,\n      0,\n      dtype_doc.doc(),\n      0,\n    },\n    {\n      min_doc.name(),\n      (getter)PyBoostUniform_GetMin,\n      0,\n      min_doc.doc(),\n      0,\n    },\n    {\n      max_doc.name(),\n      (getter)PyBoostUniform_GetMax,\n      0,\n      max_doc.doc(),\n      0,\n    },\n    {0}  /* Sentinel */\n};\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_smallint(PyBoostUniformObject* self) {\n  boost::static_pointer_cast<boost::uniform_smallint<T>>(self->distro)->reset();\n  Py_RETURN_NONE;\n}\n\ntemplate <typename T> PyObject* reset_int(PyBoostUniformObject* self) {\n  boost::static_pointer_cast<boost::uniform_int<T>>(self->distro)->reset();\n  Py_RETURN_NONE;\n}\n\ntemplate <typename T> PyObject* reset_real(PyBoostUniformObject* self) {\n  boost::static_pointer_cast<boost::uniform_real<T>>(self->distro)->reset();\n  Py_RETURN_NONE;\n}\n\nstatic PyObject* PyBoostUniform_Reset(PyBoostUniformObject* self) {\nBOB_TRY\n  switch (self->type_num) {\n    case NPY_BOOL:\n      return reset_smallint<uint8_t>(self);\n    case NPY_UINT8:\n      return reset_int<uint8_t>(self);\n    case NPY_UINT16:\n      return reset_int<uint16_t>(self);\n    case NPY_UINT32:\n      return reset_int<uint32_t>(self);\n    case NPY_UINT64:\n      return reset_int<uint64_t>(self);\n    case NPY_INT8:\n      return reset_int<int8_t>(self);\n    case NPY_INT16:\n      return reset_int<int16_t>(self);\n    case NPY_INT32:\n      return reset_int<int32_t>(self);\n    case NPY_INT64:\n      return reset_int<int64_t>(self);\n    case NPY_FLOAT32:\n      return reset_real<float>(self);\n    case NPY_FLOAT64:\n      return reset_real<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\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 uniform distribution\")\n;\nstatic PyObject* call_bool(PyBoostUniformObject* self, PyBoostMt19937Object* rng) {\n  if (boost::static_pointer_cast<boost::uniform_smallint<uint8_t>>(self->distro)->operator()(*rng->rng)) Py_RETURN_TRUE;\n  Py_RETURN_FALSE;\n}\n\ntemplate <typename T> PyObject* call_int(PyBoostUniformObject* self, PyBoostMt19937Object* rng) {\n  return PyBlitzArrayCxx_FromCScalar(boost::static_pointer_cast<boost::uniform_int<T>>(self->distro)->operator()(*rng->rng));\n}\n\ntemplate <typename T> PyObject* call_real(PyBoostUniformObject* self, PyBoostMt19937Object* rng) {\n  return PyBlitzArrayCxx_FromCScalar(boost::static_pointer_cast<boost::uniform_real<T>>(self->distro)->operator()(*rng->rng));\n}\n\n/**\n * Calling a PyBoostUniformObject to generate a random number\n */\nstatic PyObject* PyBoostUniform_Call(PyBoostUniformObject* 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_BOOL:\n      return call_bool(self, rng);\n      break;\n    case NPY_UINT8:\n      return call_int<uint8_t>(self, rng);\n      break;\n    case NPY_UINT16:\n      return call_int<uint16_t>(self, rng);\n      break;\n    case NPY_UINT32:\n      return call_int<uint32_t>(self, rng);\n      break;\n    case NPY_UINT64:\n      return call_int<uint64_t>(self, rng);\n      break;\n    case NPY_INT8:\n      return call_int<int8_t>(self, rng);\n      break;\n    case NPY_INT16:\n      return call_int<int16_t>(self, rng);\n      break;\n    case NPY_INT32:\n      return call_int<int32_t>(self, rng);\n      break;\n    case NPY_INT64:\n      return call_int<int64_t>(self, rng);\n      break;\n    case NPY_FLOAT32:\n      return call_real<float>(self, rng);\n      break;\n    case NPY_FLOAT64:\n      return call_real<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\", Py_TYPE(self)->tp_name, self->type_num);\n  }\n\n  return 0; ///< FAILURE\nBOB_CATCH_MEMBER(\"call\", 0)\n}\n\nstatic PyMethodDef PyBoostUniform_methods[] = {\n    {\n      call_doc.name(),\n      (PyCFunction)PyBoostUniform_Call,\n      METH_VARARGS|METH_KEYWORDS,\n      call_doc.doc(),\n    },\n    {\n      reset_doc.name(),\n      (PyCFunction)PyBoostUniform_Reset,\n      METH_NOARGS,\n      reset_doc.doc(),\n    },\n    {0}  /* Sentinel */\n};\n\n\n\nextern PyObject* scalar_to_bytes(PyObject* s);\n\n/**\n * String representation and print out\n */\nstatic PyObject* PyBoostUniform_Repr(PyBoostUniformObject* self) {\nBOB_TRY\n  PyObject* smin = scalar_to_bytes(PyBoostUniform_GetMin(self));\n  if (!smin) return 0;\n  auto smin_ = make_safe(smin);\n  PyObject* smax = scalar_to_bytes(PyBoostUniform_GetMax(self));\n  if (!smax) return 0;\n  auto smax_ = make_safe(smax);\n\n  return\n    PyString_FromFormat\n      (\n       \"%s(dtype='%s', min=%s, max=%s)\",\n       Py_TYPE(self)->tp_name, PyBlitzArray_TypenumAsString(self->type_num),\n       PyString_AS_STRING(smin), PyString_AS_STRING(smax)\n      );\nBOB_CATCH_MEMBER(\"repr\", 0)\n}\n\n\nPyTypeObject PyBoostUniform_Type = {\n  PyVarObject_HEAD_INIT(0,0)\n  0\n};\n\nbool init_BoostUniform(PyObject* module)\n{\n  // initialize the type struct\n  PyBoostUniform_Type.tp_name = uniform_doc.name();\n  PyBoostUniform_Type.tp_basicsize = sizeof(PyBoostUniformObject);\n  PyBoostUniform_Type.tp_flags = Py_TPFLAGS_DEFAULT;\n  PyBoostUniform_Type.tp_doc = uniform_doc.doc();\n  PyBoostUniform_Type.tp_str = reinterpret_cast<reprfunc>(PyBoostUniform_Repr);\n  PyBoostUniform_Type.tp_repr = reinterpret_cast<reprfunc>(PyBoostUniform_Repr);\n\n  // set the functions\n  PyBoostUniform_Type.tp_new = PyBoostUniform_New;\n  PyBoostUniform_Type.tp_init = reinterpret_cast<initproc>(PyBoostUniform_Init);\n  PyBoostUniform_Type.tp_dealloc = reinterpret_cast<destructor>(PyBoostUniform_Delete);\n  PyBoostUniform_Type.tp_methods = PyBoostUniform_methods;\n  PyBoostUniform_Type.tp_getset = PyBoostUniform_getseters;\n  PyBoostUniform_Type.tp_call = reinterpret_cast<ternaryfunc>(PyBoostUniform_Call);\n\n  // check that everything is fine\n  if (PyType_Ready(&PyBoostUniform_Type) < 0) return false;\n\n  // add the type to the module\n  return PyModule_AddObject(module, \"uniform\", Py_BuildValue(\"O\", &PyBoostUniform_Type)) >= 0;\n}\n", "meta": {"hexsha": "7d3de0f5d64068d73aef5b1b89de1c2510ab5c9c", "size": 17330, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bob/core/random/uniform.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/uniform.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/uniform.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.5090909091, "max_line_length": 190, "alphanum_fraction": 0.702135026, "num_tokens": 4703, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.49447062963220056}}
{"text": "\n#include \"walker.h\"\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include \"ParseSpaceDelimited.h\"\n\nvoid cWalker::read(\n        const std::string &fname)\n    {\n        std::ifstream inf(fname);\n        if (!inf.is_open())\n        {\n            std::cout << \"cannot open \" << fname << \"\\n\";\n            exit(1);\n        }\n        myGrid.clear();\n        myRowCount = 0;\n        myColCount = -1;\n        std::string line;\n        while (std::getline(inf, line))\n        {\n            std::cout << line << \"\\n\";\n            auto token = ParseSpaceDelimited(line);\n            if (!token.size())\n                continue;\n            switch (token[0][0])\n            {\n            case 'h':\n            {\n                if (myColCount == -1)\n                    myColCount = token.size() - 1;\n                else if (token.size() - 1 != myColCount)\n                    throw std::runtime_error(\"Bad column count\");\n                std::vector<float> row;\n                for (int k = 1; k < token.size(); k++)\n                    row.push_back(atof(token[k].c_str()));\n                myGrid.push_back(row);\n            }\n            break;\n            case 's':\n                if (token.size() != 3)\n                    throw std::runtime_error(\"Bad start\");\n                myStartCol = atoi(token[1].c_str()) - 1;\n                myStartRow = atoi(token[2].c_str()) - 1;\n                break;\n            case 'e':\n                if (token.size() != 3)\n                    throw std::runtime_error(\"Bad end\");\n                myEndCol = atoi(token[1].c_str()) - 1;\n                myEndRow = atoi(token[2].c_str()) - 1;\n                break;\n            }\n        }\n        myRowCount = myGrid.size();\n    }\n\n    void cWalker::ConstructBoostGraph()\n    {\n        //std::cout << \"ConstructBoostGraph \" << myColCount << \" \" << myRowCount << \"\\n\";\n        for (int row = 0; row < myRowCount; row++)\n        {\n            for (int col = 0; col < myColCount; col++)\n            {\n                int n = findoradd(name(col, row));\n                myGraph[n].myHeight = myGrid[row][col];\n            }\n        }\n\n        for (int row = 0; row < myRowCount; row++)\n            for (int col = 0; col < myColCount; col++)\n            {\n                int n = find(name(col, row));\n                if (col > 0)\n                {\n                    int left = find(name(col - 1, row));\n                    float delta = myGrid[row][col] - myGrid[col - 1][row];\n                    AddLink(n, left, 1 + delta * delta);\n                }\n                if (col < myColCount - 1)\n                {\n                    int right = find(name(col + 1, row));\n                    float delta = myGrid[row][col] - myGrid[col + 1][row];\n                    AddLink(n, right, 1 + delta * delta);\n                }\n                if (row > 0)\n                {\n                    int up = find(name(col, row - 1));\n                    float delta = myGrid[row][col] - myGrid[col][row - 1];\n                    AddLink(n, up, 1 + delta * delta);\n                }\n                if (row < myRowCount - 1)\n                {\n                    int up = find(name(col, row + 1));\n                    float delta = myGrid[row][col] - myGrid[col][row + 1];\n                    AddLink(n, up, 1 + delta * delta);\n                }\n            }\n    }\n\n    void cWalker::Path()\n    {\n    // run dijkstra algorithm\n    int startNode = find(name(myStartCol, myStartRow));\n    std::vector<int> p(num_vertices(myGraph));\n    std::vector<int> vDist(num_vertices(myGraph));\n    boost::dijkstra_shortest_paths(\n        myGraph,\n        startNode,\n        weight_map(get(&cEdge::myCost, myGraph))\n            .predecessor_map(boost::make_iterator_property_map(\n                p.begin(), get(boost::vertex_index, myGraph)))\n            .distance_map(boost::make_iterator_property_map(\n                vDist.begin(), get(boost::vertex_index, myGraph))));\n\n        // pick out path, starting at goal and finishing at start\n    int goalnode = find(name(myEndCol,myEndRow));\n    myPath.push_back(goalnode);\n    int prev = goalnode;\n    while (1)\n    {\n        //std::cout << prev << \" \" << p[prev] << \", \";\n        int next = p[prev];\n        myPath.push_back(next);\n        if (next == startNode)\n            break;\n        prev = next;\n    }\n\n    // reverse so path goes from start to goal\n    std::reverse(myPath.begin(), myPath.end()); \n    }\n\n        std::string cWalker::linksText()\n    {\n        std::stringstream ss;\n        graph_traits<graph_t>::edge_iterator ei, ei_end;\n        for (tie(ei, ei_end) = edges(myGraph); ei != ei_end; ++ei)\n        {\n            ss << \"(\"\n               << myGraph[source(*ei, myGraph)].myName << \",\"\n               << myGraph[target(*ei, myGraph)].myName << \",\"\n               << myGraph[*ei].myCost\n               << \") \";\n        }\n        ss << \"\\n\";\n        return ss.str();\n    }\n\n        std::string cWalker::pathText()\n{\n    std::stringstream ss;\n    for (auto n : myPath)\n        ss << myGraph[n].myName << \" -> \";\n    ss << \"\\n\";\n    return ss.str();\n}\n\n    int cWalker::findoradd(const std::string &name)\n    {\n        int n = find(name);\n        if (n < 0)\n            n = add_vertex(name, myGraph);\n        return n;\n    }\n\n    int cWalker::find(const std::string &name)\n    {\n        for (int n = 0; n < num_vertices(myGraph); n++)\n        {\n            if (myGraph[n].myName == name)\n            {\n                return n;\n            }\n        }\n        return -1;\n    }\n    void cWalker::AddLink(int n, int m, float cost)\n    {\n        myGraph[add_edge(n, m, myGraph).first].myCost = cost;\n        myGraph[add_edge(m, n, myGraph).first].myCost = cost;\n    }\n    std::string cWalker::name(int col, int row)\n    {\n        return std::to_string(col+1) + \"_\" + std::to_string(row+1);\n    }\n\n", "meta": {"hexsha": "9a0b30de7fb8decaaec2dc3f7ebbf6f1a4fa18d4", "size": 5823, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/walker.cpp", "max_stars_repo_name": "JamesBremner/LazyHillWalker", "max_stars_repo_head_hexsha": "2bed28c291bea6f93db26de2bed603027b7d7c48", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-07T19:02:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-07T19:02:52.000Z", "max_issues_repo_path": "src/walker.cpp", "max_issues_repo_name": "JamesBremner/LazyHillWalker", "max_issues_repo_head_hexsha": "2bed28c291bea6f93db26de2bed603027b7d7c48", "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/walker.cpp", "max_forks_repo_name": "JamesBremner/LazyHillWalker", "max_forks_repo_head_hexsha": "2bed28c291bea6f93db26de2bed603027b7d7c48", "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.3064516129, "max_line_length": 89, "alphanum_fraction": 0.4502833591, "num_tokens": 1445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435083355187, "lm_q2_score": 0.6406358479787609, "lm_q1q2_score": 0.49447062046942686}}
{"text": "\n#ifndef __AST_BITVEC_HPP_DEFINED__\n#define __AST_BITVEC_HPP_DEFINED__\n\n#include <iostream>\n#include <string>\n#include <vector>\n#include <boost/shared_ptr.hpp>\n#include <boost/python.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/lexical_cast.hpp>\n\n#include <z3++.h>\n#include <assert.h>\n#include <type.hpp>\n\n#include <ast.hpp>\n\nnamespace ila \n{\n    class Abstraction;\n    class FuncReduction;\n\n    // ---------------------------------------------------------------------- //\n    // Bitvector expressions are derived from this class.\n    class BitvectorExpr : public Node {\n    public:\n        // constructor.\n        BitvectorExpr(int width);\n        // constructor for ChoiceExpr.\n        BitvectorExpr(NodeType t);\n        // destructor.\n        virtual ~BitvectorExpr();\n    };\n\n    // ---------------------------------------------------------------------- //\n    // Bitvector variables.\n    class BitvectorVar : public BitvectorExpr {\n    public:\n        // constructor.\n        BitvectorVar(const std::string& n, int width) ;\n        // destructor.\n        virtual ~BitvectorVar();\n        // clone.\n        virtual Node* clone() const;\n        // equality method.\n        virtual bool equal(const Node* that) const;\n        // stream output.\n        virtual std::ostream& write(std::ostream& out) const;\n    };\n\n    // ---------------------------------------------------------------------- //\n    // Bitvector constants.\n    class BitvectorConst : public BitvectorExpr {\n    protected:\n        mp_int_t value;\n    public:\n        // constructor with longs.\n        BitvectorConst(const mp_int_t& v, int width);\n        // constructor with ints.\n        BitvectorConst(unsigned int v, int width);\n        // copy constructor.\n        BitvectorConst(const BitvectorConst& other);\n        // destructor.\n        virtual ~BitvectorConst();\n        // clone\n        virtual Node* clone() const;\n        // equality method.\n        virtual bool equal(const Node* that) const;\n        // get value.\n        const mp_int_t& val() const { return value; }\n        // return value.\n        virtual py::object getValue() const;\n        // stream output.\n        virtual std::ostream& write(std::ostream& out) const;\n        // get the value as a string.\n        std::string vstr() const {\n            return boost::lexical_cast<std::string>(value);\n        }\n    };\n\n    // ---------------------------------------------------------------------- //\n    // Bitvector operators.\n    class BitvectorOp : public BitvectorExpr {\n    public:\n        // Number of operands.\n        enum Arity { UNARY, BINARY, TERNARY, NARY } arity; \n\n        // What is the operation?\n        enum Op { \n            // invalid\n            INVALID,\n            // unary\n            NEGATE, COMPLEMENT, \n            LROTATE, RROTATE, Z_EXT, S_EXT, EXTRACT,\n            // binary.\n            ADD, SUB, AND, OR, XOR, XNOR, NAND, NOR,\n            SDIV, UDIV, SREM, UREM, SMOD, SHL, LSHR, ASHR, \n            MUL, CONCAT, GET_BIT, READMEM, READMEMBLOCK,\n            // ternary\n            IF, APPLY_FUNC \n        } op;\n\n        static const std::string operatorNames[];\n\n    private:\n        // the operands themselves.\n        nptr_vec_t args;\n        std::vector< int > params;        \n\n        // Don't forget to update these helper functions below.\n        static bool isUnary(Op op) { \n            return op >= NEGATE && op <= EXTRACT; \n        }\n        static bool isBinary(Op op) { \n            return op >= ADD && op <= READMEMBLOCK;\n        }\n        static bool isTernary(Op op) { \n            return op >= IF && op <= IF; \n        }\n        static bool isNary(Op op) {\n            return op >= APPLY_FUNC && op <= APPLY_FUNC;\n        }\n        // helper functions to determine result and argument types.\n        static int getUnaryResultWidth(\n            Op op, \n            const nptr_t& n);\n        static int getBinaryResultWidth(\n            Op op, \n            const nptr_t& n1, \n            const nptr_t& n2);\n        static int getBinaryResultWidth(\n            Op op, \n            const nptr_t& n1, \n            const nptr_t& n2,\n            int param);\n        static int getBinaryResultWidth(\n            Op op,\n            const nptr_t& n1,\n            int param);\n        static int getNaryResultWidth(\n            Op op, nptr_vec_t& args);\n        static int getNaryResultWidth(\n            Op op, nptr_vec_t& args, \n            std::vector< int >& params);\n\n        static bool checkUnaryOpWidth(\n            Op op, const nptr_t& n, int width);\n        static int checkBinaryOpWidth(\n            Op op, \n            const nptr_t& n1, \n            const nptr_t& n2, \n            int width);\n        static int checkBinaryOpWidth(\n            Op op, \n            const nptr_t& n1, \n            const nptr_t& n2, \n            int param,\n            int width);\n        static int checkBinaryOpWidth(\n            Op op,\n            const nptr_t& n1,\n            int param,\n            int width);\n        static int checkNaryOpWidth(\n            Op op, nptr_vec_t& args,\n            int width);\n        static int checkNaryOpWidth(\n            Op op,\n            nptr_vec_t& args,\n            std::vector< int >& params,\n            int width);\n\n\n    public:\n        // constructors.\n        // Unary op\n        BitvectorOp(Op op, \n                    const nptr_t& n1);\n        BitvectorOp(Op op,\n                    const nptr_t& n1,\n                    int param);\n        BitvectorOp(Op op, \n                    const nptr_t& n1,\n                    int p1, int p2);\n        // Binary op\n        BitvectorOp(Op op, \n                    const nptr_t& n1, \n                    const nptr_t& n2);\n        // Binary op with params (read-block)\n        BitvectorOp(Op op, \n                    const nptr_t& n1,\n                    const nptr_t& n2,\n                    int blocks, endianness_t e);\n        // Ternary op\n        BitvectorOp(Op op,\n                    nptr_vec_t& args_);\n        // copy-constructor with a fresh set of args.\n        BitvectorOp(const BitvectorOp* other, \n                nptr_vec_t& args_);\n        // destructors.\n        virtual ~BitvectorOp();\n\n        // clone.\n        virtual Node* clone() const;\n\n        // equality method.\n        virtual bool equal(const Node* that) const;\n\n        // stream output.\n        virtual std::ostream& write(std::ostream& out) const;\n\n        // number of operands.\n        virtual unsigned nArgs() const;\n\n        // operand i.\n        virtual nptr_t arg(unsigned i) const;\n\n        Op getOp() const { return op; }\n\n        // number of params\n        unsigned nParams() const;\n\n        // the ith param.\n        int param(unsigned i) const;\n\n        friend class FuncReduction;\n    };\n}\n#endif\n", "meta": {"hexsha": "66f786235d435c087d7cc28365bcc545393e63cb", "size": 6772, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "py-tmpl-synth/include/ast/bitvec.hpp", "max_stars_repo_name": "pramodsu/ILA-Tools", "max_stars_repo_head_hexsha": "e76bd90cf356ada8dd6f848fb377f57c83322c71", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-29T03:51:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T03:51:27.000Z", "max_issues_repo_path": "py-tmpl-synth/include/ast/bitvec.hpp", "max_issues_repo_name": "pramodsu/ILA-Tools", "max_issues_repo_head_hexsha": "e76bd90cf356ada8dd6f848fb377f57c83322c71", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-06-25T08:49:22.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-25T08:49:22.000Z", "max_forks_repo_path": "py-tmpl-synth/include/ast/bitvec.hpp", "max_forks_repo_name": "pramodsu/ILA-Tools", "max_forks_repo_head_hexsha": "e76bd90cf356ada8dd6f848fb377f57c83322c71", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-06-26T11:31:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-01T20:16:21.000Z", "avg_line_length": 29.316017316, "max_line_length": 80, "alphanum_fraction": 0.5067926757, "num_tokens": 1520, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390746, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.49447061904075257}}
{"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_FUNCTION_EXPONENT_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_EXPONENT_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-ieee\n    Function object implementing exponent capabilities\n\n    Returns the exponent of the floating input.\n\n    @par Semantic:\n\n    @code\n    as_integer_t<T> r = exponent(x);\n    @endcode\n\n    is similar to:\n\n    @code\n    as_integer_t<T> r = ilogb(x);\n    @endcode\n\n    @par Note:\n\n     The sign \\f$ \\pm \\f$ , exponent e and mantissa m of a floating point entry x are related by\n    x = \\f$\\pm m\\times 2^e\\f$, with m between one (included) and two (excluded).\n\n    For integral type inputs exponent is always 0 and mantissa reduces to identity.\n\n    @see mantissa,  frexp, ldexp\n\n  **/\n  const boost::dispatch::functor<tag::exponent_> exponent = {};\n} }\n#endif\n\n#include <boost/simd/function/scalar/exponent.hpp>\n#include <boost/simd/function/simd/exponent.hpp>\n\n#endif\n", "meta": {"hexsha": "1af28b53274b9c1f684e5e06b2127c80eca550bd", "size": 1385, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/exponent.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/function/exponent.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/function/exponent.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": 24.7321428571, "max_line_length": 100, "alphanum_fraction": 0.6014440433, "num_tokens": 319, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.4944706084493045}}
{"text": "/*\n * Copyright 2011 Mario Mulansky\n * Copyright 2012 Karsten Ahnert\n *\n * Distributed under the Boost Software License, Version 1.0.\n * (See accompanying file LICENSE_1_0.txt or\n * copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n\n\n#include <boost/array.hpp>\n\n//#include <boost/numeric/odeint/stepper/explicit_generic_rk.hpp>\n#include <boost/numeric/odeint/stepper/runge_kutta4.hpp>\n#include <boost/numeric/odeint/algebra/array_algebra.hpp>\n\n#include \"rk_performance_test_case.hpp\"\n\n#include \"lorenz.hpp\"\n\nusing namespace boost::numeric::odeint;\n\ntypedef boost::array< double , 3 > state_type;\n\n/*\ntypedef explicit_generic_rk< 4 , 4 , state_type , double , state_type , double , array_algebra > rk4_type;\n\ntypedef rk4_type::coef_a_type coef_a_type;\ntypedef rk4_type::coef_b_type coef_b_type;\ntypedef rk4_type::coef_c_type coef_c_type;\n\nconst boost::array< double , 1 > a1 = {{ 0.5 }};\nconst boost::array< double , 2 > a2 = {{ 0.0 , 0.5 }};\nconst boost::array< double , 3 > a3 = {{ 0.0 , 0.0 , 1.0 }};\n\nconst coef_a_type a = fusion::make_vector( a1 , a2 , a3 );\nconst coef_b_type b = {{ 1.0/6 , 1.0/3 , 1.0/3 , 1.0/6 }};\nconst coef_c_type c = {{ 0.0 , 0.5 , 0.5 , 1.0 }};\n*/\n\ntypedef runge_kutta4< state_type , double , state_type , double , array_algebra > rk4_type;\n\n\nclass rk4_wrapper\n{\n\npublic:\n\n    rk4_wrapper()\n    //        : m_stepper( a , b , c ) \n    {}\n\n    void reset_init_cond()\n    {\n        m_x[0] = 10.0 * rand() / RAND_MAX;\n        m_x[1] = 10.0 * rand() / RAND_MAX;\n        m_x[2] = 10.0 * rand() / RAND_MAX;\n        m_t = 0.0;\n    }\n\n    inline void do_step( const double dt )\n    {\n        m_stepper.do_step( lorenz(), m_x , m_t , dt );\n    }\n\n    double state( const size_t i ) const\n    { return m_x[i]; }\n\nprivate:\n    state_type m_x;\n    double m_t;\n    rk4_type m_stepper;\n};\n\n\n\nint main()\n{\n    srand( 12312354 );\n\n    rk4_wrapper stepper;\n\n    run( stepper );\n}\n", "meta": {"hexsha": "0d097564636530d45845f0a74af9a23412408ccb", "size": 1891, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/boost_1_56_0/libs/numeric/odeint/performance/generic_odeint_rk4_lorenz.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": 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/generic_odeint_rk4_lorenz.cpp", "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/generic_odeint_rk4_lorenz.cpp", "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": 22.2470588235, "max_line_length": 106, "alphanum_fraction": 0.6425171867, "num_tokens": 610, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.4944706017249059}}
{"text": "// Copyright (c) 2022 hs293go\n//\n// This software is released under the MIT License.\n// https://opensource.org/licenses/MIT\n\n#include <pybind11/attr.h>\n#include <pybind11/embed.h>\n#include <pybind11/numpy.h>\n#include <pybind11/pybind11.h>\n#include <pybind11/pytypes.h>\n\n#include <Eigen/Dense>\n#include <cmath>\n\n#define IMPORT_FROM(m, fn) auto fn = m.attr(#fn);\n\nnamespace py = pybind11;\nusing namespace pybind11::literals;\nint main() {\n  const Eigen::VectorXd xv_data = Eigen::VectorXd::LinSpaced(10000, -4, 4);\n  const Eigen::VectorXd yv_data =\n      xv_data.unaryExpr([](double it) { return tgamma(it); });\n\n  py::scoped_interpreter interp{};\n  auto sns = py::module::import(\"seaborn\");\n  IMPORT_FROM(sns, set_style);\n  set_style(\"darkgrid\");\n\n  auto plt = py::module::import(\"matplotlib.pyplot\");\n  IMPORT_FROM(plt, plot);\n  IMPORT_FROM(plt, show);\n  IMPORT_FROM(plt, ylim);\n  IMPORT_FROM(plt, legend);\n  IMPORT_FROM(plt, xlabel);\n  IMPORT_FROM(plt, ylabel);\n  IMPORT_FROM(plt, title);\n  IMPORT_FROM(plt, savefig);\n\n  py::array xv(xv_data.size(), xv_data.data());\n  py::array yv(yv_data.size(), yv_data.data());\n\n  plot(xv, yv, \"--\", \"linewidth\"_a = 3,\n       \"color\"_a = py::make_tuple(0, 0.4, 0.8, 0.6),\n       \"label\"_a = \"Function Value\");\n  ylim(py::make_tuple(-10, 10));\n  xlabel(\"x\");\n  ylabel(R\"($f(x) = \\gamma(x)$)\");\n  title(R\"(Gamma Function: $\\gamma(z) = \\int_0^\\infty x^{z-1} e^{-x} dx$)\",\n        \"fontsize\"_a = 18);\n  savefig(\"res/detailed.png\");\n  show();\n}", "meta": {"hexsha": "3525a94b8b09a27775a017ed343adffa0df81209", "size": 1476, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/demo_pyplot_detailed.cpp", "max_stars_repo_name": "Hs293Go/demo_pybind11_matplotlib", "max_stars_repo_head_hexsha": "15bc5df7d3f3911b54721fc194a93d471c2876a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/demo_pyplot_detailed.cpp", "max_issues_repo_name": "Hs293Go/demo_pybind11_matplotlib", "max_issues_repo_head_hexsha": "15bc5df7d3f3911b54721fc194a93d471c2876a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/demo_pyplot_detailed.cpp", "max_forks_repo_name": "Hs293Go/demo_pybind11_matplotlib", "max_forks_repo_head_hexsha": "15bc5df7d3f3911b54721fc194a93d471c2876a6", "max_forks_repo_licenses": ["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.3846153846, "max_line_length": 75, "alphanum_fraction": 0.6558265583, "num_tokens": 460, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059775, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.4944254184195846}}
{"text": "#ifndef NNQS_OPTIMIZERS_RMSPROP_HPP\n#define NNQS_OPTIMIZERS_RMSPROP_HPP\n#include <Eigen/Dense>\n#include <type_traits>\n\n#include <complex>\n#include \"Utilities/type_traits.hpp\"\n#include \"Optimizers/Optimizer.hpp\"\n\nnamespace yannq\n{\ntemplate <typename T>\nclass RMSProp\n\t: public OptimizerGeometry<T>\n{\npublic:\n\tusing typename OptimizerGeometry<T>::RealT;\n\tusing typename OptimizerGeometry<T>::Vector;\n\tusing typename OptimizerGeometry<T>::RealVector;\n\nprivate:\n\tconst double alpha_;\n\tconst double beta_;\n\tconst double eps_;\n\n\tint t_;\n\tRealVector v_;\n\npublic:\n\tstatic constexpr double DEFAULT_PARAMS[] = {0.05, 0.9, 1e-8};\n\n\tstatic nlohmann::json defaultParams()\n\t{\n\t\treturn nlohmann::json\n\t\t{\n\t\t\t{\"name\", \"RMSProp\"},\n\t\t\t{\"alhpa\", DEFAULT_PARAMS[0]},\n\t\t\t{\"beta\", DEFAULT_PARAMS[1]},\n\t\t\t{\"eps\", DEFAULT_PARAMS[2]},\n\t\t};\n\t}\n\n\tnlohmann::json desc() const override\n\t{\n\t\treturn nlohmann::json\n\t\t{\n\t\t\t{\"name\", \"RMSProp\"},\n\t\t\t{\"alhpa\", alpha_},\n\t\t\t{\"beta\", beta_},\n\t\t\t{\"eps\", eps_},\n\t\t};\n\t}\n\n\tRMSProp(const nlohmann::json& params)\n\t\t: alpha_(params.value(\"alpha\", DEFAULT_PARAMS[0])), \n\t\t\tbeta_(params.value(\"beta\", DEFAULT_PARAMS[1])),\n\t\t\teps_(params.value(\"eps\", DEFAULT_PARAMS[2])),\n\t\t\t t_{}\n\t{\n\t}\n\n\t//use oloc to estimate local geometry \n\tVector getUpdate(const Vector& grad, const Vector& oloc) override\n\t{\n\t\tauto sqr = [](T x) -> RealT {\n\t\t\treturn std::norm(x);\n\t\t};\n\n\t\tif(t_ == 0)\n\t\t{\n\t\t\tv_ = RealVector::Zero(grad.rows());\n\t\t}\n\t\t++t_;\n\n\t\tRealVector g = oloc.unaryExpr(sqr);\n\t\tv_ *= beta_;\n\t\tv_ += (1-beta_)*g;\n\n\t\tRealVector denom = v_.unaryExpr([eps = this->eps_](RealT x){ return sqrt(x)+eps; });\n\t\treturn -alpha_*grad.cwiseQuotient(denom);\n\t}\n};\n\ntemplate<typename T>\nconstexpr double RMSProp<T>::DEFAULT_PARAMS[];\n\n} //namespace yannq\n#endif//NNQS_OPTIMIZERS_RMSPROP_HPP\n", "meta": {"hexsha": "0fc8469cfec6376cdd6138e4ed42f8bde1d04e9f", "size": 1771, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Yannq/Optimizers/RMSProp.hpp", "max_stars_repo_name": "cecri/yannq", "max_stars_repo_head_hexsha": "b78c1f86a255059f06b34dd5e538449e7261d0ee", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Yannq/Optimizers/RMSProp.hpp", "max_issues_repo_name": "cecri/yannq", "max_issues_repo_head_hexsha": "b78c1f86a255059f06b34dd5e538449e7261d0ee", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Yannq/Optimizers/RMSProp.hpp", "max_forks_repo_name": "cecri/yannq", "max_forks_repo_head_hexsha": "b78c1f86a255059f06b34dd5e538449e7261d0ee", "max_forks_repo_licenses": ["BSD-3-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.8988764045, "max_line_length": 86, "alphanum_fraction": 0.6758893281, "num_tokens": 547, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.4944254184195845}}
{"text": "//  Copyright John Maddock 2005.\r\n//  Copyright Paul A. Bristow 2010\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 <boost/array.hpp>\r\n#include \"functor.hpp\"\r\n\r\n#include \"handle_test_result.hpp\"\r\n#include \"table_type.hpp\"\r\n\r\n\r\ntemplate <class Real, class T>\r\nvoid do_test(const T& data, const char* type_name, const char* test_name)\r\n{\r\n   typedef typename T::value_type row_type;\r\n   typedef Real value_type;\r\n\r\n   typedef value_type (*pg)(value_type);\r\n#if defined(BOOST_MATH_NO_DEDUCED_FUNCTION_POINTERS)\r\n   pg funcp = &boost::math::log1p<value_type>;\r\n#else\r\n   pg funcp = &boost::math::log1p;\r\n#endif\r\n\r\n   boost::math::tools::test_result<value_type> result;\r\n   std::cout << \"Testing \" << test_name << \" with type \" << type_name\r\n      << \"\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\";\r\n   //\r\n   // test log1p against data:\r\n   //\r\n#if defined(BOOST_MATH_NO_DEDUCED_FUNCTION_POINTERS)\r\n   funcp = boost::math::log1p<value_type>;\r\n#else\r\n   funcp = &boost::math::log1p;\r\n#endif\r\n   result = boost::math::tools::test_hetero<Real>(\r\n      data, \r\n         bind_func<Real>(funcp, 0), \r\n         extract_result<Real>(1));\r\n   handle_test_result(result, data[result.worst()], result.worst(), type_name, \"boost::math::log1p\", \"log1p and expm1\");\r\n   std::cout << std::endl;\r\n   //\r\n   // test expm1 against data:\r\n   //\r\n#if defined(BOOST_MATH_NO_DEDUCED_FUNCTION_POINTERS)\r\n   funcp = boost::math::expm1<value_type>;\r\n#else\r\n   funcp = boost::math::expm1;\r\n#endif\r\n   result = boost::math::tools::test_hetero<Real>(\r\n      data, \r\n      bind_func<Real>(funcp, 0), \r\n      extract_result<Real>(2));\r\n   handle_test_result(result, data[result.worst()], result.worst(), type_name, \"boost::math::expm1\", \"log1p and expm1\");\r\n   std::cout << std::endl;\r\n}\r\n\r\ntemplate <class T>\r\nvoid test(T, const char* type_name)\r\n{\r\n#  include \"log1p_expm1_data.ipp\"\r\n\r\n   do_test<T>(log1p_expm1_data, type_name, \"expm1 and log1p\");\r\n\r\n   //\r\n   // C99 Appendix F special cases:\r\n   static const T zero = 0;\r\n   static const T m_one = -1;\r\n   BOOST_CHECK_EQUAL(boost::math::log1p(zero), zero);\r\n   BOOST_CHECK_EQUAL(boost::math::log1p(-zero), zero);\r\n   BOOST_CHECK_EQUAL(boost::math::expm1(zero), zero);\r\n   if(std::numeric_limits<T>::has_infinity)\r\n   {\r\n      BOOST_CHECK_EQUAL(boost::math::log1p(m_one), -std::numeric_limits<T>::infinity());\r\n      BOOST_CHECK_EQUAL(boost::math::expm1(-std::numeric_limits<T>::infinity()), m_one);\r\n      BOOST_CHECK_EQUAL(boost::math::expm1(std::numeric_limits<T>::infinity()), std::numeric_limits<T>::infinity());\r\n#ifndef __BORLANDC__\r\n      // When building with Borland's compiler, simply the *presence*\r\n      // of these tests cause other unrelated tests to fail!!! :-(\r\n      using namespace boost::math::policies;\r\n      typedef policy<overflow_error<throw_on_error> > pol;\r\n      BOOST_CHECK_THROW(boost::math::log1p(m_one, pol()), std::overflow_error);\r\n      BOOST_CHECK_THROW(boost::math::expm1(std::numeric_limits<T>::infinity(), pol()), std::overflow_error);\r\n#endif\r\n   }\r\n}\r\n\r\n", "meta": {"hexsha": "d516aa928f40c0d771c9e3bdef3f34267567a534", "size": 3201, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/math/test/log1p_expm1_test.hpp", "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/math/test/log1p_expm1_test.hpp", "max_issues_repo_name": "xiaoliang2121/Boost", "max_issues_repo_head_hexsha": "fc90c3fde129c62565c023f091eddc4a7ed9902b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-03-19T08:23:23.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-24T07:48:47.000Z", "max_forks_repo_path": "libs/math/test/log1p_expm1_test.hpp", "max_forks_repo_name": "xiaoliang2121/Boost", "max_forks_repo_head_hexsha": "fc90c3fde129c62565c023f091eddc4a7ed9902b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 35.5666666667, "max_line_length": 121, "alphanum_fraction": 0.6522961575, "num_tokens": 866, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754607093178, "lm_q2_score": 0.6791786861878392, "lm_q1q2_score": 0.4944254169815414}}
{"text": "/**\n * @file ipdgfem_test_mastersolution.cc\n * @brief NPDE homework IPDGFEM code\n * @author Philippe Peter\n * @date 22.11.2019\n * @copyright Developed at ETH Zurich\n */\n\n// HACK:\n#undef SOLUTION\n#define SOLUTION 1\n\n#include \"../ipdgfem.h\"\n\n#include <gtest/gtest.h>\n\n#include <Eigen/Core>\n\nnamespace IPDGFEM::test {\n\nTEST(NewProblem, dummyFunction) {\n  double x = 0.0;\n  int n = 0;\n\n  Eigen::Vector2d v = IPDGFEM::dummyFunction(x, n);\n\n  Eigen::Vector2d v_ref = {1.0, 1.0};\n\n  double tol = 1.0e-8;\n  ASSERT_NEAR(0.0, (v - v_ref).lpNorm<Eigen::Infinity>(), tol);\n}\n\n}  // namespace IPDGFEM::test\n", "meta": {"hexsha": "651c079809c1ce45162e90b2dfbb8db984ed6187", "size": 594, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/IPDGFEM/templates/test/ipdgfem_test.cc", "max_stars_repo_name": "padomu/NPDECODES", "max_stars_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/IPDGFEM/templates/test/ipdgfem_test.cc", "max_issues_repo_name": "padomu/NPDECODES", "max_issues_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/IPDGFEM/templates/test/ipdgfem_test.cc", "max_forks_repo_name": "padomu/NPDECODES", "max_forks_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 17.4705882353, "max_line_length": 63, "alphanum_fraction": 0.664983165, "num_tokens": 199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6791786861878392, "lm_q2_score": 0.7279754489059775, "lm_q1q2_score": 0.4944254089649643}}
{"text": "#include <array>\n#include <deque>\n#include <iostream>\n#include <iterator>\n#include <tuple>\n#include <vector>\n\n#include <catch2/catch.hpp>\n#include <boost/iterator/transform_iterator.hpp>\n#include <boost/range/irange.hpp>\n#include <boost/range/adaptor/filtered.hpp>\n#include <boost/range/adaptor/transformed.hpp>\n\n#include <dirprod/range.hpp>\n\nnamespace std\n{\n    template<class... Ts>\n    std::ostream& operator<<(std::ostream& os, const std::tuple<Ts...>& t)\n    {\n        return std::apply([&os](const auto& x0, const auto&... xs) -> decltype(auto) {\n            os << \"(\" << x0;\n            (..., (os << \",\" << xs));\n            return os << \")\";\n        }, t);\n    }\n}\n\nTEST_CASE(\"iterator types\")\n{\n    std::vector<int> i0{{7, 9, 24}};\n    std::deque<char> i1{{'a', 'b', 'c'}};\n    auto i2 = boost::irange(7, 50);\n\n    auto r = dirprod::range(i0, i1, i2);\n    using iterator_t = decltype(r.begin());\n\n    static_assert(std::is_same_v<typename std::iterator_traits<iterator_t>::value_type, std::tuple<int, char, int>>);\n    static_assert(std::is_same_v<typename std::iterator_traits<iterator_t>::reference, std::tuple<int&, char&, int>>);\n\n    REQUIRE(r.begin() != r.end());\n}\n\nTEST_CASE(\"different types\")\n{\n    enum Components { Y, Cb, Cr, COMPONENTS_SIZE };\n    enum Modes { DC, PLANAR, HORIZONTAL, VERTICAL, ANGLE45, MODES_SIZE };\n\n    std::vector<Components> components{{Y, Cb, Cr}};\n    std::deque<bool> booleans{false, true};\n    std::array<Modes, MODES_SIZE> modes{{DC, PLANAR, HORIZONTAL, VERTICAL, ANGLE45}};\n\n    auto range = dirprod::range(components, booleans, modes);\n\n    SECTION(\"iterators\")\n    {\n        auto it = range.begin();\n        auto last = range.end();\n\n        for (int mode = DC; mode < MODES_SIZE; ++mode)\n        {\n            for (int boolean = 0; boolean < 2; ++boolean)\n            {\n                for (int compid = Y; compid < COMPONENTS_SIZE; ++compid, ++it)\n                {\n                    REQUIRE(it != last);\n                    auto [tcompid, tboolean, tmode] = *it;\n                    CHECK(tcompid == compid);\n                    CHECK(tboolean == boolean);\n                    CHECK(tmode == mode);\n                }\n            }\n        }\n\n        REQUIRE(it == last);\n    }\n\n    SECTION(\"for loop\")\n    {\n        for (const auto& [component, boolean, mode] : range)\n        {\n            (void)boolean; // suppress warning\n            CHECK(component < COMPONENTS_SIZE);\n            CHECK(mode < MODES_SIZE);\n        }\n    }\n}\n\nTEST_CASE(\"ranges\")\n{\n    auto range0 = boost::irange(0, 2);\n    auto range1 = boost::irange(0, 1);\n    auto range2 = boost::irange(0, 3);\n\n    auto range = dirprod::range(range0, range1, range2);\n    auto it = range.begin();\n    auto last = range.end();\n\n    REQUIRE(it != last);\n\n    CHECK(*it++ == std::make_tuple(0, 0, 0));\n    CHECK(*it++ == std::make_tuple(1, 0, 0));\n    CHECK(*it++ == std::make_tuple(0, 0, 1));\n    CHECK(*it++ == std::make_tuple(1, 0, 1));\n    CHECK(*it++ == std::make_tuple(0, 0, 2));\n    CHECK(*it++ == std::make_tuple(1, 0, 2));\n\n    CHECK(it == last);\n}\n\nTEST_CASE(\"with iterators\")\n{\n    auto range0 = boost::irange(0, 10);\n    auto range1 = boost::irange(7, 19);\n\n    auto range = dirprod::range(range0, range1);\n    auto it = range.begin();\n    auto last = range.end();\n\n    for (int i0 = 0, i1 = 7; it != last; ++it)\n    {\n        auto [r0, r1] = *it;\n        CHECK(r0 == i0);\n        CHECK(r1 == i1);\n\n        if (++i0 >= 10)\n        {\n            ++i1;\n            i0 = 0;\n        }\n    }\n}\n\nTEST_CASE(\"one element\")\n{\n    SECTION(\"by reference\")\n    {\n        std::vector x{4, 5, 6, 9, 47};\n        auto rng = dirprod::range{x};\n        auto it = rng.begin();\n\n        CHECK(*it++ == 4);\n        CHECK(*it++ == 5);\n        CHECK(*it++ == 6);\n        CHECK(*it++ == 9);\n        CHECK(*it++ == 47);\n        CHECK(it == rng.end());\n    }\n\n    SECTION(\"by prvalue\")\n    {\n        auto rng = dirprod::range{std::vector{1, 2, 8}};\n        auto it = rng.begin();\n\n        CHECK(*it++ == 1);\n        CHECK(*it++ == 2);\n        CHECK(*it++ == 8);\n        CHECK(it == rng.end());\n    }\n}\n\nTEST_CASE(\"move ranges\")\n{\n    auto rng = dirprod::range(boost::irange(0, 11), std::vector<double>({7, 55.2, 3.17, -8.5}));\n    auto it = rng.begin();\n\n    for (int i = 0; i < 11; ++i) //!< \\todo std::advance(it2, std::make_tuple(0, 1))\n        ++it;\n\n    REQUIRE(it != rng.end());\n    CHECK(*it == std::make_tuple(0, 55.2));\n}\n\nTEST_CASE(\"direct random access\")\n{\n    auto rng = dirprod::range(boost::irange(0, 11), boost::irange(7, 55), boost::irange(13, 40));\n    auto it = rng.begin();\n\n    CHECK(*(it + (3 + 11 * 8 + 11 * (55 - 7) * 1)) == std::make_tuple(3, 15, 14));\n    CHECK(*it == std::make_tuple(0, 7, 13));\n    CHECK(*(it + ((40 - 13) * (55 - 7) * (11 - 0) - 1)) == std::make_tuple(10, 54, 39));\n    CHECK(*(it + ((40 - 13) * (55 - 7) * (11 - 0))) == std::make_tuple(0, 7, 40));\n}\n\nTEST_CASE(\"const range\")\n{\n    std::vector<int> r0{{1, 2, 3}};\n    const std::vector<int> r1{{4, 5, 6}};\n\n    auto rng = dirprod::range(r0, r1);\n    auto it = rng.begin();\n\n    REQUIRE(it != rng.end());\n    CHECK(*(it + 2 + 3 * 1) == std::make_tuple(3, 5));\n}\n\nTEST_CASE(\"c-array\")\n{\n    int a[] = {7, 5, 6, 33, 76, 12};\n    auto even = [](auto x) { return x % 2 == 0; };\n    auto rng = dirprod::range(a, a | boost::adaptors::filtered(std::cref(even)));\n    auto it = std::begin(rng);\n\n    REQUIRE(it != std::end(rng));\n    CHECK(*it == std::make_tuple(7, 6));\n}\n\nTEST_CASE(\"boost::filtered\")\n{\n    int a[] = {5, 8, 68, 21, 7, 89, 44};\n    auto is_even = [](auto x) { const auto [a, b] = x; return a % 2 == 0 && b % 2 == 0; };\n    auto original_rng = dirprod::range(a, boost::irange(0, 7));\n    auto rng = original_rng | boost::adaptors::filtered(std::cref(is_even));\n    auto it = rng.begin();\n\n    REQUIRE(std::distance(it, rng.end()) == 12);\n\n    CHECK(*it++ == std::make_tuple(8, 0));\n    CHECK(*it++ == std::make_tuple(68, 0));\n    CHECK(*it++ == std::make_tuple(44, 0));\n    CHECK(*it++ == std::make_tuple(8, 2));\n    CHECK(*it++ == std::make_tuple(68, 2));\n    CHECK(*it++ == std::make_tuple(44, 2));\n    CHECK(*it == std::make_tuple(8, 4));\n}\n", "meta": {"hexsha": "3285807fb95428ea320e7a6c1708eedf0ae889d7", "size": 6148, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/dirprod.cpp", "max_stars_repo_name": "igsha/cartesian_product", "max_stars_repo_head_hexsha": "a27b4f0338f7641cd1c6c15f6782d95ad04562a3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/dirprod.cpp", "max_issues_repo_name": "igsha/cartesian_product", "max_issues_repo_head_hexsha": "a27b4f0338f7641cd1c6c15f6782d95ad04562a3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2019-02-24T14:33:53.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-20T20:12:54.000Z", "max_forks_repo_path": "tests/dirprod.cpp", "max_forks_repo_name": "igsha/dirprod", "max_forks_repo_head_hexsha": "a27b4f0338f7641cd1c6c15f6782d95ad04562a3", "max_forks_repo_licenses": ["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.203539823, "max_line_length": 118, "alphanum_fraction": 0.5214703969, "num_tokens": 1947, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754371026368, "lm_q2_score": 0.679178686187839, "lm_q1q2_score": 0.4944254009483867}}
{"text": "#include <iostream>\n#include <vector>\n#include <random>\n\n#include <Eigen/Dense>\n#include <opencv2/core/core.hpp>\n#include <opencv2/core/eigen.hpp>\n#include <opencv2/core/types_c.h>\n#include <opencv2/imgproc/imgproc.hpp>\n#include <opencv2/calib3d/calib3d.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/features2d.hpp>\n#include <opencv2/imgcodecs.hpp>\n#include <opencv2/opencv.hpp>\n\n#include <Geometry/ConvexPolygon.hpp>\n#include <Solvers/Image.hpp>\n#include <Solvers/Ransac.hpp>\n\n#include \"Panorama/Utility.hpp\"\n\nstruct WarpBounds\n{\n    cv::Size size{0, 0};\n    cv::Mat targetFrameHomography;\n};\n\ncv::Mat eigenToCv(const Eigen::Matrix3d &rhs)\n{\n    cv::Mat m = (cv::Mat_<double>(3,3) <<\n        rhs(0, 0), rhs(0, 1), rhs(0, 2),\n        rhs(1, 0), rhs(1, 1), rhs(1, 2),\n        rhs(2, 0), rhs(2, 1), rhs(2, 2) );\n\n    return m;\n}\n\nWarpBounds getWarpedBounds(const cv::Size &sourceImageSize,\n                           const cv::Size &targetImageSize,\n                           const cv::Mat &homography)\n{\n    // Set the output of sourceWarped to be the max height and max width of the\n    // warped image.  Due to the homography property that straight lines will\n    // stay straight after being transformed, this can be determined by getting\n    // the coordinates of the four corners of the image after being transformed.\n    // The maximum x and y-coordinates of the four remapped points will be used.\n\n    // Each of these points will be represented in homogenous coordinates.\n    // Simply appending 1 assumes the imager plane is of unit distance from the\n    // viewer.\n    std::array<cv::Vec3d, 4> corners({\n        cv::Vec3d(0, 0, 1),\n        cv::Vec3d(sourceImageSize.width, 0, 1),\n        cv::Vec3d(0, sourceImageSize.height, 1),\n        cv::Vec3d(sourceImageSize.width, sourceImageSize.height, 1)});\n\n    double minWidth = std::numeric_limits<double>::infinity();\n    double minHeight = std::numeric_limits<double>::infinity();\n    double maxWidth = -std::numeric_limits<double>::infinity();\n    double maxHeight = -std::numeric_limits<double>::infinity();\n    for (auto &corner : corners)\n    {\n        // Transform corner. Note that values in the output matrix can be\n        // negative!\n        const auto tmpCorner = cv::Mat(homography * corner);\n\n        // Convert homogenous coordinates back to the imager plane coordinates.\n        const auto &z = tmpCorner.at<double>(0, 2);\n        cv::Point2d tmpPoint(tmpCorner.at<double>(0, 0)/z,\n                             tmpCorner.at<double>(0, 1)/z);\n\n        minWidth = std::min(tmpPoint.x, minWidth);\n        minHeight = std::min(tmpPoint.y, minHeight);\n\n        maxWidth = std::max(tmpPoint.x, maxWidth);\n        maxHeight = std::max(tmpPoint.y, maxHeight);\n    }\n\n    auto width = static_cast<int>(maxWidth-minWidth);\n    auto height = static_cast<int>(maxHeight-minHeight);\n\n    // In case the target image would be outside the frame after applying the\n    // minWidth and minHeight translation: adjust the emitted size to entirely\n    // bound the target image.\n    auto newSize = cv::Size(\n        width + minWidth > targetImageSize.width\n            ? width\n            : targetImageSize.width - minWidth,\n        height + minHeight > targetImageSize.height\n            ? height\n            : targetImageSize.height - minHeight);\n\n    // Translate the warped source by an amount to get its edges\n    // to line up with the bounds of the image frame, which must be 0.\n    cv::Mat targetFrameHomography = cv::Mat::eye(3, 3, CV_64F);\n    targetFrameHomography.at<double>(0, 2) -= minWidth;\n    targetFrameHomography.at<double>(1, 2) -= minHeight;\n\n    return WarpBounds{newSize, targetFrameHomography};\n}\n\ncv::Mat stitchImages(const cv::Mat &sourceImage, const cv::Mat &targetImage)\n{\n    if (! sourceImage.data || ! targetImage.data)\n    {\n        throw std::runtime_error(\"Null image data.\");\n    }\n\n    std::vector<cv::KeyPoint> sourceKeyPoints;\n    cv::Mat sourceDescriptors;\n\n    std::vector<cv::KeyPoint> targetKeyPoints;\n    cv::Mat targetDescriptors;\n\n    cv::Ptr<cv::AKAZE> akaze = cv::AKAZE::create();\n    akaze->detectAndCompute(targetImage,\n                            cv::noArray(),\n                            targetKeyPoints,\n                            targetDescriptors);\n    akaze->detectAndCompute(sourceImage,\n                            cv::noArray(),\n                            sourceKeyPoints,\n                            sourceDescriptors);\n\n\n    cv::BFMatcher bruteForceMatcher{cv::NORM_HAMMING};\n\n    std::vector< std::vector<cv::DMatch> > nearestNeighborMatches;\n    // Last parameter indicates the \"k\" in knn i.e. get only the 2 best nearest-\n    // neighbor matches. Useful for Lowe's ratio.\n    bruteForceMatcher.knnMatch(\n            targetDescriptors,\n            sourceDescriptors,\n            nearestNeighborMatches,\n            2);\n\n\n    // Get all nearest neighbor matches where the best and second-best matches\n    // are not too far apart.\n    std::vector<cv::DMatch> matches;\n    for (const auto &matchVec : nearestNeighborMatches)\n    {\n        constexpr const double nearestNeighborRatio = 0.8;\n\n        // Use Lowe's ratio here to filter matches.\n        if (matchVec[0].distance < nearestNeighborRatio * matchVec[1].distance)\n        {\n            matches.push_back(matchVec[0]);\n        }\n    }\n\n    // Create a vector of correspondences between the source and target points.\n    std::vector<std::pair<cv::Point2f, cv::Point2f>> correspondences;\n    for (const auto &match : matches)\n    {\n        // Get the pixel coordinates of each of the matches.\n        correspondences.emplace_back(\n            std::make_pair(\n                sourceKeyPoints[match.trainIdx].pt,\n                targetKeyPoints[match.queryIdx].pt));\n    }\n\n    std::clog << matches.size() << '/' << sourceKeyPoints.size()\n              << \" = \"\n              << std::setprecision(2)\n              <<   static_cast<double>(matches.size())\n                 / static_cast<double>(sourceKeyPoints.size())\n                 * static_cast<double>(100)\n              << \"% inliers\" << std::endl;\n\n    auto eigenHomography = pcv::Ransac<std::pair<cv::Point2f, cv::Point2f>, Eigen::Matrix3d>(\n        correspondences,\n        pcv::findHomographyWithDirectLinearTransform<float>,\n        4,\n        pcv::getReprojectionError<float>,\n        3.0,\n        52980);\n\n    cv::Mat homography = eigenToCv(eigenHomography);\n\n    // Find the bounds and translation vector necessary to align the sourceImage\n    // into the targetImage frame.\n    WarpBounds warpBounds = getWarpedBounds(\n            sourceImage.size(), targetImage.size(), homography);\n\n    // Apply translation transform (captured by targetFrameHomography) AFTER\n    // applying projective transformation i.e. order of operations here matter.\n    homography = cv::Mat(warpBounds.targetFrameHomography*homography);\n\n    cv::Mat sourceWarped;\n    cv::warpPerspective(sourceImage, sourceWarped, homography, warpBounds.size);\n    cv::Mat targetWarped;\n    cv::warpPerspective(targetImage, targetWarped, warpBounds.targetFrameHomography, warpBounds.size);\n\n    cv::Mat dst;\n    cv::addWeighted(sourceWarped, 0.5, targetWarped, 0.5, 0.0, dst);\n    cv::imwrite(\"blended.png\", dst);\n    cv::imwrite(\"sourceWarped.png\", sourceWarped);\n    cv::imwrite(\"targetWarped.png\", targetWarped);\n\n    pcv::ConvexPolygon<int> poly0;\n    pcv::ConvexPolygon<int> poly1;\n    std::array<cv::Vec3d, 4> corners0({\n        cv::Vec3d(0, 0, 1),\n        cv::Vec3d(0, sourceImage.size().height, 1),\n        cv::Vec3d(sourceImage.size().width, sourceImage.size().height, 1),\n        cv::Vec3d(sourceImage.size().width, 0, 1)});\n    std::array<cv::Vec3d, 4> corners1({\n        cv::Vec3d(0, 0, 1),\n        cv::Vec3d(0, targetImage.size().height, 1),\n        cv::Vec3d(targetImage.size().width, targetImage.size().height, 1),\n        cv::Vec3d(targetImage.size().width, 0, 1)});\n\n    for (const auto &corner : corners0)\n    {\n        const auto tmpCorner = cv::Mat(homography * corner);\n        const auto &z = tmpCorner.at<double>(0, 2);\n        poly0.addVertex({static_cast<int>(tmpCorner.at<double>(0, 0)/z),\n                         static_cast<int>(tmpCorner.at<double>(0, 1)/z)});\n    }\n\n    for (const auto &corner : corners1)\n    {\n        const auto tmpCorner = cv::Mat(warpBounds.targetFrameHomography * corner);\n        const auto &z = tmpCorner.at<double>(0, 2);\n        poly1.addVertex({static_cast<int>(tmpCorner.at<double>(0, 0)/z),\n                         static_cast<int>(tmpCorner.at<double>(0, 1)/z)});\n    }\n\n    std::vector<pcv::ConvexPolygon<int>> polys({poly0, poly1});\n\n    std::array<cv::Mat, 3> channels;\n    cv::split(dst, channels.data());\n    cv::Mat_<uint8_t> tmpcvmat;\n    pcv::makePolygonIntersectionOpencvGrid(\n        polys, channels[0].rows, channels[0].cols, tmpcvmat);\n\n    std::array<cv::Mat, 3> outputChannels;\n    std::array<cv::Mat, 3> outputChannels2;\n    for (std::size_t i = 0; i < 3; ++i)\n    {\n        outputChannels[i] = cv::Mat(channels[i].mul(tmpcvmat));\n    }\n    tmpcvmat = (tmpcvmat * -1) + 1;\n    for (std::size_t i = 0; i < 3; ++i)\n    {\n        outputChannels2[i] = cv::Mat(channels[i].mul(tmpcvmat));\n        outputChannels[i] = outputChannels[i]+2*outputChannels2[i];\n    }\n\n    cv::Mat output;\n    cv::merge(outputChannels.data(), 3, output);\n\n    cv::imwrite(\"intersection.png\", output);\n    std::clog << \"wrote intersection.png\" << std::endl;\n\n    return sourceWarped;\n}\n", "meta": {"hexsha": "b6ed8d0bbe0957b83eeff99f00d4ea16c81f78cf", "size": 9446, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/Panorama/source/Utility.cpp", "max_stars_repo_name": "Pratool/homography", "max_stars_repo_head_hexsha": "c9daeaa3364b7c658b39c225952288dd828c332e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-08-12T17:38:22.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-12T17:38:22.000Z", "max_issues_repo_path": "cpp/Panorama/source/Utility.cpp", "max_issues_repo_name": "Pratool/homography", "max_issues_repo_head_hexsha": "c9daeaa3364b7c658b39c225952288dd828c332e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-03-03T15:43:38.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-04T03:22:47.000Z", "max_forks_repo_path": "cpp/Panorama/source/Utility.cpp", "max_forks_repo_name": "Pratool/homography", "max_forks_repo_head_hexsha": "c9daeaa3364b7c658b39c225952288dd828c332e", "max_forks_repo_licenses": ["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.471042471, "max_line_length": 102, "alphanum_fraction": 0.6298962524, "num_tokens": 2466, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.82893881677331, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4944065865489812}}
{"text": "#include \"Annihilate.h\"\n#include \"dSFMTsearch.hpp\"\n#include <NTL/GF2X.h>\n#include <MTToolBox/period.hpp>\n#include <MTToolBox/AlgorithmReducibleRecursionSearch.hpp>\n\nusing namespace NTL;\nusing namespace std;\nusing namespace MTToolBox;\nstatic void minPolyLung(GF2X& poly, dSFMT& sf, int pos);\nstatic void lungLCM(GF2X& poly, dSFMT& sf);\n\nbool anni(dSFMT& sf)\n{\n    dSFMT gen(sf);\n    GF2X poly;\n    minpoly<w128_t>(poly, sf);\n\n    GF2X irreducible = poly;\n    if (!hasFactorOfDegree(irreducible, gen.getMexp())) {\n        cout << \"error does not have factor of degree \" << dec << gen.getMexp()\n             << endl;\n        return false;\n    }\n    minpoly(poly, sf);\n    if (deg(poly) != sf.bitSize()) {\n        getLCMPoly(poly, sf);\n    }\n    //printBinary(stdout, poly);\n    GF2X quotient = poly / irreducible;\n#if defined(DEBUG)\n    cout << \"deg irreducible = \" << dec << deg(irreducible) << endl;\n    cout << \"deg characteristic = \" << dec << deg(poly)\n         << endl;\n    cout << \"deg quotient = \" << dec << deg(quotient) << endl;\n#endif\n    annihilate<w128_t>(&sf, quotient);\n    minpoly<w128_t>(poly, sf);\n    //cout << \"after annihilate deg poly = \" << dec << deg(poly) << endl;\n    return true;\n}\n\nvoid getLCMPoly(GF2X& lcm, const dSFMT& sf)\n{\n    dSFMT gen(sf);\n    lungLCM(lcm, gen);\n    int bitSize = gen.bitSize();\n    GF2X poly;\n    for (int i = 0; i < bitSize; i++) {\n        gen.setOneBit(i);\n        minPolyLung(poly, gen, 0);\n        LCM(lcm, lcm, poly);\n        if (deg(lcm) == bitSize) {\n            return;\n        }\n    }\n}\n\nstatic void lungLCM(GF2X& lcm, dSFMT& sf)\n{\n    GF2X poly;\n    for (int i = 0; i < 128; i++) {\n        minPolyLung(poly, sf, i);\n        LCM(lcm, lcm, poly);\n    }\n}\n\nstatic void minPolyLung(GF2X& poly, dSFMT& sf, int pos)\n{\n    Vec<GF2> v;\n    int size = sf.bitSize();\n    v.SetLength(2 * size);\n    for (int i = 0; i < 2 * size; i++) {\n        sf.generate();\n        w128_t w = sf.getParityValue();\n        v[i] = getBitOfPos(w, pos);\n    }\n    MinPolySeq(poly, v, size);\n}\n", "meta": {"hexsha": "6565315f274da2e56fa7ab990bc31e4647750ac8", "size": 2023, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Annihilate.cpp", "max_stars_repo_name": "MSaito/dSFMTSearchParam", "max_stars_repo_head_hexsha": "b0f5d02de7ff91a807f78fe79e9df1fd9c6e257a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Annihilate.cpp", "max_issues_repo_name": "MSaito/dSFMTSearchParam", "max_issues_repo_head_hexsha": "b0f5d02de7ff91a807f78fe79e9df1fd9c6e257a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Annihilate.cpp", "max_forks_repo_name": "MSaito/dSFMTSearchParam", "max_forks_repo_head_hexsha": "b0f5d02de7ff91a807f78fe79e9df1fd9c6e257a", "max_forks_repo_licenses": ["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.2875, "max_line_length": 79, "alphanum_fraction": 0.5758774098, "num_tokens": 642, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388167733099, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.49440658654898106}}
{"text": "#ifndef INCLUDE_EXPRTK_SIGPACK_HPP\n#define INCLUDE_EXPRTK_SIGPACK_HPP\n\n#include <exprtk.hpp>\n#include <armadillo>\n#include <sigpack.h>\n\n#ifdef exprtk_enable_debugging\n#define exprtk_debug(params) printf params\n#else\n#define exprtk_debug(params) (void)0\n#endif\n\nnamespace exprtk\n{\n   namespace sigpack\n   {\n      using namespace arma;\n      using namespace sp;\n\n      struct fir1 : public exprtk::igeneric_function<double>\n      {\n         typedef typename exprtk::igeneric_function<double> igfun_t;\n         typedef typename igfun_t::parameter_list_t    parameter_list_t;\n         typedef typename igfun_t::generic_type        generic_type;\n         typedef typename generic_type::scalar_view    scalar_t;\n         typedef typename generic_type::vector_view    vector_t;\n\n         fir1() : exprtk::igeneric_function<double>(\"TTV\") {}\n\n         inline double operator() (parameter_list_t parameters)\n         {\n            scalar_t order(parameters[0]);\n            scalar_t cutOffFrequency(parameters[1]);\n            vector_t coefficients(parameters[2]);\n\n            vec b = sp::fir1(static_cast<int>(order()), cutOffFrequency());\n\n            memcpy(coefficients.begin(), b.memptr(), std::min((size_t)b.size(), coefficients.size()) * sizeof(double));\n            return 1;\n         }\n      };\n\n      struct package\n      {\n         fir1 fir1_f;\n         bool register_package(exprtk::symbol_table<double>& symtab)\n         {\n            #define exprtk_register_function(FunctionName,FunctionType)                  \\\n            if (!symtab.add_function(FunctionName,FunctionType))                         \\\n            {                                                                            \\\n               exprtk_debug((                                                            \\\n               \"sigpack::register_package - Failed to add function: %s\\n\",               \\\n               FunctionName));                                                           \\\n               return false;                                                             \\\n            }                                                                            \\\n\n            exprtk_register_function(\"fir1\", fir1_f)\n            #undef exprtk_register_function\n\n            return true;\n         }\n      };\n   } // namespace exprtk::sigpack\n} // namespace exprtk\n\n#ifdef exprtk_debug\n#undef exprtk_debug\n#endif\n\n#endif\n", "meta": {"hexsha": "e1a72fe24da6c656810b4e969af9f4410a53b31c", "size": 2412, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "source/include/exprtk_sigpack.hpp", "max_stars_repo_name": "rajsite/exorbitant", "max_stars_repo_head_hexsha": "c0e9ab1a1f3752816f0e6197db94acd0f3f99ce9", "max_stars_repo_licenses": ["MIT"], "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/include/exprtk_sigpack.hpp", "max_issues_repo_name": "rajsite/exorbitant", "max_issues_repo_head_hexsha": "c0e9ab1a1f3752816f0e6197db94acd0f3f99ce9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-03-31T23:10:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T23:10:28.000Z", "max_forks_repo_path": "source/include/exprtk_sigpack.hpp", "max_forks_repo_name": "rajsite/exorbitant", "max_forks_repo_head_hexsha": "c0e9ab1a1f3752816f0e6197db94acd0f3f99ce9", "max_forks_repo_licenses": ["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.5, "max_line_length": 119, "alphanum_fraction": 0.5252902156, "num_tokens": 446, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.494406576467001}}
{"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_SIGN_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_SIGN_HPP_INCLUDED\n#include <boost/simd/detail/overload.hpp>\n\n#include <boost/simd/meta/hierarchy/simd.hpp>\n#include <boost/simd/constant/valmin.hpp>\n#include <boost/simd/function/if_allbits_else.hpp>\n#include <boost/simd/function/if_one_else_zero.hpp>\n// #include <boost/simd/function/is_equal.hpp>\n#include <boost/simd/function/is_gtz.hpp>\n#include <boost/simd/function/is_ltz.hpp>\n#include <boost/simd/function/is_nan.hpp>\n#include <boost/simd/function/minus.hpp>\n\n\nnamespace boost { namespace simd { namespace ext\n{\n   namespace bd = boost::dispatch;\n   namespace bs = boost::simd;\n   BOOST_DISPATCH_OVERLOAD_IF(sign_\n                          , (typename A0, typename X)\n                          , (detail::is_native<X>)\n                          , bd::cpu_\n                          , bs::pack_<bd::arithmetic_<A0>, X>\n                          )\n   {\n      BOOST_FORCEINLINE A0 operator()( const A0& a0) const BOOST_NOEXCEPT\n      {\n        return if_one_else_zero(is_gtz(a0))-if_one_else_zero(is_ltz(a0));\n      }\n   };\n\n   BOOST_DISPATCH_OVERLOAD_IF(sign_\n                          , (typename A0, typename X)\n                          , (detail::is_native<X>)\n                          , bd::cpu_\n                          , bs::pack_<bd::unsigned_<A0>, X>\n                          )\n   {\n      BOOST_FORCEINLINE A0 operator()( const A0& a0) const BOOST_NOEXCEPT\n      {\n        return if_one_else_zero(a0);\n      }\n   };\n\n   BOOST_DISPATCH_OVERLOAD_IF(sign_\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 r = if_one_else_zero(is_gtz(a0))-if_one_else_zero(is_ltz(a0));\n         #ifdef BOOST_SIMD_NO_NANS\n         return r;\n         #else\n         return if_allbits_else(is_nan(a0), r);\n         #endif\n      }\n   };\n\n} } }\n#endif\n\n", "meta": {"hexsha": "83c823605c40c90b37fc6095f6e4f0900934f235", "size": 2524, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/simd/function/sign.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/sign.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/sign.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.7792207792, "max_line_length": 100, "alphanum_fraction": 0.5320919176, "num_tokens": 556, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149978955811, "lm_q2_score": 0.6548947425132314, "lm_q1q2_score": 0.49438986316620326}}
{"text": "#include \"follower_solver.h\"\n#include \"../macros.h\"\n\n#include <algorithm>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n\nusing namespace std;\nusing namespace boost;\n\nfollower_solver::follower_solver(const problem& _prob) : follower_solver_base(_prob)\n{\n\t// Copy a new cost map\n\tproblem::edge_iterator ei, ei_end;\n\tfor (tie(ei, ei_end) = edges(prob.graph); ei != ei_end; ++ei)\n\t\ttolled_cost_map[*ei] = prob.cost_map[*ei];\n}\n\nvector<follower_solver::path> follower_solver::solve_impl(const vector<cost_type>& tolls)\n{\n\t// Add toll to new cost map\n\tLOOP(a, A1) {\n\t\tauto edge = A1_TO_EDGE(prob, a);\n\t\ttolled_cost_map[edge] = prob.cost_map[edge] + tolls[a] * 0.9999;\t// Prefer tolled arcs\n\t}\n\n\tvector<path> paths(K);\n\tvector<int> parents(V);\n\tauto index_map = get(vertex_index, prob.graph);\n\tauto cost_map = make_assoc_property_map(tolled_cost_map);\n\tauto parent_map = make_iterator_property_map(parents.begin(), index_map);\n\n\tLOOP(k, K) {\n\t\t// Find the shortest path\n\t\tint orig = prob.commodities[k].origin;\n\t\tdijkstra_shortest_paths(prob.graph, orig, weight_map(cost_map).predecessor_map(parent_map));\n\n\t\t// Trace back the path\n\t\tint curr = prob.commodities[k].destination;\n\t\twhile (curr != orig) {\n\t\t\tpaths[k].push_back(curr);\n\t\t\tcurr = parents[curr];\n\t\t}\n\t\tpaths[k].push_back(orig);\n\n\t\tstd::reverse(paths[k].begin(), paths[k].end());\n\t}\n\n\treturn paths;\n}\n", "meta": {"hexsha": "b4bf8f1593d96134f4dc18cd058b3fd6b58e5979", "size": 1359, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "netpricing/utilities/follower_solver.cpp", "max_stars_repo_name": "minhcly95/netpricing", "max_stars_repo_head_hexsha": "d2c88714b420ff21e99ebfa93ef6ae79adb438a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "netpricing/utilities/follower_solver.cpp", "max_issues_repo_name": "minhcly95/netpricing", "max_issues_repo_head_hexsha": "d2c88714b420ff21e99ebfa93ef6ae79adb438a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "netpricing/utilities/follower_solver.cpp", "max_forks_repo_name": "minhcly95/netpricing", "max_forks_repo_head_hexsha": "d2c88714b420ff21e99ebfa93ef6ae79adb438a0", "max_forks_repo_licenses": ["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.18, "max_line_length": 94, "alphanum_fraction": 0.7159676233, "num_tokens": 372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149978955811, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.4943898580814341}}
{"text": "#include \"mview.h\"\n\n#include <iostream>\n\n#include <Eigen/Eigen>\n#include <Eigen/Dense>\n#include <opencv2/core.hpp>\n#include <opencv/cv.hpp>\n#include <opencv2/core/eigen.hpp>\n\nstatic int debug_cnt = 0;\n\nTriangulated triangulate(const Rectified &rectified, const Disparity& disparity)\n{\n  cv::Mat reconstructed_points;\n  cv::reprojectImageTo3D(disparity.disparity, reconstructed_points, rectified.Q);\n\n  cv::Mat mask = disparity.disparity <= 5.;\n  reconstructed_points.setTo(cv::Vec3f(), mask);\n\n  cv::Mat point_parts[3];\n  cv::split(reconstructed_points, point_parts);\n\n#if !MVIEW_NDEBUG\n  std::stringstream depth_output_str;\n  depth_output_str << \"debug.depth\" << debug_cnt++ << \".png\";\n  std::string depth_output = depth_output_str.str();\n\n  cv::imwrite(depth_output, point_parts[2]*25.);\n#endif\n\n  cv::Mat quantitative;\n  cv::eigen2cv(rectified.left_ground_truth, quantitative);\n  quantitative = quantitative - point_parts[2];\n  quantitative.setTo(0.f, mask);\n  const int count = mask.size().area() - cv::countNonZero(mask);\n  float squared_error = 0.f;\n  quantitative.forEach<float>([&squared_error](float diff, const int*) { squared_error += diff*diff; });\n  std::cout << \"Squared absolute error: \" << squared_error << \" (count: \" << count << \")\\n\";\n  std::cout << \"Relative error: \" << std::sqrt(squared_error)/count << \"\\n\";\n\n  for(int i = 0; i < 3; i++)\n    point_parts[i] = point_parts[i].reshape(1, 1);\n\n  cv::Mat points;\n  cv::vconcat(point_parts, 3, points);\n\n  Eigen::Matrix3f local_rotation;\n  cv::cv2eigen(rectified.R1, local_rotation);\n  Eigen::Matrix4f local_extrinsics;\n  local_extrinsics.setIdentity();\n  local_extrinsics.block<3, 3>(0, 0) = local_rotation;\n\n  Eigen::Matrix4f global_extrinsics = rectified.extrinsics_left;\n  Eigen::Matrix4f extrinsics = local_extrinsics * global_extrinsics;\n\n  Eigen::Matrix3f intrinsics;\n  cv::cv2eigen(rectified.P1.colRange(0, 3), intrinsics);\n\n  std::cout << extrinsics << std::endl;\n\n  PointImage point_image(disparity.disparity.rows, disparity.disparity.cols);\n  ColourImage colour_image(disparity.disparity.rows, disparity.disparity.cols);\n\n  for (int i = 0; i < points.cols; i++){\n\tint x = i/disparity.disparity.cols;\n\tint y = i%disparity.disparity.cols;\n\n\tEigen::Vector3f point;\n\tcv::cv2eigen(points.col(i).rowRange(0, 3), point);\n\tpoint_image(x, y) = point;\n\tcolour_image(x, y).block<3, 1>(0, 0) = rectified.pixel_left_rgb(x, y);\n  }\n\n  return { point_image, colour_image, extrinsics, intrinsics };\n}\n", "meta": {"hexsha": "ab42736534ff29b3e1e0d3e6c2923a8bfd4651b8", "size": 2463, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "triangulate.cpp", "max_stars_repo_name": "temple-reconstruction/mview", "max_stars_repo_head_hexsha": "1440b5716d595c5c4d568fc45dd5afbb6f54dfc7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-09-17T07:39:35.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-24T21:09:27.000Z", "max_issues_repo_path": "triangulate.cpp", "max_issues_repo_name": "temple-reconstruction/mview", "max_issues_repo_head_hexsha": "1440b5716d595c5c4d568fc45dd5afbb6f54dfc7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-06-11T19:25:03.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-11T21:51:32.000Z", "max_forks_repo_path": "triangulate.cpp", "max_forks_repo_name": "temple-reconstruction/mview", "max_forks_repo_head_hexsha": "1440b5716d595c5c4d568fc45dd5afbb6f54dfc7", "max_forks_repo_licenses": ["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.987012987, "max_line_length": 104, "alphanum_fraction": 0.7145757207, "num_tokens": 697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149978955811, "lm_q2_score": 0.6548947290421276, "lm_q1q2_score": 0.494389852996665}}
{"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_FUNCTION_DIST_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_DIST_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-arithmetic\n    Function object implementing dist capabilities\n\n    Computes the absolute value of the difference of its parameters.\n\n    @par semantic:\n    For any given value @c x,  @c y of type @c T:\n\n    @code\n    T r = dist(x, y);\n    @endcode\n\n    is similar to:\n\n    @code\n    T r = abs(x-y);\n    @endcode\n\n    @par Note\n\n    The result can be negative for signed integers as @ref abs(@ref Valmin) is @ref Valmin.\n    To avoid the problem you can use the saturated version @ref dists.\n\n    @see  dists, ulpdist\n\n  **/\n  const boost::dispatch::functor<tag::dist_> dist = {};\n} }\n#endif\n\n#include <boost/simd/function/scalar/dist.hpp>\n#include <boost/simd/function/simd/dist.hpp>\n\n#endif\n", "meta": {"hexsha": "ed51a20a28e66a99ed6020b4bec07b1c7a74ed83", "size": 1296, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/dist.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/function/dist.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/function/dist.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": 23.5636363636, "max_line_length": 100, "alphanum_fraction": 0.587191358, "num_tokens": 293, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.754914997895581, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.4943898529966648}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*!\n Copyright (C) 2006 Allen Kuo\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/*  This example shows how to set up a term structure and price a simple\n    forward-rate agreement.\n*/\n\n#include <ql/qldefines.hpp>\n#ifdef BOOST_MSVC\n#  include <ql/auto_link.hpp>\n#endif\n#include <ql/instruments/forwardrateagreement.hpp>\n#include <ql/termstructures/yield/piecewiseyieldcurve.hpp>\n#include <ql/termstructures/yield/ratehelpers.hpp>\n#include <ql/indexes/ibor/euribor.hpp>\n#include <ql/time/daycounters/actualactual.hpp>\n\n#include <boost/timer.hpp>\n#include <iostream>\n\n#define LENGTH(a) (sizeof(a)/sizeof(a[0]))\n\nusing namespace std;\nusing namespace QuantLib;\n\n#if defined(QL_ENABLE_SESSIONS)\nnamespace QuantLib {\n\n    Integer sessionId() { return 0; }\n\n}\n#endif\n\nint main(int, char* []) {\n\n    try {\n\n        boost::timer timer;\n        std::cout << std::endl;\n\n        /*********************\n         ***  MARKET DATA  ***\n         *********************/\n\n        RelinkableHandle<YieldTermStructure> euriborTermStructure;\n        boost::shared_ptr<IborIndex> euribor3m(\n                                       new Euribor3M(euriborTermStructure));\n\n        Date todaysDate = Date(23, May, 2006);\n        Settings::instance().evaluationDate() = todaysDate;\n\n        Calendar calendar = euribor3m->fixingCalendar();\n        Integer fixingDays = euribor3m->fixingDays();\n        Date settlementDate = calendar.advance(todaysDate, fixingDays, Days);\n\n        std::cout << \"Today: \" << todaysDate.weekday()\n                  << \", \" << todaysDate << std::endl;\n\n        std::cout << \"Settlement date: \" << settlementDate.weekday()\n                  << \", \" << settlementDate << std::endl;\n\n\n        // 3 month term FRA quotes (index refers to monthsToStart)\n        Rate threeMonthFraQuote[10];\n\n        threeMonthFraQuote[1]=0.030;\n        threeMonthFraQuote[2]=0.031;\n        threeMonthFraQuote[3]=0.032;\n        threeMonthFraQuote[6]=0.033;\n        threeMonthFraQuote[9]=0.034;\n\n        /********************\n         ***    QUOTES    ***\n         ********************/\n\n        // SimpleQuote stores a value which can be manually changed;\n        // other Quote subclasses could read the value from a database\n        // or some kind of data feed.\n\n\n        // FRAs\n        boost::shared_ptr<SimpleQuote> fra1x4Rate(\n                                      new SimpleQuote(threeMonthFraQuote[1]));\n        boost::shared_ptr<SimpleQuote> fra2x5Rate(\n                                      new SimpleQuote(threeMonthFraQuote[2]));\n        boost::shared_ptr<SimpleQuote> fra3x6Rate(\n                                      new SimpleQuote(threeMonthFraQuote[3]));\n        boost::shared_ptr<SimpleQuote> fra6x9Rate(\n                                      new SimpleQuote(threeMonthFraQuote[6]));\n        boost::shared_ptr<SimpleQuote> fra9x12Rate(\n                                      new SimpleQuote(threeMonthFraQuote[9]));\n\n        RelinkableHandle<Quote> h1x4;  h1x4.linkTo(fra1x4Rate);\n        RelinkableHandle<Quote> h2x5;  h2x5.linkTo(fra2x5Rate);\n        RelinkableHandle<Quote> h3x6;  h3x6.linkTo(fra3x6Rate);\n        RelinkableHandle<Quote> h6x9;  h6x9.linkTo(fra6x9Rate);\n        RelinkableHandle<Quote> h9x12; h9x12.linkTo(fra9x12Rate);\n\n        /*********************\n         ***  RATE HELPERS ***\n         *********************/\n\n        // RateHelpers are built from the above quotes together with\n        // other instrument dependant infos.  Quotes are passed in\n        // relinkable handles which could be relinked to some other\n        // data source later.\n\n        DayCounter fraDayCounter = euribor3m->dayCounter();\n        BusinessDayConvention convention = euribor3m->businessDayConvention();\n        bool endOfMonth = euribor3m->endOfMonth();\n\n        boost::shared_ptr<RateHelper> fra1x4(\n                           new FraRateHelper(h1x4, 1, 4,\n                                             fixingDays, calendar, convention,\n                                             endOfMonth, fraDayCounter));\n\n        boost::shared_ptr<RateHelper> fra2x5(\n                           new FraRateHelper(h2x5, 2, 5,\n                                             fixingDays, calendar, convention,\n                                             endOfMonth, fraDayCounter));\n\n        boost::shared_ptr<RateHelper> fra3x6(\n                           new FraRateHelper(h3x6, 3, 6,\n                                             fixingDays, calendar, convention,\n                                             endOfMonth, fraDayCounter));\n\n        boost::shared_ptr<RateHelper> fra6x9(\n                           new FraRateHelper(h6x9, 6, 9,\n                                             fixingDays, calendar, convention,\n                                             endOfMonth, fraDayCounter));\n\n        boost::shared_ptr<RateHelper> fra9x12(\n                           new FraRateHelper(h9x12, 9, 12,\n                                             fixingDays, calendar, convention,\n                                             endOfMonth, fraDayCounter));\n\n\n        /*********************\n         **  CURVE BUILDING **\n         *********************/\n\n        // Any DayCounter would be fine.\n        // ActualActual::ISDA ensures that 30 years is 30.0\n        DayCounter termStructureDayCounter =\n            ActualActual(ActualActual::ISDA);\n\n        double tolerance = 1.0e-15;\n\n        // A FRA curve\n        std::vector<boost::shared_ptr<RateHelper> > fraInstruments;\n\n        fraInstruments.push_back(fra1x4);\n        fraInstruments.push_back(fra2x5);\n        fraInstruments.push_back(fra3x6);\n        fraInstruments.push_back(fra6x9);\n        fraInstruments.push_back(fra9x12);\n\n        boost::shared_ptr<YieldTermStructure> fraTermStructure(\n                     new PiecewiseYieldCurve<Discount,LogLinear>(\n                                         settlementDate, fraInstruments,\n                                         termStructureDayCounter,\n                                         tolerance));\n\n\n        // Term structures used for pricing/discounting\n\n        RelinkableHandle<YieldTermStructure> discountingTermStructure;\n        discountingTermStructure.linkTo(fraTermStructure);\n\n\n        /***********************\n         ***  construct FRA's ***\n         ***********************/\n\n        Calendar fraCalendar = euribor3m->fixingCalendar();\n        BusinessDayConvention fraBusinessDayConvention =\n            euribor3m->businessDayConvention();\n        Position::Type fraFwdType = Position::Long;\n        Real fraNotional = 100.0;\n        const Integer FraTermMonths = 3;\n        Integer monthsToStart[] = { 1, 2, 3, 6, 9 };\n\n        euriborTermStructure.linkTo(fraTermStructure);\n\n        cout << endl;\n        cout << \"Test FRA construction, NPV calculation, and FRA purchase\"\n             << endl\n             << endl;\n\n        Size i;\n        for (i=0; i<LENGTH(monthsToStart); i++) {\n\n            Date fraValueDate = fraCalendar.advance(\n                                       settlementDate,monthsToStart[i],Months,\n                                       fraBusinessDayConvention);\n\n            Date fraMaturityDate = fraCalendar.advance(\n                                            fraValueDate,FraTermMonths,Months,\n                                            fraBusinessDayConvention);\n\n            Rate fraStrikeRate = threeMonthFraQuote[monthsToStart[i]];\n\n            ForwardRateAgreement myFRA(fraValueDate, fraMaturityDate,\n                                       fraFwdType,fraStrikeRate,\n                                       fraNotional, euribor3m,\n                                       discountingTermStructure);\n\n            cout << \"3m Term FRA, Months to Start: \"\n                 << monthsToStart[i]\n                 << endl;\n            cout << \"strike FRA rate: \"\n                 << io::rate(fraStrikeRate)\n                 << endl;\n            cout << \"FRA 3m forward rate: \"\n                 << myFRA.forwardRate()\n                 << endl;\n            cout << \"FRA market quote: \"\n                 << io::rate(threeMonthFraQuote[monthsToStart[i]])\n                 << endl;\n            cout << \"FRA spot value: \"\n                 << myFRA.spotValue()\n                 << endl;\n            cout << \"FRA forward value: \"\n                 << myFRA.forwardValue()\n                 << endl;\n            cout << \"FRA implied Yield: \"\n                 << myFRA.impliedYield(myFRA.spotValue(),\n                                       myFRA.forwardValue(),\n                                       settlementDate,\n                                       Simple,\n                                       fraDayCounter)\n                 << endl;\n            cout << \"market Zero Rate: \"\n                 << discountingTermStructure->zeroRate(fraMaturityDate,\n                                                       fraDayCounter,\n                                                       Simple)\n                 << endl;\n            cout << \"FRA NPV [should be zero]: \"\n                 << myFRA.NPV()\n                 << endl\n                 << endl;\n\n        }\n\n\n\n\n        cout << endl << endl;\n        cout << \"Now take a 100 basis-point upward shift in FRA quotes \"\n             << \"and examine NPV\"\n             << endl\n             << endl;\n\n        const Real BpsShift = 0.01;\n\n        threeMonthFraQuote[1]=0.030+BpsShift;\n        threeMonthFraQuote[2]=0.031+BpsShift;\n        threeMonthFraQuote[3]=0.032+BpsShift;\n        threeMonthFraQuote[6]=0.033+BpsShift;\n        threeMonthFraQuote[9]=0.034+BpsShift;\n\n        fra1x4Rate->setValue(threeMonthFraQuote[1]);\n        fra2x5Rate->setValue(threeMonthFraQuote[2]);\n        fra3x6Rate->setValue(threeMonthFraQuote[3]);\n        fra6x9Rate->setValue(threeMonthFraQuote[6]);\n        fra9x12Rate->setValue(threeMonthFraQuote[9]);\n\n\n        for (i=0; i<LENGTH(monthsToStart); i++) {\n\n            Date fraValueDate = fraCalendar.advance(\n                                       settlementDate,monthsToStart[i],Months,\n                                       fraBusinessDayConvention);\n\n            Date fraMaturityDate = fraCalendar.advance(\n                                            fraValueDate,FraTermMonths,Months,\n                                            fraBusinessDayConvention);\n\n            Rate fraStrikeRate =\n                threeMonthFraQuote[monthsToStart[i]] - BpsShift;\n\n            ForwardRateAgreement myFRA(fraValueDate, fraMaturityDate,\n                                       fraFwdType, fraStrikeRate,\n                                       fraNotional, euribor3m,\n                                       discountingTermStructure);\n\n            cout << \"3m Term FRA, 100 notional, Months to Start = \"\n                 << monthsToStart[i]\n                 << endl;\n            cout << \"strike FRA rate: \"\n                 << io::rate(fraStrikeRate)\n                 << endl;\n            cout << \"FRA 3m forward rate: \"\n                 << myFRA.forwardRate()\n                 << endl;\n            cout << \"FRA market quote: \"\n                 << io::rate(threeMonthFraQuote[monthsToStart[i]])\n                 << endl;\n            cout << \"FRA spot value: \"\n                 << myFRA.spotValue()\n                 << endl;\n            cout << \"FRA forward value: \"\n                 << myFRA.forwardValue()\n                 << endl;\n            cout << \"FRA implied Yield: \"\n                 << myFRA.impliedYield(myFRA.spotValue(),\n                                       myFRA.forwardValue(),\n                                       settlementDate,\n                                       Simple,\n                                       fraDayCounter)\n                 << endl;\n            cout << \"market Zero Rate: \"\n                 << discountingTermStructure->zeroRate(fraMaturityDate,\n                                                       fraDayCounter,\n                                                       Simple)\n                 << endl;\n            cout << \"FRA NPV [should be positive]: \"\n                 << myFRA.NPV()\n                 << endl\n                 << endl;\n        }\n\n        double seconds = timer.elapsed();\n        Integer hours = int(seconds/3600);\n        seconds -= hours * 3600;\n        Integer minutes = int(seconds/60);\n        seconds -= minutes * 60;\n        cout << \" \\nRun completed in \";\n        if (hours > 0)\n            cout << hours << \" h \";\n        if (hours > 0 || minutes > 0)\n            cout << minutes << \" m \";\n        cout << fixed << setprecision(0)\n             << seconds << \" s\\n\" << endl;\n\n        return 0;\n\n    } catch (exception& e) {\n        cerr << e.what() << endl;\n        return 1;\n    } catch (...) {\n        cerr << \"unknown error\" << endl;\n        return 1;\n    }\n}\n\n", "meta": {"hexsha": "a3d1ee68692a893f3f4be0c678e013612e901a95", "size": 13447, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Examples/FRA/FRA.cpp", "max_stars_repo_name": "sfondi/QuantLib", "max_stars_repo_head_hexsha": "8a2449d2fb470a7d47a55d3e99c5dace749709c9", "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": "Examples/FRA/FRA.cpp", "max_issues_repo_name": "sfondi/QuantLib", "max_issues_repo_head_hexsha": "8a2449d2fb470a7d47a55d3e99c5dace749709c9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-07-17T18:49:22.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-17T18:49:22.000Z", "max_forks_repo_path": "Examples/FRA/FRA.cpp", "max_forks_repo_name": "sfondi/QuantLib", "max_forks_repo_head_hexsha": "8a2449d2fb470a7d47a55d3e99c5dace749709c9", "max_forks_repo_licenses": ["BSD-3-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.044077135, "max_line_length": 79, "alphanum_fraction": 0.5047966089, "num_tokens": 2915, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.6548947290421276, "lm_q1q2_score": 0.49438984577451683}}
{"text": "// This file is part of libigl, a simple c++ geometry processing library.\n// \n// Copyright (C) 2016 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 \"point_simplex_squared_distance.h\"\n#include \"project_to_line_segment.h\"\n#include \"barycentric_coordinates.h\"\n#include <Eigen/Geometry>\n#include <limits>\n#include <cassert>\n\n\n\ntemplate <\n  int DIM,\n  typename Derivedp,\n  typename DerivedV,\n  typename DerivedEle,\n  typename Derivedsqr_d,\n  typename Derivedc,\n  typename Derivedb>\nIGL_INLINE void igl::point_simplex_squared_distance(\n  const Eigen::MatrixBase<Derivedp> & p,\n  const Eigen::MatrixBase<DerivedV> & V,\n  const Eigen::MatrixBase<DerivedEle> & Ele,\n  const typename DerivedEle::Index primitive,\n  Derivedsqr_d & sqr_d,\n  Eigen::MatrixBase<Derivedc> & c,\n  Eigen::MatrixBase<Derivedb> & bary)\n{\n  typedef typename Derivedp::Scalar Scalar;\n  typedef typename Eigen::Matrix<Scalar,1,DIM> Vector;\n  typedef Vector Point;\n  //typedef Derivedb BaryPoint;\n  typedef Eigen::Matrix<typename Derivedb::Scalar,1,3> BaryPoint;\n\n  const auto & Dot = [](const Point & a, const Point & b)->Scalar\n  {\n    return a.dot(b);\n  };\n  // Real-time collision detection, Ericson, Chapter 5\n  const auto & ClosestBaryPtPointTriangle = \n    [&Dot](Point p, Point a, Point b, Point c, BaryPoint& bary_out )->Point \n  {\n    // Check if P in vertex region outside A\n    Vector ab = b - a;\n    Vector ac = c - a;\n    Vector ap = p - a;\n    Scalar d1 = Dot(ab, ap);\n    Scalar d2 = Dot(ac, ap);\n    if (d1 <= 0.0 && d2 <= 0.0) {\n      // barycentric coordinates (1,0,0)\n      bary_out << 1, 0, 0;\n      return a;\n    }\n    // Check if P in vertex region outside B\n    Vector bp = p - b;\n    Scalar d3 = Dot(ab, bp);\n    Scalar d4 = Dot(ac, bp);\n    if (d3 >= 0.0 && d4 <= d3) {\n      // barycentric coordinates (0,1,0)\n      bary_out << 0, 1, 0;\n      return b;\n    }\n    // Check if P in edge region of AB, if so return projection of P onto AB\n    Scalar vc = d1*d4 - d3*d2;\n    if( a != b)\n    {\n      if (vc <= 0.0 && d1 >= 0.0 && d3 <= 0.0) {\n        Scalar v = d1 / (d1 - d3);\n        // barycentric coordinates (1-v,v,0)\n        bary_out << 1-v, v, 0;\n        return a + v * ab;\n      }\n    }\n    // Check if P in vertex region outside C\n    Vector cp = p - c;\n    Scalar d5 = Dot(ab, cp);\n    Scalar d6 = Dot(ac, cp);\n    if (d6 >= 0.0 && d5 <= d6) {\n      // barycentric coordinates (0,0,1)\n      bary_out << 0, 0, 1;\n      return c;\n    }\n    // Check if P in edge region of AC, if so return projection of P onto AC\n    Scalar vb = d5*d2 - d1*d6;\n    if (vb <= 0.0 && d2 >= 0.0 && d6 <= 0.0) {\n      Scalar w = d2 / (d2 - d6);\n      // barycentric coordinates (1-w,0,w)\n      bary_out << 1-w, 0, w;\n      return a + w * ac;\n    }\n    // Check if P in edge region of BC, if so return projection of P onto BC\n    Scalar va = d3*d6 - d5*d4;\n    if (va <= 0.0 && (d4 - d3) >= 0.0 && (d5 - d6) >= 0.0) {\n      Scalar w = (d4 - d3) / ((d4 - d3) + (d5 - d6));\n      // barycentric coordinates (0,1-w,w)\n      bary_out << 0, 1-w, w;\n      return b + w * (c - b);\n    }\n    // P inside face region. Compute Q through its barycentric coordinates (u,v,w)\n    Scalar denom = 1.0 / (va + vb + vc);\n    Scalar v = vb * denom;\n    Scalar w = vc * denom;\n    bary_out << 1.0-v-w, v, w;\n    return a + ab * v + ac * w; // = u*a + v*b + w*c, u = va * denom = 1.0-v-w\n  };\n\n  assert(p.size() == DIM);\n  assert(V.cols() == DIM);\n  assert(Ele.cols() <= DIM+1);\n  assert(Ele.cols() <= 3 && \"Only simplices up to triangles are considered\");\n\n  assert((Derivedb::RowsAtCompileTime == 1 || Derivedb::ColsAtCompileTime == 1) && \"bary must be Eigen Vector or Eigen RowVector\");\n  assert(\n    ((Derivedb::RowsAtCompileTime == -1 || Derivedb::ColsAtCompileTime == -1) ||\n      (Derivedb::RowsAtCompileTime == Ele.cols() || Derivedb::ColsAtCompileTime == -Ele.cols())\n    ) && \"bary must be Dynamic or size of Ele.cols()\");\n\n  BaryPoint tmp_bary;\n  c = ClosestBaryPtPointTriangle(\n    p,\n    V.row(Ele(primitive,0)),\n    // modulo is a HACK to handle points, segments and triangles. Because of\n    // this, we need 3d buffer for bary\n    V.row(Ele(primitive,1%Ele.cols())),\n    V.row(Ele(primitive,2%Ele.cols())),\n    tmp_bary);\n  bary.resize( Derivedb::RowsAtCompileTime == 1 ? 1 : Ele.cols(), Derivedb::ColsAtCompileTime == 1 ? 1 : Ele.cols());\n  bary.head(Ele.cols()) = tmp_bary.head(Ele.cols());\n  sqr_d = (p-c).squaredNorm();\n}\n\ntemplate <\n  int DIM,\n  typename Derivedp,\n  typename DerivedV,\n  typename DerivedEle,\n  typename Derivedsqr_d,\n  typename Derivedc>\nIGL_INLINE void igl::point_simplex_squared_distance(\n  const Eigen::MatrixBase<Derivedp> & p,\n  const Eigen::MatrixBase<DerivedV> & V,\n  const Eigen::MatrixBase<DerivedEle> & Ele,\n  const typename DerivedEle::Index primitive,\n  Derivedsqr_d & sqr_d,\n  Eigen::MatrixBase<Derivedc> & c)\n{\n  // Use Dynamic because we don't know Ele.cols() at compile time.\n  Eigen::Matrix<typename Derivedc::Scalar,1,Eigen::Dynamic> b;\n  point_simplex_squared_distance<DIM>( p, V, Ele, primitive, sqr_d, c, b );\n}\n\n#ifdef IGL_STATIC_LIBRARY\n// Explicit template instanciation\ntemplate void igl::point_simplex_squared_distance<3, Eigen::Matrix<double, 1, 3, 1, 1, 3>, Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, double, Eigen::Matrix<double, 1, 3, 1, 1, 3> >(Eigen::MatrixBase<Eigen::Matrix<double, 1, 3, 1, 1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, double&, Eigen::MatrixBase<Eigen::Matrix<double, 1, 3, 1, 1, 3> >&);\ntemplate void igl::point_simplex_squared_distance<2, Eigen::Matrix<double, 1, 2, 1, 1, 2>, Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, double, Eigen::Matrix<double, 1, 2, 1, 1, 2> >(Eigen::MatrixBase<Eigen::Matrix<double, 1, 2, 1, 1, 2> > const&, Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, double&, Eigen::MatrixBase<Eigen::Matrix<double, 1, 2, 1, 1, 2> >&);\ntemplate void igl::point_simplex_squared_distance<3, Eigen::Matrix<double, 1, 3, 1, 1, 3>, Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, double, Eigen::Matrix<double, 1, 3, 1, 1, 3> >(Eigen::MatrixBase<Eigen::Matrix<double, 1, 3, 1, 1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, double&, Eigen::MatrixBase<Eigen::Matrix<double, 1, 3, 1, 1, 3> >&, Eigen::MatrixBase<Eigen::Matrix<double, 1, 3, 1, 1, 3> >&);\ntemplate void igl::point_simplex_squared_distance<3, Eigen::Matrix<double, 1, 3, 1, 1, 3>, Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, double, Eigen::Matrix<double, 1, 3, 1, 1, 3> >(Eigen::MatrixBase<Eigen::Matrix<double, 1, 3, 1, 1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, double&, Eigen::MatrixBase<Eigen::Matrix<double, 1, 3, 1, 1, 3> >&, Eigen::MatrixBase<Eigen::Matrix<double, 3, 1, 1, 1, 3> >&);\ntemplate void igl::point_simplex_squared_distance<2, Eigen::Matrix<double, 1, 2, 1, 1, 2>, Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, double, Eigen::Matrix<double, 1, 2, 1, 1, 2> >(Eigen::MatrixBase<Eigen::Matrix<double, 1, 2, 1, 1, 2> > const&, Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, double&, Eigen::MatrixBase<Eigen::Matrix<double, 1, 2, 1, 1, 2> >&, Eigen::MatrixBase<Eigen::Matrix<double, 1, 2, 1, 1, 2> >&);\ntemplate void igl::point_simplex_squared_distance<2, Eigen::Matrix<double, 1, 2, 1, 1, 2>, Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, double, Eigen::Matrix<double, 1, 2, 1, 1, 2> >(Eigen::MatrixBase<Eigen::Matrix<double, 1, 2, 1, 1, 2> > const&, Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::Matrix<int, -1, -1, 0, -1, -1>::Index, double&, Eigen::MatrixBase<Eigen::Matrix<double, 1, 2, 1, 1, 2> >&, Eigen::MatrixBase<Eigen::Matrix<double, 2, 1, 1, 1, 2> >&);\n#endif\n", "meta": {"hexsha": "0f0af8ad056ec0f66f97299b861bfce25a1a2f88", "size": 8735, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Source/SprueEngine/Libs/igl/point_simplex_squared_distance.cpp", "max_stars_repo_name": "Qt-Widgets/TexGraph", "max_stars_repo_head_hexsha": "8fe72cea1afcf5e235c810003bf4ee062bb3fc13", "max_stars_repo_licenses": ["MIT"], "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": "Source/SprueEngine/Libs/igl/point_simplex_squared_distance.cpp", "max_issues_repo_name": "Qt-Widgets/TexGraph", "max_issues_repo_head_hexsha": "8fe72cea1afcf5e235c810003bf4ee062bb3fc13", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-04-13T17:43:54.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-15T04:17:37.000Z", "max_forks_repo_path": "Source/SprueEngine/Libs/igl/point_simplex_squared_distance.cpp", "max_forks_repo_name": "Qt-Widgets/TexGraph", "max_forks_repo_head_hexsha": "8fe72cea1afcf5e235c810003bf4ee062bb3fc13", "max_forks_repo_licenses": ["MIT"], "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": 52.6204819277, "max_line_length": 592, "alphanum_fraction": 0.6172867773, "num_tokens": 3185, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.49438984577451667}}
{"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   testMoses3.cpp\n * @brief  Unit tests for Moses3 class\n */\n\n#include <gtsam/geometry/Moses3.h>\n#include <gtsam/geometry/Pose2.h>\n#include <gtsam/geometry/Pose3.h> \n#include <gtsam/base/lieProxies.h>\n#include <gtsam/base/Testable.h>\n#include <gtsam/base/numericalDerivative.h>\n\n//#include <gtsam/3rdparty/Eigen/unsupported/Eigen/MatrixFunctions> \n\n#include <boost/assign/std/vector.hpp> // for operator +=\nusing namespace boost::assign;\n\n#include <CppUnitLite/TestHarness.h>\n#include <cmath>\n\nusing namespace std;\nusing namespace Sophus;\nusing namespace gtsam;\n\nGTSAM_CONCEPT_TESTABLE_INST(Moses3)\nGTSAM_CONCEPT_LIE_INST(Moses3)\n\n/*\nstatic Point3 P(0.2,0.7,-2);\nstatic Rot3 R = Rot3::rodriguez(0,0,0);\nstatic Point3 Pp(10.0,0.0,0.0);\n\nstatic Rot3 R1 = Rot3(Point3(0.0, -1.0 , 0.0),Point3(1.0, 0.0 , 0.0),Point3(0.0, 0.0 , 1.0));\nstatic Rot3 R2 = Rot3(Point3(0.0, 1.0 , 0.0),Point3(-1.0, 0.0 , 0.0),Point3(0.0, 0.0 , 1.0));\n\nstatic Point3 Pp1(0.0,10.0,0.0);\nstatic Point3 Pp2(10.1,0.0,0.0);\n\n\nstatic Moses3 Tt(ScSO3(R.matrix()),Pp.vector());\nstatic Sim3 Ss(ScSO3(R.matrix()),Pp.vector());\nstatic Moses3 Ts(Ss);\n\nstatic Moses3 Tt1(ScSO3(2*R.matrix()),Pp.vector());\n\nstatic SE3 Se(R.matrix(),Pp.vector());\nstatic SE3 Se1(R1.matrix(),Pp1.vector());\n\nstatic Pose3 Po(R2,Pp);\nstatic Pose3 Po1(R2,Pp2);\n\nstatic Moses3 T(R,Point3(3.5,-8.2,4.2));\nstatic Moses3 T2(Rot3::rodriguez(0.3,0.2,0.1),Point3(3.5,-8.2,4.2));\nstatic Moses3 T3(Rot3::rodriguez(-90, 0, 0), Point3(1, 2, 3));\nconst double tol=1e-5;\n*/\nstatic Point3 P(0.2,0.7,-2);\nstatic Rot3 R = Rot3::rodriguez(0.3,0,0);\nstatic Moses3 T(R,Point3(3.5,-8.2,4.2));\nstatic Moses3 T2(Rot3::rodriguez(0.3,0.2,0.1),Point3(3.5,-8.2,4.2));\nstatic Moses3 T3(Rot3::rodriguez(-90, 0, 0), Point3(1, 2, 3));\n\nstatic Moses3 T4(ScSO3(2*Rot3::rodriguez(-90, 0, 0).matrix()), Point3(1, 2, 3).vector());\n\nconst double tol=1e-5;\n\n\n\n/* ************************************************************************* */\nTEST( Moses3, stream)\n{\n  Moses3 T;\n  std::ostringstream os;\n  os << T;\n  EXPECT(os.str() == \"1 * 1 0 0\\n0 1 0\\n0 0 1\\n\\n[0, 0, 0]';\\n\");\n}\n\n/* ************************************************************************* */\nTEST( Moses3, constructors)\n{\n  Moses3 expected(Rot3::rodriguez(0,0,3),Point3(1,2,0));\n  Pose2 pose2(1,2,3);\n  EXPECT(assert_equal(expected,Moses3(pose2)));\n}\n\n/* ************************************************************************* */\nTEST( Moses3, retract_expmap)\n{\n  Moses3 id;\n  Vector v = zero(7);\n  Rot3 Ro = Rot3::rodriguez(0.0,0,0);\n  v(6) = 0.0; //scale = e^this\n  EXPECT(assert_equal(Moses3(Ro, Point3()), id.retract(v, Moses3::EXPMAP),1e-2));\n  v(3) = 0.3; //rot1\n  EXPECT(assert_equal(Moses3(R, Point3()), id.retract(v, Moses3::EXPMAP),1e-2));  \n  v(0)=0.2;v(1)=0.394742;v(2)=-2.08998; //translation precalculated for P and R defined globle\n  EXPECT(assert_equal(Moses3(R, P),id.retract(v, Moses3::EXPMAP),1e-2));\n}\n\n/* ************************************************************************* */\nTEST( Moses3, expmap_a_full)\n{\n  Moses3 id;\n  Vector v = zero(7);\n  v(3) = 0.3;\n  EXPECT(assert_equal(expmap_default<Moses3>(id, v), Moses3(R, Point3())));\n  v(0)=0.2;v(1)=0.394742;v(2)=-2.08998;\n  EXPECT(assert_equal(Moses3(R, P),expmap_default<Moses3>(id, v),1e-5));\n}\n\n/* ************************************************************************* */\nTEST( Moses3, expmap_a_full2)\n{\n  Moses3 id;\n  Vector v = zero(7);\n  v(3) = 0.3;\n  EXPECT(assert_equal(expmap_default<Moses3>(id, v), Moses3(R, Point3())));\n  v(0)=0.2;v(1)=0.394742;v(2)=-2.08998;\n  EXPECT(assert_equal(Moses3(R, P),expmap_default<Moses3>(id, v),1e-5));\n}\n\n/* ************************************************************************* */\nTEST(Moses3, expmap_b)\n{\n  Moses3 p1(Rot3(), Point3(100, 0, 0));\n  Moses3 p2 = p1.retract((Vector(7) << 0.0, 0.0, 0.0, 0.0, 0.0, 0.1, 0.0));\n  Moses3 expected(Rot3::rodriguez(0.0, 0.0, 0.1), Point3(100.0, 0.0, 0.0));\n  EXPECT(assert_equal(expected, p2,1e-2));\n}\n\n/* ************************************************************************* */\n// test case for screw motion in the plane\nnamespace screw {\n  double a=0.3, c=cos(a), s=sin(a), w=0.3;\n  Vector xi = (Vector(7) << w, 0.0, 1.0 ,0.0, 0.0, w, 0.0);\n  Vector xi2 = (Vector(7) << w, 2.0, 1.0 ,0.0, 3.0, w, 1.0);\n\n  Vector si = (Vector(7) << w, 0.0, 1.0 ,0.0, 0.0, w);\n  Vector si2 = (Vector(7) << w, 2.0, 1.0 ,0.0, 3.0, w);\n\n  \n  Rot3 expectedR(c, -s, 0, s, c, 0, 0, 0, 1);\n  Point3 expectedT(0.29552, 0.0446635, 1);\n  Moses3 expected(expectedR, expectedT);\n}\n\n\n/* ************************************************************************* */\n// Checks correct exponential map (Expmap) with brute force matrix exponential\nTEST(Moses3, expmap_c_full)\n{\n  EXPECT(assert_equal(screw::expected, expm<Moses3>(screw::xi),1e-6));\n  EXPECT(assert_equal(screw::expected, Moses3::Expmap(screw::xi),1e-6));\n}\n\n/* ************************************************************************* */\n// assert that T*exp(xi)*T^-1 is equal to exp(Ad_T(xi))\nTEST(Moses3, Adjoint_full)\n{\n  Moses3 expected = T * Moses3::Expmap(screw::xi) * T.inverse();\n  Vector xiprime = T.Adjoint(screw::xi);\n  EXPECT(assert_equal(expected, Moses3::Expmap(xiprime), 1e-6));\n\n  Moses3 expected2 = T2 * Moses3::Expmap(screw::xi) * T2.inverse();\n  Vector xiprime2 = T2.Adjoint(screw::xi);\n  EXPECT(assert_equal(expected2, Moses3::Expmap(xiprime2), 1e-6));\n\n  Moses3 expected3 = T3 * Moses3::Expmap(screw::xi) * T3.inverse();\n  Vector xiprime3 = T3.Adjoint(screw::xi);\n  EXPECT(assert_equal(expected3, Moses3::Expmap(xiprime3), 1e-6));\n}\n\n\n/* ************************************************************************* */\n// Tested with scale\nTEST(Moses3, expmaps_galore_full)\n{\n  Vector xi; Moses3 actual;\n  xi = (Vector(7) << 0.4, 0.5, 0.6 ,0.1, 0.2, 0.3, 0.1);\n  actual = Moses3::Expmap(xi);\n  EXPECT(assert_equal(expm<Moses3>(xi), actual,1e-6));\n  //EXPECT(assert_equal(Agrawal06iros(xi), actual,1e-6));\n  EXPECT(assert_equal(xi, Moses3::Logmap(actual),1e-6));\n\n  xi = (Vector(7) << -0.4, 0.5, -0.6 ,0.1, -0.2, 0.3, 0.1);\n  for (double theta=1.0;0.3*theta<=M_PI;theta*=2) {\n    Vector txi = xi*theta;\n    actual = Moses3::Expmap(txi);\n    EXPECT(assert_equal(expm<Moses3>(txi,30), actual,1e-6));\n    //EXPECT(assert_equal(Agrawal06iros(txi), actual,1e-6));\n    Vector log = Moses3::Logmap(actual);\n    EXPECT(assert_equal(actual, Moses3::Expmap(log),1e-6));\n    EXPECT(assert_equal(txi,log,1e-6)); // not true once wraps\n  }\n\n  // Works with large v as well, but expm needs 10 iterations!\n  xi = (Vector(7) << 100.0, 120.0, -60.0 ,0.2, 0.3, -0.8, 0.1);\n  actual = Moses3::Expmap(xi);\n  EXPECT(assert_equal(expm<Moses3>(xi,10), actual,1e-5));\n  //EXPECT(assert_equal(Agrawal06iros(xi), actual,1e-6));\n  EXPECT(assert_equal(xi, Moses3::Logmap(actual),1e-6));\n}\n\n/* ************************************************************************* */\n// Tested with scale\nTEST(Moses3, Adjoint_compose_full)\n{\n  // To debug derivatives of compose, assert that\n  // T1*T2*exp(Adjoint(inv(T2),x) = T1*exp(x)*T2\n  const Moses3& T1 = T;\n  Vector x = (Vector(7) << 0.4, 0.2, 0.8 ,0.1, 0.1, 0.1, 0.0);\n  Moses3 expected = T1 * Moses3::Expmap(x) * T2;\n  Vector y = T2.inverse().Adjoint(x);\n  Moses3 actual = T1 * T2 * Moses3::Expmap(y);\n  EXPECT(assert_equal(expected, actual, 1e-6));\n}\n\n/* ************************************************************************* */\n// Check compose and its pushforward\n// NOTE: testing::compose<Pose3>(t1,t2) = t1.compose(t2)  (see lieProxies.h)\n// Tested with scale\nTEST( Moses3, compose )\n{\n\n  const Moses3& T6 = T2;\n  gtsam::Matrix actual = (T6*T6).matrix();\n  \n  gtsam::Matrix expected = T6.matrix()*T6.matrix();\n  EXPECT(assert_equal(actual,expected,1e-8));\n\n  gtsam::Matrix actualDcompose1, actualDcompose2;\n  T6.compose(T6, actualDcompose1, actualDcompose2);\n\n  gtsam::Matrix numericalH1 = numericalDerivative21(testing::compose<Moses3>, T6, T6);\n  EXPECT(assert_equal(numericalH1,actualDcompose1,5e-3));\n  EXPECT(assert_equal(T6.inverse().AdjointMap(),actualDcompose1,5e-3));\n\n  gtsam::Matrix numericalH2 = numericalDerivative22(testing::compose<Moses3>, T6, T6);\n  EXPECT(assert_equal(numericalH2,actualDcompose2,1e-4));\n}\n\n/* ************************************************************************* */\n// Check compose and its pushforward, another case \n//Tested with scale\nTEST( Moses3, compose2 )\n{\n  const Moses3& T1 = T;\n  gtsam::Matrix actual = (T1*T2).matrix();\n  gtsam::Matrix expected = T1.matrix()*T2.matrix();\n  EXPECT(assert_equal(actual,expected,1e-8));\n\n  gtsam::Matrix actualDcompose1, actualDcompose2;\n  T1.compose(T2, actualDcompose1, actualDcompose2);\n\n  gtsam::Matrix numericalH1 = numericalDerivative21(testing::compose<Moses3>, T1, T2);\n  EXPECT(assert_equal(numericalH1,actualDcompose1,5e-3));\n  EXPECT(assert_equal(T2.inverse().AdjointMap(),actualDcompose1,5e-3));\n\n  gtsam::Matrix numericalH2 = numericalDerivative22(testing::compose<Moses3>, T1, T2);\n  EXPECT(assert_equal(numericalH2,actualDcompose2,1e-5));\n}\n\n\n/* ************************************************************************* */\n// Tested with scale\nTEST( Moses3, inverse)\n{\n  const Moses3& T5 = T4;\n  gtsam::Matrix actualDinverse;\n  gtsam::Matrix actual = T5.inverse(actualDinverse).matrix();\n  gtsam::Matrix expected = inverse(T5.matrix());\n  EXPECT(assert_equal(actual,expected,1e-8));\n\n  gtsam::Matrix numericalH = numericalDerivative11(testing::inverse<Moses3>, T5);\n  EXPECT(assert_equal(numericalH,actualDinverse,5e-3));\n  EXPECT(assert_equal(-T5.AdjointMap(),actualDinverse,5e-3));\n}\n\n\n/* ************************************************************************* */\nTEST( Moses3, inverseDerivatives2)\n{\n  Rot3 R = Rot3::rodriguez(0.3,0.4,-0.5);\n  Point3 t(3.5,-8.2,4.2);\n  Moses3 T(R,t);\n\n  gtsam::Matrix numericalH = numericalDerivative11(testing::inverse<Moses3>, T);\n  gtsam::Matrix actualDinverse;\n  T.inverse(actualDinverse);\n  EXPECT(assert_equal(numericalH,actualDinverse,5e-3));\n  EXPECT(assert_equal(-T.AdjointMap(),actualDinverse,5e-3));\n}\n\n/* ************************************************************************* */\nTEST( Moses3, compose_inverse)\n{\n  gtsam::Matrix actual = (T*T.inverse()).matrix();\n  gtsam::Matrix expected = eye(4,4);\n  EXPECT(assert_equal(actual,expected,1e-8));\n}\n\n/* ************************************************************************* */\n// Jacobian Scale hacked. Not correct.\nPoint3 transform_from_(const Moses3& pose, const Point3& point) { return pose.transform_from(point); }\n\n\nTEST( Moses3, Dtransform_from1_a)\n{\n  gtsam::Matrix actualDtransform_from1;\n  T.transform_from(P, actualDtransform_from1, boost::none);\n  gtsam::Matrix numerical = numericalDerivative21(transform_from_,T,P);\n  EXPECT(assert_equal(numerical,actualDtransform_from1,1e-8));\n}\n\nTEST( Moses3, Dtransform_from1_b)\n{\n  Moses3 origin(ScSO3(2*Rot3::rodriguez(1.0,0.0,1.0).matrix()),Point3(0.0,1.0,0.0));\n  Point3 Pee(1.0,10.0,1.0);\n  gtsam::Matrix actualDtransform_from1;\n  origin.transform_from(Pee, actualDtransform_from1, boost::none);\n  gtsam::Matrix numerical = numericalDerivative21(transform_from_,origin,Pee);\n  EXPECT(assert_equal(numerical,actualDtransform_from1,1e-8));\n}\n\nTEST( Moses3, Dtransform_from1_c)\n{\n  Point3 origin;\n  Moses3 T0(R,origin);\n  gtsam::Matrix actualDtransform_from1;\n  T0.transform_from(P, actualDtransform_from1, boost::none);\n  gtsam::Matrix numerical = numericalDerivative21(transform_from_,T0,P);\n  EXPECT(assert_equal(numerical,actualDtransform_from1,1e-8));\n}\n\nTEST( Moses3, Dtransform_from1_d)\n{\n  Rot3 I;\n  Point3 t0(100,0,0);\n  Moses3 T0(I,t0);\n  gtsam::Matrix actualDtransform_from1;\n  T0.transform_from(P, actualDtransform_from1, boost::none);\n  //print(computed, \"Dtransform_from1_d computed:\");\n  gtsam::Matrix numerical = numericalDerivative21(transform_from_,T0,P);\n  //print(numerical, \"Dtransform_from1_d numerical:\");\n  EXPECT(assert_equal(numerical,actualDtransform_from1,1e-8));\n}\n\n/* ************************************************************************* */\nTEST( Moses3, Dtransform_from2)\n{\n  gtsam::Matrix actualDtransform_from2;\n  T.transform_from(P, boost::none, actualDtransform_from2);\n  gtsam::Matrix numerical = numericalDerivative22(transform_from_,T,P);\n  EXPECT(assert_equal(numerical,actualDtransform_from2,1e-8));\n}\n\n/* ************************************************************************* */\nPoint3 transform_to_(const Moses3& pose, const Point3& point) { return pose.transform_to(point); }\nTEST( Moses3, Dtransform_to1)\n{\n  gtsam::Matrix computed;\n  T.transform_to(P, computed, boost::none);\n  gtsam::Matrix numerical = numericalDerivative21(transform_to_,T,P);\n  EXPECT(assert_equal(numerical,computed,1e-8));\n}\n\n/* ************************************************************************* */\nTEST( Moses3, Dtransform_to2)\n{\n  gtsam::Matrix computed;\n  T.transform_to(P, boost::none, computed);\n  gtsam::Matrix numerical = numericalDerivative22(transform_to_,T,P);\n  EXPECT(assert_equal(numerical,computed,1e-8));\n}\n\n/* ************************************************************************* */\nTEST( Moses3, transform_to_with_derivatives)\n{\n  gtsam::Matrix actH1, actH2;\n  T.transform_to(P,actH1,actH2);\n  gtsam::Matrix expH1 = numericalDerivative21(transform_to_, T,P),\n       expH2 = numericalDerivative22(transform_to_, T,P);\n  EXPECT(assert_equal(expH1, actH1, 1e-8));\n  EXPECT(assert_equal(expH2, actH2, 1e-8));\n}\n\n/* ************************************************************************* */\nTEST( Moses3, transform_from_with_derivatives)\n{\n  gtsam::Matrix actH1, actH2;\n  T.transform_from(P,actH1,actH2);\n  gtsam::Matrix expH1 = numericalDerivative21(transform_from_, T,P),\n       expH2 = numericalDerivative22(transform_from_, T,P);\n  EXPECT(assert_equal(expH1, actH1, 1e-8));\n  EXPECT(assert_equal(expH2, actH2, 1e-8));\n}\n\n/* ************************************************************************* */\n//Will not test with scale as answer is hard coded. Manually scale checked.\nTEST( Moses3, transform_to_translate)\n{\n    Point3 actual = Moses3(ScSO3(1*Rot3().matrix()), Point3(1, 2, 3).vector()).transform_to(Point3(10.,20.,30.));\n    Point3 expected(9.,18.,27.);\n    EXPECT(assert_equal(expected, actual));\n}\n\n/* ************************************************************************* */\n//Will not test with scale as answer is hard coded. Manually scale checked.\nTEST( Moses3, transform_to_rotate)\n{\n    Moses3 transform(ScSO3(1*Rot3::rodriguez(0,0,-1.570796).matrix()), Point3());\n    Point3 actual = transform.transform_to(Point3(2,1,10));\n    Point3 expected(-1,2,10);\n    EXPECT(assert_equal(expected, actual, 0.001));\n}\n\n/* ************************************************************************* */\n//Will not test with scale as answer is hard coded. Manually scale check.\nTEST( Moses3, transform_to)\n{\n    Moses3 transform(Rot3::rodriguez(0,0,-1.570796), Point3(2,4, 0));\n    Point3 actual = transform.transform_to(Point3(3,2,10));\n    Point3 expected(2,1,10);\n    EXPECT(assert_equal(expected, actual, 0.001));\n}\n\n/* ************************************************************************* */\n//Will not test with scale as answer is hard coded. Manually scale check.\nTEST( Moses3, transform_from)\n{\n    Point3 actual = T3.transform_from(Point3());\n    Point3 expected = Point3(1.,2.,3.);\n    EXPECT(assert_equal(expected, actual));\n}\n\n/* ************************************************************************* */\n//Scale checked\nTEST( Moses3, transform_roundtrip)\n{\n    Point3 actual = T4.transform_from(T4.transform_to(Point3(12., -0.11,7.0)));\n    Point3 expected(12., -0.11,7.0);\n    EXPECT(assert_equal(expected, actual));\n}\n\n/* ************************************************************************* */\n//Scale checked\nTEST( Moses3, transformPose_to_origin)\n{\n    // transform to origin\n    Moses3 actual = T4.transform_to(Moses3());\n    EXPECT(assert_equal(T4, actual, 1e-8));\n}\n\n/* ************************************************************************* */\n// Scale checked\nTEST( Moses3, transformPose_to_itself)\n{\n    // transform to itself\n    Moses3 actual = T4.transform_to(T4);\n    EXPECT(assert_equal(Moses3(), actual, 1e-8));\n}\n\n/* ************************************************************************* */\n//Will not test with scale as answer is hard coded. Manually scale check.\nTEST( Moses3, transformPose_to_translation)\n{\n    // transform translation only\n    Rot3 r = Rot3::rodriguez(-1.570796,0,0);\n    Moses3 pose2(r, Point3(21.,32.,13.));\n    Moses3 actual = pose2.transform_to(Moses3(Rot3(), Point3(1,2,3)));\n    Moses3 expected(r, Point3(20.,30.,10.));\n    EXPECT(assert_equal(expected, actual, 1e-8));\n}\n\n/* ************************************************************************* */\n//Will not test with scale as answer is hard coded. Manually scale check.\nTEST( Moses3, transformPose_to_simple_rotate)\n{\n    // transform translation only\n    Rot3 r = Rot3::rodriguez(0,0,-1.570796);\n    Moses3 pose2(r, Point3(21.,32.,13.));\n    Moses3 transform(r, Point3(1,2,3));\n    Moses3 actual = pose2.transform_to(transform);\n    Moses3 expected(Rot3(), Point3(-30.,20.,10.));\n    EXPECT(assert_equal(expected, actual, 0.001));\n}\n\n/* ************************************************************************* */\n//Will not test with scale as answer is hard coded. Manually scale check.\nTEST( Moses3, transformPose_to)\n{\n    // transform to\n    Rot3 r = Rot3::rodriguez(0,0,-1.570796); //-90 degree yaw\n    Rot3 r2 = Rot3::rodriguez(0,0,0.698131701); //40 degree yaw\n    Moses3 pose2(r2, Point3(21.,32.,13.));\n    Moses3 transform(r, Point3(1,2,3));\n    Moses3 actual = pose2.transform_to(transform);\n    Moses3 expected(Rot3::rodriguez(0,0,2.26892803), Point3(-30.,20.,10.));\n    EXPECT(assert_equal(expected, actual, 0.001));\n}\n\n/* ************************************************************************* */\n//scale tested\nTEST(Moses3, localCoordinates_first_order)\n{\n  Vector d12 = repeat(7,0.1);\n  Moses3 t1 = T, t2 = t1.retract(d12);\n  EXPECT(assert_equal(d12, t1.localCoordinates(t2)));\n}\n\n/* ************************************************************************* */\n//Scale tested\nTEST(Moses3, manifold_expmap)\n{\n  Moses3 t1 = T4;\n  Moses3 t2 = T3;\n  Moses3 origin;\n  Vector d12 = t1.localCoordinates(t2);\n  EXPECT(assert_equal(t2, t1.retract(d12)));\n  Vector d21 = t2.localCoordinates(t1);\n  EXPECT(assert_equal(t1, t2.retract(d21)));\n\n  // Check that log(t1,t2)=-log(t2,t1)\n  EXPECT(assert_equal(d12,-d21));\n}\n\n/* ************************************************************************* */\nTEST(Moses3, subgroups)\n{\n  // Frank - Below only works for correct \"Agrawal06iros style expmap\n  // lines in canonical coordinates correspond to Abelian subgroups in SE(3)\n   Vector d = (Vector(7) << 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7);\n  // exp(-d)=inverse(exp(d))\n   EXPECT(assert_equal(Moses3::Expmap(-d),Moses3::Expmap(d).inverse()));\n  // exp(5d)=exp(2*d+3*d)=exp(2*d)exp(3*d)=exp(3*d)exp(2*d)\n   Moses3 T2 = Moses3::Expmap(2*d);\n   Moses3 T3 = Moses3::Expmap(3*d);\n   Moses3 T5 = Moses3::Expmap(5*d);\n   EXPECT(assert_equal(T5,T2*T3));\n   EXPECT(assert_equal(T5,T3*T2));\n}\n\n/* ************************************************************************* */\n// Scale tested\nTEST( Moses3, between )\n{\n  Moses3 expected = T2.inverse() * T4;\n  gtsam::Matrix actualDBetween1,actualDBetween2;\n  Moses3 actual = T2.between(T4, actualDBetween1,actualDBetween2);\n  EXPECT(assert_equal(expected,actual));\n\n  gtsam::Matrix numericalH1 = numericalDerivative21(testing::between<Moses3> , T2, T4);\n  EXPECT(assert_equal(numericalH1,actualDBetween1,5e-3));\n\n  gtsam::Matrix numericalH2 = numericalDerivative22(testing::between<Moses3> , T2, T4);\n  EXPECT(assert_equal(numericalH2,actualDBetween2,1e-5));\n}\n\n/* ************************************************************************* */\n// some shared test values - pulled from equivalent test in Pose2\nconst Point3 l1(1, 0, 0), l2(1, 1, 0), l3(2, 2, 0), l4(1, 4,-4);\nconst Moses3 x1, x2(Rot3::ypr(0.0, 0.0, 0.0), l2), x3(Rot3::ypr(M_PI/4.0, 0.0, 0.0), l2);\nconst Moses3\n    xl1(Rot3::ypr(0.0, 0.0, 0.0), Point3(1, 0, 0)),\n    xl2(Rot3::ypr(0.0, 1.0, 0.0), Point3(1, 1, 0)),\n    xl3(Rot3::ypr(1.0, 0.0, 0.0), Point3(2, 2, 0)),\n    xl4(Rot3::ypr(0.0, 0.0, 1.0), Point3(1, 4,-4));\n\n/* ************************************************************************* */\nLieVector range_proxy(const Moses3& pose, const Point3& point) {\n  return LieVector(pose.range(point));\n}\n\n// Scale Tested\nTEST( Moses3, range )\n{\n  gtsam::Matrix expectedH1, actualH1, expectedH2, actualH2;\n\n\n  Moses3 sx(ScSO3(2*Rot3::ypr(0.0, 0.0, 0.0).matrix()), Point3(1.0,1.0,0.0));\n  EXPECT_DOUBLES_EQUAL(sqrt(2)/2,sx.range(l3, actualH1, actualH2),1e-9);\n  expectedH1 = numericalDerivative21(range_proxy, sx, l3);\n  expectedH2 = numericalDerivative22(range_proxy, sx, l3);\n  EXPECT(assert_equal(expectedH1,actualH1));\n  EXPECT(assert_equal(expectedH2,actualH2));\n\n\n\n  // establish range is indeed zero\n  EXPECT_DOUBLES_EQUAL(1,x1.range(l1),1e-9);\n\n  // establish range is indeed sqrt2\n  EXPECT_DOUBLES_EQUAL(sqrt(2.0),x1.range(l2),1e-9);\n\n  // Another pair\n  double actual23 = x2.range(l3, actualH1, actualH2);\n  EXPECT_DOUBLES_EQUAL(sqrt(2.0),actual23,1e-9);\n\n  // Check numerical derivatives\n  expectedH1 = numericalDerivative21(range_proxy, x2, l3);\n  expectedH2 = numericalDerivative22(range_proxy, x2, l3);\n  EXPECT(assert_equal(expectedH1,actualH1));\n  EXPECT(assert_equal(expectedH2,actualH2));\n\n  // Another test\n  double actual34 = x3.range(l4, actualH1, actualH2);\n  EXPECT_DOUBLES_EQUAL(5,actual34,1e-9);\n\n  // Check numerical derivatives\n  expectedH1 = numericalDerivative21(range_proxy, x3, l4);\n  expectedH2 = numericalDerivative22(range_proxy, x3, l4);\n  EXPECT(assert_equal(expectedH1,actualH1));\n  EXPECT(assert_equal(expectedH2,actualH2));\n}\n\n\nLieVector range_pose_proxy(const Moses3& pose, const Moses3& point) {\n  return LieVector(pose.range(point));\n}\n\n// IMPORTANT ThIS NEEDS FURTHER TESTING\nTEST( Moses3, range_pose )\n{\n  gtsam::Matrix expectedH1, actualH1, expectedH2, actualH2;\n\n  //scale\n  Moses3 sx(ScSO3(3*Rot3::ypr(0.0, 0.0, 0.0).matrix()), Point3(0.0,0.0,0.0));\n  Moses3 sx1(ScSO3(6*Rot3::ypr(0.0, 0.0, 0.0).matrix()), Point3(1.0,1.0,0.0));\n\n  //EXPECT_DOUBLES_EQUAL(sqrt(2),sx.range(sx1),1e-9);\n  sx1.range(sx,actualH1, actualH2);\n  // Check numerical derivatives //scale checked\n  expectedH1 = numericalDerivative21(range_pose_proxy, sx1, sx);\n  expectedH2 = numericalDerivative22(range_pose_proxy, sx1, sx);\n  EXPECT(assert_equal(expectedH1,actualH1));\n  EXPECT(assert_equal(expectedH2,actualH2));\n\n  // establish range is indeed zero\n  EXPECT_DOUBLES_EQUAL(1,x1.range(xl1),1e-9);\n\n  // establish range is indeed sqrt2\n  EXPECT_DOUBLES_EQUAL(sqrt(2.0),x1.range(xl2),1e-9);\n\n  // Another pair\n  double actual23 = x2.range(xl3, actualH1, actualH2);\n  EXPECT_DOUBLES_EQUAL(sqrt(2.0),actual23,1e-9);\n\n\n  // Check numerical derivatives\n  expectedH1 = numericalDerivative21(range_pose_proxy, x2, xl3);\n  expectedH2 = numericalDerivative22(range_pose_proxy, x2, xl3);\n  EXPECT(assert_equal(expectedH1,actualH1));\n  EXPECT(assert_equal(expectedH2,actualH2));\n\n  // Another test\n  double actual34 = x3.range(xl4, actualH1, actualH2);\n  EXPECT_DOUBLES_EQUAL(5,actual34,1e-9);\n\n  // Check numerical derivatives\n  expectedH1 = numericalDerivative21(range_pose_proxy, x3, xl4);\n  expectedH2 = numericalDerivative22(range_pose_proxy, x3, xl4);\n  EXPECT(assert_equal(expectedH1,actualH1));\n  EXPECT(assert_equal(expectedH2,actualH2));\n}\n\n/* ************************************************************************* */\n// scale not checked\nTEST( Moses3, unicycle )\n{\n  // velocity in X should be X in inertial frame, rather than global frame\n  Vector x_step = delta(7,0,1.0);\n  EXPECT(assert_equal(Moses3(Rot3::ypr(0,0,0), l1), expmap_default<Moses3>(x1, x_step), tol));\n  EXPECT(assert_equal(Moses3(Rot3::ypr(0,0,0), Point3(2,1,0)), expmap_default<Moses3>(x2, x_step), tol));\n  EXPECT(assert_equal(Moses3(Rot3::ypr(M_PI/4.0,0,0), Point3(2,2,0)), expmap_default<Moses3>(x3, sqrt(2.0) * x_step), tol));\n}\n\n/* ************************************************************************* */\n// This is doubtful\n/*\n  //SIGN CONFLICT!!\n  cout << \"Moses3::adjoint\"<<endl;\n  cout << Moses3::adjoint(screw::xi,screw::xi2) << endl;\n  cout << \"Sim3::lieBracket\"<<endl;\n  cout << Sim3::lieBracket(screw::xi, screw::xi2) << endl;\n\n\n  cout << \"SE3::adjointMap\"<<endl;\n  cout << SE3::d_lieBracketab_by_d_a(screw::si)*screw::si2 << endl;\n  cout << \"SE3::lieBracket\"<<endl;\n  cout << SE3::lieBracket(screw::si, screw::si2) << endl;\n*/\nTEST( Moses3, adjointMap) {\n  gtsam::Matrix res = Moses3::adjointMap(screw::xi);\n  gtsam::Matrix wh = skewSymmetric(screw::xi(0), screw::xi(1), screw::xi(2));\n  gtsam::Matrix vh = skewSymmetric(screw::xi(3), screw::xi(4), screw::xi(5));\n  gtsam::Matrix Z3 = zeros(3,3);\n  gtsam::Matrix6 expected;\n  expected << wh, Z3, vh, wh;\n  EXPECT(assert_equal(res,res,1e-5));\n}\n\n//Vector xi = (Vector(6) << 0.1, 0.2, 0.3, 1.0, 2.0, 3.0, 0.0);\n\n/* ************************************************************************* */\nVector testDerivAdjoint(const LieVector& xi, const LieVector& v) {\n  return Moses3::adjointMap(xi)*v;\n}\n\nTEST( Moses3, adjoint) {\n  Vector expected = testDerivAdjoint(screw::xi, screw::xi2);\n\n  gtsam::Matrix actualH;\n  Vector actual = Moses3::adjoint(screw::xi, screw::xi2, actualH);\n\n  gtsam::Matrix numericalH = numericalDerivative21(\n      boost::function<Vector(const LieVector&, const LieVector&)>(\n          boost::bind(testDerivAdjoint,  _1, _2)\n          ),\n      LieVector(screw::xi), LieVector(screw::xi2), 1e-5\n      );\n\n  EXPECT(assert_equal(expected,actual,1e-5));\n  EXPECT(assert_equal(numericalH,actualH,1e-5));\n}\n\n\n/* ************************************************************************* */\nVector testDerivAdjointTranspose(const LieVector& xi, const LieVector& v) {\n  return Moses3::adjointMap(xi).transpose()*v;\n}\n\nTEST( Moses3, adjointTranspose) {\n  Vector xi = (Vector(7) << 0.01, 0.02, 0.03, 1.0, 2.0, 3.0, 0.1);\n  Vector v = (Vector(7) << 0.04, 0.05, 0.06, 4.0, 5.0, 6.0, 0.2);\n  Vector expected = testDerivAdjointTranspose(xi, v);\n\n  gtsam::Matrix actualH;\n  Vector actual = Moses3::adjointTranspose(xi, v, actualH);\n\n  gtsam::Matrix numericalH = numericalDerivative21(\n      boost::function<Vector(const LieVector&, const LieVector&)>(\n          boost::bind(testDerivAdjointTranspose,  _1, _2)\n          ),\n      LieVector(xi), LieVector(v), 1e-5\n      );\n\n  EXPECT(assert_equal(expected,actual,1e-15));\n  EXPECT(assert_equal(numericalH,actualH,1e-5));\n}\n\n\n/* ************************************************************************* \n/// exp(xi) exp(y) = exp(xi + x)\n/// Hence, y = log (exp(-xi)*exp(xi+x))\n\nVector xi = (Vector(6) << 0.1, 0.2, 0.3, 1.0, 2.0, 3.0);\n\nVector testDerivExpmapInv(const LieVector& dxi) {\n  Vector y = Pose3::Logmap(Pose3::Expmap(-xi)*Pose3::Expmap(xi+dxi));\n  return y;\n}\n\nTEST( Pose3, dExpInv_TLN) {\n  Matrix res = Pose3::dExpInv_exp(xi);\n\n  Matrix numericalDerivExpmapInv = numericalDerivative11(\n      boost::function<Vector(const LieVector&)>(\n          boost::bind(testDerivExpmapInv,  _1)\n          ),\n      LieVector(Vector::Zero(6)), 1e-5\n      );\n\n  EXPECT(assert_equal(numericalDerivExpmapInv,res,3e-1));\n}*/\n\n\n\n\n\n\n/* ************************************************************************* */\nbool moses3bracket_tests()\n{\n  bool failed = false;\n  vector<Vector7> vecs;\n  Vector7 tmp;\n  tmp << 0,0,0,0,0,0,0;\n  vecs.push_back(tmp);\n  tmp << 1,0,0,0,0,0,0;\n  vecs.push_back(tmp);\n  tmp << 0,1,0,1,0,0,0.1;\n  vecs.push_back(tmp);\n  tmp << 0,0,1,0,1,0,0.1;\n  vecs.push_back(tmp);\n  tmp << -1,1,0,0,0,1,-0.1;\n  vecs.push_back(tmp);\n  tmp << 20,-1,0,-1,1,0,-0.1;\n  vecs.push_back(tmp);\n  tmp << 30,5,-1,20,-1,0,2;\n  vecs.push_back(tmp);\n  for (size_t i=0; i<vecs.size(); ++i)\n  {\n    Vector7 resDiff = vecs[i] - Moses3::vee(Moses3::hat(vecs[i]));\n    if (resDiff.norm()>SMALL_EPS)\n    {\n      cerr << \"Hat-vee Test\" << endl;\n      cerr  << \"Test case: \" << i <<  endl;\n      cerr << resDiff.transpose() << endl;\n      cerr << endl;\n      failed = true;\n    }\n\n    for (size_t j=0; j<vecs.size(); ++j)\n    {\n      Vector7 res1 = Moses3::lieBracket(vecs[i],vecs[j]);\n      Matrix4 hati = Moses3::hat(vecs[i]);\n      Matrix4 hatj = Moses3::hat(vecs[j]);\n\n      Vector7 res2 = Moses3::vee(hati*hatj-hatj*hati);\n      Vector7 resDiff = res1-res2;\n      if (resDiff.norm()>SMALL_EPS)\n      {\n        cerr << \"Sim3 Lie Bracket Test\" << endl;\n        cerr  << \"Test case: \" << i << \", \" <<j<< endl;\n        cerr << vecs[i].transpose() << endl;\n        cerr << vecs[j].transpose() << endl;\n        cerr << resDiff.transpose() << endl;\n        cerr << endl;\n        failed = true;\n      }\n    }\n\n\n    /*\n    Vector7 omega = vecs[i];\n    Matrix4 exp_x = Moses3::exp(omega).matrix();\n    Matrix4 expmap_hat_x = (Moses3::hat(omega)).exp();\n    Matrix4 DiffR = exp_x-expmap_hat_x;\n    double nrm = DiffR.norm();\n\n    if (isnan(nrm) || nrm>SMALL_EPS)\n    {\n      cerr << \"expmap(hat(x)) - exp(x)\" << endl;\n      cerr  << \"Test case: \" << i << endl;\n      cerr << exp_x <<endl;\n      cerr << expmap_hat_x <<endl;\n      cerr << DiffR <<endl;\n      cerr << endl;\n      failed = true;\n    }*/\n  }\n  return failed;\n}\n\n/* ********************************************************************** */\n\nbool Moses3explog_tests()\n{\n  double pi = 3.14159265;\n  vector<Moses3> omegas;\n  omegas.push_back(Moses3(ScSO3::exp(Vector4(0.2, 0.5, 0.0,1.)),Vector3(0,0,0)));\n  omegas.push_back(Moses3(ScSO3::exp(Vector4(0.2, 0.5, -1.0,1.1)),Vector3(10,0,0)));\n  omegas.push_back(Moses3(ScSO3::exp(Vector4(0., 0., 0.,1.1)),Vector3(0,100,5)));\n  omegas.push_back(Moses3(ScSO3::exp(Vector4(0., 0., 0.00001, 0.)),Vector3(0,0,0)));\n  omegas.push_back(Moses3(ScSO3::exp(Vector4(0., 0., 0.00001, 0.0000001)),Vector3(1,-1.00000001,2.0000000001)));\n  omegas.push_back(Moses3(ScSO3::exp(Vector4(0., 0., 0.00001, 0)),Vector3(0.01,0,0)));\n  omegas.push_back(Moses3(ScSO3::exp(Vector4(pi, 0, 0,0.9)),Vector3(4,-5,0)));\n  omegas.push_back(Moses3(ScSO3::exp(Vector4(0.2, 0.5, 0.0,0)),Vector3(0,0,0))\n                   *Moses3(ScSO3::exp(Vector4(pi, 0, 0,0)),Vector3(0,0,0))\n                   *Moses3(ScSO3::exp(Vector4(-0.2, -0.5, -0.0,0)),Vector3(0,0,0)));\n  omegas.push_back(Moses3(ScSO3::exp(Vector4(0.3, 0.5, 0.1,0)),Vector3(2,0,-7))\n                   *Moses3(ScSO3::exp(Vector4(pi, 0, 0,0)),Vector3(0,0,0))\n                   *Moses3(ScSO3::exp(Vector4(-0.3, -0.5, -0.1,0)),Vector3(0,6,0)));\n\n  bool failed = false;\n\n  for (size_t i=0; i<omegas.size(); ++i)\n  {\n    Matrix4 R1 = omegas[i].matrix();\n    Matrix4 R2 = Moses3::Expmap(omegas[i].Logmap7()).matrix();\n    Matrix4 DiffR = R1-R2;\n    double nrm = DiffR.norm();\n\n    // ToDO: Force Sim3 to be more accurate!\n    if (isnan(nrm) || nrm>SMALL_EPS)\n    {\n      cerr << \"Sim3 - exp(log(Sim3))\" << endl;\n      cerr  << \"Test case: \" << i << endl;\n      cerr << DiffR <<endl;\n      cerr << endl;\n      failed = true;\n    }\n  }\n  for (size_t i=0; i<omegas.size(); ++i)\n  {\n    Vector3 p(1,2,4);\n    Matrix4 T = omegas[i].matrix();\n    Vector3 res1 = static_cast<const Sim3 &>(omegas[i])*p;\n    Vector3 res2 = T.topLeftCorner<3,3>()*p + T.topRightCorner<3,1>();\n\n    double nrm = (res1-res2).norm();\n\n    if (isnan(nrm) || nrm>SMALL_EPS)\n    {\n      cerr << \"Transform vector\" << endl;\n      cerr  << \"Test case: \" << i << endl;\n      cerr << (res1-res2) <<endl;\n      cerr << endl;\n      failed = true;\n    }\n  }\n\n  for (size_t i=0; i<omegas.size(); ++i)\n  {\n    Matrix4 q = omegas[i].matrix();\n    Matrix4 inv_q = omegas[i].inverse().matrix();\n    Matrix4 res = q*inv_q ;\n    Matrix4 I;\n    I.setIdentity();\n\n    double nrm = (res-I).norm();\n\n    if (isnan(nrm) || nrm>SMALL_EPS)\n    {\n      cerr << \"Inverse\" << endl;\n      cerr  << \"Test case: \" << i << endl;\n      cerr << (res-I) <<endl;\n      cerr << endl;\n      failed = true;\n    }\n  }\n  return failed;\n}\n\n\n/* ************************************************************************* */\nint main(){ \n  TestResult tr;\n/*\n  Vector7d tmp;\n  tmp << 0,0,0,0,0,0,0;\n\n\n  cout << Tt;\n  cout << Tt.to_Pose3();\n\n  cout << Tt1;\n  cout << Tt1.to_Pose3();\n\n  cout << Tt1.inverse();\n  cout << Tt1.inverse().to_Pose3();\n\n  cout << Tt1*Tt1.inverse();\n  cout << (Tt1*Tt1.inverse()).to_Pose3();\n\n\n\n  cout << Se;\n  cout << Se1;\n  cout << (Se*Se1);\n\n  cout << Po;\n  cout << Po1;\n\n  cout << Po1.between(Po);\n  cout << Po1.compose(Po.inverse());\n\n*/\n\n  bool failed = Moses3explog_tests();\n  cout << failed<<endl;\n\n  failed = moses3bracket_tests();\n  cout << failed<<endl;\n/*\n  //SIGN CONFLICT!!\n  cout << \"Moses3::adjoint\"<<endl;\n  cout << Moses3::adjoint(screw::xi,screw::xi2) << endl;\n  cout << \"Sim3::lieBracket\"<<endl;\n  cout << Sim3::lieBracket(screw::xi, screw::xi2) << endl;\n\n\n  cout << \"SE3::adjointMap\"<<endl;\n  cout << SE3::d_lieBracketab_by_d_a(screw::si)*screw::si2 << endl;\n  cout << \"SE3::lieBracket\"<<endl;\n  cout << SE3::lieBracket(screw::si, screw::si2) << endl;\n*/\n  return TestRegistry::runAllTests(tr);}\n/* ************************************************************************* */\n", "meta": {"hexsha": "a6576abf131f757763b521f2bb52b761366e7498", "size": 33433, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/geometry/tests/testMoses3.cpp", "max_stars_repo_name": "fa21autonomy/gtsam", "max_stars_repo_head_hexsha": "5f15d264ed639cb0add335e2b089086141127fff", "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/geometry/tests/testMoses3.cpp", "max_issues_repo_name": "fa21autonomy/gtsam", "max_issues_repo_head_hexsha": "5f15d264ed639cb0add335e2b089086141127fff", "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/geometry/tests/testMoses3.cpp", "max_forks_repo_name": "fa21autonomy/gtsam", "max_forks_repo_head_hexsha": "5f15d264ed639cb0add335e2b089086141127fff", "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": 33.3996003996, "max_line_length": 124, "alphanum_fraction": 0.589297999, "num_tokens": 10767, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.4943898436371374}}
{"text": "/*********************************************************************\n *\n * Software License Agreement (BSD License)\n *\n *  Copyright (c) 2014, Daichi Yoshikawa\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 Daichi Yoshikawa 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: Daichi Yoshikawa\n *\n *********************************************************************/\n\n#ifndef __GL_WRAPPER_MATH_QUATERNION_HPP\n#define __GL_WRAPPER_MATH_QUATERNION_HPP\n\n#include <Eigen/Dense>\n#include <gl_wrapper/exception/exceptions.hpp>\n\nnamespace gl_wrapper\n{\n\n  class Quaternion\n  {\n  public:\n    Quaternion();\n    Quaternion(double x, double y, double z, double w);\n    Quaternion(const Eigen::Vector3d& axis, double angle);\n    Quaternion(const Eigen::Vector3d& pos);\n\n    Quaternion& operator=(const Quaternion& q);\n    void operator*=(Quaternion& q);\n    const Quaternion operator*(Quaternion& q) const;\n\n    Quaternion inverse();\n    Quaternion& rotateWith(Quaternion& q);\n\n    const double getNorm() const\n    {\n      return sqrt(x_ * x_ + y_ * y_ + z_ * z_ + w_ * w_);\n    }\n\n    const double getX() const\n    {\n      return x_;\n    }\n\n    const double getY() const\n    {\n      return y_;\n    }\n\n    const double getZ() const\n    {\n      return z_;\n    }\n\n    const double getW() const\n    {\n      return w_;\n    }\n\n  private:\n    double x_;\n    double y_;\n    double z_;\n    double w_;\n  };\n\n}\n\n#endif /* __GL_WRAPPER_MATH_QUATERNION_HPP */\n", "meta": {"hexsha": "8d1fd9eccf755bf033f2b78a0981036bb0d2a76f", "size": 2907, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "wrapper/gl_wrapper/include/gl_wrapper/render/quaternion.hpp", "max_stars_repo_name": "daichi-yoshikawa/ahl_common", "max_stars_repo_head_hexsha": "7c720728d97f9b0bc2d85d4bc875b34b2372d094", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "wrapper/gl_wrapper/include/gl_wrapper/render/quaternion.hpp", "max_issues_repo_name": "daichi-yoshikawa/ahl_common", "max_issues_repo_head_hexsha": "7c720728d97f9b0bc2d85d4bc875b34b2372d094", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "wrapper/gl_wrapper/include/gl_wrapper/render/quaternion.hpp", "max_forks_repo_name": "daichi-yoshikawa/ahl_common", "max_forks_repo_head_hexsha": "7c720728d97f9b0bc2d85d4bc875b34b2372d094", "max_forks_repo_licenses": ["BSD-3-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.6632653061, "max_line_length": 72, "alphanum_fraction": 0.6680426557, "num_tokens": 641, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.4943898406897475}}
{"text": "/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\\n|  Phycas: Python software for phylogenetic analysis\t\t\t\t\t\t  |\n|  Copyright (C) 2006 Mark T. Holder, Paul O. Lewis and David L. Swofford\t  |\n|\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  |\n|  This program is free software; you can redistribute it and/or modify\t\t  |\n|  it under the terms of the GNU General Public License as published by\t\t  |\n|  the Free Software Foundation; either version 2 of the License, or\t\t  |\n|  (at your option) any later version.\t\t\t\t\t\t\t\t\t\t  |\n|\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  |\n|  This program is distributed in the hope that it will be useful,\t\t\t  |\n|  but WITHOUT ANY WARRANTY; without even the implied warranty of\t\t\t  |\n|  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\t See the\t\t\t  |\n|  GNU General Public License for more details.\t\t\t\t\t\t\t\t  |\n|\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  |\n|  You should have received a copy of the GNU General Public License along\t  |\n|  with this program; if not, write to the Free Software Foundation, Inc.,\t  |\n|  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\t\t\t\t  |\n\\~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n\n#if ! defined(SQUARE_MATRIX_HPP)\n#define SQUARE_MATRIX_HPP\n\n//#include <boost/enable_shared_from_this.hpp>\t\t// for boost::enable_shared_from_this\n#include <boost/shared_ptr.hpp>\n#include <vector>\n\nextern \"C\"\n{\n#include \"linalg.h\"\n}\n\nnamespace phycas\n{\n\nvoid fillTranspose(double ** p_mat_trans_scratch, const double * const *p_mat, unsigned dim);\n\nclass SquareMatrix\n\t{\n\tpublic:\n\t\t\t\t\t\t\t\t\t\tSquareMatrix();\n\t\t\t\t\t\t\t\t\t\tSquareMatrix(unsigned sz, double value);\n\t\t\t\t\t\t\t\t\t\tSquareMatrix(const SquareMatrix & other);\n\t\t\t\t\t\t\t\t\t\t~SquareMatrix();\n        void                            Clear();\n\t\tvoid\t\t\t\t\t\t\tCreateMatrix(unsigned sz, double value);\n\t\tvoid\t\t\t\t\t\t\tIdentity();\n\t\tvoid\t\t\t\t\t\t\tScalarMultiply(double scalar);\n\t\tvoid\t\t\t\t\t\t\tSubtract(const SquareMatrix & other);\n\t\tvoid\t\t\t\t\t\t\tSetToScalar(double scalar);\n\t\tunsigned\t\t\t\t\t\tGetDimension() const;\n\t\tdouble                          Trace() const;\n\t\tdouble * *\t\t\t\t\t\tGetMatrixAsRawPointer() const;\n\t\tdouble *\t\t\t\t\t\toperator[](unsigned i) const;\n\t\tvoid\t\t\t\t\t\t\tMatrixToString(std::string & s, std::string fmt) const;\n\t\tvoid\t\t\t\t\t\t\tFill(double value);\n        std::string                     GetStringRepresentation() const;\n        std::string                     GetFormattedStringRepresentation(std::string fmt) const;\n        double                          GetElement(unsigned i, unsigned j) const;\n        void                            SetElement(unsigned i, unsigned j, double v);\n        void                            AddToElement(unsigned i, unsigned j, double v);\n        std::vector<double>             GetMatrix() const;\n        void                            SetMatrix(unsigned sz, std::vector<double>);\n        double                          LogProdMainDiag() const;\n        double                          LogDeterminant() const;\n        SquareMatrix *                  Duplicate() const;\n        SquareMatrix *                  Power(double p) const;\n        SquareMatrix *                  LUDecomposition() const;\n        SquareMatrix *                  CholeskyDecomposition() const;\n        SquareMatrix *                  Inverse() const;\n        SquareMatrix *                  LeftMultiplyMatrix(SquareMatrix & matrixOnLeft) const;\n        SquareMatrix *                  RightMultiplyMatrix(SquareMatrix & matrixOnRight) const;\n        std::vector<double>             LeftMultiplyVector(const std::vector<double> & vectorOnLeft) const;\n        std::vector<double>             RightMultiplyVector(const std::vector<double> & vectorOnRight) const;\n\n\tprotected:\n\t\tstatic unsigned\t\t\t\t\tk;\t\t//temporary\n\t\tunsigned\t\t\t\t\t\tid;\t\t//temporary\n\t\tdouble * *\t\t\t\t\t\tm;\t\t/**< the two-dimensional matrix of doubles */\n\t\tunsigned\t\t\t\t\t\tdim;\t/**< the dimension of the matrix */\n        //mutable std::vector<double>     work;   /**< used as workspace whenever a reference to a vector needs to be returned */\n\t};\n\ntypedef boost::shared_ptr<SquareMatrix> SquareMatrixShPtr;\n\n\n}\t// namespace phycas\n#endif\n", "meta": {"hexsha": "c39525120d471e4b34f50771624779d27f601236", "size": 4097, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/cpp/square_matrix.hpp", "max_stars_repo_name": "plewis/phycas", "max_stars_repo_head_hexsha": "9f5a4d9b2342dab907d14a46eb91f92ad80a5605", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-09-24T23:12:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-12T07:07:01.000Z", "max_issues_repo_path": "src/cpp/square_matrix.hpp", "max_issues_repo_name": "plewis/phycas", "max_issues_repo_head_hexsha": "9f5a4d9b2342dab907d14a46eb91f92ad80a5605", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cpp/square_matrix.hpp", "max_forks_repo_name": "plewis/phycas", "max_forks_repo_head_hexsha": "9f5a4d9b2342dab907d14a46eb91f92ad80a5605", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-11-23T10:35:43.000Z", "max_forks_repo_forks_event_max_datetime": "2015-11-23T10:35:43.000Z", "avg_line_length": 46.5568181818, "max_line_length": 129, "alphanum_fraction": 0.5750549182, "num_tokens": 850, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.6548947223065754, "lm_q1q2_score": 0.4943898406897475}}
{"text": "#include <gtest/gtest.h>\n#include \"../util/util.h\"\n#include <Eigen/Core>\n\n#ifndef _MSC_VER\nextern \"C\" {\n#include <csim/memory_ops.h>\n#include <csim/stat_ops.h>\n}\n#else\n#include <csim/memory_ops.h>\n#include <csim/stat_ops.h>\n#endif\n\n\n\n// post-selection probability check\nTEST(StatOperationTest, ProbTest) {\n    const UINT n = 6;\n    const ITYPE dim = 1ULL << n;\n    const UINT max_repeat = 10;\n    const double eps = 1e-14;\n\n    CTYPE* state = allocate_quantum_state(dim);\n    Eigen::MatrixXcd P0(2, 2), P1(2, 2);\n    P0 << 1, 0, 0, 0;\n    P1 << 0, 0, 0, 1;\n\n    for (UINT rep = 0; rep < max_repeat; ++rep) {\n        initialize_Haar_random_state(state, dim);\n        ASSERT_NEAR(state_norm(state, dim), 1, eps);\n        Eigen::VectorXcd test_state(dim);\n        for (ITYPE i = 0; i < dim; ++i) test_state[i] = state[i];\n\n        for (UINT target = 0; target < n; ++target) {\n            double p0 = M0_prob(target, state, dim);\n            double p1 = M1_prob(target, state, dim);\n            ASSERT_NEAR((get_expanded_eigen_matrix_with_identity(target, P0, n)*test_state).squaredNorm(), p0, eps);\n            ASSERT_NEAR((get_expanded_eigen_matrix_with_identity(target, P1, n)*test_state).squaredNorm(), p1, eps);\n            ASSERT_NEAR(p0 + p1, 1, eps);\n        }\n    }\n    release_quantum_state(state);\n}\n\n// marginal probability check\nTEST(StatOperationTest, MarginalProbTest) {\n    const UINT n = 6;\n    const ITYPE dim = 1ULL << n;\n    const UINT max_repeat = 10;\n    const double eps = 1e-14;\n\n    CTYPE* state = allocate_quantum_state(dim);\n    Eigen::MatrixXcd P0(2, 2), P1(2, 2), Identity(2,2);\n    P0 << 1, 0, 0, 0;\n    P1 << 0, 0, 0, 1;\n    Identity << 1, 0, 0, 1;\n\n    for (UINT rep = 0; rep < max_repeat; ++rep) {\n        initialize_Haar_random_state(state, dim);\n        ASSERT_NEAR(state_norm(state, dim), 1, eps);\n        Eigen::VectorXcd test_state(dim);\n        for (ITYPE i = 0; i < dim; ++i) test_state[i] = state[i];\n\n        for (UINT target = 0; target < n; ++target) {\n            // merginal probability check\n            Eigen::MatrixXcd mat = Eigen::MatrixXcd::Identity(1, 1);\n            std::vector<UINT> index_list, measured_value_list;\n\n            index_list.clear();\n            measured_value_list.clear();\n            for (UINT i = 0; i < n; ++i) {\n                UINT measured_value = rand_int(3);\n                if (measured_value != 2) {\n                    measured_value_list.push_back(measured_value);\n                    index_list.push_back(i);\n                }\n                if (measured_value == 0) {\n                    mat = kronecker_product(P0, mat);\n                }\n                else if (measured_value == 1) {\n                    mat = kronecker_product(P1, mat);\n                }\n                else {\n                    mat = kronecker_product(Identity, mat);\n                }\n            }\n            double test_marginal_prob = (mat*test_state).squaredNorm();\n            double res = marginal_prob(index_list.data(), measured_value_list.data(), (UINT)index_list.size(), state, dim);\n            ASSERT_NEAR(test_marginal_prob, res, eps);\n        }\n    }\n    release_quantum_state(state);\n}\n\n\n// entropy\nTEST(StatOperationTest, EntropyTest) {\n    const UINT n = 6;\n    const ITYPE dim = 1ULL << n;\n    const UINT max_repeat = 10;\n    const double eps = 1e-14;\n\n    CTYPE* state = allocate_quantum_state(dim);\n    for (UINT rep = 0; rep < max_repeat; ++rep) {\n        initialize_Haar_random_state(state, dim);\n        ASSERT_NEAR(state_norm(state, dim), 1, eps);\n        Eigen::VectorXcd test_state(dim);\n        for (ITYPE i = 0; i < dim; ++i) test_state[i] = state[i];\n\n        for (UINT target = 0; target < n; ++target) {\n            double ent = 0;\n            for (ITYPE ind = 0; ind < dim; ++ind) {\n                double prob = norm(test_state[ind]);\n                if (prob > eps)\n                    ent += -prob * log(prob);\n            }\n            ASSERT_NEAR(ent, measurement_distribution_entropy(state, dim), eps);\n        }\n    }\n    release_quantum_state(state);\n}\n\n\n// inner product\nTEST(StatOperationTest, InnerProductTest) {\n    const UINT n = 6;\n    const ITYPE dim = 1ULL << n;\n    const UINT max_repeat = 10;\n    const double eps = 1e-14;\n\n    CTYPE* state = allocate_quantum_state(dim);\n    CTYPE* buffer = allocate_quantum_state(dim);\n    for (UINT rep = 0; rep < max_repeat; ++rep) {\n\n        initialize_Haar_random_state(state, dim);\n        ASSERT_NEAR(state_norm(state, dim), 1, eps);\n        Eigen::VectorXcd test_state(dim);\n        for (ITYPE i = 0; i < dim; ++i) test_state[i] = state[i];\n\n        for (UINT target = 0; target < n; ++target) {\n            initialize_Haar_random_state(buffer, dim);\n            CTYPE inp = state_inner_product(buffer, state, dim);\n            Eigen::VectorXcd test_buffer(dim);\n            for (ITYPE i = 0; i < dim; ++i) test_buffer[i] = buffer[i];\n            std::complex<double> test_inp = (test_buffer.adjoint() * test_state);\n            ASSERT_NEAR(creal(inp), test_inp.real(), eps);\n            ASSERT_NEAR(cimag(inp), test_inp.imag(), eps);\n        }\n    }\n    release_quantum_state(state);\n    release_quantum_state(buffer);\n}\n\n// single qubit expectation value\nTEST(StatOperationTest, SingleQubitExpectationValueTest) {\n    const UINT n = 6;\n    const ITYPE dim = 1ULL << n;\n    const UINT max_repeat = 10;\n    const double eps = 1e-14;\n\n    CTYPE* state = allocate_quantum_state(dim);\n    Eigen::MatrixXcd Identity(2, 2), X(2, 2), Y(2, 2), Z(2, 2);\n    Eigen::MatrixXcd pauli_op;\n    Identity << 1, 0, 0, 1;\n    X << 0, 1, 1, 0;\n    Z << 1, 0, 0, -1;\n    Y << 0, -1.i, 1.i, 0;\n\n    for (UINT rep = 0; rep < max_repeat; ++rep) {\n        initialize_Haar_random_state(state, dim);\n        ASSERT_NEAR(state_norm(state, dim), 1, eps);\n        Eigen::VectorXcd test_state(dim);\n        for (ITYPE i = 0; i < dim; ++i) test_state[i] = state[i];\n\n        for (UINT target = 0; target < n; ++target) {\n            // single qubit expectation value check\n            target = rand_int(n);\n            UINT pauli = rand_int(3) + 1;\n            if (pauli == 0) pauli_op = Identity;\n            else if (pauli == 1) pauli_op = X;\n            else if (pauli == 2) pauli_op = Y;\n            else if (pauli == 3) pauli_op = Z;\n            std::complex<double> value = (test_state.adjoint()*get_expanded_eigen_matrix_with_identity(target, pauli_op, n)*test_state);\n            ASSERT_NEAR(value.imag(), 0, eps);\n            double test_expectation = value.real();\n            double expectation = expectation_value_single_qubit_Pauli_operator(target, pauli, state, dim);\n            ASSERT_NEAR(expectation, test_expectation, eps);\n        }\n    }\n    release_quantum_state(state);\n}\n\n\n// multi qubit expectation value whole\nTEST(StatOperationTest, MultiQubitExpectationValueWholeTest) {\n    const UINT n = 6;\n    const ITYPE dim = 1ULL << n;\n    const UINT max_repeat = 10;\n    const double eps = 1e-14;\n\n    CTYPE* state = allocate_quantum_state(dim);\n    Eigen::MatrixXcd Identity(2, 2), X(2, 2), Y(2, 2), Z(2, 2);\n    Eigen::MatrixXcd pauli_op;\n    Identity << 1, 0, 0, 1;\n    X << 0, 1, 1, 0;\n    Z << 1, 0, 0, -1;\n    Y << 0, -1.i, 1.i, 0;\n\n    for (UINT rep = 0; rep < max_repeat; ++rep) {\n        initialize_Haar_random_state(state, dim);\n        ASSERT_NEAR(state_norm(state, dim), 1, eps);\n        Eigen::VectorXcd test_state(dim);\n        for (ITYPE i = 0; i < dim; ++i) test_state[i] = state[i];\n\n        for (UINT target = 0; target < n; ++target) {\n            // multi qubit expectation whole list value check\n            Eigen::MatrixXcd mat = Eigen::MatrixXcd::Identity(1, 1);\n            std::vector<UINT> pauli_whole;\n            for (UINT i = 0; i < n; ++i) {\n                UINT pauli = rand_int(4);\n                if (pauli == 0) pauli_op = Identity;\n                else if (pauli == 1) pauli_op = X;\n                else if (pauli == 2) pauli_op = Y;\n                else if (pauli == 3) pauli_op = Z;\n                mat = kronecker_product(pauli_op, mat);\n                pauli_whole.push_back(pauli);\n            }\n            std::complex<double> value = (test_state.adjoint()*mat*test_state);\n            ASSERT_NEAR(value.imag(), 0, eps);\n            double test_expectation = value.real();\n            double expectation = expectation_value_multi_qubit_Pauli_operator_whole_list(pauli_whole.data(), n, state, dim);\n            ASSERT_NEAR(expectation, test_expectation, eps);\n        }\n    }\n    release_quantum_state(state);\n}\n\n\n\n// multi qubit expectation value whole\nTEST(StatOperationTest, MultiQubitExpectationValueZopWholeTest) {\n\tconst UINT n = 6;\n\tconst ITYPE dim = 1ULL << n;\n\tconst UINT max_repeat = 10;\n\tconst double eps = 1e-14;\n\n\tCTYPE* state = allocate_quantum_state(dim);\n\tEigen::MatrixXcd Identity(2, 2), X(2, 2), Y(2, 2), Z(2, 2);\n\tEigen::MatrixXcd pauli_op;\n\tIdentity << 1, 0, 0, 1;\n\tX << 0, 1, 1, 0;\n\tZ << 1, 0, 0, -1;\n\tY << 0, -1.i, 1.i, 0;\n\n\tfor (UINT rep = 0; rep < max_repeat; ++rep) {\n\t\tinitialize_Haar_random_state(state, dim);\n\t\tASSERT_NEAR(state_norm(state, dim), 1, eps);\n\t\tEigen::VectorXcd test_state(dim);\n\t\tfor (ITYPE i = 0; i < dim; ++i) test_state[i] = state[i];\n\n\t\tfor (UINT target = 0; target < n; ++target) {\n\t\t\t// multi qubit expectation whole list value check\n\t\t\tEigen::MatrixXcd mat = Eigen::MatrixXcd::Identity(1, 1);\n\t\t\tstd::vector<UINT> pauli_whole;\n\t\t\tfor (UINT i = 0; i < n; ++i) {\n\t\t\t\tUINT pauli = rand_int(2);\n\t\t\t\tif (pauli == 1) pauli = 3;\n\t\t\t\tif (pauli == 0) pauli_op = Identity;\n\t\t\t\telse pauli_op = Z;\n\t\t\t\tmat = kronecker_product(pauli_op, mat);\n\t\t\t\tpauli_whole.push_back(pauli);\n\t\t\t}\n\t\t\tstd::complex<double> value = (test_state.adjoint()*mat*test_state);\n\t\t\tASSERT_NEAR(value.imag(), 0, eps);\n\t\t\tdouble test_expectation = value.real();\n\t\t\tdouble expectation = expectation_value_multi_qubit_Pauli_operator_whole_list(pauli_whole.data(), n, state, dim);\n\t\t\tASSERT_NEAR(expectation, test_expectation, eps);\n\t\t}\n\t}\n\trelease_quantum_state(state);\n}\n\n// multi qubit expectation value whole\nTEST(StatOperationTest, MultiQubitExpectationValuePartialTest) {\n    const UINT n = 6;\n    const ITYPE dim = 1ULL << n;\n    const double eps = 1e-14;\n    const UINT max_repeat = 10;\n\n    CTYPE* state = allocate_quantum_state(dim);\n    for (UINT rep = 0; rep < max_repeat; ++rep) {\n        initialize_Haar_random_state(state, dim);\n        ASSERT_NEAR(state_norm(state, dim), 1, eps);\n        Eigen::VectorXcd test_state(dim);\n        for (ITYPE i = 0; i < dim; ++i) test_state[i] = state[i];\n\n        Eigen::MatrixXcd Identity(2,2), X(2,2), Y(2,2), Z(2,2);\n        Identity << 1, 0, 0, 1;\n        X << 0, 1, 1, 0;\n        Z << 1, 0, 0, -1;\n        Y << 0, -1.i, 1.i, 0;\n\n        for (UINT target = 0; target < n; ++target) {\n            // multi qubit expectation partial list value check\n            Eigen::MatrixXcd mat = Eigen::MatrixXcd::Identity(1, 1);\n            Eigen::MatrixXcd pauli_op;\n\n            std::vector<UINT> pauli_partial, pauli_index;\n            std::vector<std::pair<UINT, UINT>> pauli_partial_pair;\n            for (UINT i = 0; i < n; ++i) {\n                UINT pauli = rand_int(4);\n                if (pauli == 0) pauli_op = Identity;\n                else if (pauli == 1) pauli_op = X;\n                else if (pauli == 2) pauli_op = Y;\n                else if (pauli == 3) pauli_op = Z;\n                mat = kronecker_product(pauli_op, mat);\n                if (pauli != 0) {\n                    pauli_partial_pair.push_back(std::make_pair(i, pauli));\n                }\n            }\n            std::random_shuffle(pauli_partial_pair.begin(), pauli_partial_pair.end());\n            for (auto val : pauli_partial_pair) {\n                pauli_index.push_back(val.first);\n                pauli_partial.push_back(val.second);\n            }\n            std::complex<double> value = (test_state.adjoint()*mat*test_state);\n            ASSERT_NEAR(value.imag(), 0, eps);\n            double test_expectation = value.real();\n            double expectation = expectation_value_multi_qubit_Pauli_operator_partial_list(pauli_index.data(), pauli_partial.data(), (UINT)pauli_index.size(), state,dim);\n            ASSERT_NEAR(expectation, test_expectation, eps);\n        }\n    }\n    release_quantum_state(state);\n}\n\n// multi qubit expectation value whole\nTEST(StatOperationTest, MultiQubitExpectationValueZopPartialTest) {\n\tconst UINT n = 6;\n\tconst ITYPE dim = 1ULL << n;\n\tconst double eps = 1e-14;\n\tconst UINT max_repeat = 10;\n\n\tCTYPE* state = allocate_quantum_state(dim);\n\tfor (UINT rep = 0; rep < max_repeat; ++rep) {\n\t\tinitialize_Haar_random_state(state, dim);\n\t\tASSERT_NEAR(state_norm(state, dim), 1, eps);\n\t\tEigen::VectorXcd test_state(dim);\n\t\tfor (ITYPE i = 0; i < dim; ++i) test_state[i] = state[i];\n\n\t\tEigen::MatrixXcd Identity(2, 2), X(2, 2), Y(2, 2), Z(2, 2);\n\t\tIdentity << 1, 0, 0, 1;\n\t\tX << 0, 1, 1, 0;\n\t\tZ << 1, 0, 0, -1;\n\t\tY << 0, -1.i, 1.i, 0;\n\n\t\tfor (UINT target = 0; target < n; ++target) {\n\t\t\t// multi qubit expectation partial list value check\n\t\t\tEigen::MatrixXcd mat = Eigen::MatrixXcd::Identity(1, 1);\n\t\t\tEigen::MatrixXcd pauli_op;\n\n\t\t\tstd::vector<UINT> pauli_partial, pauli_index;\n\t\t\tstd::vector<std::pair<UINT, UINT>> pauli_partial_pair;\n\t\t\tfor (UINT i = 0; i < n; ++i) {\n\t\t\t\tUINT pauli = rand_int(2);\n\t\t\t\tif (pauli == 1) pauli = 3;\n\t\t\t\tif (pauli == 0) pauli_op = Identity;\n\t\t\t\telse pauli_op = Z;\n\t\t\t\tmat = kronecker_product(pauli_op, mat);\n\t\t\t\tif (pauli != 0) {\n\t\t\t\t\tpauli_partial_pair.push_back(std::make_pair(i, pauli));\n\t\t\t\t}\n\t\t\t}\n\t\t\tstd::random_shuffle(pauli_partial_pair.begin(), pauli_partial_pair.end());\n\t\t\tfor (auto val : pauli_partial_pair) {\n\t\t\t\tpauli_index.push_back(val.first);\n\t\t\t\tpauli_partial.push_back(val.second);\n\t\t\t}\n\t\t\tstd::complex<double> value = (test_state.adjoint()*mat*test_state);\n\t\t\tASSERT_NEAR(value.imag(), 0, eps);\n\t\t\tdouble test_expectation = value.real();\n\t\t\tdouble expectation = expectation_value_multi_qubit_Pauli_operator_partial_list(pauli_index.data(), pauli_partial.data(), (UINT)pauli_index.size(), state, dim);\n\t\t\tASSERT_NEAR(expectation, test_expectation, eps);\n\t\t}\n\t}\n\trelease_quantum_state(state);\n}\n\n\n\n\n\n// multi qubit expectation value whole\nTEST(StatOperationTest, MultiQubitTransitionAmplitudeWholeTest) {\n\tconst UINT n = 6;\n\tconst ITYPE dim = 1ULL << n;\n\tconst UINT max_repeat = 10;\n\tconst double eps = 1e-14;\n\n\tCTYPE* state_ket = allocate_quantum_state(dim);\n\tCTYPE* state_bra = allocate_quantum_state(dim);\n\tEigen::MatrixXcd Identity(2, 2), X(2, 2), Y(2, 2), Z(2, 2);\n\tEigen::MatrixXcd pauli_op;\n\tIdentity << 1, 0, 0, 1;\n\tX << 0, 1, 1, 0;\n\tZ << 1, 0, 0, -1;\n\tY << 0, -1.i, 1.i, 0;\n\n\tfor (UINT rep = 0; rep < max_repeat; ++rep) {\n\t\tinitialize_Haar_random_state(state_ket, dim);\n\t\tinitialize_Haar_random_state(state_bra, dim);\n\t\tASSERT_NEAR(state_norm(state_ket, dim), 1, eps);\n\t\tASSERT_NEAR(state_norm(state_bra, dim), 1, eps);\n\n\t\tEigen::VectorXcd test_state_ket(dim);\n\t\tEigen::VectorXcd test_state_bra(dim);\n\t\tfor (ITYPE i = 0; i < dim; ++i) test_state_ket[i] = state_ket[i];\n\t\tfor (ITYPE i = 0; i < dim; ++i) test_state_bra[i] = state_bra[i];\n\n\t\tfor (UINT target = 0; target < n; ++target) {\n\t\t\t// multi qubit expectation whole list value check\n\t\t\tEigen::MatrixXcd mat = Eigen::MatrixXcd::Identity(1, 1);\n\t\t\tstd::vector<UINT> pauli_whole;\n\t\t\tfor (UINT i = 0; i < n; ++i) {\n\t\t\t\tUINT pauli = rand_int(4);\n\t\t\t\tif (pauli == 0) pauli_op = Identity;\n\t\t\t\telse if (pauli == 1) pauli_op = X;\n\t\t\t\telse if (pauli == 2) pauli_op = Y;\n\t\t\t\telse if (pauli == 3) pauli_op = Z;\n\t\t\t\tmat = kronecker_product(pauli_op, mat);\n\t\t\t\tpauli_whole.push_back(pauli);\n\t\t\t}\n\t\t\tstd::complex<double> test_transition_amplitude = (test_state_bra.adjoint()*mat*test_state_ket);\n\t\t\tCTYPE transition_amplitude = transition_amplitude_multi_qubit_Pauli_operator_whole_list(pauli_whole.data(), n, state_bra, state_ket, dim);\n\t\t\tASSERT_NEAR(creal(transition_amplitude), test_transition_amplitude.real(), eps);\n\t\t\tASSERT_NEAR(cimag(transition_amplitude), test_transition_amplitude.imag(), eps);\n\t\t}\n\t}\n\trelease_quantum_state(state_ket);\n\trelease_quantum_state(state_bra);\n}\n\n// multi qubit expectation value whole\nTEST(StatOperationTest, MultiQubitTransitionAmplitudeZopWholeTest) {\n\tconst UINT n = 6;\n\tconst ITYPE dim = 1ULL << n;\n\tconst UINT max_repeat = 10;\n\tconst double eps = 1e-14;\n\n\tCTYPE* state_ket = allocate_quantum_state(dim);\n\tCTYPE* state_bra = allocate_quantum_state(dim);\n\tEigen::MatrixXcd Identity(2, 2), X(2, 2), Y(2, 2), Z(2, 2);\n\tEigen::MatrixXcd pauli_op;\n\tIdentity << 1, 0, 0, 1;\n\tX << 0, 1, 1, 0;\n\tZ << 1, 0, 0, -1;\n\tY << 0, -1.i, 1.i, 0;\n\n\tfor (UINT rep = 0; rep < max_repeat; ++rep) {\n\t\tinitialize_Haar_random_state(state_ket, dim);\n\t\tinitialize_Haar_random_state(state_bra, dim);\n\t\tASSERT_NEAR(state_norm(state_ket, dim), 1, eps);\n\t\tASSERT_NEAR(state_norm(state_bra, dim), 1, eps);\n\n\t\tEigen::VectorXcd test_state_ket(dim);\n\t\tEigen::VectorXcd test_state_bra(dim);\n\t\tfor (ITYPE i = 0; i < dim; ++i) test_state_ket[i] = state_ket[i];\n\t\tfor (ITYPE i = 0; i < dim; ++i) test_state_bra[i] = state_bra[i];\n\n\t\tfor (UINT target = 0; target < n; ++target) {\n\t\t\t// multi qubit expectation whole list value check\n\t\t\tEigen::MatrixXcd mat = Eigen::MatrixXcd::Identity(1, 1);\n\t\t\tstd::vector<UINT> pauli_whole;\n\t\t\tfor (UINT i = 0; i < n; ++i) {\n\t\t\t\tUINT pauli = rand_int(2);\n\t\t\t\tif (pauli == 1) pauli = 3;\n\t\t\t\tif (pauli == 0) pauli_op = Identity;\n\t\t\t\telse pauli_op = Z;\n\t\t\t\tmat = kronecker_product(pauli_op, mat);\n\t\t\t\tpauli_whole.push_back(pauli);\n\t\t\t}\n\t\t\tstd::complex<double> test_transition_amplitude = (test_state_bra.adjoint()*mat*test_state_ket);\n\t\t\tCTYPE transition_amplitude = transition_amplitude_multi_qubit_Pauli_operator_whole_list(pauli_whole.data(), n, state_bra, state_ket, dim);\n\t\t\tASSERT_NEAR(creal(transition_amplitude), test_transition_amplitude.real(), eps);\n\t\t\tASSERT_NEAR(cimag(transition_amplitude), test_transition_amplitude.imag(), eps);\n\t\t}\n\t}\n\trelease_quantum_state(state_ket);\n\trelease_quantum_state(state_bra);\n}\n\n// multi qubit expectation value whole\nTEST(StatOperationTest, MultiQubitTransitionAmplitudePartialTest) {\n\tconst UINT n = 6;\n\tconst ITYPE dim = 1ULL << n;\n\tconst UINT max_repeat = 10;\n\tconst double eps = 1e-14;\n\n\tCTYPE* state_ket = allocate_quantum_state(dim);\n\tCTYPE* state_bra = allocate_quantum_state(dim);\n\tEigen::MatrixXcd Identity(2, 2), X(2, 2), Y(2, 2), Z(2, 2);\n\tEigen::MatrixXcd pauli_op;\n\tIdentity << 1, 0, 0, 1;\n\tX << 0, 1, 1, 0;\n\tZ << 1, 0, 0, -1;\n\tY << 0, -1.i, 1.i, 0;\n\n\tfor (UINT rep = 0; rep < max_repeat; ++rep) {\n\t\tinitialize_Haar_random_state(state_ket, dim);\n\t\tinitialize_Haar_random_state(state_bra, dim);\n\t\tASSERT_NEAR(state_norm(state_ket, dim), 1, eps);\n\t\tASSERT_NEAR(state_norm(state_bra, dim), 1, eps);\n\n\t\tEigen::VectorXcd test_state_ket(dim);\n\t\tEigen::VectorXcd test_state_bra(dim);\n\t\tfor (ITYPE i = 0; i < dim; ++i) test_state_ket[i] = state_ket[i];\n\t\tfor (ITYPE i = 0; i < dim; ++i) test_state_bra[i] = state_bra[i];\n\n\t\tfor (UINT target = 0; target < n; ++target) {\n\t\t\t// multi qubit expectation partial list value check\n\t\t\tEigen::MatrixXcd mat = Eigen::MatrixXcd::Identity(1, 1);\n\t\t\tEigen::MatrixXcd pauli_op;\n\n\t\t\tstd::vector<UINT> pauli_partial, pauli_index;\n\t\t\tstd::vector<std::pair<UINT, UINT>> pauli_partial_pair;\n\t\t\tfor (UINT i = 0; i < n; ++i) {\n\t\t\t\tUINT pauli = rand_int(4);\n\t\t\t\tif (pauli == 0) pauli_op = Identity;\n\t\t\t\telse if (pauli == 1) pauli_op = X;\n\t\t\t\telse if (pauli == 2) pauli_op = Y;\n\t\t\t\telse if (pauli == 3) pauli_op = Z;\n\t\t\t\tmat = kronecker_product(pauli_op, mat);\n\t\t\t\tif (pauli != 0) {\n\t\t\t\t\tpauli_partial_pair.push_back(std::make_pair(i, pauli));\n\t\t\t\t}\n\t\t\t}\n\t\t\tstd::random_shuffle(pauli_partial_pair.begin(), pauli_partial_pair.end());\n\t\t\tfor (auto val : pauli_partial_pair) {\n\t\t\t\tpauli_index.push_back(val.first);\n\t\t\t\tpauli_partial.push_back(val.second);\n\t\t\t}\n\t\t\tstd::complex<double> test_transition_amplitude = (test_state_bra.adjoint()*mat*test_state_ket);\n\t\t\tCTYPE transition_amplitude = transition_amplitude_multi_qubit_Pauli_operator_partial_list(pauli_index.data(), pauli_partial.data(), (UINT)pauli_index.size(), state_bra, state_ket, dim);\n\t\t\tASSERT_NEAR(creal(transition_amplitude), test_transition_amplitude.real(), eps);\n\t\t\tASSERT_NEAR(cimag(transition_amplitude), test_transition_amplitude.imag(), eps);\n\t\t}\n\t}\n\trelease_quantum_state(state_ket);\n\trelease_quantum_state(state_bra);\n}\n\n\n\n// multi qubit expectation value whole\nTEST(StatOperationTest, MultiQubitTransitionAmplitudeZopPartialTest) {\n\tconst UINT n = 6;\n\tconst ITYPE dim = 1ULL << n;\n\tconst UINT max_repeat = 10;\n\tconst double eps = 1e-14;\n\n\tCTYPE* state_ket = allocate_quantum_state(dim);\n\tCTYPE* state_bra = allocate_quantum_state(dim);\n\tEigen::MatrixXcd Identity(2, 2), X(2, 2), Y(2, 2), Z(2, 2);\n\tEigen::MatrixXcd pauli_op;\n\tIdentity << 1, 0, 0, 1;\n\tX << 0, 1, 1, 0;\n\tZ << 1, 0, 0, -1;\n\tY << 0, -1.i, 1.i, 0;\n\n\tfor (UINT rep = 0; rep < max_repeat; ++rep) {\n\t\tinitialize_Haar_random_state(state_ket, dim);\n\t\tinitialize_Haar_random_state(state_bra, dim);\n\t\tASSERT_NEAR(state_norm(state_ket, dim), 1, eps);\n\t\tASSERT_NEAR(state_norm(state_bra, dim), 1, eps);\n\n\t\tEigen::VectorXcd test_state_ket(dim);\n\t\tEigen::VectorXcd test_state_bra(dim);\n\t\tfor (ITYPE i = 0; i < dim; ++i) test_state_ket[i] = state_ket[i];\n\t\tfor (ITYPE i = 0; i < dim; ++i) test_state_bra[i] = state_bra[i];\n\n\t\tfor (UINT target = 0; target < n; ++target) {\n\t\t\t// multi qubit expectation partial list value check\n\t\t\tEigen::MatrixXcd mat = Eigen::MatrixXcd::Identity(1, 1);\n\t\t\tEigen::MatrixXcd pauli_op;\n\n\t\t\tstd::vector<UINT> pauli_partial, pauli_index;\n\t\t\tstd::vector<std::pair<UINT, UINT>> pauli_partial_pair;\n\t\t\tfor (UINT i = 0; i < n; ++i) {\n\t\t\t\tUINT pauli = rand_int(2);\n\t\t\t\tif (pauli == 1) pauli = 3;\n\t\t\t\tif (pauli == 0) pauli_op = Identity;\n\t\t\t\telse pauli_op = Z;\n\t\t\t\tmat = kronecker_product(pauli_op, mat);\n\t\t\t\tif (pauli != 0) {\n\t\t\t\t\tpauli_partial_pair.push_back(std::make_pair(i, pauli));\n\t\t\t\t}\n\t\t\t}\n\t\t\tstd::random_shuffle(pauli_partial_pair.begin(), pauli_partial_pair.end());\n\t\t\tfor (auto val : pauli_partial_pair) {\n\t\t\t\tpauli_index.push_back(val.first);\n\t\t\t\tpauli_partial.push_back(val.second);\n\t\t\t}\n\t\t\tstd::complex<double> test_transition_amplitude = (test_state_bra.adjoint()*mat*test_state_ket);\n\t\t\tCTYPE transition_amplitude = transition_amplitude_multi_qubit_Pauli_operator_partial_list(pauli_index.data(), pauli_partial.data(), (UINT)pauli_index.size(), state_bra, state_ket, dim);\n\t\t\tASSERT_NEAR(creal(transition_amplitude), test_transition_amplitude.real(), eps);\n\t\t\tASSERT_NEAR(cimag(transition_amplitude), test_transition_amplitude.imag(), eps);\n\t\t}\n\t}\n\trelease_quantum_state(state_ket);\n\trelease_quantum_state(state_bra);\n}\n", "meta": {"hexsha": "ba1428f768d85e16b836d72677a72b1062c29ed0", "size": 22540, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/csim/test_stat.cpp", "max_stars_repo_name": "yoooopeeee/qulacs", "max_stars_repo_head_hexsha": "25276cbfc448572ab57e30df84afddc24132b53d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2022-03-06T18:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T08:58:22.000Z", "max_issues_repo_path": "test/csim/test_stat.cpp", "max_issues_repo_name": "yoooopeeee/qulacs", "max_issues_repo_head_hexsha": "25276cbfc448572ab57e30df84afddc24132b53d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-12-13T12:40:25.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-13T17:47:06.000Z", "max_forks_repo_path": "test/csim/test_stat.cpp", "max_forks_repo_name": "yoooopeeee/qulacs", "max_forks_repo_head_hexsha": "25276cbfc448572ab57e30df84afddc24132b53d", "max_forks_repo_licenses": ["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.8300653595, "max_line_length": 188, "alphanum_fraction": 0.6325643301, "num_tokens": 6968, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.4943898385523683}}
{"text": "\n//==================================================\n// cubicBezier\n//==================================================\n#define BOOST_PYTHON_STATIC_LIB\n#define BOOST_NUMPY_STATIC_LIB\n#include <Python.h>\n#include <valarray>\n#include <iostream>\n#include <boost/python.hpp>\n#include <boost/shared_ptr.hpp>\n\n/*\n \u25c6\u958b\u767a\u74b0\u5883\n [OS]: macOS 10.14~\n [c++] gcc version 9.2.0\n [boost] 1.71.0\n [Python] v2.7.16\n */\n\ntypedef std::valarray<double> darray;\ntypedef std::valarray<darray> d2array;\nnamespace py = boost::python;\nnamespace cubicBezier\n{\n    darray cubicBezier(darray p0, darray p1, darray p2, darray p3, double u, bool restraint=true)\n    {\n        darray _p0 (2);\n        darray _p1 (2);\n        darray _p2 (2);\n        darray _p3 (2);\n        _p0 = p0; //# start-point\n        _p1 = p1; //# start-point weighted\n        _p2 = p2; //# end-point weighted\n        _p3 = p3; //# end-point\n\n        \n        if(restraint)\n        { // p0, p1, p2, p3\u306ex\u5024\u304c\u4e92\u3044\u9055\u3044\u306b\u306a\u3063\u3066\u3044\u308b\u5834\u5408\u306e\u70ba\u306e\u51e6\u7406\u3002\n            // p0[0]==3, p1[0]==1\u306e\u69d8\u306bp0\u304cp1\u3088\u308a\u5148\u306ex\u5730\u70b9\u306b\u3042\u308b\u5834\u5408\u3002\n            double scale;\n            double btKey;\n            double vx_A;\n            double vx_B;\n            btKey = _p3[0] - _p0[0];\n            vx_A = _p1[0] - _p0[0];\n            vx_B = _p3[0] - _p2[0];\n            scale = btKey/(vx_A + vx_B);\n            if(scale<1)\n            {\n                darray vec_A (2);\n                darray vec_B (2);\n                vec_A = _p1 - p0;\n                vec_B = _p2 - p3;\n                //vecB*scale;\n                \n                _p1 = vec_A*scale; //vec_A apply ([=](double v) (return v*sclae;))\n                _p2 = vec_B*scale; //vec_B apply ([=](double v) (return v;))\n                \n                _p1 = _p1+_p0;\n                _p2 = _p2+_p3;\n            }\n        }\n        darray _p4 (2);\n        darray _p5 (2);\n        darray _p6 (2);\n        darray _p7 (2);\n        darray _p8 (2);\n        darray _p9 (2);\n        \n        // \u8a08\u7b97\n        _p4 = (_p1 - _p0)*u +_p0; //\n        _p5 = (_p2 - _p1)*u +_p1; //\n        _p6 = (_p3 - _p2)*u +_p2; //\n        _p7 = (_p5 - _p4)*u +_p4; //\n        _p8 = (_p6 - _p5)*u +_p5; //\n        _p9 = (_p8 - _p7)*u +_p7; //\n        return _p9;\n    }\n\n    d2array sampling_cubicBezier_t(d2array points, int count=100)\n    {\n    /*\n     cubicBezier\u306e\u30dd\u30a4\u30f3\u30c8\uff14\u70b9\u3092\u7528\u3044\u3066\uff14\u70b9\u9593\u306ecubicBezier\u306e\u96e2\u6563\u5316\u3057\u305f\u30ab\u30fc\u30d6(point\u7fa4)\u3092\u751f\u6210\u3059\u308b\u3002\n     */\n    double u;\n    darray p;\n    d2array rList(count);\n    for(int t=0; t <count; t++)\n        {\n            u = double(t) / double(count-1);\n            p = cubicBezier::cubicBezier(points[0], points[1], points[2], points[3], u);\n            rList[t] = p;\n        }\n    return rList;\n    }\n\n}\n\n\n//==================================================\n// convert\n//==================================================\nd2array convert_list_to_d2array(py::list array)\n{\n    // array is expected as a d2array (referenced-code)\n    int count = py::len(array);\n    d2array rArray(count);\n    py::list val;\n    \n    for(int i=0; i<count; i++)\n        {\n            val = py::extract<py::list>(array[i]);\n            int mCount = py::len(val);\n            rArray[i] = darray(mCount);\n            for(int m=0; m<mCount; m++)\n                {\n                rArray[i][m] = py::extract<double>(val[m]);\n                }\n            \n        }\n    return rArray;\n}\n\npy::list convert_array_to_list(d2array array)\n{\n    // array is expected as a d2array //(referencerd-code)\n    int count = array.size();\n    py::list rArray;\n    for(int i=0; i<count; i++)\n        {\n            py::list temp;\n            int mCount = array[i].size();\n            for(int m=0; m<mCount; m++)\n                {\n                temp.append(array[i][m]);\n                }\n            rArray.append(temp);\n        }\n    return  rArray;\n}\n\n//==================================================\n// python command\n//==================================================\npy::list py_sampling_cubicBezier(py::list points, int count=100)\n{\n           d2array _points(count);\n           _points = convert_list_to_d2array(points);\n           d2array tmpArray;\n\n           tmpArray = cubicBezier::sampling_cubicBezier_t(_points, count);\n           return convert_array_to_list(tmpArray);\n}\n\npy::list py_cubicBezier(py::list p0, py::list p1, py::list p2, py::list p3, double u, bool restraint=true )\n{\n    darray _p0(2);\n    darray _p1(2);\n    darray _p2(2);\n    darray _p3(2);\n    _p0[0] = py::extract<double>(p0[0]);\n    _p0[1] = py::extract<double>(p0[1]); //# start-point\n    _p1[0] = py::extract<double>(p1[0]);\n    _p1[1] = py::extract<double>(p1[1]); //# start-point(weighted)\n    _p2[0] = py::extract<double>(p2[0]);\n    _p2[1] = py::extract<double>(p2[1]); //# end-point(weigted)\n    _p3[0] = py::extract<double>(p3[0]);\n    _p3[1] = py::extract<double>(p3[1]); //# end-point\n\n    darray points = cubicBezier::cubicBezier(_p0, _p1, _p2, _p3, u, restraint);\n    py::list rValue;\n    for(auto& v:points)\n       {\n        rValue.append(v);\n       }\n    return rValue;\n}\n\nBOOST_PYTHON_MODULE(lib)\n{\n           def(\"cubicBezier\", &py_cubicBezier);\n           def(\"sampling_cubicBezier\", &py_sampling_cubicBezier);\n}\n", "meta": {"hexsha": "504e162ee4d683aacafa001ea47284ee72e12373", "size": 5094, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cubicBezier/src/cubicbezier.cpp", "max_stars_repo_name": "hiroshi-nagai/cubicBezier", "max_stars_repo_head_hexsha": "4306302a795a875df4405929a0d2cdb57f9ad67e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cubicBezier/src/cubicbezier.cpp", "max_issues_repo_name": "hiroshi-nagai/cubicBezier", "max_issues_repo_head_hexsha": "4306302a795a875df4405929a0d2cdb57f9ad67e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cubicBezier/src/cubicbezier.cpp", "max_forks_repo_name": "hiroshi-nagai/cubicBezier", "max_forks_repo_head_hexsha": "4306302a795a875df4405929a0d2cdb57f9ad67e", "max_forks_repo_licenses": ["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.5351351351, "max_line_length": 107, "alphanum_fraction": 0.4823321555, "num_tokens": 1585, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.49438983346759924}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// importance_sampling::apply_exp_offset                                     //\n//                                                                           //\n//  Copyright 2009 Erwann Rogard. Distributed under the Boost                //\n//  Software License, Version 1.0. (See accompanying file                    //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)         //\n///////////////////////////////////////////////////////////////////////////////\n#ifndef BOOST_STATISTICS_DETAIL_IMPORTANCE_SAMPLING_WEIGHTS_APPLY_EXP_OFFSET_HPP_ER_2009\n#define BOOST_STATISTICS_DETAIL_IMPORTANCE_SAMPLING_WEIGHTS_APPLY_EXP_OFFSET_HPP_ER_2009\n#include <cmath>\n#include <algorithm>\n#include <boost/lambda/lambda.hpp>\n#include <boost/lambda/bind.hpp>\n#include <boost/math/tools/precision.hpp>\n\nnamespace boost{\nnamespace statistics{\nnamespace detail{\nnamespace importance_sampling{\n    \n    // Returns          The smallest value, c, s/t *i + c <= t, i in [b_w,e_w)\n    // Side effect:     *i <- exp(*i+c)\n    //\n    // The greater c, the higher the precision but also risk of isinf.\n    // Textbook often show t = 0 so that exp(w+c) <= 1. \n    template<typename It>\n    typename iterator_value<It>::type\n    apply_exp_offset(\n        It b,\n        It e,\n        typename iterator_value<It>::type t\n    ){\n        typedef typename iterator_value<It>::type val_;\n        val_ max = *std::max_element(b,e);\n        val_ offset = (t - max); \n        typedef val_(*fp_)(val_);\n        fp_ fp = std::exp;\n        std::transform(\n        \tb,\n            e,\n            b,\n            lambda::bind<val_>(fp,lambda::_1 + offset)\n        );\n        return offset;\n    }\n\n    // Same as above, but t set such that exp(t+epsilon) = inf, exp(t)<inf \n    template<typename It>\n    typename iterator_value<It>::type\n    apply_exp_offset(\n        It b,\n        It e\n    ){\n        typedef typename iterator_value<It>::type val_;\n        const val_ log_max = boost::math::tools::log_max_value<val_>();\n\n        return apply_exp_offset(\n            b,\n            e,\n            log_max\n        );\n    }\n\n}// importance_weights\n}// detail\n}// statistics\n}// boost\n\n#endif", "meta": {"hexsha": "49ece84903b5d0d5370d60ba4a2f0308b4624f66", "size": 2247, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "importance_sampling/boost/statistics/detail/importance_sampling/weights/apply_exp_offset.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": "importance_sampling/boost/statistics/detail/importance_sampling/weights/apply_exp_offset.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": "importance_sampling/boost/statistics/detail/importance_sampling/weights/apply_exp_offset.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.5652173913, "max_line_length": 88, "alphanum_fraction": 0.5380507343, "num_tokens": 494, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.49438983346759924}}
{"text": "/**\n * \\file\n * \\author Thomas Fischer\n * \\date   2011-03-17\n * \\brief  Implementation of the AngleSkewMetric class.\n *\n * \\copyright\n * Copyright (c) 2012-2022, OpenGeoSys Community (http://www.opengeosys.org)\n *            Distributed under a Modified BSD License.\n *              See accompanying file LICENSE.txt or\n *              http://www.opengeosys.org/project/license\n *\n */\n\n#include \"AngleSkewMetric.h\"\n\n#include <boost/math/constants/constants.hpp>\n#include <cmath>\n\n#include \"MathLib/MathTools.h\"\n#include \"MeshLib/Node.h\"\n\nusing namespace boost::math::double_constants;\n\nnamespace MeshLib\n{\nnamespace\n{\ntemplate <unsigned long N>\nstd::tuple<double, double> getMinMaxAngle(\n    std::array<MeshLib::Node, N> const& nodes)\n{\n    double min_angle(two_pi);\n    double max_angle(0.0);\n\n    for (decltype(N) i = 0; i < N; ++i)\n    {\n        const double angle(MathLib::getAngle(nodes[i], nodes[(i + 1) % N],\n                                             nodes[(i + 2) % N]));\n        min_angle = std::min(angle, min_angle);\n        max_angle = std::max(angle, max_angle);\n    }\n    return {min_angle, max_angle};\n}\n\ndouble checkTriangle(Element const& elem)\n{\n    std::array const nodes = {*elem.getNode(0), *elem.getNode(1),\n                              *elem.getNode(2)};\n    auto const& [min_angle, max_angle] = getMinMaxAngle(nodes);\n    return std::max((max_angle - third_pi) / two_thirds_pi,\n                    (third_pi - min_angle) / third_pi);\n}\n\ndouble checkQuad(Element const& elem)\n{\n    std::array const nodes = {*elem.getNode(0), *elem.getNode(1),\n                              *elem.getNode(2), *elem.getNode(3)};\n    auto const& [min_angle, max_angle] = getMinMaxAngle(nodes);\n\n    return std::max((max_angle - half_pi) / half_pi,\n                    (half_pi - min_angle) / half_pi);\n}\n\ndouble checkTetrahedron(Element const& elem)\n{\n    std::array<double, 4> min;\n    std::array<double, 4> max;\n    for (auto face_number = 0; face_number < 4; ++face_number)\n    {\n        std::unique_ptr<Element const> face{elem.getFace(face_number)};\n        std::array const nodes = {*face->getNode(0), *face->getNode(1),\n                                  *face->getNode(2)};\n        std::tie(min[face_number], max[face_number]) = getMinMaxAngle(nodes);\n    }\n\n    double const min_angle = *std::min_element(min.begin(), min.end());\n    double const max_angle = *std::max_element(max.begin(), max.end());\n\n    return std::max((max_angle - third_pi) / two_thirds_pi,\n                    (third_pi - min_angle) / third_pi);\n}\n\ndouble checkHexahedron(Element const& elem)\n{\n    std::array<double, 6> min;\n    std::array<double, 6> max;\n    for (auto face_number = 0; face_number < 6; ++face_number)\n    {\n        std::unique_ptr<Element const> face{elem.getFace(face_number)};\n        std::array const nodes = {*face->getNode(0), *face->getNode(1),\n                                  *face->getNode(2), *face->getNode(3)};\n        std::tie(min[face_number], max[face_number]) = getMinMaxAngle(nodes);\n    }\n\n    double const min_angle = *std::min_element(min.begin(), min.end());\n    double const max_angle = *std::max_element(max.begin(), max.end());\n\n    return std::max((max_angle - half_pi) / half_pi,\n                    (half_pi - min_angle) / half_pi);\n}\n\ndouble checkPrism(Element const& elem)\n{\n    // face 0: triangle (0,1,2)\n    std::unique_ptr<Element const> f0{elem.getFace(0)};\n    std::array const nodes_f0 = {*f0->getNode(0), *f0->getNode(1),\n                                 *f0->getNode(2)};\n    auto const& [min_angle_tri0, max_angle_tri0] = getMinMaxAngle(nodes_f0);\n\n    // face 4: triangle (3,4,5)\n    std::unique_ptr<Element const> f4{elem.getFace(4)};\n    std::array const nodes_f4 = {*f4->getNode(0), *f4->getNode(1),\n                                 *f4->getNode(2)};\n    auto const& [min_angle_tri1, max_angle_tri1] = getMinMaxAngle(nodes_f4);\n\n    auto const min_angle_tri = std::min(min_angle_tri0, min_angle_tri1);\n    auto const max_angle_tri = std::max(max_angle_tri0, max_angle_tri1);\n\n    double const tri_criterion(\n        std::max((max_angle_tri - third_pi) / two_thirds_pi,\n                 (third_pi - min_angle_tri) / third_pi));\n\n    std::array<double, 3> min;\n    std::array<double, 3> max;\n    for (int i = 1; i < 4; ++i)\n    {\n        std::unique_ptr<Element const> f{elem.getFace(i)};\n        std::array const nodes = {*f->getNode(0), *f->getNode(1),\n                                  *f->getNode(2), *f->getNode(3)};\n        std::tie(min[i - 1], max[i - 1]) = getMinMaxAngle(nodes);\n    }\n\n    double const min_angle_quad = *std::min_element(min.begin(), min.end());\n    double const max_angle_quad = *std::max_element(max.begin(), max.end());\n\n    double const quad_criterion(std::max((max_angle_quad - half_pi) / half_pi,\n                                         (half_pi - min_angle_quad) / half_pi));\n\n    return std::min(tri_criterion, quad_criterion);\n}\n\n}  // end unnamed namespace\n\nvoid AngleSkewMetric::calculateQuality()\n{\n    for (auto const e : _mesh.getElements())\n    {\n        switch (e->getGeomType())\n        {\n            case MeshElemType::LINE:\n                _element_quality_metric[e->getID()] = -1.0;\n                break;\n            case MeshElemType::TRIANGLE:\n                _element_quality_metric[e->getID()] = checkTriangle(*e);\n                break;\n            case MeshElemType::QUAD:\n                _element_quality_metric[e->getID()] = checkQuad(*e);\n                break;\n            case MeshElemType::TETRAHEDRON:\n                _element_quality_metric[e->getID()] = checkTetrahedron(*e);\n                break;\n            case MeshElemType::HEXAHEDRON:\n                _element_quality_metric[e->getID()] = checkHexahedron(*e);\n                break;\n            case MeshElemType::PRISM:\n                _element_quality_metric[e->getID()] = checkPrism(*e);\n                break;\n            default:\n                break;\n        }\n    }\n}\n\n}  // end namespace MeshLib\n", "meta": {"hexsha": "783b83be4c0d075afd59c6fd92dae4415c593202", "size": 5975, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "MeshLib/MeshQuality/AngleSkewMetric.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": "MeshLib/MeshQuality/AngleSkewMetric.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": "MeshLib/MeshQuality/AngleSkewMetric.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.9488636364, "max_line_length": 80, "alphanum_fraction": 0.5849372385, "num_tokens": 1546, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971190859164, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4940908802050595}}
{"text": "#include \"model.h\"\n#include <math.h>\n#include <time.h>\n#include <boost/random.hpp>\n\nModel::Model()\n{\n}\n\nvoid Model::init(double dt, int m, int n, int nh, double sigma, double sv0)\n{\n    this->dt = pow(10, dt);\n    this->nh = nh;\n    this->n = n;\n    this->m = m;\n    if (nh % 2 == 0)\n        this->N = nh*nh - nh/2;\n    else\n        this->N = nh*nh - (nh-1)/2;\n    this->sigma = sigma;\n    this->sv0 = sv0;\n\n    update();\n\n    p.resize(2, N);\n    q.resize(2, N);\n    f1.resize(2, N);\n    f2.resize(2, N);\n    f3.resize(2, N);\n    f4.resize(2, N);\n    v1.resize(2, N);\n    v2.resize(2, N);\n    v3.resize(2, N);\n    v4.resize(2, N);\n\n    typedef boost::mt19937                     ENG;    // Mersenne Twister\n    typedef boost::normal_distribution<double> DIST;   // Normal Distribution\n    typedef boost::variate_generator<ENG,DIST> GEN;    // Variate generator\n\n    ENG  eng;\n    DIST dist(0, sv0);\n    GEN  gen(eng, dist);\n\n    gen.engine().seed(time(NULL) + ::getpid());\n    gen.distribution().reset();\n\n    Eigen::Vector2d\n            qi(sigma - 0.5, sigma - 0.5),\n            n1(sigma, 0),\n            n2(sigma/2, sigma*sqrt(3)/2);\n\n    for (int i=0; i<N; ++i) {\n        p(0,i) = gen();\n        p(1,i) = gen();\n        q.col(i) = qi;\n        qi += n1;\n        if (qi[0] > nh*sigma - 0.25)\n            qi += n2 - nh*n1;\n    }\n}\n\nvoid Model::update()\n{\n    this->mass = 1.0;\n    this->boxW = sigma * (nh + 1) - 1;\n    this->boxH = sigma * ((nh - 1) * sqrt(3)/2 + 2) - 1;\n    this->packingFractionHCP = (N * M_PI / 4) / (boxW * boxH) / (M_PI / (2*sqrt(3)));\n    if (m == 0)\n        this->cutoff = pow(1e-10, -1./(n+1.));\n    else\n        this->cutoff = pow((n/(double)m-1.)*1e-10, -1./(m+1.));\n}\n\nvoid Model::forces(const Eigen::Matrix2Xd &p, const Eigen::Matrix2Xd &q,\n                   Eigen::Matrix2Xd &f, Eigen::Matrix2Xd &v)\n{\n    Eigen::Vector2d rij, fij;\n    double r;\n\n    for (int i=0; i<N; ++i)\n        f.col(i) << 0, 0;\n\n    for (int i=0; i<N; ++i) {\n        fij << n*pow(q(0,i)+0.5, -n-1) - m*pow(q(0,i)+0.5, -m-1) - \\\n               n*pow(boxW-q(0,i)+0.5, -n-1) + m*pow(boxW-q(0,i)+0.5, -m-1),\n               n*pow(q(1,i)+0.5, -n-1) - m*pow(q(1,i)+0.5, -m-1) - \\\n               n*pow(boxH-q(1,i)+0.5, -n-1) + m*pow(boxH-q(1,i)+0.5, -m-1);\n        f.col(i) = f.col(i) + fij;\n\n        for (int j=i+1; j<N; ++j) {\n            rij = q.col(j) - q.col(i);\n            r = rij.norm();\n            if (r > cutoff)\n                continue;\n            fij = (n*pow(r, -n-1) - m*pow(r, -m-1)) * rij.normalized();\n            f.col(j) = f.col(j) + fij;\n            f.col(i) = f.col(i) - fij;\n        }\n    }\n\n    v = p;\n}\n\nvoid Model::rk4step()\n{\n    forces(p,             q,             f1, v1);\n    forces(p + 0.5*dt*f1, q + 0.5*dt*v1, f2, v2);\n    forces(p + 0.5*dt*f2, q + 0.5*dt*v2, f3, v3);\n    forces(p + dt*f3,     q + dt*v3,     f4, v4);\n\n    p += dt * (f1 + 2*(f2 + f3) + f4) / 6.0;\n    q += dt * (v1 + 2*(v2 + v3) + v4) / 6.0;\n\n    t += dt;\n}\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "c12f2d9150e53e5d9c8a131d7197ced675db08ca", "size": 2969, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QtSoftMatter/model.cpp", "max_stars_repo_name": "macioosch/QtSoftMatter", "max_stars_repo_head_hexsha": "93e23f0fa27fee8885023c1a648531552e443ed7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-15T02:23:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T02:23:44.000Z", "max_issues_repo_path": "QtSoftMatter/model.cpp", "max_issues_repo_name": "macioosch/QtSoftMatter", "max_issues_repo_head_hexsha": "93e23f0fa27fee8885023c1a648531552e443ed7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "QtSoftMatter/model.cpp", "max_forks_repo_name": "macioosch/QtSoftMatter", "max_forks_repo_head_hexsha": "93e23f0fa27fee8885023c1a648531552e443ed7", "max_forks_repo_licenses": ["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.5634920635, "max_line_length": 85, "alphanum_fraction": 0.4459413944, "num_tokens": 1147, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583695, "lm_q2_score": 0.5813030906443134, "lm_q1q2_score": 0.4940908757866943}}
{"text": "#include <iostream>\n#include <fstream>\n#include <vector>\n#include <boost/numeric/ublas/matrix.hpp>\n\nconst int columns = 5;\nconst int rows = 5;\n\nstd::vector<int> getBingoNumbers(std::ifstream *file);\nstd::vector<boost::numeric::ublas::bounded_matrix<int, rows, columns>> getBingoCards(std::ifstream *file);\nbool checkRow(int row, boost::numeric::ublas::bounded_matrix<bool, rows, columns> *bingoCardHistory);\nbool checkColumn(int column, boost::numeric::ublas::bounded_matrix<bool, rows, columns> *bingoCardHistory);\nint calcWinningScore(int winningNumber, boost::numeric::ublas::bounded_matrix<int, rows, columns> *bingoCard, boost::numeric::ublas::bounded_matrix<bool, rows, columns> *bingoCardHistory);\n\n\nint main() {\n\tstd::cout << \"Hello world\" << std::endl;\n  std::ifstream bingoNumbersFile(\"hello-world.txt\");\n  if (!bingoNumbersFile.is_open())\n  {\n    std::cout << \"No file 'hello-world.txt' found! Did you name it correctly?\" << std::endl;\n    exit(1);\n  }\n\n  std::vector<int> bingoNumbers = getBingoNumbers(&bingoNumbersFile);\n  std::vector<boost::numeric::ublas::bounded_matrix<int, rows, columns>> bingoCards = getBingoCards(&bingoNumbersFile);\n\n  std::vector<boost::numeric::ublas::bounded_matrix<bool, rows, columns>> bingoCardsHistory(bingoCards.size());\n\n  int winner;\n  //loop over all numbers called\n  for (size_t i = 0; i < bingoNumbers.size(); i++)\n  {\n    int bingoNumber = bingoNumbers[i];\n    //loop over all bingocards\n    for (size_t j = 0; j < bingoCards.size(); j++)\n    {\n      boost::numeric::ublas::bounded_matrix<int, rows, columns> bingoCard = bingoCards[j];\n      //loop over rows of bingocard\n      for (size_t r = 0; r < rows; r++)\n      {\n        //loop over columns of the row\n        for (size_t c = 0; c < columns; c++)\n        {\n          if (bingoCard(r, c) == bingoNumber)\n          {\n            bingoCardsHistory[j](r,c) = 1;\n            if (checkRow(r, &bingoCardsHistory[j]) || checkColumn(c, &bingoCardsHistory[j]))\n            {\n              winner = calcWinningScore(bingoNumber, &bingoCard, &bingoCardsHistory[j]);\n              std::cout << \"ow sheesh :s\" << std::endl;\n              return 0;\n            }\n          }\n        }\n      }\n    }\n  } \n}\n\nint calcWinningScore(int winningNumber, boost::numeric::ublas::bounded_matrix<int, rows, columns> *bingoCard, boost::numeric::ublas::bounded_matrix<bool, rows, columns> *bingoCardHistory) {\n  int sum = 0;\n  for (size_t i = 0; i < rows; i++)\n  {\n    for (size_t j = 0; j < columns; j++)\n    {\n      if ((*bingoCardHistory)(i,j) != 1)\n      {\n        sum += (*bingoCard)(i,j);\n      }\n    }\n  }\n  std::cout << \"winning number: \" << sum * winningNumber << std::endl;\n  return sum * winningNumber;\n}\n\nbool checkRow(int row, boost::numeric::ublas::bounded_matrix<bool, rows, columns> *bingoCardHistory) {\n  for (size_t i = 0; i < columns; i++)\n  {\n    if ((*bingoCardHistory)(row, i) != 1)\n    {\n      return 0;\n    }\n  }\n  return 1;\n}\n\nbool checkColumn(int column, boost::numeric::ublas::bounded_matrix<bool, rows, columns> *bingoCardHistory) {\n  for (size_t i = 0; i < rows; i++)\n  {\n    if ((*bingoCardHistory)(i, column) != 1)\n    {\n      return 0;\n    }\n  }\n  return 1;\n}\n\nstd::vector<boost::numeric::ublas::bounded_matrix<int, rows, columns>> getBingoCards(std::ifstream *file) {\n  std::vector<boost::numeric::ublas::bounded_matrix<int, rows, columns>> bingoCards;\n\n  int currentColumn = 0;\n  int currentRow = 0;\n  boost::numeric::ublas::bounded_matrix<int, rows, columns> bingoCard;\n  int x;\n  while (*file >> x)\n  {\n    bingoCard(currentRow, currentColumn) = x;\n\n    currentColumn ++;\n    if (currentColumn == columns)\n    {\n      currentColumn = 0;\n      currentRow ++;\n    }\n    if (currentRow == rows)\n    {\n      currentRow = 0;\n      bingoCards.push_back(bingoCard);\n    }\n  }\n  return bingoCards;\n}\n\nstd::vector<int> getBingoNumbers(std::ifstream *file) {\n  std::string bingoNumbersString;\n  std::getline(*file, bingoNumbersString);\n\n  std::string delimiter = \",\";\n  size_t pos = 0;\n\n  std::vector<int> bingoNumbers;\n  std::string token;\n  while ((pos = bingoNumbersString.find(delimiter)) != std::string::npos) {\n      bingoNumbers.push_back(std::stoi(bingoNumbersString.substr(0, pos)));\n      bingoNumbersString.erase(0, pos + delimiter.length());\n  }\n\n  return bingoNumbers;\n}", "meta": {"hexsha": "2883221339bc2ae976d1ca340a104af4fb54a96c", "size": 4291, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "day 04/Marnix - C++/hello-world-1/hello-world.cpp", "max_stars_repo_name": "AE-nv/aedvent-code-2021", "max_stars_repo_head_hexsha": "7ce199d6be5f6cce2e61a9c0d26afd6d064a86a7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-02T12:09:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-02T12:09:11.000Z", "max_issues_repo_path": "day 04/Marnix - C++/hello-world-1/hello-world.cpp", "max_issues_repo_name": "AE-nv/aedvent-code-2021", "max_issues_repo_head_hexsha": "7ce199d6be5f6cce2e61a9c0d26afd6d064a86a7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "day 04/Marnix - C++/hello-world-1/hello-world.cpp", "max_forks_repo_name": "AE-nv/aedvent-code-2021", "max_forks_repo_head_hexsha": "7ce199d6be5f6cce2e61a9c0d26afd6d064a86a7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-01T21:14:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-01T21:14:41.000Z", "avg_line_length": 30.65, "max_line_length": 189, "alphanum_fraction": 0.6376136099, "num_tokens": 1215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711756575749, "lm_q2_score": 0.5813030906443134, "lm_q1q2_score": 0.49409087136832885}}
{"text": "#include \"aikido/planner/vectorfield/VectorFieldUtil.hpp\"\n\n#include <Eigen/Geometry>\n#include <dart/optimizer/Solver.hpp>\n#include <dart/optimizer/nlopt/NloptSolver.hpp>\n\n#include \"aikido/common/algorithm.hpp\"\n#include \"aikido/trajectory/Spline.hpp\"\n\nnamespace aikido {\nnamespace planner {\nnamespace vectorfield {\n\nnamespace {\n\n/// A function class that defines an objective. The objective measures\n/// the difference between a desired twist and Jacobian * joint velocities.\n///\nclass DesiredTwistFunction : public dart::optimizer::Function\n{\npublic:\n  using Twist = Eigen::Vector6d;\n  using Jacobian = dart::math::Jacobian;\n\n  /// Constructor.\n  ///\n  /// \\param[in] twist A desired twist.\n  /// \\param[in] jacobian System Jacobian.\n  DesiredTwistFunction(const Twist& twist, const Jacobian& jacobian)\n    : dart::optimizer::Function(\"DesiredTwistFunction\")\n    , mTwist(twist)\n    , mJacobian(jacobian)\n  {\n    // Do nothing\n  }\n\n  /// Implementation inherited.\n  /// Evaluating an objective by a state value.\n  ///\n  /// \\param[in] qd Joint velocities.\n  /// \\return Objective value.\n  double eval(const Eigen::VectorXd& qd) override\n  {\n    return 0.5 * (mJacobian * qd - mTwist).squaredNorm();\n  }\n\n  /// Implementation inherited.\n  /// Evaluating gradient of an objective by a state value.\n  /// \\param[in] qd Joint velocities.\n  /// \\param[out] grad Gradient of a defined objective.\n  void evalGradient(\n      const Eigen::VectorXd& qd, Eigen::Map<Eigen::VectorXd> grad) override\n  {\n    grad = mJacobian.transpose() * (mJacobian * qd - mTwist);\n  }\n\nprotected:\n  /// Twist.\n  Twist mTwist;\n\n  /// Jacobian of Meta Skeleton.\n  Jacobian mJacobian;\n\npublic:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n};\n} // namespace\n\n//==============================================================================\nbool computeJointVelocityFromTwist(\n    Eigen::VectorXd& jointVelocity,\n    const Eigen::Vector6d& desiredTwist,\n    const dart::dynamics::MetaSkeletonPtr metaSkeleton,\n    const dart::dynamics::ConstBodyNodePtr bodyNode,\n    double jointLimitPadding,\n    const Eigen::VectorXd& jointVelocityLowerLimits,\n    const Eigen::VectorXd& jointVelocityUpperLimits,\n    bool enforceJointVelocityLimits,\n    double stepSize)\n{\n  using dart::math::Jacobian;\n  using dart::optimizer::Problem;\n  using dart::optimizer::Solver;\n  using Eigen::VectorXd;\n\n  // Use LBFGS to find joint angles that won't violate the joint limits.\n  const Jacobian jacobian = metaSkeleton->getWorldJacobian(bodyNode);\n\n  const std::size_t numDofs = metaSkeleton->getNumDofs();\n\n  jointVelocity = Eigen::VectorXd::Zero(numDofs);\n  VectorXd positions = metaSkeleton->getPositions();\n  VectorXd initialGuess = metaSkeleton->getVelocities();\n  VectorXd positionLowerLimits = metaSkeleton->getPositionLowerLimits();\n  VectorXd positionUpperLimits = metaSkeleton->getPositionUpperLimits();\n  VectorXd velocityLowerLimits = jointVelocityLowerLimits;\n  VectorXd velocityUpperLimits = jointVelocityUpperLimits;\n\n  const auto problem = std::make_shared<Problem>(numDofs);\n  if (enforceJointVelocityLimits)\n  {\n    for (std::size_t i = 0; i < numDofs; ++i)\n    {\n      const double position = positions[i];\n      const double positionLowerLimit = positionLowerLimits[i];\n      const double positionUpperLimit = positionUpperLimits[i];\n      const double velocityLowerLimit = velocityLowerLimits[i];\n      const double velocityUpperLimit = velocityUpperLimits[i];\n\n      if (position + stepSize * velocityLowerLimit\n          <= positionLowerLimit + jointLimitPadding)\n      {\n        velocityLowerLimits[i] = 0.0;\n      }\n\n      if (position + stepSize * velocityUpperLimit\n          >= positionUpperLimit - jointLimitPadding)\n      {\n        velocityUpperLimits[i] = 0.0;\n      }\n\n      initialGuess[i] = common::clamp(\n          initialGuess[i], velocityLowerLimits[i], velocityUpperLimits[i]);\n    }\n    problem->setLowerBounds(velocityLowerLimits);\n    problem->setUpperBounds(velocityUpperLimits);\n  }\n\n  problem->setInitialGuess(initialGuess);\n  problem->setObjective(dart::common::make_aligned_shared<DesiredTwistFunction>(\n      desiredTwist, jacobian));\n\n#if DART_VERSION_AT_LEAST(6, 9, 0)\n  dart::optimizer::NloptSolver solver(\n      problem, dart::optimizer::NloptSolver::LD_LBFGS);\n#else\n  dart::optimizer::NloptSolver solver(problem, nlopt::LD_LBFGS);\n#endif\n  if (!solver.solve())\n  {\n    return false;\n  }\n  jointVelocity = problem->getOptimalSolution();\n  return true;\n}\n\n//==============================================================================\nEigen::Vector6d computeGeodesicTwist(\n    const Eigen::Isometry3d& fromTrans, const Eigen::Isometry3d& toTrans)\n{\n  using dart::math::logMap;\n  Eigen::Isometry3d relativeTrans = fromTrans.inverse() * toTrans;\n  Eigen::Vector3d relativeTranslation\n      = fromTrans.linear() * relativeTrans.translation();\n  Eigen::Vector3d axisAngles = logMap(relativeTrans.linear());\n  Eigen::Vector3d relativeAngles = fromTrans.linear() * axisAngles;\n  Eigen::Vector6d geodesicTwist;\n  geodesicTwist << relativeAngles, relativeTranslation;\n  return geodesicTwist;\n}\n\n//==============================================================================\nEigen::Vector4d computeGeodesicError(\n    const Eigen::Isometry3d& fromTrans, const Eigen::Isometry3d& toTrans)\n{\n  using dart::math::logMap;\n  Eigen::Isometry3d relativeTrans = fromTrans.inverse() * toTrans;\n  Eigen::Vector3d relativeTranslation\n      = fromTrans.linear() * relativeTrans.translation();\n  Eigen::Vector3d axisAngles = logMap(relativeTrans.linear());\n  Eigen::Vector4d geodesicError;\n  geodesicError << axisAngles.norm(), relativeTranslation;\n  return geodesicError;\n}\n\n//==============================================================================\ndouble computeGeodesicDistance(\n    const Eigen::Isometry3d& fromTrans,\n    const Eigen::Isometry3d& toTrans,\n    double r)\n{\n  Eigen::Vector4d error = computeGeodesicError(fromTrans, toTrans);\n  error[0] = r * error[0];\n  return error.norm();\n}\n\n} // namespace vectorfield\n} // namespace planner\n} // namespace aikido\n", "meta": {"hexsha": "9c25f9e5f95e64efb4dd56530955ffcc81706173", "size": 6041, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/planner/vectorfield/VectorFieldUtil.cpp", "max_stars_repo_name": "personalrobotics/r3", "max_stars_repo_head_hexsha": "1303e3f3ef99a0c2249abc7415d19113f0026565", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 181.0, "max_stars_repo_stars_event_min_datetime": "2016-04-22T15:11:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T12:51:08.000Z", "max_issues_repo_path": "src/planner/vectorfield/VectorFieldUtil.cpp", "max_issues_repo_name": "personalrobotics/r3", "max_issues_repo_head_hexsha": "1303e3f3ef99a0c2249abc7415d19113f0026565", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 514.0, "max_issues_repo_issues_event_min_datetime": "2016-04-20T04:29:51.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T19:46:21.000Z", "max_forks_repo_path": "src/planner/vectorfield/VectorFieldUtil.cpp", "max_forks_repo_name": "personalrobotics/r3", "max_forks_repo_head_hexsha": "1303e3f3ef99a0c2249abc7415d19113f0026565", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 31.0, "max_forks_repo_forks_event_min_datetime": "2017-03-17T09:53:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T10:35:05.000Z", "avg_line_length": 31.7947368421, "max_line_length": 80, "alphanum_fraction": 0.686475749, "num_tokens": 1460, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.49409087136832885}}
{"text": "/*\nMetaheuristic Optimization Using Population-Based Simulated Annealing.\n\nCopyright (c) 2021 Gabriele Gilardi\n\n\n    func            Function to minimize\n    LB              Lower boundaries of the search space\n    UB              Upper boundaries of the search space\n    nPop            Number of agents (population)\n    epochs          Number of iterations\n    nMove           Number of neighbours of a state evaluated at each epoch\n    T0              Initial temperature\n    alphaT          Temperature reduction rate\n    sigma0          Initial standard deviation used to search the neighboroud\n                    of a state (given as a fraction of the search space)\n    alphaS          Standard deviation reduction rate\n    prob            Probability the dimension of a state is changed\n    IntVar          List of indexes specifying which variable should be treated\n                    as integer\n    normalize       Specifies if the search space should be normalized\n    args            Tuple containing any parameter that needs to be passed to\n                    the function\n\n    Dimensions:\n    (nVar)          LB, UB, LB_orig, UB_orig, sigma, best_pos\n    (nPop, nVar)    agent_pos, neigh_pos, agent_pos_orig, neigh_pos_orig\n    (nPop)          agent_cost, neigh_cost\n    (epochs)        F\n    (0-nVar)        IntVar\n*/\n\n#include <random>\n#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace std;\nusing namespace Eigen;\n\n/* Structure used to pass the parameters */\nstruct Parameters {\n    int nPop;\n    int epochs;\n    int nMove;\n    double T0;\n    double alphaT;\n    double sigma0;\n    double alphaS;\n    double prob;\n    bool normalize;\n    ArrayXi IntVar;\n    ArrayXXd args;\n    int seed;\n};\n\n/* Structure used to return the results */\nstruct Results {\n    double best_cost;\n    ArrayXXd best_pos;\n    ArrayXd F;\n    double T;\n    ArrayXXd sigma;\n};\n\n\n/* Minimize a function using simulated annealing */\nResults sa(ArrayXd (*func)(ArrayXXd, ArrayXXd), ArrayXXd LB, ArrayXXd UB,\n           Parameters p)\n{\n    int nVar, nIntVar, idx;\n    double T, prob_swap, delta, best_cost;\n    Results res;\n\n    /*Eigen declarations*/\n    Index r_min, c_min;\n    ArrayXd agent_cost, neigh_cost, F;\n    ArrayXXd LBe, UBe, LBe_orig, UBe_orig, sigma, agent_pos, neigh_pos,\n             agent_pos_orig, neigh_pos_orig, best_pos, rn, flips;\n    \n    /* Random generator and probability distributions */\n    mt19937 generator(p.seed);\n    uniform_real_distribution<double> unif(0.0, 1.0);\n    normal_distribution<double> norm(0.0, 1.0);\n\n\n    nVar = LB.size();\n    nIntVar = p.IntVar.size();\n\n    /* Create boundaries for all agents*/\n    LBe = LB.replicate(p.nPop, 1);\n    UBe = UB.replicate(p.nPop, 1);\n\n    /* Normalize search space */\n    if (p.normalize) {\n        LBe_orig = LBe;\n        UBe_orig = UBe;\n        LBe.setZero(p.nPop, nVar);\n        UBe.setOnes(p.nPop, nVar);\n    }\n\n    T = p.T0;                           // Temperature\n    sigma = p.sigma0 * (UBe - LBe);     // Standard deviation of each dimension\n\n    /* Initial position of each agent */\n    rn.setZero(p.nPop, nVar);\n    for (int i=0; i<p.nPop; i++) {\n        for (int j=0; j<nVar; j++) {\n            rn(i, j) = unif(generator);\n        }\n    }\n    agent_pos = LBe + rn * (UBe - LBe);\n\n    /* Correct for any integer variable */\n    for (int j=0; j<nIntVar; j++) {\n        idx = p.IntVar(j);\n        agent_pos.col(idx) = round(agent_pos.col(idx));\n    }\n\n    /* Initial cost of each agent */\n    if (p.normalize) {\n        agent_pos_orig = LBe_orig + agent_pos * (UBe_orig - LBe_orig);\n        agent_cost = func(agent_pos_orig, p.args);\n    }\n    else {\n        agent_cost = func(agent_pos, p.args);\n    }\n\n    /* Initial (overall) best position/cost */\n    best_cost = agent_cost.minCoeff(&r_min, &c_min);\n    best_pos = agent_pos.row(r_min);\n\n    /* Main loop (T = const) */\n    neigh_pos.setZero(p.nPop, nVar);\n    F.setZero(p.epochs);\n    for (int epoch=0; epoch<p.epochs; epoch++) {\n\n        /* Sub-loop (search the neighboroud of a state) */\n        for (int move=0; move<p.nMove; move++) {\n\n            /* Randomly decide in which dimension to search */\n            for (int i=0; i<p.nPop; i++) {\n                for (int j=0; j<nVar; j++) {\n                    rn(i, j) = unif(generator);\n                }\n            }\n            flips = (rn <= p.prob).cast<double>();\n\n            /* Create each agent's neighbours */\n            for (int i=0; i<p.nPop; i++) {\n                for (int j=0; j<nVar; j++) {\n                    rn(i, j) = norm(generator);\n                }\n            }\n            neigh_pos = agent_pos + flips * rn * sigma;\n\n            /* Correct for any integer variable */\n            for (int j=0; j<nIntVar; j++) {\n                idx = p.IntVar(j);\n                neigh_pos.col(idx) = round(neigh_pos.col(idx));\n            }\n\n            /* Impose position boundaries */\n            neigh_pos = neigh_pos.max(LBe);\n            neigh_pos = neigh_pos.min(UBe);\n\n            for (int j=0; j<nIntVar; j++) {\n                idx = p.IntVar(j);\n                neigh_pos.col(idx) = neigh_pos.col(idx).max(ceil(LBe.col(idx)));\n                neigh_pos.col(idx) = neigh_pos.col(idx).min(floor(UBe.col(idx)));\n            }\n\n            /* Evaluate the cost of each agent's neighbour */\n            if (p.normalize) {\n                neigh_pos_orig = LBe_orig + neigh_pos * (UBe_orig - LBe_orig);\n                neigh_cost = func(neigh_pos_orig, p.args);\n            }\n            else {\n                neigh_cost = func(neigh_pos, p.args);\n            }\n\n            /* Decide if each agent will change its state */\n            for (int i=0; i<p.nPop; i++) {\n\n                /* Swap states if the neighbour state is better ... */\n                if (neigh_cost(i) <= agent_cost(i)) {\n                    agent_cost(i) = neigh_cost(i);\n                    agent_pos.row(i) = neigh_pos.row(i);\n                }\n\n                /* ... or decide probabilistically */\n                else {\n\n                    /* Acceptance probability */\n                    delta = (neigh_cost(i) - agent_cost(i)) / agent_cost(i);\n                    prob_swap = exp(-delta / T);\n\n                    /* Randomly swap states */\n                    if (unif(generator) <= prob_swap) {\n                        agent_cost(i) = neigh_cost(i);\n                        agent_pos.row(i) = neigh_pos.row(i);\n                    }\n                }  \n\n                /* Update the (overall) best position/cost */\n                best_cost = agent_cost.minCoeff(&r_min, &c_min);\n                best_pos = agent_pos.row(r_min);\n            }\n        }\n\n        /* Save the best cost for this epoch */\n        F(epoch) = best_cost;\n\n        /* Cooling scheduling */\n        T = p.alphaT * T;\n \n        /* Random neighboroud search schedule */\n        sigma = p.alphaS * sigma;\n    }\n\n    /* De-normalize */\n    if (p.normalize) {\n        best_pos = LB + best_pos * (UB - LB);\n        sigma = sigma * (UBe_orig - LBe_orig);\n    }\n\n    /* Copy solution */\n    res.best_cost = best_cost;\n    res.T = T;\n    res.best_pos = best_pos;\n    res.sigma = sigma.row(0);\n    res.F = F;\n\n    return res;\n}\n", "meta": {"hexsha": "0f9f4630ed4f35531517150768119366fc199907", "size": 7183, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Code_Cpp/sa_Eigen.cpp", "max_stars_repo_name": "gabrielegilardi/SimulatedAnnealing", "max_stars_repo_head_hexsha": "c9f60d5569bcfdb985743ad3036b53bac23d1152", "max_stars_repo_licenses": ["MIT"], "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_Cpp/sa_Eigen.cpp", "max_issues_repo_name": "gabrielegilardi/SimulatedAnnealing", "max_issues_repo_head_hexsha": "c9f60d5569bcfdb985743ad3036b53bac23d1152", "max_issues_repo_licenses": ["MIT"], "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_Cpp/sa_Eigen.cpp", "max_forks_repo_name": "gabrielegilardi/SimulatedAnnealing", "max_forks_repo_head_hexsha": "c9f60d5569bcfdb985743ad3036b53bac23d1152", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-26T10:03:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-26T10:03:56.000Z", "avg_line_length": 30.5659574468, "max_line_length": 81, "alphanum_fraction": 0.536266184, "num_tokens": 1736, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711604559846, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4940908625315974}}
{"text": "#include <stdio.h>\n#include <iostream>\n#include <math.h>\n#include <string>\n#include <Eigen/Dense>\n#include \"ros/ros.h\"\n\n#include <yaml-cpp/yaml.h>\n#include <ros/package.h>\n\n#include <std_msgs/Float32MultiArray.h>\n#include <sensor_msgs/JointState.h>\n#include <robot_localization_msgs/HeadTransform.h>\n\nusing namespace ros;\nusing namespace std;\nusing namespace Eigen;\n\nfloat angle_torso_pitch=0.0;\nfloat angle_torso_yaw=0.0;\nfloat angle_head_yaw=0.0;\nfloat angle_head_pitch=0.0;\n    \nvoid jointCallback(const sensor_msgs::JointState::ConstPtr& msg);\n\nbool RobotYamlRead(string path, float* length_pelvis2torsopitch, float* length_torsopitch2torsoyaw, float* length_torsoyaw2headyaw, float* length_headyaw2headpitch, float* length_headpitch2camera);\nbool ParticleYamlRead(string path, float& unit);\n\nMatrix4f makeYawMatrix(float& theta);\nMatrix4f makePitchMatrix(float& theta);\nMatrix4f makeTransMatrix(Vector3f& position);\nMatrix4f makeTransMatrix(Vector3f& position, float& unit);\n\nvoid printMatrixValue(Matrix4f& matrix);\n\nvoid insertMatrix2Message(Matrix4f& matrix, std_msgs::Float32MultiArray& msg);\nvoid insertMatrix2Message(Matrix4f& matrix, robot_localization_msgs::HeadTransform& msg, int flag); // flag=0 -> original, flag=1 -> unit\n\nint main(int argc, char** argv)\n{\n    //read setting\n    string yaml_robot_path = package::getPath(\"robot_localization_data\") + \"/data/kin_dyn_3.yaml\";\n    string yaml_particle_path = package::getPath(\"robot_localization_data\") + \"/data/particle_setting.yaml\";\n  \n    float length_pelvis2torsopitch[3];\n    float length_torsopitch2torsoyaw[3];\n\n    float length_torsoyaw2headyaw[3];\n    float length_headyaw2headpitch[3];\n    float length_headpitch2camera[3];\n\n    float unit;\n   \n    if( !RobotYamlRead(yaml_robot_path, length_pelvis2torsopitch, length_torsopitch2torsoyaw, length_torsoyaw2headyaw, length_headyaw2headpitch, length_headpitch2camera) ) exit(0);\n    if( !ParticleYamlRead(yaml_particle_path, unit) ) exit(0);\n   \n    Vector3f V_length_pelvis2torsopitch(length_pelvis2torsopitch[0], length_pelvis2torsopitch[1], length_pelvis2torsopitch[2]);\n    Vector3f V_length_torsopitch2torsoyaw(length_torsopitch2torsoyaw[0], length_torsopitch2torsoyaw[1], length_torsopitch2torsoyaw[2]);\n    Vector3f V_length_torsoyaw2headyaw(length_torsoyaw2headyaw[0],length_torsoyaw2headyaw[1],length_torsoyaw2headyaw[2]);\n    Vector3f V_length_headyaw2headpitch(length_headyaw2headpitch[0],length_headyaw2headpitch[1],length_headyaw2headpitch[2]);\n    Vector3f V_length_headpitch2camera(length_headpitch2camera[0], length_headpitch2camera[1], length_headpitch2camera[2]);\n\n    //start ros\n    ros::init(argc, argv, \"robot_localization_head_receive3\");\n    ros::NodeHandle n;\n    ros::Rate loop_rate(100);\n    \n    ros::Publisher headtransform_pub = n.advertise<std_msgs::Float32MultiArray>(\"/alice/camera_transform\",10);\n    ros::Publisher custom_headtransform_pub = n.advertise<robot_localization_msgs::HeadTransform>(\"/robot_localization/head_transform\",10);\n    ros::Subscriber joint_sub = n.subscribe(\"/robotis/present_joint_states\",10,jointCallback);\n\n    while(ros::ok())\n    {\n        std_msgs::Float32MultiArray headtransform_msg;\n        robot_localization_msgs::HeadTransform custom_headtransform_msg;\n\n        //real world\n        Matrix4f t_pelvis2torsopitch = makeTransMatrix(V_length_pelvis2torsopitch);\n        Matrix4f r_pelvis2torsopitch = Matrix4f::Identity();\n\n        Matrix4f t_torsopitch2torsoyaw = makeTransMatrix(V_length_torsopitch2torsoyaw);\n        Matrix4f r_torsopitch2torsoyaw = makePitchMatrix(angle_torso_pitch);\n\n        Matrix4f t_torsoyaw2headyaw = makeTransMatrix(V_length_torsoyaw2headyaw);\n        Matrix4f r_torsoyaw2headyaw = makeYawMatrix(angle_torso_yaw);\n        \n        Matrix4f t_headyaw2headpitch = makeTransMatrix(V_length_headyaw2headpitch);\n        Matrix4f r_headyaw2headpitch = makeYawMatrix(angle_head_yaw);\n\n        Matrix4f t_headpitch2camera = makeTransMatrix(V_length_headpitch2camera);\n        Matrix4f r_headpitch2camera = makePitchMatrix(angle_head_pitch);\n\n        Matrix4f TR01 = r_pelvis2torsopitch * t_pelvis2torsopitch;\n        Matrix4f TR12 = r_torsopitch2torsoyaw * t_torsopitch2torsoyaw;\n        Matrix4f TR23 = r_torsoyaw2headyaw * t_torsoyaw2headyaw;\n        Matrix4f TR34 = r_headyaw2headpitch * t_headyaw2headpitch;\n        Matrix4f TR45 = r_headpitch2camera * t_headpitch2camera;\n\n        Matrix4f Transform_pelvis2head = TR01 * TR12 * TR23 * TR34 * TR45;  // Transform matrix real world = TR\n\n        //virtual world\n        Matrix4f t_pelvis2torsopitch_V = makeTransMatrix(V_length_pelvis2torsopitch, unit);\n        Matrix4f t_torsopitch2torsoyaw_V = makeTransMatrix(V_length_torsopitch2torsoyaw, unit);\n        Matrix4f t_torsoyaw2headyaw_V = makeTransMatrix(V_length_torsoyaw2headyaw, unit);\n        Matrix4f t_headyaw2headpitch_V = makeTransMatrix(V_length_headyaw2headpitch, unit);\n        Matrix4f t_headpitch2camera_V = makeTransMatrix(V_length_headpitch2camera, unit);\n\n        Matrix4f TV01 = r_pelvis2torsopitch * t_pelvis2torsopitch_V;\n        Matrix4f TV12 = r_torsopitch2torsoyaw * t_torsopitch2torsoyaw_V;\n        Matrix4f TV23 = r_torsoyaw2headyaw * t_torsoyaw2headyaw_V;\n        Matrix4f TV34 = r_headyaw2headpitch * t_headyaw2headpitch_V;\n        Matrix4f TV45 = r_headpitch2camera * t_headpitch2camera_V;\n\n        Matrix4f unit_Transform_pelvis2head = TV01 * TV12 * TV23 * TV34 * TV45;   // Transform matrix virtual world = TV\n\n        insertMatrix2Message(Transform_pelvis2head, headtransform_msg);\n\n        insertMatrix2Message(Transform_pelvis2head, custom_headtransform_msg, 0);\n        insertMatrix2Message(unit_Transform_pelvis2head, custom_headtransform_msg, 1);\n\n        headtransform_pub.publish(headtransform_msg);\n        custom_headtransform_pub.publish(custom_headtransform_msg);\n      \n        cout << \"-----------------------------------------------\" << endl;\n        cout << \"waist_pitch : \" << angle_torso_pitch * 180 / M_PI << endl;\n        cout << \"waist_yaw : \" << angle_torso_yaw * 180 / M_PI << endl;\n        cout << \"head_yaw : \" << angle_head_yaw * 180 / M_PI << endl;\n        cout << \"head_pitch : \" << angle_head_pitch * 180 / M_PI << endl;\n        cout << \"-----------------------------------------------\" << endl;\n        printMatrixValue(Transform_pelvis2head);\n        cout << \"-----------------------------------------------\" << endl << endl;\n\n\n        ros::spinOnce();\n        loop_rate.sleep();\n    }\n\n    return 0;\n}\n\nvoid jointCallback(const sensor_msgs::JointState::ConstPtr& msg)\n{\n    int torso_pitch_index, torso_yaw_index, head_yaw_index, head_pitch_index;\n    for(int i=0; i<(msg->name).size(); i++)\n    {\n        if(msg->name[i] == \"waist_pitch\") torso_pitch_index = i;\n        if(msg->name[i] == \"waist_yaw\"  ) torso_yaw_index = i;\n        if(msg->name[i] == \"head_yaw\"   ) head_yaw_index = i;\n        if(msg->name[i] == \"head_pitch\" ) head_pitch_index = i;\n    }\n   \n    angle_torso_pitch = msg->position[torso_pitch_index];\n    angle_torso_yaw = msg->position[torso_yaw_index];\n    angle_head_yaw = msg->position[head_yaw_index];\n    angle_head_pitch = msg->position[head_pitch_index];\n}\n\nbool RobotYamlRead(string path, float* length_pelvis2torsopitch, float* length_torsopitch2torsoyaw, float* length_torsoyaw2headyaw, float* length_headyaw2headpitch, float* length_headpitch2camera)\n{\n    YAML::Node yaml_node;\n    try\n    {\n        yaml_node = YAML::LoadFile(path.c_str());\n\n        length_pelvis2torsopitch[0]   = yaml_node[\"torso_p\"][\"relative_position\"][0].as<float>();\n        length_pelvis2torsopitch[1]   = yaml_node[\"torso_p\"][\"relative_position\"][1].as<float>();\n        length_pelvis2torsopitch[2]   = yaml_node[\"torso_p\"][\"relative_position\"][2].as<float>();\n\n        length_torsopitch2torsoyaw[0] = yaml_node[\"torso_y\"][\"relative_position\"][0].as<float>();\n        length_torsopitch2torsoyaw[1] = yaml_node[\"torso_y\"][\"relative_position\"][1].as<float>();\n        length_torsopitch2torsoyaw[2] = yaml_node[\"torso_y\"][\"relative_position\"][2].as<float>();\n\n        length_torsoyaw2headyaw[0]    = yaml_node[\"head_y\"][\"relative_position\"][0].as<float>();\n        length_torsoyaw2headyaw[1]    = yaml_node[\"head_y\"][\"relative_position\"][1].as<float>();\n        length_torsoyaw2headyaw[2]    = yaml_node[\"head_y\"][\"relative_position\"][2].as<float>();\n\n        length_headyaw2headpitch[0]  = yaml_node[\"head_p\"][\"relative_position\"][0].as<float>();\n        length_headyaw2headpitch[1]  = yaml_node[\"head_p\"][\"relative_position\"][1].as<float>();\n        length_headyaw2headpitch[2]  = yaml_node[\"head_p\"][\"relative_position\"][2].as<float>();\n\n        length_headpitch2camera[0]   = yaml_node[\"cam\"][\"relative_position\"][0].as<float>();\n        length_headpitch2camera[1]   = yaml_node[\"cam\"][\"relative_position\"][1].as<float>();\n        length_headpitch2camera[2]   = yaml_node[\"cam\"][\"relative_position\"][2].as<float>();\n    }\n    catch(const exception& e)\n    {\n        ROS_ERROR(\"fail to read robot yaml file\");\n        return false;\n    }\n    return true;\n}\n\nbool ParticleYamlRead(string path, float& unit)\n{\n    YAML::Node yaml_node;\n    try\n    {\n        yaml_node = YAML::LoadFile(path.c_str());\n        unit = yaml_node[\"ETCSetting\"][\"unit\"].as<float>();\n    }\n    catch(const exception& e)\n    {\n        ROS_ERROR(\"fail to read particle yaml file\");\n        return false;\n    }\n    return true;\n}\n\nvoid insertMatrix2Message(Matrix4f& matrix, std_msgs::Float32MultiArray& msg)\n{\n    for(int i=0; i<4; i++)\n        for(int j=0; j<4; j++)\n            msg.data.push_back(matrix(i,j));\n}\n\nvoid printMatrixValue(Matrix4f& matrix){\n    vector<float> data;\n    for(int i=0; i<4; i++){\n        for(int j=0; j<4; j++){\n            data.push_back(matrix(i,j));\n            printf(\"%3.3f  \", data.back());\n        }\n        cout << endl;\n    }\n}\n\nvoid insertMatrix2Message(Matrix4f& matrix, robot_localization_msgs::HeadTransform& msg, int flag)\n{\n    switch(flag)\n    {\n        case 0:\n            for(int i=0; i<4; i++)\n                for(int j=0; j<4; j++)\n                    msg.Tdata.push_back(matrix(i,j));\n            break;\n        case 1:\n            for(int i=0; i<4; i++)\n                for(int j=0; j<4; j++)\n                    msg.Udata.push_back(matrix(i,j));\n            break;\n        default:\n            break;\n    }\n}\n\nMatrix4f makeYawMatrix(float& theta)\n{\n    Matrix4f matrix;\n    matrix(0,0)=cos(theta); matrix(0,1)=-sin(theta); matrix(0,2)=0; matrix(0,3)=0;\n    matrix(1,0)=sin(theta); matrix(1,1)= cos(theta); matrix(1,2)=0; matrix(1,3)=0;\n    matrix(2,0)=0;          matrix(2,1)=0;           matrix(2,2)=1; matrix(2,3)=0;\n    matrix(3,0)=0;          matrix(3,1)=0;           matrix(3,2)=0; matrix(3,3)=1;\n\n    return matrix;\n}\n\nMatrix4f makePitchMatrix(float& theta)\n{\n    Matrix4f matrix;\n    matrix(0,0)= cos(theta); matrix(0,1)=0; matrix(0,2)=sin(theta); matrix(0,3)=0;\n    matrix(1,0)=0;           matrix(1,1)=1; matrix(1,2)=0;          matrix(1,3)=0;\n    matrix(2,0)=-sin(theta); matrix(2,1)=0; matrix(2,2)=cos(theta); matrix(2,3)=0;\n    matrix(3,0)=0;           matrix(3,1)=0; matrix(3,2)=0;          matrix(3,3)=1;\n\n    return matrix;\n}\n\nMatrix4f makeTransMatrix(Vector3f& position)\n{\n    Matrix4f matrix;\n    matrix(0,0)=1; matrix(0,1)=0; matrix(0,2)=0; matrix(0,3)=position(0);\n    matrix(1,0)=0; matrix(1,1)=1; matrix(1,2)=0; matrix(1,3)=position(1);\n    matrix(2,0)=0; matrix(2,1)=0; matrix(2,2)=1; matrix(2,3)=position(2);\n    matrix(3,0)=0; matrix(3,1)=0; matrix(3,2)=0; matrix(3,3)=1;\n\n    return matrix;\n}\n\nMatrix4f makeTransMatrix(Vector3f& position, float& unit)\n{\n    Matrix4f matrix;\n    matrix(0,0)=1; matrix(0,1)=0; matrix(0,2)=0; matrix(0,3)=position(0)*unit;\n    matrix(1,0)=0; matrix(1,1)=1; matrix(1,2)=0; matrix(1,3)=position(1)*unit;\n    matrix(2,0)=0; matrix(2,1)=0; matrix(2,2)=1; matrix(2,3)=position(2)*unit;\n    matrix(3,0)=0; matrix(3,1)=0; matrix(3,2)=0; matrix(3,3)=1;\n\n    return matrix;\n}\n", "meta": {"hexsha": "ad70b7d02b539530c6ae17465fa484133dd180b0", "size": 11930, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "robot_localization_head_receive/src/robot_localization_head_receive3_test.cpp", "max_stars_repo_name": "lgkimjy/RobotLocalization_autumn", "max_stars_repo_head_hexsha": "c5caacb6b20a347e2a756d4f50124e1723b9b696", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-08-21T06:46:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T19:25:41.000Z", "max_issues_repo_path": "robot_localization_head_receive/src/robot_localization_head_receive3_test.cpp", "max_issues_repo_name": "lgkimjy/RobotLocalization_autumn", "max_issues_repo_head_hexsha": "c5caacb6b20a347e2a756d4f50124e1723b9b696", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "robot_localization_head_receive/src/robot_localization_head_receive3_test.cpp", "max_forks_repo_name": "lgkimjy/RobotLocalization_autumn", "max_forks_repo_head_hexsha": "c5caacb6b20a347e2a756d4f50124e1723b9b696", "max_forks_repo_licenses": ["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.2802768166, "max_line_length": 197, "alphanum_fraction": 0.6786253143, "num_tokens": 3513, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357735451834, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4940826344256474}}
{"text": "// Copyright (c) 2018 by University Paris-Est Marne-la-Vallee\n// InnerExplicit.hpp\n// This file is part of the Garamon for e3ga.\n// Authors: Stephane Breuils and Vincent Nozick\n// Contact: vincent.nozick@u-pem.fr\n//\n// Licence MIT\n// A a copy of the MIT License is given along with this program\n\n/// \\file InnerExplicit.hpp\n/// \\author Stephane Breuils, Vincent Nozick\n/// \\brief Explicit precomputed per grades inner products of e3ga.\n\n#ifndef E3GA_INNER_PRODUCT_EXPLICIT_HPP__\n#define E3GA_INNER_PRODUCT_EXPLICIT_HPP__\n#pragma once\n\n#include <Eigen/Core>\n\n#include \"e3ga/Mvec.hpp\"\n#include \"e3ga/Inner.hpp\"\n#include \"e3ga/Constants.hpp\"\n\n\n/*!\n * @namespace e3ga\n */\nnamespace e3ga {\n    template<typename T> class Mvec;\n\n    /// \\brief Compute the inner product between two homogeneous multivectors mv1 (grade 0) and mv2 (grade 0). \n\t/// \\tparam the type of value that we manipulate, either float or double or something.\n\t/// \\param mv1 - the first homogeneous multivector of grade 0 represented as an Eigen::VectorXd\n\t/// \\param mv2 - the second homogeneous multivector of grade 0 represented as a Eigen::VectorXd\n\t/// \\param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 0\n\ttemplate<typename T>\n\tvoid inner_0_0(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){\n\t\tmv3.coeffRef(0) +=  mv1.coeff(0)*mv2.coeff(0);\n\t}\n\n\n\t/// \\brief Compute the inner product between two homogeneous multivectors mv1 (grade 0) and mv2 (grade 1). \n\t/// \\tparam the type of value that we manipulate, either float or double or something.\n\t/// \\param mv1 - the first homogeneous multivector of grade 0 represented as an Eigen::VectorXd\n\t/// \\param mv2 - the second homogeneous multivector of grade 1 represented as a Eigen::VectorXd\n\t/// \\param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 1\n\ttemplate<typename T>\n\tvoid inner_0_1(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){\n\t\tmv3 += mv1.coeff(0)*mv2;\n\t}\n\n\n\t/// \\brief Compute the inner product between two homogeneous multivectors mv1 (grade 0) and mv2 (grade 2). \n\t/// \\tparam the type of value that we manipulate, either float or double or something.\n\t/// \\param mv1 - the first homogeneous multivector of grade 0 represented as an Eigen::VectorXd\n\t/// \\param mv2 - the second homogeneous multivector of grade 2 represented as a Eigen::VectorXd\n\t/// \\param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 2\n\ttemplate<typename T>\n\tvoid inner_0_2(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){\n\t\tmv3 += mv1.coeff(0)*mv2;\n\t}\n\n\n\t/// \\brief Compute the inner product between two homogeneous multivectors mv1 (grade 0) and mv2 (grade 3). \n\t/// \\tparam the type of value that we manipulate, either float or double or something.\n\t/// \\param mv1 - the first homogeneous multivector of grade 0 represented as an Eigen::VectorXd\n\t/// \\param mv2 - the second homogeneous multivector of grade 3 represented as a Eigen::VectorXd\n\t/// \\param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 3\n\ttemplate<typename T>\n\tvoid inner_0_3(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){\n\t\tmv3 += mv1.coeff(0)*mv2;\n\t}\n\n\n\t/// \\brief Compute the inner product between two homogeneous multivectors mv1 (grade 1) and mv2 (grade 0). \n\t/// \\tparam the type of value that we manipulate, either float or double or something.\n\t/// \\param mv1 - the first homogeneous multivector of grade 1 represented as an Eigen::VectorXd\n\t/// \\param mv2 - the second homogeneous multivector of grade 0 represented as a Eigen::VectorXd\n\t/// \\param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 1\n\ttemplate<typename T>\n\tvoid inner_1_0(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){\n\t\tmv3 += mv1*mv2.coeff(0);\n\t}\n\n\n\t/// \\brief Compute the inner product between two homogeneous multivectors mv1 (grade 1) and mv2 (grade 1). \n\t/// \\tparam the type of value that we manipulate, either float or double or something.\n\t/// \\param mv1 - the first homogeneous multivector of grade 1 represented as an Eigen::VectorXd\n\t/// \\param mv2 - the second homogeneous multivector of grade 1 represented as a Eigen::VectorXd\n\t/// \\param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 0\n\ttemplate<typename T>\n\tvoid inner_1_1(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){\n\t\tmv3.coeffRef(0) +=  mv1.coeff(0)*mv2.coeff(0) + mv1.coeff(1)*mv2.coeff(1) + mv1.coeff(2)*mv2.coeff(2);\n\t}\n\n\n\t/// \\brief Compute the inner product between two homogeneous multivectors mv1 (grade 1) and mv2 (grade 2). \n\t/// \\tparam the type of value that we manipulate, either float or double or something.\n\t/// \\param mv1 - the first homogeneous multivector of grade 1 represented as an Eigen::VectorXd\n\t/// \\param mv2 - the second homogeneous multivector of grade 2 represented as a Eigen::VectorXd\n\t/// \\param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 1\n\ttemplate<typename T>\n\tvoid inner_1_2(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){\n\t\tmv3.coeffRef(0) += -mv1.coeff(1)*mv2.coeff(0) - mv1.coeff(2)*mv2.coeff(1);\n\t\tmv3.coeffRef(1) +=  mv1.coeff(0)*mv2.coeff(0) - mv1.coeff(2)*mv2.coeff(2);\n\t\tmv3.coeffRef(2) +=  mv1.coeff(0)*mv2.coeff(1) + mv1.coeff(1)*mv2.coeff(2);\n\t}\n\n\n\t/// \\brief Compute the inner product between two homogeneous multivectors mv1 (grade 1) and mv2 (grade 3). \n\t/// \\tparam the type of value that we manipulate, either float or double or something.\n\t/// \\param mv1 - the first homogeneous multivector of grade 1 represented as an Eigen::VectorXd\n\t/// \\param mv2 - the second homogeneous multivector of grade 3 represented as a Eigen::VectorXd\n\t/// \\param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 2\n\ttemplate<typename T>\n\tvoid inner_1_3(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){\n\t\tmv3.coeffRef(0) +=  mv1.coeff(2)*mv2.coeff(0);\n\t\tmv3.coeffRef(1) += -mv1.coeff(1)*mv2.coeff(0);\n\t\tmv3.coeffRef(2) +=  mv1.coeff(0)*mv2.coeff(0);\n\t}\n\n\n\t/// \\brief Compute the inner product between two homogeneous multivectors mv1 (grade 2) and mv2 (grade 0). \n\t/// \\tparam the type of value that we manipulate, either float or double or something.\n\t/// \\param mv1 - the first homogeneous multivector of grade 2 represented as an Eigen::VectorXd\n\t/// \\param mv2 - the second homogeneous multivector of grade 0 represented as a Eigen::VectorXd\n\t/// \\param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 2\n\ttemplate<typename T>\n\tvoid inner_2_0(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){\n\t\tmv3 += mv1*mv2.coeff(0);\n\t}\n\n\n\t/// \\brief Compute the inner product between two homogeneous multivectors mv1 (grade 2) and mv2 (grade 1). \n\t/// \\tparam the type of value that we manipulate, either float or double or something.\n\t/// \\param mv1 - the first homogeneous multivector of grade 2 represented as an Eigen::VectorXd\n\t/// \\param mv2 - the second homogeneous multivector of grade 1 represented as a Eigen::VectorXd\n\t/// \\param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 1\n\ttemplate<typename T>\n\tvoid inner_2_1(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){\n\t\tmv3.coeffRef(0) +=  mv1.coeff(0)*mv2.coeff(1) + mv1.coeff(1)*mv2.coeff(2);\n\t\tmv3.coeffRef(1) += -mv1.coeff(0)*mv2.coeff(0) + mv1.coeff(2)*mv2.coeff(2);\n\t\tmv3.coeffRef(2) += -mv1.coeff(1)*mv2.coeff(0) - mv1.coeff(2)*mv2.coeff(1);\n\t}\n\n\n\t/// \\brief Compute the inner product between two homogeneous multivectors mv1 (grade 2) and mv2 (grade 2). \n\t/// \\tparam the type of value that we manipulate, either float or double or something.\n\t/// \\param mv1 - the first homogeneous multivector of grade 2 represented as an Eigen::VectorXd\n\t/// \\param mv2 - the second homogeneous multivector of grade 2 represented as a Eigen::VectorXd\n\t/// \\param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 0\n\ttemplate<typename T>\n\tvoid inner_2_2(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){\n\t\tmv3.coeffRef(0) += -mv1.coeff(0)*mv2.coeff(0) - mv1.coeff(1)*mv2.coeff(1) - mv1.coeff(2)*mv2.coeff(2);\n\t}\n\n\n\t/// \\brief Compute the inner product between two homogeneous multivectors mv1 (grade 2) and mv2 (grade 3). \n\t/// \\tparam the type of value that we manipulate, either float or double or something.\n\t/// \\param mv1 - the first homogeneous multivector of grade 2 represented as an Eigen::VectorXd\n\t/// \\param mv2 - the second homogeneous multivector of grade 3 represented as a Eigen::VectorXd\n\t/// \\param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 1\n\ttemplate<typename T>\n\tvoid inner_2_3(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){\n\t\tmv3.coeffRef(0) += -mv1.coeff(2)*mv2.coeff(0);\n\t\tmv3.coeffRef(1) +=  mv1.coeff(1)*mv2.coeff(0);\n\t\tmv3.coeffRef(2) += -mv1.coeff(0)*mv2.coeff(0);\n\t}\n\n\n\t/// \\brief Compute the inner product between two homogeneous multivectors mv1 (grade 3) and mv2 (grade 0). \n\t/// \\tparam the type of value that we manipulate, either float or double or something.\n\t/// \\param mv1 - the first homogeneous multivector of grade 3 represented as an Eigen::VectorXd\n\t/// \\param mv2 - the second homogeneous multivector of grade 0 represented as a Eigen::VectorXd\n\t/// \\param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 3\n\ttemplate<typename T>\n\tvoid inner_3_0(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){\n\t\tmv3 += mv1*mv2.coeff(0);\n\t}\n\n\n\t/// \\brief Compute the inner product between two homogeneous multivectors mv1 (grade 3) and mv2 (grade 1). \n\t/// \\tparam the type of value that we manipulate, either float or double or something.\n\t/// \\param mv1 - the first homogeneous multivector of grade 3 represented as an Eigen::VectorXd\n\t/// \\param mv2 - the second homogeneous multivector of grade 1 represented as a Eigen::VectorXd\n\t/// \\param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 2\n\ttemplate<typename T>\n\tvoid inner_3_1(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){\n\t\tmv3.coeffRef(0) +=  mv1.coeff(0)*mv2.coeff(2);\n\t\tmv3.coeffRef(1) += -mv1.coeff(0)*mv2.coeff(1);\n\t\tmv3.coeffRef(2) +=  mv1.coeff(0)*mv2.coeff(0);\n\t}\n\n\n\t/// \\brief Compute the inner product between two homogeneous multivectors mv1 (grade 3) and mv2 (grade 2). \n\t/// \\tparam the type of value that we manipulate, either float or double or something.\n\t/// \\param mv1 - the first homogeneous multivector of grade 3 represented as an Eigen::VectorXd\n\t/// \\param mv2 - the second homogeneous multivector of grade 2 represented as a Eigen::VectorXd\n\t/// \\param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 1\n\ttemplate<typename T>\n\tvoid inner_3_2(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){\n\t\tmv3.coeffRef(0) += -mv1.coeff(0)*mv2.coeff(2);\n\t\tmv3.coeffRef(1) +=  mv1.coeff(0)*mv2.coeff(1);\n\t\tmv3.coeffRef(2) += -mv1.coeff(0)*mv2.coeff(0);\n\t}\n\n\n\t/// \\brief Compute the inner product between two homogeneous multivectors mv1 (grade 3) and mv2 (grade 3). \n\t/// \\tparam the type of value that we manipulate, either float or double or something.\n\t/// \\param mv1 - the first homogeneous multivector of grade 3 represented as an Eigen::VectorXd\n\t/// \\param mv2 - the second homogeneous multivector of grade 3 represented as a Eigen::VectorXd\n\t/// \\param mv3 - the result of mv1.mv2, which is also a homogeneous multivector of grade 0\n\ttemplate<typename T>\n\tvoid inner_3_3(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){\n\t\tmv3.coeffRef(0) += -mv1.coeff(0)*mv2.coeff(0);\n\t}\n\n\n\t\n    template<typename T>\n\tstd::array<std::array<std::function<void(const Eigen::Matrix<T, Eigen::Dynamic, 1> & , const Eigen::Matrix<T, Eigen::Dynamic, 1> & , Eigen::Matrix<T, Eigen::Dynamic, 1>&)>, 4>, 4> innerFunctionsContainer = {{\n\t\t{{inner_0_0<T>,inner_0_1<T>,inner_0_2<T>,inner_0_3<T>}},\n\t\t{{inner_1_0<T>,inner_1_1<T>,inner_1_2<T>,inner_1_3<T>}},\n\t\t{{inner_2_0<T>,inner_2_1<T>,inner_2_2<T>,inner_2_3<T>}},\n\t\t{{inner_3_0<T>,inner_3_1<T>,inner_3_2<T>,inner_3_3<T>}}\n\t}};\n\n}/// End of Namespace\n\n#endif // E3GA_INNER_PRODUCT_EXPLICIT_HPP__", "meta": {"hexsha": "d333b59192e657b9d220272cc991848995db2ef2", "size": 13430, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "gaLib/e3ga/InnerExplicit.hpp", "max_stars_repo_name": "sbreuils/GADigitizedTransformations", "max_stars_repo_head_hexsha": "553a357fe12cd5ee0fa21ffc93d835555ea192f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-12-23T23:29:11.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-24T11:20:41.000Z", "max_issues_repo_path": "gaLib/e3ga/InnerExplicit.hpp", "max_issues_repo_name": "sbreuils/GADigitizedTransformations", "max_issues_repo_head_hexsha": "553a357fe12cd5ee0fa21ffc93d835555ea192f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-12-23T02:07:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-12T08:47:54.000Z", "max_forks_repo_path": "gaLib/e3ga/InnerExplicit.hpp", "max_forks_repo_name": "sbreuils/GADigitizedTransformations", "max_forks_repo_head_hexsha": "553a357fe12cd5ee0fa21ffc93d835555ea192f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 58.3913043478, "max_line_length": 209, "alphanum_fraction": 0.7160089352, "num_tokens": 4076, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6334102705979902, "lm_q1q2_score": 0.49405551401446496}}
{"text": "#pragma once\n\n#include <string>\n#include <Eigen/Geometry>\n\n#include <common_robotics_utilities/math.hpp>\n\nnamespace common_robotics_utilities\n{\nnamespace simple_robot_model_interface\n{\n/// This is basically the absolute minimal robot model interface needed to do\n/// motion planning and forward kinematics. It does not include link geometry.\ntemplate<typename Configuration,\n         typename ConfigAlloc=std::allocator<Configuration>>\nclass SimpleRobotModelInterface\n{\npublic:\n  virtual ~SimpleRobotModelInterface() {}\n\n  /// Clone the current robot model.\n  virtual SimpleRobotModelInterface<Configuration,\n                                    ConfigAlloc>* Clone() const = 0;\n\n  /// Return the current position (i.e. joint values).\n  virtual const Configuration& GetPosition() const = 0;\n\n  /// Set a new position (i.e. joint values) and return the new value.\n  virtual const Configuration& SetPosition(const Configuration& config) = 0;\n\n  /// Get names of links in the robot.\n  virtual std::vector<std::string> GetLinkNames() const = 0;\n\n  /// Get the transform of the link with index @param link_index relative to\n  /// world.\n  virtual Eigen::Isometry3d GetLinkTransform(\n      const int64_t link_index) const = 0;\n\n  /// Get the transform of the link with name @param link_name relative to\n  /// world.\n  virtual Eigen::Isometry3d GetLinkTransform(\n      const std::string& link_name) const = 0;\n\n  /// Get the transforms of all links in the robot relative to world in the same\n  /// order as returned by GetLinkNames().\n  virtual math::VectorIsometry3d GetLinkTransforms() const = 0;\n\n  /// Return a map of <name, transform> for all links in the robot relative to\n  /// the world.\n  virtual math::MapStringIsometry3d GetLinkTransformsMap() const = 0;\n\n  /// Return C-space distance between @param config1 and @param config2.\n  virtual double ComputeConfigurationDistance(\n      const Configuration& config1, const Configuration& config2) const = 0;\n\n  /// Return C-space absolute-value distance between @param config1 and @param\n  /// config2 for each dimension of the C-space separately.\n  Eigen::VectorXd ComputePerDimensionConfigurationDistance(\n      const Configuration& config1, const Configuration& config2) const\n  {\n    return ComputePerDimensionConfigurationSignedDistance(\n        config1, config2).cwiseAbs();\n  }\n\n  /// Return C-space signed distance between @param config1 and @param config2\n  /// for each dimension of the C-space separately.\n  virtual Eigen::VectorXd ComputePerDimensionConfigurationSignedDistance(\n      const Configuration& config1, const Configuration& config2) const = 0;\n\n  /// Return C-space distance between the current configuration and @param\n  /// config.\n  double ComputeConfigurationDistanceTo(const Configuration& config) const\n  {\n    return ComputeConfigurationDistance(GetPosition(), config);\n  }\n\n  /// Return C-space abolsute-value distance between the current configuration\n  /// and @param config for each dimension of the C-space separately.\n  Eigen::VectorXd ComputePerDimensionConfigurationDistanceTo(\n      const Configuration& config) const\n  {\n    return ComputePerDimensionConfigurationDistance(GetPosition(), config);\n  }\n\n  /// Return C-space signed distance between the current configuration and\n  /// @param config for each dimension of the C-space separately.\n  Eigen::VectorXd ComputePerDimensionConfigurationSignedDistanceTo(\n      const Configuration& config) const\n  {\n    return ComputePerDimensionConfigurationSignedDistance(\n        GetPosition(), config);\n  }\n\n  /// Interpolate a configuration of the robot between @param start and @param\n  /// end for the provided ratio @param ratio.\n  virtual Configuration InterpolateBetweenConfigurations(\n      const Configuration& start, const Configuration& end,\n      const double ratio) const = 0;\n\n  /// Average the provided set of configurations @param configurations.\n  virtual Configuration AverageConfigurations(\n      const std::vector<Configuration, ConfigAlloc>& configurations) const = 0;\n\n  /// Compute the translation-only part of the Jacobian at the provided point\n  /// @param link_relative_point on link @param link_name in the robot.\n  virtual Eigen::Matrix<double, 3, Eigen::Dynamic>\n  ComputeLinkPointTranslationJacobian(\n      const std::string& link_name,\n      const Eigen::Vector4d& link_relative_point) const = 0;\n\n  /// Compute the Jacobian at the provided point @param link_relative_point on\n  /// link @param link_name in the robot.\n  virtual Eigen::Matrix<double, 6, Eigen::Dynamic>\n  ComputeLinkPointJacobian(\n      const std::string& link_name,\n      const Eigen::Vector4d& link_relative_point) const = 0;\n};\n}  // namespace simple_robot_model_interface\n}  // namespace common_robotics_utilities\n", "meta": {"hexsha": "a37a7e6e31c6c403f5bcab727f11283396e39c09", "size": 4748, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/common_robotics_utilities/simple_robot_model_interface.hpp", "max_stars_repo_name": "hidmic/common_robotics_utilities", "max_stars_repo_head_hexsha": "b3e10e0e0bfa9a968efdaa57e0a4422d9327bb9c", "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/simple_robot_model_interface.hpp", "max_issues_repo_name": "hidmic/common_robotics_utilities", "max_issues_repo_head_hexsha": "b3e10e0e0bfa9a968efdaa57e0a4422d9327bb9c", "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/simple_robot_model_interface.hpp", "max_forks_repo_name": "hidmic/common_robotics_utilities", "max_forks_repo_head_hexsha": "b3e10e0e0bfa9a968efdaa57e0a4422d9327bb9c", "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": 39.5666666667, "max_line_length": 80, "alphanum_fraction": 0.747683235, "num_tokens": 1027, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825007, "lm_q2_score": 0.6334102567576901, "lm_q1q2_score": 0.4940555096978988}}
{"text": "#ifndef CAMERA_HPP\n#define CAMERA_HPP\n\n#include <cmath>\n#include <Eigen/Core>\n\nnamespace threedimutil\n{\n    class Camera\n    {\n    public:\n        Camera();\n\n        enum class Mode\n        {\n            Rotate,\n            Pan,\n            Zoom,\n            None\n        };\n\n        double& fov() { return m_fov; }\n        double fov() const { return m_fov; }\n\n        Eigen::Vector3d& position() { return m_position; }\n        const Eigen::Vector3d& position() const { return m_position; }\n        Eigen::Vector3d& target() { return m_target; }\n        const Eigen::Vector3d& target() const { return m_target; }\n        Eigen::Vector3d& up() { return m_up; }\n        const Eigen::Vector3d& up() const { return m_up; }\n\n        // Method for obtaining matrices\n        Eigen::Matrix4d GetLookAtMatrix() const;\n\n        // Method for animated visualization\n        void RotateAroundTarget(double theta_in_radian);\n\n        // Methods for cursor interaction\n        void BeginTrackball(int x, int y, Mode mode);\n        void MoveTrackball(int x, int y);\n        void EndTrackball();\n\n    private:\n        double m_fov = M_PI * 45.0 / 180.0;\n\n        Eigen::Vector3d m_position;\n        Eigen::Vector3d m_target;\n        Eigen::Vector3d m_up;\n\n        Mode m_mode;\n        Eigen::Vector2i m_prev_position;\n    };\n}\n\n#endif // CAMERA_HPP\n", "meta": {"hexsha": "38f578c3b2805fa6d1c358f913b418e484545033", "size": 1335, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/three-dim-util/camera.hpp", "max_stars_repo_name": "yuki-koyama/3d-util", "max_stars_repo_head_hexsha": "e3eca11f300d9af6cc5d3eb5636c62f95276de59", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-10-13T15:16:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T06:07:55.000Z", "max_issues_repo_path": "include/three-dim-util/camera.hpp", "max_issues_repo_name": "yuki-koyama/3d-util", "max_issues_repo_head_hexsha": "e3eca11f300d9af6cc5d3eb5636c62f95276de59", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2018-05-14T00:34:56.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-20T13:50:42.000Z", "max_forks_repo_path": "include/three-dim-util/camera.hpp", "max_forks_repo_name": "yuki-koyama/3d-util", "max_forks_repo_head_hexsha": "e3eca11f300d9af6cc5d3eb5636c62f95276de59", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-03-18T07:36:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-04T19:42:33.000Z", "avg_line_length": 23.8392857143, "max_line_length": 70, "alphanum_fraction": 0.5812734082, "num_tokens": 325, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.4940555086167971}}
{"text": "#pragma once\n#include <Eigen/Dense>\n\nnamespace filter_bay\n{\n/*!\nThe movement state consists of a pose and a velocity.\nThe state is stored as a Eigen::Matrix so it can be used directly int the\nsystems model.\nThe pose is stored in the first half of the state, the velocity is stored in\nthe second half.\n*/\ntemplate <size_t DOF>\nstruct MovementState\n{\n  using Pose = Eigen::Matrix<double, DOF, 1>;\n  using Velocity = Eigen::Matrix<double, DOF, 1>;\n  using State = Eigen::Matrix<double, 2 * DOF, 1>;\n  \n  State state;\n\n  Pose get_pose() const\n  {\n    return state.block<DOF, 1>(0, 0);\n  }\n\n  Velocity get_velocity() const\n  {\n    return state.block<DOF, 1>(DOF, 0);\n  }\n\n  void set_pose(Pose pose)\n  {\n    state.block<DOF, 1>(0, 0) = std::move(pose);\n  }\n\n  void set_velocity(Velocity velocity)\n  {\n    state.block<DOF, 1>(DOF, 0) = std::move(velocity);\n  }\n};\n} // namespace filter_bay", "meta": {"hexsha": "b2aa8b28b1acb8fdc0630f9bd9c6b2b28ce113a5", "size": 882, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/filter_bay/model/movement_state.hpp", "max_stars_repo_name": "Tuebel/filter_bay", "max_stars_repo_head_hexsha": "43728be441c3db0f3001b0d31068ce3c3e01d579", "max_stars_repo_licenses": ["MIT"], "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/filter_bay/model/movement_state.hpp", "max_issues_repo_name": "Tuebel/filter_bay", "max_issues_repo_head_hexsha": "43728be441c3db0f3001b0d31068ce3c3e01d579", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-08-10T14:36:16.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-21T10:10:08.000Z", "max_forks_repo_path": "include/filter_bay/model/movement_state.hpp", "max_forks_repo_name": "Tuebel/filter_bay", "max_forks_repo_head_hexsha": "43728be441c3db0f3001b0d31068ce3c3e01d579", "max_forks_repo_licenses": ["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.0, "max_line_length": 76, "alphanum_fraction": 0.6712018141, "num_tokens": 267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.49405549782146135}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n\nnamespace e = Eigen;\n\ntypedef e::Matrix<double, 6, 1> Vec6;\ntypedef e::Matrix<double, 6, 6> Mat6;\ntypedef e::Matrix<double, 3, 1> Vec3;\ntypedef e::Matrix<double, 3, 3> Mat3;\ntypedef e::Matrix<double, 2, 1> Vec2;\ntypedef e::Matrix<double, 2, 2> Mat2;\n", "meta": {"hexsha": "38e1977a49d90004b1a75aded5a7fd9788a53463", "size": 288, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "auv_math/types.hpp", "max_stars_repo_name": "cuauv/software", "max_stars_repo_head_hexsha": "5ad4d52d603f81a7f254f365d9b0fe636d03a260", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 70.0, "max_stars_repo_stars_event_min_datetime": "2015-11-16T18:04:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T09:04:02.000Z", "max_issues_repo_path": "auv_math/types.hpp", "max_issues_repo_name": "cuauv/software", "max_issues_repo_head_hexsha": "5ad4d52d603f81a7f254f365d9b0fe636d03a260", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-08-03T05:13:19.000Z", "max_issues_repo_issues_event_max_datetime": "2016-08-03T06:19:39.000Z", "max_forks_repo_path": "auv_math/types.hpp", "max_forks_repo_name": "cuauv/software", "max_forks_repo_head_hexsha": "5ad4d52d603f81a7f254f365d9b0fe636d03a260", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 34.0, "max_forks_repo_forks_event_min_datetime": "2015-12-15T17:29:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-18T14:15:12.000Z", "avg_line_length": 22.1538461538, "max_line_length": 37, "alphanum_fraction": 0.6875, "num_tokens": 104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8080672320414786, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.4940377388798618}}
{"text": "#include <boost/math/complex/acosh.hpp>\n", "meta": {"hexsha": "fb74239ad9fa105151384299f611bc8a061f5f68", "size": 40, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_complex_acosh.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_complex_acosh.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_complex_acosh.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 20.0, "max_line_length": 39, "alphanum_fraction": 0.775, "num_tokens": 10, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971212, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4940377332280284}}
{"text": "#ifndef nomad__src__matrix__functions__dot_hpp\n#define nomad__src__matrix__functions__dot_hpp\n\n#include <Eigen/Core>\n\n#include <src/var/var.hpp>\n#include <src/var/derived/dot_var_node.hpp>\n\nnamespace nomad {\n  \n  template<typename DerivedA, typename DerivedB>\n  inline typename\n  std::enable_if<\n    is_var<typename Eigen::MatrixBase<DerivedA>::Scalar>::value &&\n    is_var<typename Eigen::MatrixBase<DerivedB>::Scalar>::value &&\n    std::is_same<typename Eigen::MatrixBase<DerivedA>::Scalar,\n                 typename Eigen::MatrixBase<DerivedB>::Scalar>::value,\n    typename Eigen::MatrixBase<DerivedA>::Scalar >::type\n  dot(const Eigen::MatrixBase<DerivedA>& v1,\n      const Eigen::MatrixBase<DerivedB>& v2) {\n    \n    const short autodiff_order = Eigen::MatrixBase<DerivedA>::Scalar::order();\n    const bool strict_smoothness = Eigen::MatrixBase<DerivedA>::Scalar::strict();\n    const bool validate_io = Eigen::MatrixBase<DerivedA>::Scalar::validate();\n\n    eigen_idx_t N = v1.size();\n    const nomad_idx_t n_inputs = static_cast<nomad_idx_t>(2 * N);\n    \n    create_node<dot_var_node<autodiff_order>>(n_inputs);\n    \n    double sum = 0;\n    \n    for (eigen_idx_t n = 0; n < N; ++n)\n      sum += v1(n).first_val() * v2(n).first_val();\n\n    push_dual_numbers<autodiff_order>(sum);\n    \n    for (eigen_idx_t n = 0; n < N; ++n)\n      push_inputs(v1(n).dual_numbers());\n      \n    for (eigen_idx_t n = 0; n < N; ++n)\n      push_inputs(v2(n).dual_numbers());\n    \n    return var<autodiff_order, strict_smoothness, validate_io>(next_node_idx_ - 1);\n    \n  }\n  \n}\n\n#endif\n", "meta": {"hexsha": "05ecdfbd6c54caf2f48acb2bea9eaee38c847b7d", "size": 1569, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/matrix/functions/dot.hpp", "max_stars_repo_name": "stan-dev/nomad", "max_stars_repo_head_hexsha": "a21149ef9f4d53a198e6fdb06cfd0363d3df69e7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2015-12-11T20:06:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T18:59:58.000Z", "max_issues_repo_path": "src/matrix/functions/dot.hpp", "max_issues_repo_name": "stan-dev/nomad", "max_issues_repo_head_hexsha": "a21149ef9f4d53a198e6fdb06cfd0363d3df69e7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-12-15T08:12:01.000Z", "max_issues_repo_issues_event_max_datetime": "2016-07-17T01:36:56.000Z", "max_forks_repo_path": "src/matrix/functions/dot.hpp", "max_forks_repo_name": "stan-dev/nomad", "max_forks_repo_head_hexsha": "a21149ef9f4d53a198e6fdb06cfd0363d3df69e7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-10-13T17:40:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-08T19:17:51.000Z", "avg_line_length": 30.7647058824, "max_line_length": 83, "alphanum_fraction": 0.6787762906, "num_tokens": 437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.49403773322802835}}
{"text": "// Std includes\n#include <cmath>\n#include <iostream>\n#include <vector>\n// Thirdparties includes\n#include <Eigen/Dense>\n// Lib includes\n#include \"fl0w/jhtdb/channel_flow.h\"\n\nconst unsigned int DIM = 3;\n\nusing TypeScalar = double;\nusing TypeVector = Eigen::Matrix<TypeScalar, DIM, 1>;\nusing TypeMatrix = Eigen::Matrix<TypeScalar, DIM, DIM>;\ntemplate<typename... Args>\nusing TypeRef = Eigen::Ref<Args...>;\nusing TypeFlow = fl0w::jhtdb::ChannelFlow<TypeVector, TypeMatrix, TypeRef>;\n\nvoid print(const TypeFlow& flow, const TypeVector& x, const TypeScalar& t) {\n    std::cout << std::endl;\n    std::cout << \"flow.getVelocity(\" << x.transpose() << \", \" << t << \") -> \" << flow.getVelocity(x, t).transpose() << std::endl;\n    std::cout << \"flow.getJacobian(\" << x.transpose() << \", \" << t << \"):\\n -> \" << flow.getJacobian(x, t) << std::endl;\n    std::cout << std::endl;\n}\n\nint main () { \n    TypeFlow flow;\n    TypeVector x;\n    double t;\n    // Init\n    x << 1.0, 0.5, 1.0;\n    t = 1.0;\n    print(flow, x, t);\n}\n", "meta": {"hexsha": "a07f0637885cd700b711462e55730effbaa66470", "size": 1007, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/jhtdb/channel_flow/main.cpp", "max_stars_repo_name": "C0PEP0D/fl0w", "max_stars_repo_head_hexsha": "7e6b1ea0577d73ab98bfa10ae35e827d653cd1f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/jhtdb/channel_flow/main.cpp", "max_issues_repo_name": "C0PEP0D/fl0w", "max_issues_repo_head_hexsha": "7e6b1ea0577d73ab98bfa10ae35e827d653cd1f1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/jhtdb/channel_flow/main.cpp", "max_forks_repo_name": "C0PEP0D/fl0w", "max_forks_repo_head_hexsha": "7e6b1ea0577d73ab98bfa10ae35e827d653cd1f1", "max_forks_repo_licenses": ["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.7714285714, "max_line_length": 129, "alphanum_fraction": 0.6226415094, "num_tokens": 302, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.49403773322802835}}
{"text": "e#include <iostream>\n#include <vector>\n#include <tuple>\n#include <map>\n#include <algorithm>\n#include <cmath>\n#include <boost/multiprecision/cpp_int.hpp>\n\nnamespace mp = boost::multiprecision;\nusing namespace std;\n// \u4f7f\u3048\u308b\u30de\u30c3\u30c1\u68d2\u306e\u6570\u5b57 -> \u4f5c\u308b\u306e\u306b\u5fc5\u8981\u306a\u672c\u6570\nmap<int, int> costs;\n\n// n: \u6b8b\u308a\u672c\u6570 -> ret: (\u6700\u5927\u306e\u672c\u6570, \u4f7f\u3063\u305f\u6570\u5b57\u5c65\u6b74)\nmap<int, int> calc_order_memo{ {0, 1} }; // n->\u6841\u6570: 0\u672c\u3067\u4f7f\u3044\u5207\u3063\u305f\u3068\u304d\u306f\u7d42\u4e86\u6761\u4ef6\u306a\u306e\u30671\u672c\u3068\u3057\u3066\u304a\u304f\nmap<int, mp::cpp_int> calc_num_memo{ {0, 0} }; // n->\u4f7f\u3063\u305f\u6570\u5b57\u3092\u30e1\u30e2\u3057\u3066\u304a\u304d\u305f\u3044\n\ntuple<int, mp::cpp_int> calc_order(int n) {\n    if(calc_order_memo.count(n)) {\n        return { calc_order_memo[n], calc_num_memo[n] };\n    } else {\n        // \u672c\u6570\u3092\u4f7f\u3044\u5207\u3089\u305a\u306b\u4e00\u756a\u30b3\u30b9\u30c8\u306e\u4f4e\u3044\u6570\u5b57\u3092\u9078\u629e\u3059\u308b\n        int max_result = -1; // \u5e30\u3063\u3066\u304d\u305f\u6841\u6570\u3067\u6700\u5927\u306e\u85fb\u3092\n        int select_n = -1; // max_result\u6642\u306b\u3053\u306eCall\u4e0a\u3067\u9078\u3093\u3060\u6570\u5b57\n        mp::cpp_int max_num = -1; // \u5e30\u3063\u3066\u304d\u305f\u95a2\u6570\u306e\u5177\u4f53\u7684\u306a\u6570\u5024\n\n        for(const auto& c: costs) {\n            // cout << \"[DEBUG] n=\" << n << \", c=(\" << c.first << \", \" << c.second << \")\" << endl;\n            // \u3064\u304f\u308c\u306a\u3044\u306e\u3067\u5931\u6557\n            if (c.second > n) {\n                continue; \n            }\n            // \u4f5c\u308c\u308b\u306e\u3067\u518d\u5e30\u3059\u308b\n            auto t = calc_order(n - c.second);\n            auto result = get<0>(t);\n            auto num = get<1>(t);\n\n            if(result > max_result) {\n                max_result = result;\n                select_n = c.first;\n                max_num = num;\n            }\n        }\n        if (max_result == -1) {\n            return { -1, 0 }; // \u3064\u304f\u308c\u306a\u3044\n        } else {\n            calc_order_memo[n] = max_result + 1; // \u6841\u6570\n            calc_num_memo[n] = (max_num * 10) + select_n; // \u4f7f\u3063\u305f\u6570\u5b57+\u3053\u308c\u307e\u3067\u306e\u6841\u3092\u8db3\u3057\u3066\u304a\u304f\n            // cout << \"[DEBUG] ret {\" << calc_order_memo[n] << \", \" << calc_num_memo[n] << \"}\" << endl;\n\n            return { calc_order_memo[n], calc_num_memo[n] }; // \u6841\u6570\u3092\u4e00\u500b\u8db3\u3057\u3066\u8fd4\u3059\n        }\n    }\n}\n// \u5404\u6841\u306e\u6570\u5b57\u3092\u4e26\u3073\u66ff\u3048\u3066\u5927\u304d\u304f\u3059\u308b\nvoid sort_order(int order, mp::cpp_int src, std::string& str){\n    vector<int> arr(order);\n    str = src.str();\n    sort(str.begin(), str.end(), greater<char>());\n}\n\nint main(void) {\n    map<int, int> costs_src;\n    costs_src[1] = 2;\n    costs_src[2] = 5;\n    costs_src[3] = 5;\n    costs_src[4] = 4;\n    costs_src[5] = 5;\n    costs_src[6] = 6;\n    costs_src[7] = 3;\n    costs_src[8] = 7;\n    costs_src[9] = 6;\n\n    int n, m;\n    cin >> n; // \u30de\u30c3\u30c1\u672c\u6570\n    cin >> m; // \u4f7f\u3048\u308b\u6570\u5b57\u306e\u7a2e\u985e\n    for (int i = 0; i < m; ++i) {\n        int an;\n        cin >> an;\n        costs[an] = costs_src[an];\n    }\n    // \u5148\u306b\u540c\u3058\u30b3\u30b9\u30c8\u306e\u6841\u6570\u3067\u3042\u308c\u3070\u5927\u304d\u3044\u65b9\u306b\u9593\u5f15\u3044\u3066\u3057\u307e\u3046\n    for(int i = 1 ; i < 8 ; ++i) {\n        int x = -1;\n        for(int j = costs.size() - 1 ; j >= 0 ; --j) {\n            if(!costs.count(j)) continue;\n            else if(costs[j] == i) {\n                if (x != -1) {\n                    // cout << \"[DEBUG] remove costs:\" << j << endl;\n                    costs.erase(j);\n                } else {\n                    x = j;\n                }\n            }\n        }\n    }\n    // for (const auto &c : costs) {\n    //     cout << c.first << \", \" << c.second << endl;\n    // }\n    // \u4f5c\u308c\u308b\u6700\u5927\u306e\u6841\u6570\u3092\u6c42\u3081\u308b\n    auto r = calc_order(n);\n    auto order = get<0>(r);\n    auto num = get<1>(r);\n    // cout << \"[DEBUG] order: \" << order << \", num:\" << num << endl;\n\n    string dst;\n    sort_order(order, num, dst);\n    cout << dst << endl;\n    return 0;\n}", "meta": {"hexsha": "8f7a3ef116bfd2d9e156f109f5575d07c025dc07", "size": 3176, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "abc118/d/main.cpp", "max_stars_repo_name": "kamiyaowl/atcoder", "max_stars_repo_head_hexsha": "30521be1684e72e75c7ba21312c5f96ae81bf25a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "abc118/d/main.cpp", "max_issues_repo_name": "kamiyaowl/atcoder", "max_issues_repo_head_hexsha": "30521be1684e72e75c7ba21312c5f96ae81bf25a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-20T11:51:59.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-20T11:51:59.000Z", "max_forks_repo_path": "abc118/d/main.cpp", "max_forks_repo_name": "kamiyaowl/atcoder", "max_forks_repo_head_hexsha": "30521be1684e72e75c7ba21312c5f96ae81bf25a", "max_forks_repo_licenses": ["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.8727272727, "max_line_length": 104, "alphanum_fraction": 0.4845717884, "num_tokens": 1158, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672181749422, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.4940377304021114}}
{"text": "// Copyright  (C)  2007  Ruben Smits <ruben dot smits at mech dot kuleuven dot be>\n\n#ifndef KDL_CHAIN_IKSOLVERVEL_PINV_GIVENS_HPP\n#define KDL_CHAIN_IKSOLVERVEL_PINV_GIVENS_HPP\n\n#include \"chainiksolver.hpp\"\n#include \"chainjnttojacsolver.hpp\"\n\n#include <Eigen/Core>\n\nusing namespace Eigen;\n\nnamespace KDL\n{\n    /**\n     * Implementation of a inverse velocity kinematics algorithm based\n     * on the generalize pseudo inverse to calculate the velocity\n     * transformation from Cartesian to joint space of a general\n     * KDL::Chain. It uses a svd-calculation based on householders\n     * rotations.\n     *\n     * @ingroup KinematicFamily\n     */\n    class ChainIkSolverVel_pinv_givens : public ChainIkSolverVel\n    {\n    public:\n\n        /**\n         * Constructor of the solver\n         *\n         * @param chain the chain to calculate the inverse velocity\n         * kinematics for\n         *\n         */\n        explicit ChainIkSolverVel_pinv_givens(const Chain& chain);\n        ~ChainIkSolverVel_pinv_givens();\n\n        virtual int CartToJnt(const JntArray& q_in, const Twist& v_in, JntArray& qdot_out);\n        /**\n         * not (yet) implemented.\n         *\n         */\n        virtual int CartToJnt(const JntArray& /*q_init*/, const FrameVel& /*v_in*/, JntArrayVel& /*q_out*/){return (error = E_NOT_IMPLEMENTED);};\n\n        /// @copydoc KDL::SolverI::updateInternalDataStructures\n        virtual void updateInternalDataStructures();\n\n    private:\n        const Chain& chain;\n        unsigned int nj;\n        ChainJntToJacSolver jnt2jac;\n        Jacobian jac;\n        bool transpose,toggle;\n        unsigned int m,n;\n        MatrixXd jac_eigen,U,V,B;\n        VectorXd S,tempi,UY,SUY,qdot_eigen,v_in_eigen;\n    };\n}\n#endif\n", "meta": {"hexsha": "d6967e42bd0c5ea8ff2d012e1ec3e46d05c963bf", "size": 1730, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/orocos_kinematics_dynamics/orocos_kdl/src/chainiksolvervel_pinv_givens.hpp", "max_stars_repo_name": "matchRos/simulation_multirobots", "max_stars_repo_head_hexsha": "286c5add84d521ad371b2c8961dea872c34e7da2", "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/orocos_kinematics_dynamics/orocos_kdl/src/chainiksolvervel_pinv_givens.hpp", "max_issues_repo_name": "matchRos/simulation_multirobots", "max_issues_repo_head_hexsha": "286c5add84d521ad371b2c8961dea872c34e7da2", "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/orocos_kinematics_dynamics/orocos_kdl/src/chainiksolvervel_pinv_givens.hpp", "max_forks_repo_name": "matchRos/simulation_multirobots", "max_forks_repo_head_hexsha": "286c5add84d521ad371b2c8961dea872c34e7da2", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-04T09:16:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-04T09:16:28.000Z", "avg_line_length": 28.8333333333, "max_line_length": 145, "alphanum_fraction": 0.6554913295, "num_tokens": 445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4940377275761946}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// partition_by_position_parity.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_MPL_DETAIL_PARTITION_BY_POSITION_PARITY_HPP_ER_2010\n#define BOOST_MPL_DETAIL_PARTITION_BY_POSITION_PARITY_HPP_ER_2010\n\n#include <boost/mpl/at.hpp>\n#include <boost/mpl/bind.hpp>\n#include <boost/mpl/inserter.hpp>\n#include <boost/mpl/math/is_even.hpp>\n#include <boost/mpl/transform.hpp>\n#include <boost/mpl/range_c.hpp>\n#include <boost/mpl/size.hpp>\n#include <boost/mpl/vector.hpp>\n#include <boost/mpl/zip_view.hpp>\n#include <boost/mpl/partition.hpp>\n#include <boost/mpl/pair.hpp>\n#include <boost/mpl/placeholders.hpp>\n#include <boost/mpl/push_back.hpp>\n#include <boost/mpl/unpack_args.hpp>\n\nnamespace boost { \nnamespace mpl{\nnamespace detail{\n    \n    // Usage:\n    //     partition_by_position_parity< vector<a,x,b,y> >::type  \n    // equivalent to\n    //     pair< vector<a,b>, vector<x,y> >\n    template<typename T>\n    struct partition_by_position_parity{\n    \n        typedef typename boost::mpl::size<T>::type size_;\n        typedef boost::mpl::range_c<int,0,size_::value> range_;\n        typedef boost::mpl::zip_view< boost::mpl::vector<T, range_> > zip_view_;\n        \n        template<typename Seq>\n        struct fetch : boost::mpl::apply<\n            boost::mpl::unpack_args<boost::mpl::_1>,\n            Seq\n        >{};\n        \n        struct inserter : boost::mpl::inserter<\n           boost::mpl::vector0<>,\n           boost::mpl::push_back<\n                boost::mpl::_1,\n                fetch<boost::mpl::_2>\n            > \n        >{};\n\n        typedef typename boost::mpl::partition<\n            zip_view_\n            , boost::mpl::unpack_args< boost::mpl::is_even<boost::mpl::_2> >,\n            inserter,\n            inserter\n        >::type  type;    \n        \n    };\n    \n}// detail\n}// mpl\n}// boost\n\n#endif\n", "meta": {"hexsha": "b7963d329eaebaca315e927ec7e20324aea7c394", "size": 2304, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "support/boost/mpl/detail/partition_by_position_parity.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": "support/boost/mpl/detail/partition_by_position_parity.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": "support/boost/mpl/detail/partition_by_position_parity.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.3913043478, "max_line_length": 80, "alphanum_fraction": 0.5421006944, "num_tokens": 506, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527631, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4940377275761945}}
{"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_SIGNIFICANTS_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_SIGNIFICANTS_HPP_INCLUDED\n\n#ifndef BOOST_SIMD_NO_INVALIDS\n#include <boost/simd/function/if_else.hpp>\n#include <boost/simd/function/is_invalid.hpp>\n#endif\n#include <boost/simd/function/abs.hpp>\n#include <boost/simd/function/iceil.hpp>\n#include <boost/simd/function/is_eqz.hpp>\n#include <boost/simd/function/is_gtz.hpp>\n#include <boost/simd/function/log10.hpp>\n#include <boost/simd/function/minus.hpp>\n#include <boost/simd/function/nearbyint.hpp>\n#include <boost/simd/function/tenpower.hpp>\n#include <boost/simd/detail/assert_utils.hpp>\n#include <boost/simd/detail/dispatch/function/overload.hpp>\n#include <boost/simd/detail/dispatch/meta/as_integer.hpp>\n#include <boost/assert.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 ( significants_\n                          , (typename A0, typename A1)\n                          , bd::cpu_\n                          , bd::scalar_< bd::floating_<A0>>\n                          , bd::scalar_< bd::integer_<A1>>\n                          )\n  {\n\n    BOOST_FORCEINLINE A0 operator() ( A0 a0, A1 a1) const BOOST_NOEXCEPT\n    {\n      BOOST_ASSERT_MSG( assert_all(is_gtz(a1))\n                      , \"Number of significant digits must be positive\"\n                      );\n      using i_t = bd::as_integer_t<A0>;\n      if (is_eqz(a0)) return a0;\n      i_t exp = a1 - iceil(log10(abs(a0)));\n      A0 fac = tenpower(exp);\n      A0 scaled = bs::nearbyint(a0*fac);\n    #ifndef BOOST_SIMD_NO_INVALIDS\n      return is_invalid(a0) ? a0 : scaled/fac;\n    #else\n      return scaled/fac;\n    #endif\n    }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "dba0c8bb060587d0ec2828f6422a0b2f9e79b474", "size": 2188, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/scalar/function/significants.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/scalar/function/significants.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/significants.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.6615384615, "max_line_length": 100, "alphanum_fraction": 0.6060329068, "num_tokens": 501, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527631, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4940377275761945}}
{"text": "#ifndef WAVE_FIXED_PLANE_HPP\n#define WAVE_FIXED_PLANE_HPP\n\n#include <Eigen/Core>\n#include <ceres/ceres.h>\n#include \"wave/odometry/geometry/assign_jacobians.hpp\"\n\nnamespace wave {\n\ntemplate <typename Scalar, int... states>\nclass FixedPlaneResidual : public ceres::SizedCostFunction<1, 12, states...> {\n public:\n    virtual ~FixedPlaneResidual() {}\n\n    FixedPlaneResidual(const Scalar *pt,\n                  VecE<const MatX*> &jacsw1,\n                  VecE<const MatX*> &jacsw2,\n                  const Scalar &w1,\n                  const Scalar &w2,\n                  const Vec6 &plane)\n            : pt(pt),\n              jacsw1(std::move(jacsw1)),\n              jacsw2(std::move(jacsw2)),\n              w1(w1),\n              w2(w2),\n              plane(plane) { }\n\n    virtual bool Evaluate(double const *const *parameters, double *residuals, double **jacobians) const;\n\n    template<typename Derived>\n    MatX getDerivativeWpT(const Eigen::MatrixBase<Derived> &normal) const;\n\n    template<typename Derived>\n    void setWeight(const Eigen::MatrixBase<Derived> &Weight) {\n        this->weight = Weight;\n    }\n\n private:\n    // updated by evaluation callback\n    const Scalar *pt;\n    const VecE<const MatX*> jacsw1, jacsw2;\n    const Scalar w1, w2;\n    const Vec6 &plane;\n\n    Eigen::Matrix<double, 1, 1> weight = Eigen::Matrix<double, 1, 1>::Identity();\n};\n}\n\n#include \"wave/odometry/geometry/impl/fixed_plane_impl.hpp\"\n\n#endif //WAVE_FIXED_PLANE_HPP\n", "meta": {"hexsha": "67ed7595c8ea40fdd164fc53e3ccb92fae7d060a", "size": 1455, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "wave_odometry/include/wave/odometry/geometry/fixed_plane.hpp", "max_stars_repo_name": "Jebediah/libwave", "max_stars_repo_head_hexsha": "c04998c964f0dc7d414783c6e8cf989a2716ad54", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-06-13T13:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-13T14:54:35.000Z", "max_issues_repo_path": "wave_odometry/include/wave/odometry/geometry/fixed_plane.hpp", "max_issues_repo_name": "Jebediah/libwave", "max_issues_repo_head_hexsha": "c04998c964f0dc7d414783c6e8cf989a2716ad54", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "wave_odometry/include/wave/odometry/geometry/fixed_plane.hpp", "max_forks_repo_name": "Jebediah/libwave", "max_forks_repo_head_hexsha": "c04998c964f0dc7d414783c6e8cf989a2716ad54", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-13T02:27:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-13T02:27:29.000Z", "avg_line_length": 27.9807692308, "max_line_length": 104, "alphanum_fraction": 0.6288659794, "num_tokens": 376, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.808067204308405, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4940377219243606}}
{"text": "//\n// Created by saman on 10/29/20.\n//\n\n#define BOOST_TEST_MAIN\n#define BOOST_TEST_MODULE my_unit_tests\n#define BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n\n\n#include \"../includes/Vec3.h\"\n#include \"../includes/ArrayT.h\"\n\n\nBOOST_AUTO_TEST_SUITE(my_testsuite)\n\n    BOOST_AUTO_TEST_CASE(dot_product)\n    {\n        Vec3 v1(1.0, 2.0, 0.0);\n        Vec3 v2(-1.0, -3.0, 1.0);\n        BOOST_TEST ( v1.Dot(v2) == -7.0);\n    }\n\n    BOOST_AUTO_TEST_CASE(assign_to_scalar)\n    {\n        Vec3 v1(3, 5, 0);\n        double val = 3;\n        v1 = val;\n        BOOST_TEST (v1.x == 3);\n        BOOST_TEST (v1.y == 3);\n    }\n    BOOST_AUTO_TEST_CASE(multiplying_by_scalar)\n    {\n        Vec3 v1(5, 4, 0);\n        double val = 3;\n        v1 *= val;\n        BOOST_TEST (v1.x == 15);\n        BOOST_TEST (v1.y == 12);\n    }\n    BOOST_AUTO_TEST_CASE(multiplying_by_scalar_on_the_line)\n    {\n        Vec3 v1(2.0, 3.0, 0.0);\n        double val = 2.0;\n        Vec3 v2 = v1 * val;\n        BOOST_TEST (v2.x == 4.0);\n        BOOST_TEST (v2.y == 6.0);\n    }\n    \nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "9df6723120d9d9a7a5c9d97f743492f8d2b1607d", "size": 1071, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/tests.cpp", "max_stars_repo_name": "samanseifi/SimpleCloth", "max_stars_repo_head_hexsha": "b0d73176f291ef1df8b2c3d4bf369edafd45451c", "max_stars_repo_licenses": ["MIT"], "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/tests.cpp", "max_issues_repo_name": "samanseifi/SimpleCloth", "max_issues_repo_head_hexsha": "b0d73176f291ef1df8b2c3d4bf369edafd45451c", "max_issues_repo_licenses": ["MIT"], "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/tests.cpp", "max_forks_repo_name": "samanseifi/SimpleCloth", "max_forks_repo_head_hexsha": "b0d73176f291ef1df8b2c3d4bf369edafd45451c", "max_forks_repo_licenses": ["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.42, "max_line_length": 59, "alphanum_fraction": 0.5658263305, "num_tokens": 352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.7310585903489892, "lm_q1q2_score": 0.49402351662873206}}
{"text": "#include <boost/numeric/ublas/io.hpp>\n\n#include \"geometry/homogeneous_transformation.h\"\n\nnamespace gca {\n\n  homogeneous_transform\n  apply(const point d, const homogeneous_transform& t) {\n    return std::make_pair(t.first, t.second + to_vector(d));\n  }\n  \n  point apply(const homogeneous_transform& t, const point p) {\n    return times_3(t.first, p) + from_vector(t.second);\n  }\n  \n  triangular_mesh apply(const homogeneous_transform& t, const triangular_mesh& m) {\n    triangular_mesh rotated =\n      m.apply([t](const point p)\n\t      { return times_3(t.first, p); });\n    triangular_mesh shifted =\n      rotated.apply_to_vertices([t](const point p)\n\t\t\t\t{ return p + from_vector(t.second); });\n    return shifted;\n  }\n\n  boost::optional<homogeneous_transform>\n  mate_planes(const plane a, const plane b, const plane c,\n\t      const plane ap, const plane bp, const plane cp) {\n\n    const ublas::matrix<double> rotation =\n      plane_basis_rotation(a.normal(), b.normal(), c.normal(),\n\t\t\t   -1*ap.normal(), -1*bp.normal(), -1*cp.normal());\n\n    if (!within_eps(determinant(rotation), 1.0, 0.001)) {\n      return boost::none;\n    }\n\n    const ublas::vector<double> displacement =\n      plane_basis_displacement(rotation,\n\t\t\t       ap.normal(), bp.normal(), cp.normal(),\n\t\t\t       ap.pt(), bp.pt(), cp.pt(),\n\t\t\t       a.pt(), b.pt(), c.pt());\n\n    std::pair<const ublas::matrix<double>,\n\t      const ublas::vector<double> > p =\n      std::make_pair(rotation, displacement);\n    return p;\n  }\n\n  std::vector<point> apply(const homogeneous_transform& t,\n\t\t\t   const std::vector<point>& pts) {\n    vector<point> rpts;\n    for (auto p : pts) {\n      rpts.push_back(apply(t, p));\n    }\n    return rpts;\n  }\n\n  labeled_polygon_3 apply(const homogeneous_transform& t,\n\t\t\t  const labeled_polygon_3& p) {\n    vector<point> rotated_verts = apply(t, p.vertices());\n\n    vector<vector<point>> holes;\n    for (auto h : p.holes()) {\n      holes.push_back(apply(t, h));\n    }\n\n    polygon_3 transformed = build_clean_polygon_3(rotated_verts, holes);\n    \n    transformed.correct_winding_order(times_3(t.first, p.normal()));\n\n    point rnorm = transformed.normal();\n    point pnorm = p.normal();\n    point rtnorm = times_3(t.first, p.normal());\n\n    // cout << \"Original normal             = \" << pnorm << endl;\n    // cout << \"Transformed normal              = \" << rnorm << endl;\n    // cout << \"Rotation of original normal = \" << rtnorm << endl;\n    \n    double theta = angle_between(transformed.normal(), rtnorm);\n  \n    DBG_ASSERT(within_eps(theta, 0.0, 0.1));\n\n    return transformed;\n  }\n\n}\n", "meta": {"hexsha": "6a75452fbb399989dc43407073cc0007ebb049c9", "size": 2578, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/geometry/homogeneous_transformation.cpp", "max_stars_repo_name": "dillonhuff/scg", "max_stars_repo_head_hexsha": "21d004ce37c0e0e3650e373726d7e8bac51fffa4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2018-05-10T16:40:38.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-09T06:36:09.000Z", "max_issues_repo_path": "src/geometry/homogeneous_transformation.cpp", "max_issues_repo_name": "dillonhuff/scg", "max_issues_repo_head_hexsha": "21d004ce37c0e0e3650e373726d7e8bac51fffa4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-10-26T13:08:56.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-26T13:08:56.000Z", "max_forks_repo_path": "src/geometry/homogeneous_transformation.cpp", "max_forks_repo_name": "dillonhuff/scg", "max_forks_repo_head_hexsha": "21d004ce37c0e0e3650e373726d7e8bac51fffa4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-11-28T17:36:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-30T14:32:05.000Z", "avg_line_length": 29.2954545455, "max_line_length": 83, "alphanum_fraction": 0.6322730799, "num_tokens": 648, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585903489891, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.4940235118549986}}
{"text": "// Copyright John Maddock 2006.\n// Copyright Paul A. Bristow 2007, 2009\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#include <pch.hpp>\n\n#ifdef _MSC_VER\n# pragma warning (disable : 4996) // POSIX name for this item is deprecated\n# pragma warning (disable : 4224) // nonstandard extension used : formal parameter 'arg' was previously defined as a type\n# pragma warning (disable : 4180) // qualifier applied to function type has no meaning; ignored\n#endif\n\n#include <boost/math/concepts/real_concept.hpp>\n#include <boost/test/test_exec_monitor.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/math/special_functions/beta.hpp>\n#include <boost/math/tools/stats.hpp>\n#include <boost/math/tools/test.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/type_traits/is_floating_point.hpp>\n#include <boost/array.hpp>\n#include \"functor.hpp\"\n\n#include \"test_beta_hooks.hpp\"\n#include \"handle_test_result.hpp\"\n\n//\n// DESCRIPTION:\n// ~~~~~~~~~~~~\n//\n// This file tests the function beta.  There are two sets of tests, spot\n// tests which compare our results with selected values computed\n// using the online special function calculator at \n// functions.wolfram.com, while the bulk of the accuracy tests\n// use values generated with NTL::RR at 1000-bit precision\n// and our generic versions of these functions.\n//\n// Note that when this file is first run on a new platform many of\n// these tests will fail: the default accuracy is 1 epsilon which\n// is too tight for most platforms.  In this situation you will \n// need to cast a human eye over the error rates reported and make\n// a judgement as to whether they are acceptable.  Either way please\n// report the results to the Boost mailing list.  Acceptable rates of\n// error are marked up below as a series of regular expressions that\n// identify the compiler/stdlib/platform/data-type/test-data/test-function\n// along with the maximum expected peek and RMS mean errors for that\n// test.\n//\n\nvoid expected_results()\n{\n   //\n   // Define the max and mean errors expected for\n   // various compilers and platforms.\n   //\n#if LDBL_MANT_DIG == 106\n   // Darwin:\n   add_expected_result(\n      \".*\",                          // compiler\n      \".*\",                          // stdlib\n      \"Mac OS.*\",                    // platform\n      \"(long\\\\s+)?double\",           // test type(s)\n      \"Beta Function: Medium.*\",     // test data group\n      \"boost::math::beta\", 200, 35); // test function\n#endif\n\n   add_expected_result(\n      \".*\",                          // compiler\n      \".*\",                          // stdlib\n      \".*\",                          // platform\n      \"(long\\\\s+)?double\",           // test type(s)\n      \"Beta Function: Small.*\",      // test data group\n      \"boost::math::beta\", 8, 5);    // test function\n   add_expected_result(\n      \".*\",                          // compiler\n      \".*\",                          // stdlib\n      \".*\",                          // platform\n      \"(long\\\\s+)?double\",           // test type(s)\n      \"Beta Function: Medium.*\",     // test data group\n      \"boost::math::beta\", 160, 35); // test function\n   add_expected_result(\n      \".*\",                          // compiler\n      \".*\",                          // stdlib\n      \".*\",                          // platform\n      \"(long\\\\s+)?double\",           // test type(s)\n      \"Beta Function: Divergent.*\",  // test data group\n      \"boost::math::beta\", 30, 6);   // test function\n   add_expected_result(\n      \".*\",                          // compiler\n      \".*\",                          // stdlib\n      \".*\",                          // platform\n      \"real_concept\",                // test type(s)\n      \"Beta Function: Small.*\",      // test data group\n      \"boost::math::beta\", 15, 15);   // test function\n   add_expected_result(\n      \".*\",                          // compiler\n      \".*\",                          // stdlib\n      \".*\",                          // platform\n      \"real_concept\",                // test type(s)\n      \"Beta Function: Medium.*\",     // test data group\n      \"boost::math::beta\", 150, 40); // test function\n   add_expected_result(\n      \".*\",                          // compiler\n      \".*\",                          // stdlib\n      \".*\",                          // platform\n      \"real_concept\",                // test type(s)\n      \"Beta Function: Divergent.*\",  // test data group\n      \"boost::math::beta\", 25, 8);   // test function\n\n   //\n   // Finish off by printing out the compiler/stdlib/platform names,\n   // we do this to make it easier to mark up expected error rates.\n   //\n   std::cout << \"Tests run with \" << BOOST_COMPILER << \", \" \n      << BOOST_STDLIB << \", \" << BOOST_PLATFORM << std::endl;\n}\n\ntemplate <class T>\nvoid do_test_beta(const T& data, const char* type_name, const char* test_name)\n{\n   typedef typename T::value_type row_type;\n   typedef typename row_type::value_type value_type;\n\n   typedef value_type (*pg)(value_type, value_type);\n#if defined(BOOST_MATH_NO_DEDUCED_FUNCTION_POINTERS)\n   pg funcp = boost::math::beta<value_type, value_type>;\n#else\n   pg funcp = boost::math::beta;\n#endif\n\n   boost::math::tools::test_result<value_type> result;\n\n   std::cout << \"Testing \" << test_name << \" with type \" << type_name\n      << \"\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\";\n\n   //\n   // test beta against data:\n   //\n   result = boost::math::tools::test(\n      data, \n      bind_func(funcp, 0, 1), \n      extract_result(2));\n   handle_test_result(result, data[result.worst()], result.worst(), type_name, \"boost::math::beta\", test_name);\n#ifdef TEST_OTHER\n   if(::boost::is_floating_point<value_type>::value){\n      funcp = other::beta;\n      result = boost::math::tools::test(\n         data, \n         bind_func(funcp, 0, 1), \n         extract_result(2));\n      print_test_result(result, data[result.worst()], result.worst(), type_name, \"other::beta\");\n   }\n#endif\n   std::cout << std::endl;\n}\ntemplate <class T>\nvoid test_beta(T, const char* name)\n{\n   //\n   // The actual test data is rather verbose, so it's in a separate file\n   //\n   // The contents are as follows, each row of data contains\n   // three items, input value a, input value b and beta(a, b):\n   // \n#  include \"beta_small_data.ipp\"\n\n   do_test_beta(beta_small_data, name, \"Beta Function: Small Values\");\n\n#  include \"beta_med_data.ipp\"\n\n   do_test_beta(beta_med_data, name, \"Beta Function: Medium Values\");\n\n#  include \"beta_exp_data.ipp\"\n\n   do_test_beta(beta_exp_data, name, \"Beta Function: Divergent Values\");\n}\n\n#undef small // VC++ #defines small char !!!!!!\ntemplate <class T>\nvoid test_spots(T)\n{\n   //\n   // Basic sanity checks, tolerance is 20 epsilon expressed as a percentage:\n   //\n   T tolerance = boost::math::tools::epsilon<T>() * 20 * 100;\n   T small = boost::math::tools::epsilon<T>() / 1024;\n   BOOST_CHECK_CLOSE(::boost::math::beta(static_cast<T>(1), static_cast<T>(1)), static_cast<T>(1), tolerance);\n   BOOST_CHECK_CLOSE(::boost::math::beta(static_cast<T>(1), static_cast<T>(4)), static_cast<T>(0.25), tolerance);\n   BOOST_CHECK_CLOSE(::boost::math::beta(static_cast<T>(4), static_cast<T>(1)), static_cast<T>(0.25), tolerance);\n   BOOST_CHECK_CLOSE(::boost::math::beta(small, static_cast<T>(4)), 1/small, tolerance);\n   BOOST_CHECK_CLOSE(::boost::math::beta(static_cast<T>(4), small), 1/small, tolerance);\n   BOOST_CHECK_CLOSE(::boost::math::beta(static_cast<T>(4), static_cast<T>(20)), static_cast<T>(0.00002823263692828910220214568040654997176736L), tolerance);\n   BOOST_CHECK_CLOSE(::boost::math::beta(static_cast<T>(0.0125L), static_cast<T>(0.000023L)), static_cast<T>(43558.24045647538375006349016083320744662L), tolerance);\n}\n\nint test_main(int, char* [])\n{\n   expected_results();\n   BOOST_MATH_CONTROL_FP;\n   test_spots(0.0F);\n   test_spots(0.0);\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   test_spots(0.0L);\n#if !BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x582))\n   test_spots(boost::math::concepts::real_concept(0.1));\n#endif\n#else\n   std::cout << \"<note>The long double tests have been disabled on this platform \"\n      \"either because the long double overloads of the usual math functions are \"\n      \"not available at all, or because they are too inaccurate for these tests \"\n      \"to pass.</note>\" << std::cout;\n#endif\n\n   test_beta(0.1F, \"float\");\n   test_beta(0.1, \"double\");\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   test_beta(0.1L, \"long double\");\n#ifndef BOOST_MATH_NO_REAL_CONCEPT_TESTS\n#if !BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x582))\n   test_beta(boost::math::concepts::real_concept(0.1), \"real_concept\");\n#endif\n#endif\n#else\n   std::cout << \"<note>The long double tests have been disabled on this platform \"\n      \"either because the long double overloads of the usual math functions are \"\n      \"not available at all, or because they are too inaccurate for these tests \"\n      \"to pass.</note>\" << std::cout;\n#endif\n   return 0;\n}\n\n\n\n", "meta": {"hexsha": "3cde419b0c276c47416986811a68438a3b9a7e65", "size": 9116, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/test/test_beta.cpp", "max_stars_repo_name": "oudream/boost_1_42_0", "max_stars_repo_head_hexsha": "e92227bf374e478030e89876ec353de6eecaeac0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-06-25T23:20:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-14T19:38:34.000Z", "max_issues_repo_path": "libs/math/test/test_beta.cpp", "max_issues_repo_name": "boost-cmake/vintage", "max_issues_repo_head_hexsha": "dcfb7da3177134eddaee6789d6f582259cb0d6ee", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-01-17T10:11:43.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-17T10:11:43.000Z", "max_forks_repo_path": "libs/math/test/test_beta.cpp", "max_forks_repo_name": "boost-cmake/vintage", "max_forks_repo_head_hexsha": "dcfb7da3177134eddaee6789d6f582259cb0d6ee", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-07-26T08:07:09.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-25T23:20:21.000Z", "avg_line_length": 38.4641350211, "max_line_length": 165, "alphanum_fraction": 0.6172663449, "num_tokens": 2286, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.7310585786300048, "lm_q1q2_score": 0.4940235087094572}}
{"text": "//[ Calc1\r\n//  Copyright 2008 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// This is a simple example of how to build an arithmetic expression\r\n// evaluator with placeholders.\r\n\r\n#include <iostream>\r\n#include <boost/proto/core.hpp>\r\n#include <boost/proto/context.hpp>\r\nnamespace proto = boost::proto;\r\nusing proto::_;\r\n\r\ntemplate<int I> struct placeholder {};\r\n\r\n// Define some placeholders\r\nproto::terminal< placeholder< 1 > >::type const _1 = {{}};\r\nproto::terminal< placeholder< 2 > >::type const _2 = {{}};\r\n\r\n// Define a calculator context, for evaluating arithmetic expressions\r\nstruct calculator_context\r\n  : proto::callable_context< calculator_context const >\r\n{\r\n    // The values bound to the placeholders\r\n    double d[2];\r\n\r\n    // The result of evaluating arithmetic expressions\r\n    typedef double result_type;\r\n\r\n    explicit calculator_context(double d1 = 0., double d2 = 0.)\r\n    {\r\n        d[0] = d1;\r\n        d[1] = d2;\r\n    }\r\n\r\n    // Handle the evaluation of the placeholder terminals\r\n    template<int I>\r\n    double operator ()(proto::tag::terminal, placeholder<I>) const\r\n    {\r\n        return d[ I - 1 ];\r\n    }\r\n};\r\n\r\ntemplate<typename Expr>\r\ndouble evaluate( Expr const &expr, double d1 = 0., double d2 = 0. )\r\n{\r\n    // Create a calculator context with d1 and d2 substituted for _1 and _2\r\n    calculator_context const ctx(d1, d2);\r\n\r\n    // Evaluate the calculator expression with the calculator_context\r\n    return proto::eval(expr, ctx);\r\n}\r\n\r\nint main()\r\n{\r\n    // Displays \"5\"\r\n    std::cout << evaluate( _1 + 2.0, 3.0 ) << std::endl;\r\n\r\n    // Displays \"6\"\r\n    std::cout << evaluate( _1 * _2, 3.0, 2.0 ) << std::endl;\r\n\r\n    // Displays \"0.5\"\r\n    std::cout << evaluate( (_1 - _2) / _2, 3.0, 2.0 ) << std::endl;\r\n\r\n    return 0;\r\n}\r\n//]\r\n", "meta": {"hexsha": "6df52d3a60152698ee0ac63edbe1c049eb130221", "size": 1906, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/proto/example/calc1.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/proto/example/calc1.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/proto/example/calc1.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": 27.6231884058, "max_line_length": 76, "alphanum_fraction": 0.6327387198, "num_tokens": 496, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585669110203, "lm_q2_score": 0.6757646075489391, "lm_q1q2_score": 0.4940235055639155}}
{"text": "//---------------------------------------------------------------------------//\r\n// Copyright (c) 2013 Kyle Lutz <kyle.r.lutz@gmail.com>\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://boostorg.github.com/compute for more information.\r\n//---------------------------------------------------------------------------//\r\n\r\n#define BOOST_TEST_MODULE TestNthElement\r\n#include <boost/test/unit_test.hpp>\r\n\r\n#include <boost/compute/command_queue.hpp>\r\n#include <boost/compute/algorithm/copy_n.hpp>\r\n#include <boost/compute/algorithm/is_partitioned.hpp>\r\n#include <boost/compute/algorithm/nth_element.hpp>\r\n#include <boost/compute/algorithm/partition_point.hpp>\r\n#include <boost/compute/container/vector.hpp>\r\n\r\n#include \"check_macros.hpp\"\r\n#include \"context_setup.hpp\"\r\n\r\nBOOST_AUTO_TEST_CASE(nth_element_int)\r\n{\r\n    int data[] = { 9, 15, 1, 4, 9, 9, 4, 15, 12, 1 };\r\n    boost::compute::vector<int> vector(10, context);\r\n\r\n    boost::compute::copy_n(data, 10, vector.begin(), queue);\r\n\r\n    boost::compute::nth_element(\r\n        vector.begin(), vector.begin() + 5, vector.end(), queue\r\n    );\r\n\r\n    BOOST_CHECK_EQUAL(vector[5], 9);\r\n    BOOST_VERIFY(boost::compute::is_partitioned(\r\n        vector.begin(), vector.end(), boost::compute::_1 <= 9, queue\r\n    ));\r\n    BOOST_VERIFY(boost::compute::partition_point(\r\n        vector.begin(), vector.end(), boost::compute::_1 <= 9, queue\r\n    ) > vector.begin() + 5);\r\n\r\n    boost::compute::copy_n(data, 10, vector.begin(), queue);\r\n\r\n    boost::compute::nth_element(\r\n        vector.begin(), vector.end(), vector.end(), queue\r\n    );\r\n    CHECK_RANGE_EQUAL(int, 10, vector, (9, 15, 1, 4, 9, 9, 4, 15, 12, 1));\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(nth_element_median)\r\n{\r\n    int data[] = { 5, 6, 4, 3, 2, 6, 7, 9, 3 };\r\n    boost::compute::vector<int> v(9, context);\r\n    boost::compute::copy_n(data, 9, v.begin(), queue);\r\n\r\n    boost::compute::nth_element(v.begin(), v.begin() + 4, v.end(), queue);\r\n\r\n    BOOST_CHECK_EQUAL(v[4], 5);\r\n    BOOST_VERIFY(boost::compute::is_partitioned(\r\n        v.begin(), v.end(), boost::compute::_1 <= 5, queue\r\n    ));\r\n    BOOST_VERIFY(boost::compute::partition_point(\r\n        v.begin(), v.end(), boost::compute::_1 <= 5, queue\r\n    ) > v.begin() + 4);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(nth_element_second_largest)\r\n{\r\n    int data[] = { 5, 6, 4, 3, 2, 6, 7, 9, 3 };\r\n    boost::compute::vector<int> v(9, context);\r\n    boost::compute::copy_n(data, 9, v.begin(), queue);\r\n\r\n    boost::compute::nth_element(v.begin(), v.begin() + 1, v.end(), queue);\r\n\r\n    BOOST_CHECK_EQUAL(v[1], 3);\r\n    BOOST_VERIFY(boost::compute::is_partitioned(\r\n        v.begin(), v.end(), boost::compute::_1 <= 3, queue\r\n    ));\r\n    BOOST_VERIFY(boost::compute::partition_point(\r\n        v.begin(), v.end(), boost::compute::_1 <= 3, queue\r\n    ) > v.begin() + 1);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(nth_element_comparator)\r\n{\r\n    int data[] = { 9, 15, 1, 4, 9, 9, 4, 15, 12, 1 };\r\n    boost::compute::vector<int> vector(10, context);\r\n\r\n    boost::compute::less<int> less_than;\r\n\r\n    boost::compute::copy_n(data, 10, vector.begin(), queue);\r\n\r\n    boost::compute::nth_element(\r\n        vector.begin(), vector.begin() + 5, vector.end(), less_than, queue\r\n    );\r\n    BOOST_CHECK_EQUAL(vector[5], 9);\r\n    BOOST_VERIFY(boost::compute::is_partitioned(\r\n        vector.begin(), vector.end(), boost::compute::_1 <= 9, queue\r\n    ));\r\n    BOOST_VERIFY(boost::compute::partition_point(\r\n        vector.begin(), vector.end(), boost::compute::_1 <= 9, queue\r\n    ) > vector.begin() + 5);\r\n\r\n    boost::compute::copy_n(data, 10, vector.begin(), queue);\r\n\r\n    boost::compute::nth_element(\r\n        vector.begin(), vector.end(), vector.end(), less_than, queue\r\n    );\r\n    CHECK_RANGE_EQUAL(int, 10, vector, (9, 15, 1, 4, 9, 9, 4, 15, 12, 1));\r\n}\r\n\r\nBOOST_AUTO_TEST_SUITE_END()\r\n", "meta": {"hexsha": "8d4fc134435191849f8dab31660a42b4a873e18c", "size": 3929, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/compute/test/test_nth_element.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": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/compute/test/test_nth_element.cpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-04T18:00:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-04T18:00:00.000Z", "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/compute/test/test_nth_element.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 34.4649122807, "max_line_length": 80, "alphanum_fraction": 0.596589463, "num_tokens": 1086, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.4940235047498198}}
{"text": "#include <stan/math/prim/prob/hmm_marginal_lpdf.hpp>\n#include <boost/math/distributions.hpp>\n#include <boost/random.hpp>\n#include <test/unit/math/test_ad.hpp>\n#include <test/unit/util.hpp>\n#include <gtest/gtest.h>\n#include <limits>\n#include <vector>\n\n/**\n * Wrapper around hmm_marginal_density which passes rho and\n * Gamma without the last element of each column. We recover\n * the last element using the fact each column sums to 1.\n * The purpose of this function is to do finite diff benchmarking,\n * without breaking the simplex constraint.\n */\ntemplate <typename T_omega, typename T_Gamma, typename T_rho>\ninline stan::return_type_t<T_omega, T_Gamma, T_rho> hmm_marginal_test_wrapper(\n    const Eigen::Matrix<T_omega, Eigen::Dynamic, Eigen::Dynamic>& log_omegas,\n    const Eigen::Matrix<T_Gamma, Eigen::Dynamic, Eigen::Dynamic>&\n        Gamma_unconstrained,\n    const std::vector<T_rho>& rho_unconstrained) {\n  using stan::math::row;\n  using stan::math::sum;\n  int n_states = log_omegas.rows();\n\n  Eigen::Matrix<T_Gamma, Eigen::Dynamic, Eigen::Dynamic> Gamma(n_states,\n                                                               n_states);\n  for (int i = 0; i < n_states; i++) {\n    Gamma(i, n_states - 1) = 1 - sum(row(Gamma_unconstrained, i + 1));\n    for (int j = 0; j < n_states - 1; j++) {\n      Gamma(i, j) = Gamma_unconstrained(i, j);\n    }\n  }\n\n  Eigen::Matrix<T_rho, Eigen::Dynamic, 1> rho(n_states);\n  rho(1) = 1 - sum(rho_unconstrained);\n  for (int i = 0; i < n_states - 1; i++)\n    rho(i) = rho_unconstrained[i];\n\n  return stan::math::hmm_marginal_lpdf(log_omegas, Gamma, rho);\n}\n\n/**\n * In the proposed example, the latent state x determines\n * the observational distribution:\n *  0: normal(mu, sigma)\n *  1: normal(-mu, sigma)\n */\ndouble state_lpdf(double y, double abs_mu, double sigma, int state) {\n  int x = state == 0 ? 1 : -1;\n  double chi = (y - x * abs_mu) / sigma;\n  return -0.5 * chi * chi - 0.5 * std::log(2 * M_PI) - std::log(sigma);\n}\n\nclass hmm_marginal_lpdf_test : public ::testing::Test {\n protected:\n  void SetUp() override {\n    n_states_ = 2;\n    p1_init_ = 0.65;\n    gamma1_ = 0.7;\n    gamma2_ = 0.45;\n    n_transitions_ = 10;\n    abs_mu_ = 1;\n    sigma_ = 1;\n\n    Eigen::VectorXd rho(n_states_);\n    rho << p1_init_, 1 - p1_init_;\n    rho_ = rho;\n\n    Eigen::MatrixXd Gamma(n_states_, n_states_);\n    Gamma << gamma1_, 1 - gamma1_, gamma2_, 1 - gamma2_;\n    Gamma_ = Gamma;\n\n    Eigen::VectorXd obs_data(n_transitions_ + 1);\n    obs_data << -0.3315914, -0.1655340, -0.7984021, 0.2364608, -0.4489722,\n        2.1831438, -1.4778675, 0.8717423, -1.0370874, 0.1370296, 1.9786208;\n    obs_data_ = obs_data;\n\n    Eigen::MatrixXd log_omegas(n_states_, n_transitions_ + 1);\n    for (int n = 0; n < n_transitions_ + 1; n++) {\n      log_omegas.col(n)[0] = state_lpdf(obs_data[n], abs_mu_, sigma_, 0);\n      log_omegas.col(n)[1] = state_lpdf(obs_data[n], abs_mu_, sigma_, 1);\n    }\n    log_omegas_ = log_omegas;\n    log_omegas_zero_ = log_omegas.block(0, 0, n_states_, 1);\n\n    std::vector<double> rho_unconstrained(n_states_ - 1);\n    for (int i = 0; i < rho.size() - 1; i++)\n      rho_unconstrained[i] = rho(i);\n    rho_unconstrained_ = rho_unconstrained;\n\n    Gamma_unconstrained_ = Gamma.block(0, 0, n_states_, n_states_ - 1);\n  }\n\n  int n_states_, n_transitions_;\n  double abs_mu_, sigma_, p1_init_, gamma1_, gamma2_;\n\n  Eigen::VectorXd rho_;\n  Eigen::MatrixXd Gamma_;\n  Eigen::VectorXd obs_data_;\n  Eigen::MatrixXd log_omegas_;\n  Eigen::MatrixXd log_omegas_zero_;\n\n  // Construct \"unconstrained\" versions of rho and Gamma, without\n  // the final element which can be determnied using the fact\n  // the columns sum to 1. This allows us to do finite diff tests,\n  // without violating the simplex constraint of rho and Gamma.\n  std::vector<double> rho_unconstrained_;\n  Eigen::MatrixXd Gamma_unconstrained_;\n  stan::test::ad_tolerances tols_;\n};\n\n// For evaluation of the density, the C++ code is benchmarked against\n// a forward algorithm written in R.\n// TODO(charlesm93): Add public repo link with R script.\nTEST_F(hmm_marginal_lpdf_test, ten_transitions) {\n  using stan::math::hmm_marginal_lpdf;\n\n  EXPECT_FLOAT_EQ(-18.37417, hmm_marginal_lpdf(log_omegas_, Gamma_, rho_));\n\n  // Differentiation tests\n  auto hmm_functor = [](const auto& log_omegas, const auto& Gamma_unconstrained,\n                        const auto& rho_unconstrained) {\n    return hmm_marginal_test_wrapper(log_omegas, Gamma_unconstrained,\n                                     rho_unconstrained);\n  };\n\n  stan::test::expect_ad(tols_, hmm_functor, log_omegas_, Gamma_unconstrained_,\n                        rho_unconstrained_);\n}\n\nTEST_F(hmm_marginal_lpdf_test, zero_transitions) {\n  using stan::math::hmm_marginal_lpdf;\n\n  EXPECT_FLOAT_EQ(-1.520827, hmm_marginal_lpdf(log_omegas_zero_, Gamma_, rho_));\n\n  // Differentiation tests\n  auto hmm_functor = [](const auto& log_omegas, const auto& Gamma_unconstrained,\n                        const auto& rho_unconstrained) {\n    return hmm_marginal_test_wrapper(log_omegas, Gamma_unconstrained,\n                                     rho_unconstrained);\n  };\n\n  stan::test::expect_ad(tols_, hmm_functor, log_omegas_zero_,\n                        Gamma_unconstrained_, rho_unconstrained_);\n}\n\nTEST(hmm_marginal_lpdf, one_state) {\n  using stan::math::hmm_marginal_lpdf;\n  int n_states = 1, p1_init = 1, gamma1 = 1, n_transitions = 10, abs_mu = 1,\n      sigma = 1;\n  Eigen::VectorXd rho(n_states);\n  rho << p1_init;\n  Eigen::MatrixXd Gamma(n_states, n_states);\n  Gamma << gamma1;\n  Eigen::VectorXd obs_data(n_transitions + 1);\n  obs_data << -0.9692032, 1.6367754, 1.0339449, 0.9798393, 0.4829358, 2.7508704,\n      0.3122448, 1.8316583, 1.6327319, 1.2097332, 0.4087620;\n  Eigen::MatrixXd log_omegas(n_states, n_transitions + 1);\n  for (int n = 0; n < n_transitions + 1; n++)\n    log_omegas.col(n)[0] = state_lpdf(obs_data[n], abs_mu, sigma, 0);\n\n  EXPECT_FLOAT_EQ(-14.89646, hmm_marginal_lpdf(log_omegas, Gamma, rho));\n\n  // Differentiation tests\n  // In the case where we have one state, Gamma and rho\n  // are fixed (i.e = 1)\n  auto hmm_functor = [](const auto& log_omegas) {\n    Eigen::MatrixXd Gamma(1, 1);\n    Gamma << 1;\n    Eigen::VectorXd rho(1);\n    rho << 1;\n\n    return hmm_marginal_lpdf(log_omegas, Gamma, rho);\n  };\n\n  stan::test::ad_tolerances tols;\n  stan::test::expect_ad(tols, hmm_functor, log_omegas);\n}\n\nTEST(hmm_marginal_lpdf, exceptions) {\n  using Eigen::MatrixXd;\n  using Eigen::VectorXd;\n  using stan::math::hmm_marginal_lpdf;\n\n  int n_states = 2;\n  int n_transitions = 2;\n  MatrixXd log_omegas(n_states, n_transitions + 1);\n  MatrixXd Gamma(n_states, n_states);\n  VectorXd rho(n_states);\n\n  for (int i = 0; i < n_states; i++)\n    for (int j = 0; j < n_transitions + 1; j++)\n      log_omegas(i, j) = 1;\n\n  rho(0) = 0.65;\n  rho(1) = 0.35;\n  Gamma << 0.8, 0.2, 0.6, 0.4;\n\n  // Gamma is not square.\n  MatrixXd Gamma_rec(n_states, n_states + 1);\n  EXPECT_THROW_MSG(\n      hmm_marginal_lpdf(log_omegas, Gamma_rec, rho), std::invalid_argument,\n      \"hmm_marginal_lpdf: Expecting a square matrix; rows of Gamma (2) \"\n      \"and columns of Gamma (3) must match in size\");\n\n  // Gamma has a column that is not a simplex.\n  MatrixXd Gamma_bad = Gamma;\n  Gamma_bad(0, 0) = Gamma(0, 0) + 1;\n  EXPECT_THROW_MSG(hmm_marginal_lpdf(log_omegas, Gamma_bad, rho),\n                   std::domain_error,\n                   \"hmm_marginal_lpdf: Gamma[i, ] is not a valid simplex. \"\n                   \"sum(Gamma[i, ]) = 2, but should be 1\")\n\n  // The size of Gamma is 0, even though there is at least one transition\n  MatrixXd Gamma_empty(0, 0);\n  EXPECT_THROW_MSG(\n      hmm_marginal_lpdf(log_omegas, Gamma_empty, rho), std::invalid_argument,\n      \"hmm_marginal_lpdf: Gamma has size 0, but must have a non-zero size\")\n\n  // The size of Gamma is inconsistent with that of log_omega\n  MatrixXd Gamma_wrong_size(n_states + 1, n_states + 1);\n\n  EXPECT_THROW_MSG(hmm_marginal_lpdf(log_omegas, Gamma_wrong_size, rho),\n                   std::invalid_argument,\n                   \"hmm_marginal_lpdf: Columns of Gamma (3)\"\n                   \" and Rows of log_omegas (2) must match in size\")\n\n  // rho is not a simplex.\n  VectorXd rho_bad = rho;\n  rho_bad(0) = rho(0) + 1;\n  EXPECT_THROW_MSG(hmm_marginal_lpdf(log_omegas, Gamma, rho_bad),\n                   std::domain_error,\n                   \"hmm_marginal_lpdf: rho is not a valid simplex. \"\n                   \"sum(rho) = 2, but should be 1\")\n\n  // The size of rho is inconsistent with that of log_omega\n  VectorXd rho_wrong_size(n_states + 1);\n  EXPECT_THROW_MSG(\n      hmm_marginal_lpdf(log_omegas, Gamma, rho_wrong_size),\n      std::invalid_argument,\n      \"hmm_marginal_lpdf: rho has dimension = 3, expecting dimension = 2;\"\n      \" a function was called with arguments of different scalar,\"\n      \" array, vector, or matrix types, and they were not consistently sized;\"\n      \"  all arguments must be scalars or multidimensional values of\"\n      \" the same shape.\")\n}\n", "meta": {"hexsha": "137a6eb65bcbc29817c15507665a68065dea9b78", "size": 8968, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/prim/prob/hmm_marginal_test.cpp", "max_stars_repo_name": "HaoZeke/math", "max_stars_repo_head_hexsha": "fdf7f70dceed60f3b3f93137c6ac123a457b80a3", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/unit/math/prim/prob/hmm_marginal_test.cpp", "max_issues_repo_name": "HaoZeke/math", "max_issues_repo_head_hexsha": "fdf7f70dceed60f3b3f93137c6ac123a457b80a3", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/unit/math/prim/prob/hmm_marginal_test.cpp", "max_forks_repo_name": "HaoZeke/math", "max_forks_repo_head_hexsha": "fdf7f70dceed60f3b3f93137c6ac123a457b80a3", "max_forks_repo_licenses": ["BSD-3-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.016064257, "max_line_length": 80, "alphanum_fraction": 0.666926851, "num_tokens": 2728, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585669110203, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.49402350079018237}}
{"text": "// Boost.Geometry\n\n// Copyright (c) 2018, Oracle and/or its affiliates.\n\n// Contributed and/or modified by Vissarion Fysikopoulos, on behalf of Oracle\n\n// Licensed under the Boost Software License version 1.0.\n// http://www.boost.org/users/license.html\n\n#ifndef BOOST_GEOMETRY_STRATEGIES_CARTESIAN_LINE_INTERPOLATE_HPP\n#define BOOST_GEOMETRY_STRATEGIES_CARTESIAN_LINE_INTERPOLATE_HPP\n\n#include <boost/geometry/core/assert.hpp>\n#include <boost/geometry/core/coordinate_dimension.hpp>\n#include <boost/geometry/core/coordinate_type.hpp>\n#include <boost/geometry/strategies/line_interpolate.hpp>\n#include <boost/geometry/strategies/cartesian/distance_pythagoras.hpp>\n#include <boost/geometry/util/select_calculation_type.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\nnamespace strategy { namespace line_interpolate\n{\n\n\n/*!\n\\brief Interpolate point on a cartesian segment.\n\\ingroup strategies\n\\tparam CalculationType \\tparam_calculation\n\\tparam DistanceStrategy The underlying point-point distance strategy\n\n\\qbk{\n[heading See also]\n\\* [link geometry.reference.algorithms.line_interpolate.line_interpolate_4_with_strategy line_interpolate (with strategy)]\n}\n\n*/\ntemplate\n<\n    typename CalculationType = void,\n    typename DistanceStrategy = distance::pythagoras<CalculationType>\n>\nclass cartesian\n{\npublic:\n\n    // point-point strategy getters\n    struct distance_pp_strategy\n    {\n        typedef DistanceStrategy type;\n    };\n\n    inline typename distance_pp_strategy::type get_distance_pp_strategy() const\n    {\n        typedef typename distance_pp_strategy::type distance_type;\n        return distance_type();\n    }\n\n    template <typename Point, typename Fraction, typename Distance>\n    inline void apply(Point const& p0,\n                      Point const& p1,\n                      Fraction const& fraction,\n                      Point & p,\n                      Distance const&) const\n    {\n        typedef typename select_calculation_type_alt\n            <\n                CalculationType,\n                Point\n            >::type calc_t;\n\n        typedef model::point\n            <\n                calc_t,\n                geometry::dimension<Point>::value,\n                cs::cartesian\n            > calc_point_t;\n\n        calc_point_t cp0, cp1;\n        geometry::detail::conversion::convert_point_to_point(p0, cp0);\n        geometry::detail::conversion::convert_point_to_point(p1, cp1);\n\n        //segment convex combination: p0*fraction + p1*(1-fraction)\n        Fraction const one_minus_fraction = 1-fraction;\n        for_each_coordinate(cp1, detail::value_operation\n                                 <\n                                    Fraction,\n                                    std::multiplies\n                                 >(fraction));\n        for_each_coordinate(cp0, detail::value_operation\n                                 <\n                                    Fraction,\n                                    std::multiplies\n                                 >(one_minus_fraction));\n        for_each_coordinate(cp1, detail::point_operation\n                                 <\n                                    calc_point_t,\n                                    std::plus\n                                 >(cp0));\n\n        assert_dimension_equal<calc_point_t, Point>();\n        geometry::detail::conversion::convert_point_to_point(cp1, p);\n    }\n};\n\n\n#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\nnamespace services\n{\n\ntemplate <>\nstruct default_strategy<cartesian_tag>\n{\n    typedef strategy::line_interpolate::cartesian<> type;\n};\n\n\n} // namespace services\n#endif // DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\n\n\n}} // namespace strategy::line_interpolate\n\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_STRATEGIES_CARTESIAN_LINE_INTERPOLATE_HPP\n", "meta": {"hexsha": "ffad476ee4203399d095bb1d3c543f8f5053cbad", "size": 3772, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/strategies/cartesian/line_interpolate.hpp", "max_stars_repo_name": "Harshitha91/Tmdb-react-native-node", "max_stars_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/strategies/cartesian/line_interpolate.hpp", "max_issues_repo_name": "Harshitha91/Tmdb-react-native-node", "max_issues_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/strategies/cartesian/line_interpolate.hpp", "max_forks_repo_name": "Harshitha91/Tmdb-react-native-node", "max_forks_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 29.0153846154, "max_line_length": 122, "alphanum_fraction": 0.6338812301, "num_tokens": 728, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795403, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.49402245380361515}}
{"text": "// Copyright John Maddock 2006.\n// Copyright Paul A. Bristow 2007, 2009\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include <boost/math/concepts/real_concept.hpp>\n#define BOOST_TEST_MAIN\n#include <boost/test/unit_test.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/math/special_functions/math_fwd.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/array.hpp>\n#include <boost/tr1/random.hpp>\n#include \"functor.hpp\"\n\n#include \"handle_test_result.hpp\"\n#include \"table_type.hpp\"\n\n#ifndef SC_\n#define SC_(x) static_cast<typename table_type<T>::type>(BOOST_JOIN(x, L))\n#endif\n\ntemplate <class Real, typename T>\nvoid do_test_ellint_rf(T& data, const char* type_name, const char* test)\n{\n   typedef typename T::value_type row_type;\n   typedef Real                   value_type;\n\n   std::cout << \"Testing: \" << test << std::endl;\n\n#if defined(BOOST_MATH_NO_DEDUCED_FUNCTION_POINTERS)\n    value_type (*fp)(value_type, value_type, value_type) = boost::math::ellint_rf<value_type, value_type, value_type>;\n#else\n    value_type (*fp)(value_type, value_type, value_type) = boost::math::ellint_rf;\n#endif\n    boost::math::tools::test_result<value_type> result;\n \n    result = boost::math::tools::test_hetero<Real>(\n      data, \n      bind_func<Real>(fp, 0, 1, 2),\n      extract_result<Real>(3));\n   handle_test_result(result, data[result.worst()], result.worst(), \n      type_name, \"boost::math::ellint_rf\", test);\n\n   std::cout << std::endl;\n\n}\n\ntemplate <class Real, typename T>\nvoid do_test_ellint_rc(T& data, const char* type_name, const char* test)\n{\n   typedef typename T::value_type row_type;\n   typedef Real                   value_type;\n\n   std::cout << \"Testing: \" << test << std::endl;\n\n#if defined(BOOST_MATH_NO_DEDUCED_FUNCTION_POINTERS)\n    value_type (*fp)(value_type, value_type) = boost::math::ellint_rc<value_type, value_type>;\n#else\n    value_type (*fp)(value_type, value_type) = boost::math::ellint_rc;\n#endif\n    boost::math::tools::test_result<value_type> result;\n \n    result = boost::math::tools::test_hetero<Real>(\n      data, \n      bind_func<Real>(fp, 0, 1),\n      extract_result<Real>(2));\n      handle_test_result(result, data[result.worst()], result.worst(), \n      type_name, \"boost::math::ellint_rc\", test);\n\n   std::cout << std::endl;\n\n}\n\ntemplate <class Real, typename T>\nvoid do_test_ellint_rj(T& data, const char* type_name, const char* test)\n{\n   typedef typename T::value_type row_type;\n   typedef Real                   value_type;\n\n   std::cout << \"Testing: \" << test << std::endl;\n\n#if defined(BOOST_MATH_NO_DEDUCED_FUNCTION_POINTERS)\n    value_type (*fp)(value_type, value_type, value_type, value_type) = boost::math::ellint_rj<value_type, value_type, value_type, value_type>;\n#else\n    value_type (*fp)(value_type, value_type, value_type, value_type) = boost::math::ellint_rj;\n#endif\n    boost::math::tools::test_result<value_type> result;\n \n    result = boost::math::tools::test_hetero<Real>(\n      data, \n      bind_func<Real>(fp, 0, 1, 2, 3),\n      extract_result<Real>(4));\n      handle_test_result(result, data[result.worst()], result.worst(), \n      type_name, \"boost::math::ellint_rf\", test);\n\n   std::cout << std::endl;\n\n}\n\ntemplate <class Real, typename T>\nvoid do_test_ellint_rd(T& data, const char* type_name, const char* test)\n{\n   typedef typename T::value_type row_type;\n   typedef Real                   value_type;\n\n   std::cout << \"Testing: \" << test << std::endl;\n\n#if defined(BOOST_MATH_NO_DEDUCED_FUNCTION_POINTERS)\n    value_type (*fp)(value_type, value_type, value_type) = boost::math::ellint_rd<value_type, value_type, value_type>;\n#else\n    value_type (*fp)(value_type, value_type, value_type) = boost::math::ellint_rd;\n#endif\n    boost::math::tools::test_result<value_type> result;\n \n    result = boost::math::tools::test_hetero<Real>(\n      data, \n      bind_func<Real>(fp, 0, 1, 2),\n      extract_result<Real>(3));\n    handle_test_result(result, data[result.worst()], result.worst(), \n      type_name, \"boost::math::ellint_rd\", test);\n\n   std::cout << std::endl;\n\n}\n\ntemplate <typename T>\nvoid test_spots(T, const char* type_name)\n{\n#ifndef TEST_UDT\n   using namespace boost::math;\n   using namespace std;\n   // Spot values from Numerical Computation of Real or Complex \n   // Elliptic Integrals, B. C. Carlson: http://arxiv.org/abs/math.CA/9409227\n   // RF:\n   T tolerance = (std::max)(T(1e-13f), tools::epsilon<T>() * 5) * 100; // Note 5eps expressed as a persentage!!!\n   T eps2 = 2 * tools::epsilon<T>();\n   BOOST_CHECK_CLOSE(ellint_rf(T(1), T(2), T(0)), T(1.3110287771461), tolerance);\n   BOOST_CHECK_CLOSE(ellint_rf(T(0.5), T(1), T(0)), T(1.8540746773014), tolerance);\n   BOOST_CHECK_CLOSE(ellint_rf(T(2), T(3), T(4)), T(0.58408284167715), tolerance);\n   // RC:\n   BOOST_CHECK_CLOSE_FRACTION(ellint_rc(T(0), T(1)/4), boost::math::constants::pi<T>(), eps2);\n   BOOST_CHECK_CLOSE_FRACTION(ellint_rc(T(9)/4, T(2)), log(T(2)), eps2);\n   BOOST_CHECK_CLOSE_FRACTION(ellint_rc(T(1)/4, T(-2)), log(T(2))/3, eps2);\n   // RJ:\n   BOOST_CHECK_CLOSE(ellint_rj(T(0), T(1), T(2), T(3)), T(0.77688623778582), tolerance);\n   BOOST_CHECK_CLOSE(ellint_rj(T(2), T(3), T(4), T(5)), T(0.14297579667157), tolerance);\n   BOOST_CHECK_CLOSE(ellint_rj(T(2), T(3), T(4), T(-0.5)), T(0.24723819703052), tolerance);\n   BOOST_CHECK_CLOSE(ellint_rj(T(2), T(3), T(4), T(-5)), T(-0.12711230042964), tolerance);\n   // RD:\n   BOOST_CHECK_CLOSE(ellint_rd(T(0), T(2), T(1)), T(1.7972103521034), tolerance);\n   BOOST_CHECK_CLOSE(ellint_rd(T(2), T(3), T(4)), T(0.16510527294261), tolerance);\n\n   // Sanity/consistency checks from Numerical Computation of Real or Complex \n   // Elliptic Integrals, B. C. Carlson: http://arxiv.org/abs/math.CA/9409227\n   std::tr1::mt19937 ran;\n   std::tr1::uniform_real<float> ur(0, 1000);\n   T eps40 = 40 * tools::epsilon<T>();\n\n   for(unsigned i = 0; i < 1000; ++i)\n   {\n      T x = ur(ran);\n      T y = ur(ran);\n      T z = ur(ran);\n      T lambda = ur(ran);\n      T mu = x * y / lambda;\n      // RF, eq 49:\n      T s1 = ellint_rf(x+lambda, y+lambda, lambda) + \n         ellint_rf(x + mu, y + mu, mu);\n      T s2 = ellint_rf(x, y, T(0));\n      BOOST_CHECK_CLOSE_FRACTION(s1, s2, eps40);\n      // RC is degenerate case of RF:\n      s1 = ellint_rc(x, y);\n      s2 = ellint_rf(x, y, y);\n      BOOST_CHECK_CLOSE_FRACTION(s1, s2, eps40);\n      // RC, eq 50 (Note have to assume y = x):\n      T mu2 = x * x / lambda;\n      s1 = ellint_rc(lambda, x+lambda) \n         + ellint_rc(mu2, x + mu2);\n      s2 = ellint_rc(T(0), x);\n      BOOST_CHECK_CLOSE_FRACTION(s1, s2, eps40);\n      /*\n      T p = ????; // no closed form for a, b and p???\n      s1 = ellint_rj(x+lambda, y+lambda, lambda, p+lambda)\n         + ellint_rj(x+mu, y+mu, mu, p+mu);\n      s2 = ellint_rj(x, y, T(0), p)\n         - 3 * ellint_rc(a, b);\n      */\n      // RD, eq 53:\n      s1 = ellint_rd(lambda, x+lambda, y+lambda)\n         + ellint_rd(mu, x+mu, y+mu);\n      s2 = ellint_rd(T(0), x, y)\n         - 3 / (y * sqrt(x+y+lambda+mu));\n      BOOST_CHECK_CLOSE_FRACTION(s1, s2, eps40);\n      // RD is degenerate case of RJ:\n      s1 = ellint_rd(x, y, z);\n      s2 = ellint_rj(x, y, z, z);\n      BOOST_CHECK_CLOSE_FRACTION(s1, s2, eps40);\n   }\n#endif\n   //\n   // Now random spot values:\n   //\n#include \"ellint_rf_data.ipp\"\n\n   do_test_ellint_rf<T>(ellint_rf_data, type_name, \"RF: Random data\");\n\n#include \"ellint_rc_data.ipp\"\n\n   do_test_ellint_rc<T>(ellint_rc_data, type_name, \"RC: Random data\");\n\n#include \"ellint_rj_data.ipp\"\n\n   do_test_ellint_rj<T>(ellint_rj_data, type_name, \"RJ: Random data\");\n\n#include \"ellint_rd_data.ipp\"\n\n   do_test_ellint_rd<T>(ellint_rd_data, type_name, \"RD: Random data\");\n}\n\n", "meta": {"hexsha": "e7515215eb2eb31d75d9dfabb96da87d7d8b327e", "size": 7808, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/math/test/test_carlson.hpp", "max_stars_repo_name": "HelloSunyi/boost_1_54_0", "max_stars_repo_head_hexsha": "429fea793612f973d4b7a0e69c5af8156ae2b56e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2015-01-25T05:31:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-02T01:50:31.000Z", "max_issues_repo_path": "libs/math/test/test_carlson.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": "libs/math/test/test_carlson.hpp", "max_forks_repo_name": "graehl/boost", "max_forks_repo_head_hexsha": "37cc4ca77896a86ad10e90dc03e1e825dc0d5492", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-07-28T17:38:16.000Z", "max_forks_repo_forks_event_max_datetime": "2018-04-30T05:37:32.000Z", "avg_line_length": 35.1711711712, "max_line_length": 142, "alphanum_fraction": 0.6547131148, "num_tokens": 2439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795402, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4940224538036151}}
{"text": "// Copyright 2018 The Simons Foundation, Inc. - All Rights Reserved.\n// Copyright 2018 Tom Westerhout\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_SPIN_HPP\n#define NETKET_SPIN_HPP\n\nnamespace netket {\n\n/**\n  Hilbert space for integer or half-integer spins.\n  Notice that here integer values are always used to represent the local quantum\n  numbers, such that for example if total spin is S=3/2, the allowed quantum\n  numbers are -3,-1,1,3, and if S=1 we have -2,0,2.\n*/\n\nclass Spin : public AbstractHilbert {\n  double S_;\n  double totalS_;\n  bool constraintSz_;\n\n  std::vector<double> local_;\n\n  int nstates_;\n\n  int nspins_;\n\n public:\n  explicit Spin(const json &pars) {\n    const int nspins = FieldVal(pars[\"Hilbert\"], \"Nspins\", \"Hilbert\");\n    const double S = FieldVal(pars[\"Hilbert\"], \"S\", \"Hilbert\");\n\n    Init(nspins, S);\n\n    if (FieldExists(pars[\"Hilbert\"], \"TotalSz\")) {\n      SetConstraint(pars[\"Hilbert\"][\"TotalSz\"]);\n    } else {\n      constraintSz_ = false;\n    }\n  }\n\n  void Init(int nspins, double S) {\n    S_ = S;\n    nspins_ = nspins;\n\n    if (S <= 0) {\n      throw InvalidInputError(\"Invalid spin value\");\n    }\n\n    if (std::floor(2. * S) != 2. * S) {\n      throw InvalidInputError(\"Spin value is neither integer nor half integer\");\n    }\n\n    nstates_ = std::floor(2. * S) + 1;\n\n    local_.resize(nstates_);\n\n    int sp = -std::floor(2. * S);\n    for (int i = 0; i < nstates_; i++) {\n      local_[i] = sp;\n      sp += 2;\n    }\n  }\n\n  void SetConstraint(double totalS) {\n    constraintSz_ = true;\n    totalS_ = totalS;\n  }\n\n  bool IsDiscrete() const override { return true; }\n\n  int LocalSize() const override { return nstates_; }\n\n  int Size() const override { return nspins_; }\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    std::uniform_int_distribution<int> distribution(0, nstates_ - 1);\n\n    assert(state.size() == nspins_);\n\n    if (!constraintSz_) {\n      // unconstrained random\n      for (int i = 0; i < state.size(); i++) {\n        state(i) = 2. * (distribution(rgen) - S_);\n      }\n    } else if (S_ == 0.5) {\n      using std::begin;\n      using std::end;\n      // Magnetisation as a count\n      auto const m = static_cast<int>(2 * totalS_);\n      if (std::abs(m) > nspins_) {\n        throw InvalidInputError(\n            \"Cannot fix the total magnetization: 2|M| cannot \"\n            \"exceed Nspins.\");\n      }\n      if ((nspins_ + m) % 2 != 0) {\n        throw InvalidInputError(\n            \"Cannot fix the total magnetization: Nspins + \"\n            \"totalSz must be even.\");\n      }\n      auto const nup = (nspins_ + m) / 2;\n      auto const ndown = (nspins_ - m) / 2;\n      std::fill_n(state.data(), nup, 1.0);\n      std::fill_n(state.data() + nup, ndown, -1.0);\n      std::shuffle(state.data(), state.data() + nspins_, rgen);\n      return;\n    } else {\n      std::vector<int> sites;\n      for (int i = 0; i < nspins_; ++i) sites.push_back(i);\n\n      state.setConstant(-2 * S_);\n      int ss = nspins_;\n\n      for (int i = 0; i < S_ * nspins_ + totalS_; ++i) {\n        std::uniform_int_distribution<int> distribution_ss(0, ss - 1);\n        int s = distribution_ss(rgen);\n        state(sites[s]) += 2;\n        if (state(sites[s]) > 2 * S_ - 1) {\n          sites.erase(sites.begin() + s);\n          ss -= 1;\n        }\n      }\n    }\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() == nspins_);\n\n    int i = 0;\n    for (auto sf : tochange) {\n      v(sf) = newconf[i];\n      i++;\n    }\n  }\n};\n\n}  // namespace netket\n#endif\n", "meta": {"hexsha": "40a4f872d3a02622772075e350c07cac68380a75", "size": 4444, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "NetKet/Hilbert/spins.hpp", "max_stars_repo_name": "stavros11/netket", "max_stars_repo_head_hexsha": "1cec25a4884bdbd2fddb5d24daae627cd89316d8", "max_stars_repo_licenses": ["Apache-2.0"], "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/spins.hpp", "max_issues_repo_name": "stavros11/netket", "max_issues_repo_head_hexsha": "1cec25a4884bdbd2fddb5d24daae627cd89316d8", "max_issues_repo_licenses": ["Apache-2.0"], "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/spins.hpp", "max_forks_repo_name": "stavros11/netket", "max_forks_repo_head_hexsha": "1cec25a4884bdbd2fddb5d24daae627cd89316d8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-10-26T21:05:38.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-26T21:05:38.000Z", "avg_line_length": 27.263803681, "max_line_length": 80, "alphanum_fraction": 0.6091359136, "num_tokens": 1268, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4940224480078644}}
{"text": "/*\n * snake_brain.hpp\n * Copyright (C) 2020 Lucas Costa Campos <rmk236@gmail.com>\n *\n * Distributed under terms of the MIT license.\n */\n\n#ifndef SNAKE_BRAIN_HPP\n#define SNAKE_BRAIN_HPP\n\n#include \"moves.hpp\"\n#include \"location.hpp\"\n#include <Eigen/Eigen>\n#include <iostream>\n#include <cmath>\n\nclass Board;\n\nclass NeuralNetwork\n{\npublic:\n    NeuralNetwork ();\n    NeuralNetwork (const NeuralNetwork& nn);\n    virtual ~NeuralNetwork ();\n\n    void compress();\n\n    Move decide(const Eigen::Matrix<float, 24, 1>& input);\n\n    Eigen::Matrix<float, 18, 24> in;\n    Eigen::Matrix<float, 18, 18> hidden1, hidden2;\n    Eigen::Matrix<float, 4, 18> out;\n\n    Eigen::Matrix<float, 4, 24> final_matrix;\n\n};\n\nclass SnakeBrain\n{\npublic:\n    SnakeBrain ();\n    SnakeBrain (const NeuralNetwork& nn);\n    virtual ~SnakeBrain () {};\n    Move next_move(const Board& board);\n\nprivate:\n    NeuralNetwork nn;\n\n    // The orders are always Left, Right, Down, Up, Down-left, Down-Right, Up-Left, Up-Right;\n    // Each set of three entries will have, in order, (distance, hasFood, hasBody)\n    Eigen::Matrix<float, 24, 1> state;\n};\n\n\n#endif /* !SNAKE_BRAIN_HPP */\n", "meta": {"hexsha": "e16dbad4771a6d3645a16f8898cf0e82a5e3377f", "size": 1137, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "inc/snake_brain.hpp", "max_stars_repo_name": "LucasCampos/snake", "max_stars_repo_head_hexsha": "32912620d3797f029b03f3346622cde517a6d1e6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "inc/snake_brain.hpp", "max_issues_repo_name": "LucasCampos/snake", "max_issues_repo_head_hexsha": "32912620d3797f029b03f3346622cde517a6d1e6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "inc/snake_brain.hpp", "max_forks_repo_name": "LucasCampos/snake", "max_forks_repo_head_hexsha": "32912620d3797f029b03f3346622cde517a6d1e6", "max_forks_repo_licenses": ["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.3035714286, "max_line_length": 93, "alphanum_fraction": 0.6737027265, "num_tokens": 310, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375735, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.4939495310107406}}
{"text": "#include <Eigen/Core>\n#include <boost/python.hpp>\n#include <numpy/arrayobject.h>\n\nnamespace boopy\n{\n  namespace bp = boost::python;\n\n  template <typename SCALAR>  struct NumpyEquivalentType {};\n  template <> struct NumpyEquivalentType<double>  { enum { type_code = NPY_DOUBLE };};\n  template <> struct NumpyEquivalentType<int>     { enum { type_code = NPY_INT    };};\n  template <> struct NumpyEquivalentType<float>   { enum { type_code = NPY_FLOAT  };};\n\n  /* --- TO PYTHON -------------------------------------------------------------- */\n  template< typename MatType >\n  struct EigenMatrix_to_python_matrix\n  {\n    static PyObject* convert(MatType const& mat)\n    {\n      typedef typename MatType::Scalar T;\n      const int R  = mat.rows(), C = mat.cols();\n\n      npy_intp shape[2] = { R,C };\n      PyArrayObject* pyArray = (PyArrayObject*)\n\tPyArray_SimpleNew(2, shape,\n\t\t\t  NumpyEquivalentType<T>::type_code);\n\n      T* pyData = (T*)PyArray_DATA(pyArray);\n      Eigen::Map< Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic,Eigen::RowMajor> > pyMatrix(pyData,R,C);\n      pyMatrix = mat;\n\n      return (PyObject*)pyArray;\n    }\n  };\n  \n  /* --- FROM PYTHON ------------------------------------------------------------ */\n  template<typename MatType>\n  struct EigenMatrix_from_python_array\n  {\n\n    EigenMatrix_from_python_array()\n    {\n      bp::converter::registry\n\t::push_back(&convertible,\n\t\t    &construct,\n\t\t    bp::type_id<MatType>());\n    }\n \n    // Determine if obj_ptr can be converted in a Eigenvec\n    static void* convertible(PyObject* obj_ptr)\n    {\n      typedef typename MatType::Scalar T;\n\n      if (!PyArray_Check(obj_ptr)) return 0;\n\n      std::cout << \"Until here ok.   ndim = \" << PyArray_NDIM(obj_ptr) << \" isvec \" << MatType::IsVectorAtCompileTime << std::endl;\n      if (PyArray_NDIM(obj_ptr) != 2)\n\tif ( (PyArray_NDIM(obj_ptr) !=1) || (! MatType::IsVectorAtCompileTime) )\n\t  return 0;\n      std::cout << \"Until here ok.\" << std::endl;\n\n      if (PyArray_ObjectType(obj_ptr, 0) != NumpyEquivalentType<T>::type_code)\n\treturn 0;\n      \n      if (!(PyArray_FLAGS(obj_ptr) & NPY_ALIGNED))\n\t{\n\t  std::cerr << \"NPY non-aligned matrices are not implemented.\" << std::endl;\n\t  return 0;\n\t}\n      \n      return obj_ptr;\n    }\n \n    // Convert obj_ptr into a Eigenvec\n    static void construct(PyObject* pyObj,\n\t\t\t  bp::converter::rvalue_from_python_stage1_data* memory)\n    {\n      typedef typename MatType::Scalar T;\n      using namespace Eigen;\n\n      std::cout << \"Until here ok. Constructing...\" << std::endl;\n      PyArrayObject * pyArray = reinterpret_cast<PyArrayObject*>(pyObj);\n\n      if ( PyArray_NDIM(pyArray) == 2 )\n      {\n\tint R = MatType::RowsAtCompileTime;\n\tint C = MatType::ColsAtCompileTime;\n\tif (R == Eigen::Dynamic) R = PyArray_DIMS(pyArray)[0];\n\telse\t               assert(PyArray_DIMS(pyArray)[0]==R);\n\t\n\tif (C == Eigen::Dynamic) C = PyArray_DIMS(pyArray)[1];\n\telse\t               assert(PyArray_DIMS(pyArray)[1]==C);\n\t\n\tT* pyData = reinterpret_cast<T*>(PyArray_DATA(pyArray));\n\n\tint itemsize = PyArray_ITEMSIZE(pyArray);\n\tint stride1 = PyArray_STRIDE(pyArray, 0) / itemsize;\n\tint stride2 = PyArray_STRIDE(pyArray, 1) / itemsize;\n\tstd::cout << \"STRIDE = \" << stride1 << \" x \" << stride2 << std::endl;\n\tEigen::Map<MatType,0,Eigen::Stride<Eigen::Dynamic,Eigen::Dynamic> >\n\t  pyMap( pyData, R,C, Eigen::Stride<Eigen::Dynamic,Eigen::Dynamic>(stride2,stride1) );\n\tstd::cout << \"Map = \" << pyMap << std::endl;\n\t\n\tvoid* storage = ((bp::converter::rvalue_from_python_storage<MatType>*)\n\t\t\t (memory))->storage.bytes;\n\tMatType & mat = * new (storage) MatType(R,C);\n\tmat = pyMap; \n\n\tmemory->convertible = storage;\n      }\n    else\n      {\n\tint R = MatType::MaxSizeAtCompileTime, C=1;\n\tif(R==Eigen::Dynamic) R =  PyArray_DIMS(pyArray)[0];\n\telse                  assert(PyArray_DIMS(pyArray)[0]==R);\n\n\tT* pyData = reinterpret_cast<T*>(PyArray_DATA(pyArray));\n\n\tint itemsize = PyArray_ITEMSIZE(pyArray);\n\tint stride = PyArray_STRIDE(pyArray, 0) / itemsize;\n\tEigen::Stride<Eigen::Dynamic,Eigen::Dynamic> s(stride,0);\n\tEigen::Map<MatType,0,Eigen::InnerStride<Eigen::Dynamic> >\n\t  pyMap( pyData, R, 1, Eigen::InnerStride<Eigen::Dynamic>(stride) );\n\tstd::cout << \"Map = \" << pyMap << std::endl;\n\t\n\tvoid* storage = ((bp::converter::rvalue_from_python_storage<MatType>*)\n\t\t\t (memory))->storage.bytes;\n\tMatType & mat = * new (storage) MatType(R,C);\n\tmat = pyMap; \n\n\tmemory->convertible = storage;\n      }\n    }\n  };\n\n\n}\n\nEigen::MatrixXd test()\n{\n  Eigen::MatrixXd mat = Eigen::MatrixXd::Random(3,6);\n  std::cout << \"EigenMAt = \" << mat << std::endl;\n  return mat;\n}\nEigen::VectorXd testVec()\n{\n  Eigen::VectorXd mat = Eigen::VectorXd::Random(6);\n  std::cout << \"EigenVec = \" << mat << std::endl;\n  return mat;\n}\n\nvoid test2( Eigen::MatrixXd mat )\n{\n  std::cout << \"Test2 mat = \" << mat << std::endl;\n}\nvoid test2Vec( Eigen::VectorXd v )\n{\n  std::cout << \"Test2 vec = \" << v << std::endl;\n}\n\nBOOST_PYTHON_MODULE(libeigentemplate)\n{\n  import_array();\n  namespace bp = boost::python;\n  bp::to_python_converter<Eigen::MatrixXd,\n\t\t\t  boopy::EigenMatrix_to_python_matrix<Eigen::MatrixXd> >();\n  boopy::EigenMatrix_from_python_array<Eigen::MatrixXd>();\n\n  bp::to_python_converter<Eigen::VectorXd,\n   \t\t\t  boopy::EigenMatrix_to_python_matrix<Eigen::VectorXd> >();\n  boopy::EigenMatrix_from_python_array<Eigen::VectorXd>();\n\n  bp::def(\"test\", test);\n  bp::def(\"testVec\", testVec);\n  bp::def(\"test2\", test2);\n  bp::def(\"test2Vec\", test2Vec);\n}\n", "meta": {"hexsha": "59194e72448f1fa5c37550020f725c9c8ace86d9", "size": 5448, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittest/alpha/eigentemplate.cpp", "max_stars_repo_name": "wxmerkt/eigenpy", "max_stars_repo_head_hexsha": "15355e6ed0dc555072a6c07ca63e4a406e02a24e", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-05-31T01:30:36.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-24T12:06:39.000Z", "max_issues_repo_path": "unittest/alpha/eigentemplate.cpp", "max_issues_repo_name": "wxmerkt/eigenpy", "max_issues_repo_head_hexsha": "15355e6ed0dc555072a6c07ca63e4a406e02a24e", "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": "unittest/alpha/eigentemplate.cpp", "max_forks_repo_name": "wxmerkt/eigenpy", "max_forks_repo_head_hexsha": "15355e6ed0dc555072a6c07ca63e4a406e02a24e", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.606741573, "max_line_length": 131, "alphanum_fraction": 0.6345447871, "num_tokens": 1520, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375735, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.49394953101074046}}
{"text": "/**\n * \\copyright\n * Copyright (c) 2012-2017, 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/LICENSE.txt\n */\n\n\n#include <limits>\n\n#include <gtest/gtest.h>\n\n#include <Eigen/Eigen>\n\n#include \"BaseLib/ConfigTree.h\"\n\n#include \"MaterialLib/FractureModels/LinearElasticIsotropic.h\"\n#include \"MaterialLib/FractureModels/MohrCoulomb.h\"\n\n#include \"ProcessLib/Parameter/ConstantParameter.h\"\n\nusing namespace MaterialLib::Fracture;\n\nstatic const double eps_sigma = 1e6*1e-5;\nstatic const double eps_C = 1e10*1e-5;\n\nTEST(MaterialLib_Fracture, LinearElasticIsotropic)\n{\n    ProcessLib::ConstantParameter<double> const kn(\"\", 1e11);\n    ProcessLib::ConstantParameter<double> const ks(\"\", 1e9);\n    LinearElasticIsotropic<2>::MaterialProperties const mp{kn, ks};\n\n    LinearElasticIsotropic<2> fractureModel{mp};\n    std::unique_ptr<FractureModelBase<2>::MaterialStateVariables> state(\n        fractureModel.createMaterialStateVariables());\n\n    Eigen::Vector2d w_prev, w, sigma_prev, sigma;\n    Eigen::Matrix2d C;\n\n    ProcessLib::SpatialPosition x;\n    w << -1e-5, -1e-5;\n    fractureModel.computeConstitutiveRelation(0, x, w_prev, w, sigma_prev, sigma, C, *state);\n\n    ASSERT_NEAR(-1e4, sigma[0], eps_sigma);\n    ASSERT_NEAR(-1e6, sigma[1], eps_sigma);\n    ASSERT_NEAR(1e9, C(0,0), eps_C);\n    ASSERT_NEAR(0, C(0,1), eps_C);\n    ASSERT_NEAR(0, C(1,0), eps_C);\n    ASSERT_NEAR(1e11, C(1,1), eps_C);\n\n\n    w << -1e-5, 1e-5;\n    fractureModel.computeConstitutiveRelation(0, x, w_prev, w, sigma_prev, sigma, C, *state);\n\n    ASSERT_NEAR(0, sigma[0], eps_sigma);\n    ASSERT_NEAR(0, sigma[1], eps_sigma);\n    ASSERT_NEAR(0, C(0,0), eps_C);\n    ASSERT_NEAR(0, C(0,1), eps_C);\n    ASSERT_NEAR(0, C(1,0), eps_C);\n    ASSERT_NEAR(0, C(1,1), eps_C);\n}\n\nTEST(MaterialLib_Fracture, MohrCoulomb)\n{\n    ProcessLib::ConstantParameter<double> const kn(\"\", 50e9);\n    ProcessLib::ConstantParameter<double> const ks(\"\", 20e9);\n    ProcessLib::ConstantParameter<double> const phi(\"\", 15);\n    ProcessLib::ConstantParameter<double> const psi(\"\", 5);\n    ProcessLib::ConstantParameter<double> const c(\"\", 3e6);\n    MohrCoulomb<2>::MaterialProperties const mp{kn, ks, phi, psi, c};\n\n    MohrCoulomb<2> fractureModel{mp};\n    std::unique_ptr<FractureModelBase<2>::MaterialStateVariables> state(\n        fractureModel.createMaterialStateVariables());\n\n    Eigen::Vector2d w_prev, w, sigma_prev, sigma;\n    Eigen::Matrix2d C;\n\n    ProcessLib::SpatialPosition x;\n    sigma_prev << -3.46e6, -2e6;\n    w << -1.08e-5, -0.25e-5;\n    fractureModel.computeConstitutiveRelation(0, x, w_prev, w, sigma_prev, sigma, C, *state);\n\n    ASSERT_NEAR(-3.50360e6, sigma[0], eps_sigma);\n    ASSERT_NEAR(-2.16271e6, sigma[1], eps_sigma);\n    ASSERT_NEAR(1.10723e+09, C(0,0), eps_C);\n    ASSERT_NEAR(1.26558e+10, C(0,1), eps_C);\n    ASSERT_NEAR(4.13226e+09, C(1,0), eps_C);\n    ASSERT_NEAR(4.72319e+10, C(1,1), eps_C);\n}\n\n", "meta": {"hexsha": "f7496e31c14ba3a88079f5a10c560b687c3ac4a8", "size": 3018, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tests/MaterialLib/TestFractureModels.cpp", "max_stars_repo_name": "HaibingShao/ogs6_ufz", "max_stars_repo_head_hexsha": "d4acfe7132eaa2010157122da67c7a4579b2ebae", "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": "Tests/MaterialLib/TestFractureModels.cpp", "max_issues_repo_name": "HaibingShao/ogs6_ufz", "max_issues_repo_head_hexsha": "d4acfe7132eaa2010157122da67c7a4579b2ebae", "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": "Tests/MaterialLib/TestFractureModels.cpp", "max_forks_repo_name": "HaibingShao/ogs6_ufz", "max_forks_repo_head_hexsha": "d4acfe7132eaa2010157122da67c7a4579b2ebae", "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": 32.4516129032, "max_line_length": 93, "alphanum_fraction": 0.6885354539, "num_tokens": 953, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4939495310107404}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n\n/*\n Copyright (C) 2001, 2002, 2003 Sadruddin Rejeb\n Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2012 Ferdinando Ametrano\n Copyright (C) 2006 Mark Joshi\n Copyright (C) 2006 StatPro Italia srl\n Copyright (C) 2007 Cristina Duminuco\n Copyright (C) 2007 Chiara Fornarola\n Copyright (C) 2013 Gary Kennedy\n Copyright (C) 2015 Peter Caspers\n Copyright (C) 2017 Klaus Spanderen\n Copyright (C) 2019 Wojciech \u015alusarski\n Copyright (C) 2020 Marcin Rybacki\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n#include <ql/pricingengines/blackformula.hpp>\n#include <ql/math/functional.hpp>\n#include <ql/math/solvers1d/newtonsafe.hpp>\n#include <ql/math/distributions/normaldistribution.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n#if defined(__GNUC__) && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 8)) || (__GNUC__ > 4))\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wunused-local-typedefs\"\n#endif\n#include <boost/math/special_functions/atanh.hpp>\n#if defined(__GNUC__) && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 8)) || (__GNUC__ > 4))\n#pragma GCC diagnostic pop\n#endif\n\n#include <boost/math/special_functions/sign.hpp>\n\nnamespace {\n    void checkParameters(QuantLib::Real strike,\n                         QuantLib::Real forward,\n                         QuantLib::Real displacement)\n    {\n        QL_REQUIRE(displacement >= 0.0, \"displacement (\"\n                                            << displacement\n                                            << \") must be non-negative\");\n        QL_REQUIRE(strike + displacement >= 0.0,\n                   \"strike + displacement (\" << strike << \" + \" << displacement\n                                             << \") must be non-negative\");\n        QL_REQUIRE(forward + displacement > 0.0, \"forward + displacement (\"\n                                                     << forward << \" + \"\n                                                     << displacement\n                                                     << \") must be positive\");\n    }\n}\n\nnamespace QuantLib {\n\n    Real blackFormula(Option::Type optionType,\n                      Real strike,\n                      Real forward,\n                      Real stdDev,\n                      Real discount,\n                      Real displacement)\n    {\n        checkParameters(strike, forward, displacement);\n        QL_REQUIRE(stdDev>=0.0,\n                   \"stdDev (\" << stdDev << \") must be non-negative\");\n        QL_REQUIRE(discount>0.0,\n                   \"discount (\" << discount << \") must be positive\");\n\n        auto sign = Integer(optionType);\n\n        if (stdDev == 0.0)\n            return std::max((forward-strike) * sign, Real(0.0)) * discount;\n\n        forward = forward + displacement;\n        strike = strike + displacement;\n\n        // since displacement is non-negative strike==0 iff displacement==0\n        // so returning forward*discount is OK\n        if (strike==0.0)\n            return (optionType==Option::Call ? forward*discount : 0.0);\n\n        Real d1 = std::log(forward/strike)/stdDev + 0.5*stdDev;\n        Real d2 = d1 - stdDev;\n        CumulativeNormalDistribution phi;\n        Real nd1 = phi(sign * d1);\n        Real nd2 = phi(sign * d2);\n        Real result = discount * sign * (forward*nd1 - strike*nd2);\n        QL_ENSURE(result>=0.0,\n                  \"negative value (\" << result << \") for \" <<\n                  stdDev << \" stdDev, \" <<\n                  optionType << \" option, \" <<\n                  strike << \" strike , \" <<\n                  forward << \" forward\");\n        return result;\n    }\n\n    Real blackFormula(const ext::shared_ptr<PlainVanillaPayoff>& payoff,\n                      Real forward,\n                      Real stdDev,\n                      Real discount,\n                      Real displacement) {\n        return blackFormula(payoff->optionType(),\n            payoff->strike(), forward, stdDev, discount, displacement);\n    }\n\n    Real blackFormulaForwardDerivative(Option::Type optionType,\n                                       Real strike,\n                                       Real forward,\n                                       Real stdDev,\n                                       Real discount,\n                                       Real displacement)\n    {\n        checkParameters(strike, forward, displacement);\n        QL_REQUIRE(stdDev>=0.0,\n                   \"stdDev (\" << stdDev << \") must be non-negative\");\n        QL_REQUIRE(discount>0.0,\n                   \"discount (\" << discount << \") must be positive\");\n\n        auto sign = Integer(optionType);\n\n        if (stdDev == 0.0)\n            return sign * std::max(1.0 * boost::math::sign((forward - strike) * sign), 0.0) * discount;\n\n        forward = forward + displacement;\n        strike = strike + displacement;\n\n        if (strike == 0.0)\n            return (optionType == Option::Call ? discount : 0.0);\n\n        Real d1 = std::log(forward/strike)/stdDev + 0.5*stdDev;\n        CumulativeNormalDistribution phi;\n        return sign * phi(sign * d1) * discount;\n    }\n\n    Real blackFormulaForwardDerivative(const ext::shared_ptr<PlainVanillaPayoff>& payoff,\n                                       Real forward,\n                                       Real stdDev,\n                                       Real discount,\n                                       Real displacement) \n    {\n        return blackFormulaForwardDerivative(payoff->optionType(),\n            payoff->strike(), forward, stdDev, discount, displacement);\n    }\n\n    Real blackFormulaImpliedStdDevApproximation(Option::Type optionType,\n                                                Real strike,\n                                                Real forward,\n                                                Real blackPrice,\n                                                Real discount,\n                                                Real displacement)\n    {\n        checkParameters(strike, forward, displacement);\n        QL_REQUIRE(blackPrice>=0.0,\n                   \"blackPrice (\" << blackPrice << \") must be non-negative\");\n        QL_REQUIRE(discount>0.0,\n                   \"discount (\" << discount << \") must be positive\");\n\n        Real stdDev;\n        forward = forward + displacement;\n        strike = strike + displacement;\n        if (strike==forward)\n            // Brenner-Subrahmanyan (1988) and Feinstein (1988) ATM approx.\n            stdDev = blackPrice/discount*std::sqrt(2.0 * M_PI)/forward;\n        else {\n            // Corrado and Miller extended moneyness approximation\n            Real moneynessDelta = Integer(optionType) * (forward-strike);\n            Real moneynessDelta_2 = moneynessDelta/2.0;\n            Real temp = blackPrice/discount - moneynessDelta_2;\n            Real moneynessDelta_PI = moneynessDelta*moneynessDelta/M_PI;\n            Real temp2 = temp*temp-moneynessDelta_PI;\n            if (temp2<0.0) // approximation breaks down, 2 alternatives:\n                // 1. zero it\n                temp2=0.0;\n                // 2. Manaster-Koehler (1982) efficient Newton-Raphson seed\n                //return std::fabs(std::log(forward/strike))*std::sqrt(2.0);\n            temp2 = std::sqrt(temp2);\n            temp += temp2;\n            temp *= std::sqrt(2.0 * M_PI);\n            stdDev = temp/(forward+strike);\n        }\n        QL_ENSURE(stdDev>=0.0,\n                  \"stdDev (\" << stdDev << \") must be non-negative\");\n        return stdDev;\n    }\n\n    Real blackFormulaImpliedStdDevApproximation(\n                      const ext::shared_ptr<PlainVanillaPayoff>& payoff,\n                      Real forward,\n                      Real blackPrice,\n                      Real discount,\n                      Real displacement) {\n        return blackFormulaImpliedStdDevApproximation(payoff->optionType(),\n            payoff->strike(), forward, blackPrice, discount, displacement);\n    }\n\n    Real blackFormulaImpliedStdDevChambers(Option::Type optionType,\n                                                Real strike,\n                                                Real forward,\n                                                Real blackPrice,\n                                                Real blackAtmPrice,\n                                                Real discount,\n                                                Real displacement) {\n        checkParameters(strike, forward, displacement);\n        QL_REQUIRE(blackPrice >= 0.0,\n                   \"blackPrice (\" << blackPrice << \") must be non-negative\");\n        QL_REQUIRE(blackAtmPrice >= 0.0, \"blackAtmPrice (\"\n                                             << blackAtmPrice\n                                             << \") must be non-negative\");\n        QL_REQUIRE(discount > 0.0, \"discount (\" << discount\n                                                << \") must be positive\");\n\n        Real stdDev;\n\n        forward = forward + displacement;\n        strike = strike + displacement;\n        blackPrice /= discount;\n        blackAtmPrice /= discount;\n\n        Real s0 = M_SQRT2 * M_SQRTPI * blackAtmPrice /\n                  forward; // Brenner-Subrahmanyam formula\n        Real priceAtmVol =\n            blackFormula(optionType, strike, forward, s0, 1.0, 0.0);\n        Real dc = blackPrice - priceAtmVol;\n\n        if (close(dc, 0.0)) {\n            stdDev = s0;\n        } else {\n            Real d1 =\n                blackFormulaStdDevDerivative(strike, forward, s0, 1.0, 0.0);\n            Real d2 = blackFormulaStdDevSecondDerivative(strike, forward, s0,\n                                                         1.0, 0.0);\n            Real ds = 0.0;\n            Real tmp = d1 * d1 + 2.0 * d2 * dc;\n            if (std::fabs(d2) > 1E-10 && tmp >= 0.0)\n                ds = (-d1 + std::sqrt(tmp)) / d2; // second order approximation\n            else\n                if(std::fabs(d1) > 1E-10)\n                    ds = dc / d1; // first order approximation\n            stdDev = s0 + ds;\n        }\n\n        QL_ENSURE(stdDev >= 0.0, \"stdDev (\" << stdDev\n                                            << \") must be non-negative\");\n        return stdDev;\n    }\n\n    Real blackFormulaImpliedStdDevChambers(\n        const ext::shared_ptr<PlainVanillaPayoff> &payoff,\n        Real forward,\n        Real blackPrice,\n        Real blackAtmPrice,\n        Real discount,\n        Real displacement) {\n        return blackFormulaImpliedStdDevChambers(\n            payoff->optionType(), payoff->strike(), forward, blackPrice,\n            blackAtmPrice, discount, displacement);\n    }\n\n    namespace {\n        Real Af(Real x) {\n            return 0.5*(1.0+boost::math::sign(x)\n                *std::sqrt(1.0-std::exp(-M_2_PI*x*x)));\n        }\n    }\n\n    Real blackFormulaImpliedStdDevApproximationRS(\n        Option::Type type, Real K, Real F,\n        Real marketValue, Real df, Real displacement) {\n\n        checkParameters(K, F, displacement);\n        QL_REQUIRE(marketValue >= 0.0,\n                   \"blackPrice (\" << marketValue << \") must be non-negative\");\n        QL_REQUIRE(df > 0.0, \"discount (\" << df << \") must be positive\");\n\n        F = F + displacement;\n        K = K + displacement;\n\n        const Real ey = F/K;\n        const Real ey2 = ey*ey;\n        const Real y = std::log(ey);\n        const Real alpha = marketValue/(K*df);\n        const Real R = 2*alpha + ((type == Option::Call) ? -ey+1.0 : ey-1.0);\n        const Real R2 = R*R;\n\n        const Real a = std::exp((1.0-M_2_PI)*y);\n        const Real A = square<Real>()(a - 1.0/a);\n        const Real b = std::exp(M_2_PI*y);\n        const Real B = 4.0*(b + 1/b)\n            - 2*K/F*(a + 1.0/a)*(ey2 + 1 - R2);\n        const Real C = (R2-square<Real>()(ey-1))*(square<Real>()(ey+1)-R2)/ey2;\n\n        const Real beta = 2*C/(B+std::sqrt(B*B+4*A*C));\n        const Real gamma = -M_PI_2*std::log(beta);\n\n        if (y >= 0.0) {\n            const Real M0 = K*df*(\n                (type == Option::Call) ? ey*Af(std::sqrt(2*y)) - 0.5\n                                       : 0.5-ey*Af(-std::sqrt(2*y)));\n\n            if (marketValue <= M0)\n                return std::sqrt(gamma+y)-std::sqrt(gamma-y);\n            else\n                return std::sqrt(gamma+y)+std::sqrt(gamma-y);\n        }\n        else {\n            const Real M0 = K*df*(\n                (type == Option::Call) ? 0.5*ey - Af(-std::sqrt(-2*y))\n                                       : Af(std::sqrt(-2*y)) - 0.5*ey);\n\n            if (marketValue <= M0)\n                return std::sqrt(gamma-y)-std::sqrt(gamma+y);\n            else\n                return std::sqrt(gamma+y)+std::sqrt(gamma-y);\n        }\n    }\n\n    Real blackFormulaImpliedStdDevApproximationRS(\n        const ext::shared_ptr<PlainVanillaPayoff> &payoff,\n        Real F, Real marketValue,\n        Real df, Real displacement) {\n\n        return blackFormulaImpliedStdDevApproximationRS(\n            payoff->optionType(), payoff->strike(),\n            F, marketValue, df, displacement);\n    }\n\n    class BlackImpliedStdDevHelper {\n      public:\n        BlackImpliedStdDevHelper(Option::Type optionType,\n                                 Real strike,\n                                 Real forward,\n                                 Real undiscountedBlackPrice,\n                                 Real displacement = 0.0)\n        : halfOptionType_(0.5 * Integer(optionType)),\n          signedStrike_(Integer(optionType) * (strike+displacement)),\n          signedForward_(Integer(optionType) * (forward+displacement)),\n          undiscountedBlackPrice_(undiscountedBlackPrice)\n        {\n            checkParameters(strike, forward, displacement);\n            QL_REQUIRE(undiscountedBlackPrice>=0.0,\n                       \"undiscounted Black price (\" <<\n                       undiscountedBlackPrice << \") must be non-negative\");\n            signedMoneyness_ = Integer(optionType) * std::log((forward+displacement)/(strike+displacement));\n        }\n\n        Real operator()(Real stdDev) const {\n            #if defined(QL_EXTRA_SAFETY_CHECKS)\n            QL_REQUIRE(stdDev>=0.0,\n                       \"stdDev (\" << stdDev << \") must be non-negative\");\n            #endif\n            if (stdDev==0.0)\n                return std::max(signedForward_-signedStrike_, Real(0.0))\n                                                   - undiscountedBlackPrice_;\n            Real temp = halfOptionType_*stdDev;\n            Real d = signedMoneyness_/stdDev;\n            Real signedD1 = d + temp;\n            Real signedD2 = d - temp;\n            Real result = signedForward_ * N_(signedD1)\n                - signedStrike_ * N_(signedD2);\n            // numerical inaccuracies can yield a negative answer\n            return std::max(Real(0.0), result) - undiscountedBlackPrice_;\n        }\n        Real derivative(Real stdDev) const {\n            #if defined(QL_EXTRA_SAFETY_CHECKS)\n            QL_REQUIRE(stdDev>=0.0,\n                       \"stdDev (\" << stdDev << \") must be non-negative\");\n            #endif\n            Real signedD1 = signedMoneyness_/stdDev + halfOptionType_*stdDev;\n            return signedForward_*N_.derivative(signedD1);\n        }\n      private:\n        Real halfOptionType_;\n        Real signedStrike_, signedForward_;\n        Real undiscountedBlackPrice_, signedMoneyness_;\n        CumulativeNormalDistribution N_;\n    };\n\n\n    Real blackFormulaImpliedStdDev(Option::Type optionType,\n                                   Real strike,\n                                   Real forward,\n                                   Real blackPrice,\n                                   Real discount,\n                                   Real displacement,\n                                   Real guess,\n                                   Real accuracy,\n                                   Natural maxIterations)\n    {\n        checkParameters(strike, forward, displacement);\n\n        QL_REQUIRE(discount>0.0,\n                   \"discount (\" << discount << \") must be positive\");\n\n        QL_REQUIRE(blackPrice>=0.0,\n                   \"option price (\" << blackPrice << \") must be non-negative\");\n        // check the price of the \"other\" option implied by put-call paity\n        Real otherOptionPrice = blackPrice - Integer(optionType) * (forward-strike)*discount;\n        QL_REQUIRE(otherOptionPrice>=0.0,\n                   \"negative \" << Option::Type(-1*optionType) <<\n                   \" price (\" << otherOptionPrice <<\n                   \") implied by put-call parity. No solution exists for \" <<\n                   optionType << \" strike \" << strike <<\n                   \", forward \" << forward <<\n                   \", price \" << blackPrice <<\n                   \", deflator \" << discount);\n\n        // solve for the out-of-the-money option which has\n        // greater vega/price ratio, i.e.\n        // it is numerically more robust for implied vol calculations\n        if (optionType==Option::Put && strike>forward) {\n            optionType = Option::Call;\n            blackPrice = otherOptionPrice;\n        }\n        if (optionType==Option::Call && strike<forward) {\n            optionType = Option::Put;\n            blackPrice = otherOptionPrice;\n        }\n\n        strike = strike + displacement;\n        forward = forward + displacement;\n\n        if (guess==Null<Real>())\n            guess = blackFormulaImpliedStdDevApproximation(\n                optionType, strike, forward, blackPrice, discount, displacement);\n        else\n            QL_REQUIRE(guess>=0.0,\n                       \"stdDev guess (\" << guess << \") must be non-negative\");\n        BlackImpliedStdDevHelper f(optionType, strike, forward,\n                                   blackPrice/discount);\n        NewtonSafe solver;\n        solver.setMaxEvaluations(maxIterations);\n        Real minSdtDev = 0.0, maxStdDev = 24.0; // 24 = 300% * sqrt(60)\n        Real stdDev = solver.solve(f, accuracy, guess, minSdtDev, maxStdDev);\n        QL_ENSURE(stdDev>=0.0,\n                  \"stdDev (\" << stdDev << \") must be non-negative\");\n        return stdDev;\n    }\n\n    Real blackFormulaImpliedStdDev(\n                        const ext::shared_ptr<PlainVanillaPayoff>& payoff,\n                        Real forward,\n                        Real blackPrice,\n                        Real discount,\n                        Real displacement,\n                        Real guess,\n                        Real accuracy,\n                        Natural maxIterations) {\n        return blackFormulaImpliedStdDev(payoff->optionType(), payoff->strike(),\n            forward, blackPrice, discount, displacement, guess, accuracy, maxIterations);\n    }\n\n\n    namespace {\n        Real Np(Real x, Real v) {\n            return CumulativeNormalDistribution()(x/v + 0.5*v);\n        }\n        Real Nm(Real x, Real v) {\n            return std::exp(-x)*CumulativeNormalDistribution()(x/v - 0.5*v);\n        }\n        Real phi(Real x, Real v) {\n            const Real ax = 2*std::fabs(x);\n            const Real v2 = v*v;\n            return (v2-ax)/(v2+ax);\n        }\n        Real F(Real v, Real x, Real cs, Real w) {\n            return cs+Nm(x,v)+w*Np(x,v);\n        }\n        Real G(Real v, Real x, Real cs, Real w) {\n            const Real q = F(v,x,cs,w)/(1+w);\n\n            // Acklam's inverse w/o Halley's refinement step\n            // does not provide enough accuracy. But both together are\n            // slower than the boost replacement.\n            const Real k = MaddockInverseCumulativeNormal()(q);\n\n            return k + std::sqrt(k*k + 2*std::fabs(x));\n        }\n    }\n\n    Real blackFormulaImpliedStdDevLiRS(\n        Option::Type optionType,\n        Real strike,\n        Real forward,\n        Real blackPrice,\n        Real discount,\n        Real displacement,\n        Real guess,\n        Real w,\n        Real accuracy,\n        Natural maxIterations) {\n\n        QL_REQUIRE(discount>0.0,\n                   \"discount (\" << discount << \") must be positive\");\n\n        QL_REQUIRE(blackPrice>=0.0,\n                   \"option price (\" << blackPrice << \") must be non-negative\");\n\n        strike = strike + displacement;\n        forward = forward + displacement;\n\n        if (guess == Null<Real>()) {\n            guess = blackFormulaImpliedStdDevApproximationRS(\n                optionType, strike, forward,\n                blackPrice, discount, displacement);\n        }\n        else {\n            QL_REQUIRE(guess>=0.0,\n                \"stdDev guess (\" << guess << \") must be non-negative\");\n        }\n\n        Real x = std::log(forward/strike);\n        Real cs = (optionType == Option::Call)\n            ? blackPrice / (forward*discount)\n            : (blackPrice/ (forward*discount) + 1.0 - strike/forward);\n\n        QL_REQUIRE(cs >= 0.0, \"normalized call price (\" << cs\n                   << \") must be positive\");\n\n        if (x > 0) {\n            // use in-out duality\n            cs = forward/strike*cs + 1.0 - forward/strike;\n            QL_REQUIRE(cs >= 0.0, \"negative option price from in-out duality\");\n            x = -x;\n        }\n\n        Size nIter = 0;\n        Real dv, vk, vkp1 = guess;\n\n        do {\n            vk = vkp1;\n            const Real alphaK = (1+w)/(1+phi(x,vk));\n            vkp1 = alphaK*G(vk,x,cs,w) + (1-alphaK)*vk;\n            dv = std::fabs(vkp1 - vk);\n        } while (dv > accuracy && ++nIter < maxIterations);\n\n        QL_REQUIRE(dv <= accuracy, \"max iterations exceeded\");\n        QL_REQUIRE(vk >= 0.0, \"stdDev (\" << vk << \") must be non-negative\");\n\n        return vk;\n    }\n\n    Real blackFormulaImpliedStdDevLiRS(\n        const ext::shared_ptr<PlainVanillaPayoff>& payoff,\n        Real forward,\n        Real blackPrice,\n        Real discount,\n        Real displacement,\n        Real guess,\n        Real omega,\n        Real accuracy,\n        Natural maxIterations) {\n\n        return blackFormulaImpliedStdDevLiRS(\n            payoff->optionType(), payoff->strike(),\n            forward, blackPrice, discount, displacement,\n            guess, omega, accuracy, maxIterations);\n    }\n\n\n    Real blackFormulaCashItmProbability(Option::Type optionType,\n                                        Real strike,\n                                        Real forward,\n                                        Real stdDev,\n                                        Real displacement) {\n        checkParameters(strike, forward, displacement);\n\n        auto sign = Integer(optionType);\n\n        if (stdDev==0.0)\n            return (forward * sign > strike * sign ? 1.0 : 0.0);\n\n        forward = forward + displacement;\n        strike = strike + displacement;\n        if (strike==0.0)\n            return (optionType == Option::Call ? 1.0 : 0.0);\n        Real d2 = std::log(forward/strike)/stdDev - 0.5*stdDev;\n        CumulativeNormalDistribution phi;\n        return phi(sign * d2);\n    }\n\n    Real blackFormulaCashItmProbability(\n                        const ext::shared_ptr<PlainVanillaPayoff>& payoff,\n                        Real forward,\n                        Real stdDev,\n                        Real displacement) {\n        return blackFormulaCashItmProbability(payoff->optionType(),\n            payoff->strike(), forward, stdDev , displacement);\n    }\n\n    Real blackFormulaAssetItmProbability(\n                        Option::Type optionType,\n                        Real strike,\n                        Real forward,\n                        Real stdDev,\n                        Real displacement) {\n        checkParameters(strike, forward, displacement);\n\n        auto sign = Integer(optionType);\n\n        if (stdDev==0.0)\n            return (forward * sign < strike * sign ? 1.0 : 0.0);\n\n        forward = forward + displacement;\n        strike = strike + displacement;\n        if (strike == 0.0)\n            return (optionType == Option::Call ? 1.0 : 0.0);\n        Real d1 = std::log(forward/strike)/stdDev + 0.5*stdDev;\n        CumulativeNormalDistribution phi;\n        return phi(sign * d1);\n    }\n\n    Real blackFormulaAssetItmProbability(\n                        const ext::shared_ptr<PlainVanillaPayoff>& payoff,\n                        Real forward,\n                        Real stdDev,\n                        Real displacement) {\n        return blackFormulaAssetItmProbability(payoff->optionType(),\n            payoff->strike(), forward, stdDev , displacement);\n    }\n\n    Real blackFormulaVolDerivative(Rate strike,\n                                      Rate forward,\n                                      Real stdDev,\n                                      Real expiry,\n                                      Real discount,\n                                      Real displacement)\n    {\n        return  blackFormulaStdDevDerivative(strike,\n                                     forward,\n                                     stdDev,\n                                     discount,\n                                     displacement)*std::sqrt(expiry);\n    }\n\n    Real blackFormulaStdDevDerivative(Rate strike,\n                                      Rate forward,\n                                      Real stdDev,\n                                      Real discount,\n                                      Real displacement)\n    {\n        checkParameters(strike, forward, displacement);\n        QL_REQUIRE(stdDev>=0.0,\n                   \"stdDev (\" << stdDev << \") must be non-negative\");\n        QL_REQUIRE(discount>0.0,\n                   \"discount (\" << discount << \") must be positive\");\n\n        forward = forward + displacement;\n        strike = strike + displacement;\n\n        if (stdDev==0.0 || strike==0.0)\n            return 0.0;\n\n        Real d1 = std::log(forward/strike)/stdDev + .5*stdDev;\n        return discount * forward *\n            CumulativeNormalDistribution().derivative(d1);\n    }\n\n    Real blackFormulaStdDevDerivative(\n                        const ext::shared_ptr<PlainVanillaPayoff>& payoff,\n                        Real forward,\n                        Real stdDev,\n                        Real discount,\n                        Real displacement) {\n        return blackFormulaStdDevDerivative(payoff->strike(), forward,\n                                     stdDev, discount, displacement);\n    }\n\n    Real blackFormulaStdDevSecondDerivative(Rate strike,\n                                            Rate forward,\n                                            Real stdDev,\n                                            Real discount,\n                                            Real displacement)\n    {\n        checkParameters(strike, forward, displacement);\n        QL_REQUIRE(stdDev>=0.0,\n                   \"stdDev (\" << stdDev << \") must be non-negative\");\n        QL_REQUIRE(discount>0.0,\n                   \"discount (\" << discount << \") must be positive\");\n\n        forward = forward + displacement;\n        strike = strike + displacement;\n\n        if (stdDev==0.0 || strike==0.0)\n            return 0.0;\n\n        Real d1 = std::log(forward/strike)/stdDev + .5*stdDev;\n        Real d1p = -std::log(forward/strike)/(stdDev*stdDev) + .5;\n        return discount * forward *\n            NormalDistribution().derivative(d1) * d1p;\n    }\n\n    Real blackFormulaStdDevSecondDerivative(\n                        const ext::shared_ptr<PlainVanillaPayoff>& payoff,\n                        Real forward,\n                        Real stdDev,\n                        Real discount,\n                        Real displacement) {\n        return blackFormulaStdDevSecondDerivative(payoff->strike(), forward,\n                                     stdDev, discount, displacement);\n    }\n\n    Real bachelierBlackFormula(Option::Type optionType,\n                               Real strike,\n                               Real forward,\n                               Real stdDev,\n                               Real discount)\n    {\n        QL_REQUIRE(stdDev>=0.0,\n                   \"stdDev (\" << stdDev << \") must be non-negative\");\n        QL_REQUIRE(discount>0.0,\n                   \"discount (\" << discount << \") must be positive\");\n        Real d = (forward-strike) * Integer(optionType), h = d / stdDev;\n        if (stdDev==0.0)\n            return discount*std::max(d, 0.0);\n        CumulativeNormalDistribution phi;\n        Real result = discount*(stdDev*phi.derivative(h) + d*phi(h));\n        QL_ENSURE(result>=0.0,\n                  \"negative value (\" << result << \") for \" <<\n                  stdDev << \" stdDev, \" <<\n                  optionType << \" option, \" <<\n                  strike << \" strike , \" <<\n                  forward << \" forward\");\n        return result;\n    }\n\n    Real bachelierBlackFormula(\n                        const ext::shared_ptr<PlainVanillaPayoff>& payoff,\n                        Real forward,\n                        Real stdDev,\n                        Real discount) {\n        return bachelierBlackFormula(payoff->optionType(),\n            payoff->strike(), forward, stdDev, discount);\n    }\n\n    Real bachelierBlackFormulaForwardDerivative(\n        Option::Type optionType, Real strike, Real forward, Real stdDev, Real discount)\n    {\n        QL_REQUIRE(stdDev>=0.0,\n                   \"stdDev (\" << stdDev << \") must be non-negative\");\n        QL_REQUIRE(discount>0.0,\n                   \"discount (\" << discount << \") must be positive\");\n        auto sign = Integer(optionType);\n        if (stdDev == 0.0)\n            return sign * std::max(1.0 * boost::math::sign((forward - strike) * sign), 0.0) * discount;\n        Real d = (forward - strike) * sign, h = d / stdDev;\n        CumulativeNormalDistribution phi;\n        return sign * phi(h) * discount;\n    }\n\n    Real bachelierBlackFormulaForwardDerivative(\n        const ext::shared_ptr<PlainVanillaPayoff>& payoff,\n        Real forward,\n        Real stdDev,\n        Real discount)\n    {\n        return bachelierBlackFormulaForwardDerivative(payoff->optionType(),\n            payoff->strike(), forward, stdDev, discount);\n    }\n\n    static Real h(Real eta) {\n\n        const static Real  A0          = 3.994961687345134e-1;\n        const static Real  A1          = 2.100960795068497e+1;\n        const static Real  A2          = 4.980340217855084e+1;\n        const static Real  A3          = 5.988761102690991e+2;\n        const static Real  A4          = 1.848489695437094e+3;\n        const static Real  A5          = 6.106322407867059e+3;\n        const static Real  A6          = 2.493415285349361e+4;\n        const static Real  A7          = 1.266458051348246e+4;\n\n        const static Real  B0          = 1.000000000000000e+0;\n        const static Real  B1          = 4.990534153589422e+1;\n        const static Real  B2          = 3.093573936743112e+1;\n        const static Real  B3          = 1.495105008310999e+3;\n        const static Real  B4          = 1.323614537899738e+3;\n        const static Real  B5          = 1.598919697679745e+4;\n        const static Real  B6          = 2.392008891720782e+4;\n        const static Real  B7          = 3.608817108375034e+3;\n        const static Real  B8          = -2.067719486400926e+2;\n        const static Real  B9          = 1.174240599306013e+1;\n\n        QL_REQUIRE(eta>=0.0,\n                       \"eta (\" << eta << \") must be non-negative\");\n\n        const Real num = A0 + eta * (A1 + eta * (A2 + eta * (A3 + eta * (A4 + eta\n                    * (A5 + eta * (A6 + eta * A7))))));\n\n        const Real den = B0 + eta * (B1 + eta * (B2 + eta * (B3 + eta * (B4 + eta\n                    * (B5 + eta * (B6 + eta * (B7 + eta * (B8 + eta * B9))))))));\n\n        return std::sqrt(eta) * (num / den);\n\n    }\n\n    Real bachelierBlackFormulaImpliedVol(Option::Type optionType,\n                                   Real strike,\n                                   Real forward,\n                                   Real tte,\n                                   Real bachelierPrice,\n                                   Real discount) {\n\n        const static Real SQRT_QL_EPSILON = std::sqrt(QL_EPSILON);\n\n        QL_REQUIRE(tte>0.0,\n                   \"tte (\" << tte << \") must be positive\");\n\n        Real forwardPremium = bachelierPrice/discount;\n\n        Real straddlePremium;\n        if (optionType==Option::Call){\n            straddlePremium = 2.0 * forwardPremium - (forward - strike);\n        } else {\n            straddlePremium = 2.0 * forwardPremium + (forward - strike);\n        }\n\n        Real nu = (forward - strike) / straddlePremium;\n        QL_REQUIRE(nu<1.0 || close_enough(nu,1.0),\n                   \"nu (\" << nu << \") must be <= 1.0\");\n        QL_REQUIRE(nu>-1.0 || close_enough(nu,-1.0),\n                     \"nu (\" << nu << \") must be >= -1.0\");\n\n        nu = std::max(-1.0 + QL_EPSILON, std::min(nu,1.0 - QL_EPSILON));\n\n        // nu / arctanh(nu) -> 1 as nu -> 0\n        Real eta = (std::fabs(nu) < SQRT_QL_EPSILON) ? 1.0 : nu / boost::math::atanh(nu);\n\n        Real heta = h(eta);\n\n        Real impliedBpvol = std::sqrt(M_PI / (2 * tte)) * straddlePremium * heta;\n\n        return impliedBpvol;\n    }\n\n\n        Real bachelierBlackFormulaStdDevDerivative(Rate strike,\n                                      Rate forward,\n                                      Real stdDev,\n                                      Real discount)\n    {\n        QL_REQUIRE(stdDev>=0.0,\n                   \"stdDev (\" << stdDev << \") must be non-negative\");\n        QL_REQUIRE(discount>0.0,\n                   \"discount (\" << discount << \") must be positive\");\n\n        if (stdDev==0.0)\n            return 0.0;\n\n        Real d1 = (forward - strike)/stdDev;\n        return discount *\n            CumulativeNormalDistribution().derivative(d1);\n    }\n\n    Real bachelierBlackFormulaStdDevDerivative(\n                        const ext::shared_ptr<PlainVanillaPayoff>& payoff,\n                        Real forward,\n                        Real stdDev,\n                        Real discount) {\n        return bachelierBlackFormulaStdDevDerivative(payoff->strike(), forward,\n                                     stdDev, discount);\n    }\n\n    Real bachelierBlackFormulaAssetItmProbability(\n                        Option::Type optionType,\n                        Real strike,\n                        Real forward,\n                        Real stdDev) {\n        QL_REQUIRE(stdDev>=0.0,\n                   \"stdDev (\" << stdDev << \") must be non-negative\");\n        Real d = (forward - strike) * Integer(optionType), h = d / stdDev;\n        if (stdDev==0.0)\n            return std::max(d, 0.0);\n        CumulativeNormalDistribution phi;\n        Real result = phi(h);\n        return result;\n    }\n\t\n    Real bachelierBlackFormulaAssetItmProbability(\n                        const ext::shared_ptr<PlainVanillaPayoff>& payoff,\n                        Real forward,\n                        Real stdDev) {\n        return bachelierBlackFormulaAssetItmProbability(payoff->optionType(),\n            payoff->strike(), forward, stdDev);\n    }\n\n    Real bachelierBlackFormulaDelta(Option::Type optionType,\n\t\t                            Real         strike,\n                                    Real         forward,\n                                    Real         stdDev,\n                                    Real         discount) {\n        QL_REQUIRE(stdDev>=0.0,   \"stdDev (\" << stdDev << \") must be non-negative\");\n        QL_REQUIRE(discount>0.0,  \"discount (\" << discount << \") must be positive\");\n        Real d = (forward-strike)*Integer(optionType), h = d/stdDev;\n        CumulativeNormalDistribution phi;\n\t\treturn Integer(optionType)*discount*phi(h);\n\t}\n\n    Real bachelierBlackFormulaGamma(Option::Type optionType,\n\t\t                            Real         strike,\n                                    Real         forward,\n                                    Real         stdDev,\n                                    Real         discount) {\n        QL_REQUIRE(stdDev>=0.0,   \"stdDev (\" << stdDev << \") must be non-negative\");\n        QL_REQUIRE(discount>0.0,  \"discount (\" << discount << \") must be positive\");\n        Real d = (forward-strike)*Integer(optionType), h = d/stdDev;\n        CumulativeNormalDistribution phi;\n\t\treturn discount/stdDev*phi.derivative(h);\n\t}\n\n\n\n\n}\n", "meta": {"hexsha": "ed8ca41ee9f3e3aecb0f12466c2c38455c83f73b", "size": 36591, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ql/pricingengines/blackformula.cpp", "max_stars_repo_name": "sschlenkrich/quantlib", "max_stars_repo_head_hexsha": "ff39ad2cd03d06d185044976b2e26ce34dca470c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ql/pricingengines/blackformula.cpp", "max_issues_repo_name": "sschlenkrich/quantlib", "max_issues_repo_head_hexsha": "ff39ad2cd03d06d185044976b2e26ce34dca470c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ql/pricingengines/blackformula.cpp", "max_forks_repo_name": "sschlenkrich/quantlib", "max_forks_repo_head_hexsha": "ff39ad2cd03d06d185044976b2e26ce34dca470c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.6006493506, "max_line_length": 108, "alphanum_fraction": 0.5068186166, "num_tokens": 8243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.4939495255012387}}
{"text": "#define BOOST_TEST_MODULE\n#include <boost/test/unit_test.hpp>\n#include <util/test_macros.hpp>\n#include <stdlib.h>\n#include <vector>\n#include <string>\n#include <functional>\n#include <random>\n#include <cfenv>\n#include <cmath>\n\n#include <ml_data/ml_data.hpp>\n#include <optimization/optimization_interface.hpp>\n#include <optimization/utils.hpp>\n#include <toolkits/supervised_learning/logistic_regression.hpp>\n#include <toolkits/supervised_learning/logistic_regression_opt_interface.hpp>\n#include <sframe/testing_utils.hpp>\n\n\nusing namespace turi;\nusing namespace turi::supervised;\n\nvoid run_logistic_regression_test(std::map<std::string, flexible_type> opts) {\n\n\n  size_t examples = opts.at(\"examples\");\n  size_t features = opts.at(\"features\");\n  std::string target_column_name = \"target\";\n\n  // Answers\n  // -----------------------------------------------------------------------\n  DenseVector coefs(features+1);\n  coefs.randn();\n\n  // Feature names\n  std::vector<std::string> feature_names;\n  std::vector<flex_type_enum> feature_types;\n  for(size_t i=0; i < features; i++){\n    feature_names.push_back(std::to_string(i));\n    feature_types.push_back(flex_type_enum::FLOAT);\n  }\n\n  // Data\n  std::vector<std::vector<flexible_type>> y_data;\n  std::vector<std::vector<flexible_type>> X_data;\n  for(size_t i=0; i < examples; i++){\n    DenseVector x(features);\n    x.randn();\n    std::vector<flexible_type> x_tmp;\n    for(size_t k=0; k < features; k++){\n      x_tmp.push_back(x(k));\n    }\n\n    // Compute the prediction for this\n    double t = dot(x, coefs.subvec(0, features-1)) + coefs(features);\n    t = 1.0/(1.0+exp(-1.0*t));\n    int c = turi::random::bernoulli(t);\n    if (i == 0) c = 0; // Make sure category 0 is category 0 (for testing)\n    std::vector<flexible_type> y_tmp;\n    y_tmp.push_back(c);\n\n    X_data.push_back(x_tmp);\n    y_data.push_back(y_tmp);\n  }\n\n  // Options\n  std::map<std::string, flexible_type> options = {\n    {\"convergence_threshold\", 1e-2},\n    {\"step_size\", 1.0},\n    {\"lbfgs_memory_level\", 3},\n    {\"max_iterations\", 10},\n    {\"l1_penalty\", 0.0},\n    {\"l2_penalty\", 1e-2}\n  };\n\n  // Make the data\n  sframe X = make_testing_sframe(feature_names, feature_types, X_data);\n  sframe y = make_testing_sframe({\"target\"}, {flex_type_enum::STRING}, y_data);\n  std::shared_ptr<logistic_regression> model;\n  model.reset(new logistic_regression);\n  model->init(X,y);\n  model->init_options(options);\n  model->train();\n\n  // Construct the ml_data\n  ml_data data = model->construct_ml_data_using_current_metadata(X, y);\n\n  // Check coefficients & options\n  // ----------------------------------------------------------------------\n  DenseVector _coefs(features+1);\n  model->get_coefficients(_coefs);\n  TS_ASSERT(_coefs.size() == features + 1);\n\n  std::map<std::string, flexible_type> _options;\n  _options = model->get_current_options();\n  for (auto& kvp: options){\n    TS_ASSERT(_options[kvp.first] == kvp.second);\n  }\n  TS_ASSERT(model->is_trained() == true);\n\n  // Check predictions\n  // ----------------------------------------------------------------------\n  std::vector<flexible_type> pred_margin;\n  std::shared_ptr<sarray<flexible_type>> _pred_margin\n    = model->predict(data, \"margin\");\n  std::vector<flexible_type> pred_class;\n  std::shared_ptr<sarray<flexible_type>> _pred_class\n    = model->predict(data, \"class\");\n  std::vector<flexible_type> pred_prob;\n  std::shared_ptr<sarray<flexible_type>> _pred_prob\n    = model->predict(data, \"probability\");\n\n  // Save predictions made by the model\n  auto reader = _pred_margin->get_reader();\n  reader->read_rows(0, examples, pred_margin);\n  reader = _pred_class->get_reader();\n  reader->read_rows(0, examples, pred_class);\n  reader = _pred_prob->get_reader();\n  reader->read_rows(0, examples, pred_prob);\n\n  // Check that the predictions made by the model are right!\n  for(size_t i=0; i < examples; i++){\n    DenseVector x(features + 1);\n    for(size_t k=0; k < features; k++){\n      x(k) = X_data[i][k];\n    }\n    x(features) = 1;\n    double t = arma::dot(x, _coefs);\n    double p = pred_margin[i];\n    TS_ASSERT(abs(p - t) < 1e-5);\n    t = 1.0/(1.0+exp(-1.0*t));\n    p = pred_prob[i];\n    TS_ASSERT(abs(p - t) < 1e-5);\n    int c = t >= 0.5;\n    TS_ASSERT_EQUALS(pred_class[i], std::to_string(c));\n  }\n\n\n  // Check save and load\n  // ----------------------------------------------------------------------\n  dir_archive archive_write;\n  archive_write.open_directory_for_write(\"regr_logistic_regression_tests\");\n  turi::oarchive oarc(archive_write);\n  oarc << *model;\n  archive_write.close();\n\n  // Load it\n  dir_archive archive_read;\n  archive_read.open_directory_for_read(\"regr_logistic_regression_tests\");\n  turi::iarchive iarc(archive_read);\n  iarc >> *model;\n\n\n  // Check coefficients after saving and loading.\n  // ----------------------------------------------------------------------\n  DenseVector _coefs_after_load(features+1);\n  model->get_coefficients(_coefs_after_load);\n  TS_ASSERT(_coefs_after_load.size() == features + 1);\n  TS_ASSERT(arma::approx_equal(_coefs_after_load, _coefs,\"absdiff\", 1e-5));\n  _options = model->get_current_options();\n  for (auto& kvp: options){\n    TS_ASSERT(_options[kvp.first] == kvp.second);\n  }\n  TS_ASSERT(model->is_trained() == true);\n\n\n  // Check coefficients after saving and loading.\n  // ----------------------------------------------------------------------\n  _pred_margin = model->predict(data, \"margin\");\n  _pred_class = model->predict(data, \"class\");\n  _pred_prob = model->predict(data, \"probability\");\n  reader = _pred_margin->get_reader();\n  reader->read_rows(0, examples, pred_margin);\n  reader = _pred_class->get_reader();\n  reader->read_rows(0, examples, pred_class);\n  reader = _pred_prob->get_reader();\n  reader->read_rows(0, examples, pred_prob);\n\n  // Check that the predictions made by the model are right!\n  for(size_t i=0; i < examples; i++){\n    DenseVector x(features + 1);\n    for(size_t k=0; k < features; k++){\n      x(k) = X_data[i][k];\n    }\n    x(features) = 1;\n    double t = arma::dot(x, _coefs);\n    double p = pred_margin[i];\n    TS_ASSERT(abs(p - t) < 1e-5);\n\n    t = 1.0/(1.0+exp(-1.0*t));\n    p = pred_prob[i];\n    TS_ASSERT(abs(p - t) < 1e-5);\n    int c = t > 0.5;\n    TS_ASSERT_EQUALS(pred_class[i], std::to_string(c));\n  }\n\n  model->get_coefficients(_coefs);\n  TS_ASSERT(_coefs.size() == features + 1);\n  model.reset();\n\n\n  // Check that we can train a model when providing a validation set\n  model.reset(new logistic_regression);\n  logprogress_stream << \"Training with a validation set\" << std::endl;\n  model->init(X, y, X, y);\n  model->init_options(options);\n  model->train();\n\n}\n\n/**\n *  Check logistic regression\n*/\nstruct logistic_regression_test  {\n\n  public:\n\n  void test_logistic_regression_basic_2d() {\n    std::map<std::string, flexible_type> opts = {\n      {\"examples\", 100},\n      {\"features\", 1}};\n    run_logistic_regression_test(opts);\n  }\n\n  void test_logistic_regression_small() {\n    std::map<std::string, flexible_type> opts = {\n      {\"examples\", 1000},\n      {\"features\", 10}};\n    run_logistic_regression_test(opts);\n  }\n\n};\n\n\n\nvoid run_logistic_regression_opt_interface_test(std::map<std::string,\n    flexible_type> opts) {\n\n\n  size_t examples = opts.at(\"examples\");\n  size_t features = opts.at(\"features\");\n  std::string target_column_name = \"target\";\n  std::vector<std::string> column_names = {\"user\", \"item\"};\n\n  // Answers\n  // -----------------------------------------------------------------------\n  DenseVector coefs(features+1);\n  coefs.randn();\n\n  // Feature names\n  std::vector<std::string> feature_names;\n  std::vector<flex_type_enum> feature_types;\n  for(size_t i=0; i < features; i++){\n    feature_names.push_back(std::to_string(i));\n    feature_types.push_back(flex_type_enum::FLOAT);\n  }\n\n  // Data\n  std::vector<std::vector<flexible_type>> y_data;\n  std::vector<std::vector<flexible_type>> X_data;\n  for(size_t i=0; i < examples; i++){\n    DenseVector x(features);\n    x.randn();\n    std::vector<flexible_type> x_tmp;\n    for(size_t k=0; k < features; k++){\n      x_tmp.push_back(x(k));\n    }\n\n    // Compute the prediction for this\n    double t = dot(x, coefs.subvec(0, features-1)) + coefs(features);\n    t = 1.0/(1.0+exp(-1.0*t));\n    int c = turi::random::bernoulli(t);\n    std::vector<flexible_type> y_tmp;\n    y_tmp.push_back(c);\n\n    X_data.push_back(x_tmp);\n    y_data.push_back(y_tmp);\n  }\n\n  // Options\n  std::map<std::string, flexible_type> options = {\n    {\"convergence_threshold\", 1e-2},\n    {\"step_size\", 1.0},\n    {\"lbfgs_memory_level\", 3},\n    {\"mini_batch_size\", 1},\n    {\"max_iterations\", 10},\n    {\"solver\", \"auto\"},\n  };\n\n\n  // Construct the ml_data\n  // Make the data\n  sframe X = make_testing_sframe(feature_names, feature_types, X_data);\n  sframe y = make_testing_sframe({\"target\"}, {flex_type_enum::STRING}, y_data);\n  std::shared_ptr<logistic_regression> model;\n  model.reset(new logistic_regression);\n  model->init(X, y);\n\n  // Construct the ml_data\n  ml_data data = model->construct_ml_data_using_current_metadata(X, y);\n  ml_data valid_data;\n\n  std::shared_ptr<logistic_regression_opt_interface> lr_interface;\n  lr_interface.reset(new logistic_regression_opt_interface(data, valid_data, *model));\n\n  // Check examples & variables.\n  TS_ASSERT(lr_interface->num_variables() == features + 1);\n  TS_ASSERT(lr_interface->num_examples() == examples);\n\n  size_t variables = lr_interface->num_variables();\n  for(size_t i=0; i < 10; i++){\n\n    DenseVector point(variables);\n    point.randn();\n\n    // Check gradients, functions and hessians.\n    DenseVector gradient(variables);\n    double func_value;\n    DenseMatrix hessian(variables, variables);\n\n    func_value = lr_interface->compute_function_value(point);\n    lr_interface->compute_gradient(point, gradient);\n    lr_interface->compute_hessian(point, hessian);\n    TS_ASSERT(check_gradient(*lr_interface, point, gradient));\n    if( variables <= 2){\n      TS_ASSERT(check_hessian(*lr_interface, point, hessian));\n    }\n\n\n    // Check first order & second order computations\n    DenseVector _gradient(variables);\n    double _func_value;\n    DenseMatrix _hessian(variables, variables);\n\n    lr_interface->compute_first_order_statistics(point, _gradient,\n      _func_value);\n    TS_ASSERT(abs(func_value - _func_value) < 1e-5);\n    TS_ASSERT(arma::approx_equal(gradient, _gradient,\"absdiff\", 1e-10));\n    lr_interface->compute_second_order_statistics(point, _hessian, _gradient,\n      _func_value);\n    TS_ASSERT(abs(func_value - _func_value) < 1e-5);\n    TS_ASSERT(arma::approx_equal(gradient, _gradient,\"absdiff\", 1e-10));\n    TS_ASSERT(arma::approx_equal(hessian, _hessian,\"absdiff\", 1e-10));\n\n  }\n\n  model.reset();\n  lr_interface.reset();\n}\n\n\n/**\n *  Check logistic regression opt interface\n*/\nstruct logistic_regression_opt_interface_test  {\n\n  public:\n\n  void test_logistic_regression_opt_interface_basic_2d() {\n    std::map<std::string, flexible_type> opts = {\n      {\"examples\", 100},\n      {\"features\", 1}};\n    run_logistic_regression_opt_interface_test(opts);\n  }\n\n  void test_logistic_regression_opt_interface_small() {\n    std::map<std::string, flexible_type> opts = {\n      {\"examples\", 1000},\n      {\"features\", 10}};\n    run_logistic_regression_opt_interface_test(opts);\n  }\n\n};\n\nBOOST_FIXTURE_TEST_SUITE(_logistic_regression_test, logistic_regression_test)\nBOOST_AUTO_TEST_CASE(test_logistic_regression_basic_2d) {\n  logistic_regression_test::test_logistic_regression_basic_2d();\n}\nBOOST_AUTO_TEST_CASE(test_logistic_regression_small) {\n  logistic_regression_test::test_logistic_regression_small();\n}\nBOOST_AUTO_TEST_SUITE_END()\nBOOST_FIXTURE_TEST_SUITE(_logistic_regression_opt_interface_test, logistic_regression_opt_interface_test)\nBOOST_AUTO_TEST_CASE(test_logistic_regression_opt_interface_basic_2d) {\n  logistic_regression_opt_interface_test::test_logistic_regression_opt_interface_basic_2d();\n}\nBOOST_AUTO_TEST_CASE(test_logistic_regression_opt_interface_small) {\n  logistic_regression_opt_interface_test::test_logistic_regression_opt_interface_small();\n}\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "c50d1c726ff343a887d4a6b8ae464e060a3b621d", "size": 12066, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "test/toolkits/supervised_learning/logistic_regression_tests.cxx", "max_stars_repo_name": "shreyasvj25/turicreate", "max_stars_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-12-15T20:03:51.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-15T20:03:51.000Z", "max_issues_repo_path": "test/toolkits/supervised_learning/logistic_regression_tests.cxx", "max_issues_repo_name": "shreyasvj25/turicreate", "max_issues_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-12-11T10:37:10.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-11T10:37:10.000Z", "max_forks_repo_path": "test/toolkits/supervised_learning/logistic_regression_tests.cxx", "max_forks_repo_name": "shreyasvj25/turicreate", "max_forks_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-06-01T18:49:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-01T18:49:28.000Z", "avg_line_length": 30.8593350384, "max_line_length": 105, "alphanum_fraction": 0.6707276645, "num_tokens": 3117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4939495255012386}}
{"text": "#include <boost/math/special_functions/ellint_rd.hpp>\n", "meta": {"hexsha": "cbacd520885069c84253ca935cfddc1e121d326d", "size": 54, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_special_functions_ellint_rd.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_special_functions_ellint_rd.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_special_functions_ellint_rd.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 27.0, "max_line_length": 53, "alphanum_fraction": 0.8333333333, "num_tokens": 13, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708698, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.49394952550123855}}
{"text": "#include \"drake/solvers/system_identification.h\"\n\n#include <random>  // Used only with deterministic seeds!\n\n#include <Eigen/Core>\n#include <gtest/gtest.h>\n\n#include \"drake/common/polynomial.h\"\n#include \"drake/common/trig_poly.h\"\n\nnamespace drake {\nnamespace solvers {\nnamespace {\n\ntypedef SystemIdentification<double> SID;\n\nGTEST_TEST(SystemIdentificationTest, LumpedSingle) {\n  Polynomiald x = Polynomiald(\"x\");\n  Polynomiald y = Polynomiald(\"y\");\n  Polynomiald a = Polynomiald(\"a\");\n  Polynomiald b = Polynomiald(\"b\");\n  Polynomiald c = Polynomiald(\"c\");\n\n  /* From the SystemIdentification.h doxygen */\n  Polynomiald input = (a * x) + (b * x) + (a * c * y) + (a * c * y * y);\n\n  std::set<Polynomiald::VarType> parameters = {\n    a.GetSimpleVariable(),\n    b.GetSimpleVariable(),\n    c.GetSimpleVariable()};\n  SID::LumpingMapType lump_map =\n      SID::GetLumpedParametersFromPolynomial(input, parameters);\n  EXPECT_EQ(lump_map.size(), 2u);\n  EXPECT_EQ(lump_map.count(a + b), 1u);\n  EXPECT_EQ(lump_map.count(a * c), 1u);\n}\n\nGTEST_TEST(SystemIdentificationTest, LumpedMulti) {\n  Polynomiald x = Polynomiald(\"x\");\n  Polynomiald y = Polynomiald(\"y\");\n  Polynomiald a = Polynomiald(\"a\");\n  Polynomiald b = Polynomiald(\"b\");\n  Polynomiald c = Polynomiald(\"c\");\n\n  std::vector<Polynomiald> input = {\n    (a * x) + (b * x) + (a * c * y),\n    (a * c * y * y),\n    2 * a,\n    a};\n\n  std::set<Polynomiald::VarType> parameters = {\n    a.GetSimpleVariable(),\n    b.GetSimpleVariable(),\n    c.GetSimpleVariable()};\n  SID::LumpingMapType lump_map =\n      SID::GetLumpedParametersFromPolynomials(input, parameters);\n\n  // Note that we expect that 'a' and '2*a' will collapse to one lumped param.\n  EXPECT_EQ(lump_map.size(), 3u);\n  EXPECT_EQ(lump_map.count(a), 1u);\n  EXPECT_EQ(lump_map.count(a + b), 1u);\n  EXPECT_EQ(lump_map.count(a * c), 1u);\n\n  // TODO(ggould-tri) The above code should be able to be more cleanly written\n  // using gmock as something like:\n  //\n  // EXPECT_THAT(lump_map, ElementsAre(std::make_pair(a, _),\n  //                                   std::make_pair((a + b), _),\n  //                                   std::make_pair((a * c), _)));\n  //\n  // but the author could not get this working.\n}\n\nGTEST_TEST(SystemIdentificationTest, LumpedParameterRewrite) {\n  Polynomiald x = Polynomiald(\"x\");\n  Polynomiald y = Polynomiald(\"y\");\n  Polynomiald a = Polynomiald(\"a\");\n  Polynomiald b = Polynomiald(\"b\");\n  Polynomiald c = Polynomiald(\"c\");\n\n  std::vector<Polynomiald> input = {\n    (a * x) + (b * x) + (3 * a * c * y),\n    (a * x) + (2 * b * x) + (3 * a * c * y),\n    (a * c * y * y),\n    2 * a,\n    a};\n\n  std::set<Polynomiald::VarType> parameters = {\n    a.GetSimpleVariable(),\n    b.GetSimpleVariable(),\n    c.GetSimpleVariable()};\n  SID::LumpingMapType lump_map =\n      SID::GetLumpedParametersFromPolynomials(input, parameters);\n\n  // A point for testing numeric stability.\n  std::map<Polynomiald::VarType, double> eval_point = {\n    {x.GetSimpleVariable(), 1},\n    {y.GetSimpleVariable(), 2},\n    {a.GetSimpleVariable(), 3},\n    {b.GetSimpleVariable(), 5},\n    {c.GetSimpleVariable(), 7},\n  };\n  // Compute the value of each lumped parameter at eval_point; store those\n  // values into the eval_point (so that now it provides both lumped and\n  // un-lumped values and can be used to evaluate either the original or the\n  // rewritten polynomial).\n  for (const auto& poly_var_pair : lump_map) {\n    eval_point[poly_var_pair.second] =\n        poly_var_pair.first.EvaluateMultivariate(eval_point);\n  }\n\n  for (const Polynomiald& poly : input) {\n    Polynomiald rewritten =\n        SID::RewritePolynomialWithLumpedParameters(poly, lump_map);\n\n    // No non-lumped parameters should remain in rewritten.\n    EXPECT_EQ(rewritten.GetVariables().count(a.GetSimpleVariable()), 0u);\n    EXPECT_EQ(rewritten.GetVariables().count(b.GetSimpleVariable()), 0u);\n    EXPECT_EQ(rewritten.GetVariables().count(c.GetSimpleVariable()), 0u);\n\n    // Rewritten has the same or smaller number of variables and terms.\n    EXPECT_LE(rewritten.GetVariables().size(), poly.GetVariables().size());\n    EXPECT_LE(rewritten.GetMonomials().size(), poly.GetMonomials().size());\n\n    // Rewriting in terms of lumped parameters should never change the\n    // actual value of a polynomial at a particular point.\n    EXPECT_EQ(poly.EvaluateMultivariate(eval_point),\n              rewritten.EvaluateMultivariate(eval_point));\n\n    // TODO(ggould-tri) The above tests do not ensure that the original and\n    // rewritten polys are everywhere and always structurally identical, just\n    // nearly always identical in their EvaluateMultivariate behaviour.\n  }\n}\n\nGTEST_TEST(SystemIdentificationTest, BasicEstimateParameters) {\n  const Polynomiald x = Polynomiald(\"x\");\n  const auto x_var = x.GetSimpleVariable();\n  const Polynomiald y = Polynomiald(\"y\");\n  const auto y_var = y.GetSimpleVariable();\n  const Polynomiald z = Polynomiald(\"z\");\n  const auto z_var = z.GetSimpleVariable();\n  const Polynomiald a = Polynomiald(\"a\");\n  const auto a_var = a.GetSimpleVariable();\n  const Polynomiald b = Polynomiald(\"b\");\n  const auto b_var = b.GetSimpleVariable();\n  const Polynomiald c = Polynomiald(\"c\");\n  const auto c_var = c.GetSimpleVariable();\n\n  /// Parameter estimation will try to make this Polynomial evaluate to zero:\n  const Polynomiald poly = (a * x) + (b * x * x) + (c * y) - z;\n\n  { // A very simple test case in which the error is zero.\n    const std::vector<SID::PartialEvalType> sample_points {\n      {{x_var, 1}, {y_var, 1}, {z_var, 3}},\n      {{x_var, 1}, {y_var, 2}, {z_var, 4}},\n      {{x_var, 2}, {y_var, 1}, {z_var, 7}},\n      {{x_var, 2}, {y_var, 2}, {z_var, 8}}};\n\n    const SID::PartialEvalType expected_params {\n      {a_var, 1}, {b_var, 1}, {c_var, 1}};\n\n    SID::PartialEvalType estimated_params;\n    double error;\n    std::tie(estimated_params, error) =\n        SID::EstimateParameters(VectorXPoly::Constant(1, poly),\n                                sample_points);\n\n    EXPECT_LT(error, 1e-5);\n    EXPECT_EQ(estimated_params.size(), 3u);\n    for (const auto& var : {a_var, b_var, c_var}) {\n      // `9 * error` here in case all of the RMS error was in a single term.\n      EXPECT_NEAR(estimated_params[var], expected_params.at(var),\n                  9 * error);\n    }\n  }\n\n  { // Test with some error injected.\n    const std::vector<SID::PartialEvalType> sample_points {\n      {{x_var, 1}, {y_var, 1}, {z_var, 3.05}},\n      {{x_var, 1}, {y_var, 2}, {z_var, 3.95}},\n      {{x_var, 2}, {y_var, 1}, {z_var, 7.05}},\n      {{x_var, 2}, {y_var, 2}, {z_var, 8.05}}};\n\n    const SID::PartialEvalType expected_params {\n      {a_var, 1}, {b_var, 1}, {c_var, 1}};\n\n    SID::PartialEvalType estimated_params;\n    double error;\n    std::tie(estimated_params, error) =\n        SID::EstimateParameters(VectorXPoly::Constant(1, poly),\n                                sample_points);\n\n    EXPECT_LT(error, 0.1);\n    EXPECT_EQ(estimated_params.size(), 3u);\n    for (const auto& var : {a_var, b_var, c_var}) {\n      EXPECT_NEAR(estimated_params[var], expected_params.at(var), 4 * error);\n    }\n  }\n}\n\n/// Test to check parameter estimation for a basic spring-mass system.\n///@{\n\nstruct State { double acceleration, velocity, position, force; };\nstatic const double kMass = 1;\nstatic const double kDamping = 0.1;\nstatic const double kSpring = 2;\nstatic const double kNoise = 0.01;\nstatic const double kNoiseSeed = 1;\n\nState AdvanceState(const State& previous, double input_force, double dt) {\n  State next{};\n  next.force = input_force;\n  next.acceleration = (input_force -\n                       previous.velocity * kDamping -\n                       previous.position * kSpring) / kMass;\n  next.velocity = previous.velocity +\n      (dt * (previous.acceleration + next.acceleration) / 2);\n  next.position = previous.position +\n      (dt * (previous.velocity + next.velocity) / 2);\n  return next;\n}\n\nstd::vector<State> MakeTestData() {\n  static const double kDt = 0.01;\n  static const double kDuration1 = 1;\n  static const double kInputForce1 = 1;\n  static const double kDuration2 = 3;\n  static const double kInputForce2 = 0;\n  static const State kInitial {0, 0, 0, 0};\n\n  std::vector<State> result { kInitial };\n  State current = kInitial;\n  double t = 0;\n  while (t < kDuration1) {\n    current = AdvanceState(current, kInputForce1, kDt);\n    result.push_back(current);\n    t += kDt;\n  }\n  while (t < kDuration1 + kDuration2) {\n    current = AdvanceState(current, kInputForce2, kDt);\n    result.push_back(current);\n    t += kDt;\n  }\n\n  return result;\n}\n\n// TODO(ggould-tri) It is likely that much of the logic below will be\n// boilerplate shared by all manipulator identification; it should eventually\n// be pulled into a function of its own inside of system_identification.\nGTEST_TEST(SystemIdentificationTest, SpringMassIdentification) {\n  Polynomiald pos = Polynomiald(\"pos\");\n  auto pos_var = pos.GetSimpleVariable();\n  Polynomiald velocity = Polynomiald(\"vel\");\n  auto velocity_var = velocity.GetSimpleVariable();\n  Polynomiald acceleration = Polynomiald(\"acc\");\n  auto acceleration_var = acceleration.GetSimpleVariable();\n  Polynomiald input_force = Polynomiald(\"f_in\");\n  auto input_force_var = input_force.GetSimpleVariable();\n  Polynomiald mass = Polynomiald(\"m\");\n  auto mass_var = mass.GetSimpleVariable();\n  Polynomiald damping = Polynomiald(\"b\");\n  auto damping_var = damping.GetSimpleVariable();\n  Polynomiald spring = Polynomiald(\"k\");\n  auto spring_var = spring.GetSimpleVariable();\n\n  // Code style violations here:\n  // * Vector initializations use two statements on one line for clarity.\n  // * The short names and upper/lower case here are conventional in the\n  //   manipulator formulation.\n  //\n  // We write the manipulator as:\n  //   H*vdot + C*v + g = B*u + f\n  // Where f embodies any forces not appropriate to C.\n  VectorXPoly v(1); v << velocity;\n  VectorXPoly vdot(1); vdot << acceleration;\n  VectorXPoly H(1); H << mass;\n  VectorXPoly C(1); C << 0;\n  VectorXPoly g(1); g << (spring * pos);\n  VectorXPoly f(1); f << (velocity * damping);\n  VectorXPoly B(1); B << 1;\n  VectorXPoly u(1); u << input_force;\n\n  const VectorXPoly manipulator_left = (H * vdot) + (C * v) + g;\n  const VectorXPoly manipulator_right = (B * u) + f;\n\n  std::default_random_engine noise_generator;\n  noise_generator.seed(kNoiseSeed);\n  std::uniform_real_distribution<double> noise_distribution(-kNoise, kNoise);\n  auto noise = std::bind(noise_distribution, noise_generator);\n\n  const std::vector<State> oracular_data = MakeTestData();\n  std::vector<SID::PartialEvalType> measurements;\n  for (const State& oracular_state : oracular_data) {\n    SID::PartialEvalType measurement;\n    measurement[pos_var] = oracular_state.position + noise();\n    measurement[velocity_var] = oracular_state.velocity + noise();\n    measurement[acceleration_var] = oracular_state.acceleration + noise();\n    measurement[input_force_var] = oracular_state.force + noise();\n    measurements.push_back(measurement);\n  }\n\n  SID::PartialEvalType estimated_params;\n  double error;\n  std::tie(estimated_params, error) =\n      SID::EstimateParameters(manipulator_left - manipulator_right,\n                              measurements);\n\n  // Multiple layers of naive discrete-time numeric integration yields a very\n  // high error value here, which almost all lands in the damping constant\n  // because it is the smallest term in the equation of motion.\n  //\n  // The value for the error check here is an arbitrary empirical observation,\n  // to catch changes that heavily regress accuracy.\n  EXPECT_LT(error, 2e-2);\n\n  EXPECT_EQ(estimated_params.size(), 3u);\n  EXPECT_NEAR(estimated_params[mass_var], kMass, kNoise);\n  EXPECT_NEAR(estimated_params[damping_var], kDamping,\n              measurements.size() * error);\n  EXPECT_NEAR(estimated_params[spring_var], kSpring, kNoise);\n}\n\nGTEST_TEST(SystemIdentificationTest, PendulaIdentification) {\n  // Simulate two pendula that swing independently but are actuated with the\n  // same torque.  The pendula have lengths l1 = 1, l2 = 2; their masses m1\n  // and m2 are both 1.  Gravity is an earth-conventional -9.8.\n  //\n  // The comments about nomenclature from the previous test apply here as\n  // well: Variable naming is conventional rather than style-conformant.\n\n  const TrigPolyd theta1(Polynomiald(\"th\", 1),\n                         Polynomiald(\"s\", 1), Polynomiald(\"c\", 1));\n  const TrigPolyd theta2(Polynomiald(\"th\", 2),\n                         Polynomiald(\"s\", 2), Polynomiald(\"c\", 2));\n  VectorXTrigPoly q(2); q << theta1, theta2;\n\n  const TrigPolyd theta1dot(Polynomiald(\"th.\", 1),\n                            Polynomiald(\"s.\", 1), Polynomiald(\"c.\", 1));\n  const TrigPolyd theta2dot(Polynomiald(\"th.\", 2),\n                            Polynomiald(\"s.\", 2), Polynomiald(\"c.\", 2));\n  VectorXTrigPoly qdot(2); qdot << theta1dot, theta2dot;\n\n  const TrigPolyd theta1dotdot(Polynomiald(\"th..\", 1),\n                               Polynomiald(\"s..\", 1), Polynomiald(\"c..\", 1));\n  const TrigPolyd theta2dotdot(Polynomiald(\"th..\", 2),\n                               Polynomiald(\"s..\", 2), Polynomiald(\"c..\", 2));\n  VectorXTrigPoly qdotdot(2); qdotdot << theta1dotdot, theta2dotdot;\n\n  const TrigPolyd l1(Polynomiald(\"l\", 1));  //< Length of arm 1.\n  const TrigPolyd l2(Polynomiald(\"l\", 2));  //< Length of arm 2.\n  const TrigPolyd m1(Polynomiald(\"m\", 1));  //< Mass of arm 1.\n  const TrigPolyd m2(Polynomiald(\"m\", 2));  //< Mass of arm 2.\n\n  const TrigPolyd gravity(Polynomiald(\"g\"));  //< gravity\n  const TrigPolyd tau(Polynomiald(\"tau\"));  //< torque\n\n  // The following matrices and vectors are the components of the Manipulator.\n  Eigen::Matrix<TrigPolyd, 2, 2> H;  //< Inertia matrix.\n  H << (m1 * l1 * l1), 0,\n       0, (m2 * l2 * l2);\n  Eigen::Matrix<TrigPolyd, 2, 2> C;  //< Coriolis matrix.\n  C << 0, 0, 0, 0;\n  Eigen::Matrix<TrigPolyd, 2, 1> g;  //< Field function (gravity).\n  g << m1 * gravity * l1 * sin(theta1), m2 * gravity * l2 * sin(theta2);\n  Eigen::Matrix<TrigPolyd, 2, 1> B;  //< Input transmission mapping.\n  B << 1, 1;\n  Eigen::Matrix<TrigPolyd, 2, 1> f;  //< Dissipative forces.\n  f << 0, 0;\n\n  VectorXTrigPoly u(1); u << tau;  //< Input signals.\n\n  const VectorXTrigPoly manipulator_left = (H * qdotdot) + (C * qdot) + g;\n  const VectorXTrigPoly manipulator_right = (B * u) + f;\n  const VectorXTrigPoly to_estimate = manipulator_left - manipulator_right;\n\n  // Create convenience variables for our q/qdot/u values.  Convenience vars\n  // have an underscore prefix for slightly easier understandability.\n  const TrigPolyd::VarType th1_var = theta1.poly().GetSimpleVariable();\n  const TrigPolyd::VarType th2_var = theta2.poly().GetSimpleVariable();\n  const TrigPolyd::VarType th1d_var =\n      theta1dot.poly().GetSimpleVariable();\n  const TrigPolyd::VarType th2d_var =\n      theta2dot.poly().GetSimpleVariable();\n  const TrigPolyd::VarType th1dd_var =\n      theta1dotdot.poly().GetSimpleVariable();\n  const TrigPolyd::VarType th2dd_var =\n      theta2dotdot.poly().GetSimpleVariable();\n  const TrigPolyd::VarType tau_var = tau.poly().GetSimpleVariable();\n\n  const double kG = 9.8;\n  const double kPi = 3.14159265;\n  const double kPi2 = kPi / 2;\n\n  const std::vector<typename SID::PartialEvalType> pendula_data = {\n    {{tau_var, 0.},\n     {th1_var, 0.}, {th1d_var, 0.}, {th1dd_var, 0.},\n     {th2_var, 0.}, {th2d_var, 0.}, {th2dd_var, 0.}},\n    {{tau_var, 0.},\n     {th1_var, kPi2}, {th1d_var, 0.}, {th1dd_var, -kG},\n     {th2_var, kPi2}, {th2d_var, 0.}, {th2dd_var, -0.25 * kG}},\n    {{tau_var, 0.},\n     {th1_var, -kPi}, {th1d_var, 0.}, {th1dd_var, 0.},\n     {th2_var, -kPi}, {th2d_var, 0.}, {th2dd_var, 0.}},\n    {{tau_var, 0.},\n     {th1_var, -kPi2}, {th1d_var, 0.}, {th1dd_var, kG},\n     {th2_var, -kPi2}, {th2d_var, 0.}, {th2dd_var, 0.25 * kG}},\n    {{tau_var, 1.},\n     {th1_var, 0.}, {th1d_var, 0.}, {th1dd_var, 1.},\n     {th2_var, 0.}, {th2d_var, 0.}, {th2dd_var, 0.25}},\n    {{tau_var, kG},\n     {th1_var, kPi2}, {th1d_var, 0.}, {th1dd_var, 0.},\n     {th2_var, kPi2}, {th2d_var, 0.}, {th2dd_var, 0.}},\n    {{tau_var, 1.},\n     {th1_var, -kPi}, {th1d_var, 0.}, {th1dd_var, 1.},\n     {th2_var, -kPi}, {th2d_var, 0.}, {th2dd_var, 0.25}},\n    {{tau_var, -kG},\n     {th1_var, -kPi2}, {th1d_var, 0.}, {th1dd_var, 0.},\n     {th2_var, -kPi2}, {th2d_var, 0.}, {th2dd_var, 0.}},\n    };\n\n  SID::SystemIdentificationResult result =\n      SID::LumpedSystemIdentification(to_estimate, pendula_data);\n\n  // Check result.rms_error.\n  const double epsilon = 1e-5;  // Moderate, empirical epsilon for weak solvers.\n  EXPECT_LT(result.rms_error, epsilon);\n  const double max_per_term_error =\n      result.rms_error *\n      (result.lumped_parameters.size() * result.lumped_parameters.size());\n\n  // Check result.lumped_parameters.\n  Polynomiald mgl1 = (m1 * gravity * l1).poly();\n  Polynomiald mgl2 = (m2 * gravity * l2).poly();\n  Polynomiald mll1 = (m1 * l1 * l1).poly();\n  Polynomiald mll2 = (m2 * l2 * l2).poly();\n  EXPECT_EQ(result.lumped_parameters.size(), static_cast<size_t>(4));\n  Polynomiald::VarType mgl1_var = result.lumped_parameters.at(mgl1);\n  Polynomiald::VarType mgl2_var = result.lumped_parameters.at(mgl2);\n  Polynomiald::VarType mll1_var = result.lumped_parameters.at(mll1);\n  Polynomiald::VarType mll2_var = result.lumped_parameters.at(mll2);\n\n  // Check result.lumped_polys.\n  std::set<Polynomiald::VarType> expected_vars_1 = {\n    mgl1_var, mll1_var, th1_var, th1dd_var, tau_var};\n  EXPECT_EQ(result.lumped_polys[0].GetVariables(), expected_vars_1);\n  std::set<Polynomiald::VarType> expected_vars_2 = {\n    mgl2_var, mll2_var, th2_var, th2dd_var, tau_var};\n  EXPECT_EQ(result.lumped_polys[1].GetVariables(), expected_vars_2);\n\n  // Check result.lumped_parameter_values\n  EXPECT_NEAR(result.lumped_parameter_values[mgl1_var], kG, max_per_term_error);\n  EXPECT_NEAR(result.lumped_parameter_values[mgl2_var], kG, max_per_term_error);\n  EXPECT_NEAR(result.lumped_parameter_values[mll1_var], 1, max_per_term_error);\n  EXPECT_NEAR(result.lumped_parameter_values[mll2_var], 4, max_per_term_error);\n\n  // Check result.partially_evaluated_polys.\n  for (const auto& point : pendula_data) {\n    EXPECT_NEAR(result.partially_evaluated_polys[0].EvaluateMultivariate(point),\n                0, max_per_term_error);\n    EXPECT_NEAR(result.partially_evaluated_polys[1].EvaluateMultivariate(point),\n                0, max_per_term_error);\n  }\n}\n\n///@}\n\n}  // anonymous namespace\n}  // namespace solvers\n}  // namespace drake\n", "meta": {"hexsha": "3a7de6755ca0f99aabbde79718c9ed9031a4b3c3", "size": 18439, "ext": "cc", "lang": "C++", "max_stars_repo_path": "solvers/test/system_identification_test.cc", "max_stars_repo_name": "RobotLocomotion/drake-python3.7", "max_stars_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-02-25T02:01:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-17T04:52:04.000Z", "max_issues_repo_path": "solvers/test/system_identification_test.cc", "max_issues_repo_name": "RobotLocomotion/drake-python3.7", "max_issues_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "solvers/test/system_identification_test.cc", "max_forks_repo_name": "RobotLocomotion/drake-python3.7", "max_forks_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-13T12:05:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-13T12:05:39.000Z", "avg_line_length": 38.9830866808, "max_line_length": 80, "alphanum_fraction": 0.6689082922, "num_tokens": 5388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128672997041659, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4939495199917366}}
{"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_TAND_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_TAND_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-trigonometric\n    Function object implementing tand capabilities\n\n    tangent of the input in degrees: \\f$\\sin(\\pi x/180)/\\cos(\\pi x/180) \\f$.\n\n    @par Semantic:\n\n    For every parameter of floating type\n\n    @code\n    auto r = tand(x);\n    @endcode\n\n    As most other trigonometric function tand can be called with a second optional parameter\n    which is a tag on speed and accuracy (see @ref cos for further details)\n\n    @see tan, tanpi\n\n  **/\n  Value tand(Value const & v0);\n} }\n#endif\n\n#include <boost/simd/function/scalar/tand.hpp>\n#include <boost/simd/function/simd/tand.hpp>\n\n#endif\n", "meta": {"hexsha": "9cbdfe6b0d2da347797eff68d351fc256b1fa1da", "size": 1165, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/tand.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/tand.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/tand.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": 24.7872340426, "max_line_length": 100, "alphanum_fraction": 0.5939914163, "num_tokens": 252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128672997041659, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4939495199917366}}
{"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// 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// 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_AREA_HPP\n#define BOOST_GEOMETRY_EXTENSIONS_NSPHERE_ALGORITHMS_AREA_HPP\n\n\n#include <type_traits>\n\n#include <boost/math/constants/constants.hpp>\n\n#include <boost/geometry/algorithms/area.hpp>\n#include <boost/geometry/extensions/nsphere/core/radius.hpp>\n#include <boost/geometry/extensions/nsphere/core/tags.hpp>\n\n\n\nnamespace boost { namespace geometry\n{\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail { namespace area\n{\n\ntemplate<typename C>\nstruct circle_area\n{\n    typedef typename coordinate_type<C>::type coordinate_type;\n\n    // Returning the coordinate precision, but if integer, returning a double\n    typedef std::conditional_t\n        <\n            std::is_integral<coordinate_type>::value,\n            double,\n            coordinate_type\n        > return_type;\n\n    template <typename S>\n    static inline return_type apply(C const& c, S const&)\n    {\n        // Currently only works for Cartesian circles\n        // Todo: use strategy\n        // Todo: use concept\n        assert_dimension<C, 2>();\n\n        return_type r = get_radius<0>(c);\n        r *= r * boost::math::constants::pi<return_type>();\n        return r;\n    }\n};\n\n\n\n}} // namespace detail::area\n\n#endif // DOXYGEN_NO_DETAIL\n\n#ifndef DOXYGEN_NO_DISPATCH\nnamespace dispatch\n{\n\n\ntemplate <typename Geometry>\nstruct area<Geometry, nsphere_tag>\n    : detail::area::circle_area<Geometry>\n{};\n\n\n} // namespace dispatch\n#endif // DOXYGEN_NO_DISPATCH\n\n\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_EXTENSIONS_NSPHERE_ALGORITHMS_AREA_HPP\n", "meta": {"hexsha": "2d998c60308cbce42dd3e1b7528276ffdf568542", "size": 2330, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/geometry/extensions/nsphere/algorithms/area.hpp", "max_stars_repo_name": "jkerkela/geometry", "max_stars_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 709.0, "max_stars_repo_stars_event_min_datetime": "2016-03-19T07:55:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:02:22.000Z", "max_issues_repo_path": "include/boost/geometry/extensions/nsphere/algorithms/area.hpp", "max_issues_repo_name": "jkerkela/geometry", "max_issues_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 623.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T23:45:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T11:15:23.000Z", "max_forks_repo_path": "include/boost/geometry/extensions/nsphere/algorithms/area.hpp", "max_forks_repo_name": "jkerkela/geometry", "max_forks_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-01-14T15:50:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T03:58:36.000Z", "avg_line_length": 25.6043956044, "max_line_length": 79, "alphanum_fraction": 0.7248927039, "num_tokens": 550, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.49390236053832887}}
{"text": "#include <scitbx/array_family/simple_io.h>\n#include <scitbx/array_family/initialiser.h>\n#include <scitbx/array_family/ref_reductions.h>\n#include <scitbx/array_family/tiny_algebra.h>\n#include <scitbx/array_family/ref_algebra.h>\n#include <scitbx/array_family/misc_functions.h>\n#include <scitbx/matrix/special_matrices.h>\n#include <scitbx/matrix/move.h>\n#include <scitbx/error.h>\n#include <scitbx/random.h>\n#include <scitbx/array_family/simple_io.h>\n#include <iostream>\n\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_int.hpp>\n\n#include <scitbx/matrix/householder.h>\n#include <scitbx/matrix/tests.h>\n#include <scitbx/matrix/tests/utils.h>\n\nnamespace af = scitbx::af;\nusing scitbx::fn::approx_equal;\nusing namespace scitbx::matrix;\n\n#if defined(__GNUC__) && __GNUC__ == 4 && __GNUC_MINOR__ == 1 \\\n && defined(__i386__) && defined(__linux)\n// avoid internal compiler error\n#undef SCITBX_ASSERT\n#define SCITBX_ASSERT(cond)\n#endif\n\ndouble tol = 1e-12;\n\nstruct test_case\n{\n  matrix_t a0;\n  double thresh;\n\n  test_case(int m, int n, double ratio_threshold=10)\n    : a0(dim(m,n)), thresh(ratio_threshold)\n  {}\n\n  void check_qr(bool thin_q) {\n    matrix_const_ref_t a0_ = a0.const_ref();\n\n    matrix_t a = a0.deep_copy();\n    matrix_ref_t a_ = a.ref();\n\n    int m = a_.n_rows(), n=a_.n_columns();\n\n    householder::qr_decomposition<double> qr(a_);\n\n    // Get R\n    matrix_t r(dim(thin_q ? std::min(m,n) : m, n));\n    matrix_ref_t r_ = r.ref();\n    for (int i=0; i<std::min(m,n); ++i)\n    for (int j=i; j<n; ++j) {\n      r_(i,j) = a_(i,j);\n    }\n\n    // Accumulate Q out-of-place\n    matrix_t q = qr.q(thin_q);\n    matrix_const_ref_t q_ = q.const_ref();\n    SCITBX_ASSERT( normality_ratio(q_) < thresh );\n\n    // Accumulate Q in-place if it makes sense\n    if (thin_q && m >= n) {\n      qr.accumulate_q_in_place();\n      SCITBX_ASSERT( equality_ratio(q_, a_) < thresh );\n    }\n\n    // Check A = QR\n    matrix_t q_r = af::matrix_multiply(q_, r_);\n    matrix_const_ref_t q_r_ = q_r.const_ref();\n    SCITBX_ASSERT( equality_ratio(a0_, q_r_) < thresh );\n  }\n\n  void check_lq(bool thin_q) {\n    matrix_const_ref_t a0_ = a0.const_ref();\n\n    matrix_t a = a0.deep_copy();\n    matrix_ref_t a_ = a.ref();\n\n    int m = a_.n_rows(), n=a_.n_columns();\n\n    householder::lq_decomposition<double> lq(a_);\n\n    // Get L\n    matrix_t l(dim(m, thin_q ? std::min(m,n) : n));\n    matrix_ref_t l_ = l.ref();\n    for (int j=0; j<std::min(m,n); ++j) {\n    for (int i=j; i<m; ++i)\n      l_(i,j) = a_(i,j);\n    }\n\n    // Accumulate Q out-of-place\n    matrix_t q = lq.q(thin_q);\n    matrix_const_ref_t q_ = q.const_ref();\n    SCITBX_ASSERT( normality_ratio(q_) < thresh );\n\n    // Accumulate Q in-place if it makes sense\n    if (thin_q && m <= n) {\n      lq.accumulate_q_in_place();\n      SCITBX_ASSERT( equality_ratio(q_, a_) < thresh );\n    }\n\n    // Check A = LQ\n    matrix_t l_q = af::matrix_multiply(l_, q_);\n    matrix_const_ref_t l_q_ = l_q.const_ref();\n    SCITBX_ASSERT( equality_ratio(a0_, l_q_) < thresh );\n  }\n\n  void check_bidiagonalisation(bool thin) {\n    matrix_const_ref_t a0_ = a0.const_ref();\n\n    matrix_t a = a0.deep_copy();\n    matrix_ref_t a_ = a.ref();\n\n    int m = a_.n_rows(), n=a_.n_columns();\n\n    householder::bidiagonalisation<double> bidiag(a_);\n\n    // Get B\n    matrix_t b(dim(thin ? std::min(m,n) : m, thin ? std::min(m,n) : n));\n    matrix_ref_t b_ = b.ref();\n    if (m >=n) copy_upper_bidiagonal(b_, a_);\n    else copy_lower_bidiagonal(b_, a_);\n\n    matrix_t u = bidiag.u(thin);\n    matrix_ref_t u_ = u.ref();\n\n    matrix_t v = bidiag.v(thin);\n    matrix_ref_t v_ = v.ref();\n\n    // Check that U and V are orthogonal\n    SCITBX_ASSERT( normality_ratio(u_) < thresh );\n    SCITBX_ASSERT( normality_ratio(v_) < thresh );\n\n    // Check that A = U B V^T\n    matrix_t u_b_vt = product_U_M_VT(u_, b_, v_);\n    matrix_const_ref_t u_b_vt_ = u_b_vt.const_ref();\n    SCITBX_ASSERT( equality_ratio(a0_, u_b_vt_) < thresh );\n  }\n};\n\nstruct lotkin_test_case : test_case\n{\n  lotkin_test_case(int m, int n) : test_case(m,n)\n  {\n    matrix_ref_t a_ = this->a0.ref();\n    for (int i=0; i<m; ++i) for (int j=0; j<n; ++j) {\n      a_(i,j) = i > 0 ? 1./(i+j+1) : 1;\n    }\n  }\n};\n\nstruct graded_test_case : test_case\n{\n  householder::random_normal_matrix_generator<\n    double, scitbx::boost_random::mt19937> gen;\n\n  graded_test_case(int n, double x)\n    : test_case(n,n), gen(n,n)\n  {\n    vec_t d(n), f(n-1);\n    for (int i=0; i<n; ++i) {\n      d[i] = std::pow(x, i);\n      if (i < n-1) f[i] = d[i];\n    }\n    matrix_t u = gen.normal_matrix();\n    matrix_t v = gen.normal_matrix();\n    matrix_ref_t vt_ = v.ref();\n    vt_.transpose_in_place();\n    matrix_t b = upper_bidiagonal(d.ref(), f.ref());\n    a0 = af::matrix_multiply(u.ref(), b.ref());\n    a0 = af::matrix_multiply(a0.ref(), vt_);\n  }\n};\n\nvoid exercise_householder_zeroing_vector() {\n  // Householder zeroing vector (1)\n  {\n    af::tiny<double, 4> x;\n    af::init(x) = 3, 1, 5, 1;\n    householder::reflection<double> p(x.ref());\n    af::tiny<double, 3> expected;\n    af::init(expected) = -1, -5, -1;\n    expected /= 3.;\n    af::ref<double> obtained(&p.v[0], 3);\n    SCITBX_ASSERT(approx_equal(p.beta, 0.5, tol))(p.beta);\n    SCITBX_ASSERT(expected.ref().all_approx_equal(obtained, tol));\n    af::ref<double> overwritten(&x[1], 3);\n    SCITBX_ASSERT(expected.ref().all_approx_equal(overwritten, tol));\n  }\n\n  // Householder zeroing vector (2)\n  {\n    af::tiny<double, 4> x;\n    af::init(x) = -3, 1, 5, 1;\n    householder::reflection<double> p(x.ref());\n    af::tiny<double, 3> expected;\n    af::init(expected) = -1, -5, -1;\n    expected /= 9.;\n    af::ref<double> obtained(&p.v[0], 3);\n    SCITBX_ASSERT(approx_equal(p.beta, 3./2, tol))(p.beta);\n    SCITBX_ASSERT(expected.ref().all_approx_equal(obtained, tol));\n    af::ref<double> overwritten(&x[1], 3);\n    SCITBX_ASSERT(expected.ref().all_approx_equal(overwritten, tol));\n  }\n\n  // Householder zeroing vector in-place\n  {\n    householder::reflection<double> p(4);\n    af::ref<double> v(&p.v[0], 4);\n    af::init(v) = 3, 1, 5, 1;\n    af::tiny<double, 3> expected;\n    af::init(expected) = -1, -5, -1;\n    expected /= 3.;\n    p.zero_vector(4);\n    af::ref<double> obtained(&p.v[0], 3);\n    SCITBX_ASSERT(approx_equal(p.beta, 0.5, tol))(p.beta);\n    SCITBX_ASSERT(expected.ref().all_approx_equal(obtained, tol));\n  }\n\n  // Householder zeroing matrix columns or rows\n  {\n    int const m=6, n=7;\n    matrix_t a0(dim(m,n));\n    af::init(a0) = 11, 12, 13, 14, 15, 16, 17,\n                    21, 22,  1, 24, 25, 26, 27,\n                    31, 32, -1, 34, 35, 36, 37,\n                    41, 42,  2, 44, 45, 46, 47,\n                    51, 52,  1, 54, 55, 56, 57,\n                    61, 62,  3, 64, 65, 66, 67;\n\n    matrix_t a = a0.deep_copy();\n    householder::reflection<double> p(m, n,\n                                      householder::applied_on_left_tag(),\n                                      false);\n    p.zero_vector(af::column_below(a.ref(), 1, 2));\n    p.apply_on_left_to_lower_right_block(a.ref(), 1, 3);\n    /* Mathematica:\n      a = Table[10 i + j, {i, 6}, {j, 7}];\n      a[[2 ;;, 3]] = {1, -1, 2, 1, 3};\n      a // MatrixForm\n      v = {0, 1, 1/3, -2/3, -1/3, -1};\n      beta = 3/4;\n      p = IdentityMatrix[6] - beta KroneckerProduct[v, v];\n      b = p.a;\n      b // MatrixForm\n    */\n    matrix_t expected(dim(m,n));\n    af::init(expected) =  11, 12, 13   ,  14,  15   ,  16   ,  17   ,\n                          21, 22,  4   ,  81, 165./2,  84   , 171./2,\n                          31, 32,  1./3,  53, 325./6, 166./3, 113./2,\n                          41, 42, -2./3,   6,  20./3,  22./3,   8   ,\n                          51, 52, -1./3,  35, 215./6, 110./3,  75./2,\n                          61, 62, -1.  ,   7,  15./2,   8   ,  17./2;\n    SCITBX_ASSERT(expected.all_approx_equal(a, tol));\n\n    matrix_t a_t = af::matrix_transpose(a0.ref());\n\n    householder::reflection<double> q(n, m,\n                                      householder::applied_on_right_tag(),\n                                      false);\n    q.zero_vector(af::row_right_of(a_t.ref(), 2, 1));\n    q.apply_on_right_to_lower_right_block(a_t.ref(), 3, 1);\n    SCITBX_ASSERT(matrix_transpose(expected.ref()).all_approx_equal(a_t, tol));\n  }\n}\n\nvoid exercise_householder_applied_to_symmetric_matrix() {\n  double tol = 1e-12;\n  scitbx::random::mersenne_twister rnd;\n  for (int n=2; n<10; ++n) {\n    vec_t x = rnd.random_double(n);\n    householder::reflection<double> p(\n      n, n, householder::applied_on_left_and_right_tag());\n    p.zero_vector(x.ref(), false);\n    matrix_t id_n = identity<double>(n);\n    matrix_ref_t pp = id_n.ref();\n    p.apply_on_left_to_lower_right_block(pp, 0, 0);\n\n    symmetric_matrix_packed_u_t a(n);\n    double *a_ = a.begin();\n    for (int i=0; i<n; ++i) for (int j=i; j<n; ++j) *a_++ = rnd.random_double();\n    af::const_ref<double> r(a.begin(), a.size());\n    matrix_t a1 = packed_u_as_symmetric(r);\n\n    matrix_t b1 = product_U_M_VT(pp, a1.const_ref(), pp);\n    symmetric_matrix_packed_u_t b(symmetric_as_packed_u(b1.ref(), tol), n);\n\n    p.apply_to_lower_right_block(a.ref(), 0);\n    SCITBX_ASSERT(a.all_approx_equal(b, tol));\n  }\n}\n\nvoid exercise_householder_accumulation() {\n  boost::mt19937 urng;\n  boost::uniform_int<> gen(0, 64);\n  for (int m=3; m<=6; ++m) for (int n=3; n<=6; ++n) {\n    // set up test case\n    matrix_t a(dim(m,n), -1.);\n    matrix_ref_t a_ = a.ref();\n    vec_t beta(std::min(m-1, n));\n    for (int j=0; j<std::min(m-1, n); ++j) {\n      double v2 = 1;\n      for (int i=j+1; i<m; ++i) {\n        a(i,j) = gen(urng);\n        v2 += a(i,j)*a(i,j);\n      }\n      beta[j] = 2./v2;\n    }\n    matrix_t at = af::matrix_transpose(a.ref());\n    matrix_ref_t at_ = at.ref();\n\n    // test accumulation of the thin Q if m >= n or the full Q otherwise\n\n    // on the right\n    {\n      matrix_t q(dim(m, std::min(m,n)));\n      matrix_ref_t q_ = q.ref();\n      householder::reflection<double> h(m, n,\n                                        householder::applied_on_left_tag(),\n                                        true);\n      h.accumulate_factored_form_in_columns(q_, a_, beta.ref());\n      h.accumulate_in_place_factored_form_in_columns(a_, beta.ref());\n      for (int i=0; i<q_.n_rows(); ++i)\n      for (int j=0; j<q_.n_columns(); ++j) {\n        approx_equal(q_(i,j), a_(i,j), 1e-15);\n      }\n    }\n\n    // on the left\n    {\n      std::swap(m,n);\n      int p = std::min(m,n); // <|workaround for gcc 3.3.4 compilation error\n      matrix_t q(dim(p, n)); // <|\n      matrix_ref_t q_ = q.ref();\n      householder::reflection<double> h(m, n,\n                                        householder::applied_on_right_tag(),\n                                        true);\n      h.accumulate_factored_form_in_rows(\n        q_, at_, beta.ref(), householder::product_in_reverse_row_order);\n      h.accumulate_in_place_factored_form_in_rows(at_, beta.ref());\n      for (int i=0; i<q_.n_rows(); ++i)\n      for (int j=0; j<q_.n_columns(); ++j) {\n        approx_equal(q_(i,j), at_(i,j), 1e-15);\n      }\n    }\n  }\n}\n\nvoid exercise_householder() {\n  // Householder QR (Lotkin matrix: ill-conditioned)\n  std::vector<lotkin_test_case> cases;\n\n  cases.push_back( lotkin_test_case(3,2) );\n  cases.push_back( lotkin_test_case(2,3) );\n  cases.push_back( lotkin_test_case(3,3) );\n\n  cases.push_back( lotkin_test_case(4,3) );\n  cases.push_back( lotkin_test_case(3,4) );\n  cases.push_back( lotkin_test_case(4,4) );\n\n  cases.push_back( lotkin_test_case(5,3) );\n  cases.push_back( lotkin_test_case(3,5) );\n\n  for (int i=0; i<cases.size(); ++i) {\n    lotkin_test_case &t = cases[i];\n    t.check_qr(false); // full QR\n    t.check_qr(true);  // thin QR\n    t.check_lq(false); // full LQ\n    t.check_lq(true);  // thin LQ\n  }\n\n  graded_test_case t(10, 1.e-10);\n  t.check_qr(true);\n}\n\nvoid exercise_bidiagonalisation() {\n  /* Householder bidiagonalisation (Golub and Van Loan example 5.4.2)\n     The last diagonal entry in B is zero which makes it interesting.\n     In the book, the authors used higher a precision than available on standard\n     hardware: hence the difference between their result and those obtained\n     here. But the SVD is still correct to machine precision as we assert it is.\n  */\n  {\n    matrix_t a0(dim(4,3));\n    af::init(a0) =  1,  2,  3,\n                    4,  5,  6,\n                    7,  8,  9,\n                   10, 11, 12;\n    matrix_const_ref_t a0_ = a0.const_ref();\n    matrix_t a = a0.deep_copy();\n    householder::bidiagonalisation<double> bidiag(a.ref());\n    matrix_t b(dim(4,3));\n    af::init(b) = 12.8840987267251, 21.876432827428,  0             ,\n                   0              ,  2.246235240294, -0.613281332054,\n                   0              ,  0             ,  0             ,\n                   0              ,  0             ,  0             ;\n    matrix_const_ref_t b_ = b.const_ref();\n    matrix_t u = bidiag.u(false);\n    matrix_ref_t u_ = u.ref();\n    matrix_t v = bidiag.v(false);\n    matrix_ref_t v_ = v.ref();\n    SCITBX_ASSERT( normality_ratio(u_) < 10 );\n    SCITBX_ASSERT( normality_ratio(v_) < 10 );\n    matrix_t u_b_vt = product_U_M_VT(u_, b_, v_);\n    matrix_const_ref_t u_b_vt_ = u_b_vt.const_ref();\n    SCITBX_ASSERT( equality_ratio(u_b_vt_, a0_, 1e-13) < 10 );\n  }\n  {\n    matrix_t a0(dim(3,3));\n    af::init(a0) = 24.3104915623, 0.0          , 0.0                ,\n                   26.4083512403, 1.26450969612, 0.0                ,\n                   28.5062109182, 2.52901939223, 3.74525472711e-15 ;\n    matrix_const_ref_t a0_ = a0.const_ref();\n    matrix_t a = a0.deep_copy();\n    matrix_ref_t a_ = a.ref();\n    householder::bidiagonalisation<double> bidiag(a.ref());\n    matrix_t u = bidiag.u();\n    matrix_ref_t u_ = u.ref();\n    matrix_t v = bidiag.v();\n    matrix_ref_t v_ = v.ref();\n    SCITBX_ASSERT( normality_ratio(u_) < 10 );\n    SCITBX_ASSERT( normality_ratio(v_) < 10 );\n    matrix_t b(dim(3, 3));\n    matrix_ref_t b_ = b.ref();\n    copy_upper_bidiagonal(b_, a_);\n    matrix_t u_b_vt = product_U_M_VT(u_, b_, v_);\n    matrix_const_ref_t u_b_vt_ = u_b_vt.const_ref();\n    SCITBX_ASSERT( equality_ratio(u_b_vt_, a0_, 1e-13) < 10 );\n  }\n\n  // Householder bidiagonalisation (Lotkin matrix)\n  {\n    lotkin_test_case t(7,5);\n    t.check_bidiagonalisation(true);\n    t.check_bidiagonalisation(false);\n  }\n  {\n    lotkin_test_case t(10,5);\n    t.check_bidiagonalisation(true);\n    t.check_bidiagonalisation(false);\n  }\n  {\n    lotkin_test_case t(5,5);\n    t.check_bidiagonalisation(true);\n    t.check_bidiagonalisation(false);\n  }\n  {\n    lotkin_test_case t(5,7);\n    t.check_bidiagonalisation(true);\n    t.check_bidiagonalisation(false);\n  }\n  {\n    lotkin_test_case t(5,10);\n    t.check_bidiagonalisation(true);\n    t.check_bidiagonalisation(false);\n  }\n  {\n    graded_test_case t(10, 1.e10);\n    t.check_bidiagonalisation(false);\n  }\n}\n\nint main() {\n  exercise_householder_zeroing_vector();\n  exercise_householder_applied_to_symmetric_matrix();\n  exercise_householder_accumulation();\n  exercise_householder();\n  exercise_bidiagonalisation();\n  std::cout << \"OK\\n\";\n  return 0;\n}\n", "meta": {"hexsha": "89b6e2de395abfbdde760b3e3fbd514528e33108", "size": 15073, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "scitbx/matrix/tests/tst_householder.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/matrix/tests/tst_householder.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/matrix/tests/tst_householder.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": 31.5995807128, "max_line_length": 80, "alphanum_fraction": 0.5930471704, "num_tokens": 4815, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.49390236053832887}}
{"text": "#include <limits>\n#include <vector>\n#include <gtest/gtest.h>\n\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/math/distributions.hpp>\n#include <boost/math/tools/promotion.hpp>\n\n#include <stan/math/rev.hpp>\n#include <stan/math/prim/fun/sign.hpp>\n#include <stan/math/prim/fun/fabs.hpp>\n#include <stan/math/prim/fun/log1m.hpp>\n\ntemplate <typename T1, typename T2, typename T3, typename T4>\ninline typename boost::math::tools::promote_args<T1, T2, T3, T4>::type\nskew_de_ccdf_test(const T1& y, const T2& mu, const T3& sigma, const T4& tau) {\n  using stan::math::log1m;\n  using stan::math::log1m_exp;\n  using std::exp;\n  using std::log;\n\n  if (y < mu) {\n    return log1m_exp(log(tau) - 2 / sigma * (1 - tau) * (mu - y));\n  } else {\n    return log1m_exp(log1m((1 - tau) * exp(-2 / sigma * tau * (y - mu))));\n  }\n}\n\nTEST(ProbDistributionsSkewedDoubleExponential,\n     lccdf_computes_correct_gradients) {\n  using stan::math::skew_double_exponential_lccdf;\n\n  for (double ys : {-1.7, 0.2, 0.5, 0.9, 1.1, 3.2, 8.3}) {\n    for (double mus : {-1.8, 0.1, 0.55, 0.89, 1.3, 4.2, 9.3}) {\n      for (double sigmas : {0.1, 0.5, 1.1, 10.1}) {\n        for (double taus : {0.01, 0.1, 0.5, 0.6, 0.9, 0.99}) {\n          stan::math::var y = ys;\n          stan::math::var mu = mus;\n          stan::math::var sigma = sigmas;\n          stan::math::var tau = taus;\n\n          stan::math::var lp = skew_double_exponential_lccdf(y, mu, sigma, tau);\n          std::vector<stan::math::var> theta;\n          theta.push_back(y);\n          theta.push_back(mu);\n          theta.push_back(sigma);\n          theta.push_back(tau);\n          std::vector<double> grads;\n          lp.grad(theta, grads);\n\n          stan::math::var y_true = ys;\n          stan::math::var mu_true = mus;\n          stan::math::var sigma_true = sigmas;\n          stan::math::var tau_true = taus;\n\n          stan::math::var lp_test\n              = skew_de_ccdf_test(y_true, mu_true, sigma_true, tau_true);\n          std::vector<stan::math::var> theta_true;\n          theta_true.push_back(y_true);\n          theta_true.push_back(mu_true);\n          theta_true.push_back(sigma_true);\n          theta_true.push_back(tau_true);\n          std::vector<double> grads_true;\n          lp_test.grad(theta_true, grads_true);\n\n          EXPECT_NEAR(grads_true[0], grads[0], 0.01);\n          EXPECT_NEAR(grads_true[1], grads[1], 0.01);\n          EXPECT_NEAR(grads_true[2], grads[2], 0.01);\n          EXPECT_NEAR(grads_true[3], grads[3], 0.01);\n        }\n      }\n    }\n  }\n}\n\nTEST(ProbDistributionsSkewedDoubleExponential,\n     lccdf_works_on_scalar_arguments) {\n  using stan::math::skew_double_exponential_lccdf;\n\n  for (double ys : {0.2, 0.9, 1.1, 3.2}) {\n    for (double mus : {0.1, 1.3, 3.0}) {\n      for (double sigmas : {0.1, 1.1, 3.2}) {\n        for (double taus : {0.01, 0.1, 0.5, 0.9, 0.99}) {\n          EXPECT_NEAR(skew_de_ccdf_test(ys, mus, sigmas, taus),\n                      skew_double_exponential_lccdf(ys, mus, sigmas, taus),\n                      0.001);\n        }\n      }\n    }\n  }\n}\n\nTEST(ProbDistributionsSkewedDoubleExponential,\n     lccdf_works_on_vector_arguments) {\n  using stan::math::skew_double_exponential_lccdf;\n\n  std::vector<double> ys{0.2, 0.9, 1.1, 3.2};\n\n  for (double mus : {0.1, 1.3, 3.0}) {\n    for (double sigmas : {0.1, 1.1, 3.2}) {\n      for (double taus : {0.01, 0.1, 0.5, 0.9, 0.99}) {\n        double x = 0.0;\n        for (double y : ys)\n          x += skew_de_ccdf_test(y, mus, sigmas, taus);\n        EXPECT_NEAR(x, skew_double_exponential_lccdf(ys, mus, sigmas, taus),\n                    0.001);\n      }\n    }\n  }\n}\n\nTEST(ProbDistributionsSkewedDoubleExponential,\n     lccdf_works_on_vectorial_y_and_mu) {\n  using stan::math::skew_double_exponential_lccdf;\n  std::vector<double> ys{0.2, 0.9, 1.1};\n  std::vector<double> mus{0.1, 1.3, 3.0};\n\n  for (double sigmas : {0.1, 1.1, 3.2}) {\n    for (double taus : {0.01, 0.1, 0.5, 0.9, 0.99}) {\n      double x = 0.0;\n      for (int i = 0; i < 3; i++)\n        x += skew_de_ccdf_test(ys[i], mus[i], sigmas, taus);\n\n      EXPECT_NEAR(x, skew_double_exponential_lccdf(ys, mus, sigmas, taus),\n                  0.001);\n    }\n  }\n}\n\nTEST(ProbDistributionsSkewedDoubleExponential,\n     lccdf_works_on_vectorial_y_and_sigma) {\n  using stan::math::skew_double_exponential_lccdf;\n  std::vector<double> ys{0.2, 0.9, 1.1};\n  std::vector<double> sigmas{0.1, 1.1, 3.2};\n\n  for (double mus : {0.1, 1.3, 3.0}) {\n    for (double taus : {0.01, 0.1, 0.5, 0.9, 0.99}) {\n      double x = 0.0;\n      for (int i = 0; i < 3; i++)\n        x += skew_de_ccdf_test(ys[i], mus, sigmas[i], taus);\n\n      EXPECT_NEAR(x, skew_double_exponential_lccdf(ys, mus, sigmas, taus),\n                  0.001);\n    }\n  }\n}\n\nTEST(ProbDistributionsSkewedDoubleExponential,\n     lccdf_works_on_vectorial_y_and_tau) {\n  using stan::math::skew_double_exponential_lccdf;\n  std::vector<double> ys{0.2, 0.9, 1.1};\n  std::vector<double> taus{0.1, 0.5, 0.9};\n\n  for (double mus : {0.1, 1.3, 3.0}) {\n    for (double sigmas : {0.1, 1.1, 3.2}) {\n      double x = 0.0;\n      for (int i = 0; i < 3; i++)\n        x += skew_de_ccdf_test(ys[i], mus, sigmas, taus[i]);\n\n      EXPECT_NEAR(x, skew_double_exponential_lccdf(ys, mus, sigmas, taus),\n                  0.001);\n    }\n  }\n}\n\nTEST(ProbDistributionsSkewedDoubleExponential,\n     lccdf_works_on_vectorial_mu_sigma_and_tau) {\n  using stan::math::skew_double_exponential_lccdf;\n\n  std::vector<double> mus{0.1, 1.3, 3.0};\n  std::vector<double> sigmas{0.1, 1.1, 3.2};\n  std::vector<double> taus{0.1, 0.5, 0.9};\n\n  for (double ys : {0.1, 1.3, 3.0}) {\n    double x = 0.0;\n    for (int i = 0; i < 3; i++)\n      x += skew_de_ccdf_test(ys, mus[i], sigmas[i], taus[i]);\n    EXPECT_NEAR(x, skew_double_exponential_lccdf(ys, mus, sigmas, taus), 0.001);\n  }\n}\n\nTEST(ProbDistributionsSkewedDoubleExponential, lccdf_check_errors) {\n  using stan::math::skew_double_exponential_lccdf;\n  static double inff = std::numeric_limits<double>::infinity();\n  EXPECT_THROW(stan::math::skew_double_exponential_lccdf(1.0, 0.0, -1, 0.5),\n               std::domain_error);\n  EXPECT_THROW(stan::math::skew_double_exponential_lccdf(1.0, 0.0, 0.1, -0.5),\n               std::domain_error);\n  EXPECT_THROW(stan::math::skew_double_exponential_lccdf(inff, 0.0, 0.1, 1.5),\n               std::domain_error);\n  EXPECT_THROW(stan::math::skew_double_exponential_lccdf(1.0, inff, 0.1, 1.5),\n               std::domain_error);\n}\n\nTEST(ProbDistributionsSkewedDoubleExponential, lccdf_check_inconsistent_size) {\n  using stan::math::skew_double_exponential_lccdf;\n\n  std::vector<double> mus{0.1, 1.3, 3.0};\n  std::vector<double> sigmas{0.1, 1.1, 3.2, 1.0};\n  std::vector<double> taus{0.1, 0.5, 0.9};\n  EXPECT_THROW(\n      stan::math::skew_double_exponential_lccdf(1.0, mus, sigmas, taus),\n      std::invalid_argument);\n}\n\nTEST(ProbDistributionsSkewedDoubleExponential, cdf_log_matches_lccdf) {\n  double y = 0.8;\n  double mu = 2;\n  double sigma = 2.3;\n  double tau = 0.1;\n\n  EXPECT_FLOAT_EQ(\n      (stan::math::skew_double_exponential_lccdf(y, mu, sigma, tau)),\n      (stan::math::skew_double_exponential_ccdf_log(y, mu, sigma, tau)));\n  EXPECT_FLOAT_EQ(\n      (stan::math::skew_double_exponential_lccdf<double, double, double,\n                                                 double>(y, mu, sigma, tau)),\n      (stan::math::skew_double_exponential_ccdf_log<double, double, double,\n                                                    double>(y, mu, sigma,\n                                                            tau)));\n}\n", "meta": {"hexsha": "b324b1ca5bd7246aba69df4a37c0667a9a5d277a", "size": 7498, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/prim/prob/skew_double_exponential_ccdf_log_test.cpp", "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": "test/unit/math/prim/prob/skew_double_exponential_ccdf_log_test.cpp", "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": "test/unit/math/prim/prob/skew_double_exponential_ccdf_log_test.cpp", "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": 33.7747747748, "max_line_length": 80, "alphanum_fraction": 0.6037610029, "num_tokens": 2584, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4939023605383288}}
{"text": "#ifndef INCLUDE_SWIFT_VIO_SIMPLE_IMU_ODOMETRY_HPP_\n#define INCLUDE_SWIFT_VIO_SIMPLE_IMU_ODOMETRY_HPP_\n\n#include <Eigen/Core>\n#include <swift_vio/Measurements.hpp>\n\n#include <okvis/kinematics/Transformation.hpp>\n#include <okvis/kinematics/operators.hpp>\n#include <okvis/FrameTypedefs.hpp>\n#include <okvis/ImuMeasurements.hpp>\n#include <okvis/Variables.hpp>\n#include <okvis/assert_macros.hpp>\n\nnamespace swift_vio {\nnamespace ode {\ntemplate<typename Scalar>\nint predictStates(const GenericImuMeasurementDeque<Scalar> & imuMeasurements,\n            const Scalar gravityMag,\n            std::pair<Eigen::Matrix<Scalar, 3, 1>, Eigen::Quaternion<Scalar>> &T_WS,\n            Eigen::Matrix<Scalar, 9,1>& speedBgBa,\n            const Scalar t_start, const Scalar t_end)\n{\n    Eigen::Matrix<Scalar, 3,1> r_old(T_WS.first), r_new(r_old), v_old(speedBgBa.template head<3>()), v_new(v_old);\n    Eigen::Quaternion<Scalar> q_old(T_WS.second.conjugate()), q_new(q_old); //rotation from world to sensor\n    assert(imuMeasurements.front().timeStamp <= t_start && imuMeasurements.back().timeStamp >= t_end);\n\n    Scalar time = t_start;\n    Scalar end = t_end;\n    Scalar Delta_t = Scalar(0);\n    bool hasStarted = false;\n    int i = 0;\n    Scalar nexttime;\n    for(typename GenericImuMeasurementDeque<Scalar>::const_iterator it = imuMeasurements.begin();\n          it != imuMeasurements.end(); ++it) {\n\n      Eigen::Matrix<Scalar,3,1> omega_S_0 = it->template gyroscopes;\n      Eigen::Matrix<Scalar,3,1> acc_S_0 = it->template accelerometers;\n      Eigen::Matrix<Scalar,3,1> omega_S_1 = (it + 1)->template gyroscopes;\n      Eigen::Matrix<Scalar,3,1> acc_S_1 = (it + 1)->template accelerometers;\n\n      // time delta\n      if ((it + 1) == imuMeasurements.end()) {\n        nexttime = t_end;\n      } else\n        nexttime = (it + 1)->timeStamp;\n      Scalar dt = nexttime - time;\n\n      if (end < nexttime) {\n        Scalar interval = nexttime - it->timeStamp;\n        nexttime = t_end;\n        dt = nexttime - time;\n        if (dt == 0.0)\n            break;\n        const Scalar r = dt / interval;\n        omega_S_1 = ((Scalar(1.0) - r) * omega_S_0 + r * omega_S_1).eval();\n        acc_S_1 = ((Scalar(1.0) - r) * acc_S_0 + r * acc_S_1).eval();\n      }\n\n      if (dt <= Scalar(0.0)) {\n        continue;\n      }\n      Delta_t += dt;\n\n      if (!hasStarted) {\n        hasStarted = true;\n        const Scalar r = dt / (nexttime - it->timeStamp);\n        omega_S_0 = (r * omega_S_0 + (Scalar(1.0) - r) * omega_S_1).eval();\n        acc_S_0 = (r * acc_S_0 + (Scalar(1.0) - r) * acc_S_1).eval();\n      }\n\n      // actual propagation\n      Eigen::Matrix<Scalar,3,1> a_est = Scalar(0.5)*(acc_S_0+acc_S_1) - speedBgBa.template tail<3>();\n      Eigen::Matrix<Scalar,3,1> w_est = Scalar(0.5)*(omega_S_0+omega_S_1) - speedBgBa.template segment<3>(3);\n      Eigen::Matrix<Scalar,3,1> gW(Scalar(0), Scalar(0), -gravityMag);\n\n      Eigen::Quaternion<Scalar> qb = okvis::kinematics::rvec2quat(-w_est*dt);\n      q_new=qb*q_old;\n\n      Eigen::Matrix<Scalar,3,1> vel_inc1=(q_old.conjugate()._transformVector(a_est*dt)+q_new.conjugate()._transformVector(a_est*dt))*Scalar(0.5);\n      Eigen::Matrix<Scalar,3,1> vel_inc2=gW*dt;\n\n      v_new= v_old + vel_inc1+vel_inc2;\n      r_new= r_old + (v_new+v_old)*dt*Scalar(0.5);\n\n      time = nexttime;\n      ++i;\n\n      if (nexttime == t_end)\n        break;\n\n      r_old=r_new;\n      v_old=v_new;\n      q_old=q_new;\n    }\n    assert(nexttime == t_end);\n\n    T_WS.second = q_new.conjugate();\n    T_WS.first = r_new;\n    speedBgBa. template head<3>()=v_new;\n    return i;\n}\n\n/**\n * @brief predictStates accumulate the rotation vector given gyro measurements.\n * i.e., \\f$ \\int_{t_1}^{t_2} \\hat{\\omega} - \\mathbf{b}_g \\f$\n */\ntemplate <typename Scalar>\nint predictStates(\n    const std::deque<\n        okvis::Measurement<Eigen::Vector3d>,\n        Eigen::aligned_allocator<okvis::Measurement<Eigen::Vector3d>>>\n        &gyroMeasurements,\n    Eigen::Vector3d *rotVector, const Eigen::Matrix<Scalar, 3, 1> &gyroBias,\n    const okvis::Time t_start, const okvis::Time t_end) {\n  rotVector->setZero();\n  assert(gyroMeasurements.front().timeStamp <= t_start &&\n         gyroMeasurements.back().timeStamp >= t_end);\n\n  okvis::Time time = t_start;\n  okvis::Time end = t_end;\n  Scalar Delta_t = Scalar(0);\n  bool hasStarted = false;\n  int i = 0;\n  okvis::Time nexttime;\n  for (typename std::deque<okvis::Measurement<Eigen::Vector3d>,\n                           Eigen::aligned_allocator<okvis::Measurement<\n                               Eigen::Vector3d>>>::const_iterator it =\n           gyroMeasurements.begin();\n       it != gyroMeasurements.end(); ++it) {\n    Eigen::Matrix<Scalar, 3, 1> omega_S_0 = it->measurement;\n    Eigen::Matrix<Scalar, 3, 1> omega_S_1 = (it + 1)->measurement;\n    // time delta\n    if ((it + 1) == gyroMeasurements.end()) {\n      nexttime = t_end;\n    } else\n      nexttime = (it + 1)->timeStamp;\n\n    Scalar dt = (Scalar)(nexttime - time).toSec();\n    if (end < nexttime) {\n      Scalar interval = (Scalar)(nexttime - it->timeStamp).toSec();\n      nexttime = t_end;\n      dt = (Scalar)(nexttime - time).toSec();\n      if (dt == 0.0)\n        break;\n      const Scalar r = dt / interval;\n      omega_S_1 = ((Scalar(1.0) - r) * omega_S_0 + r * omega_S_1).eval();\n    }\n\n    if (dt <= Scalar(0.0)) {\n      continue;\n    }\n    Delta_t += dt;\n\n    if (!hasStarted) {\n      hasStarted = true;\n      const Scalar r = dt / ((Scalar)(nexttime - it->timeStamp).toSec());\n      omega_S_0 = (r * omega_S_0 + (Scalar(1.0) - r) * omega_S_1).eval();\n    }\n\n    // actual propagation\n    Eigen::Matrix<Scalar, 3, 1> w_est =\n        Scalar(0.5) * (omega_S_0 + omega_S_1) - gyroBias;\n    (*rotVector) += w_est * dt;\n\n    time = nexttime;\n    ++i;\n\n    if (nexttime == t_end)\n      break;\n  }\n  assert(nexttime == t_end);\n  return i;\n}\n\n// time_pair[0] timestamp of the provided state values. time_pair[0] >= time_pair[1],\ntemplate<typename Scalar>\nint predictStatesBackward(const GenericImuMeasurementDeque<Scalar> & imuMeasurements,\n                    const Scalar gravityMag,\n                    std::pair<Eigen::Matrix<Scalar, 3, 1>, Eigen::Quaternion<Scalar>> &T_WS,\n                    Eigen::Matrix<Scalar, 9,1>& speedBgBa,\n                    const Scalar t_start, const Scalar t_end)\n{\n    Eigen::Matrix<Scalar, 3,1> r_old(T_WS.first), r_new(r_old), v_old(speedBgBa.template head<3>()), v_new(v_old);\n    Eigen::Quaternion<Scalar> q_old(T_WS.second.conjugate()), q_new(q_old); //rotation from world to sensor\n    assert(imuMeasurements.front().timeStamp <= t_end && imuMeasurements.back().timeStamp >= t_start);\n\n    Scalar time = t_start;\n    Scalar end = t_end;\n    Scalar Delta_t = Scalar(0);\n    bool hasStarted = false;\n    int i = 0;\n    Scalar nexttime;\n    for(typename GenericImuMeasurementDeque<Scalar>::const_reverse_iterator it = imuMeasurements.rbegin();\n          it != imuMeasurements.rend(); ++it) {\n\n      Eigen::Matrix<Scalar,3,1> omega_S_0 = it->template gyroscopes;\n      Eigen::Matrix<Scalar,3,1> acc_S_0 = it->template accelerometers;\n      Eigen::Matrix<Scalar,3,1> omega_S_1 = (it + 1)->template gyroscopes;\n      Eigen::Matrix<Scalar,3,1> acc_S_1 = (it + 1)->template accelerometers;\n\n      // time delta\n      if ((it + 1) == imuMeasurements.rend()) {\n        nexttime = t_end;\n      } else\n        nexttime = (it + 1)->timeStamp;\n      Scalar dt = nexttime - time;\n\n      if (end > nexttime) {\n        Scalar interval = nexttime - it->timeStamp;\n        nexttime = t_end;\n        dt = nexttime - time;\n        if (dt == 0.0)\n            break;\n        const Scalar r = dt / interval;\n        omega_S_1 = ((Scalar(1.0) - r) * omega_S_0 + r * omega_S_1).eval();\n        acc_S_1 = ((Scalar(1.0) - r) * acc_S_0 + r * acc_S_1).eval();\n      }\n\n      if (dt >= Scalar(0.0)) {\n        continue;\n      }\n      Delta_t += dt;\n\n      if (!hasStarted) {\n        hasStarted = true;\n        const Scalar r = dt / (nexttime - it->timeStamp);\n        omega_S_0 = (r * omega_S_0 + (Scalar(1.0) - r) * omega_S_1).eval();\n        acc_S_0 = (r * acc_S_0 + (Scalar(1.0) - r) * acc_S_1).eval();\n      }\n\n      // actual propagation\n\n      Eigen::Matrix<Scalar,3,1> a_est = Scalar(0.5)*(acc_S_0+acc_S_1) - speedBgBa.template tail<3>();\n      Eigen::Matrix<Scalar,3,1> w_est = Scalar(0.5)*(omega_S_0+omega_S_1) - speedBgBa.template segment<3>(3);\n      Eigen::Matrix<Scalar,3,1> gW(Scalar(0), Scalar(0), -gravityMag);\n\n      Eigen::Quaternion<Scalar> qb = okvis::kinematics::rvec2quat(-w_est*dt);\n      q_new=qb*q_old;\n\n      Eigen::Matrix<Scalar,3,1> vel_inc1=(q_old.conjugate()._transformVector(a_est*dt)+q_new.conjugate()._transformVector(a_est*dt))*Scalar(0.5);\n      Eigen::Matrix<Scalar,3,1> vel_inc2=gW*dt;\n\n      v_new= v_old + vel_inc1+vel_inc2;\n      r_new= r_old + (v_new+v_old)*dt*Scalar(0.5);\n\n      time = nexttime;\n      ++i;\n\n      if (nexttime == t_end)\n        break;\n\n      r_old=r_new;\n      v_old=v_new;\n      q_old=q_new;\n    }\n    assert(nexttime == t_end);\n\n    T_WS.second = q_new.conjugate();\n    T_WS.first = r_new;\n    speedBgBa.template head<3>()=v_new;\n    return i;\n}\n\ntemplate<typename Scalar>\nint predictStates(const okvis::ImuMeasurementDeque & imuMeasurements,\n            const Scalar gravityMag,\n            std::pair<Eigen::Matrix<Scalar, 3, 1>, Eigen::Quaternion<Scalar>> &T_WS,\n            Eigen::Matrix<Scalar, 9,1>& speedBgBa,\n            const okvis::Time t_start, const okvis::Time t_end)\n{\n    Eigen::Matrix<Scalar, 3,1> r_old(T_WS.first), r_new(r_old), v_old(speedBgBa.template head<3>()), v_new(v_old);\n    Eigen::Quaternion<Scalar> q_old(T_WS.second.conjugate()), q_new(q_old); //rotation from world to sensor\n    assert(imuMeasurements.front().timeStamp <= t_start && imuMeasurements.back().timeStamp >= t_end);\n\n    okvis::Time time = t_start;\n    okvis::Time end = t_end;\n    Scalar Delta_t = Scalar(0);\n    bool hasStarted = false;\n    int i = 0;\n    okvis::Time nexttime;\n    for(typename okvis::ImuMeasurementDeque::const_iterator it = imuMeasurements.begin();\n          it != imuMeasurements.end(); ++it) {\n\n      Eigen::Matrix<Scalar,3,1> omega_S_0 = it->measurement.gyroscopes;\n      Eigen::Matrix<Scalar,3,1> acc_S_0 = it->measurement.accelerometers;\n      Eigen::Matrix<Scalar,3,1> omega_S_1 = (it + 1)->measurement.gyroscopes;\n      Eigen::Matrix<Scalar,3,1> acc_S_1 = (it + 1)->measurement.accelerometers;\n\n      // time delta\n      if ((it + 1) == imuMeasurements.end()) {\n        nexttime = t_end;\n      } else\n        nexttime = (it + 1)->timeStamp;\n\n      Scalar dt = (Scalar)(nexttime - time).toSec();\n\n      if (end < nexttime) {\n        Scalar interval = (Scalar)(nexttime - it->timeStamp).toSec();\n        nexttime = t_end;\n        dt =(Scalar)(nexttime - time).toSec();\n        if (dt == 0.0)\n            break;\n        const Scalar r = dt / interval;\n        omega_S_1 = ((Scalar(1.0) - r) * omega_S_0 + r * omega_S_1).eval();\n        acc_S_1 = ((Scalar(1.0) - r) * acc_S_0 + r * acc_S_1).eval();\n      }\n\n      if (dt <= Scalar(0.0)) {\n        continue;\n      }\n      Delta_t += dt;\n\n      if (!hasStarted) {\n        hasStarted = true;\n        const Scalar r = dt / ((Scalar)(nexttime - it->timeStamp).toSec());\n        omega_S_0 = (r * omega_S_0 + (Scalar(1.0) - r) * omega_S_1).eval();\n        acc_S_0 = (r * acc_S_0 + (Scalar(1.0) - r) * acc_S_1).eval();\n      }\n\n      // actual propagation\n      Eigen::Matrix<Scalar,3,1> a_est = Scalar(0.5)*(acc_S_0+acc_S_1) - speedBgBa.template tail<3>();\n      Eigen::Matrix<Scalar,3,1> w_est = Scalar(0.5)*(omega_S_0+omega_S_1) - speedBgBa.template segment<3>(3);\n      Eigen::Matrix<Scalar,3,1> gW(Scalar(0), Scalar(0), -gravityMag);\n\n      Eigen::Quaternion<Scalar> qb = okvis::kinematics::rvec2quat(-w_est*dt);\n      q_new=qb*q_old;\n\n      Eigen::Matrix<Scalar,3,1> vel_inc1=(q_old.conjugate()._transformVector(a_est*dt)+q_new.conjugate()._transformVector(a_est*dt))*Scalar(0.5);\n      Eigen::Matrix<Scalar,3,1> vel_inc2=gW*dt;\n\n      v_new= v_old + vel_inc1+vel_inc2;\n      r_new= r_old + (v_new+v_old)*dt*Scalar(0.5);\n\n      time = nexttime;\n      ++i;\n\n      if (nexttime == t_end)\n        break;\n\n      r_old=r_new;\n      v_old=v_new;\n      q_old=q_new;\n    }\n    assert(nexttime == t_end);\n\n    T_WS.second = q_new.conjugate();\n    T_WS.first = r_new;\n    speedBgBa. template head<3>()=v_new;\n    return i;\n}\n\n// time_pair[0] timestamp of the provided state values. time_pair[0] >= time_pair[1],\ntemplate<typename Scalar>\nint predictStatesBackward(const okvis::ImuMeasurementDeque & imuMeasurements,\n                    const Scalar gravityMag,\n                    std::pair<Eigen::Matrix<Scalar, 3, 1>, Eigen::Quaternion<Scalar>> &T_WS,\n                    Eigen::Matrix<Scalar, 9,1>& speedBgBa,\n                    const okvis::Time t_start, const okvis::Time t_end)\n{\n    Eigen::Matrix<Scalar, 3,1> r_old(T_WS.first), r_new(r_old), v_old(speedBgBa.template head<3>()), v_new(v_old);\n    Eigen::Quaternion<Scalar> q_old(T_WS.second.conjugate()), q_new(q_old); //rotation from world to sensor\n    assert(imuMeasurements.front().timeStamp <= t_end && imuMeasurements.back().timeStamp >= t_start);\n    // if this assertion fails during optimization, it often means the time offset variables diverge. Solution:\n    // either try to enlarge the range of imu reading segment, or decrease the time variables' std to effectively lock them\n\n    okvis::Time time = t_start;\n    okvis::Time end = t_end;\n    Scalar Delta_t = Scalar(0);\n    bool hasStarted = false;\n    int i = 0;\n    okvis::Time nexttime;\n    for(typename okvis::ImuMeasurementDeque::const_reverse_iterator it = imuMeasurements.rbegin();\n          it != imuMeasurements.rend(); ++it) {\n\n      Eigen::Matrix<Scalar,3,1> omega_S_0 = it->measurement.gyroscopes;\n      Eigen::Matrix<Scalar,3,1> acc_S_0 = it->measurement.accelerometers;\n      Eigen::Matrix<Scalar,3,1> omega_S_1 = (it + 1)->measurement.gyroscopes;\n      Eigen::Matrix<Scalar,3,1> acc_S_1 = (it + 1)->measurement.accelerometers;\n\n      // time delta\n      if ((it + 1) == imuMeasurements.rend()) {\n        nexttime = t_end;\n      } else\n        nexttime = (it + 1)->timeStamp;\n      Scalar dt = (Scalar)(nexttime - time).toSec();\n\n      if (end > nexttime) {\n        Scalar interval = (Scalar)(nexttime - it->timeStamp).toSec();\n        nexttime = t_end;\n        dt = (Scalar)(nexttime - time).toSec();\n        if (dt == 0.0)\n            break;\n        const Scalar r = dt / interval;\n        omega_S_1 = ((Scalar(1.0) - r) * omega_S_0 + r * omega_S_1).eval();\n        acc_S_1 = ((Scalar(1.0) - r) * acc_S_0 + r * acc_S_1).eval();\n      }\n\n      if (dt >= Scalar(0.0)) {\n        continue;\n      }\n      Delta_t += dt;\n\n      if (!hasStarted) {\n        hasStarted = true;\n        const Scalar r = dt / ((Scalar)(nexttime - it->timeStamp).toSec());\n        omega_S_0 = (r * omega_S_0 + (Scalar(1.0) - r) * omega_S_1).eval();\n        acc_S_0 = (r * acc_S_0 + (Scalar(1.0) - r) * acc_S_1).eval();\n      }\n\n      // actual propagation\n\n      Eigen::Matrix<Scalar,3,1> a_est = Scalar(0.5)*(acc_S_0+acc_S_1) - speedBgBa.template tail<3>();\n      Eigen::Matrix<Scalar,3,1> w_est = Scalar(0.5)*(omega_S_0+omega_S_1) - speedBgBa.template segment<3>(3);\n      Eigen::Matrix<Scalar,3,1> gW(Scalar(0), Scalar(0), -gravityMag);\n\n      Eigen::Quaternion<Scalar> qb = okvis::kinematics::rvec2quat(-w_est*dt);\n      q_new=qb*q_old;\n\n      Eigen::Matrix<Scalar,3,1> vel_inc1=(q_old.conjugate()._transformVector(a_est*dt)+q_new.conjugate()._transformVector(a_est*dt))*Scalar(0.5);\n      Eigen::Matrix<Scalar,3,1> vel_inc2=gW*dt;\n\n      v_new= v_old + vel_inc1+vel_inc2;\n      r_new= r_old + (v_new+v_old)*dt*Scalar(0.5);\n\n      time = nexttime;\n      ++i;\n\n      if (nexttime == t_end)\n        break;\n\n      r_old=r_new;\n      v_old=v_new;\n      q_old=q_new;\n    }\n    assert(nexttime == t_end);\n\n    T_WS.second = q_new.conjugate();\n    T_WS.first = r_new;\n    speedBgBa.template head<3>()=v_new;\n    return i;\n}\n\n// linear interpolation\ninline void interpolateInertialData(const okvis::ImuMeasurementDeque &imuMeas,\n                                    const okvis::Time &queryTime,\n                                    okvis::ImuMeasurement &queryValue) {\n  auto iterLeft = imuMeas.begin(), iterRight = imuMeas.end();\n  if (iterLeft->timeStamp > queryTime)\n    throw std::runtime_error(\"iterLeft->timeStamp > queryTime: Imu \"\n                             \"measurements has wrong timestamps\");\n  for (auto iter = imuMeas.begin(); iter != imuMeas.end(); ++iter) {\n    if (iter->timeStamp < queryTime) {\n      iterLeft = iter;\n    } else if (iter->timeStamp == queryTime) {\n      queryValue = *iter;\n      return;\n    } else {\n      iterRight = iter;\n      break;\n    }\n  }\n  double ratio = (queryTime - iterLeft->timeStamp).toSec() /\n                 (iterRight->timeStamp - iterLeft->timeStamp).toSec();\n  queryValue.timeStamp = queryTime;\n  Eigen::Vector3d omega_S0 =\n      (iterRight->measurement.gyroscopes - iterLeft->measurement.gyroscopes) *\n          ratio +\n      iterLeft->measurement.gyroscopes;\n  Eigen::Vector3d acc_S0 = (iterRight->measurement.accelerometers -\n                            iterLeft->measurement.accelerometers) *\n                               ratio +\n                           iterLeft->measurement.accelerometers;\n  queryValue.measurement.gyroscopes = omega_S0;\n  queryValue.measurement.accelerometers = acc_S0;\n}\n}  // namespace ode\n}  // namespace swift_vio\n#endif\n\n", "meta": {"hexsha": "795ad6f1d517f37a044e46e1595cafbbbf1ed91d", "size": 17430, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "okvis_ceres/include/swift_vio/imu/SimpleImuOdometry.hpp", "max_stars_repo_name": "wbl1997/okvis", "max_stars_repo_head_hexsha": "65e30d6ab25380d65c96c665485148e2ab55e93e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "okvis_ceres/include/swift_vio/imu/SimpleImuOdometry.hpp", "max_issues_repo_name": "wbl1997/okvis", "max_issues_repo_head_hexsha": "65e30d6ab25380d65c96c665485148e2ab55e93e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "okvis_ceres/include/swift_vio/imu/SimpleImuOdometry.hpp", "max_forks_repo_name": "wbl1997/okvis", "max_forks_repo_head_hexsha": "65e30d6ab25380d65c96c665485148e2ab55e93e", "max_forks_repo_licenses": ["BSD-3-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.3125, "max_line_length": 145, "alphanum_fraction": 0.611589214, "num_tokens": 5135, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4939023605383288}}
{"text": "/* Copyright (C) 2012-2017 IBM Corp.\n * This program is Licensed under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *   http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License. See accompanying LICENSE file.\n */\n\n/* Test_matmul.cpp - Testing the functionality of multiplying an encrypted\n * vector by a plaintext matrix, either over the extension- or the\n * base-field/ring.\n */\n\n#include <cassert>\n#include <NTL/lzz_pXFactoring.h>\n#include \"FHE.h\"\n#include \"timing.h\"\n#include \"EncryptedArray.h\"\n#include \"matmul.h\"\n\nstatic MatMulBase* buildRandomMatrix(EncryptedArray& ea);\nstatic MatMulBase* buildRandomBlockMatrix(const EncryptedArray& ea);\n\n\nvoid  TestIt(long m, long p, long r, long d, long L, bool verbose)\n{\n  cout << \"*** TestIt: m=\" << m\n       << \", p=\" << p\n       << \", r=\" << r\n       << \", d=\" << d\n       << \", L=\" << L\n       << endl;\n\n  FHEcontext context(m, p, r);\n  buildModChain(context, L, /*c=*/3);\n\n  FHESecKey secretKey(context);\n  const FHEPubKey& publicKey = secretKey;\n  secretKey.GenSecKey(/*w=*/64); // A Hamming-weight-w secret key\n\n  ZZX G;\n  if (d == 0)\n    G = context.alMod.getFactorsOverZZ()[0];\n  else\n    G = makeIrredPoly(p, d); \n\n  if (verbose) {\n    context.zMStar.printout();\n    cout << endl;\n    cout << \"G = \" << G << \"\\n\";\n  }\n\n  addSome1DMatrices(secretKey); // compute key-switching matrices that we need\n  addFrbMatrices(secretKey); // compute key-switching matrices that we need\n  EncryptedArray ea(context, G);\n\n  // Test a \"dense\" matrix over the extension field\n  {\n    // choose a random plaintext square matrix\n    unique_ptr<MatMulBase> ptr(buildRandomMatrix(ea));\n\n    // choose a random plaintext vector\n    NewPlaintextArray v(ea);\n    random(ea, v);\n\n    // encrypt the random vector\n    Ctxt ctxt(publicKey);\n    ea.encrypt(ctxt, publicKey, v);\n    Ctxt ctxt2 = ctxt;\n\n    cout << \" Multiplying with MatMulBase... \" << std::flush;\n    matMul(ctxt2, *ptr, cachezzX); // multiply ciphertext and build cache\n    matMul(v, *ptr);     // multiply the plaintext vector\n\n    NewPlaintextArray v1(ea);\n    ea.decrypt(ctxt2, secretKey, v1); // decrypt the ciphertext vector\n\n    if (equals(ea, v, v1))        // check that we've got the right answer\n      cout << \"Nice!!\\n\";\n    else\n      cout << \"Grrr@*\\n\";\n\n    cout << \" Multiplying with MatMulBase+dcrt cache... \" << std::flush;\n    ctxt2 = ctxt;\n    matMul(ctxt2, *ptr, cacheDCRT); // upgrade cache and use in multiplication\n\n    ea.decrypt(ctxt2, secretKey, v1); // decrypt the ciphertext vector\n\n    if (equals(ea, v, v1))        // check that we've got the right answer\n      cout << \"Nice!!\\n\";\n    else\n      cout << \"Grrr@*\\n\";\n  }\n  {\n    // choose a random plaintext square matrix\n    unique_ptr<MatMulBase> ptr(buildRandomMatrix(ea));\n\n    // choose a random plaintext vector\n    NewPlaintextArray v(ea);\n    random(ea, v);\n\n    // encrypt the random vector\n    Ctxt ctxt(publicKey);\n    ea.encrypt(ctxt, publicKey, v);\n    cout << \" Multiplying with MatMulBase+zzx cache... \" << std::flush;\n    buildCache4MatMul(*ptr, cachezzX);// build the cache\n    matMul(ctxt, *ptr);               // then use it\n    matMul(v, *ptr);     // multiply the plaintext vector\n\n    NewPlaintextArray v1(ea);\n    ea.decrypt(ctxt, secretKey, v1); // decrypt the ciphertext vector\n\n    if (equals(ea, v, v1))        // check that we've got the right answer\n      cout << \"Nice!!\\n\";\n    else\n      cout << \"Grrr@*\\n\";\n  }\n  // Test a \"diagonal sparse\" matrix over the extension field\n  {\n    // choose a random plaintext square matrix\n    unique_ptr<MatMulBase> ptr(buildRandomMatrix(ea));\n\n    // choose a random plaintext vector\n    NewPlaintextArray v(ea);\n    random(ea, v);\n\n    // encrypt the random vector\n    Ctxt ctxt(publicKey);\n    ea.encrypt(ctxt, publicKey, v);\n    Ctxt ctxt2 = ctxt;\n\n    cout << \"\\n Multiplying with Sparse MatMulBase... \" << std::flush;\n    matMul_sparse(ctxt2, *ptr, cachezzX); // multiply ciphertext and build cache\n    matMul(v, *ptr);     // multiply the plaintext vector\n\n    NewPlaintextArray v1(ea);\n    ea.decrypt(ctxt2, secretKey, v1); // decrypt the ciphertext vector\n\n    if (equals(ea, v, v1))        // check that we've got the right answer\n      cout << \"Nice!!\\n\";\n    else\n      cout << \"Grrr@*\\n\";\n\n    cout << \" Multiplying with Sparse MatMulBase+dcrt cache... \" << std::flush;\n    ctxt2 = ctxt;\n    matMul_sparse(ctxt2, *ptr, cacheDCRT); // upgrade the cache\n\n    ea.decrypt(ctxt2, secretKey, v1); // decrypt the ciphertext vector\n\n    if (equals(ea, v, v1))        // check that we've got the right answer\n      cout << \"Nice!!\\n\";\n    else\n      cout << \"Grrr@*\\n\";\n  }\n  {\n    // choose a random plaintext square matrix\n    unique_ptr<MatMulBase> ptr(buildRandomMatrix(ea));\n\n    // choose a random plaintext vector\n    NewPlaintextArray v(ea);\n    random(ea, v);\n\n    // encrypt the random vector\n    Ctxt ctxt(publicKey);\n    ea.encrypt(ctxt, publicKey, v);\n\n    cout << \" Multiplying with Sparse MatMulBase+zzx cache... \" << std::flush;\n    buildCache4MatMul_sparse(*ptr, cachezzX); // build the cache\n    matMul_sparse(ctxt, *ptr);                // then use it\n    matMul(v, *ptr);                          // multiply plaintext vector\n\n    NewPlaintextArray v1(ea);\n    ea.decrypt(ctxt, secretKey, v1); // decrypt the ciphertext vector\n\n    if (equals(ea, v, v1))        // check that we've got the right answer\n      cout << \"Nice!!\\n\";\n    else\n      cout << \"Grrr@*\\n\";\n  }\n\n  // Test a \"block matrix\" over the base field\n  {\n    // choose a random plaintext square matrix\n    std::unique_ptr<MatMulBase> ptr(buildRandomBlockMatrix(ea));\n\n    // choose a random plaintext vector\n    NewPlaintextArray v(ea);\n    random(ea, v);\n\n    // encrypt the random vector\n    Ctxt ctxt(publicKey);\n    ea.encrypt(ctxt, publicKey, v);\n    Ctxt ctxt2 = ctxt;\n\n    cout << \"\\n Multiplying with BlockMatMul... \"  << std::flush;\n    blockMatMul(ctxt2, *ptr, cachezzX); // multiply ciphertext and build cache\n    blockMatMul(v, *ptr);      // multiply the plaintext vector\n\n    NewPlaintextArray v1(ea);\n    ea.decrypt(ctxt2, secretKey, v1); // decrypt the ciphertext vector\n\n    if (equals(ea, v, v1))        // check that we've got the right answer\n      cout << \"Nice!!\\n\";\n    else\n      cout << \"Grrr...\\n\";\n\n    cout << \" Multiplying with BlockMatMul+dcrt cache... \" << std::flush;\n    ctxt2 = ctxt;\n    blockMatMul(ctxt2, *ptr, cacheDCRT); // upgrade the cache\n\n    ea.decrypt(ctxt2, secretKey, v1); // decrypt the ciphertext vector\n    if (equals(ea, v, v1))        // check that we've got the right answer\n      cout << \"Nice!!\\n\";\n    else\n      cout << \"Grrr@*\\n\";\n  }\n  {\n    // choose a random plaintext square matrix\n    std::unique_ptr<MatMulBase> ptr(buildRandomBlockMatrix(ea));\n\n    // choose a random plaintext vector\n    NewPlaintextArray v(ea);\n    random(ea, v);\n\n    // encrypt the random vector\n    Ctxt ctxt(publicKey);\n    ea.encrypt(ctxt, publicKey, v);\n\n    cout << \" Multiplying with BlockMatMul+zzx cache... \" << std::flush;\n    buildCache4BlockMatMul(*ptr, cachezzX); // build the cache\n    blockMatMul(ctxt, *ptr);                // then use it\n    blockMatMul(v, *ptr);     // multiply the plaintext vector\n\n    NewPlaintextArray v1(ea);\n    ea.decrypt(ctxt, secretKey, v1); // decrypt the ciphertext vector\n\n    if (equals(ea, v, v1))        // check that we've got the right answer\n      cout << \"Nice!!\\n\";\n    else\n      cout << \"Grrr@*\\n\";\n  }\n}\n\n\nvoid usage(char *prog) \n{\n  cout << \"Usage: \"<<prog<<\" [ optional parameters ]...\\n\";\n  cout << \"  optional parameters have the form 'attr1=val1 attr2=val2 ...'\\n\";\n  cout << \"  e.g, 'm=2047 p=2 L=4'\\n\\n\";\n  cout << \"  m defines the cyclotomic polynomial Phi_m(X)\\n\";\n  cout << \"  p is the plaintext base [default=2]\" << endl;\n  cout << \"  r is the lifting [default=1]\" << endl;\n  cout << \"  d is the degree of the field extension [default==1]\\n\";\n  cout << \"    (d == 0 => factors[0] defined the extension)\\n\";\n  cout << \"  L is the # of primes in the modulus chain [default=4]\\n\";\n  cout << \"  verbose print timing info [default=0]\\n\";\n  exit(0);\n}\n\n/* Testing the functionality of multiplying an encrypted vector by a plaintext\n * matrix, either over the extension- or the base-field/ring.\n */\nint main(int argc, char *argv[]) \n{\n  argmap_t argmap;\n  argmap[\"m\"] = \"2047\";\n  argmap[\"p\"] = \"2\";\n  argmap[\"r\"] = \"1\";\n  argmap[\"d\"] = \"1\";\n  argmap[\"L\"] = \"4\";\n  argmap[\"verbose\"] = \"0\";\n\n  // get parameters from the command line\n  if (!parseArgs(argc, argv, argmap)) usage(argv[0]);\n\n  long m = atoi(argmap[\"m\"]);\n  long p = atoi(argmap[\"p\"]);\n  long r = atoi(argmap[\"r\"]);\n  long d = atoi(argmap[\"d\"]);\n  long L = atoi(argmap[\"L\"]);\n  bool v = atoi(argmap[\"verbose\"]);\n\n  //  setTimersOn();\n  setTimersOn();\n  TestIt(m, p, r, d, L, v);\n  cout << endl;\n  if (v) {\n    printAllTimers();\n    cout << endl;\n  }\n}\n\n\n\n\ntemplate<class type> class RandomMatrix : public MatMul<type> {\n  PA_INJECT(type) \n  vector< vector< RX > > data;\n\npublic:\n  ~RandomMatrix() {/*cout << \"destructor: random dense matrix\\n\";*/}\n  RandomMatrix(const EncryptedArray& _ea): MatMul<type>(_ea) {\n    long n = _ea.size();\n    long d = _ea.getDegree();\n    long bnd = 2*n; // non-zero with probability 1/bnd\n\n    RBak bak; bak.save(); _ea.getContext().alMod.restoreContext();\n    data.resize(n);\n    for (long i = 0; i < n; i++) {\n      data[i].resize(n);\n      for (long j = 0; j < n; j++) {\n        bool zEntry = (RandomBnd(bnd) > 0);\n        if (zEntry) clear(data[i][j]);\n        else        random(data[i][j], d);\n      }\n    }\n  }\n\n  virtual bool get(RX& out, long i, long j) const {\n    assert(i >= 0 && i < this->getEA().size());\n    assert(j >= 0 && j < this->getEA().size());\n    if (IsZero(data[i][j])) return true;\n    out = data[i][j];\n    return false;\n  }\n};\nstatic MatMulBase* buildRandomMatrix(EncryptedArray& ea)\n{\n  switch (ea.getTag()) {\n    case PA_GF2_tag: { return new RandomMatrix<PA_GF2>(ea); }\n    case PA_zz_p_tag:{ return new RandomMatrix<PA_zz_p>(ea); }\n    default: return nullptr;\n  }\n}\n\n\ntemplate<class type> class RandomBlockMatrix : public BlockMatMul<type> {\n  PA_INJECT(type)\n\n  std::vector< std::vector< mat_R > > data;\n\npublic:\n  virtual ~RandomBlockMatrix() {}\n  RandomBlockMatrix(const EncryptedArray& _ea): BlockMatMul<type>(_ea)\n  { \n    RBak bak; bak.save(); _ea.getAlMod().restoreContext();\n    long n = _ea.size();\n    long d = _ea.getDegree();\n    long bnd = 2*n; // non-zero with probability 1/bnd\n\n    data.resize(n);\n    for (long i = 0; i < n; i++) {\n      data[i].resize(n);\n      for (long j = 0; j < n; j++) {\n        data[i][j].SetDims(d, d);\n\n        bool zEntry = (RandomBnd(bnd) > 0);\n\n        for (long u = 0; u < d; u++)\n          for (long v = 0; v < d; v++) \n            if (zEntry) \n              clear(data[i][j][u][v]);\n            else\n              random(data[i][j][u][v]);\n      }\n    }\n  }\n\n  virtual bool get(mat_R& out, long i, long j) const {\n    assert(i >= 0 && i < this->getEA().size());\n    assert(j >= 0 && j < this->getEA().size());\n    if (IsZero(data[i][j])) return true;\n    out = data[i][j];\n    return false;\n  }\n\n  const std::vector< std::vector< mat_R > >& getData() const {return data;}\n};\n\nstatic MatMulBase* buildRandomBlockMatrix(const EncryptedArray& ea)\n{\n  switch (ea.getTag()) {\n    case PA_GF2_tag: {\n      return new RandomBlockMatrix<PA_GF2>(ea);\n    }\n\n    case PA_zz_p_tag: {\n      return new RandomBlockMatrix<PA_zz_p>(ea);\n    }\n\n    default: return 0;\n  }\n}\n", "meta": {"hexsha": "51191aca31db0ccec9ec02834bbb31ee12c97bfa", "size": 11885, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/misc/Test_matmul.cpp", "max_stars_repo_name": "Valenceo/HElib", "max_stars_repo_head_hexsha": "f560416454d672e1253412c81840d2563ab9b456", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-29T17:10:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-28T06:46:20.000Z", "max_issues_repo_path": "src/misc/Test_matmul.cpp", "max_issues_repo_name": "Valenceo/HElib", "max_issues_repo_head_hexsha": "f560416454d672e1253412c81840d2563ab9b456", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2018-05-17T21:41:34.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-18T21:37:26.000Z", "max_forks_repo_path": "src/misc/Test_matmul.cpp", "max_forks_repo_name": "Valenceo/HElib", "max_forks_repo_head_hexsha": "f560416454d672e1253412c81840d2563ab9b456", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2017-10-16T09:14:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-10T07:24:51.000Z", "avg_line_length": 29.8618090452, "max_line_length": 80, "alphanum_fraction": 0.6127050905, "num_tokens": 3474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186768138228, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4939023545971746}}
{"text": "#include <catch2/catch.hpp>\n\n#include \"engine.hpp\"\n\n#include <iostream>\n#include <boost/units/io.hpp>\n\nusing EvolutionaryWalker::LibUtils::Point;\nusing EvolutionaryWalker::Physics::Engine;\nusing EvolutionaryWalker::Physics::LengthQuantity;\n\nnamespace\n{\n\n}\n\nTEST_CASE(\"Basic uses of Physics::Engine\", \"[physics]\")\n{\n    using boost::units::si::meters;\n    using boost::units::si::seconds;\n    using boost::units::si::kilograms;\n    using boost::units::si::meters_per_second_squared;\n\n    SECTION(\"Basic spring oscillator\")\n    {\n        Engine e{9.61 * meters_per_second_squared};\n        const auto ref = e.addFixedNode({{0 * meters, 10 * meters}});\n        const auto p = e.addNode({{0 * meters, 0 * meters}}, 1 * kilograms);\n        e.addSpring(ref, p, {5 * meters, 1 * meters_per_second_squared});\n\n        e.init();\n        const auto step = .0001 * seconds;\n        for(std::size_t i = 0; i < 100; i++)\n        {\n            e.step(step);\n            std::cout << \"y(\" << ((double)i * step) << \") = \" << e.node(p)[1] << std::endl;\n        }\n    }\n}", "meta": {"hexsha": "296a768acd37dc91760b05db27a3f3e17a1694d0", "size": 1053, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unittest_libphysics/test_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": "test/unittest_libphysics/test_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": "test/unittest_libphysics/test_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": 27.0, "max_line_length": 91, "alphanum_fraction": 0.603988604, "num_tokens": 280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867681382279, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4939023545971745}}
{"text": "//  ================================================================\n//  Created by Gregory Kramida on 10/24/18.\n//  Copyright (c) 2018 Gregory Kramida\n//  Licensed under the Apache License, Version 2.0 (the \"License\");\n//  you may not use this file except in compliance with the License.\n//  You may obtain a copy of the License at\n\n//  http://www.apache.org/licenses/LICENSE-2.0\n\n//  Unless required by applicable law or agreed to in writing, software\n//  distributed under the License is distributed on an \"AS IS\" BASIS,\n//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//  See the License for the specific language governing permissions and\n//  limitations under the License.\n//  ================================================================\n#pragma once\n\n//libraries\n#include <Eigen/Eigen>\n#include <unsupported/Eigen/CXX11/Tensor>\n\n//local\n#include \"vector2.hpp\"\n#include \"vector3.hpp\"\n#include \"matrix2.hpp\"\n#include \"matrix3.hpp\"\n#include \"nestable_type_metainfo.hpp\"\n\nnamespace math{\ntypedef unsigned char uchar;\ntypedef unsigned short ushort;\ntypedef unsigned int uint;\ntypedef unsigned long ulong;\n\ntypedef class math::Vector2<short> Vector2s;\ntypedef class math::Vector2<int> Vector2i;\ntypedef class math::Vector2<float> Vector2f;\ntypedef class math::Vector2<double> Vector2d;\n\ntypedef class math::Vector3<short> Vector3s;\ntypedef class math::Vector3<double> Vector3d;\ntypedef class math::Vector3<int> Vector3i;\ntypedef class math::Vector3<uint> Vector3ui;\ntypedef class math::Vector3<uchar> Vector3u;\ntypedef class math::Vector3<float> Vector3f;\ntypedef class math::Matrix2<float> Matrix2f;\ntypedef class math::Matrix3<float> Matrix3f;\n\ntypedef Eigen::MatrixXf MatrixXf;\ntypedef Eigen::MatrixXd MatrixXd;\ntypedef Eigen::Matrix<math::Vector2<float>, Eigen::Dynamic, Eigen::Dynamic> MatrixXv2f;\ntypedef Eigen::Matrix<math::Vector2<float>, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> MatrixXv2f_rm;\ntypedef Eigen::Matrix<math::Matrix2<float>, Eigen::Dynamic, Eigen::Dynamic> MatrixXm2f;\n\ntypedef class Eigen::Tensor<float,3> Tensor3f;\ntypedef class Eigen::Tensor<float,0> Tensor0f;\ntypedef Eigen::Tensor<math::Vector2<float>,3> Tensor3v2f;\ntypedef Eigen::Tensor<math::Vector3<float>,3> Tensor3v3f;\ntypedef Eigen::Tensor<math::Matrix3<float>,3> Tensor3m3f;\n\ntypedef class Eigen::Matrix<unsigned short, Eigen::Dynamic,Eigen::Dynamic> MatrixXus;\ntypedef class Eigen::Matrix<unsigned short, Eigen::Dynamic,1> MatrixX1us;\ntypedef class Eigen::Matrix<unsigned short, 1, Eigen::Dynamic> Matrix1Xus;\ntypedef class Eigen::Matrix<unsigned char, Eigen::Dynamic,Eigen::Dynamic> MatrixXuc;\ntypedef class Eigen::Matrix<unsigned char, Eigen::Dynamic,1> MatrixX1uc;\ntypedef class Eigen::Matrix<unsigned char, 1, Eigen::Dynamic> Matrix1Xuc;\ntypedef class Eigen::Matrix<unsigned char, Eigen::Dynamic,Eigen::Dynamic> MatrixXuc;\n\n}//namespace math\n", "meta": {"hexsha": "4f837daa949db1acc4ecdf0e03673f9c0e5ab46e", "size": 2874, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/math/typedefs.hpp", "max_stars_repo_name": "Algomorph/LevelSetFusionExperimentsCPP", "max_stars_repo_head_hexsha": "f56962f0ad5c62e6706f818062782a2e1660afda", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2019-01-07T14:12:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T01:48:03.000Z", "max_issues_repo_path": "src/math/typedefs.hpp", "max_issues_repo_name": "Algomorph/LevelSetFusionExperimentsCPP", "max_issues_repo_head_hexsha": "f56962f0ad5c62e6706f818062782a2e1660afda", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2018-12-19T16:43:33.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-06T19:50:22.000Z", "max_forks_repo_path": "src/math/typedefs.hpp", "max_forks_repo_name": "Algomorph/LevelSetFusionExperimentsCPP", "max_forks_repo_head_hexsha": "f56962f0ad5c62e6706f818062782a2e1660afda", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-01-07T14:12:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-06T06:30:24.000Z", "avg_line_length": 41.0571428571, "max_line_length": 107, "alphanum_fraction": 0.7397355602, "num_tokens": 716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.6187804196836383, "lm_q1q2_score": 0.49390234931565374}}
{"text": "\n#include <gtest/gtest.h>\n\n#include <Eigen/Core>\n#include <algorithm>\n#include <csim/init_ops.hpp>\n#include <csim/memory_ops.hpp>\n#include <csim/stat_ops.hpp>\n#include <csim/update_ops.hpp>\n#include <csim/update_ops_cpp.hpp>\n#include <string>\n\n#include \"../util/util.hpp\"\n\nvoid test_single_diagonal_matrix_gate(\n    std::function<void(UINT, const CTYPE*, CTYPE*, ITYPE)> func) {\n    const UINT n = 6;\n    const ITYPE dim = 1ULL << n;\n    const UINT max_repeat = 10;\n\n    Eigen::MatrixXcd Identity(2, 2), Z(2, 2);\n    Identity << 1, 0, 0, 1;\n    Z << 1, 0, 0, -1;\n\n    Eigen::Matrix<std::complex<double>, 2, 2, Eigen::RowMajor> U;\n\n    UINT target;\n    double icoef, zcoef, norm;\n\n    auto state = allocate_quantum_state(dim);\n    initialize_Haar_random_state(state, dim);\n    Eigen::VectorXcd test_state = Eigen::VectorXcd::Zero(dim);\n    for (ITYPE i = 0; i < dim; ++i) test_state[i] = state[i];\n\n    Eigen::MatrixXcd whole_I = Eigen::MatrixXcd::Identity(dim, dim);\n\n    for (UINT rep = 0; rep < max_repeat; ++rep) {\n        // single qubit diagonal matrix gate\n        target = rand_int(n);\n        icoef = rand_real();\n        zcoef = rand_real();\n        norm = sqrt(icoef * icoef + zcoef * zcoef);\n        icoef /= norm;\n        zcoef /= norm;\n        U = icoef * Identity + 1.i * zcoef * Z;\n        Eigen::VectorXcd diag = U.diagonal();\n        func(target, (CTYPE*)diag.data(), state, dim);\n        test_state =\n            get_expanded_eigen_matrix_with_identity(target, U, n) * test_state;\n        state_equal(state, test_state, dim, \"single diagonal gate\");\n    }\n    release_quantum_state(state);\n}\n\nTEST(UpdateTest, SingleDiagonalMatrixTest) {\n    test_single_diagonal_matrix_gate(single_qubit_diagonal_matrix_gate);\n    test_single_diagonal_matrix_gate(\n        single_qubit_diagonal_matrix_gate_single_unroll);\n#ifdef _OPENMP\n    test_single_diagonal_matrix_gate(\n        single_qubit_diagonal_matrix_gate_parallel_unroll);\n#endif\n#ifdef _USE_SIMD\n    test_single_diagonal_matrix_gate(\n        single_qubit_diagonal_matrix_gate_single_simd);\n#ifdef _OPENMP\n    test_single_diagonal_matrix_gate(\n        single_qubit_diagonal_matrix_gate_parallel_simd);\n#endif\n#endif\n}\n\nvoid test_single_phase_gate(\n    std::function<void(UINT, CTYPE, CTYPE*, ITYPE)> func) {\n    const UINT n = 6;\n    const ITYPE dim = 1ULL << n;\n    const UINT max_repeat = 10;\n\n    Eigen::Matrix<std::complex<double>, 2, 2, Eigen::RowMajor> U;\n\n    UINT target;\n    double angle;\n\n    auto state = allocate_quantum_state(dim);\n    initialize_Haar_random_state(state, dim);\n    Eigen::VectorXcd test_state = Eigen::VectorXcd::Zero(dim);\n    for (ITYPE i = 0; i < dim; ++i) test_state[i] = state[i];\n\n    Eigen::MatrixXcd whole_I = Eigen::MatrixXcd::Identity(dim, dim);\n\n    for (UINT rep = 0; rep < max_repeat; ++rep) {\n        // single qubit phase matrix gate\n        target = rand_int(n);\n        angle = rand_real();\n        U << 1, 0, 0, cos(angle) + 1.i * sin(angle);\n        CTYPE t = cos(angle) + 1.i * sin(angle);\n        func(target, t, state, dim);\n        test_state =\n            get_expanded_eigen_matrix_with_identity(target, U, n) * test_state;\n        state_equal(state, test_state, dim, \"single phase gate\");\n    }\n    release_quantum_state(state);\n}\n\nTEST(UpdateTest, SinglePhaseGateTest) {\n    test_single_phase_gate(single_qubit_phase_gate);\n    test_single_phase_gate(single_qubit_phase_gate_single_unroll);\n#ifdef _OPENMP\n    test_single_phase_gate(single_qubit_phase_gate_parallel_unroll);\n#endif\n#ifdef _USE_SIMD\n    test_single_phase_gate(single_qubit_phase_gate_single_simd);\n#ifdef _OPENMP\n    test_single_phase_gate(single_qubit_phase_gate_parallel_simd);\n#endif\n#endif\n}\n", "meta": {"hexsha": "870c7eec1f88f938e53da008bd12b6cc2359f13f", "size": 3683, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/csim/test_update_diagonal.cpp", "max_stars_repo_name": "kodack64/qulacs-osaka", "max_stars_repo_head_hexsha": "4ccc3ff084f10942e22d8663a01ed67efd24d9f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2022-01-26T06:56:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T02:07:24.000Z", "max_issues_repo_path": "test/csim/test_update_diagonal.cpp", "max_issues_repo_name": "kodack64/qulacs-osaka", "max_issues_repo_head_hexsha": "4ccc3ff084f10942e22d8663a01ed67efd24d9f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 104.0, "max_issues_repo_issues_event_min_datetime": "2021-11-12T04:15:02.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T05:12:20.000Z", "max_forks_repo_path": "test/csim/test_update_diagonal.cpp", "max_forks_repo_name": "kodack64/qulacs-osaka", "max_forks_repo_head_hexsha": "4ccc3ff084f10942e22d8663a01ed67efd24d9f7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-12-19T11:52:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-09T04:20:17.000Z", "avg_line_length": 31.2118644068, "max_line_length": 79, "alphanum_fraction": 0.68015205, "num_tokens": 1001, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.6619228691808011, "lm_q1q2_score": 0.4938864630745885}}
{"text": "#include \"../sweepline_state.hpp\"\n\n#include <boost/test/unit_test.hpp>\n#include <boost/test/test_case_template.hpp>\n\n#include <algorithm>\n\nBOOST_AUTO_TEST_SUITE(sweepline_tests)\n\nBOOST_AUTO_TEST_CASE(zigzag_test)\n{\n    //\n    //     1     3     5\n    //    / \\ b / \\ d /\n    //   / a \\ / c \\ /\n    //  0     2     4\n    //\n    std::vector<coordinate> coords {\n        coordinate {0, 0}, coordinate {1, 1}, coordinate {2, 0}, coordinate {3, 1}, coordinate {4, 0}, coordinate {5, 1}\n    };\n    std::vector<coordinate> points {\n        coordinate {1, 0.25}, coordinate {2, 0.75}, coordinate {3, 0.25}, coordinate {4, 0.75}\n    };\n\n    sweepline_state state(coords, 0);\n\n    state.move_sweepline(coords[1]);\n\n    state.insert_edge({0, 1});\n    BOOST_CHECK_EQUAL(state.intersecting_edges.size(), 1);\n    BOOST_CHECK_EQUAL(state.intersecting_edges[0], (sweepline_state::edge {0, 1}));\n\n    state.insert_edge({1, 2});\n    BOOST_CHECK_EQUAL(state.intersecting_edges.size(), 2);\n    BOOST_CHECK_EQUAL(state.intersecting_edges[0], (sweepline_state::edge {0, 1}));\n    BOOST_CHECK_EQUAL(state.intersecting_edges[1], (sweepline_state::edge {1, 2}));\n\n    state.move_sweepline(coords[3]);\n\n    state.insert_edge({2, 3});\n    BOOST_CHECK_EQUAL(state.intersecting_edges.size(), 3);\n    BOOST_CHECK_EQUAL(state.intersecting_edges[0], (sweepline_state::edge {0, 1}));\n    BOOST_CHECK_EQUAL(state.intersecting_edges[1], (sweepline_state::edge {1, 2}));\n    BOOST_CHECK_EQUAL(state.intersecting_edges[2], (sweepline_state::edge {2, 3}));\n\n    state.insert_edge({3, 4});\n    BOOST_CHECK_EQUAL(state.intersecting_edges.size(), 4);\n    BOOST_CHECK_EQUAL(state.intersecting_edges[0], (sweepline_state::edge {0, 1}));\n    BOOST_CHECK_EQUAL(state.intersecting_edges[1], (sweepline_state::edge {1, 2}));\n    BOOST_CHECK_EQUAL(state.intersecting_edges[2], (sweepline_state::edge {2, 3}));\n    BOOST_CHECK_EQUAL(state.intersecting_edges[3], (sweepline_state::edge {3, 4}));\n\n    state.move_sweepline(coords[5]);\n\n    state.insert_edge({4, 5});\n    BOOST_CHECK_EQUAL(state.intersecting_edges.size(), 5);\n    BOOST_CHECK_EQUAL(state.intersecting_edges[0], (sweepline_state::edge {0, 1}));\n    BOOST_CHECK_EQUAL(state.intersecting_edges[1], (sweepline_state::edge {1, 2}));\n    BOOST_CHECK_EQUAL(state.intersecting_edges[2], (sweepline_state::edge {2, 3}));\n    BOOST_CHECK_EQUAL(state.intersecting_edges[3], (sweepline_state::edge {3, 4}));\n    BOOST_CHECK_EQUAL(state.intersecting_edges[4], (sweepline_state::edge {4, 5}));\n\n    state.move_sweepline(points[0]);\n    auto intersect_0 = state.get_first_intersecting(points[0]);\n    BOOST_CHECK(intersect_0 != state.intersecting_edges.end());\n    BOOST_CHECK_EQUAL(*intersect_0, (sweepline_state::edge {1, 2}));\n\n    state.move_sweepline(points[1]);\n    auto intersect_1 = state.get_first_intersecting(points[1]);\n    BOOST_CHECK(intersect_1 != state.intersecting_edges.end());\n    BOOST_CHECK_EQUAL(*intersect_1, (sweepline_state::edge {2, 3}));\n\n    state.move_sweepline(points[2]);\n    auto intersect_2 = state.get_first_intersecting(points[2]);\n    BOOST_CHECK(intersect_2 != state.intersecting_edges.end());\n    BOOST_CHECK_EQUAL(*intersect_2, (sweepline_state::edge {3, 4}));\n\n    state.move_sweepline(points[3]);\n    auto intersect_3 = state.get_first_intersecting(points[3]);\n    BOOST_CHECK(intersect_3 != state.intersecting_edges.end());\n    BOOST_CHECK_EQUAL(*intersect_3, (sweepline_state::edge {4, 5}));\n}\n\nBOOST_AUTO_TEST_CASE(insert_test)\n{\n    // simulate a rotating sweepline on the following line\n    // vertices are inserted in the order given\n    //                    1\n    //    0              /\n    //   / \\            /\n    //  / a \\          /  b\n    // x     2  3     /\n    //       | / \\ c /\n    //       |/   \\ /\n    //       4     5\n    std::vector<coordinate> coords {\n        coordinate {0, 0},  // 0\n        coordinate {1, 1},  // 1\n        coordinate {2, 0},  // 2\n        coordinate {2, -1}, // 3\n        coordinate {3, 0},  // 4\n        coordinate {4, -1}, // 5\n        coordinate {5, 2}   // 6\n    };\n\n    coordinate a {0.5, 0.5};\n    coordinate b {5, 0.5};\n    coordinate c {3.75, -0.5};\n    coordinate point_on_line {3.5, -0.5};\n\n    sweepline_state state(coords, 0);\n\n    // process 1\n    state.move_sweepline(coords[1]);\n    state.insert_edge(sweepline_state::edge {1, 2});\n\n    BOOST_CHECK_EQUAL(state.intersecting_edges.size(), 1);\n    BOOST_CHECK_EQUAL(state.intersecting_edges[0], (sweepline_state::edge {1, 2}));\n\n    // process a\n    state.move_sweepline(a);\n    BOOST_CHECK(state.get_first_intersecting(a) != state.intersecting_edges.end());\n    BOOST_CHECK_EQUAL(*state.get_first_intersecting(a), (sweepline_state::edge {1, 2}));\n\n    // process 6\n    state.move_sweepline(coords[6]);\n    state.insert_edge(sweepline_state::edge {5, 6});\n\n    BOOST_CHECK_EQUAL(state.intersecting_edges.size(), 2);\n    BOOST_CHECK_EQUAL(state.intersecting_edges[0], (sweepline_state::edge {1, 2}));\n    BOOST_CHECK_EQUAL(state.intersecting_edges[1], (sweepline_state::edge {5, 6}));\n\n    // process b\n    state.move_sweepline(b);\n    BOOST_CHECK(state.get_first_intersecting(b) == state.intersecting_edges.end());\n\n    // process 2\n    state.move_sweepline(coords[2]);\n    state.remove_edge(sweepline_state::edge {1, 2});\n    state.insert_edge(sweepline_state::edge {2, 3});\n\n    BOOST_CHECK_EQUAL(state.intersecting_edges.size(), 2);\n    BOOST_CHECK_EQUAL(state.intersecting_edges[0], (sweepline_state::edge {2, 3}));\n    BOOST_CHECK_EQUAL(state.intersecting_edges[1], (sweepline_state::edge {5, 6}));\n\n    // process 4\n    state.move_sweepline(coords[4]);\n    state.insert_edge(sweepline_state::edge {3, 4});\n    state.insert_edge(sweepline_state::edge {4, 5});\n\n    BOOST_CHECK_EQUAL(state.intersecting_edges.size(), 4);\n    BOOST_CHECK_EQUAL(state.intersecting_edges[0], (sweepline_state::edge {2, 3}));\n    BOOST_CHECK_EQUAL(state.intersecting_edges[1], (sweepline_state::edge {3, 4}));\n    BOOST_CHECK_EQUAL(state.intersecting_edges[2], (sweepline_state::edge {4, 5}));\n    BOOST_CHECK_EQUAL(state.intersecting_edges[3], (sweepline_state::edge {5, 6}));\n\n    // process c\n    state.move_sweepline(c);\n    BOOST_CHECK(state.get_first_intersecting(c) != state.intersecting_edges.end());\n    BOOST_CHECK_EQUAL(*state.get_first_intersecting(c), (sweepline_state::edge {5, 6}));\n\n    // FIXME This fails because we assume that points don't lie on lines\n    // BOOST_CHECK(state.get_first_intersecting(point_on_line) != state.intersecting_edges.end());\n    // BOOST_CHECK_EQUAL(*state.get_first_intersecting(point_on_line), (sweepline_state::edge {5, 6}));\n\n    // process 3\n    state.move_sweepline(coords[3]);\n    state.remove_edge(sweepline_state::edge {3, 4});\n    state.remove_edge(sweepline_state::edge {2, 3});\n\n    BOOST_CHECK_EQUAL(state.intersecting_edges.size(), 2);\n    BOOST_CHECK_EQUAL(state.intersecting_edges[0], (sweepline_state::edge {4, 5}));\n    BOOST_CHECK_EQUAL(state.intersecting_edges[1], (sweepline_state::edge {5, 6}));\n\n    // process 5\n    state.move_sweepline(coords[5]);\n    state.remove_edge(sweepline_state::edge {5, 6});\n    state.remove_edge(sweepline_state::edge {4, 5});\n\n    BOOST_CHECK_EQUAL(state.intersecting_edges.size(), 0);\n}\n\nBOOST_AUTO_TEST_CASE(horizontal_segment)\n{\n\n    //              a\n    //         2--------3\n    //         |b\n    //         |\n    //  0------1\n    //\n    std::vector<coordinate> coords { coordinate {0, 0}, coordinate {1, 0}, coordinate {1, 1}, coordinate {2, 1} };\n\n    coordinate a {1.5, 1.25};\n    coordinate b {1.1, 0.9};\n\n    sweepline_state state(coords, 0);\n\n    state.move_sweepline(coords[2]);\n    state.insert_edge(sweepline_state::edge {2, 3});\n    state.insert_edge(sweepline_state::edge {1, 2});\n\n    state.move_sweepline(a);\n    BOOST_CHECK(state.get_first_intersecting(a) == state.intersecting_edges.end());\n\n    state.move_sweepline(b);\n    BOOST_CHECK(state.get_first_intersecting(b) != state.intersecting_edges.end());\n    BOOST_CHECK_EQUAL(*state.get_first_intersecting(b), (sweepline_state::edge {2, 3}));\n\n    state.move_sweepline(coords[3]);\n    state.remove_edge(sweepline_state::edge {2, 3});\n\n    state.move_sweepline(coords[1]);\n    state.remove_edge(sweepline_state::edge {1, 2});\n    state.insert_edge(sweepline_state::edge {0, 1});\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "4f655c055841bc67b498264ce7df362e8e8474d5", "size": 8311, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/sweepline_tests.cpp", "max_stars_repo_name": "TheMarex/deberg", "max_stars_repo_head_hexsha": "050f9ae8930801cc03d216eddc515e9929f7b916", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2015-06-23T14:01:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-12T23:08:06.000Z", "max_issues_repo_path": "tests/sweepline_tests.cpp", "max_issues_repo_name": "TheMarex/deberg", "max_issues_repo_head_hexsha": "050f9ae8930801cc03d216eddc515e9929f7b916", "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": "tests/sweepline_tests.cpp", "max_forks_repo_name": "TheMarex/deberg", "max_forks_repo_head_hexsha": "050f9ae8930801cc03d216eddc515e9929f7b916", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.9497716895, "max_line_length": 120, "alphanum_fraction": 0.6710383829, "num_tokens": 2449, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389817407017, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.4938864605775916}}
{"text": "// Software License for MTL\r\n//\r\n// Copyright (c) 2007 The Trustees of Indiana University.\r\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\r\n//               2010 SimuNova UG (haftungsbeschr\u00e4nkt), www.simunova.com.\r\n// All rights reserved.\r\n// Authors: Shikhar Vashistha\r\n//\r\n// This file is part of the Matrix Template Library\r\n//\r\n// See also license.mtl.txt in the distribution.\r\n\r\n\r\n#ifndef MTL_MATRIX_LQ_INCLUDE\r\n#define MTL_MATRIX_LQ_INCLUDE\r\n\r\n#include <cmath>\r\n#include <boost/numeric/linear_algebra/identity.hpp>\r\n#include <boost/numeric/linear_algebra/inverse.hpp>\r\n#include <boost/numeric/mtl/mtl_fwd.hpp>\r\n#include <boost/numeric/mtl/vector/parameter.hpp>\r\n#include <boost/numeric/mtl/matrix/parameter.hpp>\r\n#include <boost/numeric/mtl/utility/exception.hpp>\r\n#include <boost/numeric/mtl/utility/irange.hpp>\r\n#include <boost/numeric/mtl/concept/collection.hpp>\r\n#include <boost/numeric/mtl/concept/magnitude.hpp>\r\n#include <boost/numeric/mtl/operation/householder.hpp>\r\n#include <boost/numeric/mtl/operation/rank_one_update.hpp>\r\n#include <boost/numeric/mtl/operation/trans.hpp>\r\n#include <boost/numeric/mtl/interface/vpt.hpp>\r\n\r\nnamespace mtl {\r\n    namespace mat {\r\n\r\n\r\n        /// LQ-Factorization of matrix A(m x n)\r\n        /** Return pair L lower triangle matrix and Q= orthogonal matrix. L and Q are always dense2D **/\r\n        template <typename Matrix, typename MatrixQ, typename MatrixR>\r\n        void lq(const Matrix& A, MatrixQ& Q, MatrixR& R)\r\n        {\r\n            vampir_trace<4013> tracer;\r\n            typedef typename Collection<Matrix>::value_type   \t\t    value_type;\r\n            typedef typename Collection<Matrix>::size_type    \t\t    size_type;\r\n            typedef typename Magnitude<value_type>::type      \t\t    magnitude_type;\r\n            typedef mtl::dense_vector<value_type, vec::parameters<> >       vector_type;\r\n\r\n            size_type        ncols = num_cols(trans(A)), nrows = num_rows(trans(A)),\r\n                mini = ncols == nrows ? ncols - 1 : (nrows >= ncols ? ncols : nrows);\r\n            magnitude_type   factor = magnitude_type(2);\r\n\r\n            Q = 1;\r\n            for (size_type i = 0; i < mini; i++) {\r\n                irange r(i, imax); // Intervals [i, n-1]\r\n                vector_type   w(R[r][i]), v(householder_s(w));\r\n\r\n                // R-= 2*v*(v'*R)\r\n                // L will be same if we find R of transpose of A\r\n                MatrixR Rsub(R[r][r]);\r\n                vector_type tmp(-factor * trans(Rsub) * v);\r\n                rank_one_update(Rsub, v, tmp);\r\n\r\n                //update Q: Q-= 2*(v*Q)*v'\r\n                MatrixQ Qsub(Q[iall][r]);\r\n                vector_type qtmp(-factor * Qsub * v);\r\n                rank_one_update(Qsub, qtmp, v);\r\n            } //end for\r\n        }\r\n\r\n        /// QR-Factorization of matrix A(m x n)\r\n        template <typename Matrix>\r\n        std::pair<mtl::mat::dense2D<typename Collection<Matrix>::value_type, mat::parameters<> >,\r\n            mtl::mat::dense2D<typename Collection<Matrix>::value_type, mat::parameters<> > >\r\n            inline lq(const Matrix& A)\r\n        {\r\n            mtl::mat::dense2D<typename Collection<Matrix>::value_type, mat::parameters<> >  R(A), Q(num_rows(trans(A)), num_rows(trans(A)));\r\n            lq(trans(A), Q, R);\r\n            return std::make_pair(Q, R);\r\n        }\r\n\r\n\r\n\r\n        // LQ-Factorization of matrix A\r\n        // Return Q and L with A = L*Q   L lower triangle and Q othogonal\r\n        template <typename Matrix>\r\n        std::pair<typename mtl::mat::dense2D<typename Collection<Matrix>::value_type, mat::parameters<> >,\r\n            typename mtl::mat::dense2D<typename Collection<Matrix>::value_type, mat::parameters<> > >\r\n            inline lq_factors(const Matrix& A)\r\n        {\r\n            vampir_trace<4014> tracer;\r\n            using std::abs;\r\n            typedef typename Collection<Matrix>::value_type   value_type;\r\n            // typedef typename Magnitude<value_type>::type      magnitude_type; // to multiply with 2 not 2+0i\r\n            typedef typename Collection<Matrix>::size_type    size_type;\r\n            size_type        ncols = num_cols(trans(A)), nrows = num_rows(trans(A));\r\n            value_type       zero = math::zero(A[0][0]), one = math::one(A[0][0]);\r\n\r\n            //evaluation of Q\r\n            Matrix  Q(nrows, nrows), Qk(nrows, nrows), HEL(nrows, ncols), R(nrows, ncols), R_tmp(nrows, ncols);\r\n            Q = one; R = zero; HEL = zero;\r\n\r\n            boost::tie(Q, R_tmp) = lq(trans(A));\r\n            R = lower(R_tmp);\r\n\t\t\t//R will be a lower triangular matrix in lq decomposition\r\n            return std::make_pair(Q, R);\r\n        }\r\n\r\n    }\r\n} // namespace mtl::matrix\r\n\r\n\r\n#endif // MTL_MATRIX_QR_INCLUDE\r\n\r\n", "meta": {"hexsha": "f24c6ce6e7ac9e7f95e4abf8ba708ae96ca60b1e", "size": 4765, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/mtl/operation/lq.hpp", "max_stars_repo_name": "shikharvashistha/mtl4", "max_stars_repo_head_hexsha": "09d8523d59baf5fdec29f3509a63babc2763af4a", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "boost/numeric/mtl/operation/lq.hpp", "max_issues_repo_name": "shikharvashistha/mtl4", "max_issues_repo_head_hexsha": "09d8523d59baf5fdec29f3509a63babc2763af4a", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "boost/numeric/mtl/operation/lq.hpp", "max_forks_repo_name": "shikharvashistha/mtl4", "max_forks_repo_head_hexsha": "09d8523d59baf5fdec29f3509a63babc2763af4a", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 42.1681415929, "max_line_length": 141, "alphanum_fraction": 0.5934942288, "num_tokens": 1165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246077301781, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4938836619215036}}
{"text": "/******************************************************************************\\\n* Author: Matthew Beauregard Smith                                             *\n* Affiliation: The University of Texas at Austin                               *\n* Department: Oden Institute and Institute for Cellular and Molecular Biology  *\n* PI: Edward Marcotte                                                          *\n* Project: Protein Fluorosequencing                                            *\n\\******************************************************************************/\n\n// Boost unit test framework (recommended to be the first include):\n#include <boost/test/unit_test.hpp>\n\n// File under test:\n#include \"error-model.h\"\n\n// Standard C++ library headers:\n#include <cmath>\n#include <functional>\n\nnamespace whatprot {\n\nnamespace {\nusing boost::unit_test::tolerance;\nusing std::exp;\nusing std::function;\nusing std::log;\nconst double TOL = 0.000000001;\n}  // namespace\n\nBOOST_AUTO_TEST_SUITE(common_suite)\nBOOST_AUTO_TEST_SUITE(error_model_suite)\n\nBOOST_AUTO_TEST_CASE(constructor_test) {\n    double p_edman_failure = .07;\n    double p_detach = .04;\n    double p_bleach = .05;\n    double p_dud = .10;\n    DistributionType dist_type = DistributionType::LOGNORMAL;\n    double mu = log(1.0);\n    double sigma = .16;\n    double stuck_dye_ratio = 0.5;\n    double p_stuck_dye_loss = 0.08;\n    ErrorModel em(p_edman_failure,\n                  p_detach,\n                  p_bleach,\n                  p_dud,\n                  dist_type,\n                  mu,\n                  sigma,\n                  stuck_dye_ratio,\n                  p_stuck_dye_loss);\n    BOOST_TEST(em.p_edman_failure == p_edman_failure);\n    BOOST_TEST(em.p_detach == p_detach);\n    BOOST_TEST(em.p_bleach == p_bleach);\n    BOOST_TEST(em.p_dud == p_dud);\n    BOOST_TEST(em.distribution_type == dist_type);\n    BOOST_TEST(em.mu == mu);\n    BOOST_TEST(em.sigma == sigma);\n    BOOST_TEST(em.stuck_dye_ratio == stuck_dye_ratio);\n    BOOST_TEST(em.p_stuck_dye_loss == p_stuck_dye_loss);\n}\n\nBOOST_AUTO_TEST_CASE(pdf_lognormal_state_zero_obs_zero_test) {\n    double p_edman_failure = .07;\n    double p_detach = .04;\n    double p_bleach = .05;\n    double p_dud = .10;\n    DistributionType dist_type = DistributionType::LOGNORMAL;\n    double mu = log(1.0);\n    double sigma = .16;\n    double stuck_dye_ratio = 0.5;\n    double p_stuck_dye_loss = 0.08;\n    ErrorModel em(p_edman_failure,\n                  p_detach,\n                  p_bleach,\n                  p_dud,\n                  dist_type,\n                  mu,\n                  sigma,\n                  stuck_dye_ratio,\n                  p_stuck_dye_loss);\n    function<double(double, int)> pdf = em.pdf();\n    double observed = 0.0;\n    int state = 0;\n    BOOST_TEST(pdf(observed, state) == 1.0);\n}\n\nBOOST_AUTO_TEST_CASE(pdf_lognormal_state_zero_obs_one_test) {\n    double p_edman_failure = .07;\n    double p_detach = .04;\n    double p_bleach = .05;\n    double p_dud = .10;\n    DistributionType dist_type = DistributionType::LOGNORMAL;\n    double mu = log(1.0);\n    double sigma = .16;\n    double stuck_dye_ratio = 0.5;\n    double p_stuck_dye_loss = 0.08;\n    ErrorModel em(p_edman_failure,\n                  p_detach,\n                  p_bleach,\n                  p_dud,\n                  dist_type,\n                  mu,\n                  sigma,\n                  stuck_dye_ratio,\n                  p_stuck_dye_loss);\n    function<double(double, int)> pdf = em.pdf();\n    double observed = 1.0;\n    int state = 0;\n    BOOST_TEST(pdf(observed, state) == 0.0);\n}\n\nBOOST_AUTO_TEST_CASE(pdf_lognormal_state_one_obs_zero_test) {\n    double p_edman_failure = .07;\n    double p_detach = .04;\n    double p_bleach = .05;\n    double p_dud = .10;\n    DistributionType dist_type = DistributionType::LOGNORMAL;\n    double mu = log(1.0);\n    double sigma = .16;\n    double stuck_dye_ratio = 0.5;\n    double p_stuck_dye_loss = 0.08;\n    ErrorModel em(p_edman_failure,\n                  p_detach,\n                  p_bleach,\n                  p_dud,\n                  dist_type,\n                  mu,\n                  sigma,\n                  stuck_dye_ratio,\n                  p_stuck_dye_loss);\n    function<double(double, int)> pdf = em.pdf();\n    double observed = 0.0;\n    int state = 1;\n    BOOST_TEST(pdf(observed, state) == 0.0);\n}\n\nBOOST_AUTO_TEST_CASE(pdf_lognormal_state_one_obs_one_test, *tolerance(TOL)) {\n    double p_edman_failure = .07;\n    double p_detach = .04;\n    double p_bleach = .05;\n    double p_dud = .10;\n    DistributionType dist_type = DistributionType::LOGNORMAL;\n    double mu = log(1.0);\n    double sigma = .16;\n    double stuck_dye_ratio = 0.5;\n    double p_stuck_dye_loss = 0.08;\n    ErrorModel em(p_edman_failure,\n                  p_detach,\n                  p_bleach,\n                  p_dud,\n                  dist_type,\n                  mu,\n                  sigma,\n                  stuck_dye_ratio,\n                  p_stuck_dye_loss);\n    function<double(double, int)> pdf = em.pdf();\n    double observed = 1.0;\n    int state = 1;\n    // The test value was found using an online lognormal distribution pdf\n    // calculator.\n    BOOST_TEST(pdf(observed, state) == 2.4933892525089547);\n}\n\nBOOST_AUTO_TEST_CASE(pdf_lognormal_state_eq_obs_ne_one_test, *tolerance(TOL)) {\n    double p_edman_failure = .07;\n    double p_detach = .04;\n    double p_bleach = .05;\n    double p_dud = .10;\n    DistributionType dist_type = DistributionType::LOGNORMAL;\n    double mu = log(1.3);\n    double sigma = .16;\n    double stuck_dye_ratio = 0.5;\n    double p_stuck_dye_loss = 0.08;\n    ErrorModel em(p_edman_failure,\n                  p_detach,\n                  p_bleach,\n                  p_dud,\n                  dist_type,\n                  mu,\n                  sigma,\n                  stuck_dye_ratio,\n                  p_stuck_dye_loss);\n    function<double(double, int)> pdf = em.pdf();\n    double observed = 1.3;\n    int state = 1;\n    // The test value was found using an online lognormal distribution pdf\n    // calculator.\n    BOOST_TEST(pdf(observed, state) == 2.4933892525089547 / 1.3);\n}\n\nBOOST_AUTO_TEST_CASE(pdf_override_state_zero_obs_zero_test) {\n    double p_edman_failure = .07;\n    double p_detach = .04;\n    double p_bleach = .05;\n    double p_dud = .10;\n    DistributionType dist_type = DistributionType::OVERRIDE;\n    double mu = 1.0;\n    double sigma = .16;\n    double stuck_dye_ratio = 0.5;\n    double p_stuck_dye_loss = 0.08;\n    ErrorModel em(p_edman_failure,\n                  p_detach,\n                  p_bleach,\n                  p_dud,\n                  dist_type,\n                  mu,\n                  sigma,\n                  stuck_dye_ratio,\n                  p_stuck_dye_loss);\n    function<double(double, int)> pdf = em.pdf();\n    double observed = 0.0;\n    int state = 0;\n    BOOST_TEST(pdf(observed, state) == 1.0);\n}\n\nBOOST_AUTO_TEST_CASE(pdf_override_state_zero_obs_one_test) {\n    double p_edman_failure = .07;\n    double p_detach = .04;\n    double p_bleach = .05;\n    double p_dud = .10;\n    DistributionType dist_type = DistributionType::OVERRIDE;\n    double mu = 1.0;\n    double sigma = .16;\n    double stuck_dye_ratio = 0.5;\n    double p_stuck_dye_loss = 0.08;\n    ErrorModel em(p_edman_failure,\n                  p_detach,\n                  p_bleach,\n                  p_dud,\n                  dist_type,\n                  mu,\n                  sigma,\n                  stuck_dye_ratio,\n                  p_stuck_dye_loss);\n    function<double(double, int)> pdf = em.pdf();\n    double observed = 1.0;\n    int state = 0;\n    BOOST_TEST(pdf(observed, state) == 1.0);\n}\n\nBOOST_AUTO_TEST_CASE(pdf_override_state_one_obs_zero_test) {\n    double p_edman_failure = .07;\n    double p_detach = .04;\n    double p_bleach = .05;\n    double p_dud = .10;\n    DistributionType dist_type = DistributionType::OVERRIDE;\n    double mu = 1.0;\n    double sigma = .16;\n    double stuck_dye_ratio = 0.5;\n    double p_stuck_dye_loss = 0.08;\n    ErrorModel em(p_edman_failure,\n                  p_detach,\n                  p_bleach,\n                  p_dud,\n                  dist_type,\n                  mu,\n                  sigma,\n                  stuck_dye_ratio,\n                  p_stuck_dye_loss);\n    function<double(double, int)> pdf = em.pdf();\n    double observed = 0.0;\n    int state = 1;\n    BOOST_TEST(pdf(observed, state) == 1.0);\n}\n\nBOOST_AUTO_TEST_CASE(pdf_override_state_one_obs_one_test, *tolerance(TOL)) {\n    double p_edman_failure = .07;\n    double p_detach = .04;\n    double p_bleach = .05;\n    double p_dud = .10;\n    DistributionType dist_type = DistributionType::OVERRIDE;\n    double mu = 1.0;\n    double sigma = .16;\n    double stuck_dye_ratio = 0.5;\n    double p_stuck_dye_loss = 0.08;\n    ErrorModel em(p_edman_failure,\n                  p_detach,\n                  p_bleach,\n                  p_dud,\n                  dist_type,\n                  mu,\n                  sigma,\n                  stuck_dye_ratio,\n                  p_stuck_dye_loss);\n    function<double(double, int)> pdf = em.pdf();\n    double observed = 1.0;\n    int state = 1;\n    BOOST_TEST(pdf(observed, state) == 1.0);\n}\n\nBOOST_AUTO_TEST_CASE(relative_distance_p_edman_failure_test, *tolerance(TOL)) {\n    ErrorModel em1(\n            0.5, 0.5, 0.5, 0.5, DistributionType::OVERRIDE, 0.5, 0.5, 0.5, 0.5);\n    ErrorModel em2(0.66,\n                   0.5,\n                   0.5,\n                   0.5,\n                   DistributionType::OVERRIDE,\n                   0.5,\n                   0.5,\n                   0.5,\n                   0.5);\n    BOOST_TEST(em1.relative_distance(em2) == (0.66 - 0.5) / 0.5);\n    BOOST_TEST(em2.relative_distance(em1) == (0.66 - 0.5) / 0.66);\n}\n\nBOOST_AUTO_TEST_CASE(relative_distance_p_detach_test, *tolerance(TOL)) {\n    ErrorModel em1(\n            0.5, 0.5, 0.5, 0.5, DistributionType::OVERRIDE, 0.5, 0.5, 0.5, 0.5);\n    ErrorModel em2(0.5,\n                   0.66,\n                   0.5,\n                   0.5,\n                   DistributionType::OVERRIDE,\n                   0.5,\n                   0.5,\n                   0.5,\n                   0.5);\n    BOOST_TEST(em1.relative_distance(em2) == (0.66 - 0.5) / 0.5);\n    BOOST_TEST(em2.relative_distance(em1) == (0.66 - 0.5) / 0.66);\n}\n\nBOOST_AUTO_TEST_CASE(relative_distance_p_bleach_test, *tolerance(TOL)) {\n    ErrorModel em1(\n            0.5, 0.5, 0.5, 0.5, DistributionType::OVERRIDE, 0.5, 0.5, 0.5, 0.5);\n    ErrorModel em2(0.5,\n                   0.5,\n                   0.66,\n                   0.5,\n                   DistributionType::OVERRIDE,\n                   0.5,\n                   0.5,\n                   0.5,\n                   0.5);\n    BOOST_TEST(em1.relative_distance(em2) == (0.66 - 0.5) / 0.5);\n    BOOST_TEST(em2.relative_distance(em1) == (0.66 - 0.5) / 0.66);\n}\n\nBOOST_AUTO_TEST_CASE(relative_distance_p_dud_test, *tolerance(TOL)) {\n    ErrorModel em1(\n            0.5, 0.5, 0.5, 0.5, DistributionType::OVERRIDE, 0.5, 0.5, 0.5, 0.5);\n    ErrorModel em2(0.5,\n                   0.5,\n                   0.5,\n                   0.66,\n                   DistributionType::OVERRIDE,\n                   0.5,\n                   0.5,\n                   0.5,\n                   0.5);\n    BOOST_TEST(em1.relative_distance(em2) == (0.66 - 0.5) / 0.5);\n    BOOST_TEST(em2.relative_distance(em1) == (0.66 - 0.5) / 0.66);\n}\n\nBOOST_AUTO_TEST_CASE(relative_distance_mu_test, *tolerance(TOL)) {\n    ErrorModel em1(\n            0.5, 0.5, 0.5, 0.5, DistributionType::OVERRIDE, 0.5, 0.5, 0.5, 0.5);\n    ErrorModel em2(0.5,\n                   0.5,\n                   0.5,\n                   0.5,\n                   DistributionType::OVERRIDE,\n                   0.66,\n                   0.5,\n                   0.5,\n                   0.5);\n    BOOST_TEST(em1.relative_distance(em2) == (exp(0.66) - exp(0.5)) / exp(0.5));\n    BOOST_TEST(em2.relative_distance(em1)\n               == (exp(0.66) - exp(0.5)) / exp(0.66));\n}\n\nBOOST_AUTO_TEST_CASE(relative_distance_sigma_test, *tolerance(TOL)) {\n    ErrorModel em1(\n            0.5, 0.5, 0.5, 0.5, DistributionType::OVERRIDE, 0.5, 0.5, 0.5, 0.5);\n    ErrorModel em2(0.5,\n                   0.5,\n                   0.5,\n                   0.5,\n                   DistributionType::OVERRIDE,\n                   0.5,\n                   0.66,\n                   0.5,\n                   0.5);\n    BOOST_TEST(em1.relative_distance(em2) == (0.66 - 0.5) / 0.5);\n    BOOST_TEST(em2.relative_distance(em1) == (0.66 - 0.5) / 0.66);\n}\n\nBOOST_AUTO_TEST_CASE(relative_distance_stuck_dye_ratio_test, *tolerance(TOL)) {\n    ErrorModel em1(\n            0.5, 0.5, 0.5, 0.5, DistributionType::OVERRIDE, 0.5, 0.5, 0.5, 0.5);\n    ErrorModel em2(0.5,\n                   0.5,\n                   0.5,\n                   0.5,\n                   DistributionType::OVERRIDE,\n                   0.5,\n                   0.5,\n                   0.66,\n                   0.5);\n    BOOST_TEST(em1.relative_distance(em2) == (0.66 - 0.5) / 0.5);\n    BOOST_TEST(em2.relative_distance(em1) == (0.66 - 0.5) / 0.66);\n}\n\nBOOST_AUTO_TEST_CASE(relative_distance_p_stuck_dye_loss_test, *tolerance(TOL)) {\n    ErrorModel em1(\n            0.5, 0.5, 0.5, 0.5, DistributionType::OVERRIDE, 0.5, 0.5, 0.5, 0.5);\n    ErrorModel em2(0.5,\n                   0.5,\n                   0.5,\n                   0.5,\n                   DistributionType::OVERRIDE,\n                   0.5,\n                   0.5,\n                   0.5,\n                   0.66);\n    BOOST_TEST(em1.relative_distance(em2) == (0.66 - 0.5) / 0.5);\n    BOOST_TEST(em2.relative_distance(em1) == (0.66 - 0.5) / 0.66);\n}\n\nBOOST_AUTO_TEST_CASE(relative_distance_max_no_sum_test, *tolerance(TOL)) {\n    ErrorModel em1(0.5,\n                   0.5,\n                   0.5,\n                   0.5,\n                   DistributionType::OVERRIDE,\n                   0.66,\n                   0.5,\n                   0.5,\n                   0.5);\n    ErrorModel em2(0.7,\n                   0.7,\n                   0.7,\n                   0.7,\n                   DistributionType::OVERRIDE,\n                   0.66,\n                   0.7,\n                   0.7,\n                   0.7);\n    BOOST_TEST(em1.relative_distance(em2) == (0.7 - 0.5) / 0.5);\n    BOOST_TEST(em2.relative_distance(em1) == (0.7 - 0.5) / 0.7);\n}\n\nBOOST_AUTO_TEST_SUITE_END()  // error_model_suite\nBOOST_AUTO_TEST_SUITE_END()  // common_suite\n\n}  // namespace whatprot\n", "meta": {"hexsha": "08f2dfb507e32aa9e718d9c6509667bf65db2812", "size": 14440, "ext": "cc", "lang": "C++", "max_stars_repo_path": "cc_code/src/common/error-model.test.cc", "max_stars_repo_name": "erisyon/whatprot", "max_stars_repo_head_hexsha": "176cd7e6ee99ea3f91794dcf1ec14f3578b7ee3c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cc_code/src/common/error-model.test.cc", "max_issues_repo_name": "erisyon/whatprot", "max_issues_repo_head_hexsha": "176cd7e6ee99ea3f91794dcf1ec14f3578b7ee3c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-06-12T00:50:08.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-15T17:59:12.000Z", "max_forks_repo_path": "cc_code/src/common/error-model.test.cc", "max_forks_repo_name": "erisyon/whatprot", "max_forks_repo_head_hexsha": "176cd7e6ee99ea3f91794dcf1ec14f3578b7ee3c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-11T19:34:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-11T19:34:43.000Z", "avg_line_length": 32.3042505593, "max_line_length": 80, "alphanum_fraction": 0.5235457064, "num_tokens": 3981, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120234, "lm_q2_score": 0.5926665999540697, "lm_q1q2_score": 0.493883654561678}}
{"text": "#include <math.h>\n#include <EigenUnsupported/Eigen/KroneckerProduct>\n#include \"Core/Utilities/QProgInfo/QCircuitInfo.h\"\n#include \"Core/Utilities/Tools/MatrixDecomposition.h\"\nUSING_QPANDA\nusing namespace std;\n\nusing MatrixSequence = std::vector<MatrixUnit>;\nusing DecomposeEntry = std::pair<int, MatrixSequence>;\n\nusing ColumnOperator = std::vector<DecomposeEntry>;\nusing MatrixOperator = std::vector<ColumnOperator>;\n\nusing SingleGateUnit = std::pair<MatrixSequence, QStat>;\n\nstatic void upper_partition(int order, MatrixOperator &entries)\n{\n\tauto index = (int)std::log2(entries.size() + 1) - (int)std::log2(order) - 1;\n\n\tfor (auto cdx = 0; cdx < order - 1; ++cdx)\n\t{\n\t\tfor (auto rdx = 0; rdx < order - cdx - 1; ++rdx)\n\t\t{\n\t\t\tauto entry = entries[cdx][rdx];\n\n\t\t\tentry.first += order;\n\t\t\tentry.second[index] = MatrixUnit::SINGLE_P1;\n\n\t\t\tentries[cdx + order].emplace_back(entry);\n\t\t}\n\t}\n\n    return;\n}\n\n\nstatic bool entry_requirement(const MatrixSequence& units, int udx, int cdx)\n{\n\tint lj = ((cdx - 1) >> (udx - 1)) & 1;\n\n\tint M = 1;\n\twhile (cdx)\n\t{\n\t\tcdx >>= 1;\n\t\tM += cdx ? 1 : 0;\n\t}\n\n\t//if 1 \u2264 j \u2264 m and cj = lj' = 1 , return true\n\tauto mat = units[units.size() - udx];\n\treturn udx >= 1\n\t\t&& udx <= M\n\t\t&& lj\n\t\t&& mat == MatrixUnit::SINGLE_P1;\n}\n\nstatic bool steps_requirement(const MatrixSequence& units, int udx, int cdx)\n{\n\tint M = 1;\n\twhile (cdx)\n\t{\n\t\tcdx >>= 1;\n\t\tM += cdx ? 1 : 0;\n\t}\n\n\t//if j = n and none of cn...cm+1 is 1 , return true\n\tif (units.size() != udx)\n\t{\n\t\treturn false;\n\t}\n\telse\n\t{\n\t\tauto iter = std::find(units.begin(), units.end() - M, MatrixUnit::SINGLE_P1);\n\t\treturn (units.end() - M) == iter;\n\t}\n}\n\nstatic void under_partition(int order, MatrixOperator& entries)\n{\n\tauto qubits = (int)std::log2(entries.size() + 1);\n\n\tfor (auto cdx = 1; cdx < order; ++cdx)\n\t{\n\t\tif (cdx & 1)\n\t\t{\n\t\t\tfor (auto rdx = 0; rdx < order; ++rdx)\n\t\t\t{\n\t\t\t\tauto value = entries[0][rdx + order - 1].first ^ cdx;\n\t\t\t\tauto entry = make_pair(value, entries[cdx - 1][rdx + order - cdx].second);\n\n\t\t\t\tentries[cdx].emplace_back(entry);\n\t\t\t}\n\n\t\t\tauto &units = entries[cdx].back().second;\n\t\t\tfor (auto idx = 0; idx < (int)std::log2(order); ++idx)\n\t\t\t{\n\t\t\t\tunits[qubits - idx - 1] = ((cdx >> idx) & 1) ?\n\t\t\t\t\tMatrixUnit::SINGLE_P1 : MatrixUnit::SINGLE_I2;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfor (auto rdx = 0; rdx < order; ++rdx)\n\t\t\t{\n\t\t\t\tauto range = (int)std::log2(order) + 1;\n\t\t\t\tauto refer = entries[0][rdx + order - 1].second;\n\t\t\t\tauto entry = entries[0][rdx + order - 1].first ^ cdx;\n\n\t\t\t\tMatrixSequence units(refer.begin() + qubits - range, refer.end());\n\n\t\t\t\tfor (auto udx = 1; udx <= range; ++udx)  /*udx = j , cdx = L*/\n\t\t\t\t{\n\t\t\t\t\tbool steps_accord = steps_requirement(units, udx, cdx + 1);\n\t\t\t\t\tbool entry_accord = entry_requirement(units, udx, cdx + 1);\n\n\t\t\t\t\tunits[range - udx] = steps_accord ? MatrixUnit::SINGLE_P1 :\n\t\t\t\t\t\tentry_accord ? MatrixUnit::SINGLE_P0 : units[range - udx];\n\t\t\t\t}\n\n\t\t\t\tfor (auto idx = 0; idx < qubits - range; ++idx)\n\t\t\t\t{\n\t\t\t\t\tunits.insert(units.begin(), MatrixUnit::SINGLE_I2);\n\t\t\t\t}\n\n\t\t\t\tentries[cdx].emplace_back(make_pair(entry, units));\n\t\t\t}\n\n\t\t\tauto refer_opt = entries[0][2 * order - 2].second;\n\t\t\tfor (auto idx = 0; idx < qubits; ++idx)\n\t\t\t{\n\t\t\t\tif ((cdx >> idx) & 1)\n\t\t\t\t{\n\t\t\t\t\trefer_opt[qubits - idx - 1] = MatrixUnit::SINGLE_P1;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tentries[cdx].back().second = refer_opt;\n\t\t}\n\t}\n\n    return;\n}\n\nstatic void controller(MatrixSequence &sequence, const EigenMatrix2c U2, EigenMatrixXc &matrix)\n{\n\tEigenMatrix2c P0;\n\tEigenMatrix2c P1;\n\tEigenMatrix2c I2;\n\n\tP0 << Eigen::dcomplex(1, 0), Eigen::dcomplex(0, 0),\n\t\t  Eigen::dcomplex(0, 0), Eigen::dcomplex(0, 0);\n\tP1 << Eigen::dcomplex(0, 0), Eigen::dcomplex(0, 0),\n\t\t  Eigen::dcomplex(0, 0), Eigen::dcomplex(1, 0);\n\tI2 << Eigen::dcomplex(1, 0), Eigen::dcomplex(0, 0),\n\t\t  Eigen::dcomplex(0, 0), Eigen::dcomplex(1, 0);\n\n\tstd::map<MatrixUnit, std::function<EigenMatrix2c()>> mapping =\n\t{\n\t\t{ MatrixUnit::SINGLE_P0, [&]() {return P0; } },\n\t\t{ MatrixUnit::SINGLE_P1, [&]() {return P1; } },\n\t\t{ MatrixUnit::SINGLE_I2, [&]() {return I2; } },\n\t\t{ MatrixUnit::SINGLE_V2, [&]() {return U2 - I2; } }\n\t};\n\n\tauto order = sequence.size();\n\tEigenMatrixXc Un = EigenMatrixXc::Identity(1, 1);\n\tEigenMatrixXc In = EigenMatrixXc::Identity(1ull << order, 1ull << order);\n\n\tfor (const auto &val : sequence)\n\t{\n\t\tEigenMatrix2c M2 = mapping.find(val)->second();\n\t\tUn = Eigen::kroneckerProduct(Un, M2).eval();\n\t}\n\n\tmatrix = In + Un;\n    return;\n}\n\nstatic void recursive_partition(const EigenMatrixXc& sub_matrix, MatrixOperator &entries)\n{\n    Eigen::Index order = sub_matrix.rows();\n    if (1 == order)\n    {\n        return;\n    }\n    else\n    {\n        EigenMatrixXc corner = sub_matrix.topLeftCorner(order / 2, order / 2);\n\n        recursive_partition(corner, entries);\n\n        upper_partition(order / 2, entries);\n        under_partition(order / 2, entries);\n    }\n\n    return;\n}\n\nstatic void decomposition(EigenMatrixXc& matrix, MatrixOperator& entries, std::vector<SingleGateUnit>& cir_units)\n{\n\tfor (auto cdx = 0; cdx < entries.size(); ++cdx)\n\t{\n\t\tauto opts = entries[cdx].size();\n\t\tfor (auto idx = 0; idx < opts; ++idx)\n\t\t{\n\t\t\tauto rdx = entries[cdx][idx].first;\n\t\t\tauto opt = entries[cdx][idx].second;\n\n\t\t\tif ((EigenComplexT(0, 0) == matrix(rdx, cdx) && (idx != opts - 1)) ||\n\t\t\t\t(EigenComplexT(1, 0) == matrix(cdx + 1, cdx) && (idx == opts - 1)))\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tEigenMatrix2c C2; /*placeholder*/\n\t\t\t\tC2 << EigenComplexT(0, 1), EigenComplexT(0, 1),\n\t\t\t\t\tEigenComplexT(0, 1), EigenComplexT(0, 1);\n\n\t\t\t\tEigenMatrixXc Cn;\n\t\t\t\tcontroller(opt, C2, Cn);\n\n\t\t\t\tQnum indices(2);\n\t\t\t\tfor (Eigen::Index index = 0; index < (1ull << opt.size()); ++index)\n\t\t\t\t{\n\t\t\t\t\tif (Cn(rdx, index) != EigenComplexT(0, 0))\n\t\t\t\t\t{\n\t\t\t\t\t\tindices[index == rdx] = index;\n\t\t\t\t\t}  \n\t\t\t\t}\n\n\t\t\t\tEigenComplexT C0 = matrix(indices[0], cdx);  /*The entry to be eliminated */\n\t\t\t\tEigenComplexT C1 = matrix(indices[1], cdx);  /*The corresponding entry */\n\n\t\t\t\tEigenComplexT V11, V12, V21, V22;\n\n\t\t\t\tif (indices[0] < indices[1])\n\t\t\t\t{\n\t\t\t\t\tV11 = std::conj(C0) / std::sqrt(std::norm(C0) + std::norm(C1));\n\t\t\t\t\tV12 = std::conj(C1) / std::sqrt(std::norm(C0) + std::norm(C1));\n\t\t\t\t\tV21 = C1 / std::sqrt(std::norm(C0) + std::norm(C1));\n\t\t\t\t\tV22 = -C0 / std::sqrt(std::norm(C0) + std::norm(C1));\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tV11 = -C0 / std::sqrt(std::norm(C0) + std::norm(C1));\n\t\t\t\t\tV12 = C1 / std::sqrt(std::norm(C0) + std::norm(C1));\n\t\t\t\t\tV21 = std::conj(C1) / std::sqrt(std::norm(C0) + std::norm(C1));\n\t\t\t\t\tV22 = std::conj(C0) / std::sqrt(std::norm(C0) + std::norm(C1));\n\t\t\t\t}\n\n\t\t\t\tEigenMatrix2c V2;\n\t\t\t\tV2 << V11, V12, V21, V22;\n\n\t\t\t\tEigenMatrixXc Un;\n\t\t\t\tcontroller(opt, V2, Un);\n\n\t\t\t\tmatrix = Un * matrix;\n\n\t\t\t\tQStat M2 = { (qcomplex_t)V11 ,(qcomplex_t)V12 ,(qcomplex_t)V21 ,(qcomplex_t)V22 };\n\t\t\t\tcir_units.insert(cir_units.begin(), std::make_pair(opt, M2));\n\t\t\t}\n\t\t}\n\t}\n\n\tEigenMatrix2c V2 = matrix.bottomRightCorner(2, 2);\n\tif (EigenMatrixXc::Identity(2, 2) != V2)\n\t{\n\t\tQStat M2 = { (qcomplex_t)((EigenComplexT)1.0 / V2(0,0)), (qcomplex_t)(V2(0,1)),\n\t\t\t\t\t (qcomplex_t)(V2(1,0)) , (qcomplex_t)((EigenComplexT)1.0 / V2(1,1))};\n\n\t\tauto entry = entries.back().back().second;\n\t\tcir_units.insert(cir_units.begin(), std::make_pair(entry, M2));\n\t}\n}\n\nstatic void initialize(EigenMatrixXc& 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 entry = column[opt].first;\n            auto units = column[opt].second;\n\n            // 1 : none of cn\u22121, . . . , c1 equals 1\n            // * : otherwise\n            auto iter = std::find(units.end() - idx, units.end(), MatrixUnit::SINGLE_P1);\n\n            units[units.size() - 1 - idx] = (units.end() == iter) ?\n                MatrixUnit::SINGLE_P1 : MatrixUnit::SINGLE_I2;\n\n            column.emplace_back(make_pair(entry + path, 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    return;\n}\n\nstatic void general_scheme(EigenMatrixXc& matrix, std::vector<SingleGateUnit>& cir_units)\n{\n\tMatrixOperator entries;\n\tfor (auto idx = 1; idx < matrix.cols(); ++idx)\n\t{\n\t\tColumnOperator Co;\n\t\tentries.emplace_back(Co);\n\t}\n\n\tinitialize(matrix, entries);\n \trecursive_partition(matrix, entries);\n\tdecomposition(matrix, entries, cir_units);\n\n    return;\n}\n\nstatic void circuit_insert(QVec& qubits, std::vector<SingleGateUnit>& cir_units, QCircuit &circuit)\n{\n\tstd::sort(qubits.begin(), qubits.end(), [&](Qubit *a, Qubit *b)\n\t{\n\t\treturn a->getPhysicalQubitPtr()->getQubitAddr()\n\t\t\t < b->getPhysicalQubitPtr()->getQubitAddr();\n\t});\n\n\tauto rank = qubits.size();\n\tfor (auto &val : cir_units)\n\t{\n\t\tQVec control;\n\t\tQCircuit cir;\n\n\t\tfor (auto qdx = 0; qdx < rank; qdx++)\n\t\t{\n\t\t\tif (MatrixUnit::SINGLE_P0 == val.first[qdx])\n\t\t\t{\n\t\t\t\tcir << X(qubits[qdx]);\n\t\t\t\tcontrol.emplace_back(qubits[qdx]);\n\t\t\t}\n\t\t\telse if (MatrixUnit::SINGLE_P1 == val.first[qdx])\n\t\t\t{\n\t\t\t\tcontrol.emplace_back(qubits[qdx]);\n\t\t\t}\n\t\t\telse\n\t\t\t{}\n\t\t}\n\n\t\tfor (auto qdx = 0; qdx < rank; qdx++)\n\t\t{\n\t\t\tif (MatrixUnit::SINGLE_V2 == val.first[qdx])\n\t\t\t{\n\t\t\t\tcircuit << cir\n\t\t\t\t\t    << U4(val.second, qubits[qdx]).control(control).dagger()\n\t\t\t\t\t\t<< cir;\n\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n}  \n\nQCircuit QPanda::matrix_decompose(QVec qubits, const QStat& src_mat)\n{\n\tauto order = std::sqrt(src_mat.size());\n\n\tEigenMatrixXc matrix = EigenMatrixXc::Zero(order, order);\n\tfor (auto rdx = 0; rdx < order; ++rdx)\n\t{\n\t\tfor (auto cdx = 0; cdx < order; ++cdx)\n\t\t{\n\t\t\tmatrix(rdx, cdx) = src_mat[rdx*order + cdx];\n\t\t}\n\t}\n\n\treturn matrix_decompose(qubits, matrix);\n}\n\nQCircuit QPanda::matrix_decompose(QVec qubits, EigenMatrixXc& src_mat)\n{\n\tif (!src_mat.isUnitary(1e-6))\n\t{\n\t\tQCERR_AND_THROW_ERRSTR(invalid_argument, \"Non-unitary matrix.\");\n\t}\n\n\tif (qubits.size() != log2(src_mat.cols()))\n\t{\n\t\tQCERR_AND_THROW_ERRSTR(invalid_argument, \"The qubits number is error.\");\n\t}\n\n\tstd::vector<SingleGateUnit> cir_units;\n\tgeneral_scheme(src_mat, cir_units);\n\n\tQCircuit output_circuit;\n\tcircuit_insert(qubits, cir_units, output_circuit);\n\n\treturn output_circuit;\n}", "meta": {"hexsha": "37c02d37a7cc0f2d91870ce36c91d966964fb6af", "size": 10414, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Core/Utilities/Tools/MatrixDecomposition.cpp", "max_stars_repo_name": "JING-XINXING/QPanda-2", "max_stars_repo_head_hexsha": "c70c4117a90978916b871424e204c5159f645642", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-06T07:22:36.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-06T07:22:36.000Z", "max_issues_repo_path": "Core/Utilities/Tools/MatrixDecomposition.cpp", "max_issues_repo_name": "yinxx/QPanda-2", "max_issues_repo_head_hexsha": "c70c4117a90978916b871424e204c5159f645642", "max_issues_repo_licenses": ["Apache-2.0"], "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": "yinxx/QPanda-2", "max_forks_repo_head_hexsha": "c70c4117a90978916b871424e204c5159f645642", "max_forks_repo_licenses": ["Apache-2.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.6502463054, "max_line_length": 113, "alphanum_fraction": 0.6130209334, "num_tokens": 3499, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473614033683, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4937647756837187}}
{"text": "//\n// author: Ed Valeev (eduard@valeyev.net)\n// date  : July 8, 2014\n// the use of this software is permitted under the conditions GNU General Public License (GPL) version 2\n//\n\n#include <cmath>\n#include <iostream>\n#include <fstream>\n#include <iomanip>\n#include <vector>\n\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n\ntypedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>\n        Matrix;  // import dense, dynamically sized Matrix type from Eigen;\n                 // this is row-major to conform with C/C++\n                 // Eigen also supports statically-sized matrices, sparse matrices, etc.\n\n#define INDEX(i,j) ((i>j) ? (((i)*((i)+1)/2)+(j)) : (((j)*((j)+1)/2)+(i)))\n\nstruct Atom {\n    double zval;\n    double x, y, z;\n};\n\nvoid read_geometry(const std::string& filename, std::vector<Atom>& atoms);\nvoid read_1e_ints(Matrix& A, const std::string& filename);\ndouble* read_2e_ints(const std::string& filename, size_t nao);\n\nint main(int argc, char *argv[]) {\n\n  using std::cout;\n  using std::cerr;\n  using std::endl;\n\n  try {\n\n    /*** =========================== ***/\n    /*** initialize integrals, etc.  ***/\n    /*** =========================== ***/\n\n    // read geometry from xyz file\n    std::vector<Atom> atoms;\n    read_geometry(\"geom.dat\", atoms);\n\n    // count the number of electrons\n    auto nelectron = 0;\n    for (auto i = 0; i < atoms.size(); ++i)\n      nelectron += atoms[i].zval;\n    const auto ndocc = nelectron / 2;\n\n    // compute the nuclear repulsion energy\n    auto enuc = 0.0;\n    for (auto i = 0; i < atoms.size(); i++)\n      for (auto j = i + 1; j < atoms.size(); j++) {\n        auto xij = atoms[i].x - atoms[j].x;\n        auto yij = atoms[i].y - atoms[j].y;\n        auto zij = atoms[i].z - atoms[j].z;\n        auto r2 = xij*xij + yij*yij + zij*zij;\n        auto r = sqrt(r2);\n        enuc += atoms[i].zval * atoms[j].zval / r;\n      }\n    cout << \"\\tNuclear repulsion energy = \" << enuc << endl;\n\n    // ask the user for # of AOs\n    cout << \"\\nEnter the number of AOs (7 unless U have updated the links): \";\n    size_t nao;\n    std::cin >> nao;\n\n    // compute overlap integrals\n    Matrix S(nao, nao);      // this creates an nao by nao matrix (contents are not initialized!)\n                             // to make a matrix of zeroes do this:\n                             // auto S = Matrix::Zero(nao, nao);\n    read_1e_ints(S, \"s.dat\");\n    cout << \"\\n\\tOverlap Integrals:\\n\";\n    cout << S << endl;\n\n    // compute kinetic-energy integrals\n    Matrix T(nao, nao);\n    read_1e_ints(T, \"t.dat\");\n    cout << \"\\n\\tKinetic-Energy Integrals:\\n\";\n    cout << T << endl;\n\n    // compute nuclear-attraction integrals\n    Matrix V(nao, nao);\n    read_1e_ints(V, \"v.dat\");\n    cout << \"\\n\\tNuclear Attraction Integrals:\\n\";\n    cout << V << endl;\n\n    // Core Hamiltonian = T + V\n    Matrix H = T + V;\n    cout << \"\\n\\tCore Hamiltonian:\\n\";\n    cout << H << endl;\n\n    // T and V no longer needed, free up the memory\n    T.resize(0,0);\n    V.resize(0,0);\n\n    /* read two-electron integrals */\n    auto TEI = read_2e_ints(\"eri.dat\", nao);\n\n    /*** =========================== ***/\n    /*** build initial-guess density ***/\n    /*** =========================== ***/\n\n    // solve H C = e S C\n    Eigen::GeneralizedSelfAdjointEigenSolver<Matrix> gen_eig_solver(H, S);\n    auto eps = gen_eig_solver.eigenvalues();\n    auto C = gen_eig_solver.eigenvectors();\n    cout << \"\\n\\tInitial C Matrix:\\n\";\n    cout << C << endl;\n\n    // compute density, D = C(occ) . C(occ)T\n    auto C_occ = C.leftCols(ndocc);\n    Matrix D = C_occ * C_occ.transpose();\n    cout << \"\\n\\tInitial Density Matrix:\\n\";\n    cout << D << endl;\n\n    // compute HF energy\n    auto ehf = 0.0;\n    for (auto i = 0; i < nao; i++)\n      for (auto j = 0; j < nao; j++)\n        ehf += 2.0 * D(i,j) * H(i,j);\n\n    std::cout <<\n        \"\\n\\n Iter        E(elec)              E(tot)               Delta(E)             RMS(D)\\n\";\n    printf(\" %02d %20.12f %20.12f\\n\", 0, ehf, ehf + enuc);\n\n\n    /*** =========================== ***/\n    /*** main iterative loop ***/\n    /*** =========================== ***/\n\n    const auto maxiter = 100;\n    const auto conv = 1e-12;\n    auto iter = 0;\n    auto rmsd = 0.0;\n    auto ediff = 0.0;\n    do {\n      ++iter;\n\n      // Save a copy of the energy and the density\n      auto ehf_last = ehf;\n      auto D_last = D;\n\n      // build a new Fock matrix\n      auto F = H;\n      for (auto i = 0; i < nao; i++)\n        for (auto j = 0; j < nao; j++) {\n          for (auto k = 0; k < nao; k++)\n            for (auto l = 0; l < nao; l++) {\n              auto ij = INDEX(i, j);\n              auto kl = INDEX(k, l);\n              auto ijkl = INDEX(ij, kl);\n              auto ik = INDEX(i, k);\n              auto jl = INDEX(j, l);\n              auto ikjl = INDEX(ik, jl);\n\n              F(i,j) += D(k,l) * (2.0 * TEI[ijkl] - TEI[ikjl]);\n            }\n        }\n\n      if (iter == 1) {\n        cout << \"\\n\\tFock Matrix:\\n\";\n        cout << F << endl;\n      }\n\n      // solve F C = e S C\n      Eigen::GeneralizedSelfAdjointEigenSolver<Matrix> gen_eig_solver(F, S);\n      auto eps = gen_eig_solver.eigenvalues();\n      auto C = gen_eig_solver.eigenvectors();\n\n      // compute density, D = C(occ) . C(occ)T\n      auto C_occ = C.leftCols(ndocc);\n      D = C_occ * C_occ.transpose();\n\n      // compute HF energy\n      ehf = 0.0;\n      for (auto i = 0; i < nao; i++)\n        for (auto j = 0; j < nao; j++)\n          ehf += D(i,j) * (H(i,j) + F(i,j));\n\n      // compute difference with last iteration\n      ediff = ehf - ehf_last;\n      rmsd = (D - D_last).norm();\n\n      printf(\" %02d %20.12f %20.12f %20.12f %20.12f\\n\", iter, ehf, ehf + enuc,\n             ediff, rmsd);\n\n    } while (((fabs(ediff) > conv) || (fabs(rmsd) > conv)) && (iter < maxiter));\n\n    delete[] TEI;\n  } // end of try block\n\n  catch (const char* ex) {\n    cerr << \"caught exception: \" << ex << endl;\n    return 1;\n  }\n  catch (std::string& ex) {\n    cerr << \"caught exception: \" << ex << endl;\n    return 1;\n  }\n  catch (std::exception& ex) {\n    cerr << ex.what() << endl;\n    return 1;\n  }\n  catch (...) {\n    cerr << \"caught unknown exception\\n\";\n    return 1;\n  }\n\n  return 0;\n}\n\n\nvoid read_geometry(const std::string& filename, std::vector<Atom>& atoms) {\n\n  std::ifstream is(filename);\n  assert(is.good());\n  size_t natom;\n  is >> natom;\n\n  atoms.resize(natom);\n  for (int i = 0; i < natom; i++)\n    is >> atoms[i].zval >> atoms[i].x >> atoms[i].y >> atoms[i].z;\n}\n\nvoid read_1e_ints(Matrix& A, const std::string& filename) {\n  std::ifstream is(filename);\n  assert(is.good());\n\n  while (is) {\n    int i, j;\n    double val;\n    is >> i >> j >> val;\n    --i; --j;\n    A(i,j) = A(j,i) = val;\n  }\n}\n\ndouble* read_2e_ints(const std::string& filename, size_t nao) {\n  auto nints = ((nao * (nao + 1) / 2) * ((nao * (nao + 1) / 2) + 1) / 2);\n  auto result = new double[nints];\n  std::fill(result, result+nints, 0);\n\n  std::ifstream is(filename);\n  assert(is.good());\n\n  while (is) {\n    size_t i, j, k, l;\n    double val;\n    is >> i >> j >> k >> l >> val;\n    auto ij = INDEX(i - 1, j - 1);\n    auto kl = INDEX(k - 1, l - 1);\n    auto ijkl = INDEX(ij, kl);\n\n    result[ijkl] = val;\n  }\n\n  return result;\n}\n", "meta": {"hexsha": "b60b44795844b760f4873218eb67364f7df83190", "size": 7211, "ext": "cc", "lang": "C++", "max_stars_repo_path": "OldHPCSummerSchool/Hartree-Fock/hf.v2/scf.cc", "max_stars_repo_name": "wadejong/Summer-School-Materials", "max_stars_repo_head_hexsha": "82469995a79c667e940313d423e93c7c675e0a7c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-08-06T22:18:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-15T06:04:43.000Z", "max_issues_repo_path": "OldHPCSummerSchool/Hartree-Fock/hf.v2/scf.cc", "max_issues_repo_name": "wadejong/Summer-School-Materials", "max_issues_repo_head_hexsha": "82469995a79c667e940313d423e93c7c675e0a7c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "OldHPCSummerSchool/Hartree-Fock/hf.v2/scf.cc", "max_forks_repo_name": "wadejong/Summer-School-Materials", "max_forks_repo_head_hexsha": "82469995a79c667e940313d423e93c7c675e0a7c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2018-07-30T17:21:45.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-21T15:54:16.000Z", "avg_line_length": 27.3143939394, "max_line_length": 104, "alphanum_fraction": 0.5179586742, "num_tokens": 2203, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950907764118, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.49376399163971907}}
{"text": "// Copyright 2020 Erik Kouters (Falcons)\n// SPDX-License-Identifier: Apache-2.0\n#ifndef GEOMETRY_INTERSECT_HPP\n#define GEOMETRY_INTERSECT_HPP\n\n#include \"vector2d.hpp\"\n\n#include <vector>\n#include <boost/optional.hpp>\n\nnamespace geometry\n{\n\nclass PolynomialEquation\n{\npublic:\n    PolynomialEquation(double x0, double x1, double x2);\n\n    void solve();\n\n    boost::optional<double> getMinNonNegative() const;\n\nprivate:\n    std::vector<double> polynome_;\n    boost::optional<std::vector<double>> roots_;\n\n    void solveOrder2();\n};\n\nclass KinematicIntersect\n{\npublic:\n    static boost::optional<Vector2D> intersect(\n        const Vector2D &actor_position, double max_actor_speed,\n        const Vector2D &target_position, const Vector2D &target_velocity);\n};\n\n} // namespace geometry\n\n#endif // GEOMETRY_INTERSECT_HPP\n", "meta": {"hexsha": "da4aa005d1e21eda8bd82d9f11c69f31284a6ec1", "size": 813, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "packages/facilities/geometry/include/ext/intersect.hpp", "max_stars_repo_name": "Falcons-Robocup/code", "max_stars_repo_head_hexsha": "2281a8569e7f11cbd3238b7cc7341c09e2e16249", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-01-15T13:27:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-04T08:40:52.000Z", "max_issues_repo_path": "packages/facilities/geometry/include/ext/intersect.hpp", "max_issues_repo_name": "Falcons-Robocup/code", "max_issues_repo_head_hexsha": "2281a8569e7f11cbd3238b7cc7341c09e2e16249", "max_issues_repo_licenses": ["Apache-2.0"], "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/facilities/geometry/include/ext/intersect.hpp", "max_forks_repo_name": "Falcons-Robocup/code", "max_forks_repo_head_hexsha": "2281a8569e7f11cbd3238b7cc7341c09e2e16249", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2018-05-01T10:39:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T03:02:35.000Z", "avg_line_length": 19.8292682927, "max_line_length": 74, "alphanum_fraction": 0.7392373924, "num_tokens": 198, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950868503681, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.49376398934258636}}
{"text": "#ifndef INCLUDED_STDDEFX\n#include \"stddefx.h\"\n#define INCLUDED_STDDEFX\n#endif\n\n#ifndef INCLUDED_COM_DIMAP\n#include \"com_dimap.h\"\n#define INCLUDED_COM_DIMAP\n#endif\n\n#ifndef INCLUDED_BOOST_MATH_SPECIAL_FUNCTIONS_ROUND\n#include <boost/math/special_functions/round.hpp>\n#define INCLUDED_BOOST_MATH_SPECIAL_FUNCTIONS_ROUND\n#endif\n\n\n//------------------------------------------------------------------------------\n// DEFINITION OF STATIC CLASS MEMBERS\n//------------------------------------------------------------------------------\n\nconst double com::DiMap::logMin = 1.0e-150;\n\n\n\nconst double com::DiMap::logMax = 1.0e150;\n\n\n\n//------------------------------------------------------------------------------\n// DEFINITION OF CLASS MEMBERS\n//------------------------------------------------------------------------------\n\n/*!\n  The double and integer intervals are both set to [0,1].\n*/\ncom::DiMap::DiMap()\n\n  : d_x1(0.0), d_x2(1.0), d_y1(0), d_y2(1), d_cnv(1.0)\n\n{\n}\n\n\n\n/*!\n  \\param   i1 First border of integer interval.\n  \\param   i2 Second border of integer interval.\n  \\param   d1 First border of double interval.\n  \\param   d2 Second border of double interval.\n  \\param   logarithmic Logarithmic mapping, true or false. Defaults to false.\n\n  Constructs a com::DiMap instance with initial integer and double intervals.\n*/\ncom::DiMap::DiMap(int i1, int i2, double d1, double d2, bool logarithmic)\n\n  : d_x1(0.0), d_x2(1.0), d_y1(0), d_y2(1), d_cnv(1.0)\n\n{\n  d_log = logarithmic;\n  setIntRange(i1,i2);\n  setDblRange(d1, d2);\n}\n\n\n\ncom::DiMap::~DiMap()\n{\n}\n\n\n\n/*!\n  \\param   x Value.\n  \\return  If \\a x lies inside or at the border of the double range.\n*/\nbool com::DiMap::contains(double x) const\n{\n  return ( (x >= MIN(d_x1, d_x1)) && (x <= MAX(d_x1, d_x2)));\n}\n\n\n\n/*!\n  \\param   x Value.\n  \\return  If \\a x lies inside or at the border of the integer range.\n*/\nbool com::DiMap::contains(int x) const\n{\n  return (x >= MIN(d_y1, d_y1)) && (x <= MAX(d_y1, d_y2));\n}\n\n\n\n/*!\n  \\param   d1 First border.\n  \\param   d2 Second border.\n  \\param   lg Logarithmic (true) or linear (false) scaling. Defaults to false.\n*/\nvoid com::DiMap::setDblRange(double d1, double d2, bool lg)\n{\n  if(lg)\n  {\n    d_log = true;\n    if(d1 < logMin)\n      d1 = logMin;\n    else if(d1 > logMax)\n      d1 = logMax;\n\n    if(d2 < logMin)\n      d2 = logMin;\n    else if (d2 > logMax)\n      d2 = logMax;\n\n    d_x1 = std::log(d1);\n    d_x2 = std::log(d2);\n  }\n  else\n  {\n    d_log = false;\n    d_x1  = d1;\n    d_x2  = d2;\n  }\n\n  newFactor();\n}\n\n\n\n/*!\n  \\param   i1 First border.\n  \\param   i2 Second border.\n*/\nvoid com::DiMap::setIntRange(int i1, int i2)\n{\n  d_y1 = i1;\n  d_y2 = i2;\n  newFactor();\n}\n\n\n\n/*!\n  \\param  x Value in double interval.\n  \\return Transformed value in int interval.\n  \\sa     invTransform(), limTransform()\n\n  linear mapping: round(i1 + (i2 - i1) / (d2 - d1) * (x - d1))\n\n  logarithmic mapping: round(i1 + (i2 - i1) / log(d2 / d1) * log(x / d1))\n\n  The specified value is allowed to lie outside the intervals. If you want to\n  limit the returned value, use limTransform().\n*/\nint com::DiMap::transform(double x) const\n{\n  if(d_log)\n    return (d_y1 + boost::math::iround((std::log(x) - d_x1) * d_cnv));\n  else\n    return (d_y1 + boost::math::iround((x - d_x1) * d_cnv));\n}\n\n\n\n/*!\n  \\param   y Integer value to be transformed.\n  \\return  Transformed value in double interval.\n  \\sa      transform(), limTransform()\n\n  linear mapping: d1 + (d2 - d1) / (i2 - i1) * (y - i1)\n\n  logarithmic mapping: d1 + (d2 - d1) / log(i2 / i1) * log(y / i1)\n*/\ndouble com::DiMap::invTransform(int y) const\n{\n  if(d_cnv == 0.0)\n  {\n    return 0.0;\n  }\n  else\n  {\n    if(d_log)\n      return std::exp(d_x1 + double(y - d_y1) / d_cnv);\n    else\n      return (d_x1 + double(y - d_y1) / d_cnv);\n  }\n}\n\n\n\n/*!\n  \\param   x Value to be transformed.\n  \\return  Transformed value.\n  \\sa      transform(), invTransform()\n\n  The function is similar to transform, but limits the input value to the\n  nearest border of the map's double interval if it lies outside that interval.\n*/\nint com::DiMap::limTransform(double x) const\n{\n  if(x > MAX(d_x1, d_x2))\n    x = MAX(d_x1, d_x2);\n  else if(x < MIN(d_x1, d_x2))\n    x = MIN(d_x1, d_x2);\n\n  return transform(x);\n}\n\n\n\n/*!\n  \\param   x Value to be transformed.\n  \\return  Transformed value.\n  \\sa\n\n  linear mapping: i1 + (i2 - i1) / (d2 - d1) * (x - d1)\n  logarithmic mapping: i1 + (i2 - i1) / log(d2 / d1) * log(x / d1)\n\n  This function is similar to transform(), but makes the integer interval\n  appear to be double.\n*/\n//------------------------------------------------------------\ndouble com::DiMap::xTransform(double x) const\n{\n  double rv;\n\n  if(d_log) {\n    rv = static_cast<double>(d_y1) + (std::log(x) - d_x1) * d_cnv;\n  }\n  else {\n    rv = static_cast<double>(d_y1) + (x - d_x1) * d_cnv;\n  }\n\n  return rv;\n}\n\n\n\nvoid com::DiMap::newFactor()\n{\n  if(d_x2 != d_x1)\n    d_cnv = static_cast<double>(d_y2 - d_y1) / (d_x2 - d_x1);\n  else\n    d_cnv = 0.0;\n}\n\n\n\ndouble com::DiMap::d1() const\n{\n  return d_x1;\n}\n\n\n\ndouble com::DiMap::d2() const\n{\n  return d_x2;\n}\n\n\n\nint com::DiMap::i1() const\n{\n  return d_y1;\n}\n\n\n\nint com::DiMap::i2() const\n{\n  return d_y2;\n}\n\n\n\ndouble com::DiMap::scale() const\n{\n  return d_cnv;\n}\n\n\n\n//------------------------------------------------------------------------------\n// DOCUMENTATION OF ENUMERATIONS\n//------------------------------------------------------------------------------\n\n\n\n//------------------------------------------------------------------------------\n// DOCUMENTATION OF INLINE FUNCTIONS\n//------------------------------------------------------------------------------\n\n/*!\n  \\fn      bool com::DiMap::logarithmic() const\n  \\return  True if the double interval is scaled logarithmically.\n*/\n\n\n", "meta": {"hexsha": "b08ee1b86366ad2afd866f7603aa632218270274", "size": 5740, "ext": "cc", "lang": "C++", "max_stars_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcrcom/com_dimap.cc", "max_stars_repo_name": "quanpands/wflow", "max_stars_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcrcom/com_dimap.cc", "max_issues_repo_name": "quanpands/wflow", "max_issues_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcrcom/com_dimap.cc", "max_forks_repo_name": "quanpands/wflow", "max_forks_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.1973244147, "max_line_length": 80, "alphanum_fraction": 0.5503484321, "num_tokens": 1693, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744939732856, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4937592633528589}}
{"text": "#ifndef _POSE_ESTIMATION_ORIENTATION_UKF_HPP\n#define _POSE_ESTIMATION_ORIENTATION_UKF_HPP\n\n#include \"OrientationState.hpp\"\n#include \"OrientationUKFConfig.hpp\"\n#include <pose_estimation/Measurement.hpp>\n#include <pose_estimation/UnscentedKalmanFilter.hpp>\n#include <Eigen/Core>\n\nnamespace pose_estimation\n{\n\n/**\n * This filter estimates the orientation of an IMU in the NWU navigation frame.\n * It integrates rotation rates, accelerations and linear velocities.\n * The linear velocities help to constrain the acceleration and to estimate the biases.\n * Given gyroscopes capable of sensing the rotation of the earth (e.g. a fibre optic gyro)\n * this filter is able to estimate it's true heading.\n */\nclass OrientationUKF : public UnscentedKalmanFilter<OrientationState>\n{\npublic:\n    MEASUREMENT(RotationRate, 3)\n    MEASUREMENT(Acceleration, 3)\n    MEASUREMENT(VelocityMeasurement, 3)\n\npublic:\n    OrientationUKF(const State& initial_state, const Covariance& state_cov,\n                   double gyro_bias_tau, double acc_bias_tau, const LocationConfiguration& location);\n    virtual ~OrientationUKF() {}\n\n    /**\n     * Sets the current rotation rate of the IMU in rad/s.\n     */\n    void integrateMeasurement(const RotationRate& measurement);\n\n    /**\n     * Sets the current acceleration of the IMU in m/s^2.\n     */\n    void integrateMeasurement(const Acceleration& measurement);\n\n    /**\n     * Integrate the linear velocitiy of the IMU in m/s.\n     */\n    void integrateMeasurement(const VelocityMeasurement& measurement);\n\n    /* Returns unbiased rotation rate in IMU frame */\n    RotationRate::Mu getRotationRate();\n    \nprotected:\n    void predictionStepImpl(double delta);\n\nprotected:\n    RotationRate rotation_rate;\n    Acceleration acceleration;\n    Eigen::Vector3d earth_rotation;\n    double gyro_bias_tau;\n    double acc_bias_tau;\n};\n\n}\n\n#endif", "meta": {"hexsha": "de62304d6e3bf18f43c1ecd7f53c9e5867550052", "size": 1857, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/orientation_estimator/OrientationUKF.hpp", "max_stars_repo_name": "rock-slam/slam-pose_estimation", "max_stars_repo_head_hexsha": "66c516b2bed5f9a826811e34cf24b08b0483e508", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2017-06-13T07:26:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T02:51:09.000Z", "max_issues_repo_path": "src/orientation_estimator/OrientationUKF.hpp", "max_issues_repo_name": "rock-slam/slam-pose_estimation", "max_issues_repo_head_hexsha": "66c516b2bed5f9a826811e34cf24b08b0483e508", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2016-04-26T16:46:41.000Z", "max_issues_repo_issues_event_max_datetime": "2016-04-27T16:10:23.000Z", "max_forks_repo_path": "src/orientation_estimator/OrientationUKF.hpp", "max_forks_repo_name": "rock-slam/slam-pose_estimation", "max_forks_repo_head_hexsha": "66c516b2bed5f9a826811e34cf24b08b0483e508", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-04-20T12:29:02.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-05T14:47:10.000Z", "avg_line_length": 29.4761904762, "max_line_length": 101, "alphanum_fraction": 0.7452880991, "num_tokens": 403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744939732856, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4937592633528588}}
{"text": "#include <Eigen/Core>\n#include <gtest/gtest.h>\n\n#include \"test/utils.hpp\"\n\n#include \"ldaplusplus/e_step_utils.hpp\"\n#include \"ldaplusplus/utils.hpp\"\n\nusing namespace Eigen;\nusing namespace ldaplusplus;\n\n\n// T will be available as TypeParam in TYPED_TEST functions\ntemplate <typename T>\nclass TestApproximateSupervisedExpectationStep : public ParameterizedTest<T> {};\n\nTYPED_TEST_CASE(TestApproximateSupervisedExpectationStep, ForFloatAndDouble);\n\nTYPED_TEST(TestApproximateSupervisedExpectationStep, ComputeApproximateSupervisedPhi) {\n    VectorXi X(10);\n    X << 22, 49, 0, 2, 16, 35, 94, 3, 25, 10;\n    VectorX<TypeParam> X_ratio = X.cast<TypeParam>() / X.sum();\n    int  y = 0;\n\n    MatrixX<TypeParam> phi = MatrixX<TypeParam>::Random(5, 10);\n    VectorX<TypeParam> alpha = VectorX<TypeParam>::Constant(5, 0.2);\n    MatrixX<TypeParam> beta = MatrixX<TypeParam>::Random(5, 10);\n    MatrixX<TypeParam> eta = MatrixX<TypeParam>::Random(5, 3);\n    VectorX<TypeParam> gamma(beta.rows());\n\n    // Normalize beta and phi\n    beta.array() -= beta.minCoeff() - 0.001;\n    beta.array().rowwise() /= beta.colwise().sum().array();\n\n    phi.array() -= phi.minCoeff() - 0.001;\n    phi.array().rowwise() /= phi.colwise().sum().array();\n\n    // Compute gamma according to the random phi\n    e_step_utils::compute_gamma<TypeParam>(\n        X,\n        alpha,\n        phi,\n        gamma\n    );\n\n    // Make copies of phi\n    MatrixX<TypeParam> phi_unsupervised = phi;\n    MatrixX<TypeParam> phi_supervised = phi;\n    MatrixX<TypeParam> phi_supervised_approximation = phi;\n\n    // Make copies of gamma\n    VectorX<TypeParam> gamma_unsupervised = gamma;\n    VectorX<TypeParam> gamma_supervised = gamma;\n    VectorX<TypeParam> gamma_supervised_approximation = gamma;\n\n    VectorX<TypeParam> h(5);\n\n    TypeParam likelihood_baseline = e_step_utils::compute_supervised_likelihood(\n        X,\n        y,\n        alpha,\n        beta,\n        eta,\n        phi,\n        gamma\n    );\n\n    size_t fixed_point_iterations = 5;\n\n    for (int i=0; i<50; i++) {\n        // Compute phi with unsupervised method\n        e_step_utils::compute_unsupervised_phi<TypeParam> (\n            beta,\n            gamma_unsupervised,\n            phi_unsupervised\n        );\n        // Compute gamma\n        e_step_utils::compute_gamma <TypeParam> (\n            X,\n            alpha,\n            phi_unsupervised,\n            gamma_unsupervised\n        );\n    }\n\n    // Compute new likelihood\n    TypeParam likelihood_unsupervised = e_step_utils::compute_supervised_likelihood(\n        X,\n        y,\n        alpha,\n        beta,\n        eta,\n        phi_unsupervised,\n        gamma_unsupervised\n    );\n\n    for (int i=0; i<50; i++) {\n        // Compute phi with the supervised method\n        e_step_utils::compute_supervised_phi_gamma<TypeParam> (\n            X,\n            X_ratio,\n            y,\n            beta,\n            eta,\n            fixed_point_iterations,\n            phi_supervised,\n            gamma_supervised,\n            h\n        );\n    }\n\n    // Compute new likelihood\n    TypeParam likelihood_supervised = e_step_utils::compute_supervised_likelihood(\n        X,\n        y,\n        alpha,\n        beta,\n        eta,\n        phi_supervised,\n        gamma_supervised\n    );\n\n    TypeParam C = 1.0;\n    for (int i=0; i<50; i++) {\n        // Compute phi with the supervised approximation\n        e_step_utils::compute_supervised_approximate_phi<TypeParam> (\n            X_ratio,\n            X.sum(),\n            y,\n            beta,\n            eta,\n            gamma_supervised_approximation,\n            C,\n            phi_supervised_approximation\n        );\n\n        // Compute gamma\n        e_step_utils::compute_gamma<TypeParam> (\n            X,\n            alpha,\n            phi_supervised_approximation,\n            gamma_supervised_approximation\n        );\n    }\n    // Compute new likelihood\n    TypeParam likelihood_supervised_approximation = e_step_utils::compute_supervised_likelihood(\n        X,\n        y,\n        alpha,\n        beta,\n        eta,\n        phi_supervised_approximation,\n        gamma_supervised_approximation\n    );\n\n    EXPECT_GT(likelihood_supervised_approximation, likelihood_baseline);\n    // EXPECT_GT(likelihood_supervised_approximation, likelihood_unsupervised);\n    // EXPECT_GT(likelihood_supervised, likelihood_unsupervised);\n    //\n    // What should the following be\n    //\n    // EXPECT_GT(likelihood_supervised_approximation, likelihood_supervised);\n}\n\nTYPED_TEST(TestApproximateSupervisedExpectationStep, ComputeApproximatePhiWithEmptyDocument) {\n    VectorX<TypeParam> X_ratio = VectorX<TypeParam>::Zero(10);\n    int  y = 0;\n    TypeParam C = 1.0;\n\n    MatrixX<TypeParam> phi = MatrixX<TypeParam>::Random(5, 10);\n    VectorX<TypeParam> alpha = VectorX<TypeParam>::Constant(5, 0.2);\n    MatrixX<TypeParam> beta = MatrixX<TypeParam>::Random(5, 10);\n    MatrixX<TypeParam> eta = MatrixX<TypeParam>::Random(5, 3);\n    VectorX<TypeParam> gamma(beta.rows());\n\n    // Normalize beta and phi\n    beta.array() -= beta.minCoeff() - 0.001;\n    beta.array().rowwise() /= beta.colwise().sum().array();\n\n    phi.array() -= phi.minCoeff() - 0.001;\n    phi.array().rowwise() /= phi.colwise().sum().array();\n\n    // Compute gamma according to the random phi\n    e_step_utils::compute_gamma<TypeParam>(\n        VectorXi::Zero(10),\n        alpha,\n        phi,\n        gamma\n    );\n\n    // Compute phi and gamma\n    e_step_utils::compute_supervised_approximate_phi<TypeParam> (\n        X_ratio,\n        0,\n        y,\n        beta,\n        eta,\n        gamma,\n        C,\n        phi\n    );\n    e_step_utils::compute_gamma<TypeParam>(\n        VectorXi::Zero(10),\n        alpha,\n        phi,\n        gamma\n    );\n\n    auto cwise_isnan = math_utils::CwiseIsNaN<TypeParam>();\n    EXPECT_FALSE(phi.unaryExpr(cwise_isnan).any());\n    EXPECT_FALSE(gamma.unaryExpr(cwise_isnan).any());\n}\n", "meta": {"hexsha": "26edbbada89c213dbcd4771ebfd9d22116fa860f", "size": 5875, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_approximate_supervised_expectation_step.cpp", "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": "test/test_approximate_supervised_expectation_step.cpp", "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": "test/test_approximate_supervised_expectation_step.cpp", "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": 27.5821596244, "max_line_length": 96, "alphanum_fraction": 0.618893617, "num_tokens": 1440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834648, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.493759257984013}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2020-2021 Mikhail Komarov <nemo@nil.foundation>\n// Copyright (c) 2020-2021 Nikita Kaskov <nbering@nil.foundation>\n//\n// MIT License\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n//---------------------------------------------------------------------------//\n\n#define BOOST_TEST_MODULE bilinearity_algebra_test\n\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 <nil/crypto3/algebra/curves/edwards.hpp>\n#include <nil/crypto3/algebra/curves/bn128.hpp>\n#include <nil/crypto3/algebra/curves/alt_bn128.hpp>\n#include <nil/crypto3/algebra/curves/mnt4.hpp>\n#include <nil/crypto3/algebra/curves/mnt6.hpp>\n\nusing namespace nil::crypto3::algebra;\n\ntemplate<typename CurveType>\nvoid pairing_test() {\n    GT<CurveType> GT_one = GT<CurveType>::one();\n\n    printf(\"Running bilinearity tests:\\n\");\n    G1<CurveType> P = (Fr<CurveType>::random_element()) * G1<CurveType>::one();\n    // G1<CurveType> P = Fr<CurveType>(\"2\") * G1<CurveType>::one();\n    G2<CurveType> Q = (Fr<CurveType>::random_element()) * G2<CurveType>::one();\n    // G2<CurveType> Q = Fr<CurveType>(\"3\") * G2<CurveType>::one();\n\n    printf(\"P:\\n\");\n    P.print();\n    P.print_coordinates();\n    printf(\"Q:\\n\");\n    Q.print();\n    Q.print_coordinates();\n    printf(\"\\n\\n\");\n\n    Fr<CurveType> s = Fr<CurveType>::random_element();\n    // Fr<CurveType> s = Fr<CurveType>(\"2\");\n    G1<CurveType> sP = s * P;\n    G2<CurveType> sQ = s * Q;\n\n    printf(\"Pairing bilinearity tests (three must match):\\n\");\n    GT<CurveType> ans1 = CurveType::pair_reduced(sP, Q);\n    GT<CurveType> ans2 = CurveType::pair_reduced(P, sQ);\n    GT<CurveType> ans3 = CurveType::pair_reduced(P, Q) ^ s;\n    ans1.print();\n    ans2.print();\n    ans3.print();\n    assert(ans1 == ans2);\n    assert(ans2 == ans3);\n\n    assert(ans1 != GT_one);\n    assert((ans1 ^ Fr<CurveType>::field_char()) == GT_one);\n    printf(\"\\n\\n\");\n}\n\ntemplate<typename CurveType>\nvoid double_miller_loop_test() {\n    const G1<CurveType> P1 = (Fr<CurveType>::random_element()) * G1<CurveType>::one();\n    const G1<CurveType> P2 = (Fr<CurveType>::random_element()) * G1<CurveType>::one();\n    const G2<CurveType> Q1 = (Fr<CurveType>::random_element()) * G2<CurveType>::one();\n    const G2<CurveType> Q2 = (Fr<CurveType>::random_element()) * G2<CurveType>::one();\n\n    const typename CurveType::pairing::g1_precomp prec_P1 = CurveType::precompute_G1(P1);\n    const typename CurveType::pairing::g1_precomp prec_P2 = CurveType::precompute_G1(P2);\n    const typename CurveType::pairing::g2_precomp prec_Q1 = CurveType::precompute_G2(Q1);\n    const typename CurveType::pairing::g2_precomp prec_Q2 = CurveType::precompute_G2(Q2);\n\n    const typename CurveType::pairing::fqk_type ans_1 = CurveType::miller_loop(prec_P1, prec_Q1);\n    const typename CurveType::pairing::fqk_type ans_2 = CurveType::miller_loop(prec_P2, prec_Q2);\n    const typename CurveType::pairing::fqk_type ans_12 =\n        CurveType::double_miller_loop(prec_P1, prec_Q1, prec_P2, prec_Q2);\n    assert(ans_1 * ans_2 == ans_12);\n}\n\ntemplate<typename CurveType>\nvoid affine_pairing_test() {\n    GT<CurveType> GT_one = GT<CurveType>::one();\n\n    printf(\"Running bilinearity tests:\\n\");\n    G1<CurveType> P = (Fr<CurveType>::random_element()) * G1<CurveType>::one();\n    G2<CurveType> Q = (Fr<CurveType>::random_element()) * G2<CurveType>::one();\n\n    printf(\"P:\\n\");\n    P.print();\n    printf(\"Q:\\n\");\n    Q.print();\n    printf(\"\\n\\n\");\n\n    Fr<CurveType> s = Fr<CurveType>::random_element();\n    G1<CurveType> sP = s * P;\n    G2<CurveType> sQ = s * Q;\n\n    printf(\"Pairing bilinearity tests (three must match):\\n\");\n    GT<CurveType> ans1 = CurveType::affine_pair_reduced(sP, Q);\n    GT<CurveType> ans2 = CurveType::affine_pair_reduced(P, sQ);\n    GT<CurveType> ans3 = CurveType::affine_pair_reduced(P, Q) ^ s;\n    ans1.print();\n    ans2.print();\n    ans3.print();\n    assert(ans1 == ans2);\n    assert(ans2 == ans3);\n\n    assert(ans1 != GT_one);\n    assert((ans1 ^ Fr<CurveType>::field_char()) == GT_one);\n    printf(\"\\n\\n\");\n}\n\nint main(void) {\n    pairing_test<edwards_pp>();\n    double_miller_loop_test<edwards_pp>();\n\n    pairing_test<mnt6_pp>();\n    double_miller_loop_test<mnt6_pp>();\n    affine_pairing_test<mnt6_pp>();\n\n    pairing_test<mnt4_pp>();\n    double_miller_loop_test<mnt4_pp>();\n    affine_pairing_test<mnt4_pp>();\n\n    pairing_test<alt_bn128_pp>();\n    double_miller_loop_test<alt_bn128_pp>();\n\n    pairing_test<bn128_pp>();\n    double_miller_loop_test<bn128_pp>();\n}\n", "meta": {"hexsha": "04dd585fc3396845a37658ed4ad27ebb6db6b88e", "size": 5640, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "snark-logic/libs-source/algebra/test/bilinearity.cpp", "max_stars_repo_name": "idealatom/podlodkin-freeton-year-control", "max_stars_repo_head_hexsha": "6aa96e855fe065c9a75c76da976a87fe2d1668e6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "snark-logic/libs-source/algebra/test/bilinearity.cpp", "max_issues_repo_name": "idealatom/podlodkin-freeton-year-control", "max_issues_repo_head_hexsha": "6aa96e855fe065c9a75c76da976a87fe2d1668e6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "snark-logic/libs-source/algebra/test/bilinearity.cpp", "max_forks_repo_name": "idealatom/podlodkin-freeton-year-control", "max_forks_repo_head_hexsha": "6aa96e855fe065c9a75c76da976a87fe2d1668e6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-15T20:27:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-15T20:27:27.000Z", "avg_line_length": 38.1081081081, "max_line_length": 97, "alphanum_fraction": 0.6721631206, "num_tokens": 1574, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744806385543, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4937592552995901}}
{"text": "#ifndef __UTIL_H__\n#define __UTIL_H__\n\n#include <Eigen/Geometry>\n#include <vector>\n\n\n#include <opencv2/opencv.hpp>\n#include <cvx/util/camera/camera.hpp>\n#include <cvx/util/geometry/kdtree.hpp>\n#include <cvx/util/math/rng.hpp>\n\n// perform mean shift clustering of the points and choose the mode with larger number of votes\n\nvoid mean_shift(cvx::util::RNG &g, const std::vector<Eigen::Vector3f> &pts, Eigen::Vector3f &mode, float &weight, float sigma,\n                    unsigned int maxIter, float seed_perc, uint min_seeds) ;\n\nEigen::Vector3f back_project(const cv::Mat &depth, const cvx::util::PinholeCamera &cam, const cv::Point &pt) ;\n\n// Kabsch algorithm for rigid pose estimation between two point clouds ( finds T to minimize sum_i ||P_i * T - Q_i|| )\n\nEigen::Isometry3f find_rigid(const Eigen::Matrix3Xf &P, const Eigen::Matrix3Xf &Q) ;\nEigen::Isometry3f find_rigid(const std::vector<Eigen::Vector3f> &P, const std::vector<Eigen::Vector3f> &Q) ;\n\nvoid save_cloud_obj(const std::string &file_name, const std::vector<Eigen::Vector3f> &cloud) ;\n\n#endif\n", "meta": {"hexsha": "b9f740e2aef9a0cb8db78c6ff4b747f262d9794c", "size": 1058, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/util.hpp", "max_stars_repo_name": "malasiot/crf", "max_stars_repo_head_hexsha": "1bd7c3f8c06604e13fb30c5873132619228713e4", "max_stars_repo_licenses": ["MIT"], "max_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.hpp", "max_issues_repo_name": "malasiot/crf", "max_issues_repo_head_hexsha": "1bd7c3f8c06604e13fb30c5873132619228713e4", "max_issues_repo_licenses": ["MIT"], "max_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.hpp", "max_forks_repo_name": "malasiot/crf", "max_forks_repo_head_hexsha": "1bd7c3f8c06604e13fb30c5873132619228713e4", "max_forks_repo_licenses": ["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.7857142857, "max_line_length": 126, "alphanum_fraction": 0.7353497164, "num_tokens": 298, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.493759252615167}}
{"text": "#ifndef SQUAREDFUNCTIONINFO_H\n#define SQUAREDFUNCTIONINFO_H\n\n#include <opengv/optimization_tools/objective_function_tools/ObjectiveFunctionInfo.hpp>\n#include <Eigen/Dense>\n#include <opengv/types.hpp>\n#include <opengv/relative_pose/RelativeAdapterBase.hpp>\n\nclass SquaredFunctionInfo : public ObjectiveFunctionInfo {\n  Eigen::MatrixXd M;\n\n public:\n  SquaredFunctionInfo(const opengv::relative_pose::RelativeAdapterBase & adapter );\n  ~SquaredFunctionInfo();\n\n  Eigen::MatrixXd get_M();\n  double objective_function_value(const opengv::rotation_t & rotation, const opengv::translation_t & translation);\n  opengv::rotation_t rotation_gradient(const opengv::rotation_t & rotation, const opengv::translation_t & translation);\n  opengv::translation_t translation_gradient(const opengv::rotation_t & rotation, const opengv::translation_t & translation);\n};\n\t\t    \n#endif\n", "meta": {"hexsha": "961d67843e2bd7cc9d40fe8642ca3e1b391c2a4f", "size": 863, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/opengv/optimization_tools/objective_function_tools/SquaredFunctionInfo.hpp", "max_stars_repo_name": "mateus03/2018AMMPoseSolver", "max_stars_repo_head_hexsha": "787886846199cd0864c4e59a6545c40c3120010a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-05-15T12:41:36.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-07T10:42:52.000Z", "max_issues_repo_path": "include/opengv/optimization_tools/objective_function_tools/SquaredFunctionInfo.hpp", "max_issues_repo_name": "mateus03/2018AMMPoseSolver", "max_issues_repo_head_hexsha": "787886846199cd0864c4e59a6545c40c3120010a", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/optimization_tools/objective_function_tools/SquaredFunctionInfo.hpp", "max_forks_repo_name": "mateus03/2018AMMPoseSolver", "max_forks_repo_head_hexsha": "787886846199cd0864c4e59a6545c40c3120010a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-27T18:11:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-27T18:11:14.000Z", "avg_line_length": 37.5217391304, "max_line_length": 125, "alphanum_fraction": 0.8053302433, "num_tokens": 199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744584140003, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4937592418774745}}
{"text": "\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// Copyright Christopher Kormanyos 2016.\r\n\r\n// This file is written to be included from a Quickbook .qbk document.\r\n// It can be compiled by the C++ compiler, and run. Any output can\r\n// also be added here as comment or included or pasted in elsewhere.\r\n// Caution: this file contains Quickbook markup as well as code\r\n// and comments: don't change any of the special comment markups!\r\n\r\n// This file also includes Doxygen-style documentation about the function of the code.\r\n// See http://www.doxygen.org for details.\r\n\r\n//! \\file\r\n\r\n//! \\brief Example program showing a bare metal real-time performance measurement of sqrt(negatable), 16-bit.\r\n\r\n#include <cmath>\r\n#include <mcal_benchmark.h>\r\n#include <mcal_cpu.h>\r\n#include <mcal_irq.h>\r\n#include <mcal_port.h>\r\n\r\n#define BOOST_FIXED_POINT_DISABLE_MULTIPRECISION // Do not use Boost.Multiprecision.\r\n#define BOOST_FIXED_POINT_DISABLE_IOSTREAM       // Do not use I/O streaming.\r\n\r\n#include <boost/fixed_point/fixed_point.hpp>\r\n\r\ntypedef boost::fixed_point::negatable<4, -11> numeric_type;\r\n//typedef float numeric_type;\r\n\r\nnamespace app\r\n{\r\n  namespace benchmark\r\n  {\r\n    void task_init();\r\n    void task_func();\r\n  }\r\n\r\n  typedef mcal::benchmark::benchmark_port_type port_type;\r\n}\r\n\r\nnumeric_type x = numeric_type(6) / 10;\r\nnumeric_type y;\r\n\r\nvoid app::benchmark::task_init()\r\n{\r\n  port_type::set_direction_output();\r\n}\r\n\r\n\r\nvoid app::benchmark::task_func()\r\n{\r\n  using std::sqrt;\r\n\r\n  mcal::irq::disable_all();\r\n  port_type::set_pin_high();\r\n\r\n  y = sqrt(x);\r\n\r\n  port_type::set_pin_low();\r\n  mcal::irq::enable_all();\r\n\r\n  // sqrt(6/10) = approx. 0.7745966692414834\r\n  const bool value_is_ok =    (y > (numeric_type(7) / 10))\r\n                           && (y < (numeric_type(8) / 10));\r\n\r\n  if(value_is_ok)\r\n  {\r\n    // The benchmark is OK.\r\n    // Perform one nop and leave.\r\n\r\n    mcal::cpu::nop();\r\n  }\r\n  else\r\n  {\r\n    // The benchmark result is not OK!\r\n    // Remain in a blocking loop and crash the system.\r\n\r\n    for(;;) { mcal::cpu::nop(); }\r\n  }\r\n}\r\n", "meta": {"hexsha": "b975409c4dd8b8f3c7de06abe4b3ad4150847d4c", "size": 2217, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/fixed_point_bare_metal_benchmark_16bit_sqrt.cpp", "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": "example/fixed_point_bare_metal_benchmark_16bit_sqrt.cpp", "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": "example/fixed_point_bare_metal_benchmark_16bit_sqrt.cpp", "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": 25.4827586207, "max_line_length": 110, "alphanum_fraction": 0.6693730266, "num_tokens": 557, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105941403651, "lm_q2_score": 0.6224593452091672, "lm_q1q2_score": 0.49367620496761677}}
{"text": "/*\n@copyright Louis Dionne 2014\nDistributed under the Boost Software License, Version 1.0.\n(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n */\n\n#include <boost/hana/detail/assert.hpp>\n#include <boost/hana/integral.hpp>\n#include <boost/hana/list/instance.hpp>\n#include <boost/hana/range.hpp>\nusing namespace boost::hana;\n\n\nint main() {\n    //! [main]\n    BOOST_HANA_CONSTANT_ASSERT(\n        sum(range(int_<1>, int_<6>)) == int_<1 + 2 + 3 + 4 + 5>\n    );\n\n    BOOST_HANA_CONSTEXPR_ASSERT(\n        sum(list(1, int_<3>, long_<-5>, 9)) == 1 + 3 - 5 + 9\n    );\n    //! [main]\n}\n", "meta": {"hexsha": "d3c12adff17fc68dcea8bdf963966683c98c8436", "size": 603, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/foldable/sum.cpp", "max_stars_repo_name": "rbock/hana", "max_stars_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-05-07T14:29:13.000Z", "max_stars_repo_stars_event_max_datetime": "2015-07-04T10:59:46.000Z", "max_issues_repo_path": "example/foldable/sum.cpp", "max_issues_repo_name": "rbock/hana", "max_issues_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/foldable/sum.cpp", "max_forks_repo_name": "rbock/hana", "max_forks_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.12, "max_line_length": 78, "alphanum_fraction": 0.6451077944, "num_tokens": 182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.493676199946273}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// ars::test::standard_distribution.hpp                                      //\n//                                                                           //\n//  Copyright 2009 Erwann Rogard. Distributed under the Boost                //\n//  Software License, Version 1.0. (See accompanying file                    //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)         //\n///////////////////////////////////////////////////////////////////////////////\n#ifndef BOOST_STATISTICS_DETAIL_ARS_TEST_STANDARD_DISTRIBUTION_HPP_ER_2009\n#define BOOST_STATISTICS_DETAIL_ARS_TEST_STANDARD_DISTRIBUTION_HPP_ER_2009\n\n#include <iostream>\n#include <list>\n#include <string>\n#include <iterator>\n#include <vector>\n#include <algorithm>\n\n#include <boost/format.hpp>\n#include <boost/range.hpp>\n#include <boost/accumulators/accumulators.hpp>\n\n#include <boost/statistics/detail/distribution_common/meta/random/generator.hpp>\n#include <boost/statistics/detail/distribution_common/meta/value.hpp>\n#include <boost/statistics/detail/non_parametric/kolmogorov_smirnov/statistic.hpp>\n\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <boost/random/ref_distribution.hpp>\n\n#include <boost/ars/function/adaptor.hpp>\n#include <boost/ars/constant.hpp>\n#include <boost/ars/proposal_sampler.hpp>\n#include <boost/ars/sampler.hpp>\n\nnamespace boost{\nnamespace statistics{\nnamespace detail{\nnamespace ars{\nnamespace test{\n\nstruct standard_distribution{\n\n\tstatic void header(std::ostream& os){\n    \tos << \"This test outputs a sequence {(a,b,c)} where\" << std::endl;\n    \tos \t<< \"a : sample size\" << std::endl\n     \t\t<< \"b : kolmogorov-smirnov statistic\" << std::endl\n     \t\t<< \"c : avg number of rejections\" << std::endl;\n    }\n\n\t// Samples from distribution D using adaptive rejection sampling and outputs\n    // convergence statistics\n\ttemplate<typename D,typename U>\n\tstatic void call(\n    \tconst D& mdist, //e.g. D == math::normal_distribution<T>\n    \ttypename D::value_type x_min,\n    \ttypename D::value_type x_max,\n    \ttypename D::value_type init_0,\n    \ttypename D::value_type init_1,\n    \tU& urng,\n    \tunsigned n1,   // # loops\n    \tunsigned n2,   // # subsamples per loop  \n    \tunsigned n3,   // size of subsample \n    \tunsigned n4,   // At each loop, n2 *= n4\n    \tunsigned n_max_reject,\n    \tstd::ostream& os\n\t){\n\n    \t// The ars is re-initialized after each n3 sample.\n    \t// n3 * n4 is the total size of the sample over which a KS is computed\n\n    \tnamespace dist = boost::statistics::detail::distribution;\n    \tnamespace ks = boost::statistics::detail::kolmogorov_smirnov;\n    \ttypedef std::string                                     str_;\n    \ttypedef std::runtime_error                              err_;\n        typedef typename D::value_type\t\t\t\t\t\t\tval_;\n    \ttypedef std::vector<val_>                               vals_;\n\n    \ttypedef ars::function::adaptor<D>                       fun_t;\n    \ttypedef ars::proposal_sampler<val_,std::vector>         ps_;\n    \ttypedef ars::sampler<ps_>                               ars_;\n    \ttypedef random::ref_distribution<ars_&>                 ref_ars_;\n    \ttypedef variate_generator<U&,ref_ars_>                  vg_ars_;\n\n    \ttypedef ks::tag::statistic<val_> \t\t\t\t\t\ttag_ks_;\n    \ttypedef boost::accumulators::stats<tag_ks_> \t\t\tacc_features_;\n    \ttypedef boost::accumulators::accumulator_set<val_,acc_features_> acc_;\n\n    \tars_ ars;\n    \tars.set_function(x_min, x_max, fun_t(mdist));\n    \t{\n    \t\tstatic const str_ str \n        \t\t= \"Initialized every %1% draw(s) with x1 = %2% and x2 = %3%\";\n        \tboost::format f(str);\n        \tf%n3%init_0%init_1;\n        \tos << f.str() << std::endl;\n        \tos << description(mdist) << std::endl;\n    \t}\n    \tlong unsigned n_reject;\n    \n    \ttry{\n        \tfor(unsigned i1 = 0; i1<n1; i1++){\n            \tn_reject = 0;\n            \tacc_ acc;\n            \tfor(unsigned i2 = 0; i2<n2; i2++){\n                \ttry{\n                    \tars.initialize(init_0,init_1);\n                    \tvg_ars_ vg_ars(urng,ref_ars_(ars)); \n                    \tfor(unsigned i = 0; i<n3; i++)\n                    \t{\n\t\t\t\t\t\t\tval_ x = vg_ars();\n\t\t\t\t\t\t\tacc(x);\n                    \t}\n                    \t// Without ref_ars_, n would be reset to 0\n                    \tn_reject += (\n                        \t(vg_ars.distribution()).distribution()\n                    \t).n_reject();\n                \t}catch(std::exception& e){\n                    \tboost::format f(\"at i1 = %1%, i2 = %2% : %3%\"); \n                    \tf % i1 % i2 % e.what();\n                    \tthrow std::runtime_error(f.str());\n                \t}\n            \t}\n            \tlong int n = boost::accumulators::extract::count(acc);\n            \tval_ st = ks::extract::statistic<val_>(acc,mdist);\n            \tval_ rate = static_cast<val_>(n_reject)/static_cast<val_>(n3*n2);\n            \tos \n                \t<< '(' \n                \t<< n\n                \t<< ','\n                \t<< st\n                \t<< ','\n                \t<< rate \n                \t<< ')'\n                \t<< std::endl;\n            \tn2 *= n4;\n        \t}\n    \t}catch(std::exception& e)\n    \t{\n        \tstd::cerr << e.what() << std::endl;\n    \t}\n    \tos << std::endl;\n\t}\n};\n\n}//test\n}// ars\n}// detail\n}// statistics\n}// boost\n\n#endif\n\n\n", "meta": {"hexsha": "ab2f5eb22d070a7f4a49c05d26e270ace18fa5ad", "size": 5374, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "adaptive_rejection_sampling/boost/ars/test/standard_distribution.hpp", "max_stars_repo_name": "rogard/boost_sandbox_statistics", "max_stars_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "adaptive_rejection_sampling/boost/ars/test/standard_distribution.hpp", "max_issues_repo_name": "rogard/boost_sandbox_statistics", "max_issues_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "adaptive_rejection_sampling/boost/ars/test/standard_distribution.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": 34.8961038961, "max_line_length": 82, "alphanum_fraction": 0.5329363603, "num_tokens": 1286, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.493676199946273}}
{"text": "#ifdef MEX\n\n#include <igl/AABB.h>\n#include <igl/in_element.h>\n#include <igl/matlab/MexStream.h>\n#include <igl/matlab/mexErrMsgTxt.h>\n#include <igl/matlab/prepare_lhs.h>\n#include <igl/matlab/parse_rhs.h>\n\n#include <mex.h>\n#include <Eigen/Dense>\n#include <iostream>\n\n#include <cstring>\n#include <iostream>\nvoid parse_rhs(\n  const int nrhs, \n  const mxArray *prhs[], \n  Eigen::MatrixXd & V,\n  Eigen::MatrixXi & Ele,\n  Eigen::MatrixXd & Q,\n  Eigen::MatrixXd & bb_mins,\n  Eigen::MatrixXd & bb_maxs,\n  Eigen::VectorXi & elements)\n{\n  using namespace std;\n  using namespace igl;\n  using namespace igl::matlab;\n  mexErrMsgTxt(nrhs >= 3, \"The number of input arguments must be >=3.\");\n\n  const int dim = mxGetN(prhs[0]);\n  mexErrMsgTxt(dim == 3 || dim == 2,\n    \"Mesh vertex list must be #V by 2 or 3 list of vertex positions\");\n\n  mexErrMsgTxt(dim+1 == mxGetN(prhs[1]),\n    \"Mesh \\\"face\\\" simplex size must equal dimension+1\");\n\n  parse_rhs_double(prhs,V);\n  parse_rhs_index(prhs+1,Ele);\n  parse_rhs_double(prhs+2,Q);\n  mexErrMsgTxt(Q.cols() == dim,\"Dimension of Q should match V\");\n  if(nrhs > 3)\n  {\n    mexErrMsgTxt(nrhs >= 6, \"The number of input arguments must be 3 or >=6.\");\n    parse_rhs_double(prhs+3,bb_mins);\n    if(bb_mins.size()>0)\n    {\n      mexErrMsgTxt(bb_mins.cols() == dim,\"Dimension of bb_mins should match V\");\n      mexErrMsgTxt(bb_mins.rows() >= Ele.rows(),\"|bb_mins| should be > |Ele|\");\n    }\n    parse_rhs_double(prhs+4,bb_maxs);\n    mexErrMsgTxt(bb_maxs.cols() == bb_mins.cols(),\n      \"|bb_maxs| should match |bb_mins|\");\n    mexErrMsgTxt(bb_mins.rows() == bb_maxs.rows(),\n      \"|bb_mins| should match |bb_maxs|\");\n    parse_rhs_index(prhs+5,elements);\n    mexErrMsgTxt(elements.cols() == 1,\"Elements should be column vector\");\n    mexErrMsgTxt(bb_mins.rows() == elements.rows(),\n      \"|bb_mins| should match |elements|\");\n  }else\n  {\n    // Defaults\n    bb_mins.resize(0,dim);\n    bb_maxs.resize(0,dim);\n    elements.resize(0,1);\n  }\n}\n\nvoid mexFunction(\n  int nlhs, mxArray *plhs[], \n  int nrhs, const mxArray *prhs[])\n{\n  using namespace std;\n  using namespace Eigen;\n  using namespace igl;\n  using namespace igl::matlab;\n\n  igl::matlab::MexStream mout;        \n  std::streambuf *outbuf = cout.rdbuf(&mout);\n  //mexPrintf(\"Compiled at %s on %s\\n\",__TIME__,__DATE__);\n\n  MatrixXd V,Q,bb_mins,bb_maxs;\n  MatrixXi Ele;\n  VectorXi elements;\n  VectorXi I;\n  parse_rhs(nrhs,prhs,V,Ele,Q,bb_mins,bb_maxs,elements);\n  bool was_serialized = bb_mins.size()>0;\n\n  switch(V.cols())\n  {\n    default:\n      mexErrMsgTxt(false,\"Un-supported dimension.\");\n      break;\n    case 3:\n    {\n      AABB<MatrixXd,3> aabb;\n      aabb.init(V,Ele,bb_mins,bb_maxs,elements);\n      in_element(V,Ele,Q,aabb,I);\n      if(nlhs>1 && !was_serialized)\n      {\n        aabb.serialize(bb_mins,bb_maxs,elements);\n      }\n      break;\n    }\n    case 2:\n    {\n      AABB<MatrixXd,2> aabb;\n      aabb.init(V,Ele,bb_mins,bb_maxs,elements);\n      in_element(V,Ele,Q,aabb,I);\n      if(nlhs>1 && !was_serialized)\n      {\n        aabb.serialize(bb_mins,bb_maxs,elements);\n      }\n      break;\n    }\n  }\n\n  switch(nlhs)\n  {\n    default:\n    {\n      mexErrMsgTxt(false,\"Too many output parameters.\");\n    }\n    case 4:\n    {\n      prepare_lhs_index(elements,plhs+3);\n      //fallthrough\n    }\n    case 3:\n    {\n      prepare_lhs_double(bb_maxs,plhs+2);\n      //fallthrough\n    }\n    case 2:\n    {\n      prepare_lhs_double(bb_mins,plhs+1);\n      //fallthrough\n    }\n    case 1:\n    {\n      prepare_lhs_index(I,plhs+0);\n      //fallthrough\n    }\n    case 0: break;\n  }\n\n  std::cout.rdbuf(outbuf);\n}\n\n#endif\n", "meta": {"hexsha": "5bbe890ea691e9d6eb8daa5572916b2cec858f28", "size": 3584, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Geometry_Processing_Toolbox/src/cppmex/in_element_aabb.cpp", "max_stars_repo_name": "sidgairo18/SCILAB_MEX_TOOLBOX", "max_stars_repo_head_hexsha": "fc679f6d226c03b992b632823a5e57abea05cefa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-02-08T08:37:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-24T01:52:38.000Z", "max_issues_repo_path": "Geometry_Processing_Toolbox/src/cppmex/in_element_aabb.cpp", "max_issues_repo_name": "sidgairo18/SCILAB_MEX_TOOLBOX", "max_issues_repo_head_hexsha": "fc679f6d226c03b992b632823a5e57abea05cefa", "max_issues_repo_licenses": ["MIT"], "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_Processing_Toolbox/src/cppmex/in_element_aabb.cpp", "max_forks_repo_name": "sidgairo18/SCILAB_MEX_TOOLBOX", "max_forks_repo_head_hexsha": "fc679f6d226c03b992b632823a5e57abea05cefa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-08-18T08:24:36.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-18T08:24:36.000Z", "avg_line_length": 23.7350993377, "max_line_length": 80, "alphanum_fraction": 0.6297433036, "num_tokens": 1092, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.766293653760418, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.49366561069363457}}
{"text": "// discrete_distribution.hpp\n//\n// Copyright (c) 2009\n// Steven Watanabe\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_RANDOM_DISCRETE_DISTRIBUTION_HPP_INCLUDED\n#define BOOST_RANDOM_DISCRETE_DISTRIBUTION_HPP_INCLUDED\n\n#include <vector>\n#include <cassert>\n#include <limits>\n#include <numeric>\n#include <utility>\n\n#include <boost/range.hpp>\n#include <boost/random/uniform_int.hpp>\n#include <boost/random/uniform_01.hpp>\n#include <boost/random/variate_generator.hpp>\n\nnamespace boost {\nnamespace random {\n\ntemplate<class IntType, class WeightType>\nclass discrete_distribution {\npublic:\n    typedef WeightType input_type;\n    typedef IntType result_type;\n\n    template<class Iter>\n    discrete_distribution(Iter begin, Iter end) : weights(begin, end), data(weights.size()) {\n        std::size_t size = weights.size();\n        //assert(size <= (std::numeric_limits<IntType>::max)());\n        std::vector<std::pair<WeightType, IntType> > below_average;\n        std::vector<std::pair<WeightType, IntType> > above_average;\n        WeightType weight_sum = std::accumulate(weights.begin(), weights.end(), static_cast<WeightType>(0));\n        WeightType weight_average = weight_sum / size;\n        for(std::size_t i = 0; i < size; ++i) {\n            if(weights[i] < weight_average) {\n                below_average.push_back(std::make_pair(weights[i] / weight_average, static_cast<IntType>(i)));\n            } else {\n                above_average.push_back(std::make_pair(weights[i] / weight_average, static_cast<IntType>(i)));\n            }\n        }\n        typedef typename range_iterator< \n            std::vector<\n                std::pair<WeightType, IntType> \n            >\n        >::type iter_;\n            iter_ b_iter = below_average.begin();\n            iter_ b_end = below_average.end();\n            iter_ a_iter = above_average.begin();\n            iter_ a_end = above_average.end();\n        while(b_iter != b_end && a_iter != a_end) {\n            data[b_iter->second] = std::make_pair(b_iter->first, a_iter->second);\n            a_iter->first -= (1 - b_iter->first);\n            if(a_iter->first < 1) {\n                *b_iter = *a_iter++;\n            } else {\n                ++b_iter;\n            }\n        }\n        for(; b_iter != b_end; ++b_iter) {\n            data[b_iter->second].first = 1;\n        }\n        for(; a_iter != a_end; ++a_iter) {\n            data[a_iter->second].first = 1;\n        }\n    }\n    template<class Engine>\n    IntType operator()(Engine& eng) const {\n        assert(!data.empty());\n        boost::variate_generator<Engine&, boost::uniform_01<WeightType> > real_gen(eng, boost::uniform_01<WeightType>());\n        WeightType test = real_gen() * data.size();\n        IntType result = static_cast<IntType>(test);\n        if(test - result < data[result].first) {\n            return result;\n        } else {\n            return(data[result].second);\n        }\n    }\n    \n    result_type min BOOST_PREVENT_MACRO_SUBSTITUTION () const { return 0; }\n    result_type max BOOST_PREVENT_MACRO_SUBSTITUTION () const { return static_cast<result_type>(weights.size() - 1); }\nprivate:\n    std::vector<WeightType> weights;\n    std::vector<std::pair<WeightType, IntType> > data;\n};\n\n}\n}\n\n#endif\n\n\n", "meta": {"hexsha": "b72e245dc6a21e02195de040d2455a614aada851", "size": 3340, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "random/boost/random/discrete_distribution_sw_2009.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": "random/boost/random/discrete_distribution_sw_2009.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": "random/boost/random/discrete_distribution_sw_2009.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.7373737374, "max_line_length": 121, "alphanum_fraction": 0.6200598802, "num_tokens": 790, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.4936656038168805}}
{"text": "#include \"common/common.hpp\"\n\n#include \"geodb/hilbert.hpp\"\n\n#include <boost/program_options.hpp>\n#include <fmt/format.h>\n#include <fmt/ostream.h>\n\n#include <iostream>\n\nnamespace po = boost::program_options;\n\nusing std::cout;\nusing std::cerr;\n\nvoid parse_options(int argc, char** argv);\n\ntemplate<u32 Dimension, u32 Precision>\njson curve_json();\n\nint main(int argc, char** argv) {\n    return tpie_main([&]{\n        parse_options(argc, argv);\n\n        json curves = json::array({\n            curve_json<2, 1>(),\n            curve_json<2, 2>(),\n            curve_json<2, 3>(),\n            curve_json<3, 1>(),\n            curve_json<3, 2>(),\n            curve_json<3, 3>(),\n        });\n\n        fmt::print(cout, \"{}\\n\", curves.dump(4));\n        return 0;\n    });\n}\n\nvoid parse_options(int argc, char** argv) {\n    po::options_description options(\"Options\");\n    options.add_options()\n            (\"help,h\", \"Show this message.\");\n\n    po::variables_map vm;\n    try {\n        po::command_line_parser p(argc, argv);\n        p.options(options);\n        po::store(p.run(), vm);\n\n        if (vm.count(\"help\")) {\n            fmt::print(cerr, \"Usage: {0}\\n\"\n                             \"\\n\"\n                             \"Outputs hilbert curve points for certain dimensions and precisions.\\n\"\n                             \"\\n\"\n                             \"{1}\",\n                       argv[0], options);\n            throw exit_main(0);\n        }\n\n        po::notify(vm);\n    } catch (const po::error& e) {\n        fmt::print(cerr, \"Failed to parse arguments: {}.\\n\", e.what());\n        throw exit_main(1);\n    }\n}\n\n/// Creates a vector of points that represents a walk over\n/// the hilbert curve with the given Dimension and Precision.\ntemplate<u32 Dimension, u32 Precision>\nauto curve_points()\n{\n    using curve_t = geodb::hilbert_curve<Dimension, Precision>;\n    using point_t = typename curve_t::point_t;\n    using index_t = typename curve_t::index_t;\n\n    const index_t count = curve_t::index_count;\n\n    std::vector<point_t> result(count);\n    for (index_t i = 0; i < count; ++i) {\n        result[i] = curve_t::hilbert_index_inverse(i);\n    }\n    return result;\n}\n\ntemplate<u32 Dimension, u32 Precision>\njson curve_json() {\n    const auto points = curve_points<Dimension, Precision>();\n\n    json json_data = json::object();\n    json_data[\"dimension\"] = Dimension;\n    json_data[\"precision\"] = Precision;\n\n    json& json_points = json_data[\"points\"] = json::array();\n    for (const auto& point : points) {\n        json jp = json::array();\n        for (const auto& coord : point) {\n            jp.push_back(coord.to_ullong());\n        }\n        json_points.push_back(jp);\n    }\n    return json_data;\n}\n\n", "meta": {"hexsha": "36f3a7b9ea874b93ee27889cbaca4771211be9ad", "size": 2696, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/cmd/hilbert_curve/main.cpp", "max_stars_repo_name": "mbeckem/msc", "max_stars_repo_head_hexsha": "93e71ba163a7ffef4eec3e83934fa793f3f50ff6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/cmd/hilbert_curve/main.cpp", "max_issues_repo_name": "mbeckem/msc", "max_issues_repo_head_hexsha": "93e71ba163a7ffef4eec3e83934fa793f3f50ff6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/cmd/hilbert_curve/main.cpp", "max_forks_repo_name": "mbeckem/msc", "max_forks_repo_head_hexsha": "93e71ba163a7ffef4eec3e83934fa793f3f50ff6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9230769231, "max_line_length": 100, "alphanum_fraction": 0.5708456973, "num_tokens": 647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6442250996557036, "lm_q1q2_score": 0.4936655985825846}}
{"text": "#include \"edlib/Solver/ArpackSolver.hpp\"\n\n#include <Eigen/Sparse>\n#include <Spectra/MatOp/SparseSymMatProd.h>\n#include <Spectra/SymEigsSolver.h>\n\n#include <catch2/catch.hpp>\n\n#include <iostream>\n#include <random>\n\nconstexpr uint32_t max_iter = 1000;\nconstexpr double tol = 1e-10;\nconstexpr uint32_t n_evals = 3;\n\ntemplate<typename MatProd>\nauto eigenvectorSpectra(MatProd& prod) -> std::pair<Eigen::VectorXd, Eigen::MatrixXd>\n{\n    using Spectra::SortRule;\n    Spectra::SymEigsSolver<MatProd> eigs(prod, n_evals, 2 * n_evals + 1);\n    eigs.init();\n    eigs.compute(SortRule::SmallestAlge, max_iter, tol, SortRule::SmallestAlge);\n    return std::pair{eigs.eigenvalues(), eigs.eigenvectors()};\n}\n\ntemplate<typename MatProd>\nauto eigenvectorArpack(MatProd& prod) -> std::pair<Eigen::VectorXd, Eigen::MatrixXd>\n{\n    using namespace edlib;\n    ArpackSolver solver(prod);\n    solver.solve(n_evals, max_iter, tol);\n    return std::pair{solver.eigenvalues(), solver.eigenvectors()};\n}\n\nTEST_CASE(\"Test arpack solver\", \"[arpack_solver]\")\n{\n    using Catch::Matchers::WithinAbs;\n    using std::abs;\n\n    constexpr uint32_t dim = 1024;\n    constexpr uint32_t n_elts = 128;\n\n    std::mt19937 re{1337};\n    std::uniform_int_distribution<uint32_t> index_dist(0, dim - 1);\n    std::normal_distribution<double> elt_dist;\n\n    Eigen::SparseMatrix<double> m(dim, dim);\n\n    for(size_t idx = 0; idx < n_elts; ++idx)\n    {\n        const auto row = index_dist(re);\n        const auto col = index_dist(re);\n        const auto val = elt_dist(re);\n        m.coeffRef(row, col) = val; // NOLINT(readability-suspicious-call-argument)\n        m.coeffRef(col, row) = val; // NOLINT(readability-suspicious-call-argument)\n    }\n    m.makeCompressed();\n\n    Spectra::SparseSymMatProd<double> prod(m);\n\n    const auto [evals_spectra, evecs_spectra] = eigenvectorSpectra(prod);\n    const auto [evals_arpack, evecs_arpack] = eigenvectorArpack(prod);\n\n    REQUIRE((evals_spectra - evals_arpack).lpNorm<1>() < 1e-8);\n\n    for(uint32_t i = 0; i < n_evals; i++)\n    {\n        double inner_prod = evecs_spectra.col(i).transpose() * evecs_arpack.col(i);\n        REQUIRE_THAT(abs(inner_prod), WithinAbs(1.0, 1e-8));\n    }\n}\n", "meta": {"hexsha": "6b7e5a893ffe4a7f31e9fcf5ef5d0ab05e5c62d9", "size": 2184, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_arpack_solver.cpp", "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": "tests/test_arpack_solver.cpp", "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": "tests/test_arpack_solver.cpp", "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": 30.3333333333, "max_line_length": 85, "alphanum_fraction": 0.6904761905, "num_tokens": 646, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115012, "lm_q2_score": 0.6442250996557036, "lm_q1q2_score": 0.49366559170583046}}
{"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) 2014 Erik Erlandson\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#include <sstream>\r\n\r\n#include <boost/units/quantity.hpp>\r\n#include <boost/units/conversion.hpp>\r\n#include <boost/units/io.hpp>\r\n\r\n#include <boost/units/systems/si/prefixes.hpp>\r\n#include <boost/units/systems/si/time.hpp>\r\n\r\n// All information systems definitions\r\n#include <boost/units/systems/information.hpp>\r\n\r\nusing std::cout;\r\nusing std::cerr;\r\nusing std::endl;\r\nusing std::stringstream;\r\n\r\nnamespace bu = boost::units;\r\nnamespace si = boost::units::si;\r\n\r\nusing bu::quantity;\r\n\r\nusing bu::information::bit_base_unit;\r\nusing bu::information::byte_base_unit;\r\nusing bu::information::nat_base_unit;\r\nusing bu::information::hartley_base_unit;\r\nusing bu::information::shannon_base_unit;\r\n\r\n\r\n#define BOOST_TEST_MAIN\r\n#include <boost/test/unit_test.hpp>\r\n\r\n\r\n#include <boost/multiprecision/cpp_int.hpp>\r\n\r\nconst double close_fraction = 0.0000001;\r\n\r\n// checks that cf(u2,u1) == expected\r\n// also checks invariant property that cf(u2,u1) * cf(u1,u2) == 1 \r\n#define CHECK_DIRECT_CF(u1, u2, expected) \\\r\n    BOOST_CHECK_CLOSE_FRACTION(bu::conversion_factor((u2), (u1)), (expected), close_fraction); \\\r\n    BOOST_CHECK_CLOSE_FRACTION(bu::conversion_factor((u2), (u1)) * bu::conversion_factor((u1), (u2)), 1.0, close_fraction);\r\n\r\n// check transitive conversion factors\r\n// invariant:  cf(u1,u3) = cf(u1,u2)*cf(u2,u3) \r\n#define CHECK_TRANSITIVE_CF(u1, u2, u3) { \\\r\n    double cf12 = bu::conversion_factor((u2), (u1)) ; \\\r\n    double cf23 = bu::conversion_factor((u3), (u2)) ; \\\r\n    double cf13 = bu::conversion_factor((u3), (u1)) ; \\\r\n    BOOST_CHECK_CLOSE_FRACTION(cf13, cf12*cf23, close_fraction); \\\r\n    double cf32 = bu::conversion_factor((u2), (u3)) ; \\\r\n    double cf21 = bu::conversion_factor((u1), (u2)) ; \\\r\n    double cf31 = bu::conversion_factor((u1), (u3)) ; \\\r\n    BOOST_CHECK_CLOSE_FRACTION(cf31, cf32*cf21, close_fraction); \\\r\n}\r\n\r\n\r\nBOOST_AUTO_TEST_CASE(test_cf_bit_byte) {\r\n    CHECK_DIRECT_CF(bit_base_unit::unit_type(), byte_base_unit::unit_type(), 8.0);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(test_cf_bit_nat) {\r\n    CHECK_DIRECT_CF(bit_base_unit::unit_type(), nat_base_unit::unit_type(), 1.442695040888964);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(test_cf_bit_hartley) {\r\n    CHECK_DIRECT_CF(bit_base_unit::unit_type(), hartley_base_unit::unit_type(), 3.321928094887363);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(test_cf_bit_shannon) {\r\n    CHECK_DIRECT_CF(bit_base_unit::unit_type(), shannon_base_unit::unit_type(), 1.0);\r\n}\r\n\r\n/////////////////////////////////////////////////////////////////////////////////////\r\n// spot-check that these are automatically transitive, thru central \"hub unit\" bit:\r\n// basic pattern is to test invariant property:  cf(c,a) = cf(c,b)*cf(b,a)\r\n\r\nBOOST_AUTO_TEST_CASE(test_transitive_byte_nat) {\r\n    CHECK_TRANSITIVE_CF(byte_base_unit::unit_type(), bit_base_unit::unit_type(), nat_base_unit::unit_type());\r\n}\r\nBOOST_AUTO_TEST_CASE(test_transitive_nat_hartley) {\r\n    CHECK_TRANSITIVE_CF(nat_base_unit::unit_type(), bit_base_unit::unit_type(), hartley_base_unit::unit_type());\r\n}\r\nBOOST_AUTO_TEST_CASE(test_transitive_hartley_shannon) {\r\n    CHECK_TRANSITIVE_CF(hartley_base_unit::unit_type(), bit_base_unit::unit_type(), shannon_base_unit::unit_type());\r\n}\r\nBOOST_AUTO_TEST_CASE(test_transitive_shannon_byte) {\r\n    CHECK_TRANSITIVE_CF(shannon_base_unit::unit_type(), bit_base_unit::unit_type(), byte_base_unit::unit_type());\r\n}\r\n\r\n// test transitive factors, none of which are bit, just for good measure\r\nBOOST_AUTO_TEST_CASE(test_transitive_byte_nat_hartley) {\r\n    CHECK_TRANSITIVE_CF(byte_base_unit::unit_type(), nat_base_unit::unit_type(), hartley_base_unit::unit_type());\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(test_byte_quantity_is_default) {\r\n    using namespace bu::information;\r\n    quantity<info, double> qd(2 * byte);\r\n    BOOST_CHECK_EQUAL(qd.value(), double(2));\r\n    quantity<info, long> ql(2 * byte);\r\n    BOOST_CHECK_EQUAL(ql.value(), long(2));\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(test_byte_quantity_explicit) {\r\n    using namespace bu::information;\r\n    quantity<hu::byte::info, double> qd(2 * byte);\r\n    BOOST_CHECK_EQUAL(qd.value(), double(2));\r\n    quantity<hu::byte::info, long> ql(2 * byte);\r\n    BOOST_CHECK_EQUAL(ql.value(), long(2));\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(test_bit_quantity) {\r\n    using namespace bu::information;\r\n    quantity<hu::bit::info, double> qd(2 * bit);\r\n    BOOST_CHECK_EQUAL(qd.value(), double(2));\r\n    quantity<hu::bit::info, long> ql(2 * bit);\r\n    BOOST_CHECK_EQUAL(ql.value(), long(2));\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(test_nat_quantity) {\r\n    using namespace bu::information;\r\n    quantity<hu::nat::info, double> qd(2 * nat);\r\n    BOOST_CHECK_EQUAL(qd.value(), double(2));\r\n    quantity<hu::nat::info, long> ql(2 * nat);\r\n    BOOST_CHECK_EQUAL(ql.value(), long(2));\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(test_hartley_quantity) {\r\n    using namespace bu::information;\r\n    quantity<hu::hartley::info, double> qd(2 * hartley);\r\n    BOOST_CHECK_EQUAL(qd.value(), double(2));\r\n    quantity<hu::hartley::info, long> ql(2 * hartley);\r\n    BOOST_CHECK_EQUAL(ql.value(), long(2));\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(test_shannon_quantity) {\r\n    using namespace bu::information;\r\n    quantity<hu::shannon::info, double> qd(2 * shannon);\r\n    BOOST_CHECK_EQUAL(qd.value(), double(2));\r\n    quantity<hu::shannon::info, long> ql(2 * shannon);\r\n    BOOST_CHECK_EQUAL(ql.value(), long(2));\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(test_mixed_hu) {\r\n    using namespace bu::information;\r\n    const double cf = 0.001;\r\n    BOOST_CHECK_CLOSE_FRACTION((quantity<hu::bit::info>(1.0 * bits)).value(), 1.0, cf);\r\n    BOOST_CHECK_CLOSE_FRACTION((quantity<hu::byte::info>(1.0 * bits)).value(), 1.0/8.0, cf);\r\n    BOOST_CHECK_CLOSE_FRACTION((quantity<hu::nat::info>(1.0 * bits)).value(), 0.69315, cf);\r\n    BOOST_CHECK_CLOSE_FRACTION((quantity<hu::hartley::info>(1.0 * bits)).value(), 0.30102, cf);\r\n    BOOST_CHECK_CLOSE_FRACTION((quantity<hu::shannon::info>(1.0 * bits)).value(), 1.0, cf);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(test_info_prefixes) {\r\n    using namespace bu::information;\r\n    quantity<info, long long> q10(1LL * kibi * byte);\r\n    BOOST_CHECK_EQUAL(q10.value(), 1024LL);\r\n\r\n    quantity<info, long long> q20(1LL * mebi * byte);\r\n    BOOST_CHECK_EQUAL(q20.value(), 1048576LL);\r\n\r\n    quantity<info, long long> q30(1LL * gibi * byte);\r\n    BOOST_CHECK_EQUAL(q30.value(), 1073741824LL);\r\n\r\n    quantity<info, long long> q40(1LL * tebi * byte);\r\n    BOOST_CHECK_EQUAL(q40.value(), 1099511627776LL);\r\n\r\n    quantity<info, long long> q50(1LL * pebi * byte);\r\n    BOOST_CHECK_EQUAL(q50.value(), 1125899906842624LL);\r\n\r\n    quantity<info, long long> q60(1LL * exbi * byte);\r\n    BOOST_CHECK_EQUAL(q60.value(), 1152921504606846976LL);\r\n\r\n    using boost::multiprecision::int128_t;\r\n\r\n    quantity<info, int128_t> q70(1LL * zebi * byte);\r\n    BOOST_CHECK_EQUAL(q70.value(), int128_t(\"1180591620717411303424\"));\r\n\r\n    quantity<info, int128_t> q80(1LL * yobi * byte);\r\n    BOOST_CHECK_EQUAL(q80.value(), int128_t(\"1208925819614629174706176\"));\r\n\r\n    // sanity check: si prefixes should also operate\r\n    quantity<info, long long> q1e3(1LL * si::kilo * byte);\r\n    BOOST_CHECK_EQUAL(q1e3.value(), 1000LL);\r\n\r\n    quantity<info, long long> q1e6(1LL * si::mega * byte);\r\n    BOOST_CHECK_EQUAL(q1e6.value(), 1000000LL);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(test_unit_constant_io) {\r\n    using namespace bu::information;\r\n\r\n    std::stringstream ss;\r\n    ss << bu::symbol_format << bytes;\r\n    BOOST_CHECK_EQUAL(ss.str(), \"B\");\r\n\r\n    ss.str(\"\");\r\n    ss << bu::name_format << bytes;\r\n    BOOST_CHECK_EQUAL(ss.str(), \"byte\");\r\n\r\n    ss.str(\"\");\r\n    ss << bu::symbol_format << bits;\r\n    BOOST_CHECK_EQUAL(ss.str(), \"b\");\r\n\r\n    ss.str(\"\");\r\n    ss << bu::name_format << bits;\r\n    BOOST_CHECK_EQUAL(ss.str(), \"bit\");\r\n\r\n    ss.str(\"\");\r\n    ss << bu::symbol_format << nats;\r\n    BOOST_CHECK_EQUAL(ss.str(), \"nat\");\r\n\r\n    ss.str(\"\");\r\n    ss << bu::name_format << nats;\r\n    BOOST_CHECK_EQUAL(ss.str(), \"nat\");\r\n\r\n    ss.str(\"\");\r\n    ss << bu::symbol_format << hartleys;\r\n    BOOST_CHECK_EQUAL(ss.str(), \"Hart\");\r\n\r\n    ss.str(\"\");\r\n    ss << bu::name_format << hartleys;\r\n    BOOST_CHECK_EQUAL(ss.str(), \"hartley\");\r\n\r\n    ss.str(\"\");\r\n    ss << bu::symbol_format << shannons;\r\n    BOOST_CHECK_EQUAL(ss.str(), \"Sh\");\r\n\r\n    ss.str(\"\");\r\n    ss << bu::name_format << shannons;\r\n    BOOST_CHECK_EQUAL(ss.str(), \"shannon\");\r\n}\r\n", "meta": {"hexsha": "33b7ba38b290a1cfa4a8de826ef478b4e464713f", "size": 8643, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/units/test/test_information_units.cpp", "max_stars_repo_name": "lijgame/boost", "max_stars_repo_head_hexsha": "ec2214a19cdddd1048058321a8105dd0231dac47", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 85.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T20:36:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T20:38:31.000Z", "max_issues_repo_path": "libs/boost/libs/units/test/test_information_units.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/test/test_information_units.cpp", "max_forks_repo_name": "flingone/frameworks_base_cmds_remoted", "max_forks_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2015-01-28T16:33:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-12T05:04:39.000Z", "avg_line_length": 35.5679012346, "max_line_length": 124, "alphanum_fraction": 0.6762698137, "num_tokens": 2349, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145998, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.49359306752937965}}
{"text": "#ifndef VECTORANDCIRCULARMATH_HPP_\n#define VECTORANDCIRCULARMATH_HPP_\n\n\n#include <boost/version.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/algorithm/string.hpp>\n#include <opencv2/opencv.hpp>\n#include <utility>\n#include <vector>\n#include <array>\n#include <cmath>\n#include <cassert>\n\n\ninline bool operator==(const cv::Vec4i& lhs, const cv::Vec4i& rhs) {\n  return ((lhs[0] == rhs[0]) &&\n          (lhs[1] == rhs[1]) &&\n          (lhs[2] == rhs[2]) &&\n          (lhs[3] == rhs[3]));\n};\n\n\ninline bool operator<(const cv::Vec4i& lhs, const cv::Vec4i& rhs) {\n  if (lhs[0] < rhs[0]) return true;\n  else if (lhs[0] > rhs[0]) return false;\n  if (lhs[1] < rhs[1]) return true;\n  else if (lhs[1] > rhs[1]) return false;\n  if (lhs[2] < rhs[2]) return true;\n  else if (lhs[2] > rhs[2]) return false;\n  if (lhs[3] < rhs[3]) return true;\n  return false;\n};\ninline bool lessThanVec4i(const cv::Vec4i& lhs, const cv::Vec4i& rhs) {\n  return (lhs < rhs);\n};\ninline bool lessThanArray5i(const std::array<int, 5>& lhs, const std::array<int, 5>& rhs) {\n  return (lhs < rhs);\n};\n\n\nnamespace vc_math {\n\n\n#if BOOST_VERSION/100 < 1050\nconstexpr double pi = 3.1415926535897932384626433832795;\nconstexpr double two_pi = pi*2;\nconstexpr double inv_sqrt_2pi = 0.3989422804014327;\nconstexpr double degree = pi/180.0;\nconstexpr double radian = 180.0/pi;\nconstexpr double half_pi = pi/2.0;\n#else\nconstexpr double pi = boost::math::constants::pi<double>();\nconstexpr double two_pi = boost::math::constants::two_pi<double>();\nconstexpr double inv_sqrt_2pi = 1.0/boost::math::constants::root_two_pi<double>();\nconstexpr double degree = boost::math::constants::degree<double>();\nconstexpr double radian = boost::math::constants::radian<double>();\nconstexpr double half_pi = boost::math::constants::half_pi<double>();\n#endif\n\nconstexpr double INVALID_ANGLE = 361.0;\n\n\ninline double normal_pdf(double x, double m, double s) {\n  double a = (x - m) / s;\n  return (inv_sqrt_2pi / s) * exp(-0.5 * a * a);\n};\n\n\ninline double log_normal_pdf(double x, double m, double s) {\n  double a = (x - m) / s;\n  return log(inv_sqrt_2pi) - log(s) -0.5 * a * a;\n};\n\n\n/**\n * Generates a pair of random samples from the unit Normal distribution,\n * using the Box-Mueller method.\n */\ninline std::pair<double, double> randn() {\n  double U = double(rand())/RAND_MAX;\n  double V = double(rand())/RAND_MAX;\n  double sqrtMinusTwolnU = sqrt(-2*log(U));\n  double TwoPiV = two_pi * V;\n  return std::pair<double, double>(sqrtMinusTwolnU * cos(TwoPiV), sqrtMinusTwolnU * sin(TwoPiV));\n};\n\n/**\n * Computes angular (and general modulo-'range') magnitude, signed\n */\ninline double angularMag(\n    double a,\n    double b,\n    double range = 360.0) {\n  double d = b - a + range/2;\n  d = (d > 0) ? d - floor(d/range)*range - range/2 : d - (floor(d/range) + 1)*range + range/2;\n  return d;\n};\n\n/**\n * Computes angular (and general modulo-'range') distance\n */\ninline double angularDist(double a, double b, double range = 360.0) { return fabs(angularMag(a, b, range)); };\n\n/**\n * Computes Eulidean distance between 2 2-D points\n */\ninline double dist(double x1, double y1, double x2, double y2) {\n  return sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));\n};\ninline double dist(const cv::Point2d& xy1, const cv::Point2d& xy2) {\n  return sqrt((xy1.x-xy2.x)*(xy1.x-xy2.x)+(xy1.y-xy2.y)*(xy1.y-xy2.y));\n};\ninline double dist(const cv::Point2f& xy1, const cv::Point2f& xy2) {\n  return sqrt((xy1.x-xy2.x)*(xy1.x-xy2.x)+(xy1.y-xy2.y)*(xy1.y-xy2.y));\n};\ninline double dist(const cv::Point2i& xy1, const cv::Point2i& xy2) {\n  return sqrt((xy1.x-xy2.x)*(xy1.x-xy2.x)+(xy1.y-xy2.y)*(xy1.y-xy2.y));\n};\ninline double dist(const cv::Vec4i& xy12) {\n  return sqrt((xy12[0]-xy12[2])*(xy12[0]-xy12[2])+(xy12[1]-xy12[3])*(xy12[1]-xy12[3]));\n};\ninline double distSqrd(double x1, double y1, double x2, double y2) {\n  return (x1-x2)*(x1-x2)+(y1-y2)*(y1-y2);\n};\ninline double distSqrd(const cv::Point2d& xy1, const cv::Point2d& xy2) {\n  return (xy1.x-xy2.x)*(xy1.x-xy2.x)+(xy1.y-xy2.y)*(xy1.y-xy2.y);\n};\ninline double distSqrd(const cv::Point2f& xy1, const cv::Point2f& xy2) {\n  return (xy1.x-xy2.x)*(xy1.x-xy2.x)+(xy1.y-xy2.y)*(xy1.y-xy2.y);\n};\ninline double distSqrd(const cv::Point2i& xy1, const cv::Point2i& xy2) {\n  return (xy1.x-xy2.x)*(xy1.x-xy2.x)+(xy1.y-xy2.y)*(xy1.y-xy2.y);\n};\ninline double distSqrd(const cv::Vec4i& xy12) {\n  return (xy12[0]-xy12[2])*(xy12[0]-xy12[2])+(xy12[1]-xy12[3])*(xy12[1]-xy12[3]);\n};\n\n/**\n * Wraps angle in degrees to [0, maxAngle) range\n */\ninline constexpr double wrapAngle(double angleDeg, double maxAngle = 360.0) {\n  return (angleDeg - floor(angleDeg/maxAngle)*maxAngle);\n};\n\n/**\n * Count number of entries in matrix that are not equal\n *\n * NOTE: if Mat represents a colored image, then it will count different\n * color channels separately.\n */\ninline unsigned long long countNotEqual(const cv::Mat& a, const cv::Mat& b) {\n  if (a.size != b.size || a.channels() != b.channels()) {\n    return std::max(a.rows * a.cols * a.channels(), b.rows * b.cols * b.channels());\n  }\n\n  cv::Mat not_equal;\n  cv::compare(a, b, not_equal, cv::CMP_NE);\n  cv::Scalar sum_not_equal = sum(sum(not_equal) / 255);\n  return sum_not_equal[0] + sum_not_equal[1] + sum_not_equal[2] + sum_not_equal[3];\n};\n\ninline unsigned long long countNotEqual(const std::vector<cv::Point>& a,\n    const std::vector<cv::Point>& b) {\n  unsigned long long count = abs(a.size() - b.size());\n  size_t minSize = std::min(a.size(), b.size());\n  std::vector<cv::Point>::const_iterator itA = a.begin();\n  std::vector<cv::Point>::const_iterator itB = b.begin();\n  for (unsigned int i = 0; i < minSize; i++, itA++, itB++) {\n    if (*itA != *itB) {\n      count += 1;\n    }\n  }\n  return count;\n};\n\n/**\n * Computes the Euclidean distance between a 2-D point and a 2-D line\n */\ninline double distPointLine(\n    const cv::Point& point,\n    const cv::Vec4f& currFit) {\n  // http://local.wasp.uwa.edu.au/~pbourke/geometry/pointline/\n  double vx = currFit[0], vy = currFit[1], x1 = currFit[2], y1 = currFit[3];\n  if (vx == 0 && vy == 0) {\n    return 0; // P1 = P2!\n  }\n  double x3 = point.x, y3 = point.y;\n  double u = ((x3-x1)*vx + (y3-y1)*vy)/(vx*vx+vy*vy);\n  double dx = x1 + u*vx - x3, dy = y1 + u*vy - y3;\n  return sqrt(dx*dx + dy*dy);\n};\n\n/**\n * Finds closest point to given line in given set of points.\n */\ninline cv::Point findClosestPointToLine(\n    const std::vector<cv::Point>& points,\n    const cv::Vec4f& line) {\n  // Identify the 8-connected set of edgels closest to the previous line fit\n  std::vector<cv::Point>::const_iterator itPoints = points.begin();\n  std::vector<cv::Point>::const_iterator itPointsEnd = points.end();\n  double closestDist = distPointLine(*itPoints, line);\n  cv::Point closestPoint = *itPoints;\n  double currDist;\n  for (itPoints++; itPoints != itPointsEnd; itPoints++) {\n    currDist = distPointLine(*itPoints, line);\n    if (currDist < closestDist) {\n      closestDist = currDist;\n      closestPoint = *itPoints;\n    }\n  }\n  return closestPoint;\n};\n\n /**\n  * Computes 3D point on plane closest to specified 3D point\n  *\n  * Justification:\n  * The equation of a plane is: n * v = d, where n is the normal vector,\n  * v is an arbitrary 3D point, and d is a constant offset.\n  *\n  * Given query point v', then the closest point on the above plane is:\n  * v* = v' + a * n, for some unknown factor a\n  *\n  * Also, we know that n * v* = d, by definition of the plane.\n  *\n  * Thus, n * (v' + a * n) = d,\n  * i.e. a = ( d - n * v' ) / ( n * n ),\n  * which allows us to then solve for v* by substituting in a\n  *\n  * (side-note: n * n is guaranteed to be always non-zero for plane to exist)\n  */\ninline cv::Vec3d findClosestPointOnPlane(const cv::Vec3d& vp,\n    const cv::Vec3d& n, double d) {\n   double a = (d - n.dot(vp)) / n.dot(n);\n   cv::Vec3d vs = vp + a*n;\n   return vs;\n};\n\n\n/**\n * Computes 2D point on line closest to specified 2D point\n *\n * Justification:\n * The equation of a line is: vla + a * vd,\n * where vd = vlb - vla, for some constant a\n *\n * Let vdd be orthogonal to vd. The resulting point vr satisfied both:\n * vr = vla + a * vd, for some constant a\n * vr = vp - d * vdd, for some constant d\n *\n * Hence, vd * a + vdd * b = vp - vla. We can now solve a and d using the normal equation.\n */\ninline cv::Vec2d findClosestPointOnLine2(const cv::Vec2d& vp,\n    const cv::Vec2d& vla, const cv::Vec2d& vlb) {\n  if (vla == vlb) { return vp; }\n  cv::Vec2d vd = vlb - vla;\n\n  double det = vd[0]*vd[0] + vd[1]*vd[1];\n  double a = (vd[0] * (vp[0] - vla[0]) + vd[1] * (vp[1] - vla[1])) / det;\n  //double d = (vd[1] * (vp[0] - vla[0]) - vd[0] * (vp[1] - vla[1])) / det;\n  cv::Vec2d result = vla + a * vd;\n\n  return result;\n};\n/**\n * same as above, but takes in normal form of line: (n1, n2) * (x, y) = nd\n */\ninline cv::Vec2d findClosestPointOnLine2(const cv::Vec2d& vp,\n    double n1, double n2, double nd) {\n  // Make sure normal vector of line has non-zero norm\n  double det = n1*n1 + n2*n2;\n  if (det == 0) { return vp; }\n\n  // Compute point on line\n  double vlx = 0, vly = 0;\n  if (n1 == 0) { vly = nd/n2; }\n  else { vlx = nd/n1; }\n\n  // Compute vr = vl + a * vd, where vd is orthogonal to n\n  double a = (n2 * (vp[0] - vlx) - n1 * (vp[1] - vly)) / det;\n\n  return cv::Vec2d(vlx + a*n2, vly - a*n1);\n};\n\n\n/**\n * Computes 3D point on line closest to specified 3D point\n *\n * Justification:\n * The equation of a line is: vla + a * vld,\n * where vld = vlb - vla, for some constant a\n *\n * Denote the resulting point on the line as vr, then the vector vn = (vr->vp) is\n * orthogonal to vld, as well as to a 3rd orthogonal vector vo.\n * vo can be computed as vld x vnp, where vnp = (vl->vp) for any point vl on the line.\n *\n * Then, we can link the 2 points vla and vp together, as:\n * vnp = vp - vla = a * vld + d * vn\n *\n * There are 2 unknowns and 3 equations here, so we can solve this using the\n * normal equation.\n */\ninline cv::Vec3d findClosestPointOnLine3(const cv::Vec3d& vp,\n    const cv::Vec3d& vla, const cv::Vec3d& vlb) {\n  cv::Vec3d result;\n  if (vla == vlb) { return vp; }\n  cv::Vec3d vld = vlb - vla;\n  cv::Vec3d vnp = vp - vla;\n  if (vp == vla) { vnp = vp - vlb; }\n  cv::Vec3d vo = vld.cross(vnp);\n  cv::Vec3d vn = vld.cross(vo);\n\n  cv::Mat A(3, 2, CV_64FC1);\n  cv::Mat b(3, 1, CV_64FC1);\n  for (unsigned int i = 0; i < 3; i++) {\n    A.at<double>(i, 0) = vld[i];\n    A.at<double>(i, 1) = vn[i];\n    b.at<double>(i, 0) = vnp[i];\n  }\n  cv::Mat sln = (A.t()*A).inv()*(A.t()*b);\n  //double a = sln.at<double>(0, 0);\n  double d = sln.at<double>(1, 0);\n  result = vp - d*vn;\n\n  return result;\n};\n\n\n/**\n * Find the closest point to a number of planes, where each plane is represented\n * by their normal vector n, and constant offset d, which are stored into\n * matrices A = [n1; n2; ...], and b = [d1; d2; ...].\n *\n * The query point vp is only used in degenerate cases; see below.\n *\n * For 1 single plane, this function returns the closest point on plane to\n * the query point vp.\n *\n * Otherwise, we check if (A'*A) is invertible, and if it is, then we can use\n * the normal equation to solve for the closest point.\n *\n * If (A'*A) is not invertible, then we choose the first 2 planes that have\n * different normals, and find their intersecting line. We then compute\n * the closest point on line to the query point.\n */\ncv::Vec3d findClosestPointToPlanes3(const cv::Vec3d& vp,\n    const cv::Mat& A, const cv::Mat& b);\n\n\n/**\n * Find the closest point to a number of lines, where each line is represented\n * by their normal vector n, and constant offset d, which are stored into\n * matrices A = [n1; n2; ...], and b = [d1; d2; ...].\n *\n * The query point vp is only used in degenerate cases; see below.\n *\n * For 1 single line, this function returns the closest point on line to\n * the query point vp.\n *\n * Otherwise, we check if the lines are parallel via det(A) != 0. If they\n * intersect, then we can use the normal equation to solve for the closest point.\n *\n * If all lines are parallel, then we average over the offsets b, to get an\n * average line. We then return the closest point on this average line to the\n * query point.\n */\ncv::Vec2d findClosestPointToLines2(const cv::Vec2d& vp,\n    const cv::Mat& A, const cv::Mat& b);\n\n\n/**\n * Check if the line segments (a<->b) and (c<->d) intersect with each other\n *\n * From: http://gamedev.stackexchange.com/questions/26004/how-to-detect-2d-line-on-line-collision\n *\n * WARNING: algorithm returns true for special case where the line segments\n *          are co-linear and do not overlap\n */\ninline bool isIntersecting(const cv::Point2f& a, const cv::Point2f& b,\n    const cv::Point2f& c, const cv::Point2f& d) {\n  float denominator = ((b.x - a.x) * (d.y - c.y)) - ((b.y - a.y) * (d.x - c.x));\n  float numerator1 = ((a.y - c.y) * (d.x - c.x)) - ((a.x - c.x) * (d.y - c.y));\n  float numerator2 = ((a.y - c.y) * (b.x - a.x)) - ((a.x - c.x) * (b.y - a.y));\n\n  if (denominator == 0) return numerator1 == 0 && numerator2 == 0;\n\n  float r = numerator1 / denominator;\n  float s = numerator2 / denominator;\n\n  return (r >= 0 && r <= 1) && (s >= 0 && s <= 1);\n};\n\n\n/**\n * Computes x intercept (in pixels, intersection with bottom of image) and\n * slope (in degrees, 0' = top of image) given line in image\n *\n * \\param line: straight line; format: [dx, dy, x0, y0]\n * \\param imWidth: image width, in pixels\n * \\param imHeight: image height, in pixels\n */\nstd::pair<double, double> computeXInterceptAndSlopeFromLine(\n    cv::Vec4f line,\n    unsigned int imWidth,\n    unsigned int imHeight);\n\n\n/**\n * Computes heading angle (in degrees) given line in overhead image, and\n * given preferred heading directionality.\n *\n * \\param line: straight line; format: [dx, dy, x0, y0]\n * \\param imWidth: image width, in pixels\n * \\param imHeight: image height, in pixels\n * \\param preferredDirDeg: preferred direction of heading, in degrees (0 = top of image, 90 = right of image)\n */\ndouble computeHeadingFromOverheadLine(\n    cv::Vec4f line,\n    unsigned int imWidth,\n    unsigned int imHeight,\n    double preferredDirDeg);\n\n/**\n * Computes point closest to border in the direction of heading,\n * centered at image's center.\n *\n * \\param heading: desired heading, in degrees; 0 = North/top of image; 90 = East/right of image\n * \\param imWidth: image width\n * \\param imHeight: image height\n * \\param marginWidth: width of margin around image borders to avoid when computing intersection\n */\ncv::Point computeHeadingBorderIntersection(\n    double heading,\n    unsigned int imWidth,\n    unsigned int imHeight,\n    unsigned int marginWidth);\n\n/**\n * Computes and returns closest point within set of points\n */\ninline cv::Point findClosestPoint(\n    const std::vector<cv::Point>& points,\n    const cv::Point targetPoint) {\n  std::vector<cv::Point>::const_iterator itPoints = points.begin();\n  std::vector<cv::Point>::const_iterator itPointsEnd = points.end();\n  cv::Point result = *itPoints;\n  double bestDistSqrd =\n      (itPoints->x - targetPoint.x)*(itPoints->x - targetPoint.x) +\n      (itPoints->y - targetPoint.y)*(itPoints->y - targetPoint.y);\n  double currDistSqrd;\n  for (itPoints++; itPoints != itPointsEnd; itPoints++) {\n    currDistSqrd =\n        (itPoints->x - targetPoint.x)*(itPoints->x - targetPoint.x) +\n        (itPoints->y - targetPoint.y)*(itPoints->y - targetPoint.y);\n    if (currDistSqrd < bestDistSqrd) {\n      result = *itPoints;\n      bestDistSqrd = currDistSqrd;\n    }\n  }\n\n  return result;\n};\n\n/**\n * Computes (minimum) scale factor between 2 sizes (i.e. prefer letterbox over\n * cropping)\n */\ninline double computeScaleFactor(const cv::Size& from, const cv::Size& to) {\n  if (from == cv::Size() || to == cv::Size()) {\n    return 1.0;\n  } else {\n    return std::min(double(to.width) / double(from.width),\n        double(to.height) / double(from.height));\n  }\n};\n\n/**\n * Computes orientation of line segment (of the form [x1, y1, x2, y2]), in\n * radians.\n */\ninline double orientation(const cv::Vec4i& seg) {\n  return std::atan2(seg[3] - seg[1], seg[2] - seg[0]);\n};\ninline double orientation(const cv::Point2i& ptA, const cv::Point2i& ptB) {\n  return std::atan2(ptB.y - ptA.y, ptB.x - ptA.x);\n};\ninline double orientation(const cv::Point2d& ptA, const cv::Point2d& ptB) {\n  return std::atan2(ptB.y - ptA.y, ptB.x - ptA.x);\n};\n\n/**\n * Sort values in increasing order\n * NOTE: faster than recursive implementations and specifically\n *       cv::sort(vec4iA, vec4iB, CV_SORT_EVERY_COLUMN | CV_SORT_ASCENDING)\n */\ninline cv::Vec4i sort(cv::Vec4i v) {\n  cv::Vec4i s(v);\n  if (v[0] > v[1]) {\n    s[0] = v[1]; s[1] = v[0];\n  }\n  if (v[2] > v[3]) {\n    s[2] = v[3]; s[3] = v[2];\n  }\n\n  if (s[0] > s[2]) {\n    v[0] = s[2];\n    if (s[3] > s[1]) {\n      v[1] = s[0]; v[2] = s[1]; v[3] = s[3];\n    } else if (s[3] > s[0]) {\n      v[1] = s[0]; v[2] = s[3]; v[3] = s[1];\n    } else {\n      v[1] = s[3]; v[2] = s[0]; v[3] = s[1];\n    }\n  } else {\n    v[0] = s[0];\n    if (s[1] > s[3]) {\n      v[1] = s[2]; v[2] = s[3]; v[3] = s[1];\n    } else if (s[1] > s[2]) {\n      v[1] = s[2]; v[2] = s[1]; v[3] = s[3];\n    } else {\n      v[1] = s[1]; v[2] = s[2]; v[3] = s[3];\n    }\n  }\n  return v;\n};\n\n/**\n * Cycles vector such that smallest value is listed first, but the (cyclic)\n * ordering of values are preserved\n */\ninline cv::Vec4i minCyclicOrder(cv::Vec4i v) {\n  if ((v[0] <= v[1]) && (v[0] <= v[2]) && (v[0] <= v[3])) {\n    return v;\n  } else if ((v[1] <= v[0]) && (v[1] <= v[2]) && (v[1] <= v[3])) {\n      return cv::Vec4i(v[1], v[2], v[3], v[0]);\n  } else if ((v[2] <= v[0]) && (v[2] <= v[1]) && (v[2] <= v[3])) {\n    return cv::Vec4i(v[2], v[3], v[0], v[1]);\n  } else { // if ((v[3] <= v[0]) && (v[3] <= v[1]) && (v[3] <= v[2])) {\n    return cv::Vec4i(v[3], v[0], v[1], v[2]);\n  }\n};\n\n/**\n * Sorts and removes duplicate entries in-place\n */\ninline void unique(std::vector<cv::Vec4i>& v) {\n  std::sort(v.begin(), v.end(), lessThanVec4i);\n\n  std::vector<cv::Vec4i> u;\n  for (const cv::Vec4i& d: v) {\n    if (u.empty()) { u.push_back(d); }\n    else if (u.back() < d) { u.push_back(d); }\n  }\n  v.swap(u);\n};\ninline void unique(std::vector< std::array<int, 5> >& v) {\n  std::sort(v.begin(), v.end(), lessThanArray5i);\n\n  std::vector< std::array<int, 5> > u;\n  for (const std::array<int, 5>& d: v) {\n    if (u.empty()) { u.push_back(d); }\n    else if (u.back() < d) { u.push_back(d); }\n  }\n  v.swap(u);\n};\n\n/**\n * Returns dot product of 2 line segments (of the form [x1, y1, x2, y2])\n */\ninline double dot(const cv::Vec4i& A, const cv::Vec4i& B) {\n  return (A[2]-A[0])*(B[2]-B[0]) + (A[3]-A[1])*(B[3]-B[1]);\n};\n\n/**\n * Returns dot product of 2 line segments\n */\ninline double dot(const cv::Point2f& endA1, const cv::Point2f& endA2,\n    const cv::Point2f& endB1, const cv::Point2f& endB2) {\n  return (endA2.x-endA1.x)*(endB2.x-endB1.x) + (endA2.y-endA1.y)*(endB2.y-endB1.y);\n};\n\n/**\n * Converts a rotation matrix into a quaternion\n *\n * From: http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/\n */\ninline void rotMat2quat(const cv::Mat rotMat,\n    double& w, double& x, double& y, double& z) {\n  assert(rotMat.rows == 3 && rotMat.cols == 3 && rotMat.isContinuous() &&\n      rotMat.elemSize() == sizeof(double));\n\n  double tr = rotMat.at<double>(0, 0) + rotMat.at<double>(1, 1) + rotMat.at<double>(2, 2);\n  double s;\n\n  if (tr > 0) {\n    s = 0.5/sqrt(tr + 1.0);\n    w = 0.25/s;\n    x = (rotMat.at<double>(2, 1) - rotMat.at<double>(1, 2))*s;\n    y = (rotMat.at<double>(0, 2) - rotMat.at<double>(2, 0))*s;\n    z = (rotMat.at<double>(1, 0) - rotMat.at<double>(0, 1))*s;\n  } else if (rotMat.at<double>(0, 0) > rotMat.at<double>(1, 1) &&\n      rotMat.at<double>(0, 0) > rotMat.at<double>(2, 2)) {\n    s = 2.0*sqrt(1.0 + 2*rotMat.at<double>(0, 0) - tr);\n    w = (rotMat.at<double>(2, 1) - rotMat.at<double>(1, 2))/s;\n    x = 0.25*s;\n    y = (rotMat.at<double>(0, 1) + rotMat.at<double>(1, 0))/s;\n    z = (rotMat.at<double>(0, 2) + rotMat.at<double>(2, 0))/s;\n  } else if (rotMat.at<double>(1, 1) > rotMat.at<double>(2, 2)) {\n    s = 2.0*sqrt(1.0 + 2*rotMat.at<double>(1, 1) - tr);\n    w = (rotMat.at<double>(0, 2) - rotMat.at<double>(2, 0))/s;\n    x = (rotMat.at<double>(0, 1) + rotMat.at<double>(1, 0))/s;\n    y = 0.25*s;\n    z = (rotMat.at<double>(1, 2) + rotMat.at<double>(2, 1))/s;\n  } else {\n    s = 2.0*sqrt(1.0 + 2*rotMat.at<double>(2, 2) - tr);\n    w = (rotMat.at<double>(1, 0) - rotMat.at<double>(0, 1))/s;\n    x = (rotMat.at<double>(0, 2) + rotMat.at<double>(2, 0))/s;\n    y = (rotMat.at<double>(1, 2) + rotMat.at<double>(2, 1))/s;\n    z = 0.25*s;\n  }\n};\n\n\ninline cv::Mat quat2RotMat(double w, double x, double y, double z) {\n  double distSqrd = x*x+y*y+z*z+w*w;\n  if (distSqrd < 1e-15) { return cv::Mat::zeros(3, 3, CV_64FC1); }\n  double s = 2.0/distSqrd;\n  double xs = x * s,   ys = y * s,   zs = z * s;\n  double wx = w * xs,  wy = w * ys,  wz = w * zs;\n  double xx = x * xs,  xy = x * ys,  xz = x * zs;\n  double yy = y * ys,  yz = y * zs,  zz = z * zs;\n  cv::Mat result(3, 3, CV_64FC1);\n  double* data = (double*) result.data;\n  *data = 1.0 - (yy + zz); data++;\n  *data = xy - wz; data++;\n  *data = xz + wy; data++;\n  *data = xy + wz; data++;\n  *data = 1.0 - (xx + zz); data++;\n  *data = yz - wx; data++;\n  *data = xz - wy; data++;\n  *data = yz + wx; data++;\n  *data = 1.0 - (xx + yy);\n  return result;\n};\n\n\n/**\n * Converts a quaternion to Euler angles\n * Assume right-hand coordinate frame, and static-x-y-z (sxyz) rotation ordering\n */\ninline std::array<double, 3> quat2euler(double w, double x, double y, double z) {\n  double distSqrd = x*x+y*y+z*z+w*w;\n  if (distSqrd < 1e-15) { std::array<double, 3>{ {0, 0, 0} }; }\n  w /= distSqrd;\n  x /= distSqrd;\n  y /= distSqrd;\n  z /= distSqrd;\n\n  return std::array<double, 3>{ {\n    atan2(2*(x*w + z*y), (w*w - x*x - y*y + z*z)),\n    asin(2*(y*w - x*z)),\n    atan2(2*(x*y + z*w), (w*w + x*x - y*y - z*z))} };\n};\ninline std::array<double, 3> quat2euler(std::array<double, 4> wxyz) {\n  return quat2euler(wxyz[0], wxyz[1], wxyz[2], wxyz[3]);\n};\n\n\n/**\n * Computes (normalized) inverse of a given quaternion\n */\ninline std::array<double, 4> quatInv(double w, double x, double y, double z) {\n  double distSqrd = x*x+y*y+z*z+w*w;\n  if (distSqrd < 1e-15) { std::array<double, 4>{ {0, 0, 0, 0} }; }\n  return std::array<double, 4>{ {w/distSqrd,\n    -x/distSqrd, -y/distSqrd, -z/distSqrd} };\n};\n\n\ninline cv::Mat str2mat(const std::string& s, int rows,\n    int type = CV_64F, int channels = 1) {\n  std::string input = s;\n  auto it = std::remove_if(std::begin(input), std::end(input),\n      [](char c) { return (c == ',' || c == ';' || c == ':'); });\n  input.erase(it, std::end(input));\n\n  cv::Mat mat(0, 0, type);\n  std::istringstream iss(input);\n  double currNum;\n  while (!iss.eof()) {\n    iss >> currNum;\n    mat.push_back(currNum);\n  }\n  return mat.reshape(channels, rows);\n};\n\n\ninline std::vector<double> str2doublesVec(const std::string& doublesStr) {\n  std::list<std::string> tokens;\n  boost::split(tokens, doublesStr, boost::is_any_of(\", \"), boost::token_compress_on);\n  std::vector<double> doublesVec;\n  for (const std::string& t: tokens) {\n    doublesVec.push_back(boost::lexical_cast<double>(t));\n  }\n  return doublesVec;\n};\n\n\n/**\n * Check if 2 (convex) polygons overlap, using the dividing axis algorithm:\n * - if 2 convex polygons do not intersect, then there exists a line that passes between them\n * - such a line only exists if formed by one of the polygons' sides\n *\n * Note that two polygons sharing an edge, or whose one's endpoint intersects\n * the other's edge, are considered to be overlapping.\n */\ninline bool checkPolygonOverlap(const std::vector<cv::Point2f>& cornersA, const std::vector<cv::Point2f>& cornersB) {\n  // Compute angles perpendicular to each of the polygons' sides\n  std::vector<double> projectionAngles;\n  unsigned int i, j;\n  cv::Point2f vec;\n  for (i = 0; i < cornersA.size(); i++) {\n    j = (i == 0) ? cornersA.size() - 1 : i - 1;\n    vec = cornersA[i] - cornersA[j];\n    if (vec.x == 0 && vec.y == 0) continue;\n    projectionAngles.push_back(atan2(vec.x, vec.y)); // NOTE: (x, y) arguments swapped to compute perpendicular angle\n  }\n  for (i = 0; i < cornersB.size(); i++) {\n    j = (i == 0) ? cornersB.size() - 1 : i - 1;\n    vec = cornersB[i] - cornersB[j];\n    if (vec.x == 0 && vec.y == 0) continue;\n    projectionAngles.push_back(atan2(vec.x, vec.y));\n  }\n\n  // Scan for dividing axis line\n  bool overlap = true;\n  for (const double& angle: projectionAngles) {\n    double projAMin = std::numeric_limits<double>::infinity();\n    double projAMax = -std::numeric_limits<double>::infinity();\n    double projBMin = std::numeric_limits<double>::infinity();\n    double projBMax = -std::numeric_limits<double>::infinity();\n    double cosAngle = cos(angle);\n    double sinAngle = sin(angle);\n    for (const cv::Point2f& pt: cornersA) {\n      double proj = cosAngle * pt.x - sinAngle * pt.y;\n      if (proj < projAMin) projAMin = proj;\n      if (proj > projAMax) projAMax = proj;\n    }\n    for (const cv::Point2f& pt: cornersB) {\n      double proj = cosAngle * pt.x - sinAngle * pt.y;\n      if (proj < projBMin) projBMin = proj;\n      if (proj > projBMax) projBMax = proj;\n    }\n    if ((projAMax < projBMin) || (projAMin > projBMax)) {\n      overlap = false;\n      break;\n    }\n  }\n\n  return overlap;\n};\n\n\n};\n\n\n#endif /* VECTORANDCIRCULARMATH_HPP_ */\n", "meta": {"hexsha": "2b0334151bae3afb4b611107a54d24121695d540", "size": 25246, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/common/VectorAndCircularMath.hpp", "max_stars_repo_name": "anqixu/ftag2", "max_stars_repo_head_hexsha": "f77c0c0960a1ed44cc8723fd6c5320b7bb256a68", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-08-16T07:04:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T11:02:09.000Z", "max_issues_repo_path": "include/common/VectorAndCircularMath.hpp", "max_issues_repo_name": "anqixu/ftag2", "max_issues_repo_head_hexsha": "f77c0c0960a1ed44cc8723fd6c5320b7bb256a68", "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/common/VectorAndCircularMath.hpp", "max_forks_repo_name": "anqixu/ftag2", "max_forks_repo_head_hexsha": "f77c0c0960a1ed44cc8723fd6c5320b7bb256a68", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-09T21:05:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-09T21:05:56.000Z", "avg_line_length": 32.787012987, "max_line_length": 117, "alphanum_fraction": 0.6151073437, "num_tokens": 8566, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6513548782017746, "lm_q1q2_score": 0.49359306040358386}}
{"text": "/*\n * determinant.hh\n *\n *  Created on: Sep 21, 2011\n *      Author: bzflubko\n */\n\n#ifndef DETERMINANT_HH_\n#define DETERMINANT_HH_\n\n#include <dune/common/fmatrix.hh>\n#include <boost/static_assert.hpp>\n#include \"utilities/get.hh\"\n#include \"fem/fixdune.hh\"\n\n/// \\cond internals\nnamespace DeterminantDetail {\n\n  template <typename MatrixType>\n  Dune::FieldMatrix<double,MatrixType::rows-1,MatrixType::cols-1> getMinor(MatrixType const& matrix, int rowIndex, int colIndex)\n  {\n    BOOST_STATIC_ASSERT( (MatrixType::rows > 1) && (MatrixType::cols > 1) );\n    Dune::FieldMatrix<double,MatrixType::rows-1,MatrixType::cols-1> subMatrix(0);\n    for(int ii=0, iii=0; ii<MatrixType::rows; ++ii)\n    {\n      if(ii!=rowIndex)\n      {\n        for(int kk=0, kkk=0; kk<MatrixType::cols; ++kk)\n        {\n          if(kk!=colIndex)\n          {\n            subMatrix[iii][kkk]=matrix[ii][kk];\n            ++kkk;\n          }\n        }\n        ++iii;\n      }\n    }\n\n    return subMatrix;\n  }\n\n}\n/// \\endcond\n\nnamespace Kaskade {\n\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n/* DETERMINANT                                                                                                                     */\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\n\n/**\n * \\ingroup linalgbasic\n * \\brief Class for computing determinants of matrices and (directional) derivatives thereof.\n * \n * On construction, the Determinant class takes a reference to the matrix (or a functor returning the matrix) and computes\n * determinants and derivatives on demand. That is, if the referenced matrix is modified, the modification is reflected \n * in the next determinant computation.\n */\ntemplate <int dim, class Source=Dune::FieldMatrix<double,dim,dim> >\nclass Determinant;\n\ntemplate <class Source>\nclass Determinant<2,Source>\n{\npublic:\n  typedef Source source_type;\n  typedef Dune::FieldMatrix<double,2,2> MatrixType;\n\nprivate:\n  typedef Get<MatrixType,Source> GetMatrix;\n\n  double composeResult(MatrixType const& m1, MatrixType const& m2) const { return m1[0][0]*m2[1][1] + m1[1][1]*m2[0][0] - (m1[0][1]*m2[1][0] + m1[1][0]*m2[0][1]); }\n\npublic:\n  /**\n   * \\brief Constructor.\n   * \n   * \\param s reference to the source of the matrix of which the determinant is to be computed. This can either \n   *          be a Dune::FieldMatrix<double,n,n> itself or a functor returning such a matrix. Note that the source\n   *          is held by reference and needs to exist as long as the Determinant object exists.\n   */\n  explicit Determinant(Source& s) : matrix(s){}\n\n  double operator()() const { return d0(); }\n\n  double d0() const { return matrix()[0][0]*matrix()[1][1] - matrix()[0][1]*matrix()[1][0]; }\n\n  double d1(MatrixType const& dA) const { return composeResult(matrix(),dA); }\n\n  double d2(MatrixType const& dA, MatrixType const& dB) const { return composeResult(dB,dA); }\n\n  double d3(MatrixType const&, MatrixType const&, MatrixType const&) const { return 0; }\n\nprivate:\n  GetMatrix matrix;\n  //MatrixType &matrix;\n};\n\n/// Determinant\ntemplate <class Source>\nclass Determinant<3,Source>\n{\npublic:\n  typedef Source source_type;\n  typedef Dune::FieldMatrix<double,3,3> MatrixType;\n\nprivate:\n  typedef Get<MatrixType,Source> GetMatrix;\n\n  template<int a1, int a2, int b1, int b2, int c1, int c2> double tp(MatrixType const& t) const\n  {\n    return t[a1][a2]*t[b1][b2]*t[c1][c2];\n  }\n\n  template<int a1, int a2, int b1, int b2, int c1, int c2> double circular(MatrixType const& t, MatrixType const& u, MatrixType const& v) const\n  {\n    return t[a1][a2]*u[b1][b2]*v[c1][c2]+v[a1][a2]*t[b1][b2]*u[c1][c2]+u[a1][a2]*v[b1][b2]*t[c1][c2];\n  }\n\n  template<int a1, int a2, int b1, int b2, int c1, int c2> double dtp(MatrixType const& t, MatrixType const& dv) const\n  {\n    return circular<a1,a2,b1,b2,c1,c2>(t,t,dv);\n  }\n\n  template<int a1, int a2, int b1, int b2, int c1, int c2> double ddtp(MatrixType const& t, MatrixType const& dv, MatrixType const& dw) const\n  {\n    return circular<a1,a2,b1,b2,c1,c2>(t,dv,dw)+circular<a1,a2,b1,b2,c1,c2>(t,dw,dv);\n  }\n\n  template<int a1, int a2, int b1, int b2, int c1, int c2> double dddtp(MatrixType const& du, MatrixType const& dv, MatrixType const& dw) const\n  {\n    return circular<a1,a2,b1,b2,c1,c2>(du,dv,dw)+circular<a1,a2,b1,b2,c1,c2>(du,dw,dv);\n  }\n\npublic:\n  /**\n   * \\brief Constructor.\n   * \n   * \\param s reference to the source of the matrix of which the determinant is to be computed. This can either \n   *          be a Dune::FieldMatrix<double,n,n> itself or a functor returning such a matrix. Note that the source\n   *          is held by reference and needs to exist as long as the Determinant object exists.\n   */\n  explicit Determinant(Source &s): matrix(s){}\n\n  double operator()() const { return d0(); }\n\n  double d0() const\n  {\n    return tp<0,0,1,1,2,2>(matrix())+tp<0,1,1,2,2,0>(matrix())+tp<0,2,1,0,2,1>(matrix())\n        - tp<2,0,1,1,0,2>(matrix())-tp<2,1,1,2,0,0>(matrix())-tp<2,2,1,0,0,1>(matrix());\n  }\n\n  double d1(MatrixType const& dv) const\n  {\n    return dtp<0,0,1,1,2,2>(matrix(),dv)+dtp<0,1,1,2,2,0>(matrix(),dv)+dtp<0,2,1,0,2,1>(matrix(),dv)\n        -dtp<2,0,1,1,0,2>(matrix(),dv)-dtp<2,1,1,2,0,0>(matrix(),dv)-dtp<2,2,1,0,0,1>(matrix(),dv);\n  }\n\n  double d2(MatrixType const& dv, MatrixType const& dw) const\n  {\n    return ddtp<0,0,1,1,2,2>(matrix(),dv,dw)+ddtp<0,1,1,2,2,0>(matrix(),dv,dw)+ddtp<0,2,1,0,2,1>(matrix(),dv,dw)\n        - ddtp<2,0,1,1,0,2>(matrix(),dv,dw)-ddtp<2,1,1,2,0,0>(matrix(),dv,dw)-ddtp<2,2,1,0,0,1>(matrix(),dv,dw);\n  }\n\n  double d3(MatrixType const& du, MatrixType const& dv, MatrixType const& dw) const\n  {\n    return dddtp<0,0,1,1,2,2>(du,dv,dw)+dddtp<0,1,1,2,2,0>(du,dv,dw)+dddtp<0,2,1,0,2,1>(du,dv,dw)\n        - dddtp<2,0,1,1,0,2>(du,dv,dw)-dddtp<2,1,1,2,0,0>(du,dv,dw)-dddtp<2,2,1,0,0,1>(du,dv,dw);\n  }\n\nprivate:\n  GetMatrix matrix;\n//  MatrixType &matrix;\n};\n\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n/* ADJUGATE                                                                                                                        */\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\ntemplate <int dim, class Source=Dune::FieldMatrix<double,dim,dim> > class Adjugate;\n\ntemplate <int dim, class Source=Dune::FieldMatrix<double,dim,dim> > class Cofactor;\n\ntemplate <class Source>\nclass Adjugate<2, Source>{\npublic:\n  typedef Dune::FieldMatrix<double,2,2> MatrixType;\nprivate:\n  typedef Get<MatrixType,Source> GetMatrix;\n\n  void composeResult(MatrixType const& m) const\n  {\n    result[0][0] = m[1][1]; result[0][1] = -m[1][0];\n    result[1][0] = -m[0][1]; result[1][1] = m[0][0];\n  }\n\npublic:\n  explicit Adjugate(Source &s) : matrix(s), result(0){}\n\n  MatrixType d0() const\n  {\n    composeResult(matrix());\n    return result;\n  }\n\n  MatrixType d1(MatrixType const& dA) const\n  {\n    composeResult(dA);\n    return result;\n  }\n\n  MatrixType d2(MatrixType const&, MatrixType const&) const { return 0.0*result; }\n\n  MatrixType d3(MatrixType const&, MatrixType const&, MatrixType const&) { return 0.0*result; }\n\n  //Cofactor<2,Source> transpose() const { return Cofactor<2,Source>(matrix); }\n\nprivate:\n  GetMatrix matrix;\n//  MatrixType &matrix;\n  mutable MatrixType result;\n};\n\n/**\n * Adjugate of a 3x3-matrix\n */\ntemplate <class Source>\nclass Adjugate<3,Source>\n{\npublic:\n  enum{ dim=3 };\n  typedef Dune::FieldMatrix<double,dim,dim> MatrixType;\n  typedef typename GetSubType<double,dim,MatrixType>::type SubMatrixType;\nprivate:\n  typedef Get<MatrixType,Source> GetMatrix;\n\npublic:\n  explicit Adjugate(Source &s) :matrix(s){}\n\n  MatrixType d0() const\n  {\n    for(int i=0; i<dim; ++i)\n      for(int j=0; j<dim; ++j)\n      {\n        SubMatrixType tmp = DeterminantDetail::getMinor(matrix(),i,j);\n        int sign = 1;\n        if((i+j)%2) sign = -1;\n        result[j][i] = sign*Determinant<dim-1,SubMatrixType>(tmp).d0();\n      }\n    return result;\n  }\n\n  MatrixType d1(MatrixType const& dv) const{\n    for(int i=0; i<dim; ++i){\n      for(int j=0; j<dim; ++j){\n        int i1 = (i+1)%dim; int i2 = (i+2)%dim;\n        int j1 = (j+1)%dim; int j2 = (j+2)%dim;\n        result[j][i] = matrix()[i1][j1]*dv[i2][j2] + matrix()[i2][j2]*dv[i1][j1] -\n            matrix()[i1][j2]*dv[i2][j1] - matrix()[i2][j1]*dv[i1][j2];\n        //result[j][i] *= ((i+j)%2==0) ? 1. : -1.;\n      }\n    }\n    return result;\n  }\n\n  MatrixType d2(MatrixType const& dv, MatrixType const& dw) const {\n    result = MatrixType(0);\n    for(int i=0; i<dim; ++i){\n      for(int j=0; j<dim; ++j){\n        int i1 = (i+1)%dim; int i2 = (i+2)%dim;\n        int j1 = (j+1)%dim; int j2 = (j+2)%dim;\n\n        result[j][i] += dv[i2][j2]*dw[i1][j1] + dv[i1][j1]*dw[i2][j2];\n        result[j][i] -= dv[i2][j1]*dw[i1][j2] + dv[i1][j2]*dw[i2][j1];\n        //result[j][i] *= ((i+j)%2==0) ? 1. : -1.;\n      }\n    }\n\n    return result;\n  }\n\n  MatrixType d3(MatrixType const&, MatrixType const&, MatrixType const&) const\n  {\n    return 0.0*matrix();\n  }\n\n  //Cofactor<3,Source> transpose() const { return Cofactor<3,Source>(matrix); }\n\nprivate:\n  GetMatrix matrix;\n//  MatrixType &matrix;\n  mutable MatrixType result;\n};\n\n\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n/* Cofactor matrix                                                                                                                 */\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n/**\n * implemented as adjugate transposed\n */\ntemplate <int dimension, class Source>\nclass Cofactor{\t\npublic:\t\n  enum{ dim=dimension };\n  typedef Dune::FieldMatrix<double,dim,dim> MatrixType;\n  typedef Dune::FieldMatrix<double,dim-1,dim-1> SubMatrixType;\nprivate:\n  typedef Get<MatrixType,Source> GetMatrix;\n\npublic:\n  explicit Cofactor(Source& s) : adj(s){}\n\n  MatrixType const d0() const { return transpose( adj.d0() ); }\n\n  MatrixType const d1(MatrixType const& dv) const { return transpose( adj.d1(dv) ); }\n\n  MatrixType const d2(MatrixType const& dv, MatrixType const& dw) const\n  { return transpose( adj.d2(dv,dw) ); }\n  \n  MatrixType const d3(MatrixType const& dv, MatrixType const& dw, MatrixType const& dx) const\n  { return transpose( adj.d3(dv,dw,dx) ); }\n\n  //Adjugate<dim,Source> transpose() const { return adj; }\n\nprivate: \n  Adjugate<dim,Source> const adj;\n};\n\n} // end of namespace Kaskade\n\n#endif /* DETERMINANT_HH_ */\n", "meta": {"hexsha": "cb73bb59e6419a5c052eac20c902adb3b66676f6", "size": 10721, "ext": "hh", "lang": "C++", "max_stars_repo_path": "Kaskade/utilities/linalg/determinant.hh", "max_stars_repo_name": "chenzongxiong/streambox", "max_stars_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-07-03T14:03:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T10:18:49.000Z", "max_issues_repo_path": "Kaskade/utilities/linalg/determinant.hh", "max_issues_repo_name": "chenzongxiong/streambox", "max_issues_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-02-17T12:01:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-09T22:02:36.000Z", "max_forks_repo_path": "Kaskade/utilities/linalg/determinant.hh", "max_forks_repo_name": "chenzongxiong/streambox", "max_forks_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-03T04:41:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-11T21:44:42.000Z", "avg_line_length": 32.0988023952, "max_line_length": 164, "alphanum_fraction": 0.5686969499, "num_tokens": 3661, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.4935930604035838}}
{"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_FUNCTION_MANTISSA_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_MANTISSA_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-ieee\n    Function object implementing mantissa capabilities\n\n    Returns the signed mantissa of the floating input.\n\n    @par Semantic:\n\n    @code\n    T r = mantissa(x);\n    @endcode\n\n    is similar to:\n\n    @code\n    T r = x*pow(2, -exponent(x));\n    @endcode\n\n    @par Note\n    The @ref exponent e and signed @ref mantissa m of a floating point entry a are related by\n    \\f$a = m\\times 2^e\\f$, with the absolute value of m between one (included) ans two (excluded).\n\n    @see frexp\n\n  **/\n  const boost::dispatch::functor<tag::mantissa_> mantissa = {};\n} }\n#endif\n\n#include <boost/simd/function/scalar/mantissa.hpp>\n#include <boost/simd/function/simd/mantissa.hpp>\n\n#endif\n", "meta": {"hexsha": "9e3aa844fc9a0bff44b36381450092ee5b318206", "size": 1288, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/mantissa.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/function/mantissa.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/function/mantissa.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": 24.3018867925, "max_line_length": 100, "alphanum_fraction": 0.5931677019, "num_tokens": 300, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.4935930604035838}}
{"text": "#include \"sparse_solver.hpp\"\n#include <Eigen/Sparse>\n#include <iostream>\n#include <stdexcept>\n\nstd::unique_ptr<sparse_solver_interface> make_sparse_solver(\n    const std::string& type, const std::string& preconditioner) {\n  using std::make_unique;\n  using namespace Eigen;\n\n  if (type == \"BiCGSTAB\") {\n    if (preconditioner == \"IncompleteLUT\")\n      return make_unique<sparse_solver<\n          BiCGSTAB<SparseMatrix<double>, IncompleteLUT<double>>>>();\n    else if (preconditioner == \"Diagonal\")\n      return make_unique<sparse_solver<\n          BiCGSTAB<SparseMatrix<double>, DiagonalPreconditioner<double>>>>();\n    else if (preconditioner == \"Identity\")\n      return make_unique<sparse_solver<\n          BiCGSTAB<SparseMatrix<double>, IdentityPreconditioner>>>();\n    else if (preconditioner == \"SimplicialCholesky\")\n      return make_unique<sparse_solver<BiCGSTAB<\n          SparseMatrix<double>, SimplicialCholesky<SparseMatrix<double>>>>>();\n    else {\n      std::stringstream ss;\n      ss << \"Error: \" << __FILE__ << \": \" << __LINE__;\n      if (preconditioner.empty())\n        ss << \"\\n  Empty preconditioner found\\n\";\n      else\n        ss << \"\\n  Invalid preconditioner found: \" << preconditioner << \"\\n\";\n      ss << \"  Valid preconditioners are:\\n\"\n         << \"    SimplicialCholesky,\\n\"\n         << \"    IncompleteLUT,\\n\"\n         << \"    Diagonal,\\n\"\n         << \"    Identity\" << std::endl;\n      throw std::invalid_argument(ss.str());\n    }\n  } else if (type == \"SparseQR\") {\n    return make_unique<\n        sparse_solver<SparseQR<SparseMatrix<double>, COLAMDOrdering<int>>>>();\n  } else if (type == \"SparseLU\")\n    return make_unique<sparse_solver<SparseLU<SparseMatrix<double>>>>();\n  else {\n    std::stringstream ss;\n    ss << \"Error: \" << __FILE__ << \": \" << __LINE__\n       << \"\\n  Invalid sparse solver type found: \" << type\n       << \"\\n  Valid sparse solver types are:\\n\"\n       << \"    BiCGSTAB,\\n\"\n       << \"    SparseQR,\\n\"\n       << \"    SparseLU\" << std::endl;\n    throw std::invalid_argument(ss.str());\n  }\n}\n", "meta": {"hexsha": "a65608d860ab4df2f85a196b3ffe0aef5db7dfc0", "size": 2041, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "shohirose/eigen_solvers/sparse_solver.cpp", "max_stars_repo_name": "shohirose/qiita", "max_stars_repo_head_hexsha": "ff8548762e1587b17eee32d3733283b8b1cc937b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "shohirose/eigen_solvers/sparse_solver.cpp", "max_issues_repo_name": "shohirose/qiita", "max_issues_repo_head_hexsha": "ff8548762e1587b17eee32d3733283b8b1cc937b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "shohirose/eigen_solvers/sparse_solver.cpp", "max_forks_repo_name": "shohirose/qiita", "max_forks_repo_head_hexsha": "ff8548762e1587b17eee32d3733283b8b1cc937b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-05-15T08:47:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-15T08:47:39.000Z", "avg_line_length": 37.7962962963, "max_line_length": 78, "alphanum_fraction": 0.617344439, "num_tokens": 530, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.4935930604035838}}
{"text": "/*=============================================================================\nCopyright 2020 Syed Ali Hasan <alihasan9922@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#include <iostream>\n#include <stack>\n\n//Graph\n#include <boost/graph/graphviz.hpp>\n#include <boost/graph/properties.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/breadth_first_search.hpp>\n#include <boost/graph/named_function_params.hpp>\n\n//Matrix\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/astronomy/coordinate/utility/utility.hpp>\n\n//Angle\n#include <boost/units/io.hpp>\n#include <boost/units/systems/angle/degrees.hpp>\n#include <boost/units/systems/si/plane_angle.hpp>\n\nnamespace bu = boost::units;\nnamespace bg = boost::geometry;\nnamespace bac = boost::astronomy::coordinate;\n\nusing namespace boost::units;\nusing namespace boost::units::si;\nusing namespace boost::astronomy::coordinate;\n\nenum class COORDINATE_SYSTEM {\n  HORIZON,\n  EQUATORIAL_HA_DEC,\n  EQUATORIAL_RA_DEC,\n  ECLIPTIC,\n  GALACTIC};\n\nstruct CoordinateData\n{\n  COORDINATE_SYSTEM coordinate_system;\n  std::string coordinate_name;\n};\n\nstruct EdgeData\n{\n  std::string edge_label;\n  matrix<double> conv_matrix;\n};\n\nusing graph_t = boost::adjacency_list<boost::vecS, boost::vecS,\n    boost::directedS,\n    CoordinateData,\n    EdgeData>;\n\nusing vertex_t = boost::graph_traits<graph_t>::vertex_descriptor;\n\ntemplate\n<\n  typename CoordinateType = double,\n  typename Angle = bu::quantity<bu::si::plane_angle, CoordinateType>\n>\nmatrix<double> convert(const COORDINATE_SYSTEM src,\n                       const COORDINATE_SYSTEM dest,\n                       const Angle& phi,\n                       const Angle& st,\n                       const Angle& obliquity,\n                       coord_sys<2, bg::cs::spherical<bg::radian>, CoordinateType> source_coordinate)\n{\n  bac::column_vector<double,\n      quantity<bu::si::plane_angle, double>,\n      double>\n      col_vec(bg::get<0>(source_coordinate.get_point()) * radians, bg::get<1>(source_coordinate.get_point()) * radians);\n\n  graph_t G;\n\n  const int graph_size = 5;\n\n  vertex_t vd0 = boost::add_vertex(CoordinateData{COORDINATE_SYSTEM::HORIZON,\"Horizon\"}, G);\n  vertex_t vd1 = boost::add_vertex(CoordinateData{COORDINATE_SYSTEM::EQUATORIAL_HA_DEC,\"Equatorial_HA_Dec\"}, G);\n  vertex_t vd2 = boost::add_vertex(CoordinateData{COORDINATE_SYSTEM::EQUATORIAL_RA_DEC,\"Equatorial_RA_Dec\"}, G);\n  vertex_t vd3 = boost::add_vertex(CoordinateData{COORDINATE_SYSTEM::ECLIPTIC,\"Ecliptic\"}, G);\n  vertex_t vd4 = boost::add_vertex(CoordinateData{COORDINATE_SYSTEM::GALACTIC,\"Galactic\"}, G);\n\n  boost::add_edge(vd0, vd1, EdgeData{\"Horizon to Equatorial HA Dec\", bac::ha_dec_horizon<double, quantity<bu::degree::plane_angle>, double>(phi).get()}, G);\n  boost::add_edge(vd1, vd0, EdgeData{\"Equatorial HA Dec to Horizon\", bac::ha_dec_horizon<double, quantity<bu::degree::plane_angle>, double>(phi).get()}, G);\n  boost::add_edge(vd1, vd2, EdgeData{\"Equatorial HA Dec to Equatorial RA Dec\", bac::ha_dec_ra_dec<double, quantity<bu::degree::plane_angle>, double>(st).get()}, G);\n  boost::add_edge(vd2, vd1, EdgeData{\"Equatorial RA Dec to Equatorial HA Dec\", bac::ha_dec_ra_dec<double, quantity<bu::degree::plane_angle>, double>(st).get()}, G);\n  boost::add_edge(vd2, vd3, EdgeData{\"Equatorial RA Dec to Ecliptic\", bac::ra_dec_to_ecliptic<double, quantity<bu::degree::plane_angle>, double>(obliquity).get()}, G);\n  boost::add_edge(vd3, vd2, EdgeData{\"Ecliptic to Equatorial RA Dec\", bac::ecliptic_to_ra_dec<double, quantity<bu::degree::plane_angle>, double>(obliquity).get()}, G);\n  boost::add_edge(vd2, vd4, EdgeData{\"Equatorial RA Dec to Galactic\", bac::ra_dec_to_galactic<double>().get()}, G);\n  boost::add_edge(vd4, vd2, EdgeData{\"Galactic to Equatorial RA Dec\", bac::galactic_to_ra_dec<double>().get()}, G);\n\n  //Predecessor Array\n  boost::array<int, graph_size> predecessors{0};\n  predecessors[(int)src] = (int)src;\n\n  boost::breadth_first_search(G, (int)src, boost::visitor(\n      boost::make_bfs_visitor(\n          boost::record_predecessors(predecessors.begin(),\n                                     boost::on_tree_edge{}))));\n\n  //Get traversed path\n  std::vector<int> store_path;\n\n  int p = (int)dest;\n  while (p != (int)src)\n  {\n    store_path.push_back(p);\n    p = predecessors[p];\n  }\n  store_path.push_back(p);\n\n  matrix<double> ans = col_vec.get();\n\n  //Matrix Multiplication\n  for(auto it = store_path.rbegin(); it + 1 != store_path.rend(); ++it)\n    ans = prod(G[boost::edge(*it,*(it+1),G).first].conv_matrix, ans);\n\n  return ans;\n}", "meta": {"hexsha": "f9909e26ecc3dd4c84105ba85de45e6cfa8c2069", "size": 4768, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/astronomy/coordinate/conversion/conversion_graph.hpp", "max_stars_repo_name": "Zyro9922/astronomy", "max_stars_repo_head_hexsha": "56be0f8dfb103520ffbec0b793a92a531cd4b714", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-05-14T08:23:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-23T05:26:19.000Z", "max_issues_repo_path": "include/boost/astronomy/coordinate/conversion/conversion_graph.hpp", "max_issues_repo_name": "Zyro9922/astronomy", "max_issues_repo_head_hexsha": "56be0f8dfb103520ffbec0b793a92a531cd4b714", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/astronomy/coordinate/conversion/conversion_graph.hpp", "max_forks_repo_name": "Zyro9922/astronomy", "max_forks_repo_head_hexsha": "56be0f8dfb103520ffbec0b793a92a531cd4b714", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.144, "max_line_length": 167, "alphanum_fraction": 0.6893875839, "num_tokens": 1280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.757794360334681, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.49359305327778774}}
{"text": "\n// BLAS level 3\n// hermitian matrix (kind of ;o)\n\n#include <stddef.h>\n#include <iostream>\n#include <complex>\n#include <boost/numeric/bindings/blas.hpp>\n#include <boost/numeric/bindings/ublas/matrix.hpp>\n#include <boost/numeric/bindings/ublas/hermitian.hpp>\n#include \"utils.h\"\n\nnamespace ublas = boost::numeric::ublas;\nnamespace blas = boost::numeric::bindings::blas;\nnamespace bindings = boost::numeric::bindings;\nnamespace tag = boost::numeric::bindings::tag;\n\nusing std::cout;\nusing std::cin;\nusing std::endl; \n\ntypedef double real_t; \ntypedef std::complex<real_t> cmplx_t;\n\ntypedef ublas::matrix<cmplx_t, ublas::column_major> cm_t; \ntypedef ublas::matrix<cmplx_t, ublas::row_major> rm_t; \n\ntypedef ublas::hermitian_adaptor<cm_t, ublas::upper> uchemm_t; \ntypedef ublas::hermitian_adaptor<cm_t, ublas::lower> lchemm_t; \ntypedef ublas::hermitian_adaptor<rm_t, ublas::upper> urhemm_t; \ntypedef ublas::hermitian_adaptor<rm_t, ublas::lower> lrhemm_t; \n\nint main (int argc, char **argv) {\n  size_t n = 0;\n  if (argc > 1) {\n    n = atoi(argv [1]);\n  }\n  \n  cout << endl; \n\n  if (n <= 0) {\n    cout << \"n -> \";\n    cin >> n;\n  }\n  cout << endl; \n\n  cm_t uc (n, n);\n  uchemm_t ucs (uc); \n  cm_t lc (n, n); \n  lchemm_t lcs (lc); \n  rm_t ur (n, n); \n  urhemm_t urs (ur); \n  rm_t lr (n, n); \n  lrhemm_t lrs (lr); \n\n  init_symm (ucs, 'u'); \n  init_symm (lcs, 'l'); \n  init_symm (urs, 'u'); \n  init_symm (lrs, 'l'); \n\n  print_m (ucs, \"a == ucs\");\n  cout << endl; \n  print_m_data (ucs, \"ucs\");\n  cout << endl; \n\n  print_m (lcs, \"a == lcs\");\n  cout << endl; \n  print_m_data (lcs, \"lcs\");\n  cout << endl; \n\n  print_m (urs, \"a == urs\");\n  cout << endl; \n  print_m_data (urs, \"urs\");\n  cout << endl; \n\n  print_m (lrs, \"a == lrs\");\n  cout << endl; \n  print_m_data (lrs, \"lrs\");\n  cout << endl; \n\n  cm_t cbl (n, n+1); \n  rm_t rbl (n, n+1); \n  cm_t ccl (n, n+1); \n  rm_t rcl (n, n+1); \n\n  init_m (cbl, rws1());\n  init_m (rbl, rws1());\n\n  print_m (cbl, \"b == cb\");\n  cout << endl; \n  print_m (rbl, \"b == rb\");\n  cout << endl; \n\n  blas::hemm ( tag::left(), 1.0, ucs, cbl, 0.0, ccl); \n  print_m (ccl, \"c = a b\");\n  cout << endl; \n\n  blas::hemm ( tag::left(), 1.0, lcs, cbl, 0.0, ccl);  \n  print_m (ccl, \"c = a b\");\n  cout << endl; \n\n  blas::hemm ( tag::left(), 1.0, urs, rbl, 0.0, rcl); \n  print_m (rcl, \"c = a b\");\n  cout << endl; \n\n  blas::hemm ( tag::left(), 1.0, lrs, rbl, 0.0, rcl); \n  print_m (rcl, \"c = a b\");\n  cout << endl; \n  \n  cm_t cbr (n+1, n); \n  rm_t rbr (n+1, n); \n  cm_t ccr (n+1, n); \n  rm_t rcr (n+1, n); \n\n  init_m (cbr, cls1());\n  init_m (rbr, cls1());\n  \n  print_m (cbr, \"b == cb\");\n  cout << endl; \n  print_m (rbr, \"b == rb\");\n  cout << endl; \n\n  blas::hemm ( tag::right(), 1.0, ucs, cbr, 0.0, ccr); \n  print_m (ccr, \"c = b a\");\n  cout << endl; \n\n  blas::hemm ( tag::right(), 1.0, lcs, cbr, 0.0, ccr);  \n  print_m (ccr, \"c = b a\");\n  cout << endl; \n\n  blas::hemm ( tag::right(), 1.0, urs, rbr, 0.0, rcr); \n  print_m (rcr, \"c = b a\");\n  cout << endl; \n\n  blas::hemm ( tag::right(), 1.0, lrs, rbr, 0.0, rcr); \n  print_m (rcr, \"c = b a\");\n  cout << endl; \n\n  cout << endl; \n\n}\n", "meta": {"hexsha": "845aa2d1d8d339fca3e30af6ef22edf2ffcf3a38", "size": 3075, "ext": "cc", "lang": "C++", "max_stars_repo_path": "externals/numeric_bindings/libs/numeric/bindings/atlas/ublas_herm3.cc", "max_stars_repo_name": "ljktest/siconos", "max_stars_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 137.0, "max_stars_repo_stars_event_min_datetime": "2015-06-16T15:55:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T06:01:59.000Z", "max_issues_repo_path": "externals/numeric_bindings/libs/numeric/bindings/atlas/ublas_herm3.cc", "max_issues_repo_name": "ljktest/siconos", "max_issues_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 381.0, "max_issues_repo_issues_event_min_datetime": "2015-09-22T15:31:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-14T09:05:23.000Z", "max_forks_repo_path": "externals/numeric_bindings/libs/numeric/bindings/atlas/ublas_herm3.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": 21.6549295775, "max_line_length": 63, "alphanum_fraction": 0.5684552846, "num_tokens": 1252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.4935930450176448}}
{"text": "#include <tdp/testing/testing.h>\n#include <Eigen/Dense>\n#include <tdp/slam/keyframe_slam.h>\n#include <tdp/data/managed_image.h>\n\n#include <isam/isam.h>\n#include <isam/Slam.h>\n#include <isam/robust.h>\n\nusing namespace tdp; \nTEST(setup, KeyframeSLAM) {\n  SE3f T_wk0;\n  SE3f T_wk1 (SO3f::Rx(5.*M_PI/180.), Eigen::Vector3f(0,0,1));\n  SE3f dT_01 (SO3f::Rx(6.*M_PI/180.), Eigen::Vector3f(0,0,1.1));\n\n  KeyframeSLAM kfSLAM;  \n  kfSLAM.AddOrigin(T_wk0);\n  kfSLAM.AddIcpOdometry(0,1,T_wk0.Inverse()*T_wk1);\n  kfSLAM.AddLoopClosure(0,1,dT_01);\n\n  kfSLAM.PrintGraph();\n  kfSLAM.PrintValues();\n  kfSLAM.Optimize();\n  kfSLAM.PrintValues();\n  kfSLAM.Optimize();\n  kfSLAM.PrintValues();\n}\n\nTEST(setup, isam) {\n  isam::Slam slam;\n\n  isam::Properties props;\n  props.verbose=true;\n  props.method=isam::Method::GAUSS_NEWTON;\n  props.method=isam::Method::LEVENBERG_MARQUARDT;\n  props.epsilon_rel = 1e-6;\n  props.epsilon_abs = 1e-6;\n  slam.set_properties(props); \n\n  float a = 5.*M_PI/180.;\n  Eigen::Matrix3d Ra;\n  Ra << 1, 0, 0,\n       0, cos(a), -sin(a),\n       0, sin(a), cos(a);\n  a = 6.*M_PI/180.;\n  Eigen::Matrix3d Rb;\n  Rb << 1, 0, 0,\n       0, cos(a), -sin(a),\n       0, sin(a), cos(a);\n  \n  Eigen::Vector3d ta(0,0,1);\n  Eigen::Vector3d tb(0,0,1.1);\n  Eigen::Vector3d tc(0.01,0,1.1);\n\n  isam::Pose3d origin(ta, isam::Rot3d(Ra));\n  isam::Point3d p0(5.,1.,2.);\n\n  // first monocular camera\n  isam::Pose3d_Node* pose0 = new isam::Pose3d_Node();\n  slam.add_node(pose0);\n\n  // create a prior on the camera position\n  isam::Noise noise6 = isam::Information(100. * isam::eye(6));\n  isam::Pose3d_Factor* prior = new isam::Pose3d_Factor(pose0, origin, noise6);\n  slam.add_factor(prior);\n\n  // second monocular camera\n  isam::Pose3d_Node* pose1 = new isam::Pose3d_Node();\n  slam.add_node(pose1);\n\n  isam::Pose3d delta(tb, isam::Rot3d(Rb)); \n  isam::Pose3d delta2(tc, isam::Rot3d(Rb)); \n  isam::Pose3d_Pose3d_Factor* odo = new isam::Pose3d_Pose3d_Factor(pose0, \n      pose1, delta, noise6);\n  slam.add_factor(odo);\n  isam::Pose3d_Pose3d_Factor* odo2 = new isam::Pose3d_Pose3d_Factor(pose0, \n      pose1, delta2, noise6);\n  slam.add_factor(odo2);\n\n  // optimize\n  slam.update();\n  std::cout << \"After optimization:\" << std::endl;\n  std::cout << pose0->value() << std::endl;\n  std::cout << pose1->value() << std::endl;\n\n}\n\nint main(int argc, char **argv) {\n  ::testing::InitGoogleTest(&argc, argv);\n  return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "a4c45784f1cb33a56ce55de8246e4b50092f2580", "size": 2401, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/isam.cpp", "max_stars_repo_name": "jstraub/tdp", "max_stars_repo_head_hexsha": "dcab53662be5b88db1538cf831707b07ab96e387", "max_stars_repo_licenses": ["MIT-feh"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-10-17T19:25:47.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-17T19:25:47.000Z", "max_issues_repo_path": "test/isam.cpp", "max_issues_repo_name": "jstraub/tdp", "max_issues_repo_head_hexsha": "dcab53662be5b88db1538cf831707b07ab96e387", "max_issues_repo_licenses": ["MIT-feh"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-05-02T06:04:06.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-02T06:04:06.000Z", "max_forks_repo_path": "test/isam.cpp", "max_forks_repo_name": "jstraub/tdp", "max_forks_repo_head_hexsha": "dcab53662be5b88db1538cf831707b07ab96e387", "max_forks_repo_licenses": ["MIT-feh"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2017-09-17T18:46:20.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-11T12:52:57.000Z", "avg_line_length": 26.097826087, "max_line_length": 78, "alphanum_fraction": 0.6584756352, "num_tokens": 916, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.757794360334681, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.49359303789184894}}
{"text": "// Copyright (C) 2010  Davis E. King (davis@dlib.net)\r\n// License: Boost Software License   See LICENSE.txt for the full license.\r\n\r\n\r\n#include <dlib/matrix.h>\r\n#include <sstream>\r\n#include <string>\r\n#include <cstdlib>\r\n#include <ctime>\r\n#include <vector>\r\n#include \"../stl_checked.h\"\r\n#include \"../array.h\"\r\n#include \"../rand.h\"\r\n#include \"checkerboard.h\"\r\n#include <dlib/statistics.h>\r\n\r\n#include \"tester.h\"\r\n#include <dlib/svm.h>\r\n\r\n\r\nnamespace  \r\n{\r\n\r\n    using namespace test;\r\n    using namespace dlib;\r\n    using namespace std;\r\n\r\n    logger dlog(\"test.svm_c_linear\");\r\n\r\n    typedef matrix<double, 0, 1> sample_type;\r\n    typedef std::vector<std::pair<unsigned int, double> > sparse_sample_type;\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\n    void run_prior_test()\r\n    {\r\n        typedef matrix<double,3,1> sample_type;\r\n        typedef linear_kernel<sample_type> kernel_type;\r\n\r\n        svm_c_linear_trainer<kernel_type> trainer;\r\n\r\n        std::vector<sample_type> samples;\r\n        std::vector<double> labels;\r\n\r\n        sample_type samp;\r\n        samp = 0, 0, 1; samples.push_back(samp); labels.push_back(+1);\r\n        samp = 0, 1, 0; samples.push_back(samp); labels.push_back(-1);\r\n\r\n        trainer.set_c(10);\r\n        decision_function<kernel_type> df = trainer.train(samples, labels);\r\n\r\n        trainer.set_prior(df);\r\n\r\n        samples.clear();\r\n        labels.clear();\r\n        samp = 1, 0, 0; samples.push_back(samp); labels.push_back(+1);\r\n        samp = 0, 1, 0; samples.push_back(samp); labels.push_back(-1);\r\n\r\n        df = trainer.train(samples, labels);\r\n\r\n        samp = 0, 0, 1; samples.push_back(samp); labels.push_back(+1);\r\n        matrix<double,1,2> rs = test_binary_decision_function(df, samples, labels);\r\n        dlog << LINFO << rs;\r\n        DLIB_TEST(rs(0) == 1);\r\n        DLIB_TEST(rs(1) == 1);\r\n\r\n        dlog << LINFO << trans(df.basis_vectors(0));\r\n        DLIB_TEST(df.basis_vectors(0)(0) > 0);\r\n        DLIB_TEST(df.basis_vectors(0)(1) < 0);\r\n        DLIB_TEST(df.basis_vectors(0)(2) > 0);\r\n    }\r\n\r\n    void run_prior_sparse_test()\r\n    {\r\n        typedef std::map<unsigned long,double> sample_type;\r\n        typedef sparse_linear_kernel<sample_type> kernel_type;\r\n\r\n        svm_c_linear_trainer<kernel_type> trainer;\r\n\r\n        std::vector<sample_type> samples;\r\n        std::vector<double> labels;\r\n\r\n        sample_type samp;\r\n        samp[0] = 1; samples.push_back(samp); labels.push_back(+1); samp.clear();\r\n        samp[1] = 1; samples.push_back(samp); labels.push_back(-1); samp.clear();\r\n\r\n        trainer.set_c(10);\r\n        decision_function<kernel_type> df = trainer.train(samples, labels);\r\n\r\n        trainer.set_prior(df);\r\n\r\n        samples.clear();\r\n        labels.clear();\r\n        samp[2] = 1; samples.push_back(samp); labels.push_back(+1); samp.clear();\r\n        samp[1] = 1; samples.push_back(samp); labels.push_back(-1); samp.clear();\r\n\r\n        df = trainer.train(samples, labels);\r\n\r\n        matrix<double,1,2> rs = test_binary_decision_function(df, samples, labels);\r\n        dlog << LINFO << rs;\r\n        DLIB_TEST(rs(0) == 1);\r\n        DLIB_TEST(rs(1) == 1);\r\n\r\n        matrix<double,0,1> w = sparse_to_dense(df.basis_vectors(0));\r\n        dlog << LINFO << trans(w);\r\n        DLIB_TEST(w(0) > 0.1);\r\n        DLIB_TEST(w(1) < -0.1);\r\n        DLIB_TEST(w(2) > 0.1);\r\n    }\r\n\r\n    void get_simple_points (\r\n        std::vector<sample_type>& samples,\r\n        std::vector<double>& labels\r\n    )\r\n    {\r\n        samples.clear();\r\n        labels.clear();\r\n        sample_type samp(2);\r\n\r\n        samp = 0,0;\r\n        samples.push_back(samp);\r\n        labels.push_back(-1);\r\n\r\n        samp = 0,1;\r\n        samples.push_back(samp);\r\n        labels.push_back(-1);\r\n\r\n        samp = 3,0;\r\n        samples.push_back(samp);\r\n        labels.push_back(+1);\r\n\r\n        samp = 3,1;\r\n        samples.push_back(samp);\r\n        labels.push_back(+1);\r\n    }\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\n    void get_simple_points_sparse (\r\n        std::vector<sparse_sample_type>& samples,\r\n        std::vector<double>& labels\r\n    )\r\n    {\r\n        samples.clear();\r\n        labels.clear();\r\n        sparse_sample_type samp;\r\n\r\n        samp.push_back(make_pair(0, 0.0));\r\n        samp.push_back(make_pair(1, 0.0));\r\n        samples.push_back(samp);\r\n        labels.push_back(-1);\r\n\r\n        samp.clear();\r\n        samp.push_back(make_pair(0, 0.0));\r\n        samp.push_back(make_pair(1, 1.0));\r\n        samples.push_back(samp);\r\n        labels.push_back(-1);\r\n\r\n        samp.clear();\r\n        samp.push_back(make_pair(0, 3.0));\r\n        samp.push_back(make_pair(1, 0.0));\r\n        samples.push_back(samp);\r\n        labels.push_back(+1);\r\n\r\n        samp.clear();\r\n        samp.push_back(make_pair(0, 3.0));\r\n        samp.push_back(make_pair(1, 1.0));\r\n        samples.push_back(samp);\r\n        labels.push_back(+1);\r\n    }\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\n    void test_sparse (\r\n    )\r\n    {\r\n        print_spinner();\r\n        dlog << LINFO << \"test with sparse vectors\";\r\n        std::vector<sparse_sample_type> samples;\r\n        std::vector<double> labels;\r\n\r\n        sample_type samp;\r\n\r\n        get_simple_points_sparse(samples,labels);\r\n\r\n        svm_c_linear_trainer<sparse_linear_kernel<sparse_sample_type> > trainer;\r\n        trainer.set_c(1e4);\r\n        //trainer.be_verbose();\r\n        trainer.set_epsilon(1e-11);\r\n\r\n\r\n        double obj;\r\n        decision_function<sparse_linear_kernel<sparse_sample_type> > df = trainer.train(samples, labels, obj);\r\n        dlog << LDEBUG << \"obj: \"<< obj;\r\n        DLIB_TEST_MSG(abs(obj - 0.72222222222) < 1e-7, obj);\r\n\r\n        DLIB_TEST(abs(df(samples[0]) - (-1)) < 1e-6);\r\n        DLIB_TEST(abs(df(samples[1]) - (-1)) < 1e-6);\r\n        DLIB_TEST(abs(df(samples[2]) - (1)) < 1e-6);\r\n        DLIB_TEST(abs(df(samples[3]) - (1)) < 1e-6);\r\n\r\n\r\n        // While we are at it, make sure the krr_trainer works with sparse samples\r\n        krr_trainer<sparse_linear_kernel<sparse_sample_type> > krr;\r\n\r\n        df = krr.train(samples, labels);\r\n        DLIB_TEST(abs(df(samples[0]) - (-1)) < 1e-6);\r\n        DLIB_TEST(abs(df(samples[1]) - (-1)) < 1e-6);\r\n        DLIB_TEST(abs(df(samples[2]) - (1)) < 1e-6);\r\n        DLIB_TEST(abs(df(samples[3]) - (1)) < 1e-6);\r\n\r\n\r\n        // Now test some of the sparse helper functions\r\n        DLIB_TEST(max_index_plus_one(samples) == 2);\r\n        DLIB_TEST(max_index_plus_one(samples[0]) == 2);\r\n\r\n        matrix<double,3,1> m;\r\n        m = 1;\r\n        add_to(m, samples[3]);\r\n        DLIB_TEST(m(0) == 1 + samples[3][0].second);\r\n        DLIB_TEST(m(1) == 1 + samples[3][1].second);\r\n        DLIB_TEST(m(2) == 1);\r\n\r\n        m = 1;\r\n        subtract_from(m, samples[3]);\r\n        DLIB_TEST(m(0) == 1 - samples[3][0].second);\r\n        DLIB_TEST(m(1) == 1 - samples[3][1].second);\r\n        DLIB_TEST(m(2) == 1);\r\n\r\n        m = 1;\r\n        add_to(m, samples[3], 2);\r\n        DLIB_TEST(m(0) == 1 + 2*samples[3][0].second);\r\n        DLIB_TEST(m(1) == 1 + 2*samples[3][1].second);\r\n        DLIB_TEST(m(2) == 1);\r\n\r\n        m = 1;\r\n        subtract_from(m, samples[3], 2);\r\n        DLIB_TEST(m(0) == 1 - 2*samples[3][0].second);\r\n        DLIB_TEST(m(1) == 1 - 2*samples[3][1].second);\r\n        DLIB_TEST(m(2) == 1);\r\n\r\n    }\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\n    void test_dense (\r\n    )\r\n    {\r\n        print_spinner();\r\n        dlog << LINFO << \"test with dense vectors\";\r\n        std::vector<sample_type> samples;\r\n        std::vector<double> labels;\r\n\r\n        sample_type samp;\r\n\r\n        get_simple_points(samples,labels);\r\n\r\n        svm_c_linear_trainer<linear_kernel<sample_type> > trainer;\r\n        trainer.set_c(1e4);\r\n        //trainer.be_verbose();\r\n        trainer.set_epsilon(1e-11);\r\n\r\n\r\n        double obj;\r\n        decision_function<linear_kernel<sample_type> > df = trainer.train(samples, labels, obj);\r\n        dlog << LDEBUG << \"obj: \"<< obj;\r\n        DLIB_TEST_MSG(abs(obj - 0.72222222222) < 1e-7, abs(obj - 0.72222222222));\r\n        // There shouldn't be any margin violations since this dataset is so trivial.  So that means the objective\r\n        // should be exactly the squared norm of the decision plane (times 0.5).\r\n        DLIB_TEST_MSG(abs(length_squared(df.basis_vectors(0))*0.5 + df.b*df.b*0.5 - 0.72222222222) < 1e-7, \r\n                      length_squared(df.basis_vectors(0))*0.5 + df.b*df.b*0.5);\r\n\r\n        DLIB_TEST(abs(df(samples[0]) - (-1)) < 1e-6);\r\n        DLIB_TEST(abs(df(samples[1]) - (-1)) < 1e-6);\r\n        DLIB_TEST(abs(df(samples[2]) - (1)) < 1e-6);\r\n        DLIB_TEST(abs(df(samples[3]) - (1)) < 1e-6);\r\n    }\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\n    class tester_svm_c_linear : public tester\r\n    {\r\n    public:\r\n        tester_svm_c_linear (\r\n        ) :\r\n            tester (\"test_svm_c_linear\",\r\n                    \"Runs tests on the svm_c_linear_trainer.\")\r\n        {}\r\n\r\n        void perform_test (\r\n        )\r\n        {\r\n            test_dense();\r\n            test_sparse();\r\n            run_prior_test();\r\n            run_prior_sparse_test();\r\n\r\n            // test mixed sparse and dense dot products\r\n            {\r\n                std::map<unsigned int, double> sv;\r\n                matrix<double,0,1> dv(4);\r\n\r\n                dv = 1,2,3,4;\r\n\r\n                sv[0] = 1;\r\n                sv[3] = 1;\r\n\r\n\r\n                DLIB_TEST(dot(sv,dv) == 5);\r\n                DLIB_TEST(dot(dv,sv) == 5);\r\n                DLIB_TEST(dot(dv,dv) == 30);\r\n                DLIB_TEST(dot(sv,sv) == 2);\r\n\r\n                sv[10] = 9;\r\n                DLIB_TEST(dot(sv,dv) == 5);\r\n            }\r\n\r\n            // test mixed sparse dense assignments\r\n            {\r\n                std::map<unsigned int, double> sv, sv2;\r\n                std::vector<std::pair<unsigned int, double> > sv3;\r\n                matrix<double,0,1> dv(4), dv2;\r\n\r\n                dv = 1,2,3,4;\r\n\r\n                sv[0] = 1;\r\n                sv[3] = 1;\r\n\r\n\r\n                assign(dv2, dv);\r\n\r\n                DLIB_TEST(dv2.size() == 4);\r\n                DLIB_TEST(dv2(0) == 1);\r\n                DLIB_TEST(dv2(1) == 2);\r\n                DLIB_TEST(dv2(2) == 3);\r\n                DLIB_TEST(dv2(3) == 4);\r\n\r\n                assign(sv2, dv);\r\n                DLIB_TEST(sv2.size() == 4);\r\n                DLIB_TEST(sv2[0] == 1);\r\n                DLIB_TEST(sv2[1] == 2);\r\n                DLIB_TEST(sv2[2] == 3);\r\n                DLIB_TEST(sv2[3] == 4);\r\n\r\n                assign(sv2, sv);\r\n                DLIB_TEST(sv2.size() == 2);\r\n                DLIB_TEST(sv2[0] == 1);\r\n                DLIB_TEST(sv2[1] == 0);\r\n                DLIB_TEST(sv2[2] == 0);\r\n                DLIB_TEST(sv2[3] == 1);\r\n\r\n                assign(sv3, sv);\r\n                DLIB_TEST(sv3.size() == 2);\r\n                DLIB_TEST(sv3[0].second == 1);\r\n                DLIB_TEST(sv3[1].second == 1);\r\n                DLIB_TEST(sv3[0].first == 0);\r\n                DLIB_TEST(sv3[1].first == 3);\r\n\r\n                assign(sv3, dv);\r\n                DLIB_TEST(sv3.size() == 4);\r\n                DLIB_TEST(sv3[0].second == 1);\r\n                DLIB_TEST(sv3[1].second == 2);\r\n                DLIB_TEST(sv3[2].second == 3);\r\n                DLIB_TEST(sv3[3].second == 4);\r\n                DLIB_TEST(sv3[0].first == 0);\r\n                DLIB_TEST(sv3[1].first == 1);\r\n                DLIB_TEST(sv3[2].first == 2);\r\n                DLIB_TEST(sv3[3].first == 3);\r\n\r\n                assign(sv3, sv);\r\n                DLIB_TEST(sv3.size() == 2);\r\n                DLIB_TEST(sv3[0].second == 1);\r\n                DLIB_TEST(sv3[1].second == 1);\r\n                DLIB_TEST(sv3[0].first == 0);\r\n                DLIB_TEST(sv3[1].first == 3);\r\n\r\n                sv.clear();\r\n                assign(sv, sv3);\r\n                DLIB_TEST(sv.size() == 2);\r\n                DLIB_TEST(sv[0] == 1);\r\n                DLIB_TEST(sv[1] == 0);\r\n                DLIB_TEST(sv[2] == 0);\r\n                DLIB_TEST(sv[3] == 1);\r\n\r\n            }\r\n        }\r\n    } a;\r\n\r\n}\r\n\r\n\r\n\r\n", "meta": {"hexsha": "0358ecdefe27d8e1bbfaf0e0e7812db9de06e60f", "size": 12256, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dlib/test/svm_c_linear.cpp", "max_stars_repo_name": "ckproc/dlib-19.7", "max_stars_repo_head_hexsha": "0ca40f5e85de2436e557bee9a805d3987d2d9507", "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": "dlib/test/svm_c_linear.cpp", "max_issues_repo_name": "ckproc/dlib-19.7", "max_issues_repo_head_hexsha": "0ca40f5e85de2436e557bee9a805d3987d2d9507", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2018-02-27T15:44:25.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-28T01:26:03.000Z", "max_forks_repo_path": "dlib/test/svm_c_linear.cpp", "max_forks_repo_name": "ckproc/dlib-19.7", "max_forks_repo_head_hexsha": "0ca40f5e85de2436e557bee9a805d3987d2d9507", "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.1857506361, "max_line_length": 115, "alphanum_fraction": 0.4887402089, "num_tokens": 3210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.493571833741359}}
{"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 \"eigen_tools.h\"\n#include <Eigen/Dense>\n#include \"Transformable.h\"\n#include <vector>\n#include <set>\n#include <algorithm>\n#include <iomanip>\n#include <string>\n#include <cstdio>\n#include <cstdint>\n\n\nusing namespace Eigen;\nusing namespace std;\n\n\nvoid get_MatrixXd_row_abs_max(const MatrixXd &m, int row, int *max_col, double *max_val)\n{\n\tsize_t nrows = m.rows();\n\tsize_t ncols = m.cols();\n\tassert(row <= nrows);\n\n\t*max_col = -999;\n\t*max_val = 0;\n\tfor (size_t icol=0; icol<ncols; ++icol)\n\t{\n\t\tif(abs(m(row,icol)) > abs(*max_val))\n\t\t{\n\t\t\t*max_col = icol;\n\t\t\t*max_val = m(row,icol);\n\t\t}\n\t}\n}\n\nVectorXd stlvec_2_egienvec(const std::vector<double> &stl_vec)\n{\n\tsize_t len = stl_vec.size();\n\tVectorXd la_vec(len);\n\tfor (size_t i=0; i<len; ++i)\n\t{\n\t\tla_vec(i) = stl_vec[i];\n\t}\n\treturn la_vec;\n}\n\nvector<double> egienvec_2_stlvec(const VectorXd &eigen_vec)\n{\n\tsize_t len = eigen_vec.size();\n\tvector<double> stl_vec;\n\tstl_vec.reserve(len);\n\tfor (size_t i = 0; i<len; ++i)\n\t{\n\t\tstl_vec.push_back(eigen_vec(i));\n\t}\n\treturn stl_vec;\n}\n\n\nEigen::VectorXd transformable_2_egien_vec(const Transformable &data, vector<string> oredered_names)\n{\n\tsize_t len = oredered_names.size();\n\tVectorXd new_vec(len);\n\tauto data_end = data.end();\n\n\tfor (size_t i = 0; i<len; ++i)\n\t{\n\t\tconst auto &it = data.find(oredered_names[i]);\n\t\tassert(it != data_end);\n\t\tnew_vec(i) = it->second;\n\t}\n\treturn new_vec;\n}\n\n\nvoid matrix_del_cols(Eigen::SparseMatrix<double> &mat, const vector<size_t> &col_id_vec)\n{\n\tif (!col_id_vec.empty())\n\t{\n\t\tsize_t ncols = mat.cols();\n\t\tset<int> del_col_set(col_id_vec.begin(), col_id_vec.end());\n\n\t\tstd::vector<Eigen::Triplet<int> > triplet_list;\n\n\t\t// add rows to be retained to the beginning of the  permuatation matrix\n\t\tint icol_new = 0;\n\t\tint n_col_save = 0;\n\t\tfor (int icol_old = 0; icol_old<ncols; ++icol_old)\n\t\t{\n\t\t\tif (del_col_set.find(icol_old) == del_col_set.end())\n\t\t\t{\n\t\t\t\ttriplet_list.push_back(Eigen::Triplet<int>(icol_old, icol_new, 1));\n\t\t\t\t++icol_new;\n\t\t\t\t++n_col_save;\n\t\t\t}\n\t\t}\n\t\t// add rows to be deleted to end to permuatation matrix\n\t\tfor (int icol_old :  col_id_vec)\n\t\t{\n\t\t\ttriplet_list.push_back(Eigen::Triplet<int>(icol_old, icol_new, 1));\n\t\t\t++icol_new;\n\t\t}\n\t\tEigen::SparseMatrix<double> perm_sparse_matrix(ncols, ncols);\n\t\tperm_sparse_matrix.setZero();\n\t\tperm_sparse_matrix.setFromTriplets(triplet_list.begin(), triplet_list.end());\n\t\tEigen::SparseMatrix<double> new_matrix = mat * perm_sparse_matrix;\n\t\tmat = new_matrix.leftCols(n_col_save);\n\t}\n}\n\nEigen::SparseMatrix<double> get_diag_matrix(const Eigen::SparseMatrix<double> &mat)\n{\n\tauto  ncols = mat.cols();\n\tauto  nrows = mat.rows();\n\n\tassert(ncols == nrows);\n\tif (nrows != ncols)\n\t{\n\t\tPestError(\"Error in get_diag_matrix: Can not return the diagonal of a non-square matrix\");\n\t}\n\tVectorXd diag_vec = mat.diagonal();\n\tstd::vector<Eigen::Triplet<double> > triplet_list;\n\ttriplet_list.reserve(nrows);\n\tfor (size_t i = 0; i<nrows; ++i)\n\t{\n\t\ttriplet_list.push_back(Eigen::Triplet<double>(i, i, diag_vec(i)));\n\t}\n\n\tEigen::SparseMatrix<double> diag_matrix;\n\tdiag_matrix.resize(nrows, ncols);\n\tdiag_matrix.setZero();\n\tdiag_matrix.setFromTriplets(triplet_list.begin(), triplet_list.end());\n\treturn diag_matrix;\n}\n\nvoid print(const MatrixXd &mat, ostream & fout)\n{\n\tsize_t nrows = mat.rows();\n\tsize_t ncols = mat.cols();\n\n\tfor (size_t i=0; i<nrows; ++i)\n\t{\n\t\tfor (size_t j=0; j<ncols; ++j)\n\t\t{\n\t\t\tfout << mat(i,j);\n\t\t\tif (j < ncols-1) {fout << \", \";}\n\t\t}\n\t\tfout << endl;\n\t}\n\n}\n\nvoid print(const MatrixXd &mat, ostream & fout, int n_per_line)\n{\n\tsize_t nrows = mat.rows();\n\tsize_t ncols = mat.cols();\n\n\tfor (size_t i=0; i<nrows; ++i)\n\t{\n\t\tfor (size_t j=0; j<ncols; ++j)\n\t\t{\n\t\t\tfout << setw(15) << setiosflags(ios::right) << mat(i,j);\n\t\t\tif ((j+1) % (n_per_line) == 0 || j+1==ncols)\n\t\t\t{\n\t\t\t\tfout << '\\n';\n\t\t\t}\n\t\t}\n\t\tfout << endl;\n\t}\n\n}\n\nvoid print(const VectorXd &vec, ostream & fout, int n_per_line)\n{\n\tsize_t n = vec.size();\n\n\tfor (size_t i=0; i<n; ++i)\n\t{\n\t\tfout << showpoint << setw(15) << setiosflags(ios::right) << vec(i);\n\t\t\tif ((i+1) % (n_per_line) == 0 || i+1==n)\n\t\t{\n\t\t\tfout << '\\n';\n\t\t}\n\n\t}\n}\n\nbool save_triplets_bin(const SparseMatrix<double> &mat, ostream &fout)\n{\n\tint32_t xyn[3] = { mat.rows(), mat.cols(), mat.nonZeros() };\n\tfout.write((char*)xyn, sizeof(xyn));\n\n\tfor (int k = 0; k < mat.outerSize(); ++k)\n\t{\n\t\tSparseMatrix<double>::InnerIterator it(mat, k);\n\t\tfor (; it; ++it)\n\t\t{\n\t\t\tint32_t rc[2] = { it.row(), it.col() };\n\t\t\tfout.write((char*)rc, sizeof(rc));\n\t\t\tdouble v = it.value();\n\t\t\tfout.write((char*)&v, sizeof(v));\n\t\t}\n\t}\n\treturn true;\n}\n\nbool save_vector_bin(const VectorXd &vec, ostream &fout)\n{\n\tint32_t size = vec.size();\n\t//vector<double> buf = egienvec_2_stlvec(vec);\n\tfout.write((char*)&size, sizeof(size));\n\tfout.write((char*)vec.data(), sizeof(double)*size);\n\treturn true;\n}\n\nbool load_vector_bin(VectorXd &vec, istream &fin)\n{\n\tint32_t size = 0;\n\tfin.read((char*)&size, sizeof(size));\n\tvec.resize(size);\n\tfin.read((char*)vec.data(), sizeof(double)*size);\n\treturn true;\n}\n\nbool load_triplets_bin(SparseMatrix<double> &a, istream &fin)\n{\n\tint32_t xyn[3];\n\tfin.read((char*)xyn, sizeof(xyn));\n\ta.resize(xyn[0], xyn[1]);\n\tvector<Triplet<double>> trips(xyn[2]);\n\n\tfor (int k = 0; k < trips.size(); ++k)\n\t{\n\t\tint32_t rc[2];\n\t\tfin.read((char*)rc, sizeof(rc));\n\t\tdouble v;\n\t\tfin.read((char*)&v, sizeof(v));\n\n\t\ttrips[k] = Triplet<double>(rc[0], rc[1], v);\n\t}\n\ta.setFromTriplets(trips.begin(), trips.end());\n\treturn true;\n}\n\nEigen::SparseMatrix<double> eigenvec_2_diagsparse(Eigen::VectorXd vec)\n{\n\tvector<Eigen::Triplet<double>> triplet_list;\n\tfor (int i = 0; i != vec.size(); i++)\n\t\ttriplet_list.push_back(Eigen::Triplet<double>(i, i, vec[i]));\n\tEigen::SparseMatrix<double> mat(vec.size(), vec.size());\n\tmat.setZero();\n\tmat.setFromTriplets(triplet_list.begin(), triplet_list.end());\n\treturn mat;\n\n\n\n}\n", "meta": {"hexsha": "7467e40aedcade2057d81639eb545aaeabbdb886", "size": 6442, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/src_pestpp/libs/pestpp_common/eigen_tools.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/eigen_tools.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/eigen_tools.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": 23.4254545455, "max_line_length": 99, "alphanum_fraction": 0.6667184104, "num_tokens": 1996, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.49357183283248557}}
{"text": "#include \"hexadecimal.h\"\n#define BOOST_TEST_MAIN\n#include <boost/test/unit_test.hpp>\n\nBOOST_AUTO_TEST_CASE(hex_1_is_decimal_1)\n{\n    BOOST_REQUIRE_EQUAL(0x1, hexadecimal::convert(\"1\"));\n}\n\n#if defined(EXERCISM_RUN_ALL_TESTS)\nBOOST_AUTO_TEST_CASE(hex_c_is_decimal_12)\n{\n    BOOST_REQUIRE_EQUAL(0xc, hexadecimal::convert(\"c\"));\n}\n\nBOOST_AUTO_TEST_CASE(hex_10_is_decimal_16)\n{\n    BOOST_REQUIRE_EQUAL(0x10, hexadecimal::convert(\"10\"));\n}\n\nBOOST_AUTO_TEST_CASE(hex_af_is_decimal_175)\n{\n    BOOST_REQUIRE_EQUAL(0xaf, hexadecimal::convert(\"af\"));\n}\n\nBOOST_AUTO_TEST_CASE(hex_100_is_decimal_256)\n{\n    BOOST_REQUIRE_EQUAL(0x100, hexadecimal::convert(\"100\"));\n}\n\nBOOST_AUTO_TEST_CASE(hex_19ace_is_decimal_105166)\n{\n    BOOST_REQUIRE_EQUAL(0x19ace, hexadecimal::convert(\"19ace\"));\n}\n\nBOOST_AUTO_TEST_CASE(invalid_hex_is_decimal_0)\n{\n    BOOST_REQUIRE_EQUAL(0, hexadecimal::convert(\"carrot\"));\n}\n\nBOOST_AUTO_TEST_CASE(black)\n{\n    BOOST_REQUIRE_EQUAL(0x000000, hexadecimal::convert(\"000000\"));\n}\n\nBOOST_AUTO_TEST_CASE(white)\n{\n    BOOST_REQUIRE_EQUAL(0xffffff, hexadecimal::convert(\"ffffff\"));\n}\n\nBOOST_AUTO_TEST_CASE(yellow)\n{\n    BOOST_REQUIRE_EQUAL(0xffff00, hexadecimal::convert(\"ffff00\"));\n}\n#endif\n", "meta": {"hexsha": "a774f4054673a895c6993f1389e1cd6518e522bb", "size": 1194, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "exercises/hexadecimal/hexadecimal_test.cpp", "max_stars_repo_name": "menaczar/cpp", "max_stars_repo_head_hexsha": "6e2a2693ca7a6d609396bd61699baf73f6087247", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-08-22T18:28:20.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-22T18:28:20.000Z", "max_issues_repo_path": "exercises/hexadecimal/hexadecimal_test.cpp", "max_issues_repo_name": "menaczar/cpp", "max_issues_repo_head_hexsha": "6e2a2693ca7a6d609396bd61699baf73f6087247", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "exercises/hexadecimal/hexadecimal_test.cpp", "max_forks_repo_name": "menaczar/cpp", "max_forks_repo_head_hexsha": "6e2a2693ca7a6d609396bd61699baf73f6087247", "max_forks_repo_licenses": ["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.3214285714, "max_line_length": 66, "alphanum_fraction": 0.7788944724, "num_tokens": 306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.4935718289214937}}
{"text": "#pragma once\n#include <algorithm>\n\n#include <boost/variant/static_visitor.hpp>\n#include <boost/format.hpp>\n\n#include \"expression.hpp\"\n#include \"visitors.hpp\"\n\nnamespace metaSMT {\n  namespace expression {\n    inline logic_expression simplify( logic_expression e );\n\n    struct simplify_visitor : public boost::static_visitor< logic_expression > {\n      simplify_visitor() {}\n\n      logic_expression operator() ( bool b ) const {\n        return b;\n      }\n\n      logic_expression operator() ( logic::predicate p ) const {\n        return p;\n      }\n\n      logic_expression operator() ( unary_expression<logic_tag, predtags::not_tag> expr ) const {\n        logic_expression arg = simplify(expr.expr);\n\n        if ( has_type<bool>( arg ) ) {\n          bool b = boost::get<bool>( arg );\n          return !b;\n        }\n\n        if ( has_type< unary_expression<logic_tag, predtags::not_tag> >(arg) ) {\n          unary_expression<logic_tag, predtags::not_tag> not_arg = boost::get<unary_expression<logic_tag, predtags::not_tag> >(arg);\n          return simplify(not_arg.expr);\n        }\n\n        return unary_expression<logic_tag, predtags::not_tag>(arg);\n      }\n\n      logic_expression operator() ( binary_expression<logic_tag, predtags::equal_tag> expr ) const {\n        logic_expression lhs = simplify(expr.left);\n        logic_expression rhs = simplify(expr.right);\n\n        // ( expr e == expr e ) ==> true\n        if ( lhs == rhs ) {\n          return true;\n        }\n\n        return binary_expression<logic_tag, predtags::equal_tag>(lhs, rhs);\n      }\n\n      logic_expression operator() ( binary_expression<logic_tag, predtags::nequal_tag> expr ) const {\n        logic_expression lhs = simplify(expr.left);\n        logic_expression rhs = simplify(expr.right);\n\n        // ( expr e != expr e ) ==> false\n        if ( lhs == rhs ) {\n          return false;\n        }\n\n        return binary_expression<logic_tag, predtags::nequal_tag>(lhs, rhs);\n      }\n\n      logic_expression operator() ( binary_expression<logic_tag, predtags::implies_tag> expr ) const {\n        logic_expression lhs = simplify(expr.left);\n        logic_expression rhs = simplify(expr.right);\n\n        // true  -> predicate p ==> predicate p\n        // false -> predicate p ==> true\n        if ( has_type<bool>( lhs ) ) {\n          bool b = boost::get<bool>(lhs);\n          if ( b ) {\n            return rhs;\n          } else {\n            return true;\n          }\n        }\n\n        // predicate p --> true  ==> true\n        // predicate p --> false ==> !(predicate p)\n        if ( has_type< bool >( rhs ) ) {\n          bool b = boost::get<bool>( rhs );\n          if ( b ) {\n            return true;\n          } else {\n            return unary_expression<logic_tag, predtags::not_tag>(lhs);\n          }\n        }\n\n        // ( expr e -> expr e ) ==> true\n        if ( lhs == rhs ) {\n          return true;\n        }\n\n        return binary_expression<logic_tag, predtags::implies_tag>(lhs, rhs);\n      }\n\n      logic_expression operator() ( nary_expression<logic_tag, predtags::and_tag> expr ) const {\n        typedef nary_expression<logic_tag, predtags::and_tag> nary_and;\n        nary_and::ContainerType v;\n        for (nary_and::ContainerType::const_iterator it = expr.begin(), ie = expr.end();\n             it != ie; ++it) {\n          logic_expression e = simplify( *it );\n          if ( has_type< bool >( e ) ) {\n            bool b = boost::get<bool>( e );\n            if ( b ) {\n              // skip trues\n              continue;\n            } else {\n              // simplify to false\n              return false;\n            }\n          }\n\n          // merge with child\n          if ( has_type<nary_and>(e) ) {\n            nary_and child = boost::get<nary_and>(e);\n            v.insert( v.end(), child.begin(), child.end() );\n            continue;\n          }\n\n          v.push_back( e );\n        }\n\n        unsigned const size = v.size();\n        if (size == 0) {\n          return true;\n        }\n        else if (size == 1) {\n          return v[0];\n        }\n\n        return nary_and(v);\n      }\n\n      logic_expression operator() ( nary_expression<logic_tag, predtags::or_tag> expr ) const {\n        typedef nary_expression<logic_tag, predtags::or_tag> nary_or;\n        nary_or::ContainerType v;\n        for (nary_or::ContainerType::const_iterator it = expr.begin(), ie = expr.end();\n             it != ie; ++it) {\n          logic_expression e = simplify( *it );\n          if ( has_type< bool >( e ) ) {\n            bool b = boost::get<bool>( e );\n            if ( b ) {\n              // simplify to true\n              return true;\n            } else {\n              // skip falses\n              continue;\n            }\n          }\n\n          // merge with child\n          if ( has_type<nary_or>(e) ) {\n            nary_or child = boost::get<nary_or>(e);\n            v.insert( v.end(), child.begin(), child.end() );\n            continue;\n          }\n\n          v.push_back( e );\n        }\n\n        unsigned const size = v.size();\n        if (size == 0) {\n          return false;\n        }\n        else if (size == 1) {\n          return v[0];\n        }\n\n        return nary_or(v);\n      }\n\n      logic_expression operator() ( binary_expression<logic_tag, predtags::nand_tag> expr ) const {\n        logic_expression lhs = simplify(expr.left);\n        logic_expression rhs = simplify(expr.right);\n\n        // !( true  /\\ expr ) ==> !(expr)\n        // !( false /\\ expr ) ==> true\n        if ( has_type< bool >( lhs ) ) {\n          bool b = boost::get<bool>( lhs );\n          if ( b ) {\n            return simplify( unary_expression<logic_tag, predtags::not_tag>(rhs) );\n          } else {\n            return true;\n          }\n        }\n\n        // !( expr /\\ true  ) ==> !(expr)\n        // !( expr /\\ false ) ==> true\n        if ( has_type< bool >( rhs ) ) {\n          bool b = boost::get<bool>( rhs );\n          if ( b ) {\n            return simplify( unary_expression<logic_tag, predtags::not_tag>(lhs) );\n          } else {\n            return true;\n          }\n        }\n\n        // !( expr e /\\ expr e ) ==> !( expr e )\n        if ( lhs == rhs ) {\n          return simplify( unary_expression<logic_tag, predtags::not_tag>(lhs) );\n        }\n\n        return binary_expression<logic_tag, predtags::nand_tag>(lhs, rhs);\n      }\n\n      logic_expression operator() ( binary_expression<logic_tag, predtags::nor_tag> expr ) const {\n        logic_expression lhs = simplify(expr.left);\n        logic_expression rhs = simplify(expr.right);\n\n        // !( true  \\/ expr ) ==> false\n        // !( false \\/ expr ) ==> !(expr)\n        if ( has_type< bool >( lhs ) ) {\n          bool b = boost::get<bool>( lhs );\n          if ( b ) {\n            return false;\n          } else {\n            return simplify( unary_expression<logic_tag, predtags::not_tag>(rhs) );\n          }\n        }\n\n        // !( expr \\/ true  ) ==> false\n        // !( expr \\/ false ) ==> !(expr)\n        if ( has_type< bool >( rhs ) ) {\n          bool b = boost::get<bool>( rhs );\n          if ( b ) {\n            return true;\n          } else {\n            return simplify( unary_expression<logic_tag, predtags::not_tag>(lhs) );\n          }\n        }\n\n        // !( predicate p \\/ predicate p ) ==> !( predicate p )\n        if ( lhs == rhs ) {\n          return simplify( unary_expression<logic_tag, predtags::not_tag>(lhs) );\n        }\n\n        return binary_expression<logic_tag, predtags::nor_tag>(lhs, rhs);\n      }\n\n      logic_expression operator() ( binary_expression<logic_tag, predtags::xor_tag> expr ) const {\n        logic_expression lhs = simplify(expr.left);\n        logic_expression rhs = simplify(expr.right);\n\n        // ( true  xor expr ) ==> !(expr)\n        // ( false xor expr ) ==> expr\n        if ( has_type< bool >( lhs ) ) {\n          bool b = boost::get<bool>( lhs );\n          if ( b ) {\n            return simplify( unary_expression<logic_tag, predtags::not_tag>(rhs) );\n          } else {\n            return rhs;\n          }\n        }\n\n        // ( expr xor true  ) ==> !(expr)\n        // ( expr xor false ) ==> expr\n        if ( has_type< bool >( rhs ) ) {\n          bool b = boost::get<bool>( rhs );\n          if ( b ) {\n            return simplify( unary_expression<logic_tag, predtags::not_tag>(lhs) );\n          } else {\n            return lhs;\n          }\n        }\n\n        // ( expr e xor expr e ) ==> false\n        if ( lhs == rhs ) {\n          return false;\n        }\n\n        return binary_expression<logic_tag, predtags::xor_tag>(lhs, rhs);\n      }\n\n      logic_expression operator() ( binary_expression<logic_tag, predtags::xnor_tag> expr ) const {\n        logic_expression lhs = simplify(expr.left);\n        logic_expression rhs = simplify(expr.right);\n\n        // !( true  xor expr ) ==> expr\n        // !( false xor expr ) ==> !(expr)\n        if ( has_type< bool >( lhs ) ) {\n          bool b = boost::get<bool>( lhs );\n          if ( b ) {\n            return rhs;\n          } else {\n            return simplify( unary_expression<logic_tag, predtags::not_tag>(rhs) );\n          }\n        }\n\n        // !( expr xor true  ) ==> expr\n        // !( expr xor false ) ==> !(expr)\n        if ( has_type< bool >( rhs ) ) {\n          bool b = boost::get<bool>( rhs );\n          if ( b ) {\n            return lhs;\n          } else {\n            return simplify( unary_expression<logic_tag, predtags::not_tag>(lhs) );\n          }\n        }\n\n        // !( expr e xor expr e ) ==> true\n        if ( lhs == rhs ) {\n          return true;\n        }\n\n        return binary_expression<logic_tag, predtags::xnor_tag>(lhs, rhs);\n      }\n\n      logic_expression operator() ( ternary_expression<logic_tag, predtags::ite_tag> expr ) const {\n        logic_expression cond = simplify(expr.expr1);\n        logic_expression true_expr = simplify(expr.expr2);\n        logic_expression false_expr = simplify(expr.expr3);\n\n        // ite( true,  t_expr, f_expr) ==> t_expr\n        // ite( false, t_expr, f_expr) ==> f_expr\n        if ( has_type< bool >( cond ) ) {\n          bool b = boost::get<bool>( cond );\n          if ( b ) {\n            return true_expr;\n          } else {\n            return false_expr;\n          }\n        }\n\n        // ite( cond, expr, expr ) ==> expr\n        if ( true_expr == false_expr ) {\n          return true_expr;\n        }\n\n        return ternary_expression<logic_tag, predtags::ite_tag>(cond, true_expr, false_expr);\n      }\n\n      logic_expression operator() ( bit0_const b ) const {\n        return b;\n      }\n\n      logic_expression operator() ( bit1_const b ) const {\n        return b;\n      }\n\n      template < typename OpTag >\n      logic_expression operator() ( bv_const<OpTag> const &expr ) const {\n        if (expr.width == 1) {\n          if (expr.value == 0) {\n            return logic::QF_BV::bit0;\n          }\n          else {\n            return logic::QF_BV::bit1;\n          }\n        }\n        return expr;\n      }\n\n      logic_expression operator() ( logic::QF_BV::bitvector bv ) const {\n        return bv;\n      }\n\n      logic_expression operator() ( unary_expression<bv_tag, bvtags::bvnot_tag> expr ) const {\n        logic_expression arg = simplify(expr.expr);\n        // not( bit0 ) ==> bit1\n        if ( has_type< bit0_const >( arg ) ) {\n          return logic::QF_BV::bit1;\n        }\n        // not( bit1 ) ==> bit0\n        else if ( has_type< bit1_const >( arg ) ) {\n          return logic::QF_BV::bit0;\n        }\n        else if ( has_type< unary_expression<bv_tag, bvtags::bvnot_tag> >(arg) ) {\n          unary_expression<bv_tag, bvtags::bvnot_tag> not_arg = boost::get<unary_expression<bv_tag, bvtags::bvnot_tag> >(arg);\n          return simplify(not_arg.expr);\n        }\n\n        return unary_expression<bv_tag, bvtags::bvnot_tag>(arg);\n      }\n\n      logic_expression operator() ( unary_expression<bv_tag, bvtags::bvneg_tag> expr ) const {\n        return expr;\n      }\n\n      logic_expression operator() ( binary_expression<bv_tag, bvtags::bvand_tag> expr ) const {\n        logic_expression lhs = simplify(expr.left);\n        logic_expression rhs = simplify(expr.right);\n\n        // ( expr e /\\ expr e ) ==> expr e\n        if ( lhs == rhs ) {\n          return lhs;\n        }\n\n        if ( has_type< binary_expression<bv_tag, bvtags::bvand_tag> >(lhs) ) {\n          // TODO\n        }\n\n        if ( has_type< binary_expression<bv_tag, bvtags::bvand_tag> >(rhs) ) {\n          // TODO\n        }\n\n        return binary_expression<bv_tag, bvtags::bvand_tag>(lhs, rhs);\n      }\n\n      logic_expression operator() ( binary_expression<bv_tag, bvtags::bvnand_tag> expr ) const {\n        logic_expression lhs = simplify(expr.left);\n        logic_expression rhs = simplify(expr.right);\n\n        // !( expr e /\\ expr e ) ==> !(expr e)\n        if ( lhs == rhs ) {\n          return unary_expression<bv_tag, bvtags::bvnot_tag>(lhs);\n        }\n\n        return binary_expression<bv_tag, bvtags::bvnand_tag>(lhs, rhs);\n      }\n\n      logic_expression operator() ( binary_expression<bv_tag, bvtags::bvor_tag> expr ) const {\n        logic_expression lhs = simplify(expr.left);\n        logic_expression rhs = simplify(expr.right);\n\n        // ( expr e \\/ expr e ) ==> expr e\n        if ( lhs == rhs ) {\n          return lhs;\n        }\n\n        return binary_expression<bv_tag, bvtags::bvor_tag>(lhs, rhs);\n      }\n\n      logic_expression operator() ( binary_expression<bv_tag, bvtags::bvnor_tag> expr ) const {\n        logic_expression lhs = simplify(expr.left);\n        logic_expression rhs = simplify(expr.right);\n\n        // !( expr e \\/ expr e ) ==> !( expr e )\n        if ( lhs == rhs ) {\n          return unary_expression<bv_tag, bvtags::bvnot_tag>(lhs);\n        }\n\n        return binary_expression<bv_tag, bvtags::bvnor_tag>(lhs, rhs);\n      }\n\n      logic_expression operator() ( binary_expression<bv_tag, bvtags::bvxor_tag> expr ) const {\n        logic_expression lhs = simplify(expr.left);\n        logic_expression rhs = simplify(expr.right);\n\n        return binary_expression<bv_tag, bvtags::bvxor_tag>(lhs, rhs);\n      }\n\n      logic_expression operator() ( binary_expression<bv_tag, bvtags::bvxnor_tag> expr ) const {\n        logic_expression lhs = simplify(expr.left);\n        logic_expression rhs = simplify(expr.right);\n\n        return binary_expression<bv_tag, bvtags::bvxnor_tag>(lhs, rhs);\n      }\n\n      logic_expression operator() ( binary_expression<bv_tag, bvtags::bvshl_tag> expr ) const {\n        logic_expression lhs = simplify(expr.left);\n        logic_expression rhs = simplify(expr.right);\n\n        // expr e << 0 ==> expr e\n        if ( has_type< bit0_const >(rhs) ) {\n          return lhs;\n        }\n\n        return binary_expression<bv_tag, bvtags::bvshl_tag>(lhs, rhs);\n      }\n\n      logic_expression operator() ( binary_expression<bv_tag, bvtags::bvshr_tag> expr ) const {\n        logic_expression lhs = simplify(expr.left);\n        logic_expression rhs = simplify(expr.right);\n\n        // expr e >> 0 ==> expr e\n        if ( has_type< bit0_const >(rhs) ) {\n          return lhs;\n        }\n\n        return binary_expression<bv_tag, bvtags::bvshr_tag>(lhs, rhs);\n      }\n\n      logic_expression operator() ( binary_expression<bv_tag, bvtags::bvashr_tag> expr ) const {\n        logic_expression lhs = simplify(expr.left);\n        logic_expression rhs = simplify(expr.right);\n\n        // expr e >> 0 ==> expr e\n        if ( has_type< bit0_const >(rhs) ) {\n          return lhs;\n        }\n\n        return binary_expression<bv_tag, bvtags::bvashr_tag>(lhs, rhs);\n      }\n\n      logic_expression operator() ( binary_expression<bv_tag, bvtags::bvadd_tag> expr ) const {\n        logic_expression lhs = simplify(expr.left);\n        logic_expression rhs = simplify(expr.right);\n\n        // expr e + 0 ==> expr e\n        if ( has_const_value(rhs, 0) ) {\n          return lhs;\n        }\n\n        // 0 + expr e ==> expr e\n        if ( has_const_value(lhs, 0) ) {\n          return rhs;\n        }\n\n        return binary_expression<bv_tag, bvtags::bvadd_tag>(lhs, rhs);\n      }\n\n      logic_expression operator() ( binary_expression<bv_tag, bvtags::bvsub_tag> expr ) const {\n        logic_expression lhs = simplify(expr.left);\n        logic_expression rhs = simplify(expr.right);\n\n        // expr e - 0 ==> expr e\n        if ( has_const_value(rhs, 0) ) {\n          return lhs;\n        }\n\n        // 0 - expr e ==> expr -e\n        if ( has_const_value(lhs, 0) ) {\n          return unary_expression<bv_tag, bvtags::bvneg_tag>(rhs);\n        }\n\n        return binary_expression<bv_tag, bvtags::bvsub_tag>(lhs, rhs);\n      }\n\n      logic_expression operator() ( binary_expression<bv_tag, bvtags::bvmul_tag> expr ) const {\n        logic_expression lhs = simplify(expr.left);\n        logic_expression rhs = simplify(expr.right);\n\n        // TODO: expr e * 0 ==> 0\n        // TODO: 0 * expr e ==> 0\n\n        return binary_expression<bv_tag, bvtags::bvmul_tag>(lhs, rhs);\n      }\n\n      logic_expression operator() ( binary_expression<bv_tag, bvtags::bvsrem_tag> expr ) const {\n        logic_expression lhs = simplify(expr.left);\n        logic_expression rhs = simplify(expr.right);\n\n        return binary_expression<bv_tag, bvtags::bvsrem_tag>(lhs, rhs);\n      }\n\n      logic_expression operator() ( binary_expression<bv_tag, bvtags::bvsdiv_tag> expr ) const {\n        logic_expression lhs = simplify(expr.left);\n        logic_expression rhs = simplify(expr.right);\n\n        return binary_expression<bv_tag, bvtags::bvsdiv_tag>(lhs, rhs);\n      }\n\n      logic_expression operator() ( binary_expression<bv_tag, bvtags::bvurem_tag> expr ) const {\n        logic_expression lhs = simplify(expr.left);\n        logic_expression rhs = simplify(expr.right);\n\n        return binary_expression<bv_tag, bvtags::bvurem_tag>(lhs, rhs);\n      }\n\n      logic_expression operator() ( binary_expression<bv_tag, bvtags::bvudiv_tag> expr ) const {\n        logic_expression lhs = simplify(expr.left);\n        logic_expression rhs = simplify(expr.right);\n\n        return binary_expression<bv_tag, bvtags::bvudiv_tag>(lhs, rhs);\n      }\n\n      logic_expression operator() ( binary_expression<bv_tag, bvtags::bvcomp_tag> expr ) const {\n        logic_expression lhs = simplify(expr.left);\n        logic_expression rhs = simplify(expr.right);\n\n        return binary_expression<bv_tag, bvtags::bvcomp_tag>(lhs, rhs);\n      }\n\n      logic_expression operator() ( binary_expression<logic_tag, bvtags::bvslt_tag> expr ) const {\n        logic_expression lhs = simplify(expr.left);\n        logic_expression rhs = simplify(expr.right);\n\n        return binary_expression<logic_tag, bvtags::bvslt_tag>(lhs, rhs);\n      }\n\n      logic_expression operator() ( binary_expression<logic_tag, bvtags::bvsgt_tag> expr ) const {\n        logic_expression lhs = simplify(expr.left);\n        logic_expression rhs = simplify(expr.right);\n\n        return binary_expression<logic_tag, bvtags::bvsgt_tag>(lhs, rhs);\n      }\n\n      logic_expression operator() ( binary_expression<logic_tag, bvtags::bvsle_tag> expr ) const {\n        logic_expression lhs = simplify(expr.left);\n        logic_expression rhs = simplify(expr.right);\n\n        return binary_expression<logic_tag, bvtags::bvsle_tag>(lhs, rhs);\n      }\n\n      logic_expression operator() ( binary_expression<logic_tag, bvtags::bvsge_tag> expr ) const {\n        logic_expression lhs = simplify(expr.left);\n        logic_expression rhs = simplify(expr.right);\n\n        return binary_expression<logic_tag, bvtags::bvsge_tag>(lhs, rhs);\n      }\n\n      logic_expression operator() ( binary_expression<logic_tag, bvtags::bvult_tag> expr ) const {\n        logic_expression lhs = simplify(expr.left);\n        logic_expression rhs = simplify(expr.right);\n\n        return binary_expression<logic_tag, bvtags::bvult_tag>(lhs, rhs);\n      }\n\n      logic_expression operator() ( binary_expression<logic_tag, bvtags::bvugt_tag> expr ) const {\n        logic_expression lhs = simplify(expr.left);\n        logic_expression rhs = simplify(expr.right);\n\n        return binary_expression<logic_tag, bvtags::bvugt_tag>(lhs, rhs);\n      }\n\n      logic_expression operator() ( binary_expression<logic_tag, bvtags::bvule_tag> expr ) const {\n        logic_expression lhs = simplify(expr.left);\n        logic_expression rhs = simplify(expr.right);\n\n        return binary_expression<logic_tag, bvtags::bvule_tag>(lhs, rhs);\n      }\n\n      logic_expression operator() ( binary_expression<logic_tag, bvtags::bvuge_tag> expr ) const {\n        logic_expression lhs = simplify(expr.left);\n        logic_expression rhs = simplify(expr.right);\n\n        return binary_expression<logic_tag, bvtags::bvuge_tag>(lhs, rhs);\n      }\n\n      logic_expression operator() ( binary_expression<bv_tag, bvtags::concat_tag> expr ) const {\n        return expr;\n      }\n\n      template < typename T >\n      logic_expression operator() ( extract_expression<T> expr ) const {\n        return expr;\n      }\n\n      template < typename T >\n      logic_expression operator() ( extend_expression<T> expr ) const {\n        return expr;\n      }\n\n      // Fallback\n      template < typename T >\n      logic_expression operator() ( T const & ) const {\n        assert(false);\n        return false;\n      }\n\n      boost::function<std::string(unsigned)> table_;\n    }; // simplify_visitor\n\n    inline logic_expression simplify( logic_expression e ) {\n      return boost::apply_visitor( simplify_visitor(), e );\n    }\n  } // expression\n} // metaSMT\n", "meta": {"hexsha": "2f4a10a9e1d242af688f970e48cd2c1949f15966", "size": 21387, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/metaSMT/expression/simplify.hpp", "max_stars_repo_name": "finnhaedicke/metaSMT", "max_stars_repo_head_hexsha": "949245da0bf0f3c042cb589aaea5d015e2ed9e9a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 33.0, "max_stars_repo_stars_event_min_datetime": "2015-04-09T14:14:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T08:55:58.000Z", "max_issues_repo_path": "src/metaSMT/expression/simplify.hpp", "max_issues_repo_name": "finnhaedicke/metaSMT", "max_issues_repo_head_hexsha": "949245da0bf0f3c042cb589aaea5d015e2ed9e9a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 28.0, "max_issues_repo_issues_event_min_datetime": "2015-03-13T14:21:33.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-02T07:59:34.000Z", "max_forks_repo_path": "src/metaSMT/expression/simplify.hpp", "max_forks_repo_name": "finnhaedicke/metaSMT", "max_forks_repo_head_hexsha": "949245da0bf0f3c042cb589aaea5d015e2ed9e9a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-04-22T18:10:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T12:44:12.000Z", "avg_line_length": 32.8021472393, "max_line_length": 132, "alphanum_fraction": 0.5676813017, "num_tokens": 5046, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.734119526900183, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.49357182410162836}}
{"text": "#include <fmt/format.h>\n#include <fmt/printf.h>\n\n#include <catch2/catch.hpp>\n\n#include <boost/filesystem.hpp>\n\n#include \"test_config.hpp\"\n#include \"embedded_python/functions.hpp\"\n\nTEST_CASE( \"Python function with one parameter and returning a pair can be called from c++\"\n           , \"[embedde_python]\" ) {\n \n  std::string const module_path( \"../tests/data/embedded_python/script.py\" );\n  std::string const function_name( \"function_1\" );   \n  CppPy::FunctionP1R2 function;\n  REQUIRE_NOTHROW( function.Load( module_path, function_name ) );\n  \n  double x{ 2.0 };\n  double x2{ 0.0 };\n  double x3{ 0.0 };\n  REQUIRE( true == function.Evaluate( x, x2, x3 ) );\n  REQUIRE( x*x == x2 );\n  REQUIRE( x*x2 == x3 );\n  \n  if( TestConfig::verbose ) {\n    fmt::print( \"\\nIf x = {} then x^2 = {} and x^3 = {}\\n\", x, x2, x3 );\n  }\n\n}\n\n", "meta": {"hexsha": "f754290e4a7f840ac4f1e1abf6a3fabe60e50afe", "size": 818, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/src/embedded_python.cpp", "max_stars_repo_name": "ahmades/ChemTools", "max_stars_repo_head_hexsha": "16c901dd1c7050d1219a9ada807adfe729c651d0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/src/embedded_python.cpp", "max_issues_repo_name": "ahmades/ChemTools", "max_issues_repo_head_hexsha": "16c901dd1c7050d1219a9ada807adfe729c651d0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 16.0, "max_issues_repo_issues_event_min_datetime": "2021-05-18T22:14:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-04T14:54:33.000Z", "max_forks_repo_path": "tests/src/embedded_python.cpp", "max_forks_repo_name": "ahmades/ChemTools", "max_forks_repo_head_hexsha": "16c901dd1c7050d1219a9ada807adfe729c651d0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.5625, "max_line_length": 91, "alphanum_fraction": 0.6393643032, "num_tokens": 244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.7341195152660688, "lm_q1q2_score": 0.4935718210995098}}
{"text": "/*\n@copyright Louis Dionne 2014\nDistributed under the Boost Software License, Version 1.0.\n(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n */\n\n#include <boost/hana/detail/assert.hpp>\n#include <boost/hana/integral.hpp>\n#include <boost/hana/list/instance.hpp>\n#include <boost/hana/maybe.hpp>\nusing namespace boost::hana;\n\n\nint main() {\n    //! [list]\n    BOOST_HANA_CONSTEXPR_LAMBDA auto half = [](auto x) {\n        return if_(x % int_<2> == int_<0>,\n            just(x / int_<2>),\n            nothing\n        );\n    };\n\n    BOOST_HANA_CONSTANT_ASSERT(\n        traverse<Maybe>(half, list(int_<2>, int_<4>, int_<6>))\n        ==\n        just(list(int_<1>, int_<2>, int_<3>))\n    );\n\n    BOOST_HANA_CONSTANT_ASSERT(\n        traverse<Maybe>(half, list(int_<2>, int_<3>, int_<6>))\n        ==\n        nothing\n    );\n    //! [list]\n\n    //! [maybe]\n    BOOST_HANA_CONSTEXPR_LAMBDA auto twice = [](auto x) {\n        return list(x, x);\n    };\n\n    BOOST_HANA_CONSTEXPR_ASSERT(\n        traverse<List>(twice, just('x')) == list(just('x'), just('x'))\n    );\n\n    BOOST_HANA_CONSTANT_ASSERT(\n        traverse<List>(twice, nothing) == list(nothing)\n    );\n    //! [maybe]\n}\n", "meta": {"hexsha": "cca2e7fb0bfd5e2a122fc887a354ce98d6b7f953", "size": 1190, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/traversable/traverse.cpp", "max_stars_repo_name": "rbock/hana", "max_stars_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-05-07T14:29:13.000Z", "max_stars_repo_stars_event_max_datetime": "2015-07-04T10:59:46.000Z", "max_issues_repo_path": "example/traversable/traverse.cpp", "max_issues_repo_name": "rbock/hana", "max_issues_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/traversable/traverse.cpp", "max_forks_repo_name": "rbock/hana", "max_forks_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.8, "max_line_length": 78, "alphanum_fraction": 0.5907563025, "num_tokens": 325, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195152660688, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.49357181627964464}}
{"text": "\n// BLAS level 2\n// symmetric & hermitian matrices\n\n//#define BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS \n//#define BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n\n#include <stddef.h>\n#include <iostream>\n#include <complex>\n#include <boost/numeric/bindings/atlas/cblas1.hpp>\n#include <boost/numeric/bindings/atlas/cblas2.hpp>\n#include <boost/numeric/bindings/traits/ublas_vector.hpp>\n#include <boost/numeric/bindings/traits/ublas_symmetric.hpp>\n#include <boost/numeric/bindings/traits/ublas_hermitian.hpp>\n#include \"utils.h\"\n\nnamespace ublas = boost::numeric::ublas;\nnamespace atlas = boost::numeric::bindings::atlas;\nnamespace traits = boost::numeric::bindings::traits;\n\nusing std::cout;\nusing std::cin;\nusing std::endl; \n\ntypedef double real_t; \ntypedef std::complex<real_t> cmplx_t; \n\ntypedef ublas::vector<real_t> vct_t;\ntypedef ublas::vector<cmplx_t> cvct_t;\n\ntypedef ublas::symmetric_matrix<\n  real_t, ublas::upper, ublas::column_major\n> ucsymm_t; \ntypedef ublas::symmetric_matrix<\n  real_t, ublas::lower, ublas::column_major\n> lcsymm_t; \ntypedef ublas::symmetric_matrix<\n  real_t, ublas::upper, ublas::row_major\n> ursymm_t; \ntypedef ublas::symmetric_matrix<\n  real_t, ublas::lower, ublas::row_major\n> lrsymm_t; \n\ntypedef ublas::hermitian_matrix<\n  cmplx_t, ublas::upper, ublas::column_major\n> ucherm_t; \ntypedef ublas::hermitian_matrix<\n  cmplx_t, ublas::lower, ublas::column_major\n> lcherm_t; \ntypedef ublas::hermitian_matrix<\n  cmplx_t, ublas::upper, ublas::row_major\n> urherm_t; \ntypedef ublas::hermitian_matrix<\n  cmplx_t, ublas::lower, ublas::row_major\n> lrherm_t; \n\ntypedef ublas::matrix<cmplx_t, ublas::column_major> cm_t; \ntypedef ublas::matrix<cmplx_t, ublas::row_major> rm_t; \n\ntypedef ublas::hermitian_adaptor<cm_t, ublas::upper> ucha_t; \ntypedef ublas::hermitian_adaptor<cm_t, ublas::lower> lcha_t; \ntypedef ublas::hermitian_adaptor<rm_t, ublas::upper> urha_t; \ntypedef ublas::hermitian_adaptor<rm_t, ublas::lower> lrha_t; \n\n\nint main() {\n  \n  cout << endl; \n\n  cout << \"symmetric matrix\" << endl << endl; \n  size_t n; \n  cout << \"n -> \"; \n  cin >> n;\n  cout << endl; \n\n  vct_t vx (n), vy (n); \n  atlas::set (1., vx); \n  print_v (vx, \"vx\"); \n\n  ucsymm_t ucs (n, n); \n  lcsymm_t lcs (n, n); \n  ursymm_t urs (n, n); \n  lrsymm_t lrs (n, n); \n\n  init_symm (ucs, 'u'); \n  init_symm (lcs, 'l'); \n  init_symm (urs, 'u'); \n  init_symm (lrs, 'l'); \n\n  print_m (ucs, \"ucs\");\n  cout << endl; \n  print_m_data (ucs, \"ucs\");\n  cout << endl; \n\n  print_m (lcs, \"lcs\");\n  cout << endl; \n  print_m_data (lcs, \"lcs\");\n  cout << endl; \n\n  print_m (urs, \"urs\");\n  cout << endl; \n  print_m_data (urs, \"urs\");\n  cout << endl; \n\n  print_m (lrs, \"lrs\");\n  cout << endl; \n  print_m_data (lrs, \"lrs\");\n  cout << endl; \n\n  // vy = symm vx \n  atlas::spmv (ucs, vx, vy); \n  print_v (vy, \"vy = ucs vx\"); \n  cout << endl; \n  atlas::spmv (1, lcs, vx, 0, vy); \n  print_v (vy, \"vy = lcs vx\"); \n  cout << endl; \n  atlas::spmv (1., urs, vx, 0., vy); \n  print_v (vy, \"vy = urs vx\"); \n  cout << endl; \n  atlas::spmv (1.0f, lrs, vx, 0.0f, vy); \n  print_v (vy, \"vy = lrs vx\"); \n  cout << endl; \n\n#ifdef F_COMPILATION_FAILURE\n\n  atlas::symv (ucs, vx, vy); \n  print_v (vy, \"vy = ucs vx\"); \n  cout << endl; \n\n  atlas::hpmv (lcs, vx, vy); \n  print_v (vy, \"vy = lcs vx\"); \n  cout << endl; \n\n  atlas::gemv (urs, vx, vy); \n  print_v (vy, \"vy = urs vx\"); \n  cout << endl; \n\n  atlas::spmv (cmplx_t (1., 0.), lrs, vx, cmplx_t (0., 0.), vy); \n  print_v (vy, \"vy = lrs vx\"); \n  cout << endl; \n\n#endif \n\n  ///////////////////////////////////////////////////\n\n  cout << endl << \"hermitian matrix\" << endl << endl; \n\n  size_t n2 = 3; \n\n  cvct_t cvx (n2), cvy (n2); \n  atlas::set (1., cvx); \n  print_v (cvx, \"cvx\"); \n  cout << endl; \n\n  ucherm_t uch (n2, n2); \n  uch (0, 0) = cmplx_t (3, 0); \n  uch (0, 1) = cmplx_t (2, -2); \n  uch (1, 1) = cmplx_t (3, 0); \n  uch (0, 2) = cmplx_t (1, -1); \n  uch (1, 2) = cmplx_t (2, 2); \n  uch (2, 2) = cmplx_t (3, 0); \n  print_m (uch, \"uch\"); \n  cout << endl; \n  print_m_data (uch, \"uch\"); \n  cout << endl; \n\n  lcherm_t lch (n2, n2); \n  lch = uch; \n  print_m (lch, \"lch\"); \n  cout << endl; \n  print_m_data (lch, \"lch\"); \n  cout << endl; \n\n  urherm_t urh (uch); \n  print_m (urh, \"urh\"); \n  cout << endl; \n  print_m_data (urh, \"urh\"); \n  cout << endl; \n\n  lrherm_t lrh (uch); \n  print_m (lrh, \"lrh\"); \n  cout << endl; \n  print_m_data (lrh, \"lrh\"); \n  cout << endl; \n\n  // cvy = herm cvx \n  atlas::hpmv (uch, cvx, cvy); \n  print_v (cvy, \"cvy = uch cvx\"); \n  cout << endl; \n  atlas::hpmv (1, lch, cvx, 0, cvy); \n  print_v (cvy, \"cvy = lch cvx\"); \n  cout << endl; \n  atlas::hpmv (1., urh, cvx, 0., cvy); \n  print_v (cvy, \"cvy = urh cvx\"); \n  cout << endl; \n  atlas::hpmv (cmplx_t (1., 0.), lrh, cvx, cmplx_t (0., 0.), cvy); \n  print_v (cvy, \"cvy = lrh cvx\"); \n  cout << endl; \n\n  ///////////////////////////////////////////////////\n\n  cout << endl << \"hermitian adaptor\" << endl << endl; \n\n  cm_t cm1 (n2, n2); \n  ucha_t ucha (cm1);\n  ucha = uch; \n  print_m (ucha, \"ucha\"); \n  cout << endl; \n  print_m_data (ucha, \"ucha\"); \n  cout << endl; \n\n  cm_t cm2 (n2, n2); \n  lcha_t lcha (cm2);\n  lcha = uch;  \n  print_m (lcha, \"lcha\"); \n  cout << endl; \n  print_m_data (lcha, \"lcha\"); \n  cout << endl; \n\n  rm_t rm1 (n2, n2); \n  urha_t urha (rm1); \n  urha = uch; \n  print_m (urha, \"urha\"); \n  cout << endl; \n  print_m_data (urha, \"urha\"); \n  cout << endl; \n\n  rm_t rm2 (n2, n2); \n  lrha_t lrha (rm2); \n  lrha = uch; \n  print_m (lrha, \"lrha\"); \n  cout << endl; \n  print_m_data (lrha, \"lrha\"); \n  cout << endl; \n\n  // cvy = herma cvx \n  atlas::hemv (ucha, cvx, cvy); \n  print_v (cvy, \"cvy = uch cvx\"); \n  cout << endl; \n  atlas::hemv (1, lcha, cvx, 0, cvy); \n  print_v (cvy, \"cvy = lch cvx\"); \n  cout << endl; \n  atlas::hemv (1., urha, cvx, 0., cvy); \n  print_v (cvy, \"cvy = urh cvx\"); \n  cout << endl; \n  atlas::hemv (cmplx_t (1., 0.), lrha, cvx, cmplx_t (0., 0.), cvy); \n  print_v (cvy, \"cvy = lrh cvx\"); \n  cout << endl; \n\n}\n", "meta": {"hexsha": "c84d1521415a4cf5c0e3930679120072940f1f27", "size": 5894, "ext": "cc", "lang": "C++", "max_stars_repo_path": "libs/numeric/bindings/atlas/ublas_symm2.cc", "max_stars_repo_name": "inducer/boost-numeric-bindings", "max_stars_repo_head_hexsha": "1f994e8a2e161cddb6577eacc76b7bc358701cbe", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-14T19:18:21.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-14T19:18:21.000Z", "max_issues_repo_path": "libs/numeric/bindings/atlas/ublas_symm2.cc", "max_issues_repo_name": "inducer/boost-numeric-bindings", "max_issues_repo_head_hexsha": "1f994e8a2e161cddb6577eacc76b7bc358701cbe", "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/numeric/bindings/atlas/ublas_symm2.cc", "max_forks_repo_name": "inducer/boost-numeric-bindings", "max_forks_repo_head_hexsha": "1f994e8a2e161cddb6577eacc76b7bc358701cbe", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-23T09:56:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-23T09:56:06.000Z", "avg_line_length": 23.3888888889, "max_line_length": 68, "alphanum_fraction": 0.5914489311, "num_tokens": 2331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195152660687, "lm_q2_score": 0.6723316926137811, "lm_q1q2_score": 0.49357181627964447}}
{"text": "#include <ext/iterator/zip_iterator.hpp>\n\n#include <algorithm>\n#include <iostream>\n#include <iomanip>\n#include <random>\n#include <boost/range/algorithm.hpp>\n#include <boost/range/algorithm_ext.hpp>\n#include <boost/test/unit_test.hpp>\n\nBOOST_AUTO_TEST_CASE(zip_iterator_sort_test)\n{\n\tusing namespace std;\n\tvector<int> data = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\n\tvector<short> short_data {data.begin(), data.end()};\n\tboost::reverse(data);\n\n\tauto first = ext::make_zip_iterator(data.begin(), short_data.begin());\n\tauto last = ext::make_zip_iterator(data.end(), short_data.end());\n\n\ttypedef decltype(first) iter_type;\n\ttypedef std::tuple<const int &, const short &> ref;\n\n\tstd::stable_sort(first, last, [](const ref & r1, const ref & r2) { return std::get<0>(r1) < std::get<0>(r2); });\n\tbool reversed = boost::is_sorted(short_data, std::greater<> {});\n\tBOOST_CHECK(reversed);\n}\n\nBOOST_AUTO_TEST_CASE(zip_iterator_partition_test)\n{\n\tusing namespace std;\n\tvector<int> data = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\n\tvector<short> short_data {data.begin(), data.end()};\n\n\tauto expected_data = data;\n\tauto expected_short_data = short_data;\n\n\t// partition by odd\n\tboost::stable_partition(expected_data, [](int i) { return i % 1; });\n\tboost::stable_partition(expected_short_data, [](short i) { return i % 1; });\n\n\tauto first = ext::make_zip_iterator(data.begin(), short_data.begin());\n\tauto last = ext::make_zip_iterator(data.end(), short_data.end());\n\t\n\t//partition by odd on first array\n\ttypedef std::tuple<const int &, const short &> ref;\n\tstd::stable_partition(first, last, [](const ref & r) { return std::get<0>(r) % 1; });\n\n\tBOOST_CHECK(expected_data == data);\n\tBOOST_CHECK(expected_short_data == short_data);\n}", "meta": {"hexsha": "6cd5e8d5f079399e107802f89a6745686f205c5e", "size": 1695, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/zip_iterator_test.cpp", "max_stars_repo_name": "dmlys/ExtLibrary", "max_stars_repo_head_hexsha": "4ff7dba6bbfdf5f9ab70e8bd4dd28c87c88f35ef", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-05-14T13:36:09.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-14T13:36:09.000Z", "max_issues_repo_path": "tests/zip_iterator_test.cpp", "max_issues_repo_name": "dmlys/extlib", "max_issues_repo_head_hexsha": "faf725464164d30aa197d53eba8d2c870faf2767", "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": "tests/zip_iterator_test.cpp", "max_forks_repo_name": "dmlys/extlib", "max_forks_repo_head_hexsha": "faf725464164d30aa197d53eba8d2c870faf2767", "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.2352941176, "max_line_length": 113, "alphanum_fraction": 0.7014749263, "num_tokens": 455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300698514778, "lm_q2_score": 0.7025300449389327, "lm_q1q2_score": 0.4935484815437102}}
{"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#ifdef TESTING\n\n//#define DO_THIS_NRM_TEST\n#ifdef DO_THIS_NRM_TEST\n\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/mean.hpp>\n#include <boost/accumulators/statistics/variance.hpp>\n#include <boost/accumulators/statistics/covariance.hpp>\n#include <boost/accumulators/statistics/variates/covariate.hpp>\n\nusing namespace boost::accumulators;\n\n#include \"gtest/gtest.h\"\n\n#include \"common.h\"\n\n#include \"Species.h\"\n#include \"Reaction.h\"\n#include \"ChemNRMImpl.h\"\n#include \"ChemSim.h\"\n\n#ifdef TRACK_DEPENDENTS \n// the NRM algorithm fundamentally depends on the ability to track dependents\n\nTEST(ChemNRMTest, StoichiometryInvariants) {\n    SpeciesBulk A1(\"A1\",  100);\n    SpeciesBulk A2(\"A2\", 0);\n    SpeciesBulk A3(\"A3\", 0);\n    Reaction<1,1> r1 = { {&A1,&A2}, 10.0 };\n    Reaction<1,1> r2 = { {&A2,&A1}, 15.0 };\n    Reaction<1,1> r3 = { {&A1,&A3}, 20.0 };\n    \n    ChemSim* chemsim = new ChemSim();\n    chemsim->setInstance(new ChemNRMImpl());\n    \n    chemsim->addReaction(&r1);\n    chemsim->addReaction(&r2);\n    chemsim->addReaction(&r3);\n    \n    chemsim->initialize();\n    chemsim->runSteps(30);\n    EXPECT_EQ(100,A1.getN()+A2.getN()+A3.getN());\n}\n\n// Testing A<->B steady state\nTEST(ChemNRMTest, SimpleSteadyState) {\n    int Nstart = 16;\n    SpeciesBulk A1(\"A1\",  Nstart);\n    SpeciesBulk A2(\"A2\", 0);\n    // A1 <-> A2 with the same forward and backward rates; [A]~[B] at steady state\n    Reaction<1,1> r1 = { {&A1,&A2}, 100.0 };\n    Reaction<1,1> r2 = { {&A2,&A1}, 100.0 };\n    \n    ChemSim* chemsim = new ChemSim();\n    chemsim->setInstance(new ChemNRMImpl());\n    \n    chemsim->addReaction(&r1);\n    chemsim->addReaction(&r2);\n    \n    chemsim->initialize();\n    \n    chemsim->runSteps(1000);\n    \n    accumulator_set<int, stats<tag::variance(immediate)>> accA1;\n    accumulator_set<int, stats<tag::mean>> accA2;\n    accumulator_set<int, stats<tag::covariance<double, tag::covariate1> > > accCov;\n    int N_SAMPLE_POINTS=1000;\n    for(int i=0;i<N_SAMPLE_POINTS;++i){\n        chemsim->runSteps(100);\n        accA1(A1.getN());\n        accCov(A1.getN(), covariate1 = A2.getN());\n    }\n    double A1mean = mean(accA1);\n    double A1var = variance(accA1);\n    double var_expected = double(Nstart)/2/2;\n    double mean_error = sqrt(var_expected/N_SAMPLE_POINTS);\n    EXPECT_TRUE(fabs(A1mean-Nstart/2)<10*mean_error);\n    EXPECT_TRUE(fabs(var_expected-A1var)<0.1*var_expected);\n    // within 10% of the expected variance\n    EXPECT_FLOAT_EQ(-1.0,covariance(accCov)/(A1var));\n\n}\n\n// Testing transient dynamics for A<->B\nTEST(ChemNRMTest, SimpleTransient) {\n    const long long int N_SAMPLE_POINTS=pow(10,6);\n    const long long int Nstart = 10;\n    const double tau_snapshot = 0.48; //seconds\n    \n    SpeciesBulk A1(\"A1\",  Nstart);\n    SpeciesBulk A2(\"A2\", 0);\n    // A1 <-> A2 with the same forward and backward rates; [A]~[B] at steady state\n    Reaction<1,1> r1 = { {&A1,&A2}, 2.5 };\n    Reaction<1,1> r2 = { {&A2,&A1}, 2.5 };\n    \n    ChemSim* chemsim = new ChemSim();\n    chemsim->setInstance(new ChemNRMImpl());\n    \n    chemsim->addReaction(&r1);\n    chemsim->addReaction(&r2);\n\n    vector<long long int> n_hist(Nstart+1);\n    \n    accumulator_set<double, stats<tag::mean>> accTau;\n    long long int N_penultimate;\n    for(long long int i=0;i<N_SAMPLE_POINTS;++i){\n        A1.setN(Nstart);\n        A2.setN(0);\n        chemsim->initialize();\n        do {\n            N_penultimate=A1.getN();\n            chemsim->runSteps(1);\n        } while (tau()<tau_snapshot);\n        ++n_hist[N_penultimate];\n        accTau(tau());\n    }\n\n    double sum=0;\n    for(auto num: n_hist)\n        sum+=double(num)/N_SAMPLE_POINTS;\n    \n    // The results below are for N=10 (coming from both analytical formula\n    // and numerical integration)\n    vector<double> n_hist_analyt {0.0003773 ,  0.00452585,  0.02443017,  0.0781464 ,  0.1640442 , 0.23613261,  0.23604161,  0.1617947,  0.07277957,  0.01940041, 0.00232715};\n    double relative_error=0.15; //i.e. allow a 15% relative error\n    for(int n=0; n<(Nstart+1); ++n){\n        double p_est=double(n_hist[n])/N_SAMPLE_POINTS;\n        double p_analyt=n_hist_analyt[n];\n        EXPECT_NEAR(p_est,p_analyt,relative_error*p_analyt);\n    }\n}\n\n\n// Testing transient dynamics for the A->B->C cycle, where A, B, and C\n// can only take two values, n=0,1\nTEST(ChemNRMTest, CyclicTransient) {\n    const long long int N_SAMPLE_POINTS=pow(10,6);\n    const double tau_snapshot = 0.25; //seconds\n    //long long int print_freq = pow(10,7);\n    SpeciesBulk A1(\"A1\", 1, 1);\n    SpeciesBulk A2(\"A2\", 0, 1);\n    SpeciesBulk A3(\"A3\", 0, 1);\n    Reaction<1,1> r1 = { {&A1,&A2}, 4.5 };\n    Reaction<1,1> r2 = { {&A2,&A3}, 2.5 };\n    Reaction<1,1> r3 = { {&A3,&A1}, 0.5 };\n    \n    ChemSim* chemsim = new ChemSim();\n    chemsim->setInstance(new ChemNRMImpl());\n    \n    chemsim->addReaction(&r1);\n    chemsim->addReaction(&r2);\n    chemsim->addReaction(&r3);\n    \n    long long int n_a1_hist=0;\n    long long int n_a2_hist=0;\n    long long int n_a3_hist=0;\n    \n    for(long long int i=0;i<N_SAMPLE_POINTS;++i){\n        A1.setN(1);\n        A2.setN(0);\n        A3.setN(0);\n        long long int n_a1_pentult=0;\n        long long int n_a2_pentult=0;\n        long long int n_a3_pentult=0;\n        chemsim->initialize();\n        long long int events=0;\n        do {\n            n_a1_pentult=A1.getN();\n            n_a2_pentult=A2.getN();\n            n_a3_pentult=A3.getN();\n            chemsim->runSteps(1);\n            ++events;\n        } while (tau()<tau_snapshot);\n        n_a1_hist+=n_a1_pentult;\n        n_a2_hist+=n_a2_pentult;\n        n_a3_hist+=n_a3_pentult;\n    }\n    \n    double pa1=static_cast<double>(n_a1_hist)/N_SAMPLE_POINTS;\n    double pa2=static_cast<double>(n_a2_hist)/N_SAMPLE_POINTS;\n    double pa3=static_cast<double>(n_a3_hist)/N_SAMPLE_POINTS;\n    \n    double pa1_numeric = 0.33169986;\n    double pa2_numeric = 0.47589009;\n    double pa3_numeric = 0.19241006;\n    \n    double relative_error=0.01; //i.e. allow a 1% relative error\n    EXPECT_NEAR(pa1,pa1_numeric,relative_error*pa1_numeric);\n    EXPECT_NEAR(pa2,pa2_numeric,relative_error*pa1_numeric);\n    EXPECT_NEAR(pa3,pa3_numeric,relative_error*pa1_numeric);\n    \n}\n\n// Testing transient dynamics for the X<->A->B->C cycle, where A, B, and C\n// can only take two values, n=0,1\n#ifdef TRACK_UPPER_COPY_N\nTEST(ChemNRMTest, ComplexCyclicTransient) {\n    const long long int N_SAMPLE_POINTS=pow(10,6);\n    const long long int Nstart = 3;\n    const double tau_snapshot = 0.5; //seconds\n    SpeciesBulk X(\"X\", Nstart); // X's copy number is not restricted\n    SpeciesBulk A(\"A\", 0, 1);\n    SpeciesBulk B(\"B\", 0, 1);\n    SpeciesBulk C(\"C\", 0, 1);\n    \n    float kxa=0.8; // s^-1\n    float kax=0.3; // s^-1\n    float kab=4.5; // s^-1\n    float kbc=2.5; // s^-1\n    float kca=0.5; // s^-1\n    Reaction<1,1> xa = { {&X,&A}, kxa };\n    Reaction<1,1> ax = { {&A,&X}, kax };\n    Reaction<1,1> r1 = { {&A,&B}, kab };\n    Reaction<1,1> r2 = { {&B,&C}, kbc };\n    Reaction<1,1> r3 = { {&C,&A}, kca };\n    \n    ChemSim* chemsim = new ChemSim();\n    chemsim->setInstance(new ChemNRMImpl());\n    \n    chemsim->addReaction(&r1);\n    chemsim->addReaction(&r2);\n    chemsim->addReaction(&r3);\n    chemsim->addReaction(&xa);\n    chemsim->addReaction(&ax);\n    \n    vector<long long int> x_hist(Nstart+1);\n    long long int n_a1_hist=0;\n    long long int n_a2_hist=0;\n    long long int n_a3_hist=0;\n    \n    for(long long int i=0;i<N_SAMPLE_POINTS;++i){\n        A.setN(0);\n        B.setN(0);\n        C.setN(0);\n        X.setN(Nstart);\n        long long int n_a_pentult=0;\n        long long int n_b_pentult=0;\n        long long int n_c_pentult=0;\n        long long int x_pentult=0;\n        chemsim->initialize();\n        long long int events=0;\n        do {\n            x_pentult=X.getN();\n            n_a_pentult=A.getN();\n            n_b_pentult=B.getN();\n            n_c_pentult=C.getN();\n            bool success = chemsim->runSteps(1);\n            if(!success){\n                cout << \"chem.runSteps(1) has failed, i= \" << i << endl;\n                chemsim->printReactions();\n                break;\n            }\n            ++events;\n        } while (tau()<tau_snapshot);\n        ++x_hist[x_pentult];\n        n_a1_hist+=n_a_pentult;\n        n_a2_hist+=n_b_pentult;\n        n_a3_hist+=n_c_pentult;\n    }\n    \n    \n    vector<double> p_nrm;\n    \n    for(int n=0; n<(Nstart+1); ++n){\n        double p_est=double(x_hist[n])/N_SAMPLE_POINTS;\n        p_nrm.push_back(p_est);\n    }\n    \n    double pa1=static_cast<double>(n_a1_hist)/N_SAMPLE_POINTS;\n    double pa2=static_cast<double>(n_a2_hist)/N_SAMPLE_POINTS;\n    double pa3=static_cast<double>(n_a3_hist)/N_SAMPLE_POINTS;\n    p_nrm.push_back(pa1);\n    p_nrm.push_back(pa2);\n    p_nrm.push_back(pa3);\n    \n    // The results below are for ...\n    vector<double> p_numeric {0.001687323512088279, 0.12264078507458409, 0.55515007879166167, 0.3205218126216664, 0.32672439967797662, 0.30766594955383336, 0.17110327024528463};\n    double relative_error=0.05; //i.e. allow a 5% relative error\n    \n    for(int n=0; n<(Nstart+4); ++n){\n        EXPECT_NEAR(p_nrm[n],p_numeric[n],relative_error*p_numeric[n]);\n    }\n}\n#endif // of TRACK_UPPER_COPY_N\n\n#endif // TRACK_DEPENDENTS\n\n#endif //DO_THIS_NRM_TEST\n#endif //TESTING\n", "meta": {"hexsha": "e667357c70d70e02cfb7990beb411c33585755a2", "size": 9752, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/TESTS/test_nrm.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/TESTS/test_nrm.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/TESTS/test_nrm.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": 31.9737704918, "max_line_length": 177, "alphanum_fraction": 0.6137202625, "num_tokens": 3089, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300449389326, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.49354847716825734}}
{"text": "//\n// Created by Alex Beccaro on 18/01/18.\n//\n\n#define BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n#include \"../../src/problems/1-50/12/problem12.hpp\"\n\nBOOST_AUTO_TEST_SUITE( Problem12 )\n\n    BOOST_AUTO_TEST_CASE( Example ) {\n        auto res = problems::problem12::solve(5);\n        BOOST_CHECK_EQUAL(res, 28);\n    }\n\n    BOOST_AUTO_TEST_CASE( Solution ) {\n        auto res = problems::problem12::solve();\n        BOOST_CHECK_EQUAL(res, 76576500);\n    }\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "b46a2d61d09758480c2b55daea80920f9a827b9b", "size": 495, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/1-50/test_problem12.cpp", "max_stars_repo_name": "abeccaro/project-euler", "max_stars_repo_head_hexsha": "c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T10:17:15.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-25T10:17:15.000Z", "max_issues_repo_path": "tests/1-50/test_problem12.cpp", "max_issues_repo_name": "abeccaro/project-euler", "max_issues_repo_head_hexsha": "c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3", "max_issues_repo_licenses": ["MIT"], "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/1-50/test_problem12.cpp", "max_forks_repo_name": "abeccaro/project-euler", "max_forks_repo_head_hexsha": "c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3", "max_forks_repo_licenses": ["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.5714285714, "max_line_length": 51, "alphanum_fraction": 0.6767676768, "num_tokens": 126, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544335934767, "lm_q2_score": 0.705785040214066, "lm_q1q2_score": 0.4935233185336359}}
{"text": "/* Copyright (c) 2019 Kulpreet Singh\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// The functions in this file are useful for implementing new\n// algorithms and finding simple stats about the graph.\n\n#ifndef LNCENTRALITY_DEGREE_STATS_HPP\n#define LNCENTRALITY_DEGREE_STATS_HPP\n\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/mean.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/variance.hpp>\n#include <boost/graph/betweenness_centrality.hpp>\n\n#include <fstream>\n#include <numeric>\n\n#include \"readgraph.hpp\"\n\nusing namespace boost::accumulators;\n\nnamespace lncentrality {\n\ntypedef graph_traits<LitGraph>::degree_size_type Degree;\n\n// A class that provides a function object for iterating over all\n// vertices in the graph and printing the in/out degrees.\ntemplate <class Graph> class degrees {\npublic:\n  typedef typename graph_traits<Graph>::vertex_descriptor Vertex;\n  typedef typename graph_traits<Graph>::degree_size_type Degree;\n\n  degrees(Graph &g_) : g(g_) {}\n\n  void operator()(const Vertex &v) const {\n    using namespace boost;\n    typename property_map<Graph, vertex_index_t>::type vertex_id =\n        get(vertex_index, g);\n\n    std::cout << \"vertex: \" << get(vertex_id, v) << \" :: \" << g[v].name\n              << std::endl;\n\n    std::cout << \" in + out degree \" << degree(v, g) << std::endl;\n    std::cout << \" out degree \" << out_degree(v, g) << std::endl;\n    std::cout << \" in degree \" << in_degree(v, g) << std::endl;\n  }\n\nprivate:\n  Graph &g;\n};\n\n// For each vertex in the graph, set in/out/total degree in the\n// vectors provided.\nvoid get_degrees(vector<Degree> &in_degrees, vector<Degree> &out_degrees,\n                 vector<Degree> &degrees, LitGraph &g) {\n  graph_traits<LitGraph>::vertex_iterator i, end;\n  for (boost::tie(i, end) = vertices(g); i != end; ++i) {\n    in_degrees.push_back(in_degree(*i, g));\n    out_degrees.push_back(out_degree(*i, g));\n    degrees.push_back(degree(*i, g));\n  }\n}\n\n// Compute simple stats about degrees for each vertex in the graph and\n// print those.\nmap<string, double> get_degrees_stats(LitGraph &g) {\n  graph_traits<LitGraph>::vertex_iterator i, end;\n  accumulator_set<Degree, stats<tag::mean, tag::variance>> in_degrees,\n      out_degrees, degrees;\n  map<string, double> result;\n  for (boost::tie(i, end) = vertices(g); i != end; ++i) {\n    in_degrees(in_degree(*i, g));\n    out_degrees(out_degree(*i, g));\n    degrees(degree(*i, g));\n  }\n  result[\"in_degrees_mean\"] = mean(in_degrees);\n  result[\"in_degrees_variance\"] = variance(in_degrees);\n  result[\"out_degrees_mean\"] = mean(out_degrees);\n  result[\"out_degrees_variance\"] = variance(out_degrees);\n  result[\"degrees_mean\"] = mean(degrees);\n  result[\"degrees_variance\"] = variance(degrees);\n  return result;\n}\n\n} // namespace lncentrality\n\n#endif\n", "meta": {"hexsha": "8ea203c45fb7639d7e5ff4b6ad93a194de165349", "size": 3883, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/include/degree_stats.hpp", "max_stars_repo_name": "kulpreet/lightning-network-graph-analysis", "max_stars_repo_head_hexsha": "e2c6547f30629261521f5e19b77efdc53505445a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2018-08-28T06:35:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-17T17:09:18.000Z", "max_issues_repo_path": "src/include/degree_stats.hpp", "max_issues_repo_name": "kulpreet/lightning-network-graph-analysis", "max_issues_repo_head_hexsha": "e2c6547f30629261521f5e19b77efdc53505445a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-05-03T06:37:41.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-04T04:12:53.000Z", "max_forks_repo_path": "src/include/degree_stats.hpp", "max_forks_repo_name": "kulpreet/lightning-network-graph-analysis", "max_forks_repo_head_hexsha": "e2c6547f30629261521f5e19b77efdc53505445a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-09-06T09:21:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-08T17:10:46.000Z", "avg_line_length": 36.2897196262, "max_line_length": 80, "alphanum_fraction": 0.719804275, "num_tokens": 952, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544085240401, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.4935232965126475}}
{"text": "#include <boost/math/quadrature/trapezoidal.hpp>\n", "meta": {"hexsha": "60a360002c140ede99ea076159d9871cb851dffc", "size": 49, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_quadrature_trapezoidal.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_quadrature_trapezoidal.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_quadrature_trapezoidal.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 24.5, "max_line_length": 48, "alphanum_fraction": 0.8163265306, "num_tokens": 13, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891479496523, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4934683557094477}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2015 NumScale SAS\n  @copyright 2015 J.T. Lapreste\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_COMMON_FUNCTION_SCALAR_NTHROOT_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_FUNCTION_SCALAR_NTHROOT_HPP_INCLUDED\n#include <boost/simd/function/fast.hpp>\n\n#ifndef BOOST_SIMD_NO_INFINITIES\n#include <boost/simd/function/scalar/is_inf.hpp>\n#endif\n#ifndef BOOST_SIMD_NO_INVALID\n#include <boost/simd/function/scalar/is_nan.hpp>\n#endif\n#include <boost/simd/constant/nan.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/function/scalar/abs.hpp>\n#include <boost/simd/function/scalar/is_ltz.hpp>\n#include <boost/simd/function/scalar/is_odd.hpp>\n#include <boost/simd/function/scalar/minusone.hpp>\n#include <boost/simd/function/scalar/pow.hpp>\n#include <boost/simd/function/scalar/rec.hpp>\n#include <boost/simd/function/scalar/sign.hpp>\n#include <boost/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\n  BOOST_DISPATCH_OVERLOAD ( nthroot_\n                          , (typename A0, typename A1)\n                          , bd::cpu_\n                          , bd::scalar_< bd::floating_<A0> >\n                          , bd::scalar_< bd::integer_<A1> >\n                          )\n  {\n    inline A0 operator() ( A0 a0, A1 a1) const BOOST_NOEXCEPT\n    {\n#ifndef BOOST_SIMD_NO_INVALID\n      if (is_nan(a0)) return a0;\n#endif\n      auto is_ltza0 = is_ltz(a0);\n      auto is_odda1 = is_odd(a1);\n      if (is_ltza0 && !is_odda1) return Nan<A0>();\n      A0 x = bs::abs(a0);\n      if (x == One<A0>()) return a0;\n      if (!a1) return (x < One<A0>()) ? Zero<A0>() : sign(a0)*Inf<A0>();\n      if (!a0) return Zero<A0>();\n#ifndef BOOST_SIMD_NO_INFINITIES\n      if (is_inf(a0)) return (a1) ? a0 : One<A0>();\n#endif\n      A0 aa1 = static_cast<A0>(a1);\n      A0 y = bs::pow(x,rec(aa1));\n      // Correct numerical errors (since, e.g., 64^(1/3) is not exactly 4)\n      // by one iteration of Newton's method\n      if (y) y -= (bs::pow(y, aa1) - x) / (aa1* bs::pow(y,minusone(aa1)));\n      return (is_ltza0 && is_odda1)? -y : y;\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( nthroot_\n                          , (typename A0, typename A1)\n                          , bd::cpu_\n                          , bd::scalar_< bd::floating_<A0> >\n                          , bd::scalar_< bd::integer_<A1> >\n                          , boost::simd::fast_tag\n                          )\n  {\n    inline A0 operator() ( A0 a0, A1 a1\n                         , fast_tag const&) const BOOST_NOEXCEPT\n    {\n      auto is_ltza0 = is_ltz(a0);\n      auto is_odda1 = is_odd(a1);\n      if (is_ltza0 && !is_odda1) return Nan<A0>();\n      A0 x = bs::abs(a0);\n      if (x == One<A0>()) return a0;\n      if (!a1) return (x < One<A0>()) ? Zero<A0>() : sign(a0)*Inf<A0>();\n      if (!a0) return Zero<A0>();\n      A0 aa1 = static_cast<A0>(a1);\n      A0 y = bs::pow(x,rec(aa1));\n      return (is_ltza0 && is_odda1)? -y : y;\n    }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "7883299efcb2755ef88c0e52fa915f79bfec7ed4", "size": 3417, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arch/common/scalar/function/nthroot.hpp", "max_stars_repo_name": "yaeldarmon/boost.simd", "max_stars_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/simd/arch/common/scalar/function/nthroot.hpp", "max_issues_repo_name": "yaeldarmon/boost.simd", "max_issues_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/arch/common/scalar/function/nthroot.hpp", "max_forks_repo_name": "yaeldarmon/boost.simd", "max_forks_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.8673469388, "max_line_length": 100, "alphanum_fraction": 0.559262511, "num_tokens": 933, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891479496523, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4934683557094477}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#pragma once\n\n#include <boost/iterator/zip_iterator.hpp>\n#include <cstddef>\n\n#include \"DataStructures/ComplexDataVector.hpp\"\n#include \"DataStructures/DataVector.hpp\"\n#include \"DataStructures/Tensor/Tensor.hpp\"\n#include \"DataStructures/Tensor/TypeAliases.hpp\"\n#include \"Evolution/Systems/Cce/BoundaryData.hpp\"\n#include \"Evolution/Systems/Cce/WorldtubeBufferUpdater.hpp\"\n#include \"Helpers/Evolution/Systems/Cce/WriteToWorldtubeH5.hpp\"\n#include \"NumericalAlgorithms/Spectral/SwshCollocation.hpp\"\n#include \"PointwiseFunctions/AnalyticSolutions/GeneralRelativity/KerrSchild.hpp\"\n#include \"PointwiseFunctions/GeneralRelativity/GeneralizedHarmonic/Phi.hpp\"\n#include \"PointwiseFunctions/GeneralRelativity/GeneralizedHarmonic/Pi.hpp\"\n#include \"PointwiseFunctions/GeneralRelativity/SpacetimeMetric.hpp\"\n#include \"Utilities/FileSystem.hpp\"\n#include \"Utilities/Gsl.hpp\"\n\nnamespace Cce {\nnamespace TestHelpers {\ntemplate <typename... Structure>\nTensor<ComplexModalVector, Structure...> tensor_to_goldberg_coefficients(\n    const Tensor<DataVector, Structure...>& nodal_data, size_t l_max) noexcept {\n  Tensor<ComplexModalVector, Structure...> goldberg_modal_data{\n      square(l_max + 1)};\n  SpinWeighted<ComplexDataVector, 0> transform_buffer{\n      Spectral::Swsh::number_of_swsh_collocation_points(l_max)};\n  for (size_t i = 0; i < nodal_data.size(); ++i) {\n    transform_buffer.data() = std::complex<double>(1.0, 0.0) * nodal_data[i];\n    goldberg_modal_data[i] =\n        Spectral::Swsh::libsharp_to_goldberg_modes(\n            Spectral::Swsh::swsh_transform(l_max, 1, transform_buffer), l_max)\n            .data();\n  }\n  return goldberg_modal_data;\n}\n\ntemplate <typename... Structure>\nTensor<ComplexModalVector, Structure...> tensor_to_libsharp_coefficients(\n    const Tensor<DataVector, Structure...>& nodal_data,\n    const size_t l_max)  // NOLINT(readability-avoid-const-params-in-decls)\n    noexcept {\n  Tensor<ComplexModalVector, Structure...> libsharp_modal_data{\n      Spectral::Swsh::size_of_libsharp_coefficient_vector(l_max)};\n  SpinWeighted<ComplexDataVector, 0> transform_buffer{\n      Spectral::Swsh::number_of_swsh_collocation_points(l_max)};\n  for (size_t i = 0; i < nodal_data.size(); ++i) {\n    transform_buffer.data() = std::complex<double>(1.0, 0.0) * nodal_data[i];\n    libsharp_modal_data[i] =\n        Spectral::Swsh::swsh_transform(l_max, 1, transform_buffer).data();\n  }\n  return libsharp_modal_data;\n}\n\ntemplate <typename AnalyticSolution>\nvoid create_fake_time_varying_gh_nodal_data(\n    const gsl::not_null<tnsr::aa<DataVector, 3>*> spacetime_metric,\n    const gsl::not_null<tnsr::iaa<DataVector, 3>*> phi,\n    const gsl::not_null<tnsr::aa<DataVector, 3>*> pi,\n    const AnalyticSolution& solution, const double extraction_radius,\n    const double amplitude, const double frequency, const double time,\n    const size_t l_max) noexcept {\n  const size_t number_of_angular_points =\n      Spectral::Swsh::number_of_swsh_collocation_points(l_max);\n  // create the vector of collocation points that we want to interpolate to\n\n  tnsr::I<DataVector, 3> collocation_points{number_of_angular_points};\n  const auto& collocation = Spectral::Swsh::cached_collocation_metadata<\n      Spectral::Swsh::ComplexRepresentation::Interleaved>(l_max);\n  for (const auto collocation_point : collocation) {\n    get<0>(collocation_points)[collocation_point.offset] =\n        extraction_radius * (1.0 + amplitude * sin(frequency * time)) *\n        sin(collocation_point.theta) * cos(collocation_point.phi);\n    get<1>(collocation_points)[collocation_point.offset] =\n        extraction_radius * (1.0 + amplitude * sin(frequency * time)) *\n        sin(collocation_point.theta) * sin(collocation_point.phi);\n    get<2>(collocation_points)[collocation_point.offset] =\n        extraction_radius * (1.0 + amplitude * sin(frequency * time)) *\n        cos(collocation_point.theta);\n  }\n\n  const auto kerr_schild_variables = solution.variables(\n      collocation_points, 0.0, gr::Solutions::KerrSchild::tags<DataVector>{});\n\n  const Scalar<DataVector>& lapse =\n      get<gr::Tags::Lapse<DataVector>>(kerr_schild_variables);\n  const Scalar<DataVector>& dt_lapse =\n      get<::Tags::dt<gr::Tags::Lapse<DataVector>>>(kerr_schild_variables);\n  const auto& d_lapse = get<gr::Solutions::KerrSchild::DerivLapse<DataVector>>(\n      kerr_schild_variables);\n\n  const auto& shift = get<gr::Tags::Shift<3, ::Frame::Inertial, DataVector>>(\n      kerr_schild_variables);\n  const auto& dt_shift =\n      get<::Tags::dt<gr::Tags::Shift<3, ::Frame::Inertial, DataVector>>>(\n          kerr_schild_variables);\n  const auto& d_shift = get<gr::Solutions::KerrSchild::DerivShift<DataVector>>(\n      kerr_schild_variables);\n\n  const auto& spatial_metric =\n      get<gr::Tags::SpatialMetric<3, ::Frame::Inertial, DataVector>>(\n          kerr_schild_variables);\n  const auto& dt_spatial_metric = get<\n      ::Tags::dt<gr::Tags::SpatialMetric<3, ::Frame::Inertial, DataVector>>>(\n      kerr_schild_variables);\n  const auto& d_spatial_metric =\n      get<gr::Solutions::KerrSchild::DerivSpatialMetric<DataVector>>(\n          kerr_schild_variables);\n\n  gr::spacetime_metric(spacetime_metric, lapse, shift, spatial_metric);\n  GeneralizedHarmonic::phi(phi, lapse, d_lapse, shift, d_shift, spatial_metric,\n                           d_spatial_metric);\n  GeneralizedHarmonic::pi(pi, lapse, dt_lapse, shift, dt_shift, spatial_metric,\n                          dt_spatial_metric, *phi);\n}\n\ntemplate <typename AnalyticSolution>\nvoid create_fake_time_varying_modal_data(\n    const gsl::not_null<tnsr::ii<ComplexModalVector, 3>*>\n        spatial_metric_coefficients,\n    const gsl::not_null<tnsr::ii<ComplexModalVector, 3>*>\n        dt_spatial_metric_coefficients,\n    const gsl::not_null<tnsr::ii<ComplexModalVector, 3>*>\n        dr_spatial_metric_coefficients,\n    const gsl::not_null<tnsr::I<ComplexModalVector, 3>*> shift_coefficients,\n    const gsl::not_null<tnsr::I<ComplexModalVector, 3>*> dt_shift_coefficients,\n    const gsl::not_null<tnsr::I<ComplexModalVector, 3>*> dr_shift_coefficients,\n    const gsl::not_null<Scalar<ComplexModalVector>*> lapse_coefficients,\n    const gsl::not_null<Scalar<ComplexModalVector>*> dt_lapse_coefficients,\n    const gsl::not_null<Scalar<ComplexModalVector>*> dr_lapse_coefficients,\n    const AnalyticSolution& solution, const double extraction_radius,\n    const double amplitude, const double frequency, const double time,\n    const size_t l_max, const bool convert_to_goldberg = true,\n    const bool apply_normalization_bug = false) noexcept {\n  const size_t number_of_angular_points =\n      Spectral::Swsh::number_of_swsh_collocation_points(l_max);\n  // create the vector of collocation points that we want to interpolate to\n\n  tnsr::I<DataVector, 3> collocation_points{number_of_angular_points};\n  const auto& collocation = Spectral::Swsh::cached_collocation_metadata<\n      Spectral::Swsh::ComplexRepresentation::Interleaved>(l_max);\n  for (const auto collocation_point : collocation) {\n    get<0>(collocation_points)[collocation_point.offset] =\n        extraction_radius * (1.0 + amplitude * sin(frequency * time)) *\n        sin(collocation_point.theta) * cos(collocation_point.phi);\n    get<1>(collocation_points)[collocation_point.offset] =\n        extraction_radius * (1.0 + amplitude * sin(frequency * time)) *\n        sin(collocation_point.theta) * sin(collocation_point.phi);\n    get<2>(collocation_points)[collocation_point.offset] =\n        extraction_radius * (1.0 + amplitude * sin(frequency * time)) *\n        cos(collocation_point.theta);\n  }\n\n  const auto kerr_schild_variables = solution.variables(\n      collocation_points, 0.0, gr::Solutions::KerrSchild::tags<DataVector>{});\n\n  const Scalar<DataVector>& lapse =\n      get<gr::Tags::Lapse<DataVector>>(kerr_schild_variables);\n  const Scalar<DataVector>& dt_lapse =\n      get<::Tags::dt<gr::Tags::Lapse<DataVector>>>(kerr_schild_variables);\n  const auto& d_lapse = get<gr::Solutions::KerrSchild::DerivLapse<DataVector>>(\n      kerr_schild_variables);\n\n  const auto& shift = get<gr::Tags::Shift<3, ::Frame::Inertial, DataVector>>(\n      kerr_schild_variables);\n  const auto& dt_shift =\n      get<::Tags::dt<gr::Tags::Shift<3, ::Frame::Inertial, DataVector>>>(\n          kerr_schild_variables);\n  const auto& d_shift = get<gr::Solutions::KerrSchild::DerivShift<DataVector>>(\n      kerr_schild_variables);\n\n  const auto& spatial_metric =\n      get<gr::Tags::SpatialMetric<3, ::Frame::Inertial, DataVector>>(\n          kerr_schild_variables);\n  const auto& dt_spatial_metric = get<\n      ::Tags::dt<gr::Tags::SpatialMetric<3, ::Frame::Inertial, DataVector>>>(\n      kerr_schild_variables);\n  const auto& d_spatial_metric =\n      get<gr::Solutions::KerrSchild::DerivSpatialMetric<DataVector>>(\n          kerr_schild_variables);\n\n  DataVector normalization_factor{number_of_angular_points, 1.0};\n  if (apply_normalization_bug) {\n    normalization_factor = 0.0;\n    const auto inverse_spatial_metric =\n        determinant_and_inverse(spatial_metric).second;\n    for (size_t i = 0; i < 3; ++i) {\n      for (size_t j = 0; j < 3; ++j) {\n        normalization_factor +=\n            inverse_spatial_metric.get(i, j) * collocation_points.get(i) *\n            collocation_points.get(j) /\n            square(extraction_radius *\n                   (1.0 + amplitude * sin(frequency * time)));\n      }\n    }\n    normalization_factor = sqrt(normalization_factor);\n  }\n\n  Scalar<DataVector> dr_lapse{number_of_angular_points};\n  get(dr_lapse) = (get<0>(collocation_points) * get<0>(d_lapse) +\n                   get<1>(collocation_points) * get<1>(d_lapse) +\n                   get<2>(collocation_points) * get<2>(d_lapse)) /\n                  (extraction_radius * normalization_factor);\n  tnsr::I<DataVector, 3> dr_shift{number_of_angular_points};\n  for (size_t i = 0; i < 3; ++i) {\n    dr_shift.get(i) = (get<0>(collocation_points) * d_shift.get(0, i) +\n                       get<1>(collocation_points) * d_shift.get(1, i) +\n                       get<2>(collocation_points) * d_shift.get(2, i)) /\n                      (extraction_radius * normalization_factor);\n  }\n  tnsr::ii<DataVector, 3> dr_spatial_metric{number_of_angular_points};\n  for (size_t i = 0; i < 3; ++i) {\n    for (size_t j = i; j < 3; ++j) {\n      dr_spatial_metric.get(i, j) =\n          (get<0>(collocation_points) * d_spatial_metric.get(0, i, j) +\n           get<1>(collocation_points) * d_spatial_metric.get(1, i, j) +\n           get<2>(collocation_points) * d_spatial_metric.get(2, i, j)) /\n          (extraction_radius * normalization_factor);\n    }\n  }\n\n  if (convert_to_goldberg) {\n    *lapse_coefficients =\n        TestHelpers::tensor_to_goldberg_coefficients(lapse, l_max);\n    *dt_lapse_coefficients =\n        TestHelpers::tensor_to_goldberg_coefficients(dt_lapse, l_max);\n    *dr_lapse_coefficients =\n        TestHelpers::tensor_to_goldberg_coefficients(dr_lapse, l_max);\n\n    *shift_coefficients =\n        TestHelpers::tensor_to_goldberg_coefficients(shift, l_max);\n    *dt_shift_coefficients =\n        TestHelpers::tensor_to_goldberg_coefficients(dt_shift, l_max);\n    *dr_shift_coefficients =\n        TestHelpers::tensor_to_goldberg_coefficients(dr_shift, l_max);\n\n    *spatial_metric_coefficients =\n        TestHelpers::tensor_to_goldberg_coefficients(spatial_metric, l_max);\n    *dt_spatial_metric_coefficients =\n        TestHelpers::tensor_to_goldberg_coefficients(dt_spatial_metric, l_max);\n    *dr_spatial_metric_coefficients =\n        TestHelpers::tensor_to_goldberg_coefficients(dr_spatial_metric, l_max);\n  } else {\n    *lapse_coefficients =\n        TestHelpers::tensor_to_libsharp_coefficients(lapse, l_max);\n    *dt_lapse_coefficients =\n        TestHelpers::tensor_to_libsharp_coefficients(dt_lapse, l_max);\n    *dr_lapse_coefficients =\n        TestHelpers::tensor_to_libsharp_coefficients(dr_lapse, l_max);\n\n    *shift_coefficients =\n        TestHelpers::tensor_to_libsharp_coefficients(shift, l_max);\n    *dt_shift_coefficients =\n        TestHelpers::tensor_to_libsharp_coefficients(dt_shift, l_max);\n    *dr_shift_coefficients =\n        TestHelpers::tensor_to_libsharp_coefficients(dr_shift, l_max);\n\n    *spatial_metric_coefficients =\n        TestHelpers::tensor_to_libsharp_coefficients(spatial_metric, l_max);\n    *dt_spatial_metric_coefficients =\n        TestHelpers::tensor_to_libsharp_coefficients(dt_spatial_metric, l_max);\n    *dr_spatial_metric_coefficients =\n        TestHelpers::tensor_to_libsharp_coefficients(dr_spatial_metric, l_max);\n  }\n}\n\ntemplate <typename AnalyticSolution>\nvoid write_test_file(const AnalyticSolution& solution,\n                     const std::string& filename, const double target_time,\n                     const double extraction_radius, const double frequency,\n                     const double amplitude, const size_t l_max) noexcept {\n  const size_t goldberg_size = square(l_max + 1);\n  tnsr::ii<ComplexModalVector, 3> spatial_metric_coefficients{goldberg_size};\n  tnsr::ii<ComplexModalVector, 3> dt_spatial_metric_coefficients{goldberg_size};\n  tnsr::ii<ComplexModalVector, 3> dr_spatial_metric_coefficients{goldberg_size};\n  tnsr::I<ComplexModalVector, 3> shift_coefficients{goldberg_size};\n  tnsr::I<ComplexModalVector, 3> dt_shift_coefficients{goldberg_size};\n  tnsr::I<ComplexModalVector, 3> dr_shift_coefficients{goldberg_size};\n  Scalar<ComplexModalVector> lapse_coefficients{goldberg_size};\n  Scalar<ComplexModalVector> dt_lapse_coefficients{goldberg_size};\n  Scalar<ComplexModalVector> dr_lapse_coefficients{goldberg_size};\n\n  // write times to file for several steps before and after the target time\n  if (file_system::check_if_file_exists(filename)) {\n    file_system::rm(filename, true);\n  }\n  // scoped to close the file\n  {\n    TestHelpers::WorldtubeModeRecorder recorder{filename, l_max};\n    for (size_t t = 0; t < 30; ++t) {\n      const double time = 0.1 * t + target_time - 1.5;\n      TestHelpers::create_fake_time_varying_modal_data(\n          make_not_null(&spatial_metric_coefficients),\n          make_not_null(&dt_spatial_metric_coefficients),\n          make_not_null(&dr_spatial_metric_coefficients),\n          make_not_null(&shift_coefficients),\n          make_not_null(&dt_shift_coefficients),\n          make_not_null(&dr_shift_coefficients),\n          make_not_null(&lapse_coefficients),\n          make_not_null(&dt_lapse_coefficients),\n          make_not_null(&dr_lapse_coefficients), solution, extraction_radius,\n          amplitude, frequency, time, l_max);\n      for (size_t i = 0; i < 3; ++i) {\n        for (size_t j = i; j < 3; ++j) {\n          recorder.append_worldtube_mode_data(\n              detail::dataset_name_for_component(\"/g\", i, j), time,\n              spatial_metric_coefficients.get(i, j), l_max);\n          recorder.append_worldtube_mode_data(\n              detail::dataset_name_for_component(\"/Drg\", i, j), time,\n              dr_spatial_metric_coefficients.get(i, j), l_max);\n          recorder.append_worldtube_mode_data(\n              detail::dataset_name_for_component(\"/Dtg\", i, j), time,\n              dt_spatial_metric_coefficients.get(i, j), l_max);\n        }\n        recorder.append_worldtube_mode_data(\n            detail::dataset_name_for_component(\"/Shift\", i), time,\n            shift_coefficients.get(i), l_max);\n        recorder.append_worldtube_mode_data(\n            detail::dataset_name_for_component(\"/DrShift\", i), time,\n            dr_shift_coefficients.get(i), l_max);\n        recorder.append_worldtube_mode_data(\n            detail::dataset_name_for_component(\"/DtShift\", i), time,\n            dt_shift_coefficients.get(i), l_max);\n      }\n      recorder.append_worldtube_mode_data(\n          detail::dataset_name_for_component(\"/Lapse\"), time,\n          get(lapse_coefficients), l_max);\n      recorder.append_worldtube_mode_data(\n          detail::dataset_name_for_component(\"/DrLapse\"), time,\n          get(dr_lapse_coefficients), l_max);\n      recorder.append_worldtube_mode_data(\n          detail::dataset_name_for_component(\"/DtLapse\"), time,\n          get(dt_lapse_coefficients), l_max);\n    }\n  }\n}\n}  // namespace TestHelpers\n}  // namespace Cce\n", "meta": {"hexsha": "4044281b70839cda2e2f6f4e49b9e7203c9486b0", "size": 16173, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "tests/Unit/Helpers/Evolution/Systems/Cce/BoundaryTestHelpers.hpp", "max_stars_repo_name": "macedo22/spectre", "max_stars_repo_head_hexsha": "97b2b7ae356cf86830258cb5f689f1191fdb6ddd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-04-11T04:07:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-11T05:07:54.000Z", "max_issues_repo_path": "tests/Unit/Helpers/Evolution/Systems/Cce/BoundaryTestHelpers.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": "tests/Unit/Helpers/Evolution/Systems/Cce/BoundaryTestHelpers.hpp", "max_forks_repo_name": "macedo22/spectre", "max_forks_repo_head_hexsha": "97b2b7ae356cf86830258cb5f689f1191fdb6ddd", "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": 47.0145348837, "max_line_length": 80, "alphanum_fraction": 0.7124219378, "num_tokens": 4150, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4934683452495439}}
{"text": "/*\n@copyright Louis Dionne 2014\nDistributed under the Boost Software License, Version 1.0.\n(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n */\n\n#include <boost/hana/maybe.hpp>\n\n#include <boost/hana/detail/assert.hpp>\n#include <boost/hana/detail/constexpr.hpp>\n#include <boost/hana/integral.hpp>\n#include <boost/hana/monad/laws.hpp>\nusing namespace boost::hana;\n\n\nBOOST_HANA_CONSTEXPR_LAMBDA auto f = [](auto x) {\n    return just(x + int_<1>);\n};\n\nBOOST_HANA_CONSTEXPR_LAMBDA auto g = [](auto x) {\n    return just(x * int_<3>);\n};\n\nint main() {\n    BOOST_HANA_CONSTANT_ASSERT(Monad::laws::check(nothing, int_<1>, f, g));\n    BOOST_HANA_CONSTANT_ASSERT(Monad::laws::check(just(int_<1>), int_<1>, f, g));\n    BOOST_HANA_CONSTEXPR_ASSERT(Monad::laws::check(just(1), int_<1>, f, g));\n}\n", "meta": {"hexsha": "7810dd0ad0fd0d562cc93e4416f213c7708ca126", "size": 812, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/maybe/monad/laws.cpp", "max_stars_repo_name": "rbock/hana", "max_stars_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-05-07T14:29:13.000Z", "max_stars_repo_stars_event_max_datetime": "2015-07-04T10:59:46.000Z", "max_issues_repo_path": "test/maybe/monad/laws.cpp", "max_issues_repo_name": "rbock/hana", "max_issues_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/maybe/monad/laws.cpp", "max_forks_repo_name": "rbock/hana", "max_forks_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0, "max_line_length": 81, "alphanum_fraction": 0.710591133, "num_tokens": 236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4934683452495439}}
{"text": "#include <boost/math/complex/atanh.hpp>\n", "meta": {"hexsha": "1f85c285116d1254fdb1040ade1830bccd91a5e0", "size": 40, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_complex_atanh.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_complex_atanh.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_complex_atanh.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 20.0, "max_line_length": 39, "alphanum_fraction": 0.775, "num_tokens": 11, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891130942474, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4934683347896394}}
{"text": "#include <iostream>\n#include \"greeter/greeter.hpp\"\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n#include <plog/Log.h> // Step1: include the headers\n#include \"plog/Initializers/RollingFileInitializer.h\"\n\nint main(int argc, char* argv[]) {\n    using namespace boost::numeric::ublas;\n\n    plog::init(plog::debug, \"myapp_log.txt\");\n    PLOG_INFO << \"Program beginning.\";\n\n    greeter(\"Now running our demo program!\");\n\n    std::cout << \"Testing Boost Matrix example!\" << std::endl;\n    matrix<double> m (3, 3);\n    for (unsigned i = 0; i < m.size1 (); ++ i)\n        for (unsigned j = 0; j < m.size2 (); ++ j) {\n            m(i, j) = 3 * i + j;\n            PLOG_DEBUG << \"Indices \" << i << \" \" << j;\n        }\n    std::cout << m << std::endl;\n\n    greeter(\"Demo program ends!\");\n    PLOG_INFO << \"Program ending.\";\n\n    return 0;\n}\n", "meta": {"hexsha": "a72566178b5beefbcf14c69ba632b5d4a8179f51", "size": 864, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "c++/build-c++-demo2/main.cpp", "max_stars_repo_name": "hortonuva/learning-build-tools", "max_stars_repo_head_hexsha": "65e6f48a687468abe6e17c06fc537159becaea5e", "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": "c++/build-c++-demo2/main.cpp", "max_issues_repo_name": "hortonuva/learning-build-tools", "max_issues_repo_head_hexsha": "65e6f48a687468abe6e17c06fc537159becaea5e", "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": "c++/build-c++-demo2/main.cpp", "max_forks_repo_name": "hortonuva/learning-build-tools", "max_forks_repo_head_hexsha": "65e6f48a687468abe6e17c06fc537159becaea5e", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-10-03T01:02:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-16T06:06:50.000Z", "avg_line_length": 27.0, "max_line_length": 62, "alphanum_fraction": 0.5891203704, "num_tokens": 251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583376458153, "lm_q2_score": 0.709019146082187, "lm_q1q2_score": 0.4934477862664143}}
{"text": "#include <UnitTest++/UnitTest++.h>\n#include <stdexcept>\n#include \"../random.h\"\n\n#include <boost/filesystem.hpp>\n#include <boost/random/poisson_distribution.hpp>\n#include <boost/math/distributions/poisson.hpp>\n#include <vector>\n\n#include<unuran.h>\n\n#include <iostream>\n#include <fstream>\n\nusing namespace coela;\nusing namespace std;\n\nSUITE(random)\n{\n\n    string test_suite_output_dir = \"random_tests/\";\n\n    TEST(Notify_Suite_Has_Been_Run) {\n        cout << \"*** \\\"random number gen\\\" unit tests running ***\" <<endl;\n        boost::filesystem::create_directories(test_suite_output_dir);\n    }\n\n    TEST(Unuran_Seed) {\n        //Need to do this within a function, hence declaration within a TEST macro.\n        std::vector < unsigned long > seed;\n\n        seed.push_back(1111);\n        seed.push_back(222);\n        seed.push_back(333);\n        seed.push_back(444);\n        seed.push_back(555);\n        seed.push_back(666);\n\n        unuran::\n        StreamWrapper::set_unuran_package_seed(seed, false);\n\n    }\n\n    TEST(Unuran_Seed_Manipulation) {\n        using namespace coela::unuran;\n\n        std::vector < unsigned long > seed;\n        seed.push_back(1111);\n        seed.push_back(222);\n        seed.push_back(333);\n        seed.push_back(444);\n        seed.push_back(555);\n        seed.push_back(666);\n\n        int n_advancements = 3;\n\n        StreamWrapper::set_unuran_package_seed(seed, false);\n        StreamWrapper rns1;\n        StreamWrapper::advance_package_seed(n_advancements);\n        StreamWrapper alternate_rns1;\n\n        UniformRandomVariate urv1(0,1.0,rns1);\n        UniformRandomVariate alternate_urv1(0,1.0,alternate_rns1);\n\n\n        StreamWrapper::set_unuran_package_seed(seed, false);\n        StreamWrapper rns2;\n        StreamWrapper::advance_package_seed(n_advancements);\n        StreamWrapper alternate_rns2;\n\n        UniformRandomVariate urv2(0,1.0,rns2);\n        UniformRandomVariate alternate_urv2(0,1.0,alternate_rns2);\n\n        vector<double> results1, results2;\n\n        for (size_t i=0; i!=10; ++i) {\n            results1.push_back(urv1());\n            results2.push_back(urv2());\n        }\n\n        CHECK(results1==results2);\n\n        vector<double> alt_results1, alt_results2;\n\n        for (size_t i=0; i!=10; ++i) {\n            alt_results1.push_back(alternate_urv1());\n            alt_results2.push_back(alternate_urv2());\n        }\n\n        CHECK(alt_results1==alt_results2);\n\n        CHECK(alt_results1!=results1); //(sanity check)\n        CHECK(alt_results2!=results2);\n    }\n\n//\n//    TEST(Unuran_Uniform_Distribution) {\n//        using namespace coela::unuran;\n//\n//        StreamWrapper rns;\n//\n//        uniform_random_variate rv_0_1(0, 1.0, rns);\n//\n//        coela::HistogramContainer14bit hist;\n//\n//        size_t n_its = 1e6;\n//\n//        int n_bins=10;\n//\n//        //visual check\n////        for (size_t i=0; i!=10;++i){\n////            cout<<\"rv_0_1: \" <<rv_0_1()<<endl;\n////        }\n//\n//        for (size_t i=0; i!=n_its; ++i) {\n//            hist.count_int_value(floor(rv_0_1()*n_bins));\n//        }\n//\n//        int n_per_bin = n_its / n_bins;\n//\n//        for (int ind=0; ind<n_bins; ++ind) {\n//            CHECK_CLOSE(n_per_bin, hist[ind], n_per_bin/100);\n//        }\n//\n//        hist.write_to_file(test_suite_output_dir+\"uniform_dist_tenths.txt\");\n//    }\n//\n\n\n//\n//    TEST(Boost_Poisson_Distribution_mean_1){\n//        double mean =1.0;\n////        coela::simple_01_uniform_random_variate rv(172);\n//\n//\n//        unuran_poisson_random_variate poisson_gen(mean);\n//\n//\n//        coela::HistogramContainer14bit hist;\n//\n//        size_t n_its = 1e6;\n//\n//        boost::math::poisson_distribution<> poisson_pdf(mean);\n//\n//        for (size_t i=0; i!=n_its; ++i){\n//            hist.count_int_value((int)poisson_gen());\n//\n//        }\n//\n//        for (int ind=0; ind<100; ++ind){\n//            double predicted_num = boost::math::pdf(poisson_pdf,ind)*n_its;\n//            CHECK_CLOSE(predicted_num, (double)hist[ind] , max(predicted_num/10, 5.0));\n//        }\n//\n//        hist.write_to_file(test_suite_output_dir+\"poisson_dist_mean\"+string_utils::ftoa(mean,2)+\".txt\");\n//\n//    }\n\n\n//    TEST(Boost_Poisson_Distribution_mean_11_and_a_quarter){\n//        double mean =11.25;\n//        coela::simple_01_uniform_random_variate rv(123);\n//\n//\n//        boost::poisson_distribution<> poisson_gen(mean);\n//\n//\n//        coela::HistogramContainer14bit hist;\n//\n//        size_t n_its = 1e6;\n//\n//        boost::math::poisson_distribution<> poisson_pdf(mean);\n//\n//        int zeroes=0;\n//        for (size_t i=0; i!=n_its; ++i){\n//            assert(fmod(poisson_gen(rv),1.0) == 0.0);\n//            int result = poisson_gen(rv);\n//            if (result==0) ++zeroes;\n//            hist.count_int_value(result);\n//\n//        }\n//\n//        cerr<<\"zeros \"<<zeroes<<endl;\n//\n//        for (int ind=0; ind<100; ++ind){\n//            double predicted_num = boost::math::pdf(poisson_pdf,ind)*n_its;\n//            CHECK_CLOSE(predicted_num, (double)hist[ind] , max(predicted_num/10, 10.0));\n//        }\n//\n//        hist.write_to_file(test_suite_output_dir+\"boost_poisson_dist_mean\"+string_utils::ftoa(mean,4)+\".txt\");\n//\n//    }\n\n\n//    TEST(unuran_poisson_11_quarter) {\n//\n//        std::vector < unsigned long > seed;\n//        seed.push_back(1111);\n//        seed.push_back(222);\n//        seed.push_back(333);\n//        seed.push_back(444);\n//        seed.push_back(555);\n//        seed.push_back(666);\n//\n//        unuran::\n//        StreamWrapper::set_unuran_package_seed(seed, false);\n//\n//        using namespace random;\n//        double mean =11.25;\n//\n//        unuran::StreamWrapper rns1;\n//\n//        unuran::PoissonRandomVariate gen(mean, rns1);\n//        coela::HistogramContainer14bit hist;\n//\n//        size_t n_its = 1e6;\n//\n//        int zeroes=0;\n//        for (size_t i=0; i!=n_its; ++i) {\n//            assert(fmod(gen(),1.0) == 0.0);\n//            int result = gen();\n//            if (result==0) { ++zeroes; }\n//            hist.count_int_value(result);\n//\n//        }\n//\n////        cerr<<\"zeros \"<<zeroes<<endl; //turns out the boost method produced far too many zero counts\n//\n//        boost::math::poisson_distribution<> poisson_pdf(mean);\n//\n//        for (int ind=0; ind<100; ++ind) {\n//            double predicted_num = boost::math::pdf(poisson_pdf,ind)*n_its;\n//            CHECK_CLOSE(predicted_num, (double)hist[ind] , max(predicted_num/10, 10.0));\n//        }\n//\n//        hist.write_to_file(test_suite_output_dir+\"unuran_poisson_dist_mean\"+string_utils::ftoa(\n//                               mean,4)+\".txt\");\n//\n//    }\n\n    TEST(unuran_poisson_seed_varies) {\n        //Confirm that different poisson variates using the same stream will create different outputs:\n\n\n        double mean = 23.1234;\n\n        unuran::StreamWrapper rns1, rns2;\n\n        //NB changing the seed may cause some tests to fail due to overly tight / crude statistical checks.\n\n        //Here we can explicitly use different streams, or use default behaviour\n        //(which  is to feed both from the default random number stream)\n\n        //The advantage to explicitly specifying different streams? MULTI-THREADING.\n        //(Each stream object looks after its own state)\n        //But also, using a specific stream object makes the user aware of the need to supply a seed\n        //(and possibly vary said seed between simulations)\n\n        unuran::PoissonRandomVariate p_gen1(mean, rns1);\n        unuran::PoissonRandomVariate p_gen2(mean, rns1);\n//        unuran_poisson_random_variate p_gen1(mean);\n//        unuran_poisson_random_variate p_gen2(mean);\n\n\n        vector<int> p1, p2;\n\n        for (size_t i=0; i!=10; ++i) {\n            p1.push_back(p_gen1());\n            p2.push_back(p_gen2());\n\n            //visual check:\n//            cout<<i<<\" - rns poisson 1: \"<<gen1()<<\"; rns poisson 2: \"<<gen2()<<endl;\n        }\n\n        CHECK(p1!=p2);\n    }\n\n    TEST(unuran_gaussian) {\n\n        unuran::StreamWrapper rns;\n\n        double mean(5.0), sigma(2.5);\n        unuran::GaussianRandomVariate grv(mean, sigma ,rns);\n\n        size_t n_its=1e5;\n        vector<double> vals; vals.reserve(n_its);\n\n        ofstream datfile(string(test_suite_output_dir+\"gaussian_vals.txt\").c_str());\n\n        for (size_t i=0; i!=n_its; ++i) {\n            vals.push_back(grv());\n            datfile<<vals.back()<<\"\\n\";\n        }\n\n        datfile.close();\n\n//        cout<<\"gaussian limits: \"<< endl;\n//        cout<<\"mean: \"<< 2* sigma/sqrt((double)n_its)<<endl;\n//        cout<<\"sigma: \"<< 2* sigma*sigma/sqrt((double)n_its) <<endl;\n\n//        CHECK_CLOSE(mean, vector_mean(vals),  2*sigma/sqrt((double)n_its));\n//        CHECK_CLOSE(sigma, vector_std_dev(vals),  sigma*sigma/sqrt((double)n_its));\n\n        //Now test the parameter update: (produces weird warning messages, stuff it.)\n//        vals.clear();\n//        mean = 55;\n//        sigma = 15;\n//\n//        grv.update_params(mean,sigma);\n//        for (size_t i=0; i!=n_its;++i){\n//            vals.push_back( grv());\n//        }\n//        CHECK_CLOSE(mean, vector_mean(vals),  sigma/sqrt((double)n_its));\n//        CHECK_CLOSE(sigma, vector_std_dev(vals),  sigma*sigma/sqrt((double)n_its));\n    }\n\n}\n", "meta": {"hexsha": "15aee6432551c4b1bfbd6b6cdf5e1cc418c899f4", "size": 9202, "ext": "cc", "lang": "C++", "max_stars_repo_path": "coela_random/src/unit_tests/test_random.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_random/src/unit_tests/test_random.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_random/src/unit_tests/test_random.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": 28.9371069182, "max_line_length": 112, "alphanum_fraction": 0.5882416866, "num_tokens": 2487, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583376458153, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.49344777770814935}}
{"text": "#include <fstream>\n#include <iostream>\n#include <experimental/filesystem>\n#include <stdio.h>\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/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\n#include \"../tasks.hh\"\n#include \"../classes/BinnedTypedMatrix.hh\"\n\nnamespace fs = std::experimental::filesystem;\n\nusing namespace EMC;\n\nusing namespace boost::numeric::ublas;\n\n/*int EMC::triangulate(bool forceOverwrite, std::string input, std::string output) {\n\n\tif (!forceOverwrite && fs::exists(output)) {\n\t\tstd::cout << \"Output file already exists, use -f to force overwrite.\" << std::endl;\n\t\treturn 1;\n\t}\n\n\tstd::ifstream infile(input);\n\tBinnedTypedMatrix inputMatrix = BinnedTypedMatrix::readFromFile(infile);\n\tinfile.close();\n\n\n\n    std::ofstream outputF(output);\n    inputMatrix.writeToFile(outputF);\n    outputF.close();\n\n    return 0;\n}\n*/\n", "meta": {"hexsha": "bf281008b249273da6290c0a6eb92b1570ad9b7b", "size": 1039, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tasks/triangulate.cpp", "max_stars_repo_name": "pixel-toolbox/error-matrix-calculation", "max_stars_repo_head_hexsha": "29539c9950552f64648932747ab4c07a32004766", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/tasks/triangulate.cpp", "max_issues_repo_name": "pixel-toolbox/error-matrix-calculation", "max_issues_repo_head_hexsha": "29539c9950552f64648932747ab4c07a32004766", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tasks/triangulate.cpp", "max_forks_repo_name": "pixel-toolbox/error-matrix-calculation", "max_forks_repo_head_hexsha": "29539c9950552f64648932747ab4c07a32004766", "max_forks_repo_licenses": ["BSD-3-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.1627906977, "max_line_length": 85, "alphanum_fraction": 0.7324350337, "num_tokens": 257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.49343347523559633}}
{"text": "// A numerically integrated implementation of the circuit described in\n// \"Rolling Your Own Circuit Simulator with Eigen and Boost.ODEInt\"\n// using Eigen to store and manipulate circuit values\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 <array>\n#include <boost/numeric/odeint.hpp>\n#include <Eigen/Dense>\n\n#include \"mna.hpp\"\n\ntypedef std::array<double, 2> state_t;   // 0 = V_out, 1 = I_L\n\nstruct circuit {\n    circuit(double r, double l, double c) {\n\n        using namespace Eigen;\n\n        typedef Matrix<double, 4, 4> matrix4_t;\n        matrix4_t G = matrix4_t::Zero();\n        matrix4_t C = matrix4_t::Zero();\n\n        // state assignment: 0, 1 = node voltages; 2 = I_L, 3 = I_in\n        stamp_r(G, C, 0, 1, r);\n        stamp_c(G, C, 1, c);\n        stamp_l(G, C, 1, 2, l);\n        stamp_i(G, C, 0, 3);           // V_in, I_in\n\n        // input application vector - connects single input to appropriate equation\n        typedef Matrix<double, 4, 1> vector4_t;\n        vector4_t B;\n        B << 0, 0, 0, -1;\n\n        // output extraction vector - connects state element to output\n        Matrix<double, 1, 4> D;\n        D << 0, 1, 0, 0;         // state element idx 1 = V_out\n\n        // Now we have C*dX/dt = -G*X + B*u, and the output is = D * X\n\n        // regularize so C is non-singular\n        // First perform Gaussian elimination with full pivoting\n        // This will put non-zero elements in the upper left, generally\n        auto lu_fact = C.fullPivLu();\n        matrix4_t Cprime = lu_fact.matrixLU().template triangularView<Upper>();\n        \n        // repeat process on G matrix and u vector using the factored components\n        // LU produces a factorization P^-1 * L * U * Q^-1\n        matrix4_t L = lu_fact.matrixLU().template triangularView<UnitLower>();\n        matrix4_t P = lu_fact.permutationP();\n        matrix4_t Q = lu_fact.permutationQ();\n        matrix4_t Gprime = L.fullPivLu().solve(P * G * Q);   // permute rows and columns\n        vector4_t Bprime = L.fullPivLu().solve(P * B);       // rows only\n        Matrix<double, 1, 4> Dprime = D * Q;\n\n        // Use the \"rank\" (# independent rows/columns) to determine where to split\n        int sz = lu_fact.rank();\n        int remainder = 4 - sz;\n\n        // Produce smaller (and hopefully non-singular) matrices for calculation\n        MatrixXd Cnew = Cprime.topLeftCorner(sz, sz);   // the rest is zero\n        \n        // break up Gprime into chunks based on the size of the nonzero portion of Cprime\n        MatrixXd G11  = Gprime.topLeftCorner(sz, sz);\n        MatrixXd G12  = Gprime.topRightCorner(sz, remainder);\n        MatrixXd G21  = Gprime.bottomLeftCorner(remainder, sz);\n        MatrixXd G22  = Gprime.bottomRightCorner(remainder, remainder);\n        \n        // solve for the (sz) state variables we will retain\n        auto G22LU = G22.fullPivLu();\n        MatrixXd Gnew = G11 - G12 * G22LU.solve(G21);\n\n        // adjust input and output connections\n        Matrix<double, Dynamic, 1> Bnew;\n        Bnew = Bprime.topRows(sz) - G12 * G22LU.solve(Bprime.bottomRows(remainder));\n        Matrix<double, 1, Dynamic> Dnew;\n        Dnew = Dprime.leftCols(sz) - Dprime.rightCols(remainder) * G22LU.solve(G21);\n\n        // verify the new C is non-singular\n        assert(Cnew.rows() == Cnew.fullPivLu().rank());\n\n        // factor Cnew out of our equation by multiplying both sides by Cnew^-1\n        // new equation will be dX/dt = - Cnew^-1 * Gnew * X + Cnew^-1 * Bnew * u\n        drift_term_ = - Cnew.fullPivLu().solve(Gnew);\n        input_term_ =   Cnew.fullPivLu().solve(Bnew);\n\n        // Vout may have been moved in the reduction process, so we must supply a map\n        s2o_        = Dnew;\n    }\n\n    double state2output(state_t const& x) const {\n        Eigen::Map<const Eigen::Matrix<double, 2, 1> > xvec(x.data());\n\n        return (s2o_ * xvec)(0, 0);\n    }\n\n    void operator()(state_t const& x, state_t& dxdt, double t) {\n        using namespace Eigen;\n\n        Map<const Matrix<double, 2, 1> > xvec(x.data());\n        Map<Matrix<double, 2, 1> > result(dxdt.data());\n        \n        result = drift_term_ * xvec + input_term_ ;   // input is always 1V\n    }\n\nprivate:\n    Eigen::MatrixXd drift_term_;            // connects current state to development over time\n    Eigen::MatrixXd input_term_;            // connects input to development\n    Eigen::Matrix<double, 1, Eigen::Dynamic> s2o_; // transforms state to output\n};\n\nint main() {\n    using namespace boost::numeric::odeint;\n    circuit ckt(100.0, 20e-6, 20e-9);\n    state_t x{0.0, 0.0};                    // initial conditions\n\n    integrate( ckt, x, 0.0, 10e-6, 0.1e-6,  // time range and increment\n               [ckt](state_t const& x, double t) {\n                   std::cout << t << \" \" << ckt.state2output(x) << std::endl;\n               });\n}\n", "meta": {"hexsha": "39328d6f22301ef171f033e9f96aebd9ba602258", "size": 5900, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "eigen.cpp", "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": "eigen.cpp", "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": "eigen.cpp", "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": 40.9722222222, "max_line_length": 94, "alphanum_fraction": 0.6386440678, "num_tokens": 1572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.6370307875894139, "lm_q1q2_score": 0.493433469897966}}
{"text": "/* Copyright (C) 2012-2017 IBM Corp.\n * This program is Licensed under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *   http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License. See accompanying LICENSE file.\n */\n/* matmul1D.cpp - Data-movement operations on arrays of slots\n */\n#include <algorithm>\n#include <NTL/BasicThreadPool.h>\n#include \"EncryptedArray.h\"\n#include \"matmul.h\"\n//#include \"multiAutomorph.h\"\n\n#if 0\n\n\n// Translate a value x in Zm* to the index e s.t. g_i^e=x (mod m)\n// in a native dimension, returns e in 0..ord_i-1\n// in a non-native dimension, returns e in -ord_i+1..ord_i-1\n// returns -ord_i if it can't find such an e\n\n// For now, this is just done by brute-force search, which is\n// probably good enough.\nstatic\nlong val2index(const PAlgebra& zMStar, long dim, long x)\n{\n  FHE_TIMER_START;\n\n  long m = zMStar.getM();\n  long g = zMStar.ZmStarGen(dim);\n  long ord = zMStar.OrderOf(dim);\n\n  long e = 0;\n  long g2e = 1;\n\n  mulmod_precon_t gminv = PrepMulModPrecon(g, m);\n\n  while (e < ord && g2e != x) {\n    e++;\n    g2e = MulModPrecon(g2e, g, m, gminv);\n  }\n\n  if (e < ord) return e;\n\n  if (zMStar.SameOrd(dim)) return -ord;\n\n  x = MulMod(x, g2e, m);\n\n  e = 0;\n  g2e = 1;\n\n  while (e < ord && g2e != x) {\n    e++;\n    g2e = MulModPrecon(g2e, g, m, gminv);\n  }\n\n  if (e < ord) return e-ord;\n\n  return -ord;\n\n}\n\n\n\n// A class that implements the basic (sparse) 1D matrix-vector functions\ntemplate<class type> class matmul1D_impl {\n  PA_INJECT(type)\n  const MatrixCacheType buildCache;\n  std::unique_ptr<CachedzzxMatrix> zCache;\n  std::unique_ptr<CachedDCRTMatrix> dCache;\n\n  MatMul<type>& mat;\n  const EncryptedArrayDerived<type>& ea;\n\npublic:\n  matmul1D_impl(MatMulBase& _mat, MatrixCacheType tag, long dim)\n    : buildCache(tag), mat(dynamic_cast< MatMul<type>& >(_mat)),\n      ea(_mat.getEA().getDerived(type()))\n  {\n    long D = ea.sizeOfDimension(dim);\n    long sz = ea.nativeDimension(dim) ? D : (2*D-1);\n\n    if (buildCache==cachezzX)\n      zCache.reset(new CachedzzxMatrix(NTL::INIT_SIZE,sz));\n    else if (buildCache==cacheDCRT)\n      dCache.reset(new CachedDCRTMatrix(NTL::INIT_SIZE,sz));\n  }\n\n  // Get the i'th diagonal along dimension dim, encoded as a\n  // single constant. All blocks use the same transofmration.\n  // Returns true if this is a zero diagonal, false otherwise\n  bool processDiagonal1(zzX& cPoly, long dim, long i, long D)\n  {\n    vector<RX> tmpDiag(D);\n    bool zDiag = true; // is this a zero diagonal?\n    long nzLast = -1;  // index of last non-zero entry\n    RX entry;\n\n    // Process the entries in this diagonal one at a time\n    for (long j = 0; j < D; j++) { // process entry j\n      bool zEntry = mat.get(entry, mcMod(j-i, D), j); // entry [j-i mod D, j]\n      assert(zEntry || deg(entry) < ea.getDegree());\n      // get(...) returns true if the entry is empty, false otherwise\n\n      if (!zEntry && IsZero(entry)) zEntry = true;// zero is an empty entry too\n\n      if (!zEntry) {   // not a zero entry\n        zDiag = false; // mark diagonal as non-empty\n\n        // clear entries between last nonzero entry and this one\n        for (long jj = nzLast+1; jj < j; jj++) clear(tmpDiag[jj]);\n        tmpDiag[j] = entry;\n        nzLast = j;\n      }\n    }\n    if (zDiag) return true; // zero diagonal, nothing to do\n\n    // clear trailing zero entries\n    for (long jj = nzLast+1; jj < D; jj++) clear(tmpDiag[jj]);\n\n    vector<RX> diag(ea.size());\n    if (D==1) diag.assign(ea.size(), tmpDiag[0]); // dimension of size one\n    else for (long j = 0; j < ea.size(); j++)\n           diag[j] = tmpDiag[ ea.coordinate(dim,j) ];\n           // rearrange the indexes based on the current dimension\n\n    ea.encode(cPoly, diag);\n    return false; // a nonzero diagonal\n  }\n\n  // Get the i'th diagonal along dimension dim, encoded as a\n  // single constant. Different blocks use different transofmrations.\n  // Returns true if this is a zero diagonal, false otherwise\n  bool processDiagonal2(zzX& poly, long dim, long idx, long D)\n  {\n    bool zDiag = true; // is this a zero diagonal?\n    long nzLast = -1;  // index of last non-zero entry\n    RX entry;\n\n    // Process the entries in this diagonal one at a time\n    long blockIdx, innerIdx;\n    vector<RX> diag(ea.size());\n    for (long j=0; j<ea.size(); j++) {\n      if (D==1) {\n\tblockIdx=j; innerIdx = 0;\n      } else {\n\tstd::tie(blockIdx, innerIdx) // std::pair<long,long> idxes\n\t  = ea.getContext().zMStar.breakIndexByDim(j, dim);\n\t//\tblockIdx = idxes.first;  // which transformation\n\t//\tinnerIdx = idxes.second; // index along diemnssion dim\n      }\n      // process entry j\n      bool zEntry=mat.multiGet(entry,mcMod(innerIdx-idx,D),innerIdx,blockIdx);\n      // entry [i,j-i mod D] in the block corresponding to blockIdx\n      // multiGet(...) returns true if the entry is empty, false otherwise\n\n      // If non-zero, make sure the degree is not too large\n      assert(zEntry || deg(entry) < ea.getDegree());\n\n      if (!zEntry && IsZero(entry)) zEntry = true; // zero is an empty entry too\n\n      if (!zEntry) {   // not a zero entry\n\tzDiag = false; // mark diagonal as non-empty\n\n\t// clear entries between last nonzero entry and this one\n\tfor (long jj = nzLast+1; jj < j; jj++) clear(diag[jj]);\n\tnzLast = j;\n\tdiag[j] = entry;\n      }\n    }\n    if (zDiag) return true; // zero diagonal, nothing to do\n\n    // clear trailing zero entries\n    for (long jj = nzLast+1; jj < ea.size(); jj++) clear(diag[jj]);\n    ea.encode(poly, diag);\n    return false; // a nonzero diagonal\n  }\n\n  void fixup(zzX& cpoly, const RX& c, long i, long signed_i, long dim)\n  {\n    const PAlgebraModDerived<type>& tab = ea.getTab();\n    const vector< vector< RX > >& maskTable = tab.getMaskTable();\n    const RXModulus& PhimXMod = tab.getPhimXMod();\n\n    long D = ea.sizeOfDimension(dim);\n\n    if (signed_i > 0) {\n      RX mask = maskTable[dim][i];\n      MulMod(mask, mask, c, PhimXMod);\n      convert(cpoly, mask);\n    }\n    else {\n      RX mask;\n      NTL::negate(mask, maskTable[dim][i]);\n      MulMod(mask, mask, c, PhimXMod);\n      add(mask, mask, c);\n      convert(cpoly, mask);\n    }\n  }\n\n  void multiply(Ctxt* ctxt, long dim, bool oneTransform)\n  {\n    FHE_TIMER_START;\n\n    assert(dim >= 0 && dim < ea.dimension());\n    RBak bak; bak.save(); ea.getTab().restoreContext(); // backup NTL modulus\n\n\n    std::unique_ptr<Ctxt> res, shCtxt;\n    if (ctxt!=nullptr) { // we need to do an actual multiplication\n      ctxt->cleanUp(); // not sure, but this may be a good idea\n      res.reset(new Ctxt(ZeroCtxtLike, *ctxt));\n      shCtxt.reset(new Ctxt(ZeroCtxtLike, *ctxt));\n    }\n\n    // Check if we have the relevant constant in cache\n    CachedzzxMatrix* zcp;\n    CachedDCRTMatrix* dcp;\n    mat.getCache(&zcp, &dcp);\n\n    // set up the AutoIterator, if we have a ctxt\n    std::unique_ptr<AutoIterator> autoIterator;\n    if (ctxt) {\n      FHE_NTIMER_START(AutoIterator_build);\n      autoIterator.reset(AutoIterator::build(*ctxt, ctxt->getPubKey().getTree4dim(dim)));\n    }\n\n    // Process the diagonals one at a time\n    if (ea.nativeDimension(dim)) {\n      zzX cpoly;\n      long D = ea.sizeOfDimension(dim);\n\n      for (long cnt = 0; cnt < D; cnt++) { // process one diagonal\n\tlong i; //process diagonal i\n\n\n\tif (!ctxt) {\n\t  i = cnt;\n\t}\n\telse if (cnt == 0) {\n\t  i = 0;\n\t  *shCtxt = *ctxt;\n\t}\n\telse {\n          FHE_NTIMER_START(AutoIterator_next);\n\t  long x = autoIterator->next(*shCtxt);\n\t  assert(x !=0);\n\t  i = val2index(ea.getContext().zMStar, dim, x);\n\t  assert(i >= 0);\n\t}\n\n\tzzX* zxPtr=nullptr;\n\tDoubleCRT* dxPtr=nullptr;\n\n\n\tif (dcp != nullptr)         // DoubleCRT cache exists\n\t  dxPtr = (*dcp)[i].get();\n\telse if (zcp != nullptr)    // zzx cache exists but no DoubleCRT\n\t  zxPtr = (*zcp)[i].get();\n\telse { // no cache, compute const\n\t  bool zero = oneTransform? processDiagonal1(cpoly, dim, i, D)\n\t\t\t\t  : processDiagonal2(cpoly, dim, i, D);\n\t  if (!zero) zxPtr = &cpoly; // if it is not a zero value, point to it\n\t}\n\n\t// if zero diagonal, nothing to do for this iteration\n\tif (zxPtr==nullptr && dxPtr==nullptr)\n\t  continue;\n\n\t// Non-zero diagonal, store it in cache and/or multiply/add it\n\n\tif (ctxt) {\n\t  if (dxPtr!=nullptr) shCtxt->multByConstant(*dxPtr);\n\t  else                shCtxt->multByConstant(*zxPtr);\n\n\t  *res += *shCtxt;\n\n\t}\n\n\tif (buildCache==cachezzX) {\n\t  (*zCache)[i].reset(new zzX(*zxPtr));\n\t}\n\telse if (buildCache==cacheDCRT) {\n\t  (*dCache)[i].reset(new DoubleCRT(*zxPtr, ea.getContext()));\n\t}\n      } // end of loop over diagonals\n    }\n    else {\n\n      zzX cpoly;\n      long D = ea.sizeOfDimension(dim);\n\n      std::vector< unique_ptr<RX> > local_cache;\n      if (!dcp && !zcp) {\n        local_cache.resize(D);\n      }\n\n\n      for (long cnt = 0; cnt < 2*D-1; cnt++) { // process one diagonal\n\tlong i; //process diagonal i\n        long signed_i;\n\n\n\tif (!ctxt) {\n          if (cnt == 0) {\n             i = 0;\n             signed_i = 0;\n          }\n          else {\n             i = (cnt+1)/2;\n             signed_i = (cnt % 2) ? (i - D) : i;\n          }\n\t}\n\telse if (cnt == 0) {\n\t  i = 0;\n          signed_i = 0;\n\t  *shCtxt = *ctxt;\n\t}\n\telse {\n\t  long x = autoIterator->next(*shCtxt);\n\t  assert(x !=0);\n\t  signed_i = val2index(ea.getContext().zMStar, dim, x);\n          i = signed_i;\n          if (i < 0) i += D;\n\t}\n\n        long i_off = signed_i + (D-1);\n\n\tzzX* zxPtr=nullptr;\n\tDoubleCRT* dxPtr=nullptr;\n\n\tif (dcp != nullptr)         // DoubleCRT cache exists\n\t  dxPtr = (*dcp)[i_off].get();\n\telse if (zcp != nullptr)    // zzx cache exists but no DoubleCRT\n\t  zxPtr = (*zcp)[i_off].get();\n\telse if (local_cache[i]) {\n          if (*local_cache[i] != 0) {\n             convert(cpoly, *local_cache[i]);\n             zxPtr = &cpoly;\n             if (i) fixup(cpoly, *local_cache[i], i, signed_i, dim);\n          }\n          local_cache[i].reset(); // we've used it, so we can kill it\n        }\n        else { // no cache, compute const\n\t  bool zero = oneTransform? processDiagonal1(cpoly, dim, i, D)\n\t\t\t\t  : processDiagonal2(cpoly, dim, i, D);\n\t  if (!zero) {\n            zxPtr = &cpoly; // if it is not a zero value, point to it\n            local_cache[i].reset(new RX());\n            convert(*local_cache[i], cpoly);\n            if (i) fixup(cpoly, *local_cache[i], i, signed_i, dim);\n          }\n          else {\n            local_cache[i].reset(new RX());\n          }\n\t}\n\n\t// if zero diagonal, nothing to do for this iteration\n\tif (zxPtr==nullptr && dxPtr==nullptr)\n\t  continue;\n\n\t// Non-zero diagonal, store it in cache and/or multiply/add it\n\n\tif (ctxt) {\n\t  if (dxPtr!=nullptr) shCtxt->multByConstant(*dxPtr);\n\t  else                shCtxt->multByConstant(*zxPtr);\n\t  *res += *shCtxt;\n\t}\n\tif (buildCache==cachezzX) {\n\t  (*zCache)[i_off].reset(new zzX(*zxPtr));\n\t}\n\telse if (buildCache==cacheDCRT) {\n\t  (*dCache)[i_off].reset(new DoubleCRT(*zxPtr, ea.getContext()));\n\t}\n      } // end of loop over diagonals\n    }\n\n    if (ctxt) // copy result back to ctxt\n      *ctxt = *res;\n\n    // \"install\" the cache (if needed)\n    if (buildCache == cachezzX)\n      mat.installzzxcache(zCache);\n    else if (buildCache == cacheDCRT)\n      mat.installDCRTcache(dCache);\n  } // end of multiply(...)\n};\n\n// Wrapper functions around the implemenmtation class\nstatic void matmul1d(Ctxt* ctxt, MatMulBase& mat, long dim,\n\t\t     bool oneTransform, MatrixCacheType buildCache)\n{\n  MatMulLock locking(mat, buildCache);\n\n  // If locking.getType()!=cacheEmpty then we really do need to\n  // build the cache, and we also have the lock for it.\n\n  if (locking.getType()==cacheEmpty && ctxt==nullptr) //  nothing to do\n    return;\n\n  switch (mat.getEA().getTag()) {\n    case PA_GF2_tag: {\n      matmul1D_impl<PA_GF2> M(mat, locking.getType(), dim);\n      M.multiply(ctxt, dim, oneTransform);\n      break;\n    }\n    case PA_zz_p_tag: {\n      matmul1D_impl<PA_zz_p> M(mat, locking.getType(), dim);\n      M.multiply(ctxt, dim, oneTransform);\n      break;\n    }\n    default:\n      throw std::logic_error(\"matmul1d: neither PA_GF2 nor PA_zz_p\");\n  }\n}\nvoid buildCache4MatMul1D(MatMulBase& mat, long dim, MatrixCacheType buildCache)\n{ matmul1d(nullptr, mat, dim, true, buildCache); }\n\nvoid matMul1D(Ctxt& ctxt, MatMulBase& mat,long dim, MatrixCacheType buildCache)\n{ matmul1d(&ctxt, mat, dim, true, buildCache); }\n\nvoid buildCache4MatMulti1D(MatMulBase& mat,long dim,MatrixCacheType buildCache)\n{ matmul1d(nullptr, mat, dim, false, buildCache); }\n\nvoid matMulti1D(Ctxt& ctxt,MatMulBase& mat,long dim,MatrixCacheType buildCache)\n{ matmul1d(&ctxt, mat, dim, false, buildCache); }\n\n\n/********************************************************************\n ********************************************************************/\n// Applying matmul to plaintext, useful for debugging\n\ntemplate<class type>\nclass matmul1D_pa_impl {\npublic:\n  PA_INJECT(type)\n\n  static void multiply(NewPlaintextArray& pa, MatMul<type>& mat,\n\t\t       long dim, bool oneTrans)\n  {\n    const EncryptedArrayDerived<type>& ea = mat.getEA().getDerived(type());\n    RBak bak; bak.save(); ea.getTab().restoreContext();\n\n    long n = ea.size();\n    long D = ea.sizeOfDimension(dim);\n\n    vector< vector<RX> > data1(n/D);\n    for (long k = 0; k < n/D; k++)\n      data1[k].resize(D);\n\n    // copy the data into a vector of 1D vectors\n    vector<RX>& data = pa.getData<type>();\n    for (long i = 0; i < n; i++) {\n      long k,j;\n      std::tie(k,j) = ea.getContext().zMStar.breakIndexByDim(i, dim);\n      data1[k][j] = data[i];       // k= along dim, j = the rest of i\n    }\n\n    // multiply each one of the vectors by the same matrix\n    for (long k = 0; k < n/D; k++) {\n      for (long j = 0; j < D; j++) { // simple matrix-vector multiplication\n\tstd::pair<long,long> p(k,j);\n\tlong idx = ea.getContext().zMStar.assembleIndexByDim(p, dim);\n\n\tRX acc, val, tmp;\n\tacc = 0;\n        for (long i = 0; i < D; i++) {\n          bool zero = oneTrans? mat.get(val, i, j) : mat.multiGet(val,i,j,k);\n          if (!zero) {\n            NTL::mul(tmp, data1[k][i], val);\n            NTL::add(acc, acc, tmp);\n          }\n        }\n        rem(data[idx], acc, ea.getG()); // store the result in the data array\n      }\n    }\n  }\n};\n// A wrapper around the implementation class\nstatic void matmul1d(NewPlaintextArray& pa, MatMulBase& mat,\n\t\t     long dim, bool oneTrans)\n{\n  switch (mat.getEA().getTag()) {\n    case PA_GF2_tag: {\n      matmul1D_pa_impl<PA_GF2>::multiply(pa,\n                      dynamic_cast< MatMul<PA_GF2>& >(mat), dim, oneTrans);\n      return;\n    }\n    case PA_zz_p_tag: {\n      matmul1D_pa_impl<PA_zz_p>::multiply(pa,\n                      dynamic_cast<MatMul<PA_zz_p>&>(mat), dim, oneTrans);\n      return;\n    }\n    default:\n      throw std::logic_error(\"matMul1D: neither PA_GF2 nor PA_zz_p\");\n  }\n}\n\nvoid matMul1D(NewPlaintextArray& pa, MatMulBase& mat, long dim)\n{\n  matmul1d(pa, mat, dim, true);\n}\nvoid matMulti1D(NewPlaintextArray& pa, MatMulBase& mat, long dim)\n{\n  matmul1d(pa, mat, dim, false);\n}\n\n\n#else\n\n// baby-step giant-step implementation\n\n\nstruct PtxtPtr {\n  enum Type { ZERO=0, ZZX=1, DCRT=2 };\n  zzX*       zp;\n  DoubleCRT* dp;\n\n  PtxtPtr(): zp(nullptr), dp(nullptr) {}\n};\n\n// A class that implements the basic (sparse) 1D matrix-vector functions\ntemplate<class type> class matmul1D_impl {\n  PA_INJECT(type)\n  const MatrixCacheType buildCache;\n  std::unique_ptr<CachedzzxMatrix> zCache;\n  std::unique_ptr<CachedDCRTMatrix> dCache;\n\n  MatMul<type>& mat;\n  const EncryptedArrayDerived<type>& ea;\n\npublic:\n  matmul1D_impl(MatMulBase& _mat, long dim, MatrixCacheType tag)\n    : buildCache(tag), mat(dynamic_cast< MatMul<type>& >(_mat)),\n      ea(_mat.getEA().getDerived(type()))\n  {\n    if (buildCache==cachezzX) {\n      zCache.reset(new CachedzzxMatrix(NTL::INIT_SIZE,ea.sizeOfDimension(dim)));\n    } else if (buildCache==cacheDCRT) {\n      dCache.reset(new CachedDCRTMatrix(NTL::INIT_SIZE,ea.sizeOfDimension(dim)));\n    }\n  }\n\n  // Get the i'th diagonal along dimension dim, encoded as a\n  // single constant. All blocks use the same transofmration.\n  // Returns true if this is a zero diagonal, false otherwise\n  bool processDiagonal1(zzX& cPoly, long dim, long i, long D, long rotAmt)\n  {\n    vector<RX> tmpDiag(D);\n    bool zDiag = true; // is this a zero diagonal?\n    long nzLast = -1;  // index of last non-zero entry\n    RX entry;\n\n    // Process the entries in this diagonal one at a time\n    for (long j = 0; j < D; j++) { // process entry j\n      long rotJ = (j+rotAmt) % D;  // need to rotate constant by rotAmt\n      bool zEntry = mat.get(entry, mcMod(rotJ-i, D), rotJ); // entry [j-i mod D, j]\n      assert(zEntry || deg(entry) < ea.getDegree());\n      // get(...) returns true if the entry is empty, false otherwise\n\n      if (!zEntry && IsZero(entry)) zEntry = true;// zero is an empty entry too\n\n      if (!zEntry) {   // not a zero entry\n        zDiag = false; // mark diagonal as non-empty\n\n        // clear entries between last nonzero entry and this one\n        for (long jj = nzLast+1; jj < j; jj++) clear(tmpDiag[jj]);\n        tmpDiag[j] = entry;\n        nzLast = j;\n      }\n    }\n    if (zDiag) return true; // zero diagonal, nothing to do\n\n    // clear trailing zero entries\n    for (long jj = nzLast+1; jj < D; jj++) clear(tmpDiag[jj]);\n\n    vector<RX> diag(ea.size());\n    if (D==1) diag.assign(ea.size(), tmpDiag[0]); // dimension of size one\n    else for (long j = 0; j < ea.size(); j++)\n           diag[j] = tmpDiag[ ea.coordinate(dim,j) ];\n           // rearrange the indexes based on the current dimension\n\n    ea.encode(cPoly, diag);\n    return false; // a nonzero diagonal\n  }\n\n  // Get the i'th diagonal along dimension dim, encoded as a\n  // single constant. Different blocks use different transofmrations.\n  // Returns true if this is a zero diagonal, false otherwise\n  bool processDiagonal2(zzX& poly, long dim, long idx, long D, long rotAmt)\n  {\n    bool zDiag = true; // is this a zero diagonal?\n    long nzLast = -1;  // index of last non-zero entry\n    RX entry;\n\n    // Process the entries in this diagonal one at a time\n    long blockIdx, innerIdx;\n    vector<RX> diag(ea.size());\n    for (long j=0; j<ea.size(); j++) {\n      if (D==1) {\n\tblockIdx=j; innerIdx = 0;\n      } else {\n\tstd::tie(blockIdx, innerIdx) // std::pair<long,long> idxes\n\t  = ea.getContext().zMStar.breakIndexByDim(j, dim);\n\t//\tblockIdx = idxes.first;  // which transformation\n\t//\tinnerIdx = idxes.second; // index along diemnssion dim\n        innerIdx = (innerIdx+rotAmt) % D;  // need to rotate constant by rotAmt\n      }\n      // process entry j\n      bool zEntry=mat.multiGet(entry,mcMod(innerIdx-idx,D),innerIdx,blockIdx);\n      // entry [i,j-i mod D] in the block corresponding to blockIdx\n      // multiGet(...) returns true if the entry is empty, false otherwise\n\n      // If non-zero, make sure the degree is not too large\n      assert(zEntry || deg(entry) < ea.getDegree());\n\n      if (!zEntry && IsZero(entry)) zEntry = true; // zero is an empty entry too\n\n      if (!zEntry) {   // not a zero entry\n\tzDiag = false; // mark diagonal as non-empty\n\n\t// clear entries between last nonzero entry and this one\n\tfor (long jj = nzLast+1; jj < j; jj++) clear(diag[jj]);\n\tnzLast = j;\n\tdiag[j] = entry;\n      }\n    }\n    if (zDiag) return true; // zero diagonal, nothing to do\n\n    // clear trailing zero entries\n    for (long jj = nzLast+1; jj < ea.size(); jj++) clear(diag[jj]);\n\n    ea.encode(poly, diag);\n    return false; // a nonzero diagonal\n  }\n\n  // Returns in vec all the constants needed for a single giant-step.\n  // The return value is ZERO(=0) if all these constants are zero.\n  // Otherwise it is ZZX(=1) if using zzX or DCRT(=2) if using DoubleCRT\n  PtxtPtr::Type getConsts(std::vector<PtxtPtr>& vec, std::vector<zzX>& polys,\n                          CachedzzxMatrix* zcp, CachedDCRTMatrix* dcp,\n                          long dim, long jg, long D, bool oneTrans)\n  {\n    PtxtPtr::Type typ = PtxtPtr::ZERO;\n    long g = polys.size(); // how many constants do we need\n    vec.assign(g,PtxtPtr());\n\n    if (dcp!=nullptr) {        // we have DCRT cache\n      for (long i=0, idx=jg; i<g && idx<D; i++, idx++) {\n        if ((vec[i].dp = (*dcp)[idx].get()) != nullptr)\n          typ = PtxtPtr::DCRT;\n      }\n    } else if (zcp!=nullptr) { // we have ZZX cache\n      for (long i=0, idx=jg; i<g && idx<D; i++, idx++) {\n        if ((vec[i].zp = (*zcp)[idx].get()) != nullptr)\n          typ = PtxtPtr::ZZX;\n      }\n    } else {                   // no cache, compute consts\n      for (long i=0, idx=jg; i<g && idx<D; i++, idx++) {\n        bool zero = oneTrans? processDiagonal1(polys[i], dim, idx, D, i)\n                            : processDiagonal2(polys[i], dim, idx, D, i);\n        if (!zero) {\n          vec[i].zp = &(polys[i]); // if not a zero, point to it\n          typ = PtxtPtr::ZZX;\n        }\n      }\n    }\n    return typ;\n  }\n\n  void multiply(Ctxt* ctxt, long dim, bool oneTransform)\n  {\n    assert(dim >= 0 && dim <= ea.dimension());\n    RBak bak; bak.save(); ea.getTab().restoreContext(); // backup NTL modulus\n\n    long D = (dim==ea.dimension())? 1 : ea.sizeOfDimension(dim);\n    long g = mat.getGstep();\n    if (g<1 || g>=D) g=1; // sanity check\n    long dDivg = divc(D,g);\n\n    // Process the diagonals in baby-step/giant-step ordering.\n    //   sum_{i=0}^{d-1} const_i rot^i(X)\n    //   = \\sum_{i=0}^{g-1} \\sum_{j=0}^{d/g -1} const_{i+g*j} rot^{i+g*j}(X)\n    //   = \\sum_{i=0}^{g-1} rot^i(sum_j rot^{-i}(const_{i+g*j}) rot^{g*j}(X))\n    //\n    // so for i=0..g-1 we let\n    //    Y_i = sum_j rot^{-i}(const_{i+g*j}) rot^{g*j}(X)\n    // then compute \\sum_{i=0}^{g-1} rot^i(Y_i).\n    //\n    // Computing the Y_i's, we initialize an accumulator for each Y_i,\n    // then compute the rotations X_j = rot^{g*j}(X), j=0,...,d/g-1.\n    // Each X_j is multiplied by all the constants rot^{-i}(const_{i+g*j}),\n    // i=0,...,g-1, and the i'th product is added to the accumulator for\n    // the corresponding Y_i.\n\n    long lastRotate = 0;\n    std::vector<Ctxt> acc; // accumulators\n    if (ctxt!=nullptr) {   // we need to do an actual multiplication\n      ctxt->cleanUp();     // not sure, but this may be a good idea\n      Ctxt tmp(ZeroCtxtLike, *ctxt);\n      acc.resize(g, tmp);\n    }\n\n    // Check if we have the relevant constant in cache\n    CachedzzxMatrix* zcp;\n    CachedDCRTMatrix* dcp;\n    mat.getCache(&zcp, &dcp);\n\n    // Process the diagonals in giant-step/baby-step order\n    std::vector<zzX> cpolys(g); // scratch space for encoding consts\n    std::vector<PtxtPtr> ptrs;  // pointers to these constants\n    for (long j = 0; j < dDivg; j++) { // giant steps\n      long jg = j*g;            // beginning index of this giant step\n\n      // get all the constants rot^{-i}(const_{i+g*j}) for this step\n      PtxtPtr::Type ty = getConsts(ptrs, cpolys, zcp, dcp,\n                                   dim, jg, D, oneTransform);\n\n      if (ty==PtxtPtr::ZERO) continue; // all consts are zero\n\n      // Store constants in cache and/or multiply/add them\n\n      if (ctxt!=nullptr) {  // rotate by jg, multiply & add\n        Ctxt shCtxt(*ctxt); // temporary to hold current rot^{g*j}(X)\n\n        if (j>0) {\n          shCtxt = *ctxt;\n          ea.rotate1D(shCtxt, dim, jg); // rotate by i\n\t} // if j==0 we already have *shCtxt == *ctxt\n\n        if (ty==PtxtPtr::DCRT) for (long i=0; i<min(g,D-jg); i++) {\n            if (ptrs[i].dp!=nullptr) {\n              Ctxt tmp(shCtxt);\n              tmp.multByConstant(*(ptrs[i].dp));\n              acc[i] += tmp;\n            }\n          }\n        else /*ty==PtxtPtr::ZZX*/ for (long i=0; i<min(g,D-jg); i++) {\n            if (ptrs[i].zp!=nullptr) {\n              Ctxt tmp(shCtxt);\n              tmp.multByConstant(*(ptrs[i].zp));\n              acc[i] += tmp;\n            }\n          }\n      }\n\n      if (buildCache==cachezzX) for (long i=0; i<min(g,D-jg); i++) {\n          if (ptrs[i].zp!=nullptr)\n            (*zCache)[i+jg].reset(new zzX(*(ptrs[i].zp)));\n        }\n      else if (buildCache==cacheDCRT) for (long i=0; i<min(g,D-jg); i++) {\n          if (ptrs[i].zp!=nullptr)\n            (*dCache)[i+jg].reset(new DoubleCRT(*(ptrs[i].zp),ea.getContext()));\n        }\n      // end of giant-step loop\n    }\n    // Compute the result as \\sum_{i=0}^{g-1} rho^i(Y_i)\n    if (ctxt!=nullptr) {\n      *ctxt = acc[0];\n      for (long i = 1; i < g; i++) {\n        ea.rotate1D(acc[i], dim, i);\n        *ctxt += acc[i];\n      }\n    }\n    // \"install\" the cache if needed\n    if (buildCache == cachezzX)\n      mat.installzzxcache(zCache);\n    else if (buildCache == cacheDCRT)\n      mat.installDCRTcache(dCache);\n  } // end of multiply(...)\n};\n\n// Wrapper functions around the implemenmtation class\nstatic void matmul1d(Ctxt* ctxt, MatMulBase& mat, long dim, bool oneTransform,\n                     MatrixCacheType buildCache)\n{\n  MatMulLock locking(mat, buildCache);\n\n  // If locking.getType()!=cacheEmpty then we really do need to\n  // build the cache, and we also have the lock for it.\n\n  if (locking.getType()==cacheEmpty && ctxt==nullptr) //  nothing to do\n    return;\n\n  switch (mat.getEA().getTag()) {\n    case PA_GF2_tag: {\n      matmul1D_impl<PA_GF2> M(mat, dim, locking.getType());\n      M.multiply(ctxt, dim, oneTransform);\n      break;\n    }\n    case PA_zz_p_tag: {\n      matmul1D_impl<PA_zz_p> M(mat, dim, locking.getType());\n      M.multiply(ctxt, dim, oneTransform);\n      break;\n    }\n    default:\n      throw std::logic_error(\"matmul1d: neither PA_GF2 nor PA_zz_p\");\n  }\n}\nvoid buildCache4MatMul1D(MatMulBase& mat, long dim,\n                         MatrixCacheType buildCache)\n{ matmul1d(nullptr, mat, dim, true, buildCache); }\n\nvoid matMul1D(Ctxt& ctxt, MatMulBase& mat,long dim,\n              MatrixCacheType buildCache)\n{ matmul1d(&ctxt, mat, dim, true, buildCache); }\n\nvoid buildCache4MatMulti1D(MatMulBase& mat,long dim,\n                           MatrixCacheType buildCache)\n{ matmul1d(nullptr, mat, dim, false, buildCache); }\n\nvoid matMulti1D(Ctxt& ctxt,MatMulBase& mat,long dim,\n                MatrixCacheType buildCache)\n{ matmul1d(&ctxt, mat, dim, false, buildCache); }\n\n\n/********************************************************************\n ********************************************************************/\n// Applying matmul to plaintext, useful for debugging\n\ntemplate<class type>\nclass matmul1D_pa_impl {\npublic:\n  PA_INJECT(type)\n\n  static void multiply(NewPlaintextArray& pa, MatMul<type>& mat,\n\t\t       long dim, bool oneTrans)\n  {\n    const EncryptedArrayDerived<type>& ea = mat.getEA().getDerived(type());\n    RBak bak; bak.save(); ea.getTab().restoreContext();\n\n    long n = ea.size();\n    long D = ea.sizeOfDimension(dim);\n\n    vector< vector<RX> > data1(n/D);\n    for (long k = 0; k < n/D; k++)\n      data1[k].resize(D);\n\n    // copy the data into a vector of 1D vectors\n    vector<RX>& data = pa.getData<type>();\n    for (long i = 0; i < n; i++) {\n      long k,j;\n      std::tie(k,j) = ea.getContext().zMStar.breakIndexByDim(i, dim);\n      data1[k][j] = data[i];       // k= along dim, j = the rest of i\n    }\n\n    // multiply each one of the vectors by the same matrix\n    for (long k = 0; k < n/D; k++) {\n      for (long j = 0; j < D; j++) { // simple matrix-vector multiplication\n\tstd::pair<long,long> p(k,j);\n\tlong idx = ea.getContext().zMStar.assembleIndexByDim(p, dim);\n\n\tRX acc, val, tmp;\n\tacc = 0;\n        for (long i = 0; i < D; i++) {\n          bool zero = oneTrans? mat.get(val, i, j) : mat.multiGet(val,i,j,k);\n          if (!zero) {\n            NTL::mul(tmp, data1[k][i], val);\n            NTL::add(acc, acc, tmp);\n          }\n        }\n        rem(data[idx], acc, ea.getG()); // store the result in the data array\n      }\n    }\n  }\n};\n// A wrapper around the implementation class\nstatic void matmul1d(NewPlaintextArray& pa, MatMulBase& mat,\n\t\t     long dim, bool oneTrans)\n{\n  switch (mat.getEA().getTag()) {\n    case PA_GF2_tag: {\n      matmul1D_pa_impl<PA_GF2>::multiply(pa,\n                      dynamic_cast< MatMul<PA_GF2>& >(mat), dim, oneTrans);\n      return;\n    }\n    case PA_zz_p_tag: {\n      matmul1D_pa_impl<PA_zz_p>::multiply(pa,\n                      dynamic_cast<MatMul<PA_zz_p>&>(mat), dim, oneTrans);\n      return;\n    }\n    default:\n      throw std::logic_error(\"matMul1D: neither PA_GF2 nor PA_zz_p\");\n  }\n}\n\nvoid matMul1D(NewPlaintextArray& pa, MatMulBase& mat, long dim)\n{\n  matmul1d(pa, mat, dim, true);\n}\nvoid matMulti1D(NewPlaintextArray& pa, MatMulBase& mat, long dim)\n{\n  matmul1d(pa, mat, dim, false);\n}\n\n#endif\n", "meta": {"hexsha": "a945e42cac0e9ab7cd43fa4b1f9098939bd8d021", "size": 28738, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "misc/matmul1D.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": "misc/matmul1D.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": "misc/matmul1D.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": 31.8250276855, "max_line_length": 89, "alphanum_fraction": 0.5984758856, "num_tokens": 8517, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.493433468605885}}
{"text": "/*********************************************************************\n*  Copyright (c) 2017 Robert Bosch GmbH.\n*  All rights reserved.\n*\n*  Licensed under the Apache License, Version 2.0 (the \"License\");\n*  you may not use this file except in compliance with the License.\n*  You may obtain a copy of the License at\n*\n*      http://www.apache.org/licenses/LICENSE-2.0\n*\n*  Unless required by applicable law or agreed to in writing, software\n*  distributed under the License is distributed on an \"AS IS\" BASIS,\n*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n*  See the License for the specific language governing permissions and\n*  limitations under the License.\n* *********************************************************************/\n\n#include <gtest/gtest.h>\n\n#include <Eigen/Dense>\n\n#include \"steering_functions/filter/ekf.hpp\"\n#include \"steering_functions/steering_functions.hpp\"\n#include \"steering_functions/utilities/utilities.hpp\"\n\nusing namespace std;\nusing namespace steer;\n\n#define EPS_JACOBI 1e-4                  // [-]\n#define EPS_PERTURB 1e-7                 // [-]\n#define SAMPLES 1e6                      // [-]\n#define OPERATING_REGION_X 20.0          // [m]\n#define OPERATING_REGION_Y 20.0          // [m]\n#define OPERATING_REGION_THETA 2 * M_PI  // [rad]\n#define OPERATING_REGION_KAPPA 2.0       // [1/m]\n#define OPERATING_REGION_DELTA_S 0.4     // [m]\n#define OPERATING_REGION_SIGMA 2.0       // [1/m^2]\n#define random(lower, upper) (rand() * (upper - lower) / RAND_MAX + lower)\n#define random_boolean() rand() % 2\n\ntypedef Eigen::Matrix<double, 2, 2> Matrix2d;\ntypedef Eigen::Matrix<double, 3, 3> Matrix3d;\ntypedef Eigen::Matrix<double, 3, 2> Matrix32d;\n\nState get_random_state()\n{\n  State state;\n  state.x = random(-OPERATING_REGION_X / 2.0, OPERATING_REGION_X / 2.0);\n  state.y = random(-OPERATING_REGION_Y / 2.0, OPERATING_REGION_Y / 2.0);\n  state.theta = random(-OPERATING_REGION_THETA / 2.0, OPERATING_REGION_THETA / 2.0);\n  state.kappa = random(-OPERATING_REGION_KAPPA / 2.0, OPERATING_REGION_KAPPA / 2.0);\n  state.d = 0.0;\n  return state;\n}\n\nControl get_random_control()\n{\n  Control control;\n  control.delta_s = random(-OPERATING_REGION_DELTA_S / 2.0, OPERATING_REGION_DELTA_S / 2.0);\n  control.sigma = random(-OPERATING_REGION_SIGMA / 2.0, OPERATING_REGION_SIGMA / 2.0);\n  return control;\n}\n\nState integrate_ODE(const State &state, const Control &control, double integration_step)\n{\n  State state_next;\n  double sigma(control.sigma);\n  double d(sgn(control.delta_s));\n  if (fabs(sigma) > get_epsilon())\n  {\n    end_of_clothoid(state.x, state.y, state.theta, state.kappa, sigma, d, integration_step, &state_next.x,\n                    &state_next.y, &state_next.theta, &state_next.kappa);\n  }\n  else\n  {\n    if (fabs(state.kappa) > get_epsilon())\n    {\n      end_of_circular_arc(state.x, state.y, state.theta, state.kappa, d, integration_step, &state_next.x, &state_next.y,\n                          &state_next.theta);\n    }\n    else\n    {\n      end_of_straight_line(state.x, state.y, state.theta, d, integration_step, &state_next.x, &state_next.y);\n    }\n  }\n  state_next.theta =\n      pify(state.theta + state.kappa * d * integration_step + 0.5 * sigma * d * integration_step * integration_step);\n  state_next.kappa = state.kappa + sigma * integration_step;\n  state_next.d = d;\n\n  return state_next;\n}\n\nMatrix3d get_num_motion_jacobi_x(const State &state, const Control &control, double integration_step)\n{\n  Matrix3d F_x;\n  Matrix3d perturb(EPS_PERTURB * Matrix3d::Identity());\n\n  State f_x = integrate_ODE(state, control, integration_step);\n  for (int i = 0; i < F_x.cols(); ++i)\n  {\n    // perturb x, y, theta\n    State state_perturb;\n    state_perturb.x = state.x + perturb(0, i);\n    state_perturb.y = state.y + perturb(1, i);\n    state_perturb.theta = state.theta + perturb(2, i);\n    state_perturb.kappa = state.kappa;\n\n    State f_x_perturb = integrate_ODE(state_perturb, control, integration_step);\n    F_x(0, i) = (f_x_perturb.x - f_x.x) / perturb(i, i);\n    F_x(1, i) = (f_x_perturb.y - f_x.y) / perturb(i, i);\n    F_x(2, i) = (f_x_perturb.theta - f_x.theta) / perturb(i, i);\n  }\n  return F_x;\n}\n\nMatrix32d get_num_motion_jacobi_u(const State &state, const Control &control, double integration_step)\n{\n  Matrix32d F_u;\n  Matrix2d perturb(EPS_PERTURB * Matrix2d::Identity());\n\n  State f_u = integrate_ODE(state, control, integration_step);\n  for (int i = 0; i < F_u.cols(); ++i)\n  {\n    // perturb delta_s and kappa\n    Control control_perturb;\n    control_perturb.delta_s = control.delta_s + perturb(0, i);\n    control_perturb.sigma = control.sigma;\n    double integration_step_perturb = fabs(control_perturb.delta_s);\n\n    State state_perturb;\n    state_perturb.x = state.x;\n    state_perturb.y = state.y;\n    state_perturb.theta = state.theta;\n    state_perturb.kappa = state.kappa + perturb(1, i);\n\n    State f_u_perturb = integrate_ODE(state_perturb, control_perturb, integration_step_perturb);\n    F_u(0, i) = (f_u_perturb.x - f_u.x) / perturb(i, i);\n    F_u(1, i) = (f_u_perturb.y - f_u.y) / perturb(i, i);\n    F_u(2, i) = (f_u_perturb.theta - f_u.theta) / perturb(i, i);\n  }\n  return F_u;\n}\n\nTEST(Jacobian, F_x)\n{\n  EKF ekf;\n  for (int i = 0; i < SAMPLES; i++)\n  {\n    State state = get_random_state();\n    Control control = get_random_control();\n\n    state.kappa = random_boolean() * state.kappa;\n    control.sigma = random_boolean() * control.sigma;\n    double integration_step = fabs(control.delta_s);\n\n    Matrix3d F_x_ana(Matrix3d::Zero());\n    Matrix32d F_u_ana(Matrix32d::Zero());\n    ekf.get_motion_jacobi(state, control, integration_step, F_x_ana, F_u_ana);\n    Matrix3d F_x_num = get_num_motion_jacobi_x(state, control, integration_step);\n    for (int i = 0; i < F_x_ana.rows(); ++i)\n    {\n      for (int j = 0; j < F_x_ana.cols(); ++j)\n      {\n        EXPECT_LE(fabs(F_x_ana(i, j) - F_x_num(i, j)), EPS_JACOBI);\n      }\n    }\n  }\n}\n\nTEST(Jacobian, F_u)\n{\n  EKF ekf;\n  for (int i = 0; i < SAMPLES; i++)\n  {\n    State state = get_random_state();\n    Control control = get_random_control();\n\n    state.kappa = random_boolean() * state.kappa;\n    control.sigma = random_boolean() * control.sigma;\n    double integration_step = fabs(control.delta_s);\n\n    Matrix3d F_x_ana(Matrix3d::Zero());\n    Matrix32d F_u_ana(Matrix32d::Zero());\n    ekf.get_motion_jacobi(state, control, integration_step, F_x_ana, F_u_ana);\n    Matrix32d F_u_num = get_num_motion_jacobi_u(state, control, integration_step);\n    for (int i = 0; i < F_u_ana.rows(); ++i)\n    {\n      for (int j = 0; j < F_u_ana.cols(); ++j)\n      {\n        EXPECT_LE(fabs(F_u_ana(i, j) - F_u_num(i, j)), EPS_JACOBI);\n      }\n    }\n  }\n}\n\nint main(int argc, char **argv)\n{\n  testing::InitGoogleTest(&argc, argv);\n  return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "7666ccec836d05e2753931e1719cc9196d378fd9", "size": 6777, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/jacobian_test.cpp", "max_stars_repo_name": "nobleo/steering_functions", "max_stars_repo_head_hexsha": "f3564e2ad53259485e7eebe91d674d211783be61", "max_stars_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_stars_count": 116.0, "max_stars_repo_stars_event_min_datetime": "2018-01-28T05:11:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T14:46:10.000Z", "max_issues_repo_path": "test/jacobian_test.cpp", "max_issues_repo_name": "nobleo/steering_functions", "max_issues_repo_head_hexsha": "f3564e2ad53259485e7eebe91d674d211783be61", "max_issues_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2018-04-30T19:26:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T21:13:15.000Z", "max_forks_repo_path": "test/jacobian_test.cpp", "max_forks_repo_name": "nobleo/steering_functions", "max_forks_repo_head_hexsha": "f3564e2ad53259485e7eebe91d674d211783be61", "max_forks_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_forks_count": 66.0, "max_forks_repo_forks_event_min_datetime": "2017-10-05T09:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T04:50:50.000Z", "avg_line_length": 33.5495049505, "max_line_length": 120, "alphanum_fraction": 0.6604692342, "num_tokens": 1988, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.49343345130091265}}
{"text": "//\n//! Copyright \u00a9 2017\n//! Brandon Kohn\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 GEOMETRIX_ARITHMETIC_MATRIX_TRACE_HPP\n#define GEOMETRIX_ARITHMETIC_MATRIX_TRACE_HPP\n\n#include <geometrix/tensor/matrix_traits.hpp>\n#include <boost/concept/assert.hpp>\n\nnamespace geometrix {\n    \n    namespace detail{\n        \n        template<std::size_t I, typename Sum, typename Matrix>\n        struct trace_sum\n        {\n        private:\n            using next_t = trace_sum<I-1, decltype(std::declval<typename type_at<Matrix, I-1, I-1>::type>() + std::declval<Sum>()), Matrix>;\n        public:\n        \n            using type = typename next_t::type;\n        \n            static type apply(const Matrix& m, const Sum& s)\n            {\n                return next_t::apply(m, s + get<I-1,I-1>(m));\n            }\n        };\n        \n        template<typename Sum, typename Matrix>\n        struct trace_sum<0, Sum, Matrix>\n        {\n            using type = decltype(std::declval<typename type_at<Matrix, 0, 0>::type>() + std::declval<Sum>());\n            \n            static type apply(const Matrix&, const Sum& s)\n            {\n                return s;\n            }\n        };\n    }//! namespace detail;\n\n    //! Trace of a Matrix - Sum of the diagonals.\n    namespace result_of {\n        \n        template <typename Matrix>\n        struct trace \n            : ::geometrix::detail::trace_sum\n              <\n                geometric_traits<Matrix>::row_dimension::value - 2\n              , typename type_at<Matrix, geometric_traits<Matrix>::row_dimension::value - 1, geometric_traits<Matrix>::row_dimension::value - 1>::type\n              , Matrix\n              >\n        {};\n        \n    }//! namespace result_of;\n    \n    template <typename Matrix>\n    inline typename result_of::trace<Matrix>::type trace(const Matrix& m)\n    {\n        BOOST_CONCEPT_ASSERT(( SquareMatrixConcept<Matrix> ));        \n        auto v = get<geometric_traits<Matrix>::row_dimension::value - 1,geometric_traits<Matrix>::row_dimension::value - 1>(m);\n        return detail::trace_sum<geometric_traits<Matrix>::row_dimension::value - 1, decltype(v), Matrix>::apply(m, v);\n    }\n    \n}//namespace geometrix;\n\n#endif//GEOMETRIX_ARITHMETIC_MATRIX_TRACE_HPP\n", "meta": {"hexsha": "5d0d82b35fbbeab90271c7d7a1e0aeb531a41976", "size": 2352, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "geometrix/arithmetic/matrix/trace.hpp", "max_stars_repo_name": "brandon-kohn/Geometrix", "max_stars_repo_head_hexsha": "e107e13b469632c7d12cb236bd4fb8b17ff928e3", "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": "geometrix/arithmetic/matrix/trace.hpp", "max_issues_repo_name": "brandon-kohn/Geometrix", "max_issues_repo_head_hexsha": "e107e13b469632c7d12cb236bd4fb8b17ff928e3", "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": "geometrix/arithmetic/matrix/trace.hpp", "max_forks_repo_name": "brandon-kohn/Geometrix", "max_forks_repo_head_hexsha": "e107e13b469632c7d12cb236bd4fb8b17ff928e3", "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.6666666667, "max_line_length": 150, "alphanum_fraction": 0.5922619048, "num_tokens": 556, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879312056025699, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.4933427888144275}}
{"text": "#include \"plane_fitting.h\"\n\n#include <Eigen/Dense>\n#include \"util/mirrored_memory.h\"\n\nnamespace dart {\n\nvoid fitPlane(float3 & planeNormal,\n              float & planeIntercept,\n              const float4 * dObsVertMap,\n              const float4 * dObsNormMap,\n              const int width,\n              const int height,\n              const float distanceThreshold,\n              const float normalThreshold,\n              const int maxIters,\n              const float regularization,\n              int * dbgAssociated) {\n\n    dart::MirroredVector<float> result(4 + 16 + 1);\n\n\n    for (int iter=0; iter<maxIters; ++iter) {\n\n        cudaMemset(result.devicePtr(),0,(1+4+16)*sizeof(float));\n\n        fitPlaneIter(planeNormal,\n                     planeIntercept,\n                     dObsVertMap,\n                     dObsNormMap,\n                     width,\n                     height,\n                     distanceThreshold,\n                     normalThreshold,\n                     regularization,\n                     result.devicePtr(),\n                     dbgAssociated);\n\n        result.syncDeviceToHost();\n\n        Eigen::MatrixXf JTJ = regularization*Eigen::MatrixXf::Identity(4,4);\n        Eigen::VectorXf eJ = Eigen::VectorXf::Zero(4,1);\n\n        for (int i=0; i<4; ++i) {\n            eJ(i) = result.hostPtr()[i];\n            for(int j=0; j<4; ++j) {\n                JTJ(i,j) += result.hostPtr()[4 + j + i*4];\n            }\n        }\n\n        //std::cout << \"JTJ: \\n\" << JTJ << std::endl;\n        //std::cout << \"eJ: \\n\" << eJ << std::endl;\n\n        Eigen::VectorXf update = -JTJ.ldlt().solve(eJ);\n\n        //std::cout << \"error: \" << result.hostPtr()[4+16] << std::endl;\n        //std::cout << \"update: \" << update << std::endl;\n\n        planeNormal.x += update(0);\n        planeNormal.y += update(1);\n        planeNormal.z += update(2);\n        planeIntercept += update(3);\n\n        planeNormal = normalize(planeNormal);\n\n        //std::cout << \"new normal \" << planeNormal.x << \", \" << planeNormal.y << \", \" << planeNormal.z << std::endl;\n        //std::cout << \"new intercept \" << planeIntercept << std::endl;\n    }\n\n}\n\n}\n", "meta": {"hexsha": "c38986a10dbc417f2ce47a14a8fdf23986312059", "size": 2142, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/geometry/plane_fitting.cpp", "max_stars_repo_name": "bartyang9/dart", "max_stars_repo_head_hexsha": "f99746acef3eeaef377f671d40b347d08fe4fd2d", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 101.0, "max_stars_repo_stars_event_min_datetime": "2016-04-29T08:42:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T11:04:53.000Z", "max_issues_repo_path": "src/geometry/plane_fitting.cpp", "max_issues_repo_name": "bartyang9/dart", "max_issues_repo_head_hexsha": "f99746acef3eeaef377f671d40b347d08fe4fd2d", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2016-06-30T07:40:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T03:14:11.000Z", "max_forks_repo_path": "src/geometry/plane_fitting.cpp", "max_forks_repo_name": "bartyang9/dart", "max_forks_repo_head_hexsha": "f99746acef3eeaef377f671d40b347d08fe4fd2d", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2016-04-04T09:12:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T06:34:29.000Z", "avg_line_length": 29.3424657534, "max_line_length": 117, "alphanum_fraction": 0.4957983193, "num_tokens": 525, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879312056025699, "lm_q2_score": 0.6261241842048093, "lm_q1q2_score": 0.49334278331742093}}
{"text": "#pragma once\n\n#include \"../typedstateobserver.hh\"\n#include \"../../StateObject/HardwareState/hardwarestate.hh\"\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\nnamespace bold\n{\n  enum class OrientationTechnique\n  {\n    Madgwick = 0,\n    Sum = 1\n  };\n\n  template<typename> class Setting;;\n\n  /** Tracks the orientation of the torso using data from the IMU.\n   */\n  class OrientationTracker : public TypedStateObserver<HardwareState>\n  {\n  public:\n    OrientationTracker();\n\n    Eigen::Quaterniond getQuaternion() const;\n\n    void reset();\n\n  private:\n    void observeTyped(std::shared_ptr<HardwareState const> const& state, SequentialTimer& timer) override;\n\n    void updateMadgwick(std::shared_ptr<HardwareState const> const& state);\n\n    void updateSum(std::shared_ptr<HardwareState const> const& state);\n\n    // estimated orientation quaternion elements\n    float SEq_1, SEq_2, SEq_3, SEq_4;\n    Setting<OrientationTechnique>* d_technique;\n  };\n}\n", "meta": {"hexsha": "0930dffa9a64b7e49eecad3faf91a821632608d8", "size": 949, "ext": "hh", "lang": "C++", "max_stars_repo_path": "StateObserver/OrientationTracker/orientationtracker.hh", "max_stars_repo_name": "drewnoakes/bold-humanoid", "max_stars_repo_head_hexsha": "6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "StateObserver/OrientationTracker/orientationtracker.hh", "max_issues_repo_name": "drewnoakes/bold-humanoid", "max_issues_repo_head_hexsha": "6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "StateObserver/OrientationTracker/orientationtracker.hh", "max_forks_repo_name": "drewnoakes/bold-humanoid", "max_forks_repo_head_hexsha": "6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335", "max_forks_repo_licenses": ["Apache-2.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.5952380952, "max_line_length": 106, "alphanum_fraction": 0.7207586934, "num_tokens": 229, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.49334278257843395}}
{"text": "#include <gtest/gtest.h>\n#include <stan/math/rev/core.hpp>\n#include <stan/math/rev.hpp>\n#include <stan/math/torsten/dsolve/pmx_ode_system.hpp>\n#include <stan/math/torsten/dsolve/pmx_odeint_integrator.hpp>\n#include <stan/math/torsten/dsolve/pmx_integrate_ode_rk45.hpp>\n#include <stan/math/torsten/dsolve/pmx_integrate_ode_bdf.hpp>\n#include <stan/math/torsten/dsolve/pmx_ode_rk45.hpp>\n#include <stan/math/torsten/dsolve/pmx_ode_bdf.hpp>\n#include <stan/math/torsten/dsolve/pmx_ode_adams.hpp>\n#include <stan/math/torsten/dsolve/pmx_ode_ckrk.hpp>\n#include <stan/math/torsten/test/unit/pmx_ode_test_fixture.hpp>\n#include <boost/numeric/odeint/external/eigen/eigen_algebra.hpp>\n#include <boost/fusion/adapted/std_tuple.hpp>\n#include <boost/fusion/include/algorithm.hpp>\n\nTEST_F(TorstenOdeTest_sho, variadic_ode_system_odeint) {\n  using torsten::dsolve::PMXVariadicOdeSystem;\n  using stan::math::value_of;\n  using stan::math::to_var;\n  \n  y0[1] = 0.5;\n  y0_vec[1] = 0.5;\n  Eigen::Matrix<stan::math::var, -1, 1> y0_var(to_var(y0_vec));\n  std::vector<stan::math::var> theta_var(to_var(theta));\n\n  PMXVariadicOdeSystem<harm_osc_ode_fun_eigen, double, stan::math::var,\n                       std::vector<stan::math::var>, std::vector<double>, std::vector<int>>\n    ode(f_eigen, 0.0, ts, y0_var, nullptr, theta_var, x_r, x_i);\n\n  Eigen::VectorXd dydt = f_eigen(ts[0], y0_vec, nullptr, theta, x_r, x_i);\n\n  Eigen::VectorXd ydot = ode.dbl_rhs_impl(ts[0], y0_vec);\n  EXPECT_FLOAT_EQ(ydot[0], dydt[0]);\n  EXPECT_FLOAT_EQ(ydot[1], dydt[1]);\n\n  torsten::dsolve::PMXOdeSystem<harm_osc_ode_fun, double, stan::math::var, stan::math::var>\n    ode0(f, 0.0, ts, to_var(y0), theta_var, x_r, x_i, nullptr);\n  std::vector<double> dydt_vec(ode.system_size), dydt_vec2(ode.system_size);\n  ode0(ode0.y0_fwd_system, dydt_vec, ts[0]);\n\n  ode(ode.y0_fwd_system, dydt_vec2, ts[0]);\n  EXPECT_EQ(ode.system_size, ode0.system_size);\n  for (size_t i = 0; i < ode0.system_size; ++i) {\n    EXPECT_FLOAT_EQ(dydt_vec2[i], dydt_vec[i]);\n  }\n}\n\nTEST_F(TorstenOdeTest_sho, variadic_ode_system_cvodes) {\n  using torsten::dsolve::PMXVariadicOdeSystem;\n  \n  using stan::math::value_of;\n  using stan::math::to_var;\n  \n  y0[1] = 0.5;\n  y0_vec[1] = 0.5;\n\n  Eigen::Matrix<stan::math::var, -1, 1> y0_var(to_var(y0_vec));\n  std::vector<stan::math::var> theta_var(to_var(theta));\n\n  PMXVariadicOdeSystem<harm_osc_ode_fun_eigen, double, stan::math::var,\n                       std::vector<stan::math::var>, std::vector<double>, std::vector<int>>\n    ode(f_eigen, 0.0, ts, y0_var, nullptr, theta_var, x_r, x_i);\n\n  Eigen::VectorXd dydt = f_eigen(ts[0], y0_vec, nullptr, theta, x_r, x_i);\n  N_Vector nv_y(N_VNew_Serial(2));\n  N_Vector ydot(N_VNew_Serial(2));\n  NV_Ith_S(nv_y, 0) = y0[0];\n  NV_Ith_S(nv_y, 1) = y0[1];\n  ode(ts[0], nv_y, ydot);\n  EXPECT_FLOAT_EQ(NV_Ith_S(ydot, 0), dydt[0]);\n  EXPECT_FLOAT_EQ(NV_Ith_S(ydot, 1), dydt[1]);\n  N_VDestroy(nv_y);\n  N_VDestroy(ydot);\n}\n\nTEST_F(TorstenOdeTest_sho, eigen_vector_rk45) {\n  using torsten::dsolve::PMXVariadicOdeSystem;\n  \n  using stan::math::value_of;\n  using torsten::dsolve::PMXOdeintIntegrator;\n\n  {                             // data only\n    auto y = torsten::pmx_ode_rk45_ctrl(f_eigen, y0_vec, t0, ts, msgs, rtol, atol, max_num_steps,\n                                        theta, x_r, x_i);\n    auto y_sol = torsten::pmx_integrate_ode_rk45(f, y0, t0, ts,\n                                                 theta, x_r, x_i, rtol, atol, max_num_steps, msgs);\n    for (size_t j = 0; j < ts.size(); ++j) {\n      for (size_t i = 0; i < y0.size(); ++i) {\n        EXPECT_FLOAT_EQ(y[j][i], y_sol[j][i]);\n      }\n    }\n  }\n\n  {                             // theat var\n    std::vector<stan::math::var> theta_var(stan::math::to_var(theta));\n    auto y = torsten::pmx_ode_rk45_ctrl(f_eigen, y0_vec, t0, ts, msgs, rtol, atol, max_num_steps,\n                                        theta_var, x_r, x_i);\n    auto y_sol = stan::math::ode_rk45_tol(f_eigen, y0_vec, t0, ts, rtol, atol, max_num_steps, msgs,\n                                          theta_var, x_r, x_i);\n    for (size_t j = 0; j < ts.size(); ++j) {\n      torsten::test::test_grad(theta_var, y_sol[j], y[j], 1e-8, 1e-8);\n    }\n  }\n\n  {                             // theat & y0 var\n    std::vector<stan::math::var> theta_var(stan::math::to_var(theta));\n    std::vector<stan::math::var> y0_var(stan::math::to_var(y0));\n    Eigen::Matrix<stan::math::var, -1, 1> y0_vec_var(stan::math::to_vector(y0_var));\n\n    auto y = torsten::pmx_ode_rk45_ctrl(f_eigen, y0_vec_var, t0, ts, msgs, rtol, atol, max_num_steps,\n                                        theta_var, x_r, x_i);\n    auto y_sol = stan::math::ode_rk45_tol(f_eigen, y0_vec_var, t0, ts, rtol, atol, max_num_steps, msgs,\n                                          theta_var, x_r, x_i);\n\n    for (size_t j = 0; j < ts.size(); ++j) {\n      torsten::test::test_grad(theta_var, y_sol[j], y[j], 1e-8, 1e-8);\n      torsten::test::test_grad(y0_var, y_sol[j], y[j], 1e-8, 1e-8);\n    }\n  }\n\n  {                             // y0 & ts var\n    std::vector<stan::math::var> y0_var(stan::math::to_var(y0));\n    Eigen::Matrix<stan::math::var, -1, 1> y0_vec_var(stan::math::to_vector(y0_var));\n    std::vector<stan::math::var> ts_var(stan::math::to_var(ts));\n\n    auto y = torsten::pmx_ode_rk45_ctrl(f_eigen, y0_vec_var, t0, ts_var, msgs, rtol, atol, max_num_steps,\n                                        theta, x_r, x_i);\n    auto y_sol = stan::math::ode_rk45_tol(f_eigen, y0_vec_var, t0, ts_var, rtol, atol, max_num_steps, msgs,\n                                          theta, x_r, x_i);\n\n    for (size_t j = 0; j < ts.size(); ++j) {\n      torsten::test::test_grad(ts_var, y_sol[j], y[j], 1e-8, 1e-8);\n      torsten::test::test_grad(y0_var, y_sol[j], y[j], 1e-8, 1e-8);\n    }\n  }\n}\n\nTEST_F(TorstenOdeTest_chem, eigen_vector_bdf) {\n  using torsten::dsolve::PMXVariadicOdeSystem;\n  \n  using stan::math::value_of;\n  using torsten::dsolve::PMXOdeintIntegrator;\n\n  {                             // data only\n    auto y = torsten::pmx_ode_bdf_ctrl(f_eigen, y0_vec, t0, ts, msgs, rtol, atol, max_num_steps,\n                                        theta, x_r, x_i);\n    auto y_sol = torsten::pmx_integrate_ode_bdf(f, y0, t0, ts,\n                                                 theta, x_r, x_i, rtol, atol, max_num_steps, msgs);\n    for (size_t j = 0; j < ts.size(); ++j) {\n      for (size_t i = 0; i < y0.size(); ++i) {\n        EXPECT_FLOAT_EQ(y[j][i], y_sol[j][i]);\n      }\n    }\n  }\n\n  {                             // theat var\n    std::vector<stan::math::var> theta_var(stan::math::to_var(theta));\n    auto y = torsten::pmx_ode_bdf_ctrl(f_eigen, y0_vec, t0, ts, msgs, rtol, atol, max_num_steps,\n                                        theta_var, x_r, x_i);\n    auto y_sol = stan::math::ode_bdf_tol(f_eigen, y0_vec, t0, ts, rtol, atol, max_num_steps, msgs,\n                                          theta_var, x_r, x_i);\n    for (size_t j = 0; j < ts.size(); ++j) {\n      torsten::test::test_grad(theta_var, y_sol[j], y[j], 1e-8, 1e-6);\n    }\n  }\n\n  {                             // theat & y0 var\n    std::vector<stan::math::var> theta_var(stan::math::to_var(theta));\n    std::vector<stan::math::var> y0_var(stan::math::to_var(y0));\n    Eigen::Matrix<stan::math::var, -1, 1> y0_vec_var(stan::math::to_vector(y0_var));\n\n    auto y = torsten::pmx_ode_bdf_ctrl(f_eigen, y0_vec_var, t0, ts, msgs, rtol, atol, max_num_steps,\n                                        theta_var, x_r, x_i);\n    auto y_sol = stan::math::ode_bdf_tol(f_eigen, y0_vec_var, t0, ts, rtol, atol, max_num_steps, msgs,\n                                          theta_var, x_r, x_i);\n\n    for (size_t j = 0; j < ts.size(); ++j) {\n      torsten::test::test_grad(theta_var, y_sol[j], y[j], 1e-8, 1e-6);\n      torsten::test::test_grad(y0_var, y_sol[j], y[j], 1e-8, 1e-6);\n    }\n  }\n\n  {                             // y0 & ts var\n    std::vector<stan::math::var> y0_var(stan::math::to_var(y0));\n    Eigen::Matrix<stan::math::var, -1, 1> y0_vec_var(stan::math::to_vector(y0_var));\n    std::vector<stan::math::var> ts_var(stan::math::to_var(ts));\n\n    auto y = torsten::pmx_ode_bdf_ctrl(f_eigen, y0_vec_var, t0, ts_var, msgs, rtol, atol, max_num_steps,\n                                        theta, x_r, x_i);\n    auto y_sol = stan::math::ode_bdf_tol(f_eigen, y0_vec_var, t0, ts_var, rtol, atol, max_num_steps, msgs,\n                                          theta, x_r, x_i);\n\n    for (size_t j = 0; j < ts.size(); ++j) {\n      torsten::test::test_grad(ts_var, y_sol[j], y[j], 1e-8, 1e-6);\n      torsten::test::test_grad(y0_var, y_sol[j], y[j], 1e-8, 1e-6);\n    }\n  }\n}\n\nTEST_F(TorstenOdeTest_lorenz, eigen_vector_adams) {\n  using torsten::dsolve::PMXVariadicOdeSystem;\n  \n  using stan::math::value_of;\n  using torsten::dsolve::PMXOdeintIntegrator;\n\n  {                             // theat & y0 var\n    std::vector<stan::math::var> theta_var(stan::math::to_var(theta));\n    std::vector<stan::math::var> y0_var(stan::math::to_var(y0));\n    Eigen::Matrix<stan::math::var, -1, 1> y0_vec_var(stan::math::to_vector(y0_var));\n\n    auto y = torsten::pmx_ode_adams_ctrl(f_eigen, y0_vec_var, t0, ts, msgs, rtol, atol, max_num_steps,\n                                        theta_var, x_r, x_i);\n    auto y_sol = stan::math::ode_adams_tol(f_eigen, y0_vec_var, t0, ts, rtol, atol, max_num_steps, msgs,\n                                          theta_var, x_r, x_i);\n\n    for (size_t j = 0; j < ts.size(); ++j) {\n      torsten::test::test_grad(theta_var, y_sol[j], y[j], 1e-6, 8e-6);\n      torsten::test::test_grad(y0_var, y_sol[j], y[j], 1e-6, 8e-6);\n    }\n  }\n\n  {                             // y0 & ts var\n    std::vector<stan::math::var> y0_var(stan::math::to_var(y0));\n    Eigen::Matrix<stan::math::var, -1, 1> y0_vec_var(stan::math::to_vector(y0_var));\n    std::vector<stan::math::var> ts_var(stan::math::to_var(ts));\n\n    auto y = torsten::pmx_ode_adams_ctrl(f_eigen, y0_vec_var, t0, ts_var, msgs, rtol, atol, max_num_steps,\n                                        theta, x_r, x_i);\n    auto y_sol = stan::math::ode_adams_tol(f_eigen, y0_vec_var, t0, ts_var, rtol, atol, max_num_steps, msgs,\n                                          theta, x_r, x_i);\n\n    for (size_t j = 0; j < ts.size(); ++j) {\n      torsten::test::test_grad(ts_var, y_sol[j], y[j], 1e-6, 8e-6);\n      torsten::test::test_grad(y0_var, y_sol[j], y[j], 1e-6, 8e-6);\n    }\n  }\n\n  {                             // ts var\n    std::vector<stan::math::var> ts_var(stan::math::to_var(ts));\n    auto y = torsten::pmx_ode_adams_ctrl(f_eigen, y0_vec, t0, ts_var, msgs, rtol, atol, max_num_steps,\n                                        theta, x_r, x_i);\n    auto y_sol = stan::math::ode_adams_tol(f_eigen, y0_vec, t0, ts_var, rtol, atol, max_num_steps, msgs,\n                                          theta, x_r, x_i);\n\n    for (size_t j = 0; j < ts.size(); ++j) {\n      torsten::test::test_grad(ts_var, y_sol[j], y[j], 1e-6, 8e-6);\n    }\n  }\n}\n\nTEST_F(TorstenOdeTest_neutropenia, eigen_vector_ckrk) {\n  using torsten::dsolve::PMXVariadicOdeSystem;\n  \n  using stan::math::value_of;\n  using torsten::dsolve::PMXOdeintIntegrator;\n\n  {                             // theat & y0 var\n    std::vector<stan::math::var> theta_var(stan::math::to_var(theta));\n    std::vector<stan::math::var> y0_var(stan::math::to_var(y0));\n    Eigen::Matrix<stan::math::var, -1, 1> y0_vec_var(stan::math::to_vector(y0_var));\n\n    auto y = torsten::pmx_ode_ckrk_ctrl(f_eigen, y0_vec_var, t0, ts, msgs, rtol, atol, max_num_steps,\n                                        theta_var, x_r, x_i);\n    auto y_sol = stan::math::ode_rk45_tol(f_eigen, y0_vec_var, t0, ts, rtol, atol, max_num_steps, msgs,\n                                          theta_var, x_r, x_i);\n\n    for (size_t j = 0; j < ts.size(); ++j) {\n      torsten::test::test_grad(theta_var, y_sol[j], y[j], 1e-8, 1e-8);\n      torsten::test::test_grad(y0_var, y_sol[j], y[j], 1e-8, 1e-8);\n    }\n  }\n\n  {                             // y0 & ts var\n    std::vector<stan::math::var> y0_var(stan::math::to_var(y0));\n    Eigen::Matrix<stan::math::var, -1, 1> y0_vec_var(stan::math::to_vector(y0_var));\n    std::vector<stan::math::var> ts_var(stan::math::to_var(ts));\n\n    auto y = torsten::pmx_ode_ckrk_ctrl(f_eigen, y0_vec_var, t0, ts_var, msgs, rtol, atol, max_num_steps,\n                                        theta, x_r, x_i);\n    auto y_sol = stan::math::ode_rk45_tol(f_eigen, y0_vec_var, t0, ts_var, rtol, atol, max_num_steps, msgs,\n                                          theta, x_r, x_i);\n\n    for (size_t j = 0; j < ts.size(); ++j) {\n      torsten::test::test_grad(ts_var, y_sol[j], y[j], 1e-8, 1e-7);\n      torsten::test::test_grad(y0_var, y_sol[j], y[j], 1e-8, 1e-7);\n    }\n  }\n\n  {                             // ts var\n    std::vector<stan::math::var> ts_var(stan::math::to_var(ts));\n    auto y = torsten::pmx_ode_ckrk_ctrl(f_eigen, y0_vec, t0, ts_var, msgs, rtol, atol, max_num_steps,\n                                        theta, x_r, x_i);\n    auto y_sol = stan::math::ode_rk45_tol(f_eigen, y0_vec, t0, ts_var, rtol, atol, max_num_steps, msgs,\n                                          theta, x_r, x_i);\n\n    for (size_t j = 0; j < ts.size(); ++j) {\n      torsten::test::test_grad(ts_var, y_sol[j], y[j], 1e-8, 1e-7);\n    }\n  }\n}\n", "meta": {"hexsha": "b0baef3f87077fac0581fc90b522650a3d12b66b", "size": 13282, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/dsolve/variadic_ode_test.cpp", "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": "test/unit/dsolve/variadic_ode_test.cpp", "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": "test/unit/dsolve/variadic_ode_test.cpp", "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": 43.9801324503, "max_line_length": 108, "alphanum_fraction": 0.5801084174, "num_tokens": 4463, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.78793120560257, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.4933427778204143}}
{"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 <Eigen/Dense>\n#include <algorithm>\n#include <iterator>\n#include <numeric>\n#include <random>\n#include <unordered_set>\n\n#include \"open3d/geometry/PointCloud.h\"\n#include \"open3d/geometry/TriangleMesh.h\"\n#include \"open3d/utility/Console.h\"\n\nnamespace open3d {\nnamespace geometry {\n\n/// \\class RANSACResult\n///\n/// \\brief Stores the current best result in the RANSAC algorithm.\nclass RANSACResult {\npublic:\n    RANSACResult() : fitness_(0), inlier_rmse_(0) {}\n    ~RANSACResult() {}\n\npublic:\n    double fitness_;\n    double inlier_rmse_;\n};\n\n// Calculates the number of inliers given a list of points and a plane model,\n// and the total distance between the inliers and the plane. These numbers are\n// then used to evaluate how well the plane model fits the given points.\nRANSACResult EvaluateRANSACBasedOnDistance(\n        const std::vector<Eigen::Vector3d> &points,\n        const Eigen::Vector4d plane_model,\n        std::vector<size_t> &inliers,\n        double distance_threshold,\n        double error) {\n    RANSACResult result;\n\n    for (size_t idx = 0; idx < points.size(); ++idx) {\n        Eigen::Vector4d point(points[idx](0), points[idx](1), points[idx](2),\n                              1);\n        double distance = std::abs(plane_model.dot(point));\n\n        if (distance < distance_threshold) {\n            error += distance;\n            inliers.emplace_back(idx);\n        }\n    }\n\n    size_t inlier_num = inliers.size();\n    if (inlier_num == 0) {\n        result.fitness_ = 0;\n        result.inlier_rmse_ = 0;\n    } else {\n        result.fitness_ = (double)inlier_num / (double)points.size();\n        result.inlier_rmse_ = error / std::sqrt((double)inlier_num);\n    }\n    return result;\n}\n\n// Find the plane such that the summed squared distance from the\n// plane to all points is minimized.\n//\n// Reference:\n// https://www.ilikebigbits.com/2015_03_04_plane_from_points.html\nEigen::Vector4d GetPlaneFromPoints(const std::vector<Eigen::Vector3d> &points,\n                                   const std::vector<size_t> &inliers) {\n    Eigen::Vector3d centroid(0, 0, 0);\n    for (size_t idx : inliers) {\n        centroid += points[idx];\n    }\n    centroid /= double(inliers.size());\n\n    double xx = 0, xy = 0, xz = 0, yy = 0, yz = 0, zz = 0;\n\n    for (size_t idx : inliers) {\n        Eigen::Vector3d r = points[idx] - centroid;\n        xx += r(0) * r(0);\n        xy += r(0) * r(1);\n        xz += r(0) * r(2);\n        yy += r(1) * r(1);\n        yz += r(1) * r(2);\n        zz += r(2) * r(2);\n    }\n\n    double det_x = yy * zz - yz * yz;\n    double det_y = xx * zz - xz * xz;\n    double det_z = xx * yy - xy * xy;\n\n    Eigen::Vector3d abc;\n    if (det_x > det_y && det_x > det_z) {\n        abc = Eigen::Vector3d(det_x, xz * yz - xy * zz, xy * yz - xz * yy);\n    } else if (det_y > det_z) {\n        abc = Eigen::Vector3d(xz * yz - xy * zz, det_y, xy * xz - yz * xx);\n    } else {\n        abc = Eigen::Vector3d(xy * yz - xz * yy, xy * xz - yz * xx, det_z);\n    }\n\n    double norm = abc.norm();\n    // Return invalid plane if the points don't span a plane.\n    if (norm == 0) {\n        return Eigen::Vector4d(0, 0, 0, 0);\n    }\n    abc /= abc.norm();\n    double d = -abc.dot(centroid);\n    return Eigen::Vector4d(abc(0), abc(1), abc(2), d);\n}\n\nstd::tuple<Eigen::Vector4d, std::vector<size_t>> PointCloud::SegmentPlane(\n        const double distance_threshold /* = 0.01 */,\n        const int ransac_n /* = 3 */,\n        const int num_iterations /* = 100 */) const {\n    RANSACResult result;\n    double error = 0;\n\n    // Initialize the plane model ax + by + cz + d = 0.\n    Eigen::Vector4d plane_model = Eigen::Vector4d(0, 0, 0, 0);\n    // Initialize the best plane model.\n    Eigen::Vector4d best_plane_model = Eigen::Vector4d(0, 0, 0, 0);\n\n    // Initialize consensus set.\n    std::vector<size_t> inliers;\n\n    size_t num_points = points_.size();\n    std::vector<size_t> indices(num_points);\n    std::iota(std::begin(indices), std::end(indices), 0);\n\n    std::random_device rd;\n    std::mt19937 rng(rd());\n\n    // Return if ransac_n is less than the required plane model parameters.\n    if (ransac_n < 3) {\n        utility::LogError(\n                \"ransac_n should be set to higher than or equal to 3.\");\n        return std::make_tuple(best_plane_model, inliers);\n    }\n    if (num_points < size_t(ransac_n)) {\n        utility::LogError(\"There must be at least 'ransac_n' points.\");\n        return std::make_tuple(best_plane_model, inliers);\n    }\n\n    for (int itr = 0; itr < num_iterations; itr++) {\n        for (int i = 0; i < ransac_n; ++i) {\n            std::swap(indices[i], indices[rng() % num_points]);\n        }\n        inliers.clear();\n        for (int idx = 0; idx < ransac_n; ++idx) {\n            inliers.emplace_back(indices[idx]);\n        }\n\n        // Fit model to num_model_parameters randomly selected points among the\n        // inliers.\n        plane_model = TriangleMesh::ComputeTrianglePlane(\n                points_[inliers[0]], points_[inliers[1]], points_[inliers[2]]);\n        if (plane_model.isZero(0)) {\n            continue;\n        }\n\n        error = 0;\n        inliers.clear();\n        auto this_result = EvaluateRANSACBasedOnDistance(\n                points_, plane_model, inliers, distance_threshold, error);\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            best_plane_model = plane_model;\n        }\n    }\n\n    // Find the final inliers using best_plane_model.\n    inliers.clear();\n    for (size_t idx = 0; idx < points_.size(); ++idx) {\n        Eigen::Vector4d point(points_[idx](0), points_[idx](1), points_[idx](2),\n                              1);\n        double distance = std::abs(best_plane_model.dot(point));\n\n        if (distance < distance_threshold) {\n            inliers.emplace_back(idx);\n        }\n    }\n\n    // Improve best_plane_model using the final inliers.\n    best_plane_model = GetPlaneFromPoints(points_, inliers);\n\n    utility::LogDebug(\"RANSAC | Inliers: {:d}, Fitness: {:e}, RMSE: {:e}\",\n                      inliers.size(), result.fitness_, result.inlier_rmse_);\n    return std::make_tuple(best_plane_model, inliers);\n}\n\n}  // namespace geometry\n}  // namespace open3d\n", "meta": {"hexsha": "140944b0ef14fd6fcf66efd1512d6aa8c701bc51", "size": 7771, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Open3D/cpp/open3d/geometry/PointCloudSegmentation.cpp", "max_stars_repo_name": "xdeng7/redwood_open3d_3dreconstruction", "max_stars_repo_head_hexsha": "aa1651d3cec1feb00468d548ac2268a3ed17b856", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2021-03-17T14:24:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T15:35:27.000Z", "max_issues_repo_path": "cpp/open3d/geometry/PointCloudSegmentation.cpp", "max_issues_repo_name": "moonwonlee/Open3D", "max_issues_repo_head_hexsha": "dda9b3a0129fa6c60f913672a70ff02483dcd0f3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-11-04T09:22:25.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-14T01:32:31.000Z", "max_forks_repo_path": "cpp/open3d/geometry/PointCloudSegmentation.cpp", "max_forks_repo_name": "moonwonlee/Open3D", "max_forks_repo_head_hexsha": "dda9b3a0129fa6c60f913672a70ff02483dcd0f3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-09-30T06:32:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-25T11:52:04.000Z", "avg_line_length": 35.4840182648, "max_line_length": 80, "alphanum_fraction": 0.5976064857, "num_tokens": 2007, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.4933427715844208}}
{"text": "#include <body_interact_game/body_analizer.hpp>\n\n#include <Eigen/SVD>\n\nnamespace\n{\n\nconstexpr auto pi {3.141592653589793};\n\ninline Eigen::AngleAxisd get_yaw_inverse_matrix(Eigen::Affine3d pos) noexcept\n{\n  const auto ypr {pos.rotation().eulerAngles(2, 0, 1)};\n  const auto yaw_angle {ypr(0) < pi / 2 ? ypr(2) : ypr(2) - pi};\n  return {-yaw_angle, Eigen::Vector3d::UnitY()};\n}\n\n}\n\nbody_analizer::body_analizer(std::string root, std::size_t target_number)\n  : root_ {root},\n    target_number_ {std::to_string(target_number)},\n    base_name_ {\"torso_\" + target_number_},\n    right_hand_name_ {\"right_hand_\" + target_number_},\n    left_hand_name_ {\"left_hand_\" + target_number_},\n    right_knee_name_ {\"right_knee_\" + target_number_},\n    left_knee_name_ {\"left_knee_\" + target_number_}\n{\n}\n\nvoid body_analizer::update()\n{\n  const auto current_time {ros::Time{0}};\n  const auto base_pos {get_position(base_name_, current_time)};\n  const auto yaw_canceller {get_yaw_inverse_matrix(base_pos)};\n  head_ = yaw_canceller * base_pos.rotation() * Eigen::Vector3d::UnitY();\n  const auto base_vec {base_pos.translation()};\n  right_hand_ = yaw_canceller * (get_position(right_hand_name_, current_time).translation() - base_vec);\n  left_hand_ = yaw_canceller * (get_position(left_hand_name_, current_time).translation() - base_vec);\n  right_knee_ = yaw_canceller * (get_position(right_knee_name_, current_time).translation() - base_vec);\n  left_knee_ = yaw_canceller * (get_position(left_knee_name_, current_time).translation() - base_vec);\n}\n", "meta": {"hexsha": "b2dbd22913caabe1dd52abe4ff37accd261dd658", "size": 1528, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/body_interact_game/body_analizer.cpp", "max_stars_repo_name": "forno/body_interact_game", "max_stars_repo_head_hexsha": "8668c45fbe4c0d91aa1345b6c833d3b507920669", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-26T04:44:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-26T04:44:19.000Z", "max_issues_repo_path": "src/body_interact_game/body_analizer.cpp", "max_issues_repo_name": "forno/body_interact_game", "max_issues_repo_head_hexsha": "8668c45fbe4c0d91aa1345b6c833d3b507920669", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/body_interact_game/body_analizer.cpp", "max_forks_repo_name": "forno/body_interact_game", "max_forks_repo_head_hexsha": "8668c45fbe4c0d91aa1345b6c833d3b507920669", "max_forks_repo_licenses": ["BSD-3-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.380952381, "max_line_length": 104, "alphanum_fraction": 0.7447643979, "num_tokens": 430, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311856832191, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.4933427653484271}}
{"text": "/* ----------------------------------------------------------------------------\n * GTDynamics Copyright 2020, Georgia Tech Research Corporation,\n * Atlanta, Georgia 30332-0415\n * All Rights Reserved\n * See LICENSE for the license information\n * -------------------------------------------------------------------------- */\n\n/**\n * @file  WrenchFactor.cpp\n * @brief Wrench balance factor, common between forward and inverse dynamics.\n * @author Frank Dellaert, Mandy Xie, Yetong Zhang, and Gerry Chen\n */\n\n#include \"gtdynamics/factors/WrenchFactor.h\"\n\n#include <gtsam/base/Matrix.h>\n#include <gtsam/base/OptionalJacobian.h>\n#include <gtsam/base/Vector.h>\n#include <gtsam/geometry/Pose3.h>\n#include <gtsam/nonlinear/Values.h>\n\n#include <boost/optional.hpp>\n#include <iostream>\n#include <vector>\n\n#include \"gtdynamics/dynamics/Dynamics.h\"\n#include \"gtdynamics/statics/Statics.h\"\n\nusing gtsam::Matrix;\nusing gtsam::Matrix6;\nusing gtsam::Pose3;\nusing gtsam::Values;\nusing gtsam::Vector;\nusing gtsam::Vector6;\n\nnamespace gtdynamics {\n\nWrenchFactor::WrenchFactor(\n    gtsam::Key twist_key, gtsam::Key twistAccel_key,\n    const std::vector<DynamicsSymbol> &wrench_keys, gtsam::Key pose_key,\n    const gtsam::noiseModel::Base::shared_ptr &cost_model,\n    const Matrix6 &inertia, const boost::optional<gtsam::Vector3> &gravity)\n    : Base(cost_model), inertia_(inertia), gravity_(gravity) {\n  keys_.reserve(wrench_keys.size() + 3);\n  keys_.push_back(twist_key);\n  keys_.push_back(twistAccel_key);\n  keys_.insert(keys_.end(), wrench_keys.cbegin(), wrench_keys.cend());\n  keys_.push_back(pose_key);\n}\n\nVector WrenchFactor::unwhitenedError(\n    const Values &x, boost::optional<std::vector<Matrix> &> H) const {\n  if (!this->active(x)) {\n    return Vector::Zero(this->dim());\n  }\n\n  // Collect wrenches to implement L&P Equation 8.48 (F = ma)\n  std::vector<Vector6> wrenches;\n\n  // Coriolis forces.\n  const Vector6 twist = x.at<Vector6>(keys_.at(0));\n  Matrix6 H_twist;\n  wrenches.push_back(Coriolis(inertia_, twist, H ? &H_twist : 0));\n\n  // Change in generalized momentum.\n  const Vector6 twistAccel = x.at<Vector6>(keys_.at(1));\n  wrenches.push_back(-inertia_ * twistAccel);\n\n  // External wrenches.\n  for (auto key = keys_.cbegin() + 2; key != keys_.cend() - 1; ++key) {\n    wrenches.push_back(x.at<Vector6>(*key));\n  }\n\n  // Calculate resultant wrench, fills up H with identity matrices if asked,\n  // except the last H contains the pose derivative or zero if no gravity.\n  const Vector6 error = ResultantWrench(wrenches, inertia_(3, 3),\n                                        x.at<Pose3>(keys_.back()), gravity_, H);\n\n  // If asked, update Jacobians not yet calculated by ResultantWrench.\n  if (H) {\n    (*H)[0] = H_twist;    // Coriolis depends in twist (key 0)\n    (*H)[1] = -inertia_;  // Derivative with respect to twist acceleration\n  }\n\n  return error;\n}\n\n}  // namespace gtdynamics\n", "meta": {"hexsha": "144b38de52e75abd79a38751461b3a0a2d389289", "size": 2883, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtdynamics/factors/WrenchFactor.cpp", "max_stars_repo_name": "danbarla/GTDynamics", "max_stars_repo_head_hexsha": "0448b359aff9e0e784832666e4048ee01c8b082d", "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": "gtdynamics/factors/WrenchFactor.cpp", "max_issues_repo_name": "danbarla/GTDynamics", "max_issues_repo_head_hexsha": "0448b359aff9e0e784832666e4048ee01c8b082d", "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": "gtdynamics/factors/WrenchFactor.cpp", "max_forks_repo_name": "danbarla/GTDynamics", "max_forks_repo_head_hexsha": "0448b359aff9e0e784832666e4048ee01c8b082d", "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.393258427, "max_line_length": 80, "alphanum_fraction": 0.6645855012, "num_tokens": 786, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.4933427605904075}}
{"text": "#include <utility>\n\n#include <boost/numeric/ublas/matrix.hpp>\n\n#include \"total_unimodularity.hpp\"\n\nnamespace tu\n{\n\n  /**\n   * Tests if the given matrix contains only -1,0,+1 entries,\n   * returning the violating position if this is not the case.\n   *\n   * @param matrix The given matrix\n   * @param position Returns a violating entry\n   * @return true if and only if it is a -1,0,+1 matrix\n   */\n\n  bool is_zero_plus_minus_one_matrix(const integer_matrix& matrix, std::pair <integer_matrix::size_type, integer_matrix::size_type>& position)\n  {\n    for (size_t row = 0; row < matrix.size1(); ++row)\n    {\n      for (size_t column = 0; column < matrix.size2(); ++column)\n      {\n        const int value = matrix(row, column);\n        if (value < -1 || value > 1)\n        {\n          position.first = row;\n          position.second = column;\n          return false;\n        }\n      }\n    }\n\n    return true;\n  }\n\n  /**\n   * Tests if the given matrix contains only -1,0,+1 entries.\n   *\n   * @param matrix The given matrix\n   * @return true if and only if it is a -1,0,+1 matrix\n   */\n\n  bool is_zero_plus_minus_one_matrix(const integer_matrix& matrix)\n  {\n    std::pair <size_t, size_t> result;\n\n    return is_zero_plus_minus_one_matrix(matrix, result);\n  }\n\n  /**\n   * Tests if the given matrix contains only 0 or 1 entries,\n   * returning the violating position if this is not the case.\n   *\n   * @param matrix The given matrix\n   * @param position Returns a violating entry\n   * @return true if and only if it is a 0-1 matrix\n   */\n\n  bool is_zero_one_matrix(const integer_matrix& matrix, std::pair <integer_matrix::size_type, integer_matrix::size_type>& position)\n  {\n    for (size_t i = 0; i < matrix.size1(); ++i)\n    {\n      for (size_t j = 0; j < matrix.size2(); ++j)\n      {\n        const int value = matrix(i, j);\n        if (value < 0 || value > 1)\n        {\n          position .first = i;\n          position.second = j;\n          return false;\n        }\n      }\n    }\n\n    return true;\n  }\n\n  /**\n   * Tests if the given matrix contains only 0 or 1 entries.\n   *\n   * @param matrix The given matrix\n   * @return true if and only if it is a 0-1 matrix\n   */\n\n  bool is_zero_one_matrix(const integer_matrix& matrix)\n  {\n    std::pair <size_t, size_t> result;\n\n    return is_zero_one_matrix(matrix, result);\n  }\n\n} /* namespace tu */\n", "meta": {"hexsha": "793468dd2bef33443e62f14baae507e0a09b491d", "size": 2340, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cmr/zero_plus_minus_one.cpp", "max_stars_repo_name": "discopt/cmr", "max_stars_repo_head_hexsha": "669811a8c8cbaa12dabd2a1242f0c0ff1aea6e09", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2015-04-13T12:48:09.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-26T11:56:31.000Z", "max_issues_repo_path": "src/cmr/zero_plus_minus_one.cpp", "max_issues_repo_name": "xammy/unimodularity-test", "max_issues_repo_head_hexsha": "669811a8c8cbaa12dabd2a1242f0c0ff1aea6e09", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2021-08-19T09:06:05.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-27T23:18:47.000Z", "max_forks_repo_path": "src/cmr/zero_plus_minus_one.cpp", "max_forks_repo_name": "discopt/cmr", "max_forks_repo_head_hexsha": "669811a8c8cbaa12dabd2a1242f0c0ff1aea6e09", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.6315789474, "max_line_length": 142, "alphanum_fraction": 0.6153846154, "num_tokens": 621, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419958239132, "lm_q2_score": 0.7122321903471565, "lm_q1q2_score": 0.49332192581209167}}
{"text": "/* \r\n   Copyright (c) Marshall Clow 2014.\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 Revision history:\r\n    2 Dec 2014 mtc First version; power\r\n   \r\n*/\r\n\r\n/// \\file algorithm.hpp\r\n/// \\brief Misc Algorithms\r\n/// \\author Marshall Clow\r\n///\r\n\r\n#ifndef BOOST_ALGORITHM_HPP\r\n#define BOOST_ALGORITHM_HPP\r\n\r\n#include <functional> // for plus and multiplies\r\n\r\n#include <boost/utility/enable_if.hpp> // for boost::disable_if\r\n#include <boost/type_traits/is_integral.hpp>\r\n\r\nnamespace boost { namespace algorithm {\r\n\r\ntemplate <typename T>\r\nBOOST_CXX14_CONSTEXPR T identity_operation ( std::multiplies<T> ) { return T(1); }\r\n\r\ntemplate <typename T>\r\nBOOST_CXX14_CONSTEXPR T identity_operation ( std::plus<T> ) { return T(0); }\r\n\r\n\r\n/// \\fn power ( T x, Integer n )\r\n/// \\return the value \"x\" raised to the power \"n\"\r\n/// \r\n/// \\param x     The value to be exponentiated\r\n/// \\param n     The exponent (must be >= 0)\r\n///\r\n//  \\remark Taken from Knuth, The Art of Computer Programming, Volume 2:\r\n//  Seminumerical Algorithms, Section 4.6.3\r\ntemplate <typename T, typename Integer>\r\nBOOST_CXX14_CONSTEXPR typename boost::enable_if<boost::is_integral<Integer>, T>::type\r\npower (T x, Integer n) {\r\n    T y = 1; // Should be \"T y{1};\" \r\n    if (n == 0) return y;\r\n    while (true) {\r\n        if (n % 2 == 1) {\r\n            y = x * y;\r\n            if (n == 1)\r\n                return y;\r\n            }\r\n        n = n / 2;\r\n        x = x * x;\r\n        }\r\n    return y;\r\n    }\r\n\r\n/// \\fn power ( T x, Integer n, Operation op )\r\n/// \\return the value \"x\" raised to the power \"n\"\r\n/// using the operation \"op\".\r\n/// \r\n/// \\param x     The value to be exponentiated\r\n/// \\param n     The exponent (must be >= 0)\r\n/// \\param op    The operation used\r\n///\r\n//  \\remark Taken from Knuth, The Art of Computer Programming, Volume 2:\r\n//  Seminumerical Algorithms, Section 4.6.3\r\ntemplate <typename T, typename Integer, typename Operation>\r\nBOOST_CXX14_CONSTEXPR typename boost::enable_if<boost::is_integral<Integer>, T>::type\r\npower (T x, Integer n, Operation op) {\r\n    T y = identity_operation(op);\r\n    if (n == 0) return y;\r\n    while (true) {\r\n        if (n % 2 == 1) {\r\n            y = op(x, y);\r\n            if (n == 1)\r\n                return y;\r\n            }\r\n        n = n / 2;\r\n        x = op(x, x);\r\n        }\r\n    return y;\r\n    }\r\n\r\n}}\r\n\r\n#endif // BOOST_ALGORITHM_HPP\r\n", "meta": {"hexsha": "c86abff70fa5abed6f7b8297946a822b70a14956", "size": 2481, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "externals/boost/boost/algorithm/algorithm.hpp", "max_stars_repo_name": "YuukiTsuchida/v8_embeded", "max_stars_repo_head_hexsha": "c6e18f4e91fcc50607f8e3edc745a3afa30b2871", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 995.0, "max_stars_repo_stars_event_min_datetime": "2018-06-22T10:39:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T01:22:14.000Z", "max_issues_repo_path": "jeff/common/include/boost/algorithm/algorithm.hpp", "max_issues_repo_name": "jeffphi/advent-of-code-2018", "max_issues_repo_head_hexsha": "8e54bd23ebfe42fcbede315f0ab85db903551532", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 32.0, "max_issues_repo_issues_event_min_datetime": "2018-06-23T14:19:37.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T10:20:37.000Z", "max_forks_repo_path": "jeff/common/include/boost/algorithm/algorithm.hpp", "max_forks_repo_name": "jeffphi/advent-of-code-2018", "max_forks_repo_head_hexsha": "8e54bd23ebfe42fcbede315f0ab85db903551532", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 172.0, "max_forks_repo_forks_event_min_datetime": "2018-06-22T11:12:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T07:44:33.000Z", "avg_line_length": 27.8764044944, "max_line_length": 86, "alphanum_fraction": 0.5900846433, "num_tokens": 671, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419704455588, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.49332189927520614}}
{"text": "// This file is part of Eigen, a lightweight C++ template library\n// for linear algebra.\n//\n// Copyright (C) 2012 Alexey Korepanov <kaikaikai@yandex.ru>\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#define EIGEN_RUNTIME_NO_MALLOC\n#include \"main.h\"\n#include <limits>\n#include <Eigen/Eigenvalues>\n\ntemplate<typename MatrixType> void real_qz(const MatrixType& m)\n{\n  /* this test covers the following files:\n     RealQZ.h\n  */\n  using std::abs;\n  typedef typename MatrixType::Index Index;\n  typedef typename MatrixType::Scalar Scalar;\n  \n  Index dim = m.cols();\n  \n  MatrixType A = MatrixType::Random(dim,dim),\n             B = MatrixType::Random(dim,dim);\n\n\n  // Regression test for bug 985: Randomly set rows or columns to zero\n  Index k=internal::random<Index>(0, dim-1);\n  switch(internal::random<int>(0,10)) {\n  case 0:\n    A.row(k).setZero(); break;\n  case 1:\n    A.col(k).setZero(); break;\n  case 2:\n    B.row(k).setZero(); break;\n  case 3:\n    B.col(k).setZero(); break;\n  default:\n    break;\n  }\n\n  RealQZ<MatrixType> qz(dim);\n  // TODO enable full-prealocation of required memory, this probably requires an in-place mode for HessenbergDecomposition\n  //Eigen::internal::set_is_malloc_allowed(false);\n  qz.compute(A,B);\n  //Eigen::internal::set_is_malloc_allowed(true);\n  \n  VERIFY_IS_EQUAL(qz.info(), Success);\n  // check for zeros\n  bool all_zeros = true;\n  for (Index i=0; i<A.cols(); i++)\n    for (Index j=0; j<i; j++) {\n      if (abs(qz.matrixT()(i,j))!=Scalar(0.0))\n      {\n        std::cerr << \"Error: T(\" << i << \",\" << j << \") = \" << qz.matrixT()(i,j) << std::endl;\n        all_zeros = false;\n      }\n      if (j<i-1 && abs(qz.matrixS()(i,j))!=Scalar(0.0))\n      {\n        std::cerr << \"Error: S(\" << i << \",\" << j << \") = \" << qz.matrixS()(i,j) << std::endl;\n        all_zeros = false;\n      }\n      if (j==i-1 && j>0 && abs(qz.matrixS()(i,j))!=Scalar(0.0) && abs(qz.matrixS()(i-1,j-1))!=Scalar(0.0))\n      {\n        std::cerr << \"Error: S(\" << i << \",\" << j << \") = \" << qz.matrixS()(i,j)  << \" && S(\" << i-1 << \",\" << j-1 << \") = \" << qz.matrixS()(i-1,j-1) << std::endl;\n        all_zeros = false;\n      }\n    }\n  VERIFY_IS_EQUAL(all_zeros, true);\n  VERIFY_IS_APPROX(qz.matrixQ()*qz.matrixS()*qz.matrixZ(), A);\n  VERIFY_IS_APPROX(qz.matrixQ()*qz.matrixT()*qz.matrixZ(), B);\n  VERIFY_IS_APPROX(qz.matrixQ()*qz.matrixQ().adjoint(), MatrixType::Identity(dim,dim));\n  VERIFY_IS_APPROX(qz.matrixZ()*qz.matrixZ().adjoint(), MatrixType::Identity(dim,dim));\n}\n\nvoid test_real_qz()\n{\n  int s = 0;\n  for(int i = 0; i < g_repeat; i++) {\n    CALL_SUBTEST_1( real_qz(Matrix4f()) );\n    s = internal::random<int>(1,EIGEN_TEST_MAX_SIZE/4);\n    CALL_SUBTEST_2( real_qz(MatrixXd(s,s)) );\n\n    // some trivial but implementation-wise tricky cases\n    CALL_SUBTEST_2( real_qz(MatrixXd(1,1)) );\n    CALL_SUBTEST_2( real_qz(MatrixXd(2,2)) );\n    CALL_SUBTEST_3( real_qz(Matrix<double,1,1>()) );\n    CALL_SUBTEST_4( real_qz(Matrix2d()) );\n  }\n  \n  TEST_SET_BUT_UNUSED_VARIABLE(s)\n}\n", "meta": {"hexsha": "99ac31235ff642bcd8fbf7e21c897e97c84ffbb3", "size": 3138, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Eigen-3.3/test/real_qz.cpp", "max_stars_repo_name": "shareq2005/CarND-MPC-Project", "max_stars_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 719.0, "max_stars_repo_stars_event_min_datetime": "2019-05-10T00:31:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T23:04:23.000Z", "max_issues_repo_path": "src/Eigen-3.3/test/real_qz.cpp", "max_issues_repo_name": "shareq2005/CarND-MPC-Project", "max_issues_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 224.0, "max_issues_repo_issues_event_min_datetime": "2018-02-26T00:41:51.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T10:38:16.000Z", "max_forks_repo_path": "src/Eigen-3.3/test/real_qz.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": 32.6875, "max_line_length": 163, "alphanum_fraction": 0.614404079, "num_tokens": 982, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419704455589, "lm_q2_score": 0.7122321720225278, "lm_q1q2_score": 0.4933218950444039}}
{"text": "//\n// Created by \u0421\u0435\u0440\u0433\u0435\u0439 \u041a\u0440\u0438\u0432\u043e\u043d\u043e\u0441 on 01.09.17.\n//\n#include \"Exponentiation.h\"\n\n#include \"e.h\"\n#include \"i.h\"\n#include \"Infinity.h\"\n#include \"pi.h\"\n#include \"Integer.h\"\n#include \"Sum.h\"\n#include \"Product.h\"\n\n#include <cmath>\n#include <limits>\n\n#include <boost/numeric/conversion/cast.hpp>\n\nnamespace omnn{\nnamespace math {\n\n    Exponentiation::Exponentiation(const Valuable& _1, const Valuable& _2)\n    : base(_1,_2)\n    {\n        InitVars();\n    }\n\n    max_exp_t Exponentiation::getMaxVaExp(const Valuable& b, const Valuable& e)\n    {\n        if (e.IsInt()) {\n            return b.getMaxVaExp() * e.ca();\n        } else if (e.FindVa()) {\n            auto i = b.getMaxVaExp();\n            if (i) {\n                auto _ = e;\n                const Variable* v;\n                while ((v = _.FindVa())) {\n                    _.Eval(*v, 0);\n                }\n                _.optimize();\n                i *= static_cast<a_int>(_);\n            }\n            return i;\n        } else {\n            auto maxVaExp = e * b.getMaxVaExp();\n            if (maxVaExp.IsInt()) {\n                return maxVaExp.ca();\n            } else if (maxVaExp.IsSimpleFraction()) {\n                auto& f = maxVaExp.as<Fraction>();\n                return {f.getNumerator().ca(), f.getDenominator().ca()};\n            } else if(!optimizations) {\n                optimizations = true;\n                maxVaExp.optimize();\n                optimizations = {};\n                if (maxVaExp.IsInt()) {\n                    return maxVaExp.ca();\n                }\n            }\n        }\n\n        IMPLEMENT\n    }\n\n    max_exp_t Exponentiation::getMaxVaExp() const\n    {\n        return getMaxVaExp(getBase(), getExponentiation());\n    }\n    \n\tValuable Exponentiation::operator -() const\n    {\n        return Product {*this, -1};\n    }\n\n    void Exponentiation::InitVars() {\n        v.clear();\n        if (ebase().IsVa())\n            v[ebase().as<Variable>()] = eexp();\n    }\n\n    void Exponentiation::optimize()\n    {\n        if (optimized) {\n            return;\n        }\n\n        if (!optimizations)\n        {\n            hash = ebase().Hash() ^ eexp().Hash();\n            return;\n        }\n\n        ebase().optimize();\n        eexp().optimize();\n\n        if (ebase().IsExponentiation() || ebase().IsProduct())\n        {\n            ebase() ^= eexp();\n            Become(std::move(ebase()));\n            return;\n        }\n        \n        if (eexp().IsSum())\n        {\n            auto& s = eexp().as<Sum>();\n            auto sz = s.size();\n            auto v = 1_v;\n            for(auto it = s.begin(), e = s.end();\n                it != e; )\n            {\n                if (it->IsInt()) {\n                    v *= ebase()^*it;\n                    s.Delete(it);\n                }\n                else\n                    ++it;\n            }\n            if (sz != s.size()) {\n                Become(*this * v);\n                return;\n            }\n        }\n\n        // todo : check it, comment this and try System test\n//        if (ebase().IsSum() && eexp().IsFraction())\n//        {\n//            auto f = Fraction::cast(eexp());\n//            auto& d = f->getDenominator();\n//            if (d == ebase().getMaxVaExp()) {\n//                auto vars = ebase().Vars();\n//                if (vars.size() == 1) {\n//                    auto va = *vars.begin();\n//                    auto baseToSolve = ebase();\n//                    baseToSolve.SetView(View::Solving);\n//                    baseToSolve.optimize();\n//                    auto eq = va - baseToSolve(va);\n//                    auto sq = eq ^ d;\n//                    auto check = ebase()/sq;\n//                    if (check.IsInt() || check.IsSimpleFraction()) {\n//                        ebase() = eq;\n//                        eexp() = f->getNumerator();\n//                    } else {\n//                        // TODO : IMPLEMENT\n//                    }\n//                }\n//            }\n//        }\n//\n//        if (ebase().IsSum() && eexp().IsFraction())\n//        {\n//            auto f = Fraction::cast(eexp());\n//            auto& d = f->getDenominator();\n//            auto e = ebase() ^ f->getNumerator();\n//            if (d == e.getMaxVaExp()) {\n//                auto vars = e.Vars();\n//                if (vars.size() == 1) {\n//                    auto va = *vars.begin();\n//                    auto eq = va - e(va);\n//                    auto sq = eq ^ d;\n//                    auto check = e / sq;\n//                    if (check.IsInt() || check.IsSimpleFraction()) {\n//                        Become(std::move(eq));\n//                        return;\n//                    } else {\n//                        // TODO : IMPLEMENT\n//                    }\n//                }\n//            }\n//        }\n        \n        if (ebase().IsFraction() && eexp().IsMultival()==YesNoMaybe::No) {\n            auto& f = ebase().as<Fraction>();\n            auto _ = (f.getNumerator() ^ eexp()) / (f.getDenominator() ^ eexp());\n            if (_.IsExponentiation()) {\n                auto& e = _.as<Exponentiation>();\n                if (!(e.ebase()==ebase() && eexp()==e.eexp())) {\n                    IMPLEMENT\n                }\n            } else {\n                Become(std::move(_));\n                return;\n            }\n        }\n\n        if (ebase().IsFraction() && eexp().IsInt() && eexp() < 0_v) {\n            eexp() = -eexp();\n            ebase() = ebase().as<Fraction>().Reciprocal();\n        }\n\n        if (ebase().Is_e()) {\n            if (eexp().IsProduct()) {\n                auto& p = eexp().as<Product>();\n                if (p.Has(constant::pi) && p.Has(constant::i)) { // TODO : sequence does metter\n//                    ebase() = -1;\n//                    eexp() /= constant::i;\n//                    eexp() /= constant::pi;\n                }\n            }\n        }\n        // todo : check\n        if (ebase().IsSimple()) {\n            if (eexp().IsProduct()) {\n                auto& p = eexp().as<Product>();\n                auto it = p.GetFirstOccurence<Integer>();\n                auto in = ebase() ^ *it;  // IsExponentiationSimplifiable\n                if (in.IsInt()) {\n                    ebase() = in;\n                    p.Delete(it);\n                    if (p.size() == 1) {\n                        eexp().optimize();\n                    }\n                }\n            }\n            if (ebase()==1) {\n                if (eexp().IsInt()) {\n                    Become(std::move(ebase()));\n                    return;\n                } else if (eexp().IsSimpleFraction()) {\n                    if (eexp().as<Fraction>().getDenominator().bit(0)) {\n                        Become(std::move(ebase()));\n                        return;\n                    }\n                } else if (!!eexp().IsMultival()) {\n                } else if (!(eexp().IsInfinity() || eexp().IsMInfinity())) {\n                    Become(std::move(ebase()));\n                    return;\n                } else\n                    IMPLEMENT;\n            } else if (ebase()==-1 && eexp().IsInt() && eexp() > 0 && eexp()!=1) {\n                eexp() = eexp().bit(0);\n            } else if (eexp()==-1) {\n                Become(Fraction{1,ebase()});\n                return;\n            } else if (eexp().IsInfinity()) {\n                IMPLEMENT\n            } else if (eexp().IsFraction()) {\n                auto& f = eexp().as<Fraction>();\n                auto& n = f.getNumerator();\n                if (n != 1) {\n                    // TODO: auto is = ebase().IsExponentiationSimplifiable(n);\n                    auto newBase = ebase() ^ n;\n                    if(!newBase.IsExponentiation()){\n                        Become(newBase ^ (1_v / f.getDenominator()));\n                        return;\n                    }\n                }\n            }\n        }\n\n        bool ebz = ebase() == 0_v;\n        bool exz = eexp() == 0_v;\n        if(exz)\n        {\n            if (ebase().IsInfinity() || ebase().IsMInfinity()) {\n                IMPLEMENT\n            }\n            if(ebz)\n                throw \"NaN\";\n\n            Become(1_v);\n            return;\n        }\n        else if(eexp() == 1_v)\n        {\n            Become(std::move(ebase()));\n            return;\n        }\n        else if (ebz)\n        {\n            if (exz)\n                throw \"NaN\";\n            Become(0_v);\n            return;\n        }\n        else if (ebase().IsInfinity())\n        {\n            if (eexp() > 0) {\n                Become(std::move(ebase()));\n            } else\n                IMPLEMENT\n        }\n        else if (ebase().IsMInfinity())\n        {\n            if (eexp() > 0) {\n                if ((eexp() % 2) > 0) // TODO : test with non-ints\n                    Become(std::move(ebase()));\n                else\n                    Become(Infinity());\n            } else\n                IMPLEMENT\n        }\n        else if (ebase().IsVa() && eexp().IsSimple())\n        {\n        }\n        else\n        {\n            switch(view)\n            {\n                case View::Solving:\n\n                case View::None:\n                case View::Calc:\n                {\n                    if (eexp().IsInt() && eexp()>0) {\n                        auto b = 1_v;\n                        for (; eexp()--;) {\n                            b *= ebase();\n                        }\n                        Become(std::move(b));\n                        return;\n                    }\n                    if (ebase().IsInt() && eexp().IsInt()) {\n                        Become(ebase() ^ eexp());\n                        return;\n                    }\n                    break;\n                }\n                case View::Flat: {\n\n                    if(eexp().IsInt())\n                    {\n                        if (ebase().IsVa()) {\n                            break;\n                        }\n                        if (eexp() != 0_v) {\n                            if (eexp() > 1) {\n                                Valuable x = ebase();\n                                Valuable n = eexp();\n                                if (n < 0_v)\n                                {\n                                    x = 1_v / x;\n                                    n = -n;\n                                }\n                                if (n == 0_v)\n                                {\n                                    Become(1_v);\n                                    return;\n                                }\n                                auto y = 1_v;\n                                while(n > 1)\n                                {\n                                    bool isInt = n.IsInt();\n                                    if (!isInt)\n                                        IMPLEMENT\n                                    if (isInt && n.bit(0) == 0_v)\n                                    {\n                                        x.sq();\n                                        n /= 2;\n                                    }\n                                    else\n                                    {\n                                        y *= x;\n                                        x.sq();\n                                        --n;\n                                        n /= 2;\n                                    }\n                                }\n                                x *= y;\n                                Become(std::move(x));\n                            } else if (eexp()!=-1){\n                                // negative\n                                Become(1_v/(ebase()^(-eexp())));\n                            }\n                        }\n                        else { // zero\n                            if (ebase() == 0_v)\n                            {\n                                IMPLEMENT\n                                throw \"NaN\"; // feel free to handle this properly\n                            }\n                            else\n                            {\n                                Become(1_v);\n                            }\n                        }\n                    }\n//                    else\n//                    IMPLEMENT\n                    break;\n                }\n                case View::Equation: {\n                    if(eexp().IsSimple())\n                        Become(std::move(ebase()));\n                    break;\n                }\n                default:\n                \tLOG_AND_IMPLEMENT(str() << \" mode is \" << view);\n            }\n        }\n\n        if(IsExponentiation() && ebase().IsExponentiation())\n        {\n            auto& e = ebase().as<Exponentiation>();\n            auto& eeexp = e.getExponentiation();\n            if ((eeexp.FindVa() == nullptr) == (eexp().FindVa() == nullptr)) {\n                eexp() *= eeexp;\n                // todo : copy if it shared\n                ebase() = std::move(const_cast<Valuable&>((e.getBase())));\n            }\n        }\n\n        if (IsExponentiation()) {\n            hash = ebase().Hash() ^ eexp().Hash();\n            optimized = true;\n            InitVars();\n        }\n    }\n    \n    Valuable& Exponentiation::operator +=(const Valuable& v)\n    {\n        return Become(Sum {*this, v});\n    }\n\n    Valuable& Exponentiation::operator *=(const Valuable& v)\n    {\n        const Exponentiation* e;\n        const Fraction* f;\n        const Product* fdn = {};\n        const Exponentiation* fdne;\n        auto isProdHasExpWithSameBase = [this](const Product* p) -> const Exponentiation*\n        {\n            for(auto& it : *p){\n                if (it.IsExponentiation()) {\n                    auto& e = it.as<Exponentiation>();\n                    if (ebase() == e.getBase()) {\n                        return &e;\n                    }\n                }\n            }\n            return {};\n        };\n        if (v.IsExponentiation()\n            && ebase() == (e = &v.as<Exponentiation>())->getBase()\n            && (eexp().IsInt() || eexp().IsSimpleFraction()) && eexp() > 0\n            && (e->eexp().IsInt() || e->eexp().IsSimpleFraction()) && e->eexp() > 0\n            )\n        {\n            eexp() += e->getExponentiation();\n            optimized={};\n        }\n        else if(v.IsFraction()\n                && (f = &v.as<Fraction>())->getDenominator() == ebase())\n        {\n            --eexp();\n            optimized={};\n            optimize();\n            return *this *= f->getNumerator();\n        }\n        else if(v.IsFraction()\n                && f->getDenominator().IsProduct()\n                && (fdn = &f->getDenominator().as<Product>())->Has(ebase()))\n        {\n            --eexp();\n            optimized={};\n            optimize();\n            return *this *= f->getNumerator() / (*fdn / ebase());\n        }\n        else if(fdn\n                && (fdne = isProdHasExpWithSameBase(fdn)))\n        {\n            eexp() -= fdne->getExponentiation();\n            optimized={};\n            optimize();\n            return *this *= f->getNumerator() / (*fdn / *fdne);\n        }\n        else if(ebase() == v && v.FindVa())\n        {\n            ++eexp();\n            optimized={};\n        }\n        else if(v.IsProduct())\n        {\n            return Become(v * *this);\n        }\n        else if(v.IsInt())\n        {\n            if(v==1)\n                return *this;\n            else if(eexp()==-1 && ebase().IsInt())\n                return Become(v/ebase());\n            else\n                return Become(Product{v, *this});\n        }\n        else\n            return Become(Product{v, *this});\n\n        optimize();\n        return *this;\n    }\n\n    bool Exponentiation::MultiplyIfSimplifiable(const Valuable& v)\n    {\n        auto is = v == getBase();\n        if (is) {\n            ++eexp();\n            optimized = {};\n            optimize();\n        } else if (v.IsExponentiation()) {\n            auto& vexpo = v.as<Exponentiation>();\n            is = vexpo.getBase() == getBase();\n            if (is) {\n                eexp() += vexpo.eexp();\n                optimized = {};\n                optimize();\n            } // TODO : else if ? (base^2 == v.base)\n        } else if (v.IsInt()) {\n            IMPLEMENT\n        } else {\n//            std::cout << str() << \" * \" << v.str() << std::endl;\n        }\n        return is;\n    }\n\n    static auto one = 1_v;\n    std::pair<bool,Valuable> Exponentiation::IsMultiplicationSimplifiable(const Valuable& v) const\n    {\n        std::pair<bool,Valuable> is, expSumSimplifiable = {};\n        is.first = v == getBase()\n            && (expSumSimplifiable = vo<1>::get().IsSummationSimplifiable(eexp())).first;\n        if (is.first) {\n            is.second = getBase() ^ expSumSimplifiable.second;\n        } else if (v.IsExponentiation()) {\n            auto& vexpo = v.as<Exponentiation>();\n            is.first = vexpo.getBase() == getBase();\n            if (is.first) {\n                is.second = ebase() ^ (eexp() + vexpo.eexp());\n            } // TODO : else if ? (base^2 == v.base)\n        } else if (v.IsSimple()) {\n//            if (getBase().IsVa()) {\n//            } else if (getExponentiation().IsSimpleFraction()) {\n//                auto\n//                is.first = IsMultiplicationSimplifiable()\n//            } else if (getExponentiation().IsSimple()) {\n//                is = base::IsMultiplicationSimplifiable(v);\n//            } else {\n//                IMPLEMENT\n//            }\n        } else if (v.IsVa()) {\n            // covered by (v==base()) case\n        } else {\n#ifndef NDEBUG\n            std::cout << \"IsMultiplication simplifiable?: \" << str() << \" * \" << v.str() << std::endl;\n#endif\n        }\n        return is;\n    }\n\n    bool Exponentiation::SumIfSimplifiable(const Valuable& v)\n    {\n        auto is = !v.IsSimple() && !v.IsFraction() && !v.IsExponentiation();\n        if(is){\n            auto sumIfSimplifiable = v.IsSummationSimplifiable(*this);\n            is = sumIfSimplifiable.first;\n            if (is)\n                Become(std::move(sumIfSimplifiable.second));\n        }\n        return is;\n    }\n\n    std::pair<bool,Valuable> Exponentiation::IsSummationSimplifiable(const Valuable& v) const\n    {\n        std::pair<bool,Valuable> is;\n        is.first = operator==(v);\n        if (is.first) {\n            is.second = *this * 2;\n        } else if ((is.first = operator==(-v))) {\n                is.second = 0;\n        } else if (v.IsSimple()\n                || v.IsExponentiation()\n                || v.IsVa()\n                || v.IsFraction())\n        {\n        } else {\n            is = v.IsSummationSimplifiable(*this);\n        }\n        return is;\n    }\n\n    Valuable& Exponentiation::operator /=(const Valuable& v)\n    {\n        auto isMultival = IsMultival()==YesNoMaybe::Yes;\n        auto vIsMultival = v.IsMultival()==YesNoMaybe::Yes;\n        if(isMultival && vIsMultival) {\n            solutions_t vals, thisValues;\n            Values([&](auto& thisVal){\n                thisValues.insert(thisVal);\n                return true;\n            });\n            \n            v.Values([&](auto&vVal){\n                for(auto& tv:thisValues)\n                    vals.insert(tv/vVal);\n                return true;\n            });\n            \n            return Become(Valuable(vals));\n        }\n        else if (v.IsExponentiation())\n        {\n            auto& e = v.as<Exponentiation>();\n            if(ebase() == e.ebase() && (ebase().IsVa() || !ebase().IsMultival()))\n            {\n                eexp() -= e.eexp();\n            }\n            else\n            {\n                Become(Fraction(*this, v));\n                return *this;\n            }\n        }\n        else if(v.IsFraction())\n        {\n            *this *= v.as<Fraction>().Reciprocal();\n            return *this;\n        }\n        else if(ebase() == v)\n        {\n            --eexp();\n        }\n        else\n        {\n            Become(Fraction(*this, v));\n            return *this;\n        }\n\n        optimized={};\n        optimize();\n        return *this;\n    }\n\n    Valuable& Exponentiation::operator^=(const Valuable& v)\n    {\n        eexp() *= v;\n        optimized={};\n        optimize();\n        return *this;\n    }\n    \n    bool Exponentiation::operator ==(const Valuable& v) const\n    {\n        auto eq = v.IsExponentiation() && Hash()==v.Hash();\n        if(eq){\n            auto& e = v.as<Exponentiation>();\n            eq = _1.Hash() == e._1.Hash()\n                && _2.Hash() == e._2.Hash()\n                && _1 == e._1\n                && _2 == e._2;\n        } else if (v.IsFraction()) {\n            eq = eexp().IsInt()\n                 && eexp() < 0\n                 && ebase() == (v.as<Fraction>().getDenominator() ^ (-eexp()));\n        }\n        return eq;\n    }\n    \n    Exponentiation::operator double() const\n    {\n        return std::pow(static_cast<double>(ebase()), static_cast<double>(eexp()));\n    }\n\n    Valuable& Exponentiation::d(const Variable& x)\n    {\n        optimized={};\n        bool bhx = ebase().HasVa(x);\n        bool ehx = eexp().HasVa(x);\n        if(ehx) {\n            IMPLEMENT\n            if(bhx){\n                \n            }else{\n                \n            }\n        } else if (bhx) {\n            if(ebase() == x)\n                Become(eexp() * (ebase() ^ (eexp()-1)));\n            else\n                IMPLEMENT\n        } else\n            Become(0_v);\n        optimize();\n        return *this;\n    }\n    \n    Valuable& Exponentiation::i(const Variable& x, const Variable& C)\n    {\n        if ((eexp().IsInt() || eexp().IsSimpleFraction()) && ebase()==x) {\n            ++eexp();\n            operator/=(eexp());\n            operator+=(C);\n        } else {\n            IMPLEMENT\n        }\n        \n        optimize();\n        return *this;\n    }\n\n    Valuable Exponentiation::I(const Variable& x, const Variable& C) const\n    {\n        if ((eexp().IsInt() || eexp().IsSimpleFraction()) && ebase()==x) {\n            auto einc = eexp()+1;\n            return (ebase() ^ einc) / einc + C;\n        } else {\n            IMPLEMENT\n        }\n    }\n\n    bool Exponentiation::operator <(const Valuable& v) const\n    {\n        if (v.IsExponentiation())\n        {\n            auto& e = v.as<Exponentiation>();\n            if (e.getBase() == getBase())\n                return getExponentiation() < e.getExponentiation();\n            if (e.getExponentiation() == getExponentiation())\n                return getBase() < e.getBase();\n        }\n        \n        return base::operator <(v);\n    }\n\n    std::ostream& Exponentiation::print_sign(std::ostream& out) const\n    {\n        return out << \"^\";\n    }\n\n    Valuable::YesNoMaybe Exponentiation::IsMultival() const\n    {\n        auto is = _1.IsMultival() || _2.IsMultival();\n        if (is != YesNoMaybe::Yes && _2.IsFraction())\n            is = _2.as<Fraction>().getDenominator().IsEven() || is;\n        return is;\n    }\n    \n    void Exponentiation::Values(const std::function<bool(const Valuable&)>& fun) const\n    {\n        if (fun) {\n            auto cache = optimized; // TODO: multival caching (inspect all optimized and optimization transisions) auto isCached =\n            \n            std::set<Valuable> vals;\n            {\n            std::deque<Valuable> d1;\n            _1.Values([&](auto& v){\n                d1.push_back(v);\n                return true;\n            });\n            \n            _2.Values([&](auto& v){\n                auto vIsFrac = v.IsFraction();\n                const Fraction* f;\n                if(vIsFrac)\n                    f = &v.template as<Fraction>();\n                auto vMakesMultival = vIsFrac && f->getDenominator().IsEven()==YesNoMaybe::Yes;\n                \n                for(auto& item1:d1){\n                    if(vMakesMultival){\n                        Variable x;\n                        auto& dn = f->getDenominator();\n                        auto solutions = (x ^ dn).Equals(*this ^ dn).Solutions(x);\n                        for(auto&& s:solutions)\n                            vals.insert(s);\n                    } else {\n                        auto value=item1^v;\n                        if(value.IsMultival()==YesNoMaybe::No)\n                            vals.insert(value);\n                        else {\n                            IMPLEMENT\n                        }\n                    }\n                }\n                return true;\n            });\n            }\n            \n            for(auto& v:vals)\n                fun(v);\n        }\n    }\n\n    std::ostream& Exponentiation::code(std::ostream& out) const\n    {\n        if(!getExponentiation().IsInt())\n            IMPLEMENT;\n\n        out << \"(1\";\n        for (auto i=getExponentiation(); i-->0;) {\n            out << '*' << getBase();\n        }\n        out << ')';\n        \n        return out;\n    }\n    \n    bool Exponentiation::IsComesBefore(const Valuable& v) const\n    {\n        auto mve = getMaxVaExp();\n        auto vmve = v.getMaxVaExp();\n        auto is = mve > vmve;\n        if (mve != vmve)\n        {}\n        else if (v.IsExponentiation())\n        {\n            auto& e = v.as<Exponentiation>();\n            bool baseIsVa = getBase().IsVa();\n            bool vbaseIsVa = e.getBase().IsVa();\n            if (baseIsVa && vbaseIsVa)\n                is = getExponentiation() == e.getExponentiation() ? getBase().IsComesBefore(e.getBase()) : getExponentiation() > e.getExponentiation();\n            else if(baseIsVa)\n                is = false;\n            else if(vbaseIsVa)\n                is = true;\n            else if(getBase() == e.ebase())\n                is = getExponentiation().IsComesBefore(e.getExponentiation());\n            else if(getExponentiation() == e.getExponentiation())\n                is = getBase().IsComesBefore(e.getBase());\n            else\n            {\n                auto c = Complexity();\n                auto ec = e.Complexity();\n                if (c != ec)\n                    is = c > ec;\n                else {\n                    is = getBase().IsComesBefore(e.getBase()) || \n                        (!e.ebase().IsComesBefore(ebase()) && getExponentiation().IsComesBefore(e.getExponentiation())); //  || str().length() > e->str().length();\n    //                auto expComesBefore = eexp().IsComesBefore(e->eexp());\n    //                auto ebase()ComesBefore = ebase().IsComesBefore(e->ebase());\n    //                is = expComesBefore==ebase()ComesBefore || str().length() > e->str().length();\n                }\n            }\n        }\n        else if(v.IsProduct())\n        {\n            is = !v.IsComesBefore(*this);\n        }\n        else if(v.IsInt())\n            is = true;\n//        else if(v.IsFraction())\n//        {is=}\n        else if(v.IsVa())\n            is = !!FindVa();\n        else if(v.IsSum())\n            is = IsComesBefore(*v.as<Sum>().begin());\n        else\n            IMPLEMENT\n\n        return is;\n    }\n    \n    Valuable Exponentiation::calcFreeMember() const\n    {\n        Valuable c;\n        if(getBase().IsSum() && getExponentiation().IsInt()){\n            c = getBase().calcFreeMember() ^ getExponentiation();\n        } else if(getBase().IsVa()) {\n            c = 0_v;\n        } else\n            IMPLEMENT;\n        return c;\n    }\n\n    Valuable & Exponentiation::sq()\n    {\n        eexp() *= 2;\n        optimized = {};\n        optimize();\n        return *this;\n    }\n\n    const Valuable::vars_cont_t& Exponentiation::getCommonVars() const\n    {\n        return v;\n    }\n    \n    Valuable Exponentiation::InCommonWith(const Valuable& v) const\n    {\n        auto c = 1_v;\n        if (v.IsProduct()) {\n            for(auto& m: v.as<Product>()){\n                c = InCommonWith(m);\n                if (c != 1_v) {\n                    break;\n                }\n            }\n        } else if (v.IsExponentiation()) {\n            auto& e = v.as<Exponentiation>();\n            if (e.getBase() == getBase()) {\n                if (e.getExponentiation() == getExponentiation()) {\n                    c = e;\n                } else if (getExponentiation().IsSimple() && e.getExponentiation().IsSimple()) {\n                    if (getExponentiation() > 0 || e.getExponentiation() > 0) {\n                        if (e.getExponentiation() >= getExponentiation()) {\n                            c = *this;\n                        } else\n                            c = e;\n                    } else if (getExponentiation() < 0 || e.getExponentiation() < 0) {\n                        if (e.getExponentiation() >= getExponentiation()) {\n                            c = e;\n                        } else\n                            c = *this;\n                    } else {\n                        IMPLEMENT\n                    }\n                } else if (getExponentiation().IsSimpleFraction() && e.getExponentiation().IsSimpleFraction()) {\n                    if (getExponentiation()<0 == e.getExponentiation()<0) {\n                        c = getBase() ^ getExponentiation().InCommonWith(e.getExponentiation());\n                    }\n                } else if (getExponentiation().IsSum()) {\n                    auto sz = getExponentiation().as<Sum>().size();\n                    auto diff = getExponentiation() - e.getExponentiation();\n                    if (!diff.IsSum() || diff.as<Sum>().size() < sz)\n                        c = v;\n                } else if (e.getExponentiation().IsSum()) {\n                    c = e.InCommonWith(*this);\n                } else if (e.getExponentiation().IsProduct()) {\n                    c = ebase() ^ e.eexp().InCommonWith(eexp());\n                } else {\n                    IMPLEMENT\n                }\n            }\n        } else if (getExponentiation().IsInt()) {\n            if(getExponentiation() > 0)\n                c = getBase().InCommonWith(v);\n        } else if (getExponentiation().IsFraction()) {\n        } else if (v.IsVa()) {\n            c = v.InCommonWith(*this);\n        } else if (v.IsInt() || v.IsSimpleFraction()) {\n        } else if (getExponentiation().IsVa()) {\n        } else {\n            IMPLEMENT\n        }\n        return c;\n    }\n    \n    Valuable Exponentiation::operator()(const Variable& va) const\n    {\n        return operator()(va, 0_v);\n    }\n\n    Valuable Exponentiation::operator()(const Variable& v, const Valuable& augmentation) const\n    {\n        if (!getExponentiation().FindVa() && getExponentiation()!=0 && augmentation==0) {\n            return getBase()(v,augmentation);\n        } else if (getExponentiation().IsSimpleFraction()) {\n            auto& f = getExponentiation().as<Fraction>();\n            return (getBase()^f.getNumerator())(v,augmentation^f.getDenominator());\n        } else {\n            IMPLEMENT\n        }\n    }\n\n    Valuable::solutions_t Exponentiation::Distinct() const\n    {\n        solutions_t branches;\n        if (eexp().IsSimpleFraction()){\n            auto& f = eexp().as<Fraction>();\n            auto& denom = f.denominator();\n            if (denom.IsEven() == YesNoMaybe::Yes) {\n                // TODO : de-recoursefy:\n//                auto branchesSz = boost::multiprecision::msb(denom); // the largest bit\n//                branches.reserve(branchesSz);\n//                ...\n                if(!ebase().IsInt()){\n                    LOG_AND_IMPLEMENT(\"Distinct for \" << str());\n                } else {\n                    for (auto&& branch\n                            : (ebase().Sqrt() ^ (f.numerator() / (denom / 2))).Distinct())\n                    {\n                        branches.emplace(-branch);\n                        branches.emplace(std::move(branch));\n                    }\n                }\n            }\n        } else {\n            branches.emplace(*this);\n        }\n        return branches;\n    }\n}}\n", "meta": {"hexsha": "51fa3d854220e408abc50efe7f6e360b1a07bc19", "size": 31530, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "omnn/math/Exponentiation.cpp", "max_stars_repo_name": "ApusDT/openmind", "max_stars_repo_head_hexsha": "9d106248c79a37d19e0da894acbecd1493d4240f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "omnn/math/Exponentiation.cpp", "max_issues_repo_name": "ApusDT/openmind", "max_issues_repo_head_hexsha": "9d106248c79a37d19e0da894acbecd1493d4240f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "omnn/math/Exponentiation.cpp", "max_forks_repo_name": "ApusDT/openmind", "max_forks_repo_head_hexsha": "9d106248c79a37d19e0da894acbecd1493d4240f", "max_forks_repo_licenses": ["BSD-3-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.2392638037, "max_line_length": 163, "alphanum_fraction": 0.3893117666, "num_tokens": 7104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.49326529212112397}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n//  Copyright 2016 John Maddock. Distributed under the Boost\n//  Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include <boost/multiprecision/cpp_bin_float.hpp>\n\nint main()\n{\n   typedef boost::multiprecision::number<boost::multiprecision::backends::cpp_bin_float<256> >  ext_float_t;\n   typedef boost::multiprecision::number<boost::multiprecision::backends::cpp_bin_float<2046> > long_ext_float_t;\n\n   ext_float_t x = 5e15;\n   x += 0.5;\n   ext_float_t x1 = x + 255.0 / (1 << 20); // + 2^-12 - eps\n   ext_float_t x2 = x + 257.0 / (1 << 20); // + 2^-12 + eps\n   double      d1 = x1.convert_to<double>();\n   double      d2 = x2.convert_to<double>();\n\n   std::cout << std::setprecision(18) << d1 << std::endl;\n   std::cout << std::setprecision(18) << d2 << std::endl;\n\n   x        = 1e7 + 0.5;\n   x1       = x + ldexp(255.0, -38); // + 2^-30 - eps\n   x2       = x + ldexp(257.0, -38); // + 2^-30 + eps\n   float f1 = x1.convert_to<float>();\n   float f2 = x2.convert_to<float>();\n\n   std::cout << std::setprecision(9) << f1 << std::endl;\n   std::cout << std::setprecision(9) << f2 << std::endl;\n\n   long_ext_float_t lf(1);\n   lf += std::numeric_limits<long_ext_float_t>::epsilon();\n   lf += std::numeric_limits<float>::epsilon() / 2;\n   BOOST_MP_ASSERT(lf != 1);\n   float f3 = lf.convert_to<float>();\n   std::cout << std::setprecision(9) << f3 << std::endl;\n\n   return (d1 == d2) && (f1 == f2) && (f3 != 1) ? 0 : 1;\n}\n", "meta": {"hexsha": "f6e601045c37ce35eea178299d9dde8d141bb41b", "size": 1570, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/bug12039.cpp", "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": "test/bug12039.cpp", "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": "test/bug12039.cpp", "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": 38.2926829268, "max_line_length": 113, "alphanum_fraction": 0.5757961783, "num_tokens": 507, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.49326528734700426}}
{"text": "#include <Eigen/Core>\n#include <Eigen/SparseCore>\n#include <Eigen/QR>\n#include <Eigen/Householder> \n#include <Eigen/SVD>\n#include \"operations.h\"\n\nusing namespace std;\nusing namespace Eigen;\n\n/* QR */\nvoid QR::fwd(){\n\tMatrixXd Q = MatrixXd::Zero(nrows, ncols);\n\tVectorXd xc = VectorXd::Zero(nrows);\n\n\tint curr_row = 0;\n\tint i=0;\n\tfor (auto e: c->edgesOut){\n\t\tif (e->A21 != nullptr){\n\t\t\tint s = A21_indices[i];\n\t\t\txc.segment(curr_row, s) = e->n2->get_x()->segment(0, s);\n\t\t\tQ.middleRows(curr_row, s) = *(e->A21); \n\t\t\tcurr_row += s;\n\t\t\t++i;\n\t\t}\n\t}\n\n\tlarfb(&Q, c->get_T(), &xc);\n\tcurr_row = 0;\n\ti=0;\n\tfor (auto e: c->edgesOut){\n\t\tif (e->A21 != nullptr){\n\t\t\tint s = A21_indices[i];\n\t\t\te->n2->get_x()->segment(0, s) = xc.segment(curr_row, s);\n\t\t\tcurr_row += s;\n\t\t\t++i;\n\t\t}\n\t}\n}\n\nvoid QR::bwd(){\n\tMatrixXd R;\n\tint i=0;\n\tSegment xs = c->get_x()->segment(0, ccols);\n\tfor (auto e: c->edgesIn){\n\t\tassert(e->A21 != nullptr);\n\t\tint s = A12_indices[i];\n\t\tassert(e->A21->cols() == s);\n\t\txs -= (e->A21->topRows(ccols))*(e->n1->get_x()->segment(0, s)); \n\t\t++i;\t\n\t}\n\tassert((*c->edgesOut.begin())->n2 == c);\n\n\tR = ((*c->edgesOut.begin())->A21->topRows(xs.size()));\n\ttrsv(&R, &xs, CblasUpper, CblasNoTrans, CblasNonUnit);\n\n}\n\n/* Reassign rows */\nvoid Reassign::fwd(){\n\t// cout << c->get_id() << \" \" << n->get_id() << endl;\n\tassert(indices.size() == nrows);\n\tfor (int i= nstart; i < nstart+nrows; ++i){\n\t\t// n->get_x()->segment(i,1) = c->get_x()->segment(indices[i-nstart],1);\n\t\t(*n->get_x())[i] = (*c->get_x())[indices[i-nstart]];\n\n\t}\n\n}\n\n/* Scaling */\nvoid Scale::bwd(){\n    trsv(R, &xs, CblasUpper, CblasNoTrans, CblasNonUnit);\n}\n\nvoid ScaleD::fwd(){\n\tassert(t != nullptr);\n\tormqr_trans(Q, t, &xsf);\n}\n\nvoid ScaleD::bwd(){\n\tMatrixXd R = Q->topRows(xs.size());\n\ttrsv(&R, &xs, CblasUpper, CblasNoTrans, CblasNonUnit);\n}\n\n/* Sparsification using Orthogonal transformations */\nvoid Orthogonal::bwd(){ormqr_notrans(V, tau, &xs);}\n\nvoid OrthogonalD::fwd(){ormqr_trans(V, tau, &xs);}\nvoid OrthogonalD::bwd(){ormqr_notrans(V, tau, &xs);}\n\n\n/* Merging in the cluster heirarchy */\nvoid Merge::fwd(){\n\tint k=0;\n\tfor (auto c: parent->children){\n\t\tfor (int i=0; i < c->rows(); ++i){\n\t\t\t(*parent->get_x())[k] = (*c->get_x())[i];\n\t\t\t++k;\n\t\t}\n\t}\n\t// assert(k== parent->get_x()->size());\n}\n\nvoid Merge::bwd(){\n\tint k=0;\n\t// cout << \"merge bwd \" << parent->get_id() << endl;\n\tfor (auto c: parent->children){\n\t\tfor (int i=0; i < c->cols(); ++i){\n\t\t\t(*c->get_x())[i] = (*parent->get_x())[k];\n\t\t\t++k;\n\t\t}\n\t}\n\t// assert(k== parent->get_x()->size());\n}\n\n/* Split between coarse and fine nodes */\nvoid Split::fwd(){xsf = xsc.bottomRows(xsf.size());}\nvoid Split::bwd(){xsc_head.bottomRows(xsf.size()) = xsf;}\n\nvoid SplitD::fwd(){\n\txsf = xsc.middleRows(rank, ccols-rank);\n\tVectorXd xsc_rem = xsc.bottomRows(crows-ccols);\n\txsc.middleRows(rank, crows-ccols) = xsc_rem;\n\txsc.bottomRows(ccols-rank) = xsf;\n}\nvoid SplitD::bwd(){\n\tVectorXd xsc_rem = xsc.middleRows(rank, crows-ccols);\n\txsc.middleRows(rank, ccols-rank) = xsf;\n\txsc.bottomRows(crows-ccols) = xsc_rem;\n}\n\n\n\n\n\n", "meta": {"hexsha": "07eb9a90a6598bb0fb7ab10923263b61cbe67a40", "size": 3024, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/operations.cpp", "max_stars_repo_name": "Abeynaya/spaQR_public", "max_stars_repo_head_hexsha": "4fd28b1a23c73feb914b40e4285d5a076ffc9058", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/operations.cpp", "max_issues_repo_name": "Abeynaya/spaQR_public", "max_issues_repo_head_hexsha": "4fd28b1a23c73feb914b40e4285d5a076ffc9058", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/operations.cpp", "max_forks_repo_name": "Abeynaya/spaQR_public", "max_forks_repo_head_hexsha": "4fd28b1a23c73feb914b40e4285d5a076ffc9058", "max_forks_repo_licenses": ["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.0729927007, "max_line_length": 73, "alphanum_fraction": 0.5992063492, "num_tokens": 1058, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262966, "lm_q2_score": 0.5888891307678319, "lm_q1q2_score": 0.4932652873470041}}
{"text": "#ifndef __TARGET_FIELD_HPP__\n#define __TARGET_FIELD_HPP__ 1\n\n#include <list>\n#include <vector>\n#include <Eigen/Dense>\n\nclass TargetField {\n public:\n  const double ignore = -666.666;\n\n  class Target {\n   public:\n    Target(\n      const double p_value,\n      const std::pair<double, double> p_coordinates\n    );\n    \n    ~Target();\n    \n    double value() const;\n    \n    std::pair<double, double> coordinates() const;\n\n   private:\n    double value_;\n    std::pair<double, double> coordinates_;\n  };\n\n  TargetField(\n    const double p_x_size,\n    const double p_y_size,\n    const int p_num_cells\n  );\n\n  ~TargetField();\n  \n  TargetField& add_target(const Target& p_target);\n  \n  std::vector<Target> get_targets() const;\n  \n  Eigen::MatrixXd as_cells() const;\n\n  std::pair<double, double> coordinates_of_cell(\n    const int p_cell_x,\n    const int p_cell_y\n  ) const;\n\n private:\n  int num_cells_;\n  double x_size_;\n  double y_size_;\n  std::vector<Target> targets_;\n};\n\n#endif //__TARGET_FIELD_HPP__", "meta": {"hexsha": "bf7645fa5a548be2ddf9ef41cf6268c8cde945b3", "size": 995, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "CS791x_Fall14/Project02_ConsensusFilter/code/target_field.hpp", "max_stars_repo_name": "T-R0D/Past-Courses", "max_stars_repo_head_hexsha": "0edc83a7bf09515f0d01d23a26df2ff90c0f458a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2017-03-13T17:32:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-27T16:51:22.000Z", "max_issues_repo_path": "CS791x_Fall14/Project02_ConsensusFilter/code/target_field.hpp", "max_issues_repo_name": "T-R0D/Past-Courses", "max_issues_repo_head_hexsha": "0edc83a7bf09515f0d01d23a26df2ff90c0f458a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-29T19:54:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-29T19:54:52.000Z", "max_forks_repo_path": "CS791x_Fall14/Project02_ConsensusFilter/code/target_field.hpp", "max_forks_repo_name": "T-R0D/Past-Courses", "max_forks_repo_head_hexsha": "0edc83a7bf09515f0d01d23a26df2ff90c0f458a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2016-10-18T03:31:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-29T13:23:10.000Z", "avg_line_length": 17.7678571429, "max_line_length": 51, "alphanum_fraction": 0.672361809, "num_tokens": 251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.7490872187162396, "lm_q1q2_score": 0.4932121342498493}}
{"text": "/* ----------------------------------------------------------------------------\n * Copyright 2020, Jesus Tordesillas Torres, Aerospace Controls Laboratory\n * Massachusetts Institute of Technology\n * All Rights Reserved\n * Authors: Jesus Tordesillas, et al.\n * See LICENSE file for the license information\n * -------------------------------------------------------------------------- */\n\n#ifndef SOLVER_GUROBI_HPP\n#define SOLVER_GUROBI_HPP\n#include <Eigen/Dense>\n#include \"gurobi_c++.h\"\n#include <Eigen/StdVector>\n\n#include <iomanip>  //set precision\n#include \"mader_types.hpp\"\n#include \"utils.hpp\"\n#include \"timer.hpp\"\n#include <decomp_geometry/polyhedron.h>  //For Polyhedron  and Hyperplane definition\n#include \"separator.hpp\"\n#include \"octopus_search.hpp\"\n#include \"solver_params.hpp\"\n\ntypedef MADER_timers::Timer MyTimer;\n\nclass SolverGurobi\n{\npublic:\n  SolverGurobi(ms::par_solver &par);\n\n  ~SolverGurobi();\n\n  bool optimize();\n\n  // setters\n  void setMaxRuntimeKappaAndMu(double runtime, double kappa, double mu);\n  bool setInitStateFinalStateInitTFinalT(mt::state initial_state, mt::state final_state, double t_init,\n                                         double &t_final);\n  void setHulls(mt::ConvexHullsOfCurves_Std &hulls);\n\n  mt::trajectory traj_solution_;\n\n  // getters\n  void getPlanes(std::vector<Hyperplane3D> &planes);\n  int getNumOfLPsRun();\n  int getNumOfQCQPsRun();\n  void getSolution(mt::PieceWisePol &solution);\n  double getTimeNeeded();\n\n  int B_SPLINE = 1;  // B-Spline Basis\n  int MINVO = 2;     // Minimum volume basis\n  int BEZIER = 3;    // Bezier basis\n\n  bool checkGradientsUsingFiniteDiff();\n\nprotected:\nprivate:\n  bool getIntersectionWithPlane(const Eigen::Vector3d &P1, const Eigen::Vector3d &P2, const Eigen::Vector4d &coeff,\n                                Eigen::Vector3d &intersection);\n\n  void addObjective();\n  void addConstraints();\n\n  void saturateQ(std::vector<Eigen::Vector3d> &q);\n\n  // transform functions (with Eigen)\n  void transformPosBSpline2otherBasis(const Eigen::Matrix<double, 3, 4> &Qbs, Eigen::Matrix<double, 3, 4> &Qmv,\n                                      int interval);\n  void transformVelBSpline2otherBasis(const Eigen::Matrix<double, 3, 3> &Qbs, Eigen::Matrix<double, 3, 3> &Qmv,\n                                      int interval);\n\n  // transform functions (with std)\n  void transformPosBSpline2otherBasis(const std::vector<std::vector<GRBLinExpr>> &Qbs,\n                                      std::vector<std::vector<GRBLinExpr>> &Qmv, int interval);\n\n  void transformVelBSpline2otherBasis(const std::vector<std::vector<GRBLinExpr>> &Qbs,\n                                      std::vector<std::vector<GRBLinExpr>> &Qmv, int interval);\n\n  void generateRandomGuess();\n  bool generateAStarGuess();\n  void generateStraightLineGuess();\n\n  void printStd(const std::vector<Eigen::Vector3d> &v);\n  void printStd(const std::vector<double> &v);\n  void generateGuessNDFromQ(const std::vector<Eigen::Vector3d> &q, std::vector<Eigen::Vector3d> &n,\n                            std::vector<double> &d);\n\n  void fillPlanesFromNDQ(const std::vector<Eigen::Vector3d> &n, const std::vector<double> &d,\n                         const std::vector<Eigen::Vector3d> &q);\n\n  void generateRandomD(std::vector<double> &d);\n  void generateRandomN(std::vector<Eigen::Vector3d> &n);\n  void generateRandomQ(std::vector<Eigen::Vector3d> &q);\n\n  void printQVA(const std::vector<Eigen::Vector3d> &q);\n\n  void printQND(std::vector<Eigen::Vector3d> &q, std::vector<Eigen::Vector3d> &n, std::vector<double> &d);\n\n  GRBEnv *env_ = new GRBEnv();\n  GRBModel m_ = GRBModel(*env_);\n\n  std::vector<std::vector<GRBVar>> q_var_;      // Each q_var_[i] has 3 elements (x,y,z)\n  std::vector<std::vector<GRBLinExpr>> q_exp_;  // Each q_exp_[i] has 3 elements (x,y,z)\n\n  std::vector<Eigen::Vector3d> n_;  // Each n_[i] has 3 elements (nx,ny,nz)\n  std::vector<double> d_;           // d_[i] has 1 element\n\n  void findCentroidHull(const mt::Polyhedron_Std &hull, Eigen::Vector3d &centroid);\n\n  // void printIndexesConstraints();\n  // void printIndexesVariables();\n\n  mt::PieceWisePol solution_;\n\n  int basis_ = B_SPLINE;\n\n  int p_ = 5;\n  int i_min_;\n  int i_max_;\n  int j_min_;\n  int j_max_;\n  int k_min_;\n  int k_max_;\n  int M_;\n  int N_;\n\n  int num_of_normals_;\n\n  int num_of_obst_;\n  int num_of_segments_;\n\n  std::vector<Hyperplane3D> planes_;\n\n  double dc_;\n  Eigen::RowVectorXd knots_;\n  double t_init_;\n  double t_final_;\n  double deltaT_;\n\n  // double weight_ = 10000;\n  double weight_modified_ = 10000;\n\n  mt::state initial_state_;\n  mt::state final_state_;\n\n  Eigen::Vector3d q0_, q1_, q2_, qNm2_, qNm1_, qN_;\n\n  mt::ConvexHullsOfCurves_Std hulls_;\n\n  MyTimer opt_timer_;\n\n  double max_runtime_ = 2;  //[seconds]\n\n  // Guesses\n  std::vector<Eigen::Vector3d> n_guess_;  // Guesses for the normals\n  std::vector<Eigen::Vector3d> q_guess_;  // Guesses for the normals\n  std::vector<double> d_guess_;           // Guesses for the normals\n\n  double kappa_ = 0.2;  // kappa_*max_runtime_ is spent on the initial guess\n  double mu_ = 0.5;     // mu_*max_runtime_ is spent on the optimization\n\n  int num_of_QCQPs_run_ = 0;\n\n  // transformation between the B-spline control points and other basis\n  std::vector<Eigen::Matrix<double, 4, 4>> M_pos_bs2basis_;\n  std::vector<Eigen::Matrix<double, 3, 3>> M_vel_bs2basis_;\n  std::vector<Eigen::Matrix<double, 4, 4>> A_pos_bs_;\n\n  separator::Separator *separator_solver_;\n  OctopusSearch *octopusSolver_;\n\n  ms::par_solver par_;\n\n  GRBQuadExpr control_cost_ = 0.0;\n  GRBQuadExpr terminal_cost_ = 0.0;\n  GRBQuadExpr cost_ = 0.0;\n\n  // double x_min_ = -std::numeric_limits<double>::max();\n  // double x_max_ = std::numeric_limits<double>::max();\n\n  // double y_min_ = -std::numeric_limits<double>::max();\n  // double y_max_ = std::numeric_limits<double>::max();\n\n  // double z_min_ = -std::numeric_limits<double>::max();\n  // double z_max_ = std::numeric_limits<double>::max();\n\n  // int deg_pol_ = 3;\n  // int num_pol_ = 5;\n\n  // int a_star_samp_x_ = 7;\n  // int a_star_samp_y_ = 7;\n  // int a_star_samp_z_ = 7;\n\n  // double a_star_bias_ = 1.0;\n  // double a_star_fraction_voxel_size_ = 0.5;\n  // double Ra_ = 1e10;\n};\n#endif", "meta": {"hexsha": "6189353a50008b9b6bfd91222790b0ef76676a88", "size": 6181, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "mader/include/solver_gurobi.hpp", "max_stars_repo_name": "duobin/mader", "max_stars_repo_head_hexsha": "a70e7aaf2c33732960cc1315536c7006d28f42a2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-16T05:41:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T05:41:03.000Z", "max_issues_repo_path": "mader/include/solver_gurobi.hpp", "max_issues_repo_name": "duobin/mader", "max_issues_repo_head_hexsha": "a70e7aaf2c33732960cc1315536c7006d28f42a2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mader/include/solver_gurobi.hpp", "max_forks_repo_name": "duobin/mader", "max_forks_repo_head_hexsha": "a70e7aaf2c33732960cc1315536c7006d28f42a2", "max_forks_repo_licenses": ["BSD-3-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.2171717172, "max_line_length": 115, "alphanum_fraction": 0.6638084452, "num_tokens": 1780, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.4932121205199641}}
{"text": "////////////////////////////////////////////////////////////////////////////////\n// TensionFieldEnergy.hh\n////////////////////////////////////////////////////////////////////////////////\n/*! @file\n//  The tension-field-theory-based strain energy density used in Skouras 2014:\n//  Designing Inflatable Structures.\n//\n//  This energy is implemented as a function of the right Green-Green\n//  deformation tensor.\n*/\n//  Author:  Julian Panetta (jpanetta), julian.panetta@gmail.com\n//  Created:  04/04/2019 18:21:53\n////////////////////////////////////////////////////////////////////////////////\n#ifndef TENSIONFIELDENERGY_HH\n#define TENSIONFIELDENERGY_HH\n\n#include <Eigen/Dense>\n#include <array>\n#include \"EigSensitivity.hh\"\n#include \"IncompressibleBalloonEnergy.hh\"\n\ntemplate<typename Real>\nstruct TensionFieldEnergy {\n    using V2d  = Eigen::Matrix<Real, 2, 1>;\n    using M2d  = Eigen::Matrix<Real, 2, 2>;\n\n    TensionFieldEnergy() { }\n\n    template<typename Derived>\n    TensionFieldEnergy(const Eigen::MatrixBase<Derived> &C) { setMatrix(C); }\n\n    template<typename Derived>\n    void setMatrix(const Eigen::MatrixBase<Derived> &C) {\n        m_balloonEnergy   .setMatrix(C);\n        m_eigSensitivities.setMatrix(C);\n        setEigs(m_eigSensitivities.lambda(0), m_eigSensitivities.lambda(1));\n    }\n    Real energy() const {\n        if ((m_l1 < 1.0) && (m_l2 < 1.0)) return 0.0;\n        if (m_l2 < m_l2_tilde)            return m_balloonEnergy.stiffness * (m_l1 + 2.0 * m_l2_tilde - 3.0);\n        return m_balloonEnergy.energy();\n    }\n\n    Real denergy(const M2d &dC) const {\n        if ((m_l1 < 1.0) && (m_l2 < 1.0)) return 0.0;\n        if (m_l2 < m_l2_tilde)            return m_balloonEnergy.stiffness * ((1.0 - m_l2_tilde * m_l2_tilde * m_l2_tilde) * m_eigSensitivities.dLambda(dC)[0]);\n        return m_balloonEnergy.denergy(dC);\n    }\n\n    M2d denergy() const {\n        if ((m_l1 < 1.0) && (m_l2 < 1.0)) return M2d::Zero();\n        if (m_l2 < m_l2_tilde)            return (m_balloonEnergy.stiffness * ((1.0 - m_l2_tilde * m_l2_tilde * m_l2_tilde))) * m_eigSensitivities.dLambda(0);\n        return m_balloonEnergy.denergy();\n    }\n\n    Real d2energy(const M2d &dC_a, const M2d &dC_b) const {\n        if ((m_l1 < 1.0) && (m_l2 < 1.0)) return 0.0;\n        if (m_l2 < m_l2_tilde) {\n            Real inv_l1 = 1.0 / m_l1;\n            return m_balloonEnergy.stiffness * ((1.0 - inv_l1 * m_l2_tilde)         * m_eigSensitivities.d2Lambda(dC_a, dC_b)[0]\n                                               + 1.5 * inv_l1 * inv_l1 * m_l2_tilde * m_eigSensitivities. dLambda(0, dC_a)\n                                                                                    * m_eigSensitivities. dLambda(0, dC_b));\n        }\n        return m_balloonEnergy.d2energy(dC_a, dC_b);\n    }\n\n    M2d delta_denergy(const M2d &dC) const {\n        if ((m_l1 < 1.0) && (m_l2 < 1.0)) return m_relaxedStiffnessEps * m_balloonEnergy.delta_denergy_undeformed(dC); // add a small artificial stiffness to avoid rank-deficient Hessian in fully compressed regions\n        if (m_l2 < m_l2_tilde) {\n            Real inv_l1 = 1.0 / m_l1;\n            return m_balloonEnergy.stiffness * ((1.0 - inv_l1 * m_l2_tilde)         * m_eigSensitivities.delta_dLambda(0, dC)\n                                              + (1.5 * inv_l1 * inv_l1 * m_l2_tilde * m_eigSensitivities.      dLambda(0, dC))\n                                                                                    * m_eigSensitivities.      dLambda(0)\n                                              + (m_relaxedStiffnessEps * m_eigSensitivities.dLambda(1, dC)) // add a small artificial stiffness to avoid rank-deficient Hessian in regions of partial tension\n                                                                       * m_eigSensitivities.dLambda(1));\n        }\n        return m_balloonEnergy.delta_denergy(dC);\n    }\n\n    size_t tensionState() const {\n        if ((m_l1 < 1.0) && (m_l2 < 1.0)) return 0; // compression in both directions\n        if (m_l2 < m_l2_tilde)            return 1; //     tension in one  direction\n        return 2;                                   //     tension in both directions\n    }\n\n    Real stiffness() const { return m_balloonEnergy.stiffness; }\n    void setStiffness(Real val ) { m_balloonEnergy.stiffness = val; }\n\n    // Note: the stiffness added in the relaxed case is also proportional to stiffness()!\n    void setRelaxedStiffnessEpsilon(Real val) { m_relaxedStiffnessEps = val; }\n    Real getRelaxedStiffnessEpsilon() const { return m_relaxedStiffnessEps; }\n\n    const EigSensitivity<Real> &eigSensitivities() const { return m_eigSensitivities; }\n\n    // Useful for visualizing/debugging the energy and its derivatives at\n    // arbitrary (l1, l2)...\n    void setEigs(Real l1, Real l2) {\n        if (l1 < l2) std::swap(l1, l2);\n        m_l1 = l1;\n        m_l2 = l2;\n        m_l2_tilde = 1.0 / std::sqrt(l1);\n    }\n\n    ////////////////////////////////////////////////////////////////////////////\n    // Expressions in terms of eigenvalues for debugging/developing smoothed\n    // energy density.\n    ////////////////////////////////////////////////////////////////////////////\n    // Energy expressed in terms of eigenvalues.\n    Real psi() const {\n        const Real k = m_balloonEnergy.stiffness;\n        if ((m_l1 < 1.0) && (m_l2 < 1.0)) return 0.0;\n        if (m_l2 < m_l2_tilde)            return k * (m_l1 + 2.0 * m_l2_tilde - 3.0);\n        // full neo-Hookean energy in terms of eigenvalues\n        return k * (m_l1 + m_l2 + 1.0 / (m_l1 * m_l2) - 3.0);\n    }\n\n    // Derivatives of energy with respect to eigenvalues l1, l2 (Note: these formulas can\n    // not be used for computing denergy(dC) when l1 == l2 since the eigenvalues become\n    // non-smooth functions of C in this case).\n    V2d dpsi_dl() const {\n        const Real k = m_balloonEnergy.stiffness;\n        V2d result(V2d::Zero());\n        if ((m_l1 < 1.0) && (m_l2 < 1.0)) return V2d::Zero();\n        if (m_l2 < m_l2_tilde) return k * V2d(1.0 - m_l2_tilde * m_l2_tilde * m_l2_tilde, 0.0);\n        return k * V2d(1.0 - 1.0 / (m_l1 * m_l1 * m_l2),\n                       1.0 - 1.0 / (m_l1 * m_l2 * m_l2));\n    }\n\n    M2d d2psi_dl2() const {\n        if ((m_l1 < 1.0) && (m_l2 < 1.0)) return M2d::Zero();\n        M2d result;\n        const Real k = m_balloonEnergy.stiffness;\n        const Real inv_l1 = 1.0 / m_l1;\n        if (m_l2 < m_l2_tilde) {\n            result << k * 1.5 * inv_l1 * inv_l1 * m_l2_tilde, 0.0, 0.0, 0.0;\n        }\n        else {\n            result << 2.0 / (m_l1 * m_l1 * m_l1 * m_l2), 1.0 / (m_l1 * m_l1 * m_l2 * m_l2),\n                      1.0 / (m_l1 * m_l1 * m_l2 * m_l2), 2.0 / (m_l1 * m_l2 * m_l2 * m_l2);\n            result *= k;\n        }\n        return result;\n    }\n\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\nprotected:\n    IncompressibleBalloonEnergy<Real> m_balloonEnergy;\n    EigSensitivity<Real>              m_eigSensitivities;\n    Real m_l1 = 0.0, m_l2 = 0.0, m_l2_tilde = 0.0;\n    bool useSmoothedTensionField = false;\n    Real m_relaxedStiffnessEps = 1e-8;\n};\n\n// Optionally use either TensionFieldEnergy or IncompressibleBalloonEnergy\ntemplate<typename _Real>\nstruct OptionalTensionFieldEnergy : public TensionFieldEnergy<Real> {\n    using Real = _Real;\n    using TFE = TensionFieldEnergy<Real>;\n    using V2d = typename TFE::V2d;\n    using M2d = typename TFE::M2d;\n\n    OptionalTensionFieldEnergy() { }\n\n    template<typename Derived>\n    OptionalTensionFieldEnergy(const Eigen::MatrixBase<Derived> &C) : TFE(C) { }\n\n    Real energy() const {\n        if (useTensionField) return TFE::energy();\n        return TFE::m_balloonEnergy.energy();\n    }\n\n    Real denergy(const M2d &dC) const {\n        if (useTensionField) return TFE::denergy(dC);\n        return TFE::m_balloonEnergy.denergy(dC);\n    }\n\n    M2d denergy() const {\n        if (useTensionField) return TFE::denergy();\n        return TFE::m_balloonEnergy.denergy();\n    }\n\n    M2d delta_denergy(const M2d &dC) const {\n        if (useTensionField) return TFE::delta_denergy(dC);\n        return TFE::m_balloonEnergy.delta_denergy(dC);\n    }\n\n    Real d2energy(const M2d &dC_a, const M2d &dC_b) const {\n        if (useTensionField) return TFE::d2energy(dC_a, dC_b);\n        return TFE::m_balloonEnergy.d2energy(dC_a, dC_b);\n    }\n\n    ////////////////////////////////////////////////////////////////////////////\n    // Conform to the C-based energy interface\n    // (So we can use the membrane energy density wrapper)\n    ////////////////////////////////////////////////////////////////////////////\n    OptionalTensionFieldEnergy(const OptionalTensionFieldEnergy &other, UninitializedDeformationTag &&) {\n        copyMaterialProperties(other);\n    }\n\n    static constexpr EDensityType EDType = EDensityType::CBased;\n    static constexpr size_t Dimension = 2;\n    static constexpr size_t N         = 2;\n    void setC(Eigen::Ref<const M2d> C) { setMatrix(C); }\n    M2d PK2Stress() const { return 2.0 * denergy(); }\n\n    template<class Mat_>\n    M2d delta_PK2Stress(const Mat_ &dC) const { return 2.0 * delta_denergy(dC.matrix()); }\n\n    template<class Mat_, class Mat2_>\n    M2d delta2_PK2Stress(const Mat_ &/* dC_a */, const Mat2_ &/* dC_b */) const {\n        throw std::runtime_error(\"Unimplemented\");\n    }\n\n    bool useTensionField = true;\n\n    void copyMaterialProperties(const OptionalTensionFieldEnergy &b) {\n        setStiffness(b.stiffness());\n        setRelaxationEnabled(b.getRelaxationEnabled());\n        setRelaxedStiffnessEpsilon(b.getRelaxedStiffnessEpsilon());\n    }\n    bool getRelaxationEnabled() const { return useTensionField; }\n    void setRelaxationEnabled(bool enable) { useTensionField = enable; }\n};\n\n#endif /* end of include guard: TENSIONFIELDENERGY_HH */\n", "meta": {"hexsha": "0e8ec5e95d8d1256d73df6a2c910f6a86ef1da35", "size": 9717, "ext": "hh", "lang": "C++", "max_stars_repo_path": "TensionFieldEnergy.hh", "max_stars_repo_name": "jpanetta/Inflatables", "max_stars_repo_head_hexsha": "6941fb1bf4a2f61a847605aea37adef97bf05d76", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2021-10-05T18:52:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T06:35:04.000Z", "max_issues_repo_path": "TensionFieldEnergy.hh", "max_issues_repo_name": "jpanetta/Inflatables", "max_issues_repo_head_hexsha": "6941fb1bf4a2f61a847605aea37adef97bf05d76", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TensionFieldEnergy.hh", "max_forks_repo_name": "jpanetta/Inflatables", "max_forks_repo_head_hexsha": "6941fb1bf4a2f61a847605aea37adef97bf05d76", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-09-24T22:26:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-14T21:51:18.000Z", "avg_line_length": 42.9955752212, "max_line_length": 214, "alphanum_fraction": 0.5765153854, "num_tokens": 2872, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007393, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.49317053546240025}}
{"text": "/*-----------------------------------------------------------------------------+\nCopyright (c) 2008-2009: Joachim Faulhaber\n+------------------------------------------------------------------------------+\n   Distributed under the Boost Software License, Version 1.0.\n      (See accompanying file LICENCE.txt or copy at\n           http://www.boost.org/LICENSE_1_0.txt)\n+-----------------------------------------------------------------------------*/\n#define BOOST_TEST_MODULE icl::example_boost_party unit test\n\n#include <libs/icl/test/disable_test_warnings.hpp>\n#include \"../unit_test_unwarned.hpp\"\n//#include <boost/icl/set.hpp> // Needed for implicit calls of operator << on\n//JODO CLANG                   // GuestSets via test macros.\n\n//------------------------------------------------------------------------------\n// begin example code. return value added to function boost_party\n//------------------------------------------------------------------------------\n#include <boost/icl/ptime.hpp>\n#include <iostream>\n#include <boost/icl/interval_map.hpp>\n\nusing namespace std;\nusing namespace boost::posix_time;\nusing namespace boost::icl;\n\n// Type set<string> collects the names of party guests. Since std::set is\n// a model of the itl's set concept, the concept provides an operator +=\n// that performs a set union on overlap of intervals.\ntypedef std::set<string> GuestSetT;\n\ninterval_map<ptime, GuestSetT> boost_party()\n{\n    GuestSetT mary_harry;\n    mary_harry.insert(\"Mary\");\n    mary_harry.insert(\"Harry\");\n\n    GuestSetT diana_susan;\n    diana_susan.insert(\"Diana\");\n    diana_susan.insert(\"Susan\");\n\n    GuestSetT peter;\n    peter.insert(\"Peter\");\n\n    // A party is an interval map that maps time intervals to sets of guests\n    interval_map<ptime, GuestSetT> party;\n\n    party.add( // add and element\n      make_pair(\n        interval<ptime>::right_open(\n          time_from_string(\"2008-05-20 19:30\"),\n          time_from_string(\"2008-05-20 23:00\")),\n        mary_harry));\n\n    party += // element addition can also be done via operator +=\n      make_pair(\n        interval<ptime>::right_open(\n          time_from_string(\"2008-05-20 20:10\"),\n          time_from_string(\"2008-05-21 00:00\")),\n        diana_susan);\n\n    party +=\n      make_pair(\n        interval<ptime>::right_open(\n          time_from_string(\"2008-05-20 22:15\"),\n          time_from_string(\"2008-05-21 00:30\")),\n        peter);\n\n\n    interval_map<ptime, GuestSetT>::iterator it = party.begin();\n    cout << \"----- History of party guests -------------------------\\n\";\n    while(it != party.end())\n    {\n        interval<ptime>::type when = it->first;\n        // Who is at the party within the time interval 'when' ?\n        GuestSetT who = (*it++).second;\n        cout << when << \": \" << who << endl;\n    }\n\n    return party;\n}\n//------------------------------------------------------------------------------\n// end example code\n//------------------------------------------------------------------------------\n\ntypedef interval_map<ptime, GuestSetT> PartyHistory;\n\ntypedef PartyHistory::segment_type SegmentT;\n\nSegmentT episode(const char* from, const char* to, GuestSetT guests)\n{\n    return make_pair( interval<ptime>\n                      ::right_open( time_from_string(from)\n                                  , time_from_string(to)   )\n                    , guests);\n}\n\nPartyHistory check_party()\n{\n    GuestSetT mary_harry;\n    mary_harry.insert(\"Mary\");\n    mary_harry.insert(\"Harry\");\n\n    GuestSetT diana_susan;\n    diana_susan.insert(\"Diana\");\n    diana_susan.insert(\"Susan\");\n\n    GuestSetT peter;\n    peter.insert(\"Peter\");\n\n    GuestSetT Diana_Harry_Mary_Susan       = mary_harry + diana_susan;\n    GuestSetT Diana_Harry_Mary_Peter_Susan = Diana_Harry_Mary_Susan + peter;\n    GuestSetT Diana_Peter_Susan            = Diana_Harry_Mary_Peter_Susan - mary_harry;\n\n    PartyHistory party;\n\n    party += episode(\"2008-05-20 19:30\", \"2008-05-20 20:10\", mary_harry);\n    party += episode(\"2008-05-20 20:10\", \"2008-05-20 22:15\", Diana_Harry_Mary_Susan);\n    party += episode(\"2008-05-20 22:15\", \"2008-05-20 23:00\", Diana_Harry_Mary_Peter_Susan);\n    party += episode(\"2008-05-20 23:00\", \"2008-05-21 00:00\", Diana_Peter_Susan);\n    party += episode(\"2008-05-21 00:00\", \"2008-05-21 00:30\", peter);\n\n    return party;\n}\n\nBOOST_AUTO_TEST_CASE(icl_example_boost_party)\n{\n    PartyHistory party1 = boost_party();\n    PartyHistory party2 = check_party();\n    bool party_equality = (party1==party2);\n    BOOST_CHECK(party_equality);\n    //BOOST_CHECK_EQUAL(boost_party(), check_party());\n}\n", "meta": {"hexsha": "a0f23df7fe098ed0937c0c488338ec459e5e248c", "size": 4566, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/libs/icl/test/ex_boost_party_/ex_boost_party.cpp", "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/libs/icl/test/ex_boost_party_/ex_boost_party.cpp", "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/libs/icl/test/ex_boost_party_/ex_boost_party.cpp", "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": 34.3308270677, "max_line_length": 91, "alphanum_fraction": 0.5775295664, "num_tokens": 1082, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154240079185318, "lm_q2_score": 0.6893056295505783, "lm_q1q2_score": 0.49314579617388143}}
{"text": "#include <gtest/gtest.h>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <memory>\n#include <stdexcept>\n\n#include \"../filters/Filter/ParticleFilter/particlefilter.hh\"\n#include \"helpers.hh\"\n\nusing namespace std;\nusing namespace bold;\nusing namespace Eigen;\n\nTEST (ParticleFilterTests, ESSCheck)\n{\n  // With uniform weights, ESS should be number of non-zero weights\n  ESSFun<100> essFun;\n\n  VectorXd weights(100);\n\n  weights.fill(1.0 / 100);\n  EXPECT_EQ(100, essFun.ESS(weights));\n\n  weights.fill(0);\n  weights.head<50>().fill(1.0 / 50);\n  EXPECT_EQ(50, essFun.ESS(weights));\n}\n\nTEST (ParticleFilterTests, SystematicResample)\n{\n  constexpr int N = 6;\n  SystematicResample<1, N> resample;\n  MatrixXd particles = Matrix<double, 1, N>();\n  for (unsigned i = 0; i < N; ++i)\n    particles(i) = i;\n\n  // With uniform weights, we should get the same samples\n  VectorXd weights = Matrix<double, N, 1>::Constant(1.0 / N);\n  auto newParticlesWeights = resample.resample(particles, weights, N);\n  EXPECT_TRUE( MatricesEqual(particles, newParticlesWeights.first) );\n\n  // Sampling half the samples should give either all odd or all even samples\n  newParticlesWeights = resample.resample(particles, weights, N / 2);\n  for (unsigned i = 0; i < N / 2; ++i)\n    EXPECT_TRUE( newParticlesWeights.first(i) == particles(2 * i) || newParticlesWeights.first(i) == particles(2 * i + 1) );\n\n  // A lone particle with non-zero weight should be sampled always\n  weights.fill(0);\n  weights(0) = 1;\n  newParticlesWeights = resample.resample(particles, weights, N);\n  for (unsigned i = 0 ; i < N; ++i)\n    EXPECT_TRUE( VectorsEqual(VectorXd(newParticlesWeights.first.col(i)), VectorXd(particles.col(0))) );\n\n  weights.fill(0);\n  weights(N / 2) = 1;\n  newParticlesWeights = resample.resample(particles, weights, N);\n  for (unsigned i = 0 ; i < N; ++i)\n    EXPECT_TRUE( VectorsEqual(VectorXd(newParticlesWeights.first.col(i)), VectorXd(particles.col(N / 2))) );\n\n  weights.fill(0);\n  weights(N - 1) = 1;\n  newParticlesWeights = resample.resample(particles, weights, N);\n  for (unsigned i = 0 ; i < N; ++i)\n    EXPECT_TRUE( VectorsEqual(VectorXd(newParticlesWeights.first.col(i)), VectorXd(particles.col(N - 1))) );\n\n  // A particle with twice the weight should be sampled twice as often\n  // (in this test case where N is even, and weights are larger than 1.0 / N)\n  weights.fill(0);\n  weights(0) = 1.0 / 3.0;\n  weights(1) = 2.0 / 3.0;\n  newParticlesWeights = resample.resample(particles, weights, N);\n  unsigned count1 = (newParticlesWeights.first.array() == 0).count();\n  unsigned count2 = (newParticlesWeights.first.array() == 1).count();\n  EXPECT_EQ( count2, 2 * count1 );\n}\n", "meta": {"hexsha": "24e11a0c9a48e282560484a8e1b5e9ed8fc56e4d", "size": 2656, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/ParticleFilterTests.cc", "max_stars_repo_name": "drewnoakes/bold-humanoid", "max_stars_repo_head_hexsha": "6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335", "max_stars_repo_licenses": ["Apache-2.0"], "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/ParticleFilterTests.cc", "max_issues_repo_name": "drewnoakes/bold-humanoid", "max_issues_repo_head_hexsha": "6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335", "max_issues_repo_licenses": ["Apache-2.0"], "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/ParticleFilterTests.cc", "max_forks_repo_name": "drewnoakes/bold-humanoid", "max_forks_repo_head_hexsha": "6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335", "max_forks_repo_licenses": ["Apache-2.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.4935064935, "max_line_length": 124, "alphanum_fraction": 0.6961596386, "num_tokens": 762, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.49314577867663534}}
{"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#define NT2_UNIT_MODULE \"nt2 trigonometric toolbox - rem_pio2_straight/scalar Mode\"\n\n//////////////////////////////////////////////////////////////////////////////\n// unit test behavior of trigonometric components in scalar mode\n//////////////////////////////////////////////////////////////////////////////\n///\n#include <nt2/toolbox/trigonometric/include/functions/rem_pio2_straight.hpp>\n#include <nt2/toolbox/trigonometric/constants.hpp>\n#include <nt2/toolbox/constant/constant.hpp>\n\n#include <nt2/sdk/functor/meta/call.hpp>\n#include <nt2/sdk/meta/scalar_of.hpp>\n#include <boost/type_traits/is_same.hpp>\n\n#include <nt2/sdk/unit/module.hpp>\n#include <nt2/sdk/unit/tests/basic.hpp>\n#include <nt2/sdk/unit/tests/ulp.hpp>\n\nNT2_TEST_CASE_TPL ( rem_pio2_straight_real__1_0,  NT2_REAL_TYPES)\n{\n\n  using nt2::rem_pio2_straight;\n  using nt2::tag::rem_pio2_straight_;\n  typedef typename nt2::meta::call<rem_pio2_straight_(T)>::type r_t;\n  typedef typename nt2::meta::scalar_of<r_t>::type ssr_t;\n  typedef typename nt2::meta::call<rem_pio2_straight_(T)>::type wished_r_t;\n\n  // return type conformity test\n  NT2_TEST( (boost::is_same < r_t, wished_r_t >::value) );\n  std::cout << std::endl;\n\n  // specific values tests\n  typedef typename boost::fusion::result_of::value_at_c<r_t,0>::type r_t0;\n  typedef typename boost::fusion::result_of::value_at_c<r_t,1>::type r_t1;\n  typedef typename boost::fusion::result_of::value_at_c<r_t,2>::type r_t2;\n  {\n    r_t res = rem_pio2_straight(nt2::Pio_2<T>());\n    NT2_TEST_ULP_EQUAL( boost::fusion::get<0>(res), nt2::Zero<r_t0>(), 0.5);\n    NT2_TEST_ULP_EQUAL( boost::fusion::get<1>(res), nt2::Zero<r_t1>(), 0.5);\n    NT2_TEST_ULP_EQUAL( boost::fusion::get<2>(res), nt2::One<r_t2>(), 0.5);\n  }\n  {\n    r_t res = rem_pio2_straight(nt2::Pio_4<T>());\n    NT2_TEST_ULP_EQUAL( boost::fusion::get<0>(res), -nt2::Pio_4<r_t0>(), 0.5);\n    NT2_TEST_ULP_EQUAL( boost::fusion::get<1>(res), nt2::Zero<r_t1>(), 0.5);\n    NT2_TEST_ULP_EQUAL( boost::fusion::get<2>(res), nt2::One<r_t2>(), 0.5);\n  }\n  {\n    r_t res = rem_pio2_straight(nt2::Zero<T>());\n    NT2_TEST_ULP_EQUAL( boost::fusion::get<0>(res), -nt2::Pio_2<r_t0>(), 0.5);\n    NT2_TEST_ULP_EQUAL( boost::fusion::get<1>(res), nt2::Zero<r_t1>(), 0.5);\n    NT2_TEST_ULP_EQUAL( boost::fusion::get<2>(res), nt2::One<r_t2>(), 0.5);\n  }\n} // end of test for floating_\n", "meta": {"hexsha": "b02451474e6193d755de99169fa461a496bf3b9a", "size": 2841, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/core/trigonometric/unit/scalar/rem_pio2_straight.cpp", "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/unit/scalar/rem_pio2_straight.cpp", "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/unit/scalar/rem_pio2_straight.cpp", "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.0952380952, "max_line_length": 83, "alphanum_fraction": 0.6124604013, "num_tokens": 843, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056040203135, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.49314577372653523}}
{"text": "//          Copyright Carl Philipp Reh 2009 - 2016.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n\n#include <fcppt/math/at_c.hpp>\n#include <fcppt/math/dim/static.hpp>\n#include <fcppt/preprocessor/disable_gcc_warning.hpp>\n#include <fcppt/preprocessor/pop_warning.hpp>\n#include <fcppt/preprocessor/push_warning.hpp>\n#include <fcppt/config/external_begin.hpp>\n#include <boost/test/unit_test.hpp>\n#include <fcppt/config/external_end.hpp>\n\n\nBOOST_AUTO_TEST_CASE(\n\tmath_at_c\n)\n{\n\ttypedef\n\tfcppt::math::dim::static_<\n\t\tint,\n\t\t2\n\t>\n\tdim2;\n\n\tdim2 const dim_c(\n\t\t1,\n\t\t2\n\t);\n\n\tBOOST_CHECK_EQUAL(\n\t\tfcppt::math::at_c<\n\t\t\t0\n\t\t>(\n\t\t\tdim_c\n\t\t),\n\t\t1\n\t);\n\n\tBOOST_CHECK_EQUAL(\n\t\tfcppt::math::at_c<\n\t\t\t1\n\t\t>(\n\t\t\tdim_c\n\t\t),\n\t\t2\n\t);\n\n\n\tdim2 dim_m(\n\t\t1,\n\t\t2\n\t);\n\n\tfcppt::math::at_c<\n\t\t1\n\t>(\n\t\tdim_m\n\t) =\n\t\t42;\n\n\tBOOST_CHECK_EQUAL(\n\t\tfcppt::math::at_c<\n\t\t\t1\n\t\t>(\n\t\t\tdim_m\n\t\t),\n\t\t42\n\t);\n}\n", "meta": {"hexsha": "8a2441b9d9cd5345cb5321854e000ea95dee0523", "size": 988, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/math/at_c.cpp", "max_stars_repo_name": "vinzenz/fcppt", "max_stars_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "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": "test/math/at_c.cpp", "max_issues_repo_name": "vinzenz/fcppt", "max_issues_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "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/math/at_c.cpp", "max_forks_repo_name": "vinzenz/fcppt", "max_forks_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "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": 13.5342465753, "max_line_length": 61, "alphanum_fraction": 0.6497975709, "num_tokens": 350, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239836484143, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.4931457657456302}}
{"text": "/*\n   (c) Copyright 2012, Hewlett-Packard Development Company, LP\n\n   See the file named COPYING for license details\n*/\n\n/** @file\n    Interpolation search template\n*/\n\n#ifndef LINTEL_INTERPOLATION_SEARCH_HPP\n#define LINTEL_INTERPOLATION_SEARCH_HPP\n\n#include <inttypes.h>\n\n#include <boost/type_traits/make_unsigned.hpp>\n\n#include <Lintel/AssertBoost.hpp>\n\n// http://www.cs.technion.ac.il/~itai/publications/Algorithms/p550-perl.pdf\n// http://en.wikipedia.org/wiki/Interpolation_search\n\nnamespace lintel {\n\n    // TODO: redo the interface to have no precondition, i.e. v does not have to be in first..last\n    // and that if it is outside that rande, the function can return a value < 0 or > last_pos.\n    // but it needs to not crash.  Then clamp the return in the caller using the standard signed\n    // compare trick to usually only take one compare to check if 0..last_pos but if it is out of\n    // range a second to decide whether we clamp to 0 or last_pos.  A good estimator will estimate\n    // <0 if v < first, and >last_pos if v > last.  This approach means that we avoid the compares\n    // to re-establish the pre-condition at the cost of compares to clamp the range, but the clamp\n    // compares are always going to be fast because they are ssize_t compares, whereas the current\n    // compares could be expensive because they are value compares.  Tricky question on what\n    // happens if first == last --> value_range == 0.  That can't happen right now because it \n    // implies the return value is first and we will have stopped, but with this change it can\n    // happen.\ntemplate<typename ValueT> struct EstimateOffset {\n    typedef typename boost::make_unsigned<ValueT>::type UnsignedValueT;\n    // Preconditions: first < v <= last\n    // Postconditions: 0 <= return value <= last_pos\n    size_t \n    operator()(const ValueT &v, const ValueT &first, const ValueT &last, size_t last_pos) const {\n        UnsignedValueT value_range = last - first;\n        double relative_pos = static_cast<double>(v - first) / value_range; // [0,1]\n        return relative_pos * last_pos;\n    }\n};\n\ntemplate<typename ValueT> struct Compare {\n    bool operator()(const ValueT &a, const ValueT &b) const {\n        return a < b;\n    }\n};\n\nnamespace detail {\n\ntemplate<size_t interpolation_steps, size_t binary_steps, size_t binary_search_below_length,\n         typename ValueT, typename Iterator, class EstimateOffsetT, class CompareT>\nIterator interpolationLowerBound(Iterator begin, Iterator end, const ValueT &v, \n                                 const EstimateOffsetT &estimator, const CompareT &comparer) {\n    size_t estimated_offset;\n    Iterator estimated_pos;\n\n    if (begin == end) {\n        return begin;\n    }\n    if (comparer(*begin, v)) {\n        if (comparer(*(end - 1), v)) {\n            // v > *end\n            return end;\n        } else {\n            // ok, v \\in ]*begin, *end]\n        }\n    } else {\n        return begin;\n    }\n\n    // estimateOffset function can now safely assume that v is in range, so we don't have\n    // to check each time to see if we are in bounds.\n    \n    size_t len = end - begin; // - on struct iterator involves divide, do it once.\n    while (len > 0) {\n        for (size_t is = 0; len > 0 && is < interpolation_steps; ++is) {\n            DEBUG_SINVARIANT(begin < end);\n            DEBUG_SINVARIANT((end - begin) == static_cast<ptrdiff_t>(len));\n            DEBUG_SINVARIANT(comparer(*begin, v)); // *begin < v\n            DEBUG_INVARIANT(!comparer(*(end - 1), v),// v <= *(end - 1)\n                            boost::format(\"%s < %s\") % *(end - 1) % v); \n            estimated_offset = estimator(v, *begin, *(end - 1), len - 1);\n            //            std::cout << boost::format(\"len = %d, is = %d, eo = %d\\n\") % len % is % estimated_offset;\n            estimated_pos = begin + estimated_offset;\n            DEBUG_INVARIANT(estimated_offset < len, boost::format(\"%d >= %d from %s [%s .. %s]\")\n                            % estimated_offset % len % v % *begin % *(end - 1));\n            DEBUG_SINVARIANT(estimated_pos < end);\n            if (comparer(*estimated_pos, v)) {\n                begin = estimated_pos;\n                ++begin;\n                if (!comparer(*begin, v)) {\n                    return begin; // this is lower bound since it is not < and one less is\n                }\n                len = len - (estimated_offset + 1);\n            } else { // estimated_pos >= v\n                if (comparer(*(estimated_pos - 1), v)) {\n                    return estimated_pos; // this is the lower bound since it is not < and one less is\n                }\n                end = estimated_pos;\n                len = estimated_offset;\n            }\n        }\n\n        if (len == 0) {\n            return begin;\n        }\n\n        // std::cout << boost::format(\"len = %d\\n\") % len;\n        if (len <= binary_search_below_length) {\n            return std::lower_bound(begin, end, v, comparer);\n        }\n        bool adjusted_begin = false, adjusted_end = false;\n        for (size_t bs = 0; len > 0 && bs < binary_steps; ++bs) {\n            DEBUG_SINVARIANT(begin < end);\n            DEBUG_SINVARIANT((end - begin) == static_cast<ptrdiff_t>(len));\n            estimated_offset = len >> 1;\n            estimated_pos = begin + estimated_offset;\n            if (comparer(*estimated_pos, v)) {\n                begin = estimated_pos;\n                ++begin;\n                len = len - (estimated_offset + 1);\n                adjusted_begin = true;\n            } else {\n                len = estimated_offset;\n                end = estimated_pos;\n                adjusted_end = true;\n            }\n        }\n        // Repair invariants used for interpolation function\n        if (adjusted_begin) {\n            if (!comparer(*begin, v)) {\n                return begin;\n            }\n        }\n        if (adjusted_end) {\n            if (comparer(*(end - 1), v)) {\n                return end;\n            }\n        }\n    }\n    return begin;\n}\n\n} // namespace detail\n\n// We want to write estimator = EstimateOffset<ValueT>, but that requires C++0x\ntemplate<typename ValueT, typename Iterator> Iterator\ninterpolationLowerBound(Iterator begin, Iterator end, const ValueT &v) {\n    EstimateOffset<ValueT> eo;\n    return detail::interpolationLowerBound<2,4,256>(begin, end, v, eo, Compare<ValueT>());\n}\n\n} // namespace lintel\n\n#endif\n", "meta": {"hexsha": "11471e3e76a90daa5f01e14dd772bbd4a310d690", "size": 6377, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/Lintel/unstable/InterpolationSearch.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/unstable/InterpolationSearch.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/unstable/InterpolationSearch.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": 39.1226993865, "max_line_length": 115, "alphanum_fraction": 0.5896189431, "num_tokens": 1519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239836484143, "lm_q2_score": 0.6893056040203135, "lm_q1q2_score": 0.49314576117938913}}
{"text": "#include \"quadrotor_simulator/Quadrotor.h\"\n#include <iostream>\n#include <boost/bind.hpp>\n#include \"odeint-v2/boost/numeric/odeint.hpp\"\n#include <Eigen/Geometry>\n\nnamespace odeint = boost::numeric::odeint;\n\nnamespace QuadrotorSimulator\n{\n\nQuadrotor::Quadrotor(void)\n{\n  g_ = 9.81;\n  mass_ = 0.075;\n  double Ixx = 2.64e-3, Iyy = 2.64e-3, Izz = 4.96e-3;\n  prop_radius_ = 0.099;\n  J_ = Eigen::Vector3d(Ixx, Iyy, Izz).asDiagonal();\n\n  kf_ = 5.55e-8;\n  // km_ = 2.5e-9; // from Nate\n  // km = (Cq/Ct)*Dia*kf\n  // Cq/Ct for 8 inch props from UIUC prop db ~ 0.07\n  km_ = 0.07*(2*prop_radius_)*kf_;\n\n  arm_length_ = 0.17;\n  motor_time_constant_ = 1.0/20;\n  min_rpm_ = 1500;\n  max_rpm_ = 7500;\n\n  state_.x = Eigen::Vector3d::Zero();\n  state_.v = Eigen::Vector3d::Zero();\n  state_.R = Eigen::Matrix3d::Identity();\n  state_.omega = Eigen::Vector3d::Zero();\n  state_.motor_rpm = Eigen::Array4d::Zero();\n  updateInternalState();\n\n  input_ = Eigen::Array4d::Zero();\n}\n\nvoid Quadrotor::step(double dt)\n{\n  odeint::integrate(boost::ref(*this), internal_state_, 0.0, dt, dt);\n\n  for(int i = 0; i < 3; i++)\n  {\n    state_.x(i) = internal_state_[0+i];\n    state_.v(i) = internal_state_[3+i];\n    state_.R(i,0) = internal_state_[6+i];\n    state_.R(i,1) = internal_state_[9+i];\n    state_.R(i,2) = internal_state_[12+i];\n    state_.omega(i) = internal_state_[15+i];\n  }\n  state_.motor_rpm(0) = internal_state_[18];\n  state_.motor_rpm(1) = internal_state_[19];\n  state_.motor_rpm(2) = internal_state_[20];\n  state_.motor_rpm(3) = internal_state_[21];\n\n  // Re-orthonormalize R (polar decomposition)\n  Eigen::LLT<Eigen::Matrix3d> llt(state_.R.transpose()*state_.R);\n  Eigen::Matrix3d P = llt.matrixL();\n  Eigen::Matrix3d R = state_.R*P.inverse();\n  state_.R = R;\n\n  // Don't go below zero, simulate floor\n  if(state_.x(2) < 0.0 && state_.v(2) < 0)\n  {\n    state_.x(2) = 0;\n    state_.v(2) = 0;\n  }\n  updateInternalState();\n}\n\nvoid Quadrotor::operator()(const Quadrotor::InternalState &x, Quadrotor::InternalState &dxdt, const double /* t */)\n{\n  State cur_state;\n  for(int i = 0; i < 3; i++)\n  {\n    cur_state.x(i) = x[0+i];\n    cur_state.v(i) = x[3+i];\n    cur_state.R(i,0) = x[6+i];\n    cur_state.R(i,1) = x[9+i];\n    cur_state.R(i,2) = x[12+i];\n    cur_state.omega(i) = x[15+i];\n  }\n  for(int i = 0; i < 4; i++)\n  {\n    cur_state.motor_rpm(i) = x[18 + i];\n  }\n\n  // Re-orthonormalize R (polar decomposition)\n  Eigen::LLT<Eigen::Matrix3d> llt(cur_state.R.transpose()*cur_state.R);\n  Eigen::Matrix3d P = llt.matrixL();\n  Eigen::Matrix3d R = cur_state.R*P.inverse();\n\n  Eigen::Vector3d x_dot, v_dot, omega_dot;\n  Eigen::Matrix3d R_dot;\n  Eigen::Array4d motor_rpm_dot;\n  Eigen::Array4d motor_rpm_sq;\n  Eigen::Matrix3d omega_hat(Eigen::Matrix3d::Zero());\n\n  omega_hat(2,1) = cur_state.omega(0);\n  omega_hat(1,2) = -cur_state.omega(0);\n  omega_hat(0,2) = cur_state.omega(1);\n  omega_hat(2,0) = -cur_state.omega(1);\n  omega_hat(1,0) = cur_state.omega(2);\n  omega_hat(0,1) = -cur_state.omega(2);\n\n  motor_rpm_sq = cur_state.motor_rpm.square();\n\n  double thrust = kf_*motor_rpm_sq.sum();\n  Eigen::Vector3d moments;\n  moments(0) = kf_*(motor_rpm_sq(2) - motor_rpm_sq(3)) * arm_length_;\n  moments(1) = kf_*(motor_rpm_sq(1) - motor_rpm_sq(0)) * arm_length_;\n  moments(2) = km_*(motor_rpm_sq(0) + motor_rpm_sq(1) - motor_rpm_sq(2) - motor_rpm_sq(3));\n\n  x_dot = cur_state.v;\n  v_dot = -Eigen::Vector3d(0,0,g_) + thrust*R.col(2)/mass_ + external_force_/mass_;\n  R_dot = R*omega_hat;\n  omega_dot = J_.inverse()*(moments - cur_state.omega.cross(J_*cur_state.omega) + external_moment_);\n  motor_rpm_dot = (input_ - cur_state.motor_rpm)/motor_time_constant_;\n\n  for(int i = 0; i < 3; i++)\n  {\n    dxdt[0+i] = x_dot(i);\n    dxdt[3+i] = v_dot(i);\n    dxdt[6+i] = R_dot(i,0);\n    dxdt[9+i] = R_dot(i,1);\n    dxdt[12+i] = R_dot(i,2);\n    dxdt[15+i] = omega_dot(i);\n  }\n  for(int i = 0; i < 4; i++)\n  {\n    dxdt[18 + i] = motor_rpm_dot(i);\n  }\n}\n\nvoid Quadrotor::setInput(double u1, double u2, double u3, double u4)\n{\n  input_(0) = u1;\n  input_(1) = u2;\n  input_(2) = u3;\n  input_(3) = u4;\n  for(int i = 0; i < 4; i++)\n  {\n    if(input_(i) > max_rpm_)\n      input_(i) = max_rpm_;\n    else if(input_(i) < min_rpm_)\n      input_(i) = min_rpm_;\n  }\n}\n\nconst Quadrotor::State &Quadrotor::getState(void) const\n{\n  return state_;\n}\nvoid Quadrotor::setState(const Quadrotor::State &state)\n{\n  state_.x = state.x;\n  state_.v = state.v;\n  state_.R = state.R;\n  state_.omega = state.omega;\n  state_.motor_rpm = state.motor_rpm;\n\n  updateInternalState();\n}\n\ndouble Quadrotor::getMass(void) const\n{\n  return mass_;\n}\nvoid Quadrotor::setMass(double mass)\n{\n  mass_ = mass;\n}\n\ndouble Quadrotor::getGravity(void) const\n{\n  return g_;\n}\nvoid Quadrotor::setGravity(double g)\n{\n  g_ = g;\n}\n\nconst Eigen::Matrix3d &Quadrotor::getInertia(void) const\n{\n  return J_;\n}\nvoid Quadrotor::setInertia(const Eigen::Matrix3d &inertia)\n{\n  if(inertia != inertia.transpose())\n  {\n    std::cerr << \"Inertia matrix not symmetric, not setting\" << std::endl;\n    return;\n  }\n  J_ = inertia;\n}\n\ndouble Quadrotor::getArmLength(void) const\n{\n  return arm_length_;\n}\nvoid Quadrotor::setArmLength(double d)\n{\n  if(d <= 0)\n  {\n    std::cerr << \"Arm length <= 0, not setting\" << std::endl;\n    return;\n  }\n\n  arm_length_ = d;\n}\n\ndouble Quadrotor::getPropRadius(void) const\n{\n  return prop_radius_;\n}\nvoid Quadrotor::setPropRadius(double r)\n{\n  if(r <= 0)\n  {\n    std::cerr << \"Prop radius <= 0, not setting\" << std::endl;\n    return;\n  }\n  prop_radius_ = r;\n}\n\ndouble Quadrotor::getPropellerThrustCoefficient(void) const\n{\n  return kf_;\n}\nvoid Quadrotor::setPropellerThrustCoefficient(double kf)\n{\n  if(kf <= 0)\n  {\n    std::cerr << \"Thrust coefficient <= 0, not setting\" << std::endl;\n    return;\n  }\n\n  kf_ = kf;\n}\n\ndouble Quadrotor::getPropellerMomentCoefficient(void) const\n{\n  return km_;\n}\nvoid Quadrotor::setPropellerMomentCoefficient(double km)\n{\n  if(km <= 0)\n  {\n    std::cerr << \"Moment coefficient <= 0, not setting\" << std::endl;\n    return;\n  }\n\n  km_ = km;\n}\n\ndouble Quadrotor::getMotorTimeConstant(void) const\n{\n  return motor_time_constant_;\n}\nvoid Quadrotor::setMotorTimeConstant(double k)\n{\n  if(k <= 0)\n  {\n    std::cerr << \"Motor time constant <= 0, not setting\" << std::endl;\n    return;\n  }\n\n  motor_time_constant_ = k;\n}\n\nconst Eigen::Vector3d &Quadrotor::getExternalForce(void) const\n{\n  return external_force_;\n}\nvoid Quadrotor::setExternalForce(const Eigen::Vector3d &force)\n{\n  external_force_ = force;\n}\n\nconst Eigen::Vector3d &Quadrotor::getExternalMoment(void) const\n{\n  return external_moment_;\n}\nvoid Quadrotor::setExternalMoment(const Eigen::Vector3d &moment)\n{\n  external_moment_ = moment;\n}\n\ndouble Quadrotor::getMaxRPM(void) const\n{\n  return max_rpm_;\n}\nvoid Quadrotor::setMaxRPM(double max_rpm)\n{\n  if(max_rpm <= 0)\n  {\n    std::cerr << \"Max rpm <= 0, not setting\" << std::endl;\n    return;\n  }\n  max_rpm_ = max_rpm;\n}\n\ndouble Quadrotor::getMinRPM(void) const\n{\n  return min_rpm_;\n}\nvoid Quadrotor::setMinRPM(double min_rpm)\n{\n  if(min_rpm < 0)\n  {\n    std::cerr << \"Min rpm < 0, not setting\" << std::endl;\n    return;\n  }\n  min_rpm_ = min_rpm;\n}\n\nvoid Quadrotor::updateInternalState(void)\n{\n  for(int i = 0; i < 3; i++)\n  {\n    internal_state_[0+i] = state_.x(i);\n    internal_state_[3+i] = state_.v(i);\n    internal_state_[6+i] = state_.R(i,0);\n    internal_state_[9+i] = state_.R(i,1);\n    internal_state_[12+i] = state_.R(i,2);\n    internal_state_[15+i] = state_.omega(i);\n  }\n  internal_state_[18] = state_.motor_rpm(0);\n  internal_state_[19] = state_.motor_rpm(1);\n  internal_state_[20] = state_.motor_rpm(2);\n  internal_state_[21] = state_.motor_rpm(3);\n}\n\n}\n", "meta": {"hexsha": "245df1b17b12badd823862bd7419e418e618f3db", "size": 7618, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Src/ros_simulator/src/quadrotor_simulator/src/dynamics/Quadrotor_back.cpp", "max_stars_repo_name": "Drona-Org/Drona-DMR", "max_stars_repo_head_hexsha": "ecc756ec137aee90ab5ac9ea97f09b6e030066f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-05-14T14:49:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T06:53:28.000Z", "max_issues_repo_path": "Src/ros_simulator/src/quadrotor_simulator/src/dynamics/Quadrotor_back.cpp", "max_issues_repo_name": "Dronacharya-Org/Dronacharya", "max_issues_repo_head_hexsha": "ecc756ec137aee90ab5ac9ea97f09b6e030066f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Src/ros_simulator/src/quadrotor_simulator/src/dynamics/Quadrotor_back.cpp", "max_forks_repo_name": "Dronacharya-Org/Dronacharya", "max_forks_repo_head_hexsha": "ecc756ec137aee90ab5ac9ea97f09b6e030066f0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-12-15T20:18:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-31T19:26:57.000Z", "avg_line_length": 22.5384615385, "max_line_length": 115, "alphanum_fraction": 0.6508269887, "num_tokens": 2654, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4931306571026664}}
{"text": "// Std includes\n#include <cmath>\n#include <iostream>\n#include <memory>\n// Thirdparties includes\n#include <Eigen/Dense>\n// Lib includes\n#include \"s0s/runge_kutta_fehlberg.h\"\n#include \"sl0/point.h\"\n#include \"sl0/chain/static.h\"\n// Simple includes\n#include \"flow.h\"\n\nusing TypeScalar = double;\n// State\ntemplate<int StateSize>\nusing TypeState = Eigen::Matrix<TypeScalar, StateSize, 1>;\nusing TypeStateDynamic = Eigen::Matrix<TypeScalar, Eigen::Dynamic, 1>;\n// Space\nconstexpr unsigned int DIM = 3;\nusing TypeVector = Eigen::Matrix<TypeScalar, DIM, 1>;\n// Ref and View\ntemplate<typename ...Args>\nusing TypeRef = Eigen::Ref<Args...>;\ntemplate<typename ...Args>\nusing TypeView = Eigen::Map<Args...>;\n// Group Parameters\nusing TypeStepPoint = sl0::StepPoint<TypeState, DIM, TypeRef, TypeView, Flow>;\n// Solver\nusing TypeSolver = s0s::SolverRungeKuttaFehlberg;\n\nconst unsigned int np = 10;\n\nint main () { \n    // Parameters\n    TypeVector x0 = TypeVector({0.0, 0.0, 0.0});\n    TypeScalar t0 = 0.0;\n    TypeScalar dt = 1e-3;\n    unsigned int nt = std::round(1.0 / dt);\n    double l = 1.0;\n    // Create chain\n    std::shared_ptr<TypeStepPoint> sStepPoint = std::make_shared<TypeStepPoint>(std::make_shared<Flow>());\n    sl0::ChainStatic<TypeState, DIM, TypeRef, np, TypeView, TypeStepPoint, TypeSolver> chain(sStepPoint, l, 4);\n    // Init\n    for(std::size_t i = 0; i < np; i++) {\n        sStepPoint->x(chain.sStep->memberState(chain.state, i)) = x0;\n        sStepPoint->x(chain.sStep->memberState(chain.state, i))[0] += i * l/double(np-1);\n    }\n    std::cout << \"Init Length : \" << \"\\n\" << chain.sStep->actualLength(chain.state) << \"\\n\";\n    std::cout << \"Init State : \" << \"\\n\" << chain.state << \"\\n\";\n    chain.t = t0;\n    // Computation\n    std::cout << \"Computing\" << \"\\n\";\n    for(std::size_t i = 0; i < nt; i++) {\n        chain.update(dt);\n    }\n    // out\n    std::cout << \"\\n\";\n    std::cout << \"Chain advected following an exponential flow, exp(\" << chain.t << \") = \" << \"\\n\";\n    std::cout << \"\\n\";\n    std::cout << \"Final State : \" << \"\\n\" << chain.state << \"\\n\";\n    std::cout << \"Final Length : \" << \"\\n\" << chain.sStep->actualLength(chain.state) << \"\\n\";\n    std::cout << std::endl;\n}\n\n", "meta": {"hexsha": "095c55c6069a9b3183086f0509e06fa6d6d639f4", "size": 2194, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/chain/static/main.cpp", "max_stars_repo_name": "C0PEP0D/sl0", "max_stars_repo_head_hexsha": "65d6a6c6d9c230676aaa4088fc411dc3971ec15a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/chain/static/main.cpp", "max_issues_repo_name": "C0PEP0D/sl0", "max_issues_repo_head_hexsha": "65d6a6c6d9c230676aaa4088fc411dc3971ec15a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/chain/static/main.cpp", "max_forks_repo_name": "C0PEP0D/sl0", "max_forks_repo_head_hexsha": "65d6a6c6d9c230676aaa4088fc411dc3971ec15a", "max_forks_repo_licenses": ["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.2424242424, "max_line_length": 111, "alphanum_fraction": 0.6257976299, "num_tokens": 666, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4931306571026664}}
{"text": "#include \"TensorCoreLinesEvaluator.hh\"\n\n#include <Eigen/Geometry>\n\n#include <boost/algorithm/cxx11/any_of.hpp>\n#include <boost/range/algorithm/min_element.hpp>\n#include <boost/range/algorithm/max_element.hpp>\n\n#include <vector>\n#include <tuple>\n#include <utility>\n\nusing namespace cpp_utils;\n\nnamespace tl\n{\n\ntemplate <typename T, std::size_t... Degrees>\nusing TPBT = TensorProductBezierTriangle<T, double, Degrees...>;\n\nstd::pair<std::array<TPBT<double, 1, 2>, 3>, std::array<TPBT<double, 0, 3>, 3>>\ntensorCoreLinesCoeffs(const TensorInterp& t,\n                      const std::array<TensorInterp, 3>& dt,\n                      const Triangle& r)\n{\n    using Coords1 = TPBT<double, 1, 2>::Coords;\n    using Coords2 = TPBT<double, 0, 3>::Coords;\n\n    // (T * r) x r\n    auto eval_ev =\n            [&](const Coords1& coords, const TensorInterp& t, int i) -> double {\n        auto rv = r(coords.tail<3>());\n        auto tv = t(coords.head<3>());\n        return (tv * rv).cross(rv)[i];\n    };\n\n    // ((\\nabla T * r) * r) x r\n    auto eval_deriv_ev = [&](const Coords2& coords,\n                             const std::array<TensorInterp, 3>& dt,\n                             int i) -> double {\n        auto rv = r(coords.tail<3>());\n        auto txv = dt[0](coords.head<3>());\n        auto tyv = dt[1](coords.head<3>());\n        auto tzv = dt[2](coords.head<3>());\n\n        return ((txv * rv[0] + tyv * rv[1] + tzv * rv[2]) * rv).cross(rv)[i];\n    };\n\n    auto eval1 = [&](const Coords1& coords) { return eval_ev(coords, t, 0); };\n    auto eval2 = [&](const Coords1& coords) { return eval_ev(coords, t, 1); };\n    auto eval3 = [&](const Coords1& coords) { return eval_ev(coords, t, 2); };\n\n    auto eval4 = [&](const Coords2& coords) {\n        return eval_deriv_ev(coords, dt, 0);\n    };\n    auto eval5 = [&](const Coords2& coords) {\n        return eval_deriv_ev(coords, dt, 1);\n    };\n    auto eval6 = [&](const Coords2& coords) {\n        return eval_deriv_ev(coords, dt, 2);\n    };\n\n    return {{TPBT<double, 1, 2>{eval1},\n             TPBT<double, 1, 2>{eval2},\n             TPBT<double, 1, 2>{eval3}},\n            {TPBT<double, 0, 3>{eval4},\n             TPBT<double, 0, 3>{eval5},\n             TPBT<double, 0, 3>{eval6}}};\n}\n\n\nusing TSHE = TensorCoreLinesEvaluator;\n\nTSHE::TensorCoreLinesEvaluator(const DoubleTri& tri,\n                               const TensorInterp& t,\n                               const std::array<TensorInterp, 3>& dt,\n                               const Options& opts)\n        : _tri(tri),\n          _opts(opts)\n{\n    std::tie(_target_funcs_t, _target_funcs_dt) =\n            tensorCoreLinesCoeffs(t, dt, tri.dir_tri);\n}\n\n\nstd::array<TSHE, 4> TSHE::split() const\n{\n    if(_last_split_dir)\n    {\n        return split<0>();\n    }\n    return split<1>();\n}\n\n\nResult TSHE::eval()\n{\n    // Check if any of the error components can not become zero in the\n    // current subdivision triangles\n    auto has_nonzero =\n            boost::algorithm::any_of(_target_funcs_t, [](const auto& c) {\n                    return sameSign(c.coefficients()) != 0;\n            })\n            || boost::algorithm::any_of(_target_funcs_dt, [](const auto& c) {\n                   return sameSign(c.coefficients()) != 0;\n               });\n\n    // Discard triangles if no roots can occur inside\n    if(has_nonzero)\n    {\n        return Result::Discard;\n    }\n\n    // Compute upper bound for target functions\n    auto max_error = std::max(abs_max_upper_bound(_target_funcs_t),\n                              abs_max_upper_bound(_target_funcs_dt));\n\n    if(max_error < _opts.tolerance)\n    {\n        return Result::Accept;\n    }\n\n    return Result::Split;\n}\n\n\ndouble TSHE::error() const\n{\n    return std::max(upper_bound_norm(_target_funcs_t),\n                    upper_bound_norm(_target_funcs_dt));\n}\n\n\ndouble distance(const TSHE& t1, const TSHE& t2)\n{\n    return distance(t1.tris(), t2.tris());\n}\n\n\nbool operator==(const TSHE& t1, const TSHE& t2)\n{\n    return t1._tri == t2._tri && t1._target_funcs_t == t2._target_funcs_t\n           && t1._target_funcs_dt == t2._target_funcs_dt\n           && t1._last_split_dir == t2._last_split_dir\n           && t1._split_level == t2._split_level && t1._opts == t2._opts;\n}\n\n\nbool operator!=(const TSHE& t1, const TSHE& t2)\n{\n    return !(t1 == t2);\n}\n\n}\n", "meta": {"hexsha": "877c52fd143fe002ca88516dcb9d0c1a18702114", "size": 4294, "ext": "cc", "lang": "C++", "max_stars_repo_path": "cpp/src/TensorCoreLinesEvaluator.cc", "max_stars_repo_name": "timo-oster/tensor-lines", "max_stars_repo_head_hexsha": "b4f489452f3ce5b5f48042cc035e53d3fdaa675e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cpp/src/TensorCoreLinesEvaluator.cc", "max_issues_repo_name": "timo-oster/tensor-lines", "max_issues_repo_head_hexsha": "b4f489452f3ce5b5f48042cc035e53d3fdaa675e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp/src/TensorCoreLinesEvaluator.cc", "max_forks_repo_name": "timo-oster/tensor-lines", "max_forks_repo_head_hexsha": "b4f489452f3ce5b5f48042cc035e53d3fdaa675e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-13T00:08:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-13T00:08:09.000Z", "avg_line_length": 27.7032258065, "max_line_length": 80, "alphanum_fraction": 0.5696320447, "num_tokens": 1188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118111485244, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4930783265774413}}
{"text": "#include <boost/math/distributions/weibull.hpp>\n", "meta": {"hexsha": "f882bdae9bc11f862f0487f7187de3445dc13636", "size": 48, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_distributions_weibull.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_distributions_weibull.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_distributions_weibull.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 24.0, "max_line_length": 47, "alphanum_fraction": 0.8125, "num_tokens": 11, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118111485244, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4930783265774413}}
{"text": "/** @file\n    @brief Implementation\n\n    @date 2015\n\n    @author\n    Sensics, Inc.\n    <http://sensics.com/osvr>\n*/\n\n// Copyright 2015 Sensics, Inc.\n//\n// SPDX-License-Identifer: Apache-2.0\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/Core>\n#include <Eigen/Geometry>\n#include <iostream>\ntemplate <typename T>\ninline void dumpKalmanDebugOuput(const char name[], const char expr[],\n                                 T const &value) {\n    std::cout << \"\\n(Kalman Debug Output) \" << name << \" [\" << expr << \"]:\\n\"\n              << value << std::endl;\n}\n\n#define FLEXKALMAN_DEBUG_OUTPUT(Name, Value)                                   \\\n    dumpKalmanDebugOuput(Name, #Value, Value)\n\n// Internal Includes\n#include \"FlexKalman/AbsoluteOrientationMeasurement.h\"\n#include \"FlexKalman/FlexibleKalmanFilter.h\"\n#include \"FlexKalman/PoseConstantVelocity.h\"\n\n#include \"ContentsInvalid.h\"\n\n// Library/third-party includes\n// - none\n\n// Standard includes\n#include <iostream>\n\nint main() {\n    using ProcessModel = flexkalman::PoseConstantVelocityProcessModel;\n    using State = flexkalman::pose_externalized_rotation::State;\n    using Measurement = flexkalman::AbsoluteOrientationEKFMeasurement<State>;\n    State state;\n    ProcessModel processModel;\n    std::cout << \"Initial state:\" << std::endl;\n    std::cout << state << std::endl;\n    {\n        auto meas = Measurement{Eigen::Quaterniond::Identity(),\n                                Eigen::Vector3d(0.00001, 0.00001, 0.00001)};\n        std::cout << \"Measurement covariance:\\n\"\n                  << meas.getCovariance(state) << std::endl;\n\n        for (int i = 0; i < 100; ++i) {\n            flexkalman::predict(state, processModel, 0.1);\n\n            std::cout << \"\\nAfter prediction (iteration \" << i << \"):\\n\"\n                      << state << std::endl;\n            if (stateContentsInvalid(state)) {\n                std::cout << \"ERROR: Detected invalid state contents after \"\n                             \"prediction step of iteration \"\n                          << i << std::endl;\n                return -1;\n            }\n            if (covarianceContentsInvalid(state)) {\n                std::cout << \"ERROR: Detected invalid covariance contents \"\n                             \"after prediction step of iteration \"\n                          << i << std::endl;\n                return -1;\n            }\n            flexkalman::correct(state, processModel, meas);\n            std::cout << \"\\nAfter correction (iteration \" << i << \"):\\n\"\n                      << state << std::endl;\n            if (stateContentsInvalid(state)) {\n                std::cout << \"ERROR: Detected invalid state contents after \"\n                             \"correction step of iteration \"\n                          << i << std::endl;\n                return -1;\n            }\n            if (covarianceContentsInvalid(state)) {\n                std::cout << \"ERROR: Detected invalid covariance contents \"\n                             \"after correction step of iteration \"\n                          << i << std::endl;\n                return -1;\n            }\n        }\n    }\n    std::cout << \"SUCCESS: ran till completion of configured number of \"\n                 \"iterations without denormalizing in some way.\"\n              << std::endl;\n    return 0;\n}\n", "meta": {"hexsha": "19269a4d9ce55117d6712990801da492ae4c9420", "size": 3808, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/cplusplus/Kalman/ManualTest.cpp", "max_stars_repo_name": "rpavlik/FlexKalman", "max_stars_repo_head_hexsha": "908ed252cc1312bcdc30d6a6d82e38056ca7dcb8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/cplusplus/Kalman/ManualTest.cpp", "max_issues_repo_name": "rpavlik/FlexKalman", "max_issues_repo_head_hexsha": "908ed252cc1312bcdc30d6a6d82e38056ca7dcb8", "max_issues_repo_licenses": ["Apache-2.0"], "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/cplusplus/Kalman/ManualTest.cpp", "max_forks_repo_name": "rpavlik/FlexKalman", "max_forks_repo_head_hexsha": "908ed252cc1312bcdc30d6a6d82e38056ca7dcb8", "max_forks_repo_licenses": ["Apache-2.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.9245283019, "max_line_length": 80, "alphanum_fraction": 0.5648634454, "num_tokens": 828, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095992, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.4930783214845433}}
{"text": "#include \"mLibInclude.h\"\n#include \"../../shared/OptUtils.h\"\n#define GLOG_NO_ABBREVIATED_SEVERITIES\n#include <Eigen33b1/Eigen>\n#include <Eigen33b1/IterativeLinearSolvers>\n#include <cuda_runtime.h>\n\n#include <time.h>\n\n#define LEAST_SQ_CONJ_GRADIENT 0\n#define SPARSE_QR 1\n\n#define SOLVER LEAST_SQ_CONJ_GRADIENT\n\ntypedef Eigen::Triplet<float> Tripf;\ntypedef Eigen::SparseMatrix<float> SpMatrixf;\n#include \"EigenSolverPoissonImageEditing.h\"\n#include <Eigen33b1/OrderingMethods>\n\n#if SOLVER == LEAST_SQ_CONJ_GRADIENT\ntypedef Eigen::LeastSquaresConjugateGradient<SpMatrixf > AxEqBSolver;\n#elif SOLVER == SPARSE_QR\ntypedef Eigen::SparseQR<SpMatrixf, Eigen::COLAMDOrdering<int> > AxEqBSolver;\n#endif\n\nstruct vec2iHash {\n    size_t operator()(const vec2i& v) const {\n        return std::hash < int > {}(v.x) ^ std::hash < int > {}(v.y);\n    }\n};\n\n\nfloat4 sampleImage(float4* image, vec2i p, int W) {\n    return image[p.y*W + p.x];\n}\n\nvoid setPixel(float4* image, vec2i p, int W, float r, float g, float b) {\n    image[p.y*W + p.x].x = r;\n    image[p.y*W + p.x].y = g;\n    image[p.y*W + p.x].z = b;\n}\n\nvoid solveAxEqb(AxEqBSolver& solver, const Eigen::VectorXf& b, Eigen::VectorXf& x) {\n    \n#if SOLVER==LEAST_SQ_CONJ_GRADIENT\n    x = solver.solveWithGuess(b, x);\n    //std::cout << \"#iterations:     \" << solver.iterations() << std::endl;\n    //std::cout << \"estimated error: \" << solver.error() << std::endl;\n#else\n    x = solver.solve(b);\n#endif\n}\ndouble EigenSolverPoissonImageEditing::solve(const NamedParameters& solverParameters, const NamedParameters& problemParameters, bool profileSolve, std::vector<SolverIteration>& iters)\n{\n    int numUnknowns = 0;\n    std::unordered_map<vec2i, int, vec2iHash> pixelLocationsToIndex;\n    std::vector<vec2i> pixelLocations;\n    size_t pixelCount = m_dims[0] * m_dims[1];\n    std::vector<float4> h_unknownFloat(pixelCount);\n    std::vector<float4> h_target(pixelCount);\n    std::vector<float>  h_mask(pixelCount);\n\n    findAndCopyArrayToCPU(\"X\", h_unknownFloat, problemParameters);\n    findAndCopyArrayToCPU(\"T\", h_target, problemParameters);\n    findAndCopyArrayToCPU(\"M\", h_mask, problemParameters);\n\n    for (int y = 0; y < (int)m_dims[1]; ++y) {\n        for (int x = 0; x < (int)m_dims[0]; ++x) {\n            if (h_mask[y*m_dims[0] + x] == 0.0f) {\n                ++numUnknowns;\n                vec2i p(x, y);\n                pixelLocationsToIndex[p] =(int)pixelLocations.size();\n                pixelLocations.push_back(p);\n            }\n        }\n    }\n    printf(\"# Unknowns: %d\\n\", numUnknowns);\n    int numResiduals = (int)pixelLocations.size() * 4;\n\n    Eigen::VectorXf x_r(numUnknowns), b_r(numResiduals);\n    Eigen::VectorXf x_g(numUnknowns), b_g(numResiduals);\n    Eigen::VectorXf x_b(numUnknowns), b_b(numResiduals);\n    Eigen::VectorXf x_a(numUnknowns), b_a(numResiduals);\n\n    b_r.setZero();\n    b_g.setZero();\n    b_b.setZero();\n    b_a.setZero();\n\n    for (int i = 0; i < pixelLocations.size(); ++i) {\n        vec2i p = pixelLocations[i];\n        float4 color = sampleImage(h_unknownFloat.data(), p, m_dims[0]);\n        x_r[i] = color.x;\n        //printf(\"%f\\n\", color.x);\n        x_g[i] = color.y;\n        x_b[i] = color.z;\n        x_a[i] = color.w;\n    }\n    SpMatrixf A(numResiduals, numUnknowns);\n    A.setZero();\n    printf(\"Constructing Matrix\\n\");\n    std::vector<Tripf> entriesA;\n\n    std::vector<vec2i> offsets;\n    offsets.push_back(vec2i(-1, 0));\n    offsets.push_back(vec2i(1, 0));\n    offsets.push_back(vec2i(0, -1));\n    offsets.push_back(vec2i(0, 1));\n\n    for (int i = 0; i < pixelLocations.size(); ++i) {\n        vec2i p = pixelLocations[i];\n        int numInternalNeighbors = 0;\n        float4 g_p = sampleImage(h_target.data(), p, m_dims[0]);\n        int j = 0;\n\n        for (vec2i off : offsets) {\n            vec2i q = p + off;\n            if (q.x >= 0 && q.y >= 0 && q.x < (int)m_dims[0] && q.y < (int)m_dims[1]) {\n                auto it = pixelLocationsToIndex.find(q);\n                int row = 4 * i + j;\n                if (it == pixelLocationsToIndex.end()) {\n                    float4 f_q = sampleImage(h_unknownFloat.data(), q, m_dims[0]);\n                    b_r[row] += f_q.x;\n                    b_g[row] += f_q.y;\n                    b_b[row] += f_q.z;\n                    b_a[row] += f_q.w;\n                }\n                else {\n                    entriesA.push_back(Tripf(row, it->second, -1.0f));\n                }\n                entriesA.push_back(Tripf(row, i, 1.0f));\n\n                float4 g_q = sampleImage(h_target.data(), q, m_dims[0]);\n                b_r[row] += (g_p.x - g_q.x);\n                b_g[row] += (g_p.y - g_q.y);\n                b_b[row] += (g_p.z - g_q.z);\n                b_a[row] += (g_p.w - g_q.w);\n            }\n            ++j;\n            \n        }\n    }\n    \n\n    printf(\"Entries Set\\n\");\n    A.setFromTriplets(entriesA.begin(), entriesA.end());\n    printf(\"Sparse Matrix Constructed\\n\");\n    A.makeCompressed();\n    printf(\"Matrix Compressed\\n\");\n    {\n        float totalCost = 0.0f;\n        \n        float cost_r = (A*x_r - b_r).squaredNorm();\n        float cost_g = (A*x_g - b_g).squaredNorm();\n        float cost_b = (A*x_b - b_b).squaredNorm();\n        float cost_a = (A*x_a - b_a).squaredNorm();\n        totalCost = cost_r + cost_g + cost_b + cost_a;\n        printf(\"Initial Cost: %f : (%f, %f, %f, %f)\\n\", totalCost, cost_r, cost_g, cost_b, cost_a);\n\n    }\n    \n\n    AxEqBSolver solver;\n    solver.setMaxIterations(97);\n    printf(\"Solvers Initialized\\n\");\n\n    clock_t start = clock(), diff;\n    \n    solver.compute(A);\n    //printf(\"solver.compute(A)\\n\");\n    solveAxEqb(solver, b_r, x_r);\n    //printf(\"Red solve done\\n\");\n    solveAxEqb(solver, b_g, x_g);\n    //printf(\"Green solve done\\n\");\n    solveAxEqb(solver, b_b, x_b);\n    //printf(\"Blue solve done\\n\");\n    solveAxEqb(solver, b_a, x_a);\n\n    diff = clock() - start;\n    printf(\"Time taken %f ms\\n\", diff*1000.0 / double(CLOCKS_PER_SEC));\n\n    float totalCost = 0.0f;\n \n    float cost_r = (A*x_r - b_r).squaredNorm(); \n    float cost_g = (A*x_g - b_g).squaredNorm();\n    float cost_b = (A*x_b - b_b).squaredNorm();\n    float cost_a = (A*x_a - b_a).squaredNorm();\n    totalCost = cost_r + cost_g + cost_b + cost_a;\n    printf(\"Final Cost: %f : (%f, %f, %f, %f)\\n\", totalCost, cost_r, cost_g, cost_b, cost_a);\n\n    for (int i = 0; i < pixelLocations.size(); ++i) {\n        setPixel(h_unknownFloat.data(), pixelLocations[i], m_dims[0], x_r[i], x_g[i], x_b[i]);\n    }\n    findAndCopyToArrayFromCPU(\"X\", h_unknownFloat, problemParameters);;\n    return (double)totalCost;\n\n}\n\n\n/* Proper Poisson Image Editing\n\nfor (int i = 0; i < pixelLocations.size(); ++i) {\nvec2i p = pixelLocations[i];\nint row = i;\nint numInternalNeighbors = 0;\nfloat4 g_p = sampleImage(h_target, p, m_width);\nfor (int off_y = -1; off_y <= 1; off_y += 2) {\nfor (int off_x = -1; off_x <= 1; off_x += 2) {\nvec2i q(p.x + off_x, p.y + off_y);\nauto it = pixelLocationsToIndex.find(q);\nif (it != pixelLocationsToIndex.end()) {\n++numInternalNeighbors;\nentriesA.push_back(Tripf(row, it->second, -1.0f));\n} else {\n\nfloat4 f_star_q = sampleImage(h_target, q, m_width);\nb_r[i] += f_star_q.x;\nb_g[i] += f_star_q.y;\nb_b[i] += f_star_q.z;\n}\nfloat4 g_q = sampleImage(h_target, q, m_width);\nb_r[i] += (g_p.x - g_q.x);\nb_g[i] += (g_p.y - g_q.y);\nb_b[i] += (g_p.z - g_q.z);\n}\n}\nentriesA.push_back(Tripf(row, row, (float)numInternalNeighbors));\n}\n\n*/\n", "meta": {"hexsha": "282178a079d54a03ae8728ef4f53fc5114208572", "size": 7391, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/poisson_image_editing/src/EigenSolverPoissonImageEditing.cpp", "max_stars_repo_name": "zhangxaochen/Opt", "max_stars_repo_head_hexsha": "7f1af802bfc84cc9ef1adb9facbe4957078f529a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 260.0, "max_stars_repo_stars_event_min_datetime": "2017-03-02T19:57:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-21T03:52:03.000Z", "max_issues_repo_path": "examples/poisson_image_editing/src/EigenSolverPoissonImageEditing.cpp", "max_issues_repo_name": "zhangxaochen/Opt", "max_issues_repo_head_hexsha": "7f1af802bfc84cc9ef1adb9facbe4957078f529a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 102.0, "max_issues_repo_issues_event_min_datetime": "2017-03-03T00:42:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T14:15:20.000Z", "max_forks_repo_path": "examples/poisson_image_editing/src/EigenSolverPoissonImageEditing.cpp", "max_forks_repo_name": "zhangxaochen/Opt", "max_forks_repo_head_hexsha": "7f1af802bfc84cc9ef1adb9facbe4957078f529a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 71.0, "max_forks_repo_forks_event_min_datetime": "2017-03-02T20:22:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-02T03:49:04.000Z", "avg_line_length": 31.9956709957, "max_line_length": 183, "alphanum_fraction": 0.5946421323, "num_tokens": 2293, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117983401363, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.493078318938094}}
{"text": "#include <ompl/base/spaces/SE2StateSpace.h>\n#include <ompl/control/spaces/RealVectorControlSpace.h>\n#include <ompl/tools/config/SelfConfig.h>\n#include <limits>\n#include <boost/function.hpp>\n#include <boost/bind.hpp>\n\n#include \"pid_ctrl.h\"\n\nnamespace ob = ompl::base;\nnamespace oc = ompl::control;\n\nompl::control::PID::PID(const SpaceInformationPtr &si) : base::Planner(si, \"PID\")\n{\n\tspecs_.approximateSolutions = true;\n\tsiC_ = si.get();\n}\n\nompl::control::PID::~PID(void)\n{\n}\n\nvoid ompl::control::PID::setup(void)\n{\n\tbase::Planner::setup();\n}\n\nvoid ompl::control::PID::clear(void)\n{\n\tPlanner::clear();\n\tsampler_.reset();\n\tcontrolSampler_.reset();\n}\n\nvoid ompl::control::PID::control_action(oc::Control*& control, ob::State*& state)\n{\n\tstatic const double KP = 25.0;\n\tstatic const double KD = 5.0;\n\t//static const double KP = 0.0;\n\t//static const double KD = 0.0;\n\tdouble* u = control->as<oc::RealVectorControlSpace::ControlType>()->values;\n\n\tconst ompl::base::CompoundState* cstate = state->as<ompl::base::CompoundState>();\n\tconst ompl::base::SO2StateSpace::StateType* theta = cstate->as<ompl::base::SO2StateSpace::StateType>(1);\n\tconst ompl::base::SO2StateSpace::StateType* omega = cstate->as<ompl::base::SO2StateSpace::StateType>(3);\n\n\t*u = KP * theta->value + KD * omega->value;\n}\nompl::base::PlannerStatus ompl::control::PID::solve(const base::PlannerTerminationCondition &ptc)\n{\n\tcheckValidity();\n\tbase::Goal                   *goal = pdef_->getGoal().get();\n\n\twhile (const base::State *st = pis_.nextStart())\n\t{\n\t\tmotions.push_back(new Motion(siC_));\n\t\tsi_->copyState(motions.back()->state, st);\n\t\tsiC_->nullControl(motions.back()->control);\n\t}\n\n\tif(motions.empty())\n\t{\n\t\tOMPL_ERROR(\"Invalid Start State\");\n\t\treturn base::PlannerStatus::INVALID_START;\n\t}\n\n\tif (!sampler_)\n\t{\n\t\tsampler_ = si_->allocStateSampler();\n\t}\n\n\tif (!controlSampler_)\n\t{\n\t\tcontrolSampler_ = siC_->allocDirectedControlSampler();\n\t}\n\n\tbool solved = false;\n\tdouble  approxdif = std::numeric_limits<double>::infinity();\n\twhile (ptc == false)\n\t{\n\t\t/* create a motion */\n\t\t// Add PID control action\n\t\tMotion* new_motion = new Motion(siC_);\n\t\tnew_motion->state = si_->allocState();\n\t\tsiC_->nullControl(new_motion->control);\n\t\tcontrol_action(new_motion->control, motions.back()->state);\n\n\t\t// Add State Propagation\n\t\tunsigned int cd = siC_->propagateWhileValid(motions.back()->state, new_motion->control, siC_->getMinControlDuration(), new_motion->state); \n\t\tmotions.push_back(new_motion);\n\n\t\tdouble dist = 0.0;\n\t\tbool solv = goal->isSatisfied(new_motion->state, &dist);\n\t\tif(solv)\n\t\t{\n\t\t\tsolved = true;\n\t\t}\n\n\t\tif(dist < approxdif)\n\t\t{\n\t\t\tapproxdif = dist;\n\t\t}\n\t}\n\n\t/* set the solution path */\n\tPathControl *path = new PathControl(si_);\n\tfor (unsigned i = 0 ; i < motions.size()-1; ++i)\n\t{\n\t\tpath->append(motions[i]->state, motions[i]->control, siC_->getPropagationStepSize());\n\t}\n\tpath->append(motions[motions.size()-1]->state);\n\tpdef_->addSolutionPath(base::PathPtr(path), false, approxdif);\n\treturn base::PlannerStatus(true, solved);\n}\n\nvoid ompl::control::PID::getPlannerData(base::PlannerData &data) const\n{\n\tPlanner::getPlannerData(data);\n\tdouble delta = siC_->getPropagationStepSize();\n\n\tif (motions.back())\n\t{\n\t\tdata.addGoalVertex(base::PlannerDataVertex(motions.back()->state));\n\t}\n\n\tfor (int i = motions.size()-1 ; i >= 1 ; --i)\n\t{\n\t\tconst Motion* m = motions[i];\n\t\tdata.addEdge(base::PlannerDataVertex(motions[i-1]->state), base::PlannerDataVertex(m->state), control::PlannerDataEdgeControl(m->control, delta));\n\t}\n\tdata.addStartVertex(base::PlannerDataVertex(motions.front()->state));\n}\n", "meta": {"hexsha": "ff15db73db099bdb20f9e247d008b0d6461bb99e", "size": 3569, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "RSpring/rtr_copilot/inverted_pendulum_rtr_ompl/pid_ctrl.cpp", "max_stars_repo_name": "Copilot-Language/copilot-discussion", "max_stars_repo_head_hexsha": "caccad918b23dae991095344a845827ddccd6047", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-06-10T00:44:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-17T13:20:09.000Z", "max_issues_repo_path": "RSpring/rtr_copilot/inverted_pendulum_rtr_ompl/pid_ctrl.cpp", "max_issues_repo_name": "Copilot-Language/copilot-discussion", "max_issues_repo_head_hexsha": "caccad918b23dae991095344a845827ddccd6047", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 30.0, "max_issues_repo_issues_event_min_datetime": "2019-04-01T20:24:19.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-07T22:34:17.000Z", "max_forks_repo_path": "RSpring/rtr_copilot/inverted_pendulum_rtr_ompl/pid_ctrl.cpp", "max_forks_repo_name": "Copilot-Language/copilot-discussion", "max_forks_repo_head_hexsha": "caccad918b23dae991095344a845827ddccd6047", "max_forks_repo_licenses": ["BSD-3-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.8345864662, "max_line_length": 148, "alphanum_fraction": 0.6943121322, "num_tokens": 1032, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.49307831639164484}}
{"text": "// Copyright (c) 2012-2017 VideoStitch SAS\n// Copyright (c) 2018 stitchEm\n\n#pragma once\n\n#include \"libvideostitch/quaternion.hpp\"\n\n#include <Eigen/Dense>\n\n#include <vector>\n\nnamespace VideoStitch {\n\nnamespace Stabilization {\n\ntypedef Eigen::Matrix<double, 9, 1> Vector9d;\n\n/**\n * @brief The UKF_Quaternion class\n *\n * Inspired by: A Quaternion-Based Unscented Kalman Filter for Orientation Tracking (Edgar Kraft)\n */\nclass UKF_Quaternion {\n public:\n  UKF_Quaternion();\n  /**\n   * @brief Propagate current state in time\n   * @param delta_t : time in seconds\n   */\n  void predict(double delta_t);\n\n  /**\n   * @brief Incorporate a new measurement, update state and covariance matrix\n   * @param v : 9 dimensional vector (gyr_xyz, acc_xyz, mag_xyz)\n   */\n  void measure(const Vector9d& v);\n\n  Quaternion<double> getCurrentOrientation() const;\n  Vector3<double> getCurrentAngularVelocity() const;\n  Vector3<double> getCurrentAngularAcceleration() const;\n  Eigen::Matrix<double, 9, 9> getCovarianceMatrix() const;\n\n protected:\n  class qState {\n   public:\n    qState();\n    void initFromVect(const Vector9d& v);\n    void toVect(Vector9d& v) const;\n\n    Quaternion<double> q;  // quaternion orientation\n    Vector3<double> w;     // angular velocity\n    Vector3<double> ww;    // angular acceleration\n  };\n\n  void computeSigmaPoints();\n  void computeProcessModel(double delta_t);\n  void computeAverageState();\n  void computeCovarianceState();\n  void computeMeasurements();\n  void computeMeanAndCovMeasures();\n\n  qState x;    // current a posteriori state vector\n  qState xk_;  // a priori state vector\n\n  Quaternion<double> b;  // orientation of the magnetic north\n  Quaternion<double> g;  // orientation of the gravity\n\n  Eigen::Matrix<double, 9, 9> P;    // current covariance of the state vector\n  Eigen::Matrix<double, 9, 9> Pk_;  // a priori state vector covariance\n\n  Eigen::Matrix<double, 9, 9> Q;  // process noise\n  Eigen::Matrix<double, 9, 9> R;  // measurement noise\n\n  Eigen::Matrix<double, 4, 18> M;  // temporary data used to compute Cholesky decomposition\n\n  Eigen::Matrix<double, 9, 18> W_;  // temporary data used to compute a priori state vector covariance\n  std::vector<Vector9d> W;          // temporary data used to compute sigma points\n  std::vector<qState> X;            // sigma points {Xi}\n  std::vector<qState> Y;            // propagated sigma points {Yi}\n  Eigen::Matrix<double, 9, 18> Z;   // projection of the sigma points in the measurement space {Zi}\n  std::vector<Vector3<double> > E;  // temporary data used to compute error vectors ei\n  Vector9d zk_;                     // mean of {Zi}\n  Eigen::Matrix<double, 9, 9> Pvv;  // innovation covariance\n  Eigen::Matrix<double, 9, 9>\n      Pxz;  // cross-correlation matrix (temporary data used for the computation of the Kalman gain)\n  Eigen::Matrix<double, 9, 9> Kk;  // Kalman gain\n};\n\n}  // namespace Stabilization\n}  // namespace VideoStitch\n", "meta": {"hexsha": "4b6ba523009104d557c19faaf28a9795fc533d45", "size": 2918, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/src/stabilization/ukfQuaternion.hpp", "max_stars_repo_name": "tlalexander/stitchEm", "max_stars_repo_head_hexsha": "cdff821ad2c500703e6cb237ec61139fce7bf11c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 182.0, "max_stars_repo_stars_event_min_datetime": "2019-04-19T12:38:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T16:48:20.000Z", "max_issues_repo_path": "lib/src/stabilization/ukfQuaternion.hpp", "max_issues_repo_name": "tlalexander/stitchEm", "max_issues_repo_head_hexsha": "cdff821ad2c500703e6cb237ec61139fce7bf11c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 107.0, "max_issues_repo_issues_event_min_datetime": "2019-04-23T10:49:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-02T18:12:28.000Z", "max_forks_repo_path": "lib/src/stabilization/ukfQuaternion.hpp", "max_forks_repo_name": "tlalexander/stitchEm", "max_forks_repo_head_hexsha": "cdff821ad2c500703e6cb237ec61139fce7bf11c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 59.0, "max_forks_repo_forks_event_min_datetime": "2019-06-04T11:27:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T23:49:49.000Z", "avg_line_length": 32.0659340659, "max_line_length": 102, "alphanum_fraction": 0.6953392735, "num_tokens": 786, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.49307831639164484}}
{"text": "//\n//! Copyright \u00a9 2022\n//! Brandon Kohn\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#pragma once\n\n#include <boost/units/quantity.hpp>\n#include <boost/units/cmath.hpp>\n#include <geometrix/utility/tagged_quantity.hpp>\n#include <geometrix/utility/tagged_quantity_cmath.hpp>\n#include <type_traits>\n\nnamespace geometrix {\n\n    struct abs_tag{};\n    struct ceil_tag{};\n    struct floor_tag{};\n    struct exp_tag{};\n    struct log_tag{};\n    struct log10_tag{};\n    struct sqrt_tag{};\n    struct cos_tag{};\n    struct sin_tag{};\n    struct tan_tag{};\n    struct acos_tag{};\n    struct asin_tag{};\n    struct atan_tag{};\n    struct hypot_tag{};\n    struct pow_tag{};\n    struct atan2_tag{};\n    \n    template <typename Tag, typename T1, typename T2=void, typename T3=void, typename T4=void, typename EnableIF=void>\n    struct math_function_traits;\n    \n    template <typename Tag, typename T>\n    struct math_function_traits<Tag, T, typename std::enable_if<std::is_floating_point<T>::value>::type>\n    {\n        using result_type = typename std::decay<T>::type;\n    };\n\n    template <typename Tag, typename T>\n    struct math_function_traits<Tag, T, typename std::enable_if<std::is_integral<T>::value>::type>\n    {\n        using result_type = double;\n    };\n\n}//! namespace geometrix;\n\n", "meta": {"hexsha": "484be8f409f0d4a2f1d454d6bc807cafe064fea5", "size": 1400, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "geometrix/arithmetic/math_function_traits.hpp", "max_stars_repo_name": "brandon-kohn/Geometrix", "max_stars_repo_head_hexsha": "e107e13b469632c7d12cb236bd4fb8b17ff928e3", "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": "geometrix/arithmetic/math_function_traits.hpp", "max_issues_repo_name": "brandon-kohn/Geometrix", "max_issues_repo_head_hexsha": "e107e13b469632c7d12cb236bd4fb8b17ff928e3", "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": "geometrix/arithmetic/math_function_traits.hpp", "max_forks_repo_name": "brandon-kohn/Geometrix", "max_forks_repo_head_hexsha": "e107e13b469632c7d12cb236bd4fb8b17ff928e3", "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.4150943396, "max_line_length": 118, "alphanum_fraction": 0.6814285714, "num_tokens": 343, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.826711776992821, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.49307830620584764}}
{"text": "#include <boost/timer/timer.hpp>\n#include <iostream>\n#include <random>\n#include <cmath>\n\nusing namespace std;\n\nint main() {\n\n\tboost::timer::cpu_timer timer;\n\tint count = 1000*1000;\n\trandom_device rd;\n\tminstd_rand minstd_rng(rd());\n\tmt19937 mt_rng(rd());\n\tnormal_distribution<double> ndist(0,100);\n\tuniform_real_distribution<double> udist(-1, 1);\n\n\t// min max\n\tcout << \"--- modf\" << endl;\n\tcout << \"------ modf() \" << count << endl;\n\t{\n\t\tdouble f;\n\t\tdouble integral_part;\n\t\tdouble fractional_part;\n\n\t\ttimer.start();\n\t\tfor ( int i = 0; i< count; ++i ) {\n\t\t\tf = udist(minstd_rng);\n\t\t\tfractional_part = modf( f, &integral_part );\n\t\t}\n\t\ttimer.stop();\n\n\t\tcout << \"f               = \" << f << \" ( \" << std::hexfloat << f << \" )\" << std::defaultfloat << endl;\n\t\tcout << \"integral_part   = \" << integral_part << \" ( \" << std::hexfloat << integral_part << \" )\" << std::defaultfloat <<endl;\n\t\tcout << \"fractional_part = \" << fractional_part << \" ( \" << std::hexfloat << fractional_part << \" )\" << std::defaultfloat <<endl;\n\n\t\tcout << \"modf() \" << timer.format() << endl;\n\t}\n\n\treturn 0;\n}\n\n\n", "meta": {"hexsha": "fd42e9ec2da82c4e7f9f0e0eaad88c4307dd697e", "size": 1079, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tcpl/NumericTest.cpp", "max_stars_repo_name": "batangr00t/cppLab", "max_stars_repo_head_hexsha": "3946e702692dffb53f92c776e9e8c4a073d68bc9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tcpl/NumericTest.cpp", "max_issues_repo_name": "batangr00t/cppLab", "max_issues_repo_head_hexsha": "3946e702692dffb53f92c776e9e8c4a073d68bc9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tcpl/NumericTest.cpp", "max_forks_repo_name": "batangr00t/cppLab", "max_forks_repo_head_hexsha": "3946e702692dffb53f92c776e9e8c4a073d68bc9", "max_forks_repo_licenses": ["Apache-2.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.5227272727, "max_line_length": 131, "alphanum_fraction": 0.5912882298, "num_tokens": 312, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.6688802735722128, "lm_q1q2_score": 0.49307055348506346}}
{"text": "#include <cmath>\n#include <iostream>\n#include <limits> \n\n#include <boost/date_time/posix_time/posix_time.hpp>\n#include <boost/move/unique_ptr.hpp>\n\nusing namespace std;\nnamespace bpt = boost::posix_time;\nnamespace bml = boost::movelib;\n\nconst size_t LOOP_NUM = 100000000;\n\n#define COUT_INTEGRAL(_t) \\\n    cout << \"Size of \" << #_t << \" = \" << sizeof(_t) << \", \" \\\n         << \"[ \" << numeric_limits<_t>::min() << \", \" \\\n         << numeric_limits<_t>::max() << \" ].\" << endl;\n\n#define COUT_FLOATING_POINT(_t) \\\n    cout << \"Size of \" << #_t << \" = \" << sizeof(_t) << \", \" \\\n         << scientific << \"[ \" << numeric_limits<_t>::min() << \", \" \\\n         << numeric_limits<_t>::max() << \" ].\" << endl;\n\nstatic void show_types(void)\n{\n    COUT_INTEGRAL(int);\n    COUT_INTEGRAL(short);\n    COUT_INTEGRAL(long);\n\n    COUT_FLOATING_POINT(float);\n    COUT_FLOATING_POINT(double);\n    COUT_FLOATING_POINT(long double);\n}\n\nclass Runnable\n{\npublic:\n    Runnable() { };\n    virtual ~Runnable() { };\n\n    virtual void prepare(void) = 0;\n    virtual void run(int loops) = 0;\n    virtual void finalize(void) = 0;\n};\n\ntemplate <typename _T> \nclass FloatingPointMuliplification : public Runnable\n{\npublic:\n    FloatingPointMuliplification( ) : Runnable() { };\n    virtual ~FloatingPointMuliplification() { };\n\n    virtual void prepare(void) { };\n    virtual void finalize(void) { };\n\n    virtual void run(int loops)\n    {\n        _T temp = (_T)( 0 );\n        _T val  = (_T)( 2 );\n\n        for ( int i = 0; i < loops; ++i )\n        {\n            temp = val * val;\n        }\n    }\n};\n\ntemplate <typename _T> \nclass CMathExponential : public Runnable\n{\npublic:\n    CMathExponential() { };\n    ~CMathExponential() { };\n\n    virtual void prepare(void) { };\n    virtual void finalize(void) { };\n\n    virtual void run( int loops )\n    {\n        _T temp = (_T)( 0 );\n        const _T exponent = (_T)( 2 );\n\n        for ( int i = 0; i < loops; ++i )\n        {\n            temp = exp( exponent );\n        }\n    }\n};\n\ntemplate <typename _T> \nclass ArrayAccess : public Runnable\n{\npublic:\n    ArrayAccess(size_t size) : mSize(size), mArray(NULL) { };\n    virtual ~ArrayAccess()\n    {\n        destroy();\n        cout << \"Destructor Get called.\" << endl;\n    }\n\n    virtual void prepare(void)\n    {\n        destroy();\n        mArray = new _T[mSize];\n    }\n\n    virtual void finalize(void)\n    {\n        destroy();\n    }\n\n    virtual void run(int loops)\n    {\n        size_t p = 0;\n\n        _T temp = (_T)( 0 );\n\n        for ( int i = 0; i < loops; ++i )\n        {\n            temp = mArray[p];\n            p++;\n\n            if ( p == mSize )\n            {\n                p = 0;\n            }\n        }\n    }\n\nprivate:\n    void destroy(void)\n    {\n        if ( NULL != mArray )\n        {\n            delete [] mArray; mArray = NULL;\n        }\n    }\n\nprivate:\n    const size_t mSize;\n    _T* mArray;\n};\n\nclass RunnableOperator\n{\npublic:\n    RunnableOperator() { };\n    ~RunnableOperator() { };\n\n    void profile( Runnable* rnb, int loops )\n    {\n        rnb->prepare();\n\n        bpt::ptime start = bpt::microsec_clock::universal_time();\n\n        rnb->run(loops);\n\n        bpt::ptime end = bpt::microsec_clock::universal_time();\n        bpt::time_duration td = end - start;\n\n        rnb->finalize();\n\n        cout << \"Total time: \" << td.total_milliseconds() << \" ms.\" << endl;\n    }\n};\n\nint main(void)\n{\n    cout << \"Hello efficiency!\" << endl;\n\n    cout << \"Show the maximum representable values of various types. \" << endl;\n\n    show_types();\n\n    bml::unique_ptr<Runnable> rnbFloat(     new FloatingPointMuliplification<float> );\n    bml::unique_ptr<Runnable> rnbDouble(    new FloatingPointMuliplification<double> );\n    bml::unique_ptr<Runnable> rnbExpFloat(  new CMathExponential<float> );\n    bml::unique_ptr<Runnable> rnbExpDouble( new CMathExponential<double> );\n    bml::unique_ptr<Runnable> rnbAAFloat(   new ArrayAccess<float>(1000000) );\n    bml::unique_ptr<Runnable> rnbAADouble(  new ArrayAccess<double>(1000000) );\n\n    RunnableOperator ro;\n\n    cout << \"Executing time of various operations.\" << endl;\n\n    ro.profile( rnbFloat.get(),     LOOP_NUM );\n    ro.profile( rnbDouble.get(),    LOOP_NUM );\n    ro.profile( rnbExpFloat.get(),  LOOP_NUM );\n    ro.profile( rnbExpDouble.get(), LOOP_NUM );\n    ro.profile( rnbAAFloat.get(),   LOOP_NUM );\n    ro.profile( rnbAADouble.get(),  LOOP_NUM );\n\n    // delete rnbAADouble; rnbAADouble = NULL;\n    // delete rnbAAFloat; rnbAAFloat = NULL;\n    // delete rnbExpDouble; rnbExpDouble = NULL;\n    // delete rnbExpFloat; rnbExpFloat = NULL;\n    // delete rnbDouble; rnbDouble = NULL;\n    // delete rnbFloat; rnbFloat = NULL;\n\n    return 0;\n}\n", "meta": {"hexsha": "7ee7fce41f305fc19dbc5fd599f982d08d848971", "size": 4667, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Src/main.cpp", "max_stars_repo_name": "huyaoyu/CppTestEfficiency", "max_stars_repo_head_hexsha": "2b26333dd73117f0e51f701ad6d0cbc049ba67ab", "max_stars_repo_licenses": ["MIT"], "max_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": "huyaoyu/CppTestEfficiency", "max_issues_repo_head_hexsha": "2b26333dd73117f0e51f701ad6d0cbc049ba67ab", "max_issues_repo_licenses": ["MIT"], "max_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": "huyaoyu/CppTestEfficiency", "max_forks_repo_head_hexsha": "2b26333dd73117f0e51f701ad6d0cbc049ba67ab", "max_forks_repo_licenses": ["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.103960396, "max_line_length": 87, "alphanum_fraction": 0.5714591815, "num_tokens": 1264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799253, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.49307053602895173}}
{"text": "//[ Calc2\r\n//  Copyright 2008 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// This example enhances the simple arithmetic expression evaluator\r\n// in calc1.cpp by using proto::extends to make arithmetic\r\n// expressions immediately evaluable with operator (), a-la a\r\n// function object\r\n\r\n#include <iostream>\r\n#include <boost/proto/core.hpp>\r\n#include <boost/proto/context.hpp>\r\nnamespace proto = boost::proto;\r\nusing proto::_;\r\n\r\ntemplate<typename Expr>\r\nstruct calculator_expression;\r\n\r\n// Tell proto how to generate expressions in the calculator_domain\r\nstruct calculator_domain\r\n  : proto::domain<proto::generator<calculator_expression> >\r\n{};\r\n\r\n// Will be used to define the placeholders _1 and _2\r\ntemplate<int I> struct placeholder {};\r\n\r\n// Define a calculator context, for evaluating arithmetic expressions\r\n// (This is as before, in calc1.cpp)\r\nstruct calculator_context\r\n  : proto::callable_context< calculator_context const >\r\n{\r\n    // The values bound to the placeholders\r\n    double d[2];\r\n\r\n    // The result of evaluating arithmetic expressions\r\n    typedef double result_type;\r\n\r\n    explicit calculator_context(double d1 = 0., double d2 = 0.)\r\n    {\r\n        d[0] = d1;\r\n        d[1] = d2;\r\n    }\r\n\r\n    // Handle the evaluation of the placeholder terminals\r\n    template<int I>\r\n    double operator ()(proto::tag::terminal, placeholder<I>) const\r\n    {\r\n        return d[ I - 1 ];\r\n    }\r\n};\r\n\r\n// Wrap all calculator expressions in this type, which defines\r\n// operator () to evaluate the expression.\r\ntemplate<typename Expr>\r\nstruct calculator_expression\r\n  : proto::extends<Expr, calculator_expression<Expr>, calculator_domain>\r\n{\r\n    explicit calculator_expression(Expr const &expr = Expr())\r\n      : calculator_expression::proto_extends(expr)\r\n    {}\r\n\r\n    BOOST_PROTO_EXTENDS_USING_ASSIGN(calculator_expression<Expr>)\r\n\r\n    // Override operator () to evaluate the expression\r\n    double operator ()() const\r\n    {\r\n        calculator_context const ctx;\r\n        return proto::eval(*this, ctx);\r\n    }\r\n\r\n    double operator ()(double d1) const\r\n    {\r\n        calculator_context const ctx(d1);\r\n        return proto::eval(*this, ctx);\r\n    }\r\n\r\n    double operator ()(double d1, double d2) const\r\n    {\r\n        calculator_context const ctx(d1, d2);\r\n        return proto::eval(*this, ctx);\r\n    }\r\n};\r\n\r\n// Define some placeholders (notice they're wrapped in calculator_expression<>)\r\ncalculator_expression<proto::terminal< placeholder< 1 > >::type> const _1;\r\ncalculator_expression<proto::terminal< placeholder< 2 > >::type> const _2;\r\n\r\n// Now, our arithmetic expressions are immediately executable function objects:\r\nint main()\r\n{\r\n    // Displays \"5\"\r\n    std::cout << (_1 + 2.0)( 3.0 ) << std::endl;\r\n\r\n    // Displays \"6\"\r\n    std::cout << ( _1 * _2 )( 3.0, 2.0 ) << std::endl;\r\n\r\n    // Displays \"0.5\"\r\n    std::cout << ( (_1 - _2) / _2 )( 3.0, 2.0 ) << std::endl;\r\n\r\n    return 0;\r\n}\r\n//]\r\n", "meta": {"hexsha": "ed1288aff709455161a8e03a809a1c83468f253e", "size": 3060, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/proto/example/calc2.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/proto/example/calc2.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/proto/example/calc2.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": 29.4230769231, "max_line_length": 80, "alphanum_fraction": 0.6598039216, "num_tokens": 718, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799253, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.49307052629757614}}
{"text": "// Copyright (c) 2021 CNES\r\n//\r\n// All rights reserved. Use of this source code is governed by a\r\n// BSD-style license that can be found in the LICENSE file.\r\n#pragma once\r\n#include <pybind11/eigen.h>\r\n\r\n#include <Eigen/Core>\r\n#include <optional>\r\n#include <tuple>\r\n#include <unordered_map>\r\n\r\n#include \"pyinterp/detail/broadcast.hpp\"\r\n#include \"pyinterp/detail/math.hpp\"\r\n#include \"pyinterp/eigen.hpp\"\r\n#include \"pyinterp/geodetic/box.hpp\"\r\n#include \"pyinterp/geodetic/point.hpp\"\r\n#include \"pyinterp/geodetic/polygon.hpp\"\r\n\r\nnamespace pyinterp::geohash::int64 {\r\n\r\n/// Returns the precision in longitude/latitude and degrees for the given\r\n/// precision\r\n[[nodiscard]] inline auto error_with_precision(const uint32_t precision)\r\n    -> std::tuple<double, double> {\r\n  auto lat_bits = static_cast<int32_t>(precision >> 1U);\r\n  auto lng_bits = static_cast<int32_t>(precision - lat_bits);\r\n\r\n  return std::make_tuple(360 * detail::math::power2(-lng_bits),\r\n                         180 * detail::math::power2(-lat_bits));\r\n}\r\n\r\n// Encode a point into geohash with the given precision\r\n[[nodiscard]] auto encode(const geodetic::Point& point, uint32_t precision)\r\n    -> uint64_t;\r\n\r\n// Encode points into geohash with the given precision\r\n[[nodiscard]] inline auto encode(const Eigen::Ref<const Eigen::VectorXd>& lon,\r\n                                 const Eigen::Ref<const Eigen::VectorXd>& lat,\r\n                                 uint32_t precision) -> Vector<uint64_t> {\r\n  detail::check_eigen_shape(\"lon\", lon, \"lat\", lat);\r\n  auto size = lon.size();\r\n  auto result = Vector<uint64_t>(size);\r\n  for (Eigen::Index ix = 0; ix < size; ++ix) {\r\n    result(ix) = encode({lon[ix], lat[ix]}, precision);\r\n  }\r\n  return result;\r\n}\r\n\r\n// Returns the region encoded by the integer geohash with the specified\r\n// precision.\r\n[[nodiscard]] auto bounding_box(uint64_t hash, uint32_t precision)\r\n    -> geodetic::Box;\r\n\r\n// Decode a hash into a geographic point with the given precision.\r\n// If round is true, the coordinates of the points will be rounded to the\r\n// accuracy defined by the GeoHash.\r\n[[nodiscard]] inline auto decode(const uint64_t hash, const uint32_t precision,\r\n                                 const bool round) -> geodetic::Point {\r\n  auto bbox = bounding_box(hash, precision);\r\n  return round ? bbox.round() : bbox.centroid();\r\n}\r\n\r\n// Decode hashes into a geographic points with the given bit depth.\r\n// If round is true, the coordinates of the points will be rounded to the\r\n// accuracy defined by the GeoHash.\r\n[[nodiscard]] inline auto decode(const Eigen::Ref<const Vector<uint64_t>>& hash,\r\n                                 const uint32_t precision, const bool center)\r\n    -> std::tuple<Eigen::VectorXd, Eigen::VectorXd> {\r\n  auto lon = Eigen::VectorXd(hash.size());\r\n  auto lat = Eigen::VectorXd(hash.size());\r\n  auto point = geodetic::Point();\r\n  for (Eigen::Index ix = 0; ix < hash.size(); ++ix) {\r\n    point = decode(hash(ix), precision, center);\r\n    lon[ix] = point.lon();\r\n    lat[ix] = point.lat();\r\n  }\r\n  return std::make_tuple(lon, lat);\r\n}\r\n\r\n// Returns all neighbors hash clockwise from north around northwest at the given\r\n// precision.\r\n// 7 0 1\r\n// 6 x 2\r\n// 5 4 3\r\n[[nodiscard]] auto neighbors(uint64_t hash, uint32_t precision)\r\n    -> Eigen::Matrix<uint64_t, 8, 1>;\r\n\r\n// Returns the property of the grid covering the given box: geohash of the\r\n// minimum corner point, number of boxes in longitudes and latitudes.\r\n[[nodiscard]] auto grid_properties(const geodetic::Box& box, uint32_t precision)\r\n    -> std::tuple<uint64_t, size_t, size_t>;\r\n\r\n// Returns all the GeoHash codes within the box.\r\n[[nodiscard]] auto bounding_boxes(const std::optional<geodetic::Box>& box,\r\n                                  uint32_t precision) -> Vector<uint64_t>;\r\n\r\n// Returns all the GeoHash codes within the polygon.\r\n[[nodiscard]] inline auto bounding_boxes(const geodetic::Polygon& polygon,\r\n                                         uint32_t chars) -> Vector<uint64_t> {\r\n  auto box = geodetic::Box();\r\n  boost::geometry::envelope<geodetic::Polygon, geodetic::Box>(polygon, box);\r\n  return bounding_boxes(box, chars);\r\n}\r\n\r\n// Returns the area covered by the GeoHash\r\n[[nodiscard]] inline auto area(uint64_t hash, uint32_t precision,\r\n                               const std::optional<geodetic::System>& wgs)\r\n    -> double {\r\n  return bounding_box(hash, precision).area(wgs);\r\n}\r\n\r\n// Returns the start and end indexes of the different GeoHash boxes.\r\n[[nodiscard]] auto where(\r\n    const pybind11::EigenDRef<const Eigen::Matrix<uint64_t, -1, -1>>& hash)\r\n    -> std::unordered_map<uint64_t, std::tuple<std::tuple<int64_t, int64_t>,\r\n                                     std::tuple<int64_t, int64_t>>>;\r\n\r\n}  // namespace pyinterp::geohash::int64", "meta": {"hexsha": "3a5009db23a1fffeabd27a4f8f3d91d5c8809f5a", "size": 4771, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/pyinterp/core/include/pyinterp/geohash/int64.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/geohash/int64.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/geohash/int64.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": 40.0924369748, "max_line_length": 81, "alphanum_fraction": 0.6573045483, "num_tokens": 1140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240964782011, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.49305024544552134}}
{"text": "/*\n * dynamical-system.hpp\n *\n *  Created on: 19 mai 2014\n *      Author: alexis\n */\n\n#ifndef DYNAMICAL_SYSTEM_HPP_\n#define DYNAMICAL_SYSTEM_HPP_\n\n#include <vector>\n\n#include <state-observation/api.h>\n#include <state-observation/dynamical-system/dynamical-system-functor-base.hpp>\n#include <state-observation/noise/noise-base.hpp>\n#include <state-observation/sensors-simulation/accelerometer-gyrometer.hpp>\n#include <state-observation/tools/hrp2.hpp>\n#include <state-observation/tools/rigid-body-kinematics.hpp>\n\n#include <Eigen/Cholesky>\n\nnamespace stateObservation\n{\n\nnamespace flexibilityEstimation\n{\n\n/**\n * \\class  DynamicalSystem\n * \\brief  This class describes the dynamics of a robot's flexibility\n *         this dynamics is the simplest possible system, the flexibility\n *         is expressed as a rotation against the contact positions with no\n *         other hypothesis than that the contact points are at constant position\n *\n */\nclass STATE_OBSERVATION_DLLAPI IMUElasticLocalFrameDynamicalSystem : public stateObservation::DynamicalSystemFunctorBase\n{\npublic:\n  struct input\n  {\n    /// indices of the different components of a vector of the input state\n    static constexpr unsigned posCom = 0;\n    static constexpr unsigned velCom = 3;\n    static constexpr unsigned accCom = 6;\n    static constexpr unsigned inertia = 9;\n    static constexpr unsigned angMoment = 15;\n    static constexpr unsigned dotInertia = 18;\n    static constexpr unsigned dotAngMoment = 24;\n    static constexpr unsigned posIMU = 27;\n    static constexpr unsigned oriIMU = 30;\n    static constexpr unsigned linVelIMU = 33;\n    static constexpr unsigned angVelIMU = 36;\n    static constexpr unsigned linAccIMU = 39;\n    static constexpr unsigned additionalForces = 42;\n    static constexpr unsigned contacts = 48;\n\n    static constexpr unsigned sizeBase = 48;\n  };\n\n  struct state\n  {\n    static constexpr unsigned pos = 0;\n    static constexpr unsigned ori = 3;\n    static constexpr unsigned linVel = 6;\n    static constexpr unsigned angVel = 9;\n    static constexpr unsigned fc = 12;\n    static constexpr unsigned unmodeledForces = 24;\n    static constexpr unsigned comBias = 30;\n    static constexpr unsigned drift = 32;\n\n    static constexpr unsigned size = 35;\n  };\n\n  struct contactModel\n  {\n    /// indices of the different components of a vector of the input state\n    static constexpr unsigned elasticContact = 1;\n    static constexpr unsigned pendulum = 2;\n    static constexpr unsigned none = 0;\n  };\n\n  typedef Eigen::LLT<Matrix3> LLTMatrix3;\n\n  /// constructor\n  explicit IMUElasticLocalFrameDynamicalSystem(double dt);\n\n  /// virtual destructor\n  virtual ~IMUElasticLocalFrameDynamicalSystem();\n\n  void test();\n\n  // Get the contact wrench\n  void computeContactWrench(const Matrix3 & orientation,\n                            const Vector3 & position,\n                            const IndexedVectorArray & contactPosV,\n                            const IndexedVectorArray & contactOriV,\n                            const Vector & fc,\n                            const Vector & tc,\n                            const Vector3 & fm,\n                            const Vector3 & tm,\n                            const Vector3 & addForce,\n                            const Vector3 & addMoment);\n\n  stateObservation::Vector computeAccelerations(const Vector & x, const Vector & u);\n\n  // computation of the acceleration linear\n  virtual void computeAccelerations(const Vector3 & positionCom,\n                                    const Vector3 & velocityCom,\n                                    const Vector3 & accelerationCom,\n                                    const Vector3 & AngMomentum,\n                                    const Vector3 & dotAngMomentum,\n                                    const Matrix3 & Inertia,\n                                    const Matrix3 & dotInertia,\n                                    const IndexedVectorArray & contactPos,\n                                    const IndexedVectorArray & contactOri,\n                                    const Vector3 & position,\n                                    const Vector3 & linVelocity,\n                                    Vector3 & linearAcceleration,\n                                    const Vector3 & oriVector,\n                                    const Matrix3 & orientation,\n                                    const Vector3 & angularVel,\n                                    Vector3 & angularAcceleration,\n                                    const Vector & fc,\n                                    const Vector & tc,\n                                    const Vector3 & fm,\n                                    const Vector3 & tm,\n                                    const Vector3 & addForces,\n                                    const Vector3 & addMoments);\n\n  /// Description of the state dynamics\n  virtual stateObservation::Vector stateDynamics(const stateObservation::Vector & x,\n                                                 const stateObservation::Vector & u,\n                                                 TimeIndex k);\n\n  /// compute the jacobien of the state dynamics at the last computed value\n  stateObservation::Matrix stateDynamicsJacobian();\n\n  /// compute the jacobien of the state dynamics at a given state\n  stateObservation::Matrix stateDynamicsJacobian(const stateObservation::Vector & x,\n                                                 const stateObservation::Vector & u,\n                                                 TimeIndex k);\n\n  /// sets the finite differences derivation step vector\n  void setFDstep(const stateObservation::Vector & dx);\n\n  /// Description of the sensor's dynamics\n  virtual stateObservation::Vector measureDynamics(const stateObservation::Vector & x,\n                                                   const stateObservation::Vector & u,\n                                                   TimeIndex k);\n\n  /// compute the Jacobien of the measurements dynamics at the last computed value\n  stateObservation::Matrix measureDynamicsJacobian();\n\n  /// compute the Jacobien of the measurements dynamics at a given state value\n  stateObservation::Matrix measureDynamicsJacobian(const stateObservation::Vector & x,\n                                                   const stateObservation::Vector & u,\n                                                   TimeIndex k);\n\n  /// Sets a noise which disturbs the state dynamics\n  virtual void setProcessNoise(stateObservation::NoiseBase *);\n\n  /// Removes the process noise\n  virtual void resetProcessNoise();\n\n  /// Gets the process noise\n  virtual stateObservation::NoiseBase * getProcessNoise() const;\n\n  /// Sets a noise which disturbs the measurements\n  virtual void setMeasurementNoise(stateObservation::NoiseBase *);\n\n  /// Removes the measurement noise\n  virtual void resetMeasurementNoise();\n\n  /// Gets a pointer on the measurement noise\n  virtual stateObservation::NoiseBase * getMeasurementNoise() const;\n\n  /// Set the period of the time discretization\n  virtual void setSamplingPeriod(double dt);\n\n  /// Gets the state size\n  virtual Index getStateSize() const;\n\n  /// Gets the input size\n  virtual Index getInputSize() const;\n\n  /// Sets the input size\n  virtual void setInputSize(Index i);\n\n  /// Gets the contact number\n  /// virtual\n\n  /// Gets the contacts position\n\n  /// Gets the measurement size\n  virtual Index getMeasurementSize() const;\n\n  /// Sets the number of contacts\n  virtual void setContactsNumber(unsigned);\n\n  virtual void setPe(stateObservation::Vector3 Pe)\n  {\n    pe = Pe;\n  }\n\n  /// Gets the nimber of contacts\n  inline unsigned getContactsNumber(void) const\n  {\n    return nbContacts_;\n  }\n\n  virtual void setContactModel(unsigned nb);\n\n  virtual void setPrinted(bool b)\n  {\n    printed_ = b;\n  }\n\n  virtual void computeElastContactForcesAndMoments(const IndexedVectorArray & contactPosArray,\n                                                   const IndexedVectorArray & contactOriArray,\n                                                   const IndexedVectorArray & contactVelArray,\n                                                   const IndexedVectorArray & contactAngVelArray,\n                                                   const Vector3 & position,\n                                                   const Vector3 & linVelocity,\n                                                   const Vector3 & oriVector,\n                                                   const Matrix3 & orientation,\n                                                   const Vector3 & angVel,\n                                                   Vector & fc,\n                                                   Vector & tc);\n\n  virtual void computeElastPendulumForcesAndMoments(const IndexedVectorArray & PrArray,\n                                                    const Vector3 & position,\n                                                    const Vector3 & linVelocity,\n                                                    const Vector3 & oriVector,\n                                                    const Matrix3 & orientation,\n                                                    const Vector3 & angVel,\n                                                    Vector & forces,\n                                                    Vector & moments);\n\n  void computeForcesAndMoments(const IndexedVectorArray & position1,\n                               const IndexedVectorArray & position2,\n                               const IndexedVectorArray & velocity1,\n                               const IndexedVectorArray & velocity2,\n                               const Vector3 & position,\n                               const Vector3 & linVelocity,\n                               const Vector3 & oriVector,\n                               const Matrix3 & orientation,\n                               const Vector3 & angVel,\n                               Vector & fc,\n                               Vector & tc);\n\n  virtual void computeForcesAndMoments(const Vector & x, const Vector & u);\n\n  virtual Vector getForcesAndMoments();\n\n  virtual Vector getForcesAndMoments(const Vector & x, const Vector & u);\n\n  virtual Vector getMomentaDotFromForces(const Vector & x, const Vector & u);\n  virtual Vector getMomentaDotFromKinematics(const Vector & x, const Vector & u);\n\n  virtual void iterateDynamicsEuler(const Vector3 & positionCom,\n                                    const Vector3 & velocityCom,\n                                    const Vector3 & accelerationCom,\n                                    const Vector3 & AngMomentum,\n                                    const Vector3 & dotAngMomentum,\n                                    const Matrix3 & Inertia,\n                                    const Matrix3 & dotInertia,\n                                    const IndexedVectorArray & contactPos,\n                                    const IndexedVectorArray & contactOri,\n                                    Vector3 & position,\n                                    Vector3 & linVelocity,\n                                    Vector & fc1,\n                                    Vector3 & oriVector,\n                                    Vector3 & angularVel,\n                                    Vector & fc2,\n                                    const Vector3 & fm,\n                                    const Vector3 & tm,\n                                    const Vector3 & addForces,\n                                    const Vector3 & addMoments,\n                                    double dt);\n\n  virtual void iterateDynamicsRK4(const Vector3 & positionCom,\n                                  const Vector3 & velocityCom,\n                                  const Vector3 & accelerationCom,\n                                  const Vector3 & AngMomentum,\n                                  const Vector3 & dotAngMomentum,\n                                  const Matrix3 & Inertia,\n                                  const Matrix3 & dotInertia,\n                                  const IndexedVectorArray & contactPos,\n                                  const IndexedVectorArray & contactOri,\n                                  Vector3 & position,\n                                  Vector3 & linVelocity,\n                                  Vector & fc1,\n                                  Vector3 & oriVector,\n                                  Vector3 & angularVel,\n                                  Vector & fc2,\n                                  const Vector3 & fm,\n                                  const Vector3 & tm,\n                                  const Vector3 & addForces,\n                                  const Vector3 & addMoments,\n                                  double dt);\n\n  virtual void setWithForceMeasurements(bool b);\n  virtual bool getWithForceMeasurements() const;\n  virtual void setWithComBias(bool b);\n  virtual bool getWithComBias() const;\n  virtual void setWithAbsolutePosition(bool b);\n  virtual bool getWithAbsolutePosition() const;\n  void setWithUnmodeledForces(bool b);\n\n  virtual void setKfe(const Matrix3 & m);\n  virtual void setKfv(const Matrix3 & m);\n  virtual void setKte(const Matrix3 & m);\n  virtual void setKtv(const Matrix3 & m);\n\n  virtual void setKfeRopes(const Matrix3 & m);\n  virtual void setKfvRopes(const Matrix3 & m);\n  virtual void setKteRopes(const Matrix3 & m);\n  virtual void setKtvRopes(const Matrix3 & m);\n\n  virtual Matrix getKfe() const;\n  virtual Matrix getKfv() const;\n  virtual Matrix getKte() const;\n  virtual Matrix getKtv() const;\n\n  virtual void setRobotMass(double d);\n\n  virtual double getRobotMass() const;\n\nprotected:\n  bool printed_;\n\n  stateObservation::AccelerometerGyrometer sensor_;\n\n  stateObservation::NoiseBase * processNoise_;\n\n  void updateMeasurementSize_();\n\n  double dt_;\n\n  double robotMass_;\n  double robotMassInv_;\n\n  Matrix3 & computeRotation_(const Vector3 & x, int i);\n\n  static constexpr Index stateSize_ = state::size;\n  Index inputSize_;\n  static constexpr Index measurementSizeBase_ = 6;\n  unsigned nbContacts_;\n  unsigned contactModel_;\n\n  Vector fc_;\n  Vector tc_;\n\n  Vector dx_;\n\n  Vector xk1_;\n  Vector xk_;\n  Vector uk_;\n\n  Vector xk_fory_;\n  Vector yk_;\n  Vector uk_fory_;\n\n  Index measurementSize_;\n\n  std::vector<Vector3, Eigen::aligned_allocator<Vector3>> contactPositions_;\n\n  Matrix3 Kfe_, Kte_, Kfv_, Ktv_;\n  Matrix3 KfeRopes_, KteRopes_, KfvRopes_, KtvRopes_;\n\n  TimeIndex kcurrent_;\n\n  bool withForceMeasurements_;\n  bool withComBias_;\n  bool withAbsolutePos_;\n  bool withUnmodeledForces_;\n\n  stateObservation::Vector3 pe;\n\n  double marginalStabilityFactor_;\n  // a scaling factor a=1-epsilon to avoid the natural marginal stability of\n  // the dynamics x_{k+1}=x_k we replace it with x_{k+1}=a*x_k\n\n  unsigned index_;\n\n  struct Optimization\n  {\n\n    Vector6 momentaDot;\n\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n    Vector3 positionFlex;\n    Vector3 velocityFlex;\n    Vector3 accelerationFlex;\n    Vector3 orientationFlexV;\n    Vector3 angularVelocityFlex;\n    Vector3 angularAccelerationFlex;\n    Vector3 positionComBias;\n\n    Matrix3 rFlex;\n    Matrix3 rFlexT;\n\n    Vector3 drift;\n    Vector3 pdrift;\n    Matrix3 rdrift;\n\n    double cy, sy;\n\n    AngleAxis orientationAA;\n\n    Vector xk1;\n    Vector xk;\n    Vector xk1dx;\n\n    Vector xdx;\n\n    Vector xk_fory;\n    Vector yk;\n    Vector ykdy;\n\n    TimeIndex k_fory;\n\n    Matrix3 orinertia;\n\n    LLTMatrix3 invinertia;\n\n    Matrix3 rtotal;\n    Vector3 ptotal;\n    AngleAxis aatotal;\n    Vector3 oritotal;\n\n    Matrix Jx;\n    Matrix Jy;\n\n    Matrix3 rimu;\n    Vector3 imuAcc;\n    Vector3 imuOmega;\n    Vector sensorState;\n\n    Vector3 positionCom;\n    Vector3 velocityCom;\n    Vector3 accelerationCom;\n    Vector3 AngMomentum;\n    Vector3 dotAngMomentum;\n\n    Vector3 positionControl;\n    Vector3 velocityControl;\n    Vector3 accelerationControl;\n    Vector3 orientationControlV;\n    Vector3 angularVelocityControl;\n\n    Matrix3 rControl;\n\n    IndexedVectorArray contactPosV;\n    IndexedVectorArray contactOriV;\n    IndexedVectorArray contactVelArray;\n    IndexedVectorArray contactAngVelArray;\n\n    Matrix3 inertia;\n    Matrix3 dotInertia;\n\n    IndexedVectorArray efforts;\n\n    Vector3 f, fi;\n    Vector3 t;\n\n    // unmodelled and unmeasured forces\n    Vector3 fm;\n    Vector3 tm;\n\n    Vector3 linearAcceleration;\n    Vector3 angularAcceleration;\n\n    Vector3 vf;\n    Vector3 vt;\n\n    Vector3 crosstempV;\n    Matrix3 crosstempM;\n\n    // elastic contact forces and moments\n    Matrix3 Rci; // rotation of contact i\n    Matrix3 Rcit; // transpose of previous\n    Vector3 contactPos; //\n    Vector3 contactVel;\n    Vector3 RciContactPos;\n    Vector3 globalContactPos;\n    Matrix3 Rt;\n\n    Vector3 forcei;\n    Vector3 momenti;\n\n    // additional forces and moments\n    Vector3 addForce;\n    Vector3 addMoment;\n\n    Matrix3 skewV;\n    Matrix3 skewV2;\n    Matrix3 skewVR;\n    Matrix3 skewV2R;\n    Matrix3 RIRT;\n    Vector3 wx2Rc;\n    Vector3 _2wxRv;\n    Vector3 Ra;\n    Vector3 Rc;\n    Vector3 Rcp;\n\n    // optimization of orientation transformation between vector3 to rotation matrix\n\n    Matrix3 curRotation0;\n    Vector3 orientationVector0;\n    Matrix3 curRotation1;\n    Vector3 orientationVector1;\n    Matrix3 curRotation2;\n    Vector3 orientationVector2;\n    Matrix3 curRotation3;\n    Vector3 orientationVector3;\n\n    Optimization()\n    : curRotation0(Matrix3::Identity()), orientationVector0(Vector3::Zero()), curRotation1(Matrix3::Identity()),\n      orientationVector1(Vector3::Zero()), curRotation2(Matrix3::Identity()), orientationVector2(Vector3::Zero()),\n      curRotation3(Matrix3::Identity()), orientationVector3(Vector3::Zero())\n    {\n    }\n\n    inline Vector3 & orientationVector(int i)\n    {\n      if(i == 0) return orientationVector0;\n      if(i == 1) return orientationVector1;\n      if(i == 2) return orientationVector2;\n\n      return orientationVector3;\n    }\n\n    inline Matrix3 & curRotation(int i)\n    {\n      if(i == 0) return curRotation0;\n      if(i == 1) return curRotation1;\n      if(i == 2) return curRotation2;\n\n      return curRotation3;\n    }\n\n  } op_;\n\npublic:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n};\n} // namespace flexibilityEstimation\n} // namespace stateObservation\n\n#endif /* DYNAMICAL_SYSTEM_HPP_ */\n", "meta": {"hexsha": "dc1be6584d91069d1ca526b08f0aa59092fcd149", "size": 18235, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/state-observation/flexibility-estimation/imu-elastic-local-frame-dynamical-system.hpp", "max_stars_repo_name": "arntanguy/state-observation", "max_stars_repo_head_hexsha": "333d826eb3790f6f65c5694018052dbbc7aec9fc", "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/state-observation/flexibility-estimation/imu-elastic-local-frame-dynamical-system.hpp", "max_issues_repo_name": "arntanguy/state-observation", "max_issues_repo_head_hexsha": "333d826eb3790f6f65c5694018052dbbc7aec9fc", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-07-03T04:30:00.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-03T04:30:00.000Z", "max_forks_repo_path": "include/state-observation/flexibility-estimation/imu-elastic-local-frame-dynamical-system.hpp", "max_forks_repo_name": "arntanguy/state-observation", "max_forks_repo_head_hexsha": "333d826eb3790f6f65c5694018052dbbc7aec9fc", "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.9746835443, "max_line_length": 120, "alphanum_fraction": 0.583383603, "num_tokens": 3616, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240791017536, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4930502355435067}}
{"text": "//==================================================================================================\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_ACOSH_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_ACOSH_HPP_INCLUDED\n\n#include <boost/simd/detail/overload.hpp>\n#include <boost/simd/meta/as_logical.hpp>\n#include <boost/simd/constant/log_2.hpp>\n#include <boost/simd/constant/oneotwoeps.hpp>\n#include <boost/simd/function/if_else.hpp>\n#include <boost/simd/function/is_greater.hpp>\n#include <boost/simd/function/log1p.hpp>\n#include <boost/simd/function/dec.hpp>\n#include <boost/simd/function/plus.hpp>\n#include <boost/simd/function/if_plus.hpp>\n#include <boost/simd/function/sqr.hpp>\n#include <boost/simd/function/sqrt.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n   namespace bd = boost::dispatch;\n   namespace bs = boost::simd;\n   BOOST_DISPATCH_OVERLOAD_IF( acosh_\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 t = dec(a0);\n        auto test = is_greater(t,Oneotwoeps<A0>());\n        A0 z = if_else(test, a0, t+sqrt(t+t+sqr(t)));\n        return if_plus(test, log1p(z), Log_2<A0>());\n      }\n   };\n\n} } }\n\n#endif\n", "meta": {"hexsha": "0fad9f55f2b0c2420a3d6bd4b41ba07a04a67d6f", "size": 1698, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/simd/function/acosh.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/acosh.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/acosh.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.375, "max_line_length": 100, "alphanum_fraction": 0.5789163722, "num_tokens": 382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264639, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4930502335631036}}
{"text": "\r\n//          Copyright surrealwaffle 2018 - 2020.\r\n// Distributed under the Boost Software License, Version 1.0.\r\n//    (See accompanying file LICENSE_1_0.txt or copy at\r\n//          https://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#pragma once\r\n\r\n#include <cstddef>\r\n#include <cmath>\r\n\r\n#include <algorithm>\r\n#include <functional>\r\n#include <type_traits>\r\n#include <utility>\r\n\r\n#include <sentinel/config.hpp>\r\n\r\n\r\n#include <boost/geometry/core/access.hpp>\r\n#include <boost/geometry/core/coordinate_dimension.hpp>\r\n#include <boost/geometry/core/coordinate_type.hpp>\r\n#include <boost/geometry/core/cs.hpp>\r\n#include <boost/geometry/geometries/register/point.hpp>\r\n\r\nnamespace sentinel { namespace math {\r\n\r\ntemplate<class T, std::size_t N>\r\nstruct vector {\r\n    using value_type      = T;\r\n    using size_type       = std::size_t;\r\n    using difference_type = std::ptrdiff_t;\r\n    using reference       = value_type&;\r\n    using const_reference = const value_type&;\r\n    using pointer         = value_type*;\r\n    using const_pointer   = const value_type*;\r\n    using iterator        = pointer;\r\n    using const_iterator  = const_pointer;\r\n\r\n    static_assert(N > 0);\r\n    value_type array[N];\r\n\r\n    static inline constexpr vector zero = vector(/*ZERO INITIALIZED*/);\r\n\r\n    constexpr reference       operator[](size_type pos)       { return array[pos]; }\r\n    constexpr const_reference operator[](size_type pos) const { return array[pos]; }\r\n\r\n    constexpr pointer       data() noexcept       { return array; }\r\n    constexpr const_pointer data() const noexcept { return array; }\r\n\r\n    static\r\n    constexpr size_type size() noexcept { return N; }\r\n\r\n    constexpr iterator begin() noexcept { return array; }\r\n    constexpr iterator end()   noexcept { return begin() + size(); }\r\n\r\n    constexpr const_iterator cbegin() const noexcept { return array; }\r\n    constexpr const_iterator cend()   const noexcept { return begin() + size(); }\r\n\r\n    constexpr const_iterator begin() const noexcept { return cbegin(); }\r\n    constexpr const_iterator end()   const noexcept { return cend(); }\r\n\r\n    constexpr void fill(const T& value) { for (auto& v : *this) v = value; }\r\n\r\n    constexpr bool operator==(const vector& other) const {\r\n        return std::mismatch(begin(), end(), other.begin()).first == end();\r\n    }\r\n\r\n    constexpr bool operator!=(const vector& other) const {\r\n        return !(*this == other);\r\n    }\r\n\r\n    static constexpr vector filled(const T& value)\r\n    {\r\n        auto return_fill_value = [&value] (auto&&...) -> const T& { return value; };\r\n        return [&return_fill_value] <std::size_t... I> (std::index_sequence<I...>) {\r\n            return vector{return_fill_value(I)...};\r\n        } (std::make_index_sequence<N>{});\r\n    }\r\n\r\n    template<class BinaryOp>\r\n    constexpr vector& pointwise_transform(const vector& other, BinaryOp op)\r\n    {\r\n        auto other_it = other.begin();\r\n        for (auto it = begin(), end = this->end(); it != end; ++it, ++other_it)\r\n             *it = op(*it, *other_it);\r\n        return *this;\r\n    }\r\n\r\n    constexpr vector& operator+=(const vector& other) { return pointwise_transform(other, std::plus{}); }\r\n    constexpr vector& operator-=(const vector& other) { return pointwise_transform(other, std::minus{}); }\r\n    constexpr vector& operator*=(const vector& other) { return pointwise_transform(other, std::multiplies{}); }\r\n    constexpr vector& operator/=(const vector& other) { return pointwise_transform(other, std::divides{}); }\r\n\r\n    constexpr vector& operator*=(const T& scalar) { return (*this) *= filled(scalar); }\r\n\r\n    constexpr vector operator+(const vector& other) const { vector result = *this; result += other; return result; }\r\n    constexpr vector operator-(const vector& other) const { vector result = *this; result -= other; return result; }\r\n    constexpr vector operator*(const vector& other) const { vector result = *this; result *= other; return result; }\r\n    constexpr vector operator/(const vector& other) const { vector result = *this; result /= other; return result; }\r\n\r\n    constexpr vector operator-() const;\r\n};\r\n\r\ntemplate<class T, std::size_t N>\r\nconstexpr vector<T, N> vector<T, N>::operator-() const\r\n{\r\n    vector res = *this;\r\n    for (auto& v : res)\r\n        v = -v;\r\n    return res;\r\n}\r\n\r\n/** \\brief Computes the dot product of two vectors.\r\n */\r\ntemplate<class T, std::size_t N>\r\nconstexpr T dot(const vector<T, N>& a, const vector<T, N>& b)\r\n{\r\n    T result = static_cast<T>(0);\r\n    for (std::size_t pos = 0; pos < N; ++pos)\r\n        result += a[pos] * b[pos];\r\n    return result;\r\n}\r\n\r\n/** \\brief Computes the cross product of two vector.\r\n */\r\ntemplate<class T>\r\nconstexpr vector<T, 3> cross(const vector<T, 3>& a, const vector<T, 3>& b)\r\n{\r\n    return {\r\n        a[1] * b[2] - a[2] * b[1],\r\n        a[2] * b[0] - a[0] * b[2],\r\n        a[0] * b[1] - a[1] * b[0]\r\n    };\r\n}\r\n\r\n/** \\brief Computes the square of the norm of a vector.\r\n */\r\ntemplate<class T, std::size_t N>\r\nconstexpr float norm2(const vector<T, N>& vec) { return dot(vec, vec); }\r\n\r\n/** \\brief Computes the norm of a vector.\r\n */\r\ntemplate<class T, std::size_t N>\r\nconstexpr float norm(const vector<T, N>& vec) { return std::sqrt(norm2(vec)); }\r\n\r\n/** \\brief Computes a normalized vector.\r\n *\r\n * If the norm of \\a vec is less than or equal to SENTINEL_VECTOR_SMALL_NORM,\r\n * the returned vector is the `0` vector.\r\n */\r\ntemplate<class T, std::size_t N>\r\nconstexpr vector<T, N> normalized(const vector<T, N>& vec)\r\n{\r\n    const auto length = norm(vec);\r\n    return length > SENTINEL_VECTOR_SMALL_NORM ? (1 / length) * vec\r\n                                               : vector<T, N>::zero;\r\n}\r\n\r\n/** \\brief Performs scalar-vector multiplication.\r\n */\r\ntemplate<class T, std::size_t N>\r\nconstexpr vector<T, N> operator*(const T& scalar, const vector<T, N>& vec)\r\n{\r\n    return vector<T, N>::filled(scalar) * vec;\r\n}\r\n\r\n/** \\brief Performs scalar-vector multiplication.\r\n */\r\ntemplate<class T, std::size_t N>\r\nconstexpr vector<T, N> operator*(const vector<T, N>& vec, const T& scalar)\r\n{\r\n    return vec * vector<T, N>::filled(scalar);\r\n}\r\n\r\ntemplate<class T, std::size_t N, class BinaryOp>\r\nconstexpr vector<T, N> pointwise_compose(const vector<T, N>& a,\r\n                                         const vector<T, N>& b,\r\n                                         BinaryOp op)\r\n{\r\n    vector<T, N> result = a;\r\n    a.pointwise_accumulate(a, std::cref(op));\r\n    return result;\r\n}\r\n\r\nusing fvec2 = vector<float, 2>;\r\nusing fvec3 = vector<float, 3>;\r\n\r\nusing dvec2 = vector<double, 2>;\r\nusing dvec3 = vector<double, 3>;\r\n\r\n} } // namespace sentinel::math\r\n\r\nBOOST_GEOMETRY_REGISTER_POINT_2D(sentinel::math::fvec2,\r\n                                 float,\r\n                                 boost::geometry::cs::cartesian,\r\n                                 operator[](0),\r\n                                 operator[](1)\r\n                                 );\r\n\r\nBOOST_GEOMETRY_REGISTER_POINT_3D(sentinel::math::fvec3,\r\n                                 float,\r\n                                 boost::geometry::cs::cartesian,\r\n                                 operator[](0),\r\n                                 operator[](1),\r\n                                 operator[](2)\r\n                                 );\r\n\r\nBOOST_GEOMETRY_REGISTER_POINT_2D(sentinel::math::dvec2,\r\n                                 double,\r\n                                 boost::geometry::cs::cartesian,\r\n                                 operator[](0),\r\n                                 operator[](1)\r\n                                 );\r\n\r\nBOOST_GEOMETRY_REGISTER_POINT_3D(sentinel::math::dvec3,\r\n                                 double,\r\n                                 boost::geometry::cs::cartesian,\r\n                                 operator[](0),\r\n                                 operator[](1),\r\n                                 operator[](2)\r\n                                 );\r\n", "meta": {"hexsha": "c71c55c1dbc7f42ac3a3d73536758c0a43e9eb9c", "size": 7925, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sentinel/include/sentinel/math/vector.hpp", "max_stars_repo_name": "surrealwaffle/thesurrealwaffle", "max_stars_repo_head_hexsha": "6937d8e2604628a5c9141feef837d89e81f68165", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-07-20T23:04:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-09T04:16:42.000Z", "max_issues_repo_path": "sentinel/include/sentinel/math/vector.hpp", "max_issues_repo_name": "surrealwaffle/thesurrealwaffle", "max_issues_repo_head_hexsha": "6937d8e2604628a5c9141feef837d89e81f68165", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sentinel/include/sentinel/math/vector.hpp", "max_forks_repo_name": "surrealwaffle/thesurrealwaffle", "max_forks_repo_head_hexsha": "6937d8e2604628a5c9141feef837d89e81f68165", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-07-21T06:32:13.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-21T06:32:13.000Z", "avg_line_length": 35.5381165919, "max_line_length": 117, "alphanum_fraction": 0.5723659306, "num_tokens": 1773, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677737461007, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4929262876453861}}
{"text": "#include <benchmark/benchmark.h>\n#include <random>\n#include <complex>\n#include <boost/math/fft/bsl_backend.hpp>\n#include <boost/math/fft/fftw_backend.hpp>\n#include <boost/math/fft/gsl_backend.hpp>\n#include <boost/math/constants/constants.hpp>\n\n#include \"fft_test_helpers.hpp\"\n\nstd::default_random_engine gen;\nstd::uniform_real_distribution<double> distribution;\n\n\ntypedef std::complex<double> cd;\nstd::vector<cd> random_vec(size_t N)\n{\n    std::vector<cd> V(N);\n    for (auto& x : V)\n      x = distribution(gen);\n    return V;\n}\n\nvoid bench_bsl(benchmark::State& state)\n{\n    auto A = random_vec(state.range(0));\n    for (auto _ : state)\n    {\n        using fft_transform = boost::math::fft::bsl_transform;\n        fft_transform::forward(A.data(),A.data()+A.size(),A.data());\n    }\n    state.SetComplexityN(state.range(0));\n}\nvoid bench_gsl(benchmark::State& state)\n{\n    auto A = random_vec(state.range(0));\n    for (auto _ : state)\n    {\n        using fft_transform = boost::math::fft::gsl_transform;\n        fft_transform::forward(A.data(),A.data()+A.size(),A.data());\n    }\n    state.SetComplexityN(state.range(0));\n}\nvoid bench_fftw(benchmark::State& state)\n{\n    auto A = random_vec(state.range(0));\n    for (auto _ : state)\n    {\n        using fft_transform = boost::math::fft::fftw_transform;\n        fft_transform::forward(A.data(),A.data()+A.size(),A.data());\n    }\n    state.SetComplexityN(state.range(0));\n}\n\n//// powers of 2\n//BENCHMARK(bench_bsl)\n//    ->RangeMultiplier(4)\n//    ->Range(1 << 8, 1 << 20)\n//    ->Complexity(benchmark::oNLogN);\n//\n//BENCHMARK(bench_gsl)\n//    ->RangeMultiplier(4)\n//    ->Range(1 << 8, 1 << 20)\n//    ->Complexity(benchmark::oNLogN);\n//\n//BENCHMARK(bench_fftw)\n//    ->RangeMultiplier(4)\n//    ->Range(1 << 8, 1 << 20)\n//    ->Complexity(benchmark::oNLogN);\n\n// powers of 10\n//BENCHMARK(bench_bsl)\n//    ->RangeMultiplier(10)\n//    ->Range(100, 1000000)\n//    ->Complexity(benchmark::oNLogN);\n//\n//BENCHMARK(bench_gsl)\n//    ->RangeMultiplier(10)\n//    ->Range(100, 1000000)\n//    ->Complexity(benchmark::oNLogN);\n//\n//BENCHMARK(bench_fftw)\n//    ->RangeMultiplier(10)\n//    ->Range(100, 1000000)\n//    ->Complexity(benchmark::oNLogN);\n\n// primes\nBENCHMARK(bench_bsl)\n    ->Arg(109)\n    ->Arg(1009)\n    ->Arg(10009)\n    ->Arg(100003)\n    ->Complexity(benchmark::oNLogN);\n\nBENCHMARK(bench_gsl)\n    ->Arg(109)\n    ->Arg(1009)\n    ->Arg(10009)\n    ->Arg(100003)\n    ->Complexity(benchmark::oNLogN);\n\nBENCHMARK(bench_fftw)\n    ->Arg(109)\n    ->Arg(1009)\n    ->Arg(10009)\n    ->Arg(100003)\n    ->Complexity(benchmark::oNLogN);\n\nBENCHMARK_MAIN();\n", "meta": {"hexsha": "097828b4b8c4150b4f5b59f48c9051e650832535", "size": 2588, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/fft_complex_benchmark.cpp", "max_stars_repo_name": "BoostGSoC21/math", "max_stars_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "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": "test/fft_complex_benchmark.cpp", "max_issues_repo_name": "BoostGSoC21/math", "max_issues_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 30.0, "max_issues_repo_issues_event_min_datetime": "2021-06-22T12:59:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-02T09:27:49.000Z", "max_forks_repo_path": "test/fft_complex_benchmark.cpp", "max_forks_repo_name": "BoostGSoC21/math", "max_forks_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-07T21:15:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-07T21:15:02.000Z", "avg_line_length": 23.5272727273, "max_line_length": 68, "alphanum_fraction": 0.6313755796, "num_tokens": 788, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.5813030906443134, "lm_q1q2_score": 0.49292627424494734}}
{"text": "/** @file\n * @brief NPDE WaveABC2D\n * @author Erick Schulz\n * @date 11/12/2019\n * @copyright Developed at ETH Zurich\n */\n\n#include \"waveabc2d.h\"\n\n#include <iostream>\n#include <memory>\n#include <string>\n// Eigen includes\n#include <Eigen/Core>\n// Lehrfem++ includes\n#include <lf/assemble/assemble.h>\n#include <lf/io/io.h>\n#include <lf/mesh/hybrid2d/hybrid2d.h>\n#include <lf/mesh/utils/utils.h>\n#include <lf/uscalfe/uscalfe.h>\n\nusing namespace WaveABC2D;\n\nint main(int /*argc*/, const char ** /*argv*/) {\n  std::cout << \"\\n\" << std::endl;\n  std::cout << \"PROBLEM - WaveABC2D\" << std::endl;\n\n  testConvergenceScalarImplicitTimestepping();\n\n  // Load mesh into a Lehrfem++ object\n  std::cout << \"Loading mesh...\" << std::endl;\n  auto mesh_factory = std::make_unique<lf::mesh::hybrid2d::MeshFactory>(2);\n  const lf::io::GmshReader reader(\n      std::move(mesh_factory), CURRENT_SOURCE_DIR \"/../meshes/unitsquare2.msh\");\n  auto mesh_p = reader.mesh();  // type shared_ptr< const lf::mesh::Mesh>\n\n  // Finite element space\n  auto fe_space_p =\n      std::make_shared<lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n  // Obtain local->global index mapping for current finite element space\n  const lf::assemble::DofHandler &dofh{fe_space_p->LocGlobMap()};\n  // Dimension of finite element space\n  const lf::uscalfe::size_type N_dofs(dofh.NumDofs());\n\n  auto mu0 = [](const Eigen::Vector2d &x) -> double {\n    return std::sin(x.norm());\n  };\n  auto nu0 = [](const Eigen::Vector2d &x) -> double { return std::cos(x(1)); };\n  auto rho = [](Eigen::Vector2d) -> double { return 1.0; };\n\n  WaveABC2DTimestepper<decltype(rho), decltype(mu0), decltype(nu0)> stepper(\n      fe_space_p, rho, 250, 1.0);\n  Eigen::VectorXd discrete_solution = stepper.solveWaveABC2D(mu0, nu0);\n\n  double discrete_energy = stepper.energies();\n\n  // Output results to vtk file\n  lf::io::VtkWriter vtk_writer(mesh_p, \"WaveABC2D_solution.vtk\");\n  // Write nodal data taking the values of the discrete solution at the vertices\n  auto nodal_data = lf::mesh::utils::make_CodimMeshDataSet<double>(mesh_p, 2);\n  for (int global_idx = 0; global_idx < N_dofs; global_idx++) {\n    nodal_data->operator()(dofh.Entity(global_idx)) =\n        discrete_solution[global_idx];\n  };\n  vtk_writer.WritePointData(\"WaveABC2D_solution\", *nodal_data);\n\n  std::cout << \"\\nThe WaveABC2D_solution was written to:\" << std::endl;\n  std::cout << \"WaveABC2D_solution.vtk\\n\" << std::endl;\n\n  std::cout << \"The discrete energies E^(k) : \" << discrete_energy << std::endl;\n  return 0;\n}  // main\n", "meta": {"hexsha": "25bfb8e6ed01fae4339bf653123b19c863bdcc41", "size": 2522, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/WaveABC2D/templates/waveabc2d_main.cc", "max_stars_repo_name": "padomu/NPDECODES", "max_stars_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "homeworks/WaveABC2D/templates/waveabc2d_main.cc", "max_issues_repo_name": "padomu/NPDECODES", "max_issues_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homeworks/WaveABC2D/templates/waveabc2d_main.cc", "max_forks_repo_name": "padomu/NPDECODES", "max_forks_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_forks_repo_licenses": ["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.5479452055, "max_line_length": 80, "alphanum_fraction": 0.6867565424, "num_tokens": 749, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081925, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.4929194360898107}}
{"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#define NT2_UNIT_MODULE \"nt2 polynom toolbox - roots/scalar Mode\"\n\n//////////////////////////////////////////////////////////////////////////////\n// unit test behavior of polynom components in scalar mode\n//////////////////////////////////////////////////////////////////////////////\n/// created  by jt the 06/03/2011\n///\n#include <nt2/include/functions/roots.hpp>\n#include <nt2/include/functions/eye.hpp>\n#include <nt2/include/functions/ones.hpp>\n#include <nt2/include/functions/real.hpp>\n#include <nt2/include/functions/isulpequal.hpp>\n#include <boost/type_traits/is_same.hpp>\n#include <nt2/sdk/functor/meta/call.hpp>\n#include <nt2/sdk/unit/tests.hpp>\n#include <nt2/sdk/unit/module.hpp>\n#include <nt2/sdk/memory/buffer.hpp>\n#include <nt2/include/constants/real.hpp>\n#include <nt2/table.hpp>\n\n\nNT2_TEST_CASE_TPL ( roots_real__1_0,  NT2_REAL_TYPES)\n{\n\n  using nt2::roots;\n  using nt2::tag::roots_;\n  typedef std::complex<T> cT;\n  nt2::table<T> p =  nt2::_(T(1), T(3));\n  p(2) = T(-3); p(3) = T(2);\n  nt2::table<T> c = nt2::_(T(2), T(-1), T(1));\n  NT2_DISPLAY(roots(p));\n  NT2_DISPLAY(c);\n  NT2_TEST(nt2::isulpequal(nt2::real(roots(p)), c, T(5.0)));\n} // end of test for floating_\n\n\n\n\n\n\n", "meta": {"hexsha": "03c84c208c603a61ba009c946ea46980738fbc37", "size": 1694, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/core/polynom/unit/scalar/roots.cpp", "max_stars_repo_name": "pbrunet/nt2", "max_stars_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "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/polynom/unit/scalar/roots.cpp", "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/polynom/unit/scalar/roots.cpp", "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": 34.5714285714, "max_line_length": 80, "alphanum_fraction": 0.5454545455, "num_tokens": 431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7185944046238981, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.49291943561025175}}
{"text": "#include <bitset>\n#include <vector>\n//#include \"stdint.h\"\n#include <iostream>\n#include <functional>\n#include <ctime>\n#include <chrono>\n#include <sys/time.h>\n#include <boost/dynamic_bitset.hpp>\nusing namespace boost;\n\nstruct timeval start, end;\n\nvoid startTimer()\n{\n  gettimeofday(&start,NULL);\n}\nvoid stopTimer()\n{\n  gettimeofday(&end,NULL);\n}\nint getMs()\n{\n  return  (end.tv_sec - start.tv_sec)*1000 + (end.tv_usec-start.tv_usec)/1000;\n}\nint getUs()\n{\n  return  (end.tv_sec - start.tv_sec)*1000*1000 + (end.tv_usec-start.tv_usec);\n}\n\nint main()\n{\n  // empty constructor\n  const int NUM = 10000000;\n  std::vector<uint64_t>  bitwise_v;\n  std::vector<std::bitset<64> >  bitset_v;\n  std::vector<boost::dynamic_bitset<> > boost_bitset_v;\n\n  for (int i = 0; i < NUM; ++i)\n  {\n    std::bitset<64> v(i);\n    boost::dynamic_bitset<> dv(64, i);\n    bitset_v.push_back(v);\n    bitwise_v.push_back(v.to_ulong());\n    boost_bitset_v.push_back(dv);\n  }\n\n  uint64_t biter = 100;\n  std::bitset<64> bitseter(100);\n  boost::dynamic_bitset<> boost_bitsetr(64, 100);\n  int wise_count = 0;\n  int bitset_count = 0;\n  int boost_count = 0;\n  startTimer();\n  for (std::vector<uint64_t>::const_iterator wisei = bitwise_v.begin(); wisei != bitwise_v.end(); ++wisei) {\n    if ((biter & *wisei ) == biter)\n    {\n      wise_count++;\n    }\n  }\n  stopTimer();\n  std::cout << \"time cost Ms: \" << getMs() << std::endl;\n  std::cout << \"time cost Us: \" << getUs() << std::endl;\n  std::cout << \"wise_count: \" << wise_count << std::endl;\n\n  startTimer();\n  for (std::vector<std::bitset<64> >::const_iterator seti = bitset_v.begin(); seti != bitset_v.end(); ++seti) {\n    if ((bitseter & *seti) == bitseter)\n    {\n      bitset_count++;\n    }\n  }\n  stopTimer();\n  std::cout << \"time cost Ms: \" << getMs() << std::endl;\n  std::cout << \"time cost Us: \" << getUs() << std::endl;\n  std::cout << \"biter_count: \" << bitset_count << std::endl;\n\n// boost dynamic bitset\n  startTimer();\n  for (std::vector<boost::dynamic_bitset<> >::const_iterator dbi = boost_bitset_v.begin(); dbi != boost_bitset_v.end(); ++dbi) {\n    if ((boost_bitsetr & *dbi) == boost_bitsetr)\n    {\n      boost_count++;\n    }\n  }\n  stopTimer();\n  std::cout << \"time cost Ms: \" << getMs() << std::endl;\n  std::cout << \"time cost Us: \" << getUs() << std::endl;\n  std::cout << \"boost_count: \" << boost_count << std::endl;\n  // unsigned long long constructor\n  //std::bitset<8> b02(42);          // [0,0,1,0,1,0,1,0]\n  //std::bitset<70> bl(ULLONG_MAX); // [0,0,0,0,0,0,1,1,1,...,1,1,1] in C++11\n  //std::bitset<8> bs(0xfff0);      // [1,1,1,1,0,0,0,0]\n\n  //// string constructor\n  //std::string bit_string = \"110010\";\n  //std::bitset<8> b3(bit_string); // [0,0,1,1,0,0,1,0]\n  //std::bitset<8> b4(bit_string, 2); // [0,0,0,0,0,0,1,0]\n  //std::bitset<8> b5(bit_string, 2, 3); // [0,0,0,0,0,0,0,1]\n\n  //// string constructor using custom zero/one digits\n  //std::string alpha_bit_string = \"aBaaBBaB\";\n  //std::bitset<8> b6 (alpha_bit_string, 0, alpha_bit_string.size(), 'a', 'B'); // [0,1,0,0,1,1,0,1]\n\n  //// char* constructor using custom digits\n  //std::bitset<8> b7(\"XXXXYYYY\", 8, 'X', 'Y');\n\n  //std::cout << b01 << '\\n' << b02 << '\\n' << bl << '\\n' << bs << '\\n'\n  //<< b3 << '\\n' << b4 << '\\n' << b5 << '\\n' << b6 << '\\n'\n  //<< b7 << '\\n';\n\n  //// bitwise operation\n  //std::bitset<4> b1(\"0110\");\n  //std::bitset<4> b2(\"0011\");\n  //std::cout << \"b1 & b2: \" << (b1 & b2) << '\\n';\n  //std::cout << \"b1 | b2: \" << (b1 | b2) << '\\n';\n  //std::cout << \"b1 ^ b2: \" << (b1 ^ b2) << '\\n';\n\n  //// operation all any none\n  //std::bitset<4> bo1(\"0000\");\n  //std::bitset<4> bo2(\"0101\");\n  //std::bitset<4> bo3(\"1111\");\n\n  //std::cout << \"bitset\\t\" << \"all\\t\" << \"any\\t\" << \"none\\n\";\n  //std::cout << bo1 << '\\t' << bo1.all() << '\\t' << bo1.any() << '\\t' << bo1.none() << '\\n';\n  //std::cout << bo2 << '\\t' << bo2.all() << '\\t' << bo2.any() << '\\t' << bo2.none() << '\\n';\n  //std::cout << bo3 << '\\t' << bo3.all() << '\\t' << bo3.any() << '\\t' << bo3.none() << '\\n';\n}\n\n", "meta": {"hexsha": "549196d5e5bc6a1f0e745807df73441dac7d2e69", "size": 3982, "ext": "cc", "lang": "C++", "max_stars_repo_path": "cpp/cpp-snippet/bitset/bitsetAndBitWise.cc", "max_stars_repo_name": "haitongz/code", "max_stars_repo_head_hexsha": "9b2f559aa57e5ad669611b2c68f041b389dcb49c", "max_stars_repo_licenses": ["Apache-2.0"], "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/cpp-snippet/bitset/bitsetAndBitWise.cc", "max_issues_repo_name": "haitongz/code", "max_issues_repo_head_hexsha": "9b2f559aa57e5ad669611b2c68f041b389dcb49c", "max_issues_repo_licenses": ["Apache-2.0"], "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/cpp-snippet/bitset/bitsetAndBitWise.cc", "max_forks_repo_name": "haitongz/code", "max_forks_repo_head_hexsha": "9b2f559aa57e5ad669611b2c68f041b389dcb49c", "max_forks_repo_licenses": ["Apache-2.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.6307692308, "max_line_length": 128, "alphanum_fraction": 0.5570065294, "num_tokens": 1447, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943805178139, "lm_q2_score": 0.6859494678483918, "lm_q1q2_score": 0.4929194329150392}}
{"text": "/*\r\nThis file is a part of Raman-Scattering-Code-Conversion.\r\n<https://github.com/Kirbologist/Raman-Scattering-Code-Conversion>\r\n\r\nWritten by Siwan Li for the UQ School of Maths and Physics.\r\nBased on the SMARTIES MATLAB package by W.R.C. Somerville, B. Augui\u00e9, E.C. Le Ru\r\nCopyright (C) 2021-2022 Siwan Li\r\n\r\nThis source code form is subject to the terms of the MIT License.\r\nIf a copy of the MIT License was not distributed with this file,\r\nyou can obtain one at <https://opensource.org/licenses/MIT>.\r\n\r\n\r\nVarious small maths functions, helper functions and others used throughout SMARTIES functions that don't fit anywhere.\r\n*/\r\n\r\n#ifndef SMARTIES_MATH_HPP\r\n#define SMARTIES_MATH_HPP\r\n\r\n#include \"core.hpp\"\r\n#include <Eigen/LU>\r\n#include <boost/math/special_functions/bessel.hpp>\r\n#include <boost/math/constants/constants.hpp>\r\n\r\nusing namespace Eigen;\r\nusing namespace std;\r\n\r\nnamespace Smarties {\r\n  /* Returns the mathematical constant pi with the amount of precision specified by template argument */\r\n  template <class Real>\r\n  inline Real mp_pi(void) { return boost::math::constants::pi<Real>(); }\r\n\r\n  /* Returns the machine epsilon of the type given in the template argument */\r\n  template <class Real>\r\n  inline Real mp_eps(void) { return numeric_limits<Real>::epsilon(); }\r\n\r\n  /* Returns the imaginary unit 'i' with the type given in the template argument */\r\n  template <class Real>\r\n  inline complex<Real> mp_im_unit(void) { return complex<Real>(0.0, 1.0); }\r\n\r\n  /*\r\n  View an existing Eigen::Tensor of rank 2 as an Eigen::Map<Eigen::Matrix>\r\n  Rows/Cols are determined from the matrix\r\n  */\r\n  template<typename Scalar>\r\n  auto ArrayMap(Tensor<Scalar, 2>& tensor) {\r\n      return Eigen::Map<ArrayXXr<Scalar>>(tensor.data(), tensor.dimension(0), tensor.dimension(1));\r\n  }\r\n\r\n  /*\r\n  Converts an Eigen::Matrix (or expression) to Eigen::Tensor\r\n  with dimensions specified in std::array\r\n  */\r\n  template<typename Derived, typename T, auto rank>\r\n  Tensor<typename Derived::Scalar, rank>\r\n  TensorCast(const EigenBase<Derived>& matrix, const std::array<T, rank>& dims) {\r\n      return Eigen::TensorMap<const Tensor<const typename Derived::Scalar, rank>>\r\n                  (matrix.derived().eval().data(), dims);\r\n  }\r\n\r\n  /*\r\n  Converts an Eigen::Matrix (or expression) to Eigen::Tensor\r\n  with dimensions as variadic arguments\r\n  */\r\n  template<typename Derived, typename... Dims>\r\n  auto TensorCast(const EigenBase<Derived>& matrix, const Dims... dims) {\r\n      static_assert(sizeof...(Dims) > 0, \"TensorCast: sizeof... (Dims) must be larger than 0\");\r\n      return TensorCast(matrix, std::array<Eigen::Index, sizeof...(Dims)>{dims...});\r\n  }\r\n\r\n  /*\r\n  Converts an Eigen::Matrix (or expression) to Eigen::Tensor\r\n  with dimensions directly as arguments in a variadic template\r\n  */\r\n  template<typename Derived>\r\n  auto TensorCast(const EigenBase<Derived>& matrix) {\r\n    if constexpr(Derived::ColsAtCompileTime == 1 or Derived::RowsAtCompileTime == 1) {\r\n      return TensorCast(matrix, matrix.size());\r\n    } else {\r\n      return TensorCast(matrix, matrix.rows(), matrix.cols());\r\n    }\r\n  }\r\n\r\n  /* Get a readable name/description of the type given in the template argument */\r\n  template <class Real>\r\n  string GetTypeName() {\r\n    string calc_type = typeid(static_cast<Real>(0)).name();\r\n    if (calc_type.find(\"N5boost14multiprecision6numberINS0_8backends18mpfr_float_backend\") != string::npos) {\r\n      size_t prec_begin = calc_type.find(\"ILj\") + 3;\r\n      size_t prec_end = calc_type.find(\"ELNS\");\r\n      string precision = calc_type.substr(prec_begin, prec_end - prec_begin);\r\n      calc_type = \"custom_\" + precision;\r\n    } else if (calc_type == \"f\")\r\n      calc_type = \"single\";\r\n    else if (calc_type == \"d\")\r\n      calc_type = \"double\";\r\n    else if (calc_type == \"e\")\r\n      calc_type = \"quad\";\r\n    return calc_type;\r\n  }\r\n\r\n  /*\r\n  Get a slice of a rank-3 tensor, so that the indices of the slices are given by Eigen::ArithmeticSequence.\r\n  This is just a helper function for sphCheckBesselConvergence, and is not usable for general purpose.\r\n  */\r\n  template <class Real>\r\n  Tensor3c<Real> TensorSlice(Tensor3c<Real>& tensor,\r\n      ArithmeticSequence<long int, long int, long int> slice_dim1,\r\n      ArithmeticSequence<long int, long int, long int> slice_dim2,\r\n      ArithmeticSequence<long int, long int, long int> slice_dim3) {\r\n    long int new_dim1 = slice_dim1.size();\r\n    long int new_dim2 = slice_dim2.size();\r\n    long int new_dim3 = slice_dim3.size();\r\n    Tensor3c<Real> output(new_dim1, new_dim2, new_dim3);\r\n    for (long int i = 0; i < new_dim1; i++) {\r\n      for (long int j = 0; j < new_dim2; j++) {\r\n        for (long int k = 0; k < new_dim3; k++)\r\n          output(i, j, k) = tensor(slice_dim1[i], slice_dim2[j], slice_dim3[k]);\r\n      }\r\n    }\r\n    return output;\r\n  }\r\n\r\n  /*\r\n  Initialize a linearly-spaced single-column Eigen::Array by converting from an Eigen::ArithmeticSequence.\r\n  Parameters are the same ones used to construct an Eigen::ArithmeticSequence.\r\n  */\r\n  ArrayXi Seq2Array(long int first, long int last, long int stride);\r\n\r\n  /*\r\n  Reduce a complex rank-3 Eigen::Tensor into a complex Eigen::Array by\r\n  reducing the third dimension of the tensor down to only coefficients whose third index is `offset`,\r\n  and reducing the first dimenstion down to only the last `num_rows` rows.\r\n  This was used specifically as a helper function in sphCalculatePQ.\r\n  */\r\n  template <class Real>\r\n  ArrayXXc<Real> Subtensor2ArrMap(const Tensor3c<Real>& tensor,\r\n      const std::array<int, 3>& offsets, const std::array<int, 3>& extents, int rows, int cols) {\r\n    ArrayXXc<Real> output(rows, cols);\r\n    for (int i = 0; i < rows; i++) {\r\n      for (int j = 0; j < cols; j++)\r\n        output(i, j) = tensor(offsets[0] + i, offsets[1], offsets[2] + j);\r\n    }\r\n    return output;\r\n  }\r\n\r\n  /* Performs matrix inversion using LU with partial pivoting of columns. This is used in rvhGetTRfromPQ. */\r\n  template <class Real>\r\n  ArrayXXc<Real> InvertLUcol(MatrixXc<Real>& M) {\r\n    PartialPivLU<MatrixXc<Real>> PLU_decomp = M.matrix().lu();\r\n    return PLU_decomp.inverse().array();\r\n  }\r\n\r\n  /* Performs the equivalent of MATLAB's logical indexing on a single-column Eigen::Array. */\r\n  template <class Real>\r\n  ArrayXr<Real> LogicalSlice(ArrayXr<Real>& base_array, ArrayXb& bool_array) {\r\n    assert(base_array.size() == bool_array.size());\r\n    int output_size = bool_array.count();\r\n    ArrayXr<Real> output(output_size);\r\n    int base_index = 0;\r\n    for (int i = 0; i < output_size && base_index < bool_array.size(); i++, base_index++) {\r\n      while (!bool_array(base_index))\r\n        base_index++;\r\n      output(i) = base_array(base_index);\r\n    }\r\n    return output;\r\n  }\r\n\r\n  /* Performs the equivalent of MATLAB's logical indexing on a single-row Eigen::Array. */\r\n  template <class Real>\r\n  RowArrayXr<Real> LogicalSlice(RowArrayXr<Real>& base_array, RowArrayXb& bool_array) {\r\n    assert(base_array.size() == bool_array.size());\r\n    int output_size = bool_array.count();\r\n    RowArrayXr<Real> output(output_size);\r\n    int base_index = 0;\r\n    for (int i = 0; i < output_size && base_index < bool_array.size(); i++, base_index++) {\r\n      while (!bool_array(base_index))\r\n        base_index++;\r\n      output(i) = base_array(base_index);\r\n    }\r\n    return output;\r\n  }\r\n\r\n  /* Gets the indices of all 'true' components of a single-column boolean Eigen::Array. */\r\n  ArrayXi LogicalIndices(ArrayXb& bool_array);\r\n\r\n  /* Take a tensor and return the same tensor, but with all its coefficients conjugated. */\r\n  template <class Real>\r\n  Tensor4c<Real> TensorConj(Tensor4c<Real>& base) {\r\n    Tensor4c<Real> output = base;\r\n    for (int i = 0; i < base.dimension(0); i++) {\r\n      for (int j = 0; j < base.dimension(1); j++) {\r\n        for (int k = 0; k < base.dimension(2); k++) {\r\n          for (int l = 0; l < base.dimension(3); l++)\r\n            output(i, j, k, l) = conj(base(i, j, k, l));\r\n        }\r\n      }\r\n    }\r\n    return output;\r\n  }\r\n\r\n  /* Calculates the Bessel function of the first kind with many values of `nu` and a fixed value of `x`. */\r\n  template <class Real>\r\n  ArrayXr<Real> ArrBesselJ(ArrayXr<Real>& nu, Real x) {\r\n    ArrayXr<Real> output(nu.size());\r\n    for (int i = 0; i < nu.size(); i++)\r\n      output(i) = boost::math::cyl_bessel_j<Real>(nu(i), x);\r\n    return output;\r\n  }\r\n\r\n  /* Calculates the Bessel function of the second kind with many values of `nu` and a fixed value of `x`. */\r\n  template <class Real>\r\n  ArrayXr<Real> ArrBesselY(ArrayXr<Real>& nu, Real x) {\r\n    ArrayXr<Real> output(nu.size());\r\n    for (int i = 0; i < nu.size(); i++)\r\n      output(i) = boost::math::cyl_neumann<Real>(nu(i), x);\r\n    return output;\r\n  }\r\n}\r\n\r\n#endif\r\n", "meta": {"hexsha": "634fa429ad2e7a1fe00962de92fff9f2978b73a9", "size": 8749, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/misc.hpp", "max_stars_repo_name": "Kirbologist/Raman-Scattering-Code-Conversion", "max_stars_repo_head_hexsha": "118a08238a2525f595c4b7d2b735dd37852fac6f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-09T12:41:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-09T12:41:22.000Z", "max_issues_repo_path": "src/misc.hpp", "max_issues_repo_name": "Kirbologist/Raman-Scattering-Code-Conversion", "max_issues_repo_head_hexsha": "118a08238a2525f595c4b7d2b735dd37852fac6f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/misc.hpp", "max_forks_repo_name": "Kirbologist/Raman-Scattering-Code-Conversion", "max_forks_repo_head_hexsha": "118a08238a2525f595c4b7d2b735dd37852fac6f", "max_forks_repo_licenses": ["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.4099099099, "max_line_length": 119, "alphanum_fraction": 0.6608755286, "num_tokens": 2250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943805178139, "lm_q2_score": 0.6859494678483918, "lm_q1q2_score": 0.4929194329150392}}
{"text": "#include <boost/random/laplace_distribution.hpp>\n", "meta": {"hexsha": "b8198e0534ae2cdd02b7a3aac189ca00d42e248f", "size": 49, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_random_laplace_distribution.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_random_laplace_distribution.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_random_laplace_distribution.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 24.5, "max_line_length": 48, "alphanum_fraction": 0.8367346939, "num_tokens": 10, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624890918021, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.4929009617979507}}
{"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 tree_augmentation_long_test.cpp\n * @brief\n * @author Attila Bernath\n * @version 1.0\n * @date 2013-07-08\n */\n\n#include \"test_utils/logger.hpp\"\n#include \"test_utils/test_result_check.hpp\"\n#include \"test_utils/get_test_dir.hpp\"\n#include \"test_utils/system.hpp\"\n\n#include \"paal/iterative_rounding/treeaug/tree_augmentation.hpp\"\n#include \"paal/utils/parse_file.hpp\"\n\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/test/unit_test.hpp>\n\n#include <fstream>\n\nusing namespace paal;\nusing namespace paal::ir;\nusing namespace boost;\n\n\nusing Graph = adjacency_list<vecS, vecS, undirectedS,\n        no_property,\n        property<edge_weight_t, double,\n        property<edge_color_t, bool>>>;\n\nusing Traits = adjacency_list_traits<vecS, vecS, undirectedS>;\nusing Vertex = graph_traits<Graph>::vertex_descriptor;\nusing Edge = graph_traits<Graph>::edge_descriptor;\n\nusing Index = property_map<Graph, vertex_index_t>::type;\nusing Cost = property_map<Graph, edge_weight_t>::type;\nusing TreeMap = property_map<Graph, edge_color_t>::type;\n\n// Read instance in format\n// @nodes 6\n// label\n// 0\n// 1\n// 2\n// 3\n// 4\n// 5\n// @edges 10\n//                 label   intree  cost\n// 0       1       0       1       0\n// 1       2       1       1       0\n// 1       3       2       1       0\n// 3       4       3       1       0\n// 3       5       4       1       0\n// 0       3       0       0       1\n// 0       2       1       0       1\n// 2       4       2       0       1\n// 2       5       3       0       1\n// 4       5       4       0       1\nvoid read_tree_aug(std::ifstream & is,\n        Graph & g, Cost & cost, TreeMap & tree_map) {\n    std::string s;\n    std::unordered_map<std::string, Vertex> nodes;\n    int vertices_num, edges_num;\n    is >> s; is >> vertices_num; is >> s;\n\n    for (int i = 0; i < vertices_num; i++) {\n        std::string nlabel;\n        is >> nlabel;\n        nodes[nlabel] = add_vertex(g);\n    }\n\n    LOGLN(num_vertices(g));\n\n    is >> s; is >> edges_num; is >> s; is >> s; is >> s;\n\n    for (int i = 0; i < edges_num; i++) {\n        // read from the file\n        std::string u, v;\n        double c;\n        int dummy;\n        bool in_t;\n        is >> u >> v >> dummy >> in_t >> c;\n\n        bool b;\n        Traits::edge_descriptor e;\n        std::tie(e, b) = add_edge(nodes[u], nodes[v], g);\n        assert(b);\n        put(cost, e, c);\n        put(tree_map, e, in_t);\n    }\n}\n\ntemplate <typename TA>\n// the copy is intended\n    double get_lower_bound(TA ta) {\n    tree_augmentation_ir_components<> comps;\n    lp::glp lp;\n    comps.call<Init>(ta, lp);\n    auto prob_type = comps.call<SolveLP>(ta, lp);\n    BOOST_CHECK_EQUAL(prob_type, lp::OPTIMAL);\n    return lp.get_obj_value();\n}\n\nBOOST_AUTO_TEST_CASE(tree_augmentation_long) {\n    std::string test_dir = paal::system::get_test_data_dir(\"TREEAUG\");\n    using paal::system::build_path;\n\n    parse(build_path(test_dir, \"tree_aug.txt\"), [&](const std::string & fname, std::istream &) {\n        LOGLN(fname);\n        std::string filename = build_path(test_dir, \"cases/\" + fname + \".lgf\");\n        std::ifstream ifs(filename);\n        assert(ifs.good());\n\n        Graph g;\n        Cost cost = get(edge_weight, g);\n        TreeMap tree_map = get(edge_color, g);\n\n        read_tree_aug(ifs, g, cost, tree_map);\n\n        std::vector<Edge> solution;\n        auto treeaug(make_tree_aug(g, std::back_inserter(solution)));\n\n        auto invalid = treeaug.check_input_validity();\n        BOOST_CHECK(!invalid);\n        LOGLN(\"Input validation \" << filename << \" ends.\");\n\n        double lplowerbd = get_lower_bound(treeaug);\n        auto result = solve_iterative_rounding(\n            treeaug, tree_augmentation_ir_components<>());\n        BOOST_CHECK_EQUAL(result.first, lp::OPTIMAL);\n\n        double solval = treeaug.get_solution_cost();\n        BOOST_CHECK_EQUAL(solval, *(result.second));\n        check_result_compare_to_bound(solval, lplowerbd, 2);\n    });\n}\n", "meta": {"hexsha": "ccef7c2ad01af7a764c49ea2cd793cccff144a80", "size": 4253, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/iterative_rounding/tree_augmentation/tree_augmentation_long_test.cpp", "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": "test/iterative_rounding/tree_augmentation/tree_augmentation_long_test.cpp", "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": "test/iterative_rounding/tree_augmentation/tree_augmentation_long_test.cpp", "max_forks_repo_name": "Kommeren/AA", "max_forks_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-24T06:23:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-24T06:23:56.000Z", "avg_line_length": 29.1301369863, "max_line_length": 96, "alphanum_fraction": 0.5753585704, "num_tokens": 1149, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.782662489091802, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.49290096179795057}}
{"text": "#pragma once\n\n#include <polyfem/ProblemWithSolution.hpp>\n\n#include <vector>\n#include <Eigen/Dense>\n\nnamespace polyfem\n{\n\n\tclass FrankeProblem: public ProblemWithSolution\n\t{\n\tpublic:\n\t\tFrankeProblem(const std::string &name);\n\n\t\tVectorNd eval_fun(const VectorNd &pt) const override;\n\t\tAutodiffGradPt eval_fun(const AutodiffGradPt &pt) const override;\n\t\tAutodiffHessianPt eval_fun(const AutodiffHessianPt &pt) const override;\n\n\t\tbool is_scalar() const override { return true; }\n\n\t};\n}\n\n\n", "meta": {"hexsha": "c8660deac94a598fe7c004501c5ac0d7de3bb5f8", "size": 484, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/problem/FrankeProblem.hpp", "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/problem/FrankeProblem.hpp", "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/problem/FrankeProblem.hpp", "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": 18.6153846154, "max_line_length": 73, "alphanum_fraction": 0.7644628099, "num_tokens": 129, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.6297746074044135, "lm_q1q2_score": 0.4929009490275516}}
{"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__EKF_HPP_\n#define SMOOTH__FEEDBACK__EKF_HPP_\n\n#include <Eigen/Cholesky>\n#include <boost/numeric/odeint.hpp>\n#include <smooth/compat/odeint.hpp>\n#include <smooth/diff.hpp>\n#include <smooth/lie_group.hpp>\n\nnamespace smooth::feedback {\n\n/**\n * @brief Extended Kalman filter on Lie groups.\n *\n * The primary methods are predict() and update().\n * - predict(): propagates filter state through a dynamical model.\n * - update(): Bayesian update of filter state from a measurement.\n *\n * Use this class for information fusion (without dynamics) by solely using update().\n *\n * @tparam G \\p smooth::LieGroup type.\n * @tparam DiffType \\p smooth::diff::Type method for calculating derivatives.\n * @tparam Stpr \\p boost::numeric::odeint templated stepper type (\\p euler / \\p runge_kutta4 /\n * ...). Defaults to \\p euler.\n */\ntemplate<\n  LieGroup G,\n  diff::Type DiffType                 = diff::Type::Default,\n  template<typename...> typename Stpr = boost::numeric::odeint::euler>\n  requires(Dof<G> > 0)\nclass EKF\n{\npublic:\n  //! Scalar type for computations.\n  //! Degrees of freedom.\n  using CovT = Eigen::Matrix<Scalar<G>, Dof<G>, Dof<G>>;\n\n  /**\n   * @brief Reset the state of the EKF.\n   *\n   * @param g filter value\n   * @param P filter covariance\n   */\n  void reset(const G & g, const CovT & P)\n  {\n    g_hat_ = g;\n    P_     = P;\n  }\n\n  /**\n   * @brief Access filter state estimate.\n   */\n  G estimate() const { return g_hat_; }\n\n  /**\n   * @brief Access filter covariance.\n   */\n  CovT covariance() const { return P_; }\n\n  /**\n   * @brief Propagate EKF through dynamics \\f$ \\mathrm{d}^r x_t = f(t, x) \\f$ with covariance\n   * \\f$Q\\f$ over a time interval \\f$ [0, \\tau] \\f$.\n   *\n   * @param f right-hand side \\f$ f : \\mathbb{R} \\times \\mathbb{G} \\rightarrow \\mathbb{R}^{\\dim\n   * \\mathfrak{g}} \\f$ of the dynamics. The time type must be the scalar type of G.\n   * @param Q process covariance (size \\f$ \\dim \\mathfrak{g} \\times \\dim \\mathfrak{g} \\f$)\n   * @param tau amount of time to propagate\n   * @param dt maximal ODE solver step size (defaults to \\p tau, i.e. one step)\n   *\n   * @note The time \\f$ t \\f$ argument of \\f$ f(t, x) \\f$ ranges over the interval \\f$t  \\in [0,\n   * \\tau] \\f$.\n   *\n   * @note The covariance \\f$ Q \\f$ is infinitesimal, i.e. its SI unit is \\f$ S^2/T \\f$\n   * where \\f$S\\f$ is the unit of state and \\f$T\\f$ is the unit of time.\n   *\n   * @note Only the upper triangular part of Q is used.\n   */\n  template<typename F, typename QDer>\n  void predict(\n    F && f, const Eigen::MatrixBase<QDer> & Q, Scalar<G> tau, std::optional<Scalar<G>> dt = {})\n  {\n    const auto state_ode = [&f](const G & g, Tangent<G> & dg, Scalar<G> t) { dg = f(t, g); };\n\n    const auto cov_ode = [this, &f, &Q](const CovT & cov, CovT & dcov, Scalar<G> t) {\n      const auto f_x = [&f, &t]<typename _T>(const CastT<_T, G> & x) -> Tangent<CastT<_T, G>> {\n        return f(t, x);\n      };\n      const auto [fv, dr] = diff::dr<1, DiffType>(f_x, wrt(g_hat_));\n      const CovT A        = -ad<G>(fv) + dr;\n      dcov = (A * cov + cov * A.transpose() + Q).template selfadjointView<Eigen::Upper>();\n    };\n\n    Scalar<G> t          = 0;\n    const Scalar<G> dt_v = dt.value_or(2 * tau);\n    while (t + dt_v < tau) {\n      // step covariance first since it depends on g_hat_\n      cst_.do_step(cov_ode, P_, t, dt_v);\n      sst_.do_step(state_ode, g_hat_, t, dt_v);\n      t += dt_v;\n    }\n\n    // last step up to time t\n    cst_.do_step(cov_ode, P_, t, tau - t);\n    sst_.do_step(state_ode, g_hat_, t, tau - t);\n  }\n\n  /**\n   * @brief Update EKF with a measurement \\f$y = h(x) + w\\f$ where \\f$w \\sim \\mathcal N(0, R)\\f$.\n   *\n   * @param h measurement function \\f$ h : \\mathbb{G} \\rightarrow \\mathbb{Y} \\f$\n   * @param y measurement value \\f$ y \\in \\mathbb{Y} \\f$\n   * @param R measurement covariance (size \\f$ \\dim \\mathbb{Y} \\times \\dim \\mathbb{Y} \\f$)\n   *\n   * @note The function h must be differentiable using the desired method.\n   *\n   * @note Only the upper triangular part of \\f$R\\f$ is used\n   */\n  template<typename F, typename RDev, Manifold Y = std::invoke_result_t<F, G>>\n  void update(F && h, const Y & y, const Eigen::MatrixBase<RDev> & R)\n  {\n    const auto [hval, H] = diff::dr<1, DiffType>(h, wrt(g_hat_));\n\n    using Result = std::decay_t<decltype(hval)>;\n\n    static_assert(Manifold<Result>, \"h(x) is not a Manifold\");\n\n    static constexpr Eigen::Index Ny = Dof<Result>;\n\n    static_assert(Ny > 0, \"h(x) must be statically sized\");\n\n    const Eigen::Matrix<Scalar<G>, Ny, Ny> S =\n      (H * P_.template selfadjointView<Eigen::Upper>() * H.transpose() + R)\n        .template triangularView<Eigen::Upper>();\n\n    // solve for Kalman gain\n    const Eigen::Matrix<Scalar<G>, Dof<G>, Ny> K =\n      S.template selfadjointView<Eigen::Upper>().ldlt().solve(H * P_).transpose();\n\n    // update estimate and covariance\n    g_hat_ += K * (y - hval);\n    P_ = ((CovT::Identity() - K * H) * P_).template selfadjointView<Eigen::Upper>();\n  }\n\nprivate:\n  // filter estimate and covariance\n  G g_hat_ = Default<G>();\n  CovT P_  = CovT::Identity();\n\n  // steppers for numerical ODE solutions\n  Stpr<G, Scalar<G>, Tangent<G>, Scalar<G>, boost::numeric::odeint::vector_space_algebra> sst_{};\n  Stpr<CovT, Scalar<G>, CovT, Scalar<G>, boost::numeric::odeint::vector_space_algebra> cst_{};\n};\n\n}  // namespace smooth::feedback\n\n#endif  // SMOOTH__FEEDBACK__EKF_HPP_\n", "meta": {"hexsha": "7001cdfa69ec6a90b58ff8aad01352a35dc35ec5", "size": 6665, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/smooth/feedback/ekf.hpp", "max_stars_repo_name": "tgurriet/smooth_feedback", "max_stars_repo_head_hexsha": "1f926cb4269741ddc09ba048af5bea5e0390a053", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-09-08T16:18:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-28T06:13:55.000Z", "max_issues_repo_path": "include/smooth/feedback/ekf.hpp", "max_issues_repo_name": "tgurriet/smooth_feedback", "max_issues_repo_head_hexsha": "1f926cb4269741ddc09ba048af5bea5e0390a053", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2021-09-08T16:39:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-10T03:51:41.000Z", "max_forks_repo_path": "include/smooth/feedback/ekf.hpp", "max_forks_repo_name": "tgurriet/smooth_feedback", "max_forks_repo_head_hexsha": "1f926cb4269741ddc09ba048af5bea5e0390a053", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2022-02-07T15:56:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T07:23:18.000Z", "avg_line_length": 36.6208791209, "max_line_length": 97, "alphanum_fraction": 0.6496624156, "num_tokens": 1965, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.4929009445358303}}
{"text": "// This file is part of Eigen, a lightweight C++ template library\n// for linear algebra.\n//\n// Copyright (C) 2008-2009 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 \"main.h\"\n#include <Eigen/Geometry>\n#include <Eigen/LU>\n#include <Eigen/SVD>\n\n/* this test covers the following files:\n   Geometry/OrthoMethods.h\n*/\n\ntemplate<typename Scalar> void orthomethods_3()\n{\n  typedef typename NumTraits<Scalar>::Real RealScalar;\n  typedef Matrix<Scalar,3,3> Matrix3;\n  typedef Matrix<Scalar,3,1> Vector3;\n\n  typedef Matrix<Scalar,4,1> Vector4;\n\n  Vector3 v0 = Vector3::Random(),\n          v1 = Vector3::Random(),\n          v2 = Vector3::Random();\n\n  // cross product\n  VERIFY_IS_MUCH_SMALLER_THAN(v1.cross(v2).dot(v1), Scalar(1));\n  VERIFY_IS_MUCH_SMALLER_THAN(v1.dot(v1.cross(v2)), Scalar(1));\n  VERIFY_IS_MUCH_SMALLER_THAN(v1.cross(v2).dot(v2), Scalar(1));\n  VERIFY_IS_MUCH_SMALLER_THAN(v2.dot(v1.cross(v2)), Scalar(1));\n  Matrix3 mat3;\n  mat3 << v0.normalized(),\n         (v0.cross(v1)).normalized(),\n         (v0.cross(v1).cross(v0)).normalized();\n  VERIFY(mat3.isUnitary());\n\n\n  // colwise/rowwise cross product\n  mat3.setRandom();\n  Vector3 vec3 = Vector3::Random();\n  Matrix3 mcross;\n  int i = internal::random<int>(0,2);\n  mcross = mat3.colwise().cross(vec3);\n  VERIFY_IS_APPROX(mcross.col(i), mat3.col(i).cross(vec3));\n  mcross = mat3.rowwise().cross(vec3);\n  VERIFY_IS_APPROX(mcross.row(i), mat3.row(i).cross(vec3));\n\n  // cross3\n  Vector4 v40 = Vector4::Random(),\n          v41 = Vector4::Random(),\n          v42 = Vector4::Random();\n  v40.w() = v41.w() = v42.w() = 0;\n  v42.template head<3>() = v40.template head<3>().cross(v41.template head<3>());\n  VERIFY_IS_APPROX(v40.cross3(v41), v42);\n  \n  // check mixed product\n  typedef Matrix<RealScalar, 3, 1> RealVector3;\n  RealVector3 rv1 = RealVector3::Random();\n  VERIFY_IS_APPROX(v1.cross(rv1.template cast<Scalar>()), v1.cross(rv1));\n  VERIFY_IS_APPROX(rv1.template cast<Scalar>().cross(v1), rv1.cross(v1));\n}\n\ntemplate<typename Scalar, int Size> void orthomethods(int size=Size)\n{\n  typedef typename NumTraits<Scalar>::Real RealScalar;\n  typedef Matrix<Scalar,Size,1> VectorType;\n  typedef Matrix<Scalar,3,Size> Matrix3N;\n  typedef Matrix<Scalar,Size,3> MatrixN3;\n  typedef Matrix<Scalar,3,1> Vector3;\n\n  VectorType v0 = VectorType::Random(size);\n\n  // unitOrthogonal\n  VERIFY_IS_MUCH_SMALLER_THAN(v0.unitOrthogonal().dot(v0), Scalar(1));\n  VERIFY_IS_APPROX(v0.unitOrthogonal().norm(), RealScalar(1));\n\n  if (size>=3)\n  {\n    v0.template head<2>().setZero();\n    v0.tail(size-2).setRandom();\n\n    VERIFY_IS_MUCH_SMALLER_THAN(v0.unitOrthogonal().dot(v0), Scalar(1));\n    VERIFY_IS_APPROX(v0.unitOrthogonal().norm(), RealScalar(1));\n  }\n\n  // colwise/rowwise cross product\n  Vector3 vec3 = Vector3::Random();\n  int i = internal::random<int>(0,size-1);\n\n  Matrix3N mat3N(3,size), mcross3N(3,size);\n  mat3N.setRandom();\n  mcross3N = mat3N.colwise().cross(vec3);\n  VERIFY_IS_APPROX(mcross3N.col(i), mat3N.col(i).cross(vec3));\n\n  MatrixN3 matN3(size,3), mcrossN3(size,3);\n  matN3.setRandom();\n  mcrossN3 = matN3.rowwise().cross(vec3);\n  VERIFY_IS_APPROX(mcrossN3.row(i), matN3.row(i).cross(vec3));\n}\n\nvoid test_geo_orthomethods()\n{\n  for(int i = 0; i < g_repeat; i++) {\n    CALL_SUBTEST_1( orthomethods_3<float>() );\n    CALL_SUBTEST_2( orthomethods_3<double>() );\n    CALL_SUBTEST_4( orthomethods_3<std::complex<double> >() );\n    CALL_SUBTEST_1( (orthomethods<float,2>()) );\n    CALL_SUBTEST_2( (orthomethods<double,2>()) );\n    CALL_SUBTEST_1( (orthomethods<float,3>()) );\n    CALL_SUBTEST_2( (orthomethods<double,3>()) );\n    CALL_SUBTEST_3( (orthomethods<float,7>()) );\n    CALL_SUBTEST_4( (orthomethods<std::complex<double>,8>()) );\n    CALL_SUBTEST_5( (orthomethods<float,Dynamic>(36)) );\n    CALL_SUBTEST_6( (orthomethods<double,Dynamic>(35)) );\n  }\n}\n", "meta": {"hexsha": "c836dae40cca7390e07a4619b5e169fed43ef551", "size": 4018, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "thirdparty/instant-meshes/instant-meshes-dust3d/ext/nanogui/ext/eigen/test/geo_orthomethods.cpp", "max_stars_repo_name": "MelvinG24/dust3d", "max_stars_repo_head_hexsha": "c4936fd900a9a48220ebb811dfeaea0effbae3ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2392.0, "max_stars_repo_stars_event_min_datetime": "2016-12-17T14:14:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T19:40:40.000Z", "max_issues_repo_path": "thirdparty/instant-meshes/instant-meshes-dust3d/ext/nanogui/ext/eigen/test/geo_orthomethods.cpp", "max_issues_repo_name": "MelvinG24/dust3d", "max_issues_repo_head_hexsha": "c4936fd900a9a48220ebb811dfeaea0effbae3ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 113.0, "max_issues_repo_issues_event_min_datetime": "2015-07-28T20:31:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-01T15:29:20.000Z", "max_forks_repo_path": "thirdparty/instant-meshes/instant-meshes-dust3d/ext/nanogui/ext/eigen/test/geo_orthomethods.cpp", "max_forks_repo_name": "MelvinG24/dust3d", "max_forks_repo_head_hexsha": "c4936fd900a9a48220ebb811dfeaea0effbae3ee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 184.0, "max_forks_repo_forks_event_min_datetime": "2017-11-15T09:55:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T16:30:46.000Z", "avg_line_length": 32.9344262295, "max_line_length": 80, "alphanum_fraction": 0.6869089099, "num_tokens": 1251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140728, "lm_q2_score": 0.6297746004557471, "lm_q1q2_score": 0.49290094358909126}}
{"text": "#include<stdio.h>\n#include\"mex.h\"\n\n#include<ceres/ceres.h>\nusing namespace std;\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\nstruct NORMAL_COST\n{\n  NORMAL_COST(Eigen::Matrix<double, 1, 3> parent_normal, Eigen::Matrix<double, 1, 3> child_normal):_parent_normal(parent_normal),_child_normal(child_normal){}\n  template <typename T>\n  bool operator()(const T *child_to_parent_q, T *residual)const\n  {\n    // get the transformation from the child_to_parent_q [qw qx qy qz]\n    // Quaternion [w, x, y, z]\n    Eigen::Quaternion<T> child_to_parent_q_(child_to_parent_q[0], child_to_parent_q[1], child_to_parent_q[2], child_to_parent_q[3]);\n    Eigen::Matrix<T, 3, 3> child_to_parent_rotationalMatrix = child_to_parent_q_.toRotationMatrix();\n\n\n    // get the vector from the parent_normal and child_normal [nx ny nz]\n    Eigen::Matrix<T, 3, 1> parent_normal_v(T(_parent_normal(0, 0)), T(_parent_normal(0, 1)), T(_parent_normal(0, 2)));\n\n    Eigen::Matrix<T, 3, 1> child_normal_v(T(_child_normal(0, 0)), T(_child_normal(0, 1)), T(_child_normal(0, 2)));\n\n    Eigen::Matrix<T, 3, 1> _residual_normal_v = child_to_parent_rotationalMatrix * child_normal_v - parent_normal_v;\n\n    residual[0] = _residual_normal_v(0, 0);\n    residual[1] = _residual_normal_v(1, 0);\n    residual[2] = _residual_normal_v(2, 0);\n\n    #ifdef DEBUG\n      mexPrintf(\"child_normal_v: [%f, %f, %f]\\n\", _child_normal(0, 0), _child_normal(0, 1), _child_normal(0, 2));\n      mexPrintf(\"parent_normal_v: [%f, %f, %f]\\n\", _parent_normal(0, 0), _parent_normal(0, 1), _parent_normal(0, 2));\n      mexPrintf(\"child_to_parent_rotationalMatrix: \\n[%f, %f, %f]\\n[%f, %f, %f]\\n[%f, %f, %f]\\n\", \\\n              child_to_parent_rotationalMatrix(0, 0), child_to_parent_rotationalMatrix(0, 1), child_to_parent_rotationalMatrix(0, 2), \\\n              child_to_parent_rotationalMatrix(1, 0), child_to_parent_rotationalMatrix(1, 1), child_to_parent_rotationalMatrix(1, 2), \\\n              child_to_parent_rotationalMatrix(2, 0), child_to_parent_rotationalMatrix(2, 1), child_to_parent_rotationalMatrix(2, 2) \\\n              );\n      mexPrintf(\"residual: [%f, %f, %f]\\n\", residual[0], residual[1], residual[2]);\n    #endif\n    \n    return true;\n  }\n  const Eigen::Matrix<double, 1, 3> _parent_normal, _child_normal;\n};\n\nvoid mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]){\n    // nlhs represent the number of parameters of the output\n    // plhs is a array of the mxarray pointers, each pointing to the output\n    // nrhs represents the number of parameters of the input\n    // prhs is a array of the mxarray pointers, each pointing to the input\n\n    // prhs[0], nx3 double, parent_normal, [nx ny nz]\n    // prhs[1], nx3 double, child_normal, [nx ny nz]\n    // prhs[2], 1x4 double, child_to_parent_q, [qx qy qz qw]\n    // prhs[3], 1x1 double, verbose\n\n    if(nrhs < 4){\n        mexErrMsgIdAndTxt( \"estimatePitchRollByCoNormalCeresMex:invalidNumInputs\", \"at least 4 input arguments required\");\n        return;\n    }\n\n    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n    // get the parent_normals\n    const size_t *dimArrayOfParentNormals = mxGetDimensions(prhs[0]);\n    size_t sizeRowsParentNormals = *(dimArrayOfParentNormals + 0);\n    size_t sizeColsParentNormals = *(dimArrayOfParentNormals + 1);\n\n    if(sizeColsParentNormals != 3){\n        mexErrMsgIdAndTxt( \"estimatePitchRollByCoNormalCeresMex:invalidInputs\", \"the 1st param should be Nx3\");\n        return;\n    }\n\n    double *ptrParentNormals = (double *)(mxGetPr(prhs[0]));\n    std::vector<Eigen::Matrix<double, 1, 3>>parent_normals_all;\n    for(int i = 0; i < sizeRowsParentNormals; i++){\n        Eigen::Matrix<double, 1, 3> current_parent_normal;\n        for(int j = 0; j < 3; j++){\n            current_parent_normal(0, j) = ptrParentNormals[j * sizeRowsParentNormals + i];\n        }\n        parent_normals_all.push_back(current_parent_normal);\n    }\n\n    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n    // get the child_normals\n    const size_t *dimArrayOfChildNormals = mxGetDimensions(prhs[1]);\n    size_t sizeRowsChildNormals = *(dimArrayOfChildNormals + 0);\n    size_t sizeColsChildNormals = *(dimArrayOfChildNormals + 1);\n    if(sizeColsChildNormals != 3){\n        mexErrMsgIdAndTxt( \"estimatePitchRollByCoNormalCeresMex:invalidInputs\", \"the 2st param should be Nx3\");\n        return;\n    }\n\n    double *ptrChildNormals = (double *)(mxGetPr(prhs[1]));\n    std::vector<Eigen::Matrix<double, 1, 3>>child_normals_all;\n    for(int i = 0; i < sizeRowsChildNormals; i++){\n        Eigen::Matrix<double, 1, 3> current_child_normal;\n        for(int j = 0; j < 3; j++){\n            current_child_normal(0, j) = ptrChildNormals[j * sizeRowsChildNormals + i];\n        }\n        child_normals_all.push_back(current_child_normal);\n    }\n\n    if(sizeRowsParentNormals != sizeRowsChildNormals){\n        mexErrMsgIdAndTxt( \"estimatePitchRollByCoNormalCeresMex:invalidInputs\", \"the 1st param and the 2st param should have the same size\");\n        return;\n    }\n\n    #ifdef DEBUG\n        mexPrintf(\"observation number: %d\\n\", sizeRowsParentNormals);\n    #endif\n\n    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n    // get the init_child_to_parent_q\n    double child_to_parent_q[4] = {0};\n    const size_t *dimArrayOfChildToParentQ = mxGetDimensions(prhs[2]);\n    size_t sizeRowsChildToParentQ = *(dimArrayOfChildToParentQ + 0);\n    size_t sizeColsChildToParentQ = *(dimArrayOfChildToParentQ + 1);\n    if(sizeColsChildToParentQ != 4 && sizeRowsChildToParentQ != 1){\n        mexErrMsgIdAndTxt( \"estimatePitchRollByCoNormalCeresMex:invalidInputs\", \"the 3st param should be 1x4\");\n        return;\n    }\n    double *ptrChildToParentQ = (double *)(mxGetPr(prhs[2]));\n    for(int i = 0; i < 4; i++){\n        child_to_parent_q[i] = ptrChildToParentQ[i];\n    }\n\n    #ifdef DEBUG\n        mexPrintf(\"init child_to_parent_q: [%.4f,%.4f,%.4f,%.4f]\\n\", \\\n                    child_to_parent_q[0], \\\n                    child_to_parent_q[1], \\\n                    child_to_parent_q[2], \\\n                    child_to_parent_q[3]);\n    #endif\n\n    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n    // get the verbose\n    bool verbose = false;\n    const size_t *dimArrayOfVerbose = mxGetDimensions(prhs[3]);\n    size_t sizeRowsVerbose = *(dimArrayOfVerbose + 0);\n    size_t sizeColsVerbose = *(dimArrayOfVerbose + 1);\n    if(sizeRowsVerbose != 1 && sizeColsVerbose != 1){\n        mexErrMsgIdAndTxt( \"estimatePitchRollByCoNormalCeresMex:invalidInputs\", \"the 4st param should be 1x1\");\n        return;\n    }\n    double *ptrVerbose = (double *)(mxGetPr(prhs[3]));\n    verbose = bool(ptrVerbose[0]);\n\n    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n    ceres::Problem problem;\n    for(int i=0; i<sizeRowsParentNormals; i++)\n    {\n        problem.AddResidualBlock(\n          new ceres::AutoDiffCostFunction<NORMAL_COST, 3, 4>(\n              new NORMAL_COST(parent_normals_all[i], child_normals_all[i])\n          ),\n          NULL,\n          child_to_parent_q\n        );\n    }\n\n    #ifdef DEBUG\n        mexPrintf(\"AddResidualBlock done!\\n\");\n    #endif\n\n    //\u914d\u7f6e\u6c42\u89e3\u5668\u5e76\u6c42\u89e3\uff0c\u8f93\u51fa\u7ed3\u679c\n    ceres::Solver::Options options;\n    options.linear_solver_type=ceres::DENSE_QR;\n    options.minimizer_progress_to_stdout=verbose;\n    ceres::Solver::Summary summary;\n    ceres::Solve(options,&problem,&summary);\n\n    #ifdef DEBUG\n        mexPrintf(\"estimated child_to_parent_q: [%.4f,%.4f,%.4f,%.4f]\\n\", \\\n                    child_to_parent_q[0], \\\n                    child_to_parent_q[1], \\\n                    child_to_parent_q[2], \\\n                    child_to_parent_q[3]);\n    #endif\n\n    // the output q will be 1x4\n    size_t dimArrayOfParams[2] = { 1, 4 };\n    plhs[0] = mxCreateNumericArray(2, dimArrayOfParams, mxDOUBLE_CLASS, mxREAL);\n    double *out_params = (double *)mxGetData(plhs[0]);\n\n    for(int i = 0; i < 4; i++){\n        out_params[i] = child_to_parent_q[i];\n    }\n}", "meta": {"hexsha": "7b060949d949e1f94ec78a438682660101491712", "size": 8259, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "utils/linefit_ground_segmentation/cpp/estimatePitchRollByCoNormalCeresMex.cpp", "max_stars_repo_name": "ccyinlu/multimodal_data_studio", "max_stars_repo_head_hexsha": "9b76f9033d46a5a812f2ee2babe1526c7d874111", "max_stars_repo_licenses": ["Xnet", "X11"], "max_stars_count": 37.0, "max_stars_repo_stars_event_min_datetime": "2019-03-14T01:18:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T00:07:58.000Z", "max_issues_repo_path": "utils/linefit_ground_segmentation/cpp/estimatePitchRollByCoNormalCeresMex.cpp", "max_issues_repo_name": "yxw027/multimodal_data_studio", "max_issues_repo_head_hexsha": "975f0560e32d810fccb8690a36d157162d7da5ab", "max_issues_repo_licenses": ["Xnet", "X11"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-07-29T08:08:39.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-20T09:25:31.000Z", "max_forks_repo_path": "utils/linefit_ground_segmentation/cpp/estimatePitchRollByCoNormalCeresMex.cpp", "max_forks_repo_name": "yxw027/multimodal_data_studio", "max_forks_repo_head_hexsha": "975f0560e32d810fccb8690a36d157162d7da5ab", "max_forks_repo_licenses": ["Xnet", "X11"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2019-07-16T06:06:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-10T23:53:56.000Z", "avg_line_length": 43.2408376963, "max_line_length": 158, "alphanum_fraction": 0.6104855309, "num_tokens": 2241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972583359805, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4927741849090736}}
{"text": "#include \"itkImage.h\"\n#include \"itkImageFileReader.h\"\n#include \"itkImageFileWriter.h\"\n#include \"vnl/vnl_matrix_ref.h\"\n#include \"vnl/vnl_matrix.h\"\n#include \"itkNumericTraits.h\"\n\n#include \"tkdCmdParser.h\"\n\n#include <iostream>\n#include <utility>\n#include <fstream>\n\n#include <boost/utility.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/graph_utility.hpp>\n#include <boost/graph/betweenness_centrality.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/adjacency_matrix.hpp>\n#include <boost/graph/kruskal_min_spanning_tree.hpp>\n\n/**\n * Minimum spanning tree.\n */\nclass MST\n{\npublic:\n\n\ttypedef double PixelType;\n\n\ttypedef boost::property< boost::vertex_index_t, unsigned int, boost::property< boost::vertex_centrality_t, PixelType > >\n\t\t\tVertexPropertyType;\n\ttypedef boost::property< boost::edge_weight_t, PixelType, boost::property< boost::edge_centrality_t, PixelType > > EdgePropertyType;\n\ttypedef boost::adjacency_matrix< boost::undirectedS, VertexPropertyType, EdgePropertyType > GraphMatrixType;\n\ttypedef boost::adjacency_list< boost::vecS, boost::vecS, boost::undirectedS, boost::no_property, boost::property< boost::edge_weight_t,\n\t\t\tPixelType > > GraphListType;\n\n\ttypedef itk::Image< PixelType, 2 > ImageType;\n\ttypedef itk::ImageFileWriter< ImageType > WriterType;\n\ttypedef vnl_matrix_ref< PixelType > DataMatrixType;\n\ttypedef vnl_vector< PixelType > VectorType;\n\npublic:\n\n\t/**\n\t * Run.\n\t */\n\tvoid Run( const std::string& inputFileName,\n\t\t\tPixelType lowerThreshold, PixelType upperThreshold, const std::string& outputFileName )\n\t{\n\t\tWriterType::Pointer writer = WriterType::New();\n\n\t\twriter->SetFileName( outputFileName.c_str() );\n\t\twriter->SetInput( GetMinimumSpanningTree( inputFileName, lowerThreshold, upperThreshold  ) );\n\n\t\ttry\n\t\t{\n\t\t\twriter->Update();\n\t\t} catch ( itk::ExceptionObject& e )\n\t\t{\n\t\t\tstd::cerr << \"Error writing: \" << outputFileName << std::endl;\n\t\t\tstd::cerr << e.GetDescription() << std::endl;\n\t\t}\n\n\t}\n\nprotected:\n\n\t/**\n\t * Return minimum spanning tree as matrix image.\n\t */\n\tImageType::Pointer GetMinimumSpanningTree( const std::string& filename, PixelType lowerThreshold, PixelType upperThreshold )\n\t{\n\n\t\t//Example();\n\n\t\ttypedef itk::ImageFileReader< ImageType > ReaderType;\n\t\tReaderType::Pointer reader = ReaderType::New();\n\t\treader->SetFileName( filename.c_str() );\n\t\treader->Update();\n\n\t\tImageType::Pointer image = reader->GetOutput();\n\t\treader = 0;\n\n\t\tPixelType* buffer = image->GetPixelContainer()->GetBufferPointer();\n\t\tImageType::RegionType region = image->GetLargestPossibleRegion();\n\t\tImageType::SizeType size = region.GetSize();\n\t\tint rows = size[0];\n\t\tint cols = size[1];\n\n\t\tDataMatrixType data( rows, cols, buffer );\n\n\t\tGraphMatrixType g( rows );\n\n\t\tfor ( int i = 0; i < rows; ++i )\n\t\t{\n\t\t\tfor ( int j = i + 1; j < cols; ++j )\n\t\t\t{\n\t\t\t\tif ( i == j )\n\t\t\t\t{\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tPixelType weight = data( i, j );\n\n\t\t\t\tif ( weight <= upperThreshold && weight > 0 && weight > lowerThreshold )\n\t\t\t\t{\n\t\t\t\t\t// invert weight ( e.g. correlation coefficients ... )\n\t\t\t\t\tboost::add_edge( i, j, EdgePropertyType( 1.0 / weight ), g );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// [ 2 ]: Calculate minimum spanning tree ...\n\n\t\ttypedef boost::graph_traits< GraphMatrixType >::edge_descriptor EdgeType;\n\t\tstd::vector< EdgeType > spanningTree;\n\n\t\t// get spanning tree ...\n\t\tkruskal_minimum_spanning_tree( g, std::back_inserter( spanningTree ) );\n\n\t\tGraphMatrixType spanningTreeGraph();\n\n\t\t// [ 3 ]: Write minimum spanning tree to image ...\n\n\t\tImageType::Pointer output = ImageType::New();\n\t\toutput->CopyInformation( image );\n\t\toutput->SetRegions( image->GetLargestPossibleRegion() );\n\t\toutput->Allocate();\n\t\toutput->FillBuffer( 0 );\n\n\t\tboost::graph_traits< GraphMatrixType >::edge_iterator eiter, eiter_end;\n\t\tfor ( boost::tie( eiter, eiter_end ) = boost::edges( g ); eiter != eiter_end; ++eiter )\n\t\t{\n\t\t\tif ( std::find( spanningTree.begin(), spanningTree.end(), *eiter ) != spanningTree.end() )\n\t\t\t{\n\t\t\t\tPixelType w = boost::get( boost::edge_weight, g, *eiter );\n\n\t\t\t\tImageType::IndexType index;\n\t\t\t\tindex[0] = source( *eiter, g );\n\t\t\t\tindex[1] = target( *eiter, g );\n\t\t\t\toutput->SetPixel( index, w );\n\n\t\t\t\tindex[1] = source( *eiter, g );\n\t\t\t\tindex[0] = target( *eiter, g );\n\t\t\t\toutput->SetPixel( index, w );\n\t\t\t}\n\t\t}\n\t\treturn output;\n\t}\n};\n\n/**\n * Main.\n */\nint main( int argc, char ** argv )\n{\n\ttkd::CmdParser p( \"minimum spanning tree\", \"Calculate minimum spanning tree on undirected graph\" );\n\n\tstd::string inputFileName;\n\tstd::string outputFileName;\n\n\tfloat lowerThreshold = 0;\n\tfloat upperThreshold = 1.0;\n\n\n\tp.AddArgument( inputFileName, \"input\" ) ->AddAlias( \"i\" ) ->SetDescription( \"Input image: 2D undirected adjacency matrix\" ) ->SetRequired( true );\n\n\tp.AddArgument( upperThreshold, \"threshold\" ) ->AddAlias( \"thu\" ) ->AddAlias( \"t\" ) ->SetDescription(\n\t\t\t\"Threshold; only include paths with weight in (0, threshold] (default: 1.0)\" );\n\n\tp.AddArgument( lowerThreshold, \"threshold-lower\" ) ->AddAlias( \"thl\" ) ->SetDescription(\n\t\t\t\"Lower threshold; only include paths with weight > threshold (default: 0)\" );\n\n\tp.AddArgument( outputFileName, \"output\" ) ->AddAlias( \"o\" ) ->SetDescription(\n\t\t\t\"Output image: minimum spanning tree with weights\" ) ->SetRequired( true );\n\n\n\tif ( !p.Parse( argc, argv ) )\n\t{\n\t\tp.PrintUsage( std::cout );\n\t\treturn -1;\n\t}\n\n\tMST mst;\n\tmst.Run( inputFileName, lowerThreshold, upperThreshold, outputFileName );\n\n\treturn EXIT_SUCCESS;\n}\n\n", "meta": {"hexsha": "58754af4bc798630c6b151aa261a9e6831506949", "size": 5414, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/graphs/minimumspanningtree.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/graphs/minimumspanningtree.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/graphs/minimumspanningtree.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": 28.3455497382, "max_line_length": 147, "alphanum_fraction": 0.6904322128, "num_tokens": 1484, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972549785201, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4927741830086888}}
{"text": "#include \"stdafx.h\"\n\n#include \"problem.hpp\"\n#include \"utility.hpp\"\n\n#include <fstream>\n#include <sstream>\n#include <iomanip>\n#include <array>\n#include <functional>\n#include <vector>\n#include <type_traits>\n#include <boost/algorithm/string.hpp>\n\nstruct advent_2017_10 : problem\n{\n\tadvent_2017_10() noexcept : problem(2017, 10) {\n\t}\n\nprotected:\n\tstd::string raw_input;\n\n\tvoid prepare_input(std::ifstream& fin) override {\n\t\tstd::getline(fin, raw_input);\n\t}\n\n\tstd::array<std::size_t, 256> partial_hash(std::size_t iterations, std::vector<std::size_t> input) {\n\t\tstd::array<std::size_t, 256> sparse;\n\t\tstd::iota(std::begin(sparse), std::end(sparse), 0);\n\t\tusing cyclic = utility::cyclic_iterator<std::array<std::size_t, 256>::iterator>;\n\t\tcyclic first = cyclic(std::begin(sparse), std::end(sparse));\n\t\tstd::size_t skip_size = 0;\n\t\twhile(iterations--) {\n\t\t\tfor(const std::size_t length : input) {\n\t\t\t\tstd::reverse(first, first + gsl::narrow<std::ptrdiff_t>(length));\n\t\t\t\tfirst += gsl::narrow<std::ptrdiff_t>(length + skip_size);\n\t\t\t\t++skip_size;\n\t\t\t}\n\t\t}\n\t\treturn sparse;\n\t}\n\n\tstd::string part_1() override {\n\t\tstd::vector<std::string> words;\n\t\tboost::split(words, raw_input, [](char c) { return c == ','; });\n\t\tstd::vector<std::size_t> lengths;\n\t\tstd::transform(std::begin(words), std::end(words), std::back_inserter(lengths), [](const std::string& s) {\n\t\t\treturn std::stoull(s);\n\t\t});\n\n\t\tstd::array<std::size_t, 256> single_round = partial_hash(1, lengths);\n\n\t\tconst std::size_t first_hash = single_round[0] * single_round[1];\n\t\treturn std::to_string(first_hash);\n\t}\n\n\tstd::string part_2() override {\n\t\tstd::vector<std::size_t> lengths;\n\t\tstd::copy(std::begin(raw_input), std::end(raw_input), std::back_inserter(lengths));\n\t\tlengths.insert(lengths.end(), { 17u, 31u, 73u, 47u, 23u });\n\n\t\tstd::array<std::size_t, 256> sparse = partial_hash(64, lengths);\n\n\t\tstd::vector<std::size_t> dense;\n\t\tdense.reserve(16);\n\t\tfor(auto it = std::begin(sparse); it != std::end(sparse); std::advance(it, 16)) {\n\t\t\tdense.push_back(std::accumulate(it, std::next(it, 16), 0ull, std::bit_xor<void>{}));\n\t\t}\n\t\tstd::stringstream res;\n\t\tres << std::hex << std::setfill('0');\n\t\tfor(std::size_t i = 0; i < 16; ++i) {\n\t\t\tres << std::setw(2) << dense[i];\n\t\t}\n\t\treturn res.str();\n\t}\n};\n\nREGISTER_SOLVER(2017, 10);\n", "meta": {"hexsha": "eef704320e7823330084c0bd71639826b9410fde", "size": 2279, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "aoc/src/2017/day-10.cpp", "max_stars_repo_name": "DrPizza/advent-of-code-2017", "max_stars_repo_head_hexsha": "bcba170e3ffececb9c5b29f3b0fa0193fa59dcf9", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-12-09T06:13:08.000Z", "max_stars_repo_stars_event_max_datetime": "2017-12-18T12:15:08.000Z", "max_issues_repo_path": "aoc/src/2017/day-10.cpp", "max_issues_repo_name": "DrPizza/advent-of-code-2017", "max_issues_repo_head_hexsha": "bcba170e3ffececb9c5b29f3b0fa0193fa59dcf9", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-01-03T17:46:56.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-03T17:46:56.000Z", "max_forks_repo_path": "aoc/src/2017/day-10.cpp", "max_forks_repo_name": "DrPizza/advent-of-code", "max_forks_repo_head_hexsha": "bcba170e3ffececb9c5b29f3b0fa0193fa59dcf9", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8481012658, "max_line_length": 108, "alphanum_fraction": 0.66388767, "num_tokens": 694, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.4927481476326507}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n  Matrix3f m;\nm << 1, 2, 3,\n     4, 5, 6,\n     7, 8, 9;\nstd::cout << m;\n\n  return 0;\n}\n", "meta": {"hexsha": "fd885c2447054d1b6a882badffff830102dd7b19", "size": 221, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_Tutorial_commainit_01.cpp", "max_stars_repo_name": "TANHAIYU/Self-calibration-using-Homography-Constraints", "max_stars_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-03-17T16:34:31.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-17T18:30:13.000Z", "max_issues_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_Tutorial_commainit_01.cpp", "max_issues_repo_name": "TANHAIYU/planecalib", "max_issues_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_Tutorial_commainit_01.cpp", "max_forks_repo_name": "TANHAIYU/planecalib", "max_forks_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 12.2777777778, "max_line_length": 22, "alphanum_fraction": 0.5882352941, "num_tokens": 81, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.6477982315512488, "lm_q1q2_score": 0.4927481476326505}}
{"text": "/*\n! Program for 2D explicit finite element analysis of incompressible Navier-Stokes\n!\n!\n! Author: Dr. Chennakesava Kadapa\n! Date  : 17-May-2018\n! Place : Swansea, UK\n!\n!\n*/\n\n\n#include \"headersVTK.h\"\n#include \"headersBasic.h\"\n#include \"headersEigen.h\"\n#include \"elementutilitiescfd.h\"\n#include \"SolutionData.h\"\n#include \"BernsteinElem2DINSTria6Node.h\"\n#include \"BernsteinElem2DINSQuad9Node.h\"\n#include <Eigen/SuperLUSupport>\n\n\nusing namespace std;\n\n\n\nint main(int argc, char* argv[])\n{\n    double tstart, tend;\n\n    int ndim=2, ndof=3, npElem=6;\n    double fact, xNode[50], yNode[50];\n\n    vector<vector<int> > ElemDofArray;\n\n    int  nElem, nNode, nDBC, nFBC;\n    int  ee, ii, jj, kk, ind, count, row, col;\n    int  n1, n2, n3, n4, n5, n6, nsize;\n    int  nn, dof;\n\n    string  infileNodes, infileElems, infileDBCs, infileOutput;\n    string  infileFBCs, charTemp, outFileName;\n\n    //Set file names\n    //The file names are specified as inputs from the command line\n    if(argc == 0)\n    {\n        cerr << \" Error in input data \" << endl;\n        cerr <<  \"Number of input files is not sufficient \" << endl;\n        cerr <<  \"You must enter names of THREE files\" << endl;\n        cerr <<  \"a.) Node file, b.) Element file, and c.) Dirichlet BC file\" << endl;\n        cerr << \"Aborting...\" << endl;\n    }\n    else\n    {\n       infileNodes = argv[1];\n       infileElems = argv[2];\n       infileDBCs  = argv[3];\n\n       //if(argc == 5)\n         //infileFBCs  = argv[3];\n\n       if(argc == 5)\n         infileOutput = argv[4];\n    }\n\n\n    // Read nodal data files\n    /////////////////////////////////////\n\n    std::ifstream  infile_nodes(infileNodes);\n    std::ifstream  infile_elems(infileElems);\n    std::ifstream  infile_DBCs(infileDBCs);\n    std::ifstream  infile_FBCs(infileFBCs);\n\n    if(infile_nodes.fail())\n    {\n       cout << \" Could not open the input nodes file \" << endl;\n       exit(1);\n    }\n\n    double  val[50];\n    int  val2[50];\n\n    std::string line;\n\n    // read nodal coordinates\n    ////////////////////////////////////////////\n\n    cout << \" reading nodes \" << endl;\n\n    nNode = 0;\n    while (std::getline(infile_nodes, line))\n      ++nNode;\n\n    vector<vector<double> >  node_coords(nNode, vector<double>(3));\n\n    infile_nodes.clear();\n    infile_nodes.seekg(0, infile_nodes.beg);\n\n      ii=0;\n      while(infile_nodes >> val[0] >> val[1] >> val[2] )\n      {\n        //printf(\"%12.6f \\t %12.6f \\t %12.6f \\n\", val[0], val[1], val[2]);\n\n        node_coords[ii][0] = val[1];\n        node_coords[ii][1] = val[2];\n        node_coords[ii][2] = 0.0;\n\n        ii++;\n      }\n\n\n    // read elements\n    ////////////////////////////////////////////\n    cout << \" reading elements \" << endl;\n\n    if(infile_elems.fail())\n    {\n       cout << \" Could not open the input elements file \" << endl;\n       exit(1);\n    }\n\n\n    nElem = 0;\n    while (std::getline(infile_elems, line))\n      ++nElem;\n\n    cout << \" nElem   \" << nElem << endl;\n\n    infile_elems.clear();\n    infile_elems.seekg(0, infile_elems.beg);\n\n    vector<vector<int> >  elemNodeConn(nElem, vector<int>(npElem));\n\n    ee=0;\n    if(npElem == 6)\n    {\n      while(infile_elems >> val2[0] >> val2[1] >> val2[2] >> val2[3] >> val2[4] >> val2[5] >> val2[6] >> val2[7] >> val2[8] >> val2[9] )\n      {\n        //printf(\"%6d \\t %6d \\t %6d \\t %6d \\n\", val2[4], val2[5], val2[6], val2[7]);\n\n        for(ii=0; ii<npElem; ii++)\n          elemNodeConn[ee][ii] = val2[4+ii]-1;\n\n        ee++;\n      }\n    }\n    else if(npElem == 9)\n    {\n      while(infile_elems >> val2[0] >> val2[1] >> val2[2] >> val2[3] >> val2[4] >> val2[5] >> val2[6] >> val2[7] >> val2[8] >> val2[9] >> val2[10] >> val2[11] >> val2[12] )\n      {\n        //printf(\"%6d \\t %6d \\t %6d \\t %6d \\n\", val2[4], val2[5], val2[6], val2[7]);\n\n        for(ii=0; ii<npElem; ii++)\n          elemNodeConn[ee][ii] = val2[4+ii]-1;\n\n        ee++;\n      }\n    }\n    else\n    {\n      cerr << \" Invalid npElem \" << npElem << endl;\n      exit(-1);\n    }\n    //\n    // Read Dirichlet BC data\n    //\n    ////////////////////////////////////////////\n    cout << \" reading DBCs \" << endl;\n\n    if(infile_DBCs.fail())\n    {\n       cout << \" Could not open the input elements file \" << endl;\n       exit(1);\n    }\n\n    vector<vector<double> >  DirichletBCs;\n    vector<double>  vecDblTemp(3);\n\n    nDBC = 0;\n    while(infile_DBCs >> val[0] >> val[1] >> val[2] )\n    {\n      vecDblTemp[0] = val[0]-1;\n      vecDblTemp[1] = val[1]-1;\n      vecDblTemp[2] = val[2];\n\n      //if( val[1] <= ndof )\n      //{\n        DirichletBCs.push_back(vecDblTemp);\n        nDBC++;\n      //}\n    }\n\n    cout << \" nDBC  = \" << '\\t' << nDBC << endl;\n\n    infile_nodes.close();\n    infile_elems.close();\n    infile_DBCs.close();\n\n    //\n    // Read Output data\n    //\n    ////////////////////////////////////////////\n\n    vector<int>  OutputData;\n\n    if( !infileOutput.empty() )\n    {\n      std::ifstream  infile_output(infileOutput);\n\n      cout << \" reading output data \" << endl;\n\n      if(infile_output.fail())\n      {\n        cout << \" Could not open the input elements file \" << endl;\n        exit(1);\n      }\n\n      ii = 0;\n      while (std::getline(infile_output, line))\n        ++ii;\n\n      infile_output.clear();\n      infile_output.seekg(0, infile_output.beg);\n\n      OutputData.resize(ii);\n\n      ee=0;\n      while(infile_output >> val[0] )\n      {\n        OutputData[ee] = val[0]-1;\n        ee++;\n      }\n\n      infile_output.close();\n    }\n\n    cout << \" Input files have been read successfully \\n\\n \" << endl;\n\n\n      vector<vector<int> >  midNodeData;\n\n      midNodeData.resize(nNode);\n\n      for(ii=0; ii<nNode; ii++)\n      {\n        midNodeData[ii].resize(3);\n\n        midNodeData[ii][0] = 0;  midNodeData[ii][1] = 0;  midNodeData[ii][2] = 0;\n      }\n\n\n    if(npElem == 6)\n    {\n      for(ee=0; ee<nElem; ee++)\n      {\n        ii = elemNodeConn[ee][3];\n        midNodeData[ii][0] = 1;\n        midNodeData[ii][1] = elemNodeConn[ee][0];\n        midNodeData[ii][2] = elemNodeConn[ee][1];\n\n        ii = elemNodeConn[ee][4];\n        midNodeData[ii][0] = 1;\n        midNodeData[ii][1] = elemNodeConn[ee][1];\n        midNodeData[ii][2] = elemNodeConn[ee][2];\n\n        ii = elemNodeConn[ee][5];\n        midNodeData[ii][0] = 1;\n        midNodeData[ii][1] = elemNodeConn[ee][2];\n        midNodeData[ii][2] = elemNodeConn[ee][0];\n      }\n    }\n    else if(npElem == 9)\n    {\n      for(ee=0; ee<nElem; ee++)\n      {\n        ii = elemNodeConn[ee][4];\n        midNodeData[ii][0] = 1;\n        midNodeData[ii][1] = elemNodeConn[ee][0];\n        midNodeData[ii][2] = elemNodeConn[ee][1];\n\n        ii = elemNodeConn[ee][5];\n        midNodeData[ii][0] = 1;\n        midNodeData[ii][1] = elemNodeConn[ee][1];\n        midNodeData[ii][2] = elemNodeConn[ee][2];\n\n        ii = elemNodeConn[ee][6];\n        midNodeData[ii][0] = 1;\n        midNodeData[ii][1] = elemNodeConn[ee][2];\n        midNodeData[ii][2] = elemNodeConn[ee][3];\n\n        ii = elemNodeConn[ee][7];\n        midNodeData[ii][0] = 1;\n        midNodeData[ii][1] = elemNodeConn[ee][3];\n        midNodeData[ii][2] = elemNodeConn[ee][0];\n      }\n    }\n\n    vector<vector<int> >  ID;\n    vector<vector<bool> >  NodeType;\n    vector<int>  assyForSoln;\n\n    NodeType.resize(nNode);\n\n    ID.resize(nNode);\n\n    for(ii=0;ii<nNode;ii++)\n    {\n      NodeType[ii].resize(ndof);\n      ID[ii].resize(ndof);\n\n      for(jj=0;jj<ndof;jj++)\n      {\n        NodeType[ii][jj] = false;\n        ID[ii][jj] = -1;\n      }\n    }\n\n    // fix the pressure at all the mid nodes\n    for(ii=0; ii<nNode; ii++)\n    {\n      if(midNodeData[ii][0])\n        NodeType[ii][2] = true;\n    }\n\n    if(npElem == 9)\n    {\n      for(ee=0; ee<nElem; ee++)\n      {\n        NodeType[elemNodeConn[ee][8]][2] = true;\n      }\n    }\n\n    // fix the specified Dirichlet BCs\n    for(ii=0; ii<nDBC; ii++)\n    {\n      //cout << ii << '\\t' << DirichletBCs[ii][0] << '\\t' << DirichletBCs[ii][1] << endl;\n      NodeType[DirichletBCs[ii][0]][DirichletBCs[ii][1]] = true;\n    }\n\n    //for(ii=0; ii<totalDOF; ii++)\n      //cout << ii << '\\t' << assyForSoln[ii] << endl;\n\n    int totalDOF = 0;\n    for(ii=0;ii<nNode;ii++)\n    {\n      for(jj=0;jj<ndof;jj++)\n      {\n        //cout << ii << '\\t' << jj << '\\t' << NodeType[ii][jj] << endl;\n        if(!NodeType[ii][jj])\n        {\n          ID[ii][jj] = totalDOF++;\n          assyForSoln.push_back(ii*ndof+jj);\n        }\n      }\n    }\n\n      cout << \" Mesh statistics .....\\n\" << endl;\n      cout << \" nElem          = \" << '\\t' << nElem << endl;\n      cout << \" nNode          = \" << '\\t' << nNode  << endl;\n      cout << \" npElem         = \" << '\\t' << npElem << endl;\n      cout << \" ndof           = \" << '\\t' << ndof << endl;\n      cout << \" Total DOF      = \" << '\\t' << totalDOF << endl;\n\n\n      vector<vector<int> >  LM, forAssyMat;\n\n      LM.resize(nElem);\n\n      for(ee=0;ee<nElem;ee++)\n      {\n        npElem = elemNodeConn[ee].size();\n\n        //printVector(IEN[ee]);\n\n        ind = ndof*npElem;\n        LM[ee].resize(ind);\n\n        for(ii=0;ii<npElem;ii++)\n        {\n          ind = ndof*ii;\n\n          kk = elemNodeConn[ee][ii];\n\n          for(jj=0;jj<ndof;jj++)\n          {\n            LM[ee][ind+jj] = ID[kk][jj];\n          }\n        }\n      }\n\n      printf(\"\\n element DOF values initialised \\n\\n\");\n      printf(\"\\n Preparing matrix pattern \\n\\n\");\n\n      // compute matrix pattern needs to be prepared only for the implicit solver\n\n      forAssyMat.clear();\n      forAssyMat.resize(totalDOF);\n\n      int *tt, r, c;\n\n    for(ee=0;ee<nElem;ee++)\n    {\n      tt = &(LM[ee][0]);\n      nsize = LM[ee].size();\n\n      for(ii=0;ii<nsize;ii++)\n      {\n        r = tt[ii];\n\n        if(r != -1)\n        {\n          for(jj=0;jj<nsize;jj++)\n          {\n            if(tt[jj] != -1)\n            {\n              //printf(\"ii.... %5d \\t %5d \\t %5d \\t %5d \\n\",ii, jj, r, tt[jj]);\n              forAssyMat[r].push_back(tt[jj]);\n            }\n          }\n        }\n      }\n    }\n\n    printf(\"\\n Preparing matrix pattern DONE \\n\\n\");\n\n    VectorXi  nnzVec(totalDOF);\n\n    int nnz = 0;\n    for(ii=0;ii<totalDOF;ii++)\n    {\n      findUnique(forAssyMat[ii]);\n\n      nnzVec[ii] = forAssyMat[ii].size();\n      nnz += nnzVec[ii];\n    }\n    cout << \" nnz \" << nnz << endl;\n\n\n    bool pp1=false;\n    //pp1=true;\n    if(pp1)\n    {\n       printf(\"   Number of non-zeros = %5d \\n\\n\", nnz);\n       printf(\"   dof to dof connectivity ...:  \\n\\n\");\n       for(ii=0;ii<totalDOF;ii++)\n       {\n          cout << \" dof # \" << ii << \" : \";\n          for(jj=0;jj<forAssyMat[ii].size();jj++)\n            cout << '\\t' << forAssyMat[ii][jj];\n          cout << endl;\n       }\n       printf(\"\\n\\n\\n\");\n    }\n\n      /////////////////////////////////////////\n      //\n      // Eigen based solver\n      //\n      /////////////////////////////////////////\n\n      cout << \" Eigen based solver \" << totalDOF << endl;\n\n      //solver->rhsVec.resize(nRow);\n\n      SparseMatrixXd  mtx(totalDOF, totalDOF);\n\n      mtx.reserve(nnz);\n      mtx.reserve(nnzVec);\n\n      for(ii=0;ii<totalDOF;ii++)\n      {\n        for(jj=0;jj<forAssyMat[ii].size();jj++)\n        {\n          mtx.coeffRef(ii, forAssyMat[ii][jj]) = 0.0;\n        }\n      }\n\n      mtx.makeCompressed();\n\n\n////////////////////////////////////////////\n////////////////////////////////////////////\n////////////////////////////////////////////\n\n      VectorXd  pres, presCur, presPrev, presPrev2, presPrev3;\n      VectorXd  presDot, presDotPrev, presDotCur, presDiff;\n      VectorXd  velo, veloCur, veloDiff, veloPrev, veloPrev2, veloPrev3;\n      VectorXd  veloDot, veloDotPrev, acceCur;\n\n      VectorXd  solnApplied, solnVTK, soln, solnCur, solnTemp, rhsVec;\n\n      ind = nNode*ndim;\n\n      velo.resize(ind);\n      velo.setZero();\n\n      veloPrev  = velo;\n      veloCur   = velo;\n      veloPrev2 = velo;\n      veloPrev3 = velo;\n\n      veloDot     = velo;\n      veloDotPrev = veloDot;\n      acceCur  = veloDot;\n\n      pres.resize(nNode);\n      pres.setZero();\n\n      presPrev  = pres;\n      presPrev2 = pres;\n      presPrev3 = pres;\n      presCur   = pres;\n\n      presDot     = velo;\n      presDotPrev = pres;\n      presDotCur  = pres;\n\n\n      soln.resize(nNode*ndof);\n      soln.setZero();\n\n      solnCur = soln;\n      solnApplied = soln;\n\n      solnTemp.resize(totalDOF);\n      solnTemp.setZero();\n\n      rhsVec = solnTemp;\n\n      ////////////////////////////////////////////////\n      // Computations start from here\n      ////////////////////////////////////////////////\n\n      char fname[200];\n      //sprintf(fname,\"(),\"-explicit.dat\");\n\n      ofstream fout(\"convergence-data2.dat\");\n\n      if(fout.fail())\n      {\n        cout << \" Could not open the Output file\" << endl;\n        exit(1);\n      }\n\n      fout.setf(ios::fixed);\n      fout.setf(ios::showpoint);\n      fout.precision(14);\n\n\n      double  xx, yy;\n//\n      // loop over the nodes and adjust nodal coordinates\n      for(nn=0; nn<nNode; nn++)\n      {\n        if( midNodeData[nn][0] )\n        {\n          n1 = midNodeData[nn][1];\n          n2 = midNodeData[nn][2];\n\n          xx = 0.25*node_coords[n1][0] + 0.25*node_coords[n2][0];\n          yy = 0.25*node_coords[n1][1] + 0.25*node_coords[n2][1];\n\n          node_coords[nn][0] = 2.0*(node_coords[nn][0] - xx);\n          node_coords[nn][1] = 2.0*(node_coords[nn][1] - yy);\n        }\n      }\n//\n\n      double  elemData[50], timeData[50];\n      double  norm_rhs=1000.0, norm_pres=1000.0;\n\n      //time integration parameters\n      timeData[1] = 1.0;   timeData[2] = 0.0;\n\n      //density\n      elemData[0] = 1.0;\n      //viscosity\n      //elemData[1] = 1.0;\n      //elemData[1] = 0.025;\n      elemData[1] = 1.0/229.0;\n      //Body force in X-, Y- and Z- direction\n      elemData[2] = 0.0;   elemData[3] = 0.0; elemData[4] = 0.0;\n      //beta\n      elemData[5] = 2.0;\n\n      double  rhoInf;\n      double  am = 1.0;\n      double  gamm = 0.5+am;\n\n      int  stepsMax = 4000000;\n      int  stepsCompleted=0;\n      int  outputFreq = 10;\n      int  fileCount=1;\n\n      double  dt = 0.01;\n      double  timeFact=0.0;\n      double  timeNow=0.0;\n      double  timeFinal = 4000.0;\n      double  num, denom;\n      double  fact1, fact2;\n\n      // create elements and prepare element data\n      BernsteinElem2DINSTria6Node   **elems;\n      //BernsteinElem2DINSQuad9Node   **elems;\n\n      elems = new BernsteinElem2DINSTria6Node* [nElem];\n      //elems = new BernsteinElem2DINSQuad9Node* [nElem];\n\n      for(ee=0;ee<nElem;ee++)\n      {\n        elems[ee] = new BernsteinElem2DINSTria6Node;\n        //elems[ee] = new BernsteinElem2DINSQuad9Node;\n\n        elems[ee]->nodeNums = elemNodeConn[ee];\n\n        //elems[ee]->SolnData = &(SolnData);\n\n        elems[ee]->prepareElemData(node_coords);\n\n        elems[ee]->forAssyVec = LM[ee];\n      }\n\n      cout << \" elements are created and prepated \" << endl;\n      cout << \" Computing the solution \\n\" << endl;\n\n      //SimplicialLDLT<SparseMatrix<double> > solver;\n      SuperLU<SparseMatrixXd > solver;\n\n      ///////////////////////////////////////////////////////////////\n      ///////////////////////////////////////////////////////////////\n      ///////////////////////////////////////////////////////////////\n\n      velo.setZero();      veloPrev.setZero();      veloCur.setZero();\n      veloDot.setZero();      veloDotPrev.setZero();      acceCur.setZero();\n      pres.setZero();      presPrev.setZero();      presCur.setZero();\n      presDot.setZero();   presDotPrev.setZero();   presDotCur.setZero();\n\n      //for(ii=0; ii<nNode_Velo; ii++)\n      //{\n        //veloPrev(ii*2) = 1.0;\n      //}\n\n      //velo = veloPrev;\n\n        //SolnData.applyDirichletBCs(timeFact);\n\n        solnApplied.setZero();\n\n        //Add specified Dirichlet BC\n        for(ii=0; ii<nDBC; ii++)\n        {\n          nn  = DirichletBCs[ii][0];\n          dof = DirichletBCs[ii][1];\n\n          jj = nn*ndof+dof;\n\n          solnApplied(jj) = DirichletBCs[ii][2];\n        }\n\n        //printVector(soln);\n\n        for(ii=0; ii<nDBC; ii++)\n        {\n          nn   = (int) (DirichletBCs[ii][0]);\n          dof  = (int) (DirichletBCs[ii][1]);\n\n          if( midNodeData[nn][0] )\n          {\n            fact = 0.25*solnApplied(midNodeData[nn][1]*ndof+dof) + 0.25*solnApplied(midNodeData[nn][2]*ndof+dof);\n\n            solnApplied[nn*ndof+dof] = 2.0*(solnApplied(nn*ndof+dof) - fact);\n          }\n        }\n        //printVector(solnApplied);\n\n      //Time loop\n      //while( (stepsCompleted < stepsMax ) && (timeNow < timeFinal) )\n\n      vector<int>  vecTempInt;\n\n      ind = npElem*ndof;\n\n      VectorXd  Flocal(ind);\n      MatrixXd  Klocal(ind, ind);\n\n      int iter=0, loadIncr;\n\n      soln.setZero();\n\n      for(loadIncr=0; loadIncr<10; loadIncr++)\n      {\n        //timeFact = 0.5*(1-cos(PI*stepsCompleted/2000));\n        timeFact = 0.1*(loadIncr+1);\n\n        for(ii=0; ii<nDBC; ii++)\n        {\n          nn   = (int) (DirichletBCs[ii][0]);\n          dof  = (int) (DirichletBCs[ii][1]);\n\n          jj = nn*ndof + dof;\n\n          soln[jj] = timeFact*solnApplied(jj);\n        }\n\n        //cout << \" aaaaaaaaaaa \" << endl;\n\n      for(iter=0; iter<20; iter++)\n      {\n        //Loop over elements and compute the RHS\n\n        mtx *= 0.0;\n        rhsVec.setZero();\n\n        for(ee=0; ee<nElem; ee++)\n        {\n            fact = timeNow - dt;\n\n            //Compute the element force vector, including residual force\n            elems[ee]->StiffnessAndResidual(node_coords, elemData, timeData, soln, Klocal, Flocal, fact);\n\n            vecTempInt = elems[ee]->forAssyVec;\n            ind = vecTempInt.size();\n\n            //Assemble the element vector\n            for(ii=0; ii<ind; ii++)\n            {\n              r = vecTempInt[ii];\n              if( r != -1)\n              {\n                rhsVec(r)  += Flocal(ii);\n\n                for(jj=0; jj<ind; jj++)\n                {\n                  c = vecTempInt[jj];\n                  if( c != -1)\n                  {\n                    mtx.coeffRef(r, c)  += Klocal(ii, jj);\n                  }\n                }\n              }\n            }\n        } //LoopElem\n\n        // Add specified nodal force \n        //SolnData.addNodalForces(timeFact);\n\n        norm_rhs = rhsVec.norm();\n\n        cout << \" RHS norm = \" << norm_rhs << endl;\n\n        if(norm_rhs < 1.0e-8)\n        {\n          cout << \" Solution converged below the specified tolerance \" << endl;\n          break;\n        }\n        else\n        {\n          solver.compute(mtx);\n\n          solnTemp = solver.solve(rhsVec);\n\n          for(ii=0; ii<totalDOF; ii++)\n          {\n            soln(assyForSoln[ii]) += solnTemp(ii);\n          }\n\n          //printVector(soln);\n        }\n      } // iteration loop\n\n          // write the solution to the VTK file\n\n          velo.resize(nNode*3);\n          velo.setZero();\n          pres.setZero();\n\n          /*\n          for(ii=0; ii<nNode; ii++)\n          {\n            n1 = ii*2;\n            n2 = ii*3;\n\n            velo(n1)   = soln(n2);\n            velo(n1+1) = soln(n2+1);\n\n            pres(ii)   = soln(n2+2);\n\n            //pres(ii)   = soln(ii);\n          }\n\n          for(ii=0; ii<nNode; ii++)\n          {\n            if(midNodeData[ii][0])\n            {\n              jj = ii*2;\n              n1 = midNodeData[ii][1]*2;\n              n2 = midNodeData[ii][2]*2;\n\n              velo(jj)    = 0.5*velo(jj)   + 0.25*velo(n1)   + 0.25*velo(n2);\n              velo(jj+1)  = 0.5*velo(jj+1) + 0.25*velo(n1+1) + 0.25*velo(n2+1);\n\n              pres(ii)    = 0.5*(pres(midNodeData[ii][1]) + pres(midNodeData[ii][2]) );\n            }\n          }\n          */\n\n          //writevtk(ndim, node_coords, elemNodeConn, midNodeData, soln, fileCount);\n\n          fileCount = fileCount+1;\n\n          //fact1 = 0.0;\n          //fact2 = 0.0;\n          //for(ii=0; ii<OutputData.size(); ii++)\n          //{\n            //jj = OutputData[ii]*2;\n\n            //fact1 += rhsVec(jj);\n            //fact2 += rhsVec(jj+1);\n          //}\n\n          //fout << timeNow << '\\t' << stepsCompleted << '\\t' << norm_rhs << '\\t' << norm_pres ;\n          //fout << '\\t' << fact1 << '\\t' << fact2 << endl;\n\n\n        // store the variables\n        //SolnData.timeUpdate();\n        veloPrev3  = veloPrev2;\n        veloPrev2  = veloPrev;\n        veloPrev   = velo;\n\n        veloDotPrev  = veloDot;\n\n        presPrev3  = presPrev2;\n        presPrev2  = presPrev;\n        presPrev   = pres;\n        presDotPrev  = presDot;\n\n      } //Time loop\n\n    //\n    cout << \" Computing errors \\n \" << endl;\n    double totalError = 0.0;\n    //cout << \" index = \" << index << endl;\n    for(int index=0; index<4; index++)\n    {\n      totalError = 0.0;\n      for(ee=0; ee<nElem; ee++)\n      {\n        //Compute the element force vector, including residual force\n        totalError += elems[ee]->CalculateError(node_coords, elemData, timeData, soln, veloDot, pres, timeNow, index);\n      }\n\n      totalError = sqrt(totalError);\n\n      if(index == 0)\n        printf(\" \\n\\n \\t L2 Error in X-velocity = %12.6E \\n\\n \" , totalError);\n      else if(index == 1)\n        printf(\" \\n\\n \\t L2 Error in Y-velocity = %12.6E \\n\\n \" , totalError);\n      else if(index == 2)\n        printf(\" \\n\\n \\t L2 Error in pressure   = %12.6E \\n\\n \" , totalError);\n      else\n        printf(\" \\n\\n \\t H1 Error in velocity   = %12.6E \\n\\n \" , totalError);\n    }\n    //\n\n    //tend = MPI_Wtime()\n    //write(*,*) \"That took \", (tend-tstart), \"seconds\"\n\n    if(elems != NULL)\n    {\n      for(ii=0;ii<nElem;ii++)\n        delete elems[ii];\n\n      delete [] elems;\n      elems = NULL;\n    }\n\n    cout << \" Program is successful \\n \" << endl;\n\n    return 1;\n}\n\n\n\n\n\n\n\n", "meta": {"hexsha": "7acf4d2b2ae7d6c051f2a8d893eeec70272553e8", "size": 21500, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/incimplicit.cpp", "max_stars_repo_name": "M4rkD/XCFD", "max_stars_repo_head_hexsha": "e4b6156a8823cbe0771c44df16539e7491e9fe11", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-28T18:06:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-28T18:06:34.000Z", "max_issues_repo_path": "src/incimplicit.cpp", "max_issues_repo_name": "M4rkD/XCFD", "max_issues_repo_head_hexsha": "e4b6156a8823cbe0771c44df16539e7491e9fe11", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2019-08-09T13:01:03.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-09T14:57:53.000Z", "max_forks_repo_path": "src/incimplicit.cpp", "max_forks_repo_name": "M4rkD/XCFD", "max_forks_repo_head_hexsha": "e4b6156a8823cbe0771c44df16539e7491e9fe11", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-07-29T14:01:48.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-18T17:10:03.000Z", "avg_line_length": 24.1301907969, "max_line_length": 172, "alphanum_fraction": 0.4809767442, "num_tokens": 6507, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.49274813728845707}}
{"text": "/**\n *  @file eigen_isnan.cpp\n *  @author Maximilian Harr <maximilian.harr@daimler.com>\n *  @date 29.06.2017\n *\n *  @brief Check if matrix has nan values\n *\n *\n *\n *          Coding Standard:\n *          wiki.ros.org/CppStyleGuide\n *          https://google.github.io/styleguide/cppguide.html\n *\n *\n *  @bug\n *\n *\n *  @todo\n *\n *\n */\n\n// PRAGMA\n\n// SYSTEM INCLUDES\n#include <Eigen/Core>\n#include <iostream>\n\n// PROJECT INCLUDES\n\n// LOCAL INCLUDES\n\n// FORWARD REFERENCES\n\n// FUNCTION PROTOTYPES\n\n// GLOBAL VARIABLES\n\nusing namespace Eigen;\nusing namespace std;\n\n\n//// MAIN //////////////////////////////////////////////////////////////////////////////////////////\nint main(int argc, char* argv[])\n{  \n\tEigen::Matrix3d v;\n\tv << 0, 1, 2, 3, 4, 5, 6, 7, 8;\n\n\tif( !isnan(v.array()).isZero(0) || !isinf(v.array()).isZero(0) ){\n\t\tstd::cout << \"Matrix has a nan/inf value.\" << std::endl;\n\t}\n\telse{\n\t\tstd::cout << \"Matrix has no nan/inf value.\" << std::endl;\n\t}\n\tv(0,0) *= 0.0/0.0;\n\tv(1,1) /= 0.0;\n\tstd::cout << v << std::endl << std::endl;\n\tstd::cout << \"isinf:\" << std::endl << Eigen::isinf(v.array()) << std::endl;\n\tstd::cout << \"isnan:\" << std::endl << Eigen::isnan(v.array()) << std::endl;\n\tif( !isnan(v.array()).isZero(0) ){\n\t\tstd::cout << \"Matrix has a nan/inf value.\" << std::endl;\n\t}\n\telse{\n\t\tstd::cout << \"Matrix has no nan/inf value.\" << std::endl;\n\t}\n\n}\n\n\n//// FUNCTION DEFINITIONS //////////////////////////////////////////////////////////////////////////\n\n\n", "meta": {"hexsha": "93ca8e555a35b00a1fbb2a957f5adc1e59cfe3ca", "size": 1462, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/cpp_libs/src/eigen_isnan.cpp", "max_stars_repo_name": "maximilianharr/code_snippets", "max_stars_repo_head_hexsha": "8b271e6fa9174e24200e88be59e417abd5f2f59a", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/cpp_libs/src/eigen_isnan.cpp", "max_issues_repo_name": "maximilianharr/code_snippets", "max_issues_repo_head_hexsha": "8b271e6fa9174e24200e88be59e417abd5f2f59a", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/cpp_libs/src/eigen_isnan.cpp", "max_forks_repo_name": "maximilianharr/code_snippets", "max_forks_repo_head_hexsha": "8b271e6fa9174e24200e88be59e417abd5f2f59a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.0273972603, "max_line_length": 100, "alphanum_fraction": 0.5123119015, "num_tokens": 428, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.49274813728845707}}
{"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/filter_view_pairs_from_orientation.h\"\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <glog/logging.h>\n#include <unordered_map>\n#include <unordered_set>\n\n#include \"theia/math/rotation.h\"\n#include \"theia/math/util.h\"\n#include \"theia/util/hash.h\"\n#include \"theia/util/map_util.h\"\n#include \"theia/sfm/twoview_info.h\"\n#include \"theia/sfm/types.h\"\n#include \"theia/sfm/view_graph/view_graph.h\"\n\nnamespace theia {\n\nnamespace {\n\nbool AngularDifferenceIsAcceptable(\n    const Eigen::Vector3d& orientation1,\n    const Eigen::Vector3d& orientation2,\n    const Eigen::Vector3d& relative_orientation,\n    const double sq_max_relative_rotation_difference_radians) {\n  const Eigen::Vector3d composed_relative_rotation =\n      MultiplyRotations(orientation2, -orientation1);\n  const Eigen::Vector3d loop_rotation =\n      MultiplyRotations(-relative_orientation, composed_relative_rotation);\n  const double sq_rotation_angular_difference_radians =\n      loop_rotation.squaredNorm();\n  return sq_rotation_angular_difference_radians <=\n         sq_max_relative_rotation_difference_radians;\n}\n\n}  // namespace\n\nvoid FilterViewPairsFromOrientation(\n    const std::unordered_map<ViewId, Eigen::Vector3d>& orientations,\n    const double max_relative_rotation_difference_degrees,\n    ViewGraph* view_graph) {\n  CHECK_NOTNULL(view_graph);\n  CHECK_GE(max_relative_rotation_difference_degrees, 0.0);\n\n  // Precompute the squared threshold in radians.\n  const double max_relative_rotation_difference_radians =\n      DegToRad(max_relative_rotation_difference_degrees);\n  const double sq_max_relative_rotation_difference_radians =\n      max_relative_rotation_difference_radians *\n      max_relative_rotation_difference_radians;\n\n  std::unordered_set<ViewIdPair> view_pairs_to_remove;\n  const auto& view_pairs = view_graph->GetAllEdges();\n  for (const auto& view_pair : view_pairs) {\n    const Eigen::Vector3d* orientation1 =\n        FindOrNull(orientations, view_pair.first.first);\n    const Eigen::Vector3d* orientation2 =\n        FindOrNull(orientations, view_pair.first.second);\n\n    // If the view pair contains a view that does not have an orientation then\n    // remove it.\n    if (orientation1 == nullptr || orientation2 == nullptr) {\n      LOG(WARNING)\n          << \"View pair (\" << view_pair.first.first << \", \"\n          << view_pair.first.second\n          << \") contains a view that does not exist! Removing the view pair.\";\n      view_pairs_to_remove.insert(view_pair.first);\n      continue;\n    }\n\n    // Remove the view pair if the relative rotation estimate is not within the\n    // tolerance.\n    if (!AngularDifferenceIsAcceptable(\n            *orientation1,\n            *orientation2,\n            view_pair.second.rotation_2,\n            sq_max_relative_rotation_difference_radians)) {\n      view_pairs_to_remove.insert(view_pair.first);\n    }\n  }\n\n  // Remove all the \"bad\" relative poses.\n  for (const ViewIdPair view_id_pair : view_pairs_to_remove) {\n    view_graph->RemoveEdge(view_id_pair.first, view_id_pair.second);\n  }\n  VLOG(1) << \"Removed \" << view_pairs_to_remove.size()\n          << \" view pairs by rotation filtering.\";\n}\n\n}  // namespace theia\n", "meta": {"hexsha": "bbd7ae3c74a4ad1a419dc8d01dc59b384d2ebd8c", "size": 4975, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/sfm/filter_view_pairs_from_orientation.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": "src/theia/sfm/filter_view_pairs_from_orientation.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": "src/theia/sfm/filter_view_pairs_from_orientation.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": 39.8, "max_line_length": 79, "alphanum_fraction": 0.7419095477, "num_tokens": 1070, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.49274813728845696}}
{"text": "#include \"ConnectFour.hpp\"\n#include \"Graph.hpp\"\n\n#include <set>\n#include <fstream>\n#include <boost/timer/timer.hpp>\n#include <boost/range/adaptor/reversed.hpp>\n\n#include <boost/serialization/vector.hpp>\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/archive/text_iarchive.hpp>\n\n#include <boost/variant.hpp>\n\n/*\n        We can solve connect as follows. First to comprehand the computational\n        complexity, note that for every square on a 7x6 board we can have\n        either {empty,hero,villian}. This means the number of boards is\n        bounded above by 3^{6*7} < 2^66, and I observe about\n        2.1^n number.\n                All in all, this means that we can't simply let my computer\n        solve as it won't fit in memory (I need to store the result\n        somehow, because of the way boards are constructed I would \n        be recomputing the same board from different paths). \n                The way solve solve this computation problem, is to first\n        work forwards, creating a database of boards, starting from\n        an empty board db_0, and then iterativley produce \n                        db_{i+1} = f(db_i),\n        untill we reach the end of the game tree. One we have the set\n                        DB = {db_i},\n        we then create another database\n                        s_i = f(db_i, s_{i+1}),\n        where s_i as a database, evaulating each configuration. This\n        iterative step.\n\n        The algebra for evaluating the result database, is as follows.\n        For each board b, where we have i moves, if b is a terminal\n        board, we assign r(b) one of {Win,Lose,Draw} depending on the\n        evaulation, and we are done.\n                If b is a non-terminal, we then take the set all \n\n\n\n\n        \n\n\n */\n\nvoid Driver0(){\n        //BoardInputOutput io;\n        //auto board = io.ParseBoard(6,5,\"      \"\n                                       //\"      \"\n                                       //\"      \"\n                                       //\"      \"\n                                       //\"      \");\n        //auto root = GenerateGameTree(board.get());\n        auto root = GenerateGameTree();\n        NodeMarker marker;\n        marker.Run(root);\n\n        PRINT( marker.Lookup(root.GetStart() ) );\n        Profiler prof;\n        prof.Run(root);\n\n\n}\n\n\n/*\n        This represents the level of the board,\n        ie for \n                (width,height,n)\n                \n                (7,6,0) => P =  {(0,0,0,0,0,0,0)}\n                (7,6,1) => P =  {(1,0,0,0,0,0,0),\n                                 (0,1,0,0,0,0,0),\n                                 (0,1,1,0,0,0,0),\n                                 ...\n                                 }\n                (7,6,2) => P =  {(1,0,0,0,0,0,0),\n                                 (0,1,0,0,0,0,0),\n                                 (0,1,1,0,0,0,0),\n                                 ...\n                                 }\n */\n\ntemplate<class T>\nstd::string tostring(T const& iter){\n        std::stringstream sstr;\n        sstr << \"{\";\n        bool first = false;\n        for( auto const& _ : iter){\n                sstr\n                        << ( first ? (first=false,\"\") : \", \")\n                        << (int)_;\n        }\n        sstr << \"}\";\n        return sstr.str();\n}\n\nstruct LevelCombinationSet{\n        using CombinationType = std::vector<char>;\n\n        explicit LevelCombinationSet(char width, char height, char n)\n                :width_{width}\n                ,height_{height}\n        {\n                CombinationType iter(width, 0 );\n                Recurse_( iter, n );\n                #if 0\n                char tmp = n; \n                for(auto& _ : iter){\n                        _ = std::min(height, tmp);\n                        tmp -= _;\n                        if( _ == 0 )\n                                break;\n                }\n                #endif\n\n        }\n        auto begin()const{ return set_.begin(); }\n        auto end()const{ return set_.end(); }\nprivate:\n        void Recurse_( std::vector<char> proto, char n ){\n                if( n == 0 ){\n                        set_.insert(std::move(proto));\n                        return;\n                }\n                for(size_t i=0;i!=proto.size();++i){\n                        if( ! (proto[i] < height_ ) )\n                                continue;\n                        auto next = proto;\n                        ++next[i];\n                        Recurse_(std::move(next), n-1);\n                }\n        }\n        char width_;\n        char height_;\n        std::set<CombinationType> set_;\n};\n\nstd::string Bits(unsigned long long val){\n        std::bitset<sizeof(val)*8> aux{val};\n        return aux.to_string();\n}\n\nvoid PermuattionTest(){\n\n        #if 0\n        for(int k=0;;++k){\n                boost::timer::auto_cpu_timer at;\n                std::vector<int> proto(7*6, 0);\n                for(int i=0;i!=k;++i)\n                        proto[proto.size()-1-i] = 1;\n                for(;;){\n                        if( ! std::next_permutation(proto.begin(), proto.end()))\n                                break;\n                }\n                PRINT(k);\n                std::cout << \"--------------\\n\";\n        }\n        #endif\n        unsigned long long upper = 1;\n        for(int i=0;i!=6*7;++i)\n                upper *= 2;\n        for(int k=0;;++k){\n                boost::timer::auto_cpu_timer at;\n                unsigned long long iter = 0;\n                int n = 0;\n                PRINT_SEQ((k)(iter)(upper));\n                for(;iter < upper;++iter){\n                        if( __builtin_popcountll(iter) == k ){\n                                PRINT_SEQ( (Bits(iter))(__builtin_popcountll(iter)) );\n                                ++n;\n                        }\n                }\n                PRINT_SEQ((upper)(k)(n));\n        }\n\n        #if 0\n        LevelCombinationSet ps(7,6,10);\n        for( auto const& _ : ps )\n                PRINT( tostring(_));\n                #endif\n        /*\n                want sequence\n                        s1 .. sn\n                where there are only K sn for sn = Empty.\n                This imples can take sequence\n                        t1 ... tm  where m = n -k\n                where ti \\in {Hero, Villian},\n                        and take \n                        q1 .. qk\n                are index positions for inset the Empy ones\n\n         */\n\n\n}\n\nstruct SubGraph{\n        void Push(Node* ptr){\n                start_.push_back(ptr);\n        }\n        auto begin()const{ return start_.begin(); }\n        auto end()const{ return start_.end(); }\n        void Debug()const{\n                PRINT( start_.size() );\n                #if 0\n                for( auto ptr : start_){\n                        ptr->Ctx().Display();\n                }\n                #endif\n        }\nprivate:\n        std::vector<Node*> start_;\n};\n\nstruct Graph{\n        void Push(SubGraph* sub){\n                subs_.push_back(sub);\n        }\n        auto begin()const{ return subs_.begin(); }\n        auto end()const{ return subs_.end(); }\n        auto begin(){ return subs_.begin(); }\n        auto end(){ return subs_.end(); }\n        auto Back(){  return subs_.back(); }\n        // Assume first one only have one entry\n        auto Start(){ return *subs_.front()->begin(); }\n        auto At(size_t idx)const{ return subs_[idx]; }\n        auto Size()const{ return subs_.size(); }\nprivate:\n        // increasing popcount\n        std::vector<SubGraph*> subs_;\n};\n\n#include <boost/pool/object_pool.hpp>\n\n/*\n        The essence of the problem is that I can't easily work backwards\n        in this game. This is because I can't git the game tree\n        with depth of 42 into memory. I also have to keep results in \n        memory, because otherwise I'll be re-computing the result\n        for a certain board for each path from it.\n                What I need to do is create auxiallary sets of all the\n        board at each depth. From this, I can work backwards.\n\n*/\n\n#if 0\nstruct BoardAllocator{\n        using hash_t = decltype(std::declval<Board>().Hash());\n        // (was_allocated, ptr)\n        std::pair<bool, Board*> FindOrAllocate(Board const& brd){\n                auto h = brd.Hash();\n                auto iter = nodes_.find(h);\n                if( iter == nodes_.end()){\n                        auto tmp = pool_.construct(brd);\n                        nodes_.emplace(h, tmp);\n                        return std::make_pair(true, tmp);\n                }\n                return std::make_pair(false, iter->second);\n        }\nprivate:\n        boost::object_pool<Board> pool_;\n        std::map<hash_t, Board*> nodes_;\n};\n\nSubGraph* CreateSubGraph(BoardAllocator& alloc, SubGraph const& entry){\n        ConnectFourLogic logic;\n\n        SubGraph* result = new SubGraph;\n\n        for( auto node : entry){\n                auto const& ctx{node->Ctx()};\n\n                // try to place a tile\n                for( unsigned x=0;x!=ctx.BoardWidth();++x){\n                        if( ! CanPlace( ctx.GetBoard(), x) ){\n                                continue;\n                        }\n                        GameContext nextCtx{ctx};\n                        nextCtx.Place(logic, x);\n\n                        //nextCtx.Display();\n\n\n                        auto ret = alloc.FindOrAllocate(nextCtx);\n                        if( ret.first) {\n                                result->Push(ret.second);\n                        }\n\n                        node->AddEdge( x, ret.second );\n                }\n        }\n        \n        return result;\n}\nint main(){\n\n        Graph graph;\n        SubGraph* start = new SubGraph;\n        start->Push( new Node{GameContext{}} );\n        //start->Push( alloc.FindOrAllocate(GameContext{}).second );\n        graph.Push(start);\n\n        std::vector< std::unique_ptr<BoardAllocator> > alloc;\n\n        for(int i=0;;++i){\n                //if( alloc.size())\n                        //alloc.back().reset();\n                alloc.emplace_back( std::make_unique<BoardAllocator>() );\n                boost::timer::auto_cpu_timer at;\n                graph.Back()->Debug();\n\n                auto next = CreateSubGraph(*alloc.back(), *graph.Back() );\n\n                graph.Push(next);\n                //if( i == 10 )\n                        //break;\n                PRINT(i);\n\n                if( alloc.size() >= 3 ){\n                        alloc[alloc.size()-2].reset();\n                        delete graph.At(alloc.size()-2);\n                }\n                PRINT( sizeof(Node) );\n        }\n\n\n}\n#endif\n\ntemplate<class BoardType>\nstruct FileBackedBoardSet{\nprivate:\n        std::vector<BoardType> boards_;\n};\n\ntemplate<class BoardType>\nstruct LevelGroup{\n        using HashType = decltype(std::declval<BoardType>().Hash());\n        LevelGroup():player_{Player_NotAPlayer}{}\n        template<class IterType>\n        LevelGroup(Player p, IterType first, IterType last)\n                :player_{p}\n                ,boards_{first,last}\n        {\n                std::sort(boards_.begin(), boards_.end());\n        }\n        auto GetPlayer()const{ return player_; }\n        BoardType const& Find(HashType const& hash)const{\n                auto iter = std::lower_bound( boards_.begin(),\n                                              boards_.end(),\n                                              hash );\n                if( iter->Hash() == hash )\n                        return *iter;\n                throw std::domain_error(\"hash doesn't exist\");\n        }\n        auto begin()const{ return boards_.begin(); }\n        auto end()const{ return boards_.end(); }\n        auto Size()const{ return boards_.size(); }\n        auto const& operator[](size_t idx)const{\n                return boards_.at(idx);\n        }\nprivate:\n        friend class boost::serialization::access;\n\n        template <typename Archive>\n        void serialize(Archive &ar, const unsigned int version){\n                ar & player_;\n                ar & boards_;\n        }\nprivate:\n        Player player_;\n        std::vector<BoardType> boards_;\n};\n\n\n#if 0\ntemplate<class BoardType>\nstruct LevelGroupProducer{\n        using LevelGroupType = LevelGroup<BoardType>;\n        virtual ~LevelGroupProducer()=default;\n\n        virtual\n        std::unique_ptr<LevelGroupType> ProduceNextInSequence(LevelGroupType const& prev)const=0;\n};\n\ntemplate<class BoardType>\nstruct LevelGroupProducerFactory{\n        using LevelGroupProducerType = LevelGroupProducer<BoardType>;\n        std::unique_ptr<LevelGroupProducerType> MakeForLevel(int level)const=0;\n};\n#endif\n\n\n\n/*\n        G0 -> G1 -> G2\n\n        G1 = Generate(G0)\n        G2 = Generate(G1)\n        ...\n\n\n        Because a single group is too large to have in memory\n */\ntemplate<class BoardType>\nstruct Group\n{\n        using LevelType = LevelGroup<BoardType>;\n\n        struct MemoryManager{\n                MemoryManager(std::string filename,\n                              std::unique_ptr<LevelType> ptr):\n                        filename_{std::move(filename)},\n                        ptr_{std::move(ptr)}\n                {\n                        //PRINT(filename_);\n                }\n                void Close(){\n                        //std::cerr << \"Closing \" << filename_ << \"\\n\";\n                        ptr_.reset();\n                }\n                bool Load(){\n                        if( !! ptr_.get() )\n                                return false;\n                        //std::cerr << \"Loading \" << filename_ << \"\\n\";\n                        std::ifstream ifs(filename_);\n                        if( ! ifs.is_open()){\n                                std::cerr << \"Unable to open \" << filename_ << \"\\n\";\n                                return false;\n                        }\n                        boost::archive::text_iarchive ia{ifs};\n                        ptr_.reset(new LevelType{});\n                        ia >> *ptr_;\n                        return true;\n                }\n                bool Save()const{\n                        //std::cerr << \"Saving \" << filename_ << \"\\n\";\n                        if( ! ptr_.get() ){\n                                std::cerr << \"Nothing to save\\n\";\n                                return false;\n                        }\n                        std::ofstream of(filename_);\n                        if( ! of.is_open()){\n                                std::cerr << \"Unable to open \" << filename_ << \"\\n\";\n                                return false;\n                        }\n                        boost::archive::text_oarchive oa{of};\n                        oa << *ptr_;\n                        return true;\n                }\n                LevelType const* operator->(){\n                        // Autoload\n                        Load();\n                        return ptr_.get();\n                }\n                LevelType const& operator*(){\n                        // Autoload\n                        Load();\n                        return *ptr_;\n                }\n        private:\n                std::string filename_;\n                mutable std::unique_ptr<LevelType> ptr_;\n        };\n\n        auto& DeclSubGroup(std::string const& filename, std::unique_ptr<LevelType> ptr){\n                groups_.emplace_back(filename, std::move(ptr));\n                return groups_.back();\n        }\n        auto Size()const{ return groups_.size(); }\n        auto& operator[](size_t idx){\n                return groups_.at(idx);\n        }\n\nprivate:\n        mutable std::vector<MemoryManager> groups_;\n};\n\nvoid Driver2(){\n        using BoardType = GenericBoard<7,6>;\n        //using BoardType = GenericBoard<4,4>;\n        ConnectFourLogic logic;\n        BoardInputOutput io;\n\n        std::vector<Player> p;\n        std::vector< std::set< BoardType > > b;\n\n        p.emplace_back(Player_Hero);\n        b.emplace_back();\n        b.back().emplace();\n\n        Group<BoardType> group;\n\n        int level=0;\n\n        auto namebroker = [](int lvl){\n                std::stringstream sstr;\n                sstr << BoardType::Width() << \"x\" << BoardType::Height() << \"Depth\" << lvl << \".bin\";\n                return sstr.str();\n        };\n\n        auto& firstSub = group.DeclSubGroup(namebroker(level++), std::make_unique<LevelGroup<BoardType> >(p.back(), b.back().begin(), b.back().end() ));\n        firstSub.Save();\n\n        for(;;){\n                boost::timer::auto_cpu_timer at;\n\n\n                p.emplace_back( NextPlayer(p.back()));\n                b.emplace_back();\n\n                auto width = b.back().begin()->Width();\n                auto height = b.back().begin()->Height();\n\n                auto t = TileForPlayer(NextPlayer(p.back()));\n\n\n                for( auto const& board : b[b.size()-2]){\n\n                        auto e = logic.Evaluate(board);\n                        if( e != Eval_NotFinished )\n                                continue;\n\n                        for( unsigned x=0;x!=width;++x){\n                                auto level = Level(board, x);\n                                if( level == height )\n                                        continue;\n                                BoardType next(board);\n                                next.Set(x, level, t);\n\n                                b.back().emplace(next);\n\n                                //io.Display(next);\n                                //std::stringstream sstr;\n                                //sstr \n                                        //<< io.ToString(board) << \" => \"\n                                        //<< io.ToString(next);\n                                //std::cout << sstr.str() << \"\\n\";\n                        }\n                }\n\n\n\n                if( b.back().size() == 0 ){\n                        p.pop_back();\n                        b.pop_back();\n                        break;\n                }\n        \n                auto& sub = group.DeclSubGroup(namebroker(level++), std::make_unique<LevelGroup<BoardType> >(p.back(), b.back().begin(), b.back().end() ));\n                sub.Save();\n\n                if( group.Size() > 2 ){\n                        group[group.Size()-2].Close();\n                }\n                \n                \n                PRINT(level);\n                PRINT(b.back().size());\n                io.Display(*b.back().begin());\n                PRINT(EvalToString(logic.Evaluate(*b.back().begin())));\n        }\n\n        std::vector<\n                std::map<\n                        decltype( std::declval<BoardType>().Hash() ),\n                        int\n                >\n        > m(b.size());\n\n        auto marking_lt = [](auto left, auto right){\n                static std::map<int, int> order = [](){\n                        int precedence[] = {\n                                Marked_Win,\n                                Marked_Win  | Marked_Draw,\n                                Marked_Draw,\n                                Marked_Win  | Marked_Draw | Marked_Lose,\n                                Marked_Win  | Marked_Lose,\n                                Marked_Draw | Marked_Lose,\n                                Marked_Lose,\n                                Marked_Zero, \n                        };\n                        std::map<int, int> ret;\n                        int index = 0;\n                        for( auto mark : precedence ){\n                                ret.emplace(mark, index++);\n                        }\n                        return std::move(ret);\n                }();\n                return order[left] < order[right];\n        };\n\n        for(size_t idx=group.Size();idx!=0;){\n                --idx;\n\n                auto& ctrl = group[idx];\n                ctrl.Load();\n                auto const& sub = *ctrl;\n\n                auto cp = sub.GetPlayer();\n                \n                PRINT(sub.Size());\n                PRINT(cp);\n\n                for(size_t i=0;i!=sub.Size();++i){\n                        auto const& board = sub[i];\n                        auto h = board.Hash();\n                        auto e = logic.Evaluate(board);\n\n                        //std::cout << \"processing \" << io.ToString(board) << \"\\n\";\n                        //PRINT(EvalToString(e));\n                        switch(e){\n                        case Eval_Hero:\n                                m[idx][h] = Marked_Win;\n                                break;\n                        case Eval_Villian:\n                                m[idx][h] = Marked_Lose;\n                                break;\n                        case Eval_Draw:\n                                m[idx][h] = Marked_Draw;\n                                break;\n                        case Eval_NotFinished:{\n                                int aggregate = 0;\n                                for( unsigned x=0;x!=board.Width();++x){\n                                        auto level = Level(board, x);\n                                        if( level == board.Height() )\n                                                continue;\n                                        BoardType next(board);\n                                        next.Set(x, level, TileForPlayer(cp));\n\n                                        auto nh = next.Hash();\n\n                                        if( m[idx+1][nh] == 0 ){\n                                                PRINT(x);\n                                                std::cout << \"####### FROM #######\\n\";\n                                                io.Display(board);\n                                                std::cout << io.ToString(board) << \"\\n\";\n                                                std::cout << \"####### TO   #######\\n\";\n                                                io.Display(next);\n                                                std::cout << io.ToString(next) << \"\\n\";\n                                                PRINT_SEQ((std::get<0>(nh))(std::get<1>(nh)));\n                                                std::cout << \"bad marking----------------\\n\";\n                                                std::cout << \"####### END  #######\\n\";\n                                        }\n                                        if( cp == Player_Hero ){\n                                                auto cand = m[idx+1][nh];\n                                                if( marking_lt( cand, aggregate) )\n                                                        aggregate = cand;\n                                        } else {\n                                                aggregate |= m[idx+1][nh];\n                                        }\n                                }\n                                m[idx][h] = aggregate;\n                        }\n                                break;\n                        }\n                        //io.Display(board);\n                        //PRINT_SEQ((std::get<0>(h))(std::get<1>(h))(m[idx][h]));\n                }\n                std::cout << \"\\n\\n\";\n                ctrl.Close();\n\n                //if( idx == group.Size()-4)\n                        //break;\n        }\n\n        PRINT( m[0].size() );\n        PRINT( m[0].begin()->second );\n\n        \n\n}\n\nint main(){\n        Driver2();\n}\n", "meta": {"hexsha": "80c3a15df9a61ae90bd38ddf1f60cd9fe8c7458c", "size": 23212, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ConnectFour.cpp", "max_stars_repo_name": "sweeterthancandy/connect4", "max_stars_repo_head_hexsha": "9c2e0531beb52ee3f495fe5ae9c02edd1d9cd45e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ConnectFour.cpp", "max_issues_repo_name": "sweeterthancandy/connect4", "max_issues_repo_head_hexsha": "9c2e0531beb52ee3f495fe5ae9c02edd1d9cd45e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ConnectFour.cpp", "max_forks_repo_name": "sweeterthancandy/connect4", "max_forks_repo_head_hexsha": "9c2e0531beb52ee3f495fe5ae9c02edd1d9cd45e", "max_forks_repo_licenses": ["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.0351906158, "max_line_length": 155, "alphanum_fraction": 0.4023780803, "num_tokens": 4499, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.49274813728845696}}
{"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_SWAR_FUNCTIONS_COMPLEX_SIMD_COMMON_SORT_HPP_INCLUDED\n#define NT2_SWAR_FUNCTIONS_COMPLEX_SIMD_COMMON_SORT_HPP_INCLUDED\n#include <nt2/swar/functions/sort.hpp>\n#include <nt2/include/functions/simd/aligned_load.hpp>\n#include <nt2/include/functions/simd/aligned_store.hpp>\n#include <boost/simd/preprocessor/aligned_type.hpp>\n#include <boost/simd/sdk/meta/cardinal_of.hpp>\n#include <boost/simd/sdk/meta/scalar_of.hpp>\n#include <nt2/sdk/complex/meta/as_complex.hpp>\n#include <nt2/include/functions/real.hpp>\n\n#include <algorithm>\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT  ( sort_, tag::cpu_\n                            , (A0)(X)\n                            , ((simd_<complex_<floating_<A0> >,X>))\n                            )\n  {\n    typedef A0 result_type;\n    typedef typename meta::scalar_of<A0>::type stype;\n    NT2_FUNCTOR_CALL(1)\n    {\n      static const size_t size = nt2::meta::cardinal_of<A0>::value;\n      BOOST_SIMD_ALIGNED_TYPE(stype) tmp[size];\n      aligned_store(a0, &tmp[0], 0);\n      std::sort(tmp, tmp + size, cmp);\n      return aligned_load<A0>(&tmp[0], 0);\n    }\n   private:\n    static bool cmp(const stype& a0, const stype& a1)\n    {\n      //  when x is complex, the elements are sorted by abs(x).  complex\n      //  matches are further sorted by arg(x).\n      return (nt2::abs(a0) < nt2::abs(a1)) || ((nt2::abs(a0) == nt2::abs(a1))&& (arg(a0) <= arg(a1)));\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  ( sort_, tag::cpu_\n                            , (A0)(X)\n                            , ((simd_<dry_<floating_<A0> >,X>))\n                            )\n  {\n    typedef A0 result_type;\n    typedef typename meta::scalar_of<A0>::type stype;\n    NT2_FUNCTOR_CALL(1)\n    {\n      result_type(nt2::sort(nt2::real(a0)));\n    }\n  };\n\n } } }\n\n\n#endif\n", "meta": {"hexsha": "5eca6635d0cc65f24d656086a813a803ad56927a", "size": 2307, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/type/complex/base/include/nt2/swar/functions/complex/simd/common/sort.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/type/complex/base/include/nt2/swar/functions/complex/simd/common/sort.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/type/complex/base/include/nt2/swar/functions/complex/simd/common/sort.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.4923076923, "max_line_length": 102, "alphanum_fraction": 0.5695708713, "num_tokens": 583, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.49274813728845696}}
{"text": "/*\n * \\file knight_solver.cpp\n * Implements the KnightSolver interface.\n *\n * @author Daniel Grigg\n *\n */\n#include \"knight_solver.h\"\n#include \"position.h\"\n#include \"io.h\"\n\n#include <iostream>\n#include <vector>\n#include <list>\n#include <algorithm>\n#include <boost/bind.hpp>\n#include <boost/iterator/counting_iterator.hpp>\n#include <boost/graph/graph_concepts.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n\nnamespace kt {\n\n  // Legal, relative knight movements\n  Position knight_jumps[KT::KNIGHT_MOVE_DEGREE] = {\n  Position(2, -1),\n  Position(1, -2),\n  Position(-1, -2),\n  Position(-2, -1),\n  Position(-2, 1),\n  Position(-1, 2),\n  Position(1, 2),\n  Position(2, 1)\n};\n\n// Convert a node into a Position (0 <= node <= 63).\nPosition node_to_position(int n) {\n  return Position(n / KT::BOARD_SIZE, n % KT::BOARD_SIZE);\n}\n\n// Convert a Position into a node (0 <= node <= 63).\nsize_t position_to_node(Position p) {\n  return KT::BOARD_SIZE * p[0] + p[1];\n}\n\n// List all legal edges adjacent to vertex n.\nstd::vector<Edge> vertex_adjacent_edges(int n) {\n  std::vector<Edge> edges;\n  edges.reserve(KT::BOARD_SIZE);\n  Position vertex_pos = node_to_position(n);\n                \n  // Add all possible knight moves that stay on the board.\n  for (int i = 0; i < KT::BOARD_SIZE; ++i) {\n    Position jump_position = vertex_pos + knight_jumps[i];\n    if (jump_position.valid_position()) {\n      edges.push_back(std::make_pair(n, position_to_node(jump_position)));\n    }\n  }\n  return edges;\n}\n\n// Append a sequence to a sequence.\ntemplate <typename SequenceT>\nvoid concat(SequenceT& result, SequenceT& src) {\n  result.insert(result.end(), src.begin(), src.end());\n}\n\nKnightSolver::KnightSolver() {\n  std::list<std::vector<Edge> > edges_by_vertex;\n\n  // Generate the adjacent-edges for every vertex.\n  std::transform(boost::counting_iterator<int>(0),\n      boost::counting_iterator<int>(KT::NUM_BOARD_VERTICES),\n      std::back_inserter(edges_by_vertex),\n      vertex_adjacent_edges);\n\n  // Flatten into a single, consecutive edge list\n  std::vector<Edge> edges;\n  std::for_each(edges_by_vertex.begin(), edges_by_vertex.end(),\n      boost::bind(concat<std::vector<Edge> >, boost::ref(edges), _1));\n\n  // All weights are one and yes, we could use BFS instead.  But dijkstra\n  // is a little better optimised in boost.\n  std::vector<int> weights(edges.size(), 1);\n  _g = graph_t_ptr(new graph_t(edges.begin(), edges.end(), weights.begin(), \n        KT::NUM_BOARD_VERTICES));\n}\n\nbool KnightSolver::shortest_path(const Position& start_at, \n    const Position& end_at,\n    std::vector<Position>& path) { \n  path.clear();\n\n  if (!start_at.valid_position() || !end_at.valid_position()) {\n    return false;\n  }\n\n  using namespace boost;\n\n  std::vector<vertex_descriptor> pred(num_vertices(*_g));\n  std::vector<int> dist(num_vertices(*_g));\n  vertex_descriptor src = vertex(position_to_node(start_at), *_g);\n  dijkstra_shortest_paths(*_g, src, \n      predecessor_map(&pred[0]).distance_map(&dist[0]));\n\n  // Walk the predecessors and construct the backwards path.\n  vertex_descriptor v(position_to_node(end_at));\n  path.reserve(dist[v]);\n  do {\n    path.push_back(node_to_position(v));\n    v = pred[v];\n  } while (dist[v] > 0);\n\n  reverse(path.begin(), path.end());\n  return true;\n}\n\nbool KnightSolver::knight_travail(const std::string& input, std::string& output) {\n\n  Position start_at, end_at;\n  if (parse_input(input, start_at, end_at)) {\n\n    std::vector<Position> route;\n\n    if (!shortest_path(start_at, end_at, route)) {\n      std::cerr << \"Unable to find route between \" \n        << start_at.chess_notation()\n        << \" and \" << end_at.chess_notation() << std::endl;\n      return false;\n    }\n    output = route_to_string(route);\n  } else {\n    std::cerr << \"Input must be a pair of valid chesssboard positions\"\n      << \" in chess notation, eg, B2 E5\" << std::endl;\n    return false;\n\n  }\n  return true;\n}\n}\n\n", "meta": {"hexsha": "1ef298afd6af44cdb4ae4e880f81a59a1649b052", "size": 3902, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "toy-problems/knight_trav/Sources/Knight/knight_solver.cpp", "max_stars_repo_name": "danielgrigg/sandbox", "max_stars_repo_head_hexsha": "95128ef44ddc2df2a819b14b9930f95d9c9fd423", "max_stars_repo_licenses": ["WTFPL"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-02-23T03:57:39.000Z", "max_stars_repo_stars_event_max_datetime": "2017-02-23T03:57:39.000Z", "max_issues_repo_path": "toy-problems/knight_trav/Sources/Knight/knight_solver.cpp", "max_issues_repo_name": "danielgrigg/sandbox", "max_issues_repo_head_hexsha": "95128ef44ddc2df2a819b14b9930f95d9c9fd423", "max_issues_repo_licenses": ["WTFPL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "toy-problems/knight_trav/Sources/Knight/knight_solver.cpp", "max_forks_repo_name": "danielgrigg/sandbox", "max_forks_repo_head_hexsha": "95128ef44ddc2df2a819b14b9930f95d9c9fd423", "max_forks_repo_licenses": ["WTFPL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6737588652, "max_line_length": 82, "alphanum_fraction": 0.6768323936, "num_tokens": 1026, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255928, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.49274813025874803}}
{"text": "#include <dlib/optimization/max_cost_assignment.h>\n#include <iostream>\n#include <vector>\n\n#include <dlib/optimization.h>\n\nint main() {\n  int n;\n  std::cin >> n;\n\n  dlib::matrix<int> matrix(n, n);\n\n  for (int i = 0; i < n; i++) {\n    for (int j = 0; j < n; j++) {\n      int l;\n      std::cin >> l;\n      matrix(i, j) = -l;\n    }\n  }\n\n  auto result = dlib::max_cost_assignment(matrix);\n\n  for (auto i : result) {\n    std::cout << i << ' ';\n  }\n\n  std::cout << '\\n';\n\n  int sum = 0;\n\n  for (int i = 0; i < n; i++) {\n    sum += matrix(i, result[i]);\n  }\n\n  std::cout << sum;\n\n  return 0;\n}\n", "meta": {"hexsha": "1796dc314f2b1f33445f7fca7e5aeb8511065576", "size": 586, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "algorithm-experiment/3.1.cpp", "max_stars_repo_name": "crupest/what-can-a-programmer-do", "max_stars_repo_head_hexsha": "e704ef15dcb0663192a353760108ce7d52ab840b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-11-28T06:38:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-18T12:55:37.000Z", "max_issues_repo_path": "algorithm-experiment/3.1.cpp", "max_issues_repo_name": "crupest/what-can-a-programmer-do", "max_issues_repo_head_hexsha": "e704ef15dcb0663192a353760108ce7d52ab840b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "algorithm-experiment/3.1.cpp", "max_forks_repo_name": "crupest/what-can-a-programmer-do", "max_forks_repo_head_hexsha": "e704ef15dcb0663192a353760108ce7d52ab840b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-18T14:03:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-18T14:03:19.000Z", "avg_line_length": 15.0256410256, "max_line_length": 50, "alphanum_fraction": 0.5068259386, "num_tokens": 200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.6477982043529716, "lm_q1q2_score": 0.4927481269442633}}
{"text": "/* ************************************************************************\n * Copyright 2016 Advanced Micro Devices, Inc.\n * ************************************************************************ */\n\n#include <iostream>\n#include <cstdio>\n#include <cstring>\n#include <cctype>\n#include <boost/program_options.hpp>\n\n#include \"rocblas.h\"\n#include \"utility.h\"\n#include \"rocblas.hpp\"\n#include \"testing_iamax.hpp\"\n#include \"testing_iamin.hpp\"\n#include \"testing_asum.hpp\"\n#include \"testing_axpy.hpp\"\n#include \"testing_copy.hpp\"\n#include \"testing_dot.hpp\"\n#include \"testing_swap.hpp\"\n#include \"testing_gemv.hpp\"\n#include \"testing_ger.hpp\"\n#include \"testing_syr.hpp\"\n#include \"testing_nrm2.hpp\"\n#include \"testing_scal.hpp\"\n#include \"testing_trtri.hpp\"\n#include \"testing_trtri_batched.hpp\"\n#include \"testing_geam.hpp\"\n#include \"testing_set_get_vector.hpp\"\n#include \"testing_set_get_matrix.hpp\"\n#if BUILD_WITH_TENSILE\n#include \"testing_gemm.hpp\"\n#include \"testing_gemm_strided_batched.hpp\"\n#include \"testing_gemm_kernel_name.hpp\"\n#include \"testing_gemm_strided_batched_kernel_name.hpp\"\n#include \"testing_trsm.hpp\"\n#include \"testing_gemm_ex.hpp\"\n#include \"testing_gemm_strided_batched_ex.hpp\"\n#endif\n\nstatic int run_bench_test(const char* function, char precision, Arguments argus)\n{\n    static const char prefix[] = \"testing_\";\n    if(!strncmp(function, prefix, sizeof(prefix) - 1))\n    {\n        function += sizeof(prefix) - 1;\n    }\n\n    if(!strcmp(function, \"asum\"))\n    {\n        if(precision == 's')\n            testing_asum<float, float>(argus);\n        else if(precision == 'd')\n            testing_asum<double, double>(argus);\n    }\n    else if(!strcmp(function, \"axpy\"))\n    {\n        if(precision == 'h')\n            testing_axpy<rocblas_half>(argus);\n        else if(precision == 's')\n            testing_axpy<float>(argus);\n        else if(precision == 'd')\n            testing_axpy<double>(argus);\n    }\n    else if(!strcmp(function, \"copy\"))\n    {\n        if(precision == 's')\n            testing_copy<float>(argus);\n        else if(precision == 'd')\n            testing_copy<double>(argus);\n    }\n    else if(!strcmp(function, \"dot\"))\n    {\n        if(precision == 's')\n            testing_dot<float>(argus);\n        else if(precision == 'd')\n            testing_dot<double>(argus);\n    }\n    else if(!strcmp(function, \"swap\"))\n    {\n        if(precision == 's')\n            testing_swap<float>(argus);\n        else if(precision == 'd')\n            testing_swap<double>(argus);\n    }\n    else if(!strcmp(function, \"iamax\"))\n    {\n        if(precision == 's')\n            testing_iamax<float>(argus);\n        else if(precision == 'd')\n            testing_iamax<double>(argus);\n    }\n    else if(!strcmp(function, \"iamin\"))\n    {\n        if(precision == 's')\n            testing_iamin<float>(argus);\n        else if(precision == 'd')\n            testing_iamin<double>(argus);\n    }\n    else if(!strcmp(function, \"nrm2\"))\n    {\n        if(precision == 's')\n            testing_nrm2<float, float>(argus);\n        else if(precision == 'd')\n            testing_nrm2<double, double>(argus);\n    }\n    else if(!strcmp(function, \"scal\"))\n    {\n        if(precision == 's')\n            testing_scal<float>(argus);\n        else if(precision == 'd')\n            testing_scal<double>(argus);\n    }\n    else if(!strcmp(function, \"gemv\"))\n    {\n        if(precision == 's')\n            testing_gemv<float>(argus);\n        else if(precision == 'd')\n            testing_gemv<double>(argus);\n    }\n    else if(!strcmp(function, \"ger\"))\n    {\n        if(precision == 's')\n            testing_ger<float>(argus);\n        else if(precision == 'd')\n            testing_ger<double>(argus);\n    }\n    else if(!strcmp(function, \"syr\"))\n    {\n        if(precision == 's')\n            testing_syr<float>(argus);\n        else if(precision == 'd')\n            testing_syr<double>(argus);\n    }\n    else if(!strcmp(function, \"trtri\"))\n    {\n        if(precision == 's')\n            testing_trtri<float>(argus);\n        else if(precision == 'd')\n            testing_trtri<double>(argus);\n    }\n    else if(!strcmp(function, \"trtri_batched\"))\n    {\n        if(precision == 's')\n            testing_trtri_batched<float>(argus);\n        else if(precision == 'd')\n            testing_trtri_batched<double>(argus);\n    }\n    else if(!strcmp(function, \"geam\"))\n    {\n        if(precision == 's')\n            testing_geam<float>(argus);\n        else if(precision == 'd')\n            testing_geam<double>(argus);\n    }\n    else if(!strcmp(function, \"set_get_vector\"))\n    {\n        if(precision == 's')\n            testing_set_get_vector<float>(argus);\n        else if(precision == 'd')\n            testing_set_get_vector<double>(argus);\n    }\n    else if(!strcmp(function, \"set_get_matrix\"))\n    {\n        if(precision == 's')\n            testing_set_get_matrix<float>(argus);\n        else if(precision == 'd')\n            testing_set_get_matrix<double>(argus);\n    }\n#if BUILD_WITH_TENSILE\n    else if(!strcmp(function, \"gemm\"))\n    {\n        // adjust dimension for GEMM routines\n        rocblas_int min_lda = argus.transA_option == 'N' ? argus.M : argus.K;\n        rocblas_int min_ldb = argus.transB_option == 'N' ? argus.K : argus.N;\n        rocblas_int min_ldc = argus.M;\n\n        if(argus.lda < min_lda)\n        {\n            std::cout << \"rocblas-bench INFO: lda < min_lda, set lda = \" << min_lda << std::endl;\n            argus.lda = min_lda;\n        }\n        if(argus.ldb < min_ldb)\n        {\n            std::cout << \"rocblas-bench INFO: ldb < min_ldb, set ldb = \" << min_ldb << std::endl;\n            argus.ldb = min_ldb;\n        }\n        if(argus.ldc < min_ldc)\n        {\n            std::cout << \"rocblas-bench INFO: ldc < min_ldc, set ldc = \" << min_ldc << std::endl;\n            argus.ldc = min_ldc;\n        }\n\n        if(precision == 'h')\n            testing_gemm<rocblas_half>(argus);\n        else if(precision == 's')\n            testing_gemm<float>(argus);\n        else if(precision == 'd')\n            testing_gemm<double>(argus);\n    }\n    else if(!strcmp(function, \"gemm_ex\"))\n    {\n        // adjust dimension for GEMM routines\n        rocblas_int min_lda = argus.transA_option == 'N' ? argus.M : argus.K;\n        rocblas_int min_ldb = argus.transB_option == 'N' ? argus.K : argus.N;\n        rocblas_int min_ldc = argus.M;\n        rocblas_int min_ldd = argus.M;\n\n        if(argus.lda < min_lda)\n        {\n            std::cout << \"rocblas-bench INFO: lda < min_lda, set lda = \" << min_lda << std::endl;\n            argus.lda = min_lda;\n        }\n        if(argus.ldb < min_ldb)\n        {\n            std::cout << \"rocblas-bench INFO: ldb < min_ldb, set ldb = \" << min_ldb << std::endl;\n            argus.ldb = min_ldb;\n        }\n        if(argus.ldc < min_ldc)\n        {\n            std::cout << \"rocblas-bench INFO: ldc < min_ldc, set ldc = \" << min_ldc << std::endl;\n            argus.ldc = min_ldc;\n        }\n        if(argus.ldd < min_ldd)\n        {\n            std::cout << \"rocblas-bench INFO: ldd < min_ldd, set ldd = \" << min_ldc << std::endl;\n            argus.ldd = min_ldd;\n        }\n        testing_gemm_ex(argus);\n    }\n    else if(!strcmp(function, \"gemm_strided_batched\"))\n    {\n        // adjust dimension for GEMM routines\n        rocblas_int min_lda = argus.transA_option == 'N' ? argus.M : argus.K;\n        rocblas_int min_ldb = argus.transB_option == 'N' ? argus.K : argus.N;\n        rocblas_int min_ldc = argus.M;\n        if(argus.lda < min_lda)\n        {\n            std::cout << \"rocblas-bench INFO: lda < min_lda, set lda = \" << min_lda << std::endl;\n            argus.lda = min_lda;\n        }\n        if(argus.ldb < min_ldb)\n        {\n            std::cout << \"rocblas-bench INFO: ldb < min_ldb, set ldb = \" << min_ldb << std::endl;\n            argus.ldb = min_ldb;\n        }\n        if(argus.ldc < min_ldc)\n        {\n            std::cout << \"rocblas-bench INFO: ldc < min_ldc, set ldc = \" << min_ldc << std::endl;\n            argus.ldc = min_ldc;\n        }\n\n        //      rocblas_int min_stride_a =\n        //          argus.transA_option == 'N' ? argus.K * argus.lda : argus.M * argus.lda;\n        //      rocblas_int min_stride_b =\n        //          argus.transB_option == 'N' ? argus.N * argus.ldb : argus.K * argus.ldb;\n        //      rocblas_int min_stride_a =\n        //          argus.transA_option == 'N' ? argus.K * argus.lda : argus.M * argus.lda;\n        //      rocblas_int min_stride_b =\n        //          argus.transB_option == 'N' ? argus.N * argus.ldb : argus.K * argus.ldb;\n        rocblas_int min_stride_c = argus.ldc * argus.N;\n        //      if (argus.stride_a < min_stride_a)\n        //      {\n        //          std::cout << \"rocblas-bench INFO: stride_a < min_stride_a, set stride_a = \" <<\n        //          min_stride_a << std::endl;\n        //          argus.stride_a = min_stride_a;\n        //      }\n        //      if (argus.stride_b < min_stride_b)\n        //      {\n        //          std::cout << \"rocblas-bench INFO: stride_b < min_stride_b, set stride_b = \" <<\n        //          min_stride_b << std::endl;\n        //          argus.stride_b = min_stride_b;\n        //      }\n        if(argus.stride_c < min_stride_c)\n        {\n            std::cout << \"rocblas-bench INFO: stride_c < min_stride_c, set stride_c = \"\n                      << min_stride_c << std::endl;\n            argus.stride_c = min_stride_c;\n        }\n\n        if(precision == 'h')\n            testing_gemm_strided_batched<rocblas_half>(argus);\n        else if(precision == 's')\n            testing_gemm_strided_batched<float>(argus);\n        else if(precision == 'd')\n            testing_gemm_strided_batched<double>(argus);\n    }\n    else if(!strcmp(function, \"gemm_strided_batched_ex\"))\n    {\n        // adjust dimension for GEMM routines\n        rocblas_int min_lda = argus.transA_option == 'N' ? argus.M : argus.K;\n        rocblas_int min_ldb = argus.transB_option == 'N' ? argus.K : argus.N;\n        rocblas_int min_ldc = argus.M;\n        rocblas_int min_ldd = argus.M;\n        if(argus.lda < min_lda)\n        {\n            std::cout << \"rocblas-bench INFO: lda < min_lda, set lda = \" << min_lda << std::endl;\n            argus.lda = min_lda;\n        }\n        if(argus.ldb < min_ldb)\n        {\n            std::cout << \"rocblas-bench INFO: ldb < min_ldb, set ldb = \" << min_ldb << std::endl;\n            argus.ldb = min_ldb;\n        }\n        if(argus.ldc < min_ldc)\n        {\n            std::cout << \"rocblas-bench INFO: ldc < min_ldc, set ldc = \" << min_ldc << std::endl;\n            argus.ldc = min_ldc;\n        }\n        if(argus.ldd < min_ldd)\n        {\n            std::cout << \"rocblas-bench INFO: ldd < min_ldd, set ldd = \" << min_ldc << std::endl;\n            argus.ldd = min_ldd;\n        }\n        rocblas_int min_stride_c = argus.ldc * argus.N;\n        if(argus.stride_c < min_stride_c)\n        {\n            std::cout << \"rocblas-bench INFO: stride_c < min_stride_c, set stride_c = \"\n                      << min_stride_c << std::endl;\n            argus.stride_c = min_stride_c;\n        }\n\n        testing_gemm_strided_batched_ex(argus);\n    }\n    else if(!strcmp(function, \"gemm_kernel_name\"))\n    {\n        // adjust dimension for GEMM routines\n        rocblas_int min_lda = argus.transA_option == 'N' ? argus.M : argus.K;\n        rocblas_int min_ldb = argus.transB_option == 'N' ? argus.K : argus.N;\n        rocblas_int min_ldc = argus.M;\n        if(argus.lda < min_lda)\n        {\n            std::cout << \"rocblas-bench INFO: lda < min_lda, set lda = \" << min_lda << std::endl;\n            argus.lda = min_lda;\n        }\n        if(argus.ldb < min_ldb)\n        {\n            std::cout << \"rocblas-bench INFO: ldb < min_ldb, set ldb = \" << min_ldb << std::endl;\n            argus.ldb = min_ldb;\n        }\n        if(argus.ldc < min_ldc)\n        {\n            std::cout << \"rocblas-bench INFO: ldc < min_ldc, set ldc = \" << min_ldc << std::endl;\n            argus.ldc = min_ldc;\n        }\n\n        if(precision == 'h')\n            testing_gemm_strided_batched_kernel_name<rocblas_half>(argus);\n        else if(precision == 's')\n            testing_gemm_strided_batched_kernel_name<float>(argus);\n        else if(precision == 'd')\n            testing_gemm_strided_batched_kernel_name<double>(argus);\n    }\n    else if(!strcmp(function, \"gemm_strided_batched_kernel_name\"))\n    {\n        // adjust dimension for GEMM routines\n        rocblas_int min_lda = argus.transA_option == 'N' ? argus.M : argus.K;\n        rocblas_int min_ldb = argus.transB_option == 'N' ? argus.K : argus.N;\n        rocblas_int min_ldc = argus.M;\n        if(argus.lda < min_lda)\n        {\n            std::cout << \"rocblas-bench INFO: lda < min_lda, set lda = \" << min_lda << std::endl;\n            argus.lda = min_lda;\n        }\n        if(argus.ldb < min_ldb)\n        {\n            std::cout << \"rocblas-bench INFO: ldb < min_ldb, set ldb = \" << min_ldb << std::endl;\n            argus.ldb = min_ldb;\n        }\n        if(argus.ldc < min_ldc)\n        {\n            std::cout << \"rocblas-bench INFO: ldc < min_ldc, set ldc = \" << min_ldc << std::endl;\n            argus.ldc = min_ldc;\n        }\n\n        //      rocblas_int min_stride_a =\n        //          argus.transA_option == 'N' ? argus.K * argus.lda : argus.M * argus.lda;\n        //      rocblas_int min_stride_b =\n        //          argus.transB_option == 'N' ? argus.N * argus.ldb : argus.K * argus.ldb;\n        rocblas_int min_stride_c = argus.ldc * argus.N;\n        //      if (argus.stride_a < min_stride_a)\n        //      {\n        //          std::cout << \"rocblas-bench INFO: stride_a < min_stride_a, set stride_a = \" <<\n        //          min_stride_a << std::endl;\n        //          argus.stride_a = min_stride_a;\n        //      }\n        //      if (argus.stride_b < min_stride_b)\n        //      {\n        //          std::cout << \"rocblas-bench INFO: stride_b < min_stride_b, set stride_b = \" <<\n        //          min_stride_b << std::endl;\n        //          argus.stride_b = min_stride_b;\n        //      }\n        if(argus.stride_c < min_stride_c)\n        {\n            std::cout << \"rocblas-bench INFO: stride_c < min_stride_c, set stride_c = \"\n                      << min_stride_c << std::endl;\n            argus.stride_c = min_stride_c;\n        }\n\n        if(precision == 'h')\n            testing_gemm_strided_batched_kernel_name<rocblas_half>(argus);\n        else if(precision == 's')\n            testing_gemm_strided_batched_kernel_name<float>(argus);\n        else if(precision == 'd')\n            testing_gemm_strided_batched_kernel_name<double>(argus);\n    }\n    else if(!strcmp(function, \"trsm\"))\n    {\n        if(precision == 's')\n            testing_trsm<float>(argus);\n        else if(precision == 'd')\n            testing_trsm<double>(argus);\n    }\n#endif\n    else\n    {\n        printf(\"Invalid value for --function \\n\");\n        return -1;\n    }\n\n    return 0;\n}\n\nstatic int rocblas_bench_datafile(const string& datafile)\n{\n    RocBLAS_PerfData::init(datafile);\n\n    for(auto i = RocBLAS_PerfData::begin(); i != RocBLAS_PerfData::end(); ++i)\n    {\n        Arguments argus = *i;\n        char precision;\n\n        // disable unit_check in client benchmark, it is only used in gtest unit test\n        argus.unit_check = 0;\n\n        // enable timing check,otherwise no performance data collected\n        argus.timing = 1;\n\n        switch(argus.a_type)\n        {\n        case rocblas_datatype_f64_r: precision = 'd'; break;\n        case rocblas_datatype_f32_r: precision = 's'; break;\n        case rocblas_datatype_f16_r: precision = 'h'; break;\n        case rocblas_datatype_f64_c: precision = 'z'; break;\n        case rocblas_datatype_f32_c: precision = 'c'; break;\n        case rocblas_datatype_f16_c: precision = 'k'; break;\n        default: precision                     = 's'; break;\n        }\n        run_bench_test(argus.function, precision, argus);\n    }\n\n    return 0;\n}\n\nusing namespace boost::program_options;\n\nint main(int argc, char* argv[])\n{\n    Arguments argus;\n    argus.unit_check =\n        0;            // disable unit_check in client benchmark, it is only used in gtest unit test\n    argus.timing = 1; // enable timing check,otherwise no performance data collected\n\n    std::string function;\n    char precision;\n    char a_type;\n    char b_type;\n    char c_type;\n    char d_type;\n    char compute_type;\n\n    rocblas_int device_id;\n    std::string datafile;\n\n    options_description desc(\"rocblas client command line options\");\n    desc.add_options()\n        // clang-format off\n        (\"sizem,m\",\n         value<rocblas_int>(&argus.M)->default_value(128),\n         \"Specific matrix size: sizem is only applicable to BLAS-2 & BLAS-3: the number of \"\n         \"rows or columns in matrix.\")\n\n        (\"sizen,n\",\n         value<rocblas_int>(&argus.N)->default_value(128),\n         \"Specific matrix/vector size: BLAS-1: the length of the vector. BLAS-2 & \"\n         \"BLAS-3: the number of rows or columns in matrix\")\n\n        (\"sizek,k\",\n         value<rocblas_int>(&argus.K)->default_value(128),\n         \"Specific matrix size:sizek is only applicable to BLAS-3: the number of columns in \"\n         \"A and rows in B.\")\n\n        (\"lda\",\n         value<rocblas_int>(&argus.lda)->default_value(128),\n         \"Leading dimension of matrix A, is only applicable to BLAS-2 & BLAS-3.\")\n\n        (\"ldb\",\n         value<rocblas_int>(&argus.ldb)->default_value(128),\n         \"Leading dimension of matrix B, is only applicable to BLAS-2 & BLAS-3.\")\n\n        (\"ldc\",\n         value<rocblas_int>(&argus.ldc)->default_value(128),\n         \"Leading dimension of matrix C, is only applicable to BLAS-2 & BLAS-3.\")\n\n        (\"ldd\",\n         value<rocblas_int>(&argus.ldd)->default_value(128),\n         \"Leading dimension of matrix D, is only applicable to BLAS-EX \")\n\n        (\"stride_a\",\n         value<rocblas_int>(&argus.stride_a)->default_value(128*128),\n         \"Specific stride of strided_batched matrix A, is only applicable to strided batched\"\n         \"BLAS-2 and BLAS-3: second dimension * leading dimension.\")\n\n        (\"stride_b\",\n         value<rocblas_int>(&argus.stride_b)->default_value(128*128),\n         \"Specific stride of strided_batched matrix B, is only applicable to strided batched\"\n         \"BLAS-2 and BLAS-3: second dimension * leading dimension.\")\n\n        (\"stride_c\",\n         value<rocblas_int>(&argus.stride_c)->default_value(128*128),\n         \"Specific stride of strided_batched matrix C, is only applicable to strided batched\"\n         \"BLAS-2 and BLAS-3: second dimension * leading dimension.\")\n\n        (\"stride_d\",\n         value<rocblas_int>(&argus.stride_d)->default_value(128*128),\n         \"Specific stride of strided_batched matrix D, is only applicable to strided batched\"\n         \"BLAS_EX: second dimension * leading dimension.\")\n\n        (\"incx\",\n         value<rocblas_int>(&argus.incx)->default_value(1),\n         \"increment between values in x vector\")\n\n        (\"incy\",\n         value<rocblas_int>(&argus.incy)->default_value(1),\n         \"increment between values in y vector\")\n\n        (\"alpha\",\n          value<double>(&argus.alpha)->default_value(1.0), \"specifies the scalar alpha\")\n\n        (\"beta\",\n         value<double>(&argus.beta)->default_value(0.0), \"specifies the scalar beta\")\n\n        (\"function,f\",\n         value<std::string>(&function)->default_value(\"gemv\"),\n         \"BLAS function to test. Options: gemv, ger, syr, trsm, trmm, symv, syrk, syr2k\")\n\n        (\"precision,r\",\n         value<char>(&precision)->default_value('s'), \"Options: h,s,d,c,z\")\n\n        (\"a_type\",\n         value<char>(&a_type)->default_value('s'), \"Options: h,s,d,c,z\"\n         \"Precision of matrix A, only applicable to BLAS_EX\")\n\n        (\"b_type\",\n         value<char>(&b_type)->default_value('s'), \"Options: h,s,d,c,z\"\n         \"Precision of matrix B, only applicable to BLAS_EX\")\n\n        (\"c_type\",\n         value<char>(&c_type)->default_value('s'), \"Options: h,s,d,c,z\"\n         \"Precision of matrix C, only applicable to BLAS_EX\")\n\n        (\"d_type\",\n         value<char>(&d_type)->default_value('s'), \"Options: h,s,d,c,z\"\n         \"Precision of matrix D, only applicable to BLAS_EX\")\n\n        (\"compute_type\",\n         value<char>(&compute_type)->default_value('s'), \"Options: h,s,d,c,z\"\n         \"Precision of computation, only applicable to BLAS_EX\")\n\n        (\"transposeA\",\n         value<char>(&argus.transA_option)->default_value('N'),\n         \"N = no transpose, T = transpose, C = conjugate transpose\")\n\n        (\"transposeB\",\n         value<char>(&argus.transB_option)->default_value('N'),\n         \"N = no transpose, T = transpose, C = conjugate transpose\")\n\n        (\"side\",\n         value<char>(&argus.side_option)->default_value('L'),\n         \"L = left, R = right. Only applicable to certain routines\")\n\n        (\"uplo\",\n         value<char>(&argus.uplo_option)->default_value('U'),\n         \"U = upper, L = lower. Only applicable to certain routines\") // xsymv xsyrk xsyr2k xtrsm\n                                                                     // xtrmm\n        (\"diag\",\n         value<char>(&argus.diag_option)->default_value('N'),\n         \"U = unit diagonal, N = non unit diagonal. Only applicable to certain routines\") // xtrsm\n                                                                                          // xtrmm\n        (\"batch\",\n         value<rocblas_int>(&argus.batch_count)->default_value(1),\n         \"Number of matrices. Only applicable to batched routines\") // xtrsm xtrmm xgemm\n\n        (\"verify,v\",\n         value<rocblas_int>(&argus.norm_check)->default_value(0),\n         \"Validate GPU results with CPU? 0 = No, 1 = Yes (default: No)\")\n\n        (\"iters,i\",\n         value<rocblas_int>(&argus.iters)->default_value(10),\n         \"Iterations to run inside timing loop\")\n\n        (\"algo\",\n         value<uint32_t>(&argus.algo)->default_value(0),\n         \"extended precision gemm algorithm\")\n\n        (\"solution_index\",\n         value<int32_t>(&argus.solution_index)->default_value(0),\n         \"extended precision gemm solution index\")\n\n        (\"flags\",\n         value<uint32_t>(&argus.flags)->default_value(10),\n         \"extended precision gemm flags\")\n\n        (\"workspace_size\",\n         value<size_t>(&argus.workspace_size)->default_value(10),\n         \"extended precision gemm workspace size\")\n\n        (\"data\",\n         value<string>(&datafile),\n         \"Data file to use for test arguments (overrides all of the above)\")\n\n        (\"device\",\n         value<rocblas_int>(&device_id)->default_value(0),\n         \"Set default device to be used for subsequent program runs\")\n\n        (\"help,h\", \"produces this help message\");\n    // clang-format on\n\n    variables_map vm;\n    store(parse_command_line(argc, argv, desc), vm);\n    notify(vm);\n\n    if(vm.count(\"help\"))\n    {\n        std::cout << desc << std::endl;\n        return 0;\n    }\n\n    // Device Query\n    rocblas_int device_count = query_device_property();\n\n    std::cout << std::endl;\n    if(device_count <= device_id)\n    {\n        printf(\"Error: Invalid device ID. There may not be such device ID. Will exit \\n\");\n        return -1;\n    }\n    else\n    {\n        set_device(device_id);\n    }\n\n    if(datafile != \"\")\n    {\n        return rocblas_bench_datafile(datafile);\n    }\n\n    if(!strchr(\"hsdcz\", tolower(precision)))\n    {\n        std::cerr << \"Invalid value for --precision\" << std::endl;\n        return -1;\n    }\n\n    argus.a_type = char2rocblas_datatype(a_type);\n    if(argus.a_type == static_cast<rocblas_datatype>(-1))\n    {\n        std::cerr << \"Invalid value for --a_type\" << std::endl;\n        return -1;\n    }\n\n    argus.b_type = char2rocblas_datatype(b_type);\n    if(argus.b_type == static_cast<rocblas_datatype>(-1))\n    {\n        std::cerr << \"Invalid value for --b_type\" << std::endl;\n        return -1;\n    }\n\n    argus.c_type = char2rocblas_datatype(c_type);\n    if(argus.c_type == static_cast<rocblas_datatype>(-1))\n    {\n        std::cerr << \"Invalid value for --c_type\" << std::endl;\n        return -1;\n    }\n\n    argus.d_type = char2rocblas_datatype(d_type);\n    if(argus.d_type == static_cast<rocblas_datatype>(-1))\n    {\n        std::cerr << \"Invalid value for --d_type\" << std::endl;\n        return -1;\n    }\n\n    argus.compute_type = char2rocblas_datatype(compute_type);\n    if(argus.compute_type == static_cast<rocblas_datatype>(-1))\n    {\n        std::cerr << \"Invalid value for --compute_type\" << std::endl;\n        return -1;\n    }\n\n    if(argus.M < 0 || argus.N < 0 || argus.K < 0)\n    {\n        printf(\"Invalid matrix dimension\\n\");\n    }\n\n    return run_bench_test(function.c_str(), precision, argus);\n}\n", "meta": {"hexsha": "b73fa3842ab54d98e02e945254b35b7042565382", "size": 24627, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "clients/benchmarks/client.cpp", "max_stars_repo_name": "gilbertlee-amd/rocBLAS", "max_stars_repo_head_hexsha": "8f1482fba33707dc885d30ff84b0bc1018ec3702", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "clients/benchmarks/client.cpp", "max_issues_repo_name": "gilbertlee-amd/rocBLAS", "max_issues_repo_head_hexsha": "8f1482fba33707dc885d30ff84b0bc1018ec3702", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "clients/benchmarks/client.cpp", "max_forks_repo_name": "gilbertlee-amd/rocBLAS", "max_forks_repo_head_hexsha": "8f1482fba33707dc885d30ff84b0bc1018ec3702", "max_forks_repo_licenses": ["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.8824362606, "max_line_length": 99, "alphanum_fraction": 0.5600357331, "num_tokens": 6490, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851919, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.4927003788883329}}
{"text": "#include <iostream> // cerr\n#include <random> // mt19937_64, uniform_x_distribution\n#include <vector>\n#include <boost/config.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/johnson_all_pairs_shortest.hpp>\n\n#include \"johnson.hpp\"\n\ngraph_t *johnson_init(const int n, const double p, const unsigned long seed) {\n  static std::uniform_real_distribution<double> flip(0, 1);\n  static std::uniform_int_distribution<int> choose_weight(1, 100);\n\n  std::mt19937_64 rand_engine(seed);\n\n  int *adj_matrix = new int[n * n];\n  size_t E = 0;\n  for (int i = 0; i < n; i++) {\n    for (int j = 0; j < n; j++) {\n      if (i == j) {\n        adj_matrix[i*n + j] = 0;\n      } else if (flip(rand_engine) < p) {\n        adj_matrix[i*n + j] = choose_weight(rand_engine);\n        E ++;\n      } else {\n        adj_matrix[i*n + j] = INT_MAX;\n      }\n    }\n  }\n  Edge *edge_array = new Edge[E];\n  int *weights = new int[E];\n  int ei = 0;\n  for (int i = 0; i < n; i++) {\n    for (int j = 0; j < n; j++) {\n      if (adj_matrix[i*n + j] != 0\n          && adj_matrix[i*n + j] != INT_MAX) {\n        edge_array[ei] = Edge(i,j);\n        weights[ei] = adj_matrix[i*n + j];\n        ei++;\n      }\n    }\n  }\n\n  delete[] adj_matrix;\n\n  graph_t *gr = new graph_t;\n  gr->V = n;\n  gr->E = E;\n  gr->edge_array = edge_array;\n  gr->weights = weights;\n\n  return gr;\n}\n\n#ifdef CUDA\nvoid free_graph_cuda(graph_cuda_t *g) {\n  delete[] g->edge_array;\n  delete[] g->weights;\n  delete g;\n}\n\nvoid set_edge(edge_t *edge, int u, int v) {\n  edge->u = u;\n  edge->v = v;\n}\n\ngraph_cuda_t *johnson_cuda_init(const int n, const double p, const unsigned long seed) {\n  static std::uniform_real_distribution<double> flip(0, 1);\n  static std::uniform_int_distribution<int> choose_weight(1, 100);\n\n  std::mt19937_64 rand_engine(seed);\n\n  int *adj_matrix = new int[n * n];\n  size_t E = 0;\n  for (int i = 0; i < n; i++) {\n    for (int j = 0; j < n; j++) {\n      if (i == j) {\n        adj_matrix[i*n + j] = 0;\n      } else if (flip(rand_engine) < p) {\n        adj_matrix[i*n + j] = choose_weight(rand_engine);\n        E ++;\n      } else {\n        adj_matrix[i*n + j] = INT_MAX;\n      }\n    }\n  }\n  edge_t *edge_array = new edge_t[E];\n  int* starts = new int[n + 1];  // Starting point for each edge\n  int* weights = new int[E];\n  int ei = 0;\n  for (int i = 0; i < n; i++) {\n    starts[i] = ei;\n    for (int j = 0; j < n; j++) {\n      if (adj_matrix[i*n + j] != 0\n          && adj_matrix[i*n + j] != INT_MAX) {\n        set_edge(&edge_array[ei], i, j);\n        weights[ei] = adj_matrix[i*n + j];\n        ei++;\n      }\n    }\n  }\n  starts[n] = ei; // One extra\n\n  delete[] adj_matrix;\n\n  graph_cuda_t *gr = new graph_cuda_t;\n  gr->V = n;\n  gr->E = E;\n  gr->edge_array = edge_array;\n  gr->weights = weights;\n  gr->starts = starts;\n\n  return gr;\n}\n\nvoid free_cuda_graph(graph_cuda_t* g) {\n  delete[] g->edge_array;\n  delete[] g->weights;\n  delete[] g->starts;\n  delete g;\n}\n\n#endif\n\nvoid free_graph(graph_t* g) {\n  delete[] g->edge_array;\n  delete[] g->weights;\n  delete g;\n}\n\ninline bool bellman_ford(graph_t* gr, int* dist, int src) {\n  int V = gr->V;\n  int E = gr->E;\n  Edge* edges = gr->edge_array;\n  int* weights = gr->weights;\n\n#ifdef _OPENMP\n#pragma omp parallel for\n#endif\n  for (int i = 0; i < V; i++) {\n    dist[i] = INT_MAX;\n  }\n  dist[src] = 0;\n\n\n  for (int i = 1; i <= V-1; i++) {\n#ifdef _OPENMP\n#pragma omp parallel for\n#endif\n    for (int j = 0; j < E; j++) {\n      int u = std::get<0>(edges[j]);\n      int v = std::get<1>(edges[j]);\n      int new_dist = weights[j] + dist[u];\n      if (dist[u] != INT_MAX && new_dist < dist[v])\n        dist[v] = new_dist;\n    }\n  }\n\n  bool no_neg_cycle = true;\n#ifdef _OPENMP\n#pragma omp parallel for\n#endif\n  for (int i = 0; i < E; i++) {\n    int u = std::get<0>(edges[i]);\n    int v = std::get<1>(edges[i]);\n    int weight = weights[i];\n    if (dist[u] != INT_MAX && dist[u] + weight < dist[v])\n      no_neg_cycle = false;\n  }\n  return no_neg_cycle;\n}\n\nvoid johnson_parallel(graph_t* gr, int* output) {\n\n  int V = gr->V;\n\n  // Make new graph for Bellman-Ford\n  // First, a new node q is added to the graph, connected by zero-weight edges\n  // to each of the other nodes.\n  graph_t* bf_graph = new graph_t;\n  bf_graph->V = V + 1;\n  bf_graph->E = gr->E + V;\n  bf_graph->edge_array = new Edge[bf_graph->E];\n  bf_graph->weights = new int[bf_graph->E];\n\n  std::memcpy(bf_graph->edge_array, gr->edge_array, gr->E  * sizeof(Edge));\n  std::memcpy(bf_graph->weights, gr->weights, gr->E * sizeof(int));\n  std::memset(&bf_graph->weights[gr->E], 0, V * sizeof(int));\n\n#ifdef _OPENMP\n#pragma omp parallel for\n#endif\n  for (int e = 0; e < V; e++) {\n    bf_graph->edge_array[e + gr->E] = Edge(V, e);\n  }\n\n  // Second, the Bellman\u2013Ford algorithm is used, starting from the new vertex q,\n  // to find for each vertex v the minimum weight h(v) of a path from q to v. If\n  // this step detects a negative cycle, the algorithm is terminated.\n  // TODO Can run parallel version?\n  int* h = new int[bf_graph->V];\n  bool r = bellman_ford(bf_graph, h, V);\n  if (!r) {\n    std::cerr << \"\\nNegative Cycles Detected! Terminating Early\\n\";\n    exit(1);\n  }\n  // Next the edges of the original graph are reweighted using the values computed\n  // by the Bellman\u2013Ford algorithm: an edge from u to v, having length\n  // w(u,v), is given the new length w(u,v) + h(u) \u2212 h(v).\n#ifdef _OPENMP\n#pragma omp parallel for\n#endif\n  for (int e = 0; e < gr->E; e++) {\n    int u = std::get<0>(gr->edge_array[e]);\n    int v = std::get<1>(gr->edge_array[e]);\n    gr->weights[e] = gr->weights[e] + h[u] - h[v];\n  }\n\n  Graph G(gr->edge_array, gr->edge_array + gr->E, gr->weights, V);\n\n#ifdef _OPENMP\n#pragma omp parallel for schedule(dynamic)\n#endif\n  for (int s = 0; s < V; s++) {\n    std::vector<int> d(num_vertices(G));\n    dijkstra_shortest_paths(G, s, distance_map(&d[0]));\n    for (int v = 0; v < V; v++) {\n      output[s*V + v] = d[v] + h[v] - h[s];\n    }\n  }\n\n  delete[] h;\n  free_graph(bf_graph);\n}\n", "meta": {"hexsha": "8cb1e4fce76816c077ce613142f0fc24b79f4350", "size": 5957, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/johnson.cpp", "max_stars_repo_name": "moorejs/APSP-in-parallel", "max_stars_repo_head_hexsha": "80bfcb80ce6125700fb18bb73a2424e329a8217a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2018-10-08T04:28:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-04T09:12:33.000Z", "max_issues_repo_path": "src/johnson.cpp", "max_issues_repo_name": "moorejs/418-final", "max_issues_repo_head_hexsha": "80bfcb80ce6125700fb18bb73a2424e329a8217a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/johnson.cpp", "max_forks_repo_name": "moorejs/418-final", "max_forks_repo_head_hexsha": "80bfcb80ce6125700fb18bb73a2424e329a8217a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-04-30T12:42:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-05T14:12:41.000Z", "avg_line_length": 25.3489361702, "max_line_length": 88, "alphanum_fraction": 0.5853617593, "num_tokens": 1926, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.6406358479787609, "lm_q1q2_score": 0.49270037662098626}}
{"text": "// Do not include this line twice in your project!\n#define STB_IMAGE_WRITE_IMPLEMENTATION\n#define STB_IMAGE_IMPLEMENTATION\n\n#include <memory>\n#include <random>\n\n#include <Eigen/Core>\n\n#include \"camera.hpp\"\n#include \"color_factory.hpp\"\n#include \"image.hpp\"\n#include \"log.hpp\"\n#include \"orthographic_projection.hpp\"\n#include \"ray_tracing_renderer.hpp\"\n#include \"renderer.hpp\"\n#include \"scene.hpp\"\n#include \"sphere.hpp\"\n\nScene createScene1(); // With accretion disk\nScene createScene2(); // Without accretion disk\nScene createScene3(); // With accretion disk but without black hole distortion\nScene createScene4(); // Without accretion disk nor black hole distortion\nScene createScene5(); // Without accretion disk but with black hole distortion\nScene createScene6(); // With background texture and no black hole\nScene createScene7(); // With background texture and black hole but no accretion disk\nScene createScene8(); // With background texture, black hole and accretion disk\n\nstd::shared_ptr<Renderer> createRenderer1(int width, int height);\n\nvoid task1();\nvoid task2();\nvoid task3();\nvoid task4();\nvoid task5();\nvoid task6();\nvoid task7();\nvoid task8();\nvoid task9();\nvoid task10();\n\nint main() {\n    // LOG_SET_DEBUG();\n    task1();\n    task2();\n    task3();\n    task4();\n    task5();\n    task6();\n    task7();\n    task8();\n    task9();\n    task10();\n    return 0;\n}\n\nScene createScene1() {\n    std::random_device r;\n    std::default_random_engine generator {0};\n\n    Scene scene(\"Scene 1\");\n\n    // Creating stars distributed in a sphere\n    float radius;\n    float x, y, z;\n    float rho, theta, psi;\n    std::uniform_real_distribution<float> radius_distribution(0.03, 0.1);\n    std::uniform_real_distribution<float> rho_distribution(4.0, 9.0);\n    std::uniform_real_distribution<float> theta_distribution(-M_PI, M_PI);\n    std::uniform_real_distribution<float> psi_distribution(-M_PI/4, M_PI/4);\n    for (int i = 0; i < 100; i++) {\n        radius = radius_distribution(generator);\n        rho = rho_distribution(generator);\n        theta = theta_distribution(generator);\n        psi = psi_distribution(generator);\n\n        x = rho*sin(psi)*cos(theta);\n        y = rho*sin(psi)*sin(theta);\n        z = rho*cos(psi);\n\n        scene.addStar(radius, Eigen::Vector4d(x, y, z, 1));\n    }\n\n    scene.addBlackHole(0.25, Eigen::Vector4d(0, 0, 0, 1));\n    scene.addAccretionDisk(1.75, 0.75, Eigen::Vector4d(0, 0, 0, 1), Eigen::Vector4d(4, -30, 1, 0).normalized());\n    return scene;\n}\n\nScene createScene2() {\n    std::random_device r;\n    std::default_random_engine generator {0};\n\n    Scene scene(\"Scene 2\");\n\n    // Creating stars distributed in a sphere\n    float radius;\n    float x, y, z;\n    float rho, theta, psi;\n    std::uniform_real_distribution<float> radius_distribution(0.005, 0.12);\n    std::uniform_real_distribution<float> rho_distribution(4.0, 9.0);\n    std::uniform_real_distribution<float> theta_distribution(-M_PI, M_PI);\n    std::uniform_real_distribution<float> psi_distribution(-M_PI/4, M_PI/4);\n    for (int i = 0; i < 100; i++) {\n        radius = radius_distribution(generator);\n        rho = rho_distribution(generator);\n        theta = theta_distribution(generator);\n        psi = psi_distribution(generator);\n\n        x = rho*sin(psi)*cos(theta);\n        y = rho*sin(psi)*sin(theta);\n        z = rho*cos(psi);\n\n        scene.addStar(radius, Eigen::Vector4d(x, y, z, 1));\n    }\n\n    scene.addBlackHole(0.25, Eigen::Vector4d(0, 0, 0, 1));\n\n    return scene;\n}\n\nScene createScene3() {\n    std::random_device r;\n    std::default_random_engine generator {0};\n\n    Scene scene(\"Scene 3\");\n\n    // Creating stars distributed in a sphere\n    float radius;\n    float x, y, z;\n    float rho, theta, psi;\n    std::uniform_real_distribution<float> radius_distribution(0.005, 0.12);\n    std::uniform_real_distribution<float> rho_distribution(4.0, 9.0);\n    std::uniform_real_distribution<float> theta_distribution(-M_PI, M_PI);\n    std::uniform_real_distribution<float> psi_distribution(-M_PI/4, M_PI/4);\n    for (int i = 0; i < 100; i++) {\n        radius = radius_distribution(generator);\n        rho = rho_distribution(generator);\n        theta = theta_distribution(generator);\n        psi = psi_distribution(generator);\n\n        x = rho*sin(psi)*cos(theta);\n        y = rho*sin(psi)*sin(theta);\n        z = rho*cos(psi);\n\n        scene.addStar(radius, Eigen::Vector4d(x, y, z, 1));\n    }\n\n    scene.addAccretionDisk(1.75, 0.75, Eigen::Vector4d(0, 0, 0, 1), Eigen::Vector4d(4, -30, 1, 0).normalized());\n    return scene;\n}\n\nScene createScene4() {\n    std::random_device r;\n    std::default_random_engine generator {0};\n\n    Scene scene(\"Scene 4\");\n\n    // Creating stars distributed in a sphere\n    float radius;\n    float x, y, z;\n    float rho, theta, psi;\n    std::uniform_real_distribution<float> radius_distribution(0.005, 0.12);\n    std::uniform_real_distribution<float> rho_distribution(4.0, 9.0);\n    std::uniform_real_distribution<float> theta_distribution(-M_PI, M_PI);\n    std::uniform_real_distribution<float> psi_distribution(-M_PI/4, M_PI/4);\n    for (int i = 0; i < 100; i++) {\n        radius = radius_distribution(generator);\n        rho = rho_distribution(generator);\n        theta = theta_distribution(generator);\n        psi = psi_distribution(generator);\n\n        x = rho*sin(psi)*cos(theta);\n        y = rho*sin(psi)*sin(theta);\n        z = rho*cos(psi);\n\n        scene.addStar(radius, Eigen::Vector4d(x, y, z, 1));\n    }\n\n    return scene;\n}\n\nScene createScene5() {\n    std::random_device r;\n    std::default_random_engine generator {0};\n\n    Scene scene(\"Scene 5\");\n\n    // Creating stars distributed in a sphere\n    float radius;\n    float x, y, z;\n    float rho, theta, psi;\n    std::uniform_real_distribution<float> radius_distribution(0.005, 0.12);\n    std::uniform_real_distribution<float> rho_distribution(4.0, 9.0);\n    std::uniform_real_distribution<float> theta_distribution(-M_PI, M_PI);\n    std::uniform_real_distribution<float> psi_distribution(-M_PI/4, M_PI/4);\n    for (int i = 0; i < 100; i++) {\n        radius = radius_distribution(generator);\n        rho = rho_distribution(generator);\n        theta = theta_distribution(generator);\n        psi = psi_distribution(generator);\n\n        x = rho*sin(psi)*cos(theta);\n        y = rho*sin(psi)*sin(theta);\n        z = rho*cos(psi);\n\n        scene.addStar(radius, Eigen::Vector4d(x, y, z, 1));\n    }\n\n    scene.addBlackHole(0.25, Eigen::Vector4d(0, 0, 0, 1));\n\n    return scene;\n}\n\nScene createScene6() {\n    std::random_device r;\n    std::default_random_engine generator {0};\n\n    Scene scene(\"Scene 6\");\n\n    scene.addUniverse(5, Eigen::Vector4d(0, 0, 0, 1));\n    return scene;\n}\n\nScene createScene7() {\n    std::random_device r;\n    std::default_random_engine generator {0};\n\n    Scene scene(\"Scene 7\");\n\n    scene.addUniverse(5, Eigen::Vector4d(0, 0, 0, 1));\n    scene.addBlackHole(0.25, Eigen::Vector4d(0, 0, 0, 1));\n    return scene;\n}\n\nScene createScene8() {\n    std::random_device r;\n    std::default_random_engine generator {0};\n\n    Scene scene(\"Scene 8\");\n\n    scene.addUniverse(5, Eigen::Vector4d(0, 0, 0, 1));\n    scene.addBlackHole(0.25, Eigen::Vector4d(0, 0, 0, 1));\n    scene.addAccretionDisk(1.75, 0.75, Eigen::Vector4d(0, 0, 0, 1), Eigen::Vector4d(4, -30, 1, 0).normalized());\n    return scene;\n}\n\nstd::shared_ptr<Renderer> createRenderer1(int width, int height) {\n    std::shared_ptr<Viewport> viewport = std::make_shared<Viewport>(width, height);\n\n    std::shared_ptr<Projection> projection = std::make_shared<OrthographicProjection>(-1, 1, -1, 1, -1, 1);\n\n    Eigen::Vector4d cameraPositionPoint(0, 0, -2, 1);\n    Eigen::Vector4d cameraGazeDirection(0, 0, 1, 0);\n    Eigen::Vector4d cameraViewUpDirection(0, -1, 0, 0);\n    std::shared_ptr<Camera> camera = std::make_shared<Camera>(cameraPositionPoint, cameraGazeDirection, cameraViewUpDirection);\n\n    camera->setVelocityVector(Eigen::Vector4d(-0.1, 0, 0, 0));\n\n    std::shared_ptr<Renderer> renderer = std::make_shared<RayTracingRenderer>(viewport, projection, camera);\n\n    return renderer;\n}\n\nvoid task1() {\n    Scene scene = createScene1();\n    LOG_I(\"Running task 1\");\n    std::shared_ptr<Renderer> renderer = createRenderer1(300, 300);\n    Image image = renderer->render(scene, Renderer::PerspectiveProjection);\n    image.save(\"task1.png\");\n}\n\nvoid task2() {\n    Scene scene = createScene1();\n    LOG_I(\"Running task 2\");\n    std::shared_ptr<Renderer> renderer = createRenderer1(300, 300);\n    renderer->animate(scene, 10, 0.25, \"task2\", Renderer::PerspectiveProjection);\n}\n\nvoid task3() {\n    Scene scene = createScene2();\n    LOG_I(\"Running task 3\");\n    std::shared_ptr<Renderer> renderer = createRenderer1(300, 300);\n    renderer->animate(scene, 10, 0.25, \"task3\", Renderer::PerspectiveProjection);\n}\n\nvoid task4() {\n    Scene scene = createScene3();\n    LOG_I(\"Running task 4\");\n    std::shared_ptr<Renderer> renderer = createRenderer1(300, 300);\n    Image image = renderer->render(scene, Renderer::PerspectiveProjection);\n    image.save(\"task4.png\");\n}\n\nvoid task5() {\n    Scene scene = createScene4();\n    LOG_I(\"Running task 5\");\n    std::shared_ptr<Renderer> renderer = createRenderer1(300, 300);\n    Image image = renderer->render(scene, Renderer::PerspectiveProjection);\n    image.save(\"task5.png\");\n}\n\nvoid task6() {\n    Scene scene = createScene5();\n    LOG_I(\"Running task 6\");\n    std::shared_ptr<Renderer> renderer = createRenderer1(300, 300);\n    Image image = renderer->render(scene, Renderer::PerspectiveProjection);\n    image.save(\"task6.png\");\n}\n\nvoid task7() {\n    Scene scene = createScene6();\n    LOG_I(\"Running task 7\");\n    std::shared_ptr<Renderer> renderer = createRenderer1(600, 600);\n    renderer->animate(scene, 10, 0.25, \"task7\", Renderer::PerspectiveProjection);\n}\n\nvoid task8() {\n    Scene scene = createScene7();\n    LOG_I(\"Running task 8\");\n    std::shared_ptr<Renderer> renderer = createRenderer1(600, 600);\n    renderer->animate(scene, 10, 0.25, \"task8\", Renderer::PerspectiveProjection);\n}\n\nvoid task9() {\n    Scene scene = createScene8();\n    LOG_I(\"Running task 9\");\n    std::shared_ptr<Renderer> renderer = createRenderer1(600, 600);\n    renderer->animate(scene, 10, 0.25, \"task9\", Renderer::PerspectiveProjection);\n}\n\nvoid task10() {\n    Scene scene = createScene8();\n    LOG_I(\"Running task 10\");\n    std::shared_ptr<Renderer> renderer = createRenderer1(600, 600);\n    Image image = renderer->render(scene, Renderer::PerspectiveProjection);\n    image.save(\"task10.png\");\n}", "meta": {"hexsha": "76b2b88ced03216e66fed4831ff7332733a57be5", "size": 10490, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "matheusportela/black-hole-ray-tracer", "max_stars_repo_head_hexsha": "3a7f1a32d6d44f74278b721e1f49e11b8a9ad86e", "max_stars_repo_licenses": ["MIT"], "max_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": "matheusportela/black-hole-ray-tracer", "max_issues_repo_head_hexsha": "3a7f1a32d6d44f74278b721e1f49e11b8a9ad86e", "max_issues_repo_licenses": ["MIT"], "max_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": "matheusportela/black-hole-ray-tracer", "max_forks_repo_head_hexsha": "3a7f1a32d6d44f74278b721e1f49e11b8a9ad86e", "max_forks_repo_licenses": ["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.1275964392, "max_line_length": 127, "alphanum_fraction": 0.6686367969, "num_tokens": 2879, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.4927003645627475}}
{"text": "#ifndef NUMERICS_HPP\n#define NUMERICS_HPP\n\n#include <functional>\n#include <cmath>\n#include <iostream>\n#include <iomanip>\n#include <algorithm>\n#include <queue>\n#include <set>\n#include <memory>\n\n#include <omp.h>\n\n#define ARMA_USE_SUPERLU 1 // optional, but really should be used when handling sparse matrices\n#include <armadillo>\n\n/* Copyright 2019 Amit Rotem\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\nnamespace numerics {\n    #include <numerics/utility.hpp>\n    #include <numerics/interpolation.hpp>\n    #include <numerics/neural_network.hpp>\n    #include <numerics/data_science.hpp>\n    #include <numerics/derivatives.hpp>\n    #include <numerics/integrals.hpp>\n    #include <numerics/optimization.hpp>\n    #include <numerics/ode.hpp>\n}\n\n#endif", "meta": {"hexsha": "d5eb1c07ff46dbab6b74524f1f9a7e95ce3510fa", "size": 1230, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/numerics.hpp", "max_stars_repo_name": "arotem3/numerics", "max_stars_repo_head_hexsha": "ba208d9fc0ccb9471cfec9927a21622eb3535f54", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2019-04-18T17:34:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-15T07:57:29.000Z", "max_issues_repo_path": "include/numerics.hpp", "max_issues_repo_name": "arotem3/numerics", "max_issues_repo_head_hexsha": "ba208d9fc0ccb9471cfec9927a21622eb3535f54", "max_issues_repo_licenses": ["Apache-2.0"], "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/numerics.hpp", "max_forks_repo_name": "arotem3/numerics", "max_forks_repo_head_hexsha": "ba208d9fc0ccb9471cfec9927a21622eb3535f54", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-12-02T04:04:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T08:23:09.000Z", "avg_line_length": 28.6046511628, "max_line_length": 95, "alphanum_fraction": 0.7601626016, "num_tokens": 285, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851918, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.4927003577812735}}
{"text": "// Copyright (c) 2017 Graphcore Ltd. All rights reserved.\n#include \"Constraint.hpp\"\n\n#include \"Scheduler.hpp\"\n\n#include <popsolver/Model.hpp>\n\n#include <poplibs_support/Visitor.hpp>\n\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/range/iterator_range.hpp>\n\n#include <limits>\n\nusing namespace popsolver;\n\nusing BigInteger = boost::multiprecision::uint128_t;\nstatic_assert(\n    sizeof(BigInteger) >= sizeof(DataType::UnderlyingType) * 2,\n    \"BigInteger isn't large enough to perform operations on DataType\");\n\nConstraint::~Constraint() = default;\n\nbool Product::propagate(Scheduler &scheduler) {\n  const Domains &domains = scheduler.getDomains();\n  const auto result = vars[0];\n  const auto left = vars[1];\n  const auto right = vars[2];\n\n  bool madeChange;\n  do {\n    madeChange = false;\n\n    // Check if the result doesn't match the inputs\n    // left[max] * right[max] = result[max]\n    // left[min] * right[min] = result[min]\n    const BigInteger maxProduct =\n        BigInteger{*domains[left].max()} * BigInteger{*domains[right].max()};\n    const BigInteger minProduct =\n        BigInteger{*domains[left].min()} * BigInteger{*domains[right].min()};\n    if (minProduct > *domains[result].max() ||\n        maxProduct < *domains[result].min()) {\n      return false;\n    }\n    if (minProduct > *domains[result].min()) {\n      // This is fine to do unchecked because minProduct is less than the\n      // value in *domains[result].max() which is limited to DataType. Otherwise\n      // We would have already bailed out.\n      scheduler.setMin(result,\n                       popsolver::DataType{\n                           minProduct.convert_to<DataType::UnderlyingType>()});\n      madeChange = true;\n    }\n    if (maxProduct < *domains[result].max()) {\n      // This is fine to do unchecked because we are less than the value of\n      // *domains[result].max(), which is of type DataType.\n      scheduler.setMax(result,\n                       popsolver::DataType{\n                           maxProduct.convert_to<DataType::UnderlyingType>()});\n      madeChange = true;\n    }\n\n    // Check if the inputs do not match the result\n    // We shortcut some calculations avoiding a costly divide by noting:\n    // result[min] <= left[max] * right[min] <= result[max]\n    // result[min] <= left[min] * right[max] <= result[max]\n\n    // If we want to reduce the value of left[max] we can check if it\n    // is valid by comparing against result[max].\n    //\n    // If (left[max] * right[min] <= result[max]) is not true,\n    // we can reduce the value of left[max] to be result[max] / right[min]. And\n    // likewise for all other permutations.\n\n    // left[max] * right[min] <= result[max]\n    if (domains[right].min() != popsolver::DataType{0} &&\n        BigInteger{*domains[right].min()} * BigInteger{*domains[left].max()} >\n            BigInteger{*domains[result].max()}) {\n      auto newLeftMax = domains[result].max() / domains[right].min();\n      assert(newLeftMax < domains[left].max());\n      if (newLeftMax < domains[left].min())\n        return false;\n      scheduler.setMax(left, newLeftMax);\n      madeChange = true;\n    }\n    // left[min] * right[max] <= result[max]\n    if (domains[left].min() != popsolver::DataType{0} &&\n        BigInteger{*domains[left].min()} * BigInteger{*domains[right].max()} >\n            BigInteger{*domains[result].max()}) {\n      auto newRightMax = domains[result].max() / domains[left].min();\n      assert(newRightMax < domains[right].max());\n      if (newRightMax < domains[right].min())\n        return false;\n      scheduler.setMax(right, newRightMax);\n      madeChange = true;\n    }\n\n    // left[min] * right[max] >= result[min]\n    if (domains[right].max() != popsolver::DataType{0} &&\n        BigInteger{*domains[right].max()} * BigInteger{*domains[left].min()} <\n            BigInteger{*domains[result].min()}) {\n      auto newLeftMin =\n          domains[result].min() / domains[right].max() +\n          popsolver::DataType{(domains[result].min() % domains[right].max() !=\n                               popsolver::DataType{0})};\n      if (newLeftMin > domains[left].min()) {\n        if (newLeftMin > domains[left].max())\n          return false;\n        scheduler.setMin(left, newLeftMin);\n        madeChange = true;\n      }\n    }\n    // left[max] * right[min] >= result[min]\n    if (domains[left].max() != popsolver::DataType{0} &&\n        BigInteger{*domains[left].max()} * BigInteger{*domains[right].min()} <\n            BigInteger{*domains[result].min()}) {\n      auto newRightMin =\n          domains[result].min() / domains[left].max() +\n          popsolver::DataType{(domains[result].min() % domains[left].max() !=\n                               popsolver::DataType{0})};\n      if (newRightMin > domains[right].min()) {\n        if (newRightMin > domains[right].max())\n          return false;\n        scheduler.setMin(right, newRightMin);\n        madeChange = true;\n      }\n    }\n  } while (madeChange);\n  return true;\n}\n\nbool Sum::propagate(Scheduler &scheduler) {\n  const Domains &domains = scheduler.getDomains();\n  const auto result = vars[0];\n  const auto args =\n      boost::make_iterator_range(std::begin(vars) + 1, std::end(vars));\n\n  // The data type used to store the max sum must be large enough to store\n  // the maximum value of the result plus the maximum value of any operand so\n  // that we can compute the max sum of a subset containing all but one variable\n  // by subtracting the the maximum value of the variable from the max sum.\n  BigInteger minSum = 0;\n  BigInteger maxSum = 0;\n  for (const auto &v : args) {\n    minSum = minSum + *domains[v].min();\n    maxSum = maxSum + *domains[v].max();\n  }\n  if (minSum > *domains[result].max() || maxSum < *domains[result].min()) {\n    return false;\n  }\n  if (minSum > *domains[result].min()) {\n    scheduler.setMin(\n        result,\n        popsolver::DataType{minSum.convert_to<DataType::UnderlyingType>()});\n  }\n  if (maxSum < *domains[result].max()) {\n    scheduler.setMax(\n        result,\n        popsolver::DataType{maxSum.convert_to<DataType::UnderlyingType>()});\n  }\n  for (const auto &v : args) {\n    auto &domain = domains[v];\n    auto minOtherVarsSum = minSum - *domain.min();\n    if (minOtherVarsSum > *domains[result].max())\n      return false;\n    auto newMax = *domains[result].max() - minOtherVarsSum;\n    if (newMax < *domain.min())\n      return false;\n    if (newMax < *domain.max())\n      scheduler.setMax(v, popsolver::DataType{\n                              newMax.convert_to<DataType::UnderlyingType>()});\n    auto maxOtherVarsSum = maxSum - *domain.max();\n    if (maxOtherVarsSum < *domains[result].min()) {\n      auto newMin = *domains[result].min() - maxOtherVarsSum;\n      if (newMin > *domain.max())\n        return false;\n      if (newMin > *domain.min())\n        scheduler.setMin(v, popsolver::DataType{\n                                newMin.convert_to<DataType::UnderlyingType>()});\n    }\n  }\n  return true;\n}\n\nbool Max::propagate(Scheduler &scheduler) {\n  const Domains &domains = scheduler.getDomains();\n  const auto result = vars[0];\n  const auto args =\n      boost::make_iterator_range(std::begin(vars) + 1, std::end(vars));\n\n  // give A = max(B, C), we can deduce:\n  //  - upperbound(A) = min(upperbound(A), max(upperbound(B), upperbound(C))),\n  //  - lowerbound(A) = max(lowerbound(A), max(lowerbound(B), lowerbound(C))),\n  //  - upperbound(B) = min(upperbound(A), upperbound(B)),\n  //  - upperbound(C) = min(upperbound(A), upperbound(C))\n  // propagation will fail if:\n  //  - upperbound(A) < max(lowerbound(B), lowerbound(C)),\n  //  - lowerbound(A) > max(upperbound(B), upperbound(C))\n\n  const auto resultLower = domains[result].min();\n  const auto resultUpper = domains[result].max();\n\n  auto maxLowerBound = DataType::min();\n  auto minLowerBound = DataType::max();\n  auto maxUpperBound = DataType::min();\n  auto minUpperBound = DataType::max();\n\n  for (const auto &var : args) {\n    if (domains[var].min() > resultUpper) {\n      return false;\n    } else if (domains[var].max() > resultUpper) {\n      scheduler.setMax(var, resultUpper);\n    }\n\n    maxLowerBound = std::max(maxLowerBound, domains[var].min());\n    minLowerBound = std::min(minLowerBound, domains[var].min());\n    maxUpperBound = std::max(maxUpperBound, domains[var].max());\n    minUpperBound = std::min(minUpperBound, domains[var].max());\n  }\n\n  assert(resultUpper >= maxLowerBound);\n  if (resultLower > maxUpperBound) {\n    return false;\n  }\n\n  if (resultUpper > maxUpperBound) {\n    scheduler.setMax(result, maxUpperBound);\n  }\n\n  if (resultLower < maxLowerBound) {\n    scheduler.setMin(result, maxLowerBound);\n  }\n\n  return true;\n}\n\nbool Min::propagate(Scheduler &scheduler) {\n  const Domains &domains = scheduler.getDomains();\n  const auto result = vars[0];\n  const auto args =\n      boost::make_iterator_range(std::begin(vars) + 1, std::end(vars));\n\n  // give A = min(B, C), we can deduce:\n  //  - upperbound(A) = min(upperbound(A), min(upperbound(B), upperbound(C))),\n  //  - lowerbound(A) = max(lowerbound(A), min(lowerbound(B), lowerbound(C))),\n  //  - lowerbound(B) = max(lowerbound(A), lowerbound(B)),\n  //  - lowerbound(C) = max(lowerbound(A), lowerbound(C))\n  // propagation will fail if:\n  //  - upperbound(A) < max(lowerbound(B), lowerbound(C)),\n  //  - lowerbound(A) > max(upperbound(B), upperbound(C))\n\n  const auto resultLower = domains[result].min();\n  const auto resultUpper = domains[result].max();\n\n  auto maxLowerBound = DataType::min();\n  auto minLowerBound = DataType::max();\n  auto maxUpperBound = DataType::min();\n  auto minUpperBound = DataType::max();\n\n  for (const auto &var : args) {\n    if (domains[var].max() < resultLower) {\n      return false;\n    } else if (domains[var].min() < resultLower) {\n      scheduler.setMin(var, resultLower);\n    }\n\n    maxLowerBound = std::max(maxLowerBound, domains[var].min());\n    minLowerBound = std::min(minLowerBound, domains[var].min());\n    maxUpperBound = std::max(maxUpperBound, domains[var].max());\n    minUpperBound = std::min(minUpperBound, domains[var].max());\n  }\n\n  assert(resultLower <= minUpperBound);\n  if (resultUpper < minLowerBound) {\n    return false;\n  }\n\n  if (resultUpper > minUpperBound) {\n    scheduler.setMax(result, minUpperBound);\n  }\n\n  if (resultLower < minLowerBound) {\n    scheduler.setMin(result, minLowerBound);\n  }\n\n  return true;\n}\n\nbool Less::propagate(Scheduler &scheduler) {\n  const Domains &domains = scheduler.getDomains();\n  const auto left = vars[0];\n  const auto right = vars[1];\n\n  if (domains[left].min() >= domains[right].max()) {\n    return false;\n  }\n  if (domains[left].min() >= domains[right].min()) {\n    scheduler.setMin(right, domains[left].min() + popsolver::DataType{1});\n  }\n  if (domains[right].max() <= domains[left].max()) {\n    scheduler.setMax(left, domains[right].max() - popsolver::DataType{1});\n  }\n  return true;\n}\n\nbool LessOrEqual::propagate(Scheduler &scheduler) {\n  const Domains &domains = scheduler.getDomains();\n  const auto left = vars[0];\n  const auto right = vars[1];\n\n  if (domains[left].min() > domains[right].max()) {\n    return false;\n  }\n  if (domains[left].min() > domains[right].min()) {\n    scheduler.setMin(right, domains[left].min());\n  }\n  if (domains[right].max() < domains[left].max()) {\n    scheduler.setMax(left, domains[right].max());\n  }\n  return true;\n}\n\ntemplate <> bool GenericAssignment<DataType>::propagate(Scheduler &scheduler) {\n  const Domains &domains = scheduler.getDomains();\n  for (std::size_t i = 1; i != vars.size(); ++i) {\n    const auto domain = domains[vars[i]];\n    if (domain.size() > popsolver::DataType{1}) {\n      return true;\n    }\n    values[i - 1] = domain.val();\n  }\n\n  const auto x = f(values);\n\n  if (!x) {\n    return false;\n  }\n  const auto result = vars[0];\n  if (x.get() < domains[result].min() || x.get() > domains[result].max()) {\n    return false;\n  }\n  if (domains[result].min() != x.get() || domains[result].max() != x.get()) {\n    scheduler.set(result, x.get());\n  }\n  return true;\n}\n\ntemplate <typename T>\nbool GenericAssignment<T>::propagate(Scheduler &scheduler) {\n  const Domains &domains = scheduler.getDomains();\n  for (std::size_t i = 1; i != vars.size(); ++i) {\n    // Input operands must be with the range allowed for the data type\n    const auto &domain = domains[vars[i]];\n    if (domain.min() > popsolver::DataType{std::numeric_limits<T>::max()} ||\n        domain.max() < popsolver::DataType{std::numeric_limits<T>::min()}) {\n      return false;\n    }\n    if (domain.min() < popsolver::DataType{std::numeric_limits<T>::min()}) {\n      scheduler.setMin(vars[i],\n                       popsolver::DataType{std::numeric_limits<T>::min()});\n    }\n    if (domain.max() > popsolver::DataType{std::numeric_limits<T>::max()}) {\n      scheduler.setMax(vars[i],\n                       popsolver::DataType{std::numeric_limits<T>::max()});\n    }\n  }\n\n  for (std::size_t i = 1; i != vars.size(); ++i) {\n    const auto domain = domains[vars[i]];\n    if (domain.size() > popsolver::DataType{1}) {\n      return true;\n    }\n    values[i - 1] = domain.val();\n  }\n\n  std::vector<T> castedValues{};\n  castedValues.reserve(values.size());\n  for (auto v : values) {\n    castedValues.push_back(v.template getAs<T>());\n  }\n\n  const auto x = f(castedValues);\n\n  if (!x) {\n    return false;\n  }\n  const auto result = vars[0];\n  if (x.get() < domains[result].min() || x.get() > domains[result].max()) {\n    return false;\n  }\n  if (domains[result].min() != x.get() || domains[result].max() != x.get()) {\n    scheduler.set(result, x.get());\n  }\n  return true;\n}\n\ntemplate class popsolver::GenericAssignment<DataType>;\ntemplate class popsolver::GenericAssignment<unsigned>;\ntemplate class popsolver::GenericAssignment<uint64_t>;\n", "meta": {"hexsha": "0448157ab34d6baf88887aa63e5fad1599e6c333", "size": 13726, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/popsolver/Constraint.cpp", "max_stars_repo_name": "giantchen2012/poplibs", "max_stars_repo_head_hexsha": "2bc6b6f3d40863c928b935b5da88f40ddd77078e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-23T05:58:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-23T05:58:24.000Z", "max_issues_repo_path": "lib/popsolver/Constraint.cpp", "max_issues_repo_name": "giantchen2012/poplibs", "max_issues_repo_head_hexsha": "2bc6b6f3d40863c928b935b5da88f40ddd77078e", "max_issues_repo_licenses": ["MIT"], "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/popsolver/Constraint.cpp", "max_forks_repo_name": "giantchen2012/poplibs", "max_forks_repo_head_hexsha": "2bc6b6f3d40863c928b935b5da88f40ddd77078e", "max_forks_repo_licenses": ["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.315, "max_line_length": 80, "alphanum_fraction": 0.624581087, "num_tokens": 3484, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278633625322, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.492683296668989}}
{"text": "#include <catch2/catch.hpp>\n\n#include \"../src/lib/cpplib.h\"\n#include <Eigen/Core>\n#include <boost/math/quadrature/trapezoidal.hpp>\n#include <tbb/parallel_for.h>\n\nusing namespace Catch::literals;\n\n#if (__clang__)\n  #pragma clang diagnostic push\n  #pragma clang diagnostic ignored \"-Wsign-conversion\"\n  #pragma clang diagnostic ignored \"-Wconversion\"\n  #pragma clang diagnostic ignored \"-Wold-style-cast\"\n  #pragma clang diagnostic ignored \"-Wshadow\"\n  #include <EigenRand/EigenRand>\n  #pragma clang diagnostic pop\n#elif (__GNUC__)|| defined(__GNUG__)\n  #pragma GCC diagnostic push\n  #pragma GCC diagnostic ignored \"-Wsign-conversion\"\n  #pragma GCC diagnostic ignored \"-Wconversion\"\n  #pragma GCC diagnostic ignored \"-Wold-style-cast\"\n  #pragma GCC diagnostic ignored \"-Wuseless-cast\"\n  #include <EigenRand/EigenRand>\n  #pragma GCC diagnostic pop\n#elif (_MSC_VER)\n  # pragma warning(disable: 4245)\n  #include <EigenRand/EigenRand>\n#endif\n\nunsigned int Factorial(unsigned int number)// NOLINT(misc-no-recursion)\n{\n  return number <= 1 ? number : Factorial(number - 1) * number;\n}\n\nTEST_CASE(\"Factorials are computed\", \"[factorial]\")\n{\n  REQUIRE(Factorial(1) == 1);\n  REQUIRE(Factorial(2) == 2);\n  REQUIRE(Factorial(3) == 6);\n  REQUIRE(Factorial(10) == 3628800);\n}\n\nTEST_CASE(\"FindMax\", \"[cpplib]\") {\n  CPPLib cpplib;\n\n  SECTION(\"Should find max of consecutive numbers\") {\n    std::vector<int> inputs = {1, 2, 3, 4};\n    REQUIRE(cpplib.FindMax(inputs) == 4);\n  }\n\n  SECTION(\"Should find max of non consecutive numbers\") {\n    std::vector<int> inputs = {1, 7, 3, 4};\n    REQUIRE(cpplib.FindMax(inputs) == 7);\n  }\n\n  SECTION(\"Should find max with negative numbers\") {\n    std::vector<int> inputs = {-1, -7, -3, -4};\n    REQUIRE(cpplib.FindMax(inputs) == -1);\n  }\n\n  SECTION(\"Should find max of all equal values\") {\n    std::vector<int> inputs = {-1, -1, -1, -1};\n    REQUIRE(cpplib.FindMax(inputs) == -1);\n  }\n\n  SECTION(\"Should find return min for empty vector\") {\n    std::vector<int> inputs = {};\n    REQUIRE(cpplib.FindMax(inputs) == std::numeric_limits<int>::min());\n  }\n\n  SECTION(\"Should find return min for empty vector\") {\n    std::vector<int> inputs = {1000};\n    REQUIRE(cpplib.FindMax(inputs) == 1000);\n  }\n}\n\nTEST_CASE(\"TBB parallel for\", \"[TBB]\")\n{\n  auto values = std::vector<double>(10000);    \n  tbb::parallel_for( tbb::blocked_range<size_t>(0,values.size()),\n                       [&](tbb::blocked_range<size_t> r){\n    for (size_t i=r.begin(); i<r.end(); ++i){\n      values[i] = std::sin(static_cast<double>(i) * 0.001);\n    }\n  });\n\n  double total = 0;\n  for (double value : values){\n    total += value;\n  }\n  //REQUIRE(total == Approx(1839.3433863759381)); \n  REQUIRE(1 == 1);\n}\n", "meta": {"hexsha": "fe57361fd9afff0c06a2e9e84624a76b9ed5cd81", "size": 2695, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/tests.cpp", "max_stars_repo_name": "suhasghorp/jason-cpp-starter", "max_stars_repo_head_hexsha": "e035326575eb022f37344dc7a80f7a0f243de5d7", "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": "test/tests.cpp", "max_issues_repo_name": "suhasghorp/jason-cpp-starter", "max_issues_repo_head_hexsha": "e035326575eb022f37344dc7a80f7a0f243de5d7", "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": "test/tests.cpp", "max_forks_repo_name": "suhasghorp/jason-cpp-starter", "max_forks_repo_head_hexsha": "e035326575eb022f37344dc7a80f7a0f243de5d7", "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.3684210526, "max_line_length": 71, "alphanum_fraction": 0.6612244898, "num_tokens": 763, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432182679956, "lm_q2_score": 0.6825737473266736, "lm_q1q2_score": 0.4926429731007991}}
{"text": "// Created by Dinies on 23/11/2018.\n\n#pragma once\n#include <unistd.h>\n#include <Eigen/Core>\n\nnamespace MultiRobot {\n\n\n  class Gaussian{\n    private:\n\n    double m_expFactor;\n    Eigen::Vector2d m_center;\n\n    public:\n    Gaussian( const double t_expFactor, const Eigen::Vector2d &t_center );\n\n    double eval( const double t_x, const double t_y);\n\n    double computeDistrib( const double t_x, const double t_center);\n  };\n}\n\n      \n\n\n", "meta": {"hexsha": "a9fa3497f4f4c552a47f50b8d232b73e7905fa78", "size": 434, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "code/src/Gaussian.hpp", "max_stars_repo_name": "dinies/MultiRobot", "max_stars_repo_head_hexsha": "eaf3cb34ce7baf5653bf54b31bffe02426885060", "max_stars_repo_licenses": ["MIT"], "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/src/Gaussian.hpp", "max_issues_repo_name": "dinies/MultiRobot", "max_issues_repo_head_hexsha": "eaf3cb34ce7baf5653bf54b31bffe02426885060", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/src/Gaussian.hpp", "max_forks_repo_name": "dinies/MultiRobot", "max_forks_repo_head_hexsha": "eaf3cb34ce7baf5653bf54b31bffe02426885060", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.5, "max_line_length": 74, "alphanum_fraction": 0.6797235023, "num_tokens": 110, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.49264296026969784}}
{"text": "#include <catch.hpp>\n#include <tmock.hpp>\n\n#include <boost/filesystem.hpp>\n\nunsigned int Factorial1( unsigned int number ) {\n    return number <= 1 ? number : Factorial1(number-1)*number;\n}\n\nTEST_CASE( \"Factorials are computed once more\", \"[factorial]\" ) \n{\n    REQUIRE( Factorial1(1) == 1 );\n    REQUIRE( Factorial1(2) == 2 );\n    REQUIRE( Factorial1(3) == 6 );\n    REQUIRE( Factorial1(10) == 3628800 );\n}\n\nTEST_CASE(\"Cmake has placed data correctly\", \"\")\n{\n    CHECK(boost::filesystem::exists( \"./test_data/example_test_catch/test1/data.txt\" ));\n}\n", "meta": {"hexsha": "e507cebcc339f2ae354d7fc96aa252f656bc3a44", "size": 550, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/example_catch/source/some_test.cpp", "max_stars_repo_name": "variar/contest-template", "max_stars_repo_head_hexsha": "bad78a60fd32b3b66035cb064838663c39b38bc2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-09-09T01:50:13.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-09T01:50:31.000Z", "max_issues_repo_path": "tests/example_catch/source/some_test.cpp", "max_issues_repo_name": "variar/contest-template", "max_issues_repo_head_hexsha": "bad78a60fd32b3b66035cb064838663c39b38bc2", "max_issues_repo_licenses": ["MIT"], "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/example_catch/source/some_test.cpp", "max_forks_repo_name": "variar/contest-template", "max_forks_repo_head_hexsha": "bad78a60fd32b3b66035cb064838663c39b38bc2", "max_forks_repo_licenses": ["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.0, "max_line_length": 88, "alphanum_fraction": 0.6654545455, "num_tokens": 155, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.682573734412324, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.49264295969461536}}
{"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//! @ingroup openOR_core_math\n\n#ifndef openOR_core_Math_matrix_types_hpp\n#define openOR_core_Math_matrix_types_hpp\n\n#include <boost/numeric/ublas/fwd.hpp>\n\nnamespace openOR {\n   namespace Math {\n      \n      //----------------------------------------------------------------------------\n      // convenience typedefs\n      //----------------------------------------------------------------------------    \n\n      typedef boost::numeric::ublas::bounded_matrix<int, 2, 2, boost::numeric::ublas::column_major>          Matrix22i;    //!< @ingroup openOR_core_math\n      typedef boost::numeric::ublas::bounded_matrix<unsigned int, 2, 2, boost::numeric::ublas::column_major> Matrix22ui;   //!< @ingroup openOR_core_math\n      typedef boost::numeric::ublas::bounded_matrix<float, 2, 2, boost::numeric::ublas::column_major>        Matrix22f;    //!< @ingroup openOR_core_math\n      typedef boost::numeric::ublas::bounded_matrix<double, 2, 2, boost::numeric::ublas::column_major>       Matrix22d;    //!< @ingroup openOR_core_math\n\n      typedef boost::numeric::ublas::bounded_matrix<int, 3, 3, boost::numeric::ublas::column_major>          Matrix33i;    //!< @ingroup openOR_core_math\n      typedef boost::numeric::ublas::bounded_matrix<unsigned int, 3, 3, boost::numeric::ublas::column_major> Matrix33ui;   //!< @ingroup openOR_core_math\n      typedef boost::numeric::ublas::bounded_matrix<float, 3, 3, boost::numeric::ublas::column_major>        Matrix33f;    //!< @ingroup openOR_core_math\n      typedef boost::numeric::ublas::bounded_matrix<double, 3, 3, boost::numeric::ublas::column_major>       Matrix33d;    //!< @ingroup openOR_core_math\n\n      typedef boost::numeric::ublas::bounded_matrix<int, 4, 4, boost::numeric::ublas::column_major>          Matrix44i;    //!< @ingroup openOR_core_math\n      typedef boost::numeric::ublas::bounded_matrix<unsigned int, 4, 4, boost::numeric::ublas::column_major> Matrix44ui;   //!< @ingroup openOR_core_math\n      typedef boost::numeric::ublas::bounded_matrix<float, 4, 4, boost::numeric::ublas::column_major>        Matrix44f;    //!< @ingroup openOR_core_math\n      typedef boost::numeric::ublas::bounded_matrix<double, 4, 4, boost::numeric::ublas::column_major>       Matrix44d;    //!< @ingroup openOR_core_math\n\n   }\n}\n\n#endif\n", "meta": {"hexsha": "8f5c5599c07260067b0472fed330e5d1cd9c979d", "size": 2769, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/core/include/openOR/Math/matrix_types.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/matrix_types.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/matrix_types.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": 61.5333333333, "max_line_length": 153, "alphanum_fraction": 0.5984109787, "num_tokens": 666, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432182679956, "lm_q2_score": 0.6825737214979745, "lm_q1q2_score": 0.4926429544591106}}
{"text": "// C_error_policy_example.cpp\n\n// Copyright Paul A. Bristow 2007, 2010.\n// Copyright John Maddock 2007.\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// Suppose we want a call to tgamma  to behave in a C-compatible way\n// and set global ::errno rather than throw an exception.\n\n#include <cerrno> // for ::errno\n\n#include <boost/math/special_functions/gamma.hpp>\nusing boost::math::tgamma;\n\nusing boost::math::policies::policy;\n// Possible errors\nusing boost::math::policies::overflow_error;\nusing boost::math::policies::underflow_error;\nusing boost::math::policies::domain_error;\nusing boost::math::policies::pole_error;\nusing boost::math::policies::denorm_error;\nusing boost::math::policies::evaluation_error;\n\nusing boost::math::policies::errno_on_error;\nusing boost::math::policies::ignore_error;\n\n//using namespace boost::math::policies;\n//using namespace boost::math; // avoid potential ambiguity with std:: <random>\n\n// Define a policy:\ntypedef policy<\n      domain_error<errno_on_error>, // 'bad' arguments.\n      pole_error<errno_on_error>, // argument is pole value.\n      overflow_error<errno_on_error>, // argument value causes overflow.\n      evaluation_error<errno_on_error>  // evaluation does not converge and may be inaccurate, or worse,\n      // or there is no way  known (yet) to implement this evaluation,\n      // for example, kurtosis of non-central beta distribution.\n      > C_error_policy;\n\n// std\n#include <iostream>\n   using std::cout;\n   using std::endl;   \n\nint main()\n{\n  // We can achieve this at the function call site\n  // with the previously defined policy C_error_policy.\n  double t = tgamma(4., C_error_policy());\n  cout << \"tgamma(4., C_error_policy() = \" << t << endl; // 6\n\n  // Alternatively we could use the function make_policy,\n  // provided for convenience,\n  // and define everything at the call site:\n  t = tgamma(4., make_policy(\n         domain_error<errno_on_error>(), \n         pole_error<errno_on_error>(),\n         overflow_error<errno_on_error>(),\n         evaluation_error<errno_on_error>() \n      ));\n  cout << \"tgamma(4., make_policy(...) = \" << t << endl; // 6\n\n  return 0;\n} // int main()\n\n/*\n\nOutput\n\n  c_error_policy_example.cpp\n  Generating code\n  Finished generating code\n  c_error_policy_example.vcxproj -> J:\\Cpp\\MathToolkit\\test\\Math_test\\Release\\c_error_policy_example.exe\n  tgamma(4., C_error_policy() = 6\n  tgamma(4., make_policy(...) = 6\n  tgamma(4., C_error_policy() = 6\n  tgamma(4., make_policy(...) = 6\n\n*/\n", "meta": {"hexsha": "73ae024b05556f8d4e6e20d79c9439b76605bc09", "size": 2625, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/c_error_policy_example.cpp", "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": "3rdparty/boost_1_73_0/libs/math/example/c_error_policy_example.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "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": "3rdparty/boost_1_73_0/libs/math/example/c_error_policy_example.cpp", "max_forks_repo_name": "qingkouwei/mediaones", "max_forks_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_forks_repo_licenses": ["MIT"], "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": 31.25, "max_line_length": 104, "alphanum_fraction": 0.7066666667, "num_tokens": 676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.682573734412324, "lm_q2_score": 0.721743200312399, "lm_q1q2_score": 0.4926429515239362}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n// Unit Test\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// 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// 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\r\n#if defined(_MSC_VER)\r\n#pragma warning( disable : 4305 ) // truncation double -> float\r\n#endif // defined(_MSC_VER)\r\n\r\n\r\n#define BOOST_GEOMETRY_SRS_ENABLE_STATIC_PROJECTION_HYBRID_INTERFACE\r\n\r\n#include <geometry_test_common.hpp>\r\n\r\n#include <boost/geometry/srs/projection.hpp>\r\n\r\n#include <boost/geometry/algorithms/transform.hpp>\r\n#include <boost/geometry/core/coordinate_type.hpp>\r\n\r\n#include <boost/geometry/geometries/geometries.hpp>\r\n#include <boost/geometry/geometries/point_xy.hpp>\r\n#include <boost/geometry/geometries/adapted/c_array.hpp>\r\n#include <test_common/test_point.hpp>\r\n\r\n\r\nnamespace srs = bg::srs;\r\n\r\ntemplate <typename P1, typename P2, typename Params>\r\nvoid test_one(double lon, double lat,\r\n              typename bg::coordinate_type<P2>::type x,\r\n              typename bg::coordinate_type<P2>::type y,\r\n              Params const& params)\r\n{\r\n    // hybrid interface disabled by default\r\n    // static_proj4 default ctor, dynamic parameters passed\r\n    srs::projection<Params> prj(params);\r\n\r\n    P1 ll;\r\n    bg::set<0>(ll, lon);\r\n    bg::set<1>(ll, lat);\r\n\r\n    P2 xy;\r\n    prj.forward(ll, xy);\r\n\r\n    BOOST_CHECK_CLOSE(bg::get<0>(xy), x, 0.001);\r\n    BOOST_CHECK_CLOSE(bg::get<1>(xy), y, 0.001);\r\n}\r\n\r\ntemplate <typename P>\r\nvoid test_all()\r\n{\r\n    typedef typename bg::coordinate_type<P>::type coord_type;\r\n    typedef bg::model::point<coord_type, 2, bg::cs::geographic<bg::degree> > point_type;\r\n\r\n    using namespace srs::spar;\r\n\r\n    // aea\r\n    test_one<point_type, P>\r\n        (4.897000, 52.371000, 334609.583974, 5218502.503686,\r\n         parameters<proj_aea, ellps_wgs84, units_m, lat_1<>, lat_2<> >(\r\n             proj_aea(), ellps_wgs84(), units_m(), lat_1<>(55), lat_2<>(65)));\r\n}\r\n\r\nBOOST_GEOMETRY_REGISTER_C_ARRAY_CS(bg::cs::cartesian)\r\n\r\nint test_main(int, char* [])\r\n{\r\n    //test_all<int[2]>();\r\n    test_all<float[2]>();\r\n    test_all<double[2]>();\r\n\r\n    // 2D -> 3D\r\n    //test_all<test::test_point>();\r\n    \r\n    //test_all<bg::model::d2::point_xy<int> >();\r\n    test_all<bg::model::d2::point_xy<float> >();\r\n    test_all<bg::model::d2::point_xy<double> >();\r\n    test_all<bg::model::d2::point_xy<long double> >();\r\n\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "f5ec5bd5229e4c55acf5235585c3d4ef8b9d7360", "size": 2989, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/libs/geometry/test/srs/projection.cpp", "max_stars_repo_name": "Jackarain/tinyrpc", "max_stars_repo_head_hexsha": "07060e3466776aa992df8574ded6c1616a1a31af", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "third_party/boost/libs/geometry/test/srs/projection.cpp", "max_issues_repo_name": "avplayer/cxxrpc", "max_issues_repo_head_hexsha": "7049b4079fac78b3828e68f787d04d699ce52f6d", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-04T18:00:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-04T18:00:00.000Z", "max_forks_repo_path": "third_party/boost/libs/geometry/test/srs/projection.cpp", "max_forks_repo_name": "avplayer/cxxrpc", "max_forks_repo_head_hexsha": "7049b4079fac78b3828e68f787d04d699ce52f6d", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 31.1354166667, "max_line_length": 89, "alphanum_fraction": 0.6697892272, "num_tokens": 829, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217431943271999, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.4926429474385966}}
{"text": "#include <bits/types/FILE.h>\n#include <fstream>\n#include <iostream>\n#include <stdio.h>\n#include <vector>\n#include <string>\n#include <tgmath.h>\n#include \"image_ppm.h\"\n#include <filesystem>\n#include <Eigen/Dense>\n\nusing namespace std;\nusing namespace Eigen;\n\ntypedef Matrix<u_char, Dynamic, Dynamic> MatrixImg;\ntypedef Matrix<double, Dynamic, Dynamic> TempMatrixImg;\ntypedef Vector<u_char,Dynamic> ImgLine;\ntypedef Vector<double,Dynamic> TempImgLine;\n//typedef Matrix<ImgLine,Dynamic,Dynamic> FlattenedImages;\n\n\n\nunsigned char max(u_char a, u_char b){\n    if (a<b) return b;\n    else return a;\n}\n\nunsigned char min(u_char a, u_char b){\n    if (a>b) return b;\n    else return a;\n}\n\n\ndouble max(double a, double b){\n    if (a<b) return b;\n    else return a;\n}\n\ndouble min(double a, double b){\n    if (a>b) return b;\n    else return a;\n}\n\nint max(int a, int b){\n    if (a<b) return b;\n    else return a;\n}\n\nint min(int a, int b){\n    if (a>b) return b;\n    else return a;\n}\n\n\n\nvector<double> projectOnEigenSpace(vector<TempImgLine> eigenfaces, TempImgLine imToProj,int K){\n    vector<double> res = vector<double>();\n    for (int i=0;i<K;i++){\n        res.push_back(eigenfaces[i].dot(imToProj));\n    }\n    return res;\n}\n\nImgLine octToVec(OCTET* im, int nH, int nW){\n    ImgLine res(nH*nW);\n    for (int i=0; i<nH*nW;i++){\n        res(i)=im[i];\n    }\n    return res;\n}\n\ndouble eigenProjsDistance(vector<double> proj1, vector<double> proj2){\n\n    double res =0.0;\n    for (int i=0; i<min(proj1.size(),proj2.size());i++){\n        res+=(proj1[i]-proj2[i])*(proj1[i]-proj2[i]);\n    }\n    return res;\n}\n\n\n\nint main(int argc, char* argv[]){\n\n\n    //recup eigenfaces\n    \n    vector<TempImgLine> eigenfaces;\n    int K =200; int nH;int nW;\n\n    for (int i=0; i<K;i++){\n        OCTET* im;\n        char name[50];\n        sprintf(name,\"out/eigenfaces/im%d.pgm\",i);\n        lire_nb_lignes_colonnes_image_pgm(name,&nH,&nW);\n        allocation_tableau(im,OCTET,nH*nW);\n        lire_image_pgm(name,im,nH*nW);\n        TempImgLine eigenFace(nH*nW) ;\n        double sum=0.0;\n        for (int j=0;j<nH*nW;j++){\n            eigenFace(j)=im[j]-127;\n            sum+=(double)(im[j]-127)*(double)(im[j]-127);\n        }\n        for (int j=0;j<nH*nW;j++){\n            eigenFace(j)=eigenFace(j)/sqrt(sum);\n            }\n        eigenfaces.push_back(eigenFace);\n        free(im);\n    }\n\n    string dirIn = string(argv[1]);\n\n    //vector<vector<int*>> histos = vector<vector<int*>>(); \n\n    vector<vector<vector<double>>> registre = vector<vector<vector<double>>>();\n\n    int countDirs =0;\n    for (auto & dir : std::filesystem::directory_iterator(dirIn)){\n        registre.push_back(vector<vector<double>>());\n        int countFile=0;\n        for (auto & file : std::filesystem::directory_iterator(dir.path())){\n            OCTET* img;\n            lire_nb_lignes_colonnes_image_pgm(file.path().c_str(),&nH,&nW);\n            TempImgLine imgLine(nH*nW);            \n            allocation_tableau(img,OCTET, nH*nW);\n            lire_image_pgm(file.path().c_str(),img,nH*nW);\n            double sumIm=0.0;\n            for (int i=0;i<nH*nW;i++){sumIm+=(double)(img[i]-127)*(double)(img[i]-127);}\n            for (int i=0; i<nH*nW;i++){imgLine(i)=(double)(img[i]-127)/sumIm;}\n            registre[countDirs].push_back(projectOnEigenSpace(eigenfaces,imgLine,K));\n\n            countFile++;\n        }\n        countDirs++;\n    }\n\n    for (double threshold=0.0;threshold<0.0000005;threshold+=0.00000001){\n        int VP=0,VN=0,FP=0,FN=0;\n\n        for (int i=0;i<registre.size();i++){\n            for (int j=0; j<registre[i].size();j++){\n                for (int ip=0;ip<registre.size();ip++){\n                    for (int jp=0;jp<registre[ip].size();jp++){\n                        if (!(i==ip && j==jp)){\n                            //cout<<eigenProjsDistance(registre[i][j],registre[ip][jp])<<endl;\n                            if (eigenProjsDistance(registre[i][j],registre[ip][jp])<threshold){\n                                if (i==ip){\n                                    VP++;\n                                }\n                                else{\n                                    FP++;\n                                }\n                            }\n\n                        else{\n                                if (i==ip){\n                                    FN++;\n                                }\n                                else{\n                                    VN++;\n                                }\n                            }\n\n                        }\n                    }\n                }\n            }\n        }\n\n        double sensitivite = (double)((double)VP/(double)(VP+FN));\n        double antispecificite = 1.0-(double)((double)VN/(double)(VN+FP));\n        double distance = antispecificite*antispecificite + (1-sensitivite)*(1-sensitivite);\n        cout<<antispecificite<<\" \"<<sensitivite<<\" \"<<distance<<\" \"<<threshold<<endl;\n    }\n\n}", "meta": {"hexsha": "5c734134504440ebe4b4f85222e192f954f73df4", "size": 4932, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Code/eigenThreshold.cpp", "max_stars_repo_name": "JPhilippot/FaceRecognition", "max_stars_repo_head_hexsha": "12a657d05f0103b0193a28a6347d1f41f466f0d0", "max_stars_repo_licenses": ["MIT"], "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/eigenThreshold.cpp", "max_issues_repo_name": "JPhilippot/FaceRecognition", "max_issues_repo_head_hexsha": "12a657d05f0103b0193a28a6347d1f41f466f0d0", "max_issues_repo_licenses": ["MIT"], "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/eigenThreshold.cpp", "max_forks_repo_name": "JPhilippot/FaceRecognition", "max_forks_repo_head_hexsha": "12a657d05f0103b0193a28a6347d1f41f466f0d0", "max_forks_repo_licenses": ["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.0227272727, "max_line_length": 95, "alphanum_fraction": 0.5150040552, "num_tokens": 1288, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.831143060406073, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4925907316862873}}
{"text": "\n#include <carma>\n#include <armadillo>\n\n#include <pybind11/pybind11.h>\n#include <pybind11/stl.h>\n#include <pybind11/numpy.h>\n#include <cmath> // fabs\n#include <chrono>\n#include <limits>\n#include \"svd_3x3.h\" // fast 3x3 svd\n#include \"carma_svd.h\" // fast 3x3 svd using carma\n\n\nusing namespace std::chrono;\nusing std::vector; \n\nusing namespace pybind11::literals;\nnamespace py = pybind11;\n\n// Compile command: g++ -O3 -Wall -shared -std=c++17 -fPIC -Wl,-undefined,dynamic_lookup $(python3 -m pybind11 --includes) example.cpp -o example$(python3-config --extension-suffix)\n\nconstexpr auto rank_comb2(size_t i, size_t j, size_t n) noexcept -> size_t { \n  if (j < i){ std::swap(i,j); }\n  return(size_t(n*i - i*(i+1)/2 + j - i - 1));\n}\n\ninline std::array< size_t, 2 > unrank_comb2(const size_t x, const size_t n) noexcept {\n\tauto i = static_cast< size_t >( (n - 2 - floor(sqrt(-8*x + 4*n*(n-1)-7)/2.0 - 0.5)) );\n\tauto j = static_cast< size_t >( x + i + 1 - n*(n-1)/2 + (n-i)*((n-i)-1)/2 );\n\treturn (std::array< size_t, 2 >{ i, j });\n}\n\n// Require column-major layout (AoS - Fortran style)\nusing np_array_t = py::array_t< float, py::array::f_style | py::array::forcecast >;\n\n// Evaluations a cost function quickly \nstruct StiefelLoss {\n\tusing index_mat_map = std::unordered_map< size_t, arma::mat >;\n\tconst size_t n; // number of points\n\tconst size_t d; // intrinsic dimension \n\tconst size_t D; // target dimension of coordinatization\n\tindex_mat_map rotations; // stores the rotation matrices (Omega)\n\t\n\tarma::mat frames; // all column-stacked frames (dJ x dn) for some choice of iota, weighted by PoU\n\tarma::sp_mat frames_sparse; // same as frames, but as sp_mat. Only one should be used\n\n\tarma::sp_mat pou; // (J x n) partition of unity\n\tnp_array_t output; // preallocated output for (A^T x Phi) => (D x dn)\n\n\n\tStiefelLoss(int n_points, int dim, int target_dim) : n(n_points), d(dim), D(target_dim) {\n\t\toutput = np_array_t({ D, d*n });\n\t}\n\n\t// Assuming output contains the result of (A^* x Phi)\n\tauto gradient(const py::array_t< double >& At, bool normalize=false) -> std::list< np_array_t > {\n\t\t\n\t\t// First project the alignment to a D-dimensional space\n\t\tarma::Mat< double > A_star { carma::arr_to_mat< double >(At) };\n\t\toutput = carma::mat_to_arr< double >(A_star * frames);\n\t\t\n\t\t// Calculate all the SVDs\n\t\t// const size_t J = frames.n_rows / d;\n\t\tauto nuclear_norm = (float) 0.0;\n\t\tauto G = arma::mat(D, d*n);\n\t\tauto i = size_t(0);\n\t\tarma::mat S = arma::zeros(D, d);\n\t\tfast_svd_stream(output, d, [this, &i, &G, &S, &nuclear_norm](np_array_t& u, np_array_t& s, np_array_t& vt){\n\t\t\tauto u_copy = py::array_t< double >(u);\n\t\t\tauto v_copy = py::array_t< double >(vt);\n\t\t\tauto s_copy = py::array_t< double >(s);\n\t\t\tarma::mat U { carma::arr_to_mat< double >(u_copy, true) };\n\t\t\tS.diag() = carma::arr_to_col< double >(s_copy, true);\n\t\t\tarma::mat V { carma::arr_to_mat< double >(v_copy, true) };\n\t\t\t// py::print(U.n_rows, U.n_cols, S.n_rows, S.n_cols, V.n_rows, V.n_cols);\n\t\t\tG(arma::span::all, arma::span(i, i+d-1)) = U * S * V; // TODO: transpose?\n\t\t\tnuclear_norm += arma::trace(S);\n\t\t\ti += d;\n\t\t});\n\t\t// Calculate gradient\n\t\tarma::mat GF = frames * G.t(); // (dJ x dn)*(dn x D) => (dJ x D)\n\t\tif (normalize){\n\t\t\tGF /= n;\n\t\t\tnuclear_norm /= n;\n\t\t}\n\t\tauto out = std::list< np_array_t >();\n\t\tout.push_back(carma::mat_to_arr(arma::Mat< float >(&nuclear_norm, 1, 1)));\n\t\tout.push_back(carma::mat_to_arr(GF));\n\t\treturn(out);\n\t}\n\n\t// Populate the O(J^2)-sized hashmap mapping index pairs i,j \\in J -> rotation matrices\n\t// omega_ is expected to contain the vertically-stacked d-d rotation matrices corresponding to each (i,j) pair\n\tvoid init_rotations(py::list I_ind, py::list J_ind, py::array_t< double > omega_, const size_t J){\n\t\tstd::vector< size_t > I1 = py::cast< std::vector< size_t > >(I_ind);\n\t\tstd::vector< size_t > I2 = py::cast< std::vector< size_t > >(J_ind);\n\t\t// np_array_t O = static_cast< np_array_t >(omega_);\n\t\tarma::mat omega = carma::arr_to_mat< double >(omega_, true);\n\t\tfor (size_t j = 0; j < I1.size(); ++j){\n\t\t\tsize_t ii = I1[j], jj = I2[j];\n\t\t\tsize_t key = rank_comb2(ii,jj,J);\n\t\t\tarma::mat R = omega(arma::span(j*d, (j+1)*d-1), arma::span::all);\n\t\t\trotations.emplace(key, R);\n\t\t}\n\t}\n\n\tauto get_rotation(const size_t i, const size_t j, const size_t J) -> py::array_t< double > {\n\t\tsize_t key = rank_comb2(i,j,J);\n\t\tif (rotations.find(key) != rotations.end()){\n\t\t\treturn(carma::mat_to_arr(rotations[key], true));\n\t\t}\n\t\tthrow std::invalid_argument(\"Invalid key given\");\n\t}\n\t\n\t// Generates a weighted (dJ x d) frame relative to some origin subset \n\t// This is equivalent to Phi_{origin}(x) where 'weights' are specific to 'x'\n\tauto generate_frame(const size_t origin, py::array_t< double > weights) -> py::array_t< double > {\n\t\tconst size_t J = weights.size();\n\t\tarma::mat d_frame(d*J, d, arma::fill::zeros); // output \n\t\tvector< double > weights_vec = weights.cast< vector< double > >();\n\t\tgenerate_frame_(origin, weights_vec, d_frame);\n\t\treturn(carma::mat_to_arr< double >(d_frame, true));\n\t}\n\n\t// This generates a given dense (dJ x d) frame with the weighted rotation matrices given in the 'rotations' table\n\t// Note: this applies sqrt to the phi weights! \n\t// TODO: should the weights be sqrt'ed on identity matrices? Assume yes.\n\t// TODO: consider filling a (d x dJ) matrix instead to be more cache-friendly\n\tvoid generate_frame_(const size_t origin, const vector< double >& weights, arma::mat& d_frame) {\n\t\tconst size_t J = weights.size();\t\n\t\tarma::mat I = arma::eye(d, d);\n\n\t\t// This fills up the (dJ x d) frame one (d x d) matrix at a time \n\t\tfor (size_t j = 0; j < J; ++j){\n\t\t\tauto r_rng = arma::span(j*d,(j+1)*d-1); \n\t\t\tif (j == origin){ \n\t\t\t\td_frame(r_rng, arma::span::all) = std::sqrt(weights[j]) * I; \n\t\t\t\tcontinue;\n\t\t\t} else if (weights[j] == 0.0){\n\t\t\t\td_frame(r_rng, arma::span::all) = std::sqrt(weights[j]) * I; \n\t\t\t\tcontinue; \n\t\t\t} else {\n\t\t\t\t// If pair exists, load it up, otherwise use identity\n\t\t\t\tconst size_t key = rank_comb2(origin, j, J); \n\t\t\t\tbool key_exists = rotations.find(key) != rotations.end();\n\t\t\t\td_frame(r_rng, arma::span::all) = std::sqrt(weights[j])*(key_exists ? (origin < j ? rotations[key] : rotations[key].t()) : I);\n\t\t\t}\n\t\t}\n\t}\n\n\t// This generates a given dense (d x dJ) frame with the weighted rotation matrices given in the 'rotations' table\n\t// Note: this applies sqrt to the phi weights! \n\tvoid generate_frame_T(const size_t origin, const vector< double >& weights, arma::mat& d_frame) {\n\t\tconst size_t J = weights.size();\t\n\t\tarma::mat I = arma::eye(d, d);\n\n\t\t// This fills up the (d x dJ) frame one (d x d) matrix at a time (column-wise)\n\t\tfor (size_t j = 0; j < J; ++j){\n\t\t\tauto c_rng = arma::span(j*d,(j+1)*d-1); \n\t\t\tauto weight = std::sqrt(weights[j]);\n\t\t\tif (j == origin || weights[j] == 0.0){ \n\t\t\t\td_frame(arma::span::all, c_rng) = std::sqrt(weights[j]) * I; \n\t\t\t\tcontinue;\n\t\t\t} else {\n\t\t\t\t// If pair exists, load it up, otherwise use identity\n\t\t\t\tconst size_t key = rank_comb2(origin, j, J); \n\t\t\t\tbool key_exists = rotations.find(key) != rotations.end();\n\t\t\t\td_frame(arma::span::all, c_rng) = weight *  (key_exists ? (origin < j ? rotations[key] : rotations[key].t()) : I);\n\t\t\t}\n\t\t}\n\t}\n\n\t// TODO: come back to this to fix the populate_frames functions efficiency\n\ttemplate< typename OutputIt1, typename OutputIt2 >\n\tinline void generate_frame_ijx(const size_t origin, const size_t j, const size_t J, const double weight, const size_t col_offset, OutputIt1 RC, OutputIt2 X){\n\t\t\n\t\t// For each cover set, detect whether there exists rotation matrices to transform between them\n\t\tif (j == origin){ \n\t\t\tconst size_t row_offset = (j*d);\n\t\t\tauto w = std::sqrt(weight);\n\t\t\tfor (size_t ri = 0; ri < d; ++ri){\n\t\t\t\t// py::print(\"row: \", row_offset + ri, \", col: \", col_offset + ri, \", val: \", weight);\n\t\t\t\t*RC++ = row_offset + ri; // row index of non-zero element\n\t\t\t\t*RC++ = col_offset + ri; // column index of non-zero element\n\t\t\t\t*X++ = w;\n\t\t\t}\n\t\t} else { // j != origin and weights[j] > 0\n\t\t\tconst size_t row_offset = (j*d), key = rank_comb2(origin, j, J); \n\t\t\tauto w = std::sqrt(weight);\n\t\t\t\n\t\t\t// If key exists, there's a non-empty intersection between the cover sets (i,j)\n\t\t\t// otherwise, just use the (weighted) identity matrix\n\t\t\tbool key_exists = rotations.find(key) != rotations.end();\n\t\t\tif (!key_exists){\n\t\t\t\tfor (size_t ri = 0; ri < d; ++ri){\n\t\t\t\t\t// py::print(\"row: \", row_offset + ri, \", col: \", col_offset + ri, \", val: \", weight);\n\t\t\t\t\t*RC++ = row_offset + ri; // row index of non-zero element\n\t\t\t\t\t*RC++ = col_offset + ri; // column index of non-zero element\n\t\t\t\t\t*X++ = w;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tconst arma::mat& omega = origin < j ? rotations[key] : rotations[key].t();\n\t\t\t\tarma::umat nz_ind = arma::ind2sub(arma::size(omega), arma::find(omega != 0.0));\n\t\t\t\tnz_ind.each_col([&](arma::uvec& a){ \n\t\t\t\t\t// py::print(\"| row: \", row_offset + a[0], \", col: \", col_offset + a[1], \", val: \", omega(a[0], a[1]));\n\t\t\t\t\t*RC++ = row_offset + a[0];\n\t\t\t\t\t*RC++ = col_offset + a[1];\n\t\t\t\t\t*X++ = w*omega(a[0], a[1]);\n\t\t\t\t});  \n\t\t\t}\n\t\t}\n\t}\n\n\n\t// Using the rotations from the omega map, initialize the phi matrix representing the concatenation \n\t// of the weighted frames for some choice of iota \n\t// py::array_t< double > iota, bool sparse = false\n\tvoid populate_frame(const size_t i, py::array_t< double > weights, bool sparse = false){\n\t\t// if (iota.size() != n || weights.size() != ){\n\t\t// \tthrow std::invalid_argument(\"Invalid input. Must have one weight for each cover element.\")\n\t\t// }\n\t\tconst size_t J = weights.size();\n\t\tauto w = weights.unchecked< 1 >();\n\t\t\n\t\t// Find the reference frame\n\t\tsize_t k = 0; \n\t\tdouble max_weight = 0.0; \n\t\tfor (size_t j = 0; j < J; ++j){\n\t\t\tif (w(j) > max_weight){\n\t\t\t\tmax_weight = w(j);\n\t\t\t\tk = j; \n\t\t\t}\n\t\t}\n\n\t\tif (sparse && frames_sparse.is_empty()){\n\t\t\tframes_sparse.resize(d*J, d*n);\n\t\t} else if (!sparse && frames.is_empty()){\n\t\t\tframes.resize(d*J, d*n);\n\t\t}\t \n\n\t\tpy::array_t< double > _d_frame = generate_frame(k, weights);\n\t\tarma::mat d_frame = carma::arr_to_mat(_d_frame, true);\n\n\t\t// arma::mat d_frame(d*J, d); // output \n\t\t// arma::mat I = arma::eye(d, d);\n\t\t// for (size_t j = 0; j < J; ++j){\n\t\t// \tauto r_rng = arma::span(j*d,(j+1)*d-1); \n\t\t// \tif (j == k){ d_frame(r_rng, arma::span::all) = I; }\n\t\t\t\n\t\t// \t// If pair exists, load it up, otherwise use identity\n\t\t// \tsize_t key = rank_comb2(k, j, J); \n\t\t// \tbool key_exists = rotations.find(key) != rotations.end();\n\t\t// \td_frame(r_rng, arma::span::all) = double(w(j))*(key_exists ? (k < j ? rotations[key] : rotations[key].t()) : I);\n\t\t// }\n\n\t\t// Assign the frame to right position in the frames matrix\n\t\tif (sparse){\n\t\t\tframes_sparse(arma::span::all, arma::span(i*d, (i+1)*d-1)) = d_frame; \n\t\t} else {\n\t\t\tframes(arma::span::all, arma::span(i*d, (i+1)*d-1)) = d_frame; \n\t\t}\n\t}\n\n\tvoid setup_pou(py::object& P_csc){\n\t\tto_sparse(P_csc, pou);\n\t}\n\t\t\n\tauto extract_iota(){\n\t\tif (pou.is_empty()){ throw std::invalid_argument(\"Partition of unity matrix not populated.\"); }\n\t\t// weights.assign(J, 0.0);\n\t\t// auto ci = pou_.begin_col(i);\n\t\t// for (; ci != pou_.end_col(i); ++ci){ weights[ci.row()] = *ci; }\n\t\t// size_t iota_i = std::distance(weights.begin(), std::max_element(weights.begin(), weights.end()));\n\t\tarma::urowvec u = arma::index_max(pou,0);\n\t\treturn(carma::row_to_arr< unsigned long long >(std::move(u)));\n\t}\n\n\t// Populate the 'frames_sparse' arma::sp_mat member variable using the iota bijection\n\t// Postcondition: self.frames_sparse is a sparse (dJ x dn) matrix representing the horizontal concatenation of all the Phi's for each x \\in X\n\tvoid populate_frames_sparse(py::array_t< arma::uword >& iota){\n\t\tif (pou.n_cols != n){ throw std::invalid_argument(\"Invalid input. Must have one weight for each cover element.\"); }\n\t\tconst size_t J = pou.n_rows;\n\t\tarma::uvec I = carma::arr_to_col(iota, true);\n\n\t\t// Prepare the vectors needed to construct the sparse matrix using COO-input \n\t\tvector< arma::uword > RC; \n\t\tvector< double > X;\n\t\tRC.reserve(2*d*d*n);\n\t\tX.reserve(d*d*n);\n\n\t\t// Output iterators\n\t\tauto rc_out = std::back_inserter(RC);\n\t\tauto x_out = std::back_inserter(X);\n\n\t\t// Generate all the frames using iota\n\t\tfor (size_t i = 0; i < n; ++i){\n\t\t\t\n\t\t\t// Iterate through sparse columns\n\t\t\tauto ci = pou.begin_col(i);\n\t\t\tfor (; ci != pou.end_col(i); ++ci){ \n\t\t\t\tgenerate_frame_ijx(I[i], ci.row(), J, *ci, i*d, rc_out, x_out);\n\t\t\t}\n\t\t}\n\t\t\n\t\t// Assign to frames_sparse\n\t\tauto locations = arma::umat(RC.data(), 2, RC.size()/2, false, true);\n\t\tframes_sparse = arma::sp_mat(std::move(locations), arma::vec(std::move(X)), d*J, d*n);\n\t} // populate_frames_sparse\n\n\t// Using the rotations from the omega map, initialize the phi matrix representing the concatenation \n\t// of the weighted frames for some *fixed* choice of iota \n\t// iota := n-length vector of indices each in [0, J) indicating the most similar cover set\n\t// pou := (J x n) sparse csc_matrix representing the partition of unity\n\t// Note the transpose! \n\t// TODO: change this to construct the sparse matrix *not* using block assignments\n\tvoid populate_frames(const py::array_t< size_t >& iota, py::object& pou, bool sparse = false){\n\t\tif (iota.size() != size_t(n)){\n\t\t\tthrow std::invalid_argument(\"Invalid input. Must have one weight for each cover element.\");\n\t\t}\n\n\t\t// Convert partition of unity to arma\n\t\tarma::sp_mat pou_;\n\t\tto_sparse(pou, pou_);\n\t\tconst size_t J = pou_.n_rows;\n\n\t\tif (sparse && frames_sparse.is_empty()){\n\t\t\tframes_sparse.resize(d*J, d*n);\n\t\t} else if (!sparse && frames.is_empty()){\n\t\t\tframes.resize(d*J, d*n);\n\t\t}\t \n\n\t\t// Generate all the frames using iota\n\t\tvector< double > weights(J, 0.0);\n\t\tarma::mat d_frame(d*J, d, arma::fill::zeros);\n\t\tfor (size_t i = 0; i < n; ++i){\n\t\t\t\n\t\t\t// Fill the weight vector\n\t\t\tweights.assign(J, 0.0);\n\t\t\tauto ci = pou_.begin_col(i);\n\t\t\tfor (; ci != pou_.end_col(i); ++ci){ weights[ci.row()] = *ci; }\n\n\t\t\t// Generate the current frame using iota to specify the origin \n\t\t\tgenerate_frame_(iota.at(i), weights, d_frame);\n\n\t\t\t// Assign the frame to right position in the frames matrix\n\t\t\tif (sparse){\n\t\t\t\tframes_sparse(arma::span::all, arma::span(i*d, (i+1)*d-1)) = d_frame; \n\t\t\t} else {\n\t\t\t\tframes(arma::span::all, arma::span(i*d, (i+1)*d-1)) = d_frame; \n\t\t\t}\n\t\t}\n\t\t\n\t\t// If sparse, make sure to clean up \n\t\tif (sparse){ frames_sparse.clean(std::numeric_limits< double >::epsilon()); }\n\t} // populate_frames\n\n\tpy::tuple initial_guess(const size_t D, bool sparse=true){\n\t\tif (sparse){\n\t\t\tif (frames_sparse.empty()) { throw std::invalid_argument(\"Frames sparse matrix has not been populated.\"); } \n\t\t\tarma::vec eigval;\n\t\t\tarma::mat eigvec;\n\t\t\tarma::eigs_sym(eigval, eigvec, frames_sparse * frames_sparse.t(), D, \"lm\"); // largest first\n\t\t\teigval = arma::reverse(eigval);\n\t\t\teigvec = arma::fliplr(eigvec);\n\t\t\treturn py::make_tuple(carma::col_to_arr(eigval), carma::mat_to_arr(eigvec));\n\t\t} else {\n\t\t\tif (frames.empty()) { throw std::invalid_argument(\"Frames matrix has not been populated.\"); } \n\t\t\tarma::vec eigval;\n\t\t\tarma::mat eigvec;\n\t\t\tarma::eig_sym(eigval, eigvec, frames * frames.t()); // largest first\n\t\t\teigval = arma::reverse(eigval);\n\t\t\teigvec = arma::fliplr(eigvec);\n\t\t\treturn py::make_tuple(carma::col_to_arr(eigval), carma::mat_to_arr(eigvec));\n\t\t}\n\t}\n\n\n\t// Returns the i'th frame of the matrix\n\tauto get_frame(const size_t i) -> py::array_t< double > {\n\t\tif (i >= n){ throw std::invalid_argument(\"Invalid index supplied.\"); }\n\t\tarma::mat d_frame = frames(arma::span::all, arma::span(i*d, (i+1)*d-1));\n\t\tpy::array_t< double > res = carma::mat_to_arr< double >(d_frame, true);\n\t\treturn(res);\n\t}\n\n\t// Returns all the frames \n\tauto all_frames() -> py::array_t< double > {\n\t\tpy::array_t< double > res = carma::mat_to_arr< double >(frames, true);\n\t\treturn(res);\n\t}\n\n\tauto all_frames_sparse() -> py::tuple {\n\t\t// py::tuple shape = S.attr(\"shape\").cast< py::tuple >();\n\t\t// const size_t nr = shape[0].cast< size_t >(), nc = shape[1].cast< size_t >();\n\t\t// S.attr(\"indices\") = py::array_t< arma::uword >();\n\t\t// S.attr(\"indptr\") = py::array_t< arma::uword >()\n\t\t// arma::uvec ind_ptr = carma::arr_to_col(.cast< py::array_t< arma::uword > >());\n\t\t// arma::vec data = carma::arr_to_col(S.attr(\"data\").cast< py::array_t< double > >());\n\t\t// out = arma::sp_mat(std::move(ind), std::move(ind_ptr), std::move(data), nr, nc);\n\n\t\t// py::array_t< double > res = carma::mat_to_arr< double >(frames, true);\n\t\t// return(res);\n\t\tframes_sparse.sync();\n\t\t//const ptr_aux_mem, number_of_elements\n\t\tauto ri = carma::col_to_arr(arma::uvec(frames_sparse.row_indices, frames_sparse.n_nonzero));\n\t\tauto cp = carma::col_to_arr(arma::uvec(frames_sparse.col_ptrs, frames_sparse.n_cols+1));\n\t\tauto x = carma::col_to_arr(arma::vec(frames_sparse.values, frames_sparse.n_nonzero));\n\t\t// auto ri = carma::col_to_arr< const arma::uword >(*frames_sparse.row_indices, true);\n\t\t// auto out = py::dict(\n\t\t// \t\"indices\"= py::array(ri), \n\t\t// \t\"indptr\"=cp, \"values\"=x);\n\t\treturn(py::make_tuple(ri, cp, x));\n\t}\n\n\n\tvoid embed(const py::array_t< double >& At){\n\t\tarma::Mat< double > A_star { carma::arr_to_mat< double >(At) };\n\t\toutput = carma::mat_to_arr< double >(A_star * frames);\n\t}\n\n\tvoid benchmark_embedding(py::array_t< double >& At, const size_t m){\n\t\tif (frames_sparse.is_empty()){ frames_sparse = arma::sp_mat(frames); }\n\t\tarma::Mat< double > A_star { carma::arr_to_mat< double >(At, true) };\n\t\t\n\t\tsize_t ms_dense = 0, ms_sparse = 0;\n\t\t\n\t\tauto start = high_resolution_clock::now();\n\t\tfor (size_t i = 0; i < m; ++i){\n\t\t\toutput = carma::mat_to_arr< double >(A_star * frames);\n\t\t}\n\t\tauto stop = high_resolution_clock::now();\n\t\tauto duration = duration_cast< milliseconds >(stop - start);\n\t\tms_dense = duration.count(); \n\n\t\tstart = high_resolution_clock::now();\n\t\tfor (size_t i = 0; i < m; ++i){\n\t\t\toutput = carma::mat_to_arr< double >(A_star * frames_sparse);\n\t\t}\n\t\tstop = high_resolution_clock::now();\n\t\tduration = duration_cast< milliseconds >(stop - start);\n\t\tms_sparse = duration.count(); \n\n\t\tpy::print(\"ms dense: \", ms_dense, \"ms sparse: \", ms_sparse);\n\t}\n\n\n\tusing index_list = vector< vector< size_t > >;\n\tusing vec_mats = vector< arma::mat >;\n\n\t// Given sorted range [b,e), finds 'element' in log time, or throws an exception if not found\n\ttemplate< typename Iter, typename T = typename Iter::value_type >\n\tauto find_index(Iter b, const Iter e, T element) -> size_t {\n\t\tauto lb = std::lower_bound(b, e, element);\n\t\tif (lb != e && (*lb == element)){\n\t\t\treturn(std::distance(b, lb));\n\t\t}\n\t\tthrow std::logic_error(\"Unable to find element in array.\");\n\t}\n\tvoid to_sparse(const py::object& S, arma::sp_mat& out){\n\t\tpy::tuple shape = S.attr(\"shape\").cast< py::tuple >();\n\t\tconst size_t nr = shape[0].cast< size_t >(), nc = shape[1].cast< size_t >();\n\t\tarma::uvec ind = carma::arr_to_col(S.attr(\"indices\").cast< py::array_t< arma::uword > >());\n\t\tarma::uvec ind_ptr = carma::arr_to_col(S.attr(\"indptr\").cast< py::array_t< arma::uword > >());\n\t\tarma::vec data = carma::arr_to_col(S.attr(\"data\").cast< py::array_t< double > >());\n\t\tout = arma::sp_mat(std::move(ind), std::move(ind_ptr), std::move(data), nr, nc);\n\t}\n\n\n\t// A := (dJ x D) dense orthonormal matrix \n\t// pou := (J x n) sparse matrix representing the transpose of the PoU\n\t// cover_subsets := (J)-length vector of sorted cover sets \n\t// local_models := (J)-length vector of column-oriented euclidean coordinate models (point for each column)\n\t// T := (D x n) matrix of translation vectors\n\t// Note: with armadillo's csc impmenentations, (dense x sparse) is faster than (sparse x dense)\n\t// Output => (D x n) matrix of the assembled coordinates\n\tvoid fast_assembly2(const arma::mat& A, const arma::sp_mat& pou, const index_list& cover_subsets, const vec_mats& local_models, const arma::mat& T, arma::mat& assembly){\n\t\t// arma::mat assembly = arma::zeros(D, n);\n\t\tarma::vec coords = arma::zeros(D);\n\t\tconst size_t J = pou.n_rows;\n\t\t\n\t\t// Variables to re-use/cache in the loop \n\t\tvector< double > phi_i(J); // the partition of unity weights for x_i \n\t\tarma::mat d_frame(d*J, d); // the current frame to populate \n\t\tarma::mat U, V;\n\t\tarma::vec s;\n\n\t\t// Build the assembly\n\t\tfor (size_t i = 0; i < n; ++i){\n\t\t\tphi_i.assign(J, 0.0);\n\t\t\tcoords.zeros();\n\n\t\t\t// Fill phi weight vector \n\t\t\tarma::sp_mat::const_col_iterator ci = pou.begin_col(i);\n\t\t\tfor (; ci != pou.end_col(i); ++ci){ phi_i[ci.row()] = *ci; }\n\n\t\t\t// Compute the weighted average of the Fj's using the partition of unity\n\t\t\tci = pou.begin_col(i);\n\t\t\tfor (; ci != pou.end_col(i); ++ci){\n\t\t\t\tsize_t j = ci.row(); \n\t\t\t\tgenerate_frame_(j, phi_i, d_frame); \t\t\t// populates the (dJ x d) frame in d_frame\n\t\t\t\tsvd_econ(U, s, V, A * (A.t() * d_frame)); // compute SVD of A A^T phi_j (U := dj x r, V := r x d, r <= d)\n\t\t\t\t\n\t\t\t\t// In cover set U_j, find the index of the local coordinate for point x_i, add the translation vector\n\t\t\t\tsize_t jj = find_index(cover_subsets[j].begin(), cover_subsets[j].end(), i); // todo: remove this\n\t\t\t\tarma::vec local_coord = local_models[j].col(jj) + T.col(j); // should be column vector\n\t\t\t\t\n\t\t\t\t// Add to the current coordinate\n\t\t\t\tcoords += ((*ci) * A.t() * U * V.t()) * local_coord; // lhs := (D x d), local coords := (d x 1)\n\t\t\t}\n\t\t\tassembly.col(i) = coords; \n\t\t}\n\t}\n\n\t// High dimensional (dJ) assembly\n\t// assembly := output (dJ x n) matrix \n\tvoid fast_assembly_high(const arma::sp_mat& pou, const index_list& cover_subsets, const vec_mats& local_models, const arma::mat& T, arma::mat& assembly){\n\t\t\n\t\tconst size_t J = pou.n_rows;\n\t\tarma::vec coords = arma::zeros(d*J);\n\t\t\n\t\t// Variables to re-use/cache in the loop \n\t\tvector< double > phi_i(J); // the partition of unity weights for x_i \n\t\tarma::mat d_frame(d*J, d); // the current frame to populate \n\n\t\t// Build the assembly\n\t\tfor (size_t i = 0; i < n; ++i){\n\t\t\tphi_i.assign(J, 0.0);\n\t\t\tcoords.zeros();\n\n\t\t\t// Fill phi weight vector \n\t\t\tarma::sp_mat::const_col_iterator ci = pou.begin_col(i);\n\t\t\tfor (; ci != pou.end_col(i); ++ci){ phi_i[ci.row()] = *ci; }\n\n\t\t\t// Compute the weighted average of the Fj's using the partition of unity\n\t\t\tci = pou.begin_col(i);\n\t\t\tfor (; ci != pou.end_col(i); ++ci){\n\t\t\t\tsize_t j = ci.row(); \n\t\t\t\tgenerate_frame_(j, phi_i, d_frame); \t\t\t// populates the (dJ x d) frame in d_frame\n\t\t\t\tsize_t jj = find_index(cover_subsets[j].begin(), cover_subsets[j].end(), i); // todo: remove this\n\t\t\t\tarma::vec local_coord = local_models[j].col(jj) + T.col(j); // should be (d)-length column vector\n\t\t\t\tcoords += (*ci) * d_frame * local_coord; // lhs := (dJ x 1), local coords := (d x 1)\n\t\t\t}\n\t\t\tassembly.col(i) = coords; \n\t\t}\n\t}\n\n\t// Uses the fast_assembly2() function. \n\t// All inputs as passed as-is to fast_assembly2; do not transpose anything here\n\tauto assemble_frames2(const py::array_t< double >& A, const py::object& pou, const py::list& cover_subsets, const py::list& local_models, const py::array_t< double >& T, bool high) -> py::array_t< double > {\n\t\tarma::mat A_ = carma::arr_to_mat(A);\n\t\t\n\t\t// Partition of unity\n\t\tarma::sp_mat pou_;\n\t\tto_sparse(pou, pou_);\n\t\tconst size_t J = pou_.n_rows;\n\n\t\t// Convert cover subsets to C++ versions\n\t\tauto subsets = vector< vector< size_t > >();\n\t\tfor (auto ind: cover_subsets){ subsets.push_back(ind.cast< vector< size_t > >()); }\n\n\t\t// Copy the local euclidean models (transposed)\t\n\t\tauto models = vector< arma::mat >();\n\t\tfor (auto pts: local_models){\n\t\t\tpy::array_t< double > pts_ = pts.cast< py::array_t< double > >();\n\t\t\tmodels.push_back(carma::arr_to_mat(pts_, true));\n\t\t}\n\n\t\t// Copy/move the translations\n\t\tarma::mat translations = carma::arr_to_mat(T);\n\t\t\n\t\t// Output assembly\n\t\tif (high){\n\t\t\tarma::mat assembly = arma::zeros(d*J, n);\n\t\t\tfast_assembly_high(pou_, subsets, models, translations, assembly);\n\t\t\treturn(carma::mat_to_arr(assembly));\t\n\t\t}\n\t\telse {\n\t\t\tarma::mat assembly = arma::zeros(D, n);\n\t\t\tfast_assembly2(A_, pou_, subsets, models, translations, assembly);\n\t\t\treturn(carma::mat_to_arr(assembly));\n\t\t}\n\t}\n\n\t// TODO: make pou and local_models transposed to access by column\n\tarma::mat fast_assembly(const arma::mat& A, const arma::sp_mat& pou, const index_list& cover_subsets, const vec_mats& local_models, const arma::mat& T){\n\t\t//py::array_t< double > phi_i = generate_frame(const size_t origin, py::array_t< double > weights);\n\t\tarma::mat assembly = arma::zeros(n, D);\n\t\tarma::vec coords = arma::zeros(D);\n\t\tconst size_t J = pou.n_cols;\n\t\t\n\t\t// Variables to re-use/cache in the loop \n\t\tvector< double > phi_i(J); // the partition of unity weights for x_i \n\t\tarma::mat d_frame(d*J, d); // the current frame to populate \n\t\tarma::mat U, V;\n\t\tarma::vec s;\n\n\t\t// Build the assembly\n\t\tfor (size_t i = 0; i < n; ++i){\n\t\t\tphi_i.assign(J, 0.0);\n\t\t\tcoords.zeros();\n\n\t\t\t// Fill phi weight vector \n\t\t\tarma::sp_mat::const_row_iterator ri = pou.begin_row(i);\n\t\t\tfor (; ri != pou.end_row(i); ++ri){ phi_i[ri.col()] = *ri; }\n\n\t\t\t// Compute the weighted average of the Fj's using the partition of unity\n\t\t\tri = pou.begin_row(i);\n\t\t\tfor (; ri != pou.end_row(i); ++ri){\n\t\t\t\tsize_t j = ri.col(); \n\t\t\t\tsize_t jj = find_index(cover_subsets[j].begin(), cover_subsets[j].end(), i);\n\t\t\t\tgenerate_frame_(j, phi_i, d_frame); \t\t\t// populates d_frame\n\t\t\t\tsvd_econ(U, s, V, A * (A.t() * d_frame)); // compute SVD of A A^T phi_j\n\t\t\t\tarma::rowvec local_coord = local_models[j].row(jj) + T.row(j); // should be column vector\n\t\t\t\tcoords += ((*ri) * A.t() * U * V.t()) * local_coord.t(); // left-side should be (D x d)\n\t\t\t}\n\t\t\tassembly.row(i) = coords.t(); \n\t\t}\n\t\treturn(assembly);\n\t}\n\n\t// Wrapper for the fast_assembly above\n\tauto assemble_frames(py::array_t< double >& A, py::object& pou, py::list& cover_subsets, const py::list& local_models, py::array_t< double >& T ) -> py::array_t< double > {\n\t\tarma::mat A_ = carma::arr_to_mat(A, true);\n\t\tarma::sp_mat pou_;\n\t\tto_sparse(pou, pou_);\n\t\tauto subsets = vector< vector< size_t > >();\n\t\tfor (auto ind: cover_subsets){\n\t\t\tsubsets.push_back(ind.cast< vector< size_t > >());\n\t\t}\t\n\t\tauto models = vector< arma::mat >();\n\t\tfor (auto pts: local_models){\n\t\t\tpy::array_t< double > pts_ = pts.cast< py::array_t< double > >();\n\t\t\tmodels.push_back(carma::arr_to_mat(pts_, true));\n\t\t}\n\t\tarma::mat translations = carma::arr_to_mat(T, true);\n\t\tarma::mat assembly = fast_assembly(A_, pou_, subsets, models, translations);\n\t\treturn(carma::mat_to_arr(assembly));\n\t}\n\n};\n\n// if len(translations) != len(cover): raise ValueError(\"There should be a translation vector for each subset of the cover.\")\n// assembly = np.zeros((stf.n, stf.D), dtype=np.float64)\n// coords = np.zeros((1,stf.D), dtype=np.float64)\n// index_set = list(local_models.keys())\n// for i in range(stf.n):\n// \tw_i = np.ravel(pou[i,:].todense())\n// \tnz_ind = np.where(w_i > 0)[0]\n// \tcoords.fill(0)\n// \t## Construct assembly functions F_j(x) for x_i\n// \tfor j in nz_ind: \n// \t\tsubset_j = cover[index_set[j]]\n// \t\trelative_index = find_where(i, subset_j, True) ## This should always be true!\n// \t\tu, s, vt = np.linalg.svd((A @ (A.T @ stf.generate_frame(j, w_i))), full_matrices=False, compute_uv=True) \n// \t\td_coords = local_models[index_set[j]][relative_index,:]\n// \t\tcoords += (w_i[j]*A.T @ (u @ vt) @ (d_coords + translations[j]).T).T\n// \tassembly[i,:] = coords\n\n// extern void slaed1(int* N, float* D, float* Q, int* LDQ, int* INDXQ, float* RHO, int* CUTPNT, float* WORK, int* IWORK, int* INFO);\t\n\n// Computes U A U^T + sigma (u * u^T)\n// SLAED1 computes the updated eigensystem of a diagonal matrix after modification by a rank-one symmetric matrix.\n// void dpr1(py::array_t< float > D, py::array_t< float > V, float sigma, py::array_t< float > u){\n// \tarma::fvec d = carma::arr_to_col(D, true);\n// \tarma::fvec v = carma::arr_to_col(u, true);\n// \tarma::fmat Q = carma::arr_to_mat(V, true);\n// \tint N = d.size();\n// \tint LDQ = Q.n_rows;\n// \tvector< int > indxq(N);\n// \tstd::iota(indxq.begin(), indxq.end(), 0);\n// \tint CUTPNT = N/2;\n// \tvector< float > workspace(4*N + N*N);\n// \tvector< int > iworkspace(4*N);\n// \tint info = 0;\n// \tslaed1(&N, d.memptr(), Q.memptr(), &LDQ, indxq.data(), &sigma, &CUTPNT, workspace.data(), iworkspace.data(), &info);\n// \tpy::print(\"Info: \", info);\n// }\n\n// diag( D ) +  RHO *  Z * Z_transpose.\n// void dpr1(py::array_t< float > D, float rho, py::array_t< float > Z, int I){\n// \tarma::fvec d = carma::arr_to_col(D, true);\n// \tarma::fvec z = carma::arr_to_col(Z, true);\n// \tint N = D.size(), info = 0;\n// \tarma::fvec delta(N); // used for reconstructing eiegnvectors\n// \tfloat lambda = 0; // output eigenvalue\n// \tslaed4(&N, &I, d.memptr(), z.memptr(), delta.memptr(), &rho, &lambda, &info);\n// \tpy::print(\"Info: \", info, \"updated ev: \", lambda);\n// }\n\n// slaed9(int* K, int* KSTART, int* KSTOP, int* N, float* D, float* Q, int* LDQ, float* rho, float* dlambda, float* W, float* S, int& lds, int& info); \t\n// auto dpr1_ev(py::array_t< float > Q, py::array_t< float > D, float rho, py::array_t< float > Z) -> py::dict {\n// \tarma::fmat q = carma::arr_to_mat(Q, true); // eigenvectors\n// \tarma::fvec d = carma::arr_to_col(D, true); // diagonal entries / poles \n// \tarma::fvec z = carma::arr_to_col(Z, true); // perturbation vector\n// \tint K = d.size(), N = q.n_rows, info = 0;\n// \tint KSTART = 1, KEND = K;\n// \tarma::fvec lambda(K); \n// \tarma::fmat S(q.n_rows, q.n_cols);\n// \tslaed9(&K, &KSTART, &KEND, &N, lambda.memptr(), q.memptr(), &N, &rho, d.memptr(), z.memptr(), S.memptr(), &N, &info); \t\n// \t// py::print(\"Info: \", info);\n// \tpy::dict output; \n// \toutput[\"info\"] = info;\n// \toutput[\"eval\"] = carma::col_to_arr(lambda, true);\n// \toutput[\"evec\"] = carma::mat_to_arr(S, true);\n// \treturn(output);\n// }\n\n// T = Q(in) ( D(in) + RHO * Z*Z**T ) Q**T(in) = Q(out) * D(out) * Q**T(out)\n\n\nPYBIND11_MODULE(fast_svd, m) {\n\tm.def(\"fast_svd\", &fast_svd, \"Yields the svd of a matrix of low dimension\");\n\t//m.def(\"lapack_svd\", &lapack_svd, \"Yields the svd of a matrix of low dimension\");\n\t//m.def(\"test_sparse\", &test_sparse, \"Test conversion to sparse matrix\");\n\t//m.def(\"dpr1\", &dpr1, \"Diagonal + rank-1 matrix eigenvalue update\");\n\t//m.def(\"dpr1_ev\", &dpr1_ev, \"Diagonal + rank-1 matrix eigenvalue update\");\n\tpy::class_<StiefelLoss>(m, \"StiefelLoss\")\n\t\t.def(py::init< int, int, int >())\n\t\t.def_readonly(\"d\", &StiefelLoss::d)\n\t\t.def_readonly(\"n\", &StiefelLoss::n)\n\t\t.def_readonly(\"D\", &StiefelLoss::D)\n\t\t.def_readwrite(\"output\", &StiefelLoss::output)\n\t\t// .def_readwrite(\"rotations\", &StiefelLoss::rotations)\n\t\t//.def(\"benchmark_gradient\", &StiefelLoss::benchmark_gradient)\n\t\t.def(\"gradient\", &StiefelLoss::gradient)\n\t\t.def(\"init_rotations\", &StiefelLoss::init_rotations)\n\t\t.def(\"get_rotation\", &StiefelLoss::get_rotation)\t\t\n\t\t.def(\"populate_frame\", &StiefelLoss::populate_frame)\n\t\t.def(\"populate_frames\", &StiefelLoss::populate_frames)\n\t\t.def(\"populate_frames_sparse\", &StiefelLoss::populate_frames_sparse)\n\t\t.def(\"generate_frame\", &StiefelLoss::generate_frame)\n\t\t.def(\"get_frame\", &StiefelLoss::get_frame)\n\t\t.def(\"all_frames\", &StiefelLoss::all_frames)\n\t\t.def(\"all_frames_sparse\", &StiefelLoss::all_frames_sparse)\n\t\t.def(\"embed\", &StiefelLoss::embed)\n\t\t.def(\"extract_iota\", &StiefelLoss::extract_iota)\n\t\t.def(\"setup_pou\", &StiefelLoss::setup_pou)\n\t\t.def(\"benchmark_embedding\", &StiefelLoss::benchmark_embedding)\n\t\t.def(\"assemble_frames\", &StiefelLoss::assemble_frames)\n\t\t.def(\"assemble_frames2\", &StiefelLoss::assemble_frames2)\n\t\t.def(\"initial_guess\", &StiefelLoss::initial_guess)\n\t\t.def(\"__repr__\",[](const StiefelLoss &stf) {\n\t\t\treturn(\"Stiefel Loss w/ parameters n=\"+std::to_string(stf.n)+\",d=\"+std::to_string(stf.d)+\",D=\"+std::to_string(stf.D));\n  \t});\n}\n\n\n\n\n\n// double numpy_svd(){\n// \tauto svd = py::module::import(\"numpy.linalg\").attr(\"svd\");\n// \tpy::buffer_info output_buffer = output.request();\n// \tconst size_t inc = D*d;\n// \tdouble nuclear_norm = 0.0;\n// \tfor (int j = 0; j < n; ++j){\n// \t\tnp_array_t inp = np_array_t({ D, d }, output.data()+(j*inc));\n// \t\tnp_array_t sv = svd(inp, false, false, false);\n// \t\tauto r = sv.unchecked< 1 >();\n// \t\tfor (size_t i = 0; i < sv.shape(0); i++){ \n// \t\t\tnuclear_norm += r(i); \n// \t\t}\n// \t}\n// \treturn(nuclear_norm);\n// }", "meta": {"hexsha": "f49b7a8f3294fba2a0cbf085de9c2510eb4e0d58", "size": 31793, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tallem/extensions/fast_svd.cpp", "max_stars_repo_name": "peekxc/tallem", "max_stars_repo_head_hexsha": "949af20c1f50f9b6784ee32463e59123cd64294b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/tallem/extensions/fast_svd.cpp", "max_issues_repo_name": "peekxc/tallem", "max_issues_repo_head_hexsha": "949af20c1f50f9b6784ee32463e59123cd64294b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tallem/extensions/fast_svd.cpp", "max_forks_repo_name": "peekxc/tallem", "max_forks_repo_head_hexsha": "949af20c1f50f9b6784ee32463e59123cd64294b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-07-25T04:58:58.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-25T04:58:58.000Z", "avg_line_length": 41.5052219321, "max_line_length": 208, "alphanum_fraction": 0.6436322461, "num_tokens": 10169, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234877, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4925907292074087}}
{"text": "#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <cmath>\n#include \"UKF/Types.h\"\n#include \"UKF/Integrator.h\"\n#include \"UKF/StateVector.h\"\n#include \"UKF/MeasurementVector.h\"\n#include \"UKF/Core.h\"\n#include \"cukf.h\"\n\n/*\nThis file implements the same UKF as was used for the 2014 UAV Challenge.\nThere are a number of efficiency and performance improvements that could be\nmade with the new library structure, but the main purpose of this is for\ndirect comparison of performance of the new library against the old\nimplementation.\n*/\n\nenum SFWA_States {\n    LatLon,\n    Altitude,\n    Velocity,\n    Acceleration,\n    Attitude,\n    AngularVelocity,\n    AngularAcceleration,\n    WindVelocity,\n    GyroBias\n};\n\nusing SFWA_StateVector = UKF::StateVector<\n    UKF::Field<LatLon, UKF::Vector<2>>,                 /* Latitude and longitude (rad) */\n    UKF::Field<Altitude, real_t>,                       /* Altitude above the WGS84 ellipsoid (m) */\n    UKF::Field<Velocity, UKF::Vector<3>>,               /* Velocity (NED frame, m/s) */\n    UKF::Field<Acceleration, UKF::Vector<3>>,           /* Acceleration (body frame, m/s^2) */\n    UKF::Field<Attitude, UKF::Quaternion>,              /* Attitude as a quaternion (NED frame to body frame) */\n    UKF::Field<AngularVelocity, UKF::Vector<3>>,        /* Angular velocity (body frame, rad/s) */\n    UKF::Field<AngularAcceleration, UKF::Vector<3>>,    /* Angular acceleration (body frame, rad/s^2) */\n    UKF::Field<WindVelocity, UKF::Vector<3>>,           /* Wind velocity (NED frame, m/s) */\n    UKF::Field<GyroBias, UKF::Vector<3>>                /* Gyro bias (body frame, rad/s) */\n>;\n\n/* WGS84 reference ellipsoid constants. */\n#define WGS84_A (6378137.0)\n#define WGS84_B (6356752.314245)\n#define WGS84_A2 (WGS84_A*WGS84_A)\n#define WGS84_B2 (WGS84_B*WGS84_B)\n#define WGS84_AB2 (WGS84_A2*WGS84_B2)\n\n#define G_ACCEL (9.80665)\n#define RHO (1.225)\n\n/* SFWA vehicle dynamics model. Not used for this comparison. */\nUKF::Vector<6> x8_dynamics_model(const SFWA_StateVector &state, const UKF::Vector<3> &control) {\n    UKF::Vector<6> output;\n\n    /* Cache state data for convenience */\n    UKF::Quaternion attitude = state.get_field<Attitude>();\n    real_t yaw_rate = state.get_field<AngularVelocity>()[2],\n           pitch_rate = state.get_field<AngularVelocity>()[1],\n           roll_rate = state.get_field<AngularVelocity>()[0];\n\n    /* External axes */\n    UKF::Vector<3> airflow = attitude * (state.get_field<WindVelocity>() - state.get_field<Velocity>());\n\n    /*\n    Calculate axial airflow\n    */\n    real_t airflow_x2, airflow_y2, airflow_z2, airflow_v2;\n    airflow_x2 = airflow[0]*airflow[0];\n    airflow_y2 = airflow[1]*airflow[1];\n    airflow_z2 = airflow[2]*airflow[2];\n    airflow_v2 = airflow_x2 + airflow_y2 + airflow_z2;\n\n    /*\n    Determine motor thrust and torque.\n    */\n    real_t rpm = control[0] * 12000.0, thrust,\n           ve2 = (0.0025 * 0.0025) * rpm * rpm;\n    /* 1 / 3.8kg times area * density of air */\n    thrust = (ve2 - airflow_v2) *\n             (0.26315789473684 * 0.5 * RHO * 0.02);\n\n    /*\n    Calculate airflow in the horizontal and vertical planes, as well as\n    pressure\n    */\n    real_t v_inv, vertical_v, vertical_v_inv, qbar;\n\n    qbar = (RHO * 0.5) * airflow_v2;\n    v_inv = 1.0 / std::sqrt(std::max(1.0, airflow_v2));\n\n    vertical_v = std::sqrt(airflow_x2 + airflow_z2);\n    vertical_v_inv = 1.0 / std::max(1.0, vertical_v);\n\n    /* Work out sin/cos of alpha and beta */\n    real_t sin_alpha, cos_alpha, sin_beta, cos_beta, sin_cos_alpha;\n\n    sin_beta = airflow[1] * v_inv;\n    cos_beta = vertical_v * v_inv;\n\n    sin_alpha = -airflow[2] * vertical_v_inv;\n    cos_alpha = -airflow[0] * vertical_v_inv;\n\n    sin_cos_alpha = sin_alpha * cos_alpha;\n\n    /* Work out aerodynamic forces in wind frame */\n    real_t lift, drag, side_force;\n\n    /* 0.26315789473684 is the reciprocal of mass (3.8kg) */\n    lift = (qbar * 0.26315789473684) * (0.8 * sin_cos_alpha + 0.18);\n    drag = (qbar * 0.26315789473684) *\n           (0.05 + 0.7 * sin_alpha * sin_alpha);\n    side_force = (qbar * 0.26315789473684) * 0.2 * sin_beta * cos_beta;\n\n    /* Convert aerodynamic forces from wind frame to body frame */\n    real_t x_aero_f = lift * sin_alpha - drag * cos_alpha -\n                             side_force * sin_beta,\n           z_aero_f = lift * cos_alpha + drag * sin_alpha,\n           y_aero_f = side_force * cos_beta;\n\n    output.segment<3>(0) << UKF::Vector<3>(x_aero_f + thrust, y_aero_f, -z_aero_f) +\n        (attitude * UKF::Vector<3>(0, 0, G_ACCEL));\n\n    /* Determine moments */\n    real_t pitch_moment, yaw_moment, roll_moment,\n           left_aileron = control[1] - 0.5, right_aileron = control[2] - 0.5;\n    pitch_moment = 0.0 - 0.0 * sin_alpha - 0.0 * pitch_rate -\n                   0.1 * (left_aileron + right_aileron) * vertical_v * 0.1;\n    roll_moment = 0.05 * sin_beta - 0.1 * roll_rate +\n                  0.15 * (left_aileron - right_aileron) * vertical_v * 0.1;\n    yaw_moment = -0.02 * sin_beta - 0.05 * yaw_rate -\n                 0.02 * (std::abs(left_aileron) + std::abs(right_aileron)) *\n                 vertical_v * 0.1;\n    pitch_moment *= qbar;\n    roll_moment *= qbar;\n    yaw_moment *= qbar;\n\n    /*\n    Calculate angular acceleration (tau / inertia tensor).\n    Inertia tensor is:\n        0.3 0 -0.0334\n        0 0.17 0\n        -0.0334 0 0.405\n    So inverse is:\n        3.36422 0 0.277444\n        0 5.88235 0\n        0.277444 0 2.49202\n    */\n    output.segment<3>(3) << UKF::Vector<3>(\n        (3.364222 * roll_moment + 0.27744448 * yaw_moment),\n        10.8823528 * pitch_moment,\n        (0.27744448 * roll_moment + 2.4920163 * yaw_moment));\n\n    return output;\n}\n\nnamespace UKF {\n\n/* SFWA state vector process model. */\ntemplate <> template <>\nSFWA_StateVector SFWA_StateVector::derivative<>() const {\n    SFWA_StateVector output;\n\n    /* Calculate the normal and meridional radii of curvature. */\n    real_t lat = get_field<LatLon>()[0];\n    real_t tempA = WGS84_A*std::cos(lat), tempB = WGS84_B*std::sin(lat),\n           temp = tempA * tempA + tempB * tempB,\n           temp_sqrt = std::sqrt(temp);\n    real_t M = WGS84_AB2 / (temp_sqrt * temp);\n    real_t N = WGS84_A2 / temp_sqrt;\n\n    /*\n    Calculate change in position. Using the small angle approximation, this\n    becomes very simple \u2013 no trig required for latitude derivative, and one\n    cosine function for longitude derivative.\n    */\n    UKF::Vector<3> vel = get_field<Velocity>();\n    output.set_field<LatLon>(Vector<2>(\n        vel[0] / (M + get_field<Altitude>()),\n        (vel[1] / (N + get_field<Altitude>())) * std::cos(lat)));\n    output.set_field<Altitude>(-vel[2]);\n\n    /* Calculate change in velocity. */\n    output.set_field<Velocity>(get_field<Attitude>().conjugate() * get_field<Acceleration>());\n\n    /* Change in linear acceleration is zero. */\n    output.set_field<Acceleration>(UKF::Vector<3>(0, 0, 0));\n\n    /* Calculate change in attitude. */\n    UKF::Quaternion omega_q;\n    omega_q.vec() = get_field<AngularVelocity>() * 0.5;\n    omega_q.w() = 0;\n    output.set_field<Attitude>(omega_q.conjugate() * get_field<Attitude>());\n\n    /* Calculate change in angular velocity (just angular acceleration). */\n    output.set_field<AngularVelocity>(get_field<AngularAcceleration>());\n\n    /* Change in angular acceleration is zero. */\n    output.set_field<AngularAcceleration>(UKF::Vector<3>(0, 0, 0));\n\n    /* Change in wind velocity is zero. */\n    output.set_field<WindVelocity>(UKF::Vector<3>(0, 0, 0));\n\n    /* Change in gyro bias is zero. */\n    output.set_field<GyroBias>(UKF::Vector<3>(0, 0, 0));\n\n    return output;\n}\n\n}\n\nenum SFWA_Measurements {\n    Accelerometer,\n    Gyroscope,\n    Magnetometer,\n    GPS_Position,\n    GPS_Velocity,\n    Airspeed,\n    PressureAltitude\n};\n\nusing SFWA_MeasurementVector = UKF::DynamicMeasurementVector<\n    UKF::Field<Accelerometer, UKF::Vector<3>>,\n    UKF::Field<Gyroscope, UKF::Vector<3>>,\n    UKF::Field<Magnetometer, UKF::Vector<3>>,\n    UKF::Field<GPS_Position, UKF::Vector<3>>,\n    UKF::Field<GPS_Velocity, UKF::Vector<3>>,\n    UKF::Field<Airspeed, real_t>,\n    UKF::Field<PressureAltitude, real_t>\n>;\n\n/*\nHard code the magnetic field vector to the WMM value for\n-37.954690, 145.237575 for the purposes of this comparison. Value is in\nmicrotesla.\n*/\nstatic UKF::Vector<3> local_mag_field = UKF::Vector<3>(21.2584, 4.4306, -55.9677);\n\nusing SFWA_UKF = UKF::Core<\n    SFWA_StateVector,\n    SFWA_MeasurementVector,\n    UKF::IntegratorRK4\n>;\n\nnamespace UKF {\n/* SFWA measurement model. */\ntemplate <> template <>\nUKF::Vector<3> SFWA_MeasurementVector::expected_measurement\n<SFWA_StateVector, Accelerometer>(const SFWA_StateVector& state) {\n    return state.get_field<Acceleration>() + state.get_field<Attitude>() * UKF::Vector<3>(0, 0, -G_ACCEL);\n}\n\ntemplate <> template <>\nUKF::Vector<3> SFWA_MeasurementVector::expected_measurement\n<SFWA_StateVector, Gyroscope>(const SFWA_StateVector& state) {\n    return state.get_field<AngularVelocity>() + state.get_field<GyroBias>();\n}\n\ntemplate <> template <>\nUKF::Vector<3> SFWA_MeasurementVector::expected_measurement\n<SFWA_StateVector, Magnetometer>(const SFWA_StateVector& state) {\n    return state.get_field<Attitude>() * local_mag_field;\n}\n\ntemplate <> template <>\nUKF::Vector<3> SFWA_MeasurementVector::expected_measurement\n<SFWA_StateVector, GPS_Position>(const SFWA_StateVector& state) {\n    return UKF::Vector<3>(state.get_field<LatLon>()[0], state.get_field<LatLon>()[1], state.get_field<Altitude>());\n}\n\ntemplate <> template <>\nUKF::Vector<3> SFWA_MeasurementVector::expected_measurement\n<SFWA_StateVector, GPS_Velocity>(const SFWA_StateVector& state) {\n    return state.get_field<Velocity>();\n}\n\ntemplate <> template <>\nreal_t SFWA_MeasurementVector::expected_measurement\n<SFWA_StateVector, Airspeed>(const SFWA_StateVector& state) {\n    return (state.get_field<Attitude>() * (state.get_field<Velocity>() - state.get_field<WindVelocity>()))[0];\n}\n\ntemplate <> template <>\nreal_t SFWA_MeasurementVector::expected_measurement\n<SFWA_StateVector, PressureAltitude>(const SFWA_StateVector& state) {\n    return state.get_field<Altitude>();\n}\n\n}\nstatic SFWA_UKF ukf;\nstatic SFWA_MeasurementVector meas;\n\n/*\nThe following functions provide a ctypes-compatible interface for ease of\ntesting.\n*/\n\nvoid ukf_init() {\n    ukf.state.set_field<LatLon>(UKF::Vector<2>(-0.662434, 2.534874));\n    ukf.state.set_field<Altitude>(0);\n    ukf.state.set_field<Velocity>(UKF::Vector<3>(0, 0, 0));\n    ukf.state.set_field<Acceleration>(UKF::Vector<3>(0, 0, 0));\n    ukf.state.set_field<Attitude>(UKF::Quaternion(1, 0, 0, 0));\n    ukf.state.set_field<AngularVelocity>(UKF::Vector<3>(0, 0, 0));\n    ukf.state.set_field<AngularAcceleration>(UKF::Vector<3>(0, 0, 0));\n    ukf.state.set_field<WindVelocity>(UKF::Vector<3>(0, 0, 0));\n    ukf.state.set_field<GyroBias>(UKF::Vector<3>(0, 0, 0));\n    ukf.covariance = SFWA_StateVector::CovarianceMatrix::Zero();\n    ukf.covariance.diagonal() <<\n        1, 1, 10000, 1e-6, 1e-6, 1e-6, 1e-6, 1e-6, 1e-6, 10, 10, 10,\n        1e-6, 1e-6, 1e-6, 1e-6, 1e-6, 1e-6, 100, 100, 100, 0.01, 0.01, 0.01;\n    ukf.measurement_covariance <<1, 1, 1, 0.01, 0.01, 0.01, 10, 10, 10, 1e-20, 1e-20, 1, 1, 1, 1, 1, 1;\n\n    local_mag_field = UKF::Vector<3>(21.2584, 4.4306, -55.9677);\n\n    ukf.process_noise_covariance = SFWA_StateVector::CovarianceMatrix::Zero();\n    ukf.process_noise_covariance.diagonal() <<\n        1e-17, 1e-17, 1e-4,     /* lat, lon, alt */\n        2e-3, 2e-3, 2e-3,       /* velocity N, E, D */\n        2e-2, 2e-2, 2e-2,       /* acceleration x, y, z */\n        7e-8, 7e-8, 7e-8,       /* attitude roll, pitch, yaw */\n        1e-3, 1e-3, 1e-3,       /* angular velocity roll, pitch, yaw */\n        1e-3, 1e-3, 1e-3,       /* angular acceleration roll, pitch, yaw */\n        1e-7, 1e-7, 1e-7,       /* wind velocity N, E, D -- NOTE: from FCS armed mode */\n        1e-12, 1e-12, 1e-12;    /* gyro bias x, y, z -- NOTE: from FCS armed mode */\n}\n\nvoid ukf_set_position(real_t lat, real_t lon, real_t alt) {\n    ukf.state.set_field<LatLon>(UKF::Vector<2>(lat, lon));\n    ukf.state.set_field<Altitude>(alt);\n}\n\nvoid ukf_set_velocity(real_t x, real_t y, real_t z) {\n    ukf.state.set_field<Velocity>(UKF::Vector<3>(x, y, z));\n}\n\nvoid ukf_set_acceleration(real_t x, real_t y, real_t z) {\n    ukf.state.set_field<Acceleration>(UKF::Vector<3>(x, y, z));\n}\n\nvoid ukf_set_attitude(real_t w, real_t x, real_t y, real_t z) {\n    ukf.state.set_field<Attitude>(UKF::Quaternion(w, x, y, z));\n}\n\nvoid ukf_set_angular_velocity(real_t x, real_t y, real_t z) {\n    ukf.state.set_field<AngularVelocity>(UKF::Vector<3>(x, y, z));\n}\n\nvoid ukf_set_angular_acceleration(real_t x, real_t y, real_t z) {\n    ukf.state.set_field<AngularAcceleration>(UKF::Vector<3>(x, y, z));\n}\n\nvoid ukf_set_wind_velocity(real_t x, real_t y, real_t z) {\n    ukf.state.set_field<WindVelocity>(UKF::Vector<3>(x, y, z));\n}\n\nvoid ukf_set_gyro_bias(real_t x, real_t y, real_t z) {\n    ukf.state.set_field<GyroBias>(UKF::Vector<3>(x, y, z));\n}\n\nvoid ukf_get_state(struct ukf_state_t *in) {\n    in->position[0] = ukf.state.get_field<LatLon>()[0];\n    in->position[1] = ukf.state.get_field<LatLon>()[1];\n    in->position[2] = ukf.state.get_field<Altitude>();\n    in->velocity[0] = ukf.state.get_field<Velocity>()[0];\n    in->velocity[1] = ukf.state.get_field<Velocity>()[1];\n    in->velocity[2] = ukf.state.get_field<Velocity>()[2];\n    in->acceleration[0] = ukf.state.get_field<Acceleration>()[0];\n    in->acceleration[1] = ukf.state.get_field<Acceleration>()[1];\n    in->acceleration[2] = ukf.state.get_field<Acceleration>()[2];\n    in->attitude[0] = ukf.state.get_field<Attitude>().x();\n    in->attitude[1] = ukf.state.get_field<Attitude>().y();\n    in->attitude[2] = ukf.state.get_field<Attitude>().z();\n    in->attitude[3] = ukf.state.get_field<Attitude>().w();\n    in->angular_velocity[0] = ukf.state.get_field<AngularVelocity>()[0];\n    in->angular_velocity[1] = ukf.state.get_field<AngularVelocity>()[1];\n    in->angular_velocity[2] = ukf.state.get_field<AngularVelocity>()[2];\n    in->angular_acceleration[0] = ukf.state.get_field<AngularAcceleration>()[0];\n    in->angular_acceleration[1] = ukf.state.get_field<AngularAcceleration>()[1];\n    in->angular_acceleration[2] = ukf.state.get_field<AngularAcceleration>()[2];\n    in->wind_velocity[0] = ukf.state.get_field<WindVelocity>()[0];\n    in->wind_velocity[1] = ukf.state.get_field<WindVelocity>()[1];\n    in->wind_velocity[2] = ukf.state.get_field<WindVelocity>()[2];\n    in->gyro_bias[0] = ukf.state.get_field<GyroBias>()[0];\n    in->gyro_bias[1] = ukf.state.get_field<GyroBias>()[1];\n    in->gyro_bias[2] = ukf.state.get_field<GyroBias>()[2];\n}\n\nvoid ukf_set_state(struct ukf_state_t *in) {\n    ukf.state.set_field<LatLon>(UKF::Vector<2>(in->position[0], in->position[1]));\n    ukf.state.set_field<Altitude>(in->position[2]);\n    ukf.state.set_field<Velocity>(\n        UKF::Vector<3>(in->velocity[0], in->velocity[1], in->velocity[2]));\n    ukf.state.set_field<Acceleration>(\n        UKF::Vector<3>(in->acceleration[0], in->acceleration[1], in->acceleration[2]));\n    ukf.state.set_field<Attitude>(\n        UKF::Quaternion(in->attitude[3], in->attitude[0], in->attitude[1], in->attitude[2]));\n    ukf.state.set_field<AngularVelocity>(\n        UKF::Vector<3>(in->angular_velocity[0], in->angular_velocity[1], in->angular_velocity[2]));\n    ukf.state.set_field<AngularAcceleration>(\n        UKF::Vector<3>(in->angular_acceleration[0], in->angular_acceleration[1], in->angular_acceleration[2]));\n    ukf.state.set_field<WindVelocity>(\n        UKF::Vector<3>(in->wind_velocity[0], in->wind_velocity[1], in->wind_velocity[2]));\n    ukf.state.set_field<GyroBias>(\n        UKF::Vector<3>(in->gyro_bias[0], in->gyro_bias[1], in->gyro_bias[2]));\n}\n\nvoid ukf_get_state_covariance(\n        real_t state_covariance[SFWA_StateVector::covariance_size()*SFWA_StateVector::covariance_size()]) {\n    Eigen::Map<typename SFWA_StateVector::CovarianceMatrix> covariance_map(state_covariance);\n    covariance_map = ukf.covariance;\n}\n\nvoid ukf_get_state_covariance_diagonal(\n        real_t state_covariance_diagonal[SFWA_StateVector::covariance_size()]) {\n    Eigen::Map<UKF::Vector<SFWA_StateVector::covariance_size()>> covariance_map(state_covariance_diagonal);\n    covariance_map = ukf.covariance.diagonal();\n}\n\nvoid ukf_get_state_error(real_t state_error[SFWA_StateVector::covariance_size()]) {\n    Eigen::Map<typename SFWA_StateVector::StateVectorDelta> error_map(state_error);\n    error_map = ukf.covariance.cwiseAbs().rowwise().sum().cwiseSqrt();\n}\n\nvoid ukf_sensor_clear() {\n    meas = SFWA_MeasurementVector();\n}\n\nvoid ukf_sensor_set_accelerometer(real_t x, real_t y, real_t z) {\n    meas.set_field<Accelerometer>(UKF::Vector<3>(x, y, z));\n}\n\nvoid ukf_sensor_set_gyroscope(real_t x, real_t y, real_t z) {\n    meas.set_field<Gyroscope>(UKF::Vector<3>(x, y, z));\n}\n\nvoid ukf_sensor_set_magnetometer(real_t x, real_t y, real_t z) {\n    meas.set_field<Magnetometer>(UKF::Vector<3>(x, y, z));\n}\n\nvoid ukf_sensor_set_gps_position(real_t lat, real_t lon, real_t alt) {\n    meas.set_field<GPS_Position>(UKF::Vector<3>(lat, lon, alt));\n}\n\nvoid ukf_sensor_set_gps_velocity(real_t x, real_t y, real_t z) {\n    meas.set_field<GPS_Velocity>(UKF::Vector<3>(x, y, z));\n}\n\nvoid ukf_sensor_set_pitot_tas(real_t tas) {\n    meas.set_field<Airspeed>(tas);\n}\n\nvoid ukf_sensor_set_barometer_amsl(real_t amsl) {\n    meas.set_field<PressureAltitude>(amsl);\n}\n\nvoid ukf_set_params(struct ukf_ioboard_params_t *in) {\n    local_mag_field << in->mag_field[0], in->mag_field[1], in->mag_field[2];\n    ukf.measurement_covariance <<\n        in->accel_covariance[0], in->accel_covariance[1], in->accel_covariance[2],\n        in->gyro_covariance[0], in->gyro_covariance[1], in->gyro_covariance[2],\n        in->mag_covariance[0], in->mag_covariance[1], in->mag_covariance[2],\n        in->gps_position_covariance[0], in->gps_position_covariance[1], in->gps_position_covariance[2],\n        in->gps_velocity_covariance[0], in->gps_velocity_covariance[1], in->gps_velocity_covariance[2],\n        in->pitot_covariance,\n        in->barometer_amsl_covariance;\n}\n\nvoid ukf_choose_dynamics(enum ukf_model_t t) {\n\n}\n\nvoid ukf_set_custom_dynamics_model(ukf_model_function_t func) {\n\n}\n\nvoid ukf_iterate(float dt, real_t control_vector[UKF_CONTROL_DIM]) {\n    ukf.step(dt, meas);\n}\n\nvoid ukf_set_process_noise(real_t process_noise_covariance[SFWA_StateVector::covariance_size()]) {\n    Eigen::Map<typename SFWA_StateVector::StateVectorDelta> covariance_map(process_noise_covariance);\n    ukf.process_noise_covariance = SFWA_StateVector::CovarianceMatrix::Zero();\n    ukf.process_noise_covariance.diagonal() << covariance_map;\n}\n\nuint32_t ukf_config_get_state_dim() {\n    return SFWA_StateVector::covariance_size();\n}\n\nuint32_t ukf_config_get_measurement_dim() {\n    return SFWA_MeasurementVector::max_size();\n}\n\nuint32_t ukf_config_get_control_dim() {\n    return UKF_CONTROL_DIM;\n}\n\nenum ukf_precision_t ukf_config_get_precision() {\n    return UKF_PRECISION_DOUBLE;\n}\n", "meta": {"hexsha": "81bbeab665795c11202045a018837290f129ea8c", "size": 19027, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/sfwa_ukf/cukf.cpp", "max_stars_repo_name": "rafaelrietmann/ukf", "max_stars_repo_head_hexsha": "bf53dacafbfee8c7591c48a66b50229f82afe4b4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 320.0, "max_stars_repo_stars_event_min_datetime": "2015-01-07T05:49:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:52:15.000Z", "max_issues_repo_path": "examples/sfwa_ukf/cukf.cpp", "max_issues_repo_name": "msnh2012/ukf", "max_issues_repo_head_hexsha": "04f0a996fee1f49699142bf5b149548a8d3a4ad1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 22.0, "max_issues_repo_issues_event_min_datetime": "2015-03-03T17:28:32.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T14:46:54.000Z", "max_forks_repo_path": "examples/sfwa_ukf/cukf.cpp", "max_forks_repo_name": "msnh2012/ukf", "max_forks_repo_head_hexsha": "04f0a996fee1f49699142bf5b149548a8d3a4ad1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 155.0, "max_forks_repo_forks_event_min_datetime": "2015-02-20T01:18:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-22T01:58:53.000Z", "avg_line_length": 37.8270377734, "max_line_length": 115, "alphanum_fraction": 0.6755663005, "num_tokens": 5956, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.841825655188238, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4925531624885294}}
{"text": "// UNDER CONSTRUCTION\n#include <utility>\n\n#include \"skeletons.h\"\n#include <boost/graph/connected_components.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/config.hpp>\n\n#include <cctbx/error.h>\n\nnamespace cctbx { namespace maptbx\n{\n\ntypedef boost::adjacency_list<boost::vecS,boost::vecS,boost::undirectedS>\n  graph_t;\n\nstd::pair<size_t,std::vector<int> > skeleton_components(const joins_t &joins,\n  std::size_t nv)\n{\n  namespace b = boost;\n  graph_t g(nv);\n  for( const auto & j : joins )\n    b::add_edge(j.ilt, j.igt, g);\n  size_t nvj = b::num_vertices(g);\n  CCTBX_ASSERT( nv == nvj );\n  std::vector<int> cm(nv);\n  size_t n = b::connected_components(g,&cm[0]);\n  return std::make_pair(n,std::move(cm));\n}\n\nstd::vector<std::size_t> mask_components(marks_t &mask,\n  const std::vector<int> &components)\n{\n  std::vector<std::size_t> sizes(components.size(),0);\n  for( auto & m : mask )\n  {\n    if( m!=0 )\n    {\n      m = components.at(m);\n      ++(sizes.at(m));\n    }\n  }\n  return sizes;\n}\n\nvoid mask_density_map(asymmetric_map::data_ref_t map, const marks_t &mask,\n  unsigned val)\n{\n  // CCTBX_ASSERT( map.accessor() == mask.accessor() );\n\n  CCTBX_ASSERT( map.size() == mask.size() );\n  for(size_t i=0; i<map.size(); ++i)\n  {\n    if( mask[i]!=val )\n      map[i] = 0.;\n  }\n}\n\n\n// consider useing boost::graph\nshortest_paths dijkstra(const skeleton &skelet,\n    const std::vector<std::size_t> &molids, std::size_t iatom)\n{\n  shortest_paths result;\n  if( iatom> skelet.maximums.size() )\n    throw std::runtime_error(\"wrong vertex\");\n  CCTBX_ASSERT( skelet.maximums.size() == molids.size() );\n  std::size_t molid = molids[iatom];\n  std::size_t nv = std::count(molids.begin(), molids.end(), molid);\n  result.distances.resize(nv,0);\n  result.predecessors.resize(nv,0);\n  std::vector<std::size_t> Q(nv);\n  for(std::size_t i=0; i<Q.size(); ++i)\n    Q[i] = i;\n  std::size_t j=0;\n  std::size_t inv = std::numeric_limits<std::size_t>::max();\n  do\n  {\n    std::size_t mloc = std::min_element(result.distances.begin(),\n       result.distances.end()) - result.distances.begin();\n    mloc = Q[mloc];\n    if( mloc == inv )\n      break;\n    if( j>nv )\n      throw std::logic_error(\"index is out of range\");\n    ++j;\n    for(joins_t::const_iterator i=skelet.joins.begin();\n        i!=skelet.joins.end(); ++i)\n    {\n      const join_t &join = *i; // kelet.joins[i];\n      std::size_t adj = 0;\n      if( join.ilt == mloc )\n        adj = join.igt;\n      if( join.igt == mloc )\n        adj = join.ilt;\n      if( adj!=0 )\n      {\n        if( result.distances[adj] > result.distances[mloc]+1 )\n        {\n          result.distances[adj] = result.distances[mloc] + 1;\n          result.predecessors[adj] = mloc;\n        }\n      }\n    }\n    Q[mloc] = inv;\n  } while(true);\n  return result;\n}\n\n}}\n", "meta": {"hexsha": "eff35324c5ecd48bfe7b1b242d408c477831ff1a", "size": 2781, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cctbx/maptbx/dijkstra.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/dijkstra.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/dijkstra.cpp", "max_forks_repo_name": "rimmartin/cctbx_project", "max_forks_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 115.0, "max_forks_repo_forks_event_min_datetime": "2016-11-15T08:17:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T15:30:14.000Z", "avg_line_length": 25.0540540541, "max_line_length": 77, "alphanum_fraction": 0.6148867314, "num_tokens": 848, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4925531532010199}}
{"text": "#include \"wrappers/qpWrapperBase.hpp\"\n\n#include <Eigen/Cholesky>\n\nnamespace cvx::internal\n{\n\n    QPWrapperBase::QPWrapperBase(OptimizationProblem &problem)\n    {\n        std::vector<Eigen::Triplet<Parameter>> A_coeffs, P_coeffs;\n        std::vector<Parameter> l_coeffs, u_coeffs;\n\n        // Build equality constraint parameters\n        for (internal::EqualityConstraint &constraint : problem.equality_constraints)\n        {\n            constraint.affine.cleanUp();\n            if (constraint.affine.isConstant())\n            {\n                continue;\n            }\n\n            for (Term &term : constraint.affine.terms)\n            {\n                addVariable(term.variable);\n                A_coeffs.emplace_back(u_coeffs.size(),\n                                      term.variable.getProblemIndex(),\n                                      term.parameter);\n            }\n            l_coeffs.push_back(Parameter(-1.) * constraint.affine.constant);\n            u_coeffs.push_back(Parameter(-1.) * constraint.affine.constant);\n        }\n\n        // Build positive constraint parameters\n        for (internal::PositiveConstraint &constraint : problem.positive_constraints)\n        {\n            constraint.affine.cleanUp();\n            if (constraint.affine.isConstant())\n            {\n                continue;\n            }\n\n            for (Term &term : constraint.affine.terms)\n            {\n                addVariable(term.variable);\n                A_coeffs.emplace_back(u_coeffs.size(),\n                                      term.variable.getProblemIndex(),\n                                      term.parameter);\n            }\n            l_coeffs.push_back(Parameter(-1.) * constraint.affine.constant);\n            u_coeffs.push_back(Parameter(std::numeric_limits<double>::max()));\n        }\n\n        // Build box constraint parameters\n        for (internal::BoxConstraint &constraint : problem.box_constraints)\n        {\n            if (constraint.lower.isConstant() and constraint.upper.isConstant())\n            {\n                // lower <= middle <= upper\n                constraint.middle.cleanUp();\n                if (constraint.middle.isConstant())\n                {\n                    continue;\n                }\n\n                for (Term &term : constraint.middle.terms)\n                {\n                    addVariable(term.variable);\n                    A_coeffs.emplace_back(u_coeffs.size(),\n                                          term.variable.getProblemIndex(),\n                                          term.parameter);\n                }\n                l_coeffs.push_back(constraint.lower.constant - constraint.middle.constant);\n                u_coeffs.push_back(constraint.upper.constant - constraint.middle.constant);\n            }\n            else\n            {\n                // c_lower - c_middle <= middle - lower <= inf\n                Affine middle_m_lower = constraint.middle - constraint.lower;\n                middle_m_lower.cleanUp();\n\n                if (middle_m_lower.isFirstOrder())\n                {\n                    for (Term &term : middle_m_lower.terms)\n                    {\n                        addVariable(term.variable);\n                        A_coeffs.emplace_back(u_coeffs.size(),\n                                              term.variable.getProblemIndex(),\n                                              term.parameter);\n                    }\n                    l_coeffs.push_back(constraint.lower.constant - constraint.middle.constant);\n                    u_coeffs.push_back(Parameter(std::numeric_limits<double>::max()));\n                }\n\n                // c_middle - c_upper <= upper - middle <= inf\n                Affine upper_m_middle = constraint.upper - constraint.middle;\n                upper_m_middle.cleanUp();\n\n                if (upper_m_middle.isFirstOrder())\n                {\n                    for (Term &term : upper_m_middle.terms)\n                    {\n                        addVariable(term.variable);\n                        A_coeffs.emplace_back(u_coeffs.size(),\n                                              term.variable.getProblemIndex(),\n                                              term.parameter);\n                    }\n                    l_coeffs.push_back(constraint.middle.constant - constraint.upper.constant);\n                    u_coeffs.push_back(Parameter(std::numeric_limits<double>::max()));\n                }\n            }\n        }\n\n        // Build cost function\n        if (problem.costFunction.getOrder() == 0 or problem.costFunction.isNorm())\n        {\n            throw std::runtime_error(\"QP cost functions must be linear or quadratic.\");\n        }\n\n        // Linear part\n        for (Term &term : problem.costFunction.affine.terms)\n        {\n            addVariable(term.variable);\n            q_params(term.variable.getProblemIndex()) += term.parameter;\n        }\n\n        // Quadratic part\n        for (Product &product : problem.costFunction.products)\n        {\n            for (Term &term1 : product.firstTerm().terms)\n            {\n                for (Term &term2 : product.secondTerm().terms)\n                {\n                    addVariable(term1.variable);\n                    addVariable(term2.variable);\n\n                    const std::pair<size_t, size_t> sorted = std::minmax(term1.variable.getProblemIndex(),\n                                                                         term2.variable.getProblemIndex());\n\n                    Parameter param = term1.parameter * term2.parameter;\n\n                    // Explicitly double diagonal elements\n                    if (sorted.first == sorted.second)\n                    {\n                        param *= Parameter(2.);\n                    }\n\n                    P_coeffs.emplace_back(sorted.first,\n                                          sorted.second,\n                                          param);\n                }\n            }\n\n            // The linear parts from the multiplication\n            if (not product.firstTerm().constant.isZero())\n            {\n                for (Term &term : product.secondTerm().terms)\n                {\n                    addVariable(term.variable);\n                    q_params(term.variable.getProblemIndex()) += product.firstTerm().constant * term.parameter;\n                }\n            }\n            if (not product.secondTerm().constant.isZero())\n            {\n                for (Term &term : product.firstTerm().terms)\n                {\n                    addVariable(term.variable);\n                    q_params(term.variable.getProblemIndex()) += product.secondTerm().constant * term.parameter;\n                }\n            }\n        }\n\n        assert(l_coeffs.size() == u_coeffs.size());\n\n        // Fill matrices and vectors\n        A_params.resize(l_coeffs.size(), getNumVariables());\n        P_params.resize(getNumVariables(), getNumVariables());\n\n        A_params.setFromTriplets(A_coeffs.begin(), A_coeffs.end());\n        P_params.setFromTriplets(P_coeffs.begin(), P_coeffs.end());\n\n        l_params = Eigen::Map<VectorXp>(l_coeffs.data(), l_coeffs.size());\n        u_params = Eigen::Map<VectorXp>(u_coeffs.data(), u_coeffs.size());\n\n        solution->resize(getNumVariables());\n    }\n\n    size_t QPWrapperBase::getNumInequalityConstraints() const\n    {\n        return A_params.rows();\n    }\n\n    void QPWrapperBase::addVariable(Variable &variable)\n    {\n        const bool was_linked = variable.linkToSolver(solution, getNumVariables());\n        if (was_linked)\n        {\n            variables.push_back(variable);\n            q_params.conservativeResize(getNumVariables());\n        }\n    }\n\n    std::ostream &operator<<(std::ostream &os, const QPWrapperBase &wrapper)\n    {\n        Eigen::MatrixXd A = eval(wrapper.A_params);\n        Eigen::MatrixXd P = eval(wrapper.P_params);\n        P += P.triangularView<Eigen::StrictlyUpper>().transpose();\n        Eigen::VectorXd q = eval(wrapper.q_params);\n        Eigen::VectorXd l = eval(wrapper.l_params);\n        Eigen::VectorXd u = eval(wrapper.u_params);\n\n        os << \"Quadratic problem\\n\";\n        os << \"Minimize 0.5x'Px + q'x\\n\";\n        os << \"Subject to l <= Ax <= u\\n\";\n        os << \"With:\\n\\n\";\n\n        os << \"P:\\n\"\n           << P << \"\\n\\n\";\n        os << \"q:\\n\"\n           << q << \"\\n\\n\";\n        os << \"A:\\n\"\n           << A << \"\\n\\n\";\n        os << \"l:\\n\"\n           << l << \"\\n\\n\";\n        os << \"u:\\n\"\n           << u;\n\n        return os;\n    }\n\n    bool QPWrapperBase::isConvex() const\n    {\n        if (P_params.nonZeros() == 0)\n        {\n            return true;\n        }\n        else\n        {\n            Eigen::LLT<Eigen::MatrixXd> llt(eval(P_params));\n            return llt.info() != Eigen::NumericalIssue;\n        }\n    }\n\n} // namespace cvx::internal\n", "meta": {"hexsha": "7726b2c0e650da8c686ad3cf1e5c96d2faff2738", "size": 8797, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/wrappers/qpWrapperBase.cpp", "max_stars_repo_name": "BenjaminNavarro/Epigraph", "max_stars_repo_head_hexsha": "c76293fe437d68442598c080ab092e3806177b48", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/wrappers/qpWrapperBase.cpp", "max_issues_repo_name": "BenjaminNavarro/Epigraph", "max_issues_repo_head_hexsha": "c76293fe437d68442598c080ab092e3806177b48", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/wrappers/qpWrapperBase.cpp", "max_forks_repo_name": "BenjaminNavarro/Epigraph", "max_forks_repo_head_hexsha": "c76293fe437d68442598c080ab092e3806177b48", "max_forks_repo_licenses": ["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.0532786885, "max_line_length": 112, "alphanum_fraction": 0.4959645334, "num_tokens": 1600, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.49254899744864633}}
{"text": "#include <iostream>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/cycle_canceling.hpp>\n#include <boost/graph/push_relabel_max_flow.hpp>\n#include <boost/graph/successive_shortest_path_nonnegative_weights.hpp>\n#include <boost/graph/find_flow_cost.hpp>\n\n// Graph Type with nested interior edge properties for Cost Flow Algorithms\ntypedef boost::adjacency_list_traits<boost::vecS, boost::vecS, boost::directedS> traits;\ntypedef boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS, boost::no_property,\n                              boost::property<boost::edge_capacity_t, long,\n                                              boost::property<boost::edge_residual_capacity_t, long,\n                                                              boost::property<boost::edge_reverse_t, traits::edge_descriptor,\n                                                                              boost::property<boost::edge_weight_t, long>>>>>\n    graph; // new! weightmap corresponds to costs\ntypedef boost::graph_traits<graph>::edge_descriptor edge_desc;\ntypedef boost::graph_traits<graph>::out_edge_iterator out_edge_it; // Iterator\n\n// Custom edge adder class\nclass edge_adder\n{\n    graph &G;\n\npublic:\n    explicit edge_adder(graph &G) : G(G) {}\n    void add_edge(int from, int to, long capacity, long cost)\n    {\n        auto c_map = boost::get(boost::edge_capacity, G);\n        auto r_map = boost::get(boost::edge_reverse, G);\n        auto w_map = boost::get(boost::edge_weight, G); // new!\n        const edge_desc e = boost::add_edge(from, to, G).first;\n        const edge_desc rev_e = boost::add_edge(to, from, G).first;\n        c_map[e] = capacity;\n        c_map[rev_e] = 0; // reverse edge has no capacity!\n        r_map[e] = rev_e;\n        r_map[rev_e] = e;\n        w_map[e] = cost;      // new assign cost\n        w_map[rev_e] = -cost; // new negative cost\n    }\n};\n\nusing namespace std;\n\nvoid solve()\n{\n    int buyers, sites, states;\n    cin >> buyers >> sites >> states;\n\n    graph G(states + sites + buyers);\n    edge_adder adder(G);\n    auto c_map = boost::get(boost::edge_capacity, G);\n    auto r_map = boost::get(boost::edge_reverse, G);\n    auto rc_map = boost::get(boost::edge_residual_capacity, G);\n\n    auto source = boost::add_vertex(G);\n    auto target = boost::add_vertex(G);\n\n    int stateLimit;\n    for (int state = 0; state < states; ++state) {\n        cin >> stateLimit;\n        adder.add_edge(source, state, stateLimit, 0);\n    }\n\n    int state;\n    int offsetSites = states;\n    for (int site = offsetSites; site < offsetSites + sites; ++site) {\n        cin >> state; --state; // convert to 0 based\n        adder.add_edge(state, site, 1, 0);\n    }\n\n    int bid; \n    int maxBid = 100;\n    int offsetBuyers = states + sites;\n    for (int buyer = offsetBuyers; buyer < offsetBuyers + buyers; ++buyer) {\n        for (int site = offsetSites; site < offsetSites + sites; ++site) {\n            cin >> bid;\n            adder.add_edge(site, buyer, 1, maxBid - bid); // Avoid negative costs\n        }\n        adder.add_edge(buyer, target, 1, 0);\n    }\n\n    boost::successive_shortest_path_nonnegative_weights(G, source, target);\n    auto cost = boost::find_flow_cost(G);\n    \n    int flow = 0;\n    out_edge_it e, eend;\n    for (boost::tie(e, eend) = boost::out_edges(boost::vertex(source, G), G); e != eend; ++e)\n    {\n        flow += c_map[*e] - rc_map[*e];\n    }\n    cost = maxBid * flow - cost; // Convert back to actual cost\n\n    cout << flow << \" \" << cost << endl;\n}\n\nint main()\n{\n    int t; cin >> t;\n    for (int i = 0; i < t; ++i) {\n        solve();\n    }\n    return 0;\n}\n", "meta": {"hexsha": "79cc318d2b17cb4433b71ef61c10e92dcd707362", "size": 3616, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/real_estate.cpp", "max_stars_repo_name": "dsparber/algolab", "max_stars_repo_head_hexsha": "9781eb5c7444236f796f167f1f39fc9d913e5c53", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2021-01-01T17:19:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T12:27:57.000Z", "max_issues_repo_path": "src/real_estate.cpp", "max_issues_repo_name": "dsparber/algolab", "max_issues_repo_head_hexsha": "9781eb5c7444236f796f167f1f39fc9d913e5c53", "max_issues_repo_licenses": ["MIT"], "max_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_estate.cpp", "max_forks_repo_name": "dsparber/algolab", "max_forks_repo_head_hexsha": "9781eb5c7444236f796f167f1f39fc9d913e5c53", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-28T10:55:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-28T10:55:25.000Z", "avg_line_length": 34.7692307692, "max_line_length": 125, "alphanum_fraction": 0.6020464602, "num_tokens": 931, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812554, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.49254899744864633}}
{"text": "/*\n * StokesM2L.cpp\n *\n *  Created on: Oct 12, 2016\n *      Author: wyan\n */\n\n#include \"SVD_pvfmm.hpp\"\n\n#include <Eigen/Dense>\n\n#include <iomanip>\n#include <iostream>\n\n#define DIRECTLAYER 2\n\nnamespace StokesPVel1D3D {\n\nusing EVec3 = Eigen::Vector3d;\nusing EVec4 = Eigen::Vector4d;\nusing EMat3 = Eigen::Matrix3d;\nusing EMat4 = Eigen::Matrix4d;\n\n/**\n * \\brief Returns the coordinates of points on the surface of a cube.\n * \\param[in] p Number of points on an edge of the cube is (n+1)\n * \\param[in] c Coordinates to the centre of the cube (3D array).\n * \\param[in] alpha Scaling factor for the size of the cube.\n * \\param[in] depth Depth of the cube in the octree.\n * \\return Vector with coordinates of points on the surface of the cube in the\n * format [x0 y0 z0 x1 y1 z1 .... ].\n */\ntemplate <class Real_t>\nstd::vector<Real_t> surface(int p, Real_t *c, Real_t alpha, int depth) {\n    size_t n_ = (6 * (p - 1) * (p - 1) + 2); // Total number of points.\n\n    std::vector<Real_t> coord(n_ * 3);\n    coord[0] = coord[1] = coord[2] = -1.0;\n    size_t cnt = 1;\n    for (int i = 0; i < p - 1; i++)\n        for (int j = 0; j < p - 1; j++) {\n            coord[cnt * 3] = -1.0;\n            coord[cnt * 3 + 1] = (2.0 * (i + 1) - p + 1) / (p - 1);\n            coord[cnt * 3 + 2] = (2.0 * j - p + 1) / (p - 1);\n            cnt++;\n        }\n    for (int i = 0; i < p - 1; i++)\n        for (int j = 0; j < p - 1; j++) {\n            coord[cnt * 3] = (2.0 * i - p + 1) / (p - 1);\n            coord[cnt * 3 + 1] = -1.0;\n            coord[cnt * 3 + 2] = (2.0 * (j + 1) - p + 1) / (p - 1);\n            cnt++;\n        }\n    for (int i = 0; i < p - 1; i++)\n        for (int j = 0; j < p - 1; j++) {\n            coord[cnt * 3] = (2.0 * (i + 1) - p + 1) / (p - 1);\n            coord[cnt * 3 + 1] = (2.0 * j - p + 1) / (p - 1);\n            coord[cnt * 3 + 2] = -1.0;\n            cnt++;\n        }\n    for (size_t i = 0; i < (n_ / 2) * 3; i++)\n        coord[cnt * 3 + i] = -coord[i];\n\n    Real_t r = 0.5 * pow(0.5, depth);\n    Real_t b = alpha * r;\n    for (size_t i = 0; i < n_; i++) {\n        coord[i * 3 + 0] = (coord[i * 3 + 0] + 1.0) * b + c[0];\n        coord[i * 3 + 1] = (coord[i * 3 + 1] + 1.0) * b + c[1];\n        coord[i * 3 + 2] = (coord[i * 3 + 2] + 1.0) * b + c[2];\n    }\n    return coord;\n}\n\n// fx,fy,fz,trD -> p, vx,vy,vz\ninline void Wkernel(const EVec3 &target, const EVec3 &source, EMat4 &answer) {\n    auto rst = target - source;\n    double rnorm = rst.norm();\n    if (rnorm < 1e-13) {\n        answer.setZero();\n        return;\n    }\n    double rnorm3 = rnorm * rnorm * rnorm;\n\n    answer.block<3, 3>(1, 0) = EMat3::Identity() / rnorm;\n    answer.block<3, 3>(1, 0) += rst * rst.transpose() / rnorm3;\n\n    answer(0, 0) = rst[0] / rnorm3;\n    answer(0, 1) = rst[1] / rnorm3;\n    answer(0, 2) = rst[2] / rnorm3;\n    answer(0, 3) = 0;\n    answer(1, 3) = -rst[0] / rnorm3;\n    answer(2, 3) = -rst[1] / rnorm3;\n    answer(3, 3) = -rst[2] / rnorm3;\n    answer.row(0) *= (1 / (4 * M_PI));\n    answer.block<3, 4>(1, 0) *= (1 / (8 * M_PI));\n}\n\ninline void WkernelFF(const EVec3 &target, const EVec3 &source, EMat4 &answer) {\n    answer.setZero();\n    const int imageN = 1000000; // images to sum\n    for (int per = DIRECTLAYER + 1; per < imageN; per++) {\n        EVec3 perVec(1.0 * per, 0, 0);\n        EMat4 W1 = EMat4::Zero();\n        EMat4 W2 = EMat4::Zero();\n        Wkernel(target, source + perVec, W1);\n        Wkernel(target, source - perVec, W2);\n        answer += (W1 + W2);\n    }\n}\n\n// calculate the M2L matrix of images from 2 to 1000\nint main(int argc, char **argv) {\n    Eigen::initParallel();\n    Eigen::setNbThreads(1);\n\n    const int pEquiv = atoi(argv[1]); // (8-1)^2*6 + 2 points\n    const int pCheck = atoi(argv[1]);\n    const double scaleEquiv = 1.05;\n    const double scaleCheck = 2.95;\n    const double pCenterEquiv[3] = {-(scaleEquiv - 1) / 2, -(scaleEquiv - 1) / 2, -(scaleEquiv - 1) / 2};\n    const double pCenterCheck[3] = {-(scaleCheck - 1) / 2, -(scaleCheck - 1) / 2, -(scaleCheck - 1) / 2};\n    auto pointMEquiv = surface(pEquiv, (double *)&(pCenterEquiv[0]), scaleEquiv,\n                               0); // center at 0.5,0.5,0.5, periodic box 1,1,1, scale 1.05, depth = 0\n    auto pointMCheck = surface(pCheck, (double *)&(pCenterCheck[0]), scaleCheck,\n                               0); // center at 0.5,0.5,0.5, periodic box 1,1,1, scale 1.05, depth = 0\n\n    auto pointLEquiv = surface(pEquiv, (double *)&(pCenterCheck[0]), scaleCheck,\n                               0); // center at 0.5,0.5,0.5, periodic box 1,1,1, scale 1.05, depth = 0\n    auto pointLCheck = surface(pCheck, (double *)&(pCenterEquiv[0]), scaleEquiv,\n                               0); // center at 0.5,0.5,0.5, periodic box 1,1,1, scale 1.05, depth = 0\n\n    // calculate the operator M2L with least square\n    const int equivN = pointMEquiv.size() / 3;\n    const int checkN = pointLCheck.size() / 3;\n    Eigen::MatrixXd A(4 * checkN, 4 * equivN);\n#pragma omp parallel for\n    for (int k = 0; k < checkN; k++) {\n        EMat4 W;\n        W.setZero();\n        Eigen::Vector3d Cpoint(pointLCheck[3 * k], pointLCheck[3 * k + 1], pointLCheck[3 * k + 2]);\n        for (int l = 0; l < equivN; l++) {\n            const Eigen::Vector3d Lpoint(pointLEquiv[3 * l], pointLEquiv[3 * l + 1], pointLEquiv[3 * l + 2]);\n            Wkernel(Cpoint, Lpoint, W);\n            A.block<4, 4>(4 * k, 4 * l) = W;\n        }\n    }\n    Eigen::MatrixXd ApinvU(A.cols(), A.rows());\n    Eigen::MatrixXd ApinvVT(A.cols(), A.rows());\n    pinv(A, ApinvU, ApinvVT);\n\n    Eigen::MatrixXd M2L(4 * equivN, 4 * equivN);\n#pragma omp parallel for\n    for (int i = 0; i < equivN; i++) {\n        const Eigen::Vector3d Mpoint(pointMEquiv[3 * i], pointMEquiv[3 * i + 1], pointMEquiv[3 * i + 2]);\n        Eigen::MatrixXd f(4 * checkN, 4);\n        for (int k = 0; k < checkN; k++) {\n            EMat4 temp = EMat4::Zero();\n            Eigen::Vector3d Cpoint(pointLCheck[3 * k], pointLCheck[3 * k + 1], pointLCheck[3 * k + 2]);\n            WkernelFF(Cpoint, Mpoint, temp);\n            f.block<4, 4>(4 * k, 0) = temp;\n        }\n        M2L.block(0, 4 * i, 4 * equivN, 4) = (ApinvU.transpose() * (ApinvVT.transpose() * f));\n    }\n\n    // dump M2L\n    for (int i = 0; i < 4 * equivN; i++) {\n        for (int j = 0; j < 4 * equivN; j++) {\n            std::cout << i << \" \" << j << \" \" << std::scientific << std::setprecision(18) << M2L(i, j) << std::endl;\n        }\n    }\n\n    // Test\n    // Sum of force and trD must be zero\n    std::vector<EVec3, Eigen::aligned_allocator<EVec3>> forcePoint(3);\n    std::vector<EVec4, Eigen::aligned_allocator<EVec4>> forceValue(3);\n    forcePoint[0] = EVec3(0.5, 0.55, 0.2);\n    forcePoint[1] = EVec3(0.5, 0.5, 0.5);\n    forcePoint[2] = EVec3(0.7, 0.7, 0.7);\n    forceValue[0] = EVec4(0.1, 0.2, 0.3, 0.4);\n    forceValue[1] = EVec4(-0.1, -0.1, -0.3, -0.4);\n    forceValue[2] = EVec4(0, -0.1, 0, 0);\n\n    // solve M\n    A.resize(4 * checkN, 4 * equivN);\n    ApinvU.resize(A.cols(), A.rows());\n    ApinvVT.resize(A.cols(), A.rows());\n    Eigen::VectorXd f(4 * checkN);\n#pragma omp parallel for\n    for (int k = 0; k < checkN; k++) {\n        Eigen::Vector3d Cpoint(pointMCheck[3 * k], pointMCheck[3 * k + 1], pointMCheck[3 * k + 2]);\n        EVec4 temp = EVec4::Zero();\n        for (int p = 0; p < forceValue.size(); p++) {\n            EMat4 W = EMat4::Zero();\n            Wkernel(Cpoint, forcePoint[p], W);\n            temp += W * (forceValue[p]);\n        }\n        f.block<4, 1>(4 * k, 0) = temp;\n        for (int l = 0; l < equivN; l++) {\n            Eigen::Vector3d Mpoint(pointMEquiv[3 * l], pointMEquiv[3 * l + 1], pointMEquiv[3 * l + 2]);\n            EMat4 W = EMat4::Zero();\n            Wkernel(Cpoint, Mpoint, W);\n            A.block<4, 4>(4 * k, 4 * l) = W;\n        }\n    }\n    pinv(A, ApinvU, ApinvVT);\n    Eigen::VectorXd Msource = (ApinvU.transpose() * (ApinvVT.transpose() * f));\n\n    std::cout << \"Msource: \" << Msource << std::endl;\n    std::cout << \"Msource Sum: \" << Msource.sum() << std::endl;\n    Eigen::VectorXd M2Lsource = M2L * (Msource);\n\n    {\n        EVec3 samplePoint(0.5, 0.2, 0.8);\n        // Compute: WFF from L, WFF from WkernelFF\n        EVec4 WFFL = EVec4::Zero();\n        EVec4 WFFK = EVec4::Zero();\n\n        for (int k = 0; k < equivN; k++) {\n            EVec3 Lpoint(pointLEquiv[3 * k], pointLEquiv[3 * k + 1], pointLEquiv[3 * k + 2]);\n            EMat4 W = EMat4::Zero();\n            Wkernel(samplePoint, Lpoint, W);\n            WFFL += W * M2Lsource.block<4, 1>(4 * k, 0);\n        }\n\n        for (int k = 0; k < forceValue.size(); k++) {\n            EMat4 W;\n            WkernelFF(samplePoint, forcePoint[k], W);\n            WFFK += W * forceValue[k];\n        }\n        std::cout << \"WFF from Lequiv: \" << WFFL << std::endl;\n        std::cout << \"WFF from Kernel: \" << WFFK << std::endl;\n        std::cout << \"FF Error: \" << WFFL - WFFK << std::endl;\n    }\n\n    return 0;\n}\n\n} // namespace StokesPVel1D3D\n\n#undef DIRECTLAYER\n", "meta": {"hexsha": "8b69c1cbda334c36c24577ecdc3c81f92fbfd1bd", "size": 8927, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "M2L/StokesPVel/StokesPVel1D3D.cpp", "max_stars_repo_name": "lamsoa729/STKFMM", "max_stars_repo_head_hexsha": "26d7d971c198e3bed68eb8373e5590a6eb72f764", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "M2L/StokesPVel/StokesPVel1D3D.cpp", "max_issues_repo_name": "lamsoa729/STKFMM", "max_issues_repo_head_hexsha": "26d7d971c198e3bed68eb8373e5590a6eb72f764", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "M2L/StokesPVel/StokesPVel1D3D.cpp", "max_forks_repo_name": "lamsoa729/STKFMM", "max_forks_repo_head_hexsha": "26d7d971c198e3bed68eb8373e5590a6eb72f764", "max_forks_repo_licenses": ["Apache-2.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.0414937759, "max_line_length": 116, "alphanum_fraction": 0.5143945334, "num_tokens": 3310, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812552, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.49254899744864616}}
{"text": "//\n// Created by Alex Beccaro on 18/01/18.\n//\n\n#define BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n#include \"../../src/problems/1-50/6/problem6.hpp\"\n\nBOOST_AUTO_TEST_SUITE( Problem6 )\n\n    BOOST_AUTO_TEST_CASE( Example ) {\n        auto res = problems::problem6::solve(10);\n        BOOST_CHECK_EQUAL(res, 2640);\n    }\n\n    BOOST_AUTO_TEST_CASE( Solution ) {\n        auto res = problems::problem6::solve();\n        BOOST_CHECK_EQUAL(res, 25164150);\n    }\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "c7bcb4d16043d4755e97e3259b2a578cb34d45d6", "size": 493, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/1-50/test_problem6.cpp", "max_stars_repo_name": "abeccaro/project-euler", "max_stars_repo_head_hexsha": "c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T10:17:15.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-25T10:17:15.000Z", "max_issues_repo_path": "tests/1-50/test_problem6.cpp", "max_issues_repo_name": "abeccaro/project-euler", "max_issues_repo_head_hexsha": "c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3", "max_issues_repo_licenses": ["MIT"], "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/1-50/test_problem6.cpp", "max_forks_repo_name": "abeccaro/project-euler", "max_forks_repo_head_hexsha": "c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3", "max_forks_repo_licenses": ["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.4761904762, "max_line_length": 49, "alphanum_fraction": 0.6754563895, "num_tokens": 127, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6654105720171531, "lm_q2_score": 0.7401743620390162, "lm_q1q2_score": 0.49251984563681317}}
{"text": "#include \"../include/Length.h\"\r\n\n#include <vector>\n#include <fstream>\n#include <iostream>\n\n#include \"../include/utility.h\"\n#include \"../include/Timer.h\"\n#include \"../include/exceptions.h\"\n\n#include <boost/lexical_cast.hpp>\n#include <boost/iostreams/filtering_streambuf.hpp>\n#include <boost/iostreams/copy.hpp>\n#include <boost/iostreams/filter/zlib.hpp>\n//#include \"Model.cpp\"\n\nusing namespace boost;\n\nstring Length::ending = \"length\";\n\r\nLength::Length(Corpus* co) : Model<Length>(co)\r\n{\n    size1 = LMAX;\n    size2 = LMAX;\n    systemMessage(\"Creating Length Model\");\r\n    model = new float*[LMAX];\n    float norm[LMAX];\n    for(int i = 0; i < LMAX; i++)\n    {\n        model[i] = new float[LMAX];\n        norm[i] = SMOOTH * LMAX;\n        for(int j = 0; j < LMAX; j++)\n        {\n            model[i][j] = SMOOTH;\n        }\n    }\n\n    vector<int*>::iterator eIt;\n    vector<int*>::iterator fIt;\n\n    int m = 0;\n    int n = 0;\n\n    for(eIt = co->getElines()->begin(), fIt = co->getFlines()->begin(); eIt != co->getElines()->end(), fIt != co->getFlines()->end(); eIt++, fIt++)\n    {\n        m = (*eIt)[0];\n        n = (*fIt)[0];\n        if(m < LMAX && n < LMAX)\n        {\n            model[n][m] += 1.0;\n            norm[m] += 1.0;\n        }\n    }\n\n    for(int i = 0; i < LMAX; i++)\n    {\n        for(int j = 0; j < LMAX; j++)\n        {\n            model[i][j] = model[i][j]/norm[j];\n        }\n    }\n    saveModel();\r\n}\n\nfloat** Length::getLengthmodel()\n{\n    return model;\n}\r\n", "meta": {"hexsha": "72f1bdc9abef4716e29b64000c3d040ca2579991", "size": 1472, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "share/packages/implementations/jobst-ibm1/src/Length.cpp", "max_stars_repo_name": "tud-fop/vanda-studio", "max_stars_repo_head_hexsha": "b636a695d5ba1f199c07aa0950bfeacede4fdf19", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-31T12:07:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-31T12:07:50.000Z", "max_issues_repo_path": "share/packages/implementations/jobst-ibm1/src/Length.cpp", "max_issues_repo_name": "tud-fop/vanda-studio", "max_issues_repo_head_hexsha": "b636a695d5ba1f199c07aa0950bfeacede4fdf19", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "share/packages/implementations/jobst-ibm1/src/Length.cpp", "max_forks_repo_name": "tud-fop/vanda-studio", "max_forks_repo_head_hexsha": "b636a695d5ba1f199c07aa0950bfeacede4fdf19", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-04-08T14:51:01.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-08T14:51:01.000Z", "avg_line_length": 21.3333333333, "max_line_length": 147, "alphanum_fraction": 0.5217391304, "num_tokens": 437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743735019594, "lm_q2_score": 0.6654105587468141, "lm_q1q2_score": 0.49251984344201183}}
{"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 BOOST_SIMD_META_IS_POWER_OF_2_HPP_INCLUDED\n#define BOOST_SIMD_META_IS_POWER_OF_2_HPP_INCLUDED\n\n#include <cstddef>\n#include <boost/mpl/bool.hpp>\n\nnamespace boost { namespace simd {  namespace meta\n{\n  /*!\n    @brief Checks if an integral value is a power of two.\n\n    is_power_of_2_c checks if any given integral @c N is a non-zero power of two.\n\n    @par Semantic:\n    For any given integral value @c N:\n\n    @code\n    typedef is_power_of_2_c<N>::type r;\n    @endcode\n\n    is equivalent to:\n\n    @code\n    typedef mpl::bool<(!(N & (N - 1)) && N)> r;\n    @endcode\n\n    @usage{meta/is_power_of_2_c.cpp}\n\n    @tparam N Integral value to check\n  **/\n  template<std::size_t N> struct  is_power_of_2_c\n#if !defined(DOXYGEN_ONLY)\n        : boost::mpl::bool_<(!(N & (N - 1)) && N)>\n#endif\n  {};\n\n  /*!\n    @brief Checks if an @mplint is a power of two.\n\n    is_power_of_2_c is a Boolean @metafunction that checks if any given\n    @mplint @c N is a non-zero power of two.\n\n    @par Semantic:\n    For any given @mplint @c N:\n\n    @code\n    typedef is_power_of_2<N>::type r;\n    @endcode\n\n    is equivalent to:\n\n    @code\n    typedef is_power_of_2_c<N::value>::type r;\n    @endcode\n\n    @usage{meta/is_power_of_2.cpp}\n\n    @tparam N @mplint to check\n  **/\n  template<class N> struct  is_power_of_2\n#if !defined(DOXYGEN_ONLY)\n        : boost::mpl::bool_<(!(N::value & (N::value - 1)) && N::value)>\n#endif\n  {};\n} } }\n\n#endif\n", "meta": {"hexsha": "59a9d5a0b34343051be0e52a88d206ad4e0439a0", "size": 1978, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/sdk/include/boost/simd/meta/is_power_of_2.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/sdk/include/boost/simd/meta/is_power_of_2.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/boost/simd/sdk/include/boost/simd/meta/is_power_of_2.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": 25.6883116883, "max_line_length": 81, "alphanum_fraction": 0.58190091, "num_tokens": 545, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.4925198407256308}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2013   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2013   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#include <nt2/trigonometric/include/functions/indeg.hpp>\n\n#include <nt2/sdk/functor/meta/call.hpp>\n#include <boost/simd/sdk/simd/native.hpp>\n#include <nt2/sdk/unit/tests/type_expr.hpp>\n#include <nt2/sdk/unit/tests/ulp.hpp>\n#include <nt2/include/functions/splat.hpp>\n#include <nt2/include/functions/unary_minus.hpp>\n#include <nt2/sdk/unit/module.hpp>\n#include <boost/simd/sdk/config.hpp>\n#include <boost/simd/sdk/simd/io.hpp>\n\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/zero.hpp>\n#include <nt2/include/constants/inf.hpp>\n#include <nt2/include/constants/minf.hpp>\n#include <nt2/include/constants/nan.hpp>\n#include <nt2/include/constants/_45.hpp>\n#include <nt2/include/constants/_90.hpp>\n#include <nt2/include/constants/_180.hpp>\n\nNT2_TEST_CASE_TPL ( indeg_real_1,  NT2_SIMD_REAL_TYPES)\n{\n  using nt2::indeg;\n  using nt2::tag::indeg_;\n  using boost::simd::native;\n  typedef BOOST_SIMD_DEFAULT_EXTENSION  ext_t;\n  typedef native<T,ext_t>                  vT;\n\n  typedef typename nt2::meta::call<indeg_(vT)>::type r_t;\n  typedef vT wished_r_t;\n\n  // return type conformity test\n  NT2_TEST_TYPE_IS(r_t, wished_r_t);\n\n\n  // specific values tests\n#ifndef BOOST_SIMD_NO_INVALIDS\n  NT2_TEST_ULP_EQUAL(indeg(nt2::Inf<vT>()), nt2::Inf<r_t>(), 0.5);\n  NT2_TEST_ULP_EQUAL(indeg(nt2::Minf<vT>()), nt2::Minf<r_t>(), 0.5);\n  NT2_TEST_ULP_EQUAL(indeg(nt2::Nan<vT>()), nt2::Nan<r_t>(), 0.5);\n#endif\n  NT2_TEST_ULP_EQUAL(indeg(-nt2::Pi<vT>()), -nt2::_180<r_t>(), 0.5);\n  NT2_TEST_ULP_EQUAL(indeg(-nt2::Pio_2<vT>()), -nt2::_90<r_t>(), 0.5);\n  NT2_TEST_ULP_EQUAL(indeg(-nt2::Pio_4<vT>()), -nt2::_45<r_t>(), 0.5);\n  NT2_TEST_ULP_EQUAL(indeg(nt2::Pi<vT>()), nt2::_180<r_t>(), 0.5);\n  NT2_TEST_ULP_EQUAL(indeg(nt2::Pio_2<vT>()), nt2::_90<r_t>(), 0.5);\n  NT2_TEST_ULP_EQUAL(indeg(nt2::Pio_4<vT>()), nt2::_45<r_t>(), 0.5);\n  NT2_TEST_ULP_EQUAL(indeg(nt2::Zero<vT>()), nt2::Zero<r_t>(), 0.5);\n}\n", "meta": {"hexsha": "517f23f22dd9eb6b923ee6b54efbde4a22be3171", "size": 2490, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/core/trigonometric/unit/simd/indeg.cpp", "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/unit/simd/indeg.cpp", "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/unit/simd/indeg.cpp", "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.8196721311, "max_line_length": 80, "alphanum_fraction": 0.6493975904, "num_tokens": 762, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.6654105587468141, "lm_q1q2_score": 0.4925198358144485}}
{"text": "//\n// Created by riku on 2016/07/19.\n//\n#include \"core/ctxt_util.hpp\"\n#include \"core/literal.hpp\"\n#include \"HElib/Ctxt.h\"\n#include \"HElib/EncryptedArray.h\"\n#include \"HElib/PAlgebra.h\"\n#include <NTL/ZZ.h>\n#include <random>\n#include <algorithm>\n#include <sstream>\n\nnamespace core {\nsize_t number_bits(long a) {\n    size_t bits = 0;\n    while (a > 0) {\n        bits += 1;\n        a = a >> 1;\n    }\n    return bits;\n}\n\nstatic bool test_bit(long a, size_t i) {\n    return (a & (1 << i)) != 0;\n}\n\nCtxt repeat0(const Ctxt &c,\n             const long n_slots, const long rep,\n             const EncryptedArray &ea) {\n    Ctxt repeated(c);\n    Ctxt res(c.getPubKey()); /// zero-like\n    long offset = n_slots;\n    for (size_t i = 0; i < number_bits(rep); i++) {\n        if (test_bit(rep, i)) {\n            FHE_NTIMER_START(ea_rotate);\n            ea.rotate(res, offset);\n            FHE_NTIMER_STOP(ea_rotate);\n            res += repeated;\n        }\n        Ctxt tmp(repeated);\n        FHE_NTIMER_START(ea_rotate);\n        ea.rotate(tmp, offset);\n        FHE_NTIMER_STOP(ea_rotate);\n        repeated += tmp;\n        offset = offset << 1;\n    }\n    return res;\n}\n\nCtxt repeat(const Ctxt &c,\n            const long n_slots, const long rep,\n            const EncryptedArray &ea) {\n    assert(n_slots * rep <= ea.size() && \"n_slots * rep > ea.size()\");\n    assert(n_slots >= 0 && rep >= 0 && \"n_slots < 0 || rep < 0\");\n    Ctxt repeated(c);\n    mask_first(repeated, n_slots, ea);\n    return repeat0(repeated, n_slots, rep, ea);\n}\n\n// NOTE. This function might introduce too many noise.\nvoid replicate(Ctxt *out, const int pos ,const int length, const EncryptedArray *ea) {\n    ZZX mask;\n    ea->encodeUnitSelector(mask, pos);\n    out->multByConstant(mask);\n    ea->rotate(*out, -pos);\n    long offset = 0;\n    long k = number_bits(length);\n    Ctxt ctxt_orig(*out);\n    long e = 1;\n    // now process bits k-2 down to 0\n    for (long j = k-2; j >= 0; j--) {\n        // e -> 2*e\n        Ctxt tmp = *out;\n        ea->rotate(tmp, e);\n        out->addCtxt(tmp);\n        e <<= 1;\n\n        long b = test_bit(length, j);\n        // e -> e+b\n        if (b) {\n            ea->rotate(*out, 1);\n            out->addCtxt(ctxt_orig);\n            e++;\n        }\n    }\n}\n\nvoid mask_first(Ctxt &ctxt, size_t n, const EncryptedArray &ea) {\n    std::vector<long> mask(ea.size(), 0);\n    for (long i = 0; i < n; i++) mask[i] = 1;\n    NTL::ZZX poly;\n    ea.encode(poly, mask);\n    ctxt.multByConstant(poly);\n}\n\nstd::vector<std::vector<long>> random_permutation(long D, const EncryptedArray &ea) {\n    size_t nr = (D + ea.size() - 1) / ea.size();\n    std::vector<std::vector<long>> parts(nr, std::vector<long>(ea.size(), 0));\n    std::vector<long> I(nr * ea.size(), 0);\n    for (size_t i = 0; i < I.size(); i++) I.at(i) = i;\n\n    std::random_shuffle(I.begin(), I.end());\n    auto itr = I.begin();\n    for (auto &part : parts) {\n        for (auto &value : part) {\n            value = *itr;\n            itr++;\n        }\n    }\n    return parts;\n}\n\nstd::vector<std::vector<long>> randomness(long D, const EncryptedArray &ea) {\n    size_t nr = (D + ea.size() - 1) / ea.size();\n    std::vector<std::vector<long>> parts(nr, std::vector<long>(ea.size()));\n    std::vector<long> I(nr * ea.size());\n    long pr = ea.getAlMod().getPPowR();\n    for (size_t i = 0; i < I.size(); i++) {\n        do{\n            I.at(i) = NTL::RandomBnd(pr);\n        } while (I.at(i) == 0);\n    }\n    auto itr = I.begin();\n    for (auto &part : parts) {\n        for (auto &value : part) {\n            value = *itr;\n            itr++;\n        }\n    }\n    return parts;\n}\n\ntemplate<>\nstd::string conv(const Ctxt &obj) {\n    std::stringstream sstream;\n    sstream << obj;\n    return sstream.str();\n}\n\ntemplate<>\nvoid conv(Ctxt &obj, const std::string &str) {\n    std::stringstream sstream(str);\n    sstream >> obj;\n}\n\nbool dumpCtxts(const std::vector<Ctxt> &ctxts,\n               const std::string &outputDirPath) {\n    auto makePath = [](std::string const& path, const long count) -> std::string {\n        return path + literal::separator + \"FILE_\" + std::to_string(count);\n    };\n\n    long file_nr = 1;\n    long ctx_dumped = 0;\n    std::ofstream fout(makePath(outputDirPath, file_nr), std::ios::binary | std::ios::trunc);\n    if (!fout.is_open()) {\n        return false;\n    }\n\n    for (const Ctxt &ctx :ctxts) {\n        if (ctx_dumped < core::core_setting.CTX_PER_FILE) {\n            fout << ctx;\n            ctx_dumped += 1;\n        } else {\n            fout.close();\n            file_nr += 1;\n            fout.open(makePath(outputDirPath, file_nr), std::ios::binary);\n            if (!fout.is_open())\n                return false;\n            fout << ctx;\n            ctx_dumped = 1;\n        }\n    }\n    fout.close();\n    return true;\n}\n\n}\n\n", "meta": {"hexsha": "1bd7cd92182d148b186996f11b1d8ce900ca833e", "size": 4777, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "core/src/core/ctxt_util.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/core/ctxt_util.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/core/ctxt_util.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": 26.5388888889, "max_line_length": 93, "alphanum_fraction": 0.5407159305, "num_tokens": 1371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.49251983090326595}}
{"text": "//\n// Copyright (c) 2019 INRIA\n//\n\n#include <pinocchio/autodiff/casadi.hpp>\n#include <Eigen/Dense>\n\n#include <boost/variant.hpp> // to avoid C99 warnings\n\n#include <boost/test/unit_test.hpp>\n#include <boost/utility/binary.hpp>\n\nBOOST_AUTO_TEST_SUITE(BOOST_TEST_MODULE)\n\nBOOST_AUTO_TEST_CASE(test_eigen)\n{\n  Eigen::Matrix<casadi::SX, 3, 3> A, B;\n  Eigen::Matrix<casadi::SX, 3, 1> a, b;\n  Eigen::Matrix<casadi::SX, 3, 1> c = A * a - B.transpose() * b;\n}\n\n// A function working with Eigen::Matrix'es parameterized by the Scalar type\ntemplate <typename Scalar, typename T1, typename T2, typename T3, typename T4>\nEigen::Matrix<Scalar, Eigen::Dynamic, 1>\neigenFun(Eigen::MatrixBase<T1> const& A,\n         Eigen::MatrixBase<T2> const& a,\n         Eigen::MatrixBase<T3> const& B,\n         Eigen::MatrixBase<T4> const& b)\n{\n  Eigen::Matrix<Scalar, Eigen::Dynamic, 1> c(4);\n  c.segment(1, 3) = A * a.segment(1, 3) - B.transpose() * b;\n  c[0] = 0.;\n  \n  return c;\n}\n\nBOOST_AUTO_TEST_CASE(test_example)\n{\n  // Declare casadi symbolic matrix arguments\n  casadi::SX cs_a = casadi::SX::sym(\"a\", 4);\n  casadi::SX cs_b = casadi::SX::sym(\"b\", 3);\n  \n  // Declare Eigen matrices\n  Eigen::Matrix<casadi::SX, 3, 3> A, B;\n  Eigen::Matrix<casadi::SX, -1, 1> a (4), c (4);\n  Eigen::Matrix<casadi::SX, 3, 1> b;\n  \n  // Let A, B be some numeric matrices\n  for (Eigen::Index i = 0; i < A.rows(); ++i)\n  {\n    for (Eigen::Index j = 0; j < A.cols(); ++j)\n    {\n      A(i, j) = 10. * static_cast<double>(i) + static_cast<double>(j);\n      B(i, j) = -10. * static_cast<double>(i) - static_cast<double>(j);\n    }\n  }\n  \n  // Let a, b be symbolic arguments of a function\n  pinocchio::casadi::copy(cs_b, b);\n  pinocchio::casadi::copy(cs_a, a);\n  \n  // Call the function taking Eigen matrices\n  c = eigenFun<casadi::SX>(A, a, B, b);\n  \n  // Copy the result from Eigen matrices to casadi matrix\n  casadi::SX cs_c = casadi::SX(casadi::Sparsity::dense(c.rows(), 1));\n  pinocchio::casadi::copy(c, cs_c);\n  \n  // Display the resulting casadi matrix\n  std::cout << \"c = \" << cs_c << std::endl;\n  \n  // Do some AD\n  casadi::SX dc_da = jacobian(cs_c, cs_a);\n  \n  // Display the resulting jacobian\n  std::cout << \"dc/da = \" << dc_da << std::endl;\n  \n  // Create a function which takes a, b and returns c and dc_da\n  casadi::Function fun(\"fun\", casadi::SXVector {cs_a, cs_b}, casadi::SXVector {cs_c, dc_da});\n  std::cout << \"fun = \" << fun << std::endl;\n  \n  // Evaluate the function\n  casadi::DMVector res = fun(casadi::DMVector {std::vector<double> {1., 2., 3., 4.}, std::vector<double> {-1., -2., -3.}});\n  std::cout << \"fun(a, b)=\" << res << std::endl;\n}\n\nBOOST_AUTO_TEST_CASE(test_jacobian)\n{\n  casadi::SX cs_x = casadi::SX::sym(\"x\", 3);\n  \n  casadi::SX cs_y = casadi::SX::sym(\"y\", 1);\n  cs_y(0) = cs_x(0) + cs_x(1) + cs_x(2);\n  \n  // Display the resulting expression\n  std::cout << \"y = \" << cs_y << std::endl;\n  \n  // Do some AD\n  casadi::SX dy_dx = jacobian(cs_x, cs_x);\n\n  // Display the resulting jacobian\n  std::cout << \"dy/dx = \" << dy_dx << std::endl;\n}\n\nBOOST_AUTO_TEST_CASE(test_copy_casadi_to_eigen)\n{\n  casadi::SX cs_mat = casadi::SX::sym(\"A\", 3, 4);\n  Eigen::Matrix<casadi::SX, 3, 4> eig_mat;\n\n  pinocchio::casadi::copy(cs_mat, eig_mat);\n  std::cout << eig_mat << std::endl;\n}\n\nBOOST_AUTO_TEST_CASE(test_copy_eigen_to_casadi)\n{\n  Eigen::Matrix<casadi::SX, 3, 4> eig_mat;\n  pinocchio::casadi::sym(eig_mat, \"A\");\n\n  casadi::SX cs_mat;\n\n  pinocchio::casadi::copy(eig_mat, cs_mat);\n  std::cout << cs_mat << std::endl;\n}\n\nBOOST_AUTO_TEST_CASE(test_casadi_codegen)\n{\n  casadi::SX x = casadi::SX::sym(\"x\");\n  casadi::SX y = casadi::SX::sym(\"y\");\n  casadi::Function fun(\"fun\", casadi::SXVector {x, y}, casadi::SXVector {x + y});\n  \n  casadi::CodeGenerator gen(\"module\");\n  gen.add(fun);\n  \n  std::cout << gen.dump();\n}\n\nBOOST_AUTO_TEST_CASE(test_max)\n{\n  casadi::SX x = casadi::SX::sym(\"x\");\n  casadi::SX y = casadi::SX::sym(\"y\");\n  \n  casadi::SX max_x_y = pinocchio::math::max(x,y);\n  casadi::SX max_x_0 = pinocchio::math::max(x,0.);\n  casadi::SX max_0_y = pinocchio::math::max(0.,y);\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "43baf49debb57b266966d07bacaa48da2da9c80e", "size": 4084, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittest/casadi-basic.cpp", "max_stars_repo_name": "yDMhaven/pinocchio", "max_stars_repo_head_hexsha": "fabed17d5ad0dc1c8d251c64cfa656a0215469a5", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-04-07T07:23:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-07T07:23:34.000Z", "max_issues_repo_path": "unittest/casadi-basic.cpp", "max_issues_repo_name": "yDMhaven/pinocchio", "max_issues_repo_head_hexsha": "fabed17d5ad0dc1c8d251c64cfa656a0215469a5", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unittest/casadi-basic.cpp", "max_forks_repo_name": "yDMhaven/pinocchio", "max_forks_repo_head_hexsha": "fabed17d5ad0dc1c8d251c64cfa656a0215469a5", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-25T13:34:37.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-25T13:34:37.000Z", "avg_line_length": 27.5945945946, "max_line_length": 123, "alphanum_fraction": 0.6285504407, "num_tokens": 1415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.49251982327570243}}
{"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]=-10;\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}\nextern \"C\" void externalForcesB1(double t, double *f, unsigned int size_z,double *z)\n{\n  f[0]=0;\n  f[1]=0;\n  f[2]=-9.81*0.038;\n  // printf(\"externalForcesB1 :\\n\");\n  // printf(\"f[0] = %e\\t f[1] = %e\\t, f[2]=%e\\n\",f[0],f[1],f[2]);\n}\nextern \"C\" void internalForcesB1(double t, double *q, double *v, double *f, unsigned int size_z,double *z)\n{\n  // Simple spring in z direction.\n  f[0]=0;\n  f[1]=0;\n  f[2]=1e4*q[2];\n  // printf(\"internalForcesB1 :\\n\");\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 internalForcesB1_Jacq(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[2+2*3]=1e4;\n  // printf(\"internalForcesB1_Jacq :\\n\");\n  // printf(\"jac[2+2*3] = %e\\n\", jac[2+2*3]);\n}\n\nextern \"C\" void internalMomentsB1(double t, double *q, double *v, double *m, unsigned int size_z,double *z)\n{\n  //  printf(\"internalMomentsB1 :\\n\");\n  // Simple torsional spring around y axis\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);\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 internalMomentsB1_Jacq(double t, double *q, double *v, double *jac, unsigned int size_z,double *z)\n{\n  //printf(\"internalMomentsB1_Jacq :\\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[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}\n\nextern \"C\" void externalForcesB2(double t,double *f, unsigned  int size_z,double *z)\n{\n  f[0]=0;\n  f[1]=0;\n  f[2]=-9.81*0.038;\n\n}\n\nextern \"C\" void externalForcesS(double t,double *f, unsigned int size_z, double *z)\n{\n  f[0]=0;\n  f[1]=0;\n  f[2]=-9.81*0.076;\n\n}\nextern \"C\" void externalForceG(double t,double *f, unsigned  int size_z, double *z)\n{\n  // std::cout << \"externalForceG\"<<std::endl;\n  f[0]=0;\n  f[1]=0;\n  f[2]=-9.81;\n}\n\nextern \"C\" void prescribedvelocityB1(double time, unsigned int sizeofprescribedvelocity, double *pv)\n{\n  /* the plugin implements v(t) = C + A cos(omega *t) */\n\n  double C = -150.0 ;\n  double omega = M_PI / 2.0;\n  double A = 10.0;\n\n  //pv[0] =  A * cos(omega * time*100.0);\n  pv[0] =  C;\n  //printf(\"prescribed velocity = %e\\n\", pv[0]);\n}\n", "meta": {"hexsha": "296d2e13dfcf21c28c89068245cceefefe1cf079", "size": 2965, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/mechanics/Mechanisms/SliderCrank/SliderCrankPlugin/SliderCrankPlugin.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/Mechanisms/SliderCrank/SliderCrankPlugin/SliderCrankPlugin.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/Mechanisms/SliderCrank/SliderCrankPlugin/SliderCrankPlugin.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.7083333333, "max_line_length": 114, "alphanum_fraction": 0.560539629, "num_tokens": 1225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.810478926981208, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4924981938521616}}
{"text": "#include \"Solver.h\"\n#include <algorithm> /* min, max */\n#include <armadillo>\n#include <assert.h>\n#include <math.h>   /* pow */\n#include <functional>\n#include <stdlib.h> /* abs, drand48 */\n\nusing namespace arma;\n\ndouble SmoSolver::SvmOutputOnPoint(int i) {\n  vec point = this->x.row(i).t();\n  double result = (kernel->*(kernel->KernelFunction))(this->theta, point);\n  return result - this->b;\n}\n\ndouble SmoSolver::Predict(vec &x) { return dot(this->theta, x) - this->b; }\n\ndouble SmoSolver::KernelCal(int i1, int i2) {\n  vec point1 = this->x.row(i1).t();\n  vec point2 = this->x.row(i2).t();\n  return (kernel->*(kernel->KernelFunction))(point1, point2);\n}\n\nint SmoSolver::TakeStep(int i1, int i2) {\n  double alpha1 = 0.0, alpha2 = 0.0;\n  double a1 = 0.0, a2 = 0.0;\n  int y1 = 0, y2 = 0;\n  double e1 = 0.0, e2 = 0.0;\n  int s = 0;\n  double low = 0.0, high = 0.0;\n  double k11 = 0.0, k12 = 0.0, k22 = 0.0, eta = 0.0;\n\n  if (i1 == i2) {\n    return 0;\n  }\n\n  alpha1 = this->lagrangeMultiplier[i1];\n  alpha2 = this->lagrangeMultiplier[i2];\n  y1 = this->y[i1];\n  y2 = this->y[i2];\n\n  if (alpha1 > 0 && alpha1 < this->C) {\n    e1 = this->errorCache[i1];\n  } else {\n    e1 = this->SvmOutputOnPoint(i1) - y1;\n  }\n  if (alpha2 > 0 && alpha2 < this->C) {\n    e2 = this->errorCache[i2];\n  } else {\n    e2 = this->SvmOutputOnPoint(i1) - y2;\n  }\n\n  s = y1 * y2;\n  if (y1 != y2) {\n    double temp = alpha2 - alpha1;\n    low = std::max(0.0, temp);\n    high = std::min(this->C, this->C + temp);\n  } else {\n    double temp = alpha2 + alpha1;\n    low = std::max(0.0, temp - this->C);\n    high = std::min(this->C, temp);\n  }\n\n  // check if low is equal to high\n  if (abs(low - high) < 1.0e-7) {\n    return 0;\n  }\n  k11 = this->KernelCal(i1, i1);\n  k12 = this->KernelCal(i1, i2);\n  k22 = this->KernelCal(i2, i2);\n  eta = k11 + k22 - 2 * k12;\n\n  if (eta > 0) {\n    a2 = alpha2 + y2 * (e1 - e2) / eta;\n    if (a2 < low) {\n      a2 = low;\n    } else if (a2 > high) {\n      a2 = high;\n    }\n  } else {\n    // In papaer 2.1 (19)\n    double f1 = y1 * (e1 + this->b) - alpha1 * k11 - s * alpha2 * k12;\n    double f2 = y2 * (e2 + this->b) - s * alpha1 * k12 - alpha2 * k12;\n    double low1 = alpha1 + s * (alpha2 - low);\n    double high1 = alpha1 + s * (alpha2 - high);\n    double objLow = low1 * f1 + low * f2 + 0.5 * pow(low1, 2.0) * k11 +\n                    0.5 * pow(low, 2.0) * k22 + s * low * low1 * k12;\n    double objHigh = high1 * f1 + high * f2 + 0.5 * pow(high1, 2.0) * k11 +\n                     0.5 * pow(high, 2.0) * k22 + s * high * high1 * k12;\n    if (objLow < objHigh - this->eps) {\n      a2 = low;\n    } else if (objLow > objHigh + this->eps) {\n      a2 = high;\n    } else {\n      a2 = alpha2;\n    }\n  }\n\n  if (std::abs(a2 - alpha2) < this->eps * (a2 + alpha2 + this->eps)) {\n    return 0;\n  }\n  a1 = alpha1 + s * (alpha2 - a2);\n\n  // Update threshold to reflect change in Lagrange multipliers\n  double b1 = 0.0;\n  double b2 = 0.0;\n  double bReal = 0.0;\n  double temp1 = y1 * (a1 - alpha1);\n  double temp2 = y2 * (a2 - alpha2);\n  if (a1 > 0 && a1 < this->C) {\n    bReal = e1 + temp1 * k11 + temp2 * k12 + b;\n  } else if (a2 > 0 && a2 < this->C) {\n    bReal = e2 + temp1 * k12 + temp2 * k22 + b;\n  } else {\n    b1 = e1 + temp1 * k11 + temp2 * k12 + b;\n    b2 = e2 + temp1 * k12 + temp2 * k22 + b;\n    bReal = (b1 + b2) / 2.0;\n  }\n  double bDiff = bReal - this->b;\n  this->b = bReal;\n\n  // Update weight vector (theta) to reflect change in al & a2, if SVM is\n  // linear\n  if (this->kernel->kernelType == LINEAR) {\n    this->theta = this->theta + temp1 * this->x.row(i1).t() +\n                  temp2 * this->x.row(i2).t();\n  }\n  // Update error cache using new Lagrange multipliers\n  int exampleNum = this->ExampleNum();\n  for (int i = 0; i < exampleNum; i++) {\n    if (lagrangeMultiplier[i] > 0 && lagrangeMultiplier[i] < this->C) {\n      this->errorCache[i] += temp1 * this->KernelCal(i1, i) +\n                             temp2 * this->KernelCal(i2, i) - bDiff;\n    }\n  }\n\n  this->errorCache[i1] = 0.0;\n  this->errorCache[i2] = 0.0;\n\n  // Store a1, a2 in the alpha array\n  this->lagrangeMultiplier[i1] = a1;\n  this->lagrangeMultiplier[i2] = a2;\n  return 1;\n}\n\nint SmoSolver::ExamineExample(int i2) {\n  double y2 = 0.0;\n  double alpha2 = 0.0;\n  double e2 = 0.0;\n  double r2 = 0.0;\n\n  alpha2 = this->lagrangeMultiplier[i2];\n  y2 = this->y[i2];\n  if (alpha2 > 0 && alpha2 < this->C) {\n    e2 = this->errorCache[i2];\n  } else {\n    e2 = this->SvmOutputOnPoint(i2) - y2;\n  }\n  r2 = e2 * y2;\n\n  int exampleNum = this->ExampleNum();\n  //\n  double tmax = 0.0;\n  int i1 = 0;\n  int k = 0;\n  if ((r2 < -tol && alpha2 < this->C) || (r2 > tol && alpha2 > 0)) {\n    for (i1 = -1, tmax = 0, k = 0; k < exampleNum; k++) {\n      if (lagrangeMultiplier[k] > 0 && lagrangeMultiplier[k] < this->C) {\n        double e1 = 0.0;\n        double temp = 0.0;\n        e1 = this->errorCache[k];\n        temp = std::abs(e2 - e1);\n        if (temp > tmax) {\n          tmax = temp;\n          i1 = k;\n        }\n      }\n      if (i1 >= 0) {\n        if (TakeStep(i1, i2)) {\n          return 1;\n        }\n      }\n    }\n\n    for (int i = (int)(drand48() * exampleNum), k = i; k < exampleNum + i;\n         k++) {\n      i1 = k % exampleNum;\n      if (lagrangeMultiplier[i1] > 0 && lagrangeMultiplier[i1] < C) {\n        if (TakeStep(i1, i2)) {\n          return 1;\n        }\n      }\n    }\n    for (int i = (int)(drand48() * exampleNum), k = i; k < exampleNum + i;\n         k++) {\n      i1 = k % exampleNum;\n      if (TakeStep(i1, i2)) {\n        return 1;\n      }\n    }\n  }\n  return 0;\n}\n\nint SmoSolver::ExampleNum() { return (int)this->x.n_rows; }\n\nint SmoSolver::Train() {\n  int exampleNum = this->ExampleNum();\n  if (!trained) {\n    this->b = 0.0;\n    this->theta = zeros<vec>(exampleNum);\n    this->errorCache = zeros<vec>(exampleNum);\n    this->lagrangeMultiplier = zeros<vec>(exampleNum);\n  }\n\n  unsigned int numChanged = 0;\n  unsigned int examineAll = 1;\n  while (numChanged > 0 || examineAll) {\n    numChanged = 0;\n    if (examineAll) {\n      for (unsigned int i = 0; i < exampleNum; i++) {\n        numChanged += ExamineExample(i);\n      }\n    } else {\n      for (unsigned int i = 0; i < exampleNum; i++) {\n        if (lagrangeMultiplier[i] != 0 && lagrangeMultiplier[i] != C) {\n          numChanged += ExamineExample(i);\n        }\n      }\n    }\n    if (examineAll == 1) {\n      examineAll = 0;\n    } else if (numChanged == 0) {\n      examineAll = 1;\n    }\n  }\n  this->trained = true;\n  return 0;\n}\n", "meta": {"hexsha": "eaeb6cecda5a1edc96050cd4f85cb4f8cb34cea8", "size": 6455, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/SVM/Solver.cc", "max_stars_repo_name": "Gh0u1L5/Cetus", "max_stars_repo_head_hexsha": "979a13db4f6837e845fd5f540f7a710d0256dd9a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/SVM/Solver.cc", "max_issues_repo_name": "Gh0u1L5/Cetus", "max_issues_repo_head_hexsha": "979a13db4f6837e845fd5f540f7a710d0256dd9a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SVM/Solver.cc", "max_forks_repo_name": "Gh0u1L5/Cetus", "max_forks_repo_head_hexsha": "979a13db4f6837e845fd5f540f7a710d0256dd9a", "max_forks_repo_licenses": ["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.7842323651, "max_line_length": 75, "alphanum_fraction": 0.5284275755, "num_tokens": 2383, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257653, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.4924981882887363}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2012-2014 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_GET_LEFT_TURNS_HPP\n#define BOOST_GEOMETRY_ALGORITHMS_DETAIL_GET_LEFT_TURNS_HPP\n\n#include <boost/geometry/core/assert.hpp>\n\n#include <boost/geometry/arithmetic/arithmetic.hpp>\n#include <boost/geometry/algorithms/detail/overlay/segment_identifier.hpp>\n#include <boost/geometry/algorithms/detail/overlay/turn_info.hpp>\n#include <boost/geometry/iterators/closing_iterator.hpp>\n#include <boost/geometry/iterators/ever_circling_iterator.hpp>\n#include <boost/geometry/strategies/side.hpp>\n\nnamespace boost { namespace geometry\n{\n\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail\n{\n\n// TODO: move this to /util/\ntemplate <typename T>\ninline std::pair<T, T> ordered_pair(T const& first, T const& second)\n{\n    return first < second ? std::make_pair(first, second) : std::make_pair(second, first);\n}\n\nnamespace left_turns\n{\n\n\n\ntemplate <typename Vector>\ninline int get_quadrant(Vector const& vector)\n{\n    // Return quadrant as layouted in the code below:\n    // 3 | 0\n    // -----\n    // 2 | 1\n    return geometry::get<1>(vector) >= 0\n        ? (geometry::get<0>(vector)  < 0 ? 3 : 0)\n        : (geometry::get<0>(vector)  < 0 ? 2 : 1)\n        ;\n}\n\ntemplate <typename Vector>\ninline int squared_length(Vector const& vector)\n{\n    return geometry::get<0>(vector) * geometry::get<0>(vector)\n         + geometry::get<1>(vector) * geometry::get<1>(vector)\n         ;\n}\n\n\ntemplate <typename Point>\nstruct angle_less\n{\n    typedef Point vector_type;\n    typedef typename strategy::side::services::default_strategy\n    <\n        typename cs_tag<Point>::type\n    >::type side_strategy_type;\n\n    angle_less(Point const& origin)\n        : m_origin(origin)\n    {}\n\n    template <typename Angle>\n    inline bool operator()(Angle const& p, Angle const& q) const\n    {\n        // Vector origin -> p and origin -> q\n        vector_type pv = p.point;\n        vector_type qv = q.point;\n        geometry::subtract_point(pv, m_origin);\n        geometry::subtract_point(qv, m_origin);\n\n        int const quadrant_p = get_quadrant(pv);\n        int const quadrant_q = get_quadrant(qv);\n        if (quadrant_p != quadrant_q)\n        {\n            return quadrant_p < quadrant_q;\n        }\n        // Same quadrant, check if p is located left of q\n        int const side = side_strategy_type::apply(m_origin, q.point,\n                    p.point);\n        if (side != 0)\n        {\n            return side == 1;\n        }\n        // Collinear, check if one is incoming, incoming angles come first\n        if (p.incoming != q.incoming)\n        {\n            return int(p.incoming) < int(q.incoming);\n        }\n        // Same quadrant/side/direction, return longest first\n        // TODO: maybe not necessary, decide this\n        int const length_p = squared_length(pv);\n        int const length_q = squared_length(qv);\n        if (length_p != length_q)\n        {\n            return squared_length(pv) > squared_length(qv);\n        }\n        // They are still the same. Just compare on seg_id\n        return p.seg_id < q.seg_id;\n    }\n\nprivate:\n    Point m_origin;\n};\n\ntemplate <typename Point>\nstruct angle_equal_to\n{\n    typedef Point vector_type;\n    typedef typename strategy::side::services::default_strategy\n    <\n        typename cs_tag<Point>::type\n    >::type side_strategy_type;\n\n    inline angle_equal_to(Point const& origin)\n        : m_origin(origin)\n    {}\n\n    template <typename Angle>\n    inline bool operator()(Angle const& p, Angle const& q) const\n    {\n        // Vector origin -> p and origin -> q\n        vector_type pv = p.point;\n        vector_type qv = q.point;\n        geometry::subtract_point(pv, m_origin);\n        geometry::subtract_point(qv, m_origin);\n\n        if (get_quadrant(pv) != get_quadrant(qv))\n        {\n            return false;\n        }\n        // Same quadrant, check if p/q are collinear\n        int const side = side_strategy_type::apply(m_origin, q.point,\n                    p.point);\n        return side == 0;\n    }\n\nprivate:\n    Point m_origin;\n};\n\ntemplate <typename AngleCollection, typename Turns>\ninline void get_left_turns(AngleCollection const& sorted_angles,\n        Turns& turns)\n{\n    std::set<int> good_incoming;\n    std::set<int> good_outgoing;\n\n    for (typename boost::range_iterator<AngleCollection const>::type it =\n        sorted_angles.begin(); it != sorted_angles.end(); ++it)\n    {\n        if (!it->blocked)\n        {\n            if (it->incoming)\n            {\n                good_incoming.insert(it->turn_index);\n            }\n            else\n            {\n                good_outgoing.insert(it->turn_index);\n            }\n        }\n    }\n\n    if (good_incoming.empty() || good_outgoing.empty())\n    {\n        return;\n    }\n\n    for (typename boost::range_iterator<AngleCollection const>::type it =\n        sorted_angles.begin(); it != sorted_angles.end(); ++it)\n    {\n        if (good_incoming.count(it->turn_index) == 0\n            || good_outgoing.count(it->turn_index) == 0)\n        {\n            turns[it->turn_index].remove_on_multi = true;\n        }\n    }\n}\n\n\n//! Returns the number of clusters\ntemplate <typename Point, typename AngleCollection>\ninline std::size_t assign_cluster_indices(AngleCollection& sorted, Point const& origin)\n{\n    // Assign same cluster_index for all turns in same direction\n    BOOST_GEOMETRY_ASSERT(boost::size(sorted) >= 4u);\n\n    angle_equal_to<Point> comparator(origin);\n    typename boost::range_iterator<AngleCollection>::type it = sorted.begin();\n\n    std::size_t cluster_index = 0;\n    it->cluster_index = cluster_index;\n    typename boost::range_iterator<AngleCollection>::type previous = it++;\n    for (; it != sorted.end(); ++it)\n    {\n        if (!comparator(*previous, *it))\n        {\n            cluster_index++;\n            previous = it;\n        }\n        it->cluster_index = cluster_index;\n    }\n    return cluster_index + 1;\n}\n\ntemplate <typename AngleCollection>\ninline void block_turns(AngleCollection& sorted, std::size_t cluster_size)\n{\n    BOOST_GEOMETRY_ASSERT(boost::size(sorted) >= 4u && cluster_size > 0);\n\n    std::vector<std::pair<bool, bool> > directions;\n    for (std::size_t i = 0; i < cluster_size; i++)\n    {\n        directions.push_back(std::make_pair(false, false));\n    }\n\n    for (typename boost::range_iterator<AngleCollection const>::type it = sorted.begin();\n        it != sorted.end(); ++it)\n    {\n        if (it->incoming)\n        {\n            directions[it->cluster_index].first = true;\n        }\n        else\n        {\n            directions[it->cluster_index].second = true;\n        }\n    }\n\n    for (typename boost::range_iterator<AngleCollection>::type it = sorted.begin();\n        it != sorted.end(); ++it)\n    {\n        int cluster_index = it->cluster_index;\n        int previous_index = cluster_index - 1;\n        if (previous_index < 0)\n        {\n            previous_index = cluster_size - 1;\n        }\n        int next_index = cluster_index + 1;\n        if (next_index >= static_cast<int>(cluster_size))\n        {\n            next_index = 0;\n        }\n\n        if (directions[cluster_index].first\n            && directions[cluster_index].second)\n        {\n            it->blocked = true;\n        }\n        else if (!directions[cluster_index].first\n            && directions[cluster_index].second\n            && directions[previous_index].second)\n        {\n            // Only outgoing, previous was also outgoing: block this one\n            it->blocked = true;\n        }\n        else if (directions[cluster_index].first\n            && !directions[cluster_index].second\n            && !directions[previous_index].first\n            && directions[previous_index].second)\n        {\n            // Only incoming, previous was only outgoing: block this one\n            it->blocked = true;\n        }\n        else if (directions[cluster_index].first\n            && !directions[cluster_index].second\n            && directions[next_index].first\n            && !directions[next_index].second)\n        {\n            // Only incoming, next also incoming, block this one\n            it->blocked = true;\n        }\n    }\n}\n\n#if defined(BOOST_GEOMETRY_BUFFER_ENLARGED_CLUSTERS)\ntemplate <typename AngleCollection, typename Point>\ninline bool has_rounding_issues(AngleCollection const& angles, Point const& origin)\n{\n    for (typename boost::range_iterator<AngleCollection const>::type it =\n        angles.begin(); it != angles.end(); ++it)\n    {\n        // Vector origin -> p and origin -> q\n        typedef Point vector_type;\n        vector_type v = it->point;\n        geometry::subtract_point(v, origin);\n        return geometry::math::abs(geometry::get<0>(v)) <= 1\n            || geometry::math::abs(geometry::get<1>(v)) <= 1\n            ;\n    }\n    return false;\n}\n#endif\n\n\n}  // namespace left_turns\n\n} // namespace detail\n#endif // DOXYGEN_NO_DETAIL\n\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_GET_LEFT_TURNS_HPP\n", "meta": {"hexsha": "3361b139c3b8e5b0531094f89040cbc92b0ce4ee", "size": 9217, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3party/boost/boost/geometry/algorithms/detail/get_left_turns.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/algorithms/detail/get_left_turns.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/algorithms/detail/get_left_turns.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": 28.8934169279, "max_line_length": 90, "alphanum_fraction": 0.6169035478, "num_tokens": 2168, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.49249818828873626}}
{"text": "#include <iostream>\n#include \"GUI/GlutGUI/GLApp.h\"\n#include \"Framework/Framework/SceneGraph.h\"\n#include \"Dynamics/EmbeddedMethod/EmbeddedFiniteElement.h\"\n#include \"Dynamics/ParticleSystem/StaticBoundary.h\"\n#include \"Dynamics/ParticleSystem/ElasticityModule.h\"\n#include \"Dynamics/ParticleSystem/ParticleElasticBody.h\"\n#include \"Rendering/SurfaceMeshRender.h\"\n#include \"Rendering/PointRenderModule.h\"\n#include <boost/property_tree/json_parser.hpp>\n\n#include \"Dynamics/EmbeddedMethod/EmbeddedFiniteElement.h\"\n#include \"Dynamics/EmbeddedMethod/EmbeddedMassSpring.h\"\n\nusing namespace PhysIKA;\nusing namespace std;\n\nint main(int argc, char* argv[])\n{\n    Log::sendMessage(Log::Info, \"Simulation start\");\n\n    SceneGraph& scene = SceneGraph::getInstance();\n\n    std::shared_ptr<StaticBoundary<DataType3f>> root = scene.createNewScene<StaticBoundary<DataType3f>>();\n    root->loadCube(Vector3f(0), Vector3f(1), 0.005f, true);\n\n    const string discret_m = argc != 3 ? \"fem\" : argv[1];\n    const string calcu_m   = argc != 3 ? \"implicit_euler\" : argv[2];\n\n    if (discret_m == \"tet_fem\")\n    {\n        std::shared_ptr<EmbeddedFiniteElement<DataType3f>> bunny = std::make_shared<EmbeddedFiniteElement<DataType3f>>();\n        root->addParticleSystem(bunny);\n        auto m_pointsRender = std::make_shared<PointRenderModule>();\n        m_pointsRender->setColor(Vector3f(0, 1, 1));\n        bunny->addVisualModule(m_pointsRender);\n\n        bunny->setMass(1.0);\n        bunny->loadParticles(\"../../Media/bunny/bunny_points.obj\");\n        bunny->loadSurface(\"../../Media/bunny/bunny_mesh.obj\");\n\n        // bunny->scale(1.0 / 6);\n        bunny->translate(Vector3f(0.5, 0.2, 0.5));\n        bunny->setVisible(true);\n\n        auto sRender = std::make_shared<SurfaceMeshRender>();\n        bunny->getSurfaceNode()->addVisualModule(sRender);\n        sRender->setColor(Vector3f(1, 1, 0));\n\n        // bunny->getElasticitySolver()->setIterationNumber(10);\n        boost::property_tree::ptree pt;\n        const std::string           jsonfile_path = \"../../Media/bunny/embedded_finite_element.json\";\n        read_json(jsonfile_path, pt);\n        bunny->init_problem_and_solver(pt);\n    }\n    else if (discret_m == \"mass_spring\")\n    {\n        std::shared_ptr<EmbeddedMassSpring<DataType3f>> bunny = std::make_shared<EmbeddedMassSpring<DataType3f>>();\n        root->addParticleSystem(bunny);\n\n        auto m_pointsRender = std::make_shared<PointRenderModule>();\n        m_pointsRender->setColor(Vector3f(0, 1, 1));\n        bunny->addVisualModule(m_pointsRender);\n\n        bunny->setMass(1.0);\n        bunny->loadParticles(\"../../Media/bunny/bunny_points.obj\");\n        bunny->loadSurface(\"../../Media/bunny/bunny_mesh.obj\");\n\n        // bunny->scale(1.0 / 6);\n        bunny->translate(Vector3f(0.5, 0.2, 0.5));\n        bunny->setVisible(true);\n\n        auto sRender = std::make_shared<SurfaceMeshRender>();\n        bunny->getSurfaceNode()->addVisualModule(sRender);\n        sRender->setColor(Vector3f(1, 1, 0));\n\n        // bunny->getElasticitySolver()->setIterationNumber(10);\n        boost::property_tree::ptree pt;\n        const std::string           jsonfile_path = \"../../Media/bunny/embedded_mass_spring.json\";\n        read_json(jsonfile_path, pt);\n        bunny->init_problem_and_solver(pt);\n    }\n    else if (discret_m == \"voxel\")\n    {\n        std::shared_ptr<ParticleElasticBody<DataType3f>> bunny = std::make_shared<ParticleElasticBody<DataType3f>>();\n        root->addParticleSystem(bunny);\n\n        auto m_pointsRender = std::make_shared<PointRenderModule>();\n        m_pointsRender->setColor(Vector3f(0, 1, 1));\n        bunny->addVisualModule(m_pointsRender);\n\n        bunny->setMass(1.0);\n        bunny->loadParticles(\"../../Media/bunny/bunny_points.obj\");\n        bunny->loadSurface(\"../../Media/bunny/bunny_mesh.obj\");\n        bunny->translate(Vector3f(0.5, 0.2, 0.5));\n        bunny->setVisible(true);\n\n        auto sRender = std::make_shared<SurfaceMeshRender>();\n        bunny->getSurfaceNode()->addVisualModule(sRender);\n        sRender->setColor(Vector3f(1, 1, 0));\n\n        bunny->getElasticitySolver()->setIterationNumber(10);\n    }\n    else if (discret_m == \"particle\")\n    {\n        std::shared_ptr<ParticleElasticBody<DataType3f>> bunny = std::make_shared<ParticleElasticBody<DataType3f>>();\n        root->addParticleSystem(bunny);\n\n        auto m_pointsRender = std::make_shared<PointRenderModule>();\n        m_pointsRender->setColor(Vector3f(0, 1, 1));\n        bunny->addVisualModule(m_pointsRender);\n\n        bunny->setMass(1.0);\n        bunny->loadParticles(\"../../Media/bunny/bunny_points.obj\");\n        bunny->loadSurface(\"../../Media/bunny/bunny_mesh.obj\");\n        bunny->translate(Vector3f(0.5, 0.2, 0.5));\n        bunny->setVisible(true);\n\n        auto sRender = std::make_shared<SurfaceMeshRender>();\n        bunny->getSurfaceNode()->addVisualModule(sRender);\n        sRender->setColor(Vector3f(1, 1, 0));\n\n        bunny->getElasticitySolver()->setIterationNumber(10);\n    }\n    else if (discret_m == \"hybrid\")\n    {\n        std::shared_ptr<ParticleElasticBody<DataType3f>> bunny = std::make_shared<ParticleElasticBody<DataType3f>>();\n        root->addParticleSystem(bunny);\n\n        auto m_pointsRender = std::make_shared<PointRenderModule>();\n        m_pointsRender->setColor(Vector3f(0, 1, 1));\n        bunny->addVisualModule(m_pointsRender);\n\n        bunny->setMass(1.0);\n        bunny->loadParticles(\"../../Media/bunny/bunny_points.obj\");\n        bunny->loadSurface(\"../../Media/bunny/bunny_mesh.obj\");\n        bunny->translate(Vector3f(0.5, 0.2, 0.5));\n        bunny->setVisible(true);\n\n        auto sRender = std::make_shared<SurfaceMeshRender>();\n        bunny->getSurfaceNode()->addVisualModule(sRender);\n        sRender->setColor(Vector3f(1, 1, 0));\n\n        bunny->getElasticitySolver()->setIterationNumber(10);\n    }\n    else\n    {\n        std::shared_ptr<EmbeddedFiniteElement<DataType3f>> bunny = std::make_shared<EmbeddedFiniteElement<DataType3f>>();\n        root->addParticleSystem(bunny);\n        auto m_pointsRender = std::make_shared<PointRenderModule>();\n        m_pointsRender->setColor(Vector3f(0, 1, 1));\n        bunny->addVisualModule(m_pointsRender);\n\n        bunny->setMass(1.0);\n        bunny->loadParticles(\"../../Media/bunny/bunny_points.obj\");\n        bunny->loadSurface(\"../../Media/bunny/bunny_mesh.obj\");\n\n        // bunny->scale(1.0 / 6);\n        bunny->translate(Vector3f(0.5, 0.2, 0.5));\n        bunny->setVisible(true);\n\n        auto sRender = std::make_shared<SurfaceMeshRender>();\n        bunny->getSurfaceNode()->addVisualModule(sRender);\n        sRender->setColor(Vector3f(1, 1, 0));\n\n        // bunny->getElasticitySolver()->setIterationNumber(10);\n        boost::property_tree::ptree pt;\n        const std::string           jsonfile_path = \"../../Media/bunny/embedded_finite_element.json\";\n        read_json(jsonfile_path, pt);\n        bunny->init_problem_and_solver(pt);\n    }\n\n    GLApp window;\n    window.createWindow(1024, 768);\n\n    window.mainLoop();\n\n    return 0;\n}\n", "meta": {"hexsha": "e92a762936bc97df68f7355bc233693061f17d11", "size": 7029, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Examples/App_Test/main.cpp", "max_stars_repo_name": "weikm/sandcarSimulation2", "max_stars_repo_head_hexsha": "fe499d0a3289c0ac1acce69c7dc78d8ce1b2708a", "max_stars_repo_licenses": ["Apache-2.0"], "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/App_Test/main.cpp", "max_issues_repo_name": "weikm/sandcarSimulation2", "max_issues_repo_head_hexsha": "fe499d0a3289c0ac1acce69c7dc78d8ce1b2708a", "max_issues_repo_licenses": ["Apache-2.0"], "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/App_Test/main.cpp", "max_forks_repo_name": "weikm/sandcarSimulation2", "max_forks_repo_head_hexsha": "fe499d0a3289c0ac1acce69c7dc78d8ce1b2708a", "max_forks_repo_licenses": ["Apache-2.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.05, "max_line_length": 121, "alphanum_fraction": 0.6555697823, "num_tokens": 1796, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.4924981827253109}}
{"text": "//==================================================================================================\n/**\n  EVE - Expressive Vector Engine\n  Copyright : EVE Contributors & Maintainers\n  SPDX-License-Identifier: MIT\n**/\n//==================================================================================================\n#include <boost/math/special_functions/factorials.hpp>\n#include <eve/function/double_factorial.hpp>\n#include <eve/constant/inf.hpp>\n#include <type_traits>\n\nTTS_CASE_TPL(\"Check eve::double_factorial return type\", EVE_TYPE)\n{\n  if constexpr(eve::simd_value<T>)\n  {\n    using r_t = eve::wide<double, eve::cardinal_t<T>>;\n    TTS_EXPR_IS(eve::double_factorial(T()), r_t);\n  }\n  else\n  {\n    TTS_EXPR_IS(eve::double_factorial(T()), double);\n  }\n}\n\nTTS_CASE_TPL(\"Check eve::double_factorial behavior\", EVE_TYPE)\n{\n  using r_t = std::conditional_t<eve::simd_value<T>\n    , eve::wide<double, eve::cardinal_t<T>>\n   , double>;\n  TTS_ULP_EQUAL(eve::double_factorial(T(10)) , r_t(boost::math::double_factorial<double>(10)), 0.5);\n  TTS_ULP_EQUAL(eve::double_factorial(T( 5)) , r_t(boost::math::double_factorial<double>( 5)), 0.5);\n  TTS_ULP_EQUAL(eve::double_factorial(T(180))    , r_t(boost::math::double_factorial<double>( 180)), 1.0);\n  TTS_ULP_EQUAL(eve::double_factorial(T(181))    , r_t(boost::math::double_factorial<double>( 181)), 1.0);\n  if constexpr(sizeof(eve::element_type_t<T>) > 1)\n  {\n    TTS_ULP_EQUAL(eve::double_factorial(T(301))    , eve::inf(eve::as<r_t>()), 0);\n    TTS_ULP_EQUAL(eve::double_factorial(T(302))    , eve::inf(eve::as<r_t>()), 0);\n  }\n}\n", "meta": {"hexsha": "20fac3db0452d2e4c8b9e2970a94a040a6d74fa5", "size": 1580, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/unit/module/real/combinatorial/double_factorial/regular/double_factorial.hpp", "max_stars_repo_name": "orao/eve", "max_stars_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_stars_repo_licenses": ["MIT"], "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/unit/module/real/combinatorial/double_factorial/regular/double_factorial.hpp", "max_issues_repo_name": "orao/eve", "max_issues_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_issues_repo_licenses": ["MIT"], "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/unit/module/real/combinatorial/double_factorial/regular/double_factorial.hpp", "max_forks_repo_name": "orao/eve", "max_forks_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_forks_repo_licenses": ["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.5365853659, "max_line_length": 106, "alphanum_fraction": 0.603164557, "num_tokens": 440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4924981827253108}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#pragma once\n\n#include <boost/preprocessor/arithmetic/dec.hpp>\n#include <boost/preprocessor/arithmetic/inc.hpp>\n#include <boost/preprocessor/control/expr_iif.hpp>\n#include <boost/preprocessor/list/adt.hpp>\n#include <boost/preprocessor/repetition/for.hpp>\n#include <boost/preprocessor/repetition/repeat.hpp>\n#include <boost/preprocessor/tuple/to_list.hpp>\n#include <limits>\n#include <pup.h>\n#include <vector>\n\n#include \"DataStructures/Tensor/TypeAliases.hpp\"\n#include \"Options/Options.hpp\"\n#include \"Parallel/CharmPupable.hpp\"\n#include \"PointwiseFunctions/Hydro/EquationsOfState/EquationOfState.hpp\"  // IWYU pragma: keep\n#include \"Utilities/Math.hpp\"\n#include \"Utilities/TMPL.hpp\"\n\n/// \\cond\nclass DataVector;\n\n/// \\endcond\n\n// IWYU pragma: no_forward_declare Tensor\n\nnamespace EquationsOfState {\n\n/*!\n * \\ingroup EquationsOfStateGroup\n * \\brief An equation of state given by parametrized enthalpy\n *\n * This equation of state is determined as a function of \\f$x =\n * \\ln(\\rho/\\rho_0)\\f$ where \\f$\\rho\\f$ is the rest mass density and\n * \\f$\\rho_0\\f$ is the provided reference density.\n * The pseudo-enthalpy \\f$h \\equiv (p + rho  + u)/rho\\f$\n * is expanded as\n *\n * \\f{equation}\n * h(x) = \\sum_i a_i x^i + \\sum_j b_j \\sin(jkx) + c_j \\cos(jkx)\n * \\f}\n *\n * This form allows for convenient calculation of thermodynamic\n * quantities for a cold equation of state. For example\n *\n * \\f{equation}\n * h(x) = \\frac{d e} {d \\rho} |_{x = \\log(\\rho/\\rho_0)}\n * \\f}\n *\n * where \\f$e\\f$ is the total energy density.  At the same time \\f$ dx =\n * d\\rho/\\rho \\f$ so \\f$ \\rho_0 e^x dx = d \\rho \\f$ Therefore,\n *\n * \\f{equation}\n * e(x) - e(x_0) = \\int_{x_0}^x h(x') e^{x'} dx '\n * \\f}\n *\n * This can be computed analytically because\n *\n * \\f{equation}\n *  \\int a_i \\frac{x^i}{i!} e^{x} dx = \\sum_{j \\leq i} a_i (-1)^{i-j}\n * \\frac{(x)^{j}}{j!}\n * + C \\f}\n *\n * and\n *\n * \\f{equation}\n * \\int b_j \\sin(j k x) e^x dx = b_j e^x \\frac{\\sin(jkx) - j k \\cos(jkx)}{j^2\n * k^2 + 1} \\f}\n *\n * \\f{equation}\n * \\int c_j \\cos(j k x) e^x dx = b_j e^x \\frac{\\cos(jkx) + j k \\sin(jkx)}{j^2\n * k^2 + 1} \\f}\n *\n * From this most other thermodynamic quantities can be computed\n * analytically\n *\n * The internal energy density\n * \\f{equation}\n * \\epsilon(x)\\rho(x) = e(x)  - \\rho(x)\n * \\f}\n *\n * The pressure\n * \\f{equation}\n * p(x) = \\rho(x) h(x) - e(x)\n * \\f}\n *\n * The derivative of the pressure with respect to the rest mass density\n * \\f{equation}\n * \\chi(x) = \\frac{dp}{d\\rho} |_{x = x(\\rho)} = \\frac{dh}{dx}\n * \\f}\n *\n * Below the minimum density, a spectral parameterization\n * is used.\n *\n *\n *\n */\ntemplate <typename LowDensityEoS>\nclass Enthalpy : public EquationOfState<true, 1> {\n private:\n  struct Coefficients {\n    std::vector<double> polynomial_coefficients;\n    std::vector<double> sin_coefficients;\n    std::vector<double> cos_coefficients;\n    double trig_scale;\n    double reference_density;\n    bool has_exponential_prefactor;\n    double exponential_external_constant;\n    Coefficients() = default;\n    ~Coefficients() = default;\n    Coefficients(const Coefficients& coefficients) = default;\n    Coefficients(std::vector<double> in_polynomial_coefficients,\n                 std::vector<double> in_sin_coefficients,\n                 std::vector<double> in_cos_coefficients, double in_trig_scale,\n                 double in_reference_density,\n                 double in_exponential_constant =\n                     std::numeric_limits<double>::quiet_NaN());\n\n    Enthalpy<LowDensityEoS>::Coefficients compute_exponential_integral(\n        const std::pair<double, double>& initial_condition);\n    Enthalpy<LowDensityEoS>::Coefficients compute_derivative();\n    void pup(PUP::er& p);\n  };\n\n public:\n  static constexpr size_t thermodynamic_dim = 1;\n  static constexpr bool is_relativistic = true;\n\n  struct ReferenceDensity {\n    using type = double;\n    static constexpr Options::String help = {\"Reference density rho_0\"};\n    static double lower_bound() { return 0.0; }\n  };\n\n  struct MinimumDensity {\n    using type = double;\n    static constexpr Options::String help = {\n        \"Minimum valid density rho_min,\"\n        \" for this parametrization\"};\n    static double lower_bound() { return 0.0; }\n  };\n  struct MaximumDensity {\n    using type = double;\n    static constexpr Options::String help = {\"Maximum density for this EoS\"};\n    static double lower_bound() { return 0.0; }\n  };\n\n  struct PolynomialCoefficients {\n    using type = std::vector<double>;\n    static constexpr Options::String help = {\"Polynomial coefficients a_i\"};\n  };\n\n  struct TrigScaling {\n    using type = double;\n    static constexpr Options::String help = {\n        \"Fundamental wavenumber of trig \"\n        \"functions, k\"};\n    static double lower_bound() { return 0.0; }\n  };\n\n  struct SinCoefficients {\n    using type = std::vector<double>;\n    static constexpr Options::String help = {\"Sine coefficients b_j\"};\n  };\n  struct CosCoefficients {\n    using type = std::vector<double>;\n    static constexpr Options::String help = {\"Cosine coefficients c_j\"};\n  };\n  struct StitchedLowDensityEoS {\n    using type = LowDensityEoS;\n    static std::string name() {\n      return pretty_type::short_name<LowDensityEoS>();\n    }\n    static constexpr Options::String help = {\n        \"Low density EoS stitched at the MinimumDensity\"};\n  };\n\n  struct TransitionDeltaEpsilon {\n    using type = double;\n    static constexpr Options::String help = {\n        \"the change in internal energy across the low-\"\n        \"to-high-density transition, generically 0.0\"};\n    static double lower_bound() { return 0.0; }\n  };\n\n  static constexpr Options::String help = {\n      \"An EoS with a parametrized value h(log(rho/rho_0)) with h the specific \"\n      \"enthalpy and rho the baryon rest mass density.  The enthalpy is \"\n      \"expanded as a sum of polynomial terms and trigonometric corrections. \"\n      \"let x = log(rho/rho_0) in\"\n      \"h(x) = \\\\sum_i a_ix^i + \\\\sum_j b_jsin(k * j * x) + c_jcos(k * j * x) \"\n      \"Note that rho(x)(1+epsilon(x)) = int_0^x e^x' h((x') dx' can be \"\n      \"computed \"\n      \"analytically, and therefore so can \"\n      \"P(x) = rho(x) * (h(x) - (1 + epsilon(x))) \"};\n\n  using options =\n      tmpl::list<ReferenceDensity, MaximumDensity, MinimumDensity, TrigScaling,\n                 PolynomialCoefficients, SinCoefficients, CosCoefficients,\n                 StitchedLowDensityEoS, TransitionDeltaEpsilon>;\n\n  Enthalpy() = default;\n  Enthalpy(const Enthalpy&) = default;\n  Enthalpy& operator=(const Enthalpy&) = default;\n  Enthalpy(Enthalpy&&) = default;\n  Enthalpy& operator=(Enthalpy&&) = default;\n  ~Enthalpy() override = default;\n\n  Enthalpy(double reference_density, double max_density, double min_density,\n           double trig_scale,\n           const std::vector<double>& polynomial_coefficients,\n           const std::vector<double>& sin_coefficients,\n           const std::vector<double>& cos_coefficients,\n           const LowDensityEoS& low_density_eos,\n           const double transition_delta_epsilon);\n\n  EQUATION_OF_STATE_FORWARD_DECLARE_MEMBERS(Enthalpy, 1)\n\n  WRAPPED_PUPable_decl_base_template(  // NOLINT\n      SINGLE_ARG(EquationOfState<true, 1>), Enthalpy);\n\n  /// The lower bound of the rest mass density that is valid for this EOS\n  double rest_mass_density_lower_bound() const override { return 0.0; }\n\n  /// The upper bound of the rest mass density that is valid for this EOS\n  double rest_mass_density_upper_bound() const override {\n    return std::numeric_limits<double>::max();\n  }\n\n  /// The lower bound of the specific internal energy that is valid for this EOS\n  /// at the given rest mass density \\f$\\rho\\f$\n  double specific_internal_energy_lower_bound(\n      const double /* rest_mass_density */) const override {\n    return 0.0;\n  }\n\n  /// The upper bound of the specific internal energy that is valid for this EOS\n  /// at the given rest mass density \\f$\\rho\\f$\n  double specific_internal_energy_upper_bound(\n      const double /* rest_mass_density */) const override {\n    return std::numeric_limits<double>::max();\n  }\n\n  /// The lower bound of the specific enthalpy that is valid for this EOS\n  double specific_enthalpy_lower_bound() const override { return 1.0; }\n\n private:\n  EQUATION_OF_STATE_FORWARD_DECLARE_MEMBER_IMPLS(1)\n\n  SPECTRE_ALWAYS_INLINE\n  bool in_low_density_domain(const double density) const {\n    return density < minimum_density_;\n  }\n\n  double x_from_density(const double density) const;\n  double density_from_x(const double x) const;\n  double energy_density_from_log_density(const double x) const;\n  static double evaluate_coefficients(\n      const Enthalpy::Coefficients& coefficients, const double x);\n\n  double chi_from_density(const double density) const;\n  double specific_internal_energy_from_density(const double density) const;\n  double specific_enthalpy_from_density(const double density) const;\n  double pressure_from_density(const double density) const;\n  double pressure_from_log_density(const double x) const;\n  double rest_mass_density_from_enthalpy(const double specific_enthalpy) const;\n\n  double reference_density_ = std::numeric_limits<double>::signaling_NaN();\n  double minimum_density_ = std::numeric_limits<double>::signaling_NaN();\n  double maximum_density_ = std::numeric_limits<double>::signaling_NaN();\n  double minimum_enthalpy_ = std::numeric_limits<double>::signaling_NaN();\n\n  LowDensityEoS low_density_eos_;\n  Coefficients coefficients_;\n  Coefficients exponential_integral_coefficients_;\n  Coefficients derivative_coefficients_;\n};\n\n}  // namespace EquationsOfState\n", "meta": {"hexsha": "21842a7e93bc107037665d2db61fce7bef65cec5", "size": 9605, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/PointwiseFunctions/Hydro/EquationsOfState/Enthalpy.hpp", "max_stars_repo_name": "nilsvu/spectre", "max_stars_repo_head_hexsha": "1455b9a8d7e92db8ad600c66f54795c29c3052ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/PointwiseFunctions/Hydro/EquationsOfState/Enthalpy.hpp", "max_issues_repo_name": "nilsvu/spectre", "max_issues_repo_head_hexsha": "1455b9a8d7e92db8ad600c66f54795c29c3052ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/PointwiseFunctions/Hydro/EquationsOfState/Enthalpy.hpp", "max_forks_repo_name": "nilsvu/spectre", "max_forks_repo_head_hexsha": "1455b9a8d7e92db8ad600c66f54795c29c3052ee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.8204225352, "max_line_length": 94, "alphanum_fraction": 0.6926600729, "num_tokens": 2538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4924981827253108}}
{"text": "/**\n * @author Luca Marchionni\n * @author Bence Magyar\n * @author Enrique Fern\u00e1ndez\n * @author Paul Mathieu\n * @author G\u00e9rald Lelong\n */\n\n#include <ackermann_controller/odometry.h>\n#include <boost/bind.hpp>\n\nnamespace ackermann_controller\n{\n\nnamespace bacc = boost::accumulators;\n\nOdometry::Odometry(size_t velocity_rolling_window_size)\n    : timestamp_(0.0)\n    , x_(0.0)\n    , y_(0.0)\n    , heading_(0.0)\n    , linear_(0.0)\n    , angular_(0.0)\n    , wheelbase_(1.0)\n    , velocity_rolling_window_size_(velocity_rolling_window_size)\n    , linear_acc_(RollingWindow::window_size = velocity_rolling_window_size)\n    , angular_acc_(RollingWindow::window_size = velocity_rolling_window_size)\n    , integrate_fun_(boost::bind(&Odometry::integrateExact, this, _1, _2))\n{\n}\n\nvoid Odometry::init(const ros::Time& time)\n{\n    // Reset accumulators and timestamp:\n    resetAccumulators();\n    timestamp_ = time;\n}\n\nbool Odometry::update(\n    const std::vector<ActuatedJoint>& steering_joints,\n    const std::vector<Wheel>& odometry_joints,\n    const ros::Time &time)\n{\n    double linear_sum = 0.0;\n    double angular_sum = 0.0;\n    double steering_angle_sum = 0.0;\n\n    const double dt = (time - timestamp_).toSec();\n    timestamp_ = time;\n\n    for (std::vector<Wheel>::const_iterator it = odometry_joints.begin(); it != odometry_joints.end(); ++it)\n    {\n        const double wheel_est_vel = it->handle_.getVelocity() * dt;\n        linear_sum += wheel_est_vel * it->radius_;\n    }\n\n    const double linear = linear_sum / odometry_joints.size();\n\n    for (std::vector<ActuatedJoint>::const_iterator it = steering_joints.begin(); it != steering_joints.end(); ++it)\n    {\n        const double steering_angle = it->getPosition();\n        double virtual_steering_angle = std::atan(wheelbase_ * std::tan(steering_angle)/std::abs(wheelbase_ + it->lateral_deviation_ * std::tan(steering_angle)));\n        steering_angle_sum += virtual_steering_angle;\n        angular_sum += linear * tan(virtual_steering_angle) / wheelbase_;\n    }\n\n    const double angular = angular_sum / steering_joints.size();\n    const double steering_angle = steering_angle_sum / steering_joints.size();\n\n    /// Integrate odometry:\n    const double curvature_radius = wheelbase_ / cos(M_PI/2.0 - steering_angle);\n\n    if (fabs(curvature_radius) > 0.0001)\n    {\n        const double elapsed_distance = linear;\n        const double elapsed_angle = elapsed_distance / curvature_radius;\n        const double x_curvature = curvature_radius * sin(elapsed_angle);\n        const double y_curvature = curvature_radius * (cos(elapsed_angle) - 1.0);\n        const double wheel_heading = heading_ + steering_angle;\n        y_ += x_curvature * sin(wheel_heading) + y_curvature * cos(wheel_heading);\n        x_ += x_curvature * cos(wheel_heading) - y_curvature * sin(wheel_heading);\n        heading_ += elapsed_angle;\n    }\n\n    if (dt < 0.0001)\n        return false; // Interval too small to integrate with\n\n    /// Estimate speeds using a rolling mean to filter them out:\n    linear_acc_(linear/dt);\n    angular_acc_(angular/dt);\n\n    linear_ = bacc::rolling_mean(linear_acc_);\n    angular_ = bacc::rolling_mean(angular_acc_);\n\n    return true;\n}\n\nvoid Odometry::updateOpenLoop(double linear, double angular, const ros::Time &time)\n{\n    /// Save last linear and angular velocity:\n    linear_ = linear;\n    angular_ = angular;\n\n    /// Integrate odometry:\n    const double dt = (time - timestamp_).toSec();\n    timestamp_ = time;\n    integrate_fun_(linear * dt, angular * dt);\n}\n\nvoid Odometry::setVelocityRollingWindowSize(size_t velocity_rolling_window_size)\n{\n    velocity_rolling_window_size_ = velocity_rolling_window_size;\n\n    resetAccumulators();\n}\n\nvoid Odometry::integrateRungeKutta2(double linear, double angular)\n{\n    const double direction = heading_ + angular * 0.5;\n\n    /// Runge-Kutta 2nd order integration:\n    x_       += linear * cos(direction);\n    y_       += linear * sin(direction);\n    heading_ += angular;\n}\n\n/**\n* \\brief Other possible integration method provided by the class\n* \\param linear linear speed\n* \\param angular angular speed\n*/\nvoid Odometry::integrateExact(double linear, double angular)\n{\n    if (fabs(angular) < 1e-6)\n        integrateRungeKutta2(linear, angular);\n    else\n    {\n        /// Exact integration (should solve problems when angular is zero):\n        const double heading_old = heading_;\n        const double r = linear/angular;\n        heading_ += angular;\n        x_       +=  r * (sin(heading_) - sin(heading_old));\n        y_       += -r * (cos(heading_) - cos(heading_old));\n    }\n}\n\nvoid Odometry::resetAccumulators()\n{\n    linear_acc_ = RollingMeanAcc(RollingWindow::window_size = velocity_rolling_window_size_);\n    angular_acc_ = RollingMeanAcc(RollingWindow::window_size = velocity_rolling_window_size_);\n}\n\n}\n", "meta": {"hexsha": "6404d0ff7784ff1212d6d474c6b95f3a363a0e19", "size": 4821, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/odometry.cpp", "max_stars_repo_name": "easymov/ackermann_controller", "max_stars_repo_head_hexsha": "fce99623c80c49bb72204dd75b8966f591fb103e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2018-04-12T07:04:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-06T17:46:33.000Z", "max_issues_repo_path": "src/odometry.cpp", "max_issues_repo_name": "lichunhong/ackermann_controller", "max_issues_repo_head_hexsha": "fce99623c80c49bb72204dd75b8966f591fb103e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/odometry.cpp", "max_forks_repo_name": "lichunhong/ackermann_controller", "max_forks_repo_head_hexsha": "fce99623c80c49bb72204dd75b8966f591fb103e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2018-01-03T10:05:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-16T23:48:37.000Z", "avg_line_length": 31.3051948052, "max_line_length": 162, "alphanum_fraction": 0.6892760838, "num_tokens": 1219, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079209, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4924959323487615}}
{"text": "/*\n * Copyright (c) 2013-2015 Masahide Kashiwagi (kashi@waseda.jp)\n */\n\n#ifndef ALLSOL_SIMPLE_HPP\n#define ALLSOL_SIMPLE_HPP\n\n#include <iostream>\n#include <list>\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/matrix-inversion.hpp>\n#include <kv/autodif.hpp>\n\n\nnamespace kv {\n\nnamespace ub = boost::numeric::ublas;\n\nnamespace allsol_simple_sub {\n\n// return index of I_i which has maximum width\n\ntemplate <class T> int search_maxwidth (const ub::vector< interval<T> >& I) {\n\tint s = I.size();\n\tint i, mi;\n\tT m, tmp;\n\n\tm = 0.;\n\tfor (i=0; i<s; i++) {\n\t\ttmp = width(I(i));\n\t\tif (tmp > m) {\n\t\t\tm = tmp; mi = i;\n\t\t}\n\t}\n\n\treturn mi;\n}\n\n// return max width(I_i) / width(J_i)\n\ntemplate <class T> T widthratio_max (const ub::vector< interval<T> >& I, const ub::vector< interval<T> >& J) {\n\tint s = I.size();\n\tint i;\n\tT tmp, r;\n\n\tr = 0.;\n\n\tfor (i=0; i<s; i++) {\n\t\ttmp = width(I(i)) / width(J(i));\n\t\tif (tmp > r) r = tmp;\n\t}\n\n\treturn r;\n}\n\n// return min width(I_i) / width(J_i)\n\ntemplate <class T> T widthratio_min (const ub::vector< interval<T> >& I, const ub::vector< interval<T> >& J) {\n\tint s = I.size();\n\tint i;\n\tT tmp, r;\n\n\tr = std::numeric_limits<T>::max();\n\n\tfor (i=0; i<s; i++) {\n\t\ttmp = width(I(i)) / width(J(i));\n\t\tif (tmp < r) r = tmp;\n\t}\n\n\treturn r;\n}\n\n} // namespace allsol_simple_sub\n\n// find all solution of f in I\n\ntemplate <class T, class F> std::list< ub::vector< interval<T> > >\nallsol_simple (F f, const ub::vector< interval<T> >& I, int verbose=1)\n{\n\tstd::list< ub::vector < interval<T> > > targets;\n\ttargets.push_back(I);\n\treturn allsol_list_simple(f, targets, verbose);\n}\n\n\n// find all solution of f in targets (list of intervals)\n\ntemplate <class T, class F> std::list< ub::vector< interval<T> > >\nallsol_list_simple (F f, std::list< ub::vector< interval<T> > > targets, int verbose=1)\n{\n\tint s = (targets.front()).size();\n\tub::vector< interval<T> > I, fc, fi, C, CK, K, mvf, I1, I2;\n\tub::matrix< interval<T> > fdi, M;\n\tub::matrix<T> L, R, E;\n\tstd::list< ub::vector< interval<T> > > solutions, solutions_big;\n\ttypename std::list< ub::vector< interval<T> > >::iterator p, p2;\n\tint i, j, k, mi;\n\tT tmp;\n\tbool r, flag, flag2;\n\tint count_ne_test = 0;\n\tint count_ex_test = 0;\n\tint count_unknown = targets.size();\n\tint count_ne = 0;\n\tint count_ex = 0;\n\n\tE = ub::identity_matrix<T>(s);\n\n\twhile (!targets.empty()) {\n\t\tif (verbose >= 2) {\n\t\t\tstd::cout << \"ne_test: \" << count_ne_test << \", ex_test: \" << count_ex_test << \", unknown: \" << count_unknown << \", ne: \" << count_ne << \", ex: \" << count_ex << \"    \\r\" << std::flush;\n\t\t}\n\n\t\tI = targets.front();\n\t\ttargets.pop_front();\n\t\tcount_unknown--;\n\n\t\t// non-existence test\n\n\t\tcount_ne_test++;\n\n\t\ttry {\n\t\t\tfi = f(I);\n\t\t}\n\t\tcatch (std::domain_error& e) {\n\t\t\tgoto label;\n\t\t}\n\n\t\tif (!zero_in(fi)) {\n\t\t\tcount_ne++;\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\tgoto label;\n\t\t}\n\n\t\tmvf = fc + prod(fdi, I - C);\n\t\tif (!zero_in(mvf)) {\n\t\t\tcount_ne++;\n\t\t\tcontinue;\n\t\t}\n\n\t\t// existence test\n\n\t\tL = mid(fdi);\n\n\t\tcount_ex_test++;\n\n\t\tr = invert(L, R);\n\t\tif (!r) goto label;\n\n\t\tM = E - prod(R, fdi);\n\t\tCK = C - prod(R, fc);\n\t\tK = CK +  prod(M, I - C);\n\t\tif (!overlap(K, I)) {\n\t\t\tcount_ne++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (proper_subset(K, I)) {\n\t\t\t// check whether the solution is already found or not\n\t\t\tflag = true;\n\t\t\tp = solutions.begin();\n\t\t\tp2 = solutions_big.begin();\n\t\t\twhile (p != solutions.end()) {\n\t\t\t\tif (overlap(K, *p)) {\n\t\t\t\t\tif (subset(K, *p2)||subset(*p, I)) {\n\t\t\t\t\t\tflag = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\twhile (true) {\n\t\t\t\t\t\tC = mid(K);\n\t\t\t\t\t\tI1 = C - prod(R, f(C)) + prod(M, K - C);\n\t\t\t\t\t\tK = intersect(K, I1);\n\t\t\t\t\t\tif (subset(K, *p2)) {\n\t\t\t\t\t\t\tflag2 = true;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!overlap(K, *p)) {\n\t\t\t\t\t\t\tflag2 = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (flag2 == true) {\n\t\t\t\t\t\tflag = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t/* never reach? */\n\t\t\t\t\t\tstd::cout << \"two overlap intervals includes different solutions\";\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tp++;\n\t\t\t\tp2++;\n\t\t\t}\n\t\t\tif (flag) { // new solution found\n\t\t\t\tif (verbose >= 1) std::cout << I << \"(ex)\\n\";\n\t\t\t\tsolutions_big.push_back(I);\n\t\t\t\t// iterative refinement\n\t\t\t\twhile (1) {\n\t\t\t\t\tC = mid(K);\n\t\t\t\t\tI1 = C - prod(R, f(C)) + prod(M, K - C);\n\t\t\t\t\tI1 = intersect(K, I1);\n\t\t\t\t\ttmp = allsol_simple_sub::widthratio_min(I1, K);\n\t\t\t\t\tK = I1;\n\t\t\t\t\tif (tmp > 0.9) break;\n\t\t\t\t}\n\t\t\t\tsolutions.push_back(K);\n\t\t\t\tcount_ex++;\n\t\t\t\tif (verbose >= 1) std::cout << K << \"(ex:improved)\\n\";\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\t// check the case that solution may exist near boundary.\n\t\t// If so, use K as next interval\n\n\t\tif (allsol_simple_sub::widthratio_max(K, I) < 0.9) {\n\t\t\ttargets.push_back(K);\n\t\t\tcount_unknown++;\n\t\t\tcontinue;\n\t\t}\n\n\t\tI = intersect(I, K);\n\n\t\tlabel:\n\n\t\t// divide interval\n\n\t\tmi = allsol_simple_sub::search_maxwidth(I);\n\n\t\ttmp = mid(I(mi));\n\t\tif (tmp == I(mi).lower() || tmp == I(mi).upper()) {\n\t\t\tstd::cout << \"too small interval (may be multiple root?):\\n\" << I << \"\\n\";\n\t\t\tcontinue;\n\t\t}\n\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\tcount_unknown += 2;\n\t}\n\n\tif (verbose >= 1) {\n\t\t\tstd::cout << \"ne_test: \" << count_ne_test << \", ex_test: \" << count_ex_test << \", ne: \" << count_ne << \", ex: \" << count_ex << \"    \\n\";\n\t}\n\n\treturn solutions;\n}\n\n} // namespace kv\n\n#endif // ALLSOL_SIMPLE_HPP\n", "meta": {"hexsha": "e4e59bc17a33807e43fb72d96e87ed4a9e2833ae", "size": 5587, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "kv/allsol-simple.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/allsol-simple.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/allsol-simple.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.1628787879, "max_line_length": 187, "alphanum_fraction": 0.5695364238, "num_tokens": 1818, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079209, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4924959323487615}}
{"text": "/* vim: set sw=4 sts=4 et foldmethod=syntax : */\n\n#include <gcs/constraints/comparison.hh>\n#include <gcs/constraints/linear_equality.hh>\n#include <gcs/problem.hh>\n#include <gcs/solve.hh>\n\n#include <util/for_each.hh>\n\n#include <boost/program_options.hpp>\n\n#include <cstdlib>\n#include <iostream>\n#include <optional>\n#include <vector>\n\nusing namespace gcs;\n\nusing std::cerr;\nusing std::cout;\nusing std::endl;\nusing std::nullopt;\nusing std::optional;\nusing std::pair;\nusing std::string;\nusing std::to_string;\nusing std::vector;\n\nnamespace po = boost::program_options;\n\nauto main(int argc, char * argv[]) -> int\n{\n    po::options_description display_options{ \"Program options\" };\n    display_options.add_options()\n        (\"help\", \"Display help information\")\n        (\"prove\", \"Create a proof\")\n        (\"extra-constraints\", \"Use extra constraints described in the MiniCP paper\");\n\n    po::options_description all_options{ \"All options\" };\n    all_options.add_options()\n        (\"size\", po::value<int>()->default_value(300), \"Size of the problem to solve\")\n        ;\n\n    all_options.add(display_options);\n\n    po::positional_options_description positional_options;\n    positional_options\n        .add(\"size\", -1);\n\n    po::variables_map options_vars;\n\n    try {\n        po::store(po::command_line_parser(argc, argv)\n                .options(all_options)\n                .positional(positional_options)\n                .run(), options_vars);\n        po::notify(options_vars);\n    }\n    catch (const po::error & e) {\n        cerr << \"Error: \" << e.what() << endl;\n        cerr << \"Try \" << argv[0] << \" --help\" << endl;\n        return EXIT_FAILURE;\n    }\n\n    if (options_vars.count(\"help\")) {\n        cout << \"Usage: \" << argv[0] << \" [options] [size]\" << endl;\n        cout << endl;\n        cout << display_options << endl;\n        return EXIT_SUCCESS;\n    }\n\n    cout << \"Replicating the MiniCP Magic Series benchmark.\" << endl;\n    cout << \"See Laurent D. Michel, Pierre Schaus, Pascal Van Hentenryck:\" << endl;\n    cout << \"\\\"MiniCP: a lightweight solver for constraint programming.\\\"\" << endl;\n    cout << \"Math. Program. Comput. 13(1): 133-184 (2021).\" << endl;\n    cout << \"This should take 1193 recursions with default options.\" << endl;\n    cout << endl;\n\n    int size = options_vars[\"size\"].as<int>();\n    Problem p = options_vars.count(\"prove\") ? Problem{ Proof{ \"magic_series.opb\", \"magic_series.veripb\" } } : Problem{ };\n\n    vector<IntegerVariableID> series;\n    for (int v = 0 ; v != size ; ++v)\n        series.push_back(p.create_integer_variable(0_i, Integer{ size - 1 }, \"series\" + to_string(v)));\n\n    for (int i = 0 ; i < size ; ++i) {\n        Linear coeff_vars;\n        for (int j = 0 ; j < size ; ++j) {\n            auto series_j_eq_i = p.create_integer_variable(0_i, 1_i);\n            p.post(EqualsIff{ series[j], constant_variable(Integer{ i }), series_j_eq_i == 1_i });\n            coeff_vars.emplace_back(1_i, series_j_eq_i);\n        }\n\n        coeff_vars.emplace_back(-1_i, series[i]);\n        p.post(LinearEquality{ move(coeff_vars), 0_i });\n    }\n\n    Linear sum_s;\n    for (auto & s : series)\n        sum_s.emplace_back(1_i, s);\n    p.post(LinearEquality{ move(sum_s), Integer{ size } });\n\n    // Although this is discussed in the text, it isn't included in the executed\n    // benchmarks.\n    if (options_vars.count(\"extra-constraints\")) {\n        Linear sum_mul_s;\n        for_each_with_index(series, [&] (IntegerVariableID s, auto idx) {\n                sum_mul_s.emplace_back(Integer(idx), s);\n                });\n        p.post(LinearEquality{ move(sum_mul_s), Integer{ size } });\n    }\n\n    p.branch_on(series);\n\n    auto stats = solve_with(p, SolveCallbacks{\n            .solution = [&] (const State & s) -> bool {\n                cout << \"solution:\";\n                for (auto & v : series)\n                    cout << \" \" << s(v);\n                cout << endl;\n\n                return true;\n                },\n            .guess = [&] (const State & state, IntegerVariableID var) -> vector<Literal> {\n                return vector<Literal>{ var == state.lower_bound(var), var != state.lower_bound(var) };\n            }\n            });\n\n    cout << stats;\n\n    return EXIT_SUCCESS;\n}\n\n", "meta": {"hexsha": "49ed8885761987edd25743a00f6cf39145767bcd", "size": 4217, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/magic_series/magic_series.cc", "max_stars_repo_name": "ciaranm/glasgow-constraint-solver", "max_stars_repo_head_hexsha": "39d925c776474743a51a80492585db3a07801908", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-08-13T11:36:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T11:13:04.000Z", "max_issues_repo_path": "examples/magic_series/magic_series.cc", "max_issues_repo_name": "ciaranm/glasgow-constraint-solver", "max_issues_repo_head_hexsha": "39d925c776474743a51a80492585db3a07801908", "max_issues_repo_licenses": ["MIT"], "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/magic_series/magic_series.cc", "max_forks_repo_name": "ciaranm/glasgow-constraint-solver", "max_forks_repo_head_hexsha": "39d925c776474743a51a80492585db3a07801908", "max_forks_repo_licenses": ["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.4701492537, "max_line_length": 121, "alphanum_fraction": 0.5937870524, "num_tokens": 1039, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4924959264980664}}
{"text": "//\n// Copyright (c) 2016-2019 CNRS, INRIA\n//\n\n#include \"pinocchio/multibody/model.hpp\"\n#include \"pinocchio/multibody/data.hpp\"\n#include \"pinocchio/parsers/sample-models.hpp\"\n#include \"pinocchio/algorithm/joint-configuration.hpp\"\n#include \"pinocchio/algorithm/kinematics.hpp\"\n#include \"pinocchio/algorithm/jacobian.hpp\"\n\n#include <boost/test/unit_test.hpp>\n#include <boost/utility/binary.hpp>\n\nusing namespace pinocchio;\nusing namespace Eigen;\n\ntemplate<bool local>\nData::Matrix6x finiteDiffJacobian(const Model & model, Data & data, const Eigen::VectorXd & q, const Model::JointIndex joint_id)\n{\n  Data::Matrix6x res(6,model.nv); res.setZero();\n  VectorXd q_integrate (model.nq);\n  VectorXd v_integrate (model.nv); v_integrate.setZero();\n  \n  forwardKinematics(model,data,q);\n  const SE3 oMi_ref = data.oMi[joint_id];\n  \n  double eps = 1e-8;\n  for(int k=0; k<model.nv; ++k)\n  {\n    // Integrate along kth direction\n    v_integrate[k] = eps;\n    q_integrate = integrate(model,q,v_integrate);\n    \n    forwardKinematics(model,data,q_integrate);\n    const SE3 & oMi = data.oMi[joint_id];\n    \n    if (local)\n      res.col(k) = log6(oMi_ref.inverse()*oMi).toVector();\n    else\n      res.col(k) = oMi_ref.act(log6(oMi_ref.inverse()*oMi)).toVector();\n    \n    res.col(k) /= eps;\n    \n    v_integrate[k] = 0.;\n  }\n  \n  return res;\n}\n\ntemplate<typename Matrix>\nvoid filterValue(MatrixBase<Matrix> & mat, typename Matrix::Scalar value)\n{\n  for(int k = 0; k < mat.size(); ++k)\n    mat.derived().data()[k] =  math::fabs(mat.derived().data()[k]) <= value?0:mat.derived().data()[k];\n}\n\ntemplate<typename JointModel_> struct init;\n\ntemplate<typename JointModel_>\nstruct init\n{\n  static JointModel_ run()\n  {\n    JointModel_ jmodel;\n    jmodel.setIndexes(0,0,0);\n    return jmodel;\n  }\n};\n\ntemplate<typename Scalar, int Options>\nstruct init<pinocchio::JointModelRevoluteUnalignedTpl<Scalar,Options> >\n{\n  typedef pinocchio::JointModelRevoluteUnalignedTpl<Scalar,Options> JointModel;\n  \n  static JointModel run()\n  {\n    typedef typename JointModel::Vector3 Vector3;\n    JointModel jmodel(Vector3::Random().normalized());\n    \n    jmodel.setIndexes(0,0,0);\n    return jmodel;\n  }\n};\n\ntemplate<typename Scalar, int Options>\nstruct init<pinocchio::JointModelRevoluteUnboundedUnalignedTpl<Scalar,Options> >\n{\n  typedef pinocchio::JointModelRevoluteUnboundedUnalignedTpl<Scalar,Options> JointModel;\n  \n  static JointModel run()\n  {\n    typedef typename JointModel::Vector3 Vector3;\n    JointModel jmodel(Vector3::Random().normalized());\n    \n    jmodel.setIndexes(0,0,0);\n    return jmodel;\n  }\n};\n\ntemplate<typename Scalar, int Options>\nstruct init<pinocchio::JointModelPrismaticUnalignedTpl<Scalar,Options> >\n{\n  typedef pinocchio::JointModelPrismaticUnalignedTpl<Scalar,Options> JointModel;\n  \n  static JointModel run()\n  {\n    typedef typename JointModel::Vector3 Vector3;\n    JointModel jmodel(Vector3::Random().normalized());\n    \n    jmodel.setIndexes(0,0,0);\n    return jmodel;\n  }\n};\n\ntemplate<typename Scalar, int Options, template<typename,int> class JointCollection>\nstruct init<pinocchio::JointModelTpl<Scalar,Options,JointCollection> >\n{\n  typedef pinocchio::JointModelTpl<Scalar,Options,JointCollection> JointModel;\n  \n  static JointModel run()\n  {\n    typedef pinocchio::JointModelRevoluteTpl<Scalar,Options,0> JointModelRX;\n    JointModel jmodel((JointModelRX()));\n    \n    jmodel.setIndexes(0,0,0);\n    return jmodel;\n  }\n};\n\ntemplate<typename Scalar, int Options, template<typename,int> class JointCollection>\nstruct init<pinocchio::JointModelCompositeTpl<Scalar,Options,JointCollection> >\n{\n  typedef pinocchio::JointModelCompositeTpl<Scalar,Options,JointCollection> JointModel;\n  \n  static JointModel run()\n  {\n    typedef pinocchio::JointModelRevoluteTpl<Scalar,Options,0> JointModelRX;\n    typedef pinocchio::JointModelRevoluteTpl<Scalar,Options,1> JointModelRY;\n    JointModel jmodel((JointModelRX()));\n    jmodel.addJoint(JointModelRY());\n    \n    jmodel.setIndexes(0,0,0);\n    return jmodel;\n  }\n};\n\ntemplate<typename JointModel_>\nstruct init<pinocchio::JointModelMimic<JointModel_> >\n{\n  typedef pinocchio::JointModelMimic<JointModel_> JointModel;\n  \n  static JointModel run()\n  {\n    JointModel_ jmodel_ref = init<JointModel_>::run();\n    \n    JointModel jmodel(jmodel_ref,1.,0.);\n    jmodel.setIndexes(0,0,0);\n    \n    return jmodel;\n  }\n};\n\nstruct FiniteDiffJoint\n{\n  void operator()(JointModelComposite & /*jmodel*/) const\n  {}\n  \n  template<typename JointModel>\n  void operator()(JointModelBase<JointModel> & /*jmodel*/) const\n  {\n    typedef typename JointModel::ConfigVector_t CV;\n    typedef typename JointModel::TangentVector_t TV;\n    typedef typename LieGroup<JointModel>::type LieGroupType;\n    \n    JointModel jmodel = init<JointModel>::run();\n    std::cout << \"name: \" << jmodel.classname() << std::endl;\n    \n    typename JointModel::JointDataDerived jdata_ = jmodel.createData();\n    typedef JointDataBase<typename JointModel::JointDataDerived> DataBaseType;\n    DataBaseType & jdata = static_cast<DataBaseType &>(jdata_);\n    \n    CV q = LieGroupType().random();\n    jmodel.calc(jdata.derived(),q);\n    SE3 M_ref(jdata.M());\n    \n    CV q_int(q);\n    const Eigen::DenseIndex nv = jdata.S().nv();\n    TV v(nv); v.setZero();\n    double eps = 1e-8;\n    \n    Eigen::Matrix<double,6,JointModel::NV> S(6,nv), S_ref(jdata.S().matrix());\n    \n    for(int k=0;k<nv;++k)\n    {\n      v[k] = eps;\n      q_int = LieGroupType().integrate(q,v);\n      jmodel.calc(jdata.derived(),q_int);\n      SE3 M_int = jdata.M();\n      \n      S.col(k) = log6(M_ref.inverse()*M_int).toVector();\n      S.col(k) /= eps;\n      \n      v[k] = 0.;\n    }\n    \n    BOOST_CHECK(S.isApprox(S_ref,eps*1e1));\n    std::cout << \"S_ref:\\n\" << S_ref << std::endl;\n    std::cout << \"S:\\n\" << S << std::endl;\n  }\n};\n\nBOOST_AUTO_TEST_SUITE ( BOOST_TEST_MODULE )\n\nBOOST_AUTO_TEST_CASE (test_S_finit_diff)\n{\n  boost::mpl::for_each<JointModelVariant::types>(FiniteDiffJoint());\n}\n\nBOOST_AUTO_TEST_CASE (test_jacobian_vs_finit_diff)\n{\n  pinocchio::Model model;\n  pinocchio::buildModels::humanoidRandom(model);\n  pinocchio::Data data(model);\n  \n  VectorXd q = VectorXd::Ones(model.nq);\n  q.segment<4>(3).normalize();\n  computeJointJacobians(model,data,q);\n\n  Model::Index idx = model.existJointName(\"rarm2\")?model.getJointId(\"rarm2\"):(Model::Index)(model.njoints-1);\n  Data::Matrix6x Jrh(6,model.nv); Jrh.fill(0);\n  \n  getJointJacobian(model,data,idx,WORLD,Jrh);\n  Data::Matrix6x Jrh_finite_diff = finiteDiffJacobian<false>(model,data,q,idx);\n  BOOST_CHECK(Jrh_finite_diff.isApprox(Jrh,1e-8*1e1));\n  \n  getJointJacobian(model,data,idx,LOCAL,Jrh);\n  Jrh_finite_diff = finiteDiffJacobian<true>(model,data,q,idx);\n  BOOST_CHECK(Jrh_finite_diff.isApprox(Jrh,1e-8*1e1));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "d6aeb00c4a6f8df20cd8cdcb633fd9dd847362d6", "size": 6767, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittest/finite-differences.cpp", "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": "unittest/finite-differences.cpp", "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": "unittest/finite-differences.cpp", "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": 27.8477366255, "max_line_length": 128, "alphanum_fraction": 0.7028225211, "num_tokens": 1901, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4924959264980664}}
{"text": "#include \"setupScene.h\"\n#include \"optimization.h\"\n#include \"types.h\"\n\n#include <iostream>\n#include <vector>\n\n#include <Eigen/Geometry>\n\nint main()\n{\n\t//using Rotation = roto::AngleAxisRotation; // Convenience switch\n\tusing Rotation = roto::QuaternionRotation; // Convenience switch\n\t//using Rotation = roto::MatrixRotation; // Convenience switch\n\n\troto::MeasuredScene<Rotation> measurements;\n\troto::OptimizedScene<Rotation> parameters;\n\n\tdouble totalTime = 0.;\n\tconst std::size_t numberOfIterations = 100;\n\tfor(std::size_t i = 0; i < numberOfIterations; i++)\n\t{\n\t\t//std::tie(measurements, parameters) = roto::setupSmallTestScene<Rotation>();\n\t\tstd::tie(measurements, parameters) = roto::setupBigTestScene<Rotation>();\n\n\t\ttotalTime += roto::optimize(measurements, parameters);\n\t}\n\tstd::cout << \"Average processing time: \"\n\t\t\t\t\t\t<< totalTime / double(numberOfIterations) << std::endl;\n\n\treturn 0;\n}\n", "meta": {"hexsha": "fc539354c8eadea835fcd0763110a3035b5b155e", "size": 897, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "klosteraner/rotation-optimization", "max_stars_repo_head_hexsha": "d5cbe4df2a28d4949fafa4843f1a951338bacacf", "max_stars_repo_licenses": ["MIT"], "max_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": "klosteraner/rotation-optimization", "max_issues_repo_head_hexsha": "d5cbe4df2a28d4949fafa4843f1a951338bacacf", "max_issues_repo_licenses": ["MIT"], "max_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": "klosteraner/rotation-optimization", "max_forks_repo_head_hexsha": "d5cbe4df2a28d4949fafa4843f1a951338bacacf", "max_forks_repo_licenses": ["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.1818181818, "max_line_length": 79, "alphanum_fraction": 0.723522854, "num_tokens": 228, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4924959206473711}}
{"text": "#include \"splineGeneration.h\"\n\n#include <Eigen/Dense>\n#include <iostream>\n#include <sstream>\n#include <numeric>\n#include <stdexcept>\n\nusing namespace std;\nusing namespace Eigen;\n\ntemplate <typename DerivedM>\nvoid setConstraintMatrixPart(double time, int derivative_order, MatrixBase<DerivedM> & constraint_matrix, double scaling = 1.0)\n{\n  double time_power = 1.0;\n  typename MatrixBase<DerivedM>::Index num_coefficients = constraint_matrix.cols();\n\n  for (int col = derivative_order; col < num_coefficients; col++)\n  {\n     double column_power = 1.0;\n     for (int i = 0; i< derivative_order; i++)\n     {\n        column_power *= (col - i);\n     }\n     constraint_matrix(0, col) = scaling * time_power * column_power;\n     time_power *= time;\n  }\n}\n\nPiecewisePolynomial<double> generateSpline(const SplineInformation& spline_information) {\n  int num_segments = spline_information.getNumberOfSegments();\n  int num_constraints = spline_information.getNumberOfConstraints();\n  int num_coefficients = spline_information.getTotalNumberOfCoefficients();\n\n  if (num_constraints != num_coefficients) {\n    stringstream msg;\n    msg << \"Only the case where the number of coefficients equals the number of variables is currently handled.\" << endl;\n    msg << \"Number of coefficients: \" << num_coefficients << \", Number of constraints: \" << num_constraints << endl;\n    throw runtime_error(msg.str().c_str());\n  }\n\n  MatrixXd constraint_matrix = MatrixXd::Zero(num_constraints, num_coefficients);\n  VectorXd right_hand_side(num_constraints); // should get overwritten completely\n\n  int constraint_row_start = 0;\n  std::vector<int> segment_col_starts;\n  int segment_col_start = 0;\n  for (int i = 0; i < num_segments; i++) {\n    segment_col_starts.push_back(segment_col_start);\n    segment_col_start += spline_information.getNumberOfCoefficients(i);\n  }\n\n  // handle value constraints\n  for (int i = 0; i < num_segments; i++) {\n    std::vector<ValueConstraint> const & value_constraints = spline_information.getValueConstraints(i);\n    for (auto it = value_constraints.begin(); it != value_constraints.end(); ++it) {\n      const ValueConstraint& constraint = *it;\n      int number_of_coefficients = spline_information.getNumberOfCoefficients(i);\n      int segment_col_start = segment_col_starts[i];\n      auto constraint_matrix_segment_part = constraint_matrix.block<1, Dynamic>(constraint_row_start, segment_col_start, 1, number_of_coefficients);\n      double t_local = constraint.getTime() - spline_information.getStartTime(i);\n      setConstraintMatrixPart(t_local, constraint.getDerivativeOrder(), constraint_matrix_segment_part);\n      right_hand_side(constraint_row_start) = constraint.getValue();\n      constraint_row_start += 1;\n    }\n  }\n\n  // handle continuity constraints\n  std::vector<ContinuityConstraint> continuity_constraints = spline_information.getContinuityConstraints();\n  for (auto it = continuity_constraints.begin(); it != continuity_constraints.end(); ++it) {\n    const ContinuityConstraint& constraint = *it;\n    int first_spline_index = constraint.getFirstSplineIndex();\n    int number_of_coefficients_1 = spline_information.getNumberOfCoefficients(first_spline_index);\n    auto constraint_matrix_segment_part_1 = constraint_matrix.block<1, Dynamic>(constraint_row_start, segment_col_starts[first_spline_index], 1, number_of_coefficients_1);\n    double t_local_1 = spline_information.getEndTime(first_spline_index) - spline_information.getStartTime(first_spline_index);\n    setConstraintMatrixPart(t_local_1, constraint.getDerivativeOrder(), constraint_matrix_segment_part_1, 1.0);\n\n    int second_spline_index = constraint.getSecondSplineIndex();\n    int number_of_coefficients_2 = spline_information.getNumberOfCoefficients(second_spline_index);\n    auto constraint_matrix_segment_part_2 = constraint_matrix.block<1, Dynamic>(constraint_row_start, segment_col_starts[second_spline_index], 1, number_of_coefficients_2);\n    setConstraintMatrixPart(0.0, constraint.getDerivativeOrder(), constraint_matrix_segment_part_2, -1.0);\n\n    right_hand_side(constraint_row_start) = 0.0;\n\n    constraint_row_start += 1;\n  }\n\n  // solve\n  auto decomposition = constraint_matrix.colPivHouseholderQr();\n  if (!decomposition.isInvertible())\n    throw ConstraintMatrixSingularError();\n  VectorXd solution = decomposition.solve(right_hand_side);\n\n  // create Polynomials\n  std::vector<Polynomial<double>> polynomials;\n  for (int i = 0; i < num_segments; i++) {\n    auto coefficients = solution.segment(segment_col_starts[i], spline_information.getNumberOfCoefficients(i));\n    polynomials.push_back(Polynomial<double>(coefficients));\n  }\n\n  // return a PiecewisePolynomial\n  return PiecewisePolynomial<double>(polynomials, spline_information.getSegmentTimes());\n}\n\nPiecewisePolynomial<double> twoWaypointCubicSpline(const vector<double>& segment_times, double x0, double xd0, double xf, double xdf, double x1, double x2) {\n  const int num_segments = 3;\n  assert(segment_times.size() == num_segments + 1);\n\n  int polynomial_order = 3;\n  vector<int> segment_polynomial_orders;\n  for (int i = 0; i < num_segments; ++i) {\n    segment_polynomial_orders.push_back(polynomial_order);\n  }\n\n  SplineInformation spline_information(segment_polynomial_orders, segment_times);\n  spline_information.addValueConstraint(0, ValueConstraint(0, spline_information.getStartTime(0), x0));\n  spline_information.addValueConstraint(0, ValueConstraint(1, spline_information.getStartTime(0), xd0));\n  spline_information.addValueConstraint(num_segments - 1, ValueConstraint(0, spline_information.getEndTime(num_segments - 1), xf));\n  spline_information.addValueConstraint(num_segments - 1, ValueConstraint(1, spline_information.getEndTime(num_segments - 1), xdf));\n  spline_information.addValueConstraint(1, ValueConstraint(0, spline_information.getStartTime(1), x1));\n  spline_information.addValueConstraint(2, ValueConstraint(0, spline_information.getStartTime(2), x2));\n\n  int num_knots = num_segments - 1;\n  for (int i = 0; i < num_knots; i++) {\n    for (int derivative_order = 0; derivative_order < 3; derivative_order++) {\n      spline_information.addContinuityConstraint(ContinuityConstraint(derivative_order, i, i + 1));\n    }\n  }\n\n  return generateSpline(spline_information);\n}\n", "meta": {"hexsha": "c1cc38c8adf964db59b332d9a4a03bc92539aaf5", "size": 6257, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "solvers/qpSpline/splineGeneration.cpp", "max_stars_repo_name": "jacob-izr/drake", "max_stars_repo_head_hexsha": "d8f0f1f231ecba83ed53b1a1c2f9f43da50396b9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "solvers/qpSpline/splineGeneration.cpp", "max_issues_repo_name": "jacob-izr/drake", "max_issues_repo_head_hexsha": "d8f0f1f231ecba83ed53b1a1c2f9f43da50396b9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "solvers/qpSpline/splineGeneration.cpp", "max_forks_repo_name": "jacob-izr/drake", "max_forks_repo_head_hexsha": "d8f0f1f231ecba83ed53b1a1c2f9f43da50396b9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.4015151515, "max_line_length": 172, "alphanum_fraction": 0.7693782963, "num_tokens": 1421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4924959206473711}}
{"text": "#include<bits/stdc++.h>\nusing namespace std;\n#include <iostream>                  // for std::cout\n#include <utility>                   // for std::pair\n#include <algorithm>                 // for std::for_each\n\n\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/adjacency_matrix.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n\nusing namespace boost;\n\n// This header file needs to be included for using Centroid decomposition.\n#include \"boost/graph/CND/cnd_ds.hpp\"\nusing namespace boost::graph;\nint main()\n{\n    int i,n,a,b;\n    scanf(\"%d\",&n);\n    //Graph type \n    typedef adjacency_list<vecS, vecS, undirectedS> Graph;\n    //Initialisation of Graph object\n    Graph graph(n);\n    for(i=1;i<n;i++)\n    {\n        scanf(\"%d %d\",&a,&b);\n        add_edge(a,b,graph);        \n    }\n    // \"CND\" class is called which constructs an object which contains the decomposed tree and its root.\n    CND<Graph> decomposed_tree(graph,0,n);\n    \n    // Printing the centroid of entire input tree or root of the centroid decomposition of input tree.\n    printf(\"%d\\n\",decomposed_tree.decomposed_root);\n\n    return 0;\n\n}", "meta": {"hexsha": "33a5cf3f0307473fd01fbbada3efaeb11b8ca12a", "size": 1167, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/prac_cnd_ds.cpp", "max_stars_repo_name": "BoostGSoC18/Advanced-Intrusive", "max_stars_repo_head_hexsha": "30c465125c460e4bc2a9583ce00f0f706ed23e5a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-08-30T18:14:40.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-22T17:12:44.000Z", "max_issues_repo_path": "example/prac_cnd_ds.cpp", "max_issues_repo_name": "BoostGSoC18/Advanced-Intrusive", "max_issues_repo_head_hexsha": "30c465125c460e4bc2a9583ce00f0f706ed23e5a", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2018-05-31T10:01:25.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-26T15:14:26.000Z", "max_forks_repo_path": "example/prac_cnd_ds.cpp", "max_forks_repo_name": "BoostGSoC18/Advanced-Intrusive", "max_forks_repo_head_hexsha": "30c465125c460e4bc2a9583ce00f0f706ed23e5a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9230769231, "max_line_length": 104, "alphanum_fraction": 0.6572407883, "num_tokens": 280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125848754471, "lm_q2_score": 0.6548947357776796, "lm_q1q2_score": 0.4924890830734958}}
{"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    testRegularJacobianFactor.cpp\n * @brief   unit test regular jacobian factors\n * @author  Sungtae An\n * @date    Nov 12, 2014\n */\n\n#include <gtsam/linear/RegularJacobianFactor.h>\n#include <gtsam/linear/GaussianFactorGraph.h>\n#include <gtsam/linear/GaussianConditional.h>\n#include <gtsam/linear/VectorValues.h>\n#include <gtsam/base/TestableAssertions.h>\n\n#include <CppUnitLite/TestHarness.h>\n\n#include <boost/assign/std/vector.hpp>\n#include <boost/assign/list_of.hpp>\n#include <boost/range/iterator_range.hpp>\n#include <boost/range/adaptor/map.hpp>\n\nusing namespace std;\nusing namespace gtsam;\nusing namespace boost::assign;\n\nstatic const size_t fixedDim = 3;\nstatic const size_t nrKeys = 3;\n\n// Keys are assumed to be from 0 to n\nnamespace {\n  namespace simple {\n    // Terms we'll use\n    const vector<pair<Key, Matrix> > terms = list_of<pair<Key,Matrix> >\n      (make_pair(0, Matrix3::Identity()))\n      (make_pair(1, 2*Matrix3::Identity()))\n      (make_pair(2, 3*Matrix3::Identity()));\n\n    // RHS and sigmas\n    const Vector b = (Vector(3) << 1., 2., 3.).finished();\n    const SharedDiagonal noise = noiseModel::Diagonal::Sigmas((Vector(3) << 0.5,0.5,0.5).finished());\n  }\n\n  namespace simple2 {\n    // Terms\n    const vector<pair<Key, Matrix> > terms2 = list_of<pair<Key,Matrix> >\n      (make_pair(0, 2*Matrix3::Identity()))\n      (make_pair(1, 4*Matrix3::Identity()))\n      (make_pair(2, 6*Matrix3::Identity()));\n\n    // RHS\n    const Vector b2 = (Vector(3) << 2., 4., 6.).finished();\n  }\n}\n\n/* ************************************************************************* */\n// Convert from double* to VectorValues\nVectorValues double2vv(const double* x,\n    const  size_t nrKeys, const size_t dim) {\n  // create map with dimensions\n  std::map<gtsam::Key, size_t> dims;\n  for (size_t i = 0; i < nrKeys; i++)\n    dims.insert(make_pair(i, dim));\n\n  size_t n = nrKeys*dim;\n  Vector xVec(n);\n  for (size_t i = 0; i < n; i++){\n    xVec(i) = x[i];\n  }\n  return VectorValues(xVec, dims);\n}\n\n/* ************************************************************************* */\nvoid vv2double(const VectorValues& vv, double* y,\n    const  size_t nrKeys, const size_t dim) {\n  // create map with dimensions\n  std::map<gtsam::Key, size_t> dims;\n  for (size_t i = 0; i < nrKeys; i++)\n    dims.insert(make_pair(i, dim));\n\n  Vector yvector = vv.vector(dims);\n  size_t n = nrKeys*dim;\n  for (size_t j = 0; j < n; j++)\n    y[j] = yvector[j];\n}\n\n/* ************************************************************************* */\nTEST(RegularJacobianFactor, constructorNway)\n{\n  using namespace simple;\n  JacobianFactor factor(terms[0].first, terms[0].second,\n        terms[1].first, terms[1].second, terms[2].first, terms[2].second, b, noise);\n  RegularJacobianFactor<fixedDim> regularFactor(terms, b, noise);\n\n  LONGS_EQUAL((long)terms[2].first, (long)regularFactor.keys().back());\n  EXPECT(assert_equal(terms[2].second, regularFactor.getA(regularFactor.end() - 1)));\n  EXPECT(assert_equal(b, factor.getb()));\n  EXPECT(assert_equal(b, regularFactor.getb()));\n  EXPECT(noise == factor.get_model());\n  EXPECT(noise == regularFactor.get_model());\n}\n\n/* ************************************************************************* */\nTEST(RegularJacobianFactor, hessianDiagonal)\n{\n  using namespace simple;\n  JacobianFactor factor(terms[0].first, terms[0].second,\n          terms[1].first, terms[1].second, terms[2].first, terms[2].second, b, noise);\n  RegularJacobianFactor<fixedDim> regularFactor(terms, b, noise);\n\n  // we compute hessian diagonal from the standard Jacobian\n  VectorValues expectedHessianDiagonal = factor.hessianDiagonal();\n\n  // we compare against the Raw memory access implementation of hessianDiagonal\n  double actualValue[9]={0};\n  regularFactor.hessianDiagonal(actualValue);\n  VectorValues actualHessianDiagonalRaw = double2vv(actualValue,nrKeys,fixedDim);\n  EXPECT(assert_equal(expectedHessianDiagonal, actualHessianDiagonalRaw));\n}\n\n/* ************************************************************************* */\nTEST(RegularJacobian, gradientAtZero)\n{\n  using namespace simple;\n  JacobianFactor factor(terms[0].first, terms[0].second,\n          terms[1].first, terms[1].second, terms[2].first, terms[2].second, b, noise);\n  RegularJacobianFactor<fixedDim> regularFactor(terms, b, noise);\n\n  // we compute gradient at zero from the standard Jacobian\n  VectorValues expectedGradientAtZero = factor.gradientAtZero();\n\n  //EXPECT(assert_equal(expectedGradientAtZero, regularFactor.gradientAtZero()));\n\n  // we compare against the Raw memory access implementation of gradientAtZero\n  double actualValue[9]={0};\n  regularFactor.gradientAtZero(actualValue);\n  VectorValues actualGradientAtZeroRaw = double2vv(actualValue,nrKeys,fixedDim);\n  EXPECT(assert_equal(expectedGradientAtZero, actualGradientAtZeroRaw));\n}\n\n/* ************************************************************************* */\nTEST(RegularJacobian, gradientAtZero_multiFactors)\n{\n  using namespace simple;\n  JacobianFactor factor(terms[0].first, terms[0].second,\n          terms[1].first, terms[1].second, terms[2].first, terms[2].second, b, noise);\n  RegularJacobianFactor<fixedDim> regularFactor(terms, b, noise);\n\n  // we compute gradient at zero from the standard Jacobian\n  VectorValues expectedGradientAtZero = factor.gradientAtZero();\n\n  // we compare against the Raw memory access implementation of gradientAtZero\n  double actualValue[9]={0};\n  regularFactor.gradientAtZero(actualValue);\n  VectorValues actualGradientAtZeroRaw = double2vv(actualValue,nrKeys,fixedDim);\n  EXPECT(assert_equal(expectedGradientAtZero, actualGradientAtZeroRaw));\n\n  // One more factor\n  using namespace simple2;\n  JacobianFactor factor2(terms2[0].first, terms2[0].second,\n          terms2[1].first, terms2[1].second, terms2[2].first, terms2[2].second, b2, noise);\n  RegularJacobianFactor<fixedDim> regularFactor2(terms2, b2, noise);\n\n  // we accumulate computed gradient at zero from the standard Jacobian\n  VectorValues expectedGradientAtZero2 = expectedGradientAtZero.add(factor2.gradientAtZero());\n\n  // we compare against the Raw memory access implementation of gradientAtZero\n  regularFactor2.gradientAtZero(actualValue);\n  VectorValues actualGradientAtZeroRaw2 = double2vv(actualValue,nrKeys,fixedDim);\n  EXPECT(assert_equal(expectedGradientAtZero2, actualGradientAtZeroRaw2));\n\n}\n\n/* ************************************************************************* */\nTEST(RegularJacobian, multiplyHessianAdd)\n{\n  using namespace simple;\n  JacobianFactor factor(terms[0].first, terms[0].second,\n            terms[1].first, terms[1].second, terms[2].first, terms[2].second, b, noise);\n  RegularJacobianFactor<fixedDim> regularFactor(terms, b, noise);\n\n  // arbitrary vector X\n  VectorValues X;\n  X.insert(0, (Vector(3) << 10.,20.,30.).finished());\n  X.insert(1, (Vector(3) << 10.,20.,30.).finished());\n  X.insert(2, (Vector(3) << 10.,20.,30.).finished());\n\n  // arbitrary vector Y\n  VectorValues Y;\n  Y.insert(0, (Vector(3) << 10.,10.,10.).finished());\n  Y.insert(1, (Vector(3) << 20.,20.,20.).finished());\n  Y.insert(2, (Vector(3) << 30.,30.,30.).finished());\n\n  // multiplyHessianAdd Y += alpha*A'A*X\n  double alpha = 2.0;\n  VectorValues expectedMHA = Y;\n  factor.multiplyHessianAdd(alpha, X, expectedMHA);\n\n  // create data for raw memory access\n  double XRaw[9];\n  vv2double(X, XRaw, nrKeys, fixedDim);\n\n  // test 1st version: multiplyHessianAdd(double alpha, const double* x, double* y)\n  double actualMHARaw[9];\n  vv2double(Y, actualMHARaw, nrKeys, fixedDim);\n  regularFactor.multiplyHessianAdd(alpha, XRaw, actualMHARaw);\n  VectorValues actualMHARawVV = double2vv(actualMHARaw,nrKeys,fixedDim);\n  EXPECT(assert_equal(expectedMHA,actualMHARawVV));\n\n  // test 2nd version: multiplyHessianAdd(double alpha, const double* x, double* y, std::vector<size_t> keys)\n  double actualMHARaw2[9];\n  vv2double(Y, actualMHARaw2, nrKeys, fixedDim);\n  vector<size_t> dims;\n  size_t accumulatedDim = 0;\n  for (size_t i = 0; i < nrKeys+1; i++){\n    dims.push_back(accumulatedDim);\n    accumulatedDim += fixedDim;\n  }\n  regularFactor.multiplyHessianAdd(alpha, XRaw, actualMHARaw2, dims);\n  VectorValues actualMHARawVV2 = double2vv(actualMHARaw2,nrKeys,fixedDim);\n  EXPECT(assert_equal(expectedMHA,actualMHARawVV2));\n}\n\n/* ************************************************************************* */\nint main() { TestResult tr; return TestRegistry::runAllTests(tr);}\n/* ************************************************************************* */\n", "meta": {"hexsha": "b8c4aa689a89ba6e4e491421bc7c852d20bd1c10", "size": 8892, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/linear/tests/testRegularJacobianFactor.cpp", "max_stars_repo_name": "kvmanohar22/gtsam", "max_stars_repo_head_hexsha": "8194b931fe07fb1bd346cdcf116a35f9c4e208ba", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1402.0, "max_stars_repo_stars_event_min_datetime": "2017-03-28T00:18:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T10:28:32.000Z", "max_issues_repo_path": "gtsam/linear/tests/testRegularJacobianFactor.cpp", "max_issues_repo_name": "kvmanohar22/gtsam", "max_issues_repo_head_hexsha": "8194b931fe07fb1bd346cdcf116a35f9c4e208ba", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 851.0, "max_issues_repo_issues_event_min_datetime": "2017-11-27T15:09:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T22:26:38.000Z", "max_forks_repo_path": "gtsam/linear/tests/testRegularJacobianFactor.cpp", "max_forks_repo_name": "kvmanohar22/gtsam", "max_forks_repo_head_hexsha": "8194b931fe07fb1bd346cdcf116a35f9c4e208ba", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 565.0, "max_forks_repo_forks_event_min_datetime": "2017-11-30T16:15:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T02:53:04.000Z", "avg_line_length": 37.6779661017, "max_line_length": 109, "alphanum_fraction": 0.6513720198, "num_tokens": 2319, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947425132315, "lm_q2_score": 0.752012562644147, "lm_q1q2_score": 0.492489073579554}}
{"text": "/* test_uniform_smallint_distribution.cpp\n *\n * Copyright Steven Watanabe 2011\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#include <boost/random/uniform_smallint.hpp>\n#include <limits>\n\n#define BOOST_RANDOM_DISTRIBUTION boost::random::uniform_smallint<>\n#define BOOST_RANDOM_ARG1 a\n#define BOOST_RANDOM_ARG2 b\n#define BOOST_RANDOM_ARG1_DEFAULT 0\n#define BOOST_RANDOM_ARG2_DEFAULT 9\n#define BOOST_RANDOM_ARG1_VALUE 5\n#define BOOST_RANDOM_ARG2_VALUE 250\n\n#define BOOST_RANDOM_DIST0_MIN 0\n#define BOOST_RANDOM_DIST0_MAX 9\n#define BOOST_RANDOM_DIST1_MIN 5\n#define BOOST_RANDOM_DIST1_MAX 9\n#define BOOST_RANDOM_DIST2_MIN 5\n#define BOOST_RANDOM_DIST2_MAX 250\n\n#define BOOST_RANDOM_TEST1_PARAMS (0, 9)\n#define BOOST_RANDOM_TEST1_MIN 0\n#define BOOST_RANDOM_TEST1_MAX 9\n\n#define BOOST_RANDOM_TEST2_PARAMS (10, 19)\n#define BOOST_RANDOM_TEST2_MIN 10\n#define BOOST_RANDOM_TEST2_MAX 19\n\n#include \"test_distribution.ipp\"\n", "meta": {"hexsha": "d943ebfb211c76de874415906f1c8c8363972f49", "size": 1039, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/random/test/test_uniform_smallint_distribution.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "boost/libs/random/test/test_uniform_smallint_distribution.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "boost/libs/random/test/test_uniform_smallint_distribution.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "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": 26.641025641, "max_line_length": 67, "alphanum_fraction": 0.822906641, "num_tokens": 268, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125626441471, "lm_q2_score": 0.6548947425132314, "lm_q1q2_score": 0.492489073579554}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// Unit Test\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// 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// 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#if defined(_MSC_VER)\n#pragma warning( disable : 4305 ) // truncation double -> float\n#endif // defined(_MSC_VER)\n\n\n#include <boost/core/ignore_unused.hpp>\n\n#include <geometry_test_common.hpp>\n\n#include <boost/geometry/srs/epsg.hpp>\n#include <boost/geometry/srs/projection.hpp>\n\n#include <boost/geometry/core/coordinate_type.hpp>\n\n#include <boost/geometry/geometries/adapted/c_array.hpp>\n#include <boost/geometry/geometries/geometries.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <test_common/test_point.hpp>\n\nnamespace srs = bg::srs;\n\ntemplate <int E, typename P1, typename P2>\nvoid test_one(double lon, double lat,\n              typename bg::coordinate_type<P2>::type x,\n              typename bg::coordinate_type<P2>::type y)\n{\n    srs::projection<srs::static_epsg<E> > prj;\n    \n    P1 ll;\n    bg::set<0>(ll, lon);\n    bg::set<1>(ll, lat);\n\n    P2 xy;\n    bg::set<0>(xy, 0.0);\n    bg::set<1>(xy, 0.0);\n    prj.forward(ll, xy);\n\n    BOOST_CHECK_CLOSE(bg::get<0>(xy), x, 0.001);\n    BOOST_CHECK_CLOSE(bg::get<1>(xy), y, 0.001);\n}\n\ntemplate <typename D, typename P>\nvoid test_deg_rad(double factor)\n{\n    typedef typename bg::coordinate_type<P>::type coord_type;\n    typedef bg::model::point<coord_type, 2, bg::cs::geographic<D> > point_type;\n\n    test_one<28992, point_type, P>(4.897000 * factor, 52.371000 * factor, 121590.388077, 487013.903377);\n    test_one<29118, point_type, P>(4.897000 * factor, 52.371000 * factor, 4852882, 9129373);\n}\n\ntemplate <typename P>\nvoid test_all()\n{\n    test_deg_rad<bg::degree, P>(1.0);\n    test_deg_rad<bg::radian, P>(bg::math::d2r<double>());\n}\n\nint test_main(int, char* [])\n{\n    // Commented out most the types because otherwise it cannot be linked\n    //test_all<int[2]>();\n    //test_all<float[2]>();\n    //test_all<double[2]>();\n    //test_all<test::test_point>();\n    //test_all<bg::model::d2::point_xy<int> >();\n    ////test_all<bg::model::d2::point_xy<float> >();\n    ////test_all<bg::model::d2::point_xy<long double> >();\n\n    test_all<bg::model::d2::point_xy<double> >();\n\n    return 0;\n}\n", "meta": {"hexsha": "e91e11502aa2c9558c5074ea88acae5718a180b8", "size": 2834, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/test/srs/projection_epsg.cpp", "max_stars_repo_name": "lliurex/boost1.67", "max_stars_repo_head_hexsha": "bab6eba0e7ac4a0232bc0bcab501f1b447ddfdd5", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 35.0, "max_stars_repo_stars_event_min_datetime": "2018-02-01T20:53:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T18:41:05.000Z", "max_issues_repo_path": "libs/geometry/test/srs/projection_epsg.cpp", "max_issues_repo_name": "lliurex/boost1.67", "max_issues_repo_head_hexsha": "bab6eba0e7ac4a0232bc0bcab501f1b447ddfdd5", "max_issues_repo_licenses": ["BSL-1.0"], "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": "libs/geometry/test/srs/projection_epsg.cpp", "max_forks_repo_name": "lliurex/boost1.67", "max_forks_repo_head_hexsha": "bab6eba0e7ac4a0232bc0bcab501f1b447ddfdd5", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2021-01-08T05:05:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T14:56:56.000Z", "avg_line_length": 30.8043478261, "max_line_length": 104, "alphanum_fraction": 0.6873676782, "num_tokens": 842, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125848754472, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.49248907294305605}}
{"text": "#ifndef HYPSYS1D_RUNGE_KUTTA_HPP\n#define HYPSYS1D_RUNGE_KUTTA_HPP\n\n#include <Eigen/Dense>\n#include <map>\n#include <memory>\n\n#include <ancse/includes.hpp>\n#include <ancse/config.hpp>\n#include <ancse/dg_limiting.hpp>\n#include <ancse/boundary_condition.hpp>\n#include <ancse/rate_of_change.hpp>\n\n/// Interface advancing the solution of a PDE by one step.\nclass TimeIntegrator {\n  public:\n    virtual ~TimeIntegrator() = default;\n\n    /// Update 'u1' starting from 'u0' using a time-step `dt`.\n    virtual void operator()(Eigen::MatrixXd &u1,\n                            const Eigen::MatrixXd &u0,\n                            double dt) const = 0;\n};\n\n/// Runge-Kutta time integration methods.\n/** Note: not all methods are Runge-Kutta methods. Therefore, 'RungeKutta' can\n *        not be the interface. It should be the base for all (explicit)\n *        Runge-Kutta methods.\n */\nclass RungeKutta : public TimeIntegrator {\n  public:\n    RungeKutta(std::shared_ptr<RateOfChange> rate_of_change_,\n               std::shared_ptr<BoundaryCondition> boundary_condition_,\n               std::shared_ptr<Limiting> limiting_)\n  : rate_of_change(std::move(rate_of_change_)),\n    boundary_condition(std::move(boundary_condition_)),\n    limiting(std::move(limiting_))\n  {}\n\n  protected:\n    void post_euler_step(Eigen::MatrixXd &u) const {\n      (*boundary_condition)(u);\n      if(limiting != nullptr) {\n        (*limiting)(u);\n      }\n      (*boundary_condition)(u);\n    }\n\n  protected:\n    std::shared_ptr<RateOfChange> rate_of_change;\n    std::shared_ptr<BoundaryCondition> boundary_condition;\n    std::shared_ptr<Limiting> limiting;\n};\n\nclass ForwardEuler : public RungeKutta {\n  private:\n    using super = RungeKutta;\n\n  public:\n    ForwardEuler(std::shared_ptr<RateOfChange> rate_of_change_,\n                 std::shared_ptr<BoundaryCondition> boundary_condition_,\n                 std::shared_ptr<Limiting> limiting_,\n                 int n_rows,\n                 int n_cols)\n        : super(std::move(rate_of_change_),\n                std::move(boundary_condition_),\n                std::move(limiting_)),\n          dudt(n_rows, n_cols) {}\n\n    virtual void operator()(Eigen::MatrixXd &u1,\n                            const Eigen::MatrixXd &u0,\n                            double dt) const override {\n\n        (*rate_of_change)(dudt, u0);\n        u1 = u0 + dt * dudt;\n        post_euler_step(u1);\n    }\n\n  private:\n    mutable Eigen::MatrixXd dudt;\n};\n\n// Mishra lecture notes 5.8.1. p. 76, cf. Toro p. 539\nclass SSP2 : public RungeKutta {\n    private:\n        using super= RungeKutta;\n\n    public:\n        SSP2(std::shared_ptr<RateOfChange> rate_of_change_,\n             std::shared_ptr<BoundaryCondition> boundary_condition_,\n             std::shared_ptr<Limiting> limiting_,\n             int n_rows,\n             int n_cols)\n             : super(std::move(rate_of_change_),\n                     std::move(boundary_condition_),\n                     std::move(limiting_)),\n               dudt(n_rows, n_cols) {}\n\n        virtual void operator() (Eigen::MatrixXd &u1,\n                                 const Eigen::MatrixXd &u0,\n                                 double dt) const override\n        {\n            // u* step: using u1 as temp variable:\n            (*rate_of_change)(dudt, u0);\n            u1= u0 + dt * dudt;\n            post_euler_step(u1);\n\n            // u** step: again using u1 as temp variable:\n            (*rate_of_change)(dudt, u1);\n            u1= u1 + dt * dudt;\n            post_euler_step(u1);\n\n            // final RK2 assembly:\n            u1= 0.5 * (u0 + u1);\n            (*boundary_condition)(u1);\n        }\n\n    private:\n        mutable Eigen::MatrixXd dudt;\n};\n\n\n\n\n\n\n/// make Runge Kutta for FVM\nstd::shared_ptr<RungeKutta>\nmake_runge_kutta(const nlohmann::json &config,\n                 const std::shared_ptr<RateOfChange> &rate_of_change,\n                 const std::shared_ptr<BoundaryCondition> &boundary_condition,\n                 int n_rows,\n                 int n_cols);\n\n/// make Runge Kutta for DG\nstd::shared_ptr<RungeKutta>\nmake_runge_kutta(const nlohmann::json &config,\n                 const std::shared_ptr<RateOfChange> &rate_of_change,\n                 const std::shared_ptr<BoundaryCondition> &boundary_condition,\n                 const std::shared_ptr<Limiting> &dg_limiting,\n                 int n_rows,\n                 int n_cols);\n\n#endif // HYPSYS1D_RUNGE_KUTTA_HPP\n", "meta": {"hexsha": "2e77048a2a83064ba2d4a6813d15dedf6e1bc2be", "size": 4414, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "series2_workbench/hyp_sys_1d/include/ancse/runge_kutta.hpp", "max_stars_repo_name": "BeatHubmann/19H-AdvNCSE", "max_stars_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-05T22:38:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-05T22:38:47.000Z", "max_issues_repo_path": "series2_workbench/hyp_sys_1d/include/ancse/runge_kutta.hpp", "max_issues_repo_name": "BeatHubmann/19H-AdvNCSE", "max_issues_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "series2_workbench/hyp_sys_1d/include/ancse/runge_kutta.hpp", "max_forks_repo_name": "BeatHubmann/19H-AdvNCSE", "max_forks_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-12-08T20:43:27.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-08T20:43:27.000Z", "avg_line_length": 30.4413793103, "max_line_length": 78, "alphanum_fraction": 0.5962845492, "num_tokens": 1084, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.49248907072869536}}
{"text": "/**\n * @file Camera.hpp\n * @author Takashi Michikawa <michikawa@acm.org>\n */\n#ifndef MI4_CAMERA_HPP\n#define MI4_CAMERA_HPP 1\n\n#include <Eigen/Dense>\nnamespace mi4\n{\n        class Camera\n        {\n        public:\n                Camera (void) : _rotation(Eigen::Quaterniond(1, 0, 0, 0)), _center(Eigen::Vector3d(0, 0, 0)), _dist(0), _radius(100), _fov(40)\n                {\n                        Eigen::Vector3d b ( 1, 1, 1 );\n                        b.normalize();\n                        b *= 100;\n                        this->init ( -b, b );\n                        return;\n                }\n                Camera ( const Camera& that ) = default;\n                Camera ( Camera&& that ) = default;\n                Camera& operator = ( const Camera& that ) = default;\n                Camera& operator = ( Camera&& that ) = default;\n                ~Camera ( void ) = default;\n\n                void init ( const Eigen::Vector3d& bmin, const Eigen::Vector3d& bmax )\n                {\n                        this->_center = ( bmin + bmax ) * 0.5;\n                        this->_radius = ( bmin - bmax ).norm() * 0.5;\n                        this->_dist   = this->_radius * 1.0 / std::sin ( this->_fov / 360.0 * 3.1415926 ) ;\n                        return;\n                }\n                void init ( const Eigen::Vector3d& center, const double radius, const double dist )\n                {\n                        this->_center = center;\n                        this->_radius = radius;\n                        this->_dist   = dist;\n                }\n\n                void clone ( const Camera& that )\n                {\n                        this->init ( that._center, that._radius, that._dist );\n                        this->_rotation = that._rotation;\n                        return;\n                }\n\n                void getLookAt ( Eigen::Vector3d& eye, Eigen::Vector3d& center, Eigen::Vector3d& up )\n                {\n                        const auto& rotation = this->_rotation;\n                        center = this->_center;\n                        const auto& dist   = this->_dist;\n\n                        const auto r = rotation.toRotationMatrix();\n                        eye = r * Eigen::Vector3d(0, 0, dist) + center;\n                        up = r * Eigen::Vector3d(0, 1, 0);\n                        return;\n                }\n\n                void zoom ( bool isUp  )\n                {\n                        this->_dist *= isUp ? 0.99 : 1.0 / 0.99;\n                }\n\n                void getZNearFar ( double& zNear, double& zFar )\n                {\n                        const double& radius = this->_radius;\n                        const double& dist   = this->_dist;\n\n                        zNear = dist - radius;\n                        zFar  = dist + radius;\n\n                        zNear = std::max(0.01, zNear);\n\n                }\n\n                double getFov ( void ) const\n                {\n                        return this->_fov;\n                }\n\n                void rotate ( const double  oldx, const double oldy, const double newx, const double newy )\n                {\n                        auto& rotation = this->_rotation;\n                        Eigen::Vector3d oldp ( oldx, oldy, 0.0 );\n                        Eigen::Vector3d newp ( newx, newy, 0.0 );\n\n                        if ( oldp.isApprox ( newp, 1.0e-16 ) ) {\n                                return;\n                        }\n\n                        double radius_virtual_sphere = 0.9; // @todo move to attribute\n                        this->project_onto_sphere ( radius_virtual_sphere, oldp );\n                        this->project_onto_sphere ( radius_virtual_sphere, newp );\n                        Eigen::Quaterniond dr;\n                        dr.setFromTwoVectors ( newp, oldp );\n                        rotation *= dr;\n                        return;\n                }\n                /**\n                 * @brief Rotate by axis and angle.\n                 * @param [in] axis Axis of rotation.\n                 * @param [in] angle Rotation angle [rad].\n                 */\n                void rotate ( const Eigen::Vector3d& axis,  const double angle )\n                {\n                        Eigen::Quaterniond& rotation = this->_rotation;\n                        Eigen::AngleAxisd aa ( angle, axis );\n                        Eigen::Quaterniond dr ( aa );\n                        rotation *= dr;\n                        return;\n                }\n\n                /**\n                 * @brief Get radius of virtual sphere.\n                 */\n                double getRadius ( void ) const\n                {\n                        return this->_radius;\n                }\n\n                void moveTo ( const Eigen::Vector3d& newRay )\n                {\n                        this->_rotation.setIdentity();\n                        auto m = this->_rotation.toRotationMatrix();\n                        auto oldRay =  m *  Eigen::Vector3d ( 0, 0, 1 );\n                        this->_rotation.setFromTwoVectors ( newRay, oldRay );\n                }\n        private:\n                void\n                project_onto_sphere ( const double& radius, Eigen::Vector3d& p )\n                {\n                        p.z() = 0; // project onto xy-plane.\n                        const double d = p.x() * p.x() + p.y() * p.y();\n                        const double r = radius * radius;\n\n                        if ( d < r )\t{\n                                p.z() = std::sqrt ( r - d );        // on sphere\n                        } else {\n                                p *= radius / p.norm();        // on silhouette\n                        }\n\n                        return;\n                }\n        private:\n                Eigen::Quaterniond _rotation;\t///< rotation\n                Eigen::Vector3d _center;\t///< center point\n                double\t _dist;\t\t\t///< distance between eye-center.\n                double   _radius;\t\t///< radius of bounding sphere.\n                double   _fov;\t\t\t///< field-of-view angle\n        };\n}\n#endif", "meta": {"hexsha": "7c8392b473be3eb1d4ef9009b20d0a4377f79e06", "size": 6069, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mi4/Camera.hpp", "max_stars_repo_name": "tmichi/mi4", "max_stars_repo_head_hexsha": "238278cd6c3e088a08920155f048bc74963986fb", "max_stars_repo_licenses": ["MIT"], "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/mi4/Camera.hpp", "max_issues_repo_name": "tmichi/mi4", "max_issues_repo_head_hexsha": "238278cd6c3e088a08920155f048bc74963986fb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-05-28T02:28:58.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-28T03:00:24.000Z", "max_forks_repo_path": "include/mi4/Camera.hpp", "max_forks_repo_name": "tmichi/mi4", "max_forks_repo_head_hexsha": "238278cd6c3e088a08920155f048bc74963986fb", "max_forks_repo_licenses": ["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.4090909091, "max_line_length": 142, "alphanum_fraction": 0.3926511781, "num_tokens": 1243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.49248907072869536}}
{"text": "#ifndef GP_KERNELS_HPP\n#define GP_KERNELS_HPP\n\n#include <iostream>\n#include <memory>\n#include <vector>\n#include <Eigen/Core>\n#include <math.h>\n\n\nnamespace librav{\n    class Kernel{\n        public:\n            typedef std::shared_ptr<Kernel> Ptr;\n            typedef std::shared_ptr<const Kernel> ConstPtr;\n            virtual ~Kernel() {};\n\n            // Pure virtual methods to be implemented in a derived class\n            virtual double Evaluate(const Eigen::VectorXd& x, const Eigen::VectorXd& y) const = 0;\n            virtual long double EvaluateGradient(const Eigen::VectorXd& x, const Eigen::VectorXd& y, size_t ii, size_t jj) const = 0;\n            virtual double Partial(const Eigen::VectorXd& x, const Eigen::VectorXd& y, size_t ii) const = 0;\n            virtual void Gradient(const Eigen::VectorXd& x, const Eigen::VectorXd& y, Eigen::VectorXd& gradient) const = 0;\n\n            // Access and reset params.\n            Eigen::VectorXd Params() {return params_;};\n            const Eigen::VectorXd& ImmutableParams() const {return params_;};\n            void Reset(const Eigen::VectorXd& params){\n                params_ = params;\n            }\n            void Adjust(double diff, size_t ii){\n                params_(ii) += diff;\n            }\n            void SetParams(const size_t ii, const double param_ii){\n                params_(ii) = std::exp(param_ii);\n                // params_(ii) = param_ii;\n            }\n            \n        \n        protected:\n            explicit Kernel(const Eigen::VectorXd& params): params_(params) {};\n            Eigen::VectorXd params_;\n    };\n}\n\n#endif /* GP_KERNELS_HPP */", "meta": {"hexsha": "6f5c9f4a4a5522eece474331419808a33de647b3", "size": 1628, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/gplib/include/gplib/kernel.hpp", "max_stars_repo_name": "jfangwpi/Interactive_planning_and_sensing", "max_stars_repo_head_hexsha": "00042c51c2fdc020b7b1c184286cf2b513ed9096", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/gplib/include/gplib/kernel.hpp", "max_issues_repo_name": "jfangwpi/Interactive_planning_and_sensing", "max_issues_repo_head_hexsha": "00042c51c2fdc020b7b1c184286cf2b513ed9096", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gplib/include/gplib/kernel.hpp", "max_forks_repo_name": "jfangwpi/Interactive_planning_and_sensing", "max_forks_repo_head_hexsha": "00042c51c2fdc020b7b1c184286cf2b513ed9096", "max_forks_repo_licenses": ["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.1777777778, "max_line_length": 133, "alphanum_fraction": 0.5884520885, "num_tokens": 347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597971, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.4924890707286953}}
{"text": "#include \"definition.h\"\n\n#include <deal.II/dofs/dof_tools.h>\n#include <deal.II/lac/sparsity_tools.h>\n#include <deal.II/grid/grid_tools.h>\n#include <deal.II/dofs/dof_renumbering.h>\n\nnamespace bart {\n\nnamespace domain {\n\ntemplate <int dim>\nDefinition<dim>::Definition(\n    std::unique_ptr<domain::mesh::MeshI<dim>> mesh,\n    std::shared_ptr<domain::finite_element::FiniteElementI<dim>> finite_element,\n    problem::DiscretizationType discretization)\n    : mesh_(std::move(mesh)),                     \n      finite_element_(finite_element),\n      triangulation_(MPI_COMM_WORLD,\n                     typename dealii::Triangulation<dim>::MeshSmoothing(\n                         dealii::Triangulation<dim>::smoothing_on_refinement |\n                         dealii::Triangulation<dim>::smoothing_on_coarsening)),\n      dof_handler_(triangulation_),\n      discretization_type_(discretization) {\n  std::string description{\"Domain, \" + std::to_string(dim) + \"D\"};\n  if (discretization == problem::DiscretizationType::kContinuousFEM) {\n    description += \", Continuous\";\n  } else if (discretization == problem::DiscretizationType::kDiscontinuousFEM ){\n    description += \", Discontinuous\";\n  }\n  this->set_description(description, utility::DefaultImplementation(true));\n}\n\ntemplate <>\nDefinition<1>::Definition(\n    std::unique_ptr<domain::mesh::MeshI<1>> mesh,\n    std::shared_ptr<domain::finite_element::FiniteElementI<1>> finite_element,\n    problem::DiscretizationType discretization)\n    : mesh_(std::move(mesh)),\n      finite_element_(finite_element),\n      triangulation_(typename dealii::Triangulation<1>::MeshSmoothing(\n                         dealii::Triangulation<1>::smoothing_on_refinement |\n                             dealii::Triangulation<1>::smoothing_on_coarsening)),\n      dof_handler_(triangulation_),\n      discretization_type_(discretization) {\n  std::string description{\"Domain, 1D\"};\n  if (discretization == problem::DiscretizationType::kContinuousFEM) {\n    description += \", Continuous\";\n  } else if (discretization == problem::DiscretizationType::kDiscontinuousFEM ){\n    description += \", Discontinuous\";\n  }\n  this->set_description(description, utility::DefaultImplementation(true));\n}\n\ntemplate <int dim>\nDefinition<dim>& Definition<dim>::SetUpMesh() {\n  // SetUp triangulation using the mesh dependency\n  AssertThrow(mesh_->has_material_mapping(),\n                    dealii::ExcMessage(\"Mesh object must have initialized material mapping\"));\n  mesh_->FillTriangulation(triangulation_);\n  mesh_->FillBoundaryID(triangulation_);\n  mesh_->FillMaterialID(triangulation_);\n  return *this;\n}\n\ntemplate <int dim>\nDefinition<dim>& Definition<dim>::SetUpDOF() {\n  // Setup dof Handler\n  dof_handler_.distribute_dofs(*(finite_element_->finite_element()));\n  // Populate dof IndexSets\n  locally_owned_dofs_ = dof_handler_.locally_owned_dofs();\n  dealii::DoFTools::extract_locally_relevant_dofs(dof_handler_,\n                                                  locally_relevant_dofs_);\n  // Create constraint matrix\n  constraint_matrix_.clear();\n  constraint_matrix_.reinit(locally_relevant_dofs_);\n  dealii::DoFTools::make_hanging_node_constraints(dof_handler_,\n                                                  constraint_matrix_);\n  constraint_matrix_.close();\n\n  for (auto cell = dof_handler_.begin_active();\n       cell != dof_handler_.end(); ++cell) {\n    if (cell->is_locally_owned())\n      local_cells_.push_back(cell);\n  }\n\n  // Set up dynamic sparsity pattern\n  dynamic_sparsity_pattern_.reinit(locally_relevant_dofs_.size(),\n                                   locally_relevant_dofs_.size(),\n                                   locally_relevant_dofs_);\n\n  if (discretization_type_ ==  problem::DiscretizationType::kDiscontinuousFEM) {\n    dealii::DoFTools::make_flux_sparsity_pattern(dof_handler_,\n                                                 dynamic_sparsity_pattern_,\n                                                 constraint_matrix_, false);\n  } else {\n    dealii::DoFTools::make_sparsity_pattern(dof_handler_,\n                                            dynamic_sparsity_pattern_,\n                                            constraint_matrix_, false);\n  }\n\n  dealii::SparsityTools::distribute_sparsity_pattern(\n      dynamic_sparsity_pattern_,\n      dof_handler_.n_locally_owned_dofs_per_processor(),\n      MPI_COMM_WORLD, locally_relevant_dofs_);\n\n  constraint_matrix_.condense(dynamic_sparsity_pattern_);\n\n  return *this;\n}\n\ntemplate <>\nDefinition<1>& Definition<1>::SetUpDOF() {\n  auto n_mpi_processes = dealii::Utilities::MPI::n_mpi_processes(MPI_COMM_WORLD);\n  auto this_process = dealii::Utilities::MPI::this_mpi_process(MPI_COMM_WORLD);\n\n  dealii::GridTools::partition_triangulation(n_mpi_processes, triangulation_);\n  dof_handler_.distribute_dofs(*(finite_element_)->finite_element());\n  dealii::DoFRenumbering::subdomain_wise(dof_handler_);\n\n  for (auto cell = dof_handler_.begin_active();\n       cell != dof_handler_.end(); ++cell) {\n    if (cell->is_locally_owned())\n      local_cells_.push_back(cell);\n  }\n\n  auto locally_owned_dofs_vector =\n      dealii::DoFTools::locally_owned_dofs_per_subdomain(dof_handler_);\n  locally_owned_dofs_ = locally_owned_dofs_vector.at(this_process);\n\n  constraint_matrix_.clear();\n  dealii::DoFTools::make_hanging_node_constraints(dof_handler_,\n                                                  constraint_matrix_);\n  constraint_matrix_.close();\n\n  dynamic_sparsity_pattern_.reinit(dof_handler_.n_dofs(), dof_handler_.n_dofs());\n\n  if (discretization_type_ ==  problem::DiscretizationType::kDiscontinuousFEM) {\n    dealii::DoFTools::make_flux_sparsity_pattern(dof_handler_, dynamic_sparsity_pattern_,\n                                                 constraint_matrix_, false);\n  } else {\n    dealii::DoFTools::make_sparsity_pattern(dof_handler_, dynamic_sparsity_pattern_,\n                                            constraint_matrix_, false);\n  }\n\n  return *this;\n}\n\ntemplate<int dim>\nstd::shared_ptr<system::MPISparseMatrix> Definition<dim>::MakeSystemMatrix() const {\n  auto system_matrix_ptr = std::make_shared<system::MPISparseMatrix>();\n  system_matrix_ptr->reinit(locally_owned_dofs_,\n      locally_owned_dofs_,\n      dynamic_sparsity_pattern_,\n      MPI_COMM_WORLD);\n  return system_matrix_ptr;\n}\n\ntemplate<int dim>\nstd::shared_ptr<system::MPIVector> Definition<dim>::MakeSystemVector() const {\n  auto system_vector_ptr = std::make_shared<system::MPIVector>();\n  system_vector_ptr->reinit(locally_owned_dofs_, MPI_COMM_WORLD);\n  return system_vector_ptr;\n}\n\ntemplate <int dim>\nint Definition<dim>::total_degrees_of_freedom() const {\n  if (total_degrees_of_freedom_ == 0)\n    total_degrees_of_freedom_ = dof_handler_.n_dofs();\n  return total_degrees_of_freedom_;\n}\n\n\ntemplate class Definition<1>;\ntemplate class Definition<2>;\ntemplate class Definition<3>;\n\n} // namespace bart\n\n} // namespace domain\n", "meta": {"hexsha": "1521aa79ef521bb87d67b12157421429f9e82faf", "size": 6884, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/domain/definition.cc", "max_stars_repo_name": "narang-amit/BART", "max_stars_repo_head_hexsha": "22997c4ce6de3e97b39f4da4601edbd4cf73f9e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/domain/definition.cc", "max_issues_repo_name": "narang-amit/BART", "max_issues_repo_head_hexsha": "22997c4ce6de3e97b39f4da4601edbd4cf73f9e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/domain/definition.cc", "max_forks_repo_name": "narang-amit/BART", "max_forks_repo_head_hexsha": "22997c4ce6de3e97b39f4da4601edbd4cf73f9e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.0331491713, "max_line_length": 94, "alphanum_fraction": 0.6927658338, "num_tokens": 1546, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.63341027059799, "lm_q1q2_score": 0.4923497154024412}}
{"text": "#include \"iris.h\"\n#include <stdexcept>\n#include <iostream>\n#include <numeric>\n#include <chrono>\n#include <Eigen/LU>\n#include <Eigen/StdVector>\n#include \"iris/iris_mosek.h\"\n#include \"iris/cvxgen_ldp.h\"\n\nnamespace iris {\n\ntemplate <typename T>\nstd::vector<size_t> arg_sort(const std::vector<T> &vec) {\n  std::vector<size_t> idx(vec.size());\n  std::iota(idx.begin(), idx.end(), 0);\n  std::sort(idx.begin(), idx.end(), [&vec](size_t i0, size_t i1) {return vec[i0] < vec[i1];});\n  return idx;\n}\n\ntypedef std::pair<Eigen::VectorXd, double> hyperplane;\n\nhyperplane tangent_plane_through_point(const Ellipsoid &ellipsoid, const Eigen::MatrixXd &Cinv2, const Eigen::VectorXd &x) {\n  Eigen::VectorXd nhat = (2 * Cinv2 * (x - ellipsoid.getD())).normalized();\n  std::pair<Eigen::VectorXd, double> plane(nhat,\n                                    nhat.transpose() * x);\n  // std::cout << \"tangent plane through point: \" << x.transpose() << std::endl;\n  // std::cout << plane.first.transpose() << \" | \" << plane.second << std::endl;\n  return plane;\n}\n\nvoid choose_closest_point_solver(const Eigen::MatrixXd &Points, Eigen::VectorXd &result, MSKenv_t &env) {\n  // std::cout << \"points: \" << std::endl << Points << std::endl;\n  if (Points.rows() <= IRIS_CVXGEN_LDP_MAX_ROWS && Points.cols() <= IRIS_CVXGEN_LDP_MAX_COLS) {\n    iris_cvxgen::closest_point_in_convex_hull(Points, result);\n  } else {\n    if (!env) {\n      // std::cout << \"making env\" << std::endl;\n      iris_mosek::check_res(MSK_makeenv(&env, NULL));\n    }\n    iris_mosek::closest_point_in_convex_hull(Points, result, &env);\n  }\n  // std::cout << \"closest point: \" << result.transpose() << std::endl;\n}\n\nvoid separating_hyperplanes(const std::vector<Eigen::MatrixXd> obstacle_pts, const Ellipsoid &ellipsoid, Polyhedron &polyhedron, bool &infeasible_start) {\n\n  int dim = ellipsoid.getDimension();\n  infeasible_start = false;\n  int n_obs = obstacle_pts.size();\n\n  if (n_obs == 0) {\n    polyhedron.setA(Eigen::MatrixXd::Zero(0, dim));\n    polyhedron.setB(Eigen::VectorXd::Zero(0));\n    return;\n  }\n\n  Eigen::MatrixXd Cinv = ellipsoid.getC().inverse();\n  Eigen::MatrixXd Cinv2 = Cinv * Cinv.transpose();\n\n  Eigen::Matrix<bool, Eigen::Dynamic, 1> uncovered_obstacles = Eigen::Matrix<bool, Eigen::Dynamic, 1>::Constant(n_obs, true);\n\n  std::vector<Eigen::MatrixXd> image_pts(n_obs);\n  for (int i=0; i < n_obs; i++) {\n    image_pts[i] = Cinv * (obstacle_pts[i].colwise() - ellipsoid.getD());\n  }\n\n  std::vector<Eigen::VectorXd> image_squared_dists(n_obs);\n  for (int i=0; i < n_obs; i++) {\n    image_squared_dists[i] = image_pts[i].colwise().squaredNorm();\n  }\n\n  std::vector<double> obs_min_squared_image_dists(n_obs);\n  for (int i=0; i < n_obs; i++) {\n    obs_min_squared_image_dists[i] = image_squared_dists[i].minCoeff();\n  }\n  std::vector<size_t> obs_sort_idx = arg_sort(obs_min_squared_image_dists);\n\n  std::vector<std::pair<Eigen::VectorXd, double>> planes;\n\n  MSKenv_t env = NULL;\n  for (auto it = obs_sort_idx.begin(); it != obs_sort_idx.end(); ++it) {\n    size_t i = *it;\n    if (!uncovered_obstacles(i)) {\n      continue;\n    }\n    Eigen::DenseIndex idx;\n    image_squared_dists[i].minCoeff(&idx);\n    hyperplane plane = tangent_plane_through_point(ellipsoid, Cinv2, obstacle_pts[i].col(idx));\n    if ((((plane.first.transpose() * obstacle_pts[i]).array() - plane.second) >= 0).all()) {\n      // nhat already separates the ellipsoid from obstacle i, so we can skip the optimization\n      planes.push_back(plane);\n    } else {\n      Eigen::VectorXd ystar(dim);\n      choose_closest_point_solver(image_pts[i], ystar, env);\n\n      if (ystar.squaredNorm() < 1e-6) {\n        // d is inside the obstacle. So we'll just reverse nhat to try to push the\n        // ellipsoid out of the obstacle.\n        infeasible_start = true;\n        planes.emplace_back(-plane.first, -plane.first.transpose() * obstacle_pts[i].col(idx));\n      } else {\n        Eigen::VectorXd xstar = ellipsoid.getC() * ystar + ellipsoid.getD();\n        planes.push_back(tangent_plane_through_point(ellipsoid, Cinv2, xstar));\n      }\n    }\n\n    for (size_t j=0; j < n_obs; j++) {\n      if (((planes.back().first.transpose() * obstacle_pts[j]).array() >= planes.back().second).all()) {\n        uncovered_obstacles(j) = false;\n      }\n    }\n    uncovered_obstacles(i) = false; // even if it doesn't pass the strict check, we're done with this obstacle\n\n    if (!uncovered_obstacles.any()) {\n      break;\n    }\n  }\n\n  // Eigen::MatrixXd A = polyhedron.getA();\n  // Eigen::VectorXd b = polyhedron.getB();\n  // A.resize(planes.size(), dim);\n  // b.resize(planes.size(), 1);\n  Eigen::MatrixXd A(planes.size(), dim);\n  Eigen::VectorXd b(planes.size());\n\n  for (auto it = planes.begin(); it != planes.end(); ++it) {\n    A.row(it - planes.begin()) = it->first.transpose();\n    b(it - planes.begin()) = it->second;\n  }\n  polyhedron.setA(A);\n  polyhedron.setB(b);\n\n  return;\n}\n\nIRISRegion inflate_region(const IRISProblem &problem, const IRISOptions &options, IRISDebugData *debug) {\n  // std::cout << \"running IRIS with the following inputs: \" << std::endl;\n  // std::cout << \"bounds: \" << std::endl << problem.getBounds().getA() << std::endl << problem.getBounds().getB() << std::endl;\n  // std::cout << \"obstacles: \" << std::endl;\n  // auto debug_obstacles = problem.getObstacles();\n  // for (auto it = debug_obstacles.begin(); it != debug_obstacles.end(); ++it) {\n  //   std::cout << *it << std::endl;\n  // }\n\n  IRISRegion region(problem.getDimension());\n  region.ellipsoid.setC(problem.getSeed().getC());\n  region.ellipsoid.setD(problem.getSeed().getD());\n\n  double best_vol = pow(ELLIPSOID_C_EPSILON, problem.getDimension());\n  double volume;\n  long int iter = 0;\n  bool infeasible_start;\n  Polyhedron new_poly(problem.getDimension());\n\n  if (debug) {\n    // std::cout << \"starting debug\" << std::endl;\n    debug->bounds = problem.getBounds();\n    debug->ellipsoid_history.push_back(region.ellipsoid);\n    // std::cout << \"pushing back obstacles\" << std::endl;\n    auto obstacles = problem.getObstacles();\n    for (auto obs = obstacles.begin(); obs != obstacles.end(); ++obs) {\n      // std::cout << \"pushing back obstacle: \" << *obs << std::endl;\n      debug->obstacles.push_back(*obs);\n    }\n    // debug->obstacles = std::vector<Eigen::MatrixXd>(problem.getObstacles().begin(), problem.getObstacles().end());\n  }\n\n  float p_time = 0;\n  float e_time = 0;\n\n  while (1) {\n    auto begin = std::chrono::high_resolution_clock::now();\n    // std::cout << \"calling hyperplanes with: \" << std::endl;\n    // std::cout << \"C: \" << region.ellipsoid->getC() << std::endl;\n    // std::cout << \"d: \" << region.ellipsoid->getD() << std::endl;\n    separating_hyperplanes(problem.getObstacles(), region.ellipsoid, new_poly, infeasible_start);\n    auto end = std::chrono::high_resolution_clock::now();\n    auto elapsed = std::chrono::duration_cast<std::chrono::duration<float>>(end - begin);\n    p_time += elapsed.count();\n\n    if (options.error_on_infeasible_start && infeasible_start) {\n      throw(InitialPointInfeasibleError());\n    }\n\n    new_poly.appendConstraints(problem.getBounds());\n\n    // std::cout << \"A: \" << std::endl << new_poly.getA() << std::endl;\n    // std::cout << \"b: \" << new_poly.getB().transpose() << std::endl;\n\n    if (options.require_containment) {\n      bool all_points_contained;\n      if (options.required_containment_points.size()) {\n        all_points_contained = true;\n        for (auto pt = options.required_containment_points.begin(); pt != options.required_containment_points.end(); ++pt) {\n          if (!new_poly.contains(*pt, 0.0)) {\n            all_points_contained = false;\n            break;\n          }\n        }\n      } else {\n        all_points_contained = new_poly.contains(problem.getSeed().getD(), 0.0);\n      }\n\n      if (all_points_contained || infeasible_start) {\n        region.polyhedron = new_poly;\n        if (debug) {\n          debug->polyhedron_history.push_back(new_poly);\n        }\n      } else {\n        std::cout << \"breaking early because the start point is no longer contained in the polyhedron\" << std::endl;\n        return region;\n      }\n    } else {\n      region.polyhedron = new_poly;\n      if (debug) {\n        debug->polyhedron_history.push_back(new_poly);\n      }\n    }\n\n    // std::cout << \"calling inner_ellipsoid with: \" << std::endl;\n    // std::cout << \"A: \" << region.polyhedron->getA() << std::endl;\n    // std::cout << \"b: \" << region.polyhedron->getB() << std::endl;\n    begin = std::chrono::high_resolution_clock::now();\n    volume = iris_mosek::inner_ellipsoid(region.polyhedron, &region.ellipsoid);\n    end = std::chrono::high_resolution_clock::now();\n    elapsed = std::chrono::duration_cast<std::chrono::duration<float>>(end - begin);\n    e_time += elapsed.count();\n\n    if (debug) {\n      debug->ellipsoid_history.push_back(region.ellipsoid);\n    }\n    // std::cout << \"C: \" << region.ellipsoid->getC() << std::endl;\n    // std::cout << \"volume: \" << volume << std::endl;\n    // std::cout << \"det: \" << region.ellipsoid->getC().determinant() << std::endl;\n\n    const bool at_iter_limit = (options.iter_limit > 0) && (iter + 1 >= options.iter_limit);\n    const bool insufficient_progress = (std::abs(volume - best_vol) / best_vol) < options.termination_threshold;\n    if (at_iter_limit || insufficient_progress) {\n      // std::cout << \"(abs(volume - best_vol) / best_vol): \" << (std::abs(volume - best_vol) / best_vol) << std::endl;\n      // std::cout << \"term thresh: \" << options.termination_threshold << std::endl;\n      break;\n    }\n\n    best_vol = volume; // always true because ellipsoid volume is guaranteed to be non-decreasing (see Deits14). \n    iter++;\n    if (debug) {\n      debug->iters = iter;\n    }\n  }\n\n  // std::cout << \"c++ p time: \" << p_time << std::endl;\n  // std::cout << \"c++ e time: \" << e_time << std::endl;\n  // std::cout << \"c++ iters: \" << iter << std::endl;\n  return region;\n}\n\n}", "meta": {"hexsha": "9393105201dc5ebf662bf6f7eb890fc1138db42c", "size": 9890, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "iris/src/iris.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/src/iris.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/src/iris.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": 38.3333333333, "max_line_length": 154, "alphanum_fraction": 0.6342770475, "num_tokens": 2716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.49234971002340966}}
{"text": "#include \"eval.hpp\"\n#include <Superpixels.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <iostream>\n#include <numeric>\n\nnamespace dasp {\nnamespace eval {\n\nfloat Area(const Superpixels& u)\n{\n\t// compute labels\n\tslimage::Image1i labels = u.ComputeLabels();\n\tstd::vector<unsigned int> sp_area(u.clusterCount());\n\tfor(std::size_t i=0; i<labels.size(); i++) {\n\t\tint label = labels[i];\n\t\tif(label == -1) {\n\t\t\tcontinue;\n\t\t}\n\t\t// compute pixel area\n\t\tsp_area[label] ++;\n\t}\n\t// mean\n\treturn static_cast<float>(std::accumulate(sp_area.begin(), sp_area.end(), 0.0f)) / static_cast<float>(sp_area.size());\n}\n\nfloat Area3D(const Superpixels& u)\n{\n\t// compute labels\n\tslimage::Image1i labels = u.ComputeLabels();\n\tstd::vector<float> sp_area(u.clusterCount());\n\tfor(std::size_t i=0; i<labels.size(); i++) {\n\t\tint label = labels[i];\n\t\tif(label == -1) {\n\t\t\tcontinue;\n\t\t}\n\t\t// 3D \n\t\tconst Point& p = u.points[i];\n\t\tfloat size_of_a_px = p.depth() / u.opt.camera.focal;\n\t\tfloat area_of_a_px = size_of_a_px*size_of_a_px / p.computeCircularity();\n\t\t// compute pixel area\n\t\tsp_area[label] += area_of_a_px;\n\t}\n\t// mean\n\treturn std::accumulate(sp_area.begin(), sp_area.end(), 0.0f) / static_cast<float>(sp_area.size());\n}\n\nslimage::Image1i MarkBoundary(const slimage::Image1i& labels)\n{\n\tslimage::Image1i boundary(labels.dimensions(), slimage::Pixel1i{1});\n\tfor(unsigned int y=1; y+1<boundary.height(); y++) {\n\t\tfor(unsigned int x=1; x+1<boundary.width(); x++) {\n\t\t\tint q = labels(x, y);\n\t\t\tint qp0 = labels(x+1, y  );\n\t\t\tint qm0 = labels(x-1, y  );\n\t\t\tint q0p = labels(x  , y+1);\n\t\t\tint q0m = labels(x  , y-1);\n\t\t\tif(q == qp0 && q == qm0 && q == q0p && q == q0m) {\n\t\t\t\tboundary(x,y) = 0;\n\t\t\t}\n\t\t}\n\t}\n\treturn boundary;\n}\n\ntemplate<typename K>\nstd::pair<float,std::vector<float>> IsoperimetricQuotientImpl(const std::vector<std::pair<K,K>>& sp_area_length)\n{\n\t// per cluster: v_i = 4*pi*A_i/L_i^2\n\t// total: sum_i v_i*A_i\n\tstd::vector<float> ipq(sp_area_length.size());\n\tfloat ipq_total = 0.0f;\n\tfloat num_total = 0.0f;\n\tfor(std::size_t i=0; i<ipq.size(); i++) {\n\t\tconst auto& q = sp_area_length[i];\n\t\tfloat area = static_cast<float>(q.first);\n\t\tfloat len = static_cast<float>(q.second);\n\t\tfloat x = 4.0f*boost::math::constants::pi<float>() * area / (len*len);\n\t\tipq[i] = x;\n\t\tipq_total += x*area;\n\t\tnum_total += area;\n//\t\tstd::cout << \"area=\" << area << \", len=\" << len << \", ipq=\" << x << std::endl;\n\t}\n\treturn {ipq_total / num_total, ipq};\n}\n\nstd::pair<float,std::vector<float>> IsoperimetricQuotient(const Superpixels& u)\n{\n\t// compute labels\n\tslimage::Image1i labels = u.ComputeLabels();\n\t// compute boundary image\n\tslimage::Image1i boundary = MarkBoundary(labels);\n\t// compute total pixel count and number of boundary pixels for each cluster\n\tstd::vector<std::pair<int,int>> ipq_els(u.clusterCount(), {0,0});\n\tfor(std::size_t i=0; i<labels.size(); i++) {\n\t\tint label = labels[i];\n\t\tif(label == -1) {\n\t\t\tcontinue;\n\t\t}\n\t\tif(boundary[i] == 1) {\n\t\t\tipq_els[label].second ++;\n\t\t}\n\t\telse {\n\t\t\tipq_els[label].first ++;\t\n\t\t}\n\t}\n\t// finalize\n\treturn IsoperimetricQuotientImpl(ipq_els);\n}\n\nstd::pair<float,std::vector<float>> IsoperimetricQuotient3D(const Superpixels& u)\n{\n\t// compute labels\n\tslimage::Image1i labels = u.ComputeLabels();\n\t// compute boundary image\n\tslimage::Image1i boundary = MarkBoundary(labels);\n\t// compute total pixel count and number of boundary pixels for each cluster\n\tstd::vector<std::pair<float,float>> ipq_els(u.clusterCount(), {0.0f,0.0f});\n//\tstd::vector<std::vector<std::size_t>> seg_bnd(u.clusterCount());\n\tfor(std::size_t i=0; i<labels.size(); i++) {\n\t\tint label = labels[i];\n\t\tif(label == -1) {\n\t\t\tcontinue;\n\t\t}\n\t\t// 3D \n\t\tconst Point& p = u.points[i];\n\t\tfloat size_of_a_px = p.depth() / u.opt.camera.focal;\n\t\tfloat gamma = p.computeCircularity();\n\t\tfloat px_area = size_of_a_px*size_of_a_px / gamma;\n\t\tfloat px_len = (1.571 - 0.571 * gamma) * size_of_a_px;\n\t\t// compute pixel area\n\t\tipq_els[label].first += px_area;\n\t\t// compute pixel diameter\n\t\tif(boundary[i] == 1) {\n//\t\t\tseg_bnd[label].push_back(i);\n\t\t\tipq_els[label].second += px_len;\n\t\t}\n\t}\n// \t// compute segment boundary length\n// \tunsigned int w = u.width();\n// \tfor(unsigned int k=0; k<seg_bnd.size(); k++) {\n// \t\tfloat L = 0.0f;\n// \t\tconst std::vector<std::size_t>& B = seg_bnd[k];\n// \t\tfor(unsigned int i=0; i<B.size(); i++) {\n// \t\t\tunsigned int ii = B[i];\n// \t\t\tint iy = ii/w;\n// \t\t\tint ix = ii - iy*w;\n// \t\t\tfor(unsigned int j=i+1; j<B.size(); j++) {\n// \t\t\t\tunsigned int jj = B[j];\n// \t\t\t\tint jy = jj/w;\n// \t\t\t\tint jx = jj - jy*w;\n// \t\t\t\tint dx = std::abs(ix-jx);\n// \t\t\t\tint dy = std::abs(iy-jy);\n// \t\t\t\tif((dx == 1 && dy == 0) || (dx == 0 && dy == 1)) {\n// \t\t\t\t\tL += (u.points[ii].position - u.points[jj].position).norm();\n// \t\t\t\t}\n// \t\t\t}\n// \t\t}\n// //\t\tstd::cout << k << \": \" << ipq_els[k].second << \" -> \" << L << std::endl;\n// \t\tipq_els[k].second = L;\n// \t}\n\t// finalize\n\treturn IsoperimetricQuotientImpl(ipq_els);\n}\n\n}}\n", "meta": {"hexsha": "e43390c2e83dc7693cbf9c3500e6cfb1033452de", "size": 4907, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib_dasp/lib_dasp/eval/ipq.cpp", "max_stars_repo_name": "jbellis/superpixel-benchmark", "max_stars_repo_head_hexsha": "81a45649d426751d1ae450ef8ea0d2d9c7b3545f", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 344.0, "max_stars_repo_stars_event_min_datetime": "2016-12-16T10:11:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T06:08:14.000Z", "max_issues_repo_path": "lib_dasp/lib_dasp/eval/ipq.cpp", "max_issues_repo_name": "jbellis/superpixel-benchmark", "max_issues_repo_head_hexsha": "81a45649d426751d1ae450ef8ea0d2d9c7b3545f", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2018-02-15T19:34:19.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-31T17:04:48.000Z", "max_forks_repo_path": "lib_dasp/lib_dasp/eval/ipq.cpp", "max_forks_repo_name": "jbellis/superpixel-benchmark", "max_forks_repo_head_hexsha": "81a45649d426751d1ae450ef8ea0d2d9c7b3545f", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 111.0, "max_forks_repo_forks_event_min_datetime": "2016-12-08T07:19:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T06:08:16.000Z", "avg_line_length": 29.3832335329, "max_line_length": 119, "alphanum_fraction": 0.6244141023, "num_tokens": 1580, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.4923497100234096}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2014 Roshan <thisisroshansmail@gmail.com>\n//\n// Distributed under the Boost Software License, Version 1.0\n// See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt\n//\n// See http://kylelutz.github.com/compute for more information.\n//---------------------------------------------------------------------------//\n\n#ifndef BOOST_COMPUTE_RANDOM_UNIFORM_INT_DISTRIBUTION_HPP\n#define BOOST_COMPUTE_RANDOM_UNIFORM_INT_DISTRIBUTION_HPP\n\n#include <boost/compute/command_queue.hpp>\n#include <boost/compute/container/vector.hpp>\n#include <boost/compute/function.hpp>\n#include <boost/compute/types/fundamental.hpp>\n#include <boost/compute/algorithm/copy_if.hpp>\n#include <boost/compute/algorithm/transform.hpp>\n\nnamespace boost {\nnamespace compute {\n\n/// \\class uniform_int_distribution\n/// \\brief Produces uniformily distributed random integers\n///\n/// The following example shows how to setup a uniform int distribution to\n/// produce random integers 0 and 1.\n///\n/// \\snippet test/test_uniform_int_distribution.cpp generate\n///\ntemplate<class IntType = uint_>\nclass uniform_int_distribution\n{\npublic:\n    typedef IntType result_type;\n\n    /// Creates a new uniform distribution producing numbers in the range\n    /// [\\p a, \\p b].\n    uniform_int_distribution(IntType a = 0, IntType b = 1)\n        : m_a(a),\n          m_b(b)\n    {\n    }\n\n    /// Destroys the uniform_int_distribution object.\n    ~uniform_int_distribution()\n    {\n    }\n\n    /// Returns the minimum value of the distribution.\n    result_type a() const\n    {\n        return m_a;\n    }\n\n    /// Returns the maximum value of the distribution.\n    result_type b() const\n    {\n        return m_b;\n    }\n\n    /// Generates uniformily distributed integers and stores\n    /// them to the range [\\p first, \\p last).\n    template<class OutputIterator, class Generator>\n    void generate(OutputIterator first,\n                  OutputIterator last,\n                  Generator &generator,\n                  command_queue &queue)\n    {\n        size_t size = std::distance(first, last);\n        typedef typename Generator::result_type g_result_type;\n\n        vector<g_result_type> tmp(size, queue.get_context());\n        vector<g_result_type> tmp2(size, queue.get_context());\n\n        uint_ bound = ((uint_(-1))/(m_b-m_a+1))*(m_b-m_a+1);\n\n        buffer_iterator<g_result_type> tmp2_iter;\n\n        while(size>0)\n        {\n            generator.generate(tmp.begin(), tmp.begin() + size, queue);\n            tmp2_iter = copy_if(tmp.begin(), tmp.begin() + size, tmp2.begin(),\n                                _1 <= bound, queue);\n            size = std::distance(tmp2_iter, tmp2.end());\n        }\n\n        BOOST_COMPUTE_FUNCTION(IntType, scale_random, (const g_result_type x),\n        {\n            return LO + (x % (HI-LO+1));\n        });\n\n        scale_random.define(\"LO\", boost::lexical_cast<std::string>(m_a));\n        scale_random.define(\"HI\", boost::lexical_cast<std::string>(m_b));\n\n        transform(tmp2.begin(), tmp2.end(), first, scale_random, queue);\n    }\n\nprivate:\n    IntType m_a;\n    IntType m_b;\n};\n\n} // end compute namespace\n} // end boost namespace\n\n#endif // BOOST_COMPUTE_RANDOM_UNIFORM_INT_DISTRIBUTION_HPP\n", "meta": {"hexsha": "11f74538b03c104f69738afa0a365d2f0f4d88d4", "size": 3301, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/compute/random/uniform_int_distribution.hpp", "max_stars_repo_name": "skozilla/compute", "max_stars_repo_head_hexsha": "861a75ae9f05f5bbd25d13120788133a1c9dc886", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-03-18T01:14:13.000Z", "max_stars_repo_stars_event_max_datetime": "2015-03-18T01:14:13.000Z", "max_issues_repo_path": "include/boost/compute/random/uniform_int_distribution.hpp", "max_issues_repo_name": "junmuz/compute", "max_issues_repo_head_hexsha": "b979ff527d3f1cb6e073da29b167bf02b3218c9a", "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/compute/random/uniform_int_distribution.hpp", "max_forks_repo_name": "junmuz/compute", "max_forks_repo_head_hexsha": "b979ff527d3f1cb6e073da29b167bf02b3218c9a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2844036697, "max_line_length": 79, "alphanum_fraction": 0.6292032717, "num_tokens": 724, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.63341026367784, "lm_q1q2_score": 0.4923497100234096}}
{"text": "/** @file\n    @brief Implementation\n\n    @date 2016\n\n    @author\n    Sensics, Inc.\n    <http://sensics.com/osvr>\n*/\n\n// Copyright 2016 Sensics, Inc.\n// Copyright 2019 Collabora, Ltd.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//        http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n// Internal Includes\n#include \"TestIMU_Common.h\"\n\n// Library/third-party includes\n#include \"FlexKalman/FlexibleUnscentedCorrect.h\"\n#include <Eigen/Eigenvalues>\n\n// Standard includes\n// - none\n\ntemplate <typename Derived>\ninline bool isPositiveDefinite(MatrixBase<Derived> const &m) {\n    Derived const &mat = m.derived();\n    if (mat.rows() != mat.cols()) {\n        /// not square!\n        return false;\n    }\n    if (!mat.isApprox(mat.transpose())) {\n        /// Not symmetric!\n        return false;\n    }\n    // Having all positive eigenvalues is equivalent to being positive definite.\n    return (mat.eigenvalues().real().array() > 0.).all();\n}\n\ntemplate <typename Derived>\ninline void checkSigmaPoints(MatrixBase<Derived> const &m) {\n    SECTION(\"Sigma points\") {\n        Derived const &mat = m.derived();\n        {\n            INFO(\"Checking that there are at least two unique sigma points in \"\n                 \"the collection of sigma points.\");\n            REQUIRE_FALSE((mat.rowwise().minCoeff().array() ==\n                           mat.rowwise().maxCoeff().array())\n                              .all());\n        }\n    }\n}\n\ntemplate <typename Derived>\ninline void thenCheckCovariance(MatrixBase<Derived> const &c) {\n    Derived const &cov = c.derived();\n    THEN(\"Covariance should be symmetric\") {\n        REQUIRE(cov.isApprox(cov.transpose()));\n        AND_THEN(\"Covariance should be positive-definite\") {\n            REQUIRE(isPositiveDefinite(cov));\n        }\n    }\n}\n\ntemplate <typename Reconstruction>\ninline void thenCheckReconstruction(Reconstruction const &recon) {\n    THEN(\"Reconstructed covariance should satisfy its invariants\") {\n        thenCheckCovariance(recon.getCov());\n    }\n}\ntemplate <typename Reconstruction>\ninline void andThenCheckReconstruction(Reconstruction const &recon) {\n    AND_THEN(\"Reconstructed covariance should satisfy its invariants\") {\n        thenCheckCovariance(recon.getCov());\n    }\n}\ntemplate <typename GeneratorType>\ninline void generatorChecks(GeneratorType const &gen) {\n    static const auto epsilon = NumTraits<double>::dummy_precision();\n\n    SECTION(\"Weights\") {\n        CAPTURE(gen.getWeightsForMean().transpose());\n        {\n            INFO(\"Weights should be non-zero\");\n            REQUIRE(((gen.getWeightsForMean().array() > epsilon) ||\n                     (gen.getWeightsForMean().array() < -epsilon))\n                        .all());\n        }\n#ifdef DEMAND_NONNEGATIVE_WEIGHTS\n        CHECK((gen.getWeightsForMean().array() >= 0.).all());\n#endif\n\n        CAPTURE(gen.getWeightsForCov().transpose());\n        {\n            INFO(\"Weights should be non-zero\");\n            REQUIRE(((gen.getWeightsForCov().array() > epsilon) ||\n                     (gen.getWeightsForCov().array() < -epsilon))\n                        .all());\n        }\n#ifdef DEMAND_NONNEGATIVE_WEIGHTS\n        CHECK((gen.getWeightsForCov().array() >= 0.).all());\n#endif\n    }\n\n    checkSigmaPoints(gen.getSigmaPoints());\n}\n\ntemplate <typename GeneratorType>\ninline void thenCheckSigmaPointGenerator(GeneratorType const &gen) {\n    THEN(\"Sigma point generator should have reasonable output\") {\n        generatorChecks(gen);\n    }\n}\ntemplate <typename GeneratorType>\ninline void andThenCheckSigmaPointGenerator(GeneratorType const &gen) {\n    AND_THEN(\"Sigma point generator should have reasonable output\") {\n        generatorChecks(gen);\n    }\n}\n\nTEST_CASE(\"Sigma point reconstruction validity\") {\n    Catch::StringMaker<float>::precision = 15;\n    Catch::StringMaker<double>::precision = 35;\n\n    static const auto DIM = 3;\n    using namespace flexkalman;\n    Matrix3d cov(Vector3d::Constant(10).asDiagonal());\n\n    auto checkReconstruction = [&](Eigen::Vector3d const &mean) {\n        using namespace flexkalman;\n        using Generator = SigmaPointGenerator<DIM>;\n        using Reconstructor =\n            ReconstructedDistributionFromSigmaPoints<DIM, Generator>;\n        const auto params = SigmaPointParameters();\n        CAPTURE(mean);\n        CAPTURE(cov);\n        auto gen = Generator(mean, cov, params);\n        thenCheckSigmaPointGenerator(gen);\n#if 0\n        static const auto numSigmaPoints = Generator::NumSigmaPoints;\n        for (std::size_t i = 0; i < numSigmaPoints; ++i) {\n            CAPTURE(gen.getSigmaPoint(i));\n            CHECK(false);\n        }\n#endif\n        AND_WHEN(\"reconstructed from the sigma points\") {\n            auto recon = Reconstructor(gen, gen.getSigmaPoints());\n            thenCheckReconstruction(recon);\n            THEN(\"the reconstructed distribution should be approximately equal \"\n                 \"to the input\") {\n                CAPTURE(gen.getSigmaPoints());\n                CAPTURE(recon.getMean());\n                for (std::size_t i = 0; i < DIM; ++i) {\n                    CAPTURE(i);\n                    REQUIRE(recon.getMean()[i] == Approx(mean[i]));\n                }\n                CAPTURE(recon.getCov());\n                REQUIRE(recon.getCov().isApprox(cov));\n            }\n        }\n    };\n\n    WHEN(\"Starting with a zero mean\") { checkReconstruction(Vector3d::Zero()); }\n\n    WHEN(\"Starting with a non-zero mean\") {\n        checkReconstruction(Vector3d(1, 2, 3));\n    }\n    WHEN(\"Starting with a small non-zero mean\") {\n        checkReconstruction(Vector3d(0.1, 0.2, 0.3));\n    }\n}\n\nenum class Axis : std::size_t { X = 0, Y = 1, Z = 2 };\n\ninline double zeroOrValueForAxis(Axis rotationAxis, Axis currentAxis,\n                                 double value) {\n    return ((rotationAxis == currentAxis) ? value : 0.);\n}\n\ninline Vector3d ZeroVec3dExceptAtAxis(Axis rotationAxis, double value) {\n    return Vector3d(zeroOrValueForAxis(rotationAxis, Axis::X, value),\n                    zeroOrValueForAxis(rotationAxis, Axis::Y, value),\n                    zeroOrValueForAxis(rotationAxis, Axis::Z, value));\n}\n\ninline Vector3d Vec3dSmallValueAt(Axis rotationAxis) {\n    return ZeroVec3dExceptAtAxis(rotationAxis, SMALL_VALUE);\n}\n\ninline Vector3d Vec3dUnit(Axis rotationAxis) {\n    return ZeroVec3dExceptAtAxis(rotationAxis, 1.);\n}\n\ninline double getSignCorrect(bool positive) { return (positive ? 1. : -1.); }\n\ntemplate <typename MeasurementType, typename InProgressType>\ninline void\ncommonSmallSingleAxisChecks(TestData *data, MeasurementType &kalmanMeas,\n                            InProgressType &inProgress, Axis const rotationAxis,\n                            bool const positive = true) {\n    const double signCorrect = getSignCorrect(positive);\n    Vector3d rotationVector = Vec3dSmallValueAt(rotationAxis) * signCorrect;\n    CAPTURE(rotationVector.transpose());\n\n    Vector3d residual = kalmanMeas.getResidual(data->state);\n    CAPTURE(residual.transpose());\n\n    AND_THEN(\"residual directly computed by measurement should be zero, except \"\n             \"for the single axis of rotation, which should be of magnitude \"\n             \"SMALL_VALUE\") {\n        CHECK(residual.isApprox(rotationVector));\n    }\n\n    CAPTURE(inProgress.deltaz);\n    AND_THEN(\"computed deltaz should equal residual\") {\n        CHECK(residual.isApprox(inProgress.deltaz));\n    }\n\n    AND_THEN(\"delta z (residual/propagated mean residual) should be \"\n             \"approximately 0, except for the single axis of rotation, which \"\n             \"should be magnitude SMALL_VALUE\") {\n        REQUIRE(inProgress.deltaz[0] ==\n                Approx(rotationVector[0]).margin(0.0001));\n        REQUIRE(inProgress.deltaz[1] ==\n                Approx(rotationVector[1]).margin(0.0001));\n        REQUIRE(inProgress.deltaz[2] ==\n                Approx(rotationVector[2]).margin(0.0001));\n    }\n\n    CAPTURE(inProgress.stateCorrection.transpose());\n    REQUIRE(inProgress.stateCorrectionFinite);\n    AND_THEN(\"state correction should have a rotation component with small \"\n             \"absolute element (sign matching rotation vector) corresponding \"\n             \"to rotation axis\") {\n        for (std::size_t i = 0; i < 3; ++i) {\n            const auto stateIndex = i + 3;\n            CAPTURE(stateIndex);\n            if (static_cast<std::size_t>(rotationAxis) == i) {\n                /// This is our rotation axis - correction should be in (0,\n                /// SMALL_VALUE)\n                REQUIRE((signCorrect * inProgress.stateCorrection[stateIndex]) >\n                        0);\n                REQUIRE((signCorrect * inProgress.stateCorrection[stateIndex]) <\n                        SMALL_VALUE);\n            } else {\n                /// Not our rotation axis, correction should be approx 0.\n                REQUIRE(inProgress.stateCorrection[stateIndex] ==\n                        Approx(0.).margin(0.0001));\n            }\n        }\n    }\n\n    AND_THEN(\"state correction should have an angular velocity component \"\n             \"with zero or small abs (sign matching rotation) corresponding to \"\n             \"rotation axis\") {\n\n        for (std::size_t i = 0; i < 3; ++i) {\n            const auto stateIndex = i + 9;\n            CAPTURE(stateIndex);\n            if (static_cast<std::size_t>(rotationAxis) == i) {\n                /// This is our rotation axis - correction should be >= 0 if\n                /// positive rotation.\n                REQUIRE(signCorrect * inProgress.stateCorrection[stateIndex] >=\n                        0.);\n            } else {\n                /// Not our rotation axis, correction should be approx 0.\n                REQUIRE(inProgress.stateCorrection[stateIndex] ==\n                        Approx(0.).margin(0.0001));\n            }\n        }\n    }\n    AND_THEN(\"state correction should not contain any translational/linear \"\n             \"velocity components\") {\n        REQUIRE(inProgress.stateCorrection.template head<3>().isZero());\n        REQUIRE(inProgress.stateCorrection.template segment<3>(6).isZero());\n    }\n    AND_WHEN(\"the correction is applied\") {\n        auto errorCovarianceCorrectionWasFinite = inProgress.finishCorrection();\n        THEN(\"the new error covariance should be finite\") {\n            REQUIRE(errorCovarianceCorrectionWasFinite);\n            AND_THEN(\"State error should have decreased\") {\n                REQUIRE((data->state.errorCovariance().array() <=\n                         data->originalStateError.array())\n                            .all());\n            }\n            thenCheckCovariance(data->state.errorCovariance());\n        }\n    }\n}\n\ntemplate <typename MeasurementType>\ninline void\nunscentedSmallSingleAxisChecks(TestData *data, MeasurementType &kalmanMeas,\n                               Axis rotationAxis, bool positive = true) {\n    const auto params = flexkalman::SigmaPointParameters();\n    auto inProgress =\n        flexkalman::beginUnscentedCorrection(data->state, kalmanMeas, params);\n\n    andThenCheckSigmaPointGenerator(inProgress.sigmaPoints);\n    AND_THEN(\"transformed sigma points should not all equal 0\") {\n        CAPTURE(inProgress.transformedPoints.transpose());\n        REQUIRE_FALSE(inProgress.transformedPoints.isZero());\n    }\n    checkSigmaPoints(inProgress.transformedPoints);\n    andThenCheckReconstruction(inProgress.reconstruction);\n\n    commonSmallSingleAxisChecks(data, kalmanMeas, inProgress, rotationAxis,\n                                positive);\n}\n\ntemplate <typename MeasurementType>\ninline void checkEffectiveIdentityMeasurement(TestData *data,\n                                              MeasurementType &kalmanMeas) {\n    AND_THEN(\"residual should be zero\") {\n        CAPTURE(kalmanMeas.getResidual(data->state));\n        REQUIRE(kalmanMeas.getResidual(data->state).isZero());\n    }\n    auto inProgress =\n        flexkalman::beginUnscentedCorrection(data->state, kalmanMeas);\n\n    andThenCheckSigmaPointGenerator(inProgress.sigmaPoints);\n    AND_THEN(\"transformed sigma points should not all equal 0\") {\n        REQUIRE_FALSE(inProgress.transformedPoints.isZero());\n    }\n    checkSigmaPoints(inProgress.transformedPoints);\n\n    auto &recon = inProgress.reconstruction;\n    AND_THEN(\"propagated predicted measurement mean should be zero\") {\n        CAPTURE(recon.getMean().transpose());\n        REQUIRE(recon.getMean().isZero());\n    }\n    AND_THEN(\"state correction should be finite - specifically, zero\") {\n        CAPTURE(inProgress.stateCorrection.transpose());\n        REQUIRE(inProgress.stateCorrection.array().allFinite());\n        REQUIRE(inProgress.stateCorrection.isZero());\n    }\n\n    const Quaterniond origQuat = data->state.getQuaternion();\n    AND_WHEN(\"the correction is applied\") {\n        inProgress.finishCorrection();\n        THEN(\"state should be unchanged\") {\n            CAPTURE(data->state.stateVector().transpose());\n            REQUIRE(data->state.stateVector().isZero());\n            CAPTURE(origQuat);\n            CAPTURE(data->state.getQuaternion());\n            REQUIRE(data->state.getQuaternion().coeffs().isApprox(\n                origQuat.coeffs()));\n        }\n        THEN(\"State error should have decreased\") {\n            REQUIRE((data->state.errorCovariance().array() <=\n                     data->originalStateError.array())\n                        .all());\n        }\n    }\n}\n\ntemplate <typename F, typename... Args>\ninline void allSmallSingleAxisRotations(F &&f, Args &&... args) {\n    WHEN(\"filtering in a small positive rotation about x\") {\n        std::forward<F>(f)(std::forward<Args>(args)..., Axis::X, true);\n    }\n\n    WHEN(\"filtering in a small positive rotation about y\") {\n        std::forward<F>(f)(std::forward<Args>(args)..., Axis::Y, true);\n    }\n\n    WHEN(\"filtering in a small positive rotation about z\") {\n        std::forward<F>(f)(std::forward<Args>(args)..., Axis::Z, true);\n    }\n\n    WHEN(\"filtering in a small negative rotation about x\") {\n        std::forward<F>(f)(std::forward<Args>(args)..., Axis::X, false);\n    }\n    WHEN(\"filtering in a small negative rotation about y\") {\n        std::forward<F>(f)(std::forward<Args>(args)..., Axis::Y, false);\n    }\n\n    WHEN(\"filtering in a small negative rotation about z\") {\n        std::forward<F>(f)(std::forward<Args>(args)..., Axis::Z, false);\n    }\n}\n\n#if 0\nCATCH_TYPELIST_DESCRIBED_TESTCASE(\n    \"unscented with identity calibration output\", \"[ukf]\",\n    /*flexkalman::QFirst, flexkalman::QLast,*/ flexkalman::SplitQ) {\n\n#endif\nTEST_CASE(\"unscented with identity calibration output\", \"[ukf]\") {\n    Catch::StringMaker<float>::precision = 15;\n    Catch::StringMaker<double>::precision = 35;\n    using TypeParam = flexkalman::SplitQ;\n\n    const auto params = flexkalman::SigmaPointParameters();\n    using MeasurementType = OrientationMeasurementUsingPolicy<TypeParam>;\n    // using MeasurementType = TypeParam;\n    unique_ptr<TestData> data(new TestData);\n    GIVEN(\"an identity state\") {\n        WHEN(\"filtering in an identity measurement\") {\n            Quaterniond xformedMeas = data->xform(Quaterniond::Identity());\n\n            THEN(\"the transformed measurement should equal the \"\n                 \"measurement\") {\n                CAPTURE(xformedMeas);\n                REQUIRE(xformedMeas.isApprox(Quaterniond::Identity()));\n\n                MeasurementType kalmanMeas{xformedMeas, data->imuVariance};\n                checkEffectiveIdentityMeasurement(data.get(), kalmanMeas);\n            }\n        }\n        allSmallSingleAxisRotations([&](Axis rotationAxis, bool positive) {\n            const double signCorrect = getSignCorrect(positive);\n            auto radians = signCorrect * SMALL_VALUE;\n            CAPTURE(radians);\n            auto axisVec = Vec3dUnit(rotationAxis);\n            CAPTURE(axisVec.transpose());\n            Quaterniond smallRotation =\n                Quaterniond(AngleAxisd(radians, axisVec));\n\n            CAPTURE(smallRotation);\n            Quaterniond xformedMeas = data->xform(smallRotation);\n            CAPTURE(xformedMeas);\n\n            THEN(\"the transformed measurement should equal the \"\n                 \"measurement\") {\n                REQUIRE(xformedMeas.isApprox(smallRotation));\n                /// Do the rest of the checks for a small rotation about y\n                MeasurementType kalmanMeas{xformedMeas, data->imuVariance};\n                unscentedSmallSingleAxisChecks(data.get(), kalmanMeas,\n                                               rotationAxis, positive);\n            }\n        });\n    }\n\n    auto runIncrementalSmallRotChecksNonIdentityState = [&](Axis rotationAxis,\n                                                            bool positive) {\n        const double signCorrect = getSignCorrect(positive);\n        auto radians = signCorrect * SMALL_VALUE;\n        CAPTURE(radians);\n        auto axisVec = Vec3dUnit(rotationAxis);\n        CAPTURE(axisVec.transpose());\n        Quaterniond smallRotation = Quaterniond(AngleAxisd(radians, axisVec)) *\n                                    data->state.getQuaternion();\n\n        CAPTURE(smallRotation);\n        Quaterniond xformedMeas = data->xform(smallRotation);\n        CAPTURE(xformedMeas);\n\n        THEN(\"the transformed measurement should equal the \"\n             \"measurement\") {\n            REQUIRE(xformedMeas.isApprox(smallRotation));\n            /// Do the rest of the checks for a small rotation about y\n            MeasurementType kalmanMeas{xformedMeas, data->imuVariance};\n            unscentedSmallSingleAxisChecks(data.get(), kalmanMeas, rotationAxis,\n                                           positive);\n        }\n    };\n    GIVEN(\"a state rotated about y\") {\n        Quaterniond stateRotation(AngleAxisd(EIGEN_PI / 4., Vector3d::UnitY()));\n        data->state.setQuaternion(stateRotation);\n        allSmallSingleAxisRotations(\n            runIncrementalSmallRotChecksNonIdentityState);\n    }\n    GIVEN(\"a state rotated about x\") {\n        Quaterniond stateRotation(AngleAxisd(EIGEN_PI / 4., Vector3d::UnitX()));\n        data->state.setQuaternion(stateRotation);\n        allSmallSingleAxisRotations(\n            runIncrementalSmallRotChecksNonIdentityState);\n    }\n}\n\nTEST_CASE(\"unscented with small x rotation calibration output\", \"[ukf]\") {\n    Catch::StringMaker<float>::precision = 15;\n    Catch::StringMaker<double>::precision = 35;\n    using MeasurementType =\n        OrientationMeasurementUsingPolicy<flexkalman::SplitQ>;\n    unique_ptr<TestData> data(new TestData);\n    CAPTURE(SMALL_VALUE);\n    data->roomToCameraRotation =\n        Quaterniond(AngleAxisd(SMALL_VALUE, Vector3d::UnitX()));\n    CAPTURE(data->roomToCameraRotation);\n    INFO(\"This calibration value means that the camera is rotated negative \"\n         \"about its x wrt. the IMU/room\");\n    INFO(\"Equivalently, that quaternion calibration value takes \"\n         \"points/orientations in room space and moves them to camera space\");\n    GIVEN(\"an identity state in camera space\") {\n        CAPTURE(data->state.getQuaternion());\n        WHEN(\"filtering in a measurement that's the inverse of the room to \"\n             \"camera rotation (a measurement matching state)\") {\n            Quaterniond meas = data->roomToCameraRotation.inverse();\n            CAPTURE(meas);\n            Quaterniond xformedMeas = data->xform(meas);\n\n            THEN(\"the transformed measurement should be approximately the \"\n                 \"identity\") {\n                CAPTURE(xformedMeas);\n                REQUIRE(xformedMeas.isApprox(Quaterniond::Identity()));\n\n                MeasurementType kalmanMeas{xformedMeas, data->imuVariance};\n                checkEffectiveIdentityMeasurement(data.get(), kalmanMeas);\n            }\n        }\n    }\n    GIVEN(\"an identity state in room space\") {\n        data->state.setQuaternion(data->roomToCameraRotation);\n        CAPTURE(data->state.getQuaternion());\n        WHEN(\"filtering in an identity measurement (a measurement matching \"\n             \"state)\") {\n            Quaterniond xformedMeas = data->xform(Quaterniond::Identity());\n\n            THEN(\"the transformed measurement should be approximately the \"\n                 \"room to camera rotation\") {\n                CAPTURE(xformedMeas);\n                REQUIRE(xformedMeas.isApprox(data->roomToCameraRotation));\n\n                MeasurementType kalmanMeas{xformedMeas, data->imuVariance};\n                checkEffectiveIdentityMeasurement(data.get(), kalmanMeas);\n            }\n        }\n        allSmallSingleAxisRotations([&](Axis rotationAxis, bool positive) {\n            const double signCorrect = getSignCorrect(positive);\n            auto radians = signCorrect * SMALL_VALUE;\n            CAPTURE(radians);\n            auto axisVec = Vec3dUnit(rotationAxis);\n            CAPTURE(axisVec.transpose());\n            Quaterniond smallRelRotationInCameraSpace =\n                Quaterniond(AngleAxisd(radians, axisVec)) *\n                data->state.getQuaternion();\n            CAPTURE(smallRelRotationInCameraSpace);\n            Quaterniond smallRotation = data->roomToCameraRotation.inverse() *\n                                        smallRelRotationInCameraSpace;\n            CAPTURE(smallRotation);\n            THEN(\"the transformed measurement should equal the original \"\n                 \"measurement as computed in camera space\") {\n                Quaterniond xformedMeas = data->xform(smallRotation);\n                CAPTURE(xformedMeas);\n                REQUIRE(xformedMeas.isApprox(smallRelRotationInCameraSpace));\n\n                /// Do the rest of the checks for a small rotation about a\n                /// single axis\n                MeasurementType kalmanMeas{xformedMeas, data->imuVariance};\n                CAPTURE(kalmanMeas.getResidual(data->state));\n                unscentedSmallSingleAxisChecks(data.get(), kalmanMeas,\n                                               rotationAxis, positive);\n            }\n        });\n    }\n}\n\nTEST_CASE(\"conceptual transformation orders\") {\n    Catch::StringMaker<float>::precision = 15;\n    Catch::StringMaker<double>::precision = 35;\n    Quaterniond positiveX(AngleAxisd(0.5, Vector3d::UnitX()));\n    Quaterniond positiveY(AngleAxisd(0.5, Vector3d::UnitY()));\n    Vector3d yVec = Vector3d::UnitY();\n    SECTION(\n        \"Quaternion composition/multiplication order matches \"\n        \"transformation order (transformation and quat mult are associative)\") {\n        CAPTURE((positiveX * (positiveY * yVec)).transpose());\n        CAPTURE(((positiveX * positiveY) * yVec).transpose());\n        REQUIRE((positiveX * (positiveY * yVec))\n                    .isApprox((positiveX * positiveY) * yVec));\n    }\n    SECTION(\"Behavior of rotations\") {\n        INFO(\"positive X is a transformation taking points from a coordinate \"\n             \"system pitched up, to a level coordinate system.\");\n        CAPTURE((positiveX * yVec).transpose());\n        REQUIRE((positiveX * yVec).z() > 0.);\n    }\n}\n", "meta": {"hexsha": "982fe6a172cb12329a7134f8509bcb943b5530c0", "size": 23275, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/cplusplus/unifiedvideoinertial/TestIMU_UKF.cpp", "max_stars_repo_name": "rpavlik/UVBI-and-KalmanFramework-Standalone", "max_stars_repo_head_hexsha": "2276a2f921f91814a03dee6d9abe0305c6abf37a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-06-08T13:33:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T05:12:29.000Z", "max_issues_repo_path": "tests/cplusplus/unifiedvideoinertial/TestIMU_UKF.cpp", "max_issues_repo_name": "rpavlik/UVBI-and-KalmanFramework-Standalone", "max_issues_repo_head_hexsha": "2276a2f921f91814a03dee6d9abe0305c6abf37a", "max_issues_repo_licenses": ["Apache-2.0"], "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/cplusplus/unifiedvideoinertial/TestIMU_UKF.cpp", "max_forks_repo_name": "rpavlik/UVBI-and-KalmanFramework-Standalone", "max_forks_repo_head_hexsha": "2276a2f921f91814a03dee6d9abe0305c6abf37a", "max_forks_repo_licenses": ["Apache-2.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.9914089347, "max_line_length": 80, "alphanum_fraction": 0.6235445757, "num_tokens": 5063, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.4923497058007778}}
{"text": "#include <boost/random.hpp>\n\n#include \"math_functions.hpp\"\n#include <cmath>\n\nnamespace pwalk {\n\n// Define random number generator type\ntypedef boost::mt19937 rng_t;\n\ntemplate <typename Dtype>\nvoid sample_gaussian(const int n, const Dtype a,\n                        const Dtype sigma, Eigen::Matrix<Dtype, Eigen::Dynamic, 1>& r) {\n  static rng_t gen(1234567);\n  static boost::normal_distribution<Dtype> random_distribution(a, sigma);\n  static boost::variate_generator<rng_t&, boost::normal_distribution<Dtype> >\n      variate_generator(gen, random_distribution);\n\n  for (int i = 0; i < n; ++i) {\n    r[i] = variate_generator();\n  }\n}\n\ntemplate <typename Dtype>\nDtype rng_uniform(const Dtype a, const Dtype b) {\n  static rng_t gen(1234567);\n  static boost::uniform_real<Dtype> random_distribution(a, b);\n  static boost::variate_generator<rng_t&, boost::uniform_real<Dtype> >\n      variate_generator(gen, random_distribution);\n\n  return variate_generator();\n}\n\ntemplate <typename Dtype>\nDtype gaussian_density(const Eigen::Matrix<Dtype, Eigen::Dynamic, 1>& x, const Eigen::Matrix<Dtype, Eigen::Dynamic, 1>& mu, const Eigen::Matrix<Dtype, Eigen::Dynamic, Eigen::Dynamic>& sqrt_cov) {\n  Eigen::Matrix<Dtype, Eigen::Dynamic, 1> c = sqrt_cov * (x - mu);\n  return std::exp(-0.5*c.dot(c)) * sqrt_cov.determinant();\n}\n\ntemplate\nvoid sample_gaussian<float>(const int n, const float mu,\n                               const float sigma, Eigen::Matrix<float, Eigen::Dynamic, 1>& r);\n\ntemplate\nvoid sample_gaussian<double>(const int n, const double mu,\n                                const double sigma, Eigen::Matrix<double, Eigen::Dynamic, 1>& r);\n\n\ntemplate\nfloat rng_uniform<float>(const float a, const float b);\n\ntemplate\ndouble rng_uniform<double>(const double a, const double b);\n\n\ntemplate\nfloat gaussian_density(const Eigen::Matrix<float, Eigen::Dynamic, 1>& x, const Eigen::Matrix<float, Eigen::Dynamic, 1>& mu, const Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic>& sqrt_inv_cov);\n\n\ntemplate\ndouble gaussian_density(const Eigen::Matrix<double, Eigen::Dynamic, 1>& x, const Eigen::Matrix<double, Eigen::Dynamic, 1>& mu, const Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>& sqrt_inv_cov);\n\n} // namespace pwalk\n", "meta": {"hexsha": "357a11e710c622a00ab66c46cdbd149df29f9c5a", "size": 2220, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "polytopewalk/src/util/math_functions.cpp", "max_stars_repo_name": "yuachen/polytopewalk", "max_stars_repo_head_hexsha": "7e7431594489b5d5b6fe9947b4ccab21eee11152", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2018-11-16T19:35:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T01:02:56.000Z", "max_issues_repo_path": "polytopewalk/src/util/math_functions.cpp", "max_issues_repo_name": "yuachen/polytopewalk", "max_issues_repo_head_hexsha": "7e7431594489b5d5b6fe9947b4ccab21eee11152", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-10-06T11:15:29.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-06T11:15:29.000Z", "max_forks_repo_path": "polytopewalk/src/util/math_functions.cpp", "max_forks_repo_name": "yuachen/polytopewalk", "max_forks_repo_head_hexsha": "7e7431594489b5d5b6fe9947b4ccab21eee11152", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-06-16T18:11:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-12T23:13:27.000Z", "avg_line_length": 34.6875, "max_line_length": 202, "alphanum_fraction": 0.7081081081, "num_tokens": 551, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.6334102567576901, "lm_q1q2_score": 0.49234970464437805}}
{"text": "/*\n@copyright Louis Dionne 2014\nDistributed under the Boost Software License, Version 1.0.\n(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n */\n\n#include <boost/hana/detail/assert.hpp>\n#include <boost/hana/ext/std/integral_constant.hpp>\n#include <boost/hana/functional.hpp>\n#include <boost/hana/integer_list.hpp>\n#include <boost/hana/integral.hpp>\nusing namespace boost::hana;\nusing namespace literals;\n\n\nint main() {\n    //! [main]\n    BOOST_HANA_CONSTANT_ASSERT(\n        take_until(_ < 2_c, integer_list<int, 3, 2, 1, 0>) == integer_list<int, 3, 2>\n    );\n    //! [main]\n}\n", "meta": {"hexsha": "7456eb719d69c451668cf385c6637daf1af057fc", "size": 605, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/list/take_until.cpp", "max_stars_repo_name": "rbock/hana", "max_stars_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-05-07T14:29:13.000Z", "max_stars_repo_stars_event_max_datetime": "2015-07-04T10:59:46.000Z", "max_issues_repo_path": "example/list/take_until.cpp", "max_issues_repo_name": "rbock/hana", "max_issues_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/list/take_until.cpp", "max_forks_repo_name": "rbock/hana", "max_forks_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.3043478261, "max_line_length": 85, "alphanum_fraction": 0.7107438017, "num_tokens": 164, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7772998508568416, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.49234970348797785}}
{"text": "/* ScaFES\n * Copyright (c) 2018, ZIH, TU Dresden, Federal Republic of Germany.\n * For details, see the files COPYING and LICENSE in the base directory\n * of the package.\n */\n\n/**\n *  @file MRIDataPBHEqnFDM.hpp\n *\n *  @brief Implementation of a n-dimensional Pennes bioheat equation problem\n *         with data from MRI.\n */\n\n#include <iostream>\n#include \"ScaFES.hpp\"\n\n#include <boost/property_tree/ini_parser.hpp>\n\n/******************************************************************************\n *****************************************************************************/\n/**\n * \\class MRIDataPBHEqnFDM\n *  @brief Class for discretized Pennes bioheat equation problem.\n *\n*/\ntemplate<typename CT, std::size_t DIM>\nclass MRIDataPBHEqnFDM : public ScaFES::Problem<MRIDataPBHEqnFDM<CT,DIM>, CT, DIM> {\n  private:\n    /** Parser for ini files. */\n    using PTree = boost::property_tree::ptree;\n    const PTree ptree;\n\n  public:\n    /** constant h. Ambient convetion. */\n    const CT H; /* W/(m^2 K) */\n\n    /** constant T_amb. Ambient temperature. */\n    const CT T_AMB; /* K */\n\n    /** constant q_bc. Heat flux at surface inside the brain. */\n    const CT Q_BC; /* W/(m^2) */\n\n    /** constant q_skull. Heat flux at upper surface under skull. */\n    const CT Q_SKULL; /* W/(m^2) */\n\n    /** constant epsilon. Emissivity. */\n    const CT EPSILON; /* - */\n\n    /** constant sigma. Stefan\u2013Boltzmann constant. */\n    const CT SIGMA = 5.670373e-8; /* W/(m^2 K^4) */\n\n    /** All fields which are related to the underlying problem\n     * are added in terms of an entry of the parameters of\n     * type \\c std::vector.\n     * @param params Set of ScaFES parameters.\n     * @param gg Global grid.\n     * @param useLeapfrog Should the leap frog scheme be used?\n     * @param nameDatafield Name of the fields.\n     * @param stencilWidth Stencil width of the fields.\n     * @param isKnownDf Is the data field are known or unknown one?\n     * @param ptree_ Config file parser.\n     * @param nLayers Number of layers at the global boundary.\n     * @param defaultValue Default value of fields.\n     * @param writeToFile How often should the data field be written to file.\n     * @param computeError Should the Linf error between the numerical\n     *                     and exact solution be computed?\n     * @param geomparamsInit Initial guess of geometrical parameters.\n     * @param checkConvergence Should convergence be checked?\n     */\n    MRIDataPBHEqnFDM(ScaFES::Parameters const& params,\n                     ScaFES::GridGlobal<DIM> const& gg,\n                     bool useLeapfrog,\n                     std::vector<std::string> const& nameDatafield,\n                     std::vector<int> const& stencilWidth,\n                     std::vector<bool> const& isKnownDf,\n                     PTree const& ptree_,\n                     std::vector<int> const& nLayers = std::vector<int>(),\n                     std::vector<CT> const& defaultValue = std::vector<CT>(),\n                     std::vector<ScaFES::WriteHowOften> const& writeToFile\n                         = std::vector<ScaFES::WriteHowOften>(),\n                     std::vector<bool> const& computeError\n                         = std::vector<bool>(),\n                     std::vector<CT> const& geomparamsInit = std::vector<CT>(),\n                     std::vector<bool> const& checkConvergence\n                         = std::vector<bool>() )\n        : ScaFES::Problem<MRIDataPBHEqnFDM<CT, DIM>, CT, DIM>(params, gg,\n                                                              useLeapfrog,\n                                                              nameDatafield,\n                                                              stencilWidth,\n                                                              isKnownDf,\n                                                              nLayers,\n                                                              defaultValue,\n                                                              writeToFile,\n                                                              computeError,\n                                                              geomparamsInit,\n                                                              checkConvergence),\n        ptree(ptree_),\n        H(ptree.get<CT>(\"Parameters.H\")),\n        T_AMB(ptree.get<CT>(\"Parameters.T_INF\")),\n        Q_BC(ptree.get<CT>(\"Parameters.Q_BC\")),\n        Q_SKULL(ptree.get<CT>(\"Parameters.Q_SKULL\")),\n        EPSILON(ptree.get<CT>(\"Parameters.EPSILON\"))\n        { }\n\n    /** Evaluates all fields at one given global inner grid node.\n     */\n    void evalInner(std::vector< ScaFES::DataField<CT, DIM> >& /*vNew*/,\n                   ScaFES::Ntuple<int,DIM> const& /*idxNode*/,\n                   int const& /*timestep*/) {\n    }\n\n    /** Evaluates all fields at one given global border grid node.\n     */\n    void evalBorder(std::vector< ScaFES::DataField<CT, DIM> >& /*vNew*/,\n                    ScaFES::Ntuple<int,DIM> const& /*idxNode*/,\n                    int const& /*timestep*/) {\n    }\n\n    /** Initializes all unknown fields at one given global inner grid node.\n     */\n    template<typename TT>\n    void initInner(std::vector< ScaFES::DataField<TT, DIM> >& /*vNew*/,\n                   std::vector<TT> const& /*vOld*/,\n                   ScaFES::Ntuple<int,DIM> const& /*idxNode*/,\n                   int const& /*timestep*/) {\n    }\n\n    /** Initializes all unknown fields at one given global border grid node.\n     */\n    template<typename TT>\n    void initBorder(std::vector< ScaFES::DataField<TT, DIM> >& /*vNew*/,\n                   std::vector<TT> const& /*vOld*/,\n                   ScaFES::Ntuple<int,DIM> const& /*idxNode*/,\n                   int const& /*timestep*/) {\n    }\n\n    /** Updates all unknown fields at one given global inner grid node.\n     *  @param vNew Set of all unknown fields at new time step (return value).\n     *  @param vOld Set of all unknown fields at old time step.\n     *  @param idxNode Index of given grid node.\n     */\n    template<typename TT>\n    void updateInner(std::vector<ScaFES::DataField<TT,DIM>>& vNew,\n                     std::vector<ScaFES::DataField<TT,DIM>> const& vOld,\n                     ScaFES::Ntuple<int,DIM> const& idxNode,\n                     int const& /*timestep*/) {\n        CT rho = this->knownDf(0, idxNode);\n        CT c = this->knownDf(1, idxNode);\n        CT k = this->knownDf(2, idxNode);\n        CT rho_blood = this->knownDf(3, idxNode);\n        CT c_blood = this->knownDf(4, idxNode);\n        CT omega = this->knownDf(5, idxNode);\n        CT T_blood = this->knownDf(6, idxNode);\n        CT q = this->knownDf(7, idxNode);\n\n        /* Discrete Pennes Bioheat Equation for updating inner nodes. */\n        vNew[0](idxNode) = vOld[0](idxNode);\n        for (std::size_t pp = 0; pp < DIM; ++pp) {\n            vNew[0](idxNode) += this->tau() * (k/(rho*c))\n                                * (vOld[0](this->connect(idxNode, 2*pp))\n                                   + vOld[0](this->connect(idxNode, 2*pp+1))\n                                   - 2.0 * vOld[0](idxNode))\n                                / (this->gridsize(pp) * this->gridsize(pp));\n        }\n        vNew[0](idxNode) += this->tau() * ((rho_blood*c_blood)/(rho*c)) * omega\n                            * (T_blood - vOld[0](idxNode));\n        vNew[0](idxNode) += this->tau() * (1.0/(rho*c)) * q;\n    }\n\n    /** Updates all unknown fields at one given global border grid node.\n     *  @param vNew Set of all unknown fields at new time step (return value).\n     *  @param vOld Set of all unknown fields at old time step.\n     *  @param idxNode Index of given grid node.\n     */\n    template<typename TT>\n    void updateBorder(std::vector<ScaFES::DataField<TT,DIM>>& vNew,\n                      std::vector<ScaFES::DataField<TT,DIM>>const& vOld,\n                      ScaFES::Ntuple<int,DIM> const& idxNode,\n                      int const& /*timestep*/) {\n        CT rho = this->knownDf(0, idxNode);\n        CT c = this->knownDf(1, idxNode);\n        CT k = this->knownDf(2, idxNode);\n        CT rho_blood = this->knownDf(3, idxNode);\n        CT c_blood = this->knownDf(4, idxNode);\n        CT omega = this->knownDf(5, idxNode);\n        CT T_blood = this->knownDf(6, idxNode);\n        CT q = this->knownDf(7, idxNode);\n        int trepanationArea = this->knownDf(8, idxNode);\n\n        /* Discrete Pennes Bioheat Equation with boundary conditions. */\n        vNew[0](idxNode) = vOld[0](idxNode);\n        for (std::size_t pp = 0; pp < DIM; ++pp) {\n            if (idxNode.elem(pp) == (this->nNodes(pp)-1)) {\n            /* vOld[0](this->connect(idxNode, 2*pp+1) needs to be replaced. */\n                if (pp == (DIM-1)) {\n                /* Last node/edge/surface in highest dimension will be brain surface. */\n                    if (trepanationArea == 1) {\n                    /* Open skull: Cauchy boundary condition and\n                     * thermal radiation boundary condition. */\n                        CT tempOld = vNew[0](idxNode) + 273.15;\n                        CT tempOldPow4 = tempOld * tempOld * tempOld * tempOld;\n                        CT tempAmb = T_AMB + 273.15;\n                        CT tempAmbPow4 = tempAmb * tempAmb * tempAmb * tempAmb;\n\n                        vNew[0](idxNode) += this->tau() * (k/(rho*c))\n                                            * (vOld[0](this->connect(idxNode, 2*pp))\n                                            /* vOld[0](this->connect(idxNode, 2*pp+1)\n                                             * is replaced by                         */\n                                               + vOld[0](this->connect(idxNode, 2*pp))\n                                               - ((2.0*this->gridsize(pp)/k)\n                                                  * H * (vOld[0](idxNode) - T_AMB))\n                                               - ((2.0*this->gridsize(pp)/k)\n                                                  * EPSILON * SIGMA\n                                                  * (tempOldPow4 - tempAmbPow4))\n                                            /********************************************/\n                                               - 2.0 * vOld[0](idxNode))\n                                            / (this->gridsize(pp) * this->gridsize(pp));\n                    } else {\n                    /* Closed skull: Neumann boundary condition. */\n                        vNew[0](idxNode) += this->tau() * (k/(rho*c))\n                                            * (vOld[0](this->connect(idxNode, 2*pp))\n                                            /* vOld[0](this->connect(idxNode, 2*pp+1))\n                                               is replaced by                          */\n                                               + vOld[0](this->connect(idxNode, 2*pp))\n                                               - ((2.0*this->gridsize(pp)/k)\n                                                  * (-1.0 * Q_SKULL))\n                                            /*********************************************/\n                                               - 2.0 * vOld[0](idxNode))\n                                            / (this->gridsize(pp) * this->gridsize(pp));\n                    }\n                } else {\n                /* Neumann boundary condition. */\n                    vNew[0](idxNode) += this->tau() * (k/(rho*c))\n                                        * (vOld[0](this->connect(idxNode, 2*pp))\n                                        /* vOld[0](this->connect(idxNode, 2*pp+1))\n                                           is replaced by                            */\n                                           + vOld[0](this->connect(idxNode, 2*pp))\n                                           - ((2.0*this->gridsize(pp)/k)\n                                              * (-1.0 * Q_BC))\n                                        /*********************************************/\n                                           - 2.0 * vOld[0](idxNode))\n                                        / (this->gridsize(pp) * this->gridsize(pp));\n                }\n            } else if (idxNode.elem(pp) == 0){\n            /* vOld[0](this->connect(idxNode, 2*pp) needs to be replaced.\n             * Neumann boundary condition. */\n                vNew[0](idxNode) += this->tau() * (k/(rho*c))\n                                    /* vOld[0](this->connect(idxNode, 2*pp))\n                                       is replaced by                          */\n                                    * (vOld[0](this->connect(idxNode, 2*pp+1))\n                                       + ((2.0*this->gridsize(pp)/k) * Q_BC)\n                                    /*******************************************/\n                                       + vOld[0](this->connect(idxNode, 2*pp+1))\n                                       - 2.0 * vOld[0](idxNode))\n                                    / (this->gridsize(pp) * this->gridsize(pp));\n            } else {\n            /* No value needs to be replaced.\n             * Use central differencing scheme. */\n                vNew[0](idxNode) += this->tau() * (k/(rho*c))\n                                    * (vOld[0](this->connect(idxNode, 2*pp))\n                                       + vOld[0](this->connect(idxNode, 2*pp+1))\n                                       - 2.0 * vOld[0](idxNode))\n                                    / (this->gridsize(pp) * this->gridsize(pp));\n            }\n        }\n\n        /* These terms are independet of the boundary condition. */\n        vNew[0](idxNode) += this->tau() * ((rho_blood*c_blood)/(rho*c)) * omega\n                            * (T_blood - vOld[0](idxNode));\n        vNew[0](idxNode) += this->tau() * (1.0/(rho*c)) * q;\n    }\n\n    /** Updates (2nd cycle) all unknown fields at one given global inner grid node.\n     *  \\remarks Only important if leap frog scheme is used.\n     */\n    template<typename TT>\n    void updateInner2(std::vector<ScaFES::DataField<TT,DIM>>&,\n                      std::vector<ScaFES::DataField<TT,DIM>> const&,\n                      ScaFES::Ntuple<int,DIM> const&,\n                      int const&) { }\n\n    /** Updates (2nd cycle) all unknown fields at one given global border\n     *  grid node.\n     *  \\remarks Only important if leap frog scheme is used.\n     */\n    template<typename TT>\n    void updateBorder2(std::vector<ScaFES::DataField<TT,DIM>>&,\n                       std::vector<ScaFES::DataField<TT,DIM>>const&,\n                       ScaFES::Ntuple<int,DIM> const&,\n                       int const&) { }\n};\n", "meta": {"hexsha": "75637507f9c71219eef1932b8afcaaa20119b165", "size": 14574, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "examples/MRIDataPBHEqnFDM/MRIDataPBHEqnFDM.hpp", "max_stars_repo_name": "nih23/MRIDrivenHeatSimulation", "max_stars_repo_head_hexsha": "de6d16853df1faf44c700d1fc06584351bf6c816", "max_stars_repo_licenses": ["BSL-1.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": "examples/MRIDataPBHEqnFDM/MRIDataPBHEqnFDM.hpp", "max_issues_repo_name": "nih23/MRIDrivenHeatSimulation", "max_issues_repo_head_hexsha": "de6d16853df1faf44c700d1fc06584351bf6c816", "max_issues_repo_licenses": ["BSL-1.0", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/MRIDataPBHEqnFDM/MRIDataPBHEqnFDM.hpp", "max_forks_repo_name": "nih23/MRIDrivenHeatSimulation", "max_forks_repo_head_hexsha": "de6d16853df1faf44c700d1fc06584351bf6c816", "max_forks_repo_licenses": ["BSL-1.0", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.9109589041, "max_line_length": 91, "alphanum_fraction": 0.4471661864, "num_tokens": 3370, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998560157663, "lm_q2_score": 0.63341024983754, "lm_q1q2_score": 0.49234969599763045}}
{"text": "#include <bits/stdc++.h>\nusing namespace std;\n\n#ifdef LOCAL\n#include \"/debug.h\"\n#else\n#define db(...)\n#endif\n\n// #include <boost/multiprecision/cpp_int.hpp>\n// using namespace boost::multiprecision;\n\n#define all(v) v.begin(), v.end()\n#define pb push_back\nusing ll = long long;\nconst int NAX = 2e5 + 5, MOD = 1000000007;\n\nvoid solveCase()\n{\n    int n, k;\n    n = k = 50;\n    cin >> n >> k;\n    // if (n < k)\n    // {\n    //     cout << 0 << '\\n';\n    //     return;\n    // }\n    vector<ll> boxes(n);\n    ll temp = 8;\n    for (auto &x : boxes)\n    {\n        x = temp;\n        temp *= 2;\n        cin >> x;\n    }\n    sort(all(boxes));\n    ll a, b;\n    a = 1e18, b = 1e18;\n    cin >> a >> b;\n    auto ncr = [](int n, int r) -> ll {\n        if (r > n || n < 0 || r < 0)\n            return 0;\n        __int128_t num = 1, den = 1;\n        r = min(r, n - r);\n        for (int i = 1; i <= r; i++)\n        {\n            num *= n - r + i;\n            num /= i;\n        }\n        db(n, r, (long long)num);\n        assert(num <= LLONG_MAX);\n        return num;\n    };\n    // db(ncr(50, 25));\n    set<int> ss;\n    function<ll(ll, int, int)> ways = [&](ll target, int boxcount, int rptr) -> ll {\n        if (boxcount == 0)\n            return 1;\n        if (boxcount < 0 || target < 0 || target < boxes[0])\n            return 0;\n        int i = 0;\n        for (; i < rptr; i++)\n            if (target < boxes[i])\n                break;\n        auto dontchose = ncr(i - 1, boxcount);\n        auto chose = 0LL;\n        if (ss.count(i) == 0)\n        {\n            ss.insert(i);\n            chose = ways(target - boxes[i - 1], boxcount - 1, i);\n        }\n        db(i, rptr, target, boxcount, dontchose, chose);\n        return chose + dontchose;\n    };\n    db(boxes);\n    auto one = ways(b, k, n);\n    ss.clear();\n    one -= ways(a - 1, k, n);\n    cout << one << '\\n';\n}\n\nint32_t main()\n{\n#ifndef LOCAL\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n#endif\n    int t = 1;\n    // cin >> t;\n    for (int i = 1; i <= t; ++i)\n        solveCase();\n    return 0;\n}", "meta": {"hexsha": "94138fde8e6f22265b37e9f8a52fa478c698ad7e", "size": 2040, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ICPC_Mirrors/Nitc_21/h.cpp", "max_stars_repo_name": "Shahraaz/CP_P_S5", "max_stars_repo_head_hexsha": "b068ad02d34338337e549d92a14e3b3d9e8df712", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ICPC_Mirrors/Nitc_21/h.cpp", "max_issues_repo_name": "Shahraaz/CP_P_S5", "max_issues_repo_head_hexsha": "b068ad02d34338337e549d92a14e3b3d9e8df712", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ICPC_Mirrors/Nitc_21/h.cpp", "max_forks_repo_name": "Shahraaz/CP_P_S5", "max_forks_repo_head_hexsha": "b068ad02d34338337e549d92a14e3b3d9e8df712", "max_forks_repo_licenses": ["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.935483871, "max_line_length": 84, "alphanum_fraction": 0.443627451, "num_tokens": 652, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324983301568, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4923448576295258}}
{"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_LAPACK_HPP\n#define BOOST_NUMERIC_BINDINGS_LAPACK_LAPACK_HPP\n\n// linear systems\n\n#include <boost/numeric/bindings/lapack/gesv.hpp>\n#include <boost/numeric/bindings/lapack/posv.hpp>\n#include <boost/numeric/bindings/lapack/ppsv.hpp>\n#include <boost/numeric/bindings/lapack/sysv.hpp>\n#include <boost/numeric/bindings/lapack/spsv.hpp>\n#include <boost/numeric/bindings/lapack/hesv.hpp>\n#include <boost/numeric/bindings/lapack/hpsv.hpp>\n\n// eigenproblems\n\n#include <boost/numeric/bindings/lapack/gees.hpp>\n#include <boost/numeric/bindings/lapack/trevc.hpp>\n#include <boost/numeric/bindings/lapack/trexc.hpp>\n#include <boost/numeric/bindings/lapack/hbev.hpp>\n#include <boost/numeric/bindings/lapack/syev.hpp>\n\n// SVD\n\n#include <boost/numeric/bindings/lapack/gesvd.hpp>\n#include <boost/numeric/bindings/lapack/gesdd.hpp>\n#include <boost/numeric/bindings/lapack/sygv.hpp>\n\n// Miscellaneous\n// QR\n#include <boost/numeric/bindings/lapack/geqrf.hpp>\n#include <boost/numeric/bindings/lapack/ormqr.hpp>\n#include <boost/numeric/bindings/lapack/orgqr.hpp>\n\n\n\n#endif // BOOST_NUMERIC_BINDINGS_LAPACK_LAPACK_HPP\n", "meta": {"hexsha": "0547857d7a014182cbc375aa55a2d41fdf75224f", "size": 1460, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/boost/numeric/bindings/lapack/lapack.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/lapack.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/lapack.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": 29.2, "max_line_length": 67, "alphanum_fraction": 0.7821917808, "num_tokens": 413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4923448522073311}}
{"text": "//  (C) Copyright 2014 Alvaro J. Genial (http://alva.ro)\n//  Use, modification and distribution are subject to the Boost Software License, Version 1.0.\n//  (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt).\n\n#ifndef AJG_SYNTH_DETAIL_IS_INTEGER_HPP_INCLUDED\n#define AJG_SYNTH_DETAIL_IS_INTEGER_HPP_INCLUDED\n\n#include <cmath>\n\n#include <boost/utility/enable_if.hpp>\n#include <boost/type_traits/is_integral.hpp>\n\nnamespace ajg {\nnamespace synth {\nnamespace detail {\n\n//\n// is_integer:\n//     Determines whether a floating-point number is an integer.\n////////////////////////////////////////////////////////////////////////////////////////////////////\n\ntemplate <class T>\ninline typename boost::enable_if<boost::is_integral<T>, bool>::type is_integer(T const) { return true; }\n\ntemplate <class T>\ninline typename boost::disable_if<boost::is_integral<T>, bool>::type is_integer(T const t) {\n    T integral_part;\n    return (std::modf)(t, &integral_part) == static_cast<T>(0.0);\n}\n\n}}} // namespace ajg::synth::detail\n\n#endif // AJG_SYNTH_DETAIL_IS_INTEGER_HPP_INCLUDED\n", "meta": {"hexsha": "a562492fafb7536fe045aa226d2dcbe9defc04fe", "size": 1102, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ajg/synth/detail/is_integer.hpp", "max_stars_repo_name": "legutierr/synth", "max_stars_repo_head_hexsha": "7540072bde2ea9c8258c2dca69d2ed3bd62fb991", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-04-10T14:13:34.000Z", "max_stars_repo_stars_event_max_datetime": "2016-04-10T14:13:34.000Z", "max_issues_repo_path": "ajg/synth/detail/is_integer.hpp", "max_issues_repo_name": "legutierr/synth", "max_issues_repo_head_hexsha": "7540072bde2ea9c8258c2dca69d2ed3bd62fb991", "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": "ajg/synth/detail/is_integer.hpp", "max_forks_repo_name": "legutierr/synth", "max_forks_repo_head_hexsha": "7540072bde2ea9c8258c2dca69d2ed3bd62fb991", "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.4117647059, "max_line_length": 104, "alphanum_fraction": 0.6833030853, "num_tokens": 254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232480373843, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4923448467851363}}
{"text": "<%\ncfg['compiler_args'] = ['-std=c++14','-fopenmp']\ncfg['linker_args'] = ['-fopenmp']\ncfg['include_dirs'] = ['/home/eigen-3.3.7']\nsetup_pybind11(cfg)\n%>\n\n#include <pybind11/pybind11.h>\n#include <pybind11/eigen.h>\n#include <Eigen/SparseCore>\n#include <Eigen/Dense>\n#include <omp.h>\n#define BATCHSIZE 8 \nnamespace py = pybind11;\nusing namespace Eigen;\n\ntypedef SparseMatrix<std::complex<double>>  SpMat; \n\n\nVectorXcd dot(int i, int l, SpMat un, VectorXcd wave, int size)\n{\n py::gil_scoped_acquire acquire; /* Acquire GIL before calling Python code */\n initParallel(); // not required after eigen 3.3 and c++11 compiler\n setNbThreads(8);\n int k;\n int chunk = pow(2, l-2*i); // dimensions of the incoming unitary sparse matrix\n int dim = pow(2, l)/size; \n int split = pow(2, 2*i)/size; // # of splitted wavefunction\n int batch = BATCHSIZE; // specify the batch size for each threads\n VectorXcd temp(dim); // temp vector to keep tract of mat-vec multiplication\n temp = VectorXcd::Zero(dim);\n // paralleling using openmp\n #pragma omp parallel shared(un, wave) private(k)\n {\n // since each mat-vec dot product is totally independent, we can safely parallel the loop \n  #pragma omp for schedule(dynamic,batch)\n  for (k = 0; k < split; k++){\n    temp.segment(k*chunk, chunk) = un * wave.segment(k*chunk, chunk);\n  }\n}\n\n return temp;\n\n}\n// simple implementation without openmp; only for benchmark purpose\nVectorXcd dot_simple(SpMat un, VectorXcd wave)\n{\n return un*wave;\n}\n\n\nPYBIND11_MODULE(eigen_dot, m) {   \n    // Release GIL before calling into C++ code \n    // and also set up the default argument to be one\n    m.def(\"dot\", &dot, py::call_guard<py::gil_scoped_release>());\n    m.def(\"dot_simple\", &dot_simple, py::call_guard<py::gil_scoped_release>());  \n }", "meta": {"hexsha": "4d11c7f8c9412a66eb3a94991735d07f633ab9a2", "size": 1753, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "eigen_dot.cpp", "max_stars_repo_name": "empyriumz/Entanglement-Dynamics", "max_stars_repo_head_hexsha": "433228042517000ae3bf2a5105b36f82272170fa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-04-08T19:10:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T14:54:27.000Z", "max_issues_repo_path": "eigen_dot.cpp", "max_issues_repo_name": "empyriumz/Entanglement-Dynamics", "max_issues_repo_head_hexsha": "433228042517000ae3bf2a5105b36f82272170fa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-05-13T02:25:33.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-19T15:32:47.000Z", "max_forks_repo_path": "eigen_dot.cpp", "max_forks_repo_name": "empyriumz/Entanglement-Dynamics", "max_forks_repo_head_hexsha": "433228042517000ae3bf2a5105b36f82272170fa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-12-02T19:31:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-17T19:13:48.000Z", "avg_line_length": 30.7543859649, "max_line_length": 91, "alphanum_fraction": 0.6993725043, "num_tokens": 494, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324803738429, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4923448467851363}}
{"text": "#ifndef STAN_MATH_PRIM_MAT_PROB_MULTI_NORMAL_RNG_HPP\n#define STAN_MATH_PRIM_MAT_PROB_MULTI_NORMAL_RNG_HPP\n\n#include <stan/math/prim/scal/err/check_finite.hpp>\n#include <stan/math/prim/scal/err/check_positive.hpp>\n#include <stan/math/prim/scal/fun/constants.hpp>\n#include <stan/math/prim/scal/meta/include_summand.hpp>\n#include <stan/math/prim/mat/err/check_pos_definite.hpp>\n#include <stan/math/prim/mat/err/check_symmetric.hpp>\n#include <stan/math/prim/mat/fun/trace_inv_quad_form_ldlt.hpp>\n#include <stan/math/prim/mat/fun/log_determinant_ldlt.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n\nnamespace stan {\n  namespace math {\n\n    /**\n     * Return a pseudo-random vector with a multi-variate normal\n     * distribution given the specified location parameter and\n     * covariance matrix and pseudo-random number generator.\n     *\n     * If calculating more than one multivariate-normal random draw\n     * then it is more efficient to calculate the Cholesky factor of\n     * the covariance matrix and use the function\n     * <code>stan::math::multi_normal_cholesky_rng</code>.\n     *\n     * @tparam RNG Type of pseudo-random number generator.\n     * @param mu Location parameter.\n     * @param S Covariance parameter.\n     * @param rng Pseudo-random number generator.\n     */\n    template <class RNG>\n    inline Eigen::VectorXd\n    multi_normal_rng(const Eigen::VectorXd& mu, const Eigen::MatrixXd& S,\n                     RNG& rng) {\n      using boost::variate_generator;\n      using boost::normal_distribution;\n\n      static const char* function(\"multi_normal_rng\");\n\n      check_positive(function, \"Covariance matrix rows\", S.rows());\n      check_symmetric(function, \"Covariance matrix\", S);\n      check_finite(function, \"Location parameter\", mu);\n\n      Eigen::LLT<Eigen::MatrixXd> llt_of_S = S.llt();\n      check_pos_definite(\"multi_normal_rng\", \"covariance matrix argument\",\n                         llt_of_S);\n\n      variate_generator<RNG&, normal_distribution<> >\n        std_normal_rng(rng, normal_distribution<>(0, 1));\n\n      Eigen::VectorXd z(S.cols());\n      for (int i = 0; i < S.cols(); i++)\n        z(i) = std_normal_rng();\n\n      return mu + llt_of_S.matrixL() * z;\n    }\n\n  }\n}\n#endif\n", "meta": {"hexsha": "b889f97e799dbbf5b45804fb50bbff7fd4633cec", "size": 2259, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/mat/prob/multi_normal_rng.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/prim/mat/prob/multi_normal_rng.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/prim/mat/prob/multi_normal_rng.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.8571428571, "max_line_length": 74, "alphanum_fraction": 0.6998671979, "num_tokens": 538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.6187804407739559, "lm_q1q2_score": 0.4923376758589848}}
{"text": "#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE JPetCachedFunctionTest\n\n#include \"JPetCachedFunction/JPetCachedFunction.h\"\n#include \"JPetLoggerInclude.h\"\n#include <boost/test/unit_test.hpp>\n\nusing namespace jpet_common_tools;\n/// Returns Time-over-threshold for given deposited energy\n/// the current parametrization is par1 + par2 * eDep\n/// Returned value in ps, and eDep is given in keV.\ndouble getToT1(double eDep, double  par1 = -91958., double par2 = 19341.)\n{\n  if (eDep < 0. ) return 0.;\n  double value = par1 + eDep * par2;\n  return value;\n}\n\nBOOST_AUTO_TEST_SUITE(JPetCachedFunctionTestSuite)\n\nBOOST_AUTO_TEST_CASE(getTot_params)\n{\n  JPetCachedFunctionParams params(\"pol1\", { -91958., 19341.});\n  JPetCachedFunction1D func(params, Range(100, 0., 100.));\n  BOOST_CHECK(func.getParams().fValidFunction);\n  BOOST_CHECK_EQUAL(func.getParams().fParams.size(), 2);\n  BOOST_CHECK_EQUAL(func.getParams().fParams[0], -91958.);\n  BOOST_CHECK_EQUAL(func.getParams().fParams[1], 19341.);\n  BOOST_CHECK_EQUAL(func.getValues().size(), 100);\n  auto vals = func.getValues();\n}\n\nBOOST_AUTO_TEST_CASE(getTot_standardFunc)\n{\n  JPetCachedFunctionParams params(\"pol1\", { -91958., 19341.});\n  JPetCachedFunction1D func(params, Range( 10000, 0., 100.));\n  BOOST_CHECK(func.getParams().fValidFunction);\n  BOOST_CHECK_CLOSE(func(0.), getToT1(0.), 0.1);\n  BOOST_CHECK_CLOSE(func(1.), getToT1(1.), 0.1);\n  BOOST_CHECK_CLOSE(func(10.), getToT1(10.), 0.1);\n  BOOST_CHECK_CLOSE(func(59.5), getToT1(59.5), 0.1);\n  BOOST_CHECK_CLOSE(func(99.9), getToT1(99.9), 0.1);\n}\n\nBOOST_AUTO_TEST_CASE(getTot_quadratic)\n{\n  JPetCachedFunctionParams params(\"pol2\", {1., 1., 1.}); /// 1 + x + x^2\n  JPetCachedFunction1D func(params, Range(10000, 0., 100.));\n  BOOST_CHECK(func.getParams().fValidFunction);\n  BOOST_CHECK_CLOSE(func(0), 1., 0.1);\n  BOOST_CHECK_CLOSE(func(1), 3., 0.1);\n  BOOST_CHECK_CLOSE(func(2), 7., 0.1);\n  BOOST_CHECK_CLOSE(func(3), 13., 0.1);\n}\n\nBOOST_AUTO_TEST_CASE(cached_2D)\n{\n  JPetCachedFunctionParams params(\"[0] + [1] * x  + [2] * y\", {1., 1., 2.}); /// 1 + x + 2 * y\n  JPetCachedFunction2D func(params, Range(100, 0., 100.), Range(100, 0., 100.));\n  BOOST_CHECK(func.getParams().fValidFunction);\n  BOOST_CHECK_CLOSE(func(0., 0.), 1., 0.1);\n  BOOST_CHECK_CLOSE(func(1, 1.), 4., 0.1);\n  BOOST_CHECK_CLOSE(func(0., 1.), 3., 0.1);\n  BOOST_CHECK_CLOSE(func(1., 0.), 2., 0.1);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "12899195b07320f4fa913f7dc8253c55c21af00f", "size": 2400, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/Core/JPetCachedFunction/JPetCachedFunctionTest.cpp", "max_stars_repo_name": "kdulski/j-pet-framework", "max_stars_repo_head_hexsha": "f7eeff83828de8e832f044abd3a7b7293dd31444", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-04-08T08:38:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-11T14:19:31.000Z", "max_issues_repo_path": "tests/Core/JPetCachedFunction/JPetCachedFunctionTest.cpp", "max_issues_repo_name": "kdulski/j-pet-framework", "max_issues_repo_head_hexsha": "f7eeff83828de8e832f044abd3a7b7293dd31444", "max_issues_repo_licenses": ["Apache-2.0"], "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/Core/JPetCachedFunction/JPetCachedFunctionTest.cpp", "max_forks_repo_name": "kdulski/j-pet-framework", "max_forks_repo_head_hexsha": "f7eeff83828de8e832f044abd3a7b7293dd31444", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-05-24T01:17:47.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-24T01:17:47.000Z", "avg_line_length": 35.2941176471, "max_line_length": 94, "alphanum_fraction": 0.7079166667, "num_tokens": 792, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.49233767026542413}}
{"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_EPS_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_EPS_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n  /*!\n\n    @ingroup group-ieee\n    Function object implementing eps capabilities\n\n    This is the distance between x and the next representable value of x's type.\n\n    @par Semantic:\n\n    For every parameter of type @c T\n\n    @code\n    T r = eps(x);\n    @endcode\n\n    is similar to:\n\n    @code\n\n    if T is floating\n      T  r = 2^(exponent(x))*Eps<T>()\n    else if T is integral\n      T r = 1;\n    @endcode\n\n    @see ulp, ulpdist, Eps\n**/\n  Value eps(Value const & v0);\n\n} }\n#endif\n\n#include <boost/simd/function/scalar/eps.hpp>\n#include <boost/simd/function/simd/eps.hpp>\n\n#endif\n", "meta": {"hexsha": "ced1b13184f82029d9fc25b8c914514744ae200d", "size": 1126, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/eps.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/function/eps.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/eps.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": 21.2452830189, "max_line_length": 100, "alphanum_fraction": 0.5577264654, "num_tokens": 257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.49233767026542413}}
{"text": "#ifndef LIBKRIGING_ORDINARYKRIGING_HPP\n#define LIBKRIGING_ORDINARYKRIGING_HPP\n\n#include <armadillo>\n\n#include \"libKriging/libKriging_exports.h\"\n// #include \"covariance.h\"\n\n/** Ordinary kriging regression\n * @ingroup Regression\n */\nclass OrdinaryKriging {\n public:\n  struct Parameters {\n    double sigma2;\n    bool has_sigma2;\n    arma::vec theta;\n    bool has_theta;\n  };\n\n  enum class RegressionModel { Constant, Linear, Quadratic };\n\n  struct RegressionModelUtils {\n    LIBKRIGING_EXPORT static RegressionModel fromString(const std::string & s);\n    LIBKRIGING_EXPORT static std::string toString(const RegressionModel & m);\n  };\n\n  const arma::mat& X() const { return m_X; };\n  const arma::rowvec& centerX() const { return m_centerX; };\n  const arma::rowvec& scaleX() const { return m_scaleX; };\n  const arma::colvec& y() const { return m_y; };\n  const double& centerY() const { return m_centerY; };\n  const double& scaleY() const { return m_scaleY; };\n  const RegressionModel& regmodel() const { return m_regmodel; };\n  const arma::mat& F() const { return m_F; };\n  const arma::mat& T() const { return m_T; };\n  const arma::mat& M() const { return m_M; };\n  const arma::colvec& z() const { return m_z; };\n  const arma::colvec& beta() const { return m_beta; };\n  const arma::vec& theta() const { return m_theta; };\n  const double& sigma2() const { return m_sigma2; };\n\n private:\n  arma::mat m_X;\n  arma::rowvec m_centerX;\n  arma::rowvec m_scaleX;\n  arma::colvec m_y;\n  double m_centerY;\n  double m_scaleY;\n  RegressionModel m_regmodel;\n  arma::mat m_F;\n  arma::mat m_T;\n  arma::mat m_M;\n  arma::colvec m_z;\n  arma::colvec m_beta;\n  arma::vec m_theta;\n  double m_sigma2;\n\n  std::function<double(const arma::vec&, const arma::vec&)> CovNorm_fun;  // Covariance function on normalized data\n  std::function<double(const arma::vec&, const arma::vec&, int)>\n      CovNorm_deriv;  // Covariance function derivative vs. theta\n\n  // returns distance matrix form Xp to X\n  LIBKRIGING_EXPORT arma::mat Cov(const arma::mat& X, const arma::mat& Xp);\n  LIBKRIGING_EXPORT arma::mat Cov(const arma::mat& X);\n  //  // same for one point\n  //  LIBKRIGING_EXPORT arma::colvec Cov(const arma::mat& X, const arma::rowvec& x, const arma::colvec& theta);\n\n  // This will create the dist(xi,xj) function above. Need to parse \"kernel\".\n  void make_Cov(const std::string& covType);\n\n public:\n  struct OKModel {\n    arma::colvec y;\n    arma::mat X;\n    arma::mat F;\n    arma::mat T;\n    arma::mat M;\n    arma::colvec z;\n    arma::colvec beta;\n    std::function<double(const arma::vec&, const arma::vec&)> covnorm_fun;\n    std::function<double(const arma::vec&, const arma::vec&, int)> covnorm_deriv;\n  };\n\n  // LIBKRIGING_EXPORT double fit_ofn(const arma::vec& theta, arma::vec* grad_out, OKModel* okm_data);\n\n  // at least, just call make_dist(kernel)\n  LIBKRIGING_EXPORT OrdinaryKriging();  // const std::string & covType);\n\n  /** Fit the kriging object on (X,y):\n   * @param y is n length column vector of output\n   * @param X is n*d matrix of input\n   * @param regmodel is the regression model to be used for the GP mean (choice between contant, linear, quadratic)\n   * @param parameters is starting value for hyper-parameters\n   * @param optim_method is an optimizer name from OptimLib, or 'none' to keep parameters unchanged\n   * @param optim_objective is 'loo' or 'loglik'. Ignored if optim_method=='none'.\n   */\n  LIBKRIGING_EXPORT void fit(const arma::colvec& y,\n                             const arma::mat& X,\n                             const RegressionModel& regmodel = RegressionModel::Constant,\n                             bool normalize = false);  //,\n  // const Parameters& parameters,\n  // const std::string& optim_method,\n  // const std::string& optim_objective);\n\n  LIBKRIGING_EXPORT double logLikelihood(const arma::vec& theta);\n  LIBKRIGING_EXPORT arma::vec logLikelihoodGrad(const arma::vec& theta);\n  LIBKRIGING_EXPORT double loofun(const arma::vec& theta);\n  LIBKRIGING_EXPORT arma::vec loofungrad(const arma::vec& theta);\n\n  /** Compute the prediction for given points X'\n   * @param Xp is m*d matrix of points where to predict output\n   * @param std is true if return also stdev column vector\n   * @param cov is true if return also cov matrix between Xp\n   * @return output prediction: m means, [m standard deviations], [m*m full covariance matrix]\n   */\n  LIBKRIGING_EXPORT std::tuple<arma::colvec, arma::colvec, arma::mat> predict(const arma::mat& Xp,\n                                                                              bool withStd,\n                                                                              bool withCov);\n\n  /** Draw sample trajectories of kriging at given points X'\n   * @param Xp is m*d matrix of points where to simulate output\n   * @param nsim is number of simulations to draw\n   * @return output is m*nsim matrix of simulations at Xp\n   */\n  LIBKRIGING_EXPORT arma::mat simulate(const int nsim, const arma::mat& Xp, bool cond = true);\n\n  /** Add new conditional data points to previous (X,y)\n   * @param newy is m length column vector of new output\n   * @param newX is m*d matrix of new input\n   * @param optim_method is an optimizer name from OptimLib, or 'none' to keep previously estimated parameters unchanged\n   * @param optim_objective is 'loo' or 'loglik'. Ignored if optim_method=='none'.\n   */\n  LIBKRIGING_EXPORT void update(const arma::vec& newy,\n                                const arma::mat& newX,\n                                const std::string& optim_method,\n                                const std::string& optim_objective);\n};\n\n#endif  // LIBKRIGING_ORDINARYKRIGING_HPP\n", "meta": {"hexsha": "bac8bdcce9745b1a7bfbaae20258fb90ae411dbc", "size": 5636, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/lib/include/libKriging/OrdinaryKriging.hpp", "max_stars_repo_name": "SebastienDaVeiga/libKriging", "max_stars_repo_head_hexsha": "62c4dfe1a55b6c867a5e9b5578270fbbd2c739a3", "max_stars_repo_licenses": ["Apache-2.0"], "max_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/include/libKriging/OrdinaryKriging.hpp", "max_issues_repo_name": "SebastienDaVeiga/libKriging", "max_issues_repo_head_hexsha": "62c4dfe1a55b6c867a5e9b5578270fbbd2c739a3", "max_issues_repo_licenses": ["Apache-2.0"], "max_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/include/libKriging/OrdinaryKriging.hpp", "max_forks_repo_name": "SebastienDaVeiga/libKriging", "max_forks_repo_head_hexsha": "62c4dfe1a55b6c867a5e9b5578270fbbd2c739a3", "max_forks_repo_licenses": ["Apache-2.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.9716312057, "max_line_length": 120, "alphanum_fraction": 0.6646557842, "num_tokens": 1469, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540518, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.492337670265424}}
{"text": "#include <boost/graph/eccentricity.hpp>\n", "meta": {"hexsha": "5479f1140c313900d0f0a53dab4f0156eda2c623", "size": 40, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_graph_eccentricity.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_graph_eccentricity.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_graph_eccentricity.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 20.0, "max_line_length": 39, "alphanum_fraction": 0.8, "num_tokens": 10, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4923376642688862}}
{"text": "#include <iostream>\n#include <iterator>\n#include <string>\n#include <vector>\n#include <algorithm>\n#include <boost/algorithm/string.hpp>\n\nlong no_paren_solution(std::string line) {\n  std::string result;\n  std::vector<std::string> items;\n  split(items, line, boost::is_any_of(\" \"), boost::token_compress_on);\n  if (items.size() == 1) {\n    return std::stol(items[0]);\n  } else if (items[1] == \"*\") {\n    result = std::to_string(std::stol(items[0]) * std::stol(items[2]));\n  } else if (items[1] == \"+\") {\n    result = std::to_string(std::stol(items[0]) + std::stol(items[2]));\n  }\n  items.erase(items.begin(), items.begin() + 3);\n  items.insert(items.begin(), result);\n  return no_paren_solution(boost::join(items, \" \"));\n}\n\nlong no_paren_solution_ordered(std::string line) {\n  std::string result;\n  std::vector<std::string> items;\n  split(items, line, boost::is_any_of(\" \"), boost::token_compress_on);\n  auto it = std::find(items.begin(), items.end(), \"+\");\n  int first_sum = std::distance(items.begin(), it);\n  if (it == items.end()){\n    return no_paren_solution(line);\n  }\n  result = std::to_string(std::stol(items[first_sum - 1]) +\n                          std::stol(items[first_sum + 1]));\n  items.erase(it-1, it + 2);\n  items.insert(it-1, result);\n  return no_paren_solution_ordered(boost::join(items, \" \"));\n}\n\nlong full_solution(std::string problem,\n                   long (*no_paren_func)(std::string line)) {\n  int open_par = problem.find_first_of(\"(\");\n  if (open_par == std::string::npos){\n    return no_paren_func(problem);\n  } else {\n    int close_par = open_par;\n    int n_open = 1;\n    while (n_open > 0){\n      close_par++;\n      if (problem[close_par] == ')'){\n        n_open--;\n      } else if (problem[close_par] == '('){\n        n_open++;\n      }\n    }\n    std::string inside_paren;\n    inside_paren = problem.substr(open_par+1, close_par-open_par-1);\n    std::string new_problem = problem;\n    std::string solved_inside = std::to_string(full_solution(inside_paren, no_paren_func));\n    new_problem.replace(open_par, close_par-open_par+1, solved_inside);\n    return full_solution(new_problem, no_paren_func);\n  }\n}\n\nint main() {\n\n  long answer_pt1 = 0;\n  long answer_pt2 = 0;\n\n  for (std::string line; std::getline(std::cin, line);){\n    long curr_sol_pt1 = full_solution(line, no_paren_solution);\n    answer_pt1 += curr_sol_pt1;\n    long curr_sol_pt2 = full_solution(line, no_paren_solution_ordered);\n    answer_pt2 += curr_sol_pt2;\n    // break;\n  }\n  std::cout << \"Part 1: \" << answer_pt1 << std::endl;\n  std::cout << \"Part 2: \" << answer_pt2 << std::endl;\n}\n", "meta": {"hexsha": "eb9a3dffaa0f2ee811fbe8e6c1d7edaf5fa4fc17", "size": 2582, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "18/aoc18.cpp", "max_stars_repo_name": "GreyGooClub/Advent2020-DTC", "max_stars_repo_head_hexsha": "b1ff37ef9a3c8272513cf6d7eba66dae11680d60", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "18/aoc18.cpp", "max_issues_repo_name": "GreyGooClub/Advent2020-DTC", "max_issues_repo_head_hexsha": "b1ff37ef9a3c8272513cf6d7eba66dae11680d60", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "18/aoc18.cpp", "max_forks_repo_name": "GreyGooClub/Advent2020-DTC", "max_forks_repo_head_hexsha": "b1ff37ef9a3c8272513cf6d7eba66dae11680d60", "max_forks_repo_licenses": ["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.275, "max_line_length": 91, "alphanum_fraction": 0.6390395043, "num_tokens": 719, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.49233766426888614}}
{"text": "//\n// Created by kamil on 13.03.18.\n//\n\n#include \"macd.hpp\"\n#include <fstream>\n#include <cmath>\n#include <algorithm>\n#include <iterator>\n#include <functional>\n#include <Python.h>\n#include <boost/format.hpp>\n#include <future>\n\nnamespace mn_macd {\n\n\n\n\n    std::shared_ptr<std::vector<double>>\n    parse_file(path_t const &file_path, std::locale locale) {\n        std::ifstream file(file_path);\n        file.imbue(locale);\n        auto result = std::make_shared<std::vector<double>>(std::istream_iterator<double>(file),\n                                                            std::istream_iterator<double>());\n        if (result->size() <=1 ) {\n            cerr << \"\\nERROR: input file empty/corrupted/bad locale\" << endl;\n            exit(1);\n        }\n        return result;\n    }\n\n    std::shared_ptr<std::vector<double>>\n    ema(std::vector<double> const &input, size_t period) {\n        if (period > input.size()){\n            cerr << \"\\nERROR: period is bigger than data\" << endl;\n            exit(2);\n        }\n        auto result = std::make_shared<std::vector<double>>(period);\n        auto data_iterator = input.begin() + period;\n        double alpha = 2 / (period - 1.0);\n        while (data_iterator != input.end()) {\n            double nominator = 0, denominator = 0;\n            for (int i = 0; i <= period; ++i) {\n                nominator += *(data_iterator - i) * std::pow(1 - alpha, i);\n                denominator += std::pow(1 - alpha, i);\n            }\n            result->push_back(nominator / denominator);\n            data_iterator++;\n        }\n        return result;\n    }\n\n\n    void write_to_file(path_t const &file_path, std::vector<double> const &data) {\n        std::ofstream file;\n        file.exceptions(std::ofstream::badbit | std::ofstream::failbit);\n        try {\n            file.open(file_path);\n            for (auto const x : data) file << x << '\\n';\n        } catch (std::ios_base::failure const &e) {\n            cerr << \"An error occured while writing to file: \" << file_path << '\\n' << e.what()\n                 << endl;\n            exit(3);\n        }\n\n    }\n\n    void\n    py_gen_plots(path_t const &py_script_path,\n                 std::string title,\n                 path_t const &rate_in,\n                 path_t const &signal_in,\n                 path_t const &macd_in,\n                 path_t const &rate_out,\n                 path_t const &macd_signal_out) {\n\n        if (!std::experimental::filesystem::exists(py_script_path)) {\n            cerr << \"Python program \" << py_script_path\n                 << \" does not exists in current location. It is needed for a plot generation.\" << endl;\n            exit(1);\n        };\n        Py_SetProgramName(const_cast<wchar_t *>(L\"MACD plot generator\"));\n        Py_Initialize();\n        auto file = std::ifstream(py_script_path);\n        auto python_code_template = std::move(\n                std::string(\n                        std::istreambuf_iterator<char>(file),\n                        std::istreambuf_iterator<char>()));\n        file.close();\n        auto python_code = boost::format(python_code_template) %\n                           title %\n                           signal_in %\n                           macd_in %\n                           rate_in %\n                           macd_signal_out %\n                           rate_out;\n        PyRun_SimpleString(python_code.str().c_str());\n        Py_Finalize();\n    }\n\n    std::tuple<\n            std::shared_ptr<std::vector<double>>, // macd\n            std::shared_ptr<std::vector<double>>, // signal\n            std::shared_ptr<std::vector<double>>> // rate\n    compute_macd(std::shared_ptr<std::vector<double>> input) {\n        auto ema12_thread = std::async(std::launch::async, mn_macd::ema, *input, 12);\n        auto ema26_thread = std::async(std::launch::async, mn_macd::ema, *input, 26);\n        auto macd = std::make_shared<std::vector<double>>();\n        macd->reserve(input->size());\n        auto ema12 = ema12_thread.get();\n        auto ema26 = ema26_thread.get();\n\n        std::transform(ema12->begin(), ema12->end(), ema26->begin(), std::back_inserter(*macd),\n                       std::minus<>()); //MACD = EMA12 - EMA26\n        auto signal = mn_macd::ema(*macd, 9);\n\n        // Trim data at beginning\n        auto trim_data = [](auto x, size_t offset) { x->erase(x->begin(), x->begin() + offset); };\n        trim_data(macd, 35);\n        trim_data(signal, 35);\n        trim_data(input, 35);\n        return std::make_tuple(macd, signal, input);\n    }\n\n}\n", "meta": {"hexsha": "52909a9c098d703c0f82c3b5877f29e50ba87c38", "size": 4522, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "macd.cpp", "max_stars_repo_name": "iceShaver/MN_MACD", "max_stars_repo_head_hexsha": "8fcc76f6258c31cc12339ea2a9d0d81937ea6ef7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "macd.cpp", "max_issues_repo_name": "iceShaver/MN_MACD", "max_issues_repo_head_hexsha": "8fcc76f6258c31cc12339ea2a9d0d81937ea6ef7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "macd.cpp", "max_forks_repo_name": "iceShaver/MN_MACD", "max_forks_repo_head_hexsha": "8fcc76f6258c31cc12339ea2a9d0d81937ea6ef7", "max_forks_repo_licenses": ["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.6062992126, "max_line_length": 104, "alphanum_fraction": 0.5314020345, "num_tokens": 1053, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.49233766426888614}}
{"text": "//  test_duration.cpp  ----------------------------------------------------------//\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\nThis code was extracted by Vicente J. Botet Escriba from Beman Dawes time2_demo.cpp which\r\nwas 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.9 Time utilities [time] of the C++ committee's working paper 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#include <boost/assert.hpp>\r\n#include <boost/chrono/chrono.hpp>\r\n#include <boost/type_traits.hpp>\r\n\r\n#include <iostream>\r\n\r\ntemplate <class Rep, class Period>\r\nvoid inspect_duration(boost::chrono::duration<Rep, Period> d, const std::string& name)\r\n{\r\n    typedef boost::chrono::duration<Rep, Period> Duration;\r\n    std::cout << \"********* \" << name << \" *********\\n\";\r\n    std::cout << \"The period of \" << name << \" is \" << (double)Period::num/Period::den << \" seconds.\\n\";\r\n    std::cout << \"The frequency of \" << name << \" is \" << (double)Period::den/Period::num << \" Hz.\\n\";\r\n    std::cout << \"The representation is \";\r\n    if (boost::is_floating_point<Rep>::value)\r\n    {\r\n        std::cout << \"floating point\\n\";\r\n        std::cout << \"The precision is the most significant \";\r\n        std::cout << std::numeric_limits<Rep>::digits10 << \" decimal digits.\\n\";\r\n    }\r\n    else if (boost::is_integral<Rep>::value)\r\n    {\r\n        std::cout << \"integral\\n\";\r\n        d = Duration(Rep(1));\r\n        boost::chrono::duration<double> dsec = d;\r\n        std::cout << \"The precision is \" << dsec.count() << \" seconds.\\n\";\r\n    }\r\n    else\r\n    {\r\n        std::cout << \"a class type\\n\";\r\n        d = Duration(Rep(1));\r\n        boost::chrono::duration<double> dsec = d;\r\n        std::cout << \"The precision is \" << dsec.count() << \" seconds.\\n\";\r\n    }\r\n    d = Duration((std::numeric_limits<Rep>::max)());\r\n    using namespace boost::chrono;\r\n    typedef duration<double, boost::ratio_multiply<boost::ratio<24*3652425,10000>, hours::period>::type> Years;\r\n    Years years = d;\r\n    std::cout << \"The range is +/- \" << years.count() << \" years.\\n\";\r\n    std::cout << \"sizeof(\" << name << \") = \" << sizeof(d) << '\\n';\r\n}\r\n\r\nvoid inspect_all()\r\n{\r\n    using namespace boost::chrono;\r\n    std::cout.precision(6);\r\n    inspect_duration(nanoseconds(), \"nanoseconds\");\r\n    inspect_duration(microseconds(), \"microseconds\");\r\n    inspect_duration(milliseconds(), \"milliseconds\");\r\n    inspect_duration(seconds(), \"seconds\");\r\n    inspect_duration(minutes(), \"minutes\");\r\n    inspect_duration(hours(), \"hours\");\r\n    inspect_duration(duration<double>(), \"duration<double>\");\r\n}\r\n\r\n\r\n\r\nusing namespace boost::chrono;\r\nvoid test_duration_division()\r\n{\r\n    typedef boost::common_type<boost::chrono::hours::rep, boost::chrono::minutes::rep>::type h_min_rep;\r\n    h_min_rep r3 = hours(3) / minutes(5);\r\n    std::cout << r3 << '\\n';\r\n    std::cout << hours(3) / minutes(5) << '\\n';\r\n    std::cout << hours(3) / milliseconds(5) << '\\n';\r\n    std::cout << milliseconds(5) / hours(3) << '\\n';\r\n    std::cout << hours(1) / milliseconds(1) << '\\n';\r\n}\r\n\r\nvoid test_duration_multiply()\r\n{\r\n    hours h15= 5 * hours(3);\r\n    hours h6= hours(3) *2;\r\n}\r\n\r\nvoid f(duration<double> d, double res)  // accept floating point seconds\r\n{\r\n    // d.count() == 3.e-6 when passed microseconds(3)\r\n    BOOST_ASSERT(d.count()==res);\r\n}\r\n\r\nvoid g(nanoseconds d, boost::intmax_t res)\r\n{\r\n    // d.count() == 3000 when passed microseconds(3)\r\n    std::cout << d.count() << \" \" <<res << std::endl;\r\n    BOOST_ASSERT(d.count()==res);\r\n}\r\n\r\ntemplate <class Rep, class Period>\r\nvoid tmpl(duration<Rep, Period> d, boost::intmax_t res)\r\n{\r\n    // convert d to nanoseconds, rounding up if it is not an exact conversion\r\n    nanoseconds ns = duration_cast<nanoseconds>(d);\r\n    if (ns < d)\r\n        ++ns;\r\n    // ns.count() == 333333334 when passed 1/3 of a floating point second\r\n    BOOST_ASSERT(ns.count()==res);\r\n}\r\n\r\ntemplate <class Period>\r\nvoid tmpl2(duration<long long, Period> d, boost::intmax_t res)\r\n{\r\n    // convert d to nanoseconds, rounding up if it is not an exact conversion\r\n    nanoseconds ns = duration_cast<nanoseconds>(d);\r\n    if (ns < d)\r\n        ++ns;\r\n    // ns.count() == 333333334 when passed 333333333333 picoseconds\r\n    BOOST_ASSERT(ns.count()==res);\r\n}\r\n\r\n\r\n\r\nint main()\r\n{\r\n    minutes m1(3);                 // m1 stores 3\r\n    minutes m2(2);                 // m2 stores 2\r\n    minutes m3 = m1 + m2;          // m3 stores 5\r\n    BOOST_ASSERT(m3.count()==5);\r\n\r\n    microseconds us1(3);           // us1 stores 3\r\n    microseconds us2(2);           // us2 stores 2\r\n    microseconds us3 = us1 + us2;  // us3 stores 5\r\n    BOOST_ASSERT(us3.count()==5);\r\n\r\n    microseconds us4 = m3 + us3;   // us4 stores 300000005\r\n    BOOST_ASSERT(us4.count()==300000005);\r\n    microseconds us5 = m3;   // us4 stores 300000000\r\n    BOOST_ASSERT(us5.count()==300000000);\r\n\r\n    //minutes m4 = m3 + us3; // won't compile\r\n\r\n    minutes m4 = duration_cast<minutes>(m3 + us3);  // m4.count() == 5\r\n    BOOST_ASSERT(m4.count()==5);\r\n\r\n    typedef duration<double, boost::ratio<60> > dminutes;\r\n    dminutes dm4 = m3 + us3;  // dm4.count() == 5.000000083333333\r\n    BOOST_ASSERT(dm4.count()==5.000000083333333);\r\n\r\n    f(microseconds(3), 0.000003);\r\n    g(microseconds(3), 3000);\r\n    duration<double> s(1./3);  // 1/3 of a second\r\n    g(duration_cast<nanoseconds>(s), 333333333);  // round towards zero in conversion to nanoseconds\r\n    //f(s);  // does not compile\r\n    tmpl(duration<double>(1./3), 333333334);\r\n    tmpl2(duration<long long, boost::pico>(333333333333LL), 333333334);  // About 1/3 of a second worth of picoseconds\r\n\r\n    //f(3,3);  // Will not compile, 3 is not implicitly convertible to any `duration`\r\n    //g(3,3);  // Will not compile, 3 is not implicitly convertible to any `duration`\r\n    //tmpl(3,3);  // Will not compile, 3 is not implicitly convertible to any `duration`\r\n    //tmpl2(3,3);  // Will not compile, 3 is not implicitly convertible to any `duration`\r\n\r\n    {\r\n    double r = double(milliseconds(3) / milliseconds(3));\r\n    std::cout << r << '\\n';\r\n\r\n    duration<double, boost::milli> d = milliseconds(3) * 2.5;\r\n    duration<double, boost::milli> d2 = 2.5 * milliseconds(3) ;\r\n    duration<double, boost::milli> d3 = milliseconds(3) / 2.5;\r\n    duration<double, boost::milli> d4 = milliseconds(3) + milliseconds(5) ;\r\n    inspect_duration(milliseconds(3) * 2.5, \"milliseconds(3) * 2.5\");\r\n    std::cout << d.count() << '\\n';\r\n//    milliseconds ms(3.5);  // doesn't compile\r\n    std::cout << \"milliseconds ms(3.5) doesn't compile\\n\";\r\n    }\r\n\r\n    test_duration_division();\r\n    test_duration_multiply();\r\n    return 0;\r\n}\r\n\r\n", "meta": {"hexsha": "80551313662b805bca252e32353650d632f8a93e", "size": 7311, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/chrono/example/test_duration.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/chrono/example/test_duration.cpp", "max_issues_repo_name": "xiaoliang2121/Boost", "max_issues_repo_head_hexsha": "fc90c3fde129c62565c023f091eddc4a7ed9902b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-03-19T08:23:23.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-24T07:48:47.000Z", "max_forks_repo_path": "libs/chrono/example/test_duration.cpp", "max_forks_repo_name": "xiaoliang2121/Boost", "max_forks_repo_head_hexsha": "fc90c3fde129c62565c023f091eddc4a7ed9902b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 36.7386934673, "max_line_length": 119, "alphanum_fraction": 0.6015592942, "num_tokens": 1982, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.4923164552814348}}
{"text": "//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\file NoiseModel.hpp\n///\n/// \\author Sean Anderson, ASRL\n//////////////////////////////////////////////////////////////////////////////////////////////\n\n#ifndef STEAM_NOISE_MODEL_HPP\n#define STEAM_NOISE_MODEL_HPP\n\n#include <Eigen/Dense>\n#include <mutex>\n\nnamespace steam {\n\n/// @class NoiseEvaluator evaluates uncertainty based on a derived model.\ntemplate <int MEAS_DIM>\nclass NoiseEvaluator {\npublic:\n  /// Convenience typedefs\n  typedef std::shared_ptr<NoiseEvaluator<MEAS_DIM> > Ptr;\n  typedef std::shared_ptr<const NoiseEvaluator<MEAS_DIM> > ConstPtr;\n  \n  /// \\brief Default constructor.\n  NoiseEvaluator()=default;\n\n  /// \\brief Default destructor.\n  virtual ~NoiseEvaluator()=default;\n\n  /// \\brief mutex locked public exposure of the virtual evaluate() function.\n  virtual Eigen::Matrix<double,MEAS_DIM,MEAS_DIM> evaluateCovariance() {\n    std::lock_guard<std::mutex> lock(eval_mutex_);\n    return evaluate();\n  }\n\nprotected:\n  /// \\brief Evaluates the uncertainty based on a derived model.\n  /// \\return the uncertainty, in the form of a covariance matrix.\n  virtual Eigen::Matrix<double,MEAS_DIM,MEAS_DIM> evaluate()=0;\n\nprivate:\n  std::mutex eval_mutex_;\n};\n\n/// Enumeration of ways to set the noise\nenum MatrixType { COVARIANCE, INFORMATION, SQRT_INFORMATION };\n\n/// @class BaseNoiseModel Base class for the steam noise models\ntemplate <int MEAS_DIM>\nclass BaseNoiseModel \n{\n public:\n\n  /// \\brief Default constructor.\n  BaseNoiseModel()=default;\n\n  /// \\brief Constructor\n  /// \\brief A noise matrix, determined by the type parameter.\n  /// \\brief The type of noise matrix set in the previous paramter.\n  BaseNoiseModel(const Eigen::Matrix<double,MEAS_DIM,MEAS_DIM>& matrix,\n             MatrixType type = COVARIANCE);\n\n  /// \\brief Deault destructor\n  virtual ~BaseNoiseModel() = default;\n\n  /// Convenience typedefs\n  typedef std::shared_ptr<BaseNoiseModel<MEAS_DIM> > Ptr;\n  typedef std::shared_ptr<const BaseNoiseModel<MEAS_DIM> > ConstPtr;\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Set by covariance matrix\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  void setByCovariance(const Eigen::Matrix<double,MEAS_DIM,MEAS_DIM>& matrix) const;\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Set by information matrix\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  void setByInformation(const Eigen::Matrix<double,MEAS_DIM,MEAS_DIM>& matrix) const ;\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Set by square root of information matrix\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  void setBySqrtInformation(const Eigen::Matrix<double,MEAS_DIM,MEAS_DIM>& matrix) const ;\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Get a reference to the square root information matrix\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  virtual const Eigen::Matrix<double,MEAS_DIM,MEAS_DIM>& getSqrtInformation() const = 0;\n\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Get the norm of the whitened error vector, sqrt(rawError^T * info * rawError)\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  virtual double getWhitenedErrorNorm(const Eigen::Matrix<double,MEAS_DIM,1>& rawError) const = 0;\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Get the whitened error vector, sqrtInformation*rawError\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  virtual Eigen::Matrix<double,MEAS_DIM,1> whitenError(\n      const Eigen::Matrix<double,MEAS_DIM,1>& rawError) const = 0;\n\n protected:\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Assert that the matrix is positive definite\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  void assertPositiveDefiniteMatrix(const Eigen::Matrix<double,MEAS_DIM,MEAS_DIM>& matrix) const;\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief The square root information (found by performing an LLT decomposition on the\n  ///        information matrix (inverse covariance matrix). This triangular matrix is\n  ///        stored directly for faster error whitening.\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  mutable Eigen::Matrix<double,MEAS_DIM,MEAS_DIM> sqrtInformation_;\n\n private:\n\n};\n\n/// @class StaticNoiseModel Noise model for uncertainties that do not change during the \n///        steam optimization problem.\ntemplate <int MEAS_DIM>\nclass StaticNoiseModel : public BaseNoiseModel<MEAS_DIM>\n{\n public:\n\n  /// Convenience typedefs\n  typedef std::shared_ptr<StaticNoiseModel<MEAS_DIM> > Ptr;\n  typedef std::shared_ptr<const StaticNoiseModel<MEAS_DIM> > ConstPtr;\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Default constructor\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  StaticNoiseModel();\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief General constructor\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  StaticNoiseModel(const Eigen::Matrix<double,MEAS_DIM,MEAS_DIM>& matrix,\n             MatrixType type = COVARIANCE);\n\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Get a reference to the square root information matrix\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  virtual const Eigen::Matrix<double,MEAS_DIM,MEAS_DIM>& getSqrtInformation() const;\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Get the norm of the whitened error vector, sqrt(rawError^T * info * rawError)\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  virtual double getWhitenedErrorNorm(const Eigen::Matrix<double,MEAS_DIM,1>& rawError) const;\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Get the whitened error vector, sqrtInformation*rawError\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  virtual Eigen::Matrix<double,MEAS_DIM,1> whitenError(\n      const Eigen::Matrix<double,MEAS_DIM,1>& rawError) const;\n\nprivate:\n\n};\n\n/// \\brief DynamicNoiseModel Noise model for uncertainties that change during the steam optimization\n///        problem.\ntemplate <int MEAS_DIM>\nclass DynamicNoiseModel : public BaseNoiseModel<MEAS_DIM>\n{\n public:\n  /// \\brief Constructor\n  /// \\param eval a pointer to a noise evaluator.\n  DynamicNoiseModel(std::shared_ptr<NoiseEvaluator<MEAS_DIM>> eval);\n\n  /// \\brief Deault destructor.\n  ~DynamicNoiseModel()=default;\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Get a reference to the square root information matrix\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  virtual const Eigen::Matrix<double,MEAS_DIM,MEAS_DIM>& getSqrtInformation() const;\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Get the norm of the whitened error vector, sqrt(rawError^T * info * rawError)\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  virtual double getWhitenedErrorNorm(const Eigen::Matrix<double,MEAS_DIM,1>& rawError) const;\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Get the whitened error vector, sqrtInformation*rawError\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  virtual Eigen::Matrix<double,MEAS_DIM,1> whitenError(\n      const Eigen::Matrix<double,MEAS_DIM,1>& rawError) const;\n\n private:\n  /// \\brief A pointer to a noise evaluator.\n  std::shared_ptr<NoiseEvaluator<MEAS_DIM>> eval_;\n};\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Typedef for the general base noise model\n//////////////////////////////////////////////////////////////////////////////////////////////\ntypedef BaseNoiseModel<Eigen::Dynamic> BaseNoiseModelX;\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Typedef for the general static noise model\n//////////////////////////////////////////////////////////////////////////////////////////////\ntypedef StaticNoiseModel<Eigen::Dynamic> StaticNoiseModelX;\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Typedef for the general dynamic noise model\n//////////////////////////////////////////////////////////////////////////////////////////////\ntypedef DynamicNoiseModel<Eigen::Dynamic> DynamicNoiseModelX;\n\n} // steam\n\n\n#include <steam/problem/NoiseModel-inl.hpp>\n\n#endif // STEAM_NOISE_MODEL_HPP\n", "meta": {"hexsha": "02cf4f796d4eb430db9264a6ce3e6efec0bc9c3c", "size": 9786, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/steam/problem/NoiseModel.hpp", "max_stars_repo_name": "utiasASRL/steam", "max_stars_repo_head_hexsha": "0905736fa356ce743636453b37e952580d40d425", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 38.0, "max_stars_repo_stars_event_min_datetime": "2019-10-17T01:37:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T03:55:47.000Z", "max_issues_repo_path": "include/steam/problem/NoiseModel.hpp", "max_issues_repo_name": "utiasASRL/steam", "max_issues_repo_head_hexsha": "0905736fa356ce743636453b37e952580d40d425", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-12-21T21:25:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-01T23:08:57.000Z", "max_forks_repo_path": "include/steam/problem/NoiseModel.hpp", "max_forks_repo_name": "utiasASRL/steam", "max_forks_repo_head_hexsha": "0905736fa356ce743636453b37e952580d40d425", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-12-21T21:13:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T23:42:14.000Z", "avg_line_length": 45.0967741935, "max_line_length": 100, "alphanum_fraction": 0.4522787656, "num_tokens": 1643, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.4923164512446837}}
{"text": "//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\file GemanMcClureLossFunc.hpp\n///\n/// \\author Sean Anderson, ASRL\n//////////////////////////////////////////////////////////////////////////////////////////////\n\n#ifndef STEAM_GM_LOSS_FUNCTION_HPP\n#define STEAM_GM_LOSS_FUNCTION_HPP\n\n#include <Eigen/Core>\n\n#include <steam/problem/lossfunc/LossFunctionBase.hpp>\n\nnamespace steam {\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Geman-McClure loss function class\n//////////////////////////////////////////////////////////////////////////////////////////////\nclass GemanMcClureLossFunc : public LossFunctionBase\n{\n public:\n\n  /// Convenience typedefs\n  typedef std::shared_ptr<GemanMcClureLossFunc> Ptr;\n  typedef std::shared_ptr<const GemanMcClureLossFunc> ConstPtr;\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Constructor -- k is the `threshold' based on number of std devs (1-3 is typical)\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  GemanMcClureLossFunc(double k) : k2_(k*k) {}\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Cost function (basic evaluation of the loss function)\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  virtual double cost(double whitened_error_norm) const;\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Weight for iteratively reweighted least-squares (influence function div. by error)\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  virtual double weight(double whitened_error_norm) const;\n\n private:\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief GM constant\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  double k2_;\n};\n\n} // steam\n\n#endif // STEAM_GM_LOSS_FUNCTION_HPP\n", "meta": {"hexsha": "1bb6c1a32823393a1f4f09e4f047cd16f1b46596", "size": 2178, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/steam/problem/lossfunc/GemanMcClureLossFunc.hpp", "max_stars_repo_name": "utiasASRL/steam", "max_stars_repo_head_hexsha": "0905736fa356ce743636453b37e952580d40d425", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 38.0, "max_stars_repo_stars_event_min_datetime": "2019-10-17T01:37:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T03:55:47.000Z", "max_issues_repo_path": "include/steam/problem/lossfunc/GemanMcClureLossFunc.hpp", "max_issues_repo_name": "utiasASRL/steam", "max_issues_repo_head_hexsha": "0905736fa356ce743636453b37e952580d40d425", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-12-21T21:25:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-01T23:08:57.000Z", "max_forks_repo_path": "include/steam/problem/lossfunc/GemanMcClureLossFunc.hpp", "max_forks_repo_name": "utiasASRL/steam", "max_forks_repo_head_hexsha": "0905736fa356ce743636453b37e952580d40d425", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-12-21T21:13:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T23:42:14.000Z", "avg_line_length": 41.0943396226, "max_line_length": 96, "alphanum_fraction": 0.354912764, "num_tokens": 319, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7248702761768249, "lm_q2_score": 0.679178692681616, "lm_q1q2_score": 0.49231644653753787}}
{"text": "/**\r\n *  @file    Problem.hpp\r\n *  @brief   Define a finite difference problem.\r\n *  @author  Francois Roy\r\n *  @date    12/01/2019\r\n */\r\n#ifndef PROBLEM_H\r\n#define PROBLEM_H\r\n\r\n#include <map>\r\n#include <string>\r\n#include <vector>\r\n#include <Eigen/SparseCore>\r\n#include \"spdlog/spdlog.h\"\r\n#include \"Parameters.hpp\"\r\n#include \"Mesh.hpp\"\r\n\r\nnamespace numerical {\r\n\r\nnamespace fdm {\r\n\r\n/*\r\n * This class defines the finite difference problem of the diffusion type:\r\n *\r\n * /f[\r\n *    \\frac{\\partial u}{\\partial t} = \\nabla\\left(\\alpha\\nabla u) + f\r\n * /f]\r\n *\r\n * over the hypercube.\r\n */\r\ntemplate <typename T>\r\nclass Problem {\r\ntypedef Eigen::SparseMatrix<T> SpMat;\r\ntypedef Eigen::Triplet<T> Trip;\r\ntypedef Eigen::Matrix<T, Eigen::Dynamic, 1> Vec;\r\nprivate:\r\n    int m_dim;\r\n    \r\nprotected:\r\n    Parameters<T>* m_params;\r\n    Vec m_u;  // The solution vector\r\npublic:\r\n    Problem(Parameters<T>* params): \r\n      m_params(params) {\r\n        // define other variables variables\r\n        m_dim = m_params->lengths.size();\r\n  \t    // define mesh\r\n  \t    Mesh<T> mesh = Mesh<T>(m_params->lengths, m_params->t0, m_params->tend, \r\n          m_params->n, m_params->nt);\r\n    }\r\n    virtual ~Problem(){\r\n    }\r\n    /**\r\n    * Diffusion coefficient value. The default is a constant obtained from \r\n    * m_params.\r\n    *\r\n    * @param x The x-coordinate of the mesh node.\r\n    * @param y The y-coordinate of the mesh node.\r\n    * @param z The z-coordinate of the mesh node.\r\n    * @param t The discrete time.\r\n    * @return The diffusion coefficient value at a specified mesh location.\r\n    */\r\n    virtual T alpha(T x, T y, T z, T t){\r\n  \t    return m_params->alpha;\r\n    }\r\n\r\n    /**\r\n    * @return The spatial dimension of the problem.\r\n    */\r\n    int dim(){\r\n    \treturn m_dim;\r\n    }\r\n\r\n    /**\r\n    * Left boundary value, i.e. for x = lengths[0][0].\r\n    *\r\n    * @param type Dirichlet = 0, Neumann = 1.\r\n    * @param x1 The first coordinate of the mesh node.\r\n    * @param x2 The second coordinate of the mesh node.\r\n    * @param t The discrete time.\r\n    * @return The boundary value at a specified mesh location.\r\n    */\r\n    virtual T left(int type, T x1, T x2, T t){\r\n  \t    return 0.0;\r\n    }\r\n\r\n    /**\r\n    * Right boundary value, i.e. for x = lengths[0][1].\r\n    *\r\n    * @param type Dirichlet = 0, Neumann = 1.\r\n    * @param x1 The first coordinate of the mesh node.\r\n    * @param x2 The second coordinate of the mesh node.\r\n    * @param t The discrete time.\r\n    * @return The boundary value at a specified mesh location.\r\n    */\r\n    virtual T right(int type, T x1, T x2, T t){\r\n        return 0.0;\r\n    }\r\n\r\n    /**\r\n    * Bottom boundary value, i.e. at y = lengths[1][0]. Only for 2D and \r\n    * 3D models.\r\n    *\r\n    * @param type Dirichlet = 0, Neumann = 1.\r\n    * @param x1 The first coordinate of the mesh node.\r\n    * @param x2 The second coordinate of the mesh node.\r\n    * @param t The discrete time.\r\n    * @return The boundary value at a specified mesh location.\r\n    */\r\n    virtual T bottom(int type, T x1, T x2, T t){\r\n        return 0.0;\r\n    }\r\n\r\n    /**\r\n    * Top boundary value, i.e. at y = lengths[1][1]. Only for 2D and 3D models.\r\n    *\r\n    * @param type Dirichlet = 0, Neumann = 1.\r\n    * @param x1 The first coordinate of the mesh node.\r\n    * @param x2 The second coordinate of the mesh node.\r\n    * @param t The discrete time.\r\n    * @return The boundary value at a specified mesh location.\r\n    */\r\n    virtual T top(int type, T x1, T x2, T t){\r\n        return 0.0;\r\n    }\r\n\r\n    /**\r\n    * Front boundary value, i.e. at cz = length[2][0]. Only for 3D models.\r\n    *\r\n    * @param type Dirichlet = 0, Neumann = 1.\r\n    * @param x1 The first coordinate of the mesh node.\r\n    * @param x2 The second coordinate of the mesh node.\r\n    * @param t The discrete time.\r\n    * @return The boundary value at a specified mesh location.\r\n    */\r\n    virtual T front(int type, T x1, T x2, T t){\r\n        return 0.0;\r\n    }\r\n\r\n    /**\r\n    * Back boundary value, i.e. at z = length[2][0]. Only for 3D models.\r\n    *\r\n    * @param type Dirichlet = 0, Neumann = 1.\r\n    * @param x1 The first coordinate of the mesh node.\r\n    * @param x2 The second coordinate of the mesh node.\r\n    * @param t The discrete time.\r\n    * @return The boundary value at a specified mesh location.\r\n    */\r\n    virtual T back(int type, T x1, T x2, T t){\r\n        return 0.0;\r\n    }\r\n\r\n    /**\r\n    * Initial  value.\r\n    *\r\n    * @param x The x-coordinate of the mesh node.\r\n    * @param y The y-coordinate of the mesh node.\r\n    * @param z The z-coordinate of the mesh node.\r\n    * @return The initial value at a specified mesh location.\r\n    */\r\n    virtual T initial_value(T x, T y, T z){\r\n  \t    return 0.0;\r\n    }\r\n\r\n    /**\r\n    *  Get the reference solution at a specified mesh location.\r\n    *\r\n    * @param x The x-coordinate of the mesh node.\r\n    * @param y The y-coordinate of the mesh node.\r\n    * @param z The z-coordinate of the mesh node.\r\n    * @param t The discrete time.\r\n    * @return The reference solution at a specified mesh location.\r\n    */\r\n    virtual T reference(T x, T y, T z, T t){\r\n    \treturn 0.0;\r\n    }\r\n\r\n    /**\r\n    *  Get the computed solution at a specified mesh location.\r\n    *\r\n    * @param x The x-coordinate of the mesh node.\r\n    * @param y The y-coordinate of the mesh node.\r\n    * @param z The z-coordinate of the mesh node.\r\n    * @param t The discrete time.\r\n    * @return The computed solution at a specified mesh location.\r\n    */\r\n    virtual T solution(T x, T y, T z, T t){\r\n    \treturn 0.0;\r\n    }\r\n\r\n    /**\r\n    * Source term.\r\n    *\r\n    * @param x The x-coordinate of the mesh node.\r\n    * @param y The y-coordinate of the mesh node.\r\n    * @param z The z-coordinate of the mesh node.\r\n    * @param t The discrete time.\r\n    * @return The source term at a specified mesh location.\r\n    */\r\n    virtual T source(T x, T y, T z, T t){\r\n  \t    return 0.0;\r\n    }\r\n\r\n};\r\n\r\n}  // namespace fdm\r\n\r\n}  // namespace numerical\r\n\r\n#endif  // PROBLEM_H\r\n", "meta": {"hexsha": "439ad0f400eb166b87529ca6b2265c4ba029ffcf", "size": 6004, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "numerical/fdm/Problem.hpp", "max_stars_repo_name": "dbeat/numerical", "max_stars_repo_head_hexsha": "bce26eb7d537eb8e32105f2887ea11940ce4fc96", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "numerical/fdm/Problem.hpp", "max_issues_repo_name": "dbeat/numerical", "max_issues_repo_head_hexsha": "bce26eb7d537eb8e32105f2887ea11940ce4fc96", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "numerical/fdm/Problem.hpp", "max_forks_repo_name": "dbeat/numerical", "max_forks_repo_head_hexsha": "bce26eb7d537eb8e32105f2887ea11940ce4fc96", "max_forks_repo_licenses": ["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.4549763033, "max_line_length": 80, "alphanum_fraction": 0.5856095936, "num_tokens": 1631, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.49231644653753787}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2020 Tinko Bartels, Berlin, Germany.\n\n// Contributed and/or modified by Tinko Bartels,\n//   as part of Google Summer of Code 2020 program.\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_GENERIC_ROBUST_PREDICATES_STRATEGIES_CARTESIAN_DETAIL_EXPRESSION_TREE_HPP\n#define BOOST_GEOMETRY_EXTENSIONS_GENERIC_ROBUST_PREDICATES_STRATEGIES_CARTESIAN_DETAIL_EXPRESSION_TREE_HPP\n\n#include <cstddef>\n#include <type_traits>\n\n#include <boost/mp11/algorithm.hpp>\n#include <boost/mp11/integral.hpp>\n#include <boost/mp11/list.hpp>\n\nnamespace boost { namespace geometry\n{\n\nnamespace detail { namespace generic_robust_predicates\n{\n\nenum class operator_types {\n    sum, difference, product, abs, no_op, max, min\n};\n\nenum class operator_arities { nullary, unary, binary };\n\nconstexpr int sign_uncertain = -2;\n\nstruct sum_error_type {};\nstruct product_error_type {};\nstruct no_error_type {};\n\ntemplate <typename... Children>\nstruct internal_node\n{\n    static constexpr bool is_leaf = false;\n    static constexpr bool non_negative = false;\n    using all_children = boost::mp11::mp_list<Children...>; //for convenience\n};\n\ntemplate <typename Left, typename Right>\nstruct internal_binary_node : internal_node<Left, Right>\n{\n    using left  = Left;\n    using right = Right;\n    static constexpr operator_arities operator_arity = operator_arities::binary;\n};\n\ntemplate <typename Child>\nstruct internal_unary_node : internal_node<Child>\n{\n    using child = Child;\n    static constexpr operator_arities operator_arity = operator_arities::unary;\n};\n\ntemplate <typename Left, typename Right>\nstruct sum : public internal_binary_node<Left, Right>\n{\n    static constexpr bool sign_exact = Left::is_leaf && Right::is_leaf;\n    static constexpr bool non_negative = Left::non_negative && Right::non_negative;\n    static constexpr operator_types operator_type = operator_types::sum;\n    using error_type = sum_error_type;\n};\n\ntemplate <typename Left, typename Right>\nstruct difference : public internal_binary_node<Left, Right>\n{\n    static constexpr bool sign_exact = Left::is_leaf && Right::is_leaf;\n    static constexpr bool non_negative = false;\n    static constexpr operator_types operator_type = operator_types::difference;\n    using error_type = sum_error_type;\n};\n\ntemplate <typename Left, typename Right>\nstruct product : public internal_binary_node<Left, Right>\n{\n    static constexpr bool sign_exact = Left::sign_exact && Right::sign_exact;\n    static constexpr bool non_negative =\n           (Left::non_negative && Right::non_negative)\n        || std::is_same<Left, Right>::value;\n    static constexpr operator_types operator_type = operator_types::product;\n    using error_type = product_error_type;\n};\n\ntemplate <typename Left, typename Right>\nstruct max : public internal_binary_node<Left, Right>\n{\n    static constexpr bool sign_exact = Left::sign_exact && Right::sign_exact;\n    static constexpr bool non_negative =\n        Left::non_negative || Right::non_negative;\n    static constexpr operator_types operator_type = operator_types::max;\n    using error_type = no_error_type;\n};\n\ntemplate <typename Left, typename Right>\nstruct min : public internal_binary_node<Left, Right>\n{\n    static constexpr bool sign_exact = Left::sign_exact && Right::sign_exact;\n    static constexpr bool non_negative =\n        Left::non_negative && Right::non_negative;\n    static constexpr operator_types operator_type = operator_types::min;\n    using error_type = no_error_type;\n};\n\ntemplate <typename Child>\nstruct abs : public internal_unary_node<Child>\n{\n    using error_type = no_error_type;\n    static constexpr operator_types operator_type = operator_types::abs;\n    static constexpr bool sign_exact = Child::sign_exact;\n    static constexpr bool non_negative = true;\n};\n\nstruct leaf\n{\n    static constexpr bool is_leaf = true;\n    static constexpr bool sign_exact = true;\n    static constexpr bool non_negative = false;\n    static constexpr operator_types operator_type = operator_types::no_op;\n    static constexpr operator_arities operator_arity = operator_arities::nullary;\n};\n\ntemplate <std::size_t Argn>\nstruct argument : public leaf\n{\n    static constexpr std::size_t argn = Argn;\n};\n\ntemplate <typename NumberType>\nstruct static_constant_interface : public leaf\n{\n    using value_type = NumberType;\n    static constexpr NumberType value = 0; //override\n    static constexpr std::size_t argn = 0;\n};\n\ntemplate <typename Node>\nusing is_leaf = boost::mp11::mp_bool<Node::is_leaf>;\n\ntemplate\n<\n    typename In,\n    typename Out,\n    template <typename> class Anchor = is_leaf,\n    bool IsBinary = In::operator_arity == operator_arities::binary,\n    bool AtAnchor = Anchor<In>::value\n>\nstruct post_order_impl;\n\ntemplate\n<\n    typename In,\n    typename Out,\n    template <typename> class Anchor,\n    bool IsBinary\n>\nstruct post_order_impl<In, Out, Anchor, IsBinary, true>\n{\n    using type = Out;\n};\n\ntemplate <typename In, typename Out, template <typename> class Anchor>\nstruct post_order_impl<In, Out, Anchor, true, false>\n{\n    using leftl = typename post_order_impl\n            <\n                typename In::left,\n                boost::mp11::mp_list<>,\n                Anchor\n            >::type;\n    using rightl = typename post_order_impl\n            <\n                typename In::right,\n                boost::mp11::mp_list<>,\n                Anchor\n            >::type;\n    using merged = boost::mp11::mp_append<Out, leftl, rightl>;\n    using type   =\n        boost::mp11::mp_unique<boost::mp11::mp_push_back<merged, In>>;\n};\n\ntemplate <typename In, typename Out, template <typename> class Anchor>\nstruct post_order_impl<In, Out, Anchor, false, false>\n{\n    using childl = typename post_order_impl\n            <\n                typename In::child,\n                boost::mp11::mp_list<>,\n                Anchor\n            >::type;\n    using merged = boost::mp11::mp_append<Out, childl>;\n    using type   =\n        boost::mp11::mp_unique<boost::mp11::mp_push_back<merged, In>>;\n};\n\ntemplate <typename In, template <typename> class Anchor = is_leaf>\nusing post_order =\n    typename post_order_impl<In, boost::mp11::mp_list<>, Anchor>::type;\n\ntemplate <typename Node, typename IsLeaf = is_leaf<Node>>\nstruct max_argn_impl;\n\ntemplate <typename Node> using max_argn = typename max_argn_impl<Node>::type;\n\ntemplate <typename Node>\nstruct max_argn_impl<Node, boost::mp11::mp_false>\n{\nprivate:\n    using children_list = boost::mp11::mp_rename<Node, boost::mp11::mp_list>;\n    using children_max_argn =\n        boost::mp11::mp_transform<max_argn, children_list>;\npublic:\n    using type = boost::mp11::mp_max_element\n        <\n            children_max_argn,\n            boost::mp11::mp_less\n        >;\n};\n\ntemplate <typename Node>\nstruct max_argn_impl<Node, boost::mp11::mp_true>\n{\n    using type = boost::mp11::mp_size_t<Node::argn>;\n};\n\nusing  _1 = argument<1>;\nusing  _2 = argument<2>;\nusing  _3 = argument<3>;\nusing  _4 = argument<4>;\nusing  _5 = argument<5>;\nusing  _6 = argument<6>;\nusing  _7 = argument<7>;\nusing  _8 = argument<8>;\nusing  _9 = argument<9>;\nusing _10 = argument<10>;\nusing _11 = argument<11>;\nusing _12 = argument<12>;\n\n}} // namespace detail::generic_robust_predicates\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_EXTENSIONS_GENERIC_ROBUST_PREDICATES_STRATEGIES_CARTESIAN_DETAIL_EXPRESSION_TREE_HPP\n", "meta": {"hexsha": "4ac3e558b075f8d56f526061cd23d55a1263b46e", "size": 7555, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/geometry/extensions/generic_robust_predicates/strategies/cartesian/detail/expression_tree.hpp", "max_stars_repo_name": "BoostGSoC20/geometry", "max_stars_repo_head_hexsha": "5b63bdc9086829c4c00bf9f5e23c664430acdd48", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-05-15T20:30:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T08:14:05.000Z", "max_issues_repo_path": "include/boost/geometry/extensions/generic_robust_predicates/strategies/cartesian/detail/expression_tree.hpp", "max_issues_repo_name": "Srutip04/geometry", "max_issues_repo_head_hexsha": "5b63bdc9086829c4c00bf9f5e23c664430acdd48", "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/generic_robust_predicates/strategies/cartesian/detail/expression_tree.hpp", "max_forks_repo_name": "Srutip04/geometry", "max_forks_repo_head_hexsha": "5b63bdc9086829c4c00bf9f5e23c664430acdd48", "max_forks_repo_licenses": ["BSL-1.0"], "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": 30.0996015936, "max_line_length": 109, "alphanum_fraction": 0.718861681, "num_tokens": 1763, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933535169629, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4920904466156932}}
{"text": "//////////////////////////////////////////////////////////////////////////////////\n// distribution::toolkit::distributions::gamma::derivative::log_unnormalized_pdf //\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_GAMMA_DERIVATIVE_LOG_UNNORMALIZED_PDF_HPP_ER_2009\n#define BOOST_STATISTICS_DETAIL_DISTRIBUTION_TOOLKIT_GAMMA_DERIVATIVE_LOG_UNNORMALIZED_PDF_HPP_ER_2009\n#include <cmath>\n#include <limits>\n#include <boost/math/distributions/gamma.hpp>\n#include <boost/math/policies/policy.hpp>\n\nnamespace boost{\nnamespace math{\n\ntemplate <class T, class P>\ninline T derivative_log_unnormalized_pdf(\n    const boost::math::gamma_distribution<T, P>& dist,\n    const T& x\n)\n{\n   BOOST_MATH_STD_USING  // for ADL of std functions\n\n   static const char* function\n        = \"log_unnormalized_pdf(const gamma_distribution<%1%>&, %1%)\";\n\n   T shape = dist.shape();\n   T scale = dist.scale();\n\n   T result;\n   if(false == boost::math::detail::check_gamma(\n    function, scale, shape, &result, P()))\n      return result;\n   if(false == boost::math::detail::check_gamma_x(function, x, &result, P()))\n      return result;\n\n   if(x == 0)\n   {\n      // TODO check. Also see log_unnormalized_pdf\n      return std::numeric_limits<T>::infinity();\n   }\n   static T one_ = static_cast<T>(1);\n   result = (shape - one_) / x - one_ / scale;\n   return result;\n} // derivative_log_unnormalized_pdf\n\n\n}// math\n}// boost\n\n#endif\n", "meta": {"hexsha": "342076317e0e0030bca0c6c3a56547cfabca3aba", "size": 1904, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "distribution_toolkit/boost/statistics/detail/distribution_toolkit/distributions/gamma/derivative_log_unnormalized_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/distributions/gamma/derivative_log_unnormalized_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/distributions/gamma/derivative_log_unnormalized_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": 34.6181818182, "max_line_length": 102, "alphanum_fraction": 0.5871848739, "num_tokens": 422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4920904360503213}}
{"text": "#include <armadillo>\n#include <boost/program_options.hpp>\n#include <HSMM.hpp>\n#include <Multivariate_Gaussian_emission.hpp>\n#include <random>\n\nusing namespace arma;\nusing namespace hsmm;\nusing namespace robotics::random;\nusing namespace std;\nnamespace po = boost::program_options;\n\n\n// MLE transition in the HMM case. This means self-transitions are allowed.\nmat getHmmTransitionFromLabels(const field<ivec>& labels_seq, int nstates) {\n    mat hmm_transition(nstates, nstates, fill::zeros);\n    for(const ivec &s : labels_seq)\n        for(int i = 0; i < s.n_elem - 1; i++)\n            hmm_transition(s(i), s(i + 1))++;\n\n    for(int i = 0; i < nstates; i++)\n        hmm_transition.row(i) = hmm_transition.row(i) / accu(\n                hmm_transition.row(i));\n    return hmm_transition;\n}\n\n// MLE categorical distribution over labels for the IID case.\nmat getMixtureModelTransitionFromLabels(const field<ivec>& labels_seq,\n        int nstates) {\n    mat transition(nstates, nstates, fill::zeros);\n    for(const ivec &s : labels_seq)\n        for(int i = 0; i < s.n_elem; i++)\n            transition.col(s(i)) += 1;\n\n    for(int i = 0; i < nstates; i++)\n        transition.row(i) = transition.row(i) / accu(transition.row(i));\n    return transition;\n}\n\n// Equivalent to np.fft.rfftfreq(512, 1.0 / 128.0) in Python.\nvec discreteFourierTransformSampleFrequencies() {\n    return linspace(0, 64, 257);\n}\n\nvec extract_frequency_features(vec input) {\n    vec nu = discreteFourierTransformSampleFrequencies();\n    uvec delta_band = find(nu > 0.4 && nu < 4.1);\n    uvec theta_band = find(nu > 5.9 && nu < 10.1);\n    uvec alpha_band = find(nu > 10 && nu < 15.1);\n    uvec all_bands = find(nu > 3.9 && nu < 40.1);\n\n    cx_mat t = fft(input);\n\n    // Ensuring the same size as np.fft.rfft(input).\n    t = t.head_rows(input.n_elem / 2 + 1);\n    mat norm = abs(t);\n    norm = norm % norm;\n    vec features = {accu(norm.elem(delta_band)), accu(norm.elem(theta_band)),\n            accu(norm.elem(alpha_band)), accu(norm.elem(all_bands))};\n    return features;\n}\n\nvec extract_eeg_features(vec eeg) {\n    return extract_frequency_features(eeg).head_rows(3);\n}\n\nvec extract_emg_features(vec emg) {\n    return extract_frequency_features(emg).tail_rows(1);\n}\n\nfield<vec> getFeatureVectors(const mat& eeg1, const mat& eeg2, const mat& emg) {\n    int nobs = eeg1.n_cols;\n    assert(nobs == eeg2.n_cols);\n    assert(nobs == emg.n_cols);\n    field<vec> features(nobs);\n    for(int i = 0; i < nobs; i++) {\n        vec f = join_vert(extract_eeg_features(eeg1.col(i)),\n                extract_eeg_features(eeg2.col(i)));\n        features(i) = join_vert(f, extract_emg_features(emg.col(i)));\n    }\n    return features;\n}\n\nivec predict_labels_iid(shared_ptr<MultivariateGaussianEmission> e,\n        const mat& test_input, const vec& class_prior) {\n    assert(class_prior.n_elem == e->getNumberStates());\n    ivec ret(test_input.n_cols);\n    double seq_loglikelihood = 0;\n    for(int i = 0; i < test_input.n_cols; i++) {\n        vec loglikelihoods(e->getNumberStates());\n        for(int j = 0; j < e->getNumberStates(); j++)\n            loglikelihoods(j) = e->loglikelihood(j,\n                    test_input.col(i)) + log(class_prior(j));\n        ret(i) = (int) loglikelihoods.index_max();\n        seq_loglikelihood += logsumexp(loglikelihoods);\n    }\n    cout << \"IIDtestloglikelihood \" << seq_loglikelihood << endl;\n    return ret;\n}\n\nivec predict_labels_from_filtering(const mat& filtering_state_marginals) {\n    ivec ret(filtering_state_marginals.n_cols);\n    for(int i = 0; i < ret.n_elem; i++)\n        ret(i) = (int) filtering_state_marginals.col(i).index_max();\n    return ret;\n}\n\nvector<NormalDist> get_normal_distributions(int nstates, int ndurations,\n        int min_duration, int ndimension) {\n    mt19937 gen(0);\n    vector<NormalDist> states;\n    vector<vec> samples;\n    vector<int> labels;\n    for(int i = 0; i < nstates; i++) {\n        vec mean = ones<vec>(ndimension) * i * 10;\n        mat cov = eye(ndimension, ndimension);\n        NormalDist a(mean, cov);\n        states.push_back(a);\n\n        // Generating toy data.\n        int nsamples = 100;\n        vector<vec> s = sample_multivariate_normal(gen, a, nsamples);\n        vector<int> l = conv_to<vector<int>>::from(ones<ivec>(nsamples) * i);\n        samples.insert(samples.end(), s.begin(), s.end());\n        labels.insert(labels.end(), l.begin(), l.end());\n    }\n\n    // Toy data handling.\n    ivec labels_vec = conv_to<ivec>::from(labels);\n    field<vec> obs_field(samples.size());\n    for(int i = 0; i < samples.size(); i++)\n        obs_field(i) = samples.at(i);\n\n    // Debug\n    shared_ptr<MultivariateGaussianEmission> emission(\n            new MultivariateGaussianEmission(states));\n    OnlineHSMMRunlengthBased model(emission, nstates, ndurations, min_duration);\n    for(int i = 0; i < samples.size(); i++)\n        model.addNewObservation(samples.at(i));\n    return states;\n}\n\nint main(int argc, char *argv[]) {\n    po::options_description desc(\"Options\");\n    vector<string> input_features, input_labels;\n    desc.add_options()\n        (\"help,h\", \"Produce help message\")\n        (\"input,i\", po::value<vector<string>>(&input_features)->multitoken(),\n                \"Path to the (multiple) input features\")\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        (\"labels,l\", po::value<vector<string>>(&input_labels)->multitoken(),\n                \"Path to input labels\")\n        (\"nodur\", \"Flag to deactivate the learning of durations\")\n        (\"iid\", \"Flag to deactivate the learning of transitions\")\n        (\"alphadurprior\", po::value<double>(),\n                \"Alpha for Dirichlet prior for the duration\")\n        (\"filteringprediction\", po::value<string>(), \"Path to predicted labels\"\n                \" based on the filtering distribution over states\")\n        (\"mr\", po::value<string>(), \"Runlength marginals output filename\")\n        (\"ms\", po::value<string>(), \"States marginals output filename\")\n        (\"ms2\", po::value<string>(), \"States marginals output filename. This \"\n                \"one is based on the residual time posterior instead of the \"\n                \"runlength posterior\")\n        (\"md\", po::value<string>(), \"Duration marginals output filename\")\n        (\"ml\", po::value<string>(), \"Remaining runlength marginals output\"\n                \" filename\")\n        (\"leaveoneout\", po::value<int>(), \"Index of the sequence that will be\"\n                \" left out for validation\")\n        (\"savefiletype\", po::value<string>()->default_value(\"arma_binary\"),\n                \"File type to save the matrices after inference\");\n    assert(input_features.size() == input_labels.size());\n    vector<string> required_fields = {\"input\", \"labels\", \"leaveoneout\",\n            \"nstates\", \"mindur\", \"ndur\"};\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    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    int nstates = vm[\"nstates\"].as<int>();\n    int ndurations = vm[\"ndur\"].as<int>();\n    int leaveoneout = vm[\"leaveoneout\"].as<int>();\n    int min_duration = vm[\"mindur\"].as<int>();\n    int nseq = input_features.size();\n\n    field<ivec> labels_seq(nseq - 1);\n    field<mat> obs_seq(nseq - 1);\n    ivec test_labels;\n    mat test_obs;\n    int train_idx = 0;\n    for(int i = 0; i < nseq; i++) {\n        if (i == leaveoneout) {\n            test_obs.load(input_features[i], raw_ascii);\n            test_labels.load(input_labels[i], raw_ascii);\n        }\n        else {\n            labels_seq(train_idx).load(input_labels[i], raw_ascii);\n            obs_seq(train_idx).load(input_features[i], raw_ascii);\n            train_idx++;\n        }\n    }\n    assert(train_idx == nseq - 1);\n    int ndimension = test_obs.n_rows;\n\n    // Creating normal distributions for the emission process.\n    vector<NormalDist> states = get_normal_distributions(nstates, ndurations,\n            min_duration, ndimension);\n\n    // Creating the emission process.\n    shared_ptr<MultivariateGaussianEmission> emission(\n            new MultivariateGaussianEmission(states));\n\n    // Training the emission based on the labels.\n    emission->fitFromLabels(obs_seq, labels_seq);\n\n    // Creating the online HSMM whose emission process doesnt take into account\n    // the total segment duration. The pmfs are uniformly initialized.\n    OnlineHSMMRunlengthBased model(emission, nstates, ndurations, min_duration);\n\n    // Setting a Dirichlet prior over the durations.\n    if (vm.count(\"alphadurprior\")) {\n        mat alphas = ones<mat>(nstates, ndurations) *\n            vm[\"alphadurprior\"].as<double>();\n        model.setDurationDirichletPrior(alphas);\n    }\n\n    // Learning the HSMM parameters from the labels.\n    if (!vm.count(\"iid\")) {\n        if (min_duration == 1 && ndurations == 1)\n            model.setTransition(getHmmTransitionFromLabels(labels_seq,nstates));\n        else\n            model.setTransitionFromLabels(labels_seq);\n    }\n    else\n        model.setTransition(getMixtureModelTransitionFromLabels(labels_seq,\n                    nstates));\n    if (!vm.count(\"nodur\"))\n        model.setDurationFromLabels(labels_seq);\n\n    if (vm.count(\"output\")) {\n        ofstream output_params(vm[\"output\"].as<string>());\n        nlohmann::json current_params = model.to_stream();\n        output_params << std::setw(4) << current_params << endl;\n        output_params.close();\n    }\n    mat runlength_marginals;\n    mat state_marginals, state_marginals_2;\n    mat remaining_runlength_marginals;\n    mat duration_marginals;\n\n    if (vm.count(\"mr\"))\n        runlength_marginals = zeros<mat>(min_duration + ndurations - 1,\n                test_obs.n_cols);\n    if (vm.count(\"ms\") || vm.count(\"filteringprediction\"))\n        state_marginals = zeros<mat>(nstates, test_obs.n_cols);\n    if (vm.count(\"ms2\"))\n        state_marginals_2 = zeros<mat>(nstates, test_obs.n_cols);\n    if (vm.count(\"md\"))\n        duration_marginals = zeros<mat>(ndurations, test_obs.n_cols);\n    if (vm.count(\"ml\"))\n        remaining_runlength_marginals = zeros<mat>(\n                min_duration + ndurations - 1, test_obs.n_cols);\n    vec loglikelihoods(test_obs.n_cols);\n    for(int i = 0; i < test_obs.n_cols; i++) {\n        loglikelihoods(i) = model.oneStepAheadLoglikelihood(test_obs.col(i));\n        model.addNewObservation(test_obs.col(i));\n        if (vm.count(\"mr\"))\n            runlength_marginals.col(i) = model.getRunlengthMarginal();\n        if (vm.count(\"ms\") || vm.count(\"filteringprediction\"))\n            state_marginals.col(i) = model.getStateMarginal();\n        if (vm.count(\"ms2\"))\n            state_marginals_2.col(i) = model.getStateMarginal2();\n        if (vm.count(\"ml\"))\n            remaining_runlength_marginals.col(i) =\n                    model.getResidualTimeMarginal();\n    }\n\n    // The test log-likelihood.\n    cout << accu(loglikelihoods) << endl;\n\n    // Saving the filtering inferences.\n    auto file_type = vm[\"savefiletype\"].as<string>().compare(\n            \"arma_binary\") == 0 ? arma_binary : raw_ascii;\n    if (vm.count(\"mr\"))\n        runlength_marginals.save(vm[\"mr\"].as<string>(), file_type);\n    if (vm.count(\"ms\"))\n        state_marginals.save(vm[\"ms\"].as<string>(), file_type);\n    if (vm.count(\"ms2\"))\n        state_marginals_2.save(vm[\"ms2\"].as<string>(), file_type);\n    if (vm.count(\"ml\"))\n        remaining_runlength_marginals.save(vm[\"ml\"].as<string>(), file_type);\n    if (vm.count(\"filteringprediction\")) {\n        ivec filtering_prediction = predict_labels_from_filtering(\n                state_marginals);\n        filtering_prediction.save(vm[\"filteringprediction\"].as<string>(),\n                raw_ascii);\n    }\n    return 0;\n}\n", "meta": {"hexsha": "470b12f57d1c695469ec06b4a66b048588d32190", "size": 12114, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/promps_hsmm_sleep_data.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_sleep_data.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_sleep_data.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": 39.0774193548, "max_line_length": 80, "alphanum_fraction": 0.628694073, "num_tokens": 3044, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118221, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.49209043076763503}}
{"text": "#include \"util/coordinate_calculation.hpp\"\n\n#include \"util/string_util.hpp\"\n#include \"util/trigonometry_table.hpp\"\n\n#include <boost/assert.hpp>\n#include <boost/math/constants/constants.hpp>\n\n#include <cmath>\n\n#include <limits>\n\nnamespace osrm\n{\nnamespace util\n{\nnamespace coordinate_calculation\n{\n\ndouble haversineDistance(const int lat1, const int lon1, const int lat2, const int lon2)\n{\n    BOOST_ASSERT(lat1 != std::numeric_limits<int>::min());\n    BOOST_ASSERT(lon1 != std::numeric_limits<int>::min());\n    BOOST_ASSERT(lat2 != std::numeric_limits<int>::min());\n    BOOST_ASSERT(lon2 != std::numeric_limits<int>::min());\n    const double lt1 = lat1 / COORDINATE_PRECISION;\n    const double ln1 = lon1 / COORDINATE_PRECISION;\n    const double lt2 = lat2 / COORDINATE_PRECISION;\n    const double ln2 = lon2 / COORDINATE_PRECISION;\n    const double dlat1 = lt1 * (RAD);\n\n    const double dlong1 = ln1 * (RAD);\n    const double dlat2 = lt2 * (RAD);\n    const double dlong2 = ln2 * (RAD);\n\n    const double dlong = dlong1 - dlong2;\n    const double dlat = dlat1 - dlat2;\n\n    const double aharv = std::pow(std::sin(dlat / 2.0), 2.0) +\n                         std::cos(dlat1) * std::cos(dlat2) * std::pow(std::sin(dlong / 2.), 2);\n    const double charv = 2. * std::atan2(std::sqrt(aharv), std::sqrt(1.0 - aharv));\n    return EARTH_RADIUS * charv;\n}\n\ndouble haversineDistance(const FixedPointCoordinate coordinate_1,\n                         const FixedPointCoordinate coordinate_2)\n{\n    return haversineDistance(coordinate_1.lat, coordinate_1.lon, coordinate_2.lat,\n                             coordinate_2.lon);\n}\n\ndouble greatCircleDistance(const FixedPointCoordinate coordinate_1,\n                           const FixedPointCoordinate coordinate_2)\n{\n    return greatCircleDistance(coordinate_1.lat, coordinate_1.lon, coordinate_2.lat,\n                               coordinate_2.lon);\n}\n\ndouble greatCircleDistance(const int lat1, const int lon1, const int lat2, const int lon2)\n{\n    BOOST_ASSERT(lat1 != std::numeric_limits<int>::min());\n    BOOST_ASSERT(lon1 != std::numeric_limits<int>::min());\n    BOOST_ASSERT(lat2 != std::numeric_limits<int>::min());\n    BOOST_ASSERT(lon2 != std::numeric_limits<int>::min());\n\n    const double float_lat1 = (lat1 / COORDINATE_PRECISION) * RAD;\n    const double float_lon1 = (lon1 / COORDINATE_PRECISION) * RAD;\n    const double float_lat2 = (lat2 / COORDINATE_PRECISION) * RAD;\n    const double float_lon2 = (lon2 / COORDINATE_PRECISION) * RAD;\n\n    const double x_value = (float_lon2 - float_lon1) * std::cos((float_lat1 + float_lat2) / 2.0);\n    const double y_value = float_lat2 - float_lat1;\n    return std::hypot(x_value, y_value) * EARTH_RADIUS;\n}\n\ndouble perpendicularDistance(const FixedPointCoordinate source_coordinate,\n                             const FixedPointCoordinate target_coordinate,\n                             const FixedPointCoordinate query_location)\n{\n    double ratio;\n    FixedPointCoordinate nearest_location;\n\n    return perpendicularDistance(source_coordinate, target_coordinate, query_location,\n                                 nearest_location, ratio);\n}\n\ndouble perpendicularDistance(const FixedPointCoordinate segment_source,\n                             const FixedPointCoordinate segment_target,\n                             const FixedPointCoordinate query_location,\n                             FixedPointCoordinate &nearest_location,\n                             double &ratio)\n{\n    using namespace coordinate_calculation;\n\n    return perpendicularDistanceFromProjectedCoordinate(\n        segment_source, segment_target, query_location,\n        {mercator::latToY(query_location.lat / COORDINATE_PRECISION),\n         query_location.lon / COORDINATE_PRECISION},\n        nearest_location, ratio);\n}\n\ndouble\nperpendicularDistanceFromProjectedCoordinate(const FixedPointCoordinate source_coordinate,\n                                             const FixedPointCoordinate target_coordinate,\n                                             const FixedPointCoordinate query_location,\n                                             const std::pair<double, double> projected_coordinate)\n{\n    double ratio;\n    FixedPointCoordinate nearest_location;\n\n    return perpendicularDistanceFromProjectedCoordinate(source_coordinate, target_coordinate,\n                                                        query_location, projected_coordinate,\n                                                        nearest_location, ratio);\n}\n\ndouble\nperpendicularDistanceFromProjectedCoordinate(const FixedPointCoordinate segment_source,\n                                             const FixedPointCoordinate segment_target,\n                                             const FixedPointCoordinate query_location,\n                                             const std::pair<double, double> projected_coordinate,\n                                             FixedPointCoordinate &nearest_location,\n                                             double &ratio)\n{\n    using namespace coordinate_calculation;\n\n    BOOST_ASSERT(query_location.IsValid());\n\n    // initialize values\n    const double x = projected_coordinate.first;\n    const double y = projected_coordinate.second;\n    const double a = mercator::latToY(segment_source.lat / COORDINATE_PRECISION);\n    const double b = segment_source.lon / COORDINATE_PRECISION;\n    const double c = mercator::latToY(segment_target.lat / COORDINATE_PRECISION);\n    const double d = segment_target.lon / COORDINATE_PRECISION;\n    double p, q /*,mX*/, new_y;\n    if (std::abs(a - c) > std::numeric_limits<double>::epsilon())\n    {\n        const double m = (d - b) / (c - a); // slope\n        // Projection of (x,y) on line joining (a,b) and (c,d)\n        p = ((x + (m * y)) + (m * m * a - m * b)) / (1.0 + m * m);\n        q = b + m * (p - a);\n    }\n    else\n    {\n        p = c;\n        q = y;\n    }\n    new_y = (d * p - c * q) / (a * d - b * c);\n\n    // discretize the result to coordinate precision. it's a hack!\n    if (std::abs(new_y) < (1.0 / COORDINATE_PRECISION))\n    {\n        new_y = 0.0;\n    }\n\n    // compute ratio\n    ratio = static_cast<double>((p - new_y * a) /\n                                c); // These values are actually n/m+n and m/m+n , we need\n    // not calculate the explicit values of m an n as we\n    // are just interested in the ratio\n    if (std::isnan(ratio))\n    {\n        ratio = (segment_target == query_location ? 1.0 : 0.0);\n    }\n    else if (std::abs(ratio) <= std::numeric_limits<double>::epsilon())\n    {\n        ratio = 0.0;\n    }\n    else if (std::abs(ratio - 1.0) <= std::numeric_limits<double>::epsilon())\n    {\n        ratio = 1.0;\n    }\n\n    // compute nearest location\n    BOOST_ASSERT(!std::isnan(ratio));\n    if (ratio <= 0.0)\n    {\n        nearest_location = segment_source;\n    }\n    else if (ratio >= 1.0)\n    {\n        nearest_location = segment_target;\n    }\n    else\n    {\n        // point lies in between\n        nearest_location.lat = static_cast<int>(mercator::yToLat(p) * COORDINATE_PRECISION);\n        nearest_location.lon = static_cast<int>(q * COORDINATE_PRECISION);\n    }\n    BOOST_ASSERT(nearest_location.IsValid());\n\n    const double approximate_distance = greatCircleDistance(query_location, nearest_location);\n    BOOST_ASSERT(0.0 <= approximate_distance);\n    return approximate_distance;\n}\n\ndouble degToRad(const double degree)\n{\n    using namespace boost::math::constants;\n    return degree * (pi<double>() / 180.0);\n}\n\ndouble radToDeg(const double radian)\n{\n    using namespace boost::math::constants;\n    return radian * (180.0 * (1. / pi<double>()));\n}\n\ndouble bearing(const FixedPointCoordinate first_coordinate,\n               const FixedPointCoordinate second_coordinate)\n{\n    const double lon_diff =\n        second_coordinate.lon / COORDINATE_PRECISION - first_coordinate.lon / COORDINATE_PRECISION;\n    const double lon_delta = degToRad(lon_diff);\n    const double lat1 = degToRad(first_coordinate.lat / COORDINATE_PRECISION);\n    const double lat2 = degToRad(second_coordinate.lat / COORDINATE_PRECISION);\n    const double y = std::sin(lon_delta) * std::cos(lat2);\n    const double x =\n        std::cos(lat1) * std::sin(lat2) - std::sin(lat1) * std::cos(lat2) * std::cos(lon_delta);\n    double result = radToDeg(std::atan2(y, x));\n    while (result < 0.0)\n    {\n        result += 360.0;\n    }\n\n    while (result >= 360.0)\n    {\n        result -= 360.0;\n    }\n    return result;\n}\n\ndouble computeAngle(const FixedPointCoordinate first,\n                    const FixedPointCoordinate second,\n                    const FixedPointCoordinate third)\n{\n    using namespace boost::math::constants;\n    using namespace coordinate_calculation;\n\n    const double v1x = (first.lon - second.lon) / COORDINATE_PRECISION;\n    const double v1y = mercator::latToY(first.lat / COORDINATE_PRECISION) -\n                       mercator::latToY(second.lat / COORDINATE_PRECISION);\n    const double v2x = (third.lon - second.lon) / COORDINATE_PRECISION;\n    const double v2y = mercator::latToY(third.lat / COORDINATE_PRECISION) -\n                       mercator::latToY(second.lat / COORDINATE_PRECISION);\n\n    double angle = (atan2_lookup(v2y, v2x) - atan2_lookup(v1y, v1x)) * 180. / pi<double>();\n\n    while (angle < 0.)\n    {\n        angle += 360.;\n    }\n\n    return angle;\n}\n\nnamespace mercator\n{\ndouble yToLat(const double value)\n{\n    using namespace boost::math::constants;\n\n    return 180. * (1. / pi<long double>()) *\n           (2. * std::atan(std::exp(value * pi<double>() / 180.)) - half_pi<double>());\n}\n\ndouble latToY(const double latitude)\n{\n    using namespace boost::math::constants;\n\n    return 180. * (1. / pi<double>()) *\n           std::log(std::tan((pi<double>() / 4.) + latitude * (pi<double>() / 180.) / 2.));\n}\n} // ns mercato // ns mercatorr\n} // ns coordinate_calculation\n} // ns util\n} // ns osrm\n", "meta": {"hexsha": "61fd77cab9c816ad49894aaa3c1555598f0c493c", "size": 9877, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/util/coordinate_calculation.cpp", "max_stars_repo_name": "mortada/osrm-backend", "max_stars_repo_head_hexsha": "aae02cd1be7e99eb75117c7d8c9f39b858ad9019", "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/util/coordinate_calculation.cpp", "max_issues_repo_name": "mortada/osrm-backend", "max_issues_repo_head_hexsha": "aae02cd1be7e99eb75117c7d8c9f39b858ad9019", "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/util/coordinate_calculation.cpp", "max_forks_repo_name": "mortada/osrm-backend", "max_forks_repo_head_hexsha": "aae02cd1be7e99eb75117c7d8c9f39b858ad9019", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-09-20T00:55:14.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-20T00:55:14.000Z", "avg_line_length": 35.5287769784, "max_line_length": 99, "alphanum_fraction": 0.6281259492, "num_tokens": 2341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681195338728, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.49208304877772613}}
{"text": "#ifndef RLSS_DISCRETESEARCH_HPP\n#define RLSS_DISCRETESEARCH_HPP\n\n#include <rlss/internal/Util.hpp>\n#include <rlss/OccupancyGrid.hpp>\n#include <rlss/CollisionShapes/CollisionShape.hpp>\n#include <libMultiRobotPlanning/a_star.hpp>\n#include <boost/functional/hash/hash.hpp>\n#include <optional>\n#include <iostream>\n\n\nnamespace rlss {\n\nnamespace internal {\n\n\n\ntemplate<typename T, unsigned int DIM>\nstd::optional<StdVectorVectorDIM<T, DIM>> discreteSearch(\n            const typename OccupancyGrid<T, DIM>::Coordinate& start_coordinate,\n            const typename OccupancyGrid<T, DIM>::Coordinate& goal_coordinate,\n            const OccupancyGrid<T, DIM>& occupancy_grid,\n            const AlignedBox<T, DIM>& workspace,\n            std::shared_ptr<rlss::CollisionShape<T,DIM>> collision_shape\n) {\n    using VectorDIM = VectorDIM<T, DIM>;\n    using OccupancyGrid = OccupancyGrid<T, DIM>;\n    using AlignedBox = AlignedBox<T, DIM>;\n    using StdVectorVectorDIM = StdVectorVectorDIM<T, DIM>;\n    using Index = typename OccupancyGrid::Index;\n    using Coordinate = typename OccupancyGrid::Coordinate;\n    using CollisionShape = rlss::CollisionShape<T, DIM>;\n\n\n    struct State {\n        Coordinate position;\n        Index dir;\n        explicit State(Coordinate c) : position(c), dir(Index::Zero()) {}\n        State(Coordinate c, Index d) : position(c), dir(d) {}\n        bool operator==(const State& rhs) const {\n            return position == rhs.position && dir == rhs.dir;\n        }\n    };\n\n    struct StateHasher {\n        std::size_t operator()(const State& s) const {\n            std::size_t seed = 0;\n            for(unsigned int d = 0; d < DIM; d++) {\n                boost::hash_combine(seed, s.position(d));\n                boost::hash_combine(seed, s.dir(d));\n            }\n            return seed;\n        }\n    };\n\n    enum class Action {\n        FORWARD,\n        ROTATE,\n        ROTATEFORWARD\n    };\n\n    class Environment {\n    public:\n\n        Environment(\n            const OccupancyGrid& occ, \n            const AlignedBox& works, \n            std::shared_ptr<CollisionShape> cols,\n            const Coordinate& goal\n            )\n            : m_occupancy_grid(occ),\n              m_workspace(works),\n              m_collision_shape(cols),\n              m_goal(goal)\n        {}\n\n        // get distance of current state pos to goal pos\n        int admissibleHeuristic(const State& s) {\n            int h = 0;\n            Index state_idx = m_occupancy_grid.getIndex(s.position);\n            Index goal_idx = m_occupancy_grid.getIndex(m_goal);\n            return (state_idx - goal_idx).norm();\n//            for(unsigned int d = 0; d < DIM; d++) {\n//                h += std::abs(state_idx(d) - goal_idx(d));\n//            }\n//            return h;\n        }\n\n        // check if current pos is the goal pos\n        bool isSolution(const State& s) { return s.position == m_goal; }\n\n        // get neighbouring voxels\n        void getNeighbors(\n            const State& s,\n            std::vector<libMultiRobotPlanning::Neighbor<State, Action, int> >& \n                neighbors) {\n\n            neighbors.clear();\n\n            Coordinate s_center = m_occupancy_grid.getCenter(s.position);\n            Index s_idx = m_occupancy_grid.getIndex(s_center);\n\n            if(this->actionValid(s.position, m_goal)) {\n                neighbors.emplace_back(\n                    State(m_goal, Index::Zero()), \n                    Action::ROTATEFORWARD, \n                    1 + (s_idx - m_occupancy_grid.getIndex(m_goal))\n                                  .norm()\n//                                .cwiseAbs().sum()\n                );\n            }\n\n            if(s_center != s.position) { // get into grid\n                if(this->actionValid(s.position, s_center)) {\n                    neighbors.emplace_back(\n                        State(s_center, Index::Zero()), \n                        Action::ROTATEFORWARD,\n                        2\n                    );\n                }\n\n                std::vector<Index> neigh_indexes\n                        = m_occupancy_grid.getNeighbors(s_idx);\n\n                for(const auto& neigh_idx: neigh_indexes) {\n                    auto neigh_center = m_occupancy_grid.getCenter(neigh_idx);\n                    if(this->actionValid(s.position, neigh_center)) {\n                        neighbors.emplace_back(\n                                State(neigh_center, Index::Zero()),\n                                Action::ROTATEFORWARD,\n                                2\n                        );\n                    }\n                }\n            } else {\n                if(s.dir == Index::Zero()) {\n                    std::vector<Index> neigh_indexes\n                            = m_occupancy_grid.getNeighbors(s_idx);\n                    for(const auto& neigh_idx : neigh_indexes) {\n                        if (this->actionValid(s_idx, neigh_idx)) {\n                            neighbors.emplace_back(\n                                State(\n                                    m_occupancy_grid.getCenter(neigh_idx),\n                                    neigh_idx - s_idx\n                                ),\n                                Action::FORWARD,\n                                1\n                            );\n                        }\n                    }\n                } else {\n                    Index idx = s_idx + s.dir;\n                    if(this->actionValid(s_idx, idx)) {\n                        neighbors.emplace_back(\n                            State(m_occupancy_grid.getCenter(idx), s.dir), \n                            Action::FORWARD, \n                            1\n                        );\n                    }\n\n                    for(unsigned int d = 0; d < DIM; d++) {\n                        if(s.dir(d) == 0) {\n                            Index dir = Index::Zero();\n                            dir(d) = 1;\n                            neighbors.emplace_back(\n                                State(m_occupancy_grid.getCenter(s_idx), dir), \n                                Action::ROTATE, \n                                1\n                            );\n                            dir(d) = -1;\n                            neighbors.emplace_back(\n                                State(m_occupancy_grid.getCenter(s_idx), dir), \n                                Action::ROTATE, \n                                1\n                            );\n                        }\n                    }\n                }\n            }\n\n            \n        }\n\n        void onExpandNode(const State& /*s*/, int /*fScore*/, int /*gScore*/) {}\n\n        void onDiscover(const State& /*s*/, int /*fScore*/, int /*gScore*/) {}\n\n    public:\n\n        bool actionValid(const Coordinate& start, const Coordinate& end) {\n            return rlss::internal::segmentValid<T, DIM>(\n                    m_occupancy_grid,\n                    m_workspace,\n                    start,\n                    end,\n                    m_collision_shape\n            );\n        }\n\n\n        bool actionValid(const Index& from_idx, const Index& to_idx) {\n            Coordinate from_center = m_occupancy_grid.getCenter(from_idx);\n            Coordinate to_center = m_occupancy_grid.getCenter(to_idx);\n\n            return this->actionValid(from_center, to_center);\n        }\n\n\n        bool positionValid(const Coordinate& pos) {\n            AlignedBox robot_box = m_collision_shape->boundingBox(pos);\n            return !m_occupancy_grid.isOccupied(robot_box)\n                    && m_workspace.contains(robot_box);\n        }\n\n        bool indexValid(const Index& idx) {\n            Coordinate center = m_occupancy_grid.getCenter(idx);\n            return this->positionValid(center);\n        }\n\n    private:\n        const OccupancyGrid& m_occupancy_grid;\n        const AlignedBox& m_workspace;\n        std::shared_ptr<CollisionShape> m_collision_shape;\n        const Coordinate& m_goal;\n    };\n\n    Environment env(\n            occupancy_grid,\n            workspace,\n            collision_shape,\n            goal_coordinate\n    );\n    libMultiRobotPlanning::AStar<State, Action, int, Environment, StateHasher>\n            astar(env);\n    libMultiRobotPlanning::PlanResult<State, Action, int> solution;\n\n    if(env.positionValid(start_coordinate)) {\n        State start_state(start_coordinate);\n        bool success = astar.search(start_state, solution);\n        if(!success) {\n            return std::nullopt;\n        }\n        \n        StdVectorVectorDIM segments;\n        segments.push_back(solution.states[0].first.position);\n        for(std::size_t i = 0; i < solution.actions.size(); i++) {\n            std::string action_text;\n            if(solution.actions[i].first == Action::ROTATE) {\n                action_text = \"ROTATE\";\n            } else if(solution.actions[i].first == Action::FORWARD) {\n                action_text = \"FORWARD\";\n            } else if(solution.actions[i].first == Action::ROTATEFORWARD) {\n                action_text = \"ROTATEFORWARD\";\n            }\n            debug_message(solution.states[i].first.position.transpose(),\n                    \",\", solution.states[i].first.dir.transpose(), \" > \",\n                    solution.states[i+1].first.position.transpose(), \",\",\n                    solution.states[i+1].first.dir.transpose(), \", action: \",\n                      action_text);\n            if(solution.actions[i].first == Action::ROTATE) {\n                segments.push_back(solution.states[i+1].first.position);\n            } else if (solution.actions[i].first == Action::ROTATEFORWARD) {\n                if(i != 0\n                    && segments.back() != solution.states[i].first.position)\n                    segments.push_back(solution.states[i].first.position);\n                if(i != solution.actions.size() - 1\n                    && segments.back() != solution.states[i+1].first.position)\n                    segments.push_back(solution.states[i+1].first.position);\n            }\n        }\n        segments.push_back(solution.states.back().first.position);\n\n        return segments;\n    }\n\n    return std::nullopt;\n}\n\n\n} // namespace internal\n} // namespace rlss\n\n#endif // RLSS_DISCRETESEARCH_HPP", "meta": {"hexsha": "f2a43d08bfd3a45f07d5619ab0ba9d2804b58c14", "size": 10187, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/rlss/internal/DiscreteSearch.hpp", "max_stars_repo_name": "sieniven/rlss", "max_stars_repo_head_hexsha": "b1f7ff1abf316242a0644b76559ad921fbca3099", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/rlss/internal/DiscreteSearch.hpp", "max_issues_repo_name": "sieniven/rlss", "max_issues_repo_head_hexsha": "b1f7ff1abf316242a0644b76559ad921fbca3099", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/rlss/internal/DiscreteSearch.hpp", "max_forks_repo_name": "sieniven/rlss", "max_forks_repo_head_hexsha": "b1f7ff1abf316242a0644b76559ad921fbca3099", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.8697183099, "max_line_length": 80, "alphanum_fraction": 0.4996564249, "num_tokens": 1996, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6224593452091672, "lm_q1q2_score": 0.49207298452712006}}
{"text": "/*--\n    Solver.cpp  \n\n    This file is part of the Cornucopia curve sketching library.\n    Copyright (C) 2010 Ilya Baran (baran37@gmail.com)\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"Solver.h\"\n#include <Eigen/Cholesky>\n#include <iostream> //TODO: TMP\n#include <cmath>\n\nusing namespace std;\nusing namespace Eigen;\nNAMESPACE_Cornu\n\nLSSolver::LSSolver(LSProblem *problem, const vector<LSBoxConstraint> &constraints)\n: _problem(problem), _constraints(constraints), _damping(1.), _maxIter(100),\n  _increaseDampingAfter(0), _dampingIncreaseFactor(1.)\n{\n};\n\nVectorXd LSSolver::solve(const VectorXd &guess, bool *is_valid)\n{\n\tif (is_valid != nullptr)\n\t\t*is_valid = true;\n\n    VectorXd best;\n    double bestError = 1e100;\n    VectorXd x = guess;\n    LSEvalData *evalData = _problem->createEvalData();\n\n    set<LSBoxConstraint> activeSet = _clamp(x);\n\n    VectorXd delta;\n    int iter;\n    for(iter = 0; iter < _maxIter; ++iter)\n    {\n        if(iter > _increaseDampingAfter)\n            _damping *= _dampingIncreaseFactor;\n        _problem->eval(x, evalData);\n\n        double error = evalData->error();\n        //printf(\"Iter = %d, error = %lf\\n\", iter, error);\n        if(error < bestError)\n        {\n            bestError = error;\n            best = x;\n\n            if(error < 1e-10)\n                break;\n        }\n\n        set<LSBoxConstraint> prevActiveSet = activeSet;\n        evalData->solveForDelta(_damping, delta, activeSet);\n\n\t\tdouble delta_norm = delta.squaredNorm();\n\t\tif (isnan(delta_norm)) {\n\t\t\tif (is_valid != nullptr)\n\t\t\t\t*is_valid = false;\n\t\t\tbreak;\n\t\t}\n\n\t\tif(delta_norm < 1e-14)\n            break;\n\n        int newConstraint = _project(x, delta, prevActiveSet);\n\n        if(newConstraint != -1)\n            activeSet.insert(_constraints[newConstraint]);\n\n        x += delta;\n\n        int halvings = 0;\n        while(_problem->error(x, evalData) > error && delta.squaredNorm() > 1e-8)\n        {\n            //printf(\"Halving\\n\");\n            delta *= 0.5;\n            x -= delta;\n            ++halvings;\n        }\n        if(halvings > 0) //halve again -- won't hurt and may actually help\n        {\n            delta *= 0.5;\n            x -= delta;\n        }\n    }\n\n    double error = _problem->error(x, evalData);\n    if(iter > 5)\n        Debugging::get()->printf(\"After %d iterations, error = %lf\", iter, sqrt(error));\n    if(error < bestError)\n    {\n        best = x;\n    }\n\n    delete evalData;\n    return best;\n}\n\nset<LSBoxConstraint> LSSolver::_clamp(VectorXd &x)\n{\n    set<LSBoxConstraint> out;\n    for(int i = 0; i < (int)_constraints.size(); ++i)\n    {\n        const LSBoxConstraint &c = _constraints[i];\n        if(c.sign == 0 || (x[c.index] - c.value) * c.sign < 0.)\n        {\n            x[c.index] = c.value;\n            out.insert(c);\n            //cout << \"Clamping constraint \" << i << endl;\n        }\n    }\n    return out;\n}\n\nint LSSolver::_project(const VectorXd &from, VectorXd &delta, const set<LSBoxConstraint> &activeSet)\n{\n    int closestConstraint = -1;\n    double minScale = 1.;\n\n    for(int i = 0; i < (int)_constraints.size(); ++i)\n    {\n        const LSBoxConstraint &c = _constraints[i];\n\n        if(c.sign == 0)\n            delta[c.index] = 0; //just in case\n\n        if(activeSet.count(c))\n            continue; //already constrained\n        \n        double scale = (c.value - from[c.index]) / delta[c.index];\n\n        if((from[c.index] + delta[c.index] - c.value) * c.sign >= 0.)\n            continue;\n\n        if(scale < minScale)\n        {\n            minScale = scale;\n            closestConstraint = i;\n        }\n    }\n\n    if(closestConstraint >= 0)\n    {\n        delta *= minScale;\n        //cout << \"Projecting up to constraint \" << closestConstraint << \" by \" << minScale << endl;\n    }\n\n    return closestConstraint;\n}\n\nbool LSSolver::verifyDerivatives(const Eigen::VectorXd &pt, double eps) const\n{\n    LSEvalData *evalData = _problem->createEvalData();\n    _problem->eval(pt, evalData);\n\n    MatrixXd exactDer = evalData->errVecDer();\n    MatrixXd numDer = exactDer;\n\n    for(int i = 0; i < numDer.cols(); ++i)\n    {\n        VectorXd mod = pt;\n        mod[i] += eps;\n\n        _problem->eval(mod, evalData);\n        VectorXd plus = evalData->errVec();\n\n        mod[i] = pt[i] - eps;\n        _problem->eval(mod, evalData);\n        VectorXd minus = evalData->errVec();\n\n        numDer.col(i) = (plus - minus) / (2 * eps);\n    }\n\n    double err = (numDer - exactDer).norm();\n\n    //TODO: just print the error for now\n    Debugging::get()->printf(\"Derivative Error = %lf\", err);\n#if 0\n    for(int i = 0; i < numDer.cols(); ++i)\n        Debugging::get()->printf(\"Col %d err = %lf\", i, (numDer.col(i) - exactDer.col(i)).norm());\n    for(int i = 0; i < numDer.rows(); ++i)\n        Debugging::get()->printf(\"Row %d err = %lf\", i, (numDer.row(i) - exactDer.row(i)).norm());\n#endif\n    delete evalData;\n\n    return true;\n}\n\nvoid LSDenseEvalData::solveForDelta(double damping, VectorXd &out, set<LSBoxConstraint> &constraints)\n{\n    int vars = (int)_errDer.cols();\n    if(constraints.empty())\n    {\n        LDLT<MatrixXd> ldlt(MatrixXd::Identity(vars, vars) * damping + _errDer.transpose() * _errDer);\n        out = ldlt.solve(-_errDer.transpose() * _err);\n    }\n    else\n    {\n        VectorXd rhs = -_err;\n\n        vector<bool> constraintIndices(vars, false);\n        for(set<LSBoxConstraint>::const_iterator it = constraints.begin(); it != constraints.end(); ++it)\n            constraintIndices[it->index] = true;\n\n        if(vars > (int)constraints.size())\n        {\n            MatrixXd lhs(_errDer.rows(), vars - (int)constraints.size());\n            int offs = 0;\n            for(int i = 0; i < vars; ++i)\n            {\n                if(constraintIndices[i])\n                {\n                    ++offs;\n                    continue;\n                }\n                lhs.col(i - offs) = _errDer.col(i);\n            }\n\n            LDLT<MatrixXd> ldlt(MatrixXd::Identity(lhs.cols(), lhs.cols()) * damping + lhs.transpose() * lhs);\n            VectorXd x = ldlt.solve(lhs.transpose() * rhs);\n            \n            out.resize(_errDer.cols());\n            offs = 0;\n\n            for(int i = 0; i < vars; ++i)\n            {\n                if(constraintIndices[i])\n                {\n                    out[i] = 0.;\n                    ++offs;\n                    continue;\n                }\n                out[i] = x[i - offs];\n            }\n        }\n        else //as many variables as constraints\n        {\n            out = VectorXd::Zero(_errDer.cols());\n        }\n\n        //check which constraints we don't need\n        VectorXd gradient = _errDer.transpose() * (_errDer * out - rhs);\n        for(set<LSBoxConstraint>::iterator it = constraints.begin(); it != constraints.end(); )\n        {\n            set<LSBoxConstraint>::iterator next = it;\n            ++next;\n            if(gradient[it->index] * it->sign < 0) //if sign is zero, constraint will not get erased\n            {\n                //cout << \"Unsetting constraint on variable at index \" << it->index << endl;\n                constraints.erase(it);\n            }\n            it = next;\n        }\n    }\n}\n\n\nEND_NAMESPACE_Cornu\n\n\n", "meta": {"hexsha": "9711a04e8518035fca15aa82416444aba87485a6", "size": 7775, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "external/Cornucopia/Solver.cpp", "max_stars_repo_name": "davepagurek/StrokeStrip", "max_stars_repo_head_hexsha": "c9ae2ebac9ecbc6461952df58a05288bccc571a1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 40.0, "max_stars_repo_stars_event_min_datetime": "2021-05-02T04:22:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T10:07:26.000Z", "max_issues_repo_path": "external/Cornucopia/Solver.cpp", "max_issues_repo_name": "davepagurek/StrokeStrip", "max_issues_repo_head_hexsha": "c9ae2ebac9ecbc6461952df58a05288bccc571a1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-08-17T03:14:45.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-17T03:15:35.000Z", "max_forks_repo_path": "external/Cornucopia/Solver.cpp", "max_forks_repo_name": "davepagurek/StrokeStrip", "max_forks_repo_head_hexsha": "c9ae2ebac9ecbc6461952df58a05288bccc571a1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2021-05-15T16:04:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-27T04:34:21.000Z", "avg_line_length": 28.1702898551, "max_line_length": 110, "alphanum_fraction": 0.5554983923, "num_tokens": 1986, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4920729734539147}}
{"text": "//\n// Created by jianping on 17-9-18.\n//\n\n#include <iostream>\n#include <glog/logging.h>\n#include <opencv2/calib3d/calib3d.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#include <Eigen/Dense>\n#include <opencv2/core/eigen.hpp>\n#include <fstream>\n#include <Eigen/Geometry>\n\n\n\n\n\nvoid saveXYZ(const char* filename, const cv::Mat& mat,float tx)\n{\n    const double max_z = 2000;\n    FILE* fp = fopen(filename, \"wt\");\n    for(int y = 0; y < mat.rows; y++)\n    {\n        for(int x = 0; x < mat.cols; x++)\n        {\n            cv::Vec3f point = mat.at<cv::Vec3f>(y, x);\n            if(fabs(fabs(point[2]) - max_z) < FLT_EPSILON || fabs(point[2]) > max_z) continue;\n            fprintf(fp, \"%f %f %f\\n\", point[0], point[1], point[2]);\n        }\n    }\n    fclose(fp);\n}\n\nvoid readParams(const std::string& intrinsicFile,\n                Eigen::Matrix3d& K0,\n                Eigen::Matrix3d& K1)\n{\n    std::ifstream ifs(intrinsicFile.c_str(),std::ios_base::in);\n    char line[256];\n    ifs.getline(line,256);\n    sscanf(line,\"cam0=[%lf %lf %lf; %lf %lf %lf; %lf %lf %lf]\",\n           &K0(0,0),&K0(0,1),&K0(0,2),&K0(1,0),&K0(1,1),&K0(1,2),&K0(2,0),&K0(2,1),&K0(2,2));\n    std::cout<<\"K0\\n\"<<K0<<\"\\n\";\n\n    ifs.getline(line,256);\n    sscanf(line,\"cam1=[%lf %lf %lf; %lf %lf %lf; %lf %lf %lf]\",\n           &K1(0,0),&K1(0,1),&K1(0,2),&K1(1,0),&K1(1,1),&K1(1,2),&K1(2,0),&K1(2,1),&K1(2,2));\n    std::cout<<\"K1\\n\"<<K1<<\"\\n\";\n}\n\n\nconst int scale = 1;\nint main() {\n    Eigen::Matrix3d K0;\n    Eigen::Matrix3d K1;\n    readParams(\"/home/jianping/workspace/datas/stereo/calib.txt\",K0,K1);\n\n    LOG(INFO)<<\"matching\"<<std::endl;\n\n\n\n    cv::Mat image_ref_origin = cv::imread(\"/home/jianping/workspace/datas/stereo/im0.png\");\n    cv::Mat image_source_origin = cv::imread(\"/home/jianping/workspace/datas/stereo/im1.png\");\n    cv::StereoSGBM sgbm(0,640,\n                        8,8*3*3*3,32*3*3*3,2,\n                        16,5,100,\n                        2,false\n    );\n\n    Eigen::Matrix3d C;\n    C = Eigen::Matrix3d::Identity();\n    Eigen::Vector3d r0,r1,r(100,0,0);\n\n    cv::Mat Q;\n    cv::Rect roi1, roi2;\n    cv::Mat M0,M1,R01(3,3,CV_64FC1),t(3,1,CV_64FC1),R0__,R1__,P0__,P1__;\n    cv::Mat D0(5,1,CV_64FC1),D1(5,1,CV_64FC1);\n    D0.setTo(0);\n    D1.setTo(0);\n    cv::eigen2cv(K0,M0);\n    cv::eigen2cv(K1,M1);\n    cv::eigen2cv(C,R01);\n    cv::eigen2cv(r,t);\n\n    cv::Size size(image_ref_origin.cols, image_ref_origin.rows);\n    cv::stereoRectify(M0,D0,M1,D1,\n                      size,R01,t,\n                      R0__,R1__,\n                      P0__,P1__,\n                      Q,cv::CALIB_FIX_INTRINSIC,-1,\n                      size, &roi1, &roi2\n    );\n\n    cv::Mat disp,disp8,dispnorm(image_ref_origin.rows,image_ref_origin.cols,CV_64FC1);\n    sgbm(image_ref_origin,image_source_origin,disp);\n\n    cv::normalize(disp,dispnorm,255,0,cv::NORM_MINMAX);\n    dispnorm.convertTo(disp8, CV_8U);\n    cv::namedWindow(\"re\",cv::WINDOW_NORMAL);\n    cv::imshow(\"re\",disp8);\n\n\n    cv::namedWindow(\"ref\",cv::WINDOW_NORMAL);\n    cv::namedWindow(\"source\",cv::WINDOW_NORMAL);\n\n    for (int i = 0; i < image_ref_origin.rows; i += image_ref_origin.rows/20 ) {\n        cv::line(image_ref_origin,cv::Point(0,i),cv::Point(image_ref_origin.cols,i),cv::Scalar(0,255,0),3);\n        cv::line(image_source_origin,cv::Point(0,i),cv::Point(image_ref_origin.cols,i),cv::Scalar(0,255,0),3);\n\n    }\n\n    cv::imshow(\"ref\",image_source_origin);\n    cv::imshow(\"source\",image_ref_origin);\n\n    cv::Mat xyz,xyz8;\n    reprojectImageTo3D(disp, xyz, Q, false);\n\n    saveXYZ(\"./pts.xyz\", xyz, r(0));\n    cv::waitKey(0);\n    return 0;\n}", "meta": {"hexsha": "50c6abaa8941114dcabfeb16852f724d0bd115a2", "size": 3617, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/stereotest.cpp", "max_stars_repo_name": "kafeiyin00/DepthProbability", "max_stars_repo_head_hexsha": "15a2f3a710cdf2aaf5dbef263dfdd32f5f53fe6f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-09-01T02:10:32.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-01T02:10:32.000Z", "max_issues_repo_path": "src/stereotest.cpp", "max_issues_repo_name": "kafeiyin00/DepthProbability", "max_issues_repo_head_hexsha": "15a2f3a710cdf2aaf5dbef263dfdd32f5f53fe6f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/stereotest.cpp", "max_forks_repo_name": "kafeiyin00/DepthProbability", "max_forks_repo_head_hexsha": "15a2f3a710cdf2aaf5dbef263dfdd32f5f53fe6f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-07-14T05:32:14.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-14T05:32:14.000Z", "avg_line_length": 29.6475409836, "max_line_length": 110, "alphanum_fraction": 0.5775504562, "num_tokens": 1271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.4920729734539147}}
{"text": "//==============================================================================\n//         Copyright 2009 - 2013 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#include <boost/simd/sdk/simd/pack.hpp>\n#include <boost/simd/include/functions/aligned_load.hpp>\n#include <boost/simd/include/functions/aligned_store.hpp>\n#include <boost/simd/include/functions/multiplies.hpp>\n#include <boost/simd/include/functions/plus.hpp>\n#include <boost/simd/include/functions/minus.hpp>\n#include <boost/simd/memory/allocator.hpp>\n#include <boost/fusion/include/at.hpp>\n#include <iostream>\n\n#include <nt2/sdk/bench/benchmark.hpp>\n#include <nt2/sdk/bench/metric/cycles_per_element.hpp>\n#include <nt2/sdk/bench/protocol/max_duration.hpp>\n#include <nt2/sdk/bench/setup/geometric.hpp>\n#include <nt2/sdk/bench/setup/combination.hpp>\n#include <nt2/sdk/bench/stats/median.hpp>\n\nusing namespace nt2::bench;\nusing namespace nt2;\n\ntemplate<typename T> struct rgb2grey_simd\n{\n  template<typename Setup>\n  rgb2grey_simd(Setup const& s)\n                    :  height(boost::fusion::at_c<0>(s))\n                    ,  width(boost::fusion::at_c<1>(s))\n                    ,  size_(height*width)\n  {\n    gr.resize(size_);\n    r.resize(size_);\n    g.resize(size_);\n    b.resize(size_);\n    for(std::size_t i=0; i<size_; i++)\n      r[i] = g[i] = b[i] = gr[i] = T(i);\n  }\n\n  void operator()()\n  {\n    using boost::simd::pack;\n\n    typedef pack<T> type;\n    std::size_t aligned_sz = size_ & ~(type::static_size-1);\n    std::size_t it         = 0;\n\n    type cr(0.3f), cg(0.59f),cb(0.11f);\n\n    for(std::size_t m=aligned_sz; it != m; it+=type::static_size)\n    {\n      type vr(&r[it]), vg(&g[it]), vb(&b[it]);\n\n      boost::simd::aligned_store( cr * vr + cg * vg + cb * vb, &gr[it] );\n    }\n\n    for(std::size_t m=size_; it != m; it++)\n    {\n      gr[it] = T(0.3) * r[it] + T(0.59) * g[it] + T(0.11) * b[it];\n    }\n  }\n\n  friend std::ostream& operator<<(std::ostream& os, rgb2grey_simd<T> const& p)\n  {\n    return os << \"(\" << p.size() << \")\";\n  }\n\n  std::size_t size() const { return size_; }\n\n  private:\n  std::size_t height, width, size_;\n  std::vector<T,boost::simd::allocator<T> > r, g, b, gr;\n};\n\nNT2_REGISTER_BENCHMARK_TPL( rgb2grey_simd, (float) )\n{\n  std::size_t hmin  = args(\"hmin\" ,  32   );\n  std::size_t hmax  = args(\"hmax\" , 128   );\n  std::size_t hstep = args(\"hstep\",   2   );\n  std::size_t wmin  = args(\"wmin\" , hmin  );\n  std::size_t wmax  = args(\"wmax\" , hmax  );\n  std::size_t wstep = args(\"wstep\", hstep );\n\n  run_during_with< rgb2grey_simd<T> > ( 1.\n                                        , and_( geometric(hmin,hmax,hstep)\n                                              , geometric(wmin,wmax,wstep)\n                                              )\n                                        , cycles_per_element<stats::median_>()\n                                        );\n}\n", "meta": {"hexsha": "724b1007ca60c014442be66558962aa1dd1a0604", "size": 3172, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "demo/rgb2grey/simd/rgb2grey_simd.cpp", "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": "demo/rgb2grey/simd/rgb2grey_simd.cpp", "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": "demo/rgb2grey/simd/rgb2grey_simd.cpp", "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": 33.0416666667, "max_line_length": 80, "alphanum_fraction": 0.5450819672, "num_tokens": 869, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.4920729734539146}}
{"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/volatility/stickybpvolswaptioncube.hpp>\n#include <ql/experimental/volatility/multiplicativesmilesection.hpp>\n#include <ql/math/interpolations/bilinearinterpolation.hpp>\n#include <ql/math/interpolations/flatextrapolation2d.hpp>\n#include <ql/quotes/simplequote.hpp>\n\n#include <boost/make_shared.hpp>\n\nnamespace QuantLib {\n\nStickyBpVolSwaptionCube::StickyBpVolSwaptionCube(\n    const boost::shared_ptr<SwaptionVolatilityCube> &sourceCube,\n    Handle<Quote> atmVolatilitySpread)\n    : SwaptionVolatilityCube(\n          sourceCube->atmVol(), sourceCube->optionTenors(),\n          sourceCube->swapTenors(), sourceCube->strikeSpreads(),\n          sourceCube->volSpreads(), sourceCube->swapIndexBase(),\n          sourceCube->shortSwapIndexBase(), sourceCube->vegaWeightedSmileFit()),\n      sourceCube_(sourceCube),\n      atmVolatilitySpread_(atmVolatilitySpread) {\n\n    registerWith(sourceCube_);\n    registerWith(atmVolatilitySpread_);\n\n    boost::shared_ptr<SwaptionVolatilityDiscrete> atm =\n        boost::dynamic_pointer_cast<SwaptionVolatilityDiscrete>(\n            *sourceCube->atmVol());\n\n    // this should never happen (?)\n    QL_REQUIRE(atm != NULL, \"atm is not of type SwaptionVolatilityDiscrete\");\n\n    atmLevel_ = Matrix(optionDates().size(), swapTenors().size());\n\n    for (Size j = 0; j < atm->swapTenors().size(); ++j)\n        for (Size i = 0; i < atm->optionDates().size(); ++i)\n            atmLevel_[i][j] = sourceCube->atmStrike(atm->optionDates()[i],\n                                                    atm->swapTenors()[j]);\n\n    originalAtm_ = FlatExtrapolator2D(boost::make_shared<BilinearInterpolation>(\n        atm->swapLengths().begin(), atm->swapLengths().end(),\n        atm->optionTimes().begin(), atm->optionTimes().end(), atmLevel_));\n\n    originalAtm_.enableExtrapolation();\n}\n\nboost::shared_ptr<SmileSection>\nStickyBpVolSwaptionCube::smileSectionImpl(Time optionTime,\n                                          Time swapLength) const {\n\n    boost::shared_ptr<SmileSection> source =\n        sourceCube_->smileSection(optionTime, swapLength, true);\n\n    Real newAtm = source->atmLevel();\n\n    QL_REQUIRE(newAtm != Null<Real>(),\n               \"source smile section does not provide atm level\");\n\n    Real mul = originalAtm_(optionTime, swapLength) / newAtm;\n    Real add = 0.0;\n    if(!atmVolatilitySpread_.empty()) {\n        if(atmVolatilitySpread_->isValid()) {\n            add = atmVolatilitySpread_->value() * mul;\n        }\n    }\n\n    boost::shared_ptr<SmileSection> tmp =\n        boost::make_shared<MultiplicativeSmileSection>(\n            source, Handle<Quote>(boost::make_shared<SimpleQuote>(mul)),\n            Handle<Quote>(boost::make_shared<SimpleQuote>(add)));\n    return tmp;\n}\n\nVolatility StickyBpVolSwaptionCube::volatilityImpl(Time optionTime,\n                                                   Time swapLength,\n                                                   Rate strike) const {\n    return smileSectionImpl(optionTime, swapLength)->volatility(strike);\n}\n}\n", "meta": {"hexsha": "b84227070baf582b99bc9d2f72e2361f63ca2463", "size": 3824, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ql/experimental/volatility/stickybpvolswaptioncube.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/volatility/stickybpvolswaptioncube.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/volatility/stickybpvolswaptioncube.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.0204081633, "max_line_length": 80, "alphanum_fraction": 0.6775627615, "num_tokens": 920, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4920729673102035}}
{"text": "#ifndef RNDCMP_INCLUDE_FIXED_HPP_\n#define RNDCMP_INCLUDE_FIXED_HPP_\n\n#include <cmath>\n#include <Eigen/Core>\n\n\nnamespace rndcmp {\n    template<typename INT_T, int FRACT_SIZE = 0, int POW = 2>\n    class Fixed {\n    public:\n        Fixed() = default;\n\n        /* constructors */\n\n        template<typename T>\n        Fixed(T v, std::enable_if_t<std::is_floating_point<T>::value, bool> = true) {\n            setValueFromT(v);\n        }\n\n        template<typename T>\n        Fixed(T v, std::enable_if_t<std::is_integral_v<T>, int> = 0) {\n            setValueFromT(static_cast<double>(v));\n        }\n\n        template<typename T, std::enable_if_t<std::is_floating_point_v<T>, int> = 0>\n        operator T() const {\n            return static_cast<T>(value) / (1 << FRACT_SIZE);\n        }\n\n        /* + operators */\n\n        template<typename T, std::enable_if_t<std::is_floating_point_v<T>, int> = 0>\n        Fixed operator+(const T& rhs) const {\n            return Fixed(T(*this) + rhs);\n        }\n\n        Fixed operator+(const Fixed& rhs) const {\n            double val = static_cast<double>(*this) + static_cast<double>(rhs);\n            return Fixed(val);\n        }\n\n        template<typename T, std::enable_if_t<std::is_floating_point_v<T>, int> = 0>\n        friend Fixed operator+(T lhs, const Fixed& rhs) {\n            T val = lhs + T(rhs);\n            return Fixed(val);\n        }\n\n        template<typename T, std::enable_if_t<std::is_floating_point_v<T>, int> = 0>\n        Fixed& operator+=(const T& rhs) {\n            T sum = T(*this) + rhs;\n            setValueFromT<T>(sum);\n            return *this;\n        }\n\n        Fixed& operator+=(const Fixed& rhs) {\n            double sum = static_cast<double>(*this) + static_cast<double>(rhs);\n            setValueFromT(sum);\n            return *this;\n        }\n\n        template<typename T, std::enable_if_t<std::is_integral_v<T>, int> = 0>\n        Fixed operator+(const T& rhs) const {\n            return Fixed(double(*this) + double(rhs));\n        }\n\n        template<typename T, std::enable_if_t<std::is_integral_v<T>, int> = 0>\n        friend Fixed operator+(T lhs, const Fixed& rhs) {\n            double val = double(lhs) + double(rhs);\n            return Fixed(val);\n        }\n\n        template<typename T, std::enable_if_t<std::is_integral_v<T>, int> = 0>\n        Fixed& operator+=(const T& rhs) {\n            double val = double(*this) + double(rhs);\n            setValueFromT<double>(val);\n            return *this;\n        }\n\n        /* - operators */\n\n        template<typename T, std::enable_if_t<std::is_floating_point_v<T>, int> = 0>\n        Fixed operator-(const T& rhs) const {\n            return Fixed(T(*this) - rhs);\n        }\n\n        Fixed operator-(const Fixed& rhs) const {\n            double val = static_cast<double>(*this) - static_cast<double>(rhs);\n            return Fixed(val);\n        }\n\n        template<typename T, std::enable_if_t<std::is_floating_point_v<T>, int> = 0>\n        Fixed& operator-=(const T& rhs) {\n            T sub = T(*this) - rhs;\n            setValueFromT<T>(sub);\n            return *this;\n        }\n\n        Fixed& operator-=(const Fixed& rhs) {\n            double val = static_cast<double>(*this) - static_cast<double>(rhs);\n            setValueFromT(val);\n            return *this;\n        }\n\n        template<typename T, std::enable_if_t<std::is_floating_point_v<T>, int> = 0>\n        friend Fixed operator-(T lhs, const Fixed& rhs) {\n            T val = lhs - T(rhs);\n            return Fixed(val);\n        }\n\n        template<typename T, std::enable_if_t<std::is_integral_v<T>, int> = 0>\n        Fixed operator-(const T& rhs) const {\n            return Fixed(double(*this) - double(rhs));\n        }\n\n        template<typename T, std::enable_if_t<std::is_integral_v<T>, int> = 0>\n        friend Fixed operator-(T lhs, const Fixed& rhs) {\n            double val = double(lhs) - double(rhs);\n            return Fixed(val);\n        }\n\n        template<typename T, std::enable_if_t<std::is_integral_v<T>, int> = 0>\n        Fixed& operator-=(const T& rhs) {\n            double val = double(*this) - double(rhs);\n            setValueFromT<double>(val);\n            return *this;\n        }\n\n        /* multiply operators */\n\n        template<typename T, std::enable_if_t<std::is_floating_point_v<T>, int> = 0>\n        Fixed operator*(const T& rhs) const {\n            return Fixed(T(*this) * rhs);\n        }\n\n        Fixed operator*(const Fixed& rhs) const {\n            return Fixed(double(*this) * double(rhs));\n        }\n\n        Fixed& operator*=(const Fixed& rhs) {\n            double val = static_cast<double>(*this) * static_cast<double>(rhs);\n            setValueFromT(val);\n            return *this;\n        }\n\n        template<typename T, std::enable_if_t<std::is_floating_point_v<T>, int> = 0>\n        Fixed& operator*=(const T& rhs) {\n            T mul = T(*this) * rhs;\n            setValueFromT<T>(mul);\n            return *this;\n        }\n\n        template<typename T, std::enable_if_t<std::is_floating_point_v<T>, int> = 0>\n        friend Fixed operator*(T lhs, const Fixed& rhs) {\n            T val = lhs * T(rhs);\n            return Fixed(val);\n        }\n\n        template<typename T, std::enable_if_t<std::is_integral_v<T>, int> = 0>\n        Fixed operator*(const T& rhs) const {\n            return Fixed(double(*this) * double(rhs));\n        }\n\n        template<typename T, std::enable_if_t<std::is_integral_v<T>, int> = 0>\n        friend Fixed operator*(T lhs, const Fixed& rhs) {\n            double val = double(lhs) * double(rhs);\n            return Fixed(val);\n        }\n\n        template<typename T, std::enable_if_t<std::is_integral_v<T>, int> = 0>\n        Fixed& operator*=(const T& rhs) {\n            double val = double(*this) * double(rhs);\n            setValueFromT<double>(val);\n            return *this;\n        }\n\n        /* divide operators */\n\n        template<typename T, std::enable_if_t<std::is_floating_point_v<T>, int> = 0>\n        Fixed operator/(const T& rhs) const {\n            return Fixed(T(*this) / rhs);\n        }\n\n        Fixed operator/(const Fixed& rhs) const {\n            return Fixed(double(*this) / double(rhs));\n        }\n\n        template<typename T, std::enable_if_t<std::is_floating_point_v<T>, int> = 0>\n        Fixed& operator/=(const T& rhs) {\n            T div = T(*this) / rhs;\n            setValueFromT<T>(div);\n            return *this;\n        }\n\n        Fixed& operator/=(const Fixed& rhs) {\n            double val = static_cast<double>(*this) / static_cast<double>(rhs);\n            setValueFromT(val);\n            return *this;\n        }\n\n        template<typename T, std::enable_if_t<std::is_floating_point_v<T>, int> = 0>\n        friend Fixed operator/(T lhs, const Fixed& rhs) {\n            T val = lhs / T(rhs);\n            return Fixed(val);\n        }\n\n        template<typename T, std::enable_if_t<std::is_integral_v<T>, int> = 0>\n        Fixed operator/(const T& rhs) const {\n            return Fixed(double(*this) / double(rhs));\n        }\n\n        template<typename T, std::enable_if_t<std::is_integral_v<T>, int> = 0>\n        friend Fixed operator/(T lhs, const Fixed& rhs) {\n            double val = double(lhs) / double(rhs);\n            return Fixed(val);\n        }\n\n        template<typename T, std::enable_if_t<std::is_integral_v<T>, int> = 0>\n        Fixed& operator/=(const T& rhs) {\n            double val = double(*this) / double(rhs);\n            setValueFromT<double>(val);\n            return *this;\n        }\n\n        /* comparison operators */\n\n        /* less */\n\n        bool operator<(const Fixed& rhs) const {\n            return value < rhs.value;\n        }\n\n        template<typename T, std::enable_if_t<std::is_floating_point_v<T>, int> = 0>\n        bool operator<(const T& rhs) const {\n            return static_cast<double>(*this) < rhs;\n        }\n\n        template<typename T, std::enable_if_t<std::is_integral_v<T>, int> = 0>\n        bool operator<(const T& rhs) const {\n            return static_cast<double>(*this) < rhs;\n        }\n\n        template<typename T, std::enable_if_t<std::is_floating_point_v<T>, int> = 0>\n        friend bool operator<(const T& rhs, const Fixed& lhs) {\n            return static_cast<double>(rhs) < static_cast<double>(lhs);\n        }\n\n        template<typename T, std::enable_if_t<std::is_integral_v<T>, int> = 0>\n        friend bool operator<(const T& rhs, const Fixed& lhs) {\n            return static_cast<double>(rhs) < static_cast<double>(lhs);\n        }\n\n        /* greater */\n\n        bool operator>(const Fixed& rhs) const {\n            return value > rhs.value;\n        }\n\n        template<typename T, std::enable_if_t<std::is_floating_point_v<T>, int> = 0>\n        bool operator>(const T& rhs) const {\n            return static_cast<double>(*this) > rhs;\n        }\n\n        template<typename T, std::enable_if_t<std::is_integral_v<T>, int> = 0>\n        bool operator>(const T& rhs) const {\n            return static_cast<double>(*this) > rhs;\n        }\n\n        template<typename T, std::enable_if_t<std::is_floating_point_v<T>, int> = 0>\n        friend bool operator>(const T& rhs, const Fixed& lhs) {\n            return static_cast<double>(rhs) > static_cast<double>(lhs);\n        }\n\n        template<typename T, std::enable_if_t<std::is_integral_v<T>, int> = 0>\n        friend bool operator>(const T& rhs, const Fixed& lhs) {\n            return static_cast<double>(rhs) > static_cast<double>(lhs);\n        }\n\n        /* equal */\n\n        bool operator==(const Fixed& rhs) const {\n            return value == rhs.value;\n        }\n\n        template<typename T, std::enable_if_t<std::is_floating_point_v<T>, int> = 0>\n        bool operator==(const T& rhs) const {\n            return static_cast<double>(*this) == rhs;\n        }\n\n        template<typename T, std::enable_if_t<std::is_integral_v<T>, int> = 0>\n        bool operator==(const T& rhs) const {\n            return static_cast<double>(*this) == rhs;\n        }\n\n        template<typename T, std::enable_if_t<std::is_floating_point_v<T>, int> = 0>\n        friend bool operator==(const T& rhs, const Fixed& lhs) {\n            return static_cast<double>(rhs) == static_cast<double>(lhs);\n        }\n\n        template<typename T, std::enable_if_t<std::is_integral_v<T>, int> = 0>\n        friend bool operator==(const T& rhs, const Fixed& lhs) {\n            return static_cast<double>(rhs) == static_cast<double>(lhs);\n        }\n\n        /* not equal */\n       \n        bool operator!=(const Fixed& rhs) const {\n            return value != rhs.value;\n        }\n\n        template<typename T, std::enable_if_t<std::is_floating_point_v<T>, int> = 0>\n        bool operator!=(const T& rhs) const {\n            return static_cast<double>(*this) != rhs;\n        }\n\n        template<typename T, std::enable_if_t<std::is_integral_v<T>, int> = 0>\n        bool operator!=(const T& rhs) const {\n            return static_cast<double>(*this) != rhs;\n        }\n\n        template<typename T, std::enable_if_t<std::is_floating_point_v<T>, int> = 0>\n        friend bool operator!=(const T& rhs, const Fixed& lhs) {\n            return static_cast<double>(rhs) != static_cast<double>(lhs);\n        }\n\n        template<typename T, std::enable_if_t<std::is_integral_v<T>, int> = 0>\n        friend bool operator!=(const T& rhs, const Fixed& lhs) {\n            return static_cast<double>(rhs) != static_cast<double>(lhs);\n        }\n\n        /* less or equal */\n\n        bool operator<=(const Fixed& rhs) const {\n            return value <= rhs.value;\n        }\n\n        template<typename T, std::enable_if_t<std::is_floating_point_v<T>, int> = 0>\n        bool operator<=(const T& rhs) const {\n            return static_cast<double>(*this)  <= rhs;\n        }\n\n        template<typename T, std::enable_if_t<std::is_integral_v<T>, int> = 0>\n        bool operator<=(const T& rhs) const {\n            return static_cast<double>(*this)  <= rhs;\n        }\n\n        template<typename T, std::enable_if_t<std::is_floating_point_v<T>, int> = 0>\n        friend bool operator<=(const T& rhs, const Fixed& lhs) {\n            return static_cast<double>(rhs) <= static_cast<double>(lhs);\n        }\n\n        template<typename T, std::enable_if_t<std::is_integral_v<T>, int> = 0>\n        friend bool operator<=(const T& rhs, const Fixed& lhs) {\n            return static_cast<double>(rhs) <= static_cast<double>(lhs);\n        }\n\n        /* greater or equal */\n\n        bool operator>=(const Fixed& rhs) const {\n            return value >= rhs.value;\n        }\n\n        template<typename T, std::enable_if_t<std::is_floating_point_v<T>, int> = 0>\n        bool operator>=(const T& rhs) const {\n            return static_cast<double>(*this) >= rhs;\n        }\n\n        template<typename T, std::enable_if_t<std::is_integral_v<T>, int> = 0>\n        bool operator>=(const T& rhs) const {\n            return static_cast<double>(*this) >= rhs;\n        }\n\n        template<typename T, std::enable_if_t<std::is_floating_point_v<T>, int> = 0>\n        friend bool operator>=(const T& rhs, const Fixed& lhs) {\n            return static_cast<double>(rhs) >= static_cast<double>(lhs);\n        }\n\n        template<typename T, std::enable_if_t<std::is_integral_v<T>, int> = 0>\n        friend bool operator>=(const T& rhs, const Fixed& lhs) {\n            return static_cast<double>(rhs) >= static_cast<double>(lhs);\n        }\n\n        /* unary minus */\n\n        Fixed operator-() const {\n            double v = - static_cast<double>(*this);\n            return Fixed(v);\n        }\n\n        /* ostream overload */\n        friend std::ostream& operator<<(std::ostream& os, const Fixed& v) {\n            os << double(v);\n            return os;\n        }\n    \n        /* Trigonometric functions */\n        friend inline Fixed cos(const Fixed&  x)  { return cos(static_cast<double>(x)); }\n        friend inline Fixed sin(const Fixed&  x)  { return sin(static_cast<double>(x)); }\n        friend inline Fixed tan(const Fixed&  x)  { return tan(static_cast<double>(x)); }\n        friend inline Fixed acos(const Fixed&  x)  { return acos(static_cast<double>(x)); }\n        friend inline Fixed asin(const Fixed&  x)  { return asin(static_cast<double>(x)); }\n        friend inline Fixed atan(const Fixed&  x)  { return atan(static_cast<double>(x)); }\n\n        /* Hyperbolic functions */\n        friend inline Fixed cosh(const Fixed&  x)  { return cosh(static_cast<double>(x)); }\n        friend inline Fixed sinh(const Fixed&  x)  { return sinh(static_cast<double>(x)); }\n        friend inline Fixed tanh(const Fixed&  x)  { return tanh(static_cast<double>(x)); }\n        friend inline Fixed acosh(const Fixed&  x)  { return acosh(static_cast<double>(x)); }\n        friend inline Fixed asinh(const Fixed&  x)  { return asinh(static_cast<double>(x)); }\n        friend inline Fixed atanh(const Fixed&  x)  { return atanh(static_cast<double>(x)); }\n\n        /* Exponential and logarithmic functions */\n        friend inline Fixed exp(const Fixed&  x)  { return exp(static_cast<double>(x)); }\n        friend inline Fixed log(const Fixed&  x)  { return log(static_cast<double>(x)); }\n        friend inline Fixed log10(const Fixed&  x)  { return log10(static_cast<double>(x)); }\n        friend inline Fixed logb(const Fixed&  x)  { return logb(static_cast<double>(x)); }\n\n        /* Power functions */\n        friend inline Fixed pow(const Fixed&  base, double exponent)  { return pow(static_cast<double>(base), exponent); }\n        friend inline Fixed sqrt(const Fixed&  x)  { return sqrt(static_cast<double>(x)); }\n        friend inline Fixed cbrt(const Fixed&  x)  { return cbrt(static_cast<double>(x)); }\n\n        friend inline Fixed scalbn(const Fixed&  x, int n)  { return scalbn(static_cast<double>(x), n); }\n\n        /* Other functions */\n        friend inline Fixed abs(const Fixed&  x)  { return abs(static_cast<double>(x)); }\n        friend inline Fixed fabs(const Fixed&  x)  { return fabs(static_cast<double>(x)); }\n        friend inline Fixed abs2(const Fixed& x)  { return x*x; }\n\n        friend inline Fixed copysign(const Fixed&  x1, const Fixed& x2)  { return copysign(static_cast<double>(x1), static_cast<double>(x2)); }\n        friend inline Fixed fmax(const Fixed&  x1, const Fixed&  x2) { return x1 < x2 ? x1 : x2; }\n        friend inline bool isfinite(const Fixed& x) { return true; }\n\n    protected:\n        INT_T value;\n    private:\n        template<typename T>\n        void setValueFromT(T v) {\n            value = static_cast<INT_T>(v * (1 << FRACT_SIZE));\n        }\n    };\n}\n\nnamespace Eigen {\n    // Inheritance from float is a temporary bad solution. Need specify all NumTraits explicitly\n    template<typename INT_T, int FRACT_SIZE, int POW> struct NumTraits<rndcmp::Fixed<INT_T, FRACT_SIZE, POW>>: NumTraits<float> {\n        typedef rndcmp::Fixed<INT_T, FRACT_SIZE, POW> Real;\n        typedef rndcmp::Fixed<INT_T, FRACT_SIZE, POW> NonInteger;\n        typedef rndcmp::Fixed<INT_T, FRACT_SIZE, POW> Nested;\n        \n        enum {\n            IsComplex = 0,\n            IsInteger = 0,\n            IsSigned = 1,\n            RequireInitialization = 1,\n            ReadCost = 1,\n            AddCost = 4,\n            MulCost = 4\n        };\n    };\n}\n\n#endif  // RNDCMP_INCLUDE_FIXED_HPP_\n", "meta": {"hexsha": "ff82bc4163476f4f4ee947e67189656dddda5d6f", "size": 17236, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/fixed.hpp", "max_stars_repo_name": "Xenobyte42/rndcmp_stochastic_emulator", "max_stars_repo_head_hexsha": "9cbf7844a41f100456ef0db603182fd31d99da92", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-05-06T08:33:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-14T21:28:53.000Z", "max_issues_repo_path": "include/fixed.hpp", "max_issues_repo_name": "Xenobyte42/rndcmp_stochastic_emulator", "max_issues_repo_head_hexsha": "9cbf7844a41f100456ef0db603182fd31d99da92", "max_issues_repo_licenses": ["MIT"], "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/fixed.hpp", "max_forks_repo_name": "Xenobyte42/rndcmp_stochastic_emulator", "max_forks_repo_head_hexsha": "9cbf7844a41f100456ef0db603182fd31d99da92", "max_forks_repo_licenses": ["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.1465517241, "max_line_length": 143, "alphanum_fraction": 0.571362265, "num_tokens": 4198, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6224593171945417, "lm_q1q2_score": 0.4920729623807092}}
{"text": "//\n// Copyright (c) 2018 CNRS\n//\n\n#include \"pinocchio/spatial/fwd.hpp\"\n#include \"pinocchio/algorithm/regressor.hpp\"\n#include \"pinocchio/algorithm/joint-configuration.hpp\"\n#include \"pinocchio/algorithm/center-of-mass.hpp\"\n#include \"pinocchio/parsers/sample-models.hpp\"\n\n#include <iostream>\n\n#include <boost/test/unit_test.hpp>\n#include <boost/utility/binary.hpp>\n\nBOOST_AUTO_TEST_SUITE(BOOST_TEST_MODULE)\n\nBOOST_AUTO_TEST_CASE(test_static_regressor)\n{\n  using namespace Eigen;\n  using namespace pinocchio;\n  \n  pinocchio::Model model; buildModels::humanoidRandom(model);\n  \n  pinocchio::Data data(model);\n  pinocchio::Data data_ref(model);\n  \n  model.lowerPositionLimit.head<7>().fill(-1.);\n  model.upperPositionLimit.head<7>().fill(1.);\n  \n  VectorXd q = randomConfiguration(model);\n  regressor::computeStaticRegressor(model,data,q);\n  \n  VectorXd phi(4*(model.njoints-1));\n  for(int k = 1; k < model.njoints; ++k)\n  {\n    const Inertia & Y = model.inertias[(size_t)k];\n    phi.segment<4>(4*(k-1)) << Y.mass(), Y.mass() * Y.lever();\n  }\n  \n  Vector3d com = centerOfMass(model,data_ref,q);\n  Vector3d static_com_ref;\n  static_com_ref <<  com;\n  \n  Vector3d static_com = data.staticRegressor * phi;\n  \n  BOOST_CHECK(static_com.isApprox(static_com_ref)); \n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "f0480a13c54d5e7c84ff43de74300f342350151e", "size": 1284, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittest/regressor.cpp", "max_stars_repo_name": "matthieuvigne/pinocchio", "max_stars_repo_head_hexsha": "01f211eceda3ac2e5edc8cf101690afb6f3184d3", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-22T15:42:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-22T15:42:45.000Z", "max_issues_repo_path": "unittest/regressor.cpp", "max_issues_repo_name": "matthieuvigne/pinocchio", "max_issues_repo_head_hexsha": "01f211eceda3ac2e5edc8cf101690afb6f3184d3", "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": "unittest/regressor.cpp", "max_forks_repo_name": "matthieuvigne/pinocchio", "max_forks_repo_head_hexsha": "01f211eceda3ac2e5edc8cf101690afb6f3184d3", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-21T09:14:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-21T09:14:26.000Z", "avg_line_length": 25.1764705882, "max_line_length": 62, "alphanum_fraction": 0.7250778816, "num_tokens": 354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.851952809486198, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4919987988353103}}
{"text": "//\n// Created by Alex Beccaro on 18/01/18.\n//\n\n#define BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n#include \"../../src/problems/1-50/26/problem26.hpp\"\n\nBOOST_AUTO_TEST_SUITE( Problem26 )\n\n    BOOST_AUTO_TEST_CASE( Example ) {\n        auto res = problems::problem26::solve(10);\n        BOOST_CHECK_EQUAL(res, 7);\n    }\n\n    BOOST_AUTO_TEST_CASE( Solution ) {\n        auto res = problems::problem26::solve();\n        BOOST_CHECK_EQUAL(res, 983);\n    }\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "fab3f682ca8f6f45c98cec863d9fbe9b48d05c33", "size": 490, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/1-50/test_problem26.cpp", "max_stars_repo_name": "abeccaro/project-euler", "max_stars_repo_head_hexsha": "c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T10:17:15.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-25T10:17:15.000Z", "max_issues_repo_path": "tests/1-50/test_problem26.cpp", "max_issues_repo_name": "abeccaro/project-euler", "max_issues_repo_head_hexsha": "c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3", "max_issues_repo_licenses": ["MIT"], "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/1-50/test_problem26.cpp", "max_forks_repo_name": "abeccaro/project-euler", "max_forks_repo_head_hexsha": "c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3", "max_forks_repo_licenses": ["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.3333333333, "max_line_length": 51, "alphanum_fraction": 0.6734693878, "num_tokens": 124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6757646140788307, "lm_q2_score": 0.7279754607093178, "lm_q1q2_score": 0.4919400562650912}}
{"text": "//\n// OpenTissue, A toolbox for physical based simulation and animation.\n// Copyright (C) 2007 Department of Computer Science, University of Copenhagen\n//\n#include <OpenTissue/configuration.h>\n\n#include <OpenTissue/core/math/big/big_types.h>\n#include <OpenTissue/core/math/optimization/optimization_compute_index_reordering.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <OpenTissue/utility/utility_push_boost_filter.h>\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n#include <OpenTissue/utility/utility_pop_boost_filter.h>\n\nBOOST_AUTO_TEST_SUITE(opentissue_math_big_compute_index_reordering);\n\nBOOST_AUTO_TEST_CASE(test_case)\n{\n  typedef ublas::vector<size_t>   idx_vector_type;\n\n  idx_vector_type bitmask;\n\n  bitmask.resize(10,false);\n\n\n  bitmask(2) = OpenTissue::math::optimization::IN_ACTIVE;\n  bitmask(4) = OpenTissue::math::optimization::IN_ACTIVE;\n  bitmask(6) = OpenTissue::math::optimization::IN_ACTIVE;\n  bitmask(9) = OpenTissue::math::optimization::IN_ACTIVE;\n  bitmask(1) = OpenTissue::math::optimization::IN_LOWER;\n  bitmask(3) = OpenTissue::math::optimization::IN_LOWER;\n  bitmask(8) = OpenTissue::math::optimization::IN_LOWER;\n  bitmask(0) = OpenTissue::math::optimization::IN_UPPER;\n  bitmask(5) = OpenTissue::math::optimization::IN_UPPER;\n  bitmask(7) = OpenTissue::math::optimization::IN_UPPER;\n\n  idx_vector_type old2new;\n  idx_vector_type new2old;\n\n  OpenTissue::math::optimization::compute_index_reordering( bitmask, old2new, new2old );\n\n  BOOST_CHECK( old2new( 2 ) == 0 );\n  BOOST_CHECK( old2new( 4 ) == 1 );\n  BOOST_CHECK( old2new( 6 ) == 2 );\n  BOOST_CHECK( old2new( 9 ) == 3 );\n  BOOST_CHECK( old2new( 1 ) == 4 );\n  BOOST_CHECK( old2new( 3 ) == 5 );\n  BOOST_CHECK( old2new( 8 ) == 6 );\n  BOOST_CHECK( old2new( 0 ) == 7 );\n  BOOST_CHECK( old2new( 5 ) == 8 );\n  BOOST_CHECK( old2new( 7 ) == 9 );\n  BOOST_CHECK( new2old( 0 ) == 2 );\n  BOOST_CHECK( new2old( 1 ) == 4 );\n  BOOST_CHECK( new2old( 2 ) == 6 );\n  BOOST_CHECK( new2old( 3 ) == 9 );\n  BOOST_CHECK( new2old( 4 ) == 1 );\n  BOOST_CHECK( new2old( 5 ) == 3 );\n  BOOST_CHECK( new2old( 6 ) == 8 );\n  BOOST_CHECK( new2old( 7 ) == 0 );\n  BOOST_CHECK( new2old( 8 ) == 5 );\n  BOOST_CHECK( new2old( 9 ) == 7 );\n\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "60c357ff4b63b8ffe53b80aab0976cd4af64b2bf", "size": 2332, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/core/math/optimization/compute_index_reordering/src/unit_compute_index_reordering.cpp", "max_stars_repo_name": "ricortiz/OpenTissue", "max_stars_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 76.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:45:06.000Z", "max_issues_repo_path": "unit_tests/core/math/optimization/compute_index_reordering/src/unit_compute_index_reordering.cpp", "max_issues_repo_name": "ricortiz/OpenTissue", "max_issues_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2018-11-20T14:32:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T15:26:45.000Z", "max_forks_repo_path": "unit_tests/core/math/optimization/compute_index_reordering/src/unit_compute_index_reordering.cpp", "max_forks_repo_name": "ricortiz/OpenTissue", "max_forks_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2018-02-21T01:45:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T07:06:49.000Z", "avg_line_length": 33.7971014493, "max_line_length": 88, "alphanum_fraction": 0.7148370497, "num_tokens": 715, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059775, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.49194003878160997}}
{"text": "// Copyright Louis Dionne 2013-2017\r\n// Distributed under the Boost Software License, Version 1.0.\r\n// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\r\n\r\n#include <boost/hana/equal.hpp>\r\n#include <boost/hana/functional/demux.hpp>\r\n#include <boost/hana/functional/placeholder.hpp>\r\n#include <boost/hana/tuple.hpp>\r\nnamespace hana = boost::hana;\r\nusing hana::_;\r\n\r\n\r\nconstexpr auto f = hana::demux(hana::make_tuple)(\r\n    _ + _,\r\n    _ - _,\r\n    _ * _,\r\n    _ / _\r\n);\r\n\r\nstatic_assert(\r\n    f(10, 4) == hana::make_tuple(\r\n        10 + 4,\r\n        10 - 4,\r\n        10 * 4,\r\n        10 / 4\r\n    )\r\n, \"\");\r\n\r\n\r\nint main() { }\r\n", "meta": {"hexsha": "058a1707688e938aab985b420b1cc47fbf295bad", "size": 653, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/hana/example/functional/demux.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": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/hana/example/functional/demux.cpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-03-04T11:21:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-24T01:36:31.000Z", "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/hana/example/functional/demux.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 21.064516129, "max_line_length": 82, "alphanum_fraction": 0.5926493109, "num_tokens": 193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680199891789, "lm_q2_score": 0.6619228891883799, "lm_q1q2_score": 0.491919922943645}}
{"text": "#include \"Demos/Utils/Config.h\"\n#include \"Demos/Visualization/MiniGL.h\"\n#include \"Demos/Visualization/Selection.h\"\n#include \"GL/glut.h\"\n#include \"Demos/Utils/TimeManager.h\"\n#include <Eigen/Dense>\n#include \"TriangleModel.h\"\n#include \"TimeStepTriangleModel.h\"\n#include <iostream>\n\n// Enable memory leak detection\n#ifdef _DEBUG\n\t#define new DEBUG_NEW \n#endif\n\nusing namespace PBD;\nusing namespace Eigen;\nusing namespace std;\n\nvoid timeStep ();\nvoid buildModel ();\nvoid createMesh();\nvoid render ();\nvoid cleanup();\nvoid reset();\nvoid selection(const Eigen::Vector2i &start, const Eigen::Vector2i &end);\nvoid TW_CALL setTimeStep(const void *value, void *clientData);\nvoid TW_CALL getTimeStep(void *value, void *clientData);\nvoid TW_CALL setStiffness(const void *value, void *clientData);\nvoid TW_CALL getStiffness(void *value, void *clientData);\nvoid TW_CALL setXXStiffness(const void *value, void *clientData);\nvoid TW_CALL getXXStiffness(void *value, void *clientData);\nvoid TW_CALL setYYStiffness(const void *value, void *clientData);\nvoid TW_CALL getYYStiffness(void *value, void *clientData);\nvoid TW_CALL setXYStiffness(const void *value, void *clientData);\nvoid TW_CALL getXYStiffness(void *value, void *clientData);\nvoid TW_CALL setXYPoissonRatio(const void *value, void *clientData);\nvoid TW_CALL getXYPoissonRatio(void *value, void *clientData);\nvoid TW_CALL setYXPoissonRatio(const void *value, void *clientData);\nvoid TW_CALL getYXPoissonRatio(void *value, void *clientData);\nvoid TW_CALL setNormalizeStretch(const void *value, void *clientData);\nvoid TW_CALL getNormalizeStretch(void *value, void *clientData);\nvoid TW_CALL setNormalizeShear(const void *value, void *clientData);\nvoid TW_CALL getNormalizeShear(void *value, void *clientData);\nvoid TW_CALL setBendingStiffness(const void *value, void *clientData);\nvoid TW_CALL getBendingStiffness(void *value, void *clientData);\nvoid TW_CALL setBendingMethod(const void *value, void *clientData);\nvoid TW_CALL getBendingMethod(void *value, void *clientData);\nvoid TW_CALL setSimulationMethod(const void *value, void *clientData);\nvoid TW_CALL getSimulationMethod(void *value, void *clientData);\nvoid TW_CALL setVelocityUpdateMethod(const void *value, void *clientData);\nvoid TW_CALL getVelocityUpdateMethod(void *value, void *clientData);\n\n\nTriangleModel model;\nTimeStepTriangleModel simulation;\n\nconst int nRows = 30;\nconst int nCols = 30;\nconst float width = 10.0f;\nconst float height = 10.0f;\nbool doPause = true;\nstd::vector<unsigned int> selectedParticles;\nEigen::Vector3f oldMousePos;\n\n// main \nint main( int argc, char **argv )\n{\n\tREPORT_MEMORY_LEAKS\n\n\t// OpenGL\n\tMiniGL::init (argc, argv, 1024, 768, 0, 0, \"Cloth demo\");\n\tMiniGL::initLights ();\n\tMiniGL::initTexture();\n\tMiniGL::setClientIdleFunc (50, timeStep);\t\t\n\tMiniGL::setKeyFunc(0, 'r', reset);\n\tMiniGL::setSelectionFunc(selection);\n\n\tbuildModel ();\n\n\tMiniGL::setClientSceneFunc(render);\t\t\t\n\tMiniGL::setViewport (40.0f, 0.1f, 500.0f, Vector3f (5.0, -10.0, 30.0), Vector3f (5.0, 0.0, 0.0));\n\n\tTwAddVarRW(MiniGL::getTweakBar(), \"Pause\", TW_TYPE_BOOLCPP, &doPause, \" label='Pause' group=Simulation key=SPACE \");\n\tTwAddVarCB(MiniGL::getTweakBar(), \"TimeStepSize\", TW_TYPE_FLOAT, setTimeStep, getTimeStep, &model, \" label='Time step size'  min=0.0 max = 0.1 step=0.001 precision=4 group=Simulation \");\n\tTwType enumType = TwDefineEnum(\"VelocityUpdateMethodType\", NULL, 0);\n\tTwAddVarCB(MiniGL::getTweakBar(), \"VelocityUpdateMethod\", enumType, setVelocityUpdateMethod, getVelocityUpdateMethod, &simulation, \" label='Velocity update method' enum='0 {First Order Update}, 1 {Second Order Update}' group=Simulation\");\n\tTwType enumType2 = TwDefineEnum(\"SimulationMethodType\", NULL, 0);\n\tTwAddVarCB(MiniGL::getTweakBar(), \"SimulationMethod\", enumType2, setSimulationMethod, getSimulationMethod, &simulation, \" label='Simulation method' enum='0 {None}, 1 {Distance constraints}, 2 {FEM based PBD}, 3 {Strain based dynamics}' group=Simulation\");\n\tTwAddVarCB(MiniGL::getTweakBar(), \"Stiffness\", TW_TYPE_FLOAT, setStiffness, getStiffness, &model, \" label='Stiffness'  min=0.0 step=0.1 precision=4 group='Distance constraints' \");\n\tTwAddVarCB(MiniGL::getTweakBar(), \"XXStiffness\", TW_TYPE_FLOAT, setXXStiffness, getXXStiffness, &model, \" label='Stiffness XX'  min=0.0 step=0.1 precision=4 group='Strain based dynamics' \");\n\tTwAddVarCB(MiniGL::getTweakBar(), \"YYStiffness\", TW_TYPE_FLOAT, setYYStiffness, getYYStiffness, &model, \" label='Stiffness YY'  min=0.0 step=0.1 precision=4 group='Strain based dynamics' \");\n\tTwAddVarCB(MiniGL::getTweakBar(), \"XYStiffness\", TW_TYPE_FLOAT, setXYStiffness, getXYStiffness, &model, \" label='Stiffness XY'  min=0.0 step=0.1 precision=4 group='Strain based dynamics' \");\n\tTwAddVarCB(MiniGL::getTweakBar(), \"XXStiffnessFEM\", TW_TYPE_FLOAT, setXXStiffness, getXXStiffness, &model, \" label='Youngs modulus XX'  min=0.0 step=0.1 precision=4 group='FEM based PBD' \");\n\tTwAddVarCB(MiniGL::getTweakBar(), \"YYStiffnessFEM\", TW_TYPE_FLOAT, setYYStiffness, getYYStiffness, &model, \" label='Youngs modulus YY'  min=0.0 step=0.1 precision=4 group='FEM based PBD' \");\n\tTwAddVarCB(MiniGL::getTweakBar(), \"XYStiffnessFEM\", TW_TYPE_FLOAT, setXYStiffness, getXYStiffness, &model, \" label='Youngs modulus XY'  min=0.0 step=0.1 precision=4 group='FEM based PBD' \");\n\tTwAddVarCB(MiniGL::getTweakBar(), \"XYPoissonRatioFEM\", TW_TYPE_FLOAT, setXYPoissonRatio, getXYPoissonRatio, &model, \" label='Poisson ratio XY'  min=0.0 step=0.1 precision=4 group='FEM based PBD' \");\n\tTwAddVarCB(MiniGL::getTweakBar(), \"YXPoissonRatioFEM\", TW_TYPE_FLOAT, setYXPoissonRatio, getYXPoissonRatio, &model, \" label='Poisson ratio YX'  min=0.0 step=0.1 precision=4 group='FEM based PBD' \");\n\tTwAddVarCB(MiniGL::getTweakBar(), \"NormalizeStretch\", TW_TYPE_BOOL32, setNormalizeStretch, getNormalizeStretch, &model, \" label='Normalize stretch' group='Strain based dynamics' \");\n\tTwAddVarCB(MiniGL::getTweakBar(), \"NormalizeShear\", TW_TYPE_BOOL32, setNormalizeShear, getNormalizeShear, &model, \" label='Normalize shear' group='Strain based dynamics' \");\n\tTwType enumType3 = TwDefineEnum(\"BendingMethodType\", NULL, 0);\n\tTwAddVarCB(MiniGL::getTweakBar(), \"BendingMethod\", enumType3, setBendingMethod, getBendingMethod, &simulation, \" label='Bending method' enum='0 {None}, 1 {Dihedral angle}, 2 {Isometric bending}' group=Bending\");\n\tTwAddVarCB(MiniGL::getTweakBar(), \"BendingStiffness\", TW_TYPE_FLOAT, setBendingStiffness, getBendingStiffness, &model, \" label='Bending stiffness'  min=0.0 step=0.01 precision=4 group=Bending \");\n\n\tglutMainLoop ();\t\n\n\tcleanup ();\n\t\n\treturn 0;\n}\n\nvoid cleanup()\n{\n\tdelete TimeManager::getCurrent();\n}\n\nvoid reset()\n{\n\tmodel.reset();\n\tsimulation.reset(model);\n\tTimeManager::getCurrent()->setTime(0.0);\n}\n\nvoid mouseMove(int x, int y)\n{\n\tEigen::Vector3f mousePos;\n\tMiniGL::unproject(x, y, mousePos);\n\tconst Eigen::Vector3f diff = mousePos - oldMousePos;\n\n\tTimeManager *tm = TimeManager::getCurrent();\n\tconst float h = tm->getTimeStepSize();\n\n\tParticleData &pd = model.getParticleMesh().getVertexData();\n\tfor (unsigned int j = 0; j < selectedParticles.size(); j++)\n\t{\n\t\tpd.getVelocity(selectedParticles[j]) += 5.0*diff/h;\n\t}\n\toldMousePos = mousePos;\n}\n\nvoid selection(const Eigen::Vector2i &start, const Eigen::Vector2i &end)\n{\n\tstd::vector<unsigned int> hits;\n\tselectedParticles.clear();\n\tParticleData &pd = model.getParticleMesh().getVertexData();\n\tSelection::selectRect(start, end, &pd.getPosition(0), &pd.getPosition(pd.size() - 1), selectedParticles);\n\tif (selectedParticles.size() > 0)\n\t\tMiniGL::setMouseMoveFunc(GLUT_MIDDLE_BUTTON, mouseMove);\n\telse\n\t\tMiniGL::setMouseMoveFunc(-1, NULL);\n\n\tMiniGL::unproject(end[0], end[1], oldMousePos);\n}\n\nvoid timeStep ()\n{\n\tif (doPause)\n\t\treturn;\n\n\t// Simulation code\n\tfor (unsigned int i = 0; i < 4; i++)\n\t\tsimulation.step(model);\n\tmodel.getParticleMesh().updateVertexNormals();\n}\n\nvoid buildModel ()\n{\n\tTimeManager::getCurrent ()->setTimeStepSize (0.005f);\n\n\tcreateMesh();\n}\n\n\nvoid render ()\n{\n\tMiniGL::coordinateSystem();\n\t\n\t// Draw simulation model\n\t\n\t// mesh \n\tconst ParticleData &pd = model.getParticleMesh().getVertexData();\n\tconst IndexedFaceMesh<ParticleData> &mesh = model.getParticleMesh();\n\tconst unsigned int *faces = mesh.getFaces().data();\n\tconst unsigned int nFaces = mesh.numFaces();\n\tconst Eigen::Vector3f *vertexNormals = mesh.getVertexNormals().data();\n\tconst Eigen::Vector2f *uvs = mesh.getUVs().data();\n\n\tfloat surfaceColor[4] = { 0.2f, 0.5f, 1.0f, 1 };\n\tfloat speccolor[4] = { 1.0, 1.0, 1.0, 1.0 };\n\tglMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, surfaceColor);\n\tglMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, surfaceColor);\n\tglMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, speccolor);\n\tglMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 100.0);\n\tglColor3fv(surfaceColor);\n\n\tMiniGL::bindTexture();\n\n\tglEnableClientState(GL_VERTEX_ARRAY);\n\tglEnableClientState(GL_NORMAL_ARRAY);\n\tglEnableClientState(GL_TEXTURE_COORD_ARRAY);\n\tglVertexPointer(3, GL_FLOAT, 0, &pd.getPosition(0)[0]);\n\tglTexCoordPointer(2, GL_FLOAT, 0, &uvs[0][0]);\n\tglNormalPointer(GL_FLOAT, 0, &vertexNormals[0][0]);\n\tglDrawElements(GL_TRIANGLES, (GLsizei)3 * mesh.numFaces(), GL_UNSIGNED_INT, mesh.getFaces().data());\n\tglDisableClientState(GL_VERTEX_ARRAY);\n\tglDisableClientState(GL_NORMAL_ARRAY);\n\tglDisableClientState(GL_TEXTURE_COORD_ARRAY);\n\n\tMiniGL::unbindTexture();\n\n\tfloat red[4] = { 0.8f, 0.0f, 0.0f, 1 };\n\tfor (unsigned int j = 0; j < selectedParticles.size(); j++)\n\t{\n\t\tMiniGL::drawSphere(pd.getPosition(selectedParticles[j]), 0.08f, red);\n\t}\n\n\tMiniGL::drawTime( TimeManager::getCurrent ()->getTime ());\n}\n\n\n/** Create a particle model mesh \n*/\nvoid createMesh()\n{\n\tTriangleModel::ParticleMesh::UVs uvs;\n\tuvs.resize(nRows*nCols);\n\n\tconst float dy = width / (float)(nCols-1);\n\tconst float dx = height / (float)(nRows-1);\n\n\tEigen::Vector3f points[nRows*nCols];\n\tfor (int i = 0; i < nRows; i++)\n\t{\n\t\tfor (int j = 0; j < nCols; j++)\n\t\t{\n\t\t\tconst float y = (float)dy*j;\n\t\t\tconst float x = (float)dx*i;\n\t\t\tpoints[i*nCols + j] = Eigen::Vector3f(x, 1.0, y);\n\n\t\t\tuvs[i*nCols + j][0] = x/width;\n\t\t\tuvs[i*nCols + j][1] = y/height;\n\t\t}\n\t}\n\tconst int nIndices = 6 * (nRows - 1)*(nCols - 1);\n\n\tTriangleModel::ParticleMesh::UVIndices uvIndices;\n\tuvIndices.resize(nIndices);\n\n\tunsigned int indices[nIndices];\n\tint index = 0;\n\tfor (int i = 0; i < nRows - 1; i++)\n\t{\n\t\tfor (int j = 0; j < nCols - 1; j++)\n\t\t{\n\t\t\tint helper = 0;\n\t\t\tif (i % 2 == j % 2)\n\t\t\t\thelper = 1;\n\n\t\t\tindices[index] = i*nCols + j;\n\t\t\tindices[index + 1] = i*nCols + j + 1;\n\t\t\tindices[index + 2] = (i + 1)*nCols + j + helper;\n\n\t\t\tuvIndices[index] = i*nCols + j;\n\t\t\tuvIndices[index + 1] = i*nCols + j + 1;\n\t\t\tuvIndices[index + 2] = (i + 1)*nCols + j + helper;\n\t\t\tindex += 3;\n\n\t\t\tindices[index] = (i + 1)*nCols + j + 1;\n\t\t\tindices[index + 1] = (i + 1)*nCols + j;\n\t\t\tindices[index + 2] = i*nCols + j + 1 - helper;\n\n\t\t\tuvIndices[index] = (i + 1)*nCols + j + 1;\n\t\t\tuvIndices[index + 1] = (i + 1)*nCols + j;\n\t\t\tuvIndices[index + 2] = i*nCols + j + 1 - helper;\n\t\t\tindex += 3;\n\t\t}\n\t}\n\tmodel.setGeometry(nRows*nCols, &points[0], nIndices / 3, &indices[0], uvIndices, uvs);\n\t\n\tTriangleModel::ParticleMesh &mesh = model.getParticleMesh();\n\tParticleData &pd = mesh.getVertexData();\n\tfor (unsigned int i = 0; i < pd.getNumberOfParticles(); i++)\n\t{\n\t\tpd.setMass(i, 1.0);\n\t}\n\n\t// Set mass of points to zero => make it static\n\tpd.setMass(0, 0.0);\n\tpd.setMass((nRows-1)*nCols, 0.0);\n\n\tmodel.initConstraints();\n\n\tstd::cout << \"Number of triangles: \" << nIndices / 3 << \"\\n\";\n\tstd::cout << \"Number of vertices: \" << nRows*nCols << \"\\n\";\n\n}\n\nvoid TW_CALL setTimeStep(const void *value, void *clientData)\n{\n\tconst float val = *(const float *)(value);\n\tTimeManager::getCurrent()->setTimeStepSize(val);\n}\n\nvoid TW_CALL getTimeStep(void *value, void *clientData)\n{\n\t*(float *)(value) = TimeManager::getCurrent()->getTimeStepSize();\n}\n\nvoid TW_CALL setStiffness(const void *value, void *clientData)\n{\n\tconst float val = *(const float *)(value);\n\t((TriangleModel*) clientData)->setStiffness(val);\n}\n\nvoid TW_CALL getStiffness(void *value, void *clientData)\n{\n\t*(float *)(value) = ((TriangleModel*)clientData)->getStiffness();\n}\n\nvoid TW_CALL setXXStiffness(const void *value, void *clientData)\n{\n\tconst float val = *(const float *)(value);\n\t((TriangleModel*)clientData)->setXXStiffness(val);\n}\n\nvoid TW_CALL getXXStiffness(void *value, void *clientData)\n{\n\t*(float *)(value) = ((TriangleModel*)clientData)->getXXStiffness();\n}\n\nvoid TW_CALL setYYStiffness(const void *value, void *clientData)\n{\n\tconst float val = *(const float *)(value);\n\t((TriangleModel*)clientData)->setYYStiffness(val);\n}\n\nvoid TW_CALL getYYStiffness(void *value, void *clientData)\n{\n\t*(float *)(value) = ((TriangleModel*)clientData)->getYYStiffness();\n}\n\nvoid TW_CALL setXYStiffness(const void *value, void *clientData)\n{\n\tconst float val = *(const float *)(value);\n\t((TriangleModel*)clientData)->setXYStiffness(val);\n}\n\nvoid TW_CALL getXYStiffness(void *value, void *clientData)\n{\n\t*(float *)(value) = ((TriangleModel*)clientData)->getXYStiffness();\n}\n\nvoid TW_CALL setYXPoissonRatio(const void *value, void *clientData)\n{\n\tconst float val = *(const float *)(value);\n\t((TriangleModel*)clientData)->setYXPoissonRatio(val);\n}\n\nvoid TW_CALL getYXPoissonRatio(void *value, void *clientData)\n{\n\t*(float *)(value) = ((TriangleModel*)clientData)->getYXPoissonRatio();\n}\n\nvoid TW_CALL setXYPoissonRatio(const void *value, void *clientData)\n{\n\tconst float val = *(const float *)(value);\n\t((TriangleModel*)clientData)->setXYPoissonRatio(val);\n}\n\nvoid TW_CALL getXYPoissonRatio(void *value, void *clientData)\n{\n\t*(float *)(value) = ((TriangleModel*)clientData)->getXYPoissonRatio();\n}\n\nvoid TW_CALL setNormalizeStretch(const void *value, void *clientData)\n{\n\tconst bool val = *(const bool *)(value);\n\t((TriangleModel*)clientData)->setNormalizeStretch(val);\n}\n\nvoid TW_CALL getNormalizeStretch(void *value, void *clientData)\n{\n\t*(bool *)(value) = ((TriangleModel*)clientData)->getNormalizeStretch();\n}\n\nvoid TW_CALL setNormalizeShear(const void *value, void *clientData)\n{\n\tconst bool val = *(const bool *)(value);\n\t((TriangleModel*)clientData)->setNormalizeShear(val);\n}\n\nvoid TW_CALL getNormalizeShear(void *value, void *clientData)\n{\n\t*(bool *)(value) = ((TriangleModel*)clientData)->getNormalizeShear();\n}\n\nvoid TW_CALL setBendingStiffness(const void *value, void *clientData)\n{\n\tconst float val = *(const float *)(value);\n\t((TriangleModel*)clientData)->setBendingStiffness(val);\n}\n\nvoid TW_CALL getBendingStiffness(void *value, void *clientData)\n{\n\t*(float *)(value) = ((TriangleModel*)clientData)->getBendingStiffness();\n}\n\nvoid TW_CALL setBendingMethod(const void *value, void *clientData)\n{\n\tconst short val = *(const short *)(value);\n\t((TimeStepTriangleModel*)clientData)->setBendingMethod((unsigned int) val);\n}\n\nvoid TW_CALL getBendingMethod(void *value, void *clientData)\n{\n\t*(short *)(value) = (short) ((TimeStepTriangleModel*)clientData)->getBendingMethod();\n}\n\nvoid TW_CALL setSimulationMethod(const void *value, void *clientData)\n{\n\tconst short val = *(const short *)(value);\n\t((TimeStepTriangleModel*)clientData)->setSimulationMethod((unsigned int)val);\n}\n\nvoid TW_CALL getSimulationMethod(void *value, void *clientData)\n{\n\t*(short *)(value) = (short)((TimeStepTriangleModel*)clientData)->getSimulationMethod();\n}\n\nvoid TW_CALL setVelocityUpdateMethod(const void *value, void *clientData)\n{\n\tconst short val = *(const short *)(value);\n\t((TimeStepTriangleModel*)clientData)->setVelocityUpdateMethod((unsigned int)val);\n}\n\nvoid TW_CALL getVelocityUpdateMethod(void *value, void *clientData)\n{\n\t*(short *)(value) = (short)((TimeStepTriangleModel*)clientData)->getVelocityUpdateMethod();\n}\n\n", "meta": {"hexsha": "b699c3f03c4091349e029dee76b413c6bc6b9142", "size": 15635, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/PositionBasedDynamics/Demos/ClothDemo/main.cpp", "max_stars_repo_name": "joeedh/game.js", "max_stars_repo_head_hexsha": "9271efd2cbbc52ff3ceca7745a0fda114ab613d6", "max_stars_repo_licenses": ["MIT"], "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/PositionBasedDynamics/Demos/ClothDemo/main.cpp", "max_issues_repo_name": "joeedh/game.js", "max_issues_repo_head_hexsha": "9271efd2cbbc52ff3ceca7745a0fda114ab613d6", "max_issues_repo_licenses": ["MIT"], "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/PositionBasedDynamics/Demos/ClothDemo/main.cpp", "max_forks_repo_name": "joeedh/game.js", "max_forks_repo_head_hexsha": "9271efd2cbbc52ff3ceca7745a0fda114ab613d6", "max_forks_repo_licenses": ["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.4535147392, "max_line_length": 256, "alphanum_fraction": 0.7257435241, "num_tokens": 4666, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743168019989179, "lm_q2_score": 0.6619228825191871, "lm_q1q2_score": 0.4919199179873142}}
{"text": "/* Copyright (C) 2012-2020 IBM Corp.\n * This program is Licensed under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *   http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License. See accompanying LICENSE file.\n */\n#include <iostream>\n#include <cassert>\n#include <fstream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <NTL/BasicThreadPool.h>\nNTL_CLIENT\n\n#include <helib/helib.h>\n\n#include <helib/intraSlot.h>\n#include <helib/binaryArith.h>\n#include <helib/ArgMap.h>\n\n#ifdef HELIB_DEBUG\n#include <helib/debugging.h>\n#endif\n\nusing namespace helib;\n\n// define flags FLAG_PRINT_ZZX, FLAG_PRINT_POLY, FLAG_PRINT_VEC, functions\n//        decryptAndPrint(ostream, ctxt, sk, ea, flags)\n//        decryptAndCompare(ctxt, sk, ea, pa);\n\nstatic std::vector<zzX> unpackSlotEncoding; // a global variable\nstatic bool verbose=false;\n\nstatic long mValues[][15] = {\n// { p, phi(m),   m,   d, m1, m2, m3,    g1,   g2,   g3, ord1,ord2,ord3, B,c}\n  {  2,    48,   105, 12,   3, 35,  0,    71,    76,    0,   2,  2,   0, 25, 2},\n  {  2 ,  600,  1023, 10,  11, 93,  0,   838,   584,    0,  10,  6,   0, 25, 2},\n  {  2,  2304,  4641, 24,   7,  3,221,  3979,  3095, 3760,   6,  2,  -8, 25, 3},\n  {  2,  5460,  8193, 26,8193,  0,  0,    46,     0,    0, 210,  0,   0, 25, 3},\n  {  2,  8190,  8191, 13,8191,  0,  0,    39,     0,    0, 630,  0,   0, 25, 3},\n  {  2, 10752, 11441, 48,  17,673,  0,  4712,  2024,    0,  16,-14,   0, 25, 3},\n  {  2, 15004, 15709, 22,  23,683,  0,  4099, 13663,    0,  22, 31,   0, 25, 3},\n  {  2, 27000, 32767, 15,  31,  7,151, 11628, 28087,25824,  30,  6, -10, 28, 4}\n};\n\nvoid test15for4(SecKey& secKey);\nvoid testProduct(SecKey& secKey, long bitSize1, long bitSize2,\n                 long outSize, bool bootstrap = false);\nvoid testAdd(SecKey& secKey, long bitSize1, long bitSize2,\n             long outSize, bool bootstrap = false);\n\nint main(int argc, char *argv[])\n{\n  ArgMap amap;\n  long prm=1;\n  amap.arg(\"prm\", prm, \"parameter size (0-tiny,...,7-huge)\");\n  long bitSize = 5;\n  amap.arg(\"bitSize\", bitSize, \"bitSize of input integers (<=32)\");\n  long bitSize2 = 0;\n  amap.arg(\"bitSize2\", bitSize2, \"bitSize of 2nd input integer (<=32)\",\n           \"same as bitSize\");\n  long outSize = 0;\n  amap.arg(\"outSize\", outSize, \"bitSize of output integers\", \"as many as needed\");\n  long nTests = 2;\n  amap.arg(\"nTests\", nTests, \"number of tests to run\");\n  bool bootstrap = false;\n  amap.arg(\"bootstrap\", bootstrap, \"test multiplication with bootstrapping\");\n  long seed=0;\n  amap.arg(\"seed\", seed, \"PRG seed\");\n  long nthreads=1;\n  amap.arg(\"nthreads\", nthreads, \"number of threads\");\n  amap.arg(\"verbose\", verbose, \"print more information\");\n\n  long tests2avoid = 1;\n  amap.arg(\"tests2avoid\", tests2avoid, \"bitmap of tests to disable (1-15for4, 2-add, 4-multiply\");\n\n  amap.parse(argc, argv);\n  assert(prm >= 0 && prm < 5);\n  if (seed) NTL::SetSeed(ZZ(seed));\n  if (nthreads>1) NTL::SetNumThreads(nthreads);\n\n  if (bitSize<=0) bitSize=5;\n  else if (bitSize>32) bitSize=32;\n  if (bitSize2<=0) bitSize2=bitSize;\n  else if (bitSize2>32) bitSize2=32;\n\n  long* vals = mValues[prm];\n  long p = vals[0];\n  //  long phim = vals[1];\n  long m = vals[2];\n\n  NTL::Vec<long> mvec;\n  append(mvec, vals[4]);\n  if (vals[5]>1) append(mvec, vals[5]);\n  if (vals[6]>1) append(mvec, vals[6]);\n\n  std::vector<long> gens;\n  gens.push_back(vals[7]);\n  if (vals[8]>1) gens.push_back(vals[8]);\n  if (vals[9]>1) gens.push_back(vals[9]);\n\n  std::vector<long> ords;\n  ords.push_back(vals[10]);\n  if (abs(vals[11])>1) ords.push_back(vals[11]);\n  if (abs(vals[12])>1) ords.push_back(vals[12]);\n\n  long B = vals[13];\n  long c = vals[14];\n\n  // Compute the number of levels\n  long L;\n  if (bootstrap) L=900; // that should be enough\n  else {\n    double nBits =\n      (outSize>0 && outSize<2*bitSize)? outSize : (2*bitSize);\n    double three4twoLvls = log(nBits/2) / log(1.5);\n    double add2NumsLvls = log(nBits) / log(2.0);\n    L = (5 + ceil(three4twoLvls + add2NumsLvls))*30;\n  }\n\n  if (verbose) {\n    cout <<\"input bitSizes=\"<<bitSize<<','<<bitSize2\n         <<\", output size bound=\"<<outSize\n         <<\", running \"<<nTests<<\" tests for each function\\n\";\n    if (nthreads>1) cout << \"  using \"<<NTL::AvailableThreads()<<\" threads\\n\";\n    cout << \"computing key-independent tables...\" << std::flush;\n  }\n  Context context(m, p, /*r=*/1, gens, ords);\n  buildModChain(context, L, c,/*willBeBootstrappable=*/bootstrap);\n  if (bootstrap) {\n    context.makeBootstrappable(mvec, /*t=*/0);\n  }\n  buildUnpackSlotEncoding(unpackSlotEncoding, *context.ea);\n  if (verbose) {\n    cout << \" done.\\n\";\n    context.zMStar.printout();\n    cout << \" L=\"<<L<<\", B=\"<<B<<endl;\n    cout << \"\\ncomputing key-dependent tables...\" << std::flush;\n  }\n  SecKey secKey(context);\n  secKey.GenSecKey();\n  addSome1DMatrices(secKey); // compute key-switching matrices\n  addFrbMatrices(secKey);\n  if (bootstrap) secKey.genRecryptData();\n  if (verbose) cout << \" done\\n\";\n\n  activeContext = &context; // make things a little easier sometimes\n#ifdef HELIB_DEBUG\n  dbgEa = context.ea;\n  dbgKey = &secKey;\n#endif\n\n  if (!(tests2avoid & 1)) {\n    for (long i=0; i<nTests; i++)\n      test15for4(secKey);\n    cout << \"GOOD\\n\";\n  }\n  if (!(tests2avoid & 2)) {\n    for (long i=0; i<nTests; i++)\n      testAdd(secKey, bitSize, bitSize2, outSize, bootstrap);\n    cout << \"GOOD\\n\";\n  }\n  if (!(tests2avoid & 4)) {\n    for (long i=0; i<nTests; i++)\n      testProduct(secKey, bitSize, bitSize2, outSize, bootstrap);\n    cout << \"GOOD\\n\";\n  }\n  if (verbose) printAllTimers(cout);\n  return 0;\n}\n\nvoid test15for4(SecKey& secKey)\n{\n  std::vector<Ctxt> inBuf(15, Ctxt(secKey));\n  std::vector<Ctxt*> inPtrs(15, nullptr);\n\n  std::vector<Ctxt> outBuf(5, Ctxt(secKey));\n\n  long sum=0;\n  std::string inputBits = \"(\";\n  for (int i=0; i<15; i++) {\n    if (NTL::RandomBnd(10)>0) { // leave empty with small probability\n      inPtrs[i] = &(inBuf[i]);\n      long bit = NTL::RandomBnd(2);  // a random bit\n      secKey.Encrypt(inBuf[i], ZZX(bit));\n      inputBits += std::to_string(bit) + \",\";\n      sum += bit;\n    }\n    else inputBits += \"-,\";\n  }\n  inputBits += \")\";\n\n  // Add these bits\n  if (verbose) {\n    cout << endl;\n    CheckCtxt(inBuf[lsize(inBuf)-1], \"b4 15for4\");\n  }\n  long numOutputs\n    = fifteenOrLess4Four(CtPtrs_vectorCt(outBuf), CtPtrs_vectorPt(inPtrs));\n  if (verbose)\n    CheckCtxt(outBuf[lsize(outBuf)-1], \"after 15for4\");\n\n  // Check the result\n  long sum2=0;\n  for (int i=0; i<numOutputs; i++) {\n    ZZX poly;\n    secKey.Decrypt(poly, outBuf[i]);\n    sum2 += to_long(ConstTerm(poly)) << i;\n  }\n  if (sum != sum2) {\n    cout << \"BAD\\n\";\n    if (verbose) {\n      cout << \"  15to4: inputs=\"<<inputBits<<\", sum=\"<<sum\n           << \" but sum2=\"<<sum2<<endl;\n    }\n    exit(0);\n  }\n  else if (verbose)\n    cout << \"15to4 succeeded, sum\"<<inputBits<<\"=\"<<sum2<<endl;\n}\n\nvoid testProduct(SecKey& secKey, long bitSize, long bitSize2,\n                 long outSize, bool bootstrap)\n{\n  const Context& context = secKey.getContext();\n  const EncryptedArray& ea = *(context.ea);\n  long mask = (outSize? ((1L<<outSize)-1) : -1);\n\n  // Choose two random n-bit integers\n  long pa = RandomBits_long(bitSize);\n  long pb = RandomBits_long(bitSize2);\n\n  // Encrypt the individual bits\n  NTL::Vec<Ctxt> eProduct, enca, encb;\n\n  resize(enca, bitSize, Ctxt(secKey));\n  for (long i=0; i<bitSize; i++) {\n    secKey.Encrypt(enca[i], ZZX((pa>>i)&1));\n    if (bootstrap) { // put them at a lower level\n      enca[i].bringToSet(context.getCtxtPrimes(5));\n    }\n  }\n  resize(encb, bitSize2, Ctxt(secKey));\n  for (long i=0; i<bitSize2; i++) {\n    secKey.Encrypt(encb[i], ZZX((pb>>i)&1));\n    if (bootstrap) { // put them at a lower level\n      encb[i].bringToSet(context.getCtxtPrimes(5));\n    }\n  }\n  if (verbose) {\n    cout << \"\\n  bits-size \"<<bitSize<<'+'<<bitSize2;\n    if (outSize>0) cout << \"->\"<<outSize;\n    CheckCtxt(encb[0], \"b4 multiplication\");\n  }\n  // Test positive multiplication\n  vector<long> slots;\n  {CtPtrs_VecCt eep(eProduct);  // A wrappers around the output vector\n  multTwoNumbers(eep,CtPtrs_VecCt(enca),CtPtrs_VecCt(encb),/*negative=*/false,\n                 outSize, &unpackSlotEncoding);\n  decryptBinaryNums(slots, eep, secKey, ea);\n  } // get rid of the wrapper\n  if (verbose)\n    CheckCtxt(eProduct[lsize(eProduct)-1], \"after multiplication\");\n  long pProd = pa*pb;\n  if (slots[0] != ((pa*pb)&mask)) {\n    cout << \"BAD\\n\";\n    if (verbose)\n      cout << \"Positive product error: pa=\"<<pa<<\", pb=\"<<pb\n           << \", but product=\"<<slots[0]\n           << \" (should be \"<<pProd<<'&'<<mask<<'='<<(pProd&mask)<<\")\\n\";\n    exit(0);\n  }\n  else if (verbose) {\n    cout << \"positive product succeeded: \";\n    if (outSize) cout << \"bottom \"<<outSize<<\" bits of \";\n    cout << pa<<\"*\"<<pb<<\"=\"<<slots[0]<<endl;\n  }\n  // Test negative multiplication\n  secKey.Encrypt(encb[bitSize2-1], ZZX(1));\n  decryptBinaryNums(slots, CtPtrs_VecCt(encb), secKey, ea, /*negative=*/true);\n  pb = slots[0];\n  eProduct.kill();\n  {CtPtrs_VecCt eep(eProduct);  // A wrappers around the output vector\n  multTwoNumbers(eep,CtPtrs_VecCt(enca),CtPtrs_VecCt(encb),/*negative=*/true,\n                 outSize, &unpackSlotEncoding);\n  decryptBinaryNums(slots, eep, secKey, ea, /*negative=*/true);\n  } // get rid of the wrapper\n  if (verbose)\n    CheckCtxt(eProduct[lsize(eProduct)-1], \"after multiplication\");\n  pProd = pa*pb;\n  if ((slots[0]&mask) != (pProd&mask)) {\n    cout << \"BAD\\n\";\n    if (verbose)\n      cout << \"Negative product error: pa=\"<<pa<<\", pb=\"<<pb\n           << \", but product=\"<<slots[0]\n           << \" (should be \"<<pProd<<'&'<<mask<<'='<<(pProd&mask)<<\")\\n\";\n    exit(0);\n  }\n  else if (verbose) {\n    cout << \"negative product succeeded: \";\n    if (outSize) cout << \"bottom \"<<outSize<<\" bits of \";\n    cout << pa<<\"*\"<<pb<<\"=\"<<slots[0]<<endl;\n  }\n\n#ifdef HELIB_DEBUG\n  const Ctxt* minCtxt = nullptr;\n  long minLvl=1000;\n  for (const Ctxt& c: eProduct) {\n    long lvl = c.logOfPrimeSet();\n    if (lvl < minLvl) {\n      minCtxt = &c;\n      minLvl = lvl;\n    }\n  }\n  decryptAndPrint((cout<<\" after multiplication: \"), *minCtxt, secKey, ea,0);\n  cout << endl;\n#endif\n}\n\n\nvoid testAdd(SecKey& secKey, long bitSize1, long bitSize2,\n             long outSize, bool bootstrap)\n{\n  const Context& context = secKey.getContext();\n  const EncryptedArray& ea = *(context.ea);\n  long mask = (outSize? ((1L<<outSize)-1) : -1);\n\n  // Choose two random n-bit integers\n  long pa = RandomBits_long(bitSize1);\n  long pb = RandomBits_long(bitSize2);\n\n  // Encrypt the individual bits\n  NTL::Vec<Ctxt> eSum, enca, encb;\n\n  resize(enca, bitSize1, Ctxt(secKey));\n  for (long i=0; i<bitSize1; i++) {\n    secKey.Encrypt(enca[i], ZZX((pa>>i)&1));\n    if (bootstrap) { // put them at a lower level\n      enca[i].bringToSet(context.getCtxtPrimes(5));\n    }\n  }\n  resize(encb, bitSize2, Ctxt(secKey));\n  for (long i=0; i<bitSize2; i++) {\n    secKey.Encrypt(encb[i], ZZX((pb>>i)&1));\n    if (bootstrap) { // put them at a lower level\n      encb[i].bringToSet(context.getCtxtPrimes(5));\n    }\n  }\n  if (verbose) {\n    cout << \"\\n  bits-size \"<<bitSize1<<'+'<<bitSize2;\n    if (outSize>0) cout << \"->\"<<outSize;\n    cout <<endl;\n    CheckCtxt(encb[0], \"b4 addition\");\n  }\n\n  // Test addition\n  vector<long> slots;\n  {CtPtrs_VecCt eep(eSum);  // A wrapper around the output vector\n  addTwoNumbers(eep, CtPtrs_VecCt(enca), CtPtrs_VecCt(encb),\n                outSize, &unpackSlotEncoding);\n  decryptBinaryNums(slots, eep, secKey, ea);\n  } // get rid of the wrapper\n  if (verbose) CheckCtxt(eSum[lsize(eSum)-1], \"after addition\");\n  long pSum = pa+pb;\n  if (slots[0] != ((pa+pb)&mask)) {\n    cout << \"BAD\\n\";\n    if (verbose)\n      cout << \"addTwoNums error: pa=\"<<pa<<\", pb=\"<<pb\n           << \", but pSum=\"<<slots[0]\n           << \" (should be =\"<<(pSum&mask)<<\")\\n\";\n    exit(0);\n  }\n  else if (verbose) {\n    cout << \"addTwoNums succeeded: \";\n    if (outSize) cout << \"bottom \"<<outSize<<\" bits of \";\n    cout << pa<<\"+\"<<pb<<\"=\"<<slots[0]<<endl;\n  }\n\n#ifdef HELIB_DEBUG\n  const Ctxt* minCtxt = nullptr;\n  long minLvl=1000;\n  for (const Ctxt& c: eSum) {\n    long lvl = c.logOfPrimeSet();\n    if (lvl < minLvl) {\n      minCtxt = &c;\n      minLvl = lvl;\n    }\n  }\n  decryptAndPrint((cout<<\" after addition: \"), *minCtxt, secKey, ea,0);\n  cout << endl;\n#endif\n}\n", "meta": {"hexsha": "0496ca489175e96c426ee8bd4ddef0736c3ed4f3", "size": 12697, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "misc/legacy_tests/Test_binaryArith.cpp", "max_stars_repo_name": "andrey-mindrin/HElib", "max_stars_repo_head_hexsha": "6b9ae8b5ab43af3b566598c095d4edaba6d6a775", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1360.0, "max_stars_repo_stars_event_min_datetime": "2015-01-02T23:57:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T01:25:28.000Z", "max_issues_repo_path": "misc/legacy_tests/Test_binaryArith.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": "misc/legacy_tests/Test_binaryArith.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": 31.8220551378, "max_line_length": 98, "alphanum_fraction": 0.6077813657, "num_tokens": 4348, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.6619228891883799, "lm_q1q2_score": 0.49191991541314833}}
{"text": "#include <blitz/array.h>\n\nusing namespace blitz;\n\nint main()\n{\n    Array<int,2> A(8,8);\n    A = 0;\n\n    Array<int,2> B = A(Range(1,7,3), Range(1,5,2));\n    B = 1;\n\n    cout << \"A = \" << A << endl;\n    return 0;\n}\n\n", "meta": {"hexsha": "ae32214e920dd9ba48cf0e7ef9db77d622115c7f", "size": 214, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depspawn-blitz-0.10/doc/examples/strideslice.cpp", "max_stars_repo_name": "fraguela/depspawn", "max_stars_repo_head_hexsha": "b5760f4c0d38a1b245ee5274e2ccc5c5fe2d3d45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-04-12T11:05:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T11:10:27.000Z", "max_issues_repo_path": "ibtk/third_party/blitz-0.10/doc/examples/strideslice.cpp", "max_issues_repo_name": "MSV-Project/IBAMR", "max_issues_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ibtk/third_party/blitz-0.10/doc/examples/strideslice.cpp", "max_forks_repo_name": "MSV-Project/IBAMR", "max_forks_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 12.5882352941, "max_line_length": 51, "alphanum_fraction": 0.4859813084, "num_tokens": 83, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.49191990550048675}}
{"text": "#include <fstream>\n#include <boost/config.hpp>\n#include <boost/version.hpp>\n\n// CGAL headers\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Regular_triangulation_2.h>\n#include <CGAL/IO/WKT.h>\n\n#include <CGAL/point_generators_2.h>\n// Qt headers\n#include <QtGui>\n#include <QString>\n#include <QActionGroup>\n#include <QFileDialog>\n#include <QInputDialog>\n\n// GraphicsView items and event filters (input classes)\n\n#include \"RegularTriangulationRemoveVertex.h\"\n#include <CGAL/Qt/GraphicsViewCircleInput.h>\n#include <CGAL/Qt/RegularTriangulationGraphicsItem.h>\n#include <CGAL/Qt/PowerdiagramGraphicsItem.h>\n\n// for viewportsBbox\n#include <CGAL/Qt/utility.h>\n// the two base classes\n#include \"ui_Regular_triangulation_2.h\"\n#include <CGAL/Qt/DemosMainWindow.h>\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\ntypedef K::Point_2                                          Point_2;\ntypedef K::Weighted_point_2                                 Weighted_point_2;\ntypedef K::Point_2                                          Circle_2;\ntypedef K::Iso_rectangle_2                                  Iso_rectangle_2;\n\ntypedef CGAL::Regular_triangulation_2<K>                    Regular;\n\nclass MainWindow :\n  public CGAL::Qt::DemosMainWindow,\n  public Ui::Regular_triangulation_2\n{\n  Q_OBJECT\n\nprivate:\n  Regular dt;\n  QGraphicsScene scene;\n\n  CGAL::Qt::RegularTriangulationGraphicsItem<Regular> * dgi;\n  CGAL::Qt::PowerdiagramGraphicsItem<Regular> * vgi;\n\n  CGAL::Qt::RegularTriangulationRemoveVertex<Regular> * trv;\n  CGAL::Qt::GraphicsViewCircleInput<K> * pi;\npublic:\n  MainWindow();\n\npublic Q_SLOTS:\n\n  void processInput(CGAL::Object o);\n\n  void on_actionShowRegular_toggled(bool checked);\n\n  void on_actionShowPowerdiagram_toggled(bool checked);\n\n  void on_actionInsertPoint_toggled(bool checked);\n\n  void on_actionInsertRandomPoints_triggered();\n\n  void on_actionLoadPoints_triggered();\n\n  void on_actionSavePoints_triggered();\n\n  void on_actionClear_triggered();\n\n  void on_actionRecenter_triggered();\n\n\nQ_SIGNALS:\n  void changed();\n};\n\n\nMainWindow::MainWindow()\n  : DemosMainWindow()\n{\n  setupUi(this);\n\n  // Add a GraphicItem for the regular triangulation\n  dgi = new CGAL::Qt::RegularTriangulationGraphicsItem<Regular>(&dt);\n\n  QObject::connect(this, SIGNAL(changed()),\n                   dgi, SLOT(modelChanged()));\n\n  dgi->setVerticesPen(QPen(Qt::red, 0, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));\n  dgi->setEdgesPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));\n  scene.addItem(dgi);\n\n  // Add a GraphicItem for the Powerdiagram diagram\n  vgi = new CGAL::Qt::PowerdiagramGraphicsItem<Regular>(&dt);\n\n  QObject::connect(this, SIGNAL(changed()),\n                   vgi, SLOT(modelChanged()));\n\n  vgi->setEdgesPen(QPen(Qt::blue, 0, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));\n  scene.addItem(vgi);\n  vgi->hide();\n\n  // Setup input handlers. They get events before the scene gets them\n  // and the input they generate is passed to the triangulation with\n  // the signal/slot mechanism\n  pi = new CGAL::Qt::GraphicsViewCircleInput<K>(this, &scene, 1); // emits center/radius\n\n\n  QObject::connect(pi, SIGNAL(generate(CGAL::Object)),\n                   this, SLOT(processInput(CGAL::Object)));\n\n  trv = new CGAL::Qt::RegularTriangulationRemoveVertex<Regular>(&dt, this);\n  QObject::connect(trv, SIGNAL(modelChanged()),\n                   this, SIGNAL(changed()));\n\n  //\n  // Manual handling of actions\n  //\n  QObject::connect(this->actionQuit, SIGNAL(triggered()),\n                   this, SLOT(close()));\n\n  // We put mutually exclusive actions in an QActionGroup\n  QActionGroup* ag = new QActionGroup(this);\n  ag->addAction(this->actionInsertPoint);\n\n  // Check two actions\n  this->actionInsertPoint->setChecked(true);\n  this->actionShowRegular->setChecked(true);\n\n  //\n  // Setup the scene and the view\n  //\n  scene.setItemIndexMethod(QGraphicsScene::NoIndex);\n  scene.setSceneRect(-100, -100, 100, 100);\n  this->graphicsView->setScene(&scene);\n  this->graphicsView->setMouseTracking(true);\n\n  // Turn the vertical axis upside down\n  this->graphicsView->transform().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/about_Regular_triangulation_2.html\");\n  this->addAboutCGAL();\n}\n\n\nvoid\nMainWindow::processInput(CGAL::Object o)\n{\n  std::pair<Point_2, K::FT > center_sqr;\n  if(CGAL::assign(center_sqr, o)){\n    Regular::Point wp(center_sqr.first, center_sqr.second);\n    dt.insert(wp);\n  }\n\n  Q_EMIT( changed());\n}\n\n\n/*\n *  Qt Automatic Connections\n *  https://doc.qt.io/qt-5/designer-using-a-ui-file.html#automatic-connections\n *\n *  setupUi(this) generates connections to the slots named\n *  \"on_<action_name>_<signal_name>\"\n */\nvoid\nMainWindow::on_actionInsertPoint_toggled(bool checked)\n{\n  if(checked){\n    scene.installEventFilter(pi);\n    scene.installEventFilter(trv);\n  } else {\n    scene.removeEventFilter(pi);\n    scene.removeEventFilter(trv);\n  }\n}\n\n\n\nvoid\nMainWindow::on_actionShowRegular_toggled(bool checked)\n{\n  dgi->setVisibleEdges(checked);\n}\n\n\nvoid\nMainWindow::on_actionShowPowerdiagram_toggled(bool checked)\n{\n  vgi->setVisible(checked);\n}\n\n\nvoid\nMainWindow::on_actionClear_triggered()\n{\n  dt.clear();\n  Q_EMIT( changed());\n}\n\n\nvoid\nMainWindow::on_actionInsertRandomPoints_triggered()\n{\n  QRectF rect = CGAL::Qt::viewportsBbox(&scene);\n  CGAL::Qt::Converter<K> convert;\n  Iso_rectangle_2 isor = convert(rect);\n  CGAL::Random_points_in_iso_rectangle_2<Point_2> pg((isor.min)(), (isor.max)());\n  CGAL::Random rnd(CGAL::get_default_random());\n\n  const int number_of_points =\n    QInputDialog::getInt(this,\n                             tr(\"Number of random points\"),\n                             tr(\"Enter number of random points\"), 100, 0);\n\n  // wait cursor\n  QApplication::setOverrideCursor(Qt::WaitCursor);\n  std::vector<Weighted_point_2> points;\n  points.reserve(number_of_points);\n  for(int i = 0; i < number_of_points; ++i){\n    Weighted_point_2 wp(*pg++, rnd.get_double(0, 500));\n    points.push_back(wp);\n  }\n  dt.insert(points.begin(), points.end());\n  // default cursor\n  QApplication::setOverrideCursor(Qt::ArrowCursor);\n  Q_EMIT( changed());\n}\n\n\nvoid\nMainWindow::on_actionLoadPoints_triggered()\n{\n  QString fileName = QFileDialog::getOpenFileName(this,\n                                                  tr(\"Open Points file\"),\n                                                  \".\",\n                                                  tr(\"Weighted Points (*.wpts.cgal);;\"\n                                                     \"WKT files (*.wkt *.WKT);;\"\n                                                     \"All (*)\"));\n\n  if(! fileName.isEmpty()){\n    std::ifstream ifs(qPrintable(fileName));\n    std::vector<Weighted_point_2> points;\n    if(fileName.endsWith(\".wkt\",Qt::CaseInsensitive))\n    {\n      std::vector<K::Point_3> points_3;\n      CGAL::IO::read_multi_point_WKT(ifs, points_3);\n      for(const K::Point_3& p : points_3)\n      {\n        points.push_back(Weighted_point_2(K::Point_2(p.x(), p.y()), p.z()));\n      }\n    }\n    else\n    {\n      Weighted_point_2 p;\n      while(ifs >> p) {\n        points.push_back(p);\n      }\n    }\n    dt.insert(points.begin(), points.end());\n\n    actionRecenter->trigger();\n    Q_EMIT( changed());\n  }\n}\n\n\nvoid\nMainWindow::on_actionSavePoints_triggered()\n{\n  QString fileName = QFileDialog::getSaveFileName(this,\n                                                  tr(\"Save points\"),\n                                                  \".reg.cgal\",\n                                                  tr(\"Weighted Points (*.wpts.cgal);;\"\n                                                     \"WKT files (*.wkt *.WKT);;\"\n                                                     \"All (*)\"));\n  if(! fileName.isEmpty()){\n    std::ofstream ofs(qPrintable(fileName));\n    if(fileName.endsWith(\".wkt\",Qt::CaseInsensitive))\n    {\n      std::vector<K::Point_3> points_3;\n      for(Regular::Finite_vertices_iterator\n          vit = dt.finite_vertices_begin(),\n          end = dt.finite_vertices_end();\n          vit!= end; ++vit)\n      {\n        points_3.push_back(K::Point_3(vit->point().x(),\n                                      vit->point().y(),\n                                      vit->point().weight()));\n      }\n      CGAL::IO::write_multi_point_WKT(ofs, points_3);\n    }\n    else\n    {\n      for(Regular::Finite_vertices_iterator\n          vit = dt.finite_vertices_begin(),\n          end = dt.finite_vertices_end();\n          vit!= end; ++vit)\n      {\n        ofs << vit->point() << std::endl;\n      }\n    }\n  }\n}\n\n\nvoid\nMainWindow::on_actionRecenter_triggered()\n{\n  this->graphicsView->setSceneRect(dgi->boundingRect());\n  this->graphicsView->fitInView(dgi->boundingRect(), Qt::KeepAspectRatio);\n}\n\n\n#include \"Regular_triangulation_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(\"Regular_triangulation_2 demo\");\n\n  // Import resources from libCGAL (Qt5).\n  CGAL_QT_INIT_RESOURCES;\n\n  MainWindow mainWindow;\n  mainWindow.show();\n\n  QStringList args = app.arguments();\n  args.removeAt(0);\n  Q_FOREACH(QString filename, args) {\n    mainWindow.open(filename);\n  }\n\n  return app.exec();\n}\n", "meta": {"hexsha": "6df0dd31901159f7765c26234fe2b4d792416e13", "size": 9466, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "GraphicsView/demo/Triangulation_2/Regular_triangulation_2.cpp", "max_stars_repo_name": "ffteja/cgal", "max_stars_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 3227.0, "max_stars_repo_stars_event_min_datetime": "2015-03-05T00:19:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:20:35.000Z", "max_issues_repo_path": "GraphicsView/demo/Triangulation_2/Regular_triangulation_2.cpp", "max_issues_repo_name": "ffteja/cgal", "max_issues_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 5574.0, "max_issues_repo_issues_event_min_datetime": "2015-03-05T00:01:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:08:11.000Z", "max_forks_repo_path": "GraphicsView/demo/Triangulation_2/Regular_triangulation_2.cpp", "max_forks_repo_name": "ffteja/cgal", "max_forks_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1274.0, "max_forks_repo_forks_event_min_datetime": "2015-03-05T00:01:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:47:56.000Z", "avg_line_length": 26.9686609687, "max_line_length": 88, "alphanum_fraction": 0.63860131, "num_tokens": 2284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.6619228758499941, "lm_q1q2_score": 0.49191990550048675}}
{"text": "#include <blitz/array.h>\n\nBZ_USING_NAMESPACE(blitz)\n\nint main()\n{\n  Array<complex<float>,2> test(4,4) ;\n Array<float,2> test2(2,2) ;\n\n test2 = real(test(Range(0,1),Range(0,1))) ;\n Array<float,2> test3;\n test3.reference(test2(Range(0,1),Range(0,1)));\n\n return 0;\n}\n\n", "meta": {"hexsha": "784e8c9f28887e9e7131b81be79d5ee9298086fc", "size": 265, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depspawn-blitz-0.10/testsuite/chris-jeffery-2.cpp", "max_stars_repo_name": "fraguela/depspawn", "max_stars_repo_head_hexsha": "b5760f4c0d38a1b245ee5274e2ccc5c5fe2d3d45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-04-12T11:05:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T11:10:27.000Z", "max_issues_repo_path": "ibtk/third_party/blitz-0.10/testsuite/chris-jeffery-2.cpp", "max_issues_repo_name": "MSV-Project/IBAMR", "max_issues_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ibtk/third_party/blitz-0.10/testsuite/chris-jeffery-2.cpp", "max_forks_repo_name": "MSV-Project/IBAMR", "max_forks_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.5882352941, "max_line_length": 47, "alphanum_fraction": 0.6528301887, "num_tokens": 97, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.49191990054415596}}
{"text": "#ifndef SKYLARK_INNER_HPP\n#define SKYLARK_INNER_HPP\n\n#include <boost/mpi.hpp>\n\nnamespace skylark { namespace base {\n\ntemplate<typename T>\ninline elem::Base<T> Nrm2(const elem::Matrix<T>& x) {\n    return elem::Nrm2(x);\n}\n\ntemplate<typename T>\ninline elem::Base<T> Nrm2(const elem::DistMatrix<T>& x) {\n    return elem::Nrm2(x);\n}\n\ntemplate<typename T>\ninline elem::Base<T> Nrm2(const elem::DistMatrix<T, elem::VC, elem::STAR>& x) {\n    boost::mpi::communicator comm(x.DistComm(), boost::mpi::comm_attach);\n    T local = elem::Nrm2(x.LockedMatrix());\n    T snrm = boost::mpi::all_reduce(comm, local * local, std::plus<T>());\n    return sqrt(snrm);\n}\n\ntemplate<typename T>\ninline elem::Base<T> Nrm2(const elem::DistMatrix<T, elem::VR, elem::STAR>& x) {\n    boost::mpi::communicator comm(x.DistComm(), boost::mpi::comm_attach);\n    T local = elem::Nrm2(x.LockedMatrix());\n    T snrm = boost::mpi::all_reduce(comm, local * local, std::plus<T>());\n    return sqrt(snrm);\n}\n\ntemplate<typename T>\ninline elem::Base<T> Nrm2(const elem::DistMatrix<T, elem::STAR, elem::STAR>& x) {\n    return elem::Nrm2(x.LockedMatrix());\n}\n\ntemplate<typename T>\ninline void ColumnNrm2(const elem::Matrix<T>& A,\n    elem::Matrix<elem::Base<T> >& N) {\n\n    double *n = N.Buffer();\n    const double *a = A.LockedBuffer();\n    for(int j = 0; j < A.Width(); j++) {\n        n[j] = 0.0;\n        for(int i = 0; i < A.Height(); i++)\n            n[j] += a[j * A.LDim() + i] * elem::Conj(a[j * A.LDim() + i]);\n        n[j] = sqrt(n[j]);\n    }\n}\n\ntemplate<typename T>\ninline void ColumnNrm2(const elem::DistMatrix<T, elem::STAR, elem::STAR>& A,\n    elem::DistMatrix<elem::Base<T>, elem::STAR, elem::STAR>& N) {\n\n    double *n = N.Buffer();\n    const double *a = A.LockedBuffer();\n    for(int j = 0; j < A.Width(); j++) {\n        n[j] = 0.0;\n        for(int i = 0; i < A.LocalHeight(); i++)\n            n[j] += a[j * A.LDim() + i] * elem::Conj(a[j * A.LDim() + i]);\n        n[j] = sqrt(n[j]);\n    }\n}\n\ntemplate<typename T>\ninline void ColumnNrm2(const elem::DistMatrix<T, elem::VC, elem::STAR>& A,\n    elem::DistMatrix<elem::Base<T>, elem::STAR, elem::STAR>& N) {\n\n    std::vector<T> n(A.Width(), 1);\n    const elem::Matrix<T> &Al = A.LockedMatrix();\n    const double *a = Al.LockedBuffer();\n    for(int j = 0; j < Al.Width(); j++) {\n        n[j] = 0.0;\n        for(int i = 0; i < Al.Height(); i++)\n            n[j] += a[j * Al.LDim() + i] * elem::Conj(a[j * Al.LDim() + i]);\n    }\n    N.Resize(A.Width(), 1);\n    elem::Zero(N);\n    boost::mpi::communicator comm(N.Grid().Comm(), boost::mpi::comm_attach);\n    boost::mpi::all_reduce(comm, n.data(), A.Width(), N.Buffer(), std::plus<T>());\n    for(int j = 0; j < A.Width(); j++)\n        N.Set(j, 0, sqrt(N.Get(j, 0)));\n}\n\ntemplate<typename T>\ninline void ColumnDot(const elem::Matrix<T>& A, const elem::Matrix<T>& B,\n    elem::Matrix<elem::Base<T> >& N) {\n\n    // TODO just assuming sizes are OK for now.\n\n    double *n = N.Buffer();\n    const double *a = A.LockedBuffer();\n    const double *b = B.LockedBuffer();\n    for(int j = 0; j < A.Width(); j++) {\n        n[j] = 0.0;\n        for(int i = 0; i < A.Height(); i++)\n            n[j] += a[j * A.LDim() + i] * elem::Conj(b[j * B.LDim() + i]);\n    }\n}\n\ntemplate<typename T>\ninline void ColumnDot(const elem::DistMatrix<T, elem::STAR, elem::STAR>& A,\n    const elem::DistMatrix<T, elem::STAR, elem::STAR>& B,\n    elem::DistMatrix<elem::Base<T>, elem::STAR, elem::STAR>& N) {\n\n    // TODO just assuming sizes are OK for now.\n\n    double *n = N.Buffer();\n    const double *a = A.LockedBuffer();\n    const double *b = B.LockedBuffer();\n    for(int j = 0; j < A.Width(); j++) {\n        n[j] = 0.0;\n        for(int i = 0; i < A.LocalHeight(); i++)\n            n[j] += a[j * A.LDim() + i] * elem::Conj(b[j * B.LDim() + i]);\n    }\n}\n\ntemplate<typename T>\ninline void ColumnDot(const elem::DistMatrix<T, elem::VC, elem::STAR>& A,\n    const elem::DistMatrix<T, elem::VC, elem::STAR>& B,\n    elem::DistMatrix<elem::Base<T>, elem::STAR, elem::STAR>& N) {\n\n    // TODO just assuming sizes are OK for now.\n\n    std::vector<T> n(A.Width(), 1);\n    const elem::Matrix<T> &Al = A.LockedMatrix();\n    const double *a = Al.LockedBuffer();\n    const elem::Matrix<T> &Bl = B.LockedMatrix();\n    const double *b = Bl.LockedBuffer();\n   for(int j = 0; j < Al.Width(); j++) {\n        n[j] = 0.0;\n        for(int i = 0; i < Al.Height(); i++)\n            n[j] += a[j * Al.LDim() + i] * elem::Conj(b[j * Bl.LDim() + i]);\n    }\n    N.Resize(A.Width(), 1);\n    elem::Zero(N);\n    boost::mpi::communicator comm(N.Grid().Comm(), boost::mpi::comm_attach);\n    boost::mpi::all_reduce(comm, n.data(), A.Width(), N.Buffer(), std::plus<T>());\n}\n\ntemplate<typename T>\ninline void RowDot(const elem::Matrix<T>& A, const elem::Matrix<T>& B,\n    elem::Matrix<elem::Base<T> >& N) {\n\n    // TODO just assuming sizes are OK for now.\n\n    double *n = N.Buffer();\n    const double *a = A.LockedBuffer();\n    const double *b = B.LockedBuffer();\n    for(int i = 0; i < A.Height(); i++)\n        n[i] = 0.0;\n\n    for(int j = 0; j < A.Width(); j++) {\n        for(int i = 0; i < A.Height(); i++)\n            n[i] += a[j * A.LDim() + i] * elem::Conj(b[j * B.LDim() + i]);\n    }\n}\n\n} } // namespace skylark::base\n\n#endif // SKYLARK_INNER_HPP\n", "meta": {"hexsha": "ba20014e8b147d0e2c6c9e37386760285c1b9a1f", "size": 5248, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "base/inner.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/inner.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/inner.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": 32.0, "max_line_length": 82, "alphanum_fraction": 0.5604039634, "num_tokens": 1659, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.6619228625116081, "lm_q1q2_score": 0.491919895587825}}
{"text": "/*\n * monte.cpp - monte carlo simulation of acoustic phonon scattering\n */\n\n/*\n * HISTORY\n * 16-Oct-88 Jeffrey Trull (jt1j) at Carnegie-Mellon University\n *       Created\n * 23-May-18 Jeffrey Trull (edaskel@att.net)\n *       Converted to Modern C++, fixed bugs\n */\n\n// Note to interested readers:\n// This program is an updated version of a programming assignment from a semiconductor\n// physics class in 1988... The textbook was Michael Shur's \"GaAs Devices and Circuits\".\n// The assignment was to estimate the electron mobility in the material by simulating\n// one particular scattering mechanism: acoustic phonons. This was done not because they\n// are the dominant mechanism, but because it makes for a tractable problem :)\n// The general approach followed is given in Chapter 2 of Shur's textbook; another helpful\n// source I (in retrospect) found is:\n// Jacoboni and Reggiani: Monte Carlo Method in Transport (Rev Mod Phys, July 1983)\n// which gives a more detailed explanation/motivation of the process\n\n\n#include <vector>\n#include <iostream>\n#include <random>\n\n#include <cmath>\n\n#include <boost/units/systems/si.hpp>\n#include <boost/units/cmath.hpp>\n#include <boost/units/io.hpp>\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/weighted_mean.hpp>\n\n#include \"monte.hpp\"\n\nusing namespace boost::units;\nusing namespace boost::units::si;\nusing namespace monte;\n\nusing vector = vector_str<float>;\n\nvector                kinit;         /* k vector prior to collision */\nfloat                 capgamma_f;    /* total scattering rate */\nint                   numtrials;     /* number of scattering events to perform */\nquantity<frequency>   maxlambda;     /* highest lambda ever calculated */\nint                   num_real_events;\n\nint main(int argc, char **argv)\n    /* initialize, then perform a number of scattering events specified by the\n     * user.  Print relevant statistics after the run\n     */\n{\n    (void)argc;          /* unused */\n    (void)argv;\n\n\n    float    phi, theta;\n    float    seed;\n\n    int      cur_trial;\n\n    num_real_events = 0;     /* initialize some statistics */\n    maxlambda = quantity<frequency>{0};\n\n    /* get number of trials from user */\n    numtrials = 0;\n    int scanf_err = 1;\n    while ((numtrials <= 0) || (scanf_err != 1)) {\n        printf(\"Number of scattering events to perform: \");\n        scanf_err = scanf(\"%d\", &numtrials);\n    }\n    std::vector<quantity<si::time, float>> scat_times(numtrials);\n    std::vector<quantity<si::velocity, float>> vel_mags(numtrials);\n\n    /* get the total scattering rate from the user */\n    capgamma_f = 0.0;\n    scanf_err = 1;\n    while ((capgamma_f <= 0.0) || (scanf_err != 1)) {\n        printf(\"Total scattering rate: \");\n        scanf_err = scanf(\"%f\", &capgamma_f);\n    }\n    quantity<frequency> capgamma = capgamma_f * hertz;\n\n    /* get a seed for the random number generator */\n    seed = 0.0;\n    scanf_err = 1;\n    while ((seed <= 0.0) || (scanf_err != 1)) {\n        printf(\"Random number generator seed : \");\n        scanf_err = scanf(\"%f\", &seed);\n    }\n    std::mt19937 randeng(seed);\n    std::uniform_real_distribution<double> drand_dist(0, 1.0);\n    auto drand = [&]() { return drand_dist(randeng); };\n\n    /* initialize and begin scattering */\n    cur_trial = 0;\n\n    quantity<wavenumber>    lastkx;\n\n    // Use Boost.Accumulators to produce an average velocity\n    using namespace boost::accumulators;\n    accumulator_set<quantity<velocity>,      // what we are storing\n                    stats<tag::mean>,        // what we want to calculate\n                    quantity<si::time>>      // the weight for each data point\n        vel_acc;\n\n    while (cur_trial < numtrials) {\n        /* determine the time until the scattering event */\n        quantity<si::time> ts = -(1.0/capgamma)*log(drand());\n        lastkx = kinit.x;\n\n        /* accelerate the particle accordingly */\n        kinit.x = kinit.x - accel_const * ts;\n\n        /* record the current value of ts and the velocity */\n        scat_times[cur_trial] = ts;\n        vel_mags[cur_trial] = vel_const * kinit.x;\n        cur_trial++;\n\n        /* do average velocity calculations */\n        quantity<velocity> cur_avg = vel_const * (lastkx + kinit.x)/2.0;\n        vel_acc(cur_avg, weight = ts);\n\n        /* determine the new acoustic scattering rate lambda */\n        quantity<energy, float> energy = kinit.get_energy();\n        quantity<frequency> lambda = scatter_const * sqrt(energy);\n        if (lambda > maxlambda) {\n            maxlambda = lambda;              /* possibly useful statistic */\n        }\n\n        /* determine if acoustic scattering event occurred */\n        if (drand() >= (lambda/capgamma)) {\n            /* no, keep going */\n            // this is a \"self-scattering\" event, a fake event that makes inverting the simulation\n            // (choosing a flight time at random instead of using fixed intervals and testing\n            // each one) work out right\n            continue;\n        }\n        num_real_events++;\n\n        /* determine the angles of the new vector */\n\n        // If I understand this correctly we are calculating the angle theta between\n        // the original k (taken facing along the Z axis) and k'\n        // theta is the polar angle (declination from Z (\"up\"))\n        // Taking dP(theta)d(theta) ~ sin(theta)d(theta), we need integration constants\n        // that give the right total from 0 to pi and the right values at the extremes\n        // (0 at 0, 1 at pi). P(theta) = 0.5*(1-cos(theta)) fits.\n        theta = acos(1 - 2.0*drand());\n        // phi, the \"azimuthal angle\" (from x in the direction of y) is uniformly distributed\n        phi = two_pi * drand();\n        // This is consistent with the approach in \"Bulk Monte Carlo Method Described\",\n        // https://nanohub.org/resources/4844/download/montecarlocodedescribed.pdf\n        // Should I have used the more complex procedure described in Shur p23?\n\n        /* determine the resultant vector and replace */\n        kinit = kinit.collision_result(theta, phi);\n    }\n\n    /* now print out results - good idea to pipe this through more */\n    std::cout << num_real_events << \" real events out of \" << numtrials << \", maximum lambda \" << maxlambda << \"\\n\" ;\n    std::cout << \"average x velocity \" << no_prefix << mean(vel_acc) << \"\\n\";\n    std::cout << \"estimated mobility: \" << ((mean(vel_acc) / Efield) / ((cm*cm)/(volt*second))).value() << \" cm^2/Vs\\n\";\n    std::cout << \"event\\t\\tscattering time\\t\\tvelocity\\n\";\n    for (cur_trial = 0; cur_trial < numtrials; cur_trial++) {\n        std::cout << cur_trial << \"\\t\\t\" << engineering_prefix << scat_times[cur_trial] << \"\\t\\t\" << no_prefix << vel_mags[cur_trial] << \"\\n\";\n    }\n}\n", "meta": {"hexsha": "97df8773efb62ff19a688a897212c0304dedb2d9", "size": 6791, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "monte.cpp", "max_stars_repo_name": "jefftrull/ee851-montecarlo", "max_stars_repo_head_hexsha": "5df7bcf4295ab81da29d5cb4a83d007e85dc2be1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "monte.cpp", "max_issues_repo_name": "jefftrull/ee851-montecarlo", "max_issues_repo_head_hexsha": "5df7bcf4295ab81da29d5cb4a83d007e85dc2be1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "monte.cpp", "max_forks_repo_name": "jefftrull/ee851-montecarlo", "max_forks_repo_head_hexsha": "5df7bcf4295ab81da29d5cb4a83d007e85dc2be1", "max_forks_repo_licenses": ["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.2543352601, "max_line_length": 142, "alphanum_fraction": 0.6328964806, "num_tokens": 1659, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.4918554193065835}}
{"text": "// Copyright 2014 Vinzenz Feenstra\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#ifndef GUARD_LSL_RUNTIME_VECTOR_HH_INCLUDED\n#define GUARD_LSL_RUNTIME_VECTOR_HH_INCLUDED\n\n#include <boost/numeric/ublas/matrix.hpp>\n\nnamespace lsl {\nnamespace runtime {\n\n    struct Vector {\n        double x, y, z;\n    };\n\n    inline Vector add(Vector l, Vector r) {\n        return Vector{\n            l.x + r.x,\n            l.y + r.y,\n            l.z + r.z\n        };\n    }\n\n    inline Vector add(Vector l, double r) {\n        return Vector{\n            l.x + r,\n            l.y + r,\n            l.z + r\n        };\n    }\n\n    inline Vector sub(Vector l, Vector r) {\n        return Vector{\n            l.x - r.x,\n            l.y - r.y,\n            l.z - r.z\n        };\n    }\n\n    inline Vector sub(Vector l, double r) {\n        return Vector{\n            l.x - r,\n            l.y - r,\n            l.z - r\n        };\n    }\n\n    inline Vector mul(Vector l, Vector r) {\n        return Vector{\n            l.x * r.x,\n            l.y * r.y,\n            l.z * r.z\n        };\n    }\n\n    inline Vector mul(Vector l, double r) {\n        return Vector{\n            l.x * r,\n            l.y * r,\n            l.z * r\n        };\n    }\n\n    inline Vector div(Vector l, Vector r) {\n        return Vector{\n            l.x / r.x,\n            l.y / r.y,\n            l.z / r.z\n        };\n    }\n\n    inline Vector div(Vector l, double r) {\n        return Vector{\n            l.x / r,\n            l.y / r,\n            l.z / r\n        };\n    }\n\n    inline Vector cross(Vector l, Vector r) {\n        return Vector{\n            l.y * r.z - l.z * r.y,\n            l.z * r.x - l.x * r.z,\n            l.x * r.y - l.y * r.x\n        };\n    }\n\n    inline double dot(Vector l, Vector r) {\n        return (l.x * r.x) + (l.y * r.y) + (l.z * r.z);\n    }\n\n    inline double mag(Vector v) {\n        return sqrt(v.x * v.x + v.y * v.y + v.z * v.z);\n    }\n\n    inline Vector norm(Vector v) {\n        double m = mag(v);\n        if(m > 0.) {\n            double inv_mag = 1.f / m;\n            return mul(v, inv_mag);\n        }\n        return Vector{0., 0., 0.};\n    }\n\n    inline Vector operator * (Vector const & a, Vector const & b) {\n        return mul(a, b);\n    }\n    inline Vector operator / (Vector const & a, Vector const & b) {\n        return div(a, b);\n    }\n    inline Vector operator + (Vector const & a, Vector const & b) {\n        return add(a, b);\n    }\n    inline Vector operator - (Vector const & a, Vector const & b) {\n        return sub(a, b);\n    }\n    inline Vector operator * (Vector const & a, double b) {\n        return mul(a, b);\n    }\n    inline Vector operator / (Vector const & a, double b) {\n        return div(a, b);\n    }\n    inline Vector operator + (Vector const & a, double b) {\n        return add(a, b);\n    }\n    inline Vector operator - (Vector const & a, double b) {\n        return sub(a, b);\n    }\n\n    inline double dist(Vector l, Vector r) {\n        return mag(l - r);\n    }\n\n    inline bool operator == (Vector const & a, Vector const & b) {\n        return a.x == b.x && a.y == b.y && a.z == b.z;\n    }\n\n    inline bool operator < (Vector const & a, Vector const & b) {\n        return mag(a) < mag(b);\n    }\n\n}}\n\n#endif //GUARD_LSL_RUNTIME_VECTOR_HH_INCLUDED\n", "meta": {"hexsha": "c180cb643c40c0f2794973b62a6494a0b8e4657e", "size": 3750, "ext": "hh", "lang": "C++", "max_stars_repo_path": "lsl/runtime/vector.hh", "max_stars_repo_name": "vinzenz/lsl-emu", "max_stars_repo_head_hexsha": "3f799248ee57d0d11d6f12e6ff0f48cf359ced1e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-03-28T19:26:44.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-28T19:26:44.000Z", "max_issues_repo_path": "lsl/runtime/vector.hh", "max_issues_repo_name": "vinzenz/lsl-emu", "max_issues_repo_head_hexsha": "3f799248ee57d0d11d6f12e6ff0f48cf359ced1e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lsl/runtime/vector.hh", "max_forks_repo_name": "vinzenz/lsl-emu", "max_forks_repo_head_hexsha": "3f799248ee57d0d11d6f12e6ff0f48cf359ced1e", "max_forks_repo_licenses": ["Apache-2.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.1935483871, "max_line_length": 75, "alphanum_fraction": 0.5024, "num_tokens": 981, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.6442251133170356, "lm_q1q2_score": 0.49185541409148087}}
{"text": "//==================================================================================================\n/*!\n\n  Copyright 2015 NumScale SAS\n  Copyright 2015 J.T. Lapreste\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#include <boost/simd/function/scalar/asind.hpp>\n#include <simd_test.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/minf.hpp>\n#include <boost/simd/constant/nan.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/mone.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/constant/mzero.hpp>\n\nSTF_CASE_TPL (\" asind\",  STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::asind;\n\n  using r_t = decltype(asind(T()));\n\n  // return type conformity test\n  STF_TYPE_IS(r_t, T);\n\n  // specific values tests\n#ifndef BOOST_SIMD_NO_INVALIDS\n  STF_ULP_EQUAL(asind(bs::Inf<T>()), bs::Nan<r_t>(), 0);\n  STF_ULP_EQUAL(asind(bs::Minf<T>()), bs::Nan<r_t>(), 0);\n  STF_ULP_EQUAL(asind(bs::Nan<T>()), bs::Nan<r_t>(), 0);\n#endif\n  STF_ULP_EQUAL(asind(bs::Half<T>()), T(30), 0.5);\n  STF_ULP_EQUAL(asind(bs::Mhalf<T>()), T(-30), 0.5);\n  STF_ULP_EQUAL(asind(bs::Mone<T>()), T(-90), 0.5);\n  STF_ULP_EQUAL(asind(bs::One<T>()), T(90), 0.5);\n  STF_ULP_EQUAL(asind(bs::Zero<T>()), bs::Zero<r_t>(), 0.5);\n}\n\n", "meta": {"hexsha": "75797135c87fbe89b8479dfc3ab2e3279487236b", "size": 1494, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/scalar/asind.cpp", "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": "test/function/scalar/asind.cpp", "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": "test/function/scalar/asind.cpp", "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.2, "max_line_length": 100, "alphanum_fraction": 0.5923694779, "num_tokens": 436, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.6442250996557036, "lm_q1q2_score": 0.49185541059519056}}
{"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 \"lemmas.h\"\n#include \"graphutil.h\"\n#include \"strutil.h\"\n#include \"Partition.h\"\n#include \"BFSVisitor.h\"\n#include <boost/graph/copy.hpp>\n#include <boost/graph/graph_utility.hpp>\nusing namespace std;\nusing namespace boost;\n\n/* Let G be any planar graph with nonnegative vertex costs summing to no more than one.\nSuppose G has a spanning tree of radius r.\nThen the vertices of G can be partitioned into three sets A, B, C such that no edge joins a vertex in A with a vertex in B, neither A nor B has total cost exceeding 2/3,\nand C contains no more than 2r+1 vertices, one the root of the tree */\n// r is spanning tree radius\nPartition lemma2(GraphCR g_orig, vector<vertex_t> const& cycle, BFSVisitorData const& visdata_orig, vertex_t costzero)\n{ \n        cout << \"lemma2 graph:\\n\";\n        print_graph(g_orig);\n        print_graph_addresses(g_orig);\n        uint n = num_vertices(g_orig);\n\n        auto prop_map = get(vertex_index, g_orig);\n        for( vertex_t v : cycle ) cout << \"cyclevert: \" << v << \" propmap: \" << prop_map[v] << endl;\n\n        // if g contains only two vertices then return trivially\n        if( n <= 2 ){ \n                VertIter vit, vjt;\n                tie(vit, vjt) = vertices(g_orig); \n                Partition p;\n                p.a.insert(*vit);\n                if( ++vit != vjt ) p.b.insert(*vit);\n                return p; \n        }\n        \n        Graph g_shrink2(g_orig);\n\n        auto g_shrink2_prop_map = get(vertex_index, g_shrink2);\n        auto g_orig_prop_map = get(vertex_index, g_orig);\n\n        // find shrinkroot\n        vertex_t shrinkroot, costzero2;\n        for( auto[vit, vjt] = vertices(g_shrink2); vit != vjt; ++vit ){ \n                if( g_shrink2_prop_map[*vit] == g_orig_prop_map[visdata_orig.root] ) shrinkroot = *vit;\n                if( g_shrink2_prop_map[*vit] == g_orig_prop_map[costzero] ) costzero2 = *vit; \n        }\n\n\tBFSVisitorData visdata(&g_shrink2, shrinkroot);\n        breadth_first_search(g_shrink2, visdata.root, boost::visitor(BFSVisitor(visdata)));\n\tuint r = visdata_orig.num_levels-1; // spanning tree radius\n\n\t//BOOST_ASSERT(visdata.num_levels == visdata_orig.num_levels);\n\t/* Let G be any planar graph with nonnegative vertex costs summing to no more than one.\n\tSuppose G has a spanning tree of radius r.\n\tThen the vertices of G can be partitioned into three sets A, B, C, such that no edge joins a vertex A with a vertex in B, neither A nor B has a total cost exceeding 2/3, and C contains no more than 2r+1 vertices, one the root of the tree. */\n\n        // decrement descendent costs from costzero\n        vertex_t ansc = costzero2;\n        while( ansc ){\n                --visdata.verts[ansc].descendant_cost;\n                ansc = visdata.verts.find(ansc)->second.parent; \n        }\n\n        make_max_planar(g_shrink2);\n        EmbedStruct em(&g_shrink2);\n\n\n\t/* Proof.  Assume no vertex has cost exceeding 1/3; otherwise the lemma is true.\n\tEmbed G in the plane.  Make each face a triangle by adding a suitable number of additional edges.\n\tAny nontree edge (including each of the added edges) forms a simple cycle with some of the tree edges.\n\tThis cycle is of length at most 2r+1 if it contains the root of the tree, at most 2r-1 otherwise.\n\tThe cycle divides the plane (and the graph) into two parts, the inside and the outside of the cycle.\n\tWe claim that at least one such cycle separates the graph so that neither the inside nor the outside contains vertices whose total cost exceeds 2/3.  This proves the lemma. */\n        \n        vector<edge_t> nontree_edges;\n        for( auto[ei, ei_end] = edges(g_shrink2); ei != ei_end; ++ei ){\n                if( source(*ei, g_shrink2) == target(*ei, g_shrink2) ) continue; // ignore workaround ciruclar nodes\n                if( !visdata.is_tree_edge(*ei) ) nontree_edges.push_back(*ei);\n        }\n\n        vector<CycleCost> ccs;\n        for( edge_t e : nontree_edges ){\n                vector<vertex_t> cycle = visdata.get_cycle(source(e, g_shrink2), target(e, g_shrink2));\n                CycleCost cc = compute_cycle_cost(cycle, g_shrink2, visdata, em);\n                ccs.push_back(cc);\n        }\n\n        uint mindiff = UINT_MAX;\n        uint min_index = UINT_MAX;\n        for( uint i = 0; i < nontree_edges.size(); ++i ){\n                uint costdiff = abs((int)ccs[i].inside - (int)ccs[i].outside);\n                if( costdiff < mindiff ){\n                        mindiff = costdiff;\n                        min_index = i;\n                }\n        }\n\t\n        edge_t xz = nontree_edges[min_index];\n        cout << \"xz: \" << source(xz, g_shrink2) << \", \" << target(xz, g_shrink2) << '\\n';\n\n        BOOST_ASSERT(ccs[min_index].inside <= 2*n/3);\n        BOOST_ASSERT(ccs[min_index].outside <= 2*n/3);\n        auto cycle2 = visdata.get_cycle(xz);\n\n        uint cyclelengthlimit = find(STLALL(cycle2), visdata.root) != cycle2.end() ? 2*r+1 : 2*r-1;\n        BOOST_ASSERT(cycle2.size() <= cyclelengthlimit);\n\n        auto p = Partition(cycle2, g_shrink2, em);\n\n        map<vertex_t, vertex_t> shrink2orig;\n\n        auto[vit, vjt] = vertices(g_shrink2);\n        for( ;vit != vjt; ++vit ){\n                uint i = g_shrink2_prop_map[*vit];\n                for( auto[vit2, vjt2] = vertices(g_orig); vit2 != vjt2; ++vit2 ){\n                        if( g_orig_prop_map[*vit2] == i ){\n                                shrink2orig[*vit] = *vit2;\n                        }\n\n                }\n        }\n\n        Partition porig;\n        for( vertex_t v : p.a ) porig.a.insert(shrink2orig[v]); // Let A be all verts inside the cycle\n        for( vertex_t v : p.b ) porig.b.insert(shrink2orig[v]); // Let B be all verts outside the cycle \n        for( vertex_t v : p.c ) porig.c.insert(shrink2orig[v]); // Let C be all verts on the cycle\n\n\t/*Proof of claim.\n\tLet (x,z) be the nontree edge whose cycle minimizes the maximum cost either inside or outside the cycle.  Break ties by choosing the nontree edge whose cycle has the smallest number of faces on the same side as the maximum cost.  If ties remain, choose arbitrarily.\n\n\tSuppose without loss of generality that the graph is embedded so that the cost inside the cycle (x z) cycle is at least as great as the cost outside the cycle.  If the vertices inside the cycle have total cost not exceeding 2/3, the claim is true.  Suppose the vertices inside the cycle have total cost exceeding 2/3.  We show by case analysis that this contradicts the choice of (x, z).\n\tConsider the face which has (x, z) as a boundary edge and lies inside the cycle.\n\tThis face is a triangle; let y be its third vertex.\n\tThe properties of (x, y) and (y, z) determine which of the following case applies.\n\tFigure 4 illustrates the cases.\n\n\t1) Both (x, y) and (y, z) lie on the cycle.  Then the face (x, y, z) is the cycle, which is impossible since vertices lie inside the cycle.\n\t2) One of (x, y) and (y, z) (say (x, y)) lies on the cycle. Then (y, z) is a nontree edge defining a cycle which contains within it the same vertices as the original cycle but one less face. This contradicts the choice of (x, z).\n\t3) Neither (x, y) nor (y, z) lies on the cycle.\n\t\ta) Both (x, y) and (y, z) are tree edges.  This is impossible since the tree itself contains no cycles.\n\t\tb) One of (x, y) and (y, z) (say x, y) is a tree edge.  Then (y, z) is a nontree edge defining a cycle which contains one less vertex (namely y) within it than the original cycle.\n\tThe inside of the (y, z) cycle contains no more cost and one less face than the inside of the (x, z) cycle.  Thus if the cost inside the (y, z) cycle is greater than the cost outside the cycle, (y, z)\n\twould have been chosen in place of (x, z).\n\tOn the other hand, suppose the cost inside the (y, z) cycle is no greater than the cost outside.\n\tThe cost outside the (y, z) cycle is equal to the cost outside the (x, z) cycle plus the cost of y.\n\tSince both the cost outside the (x, z) cycle and the cost of y are less than 1/3,\n\tthe cost outside the (y, z) cycle is less than 2/3, and (y, z) would have been chosen in place of (x, z).\n\t\tc) Neither (x, y) nor (y, z) is a tree edge. Then each of (x, y) and (y, z) defines a cycle, and every vertex inside the (x, z) cycle is either inside the (x, y) cycle, inside the (y, z) cycle, or on the boundary of both.\n\t\tOf the (x, y) and (y, z) cycles, choose the one (say (x, y)) which has inside it more total cost. The (x, y) cycle has no more cost and strictly fewer faces inside it than the (x, z) cycle.\n\t\tThus if the cost inside the (x, y) cycle is greater than the cost outside, (x, y) would have been chosen in place of (x, z).\n\tOn the other hand, suppose the cost inside the (x, y) cycle is no greater than the cost outside.\n\tSince the inside of the (x, z) cycle has cost exceeding 2/3, the (x, y) cycle and its inside together have cost exceeding 1/3, and the outside of the (x, y) cycle has cost less than 2/3.\n\tThus (x, y) would have been chosen in place of (x, z).\n\tThus all cases are impossible, and the (x, z) cycle satisfies the claim. */\n\n        p.verify_sizes_lemma2(r, visdata.root);\n\n        return porig;\n}\n\nvertex_t choose_costzero(Graph& g, BFSVisitorData const& visdata, uint l1)\n{\n        vertex_t v = Graph::null_vertex(); \n        auto[vit, vjt] = vertices(g); \n        for( VertIter next = vit; vit != vjt; vit = next ){\n                ++next;\n                if( !visdata.verts.contains(*vit) ){\n                        cout << \"ignoring vertex: \" << *vit << '\\n';\n                        continue;\n                }\n\n                uint level = visdata.verts.find(*vit)->second.level;\n                if( level <= l1 ){\n                        v = *vit;\n                        break;\n                }\n        }\n        return v; \n}\n\n// called when the middle part exceeds 2/3\nPartition lemma3_exceeds23(Graph& g_shrink2, BFSVisitorData const& vis_data_shrunken, uint l1, uint l2, vector<vertex_t> const& fundamental_cycle)\n{\n        cout << \"g_shrink2:\\n\";\n        print_graph(g_shrink2);\n        print_graph_addresses(g_shrink2);\n\n        cout << \"middle partition has cost exceeding 2/3\\n\";\n\n        //delete all verts on level l2 and above \n        VertIter vit, vjt;\n        tie(vit, vjt) = vertices(g_shrink2); \n        for( VertIter next = vit; vit != vjt; vit = next ){\n                ++next;\n                if( !vis_data_shrunken.verts.contains(*vit) ){\n                        cout << \"ignoring vertex: \" << *vit << '\\n';\n                }\n                if( vis_data_shrunken.verts.find(*vit)->second.level >= l2 ){\n                        //cout << \"killing vertex \" << vmap_shrunk.vert2uint[*vit] << \" of level l2 or above: \" << vis_data_orig.verts.find(*vit)->second.level << \" >= \" << l[2] << '\\n';\n                        kill_vertex(*vit, g_shrink2);\n                }\n        }\n\n        // shrink all verts on levels l1 and below to a single vertex of cost zero\n\n        // find a vertex to call cost zero\n        vertex_t costzero = choose_costzero(g_shrink2, vis_data_shrunken, l1);\n\n        BOOST_ASSERT(costzero != Graph::null_vertex());\n        auto prop_map = get(vertex_index, g_shrink2);\n        cout << \"costzero: \" << costzero << \" propmap: \" << prop_map[costzero] << '\\n';\n\n        // contract\n        tie(vit, vjt) = vertices(g_shrink2); \n        for( VertIter next = vit; vit != vjt; vit = next ){\n                ++next;\n                if( !vis_data_shrunken.verts.contains(*vit) ){\n                        cout << \"ignoring vertex: \" << *vit << '\\n';\n                }\n\n                uint level = vis_data_shrunken.verts.find(*vit)->second.level;\n                if( level <= l1 && *vit != costzero ){\n                        costzero = contract_vertices(costzero, *vit, g_shrink2);\n                }\n        }\n\n        // The new graph has a spanning tree radius of l2 - l1 -1 whose root corresponds to vertices on levels l1 and below in the original graph\n        uint r = l2 - l1 - 1;\n\tBOOST_ASSERT(r == vis_data_shrunken.num_levels-1);\n        // Apply Lemma 2 to the new graph.  Let A*, B*, C* be the resulting vertex partition\n        Partition star_p = lemma2(g_shrink2, fundamental_cycle, vis_data_shrunken, costzero);\n        BOOST_ASSERT(star_p.verify_sizes_lemma2(r, vis_data_shrunken.root));\n        vertex_t star_root;\n\n        Partition p;\n        p.a = star_p.a.size() > star_p.b.size() ? star_p.a : star_p.b; \n\n        p.c = star_p.c; \n        p.c.erase(star_root);\n        // add verts on levels l1 and l2 in the original graph \n        tie(vit, vjt) = vertices(g_shrink2); \n        for( VertIter next = vit; vit != vjt; vit = next ){\n                ++next;\n                BOOST_ASSERT(vis_data_shrunken.verts.contains(*vit));\n                if( vis_data_shrunken.verts.find(*vit)->second.level == l2 ||\n                        vis_data_shrunken.verts.find(*vit)->second.level == l1 ){\n                                p.c.insert(*vit);\n                }\n        } \n\n        // all verts not already in A or C go in B\n        tie(vit, vjt) = vertices(g_shrink2); \n        for( VertIter next = vit; vit != vjt; vit = next ){\n                ++next;\n                if( p.a.find(*vit) == p.a.end() &&\n                        p.c.find(*vit) == p.c.end() ){\n                                p.b.insert(*vit);\n\n                        }\n        }\n\n        return p; \n        /* By Lemma 2, A has total cost <= 2/3\n        But A and C* have total cost >= 1/3, so B also has total cost <= 2/3\n        Futhermore, C contains no more than L[l1] + L[l2] + 2(l2 - l1 - 1) */\n}\n\nPartition lemma3_l1greaterequall2(GraphCR g_shrink2, BFSVisitorData const& vis_data_orig, uint l1, uint r)\n{\n        //cout << \"l1 is greater than or equal to l2\\n\"; \n\n        Partition p;\n        for( auto[vei, vend] = vertices(g_shrink2); vei != vend; ++vei ){ \n                vertex_t v = *vei;\n                if( ! vis_data_orig.verts.contains(v) ){\n\t\t\tcout << \"ignoring non bfs vertex: \" << v << '\\n';\n\t\t\tcontinue;\n\t\t}\n                uint level = vis_data_orig.verts.find(v)->second.level;\n\n                //cout << \"level of \" << ii << \": \" << vis_data_orig.verts.find(v)->second.level << \"  \";\n                if( level <  l1 ){                 cout << \" belongs to first part\\n\";  p.a.insert(v); continue; }\n                if( level >= l1+1 && level <= r ){ cout << \" belongs to middle part\\n\"; p.b.insert(v); continue; }\n                if( level == l1 ){                 cout << \" belongs to last part\\n\";   p.c.insert(v); continue; }\n                BOOST_ASSERT(0);\n        } \n        /*cout << \"A = all verts on levels 0    thru l1-1\\n\";\n        cout << \"B = all verts on levels l1+1 thru r\\n\";\n        cout << \"C = all verts on level l1\\n\";*/\n        return p;\n}\n\nPartition lemma3_lessequal23(set<vertex_t> const& first_part, set<vertex_t> const& middle_part, set<vertex_t> const& last_part, set<vertex_t>& deleted_part, Graph const* g)\n{\n        cout << \"middle partition has cost <= 2/3\\n\";\n\n        Partition p;\n        p.a = first_part;\n        p.b = middle_part;\n        p.c = last_part;\n\n        set<vertex_t> const* costly_part;\n        set<vertex_t> const* other1;\n        set<vertex_t> const* other2;\n        p.get_most_costly_part(&costly_part, &other1, &other2);\n\n        p.print(g);\n        cout <<   \"A = most costly part of the 3 : \"; for( auto& a : *costly_part ) cout << a << ' ';\n        cout << \"\\nB = remaining 2 parts         : \"; for( auto& b : *other1      ) cout << b << ' '; for( auto& b : *other2 ) cout << b << ' '; \n        cout << \"\\nC = deleted verts on l1 and l2: \"; for( auto& v : deleted_part ) cout << v << ' '; cout << '\\n';\n\n        Partition p2;\n        p2.a = *costly_part;\n        p2.c = deleted_part;\n        p2.b = *other1;\n        p2.b.insert(other2->begin(), other2->end());\n        p2.print(g);\n        return p2; \n}\n\n/* Let G be any n-vertex connected planar graph having nonegative vertex consts summing to no more than one.\nSuppose that the vertices of G are partitioned into levels according to their distance from some vertex v, and that L(l) denotes the number of vertices on level l.\nIf r is the maximum distance of any vertex from v, let r+1 be an additional level containing no vertices.\nGiven any two levels l1 and l2 such that levels 0 through l1-1 have total cost not exceeding 2/3 and levels l2+1 through r+1 have total cost not exceeding 2/3,\nit is possible to find a partition A, B, C of the vertices of G such that no edge joins a vertex in A with a vertex in B, neither A nor B has total cost exceeding 2/3, and C contains no more than L(l1)+L(l2)+max{0,2(l2-l1-1)} vertices. */\nPartition lemma3(GraphCR g_orig, vector<uint> const& L, uint l1, uint l2, uint r, BFSVisitorData const& vis_data_orig, BFSVisitorData const& vis_data_shrunken, vector<vertex_t> const& cycle, Graph* g_shrunk)\n{\n        uint n = vis_data_orig.verts.size();\n        uint n_orig = num_vertices(g_orig); \n        cout << \"n: \" << n << '\\n';\n        cout << \"n_orig: \" << n_orig << '\\n';\n\n        if( n != n_orig ){\n                // more than one connected component, we need to recompute l1 and l2 \n\n                uint total = 0;\n                uint level = 0;\n                while( total < 2*n_orig/3 ) total += L[level++];\n\n                total = 0;\n                level = r+1;\n                while( total < 2*n_orig/3 ){ \n                        total += L[level];\n\t\t\tif( 0 == level ) break;\n\t\t\t--level;\n                }\n\n                l2 = level;\n        }\n\n        uint cost_0thrul1m1 = 0;\n        uint cost_l2p1thrur1 = 0;\n        for( uint i = 0; i < r; ++i ){ \n                if( i+1 < l1 ) cost_0thrul1m1 += L[i];\n                if( i >= l2+1 ) cost_l2p1thrur1 += L[i];\n        }\n        uint costlimit = 2*n/3;\n        BOOST_ASSERT(cost_0thrul1m1 <= costlimit);\n        BOOST_ASSERT(cost_l2p1thrur1 <= costlimit);\n\n\n        //BOOST_ASSERT(vis_data_shrunken.assert_data());\n        //BOOST_ASSERT(vis_data_orig.assert_data()); \n        //BOOST_ASSERT(n == n_orig);\n\n        //uint total_cost = 0;\n\n        auto prop_map = get(vertex_index, g_orig); // writing to this property map has side effects in the graph\n\n        Partition p;\n        if( l1 >= l2 ){\n                p = lemma3_l1greaterequall2(g_orig, vis_data_orig, l1, r);\n        } else {\n                cout << \"l1 < l2\\n\";\n\n                set<vertex_t> first_part, middle_part, last_part, deleted_part;\n                VertIter vei, vend;\n                for( tie(vei, vend) = vertices(g_orig); vei != vend; ++vei ){ \n                        vertex_t v = *vei;\n                        if( !vis_data_orig.verts.contains(v) ){\n                                cout << \"lemmas.cpp: ignoring bad vertex: \" << v << \" prop_map: \" << prop_map[v] << '\\n';\n                                continue; \n                        }\n\n                        uint level = vis_data_orig.verts.find(v)->second.level;\n\n                        cout << \"level of \" << v << \" prop_map \" << prop_map[v] << \" is : \" << level << \", \";\n                        fflush(stdout);\n                        if( level == l1 || level == l2 ){     cout << v << \" is deleted\\n\";                 deleted_part.insert(v); continue;}\n                        if( level <  l1 ){                    cout << v << \" belongs to first part (A)\\n\";  first_part.insert(v);   continue;}\n                        if( level >= l1+1 && level <= l2-1 ){ cout << v << \" belongs to middle part (B)\\n\"; middle_part.insert(v);  continue;}\n                        if( level >  l2   ){                  cout << v << \" belongs to last part (C)\\n\";   last_part.insert(v);    continue;}\n                        BOOST_ASSERT(0);\n                }\n\n                uint ptotal = first_part.size() + middle_part.size() + last_part.size() + deleted_part.size();\n                cout << \"ptotal: \" << ptotal << '\\n';\n                BOOST_ASSERT(ptotal == n);\n\n                //the only part which can have cost > 2/3 is the middle part (B)\n                cout << \"first part size: \" << first_part.size() << '\\n';\n                cout << \"middle part size: \" << middle_part.size() << '\\n';\n                cout << \"third part size: \" << last_part.size() << '\\n';\n                BOOST_ASSERT(first_part.size() <= 2*n/3);\n                BOOST_ASSERT(last_part.size() <= 2*n/3);\n                //p.print();\n\n                p = middle_part.size() <= 2*n/3                                          ?\n                    lemma3_lessequal23(first_part, middle_part, last_part, deleted_part, &g_orig) :\n                    lemma3_exceeds23(*g_shrunk, vis_data_shrunken, l1, l2, cycle);\n        }\n\n        BOOST_ASSERT(p.verify_edges(g_orig));\n\tBOOST_ASSERT(p.verify_sizes_lemma3(L, l1, l2));\n        return p;\n}\n", "meta": {"hexsha": "f799b26d9836608ca8f40342d5232cfc592a8b1d", "size": 21033, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lemmas.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": "lemmas.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": "lemmas.cpp", "max_forks_repo_name": "jeffythedragonslayer/lipton-tarjan", "max_forks_repo_head_hexsha": "d6f43395ca9d5a459c61cd55ccac6ed6295bc1dd", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-04-19T16:37:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T04:29:33.000Z", "avg_line_length": 49.6061320755, "max_line_length": 388, "alphanum_fraction": 0.5725288832, "num_tokens": 5564, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.49185540887637835}}
{"text": "/*\r\n [auto_generated]\r\n boost/numeric/odeint/stepper/adams_bashforth_moulton.hpp\r\n\r\n [begin_description]\r\n Implementation of the Adams-Bashforth-Moulton method, a predictor-corrector multistep 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_ADAMS_BASHFORTH_MOULTON_HPP_INCLUDED\r\n#define BOOST_NUMERIC_ODEINT_STEPPER_ADAMS_BASHFORTH_MOULTON_HPP_INCLUDED\r\n\r\n\r\n#include <boost/numeric/odeint/util/bind.hpp>\r\n\r\n#include <boost/numeric/odeint/stepper/stepper_categories.hpp>\r\n#include <boost/numeric/odeint/algebra/range_algebra.hpp>\r\n#include <boost/numeric/odeint/algebra/default_operations.hpp>\r\n\r\n#include <boost/numeric/odeint/util/state_wrapper.hpp>\r\n#include <boost/numeric/odeint/util/resizer.hpp>\r\n\r\n#include <boost/numeric/odeint/stepper/adams_bashforth.hpp>\r\n#include <boost/numeric/odeint/stepper/adams_moulton.hpp>\r\n\r\n\r\nnamespace boost {\r\nnamespace numeric {\r\nnamespace odeint {\r\n\r\n\r\ntemplate<\r\nsize_t Steps ,\r\nclass State ,\r\nclass Value = double ,\r\nclass Deriv = State ,\r\nclass Time = Value ,\r\nclass Algebra = range_algebra ,\r\nclass Operations = default_operations ,\r\nclass Resizer = initially_resizer\r\n>\r\nclass adams_bashforth_moulton\r\n{\r\n\r\n#ifndef DOXYGEN_SKIP\r\n    BOOST_STATIC_ASSERT(( Steps > 0 ));\r\n    BOOST_STATIC_ASSERT(( Steps < 9 ));\r\n#endif\r\n\r\npublic :\r\n\r\n    typedef State state_type;\r\n    typedef state_wrapper< state_type > wrapped_state_type;\r\n    typedef Value value_type;\r\n    typedef Deriv deriv_type;\r\n    typedef state_wrapper< deriv_type > wrapped_deriv_type;\r\n    typedef Time time_type;\r\n    typedef Algebra algebra_type;\r\n    typedef Operations operations_type;\r\n    typedef Resizer resizer_type;\r\n    typedef stepper_tag stepper_category;\r\n\r\n    static const size_t steps = Steps;\r\n#ifndef DOXYGEN_SKIP\r\n    typedef adams_bashforth< steps , state_type , value_type , deriv_type , time_type , algebra_type , operations_type , resizer_type > adams_bashforth_type;\r\n    typedef adams_moulton< steps , state_type , value_type , deriv_type , time_type , algebra_type , operations_type , resizer_type > adams_moulton_type;\r\n#endif //DOXYGEN_SKIP\r\n    typedef unsigned short order_type;\r\n    static const order_type order_value = steps + 1;\r\n\r\n    /** \\brief Constructs the adams_bashforth class. */\r\n    adams_bashforth_moulton( void )\r\n    : m_adams_bashforth() , m_adams_moulton( m_adams_bashforth.algebra() )\r\n    { }\r\n\r\n    adams_bashforth_moulton( const algebra_type &algebra )\r\n    : m_adams_bashforth( algebra ) , m_adams_moulton( m_adams_bashforth.algebra() )\r\n    { }\r\n\r\n    order_type order( void ) const { return order_value; }\r\n\r\n    template< class System , class StateInOut >\r\n    void do_step( System system , StateInOut &x , time_type t , time_type dt )\r\n    {\r\n        m_adams_bashforth.do_step( system , x , t , dt );\r\n        m_adams_moulton.do_step( system , x , t , dt , m_adams_bashforth.step_storage() );\r\n    }\r\n\r\n    /**\r\n     * \\brief Second version to solve the forwarding problem, can be called with Boost.Range as StateInOut.\r\n     */\r\n    template< class System , class StateInOut >\r\n    void do_step( System system , const StateInOut &x , time_type t , time_type dt )\r\n    {\r\n        m_adams_bashforth.do_step( system , x , t , dt );\r\n        m_adams_moulton.do_step( system , x , t , dt , m_adams_bashforth.step_storage() );\r\n    }\r\n\r\n    template< class System , class StateIn , class StateOut >\r\n    void do_step( System system , const StateIn &in , time_type t , const StateOut &out , time_type dt )\r\n    {\r\n        m_adams_bashforth.do_step( system , in , t , out , dt );\r\n        m_adams_moulton.do_step( system , out , t , dt , m_adams_bashforth.step_storage() );\r\n    }\r\n\r\n    /**\r\n     * \\brief Second version to solve the forwarding problem, can be called with Boost.Range as StateOut.\r\n     */\r\n    template< class System , class StateIn , class StateOut >\r\n    void do_step( System system , const StateIn &in , time_type t , StateOut &out , time_type dt )\r\n    {\r\n        m_adams_bashforth.do_step( system , in , t , out , dt );\r\n        m_adams_moulton.do_step( system , out , t , dt , m_adams_bashforth.step_storage() );\r\n    }\r\n\r\n\r\n    template< class StateType >\r\n    void adjust_size( const StateType &x )\r\n    {\r\n        m_adams_bashforth.adjust_size( x );\r\n        m_adams_moulton.adjust_size( x );\r\n    }\r\n\r\n\r\n    template< class ExplicitStepper , class System , class StateIn >\r\n    void initialize( ExplicitStepper explicit_stepper , System system , StateIn &x , time_type &t , time_type dt )\r\n    {\r\n        m_adams_bashforth.initialize( explicit_stepper , system , x , t , dt );\r\n    }\r\n\r\n\r\n    template< class System , class StateIn >\r\n    void initialize( System system , StateIn &x , time_type &t , time_type dt )\r\n    {\r\n        m_adams_bashforth.initialize( system , x , t , dt );\r\n    }\r\n\r\n\r\n\r\nprivate:\r\n\r\n    adams_bashforth_type m_adams_bashforth;\r\n    adams_moulton_type m_adams_moulton;\r\n};\r\n\r\n\r\n/********* DOXYGEN ********/\r\n\r\n/**\r\n * \\class adams_bashforth_moulton\r\n * \\brief The Adams-Bashforth-Moulton multistep algorithm.\r\n *\r\n * The Adams-Bashforth method is a multi-step predictor-corrector algorithm \r\n * with configurable step number. The step number is specified as template \r\n * parameter Steps and it then uses the result from the previous Steps steps. \r\n * See also\r\n * <a href=\"http://en.wikipedia.org/wiki/Linear_multistep_method\">en.wikipedia.org/wiki/Linear_multistep_method</a>.\r\n * Currently, a maximum of Steps=8 is supported.\r\n * The method is explicit and fulfills the Stepper concept. Step size control\r\n * or continuous output are not provided.\r\n * \r\n * This class derives from algebra_base and inherits its interface via\r\n * CRTP (current recurring template pattern). For more details see\r\n * algebra_stepper_base.\r\n *\r\n * \\tparam Steps The number of steps (maximal 8).\r\n * \\tparam State The state type.\r\n * \\tparam Value The value type.\r\n * \\tparam Deriv The type representing the time derivative of the state.\r\n * \\tparam Time The time representing the independent variable - the time.\r\n * \\tparam Algebra The algebra type.\r\n * \\tparam Operations The operations type.\r\n * \\tparam Resizer The resizer policy type.\r\n * \\tparam InitializingStepper The stepper for the first two steps.\r\n */\r\n\r\n    /**\r\n     * \\fn adams_bashforth_moulton::adams_bashforth_moulton( const algebra_type &algebra )\r\n     * \\brief Constructs the adams_bashforth class. This constructor can be used as a default\r\n     * constructor if the algebra has a default constructor. \r\n     * \\param algebra A copy of algebra is made and stored.\r\n     */\r\n\r\n    /**\r\n     * \\fn adams_bashforth_moulton::order( void ) const\r\n     * \\brief Returns the order of the algorithm, which is equal to the number of steps+1.\r\n     * \\return order of the method.\r\n     */\r\n\r\n    /**\r\n     * \\fn adams_bashforth_moulton::do_step( System system , StateInOut &x , time_type t , time_type dt )\r\n     * \\brief This method performs one step. It transforms the result in-place.\r\n     *\r\n     * \\param system The system function to solve, hence the r.h.s. of the ordinary differential equation. It must fulfill the\r\n     *               Simple System concept.\r\n     * \\param x The state of the ODE which should be solved. After calling do_step the result is updated in x.\r\n     * \\param t The value of the time, at which the step should be performed.\r\n     * \\param dt The step size.\r\n     */\r\n\r\n\r\n    /**\r\n     * \\fn adams_bashforth_moulton::do_step( System system , const StateIn &in , time_type t , const StateOut &out , time_type dt )\r\n     * \\brief The method performs one step with the stepper passed by Stepper. The state of the ODE is updated out-of-place.\r\n     *\r\n     * \\param system The system function to solve, hence the r.h.s. of the ODE. It must fulfill the\r\n     *               Simple System concept.\r\n     * \\param in The state of the ODE which should be solved. in is not modified in this method\r\n     * \\param t The value of the time, at which the step should be performed.\r\n     * \\param out The result of the step is written in out.\r\n     * \\param dt The step size.\r\n     */\r\n\r\n    /**\r\n     * \\fn adams_bashforth_moulton::adjust_size( const StateType &x )\r\n     * \\brief Adjust the size of all temporaries in the stepper manually.\r\n     * \\param x A state from which the size of the temporaries to be resized is deduced.\r\n     */\r\n\r\n    /**\r\n     * \\fn adams_bashforth_moulton::initialize( ExplicitStepper explicit_stepper , System system , StateIn &x , time_type &t , time_type dt )\r\n     * \\brief Initialized the stepper. Does Steps-1 steps with the explicit_stepper to fill the buffer.\r\n     * \\note The state x and time t are updated to the values after Steps-1 initial steps.\r\n     * \\param explicit_stepper the stepper used to fill the buffer of previous step results\r\n     * \\param system The system function to solve, hence the r.h.s. of the ordinary differential equation. It must fulfill the\r\n     *               Simple System concept.\r\n     * \\param x The initial state of the ODE which should be solved, updated after in this method.\r\n     * \\param t The initial time, updated in this method.\r\n     * \\param dt The step size.\r\n     */\r\n\r\n    /**\r\n     * \\fn adams_bashforth_moulton::initialize( System system , StateIn &x , time_type &t , time_type dt )\r\n     * \\brief Initialized the stepper. Does Steps-1 steps using the standard initializing stepper \r\n     * of the underlying adams_bashforth stepper.\r\n     * \\param system The system function to solve, hence the r.h.s. of the ordinary differential equation. It must fulfill the\r\n     *               Simple System concept.\r\n     * \\param x The state of the ODE which should be solved. After calling do_step the result is updated in x.\r\n     * \\param t The value of the time, at which the step should be performed.\r\n     * \\param dt The step size.\r\n     */\r\n\r\n\r\n} // odeint\r\n} // numeric\r\n} // boost\r\n\r\n\r\n\r\n#endif // BOOST_NUMERIC_ODEINT_STEPPER_ADAMS_BASHFORTH_MOULTON_HPP_INCLUDED\r\n", "meta": {"hexsha": "293d153be9053f79679ad576e602c4f84c07e701", "size": 10198, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/numeric/odeint/stepper/adams_bashforth_moulton.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/adams_bashforth_moulton.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/adams_bashforth_moulton.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": 39.3745173745, "max_line_length": 158, "alphanum_fraction": 0.6919003726, "num_tokens": 2489, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.49185540538008776}}
{"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#include <boost/math/bindings/rr.hpp>\n#include <boost/test/included/prg_exec_monitor.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/math/special_functions/erf.hpp> // for inverses\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/tools/test.hpp>\n#include <fstream>\n\n#include <boost/math/tools/test_data.hpp>\n\nusing namespace boost::math::tools;\nusing namespace std;\n\nfloat external_f;\nfloat force_truncate(const float* f)\n{\n   external_f = *f;\n   return external_f;\n}\n\nfloat truncate_to_float(boost::math::ntl::RR r)\n{\n   float f = boost::math::tools::real_cast<float>(r);\n   return force_truncate(&f);\n}\n\nstruct erf_data_generator\n{\n   boost::math::tuple<boost::math::ntl::RR, boost::math::ntl::RR> operator()(boost::math::ntl::RR z)\n   {\n      // very naively calculate spots using the gamma function at high precision:\n      int sign = 1;\n      if(z < 0)\n      {\n         sign = -1;\n         z = -z;\n      }\n      boost::math::ntl::RR g1, g2;\n      g1 = boost::math::tgamma_lower(boost::math::ntl::RR(0.5), z * z);\n      g1 /= sqrt(boost::math::constants::pi<boost::math::ntl::RR>());\n      g1 *= sign;\n\n      if(z < 0.5)\n      {\n         g2 = 1 - (sign * g1);\n      }\n      else\n      {\n         g2 = boost::math::tgamma(boost::math::ntl::RR(0.5), z * z);\n         g2 /= sqrt(boost::math::constants::pi<boost::math::ntl::RR>());\n      }\n      if(sign < 1)\n         g2 = 2 - g2;\n      return boost::math::make_tuple(g1, g2);\n   }\n};\n\ndouble double_factorial(int N)\n{\n   double result = 1;\n   while(N > 2)\n   {\n      N -= 2;\n      result *= N;\n   }\n   return result;\n}\n\nvoid asymptotic_limit(int Bits)\n{\n   //\n   // The following block of code estimates how large z has\n   // to be before we can use the asymptotic expansion for\n   // erf/erfc and still get convergence: the series becomes\n   // divergent eventually so we have to be careful!\n   //\n   double result = (std::numeric_limits<double>::max)();\n   int terms = 0;\n   for(int n = 1; n < 15; ++n)\n   {\n      double lim = (Bits-n) * log(2.0) - log(sqrt(3.14)) + log(double_factorial(2*n+1));\n      double x = 1;\n      while(x*x + (2*n+1)*log(x) <= lim)\n         x += 0.1;\n      if(x < result)\n      {\n         result = x;\n         terms = n;\n      }\n   }\n\n   std::cout << \"Erf asymptotic limit for \" \n      << Bits << \" bit numbers is \" \n      << result << \" after approximately \" \n      << terms << \" terms.\" << std::endl;\n\n   result = (std::numeric_limits<double>::max)();\n   terms = 0;\n   for(int n = 1; n < 30; ++n)\n   {\n      double x = pow(double_factorial(2*n+1)/pow(2.0, n-Bits), 1 / (2.0*n));\n      if(x < result)\n      {\n         result = x;\n         terms = n;\n      }\n   }\n\n   std::cout << \"Erfc asymptotic limit for \" \n      << Bits << \" bit numbers is \" \n      << result << \" after approximately \" \n      << terms << \" terms.\" << std::endl;\n}\n\nboost::math::tuple<boost::math::ntl::RR, boost::math::ntl::RR> erfc_inv(boost::math::ntl::RR r)\n{\n   boost::math::ntl::RR x = exp(-r * r);\n   x = NTL::RoundToPrecision(x.value(), 64);\n   std::cout << x << \"   \";\n   boost::math::ntl::RR result = boost::math::erfc_inv(x);\n   std::cout << result << std::endl;\n   return boost::math::make_tuple(x, result);\n}\n\n\nint cpp_main(int argc, char*argv [])\n{\n   boost::math::ntl::RR::SetPrecision(1000);\n   boost::math::ntl::RR::SetOutputPrecision(40);\n\n   parameter_info<boost::math::ntl::RR> arg1;\n   test_data<boost::math::ntl::RR> data;\n\n   bool cont;\n   std::string line;\n\n   if(argc >= 2)\n   {\n      if(strcmp(argv[1], \"--limits\") == 0)\n      {\n         asymptotic_limit(24);\n         asymptotic_limit(53);\n         asymptotic_limit(64);\n         asymptotic_limit(106);\n         asymptotic_limit(113);\n         return 0;\n      }\n      else if(strcmp(argv[1], \"--erf_inv\") == 0)\n      {\n         boost::math::ntl::RR (*f)(boost::math::ntl::RR);\n         f = boost::math::erf_inv;\n         std::cout << \"Welcome.\\n\"\n            \"This program will generate spot tests for the inverse erf function:\\n\";\n         std::cout << \"Enter the number of data points: \";\n         int points;\n         std::cin >> points;\n         data.insert(f, make_random_param(boost::math::ntl::RR(-1), boost::math::ntl::RR(1), points));\n      }\n      else if(strcmp(argv[1], \"--erfc_inv\") == 0)\n      {\n         boost::math::tuple<boost::math::ntl::RR, boost::math::ntl::RR> (*f)(boost::math::ntl::RR);\n         f = erfc_inv;\n         std::cout << \"Welcome.\\n\"\n            \"This program will generate spot tests for the inverse erfc function:\\n\";\n         std::cout << \"Enter the maximum *result* expected from erfc_inv: \";\n         double max_val;\n         std::cin >> max_val;\n         std::cout << \"Enter the number of data points: \";\n         int points;\n         std::cin >> points;\n         parameter_info<boost::math::ntl::RR> arg = make_random_param(boost::math::ntl::RR(0), boost::math::ntl::RR(max_val), points);\n         arg.type |= dummy_param;\n         data.insert(f, arg);\n      }\n   }\n   else\n   {\n      std::cout << \"Welcome.\\n\"\n         \"This program will generate spot tests for the erf and erfc functions:\\n\"\n         \"  erf(z) and erfc(z)\\n\\n\";\n\n      do{\n         if(0 == get_user_parameter_info(arg1, \"a\"))\n            return 1;\n         data.insert(erf_data_generator(), arg1);\n\n         std::cout << \"Any more data [y/n]?\";\n         std::getline(std::cin, line);\n         boost::algorithm::trim(line);\n         cont = (line == \"y\");\n      }while(cont);\n   }\n\n   std::cout << \"Enter name of test data file [default=erf_data.ipp]\";\n   std::getline(std::cin, line);\n   boost::algorithm::trim(line);\n   if(line == \"\")\n      line = \"erf_data.ipp\";\n   std::ofstream ofs(line.c_str());\n   write_code(ofs, data, \"erf_data\");\n   \n   return 0;\n}\n\n/* Output for asymptotic limits:\n\nErf asymptotic limit for 24 bit numbers is 2.8 after approximately 6 terms.\nErfc asymptotic limit for 24 bit numbers is 4.12064 after approximately 17 terms.\nErf asymptotic limit for 53 bit numbers is 4.3 after approximately 11 terms.\nErfc asymptotic limit for 53 bit numbers is 6.19035 after approximately 29 terms.\nErf asymptotic limit for 64 bit numbers is 4.8 after approximately 12 terms.\nErfc asymptotic limit for 64 bit numbers is 7.06004 after approximately 29 terms.\nErf asymptotic limit for 106 bit numbers is 6.5 after approximately 14 terms.\nErfc asymptotic limit for 106 bit numbers is 11.6626 after approximately 29 terms.\nErf asymptotic limit for 113 bit numbers is 6.8 after approximately 14 terms.\nErfc asymptotic limit for 113 bit numbers is 12.6802 after approximately 29 terms.\n*/\n\n", "meta": {"hexsha": "3a5d1bdc893e266cc3ed8e3ab107a602c5bb4d83", "size": 6802, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/tools/erf_data.cpp", "max_stars_repo_name": "ballisticwhisper/boost", "max_stars_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_stars_repo_licenses": ["BSL-1.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": "libs/math/tools/erf_data.cpp", "max_issues_repo_name": "ballisticwhisper/boost", "max_issues_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_issues_repo_licenses": ["BSL-1.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": "libs/math/tools/erf_data.cpp", "max_forks_repo_name": "ballisticwhisper/boost", "max_forks_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_forks_repo_licenses": ["BSL-1.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": 30.3660714286, "max_line_length": 134, "alphanum_fraction": 0.5935019112, "num_tokens": 1939, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.6442250996557036, "lm_q1q2_score": 0.4918554036612757}}
{"text": "// The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt\n/*\n    This is an example illustrating the use of the deep learning tools from the dlib C++\n    Library.  I'm assuming you have already read the dnn_introduction_ex.cpp, the\n    dnn_introduction2_ex.cpp and the dnn_introduction3_ex.cpp examples.  In this example\n    program we are going to show how one can train Generative Adversarial Networks (GANs).  In\n    particular, we will train a Deep Convolutional Generative Adversarial Network (DCGAN) like\n    the one introduced in this paper:\n    \"Unsupervised Representation Learning with Deep Convolutional Generative Adversarial Networks\"\n    by Alec Radford, Luke Metz, Soumith Chintala.\n\n    The main idea is that there are two neural networks training at the same time:\n    - the generator is in charge of generating images that look as close as possible to the\n      ones from the dataset.\n    - the discriminator will decide whether an image is fake (created by the generator) or real\n      (selected from the dataset).\n\n    Each training iteration alternates between training the discriminator and the generator.\n    We first train the discriminator with real and fake images and then use the gradient from\n    the discriminator to update the generator.\n\n    In this example, we are going to learn how to generate digits from the MNIST dataset, but\n    the same code can be run using the Fashion MNIST datset:\n    https://github.com/zalandoresearch/fashion-mnist\n*/\n\n#include <algorithm>\n#include <iostream>\n\n#include <dlib/data_io.h>\n#include <dlib/dnn.h>\n#include <dlib/gui_widgets.h>\n#include <dlib/matrix.h>\n\nusing namespace std;\nusing namespace dlib;\n\n// Some helper definitions for the noise generation\nconst size_t noise_size = 100;\nusing noise_t = std::array<matrix<float, 1, 1>, noise_size>;\n\nnoise_t make_noise(dlib::rand& rnd)\n{\n    noise_t noise;\n    for (auto& n : noise)\n    {\n        n = rnd.get_random_gaussian();\n    }\n    return noise;\n}\n\n// A convolution with custom padding\ntemplate<long num_filters, long kernel_size, int stride, int padding, typename SUBNET>\nusing conp = add_layer<con_<num_filters, kernel_size, kernel_size, stride, stride, padding, padding>, SUBNET>;\n\n// A transposed convolution to with custom padding\ntemplate<long num_filters, long kernel_size, int stride, int padding, typename SUBNET>\nusing contp = add_layer<cont_<num_filters, kernel_size, kernel_size, stride, stride, padding, padding>, SUBNET>;\n\n// The generator is made of a bunch of deconvolutional layers.  Its input is a 1 x 1 x k noise\n// tensor, and the output is the generated image.  The loss layer does not matter for the\n// training, we just stack a compatible one on top to be able to have a () operator on the\n// generator.\nusing generator_type =\n    loss_binary_log_per_pixel<\n    sig<contp<1, 4, 2, 1,\n    relu<bn_con<contp<64, 4, 2, 1,\n    relu<bn_con<contp<128, 3, 2, 1,\n    relu<bn_con<contp<256, 4, 1, 0,\n    input<noise_t>\n    >>>>>>>>>>>>;\n\n// Now, let's proceed to define the discriminator, whose role will be to decide whether an\n// image is fake or not.\nusing discriminator_type =\n    loss_binary_log<\n    conp<1, 3, 1, 0,\n    leaky_relu<bn_con<conp<256, 4, 2, 1,\n    leaky_relu<bn_con<conp<128, 4, 2, 1,\n    leaky_relu<conp<64, 4, 2, 1,\n    input<matrix<unsigned char>>\n    >>>>>>>>>>;\n\n// Some helper functions to generate and get the images from the generator\nmatrix<unsigned char> generate_image(generator_type& net, const noise_t& noise)\n{\n    const matrix<float> output = net(noise);\n    matrix<unsigned char> image;\n    assign_image(image, 255 * output);\n    return image;\n}\n\nstd::vector<matrix<unsigned char>> get_generated_images(const tensor& out)\n{\n    std::vector<matrix<unsigned char>> images;\n    for (long n = 0; n < out.num_samples(); ++n)\n    {\n        matrix<float> output = image_plane(out, n);\n        matrix<unsigned char> image;\n        assign_image(image, 255 * output);\n        images.push_back(std::move(image));\n    }\n    return images;\n}\n\n\n\n#if defined(BUILD_MONOLITHIC)\n#define main(cnt, arr)      dlib_dnn_dcgan_train_ex_main(cnt, arr)\n#endif\n\nint main(int argc, const char** argv)\ntry\n{\n    // This example is going to run on the MNIST dataset.\n    if (argc != 2)\n    {\n        cout << \"This example needs the MNIST dataset to run!\" << endl;\n        cout << \"You can get MNIST from http://yann.lecun.com/exdb/mnist/\" << endl;\n        cout << \"Download the 4 files that comprise the dataset, decompress them, and\" << endl;\n        cout << \"put them in a folder.  Then give that folder as input to this program.\" << endl;\n        return EXIT_FAILURE;\n    }\n\n    // MNIST is broken into two parts, a training set of 60000 images and a test set of 10000\n    // images.  Each image is labeled so that we know what hand written digit is depicted.\n    // These next statements load the dataset into memory.\n    std::vector<matrix<unsigned char>> training_images;\n    std::vector<unsigned long>         training_labels;\n    std::vector<matrix<unsigned char>> testing_images;\n    std::vector<unsigned long>         testing_labels;\n    load_mnist_dataset(argv[1], training_images, training_labels, testing_images, testing_labels);\n\n    // Fix the random generator seeds for network initialization and noise\n    srand(1234);\n    dlib::rand rnd(std::rand());\n\n    // Instantiate both generator and discriminator\n    generator_type generator;\n    discriminator_type discriminator;\n    // setup all leaky_relu_ layers in the discriminator to have alpha = 0.2\n    visit_computational_layers(discriminator, [](leaky_relu_& l){ l = leaky_relu_(0.2); });\n    // Remove the bias learning from all bn_ inputs in both networks\n    disable_duplicative_biases(generator);\n    disable_duplicative_biases(discriminator);\n    // Forward random noise so that we see the tensor size at each layer\n    discriminator(generate_image(generator, make_noise(rnd)));\n    cout << \"generator (\" << count_parameters(generator) << \" parameters)\" << endl;\n    cout << generator << endl;\n    cout << \"discriminator (\" << count_parameters(discriminator) << \" parameters)\" << endl;\n    cout << discriminator << endl;\n\n    // The solvers for the generator and discriminator networks.  In this example, we are going to\n    // train the networks manually, so we don't need to use a dnn_trainer.  Note that the\n    // discriminator could be trained using a dnn_trainer, but not the generator, since its\n    // training process is a bit particular.\n    std::vector<adam> g_solvers(generator.num_computational_layers, adam(0, 0.5, 0.999));\n    std::vector<adam> d_solvers(discriminator.num_computational_layers, adam(0, 0.5, 0.999));\n    double learning_rate = 2e-4;\n\n    // Resume training from last sync file\n    size_t iteration = 0;\n    if (file_exists(\"dcgan_sync\"))\n    {\n        deserialize(\"dcgan_sync\") >> generator >> discriminator >> iteration;\n    }\n\n    const size_t minibatch_size = 64;\n    const std::vector<float> real_labels(minibatch_size, 1);\n    const std::vector<float> fake_labels(minibatch_size, -1);\n    dlib::image_window win;\n    resizable_tensor real_samples_tensor, fake_samples_tensor, noises_tensor;\n    running_stats<double> g_loss, d_loss;\n    while (iteration < 50000)\n    {\n        // Train the discriminator with real images\n        std::vector<matrix<unsigned char>> real_samples;\n        while (real_samples.size() < minibatch_size)\n        {\n            auto idx = rnd.get_random_32bit_number() % training_images.size();\n            real_samples.push_back(training_images[idx]);\n        }\n        // The following lines are equivalent to calling train_one_step(real_samples, real_labels)\n        discriminator.to_tensor(real_samples.begin(), real_samples.end(), real_samples_tensor);\n        d_loss.add(discriminator.compute_loss(real_samples_tensor, real_labels.begin()));\n        discriminator.back_propagate_error(real_samples_tensor);\n        discriminator.update_parameters(d_solvers, learning_rate);\n\n        // Train the discriminator with fake images\n        // 1. Generate some random noise\n        std::vector<noise_t> noises;\n        while (noises.size() < minibatch_size)\n        {\n            noises.push_back(make_noise(rnd));\n        }\n        // 2. Convert noises into a tensor\n        generator.to_tensor(noises.begin(), noises.end(), noises_tensor);\n        // 3. Forward the noise through the network and convert the outputs into images.\n        const auto fake_samples = get_generated_images(generator.forward(noises_tensor));\n        // 4. Finally train the discriminator.  The following lines are equivalent to calling\n        // train_one_step(fake_samples, fake_labels)\n        discriminator.to_tensor(fake_samples.begin(), fake_samples.end(), fake_samples_tensor);\n        d_loss.add(discriminator.compute_loss(fake_samples_tensor, fake_labels.begin()));\n        discriminator.back_propagate_error(fake_samples_tensor);\n        discriminator.update_parameters(d_solvers, learning_rate);\n\n        // Train the generator\n        // This part is the essence of the Generative Adversarial Networks.  Until now, we have\n        // just trained a binary classifier that the generator is not aware of.  But now, the\n        // discriminator is going to give feedback to the generator on how it should update\n        // itself to generate more realistic images.  The following lines perform the same\n        // actions as train_one_step() except for the network update part.  They can also be\n        // seen as test_one_step() plus the error back propagation.\n\n        // Forward the fake samples and compute the loss with real labels\n        g_loss.add(discriminator.compute_loss(fake_samples_tensor, real_labels.begin()));\n        // Back propagate the error to fill the final data gradient\n        discriminator.back_propagate_error(fake_samples_tensor);\n        // Get the gradient that will tell the generator how to update itself\n        const tensor& d_grad = discriminator.get_final_data_gradient();\n        generator.back_propagate_error(noises_tensor, d_grad);\n        generator.update_parameters(g_solvers, learning_rate);\n\n        // At some point, we should see that the generated images start looking like samples from\n        // the MNIST dataset\n        if (++iteration % 1000 == 0)\n        {\n            serialize(\"dcgan_sync\") << generator << discriminator << iteration;\n            std::cout <<\n                \"step#: \" << iteration <<\n                \"\\tdiscriminator loss: \" << d_loss.mean() * 2 <<\n                \"\\tgenerator loss: \" << g_loss.mean() << '\\n';\n            win.set_image(tile_images(fake_samples));\n            win.set_title(\"DCGAN step#: \" + to_string(iteration));\n            d_loss.clear();\n            g_loss.clear();\n        }\n    }\n\n    // Once the training has finished, we don't need the discriminator any more. We just keep the\n    // generator.\n    generator.clean();\n    serialize(\"dcgan_mnist.dnn\") << generator;\n\n    // To test the generator, we just forward some random noise through it and visualize the\n    // output.\n    while (!win.is_closed())\n    {\n        const auto image = generate_image(generator, make_noise(rnd));\n        const auto real = discriminator(image) > 0;\n        win.set_image(image);\n        cout << \"The discriminator thinks it's \" << (real ? \"real\" : \"fake\");\n        cout << \". Hit enter to generate a new image\";\n        cin.get();\n    }\n\n    return EXIT_SUCCESS;\n}\ncatch(exception& e)\n{\n    cout << e.what() << endl;\n    return EXIT_FAILURE;\n}\n", "meta": {"hexsha": "6a7b46423278b56789e9f9430a63f05bffb2fb53", "size": 11534, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/dnn_dcgan_train_ex.cpp", "max_stars_repo_name": "GerHobbelt/dlib", "max_stars_repo_head_hexsha": "d26e917abc626fb81f0b57ecf1f3be555bddf8de", "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/dnn_dcgan_train_ex.cpp", "max_issues_repo_name": "GerHobbelt/dlib", "max_issues_repo_head_hexsha": "d26e917abc626fb81f0b57ecf1f3be555bddf8de", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/dnn_dcgan_train_ex.cpp", "max_forks_repo_name": "GerHobbelt/dlib", "max_forks_repo_head_hexsha": "d26e917abc626fb81f0b57ecf1f3be555bddf8de", "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.6893939394, "max_line_length": 112, "alphanum_fraction": 0.6926478238, "num_tokens": 2696, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.6442250996557036, "lm_q1q2_score": 0.4918554036612757}}
{"text": "#include <stan/math/opencl/double_d.hpp>\n#include <gtest/gtest.h>\n#include <limits>\n#include <Eigen/Core>\n\n#define EXPECT_NORMALIZED(a) \\\n  EXPECT_LT(std::abs(a.low), \\\n            std::abs(a.high) * std::numeric_limits<double>::epsilon());\n\nTEST(double_d, add_dd_dd_test) {\n  using stan::math::internal::add_dd_dd;\n  using stan::math::internal::double_d;\n  double eps = std::numeric_limits<double>::epsilon();\n  double h_eps = eps * 0.5;\n  double_d a{1.0, h_eps};\n  double_d c{h_eps, 0.0};\n  double_d d{-1.0, -h_eps + eps * h_eps};\n\n  // simple\n  double_d res = add_dd_dd(a, a);\n  EXPECT_NORMALIZED(res);\n  EXPECT_EQ(res.high, 2.0);\n  EXPECT_EQ(res.low, eps);\n\n  // carry\n  res = add_dd_dd(a, c);\n  EXPECT_NORMALIZED(res);\n  EXPECT_EQ(res.high, 1.0 + eps);\n  EXPECT_EQ(res.low, 0.0);\n\n  // cancelation\n  res = add_dd_dd(a, d);\n  EXPECT_NORMALIZED(res);\n  EXPECT_EQ(res.high, eps * h_eps);\n  EXPECT_EQ(res.low, 0.0);\n}\n\nTEST(double_d, mul_dd_dd_test) {\n  using stan::math::internal::double_d;\n  using stan::math::internal::mul_dd_dd;\n  double eps = std::numeric_limits<double>::epsilon();\n  double h_eps = eps * 0.5;\n  double_d a{1.0, h_eps * 0.001};\n  double_d b{h_eps, h_eps * h_eps * h_eps * h_eps};\n  double_d c{1.0, h_eps};\n  double_d d{1.0, -h_eps};\n\n  // simple\n  double_d res = mul_dd_dd(a, b);\n  EXPECT_NORMALIZED(res);\n  EXPECT_EQ(res.high, h_eps);\n  EXPECT_EQ(res.low, h_eps * h_eps * 0.001);\n\n  // carry\n  res = mul_dd_dd(c, c);\n  EXPECT_NORMALIZED(res);\n  EXPECT_EQ(res.high, 1.0 + eps);\n  EXPECT_EQ(res.low, 0.0);\n\n  // cancelation\n  res = mul_dd_dd(c, d);\n  EXPECT_NORMALIZED(res);\n  EXPECT_EQ(res.high, 1.0);\n  EXPECT_EQ(res.low, 0.0);\n}\n\nTEST(double_d, div_dd_dd_test) {\n  using stan::math::internal::div_dd_dd;\n  using stan::math::internal::double_d;\n  double eps = std::numeric_limits<double>::epsilon();\n  double h_eps = eps * 0.5;\n  double_d a{1.0, h_eps};\n  double_d b{1.0, h_eps * (1 - eps)};\n  double_d c{0.0, 0.0};\n  double_d d{1.0, -h_eps};\n\n  // simple\n  double_d res = div_dd_dd(a, a);\n  EXPECT_NORMALIZED(res);\n  EXPECT_EQ(res.high, 1.0);\n  EXPECT_EQ(res.low, 0.0);\n\n  res = div_dd_dd(a, b);\n  EXPECT_NORMALIZED(res);\n  EXPECT_EQ(res.high, 1.0);\n  EXPECT_EQ(res.low, h_eps * eps);\n\n  // div by zero\n  res = div_dd_dd(a, c);\n  EXPECT_EQ(res.high, std::numeric_limits<double>::infinity());\n  EXPECT_EQ(res.low, 0);\n}\n\n// this is the best test we have, but it relies on the nonstandard gcc extension\n// quadmath, so it is not run by default\n#ifdef GCC_QUADMATH_TEST\n#include <quadmath.h>\n\n#define EXPECT_DD_F128_EQ(dd, f128) \\\n  tmp = (dd);                       \\\n  EXPECT_NEAR((__float128)tmp.high + tmp.low, (f128), 1e-30 * 1e30)\n\nTEST(double_d, all) {\n  using stan::math::internal::double_d;\n  for (int i = 0; i < 10000000; i++) {\n    double_d tmp;\n    double high = Eigen::MatrixXd::Random(0, 0).coeff(0, 0) * 1e30;\n    double low = Eigen::MatrixXd::Random(0, 0).coeff(0, 0) * 1e-20 * 1e30;\n    double_d dd = high;\n    dd.low = low;\n    __float128 f128 = high;\n    f128 += low;\n    EXPECT_DD_F128_EQ(dd, f128);\n\n    double high2 = Eigen::MatrixXd::Random(0, 0).coeff(0, 0);\n    double low2 = Eigen::MatrixXd::Random(0, 0).coeff(0, 0) * 1e-20;\n    double_d dd2 = high2;\n    dd2.low = low2;\n    __float128 f1282 = high2;\n    f1282 += low2;\n    EXPECT_DD_F128_EQ(dd2, f1282);\n\n    EXPECT_DD_F128_EQ(dd + dd2, f128 + f1282);\n    EXPECT_DD_F128_EQ(dd - dd2, f128 - f1282);\n    EXPECT_DD_F128_EQ(dd * dd2, f128 * f1282);\n    EXPECT_DD_F128_EQ(dd / dd2, f128 / f1282);\n\n    __float128 f1283 = high;\n    __float128 f1284 = high2;\n    EXPECT_DD_F128_EQ(stan::math::internal::mul_d_d(high, high2),\n                      f1283 * f1284);\n  }\n}\n#endif\n\n#ifdef STAN_OPENCL\n\n#include <stan/math/opencl/prim.hpp>\nstatic const std::string double_d_test_kernel_code\n    = STRINGIFY(__kernel void double_d_test_kernel(__global double_d *C,\n                                                   const __global double_d *A,\n                                                   const __global double *B) {\n        const int i = get_global_id(0);\n        C[i] = mul_dd_d(A[i], B[i]);\n      });\n\nconst stan::math::opencl_kernels::kernel_cl<\n    stan::math::opencl_kernels::out_buffer,\n    stan::math::opencl_kernels::in_buffer,\n    stan::math::opencl_kernels::in_buffer>\n    double_d_test_kernel(\"double_d_test_kernel\",\n                         {stan::math::internal::double_d_src,\n                          double_d_test_kernel_code});\n\nTEST(double_d, opencl) {\n  using stan::math::internal::double_d;\n  using VectorXdd = Eigen::Matrix<double_d, -1, 1>;\n  int n = 10;\n  VectorXdd a(n);\n  Eigen::VectorXd b = Eigen::VectorXd::Random(n);\n  for (int i = 0; i < n; i++) {\n    a[i].high = Eigen::VectorXd::Random(1)[0];\n    a[i].low = Eigen::VectorXd::Random(1)[0] * 1e-17;\n  }\n  stan::math::matrix_cl<double_d> a_cl(a);\n  stan::math::matrix_cl<double> b_cl(b);\n  stan::math::matrix_cl<double_d> c_cl(n, 1);\n  double_d_test_kernel(cl::NDRange(n), c_cl, a_cl, b_cl);\n  VectorXdd c = stan::math::from_matrix_cl(c_cl);\n  for (int i = 0; i < n; i++) {\n    double_d correct = a[i] * b[i];\n    EXPECT_EQ(c[i].high, correct.high);\n    EXPECT_NEAR(c[i].low, correct.low, 1e-30);\n  }\n}\n\n#endif\n", "meta": {"hexsha": "ffbad5e7ff2c9309957546d1b07c5dbab44d26fc", "size": 5183, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/opencl/double_d_test.cpp", "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": "test/unit/math/opencl/double_d_test.cpp", "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": "test/unit/math/opencl/double_d_test.cpp", "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": 29.1179775281, "max_line_length": 80, "alphanum_fraction": 0.6311016786, "num_tokens": 1677, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911056, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.49185540194246313}}
{"text": "// -----------------------------------------------------------------------------\n// Fern \u00a9 Geoneric\n//\n// This file is part of Geoneric Fern which is available under the terms of\n// the GNU General Public License (GPL), version 2. If you do not want to\n// be bound by the terms of the GPL, you may purchase a proprietary license\n// from Geoneric (http://www.geoneric.eu/contact).\n// -----------------------------------------------------------------------------\n#define BOOST_TEST_MODULE fern algorithm space focal slope\n#include <boost/test/unit_test.hpp>\n#include \"fern/core/type_traits.h\"\n#include \"fern/core/types.h\"\n#include \"fern/feature/core/data_customization_point/array.h\"\n#include \"fern/feature/core/data_customization_point/masked_array.h\"\n#include \"fern/feature/core/data_customization_point/masked_raster.h\"\n#include \"fern/algorithm/core/mask_customization_point/array.h\"\n#include \"fern/algorithm/core/argument_traits/masked_raster.h\"\n#include \"fern/algorithm/core/argument_customization_point/masked_raster.h\"\n#include \"fern/algorithm/space/focal/slope.h\"\n\n\nnamespace fa = fern::algorithm;\n\n\ntemplate<\n    class Value,\n    class Result>\nusing OutOfRangePolicy = fa::slope::OutOfRangePolicy<Value, Result>;\n\n\nBOOST_AUTO_TEST_CASE(out_of_range_policy)\n{\n    {\n        OutOfRangePolicy<fern::float32_t, fern::float32_t> policy;\n        BOOST_CHECK(policy.within_range(4.5));\n        BOOST_CHECK(!policy.within_range(fern::nan<fern::float32_t>()));\n        BOOST_CHECK(!policy.within_range(fern::infinity<fern::float32_t>()));\n    }\n}\n\n\ntemplate<\n    class T>\nusing MaskedRaster = fern::MaskedRaster<T, 2>;\n\n\nBOOST_AUTO_TEST_CASE(algorithm)\n{\n    // Create input raster (from the PCRaster manual):\n    // +-----+-----+-----+-----+-----+\n    // |  70 |  70 |  80 |  X  | 120 |\n    // +-----+-----+-----+-----+-----+\n    // |  70 |  70 |  90 |  X  |  X  |\n    // +-----+-----+-----+-----+-----+\n    // |  70 |  70 | 100 | 140 | 280 |\n    // +-----+-----+-----+-----+-----+\n    // | 180 | 160 | 110 | 160 | 320 |\n    // +-----+-----+-----+-----+-----+\n    // | 510 | 440 | 300 | 400 | 480 |\n    // +-----+-----+-----+-----+-----+\n    size_t const nr_rows = 5;\n    size_t const nr_cols = 5;\n    auto extents = fern::extents[nr_rows][nr_cols];\n\n    double const cell_width = 50.0;\n    double const cell_height = 50.0;\n    double const west = 0.0;\n    double const north = 0.0;\n\n    MaskedRaster<double>::Transformation transformation{{west, cell_width,\n        north, cell_height}};\n    MaskedRaster<double> raster(extents, transformation);\n\n    raster[0][0] = 70.0;\n    raster[0][1] = 70.0;\n    raster[0][2] = 80.0;\n    raster.mask()[0][3] = true;\n    raster[0][4] = 120.0;\n    raster[1][0] = 70.0;\n    raster[1][1] = 70.0;\n    raster[1][2] = 90.0;\n    raster.mask()[1][3] = true;\n    raster.mask()[1][4] = true;\n    raster[2][0] = 70.0;\n    raster[2][1] = 70.0;\n    raster[2][2] = 100.0;\n    raster[2][3] = 140.0;\n    raster[2][4] = 280.0;\n    raster[3][0] = 180.0;\n    raster[3][1] = 160.0;\n    raster[3][2] = 110.0;\n    raster[3][3] = 160.0;\n    raster[3][4] = 320.0;\n    raster[4][0] = 510.0;\n    raster[4][1] = 440.0;\n    raster[4][2] = 300.0;\n    raster[4][3] = 400.0;\n    raster[4][4] = 480.0;\n\n\n    // Create output raster (from PCRaster manual).\n    MaskedRaster<double> result_we_want(extents, transformation);\n\n    result_we_want[0][0] = 0.0118;\n    result_we_want[0][1] = 0.114;\n    result_we_want[0][2] = 0.394;\n    result_we_want.mask()[0][3] = true;\n    result_we_want[0][4] = 0.673;\n    result_we_want[1][0] = 0.13;\n    result_we_want[1][1] = 0.206;\n    result_we_want[1][2] = 0.604;\n    result_we_want.mask()[1][3] = true;\n    result_we_want.mask()[1][4] = true;\n    result_we_want[2][0] = 1.3;\n    result_we_want[2][1] = 0.775;\n    result_we_want[2][2] = 0.643;\n    result_we_want[2][3] = 1.73;\n    result_we_want[2][4] = 1.87;\n    result_we_want[3][0] = 3.73;\n    result_we_want[3][1] = 3.54;\n    result_we_want[3][2] = 2.58;\n    result_we_want[3][3] = 3.02;\n    result_we_want[3][4] = 2.36;\n    result_we_want[4][0] = 2.76;\n    result_we_want[4][1] = 3.07;\n    result_we_want[4][2] = 2.59;\n    result_we_want[4][3] = 2.66;\n    result_we_want[4][4] = 1.65;\n\n\n    // Calculate slope.\n    MaskedRaster<double> result_we_get(extents, transformation);\n\n    using InputNoDataPolicy = fa::InputNoDataPolicies<\n        fa::DetectNoDataByValue<fern::Mask<2>>>;\n    using OutputNoDataPolicy = fa::MarkNoDataByValue<fern::Mask<2>>;\n\n    fa::SequentialExecutionPolicy sequential;\n\n    OutputNoDataPolicy output_no_data_policy(result_we_get.mask(), true);\n\n    fa::space::slope<fa::unary::DiscardRangeErrors>(\n        InputNoDataPolicy{{raster.mask(), true}},\n        output_no_data_policy,\n        sequential,\n        raster, result_we_get);\n\n    for(size_t r = 0; r < nr_rows; ++r) {\n        for(size_t c = 0; c < nr_cols; ++c) {\n            if((r == 0 && c == 3) || (r == 1 && c == 3) || (r == 1 && c == 4)) {\n                BOOST_CHECK(result_we_get.mask()[r][c]);\n            }\n            else {\n                BOOST_CHECK_CLOSE(result_we_get[r][c], result_we_want[r][c],\n                    1e-0);\n            }\n        }\n    }\n}\n\n\ntemplate<\n    typename T>\nvoid compare_result_flat(\n    MaskedRaster<T> const& result)\n{\n    // +-----+-----+-----+\n    // | 0.0 | 0.0 | 0.0 |\n    // +-----+-----+-----+\n    // | 0.0 | 0.0 | 0.0 |\n    // +-----+-----+-----+\n    // | 0.0 | 0.0 | 0.0 |\n    // +-----+-----+-----+\n\n    std::vector<bool> no_data = {\n        false, false, false,\n        false, false, false,\n        false, false, false\n    };\n\n    BOOST_REQUIRE_EQUAL_COLLECTIONS(no_data.begin(), no_data.end(),\n        result.mask().data(), result.mask().data() +\n            result.mask().num_elements());\n\n\n    std::vector<T> values = {\n        0.0, 0.0, 0.0,\n        0.0, 0.0, 0.0,\n        0.0, 0.0, 0.0\n    };\n\n    BOOST_REQUIRE_EQUAL_COLLECTIONS(values.begin(), values.end(),\n        result.data(), result.data() + result.num_elements());\n}\n\n\ntemplate<\n    typename T>\nvoid test_flat(\n    T const& value)\n{\n    // +-------+-------+-------+\n    // | value | value | value |\n    // +-------+-------+-------+\n    // | value | value | value |\n    // +-------+-------+-------+\n    // | value | value | value |\n    // +-------+-------+-------+\n    size_t const nr_rows = 3;\n    size_t const nr_cols = 3;\n    auto extents = fern::extents[nr_rows][nr_cols];\n\n    double const cell_width = 50.0;\n    double const cell_height = 50.0;\n    double const west = 0.0;\n    double const north = 0.0;\n\n    typename MaskedRaster<T>::Transformation transformation{{west, cell_width,\n        north, cell_height}};\n    MaskedRaster<T> raster(extents, transformation);\n\n    for(size_t r = 0; r < nr_rows; ++r) {\n        for(size_t c = 0; c < nr_cols; ++c) {\n            raster[r][c] = value;\n        }\n    }\n\n\n    using InputNoDataPolicy = fa::InputNoDataPolicies<\n        fa::DetectNoDataByValue<fern::Mask<2>>>;\n    using OutputNoDataPolicy = fa::MarkNoDataByValue<fern::Mask<2>>;\n\n    fa::ParallelExecutionPolicy parallel;\n    fa::SequentialExecutionPolicy sequential;\n\n    {\n        MaskedRaster<T> result_we_get(extents, transformation);\n        OutputNoDataPolicy output_no_data_policy(result_we_get.mask(), true);\n\n        fa::space::slope<fa::unary::DiscardRangeErrors>(\n            InputNoDataPolicy{{raster.mask(), true}},\n            output_no_data_policy,\n            sequential,\n            raster, result_we_get);\n\n        compare_result_flat<T>(result_we_get);\n    }\n\n    {\n        MaskedRaster<T> result_we_get(extents, transformation);\n        OutputNoDataPolicy output_no_data_policy(result_we_get.mask(), true);\n\n        fa::space::slope<fa::unary::DiscardRangeErrors>(\n            InputNoDataPolicy{{raster.mask(), true}},\n            output_no_data_policy,\n            parallel,\n            raster, result_we_get);\n\n        compare_result_flat<T>(result_we_get);\n    }\n}\n\n\nBOOST_AUTO_TEST_CASE(flat)\n{\n    for(auto const& value: {0.0, 0.055, 0.0925, 0.1, 0.1225, 0.17, 1.0}) {\n        test_flat<float>(value);\n        // test_flat<double>(value);\n    }\n}\n", "meta": {"hexsha": "ea8fb81679e4dfc1b173e8f9fb64d7e3f1ed8a2e", "size": 8076, "ext": "cc", "lang": "C++", "max_stars_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/fern/source/fern/algorithm/space/focal/test/slope_test.cc", "max_stars_repo_name": "quanpands/wflow", "max_stars_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/fern/source/fern/algorithm/space/focal/test/slope_test.cc", "max_issues_repo_name": "quanpands/wflow", "max_issues_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/fern/source/fern/algorithm/space/focal/test/slope_test.cc", "max_forks_repo_name": "quanpands/wflow", "max_forks_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8007380074, "max_line_length": 80, "alphanum_fraction": 0.5627786033, "num_tokens": 2498, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911056, "lm_q2_score": 0.6442251064863695, "lm_q1q2_score": 0.491855401942463}}
{"text": "#include \"Defined_Tensor.h\"\n#include <Eigen\\Dense>\n#include <queue>\n\ndefined_tensor::defined_tensor()\n{\n\tm_tensor_name = Utility_Definition::T_IDENTITY;\n\tAABB_Tree = NULL;\n\tAABB_Segment_Tree = NULL;\n\tbm = NULL;\n\tref_mesh_ = NULL;\n\tkdTree = NULL;\n}\n\ndefined_tensor::~defined_tensor()\n{\n\tif(AABB_Tree) delete AABB_Tree;\n\tif(AABB_Segment_Tree) delete AABB_Segment_Tree;\n\tif(bm) delete bm;\n\tif(kdTree) {delete kdTree; annClose();}\n}\n\nvoid defined_tensor::get_tensor( const OpenVolumeMesh::Geometry::Vec3d& p, OpenVolumeMesh::Geometry::Vec6d& M )\n{\n\tdouble det = 1.0; double t = 1.0;\n\tswitch (m_tensor_name)\n\t{\n\tcase Utility_Definition::T_IDENTITY:\n\t\tM[0] = 1.0; M[1] = 0.0; M[2] = 0.0; M[3] = 1.0; M[4] = 0.0; M[5] = 1.0;\n\t\tbreak;\n\tcase Utility_Definition::T_10_1_1:\n\t\tM[0] = 1.0; M[1] = 0.0; M[2] = 0.0; M[3] = 1.0; M[4] = 0.0; M[5] = 100.0;\n\t\tbreak;\n\tcase Utility_Definition::T_X2_Y2_Z4: //0.5*(x^2 + y^2 + z^4)\n\t\tM[0] = 1.0; M[1] = 0.0; M[2] = 0.0; M[3] = 1.0; M[4] = 0.0; M[5] = 6*p[2]*p[2];\n\t\tdet = M[0]*M[3]*M[5] + M[1]*M[4]*M[2] + M[2]*M[1]*M[4] - M[2]*M[3]*M[2] - M[4]*M[4]*M[1]- M[5]*M[1]*M[1];\n\t\tt = std::pow( det, -0.2);\n\t\tM *= t;\n\t\tbreak;\n\tcase Utility_Definition::T_EXP:\n\t\tM[0] = std::exp(p[0]*p[0]/10 + p[1]*p[1]/10 + p[2]*p[2]/10)/5 + (p[0]*p[0]*exp(p[0]*p[0]/10 + p[1]*p[1]/10 + p[2]*p[2]/10))/25;\n\t\tM[3] = std::exp(p[0]*p[0]/10 + p[1]*p[1]/10 + p[2]*p[2]/10)/5 + (p[1]*p[1]*exp(p[0]*p[0]/10 + p[1]*p[1]/10 + p[2]*p[2]/10))/25;\n\t\tM[5] = std::exp(p[0]*p[0]/10 + p[1]*p[1]/10 + p[2]*p[2]/10)/5 + (p[2]*p[2]*exp(p[0]*p[0]/10 + p[1]*p[1]/10 + p[2]*p[2]/10))/25;\n\t\tM[1] = (p[0]*p[1]*exp(p[0]*p[0]/10 + p[1]*p[1]/10 + p[2]*p[2]/10))/25;\n\t\tM[4] = (p[2]*p[1]*exp(p[0]*p[0]/10 + p[1]*p[1]/10 + p[2]*p[2]/10))/25;\n\t\tM[2] = (p[2]*p[0]*exp(p[0]*p[0]/10 + p[1]*p[1]/10 + p[2]*p[2]/10))/25;\n\t\tdet = M[0]*M[3]*M[5] + M[1]*M[4]*M[2] + M[2]*M[1]*M[4] - M[2]*M[3]*M[2] - M[4]*M[4]*M[1]- M[5]*M[1]*M[1];\n\t\tt = std::pow( det, -0.2);\n\t\tM *= t;\n\t\tbreak;\n\tdefault:\n\t\tM[0] = 1.0; M[1] = 0.0; M[2] = 0.0; M[3] = 1.0; M[4] = 0.0; M[5] = 1.0;\n\t\tbreak;\n\t}\n\n\tif(Utility_Definition::T_SPHERICAL_SHOCK == m_tensor_name)\n\t{\n\t\tdouble t = 7;\n\t\tEigen::Matrix3d R;\n\t\tdouble r = p.norm();\n\t\tOpenVolumeMesh::Geometry::Vec3d e_r = p / r;\n\t\tlocal_frame lf; lf.n = e_r; lf.find_e_x_y();\n\t\tR(0,0) =    e_r[0]; R(0,1) =    e_r[1]; R(0,2) =    e_r[2];\n\t\tR(1,0) = lf.e_y[0]; R(1,1) = lf.e_y[1]; R(1,2) = lf.e_y[2];\n\t\tR(2,0) = lf.e_x[0]; R(2,1) = lf.e_x[1]; R(2,2) = lf.e_x[2];\n\n\t\tEigen::Matrix3d D; D.setZero();\n\t\tD(0,0) = 1.0/( 0.025 + 1.0 * (1.0 - std::exp( -0.01*std::abs(r*r - t*t) ) ) );\n\t\tD(1,1) = 2.0 / 2.0; D(2,2) = 2.0 / 2.0;\n\t\tEigen::Matrix3d TM  = R.transpose() *D * D * R;\n\n\t\tM[0] = TM(0,0); M[1] = TM(0,1); M[2] = TM(0,2);\n\t\tM[3] = TM(1,1); M[4] = TM(1,2); M[5] = TM(2,2);\n\t}\n\telse if (Utility_Definition::T_CYLINDER_SHOCK == m_tensor_name)\n\t{\n\t\tdouble t = 7; Eigen::Matrix3d R;\n\t\tdouble r = std::sqrt(p[0]*p[0] + p[1]*p[1]);\n\t\tR(0,0) =  p[0]/r; R(0,1) = p[1]/r; R(0,2) = 0;\n\t\tR(1,0) = -p[1]/r; R(1,1) = p[0]/r; R(1,2) = 0;\n\t\tR(2,0) = 0; R(2,1) = 0; R(2,2) = 1;\n\n\t\tEigen::Matrix3d D; D.setZero();\n\t\tD(0,0) = 2.0/( 0.1 + 2.0 * (1.0 - std::exp( -0.01*std::abs(r*r - t*t) ) ) );\n\t\tD(1,1) = 2.0 / 2.0; D(2,2) = 2.0 / 2.0;\n\t\tEigen::Matrix3d TM  = R.transpose() *D * D * R;\n\n\t\tM[0] = TM(0,0); M[1] = TM(0,1); M[2] = TM(0,2);\n\t\tM[3] = TM(1,1); M[4] = TM(1,2); M[5] = TM(2,2);\n\t}\n\n\tif(Utility_Definition::T_PLANAR_SHOCK == m_tensor_name)\n\t{\n\t\tdouble t = 0.6;\n\t\tEigen::Matrix3d D; D.setZero();\n\t\tD(0,0) = 1.0/( 0.0025 + 0.2 * (1.0 - std::exp( -1.0*std::abs(p[0] - t) ) ) );\n\t\tD(1,1) = 1.0 / 0.2; D(2,2) = 1.0 / 0.2;\n\t\tEigen::Matrix3d TM = D * D;\n\n\t\tM[0] = TM(0,0); M[1] = TM(0,1); M[2] = TM(0,2);\n\t\tM[3] = TM(1,1); M[4] = TM(1,2); M[5] = TM(2,2);\n\t}\n\n\tif(Utility_Definition::T_SINE == m_tensor_name)\n\t{\n\t\t//printf(\"Sine tensor!!!!!!!\\n\");\n\t\tEigen::Matrix3d R;\n\t\tOpenVolumeMesh::Geometry::Vec3d e_1( 2.0*std::cos(p[0]*6.0), 1.0, 0.0 ); e_1.normalize();\n\t\tOpenVolumeMesh::Geometry::Vec3d e_2(0.0, 1.0, 0.0);\n\t\te_2 = OpenVolumeMesh::Geometry::cross(e_1, e_2); e_2.normalize();\n\t\tOpenVolumeMesh::Geometry::Vec3d e_3 = OpenVolumeMesh::Geometry::cross(e_1, e_2);\n\t\t\n\t\tR(0, 0) = e_1[0]; R(0, 1) = e_1[1]; R(0, 2) = e_1[2];\n\t\tR(1, 0) = e_2[0]; R(1, 1) = e_2[1]; R(1, 2) = e_2[2];\n\t\tR(2, 0) = e_3[0]; R(2, 1) = e_3[1]; R(2, 2) = e_3[2];\n\n\t\t//double R_det = R.determinant();\n\n\t\tEigen::Matrix3d D; D.setZero();\n\t\tD(0, 0) = 100;\n\t\tD(1, 1) = 1.0; D(2, 2) = 1.0;\n\t\tD *= 10;\n\t\tEigen::Matrix3d TM = R.transpose()* D * R;\n\n\t\tM[0] = TM(0, 0); M[1] = TM(0, 1); M[2] = TM(0, 2);\n\t\tM[3] = TM(1, 1); M[4] = TM(1, 2); M[5] = TM(2, 2);\n\n\t\t\n\n\t\tdouble D00 = 1000; double D11 = 10.0; double D22 = 10.0;\n\n\t\t/*M[0] = D00*e_1[0] * e_1[0] + D11*e_2[0] * e_2[0] + D22*e_3[0] * e_3[0];\n\t\tM[1] = e_1[0] * e_1[1] * D00 + e_2[0] * e_2[1] * D11 + e_3[0] * e_3[1] * D22;\n\t\tM[2] = e_1[0] * e_1[2] * D00 + e_2[0] * e_2[2] * D11 + e_3[0] * e_3[2] * D22;\n\t\tM[3] = D00*e_1[1] * e_1[1] + D11*e_2[1] * e_2[1] + D22*e_3[1] * e_3[1];\n\t\tM[4] = e_1[1] * e_1[2] * D00 + e_2[1] * e_2[2] * D11 + e_3[1] * e_3[2] * D22;\n\t\tM[5] = D00*e_1[2] * e_1[2] + D11*e_2[2] * e_2[2] + D22*e_3[2] * e_3[2];*/\n\n\t\tdouble M0 = D00*e_1[0] * e_1[0] + D11*e_2[0] * e_2[0] + D22*e_3[0] * e_3[0];\n\t\tdouble M1 = e_1[0] * e_1[1] * D00 + e_2[0] * e_2[1] * D11 + e_3[0] * e_3[1] * D22;\n\t\tdouble M2 = e_1[0] * e_1[2] * D00 + e_2[0] * e_2[2] * D11 + e_3[0] * e_3[2] * D22;\n\t\tdouble M3 = D00*e_1[1] * e_1[1] + D11*e_2[1] * e_2[1] + D22*e_3[1] * e_3[1];\n\t\tdouble M4 = e_1[1] * e_1[2] * D00 + e_2[1] * e_2[2] * D11 + e_3[1] * e_3[2] * D22;\n\t\tdouble M5 = D00*e_1[2] * e_1[2] + D11*e_2[2] * e_2[2] + D22*e_3[2] * e_3[2];\n\n\t\t/*M[0] = D00*e_1[0] * e_1[0] + D11*e_1[1] * e_1[1] + D22*e_1[2] * e_1[2];\n\t\tM[1] = e_1[0] * e_2[0] * D00 + e_1[1] * e_2[1] * D11 + e_1[2] * e_2[2] * D22;\n\t\tM[2] = e_1[0] * e_3[0] * D00 + e_1[1] * e_3[1] * D11 + e_1[2] * e_3[2] * D22;\n\t\tM[3] = D00*e_2[0] * e_2[0] + D11*e_2[1] * e_2[1] + D22*e_2[2] * e_2[2];\n\t\tM[4] = e_2[0] * e_3[0] * D00 + e_2[1] * e_3[1] * D11 + e_2[2] * e_3[2] * D22;\n\t\tM[5] = D00*e_3[0] * e_3[0] + D11*e_3[1] * e_3[1] + D22*e_3[2] * e_3[2];*/\n\t}\n\n\tif(Utility_Definition::T_SINK == m_tensor_name)\n\t{\n\t\tEigen::Matrix3d R;\n\t\tdouble r = std::sqrt(p[0]*p[0] + p[1]*p[1]);\n\t\tR(0,0) =  p[0]/r; R(0,1) = p[1]/r; R(0,2) = 0;\n\t\tR(1,0) = -p[1]/r; R(1,1) = p[0]/r; R(1,2) = 0;\n\t\tR(2,0) = 0; R(2,1) = 0; R(2,2) = 1;\n\n\t\tEigen::Matrix3d D; D.setZero();\n\t\tD(0,0) = 1.0;\n\t\tD(1,1) = 1.0 + r*5;\n\t\tD(2,2) = 1.0 + r*5;\n\t\tD *= 1.2/(0.5 + 1 - std::exp(-0.05*(r*r - 2.56)) );\n\t\tEigen::Matrix3d TM = R.transpose() *D * D * R ;\n\n\t\tM[0] = TM(0,0); M[1] = TM(0,1); M[2] = TM(0,2);\n\t\tM[3] = TM(1,1); M[4] = TM(1,2); M[5] = TM(2,2);\n\t}\n\n\tif(Utility_Definition::T_TEST == m_tensor_name)\n\t{\n\t\tdouble t = 4;\n\t\tEigen::Matrix3d R;\n\t\tdouble r = p.norm();\n\t\tOpenVolumeMesh::Geometry::Vec3d e_r = p / r;\n\t\tlocal_frame lf; lf.n = e_r; lf.find_e_x_y();\n\t\tR(0,0) =    e_r[0]; R(0,1) =    e_r[1]; R(0,2) =    e_r[2];\n\t\tR(1,0) = lf.e_y[0]; R(1,1) = lf.e_y[1]; R(1,2) = lf.e_y[2];\n\t\tR(2,0) = lf.e_x[0]; R(2,1) = lf.e_x[1]; R(2,2) = lf.e_x[2];\n\n\t\tEigen::Matrix3d D; D.setZero();\n\t\tD(0,0) = 1.0/( 0.05 + 1.0 * (1.0 - std::exp( -0.01*std::abs(r*r - t*t) ) ) );\n\t\tD(1,1) = 1; D(2,2) = 1;\n\t\tD *= 1.25;\n\t\tEigen::Matrix3d TM = R.transpose() *D * D * R ;\n\n\t\tM[0] = TM(0,0); M[1] = TM(0,1); M[2] = TM(0,2);\n\t\tM[3] = TM(1,1); M[4] = TM(1,2); M[5] = TM(2,2);\n\t}\n}\n\nvoid defined_tensor::build_AABB_Tree_using_ref_mesh(SurfaceMesh* mesh_)\n{\n\tif(AABB_Tree) {delete AABB_Tree; AABB_Tree = NULL;}\n\n\tunsigned nf = mesh_->n_faces();\n\tif (nf == 0) return;\n\topp_face_id.resize(nf); face_pos.resize(nf);\n\tstd::vector<int> one_face_opp_face_id(3); std::vector<OpenVolumeMesh::Geometry::Vec3d> one_face_pos(3);\n\tvisited_ref_face_id.resize(nf, -1); visited_ref_face.resize(nf, -1);\n\n\tstd::vector<CGAL_double_3_Point> v_pos( mesh_->n_vertices() ); OpenMesh::Vec3d p;\n\tfor(SurfaceMesh::VertexIter v_it = mesh_->vertices_begin(); v_it != mesh_->vertices_end(); ++v_it)\n\t{\n\t\tint vertex_id = v_it.handle().idx();\n\t\tp = mesh_->point( v_it );\n\t\tv_pos[vertex_id] = CGAL_double_3_Point( p[0], p[1], p[2] );\n\t}\n\n\ttriangle_vectors.clear();\n\ttriangle_vectors.resize(nf); int fv_id[3];\n\tfor(SurfaceMesh::FaceIter f_it = mesh_->faces_begin(); f_it != mesh_->faces_end(); ++f_it)\n\t{\n\t\tSurfaceMesh::FaceVertexIter fv_it = mesh_->fv_iter(f_it);\n\t\tfv_id[0] = fv_it.handle().idx(); ++fv_it;\n\t\tfv_id[1] = fv_it.handle().idx(); ++fv_it;\n\t\tfv_id[2] = fv_it.handle().idx(); ++fv_it;\n\t\tone_face_pos[0] = OpenVolumeMesh::Geometry::Vec3d(v_pos[fv_id[0]].x(), v_pos[fv_id[0]].y(), v_pos[fv_id[0]].z());\n\t\tone_face_pos[1] = OpenVolumeMesh::Geometry::Vec3d(v_pos[fv_id[1]].x(), v_pos[fv_id[1]].y(), v_pos[fv_id[1]].z());\n\t\tone_face_pos[2] = OpenVolumeMesh::Geometry::Vec3d(v_pos[fv_id[2]].x(), v_pos[fv_id[2]].y(), v_pos[fv_id[2]].z());\n\t\tface_pos[f_it.handle().idx()] = one_face_pos;\n\t\tSurfaceMesh::FaceHalfedgeIter fhe_it = mesh_->fh_iter(f_it);\n\t\tone_face_opp_face_id[0] = mesh_->face_handle(mesh_->opposite_halfedge_handle(fhe_it)).idx();\n\t\t++fhe_it; one_face_opp_face_id[1] = mesh_->face_handle(mesh_->opposite_halfedge_handle(fhe_it)).idx();\n\t\t++fhe_it; one_face_opp_face_id[2] = mesh_->face_handle(mesh_->opposite_halfedge_handle(fhe_it)).idx();\n\t\topp_face_id[f_it.handle().idx()] = one_face_opp_face_id;\n\n\t\ttriangle_vectors[f_it.handle().idx()] = CGAL_3_Triangle(v_pos[fv_id[0]], v_pos[fv_id[1]], v_pos[fv_id[2]]);\n\n\t\tif (fv_it)\n\t\t{\n\t\t\tfv_id[1] = fv_id[2];\n\t\t\tfv_id[2] = fv_it.handle().idx();\n\t\t\ttriangle_vectors.push_back(CGAL_3_Triangle(v_pos[fv_id[0]], v_pos[fv_id[1]], v_pos[fv_id[2]]));\n\t\t}\n\t}\n\tAABB_Tree = new CGAL_AABB_Tree(triangle_vectors.begin(), triangle_vectors.end());\n\tAABB_Tree->accelerate_distance_queries();\n\n\tprintf(\"Finish Constructing AABB Tree.\\n\");\n}\n\nvoid defined_tensor::build_AABB_Tree_using_ref_mesh(VolumeMesh* mesh_)\n{\n\tif (AABB_Tree) { delete AABB_Tree; AABB_Tree = NULL; }\n\ttriangle_vectors.clear();\n\tfor (OpenVolumeMesh::FaceIter f_it = mesh_->faces_begin(); f_it != mesh_->faces_end(); ++f_it)\n\t{\n\t\tif (!mesh_->is_boundary(*f_it)) continue;\n\n\t\tOpenVolumeMesh::HalfFaceHandle hfHandle = mesh_->halfface_handle(*f_it, 0);\n\t\tOpenVolumeMesh::HalfFaceHandle hfHandle2 = mesh_->halfface_handle(*f_it, 1);\n\t\tint cell_id = mesh_->incident_cell(hfHandle2).idx();\n\t\tif (cell_id < 0)\n\t\t{\n\t\t\thfHandle2 = hfHandle;\n\t\t\tcell_id = mesh_->incident_cell(hfHandle2).idx();\n\t\t\thfHandle = mesh_->halfface_handle(*f_it, 1);\n\t\t}\n\n\t\tOpenVolumeMesh::HalfFaceVertexIter hfv_it = mesh_->hfv_iter(hfHandle);\n\t\tOpenVolumeMesh::Geometry::Vec3d p0 = mesh_->vertex(*hfv_it);\n\t\t++hfv_it; OpenVolumeMesh::Geometry::Vec3d p1 = mesh_->vertex(*hfv_it);\n\t\t++hfv_it; OpenVolumeMesh::Geometry::Vec3d p2 = mesh_->vertex(*hfv_it);\n\t\t\n\t\tCGAL_double_3_Point q0(p0[0], p0[1], p0[2]);\n\t\tCGAL_double_3_Point q1(p1[0], p1[1], p1[2]);\n\t\tCGAL_double_3_Point q2(p2[0], p2[1], p2[2]);\n\n\t\ttriangle_vectors.push_back( CGAL_3_Triangle(q0, q1, q2) );\n\t}\n\n\tAABB_Tree = new CGAL_AABB_Tree(triangle_vectors.begin(), triangle_vectors.end());\n\tAABB_Tree->accelerate_distance_queries();\n\n\tprintf(\"Finish Constructing AABB Tree.\\n\");\n}\n\nvoid defined_tensor::build_AABB_Segment_Tree_using_ref_mesh(VolumeMesh* mesh_, const std::vector<int>& edge_feature)\n{\n\tif(AABB_Segment_Tree) {delete AABB_Segment_Tree; AABB_Segment_Tree = NULL;}\n\tif(mesh_->n_edges() == 0) return;\n\n\tstd::vector<CGAL_3_Segment> segment_vectors;\n\tfor(unsigned i=0;i<edge_feature.size();++i)\n\t{\n\t\tif(edge_feature[i] == 1)\n\t\t{\n\t\t\tOpenVolumeMesh::EdgeHandle eh(i);\n\t\t\tOpenVolumeMesh::OpenVolumeMeshEdge edge = mesh_->edge(eh);\n\t\t\tOpenVolumeMesh::VertexHandle vh_from = edge.from_vertex();\n\t\t\tOpenVolumeMesh::VertexHandle vh_to = edge.to_vertex();\n\t\t\tOpenVolumeMesh::Geometry::Vec3d p_from = mesh_->vertex(vh_from);\n\t\t\tOpenVolumeMesh::Geometry::Vec3d p_to = mesh_->vertex(vh_to);\n\t\t\tCGAL_double_3_Point pf(p_from[0], p_from[1], p_from[2]);\n\t\t\tCGAL_double_3_Point pt(p_to[0], p_to[1], p_to[2]);\n\t\t\tsegment_vectors.push_back( CGAL_3_Segment(pf, pt) );\n\t\t}\n\t}\n\tAABB_Segment_Tree = new CGAL_AABB_Segment_Tree(segment_vectors.begin(), segment_vectors.end());\n\tAABB_Segment_Tree->accelerate_distance_queries();\n\tprintf(\"Finish Constructing AABB Segment Tree.\\n\");\n}\n\nvoid defined_tensor::project_on_ref_mesh(OpenVolumeMesh::Geometry::Vec3d& p)\n{\n\tCGAL_double_3_Point pos = AABB_Tree->closest_point( CGAL_double_3_Point(p[0], p[1], p[2]) );\n\tp = OpenVolumeMesh::Geometry::Vec3d( pos.x(), pos.y(), pos.z() );\n}\n\n//if input face id = -1, will change face_id , p\nvoid defined_tensor::project_on_ref_mesh_with_guess_face(OpenVolumeMesh::Geometry::Vec3d& p, int& guess_face_id, const double& radius)\n{\n\tif (guess_face_id == -1)\n\t{\n\t\tCGAL_AABB_Tree::Point_and_primitive_id point_primitive = AABB_Tree->closest_point_and_primitive(CGAL_double_3_Point(p[0], p[1], p[2]));\n\t\tCGAL_double_3_Point pos = point_primitive.first;\n\t\tCGAL_Triangle_Iterator it = point_primitive.second;\n\t\tguess_face_id = std::distance(triangle_vectors.begin(), it);\n\t\tp = OpenVolumeMesh::Geometry::Vec3d(pos.x(), pos.y(), pos.z());\n\t}\n\telse\n\t{\n\t\tint visited_face_count = 0; double* p_data = p.data();\n\t\tvisited_ref_face_id[0] = guess_face_id; visited_ref_face[guess_face_id] = 1; ++visited_face_count;\n\t\tOpenVolumeMesh::Geometry::Vec3d np; OpenVolumeMesh::Geometry::Vec3d np_; double min_d = 1.0e30; int min_face_id = guess_face_id;\n\t\tdouble distance_th = 25.0*radius; int current_face_count = 0;\n\t\twhile (current_face_count < visited_face_count)\n\t\t{\n\t\t\t//int face_id = Q.front(); Q.pop();\n\t\t\tint face_id = visited_ref_face_id[current_face_count]; ++current_face_count;\n\t\t\tstd::vector<OpenVolumeMesh::Geometry::Vec3d>& one_face_pos = face_pos[face_id];\n\t\t\t//double d = distPointTriangleSquared(p, one_face_pos[0], one_face_pos[1], one_face_pos[2], np);\n\t\t\tdouble d = distPointTriangleSquared2(p_data, one_face_pos[0].data(), one_face_pos[1].data(), one_face_pos[2].data(), np.data());\n\t\t\tif (d < min_d) { min_d = d; min_face_id = face_id; np_ = np; }\n\n\t\t\tstd::vector<int>& one_face_opp_face_id = opp_face_id[face_id];\n\t\t\tfor (unsigned i = 0; i < 3; ++i)\n\t\t\t{\n\t\t\t\tif (one_face_opp_face_id[i] >= 0 && visited_ref_face[one_face_opp_face_id[i]] == -1)\n\t\t\t\t{\n\t\t\t\t\tstd::vector<OpenVolumeMesh::Geometry::Vec3d>& opp_face_pos = face_pos[one_face_opp_face_id[i]];\n\t\t\t\t\tOpenVolumeMesh::Geometry::Vec3d& opp_face_pos1 = opp_face_pos[0];\n\t\t\t\t\tdouble d1 = (p[0] - opp_face_pos1[0])*(p[0] - opp_face_pos1[0]) + (p[1] - opp_face_pos1[1])*(p[1] - opp_face_pos1[1]) + (p[2] - opp_face_pos1[2])*(p[2] - opp_face_pos1[2]);\n\t\t\t\t\tif (d1 < distance_th)\n\t\t\t\t\t{\n\t\t\t\t\t\tvisited_ref_face_id[visited_face_count] = one_face_opp_face_id[i];\n\t\t\t\t\t\tvisited_ref_face[one_face_opp_face_id[i]] = 1;\n\t\t\t\t\t\t++visited_face_count;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tOpenVolumeMesh::Geometry::Vec3d& opp_face_pos2 = opp_face_pos[1];\n\t\t\t\t\t\tdouble d2 = (p[0] - opp_face_pos2[0])*(p[0] - opp_face_pos2[0]) + (p[1] - opp_face_pos2[1])*(p[1] - opp_face_pos2[1]) + (p[2] - opp_face_pos2[2])*(p[2] - opp_face_pos2[2]);\n\t\t\t\t\t\tif (d2 < distance_th)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tvisited_ref_face_id[visited_face_count] = one_face_opp_face_id[i];\n\t\t\t\t\t\t\tvisited_ref_face[one_face_opp_face_id[i]] = 1;\n\t\t\t\t\t\t\t++visited_face_count;\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\tOpenVolumeMesh::Geometry::Vec3d& opp_face_pos3 = opp_face_pos[2];\n\t\t\t\t\t\t\tdouble d3 = (p[0] - opp_face_pos3[0])*(p[0] - opp_face_pos3[0]) + (p[1] - opp_face_pos3[1])*(p[1] - opp_face_pos3[1]) + (p[2] - opp_face_pos3[2])*(p[2] - opp_face_pos3[2]);\n\t\t\t\t\t\t\tif (d3 < distance_th)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tvisited_ref_face_id[visited_face_count] = one_face_opp_face_id[i];\n\t\t\t\t\t\t\t\tvisited_ref_face[one_face_opp_face_id[i]] = 1;\n\t\t\t\t\t\t\t\t++visited_face_count;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor (unsigned i = 0; i < visited_face_count; ++i)\n\t\t{\n\t\t\tvisited_ref_face[visited_ref_face_id[i]] = -1;\n\t\t}\n\n\t\tguess_face_id = min_face_id;\n\t\tp = np_;\n\t}\n\t\n}\n\nvoid defined_tensor::project_on_ref_mesh_with_metric(OpenVolumeMesh::Geometry::Vec3d& p, OpenVolumeMesh::Geometry::Vec6d& M)\n{\n\tCGAL_AABB_Tree::Point_and_primitive_id point_primitive = AABB_Tree->closest_point_and_primitive( CGAL_double_3_Point(p[0], p[1], p[2]) );\n\tCGAL_double_3_Point pos = point_primitive.first;\n\tCGAL_Triangle_Iterator it = point_primitive.second;\n\tunsigned face_id = std::distance( triangle_vectors.begin(), it);\n\tp = OpenVolumeMesh::Geometry::Vec3d( pos.x(), pos.y(), pos.z() );\n\n\t//printf(\"F : %d\\n\", face_id);\n\n\tOpenMesh::Vec3d p_(p[0], p[1], p[2]);\n\tSurfaceMesh::ConstFaceVertexIter fv_it = bm->cfv_iter( bm->face_handle(face_id) );\n\tOpenMesh::Vec3d p0 = bm->point(fv_it.handle()); int v0_id = fv_it.handle().idx();\n\t++fv_it; OpenMesh::Vec3d p1 = bm->point(fv_it.handle()); int v1_id = fv_it.handle().idx();\n\t++fv_it; OpenMesh::Vec3d p2 = bm->point(fv_it.handle()); int v2_id = fv_it.handle().idx();\n\n\tOpenMesh::Vec3d bc;\n\tif (!baryCoord(p_, p0, p1, p2, bc))\n\t\tbc[0] = bc[1] = bc[2] = 1.0/3.0;\n\n\tM = bc[0] *bm_metric[v0_id] + bc[1] *bm_metric[v1_id] + bc[2] *bm_metric[v2_id];\n}\n\nvoid defined_tensor::project_on_ref_edge(OpenVolumeMesh::Geometry::Vec3d& p)\n{\n\tCGAL_double_3_Point pos = AABB_Segment_Tree->closest_point( CGAL_double_3_Point(p[0], p[1], p[2]) );\n\tp = OpenVolumeMesh::Geometry::Vec3d( pos.x(), pos.y(), pos.z() );\n}\n\nvoid defined_tensor::construct_boundary_mesh()\n{\n\tOpenVolumeMesh::BoundaryFaceIter bf_it(ref_mesh_->bf_iter());\n\tOpenVolumeMesh::HalfFaceVertexIter hfv_it = ref_mesh_->hfv_iter( ref_mesh_->halfface_handle(*bf_it,0) );\n\n\tstd::vector<SurfaceMesh::VertexHandle> vertexHandleVec;\n\tstd::vector<SurfaceMesh::VertexHandle> faceVertexHandle;\n\tstd::map<int,int> VolumeSurfaceVertex;\n\tstd::map<int,int>::iterator map_it;\n\tint indexOnSurface = 0;\n\tint InvalidHF =0;\n\tbm->clear();\n\tfor (; bf_it.valid(); ++bf_it)\n\t{\n\t\tOpenVolumeMesh::HalfFaceHandle hfHandle = ref_mesh_->halfface_handle(*bf_it,0);\n\t\tOpenVolumeMesh::HalfFaceHandle hfHandle2 = ref_mesh_->halfface_handle(*bf_it,1);\n\t\tint cell_id = ref_mesh_->incident_cell(hfHandle2).idx();\n\t\tif( cell_id >= 0 )\n\t\t{\n\t\t\thfHandle2 = hfHandle;\n\t\t\tcell_id = ref_mesh_->incident_cell(hfHandle2).idx();\n\t\t\thfHandle = ref_mesh_->halfface_handle(*bf_it,1);\n\t\t}\n\t\t++InvalidHF;\n\t\thfv_it = ref_mesh_->hfv_iter( hfHandle );\n\t\tfaceVertexHandle.clear();\n\t\tfor( hfv_it; hfv_it.valid(); ++hfv_it)\n\t\t{\n\t\t\tmap_it = VolumeSurfaceVertex.find(hfv_it->idx()) ;\n\t\t\tif( map_it == VolumeSurfaceVertex.end() )\n\t\t\t{\n\t\t\t\tVolumeSurfaceVertex.insert(std::pair<int,int>( hfv_it->idx(), indexOnSurface ));\n\t\t\t\tOpenVolumeMesh::Geometry::Vec3d v1 = ref_mesh_->vertex(*hfv_it);\n\t\t\t\tSurfaceMesh::Point v2( v1[0], v1[1], v1[2] );\n\t\t\t\tvertexHandleVec.push_back( bm->add_vertex( v2 ) );\n\t\t\t\tbm->data(vertexHandleVec.back()).set_tet_vertex_id(hfv_it->idx());\n\t\t\t\tfaceVertexHandle.push_back( vertexHandleVec.back() );\n\t\t\t\t++indexOnSurface;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tfaceVertexHandle.push_back(vertexHandleVec[map_it->second]);\n\t\t\t}\n\t\t}\n\n\t\tstd::reverse(faceVertexHandle.begin(), faceVertexHandle.end());\n\t\tOpenMesh::FaceHandle fh = bm->add_face(faceVertexHandle);\n\t\tbm->data(fh).set_cell_id( cell_id );\n\t}\n\n\tbm->update_normals();\n}\n\nvoid defined_tensor::save_boundary_mesh_metric()\n{\n\tFILE* f_b_m = fopen(\"A:\\\\Code\\\\VolumeMeshProcessing\\\\Models\\\\Tetrahedrization\\\\elphant\\\\boundary.off\", \"w\");\n\tunsigned nv = bm->n_vertices(); unsigned nf = bm->n_faces();\n\tfprintf(f_b_m, \"OFF\");\n\tfprintf(f_b_m, \"\\n%d %d 0\", nv, nf);\n\tfor(SurfaceMesh::VertexIter v_it = bm->vertices_begin(); v_it != bm->vertices_end(); ++v_it)\n\t{\n\t\tOpenMesh::Vec3d p = bm->point(v_it);\n\t\tfprintf(f_b_m, \"\\n%20.19f %20.19f %20.19f\", p[0], p[1], p[2]);\n\t}\n\tfor(SurfaceMesh::FaceIter f_it = bm->faces_begin(); f_it != bm->faces_end(); ++f_it)\n\t{\n\t\tfprintf(f_b_m, \"\\n3\");\n\t\tfor( SurfaceMesh::FaceVertexIter fv_it = bm->fv_iter(f_it); fv_it; ++fv_it )\n\t\t{\n\t\t\tfprintf(f_b_m, \" %d\", fv_it.handle().idx());\n\t\t}\n\t}\n\tfor(unsigned i=0;i<bm_metric.size();++i)\n\t{\n\t\tfprintf(f_b_m, \"\\n%20.19f %20.19f %20.19f %20.19f %20.19f %20.19f\", bm_metric[i][0],bm_metric[i][1],bm_metric[i][2],bm_metric[i][3],bm_metric[i][4],bm_metric[i][5]);\n\t}\n\n\tfclose(f_b_m);\n}\n\nvoid defined_tensor::smmoth_metric_to_interior(VolumeMesh* mesh_)\n{\n\tif(ref_mesh_) delete ref_mesh_;\n\tref_mesh_ = mesh_;\n\n\tif(bm) delete bm;\n\tbm = new SurfaceMesh();\n\tbm->request_face_status();\n\tbm->request_vertex_status();\n\tbm->request_edge_status();\n\tbm->request_face_normals();\n\tbm->request_vertex_normals();\n\n\tconstruct_boundary_mesh();\n\t//printf(\"1\\n\");\n\n\tstd::vector<double> k1, k2; std::vector<OpenMesh::Vec3d> d1, d2;\n\tcompute_principal_curvature(bm,k1,k2,d1,d2); bm_metric.resize(k1.size());\n\ttet_vertex_metric.clear(); unsigned tet_nv = mesh_->n_vertices(); tet_vertex_metric.resize(tet_nv);\n\tstd::vector<int> tet_vertex_flag(tet_nv, -1); std::vector<int> new_one_ring_vertex(tet_nv, -1); int new_one_ring_vertex_count = 0;\n\tEigen::Matrix3d R, D, M; D.setZero();\n\t//printf(\"2 %d %d %d\\n\", k1.size(), bm->n_vertices(), tet_nv);\n\tfor(unsigned i=0;i<k1.size();++i)\n\t{\n\t\tSurfaceMesh::VertexHandle vh = bm->vertex_handle(i);\n\t\tint tet_v_id = bm->data(vh).get_tet_vertex_id();\n\t\t//printf(\"%d\\n\", tet_v_id);\n\t\t//use curvature to construct metric\n\t\tOpenMesh::Vec3d n = OpenMesh::cross(d1[i], d2[i]); n.normalize();\n\t\tR(0,0) = d1[i][0]; R(1,0) = d1[i][1]; R(2,0) = d1[i][2];\n\t\tR(0,1) = d2[i][0]; R(1,1) = d2[i][1]; R(2,1) = d2[i][2];\n\t\tR(0,2) =     n[0]; R(1,2) =     n[1]; R(2,2) =     n[2];\n\t\tD(0,0) = std::abs(k1[i]) < 1.0e-4 ? 1.0e-4 : std::abs(k1[i]);\n\t\tD(1,1) = std::abs(k2[i]) < 1.0e-4 ? 1.0e-4 : std::abs(k2[i]);\n\t\tdouble max_k = std::abs(k1[i]) > std::abs(k2[i]) ? std::abs(k1[i]) : std::abs(k2[i]);\n\t\tD(2,2) = max_k < 1e-4 ? 1e-4 : max_k;\n\t\t//D(2,2) = 0.0;\n\t\tM = R*D*R.transpose();\n\t\ttet_vertex_metric[tet_v_id] = OpenVolumeMesh::Geometry::Vec6d(M(0,0), M(0,1), M(0,2), M(1,1), M(1,2), M(2,2));\n\t\tbm_metric[i] = tet_vertex_metric[tet_v_id];\n\t\ttet_vertex_flag[tet_v_id] = 1; OpenVolumeMesh::VertexHandle tet_vh(tet_v_id);\n\t\tfor(OpenVolumeMesh::VertexOHalfEdgeIter voh_it = mesh_->voh_iter(tet_vh); voh_it; ++voh_it)\n\t\t{\n\t\t\tOpenVolumeMesh::OpenVolumeMeshEdge edge = mesh_->edge( mesh_->edge_handle(*voh_it) );\n\t\t\tOpenVolumeMesh::VertexHandle f_vh = edge.from_vertex();\n\t\t\tOpenVolumeMesh::VertexHandle t_vh = edge.to_vertex();\n\t\t\tif(f_vh != tet_vh && !mesh_->is_boundary(f_vh))\n\t\t\t{\n\t\t\t\tnew_one_ring_vertex[f_vh.idx()] = 1; ++new_one_ring_vertex_count;\n\t\t\t}\n\t\t\telse if(t_vh != tet_vh && !mesh_->is_boundary(t_vh))\n\t\t\t{\n\t\t\t\tnew_one_ring_vertex[t_vh.idx()] = 1; ++new_one_ring_vertex_count;\n\t\t\t}\n\t\t}\n\t}\n\n\t//printf(\"3,1\\n\");\n\n\tsave_boundary_mesh_metric();\n\n\t//printf(\"3,2\\n\");\n\n\t//init value\n\twhile(new_one_ring_vertex_count > 0)\n\t{\n\t\tstd::vector<int> old_v; old_v.reserve(new_one_ring_vertex_count);\n\t\tfor(unsigned i=0;i<new_one_ring_vertex.size();++i)\n\t\t{\n\t\t\tif(new_one_ring_vertex[i] == 1)\n\t\t\t{\n\t\t\t\told_v.push_back(i); OpenVolumeMesh::VertexHandle tet_vh(i);\n\t\t\t\tOpenVolumeMesh::Geometry::Vec6d ave_M(0,0,0,0,0,0); double sum_count = 0.0;\n\t\t\t\tfor(OpenVolumeMesh::VertexOHalfEdgeIter voh_it = mesh_->voh_iter(tet_vh); voh_it; ++voh_it)\n\t\t\t\t{\n\t\t\t\t\tOpenVolumeMesh::OpenVolumeMeshEdge edge = mesh_->edge( mesh_->edge_handle(*voh_it) );\n\t\t\t\t\tOpenVolumeMesh::VertexHandle f_vh = edge.from_vertex();\n\t\t\t\t\tOpenVolumeMesh::VertexHandle t_vh = edge.to_vertex();\n\t\t\t\t\tif(f_vh != tet_vh)\n\t\t\t\t\t{\n\t\t\t\t\t\tif(tet_vertex_flag[f_vh.idx()] == 1)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tave_M += tet_vertex_metric[f_vh.idx()]; sum_count += 1.0;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if(t_vh != tet_vh)\n\t\t\t\t\t{\n\t\t\t\t\t\tif(tet_vertex_flag[t_vh.idx()] == 1)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tave_M += tet_vertex_metric[t_vh.idx()]; sum_count += 1.0;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tave_M /= sum_count;\n\t\t\t\ttet_vertex_metric[i] = ave_M;\n\t\t\t}\n\t\t}\n\n\t\tfor(unsigned i=0;i<old_v.size();++i)\n\t\t{\n\t\t\ttet_vertex_flag[old_v[i]] = 1; new_one_ring_vertex[old_v[i]] = -1;\n\t\t}\n\n\t\tnew_one_ring_vertex_count = 0;\n\t\tfor(unsigned i=0;i<old_v.size();++i)\n\t\t{\n\t\t\tOpenVolumeMesh::VertexHandle tet_vh(old_v[i]);\n\t\t\tfor(OpenVolumeMesh::VertexOHalfEdgeIter voh_it = mesh_->voh_iter(tet_vh); voh_it; ++voh_it)\n\t\t\t{\n\t\t\t\tOpenVolumeMesh::OpenVolumeMeshEdge edge = mesh_->edge( mesh_->edge_handle(*voh_it) );\n\t\t\t\tOpenVolumeMesh::VertexHandle f_vh = edge.from_vertex();\n\t\t\t\tOpenVolumeMesh::VertexHandle t_vh = edge.to_vertex();\n\t\t\t\tif(f_vh != tet_vh && tet_vertex_flag[f_vh.idx()] == -1)\n\t\t\t\t{\n\t\t\t\t\tnew_one_ring_vertex[f_vh.idx()] = 1; ++new_one_ring_vertex_count;\n\t\t\t\t}\n\t\t\t\telse if(t_vh != tet_vh && tet_vertex_flag[t_vh.idx()] == -1)\n\t\t\t\t{\n\t\t\t\t\tnew_one_ring_vertex[t_vh.idx()] = 1; ++new_one_ring_vertex_count;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\t//printf(\"4\\n\");\n\t//smooth\n\tfor(unsigned i=0;i<50;++i)\n\t{\n\t\tprintf(\"%d \", i);\n\t\tfor(OpenVolumeMesh::VertexIter v_it = mesh_->vertices_begin(); v_it != mesh_->vertices_end(); ++v_it)\n\t\t{\n\t\t\tif(mesh_->is_boundary(*v_it)) continue;\n\t\t\tOpenVolumeMesh::Geometry::Vec6d ave_M(0,0,0,0,0,0); double sum_count = 0.0;\n\t\t\tfor(OpenVolumeMesh::VertexOHalfEdgeIter voh_it = mesh_->voh_iter(*v_it); voh_it; ++voh_it)\n\t\t\t{\n\t\t\t\tOpenVolumeMesh::OpenVolumeMeshEdge edge = mesh_->edge( mesh_->edge_handle(*voh_it) );\n\t\t\t\tOpenVolumeMesh::VertexHandle f_vh = edge.from_vertex();\n\t\t\t\tOpenVolumeMesh::VertexHandle t_vh = edge.to_vertex();\n\t\t\t\tif( f_vh != *v_it )\n\t\t\t\t{\n\t\t\t\t\tave_M += tet_vertex_metric[f_vh.idx()]; sum_count += 1.0;\n\t\t\t\t}\n\t\t\t\telse if( t_vh != *v_it )\n\t\t\t\t{\n\t\t\t\t\tave_M += tet_vertex_metric[t_vh.idx()]; sum_count += 1.0;\n\t\t\t\t}\n\t\t\t}\n\t\t\tave_M /= sum_count;\n\t\t\ttet_vertex_metric[v_it->idx()] = ave_M;\n\t\t}\n\t}\n\tprintf(\"\\n\");\n}\n\nvoid defined_tensor::save_tet_vertex_metric(const char* filename)\n{\n\tFILE* f_v_m = fopen(filename, \"w\");\n\n\tfprintf(f_v_m, \"%d\", tet_vertex_metric.size());\n\tfor(unsigned i=0;i<tet_vertex_metric.size();++i)\n\t{\n\t\tfprintf(f_v_m, \"\\n%20.19f %20.19f %20.19f %20.19f %20.19f %20.19f\", tet_vertex_metric[i][0],tet_vertex_metric[i][1],tet_vertex_metric[i][2],tet_vertex_metric[i][3],tet_vertex_metric[i][4],tet_vertex_metric[i][5] );\n\t}\n\n\tfclose(f_v_m);\n}\n\nvoid defined_tensor::load_tet_vertex_metric(const char* filename)\n{\n\tFILE* f_v_m = fopen(filename, \"r\");\n\tint nv = 0;\n\tchar buf[4096];  fgets(buf, 4096, f_v_m);\n\tsscanf(buf, \"%d\", &nv); tet_vertex_metric.clear(); tet_vertex_metric.resize(nv); int v_count = 0;\n\tchar h0[128]; char h1[128]; char h2[128]; char h4[128]; char h5[128]; char h8[128];\n\twhile ( !feof(f_v_m) )\n\t{\n\t\tfgets(buf, 4096, f_v_m);\n\t\tsscanf(buf, \"%s %s %s %s %s %s\", h0, h1, h2, h4, h5, h8);\n\t\ttet_vertex_metric[v_count] = OpenVolumeMesh::Geometry::Vec6d(atof(h0), atof(h1),atof(h2), atof(h4), atof(h5), atof(h8));\n\t\t++v_count;\n\t}\n\n\tfclose(f_v_m);\n}\n\nvoid defined_tensor::load_ref_tet_mesh(VolumeMesh* mesh_)\n{\n\tif(tet_vertex_metric.size() == 0)\n\t{\n\t\tprintf(\"Please Load Metric First!!!\\n\");\n\t\treturn;\n\t}\n\tif(ref_mesh_) delete ref_mesh_;\n\tref_mesh_ = mesh_;\n\tif(bm) delete bm;\n\tbm = new SurfaceMesh();\n\tconstruct_boundary_mesh();\n\tbm_metric.resize(bm->n_vertices());\n\tfor(unsigned i=0;i<bm->n_vertices(); ++i)\n\t{\n\t\tSurfaceMesh::VertexHandle vh = bm->vertex_handle(i);\n\t\tint tet_v_id = bm->data(vh).get_tet_vertex_id();\n\t\tbm_metric[i] = tet_vertex_metric[tet_v_id];\n\t}\n\tbuild_AABB_Tree_using_ref_mesh(bm);\n\tbuild_ANN_KD_tree();\n}\n\nvoid defined_tensor::build_ANN_KD_tree()\n{\n\tint nc = ref_mesh_->n_cells();\n\tANNpointArray dataPts = annAllocPts(nc, 3);\n\tfor(OpenVolumeMesh::CellIter c_it = ref_mesh_->cells_begin(); c_it != ref_mesh_->cells_end();++c_it)\n\t{\n\t\tOpenVolumeMesh::Geometry::Vec3d c_c(0,0,0); double count = 0.0;\n\t\tfor(OpenVolumeMesh::CellVertexIter cv_it = ref_mesh_->cv_iter(*c_it); cv_it; ++cv_it )\n\t\t{\n\t\t\tc_c += ref_mesh_->vertex(*cv_it); count += 1.0;\n\t\t}\n\t\tc_c /= count;\n\t\tint c_id = c_it->idx();\n\t\tdataPts[c_id][0] = c_c[0]; dataPts[c_id][1] = c_c[1]; dataPts[c_id][2] = c_c[2];\n\t}\n\tif(kdTree) delete kdTree;\n\tkdTree = new ANNkd_tree(dataPts, nc, 3);\n}\n\nbool defined_tensor::check_in_tet(const OpenVolumeMesh::Geometry::Vec3d& p, const int& cel_id)\n{\n\tif(cel_id < 0) return false;\n\n\tOpenVolumeMesh::CellHandle ch(cel_id);\n\tOpenVolumeMesh::OpenVolumeMeshCell cell = ref_mesh_->cell(ch);\n\tstd::vector<OpenVolumeMesh::HalfFaceHandle> hfh_vec = cell.halffaces();\n\tfor(unsigned i=0;i<hfh_vec.size();++i)\n\t{\n\t\tOpenVolumeMesh::HalfFaceVertexIter hfv_it = ref_mesh_->hfv_iter(hfh_vec[i]);\n\t\tOpenVolumeMesh::Geometry::Vec3d p0 = ref_mesh_->vertex(*hfv_it);\n\t\t++hfv_it; OpenVolumeMesh::Geometry::Vec3d p1 = ref_mesh_->vertex(*hfv_it);\n\t\t++hfv_it; OpenVolumeMesh::Geometry::Vec3d p2 = ref_mesh_->vertex(*hfv_it);\n\n\t\tdouble v = OpenVolumeMesh::Geometry::dot(p-p0, OpenVolumeMesh::Geometry::cross(p1-p0,p2-p0));\n\t\tif(v < 0) return false;\n\t}\n\treturn true;\n}\n\nint defined_tensor::find_nearest_cell_id(const OpenVolumeMesh::Geometry::Vec3d& p)\n{\n\tANNpoint tp = annAllocPt(3); tp[0] = p[0]; tp[1] = p[1]; tp[2] = p[2];\n\tANNidxArray nnIdx = new ANNidx[1]; ANNdistArray dists = new ANNdist[1];\n\tkdTree->annkSearch(tp, 1, nnIdx, dists);\n\tint cell_id = nnIdx[0];\n\tdelete [] nnIdx;\n\n\tstd::vector<int> visited_cell_id(ref_mesh_->n_cells(), -1);\n\tvisited_cell_id[cell_id] = 1;\n\tstd::queue<int> Q; Q.push(cell_id);\n\twhile (Q.size() > 0)\n\t{\n\t\tcell_id = Q.front(); Q.pop();\n\t\tif( check_in_tet(p, cell_id) ) return cell_id;\n\t\tOpenVolumeMesh::CellHandle ch(cell_id);\n\t\tOpenVolumeMesh::OpenVolumeMeshCell cell = ref_mesh_->cell(ch);\n\t\tstd::vector<OpenVolumeMesh::HalfFaceHandle> hfh_vec = cell.halffaces();\n\t\tfor(unsigned i=0;i<hfh_vec.size();++i)\n\t\t{\n\t\t\tOpenVolumeMesh::HalfFaceHandle hfh = ref_mesh_->opposite_halfface_handle(hfh_vec[i]);\n\t\t\tOpenVolumeMesh::CellHandle t_ch = ref_mesh_->incident_cell(hfh);\n\t\t\tif(t_ch != VolumeMesh::InvalidCellHandle && visited_cell_id[t_ch.idx()] == -1)\n\t\t\t{\n\t\t\t\tQ.push( t_ch.idx() ); visited_cell_id[t_ch.idx()] = 1;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn -1;\n}\n\nvoid defined_tensor::find_cell_bay_cor(const OpenVolumeMesh::Geometry::Vec3d& p,const int& cell_id, \n\t\t\t\t\t\t\t\t\t   OpenVolumeMesh::Geometry::Vec4i& v_id, OpenVolumeMesh::Geometry::Vec4d& b)\n{\n\tOpenVolumeMesh::CellHandle ch(cell_id);\n\tOpenVolumeMesh::OpenVolumeMeshCell cell = ref_mesh_->cell(ch);\n\tstd::vector<OpenVolumeMesh::HalfFaceHandle> hfh_vec = cell.halffaces(); double sum_b= 0.0;\n\tfor(unsigned i=0;i<hfh_vec.size();++i)\n\t{\n\t\tOpenVolumeMesh::HalfFaceVertexIter hfv_it = ref_mesh_->hfv_iter(hfh_vec[i]);\n\t\tOpenVolumeMesh::Geometry::Vec3d p0 = ref_mesh_->vertex(*hfv_it); int v0 = hfv_it->idx();\n\t\t++hfv_it; OpenVolumeMesh::Geometry::Vec3d p1 = ref_mesh_->vertex(*hfv_it); int v1 = hfv_it->idx();\n\t\t++hfv_it; OpenVolumeMesh::Geometry::Vec3d p2 = ref_mesh_->vertex(*hfv_it); int v2 = hfv_it->idx();\n\n\t\tb[i] = OpenVolumeMesh::Geometry::dot(p - p0, OpenVolumeMesh::Geometry::cross(p1-p0,p2-p0));\n\t\tsum_b += b[i];\n\t\tunsigned j = (i+1) % hfh_vec.size();\n\t\tfor( hfv_it = ref_mesh_->hfv_iter(hfh_vec[j]); hfv_it; ++hfv_it)\n\t\t{\n\t\t\tif(hfv_it->idx() != v0 &&hfv_it->idx() != v1 &&hfv_it->idx() != v2 )\n\t\t\t{\n\t\t\t\tv_id[i] = hfv_it->idx();\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tb /= sum_b;\n}\n\nvoid defined_tensor::project_for_interior(OpenVolumeMesh::Geometry::Vec3d& p, OpenVolumeMesh::Geometry::Vec6d& M)\n{\n\t//printf(\"...........\\n\");\n\tint cell_id = find_nearest_cell_id(p);\n\tif(cell_id < 0) printf(\"%d\\n\", cell_id);\n\n\tOpenVolumeMesh::Geometry::Vec4i v_id; OpenVolumeMesh::Geometry::Vec4d b;\n\tfind_cell_bay_cor(p, cell_id, v_id, b);\n\tM = tet_vertex_metric[v_id[0]] * b[0] + tet_vertex_metric[v_id[1]] * b[1] + tet_vertex_metric[v_id[2]] * b[2] + tet_vertex_metric[v_id[3]] * b[3];\n}", "meta": {"hexsha": "b3c1b82491f3dcfb923624fce4af0bf48a52df16", "size": 31111, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ScissorPoly/Defined_Tensor.cpp", "max_stars_repo_name": "msraig/CE-PolyCube", "max_stars_repo_head_hexsha": "e46aff6e0594b711735118bfa902a91bc3d392ca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2020-08-13T05:15:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:51:29.000Z", "max_issues_repo_path": "ScissorPoly/Defined_Tensor.cpp", "max_issues_repo_name": "xh-liu-tech/CE-PolyCube", "max_issues_repo_head_hexsha": "86d4ed0023215307116b6b3245e2dbd82907cbb8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-09-08T07:03:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-04T05:43:27.000Z", "max_forks_repo_path": "ScissorPoly/Defined_Tensor.cpp", "max_forks_repo_name": "xh-liu-tech/CE-PolyCube", "max_forks_repo_head_hexsha": "86d4ed0023215307116b6b3245e2dbd82907cbb8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2020-08-06T02:37:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-01T09:12:06.000Z", "avg_line_length": 38.0795593635, "max_line_length": 216, "alphanum_fraction": 0.6388737103, "num_tokens": 12289, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.49177278516677153}}
{"text": "\n#include \"DataStructures.h\"\n#include \"IncompressibleFluid.h\"\n#include \"math.h\"\n#include \"MatrixMath.h\"\n#include \"PolyMath.h\"\n#include <Eigen/Core>\n\nnamespace CoolProp {\n\n\n\n/// A thermophysical property provider for all properties\n/**\nThis fluid instance is populated using an entry from a JSON file and uses\nsimplified polynomial and exponential functions to calculate thermophysical\nand transport properties.\n*/\n//IncompressibleFluid::IncompressibleFluid();\n\nvoid IncompressibleFluid::validate(){\n    return;\n    // TODO: Implement validation function\n\n    // u and s have to be of the polynomial type!\n    //throw NotImplementedError(\"TODO\");\n}\n\nbool IncompressibleFluid::is_pure() {\n    if (density.coeffs.cols()==1) return true;\n    return false;\n}\n\n/// Base exponential function\ndouble IncompressibleFluid::baseExponential(IncompressibleData data, double y, double ybase){\n    Eigen::VectorXd coeffs = makeVector(data.coeffs);\n    size_t r=coeffs.rows(),c=coeffs.cols();\n    if (strict && (r!=3 || c!=1) ) throw ValueError(format(\"%s (%d): You have to provide a 3,1 matrix of coefficients, not  (%d,%d).\",__FILE__,__LINE__,r,c));\n    return exp( (double) (coeffs[0] / ( (y-ybase)+coeffs[1] ) - coeffs[2] ) );\n}\n/// Base exponential function with logarithmic term\ndouble IncompressibleFluid::baseLogexponential(IncompressibleData data, double y, double ybase){\n    Eigen::VectorXd coeffs = makeVector(data.coeffs);\n    size_t r=coeffs.rows(),c=coeffs.cols();\n    if (strict && (r!=3 || c!=1) ) throw ValueError(format(\"%s (%d): You have to provide a 3,1 matrix of coefficients, not  (%d,%d).\",__FILE__,__LINE__,r,c));\n    return exp( (double) ( log( (double) (1.0/((y-ybase)+coeffs[0]) + 1.0/((y-ybase)+coeffs[0])/((y-ybase)+coeffs[0]) ) ) *coeffs[1]+coeffs[2] ) );\n}\n\ndouble IncompressibleFluid::basePolyOffset(IncompressibleData data, double y, double z){\n    size_t r=data.coeffs.rows(),c=data.coeffs.cols();\n    double offset = 0.0;\n    double in     = 0.0;\n    Eigen::MatrixXd coeffs;\n    if (r>0 && c>0) {\n        offset = data.coeffs(0,0);\n        if (r==1 && c>1) { // row vector -> function of z\n            coeffs = Eigen::MatrixXd(data.coeffs.block(0,1,r,c-1));\n            in = z;\n        } else if (r>1 && c==1) { // column vector -> function of y\n            coeffs = Eigen::MatrixXd(data.coeffs.block(1,0,r-1,c));\n            in = y;\n        } else {\n            throw ValueError(format(\"%s (%d): You have to provide a vector (1D matrix) of coefficients, not  (%d,%d).\",__FILE__,__LINE__,r,c));\n        }\n        return poly.evaluate(coeffs, in, 0, offset);\n    }\n    throw ValueError(format(\"%s (%d): You have to provide a vector (1D matrix) of coefficients, not  (%d,%d).\",__FILE__,__LINE__,r,c));\n}\n\n\n/// Density as a function of temperature, pressure and composition.\ndouble IncompressibleFluid::rho (double T, double p, double x){\n    switch (density.type) {\n        case IncompressibleData::INCOMPRESSIBLE_POLYNOMIAL:\n            return poly.evaluate(density.coeffs, T, x, 0, 0, Tbase, xbase);\n        case IncompressibleData::INCOMPRESSIBLE_EXPONENTIAL:\n            return baseExponential(density, T, 0.0);\n        case IncompressibleData::INCOMPRESSIBLE_LOGEXPONENTIAL:\n            return baseLogexponential(density, T, 0.0);\n        case IncompressibleData::INCOMPRESSIBLE_EXPPOLYNOMIAL:\n            return exp(poly.evaluate(density.coeffs, T, x, 0, 0, Tbase, xbase));\n        case IncompressibleData::INCOMPRESSIBLE_POLYOFFSET:\n            return basePolyOffset(density, T, x);\n        case IncompressibleData::INCOMPRESSIBLE_NOT_SET:\n            throw ValueError(format(\"%s (%d): The function type is not specified (\\\"[%d]\\\"), are you sure the coefficients have been set?\",__FILE__,__LINE__,density.type));\n        default:\n            throw ValueError(format(\"%s (%d): Your function type \\\"[%d]\\\" is unknown.\",__FILE__,__LINE__,density.type));\n    }\n}\n\n/// Heat capacities as a function of temperature, pressure and composition.\ndouble IncompressibleFluid::c   (double T, double p, double x){\n    switch (specific_heat.type) {\n        case IncompressibleData::INCOMPRESSIBLE_POLYNOMIAL:\n            //throw NotImplementedError(\"Here you should implement the polynomial.\");\n            return poly.evaluate(specific_heat.coeffs, T, x, 0, 0, Tbase, xbase);\n        case IncompressibleData::INCOMPRESSIBLE_NOT_SET:\n            throw ValueError(format(\"%s (%d): The function type is not specified (\\\"[%d]\\\"), are you sure the coefficients have been set?\",__FILE__,__LINE__,specific_heat.type));\n        default:\n            throw ValueError(format(\"%s (%d): There is no predefined way to use this function type \\\"[%d]\\\" for specific heat.\",__FILE__,__LINE__,specific_heat.type));\n    }\n}\n\n/// Viscosity as a function of temperature, pressure and composition.\ndouble IncompressibleFluid::visc(double T, double p, double x){\n    switch (viscosity.type) {\n        case IncompressibleData::INCOMPRESSIBLE_POLYNOMIAL:\n            return poly.evaluate(viscosity.coeffs, T, x, 0, 0, Tbase, xbase);\n        case IncompressibleData::INCOMPRESSIBLE_EXPONENTIAL:\n            return baseExponential(viscosity, T, 0.0);\n        case IncompressibleData::INCOMPRESSIBLE_LOGEXPONENTIAL:\n            return baseLogexponential(viscosity, T, 0.0);\n        case IncompressibleData::INCOMPRESSIBLE_EXPPOLYNOMIAL:\n            return exp(poly.evaluate(viscosity.coeffs, T, x, 0, 0, Tbase, xbase));\n        case IncompressibleData::INCOMPRESSIBLE_POLYOFFSET:\n            return basePolyOffset(viscosity, T, x);\n        case IncompressibleData::INCOMPRESSIBLE_NOT_SET:\n            throw ValueError(format(\"%s (%d): The function type is not specified (\\\"[%d]\\\"), are you sure the coefficients have been set?\",__FILE__,__LINE__,viscosity.type));\n        default:\n            throw ValueError(format(\"%s (%d): Your function type \\\"[%d]\\\" is unknown.\",__FILE__,__LINE__,viscosity.type));\n    }\n}\n/// Thermal conductivity as a function of temperature, pressure and composition.\ndouble IncompressibleFluid::cond(double T, double p, double x){\n    switch (conductivity.type) {\n        case IncompressibleData::INCOMPRESSIBLE_POLYNOMIAL:\n            return poly.evaluate(conductivity.coeffs, T, x, 0, 0, Tbase, xbase);\n        case IncompressibleData::INCOMPRESSIBLE_EXPONENTIAL:\n            return baseExponential(conductivity, T, 0.0);\n        case IncompressibleData::INCOMPRESSIBLE_LOGEXPONENTIAL:\n            return baseLogexponential(conductivity, T, 0.0);\n        case IncompressibleData::INCOMPRESSIBLE_EXPPOLYNOMIAL:\n            return exp(poly.evaluate(conductivity.coeffs, T, x, 0, 0, Tbase, xbase));\n        case IncompressibleData::INCOMPRESSIBLE_POLYOFFSET:\n            return basePolyOffset(conductivity, T, x);\n        case IncompressibleData::INCOMPRESSIBLE_NOT_SET:\n            throw ValueError(format(\"%s (%d): The function type is not specified (\\\"[%d]\\\"), are you sure the coefficients have been set?\",__FILE__,__LINE__,conductivity.type));\n        default:\n            throw ValueError(format(\"%s (%d): Your function type \\\"[%d]\\\" is unknown.\",__FILE__,__LINE__,conductivity.type));\n    }\n}\n/// Saturation pressure as a function of temperature and composition.\ndouble IncompressibleFluid::psat(double T,           double x){\n    if (T<=this->TminPsat) return 0.0;\n    switch (p_sat.type) {\n        case IncompressibleData::INCOMPRESSIBLE_POLYNOMIAL:\n            return poly.evaluate(p_sat.coeffs, T, x, 0, 0, Tbase, xbase);\n        case IncompressibleData::INCOMPRESSIBLE_EXPONENTIAL:\n            return baseExponential(p_sat, T, 0.0);\n        case IncompressibleData::INCOMPRESSIBLE_LOGEXPONENTIAL:\n            return baseLogexponential(p_sat, T, 0.0);\n        case IncompressibleData::INCOMPRESSIBLE_EXPPOLYNOMIAL:\n            return exp(poly.evaluate(p_sat.coeffs, T, x, 0, 0, Tbase, xbase));\n        case IncompressibleData::INCOMPRESSIBLE_POLYOFFSET:\n            return basePolyOffset(p_sat, T, x);\n        case IncompressibleData::INCOMPRESSIBLE_NOT_SET:\n            throw ValueError(format(\"%s (%d): The function type is not specified (\\\"[%d]\\\"), are you sure the coefficients have been set?\",__FILE__,__LINE__,p_sat.type));\n        default:\n            throw ValueError(format(\"%s (%d): Your function type \\\"[%d]\\\" is unknown.\",__FILE__,__LINE__,p_sat.type));\n    }\n}\n/// Freezing temperature as a function of pressure and composition.\ndouble IncompressibleFluid::Tfreeze(       double p, double x){\n    switch (T_freeze.type) {\n        case IncompressibleData::INCOMPRESSIBLE_POLYNOMIAL:\n            return poly.evaluate(T_freeze.coeffs, p, x, 0, 0, 0.0, xbase);\n        case IncompressibleData::INCOMPRESSIBLE_EXPONENTIAL:\n            return baseExponential(T_freeze, x, 0.0);\n        case IncompressibleData::INCOMPRESSIBLE_LOGEXPONENTIAL:\n            return baseLogexponential(T_freeze, x, 0.0);\n        case IncompressibleData::INCOMPRESSIBLE_EXPPOLYNOMIAL:\n            return exp(poly.evaluate(T_freeze.coeffs, p, x, 0, 0, 0.0, xbase));\n        case IncompressibleData::INCOMPRESSIBLE_POLYOFFSET:\n            return basePolyOffset(T_freeze, p, x);\n        case IncompressibleData::INCOMPRESSIBLE_NOT_SET:\n            throw ValueError(format(\"%s (%d): The function type is not specified (\\\"[%d]\\\"), are you sure the coefficients have been set?\",__FILE__,__LINE__,T_freeze.type));\n        default:\n            throw ValueError(format(\"%s (%d): Your function type \\\"[%d]\\\" is unknown.\",__FILE__,__LINE__,T_freeze.type));\n    }\n}\n\n\n/* Below are direct calculations of the derivatives. Nothing\n * special is going on, we simply use the polynomial class to\n * derive the different functions with respect to temperature.\n */\n/// Partial derivative of density with respect to temperature at constant pressure and composition\ndouble IncompressibleFluid::drhodTatPx (double T, double p, double x){\n    switch (density.type) {\n        case IncompressibleData::INCOMPRESSIBLE_POLYNOMIAL:\n        \treturn poly.derivative(density.coeffs, T, x, 0, 0, 0, Tbase, xbase);\n        case IncompressibleData::INCOMPRESSIBLE_NOT_SET:\n            throw ValueError(format(\"%s (%d): The function type is not specified (\\\"[%d]\\\"), are you sure the coefficients have been set?\",__FILE__,__LINE__,density.type));\n        default:\n            throw ValueError(format(\"%s (%d): There is no predefined way to use this function type \\\"[%d]\\\" for density.\",__FILE__,__LINE__,density.type));\n    }\n}\n/// Partial derivative of entropy\n//  with respect to temperature at constant pressure and composition\n//  integrated in temperature\ndouble IncompressibleFluid::dsdTatPxdT(double T, double p, double x){\n\tswitch (specific_heat.type) {\n\t\tcase IncompressibleData::INCOMPRESSIBLE_POLYNOMIAL:\n\t\t\treturn poly.integral(specific_heat.coeffs, T, x, 0, -1, 0, Tbase, xbase);\n\t\tcase IncompressibleData::INCOMPRESSIBLE_NOT_SET:\n\t\t\tthrow ValueError(format(\"%s (%d): The function type is not specified (\\\"[%d]\\\"), are you sure the coefficients have been set?\",__FILE__,__LINE__,specific_heat.type));\n\t\tdefault:\n\t\t\tthrow ValueError(format(\"%s (%d): There is no predefined way to use this function type \\\"[%d]\\\" for entropy.\",__FILE__,__LINE__,specific_heat.type));\n\t}\n}\n/// Partial derivative of enthalpy\n//  with respect to temperature at constant pressure and composition\n//  integrated in temperature\ndouble IncompressibleFluid::dhdTatPxdT(double T, double p, double x){\n\tswitch (specific_heat.type) {\n\t\tcase IncompressibleData::INCOMPRESSIBLE_POLYNOMIAL:\n\t\t\treturn poly.integral(specific_heat.coeffs, T, x, 0, 0, 0, Tbase, xbase);\n\t\tcase IncompressibleData::INCOMPRESSIBLE_NOT_SET:\n\t\t\tthrow ValueError(format(\"%s (%d): The function type is not specified (\\\"[%d]\\\"), are you sure the coefficients have been set?\",__FILE__,__LINE__,specific_heat.type));\n\t\tdefault:\n\t\t\tthrow ValueError(format(\"%s (%d): There is no predefined way to use this function type \\\"[%d]\\\" for entropy.\",__FILE__,__LINE__,specific_heat.type));\n\t}\n}\n\n\n\n\n/// Mass fraction conversion function\n/** If the fluid type is mass-based, it does not do anything. Otherwise,\n *  it converts the mass fraction to the required input. */\ndouble IncompressibleFluid::inputFromMass (double T,     double x){\n    if (this->xid==IFRAC_PURE) {\n            return _HUGE;\n    } else if (this->xid==IFRAC_MASS) {\n        return x;\n    } else {\n        throw NotImplementedError(\"Mass composition conversion has not been implemented.\");\n        //switch (mass2input.type) {\n        //    case IncompressibleData::INCOMPRESSIBLE_POLYNOMIAL:\n        //        return poly.evaluate(mass2input.coeffs, T, x, 0, 0, 0.0, 0.0); // TODO: make sure Tbase and xbase are defined in the correct way\n        //        break;\n        //    case IncompressibleData::INCOMPRESSIBLE_EXPONENTIAL:\n        //        return baseExponential(mass2input, x, 0.0);\n        //        break;\n        //    case IncompressibleData::INCOMPRESSIBLE_LOGEXPONENTIAL:\n        //        return baseLogexponential(mass2input, x, 0.0);\n        //        break;\n        //    case IncompressibleData::INCOMPRESSIBLE_EXPPOLYNOMIAL:\n        //        return exp(poly.evaluate(mass2input.coeffs, T, x, 0, 0, 0.0, 0.0)); // TODO: make sure Tbase and xbase are defined in the correct way\n        //        break;\n        //    case IncompressibleData::INCOMPRESSIBLE_POLYOFFSET:\n        //        return basePolyOffset(mass2input, T, x);\n        //        break;\n        //    case IncompressibleData::INCOMPRESSIBLE_NOT_SET:\n        //        throw ValueError(format(\"%s (%d): The function type is not specified (\\\"[%d]\\\"), are you sure the coefficients have been set?\",__FILE__,__LINE__,mass2input.type));\n        //        break;\n        //    default:\n        //        throw ValueError(format(\"%s (%d): Your function type \\\"[%d]\\\" is unknown.\",__FILE__,__LINE__,mass2input.type));\n        //        break;\n        //}\n        //return _HUGE;\n    }\n}\n\n/// Volume fraction conversion function\n/** If the fluid type is volume-based, it does not do anything. Otherwise,\n *  it converts the volume fraction to the required input. */\ndouble IncompressibleFluid::inputFromVolume (double T,   double x){\n    if (this->xid==IFRAC_PURE) {\n            return _HUGE;\n    } else if (this->xid==IFRAC_VOLUME) {\n        return x;\n    } else {\n        throw NotImplementedError(\"Volume composition conversion has not been implemented.\");\n        //switch (volume2input.type) {\n        //    case IncompressibleData::INCOMPRESSIBLE_POLYNOMIAL:\n        //        return poly.evaluate(volume2input.coeffs, T, x, 0, 0, 0.0, 0.0); // TODO: make sure Tbase and xbase are defined in the correct way\n        //        break;\n        //    case IncompressibleData::INCOMPRESSIBLE_EXPONENTIAL:\n        //        return baseExponential(volume2input, x, 0.0);\n        //        break;\n        //    case IncompressibleData::INCOMPRESSIBLE_LOGEXPONENTIAL:\n        //        return baseLogexponential(volume2input, x, 0.0);\n        //        break;\n        //    case IncompressibleData::INCOMPRESSIBLE_EXPPOLYNOMIAL:\n        //        return exp(poly.evaluate(volume2input.coeffs, T, x, 0, 0, 0.0, 0.0)); // TODO: make sure Tbase and xbase are defined in the correct way\n        //        break;\n        //    case IncompressibleData::INCOMPRESSIBLE_POLYOFFSET:\n        //        return basePolyOffset(volume2input, T, x);\n        //        break;\n        //    case IncompressibleData::INCOMPRESSIBLE_NOT_SET:\n        //        throw ValueError(format(\"%s (%d): The function type is not specified (\\\"[%d]\\\"), are you sure the coefficients have been set?\",__FILE__,__LINE__,volume2input.type));\n        //        break;\n        //    default:\n        //        throw ValueError(format(\"%s (%d): Your function type \\\"[%d]\\\" is unknown.\",__FILE__,__LINE__,volume2input.type));\n        //        break;\n        //}\n        //return _HUGE;\n    }\n}\n\n/// Mole fraction conversion function\n/** If the fluid type is mole-based, it does not do anything. Otherwise,\n *  it converts the mole fraction to the required input. */\ndouble IncompressibleFluid::inputFromMole (double T,     double x){\n    if (this->xid==IFRAC_PURE) {\n            return _HUGE;\n    } else if (this->xid==IFRAC_MOLE) {\n        return x;\n    } else {\n        throw NotImplementedError(\"Mole composition conversion has not been implemented.\");\n        /*\n        switch (mole2input.type) {\n            case IncompressibleData::INCOMPRESSIBLE_POLYNOMIAL:\n                return poly.evaluate(mole2input.coeffs, T, x, 0, 0, 0.0, 0.0); // TODO: make sure Tbase and xbase are defined in the correct way\n                break;\n            case IncompressibleData::INCOMPRESSIBLE_EXPONENTIAL:\n                return baseExponential(mole2input, x, 0.0);\n                break;\n            case IncompressibleData::INCOMPRESSIBLE_LOGEXPONENTIAL:\n                return baseLogexponential(mole2input, x, 0.0);\n                break;\n            case IncompressibleData::INCOMPRESSIBLE_EXPPOLYNOMIAL:\n                return exp(poly.evaluate(mole2input.coeffs, T, x, 0, 0, 0.0, 0.0)); // TODO: make sure Tbase and xbase are defined in the correct way\n                break;\n            case IncompressibleData::INCOMPRESSIBLE_POLYOFFSET:\n                return basePolyOffset(mole2input, T, x);\n                break;\n            case IncompressibleData::INCOMPRESSIBLE_NOT_SET:\n                throw ValueError(format(\"%s (%d): The function type is not specified (\\\"[%d]\\\"), are you sure the coefficients have been set?\",__FILE__,__LINE__,mole2input.type));\n                break;\n            default:\n                throw ValueError(format(\"%s (%d): Your function type \\\"[%d]\\\" is unknown.\",__FILE__,__LINE__,mole2input.type));\n                break;\n        }\n        return _HUGE;\n        */\n    }\n}\n\n/* Some functions can be inverted directly, those are listed\n * here. It is also possible to solve for other quantities, but\n * that involves some more sophisticated processing and is not\n * done here, but in the backend, T(h,p) for example.\n */\n/// Temperature as a function of density, pressure and composition.\ndouble IncompressibleFluid::T_rho (double Dmass, double p, double x){\n    double d_raw = Dmass; // No changes needed, no reference values...\n    switch (density.type) {\n        case IncompressibleData::INCOMPRESSIBLE_POLYNOMIAL:\n            return poly.solve_limits(density.coeffs, x, d_raw, Tmin, Tmax, 0, 0, 0, Tbase, xbase);\n        case IncompressibleData::INCOMPRESSIBLE_NOT_SET:\n            throw ValueError(format(\"%s (%d): The function type is not specified (\\\"[%d]\\\"), are you sure the coefficients have been set?\",__FILE__,__LINE__,specific_heat.type));\n        default:\n            throw ValueError(format(\"%s (%d): There is no predefined way to use this function type \\\"[%d]\\\" for inverse density.\",__FILE__,__LINE__,specific_heat.type));\n    }\n}\n/// Temperature as a function of heat capacities as a function of temperature, pressure and composition.\ndouble IncompressibleFluid::T_c   (double Cmass, double p, double x){\n    double c_raw = Cmass; // No changes needed, no reference values...\n    switch (specific_heat.type) {\n        case IncompressibleData::INCOMPRESSIBLE_POLYNOMIAL:\n            return poly.solve_limits(specific_heat.coeffs, x, c_raw, Tmin, Tmax, 0, 0, 0, Tbase, xbase);\n        case IncompressibleData::INCOMPRESSIBLE_NOT_SET:\n            throw ValueError(format(\"%s (%d): The function type is not specified (\\\"[%d]\\\"), are you sure the coefficients have been set?\",__FILE__,__LINE__,specific_heat.type));\n        default:\n            throw ValueError(format(\"%s (%d): There is no predefined way to use this function type \\\"[%d]\\\" for inverse specific heat.\",__FILE__,__LINE__,specific_heat.type));\n    }\n}\n\n/*\n * Some more functions to provide a single implementation\n * of important routines.\n * We start with the check functions that can validate input\n * in terms of pressure p, temperature T and composition x.\n */\n/// Check validity of temperature input.\n/** Compares the given temperature T to the result of a\n *  freezing point calculation. This is not necessarily\n *  defined for all fluids, default values do not cause errors. */\nbool IncompressibleFluid::checkT(double T, double p, double x) {\n    if (Tmin <= 0.) throw ValueError(\"Please specify the minimum temperature.\");\n    if (Tmax <= 0.) throw ValueError(\"Please specify the maximum temperature.\");\n    if ((Tmin > T) || (T > Tmax)) throw ValueError(format(\"Your temperature %f is not between %f and %f.\", T, Tmin, Tmax));\n    double TF = 0.0;\n    if (T_freeze.type!=IncompressibleData::INCOMPRESSIBLE_NOT_SET) TF = Tfreeze(p, x);\n    if ( T<TF) throw ValueError(format(\"Your temperature %f is below the freezing point of %f.\", T, TF));\n    return true;\n}\n\n/// Check validity of pressure input.\n/** Compares the given pressure p to the saturation pressure at\n *  temperature T and throws and exception if p is lower than\n *  the saturation conditions.\n *  The default value for psat is -1 yielding true if psat\n *  is not redefined in the subclass.\n *  */\nbool IncompressibleFluid::checkP(double T, double p, double x) {\n    double ps = 0.0;\n    if (p_sat.type!=IncompressibleData::INCOMPRESSIBLE_NOT_SET) ps = psat(T, x);\n    if (p < 0.0) throw ValueError(format(\"You cannot use negative pressures: %f < %f. \", p, 0.0));\n    if (ps> 0.0 && p < ps)  throw ValueError(format(\"Equations are valid for liquid phase only: %f < %f (psat). \", p, ps));\n    return true;\n}\n\n/// Check validity of composition input.\n/** Compares the given composition x to a stored minimum and\n *  maximum value. Enforces the redefinition of xmin and\n *  xmax since the default values cause an error. */\nbool IncompressibleFluid::checkX(double x){\n    if (xmin < 0.0 || xmin > 1.0) throw ValueError(\"Please specify the minimum concentration between 0 and 1.\");\n    if (xmax < 0.0 || xmax > 1.0) throw ValueError(\"Please specify the maximum concentration between 0 and 1.\");\n    if ((xmin > x) || (x > xmax)) throw ValueError(format(\"Your composition %f is not between %f and %f.\", x, xmin, xmax));\n    return true;\n}\n\n} /* namespace CoolProp */\n\n\n\n// Testing still needs to be enhanced.\n/* Below, I try to carry out some basic tests for both 2D and 1D\n * polynomials as well as the exponential functions for vapour\n * pressure etc.\n */\n#ifdef ENABLE_CATCH\n#include <math.h>\n#include <iostream>\n#include \"catch.hpp\"\n#include \"TestObjects.h\"\n\n\nEigen::MatrixXd makeMatrix(const std::vector<double> &coefficients){\n    //IncompressibleClass::checkCoefficients(coefficients,18);\n    std::vector< std::vector<double> > matrix;\n    std::vector<double> tmpVector;\n\n    tmpVector.clear();\n    tmpVector.push_back(coefficients[0]);\n    tmpVector.push_back(coefficients[6]);\n    tmpVector.push_back(coefficients[11]);\n    tmpVector.push_back(coefficients[15]);\n    matrix.push_back(tmpVector);\n\n    tmpVector.clear();\n    tmpVector.push_back(coefficients[1]*100.0);\n    tmpVector.push_back(coefficients[7]*100.0);\n    tmpVector.push_back(coefficients[12]*100.0);\n    tmpVector.push_back(coefficients[16]*100.0);\n    matrix.push_back(tmpVector);\n\n    tmpVector.clear();\n    tmpVector.push_back(coefficients[2]*100.0*100.0);\n    tmpVector.push_back(coefficients[8]*100.0*100.0);\n    tmpVector.push_back(coefficients[13]*100.0*100.0);\n    tmpVector.push_back(coefficients[17]*100.0*100.0);\n    matrix.push_back(tmpVector);\n\n    tmpVector.clear();\n    tmpVector.push_back(coefficients[3]*100.0*100.0*100.0);\n    tmpVector.push_back(coefficients[9]*100.0*100.0*100.0);\n    tmpVector.push_back(coefficients[14]*100.0*100.0*100.0);\n    tmpVector.push_back(0.0);\n    matrix.push_back(tmpVector);\n\n    tmpVector.clear();\n    tmpVector.push_back(coefficients[4]*100.0*100.0*100.0*100.0);\n    tmpVector.push_back(coefficients[10]*100.0*100.0*100.0*100.0);\n    tmpVector.push_back(0.0);\n    tmpVector.push_back(0.0);\n    matrix.push_back(tmpVector);\n\n    tmpVector.clear();\n    tmpVector.push_back(coefficients[5]*100.0*100.0*100.0*100.0*100.0);\n    tmpVector.push_back(0.0);\n    tmpVector.push_back(0.0);\n    tmpVector.push_back(0.0);\n    matrix.push_back(tmpVector);\n\n\n\n    tmpVector.clear();\n    return CoolProp::vec_to_eigen(matrix).transpose();\n}\n\n\nTEST_CASE(\"Internal consistency checks and example use cases for the incompressible fluids\",\"[IncompressibleFluids]\")\n{\n    bool PRINT = false;\n    std::string tmpStr;\n    std::vector<double> tmpVector;\n    std::vector< std::vector<double> > tmpMatrix;\n\n\n    SECTION(\"Test case for \\\"SylthermXLT\\\" by Dow Chemicals\") {\n\n        std::vector<double> cRho;\n        cRho.push_back(+1.1563685145E+03);\n        cRho.push_back(-1.0269048032E+00);\n        cRho.push_back(-9.3506079577E-07);\n        cRho.push_back(+1.0368116627E-09);\n        CoolProp::IncompressibleData density;\n        density.type = CoolProp::IncompressibleData::INCOMPRESSIBLE_POLYNOMIAL;\n        density.coeffs = CoolProp::vec_to_eigen(cRho);\n\n        std::vector<double> cHeat;\n        cHeat.push_back(+1.1562261074E+03);\n        cHeat.push_back(+2.0994549103E+00);\n        cHeat.push_back(+7.7175381057E-07);\n        cHeat.push_back(-3.7008444051E-20);\n        CoolProp::IncompressibleData specific_heat;\n        specific_heat.type = CoolProp::IncompressibleData::INCOMPRESSIBLE_POLYNOMIAL;\n        specific_heat.coeffs = CoolProp::vec_to_eigen(cHeat);\n\n        std::vector<double> cCond;\n        cCond.push_back(+1.6121957379E-01);\n        cCond.push_back(-1.3023781944E-04);\n        cCond.push_back(-1.4395238766E-07);\n        CoolProp::IncompressibleData conductivity;\n        conductivity.type = CoolProp::IncompressibleData::INCOMPRESSIBLE_POLYNOMIAL;\n        conductivity.coeffs = CoolProp::vec_to_eigen(cCond);\n\n        std::vector<double> cVisc;\n        cVisc.push_back(+1.0337654989E+03);\n        cVisc.push_back(-4.3322764383E+01);\n        cVisc.push_back(+1.0715062356E+01);\n        CoolProp::IncompressibleData viscosity;\n        viscosity.type = CoolProp::IncompressibleData::INCOMPRESSIBLE_EXPONENTIAL;\n        viscosity.coeffs = CoolProp::vec_to_eigen(cVisc);\n\n        CoolProp::IncompressibleFluid XLT;\n        XLT.setName(\"XLT\");\n        XLT.setDescription(\"SylthermXLT\");\n        XLT.setReference(\"Dow Chemicals data sheet\");\n        XLT.setTmax(533.15);\n        XLT.setTmin(173.15);\n        XLT.setxmax(0.0);\n        XLT.setxmin(0.0);\n        XLT.setTminPsat(533.15);\n\n        XLT.setTbase(0.0);\n        XLT.setxbase(0.0);\n\n        /// Setters for the coefficients\n        XLT.setDensity(density);\n        XLT.setSpecificHeat(specific_heat);\n        XLT.setViscosity(viscosity);\n        XLT.setConductivity(conductivity);\n        //XLT.setPsat(parse_coefficients(fluid_json, \"saturation_pressure\", false));\n        //XLT.setTfreeze(parse_coefficients(fluid_json, \"T_freeze\", false));\n        //XLT.setVolToMass(parse_coefficients(fluid_json, \"volume2mass\", false));\n        //XLT.setMassToMole(parse_coefficients(fluid_json, \"mass2mole\", false));\n\n        /// A function to check coefficients and equation types.\n        //XLT.validate();\n        double acc = 0.0001;\n        double val = 0;\n        double res = 0;\n\n        // Prepare the results and compare them to the calculated values\n        double T = 273.15+50;\n        double p = 10e5;\n        double x = 0.0;\n\n        // Compare density\n        val = 824.4615702148608;\n        res = XLT.rho(T,p,x);\n        {\n        CAPTURE(T);\n        CAPTURE(val);\n        CAPTURE(res);\n        CHECK( check_abs(val,res,acc) );\n        }\n\n        // Compare cp\n        val = 1834.7455527670554;\n        res = XLT.c(T,p,x);\n        {\n        CAPTURE(T);\n        CAPTURE(val);\n        CAPTURE(res);\n        CHECK( check_abs(val,res,acc) );\n        }\n\n        // Check property functions\n        CHECK_THROWS(XLT.s(T,p,x));\n        CHECK_THROWS(XLT.h(T,p,x));\n        CHECK_THROWS(XLT.u(T,p,x));\n\n        // Compare v\n        val = 0.0008931435169681835;\n        res = XLT.visc(T,p,x);\n        {\n        CAPTURE(T);\n        CAPTURE(val);\n        CAPTURE(res);\n        CHECK( check_abs(val,res,acc) );\n        }\n\n        // Compare l\n        val = 0.10410086156049088;\n        res = XLT.cond(T,p,x);\n        {\n        CAPTURE(T);\n        CAPTURE(val);\n        CAPTURE(res);\n        CHECK( check_abs(val,res,acc) );\n        }\n    }\n\n\n    SECTION(\"Test case for Methanol from SecCool\") {\n\n        CoolProp::IncompressibleFluid CH3OH = CoolPropTesting::incompressibleFluidObject();\n\n        // Prepare the results and compare them to the calculated values\n        double acc = 0.0001;\n        double T   = 273.15+10;\n        double p   = 10e5;\n        double x   = 0.25;\n        double expected = 0;\n        double actual = 0;\n\n        // Compare density\n        expected = 963.2886528091547;\n        actual = CH3OH.rho(T,p,x);\n        {\n        CAPTURE(T);\n        CAPTURE(p);\n        CAPTURE(x);\n        CAPTURE(expected);\n        CAPTURE(actual);\n        CHECK( check_abs(expected,actual,acc) );\n        }\n\n        // Compare cp\n        expected = 3993.9748117022423;\n        actual = CH3OH.c(T,p,x);\n        {\n        CAPTURE(T);\n        CAPTURE(p);\n        CAPTURE(x);\n        CAPTURE(expected);\n        CAPTURE(actual);\n        CHECK( check_abs(expected,actual,acc) );\n        }\n\n        // Check property functions\n        CHECK_THROWS(CH3OH.s(T,p,x));\n        CHECK_THROWS(CH3OH.h(T,p,x));\n        CHECK_THROWS(CH3OH.u(T,p,x));\n\n        // Compare v\n        expected = 0.0023970245009602097;\n        actual = CH3OH.visc(T,p,x)/1e3;\n        {\n        CAPTURE(T);\n        CAPTURE(p);\n        CAPTURE(x);\n        CAPTURE(expected);\n        CAPTURE(actual);\n        std::string errmsg = CoolProp::get_global_param_string(\"errstring\");\n        CAPTURE(errmsg);\n        CHECK( check_abs(expected,actual,acc) );\n        }\n\n        // Compare conductivity\n        expected = 0.44791148414693727;\n        actual = CH3OH.cond(T,p,x);\n        {\n        CAPTURE(T);\n        CAPTURE(p);\n        CAPTURE(x);\n        CAPTURE(expected);\n        CAPTURE(actual);\n        std::string errmsg = CoolProp::get_global_param_string(\"errstring\");\n        CAPTURE(errmsg);\n        CHECK( check_abs(expected,actual,acc) );\n        }\n\n        // Compare Tfreeze\n        expected = -20.02+273.15;// 253.1293105454671;\n        actual = CH3OH.Tfreeze(p,x);\n        {\n        CAPTURE(T);\n        CAPTURE(p);\n        CAPTURE(x);\n        CAPTURE(expected);\n        CAPTURE(actual);\n        std::string errmsg = CoolProp::get_global_param_string(\"errstring\");\n        CAPTURE(errmsg);\n        CHECK( check_abs(expected,actual,acc) );\n        }\n\n\n    }\n\n\n}\n\n#endif /* ENABLE_CATCH */\n", "meta": {"hexsha": "117b81fbd393730b7b3c30de483e82252725c88d", "size": 30530, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Backends/Incompressible/IncompressibleFluid.cpp", "max_stars_repo_name": "jfeng08/CoolProp", "max_stars_repo_head_hexsha": "ac96aa48c8ced6fa3c7330b54b9409e0e021d618", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Backends/Incompressible/IncompressibleFluid.cpp", "max_issues_repo_name": "jfeng08/CoolProp", "max_issues_repo_head_hexsha": "ac96aa48c8ced6fa3c7330b54b9409e0e021d618", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Backends/Incompressible/IncompressibleFluid.cpp", "max_forks_repo_name": "jfeng08/CoolProp", "max_forks_repo_head_hexsha": "ac96aa48c8ced6fa3c7330b54b9409e0e021d618", "max_forks_repo_licenses": ["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.49002849, "max_line_length": 183, "alphanum_fraction": 0.6523092041, "num_tokens": 7998, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797065461671, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.49177277817863285}}
{"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_ITERATIVE_CLOSEST_POINT_2D_HPP\n#define PIC_COMPUTER_VISION_ITERATIVE_CLOSEST_POINT_2D_HPP\n\n#include <vector>\n#include <random>\n#include <stdlib.h>\n\n#include \"../base.hpp\"\n\n#include \"../util/math.hpp\"\n\n#include \"../features_matching/brief_descriptor.hpp\"\n\n#include \"../util/eigen_util.hpp\"\n\n#ifndef PIC_DISABLE_EIGEN\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#endif\n\nnamespace pic {\n#ifndef PIC_DISABLE_EIGEN\n\n/**\n * @brief getMean\n * @param p\n * @return\n */\nPIC_INLINE Eigen::Vector2f getMeanVector2f(std::vector< Eigen::Vector2f > &p)\n{\n    auto c = p[0];\n    for(unsigned int i = 1; i < p.size(); i++) {\n        c += p[i];\n    }\n    c /= float(p.size());\n\n    return c;\n}\n\n/**\n * @brief getMedianVector2f\n * @param p\n * @return\n */\nPIC_INLINE Eigen::Vector2f getMedianVector2f(std::vector< Eigen::Vector2f > &p)\n{\n    auto n = p.size();\n    float *x = new float[n];\n    float *y = new float[n];\n\n    for(unsigned int i = 0; i < n; i++) {\n        x[i] = p[i][0];\n        y[i] = p[i][1];\n    }\n\n    std::sort(x, x + n);\n    std::sort(y, y + n);\n\n    Eigen::Vector2f med;\n\n    med[0] = x[n >> 1];\n    med[1] = y[n >> 1];\n\n#ifdef PIC_DEBUG\n    printf(\"%f %f\\n\", med[0], med[1]);\n#endif\n\n    delete[] x;\n    delete[] y;\n    return med;\n}\n\nclass ICP2DTransform\n{\npublic:\n    Eigen::Matrix2f R;\n    Eigen::Vector2f t;\n    float scale;\n\n    ICP2DTransform()\n    {\n        R.setIdentity();\n\n        t.setZero();\n\n        scale = 1.0f;\n    }\n\n    ICP2DTransform(float tx, float ty, float angle, float scale)\n    {\n        this->scale = scale;\n        t[0] = tx;\n        t[1] = ty;\n\n        float cos_a = cosf(angle);\n        float sin_a = sinf(angle);\n\n        R(0, 0) =  cos_a;\n        R(0, 1) = -sin_a;\n        R(1, 0) =  sin_a;\n        R(1, 1) =  cos_a;\n    }\n\n    void print()\n    {\n        printf(\"R:\\n %f %f\\n %f %f\\n\", R(0,0), R(0,1), R(1,0), R(1,1));\n\n        printf(\"T: %f %f\\n\", t[0], t[1]);\n\n        printf(\"S: %f\\n\\n\", scale);\n    }\n\n    void apply(std::vector< Eigen::Vector2f > &points) {\n        //apply transform\n        for(unsigned int i  = 0; i < points.size(); i++) {\n            Eigen::Vector2f tmp = points[i];\n            points[i] = ((R * tmp) + t) * scale;\n        }\n    }\n\n    void apply(std::vector< Eigen::Vector2f > &points,\n               std::vector< Eigen::Vector2f > &out) {\n        //apply transform\n        for(unsigned int i  = 0; i < points.size(); i++) {\n            Eigen::Vector2f tmp = ((R * points[i]) + t) * scale;\n            out.push_back(tmp);\n        }\n    }\n\n    //\n    //\n    //\n\n    void applyC(std::vector< Eigen::Vector2f > &points) {\n\n        //compute centroid to points\n        Eigen::Vector2f c = getMeanVector2f(points);\n        auto shift = c + t;\n\n        //apply transform\n        for(unsigned int i  = 0; i < points.size(); i++) {\n            Eigen::Vector2f tmp = points[i] - c;\n            points[i] = (R * tmp) * scale + shift;\n        }\n    }\n\n    void applyC(std::vector< Eigen::Vector2f > &points,\n               std::vector< Eigen::Vector2f > &out) {\n\n        //compute centroid to points\n        Eigen::Vector2f c = getMeanVector2f(points);\n        auto shift = c + t;\n\n        //apply transform\n        for(unsigned int i  = 0; i < points.size(); i++) {\n            Eigen::Vector2f tmp = points[i] - c;\n            Eigen::Vector2f tmp2 = (R * tmp) * scale + shift;\n            out.push_back(tmp2);\n        }\n    }\n};\n\n/**\n * @brief estimateRotatioMatrixAndTranslation\n * @param p0\n * @param p1\n * @param p0_descs\n * @param p1_descs\n * @param ind\n * @return\n */\nPIC_INLINE ICP2DTransform estimateRotatioMatrixAndTranslation(std::vector< Eigen::Vector2f > &p0,\n                                                   std::vector< Eigen::Vector2f > &p1,\n                                                   std::vector< unsigned int *> &p0_descs,\n                                                   std::vector< unsigned int *> &p1_descs,\n                                                   int size_descs,\n                                                   int *ind = NULL)\n{\n    ICP2DTransform ret;\n\n    if(p0.size() < 2 || p1.size() < 2) {\n        return ret;\n    }\n\n    bool bFlag = false;\n    if(ind == NULL) {\n        ind = new int[p1.size()];\n        bFlag = true;\n    }\n\n    //compute c0\n    Eigen::Vector2f c1 = getMeanVector2f(p1);\n\n    //compute c1\n    Eigen::Vector2f c0;\n    c0.setZero();\n    int n = 0;\n\n#ifdef PIC_DEBUG\n    printf(\"Size: %d\\n\", size_descs);\n#endif\n\n    for(int i = 0; i < p1.size(); i++) {\n        auto p_i = p1[i];\n\n        float d_min = FLT_MAX;\n        int index = -1;\n        for(int j = 0; j < p0.size(); j++) {\n            auto delta_ij = p_i - p0[j];\n            float d_tmp = delta_ij.norm();\n\n            int value = BRIEFDescriptor::match(p0_descs[j], p1_descs[i], size_descs);\n            d_tmp += float(size_descs * 32) - float(value);\n\n            if(d_tmp < d_min) {\n                d_min = d_tmp;\n                index = j;\n            }\n\n        }\n\n        if(index > -1) {\n            ind[i] = index;\n            c0 += p0[index];\n            n++;\n        }\n    }\n    c0 /= float(n);\n\n\n    //compute R\n    Eigen::Matrix2f H;\n    H.setZero();\n\n    for(unsigned int i = 0; i < p1.size(); i++) {\n        int j = ind[i];\n\n        auto t0 = p0[j] - c0;\n        auto t1 = p1[i] - c1;\n\n        Eigen::RowVector2f t1r = t1;\n        Eigen::Matrix2f tmp = t0 * t1r;\n\n/*      tmp(0, 0) = t0(0) * t1(0);\n        tmp(0, 1) = t0(0) * t1(1);\n        tmp(1, 0) = t0(1) * t1(0);\n        tmp(1, 1) = t0(1) * t1(1);*/\n        H += tmp;\n    }\n\n    //SVD decomposition\n    Eigen::JacobiSVD< Eigen::Matrix2f > svd(H, Eigen::ComputeFullV | Eigen::ComputeFullU);\n    Eigen::Matrix2f U = svd.matrixU();\n    Eigen::Matrix2f V = svd.matrixV();\n\n    Eigen::Matrix2f U_t = U.transpose();\n    Eigen::Matrix2f R = V * U_t;\n\n    if(R.determinant() < 0.0f) {\n        for(unsigned int i = 0; i < V.rows(); i++) {\n            V(i, 1) = -V(i, 1);\n        }\n\n        R = V * U_t;\n    }\n\n    ret.R = R;\n    ret.t = c0 - (ret.R * c1);\n\n    if(bFlag) {\n        delete[] ind;\n    }\n\n    return ret;\n}\n\n/**\n * @brief getErrorPointsList\n * @param p0\n * @param p1\n * @return\n */\nPIC_INLINE float getErrorPointsList(std::vector< Eigen::Vector2f > &p0,\n                         std::vector< Eigen::Vector2f > &p1)\n{\n    float err = 0.0f;\n    for(unsigned int i = 0; i < p0.size(); i++) {\n        auto p_i = p0[i];\n\n        float tmp_err = FLT_MAX;\n        for(unsigned int j = 0; j < p1.size(); j++) {\n            auto delta_ij = p_i - p1[j];\n            float dist = delta_ij.norm();\n\n            if(dist < tmp_err) {\n                tmp_err = dist;\n            }\n        }\n\n        err += tmp_err;\n    }\n\n    return err / float(p0.size());\n}\n\n/**\n * @brief iterativeClosestPoints2D\n * @param points_pattern\n * @param points\n * @param points_pattern_descs\n * @param points_descs\n * @param thresholdErr\n * @param maxIterations\n */\nPIC_INLINE void iterativeClosestPoints2D(std::vector<Eigen::Vector2f> &points_pattern,\n                              std::vector<Eigen::Vector2f> &points,\n                              std::vector< unsigned int *> &points_pattern_descs,\n                              std::vector< unsigned int *> &points_descs,\n                              int size_descs,\n                              int maxIterations = 1000)\n{\n    ICP2DTransform t_init;\n    t_init.t = getMedianVector2f(points) - getMeanVector2f(points_pattern);\n    t_init.apply(points_pattern);\n\n    float err = getErrorPointsList(points_pattern, points);;\n    float prev_err = 1e32f;\n    int iter = 0;\n    while(iter < maxIterations) {\n        prev_err = err;\n        ICP2DTransform t = estimateRotatioMatrixAndTranslation(points, points_pattern,\n                                                               points_descs, points_pattern_descs,\n                                                               size_descs);\n\n#ifdef PIC_DEBUG\n        t.print();\n#endif\n\n//        std::vector< Eigen::Vector2f > points_pattern_tmp;\n        t.apply(points_pattern);\n\n        err = getErrorPointsList(points_pattern, points);\n\n        /*\n        if(err < prev_err) {\n            points_pattern.clear();\n            std::copy(points_pattern_tmp.begin(), points_pattern_tmp.end(),\n                      std::back_inserter(points_pattern));\n        } else {\n            iter = maxIterations;\n        }\n        */\n\n        #ifdef PIC_DEBUG\n            printf(\"Error: %f %f\\n\", err, prev_err);\n        #endif\n\n        iter++;\n    }\n}\n\n#endif\n} // end namespace pic\n\n#endif // PIC_COMPUTER_VISION_ITERATIVE_CLOSEST_POINT_2D_HPP\n", "meta": {"hexsha": "e62d60c9f2ed6be4ffdf1ee2056dd34f3ec72156", "size": 9217, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/computer_vision/iterative_closest_point_2D.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/iterative_closest_point_2D.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/iterative_closest_point_2D.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": 23.6333333333, "max_line_length": 98, "alphanum_fraction": 0.5144841055, "num_tokens": 2621, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267694452331, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4917720553805518}}
{"text": "\n/**\n * Kalman filter implementation using Eigen. Based on the following\n * introductory paper:\n *\n *     http://www.cs.unc.edu/~welch/media/pdf/kalman_intro.pdf\n *\n * @author: Hayk Martirosyan\n * @date: 2014.11.15\n */\n\n#include <Eigen/Dense>\n#include <mutex>\n\nusing namespace std;\n\n#pragma once\n\nclass KalmanFilter {\n    \npublic:\n    \n    /**\n     * Create a Kalman filter with the specified matrices.\n     *   A - System dynamics matrix\n     *   C - Output matrix\n     *   Q - Process noise covariance -> W\n     *   R - Measurement noise covariance -> V (sym\u00e9trique)\n     *   P - Estimate error covariance\n     */\n    KalmanFilter(\n                 double dt,\n                 double Fobj,\n                 double L,\n                 double k,\n                 double v_robot, \n                 const Eigen::VectorXd& u,\n                 const Eigen::MatrixXd& A, // matrice de doubles de taille non d\u00e9finie\n                 const Eigen::MatrixXd& C,\n                 const Eigen::MatrixXd& Q,\n                 const Eigen::MatrixXd& R,\n                 const Eigen::MatrixXd& P\n                 );\n    \n    // Create a blank estimator.\n    KalmanFilter();\n    \n    // Create a Kalman filter adapted for the specific robot case\n    KalmanFilter setRobotKalman(double stepTime, double ForceObjective);\n    \n    // Initialize the filter with initial states as zero.\n    void init();\n    \n    \n    \n    // Initialize the filter with a guess for initial states.\n    void init(double t0, const Eigen::VectorXd& x0);\n    \n    \n    /* Update the estimated state based on measured values. The\n     time step is assumed to remain constant.*/\n    double update(double a, double b);\n    \n    // Return the current state or time.\n    Eigen::VectorXd getState() { return x_hat; };\n    double getTime() { return t; };\n    \n    \nprivate:\n    \n    // Matrices for computation\n    Eigen::MatrixXd A, C, W, V, P, K, P0;\n    \n    // System dimensions\n    int m, n, c;\n    \n    // Initial and current time\n    double t0, t;\n    \n    // Discrete time step\n    double dt;\n    \n    // Force objective\n    double Fobj;\n    \n    // Lenght of tool (specific to the robot)\n    double L;\n    \n    //stiffness of the tool\n    double k;\n    \n    // Command vector\n    Eigen::VectorXd u;\n    \n    // Speed of the robot\n    double v_robot;\n    \n    // Is the filter initialized?\n    bool initialized;\n    \n    // n-size identity\n    Eigen::MatrixXd I;\n    \n    // Estimated states\n    Eigen::VectorXd x_hat, x_hat_new;\n};\n\n", "meta": {"hexsha": "26008f44067275cbf6c6703e4b86ee7117ef7f72", "size": 2493, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Computer/Correction/correcteur.hpp", "max_stars_repo_name": "ClementPhan/Force-torque_Robot", "max_stars_repo_head_hexsha": "8b2d1a539d4afdc88edf5290f628b12c03ea8760", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Computer/Correction/correcteur.hpp", "max_issues_repo_name": "ClementPhan/Force-torque_Robot", "max_issues_repo_head_hexsha": "8b2d1a539d4afdc88edf5290f628b12c03ea8760", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Computer/Correction/correcteur.hpp", "max_forks_repo_name": "ClementPhan/Force-torque_Robot", "max_forks_repo_head_hexsha": "8b2d1a539d4afdc88edf5290f628b12c03ea8760", "max_forks_repo_licenses": ["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.0833333333, "max_line_length": 86, "alphanum_fraction": 0.5720016045, "num_tokens": 581, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267694452331, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4917720553805518}}
{"text": "#include <voxelized_geometry_tools/opencl_voxelization_helpers.h>\n\n#include <cmath>\n#include <cstdint>\n#include <iostream>\n#include <map>\n#include <memory>\n#include <string>\n#include <vector>\n\n#include <Eigen/Geometry>\n#include <voxelized_geometry_tools/cl.hpp>\n\nnamespace voxelized_geometry_tools\n{\nnamespace pointcloud_voxelization\n{\nnamespace opencl_helpers\n{\nconst char* kRaycastPointKernelCode = R\"(\nvoid kernel RaycastPoint(\n    global const float* points, const float max_range,\n    global const float* grid_pointcloud_transform,\n    const float inverse_step_size, const float inverse_cell_size,\n    const int stride1, const int stride2, const int num_x_cells,\n    const int num_y_cells, const int num_z_cells, global int* tracking_grid,\n    const int tracking_grid_starting_offset)\n{\n  const int point_index = get_global_id(0);\n  // Point in pointcloud frame\n  const float px = points[(point_index * 3) + 0];\n  const float py = points[(point_index * 3) + 1];\n  const float pz = points[(point_index * 3) + 2];\n  // Skip invalid points marked with NaN or infinity\n  if (isfinite(px) && isfinite(py) && isfinite(pz))\n  {\n    // Pointcloud origin in grid frame\n    const float ox = grid_pointcloud_transform[12];\n    const float oy = grid_pointcloud_transform[13];\n    const float oz = grid_pointcloud_transform[14];\n    // Point in grid frame\n    const float gx = grid_pointcloud_transform[0] * px\n                     + grid_pointcloud_transform[4] * py\n                     + grid_pointcloud_transform[8] * pz\n                     + grid_pointcloud_transform[12];\n    const float gy = grid_pointcloud_transform[1] * px\n                     + grid_pointcloud_transform[5] * py\n                     + grid_pointcloud_transform[9] * pz\n                     + grid_pointcloud_transform[13];\n    const float gz = grid_pointcloud_transform[2] * px\n                     + grid_pointcloud_transform[6] * py\n                     + grid_pointcloud_transform[10] * pz\n                     + grid_pointcloud_transform[14];\n    const float rx = gx - ox;\n    const float ry = gy - oy;\n    const float rz = gz - oz;\n    const float current_ray_length = sqrt((rx * rx) + (ry * ry) + (rz * rz));\n    const float num_steps = floor(current_ray_length * inverse_step_size);\n    int previous_x_cell = -1;\n    int previous_y_cell = -1;\n    int previous_z_cell = -1;\n    bool ray_crossed_grid = false;\n    for (float step = 0.0; step < num_steps; step += 1.0)\n    {\n      const float elapsed_ratio = step / num_steps;\n      if ((elapsed_ratio * current_ray_length) > max_range)\n      {\n        // We've gone beyond max range of the sensor\n        break;\n      }\n      const float qx = (rx * elapsed_ratio) + ox;\n      const float qy = (ry * elapsed_ratio) + oy;\n      const float qz = (rz * elapsed_ratio) + oz;\n      const int x_cell = (int)floor(qx * inverse_cell_size);\n      const int y_cell = (int)floor(qy * inverse_cell_size);\n      const int z_cell = (int)floor(qz * inverse_cell_size);\n      if (x_cell != previous_x_cell || y_cell != previous_y_cell\n          || z_cell != previous_z_cell)\n      {\n        if (x_cell >= 0 && x_cell < num_x_cells && y_cell >= 0\n           && y_cell < num_y_cells && z_cell >= 0 && z_cell < num_z_cells)\n        {\n          ray_crossed_grid = true;\n          const int cell_index =\n              (x_cell * stride1) + (y_cell * stride2) + z_cell;\n          const int tracking_grid_index =\n              tracking_grid_starting_offset + (cell_index * 2);\n          atomic_add(&(tracking_grid[tracking_grid_index]), 1);\n        }\n        else if (ray_crossed_grid)\n        {\n          break;\n        }\n      }\n      previous_x_cell = x_cell;\n      previous_y_cell = y_cell;\n      previous_z_cell = z_cell;\n    }\n    // Set the point itself as filled, if it is in range\n    if (current_ray_length <= max_range)\n    {\n      const int x_cell = (int)floor(gx * inverse_cell_size);\n      const int y_cell = (int)floor(gy * inverse_cell_size);\n      const int z_cell = (int)floor(gz * inverse_cell_size);\n      if (x_cell >= 0 && x_cell < num_x_cells && y_cell >= 0\n          && y_cell < num_y_cells && z_cell >= 0 && z_cell < num_z_cells)\n      {\n        const int cell_index = (x_cell * stride1) + (y_cell * stride2) + z_cell;\n        const int tracking_grid_index =\n            tracking_grid_starting_offset + (cell_index * 2);\n        atomic_add(&(tracking_grid[tracking_grid_index + 1]), 1);\n      }\n    }\n  }\n}\n)\";\n\nconst char* kFilterGridsKernelCode = R\"(\nvoid kernel FilterGrids(\n    const int num_cells, const int num_grids, global const int* tracking_grid,\n    global float* filter_grid, const float percent_seen_free,\n    const int outlier_points_threshold, const int num_cameras_seen_free)\n{\n  const int voxel_index = get_global_id(0);\n  const int filter_grid_index = voxel_index * 2;\n  const float current_occupancy = filter_grid[filter_grid_index];\n  if (current_occupancy <= 0.5)\n  {\n    int cameras_seen_filled = 0;\n    int cameras_seen_free = 0;\n    for (int idx = 0; idx < num_grids; idx++)\n    {\n      const int tracking_grid_offset = num_cells * 2 * idx;\n      const int tracking_grid_index =\n          tracking_grid_offset + filter_grid_index;\n      const int free_count = tracking_grid[tracking_grid_index];\n      const int filled_count = tracking_grid[tracking_grid_index + 1];\n      const int filtered_filled_count =\n          (filled_count >= outlier_points_threshold) ? filled_count : 0;\n      if (free_count > 0 && filtered_filled_count > 0)\n      {\n        const float current_percent_seen_free =\n            (float)(free_count) / (float)(free_count + filtered_filled_count);\n        if (current_percent_seen_free >= percent_seen_free)\n        {\n          cameras_seen_free += 1;\n        }\n        else\n        {\n          cameras_seen_filled += 1;\n        }\n      }\n      else if (free_count > 0)\n      {\n        cameras_seen_free += 1;\n      }\n      else if (filtered_filled_count > 0)\n      {\n        cameras_seen_filled += 1;\n      }\n    }\n    if (cameras_seen_filled > 0)\n    {\n      filter_grid[filter_grid_index] = 1.0;\n    }\n    else if (cameras_seen_free >= num_cameras_seen_free)\n    {\n      filter_grid[filter_grid_index] = 0.0;\n    }\n    else\n    {\n      filter_grid[filter_grid_index] = 0.5;\n    }\n  }\n}\n)\";\n\nstatic std::string GetRaycastingKernelCode()\n{\n  return std::string(kRaycastPointKernelCode);\n}\n\nstatic std::string GetFilterKernelCode()\n{\n  return std::string(kFilterGridsKernelCode);\n}\n\nclass OpenCLTrackingGridsHandle : public TrackingGridsHandle\n{\npublic:\n  OpenCLTrackingGridsHandle(\n      std::unique_ptr<cl::Buffer> tracking_grids_buffer,\n      const std::vector<int64_t>& tracking_grid_starting_offsets,\n      const int64_t num_cells_per_grid)\n      : TrackingGridsHandle(tracking_grid_starting_offsets, num_cells_per_grid),\n        tracking_grids_buffer_(std::move(tracking_grids_buffer))\n  {\n    if (!tracking_grids_buffer_)\n    {\n      throw std::invalid_argument(\n          \"Cannot create OpenCLTrackingGridsHandle with null buffer\");\n    }\n  }\n\n  cl::Buffer& GetBuffer() { return *tracking_grids_buffer_; }\n\n  const cl::Buffer& GetBuffer() const { return *tracking_grids_buffer_; }\n\nprivate:\n  std::unique_ptr<cl::Buffer> tracking_grids_buffer_;\n};\n\nclass OpenCLFilterGridHandle : public FilterGridHandle\n{\npublic:\n  OpenCLFilterGridHandle(\n      std::unique_ptr<cl::Buffer> filter_grid_buffer,\n      const int64_t num_cells)\n      : FilterGridHandle(num_cells),\n        filter_grid_buffer_(std::move(filter_grid_buffer))\n  {\n    if (!filter_grid_buffer_)\n    {\n      throw std::invalid_argument(\n          \"Cannot create OpenCLFilterGridHandle with null buffer\");\n    }\n  }\n\n  cl::Buffer& GetBuffer() { return *filter_grid_buffer_; }\n\n  const cl::Buffer& GetBuffer() const { return *filter_grid_buffer_; }\n\nprivate:\n  std::unique_ptr<cl::Buffer> filter_grid_buffer_;\n};\n\nclass OpenCLVoxelizationHelperInterface\n    : public DeviceVoxelizationHelperInterface\n{\npublic:\n  explicit OpenCLVoxelizationHelperInterface(\n      const std::map<std::string, int32_t>& options)\n  {\n    std::vector<cl::Platform> all_platforms;\n    cl::Platform::get(&all_platforms);\n\n    const int32_t platform_index =\n        RetrieveOptionOrDefault(options, \"OPENCL_PLATFORM_INDEX\", 0);\n    if (all_platforms.size() > 0 && platform_index >= 0\n        && platform_index < static_cast<int32_t>(all_platforms.size()))\n    {\n      auto& opencl_platform = all_platforms.at(platform_index);\n\n      std::string platform_name;\n      opencl_platform.getInfo(CL_PLATFORM_NAME, &platform_name);\n      std::string platform_vendor;\n      opencl_platform.getInfo(CL_PLATFORM_VENDOR, &platform_vendor);\n\n      std::cout << \"Using OpenCL Platform [\" << platform_index << \"] - Name: [\"\n                << platform_name << \"], Vendor: [\" << platform_vendor << \"]\"\n                << std::endl;\n\n      std::vector<cl::Device> all_devices;\n      opencl_platform.getDevices(CL_DEVICE_TYPE_ALL, &all_devices);\n\n      const int32_t device_index =\n          RetrieveOptionOrDefault(options, \"OPENCL_DEVICE_INDEX\", 0);\n      if (all_devices.size() > 0 && device_index >= 0\n          && device_index < static_cast<int32_t>(all_devices.size()))\n      {\n        auto& opencl_device = all_devices.at(device_index);\n\n        std::string device_name;\n        opencl_device.getInfo(CL_DEVICE_NAME, &device_name);\n\n        std::cout << \"Using OpenCL Device [\" << device_index << \"] - Name: [\"\n                  << device_name << \"]\" << std::endl;\n\n        // Make context + queue\n        context_ = std::unique_ptr<cl::Context>(\n            new cl::Context({opencl_device}));\n        queue_ = std::unique_ptr<cl::CommandQueue>(\n            new cl::CommandQueue(*context_, opencl_device));\n        // Make kernel programs\n        const std::string build_options = \"-Werror -cl-fast-relaxed-math\";\n        cl::Program::Sources raycasting_sources;\n        const std::string raycasting_kernel_source = GetRaycastingKernelCode();\n        raycasting_sources.push_back({raycasting_kernel_source.c_str(),\n                                      raycasting_kernel_source.length()});\n        raycasting_program_ = std::unique_ptr<cl::Program>(\n            new cl::Program(*context_, raycasting_sources));\n        cl::Program::Sources filter_sources;\n        const std::string filter_kernel_source = GetFilterKernelCode();\n        filter_sources.push_back({filter_kernel_source.c_str(),\n                                  filter_kernel_source.length()});\n        filter_program_ = std::unique_ptr<cl::Program>(\n            new cl::Program(*context_, filter_sources));\n        if (raycasting_program_->build({opencl_device}, build_options.c_str())\n            != CL_SUCCESS)\n        {\n          std::cerr << \" Error building raycasting kernel: \"\n                    << raycasting_program_->getBuildInfo<CL_PROGRAM_BUILD_LOG>(\n                        opencl_device)\n                    << std::endl;\n          raycasting_program_.reset();\n        }\n        if (filter_program_->build({opencl_device}, build_options.c_str())\n            != CL_SUCCESS)\n        {\n          std::cerr << \" Error building filter kernel: \"\n                    << filter_program_->getBuildInfo<CL_PROGRAM_BUILD_LOG>(\n                        opencl_device)\n                    << std::endl;\n          filter_program_.reset();\n        }\n      }\n      else if (all_devices.size() > 0)\n      {\n        std::cerr << \"OPENCL_DEVICE_INDEX = \" << device_index\n                  << \" out of range for \" << all_devices.size() << \" devices\"\n                  << std::endl;\n      }\n      else\n      {\n        std::cerr << \"No OpenCL device available\" << std::endl;\n      }\n    }\n    else if (all_platforms.size() > 0)\n    {\n      std::cerr << \"OPENCL_PLATFORM_INDEX = \" << platform_index\n                << \" out of range for \" << all_platforms.size() << \" platforms\"\n                << std::endl;\n    }\n    else\n    {\n      std::cerr << \"No OpenCL platform available\" << std::endl;\n    }\n  }\n\n  bool IsAvailable() const override\n  {\n    return (context_ && queue_ && raycasting_program_ && filter_program_);\n  }\n\n  std::unique_ptr<TrackingGridsHandle> PrepareTrackingGrids(\n      const int64_t num_cells, const int32_t num_grids) override\n  {\n    const size_t buffer_size = sizeof(int32_t) * 2 * num_cells * num_grids;\n    cl_int err = 0;\n    std::unique_ptr<cl::Buffer> tracking_grids_buffer(new cl::Buffer(\n        *context_, CL_MEM_READ_WRITE, buffer_size, nullptr, &err));\n    if (err == 0)\n    {\n      // This is how we zero the buffer\n      cl::Event event;\n      err = queue_->enqueueFillBuffer<int32_t>(\n          *tracking_grids_buffer, 0, 0, buffer_size, nullptr, &event);\n      if (err == CL_SUCCESS)\n      {\n        err = event.wait();\n        if (err == CL_SUCCESS)\n        {\n          std::vector<int64_t> tracking_grid_offsets(num_grids, 0);\n          for (int32_t num_grid = 0; num_grid < num_grids; num_grid++)\n          {\n            tracking_grid_offsets.at(num_grid) = num_grid * num_cells * 2;\n          }\n          return std::unique_ptr<TrackingGridsHandle>(\n              new OpenCLTrackingGridsHandle(\n                  std::move(tracking_grids_buffer), tracking_grid_offsets,\n                  num_cells));\n        }\n        else\n        {\n          throw std::runtime_error(\"Failed to wait for event\");\n        }\n      }\n      else\n      {\n        throw std::runtime_error(\"Failed to enqueueFillBuffer\");\n      }\n    }\n    else\n    {\n      throw std::runtime_error(\"Failed to allocate tracking grid buffer\");\n    }\n  }\n\n  void RaycastPoints(\n      const std::vector<float>& raw_points, const float max_range,\n      const float* const grid_pointcloud_transform,\n      const float inverse_step_size, const float inverse_cell_size,\n      const int32_t num_x_cells, const int32_t num_y_cells,\n      const int32_t num_z_cells, TrackingGridsHandle& tracking_grids,\n      const size_t tracking_grid_index) override\n  {\n    OpenCLTrackingGridsHandle& real_tracking_grids =\n        dynamic_cast<OpenCLTrackingGridsHandle&>(tracking_grids);\n\n    cl_int err = 0;\n\n    cl::Buffer device_points_buffer(\n        *context_, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR,\n        sizeof(float) * raw_points.size(),\n        const_cast<void*>(static_cast<const void*>(raw_points.data())),\n        &err);\n    if (err != CL_SUCCESS)\n    {\n      throw std::runtime_error(\"Failed to allocate and copy pointcloud\");\n    }\n\n    cl::Buffer device_grid_pointcloud_transform_buffer(\n        *context_, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR,\n        sizeof(float) * 16,\n        const_cast<void*>(static_cast<const void*>(grid_pointcloud_transform)),\n        &err);\n    if (err != CL_SUCCESS)\n    {\n      throw std::runtime_error(\n          \"Failed to allocate and copy grid pointcloud transform\");\n    }\n\n    const int32_t stride1 = num_y_cells * num_z_cells;\n    const int32_t stride2 = num_z_cells;\n    const int32_t starting_index = static_cast<int32_t>(\n        real_tracking_grids.GetTrackingGridStartingOffset(tracking_grid_index));\n    // Build kernel\n    cl::Kernel raycasting_kernel(*raycasting_program_, \"RaycastPoint\");\n    raycasting_kernel.setArg(0, device_points_buffer);\n    raycasting_kernel.setArg(1, max_range);\n    raycasting_kernel.setArg(2, device_grid_pointcloud_transform_buffer);\n    raycasting_kernel.setArg(3, inverse_step_size);\n    raycasting_kernel.setArg(4, inverse_cell_size);\n    raycasting_kernel.setArg(5, stride1);\n    raycasting_kernel.setArg(6, stride2);\n    raycasting_kernel.setArg(7, num_x_cells);\n    raycasting_kernel.setArg(8, num_y_cells);\n    raycasting_kernel.setArg(9, num_z_cells);\n    raycasting_kernel.setArg(10, real_tracking_grids.GetBuffer());\n    raycasting_kernel.setArg(11, starting_index);\n    err = queue_->enqueueNDRangeKernel(\n        raycasting_kernel, cl::NullRange, cl::NDRange(raw_points.size() / 3),\n        cl::NullRange);\n    if (err != CL_SUCCESS)\n    {\n      throw std::runtime_error(\"Failed to enqueue raycasting kernel\");\n    }\n  }\n\n  std::unique_ptr<FilterGridHandle> PrepareFilterGrid(\n      const int64_t num_cells, const void* host_data_ptr) override\n  {\n    cl_int err = 0;\n    std::unique_ptr<cl::Buffer> filter_grid_buffer(new cl::Buffer(\n        *context_, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR,\n        sizeof(float) * num_cells * 2, const_cast<void*>(host_data_ptr), &err));\n    if (err != CL_SUCCESS)\n    {\n      throw std::runtime_error(\"Failed to allocate and copy filtered buffer\");\n    }\n\n    return std::unique_ptr<FilterGridHandle>(new OpenCLFilterGridHandle(\n        std::move(filter_grid_buffer), num_cells));\n  }\n\n  void FilterTrackingGrids(\n      const TrackingGridsHandle& tracking_grids, const float percent_seen_free,\n      const int32_t outlier_points_threshold,\n      const int32_t num_cameras_seen_free,\n      FilterGridHandle& filter_grid) override\n  {\n    const OpenCLTrackingGridsHandle& real_tracking_grids =\n        dynamic_cast<const OpenCLTrackingGridsHandle&>(tracking_grids);\n    OpenCLFilterGridHandle& real_filter_grid =\n        dynamic_cast<OpenCLFilterGridHandle&>(filter_grid);\n\n    // Build kernel\n    cl::Kernel filter_kernel(*filter_program_, \"FilterGrids\");\n    filter_kernel.setArg(\n        0, static_cast<int32_t>(real_tracking_grids.NumCellsPerGrid()));\n    filter_kernel.setArg(\n        1, static_cast<int32_t>(real_tracking_grids.GetNumTrackingGrids()));\n    filter_kernel.setArg(2, real_tracking_grids.GetBuffer());\n    filter_kernel.setArg(3, real_filter_grid.GetBuffer());\n    filter_kernel.setArg(4, percent_seen_free);\n    filter_kernel.setArg(5, outlier_points_threshold);\n    filter_kernel.setArg(6, num_cameras_seen_free);\n    const cl_int err = queue_->enqueueNDRangeKernel(\n        filter_kernel, cl::NullRange,\n        cl::NDRange(real_tracking_grids.NumCellsPerGrid()), cl::NullRange);\n    if (err != CL_SUCCESS)\n    {\n      throw std::runtime_error(\n          \"Failed to enqueue filter kernel [\" + std::to_string(err) + \"]\");\n    }\n  }\n\n  void RetrieveTrackingGrid(\n      const TrackingGridsHandle& tracking_grids,\n      const size_t tracking_grid_index, void* host_data_ptr) override\n  {\n    const OpenCLTrackingGridsHandle& real_tracking_grids =\n        dynamic_cast<const OpenCLTrackingGridsHandle&>(tracking_grids);\n\n    queue_->finish();\n    const size_t item_size = sizeof(int32_t) * 2;\n    const size_t tracking_grid_size =\n        real_tracking_grids.NumCellsPerGrid() * item_size;\n    const size_t starting_offset =\n        real_tracking_grids.GetTrackingGridStartingOffset(tracking_grid_index)\n        * sizeof(int32_t);\n    const cl_int err = queue_->enqueueReadBuffer(\n        real_tracking_grids.GetBuffer(), CL_TRUE, starting_offset,\n        tracking_grid_size, host_data_ptr);\n    if (err != CL_SUCCESS)\n    {\n      throw std::runtime_error(\"Tracking buffer enqueueReadBuffer failed\");\n    }\n  }\n\n  void RetrieveFilteredGrid(\n      const FilterGridHandle& filter_grid, void* host_data_ptr) override\n  {\n    const OpenCLFilterGridHandle& real_filter_grid =\n        dynamic_cast<const OpenCLFilterGridHandle&>(filter_grid);\n\n    queue_->finish();\n    const size_t item_size = sizeof(float) * 2;\n    const size_t buffer_size = real_filter_grid.NumCells() * item_size;\n    const cl_int err = queue_->enqueueReadBuffer(\n        real_filter_grid.GetBuffer(), CL_TRUE, 0, buffer_size, host_data_ptr);\n    if (err != CL_SUCCESS)\n    {\n      throw std::runtime_error(\"Filtered buffer enqueueReadBuffer failed\");\n    }\n  }\n\nprivate:\n  std::unique_ptr<cl::Context> context_;\n  std::unique_ptr<cl::CommandQueue> queue_;\n  std::unique_ptr<cl::Program> raycasting_program_;\n  std::unique_ptr<cl::Program> filter_program_;\n};\n\nstd::vector<AvailableDevice> GetAvailableDevices()\n{\n  std::vector<AvailableDevice> available_devices;\n\n  std::vector<cl::Platform> platforms;\n  cl::Platform::get(&platforms);\n\n  for (size_t platform_idx = 0; platform_idx < platforms.size(); platform_idx++)\n  {\n    const auto& platform = platforms.at(platform_idx);\n    std::string platform_name;\n    platform.getInfo(CL_PLATFORM_NAME, &platform_name);\n    std::string platform_vendor;\n    platform.getInfo(CL_PLATFORM_VENDOR, &platform_vendor);\n\n    std::vector<cl::Device> devices;\n    platform.getDevices(CL_DEVICE_TYPE_ALL, &devices);\n\n    for (size_t device_idx = 0; device_idx < devices.size(); device_idx++)\n    {\n      const auto& device = devices.at(device_idx);\n      std::string device_name;\n      device.getInfo(CL_DEVICE_NAME, &device_name);\n\n      const std::string full_name =\n          \"OpenCL - Platform name: [\" + platform_name + \"] Vendor: [\"\n          + platform_vendor + \"] Device: [\" + device_name + \"]\";\n\n      std::map<std::string, int32_t> device_options;\n      device_options[\"OPENCL_PLATFORM_INDEX\"] =\n          static_cast<int32_t>(platform_idx);\n      device_options[\"OPENCL_DEVICE_INDEX\"] = static_cast<int32_t>(device_idx);\n\n      available_devices.push_back(AvailableDevice(full_name, device_options));\n    }\n  }\n\n  return available_devices;\n}\n\nstd::unique_ptr<DeviceVoxelizationHelperInterface>\nMakeOpenCLVoxelizationHelper(const std::map<std::string, int32_t>& options)\n{\n  return std::unique_ptr<DeviceVoxelizationHelperInterface>(\n      new OpenCLVoxelizationHelperInterface(options));\n}\n}  // namespace opencl_helpers\n}  // namespace pointcloud_voxelization\n}  // namespace voxelized_geometry_tools\n", "meta": {"hexsha": "4cf7da499e2ae8ab300bceadf14bfe1cfdbd4213", "size": 21319, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/voxelized_geometry_tools/opencl_voxelization_helpers.cc", "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": "src/voxelized_geometry_tools/opencl_voxelization_helpers.cc", "max_issues_repo_name": "ToyotaResearchInstitute/voxelized_geometry_tools", "max_issues_repo_head_hexsha": "3928899e8493b9a812bb7b0998fd5fe9a5c98b8f", "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": "src/voxelized_geometry_tools/opencl_voxelization_helpers.cc", "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": 35.8905723906, "max_line_length": 80, "alphanum_fraction": 0.6624138093, "num_tokens": 5141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267660487573, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.49177205345808356}}
{"text": "#include \"Synthesiser.h\"\n#include <boost/timer.hpp>\n#include <set>\n#include <Eigen/QR>\n#include <Eigen/Eigenvalues>\n\nnamespace abstract{\n\n/// Constructs an empty buffer\ntemplate<class scalar>\nSynthesiser<scalar>::Synthesiser(int dimension,int idimension) :\n  CegarSystem<scalar>(dimension,idimension),\n  m_closedLoop(dimension),\n  m_synthType(eEigenSynth)\n{}\n\n/// Returns the nullSpace vectors of U_1^T(A-\\lambda_iI) where B=[U_0 U_1][Z,0]\ntemplate<class scalar>\nstd::vector<typename Synthesiser<scalar>::MatrixS> Synthesiser<scalar>::getNullSpace(const MatrixC &eigenValues)\n{\n  MatrixS B1=m_sensitivity.block(0,0,m_sensitivity.rows(),m_fdimension);\n  SolverMatrixType B1ref;\n  interToRef(B1ref,B1);\n  Eigen::HouseholderQR<SolverMatrixType> senseQR(B1ref);\n  SolverMatrixType U0U1=senseQR.householderQ();\n  SolverMatrixType U1Tref=U0U1.block(0,m_fdimension,m_dimension,m_dimension-m_fdimension).transpose();\n  MatrixC U1T(m_dimension,m_dimension-m_fdimension);\n  MatrixS U1Treal;\n  refToInter(U1Treal,U1Tref);\n  U1T.real()=U1Treal;\n  U1T.imag()=MatrixS::Zero(m_dimension,m_dimension-m_fdimension);\n  MatrixC complexDynamics(m_dimension,m_dimension);\n  complexDynamics.real()=m_dynamics;\n  complexDynamics.imag()=MatrixS::Zero(m_dimension,m_dimension);\n  std::vector<MatrixS> result(m_dimension);\n  for (int i=0;i<m_dimension;i++) {\n    MatrixC nullSpace=U1T*(complexDynamics-eigenValues.coeff(i,i)*MatrixC::Identity(m_dimension,m_dimension));\n    this->toRREF(nullSpace);\n    std::vector<bool> vars(nullSpace.cols());\n    int row=0;\n    int freeVars=nullSpace.cols();\n    for (int col=0;col<nullSpace.cols();col++) {\n      vars[col]=true;\n      if (!func::isZero(norm(nullSpace.coeff(row,col)))) {\n        vars[col]=false;\n        row++;\n        freeVars--;\n      }\n    }\n    result[i].resize(m_dimension,freeVars);\n    int col=0;\n    for (int j=0;j<nullSpace.cols();j++) {\n      if (vars[j]) {\n        result[i].row(j)=MatrixS::Zero(1,freeVars);\n        result[i].coeffRef(j,col)=this->ms_one;\n      }\n      else {\n        int pos=0;\n        for (int k=0;k<nullSpace.cols();k++) {\n          if (vars[k]) result[i].coeffRef(j,pos++)=-nullSpace.coeff(j,k).real();\n        }\n      }\n    }\n    if (m_conjugatePair[i]>i) {\n      i++;\n      result[i].resize(m_dimension,freeVars);\n      int col=0;\n      for (int j=0;j<nullSpace.cols();j++) {\n        if (vars[j]) {\n          result[i].row(j)=MatrixS::Zero(1,freeVars);\n          result[i].coeffRef(j,col)=this->ms_one;\n        }\n        else {\n          int pos;\n          for (int k=0;k<nullSpace.cols();k++) {\n            if (vars[k]) result[i].coeffRef(j,pos++)=-nullSpace.coeff(j,k).imag();\n          }\n        }\n      }\n    }\n  }\n  return result;\n}\n\n/// Returns a tranformation of the eigenvector inequalities into their corresponding nullSpace coefficients\ntemplate<class scalar>\ntypename Synthesiser<scalar>::MatrixS Synthesiser<scalar>::getNullSpaceFaces(MatrixS &faces,std::vector<MatrixS> &nullSpace)\n{\n  nullSpace=getNullSpace(m_closedLoop.getEigenValues());\n  int nullSpaceDim=0;\n  for (int i=0;i<m_dimension;i++) nullSpaceDim+=nullSpace[i].cols();\n  MatrixS result=MatrixS::Zero(faces.rows(),nullSpaceDim);\n  int pos=0;\n  for (int i=0;i<m_dimension;i++) {\n    for (int k=0;k<nullSpace[i].cols();k++,pos++)\n    {\n      for (int j=0;j<m_dimension;j++) {\n        result.col(pos)+=faces.col(i*m_dimension+j)*nullSpace[i].coeff(j,k);\n      }\n    }\n  }\n  return result;\n}\n\n/// Solves the Sylvester equation AX+XB=C for X\ntemplate<class scalar>\ntypename Synthesiser<scalar>::MatrixS Synthesiser<scalar>::solveSylvester(const MatrixS &A,const MatrixS &B,const MatrixS &C,bool BisDiagonal)\n{\n  MatrixS U,V;\n  SolverMatrixType refA,refB;\n  interToRef(refA,A);\n  interToRef(refB,B);\n  Eigen::RealSchur<SolverMatrixType> realSchur(refA.transpose());\n  refToInter(U,realSchur.matrixU());//We want transposed so keep it this way\n  refA=realSchur.matrixT().transpose();//Lower triangular\n  if (BisDiagonal) {\n    V=MatrixS::Identity(C.rows(),refB.rows());\n  }\n  else {\n    interToRef(refB,B);\n    realSchur.compute(refB);\n    refToInter(V,realSchur.matrixU());\n    refB=realSchur.matrixT();\n  }\n  MatrixS result=U*C*V;\n  for (int row=0;row<result.rows();row++) {\n    for (int col=0;col<result.cols();col++) {\n      for (int i=0;i<row;i++) {\n        result.coeffRef(row,col)-=refA.coeff(row,i)*result.coeff(i,col);\n      }\n      for (int i=0;i<col;i++) {\n        result.coeffRef(row,col)-=result.coeff(row,i)*refB.coeff(i,col);\n      }\n      result.coeffRef(row,col)/=refA.coeff(row,row)+refB.coeff(col,col);\n    }\n  }\n  return result;\n}\n\n/// Retrieves a set of viable Left Eigenvectors for given eigenvalues\ntemplate<class scalar>\ntypename Synthesiser<scalar>::MatrixS Synthesiser<scalar>::getValidLeftEigenVectors(const MatrixS &pseudoEigenValues,const MatrixS &desired)\n{\n  MatrixS S=desired.inverse();//TODO:may be transposed\n  MatrixS B=m_sensitivity.leftCols(m_fdimension);\n  bool hasInverse=false;\n  MatrixS invB=this->getSVDpseudoInverse(B,hasInverse);\n  MatrixS C=-B*invB*(m_dynamics*S-S*pseudoEigenValues);//-BP\n  S=solveSylvester(m_dynamics,pseudoEigenValues,C,true);\n  return S.inverse();//TODO:may be transposed\n}\n\n/// Retrieves a set of viable Left Eigenvectors for given eigenvalues\ntemplate<class scalar>\ntypename Synthesiser<scalar>::MatrixS Synthesiser<scalar>::getLeftEigenVectors(const MatrixS &pseudoEigenValues,AbstractPolyhedra<scalar> &eigenVectorSpace)\n{\n  UNUSED(pseudoEigenValues);\n  UNUSED(eigenVectorSpace);\n}\n\n/// Retrieves constraints on the controller coefficients based on the I/O constraints\ntemplate<class scalar>\nAbstractPolyhedra<scalar> Synthesiser<scalar>::getControllerInBounds(AbstractPolyhedra<scalar>& reachTube)\n{\n  MatrixS &vertices=reachTube.getVertices();\n  MatrixS directions=m_inputs.getDirections();\n  directions.conservativeResize(m_fdimension,directions.cols());\n  MatrixS faces(vertices.rows()*directions.cols(),vertices.cols()*m_fdimension);\n  MatrixS supports(vertices.rows()*directions.cols(),1);\n  MatrixS inputSupports=m_inputs.getSupports();\n  for (int row=0;row<vertices.rows();row++) {\n    for (int col=0;col<directions.cols();col++) {\n      for (int i=0;i<m_fdimension;i++) {\n        for (int j=0;j<vertices.cols();j++) {\n          faces.coeffRef(row*directions.cols()+col,i*vertices.cols()+j)=vertices.coeff(row,j)*directions.coeff(i,col);\n        }\n      }\n      supports.coeffRef(row*directions.cols()+col)=inputSupports.coeff(col,0);\n    }\n  }\n  AbstractPolyhedra<scalar> result(vertices.cols()*m_fdimension);\n  result.load(faces,supports);\n  return result;\n}\n\n/// Retrieves constraints on the controller coefficients based on the Dynamic constraints\ntemplate<class scalar>\nAbstractPolyhedra<scalar> Synthesiser<scalar>::getControllerDynBounds(AbstractPolyhedra<scalar>& reachTube,int &orBlockSize)\n{\n  //max((I-A-BK)Sv)>max(Rv) -> +p_R+p_S((A-I)^T)<-p_S(BK)\n  //(A-I)S-R>-SBK -> -\\sum(bji)k_{lj}S_lV_l < (A-I)Sv-B_nR_nv\n  MatrixS templates=reachTube.getDirections();\n\n  MatrixS dynamics=m_dynamics;\n  for (int i=0;i<m_dimension;i++) dynamics.coeffRef(i,i)-=ms_one;\n  MatrixS aDirections=dynamics.transpose()*templates;\n  MatrixS inDirections=m_sensitivity.transpose()*templates;\n  MatrixS aSupports;\n  reachTube.maximiseAll(aDirections,aSupports);\n\n  if (!m_reference.isEmpty()) {\n    MatrixS inSupports;\n    m_reference.maximiseAll(inDirections,inSupports);\n    aSupports-=inSupports;\n  }\n\n  MatrixS &vertices=reachTube.getVertices();\n  orBlockSize=vertices.rows();\n  MatrixS supports(aSupports.rows()*vertices.rows(),1);\n  MatrixS faces(supports.rows(),m_feedback.rows()*m_feedback.cols());\n  MatrixS coefficients=templates.transpose()*m_sensitivity;\n  for (int row=0;row<templates.cols();row++) {\n    for (int i=0;i<orBlockSize;i++) {\n      for (int j=0;j<m_feedback.rows();j++) {\n        faces.block(row*orBlockSize+i,j*m_dimension,1,m_dimension)=coefficients.coeff(row,j)*vertices.row(i);\n      }\n      supports.coeffRef(row*orBlockSize+i,0)=aSupports.coeff(row,0);\n    }\n  }\n  AbstractPolyhedra<scalar> result(faces.cols());\n  result.load(faces,supports);\n  return result;\n}\n\n/// Synthetises the input that leads to a given reach tube\ntemplate<class scalar>\nAbstractPolyhedra<scalar> Synthesiser<scalar>::synthesiseInputs(inputType_t inputType,int precision,AbstractPolyhedra<scalar> &init,AbstractPolyhedra<scalar> &end,AbstractPolyhedra<scalar> &dynamics,MatrixS& templates,refScalar tightness)\n{\n  const MatrixS vectors=end.getDirections();\n  MatrixS preSupports=end.getSupports();\n  MatrixS abstractVectors,supports;\n  dynamics.toInner(true);\n  if (inputType==eVariableInputs) {\n    MatrixS roundVectors;\n    getRoundedDirections(roundVectors,vectors);\n    MatrixS combinedVectors(vectors.rows()+roundVectors.rows(),vectors.cols());\n    combinedVectors.block(0,0,vectors.rows(),vectors.cols())=vectors;\n    combinedVectors.block(vectors.rows(),0,roundVectors.rows(),roundVectors.cols())=roundVectors;\n    MatrixS abstractRoundedVectors=dynamics.getSynthVertices(combinedVectors,m_conjugatePair,m_jordanIndex);\n    abstractVectors=abstractRoundedVectors.block(0,0,abstractRoundedVectors.rows(),m_dimension);\n    init.maximiseAll(abstractVectors.transpose(),supports);\n    int factor=supports.rows()/vectors.cols();\n    for (int row=0;row<supports.rows();row++) {\n      supports.coeffRef(row,0)=preSupports.coeff(row/factor,0)-supports.coeff(row,0);\n    }\n    AbstractPolyhedra<scalar> tempResult(roundVectors.rows());\n    int roundDirs=roundVectors.rows();\n    int outRows=abstractRoundedVectors.rows();\n    tempResult.m_faces=abstractRoundedVectors.block(0,m_dimension,outRows,roundDirs);\n    tempResult.m_faces.conservativeResize(outRows+roundDirs,roundDirs);\n    supports.conservativeResize(outRows+roundDirs,1);\n    tempResult.m_faces.block(outRows,0,roundDirs,roundDirs)=-MatrixS::Identity(roundDirs,roundDirs);\n    supports.block(outRows,0,roundDirs,1)=MatrixS::Zero(roundDirs,1);\n    tempResult.load(tempResult.m_faces,supports);\n    tempResult.toInner(true);\n    tempResult.retemplate(templates,-tightness);//templog?\n    MatrixS subTemplates;\n    std::vector<bool> isRound;\n    this->findRoundIndices(isRound);\n    int newRow=0;\n    abstractVectors=tempResult.m_faces;\n    supports=tempResult.m_supports;\n    for (int row=0;row<abstractVectors.rows();row++) {\n      bool keep=true;\n      for (int col=0;col<isRound.size();col++) {\n        if (isRound[col] && (func::hardSign(abstractVectors.coeff(row,col))<0)) keep=false;\n      }\n      if (keep) {\n        abstractVectors.row(newRow)=abstractVectors.row(row);\n        supports.row(newRow)=supports.row(row);\n        newRow++;\n      }\n    }\n    abstractVectors.conservativeResize(newRow,abstractVectors.cols());\n    supports.conservativeResize(newRow,1);\n\n    abstractVectors*=this->m_invIminF.transpose();\n    ms_logger.logData(abstractVectors,\"deccelerated rounded:\");//templog\n    for (int col=0;col<m_dimension;col++) {\n      int mult=(m_conjugatePair[col]<0) ? 1 : 2;\n      int subDim=mult;\n      while(m_jordanIndex[col+subDim]>0) subDim+=mult;\n      if (subDim>1) {\n        this->makeSphericalTemplates(precision,subDim,subTemplates,true);\n        int oldRows=abstractVectors.rows();\n        int oldCols=abstractVectors.cols();\n        abstractVectors.conservativeResize(oldRows*subTemplates.cols(),oldCols+subDim-1);\n        supports.conservativeResize(oldRows*subTemplates.cols(),1);\n        if (col+1<oldCols) {\n          abstractVectors.block(0,col+subDim,oldRows,oldCols-col-1)=abstractVectors.block(0,col+1,oldRows,oldCols-col-1);\n        }\n        for (int i=1;i<subTemplates.cols();i++) {\n          abstractVectors.block(i*oldRows,0,oldRows,col)=abstractVectors.block(0,0,oldRows,col);//All columns before this column stay the same\n          if (col+1<oldCols) {\n            abstractVectors.block(i*oldRows,col+subDim,oldRows,oldCols-col-1)=abstractVectors.block(0,col+subDim,oldRows,oldCols-col-1);//All columns after this block stay the same\n          }\n          supports.block(i*oldRows,0,oldRows,1)=supports.block(0,0,oldRows,1);\n          for (int j=0;j<oldRows;j++)\n          {\n            abstractVectors.block(i*oldRows+j,col,1,subDim)=subTemplates.col(i).transpose()*abstractVectors.coeff(j,col);\n          }\n        }\n        for (int j=0;j<oldRows;j++)\n        {\n          abstractVectors.block(j,col,1,subDim)=subTemplates.col(0).transpose()*abstractVectors.coeff(j,col);\n        }\n        col+=subDim-1;\n      }\n    }\n  }\n  else {\n    abstractVectors=dynamics.getSynthVertices(vectors,m_conjugatePair,m_jordanIndex);\n    init.maximiseAll(abstractVectors.transpose(),supports);\n    int factor=supports.rows()/vectors.cols();\n    for (int row=0;row<supports.rows();row++) {\n      supports.coeffRef(row,0)=preSupports.coeff(row/factor,0)-supports.coeff(row,0);\n    }\n    for (int row=0;row<supports.rows();row++) {\n      abstractVectors.row(row)=vectors.col(row/factor).transpose()-abstractVectors.row(row);\n    }\n  }\n  AbstractPolyhedra<scalar> result(m_dimension);\n  result.load(abstractVectors,supports);\n  if (inputType==eParametricInputs) result.transform(this->m_pseudoIminJ,this->m_pseudoInvIminJ);\n\n  //result.retemplate(templates,-tightness);\n  return result;\n}\n\n/// Synthetises the input that leads to a given reach tube\ntemplate<class scalar>\nAbstractPolyhedra<scalar> Synthesiser<scalar>::synthesiseInitialState(inputType_t inputType,AbstractPolyhedra<scalar> &input,AbstractPolyhedra<scalar> &end,AbstractPolyhedra<scalar> &dynamics)\n{\n  MatrixS vectors=end.getDirections();\n  MatrixS abstractVectors=dynamics.getSynthVertices(vectors,m_conjugatePair,m_jordanIndex);\n  MatrixS supports;\n  MatrixS preSupports=end.getSupports();\n  if(inputType==eNoInputs) {\n    for (int row=0;row<abstractVectors.rows();row++) {\n      supports.coeffRef(row,0)=preSupports.coeff(row%preSupports.rows(),0);\n    }\n  }\n  else {\n    MatrixS abstractInputVectors=-abstractVectors;\n    for (int row=0;row<abstractInputVectors.rows();row++) {\n      abstractInputVectors.row(row)+=vectors.col(row%vectors.cols()).transpose();\n    }\n    input.maximiseAll(abstractVectors,supports);\n    for (int row=0;row<supports.rows();row++) {\n      supports.coeffRef(row,0)=preSupports.coeff(row%preSupports.rows(),0)-supports.coeff(row,0);\n    }\n  }\n  AbstractPolyhedra<scalar> result(m_dimension);\n  result.load(abstractVectors,supports);\n  return result;\n}\n\n/// Synthetises the eigenstructure of a pole location\ntemplate<class scalar>\nAbstractPolyhedra<scalar> Synthesiser<scalar>::synthesiseEigenStructure(inputType_t inputType,int precision,int directions,AbstractPolyhedra<scalar> &end,AbstractPolyhedra<scalar> &dynamics)\n{\n  UNUSED(precision);\n  AbstractPolyhedra<scalar>& init=m_initialState.getPolyhedra();\n  MatrixS& templates=getTemplates(eNormalSpace,directions);\n  const MatrixS& vertices=init.getVertices();\n  const MatrixS& lambdas=dynamics.getVertices();\n  const MatrixS& final=end.getVertices();\n  if ((vertices.rows()<=0) || (lambdas.rows()<0) || (final.rows()<0)) processError(end.getName());\n  MatrixS abstractVectors,combinedAbstractVectors;\n  MatrixS finalVectors=kronecker(templates,final,true);//templates*final\n  if (inputType==eVariableInputs) {\n    MatrixS roundVectors;\n    getRoundedDirections(roundVectors,templates);\n    MatrixS combinedRoundVectors(templates.cols()+roundVectors.rows(),templates.rows());\n    combinedRoundVectors.block(0,0,templates.cols(),templates.rows())=templates.transpose();\n    combinedRoundVectors.block(templates.cols(),0,roundVectors.rows(),roundVectors.cols())=roundVectors;\n    combinedAbstractVectors=dynamics.getSynthVertices(combinedRoundVectors,m_conjugatePair,m_jordanIndex);\n    abstractVectors=combinedAbstractVectors.block(0,0,combinedAbstractVectors.rows(),m_dimension);\n  }\n  else abstractVectors=dynamics.getSynthVertices(templates,m_conjugatePair,m_jordanIndex);//templates*lambdas\n  MatrixS combinedVectors=kronecker(abstractVectors,vertices);//templates*lambdas*vertices\n  MatrixS combinedInputVectors(0,0);\n  int numInputs=1;\n  if (inputType>eNoInputs) {\n    AbstractPolyhedra<scalar> &inputsSource=m_transformedInputs.getPolyhedra();\n    const MatrixS& inputVertices=(inputType==eParametricInputs) ? inputsSource.getVertices() : inputsSource.getCentre();\n    numInputs=inputVertices.rows();\n    if (inputVertices.rows()<=0) processError(inputsSource.getName());\n    //The synth vectors are multiplied by the transpose of the acceleration matrix\n    MatrixS accelInputVectors=abstractVectors*this->m_pseudoInvIminJ;\n    MatrixS accelInputVertices=inputVertices;\n    if (m_hasOnes && (m_inputType==eVariableInputs)) {\n      for (int i=0;i<accelInputVertices.cols();i++) {\n        if (m_isOne[i]) accelInputVertices.coeffRef(i,0)=0;\n      }\n    }\n    combinedInputVectors=kronecker(accelInputVectors,accelInputVertices);//templates*lambdas*inputVertices\n  }\n  int maxValues=finalVectors.cols()*finalVectors.rows();\n  MatrixS faces(final.rows()*combinedVectors.rows()*numInputs+2*maxValues,finalVectors.cols());\n  for (int i=0;i<templates.cols();i++) {\n    for (int j=0;j<final.rows();j++) {\n      int finalBlock=i*final.rows()+j;\n      for (int k=0;k<lambdas.rows();k++) {\n        int lambdaBlock=i*lambdas.rows()+k;\n        for (int l=0;l<vertices.rows();l++) {\n          int rowBlock=(i*lambdas.rows()+k)*vertices.rows()+l;\n          rowBlock*=numInputs;\n          for (int m=0;m<numInputs;m++) {\n            int row=(rowBlock+m)*final.rows()+j;\n            faces.row(row)=combinedVectors.row(lambdaBlock*vertices.rows()+l)-finalVectors.row(finalBlock);\n          }\n        }\n      }\n    }\n  }\n  if (inputType==eVariableInputs) {\n  }\n  MatrixS supports=MatrixS::Zero(faces.rows(),1);\n  int ineqSize=final.rows()*combinedVectors.rows()*numInputs;\n  faces.block(ineqSize,0,2*maxValues,finalVectors.cols())=MatrixS::Zero(2*maxValues,finalVectors.cols());\n  supports.block(ineqSize,0,2*maxValues,1)=MatrixS::Ones(2*maxValues,1);\n  for (int i=0;i<finalVectors.cols();i++) {\n    faces.block(ineqSize+i*finalVectors.rows(),i,finalVectors.rows(),1)=MatrixS::Ones(finalVectors.rows(),1);\n    faces.block(ineqSize+maxValues+i*finalVectors.rows(),i,finalVectors.rows(),1)=-MatrixS::Ones(finalVectors.rows(),1);\n  }\n  //std::vector<MatrixS> &nullSpace;\n  //faces=getNullSpaceFaces(faces,nullSpace);\n  AbstractPolyhedra<scalar> result(faces.cols());\n  result.load(faces,supports);\n  result.logTableau();\n  result.FindFeasOrBasis(finalVectors.rows());\n  ms_logger.logData(result.m_basisInverse);\n  return result;\n}\n\n/// Synthetises an input/state polyhedra given a set of conditions\ntemplate<class scalar>\nbool Synthesiser<scalar>::loadSynthesisedResult(synthesisType_t type, AbstractPolyhedra<scalar> &result,MatrixS& templates,refScalar tightness,int time)\n{\n    boost::timer timer;\n    result.toInner(true);\n    if (ms_trace_dynamics>=eTraceDynamics) {\n      result.logTableau(\"Transformed Synth inputs\");\n    }\n    result.retemplate(templates,-tightness);\n    m_reachTime=time+timer.elapsed()*1000;;\n    result.setCalculationTime(time);\n    if (ms_trace_time) ms_logger.logData(m_reachTime,\"Synthesis Time: \",true);\n    switch(type)\n    {\n    case eInitSynth:\n      m_initialState.load(result,ms_emptyMatrix,ms_emptyMatrix,eEigenSpace);\n      break;\n    case eInputSynth:\n      m_transformedInputs.load(result,ms_emptyMatrix,ms_emptyMatrix,eEigenSpace);\n      result.transform(m_pseudoEigenVectors,m_invPseudoEigenVectors);\n      this->m_inputs.copy(result);\n      this->m_inputs.transform(ms_emptyMatrix,this->m_sensitivity);\n      break;\n    case eSensitivitySynth:\n      break;\n    default:\n      break;\n    }\n  return true;\n}\n\n/// Synthesises a bound on the dynamics given a known guard and eigenvectors.\ntemplate<class scalar>\nAbstractPolyhedra<scalar> Synthesiser<scalar>::synthesiseDynamicBounds(inputType_t inputType,AbstractPolyhedra<scalar> &end)\n{\n  setInputType(inputType);\n  MatrixS vectors;\n  int numVertices;\n  getAbstractVertices(end.getDirections(),vectors,numVertices);\n  vectors.transposeInPlace();\n  MatrixS supports(vectors.rows(),1);\n  MatrixS endSupports=end.getSupports();\n  int perTemplate=supports.rows()/endSupports.rows();\n  for (int i=0;i<endSupports.rows();i++)\n  {\n    for (int j=0;j<perTemplate;j++) {\n      supports.coeffRef(i*perTemplate+j,0)=endSupports.coeff(i,0);\n    }\n  }\n  if (m_inputType>eNoInputs) {\n    MatrixS inSupports=m_accelVertices*end.getDirections();\n    demergeAccelInSupports(supports,inSupports,endSupports.rows());\n  }\n  AbstractPolyhedra<scalar> bounds;\n  bounds.load(vectors,supports);\n  bounds.removeRedundancies();\n  return bounds;\n}\n\n/// Corrects the support set by the input offset\ntemplate <class scalar>\nvoid Synthesiser<scalar>::demergeAccelInSupports(MatrixS &supports,MatrixS &inSupports,int numTemplates)\n{\n  if (!m_hasOnes || (m_inputType==eVariableInputs))  {\n    for (int row=0;row<numTemplates;row++) {\n      int pos=row*m_numVertices;\n      supports.coeffRef(pos,0)-=inSupports.coeff(0,row);\n      for (int point=1;point<m_numVertices;point++) {\n        supports.coeffRef(pos+point,0)-=inSupports.coeff(point%inSupports.rows(),row);\n      }\n    }\n  }\n}\n\n\n/// Retrieves the support set for the inputs\ntemplate <class scalar>\ntypename JordanMatrix<scalar>::MatrixS& Synthesiser<scalar>::getRefinedAccelInSupports()\n{\n  if (m_hasOnes && (m_inputType==eVariableInputs)) {\n    AbstractPolyhedra<scalar>& inputDynamics=getAbstractDynamics(eParametricInputs);\n    MatrixS supports;\n    inputDynamics.maximiseAll(m_abstractInputVertices,supports);\n    m_accelInSupports=supports.transpose();\n    if (ms_trace_dynamics>=eTraceAbstraction) ms_logger.logData(m_accelInSupports,\"Input Supports\",true);\n  }\n  return m_accelInSupports;\n}\n\n/// Retrieves the reach tube at the given iteration\ntemplate <class scalar>\nAbstractPolyhedra<scalar>& Synthesiser<scalar>::getRefinedAbstractReachTube(space_t space,bool guarded)\n{\n  boost::timer timer;\n  AbstractPolyhedra<scalar>& init=m_initialState.getPolyhedra(eEigenSpace);\n  AbstractPolyhedra<scalar>& dynamics=getAbstractDynamics(m_inputType);\n\n  MatrixS& templates=getTemplates(eEigenSpace);\n  if (ms_trace_time) ms_logger.logData(timer.elapsed()*1000,\"Abstract Vertices: \",true);\n  MatrixS supports;\n  if (!dynamics.maximiseAll(m_abstractVertices,supports)) processError(dynamics.getName());\n\n  if (m_inputType>eNoInputs) getRefinedAccelInSupports();\n  if (ms_trace_dynamics>=eTraceAll) {\n    traceSupports(templates,supports,dynamics,m_abstractVertices);\n  }\n  if (m_inputType>eNoInputs) {\n    mergeAccelInSupports(supports,templates.cols());\n    if (ms_trace_dynamics>=eTraceAll) {\n      ms_logger.logData(m_abstractVertices,supports,\"Combined\",true);\n    }\n  }\n  mergeAbstractSupports(templates,supports);\n  MatrixS faces=templates.transpose();\n  m_pAbstractReachTube->mergeLoad(init,faces,supports,eEigenSpace);\n  AbstractPolyhedra<scalar>& result=m_pAbstractReachTube->getPolyhedra(space);\n  if (guarded) getGuardedReachTube(result,space);\n  if (ms_trace_dynamics>=eTraceAbstraction) result.logTableau();\n  m_reachTime=timer.elapsed()*1000;\n  result.setCalculationTime(m_reachTime);\n  if (ms_trace_time) ms_logger.logData(m_reachTime,\"Abstract Reach Time: \",true);\n  return result;\n}\n\n\n/// Synthetises an input/state polyhedra given a set of conditions\ntemplate<class scalar>\nbool Synthesiser<scalar>::synthesiseAll(synthesisType_t type,powerS iteration,int precision,int directions,inputType_t inputType,space_t space,refScalar tightness)\n{\n    /// sup<v.xy>=sup(sum_i(v_ix_iy_i))=sup<vx.y>\n    /// (lr1 v1x1 + li1 v1x2) + (lr2 v2x2 + li2 v2x1)\n\n    m_reachTime=-1;\n    boost::timer timer;\n    this->setInputType(inputType);\n    if (iteration<0) iteration=-iteration;\n    if (type==eDynamicSynth) {\n      AbstractPolyhedra<scalar> &end=getGuardPoly().getPolyhedra();\n      std::set<std::string> inequalities;\n      for (int i=0;i<m_dimension;i++) {\n        std::stringstream buffer;\n        buffer << \"(lr[\" << i << \"]*lr[\" << i << \"]+li[\" << i << \"]*li[\" << i << \"])<1\";\n        inequalities.insert(buffer.str());\n        for (int j=i+1;j<m_dimension;j++) {\n          std::stringstream buffer;\n          buffer << \"(w[\" << i << \"][0]*w[\" << j << \"][0]\";\n          for (int k=1;k<m_dimension;k++) {\n            buffer << \"+w[\" << i << \"][\" << k <<\"]*w[\" << j << \"][\" << k << \"]\";\n          }\n          buffer << \")==0\";\n          inequalities.insert(buffer.str());\n        }\n      }\n      for (int i=1;i<m_dimension;i++) {\n        std::stringstream buffer;\n        buffer << \"(li[\" << i-1 << \"]+li[\" << i << \"])==0\";\n        inequalities.insert(buffer.str());\n        buffer.str(std::string());\n        buffer << \"(lr[\" << i-1 << \"]==lr[\" << i << \"]) || ((li[\" << i-1 << \"]==0) && (li[\" << i << \"]==0))\";\n        inequalities.insert(buffer.str());\n      }\n      MatrixS directions=end.getDirections();\n      MatrixS safeVertices=end.getVertices();\n      MatrixS initVertices=m_initialState.getPolyhedra().getVertices();\n      MatrixS inputVertices=m_transformedInputs.getPolyhedra().getVertices();\n      MatrixS liveVertices=m_transformedInputs.getPolyhedra().getVertices();\n      for (int i=0;i<directions.cols();i++) {\n        std::vector<std::string> rv(m_dimension);\n        MatrixS row=directions.col(i).transpose();\n        for (int k=0;k<m_dimension;k++) {\n          rv[k]=ms_logger.MakeWRow(row,k);\n        }\n        for (int input=0;input<inputVertices.rows();input++) {\n          for (int init=0;init<initVertices.rows();init++) {\n            std::string centre;\n            MatrixS mid=initVertices.row(init)-inputVertices.row(input);\n            for (int j=0;j<m_dimension;j++) mid.coeffRef(0,j)*=directions.coeff(j,i);\n            std::vector<std::string> rvr(m_dimension);\n            std::vector<std::string> rvi(m_dimension);\n            for (int k=0;k<m_dimension;k++) {\n              rvr[k]=ms_logger.MakeWRow(mid,k);\n            }\n            mid=initVertices.row(init)-inputVertices.row(input);\n            if (i+1<directions.cols()) {\n              for (int j=0;j<m_dimension;j++) mid.coeffRef(0,j)*=directions.coeff(j,i+1);\n            }\n            else mid=MatrixS::Zero(1,m_dimension);\n\n            for (int k=0;k<m_dimension;k++) {\n              rvi[k]=ms_logger.MakeWRow(mid,k);\n            }\n            std::stringstream buffer;\n            buffer << \"(\"<< ms_logger.MakeLSTerm(\"lr\",0,rvr[0]);;\n            if (rvi[0]!=\"(0)\") buffer << \"+\" << ms_logger.MakeLSTerm(\"li\",0,rvi[0]);\n            for (int k=1;k<m_dimension;k++) {\n              if (rvr[k]!=\"(0)\") buffer << \"+\" << ms_logger.MakeLSTerm(\"lr\",k,rvr[k]);\n              if (rvi[k]!=\"(0)\") buffer << \"+\" << ms_logger.MakeLSTerm(\"li\",k,rvi[k]);\n            }\n            buffer << \")\";\n            centre=buffer.str();\n            std::string inequality;\n            for (int safe=0;safe<safeVertices.rows();safe++) {\n              MatrixS max=safeVertices.row(safe)-inputVertices.row(input);\n              std::stringstream buffer;\n              buffer << \"(\" << centre << \"<(\" << ms_logger.MakeSTerm(max.coeff(0,0),rv[0]);\n              for (int k=1;k<m_dimension;k++) {\n                buffer << \"+\" << ms_logger.MakeSTerm(max.coeff(0,k),rv[k]);\n              }\n              buffer << \"))\";\n              if (safe!=0) inequality+=\"\\n  || \";\n              inequality+=buffer.str();\n            }\n            inequalities.insert(inequality);\n            for (int live=0;live<liveVertices.rows();live++) {\n              MatrixS min=liveVertices.row(live)-inputVertices.row(input);\n              std::stringstream buffer;\n              buffer << \">(\" << ms_logger.MakeSTerm(min.coeff(0,0),rv[0]);\n              for (int k=1;k<m_dimension;k++) {\n                buffer << \"+\" << ms_logger.MakeSTerm(min.coeff(0,k),rv[k]);\n              }\n              buffer << \")\";\n              inequalities.insert(centre+buffer.str());\n            }\n          }\n        }\n      }\n      std::stringstream buffer;\n      buffer << \"extern float lr[\" << m_dimension << \"];\\n\";\n      buffer << \"extern float li[\" << m_dimension << \"];\\n\";\n      buffer << \"extern float w[\" << m_dimension << \"][\" << m_dimension << \"];\\n\";\n      buffer << \"void main()\\n{\";\n      std::string result=buffer.str();\n      result+=\"if (\";\n      std::set<std::string>::iterator it=inequalities.begin();\n      if (it!=inequalities.end()) {\n        result+=\"(\"+*it+\")\\n\";\n        it++;\n      }\n      for (;it!=inequalities.end();it++) result+=\" && (\"+*it+\")\\n\";\n      result+=\") {\\n    assert(0);\\n  }\\n}\\n\";\n      ms_logger.logData(result);\n      return true;\n    }\n    else if (type==eEigenSynth) {\n      m_closedLoop.getAbstractDynamics(iteration,precision,inputType);\n      AbstractPolyhedra<scalar> &end=getGuardPoly().getPolyhedra();\n      AbstractPolyhedra<scalar> eigenVectors=synthesiseEigenStructure(inputType,precision,directions,end,m_closedLoop.getAbstractDynamics(inputType));\n      eigenVectors.logTableau(\"EigenStructure:\");//templog\n    }\n    else {\n      AbstractPolyhedra<scalar> &end=getGuardPoly().getPolyhedra(eEigenSpace);\n      AbstractPolyhedra<scalar>& dynamics=getAbstractDynamics(iteration,precision,inputType);\n      MatrixS& templates=getTemplates(eEigenSpace,directions);\n      AbstractPolyhedra<scalar> &co_space=(type==eInitSynth) ? m_transformedInputs.getPolyhedra(eEigenSpace) : this->getInitialState(eEigenSpace);\n      m_reachTime=timer.elapsed()*1000;\n      if (tightness==0) tightness=1e-6;\n      if (type==eInitSynth) {\n        AbstractPolyhedra<scalar> result=synthesiseInitialState(inputType,co_space,end,dynamics);\n        return loadSynthesisedResult(type,result,templates,tightness,timer.elapsed()*1000);\n      }\n      AbstractPolyhedra<scalar> result=synthesiseInputs(inputType,precision,co_space,end,dynamics,templates,tightness);\n      return loadSynthesisedResult(type,result,templates,tightness,m_reachTime);\n    }\n    return false;\n  }\n\ntemplate <class scalar>\nint Synthesiser<scalar>::loadPoles(const std::string &data,size_t pos)\n{\n  commands_t command;\n  pos=ms_logger.getCommand(command,data,pos);\n  MatrixS poles(m_dimension,m_dimension);\n  int result=ms_logger.StringToMat(poles,data,pos);\n  ms_logger.logData(poles,\"cl dynamics\");//templog\n  m_closedLoop.loadJordan(poles);\n  return result;\n}\n\n/// Calculates the closed loop dynamics given a plant and a controller\ntemplate <class scalar>\nbool Synthesiser<scalar>::makeClosedLoop(bool useObserver,bool makeReference,bool makeNoise)\n{\n  UNUSED(useObserver);\n  MatrixS dynamics;\n  if (m_outputSensitivity.cols()>0) {\n    dynamics=m_dynamics-m_sensitivity.block(0,0,m_dimension,m_fdimension)*m_feedback*m_outputSensitivity;\n  }\n  else {\n    dynamics=m_dynamics-m_sensitivity.block(0,0,m_dimension,m_fdimension)*m_feedback;\n  }\n  int fdimension= (makeReference || (m_reference.getDimension()>0)) ? 0 : m_fdimension;\n  MatrixS sensitivity=m_sensitivity.block(0,fdimension,m_dimension,m_idimension-fdimension);\n  m_closedLoop.setInputType(eParametricInputs);\n  AbstractPolyhedra<scalar> inputs=generateFeedbackInput(fdimension,makeNoise,sensitivity);\n  if (ms_trace_dynamics>=eTraceDynamics) {\n    ms_logger.logData(dynamics,\"Loading Closed Loop\");\n  }\n  m_closedLoop.setParams(m_paramValues);\n  m_closedLoop.changeDimensions(m_dimension,sensitivity.cols(),0,0);\n  bool result=m_closedLoop.load(dynamics,sensitivity,m_guard.getPolyhedra(),m_initialState.getPolyhedra(),inputs,m_safeReachTube.getPolyhedra());\n  if (result && (ms_trace_dynamics>=eTraceDynamics)) {\n    ms_logger.logData(m_closedLoop.getDescription());\n  }\n  return result;\n}\n\ntemplate <class scalar>\nvoid Synthesiser<scalar>::processFiles(stringList &files,displayType_t displayType,space_t space,bool interval,optionList_t &options)\n{\n  for (stringList::iterator i=files.begin();i!=files.end();i++) {\n    int pos=loadFromFile(*i);\n    if (pos<0) {\n      ms_logger.logData(\"Error loading file \",false);\n      ms_logger.logData(*i);\n      continue;\n    }\n    if ((options.size()>0) && (processOptions(options,displayType,space,interval,false)<0)) continue;\n    process(displayType,space,interval);\n    while (pos<m_source.length()) {\n      pos=m_source.find('|',pos);\n      if (pos<0) break;\n      pos=load(m_source,pos+1);\n      if (pos<0) break;\n      process(displayType,space,interval,true);\n    }\n  }\n}\n\n// Processes a problem stated by the inut options\ntemplate <class scalar>\nint Synthesiser<scalar>::processOptions(optionList_t &options,displayType_t displayType,space_t space,bool interval,bool run)\n{\n  if (options.size()<=0) return 0;\n  if (options[eParamStr].size()>0) {\n    if (ms_logger.StringToDim(m_paramValues,options[eParamStr])<0) return -1;\n    if (m_paramValues.coeff(eNumBits,0)>0) {\n      functions<mpfr::mpreal>::setDefaultPrec(m_paramValues.coeff(eNumBits,0));\n    }\n    traceDynamics((traceDynamics_t)m_paramValues.coeff(eTraceLevel,0));\n    traceSimplex((traceTableau_t)m_paramValues.coeff(eTraceLevel,1),(traceVertices_t)m_paramValues.coeff(eTraceLevel,2));\n    if (m_paramValues.coeff(eNumStates,0)>0) changeDimensions(m_paramValues.coeff(eNumStates,0),m_paramValues.coeff(eNumInputs,0)+m_paramValues.coeff(eNumVarInputs,0),m_paramValues.coeff(eNumOutputs,0),m_paramValues.coeff(eNumFeedbacks,0));\n    m_sensitivity.conservativeResize(m_paramValues.coeff(eNumStates,0),m_paramValues.coeff(eNumInputs,0)+m_paramValues.coeff(eNumVarInputs,0));\n    m_inputType=(m_paramValues.coeff(eNumVarInputs,0)>0) ? eVariableInputs : ((m_paramValues.coeff(eNumInputs,0)>0) ? eParametricInputs : eNoInputs);\n  }\n  if ((options[eARMAXStr].size()>0) && (loadARMAXModel(options[eARMAXStr])<0))      return -1;\n  if ((options[eGuardStr].size()>0) && (loadGuard(options[eGuardStr])<0))           return -1;\n  if ((options[sGuardStr].size()>0) && (loadSafeReachTube(options[sGuardStr])<0))   return -1;\n  if ((options[oGuardStr].size()>0) && (loadOutputGuard(options[oGuardStr])<0))     return -1;\n  if ((options[eDynamicsStr].size()>0) && (loadDynamics(options[eDynamicsStr])<0))  return -1;\n  if ((options[eInitStr].size()>0) && (loadInitialState(options[eInitStr])<0))      return -1;\n  if ((options[iSenseStr].size()>0) && (loadSensitivities(options[iSenseStr])<0))   return -1;\n  if ((options[eInputStr].size()>0) && (loadInputs(options[eInputStr])<0))          return -1;\n  if ((options[eTemplateStr].size()>0) && (loadTemplates(options[eTemplateStr])<0)) return -1;\n  if ((options[eRefStr].size()>0) && (loadReference(options[eRefStr])<0))           return -1;\n  if ((options[eControlStr].size()>0) && (loadController(options[eControlStr])<0))  return -1;\n  if (run) process(displayType,space,interval);\n  return 0;\n}\n\ntemplate <class scalar>\nbool Synthesiser<scalar>::process(const displayType_t displayType,const space_t space,const bool interval,const bool append)\n{\n  try {\n    func::ms_isImprecise=false;\n    int iter=m_paramValues.coeff(eNumSteps,0);\n    int maxIter=m_paramValues.coeff(eNumSteps,1);\n    int stepIter=m_paramValues.coeff(eNumSteps,2);\n    if (maxIter<=0) maxIter=iter+1;\n    if (stepIter<=0) stepIter=1;\n    int precision=m_paramValues.coeff(eLogFaces,0);\n    int maxPrecision=m_paramValues.coeff(eLogFaces,1);\n    int stepPrecision=m_paramValues.coeff(eLogFaces,2);\n    if (maxPrecision<=0) maxPrecision=precision;\n    if (stepPrecision<=0) stepPrecision=1;\n    int directions=m_paramValues.coeff(eLogDirections,0);\n    int maxDirections=m_paramValues.coeff(eLogDirections,1);\n    int stepDirections=m_paramValues.coeff(eLogDirections,2);\n    if (maxDirections<=0) maxDirections=directions;\n    if (stepDirections<=0) stepDirections=1;\n    int tightness=m_paramValues.coeff(eTightness,0);\n    int maxTightness=m_paramValues.coeff(eTightness,1);\n    int stepTightness=m_paramValues.coeff(eTightness,2);\n    if (maxTightness<=0) maxTightness=tightness;\n    if (stepTightness==0) stepTightness=1;\n    int width=((maxIter-iter)/stepIter)*((maxPrecision-precision+1)/stepPrecision);\n    if (m_synthType!=eReachTubeSynth) {\n      m_dynamicParams.resize(eNumFinalParameters,0);\n      save(displayType,space,interval);\n    }\n    for (;directions<=maxDirections;directions+=stepDirections) {\n      MatrixS faces=makeLogahedralTemplates(directions,eEigenSpace).transpose();//TODO: the space in makelogahedral looks counterintuitive\n      MatrixS supports(faces.rows(),width);\n      //MatrixS dynamicSupports(0,width);\n      m_dynamicParams.resize(eNumFinalParameters,width);\n      int col=0;\n      for (iter=m_paramValues.coeff(eNumSteps,0);iter<maxIter;iter+=stepIter) {\n        for (tightness=m_paramValues.coeff(eTightness,0);tightness<=maxTightness;tightness+=stepTightness) {\n          for (precision=m_paramValues.coeff(eLogFaces,0);precision<=maxPrecision;precision+=stepPrecision) {\n            powerS iteration=iter;\n            switch(m_synthType) {\n            case eReachTubeSynth: {\n                if (iter==0) iteration=this->calculateIterations(m_initialState.getPolyhedra(eEigenSpace),m_inputType);\n                refScalar longIter=iteration;\n                getAbstractReachTube(iteration,precision,directions,m_inputType,space);\n                m_dynamicParams.coeffRef(eFinalIterations,col)=longIter;\n                m_dynamicParams.coeffRef(eFinalPrecision,col)=precision;\n                m_dynamicParams.coeffRef(eFinalLoadTime,col)=scalar(m_loadTime);\n                m_dynamicParams.coeffRef(eFinalReachTime,col)=scalar(m_reachTime);\n                supports.col(col++)=m_pAbstractReachTube->getPolyhedra(space).getSupports();\n                if (!m_safeReachTube.isEmpty()) {\n                  AbstractPolyhedra<scalar> bounds=synthesiseDynamicBounds(m_inputType,m_safeReachTube.getPolyhedra(eEigenSpace));\n                  for(int i=0;(i<5) && refineAbstractDynamics(bounds);i++) {\n                    getRefinedAbstractReachTube(space);\n                    m_dynamicParams.conservativeResize(m_dynamicParams.rows(),m_dynamicParams.cols()+1);\n                    supports.conservativeResize(supports.rows(),supports.cols()+1);\n                    m_dynamicParams.coeffRef(eFinalIterations,col)=longIter;\n                    m_dynamicParams.coeffRef(eFinalPrecision,col)=precision;\n                    m_dynamicParams.coeffRef(eFinalLoadTime,col)=scalar(m_loadTime);\n                    m_dynamicParams.coeffRef(eFinalReachTime,col)=scalar(m_reachTime);\n                    supports.col(col++)=m_pAbstractReachTube->getPolyhedra(space).getSupports();\n                  }\n                }\n              }\n              break;\n            case eCEGISSynth:\n              makeCEGISFiles();\n              break;\n            default: {\n                if (iteration==0) iteration=func::ms_infPower;\n                refScalar longIter=iteration;\n                refScalar tight=tightness;\n                tight/=100;\n                synthesiseAll(m_synthType,iteration,precision,directions,m_inputType,space,tight);\n                m_dynamicParams.resize(eNumFinalParameters,1);\n                m_dynamicParams.coeffRef(eFinalIterations,0)=longIter;\n                m_dynamicParams.coeffRef(eFinalPrecision,0)=precision;\n                m_dynamicParams.coeffRef(eFinalLoadTime,0)=scalar(m_loadTime);\n                m_dynamicParams.coeffRef(eFinalReachTime,0)=scalar(m_reachTime);\n                save(displayType,space,interval,true);\n              }\n            }\n          }\n        }\n      }\n      if (m_synthType==eReachTubeSynth) {\n        for (int row=0;row<supports.rows();row++) {\n          for (int col=0;col<supports.cols();col++) {\n            if (func::toUpper(supports.coeff(row,col))>func::ms_infPower) supports.coeffRef(row,col)=func::ms_infinity;\n          }\n        }\n        m_pAbstractReachTube->load(faces,supports,space);\n        save(displayType,space,interval,(directions>m_paramValues.coeff(eLogDirections,0)) || append);\n        if (ms_logger.ms_useConsole) {\n          ms_logger.logData(m_pAbstractReachTube->getPolyhedra(space).getDescription(displayType,interval,true));\n        }\n      }\n    }\n  }\n  catch(std::string &error) {\n    ms_logger.logData(\"Error processing \"+this->m_name);\n    ms_logger.logData(error);\n  }\n}\n\n/// Finds the statespace guard given an output guard\ntemplate <class scalar>\nAbstractPolyhedra<scalar>& Synthesiser<scalar>::calculateGuardFromOutput()\n{\n  AbstractPolyhedra<scalar>& polyhedra=m_safeReachTube.getPolyhedra();\n  m_outputGuard.getTransformedPolyhedra(polyhedra,ms_emptyMatrix,m_outputSensitivity);\n  return m_safeReachTube.getPolyhedra(eEigenSpace,true);\n}\n\n/// Loads a controller candidate for the system\ntemplate <class scalar>\nint Synthesiser<scalar>::loadController(const std::string &data,size_t pos)\n{\n  boost::timer timer;\n  commands_t command;\n  pos=ms_logger.getCommand(command,data,pos);\n  m_feedback.resize(m_idimension,(m_odimension>0) ? m_odimension : m_dimension);\n  size_t result=ms_logger.StringToMat(m_feedback,data,pos);\n  if (result>0) makeClosedLoop();\n  if (ms_trace_time) ms_logger.logData(timer.elapsed()*1000,\"Controller time:\",true);\n  return result;\n}\n\n/// Loads a reference input set for the system\ntemplate <class scalar>\nint Synthesiser<scalar>::loadReference(const std::string &data,size_t pos,bool vertices)\n{\n  boost::timer timer;\n  int result=m_reference.loadData(data,pos,vertices);\n  if (ms_trace_time) ms_logger.logData(timer.elapsed()*1000,\"Reference time:\",true);\n  return result;\n}\n\n///Creates a c header file for CEGIS\ntemplate <class scalar>\nstd::string Synthesiser<scalar>::makeCEGISHeader(bool intervals)\n{\n  std::stringstream result;\n  result << \"#define _DIMENSION \" << m_dimension << \"\\n\";\n  result << \"typedef control_floatt vectort[_DIMENSION];\\n\"\n         << \"typedef control_floatt matrixt[_DIMENSION][_DIMENSION];\\n\";\n  result << \"struct coefft\\n\"\n         << \"{\\n\"\n         << \"  vectort coeffs;\\n\";\n  if (intervals) result << \"  vectort uncertainty;\\n\";\n  result << \"};\\n\";\n  result << \"struct transformt\\n\"\n         << \"{\\n\"\n         << \"  control_floatt coeffs[_DIMENSION][_DIMENSION];\\n\";\n  if (intervals) result << \"  control_floatt uncertainty[_DIMENSION][_DIMENSION];\\n\";\n  result << \"};\\n\";\n  return result.str();\n}\n\n///Creates a c header file for CEGIS\ntemplate <class scalar>\nstd::string Synthesiser<scalar>::makeCEGISDescription(bool intervals)\n{\n  std::stringstream result;\n  MatrixS T=getReachableCanonicalTransformMatrix();\n  MatrixS invT=T.inverse();\n  MatrixS controllable=T*m_dynamics*invT;\n  if (ms_trace_dynamics>=eTraceDynamics) {\n    ms_logger.logData(controllable,\"Controllable\");\n  }\n  MatrixS coefficients=controllable.row(0);\n  int totalbits=m_paramValues.coeff(eNumBits,1);\n  int fracbits=m_paramValues.coeff(eNumBits,2);\n  int multbits=0;\n  if (totalbits<=0) {\n    totalbits=m_paramValues.coeff(eNumBits,0);\n    if (totalbits<=0) totalbits=func::getDefaultPrec();\n    fracbits=totalbits;\n  }\n  else if (fracbits==0) fracbits=totalbits>>1;\n  result << \"struct implt impl={ .int_bits=\" << (totalbits-fracbits)\n         << \", .frac_bits=\" << fracbits\n         << \", .mult_bits=\" << multbits\n         << \"};\\n\";\n  result << \"struct coefft \";\n  result << ms_logger.MatToC(\"plant\",coefficients,intervals);\n  result << \"struct transformt \" << ms_logger.MatToC(\"transform\",invT,intervals);\n  result << \"matrixt dynamics\" << ms_logger.MatToC(\"\",m_dynamics,intervals);\n  result << \"vectort sensitivity\" << ms_logger.MatToC(\"\",m_sensitivity.transpose(),intervals);\n  result << \"#ifdef __CPROVER\\n\";\n  result << \"extern vectort controller;\\n\";\n  result << \"#else\\n\";\n  result << \"vectort controller\" << ms_logger.MatToC(\"\",m_feedback,intervals);;\n  result << \"#endif\\n\";\n  if (m_safeReachTube.isEmpty() && !m_outputGuard.isEmpty()) calculateGuardFromOutput();\n  MatrixS vectors=m_safeReachTube.getPolyhedra().getFaceDirections();\n  MatrixS support=m_safeReachTube.getPolyhedra().getSupports().transpose();\n  AbstractPolyhedra<scalar> K=getControllerInBounds(m_safeReachTube.getPolyhedra());\n  K.toOuter(true);\n  int controllerOrBlocks;\n  AbstractPolyhedra<scalar> K2=getControllerDynBounds(m_safeReachTube.getPolyhedra(),controllerOrBlocks);\n  result << \"void boundController()\\n{\\n\";\n  result << ms_logger.IneToC(\"verify_assume\",\"(control_floatt)\",\"controller\",K.getFaceDirections(),K.getSupports()) << \";\\n\";\n  result << ms_logger.IneToC(\"verify_assume\",\"(control_floatt)\",\"controller\",K2.getFaceDirections(),K2.getSupports(),false,controllerOrBlocks) << \";\\n\";\n  result << \"}\\n\";\n  if (m_feedback.rows()>0) {\n    MatrixS vertices=m_initialState.getPolyhedra().getVertices();\n    makeClosedLoop(false,false,true);\n    const MatrixS inputVertices=m_closedLoop.getInputVertices(eNormalSpace,true);\n    result << \"#define _NUM_VERTICES \" << vertices.rows() << \"\\n\";\n    result << \"#define _NUM_INPUT_VERTICES \" << inputVertices.rows() << \"\\n\";\n    result << \"#define _NUM_VECTORS \" << vectors.rows() << \"\\n\";\n    if (vertices.rows()>0) {\n      result << \"control_floatt vertices[_NUM_VERTICES][_DIMENSION]\";\n      result << ms_logger.MatToC(\"\",vertices);\n      result << \"control_floatt input_vertices[_NUM_INPUT_VERTICES][_DIMENSION]\";\n      result << ms_logger.MatToC(\"\",inputVertices);\n      result << \"control_floatt accel_vertices[_NUM_INPUT_VERTICES][_DIMENSION];\\n\";\n      result << \"control_floatt vectors[_NUM_VECTORS][_DIMENSION]\";\n      result << ms_logger.MatToC(\"\",vectors);\n      result << \"control_floatt reach_vertices[_NUM_INPUT_VERTICES][_NUM_VERTICES][_DIMENSION];\\n\";\n      result << \"control_floatt supports[_NUM_VECTORS]\";\n      result << ms_logger.MatToC(\"\",support);\n      result << \"control_floatt accelsupports[_NUM_INPUT_VERTICES][_NUM_VECTORS];\\n\\n\";\n    }\n    else {\n      result << \"control_floatt vertices[1][1]={{1}};\\n\";\n    }\n  }\n  return result.str();\n}\n\n///Creates a list of iterations to check with CEGIS\ntemplate <class scalar>\nstd::string Synthesiser<scalar>::makeCEGISIterations(std::string &existing)\n{\n  std::stringstream result;\n  if (func::isZero(m_feedback.norm())) return \"#define NO_FEEDBACK\\n\";\n  makeClosedLoop(false,false,true);\n  if (m_closedLoop.isDivergent()) return \"#define DIVERGENT\\n\";\n  m_closedLoop.getRefinedDynamics(4);\n  AbstractPolyhedra<scalar> bounds=m_closedLoop.synthesiseDynamicBounds(m_inputType,m_safeReachTube.getPolyhedra(eEigenSpace));\n  powerList counterexamples;\n  bool fail=m_closedLoop.findCounterExampleIterations(counterexamples,bounds);\n  if (fail && counterexamples.empty()) counterexamples[1]=0;\n  if (!counterexamples.empty()) {\n    result << \"#define POINTS_PER_ITER\\n\";\n    result << \"#define _NUM_ITERATIONS \" << counterexamples.size() << \"\\n\";\n    result << \"int iterations[_NUM_ITERATIONS]={\";\n    for (typename powerList::iterator it=counterexamples.begin();it!=counterexamples.end();it++) {\n      if (it!=counterexamples.begin()) result << \",\";\n      result << it->first;\n    }\n    result << \"};\\n\";\n\n    result << \"int iter_vertices[_NUM_ITERATIONS][2]={\";\n    AbstractPolyhedra<scalar> &safe=m_safeReachTube.getPolyhedra();\n    MatrixS vertices=m_initialState.getPolyhedra().getVertices();\n    MatrixS inputVertices=m_closedLoop.getInputVertices();\n    for (typename powerList::iterator it=counterexamples.begin();it!=counterexamples.end();it++) {\n      if (it!=counterexamples.begin()) result << \",\";\n      MatrixS dynamics=m_closedLoop.getPseudoDynamics(it->first).transpose();\n      if (ms_trace_dynamics>eTraceDynamics) {\n        ms_logger.logData(dynamics,\"dynamics\");\n        ms_logger.logData(vertices,\"vertices\");\n        ms_logger.logData(inputVertices,\"inputVertices\");\n      }\n      bool found=false;\n      for (int i=0;i<vertices.rows();i++) {\n        for (int j=0;j<inputVertices.rows();j++) {\n          MatrixS point=(vertices.row(i)-inputVertices.row(j))*dynamics+inputVertices.row(j);\n          ms_logger.logData(point,\"point\");\n          if (!safe.isInside(point)) {\n            result << \"{\" << i << \",\" << j << \"}\";\n            i=vertices.rows();\n            found=true;\n            break;\n          }\n        }\n      }\n      if (!found) result << \"{-1,-1}\";\n    }\n    result << \"};\\n\";\n  }\n  else if (fail) {\n    return \"#define FAILED\\n\";\n  }\n  return result.str();\n}\n\n///Creates a c header file for CEGIS\ntemplate <class scalar>\nbool Synthesiser<scalar>::makeCEGISFiles()\n{\n  std::ofstream headerFile;\n  headerFile.open(\"types.h\");\n  if (!headerFile.is_open()) return false;\n  ms_logger.setPrecision(12);\n  std::string data=makeCEGISHeader();\n  headerFile.write(data.data(),data.size());\n  headerFile.close();\n\n  data=makeCEGISDescription();\n  std::string oldIters;\n  std::string iters=makeCEGISIterations(oldIters);\n  std::ofstream sucess_file;\n  sucess_file.open(\"output.txt\");\n  if (!sucess_file.is_open()) return false;\n  std::string result=iters.empty() ? \"SUCCESS\" : \"FAIL\";\n  sucess_file.write(result.data(),result.size());\n  data+=iters;\n  sucess_file.close();\n  std::ofstream file;\n  file.open(\"system.h\");\n  if (!file.is_open()) return false;\n  file.write(data.data(),data.size());\n  file.close();\n  return true;\n}\n\n\n#ifdef USE_LDOUBLE\n  #ifdef USE_SINGLES\n    template class Synthesiser<long double>;\n  #endif\n  #ifdef USE_INTERVALS\n    template class Synthesiser<ldinterval>;\n  #endif\n#endif\n#ifdef USE_MPREAL\n  #ifdef USE_SINGLES\n    template class Synthesiser<mpfr::mpreal>;\n  #endif\n  #ifdef USE_INTERVALS\n    template class Synthesiser<mpinterval>;\n  #endif\n#endif\n\n}\n", "meta": {"hexsha": "e0988f0580863f4942bcf6d46f804feb3b1e671b", "size": 49146, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "toolbox-dssynth/dssynth-tool/benchmark-runner/AACegar/src/Synthesiser.cpp", "max_stars_repo_name": "SSV-Group/dsverifier", "max_stars_repo_head_hexsha": "1daca4704216edf9a360b4a39e00663d94646ad1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2016-08-29T19:23:25.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-18T22:27:21.000Z", "max_issues_repo_path": "toolbox-dssynth/dssynth-tool/benchmark-runner/AACegar/src/Synthesiser.cpp", "max_issues_repo_name": "SSV-Group/dsverifier", "max_issues_repo_head_hexsha": "1daca4704216edf9a360b4a39e00663d94646ad1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 64.0, "max_issues_repo_issues_event_min_datetime": "2016-09-10T16:29:44.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-15T14:31:06.000Z", "max_forks_repo_path": "toolbox-dssynth/dssynth-tool/benchmark-runner/AACegar/src/Synthesiser.cpp", "max_forks_repo_name": "SSV-Group/dsverifier", "max_forks_repo_head_hexsha": "1daca4704216edf9a360b4a39e00663d94646ad1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2016-10-09T21:38:41.000Z", "max_forks_repo_forks_event_max_datetime": "2017-07-05T10:05:32.000Z", "avg_line_length": 43.2623239437, "max_line_length": 240, "alphanum_fraction": 0.6910226672, "num_tokens": 12972, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.845942452844325, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.49174896234563736}}
{"text": "//\n// OpenTissue Template Library Demo\n// - A specific demonstration of the flexibility of OTTL.\n// Copyright (C) 2008 Department of Computer Science, University of Copenhagen.\n//\n// OTTL and OTTL Demos are licensed under zlib.\n//\n#include <OpenTissue/configuration.h>\n\n#define DEFINE_GLUT_MAIN\n#include <OpenTissue/utility/glut/glut_perspective_view_application.h>\n#undef DEFINE_GLUT_MAIN\n\n\n#define SPHSH\n//#define SPHSH_PARALLEL\n\n#include <OpenTissue/dynamics/sph/sph.h>\n#include <OpenTissue/core/math/math_constants.h>\n#include <OpenTissue/core/math/math_vector3.h>\n#include <OpenTissue/core/containers/grid/grid.h>\n#include <OpenTissue/core/containers/grid/util/grid_idx2coord.h>\n#include <OpenTissue/core/containers/mesh/mesh.h>\n#include <OpenTissue/core/geometry/geometry_capsule.h>\n#include <OpenTissue/core/geometry/geometry_sphere.h>\n#include <OpenTissue/core/geometry/geometry_obb.h>\n#include <OpenTissue/collision/spatial_hashing/spatial_hashing.h>\n#include <OpenTissue/utility/utility_fps_counter.h>\n#include <OpenTissue/utility/utility_runtime_type.h>\n\n#include <vector>\n#include <list>\n#include <cmath>\n#include <string>\n\n#include <boost/cast.hpp> // we need boost::numeric_cast<>()\n\n\nusing namespace OpenTissue::math;\nusing namespace OpenTissue::math::detail;\n\n\n/**\n*\n* 2007-05-21 kenny: \n*\n*    The compiler do not like it if these typedef's are moved inside the class\n*    definition. As far as I can tell it boils down to using a pointer as a\n*    template argument.  This should be re-factored!!!\n*/\n\n  template<typename Point_Type>\n  class T4NodeTraits\n  {\n  public:\n    typedef Point_Type  point_type;\n    point_type const & vertex() const {return *m_vertex;}\n    point_type const *  m_vertex;\n  };\n\n  typedef OpenTissue::utility::RuntimeType<double>  RTreal;\n  RTreal Radius;\n  typedef BasicMathTypes<double,int> math_types;\n\n  typedef math_types::vector3_type           point;\n  typedef math_types::vector3_type           vector3_type;\n  typedef math_types::real_type              real_type;\n  typedef std::vector<point>                 point_container;\n  typedef OpenTissue::sph::Particle<real_type, Vector3, &Radius>  Particle;\n\n  typedef OpenTissue::geometry::VolumeShape<math_types> Volume;\n  typedef OpenTissue::geometry::Capsule<math_types>     CapsuleObj;\n  typedef OpenTissue::geometry::Sphere<math_types>      SphereObj;\n  typedef OpenTissue::geometry::OBB<math_types>         BoxObj;\n\n  typedef OpenTissue::sph::ImplicitSpherePrimitive<real_type, vector3_type, SphereObj> ImplicitSphere;\n  typedef OpenTissue::sph::ImplicitCapsulePrimitive<real_type, vector3_type, CapsuleObj> ImplicitCapsule;\n  typedef OpenTissue::sph::ImplicitPlanePrimitive<real_type, vector3_type> ImplicitPlane;\n  typedef OpenTissue::sph::ImplicitBoxPrimitive<real_type, vector3_type, BoxObj> ImplicitBox;\n\n  //typedef OpenTissue::CollisionTypeBinder<real_type, OpenTissue::vector3> CollisionTypes;\n  //typedef OpenTissue::ParticleWrapper<point, Particle> Particle_Wrapper;\n  //typedef OpenTissue::TetrahedronWrapper<real_type, point, tetrahedra_mesh::tetrahedron_type> Tetrahedron_Wrapper;\n  //typedef OpenTissue::TetrahedraPointsCollisionDetectionPolicy<CollisionTypes, Tetrahedron_Wrapper, Particle_Wrapper> CollisionDetection;\n  //typedef OpenTissue::TetrahedraPointsCollisionDetectionPolicy<real_type, vector3_type, tetrahedra_mesh::tetrahedron_type, Particle> T4CollisionDetection;\n  typedef OpenTissue::sph::ImplicitPrimitivesCollisionDetectionPolicy<real_type, vector3_type, Particle> IPCollisionDetection;\n\n  typedef OpenTissue::sph::Types<\n      real_type\n    , Vector3\n    , Particle\n    , IPCollisionDetection\n    , OpenTissue::spatial_hashing::PrimeNumberHashFunction\n    , OpenTissue::spatial_hashing::Grid\n    , OpenTissue::spatial_hashing::PointDataQuery\n  > SPHTypes;\n\n\n  typedef OpenTissue::sph::WFixedGaussian<SPHTypes, &Radius, false> KernelGaussian;\n  typedef OpenTissue::sph::WPoly6<SPHTypes, &Radius, false> KernelDefault;\n  typedef OpenTissue::sph::WSpiky<SPHTypes, &Radius, false> KernelPressure;\n  typedef OpenTissue::sph::WViscosity<SPHTypes, &Radius, false> KernelViscosity;\n\n  typedef OpenTissue::sph::Density<SPHTypes, KernelDefault> DensitySolver;\n  typedef OpenTissue::sph::SurfaceNormal<SPHTypes, KernelDefault> NormalSolver;\n  typedef OpenTissue::sph::PressureForce<SPHTypes, KernelPressure> PressureForce;\n  typedef OpenTissue::sph::ViscosityForce<SPHTypes, KernelViscosity> ViscosityForce;\n  typedef OpenTissue::sph::SurfaceForce<SPHTypes, KernelDefault> SurfaceForce;\n  typedef OpenTissue::sph::ColorField<SPHTypes, KernelDefault> ColorField;\n\n  typedef OpenTissue::sph::Pressure<SPHTypes> PressureSolver;\n  typedef OpenTissue::sph::Gravity<SPHTypes> GravityForce;\n  typedef OpenTissue::sph::Buoyancy<SPHTypes> BuoyancyForce;\n\n  typedef OpenTissue::sph::Verlet<SPHTypes> VerletIntegrator;\n  typedef OpenTissue::sph::Euler<SPHTypes> EulerIntegrator;\n  typedef OpenTissue::sph::LeapFrog<SPHTypes> LeapFrogIntegrator;\n\n  typedef OpenTissue::sph::Water<SPHTypes> WaterMaterial;\n  typedef OpenTissue::sph::Mucus<SPHTypes> MucusMaterial;\n  typedef OpenTissue::sph::Steam<SPHTypes> SteamMaterial;\n\n  typedef OpenTissue::sph::PointEmitter<SPHTypes> PointEmitter;\n  typedef OpenTissue::sph::CircleEmitter<SPHTypes> CircleEmitter;\n\n\n  typedef OpenTissue::sph::System\n  <   SPHTypes\n    , DensitySolver\n    , PressureSolver\n    , NormalSolver\n    , GravityForce\n    , BuoyancyForce\n    , PressureForce\n    , ViscosityForce\n    , SurfaceForce\n    , LeapFrogIntegrator\n    , ColorField\n  > DefaultSystem;\n\n\n\n\n/**\n*\n* 2007-05-21: kenny: outstanding issues: \n*                const-correctness, \n*                OT-naming conventions is not used (ie. m_ on members, _type on types,\n*                prober placement of braces etc..),\n*                messy usage of math types and ad-hoc typedefs.\n*                Contains redundant code like Screen2World and putText.\n*                documentation is missing too.\n*                avoid if-directives in code, in particular ``if 0'' stuff\n*/\nclass Application : public OpenTissue::glut::PerspectiveViewApplication\n{\nprotected:\n\n  bool draw_normals;\n  bool draw_surface;\n  bool draw_inside;\n  bool draw_velocity;\n  bool osd;\n  bool render;\n  int obstacles;\n  bool use_emitter;\n  bool waves;\n\n  int yScale;\n  bool bPanObstacle;\n  bool bScaleObstacle;\n  double xPan, yPan, zPan;\n\nprotected:\n\n\n\n  DefaultSystem* sph;\n  OpenTissue::sph::Material<SPHTypes>* material;\n  OpenTissue::grid::Grid<double,math_types>  phi;\n  OpenTissue::polymesh::PolyMesh<> surface;\n\n  OpenTissue::utility::FPSCounter<double> fps;\n  point_container points;\n  SphereObj sphere;\n  SphereObj sphere2;\n  BoxObj box;\n  ImplicitSphere isphere;\n  ImplicitSphere isphere2;\n  CapsuleObj capsule;\n  ImplicitCapsule icapsule;\n  ImplicitPlane iplane;\n  ImplicitBox ibox;\n  PointEmitter emitter1;\n  CircleEmitter emitter2;\n  CircleEmitter emitter3;\n\n  BoxObj DBb1;\n  BoxObj DBb2;\n  BoxObj DBb3;\n  ImplicitBox iDBb1;\n  ImplicitBox iDBb2;\n\n  OpenTissue::sph::Emitter<SPHTypes>* emitter;\n  Volume* object;\n\npublic:\n\n  Application()\n    : draw_normals(false)\n    , draw_surface(false)\n    , draw_inside(false)\n    , draw_velocity(false)\n    , osd(true)\n    , render(false)\n    , obstacles(0)\n    , use_emitter(false)\n    , waves(false)\n    , bPanObstacle(false)\n    , bScaleObstacle(false)\n    , sph(NULL)\n    , material(NULL)\n    , sphere(vector3_type(0,0,0.1), 0.25)\n    , sphere2(vector3_type(0,0,-0.2), 0.25)\n    , box(vector3_type(0.0,0.0,0.0), diag(1.), vector3_type(0.1875,0.1875,0.1875))\n    , isphere(sphere)\n    , isphere2(sphere2)\n    , capsule(vector3_type(0.0,0.0,0.0), vector3_type(0.0,0.0,0.6), 0.2)\n    , icapsule(capsule)\n    , iplane(vector3_type(0,0,-2.0), vector3_type(0,0,1.0))\n    , ibox(box)\n    , emitter1(vector3_type(0,0,0), vector3_type(-1.5,0,.5))\n    , emitter2( vector3_type(0.0), 0.015, vector3_type(0.0,0.0,1.5))\n    , emitter3(vector3_type(0,0,0.7), 0.02, vector3_type(0,0,-1))\n    , DBb1(vector3_type(0.0,0.0,0.0), diag(1.), vector3_type(0.1875,0.1,0.4))\n    , DBb2(vector3_type(0.3125,0.0,0.0), diag(1.), vector3_type(0.5,0.1,0.4))\n    , DBb3(vector3_type(0.0,0.0,0.0), diag(1.), vector3_type(0.5,0.1,0.4))\n    , iDBb1(DBb1)\n    , iDBb2(DBb2)\n    , emitter(&emitter2)\n    , object(&capsule)\n  { }\n\nprotected:\n\n  /**\n  * Put text onto screen (OSD)\n  *\n  * 2007-05-21 kenny: what is wrong with OpenTissue::gl::DrawString()?\n  */\n  void putText(const double &x, const double &y, const double &r, const double &g, const double &b, const std::string &text)\n  {\n    // setup orthogonal projection to use 2D text\n    glMatrixMode(GL_PROJECTION);\n    glPushMatrix();\n    glLoadIdentity();\n    glViewport(0, 0, this->width(), this->height());\n    glOrtho(0, this->width(), 0, this->height(), 0, 1);\n\n    glMatrixMode(GL_MODELVIEW);\n    glLoadIdentity();\n\n    glDisable(GL_TEXTURE_2D);\n\n    glColor4d(r, g, b, 1);\n    glRasterPos2i( static_cast<int>( x ), static_cast<int>( y ) );\n    for (const char *c = text.c_str(); *c != '\\0'; ++c)\n      glutBitmapCharacter(GLUT_BITMAP_HELVETICA_12, *c);//GLUT_BITMAP_8_BY_13\n    glColor4d(r+.5, g+.5, b+.5, 1);\n    glRasterPos2i( static_cast<int>( x+1 ), static_cast<int>( y-1 ) );\n    for (const char *c = text.c_str(); *c != '\\0'; ++c)\n      glutBitmapCharacter(GLUT_BITMAP_HELVETICA_12, *c);//GLUT_BITMAP_8_BY_13\n\n    glMatrixMode(GL_PROJECTION);\n    glPopMatrix();\n  }\n\n\n  void renderParticles(const DefaultSystem::fluid_material* mat)\n  {\n    GLUquadric * qobj = gluNewQuadric();\n    gluQuadricDrawStyle(qobj, GLU_FILL);\n    glEnable(GL_COLOR_MATERIAL);\n    glDisable(GL_LIGHTING);\n\n    //    unsigned long cnt = 0;\n    const SPHTypes::particle_container &pars = sph->particles();\n    for (SPHTypes::particle_container::const_iterator p = pars.begin(); p != pars.end(); p++) {\n      if (p->fixed()) continue;\n      const vector3_type &pos = p->position();\n\n      //\n      // V = 4/3 pi r^3  =>  m/rho = 4/3 pi r^3  =>  r^3 = (3 m)/(4 pi rho)  =>  r = ((3 m)/(4 pi rho))^1/3\n      //\n      const SPHTypes::real_type d = 0.9*pow((3.*p->mass())/(4.*pi<real_type>()*p->density()), 1./3.);\n      const vector3_type& n = p->normal();\n      const SPHTypes::real_type l = n*n;\n\n      bool draw_sphere = false;\n      if (l >= mat->threshold() || l < 0.0025) \n      {\n        // draw surface normals\n        if (draw_normals && l >= mat->threshold()) \n        {\n          const vector3_type sn = -0.05*unit(n);\n          glColor3d(0.5, 0.5, 0.5);\n          glBegin(GL_LINES);\n          glVertex3d(pos[0], pos[1], pos[2]);\n          glVertex3d(pos[0]+sn[0], pos[1]+sn[1], pos[2]+sn[2]);\n          glEnd();\n        }\n        glColor3d(mat->red(), mat->green(), mat->blue());\n        draw_sphere = draw_surface;\n      }\n      else \n      {\n        glColor3d(.5*mat->red(), .5*mat->green(), .5*mat->blue());\n        draw_sphere = draw_inside;\n      }\n\n      // default behaviour\n      if (!(draw_surface || draw_inside)) \n      {\n        glColor3d(mat->red(), mat->green(), mat->blue());\n        draw_sphere = true;\n      }\n\n      if (draw_velocity) \n      {\n        glEnable(GL_LIGHTING);\n        const vector3_type vel = 0.05*p->velocity();\n        OpenTissue::gl::DrawVector(pos, vel, 1, false);\n      }\n      else if (draw_sphere) \n      {\n        glPushMatrix();\n        glTranslated(pos[0], pos[1], pos[2]);\n        glEnable(GL_LIGHTING);\n        gluSphere(qobj, d, 8, 8);\n        glDisable(GL_LIGHTING);\n        glPopMatrix();\n      }\n\n    }\n    gluDeleteQuadric(qobj);\n  }\n\n\n  void renderSurface(const DefaultSystem::fluid_material* mat, const SPHTypes::real_type& size)\n  {\n    using std::max;\n    using std::min;\n\n    typedef SPHTypes::real_type   real_type;\n    typedef vector3_type vector3_type;\n    // find BB of fluid (for high res rendering)\n    vector3_type  m( highest<real_type>() ), M( lowest<real_type>() );\n\n    const SPHTypes::particle_container &pars = sph->particles();\n    SPHTypes::particle_container::const_iterator pars_end = pars.end();\n    for (SPHTypes::particle_container::const_iterator p = pars.begin(); p != pars_end; ++p)\n    {\n      vector3_type const & pos = p->position();\n      M = max(M, pos);\n      m = min(m, pos);\n    }\n    real_type const d = 1.35*pow((3.*mat->particle_mass())/(4.*pi<real_type>()*mat->density()), 1./3.);\n    m -= vector3_type(d);\n    M += vector3_type(d);\n\n    vector3_type v((M-m)/size);\n    v = ceil(v);\n\n    if(phi.I()<v(0) ||  phi.J()<v(1)  || phi.K()<v(2))\n      phi.create( m ,M\n      , static_cast<math_types::index_type>(v[0])\n      , static_cast<math_types::index_type>(v[1])\n      , static_cast<math_types::index_type>(v[2])\n      ); // TODO 2005-08-28 KE: hmmm, this should be pre-allocated!!!\n\n    OpenTissue::grid::Grid<double,math_types>::index_iterator phi_begin = phi.begin();\n    OpenTissue::grid::Grid<double,math_types>::index_iterator phi_end = phi.end();\n    for(OpenTissue::grid::Grid<double,math_types>::index_iterator phi_ = phi_begin; phi_ != phi_end; ++phi_)\n      *phi_ = 0.;\n\n    /*\n    SPHTypes::particle_container::const_iterator par = pars.begin();\n    SPHTypes::particle_container::const_iterator par_end = pars.end();\n    for (;par!=par_end;++par)\n    {\n    const vector3_type& n = par->normal();\n    const SPHTypes::real_type l = n*n;\n    if (l >= mat->threshold() || l < 0.0025)\n    {\n    const vector3_type &r = par->position();\n    unsigned int i = static_cast<unsigned int>(std::floor( (r(0) - phi.min_coord(0)) / phi.dx() ));\n    unsigned int j = static_cast<unsigned int>(std::floor( (r(1) - phi.min_coord(1)) / phi.dy() ));\n    unsigned int k = static_cast<unsigned int>(std::floor( (r(2) - phi.min_coord(2)) / phi.dz() ));\n    phi(  i,  j,k) = 100;\n    phi(  i,j+1,k) = 100;\n    phi(i+1,  j,k) = 100;\n    phi(i+1,j+1,k) = 100;\n    phi(  i,  j,k+1) = 100;\n    phi(  i,j+1,k+1) = 100;\n    phi(i+1,  j,k+1) = 100;\n    phi(i+1,j+1,k+1) = 100;\n    }\n    }\n    */\n\n    vector3_type coord;\n    for(OpenTissue::grid::Grid<double,math_types>::index_iterator phi_ = phi_begin; phi_ != phi_end; ++phi_)\n    {\n      //    if(*phi_>1.)\n      {\n        OpenTissue::grid::idx2coord(phi_,coord);\n        *phi_ = sph->isoValue(coord);//0.35 - sph->isoValue(pos);\n      }\n    }\n\n\n    //OpenTissue::mesh::isosurface(phi,0.0,surface);\n    OpenTissue::mesh::smooth_isosurface(phi,0.6,surface,1,true);\n\n    //  OpenTissue::polymesh::PolyMesh<>::vertex_iterator end = surface.vertex_end();\n    //  for (OpenTissue::polymesh::PolyMesh<>::vertex_iterator vtx = surface.vertex_begin(); vtx != end; ++vtx)\n    //    vtx->m_color = OpenTissue::polymesh::PolyMesh<>::vector3_type(mat->red(), mat->green(), mat->blue());\n\n    glColor3d(mat->red(), mat->green(), mat->blue());\n    //  glEnableClientState(GL_VERTEX_ARRAY);\n    //  glEnableClientState(GL_NORMAL_ARRAY);\n\n    glEnable(GL_LIGHTING);\n    glEnable(GL_COLOR_MATERIAL);\n    glEnable(GL_CULL_FACE);\n    glCullFace(GL_BACK);\n\n    OpenTissue::gl::DrawMesh(surface, GL_POLYGON, false, true, false);\n    //  OpenTissue::MeshDrawArray<PolyMesh<> > dm(surface);\n    //  dm();\n    //OpenTissue::gl::DrawMesh(surface);\n\n    //char *vertexArray = (char *) surface.getVertexArray();\n    //glVertexPointer(3, GL_FLOAT, sizeof(ISvertex), vertexArray);\n    //glNormalPointer(   GL_FLOAT, sizeof(ISvertex), vertexArray + sizeof(ISvec3));\n    //glDrawElements(GL_TRIANGLES, surface.getIndexCount(), GL_UNSIGNED_INT, surface.getIndexArray());\n\n    //  glDisableClientState(GL_NORMAL_ARRAY);\n    //  glDisableClientState(GL_VERTEX_ARRAY);\n\n    // draw bb\n#if 0\n    glDisable(GL_LIGHTING);\n    glColor3d(0,0,0);\n    glBegin(GL_LINES);\n    glVertex3d(m[0], m[1], m[2]);\n    glVertex3d(M[0], m[1], m[2]);\n    glVertex3d(M[0], m[1], m[2]);\n    glVertex3d(M[0], M[1], m[2]);\n    glVertex3d(M[0], M[1], m[2]);\n    glVertex3d(m[0], M[1], m[2]);\n    glVertex3d(m[0], M[1], m[2]);\n    glVertex3d(m[0], m[1], m[2]);\n    glVertex3d(m[0], m[1], M[2]);\n    glVertex3d(M[0], m[1], M[2]);\n    glVertex3d(M[0], m[1], M[2]);\n    glVertex3d(M[0], M[1], M[2]);\n    glVertex3d(M[0], M[1], M[2]);\n    glVertex3d(m[0], M[1], M[2]);\n    glVertex3d(m[0], M[1], M[2]);\n    glVertex3d(m[0], m[1], M[2]);\n    glVertex3d(m[0], m[1], m[2]);\n    glVertex3d(m[0], m[1], M[2]);\n    glVertex3d(M[0], m[1], m[2]);\n    glVertex3d(M[0], m[1], M[2]);\n    glVertex3d(M[0], M[1], m[2]);\n    glVertex3d(M[0], M[1], M[2]);\n    glVertex3d(m[0], M[1], m[2]);\n    glVertex3d(m[0], M[1], M[2]);\n    glEnd();\n#endif\n    /*\n    glEnable(GL_LIGHTING);\n    for (SPHTypes::real_type k = m[2]; k < M[2]; k += size)\n    for (SPHTypes::real_type j = m[1]; j <= M[1]; j += size)\n    for (SPHTypes::real_type i = m[0]; i <= M[0]; i += size) {\n    vector3_type test(i+.5*size, j+.5*size, k+.5*size);\n    if ((0.35-sph->isoValue(test)) <= 0) {\n    glBegin(GL_QUADS);\n    glColor3d(1,0,0);\n    glNormal3d(1, 0, 0);\n    glVertex3d(i, j, k);\n    glVertex3d(i, j+size, k);\n    glVertex3d(i, j+size, k+size);\n    glVertex3d(i, j, k+size);\n    glColor3d(0,1,0);\n    glNormal3d(0, 1, 0);\n    glVertex3d(i, j, k);\n    glVertex3d(i+size, j, k);\n    glVertex3d(i+size, j, k+size);\n    glVertex3d(i, j, k+size);\n    glColor3d(0,0,1);\n    glNormal3d(0, 0, 1);\n    glVertex3d(i, j, k);\n    glVertex3d(i+size, j, k);\n    glVertex3d(i+size, j+size, k);\n    glVertex3d(i, j+size, k);\n    glEnd();\n    }\n    }\n    */\n    glDisable(GL_COLOR_MATERIAL);\n    glDisable(GL_CULL_FACE);\n  }\n\n\n  void addCollisionObject(Volume* obj)\n  {\n    object = obj;\n    if (sph) {\n      if (object == &capsule)\n        sph->collisionSystem().addContainer(icapsule);\n      else if (object == &sphere)\n        sph->collisionSystem().addContainer(isphere);\n      else if (object == &box)\n        sph->collisionSystem().addContainer(ibox);\n      else if (object == &DBb1)\n        sph->collisionSystem().addContainer(iDBb1);\n      else if (object == &DBb2)\n        sph->collisionSystem().addContainer(iDBb2);\n    }\n  }\n\n\n  template<typename MaterialPolicy>\n  bool createFluid(size_t const & particles)\n  {\n    delete material;\n    delete sph;\n\n    material = new MaterialPolicy;\n    material->particles() = particles;\n    material->particle_mass(material->particle_mass());\n\n    const SPHTypes::real_type  x = material->kernel_particles();         //--- Average number of particles inside kernel...\n\n    material->threshold() = material->density()/x;\n\n    Radius = material->radius(x);\n    vector3_type gravity(0,0,-9.82);\n\n    sph = new DefaultSystem;\n\n    if (!sph->create(\n      *static_cast< MaterialPolicy* >(material), gravity)\n      )  // material, gravity\n      return false;\n\n    if (!sph->initHashing(2u*particles, Radius))  // hash table size, cell spacing (AABBs)\n      return false;\n\n    addCollisionObject(object);\n    //  sph->collisionSystem().addContainer(isphere); object = &sphere;\n    //  sph->collisionSystem().addObstacle(isphere2);\n    //  sph->collisionSystem().addContainer(icapsule); object = &capsule;\n    //  sph->collisionSystem().addObstacle(iplane);\n    //  sph->collisionSystem().addObstacle(ibox); object = &box;\n    //  sph->collisionSystem().addContainer(ibox); object = &box;\n    //  sph->collisionSystem().addContainer(iDBb1); object = &DBb1;\n    //  sph->collisionSystem().addContainer(iDBb2); object = &DBb2;\n\n    if (use_emitter) \n    {\n      emitter = &emitter2;\n      emitter->batch() = 5;//7\n      emitter->rate() = 2;\n\n      if (!sph->init(emitter2, particles))\n        return false;\n    }\n    else \n    {\n      emitter = NULL;\n      typedef std::vector<vector3_type> vectors;\n      vectors positions, velocities;\n\n      const SPHTypes::real_type dist = 1./45.;\n      const SPHTypes::real_type off = -.14;\n      size_t k = 1, j = 1, i = 1, p = particles;\n      while (p--) \n      {\n        positions.push_back(vector3_type(off+i*dist, off+j*dist, off+k*dist));\n        velocities.push_back(vector3_type(0.,0.,0.));\n        if (++i > 12) \n        {\n          i = 1;\n          if (++j > 12) \n          {\n            j = 1;\n            ++k;\n          }\n        }\n      }\n      if (!sph->init( positions.begin()\n        , positions.end()\n        , velocities.begin()\n        , velocities.end())\n        )\n        return false;\n    }\n    return true;\n  }\n\n\n  /**\n  * 2007-05-21 kenny: what is wrong with OpenTissue::gl::screen2object()?\n  */\n  void ScreenToWorld(double& xw, double& yw, double& zw, const int xs, const int ys)\n  {\n    GLdouble projMatrix[16];\n    GLdouble modelViewMatrix[16];\n    GLint viewPort[4];\n\n    //  glMatrixMode(GL_MODELVIEW);\n    //  glLoadIdentity();\n    //  gluLookAt( eyex, eyey, eyez, centerx, centery, centerz, upx, upy, upz );\n    //  glMultMatrixd( trackball.get_gl_current_rotation() );\n    //  glRotatef(-90,1,0,0);\n\n    glGetDoublev(GL_MODELVIEW_MATRIX, modelViewMatrix);\n    glGetDoublev(GL_PROJECTION_MATRIX, projMatrix);\n    glGetIntegerv(GL_VIEWPORT, viewPort);\n\n    gluUnProject(xs, viewPort[3]-ys, 1, modelViewMatrix, projMatrix, viewPort, &xw, &yw, &zw);\n  }\n\npublic:\n\n  char const * do_get_title() const { return \"Smoothed Particle Hydrodynamics Demo Application\"; }\n\n  void do_display()\n  {\n\n    if (obstacles) \n    {\n      glEnable(GL_COLOR_MATERIAL);\n      glEnable(GL_LIGHTING);\n      glColor3d(0.5, 0.0, 0.3);\n      bool const wireframe = 1 == obstacles;\n      if (CapsuleObj::id() == object->class_id())\n        OpenTissue::gl::DrawCapsule(*static_cast<CapsuleObj*>(object), wireframe);\n      else if (SphereObj::id() == object->class_id())\n        OpenTissue::gl::DrawSphere(*static_cast<SphereObj*>(object), wireframe);\n      else if (BoxObj::id() == object->class_id())\n        OpenTissue::gl::DrawOBB(*static_cast<BoxObj*>(object), wireframe);\n      glDisable(GL_LIGHTING);\n    }\n\n\n    if (use_emitter && emitter) \n    {\n      glDisable(GL_COLOR_MATERIAL);\n      glDisable(GL_LIGHTING);\n      if (emitter->active()) \n      {\n        if (emitter->running())\n          glColor3d(0.1, 0.9, 0.1);\n        else\n          glColor3d(0.9, 0.1, 0.1);\n      }\n      else\n        glColor3d(0.2, 0.2, 0.2);\n      const vector3_type& c = emitter->center();\n      const SPHTypes::real_type x = .03;\n\n      glBegin(GL_LINES);\n      glVertex3d(c(0)-x,c(1)-x,c(2)-x);\n      glVertex3d(c(0)+x,c(1)-x,c(2)-x);\n\n      glVertex3d(c(0)+x,c(1)-x,c(2)-x);\n      glVertex3d(c(0)+x,c(1)+x,c(2)-x);\n\n      glVertex3d(c(0)+x,c(1)+x,c(2)-x);\n      glVertex3d(c(0)-x,c(1)+x,c(2)-x);\n\n      glVertex3d(c(0)-x,c(1)+x,c(2)-x);\n      glVertex3d(c(0)-x,c(1)-x,c(2)-x);\n\n      glVertex3d(c(0)-x,c(1)-x,c(2)+x);\n      glVertex3d(c(0)+x,c(1)-x,c(2)+x);\n\n      glVertex3d(c(0)+x,c(1)-x,c(2)+x);\n      glVertex3d(c(0)+x,c(1)+x,c(2)+x);\n\n      glVertex3d(c(0)+x,c(1)+x,c(2)+x);\n      glVertex3d(c(0)-x,c(1)+x,c(2)+x);\n\n      glVertex3d(c(0)-x,c(1)+x,c(2)+x);\n      glVertex3d(c(0)-x,c(1)-x,c(2)+x);\n\n      glVertex3d(c(0)-x,c(1)-x,c(2)-x);\n      glVertex3d(c(0)-x,c(1)-x,c(2)+x);\n\n      glVertex3d(c(0)+x,c(1)-x,c(2)-x);\n      glVertex3d(c(0)+x,c(1)-x,c(2)+x);\n\n      glVertex3d(c(0)+x,c(1)+x,c(2)-x);\n      glVertex3d(c(0)+x,c(1)+x,c(2)+x);\n\n      glVertex3d(c(0)-x,c(1)+x,c(2)-x);\n      glVertex3d(c(0)-x,c(1)+x,c(2)+x);\n      glEnd();\n    }\n\n\n    const DefaultSystem::fluid_material* mat = sph?sph->material():NULL;\n    if (sph) \n    {\n\n      if (render)\n        renderSurface(mat, 0.02);\n      else\n        renderParticles(mat);\n\n\n      fps.frame(); // probe both sim + vis\n      if (osd) \n      {\n        glDisable(GL_LIGHTING);\n        std::stringstream ss;\n        ss << \"FPS: \" /*<< setw(4)*/ << fps();\n        putText(this->width(), this->height()-30, 0.15, 0.0, 0.05, ss.str());\n        std::ostringstream ost;\n        ost << \"Material: \" << (mat?mat->name():\"N/A\");\n        putText(16, this->height()-30, 0.15, 0.0, 0.05, ost.str());\n        ost.str(\"\");\n        ost << \"Particle Mass [kg]: \" << (mat?mat->particle_mass():0.);\n        putText(16, this->height()-50, 0.15, 0.0, 0.05, ost.str());\n        ost.str(\"\");\n        ost << \"Volume [m3]: \" << (mat?mat->volume():0.);\n        putText(16, this->height()-70, 0.15, 0.0, 0.05, ost.str());\n        ost.str(\"\");\n        ost << \"Particles: \" << (mat?mat->particles():0.);\n        putText(16, this->height()-90, 0.15, 0.0, 0.05, ost.str());\n      }  \n    }\n  }\n\n  void do_action(unsigned char choice)\n  {\n    using std::cos;\n    using std::sin;\n\n    switch (choice)\n    {\n    case 'n':\n    case 'N':\n      draw_normals = !draw_normals;\n      break;\n    case 'v':\n    case 'V':\n      draw_velocity = !draw_velocity;\n      break;\n    case 'w':\n    case 'W':\n      waves = !waves;\n      break;\n    case 's':\n    case 'S':\n      draw_surface = !draw_surface;\n      break;\n    case 'i':\n    case 'I':\n      draw_inside = !draw_inside;\n      break;\n    case 'o':\n    case 'O':\n      osd = !osd;\n      break;\n    case 'r':\n    case 'R':\n      render = !render;\n      break;\n    case 'c':\n      if (sph) sph->collisionSystem().clear();\n      if (object == &capsule)\n        addCollisionObject(&sphere);\n      else if (object == &sphere)\n        addCollisionObject(&box);\n      else\n        addCollisionObject(&capsule);\n      break;\n    case 'C':\n      if (++obstacles > 2)\n        obstacles = 0;\n      break;\n    case 'E':\n      use_emitter = !use_emitter;\n      break;\n    case 'e':\n      if (!emitter) break;\n      if (emitter->running())\n        emitter->stop();\n      else\n        emitter->start();\n      break;\n    case '1':\n      // create small water\n      createFluid<WaterMaterial>(500);\n      break;\n    case '2':\n      // create medium water\n      createFluid<WaterMaterial>(1250);//1500\n      break;\n    case '3':\n      // create medium water\n      createFluid<WaterMaterial>(2250);\n      break;\n    case '4':\n      // create large water\n      createFluid<WaterMaterial>(4400);\n      break;\n    case '5':\n      // create small mucus\n      createFluid<MucusMaterial>(500);\n      break;\n    case '6':\n      // create medium mucus\n      createFluid<MucusMaterial>(1250);//1500\n      break;\n    case '7':\n      // create medium mucus\n      createFluid<MucusMaterial>(2250);\n      break;\n    case '8':\n      // create large mucus\n      createFluid<MucusMaterial>(4400);\n      break;\n    case '0':\n      // create test steam\n      createFluid<SteamMaterial>(2000);\n      break;\n    case '.':\n      {\n        const double a = to_radians<double>(45.), b = to_radians<double>(0.), c = to_radians<double>(0.);\n        object->rotate(Volume::matrix3x3_type(1,0,0, 0,cos(a),sin(a), 0,-sin(a),cos(a)));\n        object->rotate(Volume::matrix3x3_type(cos(b),0,-sin(b), 0,1,0, sin(b),0,cos(b)));\n        object->rotate(Volume::matrix3x3_type(cos(c),sin(c),0, -sin(c),cos(c),0, 0,0,1));\n        break;\n      }\n    case ',':\n      {\n        const double a = to_radians<double>(-2.), b = to_radians<double>(-2.), c = -2*to_radians<double>(-2.);\n        object->rotate(Volume::matrix3x3_type(1,0,0, 0,cos(a),sin(a), 0,-sin(a),cos(a)));\n        object->rotate(Volume::matrix3x3_type(cos(b),0,-sin(b), 0,1,0, sin(b),0,cos(b)));\n        object->rotate(Volume::matrix3x3_type(cos(c),sin(c),0, -sin(c),cos(c),0, 0,0,1));\n        break;\n      }\n    case '+':\n      if (sph) \n      {\n        sph->collisionSystem().clear();\n        sph->collisionSystem().addContainer(iDBb2); object = &DBb2;\n      }\n      break;\n    case '-':\n      if (sph) \n      {\n        sph->collisionSystem().clear();\n        sph->collisionSystem().addContainer(iDBb1); object = &DBb1;\n      }\n      break;\n    default:\n      break;\n    }\n  }\n\n  void do_init_right_click_menu(int main_menu, void menu(int entry))\n  {\n    int toggles = glutCreateMenu(menu);\n    glutAddMenuEntry(\"On Screen Display [h]\", 'h');\n    glutAddMenuEntry(\"Render Surface [r]\", 'r');\n    glutAddMenuEntry(\"Surface Particles [s]\", 's');\n    glutAddMenuEntry(\"Intrinsic Particles [i]\", 'i');\n    glutAddMenuEntry(\"Surface Normals [n]\", 'n');\n    glutAddMenuEntry(\"Velocities [v]\", 'v');\n    glutAddMenuEntry(\"View Collision Objects [C]\", 'C');\n    glutAddMenuEntry(\"Change Collision Objects [c]\", 'c');\n    glutAddMenuEntry(\"Emitter [E]\", 'E');\n    glutAddMenuEntry(\"Start/Stop Emitter [e]\", 'e');\n    glutAddMenuEntry(\"Dam-Break: Init Dam [-]\", '-');\n    glutAddMenuEntry(\"Dam-Break: Break Dam [+]\", '+');\n    glutAddMenuEntry(\"Start/Stop Box Waves [w]\", 'w');\n\n    int materials = glutCreateMenu(menu);\n    glutAddMenuEntry(\"Water  (500) [1]\", '1');\n    glutAddMenuEntry(\"Water (1250) [2]\", '2');\n    glutAddMenuEntry(\"Water (2250) [3]\", '3');\n    glutAddMenuEntry(\"Water (4400) [4]\", '4');\n    glutAddMenuEntry(\"Mucus  (500) [5]\", '5');\n    glutAddMenuEntry(\"Mucus (1250) [6]\", '6');\n    glutAddMenuEntry(\"Mucus (2250) [7]\", '7');\n    glutAddMenuEntry(\"Mucus (4400) [8]\", '8');\n    glutAddMenuEntry(\"Steam (test) [0]\", '0');\n\n    glutSetMenu(main_menu);\n    glutAddSubMenu(\"toggles\", toggles);\n    glutAddSubMenu(\"materials\", materials);\n  }\n\n  void do_init()\n  {\n    this->camera().move(95);\n    this->zoom_sensitivity() = 0.02;\n    this->pan_sensitivity() = 0.01;\n  }\n\n  void do_run()\n  {\n    if (emitter)\n    {\n      emitter->execute();\n    }\n    if (waves) \n    {\n      vector3_type ext = DBb2.ext();\n      vector3_type cen = DBb2.center();\n      static double t = 0;\n      using std::fabs;\n      const double w = 0.1*fabs(sin(t));\n      ext(0) = 0.5+w; t += 0.05;\n      cen(0) = 0.3125+w;\n      DBb2.set(cen, DBb2.orientation(), ext);\n    }\n    //  for (int n = 0; n < 10; ++n) sph->simulate();\n    sph->simulate();\n  }\n\n  void do_shutdown(){}\n\n  void mouse_down(double cur_x,double cur_y,bool shift,bool ctrl, bool alt,bool left,bool middle,bool right) \n  {\n    if( !bScaleObstacle && middle && ctrl)\n    {\n      yScale = boost::numeric_cast<int>(cur_y);\n      bScaleObstacle = true;\n    }\n    else if( !bPanObstacle && left && shift && ctrl)\n    {\n      bPanObstacle = true;\n      ScreenToWorld(xPan, yPan, zPan, boost::numeric_cast<int>(cur_x), boost::numeric_cast<int>(cur_y));\n    }\n    else\n    {\n      OpenTissue::glut::PerspectiveViewApplication::mouse_down(cur_x,cur_y,shift, ctrl, alt, left, middle, right);\n    }\n  }\n\n  void mouse_move(double cur_x,double cur_y) \n  {\n    \n    if (bPanObstacle) \n    {\n      double x, y, z;\n      ScreenToWorld(x, y, z, boost::numeric_cast<int>(cur_x), boost::numeric_cast<int>(cur_y));\n      object->translate(this->pan_sensitivity()*vector3_type(x-xPan,y-yPan,z-zPan));\n      xPan = x;\n      yPan = y;\n      zPan = z;\n    }\n    else if (bScaleObstacle) \n    {\n      const GLdouble scale = cur_y - yScale;\n      if (scale > 0)\n        object->scale(1.02);\n      else if (scale < 0)\n        object->scale(0.98);\n      yScale = boost::numeric_cast<int>(cur_y);\n    }\n    else\n    {\n      OpenTissue::glut::PerspectiveViewApplication::mouse_move(cur_x,cur_y);\n    }\n  }\n\n  void mouse_up(double cur_x,double cur_y,bool shift,bool ctrl, bool alt, bool left,bool middle,bool right) \n  {\n    if( bScaleObstacle)\n    {\n      yScale = boost::numeric_cast<int>(cur_y);\n      bScaleObstacle = false;\n    }\n    else if(  bPanObstacle )\n    {\n      ScreenToWorld(xPan, yPan, zPan, boost::numeric_cast<int>(cur_x), boost::numeric_cast<int>(cur_y));\n      bPanObstacle = false;\n    }\n    else\n    {\n      OpenTissue::glut::PerspectiveViewApplication::mouse_up(cur_x,cur_y,shift, ctrl, alt, left, middle, right);\n    }\n  }\n\n};\n\nOpenTissue::glut::instance_pointer init_glut_application(int argc, char **argv)\n{\n  OpenTissue::glut::instance_pointer instance;\n  instance.reset( new Application() );\n  return instance;\n}\n", "meta": {"hexsha": "e62281ba5dbb5c2e1e334c4d445cc82c35e8dd5c", "size": 31303, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "demos/glut/smoothed_particle_hydrodynamics/src/application.cpp", "max_stars_repo_name": "ricortiz/OpenTissue", "max_stars_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "demos/glut/smoothed_particle_hydrodynamics/src/application.cpp", "max_issues_repo_name": "ricortiz/OpenTissue", "max_issues_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "demos/glut/smoothed_particle_hydrodynamics/src/application.cpp", "max_forks_repo_name": "ricortiz/OpenTissue", "max_forks_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.9318181818, "max_line_length": 156, "alphanum_fraction": 0.6169376737, "num_tokens": 9695, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028205, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.4917364258691534}}
{"text": "#include \"apps/detect_duplicates/outliers_action.h\"\n#include \"utils/math_utils.h\"\n#include \"utils/missing_values.hpp\"\n#include <algorithm>\n#include <boost/iterator/transform_iterator.hpp>\n#include <map>\n//#include <iostream>\n\nnamespace\n{\n    using algo_data = std::vector<double>;\n\n    algo_data detect_outliers(const algo_data& inside);\n\n    algo_data detect_outliers(const algo_data& inside)\n    {\n        static const double alpha_val = 0.1;\n        return utils::grubbstest(inside, alpha_val);\n    }\n}   // end of local namespace\n\noutlier_predicate::outlier_predicate(iterator s, iterator l) :\n    to_ignore(s, l)\n{\n    std::sort(std::begin(to_ignore), std::end(to_ignore));\n}\n\noutlier_predicate::result_type outlier_predicate::apply_action(input_data d) const\n{\n    return std::make_pair(\n            std::binary_search(std::begin(to_ignore), std::end(to_ignore), d.row),\n            d);\n}\n\n\noutlier_predicate::result_type apply_action(outlier_predicate& da, input_data arg)\n{\n    return da.apply_action(arg);\n}\n\noutliers_detector::outliers_detector(policy_action op) :\n   action(std::move(op))\n{\n}\n\n\noutlier_predicate::result_type outliers_detector::apply_action(input_data data)\n{\n    if (missing_value(data.value)) {\n        missings.push_back(data.row);\n        return std::make_pair(true, data);     // ignore missing values\n    }\n    auto i = ::apply_action(action, data);\n    if (!i.first) {\n        legal_input.push_back(data);\n    }\n    return i;\n}\n\nvoid outliers_detector::finding(row_numbers& ol, row_numbers& missing) const\n{\n    auto tranformer = [](auto it) { return it.value; };\n    using tranformer_type = decltype(tranformer);\n    using iterator_type = boost::transform_iterator<tranformer_type, data_list::const_iterator>;\n    using lookup_table = std::map<algo_data::value_type, std::size_t>;\n\n    algo_data data{iterator_type{std::begin(legal_input), tranformer},\n        iterator_type{std::end(legal_input), tranformer}\n    };\n\n\n    algo_data outliers{detect_outliers(data)};\n    //auto lib = std::begin(legal_input);\n    //auto lie = std::end(legal_input);\n    // match row number with outlier that we found, this is done\n    // since the actual outlier detection cannot accept row number\n    // and what we are returning is outliers\n    lookup_table tbl;\n    std::for_each(std::begin(outliers), std::end(outliers), \n            [this, &ol, &tbl] (auto outlier) {\n                auto off = tbl[outlier];\n                auto lib = std::begin(legal_input);\n                auto i = std::next(lib, off);\n                lib = std::find_if(i, std::end(legal_input), [outlier] (auto rd) {\n                        return rd.value == outlier;\n                    }\n                );\n                if (lib != std::end(legal_input)) {   // an error\n                    ol.push_back(lib->row);\n                    tbl[outlier] = std::distance(std::begin(legal_input), lib) + 1u;\n                    return false;\n                } else {\n                    return true;\n                }\n            }\n    );\n    if (missing.empty()) {  // we assume that if this is not missing then we fill it up in duplications\n        missing.insert(std::end(missing), std::begin(missings), std::end(missings));\n    }\n}\n\noutlier_predicate::result_type apply_action(outliers_detector& da, input_data arg)\n{\n    return da.apply_action(arg);\n}\n\nvoid finding(const outliers_detector& od, row_numbers& outlier, row_numbers& mis)\n{\n    od.finding(outlier, mis);\n}\n\n\n", "meta": {"hexsha": "e196559b66d7f21fea1c2ef73d7411d8a8768591", "size": 3469, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/apps/detect_duplicates/src/outliers_action.cpp", "max_stars_repo_name": "boazsade/machine_learinig_models", "max_stars_repo_head_hexsha": "eb1f9eda0e4e25a6d028b25682dfb20628a20624", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/apps/detect_duplicates/src/outliers_action.cpp", "max_issues_repo_name": "boazsade/machine_learinig_models", "max_issues_repo_head_hexsha": "eb1f9eda0e4e25a6d028b25682dfb20628a20624", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/apps/detect_duplicates/src/outliers_action.cpp", "max_forks_repo_name": "boazsade/machine_learinig_models", "max_forks_repo_head_hexsha": "eb1f9eda0e4e25a6d028b25682dfb20628a20624", "max_forks_repo_licenses": ["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.6991150442, "max_line_length": 103, "alphanum_fraction": 0.6405304122, "num_tokens": 811, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.491736420724172}}
{"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\n#include <boost/simd/sdk/simd/pack.hpp>\n#include <boost/simd/include/functions/plus.hpp>\n#include <boost/simd/include/functions/multiplies.hpp>\n#include <nt2/include/functions/aligned_store.hpp>\n#include <boost/simd/memory/allocator.hpp>\n#include <boost/fusion/include/at.hpp>\n#include <vector>\n\n#include <nt2/sdk/bench/benchmark.hpp>\n#include <nt2/sdk/bench/metric/gflops.hpp>\n#include <nt2/sdk/bench/protocol/max_duration.hpp>\n#include <nt2/sdk/bench/setup/geometric.hpp>\n#include <nt2/sdk/bench/setup/constant.hpp>\n#include <nt2/sdk/bench/setup/combination.hpp>\n#include <nt2/sdk/bench/stats/median.hpp>\n\nusing namespace nt2::bench;\nusing namespace nt2;\n\ntemplate<typename T> struct axpy_simd\n{\n  template<typename Setup>\n  axpy_simd(Setup const& s)\n              :  alpha(boost::fusion::at_c<1>(s))\n              ,  size_(boost::fusion::at_c<0>(s))\n  {\n    X.resize(size_); Y.resize(size_);\n    for(std::size_t i = 0; i<size_; ++i)\n      X[i] = Y[i] = T(i);\n  }\n\n  void operator()()\n  {\n    using boost::simd::pack;\n    using boost::simd::aligned_store;\n\n    typedef pack<T> type;\n    std::size_t step_size_ = boost::simd::meta::cardinal_of<type>::value;\n    for (std::size_t i = 0; i<size_; i+=step_size_)\n    {\n      type X_pack(&X[i]);\n      type Y_pack(&Y[i]);\n      aligned_store( alpha * X_pack + Y_pack, &Y[i] );\n    }\n  }\n\n  friend std::ostream& operator<<(std::ostream& os, axpy_simd<T> const& p)\n  {\n    return os << \"(\" << p.size() << \")\";\n  }\n\n  std::size_t size() const { return size_; }\n  double flops() const { return 2.*size_; }\n\nprivate:\n  T alpha;\n  std::size_t size_;\n  typename std::vector<T, boost::simd::allocator<T> > X, Y;\n};\n\nNT2_REGISTER_BENCHMARK_TPL( axpy_simd, NT2_SIMD_REAL_TYPES )\n{\n  std::size_t size_min  = args(\"size_min\",   16);\n  std::size_t size_max  = args(\"size_max\", 4096);\n  std::size_t size_step = args(\"size_step\",   2);\n  T alpha = args(\"alpha\", 1.);\n\n  run_during_with< axpy_simd<T> > ( 1.\n                                  , and_( geometric(size_min,size_max,size_step)\n                                        , constant(alpha)\n                                        )\n                                  , gflops<stats::median_>()\n                                  );\n}\n", "meta": {"hexsha": "dc87737895e983d82aad35046cb59c5eaa9ed960", "size": 2778, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "demo/saxpy/simd/saxpy_simd.cpp", "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": "demo/saxpy/simd/saxpy_simd.cpp", "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": "demo/saxpy/simd/saxpy_simd.cpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 32.6823529412, "max_line_length": 80, "alphanum_fraction": 0.5683945284, "num_tokens": 732, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.4917175593238582}}
{"text": "#ifndef MAIA_GAMEENGINE_LOCALROTATION_H_INCLUDED\n#define MAIA_GAMEENGINE_LOCALROTATION_H_INCLUDED\n\n#include <Eigen/Geometry>\n\nnamespace Maia::GameEngine::Components\n{\n\tstruct Local_rotation\n\t{\n\t\tEigen::Quaternionf value{ 1.0f, 0.0f, 0.0f, 0.0f };\n\t};\n}\n\n#endif", "meta": {"hexsha": "73f0e7d416c89dbdff94a8bec388f96637344905", "size": 260, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Source/Maia/GameEngine/Components/Local_rotation.hpp", "max_stars_repo_name": "JPMMaia/GameEngine", "max_stars_repo_head_hexsha": "d00362758f2ef20b3a2e85aaea0c7c637b02ea05", "max_stars_repo_licenses": ["MIT"], "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/Maia/GameEngine/Components/Local_rotation.hpp", "max_issues_repo_name": "JPMMaia/GameEngine", "max_issues_repo_head_hexsha": "d00362758f2ef20b3a2e85aaea0c7c637b02ea05", "max_issues_repo_licenses": ["MIT"], "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/Maia/GameEngine/Components/Local_rotation.hpp", "max_forks_repo_name": "JPMMaia/GameEngine", "max_forks_repo_head_hexsha": "d00362758f2ef20b3a2e85aaea0c7c637b02ea05", "max_forks_repo_licenses": ["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.5714285714, "max_line_length": 53, "alphanum_fraction": 0.7807692308, "num_tokens": 80, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.4917175593238582}}
{"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#include \"convenience.h\"\n#include <boost/numeric/bindings/lapack/driver/gelsd.hpp>\n\n// set to 1 to write test output to file, otherwise outputs to console\n#define OUTPUT_TO_FILE 0\n\n// determines which tests to run\n#define TEST_SQUARE 1\n#define TEST_UNDERDETERMINED 1\n#define TEST_OVERDETERMINED 1\n#define TEST_MULTIPLE_SOLUTION_VECTORS 1\n\n// determines if optimal, minimal, or both workspaces are used for testing\n#define USE_OPTIMAL_WORKSPACE 1\n#define USE_MINIMAL_WORKSPACE 1\n\nnamespace lapack = boost::numeric::bindings::lapack;\nnamespace bindings = boost::numeric::bindings;\n\n// test function declarations\ntemplate <typename StreamType, typename MatrType, typename VecType>\nint test_square_gelsd(StreamType& oss);\n\ntemplate <typename StreamType, typename MatType, typename VecType>\nint test_under_gelsd(StreamType& oss);\n\ntemplate <typename StreamType, typename MatType, typename VecType>\nint test_over_gelsd(StreamType& oss);\n\ntemplate <typename StreamType, typename MatType, typename VecType>\nint test_multiple_gelsd(StreamType& oss);\n\ntemplate <typename StreamType, typename MatType, typename VecType>\nint test_transpose_gel(StreamType& oss, const char& trans);\n\n\nint main()\n{\n  // stream for test output\n  typedef std::ostringstream stream_t;\n  stream_t oss;\n\n#if TEST_SQUARE\n  oss << \"Start Square Matrix Least Squares Tests\" << std::endl;\n  oss << \"Testing sgelsd\" << std::endl;\n  if(test_square_gelsd<stream_t, fmat_t, fvec_t>(oss) == 0)\n  {\n    oss << \"sgelsd passed.\" << std::endl;\n  }\n  else return 255;\n  oss << \"End sgelsd tests\" << std::endl;\n  oss << std::endl;\n  oss << \"Testing dgelsd\" << std::endl;\n  if(test_square_gelsd<stream_t, dmat_t, dvec_t>(oss) == 0)\n  {\n    oss << \"dgelsd passed.\" << std::endl;\n  }\n  else return 255;\n  oss << \"End dgelsd tests\" << std::endl;\n  oss << std::endl;\n  oss << \"Testing cgelsd\" << std::endl;\n  if(test_square_gelsd<stream_t, fcmat_t, fcvec_t>(oss) == 0)\n  {\n    oss << \"cgelsd passed.\" << std::endl;\n  }\n  else return 255;\n  oss << \"End cgelsd tests\" << std::endl;\n  oss << std::endl;\n  oss << \"Testing zgelsd\" << std::endl;\n  if(test_square_gelsd<stream_t, fcmat_t, fcvec_t>(oss) == 0)\n  {\n    oss << \"zgelsd passed.\" << std::endl;\n  }\n  else return 255;\n  oss << \"End zgelsd tests\" << std::endl;\n  oss << std::endl;\n  oss << \"End Square Matrix Least Squares Tests\" << std::endl;\n#endif\n\n#if TEST_UNDERDETERMINED\n  oss << std::endl;\n  oss << \"Start Under-determined Matrix Least Squares Test\" << std::endl;\n  oss << \"Testing sgelsd\" << std::endl;\n  if(test_under_gelsd<stream_t, fmat_t, fvec_t>(oss) == 0)\n  {\n    oss << \"sgelsd passed.\" << std::endl;\n  }\n  else return 255;\n  oss << \"End sgelsd tests\" << std::endl;\n  oss << std::endl;\n  oss << \"Testing dgelsd\" << std::endl;\n  if(test_under_gelsd<stream_t, dmat_t, dvec_t>(oss) == 0)\n  {\n    oss << \"dgelsd passed.\" << std::endl;\n  }\n  else return 255;\n  oss << \"End dgelsd tests\" << std::endl;\n  oss << std::endl;\n  oss << \"Testing cgelsd\" << std::endl;\n  if(test_under_gelsd<stream_t, fcmat_t, fcvec_t>(oss) == 0)\n  {\n    oss << \"cgelsd passed.\" << std::endl;\n  }\n  else return 255;\n  oss << \"End cgelsd tests\" << std::endl;\n  oss << std::endl;\n  oss << \"Testing zgelsd\" << std::endl;\n  if(test_under_gelsd<stream_t, fcmat_t, fcvec_t>(oss) == 0)\n  {\n    oss << \"zgelsd passed.\" << std::endl;\n  }\n  else return 255;\n  oss << \"End zgelsd tests\" << std::endl;\n  oss << std::endl;\n  oss << \"End Underdetermined Matrix Least Squares Tests\" << std::endl;\n#endif\n\n#if TEST_OVERDETERMINED\n  oss << std::endl;\n  oss << \"Start Overdetermined Matrix Least Squares Test\" << std::endl;\n  oss << \"Testing sgelsd\" << std::endl;\n  if(test_over_gelsd<stream_t, fmat_t, fvec_t>(oss) == 0)\n  {\n    oss << \"sgelsd passed.\" << std::endl;\n  }\n  else return 255;\n  oss << \"End sgelsd tests\" << std::endl;\n  oss << std::endl;\n  oss << \"Testing dgelsd\" << std::endl;\n  if(test_over_gelsd<stream_t, dmat_t, dvec_t>(oss) == 0)\n  {\n    oss << \"dgelsd passed.\" << std::endl;\n  }\n  else return 255;\n  oss << \"End dgelsd tests\" << std::endl;\n  oss << std::endl;\n  oss << \"Testing cgelsd\" << std::endl;\n  if(test_over_gelsd<stream_t, fcmat_t, fcvec_t>(oss) == 0)\n  {\n    oss << \"cgelsd passed.\" << std::endl;\n  }\n  else return 255;\n  oss << \"End cgelsd tests\" << std::endl;\n  oss << std::endl;\n  oss << \"Testing zgelsd\" << std::endl;\n  if(test_over_gelsd<stream_t, fcmat_t, fcvec_t>(oss) == 0)\n  {\n    oss << \"zgelsd passed.\" << std::endl;\n  }\n  else return 255;\n  oss << \"End zgelsd tests\" << std::endl;\n  oss << std::endl;\n  oss << \"End Overdetermined Matrix Least Squares Test\" << std::endl;\n#endif\n\n#if TEST_MULTIPLE_SOLUTION_VECTORS\n  oss << std::endl;\n  oss << \"Start Multiple Solution Vectors Least Squares Test\" << std::endl;\n  oss << \"Testing sgelsd\" << std::endl;\n  if(test_multiple_gelsd<stream_t, fmat_t, fvec_t>(oss) == 0)\n  {\n    oss << \"sgelsd passed.\" << std::endl;\n  }\n  else return 255;\n  oss << \"End sgelsd tests\" << std::endl;\n  oss << std::endl;\n  oss << \"Testing dgelsd\" << std::endl;\n  if(test_multiple_gelsd<stream_t, dmat_t, dvec_t>(oss) == 0)\n  {\n    oss << \"dgelsd passed.\" << std::endl;\n  }\n  else return 255;\n  oss << \"End dgelsd tests\" << std::endl;\n  oss << std::endl;\n  oss << \"Testing cgelsd\" << std::endl;\n  if(test_multiple_gelsd<stream_t, fcmat_t, fcvec_t>(oss) == 0)\n  {\n    oss << \"cgelsd passed.\" << std::endl;\n  }\n  else return 255;\n  oss << \"End cgelsd tests\" << std::endl;\n  oss << std::endl;\n  oss << \"Testing zgelsd\" << std::endl;\n  if(test_multiple_gelsd<stream_t, fcmat_t, fcvec_t>(oss) == 0)\n  {\n    oss << \"zgelsd passed.\" << std::endl;\n  }\n  else return 255;\n  oss << \"End zgelsd tests\" << std::endl;\n  oss << std::endl;\n  oss << \"End Multiple Solution Vectors Least Squares Test\" << std::endl;\n#endif\n\n#if OUTPUT_TO_FILE\n  // Finished testing\n  std::cout << std::endl;\n  std::cout << \"Tests Completed.\" << std::endl;\n  std::cout << std::endl;\n\n  std::string filename;\n  std::cout << \"Enter filename to write test results: \";\n  std::getline(std::cin, filename);\n\n  std::ofstream testFile(filename.c_str());\n\n  if(testFile)\n  {\n    testFile << oss.str();\n    testFile.close();\n  }\n#else\n  std::cout << oss.str() << std::endl;\n\n  // Finished testing\n  std::cout << std::endl;\n  std::cout << \"Tests Completed.\" << std::endl;\n  std::cout << std::endl;\n#endif\n\n  // wait for user to finish\n//\tstd::string done;\n//\tstd::cout << \"Press Enter to exit\";\n//\tstd::getline(std::cin, done);\n\n}\n\n// tests square system (m-by-n where m == n)\ntemplate <typename StreamType, typename MatType, typename VecType>\nint test_square_gelsd(StreamType& oss)\n{\n  typedef typename bindings::value_type<MatType>::type val_t;\n  typedef typename bindings::remove_imaginary<val_t>::type real_t;\n  const real_t rcond = -1;    // use machine precision\n  fortran_int_t rank;\n\n  // return value\n  int err = 0;\n\n  // square matrix test\n  MatType mat(MatrixGenerator<MatType>()(row_size, col_size));\n  VecType vec(VectorGenerator<VecType>()(row_size));\n\n  //const int m = bindings::size_row(mat);\n  const int n = bindings::size_column(mat);\n  bindings::detail::array<real_t> s(n);\n\n#if USE_OPTIMAL_WORKSPACE\n  MatType optimalmat(mat);\n  VecType optimalvec(vec);\n  err += lapack::gelsd(optimalmat, optimalvec, s, rcond, rank, lapack::optimal_workspace());\n  VecType optimalanswer(ublas::project(optimalvec, ublas::range(0, n)));\n  VecType optimal_check = ublas::prod(mat, optimalanswer);\n#endif\n#if USE_MINIMAL_WORKSPACE\n  MatType minimalmat(mat);\n  VecType minimalvec(vec);\n  err += lapack::gelsd(minimalmat, minimalvec, s, rcond, rank, lapack::minimal_workspace());\n  VecType minimalanswer(ublas::project(minimalvec, ublas::range(0, n)));\n  VecType minimal_check = ublas::prod(mat, minimalanswer);\n#endif\n\n  matrix_print(oss, \"A\", mat);\n  oss << std::endl;\n  vector_print(oss, \"B\", vec);\n  oss << std::endl;\n\n#if USE_OPTIMAL_WORKSPACE\n  vector_print(oss, \"optimal workspace x\", optimalanswer);\n  oss << std::endl;\n#endif\n#if USE_MINIMAL_WORKSPACE\n  vector_print(oss, \"minimal workspace x\", minimalanswer);\n  oss << std::endl;\n#endif\n#if USE_OPTIMAL_WORKSPACE\n  // check A*x=B\n  vector_print(oss, \"optimal A*x=B\", optimal_check);\n  oss << std::endl;\n#endif\n#if USE_MINIMAL_WORKSPACE\n  vector_print(oss, \"minimal A*x=B\", minimal_check);\n  oss << std::endl;\n#endif\n\n  return err;\n}\n\n// tests overdetermined system (m-by-n where m < n)\ntemplate <typename StreamType, typename MatType, typename VecType>\nint test_under_gelsd(StreamType& oss)\n{\n  typedef typename bindings::value_type<MatType>::type val_t;\n  typedef typename bindings::remove_imaginary<val_t>::type real_t;\n  const real_t rcond = -1;    // use machine precision\n  fortran_int_t rank;\n\n  // return value\n  int err = 0;\n\n  // under-determined matrix test\n  MatType mat(MatrixGenerator<MatType>()(row_range, col_size));\n  VecType vec(VectorGenerator<VecType>()(row_size));\n\n  //const int m = bindings::size_row(mat);\n  const int n = bindings::size_column(mat);\n  bindings::detail::array<real_t> s(n);\n\n#if USE_OPTIMAL_WORKSPACE\n  MatType optimalmat(mat);\n  VecType optimalvec(vec);\n  err += lapack::gelsd(optimalmat, optimalvec, s, rcond, rank, lapack::optimal_workspace());\n  VecType optimalanswer(ublas::project(optimalvec, ublas::range(0, n)));\n  VecType optimal_check = ublas::prod(mat, optimalanswer);\n#endif\n#if USE_MINIMAL_WORKSPACE\n  MatType minimalmat(mat);\n  VecType minimalvec(vec);\n  err += lapack::gelsd(minimalmat, minimalvec, s, rcond, rank, lapack::minimal_workspace());\n  VecType minimalanswer(ublas::project(minimalvec, ublas::range(0, n)));\n  VecType minimal_check = ublas::prod(mat, minimalanswer);\n#endif\n\n  matrix_print(oss, \"A\", mat);\n  oss << std::endl;\n  vector_print(oss, \"B\", vec);\n  oss << std::endl;\n\n#if USE_OPTIMAL_WORKSPACE\n  vector_print(oss, \"optimal workspace x\", optimalanswer);\n  oss << std::endl;\n#endif\n#if USE_MINIMAL_WORKSPACE\n  vector_print(oss, \"minimal workspace x\", minimalanswer);\n  oss << std::endl;\n#endif\n#if USE_OPTIMAL_WORKSPACE\n  // check A*x=B\n  vector_print(oss, \"optimal A*x=B\", optimal_check);\n  oss << std::endl;\n#endif\n#if USE_MINIMAL_WORKSPACE\n  vector_print(oss, \"minimal A*x=B\", minimal_check);\n  oss << std::endl;\n#endif\n\n  return err;\n}\n\n// tests overdetermined system (m-by-n where m > n)\ntemplate <typename StreamType, typename MatType, typename VecType>\nint test_over_gelsd(StreamType& oss)\n{\n  typedef typename bindings::value_type<MatType>::type val_t;\n  typedef typename bindings::remove_imaginary<val_t>::type real_t;\n  const real_t rcond = -1;    // use machine precision\n  fortran_int_t rank;\n\n  // return value\n  int err = 0;\n\n  // overdetermined matrix test\n  MatType mat(MatrixGenerator<MatType>()(row_size, col_range));\n  VecType vec(VectorGenerator<VecType>()(row_size));\n\n  //const int m = bindings::size_row(mat);\n  const int n = bindings::size_column(mat);\n  bindings::detail::array<real_t> s(n);\n\n#if USE_OPTIMAL_WORKSPACE\n  MatType optimalmat(mat);\n  VecType optimalvec(vec);\n  err += lapack::gelsd(optimalmat, optimalvec, s, rcond, rank, lapack::optimal_workspace());\n  VecType optimalanswer(ublas::project(optimalvec, ublas::range(0, n)));\n  VecType optimal_check = ublas::prod(mat, optimalanswer);\n#endif\n#if USE_MINIMAL_WORKSPACE\n  MatType minimalmat(mat);\n  VecType minimalvec(vec);\n  err += lapack::gelsd(minimalmat, minimalvec, s, rcond, rank, lapack::minimal_workspace());\n  VecType minimalanswer(ublas::project(minimalvec, ublas::range(0, n)));\n  VecType minimal_check = ublas::prod(mat, minimalanswer);\n#endif\n\n  matrix_print(oss, \"A\", mat);\n  oss << std::endl;\n  vector_print(oss, \"B\", vec);\n  oss << std::endl;\n\n#if USE_OPTIMAL_WORKSPACE\n  vector_print(oss, \"optimal workspace x\", optimalanswer);\n  oss << std::endl;\n#endif\n#if USE_MINIMAL_WORKSPACE\n  vector_print(oss, \"minimal workspace x\", minimalanswer);\n  oss << std::endl;\n#endif\n#if USE_OPTIMAL_WORKSPACE\n  // check A*x=B\n  vector_print(oss, \"optimal A*x=B\", optimal_check);\n  oss << std::endl;\n#endif\n#if USE_MINIMAL_WORKSPACE\n  vector_print(oss, \"minimal A*x=B\", minimal_check);\n  oss << std::endl;\n#endif\n\n  return err;\n}\n\n// tests multiple solution vectors stored column-wise in B for equation A*x=B\ntemplate <typename StreamType, typename MatType, typename VecType>\nint test_multiple_gelsd(StreamType& oss)\n{\n  typedef typename bindings::value_type<MatType>::type val_t;\n  typedef typename bindings::remove_imaginary<val_t>::type real_t;\n  const real_t rcond = -1;    // use machine precision\n  fortran_int_t rank;\n\n  // return value\n  int err = 0;\n\n  // multiple solutions vectors test\n  MatType mat(MatrixGenerator<MatType>()(row_size, col_size));\n  MatType vec(mat.size1(), 2);\n  ublas::column(vec, 0) = VectorGenerator<VecType>()(mat.size1());\n  ublas::column(vec, 1) = VectorGenerator<VecType>()(mat.size1());\n\n  //const int m = bindings::size_row(mat);\n  const int n = bindings::size_column(mat);\n  const int nrhs = bindings::size_column(vec);\n  bindings::detail::array<real_t> s(n);\n\n#if USE_OPTIMAL_WORKSPACE\n  MatType optimalmat(mat);\n  MatType optimalvec(vec);\n  err += lapack::gelsd(optimalmat, optimalvec, s, rcond, rank, lapack::optimal_workspace());\n  MatType optimalanswer(ublas::project(optimalvec, ublas::range(0, n), ublas::range(0, nrhs)));\n  MatType optimal_check = ublas::prod(mat, optimalanswer);\n#endif\n#if USE_MINIMAL_WORKSPACE\n  MatType minimalmat(mat);\n  MatType minimalvec(vec);\n  err += lapack::gelsd(minimalmat, minimalvec, s, rcond, rank, lapack::minimal_workspace());\n  MatType minimalanswer(ublas::project(minimalvec, ublas::range(0, n), ublas::range(0, nrhs)));\n  MatType minimal_check = ublas::prod(mat, minimalanswer);\n#endif\n\n  matrix_print(oss, \"A\", mat);\n  oss << std::endl;\n  matrix_print(oss, \"B\", vec);\n  oss << std::endl;\n\n#if USE_OPTIMAL_WORKSPACE\n  matrix_print(oss, \"optimal workspace x\", optimalanswer);\n  oss << std::endl;\n#endif\n#if USE_MINIMAL_WORKSPACE\n  matrix_print(oss, \"minimal workspace x\", minimalanswer);\n  oss << std::endl;\n#endif\n#if USE_OPTIMAL_WORKSPACE\n  // check A*x=B\n  matrix_print(oss, \"optimal A*x=B\", optimal_check);\n  oss << std::endl;\n#endif\n#if USE_MINIMAL_WORKSPACE\n  matrix_print(oss, \"minimal A*x=B\", minimal_check);\n  oss << std::endl;\n#endif\n\n  return err;\n}\n", "meta": {"hexsha": "b16ebd9b36f987644e2696c540c60ae497b5760c", "size": 14342, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "externals/numeric_bindings/libs/numeric/bindings/lapack/test/ublas_gelsd.cpp", "max_stars_repo_name": "fperignon/sandbox", "max_stars_repo_head_hexsha": "649f09d6db7bbd84c2418de74eb9453c0131f070", "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/lapack/test/ublas_gelsd.cpp", "max_issues_repo_name": "fperignon/sandbox", "max_issues_repo_head_hexsha": "649f09d6db7bbd84c2418de74eb9453c0131f070", "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/lapack/test/ublas_gelsd.cpp", "max_forks_repo_name": "fperignon/sandbox", "max_forks_repo_head_hexsha": "649f09d6db7bbd84c2418de74eb9453c0131f070", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 30.0, "max_forks_repo_forks_event_min_datetime": "2015-08-06T22:57:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T20:30:20.000Z", "avg_line_length": 29.817047817, "max_line_length": 95, "alphanum_fraction": 0.6872821085, "num_tokens": 4336, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548646660542, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.49171754910554005}}
{"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_NORMALIZE_HPP\n#define SP_ALGO_NN_NORMALIZE_HPP\n\n#include <boost/assert.hpp>\n#include \"sp/config.hpp\"\n#include \"matrix.hpp\"\n#include \"types.hpp\"\n#include \"layer/detail/layers.hpp\"\n\n\nSP_ALGO_NN_NAMESPACE_BEGIN\n\n/**\n * \\file Utility to normalize values for the network specified.\n */\n\n/**\n * \\brief Normalize and scale all values and translate to output maximum\n *\n * Note: considers all element at once for min/max of samples\n */\ntemplate<typename Network>\nvoid normalize_and_scale(Network& network, sample_vector_type& vec) {\n    auto [a, b] = network.out_range();\n    float_t min = b;\n    float_t max = a;\n    for(const auto& v : vec) {\n        //find min, max\n        std::for_each(v.data(), v.data() + v.size(), [&](auto& x) {\n            max = std::max(x, max);\n            min = std::min(x, min);\n        });\n    }\n\n    /**\n     * Perform translation and scaling at the same time: First, scale value v_i\n     * to [min, max], then rescale to [a, b].\n     */\n    for(auto& v : vec) {\n        v = ((b - a) * (v - min) / ( max - min)) + a;\n    }\n}\n\n/**\n * \\brief Normalize input_type given the network parameters into an input_type\n *\n * @param network\n * @return\n */\ntemplate<typename Network>\nauto prepare_batch(Network& network, const size_t& batch_size, sample_vector_type& samples) {\n    BOOST_ASSERT(batch_size >= 1);\n    BOOST_ASSERT(!samples.empty());\n\n    const size_t input_count = samples.size();\n    const size_t batch_count = input_count / batch_size;\n\n    const auto& sample_dims = samples[0].dimensions();\n\n    std::vector<tensor_4> vec(\n        batch_count,\n        tensor_4(\n            batch_size,\n            sample_dims[0],\n            sample_dims[1],\n            sample_dims[2]\n        )\n    );\n\n    /**\n     * Merge input sample_type into input_type batch\n     */\n    for(size_t b = 0; b < batch_count; ++b) {\n        for(size_t s = 0; s < batch_size; ++s) {\n            BOOST_ASSERT_MSG(\n                detail::validate_dimensions<typename Network::input_dims>(samples[b*batch_size+s]),\n                \"Dimensions of sample matches network input dimension\"\n            );\n            vec[b].chip(s, 0) = samples[b*batch_size + s];\n        }\n    }\n\n    return vec;\n}\n\n/**\n * \\brief Prepare samples into batch format of input_type given the network parameters into an input_type\n *\n * @param network\n * @return\n */\ntemplate<typename Network>\nauto prepare_batch(Network& network, sample_vector_type& samples) {\n    return prepare_labels(network, 1, samples);\n}\n\n/**\n * \\brief Prepare a batch of input_type given the network parameters into an input_type\n *\n * @param network\n * @return\n */\ntemplate<typename Network>\nauto prepare_batch(Network& network, sample_type& sample) {\n    sample_vector_type vec{sample};\n    return prepare_labels(network, 1, vec)[0];\n}\n\n\nnamespace detail {\n    /**\n     * \\brief Convert class vector type to a a vector of output_type\n     */\n    template<typename Network>\n    auto normalize_label_to_vector_helper(Network& network, const size_t& batch_size, class_vector_type& classes) {\n\n        const size_t class_count = classes.size();\n        const size_t batch_count = class_count / batch_size;\n\n        /* Output is a vector of output_type */\n        std::vector<tensor_4> vec(\n            /* of dimensions (1, 1, 1, the size of the output of the last layer) */\n            batch_count, tensor_4(batch_size, Network::output_dims::size, 1, 1)\n        );\n\n        auto[min, max] = network.out_target_range();\n\n        for(size_t b = 0; b < batch_count; ++b) {\n            /* default to minimum value */\n            vec[b].setConstant(min);\n            for(size_t s = 0; s < batch_size; ++s) {\n                const size_t idx = b * batch_size + s;\n\n                BOOST_ASSERT_MSG(\n                    classes[idx] < Network::output_dims::size,\n                    \"Class value can not exceeds network output size\"\n                );\n                /* set the max value to output layer max */\n                vec[b](s, classes[idx], 0, 0) = max;\n            }\n        }\n\n        return vec;\n    }\n}\n\n/**\n * \\brief Normalize a vector of classes\n */\ntemplate<typename Network>\nstd::vector<tensor_4> prepare_labels(     Network& network,\n                                        const size_t& batch_size,\n                                        class_vector_type& classes) {\n    return detail::normalize_label_to_vector_helper(network, batch_size, classes);\n}\n\n/**\n * \\brief Normalize a vector of classes\n */\ntemplate<typename Network>\nstd::vector<tensor_4> prepare_batch(     Network& network,\n                                        class_vector_type& classes) {\n    return prepare_labels(network, 1, classes);\n}\n\n\n\n/**\n * \\brief Converters a vector of a vector to a vector of sample_type\n */\nsample_vector_type nested_vector_to_sample_vector(std::vector<std::vector<float_t>> vectors) {\n    if(vectors.empty()) {\n        return {};\n    } else {\n        const size_t vector_element_count = vectors[0].size();\n        sample_vector_type res(vectors.size(), sample_type(1, 1, vector_element_count));\n        size_t idx = 0;\n        for(auto& v : vectors) {\n            auto& r = res[idx];\n            float_t* start = r.data();\n            BOOST_ASSERT((static_cast<size_t>(std::distance(start, r.data() + r.size())) == vector_element_count));\n            BOOST_ASSERT(vector_element_count == v.size());\n            std::copy(v.begin(), v.end(), start);\n            ++idx;\n        }\n        return res;\n    }\n}\nSP_ALGO_NN_NAMESPACE_END\n\n#endif\t/* SP_ALGO_NN_NORMALIZE_HPP */\n\n", "meta": {"hexsha": "d673d6d418896a3ba26e4a3f6acbce4a9fcfff20", "size": 5791, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/sp/algo/nn/normalize.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/normalize.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/normalize.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": 28.8109452736, "max_line_length": 115, "alphanum_fraction": 0.6106026593, "num_tokens": 1348, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.754914975839675, "lm_q2_score": 0.6513548714339144, "lm_q1q2_score": 0.4917175470315881}}
{"text": "\r\n///////////////////////////////////////////////////////////////////////////////\r\n//  Copyright 2013 Nikhar Agrawal\r\n//  Copyright 2013 Christopher Kormanyos\r\n//  Copyright 2014 John Maddock\r\n//  Copyright 2013 Paul Bristow\r\n//  Distributed under the Boost\r\n//  Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef _BOOST_POLYGAMMA_2013_07_30_HPP_\r\n  #define _BOOST_POLYGAMMA_2013_07_30_HPP_\r\n\r\n#include <boost/math/special_functions/factorials.hpp>\r\n#include <boost/math/special_functions/detail/polygamma.hpp>\r\n#include <boost/math/special_functions/trigamma.hpp>\r\n\r\nnamespace boost { namespace math {\r\n\r\n  \r\n  template<class T, class Policy>\r\n  inline typename tools::promote_args<T>::type polygamma(const int n, T x, const Policy& pol)\r\n  {\r\n     //\r\n     // Filter off special cases right at the start:\r\n     //\r\n     if(n == 0)\r\n        return boost::math::digamma(x, pol);\r\n     if(n == 1)\r\n        return boost::math::trigamma(x, pol);\r\n     //\r\n     // We've found some standard library functions to misbehave if any FPU exception flags\r\n     // are set prior to their call, this code will clear those flags, then reset them\r\n     // on exit:\r\n     //\r\n     BOOST_FPU_EXCEPTION_GUARD\r\n     //\r\n     // The type of the result - the common type of T and U after\r\n     // any integer types have been promoted to double:\r\n     //\r\n     typedef typename tools::promote_args<T>::type result_type;\r\n     //\r\n     // The type used for the calculation.  This may be a wider type than\r\n     // the result in order to ensure full precision:\r\n     //\r\n     typedef typename policies::evaluation<result_type, Policy>::type value_type;\r\n     //\r\n     // The type of the policy to forward to the actual implementation.\r\n     // We disable promotion of float and double as that's [possibly]\r\n     // happened already in the line above.  Also reset to the default\r\n     // any policies we don't use (reduces code bloat if we're called\r\n     // multiple times with differing policies we don't actually use).\r\n     // Also normalise the type, again to reduce code bloat in case we're\r\n     // called multiple times with functionally identical policies that happen\r\n     // to be different types.\r\n     //\r\n     typedef typename policies::normalise<\r\n        Policy,\r\n        policies::promote_float<false>,\r\n        policies::promote_double<false>,\r\n        policies::discrete_quantile<>,\r\n        policies::assert_undefined<> >::type forwarding_policy;\r\n     //\r\n     // Whew.  Now we can make the actual call to the implementation.\r\n     // Arguments are explicitly cast to the evaluation type, and the result\r\n     // passed through checked_narrowing_cast which handles things like overflow\r\n     // according to the policy passed:\r\n     //\r\n     return policies::checked_narrowing_cast<result_type, forwarding_policy>(\r\n        detail::polygamma_imp(n, static_cast<value_type>(x), forwarding_policy()),\r\n        \"boost::math::polygamma<%1%>(int, %1%)\");\r\n  }\r\n\r\n  template<class T>\r\n  inline typename tools::promote_args<T>::type polygamma(const int n, T x)\r\n  {\r\n      return boost::math::polygamma(n, x, policies::policy<>());\r\n  }\r\n\r\n} } // namespace boost::math\r\n\r\n#endif // _BOOST_BERNOULLI_2013_05_30_HPP_\r\n\r\n", "meta": {"hexsha": "6f36c4627b9476a3f34767965cf43688f6854de8", "size": 3292, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ios/Pods/boost-for-react-native/boost/math/special_functions/polygamma.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/special_functions/polygamma.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/special_functions/polygamma.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.1904761905, "max_line_length": 94, "alphanum_fraction": 0.6549210207, "num_tokens": 776, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370423, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.4917006953707739}}
{"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://graphlab.org\n *\n */\n\n\n/**\n * \\file\n * \n * \\brief The main file for the BIAS-SGD matrix factorization algorithm.\n *\n * This file contains the main body of the BIAS-SGD matrix factorization\n * algorithm. \n */\n\n#include <graphlab/util/stl_util.hpp>\n#include <graphlab.hpp>\n#include \"eigen_serialization.hpp\"\n#include <Eigen/Dense>\n#include <graphlab/macros_def.hpp>\n\n\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;\nfloat itmBiasStep = 1e-4;\nfloat itmBiasReg = 1e-4;\nfloat usrBiasStep = 1e-4;\nfloat usrBiasReg = 1e-4;\nfloat usrFctrStep = 1e-4;\nfloat usrFctrReg = 1e-4;\nfloat itmFctrStep = 1e-4;\nfloat itmFctrReg = 1e-4; //gamma7\nfloat itmFctr2Step = 1e-4;\nfloat itmFctr2Reg = 1e-4;\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 BIASSGD graph.  Associated with each vertex is a pvec\n * (vector) of latent parameters that represent that vertex.  The goal\n * of the BIASSGD 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 number of times this vertex has been updated. */\n  uint32_t nupdates;\n  /** \\brief The latent pvec for this vertex */\n  vec_type pvec;\n  vec_type weight;\n  double bias;\n  /** \n   * \\brief Simple default constructor which randomizes the vertex\n   *  data \n   */\n  vertex_data() : nupdates(0) { randomize(); } \n  /** \\brief Randomizes the latent pvec */\n  void randomize() { pvec.resize(NLATENT); pvec.setRandom(); weight.resize(NLATENT); weight.setRandom(); }\n  /** \\brief Save the vertex data to a binary archive */\n  void save(graphlab::oarchive& arc) const { \n    arc << nupdates << pvec << weight << bias;\n  }\n  /** \\brief Load the vertex data from a binary archive */\n  void load(graphlab::iarchive& arc) { \n    arc >> nupdates >> pvec >> weight >> bias;\n  }\n}; // end of vertex data\n\n\n/**\n * \\brief The edge data stores the entry in the matrix.\n *\n * In addition the edge data svdppo 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\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;\n\n#include \"implicit.hpp\"\n\ndouble extract_l2_error(const graph_type::edge_type & edge);\n\n\n/**\n * \\brief Given a vertex and an edge return the other vertex in the\n * edge.\n */\ninline graph_type::vertex_type\nget_other_vertex(graph_type::edge_type& edge, \n    const graph_type::vertex_type& vertex) {\n  return vertex.id() == edge.source().id()? edge.target() : edge.source();\n}; // end of get_other_vertex\n\n\n\n\n\n/**\n * \\brief The gather type used to construct XtX and Xty needed for the BIASSGD\n * update\n *\n * To compute the ALS update we need to compute the sum of \n * \\code\n *  sum: XtX = nbr.pvec.transpose() * nbr.pvec \n *  sum: Xy  = nbr.pvec * edge.obs\n * \\endcode\n * For each of the neighbors of a vertex. \n *\n * To do this in the Gather-Apply-Scatter model the gather function\n * computes and returns a pair consisting of XtX and Xy which are then\n * added. The gather type represents that tuple and provides the\n * necessary gather_type::operator+= operation.\n *\n */\nclass gather_type {\n  public:\n    /**\n     * \\brief Stores the current sum of nbr.pvec.transpose() *\n     * nbr.pvec\n     */\n\n    /**\n     * \\brief Stores the current sum of nbr.pvec * edge.obs\n     */\n    vec_type pvec;\n    vec_type weight;\n    double bias;\n\n    /** \\brief basic default constructor */\n    gather_type() { }\n\n    /**\n     * \\brief This constructor computes XtX and Xy and stores the result\n     * in XtX and Xy\n     */\n    gather_type(const vec_type& X, const vec_type & _weight, double _bias) {\n      pvec = X;\n      bias = _bias;\n      weight = _weight;\n    } // end of constructor for gather type\n\n    /** \\brief Save the values to a binary archive */\n    void save(graphlab::oarchive& arc) const { arc << pvec << bias << weight; }\n\n    /** \\brief Read the values from a binary archive */\n    void load(graphlab::iarchive& arc) { arc >> pvec >> bias >> weight; }  \n\n    /** \n     * \\brief Computes XtX += other.XtX and Xy += other.Xy updating this\n     * tuples value\n     */\n    gather_type& operator+=(const gather_type& other) {\n      if (pvec.size() == 0){\n        pvec = other.pvec;\n        bias = other.bias;\n        weight = other.weight;\n        return *this;\n      }\n      else if (other.pvec.size() == 0)\n        return *this;\n      pvec += other.pvec;\n      bias += other.bias;\n      weight += other.weight;\n      return *this;\n    } // end of operator+=\n\n}; // end of gather type\n\n//typedef gather_type message_type;\n\n\nenum{\n  PHASE1 = 0, PHASE2 = 1\n};\n\n/**\n * BIASSGD vertex program type\n */ \nclass svdpp_vertex_program : \n  public graphlab::ivertex_program<graph_type, gather_type,\n  gather_type> {\n    public:\n      /** The convergence tolerance */\n      static double TOLERANCE;\n      static double LAMBDA;\n      static double GAMMA;\n      static double MAXVAL;\n      static double MINVAL;\n      static double STEP_DEC;\n      static bool debug;\n      static size_t MAX_UPDATES;\n      static double GLOBAL_MEAN;\n      static size_t NUM_TRAINING_EDGES;\n      static uint   USERS;\n\n      gather_type pmsg;\n      void save(graphlab::oarchive& arc) const { \n        arc << pmsg;\n      }\n      /** \\brief Load the vertex data from a binary archive */\n      void load(graphlab::iarchive& arc) { \n        arc >> pmsg;\n      }\n\n      /** The set of edges to gather along */\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      gather_type gather(icontext_type& context, const vertex_type& vertex, \n          edge_type& edge) const {\n        vec_type step = vec_type::Zero(vertex_data::NLATENT);\n        double bias =0, other_bias = 0;\n        vec_type delta, other_delta;\n\n        //user node\n        if (vertex.num_in_edges() == 0){\n          vertex_type other_vertex(get_other_vertex(edge, vertex));\n          vertex_type my_vertex(vertex);\n\n          int phase = my_vertex.data().nupdates % 2; \n          if (phase == PHASE1){\n            //my_vertex.data().weight += movie.weight;\n            context.signal(other_vertex, gather_type(vec_type::Zero(vertex_data::NLATENT), vec_type::Zero(vertex_data::NLATENT), 0));\n            return gather_type(vec_type::Zero(vertex_data::NLATENT), other_vertex.data().weight, 0);\n          }\n          else if (phase == PHASE2){\n            //vertex_data & my_data = my_vertex.data();\n            double pred = svdpp_vertex_program::GLOBAL_MEAN + \n              my_vertex.data().bias + other_vertex.data().bias + my_vertex.data().pvec.dot(other_vertex.data().pvec+other_vertex.data().weight);\n            pred = std::min(pred, svdpp_vertex_program::MAXVAL);\n            pred = std::max(pred, svdpp_vertex_program::MINVAL); \n            const float err = edge.data().obs - pred;\n            if (debug)\n              std::cout<<\"entering edge \" << (int)edge.source().id() << \":\" << (int)edge.target().id() << \" err: \" << err << \" rmse: \" << err*err <<std::endl;\n            if (std::isnan(err))\n              logstream(LOG_FATAL)<<\"Got into numeric errors.. try to tune step size and regularization using command line flags\" << std::endl;\n            if (edge.data().role == edge_data::TRAIN){\n              vec_type itmFctr = other_vertex.data().pvec;\n              vec_type usrFctr = my_vertex.data().pvec;\n\n              bias = usrBiasStep*(err - usrBiasReg*bias);\n              other_bias = itmBiasStep*(err - itmBiasReg*other_bias);\n\n              delta = usrFctrStep*(err*(itmFctr - usrFctrReg *usrFctr));\n              other_delta = itmFctrStep*(err*(usrFctr+my_vertex.data().weight) - itmFctrReg*other_vertex.data().pvec);\n\n              step = err*itmFctr;\n              float usrNorm = double(1.0/sqrt(my_vertex.num_out_edges()));\n              step *= itmFctr2Step*usrNorm;\n\n              double mult = itmFctr2Step*itmFctr2Reg;\n              step -= mult*other_vertex.data().weight; \n              //A HACK: update memory cached values to reflect new vals \n              /*my_vertex.data().bias += bias;\n                other_vertex.data().bias += other_bias;\n                my_vertex.data().pvec += delta;\n                other_vertex.data().pvec += other_delta;*/\n\n              if (debug)\n                std::cout<<\"new val:\" << (int)edge.source().id() << \":\" << (int)edge.target().id() << \" U \" << my_vertex.data().pvec.transpose() << \" V \" << other_vertex.data().pvec.transpose() << std::endl;\n\n              if(other_vertex.data().nupdates < MAX_UPDATES) \n                context.signal(other_vertex, gather_type(other_delta, step, other_bias));\n            }\n            return gather_type(delta, step, bias);\n\n          } //end of PHASE2\n        }\n        return gather_type(delta, step, bias);\n      }  \n\n      //typedef vec_type message_type;\n      void init(icontext_type& context,\n          const vertex_type& vertex,\n          const message_type& msg) {\n\n        int phase = vertex.data().nupdates % 2;\n        //movie node receives updates here\n        if (vertex.num_in_edges() > 0){\n          if (phase == PHASE1){\n            pmsg = msg;\n          }\n          else if (phase == PHASE2){\n            pmsg = msg;\n          }\n        }\n      }\n\n      /** apply collects the sum of XtX and Xy */\n      void apply(icontext_type& context, vertex_type& vertex,\n          const gather_type& sum) {\n        vertex_data& vdata = vertex.data(); \n        int phase = vdata.nupdates %2;\n\n        if (phase == PHASE1){\n          //user node receives the sum of movie weights\n          if (vertex.num_out_edges() > 0){\n            vertex.data().weight = sum.pvec;\n            float usrNorm = double(1.0/sqrt(vertex.num_out_edges()));\n            vertex.data().weight *= usrNorm;\n          }\n          //movie node doe nothing\n          else {}\n        }\n        else if (phase == PHASE2){\n          //user node update gradients and bias\n          if (vertex.num_in_edges() == 0){\n            vdata.pvec += sum.pvec;\n            vdata.bias += sum.bias;\n            //does not update weight here (since was done in phase1)\n          }\n          //movie node\n          else {\n            vdata.weight += pmsg.weight; //step\n            vdata.pvec += pmsg.pvec;\n            vdata.bias += pmsg.bias;\n          }\n        }\n        ++vdata.nupdates;\n      } // end of apply\n\n      /** The edges to scatter along */\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      /** Scatter reschedules neighbors */  \n      void scatter(icontext_type& context, const vertex_type& vertex, \n          edge_type& edge) const {\n        edge_data& edata = edge.data();\n        if(edata.role == edge_data::TRAIN) {\n          const vertex_type other_vertex = get_other_vertex(edge, vertex);\n          // Reschedule neighbors ------------------------------------------------\n          if(other_vertex.data().nupdates < MAX_UPDATES) \n            context.signal(other_vertex, gather_type(vec_type::Zero(vertex_data::NLATENT),vec_type::Zero(vertex_data::NLATENT),0));\n        }\n      } // end of scatter function\n\n\n      /**\n       * \\brief Signal all vertices on one side of the bipartite graph\n       */\n      static graphlab::empty signal_left(icontext_type& context,\n          vertex_type& vertex) {\n        if(vertex.num_out_edges() > 0) context.signal(vertex, gather_type(vec_type::Zero(vertex_data::NLATENT),vec_type::Zero(vertex_data::NLATENT),0));\n        return graphlab::empty();\n      } // end of signal_left \n\n  }; // end of svdpp vertex program\n\n\nstruct error_aggregator : public graphlab::IS_POD_TYPE {\n  typedef svdpp_vertex_program::icontext_type icontext_type;\n  typedef graph_type::edge_type edge_type;\n  double train_error, validation_error;\n  size_t ntrain, nvalidation;\n  error_aggregator() : \n    train_error(0), validation_error(0), ntrain(0), nvalidation(0) { }\n  error_aggregator& operator+=(const error_aggregator& other) {\n    train_error += other.train_error;\n    assert(!std::isnan(train_error));\n    validation_error += other.validation_error;\n    ntrain += other.ntrain;\n    nvalidation += other.nvalidation;\n    return *this;\n  }\n  static error_aggregator map(icontext_type& context, const graph_type::edge_type& edge) {\n    error_aggregator agg;\n    if (edge.data().role == edge_data::TRAIN){\n      agg.train_error = extract_l2_error(edge); agg.ntrain = 1;\n      assert(!std::isnan(agg.train_error));\n    }\n    else if (edge.data().role == edge_data::VALIDATE){\n      agg.validation_error = extract_l2_error(edge); agg.nvalidation = 1;\n    }\n    return agg;\n  }\n\n\n  static void finalize(icontext_type& context, const error_aggregator& agg) {\n    iter++;\n    if (iter%2 == 0)\n      return; \n    ASSERT_GT(agg.ntrain, 0);\n    const double train_error = std::sqrt(agg.train_error / agg.ntrain);\n    assert(!std::isnan(train_error));\n    context.cout() << std::setw(8) << context.elapsed_seconds() << std::setw(8) << train_error;\n    if(agg.nvalidation > 0) {\n      const double validation_error = \n        std::sqrt(agg.validation_error / agg.nvalidation);\n      context.cout() << std::setw(8) << validation_error; \n    }\n    context.cout() << std::endl;\n    usrBiasStep *= svdpp_vertex_program::STEP_DEC;\n    itmBiasStep *= svdpp_vertex_program::STEP_DEC;\n    usrFctrStep  *= svdpp_vertex_program::STEP_DEC;\n    itmFctrStep  *= svdpp_vertex_program::STEP_DEC;\n    itmFctr2Step *= svdpp_vertex_program::STEP_DEC;\n\n  }\n}; // end of error aggregator\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 = svdpp_vertex_program::GLOBAL_MEAN + \n    edge.source().data().bias +\n    edge.target().data().bias + \n    edge.source().data().pvec.dot(edge.target().data().pvec);\n  pred = std::min(svdpp_vertex_program::MAXVAL, pred);\n  pred = std::max(svdpp_vertex_program::MINVAL, pred);\n  double rmse = (edge.data().obs - pred) * (edge.data().obs - pred);\n  assert(rmse <= pow(svdpp_vertex_program::MAXVAL-svdpp_vertex_program::MINVAL,2));\n  return rmse;\n} // end of extract_l2_error\n\n\nstruct prediction_saver {\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    return \"\"; //nop\n  }\n  std::string save_edge(const edge_type& edge) const {\n    if (edge.data().role != edge_data::PREDICT)\n      return \"\";\n\n    std::stringstream strm;\n    double pred = svdpp_vertex_program::GLOBAL_MEAN +\n      edge.target().data().bias + edge.source().data().bias + edge.source().data().pvec.dot(edge.target().data().pvec+edge.target().data().weight);\n      pred = std::min(pred, svdpp_vertex_program::MAXVAL);\n      pred = std::max(pred, svdpp_vertex_program::MINVAL);\n    strm << edge.source().id() << '\\t' \n      << -edge.target().id()-SAFE_NEG_OFFSET << '\\t'\n      << pred << '\\n';\n    return strm.str();\n  }\n}; // end of prediction_saver\n\nstruct linear_model_saver_U {\n  typedef graph_type::vertex_type vertex_type;\n  typedef graph_type::edge_type   edge_type;\n  /* save the linear model, using the format:\n     nodeid) factor1 factor2 ... factorNLATENT \\n\n     */\n  std::string save_vertex(const vertex_type& vertex) const {\n    if (vertex.num_out_edges() > 0){\n      std::string ret = boost::lexical_cast<std::string>(vertex.id()) + \" \";\n      for (uint i=0; i< vertex_data::NLATENT; i++)\n        ret += boost::lexical_cast<std::string>(vertex.data().pvec[i]) + \" \";\n      ret += \"\\n\";\n      return ret;\n    }\n    else return \"\";\n  }\n  std::string save_edge(const edge_type& edge) const {\n    return \"\";\n  }\n}; \n\nstruct linear_model_saver_V {\n  typedef graph_type::vertex_type vertex_type;\n  typedef graph_type::edge_type   edge_type;\n  /* save the linear model, using the format:\n     nodeid) factor1 factor2 ... factorNLATENT \\n\n     */\n  std::string save_vertex(const vertex_type& vertex) const {\n    if (vertex.num_out_edges() == 0){\n      std::string ret = boost::lexical_cast<std::string>(-vertex.id()-SAFE_NEG_OFFSET) + \" \";\n      for (uint i=0; i< vertex_data::NLATENT; i++)\n        ret += boost::lexical_cast<std::string>(vertex.data().pvec[i]) + \" \";\n      ret += \"\\n\";\n      return ret;\n    }\n    else return \"\";\n  }\n  std::string save_edge(const edge_type& edge) const {\n    return \"\";\n  }\n}; \n\nstruct linear_model_saver_bias_U {\n  typedef graph_type::vertex_type vertex_type;\n  typedef graph_type::edge_type   edge_type;\n  /* save the linear model, using the format:\n     nodeid) factor1 factor2 ... factorNLATENT \\n\n     */\n  std::string save_vertex(const vertex_type& vertex) const {\n    if (vertex.num_out_edges() > 0){\n      std::string ret = boost::lexical_cast<std::string>(vertex.id()) + \" \";\n      ret += boost::lexical_cast<std::string>(vertex.data().bias) + \"\\n\";\n      return ret;\n    }\n    else return \"\";\n  }\n  std::string save_edge(const edge_type& edge) const {\n    return \"\";\n  }\n}; \nstruct linear_model_saver_bias_V {\n  typedef graph_type::vertex_type vertex_type;\n  typedef graph_type::edge_type   edge_type;\n  /* save the linear model, using the format:\n     nodeid) factor1 factor2 ... factorNLATENT \\n\n     */\n  std::string save_vertex(const vertex_type& vertex) const {\n    if (vertex.num_out_edges() == 0){\n      std::string ret = boost::lexical_cast<std::string>(-vertex.id()-SAFE_NEG_OFFSET) + \" \";\n      ret += boost::lexical_cast<std::string>(vertex.data().bias) + \"\\n\";\n      return ret;\n    }\n    else return \"\";\n  }\n  std::string save_edge(const edge_type& edge) const {\n    return \"\";\n  }\n}; \n\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  if(role == edge_data::TRAIN || role == edge_data::VALIDATE){\n    strm >> obs;\n    if (obs < svdpp_vertex_program::MINVAL || obs > svdpp_vertex_program::MAXVAL)\n      logstream(LOG_FATAL)<<\"Rating values should be between \" << svdpp_vertex_program::MINVAL << \" and \" << svdpp_vertex_program::MAXVAL << \". Got value: \" << obs << \" [ user: \" << source_id << \" to item: \" <<target_id << \" ] \" << std::endl; \n  }\n  target_id = -(graphlab::vertex_id_type(target_id + SAFE_NEG_OFFSET));\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\n\n\n\nsize_t vertex_data::NLATENT = 20;\ndouble svdpp_vertex_program::TOLERANCE = 1e-3;\ndouble svdpp_vertex_program::LAMBDA = 0.001;\ndouble svdpp_vertex_program::GAMMA = 0.001;\nsize_t svdpp_vertex_program::MAX_UPDATES = -1;\ndouble svdpp_vertex_program::MAXVAL = 1e+100;\ndouble svdpp_vertex_program::MINVAL = -1e+100;\ndouble svdpp_vertex_program::STEP_DEC = 0.9;\nbool svdpp_vertex_program::debug = false;\ndouble svdpp_vertex_program::GLOBAL_MEAN = 0;\nsize_t svdpp_vertex_program::NUM_TRAINING_EDGES = 0;\n\n/**\n * \\brief The engine type used by the ALS matrix factorization\n * algorithm.\n *\n * The ALS matrix factorization algorithm currently uses the\n * synchronous engine.  However we plan to add support for alternative\n * engines in the future.\n */\ntypedef graphlab::omni_engine<svdpp_vertex_program> engine_type;\n\n  double calc_global_mean(const graph_type::edge_type & edge){\n    if (edge.data().role == edge_data::TRAIN)\n      return edge.data().obs;\n    else return 0;\n  }\n\n  size_t count_edges(const graph_type::edge_type & edge){\n    if (edge.data().role == edge_data::TRAIN)\n      return 1;\n    else return 0;\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, output_dir;\n  std::string predictions;\n  size_t interval = 0;\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(\"engine\", exec_type, \n      \"The engine type synchronous or asynchronous\");\n  clopts.attach_option(\"max_iter\", svdpp_vertex_program::MAX_UPDATES,\n      \"The maxumum number of udpates allowed for a vertex\");\n  clopts.attach_option(\"lambda\", svdpp_vertex_program::LAMBDA, \n      \"SGD regularization weight\"); \n  clopts.attach_option(\"gamma\", svdpp_vertex_program::GAMMA, \n      \"SGD step size\"); \n  clopts.attach_option(\"debug\", svdpp_vertex_program::debug, \n      \"debug - additional verbose info\"); \n  clopts.attach_option(\"tol\", svdpp_vertex_program::TOLERANCE,\n      \"residual termination threshold\");\n  clopts.attach_option(\"maxval\", svdpp_vertex_program::MAXVAL, \"max allowed value\");\n  clopts.attach_option(\"minval\", svdpp_vertex_program::MINVAL, \"min allowed value\");\n  clopts.attach_option(\"step_dec\", svdpp_vertex_program::STEP_DEC, \"multiplicative step decrement\");\n  clopts.attach_option(\"user_bias_step\", usrBiasStep, \"user_bias_step\");\n  clopts.attach_option(\"user_bias_reg\", usrBiasReg, \"user_bias_reg\");\n  clopts.attach_option(\"item_bias_step\",itmBiasStep, \"item_bias_step\");\n  clopts.attach_option(\"item_bias_reg\", itmBiasReg, \"item_bias_reg\");\n  clopts.attach_option(\"user_factor_step\", usrFctrStep, \"user_factor_step\");\n  clopts.attach_option(\"user_factor_reg\", usrFctrReg, \"user_factor_reg\");\n  clopts.attach_option(\"item_factor_step\", itmFctrStep, \"item_factor_step\");\n  clopts.attach_option(\"item_factor_reg\", itmFctrReg, \"item_factor_reg\");\n  clopts.attach_option(\"item_factor2_step\", itmFctr2Step, \"item_factor2_step\");\n  clopts.attach_option(\"item_factor2_reg\", itmFctr2Reg, \"item_factor2_reg\");\n  clopts.attach_option(\"interval\", interval, \"The time in seconds between error reports\");\n  clopts.attach_option(\"predictions\", predictions,\n      \"The prefix (folder and filename) to save predictions.\");\n  clopts.attach_option(\"output\", output_dir, \"Output results\");\n\n  parse_implicit_command_line(clopts);\n\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  debug = svdpp_vertex_program::debug;\n  //  omp_set_num_threads(clopts.get_ncpus());\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  if (dc.procid() == 0) \n    add_implicit_edges<edge_data>(implicitratingtype, graph, dc);\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\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  engine_type engine(dc, graph, exec_type, clopts);\n\n  // Add error reporting to the engine\n  const bool success = engine.add_edge_aggregator<error_aggregator>\n    (\"error\", error_aggregator::map, error_aggregator::finalize) &&\n    engine.aggregate_periodic(\"error\", interval);\n  ASSERT_TRUE(success);\n\n\n  svdpp_vertex_program::GLOBAL_MEAN = graph.map_reduce_edges<double>(calc_global_mean);\n  svdpp_vertex_program::NUM_TRAINING_EDGES = graph.map_reduce_edges<size_t>(count_edges);\n  svdpp_vertex_program::GLOBAL_MEAN /= svdpp_vertex_program::NUM_TRAINING_EDGES;\n  dc.cout() << \"Global mean is: \" <<svdpp_vertex_program::GLOBAL_MEAN << std::endl;\n\n  // Signal all vertices on the vertices on the left (libersgd) \n  engine.map_reduce_vertices<graphlab::empty>(svdpp_vertex_program::signal_left);\n\n\n  // Run the PageRank ---------------------------------------------------------\n  dc.cout() << \"Running Bias-SGD\" << std::endl;\n  dc.cout() << \"(C) Code by Danny Bickson, CMU \" << std::endl;\n  dc.cout() << \"Please send bug reports to danny.bickson@gmail.com\" << std::endl;\n  dc.cout() << \"Time   Training    Validation\" <<std::endl;\n  dc.cout() << \"       RMSE        RMSE \" <<std::endl;\n  timer.start();\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  // Compute the final training error -----------------------------------------\n  dc.cout() << \"Final error: \" << std::endl;\n  engine.aggregate_now(\"error\");\n\n  // Make predictions ---------------------------------------------------------\n  if(!predictions.empty()) {\n    std::cout << \"Saving predictions\" << std::endl;\n    const bool gzip_output = false;\n    const bool save_vertices = false;\n    const bool save_edges = true;\n    const size_t threads_per_machine = 1;\n    graph.save(predictions, prediction_saver(),\n        gzip_output, save_vertices, \n        save_edges, threads_per_machine);\n    //save the linear model\n    graph.save(predictions + \".U\", linear_model_saver_U(),\n        gzip_output, save_edges, save_vertices, threads_per_machine);\n    graph.save(predictions + \".V\", linear_model_saver_V(),\n        gzip_output, save_edges, save_vertices, threads_per_machine);\n    graph.save(predictions + \".bias.U\", linear_model_saver_bias_U(),\n        gzip_output, save_edges, save_vertices, threads_per_machine);\n    graph.save(predictions + \".bias.V\", linear_model_saver_bias_V(),\n        gzip_output, save_edges, save_vertices, threads_per_machine);\n\n  }\n\n\n\n  graphlab::mpi_tools::finalize();\n  return EXIT_SUCCESS;\n} // end of main\n\n\n\n", "meta": {"hexsha": "a350fe3e58c2c9c92b0188ae99e3c7d7ec34f2d9", "size": 29459, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "toolkits/collaborative_filtering/svdpp.cpp", "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": 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/collaborative_filtering/svdpp.cpp", "max_issues_repo_name": "kesinger/graphlab", "max_issues_repo_head_hexsha": "5acb39d816f33e59433e88a9d3621eb4cf7cb05e", "max_issues_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "toolkits/collaborative_filtering/svdpp.cpp", "max_forks_repo_name": "kesinger/graphlab", "max_forks_repo_head_hexsha": "5acb39d816f33e59433e88a9d3621eb4cf7cb05e", "max_forks_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-27T12:40:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-27T12:40:52.000Z", "avg_line_length": 35.9694749695, "max_line_length": 243, "alphanum_fraction": 0.6444210598, "num_tokens": 7458, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.49170068907867404}}
{"text": "#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/depth_first_search.hpp>\n#include <iostream>\nusing namespace std;\nusing namespace boost;\ntypedef property<edge_weight_t, int> EdgeWeightProperty;\ntypedef boost::adjacency_list < listS, vecS, undirectedS, no_property, EdgeWeightProperty> mygraph;\n\nclass custom_dfs_visitor : public boost::default_dfs_visitor\n{\n    public:\n    template < typename Vertex, typename Graph >\n    void discover_vertex(Vertex u, const Graph & g)\n    const { cout << \"At \" << u << endl; }\n    template < typename Edge, typename Graph >\n    void examine_edge(Edge e, const Graph& g)\n    const { cout << \"Examining edges \" << e << endl;}\n};\n\nint main()\n{\n    mygraph g;\n    add_edge (0, 1, 8, g);\n    add_edge (0, 3, 18, g);\n    add_edge (1, 2, 20, g);\n    add_edge (2, 3, 2, g);\n    add_edge (3, 1, 1, g);\n    add_edge (1, 3, 7, g);\n    custom_dfs_visitor vis;\n    depth_first_search(g, visitor(vis));\n}", "meta": {"hexsha": "d9f966b9c111fd0b68986ca741a9d15f1cd154bc", "size": 941, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "7DFS_using_BGL.cpp", "max_stars_repo_name": "mohsenuss91/BGL_workshop", "max_stars_repo_head_hexsha": "03d2bea291d4c6d67e7ddcd562694a0b7ecc5130", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-02-12T18:40:32.000Z", "max_stars_repo_stars_event_max_datetime": "2015-02-12T18:40:32.000Z", "max_issues_repo_path": "7DFS_using_BGL.cpp", "max_issues_repo_name": "mohsenuss91/IBM_BGL", "max_issues_repo_head_hexsha": "03d2bea291d4c6d67e7ddcd562694a0b7ecc5130", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "7DFS_using_BGL.cpp", "max_forks_repo_name": "mohsenuss91/IBM_BGL", "max_forks_repo_head_hexsha": "03d2bea291d4c6d67e7ddcd562694a0b7ecc5130", "max_forks_repo_licenses": ["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.3548387097, "max_line_length": 99, "alphanum_fraction": 0.6726886291, "num_tokens": 273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384735, "lm_q2_score": 0.6261241842048092, "lm_q1q2_score": 0.49170068826528385}}
{"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <iostream>\n#include <fstream>\n#include <iomanip>\n#include <limits>\n#include <vector>\n#include <algorithm>\n#include <string>\n#include <sstream>\n#include <chrono>\n\n#include <boost/filesystem.hpp>\n#include <boost/circular_buffer.hpp>\n\n#include <ScrimpSequVec.hpp>\n#include <logging.hpp>\n#include <papiwrapper.hpp>\n\nusing namespace matrix_profile;\n\nstatic FactoryRegistration<ScrimpSequVec> s_sequRegistr(\"scrimp_sequ_vec\");\nstatic const int notification_interval_iter = 10000;\n\nPerfCounters cumsum_perf(\"cumulative_sum\");\nPerfCounters eval_perf(\"vectorized evaluation\");\n\ntsa_dtype ScrimpSequVec::init_diagonal(const aligned_tsdtype_vec& ASigmaInv, aligned_tsdtype_vec& cumDotproduct, aligned_tsdtype_vec& profile, const int diag, const aligned_tsdtype_vec& A, aligned_int_vec& profileIndex, const int windowSize, const aligned_tsdtype_vec& AMeanScaledSigSqrM)\n{\n\ttsa_dtype corr_score=0;\n\ttsa_dtype lastz=0;\n\n\t//evaluate the fist distance value in the current diagonal\n\tfor (int k = 0; k < windowSize; k++)\n\t{\n\t\tcumDotproduct[k+diag]=lastz;\n\t\tlastz += A[k+diag]*A[k];\n\t}\n\t//j is the column index, i is the row index of the current distance value in the distance matrix\n\n\treturn lastz;\n}\n\nvoid ScrimpSequVec::eval_diagonal(idx_dtype* const profileIndex, const tsa_dtype* const A, tsa_dtype& lastz, const idx_dtype windowSize, tsa_dtype* const cumDotproduct, tsa_dtype* const ASigmaInv, const tsa_dtype* const AMeanScaledSigSqrM, const idx_dtype diag, tsa_dtype* const profile, const idx_dtype profileLength)\n{\n\t{\n\t\tScopedPerfAccumulator monitor(cumsum_perf);\n\t\ttsa_dtype cumProd = lastz; //TODO: rename lastz. The idea of this line is toavoid unnecessary writes to the input reference....\n\t\tfor (idx_dtype j=diag; j<profileLength; j++)\n\t\t{\n\t\t\tcumDotproduct[j+windowSize]=cumProd;\n\t\t\tcumProd += A[j+windowSize]*A[j+windowSize-diag];\n\t\t}\n\t}\n\t{\n\t\tScopedPerfAccumulator monitor(eval_perf);\n        #pragma omp simd aligned(profile, profileIndex, ASigmaInv, AMeanScaledSigSqrM, cumDotproduct : alignment)\n\t\tfor (idx_dtype j=diag; j<profileLength; j++)\n\t\t{\n\t\t\tidx_dtype i=j-diag;\n\t\t\ttsa_dtype corrScore = ( (cumDotproduct[j+windowSize] - cumDotproduct [j]) * (ASigmaInv[j] * ASigmaInv[i]) - AMeanScaledSigSqrM[j] * AMeanScaledSigSqrM[i]) ;\n\n\t\t\tbool update_j = (corrScore > profile[j]);\n\t\t\tprofile[j] = update_j?corrScore:profile[j];\n\t\t\tprofileIndex [j] = update_j?i:profileIndex [j];\n\n\t\t\tbool update_i = (corrScore > profile[i]);\n\t\t\tprofile[i] = update_i?corrScore:profile[i];\n\t\t\tprofileIndex [i] = update_i?j:profileIndex[i];\n\t\t}\n\t}\n}\n\nvoid ScrimpSequVec::compute_matrix_profile(const Scrimppp_params& params)\n{\n\tstd::chrono::high_resolution_clock::time_point tstart, tend;\n\tstd::chrono::duration<double> time_elapsed;\n\taligned_tsdtype_vec A = fetch_time_series<aligned_tsdtype_vec::allocator_type>(params); //load the time series data\n\taligned_tsdtype_vec AMeanScaledSqrtM(A.size());\n\taligned_tsdtype_vec ASigmaInv(A.size());\n\tint windowSize = params.query_window_len;\n\tint exclusionZone = windowSize / 4;\n\tint timeSeriesLength = A.size();\n\tint ProfileLength = timeSeriesLength - windowSize + 1;\n\t//Initialize Matrix Profile and Matrix Profile Index\n\taligned_tsdtype_vec profile(ProfileLength, 0.0);\n\taligned_int_vec profileIndex(ProfileLength, 0);\n\taligned_tsdtype_vec dotproduct(timeSeriesLength); // stores products between two Timeseries values with a distinct offset\n\taligned_int_vec idx; // store indices of the diagonals, defining their evaluation order\n\tidx.reserve(ProfileLength-exclusionZone-1);\n\n\t//several monitors for performance measurement\n\tPerfCounters setup_perf(\"setup performance\");\n\tPerfCounters init_diag_perf(\"diagonal initialization\");\n\t//PerfCounters eval_diag_perf(\"diagonal evaluation\");\n\n\t//validation of parameters\n\tif (timeSeriesLength < windowSize) {\n\t\tthrow std::invalid_argument(\"ERROR: Time series is shorter than the window length, can not proceed\");\n\t}\n\n\tEXEC_INFO( \"Sequential SCRIMP matrix profile computation with profile length \" << ProfileLength << \" and window size \" << windowSize);\n\n\n\t{\n\t\tScopedPerfAccumulator monitor(setup_perf);\n\t\t//precompute the mean and standard deviations of the sliding windows along the time series\n\t\tprecompute_window_statistics(windowSize, A, ProfileLength, AMeanScaledSqrtM, ASigmaInv);\n\n\t\t//start time measurment\n\t\ttstart = std::chrono::high_resolution_clock::now();\n\n\t\t/******************** SCRIMP ********************/\n\t\t//Random shuffle the computation order of the diagonals of the distance matrix\n\t\tfor (int i = exclusionZone+1; i < ProfileLength; i++) {\n\t\t\tidx.push_back(i);\n\t\t}\n\t\tstd::random_shuffle(idx.begin(), idx.end());\n\t}\n\n\t//iteratively evaluate the diagonals of the distance matrix\n\tfor (int ri = 0; ri < idx.size(); ri++)\n\t    {\n\t\t//select a random diagonal\n\t\tint diag = idx[ri];\n\t\ttsa_dtype lastz=0; //the dot product of a subsequence\n\n\n\t\t// compute the first distance value in the diagonal (i.e. compute the distance between the first windows)\n\t\t{\n\t\t\tScopedPerfAccumulator monitor(init_diag_perf);\n\t\t\tlastz = init_diagonal(ASigmaInv, dotproduct, profile, diag, A, profileIndex, windowSize, AMeanScaledSqrtM);\n\t\t}\n\n\t\t//evaluate the second to the last distance values along the diagonal in the matrix and update the matrix profile/matrix profile index.\n\t\t{\n\t\t\t//ScopedPerfAccumulator monitor(eval_diag_perf);\n\t\t\t// eval_diagonal(profileIndex, A, lastz, windowSize, dotproduct, ASigmaInv, AMeanScaledSqrtM, diag, profile);\n\t\t\teval_diagonal(profileIndex.data(), A.data(), lastz, windowSize, dotproduct.data(), ASigmaInv.data(), AMeanScaledSqrtM.data(), diag, profile.data(), AMeanScaledSqrtM.size());\n\t\t}\n\n\t\t//Show time per 10000 iterations\n\t\tif ((ri+1) % notification_interval_iter == 0)\n\t\t{\n\t\t\ttend = std::chrono::high_resolution_clock::now();\n\t\t\ttime_elapsed = tend - tstart;\n\t\t\tEXEC_INFO ( \"finished \" << ri+1 << \" iterations after \" << std::setprecision(std::numeric_limits<tsa_dtype>::digits10 + 2) << time_elapsed.count() << \" seconds.\");\n\t\t}\n\t}\n\n\t// apply a correction of the distance values, as we dropped a factor of 2 to avoid unnecessary computations\n\ttsa_dtype twice_m = 2.0*static_cast<tsa_dtype>(windowSize);\n\tfor (auto iter=profile.begin(); iter<profile.end(); ++iter) {\n\t\t(*iter) = twice_m - 2.0 * (*iter);\n\t}\n\n\t// end timer\n\t// tend = time(0);\n\ttend = std::chrono::high_resolution_clock::now();\n\ttime_elapsed = tend - tstart;\n\n\tPERF_LOG ( \"total computation time: \" << std::setprecision(std::numeric_limits<tsa_dtype>::digits10 + 2) << time_elapsed.count() << \" seconds.\" );\n\tconst double triang_len = ProfileLength-exclusionZone;\n\tPERF_LOG ( \"throughput computations: \" << triang_len * triang_len / time_elapsed.count() << \" matrix entries/second\");\n\n\t//store the result\n\tstore_matrix_profile(profile, profileIndex, params);\n\n\tsetup_perf.log_perf();\n\tinit_diag_perf.log_perf();\n\tcumsum_perf.log_perf();\n\teval_perf.log_perf();\n\t//eval_diag_perf.log_perf();\n#ifdef PROFILING\n\tPERF_LOG ( \"number of matrix profile updates: \" << _profileUpdateCounter);\n#endif\n\n}\n", "meta": {"hexsha": "ecee9cd891bc4ae0355576bfd20383a4a205be71", "size": 7023, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "scrimppp/src/ScrimpSequVec.cpp", "max_stars_repo_name": "franzbischoff/ThesisCode", "max_stars_repo_head_hexsha": "b9526fb801893c8d54a937f3d959833148004aa2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-10-06T22:05:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-23T03:14:16.000Z", "max_issues_repo_path": "scrimppp/src/ScrimpSequVec.cpp", "max_issues_repo_name": "franzbischoff/ThesisCode", "max_issues_repo_head_hexsha": "b9526fb801893c8d54a937f3d959833148004aa2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scrimppp/src/ScrimpSequVec.cpp", "max_forks_repo_name": "franzbischoff/ThesisCode", "max_forks_repo_head_hexsha": "b9526fb801893c8d54a937f3d959833148004aa2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-10-20T22:41:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-19T09:15:48.000Z", "avg_line_length": 39.0166666667, "max_line_length": 318, "alphanum_fraction": 0.7449807774, "num_tokens": 1881, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435083355187, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.4916880939670015}}
{"text": "// This file is distributed under the MIT license.\n// See the LICENSE file for details.\n\n#include <cstddef>\n#include <sstream>\n\n#include <boost/archive/text_iarchive.hpp>\n#include <boost/archive/text_oarchive.hpp>\n\n#include <visionaray/math/serialization.h>\n\n#include <gtest/gtest.h>\n\nusing namespace visionaray;\n\n\nTEST(Serialization, AABB)\n{\n    // use as input\n    basic_aabb<int>    dsti;\n    basic_aabb<float>  dstf;\n    basic_aabb<double> dstd;\n\n    // test some invalid boxes\n    basic_aabb<int>    srci;\n    basic_aabb<float>  srcf;\n    basic_aabb<double> srcd;\n\n    srci.invalidate();\n    srcf.invalidate();\n    srcd.invalidate();\n\n    std::stringstream sstream;\n    boost::archive::text_oarchive oa(sstream);\n\n    oa << srci;\n    oa << srcf;\n    oa << srcd;\n\n    boost::archive::text_iarchive ia(sstream);\n\n    ia >> dsti;\n    ia >> dstf;\n    ia >> dstd;\n\n    ASSERT_EQ(dsti.min, srci.min);\n    ASSERT_EQ(dsti.max, srci.max);\n    EXPECT_FLOAT_EQ(dstf.min.x, srcf.min.x);\n    EXPECT_FLOAT_EQ(dstf.min.y, srcf.min.y);\n    EXPECT_FLOAT_EQ(dstf.min.z, srcf.min.z);\n    EXPECT_FLOAT_EQ(dstf.max.x, srcf.max.x);\n    EXPECT_FLOAT_EQ(dstf.max.y, srcf.max.y);\n    EXPECT_FLOAT_EQ(dstf.max.z, srcf.max.z);\n    EXPECT_DOUBLE_EQ(dstd.min.x, srcd.min.x);\n    EXPECT_DOUBLE_EQ(dstd.min.y, srcd.min.y);\n    EXPECT_DOUBLE_EQ(dstd.min.z, srcd.min.z);\n    EXPECT_DOUBLE_EQ(dstd.max.x, srcd.max.x);\n    EXPECT_DOUBLE_EQ(dstd.max.y, srcd.max.y);\n    EXPECT_DOUBLE_EQ(dstd.max.z, srcd.max.z);\n}\n\nTEST(Serialization, Matrix)\n{\n    matrix<3, 3, float>  dst3f;\n    matrix<3, 3, double> dst3d;\n    matrix<4, 4, float>  dst4f;\n    matrix<4, 4, double> dst4d;\n\n    matrix<3, 3, float>  src3f(\n            0.0f, 1.0f, 2.0f,\n            3.0f, 4.0f, 5.0f,\n            6.0f, 7.0f, 8.0f\n            );\n    matrix<3, 3, double> src3d(\n            0.0, 1.0, 2.0,\n            3.0, 4.0, 5.0,\n            6.0, 7.0, 8.0\n            );\n    matrix<4, 4, float> src4f(\n             0.0f,  1.0f,  2.0f,  3.0f,\n             4.0f,  5.0f,  6.0f,  7.0f,\n             8.0f,  9.0f, 10.0f, 11.0f,\n            12.0f, 13.0f, 14.0f, 15.0f\n            );\n    matrix<4, 4, double> src4d(\n             0.0,  1.0,  2.0,  3.0,\n             4.0,  5.0,  6.0,  7.0,\n             8.0,  9.0, 10.0, 11.0,\n            12.0, 13.0, 14.0, 15.0\n            );\n\n    std::stringstream sstream;\n    boost::archive::text_oarchive oa(sstream);\n\n    oa << src3f;\n    oa << src3d;\n    oa << src4f;\n    oa << src4d;\n\n    boost::archive::text_iarchive ia(sstream);\n\n    ia >> dst3f;\n    ia >> dst3d;\n    ia >> dst4f;\n    ia >> dst4d;\n\n    for (size_t i = 0; i < 4; ++i)\n    {\n        for (size_t j = 0; j < 4; ++j)\n        {\n            if (i < 3 && j < 3)\n            {\n                EXPECT_FLOAT_EQ(dst3f(i, j), src3f(i, j));\n                EXPECT_DOUBLE_EQ(dst3d(i, j), src3d(i, j));\n            }\n            EXPECT_FLOAT_EQ(dst4f(i, j), src4f(i, j));\n            EXPECT_DOUBLE_EQ(dst4d(i, j), src4d(i, j));\n        }\n    }\n}\n\nTEST(Serialization, RectangleXYWH)\n{\n    rectangle<xywh_layout<int>, int>       dsti;\n    rectangle<xywh_layout<float>, float>   dstf;\n    rectangle<xywh_layout<double>, double> dstd;\n\n    rectangle<xywh_layout<int>, int>       srci(0, 0, 1024, 768);\n    rectangle<xywh_layout<float>, float>   srcf(-3.14f, -314.15f, 6.28f, 628.31f);\n    rectangle<xywh_layout<double>, double> srcd(700.0, 700.0, 0.0, 0.0);\n\n    std::stringstream sstream;\n    boost::archive::text_oarchive oa(sstream);\n\n    oa << srci;\n    oa << srcf;\n    oa << srcd;\n\n    boost::archive::text_iarchive ia(sstream);\n\n    ia >> dsti;\n    ia >> dstf;\n    ia >> dstd;\n\n    ASSERT_EQ(dsti.x, srci.x);\n    ASSERT_EQ(dsti.y, srci.y);\n    ASSERT_EQ(dsti.w, srci.w);\n    ASSERT_EQ(dsti.h, srci.h);\n\n    EXPECT_FLOAT_EQ(dstf.x, srcf.x);\n    EXPECT_FLOAT_EQ(dstf.y, srcf.y);\n    EXPECT_FLOAT_EQ(dstf.w, srcf.w);\n    EXPECT_FLOAT_EQ(dstf.h, srcf.h);\n\n    EXPECT_DOUBLE_EQ(dstd.x, srcd.x);\n    EXPECT_DOUBLE_EQ(dstd.y, srcd.y);\n    EXPECT_DOUBLE_EQ(dstd.w, srcd.w);\n    EXPECT_DOUBLE_EQ(dstd.h, srcd.h);\n}\n\nTEST(Serialization, Vector)\n{\n    float f1[] = { 3.14f };\n    float f2[] = { 3.14f, 3.15f };\n    float f3[] = { 3.14f, 3.15f, 3.16f };\n    float f4[] = { 3.14f, 3.15f, 3.16f, 3.17f };\n    float f5[] = { 3.14f, 3.15f, 3.16f, 3.17f, 3.18f };\n    float f6[] = { 3.14f, 3.15f, 3.16f, 3.17f, 3.18f, 3.19f };\n    float f7[] = { 3.14f, 3.15f, 3.16f, 3.17f, 3.18f, 3.19f, 3.20f };\n\n    vector<1, float> src1f(f1);\n    vector<2, float> src2f(f2);\n    vector<3, float> src3f(f3);\n    vector<4, float> src4f(f4);\n    vector<5, float> src5f(f5);\n    vector<6, float> src6f(f6);\n    vector<7, float> src7f(f7);\n\n    vector<1, float> dst1f;\n    vector<2, float> dst2f;\n    vector<3, float> dst3f;\n    vector<4, float> dst4f;\n    vector<5, float> dst5f;\n    vector<6, float> dst6f;\n    vector<7, float> dst7f;\n\n    std::stringstream sstream;\n    boost::archive::text_oarchive oa(sstream);\n\n    oa << src1f;\n    oa << src2f;\n    oa << src3f;\n    oa << src4f;\n    oa << src5f;\n    oa << src6f;\n    oa << src7f;\n\n    boost::archive::text_iarchive ia(sstream);\n\n    ia >> dst1f;\n    ia >> dst2f;\n    ia >> dst3f;\n    ia >> dst4f;\n    ia >> dst5f;\n    ia >> dst6f;\n    ia >> dst7f;\n\n    EXPECT_FLOAT_EQ(dst1f[0], src1f[0]);\n\n    EXPECT_FLOAT_EQ(dst2f[0], src2f[0]);\n    EXPECT_FLOAT_EQ(dst2f[1], src2f[1]);\n\n    EXPECT_FLOAT_EQ(dst3f[0], src3f[0]);\n    EXPECT_FLOAT_EQ(dst3f[1], src3f[1]);\n    EXPECT_FLOAT_EQ(dst3f[2], src3f[2]);\n\n    EXPECT_FLOAT_EQ(dst4f[0], src4f[0]);\n    EXPECT_FLOAT_EQ(dst4f[1], src4f[1]);\n    EXPECT_FLOAT_EQ(dst4f[2], src4f[2]);\n    EXPECT_FLOAT_EQ(dst4f[3], src4f[3]);\n\n    EXPECT_FLOAT_EQ(dst5f[0], src5f[0]);\n    EXPECT_FLOAT_EQ(dst5f[1], src5f[1]);\n    EXPECT_FLOAT_EQ(dst5f[2], src5f[2]);\n    EXPECT_FLOAT_EQ(dst5f[3], src5f[3]);\n    EXPECT_FLOAT_EQ(dst5f[4], src5f[4]);\n\n    EXPECT_FLOAT_EQ(dst6f[0], src6f[0]);\n    EXPECT_FLOAT_EQ(dst6f[1], src6f[1]);\n    EXPECT_FLOAT_EQ(dst6f[2], src6f[2]);\n    EXPECT_FLOAT_EQ(dst6f[3], src6f[3]);\n    EXPECT_FLOAT_EQ(dst6f[4], src6f[4]);\n    EXPECT_FLOAT_EQ(dst6f[5], src6f[5]);\n\n    EXPECT_FLOAT_EQ(dst7f[0], src7f[0]);\n    EXPECT_FLOAT_EQ(dst7f[1], src7f[1]);\n    EXPECT_FLOAT_EQ(dst7f[2], src7f[2]);\n    EXPECT_FLOAT_EQ(dst7f[3], src7f[3]);\n    EXPECT_FLOAT_EQ(dst7f[4], src7f[4]);\n    EXPECT_FLOAT_EQ(dst7f[5], src7f[5]);\n    EXPECT_FLOAT_EQ(dst7f[6], src7f[6]);\n}\n", "meta": {"hexsha": "5ed519fe6616edd0129dc0203ac96053f5a75109", "size": 6347, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unittests/math/serialization.cpp", "max_stars_repo_name": "sylvainbouxin/visionaray", "max_stars_repo_head_hexsha": "39aba3605ca92b6b086852d3524b762ac259ed43", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-10-23T19:58:11.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-23T19:58:11.000Z", "max_issues_repo_path": "test/unittests/math/serialization.cpp", "max_issues_repo_name": "stoeckley/visionaray", "max_issues_repo_head_hexsha": "226d6cdf870f658d0fd0d1e1e292a8324d65ff4d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/unittests/math/serialization.cpp", "max_forks_repo_name": "stoeckley/visionaray", "max_forks_repo_head_hexsha": "226d6cdf870f658d0fd0d1e1e292a8324d65ff4d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-09-11T20:21:23.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-11T20:21:23.000Z", "avg_line_length": 26.1193415638, "max_line_length": 82, "alphanum_fraction": 0.5764928313, "num_tokens": 2395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435083355187, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.4916880833295018}}
{"text": "//==================================================================================================\n/**\n  EVE - Expressive Vector Engine\n  Copyright : EVE Contributors & Maintainers\n  SPDX-License-Identifier: MIT\n**/\n//==================================================================================================\n#include \"test.hpp\"\n#include <eve/function/cyl_bessel_k1.hpp>\n#include <eve/function/diff/cyl_bessel_k1.hpp>\n#include <eve/function/prev.hpp>\n#include <eve/constant/inf.hpp>\n#include <eve/constant/minf.hpp>\n#include <eve/constant/nan.hpp>\n#include <eve/platform.hpp>\n#include <cmath>\n#include <boost/math/special_functions/bessel.hpp>\n#include <boost/math/special_functions/bessel_prime.hpp>\n\nEVE_TEST_TYPES( \"Check return types of cyl_bessel_k1\"\n            , eve::test::simd::ieee_reals\n            )\n<typename T>(eve::as<T>)\n{\n  using v_t = eve::element_type_t<T>;\n  TTS_EXPR_IS(eve::cyl_bessel_k1(T(0)), T);\n  TTS_EXPR_IS(eve::cyl_bessel_k1(v_t(0)), v_t);\n};\n\n EVE_TEST( \"Check behavior of cyl_bessel_k1 on wide\"\n        , eve::test::simd::ieee_reals\n         , eve::test::generate( eve::test::randoms(0.0, 0.5)\n                              , eve::test::randoms(0.5, 1.5)\n                              , eve::test::randoms(1.5, 500.0))\n         )\n   <typename T>(T const& a0, T const& a1, T const& a2)\n{\n  using v_t = eve::element_type_t<T>;\n\n  auto eve__cyl_bessel_k1 =  [](auto x) { return eve::cyl_bessel_k1(x); };\n#if defined(__cpp_lib_math_special_functions)\n  auto std__cyl_bessel_k1 =  [](auto x)->v_t { return std::cyl_bessel_k(v_t(1), x); };\n#else\n  auto std__cyl_bessel_k1 =  [](auto x)->v_t { return boost::math::cyl_bessel_k(v_t(1), x); };\n#endif\n  if constexpr( eve::platform::supports_invalids )\n  {\n    TTS_ULP_EQUAL(eve__cyl_bessel_k1(eve::inf(eve::as<v_t>())), eve::zero(eve::as<v_t>()), 0);\n    TTS_ULP_EQUAL(eve__cyl_bessel_k1(eve::nan(eve::as<v_t>())), eve::nan(eve::as<v_t>()), 0);\n    TTS_ULP_EQUAL(eve__cyl_bessel_k1(eve::zero(eve::as<v_t>())), eve::inf(eve::as<v_t>()), 0);\n    TTS_ULP_EQUAL(eve__cyl_bessel_k1(eve::inf(eve::as<T>())),  eve::zero(eve::as< T>()), 0);\n    TTS_ULP_EQUAL(eve__cyl_bessel_k1(eve::nan(eve::as< T>())), eve::nan(eve::as< T>()), 0);\n    TTS_ULP_EQUAL(eve__cyl_bessel_k1(eve::zero(eve::as<T>())),  eve::inf(eve::as< T>()), 0);\n  }\n  TTS_IEEE_EQUAL(eve__cyl_bessel_k1(v_t(-1)), eve::nan(eve::as<v_t>()));\n  TTS_ULP_EQUAL(eve__cyl_bessel_k1(v_t(500)), std__cyl_bessel_k1(v_t(500)), 6.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_k1(v_t(10)), std__cyl_bessel_k1(v_t(10))  , 6.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_k1(v_t(5)),  std__cyl_bessel_k1(v_t(5))   , 6.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_k1(v_t(2)),  std__cyl_bessel_k1(v_t(2))   , 6.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_k1(v_t(1.5)),std__cyl_bessel_k1(v_t(1.5)) , 6.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_k1(v_t(0.5)),std__cyl_bessel_k1(v_t(0.5)) , 6.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_k1(v_t(0.05)),std__cyl_bessel_k1(v_t(0.05)) , 6.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_k1(v_t(1)),  std__cyl_bessel_k1(v_t(1))   , 6.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_k1(v_t(0)),  eve::inf(eve::as<v_t>()), 0.0);\n\n  TTS_IEEE_EQUAL(eve__cyl_bessel_k1(T(-1)), eve::nan(eve::as<T>()));\n  TTS_ULP_EQUAL(eve__cyl_bessel_k1( T(500)),  T(std__cyl_bessel_k1(v_t(500)) ), 6.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_k1( T(10)) ,  T(std__cyl_bessel_k1( v_t(10)) ), 6.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_k1( T(5))  ,  T(std__cyl_bessel_k1( v_t(5))  ), 6.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_k1( T(2))  ,  T(std__cyl_bessel_k1( v_t(2))  ), 6.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_k1( T(1.5)),  T(std__cyl_bessel_k1( v_t(1.5))), 6.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_k1( T(0.5)),  T(std__cyl_bessel_k1( v_t(0.5))), 6.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_k1( T(1))  ,  T(std__cyl_bessel_k1( v_t(1))  ), 6.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_k1( T(0))  , eve::inf(eve::as<T>()), 0.0);\n\n\n  TTS_ULP_EQUAL(eve__cyl_bessel_k1(a0), map(std__cyl_bessel_k1, a0), 10.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_k1(a1), map(std__cyl_bessel_k1, a1), 10.0);\n  TTS_RELATIVE_EQUAL(eve__cyl_bessel_k1(a2), map(std__cyl_bessel_k1, a2), 0.001);\n};\n\nEVE_TEST( \"Check behavior of cyl_bessel_k1 on wide with negative non integral order\"\n        , eve::test::simd::ieee_reals\n        , eve::test::generate(eve::test::randoms(0.0, 60.0))\n        )\n  <typename T>(T a0 )\n{\n  using v_t = eve::element_type_t<T>;\n  auto eve__diff_bessel_k1 =  [](auto x) { return eve::diff(eve::cyl_bessel_k1)(x); };\n  auto std__diff_bessel_k1 =  [](auto x)->v_t { return boost::math::cyl_bessel_k_prime(1, x); };\n  TTS_RELATIVE_EQUAL(eve__diff_bessel_k1(a0),   map(std__diff_bessel_k1, a0)   , 1.0e-3);\n\n};\n", "meta": {"hexsha": "f26d596a22a20dc6bde4ef01d448eb7416202527", "size": 4633, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/module/bessel/cyl_bessel_k1.cpp", "max_stars_repo_name": "the-moisrex/eve", "max_stars_repo_head_hexsha": "80b52663eefee11460abb0aedf4158a5067cf7dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 340.0, "max_stars_repo_stars_event_min_datetime": "2020-09-16T21:12:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T15:40:33.000Z", "max_issues_repo_path": "test/unit/module/bessel/cyl_bessel_k1.cpp", "max_issues_repo_name": "the-moisrex/eve", "max_issues_repo_head_hexsha": "80b52663eefee11460abb0aedf4158a5067cf7dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 383.0, "max_issues_repo_issues_event_min_datetime": "2020-09-17T06:56:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T15:58:53.000Z", "max_forks_repo_path": "test/unit/module/bessel/cyl_bessel_k1.cpp", "max_forks_repo_name": "the-moisrex/eve", "max_forks_repo_head_hexsha": "80b52663eefee11460abb0aedf4158a5067cf7dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 28.0, "max_forks_repo_forks_event_min_datetime": "2021-02-27T23:11:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T12:31:29.000Z", "avg_line_length": 49.2872340426, "max_line_length": 100, "alphanum_fraction": 0.6468810706, "num_tokens": 1798, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6370308013713525, "lm_q1q2_score": 0.4916880819616935}}
{"text": "/*\n * dijkstra.cpp\n *\n * \t\\brief     My dijkstra implementation for the fifth exercise\n *  \\details   This class computes the longest shortest path for starting point 1.\n *  \\author    Julia Baumbach\n *  \\date      17.06.2017\n */\n\n#include \"dijkstra.h\"\n#include <climits>\n#include <iostream>\n#include <boost/heap/fibonacci_heap.hpp>\n#include <exception>\n\nusing VisitedMap = std::vector<bool>;\n\n/**\n * \\struct compare_function\n * \\brief defines how 2 dijkstra pairs should be compared at fibonacci-heap\n * \\param edge1 first edge to compare\n * \\param edge2 second edge to compare\n * \\return true if the weight of edge2 is smaller than edge1's weight\n */\nstruct compare_function{\n\tbool operator()(const DijkstraPair edge1, const DijkstraPair edge2) const{\n\t\treturn edge1.second > edge2.second;\n\t}\n};\n\n/**\n * \\fn the constructor\n * \\brief initialize a new dijkstra instance while sorting the given edges\n * \\param weights Vector of the weights for the given graph\n * \\param edges Vector of the edges for the given graph\n * \\return the new dijkstra instance\n */\ndijkstra::dijkstra(WeightMap weights, Edges edges, unsigned int numberOfVertices):\n\tnumberOfVertices(numberOfVertices) {\n\t//sort the edges in a more efficient data structure\n\tsortedEdges.resize(numberOfVertices);\n\tfor (unsigned int i = 0; i < edges.size(); i++){\n\t\tsortedEdges.at(edges.at(i).first).push_back(std::make_pair(edges.at(i).second, weights.at(i)));\n\t\tsortedEdges.at(edges.at(i).second).push_back(std::make_pair(edges.at(i).first, weights.at(i)));\n\t}\n}\n\n/**\n * \\fn vector<int> dijkstra::computeShortestPath\n * \\brief computes all shortest paths from given start vertex for the initialized dijkstra instance\n * \\param unsigned int numberOfVertices Number of Vertices for the graph\n * \\return vector of the weights for all shortest paths\n */\nWeightMap dijkstra::computeShortestPath(int startNode){\n\tif(startNode > numberOfVertices){\n\t\tstd::cerr << \"Index of StartVertex must be less or equal to number of vertices\" << std::endl;\n\t\tthrow std::exception();\n\t}\n\tWeightMap weightsToVertices(numberOfVertices); //should be returned\n\tstd::vector<int> predecessorMap(numberOfVertices);\n\tVisitedMap alreadyVisited(numberOfVertices);\n\n\tfor (unsigned int i = 0; i < numberOfVertices; i++) {\n\t\tweightsToVertices[i] = INT_MAX;\n\t\tpredecessorMap[i] = -1;\n\t}\n\t//Start in point startNode\n\tweightsToVertices[startNode] = 0;\n\tpredecessorMap[startNode] = startNode;\n\tint currentVertex = startNode;\n\tint currentDist = 0;\n\n\tboost::heap::fibonacci_heap<DijkstraPair, boost::heap::compare<compare_function>> heap;\n\t//Put the start vertex in the verticesToVisit list\n\theap.push(std::make_pair(startNode, 0));\n\n\twhile(!heap.empty()){\n\t\tif (!alreadyVisited.at(heap.top().first)){\n\t\t\tcurrentVertex = heap.top().first;\n\t\t\tcurrentDist = heap.top().second;\n\n\t\t\theap.pop();\n\n\t\t\tstd::vector<DijkstraPair> currentEdges = sortedEdges.at(currentVertex);\n\n\t\t\tfor (const DijkstraPair pair : currentEdges){\n\t\t\t\t//Find out the current neighbor vertex and the weight of the current edge\n\t\t\t\tint neighborVertex = pair.first;\n\t\t\t\tint currentWeight = pair.second;\n\t\t\t\t//Search for the right position in verticesToVisit-list. If Vertex is already visited, don't add this edge\n\t\t\t\tif (!alreadyVisited.at(neighborVertex)){\n\t\t\t\t\theap.push(std::make_pair(neighborVertex, currentDist + currentWeight));\n\t\t\t\t}\n\n\t\t\t\tint currentDistance = currentDist + currentWeight;\n\n\t\t\t\t//Update the predecessor and weightsToVerices maps\n\t\t\t\tif (currentDistance < weightsToVertices[neighborVertex]){\n\t\t\t\t\tweightsToVertices[neighborVertex] = currentDistance;\n\t\t\t\t\tpredecessorMap[neighborVertex] = currentVertex;\n\t\t\t\t}\n\t\t\t}\n\t\t\t//Current vertex is visited now\n\t\t\talreadyVisited.at(currentVertex) = true;\n\t\t} else {\n\t\t\theap.pop();\n\t\t}\n\t}\n\treturn weightsToVertices;\n}\n", "meta": {"hexsha": "5b876fd539327ec60a24f38790cf88d5a00cf40a", "size": 3764, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Julia/ex5/src/dijkstra.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": "Julia/ex5/src/dijkstra.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": "Julia/ex5/src/dijkstra.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": 33.9099099099, "max_line_length": 110, "alphanum_fraction": 0.7345908608, "num_tokens": 939, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.4916880766429437}}
{"text": "//  (C) Copyright John Maddock 2006.\r\n//  Use, modification and distribution are subject to the\r\n//  Boost Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef BOOST_MATH_SPECIAL_BETA_HPP\r\n#define BOOST_MATH_SPECIAL_BETA_HPP\r\n\r\n#ifdef _MSC_VER\r\n#pragma once\r\n#endif\r\n\r\n#include <boost/math/special_functions/math_fwd.hpp>\r\n#include <boost/math/tools/config.hpp>\r\n#include <boost/math/special_functions/gamma.hpp>\r\n#include <boost/math/special_functions/factorials.hpp>\r\n#include <boost/math/special_functions/erf.hpp>\r\n#include <boost/math/special_functions/log1p.hpp>\r\n#include <boost/math/special_functions/expm1.hpp>\r\n#include <boost/math/special_functions/trunc.hpp>\r\n#include <boost/math/tools/roots.hpp>\r\n#include <boost/static_assert.hpp>\r\n#include <boost/config/no_tr1/cmath.hpp>\r\n\r\nnamespace boost{ namespace math{\r\n\r\nnamespace detail{\r\n\r\n//\r\n// Implementation of Beta(a,b) using the Lanczos approximation:\r\n//\r\ntemplate <class T, class Lanczos, class Policy>\r\nT beta_imp(T a, T b, const Lanczos&, const Policy& pol)\r\n{\r\n   BOOST_MATH_STD_USING  // for ADL of std names\r\n\r\n   if(a <= 0)\r\n      policies::raise_domain_error<T>(\"boost::math::beta<%1%>(%1%,%1%)\", \"The arguments to the beta function must be greater than zero (got a=%1%).\", a, pol);\r\n   if(b <= 0)\r\n      policies::raise_domain_error<T>(\"boost::math::beta<%1%>(%1%,%1%)\", \"The arguments to the beta function must be greater than zero (got b=%1%).\", b, pol);\r\n\r\n   T result;\r\n\r\n   T prefix = 1;\r\n   T c = a + b;\r\n\r\n   // Special cases:\r\n   if((c == a) && (b < tools::epsilon<T>()))\r\n      return boost::math::tgamma(b, pol);\r\n   else if((c == b) && (a < tools::epsilon<T>()))\r\n      return boost::math::tgamma(a, pol);\r\n   if(b == 1)\r\n      return 1/a;\r\n   else if(a == 1)\r\n      return 1/b;\r\n\r\n   /*\r\n   //\r\n   // This code appears to be no longer necessary: it was\r\n   // used to offset errors introduced from the Lanczos\r\n   // approximation, but the current Lanczos approximations\r\n   // are sufficiently accurate for all z that we can ditch\r\n   // this.  It remains in the file for future reference...\r\n   //\r\n   // If a or b are less than 1, shift to greater than 1:\r\n   if(a < 1)\r\n   {\r\n      prefix *= c / a;\r\n      c += 1;\r\n      a += 1;\r\n   }\r\n   if(b < 1)\r\n   {\r\n      prefix *= c / b;\r\n      c += 1;\r\n      b += 1;\r\n   }\r\n   */\r\n\r\n   if(a < b)\r\n      std::swap(a, b);\r\n\r\n   // Lanczos calculation:\r\n   T agh = a + Lanczos::g() - T(0.5);\r\n   T bgh = b + Lanczos::g() - T(0.5);\r\n   T cgh = c + Lanczos::g() - T(0.5);\r\n   result = Lanczos::lanczos_sum_expG_scaled(a) * Lanczos::lanczos_sum_expG_scaled(b) / Lanczos::lanczos_sum_expG_scaled(c);\r\n   T ambh = a - T(0.5) - b;\r\n   if((fabs(b * ambh) < (cgh * 100)) && (a > 100))\r\n   {\r\n      // Special case where the base of the power term is close to 1\r\n      // compute (1+x)^y instead:\r\n      result *= exp(ambh * boost::math::log1p(-b / cgh, pol));\r\n   }\r\n   else\r\n   {\r\n      result *= pow(agh / cgh, a - T(0.5) - b);\r\n   }\r\n   if(cgh > 1e10f)\r\n      // this avoids possible overflow, but appears to be marginally less accurate:\r\n      result *= pow((agh / cgh) * (bgh / cgh), b);\r\n   else\r\n      result *= pow((agh * bgh) / (cgh * cgh), b);\r\n   result *= sqrt(boost::math::constants::e<T>() / bgh);\r\n\r\n   // If a and b were originally less than 1 we need to scale the result:\r\n   result *= prefix;\r\n\r\n   return result;\r\n} // template <class T, class Lanczos> beta_imp(T a, T b, const Lanczos&)\r\n\r\n//\r\n// Generic implementation of Beta(a,b) without Lanczos approximation support\r\n// (Caution this is slow!!!):\r\n//\r\ntemplate <class T, class Policy>\r\nT beta_imp(T a, T b, const lanczos::undefined_lanczos& /* l */, const Policy& pol)\r\n{\r\n   BOOST_MATH_STD_USING\r\n\r\n   if(a <= 0)\r\n      policies::raise_domain_error<T>(\"boost::math::beta<%1%>(%1%,%1%)\", \"The arguments to the beta function must be greater than zero (got a=%1%).\", a, pol);\r\n   if(b <= 0)\r\n      policies::raise_domain_error<T>(\"boost::math::beta<%1%>(%1%,%1%)\", \"The arguments to the beta function must be greater than zero (got b=%1%).\", b, pol);\r\n\r\n   T result;\r\n\r\n   T prefix = 1;\r\n   T c = a + b;\r\n\r\n   // special cases:\r\n   if((c == a) && (b < tools::epsilon<T>()))\r\n      return boost::math::tgamma(b, pol);\r\n   else if((c == b) && (a < tools::epsilon<T>()))\r\n      return boost::math::tgamma(a, pol);\r\n   if(b == 1)\r\n      return 1/a;\r\n   else if(a == 1)\r\n      return 1/b;\r\n\r\n   // shift to a and b > 1 if required:\r\n   if(a < 1)\r\n   {\r\n      prefix *= c / a;\r\n      c += 1;\r\n      a += 1;\r\n   }\r\n   if(b < 1)\r\n   {\r\n      prefix *= c / b;\r\n      c += 1;\r\n      b += 1;\r\n   }\r\n   if(a < b)\r\n      std::swap(a, b);\r\n\r\n   // set integration limits:\r\n   T la = (std::max)(T(10), a);\r\n   T lb = (std::max)(T(10), b);\r\n   T lc = (std::max)(T(10), T(a+b));\r\n\r\n   // calculate the fraction parts:\r\n   T sa = detail::lower_gamma_series(a, la, pol) / a;\r\n   sa += detail::upper_gamma_fraction(a, la, ::boost::math::policies::get_epsilon<T, Policy>());\r\n   T sb = detail::lower_gamma_series(b, lb, pol) / b;\r\n   sb += detail::upper_gamma_fraction(b, lb, ::boost::math::policies::get_epsilon<T, Policy>());\r\n   T sc = detail::lower_gamma_series(c, lc, pol) / c;\r\n   sc += detail::upper_gamma_fraction(c, lc, ::boost::math::policies::get_epsilon<T, Policy>());\r\n\r\n   // and the exponent part:\r\n   result = exp(lc - la - lb) * pow(la/lc, a) * pow(lb/lc, b);\r\n\r\n   // and combine:\r\n   result *= sa * sb / sc;\r\n\r\n   // if a and b were originally less than 1 we need to scale the result:\r\n   result *= prefix;\r\n\r\n   return result;\r\n} // template <class T>T beta_imp(T a, T b, const lanczos::undefined_lanczos& l)\r\n\r\n\r\n//\r\n// Compute the leading power terms in the incomplete Beta:\r\n//\r\n// (x^a)(y^b)/Beta(a,b) when normalised, and\r\n// (x^a)(y^b) otherwise.\r\n//\r\n// Almost all of the error in the incomplete beta comes from this\r\n// function: particularly when a and b are large. Computing large\r\n// powers are *hard* though, and using logarithms just leads to\r\n// horrendous cancellation errors.\r\n//\r\ntemplate <class T, class Lanczos, class Policy>\r\nT ibeta_power_terms(T a,\r\n                        T b,\r\n                        T x,\r\n                        T y,\r\n                        const Lanczos&,\r\n                        bool normalised,\r\n                        const Policy& pol)\r\n{\r\n   BOOST_MATH_STD_USING\r\n\r\n   if(!normalised)\r\n   {\r\n      // can we do better here?\r\n      return pow(x, a) * pow(y, b);\r\n   }\r\n\r\n   T result;\r\n\r\n   T prefix = 1;\r\n   T c = a + b;\r\n\r\n   // combine power terms with Lanczos approximation:\r\n   T agh = a + Lanczos::g() - T(0.5);\r\n   T bgh = b + Lanczos::g() - T(0.5);\r\n   T cgh = c + Lanczos::g() - T(0.5);\r\n   result = Lanczos::lanczos_sum_expG_scaled(c) / (Lanczos::lanczos_sum_expG_scaled(a) * Lanczos::lanczos_sum_expG_scaled(b));\r\n\r\n   // l1 and l2 are the base of the exponents minus one:\r\n   T l1 = (x * b - y * agh) / agh;\r\n   T l2 = (y * a - x * bgh) / bgh;\r\n   if(((std::min)(fabs(l1), fabs(l2)) < 0.2))\r\n   {\r\n      // when the base of the exponent is very near 1 we get really\r\n      // gross errors unless extra care is taken:\r\n      if((l1 * l2 > 0) || ((std::min)(a, b) < 1))\r\n      {\r\n         //\r\n         // This first branch handles the simple cases where either: \r\n         //\r\n         // * The two power terms both go in the same direction \r\n         // (towards zero or towards infinity).  In this case if either \r\n         // term overflows or underflows, then the product of the two must \r\n         // do so also.  \r\n         // *Alternatively if one exponent is less than one, then we \r\n         // can't productively use it to eliminate overflow or underflow \r\n         // from the other term.  Problems with spurious overflow/underflow \r\n         // can't be ruled out in this case, but it is *very* unlikely \r\n         // since one of the power terms will evaluate to a number close to 1.\r\n         //\r\n         if(fabs(l1) < 0.1)\r\n         {\r\n            result *= exp(a * boost::math::log1p(l1, pol));\r\n            BOOST_MATH_INSTRUMENT_VARIABLE(result);\r\n         }\r\n         else\r\n         {\r\n            result *= pow((x * cgh) / agh, a);\r\n            BOOST_MATH_INSTRUMENT_VARIABLE(result);\r\n         }\r\n         if(fabs(l2) < 0.1)\r\n         {\r\n            result *= exp(b * boost::math::log1p(l2, pol));\r\n            BOOST_MATH_INSTRUMENT_VARIABLE(result);\r\n         }\r\n         else\r\n         {\r\n            result *= pow((y * cgh) / bgh, b);\r\n            BOOST_MATH_INSTRUMENT_VARIABLE(result);\r\n         }\r\n      }\r\n      else if((std::max)(fabs(l1), fabs(l2)) < 0.5)\r\n      {\r\n         //\r\n         // Both exponents are near one and both the exponents are \r\n         // greater than one and further these two \r\n         // power terms tend in opposite directions (one towards zero, \r\n         // the other towards infinity), so we have to combine the terms \r\n         // to avoid any risk of overflow or underflow.\r\n         //\r\n         // We do this by moving one power term inside the other, we have:\r\n         //\r\n         //    (1 + l1)^a * (1 + l2)^b\r\n         //  = ((1 + l1)*(1 + l2)^(b/a))^a\r\n         //  = (1 + l1 + l3 + l1*l3)^a   ;  l3 = (1 + l2)^(b/a) - 1\r\n         //                                    = exp((b/a) * log(1 + l2)) - 1\r\n         //\r\n         // The tricky bit is deciding which term to move inside :-)\r\n         // By preference we move the larger term inside, so that the\r\n         // size of the largest exponent is reduced.  However, that can\r\n         // only be done as long as l3 (see above) is also small.\r\n         //\r\n         bool small_a = a < b;\r\n         T ratio = b / a;\r\n         if((small_a && (ratio * l2 < 0.1)) || (!small_a && (l1 / ratio > 0.1)))\r\n         {\r\n            T l3 = boost::math::expm1(ratio * boost::math::log1p(l2, pol), pol);\r\n            l3 = l1 + l3 + l3 * l1;\r\n            l3 = a * boost::math::log1p(l3, pol);\r\n            result *= exp(l3);\r\n            BOOST_MATH_INSTRUMENT_VARIABLE(result);\r\n         }\r\n         else\r\n         {\r\n            T l3 = boost::math::expm1(boost::math::log1p(l1, pol) / ratio, pol);\r\n            l3 = l2 + l3 + l3 * l2;\r\n            l3 = b * boost::math::log1p(l3, pol);\r\n            result *= exp(l3);\r\n            BOOST_MATH_INSTRUMENT_VARIABLE(result);\r\n         }\r\n      }\r\n      else if(fabs(l1) < fabs(l2))\r\n      {\r\n         // First base near 1 only:\r\n         T l = a * boost::math::log1p(l1, pol)\r\n            + b * log((y * cgh) / bgh);\r\n         result *= exp(l);\r\n         BOOST_MATH_INSTRUMENT_VARIABLE(result);\r\n      }\r\n      else\r\n      {\r\n         // Second base near 1 only:\r\n         T l = b * boost::math::log1p(l2, pol)\r\n            + a * log((x * cgh) / agh);\r\n         result *= exp(l);\r\n         BOOST_MATH_INSTRUMENT_VARIABLE(result);\r\n      }\r\n   }\r\n   else\r\n   {\r\n      // general case:\r\n      T b1 = (x * cgh) / agh;\r\n      T b2 = (y * cgh) / bgh;\r\n      l1 = a * log(b1);\r\n      l2 = b * log(b2);\r\n      BOOST_MATH_INSTRUMENT_VARIABLE(b1);\r\n      BOOST_MATH_INSTRUMENT_VARIABLE(b2);\r\n      BOOST_MATH_INSTRUMENT_VARIABLE(l1);\r\n      BOOST_MATH_INSTRUMENT_VARIABLE(l2);\r\n      if((l1 >= tools::log_max_value<T>())\r\n         || (l1 <= tools::log_min_value<T>())\r\n         || (l2 >= tools::log_max_value<T>())\r\n         || (l2 <= tools::log_min_value<T>())\r\n         )\r\n      {\r\n         // Oops, overflow, sidestep:\r\n         if(a < b)\r\n            result *= pow(pow(b2, b/a) * b1, a);\r\n         else\r\n            result *= pow(pow(b1, a/b) * b2, b);\r\n         BOOST_MATH_INSTRUMENT_VARIABLE(result);\r\n      }\r\n      else\r\n      {\r\n         // finally the normal case:\r\n         result *= pow(b1, a) * pow(b2, b);\r\n         BOOST_MATH_INSTRUMENT_VARIABLE(result);\r\n      }\r\n   }\r\n   // combine with the leftover terms from the Lanczos approximation:\r\n   result *= sqrt(bgh / boost::math::constants::e<T>());\r\n   result *= sqrt(agh / cgh);\r\n   result *= prefix;\r\n\r\n   BOOST_MATH_INSTRUMENT_VARIABLE(result);\r\n\r\n   return result;\r\n}\r\n//\r\n// Compute the leading power terms in the incomplete Beta:\r\n//\r\n// (x^a)(y^b)/Beta(a,b) when normalised, and\r\n// (x^a)(y^b) otherwise.\r\n//\r\n// Almost all of the error in the incomplete beta comes from this\r\n// function: particularly when a and b are large. Computing large\r\n// powers are *hard* though, and using logarithms just leads to\r\n// horrendous cancellation errors.\r\n//\r\n// This version is generic, slow, and does not use the Lanczos approximation.\r\n//\r\ntemplate <class T, class Policy>\r\nT ibeta_power_terms(T a,\r\n                        T b,\r\n                        T x,\r\n                        T y,\r\n                        const boost::math::lanczos::undefined_lanczos&,\r\n                        bool normalised,\r\n                        const Policy& pol)\r\n{\r\n   BOOST_MATH_STD_USING\r\n\r\n   if(!normalised)\r\n   {\r\n      return pow(x, a) * pow(y, b);\r\n   }\r\n\r\n   T result= 0; // assignment here silences warnings later\r\n\r\n   T c = a + b;\r\n\r\n   // integration limits for the gamma functions:\r\n   //T la = (std::max)(T(10), a);\r\n   //T lb = (std::max)(T(10), b);\r\n   //T lc = (std::max)(T(10), a+b);\r\n   T la = a + 5;\r\n   T lb = b + 5;\r\n   T lc = a + b + 5;\r\n   // gamma function partials:\r\n   T sa = detail::lower_gamma_series(a, la, pol) / a;\r\n   sa += detail::upper_gamma_fraction(a, la, ::boost::math::policies::get_epsilon<T, Policy>());\r\n   T sb = detail::lower_gamma_series(b, lb, pol) / b;\r\n   sb += detail::upper_gamma_fraction(b, lb, ::boost::math::policies::get_epsilon<T, Policy>());\r\n   T sc = detail::lower_gamma_series(c, lc, pol) / c;\r\n   sc += detail::upper_gamma_fraction(c, lc, ::boost::math::policies::get_epsilon<T, Policy>());\r\n   // gamma function powers combined with incomplete beta powers:\r\n\r\n   T b1 = (x * lc) / la;\r\n   T b2 = (y * lc) / lb;\r\n   T e1 = lc - la - lb;\r\n   T lb1 = a * log(b1);\r\n   T lb2 = b * log(b2);\r\n\r\n   if((lb1 >= tools::log_max_value<T>())\r\n      || (lb1 <= tools::log_min_value<T>())\r\n      || (lb2 >= tools::log_max_value<T>())\r\n      || (lb2 <= tools::log_min_value<T>())\r\n      || (e1 >= tools::log_max_value<T>())\r\n      || (e1 <= tools::log_min_value<T>())\r\n      )\r\n   {\r\n      result = exp(lb1 + lb2 - e1);\r\n   }\r\n   else\r\n   {\r\n      T p1, p2;\r\n      if((fabs(b1 - 1) * a < 10) && (a > 1))\r\n         p1 = exp(a * boost::math::log1p((x * b - y * la) / la, pol));\r\n      else\r\n         p1 = pow(b1, a);\r\n      if((fabs(b2 - 1) * b < 10) && (b > 1))\r\n         p2 = exp(b * boost::math::log1p((y * a - x * lb) / lb, pol));\r\n      else\r\n         p2 = pow(b2, b);\r\n      T p3 = exp(e1);\r\n      result = p1 * p2 / p3;\r\n   }\r\n   // and combine with the remaining gamma function components:\r\n   result /= sa * sb / sc;\r\n\r\n   return result;\r\n}\r\n//\r\n// Series approximation to the incomplete beta:\r\n//\r\ntemplate <class T>\r\nstruct ibeta_series_t\r\n{\r\n   typedef T result_type;\r\n   ibeta_series_t(T a_, T b_, T x_, T mult) : result(mult), x(x_), apn(a_), poch(1-b_), n(1) {}\r\n   T operator()()\r\n   {\r\n      T r = result / apn;\r\n      apn += 1;\r\n      result *= poch * x / n;\r\n      ++n;\r\n      poch += 1;\r\n      return r;\r\n   }\r\nprivate:\r\n   T result, x, apn, poch;\r\n   int n;\r\n};\r\n\r\ntemplate <class T, class Lanczos, class Policy>\r\nT ibeta_series(T a, T b, T x, T s0, const Lanczos&, bool normalised, T* p_derivative, T y, const Policy& pol)\r\n{\r\n   BOOST_MATH_STD_USING\r\n\r\n   T result;\r\n\r\n   BOOST_ASSERT((p_derivative == 0) || normalised);\r\n\r\n   if(normalised)\r\n   {\r\n      T c = a + b;\r\n\r\n      // incomplete beta power term, combined with the Lanczos approximation:\r\n      T agh = a + Lanczos::g() - T(0.5);\r\n      T bgh = b + Lanczos::g() - T(0.5);\r\n      T cgh = c + Lanczos::g() - T(0.5);\r\n      result = Lanczos::lanczos_sum_expG_scaled(c) / (Lanczos::lanczos_sum_expG_scaled(a) * Lanczos::lanczos_sum_expG_scaled(b));\r\n      if(a * b < bgh * 10)\r\n         result *= exp((b - 0.5f) * boost::math::log1p(a / bgh, pol));\r\n      else\r\n         result *= pow(cgh / bgh, b - 0.5f);\r\n      result *= pow(x * cgh / agh, a);\r\n      result *= sqrt(agh / boost::math::constants::e<T>());\r\n\r\n      if(p_derivative)\r\n      {\r\n         *p_derivative = result * pow(y, b);\r\n         BOOST_ASSERT(*p_derivative >= 0);\r\n      }\r\n   }\r\n   else\r\n   {\r\n      // Non-normalised, just compute the power:\r\n      result = pow(x, a);\r\n   }\r\n   if(result < tools::min_value<T>())\r\n      return s0; // Safeguard: series can't cope with denorms.\r\n   ibeta_series_t<T> s(a, b, x, result);\r\n   boost::uintmax_t max_iter = policies::get_max_series_iterations<Policy>();\r\n   result = boost::math::tools::sum_series(s, boost::math::policies::get_epsilon<T, Policy>(), max_iter, s0);\r\n   policies::check_series_iterations<T>(\"boost::math::ibeta<%1%>(%1%, %1%, %1%) in ibeta_series (with lanczos)\", max_iter, pol);\r\n   return result;\r\n}\r\n//\r\n// Incomplete Beta series again, this time without Lanczos support:\r\n//\r\ntemplate <class T, class Policy>\r\nT ibeta_series(T a, T b, T x, T s0, const boost::math::lanczos::undefined_lanczos&, bool normalised, T* p_derivative, T y, const Policy& pol)\r\n{\r\n   BOOST_MATH_STD_USING\r\n\r\n   T result;\r\n   BOOST_ASSERT((p_derivative == 0) || normalised);\r\n\r\n   if(normalised)\r\n   {\r\n      T c = a + b;\r\n\r\n      // figure out integration limits for the gamma function:\r\n      //T la = (std::max)(T(10), a);\r\n      //T lb = (std::max)(T(10), b);\r\n      //T lc = (std::max)(T(10), a+b);\r\n      T la = a + 5;\r\n      T lb = b + 5;\r\n      T lc = a + b + 5;\r\n\r\n      // calculate the gamma parts:\r\n      T sa = detail::lower_gamma_series(a, la, pol) / a;\r\n      sa += detail::upper_gamma_fraction(a, la, ::boost::math::policies::get_epsilon<T, Policy>());\r\n      T sb = detail::lower_gamma_series(b, lb, pol) / b;\r\n      sb += detail::upper_gamma_fraction(b, lb, ::boost::math::policies::get_epsilon<T, Policy>());\r\n      T sc = detail::lower_gamma_series(c, lc, pol) / c;\r\n      sc += detail::upper_gamma_fraction(c, lc, ::boost::math::policies::get_epsilon<T, Policy>());\r\n\r\n      // and their combined power-terms:\r\n      T b1 = (x * lc) / la;\r\n      T b2 = lc/lb;\r\n      T e1 = lc - la - lb;\r\n      T lb1 = a * log(b1);\r\n      T lb2 = b * log(b2);\r\n\r\n      if((lb1 >= tools::log_max_value<T>())\r\n         || (lb1 <= tools::log_min_value<T>())\r\n         || (lb2 >= tools::log_max_value<T>())\r\n         || (lb2 <= tools::log_min_value<T>())\r\n         || (e1 >= tools::log_max_value<T>())\r\n         || (e1 <= tools::log_min_value<T>()) )\r\n      {\r\n         T p = lb1 + lb2 - e1;\r\n         result = exp(p);\r\n      }\r\n      else\r\n      {\r\n         result = pow(b1, a);\r\n         if(a * b < lb * 10)\r\n            result *= exp(b * boost::math::log1p(a / lb, pol));\r\n         else\r\n            result *= pow(b2, b);\r\n         result /= exp(e1);\r\n      }\r\n      // and combine the results:\r\n      result /= sa * sb / sc;\r\n\r\n      if(p_derivative)\r\n      {\r\n         *p_derivative = result * pow(y, b);\r\n         BOOST_ASSERT(*p_derivative >= 0);\r\n      }\r\n   }\r\n   else\r\n   {\r\n      // Non-normalised, just compute the power:\r\n      result = pow(x, a);\r\n   }\r\n   if(result < tools::min_value<T>())\r\n      return s0; // Safeguard: series can't cope with denorms.\r\n   ibeta_series_t<T> s(a, b, x, result);\r\n   boost::uintmax_t max_iter = policies::get_max_series_iterations<Policy>();\r\n   result = boost::math::tools::sum_series(s, boost::math::policies::get_epsilon<T, Policy>(), max_iter, s0);\r\n   policies::check_series_iterations<T>(\"boost::math::ibeta<%1%>(%1%, %1%, %1%) in ibeta_series (without lanczos)\", max_iter, pol);\r\n   return result;\r\n}\r\n\r\n//\r\n// Continued fraction for the incomplete beta:\r\n//\r\ntemplate <class T>\r\nstruct ibeta_fraction2_t\r\n{\r\n   typedef std::pair<T, T> result_type;\r\n\r\n   ibeta_fraction2_t(T a_, T b_, T x_, T y_) : a(a_), b(b_), x(x_), y(y_), m(0) {}\r\n\r\n   result_type operator()()\r\n   {\r\n      T aN = (a + m - 1) * (a + b + m - 1) * m * (b - m) * x * x;\r\n      T denom = (a + 2 * m - 1);\r\n      aN /= denom * denom;\r\n\r\n      T bN = m;\r\n      bN += (m * (b - m) * x) / (a + 2*m - 1);\r\n      bN += ((a + m) * (a * y - b * x + 1 + m *(2 - x))) / (a + 2*m + 1);\r\n\r\n      ++m;\r\n\r\n      return std::make_pair(aN, bN);\r\n   }\r\n\r\nprivate:\r\n   T a, b, x, y;\r\n   int m;\r\n};\r\n//\r\n// Evaluate the incomplete beta via the continued fraction representation:\r\n//\r\ntemplate <class T, class Policy>\r\ninline T ibeta_fraction2(T a, T b, T x, T y, const Policy& pol, bool normalised, T* p_derivative)\r\n{\r\n   typedef typename lanczos::lanczos<T, Policy>::type lanczos_type;\r\n   BOOST_MATH_STD_USING\r\n   T result = ibeta_power_terms(a, b, x, y, lanczos_type(), normalised, pol);\r\n   if(p_derivative)\r\n   {\r\n      *p_derivative = result;\r\n      BOOST_ASSERT(*p_derivative >= 0);\r\n   }\r\n   if(result == 0)\r\n      return result;\r\n\r\n   ibeta_fraction2_t<T> f(a, b, x, y);\r\n   T fract = boost::math::tools::continued_fraction_b(f, boost::math::policies::get_epsilon<T, Policy>());\r\n   BOOST_MATH_INSTRUMENT_VARIABLE(fract);\r\n   BOOST_MATH_INSTRUMENT_VARIABLE(result);\r\n   return result / fract;\r\n}\r\n//\r\n// Computes the difference between ibeta(a,b,x) and ibeta(a+k,b,x):\r\n//\r\ntemplate <class T, class Policy>\r\nT ibeta_a_step(T a, T b, T x, T y, int k, const Policy& pol, bool normalised, T* p_derivative)\r\n{\r\n   typedef typename lanczos::lanczos<T, Policy>::type lanczos_type;\r\n\r\n   BOOST_MATH_INSTRUMENT_VARIABLE(k);\r\n\r\n   T prefix = ibeta_power_terms(a, b, x, y, lanczos_type(), normalised, pol);\r\n   if(p_derivative)\r\n   {\r\n      *p_derivative = prefix;\r\n      BOOST_ASSERT(*p_derivative >= 0);\r\n   }\r\n   prefix /= a;\r\n   if(prefix == 0)\r\n      return prefix;\r\n   T sum = 1;\r\n   T term = 1;\r\n   // series summation from 0 to k-1:\r\n   for(int i = 0; i < k-1; ++i)\r\n   {\r\n      term *= (a+b+i) * x / (a+i+1);\r\n      sum += term;\r\n   }\r\n   prefix *= sum;\r\n\r\n   return prefix;\r\n}\r\n//\r\n// This function is only needed for the non-regular incomplete beta,\r\n// it computes the delta in:\r\n// beta(a,b,x) = prefix + delta * beta(a+k,b,x)\r\n// it is currently only called for small k.\r\n//\r\ntemplate <class T>\r\ninline T rising_factorial_ratio(T a, T b, int k)\r\n{\r\n   // calculate:\r\n   // (a)(a+1)(a+2)...(a+k-1)\r\n   // _______________________\r\n   // (b)(b+1)(b+2)...(b+k-1)\r\n\r\n   // This is only called with small k, for large k\r\n   // it is grossly inefficient, do not use outside it's\r\n   // intended purpose!!!\r\n   BOOST_MATH_INSTRUMENT_VARIABLE(k);\r\n   if(k == 0)\r\n      return 1;\r\n   T result = 1;\r\n   for(int i = 0; i < k; ++i)\r\n      result *= (a+i) / (b+i);\r\n   return result;\r\n}\r\n//\r\n// Routine for a > 15, b < 1\r\n//\r\n// Begin by figuring out how large our table of Pn's should be,\r\n// quoted accuracies are \"guestimates\" based on empiracal observation.\r\n// Note that the table size should never exceed the size of our\r\n// tables of factorials.\r\n//\r\ntemplate <class T>\r\nstruct Pn_size\r\n{\r\n   // This is likely to be enough for ~35-50 digit accuracy\r\n   // but it's hard to quantify exactly:\r\n   BOOST_STATIC_CONSTANT(unsigned, value = 50);\r\n   BOOST_STATIC_ASSERT(::boost::math::max_factorial<T>::value >= 100);\r\n};\r\ntemplate <>\r\nstruct Pn_size<float>\r\n{\r\n   BOOST_STATIC_CONSTANT(unsigned, value = 15); // ~8-15 digit accuracy\r\n   BOOST_STATIC_ASSERT(::boost::math::max_factorial<float>::value >= 30);\r\n};\r\ntemplate <>\r\nstruct Pn_size<double>\r\n{\r\n   BOOST_STATIC_CONSTANT(unsigned, value = 30); // 16-20 digit accuracy\r\n   BOOST_STATIC_ASSERT(::boost::math::max_factorial<double>::value >= 60);\r\n};\r\ntemplate <>\r\nstruct Pn_size<long double>\r\n{\r\n   BOOST_STATIC_CONSTANT(unsigned, value = 50); // ~35-50 digit accuracy\r\n   BOOST_STATIC_ASSERT(::boost::math::max_factorial<long double>::value >= 100);\r\n};\r\n\r\ntemplate <class T, class Policy>\r\nT beta_small_b_large_a_series(T a, T b, T x, T y, T s0, T mult, const Policy& pol, bool normalised)\r\n{\r\n   typedef typename lanczos::lanczos<T, Policy>::type lanczos_type;\r\n   BOOST_MATH_STD_USING\r\n   //\r\n   // This is DiDonato and Morris's BGRAT routine, see Eq's 9 through 9.6.\r\n   //\r\n   // Some values we'll need later, these are Eq 9.1:\r\n   //\r\n   T bm1 = b - 1;\r\n   T t = a + bm1 / 2;\r\n   T lx, u;\r\n   if(y < 0.35)\r\n      lx = boost::math::log1p(-y, pol);\r\n   else\r\n      lx = log(x);\r\n   u = -t * lx;\r\n   // and from from 9.2:\r\n   T prefix;\r\n   T h = regularised_gamma_prefix(b, u, pol, lanczos_type());\r\n   if(h <= tools::min_value<T>())\r\n      return s0;\r\n   if(normalised)\r\n   {\r\n      prefix = h / boost::math::tgamma_delta_ratio(a, b, pol);\r\n      prefix /= pow(t, b);\r\n   }\r\n   else\r\n   {\r\n      prefix = full_igamma_prefix(b, u, pol) / pow(t, b);\r\n   }\r\n   prefix *= mult;\r\n   //\r\n   // now we need the quantity Pn, unfortunatately this is computed\r\n   // recursively, and requires a full history of all the previous values\r\n   // so no choice but to declare a big table and hope it's big enough...\r\n   //\r\n   T p[ ::boost::math::detail::Pn_size<T>::value ] = { 1 };  // see 9.3.\r\n   //\r\n   // Now an initial value for J, see 9.6:\r\n   //\r\n   T j = boost::math::gamma_q(b, u, pol) / h;\r\n   //\r\n   // Now we can start to pull things together and evaluate the sum in Eq 9:\r\n   //\r\n   T sum = s0 + prefix * j;  // Value at N = 0\r\n   // some variables we'll need:\r\n   unsigned tnp1 = 1; // 2*N+1\r\n   T lx2 = lx / 2;\r\n   lx2 *= lx2;\r\n   T lxp = 1;\r\n   T t4 = 4 * t * t;\r\n   T b2n = b;\r\n\r\n   for(unsigned n = 1; n < sizeof(p)/sizeof(p[0]); ++n)\r\n   {\r\n      /*\r\n      // debugging code, enable this if you want to determine whether\r\n      // the table of Pn's is large enough...\r\n      //\r\n      static int max_count = 2;\r\n      if(n > max_count)\r\n      {\r\n         max_count = n;\r\n         std::cerr << \"Max iterations in BGRAT was \" << n << std::endl;\r\n      }\r\n      */\r\n      //\r\n      // begin by evaluating the next Pn from Eq 9.4:\r\n      //\r\n      tnp1 += 2;\r\n      p[n] = 0;\r\n      T mbn = b - n;\r\n      unsigned tmp1 = 3;\r\n      for(unsigned m = 1; m < n; ++m)\r\n      {\r\n         mbn = m * b - n;\r\n         p[n] += mbn * p[n-m] / boost::math::unchecked_factorial<T>(tmp1);\r\n         tmp1 += 2;\r\n      }\r\n      p[n] /= n;\r\n      p[n] += bm1 / boost::math::unchecked_factorial<T>(tnp1);\r\n      //\r\n      // Now we want Jn from Jn-1 using Eq 9.6:\r\n      //\r\n      j = (b2n * (b2n + 1) * j + (u + b2n + 1) * lxp) / t4;\r\n      lxp *= lx2;\r\n      b2n += 2;\r\n      //\r\n      // pull it together with Eq 9:\r\n      //\r\n      T r = prefix * p[n] * j;\r\n      sum += r;\r\n      if(r > 1)\r\n      {\r\n         if(fabs(r) < fabs(tools::epsilon<T>() * sum))\r\n            break;\r\n      }\r\n      else\r\n      {\r\n         if(fabs(r / tools::epsilon<T>()) < fabs(sum))\r\n            break;\r\n      }\r\n   }\r\n   return sum;\r\n} // template <class T, class Lanczos>T beta_small_b_large_a_series(T a, T b, T x, T y, T s0, T mult, const Lanczos& l, bool normalised)\r\n\r\n//\r\n// For integer arguments we can relate the incomplete beta to the\r\n// complement of the binomial distribution cdf and use this finite sum.\r\n//\r\ntemplate <class T>\r\ninline T binomial_ccdf(T n, T k, T x, T y)\r\n{\r\n   BOOST_MATH_STD_USING // ADL of std names\r\n   T result = pow(x, n);\r\n   T term = result;\r\n   for(unsigned i = itrunc(T(n - 1)); i > k; --i)\r\n   {\r\n      term *= ((i + 1) * y) / ((n - i) * x) ;\r\n      result += term;\r\n   }\r\n\r\n   return result;\r\n}\r\n\r\n\r\n//\r\n// The incomplete beta function implementation:\r\n// This is just a big bunch of spagetti code to divide up the\r\n// input range and select the right implementation method for\r\n// each domain:\r\n//\r\ntemplate <class T, class Policy>\r\nT ibeta_imp(T a, T b, T x, const Policy& pol, bool inv, bool normalised, T* p_derivative)\r\n{\r\n   static const char* function = \"boost::math::ibeta<%1%>(%1%, %1%, %1%)\";\r\n   typedef typename lanczos::lanczos<T, Policy>::type lanczos_type;\r\n   BOOST_MATH_STD_USING // for ADL of std math functions.\r\n\r\n   BOOST_MATH_INSTRUMENT_VARIABLE(a);\r\n   BOOST_MATH_INSTRUMENT_VARIABLE(b);\r\n   BOOST_MATH_INSTRUMENT_VARIABLE(x);\r\n   BOOST_MATH_INSTRUMENT_VARIABLE(inv);\r\n   BOOST_MATH_INSTRUMENT_VARIABLE(normalised);\r\n\r\n   bool invert = inv;\r\n   T fract;\r\n   T y = 1 - x;\r\n\r\n   BOOST_ASSERT((p_derivative == 0) || normalised);\r\n\r\n   if(p_derivative)\r\n      *p_derivative = -1; // value not set.\r\n\r\n   if((x < 0) || (x > 1))\r\n      policies::raise_domain_error<T>(function, \"Parameter x outside the range [0,1] in the incomplete beta function (got x=%1%).\", x, pol);\r\n\r\n   if(normalised)\r\n   {\r\n      if(a < 0)\r\n         policies::raise_domain_error<T>(function, \"The argument a to the incomplete beta function must be >= zero (got a=%1%).\", a, pol);\r\n      if(b < 0)\r\n         policies::raise_domain_error<T>(function, \"The argument b to the incomplete beta function must be >= zero (got b=%1%).\", b, pol);\r\n      // extend to a few very special cases:\r\n      if(a == 0)\r\n      {\r\n         if(b == 0)\r\n            policies::raise_domain_error<T>(function, \"The arguments a and b to the incomplete beta function cannot both be zero, with x=%1%.\", x, pol);\r\n         if(b > 0)\r\n            return inv ? 0 : 1;\r\n      }\r\n      else if(b == 0)\r\n      {\r\n         if(a > 0)\r\n            return inv ? 1 : 0;\r\n      }\r\n   }\r\n   else\r\n   {\r\n      if(a <= 0)\r\n         policies::raise_domain_error<T>(function, \"The argument a to the incomplete beta function must be greater than zero (got a=%1%).\", a, pol);\r\n      if(b <= 0)\r\n         policies::raise_domain_error<T>(function, \"The argument b to the incomplete beta function must be greater than zero (got b=%1%).\", b, pol);\r\n   }\r\n\r\n   if(x == 0)\r\n   {\r\n      if(p_derivative)\r\n      {\r\n         *p_derivative = (a == 1) ? (T)1 : (a < 1) ? T(tools::max_value<T>() / 2) : T(tools::min_value<T>() * 2);\r\n      }\r\n      return (invert ? (normalised ? T(1) : boost::math::beta(a, b, pol)) : T(0));\r\n   }\r\n   if(x == 1)\r\n   {\r\n      if(p_derivative)\r\n      {\r\n         *p_derivative = (b == 1) ? T(1) : (b < 1) ? T(tools::max_value<T>() / 2) : T(tools::min_value<T>() * 2);\r\n      }\r\n      return (invert == 0 ? (normalised ? 1 : boost::math::beta(a, b, pol)) : 0);\r\n   }\r\n\r\n   if((std::min)(a, b) <= 1)\r\n   {\r\n      if(x > 0.5)\r\n      {\r\n         std::swap(a, b);\r\n         std::swap(x, y);\r\n         invert = !invert;\r\n         BOOST_MATH_INSTRUMENT_VARIABLE(invert);\r\n      }\r\n      if((std::max)(a, b) <= 1)\r\n      {\r\n         // Both a,b < 1:\r\n         if((a >= (std::min)(T(0.2), b)) || (pow(x, a) <= 0.9))\r\n         {\r\n            if(!invert)\r\n            {\r\n               fract = ibeta_series(a, b, x, T(0), lanczos_type(), normalised, p_derivative, y, pol);\r\n               BOOST_MATH_INSTRUMENT_VARIABLE(fract);\r\n            }\r\n            else\r\n            {\r\n               fract = -(normalised ? 1 : boost::math::beta(a, b, pol));\r\n               invert = false;\r\n               fract = -ibeta_series(a, b, x, fract, lanczos_type(), normalised, p_derivative, y, pol);\r\n               BOOST_MATH_INSTRUMENT_VARIABLE(fract);\r\n            }\r\n         }\r\n         else\r\n         {\r\n            std::swap(a, b);\r\n            std::swap(x, y);\r\n            invert = !invert;\r\n            if(y >= 0.3)\r\n            {\r\n               if(!invert)\r\n               {\r\n                  fract = ibeta_series(a, b, x, T(0), lanczos_type(), normalised, p_derivative, y, pol);\r\n                  BOOST_MATH_INSTRUMENT_VARIABLE(fract);\r\n               }\r\n               else\r\n               {\r\n                  fract = -(normalised ? 1 : boost::math::beta(a, b, pol));\r\n                  invert = false;\r\n                  fract = -ibeta_series(a, b, x, fract, lanczos_type(), normalised, p_derivative, y, pol);\r\n                  BOOST_MATH_INSTRUMENT_VARIABLE(fract);\r\n               }\r\n            }\r\n            else\r\n            {\r\n               // Sidestep on a, and then use the series representation:\r\n               T prefix;\r\n               if(!normalised)\r\n               {\r\n                  prefix = rising_factorial_ratio(T(a+b), a, 20);\r\n               }\r\n               else\r\n               {\r\n                  prefix = 1;\r\n               }\r\n               fract = ibeta_a_step(a, b, x, y, 20, pol, normalised, p_derivative);\r\n               if(!invert)\r\n               {\r\n                  fract = beta_small_b_large_a_series(T(a + 20), b, x, y, fract, prefix, pol, normalised);\r\n                  BOOST_MATH_INSTRUMENT_VARIABLE(fract);\r\n               }\r\n               else\r\n               {\r\n                  fract -= (normalised ? 1 : boost::math::beta(a, b, pol));\r\n                  invert = false;\r\n                  fract = -beta_small_b_large_a_series(T(a + 20), b, x, y, fract, prefix, pol, normalised);\r\n                  BOOST_MATH_INSTRUMENT_VARIABLE(fract);\r\n               }\r\n            }\r\n         }\r\n      }\r\n      else\r\n      {\r\n         // One of a, b < 1 only:\r\n         if((b <= 1) || ((x < 0.1) && (pow(b * x, a) <= 0.7)))\r\n         {\r\n            if(!invert)\r\n            {\r\n               fract = ibeta_series(a, b, x, T(0), lanczos_type(), normalised, p_derivative, y, pol);\r\n               BOOST_MATH_INSTRUMENT_VARIABLE(fract);\r\n            }\r\n            else\r\n            {\r\n               fract = -(normalised ? 1 : boost::math::beta(a, b, pol));\r\n               invert = false;\r\n               fract = -ibeta_series(a, b, x, fract, lanczos_type(), normalised, p_derivative, y, pol);\r\n               BOOST_MATH_INSTRUMENT_VARIABLE(fract);\r\n            }\r\n         }\r\n         else\r\n         {\r\n            std::swap(a, b);\r\n            std::swap(x, y);\r\n            invert = !invert;\r\n\r\n            if(y >= 0.3)\r\n            {\r\n               if(!invert)\r\n               {\r\n                  fract = ibeta_series(a, b, x, T(0), lanczos_type(), normalised, p_derivative, y, pol);\r\n                  BOOST_MATH_INSTRUMENT_VARIABLE(fract);\r\n               }\r\n               else\r\n               {\r\n                  fract = -(normalised ? 1 : boost::math::beta(a, b, pol));\r\n                  invert = false;\r\n                  fract = -ibeta_series(a, b, x, fract, lanczos_type(), normalised, p_derivative, y, pol);\r\n                  BOOST_MATH_INSTRUMENT_VARIABLE(fract);\r\n               }\r\n            }\r\n            else if(a >= 15)\r\n            {\r\n               if(!invert)\r\n               {\r\n                  fract = beta_small_b_large_a_series(a, b, x, y, T(0), T(1), pol, normalised);\r\n                  BOOST_MATH_INSTRUMENT_VARIABLE(fract);\r\n               }\r\n               else\r\n               {\r\n                  fract = -(normalised ? 1 : boost::math::beta(a, b, pol));\r\n                  invert = false;\r\n                  fract = -beta_small_b_large_a_series(a, b, x, y, fract, T(1), pol, normalised);\r\n                  BOOST_MATH_INSTRUMENT_VARIABLE(fract);\r\n               }\r\n            }\r\n            else\r\n            {\r\n               // Sidestep to improve errors:\r\n               T prefix;\r\n               if(!normalised)\r\n               {\r\n                  prefix = rising_factorial_ratio(T(a+b), a, 20);\r\n               }\r\n               else\r\n               {\r\n                  prefix = 1;\r\n               }\r\n               fract = ibeta_a_step(a, b, x, y, 20, pol, normalised, p_derivative);\r\n               BOOST_MATH_INSTRUMENT_VARIABLE(fract);\r\n               if(!invert)\r\n               {\r\n                  fract = beta_small_b_large_a_series(T(a + 20), b, x, y, fract, prefix, pol, normalised);\r\n                  BOOST_MATH_INSTRUMENT_VARIABLE(fract);\r\n               }\r\n               else\r\n               {\r\n                  fract -= (normalised ? 1 : boost::math::beta(a, b, pol));\r\n                  invert = false;\r\n                  fract = -beta_small_b_large_a_series(T(a + 20), b, x, y, fract, prefix, pol, normalised);\r\n                  BOOST_MATH_INSTRUMENT_VARIABLE(fract);\r\n               }\r\n            }\r\n         }\r\n      }\r\n   }\r\n   else\r\n   {\r\n      // Both a,b >= 1:\r\n      T lambda;\r\n      if(a < b)\r\n      {\r\n         lambda = a - (a + b) * x;\r\n      }\r\n      else\r\n      {\r\n         lambda = (a + b) * y - b;\r\n      }\r\n      if(lambda < 0)\r\n      {\r\n         std::swap(a, b);\r\n         std::swap(x, y);\r\n         invert = !invert;\r\n         BOOST_MATH_INSTRUMENT_VARIABLE(invert);\r\n      }\r\n      \r\n      if(b < 40)\r\n      {\r\n         if((floor(a) == a) && (floor(b) == b) && (a < (std::numeric_limits<int>::max)() - 100))\r\n         {\r\n            // relate to the binomial distribution and use a finite sum:\r\n            T k = a - 1;\r\n            T n = b + k;\r\n            fract = binomial_ccdf(n, k, x, y);\r\n            if(!normalised)\r\n               fract *= boost::math::beta(a, b, pol);\r\n            BOOST_MATH_INSTRUMENT_VARIABLE(fract);\r\n         }\r\n         else if(b * x <= 0.7)\r\n         {\r\n            if(!invert)\r\n            {\r\n               fract = ibeta_series(a, b, x, T(0), lanczos_type(), normalised, p_derivative, y, pol);\r\n               BOOST_MATH_INSTRUMENT_VARIABLE(fract);\r\n            }\r\n            else\r\n            {\r\n               fract = -(normalised ? 1 : boost::math::beta(a, b, pol));\r\n               invert = false;\r\n               fract = -ibeta_series(a, b, x, fract, lanczos_type(), normalised, p_derivative, y, pol);\r\n               BOOST_MATH_INSTRUMENT_VARIABLE(fract);\r\n            }\r\n         }\r\n         else if(a > 15)\r\n         {\r\n            // sidestep so we can use the series representation:\r\n            int n = itrunc(T(floor(b)), pol);\r\n            if(n == b)\r\n               --n;\r\n            T bbar = b - n;\r\n            T prefix;\r\n            if(!normalised)\r\n            {\r\n               prefix = rising_factorial_ratio(T(a+bbar), bbar, n);\r\n            }\r\n            else\r\n            {\r\n               prefix = 1;\r\n            }\r\n            fract = ibeta_a_step(bbar, a, y, x, n, pol, normalised, static_cast<T*>(0));\r\n            fract = beta_small_b_large_a_series(a,  bbar, x, y, fract, T(1), pol, normalised);\r\n            fract /= prefix;\r\n            BOOST_MATH_INSTRUMENT_VARIABLE(fract);\r\n         }\r\n         else if(normalised)\r\n         {\r\n            // the formula here for the non-normalised case is tricky to figure\r\n            // out (for me!!), and requires two pochhammer calculations rather\r\n            // than one, so leave it for now....\r\n            int n = itrunc(T(floor(b)), pol);\r\n            T bbar = b - n;\r\n            if(bbar <= 0)\r\n            {\r\n               --n;\r\n               bbar += 1;\r\n            }\r\n            fract = ibeta_a_step(bbar, a, y, x, n, pol, normalised, static_cast<T*>(0));\r\n            fract += ibeta_a_step(a, bbar, x, y, 20, pol, normalised, static_cast<T*>(0));\r\n            if(invert)\r\n               fract -= (normalised ? 1 : boost::math::beta(a, b, pol));\r\n            //fract = ibeta_series(a+20, bbar, x, fract, l, normalised, p_derivative, y);\r\n            fract = beta_small_b_large_a_series(T(a+20),  bbar, x, y, fract, T(1), pol, normalised);\r\n            if(invert)\r\n            {\r\n               fract = -fract;\r\n               invert = false;\r\n            }\r\n            BOOST_MATH_INSTRUMENT_VARIABLE(fract);\r\n         }\r\n         else\r\n         {\r\n            fract = ibeta_fraction2(a, b, x, y, pol, normalised, p_derivative);\r\n            BOOST_MATH_INSTRUMENT_VARIABLE(fract);\r\n         }\r\n      }\r\n      else\r\n      {\r\n         fract = ibeta_fraction2(a, b, x, y, pol, normalised, p_derivative);\r\n         BOOST_MATH_INSTRUMENT_VARIABLE(fract);\r\n      }\r\n   }\r\n   if(p_derivative)\r\n   {\r\n      if(*p_derivative < 0)\r\n      {\r\n         *p_derivative = ibeta_power_terms(a, b, x, y, lanczos_type(), true, pol);\r\n      }\r\n      T div = y * x;\r\n\r\n      if(*p_derivative != 0)\r\n      {\r\n         if((tools::max_value<T>() * div < *p_derivative))\r\n         {\r\n            // overflow, return an arbitarily large value:\r\n            *p_derivative = tools::max_value<T>() / 2;\r\n         }\r\n         else\r\n         {\r\n            *p_derivative /= div;\r\n         }\r\n      }\r\n   }\r\n   return invert ? (normalised ? 1 : boost::math::beta(a, b, pol)) - fract : fract;\r\n} // template <class T, class Lanczos>T ibeta_imp(T a, T b, T x, const Lanczos& l, bool inv, bool normalised)\r\n\r\ntemplate <class T, class Policy>\r\ninline T ibeta_imp(T a, T b, T x, const Policy& pol, bool inv, bool normalised)\r\n{\r\n   return ibeta_imp(a, b, x, pol, inv, normalised, static_cast<T*>(0));\r\n}\r\n\r\ntemplate <class T, class Policy>\r\nT ibeta_derivative_imp(T a, T b, T x, const Policy& pol)\r\n{\r\n   static const char* function = \"ibeta_derivative<%1%>(%1%,%1%,%1%)\";\r\n   //\r\n   // start with the usual error checks:\r\n   //\r\n   if(a <= 0)\r\n      policies::raise_domain_error<T>(function, \"The argument a to the incomplete beta function must be greater than zero (got a=%1%).\", a, pol);\r\n   if(b <= 0)\r\n      policies::raise_domain_error<T>(function, \"The argument b to the incomplete beta function must be greater than zero (got b=%1%).\", b, pol);\r\n   if((x < 0) || (x > 1))\r\n      policies::raise_domain_error<T>(function, \"Parameter x outside the range [0,1] in the incomplete beta function (got x=%1%).\", x, pol);\r\n   //\r\n   // Now the corner cases:\r\n   //\r\n   if(x == 0)\r\n   {\r\n      return (a > 1) ? 0 : \r\n         (a == 1) ? 1 / boost::math::beta(a, b, pol) : policies::raise_overflow_error<T>(function, 0, pol);\r\n   }\r\n   else if(x == 1)\r\n   {\r\n      return (b > 1) ? 0 :\r\n         (b == 1) ? 1 / boost::math::beta(a, b, pol) : policies::raise_overflow_error<T>(function, 0, pol);\r\n   }\r\n   //\r\n   // Now the regular cases:\r\n   //\r\n   typedef typename lanczos::lanczos<T, Policy>::type lanczos_type;\r\n   T f1 = ibeta_power_terms<T>(a, b, x, 1 - x, lanczos_type(), true, pol);\r\n   T y = (1 - x) * x;\r\n\r\n   if(f1 == 0)\r\n      return 0;\r\n   \r\n   if((tools::max_value<T>() * y < f1))\r\n   {\r\n      // overflow:\r\n      return policies::raise_overflow_error<T>(function, 0, pol);\r\n   }\r\n\r\n   f1 /= y;\r\n\r\n   return f1;\r\n}\r\n//\r\n// Some forwarding functions that dis-ambiguate the third argument type:\r\n//\r\ntemplate <class RT1, class RT2, class Policy>\r\ninline typename tools::promote_args<RT1, RT2>::type \r\n   beta(RT1 a, RT2 b, const Policy&, const mpl::true_*)\r\n{\r\n   BOOST_FPU_EXCEPTION_GUARD\r\n   typedef typename tools::promote_args<RT1, RT2>::type result_type;\r\n   typedef typename policies::evaluation<result_type, Policy>::type value_type;\r\n   typedef typename lanczos::lanczos<value_type, Policy>::type evaluation_type;\r\n   typedef typename policies::normalise<\r\n      Policy, \r\n      policies::promote_float<false>, \r\n      policies::promote_double<false>, \r\n      policies::discrete_quantile<>,\r\n      policies::assert_undefined<> >::type forwarding_policy;\r\n\r\n   return policies::checked_narrowing_cast<result_type, forwarding_policy>(detail::beta_imp(static_cast<value_type>(a), static_cast<value_type>(b), evaluation_type(), forwarding_policy()), \"boost::math::beta<%1%>(%1%,%1%)\");\r\n}\r\ntemplate <class RT1, class RT2, class RT3>\r\ninline typename tools::promote_args<RT1, RT2, RT3>::type \r\n   beta(RT1 a, RT2 b, RT3 x, const mpl::false_*)\r\n{\r\n   return boost::math::beta(a, b, x, policies::policy<>());\r\n}\r\n} // namespace detail\r\n\r\n//\r\n// The actual function entry-points now follow, these just figure out\r\n// which Lanczos approximation to use\r\n// and forward to the implementation functions:\r\n//\r\ntemplate <class RT1, class RT2, class A>\r\ninline typename tools::promote_args<RT1, RT2, A>::type \r\n   beta(RT1 a, RT2 b, A arg)\r\n{\r\n   typedef typename policies::is_policy<A>::type tag;\r\n   return boost::math::detail::beta(a, b, arg, static_cast<tag*>(0));\r\n}\r\n\r\ntemplate <class RT1, class RT2>\r\ninline typename tools::promote_args<RT1, RT2>::type \r\n   beta(RT1 a, RT2 b)\r\n{\r\n   return boost::math::beta(a, b, policies::policy<>());\r\n}\r\n\r\ntemplate <class RT1, class RT2, class RT3, class Policy>\r\ninline typename tools::promote_args<RT1, RT2, RT3>::type \r\n   beta(RT1 a, RT2 b, RT3 x, const Policy&)\r\n{\r\n   BOOST_FPU_EXCEPTION_GUARD\r\n   typedef typename tools::promote_args<RT1, RT2, RT3>::type result_type;\r\n   typedef typename policies::evaluation<result_type, Policy>::type value_type;\r\n   typedef typename lanczos::lanczos<value_type, Policy>::type evaluation_type;\r\n   typedef typename policies::normalise<\r\n      Policy, \r\n      policies::promote_float<false>, \r\n      policies::promote_double<false>, \r\n      policies::discrete_quantile<>,\r\n      policies::assert_undefined<> >::type forwarding_policy;\r\n\r\n   return policies::checked_narrowing_cast<result_type, forwarding_policy>(detail::ibeta_imp(static_cast<value_type>(a), static_cast<value_type>(b), static_cast<value_type>(x), forwarding_policy(), false, false), \"boost::math::beta<%1%>(%1%,%1%,%1%)\");\r\n}\r\n\r\ntemplate <class RT1, class RT2, class RT3, class Policy>\r\ninline typename tools::promote_args<RT1, RT2, RT3>::type \r\n   betac(RT1 a, RT2 b, RT3 x, const Policy&)\r\n{\r\n   BOOST_FPU_EXCEPTION_GUARD\r\n   typedef typename tools::promote_args<RT1, RT2, RT3>::type result_type;\r\n   typedef typename policies::evaluation<result_type, Policy>::type value_type;\r\n   typedef typename lanczos::lanczos<value_type, Policy>::type evaluation_type;\r\n   typedef typename policies::normalise<\r\n      Policy, \r\n      policies::promote_float<false>, \r\n      policies::promote_double<false>, \r\n      policies::discrete_quantile<>,\r\n      policies::assert_undefined<> >::type forwarding_policy;\r\n\r\n   return policies::checked_narrowing_cast<result_type, forwarding_policy>(detail::ibeta_imp(static_cast<value_type>(a), static_cast<value_type>(b), static_cast<value_type>(x), forwarding_policy(), true, false), \"boost::math::betac<%1%>(%1%,%1%,%1%)\");\r\n}\r\ntemplate <class RT1, class RT2, class RT3>\r\ninline typename tools::promote_args<RT1, RT2, RT3>::type \r\n   betac(RT1 a, RT2 b, RT3 x)\r\n{\r\n   return boost::math::betac(a, b, x, policies::policy<>());\r\n}\r\n\r\ntemplate <class RT1, class RT2, class RT3, class Policy>\r\ninline typename tools::promote_args<RT1, RT2, RT3>::type \r\n   ibeta(RT1 a, RT2 b, RT3 x, const Policy&)\r\n{\r\n   BOOST_FPU_EXCEPTION_GUARD\r\n   typedef typename tools::promote_args<RT1, RT2, RT3>::type result_type;\r\n   typedef typename policies::evaluation<result_type, Policy>::type value_type;\r\n   typedef typename policies::normalise<\r\n      Policy, \r\n      policies::promote_float<false>, \r\n      policies::promote_double<false>, \r\n      policies::discrete_quantile<>,\r\n      policies::assert_undefined<> >::type forwarding_policy;\r\n\r\n   return policies::checked_narrowing_cast<result_type, forwarding_policy>(detail::ibeta_imp(static_cast<value_type>(a), static_cast<value_type>(b), static_cast<value_type>(x), forwarding_policy(), false, true), \"boost::math::ibeta<%1%>(%1%,%1%,%1%)\");\r\n}\r\ntemplate <class RT1, class RT2, class RT3>\r\ninline typename tools::promote_args<RT1, RT2, RT3>::type \r\n   ibeta(RT1 a, RT2 b, RT3 x)\r\n{\r\n   return boost::math::ibeta(a, b, x, policies::policy<>());\r\n}\r\n\r\ntemplate <class RT1, class RT2, class RT3, class Policy>\r\ninline typename tools::promote_args<RT1, RT2, RT3>::type \r\n   ibetac(RT1 a, RT2 b, RT3 x, const Policy&)\r\n{\r\n   BOOST_FPU_EXCEPTION_GUARD\r\n   typedef typename tools::promote_args<RT1, RT2, RT3>::type result_type;\r\n   typedef typename policies::evaluation<result_type, Policy>::type value_type;\r\n   typedef typename policies::normalise<\r\n      Policy, \r\n      policies::promote_float<false>, \r\n      policies::promote_double<false>, \r\n      policies::discrete_quantile<>,\r\n      policies::assert_undefined<> >::type forwarding_policy;\r\n\r\n   return policies::checked_narrowing_cast<result_type, forwarding_policy>(detail::ibeta_imp(static_cast<value_type>(a), static_cast<value_type>(b), static_cast<value_type>(x), forwarding_policy(), true, true), \"boost::math::ibetac<%1%>(%1%,%1%,%1%)\");\r\n}\r\ntemplate <class RT1, class RT2, class RT3>\r\ninline typename tools::promote_args<RT1, RT2, RT3>::type \r\n   ibetac(RT1 a, RT2 b, RT3 x)\r\n{\r\n   return boost::math::ibetac(a, b, x, policies::policy<>());\r\n}\r\n\r\ntemplate <class RT1, class RT2, class RT3, class Policy>\r\ninline typename tools::promote_args<RT1, RT2, RT3>::type \r\n   ibeta_derivative(RT1 a, RT2 b, RT3 x, const Policy&)\r\n{\r\n   BOOST_FPU_EXCEPTION_GUARD\r\n   typedef typename tools::promote_args<RT1, RT2, RT3>::type result_type;\r\n   typedef typename policies::evaluation<result_type, Policy>::type value_type;\r\n   typedef typename policies::normalise<\r\n      Policy, \r\n      policies::promote_float<false>, \r\n      policies::promote_double<false>, \r\n      policies::discrete_quantile<>,\r\n      policies::assert_undefined<> >::type forwarding_policy;\r\n\r\n   return policies::checked_narrowing_cast<result_type, forwarding_policy>(detail::ibeta_derivative_imp(static_cast<value_type>(a), static_cast<value_type>(b), static_cast<value_type>(x), forwarding_policy()), \"boost::math::ibeta_derivative<%1%>(%1%,%1%,%1%)\");\r\n}\r\ntemplate <class RT1, class RT2, class RT3>\r\ninline typename tools::promote_args<RT1, RT2, RT3>::type \r\n   ibeta_derivative(RT1 a, RT2 b, RT3 x)\r\n{\r\n   return boost::math::ibeta_derivative(a, b, x, policies::policy<>());\r\n}\r\n\r\n} // namespace math\r\n} // namespace boost\r\n\r\n#include <boost/math/special_functions/detail/ibeta_inverse.hpp>\r\n#include <boost/math/special_functions/detail/ibeta_inv_ab.hpp>\r\n\r\n#endif // BOOST_MATH_SPECIAL_BETA_HPP\r\n\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "3342e9caf8e3481a41af6f0fd0ee9ae56d81fbc8", "size": 48977, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/math/special_functions/beta.hpp", "max_stars_repo_name": "PXLVision/opengv", "max_stars_repo_head_hexsha": "e48f77da4db7b8cee36ec677ed4ff5c5354571bb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 198.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T05:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:46:46.000Z", "max_issues_repo_path": "master/core/third/boost/math/special_functions/beta.hpp", "max_issues_repo_name": "isuhao/klib", "max_issues_repo_head_hexsha": "a59837857689d0e60d3df6d2ebd12c3160efa794", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 197.0, "max_issues_repo_issues_event_min_datetime": "2017-07-06T16:53:59.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-31T17:57:51.000Z", "max_forks_repo_path": "master/core/third/boost/math/special_functions/beta.hpp", "max_forks_repo_name": "isuhao/klib", "max_forks_repo_head_hexsha": "a59837857689d0e60d3df6d2ebd12c3160efa794", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 33.7772413793, "max_line_length": 262, "alphanum_fraction": 0.5451946832, "num_tokens": 13739, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.4916880766429436}}
{"text": "#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE Suites\n#include <boost/test/unit_test.hpp>\n#include\"basis.hpp\"\n\nusing namespace boost::unit_test;\nusing boost::unit_test_framework::test_suite;\nusing namespace Many_Body;\nBOOST_AUTO_TEST_SUITE(basistesting)\nBOOST_AUTO_TEST_CASE(phonondimension)\n{\n  const size_t L1=3;\n  const size_t L2=4;\n  const size_t L3=5;\n  const size_t L4=6;\n\n  BosonState b1( 4, 5);\n    \n  std::vector<size_t> state {1, 4, 1, 0};\n  BosonState b2(state, 5);\n    \n    \n \n      BOOST_CHECK(b1.GetId()==0);\n      BOOST_CHECK(b2[1]==4);\n      PhononBasis g1{ 4, 1};\n\n    for(size_t i=2; i<3; i++)\n      {\n\tPhononBasis g1{ 4, i};\n        PhononBasis g2{ 3, i};\n   \n\n        BOOST_CHECK(g1.dim==static_cast<size_t>(std::pow((i+1), 4)));\n        BOOST_CHECK(g2.dim==static_cast<size_t>(std::pow((i+1), 3)));\n   \n      \n   }\n}\nBOOST_AUTO_TEST_CASE(electrondimension)\n{\n  ElectronState df;\n  std::vector<size_t> state {1, 1,      1, 0};\n  ElectronState constru1(state);\n\n     BOOST_CHECK(constru1.GetId()==14);\n      constru1.flip(1);\n\n      BOOST_CHECK(constru1.GetId()==10);\n        ElectronState constru2(3, 4);\n\t\n//        BOOST_CHECK(constru2.GetId()==3);\n ElectronBasis g1( 3);\n\n const ElectronBasis g2(5, 2);\n       ElectronBasis g3( 3, 1);\n      \n       BOOST_CHECK(g1.dim==std::pow(2, 3));\n     BOOST_CHECK(g2.dim==Factorial(5)/(Factorial(5-2)*Factorial(2)));\n     BOOST_CHECK(g3.dim== 3);\n    \n\n\n\n }\n\n// BOOST_AUTO_TEST_CASE(bosondimension)\n// {\n\n   // const size_t L2=4;\n   // const size_t L3=5;\n   // std::array<size_t, L2> stateArray{0, 1, 2};\n   \n   //   BosonState<L2> a{stateArray};\n\n   // const BosonBasis<L2> g2{2};\n   // BosonBasis<L3> g3{1};\n\n\n      \n   // //BOOST_CHECK(g1.dim==Factorial(L2)/(Factorial(L2-2)*Factorial(2)));\n   // BOOST_CHECK(g2.dim==Factorial(L2+2-1)/(Factorial(L2-1)*Factorial(2)));\n   // BOOST_CHECK(g3.dim==Factorial(L3+1-1)/(Factorial(L3-1)*Factorial(1)));\n\n\n\n// }\n\n BOOST_AUTO_TEST_CASE(tensorproductdimension)\n {\n//   // const size_t L1=3;\n//  //  const size_t L2=4;\n//  //  const size_t L3=5;\n//  // //  const size_t L4=6;\n\n\n   PhononBasis g{ 4, 1};\n\n   \n\n ElectronBasis e{ 4, 1};\n\n TensorProduct<  ElectronBasis,  PhononBasis> TP(e, g);\n\n\n     for(size_t i=1; i<2; i++)\n         {\n\t   PhononBasis g1{3, i};\n\t   PhononBasis g2{ 4, i};\n\t   PhononBasis g3{ 5, i};\n\n\n\t   ElectronBasis e1{ 3, 1};\n\t   ElectronBasis e2{ 4, 2};\n\t   ElectronBasis e3{ 5, 3};\n\n TensorProduct<  ElectronBasis,  PhononBasis> TP1(e1, g1);\n  \t TensorProduct<  ElectronBasis,  PhononBasis> TP2(e2, g2);\n          TensorProduct<  ElectronBasis,  PhononBasis> TP3(e3, g3);\n\n  \t BOOST_CHECK(g1.dim*e1.dim==TP1.dim);\n \t BOOST_CHECK(g2.dim*e2.dim==TP2.dim);\n  \t BOOST_CHECK(g3.dim*e3.dim==TP3.dim);\n\n\n   }\n}\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "af9c4424a8ecc91c01bb9b48e290ec1693cc51ed", "size": 2764, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "testdir/basistest.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": "testdir/basistest.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": "testdir/basistest.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": 21.4263565891, "max_line_length": 76, "alphanum_fraction": 0.6219247467, "num_tokens": 970, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.6370307875894138, "lm_q1q2_score": 0.4916880646376354}}
{"text": "//  Copyright (c) 2006 Xiaogang Zhang\n//  Copyright (c) 2006 John Maddock\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//  History:\n//  XZ wrote the original of this file as part of the Google\n//  Summer of Code 2006.  JM modified it to fit into the\n//  Boost.Math conceptual framework better, and to ensure\n//  that the code continues to work no matter how many digits\n//  type T has.\n\n#ifndef BOOST_MATH_ELLINT_1_HPP\n#define BOOST_MATH_ELLINT_1_HPP\n\n#include <boost/math/special_functions/ellint_rf.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/policies/error_handling.hpp>\n#include <boost/math/tools/workaround.hpp>\n\n// Elliptic integrals (complete and incomplete) of the first kind\n// Carlson, Numerische Mathematik, vol 33, 1 (1979)\n\nnamespace boost { namespace math {\n\ntemplate <class T1, class T2, class Policy>\ntypename tools::promote_args<T1, T2>::type ellint_1(T1 k, T2 phi, const Policy& pol);\n\nnamespace detail{\n\ntemplate <typename T, typename Policy>\nT ellint_k_imp(T k, const Policy& pol);\n\n// Elliptic integral (Legendre form) of the first kind\ntemplate <typename T, typename Policy>\nT ellint_f_imp(T phi, T k, const Policy& pol)\n{\n    BOOST_MATH_STD_USING\n    using namespace boost::math::tools;\n    using namespace boost::math::constants;\n\n    static const char* function = \"boost::math::ellint_f<%1%>(%1%,%1%)\";\n    BOOST_MATH_INSTRUMENT_VARIABLE(phi);\n    BOOST_MATH_INSTRUMENT_VARIABLE(k);\n    BOOST_MATH_INSTRUMENT_VARIABLE(function);\n\n    if (abs(k) > 1)\n    {\n       return policies::raise_domain_error<T>(function,\n            \"Got k = %1%, function requires |k| <= 1\", k, pol);\n    }\n\n    bool invert = false;\n    if(phi < 0)\n    {\n       BOOST_MATH_INSTRUMENT_VARIABLE(phi);\n       phi = fabs(phi);\n       invert = true;\n    }\n\n    T result;\n\n    if(phi >= tools::max_value<T>())\n    {\n       // Need to handle infinity as a special case:\n       result = policies::raise_overflow_error<T>(function, 0, pol);\n       BOOST_MATH_INSTRUMENT_VARIABLE(result);\n    }\n    else if(phi > 1 / tools::epsilon<T>())\n    {\n       // Phi is so large that phi%pi is necessarily zero (or garbage),\n       // just return the second part of the duplication formula:\n       result = 2 * phi * ellint_k_imp(k, pol) / constants::pi<T>();\n       BOOST_MATH_INSTRUMENT_VARIABLE(result);\n    }\n    else\n    {\n       // Carlson's algorithm works only for |phi| <= pi/2,\n       // use the integrand's periodicity to normalize phi\n       //\n       // Xiaogang's original code used a cast to long long here\n       // but that fails if T has more digits than a long long,\n       // so rewritten to use fmod instead:\n       //\n       BOOST_MATH_INSTRUMENT_CODE(\"pi/2 = \" << constants::pi<T>() / 2);\n       T rphi = boost::math::tools::fmod_workaround(phi, constants::pi<T>() / 2);\n       BOOST_MATH_INSTRUMENT_VARIABLE(rphi);\n       T m = 2 * (phi - rphi) / constants::pi<T>();\n       BOOST_MATH_INSTRUMENT_VARIABLE(m);\n       int s = 1;\n       if(boost::math::tools::fmod_workaround(m, T(2)) > 0.5)\n       {\n          m += 1;\n          s = -1;\n          rphi = constants::pi<T>() / 2 - rphi;\n          BOOST_MATH_INSTRUMENT_VARIABLE(rphi);\n       }\n       T sinp = sin(rphi);\n       T cosp = cos(rphi);\n       BOOST_MATH_INSTRUMENT_VARIABLE(sinp);\n       BOOST_MATH_INSTRUMENT_VARIABLE(cosp);\n       result = s * sinp * ellint_rf_imp(cosp * cosp, 1 - k * k * sinp * sinp, T(1), pol);\n       BOOST_MATH_INSTRUMENT_VARIABLE(result);\n       if(m != 0)\n       {\n          result += m * ellint_k_imp(k, pol);\n          BOOST_MATH_INSTRUMENT_VARIABLE(result);\n       }\n    }\n    return invert ? -result : result;\n}\n\n// Complete elliptic integral (Legendre form) of the first kind\ntemplate <typename T, typename Policy>\nT ellint_k_imp(T k, const Policy& pol)\n{\n    BOOST_MATH_STD_USING\n    using namespace boost::math::tools;\n\n    static const char* function = \"boost::math::ellint_k<%1%>(%1%)\";\n\n    if (abs(k) > 1)\n    {\n       return policies::raise_domain_error<T>(function,\n            \"Got k = %1%, function requires |k| <= 1\", k, pol);\n    }\n    if (abs(k) == 1)\n    {\n       return policies::raise_overflow_error<T>(function, 0, pol);\n    }\n\n    T x = 0;\n    T y = 1 - k * k;\n    T z = 1;\n    T value = ellint_rf_imp(x, y, z, pol);\n\n    return value;\n}\n\ntemplate <typename T, typename Policy>\ninline typename tools::promote_args<T>::type ellint_1(T k, const Policy& pol, const mpl::true_&)\n{\n   typedef typename tools::promote_args<T>::type result_type;\n   typedef typename policies::evaluation<result_type, Policy>::type value_type;\n   return policies::checked_narrowing_cast<result_type, Policy>(detail::ellint_k_imp(static_cast<value_type>(k), pol), \"boost::math::ellint_1<%1%>(%1%)\");\n}\n\ntemplate <class T1, class T2>\ninline typename tools::promote_args<T1, T2>::type ellint_1(T1 k, T2 phi, const mpl::false_&)\n{\n   return boost::math::ellint_1(k, phi, policies::policy<>());\n}\n\n}\n\n// Complete elliptic integral (Legendre form) of the first kind\ntemplate <typename T>\ninline typename tools::promote_args<T>::type ellint_1(T k)\n{\n   return ellint_1(k, policies::policy<>());\n}\n\n// Elliptic integral (Legendre form) of the first kind\ntemplate <class T1, class T2, class Policy>\ninline typename tools::promote_args<T1, T2>::type ellint_1(T1 k, T2 phi, const Policy& pol)\n{\n   typedef typename tools::promote_args<T1, T2>::type result_type;\n   typedef typename policies::evaluation<result_type, Policy>::type value_type;\n   return policies::checked_narrowing_cast<result_type, Policy>(detail::ellint_f_imp(static_cast<value_type>(phi), static_cast<value_type>(k), pol), \"boost::math::ellint_1<%1%>(%1%,%1%)\");\n}\n\ntemplate <class T1, class T2>\ninline typename tools::promote_args<T1, T2>::type ellint_1(T1 k, T2 phi)\n{\n   typedef typename policies::is_policy<T2>::type tag_type;\n   return detail::ellint_1(k, phi, tag_type());\n}\n\n}} // namespaces\n\n#endif // BOOST_MATH_ELLINT_1_HPP\n", "meta": {"hexsha": "8b10cf044c9111b90660cdea368d07d8ca625195", "size": 6054, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "vegastrike/boost/1_35/boost/math/special_functions/ellint_1.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/special_functions/ellint_1.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/special_functions/ellint_1.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": 33.0819672131, "max_line_length": 188, "alphanum_fraction": 0.6625371655, "num_tokens": 1689, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.6723317123102956, "lm_q1q2_score": 0.4915138659694421}}
{"text": "//==================================================================================================\n/*!\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#include <boost/simd/function/scalar/sinhcosh.hpp>\n#include <scalar_test.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/minf.hpp>\n#include <boost/simd/constant/nan.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/mone.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/constant/mzero.hpp>\n#include <boost/simd/function/cosh.hpp>\n#include <boost/simd/function/sinh.hpp>\n\nSTF_CASE_TPL(\"sinhcosh\", STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::sinhcosh;\n\n  T a[] = {bs::Zero<T>(), bs::One<T>(), T(5), T(-5)};\n  size_t N =  sizeof(a)/sizeof(T);\n  STF_EXPR_IS( (sinhcosh(T()))\n                  , (std::pair<T,T>)\n                  );\n\n  {\n    for(size_t i=0; i < N; ++i)\n    {\n      std::pair<T,T> p = sinhcosh(a[i]);\n      STF_ULP_EQUAL(p.first,  bs::sinh(a[i]), 1);\n      STF_ULP_EQUAL(p.second, bs::cosh(a[i]), 1);\n    }\n  }\n\n  T b[] = {bs::Inf<T>(), bs::Minf<T>(), bs::Nan<T>()};\n  N =  sizeof(b)/sizeof(T);\n#ifndef BOOST_SIMD_NO_INVALIDS\n\n  {\n    for(size_t i=0; i < N; ++i)\n    {\n      std::pair<T,T> p = sinhcosh(b[i]);\n      STF_ULP_EQUAL(p.first,  bs::sinh(b[i]), 1);\n      STF_ULP_EQUAL(p.second, bs::cosh(b[i]), 1);\n    }\n  }\n#endif\n}\n", "meta": {"hexsha": "99bfbcbc4ea384febbf7c9720ae9bb853db9a009", "size": 1640, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/scalar/sinhcosh.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": "test/function/scalar/sinhcosh.cpp", "max_issues_repo_name": "remymuller/boost.simd", "max_issues_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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/function/scalar/sinhcosh.cpp", "max_forks_repo_name": "remymuller/boost.simd", "max_forks_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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": 28.7719298246, "max_line_length": 100, "alphanum_fraction": 0.5402439024, "num_tokens": 469, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585903489891, "lm_q2_score": 0.6723316991792861, "lm_q1q2_score": 0.49151386424894955}}
{"text": "/*\n * PolygonTest.cpp\n *\n *  Created on: Mar 24, 2015\n *      Author: Martin Wermelinger, P\u00e9ter Fankhauser\n *\t Institute: ETH Zurich, ANYbotics\n */\n\n#include \"grid_map_core/Polygon.hpp\"\n\n// gtest\n#include <gtest/gtest.h>\n\n// Eigen\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\nusing namespace std;\nusing namespace Eigen;\nusing namespace grid_map;\n\nTEST(Polygon, getCentroidTriangle)\n{\n  Polygon triangle;\n  triangle.addVertex(Vector2d(0.0, 0.0));\n  triangle.addVertex(Vector2d(1.0, 0.0));\n  triangle.addVertex(Vector2d(0.5, 1.0));\n\n  Position expectedCentroid;\n  expectedCentroid.x() = 1.0 / 3.0 * (1.0 + 0.5);\n  expectedCentroid.y() = 1.0 / 3.0;\n  Position centroid = triangle.getCentroid();\n  EXPECT_DOUBLE_EQ(expectedCentroid.x(), centroid.x());\n  EXPECT_DOUBLE_EQ(expectedCentroid.y(), centroid.y());\n}\n\nTEST(Polygon, getCentroidRectangle)\n{\n  Polygon rectangle;\n  rectangle.addVertex(Vector2d(-2.0, -1.0));\n  rectangle.addVertex(Vector2d(-2.0, 2.0));\n  rectangle.addVertex(Vector2d(1.0, 2.0));\n  rectangle.addVertex(Vector2d(1.0, -1.0));\n\n  Position expectedCentroid(-0.5, 0.5);\n  Position centroid = rectangle.getCentroid();\n  EXPECT_DOUBLE_EQ(expectedCentroid.x(), centroid.x());\n  EXPECT_DOUBLE_EQ(expectedCentroid.y(), centroid.y());\n}\n\nTEST(Polygon, getBoundingBox)\n{\n  Polygon triangle;\n  triangle.addVertex(Vector2d(0.0, 0.0));\n  triangle.addVertex(Vector2d(0.5, -1.2));\n  triangle.addVertex(Vector2d(1.0, 0.0));\n\n  Position expectedCenter(0.5, -0.6);\n  Length expectedLength(1.0, 1.2);\n  Position center;\n  Length length;\n  triangle.getBoundingBox(center, length);\n\n  EXPECT_DOUBLE_EQ(expectedCenter.x(), center.x());\n  EXPECT_DOUBLE_EQ(expectedCenter.y(), center.y());\n  EXPECT_DOUBLE_EQ(expectedLength.x(), length.x());\n  EXPECT_DOUBLE_EQ(expectedLength.y(), length.y());\n}\n\nTEST(Polygon, convexHullPolygon)\n{\n  Polygon polygon1;\n  polygon1.addVertex(Vector2d(0.0, 0.0));\n  polygon1.addVertex(Vector2d(1.0, 1.0));\n  polygon1.addVertex(Vector2d(0.0, 1.0));\n  polygon1.addVertex(Vector2d(1.0, 0.0));\n\n  Polygon polygon2;\n  polygon2.addVertex(Vector2d(0.5, 0.5));\n  polygon2.addVertex(Vector2d(0.5, 1.5));\n  polygon2.addVertex(Vector2d(1.5, 0.5));\n  polygon2.addVertex(Vector2d(1.5, 1.5));\n\n  Polygon hull = Polygon::convexHull(polygon1, polygon2);\n\n  EXPECT_EQ(6, hull.nVertices());\n  EXPECT_TRUE(hull.isInside(Vector2d(0.5, 0.5)));\n  EXPECT_FALSE(hull.isInside(Vector2d(0.01, 1.49)));\n}\n\nTEST(Polygon, convexHullCircles)\n{\n  Position center1(0.0, 0.0);\n  Position center2(1.0, 0.0);\n  double radius = 0.5;\n  const int nVertices = 15;\n\n  Polygon hull = Polygon::convexHullOfTwoCircles(center1, center2, radius);\n  EXPECT_EQ(20, hull.nVertices());\n  EXPECT_TRUE(hull.isInside(Vector2d(-0.25, 0.0)));\n  EXPECT_TRUE(hull.isInside(Vector2d(0.5, 0.0)));\n  EXPECT_TRUE(hull.isInside(Vector2d(0.5, 0.4)));\n  EXPECT_FALSE(hull.isInside(Vector2d(0.5, 0.6)));\n  EXPECT_FALSE(hull.isInside(Vector2d(1.5, 0.2)));\n\n  hull = Polygon::convexHullOfTwoCircles(center1, center2, radius, nVertices);\n  EXPECT_EQ(nVertices + 1, hull.nVertices());\n  EXPECT_TRUE(hull.isInside(Vector2d(-0.25, 0.0)));\n  EXPECT_TRUE(hull.isInside(Vector2d(0.5, 0.0)));\n  EXPECT_TRUE(hull.isInside(Vector2d(0.5, 0.4)));\n  EXPECT_FALSE(hull.isInside(Vector2d(0.5, 0.6)));\n  EXPECT_FALSE(hull.isInside(Vector2d(1.5, 0.2)));\n\n  hull = Polygon::convexHullOfTwoCircles(center1, center1, radius);\n  EXPECT_EQ(20, hull.nVertices());\n  EXPECT_TRUE(hull.isInside(Vector2d(-0.25, 0.0)));\n  EXPECT_TRUE(hull.isInside(Vector2d(0.25, 0.0)));\n  EXPECT_TRUE(hull.isInside(Vector2d(0.0, 0.25)));\n  EXPECT_TRUE(hull.isInside(Vector2d(0.0, -0.25)));\n  EXPECT_FALSE(hull.isInside(Vector2d(0.5, 0.5)));\n  EXPECT_FALSE(hull.isInside(Vector2d(0.6, 0.0)));\n  EXPECT_FALSE(hull.isInside(Vector2d(-0.6, 0.0)));\n  EXPECT_FALSE(hull.isInside(Vector2d(0.0, 0.6)));\n  EXPECT_FALSE(hull.isInside(Vector2d(0.0, -0.6)));\n\n  hull = Polygon::convexHullOfTwoCircles(center1, center1, radius, nVertices);\n  EXPECT_EQ(nVertices, hull.nVertices());\n  EXPECT_TRUE(hull.isInside(Vector2d(-0.25, 0.0)));\n  EXPECT_TRUE(hull.isInside(Vector2d(0.25, 0.0)));\n  EXPECT_TRUE(hull.isInside(Vector2d(0.0, 0.25)));\n  EXPECT_TRUE(hull.isInside(Vector2d(0.0, -0.25)));\n  EXPECT_FALSE(hull.isInside(Vector2d(0.5, 0.5)));\n  EXPECT_FALSE(hull.isInside(Vector2d(0.6, 0.0)));\n  EXPECT_FALSE(hull.isInside(Vector2d(-0.6, 0.0)));\n  EXPECT_FALSE(hull.isInside(Vector2d(0.0, 0.6)));\n  EXPECT_FALSE(hull.isInside(Vector2d(0.0, -0.6)));\n}\n\nTEST(Polygon, convexHullCircle)\n{\n  Position center(0.0, 0.0);\n  double radius = 0.5;\n  const int nVertices = 15;\n\n  Polygon hull = Polygon::fromCircle(center, radius);\n\n  EXPECT_EQ(20, hull.nVertices());\n  EXPECT_TRUE(hull.isInside(Vector2d(-0.25, 0.0)));\n  EXPECT_TRUE(hull.isInside(Vector2d(0.49, 0.0)));\n  EXPECT_FALSE(hull.isInside(Vector2d(0.5, 0.4)));\n  EXPECT_FALSE(hull.isInside(Vector2d(1.0, 0.0)));\n\n  hull = Polygon::fromCircle(center, radius, nVertices);\n  EXPECT_EQ(nVertices, hull.nVertices());\n  EXPECT_TRUE(hull.isInside(Vector2d(-0.25, 0.0)));\n  EXPECT_TRUE(hull.isInside(Vector2d(0.49, 0.0)));\n  EXPECT_FALSE(hull.isInside(Vector2d(0.5, 0.4)));\n  EXPECT_FALSE(hull.isInside(Vector2d(1.0, 0.0)));\n}\n\nTEST(convertToInequalityConstraints, triangle1)\n{\n  Polygon polygon({Position(1.0, 1.0), Position(0.0, 0.0), Position(1.1, -1.1)});\n  MatrixXd A;\n  VectorXd b;\n  ASSERT_TRUE(polygon.convertToInequalityConstraints(A, b));\n  EXPECT_NEAR(-1.3636, A(0, 0), 1e-4);\n  EXPECT_NEAR( 1.3636, A(0, 1), 1e-4);\n  EXPECT_NEAR(-1.5000, A(1, 0), 1e-4);\n  EXPECT_NEAR(-1.5000, A(1, 1), 1e-4);\n  EXPECT_NEAR( 2.8636, A(2, 0), 1e-4);\n  EXPECT_NEAR( 0.1364, A(2, 1), 1e-4);\n  EXPECT_NEAR( 0.0000, b(0), 1e-4);\n  EXPECT_NEAR( 0.0000, b(1), 1e-4);\n  EXPECT_NEAR( 3.0000, b(2), 1e-4);\n}\n\nTEST(convertToInequalityConstraints, triangle2)\n{\n  Polygon polygon({Position(-1.0, 0.5), Position(-1.0, -0.5), Position(1.0, -0.5)});\n  MatrixXd A;\n  VectorXd b;\n  ASSERT_TRUE(polygon.convertToInequalityConstraints(A, b));\n  EXPECT_NEAR(-1.5000, A(0, 0), 1e-4);\n  EXPECT_NEAR( 0.0000, A(0, 1), 1e-4);\n  EXPECT_NEAR( 0.0000, A(1, 0), 1e-4);\n  EXPECT_NEAR(-3.0000, A(1, 1), 1e-4);\n  EXPECT_NEAR( 1.5000, A(2, 0), 1e-4);\n  EXPECT_NEAR( 3.0000, A(2, 1), 1e-4);\n  EXPECT_NEAR( 1.5000, b(0), 1e-4);\n  EXPECT_NEAR( 1.5000, b(1), 1e-4);\n  EXPECT_NEAR( 0.0000, b(2), 1e-4);\n}\n\nTEST(offsetInward, triangle)\n{\n  Polygon polygon({Position(1.0, 1.0), Position(0.0, 0.0), Position(1.0, -1.0)});\n  polygon.offsetInward(0.1);\n  EXPECT_NEAR(0.9, polygon.getVertex(0)(0), 1e-4);\n  EXPECT_NEAR(0.758579, polygon.getVertex(0)(1), 1e-4);\n  EXPECT_NEAR(0.141421, polygon.getVertex(1)(0), 1e-4);\n  EXPECT_NEAR(0.0, polygon.getVertex(1)(1), 1e-4);\n  EXPECT_NEAR(0.9, polygon.getVertex(2)(0), 1e-4);\n  EXPECT_NEAR(-0.758579, polygon.getVertex(2)(1), 1e-4);\n}\n\nTEST(triangulation, triangle)\n{\n  Polygon polygon({Position(1.0, 1.0), Position(0.0, 0.0), Position(1.0, -1.0)});\n  std::vector<Polygon> polygons;\n  polygons = polygon.triangulate();\n  ASSERT_EQ(1, polygons.size());\n  EXPECT_EQ(polygon.getVertex(0).x(), polygons[0].getVertex(0).x());\n  EXPECT_EQ(polygon.getVertex(0).y(), polygons[0].getVertex(0).y());\n  EXPECT_EQ(polygon.getVertex(1).x(), polygons[0].getVertex(1).x());\n  EXPECT_EQ(polygon.getVertex(1).y(), polygons[0].getVertex(1).y());\n  EXPECT_EQ(polygon.getVertex(2).x(), polygons[0].getVertex(2).x());\n  EXPECT_EQ(polygon.getVertex(2).y(), polygons[0].getVertex(2).y());\n}\n\nTEST(triangulation, rectangle)\n{\n  Polygon rectangle;\n  rectangle.addVertex(Vector2d(-2.0, -1.0));\n  rectangle.addVertex(Vector2d(-2.0, 2.0));\n  rectangle.addVertex(Vector2d(1.0, 2.0));\n  rectangle.addVertex(Vector2d(1.0, -1.0));\n  std::vector<Polygon> polygons;\n  polygons = rectangle.triangulate();\n  ASSERT_EQ(2, polygons.size());\n  // TODO Extend.\n}\n", "meta": {"hexsha": "1110d4d9f8c80461ad0485cd96d6b148060a1d82", "size": 7756, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "grid_map_core/test/PolygonTest.cpp", "max_stars_repo_name": "jcmayoral/grid_map", "max_stars_repo_head_hexsha": "c4a16b71d40c2c6df8d60b1c91cd78616f9db672", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-09-11T02:32:16.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-28T10:59:20.000Z", "max_issues_repo_path": "grid_map_core/test/PolygonTest.cpp", "max_issues_repo_name": "jcmayoral/grid_map", "max_issues_repo_head_hexsha": "c4a16b71d40c2c6df8d60b1c91cd78616f9db672", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "grid_map_core/test/PolygonTest.cpp", "max_forks_repo_name": "jcmayoral/grid_map", "max_forks_repo_head_hexsha": "c4a16b71d40c2c6df8d60b1c91cd78616f9db672", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-07-05T17:48:18.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-11T07:55:44.000Z", "avg_line_length": 33.2875536481, "max_line_length": 84, "alphanum_fraction": 0.6905621454, "num_tokens": 2809, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585903489892, "lm_q2_score": 0.6723316860482763, "lm_q1q2_score": 0.49151385464941205}}
{"text": "// Copyright (C) 2021 Icey Chiu\n// Using to translate the camera reference system to the arbitray one.\n\n#include <iostream>\n#include <opencv2/opencv.hpp>\n#include <Eigen/Core>\n\n#include <dirent.h>\n#include <sys/types.h>\n\n#include <opencv2/opencv.hpp>\n#include <boost/foreach.hpp>\n#define foreach BOOST_FOREACH \n\nclass Calibration\n{\npublic:\n    Calibration ( const std::string& setting_dir ) {\n        /* load parameters */\n        cv::FileStorage fs ( setting_dir, cv::FileStorage::READ );\n\n        // camera params                                                                                                                                                                                     \n        fx = fs[\"camera.fx\"];\n        fy = fs[\"camera.fy\"];\n        cx = fs[\"camera.cx\"];\n        cy = fs[\"camera.cy\"];\n\n        k1 = fs[\"camera.k1\"];\n        k2 = fs[\"camera.k2\"];\n        p1 = fs[\"camera.p1\"];\n        p2 = fs[\"camera.p2\"];\n        k3 = fs[\"camera.k3\"];\n\n        K = ( cv::Mat_<float> ( 3, 3 ) << fx, 0.0, cx, 0.0, fy, cy, 0.0, 0.0, 1.0 );\n        dist = ( cv::Mat_<float> ( 1, 5 ) << k1, k2, p1, p2, k3 );\n        eK << fx, 0.0, cx, 0.0, fy, cy, 0.0, 0.0, 1.0;\n\n        // target params\n        target_cols = fs[\"target.cols\"];\n        target_rows = fs[\"target.rows\"];\n        target_col_grid_size = fs[\"target.col_grid_size\"];\n        target_row_grid_size = fs[\"target.row_grid_size\"];\n        target_offset = fs[\"target.offset\"];\n    }\n\n    bool calibrate ( cv::Mat& image ) {\n        /* process the img with one time calibration */\n\n        // extract corners\n        std::vector<cv::Point2f> corners, undist_corners;\n        bool found = cv::findChessboardCorners ( image, cv::Size ( 3, 7 ), corners );\n\n        if ( found ) {\n\n            // refine corners\n            cv::cornerSubPix ( image, corners, cv::Size ( 11, 8 ), cv::Size ( 6 , 3 ),\n                               cv::TermCriteria ( cv::TermCriteria::EPS + cv::TermCriteria::COUNT, 30, 0.1 ) );\n\n            // show corners\n            cv::drawChessboardCorners ( image, cv::Size ( target_cols, target_rows ), corners, found );\n            cv::resize ( image, image, cv::Size ( image.cols / 4,  image.rows/4 ) );\n            cv::imshow ( \"detect corners\", image );\n            cv::waitKey ( 1 );\n\n            // undistort\n            cv::undistortPoints ( corners, undist_corners, K, dist, cv::Mat(), K );\n        }// if found target\n        else {\n            return false;\n        }\n\n        // get Tct, translation between camera and the target\n        // get 3d mappoints refer to the target coordinate\n        std::vector<cv::Point3f> pts;\n        for ( int i = 0; i < target_rows; ++i )\n            for ( int j = 0; j < target_cols; ++j ) {\n// \t\t\t\tint yj = ( target_cols - j - 1);\n// \t\t\t\tpts.push_back ( cv::Point3f ( yj*target_col_grid_size, i*target_row_grid_size, 0 ) );\n\t\t\t\tpts.push_back ( cv::Point3f ( i*target_row_grid_size, j*target_col_grid_size, 0 ) );\n            }\n\n        cv::Vec3d rvec, tvec;\n        bool solve_ok =  cv::solvePnP ( pts, undist_corners, K, cv::Mat(), rvec, tvec );\n        if ( !solve_ok ) {\n            return false;\n        }\n\n        // convert to homo T\n        Eigen::Matrix3d R;\n        cv::Mat cvR;\n        cv::Rodrigues ( rvec, cvR );\n        R <<  cvR.at<double> ( 0, 0 ), cvR.at<double> ( 0, 1 ), cvR.at<double> ( 0, 2 ),\n          cvR.at<double> ( 1, 0 ), cvR.at<double> ( 1, 1 ), cvR.at<double> ( 1, 2 ),\n          cvR.at<double> ( 2, 0 ), cvR.at<double> ( 2, 1 ), cvR.at<double> ( 2, 2 );\n\n        Eigen::Vector3d t;\n        t << tvec[0], tvec[1], tvec[2];\n\n        Eigen::Vector3d r1 = R.block ( 0, 0, 3, 1 );\n        Eigen::Vector3d r2 = R.block ( 0, 1, 3, 1 );\n\n        Eigen::Vector3d tb;\n        tb << 0.0, 0.0, target_offset;\n\n        Eigen::Matrix3d RT;\n        RT.block ( 0,0, 3, 1 ) = r1;\n        RT.block ( 0,1, 3, 1 ) = r2;\n        RT.block ( 0,2, 3, 1 ) = R * tb + t;\n\n        H = eK * RT; // homography\n        std::cout << std::endl << H << std::endl << std::endl << std::endl;\n        // Save result.\n        return true;\n    }\n\n    void saveResult ( const std::string& result_dir ) {\n        cv::FileStorage fs ( result_dir, cv::FileStorage::WRITE );\n\n        // Save homography Matrix\n        cv::Mat cvH = ( cv::Mat_<double> ( 3, 3 ) << H ( 0,0 ), H ( 0,1 ), H ( 0,2 ), H ( 1,0 ), H ( 1,1 ), H ( 1,2 ), H ( 2,0 ), H ( 2,1 ), H ( 2,2 ) );\n        fs << \"homograph_matrix\" << cvH;\n        fs.release();\n    }\n\nprivate:\n\n    float fx;\n    float fy;\n    float cx;\n    float cy;\n\n    float k1;\n    float k2;\n    float p1;\n    float p2;\n    float k3;\n    cv::Mat K;\n    cv::Mat dist;\n    Eigen::Matrix3d eK;\n\n    int target_cols;\n    int target_rows;\n    float target_col_grid_size;\n    float target_row_grid_size;\n    float target_offset;\n\n    Eigen::Matrix3d H;\n};// class Calbration\n\n\nint main ( int argc, char **argv )\n{\n    //if ( argc != 2 ) {\n    //    std::cout << \"Please input: setting file, homograph_matrix.yaml\\n\";\n    //    return -1;\n    //}\n\n    /* load parameters */\n    const std::string cfg_dir = \"/home/icey/workspace/Aruco/intrinsic_calibrationfile.yml\";\n    const std::string calibration_dir = \"/home/icey/workspace/Aruco/extrinsic_calibrationfile.yml\";\n    cv::Mat img = cv::imread(\"/home/icey/\u56fe\u7247/calibration/666.jpg\", 2 | 4);\n    // Init Calbration class.\n    Calibration calibration ( cfg_dir );\n\n    // Calibration.\n    calibration.calibrate ( img );\n    calibration.saveResult ( calibration_dir );\n            \n    cv::waitKey( 0 );\n\n    std::cout << \"Complete\" << std::endl;\n    return 0;\n}\n\n/*\ncv::Mat getRTMatrix ( const cv::Mat &R_,const cv::Mat &T_ ,int forceType ) {\n   cv::Mat M;\n   cv::Mat R,T;\n   R_.copyTo ( R );\n   T_.copyTo ( T );\n   if ( R.type() ==CV_64F ) {\n       assert ( T.type() ==CV_64F );\n       cv::Mat Matrix=cv::Mat::eye ( 4,4,CV_64FC1 );\n       cv::Mat R33=cv::Mat ( Matrix,cv::Rect ( 0,0,3,3 ) );\n       if ( R.total() ==3 ) {\n           cv::Rodrigues ( R,R33 );\n       } else if ( R.total() ==9 ) {\n           cv::Mat R64;\n           R.convertTo ( R64,CV_64F );\n           R.copyTo ( R33 );\n       }\n       for ( int i=0; i<3; i++ )\n           Matrix.at<double> ( i,3 ) =T.ptr<double> ( 0 ) [i];\n       M=Matrix;\n   } else if ( R.depth() ==CV_32F ) {\n       cv::Mat Matrix=cv::Mat::eye ( 4,4,CV_32FC1 );\n       cv::Mat R33=cv::Mat ( Matrix,cv::Rect ( 0,0,3,3 ) );\n       if ( R.total() ==3 ) {\n           cv::Rodrigues ( R,R33 );\n       } else if ( R.total() ==9 ) {\n           cv::Mat R32;\n           R.convertTo ( R32,CV_32F );\n           R.copyTo ( R33 );\n       }\n       for ( int i=0; i<3; i++ )\n           Matrix.at<float> ( i,3 ) =T.ptr<float> ( 0 ) [i];\n       M=Matrix;\n   }\n   if ( forceType==-1 ) return M;\n   else {\n       cv::Mat MTyped;\n       M.convertTo ( MTyped,forceType );\n       return MTyped;\n   }\n}\n*/\n", "meta": {"hexsha": "50fe4ea8b3bcd96f507b8ab0a55139bd59c9bfa6", "size": 6822, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "thirdparty/MVS/Samples/64/GrabImage/src/extrinsic_calibration.cpp", "max_stars_repo_name": "IceyChiu/Visual-Tracking-System", "max_stars_repo_head_hexsha": "d43b873a408d94a5c7191fcaeae5b94f8d6e4087", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-09T02:40:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-09T02:40:57.000Z", "max_issues_repo_path": "thirdparty/MVS/Samples/64/GrabImage/src/extrinsic_calibration.cpp", "max_issues_repo_name": "IceyChiu/Visual-Tracking-System", "max_issues_repo_head_hexsha": "d43b873a408d94a5c7191fcaeae5b94f8d6e4087", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thirdparty/MVS/Samples/64/GrabImage/src/extrinsic_calibration.cpp", "max_forks_repo_name": "IceyChiu/Visual-Tracking-System", "max_forks_repo_head_hexsha": "d43b873a408d94a5c7191fcaeae5b94f8d6e4087", "max_forks_repo_licenses": ["Apache-2.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.4377880184, "max_line_length": 205, "alphanum_fraction": 0.5051304603, "num_tokens": 2106, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.874077222043951, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4913856741926471}}
{"text": "#include <iostream>\n#include <Eigen/SparseCore>\n#include <Eigen/SparseLU>\n#include <Eigen/SparseCholesky>\n#include <Eigen/Dense>\n#include <chrono>\n\ntypedef Eigen::SparseMatrix<double> SpMat;\ntypedef Eigen::Matrix<double, Eigen::Dynamic, 1> VectorXd;\n\n#include \"mesh_reader_eigen.hpp\"\n#include \"constants_sparse.hpp\"\n#include \"newton_raphson_sparse.hpp\"\n\n// Compile command:\n// g++ -Wall -std=c++14 eigen_sparse.cpp -o sparse.o -I/usr/local/include/eigen3\n// Run command:\n// ./sparse.o filename T(in C) eta_u(in %) eta_v(in %) 0/1 (1 for quasi-newton, 0 for newton)\n\n// u = Cu = concentration O2, v = Cv = concentration CO2\n\n\nSpMat block(SpMat A,SpMat B,SpMat C, SpMat D)\n{\n  SpMat R(2*A.rows(),2*A.rows());\n  int n = A.rows();\n  for (int k=0; k<A.outerSize(); ++k)\n  {\n    for (SparseMatrix<double>::InnerIterator it(A,k); it; ++it)\n    {\n      R.insert(it.row(),it.col())  = it.value();\n    }\n  }\n  for (int k=0; k<B.outerSize(); ++k)\n  {\n    for (SparseMatrix<double>::InnerIterator it(B,k); it; ++it)\n    {\n      R.insert(it.row(),n+it.col())  = it.value();\n    }\n  }\n  for (int k=0; k<C.outerSize(); ++k)\n  {\n    for (SparseMatrix<double>::InnerIterator it(C,k); it; ++it)\n    {\n      R.insert(n+it.row(),it.col())  = it.value();\n    }\n  }\n  for (int k=0; k<D.outerSize(); ++k)\n  {\n    for (SparseMatrix<double>::InnerIterator it(D,k); it; ++it)\n    {\n      R.insert(n+it.row(),n+it.col())  = it.value();\n    }\n  }\n  return R;\n}\n\nclass F\n{\n  /* Returns tuple containing two functors, one for the original expression and one for the Jacobian. */\n\n  private:\n    SpMat& Au_;\n    SpMat& Av_;\n    SpMat& B_;\n    SpMat& C_;\n    SpMat& D_;\n\n  public:\n    F(SpMat& Au, SpMat& Av,SpMat& B,SpMat& C,SpMat& D)\n    :Au_(Au), Av_(Av),B_(B), C_(C),D_(D)\n    {\n    }\n\n    VectorXd operator()(VectorXd& x)\n    {\n      int n = Au_.rows();\n      VectorXd u = x.head(n).sparseView();\n      VectorXd v = x.tail(n).sparseView();\n      VectorXd func(2*n);\n      VectorXd f1 = Au_*u + B_*Ru(u,v) + hu*(C_*u - D_*uamb);\n      VectorXd f2 = Av_*v - B_*Rv(u,v) + hv*(C_*v - D_*vamb);\n      func << f1,f2;\n      return func;\n    }\n};\n\n\nclass J\n{\n  /* Returns tuple containing two functors, one for the original expression and one for the Jacobian. */\n\n  private:\n    SpMat& Au_;\n    SpMat& Av_;\n    SpMat& B_;\n    SpMat& C_;\n    SpMat& D_;\n  public:\n    J(SpMat& Au, SpMat& Av,SpMat& B,SpMat& C,SpMat& D)\n    :Au_(Au), Av_(Av),B_(B), C_(C),D_(D)\n    {\n    }\n\n    SpMat operator()(VectorXd& x)\n    {\n      int n = Au_.rows();\n      VectorXd u = x.head(n);\n      VectorXd v = x.tail(n);\n      SpMat func(2*n,2*n);\n      func = block(Au_ + B_*dRudu(u,v)+hu*C_,B_*dRudv(u,v),-B_*dRvdu(u,v),Av_ - (B_*dRvdv(u,v)) + hv*C_);\n      return func;\n    }\n};\n\n\nint main(int argc, char *argv[])\n{\n  std::cout << std::endl;\n  std::cout << \"Setting constants ...\" << std::endl;\n  int quasi = atoi(argv[5]);\n  setConstants(atof(argv[2])+273.15,atof(argv[3])/100,atof(argv[4])/100);\n\n  auto t1 = std::chrono::high_resolution_clock::now();\n  std::string file_name = argv[1];\n  std::string location = \"../mesh/\"+ file_name +\".1\";\n  MatrixXd vertices = mesh::read_vertices(location+\".node\");\n  MatrixXd triangles = mesh::read_triangles(vertices,location+\".ele\");\n  MatrixXi boundaries = mesh::read_boundaries(vertices,location+\".poly\");\n  auto t2 = std::chrono::high_resolution_clock::now();\n\n  std::cout << std::endl;\n  std::cout << \"Input data successfully read:\" << std::endl;\n  std::cout << \"This took: \"\n            << std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1).count()\n            << \" milliseconds\" << std::endl;\n  std::cout << \"Number of vertices :\" << vertices.rows() << std::endl;\n  std::cout << \"Number of triangles:\" << triangles.rows() <<std::endl;\n  t1 = std::chrono::high_resolution_clock::now();\n\n  /* Calculate coefficient matrix B related to the respiration kinetics,\n  part of right hand side in system of nonlinear equations */\n\n  SpMat B_init(vertices.rows(), vertices.rows());\n  for (unsigned t = 0; t < triangles.rows(); ++t)\n  {\n    int a = triangles(t, 0);\n    int b = triangles(t, 1);\n    int c = triangles(t, 2);\n    double area = triangles(t, 3);\n    B_init.coeffRef(a, a) += area*(6.*vertices(a, 0) + 2.*vertices(b, 0) + 2.*vertices(c, 0));\n    B_init.coeffRef(std::min(a,b),std::max(a,b)) += area*(2.*vertices(a, 0) + 2.*vertices(b, 0) + vertices(c, 0));\n    B_init.coeffRef(std::min(c, a),std::max(c, a)) += area*(2.*vertices(a, 0) + vertices(b, 0) + 2.*vertices(c, 0));\n    B_init.coeffRef(b, b) += area*(2.*vertices(a, 0) + 6.*vertices(b, 0) + 2.*vertices(c, 0));\n    B_init.coeffRef(std::min(b, c),std::max(b, c)) += area*(vertices(a, 0) + 2.*vertices(b, 0) + 2.*vertices(c, 0));\n    B_init.coeffRef(c, c) += area*(2.*vertices(a, 0) + 2.*vertices(b, 0) + 6.*vertices(c, 0));\n  }\n  B_init *= (1./60.);\n  SpMat B = B_init.selfadjointView<Eigen::Upper>();\n  t2 = std::chrono::high_resolution_clock::now();\n  std::cout << std::endl;\n  std::cout << \"B matrix successfully assembled\" << std::endl;\n  std::cout << \"This took: \"\n            << std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1).count()\n            << \" milliseconds\" << std::endl;\n\n  /* Calculate the first part of the stiffness matrix in the lefthand\n  side of the the nonlinear system, A */\n\n  t1 = std::chrono::high_resolution_clock::now();\n  SpMat A_U_init(vertices.rows(), vertices.rows());\n  SpMat A_V_init(vertices.rows(), vertices.rows());\n  Eigen::Matrix<double,3,2> G;\n  Eigen::Matrix<double,3,3> GGT_U;\n  Eigen::Matrix<double,3,3> GGT_V;\n  Eigen::Matrix<double,2,2> I_U;\n  Eigen::Matrix<double,2,2> I_V;\n  I_U(0,0) = DU_R;\n  I_U(1,0) = 0;\n  I_U(0,1) = 0;\n  I_U(1,1) = DU_Z;\n  I_V(0,0) = DV_R;\n  I_V(1,1) = DV_Z;\n  I_V(1,0) = 0;\n  I_V(0,1) = 0;\n  for (unsigned t = 0; t < triangles.rows(); ++t)\n  {\n    int a = triangles(t, 0);\n    int b = triangles(t, 1);\n    int c = triangles(t, 2);\n    double area = triangles(t, 3);\n    G(0, 0) = (vertices(b, 1) - vertices(c, 1));\n    G(1, 0) = (vertices(c, 1) - vertices(a, 1));\n    G(2, 0) = (vertices(a, 1) - vertices(b, 1));\n    G(0, 1) = (vertices(c, 0) - vertices(b, 0));\n    G(1, 1) = (vertices(a, 0) - vertices(c, 0));\n    G(2, 1) = (vertices(b, 0) - vertices(a, 0));\n    GGT_U = (1/(2*area))*((vertices(a, 0)+vertices(b, 0)+vertices(c, 0))/6)*(G*I_U*G.transpose());\n    GGT_V = (1/(2*area))*((vertices(a, 0)+vertices(b, 0)+vertices(c, 0))/6)*(G*I_V*G.transpose());\n    #ifdef DEBUG\n    std::cout<<\"GGT_U\" << std::endl << GGT_U << std::endl;\n    std::cout<<\"GGT_V\" << std::endl << GGT_V << std::endl;\n    #endif\n    A_U_init.coeffRef(a, a) += GGT_U(0, 0);\n    A_U_init.coeffRef(std::min(b, a),std::max(b, a)) += GGT_U(1, 0);\n    A_U_init.coeffRef(std::min(c, a),std::max(c, a)) += GGT_U(2, 0);\n    A_U_init.coeffRef(b, b) += GGT_U(1, 1);\n    A_U_init.coeffRef(std::min(b, c),std::max(b,c)) += GGT_U(1, 2);\n    A_U_init.coeffRef(c, c) += GGT_U(2, 2);\n    A_V_init.coeffRef(a, a) += GGT_V(0, 0);\n    A_V_init.coeffRef(std::min(b, a),std::max(b, a)) += GGT_V(1, 0);\n    A_V_init.coeffRef(std::min(c, a),std::max(c, a)) += GGT_V(2, 0);\n    A_V_init.coeffRef(b, b) += GGT_V(1, 1);\n    A_V_init.coeffRef(std::min(b, c),std::max(b,c)) += GGT_V(1, 2);\n    A_V_init.coeffRef(c, c) += GGT_V(2, 2);\n  }\n  SpMat A_U = A_U_init.selfadjointView<Eigen::Upper>();\n  SpMat A_V = A_V_init.selfadjointView<Eigen::Upper>();\n  t2 = std::chrono::high_resolution_clock::now();\n  std::cout << std::endl;\n  std::cout << \"A matrices assembled.\" << std::endl;\n  std::cout << \"This took: \"\n            << std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1).count()\n            << \" milliseconds\" << std::endl;\n\n  /* Calculate the second part of the stiffness matrix (C) and the\n  second part of the righthand side (D) */\n\n  SpMat C(vertices.rows(), vertices.rows());\n  SpMat D(vertices.rows(),1);\n  for (unsigned b = 0; b < boundaries.rows(); ++b)\n  {\n    double len = sqrt(pow(vertices(boundaries(b, 0), 0) - vertices(boundaries(b, 1), 0), 2) +\n      pow(vertices(boundaries(b, 0), 1) - vertices(boundaries(b, 1), 1), 2));\n    C.coeffRef(boundaries(b, 0), boundaries(b, 0)) += len*(vertices(boundaries(b, 0), 0)/4 + vertices(boundaries(b, 1), 0)/12);\n    C.coeffRef(boundaries(b, 0), boundaries(b, 1)) += len*(vertices(boundaries(b, 0), 0)/12 + vertices(boundaries(b, 1), 0)/12);\n    C.coeffRef(boundaries(b, 1), boundaries(b, 0)) += len*(vertices(boundaries(b, 0), 0)/12 + vertices(boundaries(b, 1), 0)/12);\n    C.coeffRef(boundaries(b, 1), boundaries(b, 1)) += len*(vertices(boundaries(b, 0), 0)/12 + vertices(boundaries(b, 1), 0)/4);\n    D.coeffRef(boundaries(b,0),0) += len*(vertices(boundaries(b,0),0)/3.+vertices(boundaries(b,1),0)/6.);\n    D.coeffRef(boundaries(b,1),0) += len*(vertices(boundaries(b,0),0)/6.+vertices(boundaries(b,1),0)/3.);\n  }\n\n  t2 = std::chrono::high_resolution_clock::now();\n  std::cout << std::endl;\n  std::cout << \"C matrix and D vector assembled.\" << std::endl;\n  std::cout << \"This took: \"\n            << std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1).count()\n            << \" milliseconds\" << std::endl;\n\n  /* Solve linearized problem with ambient concentrations as input_field\n  to obtain starting concentration values, then solve the nonlinear\n  system with Newton-Raphson */\n\n  t1 = std::chrono::high_resolution_clock::now();\n\n  t1 = std::chrono::high_resolution_clock::now();\n  F F_funct(A_U, A_V, B, C, D);\n  J J_funct(A_U, A_V, B, C, D);\n  t2 = std::chrono::high_resolution_clock::now();\n  std::cout << std::endl;\n  std::cout << \"Functors are created\" << std::endl;\n  std::cout << \"This took: \"\n            << std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1).count()\n            << \" milliseconds\" << std::endl;\n  t1 = std::chrono::high_resolution_clock::now();\n  SparseLU<SpMat> solver;\n  VectorXd guess(vertices.rows()*2);\n  SpMat T1 = A_U+(Vmu/Kmu)*B+hu*C;\n  SpMat T2 = A_V+hv*C;\n\n  solver.analyzePattern(T1);\n  solver.factorize(T1);\n  VectorXd u_0 = solver.solve(hu*D*uamb);\n  solver.analyzePattern(T2);\n  solver.factorize(T2);\n  VectorXd v_0 = solver.solve(rq*(Vmu/Kmu)*B*u_0+hv*vamb*D);\n\n  guess << u_0,v_0;\n  t2 = std::chrono::high_resolution_clock::now();\n  std::cout << std::endl;\n  std::cout<< \"Initial guess calculated\" << std::endl;\n  std::cout << \"This took: \"\n            << std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1).count()\n            << \" milliseconds\" << std::endl;\n\n  #ifdef DEBUG\n  std::cout << \"A_U =\" << std::endl;\n  std::cout << MatrixXd(A_U) << std::endl;\n  std::cout << \"A_V =\" << std::endl;\n  std::cout << MatrixXd(A_V) << std::endl;\n  std::cout << \"B =\" << std::endl;\n  std::cout << MatrixXd(B) << std::endl;\n  std::cout << \"C =\" << std::endl;\n  std::cout << MatrixXd(C) << std::endl;\n  std::cout << \"D =\" << std::endl;\n  std::cout << MatrixXd(D) << std::endl;\n  std::cout << \"u_0\" << std::endl;\n  std::cout << u_0 << std::endl;\n  std::cout << \"v_0\" << std::endl;\n  std::cout << v_0 <<std::endl;\n  std::cout << \"Initial function value = \" << std::endl;\n  std::cout << F_funct(guess) <<std::endl;\n  std::cout << \"Initial Jacobian = \" << std::endl;\n  std::cout << J_funct(guess);\n  #endif\n\n  std::cout << std::endl;\n  std::cout<< \"Calculating nonlinear system solution ...\" << std::endl;\n  t1 = std::chrono::high_resolution_clock::now();\n  if (quasi==0)\n  {\n    newton_raphson(F_funct,J_funct,guess,pow(10,-17));\n  }\n  else\n  {\n    quasi_newton_raphson(F_funct,J_funct,guess,pow(10,-17));\n  }\n  t2 = std::chrono::high_resolution_clock::now();\n\n  std::cout<< \"Numerical solution nonlinear system calculated\" << std::endl;\n  std::cout << \"This took: \"\n            << std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1).count()\n            << \" milliseconds\" << std::endl;\n\n  /* Write out the result for python matplotlib code */\n\n  t1 = std::chrono::high_resolution_clock::now();\n  int n = vertices.rows();\n  VectorXd u = guess.head(n);\n  VectorXd v = guess.tail(n);\n  mesh::write_result(u,v);\n  t2 = std::chrono::high_resolution_clock::now();\n\n  std::cout << std::endl;\n  std::cout<< \"Results for u and v written out\" << std::endl;\n  std::cout << \"This took: \"\n            << std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1).count()\n            << \" milliseconds\" << std::endl;\n  std::cout << std::endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "1683404274ba5d6af42dcf5e7e616512da170c0c", "size": 12266, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/eigen_sparse.cpp", "max_stars_repo_name": "PieterAppeltans/ProjectWIT", "max_stars_repo_head_hexsha": "081e2537e2e9d9b92e50fdca2cb44039db5ffa59", "max_stars_repo_licenses": ["MIT"], "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/eigen_sparse.cpp", "max_issues_repo_name": "PieterAppeltans/ProjectWIT", "max_issues_repo_head_hexsha": "081e2537e2e9d9b92e50fdca2cb44039db5ffa59", "max_issues_repo_licenses": ["MIT"], "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/eigen_sparse.cpp", "max_forks_repo_name": "PieterAppeltans/ProjectWIT", "max_forks_repo_head_hexsha": "081e2537e2e9d9b92e50fdca2cb44039db5ffa59", "max_forks_repo_licenses": ["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.7609329446, "max_line_length": 128, "alphanum_fraction": 0.5983205609, "num_tokens": 4124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.49132931840215827}}
{"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/exercise.hpp>\n#include <ql/pricingengines/blackformula.hpp>\n#include <ql/experimental/models/fxoptionhelper.hpp>\n#include <ql/time/calendars/nullcalendar.hpp>\n\n#include <boost/make_shared.hpp>\n\nnamespace QuantLib {\n\nFxOptionHelper::FxOptionHelper(\n    const Period &maturity, const Calendar &calendar, const Real strike,\n    const Handle<Quote> fxSpot, const Handle<Quote> volatility,\n    const Handle<YieldTermStructure> &domesticYield,\n    const Handle<YieldTermStructure> &foreignYield,\n    CalibrationHelper::CalibrationErrorType errorType)\n    : CalibrationHelper(volatility, domesticYield, errorType),\n      hasMaturity_(true), maturity_(maturity), calendar_(calendar),\n      strike_(strike), fxSpot_(fxSpot), foreignYield_(foreignYield) {\n    registerWith(fxSpot_);\n    registerWith(foreignYield_);\n}\n\nFxOptionHelper::FxOptionHelper(\n    const Date &exerciseDate, const Real strike, const Handle<Quote> fxSpot,\n    const Handle<Quote> volatility,\n    const Handle<YieldTermStructure> &domesticYield,\n    const Handle<YieldTermStructure> &foreignYield,\n    CalibrationHelper::CalibrationErrorType errorType)\n    : CalibrationHelper(volatility, domesticYield, errorType),\n      hasMaturity_(false), exerciseDate_(exerciseDate), strike_(strike),\n      fxSpot_(fxSpot), foreignYield_(foreignYield) {\n    registerWith(fxSpot_);\n    registerWith(foreignYield_);\n}\n\nvoid FxOptionHelper::performCalculations() const {\n    if (hasMaturity_)\n        exerciseDate_ =\n            calendar_.advance(termStructure_->referenceDate(), maturity_);\n    tau_ = termStructure_->timeFromReference(exerciseDate_);\n    atm_ = fxSpot_->value() * foreignYield_->discount(tau_) /\n           termStructure_->discount(tau_);\n    effStrike_ = strike_;\n    if(effStrike_ == Null<Real>())\n        effStrike_ = atm_;\n    type_ = effStrike_ >= atm_ ? Option::Call : Option::Put;\n    boost::shared_ptr<StrikedTypePayoff> payoff(\n        new PlainVanillaPayoff(type_, effStrike_));\n    boost::shared_ptr<Exercise> exercise =\n        boost::make_shared<EuropeanExercise>(exerciseDate_);\n    option_ =\n        boost::shared_ptr<VanillaOption>(new VanillaOption(payoff, exercise));\n    CalibrationHelper::performCalculations();\n}\n\nReal FxOptionHelper::modelValue() const {\n    calculate();\n    option_->setPricingEngine(engine_);\n    return option_->NPV();\n}\n\nReal FxOptionHelper::blackPrice(Real volatility) const {\n    calculate();\n    const Real stdDev = volatility * std::sqrt(tau_);\n    return blackFormula(type_, strike_, atm_, stdDev, termStructure_->discount(tau_));\n}\n\n} // namespace QuantLib\n", "meta": {"hexsha": "732b53e783eb65d84debaeb1cf34c8d255339b43", "size": 3384, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ql/experimental/models/fxoptionhelper.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/fxoptionhelper.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/fxoptionhelper.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": 38.4545454545, "max_line_length": 86, "alphanum_fraction": 0.7399527187, "num_tokens": 809, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.49128434509783175}}
{"text": "#include <SBGATPolyhedronGravityModel.hpp>\n#include <SBGATPolyhedronGravityModelUQ.hpp>\n#include <SBGATObjWriter.hpp>\n\n#include <vtkCleanPolyData.h>\n#include <vtkOBJReader.h>\n\n#include <json.hpp>\n#include <boost/progress.hpp>\n\n#include <armadillo>\n\nint main(){\n\n\n\tstd::ifstream i(\"input_file.json\");\n\tnlohmann::json input_data;\n\ti >> input_data;\n\n\tarma::arma_rng::set_seed(0);\n\n\tstd::string PATH_SHAPE = input_data[\"PATH_SHAPE\"];\n\tdouble CORRELATION_DISTANCE =  input_data[\"CORRELATION_DISTANCE\"];\n\n\tdouble ERROR_STANDARD_DEV  = input_data[\"ERROR_STANDARD_DEV\"];\n\tdouble DENSITY  = input_data[\"DENSITY\"];\n\tdouble PERIOD_SD  = input_data[\"PERIOD_SD\"];\n\tdouble PERIOD  = input_data[\"PERIOD\"];\n\t\n\tbool UNIT_IN_METERS  = input_data[\"UNIT_IN_METERS\"];\n\tbool HOLD_MASS_CONSTANT  = input_data[\"HOLD_MASS_CONSTANT\"];\n\n\n\tint N_MONTE_CARLO = input_data[\"N_MONTE_CARLO\"];\n\tstd::vector<int> COV_REGION_CENTERS = input_data[\"COV_REGION_CENTERS\"];\n\n\tstd::string OUTPUT_DIR = input_data[\"OUTPUT_DIR\"];\n\tstd::string UNCERTAINTY_TYPE = input_data[\"UNCERTAINTY_TYPE\"];\n\n\tstd::vector<unsigned int > FACETS_TO_INVESTIGATE = input_data[\"FACETS_TO_INVESTIGATE\"];\n\n\n\tstd::cout << \"- Path to shape: \" << PATH_SHAPE << std::endl;\n\tstd::cout << \"- Uncertainty type: \" << UNCERTAINTY_TYPE << std::endl;\n\tstd::cout << \"- Standard deviation on point coordinates (m) : \" << ERROR_STANDARD_DEV << std::endl;\n\tstd::cout << \"- Correlation distance (m) : \" << CORRELATION_DISTANCE << std::endl;\n\tstd::cout << \"- Standard deviation on rotation period (s) : \" << PERIOD_SD << std::endl;\n\tstd::cout << \"- Density (kg/m^3) : \" << DENSITY << std::endl;\n\tstd::cout << \"- Rotation period (s) : \" << PERIOD << std::endl;\n\tstd::cout << \"- Covariance region centers:\\n\" ;\n\tfor(auto center : COV_REGION_CENTERS){\n\t\tstd::cout << \"\\t\" << center << std::endl;\n\t}\n\tstd::cout << \"- Facets to investigate:\\n\" ;\n\tfor(auto facet : FACETS_TO_INVESTIGATE){\n\t\tstd::cout << \"\\t\" << facet << std::endl;\n\t}\n\n\t// Reading\n\tvtkSmartPointer<vtkOBJReader> reader = vtkSmartPointer<vtkOBJReader>::New();\n\treader -> SetFileName(PATH_SHAPE.c_str());\n\treader -> Update(); \n\n\t// An instance of SBGATPolyhedronGravityModel is created to evaluate the PGM of \n\t// the considered polytdata\n\tvtkSmartPointer<SBGATPolyhedronGravityModel> pgm_filter = vtkSmartPointer<SBGATPolyhedronGravityModel>::New();\n\tpgm_filter -> SetInputConnection(reader -> GetOutputPort());\n\tpgm_filter -> SetDensity(DENSITY);\n\n\t\n\tif(UNIT_IN_METERS){\n\t\tpgm_filter -> SetScaleMeters();\n\t} else{\n\t\tpgm_filter -> SetScaleKiloMeters();\n\t}\n\n\tstd::cout << \"Building pgm ...\\n\";\n\tpgm_filter -> SetOmega(2 * arma::datum::pi / PERIOD * arma::vec({0,0,1}));\n\tpgm_filter -> Update();\n\n\t// An instance of SBGATPolyhedronGravityModelUQ is created to perform\n\t// uncertainty quantification from the PGM associated to the shape\n\tSBGATPolyhedronGravityModelUQ pgm_uq;\n\tpgm_uq.SetModel(pgm_filter);\n\tpgm_uq.SetPeriodErrorStandardDeviation(PERIOD_SD);\n\tpgm_uq.PrecomputeMassPropertiesPartials();\n\t\n\t// Saving baseline slices\n\tpgm_uq.TakeAndSaveSlice(0,OUTPUT_DIR + \"baseline_slice_x.txt\",0);\n\tpgm_uq.TakeAndSaveSlice(1,OUTPUT_DIR + \"baseline_slice_y.txt\",0);\n\tpgm_uq.TakeAndSaveSlice(2,OUTPUT_DIR + \"baseline_slice_z.txt\",0);\n\n\tstd::cout << \"Populating shape covariance ...\\n\";\n\n\t// Populate the shape vertices covariance\n\t\n\tif (UNCERTAINTY_TYPE == \"radial\"){\n\t\tfor (auto region_center : COV_REGION_CENTERS){\n\t\t\tpgm_uq.AddRadialUncertaintyRegionToCovariance(region_center,ERROR_STANDARD_DEV,CORRELATION_DISTANCE);\n\n\t\t}\n\t}\n\telse if (UNCERTAINTY_TYPE == \"normal\"){\n\t\tfor (auto region_center : COV_REGION_CENTERS){\n\n\t\t\tpgm_uq.AddRadialUncertaintyRegionToCovariance(region_center,ERROR_STANDARD_DEV,CORRELATION_DISTANCE);\n\n\t\t}\n\t}\n\telse if (UNCERTAINTY_TYPE == \"global\"){\n\t\tpgm_uq.ComputeVerticesCovarianceGlobal(ERROR_STANDARD_DEV,CORRELATION_DISTANCE);\n\t}\n\telse{\n\t\tthrow(std::runtime_error(\"Got unknown uncertainty direction type: \" + UNCERTAINTY_TYPE));\n\t}\n\n\n\tarma::mat P_CC = pgm_uq.GetVerticesCovariance();\n\tarma::mat C_CC = pgm_uq.GetCovarianceSquareRoot();\n\t\n\tP_CC.save(OUTPUT_DIR + \"full_covariance.txt\",arma::raw_ascii);\n\tC_CC.save(OUTPUT_DIR + \"full_covariance_sqrt.txt\",arma::raw_ascii);\n\n\t// Regularizing the covariance\n\tint regularized_eigen_values = pgm_uq.RegularizeCovariance();\n\n\tstd::cout << regularized_eigen_values << \" eigenvalues were regularized\\n\";\n\tC_CC = pgm_uq.GetCovarianceSquareRoot();\n\t\n\tP_CC = pgm_uq.GetVerticesCovariance();\n\tP_CC.save(OUTPUT_DIR + \"full_covariance_regularized.txt\",arma::raw_ascii);\n\tC_CC.save(OUTPUT_DIR + \"full_covariance_sqrt_regularized.txt\",arma::raw_ascii);\n\n\tregularized_eigen_values = pgm_uq.RegularizeCovariance();\n\n\tstd::cout << regularized_eigen_values << \" eigenvalues were regularized\\n\";\n\n\tstd::cout << \"Maximum absolute error in covariance square root: \" << arma::abs(P_CC - C_CC * C_CC.t()).max() << std::endl;\n\n\tstd::cout << \"Saving non-zero partition of shape covariance ...\\n\";\n\t\n\n\n\t// Analytical UQ\n\tstd::vector<double> analytical_variances_slopes;\n\n\tstd::cout << \"Computing analytical uncertainties ... \";\n\tauto start = std::chrono::system_clock::now();\n\n\tpgm_uq.GetVarianceSlopes(analytical_variances_slopes,FACETS_TO_INVESTIGATE,HOLD_MASS_CONSTANT);\n\n\tauto end = std::chrono::system_clock::now();\n\n\tstd::chrono::duration<double> elapsed_seconds = end-start;\n\tstd::cout << \"Done computing analytical uncertainties in \" << elapsed_seconds.count() << \" s\\n\";\n\n\t// Running a Monte Carlo to compare against\n\tstd::vector<arma::vec> deviations;\n\tstd::vector<double> period_errors;\n\tstd::vector<double> densities;\n\n\tstd::vector < std::vector<double> > all_slopes;\n\n\tstd::cout << \"Running MC ... \";\n\n\tstart = std::chrono::system_clock::now();\n\tSBGATPolyhedronGravityModelUQ::RunMCUQSlopes(PATH_SHAPE,\n\t\tDENSITY,\n\t\tpgm_filter -> GetOmega() ,\n\t\tUNIT_IN_METERS,\n\t\tHOLD_MASS_CONSTANT,\n\t\tC_CC,\n\t\tPERIOD_SD,\n\t\tN_MONTE_CARLO, \n\t\tFACETS_TO_INVESTIGATE,\n\t\tOUTPUT_DIR,\n\t\tstd::min(30,N_MONTE_CARLO),\n\t\tdeviations,\n\t\tdensities,\n\t\tperiod_errors,\n\t\tall_slopes);\n\n\n\tend = std::chrono::system_clock::now();\n\n\telapsed_seconds = end-start;\n\n\tstd::cout << \"Done running MC in \" << elapsed_seconds.count() << \" s\\n\";\n\n\t\n\tstd::vector<double> mc_variances_slopes(FACETS_TO_INVESTIGATE.size());\n\n\tstd::cout << \"Computing MC dispersions...\\n\";\n\t\n\tfor (int e = 0; e < mc_variances_slopes.size(); ++e){\n\t\tarma::vec slopes_mc(N_MONTE_CARLO);\n\t\tfor (int sample = 0; sample < N_MONTE_CARLO; ++sample){\n\t\t\tslopes_mc(sample) = all_slopes[sample][e];\n\t\t}\n\t\tmc_variances_slopes[e] = arma::var(slopes_mc);\n\n\t\tslopes_mc.save(OUTPUT_DIR + \"/slope_distribution_facet_\" + std::to_string(FACETS_TO_INVESTIGATE[e]) + \".txt\",arma::raw_ascii);\n\t}\n\n\tstd::cout << \"\\t After \" << N_MONTE_CARLO << \" MC outcomes:\\n\";\n\n\tfor (int e = 0; e < FACETS_TO_INVESTIGATE.size(); ++e){\n\t\tstd::cout << \"\\tAt facet \" << FACETS_TO_INVESTIGATE[e] << \"\\n\";\n\t\tstd::cout << \"\\t\\tSlope (rad): \" << pgm_filter -> GetSlope(FACETS_TO_INVESTIGATE[e]) << std::endl;\n\t\tstd::cout << \"\\t\\tMC variance in slope: \" << mc_variances_slopes[e] << std::endl;\n\t\tstd::cout << \"\\t\\tAnalytical variance in slope: \" << analytical_variances_slopes[e] << std::endl;\n\t\tstd::cout << \"\\t\\tError (%): \" << (mc_variances_slopes[e] - analytical_variances_slopes[e])/analytical_variances_slopes[e] * 100 << std::endl;\n\t\t\n\t}\n\n\n\n\n\treturn 0;\n}\n", "meta": {"hexsha": "14877791d53932e31009e7c47ba1a90d59ce1c4a", "size": 7289, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Examples/PGMUncertaintyMCSlopesValidation/main.cpp", "max_stars_repo_name": "bbercovici/SBGAT", "max_stars_repo_head_hexsha": "93e935baff49eb742470d7d593931f0573f0c062", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2017-11-29T02:47:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-26T05:25:44.000Z", "max_issues_repo_path": "Examples/PGMUncertaintyMCSlopesValidation/main.cpp", "max_issues_repo_name": "bbercovici/SBGAT", "max_issues_repo_head_hexsha": "93e935baff49eb742470d7d593931f0573f0c062", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 34.0, "max_issues_repo_issues_event_min_datetime": "2017-02-09T15:38:35.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-25T20:53:37.000Z", "max_forks_repo_path": "Examples/PGMUncertaintyMCSlopesValidation/main.cpp", "max_forks_repo_name": "bbercovici/SBGAT", "max_forks_repo_head_hexsha": "93e935baff49eb742470d7d593931f0573f0c062", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-03-12T12:20:25.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-12T12:20:25.000Z", "avg_line_length": 32.9819004525, "max_line_length": 144, "alphanum_fraction": 0.721772534, "num_tokens": 2101, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.49128434008867605}}
{"text": "/*\n * @file SURF_FlannMatcher\n * @brief SURF detector + descriptor + FLANN Matcher\n * @author A. Huaman\n */\n\n#include <fstream>\n#include <iostream>\n#include <stdio.h>\n#include <iomanip>\n#include <sstream>\n#include <stdio.h>\n#include <stdlib.h>\n\n#include <Eigen/Dense>\n#include <opengv/amm.hpp>\n#include <opengv/relative_pose/methods.hpp>\n#include <opengv/relative_pose/NoncentralRelativeAdapter.hpp>\n#include <opengv/optimization_tools/objective_function_tools/GlobalPnPFunctionInfo.hpp>\n#include <opengv/optimization_tools/objective_function_tools/SquaredFunctionNoIterationsInfo.hpp>\n#include <opengv/optimization_tools/solver_tools/SolverToolsNoncentralRelativePose.hpp>\n\n#include \"opencv2/core.hpp\"\n#include \"opencv2/features2d.hpp\"\n#include \"opencv2/imgcodecs.hpp\"\n#include \"opencv2/highgui.hpp\"\n#include \"opencv2/xfeatures2d.hpp\"\n\n#include \"random_generators.hpp\"\n#include \"experiment_helpers.hpp\"\n#include \"time_measurement.hpp\"\n\n\nusing namespace std;\nusing namespace cv;\nusing namespace cv::xfeatures2d;\n//void readme();\n/*\n * @function main\n * @brief Main function\n */\nvoid returnCorrespondences(const Mat & img1, const Mat & img2, std::vector<KeyPoint> & k1, std::vector<KeyPoint> & k2);\n\nint main( int argc, char** argv )\n{\n  if( argc != 5 )\n  {\n    std::cout << \"argc: \" << argc << std::endl;\n    //readme();\n    return -1;\n  }\n  Mat img_left_1 = imread( argv[1], IMREAD_GRAYSCALE );\n  Mat img_left_2 = imread( argv[2], IMREAD_GRAYSCALE );\n\n  Mat img_right_1 = imread( argv[3], IMREAD_GRAYSCALE );\n  Mat img_right_2 = imread( argv[4], IMREAD_GRAYSCALE );\n  if( !img_left_1.data || !img_left_2.data || !img_right_1.data || !img_right_2.data)\n  {\n    std::cout<< \" --(!) Error reading images \" << std::endl;\n    return -1;\n  }\n  std::vector<KeyPoint> k1_left;\n  std::vector<KeyPoint> k2_left;\n  returnCorrespondences(img_left_1, img_left_2, k1_left, k2_left);\n\n  std::vector<KeyPoint> k1_right;\n  std::vector<KeyPoint> k2_right;\n  returnCorrespondences(img_right_1, img_right_2, k1_right, k2_right);\n\n  /*std::cout << \"Left: \" << std::endl;\n  for(int i=0; i < k1_left.size(); ++i){\n    std::cout << \"(\" << k1_left[i].pt.x << \", \" << k1_left[i].pt.y << \")  (\" << k2_left[i].pt.x << \", \" << k2_left[i].pt.y << \")\" <<  std::endl;\n  }\n\n  std::cout << \"Right: \" << std::endl;\n  for(int i=0; i < k1_right.size(); ++i){\n    std::cout << \"(\" << k1_right[i].pt.x << \", \" << k1_right[i].pt.y << \")  (\" << k2_right[i].pt.x << \", \" << k2_right[i].pt.y << \")\" <<  std::endl;\n    }*/\n\n   \n  std::cout << \"Cal matrices: \" << std::endl;\n  Eigen::Matrix3d K_left = Eigen::Matrix3d::Identity(3,3);\n  K_left(0,0) = 9.597910e+02; K_left(0,1) =  0.000000e+00; K_left(0,2) = 6.960217e+02;\n  K_left(1,0) = 0.000000e+00; K_left(1,1) =  9.569251e+02; K_left(1,2) = 2.241806e+02;\n  K_left(2,0) = 0.000000e+00; K_left(2,1) =  0.000000e+00; K_left(2,2) = 1.000000e+00;\n\n  Eigen::Matrix3d K_right = Eigen::Matrix3d::Identity(3,3);\n  K_right(0,0) = 9.037596e+02; K_right(0,1) =  0.000000e+00; K_right(0,2) = 6.957519e+02;\n  K_right(1,0) = 0.000000e+00; K_right(1,1) =  9.019653e+02; K_right(1,2) = 2.242509e+02;\n  K_right(2,0) = 0.000000e+00; K_right(2,1) =  0.000000e+00; K_right(2,2) = 1.000000e+00;\n\n  //We have the calibration matrices and the vector points now it is necessary to build the bearing vectors and convert them in the reference frame of the centra\n\n  //Pose for viewpoint left\n  opengv::translation_t position_left = Eigen::MatrixXd::Zero(3,1);\n  position_left(0,0) = -0.27;\n  opengv::rotation_t rotation_left    = Eigen::MatrixXd::Identity(3,3);\n\n  //Pose for viewpoint right\n  opengv::translation_t position_right = Eigen::MatrixXd::Zero(3,1);\n  position_right(0,0) = 0.27;\n  opengv::rotation_t rotation_right    = Eigen::MatrixXd::Identity(3,3);\n\n  //Create a fake central camera\n \n  opengv::bearingVectors_t bearingVectors1;\n  opengv::bearingVectors_t bearingVectors2;\n  Eigen::MatrixXd aux = Eigen::MatrixXd::Zero(3,1);\n  for(int j = 0; j < k1_left.size(); ++j){\n    aux(0,0) = k1_left[j].pt.x; aux(1,0) = k1_left[j].pt.y; aux(2,0) = 1;\n    aux = K_left.inverse() * aux;\n    bearingVectors1.push_back(aux);\n  }\n  \n  for(int j = 0; j < k1_right.size(); ++j){\n    aux(0,0) = k1_right[j].pt.x; aux(1,0) = k1_right[j].pt.y; aux(2,0) = 1;\n    aux = K_right.inverse() * aux;\n    bearingVectors1.push_back(aux);\n  }\n  \n  for(int j = 0; j < k2_left.size(); ++j){\n    aux(0,0) = k2_left[j].pt.x; aux(1,0) = k2_left[j].pt.y; aux(2,0) = 1;\n    aux = K_left.inverse() * aux;\n    bearingVectors2.push_back(aux);\n  }\n  \n  for(int j = 0; j < k2_right.size(); ++j){\n    aux(0,0) = k2_right[j].pt.x; aux(1,0) = k2_right[j].pt.y; aux(2,0) = 1;\n    aux = K_right.inverse() * aux;\n    bearingVectors2.push_back(aux);\n  }\n  std::cout << \"bearing vector1: \" << bearingVectors1.size() << std::endl;\n  std::cout << \"bearing vector2: \" << bearingVectors2.size() << std::endl;\n  //To use the methods it will be necessary to build the central adapter\n  /*opengv::bearingVectors_t v1;\n  opengv::bearingVectors_t v2;\n  int cols = (int)good_matches.size();\n  for( int i = 0; i < cols; i++ )\n    {\n      std::cout << \"Start cycle: \" << i << std::endl;\n      Eigen::MatrixXd v_left = Eigen::MatrixXd::Zero(3,1);\n      v_left(0,0) = k1[i].pt.x;\n      v_left(1,0) = k1[i].pt.y;\n      v_left(2,0) = 1;\n      //std::cout << \"v1: \" << std::endl << v1 << std::endl;\n\n      Eigen::MatrixXd v_right = Eigen::MatrixXd::Zero(3,1);\n      v_right(0,0) = k2[i].pt.x;\n      v_right(1,0) = k2[i].pt.y;\n      v_right(2,0) = 1;\n      //std::cout << \"v2: \" << std::endl << v2 <<std::endl;\n\n      v_left = K_left.inverse() * v_left;\n      double norm_left = v_left.norm();\n      v_left = v_left / norm_left;\n\n      v_right = K_right.inverse() * v_right;\n      double norm_right = v_right.norm();\n      v_right = v_right /norm_right;\n      \n      v1.push_back(v_left);\n      v2.push_back(v_right);\n    }\n  opengv::rotations_t camRotations;\n  opengv::rotation_t rotation1 = Eigen::MatrixXd::Identity(3,3);\n  opengv::rotation_t rotation2 = Eigen::MatrixXd::Identity(3,3);\n  opengv::translation_t position1 = Eigen::MatrixXd::Zero(3,1);\n  opengv::translation_t position2 = Eigen::MatrixXd::Zero(3,1);\n  position2(0,0) = 0.54;\n  camRotations.push_back(rotation1);\n  camRotations.push_back(rotation2);\n \n  opengv::translations_t camOffsets;\n  camOffsets.push_back(position1);\n  camOffsets.push_back(position2);\n  std::vector<int> camCorrespondences1;\n  std::vector<int> camCorrespondences2;\n  int camCorrespondence = 0;\n  for(int i = 0; i < good_matches.size(); ++i){\n    camCorrespondences1.push_back(camCorrespondence);\n    camCorrespondences2.push_back(camCorrespondence++);\n  }\n  \n  //Extract the relative pose\n  opengv::translation_t position; opengv::rotation_t rotation;\n  opengv::extractRelativePose(position1, position2, rotation1, rotation2, position, rotation, false );\n\n  //create non-central relative adapter\n  opengv::relative_pose::NoncentralRelativeAdapter adapter(\n\t\t\t\t\t\t       v1,\n\t\t\t\t\t\t       v2,\n\t\t\t\t\t\t       camCorrespondences1,\n\t\t\t\t\t\t       camCorrespondences2,\n\t\t\t\t\t\t       camOffsets,\n\t\t\t\t\t\t       camRotations,\n\t\t\t\t\t\t       position,\n\t\t\t\t\t\t       rotation);\n  return 0;*/\n}\n\n/*\n * @function readme\n */\n/*void readme(){\n  std::cout << \" Usage: ./SURF_FlannMatcher <img1> <img2>\" << std::endl;\n  }*/\n\nvoid returnCorrespondences(const Mat & img1, const Mat & img2, std::vector<KeyPoint> & k1, std::vector<KeyPoint> & k2){\n  //-- Step 1: Detect the keypoints using SURF Detector, compute the descriptors\n  int minHessian = 400;\n  Ptr<SURF> detector = SURF::create();\n  detector->setHessianThreshold(minHessian);\n  \n  std::vector<KeyPoint> keypoints_1, keypoints_2;\n  Mat descriptors_1, descriptors_2;\n  detector->detectAndCompute( img1, Mat(), keypoints_1, descriptors_1 );\n  detector->detectAndCompute( img2, Mat(), keypoints_2, descriptors_2 );\n  //-- Step 2: Matching descriptor vectors using FLANN matcher\n  FlannBasedMatcher matcher;\n  std::vector< DMatch > matches;\n  matcher.match( descriptors_1, descriptors_2, matches );\n  double max_dist = 0; double min_dist = 100;\n  //-- Quick calculation of max and min distances between keypoints\n  for( int i = 0; i < descriptors_1.rows; i++ )\n  {\n    double dist = matches[i].distance;\n    if( dist < min_dist ) min_dist = dist;\n    if( dist > max_dist ) max_dist = dist;\n  }\n  printf(\"-- Max dist : %f \\n\", max_dist );\n  printf(\"-- Min dist : %f \\n\", min_dist );\n  //-- Draw only \"good\" matches (i.e. whose distance is less than 2*min_dist,\n  //-- or a small arbitary value ( 0.02 ) in the event that min_dist is very\n  //-- small)\n  //-- PS.- radiusMatch can also be used here.\n  std::vector< DMatch > good_matches;\n  for( int i = 0; i < descriptors_1.rows; i++ )\n  {\n    if( matches[i].distance <= max(2*min_dist, 0.02) ){\n      good_matches.push_back( matches[i]);\n    }\n  }\n  //-- Draw only \"good\" matches\n  k1.clear();\n  k2.clear();\n  for( int i = 0; i < (int)good_matches.size(); i++ )\n  {\n    //printf( \"-- Good Match [%d] Keypoint 1: %d  -- Keypoint 2: %d  \\n\", i, good_matches[i].queryIdx, good_matches[i].trainIdx );\n    std::cout << ( \"-- Good Match [%d] Keypoint 1: %d  -- Keypoint 2: %d  \\n\", i, good_matches[i].queryIdx, good_matches[i].trainIdx ) << std::endl;\n    k1.push_back(keypoints_1[good_matches[i].queryIdx]);\n    k2.push_back(keypoints_2[good_matches[i].trainIdx]);    \n  }\n  \n}\n", "meta": {"hexsha": "e2fba58494d75f727004c4b1b375798e1882f33d", "size": 9319, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/features_noncentral.cpp", "max_stars_repo_name": "mateus03/2018AMMPoseSolver", "max_stars_repo_head_hexsha": "787886846199cd0864c4e59a6545c40c3120010a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-05-15T12:41:36.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-07T10:42:52.000Z", "max_issues_repo_path": "test/features_noncentral.cpp", "max_issues_repo_name": "mateus03/2018AMMPoseSolver", "max_issues_repo_head_hexsha": "787886846199cd0864c4e59a6545c40c3120010a", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/features_noncentral.cpp", "max_forks_repo_name": "mateus03/2018AMMPoseSolver", "max_forks_repo_head_hexsha": "787886846199cd0864c4e59a6545c40c3120010a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-27T18:11:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-27T18:11:14.000Z", "avg_line_length": 36.5450980392, "max_line_length": 161, "alphanum_fraction": 0.6507135959, "num_tokens": 3046, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387956435734, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4912843375840981}}
{"text": "#ifndef COMMON_HPP\n#define COMMON_HPP\n\n#include <boost/multiprecision/cpp_bin_float.hpp>\n\nnamespace ccalc\n{\n    namespace mp = boost::multiprecision;\n    using Float = mp::number<mp::cpp_bin_float<128>>;\n} // namespace ccalc\n\n#endif // !COMMON_HPP", "meta": {"hexsha": "469403239e7de2198365abc9e4ed9da105edcdea", "size": 247, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/common.hpp", "max_stars_repo_name": "tretre91/ccalc", "max_stars_repo_head_hexsha": "3e13365855018314b798287967a978f4951783da", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/common.hpp", "max_issues_repo_name": "tretre91/ccalc", "max_issues_repo_head_hexsha": "3e13365855018314b798287967a978f4951783da", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/common.hpp", "max_forks_repo_name": "tretre91/ccalc", "max_forks_repo_head_hexsha": "3e13365855018314b798287967a978f4951783da", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.5833333333, "max_line_length": 53, "alphanum_fraction": 0.7408906883, "num_tokens": 60, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.49127098086514764}}
{"text": "#include <iostream>\n#include <math.h>\n#include <fstream>\n#include <time.h>\n#include <boost/range/numeric.hpp>\n#include <boost/range/adaptor/map.hpp>\n#include <unordered_map>\n#include <algorithm>\n#include <vector>\n#include <iterator>\n#define h  800 \n#define w  800\n#define output_file \"output.raw\"\n\nunsigned char* readImage(const char *image, int height, int width, int bpp)\n{\n\n\tunsigned char* Imagedata = new unsigned char [height*width*bpp];\n\n\tFILE *file;\n\tif (!(file=fopen(image,\"rb\"))) {\n\t\tstd::cout << \"Cannot open file: \" << image << std::endl;\n\t\texit(1);\n\t}\n\tfread(Imagedata, sizeof(unsigned char), height*width*bpp, file);\n\tfclose(file);\n\n\treturn Imagedata;\n}\n\nvoid saveImage(const char* image, unsigned char* Imagedata, int height, int width, int bpp)\n{\n\tFILE *file;\n\n\tif (!(file=fopen(image,\"wb\"))) {\n\t\tstd::cout << \"Cannot open file: \" << image << std::endl;\n\t\texit(1);\n\t}\n\tfwrite(Imagedata, sizeof(unsigned char), height*width*bpp, file);\n\tfclose(file);\n\n\tstd::cout << \"Filed Saved Succesfully\" << std::endl;\n}\n\n\nint getEuclideanDist(int pixel, int mean)\n{\n\treturn abs(pixel - mean);\n}\n\nint getMeanOfCluster(std::unordered_map<int, int> cluster)\n{\n\tstd::unordered_map<int, int>::iterator itr;\n\tint sum(0);\n\n\t// for(itr = cluster.begin(); itr != cluster.end(); itr++)\n\t// {\n\t// \tsum += itr->second;\n\t// \t// std::cout << sum << std::endl;\n\t// }\n\n\tsum = boost::accumulate(cluster | boost::adaptors::map_values, 0);\n\n\treturn sum/cluster.size();\n}\n\n\nunsigned char* getFinalOutput(unsigned char* Image1DOutput, std::unordered_map<int, int> cluster, \n\tint height, int width, int mean)\n{\n\tstd::unordered_map<int, int>::iterator itr;\n\n\tfor(itr = cluster.begin(); itr != cluster.end(); itr++)\n\t{\n\t\tImage1DOutput[itr->first] = mean;\n\t}\n\n\treturn Image1DOutput;\n}\n\n\nunsigned char* getKMeansClustered(unsigned char* Image1D, int height, int width)\n{\n\tint iters(30);\n\tint mean1(0), mean2(85), mean3(170), mean4(255), pixel; \n\n\tunsigned char* Image1DOutput = new unsigned char[height*width];\n\tstd::unordered_map<int, int> cluster1, cluster2, cluster3, cluster4;\n\tstd::vector<int> minDist(4, 0);\n\n\twhile(iters>0)\n\t{\n\t\tcluster1.clear();\n\t\tcluster2.clear();\n\t\tcluster3.clear();\n\t\tcluster4.clear();\n\t\tfor (int i = 0; i < height; ++i)\n\t\t{\n\t\t\tfor (int j = 0; j < width; ++j)\n\t\t\t{\n\t\t\t\tpixel = Image1D[i*width + j];\n\n\n\t\t\t\tminDist[0] = (int(abs(pixel - mean1)));\n\n\t\t\t\tminDist[1] = (int(abs(pixel - mean2)));\n\n\t\t\t\tminDist[2] = (int(abs(pixel - mean3)));\n\n\t\t\t\tminDist[3] = (int(abs(pixel - mean4)));\n\n\t\t\t\tint min_pos = std::distance(minDist.begin(), std::min_element(minDist.begin(),minDist.end()));\n\n\n\t\t\t\tswitch(min_pos)\n\t\t\t\t{\n\t\t\t\t\tcase 0:\n\t\t\t\t\tcluster1[i*width + j] = pixel;\n\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 1:\n\t\t\t\t\tcluster2[i*width + j] = pixel;\n\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 2:\n\t\t\t\t\tcluster3[i*width + j] = pixel;\n\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 3:\n\t\t\t\t\tcluster4[i*width + j] = pixel;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\n\t\titers--;\n\t\tmean1 = getMeanOfCluster(cluster1);\n\t\tmean2 = getMeanOfCluster(cluster2);\n\t\tmean3 = getMeanOfCluster(cluster3);\n\t\tmean4 = getMeanOfCluster(cluster4);\n\n\t\t// std::cout << \"Means are: \" << mean1 << \", \" << mean2 << \", \" << mean3 << \", \" << mean4 << \", \" << \"; Iter: \" << iters << std::endl;\n\t}\n\n\n\n\tImage1DOutput = getFinalOutput(Image1DOutput, cluster1, h, w, mean1);\n\tImage1DOutput = getFinalOutput(Image1DOutput, cluster2, h, w, mean2);\n\tImage1DOutput = getFinalOutput(Image1DOutput, cluster3, h, w, mean3);\n\tImage1DOutput = getFinalOutput(Image1DOutput, cluster4, h, w, mean4);\n\n\treturn Image1DOutput;\n\n\n}\n\n\n\nint main(int argc, char const *argv[])\n{\n\tstruct timespec start, stop;\n\tunsigned char* Image1D = readImage(argv[1], h, w, 1); \n\tstd::cout << \"Image read\" << std::endl;\n\t\n\n\tif(clock_gettime(CLOCK_REALTIME, &start) == -1) \n\t\tperror(\"clock gettime\");\n\n\tunsigned char* Image1DOutput = getKMeansClustered(Image1D, h, w);\n\n\tif(clock_gettime( CLOCK_REALTIME, &stop) == -1 )\n\t\tperror(\"clock gettime\");\n\n\n\tdouble time = (stop.tv_sec - start.tv_sec)+ (double)(stop.tv_nsec - start.tv_nsec)/1e9;\n\tstd::cout << \"time taken: \" << time << std::endl;\n\n\t\n\tsaveImage(output_file, Image1DOutput, h, w, 1);\n\tdelete [] Image1D;\n\tdelete [] Image1DOutput;\n\n\n\treturn 0;\n}", "meta": {"hexsha": "981f7986b81239b49101a2dbe9e926f43d4edb61", "size": 4146, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/PHW_1/p2.cpp", "max_stars_repo_name": "SiddhantNadkarni/Parallel-and-Distributed-Computing", "max_stars_repo_head_hexsha": "e49aae454a5ac3e8eb557805c72ebab490851509", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-04T08:59:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-04T08:59:13.000Z", "max_issues_repo_path": "src/PHW_1/p2.cpp", "max_issues_repo_name": "SiddhantNadkarni/Parallel-and-Distributed-Computing", "max_issues_repo_head_hexsha": "e49aae454a5ac3e8eb557805c72ebab490851509", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/PHW_1/p2.cpp", "max_forks_repo_name": "SiddhantNadkarni/Parallel-and-Distributed-Computing", "max_forks_repo_head_hexsha": "e49aae454a5ac3e8eb557805c72ebab490851509", "max_forks_repo_licenses": ["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.2903225806, "max_line_length": 136, "alphanum_fraction": 0.6456825856, "num_tokens": 1241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208004, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.4912709782964842}}
{"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_SCALAR_SINC_HPP_INCLUDED\n#define NT2_TRIGONOMETRIC_FUNCTIONS_SCALAR_SINC_HPP_INCLUDED\n#include <nt2/trigonometric/functions/sinc.hpp>\n#include <nt2/include/functions/scalar/sin.hpp>\n#include <nt2/include/constants/one.hpp>\n#include <boost/simd/sdk/config.hpp>\n\n#if !defined(BOOST_SIMD_NO_INFINITIES)\n#include <nt2/include/functions/scalar/is_inf.hpp>\n#include <nt2/include/constants/zero.hpp>\n#endif\n\n#if !defined(BOOST_SIMD_NO_DENORMALS)\n#include <nt2/include/functions/scalar/abs.hpp>\n#include <nt2/include/constants/eps.hpp>\n#endif\n\nnamespace nt2 { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT  ( sinc_, tag::cpu_\n                            , (A0)\n                            , (scalar_< floating_<A0> >)\n                            )\n  {\n\n    typedef A0 result_type;\n\n    NT2_FUNCTOR_CALL(1)\n    {\n      #if !defined(BOOST_SIMD_NO_INFINITIES)\n      if(nt2::is_inf(a0)) return nt2::Zero<result_type>();\n      #endif\n\n      #if !defined(BOOST_SIMD_NO_DENORMALS)\n      return (nt2::abs(a0) < nt2::Eps<result_type>()) ? nt2::One<result_type>()\n                                                      : nt2::sin(a0)/a0;\n      #else\n      return a0 ? nt2::sin(a0)/a0 : nt2::One<result_type>();\n      #endif\n    }\n  };\n} }\n\n\n#endif\n", "meta": {"hexsha": "29925a7c4162704ce32c3151f5c43babd1ea8f0d", "size": 1766, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/trigonometric/include/nt2/trigonometric/functions/scalar/sinc.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/sinc.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/sinc.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 32.7037037037, "max_line_length": 80, "alphanum_fraction": 0.5719139298, "num_tokens": 437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.49127097829648414}}
{"text": "/* ----------------------------------------------------------------------- *//**\n *\n * @file student.hpp\n *\n * @brief Evaluate the Student's t-distribution function.\n * @author Florian Schoppmann\n * @date   November 2010\n *\n *//* -------------------------------------------------------------------- *//**\n *\n * @file student.hpp\n *\n * Emprirical results indicate that the numerical quality of the series\n * expansion from [1] (see notes below) is vastly superior to using continued\n * fractions for computing the cdf via the incomplete beta function.\n *\n * @literature\n *\n * [1] Abramowitz and Stegun, Handbook of Mathematical Functions with Formulas,\n *     Graphs, and Mathematical Tables, 1972\n *     page 948: http://people.math.sfu.ca/~cbm/aands/page_948.htm\n *\n * Further reading (for computing the Student-T cdf via the incomplete beta\n * function):\n *\n * [2] NIST Digital Library of Mathematical Functions, Ch. 8,\n *     Incomplete Gamma and Related Functions,\n *     http://dlmf.nist.gov/8.17\n *\n * [3] Lentz, Generating Bessel functions in Mie scattering calculations using\n *     continued fractions, Applied Optics, Vol. 15, No. 3, 1976\n *\n * [4] Thompson and Barnett, Coulomb and Bessel Functions of Complex Arguments\n *     and Order, Journal of Computational Physics, Vol. 64, 1986\n *\n * [5] Cuyt et al., Handbook of Continued Fractions for Special Functions,\n *     Springer, 2008\n *\n * [6] Gil et al., Numerical Methods for Special Functions, SIAM, 2008\n *\n * [7] Press et al., Numerical Recipes in C++, 3rd edition,\n *     Cambridge Univ. Press, 2007\n *\n * [8] DiDonato, Morris, Jr., Algorithm 708: Significant Digit Computation of\n *     the Incomplete Beta Function Ratios, ACM Transactions on Mathematical\n *     Software, Vol. 18, No. 3, 1992\n *\n * Approximating the Student-T distribution function with the normal\n * distribution:\n *\n * [9]  Gleason, A note on a proposed student t approximation, Computational\n *      Statistics & Data Analysis, Vol. 34, No. 1, 2000\n *\n * [10] Gaver and Kafadar, A Retrievable Recipe for Inverse t, The American\n *      Statistician, Vol. 38, No. 4, 1984\n */\n\n/**\n * @brief Student-t cumulative distribution function\n */\nDECLARE_UDF(prob, students_t_cdf)\nDECLARE_UDF(prob, students_t_pdf)\nDECLARE_UDF(prob, students_t_quantile)\n\n\n#ifndef MADLIB_MODULES_PROB_STUDENT_T_HPP\n#define MADLIB_MODULES_PROB_STUDENT_T_HPP\n\n#include <boost/math/distributions/detail/common_error_handling.hpp>\n#include <boost/math/distributions/normal.hpp>\n#include <boost/math/distributions/students_t.hpp>\n\nnamespace madlib {\n\nnamespace modules {\n\nnamespace prob {\n\ntypedef boost::math::students_t_distribution<double, boost_mathkit_policy>\n    students_t;\n\nnamespace {\n\n/**\n * @brief Compute one-sided Student's t cumulative distribution function\n *\n * We use the series expansions 26.7.3 and 26.7.4 from [1] and\n * substitute sin(theta) = t/sqrt(n * z), where z = 1 + t^2/nu.\n *\n * This gives:\n * @verbatim\n *                          t\n *   A(t|1)  = 2 arctan( -------- ) ,\n *                       sqrt(nu)\n *\n *                                                    (nu-3)/2\n *             2   [            t              t         --    2 * 4 * ... * (2i)  ]\n *   A(t|nu) = - * [ arctan( -------- ) + ------------ * \\  ---------------------- ]\n *             \u03c0   [         sqrt(nu)     sqrt(nu) * z   /_ 3 * ... * (2i+1) * z^i ]\n *                                                       i=0\n *           for odd nu > 1, and\n *\n *                         (nu-2)/2\n *                  t         -- 1 * 3 * ... * (2i - 1)\n *   A(t|nu) = ------------ * \\  ------------------------ for even nu,\n *             sqrt(nu * z)   /_ 2 * 4 * ... * (2i) * z^i\n *                            i=0\n *\n * where A(t|nu) = Pr[|T| <= t].\n * @endverbatim\n *\n * @param t\n * @param nu Degree of freedom \\f$ \\nu > 0 \\f$\n * @return \\f$ \\Pr[|T| < t] \\f$ where \\f$ t \\geq 0 \\f$, \\f$ T \\f$ is a Student's\n *     T-distributed random variable with \\f$ \\nu \\f$ degrees of\n *     freedom.\n *\n * Note: The running time of calculating the series is proportional to nu.\n * We therefore use the normal distribution as an approximation for large nu.\n * Another idea for handling this case can be found in reference [8].\n */\ntemplate <class RealType>\ninline\nRealType\noneSidedStudentsT_CDF(const RealType& t,  uint64_t nu) {\n    RealType    z,\n                t_by_sqrt_nu;\n    RealType    A, /* contains A(t|nu) */\n                prod = 1.,\n                sum = 1.;\n\n    /* Handle main case (nu \\in {1, ..., 200}) in the rest of the function. */\n    z = 1. + t * t / static_cast<double>(nu);\n    t_by_sqrt_nu = std::fabs(t) / std::sqrt(static_cast<double>(nu));\n\n    if (nu == 1)\n    {\n        A = 2. / M_PI * std::atan(t_by_sqrt_nu);\n    }\n    else if (nu & 1) /* odd nu > 1 */\n    {\n        for (uint64_t j = 2; j + 3 <= nu; j += 2)\n        {\n            prod = prod * static_cast<double>(j)\n                 / (static_cast<double>(j + 1) * z);\n            sum = sum + prod;\n        }\n        A = 2 / M_PI * ( std::atan(t_by_sqrt_nu) + t_by_sqrt_nu / z * sum );\n    }\n    else /* even nu */\n    {\n        for (uint64_t j = 2; j + 2 <= nu; j += 2)\n        {\n            prod = prod * static_cast<double>(j - 1)\n                 / (static_cast<double>(j) * z);\n            sum = sum + prod;\n        }\n        A = t_by_sqrt_nu / std::sqrt(z) * sum;\n    }\n\n    /* A should obviously be within the interval [0,1] plus minus (hopefully\n     * small) rounding errors. */\n    if (A > 1.)\n        A = 1.;\n    else if (A < 0.)\n        A = 0.;\n\n    return A;\n}\n\n/**\n * @brief Compute parameter for normal CDF for approximating the Student's T CDF\n *\n * Gleason suggested a formula for approximating the Student's\n * t-distribution [9], which goes back to an approximation suggested in [10].\n *\n * Compared to the series expansion, this approximation satisfies\n * rel_error < 0.0001 || abs_error < 0.00000001\n * for all nu >= 200. (Tested on Mac OS X 10.6, gcc-4.2.)\n *\n * @param t\n * @param nu Degree of freedom \\f$ \\nu > 0 \\f$\n * @returns A value \\f$ z \\f$ such that for a Student's t-distributed\n *     random variable \\f$ T \\f$ with \\f$ nu \\f$ degrees of freedom and a\n *     standard normally distributed random variable \\f$ Z \\f$, it holds that\n *     \\f$ \\Pr[T \\leq t] \\approx \\Pr[Z \\leq z] \\f$.\n */\ntemplate <class RealType>\ninline\nRealType\nGleasonsNormalApproxForStudentsT(const RealType& t, const RealType& nu) {\n    double  g = (nu - 1.5) / ((nu - 1) * (nu - 1)),\n            z = std::sqrt( std::log(1. + t * t / nu) / g );\n\n    if (t < 0)\n        z *= -1.;\n\n    return z;\n}\n\n} // anonymous namespace\n\n/**\n * @brief Compute Student's cumulative distribution function\n *\n * For nu >= 1000000, we just use the normal distribution as an approximation.\n * For 1000000 >= nu >= 200, we use a simple approximation from [9].\n * If nu is not within 0.01 of a natural number, we will call the student-t\n * CDF from boost. Otherwise, our approach should be much more precise than\n * using the incomplete beta function as boost does (see the references).\n *\n * We are much more cautious than usual here (it is folklore that the normal\n * distribution is a \"good\" estimate for Student-T if nu >= 30), but we can\n * afford the extra work as this function is not designed to be called from\n * inner loops. Performance should still be reasonably good, with at most ~100\n * iterations in any case (just one if nu >= 200).\n *\n * For nu < 200, we use the series expansions 26.7.3 and 26.7.4 from [1] and\n * substitute sin(theta) = t/sqrt(n * z), where z = 1 + t^2/nu (using\n * oneSidedStudentsT_CDF()).\n *\n * @param dist A Student's t-distribution object, containing the degree of\n *     freedom \\f$ \\nu \\f$\n * @param t\n * @return \\f$ \\Pr[T < t] \\f$ where \\f$ t \\geq 0 \\f$, \\f$ T \\f$ is a Student's\n *     T-distributed random variable with \\f$ \\nu \\f$ degrees of\n *     freedom.\n */\ntemplate <class RealType, class Policy>\ninline\nRealType\ncdf(const boost::math::students_t_distribution<RealType, Policy>& dist,\n    const RealType& t) {\n\n    RealType df = dist.degrees_of_freedom();\n\n    // FIXME: Add some justification/do some tests.\n    if (!std::isfinite(df) || std::fabs(df - std::floor(df))/df > 0.01)\n        return boost::math::cdf(dist, t);\n\n    static const char* function = \"madlib::modules::prob::cdf(\"\n        \"const students_t_distribution<%1%>&, %1%)\";\n\n    RealType result;\n    if (!boost::math::detail::check_df(function, df, &result, Policy()))\n        return result;\n\n    if (df >= 200)\n        return\n            boost::math::cdf(\n                boost::math::normal_distribution<RealType, Policy>(),\n                df >= 1000000\n                    ? t\n                    : GleasonsNormalApproxForStudentsT(t, df)\n            );\n\n    // We first compute A = Pr[|T| < t]\n    RealType A = oneSidedStudentsT_CDF(t, static_cast<uint64_t>(df));\n\n    /* The Student-T distribution is obviously symmetric around t=0... */\n    if (t < 0)\n        /* FIXME: If A is approximately 1, we will face a loss of significance.\n         *  */\n        return .5 * (1. - A);\n    else\n        /* While we only know A in [0,1] here, the end result will be in\n         * [0.5, 1]. Hence, there is no problem with adding 1 and A, even if\n         * A << 1. */\n        return .5 * (1. + A);\n}\n\n/**\n * @brief Compute the complement of Student's cumulative distribution function\n */\ntemplate <class RealType, class Policy>\ninline\nRealType\ncdf(\n    const boost::math::complemented2_type<\n        boost::math::students_t_distribution<RealType, Policy>,\n        RealType\n    >& c\n) {\n    RealType df = c.dist.degrees_of_freedom();\n    if (df >= 200) {\n        static const char* function = \"madlib::modules::prob::cdf(\"\n            \"const complement(students_t_distribution<%1%>&), %1%)\";\n\n        RealType result;\n        if (!boost::math::detail::check_df(function, df, &result, Policy()))\n            return result;\n\n        return\n            boost::math::cdf(complement(\n                boost::math::normal_distribution<RealType, Policy>(),\n                df >= 1000000\n                    ? c.param\n                    : GleasonsNormalApproxForStudentsT(c.param, df)\n            ));\n    }\n\n    return prob::cdf(c.dist, -c.param);\n}\n\ntemplate <class RealType, class Policy>\ninline\nRealType\npdf(const boost::math::students_t_distribution<RealType, Policy>& dist,\n    const RealType& t) {\n    return boost::math::pdf(dist, t);\n}\n\ntemplate <class RealType, class Policy>\ninline\nRealType\npdf(\n    const boost::math::complemented2_type<\n        boost::math::students_t_distribution<RealType, Policy>,\n        RealType\n    >& c\n) {\n    return boost::math::pdf(c);\n}\n\ntemplate <class RealType, class Policy>\ninline\nRealType\nquantile(const boost::math::students_t_distribution<RealType, Policy>& dist,\n    const RealType& p) {\n\n    using namespace boost::math;\n\n    static const char* function = \"madlib::modules::prob::quantile(\"\n        \"const students_t_distribution<%1%>&, %1%)\";\n\n    // FIXME: Boost bug 6937 prevent proper argument validation.\n    // https://svn.boost.org/trac/boost/ticket/6937\n    // Until this is fixed upstream, we do the following checks here.\n    RealType df = dist.degrees_of_freedom();\n    RealType result;\n    if (!detail::check_df(function, df, &result, Policy())\n        || !detail::check_probability(function, p, &result, Policy()))\n        return result;\n\n    return boost::math::quantile(dist, p);\n}\n\ntemplate <class RealType, class Policy>\ninline\nRealType\nquantile(\n    const boost::math::complemented2_type<\n        boost::math::students_t_distribution<RealType, Policy>,\n        RealType\n    >& c\n) {\n    return boost::math::quantile(c);\n}\n\n} // namespace prob\n\n} // namespace modules\n\n} // namespace madlib\n\n#endif // defined(MADLIB_MODULES_PROB_STUDENT_T_HPP)\n", "meta": {"hexsha": "8dcbedf0b91c61c8977b2d08fce0dc2386ee766c", "size": 11777, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/modules/prob/student.hpp", "max_stars_repo_name": "fmcquillan99/apache-madlib", "max_stars_repo_head_hexsha": "e2dea62d1eadc7f662f2d926c71f42332f414ca0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2015-01-01T09:13:57.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-30T02:55:46.000Z", "max_issues_repo_path": "src/modules/prob/student.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/student.hpp", "max_forks_repo_name": "fmcquillan99/apache-madlib", "max_forks_repo_head_hexsha": "e2dea62d1eadc7f662f2d926c71f42332f414ca0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2015-10-16T12:17:55.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-12T10:33:18.000Z", "avg_line_length": 32.0899182561, "max_line_length": 84, "alphanum_fraction": 0.5935297614, "num_tokens": 3241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.49127097586403295}}
{"text": "/* test_bernoulli_distribution.cpp\r\n *\r\n * Copyright Steven Watanabe 2010\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 * $Id: test_bernoulli_distribution.cpp 71018 2011-04-05 21:27:52Z steven_watanabe $\r\n *\r\n */\r\n\r\n#include <boost/random/bernoulli_distribution.hpp>\r\n\r\n#define BOOST_RANDOM_DISTRIBUTION boost::random::bernoulli_distribution<>\r\n#define BOOST_RANDOM_ARG1 p\r\n#define BOOST_RANDOM_ARG1_DEFAULT 0.5\r\n#define BOOST_RANDOM_ARG1_VALUE 0.25\r\n\r\n#define BOOST_RANDOM_DIST0_MIN false\r\n#define BOOST_RANDOM_DIST0_MAX true\r\n#define BOOST_RANDOM_DIST1_MIN false\r\n#define BOOST_RANDOM_DIST1_MAX true\r\n\r\n#define BOOST_RANDOM_TEST1_PARAMS (0.0)\r\n#define BOOST_RANDOM_TEST1_MIN false\r\n#define BOOST_RANDOM_TEST1_MAX false\r\n\r\n#define BOOST_RANDOM_TEST2_PARAMS (1.0)\r\n#define BOOST_RANDOM_TEST2_MIN true\r\n#define BOOST_RANDOM_TEST2_MAX true\r\n\r\n#include \"test_distribution.ipp\"\r\n", "meta": {"hexsha": "3bb4e0a95e77900e64a680aaaffcf749bf8c6cad", "size": 994, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/random/test/test_bernoulli_distribution.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/random/test/test_bernoulli_distribution.cpp", "max_issues_repo_name": "xiaoliang2121/Boost", "max_issues_repo_head_hexsha": "fc90c3fde129c62565c023f091eddc4a7ed9902b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-03-19T08:23:23.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-24T07:48:47.000Z", "max_forks_repo_path": "libs/random/test/test_bernoulli_distribution.cpp", "max_forks_repo_name": "xiaoliang2121/Boost", "max_forks_repo_head_hexsha": "fc90c3fde129c62565c023f091eddc4a7ed9902b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 30.1212121212, "max_line_length": 85, "alphanum_fraction": 0.7957746479, "num_tokens": 249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.49127097586403284}}
{"text": "// This file is part of Eigen, a lightweight C++ template library\n// for linear algebra.\n//\n// Copyright (C) 2012 Giacomo Po <gpo@ucla.edu>\n// Copyright (C) 2011 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#include <cmath>\n\n#include \"../../test/sparse_solver.h\"\n#include <Eigen/IterativeSolvers>\n\ntemplate<typename T> void test_minres_T()\n{\n  // Identity preconditioner\n  MINRES<SparseMatrix<T>, Lower, IdentityPreconditioner    > minres_colmajor_lower_I;\n  MINRES<SparseMatrix<T>, Upper, IdentityPreconditioner    > minres_colmajor_upper_I;\n\n  // Diagonal preconditioner\n  MINRES<SparseMatrix<T>, Lower, DiagonalPreconditioner<T> > minres_colmajor_lower_diag;\n  MINRES<SparseMatrix<T>, Upper, DiagonalPreconditioner<T> > minres_colmajor_upper_diag;\n  MINRES<SparseMatrix<T>, Lower|Upper, DiagonalPreconditioner<T> > minres_colmajor_uplo_diag;\n  \n  // call tests for SPD matrix\n  CALL_SUBTEST( check_sparse_spd_solving(minres_colmajor_lower_I) );\n  CALL_SUBTEST( check_sparse_spd_solving(minres_colmajor_upper_I) );\n    \n  CALL_SUBTEST( check_sparse_spd_solving(minres_colmajor_lower_diag)  );\n  CALL_SUBTEST( check_sparse_spd_solving(minres_colmajor_upper_diag)  );\n  CALL_SUBTEST( check_sparse_spd_solving(minres_colmajor_uplo_diag)  );\n    \n  // TO DO: symmetric semi-definite matrix\n  // TO DO: symmetric indefinite matrix\n\n}\n\nvoid test_minres()\n{\n  CALL_SUBTEST_1(test_minres_T<double>());\n//  CALL_SUBTEST_2(test_minres_T<std::compex<double> >());\n\n}\n", "meta": {"hexsha": "8b300b78a557fc939bed6d7376237650c1f8c994", "size": 1650, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Eigen-3.3/unsupported/test/minres.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/unsupported/test/minres.cpp", "max_issues_repo_name": "shareq2005/CarND-MPC-Project", "max_issues_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_issues_repo_licenses": ["MIT"], "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": "src/Eigen-3.3/unsupported/test/minres.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": 36.6666666667, "max_line_length": 93, "alphanum_fraction": 0.7636363636, "num_tokens": 455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.4912709708629182}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2015 NumScale SAS\n  @copyright 2015 J.T. Lapreste\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_CONSTANT_SQRT_2OPI_HPP_INCLUDED\n#define BOOST_SIMD_CONSTANT_SQRT_2OPI_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n  /*!\n\n    @ingroup group-constant\n\n    Constant  \\f$\\frac{\\sqrt2}{\\pi}\\f$.\n\n    @par Semantic:\n\n    For type T:\n\n    @code\n    T r = Sqrt_2opi<T>();\n    @endcode\n\n    is similar to:\n\n    @code\n    T r = sqrt(Two<T>())/Pi<T>();\n    @endcode\n\n    @return a value of type T\n\n**/\n  template<typename T> T Sqrt_2opi();\n\n  namespace functional\n  {\n    /*!\n      @ingroup group-callable-constant\n\n\n      Constant  \\f$\\frac{\\sqrt2}{\\pi}\\f$.\n\n      Generate the  constant sqrt_2opi.\n\n      @return The Sqrt_2opi constant for the proper type\n    **/\n    const boost::dispatch::functor<tag::sqrt_2opi_> sqrt_2opi = {};\n  }\n} }\n#endif\n\n#include <boost/simd/constant/definition/sqrt_2opi.hpp>\n#include <boost/simd/arch/common/scalar/constant/constant_value.hpp>\n#include <boost/simd/arch/common/simd/constant/constant_value.hpp>\n\n#endif\n", "meta": {"hexsha": "c8f240dc776added6118b9e561b448ad928c39df", "size": 1413, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/constant/sqrt_2opi.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/constant/sqrt_2opi.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/constant/sqrt_2opi.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": 21.7384615385, "max_line_length": 100, "alphanum_fraction": 0.5817409766, "num_tokens": 356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.4912709658618033}}
{"text": "//  (C) Copyright Gennadiy Rozental 2011-2015.\n//  Distributed under the Boost Software License, Version 1.0.\n//  (See accompanying file LICENSE_1_0.txt or copy at\n//  http://www.boost.org/LICENSE_1_0.txt)\n\n//  See http://www.boost.org/libs/test for the library home page.\n\n\n//[example_code\n#define BOOST_TEST_MODULE example\n#include <boost/test/included/unit_test.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n\nBOOST_AUTO_TEST_CASE( test )\n{\n  double v1 = 1.23456e28;\n  double v2 = 1.23457e28;\n\n  BOOST_REQUIRE_CLOSE( v1, v2, 0.001 );\n  // Absolute value of difference between these two values is 1e+23.\n  // But we are interested only that it does not exeed 0.001% of a values compared\n  // And this test will pass.\n}\n//]\n", "meta": {"hexsha": "3eb3f495d1bcf05d30cf284b0583b2a553a98975", "size": 735, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/test/doc/examples/example43.run.cpp", "max_stars_repo_name": "Manu343726/boost-cmake", "max_stars_repo_head_hexsha": "009c3843b49a56880d988ffdca6d909f881edb3d", "max_stars_repo_licenses": ["BSL-1.0"], "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": "libs/test/doc/examples/example43.run.cpp", "max_issues_repo_name": "Manu343726/boost-cmake", "max_issues_repo_head_hexsha": "009c3843b49a56880d988ffdca6d909f881edb3d", "max_issues_repo_licenses": ["BSL-1.0"], "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": "libs/test/doc/examples/example43.run.cpp", "max_forks_repo_name": "Manu343726/boost-cmake", "max_forks_repo_head_hexsha": "009c3843b49a56880d988ffdca6d909f881edb3d", "max_forks_repo_licenses": ["BSL-1.0"], "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": 29.4, "max_line_length": 82, "alphanum_fraction": 0.7319727891, "num_tokens": 211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544335934766, "lm_q2_score": 0.7025300636233415, "lm_q1q2_score": 0.4912472617213287}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2013 Kyle Lutz <kyle.r.lutz@gmail.com>\n//\n// Distributed under the Boost Software License, Version 1.0\n// See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt\n//\n// See http://kylelutz.github.com/compute for more information.\n//---------------------------------------------------------------------------//\n\n#define BOOST_TEST_MODULE TestTransformIf\n#include <boost/test/unit_test.hpp>\n\n#include <boost/compute/lambda.hpp>\n#include <boost/compute/algorithm/transform_if.hpp>\n#include <boost/compute/container/vector.hpp>\n\n#include \"check_macros.hpp\"\n#include \"context_setup.hpp\"\n\nnamespace compute = boost::compute;\n\nBOOST_AUTO_TEST_CASE(transform_if_odd)\n{\n    using boost::compute::abs;\n    using boost::compute::lambda::_1;\n\n    int data[] = { -2, -3, -4, -5, -6, -7, -8, -9 };\n    compute::vector<int> vector(data, data + 8, queue);\n\n    compute::vector<int>::iterator end = compute::transform_if(\n        vector.begin(), vector.end(), vector.begin(), abs<int>(), _1 % 2 != 0, queue\n    );\n    BOOST_CHECK_EQUAL(std::distance(vector.begin(), end), 4);\n\n    CHECK_RANGE_EQUAL(int, 4, vector, (+3, +5, +7, +9));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "c6c814bbb96d7394c9f66e4d20e4a8e54cc0cd0e", "size": 1277, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_transform_if.cpp", "max_stars_repo_name": "junmuz/compute", "max_stars_repo_head_hexsha": "b979ff527d3f1cb6e073da29b167bf02b3218c9a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-03-18T01:14:13.000Z", "max_stars_repo_stars_event_max_datetime": "2015-03-18T01:14:13.000Z", "max_issues_repo_path": "test/test_transform_if.cpp", "max_issues_repo_name": "junmuz/compute", "max_issues_repo_head_hexsha": "b979ff527d3f1cb6e073da29b167bf02b3218c9a", "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/test_transform_if.cpp", "max_forks_repo_name": "junmuz/compute", "max_forks_repo_head_hexsha": "b979ff527d3f1cb6e073da29b167bf02b3218c9a", "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.925, "max_line_length": 84, "alphanum_fraction": 0.6076742365, "num_tokens": 308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300698514777, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.49124726167337246}}
{"text": "// Copyright 2019 Hans Dembinski\n//\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n//[ guide_axis_circular\n\n#include <boost/histogram/axis.hpp>\n#include <limits>\n\nint main() {\n  using namespace boost::histogram;\n\n  // make a circular regular axis ... [0, 180), [180, 360), [0, 180) ....\n  using opts = decltype(axis::option::overflow | axis::option::circular);\n  auto r = axis::regular<double, use_default, use_default, opts>{2, 0., 360.};\n  assert(r.index(-180) == 1);\n  assert(r.index(0) == 0);\n  assert(r.index(180) == 1);\n  assert(r.index(360) == 0);\n  assert(r.index(540) == 1);\n  assert(r.index(720) == 0);\n  // special values are mapped to the overflow bin index\n  assert(r.index(std::numeric_limits<double>::infinity()) == 2);\n  assert(r.index(-std::numeric_limits<double>::infinity()) == 2);\n  assert(r.index(std::numeric_limits<double>::quiet_NaN()) == 2);\n\n  // since the regular axis is the most common circular axis, there exists an alias\n  auto c = axis::circular<>{2, 0., 360.};\n  assert(r == c);\n\n  // make a circular integer axis\n  auto i = axis::integer<int, use_default, axis::option::circular_t>{1, 4};\n  assert(i.index(0) == 2);\n  assert(i.index(1) == 0);\n  assert(i.index(2) == 1);\n  assert(i.index(3) == 2);\n  assert(i.index(4) == 0);\n  assert(i.index(5) == 1);\n}\n\n//]\n", "meta": {"hexsha": "b4b8b49414740feb5ab74bf37b448f7a80972d05", "size": 1402, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/histogram/examples/guide_axis_circular.cpp", "max_stars_repo_name": "cpp-pm/boost", "max_stars_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "libs/histogram/examples/guide_axis_circular.cpp", "max_issues_repo_name": "cpp-pm/boost", "max_issues_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "libs/histogram/examples/guide_axis_circular.cpp", "max_forks_repo_name": "cpp-pm/boost", "max_forks_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 31.8636363636, "max_line_length": 83, "alphanum_fraction": 0.6469329529, "num_tokens": 430, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.4912472529632689}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// QuickBook Example\n\n// Copyright (c) 2011-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//[rings\n/*`\nShows how to access the exterior ring (one) \nand interior rings (zero or more) of a polygon.\nAlso shows the related ring_type and interior_type.\n*/\n\n#include <iostream>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n\n\nint main()\n{\n    typedef boost::geometry::model::d2::point_xy<double> point;\n    typedef boost::geometry::model::polygon<point> polygon_type;\n\n    polygon_type poly;\n    \n    typedef boost::geometry::ring_type<polygon_type>::type ring_type;\n    ring_type& ring = boost::geometry::exterior_ring(poly);\n    \n    // For a ring of model::polygon, you can call \"push_back\".\n    // (internally, it is done using a traits::push_back class)\n    ring.push_back(point(0, 0));\n    ring.push_back(point(0, 5));\n    ring.push_back(point(5, 4));\n    ring.push_back(point(0, 0));\n    \n    ring_type inner;\n    inner.push_back(point(1, 1));\n    inner.push_back(point(2, 1));\n    inner.push_back(point(2, 2));\n    inner.push_back(point(1, 1));\n\n    typedef boost::geometry::interior_type<polygon_type>::type int_type;\n    int_type& interiors = boost::geometry::interior_rings(poly);\n    interiors.push_back(inner);\n\n    std::cout << boost::geometry::dsv(poly) << std::endl;\n    \n    // So int_type defines a collection of rings, \n    // which is a Boost.Range compatible range\n    // The type of an element of the collection is the very same ring type again.\n    // We show that.\n    typedef boost::range_value<int_type>::type int_ring_type;\n    \n    std::cout \n        << std::boolalpha\n        << boost::is_same<ring_type, int_ring_type>::value \n        << std::endl;\n\n    return 0;\n}\n\n//]\n\n//[rings_output\n/*`\nOutput:\n[pre\n(((0, 0), (0, 5), (5, 4), (0, 0)), ((1, 1), (2, 1), (2, 2), (1, 1)))\ntrue\n]\n*/\n//]\n", "meta": {"hexsha": "81f1ded651b43b2aa6b00a932f53524e3eed6914", "size": 2142, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/geometry/doc/src/examples/core/rings.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2016-04-12T16:29:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-28T11:01:57.000Z", "max_issues_repo_path": "boost/libs/geometry/doc/src/examples/core/rings.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-10-31T19:35:14.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-04T17:11:27.000Z", "max_forks_repo_path": "boost/libs/geometry/doc/src/examples/core/rings.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-09-09T02:38:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-30T00:24:24.000Z", "avg_line_length": 27.4615384615, "max_line_length": 81, "alphanum_fraction": 0.6676003735, "num_tokens": 591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587586, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.4912472529153125}}
{"text": "#include <deque>\n#include <vector>\n#include <list>\n#include <iostream>\n#include <boost/graph/vector_as_graph.hpp>\n#include <boost/graph/topological_sort.hpp>\n#include <boost/range.hpp>\n#include <boost/range/adaptor/indexed.hpp>\n\n\nint main(){\n    using namespace boost;\n\n    const char * tasks[] = {\n        \"pick up kids from school\",\n        \"buy groceries (and snack)\",\n        \"get cash at ATM\",\n        \"drop off kids at soccer practice\",\n        \"cook dinner\",\n        \"pick up kids from soccer\",\n        \"eat dinner\"\n    };\n\n    const int n_tasks = sizeof(tasks) /sizeof(char*);\n\n    std::vector<std::list<int>> g(n_tasks);\n    g[0].push_back(3);\n    g[1].push_back(3);\n    g[1].push_back(4);\n    g[2].push_back(1);\n    g[3].push_back(5);\n    g[4].push_back(6);\n    g[5].push_back(6);\n\n    std::deque<int> topo_order;\n\n    topological_sort(g, std::front_inserter(topo_order),\n            vertex_index_map(identity_property_map()));\n\n    for(const auto& [index, i] : topo_order \n            | boost::adaptors::indexed())\n    {\n        std::cout << tasks[i.head] << std::endl;\n    }\n}\n", "meta": {"hexsha": "a6b03be55465cfb5a8541ac6572ec5757b2f14c2", "size": 1089, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "chapter1/topo-sort1.cpp", "max_stars_repo_name": "Zilleplus/boost_graph", "max_stars_repo_head_hexsha": "65d6dee7d060fc9aa76a822fde55c244e9468b0d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapter1/topo-sort1.cpp", "max_issues_repo_name": "Zilleplus/boost_graph", "max_issues_repo_head_hexsha": "65d6dee7d060fc9aa76a822fde55c244e9468b0d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapter1/topo-sort1.cpp", "max_forks_repo_name": "Zilleplus/boost_graph", "max_forks_repo_head_hexsha": "65d6dee7d060fc9aa76a822fde55c244e9468b0d", "max_forks_repo_licenses": ["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.6739130435, "max_line_length": 56, "alphanum_fraction": 0.6014692378, "num_tokens": 290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300698514777, "lm_q2_score": 0.6992544147913993, "lm_q1q2_score": 0.4912472528673559}}
{"text": "//         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#include <nt2/elliptic/include/functions/scalar/ellipke.hpp>\n#include <nt2/elliptic/include/functions/simd/ellipke.hpp>\n\n#include <nt2/include/constants/pi.hpp>\n#include <nt2/include/constants/zero.hpp>\n#include <nt2/include/constants/one.hpp>\n#include <nt2/include/constants/half.hpp>\n#include <nt2/include/constants/two.hpp>\n#include <nt2/include/constants/pio_2.hpp>\n#include <nt2/include/constants/inf.hpp>\n#include <nt2/include/constants/minf.hpp>\n#include <nt2/include/constants/nan.hpp>\n#include <nt2/include/constants/eps.hpp>\n#include <nt2/include/functions/sin.hpp>\n#include <nt2/include/functions/cos.hpp>\n#include <boost/dispatch/functor/meta/call.hpp>\n#include <boost/fusion/include/vector_tie.hpp>\n\n#include <nt2/sdk/unit/module.hpp>\n#include <nt2/sdk/unit/tests/ulp.hpp>\n#include <nt2/sdk/unit/tests/type_expr.hpp>\n\nNT2_TEST_CASE_TPL ( ellipke_real__1_0,  NT2_REAL_TYPES)\n{\n\n  using nt2::ellipke;\n  using nt2::tag::ellipke_;\n  T a[] = {nt2::One<T>(), nt2::Zero<T>(), nt2::Half<T>(), nt2::Two<T>()};\n  size_t N =  sizeof(a)/sizeof(T);\n  T e1[] = {nt2::Inf<T>(), nt2::Pio_2<T>(), T(1.854074677301372), nt2::Nan<T>()};\n  T e2[] = {nt2::One<T>(), nt2::Pio_2<T>(), T(1.350643881047675), nt2::Nan<T>()};\n\n  NT2_TEST_TYPE_IS( (typename boost::dispatch::meta::call<ellipke_(T)>::type)\n                  , (std::pair<T,T>)\n                  );\n  NT2_TEST_TYPE_IS( (typename boost::dispatch::meta::call<ellipke_(T, T)>::type)\n                  , (std::pair<T,T>)\n                  );\n  NT2_TEST_TYPE_IS( (typename boost::dispatch::meta::call<ellipke_(T, T, T&)>::type)\n                  , (T)\n                  );\n  NT2_TEST_TYPE_IS( (typename boost::dispatch::meta::call<ellipke_(T, T, T&, T&)>::type)\n                  , (void)\n                  );\n\n {\n    T s, c;\n    for(size_t i=0; i < N; ++i)\n    {\n      ellipke(a[i],nt2::Eps<T>(), s, c);\n      NT2_TEST_ULP_EQUAL(s, e1[i], 1);\n      NT2_TEST_ULP_EQUAL(c, e2[i], 1);\n    }\n  }\n\n  {\n    T s, c;\n    for(size_t i=0; i < N; ++i)\n    {\n      s = ellipke(a[i], nt2::Eps<T>(), c);\n      NT2_TEST_ULP_EQUAL(s, e1[i], 1);\n      NT2_TEST_ULP_EQUAL(c, e2[i], 1);\n    }\n  }\n\n  {\n    T s, c;\n    for(size_t i=0; i < N; ++i)\n    {\n      boost::fusion::vector_tie(s, c) = ellipke(a[i]);\n      NT2_TEST_ULP_EQUAL(s, e1[i], 1);\n      NT2_TEST_ULP_EQUAL(c, e2[i], 1);\n    }\n  }\n\n  {\n    for(size_t i=0; i < N; ++i)\n    {\n      std::pair<T,T> p = ellipke(a[i]);\n      NT2_TEST_ULP_EQUAL(p.first,  e1[i], 1);\n      NT2_TEST_ULP_EQUAL(p.second, e2[i], 1);\n    }\n  }\n}\n", "meta": {"hexsha": "9c2ef8da8bb3f41474efa09005eee5d5c496ba83", "size": 2937, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/core/elliptic/unit/scalar/ellipke.cpp", "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/elliptic/unit/scalar/ellipke.cpp", "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/elliptic/unit/scalar/ellipke.cpp", "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": 31.9239130435, "max_line_length": 88, "alphanum_fraction": 0.5740551583, "num_tokens": 940, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300698514778, "lm_q2_score": 0.6992544085240401, "lm_q1q2_score": 0.4912472484643477}}
{"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#include <nt2/exponential/include/functions/significants.hpp>\n\n#include <nt2/sdk/functor/meta/call.hpp>\n#include <boost/simd/sdk/simd/native.hpp>\n#include <nt2/sdk/unit/tests/type_expr.hpp>\n#include <nt2/sdk/unit/tests/ulp.hpp>\n#include <nt2/include/functions/splat.hpp>\n#include <nt2/sdk/unit/module.hpp>\n#include <boost/simd/sdk/config.hpp>\n#include <boost/simd/sdk/simd/io.hpp>\n\n#include <nt2/include/constants/mone.hpp>\n#include <nt2/include/constants/one.hpp>\n#include <nt2/include/constants/zero.hpp>\n#include <nt2/include/constants/inf.hpp>\n#include <nt2/include/constants/minf.hpp>\n#include <nt2/include/constants/nan.hpp>\n\nNT2_TEST_CASE_TPL ( significants,  NT2_SIMD_REAL_TYPES)\n{\n  using nt2::significants;\n  using nt2::tag::significants_;\n  using boost::simd::native;\n  typedef BOOST_SIMD_DEFAULT_EXTENSION  ext_t;\n  typedef native<T,ext_t>                  vT;\n  typedef typename nt2::meta::as_integer<vT>::type ivT;\n\n  typedef typename nt2::meta::call<significants_(vT, ivT)>::type r_t;\n  typedef vT wished_r_t;\n\n  // return type conformity test\n  NT2_TEST_TYPE_IS(r_t, wished_r_t);\n\n\n  // specific values tests\n#ifndef BOOST_SIMD_NO_INVALIDS\n  NT2_TEST_ULP_EQUAL(significants(nt2::Inf<vT>(), 1), nt2::Inf<r_t>(), 0.5);\n  NT2_TEST_ULP_EQUAL(significants(nt2::Minf<vT>(), 1), nt2::Minf<r_t>(), 0.5);\n  NT2_TEST_ULP_EQUAL(significants(nt2::Nan<vT>(), 1), nt2::Nan<r_t>(), 0.5);\n#endif\n  NT2_TEST_ULP_EQUAL(significants(nt2::splat<vT>(25.34), nt2::splat<ivT>(1)), nt2::splat<vT>(30), 0.5);\n  NT2_TEST_ULP_EQUAL(significants(nt2::splat<vT>(25.34), nt2::splat<ivT>(2)), nt2::splat<vT>(25), 0.5);\n  NT2_TEST_ULP_EQUAL(significants(nt2::splat<vT>(25.34), nt2::splat<ivT>(3)), nt2::splat<vT>(25.3), 0.5);\n  NT2_TEST_ULP_EQUAL(significants(nt2::splat<vT>(25.34), nt2::splat<ivT>(4)), nt2::splat<vT>(25.34), 0.5);\n  NT2_TEST_ULP_EQUAL(significants(nt2::splat<vT>(-25.34), nt2::splat<ivT>(1)), nt2::splat<vT>(-30), 0.5);\n  NT2_TEST_ULP_EQUAL(significants(nt2::splat<vT>(-25.34), nt2::splat<ivT>(2)), nt2::splat<vT>(-25), 0.5);\n  NT2_TEST_ULP_EQUAL(significants(nt2::splat<vT>(-25.34), nt2::splat<ivT>(3)), nt2::splat<vT>(-25.3), 0.5);\n  NT2_TEST_ULP_EQUAL(significants(nt2::splat<vT>(-25.34), nt2::splat<ivT>(4)), nt2::splat<vT>(-25.34), 0.5);\n}\n", "meta": {"hexsha": "617b892c9aa22151a791696357c8edd7d5414269", "size": 2648, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/core/exponential/unit/simd/significants.cpp", "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/exponential/unit/simd/significants.cpp", "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/exponential/unit/simd/significants.cpp", "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": 46.4561403509, "max_line_length": 108, "alphanum_fraction": 0.6540785498, "num_tokens": 872, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.4912472442052088}}
{"text": "//\n// Created by Alex Beccaro on 18/01/18.\n//\n\n#define BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n#include \"../../src/problems/1-50/45/problem45.hpp\"\n\nBOOST_AUTO_TEST_SUITE( Problem45 )\n\n    BOOST_AUTO_TEST_CASE( Example ) {\n        auto res = problems::problem45::solve(2);\n        BOOST_CHECK_EQUAL(res, 40755);\n    }\n\n    BOOST_AUTO_TEST_CASE( Solution ) {\n        auto res = problems::problem45::solve();\n        BOOST_CHECK_EQUAL(res, 1533776805);\n    }\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "aaba09ba4d11fb588ef4109f2af3bb07fac0e315", "size": 500, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/1-50/test_problem45.cpp", "max_stars_repo_name": "abeccaro/project-euler", "max_stars_repo_head_hexsha": "c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T10:17:15.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-25T10:17:15.000Z", "max_issues_repo_path": "tests/1-50/test_problem45.cpp", "max_issues_repo_name": "abeccaro/project-euler", "max_issues_repo_head_hexsha": "c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3", "max_issues_repo_licenses": ["MIT"], "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/1-50/test_problem45.cpp", "max_forks_repo_name": "abeccaro/project-euler", "max_forks_repo_head_hexsha": "c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3", "max_forks_repo_licenses": ["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.8095238095, "max_line_length": 51, "alphanum_fraction": 0.68, "num_tokens": 128, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7025300573952052, "lm_q2_score": 0.6992544147913993, "lm_q1q2_score": 0.4912472441572524}}
{"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_STRATEGIES_SPHERICAL_AREA_HUILLER_HPP\n#define BOOST_GEOMETRY_STRATEGIES_SPHERICAL_AREA_HUILLER_HPP\n\n\n\n#include <boost/geometry/strategies/spherical/distance_haversine.hpp>\n\n#include <boost/geometry/core/radian_access.hpp>\n#include <boost/geometry/util/math.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\nnamespace strategy { namespace area\n{\n\n\n\n/*!\n\\brief Area calculation by spherical excess / Huiller's formula\n\\ingroup strategies\n\\tparam PointOfSegment point type of segments of rings/polygons\n\\tparam CalculationType \\tparam_calculation\n\\author Barend Gehrels. Adapted from:\n- http://www.soe.ucsc.edu/~pang/160/f98/Gems/GemsIV/sph_poly.c\n- http://williams.best.vwh.net/avform.htm\n\\note The version in Gems didn't account for polygons crossing the 180 meridian.\n\\note This version works for convex and non-convex polygons, for 180 meridian\ncrossing polygons and for polygons with holes. However, some cases (especially\n180 meridian cases) must still be checked.\n\\note The version which sums angles, which is often seen, doesn't handle non-convex\npolygons correctly.\n\\note The version which sums longitudes, see\nhttp://trs-new.jpl.nasa.gov/dspace/bitstream/2014/40409/1/07-03.pdf, is simple\nand works well in most cases but not in 180 meridian crossing cases. This probably\ncould be solved.\n\n\\note This version is made for spherical equatorial coordinate systems\n\n\\qbk{\n\n[heading Example]\n[area_with_strategy]\n[area_with_strategy_output]\n\n\n[heading See also]\n[link geometry.reference.algorithms.area.area_2_with_strategy area (with strategy)]\n}\n\n*/\ntemplate\n<\n    typename PointOfSegment,\n    typename CalculationType = void\n>\nclass huiller\n{\ntypedef typename boost::mpl::if_c\n    <\n        boost::is_void<CalculationType>::type::value,\n        typename select_most_precise\n            <\n                typename coordinate_type<PointOfSegment>::type,\n                double\n            >::type,\n        CalculationType\n    >::type calculation_type;\n\nprotected :\n    struct excess_sum\n    {\n        calculation_type sum;\n\n        // Distances are calculated on unit sphere here\n        strategy::distance::haversine<PointOfSegment, PointOfSegment>\n                distance_over_unit_sphere;\n\n\n        inline excess_sum()\n            : sum(0)\n            , distance_over_unit_sphere(1)\n        {}\n        inline calculation_type area(calculation_type radius) const\n        {\n            return - sum * radius * radius;\n        }\n    };\n\npublic :\n    typedef calculation_type return_type;\n    typedef PointOfSegment segment_point_type;\n    typedef excess_sum state_type;\n\n    inline huiller(calculation_type radius = 1.0)\n        : m_radius(radius)\n    {}\n\n    inline void apply(PointOfSegment const& p1,\n                PointOfSegment const& p2,\n                excess_sum& state) const\n    {\n        if (! geometry::math::equals(get<0>(p1), get<0>(p2)))\n        {\n            calculation_type const half = 0.5;\n            calculation_type const two = 2.0;\n            calculation_type const four = 4.0;\n            calculation_type const two_pi = two * geometry::math::pi<calculation_type>();\n            calculation_type const half_pi = half * geometry::math::pi<calculation_type>();\n\n            // Distance p1 p2\n            calculation_type a = state.distance_over_unit_sphere.apply(p1, p2);\n\n            // Sides on unit sphere to south pole\n            calculation_type b = half_pi - geometry::get_as_radian<1>(p2);\n            calculation_type c = half_pi - geometry::get_as_radian<1>(p1);\n\n            // Semi parameter\n            calculation_type s = half * (a + b + c);\n\n            // E: spherical excess, using l'Huiller's formula\n            // [tg(e / 4)]2   =   tg[s / 2]  tg[(s-a) / 2]  tg[(s-b) / 2]  tg[(s-c) / 2]\n            calculation_type E = four * atan(sqrt(geometry::math::abs(tan(s / two)\n                    * tan((s - a) / two)\n                    * tan((s - b) / two)\n                    * tan((s - c) / two))));\n\n            E = geometry::math::abs(E);\n\n            // In right direction: positive, add area. In left direction: negative, subtract area.\n            // Longitude comparisons are not so obvious. If one is negative, other is positive,\n            // we have to take the dateline into account.\n            // TODO: check this / enhance this, should be more robust. See also the \"grow\" for ll\n            // TODO: use minmax or \"smaller\"/\"compare\" strategy for this\n            calculation_type lon1 = geometry::get_as_radian<0>(p1) < 0\n                ? geometry::get_as_radian<0>(p1) + two_pi\n                : geometry::get_as_radian<0>(p1);\n\n            calculation_type lon2 = geometry::get_as_radian<0>(p2) < 0\n                ? geometry::get_as_radian<0>(p2) + two_pi\n                : geometry::get_as_radian<0>(p2);\n\n            if (lon2 < lon1)\n            {\n                E = -E;\n            }\n\n            state.sum += E;\n        }\n    }\n\n    inline return_type result(excess_sum const& state) const\n    {\n        return state.area(m_radius);\n    }\n\nprivate :\n    /// Radius of the sphere\n    calculation_type m_radius;\n};\n\n#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\n\nnamespace services\n{\n\n\ntemplate <typename Point>\nstruct default_strategy<spherical_equatorial_tag, Point>\n{\n    typedef strategy::area::huiller<Point> type;\n};\n\n// Note: spherical polar coordinate system requires \"get_as_radian_equatorial\"\n/***template <typename Point>\nstruct default_strategy<spherical_polar_tag, Point>\n{\n    typedef strategy::area::huiller<Point> type;\n};***/\n\n} // namespace services\n\n#endif // DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\n\n\n}} // namespace strategy::area\n\n\n\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_STRATEGIES_SPHERICAL_AREA_HUILLER_HPP\n", "meta": {"hexsha": "1bef9b5f2f6f3fbc832906b9bbcf34ff348f57b8", "size": 6052, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/boost/geometry/strategies/spherical/area_huiller.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/geometry/strategies/spherical/area_huiller.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/geometry/strategies/spherical/area_huiller.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": 29.8128078818, "max_line_length": 98, "alphanum_fraction": 0.6574686054, "num_tokens": 1455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.779992900254107, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.49121973337558067}}
{"text": "/**\n * @file maximum_coverage_test.cpp\n * @brief\n * @author Piotr Smulewicz\n * @version 1.0\n * @date 2014-02-17\n */\n\n#include \"test_utils/logger.hpp\"\n#include \"test_utils/test_result_check.hpp\"\n\n#include \"paal/utils/functors.hpp\"\n#include \"paal/greedy/set_cover/maximum_coverage.hpp\"\n\n#include <boost/test/unit_test.hpp>\n#include <boost/range/irange.hpp>\n\n#include <vector>\n#include <iterator>\n#include <cmath>\n\nBOOST_AUTO_TEST_CASE(MaximumCoverage) {\n    LOGLN(\"MaximumCoverage\");\n    const int OPTIMAL = 14;\n    const int NUMBER_OF_SETS = 2;\n    const double APPROXIMATION_RATIO = 1 - 1 / std::exp(1.0);\n    std::vector<std::vector<int>> sets_element = { { 1, 2 },\n                                                   { 3, 4, 5, 6 },\n                                                   { 7, 8, 9, 10, 11, 12, 13,\n                                                     0 },\n                                                   { 1, 3, 5, 7, 9, 11, 13 },\n                                                   { 2, 4, 6, 8, 10, 12, 0 } };\n    auto sets = boost::irange(0, 5);\n    std::vector<int> result;\n    auto element_index = paal::utils::identity_functor{};\n    auto cost = paal::greedy::maximum_coverage(\n        sets, paal::utils::make_array_to_functor(sets_element),\n        std::back_inserter(result), element_index, NUMBER_OF_SETS);\n    check_result(cost, OPTIMAL, APPROXIMATION_RATIO,\n                 paal::utils::greater_equal());\n}\n", "meta": {"hexsha": "367aa59678d3aed9f8bbbcdbca91d51f63cc3e74", "size": 1435, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/greedy/max_coverage_test.cpp", "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": "test/greedy/max_coverage_test.cpp", "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": "test/greedy/max_coverage_test.cpp", "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": 34.1666666667, "max_line_length": 79, "alphanum_fraction": 0.5442508711, "num_tokens": 386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.629774621301746, "lm_q1q2_score": 0.49121973337558067}}
{"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_FNMA_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_FNMA_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n\n    @ingroup group-arithmetic\n    This function object computes the negated (fused) multiply add of\n    its three parameters.\n\n\n    @par Header <boost/simd/function/fnma.hpp>\n\n    @par Notes\n    The call `fnma(x, y, z)` is similar to `-x*y-z`\n\n    But really conformant fused multiply/add also implies\n\n    - only one rounding\n\n    - no \"intermediate\" overflow\n\n    fnma provides this for all integral types (however, using it on unsigned types\n    is not recommanded for obvious reasons)  and also each time it is reasonable\n    in terms of performance for floating ones (i.e. if the system has the hard\n    wired capability).\n\n    If you need pedantic fnma capabilities in all circumstances in your own\n    code you can use the pedantic_ decorator (can be very expensive).\n\n    @par Decorators\n    - pedantic_ ensures the fnma properties and allows SIMD acceleration if available.\n\n    @see fms, fma, fnms\n\n    @par Example:\n\n      @snippet fnma.cpp fnma\n\n    @par Possible output:\n\n      @snippet fnma.txt fnma\n\n  **/\n  Value fnma(Value const& x, Value const& y, Value const& z);\n} }\n#endif\n\n#include <boost/simd/function/scalar/fnma.hpp>\n#include <boost/simd/function/simd/fnma.hpp>\n\n#endif\n", "meta": {"hexsha": "e2b337acabbef933e8eab761a21c3ea1ef148608", "size": 1751, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/fnma.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/fnma.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/fnma.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": 26.5303030303, "max_line_length": 100, "alphanum_fraction": 0.6344945745, "num_tokens": 396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.49121973337558056}}
{"text": "///////////////////////////////////////////////////////////////////////////////////////\n// survival::modelss::exponential::scalar::meta::is_survival_model.hpp         \t\t //\n//                                                                                   //\n//  Copyright 2009 Erwann Rogard. Distributed under the Boost                        //\n//  Software License, Version 1.0. (See accompanying file                            //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)                 //\n///////////////////////////////////////////////////////////////////////////////////////\n#ifndef BOOST_STATISTICS_DETAIL_DISTRIBUTION_SURVIVAL_MODELS_EXPONENTIAL_SCALAR_META_IS_SURVIVAL_MODEL_HPP_ER_2009\n#define BOOST_STATISTICS_DETAIL_DISTRIBUTION_SURVIVAL_MODELS_EXPONENTIAL_SCALAR_META_IS_SURVIVAL_MODEL_HPP_ER_2009\n#include <boost/mpl/bool.hpp>\n#include <boost/statistics/detail/distribution/survival/models/common/meta/is_survival_model.hpp>\n#include <boost/statistics/detail/distribution/survival/models/exponential/scalar/model.hpp>\n\nnamespace boost {\nnamespace statistics{\nnamespace detail{\nnamespace distribution{\nnamespace survival {\nnamespace meta{\n\n    template<typename T,typename L>\n    struct is_survival_model< exponential_model<T,L> > \n        : boost::mpl::bool_<true>{};\n    \n}// meta\n}// survival\n}// distribution\n}// detail\n}// statistics\n}// boost\n\n#endif", "meta": {"hexsha": "6478ea80ea3fe56ecb9966b49ad8d1557d02f3a7", "size": 1401, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "distribution_survival/boost/statistics/detail/distribution/survival/models/exponential/scalar/meta/is_survival_model.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_survival/boost/statistics/detail/distribution/survival/models/exponential/scalar/meta/is_survival_model.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_survival/boost/statistics/detail/distribution/survival/models/exponential/scalar/meta/is_survival_model.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": 43.78125, "max_line_length": 114, "alphanum_fraction": 0.6009992862, "num_tokens": 273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.49121973337558056}}
{"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 a qp allocating forces to track a desired centroidal wrench.\n *\n */\n\n#pragma once\n\n#include <Eigen/Dense>\n#include <eiquadprog/eiquadprog-fast.hpp>\n\nnamespace blmc_controllers\n{\ntypedef Eigen::Array<double, 6, 1> Array6d;\ntypedef Eigen::Matrix<double, 6, 1> Vector6d;\n\n/**\n * @brief Impedance controller between any two frames of the robot.\n */\nclass CentroidalForceQPController\n{\npublic:\n    /**\n     * @brief Construct a new ImpedanceController object.\n     */\n    CentroidalForceQPController();\n\n    /**\n     * @brief Initialize the internal data. None real-time safe method.\n     *\n     * @param number_endeffectors Maximum number of endeffectors in the problem.\n     * @param friction_coeff Floor friction coefficient to use.\n     * @param qp_penalty_lin The penalty weight for the linear wcom violation.\n     * @param qp_penalty_ang The penalty weight for the angular wcom violation.\n     */\n    void initialize(int number_endeffectors, double friction_coeff,\n                    double qp_penalty_lin, double qp_penalty_ang);\n\n    /**\n     * @brief Computes the centroidal wrench using a PD controller.\n     * \n     * @param w_com The desired centroidal wrench to track.\n     * @param relative_position_endeff The relative position of the endeffectors\n     *     with respect to the center of mass.\n     */\n    void run(Eigen::Ref<const Vector6d> w_com,\n             Eigen::Ref<const Eigen::VectorXd> relative_position_endeff,\n             Eigen::Ref<const Eigen::VectorXd> cnt_array);\n\n    /**\n     * @brief Get the computed desired forces\n     *\n     * @return Eigen::VectorXd&\n     */\n    Eigen::VectorXd& get_forces();\n\nprivate:  // attributes\n    /** @brief Output forces */\n    Eigen::VectorXd forces_;\n    Eigen::VectorXd sol_;\n\n    Eigen::MatrixXd hess_;\n    Eigen::MatrixXd ce_;\n    Eigen::MatrixXd ce_new_;\n    Eigen::MatrixXd ci_;\n\n    Eigen::VectorXd g0_;\n    Eigen::VectorXd ci0_;\n\n    int nb_eff_;\n\n    double mu_;\n\n    double qp_penalty_lin_;\n    double qp_penalty_ang_;\n\n    eiquadprog::solvers::EiquadprogFast qp_;\n\n};\n\n}  // namespace blmc_controllers\n", "meta": {"hexsha": "5eb63f87a557ce2d67af8d135b83ecaed211f4a7", "size": 2224, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/blmc_controllers/centroidal_force_qp_controller.hpp", "max_stars_repo_name": "avadesh02/blmc_controllers", "max_stars_repo_head_hexsha": "572ead0eabd5b4d1dbcec77c447f733f204fb97f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-17T17:51:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-17T17:51:52.000Z", "max_issues_repo_path": "include/blmc_controllers/centroidal_force_qp_controller.hpp", "max_issues_repo_name": "avadesh02/blmc_controllers", "max_issues_repo_head_hexsha": "572ead0eabd5b4d1dbcec77c447f733f204fb97f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-12-17T11:08:11.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-11T16:47:45.000Z", "max_forks_repo_path": "include/blmc_controllers/centroidal_force_qp_controller.hpp", "max_forks_repo_name": "avadesh02/blmc_controllers", "max_forks_repo_head_hexsha": "572ead0eabd5b4d1dbcec77c447f733f204fb97f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-17T11:04:40.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-17T11:04:40.000Z", "avg_line_length": 25.8604651163, "max_line_length": 81, "alphanum_fraction": 0.681205036, "num_tokens": 528, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.49121973337558056}}
{"text": "/* ----------------------------------------------------------------------------\n * Copyright 2021, Jesus Tordesillas Torres, Aerospace Controls Laboratory\n * Massachusetts Institute of Technology\n * All Rights Reserved\n * Authors: Jesus Tordesillas, et al.\n * See LICENSE file for the license information\n * -------------------------------------------------------------------------- */\n\n#ifndef SOLVER_IPOPT_HPP\n#define SOLVER_IPOPT_HPP\n\n#include <Eigen/Dense>\n#include <Eigen/StdVector>\n\n#include <iomanip>  //set precision\n#include <iostream>\n\n#include \"panther_types.hpp\"\n#include \"utils.hpp\"\n#include <casadi/casadi.hpp>\n#include \"timer.hpp\"\n#include \"separator.hpp\"\n#include \"octopus_search.hpp\"\n\n// For the yaw search:\n#include <boost/graph/astar_search.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/random.hpp>\n#include <boost/random.hpp>\n\ntypedef PANTHER_timers::Timer MyTimer;\n\nclass SolverIpopt\n{\npublic:\n  SolverIpopt(mt::parameters &par, std::shared_ptr<mt::log> log_ptr);\n\n  ~SolverIpopt();\n\n  bool optimize();\n\n  // setters\n  void setMaxRuntimeKappaAndMu(double runtime, double kappa, double mu);\n  bool setInitStateFinalStateInitTFinalT(mt::state initial_state, mt::state final_state, double t_init,\n                                         double &t_final);\n  void setHulls(ConvexHullsOfCurves_Std &hulls);\n  void setSimpsonFeatureSamples(const std::vector<Eigen::Vector3d> &samples,\n                                const std::vector<Eigen::Vector3d> &w_velsampleswrtworld);\n  void setFocusOnObstacle(bool focus_on_obstacle)\n  {\n    focus_on_obstacle_ = focus_on_obstacle;\n  }\n  mt::trajectory traj_solution_;\n\n  // getters\n  void getPlanes(std::vector<Hyperplane3D> &planes);\n  int getNumOfLPsRun();\n  int getNumOfQCQPsRun();\n  void getSolution(mt::PieceWisePol &solution);\n  double getTimeNeeded();\n\n  int B_SPLINE = 1;  // B-Spline Basis\n  int MINVO = 2;     // Minimum volume basis\n  int BEZIER = 3;    // Bezier basis\n\n  bool checkGradientsUsingFiniteDiff();\n\n  mt::parameters par_;\n\nprotected:\nprivate:\n  // https://stackoverflow.com/a/11498248/6057617\n  double wrapFromMPitoPi(double x)\n  {\n    x = fmod(x + M_PI, 2 * M_PI);\n    if (x < 0)\n      x += 2 * M_PI;\n    return x - M_PI;\n  }\n\n  bool getIntersectionWithPlane(const Eigen::Vector3d &P1, const Eigen::Vector3d &P2, const Eigen::Vector4d &coeff,\n                                Eigen::Vector3d &intersection);\n\n  void addObjective();\n  void addConstraints();\n\n  void saturateQ(std::vector<Eigen::Vector3d> &q);\n\n  // transform functions (with Eigen)\n  void transformPosBSpline2otherBasis(const Eigen::Matrix<double, 3, 4> &Qbs, Eigen::Matrix<double, 3, 4> &Qmv,\n                                      int interval);\n  void transformVelBSpline2otherBasis(const Eigen::Matrix<double, 3, 3> &Qbs, Eigen::Matrix<double, 3, 3> &Qmv,\n                                      int interval);\n\n  void generateRandomGuess();\n  bool generateAStarGuess();\n  void generateStraightLineGuess();\n\n  void printStd(const std::vector<Eigen::Vector3d> &v);\n  void printStd(const std::vector<double> &v);\n  void generateGuessNDFromQ(const std::vector<Eigen::Vector3d> &q, std::vector<Eigen::Vector3d> &n,\n                            std::vector<double> &d);\n\n  void fillPlanesFromNDQ(const std::vector<Eigen::Vector3d> &n, const std::vector<double> &d,\n                         const std::vector<Eigen::Vector3d> &q);\n\n  void generateRandomD(std::vector<double> &d);\n  void generateRandomN(std::vector<Eigen::Vector3d> &n);\n  void generateRandomQ(std::vector<Eigen::Vector3d> &q);\n\n  void printQVA(const std::vector<Eigen::Vector3d> &q);\n\n  void printQND(std::vector<Eigen::Vector3d> &q, std::vector<Eigen::Vector3d> &n, std::vector<double> &d);\n\n  void findCentroidHull(const Polyhedron_Std &hull, Eigen::Vector3d &centroid);\n\n  casadi::DM generateYawGuess(casadi::DM matrix_qp_guess, casadi::DM all_w_fe, double y0, double ydot0, double ydotf,\n                              double t0, double tf);\n\n  std::vector<Eigen::Vector3d> n_;  // Each n_[i] has 3 elements (nx,ny,nz)\n  std::vector<double> d_;           // d_[i] has 1 element\n\n  mt::PieceWisePol pwp_solution_;\n\n  int basis_ = B_SPLINE;\n\n  int p_ = 5;\n  int M_;\n  int N_;\n\n  int Ny_;\n\n  double index_instruction_;  // hack\n\n  int num_of_normals_;\n\n  int num_of_obst_;\n  int num_of_segments_;\n\n  std::vector<Hyperplane3D> planes_;\n\n  Eigen::RowVectorXd knots_;\n  double t_init_;\n  double t_final_;\n  double deltaT_;\n\n  mt::state initial_state_;\n  mt::state final_state_;\n\n  Eigen::Vector3d q0_, q1_, q2_, qNm2_, qNm1_, qN_;\n\n  ConvexHullsOfCurves_Std hulls_;\n\n  MyTimer opt_timer_;\n\n  double max_runtime_ = 2;  //[seconds]\n\n  // Guesses\n  std::vector<Eigen::Vector3d> n_guess_;   // Guesses for the normals\n  std::vector<double> d_guess_;            // Guesses for the d of the planes\n  std::vector<Eigen::Vector3d> qp_guess_;  // Guesses for the position control points\n  std::vector<double> qy_guess_;           // Guesses for the yaw control points\n\n  double kappa_ = 0.2;  // kappa_*max_runtime_ is spent on the initial guess\n  double mu_ = 0.5;     // mu_*max_runtime_ is spent on the optimization\n\n  int num_of_QCQPs_run_ = 0;\n\n  // transformation between the B-spline control points and other basis\n  std::vector<Eigen::Matrix<double, 4, 4>> M_pos_bs2basis_;\n  std::vector<Eigen::Matrix<double, 3, 3>> M_vel_bs2basis_;\n  std::vector<Eigen::Matrix<double, 4, 4>> A_pos_bs_;\n\n  // double a_star_bias_ = 1.0;\n\n  std::unique_ptr<separator::Separator> separator_solver_ptr_;\n  std::unique_ptr<OctopusSearch> octopusSolver_ptr_;\n\n  casadi::Function cf_op_;\n  // casadi::Function cf_op_force_final_pos_;\n  casadi::Function cf_fixed_pos_op_;\n  casadi::Function cf_fit_yaw_;\n  casadi::Function cf_visibility_;\n\n  casadi::DM all_w_fe_;\n  casadi::DM all_w_velfewrtworld_;\n  casadi::DM b_Tmatrixcasadi_c_;\n\n  // auxiliary types\n  // struct location\n  // {\n  //   float y, x;  // lat, long\n  // };\n\n  struct data\n  {\n    float yaw;\n    size_t layer;\n    size_t circle;\n\n    void print()\n    {\n      std::cout << \"yaw= \" << yaw << \", layer= \" << layer << std::endl;\n    }\n  };\n\n  typedef float cost_graph;\n\n  ///////////////////////////////// Things for the yaw search\n  // specify some types\n  // typedef adjacency_list<listS, vecS, undirectedS, no_property, property<edge_weight_t, cost_graph>> mygraph_t;\n  typedef boost::adjacency_list<boost::listS, boost::vecS, boost::directedS, data,\n                                boost::property<boost::edge_weight_t, cost_graph>>\n      mygraph_t;\n  typedef boost::property_map<mygraph_t, boost::edge_weight_t>::type WeightMap;\n  typedef mygraph_t::vertex_descriptor vd;\n  typedef mygraph_t::edge_descriptor edge_descriptor;\n  // typedef std::pair<int, int> edge;\n\n  mygraph_t mygraph_;\n\n  double num_of_yaw_per_layer_;  // = par_.num_of_yaw_per_layer;\n  double num_of_layers_;         // = par_.num_samples_simpson;\n  // WeightMap weightmap_;\n  std::vector<std::vector<vd>> all_vertexes_;\n  casadi::DM vector_yaw_samples_;\n\n  std::shared_ptr<mt::log> log_ptr_;\n\n  casadi::DM eigen2casadi(const Eigen::Vector3d &a);\n\n  bool focus_on_obstacle_;\n\n  // std::unique_ptr<mygraph_t> mygraph_ptr;\n  //////////////////////////////////\n\n  // PImpl idiom\n  // https://www.geeksforgeeks.org/pimpl-idiom-in-c-with-examples/\n  // struct PImpl;\n  // std::unique_ptr<PImpl> m_casadi_ptr_;  // Opaque pointer\n\n  // double Ra_ = 1e10;\n};\n\n// struct SolverIpopt::PImpl  // TODO: Not use PImpl\n// {\n//   casadi::Function casadi_function_;\n//   casadi::DM all_w_fe_;\n// };\n\n#endif", "meta": {"hexsha": "600c51c5d4c4e21c65af982a5355a024fcdbaeb1", "size": 7532, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "panther/include/solver_ipopt.hpp", "max_stars_repo_name": "mit-acl/panther", "max_stars_repo_head_hexsha": "8b6e446a4db5181ec4bd5826cadf553bb4889d64", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 79.0, "max_stars_repo_stars_event_min_datetime": "2021-03-12T03:08:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T09:43:14.000Z", "max_issues_repo_path": "panther/include/solver_ipopt.hpp", "max_issues_repo_name": "NamDinhRobotics/panther", "max_issues_repo_head_hexsha": "385b9ac3775a8df7db17e69c6278f8fcab769507", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2021-03-15T05:22:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T08:54:12.000Z", "max_forks_repo_path": "panther/include/solver_ipopt.hpp", "max_forks_repo_name": "NamDinhRobotics/panther", "max_forks_repo_head_hexsha": "385b9ac3775a8df7db17e69c6278f8fcab769507", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2021-03-14T06:18:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T09:43:12.000Z", "avg_line_length": 30.0079681275, "max_line_length": 117, "alphanum_fraction": 0.6658258099, "num_tokens": 2106, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825006, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.49121972897734256}}
{"text": "/*\n@copyright Louis Dionne 2014\nDistributed under the Boost Software License, Version 1.0.\n(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n */\n\n#include <boost/hana/detail/assert.hpp>\n#include <boost/hana/integer_list.hpp>\n#include <boost/hana/integral.hpp>\n#include <boost/hana/list/instance.hpp>\nusing namespace boost::hana;\n\n\nint main() {\n    //! [main]\n    BOOST_HANA_CONSTANT_ASSERT(to<List>(integer_list<int, 0, 1, 2>) == list(int_<0>, int_<1>, int_<2>));\n    BOOST_HANA_CONSTANT_ASSERT(head(integer_list<int, 0, 1, 2>) == int_<0>);\n    //! [main]\n}\n", "meta": {"hexsha": "4ef961f8a8219a2c1afdb6960c0381ff85c6e891", "size": 587, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/integer_list/integer_list.cpp", "max_stars_repo_name": "rbock/hana", "max_stars_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-05-07T14:29:13.000Z", "max_stars_repo_stars_event_max_datetime": "2015-07-04T10:59:46.000Z", "max_issues_repo_path": "example/integer_list/integer_list.cpp", "max_issues_repo_name": "rbock/hana", "max_issues_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/integer_list/integer_list.cpp", "max_forks_repo_name": "rbock/hana", "max_forks_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.35, "max_line_length": 104, "alphanum_fraction": 0.7052810903, "num_tokens": 166, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6297746074044135, "lm_q1q2_score": 0.49121972253575996}}
{"text": "// ---------------------------------------------------------------------------\n//\n//  This file is part of PermLib.\n//\n// Copyright (c) 2009-2011 Thomas Rehn <thomas@carmen76.de>\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// 3. The name of the author 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 AUTHOR ``AS IS'' AND ANY EXPRESS OR\n// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// ---------------------------------------------------------------------------\n\n\n#define BOOST_TEST_DYN_LINK \n#define BOOST_TEST_MODULE permutation test\n#include <boost/test/unit_test.hpp>\n\n#include <iostream>\n#include <fstream>\n\n#include <permlib/permutation.h>\n#include <permlib/permutationword.h>\n#include <permlib/bsgs.h>\n\nusing namespace permlib;\n\ntemplate<class PERM>\nvoid testPermutation() {\n\tconst unsigned int n = 10;\n\tPERM a(n, \"1 2 5,3 6 7 8, 9 4 10\");\n\tPERM b(n, \"1 2, 5 3 6, 7 8 9 4 10\");\n\t\n\tBOOST_CHECK_EQUAL(a / 1, 4);\n\tBOOST_CHECK_EQUAL(a % 4, 1);\n\tBOOST_CHECK_EQUAL((~a) / 4, 1);\n\n\tBOOST_CHECK_EQUAL(b / 1, 0);\n\tBOOST_CHECK_EQUAL(b % 0, 1);\n\tBOOST_CHECK_EQUAL((~b) / 0, 1);\n\t\n\tfor (unsigned int i = 0; i < n; ++i) {\n\t\tBOOST_CHECK_EQUAL( a / (~a / i), i);\n\t\tBOOST_CHECK_EQUAL( a % (~a % i), i);\n\t}\n\t\n\tPERM c = a * b;\n\tPERM d(a);\n\td *= b;\n\t\n\tBOOST_CHECK(c == d);\n\t\n\td.invertInplace();\n\t\n\tfor (unsigned int i = 0; i < n; ++i) {\n\t\tBOOST_CHECK_EQUAL( c / (d / i), i);\n\t\tBOOST_CHECK_EQUAL( c % (d % i), i);\n\t}\n\t\n\tc *= d;\n\t\n\tBOOST_CHECK(c.isIdentity());\n\t\n\tPERM a2(a);\n\tPERM e(a * a);\n\ta2 *= a2;\n\tBOOST_CHECK( a2 == e );\n}\n\nBOOST_AUTO_TEST_CASE( test_permutation )\n{\n    testPermutation<Permutation>();\n}\n\nBOOST_AUTO_TEST_CASE( test_permutationword )\n{\n    testPermutation<PermutationWord>();\n}\n\nvoid testPermutationOrder(const Permutation& p) {\n\tPermutation q(p);\n\t\n\tfor (boost::uint64_t i = 0; i < p.order() - 1; ++i) {\n\t\tBOOST_CHECK( ! q.isIdentity() );\n\t\tq *= p;\n\t}\n\tBOOST_CHECK( q.isIdentity() );\n}\n\nBOOST_AUTO_TEST_CASE( test_permutation_order ) {\n\tconst unsigned int n = 10;\n\tPermutation a(n, \"1 2 5,3 6 7 8, 9 4 10\");\n\tPermutation b(n, \"1 2, 5 3 6, 7 8 4 10\");\n\tPermutation c(n, \"1 2, 5 3 6, 7 8 9 4 10\");\n\tPermutation d(n, \"1 2 3, 5 6 7, 8 9 10\");\n\t\n\tBOOST_CHECK_EQUAL( a.order(), 12 );\n\ttestPermutationOrder(a);\n\t\n\tBOOST_CHECK_EQUAL( b.order(), 12 );\n\ttestPermutationOrder(b);\n\t\n\tBOOST_CHECK_EQUAL( c.order(), 30 );\n\ttestPermutationOrder(c);\n\t\n\tBOOST_CHECK_EQUAL( d.order(), 3 );\n\ttestPermutationOrder(d);\n}\n\nBOOST_AUTO_TEST_CASE( test_permutation_cycles )\n{\n\tconst unsigned int n = 10;\n\tPermutation a(n, \"1 2 5,3 6 7 8, 9 4 10\");\n\tPermutation b(n, \"1 2, 5 3 6, 7 8 4 10\");\n\t\n\ttypedef std::pair<dom_int, unsigned int> CyclePair;\n\tCyclePair c;\n\t\n\tstd::list<CyclePair> cyclesA = a.cycles();\n\tBOOST_REQUIRE_EQUAL(cyclesA.size(), 3);\n\t\n\tc = cyclesA.front();\n\tcyclesA.pop_front();\n\tBOOST_CHECK_EQUAL(c.first, 0);\n\tBOOST_CHECK_EQUAL(c.second, 3);\n\t\n\tc = cyclesA.front();\n\tcyclesA.pop_front();\n\tBOOST_CHECK_EQUAL(c.first, 2);\n\tBOOST_CHECK_EQUAL(c.second, 4);\n\t\n\tc = cyclesA.front();\n\tcyclesA.pop_front();\n\tBOOST_CHECK_EQUAL(c.first, 3);\n\tBOOST_CHECK_EQUAL(c.second, 3);\n\t\n\t\n\t// include trivial cycles\n\tstd::list<CyclePair> cyclesB = b.cycles(true);\n\tBOOST_REQUIRE_EQUAL(cyclesB.size(), 4);\n\t\n\tc = cyclesB.front();\n\tcyclesB.pop_front();\n\tBOOST_CHECK_EQUAL(c.first, 0);\n\tBOOST_CHECK_EQUAL(c.second, 2);\n\t\n\tc = cyclesB.front();\n\tcyclesB.pop_front();\n\tBOOST_CHECK_EQUAL(c.first, 2);\n\tBOOST_CHECK_EQUAL(c.second, 3);\n\t\n\tc = cyclesB.front();\n\tcyclesB.pop_front();\n\tBOOST_CHECK_EQUAL(c.first, 3);\n\tBOOST_CHECK_EQUAL(c.second, 4);\n\t\n\tc = cyclesB.front();\n\tcyclesB.pop_front();\n\tBOOST_CHECK_EQUAL(c.first, 8);\n\tBOOST_CHECK_EQUAL(c.second, 1);\n\t\n\t\n\tcyclesB = b.cycles(false);\n\tBOOST_REQUIRE_EQUAL(cyclesB.size(), 3);\n\t\n\tc = cyclesB.front();\n\tcyclesB.pop_front();\n\tBOOST_CHECK_EQUAL(c.first, 0);\n\tBOOST_CHECK_EQUAL(c.second, 2);\n\t\n\tc = cyclesB.front();\n\tcyclesB.pop_front();\n\tBOOST_CHECK_EQUAL(c.first, 2);\n\tBOOST_CHECK_EQUAL(c.second, 3);\n\t\n\tc = cyclesB.front();\n\tcyclesB.pop_front();\n\tBOOST_CHECK_EQUAL(c.first, 3);\n\tBOOST_CHECK_EQUAL(c.second, 4);\n}\n\n\nBOOST_AUTO_TEST_CASE( test_permutation_projection )\n{\n\tstd::string line1(\"1 2 5 9,3 6 7 8, 4 10\");\n\tconst unsigned int n = 10;\n\tPermutation a(n, line1);\n\t\n\tconst dom_int projDomainSize = 4;\n\tconst dom_int projDomain[projDomainSize] = { 2, 5, 6, 7 };\n\tPermutation* p = a.project(projDomainSize, projDomain, projDomain+projDomainSize);\n\t\n\tBOOST_ASSERT( p );\n\t\n\tBOOST_CHECK( ! p->isIdentity() );\n\t\n\tfor (unsigned int i = 0; i < projDomainSize; ++i)\n\t\tBOOST_CHECK_EQUAL( *p / i, (i + 1) % projDomainSize );\n\t\n\tdelete p;\n}\n\nBOOST_AUTO_TEST_CASE( test_exotic_permutations )\n{\n  Permutation* p = new Permutation(1, \"\");\n  BOOST_ASSERT( p );\n  BOOST_CHECK_EQUAL( p->size(), 1 );\n  delete p;\n  \n  p = new Permutation(0, \"\");\n  BOOST_ASSERT( p );\n  BOOST_CHECK_EQUAL( p->size(), 0 );\n  delete p;\n}\n\n\nBOOST_AUTO_TEST_CASE( test_identity )\n{\n\tstd::string line1(\"1 2 5 9,3 6 7 8, 4 10\");\n\tconst unsigned int n = 10;\n\tPermutation a(n, line1);\n\t\n\tBOOST_CHECK( ! a.isIdentity() );\n\t\n\tconst dom_int lineArray[] = { 1, 4, 5, 9, 8, 6, 7, 2, 0, 3 };\n\tPermutation b(lineArray, lineArray + n);\n\tBOOST_CHECK( ! b.isIdentity() );\n\t\n\tPermutation c(a);\n\tc = ~a * b;\n\tBOOST_CHECK( c.isIdentity() );\n}\n", "meta": {"hexsha": "c0b231df3c7894dc7d24414cfaf837cf2cc25096", "size": 6441, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test-permutation.cpp", "max_stars_repo_name": "peterlietz/PermLib", "max_stars_repo_head_hexsha": "c2c0ae7e078df6c91c16c7326081c483700fde75", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-05-22T13:07:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-18T04:31:39.000Z", "max_issues_repo_path": "test/test-permutation.cpp", "max_issues_repo_name": "peterlietz/PermLib", "max_issues_repo_head_hexsha": "c2c0ae7e078df6c91c16c7326081c483700fde75", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-12-29T12:40:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-07T22:56:33.000Z", "max_forks_repo_path": "test/test-permutation.cpp", "max_forks_repo_name": "peterlietz/PermLib", "max_forks_repo_head_hexsha": "c2c0ae7e078df6c91c16c7326081c483700fde75", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.6613545817, "max_line_length": 83, "alphanum_fraction": 0.6688402422, "num_tokens": 1913, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.4911969701140922}}
{"text": "//\n// Created by Hamza El-Kebir on 4/17/21.\n//\n\n#ifndef LODESTAR_ZEROORDERHOLD_HPP\n#define LODESTAR_ZEROORDERHOLD_HPP\n\n#include <Eigen/Dense>\n#include <unsupported/Eigen/MatrixFunctions>\n#include \"Lodestar/systems/StateSpace.hpp\"\n#include \"Lodestar/aux/CompileTimeQualifiers.hpp\"\n\nnamespace ls {\n    namespace analysis {\n        /**\n         * @brief Routines for computing zero-order hold transformation on state\n         * space systems.\n         *\n         * @sa <a href=\"https://theory.ldstr.dev/discretization\">theory.ldstr.dev/discretization</a>\n         */\n        class ZeroOrderHold {\n        public:\n            template<typename TScalar = double, int TStateDim = Eigen::Dynamic, int TInputDim = Eigen::Dynamic, int TOutputDim = Eigen::Dynamic>\n            struct mallocStruct {\n                template<int TTStateDim = TStateDim, int TTInputDim = TInputDim, int TTOutputDim = TOutputDim, typename ::std::enable_if<\n                        (TTStateDim >= 0) && (TTInputDim >= 0) && (TTOutputDim >= 0)>::type * = nullptr>\n                mallocStruct() : upperXM(decltype(upperXM)::Zero()), lowerXM(decltype(lowerXM)::Zero()),\n                                 XM(decltype(XM)::Zero()), XXM(\n                                decltype(XXM)::Zero())\n                {}\n\n                template<int TTStateDim = TStateDim, int TTInputDim = TInputDim, int TTOutputDim = TOutputDim, typename ::std::enable_if<\n                        (TTStateDim < 0) && (TTInputDim < 0) && (TTOutputDim < 0)>::type * = nullptr>\n                mallocStruct()\n                {}\n\n                Eigen::Matrix<TScalar, TStateDim, LS_STATIC_UNLESS_DYNAMIC(TStateDim + TInputDim)> upperXM;\n                Eigen::Matrix<TScalar, TInputDim, LS_STATIC_UNLESS_DYNAMIC(TStateDim + TInputDim)> lowerXM;\n                Eigen::Matrix<TScalar, LS_STATIC_UNLESS_DYNAMIC(TStateDim + TInputDim), LS_STATIC_UNLESS_DYNAMIC(\n                        TStateDim + TInputDim)> XM;\n                Eigen::Matrix<TScalar, TStateDim, LS_STATIC_UNLESS_DYNAMIC(TStateDim + TInputDim)> XXM;\n            };\n\n            /**\n             * @brief Generates zero-order hold discretization from a\n             * continuous-time state space system.\n             *\n             * @param A State matrix.\n             * @param B Input matrix.\n             * @param C Output matrix.\n             * @param D Feedforward matrix.\n             * @param dt Sampling period.\n             *\n             * @return Zero-order hold discrete-time state space system.\n             */\n            static systems::StateSpace<>\n            c2d(const Eigen::MatrixXd &A, const Eigen::MatrixXd &B,\n                const Eigen::MatrixXd &C, const Eigen::MatrixXd &D, double dt);\n\n            /**\n             * @brief Generates zero-order hold discretization from a\n             * continuous-time state space system.\n             *\n             * @param A State matrix.\n             * @param B Input matrix.\n             * @param C Output matrix.\n             * @param D Feedforward matrix.\n             * @param dt Sampling period.\n             *\n             * @return Zero-order hold discrete-time state space system.\n             */\n            static systems::StateSpace<>\n            c2d(Eigen::MatrixXd *A, Eigen::MatrixXd *B, Eigen::MatrixXd *C, Eigen::MatrixXd *D, double dt);\n\n\n            template<typename TScalar, int TStateDim, int TInputDim, int TOutputDim>\n            static void c2d(const systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim> *ss, double dt,\n                            systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim> *out,\n                            mallocStruct<TScalar, TStateDim, TInputDim, TOutputDim> *memStruct,\n                            LS_IS_DYNAMIC_DEFAULT(TStateDim, TInputDim, TOutputDim));\n\n            template<typename TScalar, int TStateDim, int TInputDim, int TOutputDim>\n            static void c2d(const systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim> *ss, double dt,\n                            systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim> *out,\n                            mallocStruct<TScalar, TStateDim, TInputDim, TOutputDim> *memStruct,\n                            LS_IS_STATIC_DEFAULT(TStateDim, TInputDim, TOutputDim));\n\n            /**\n             * @brief Generates zero-order hold discretization from a\n             * continuous-time state space system.\n             *\n             * @param ss State space system.\n             * @param dt Sampling period.\n             *\n             * @return Zero-order hold discrete-time state space system.\n             */\n            static systems::StateSpace<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::Dynamic>\n            c2d(const systems::StateSpace<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::Dynamic> &ss, double dt);\n\n            /**\n             * @brief Generates zero-order hold discretization from a\n             * continuous-time state space system.\n             *\n             * @param ss Pointer to state space system.\n             * @param dt Sampling period.\n             *\n             * @return Zero-order hold discrete-time state space system.\n             */\n            static systems::StateSpace<> c2d(const systems::StateSpace<> *ss, double dt);\n\n            /**\n             * @brief Reverts a zero-order hold discretization on a\n             * discrete-time state space system.\n             *\n             * @param A State matrix.\n             * @param B Input matrix.\n             * @param C Output matrix.\n             * @param D Feedforward matrix.\n             * @param dt Sampling period.\n             *\n             * @return Zero-order hold continuous-time state space system.\n             */\n            static systems::StateSpace<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::Dynamic>\n            d2c(const Eigen::MatrixXd &A, const Eigen::MatrixXd &B,\n                const Eigen::MatrixXd &C, const Eigen::MatrixXd &D, double dt);\n\n            /**\n             * @brief Reverts a zero-order hold discretization on a\n             * discrete-time state space system.\n             *\n             * @param A State matrix.\n             * @param B Input matrix.\n             * @param C Output matrix.\n             * @param D Feedforward matrix.\n             * @param dt Sampling period.\n             *\n             * @return Zero-order hold continuous-time state space system.\n             */\n            static systems::StateSpace<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::Dynamic>\n            d2c(Eigen::MatrixXd *A, Eigen::MatrixXd *B,\n                Eigen::MatrixXd *C, Eigen::MatrixXd *D, double dt);\n\n            /**\n             * @brief Reverts a zero-order hold discretization on a\n             * discrete-time state space system.\n             *\n             * @param ss State space system.\n             * @param dt Sampling period.\n             *\n             * @return Continuous-time state space system.\n             */\n            static systems::StateSpace<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::Dynamic>\n            d2c(const systems::StateSpace<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::Dynamic> &ss, double dt);\n\n            /**\n             * @brief Reverts a zero-order hold discretization on a\n             * discrete-time state space system.\n             *\n             * @param ss State space system.\n             * @param dt Sampling period.\n             *\n             * @return Continuous-time state space system.\n             */\n            static systems::StateSpace<>\n            d2c(const systems::StateSpace<> *ss, double dt);\n\n            /**\n             * @brief Reverts a zero-order hold discretization on a\n             * discrete-time state space system.\n             *\n             * This method retrieves the sampling period from the state space\n             * object.\n             *\n             * @param ss State space system.\n             * @param dt Sampling period.\n             *\n             * @return Continuous-time state space system.\n             */\n            static systems::StateSpace<>\n            d2c(const systems::StateSpace<> *ss);\n\n            /**\n             * @brief Reverts a zero-order hold discretization on a\n             * discrete-time state space system.\n             *\n             * This method retrieves the sampling period from the state space\n             * object.\n             *\n             * @param ss State space system.\n             * @param dt Sampling period.\n             *\n             * @return Continuous-time state space system.\n             */\n            static systems::StateSpace<>\n            d2c(const systems::StateSpace<> &ss);\n\n            /**\n             * @brief Reverts a zero-order hold discretization on a\n             * discrete-time state space system.\n             *\n             * @param ss State space system.\n             * @param dt Sampling period.\n             *\n             * @return Continuous-time state space system.\n             */\n            template<typename TScalar, int TStateDim, int TInputDim, int TOutputDim>\n            static void d2c(const systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim> *ss, double dt,\n                            systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim> *out,\n                            mallocStruct<TScalar, TStateDim, TInputDim, TOutputDim> *memStruct,\n                            LS_IS_DYNAMIC_DEFAULT(TStateDim, TInputDim, TOutputDim));\n\n            /**\n             * @brief Reverts a zero-order hold discretization on a\n             * discrete-time state space system.\n             *\n             * @param ss State space system.\n             * @param dt Sampling period.\n             *\n             * @return Continuous-time state space system.\n             */\n            template<typename TScalar, int TStateDim, int TInputDim, int TOutputDim>\n            static void d2c(const systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim> *ss, double dt,\n                            systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim> *out,\n                            mallocStruct<TScalar, TStateDim, TInputDim, TOutputDim> *memStruct,\n                            LS_IS_STATIC_DEFAULT(TStateDim, TInputDim, TOutputDim));\n        };\n    }\n}\n\ntemplate<typename TScalar, int TStateDim, int TInputDim, int TOutputDim>\nvoid ls::analysis::ZeroOrderHold::c2d(const ls::systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim> *ss,\n                                      double dt,\n                                      ls::systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim> *out,\n                                      ls::analysis::ZeroOrderHold::mallocStruct<TScalar, TStateDim, TInputDim, TOutputDim> *memStruct,\n                                      LS_IS_DYNAMIC(TStateDim, TInputDim, TOutputDim))\n{\n    dt = abs(dt);\n\n    const long n = ss->stateDim();\n    const long m = ss->inputDim();\n\n    memStruct->upperXM.block(0, 0, n, n) << (ss->getA());\n    memStruct->upperXM.block(0, n, n, m) << (ss->getB());\n\n    memStruct->lowerXM.setZero();\n\n    memStruct->XM.block(0, 0, n, n + m) << memStruct->upperXM;\n    memStruct->XM.block(n, 0, m, n + m) << memStruct->lowerXM;\n\n    memStruct->XXM = (memStruct->XM * dt).exp().block(0, 0, n, n + m);\n\n    out->setA(memStruct->XXM.block(0, 0, n, n));\n    out->setB(memStruct->XXM.block(0, n, n, m));\n    out->setC(Eigen::MatrixXd::Identity(n, n));\n    out->setD(Eigen::MatrixXd::Zero(n, m));\n    out->setDiscreteParams(dt, true);\n\n}\n\ntemplate<typename TScalar, int TStateDim, int TInputDim, int TOutputDim>\nvoid ls::analysis::ZeroOrderHold::c2d(const ls::systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim> *ss,\n                                      double dt,\n                                      ls::systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim> *out,\n                                      ls::analysis::ZeroOrderHold::mallocStruct<TScalar, TStateDim, TInputDim, TOutputDim> *memStruct,\n                                      LS_IS_STATIC(TStateDim, TInputDim, TOutputDim))\n{\n    dt = abs(dt);\n\n    memStruct->upperXM.template block<TStateDim, TStateDim>(0, 0);\n    memStruct->upperXM.template block<TStateDim, TStateDim>(0, 0) << (ss->getA());\n    memStruct->upperXM.template block<TStateDim, TInputDim>(0, TStateDim) << (ss->getB());\n\n    memStruct->lowerXM.setZero();\n\n    memStruct->XM.template block<TStateDim, TStateDim + TInputDim>(0, 0) << memStruct->upperXM;\n    memStruct->XM.template block<TInputDim, TStateDim + TInputDim>(TStateDim, 0) << memStruct->lowerXM;\n\n    memStruct->XXM = (memStruct->XM * dt).exp().template block<TStateDim, TStateDim + TInputDim>(0, 0);\n\n    out->setA(memStruct->XXM.template block<TStateDim, TStateDim>(0, 0));\n    out->setB(memStruct->XXM.template block<TStateDim, TInputDim>(0, TStateDim));\n    out->setDiscreteParams(dt, true);\n}\n\ntemplate<typename TScalar, int TStateDim, int TInputDim, int TOutputDim>\nvoid ls::analysis::ZeroOrderHold::d2c(const ls::systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim> *ss,\n                                      double dt,\n                                      ls::systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim> *out,\n                                      ls::analysis::ZeroOrderHold::mallocStruct<TScalar, TStateDim, TInputDim, TOutputDim> *memStruct,\n                                      LS_IS_DYNAMIC(TStateDim, TInputDim, TOutputDim))\n{\n    dt = abs(dt);\n\n    const long n = ss->stateDim();\n    const long m = ss->inputDim();\n\n    memStruct->upperXM.block(0, 0, n, n) << (ss->getA());\n    memStruct->upperXM.block(0, n, n, m) << (ss->getB());\n\n    memStruct->lowerXM.setZero();\n    memStruct->lowerXM.block(0, n, m, m).setIdentity();\n\n    memStruct->XM.block(0, 0, n, n + m) << memStruct->upperXM;\n    memStruct->XM.block(n, 0, m, n + m) << memStruct->lowerXM;\n\n    memStruct->XXM = (memStruct->XM).log().block(0, 0, n, n + m) / dt;\n\n    out->setA(memStruct->XXM.block(0, 0, n, n));\n    out->setB(memStruct->XXM.block(0, n, n, m));\n}\n\ntemplate<typename TScalar, int TStateDim, int TInputDim, int TOutputDim>\nvoid ls::analysis::ZeroOrderHold::d2c(const ls::systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim> *ss,\n                                      double dt,\n                                      ls::systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim> *out,\n                                      ls::analysis::ZeroOrderHold::mallocStruct<TScalar, TStateDim, TInputDim, TOutputDim> *memStruct,\n                                      LS_IS_STATIC(TStateDim, TInputDim, TOutputDim))\n{\n    dt = abs(dt);\n\n    memStruct->upperXM.template block<TStateDim, TStateDim>(0, 0) << (ss->getA());\n    memStruct->upperXM.template block<TStateDim, TInputDim>(0, TStateDim) << (ss->getB());\n\n    memStruct->lowerXM.setZero();\n    memStruct->lowerXM.template block<TInputDim, TInputDim>(0, TStateDim)\n            << Eigen::Matrix<TScalar, TInputDim, TInputDim>::Identity();\n\n    memStruct->XM.template block<TStateDim, TStateDim + TInputDim>(0, 0) << memStruct->upperXM;\n    memStruct->XM.template block<TInputDim, TStateDim + TInputDim>(TStateDim, 0) << memStruct->lowerXM;\n\n    memStruct->XXM = (memStruct->XM).log().template block<TStateDim, TStateDim + TInputDim>(0, 0) / dt;\n\n    out->setA(memStruct->XXM.template block<TStateDim, TStateDim>(0, 0));\n    out->setB(memStruct->XXM.template block<TStateDim, TInputDim>(0, TStateDim));\n}\n\n#endif //LODESTAR_ZEROORDERHOLD_HPP\n", "meta": {"hexsha": "6f6aca50cead1f11c8708b7dbef64cabd0c7c213", "size": 15543, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Lodestar/analysis/ZeroOrderHold.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/analysis/ZeroOrderHold.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/analysis/ZeroOrderHold.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": 45.9852071006, "max_line_length": 144, "alphanum_fraction": 0.5722190053, "num_tokens": 3712, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.7057850278370111, "lm_q1q2_score": 0.49119696580713496}}
{"text": "/**\n * @file\n * @brief NPDE homework \"Handling degrees of freedom (DOFs) in LehrFEM++\"\n * @author Julien Gacon\n * @date March 1st, 2019\n * @copyright Developed at ETH Zurich\n */\n\n#include \"lfppdofhandling.h\"\n\n#include <Eigen/Dense>\n#include <array>\n#include <memory>\n\n#include \"lf/assemble/assemble.h\"\n#include \"lf/base/base.h\"\n#include \"lf/geometry/geometry.h\"\n#include \"lf/mesh/mesh.h\"\n#include \"lf/mesh/utils/utils.h\"\n\nnamespace LFPPDofHandling {\n\n/* SAM_LISTING_BEGIN_1 */\nstd::array<std::size_t, 3> countEntityDofs(\n    const lf::assemble::DofHandler &dofhandler) {\n  std::array<std::size_t, 3> entityDofs;\n  //====================\n  // Your code goes here\n\n  //STEP 0: Error handling in case we have quadrilateral cell\n  const lf::mesh::Entity& ent = dofhandler.Entity(0);\n\n\n  // STEP 1: obtain the mesh\n  std::shared_ptr<const lf::mesh::Mesh> mesh = dofhandler.Mesh();\n\n\n  // STEP 2: loop over all mesh entities\n  for(std::size_t codim = 0; codim <= 2; ++codim){\n    // clear the array entry to 0\n    entityDofs[codim] = 0;\n\n    for(const lf::mesh::Entity* ent: mesh->Entities(codim)){\n      // LF_VERIFY_MSG(ent->RefEl() == lf::base::RefEl::kQuad(), \"Unsupported cell type \" << ent->RefEl());\n      if(ent->RefEl() == lf::base::RefEl::kQuad()){\n        throw \"Unsupported cell type\";\n      }\n\n      entityDofs[codim] += dofhandler.NumInteriorDofs(*ent);\n    }\n  }\n\n\n  //====================\n  return entityDofs;\n}\n/* SAM_LISTING_END_1 */\n\n/* SAM_LISTING_BEGIN_2 */\nstd::size_t countBoundaryDofs(const lf::assemble::DofHandler &dofhandler) {\n  std::shared_ptr<const lf::mesh::Mesh> mesh = dofhandler.Mesh();\n  // given an entity, bd\\_flags(entity) == true, if the entity is on the\n  // boundary\n  lf::mesh::utils::AllCodimMeshDataSet<bool> bd_flags(\n      lf::mesh::utils::flagEntitiesOnBoundary(mesh));\n  std::size_t no_dofs_on_bd = 0;\n  //====================\n  // Your code goes here\n\n  // using bd_flags to know whether to take the entity into account\n  // STEP 1: add up edges at the boundary\n  for(const auto* edge: mesh->Entities(1)){\n\n      if(bd_flags(*edge)){\n          no_dofs_on_bd += dofhandler.NumInteriorDofs(*edge);\n      }\n  }\n\n  // STEP 2: add up nodes at the boundary\n  for(const auto* node: mesh->Entities(2)){\n\n      if(bd_flags(*node)){\n          no_dofs_on_bd += dofhandler.NumInteriorDofs(*node);\n      }\n  }\n\n\n  //====================\n  return no_dofs_on_bd;\n}\n/* SAM_LISTING_END_2 */\n\n// clang-format off\n/* SAM_LISTING_BEGIN_3 */\ndouble integrateLinearFEFunction(\n    const lf::assemble::DofHandler& dofhandler,\n    const Eigen::VectorXd& mu) {\n  double I = 0;\n  //====================\n  // Your code goes here\n\n  double vol = 0.;  // store the volume\n\n  // loop over the cells\n  std::shared_ptr<const lf::mesh::Mesh> mesh_ptr = dofhandler.Mesh();\n  for(const auto* cell: mesh_ptr->Entities(0)){\n\n        // STEP 0: exception handling\n        // no quadrilateral cells allowed\n        if(cell->RefEl() == lf::base::RefEl::kQuad()){\n          throw \"Unsupported cell type\";\n        }\n\n        // dofhandler dimension match\n        if (dofhandler.NumLocalDofs(*cell) != 3){\n          throw \"Dimension mismatch for dofhandler\";\n        }\n\n\n        // STEP 2: compute the fixed value of integration using properties of Barycentric basis\n        vol = lf::geometry::Volume(*(cell->Geometry())) / 3.;  // calculate the volume for the current cell\n\n        // STEP 3: obtain the array of global indices\n        auto indices = dofhandler.GlobalDofIndices(*cell);\n        auto end = indices.end();\n\n        for(auto index_ptr = indices.begin(); index_ptr < end; ++index_ptr){\n            // update I - dereference the pointer to obtain global index\n            I += vol * mu(*index_ptr);\n        }\n  }\n  //====================\n  return I;\n}\n/* SAM_LISTING_END_3 */\n// clang-format on\n\n/* SAM_LISTING_BEGIN_4 */\ndouble integrateQuadraticFEFunction(const lf::assemble::DofHandler &dofhandler,\n                                    const Eigen::VectorXd &mu) {\n  double I = 0;\n  //====================\n  // Your code goes here\n\n\n  // loop over the cells\n  std::shared_ptr<const lf::mesh::Mesh> mesh_ptr = dofhandler.Mesh();\n  for(const auto* cell: mesh_ptr->Entities(0)){\n\n    // STEP 0: exception handling\n\n    // no quadrilateral cells\n    if(cell->RefEl() == lf::base::RefEl::kQuad()){\n      throw \"No quadrilateral cells allowed\";\n    }\n\n    // dofhandler dimension match\n    if(dofhandler.NumLocalDofs(*cell) != 6){\n      throw \"Dimension mismatch!\";\n    }\n\n    // STEP 2: compute the fixed value of integration using properties of Barycentric basis\n    double vol = lf::geometry::Volume(*(cell->Geometry())) / 3.;  // calculate the volume for the current cell\n\n    // STEP 3: obtain the array of global indices\n    auto indices = dofhandler.GlobalDofIndices(*cell);\n    auto end = indices.end();\n\n\n    // start indexing from 0 in C++\n    for(int i = 3; i <= 5; ++i){\n        I += vol * mu(indices[i]);\n    }\n\n\n  }\n  //====================\n  return I;\n}\n/* SAM_LISTING_END_4 */\n\n/* SAM_LISTING_BEGIN_5 */\nEigen::VectorXd convertDOFsLinearQuadratic(\n    const lf::assemble::DofHandler &dofh_Linear_FE,\n    const lf::assemble::DofHandler &dofh_Quadratic_FE,\n    const Eigen::VectorXd &mu) {\n  if (dofh_Linear_FE.Mesh() != dofh_Quadratic_FE.Mesh()) {\n    throw \"Underlying meshes must be the same for both DOF handlers!\";\n  }\n  std::shared_ptr<const lf::mesh::Mesh> mesh =\n      dofh_Linear_FE.Mesh();                          // get the mesh\n  Eigen::VectorXd zeta(dofh_Quadratic_FE.NumDofs());  // initialise empty zeta\n  // safety guard: always set zero if you're not sure to set every entry later\n  // on for us this shouldn't be a problem, but just to be sure\n  zeta.setZero();\n\n  for (const auto *cell : mesh->Entities(0)) {\n    // check if the spaces are actually linear and quadratic\n    if(dofh_Linear_FE.NumLocalDofs(*cell) != 3){\n      throw \"The dimension of linear FE space should be 3!\";\n    }\n\n    if(dofh_Quadratic_FE.NumLocalDofs(*cell)!= 6){\n      throw \"The dimension of Quadratic FE space should be 6!\";\n    }\n    //====================\n    // Your code goes here\n    // STEP 3: obtain the array of global indices\n    auto linear_indices = dofh_Linear_FE.GlobalDofIndices(*cell);\n    auto quadratic_indices = dofh_Quadratic_FE.GlobalDofIndices(*cell);\n    //====================\n    // get the global dof indices of the linear and quadratic FE spaces, note\n    // that the vectors obey the LehrFEM++ numbering, which we will make use of\n    // lin\\_dofs will have size 3 for the 3 dofs on the nodes and\n    // quad\\_dofs will have size 6, the first 3 entries being the nodes and\n    // the last 3 the edges\n    //====================\n    // Your code goes here\n    // assign the coefficients of mu to the correct entries of zeta, use\n    // the previous subproblem 2-9.a\n\n\n    // using just one loop from 0-3 but deal with all 6 entries at the time\n    for(int i = 0; i < 3; ++i){\n          zeta(quadratic_indices[i]) = mu(linear_indices[i]); // the first 3 entries of basis func have coeff 1\n\n          // make use of the pattern of the basis functions used in the linear combination \n          zeta(quadratic_indices[i + 3]) = 0.5 * (mu(linear_indices[i]) + mu(linear_indices[(i + 1) % 3]));\n    }\n    //====================\n  }\n  return zeta;\n}\n/* SAM_LISTING_END_5 */\n\n}  // namespace LFPPDofHandling\n", "meta": {"hexsha": "f41d329846349cbaf7318502aeb584a03348dfaf", "size": 7347, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/LFPPDofHandling/mysolution/lfppdofhandling.cc", "max_stars_repo_name": "youwuyou/NPDECODES", "max_stars_repo_head_hexsha": "c6db4e50476eab37464744797d3b932ab4cdfb44", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "homeworks/LFPPDofHandling/mysolution/lfppdofhandling.cc", "max_issues_repo_name": "youwuyou/NPDECODES", "max_issues_repo_head_hexsha": "c6db4e50476eab37464744797d3b932ab4cdfb44", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homeworks/LFPPDofHandling/mysolution/lfppdofhandling.cc", "max_forks_repo_name": "youwuyou/NPDECODES", "max_forks_repo_head_hexsha": "c6db4e50476eab37464744797d3b932ab4cdfb44", "max_forks_repo_licenses": ["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.0, "max_line_length": 111, "alphanum_fraction": 0.6254253437, "num_tokens": 1989, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.49119696150017783}}
{"text": "#include <hmLib/config_vc.h>\n#include <array>\n#include <cmath>\n#include <fstream>\n#include <boost/numeric/odeint.hpp>\n#include <hmLib/odeint.hpp>\n#include <hmLib/odeint/breakable_integrate.hpp>\n#include <hmLib/odeint/container_observer.hpp>\n#include <hmLib/odeint/stream_observer.hpp>\n#include <hmLib/odeint/iterator_observer.hpp>\n#include <hmLib/odeint/break_observer.hpp>\n#include <hmLib/odeint/eqstate_break_observer.hpp>\n#include <hmLib/odeint/breakable_integrate.hpp>\n#include<hmLib/odeint/range_stepper.hpp>\n#define TEST_METHOD(Name) struct Name{};\nnamespace hmLib{\n\tstruct test_system{\n\t\tstatic constexpr double region_error(){ return 0.00001; }\n\t\tusing state = std::array<double, 2>;\n\t\tvoid operator()(const state& x, state& dxdt, double t){\n\t\t\toperator()(x, dxdt, t, region(x,t));\n\t\t}\n\t\tvoid operator()(const state& x, state& dxdt, double t, int r){\n\t\t\tdouble base = std::sqrt(x[0] * x[0] + x[1] * x[1]);\n\t\t\tdxdt[0] = -x[1];\n\t\t\tdxdt[1] = x[0];\n\n\t\t\tif(r == 2 && dxdt[0] > 0)dxdt[0] = 0.0;\n\t\t\telse if(r == 3 && dxdt[1] < 0)dxdt[1] = 0.0;\n\t\t\telse if(r == 4){\n\t\t\t\tif(dxdt[0] > 0)dxdt[0] = 0.0;\n\t\t\t\tif(dxdt[1] < 0)dxdt[1] = 0.0;\n\t\t\t}\n\t\t}\n\t\tint region(const state& x, double t){\n\t\t\tif(x[0] >= 0.5 - region_error()){\n\t\t\t\tif(x[1] <= -0.75 - region_error())return 4;\n\t\t\t\treturn 2;\n\t\t\t}\n\t\t\tif(x[1] <= -0.75 - region_error())return 3;\n\n\t\t\treturn 1;\n\t\t}\n\t};\n}\nint main(){\n\tusing namespace hmLib;\n\tnamespace bodeint = boost::numeric::odeint;\n\tTEST_METHOD(create){\n\t\tbodeint::runge_kutta_dopri5<test_system::state> Stepper;\n\t\ttest_system System;\n\t\ttest_system::state State{0.0,1.0};\n\n\t\todeint::container_observer<test_system::state> Observer;\n\n\t\tbodeint::integrate_adaptive(Stepper, System, State, 0.0, 100.0, 0.1, std::ref(Observer));\n\n\t\tstd::ofstream fout(\"result1.csv\");\n\t\tfor(auto val : Observer){\n\t\t\tfout << val.first << \",\" << val.second[0] << \",\" << val.second[1] << std::endl;\n\t\t}\n\t}\n\tTEST_METHOD(stream_observer){\n\t\tbodeint::runge_kutta_dopri5<test_system::state> Stepper;\n\t\ttest_system System;\n\t\ttest_system::state State{0.0,1.0};\n\n\t\todeint::stream_observer Observer(std::cout);\n\n\t\tbodeint::integrate_adaptive(Stepper, System, State, 0.0, 10.0, 0.1, Observer);\n\t}\n\tTEST_METHOD(s_iterator_observer){\n\t\tbodeint::runge_kutta_dopri5<test_system::state> Stepper;\n\t\ttest_system System;\n\t\ttest_system::state State{0.0,1.0};\n\n\t\tstd::vector<test_system::state> Log;\n\t\tauto Observer = odeint::make_iterator_observer(std::back_inserter(Log));\n\n\t\tbodeint::integrate_adaptive(Stepper, System, State, 0.0, 10.0, 0.1, Observer);\n\t}\n\tTEST_METHOD(st_iterator_observer){\n\t\tbodeint::runge_kutta_dopri5<test_system::state> Stepper;\n\t\ttest_system System;\n\t\ttest_system::state State{0.0,1.0};\n\n\t\tstd::vector<test_system::state> Log;\n\t\tstd::vector<double> TLog;\n\t\tauto Observer = odeint::make_iterator_observer(std::back_inserter(Log), std::back_inserter(TLog));\n\n\t\tbodeint::integrate_adaptive(Stepper, System, State, 0.0, 10.0, 0.1, Observer);\n\t}\n\tTEST_METHOD(pair_iterator_observer){\n\t\tbodeint::runge_kutta_dopri5<test_system::state> Stepper;\n\t\ttest_system System;\n\t\ttest_system::state State{0.0,1.0};\n\n\t\tstd::vector<std::pair<double, test_system::state> > Log;\n\t\tauto Observer = odeint::make_pair_iterator_observer(std::back_inserter(Log));\n\n\t\tbodeint::integrate_adaptive(Stepper, System, State, 0.0, 10.0, 0.1, Observer);\n\t}\n\tTEST_METHOD(break_observer){\n\t\tbodeint::runge_kutta_dopri5<test_system::state> Stepper;\n\t\ttest_system System;\n\t\ttest_system::state State{0.0,1.0};\n\n\t\tauto Observer = odeint::make_break_observer([](const test_system::state& State,double t)->bool{return State[0] > 1.0; });\n\n\t\todeint::breakable_integrate_adaptive(Stepper, System, State, 0.0, 10.0, 0.1, Observer);\n\t}\n\tTEST_METHOD(break_observer_with_container_observer){\n\t\tbodeint::runge_kutta_dopri5<test_system::state> Stepper;\n\t\ttest_system System;\n\t\ttest_system::state State{0.0,1.0};\n\n\t\tauto Observer = odeint::make_break_observer([](const test_system::state& State, double t)->bool{return State[0] > 1.0; }, odeint::container_observer<test_system::state>());\n\n\t\todeint::breakable_integrate_adaptive(Stepper, System, State, 0.0, 10.0, 0.1, std::ref(Observer));\n\t}\n\tTEST_METHOD(eqstate_break_observer){\n\t\tbodeint::runge_kutta_dopri5<test_system::state> Stepper;\n\t\ttest_system System;\n\t\ttest_system::state State{0.0,1.0};\n\n\t\todeint::eqstate_break_observer<test_system::state> Observer(odeint::detail::eqstate_breaker<test_system::state,double>(1));\n\n\t\t//odeint::breakable_integrate_adaptive(Stepper, System, State, 0.0, 100.0, 0.1, std::ref(Observer));\n\t\tbodeint::integrate_adaptive(Stepper, System, State, 0.0, 100.0, 0.1, std::ref(Observer));\n\n\t\tstd::ofstream fout(\"result2.csv\");\n\t\tfor(auto val : Observer){\n\t\t\tfout << val.first << \",\" << val.second[0] << \",\" << val.second[1] << std::endl;\n\t\t}\n\t}\n\tTEST_METHOD(range_stepper){\n\t\tauto BaseStepper = bodeint::make_dense_output(1.0e-10, 1.0e-6, bodeint::runge_kutta_dopri5<test_system::state>());\n\t\ttest_system System;\n\t\ttest_system::state State{0.0,1.0};\n\n\t\todeint::region_abridged_stepper<decltype(BaseStepper)> Stepper(System.region_error(), std::move(BaseStepper));\n\n//\t\todeint::container_observer<test_system::state> Observer;\n\n\t\t//odeint::breakable_integrate_adaptive(Stepper, System, State, 0.0, 100.0, 0.1, std::ref(Observer));\n\n\t\tstd::ofstream fout(\"result3b.csv\");\n\t\tStepper.initialize(State, 0.0, 0.001);\n\t\tfor(unsigned int i = 0; i < 100; ++i){\n\t\t\tauto Ans=Stepper.do_step(System);\n\t\t\tfout << Ans.first << \",\" << Ans.second << \",\" << Stepper.current_time() << \",\" << Stepper.current_time_step() << \",\" << Stepper.current_state()[0] << \",\" << Stepper.current_state()[1] << \",\" << Stepper.current_region() << std::endl;\n\t\t}\n\n\t}\n\tTEST_METHOD(range_stepper_integrate){\n\t\tauto BaseStepper = bodeint::make_dense_output(1.0e-10, 1.0e-6, bodeint::runge_kutta_dopri5<test_system::state>());\n\t\ttest_system System;\n\t\ttest_system::state State{0.0,1.0};\n\n\t\todeint::region_abridged_stepper<decltype(BaseStepper)> Stepper(System.region_error(), std::move(BaseStepper));\n\t\tStepper.initialize(State, 0.0, 0.001);\n\n\t\t//odeint::eqstate_break_observer<test_system::state> Observer(0.001, 1);\n\t\todeint::container_observer<test_system::state> Observer;\n\n\t\t//odeint::breakable_integrate_adaptive(Stepper, System, State, 0.0, 100.0, 0.1, std::ref(Observer));\n\t\tbodeint::integrate_adaptive(Stepper, System, State, 0.0, 100.0, 0.1, std::ref(Observer));\n\n\t\tstd::ofstream fout(\"result3.csv\");\n\t\tfor(auto val : Observer){\n\t\t\tfout << val.first << \",\" << val.second[0] << \",\" << val.second[1] << std::endl;\n\t\t}\n\t}\n\tsystem(\"pause\");\n\n\treturn 0;\n}\n", "meta": {"hexsha": "63a8ce31a7608bc7d9812f72f9b3b7bfe05ec62b", "size": 6541, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "vc/hmLib/hmLib/main.cpp", "max_stars_repo_name": "hmito/hmLib", "max_stars_repo_head_hexsha": "0f2515ba9c99c06d02e2fa633eeae73bcd793983", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "vc/hmLib/hmLib/main.cpp", "max_issues_repo_name": "hmito/hmLib", "max_issues_repo_head_hexsha": "0f2515ba9c99c06d02e2fa633eeae73bcd793983", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vc/hmLib/hmLib/main.cpp", "max_forks_repo_name": "hmito/hmLib", "max_forks_repo_head_hexsha": "0f2515ba9c99c06d02e2fa633eeae73bcd793983", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-09-22T03:32:11.000Z", "max_forks_repo_forks_event_max_datetime": "2015-09-22T03:32:11.000Z", "avg_line_length": 36.7471910112, "max_line_length": 235, "alphanum_fraction": 0.7020333282, "num_tokens": 2156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850154599563, "lm_q2_score": 0.6959583124210896, "lm_q1q2_score": 0.4911969482916039}}
{"text": "#include <Eigen/Core>\n#include <fstream>\n#include <sequential-line-search/utils.hpp>\n\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\n\nEigen::VectorXd sequential_line_search::utils::GenerateRandomVector(unsigned n)\n{\n    return 0.5 * (Eigen::VectorXd::Random(n) + Eigen::VectorXd::Ones(n));\n}\n\nvoid sequential_line_search::utils::ExportMatrixToCsv(const std::string& file_path, const Eigen::MatrixXd& X)\n{\n    std::ofstream   file(file_path);\n    Eigen::IOFormat format(Eigen::StreamPrecision, Eigen::DontAlignCols, \",\");\n    file << X.format(format);\n}\n", "meta": {"hexsha": "f6a496f3fd97c29b1ffd726ad076a50fe69f8348", "size": 552, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/utils.cpp", "max_stars_repo_name": "yuki-koyama/sequential-line-search", "max_stars_repo_head_hexsha": "7f68ce6f3ccb63eee4e921b867bd1014e3f947ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 26.0, "max_stars_repo_stars_event_min_datetime": "2018-03-12T13:18:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T20:28:04.000Z", "max_issues_repo_path": "src/utils.cpp", "max_issues_repo_name": "yuki-koyama/sequential-line-search", "max_issues_repo_head_hexsha": "7f68ce6f3ccb63eee4e921b867bd1014e3f947ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 37.0, "max_issues_repo_issues_event_min_datetime": "2018-04-05T23:42:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-13T03:52:42.000Z", "max_forks_repo_path": "src/utils.cpp", "max_forks_repo_name": "yuki-koyama/sequential-line-search", "max_forks_repo_head_hexsha": "7f68ce6f3ccb63eee4e921b867bd1014e3f947ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2018-06-12T17:50:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-17T11:13:03.000Z", "avg_line_length": 29.0526315789, "max_line_length": 109, "alphanum_fraction": 0.731884058, "num_tokens": 132, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.709019146082187, "lm_q2_score": 0.6926419894793248, "lm_q1q2_score": 0.491096431921298}}
{"text": "#include <stan/math/prim/scal.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <gtest/gtest.h>\n\nTEST(MathFunctions, if_else) {\n  using stan::math::if_else;\n  unsigned int c = 5;\n  double x = 1.0;\n  double y = -1.0;\n  EXPECT_FLOAT_EQ(x, if_else(c,x,y));\n  c = 0;\n  EXPECT_FLOAT_EQ(y, if_else(c,x,y));\n\n  bool d = true;\n  int u = 1;\n  int v = -1;\n  EXPECT_EQ(1.0, stan::math::if_else(d,u,v));\n  d = false;\n  EXPECT_FLOAT_EQ(-1.0, stan::math::if_else(d,u,v));\n\n  EXPECT_FLOAT_EQ(1.2,if_else(true,1.2,12));\n  EXPECT_FLOAT_EQ(12.0,if_else(false,1.2,12));\n\n  EXPECT_FLOAT_EQ(1.0,if_else(true,1,12.3));\n  EXPECT_FLOAT_EQ(12.3,if_else(false,1,12.3));\n}\n\nTEST(MathFunctions, if_else_promote) {\n  using stan::math::if_else;\n  double x = 2.5;\n  int y = -1;\n  EXPECT_FLOAT_EQ(2.5, if_else(true,x,y));\n  EXPECT_FLOAT_EQ(-1.0, if_else(false,x,y));\n}\n\nTEST(MathFunctions, if_else_nan) {\n  double nan = std::numeric_limits<double>::quiet_NaN();\n  \n  EXPECT_FLOAT_EQ(1.2, stan::math::if_else(true, 1.2, nan));\n  EXPECT_PRED1(boost::math::isnan<double>,\n               stan::math::if_else(false, 1.2, nan));\n\n\n  EXPECT_PRED1(boost::math::isnan<double>,\n               stan::math::if_else(true, nan, 2.4));\n  EXPECT_FLOAT_EQ(2.4, stan::math::if_else(false, nan, 2.4));\n\n  EXPECT_PRED1(boost::math::isnan<double>,\n               stan::math::if_else(true, nan, nan));\n  EXPECT_PRED1(boost::math::isnan<double>,\n               stan::math::if_else(false, nan, nan));\n}\n", "meta": {"hexsha": "4785b24ea9f9dc77d25f6fa5fe0f789def20de82", "size": 1466, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/scal/fun/if_else_test.cpp", "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/test/unit/math/prim/scal/fun/if_else_test.cpp", "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/test/unit/math/prim/scal/fun/if_else_test.cpp", "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": 27.6603773585, "max_line_length": 61, "alphanum_fraction": 0.6459754434, "num_tokens": 481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.7090191399336403, "lm_q1q2_score": 0.4910964231641216}}
{"text": "////////////////////////////////////////////////////////////////////////////////\n//  Copyright (c)      2012 Zach Byerly\n//  Copyright (c) 2011-2012 Bryce Adelstein-Lelbach\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// This is a program written to evolve in time the equation:\n//\n// D^2 U / Dt^2 = c^2  D^2 U / Dx^2\n//\n// The parameter alpha = c*dt/dx must be less than 1 to ensure the stability\n//     of the algorithm.\n// Discretizing the equation and solving for U(t+dt,x) yields\n// alpha^2 * (U(t,x+dx)+U(t,x-dx))+2(1-alpha^2)*U(t,x) - U(t-dt,x)\n//\n// For the first timestep, we approximate U(t-dt,x) by u(t+dt,x)-2*dt*du/dt(t,x)\n//\n\n\n// Include statements.\n#include <hpx/hpx_init.hpp>\n#include <hpx/runtime/actions/plain_action.hpp>\n#include <hpx/include/async.hpp>\n#include <hpx/lcos/future_wait.hpp>\n#include <hpx/include/iostreams.hpp>\n#include <hpx/util/format.hpp>\n\n#include <boost/math/constants/constants.hpp>\n\n#include <cstddef>\n#include <cstdint>\n#include <fstream>\n#include <iostream>\n#include <mutex>\n#include <vector>\n\nusing boost::program_options::variables_map;\nusing boost::program_options::options_description;\nusing boost::program_options::value;\n\nusing hpx::naming::id_type;\nusing hpx::naming::invalid_id;\n\nusing hpx::lcos::future;\nusing hpx::async;\nusing hpx::lcos::wait;\n\nusing hpx::util::high_resolution_timer;\n\nusing hpx::init;\nusing hpx::finalize;\nusing hpx::find_here;\n\nusing hpx::cout;\nusing hpx::flush;\n\n///////////////////////////////////////////////////////////////////////////////\n// Globals.\n\n//double const alpha_squared = 0.25;\ndouble alpha_squared = 0;\n\n// Initialized in hpx_main.\nid_type here = invalid_id;\ndouble pi = 0.;\ndouble c = 0.;\ndouble dt = 0.;\ndouble dx = 0.;\n\n// Command line argument.\nstd::uint64_t nt = 0;\nstd::uint64_t nx = 0;\n\nstruct data{\n  // Default constructor: data d1;\n  data()\n    : mtx()\n    , u_value(0.0)\n    , computed(false)\n  {}\n\n  // Copy constructor: data d1; data d2(d1);\n  // We can't copy the mutex, because mutexs are noncopyable.\n  data(\n       data const& other\n       )\n    : mtx()\n    , u_value(other.u_value)\n    , computed(other.computed)\n  {}\n\n  data& operator=(\n      data const& other\n      )\n  {\n    u_value = other.u_value;\n    computed = other.computed;\n    return *this;\n  }\n\n  hpx::lcos::local::mutex mtx;\n  double u_value;\n  bool computed;\n};\n\nstd::vector<std::vector<data> > u;\n\n\n///////////////////////////////////////////////////////////////////////////////\n// Forward declaration of the wave function.\ndouble wave(std::uint64_t t, std::uint64_t x);\n\n// Any global function needs to be wrapped into a plain_action if it should be\n// invoked as a HPX-thread.\n// This generates the required boilerplate we need for remote invocation.\nHPX_PLAIN_ACTION(wave);\n\ndouble calculate_u_tplus_x(double u_t_xplus, double u_t_x, double u_t_xminus,\n                           double u_tminus_x)\n{\n  double u_tplus_x = alpha_squared*(u_t_xplus + u_t_xminus)\n    + 2.0*(1-alpha_squared)*u_t_x - u_tminus_x;\n  return u_tplus_x;\n}\n\ndouble calculate_u_tplus_x_1st(double u_t_xplus, double u_t_x,\n                               double u_t_xminus, double u_dot)\n{\n  double u_tplus_x = 0.5*alpha_squared*(u_t_xplus + u_t_xminus)\n    + (1-alpha_squared)*u_t_x + dt*u_dot;\n  return u_tplus_x;\n}\n\ndouble wave(std::uint64_t t, std::uint64_t x)\n{\n  std::lock_guard<hpx::lcos::local::mutex> l(u[t][x].mtx);\n  //  hpx::util::format_to(cout, \"calling wave... t={1} x={2}\\n\", t, x) << flush;\n  if (u[t][x].computed)\n    {\n      //cout << (\"already computed!\\n\") << flush;\n      return u[t][x].u_value;\n    }\n  u[t][x].computed = true;\n\n  if (t == 0) //first timestep are initial values\n    {\n      //        hpx::util::format_to(cout, \"first timestep\\n\") << flush;\n      u[t][x].u_value = std::sin(2.*pi*x*dx); // initial u(x) value\n      return u[t][x].u_value;\n    }\n  future<double> n1;\n\n\n\n\n  // NOT using ghost zones here... just letting the stencil cross the periodic\n  // boundary.\n  if (x == 0)\n    n1 = async<wave_action>(here,t-1,nx-1);\n  else\n    n1 = async<wave_action>(here,t-1,x-1);\n\n  future<double> n2 = async<wave_action>(here,t-1,x);\n\n  future<double> n3;\n\n  if (x == (nx-1))\n    n3 = async<wave_action>(here,t-1,0);\n  else\n    n3 = async<wave_action>(here,t-1,x+1);\n\n  double u_t_xminus = n1.get(); //get the futures\n  double u_t_x = n2.get();\n  double u_t_xplus = n3.get();\n\n  if (t == 1) //second time coordinate handled differently\n    {\n      double u_dot = 0;// initial du/dt(x)\n      u[t][x].u_value = calculate_u_tplus_x_1st(u_t_xplus,u_t_x,u_t_xminus,u_dot);\n      return u[t][x].u_value;\n    } else {\n    double u_tminus_x = async<wave_action>(here,t-2,x).get();\n    u[t][x].u_value =  calculate_u_tplus_x(u_t_xplus,u_t_x,u_t_xminus,u_tminus_x);\n    return u[t][x].u_value;\n  }\n\n}\n\n///////////////////////////////////////////////////////////////////////////////\nint hpx_main(variables_map& vm)\n{\n  here = find_here();\n  pi = boost::math::constants::pi<double>();\n\n  //    dt = vm[\"dt-value\"].as<double>();\n  //    dx = vm[\"dx-value\"].as<double>();\n  //    c = vm[\"c-value\"].as<double>();\n  nx = vm[\"nx-value\"].as<std::uint64_t>();\n  nt = vm[\"nt-value\"].as<std::uint64_t>();\n\n  c = 1.0;\n\n  dt = 1.0/(nt-1);\n  dx = 1.0/(nx-1);\n  alpha_squared = (c*dt/dx)*(c*dt/dx);\n\n  // check that alpha_squared satisfies the stability condition\n  if (0.25 < alpha_squared)\n    {\n      cout << ((\"alpha^2 = (c*dt/dx)^2 should be less than 0.25 for stability!\\n\"))\n          << flush;\n    }\n\n  u = std::vector<std::vector<data> >(nt, std::vector<data>(nx));\n\n  hpx::util::format_to(cout, \"dt = {1}\\n\", dt) << flush;\n  hpx::util::format_to(cout, \"dx = {1}\\n\", dx) << flush;\n  hpx::util::format_to(cout, \"alpha^2 = {1}\\n\", alpha_squared) << flush;\n\n  {\n    // Keep track of the time required to execute.\n    high_resolution_timer t;\n\n    std::vector<future<double> > futures;\n    for (std::uint64_t i=0;i<nx;i++)\n      futures.push_back(async<wave_action>(here,nt-1,i));\n\n    // open file for output\n    std::ofstream outfile;\n    outfile.open (\"output.dat\");\n\n    wait(futures, [&](std::size_t i, double n)\n         { double x_here = i*dx;\n           hpx::util::format_to(outfile, \"{1} {2}\\n\", x_here, n) << flush; });\n\n    outfile.close();\n\n    char const* fmt = \"elapsed time: {1} [s]\\n\";\n    hpx::util::format_to(std::cout, fmt, t.elapsed());\n  }\n\n  finalize();\n  return 0;\n}\n\n///////////////////////////////////////////////////////////////////////////////\nint main(int argc, char* argv[])\n{\n  // Configure application-specific options.\n  options_description\n    desc_commandline(\"Usage: \" HPX_APPLICATION_STRING \" [options]\");\n\n  desc_commandline.add_options()\n    ( \"dt-value\"\n      , value<double>()->default_value(0.05)\n      , \"dt parameter of the wave equation\")\n\n    ( \"dx-value\"\n      , value<double>()->default_value(0.1)\n      , \"dx parameter of the wave equation\")\n\n    ( \"c-value\"\n      , value<double>()->default_value(1.0)\n      , \"c parameter of the wave equation\")\n\n    ( \"nx-value\"\n      , value<std::uint64_t>()->default_value(100)\n      , \"nx parameter of the wave equation\")\n\n    ( \"nt-value\"\n      , value<std::uint64_t>()->default_value(400)\n      , \"nt parameter of the wave equation\")\n    ;\n\n  // Initialize and run HPX.\n  return init(desc_commandline, argc, argv);\n}\n\n", "meta": {"hexsha": "0e179e8790a1f77cf3103169cef3b914b366415a", "size": 7465, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/quickstart/1d_wave_equation.cpp", "max_stars_repo_name": "bremerm31/hpx", "max_stars_repo_head_hexsha": "a9d22b8eb2e443d2e95991da9b1a621f94d4ebaa", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T08:34:59.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-29T08:34:59.000Z", "max_issues_repo_path": "examples/quickstart/1d_wave_equation.cpp", "max_issues_repo_name": "bremerm31/hpx", "max_issues_repo_head_hexsha": "a9d22b8eb2e443d2e95991da9b1a621f94d4ebaa", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-19T05:59:19.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-19T05:59:19.000Z", "max_forks_repo_path": "examples/quickstart/1d_wave_equation.cpp", "max_forks_repo_name": "biddisco/hpx", "max_forks_repo_head_hexsha": "2d244e1e27c6e014189a6cd59c474643b31fad4b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-03-13T04:53:43.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-13T04:53:43.000Z", "avg_line_length": 26.4716312057, "max_line_length": 83, "alphanum_fraction": 0.5922304086, "num_tokens": 2133, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.49109641890537975}}
{"text": "/*\n *  Zp.hpp\n *\n *  Created by Andrea Bedini on 19/09/08.\n *  Copyright (c) 2008-2014, Andrea Bedini <andrea.bedini@gmail.com>.\n *\n *  Distributed under the terms of the Modified BSD License.\n *  The full license is in the file COPYING, distributed as part of\n *  this software.\n *\n */\n\n#ifndef ZP_HPP\n#define ZP_HPP\n\n#include <boost/cstdint.hpp>\n#include <boost/operators.hpp>\n#include <boost/type_traits/is_integral.hpp>\n#include <boost/type_traits/is_signed.hpp>\n#include <boost/utility/enable_if.hpp>\n\n#include <iosfwd>\n\nnamespace modular {\n  class Zp;\n}\n\nnamespace boost {\n  template<> struct is_integral <modular::Zp> : public true_type {};\n  template<> struct is_signed   <modular::Zp> : public false_type {};\n  template<> struct is_unsigned   <modular::Zp> : public true_type {};\n}\n\nnamespace modular {\n  using boost::enable_if;\n  using boost::disable_if;\n\n  using boost::uint64_t;\n\n  typedef long double ldouble;\n\n  inline uint64_t mul_mod(uint64_t a, uint64_t b, uint64_t m)\n  {\n    uint64_t x = a * b;\n    uint64_t y = m * (uint64_t)( (ldouble)a * (ldouble)b/m + (ldouble)1/2 );\n    uint64_t r = x - y;\n    if ( (int64_t)r < 0 )  r += m;\n    return  r;\n  }\n\n  class Zp : boost::ring_operators< Zp\n\t   , boost::equality_comparable< Zp\n\t   > >\n  {\n    static uint64_t M;\n    uint64_t rep_;\n\n  public:\n    Zp() : rep_(0) { }\n    Zp(Zp const& x) : rep_(x.rep_) { }\n\n    template<class T>\n    explicit Zp(T n, typename boost::enable_if<boost::is_signed<T> >::type* = 0)\n      : rep_( n < 0 ?  M - ((- n) % M) : n % M)\n    { }\n\n    template<class T>\n    explicit Zp(T n, typename boost::disable_if<boost::is_signed<T> >::type* = 0)\n      : rep_(n % M)\n    { }\n\n    operator unsigned long() const { return rep_; }\n\n    static uint64_t get_modulus() {\n      return M;\n    }\n\n    static void set_modulus(uint64_t p) {\n      M = p;\n    }\n\n    // addable\n    Zp& operator+=(Zp const& x)\n    {\n      if (rep_ >= M - x.rep_)\n\trep_ -= M - x.rep_;\n      else\n\trep_ += x.rep_;\n      return *this;\n    }\n\n    // subtractable\n    Zp& operator-=(Zp const& x)\n    {\n      if (rep_ >= x.rep_)\n\trep_ -= x.rep_;\n      else\n\trep_ = M - x.rep_ + rep_;\n      return *this;\n    }\n\n    // multipliable\n    Zp& operator*=(Zp const& x)\n    {\n      rep_ = mul_mod(rep_, x.rep_, M);\n      // rep_ *= x.rep_;\n      // rep_ %= M;\n      return *this;\n    }\n\n    Zp operator-() const\n    {\n      return Zp(M - rep_);\n    }\n\n    // equality_comparable\n    bool operator==(Zp const& rhs) const\n    {\n      return rep_ == rhs.rep_;\n    }\n\n    friend std::ostream& operator<<(std::ostream& o, Zp const& x)\n    {\n      return o << x.rep_ << \" (\" << M << \")\";\n    }\n  };\n\n  uint64_t Zp::M;\n}\n\n#endif\n", "meta": {"hexsha": "81b6a11d7821a31448efc473db442fb42b9d57cf", "size": 2670, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/utility/Zp.hpp", "max_stars_repo_name": "andreabedini/tutte", "max_stars_repo_head_hexsha": "6bd620e06f6ac27fafc75898a3b12e9995a5e964", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-01-29T23:04:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-04T13:33:46.000Z", "max_issues_repo_path": "include/utility/Zp.hpp", "max_issues_repo_name": "andreabedini/tutte", "max_issues_repo_head_hexsha": "6bd620e06f6ac27fafc75898a3b12e9995a5e964", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/utility/Zp.hpp", "max_forks_repo_name": "andreabedini/tutte", "max_forks_repo_head_hexsha": "6bd620e06f6ac27fafc75898a3b12e9995a5e964", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.2272727273, "max_line_length": 81, "alphanum_fraction": 0.5790262172, "num_tokens": 826, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738152021788, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.49104599203649985}}
{"text": "/* ----------------------------------------------------------------------------\n * Copyright 2021, Jesus Tordesillas Torres, Aerospace Controls Laboratory\n * Massachusetts Institute of Technology\n * All Rights Reserved\n * Authors: Jesus Tordesillas, et al.\n * See LICENSE file for the license information\n * -------------------------------------------------------------------------- */\n\n#pragma once\n\n#include <Eigen/Dense>\n#include <unsupported/Eigen/Splines>\n#include \"panther_types.hpp\"\n\nvoid CPs2TrajAndPwp(std::vector<Eigen::Vector3d> &qp, std::vector<double> &qy, std::vector<mt::state> &traj,\n                    mt::PieceWisePol &pwp, int param_pp, int param_py, Eigen::RowVectorXd &knots_p, double dc);\n\nvoid CPs2TrajAndPwp_old(std::vector<Eigen::Vector3d> &q, std::vector<mt::state> &traj, mt::PieceWisePol &solution_,\n                        int N, int p, int num_seg, Eigen::RowVectorXd &knots, double dc);\n\nEigen::Spline3d findInterpolatingBsplineNormalized(const std::vector<double> &times,\n                                                   const std::vector<Eigen::Vector3d> &positions);", "meta": {"hexsha": "6a7f4b3f20af06e8e4631569d9994cb0c0396ee1", "size": 1103, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "panther/include/bspline_utils.hpp", "max_stars_repo_name": "t-thanh/panther", "max_stars_repo_head_hexsha": "c7ecb04b7a6ad0e61ee0596252196305a7fd0878", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 79.0, "max_stars_repo_stars_event_min_datetime": "2021-03-12T03:08:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T09:43:14.000Z", "max_issues_repo_path": "panther/include/bspline_utils.hpp", "max_issues_repo_name": "t-thanh/panther", "max_issues_repo_head_hexsha": "c7ecb04b7a6ad0e61ee0596252196305a7fd0878", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2021-03-15T05:22:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T08:54:12.000Z", "max_forks_repo_path": "panther/include/bspline_utils.hpp", "max_forks_repo_name": "t-thanh/panther", "max_forks_repo_head_hexsha": "c7ecb04b7a6ad0e61ee0596252196305a7fd0878", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2021-03-14T06:18:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T09:43:12.000Z", "avg_line_length": 50.1363636364, "max_line_length": 115, "alphanum_fraction": 0.5893019039, "num_tokens": 257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795403, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.49104598627566864}}
{"text": "#ifndef CSVFUNCTION_H\n#define CSVFUNCTION_H\n\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include \"IntrogressionSimulations.h\"\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/mean.hpp>\n#include <boost/accumulators/statistics/variance.hpp>\n#include <boost/filesystem.hpp>\n#include <stdio.h>\n#include <iomanip>\n#include <chrono>\n#include \"random.h\"\n\n#ifdef _OPENMP\n    #include <omp.h>\n#endif\n\nenum nameofstream {Parametersoff, Dataoff, AlleleFrequencyoff_mean, AlleleFrequencyoff_var};\n\nvoid CSV_WriteOutput(std::ofstream arrayofstream[4], const Parameters &pars, SimData &SimulationData){\n\n    using namespace boost::accumulators;\n    // Parameters output\n    for (int i = 0; i < 2; ++i)\n    {\n        arrayofstream[Parametersoff] << \"NINIT\" << i << arrayofstream[Parametersoff].fill() << pars.NINIT[i] << std::endl;\n    }\n    arrayofstream[Parametersoff] << \"NGEN\" << arrayofstream[Parametersoff].fill() << pars.NGEN << std::endl;\n    arrayofstream[Parametersoff] << \"NLOCI\" << arrayofstream[Parametersoff].fill() << pars.NLOCI << std::endl;\n    arrayofstream[Parametersoff] << \"NREP\" << arrayofstream[Parametersoff].fill() << pars.NREP << std::endl;\n    arrayofstream[Parametersoff] << \"MUTATIONRATE\" << arrayofstream[Parametersoff].fill() << pars.MUTATIONRATE << std::endl;\n    arrayofstream[Parametersoff] << \"RECOMBINATIONRATE\" << arrayofstream[Parametersoff].fill() << pars.RECOMBINATIONRATE << std::endl;\n    arrayofstream[Parametersoff] << \"CARRYINGCAPACITY\" << arrayofstream[Parametersoff].fill() << pars.K << std::endl;\n    arrayofstream[Parametersoff] << \"BIRTHRATE\" << arrayofstream[Parametersoff].fill() << pars.BIRTHRATE << std::endl;\n    arrayofstream[Parametersoff] << \"DEATHRATEA\" << arrayofstream[Parametersoff].fill() << pars.DEATHRATEA << std::endl;\n    arrayofstream[Parametersoff] << \"DEATHRATEa\" << arrayofstream[Parametersoff].fill() << pars.DEATHRATEa << std::endl;\n    arrayofstream[Parametersoff] << std::endl;\n\n    //Simulation output\n    arrayofstream[Dataoff] \n    << \"Generation\" << arrayofstream[Dataoff].fill() \n    << \"AVG_popsize\" << arrayofstream[Dataoff].fill()\n    << \"AVG_major0\" << arrayofstream[Dataoff].fill() \n    << \"AVG_major1\" << arrayofstream[Dataoff].fill() \n    << \"AVG_introgressed0\" << arrayofstream[Dataoff].fill()\n    << \"AVG_introgressed1\" << arrayofstream[Dataoff].fill() \n    << \"VAR_popsize\" << arrayofstream[Dataoff].fill()\n    << \"VAR_major0\" << arrayofstream[Dataoff].fill() \n    << \"VAR_major1\" << arrayofstream[Dataoff].fill()\n    << \"VAR_introgressed0\" << arrayofstream[Dataoff].fill() \n    << \"VAR_introgressed1\" << std::endl;\n\n    for(int i = 0; i < pars.NGEN; ++i){\n        accumulator_set<int, stats<tag::mean, tag::variance > > popsize;\n        accumulator_set<int, stats<tag::mean, tag::variance > > major0;\n        accumulator_set<int, stats<tag::mean, tag::variance > > major1;\n        accumulator_set<double, stats<tag::mean, tag::variance > > introgressed0;\n        accumulator_set<double, stats<tag::mean, tag::variance > > introgressed1;\n\n        ///FINISH ANALYSIS OF THE GENOTYPE RESCUE PER LOCUS PART. \n        for(int j = 0; j < pars.NREP; ++j){\n            popsize(SimulationData.DataSet[j]->popsize[i]);\n            major0(SimulationData.DataSet[j]->major0[i]);\n            major1(SimulationData.DataSet[j]->major1[i]);\n            introgressed0(SimulationData.DataSet[j]->introgressed0[i]);\n            introgressed1(SimulationData.DataSet[j]->introgressed1[i]);\n        }\n\n        arrayofstream[Dataoff]\n        << i << arrayofstream[Dataoff].fill() \n        << mean(popsize) << arrayofstream[Dataoff].fill()\n        << (double)mean(major0) << arrayofstream[Dataoff].fill()\n        << (double)mean(major1) << arrayofstream[Dataoff].fill() \n        << mean(introgressed0) << arrayofstream[Dataoff].fill()\n        << mean(introgressed1) << arrayofstream[Dataoff].fill()\n\n        << variance(popsize) << arrayofstream[Dataoff].fill()\n        << (double)variance(major0) << arrayofstream[Dataoff].fill()\n        << (double)variance(major1) << arrayofstream[Dataoff].fill()\n        << variance(introgressed0)<< arrayofstream[Dataoff].fill()\n        << variance(introgressed1) << arrayofstream[Dataoff].fill() << std::endl;\n    };\n    \n    for(int i = 0; i < pars.NGEN; ++i){\n        arrayofstream[AlleleFrequencyoff_mean] << i << arrayofstream[AlleleFrequencyoff_mean].fill(); \n        arrayofstream[AlleleFrequencyoff_var] << i << arrayofstream[AlleleFrequencyoff_var].fill();\n        for(int l = 0; l < pars.NLOCI; ++l)\n        {\n            accumulator_set<double, stats<tag::mean, tag::variance > > locus;\n            for(int r = 0; r < pars.NREP; ++r)\n            {\n                locus((double)SimulationData.DataSet[r]->allele0[i][l] / ((double)SimulationData.DataSet[r]->popsize[i]));\n            }\n            arrayofstream[AlleleFrequencyoff_mean] << mean(locus)  << arrayofstream[AlleleFrequencyoff_mean].fill();\n            arrayofstream[AlleleFrequencyoff_var] << variance(locus) << arrayofstream[AlleleFrequencyoff_var].fill(); \n        }\n        arrayofstream[AlleleFrequencyoff_mean] << std::endl;\n        arrayofstream[AlleleFrequencyoff_var] << std::endl;\n    }\n\n    // Cleanup\n    for(int i = 0; i < pars.NREP; ++i){\n        delete SimulationData.DataSet[i];\n    }\n}\n\nstd::string CreateOutputStreams(std::ofstream arrayofstream[4]){\n    \n    std::string CurrentWorkingDirectory = boost::filesystem::current_path().c_str();\n    CurrentWorkingDirectory.append(\"/data\");\n\n    auto t = std::time(nullptr);\n    auto tm = *std::localtime(&t);\n    std::ostringstream oss;\n    oss << std::put_time(&tm, \"%d-%m-%Y-%H-%M-%S\");\n    std::string str = oss.str();\n\n    std::string MainOutputFolder = CurrentWorkingDirectory;\n    MainOutputFolder.append(\"/\");\n    MainOutputFolder.append(str);\n\n    boost::filesystem::create_directories(MainOutputFolder.c_str());\n\n    std::string ParameterOutput = MainOutputFolder;\n    ParameterOutput.append(\"/Parameters.csv\");\n\n    arrayofstream[Parametersoff].open(ParameterOutput);\n    arrayofstream[Parametersoff].fill(',');\n\n    std::string DataOutput = MainOutputFolder;\n    DataOutput.append(\"/Data.csv\");\n\n    std::string AlleleFOutput_mean = MainOutputFolder;\n    std::string AlleleFOutput_var = MainOutputFolder;\n\n    AlleleFOutput_mean.append(\"/AlleleF_mean.csv\");\n    AlleleFOutput_var.append(\"/AlleleF_var.csv\");\n\n    arrayofstream[Dataoff].open(DataOutput);\n    arrayofstream[AlleleFrequencyoff_mean].open(AlleleFOutput_mean);\n    arrayofstream[AlleleFrequencyoff_var].open(AlleleFOutput_var);\n    arrayofstream[Dataoff].fill(',');\n    arrayofstream[AlleleFrequencyoff_mean].fill(',');\n    arrayofstream[AlleleFrequencyoff_var].fill(',');\n\n    return MainOutputFolder;\n}\n\nint main(int argc, char *argv[]){\n    // Initialize simulation\n    rnd::set_seed();\n    const Parameters GlobalPars(argc, argv);\n\n    SimData SimulationData;\n    // Run nrep successful simulations\n    // auto start = std::chrono::high_resolution_clock::now();\n    #ifdef _OPENMP\n        printf(\"Parallel activated : Number of threads=%i\\n\",omp_get_max_threads());   \n    #endif\n\n    #pragma omp parallel for schedule(static)\n    for(int task = 0; task < GlobalPars.NREP; ++task){\n        while(RunSimulation(GlobalPars, SimulationData)==false);\n    }\n    // auto finish = std::chrono::high_resolution_clock::now();\n    \n    // Write outputfiles\n    std::ofstream arrayofstream[4]; \n    CreateOutputStreams(arrayofstream); \n\tCSV_WriteOutput(arrayofstream, GlobalPars, SimulationData);\n\n    /*\n    // Cleanup\n    for(int i = 0; i < GlobalPars.NREP; ++i){\n        delete SimulationData.DataSet[i];\n    }\n    */\n\n    /*\n    std::chrono::duration<double> elapsed = finish-start;\n    std::cout << \"Elapsed time: \" << elapsed.count() << \" s\" << std::endl;\n    */\n    return 0;\n}\n\n#endif\n", "meta": {"hexsha": "f2d4b1e2db559f55186ff2e03850c6b9e7db611d", "size": 7889, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Models/IBS_Simulations/CSV_output.cpp", "max_stars_repo_name": "freekdh/GeneticRescue", "max_stars_repo_head_hexsha": "62226b4fd2ba25a1891bf02e3d0272b67897409f", "max_stars_repo_licenses": ["Apache-2.0"], "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/IBS_Simulations/CSV_output.cpp", "max_issues_repo_name": "freekdh/GeneticRescue", "max_issues_repo_head_hexsha": "62226b4fd2ba25a1891bf02e3d0272b67897409f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-08-01T23:29:56.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-20T23:35:56.000Z", "max_forks_repo_path": "CppFiles/CSV_output.cpp", "max_forks_repo_name": "freekdh/Introgression", "max_forks_repo_head_hexsha": "f26c7b84efee64ec5bb4e662753e052195b7fc71", "max_forks_repo_licenses": ["Apache-2.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.3036649215, "max_line_length": 134, "alphanum_fraction": 0.6694131069, "num_tokens": 2069, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795402, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4910459862756686}}
{"text": "#include \"../../include/IntrinsicFormula/AmpSolver.h\"\n#include <igl/cotmatrix_entries.h>\n#include <igl/massmatrix.h>\n#include <Eigen/Sparse>\n#include <SymGEigsShiftSolver.h>\n#include <MatOp/SparseCholesky.h>\n#include <MatOp/SparseSymShiftSolve.h>\n#include <cassert>\n\n// Baseline implementation; can be used if Spectra not available\n\n/*\nstatic void inversePowerIteration(const Eigen::SparseMatrix<double>& A, const Eigen::SparseMatrix<double>& B, Eigen::VectorXd& sol)\n{\n    sol.resize(A.rows());\n    sol.setRandom();\n    double eps = 1e-6;\n    Eigen::SparseMatrix<double> M = A + eps * B;\n    Eigen::SimplicialLDLT<Eigen::SparseMatrix<double> > solver(M);\n    sol.setRandom();\n    for (int i = 0; i < 10000; i++)\n    {\n        sol = solver.solve(B * sol);\n        sol /= std::sqrt(sol.transpose() * B * sol);\n    }  \n}\n*/\n\nvoid ampSolver(const Eigen::MatrixXd& V, const MeshConnectivity& mesh, const Eigen::MatrixXd& omegas, Eigen::VectorXd& amplitudes)\n{\n    Eigen::MatrixXd C;\n    igl::cotmatrix_entries(V, mesh.faces(), C);\n\n    int nedges = mesh.nEdges();\n    Eigen::VectorXd onestar(nedges);\n    \n    for (int i = 0; i < nedges; i++)\n    {\n        onestar[i] = 0;\n        for (int j = 0; j < 2; j++)\n        {\n            int fidx = mesh.edgeFace(i, j);\n            if (fidx != -1)\n            {\n                int opp = mesh.oppositeVertexIndex(i, j);\n                onestar[i] += C(fidx, opp);\n            }\n        }\n    }\n\n    std::vector<Eigen::Triplet<double> > Mcoeffs;\n    for (int i = 0; i < nedges; i++)\n    {\n        int v0 = mesh.edgeVertex(i, 0);\n        int v1 = mesh.edgeVertex(i, 1);\n        \n        // Laplacian coeffs\n        Mcoeffs.push_back({ v0, v0, onestar[i] });\n        Mcoeffs.push_back({ v1, v1, onestar[i] });\n        Mcoeffs.push_back({ v0, v1, -onestar[i] });\n        Mcoeffs.push_back({ v1, v0, -onestar[i] });\n\n        // frequency coeffs\n        // frequency coeffs\n        double freqweight1 = 0.5 * omegas(i, 0) * omegas(i, 0);\n        double freqweight2 = 0.5 * omegas(i, 1) * omegas(i, 1);\n        Mcoeffs.push_back({ v0, v0, freqweight1 * onestar[i] });\n        Mcoeffs.push_back({ v1, v1, freqweight2 * onestar[i] });\n    }\n\n    int nverts = V.rows();\n    Eigen::SparseMatrix<double> M(nverts, nverts);\n    M.setFromTriplets(Mcoeffs.begin(), Mcoeffs.end());\n\n    Eigen::SparseMatrix<double> massM;\n    igl::massmatrix(V, mesh.faces(), igl::MASSMATRIX_TYPE_BARYCENTRIC, massM);\n\n    Spectra::SymShiftInvert<double> op(M, massM);\n    Spectra::SparseSymMatProd<double> Bop(massM);\n    Spectra::SymGEigsShiftSolver<Spectra::SymShiftInvert<double>, Spectra::SparseSymMatProd<double>, Spectra::GEigsMode::ShiftInvert> geigs(op, Bop, 1, 6, -1e-6);\n    geigs.init();\n    int nconv = geigs.compute(Spectra::SortRule::LargestMagn, 1e6);\n\n    Eigen::VectorXd evalues;\n    Eigen::MatrixXd evecs;\n\n    evalues = geigs.eigenvalues();\n    evecs = geigs.eigenvectors();\n    if (nconv != 1 || geigs.info() != Spectra::CompInfo::Successful)\n    {\n        std::cout << \"Eigensolver failed to converge!!\" << std::endl;\n    }\n    amplitudes = evecs.col(0);\n    std::cout << \"Eigenvalue is \" << evalues[0] << std::endl;\n\n    //inversePowerIteration(M, massM, amplitudes);    \n\n    // try to fix sign\n    int posvotes = 0;\n    int negvotes = 0;\n    for (int i = 0; i < nverts; i++)\n    {\n        if (amplitudes[i] < 0)\n            negvotes++;\n        else\n            posvotes++;\n    }\n    if (negvotes > posvotes)\n        amplitudes *= -1;\n}", "meta": {"hexsha": "b3c6b15bd7e8c525a62cff3c10702398c5ef74b9", "size": 3466, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/IntrinsicFormula/AmpSolver.cpp", "max_stars_repo_name": "csyzzkdcz/PhaseInterpolation_polyscope", "max_stars_repo_head_hexsha": "4833a569f9eca1c222f7cdfd8e4aae3f03d8ad0b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/IntrinsicFormula/AmpSolver.cpp", "max_issues_repo_name": "csyzzkdcz/PhaseInterpolation_polyscope", "max_issues_repo_head_hexsha": "4833a569f9eca1c222f7cdfd8e4aae3f03d8ad0b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/IntrinsicFormula/AmpSolver.cpp", "max_forks_repo_name": "csyzzkdcz/PhaseInterpolation_polyscope", "max_forks_repo_head_hexsha": "4833a569f9eca1c222f7cdfd8e4aae3f03d8ad0b", "max_forks_repo_licenses": ["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.5090909091, "max_line_length": 162, "alphanum_fraction": 0.5920369302, "num_tokens": 1053, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.49104598051483705}}
{"text": "#include <boost/compute/random/mersenne_twister_engine.hpp>\n", "meta": {"hexsha": "9b8ff81697e244ac7b5753ef70be482342418480", "size": 60, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_compute_random_mersenne_twister_engine.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_compute_random_mersenne_twister_engine.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_compute_random_mersenne_twister_engine.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 30.0, "max_line_length": 59, "alphanum_fraction": 0.85, "num_tokens": 14, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.491045980514837}}
{"text": "//=============================================================================\n// Copyright (C) 2011-2018 The pmp-library developers\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are met:\n//\n// * Redistributions of source code must retain the above copyright notice, this\n//   list of conditions and the following disclaimer.\n// * Redistributions in binary form must reproduce the above copyright notice,\n//   this list of conditions and the following disclaimer in the documentation\n//   and/or other materials provided with the distribution.\n// * Neither the name of the copyright holder nor the names of its\n//   contributors may be used to endorse or promote products derived from\n//   this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n// POSSIBILITY OF SUCH DAMAGE.\n//=============================================================================\n\n#include <pmp/algorithms/SurfaceSmoothing.h>\n#include <pmp/algorithms/DifferentialGeometry.h>\n\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n\n//=============================================================================\n\nnamespace pmp {\n\n//=============================================================================\n\nusing SparseMatrix = Eigen::SparseMatrix<double>;\nusing Triplet = Eigen::Triplet<double>;\n\n//=============================================================================\n\nvoid SurfaceSmoothing::explicitSmoothing(unsigned int iters,\n                                         bool useUniformLaplace)\n{\n    auto points = m_mesh.vertexProperty<Point>(\"v:point\");\n    auto eweight = m_mesh.addEdgeProperty<Scalar>(\"e:cotan\");\n    auto laplace = m_mesh.addVertexProperty<Point>(\"v:laplace\");\n\n    // compute Laplace weight per edge: cotan or uniform\n    if (useUniformLaplace)\n    {\n        for (auto e : m_mesh.edges())\n            eweight[e] = 1.0;\n    }\n    else\n    {\n        for (auto e : m_mesh.edges())\n            eweight[e] = std::max(0.0, cotanWeight(m_mesh, e));\n    }\n\n    // smoothing iterations\n    SurfaceMesh::Vertex vv;\n    SurfaceMesh::Edge e;\n    for (unsigned int i = 0; i < iters; ++i)\n    {\n        // step 1: compute Laplace for each vertex\n        for (auto v : m_mesh.vertices())\n        {\n            Point l(0, 0, 0);\n\n            if (!m_mesh.isSurfaceBoundary(v))\n            {\n                Scalar w(0);\n\n                for (auto h : m_mesh.halfedges(v))\n                {\n                    vv = m_mesh.toVertex(h);\n                    e = m_mesh.edge(h);\n                    l += eweight[e] * (points[vv] - points[v]);\n                    w += eweight[e];\n                }\n\n                l /= w;\n            }\n\n            laplace[v] = l;\n        }\n\n        // step 2: move each vertex by its (damped) Laplacian\n        for (auto v : m_mesh.vertices())\n        {\n            points[v] += 0.5f * laplace[v];\n        }\n    }\n\n    // clean-up custom properties\n    m_mesh.removeVertexProperty(laplace);\n    m_mesh.removeEdgeProperty(eweight);\n}\n\n//-----------------------------------------------------------------------------\n\nvoid SurfaceSmoothing::implicitSmoothing(Scalar timestep,\n                                         bool useUniformLaplace)\n{\n    if (!m_mesh.nVertices())\n        return;\n\n    // properties\n    auto points = m_mesh.vertexProperty<Point>(\"v:point\");\n    auto vweight = m_mesh.addVertexProperty<Scalar>(\"v:area\");\n    auto eweight = m_mesh.addEdgeProperty<Scalar>(\"e:cotan\");\n    auto idx = m_mesh.addVertexProperty<int>(\"v:idx\", -1);\n\n    // compute weights: cotan or uniform\n    if (useUniformLaplace)\n    {\n        for (auto v : m_mesh.vertices())\n            vweight[v] = 1.0 / m_mesh.valence(v);\n        for (auto e : m_mesh.edges())\n            eweight[e] = 1.0;\n    }\n    else\n    {\n        for (auto v : m_mesh.vertices())\n            vweight[v] = 0.5 / voronoiArea(m_mesh, v);\n        for (auto e : m_mesh.edges())\n            eweight[e] = std::max(0.0, cotanWeight(m_mesh, e));\n    }\n\n    // collect free (non-boundary) vertices in array free_vertices[]\n    // assign indices such that idx[ free_vertices[i] ] == i\n    unsigned i = 0;\n    std::vector<SurfaceMesh::Vertex> free_vertices;\n    free_vertices.reserve(m_mesh.nVertices());\n    for (auto v : m_mesh.vertices())\n    {\n        if (!m_mesh.isSurfaceBoundary(v))\n        {\n            idx[v] = i++;\n            free_vertices.push_back(v);\n        }\n    }\n    const unsigned int n = free_vertices.size();\n\n    // A*X = B\n    SparseMatrix A(n, n);\n    Eigen::MatrixXd B(n, 3);\n\n    // nonzero elements of A as triplets: (row, column, value)\n    std::vector<Triplet> triplets;\n\n    // setup matrix A and rhs B\n    double ww;\n    SurfaceMesh::Vertex v, vv;\n    SurfaceMesh::Edge e;\n    for (unsigned int i = 0; i < n; ++i)\n    {\n        v = free_vertices[i];\n\n        // rhs row\n        B(i, 0) = points[v][0] / vweight[v];\n        B(i, 1) = points[v][1] / vweight[v];\n        B(i, 2) = points[v][2] / vweight[v];\n\n        // lhs row\n        ww = 0.0;\n        for (auto h : m_mesh.halfedges(v))\n        {\n            vv = m_mesh.toVertex(h);\n            e = m_mesh.edge(h);\n            ww += eweight[e];\n\n            // fixed boundary vertex -> right hand side\n            if (m_mesh.isSurfaceBoundary(vv))\n            {\n                B(i, 0) -= -timestep * eweight[e] * points[vv][0];\n                B(i, 1) -= -timestep * eweight[e] * points[vv][1];\n                B(i, 2) -= -timestep * eweight[e] * points[vv][2];\n            }\n            // free interior vertex -> matrix\n            else\n            {\n                triplets.emplace_back(i, idx[vv], -timestep * eweight[e]);\n            }\n        }\n\n        // center vertex -> matrix\n        triplets.emplace_back(i, i, 1.0 / vweight[v] + timestep * ww);\n    }\n\n    // build sparse matrix from triplets\n    A.setFromTriplets(triplets.begin(), triplets.end());\n\n    // solve A*X = B\n    Eigen::SimplicialLDLT<SparseMatrix> solver(A);\n    Eigen::MatrixXd X = solver.solve(B);\n    if (solver.info() != Eigen::Success)\n    {\n        std::cerr << \"SurfaceSmoothing: Could not solve linear system\\n\";\n    }\n    else\n    {\n        // copy solution\n        for (unsigned int i = 0; i < n; ++i)\n        {\n            v = free_vertices[i];\n            points[v][0] = X(i, 0);\n            points[v][1] = X(i, 1);\n            points[v][2] = X(i, 2);\n        }\n    }\n\n    // clean-up\n    m_mesh.removeVertexProperty(idx);\n    m_mesh.removeVertexProperty(vweight);\n    m_mesh.removeEdgeProperty(eweight);\n}\n\n//=============================================================================\n} // namespace pmp\n//=============================================================================\n", "meta": {"hexsha": "42ecf102ab3e593814126ddc0b1c592e41cef75b", "size": 7492, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/pmp/algorithms/SurfaceSmoothing.cpp", "max_stars_repo_name": "choyfung/pmp-library", "max_stars_repo_head_hexsha": "4a72c918494dac92f5e77545b71c7a327dafe71e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-21T04:15:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-21T04:15:44.000Z", "max_issues_repo_path": "src/pmp/algorithms/SurfaceSmoothing.cpp", "max_issues_repo_name": "choyfung/pmp-library", "max_issues_repo_head_hexsha": "4a72c918494dac92f5e77545b71c7a327dafe71e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pmp/algorithms/SurfaceSmoothing.cpp", "max_forks_repo_name": "choyfung/pmp-library", "max_forks_repo_head_hexsha": "4a72c918494dac92f5e77545b71c7a327dafe71e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-05-21T04:15:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-21T04:15:52.000Z", "avg_line_length": 33.0044052863, "max_line_length": 80, "alphanum_fraction": 0.532835024, "num_tokens": 1733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342624, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.49104597475400547}}
{"text": "/*************************************************************************\nCopyright (c) 2019 Cognitics, Inc.\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the \"Software\"),\nto deal in the Software without restriction, including without limitation\nthe rights to use, copy, modify, merge, publish, distribute, sublicense,\nand/or sell copies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\nTHE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\nDEALINGS IN THE SOFTWARE.\n****************************************************************************/\n#include \"sfa/ConvexHull.h\"\n#include \"sfa/Point.h\"\n#include \"sfa/Polygon.h\"\n#include \"sfa/PointMath.h\"\n#include \"sfa/RingMath.h\"\n#include <float.h>\n#include <cmath>\n#include <boost/foreach.hpp>\nnamespace sfa {\n\n//MELKMAN ========================================================================================\n    int MelkmanHull::isLeft(const Point& p, const Point& p1, const Point& p2)\n    {\n        double a = (p1.X() - p.X())*(p2.Y() - p.Y()) - (p2.X() - p.X())*(p1.Y() - p.Y());\n        if (a < -SFA_EPSILON) return -1;\n        else if (a > SFA_EPSILON) return 1;\n        else return 0;\n    }\n\n    Geometry* MelkmanHull::apply(const LineString* a)\n    {\n        //check if the linestring is long enough\n        if (a->getNumPoints() < 3)\n            new LineString(a);\n\n        std::vector<Point> points;\n        for (int i = 0; i < a->getNumPoints(); i++)\n        {\n            points.push_back(*a->getPointN(i));\n        }\n\n        //remove any redundant points\n        if (a->isClosed()) points.pop_back();\n\n        //create the dequeue\n        Point* D = new Point[2*points.size() + 1];\n        int bottom = int(points.size()) - 2;\n        int top = bottom + 3;\n\n        //special case, the first three points are collinear\n        //in that case keep moving down\n        int first = 0;\n        int second = 1;\n        int third = 2;\n\n        while(third < int(points.size()))\n        {\n            if (Collinear(points[first],points[second],points[third]))\n            {\n                second++;\n                third++;\n            }\n            else break;\n        }\n        if (third >= int(points.size()))\n            return new LineString(a);\n\n        //set up the first three points so that they are in CCW order\n        if (isLeft(points[first], points[second], points[third]) > 0)\n        {\n            D[bottom+1] = points[first];\n            D[bottom+2] = points[second];\n        }\n        else\n        {\n            D[bottom+1] = points[second];\n            D[bottom+2] = points[first];\n        }\n        D[bottom] = points[third];\n        D[top] = points[third];\n\n        for (int i = third++; i < int(points.size()); i++)\n        {\n            // test if next vertex is inside the deque hull\n            if ((isLeft(D[bottom], D[bottom+1], points[i]) > 0) &&\n                (isLeft(D[top-1], D[top], points[i]) > 0) )\n                    continue;\n\n            // Find the rightmost vertex to connect to\n            while (isLeft(D[bottom], D[bottom+1], points[i]) <= 0)\n                ++bottom;\n\n            D[--bottom] = points[i];    // insert V[i] at bot of deque\n\n            // find the leftmost vertex to connect to\n            while (isLeft(D[top-1], D[top], points[i]) <= 0)\n                --top;\n\n            D[++top] = points[i];        // push V[i] onto top of deque\n        }\n\n        LineString* result = new LineString;\n        for (int i = 0; i <= (top-bottom); i++)\n        {\n            D[bottom + i].setZ(0);\n            result->addPoint(D[bottom + i]);\n        }\n        if (result->isEmpty()) \n        {\n            delete result;\n            return NULL;\n        }\n        else\n        {\n            Polygon* returnValue = new Polygon;\n            returnValue->addRing(result);\n            return returnValue;\n        }\n    }\n\n//GRAHAM =========================================================================================\n\n    void GrahamHull::findLowest(void)\n    {\n        int n = 0;\n        for (int i = 0; i < num; i++)\n        {\n            if ( (P[n]->p.Y() > P[i]->p.Y()) || (P[n]->p.Y() == P[i]->p.Y() && P[n]->p.X() > P[i]->p.X()) )\n                n = i;\n        }\n\n        if (n != 0) swap(0,n);\n    }\n\n    int GrahamHull::comparePoints(GrahamPoint* a, GrahamPoint* b)\n    {\n        int comp = CrossProduct(P[0]->p,a->p,P[0]->p,b->p);\n        if (comp > 0) return -1;\n        else if (comp < 0) return 1;\n        else\n        {\n            double x = abs(a->p.X() - P[0]->p.X()) - abs(b->p.X() - P[0]->p.X());\n            double y = abs(a->p.Y() - P[0]->p.Y()) - abs(b->p.Y() - P[0]->p.Y());\n\n            if (x<0 || y<0)\n            {\n                a->toDelete = true;\n                return -1;\n            }\n            else if (x>0 || y>0)\n            {\n                b->toDelete = true;\n                return 1;\n            }\n            else\n            {\n                return 0;\n            }\n        }\n    }\n\n    void GrahamHull::swap(int i, int j)\n    {\n        GrahamPoint* temp = P[i];\n        P[i] = P[j];\n        P[j] = temp;\n    }\n\n    void GrahamHull::quickSort(int left, int right)\n    {\n        int i = left, j = right;\n        GrahamPoint* pivot = P[(left + right) / 2];\n\n        while (i <= j) {\n            while (comparePoints(P[i],pivot) < 0)\n                i++;\n            while (comparePoints(P[j],pivot) > 0)\n                j--;\n            if (i <= j) {\n                swap(i,j);\n                i++;\n                j--;\n            }\n        };\n\n        if (left < j)\n            quickSort(left, j);\n        if (i < right)\n            quickSort(i, right);\n    }\n\n    void GrahamHull::sort(void)\n    {\n        quickSort(1,num-1);\n    }\n\n    void GrahamHull::compress(void)\n    {\n    /*    This method doesn't actually delete anything, it just pushes the \"deleted\" points to the end of \n        the vector and ignores them for the rest of the computation.\n    */\n        int j = 0;\n        int i = 0;\n        int nextGroup = 0;\n        \n        //pre compress first group to ensure that the first point is not deleted\n        for (i = 1; i < num; i++)\n        {\n            if (P[0]->p.equals(&P[i]->p)) nextGroup++;\n            else break;\n        }\n        j = 1;\n\n        //compress the rest of the array\n        for (i = nextGroup+1; i < num; i++)\n        {\n            bool deleteGroup = false;\n            nextGroup = i;\n\n            //Find the end of this duplicate group\n            for (int k = i+1; k < num; k++)\n            {\n                if (P[k]->p.equals(&P[i]->p))\n                {\n                    if (P[k]->toDelete) deleteGroup = true;\n                    nextGroup++;\n                }\n                else break;\n            }\n\n            if (!P[i]->toDelete && !deleteGroup)\n            {\n                P[j] = P[i];\n                j++;\n            }\n            i = nextGroup;\n        }\n\n        num = j;\n    }\n\n    void GrahamHull::compute(void)\n    {\n        if (num == 0)\n        {\n            return;\n        }\n        else if (num == 1)\n        {\n            hull.push_back(_P[0].p);\n        }\n        else if (num == 2)\n        {\n            hull.push_back(_P[0].p);\n            hull.push_back(_P[1].p);\n        }\n        else if (num == 3)\n        {\n            hull.push_back(_P[0].p);\n            hull.push_back(_P[1].p);\n            hull.push_back(_P[2].p);\n            hull.push_back(_P[0].p);\n\n            if (    (hull[1].X() - hull[0].X())*(hull[2].Y() - hull[0].Y()) <\n                    (hull[2].X() - hull[0].X())*(hull[1].Y() - hull[0].Y()) )\n                    std::reverse(hull.begin(),hull.end());\n        }\n        else\n        {\n            findLowest();\n            sort();\n            compress();\n\n        /*    \n            Quick test to ensure there is a hull..if there are only 2 points in the queue, then that means\n            the rest were deleted because of collinearity, meaning the result is simple a line between the two\n            points.\n        */\n            if (num == 2)\n            {\n                hull.push_back(P[0]->p);\n                hull.push_back(P[1]->p);\n                hull.push_back(hull.front());\n                return;\n            }\n\n        //    Create Resulting Hull\n            hull.push_back(P[0]->p);\n            hull.push_back(P[1]->p);\n            hull.push_back(P[2]->p);\n\n            int i = 3;\n\n            while (i < num)\n            {\n                Point p1 = hull[hull.size() - 2];\n                Point p2 = hull.back();\n                if (CrossProduct(p1,p2,p1,P[i]->p) > 0)\n                {\n                    hull.push_back(P[i]->p);\n                    i++;\n                }\n                else\n                {\n                    hull.pop_back();\n                }\n\n            }\n        \n        //    Close hull\n            hull.push_back(hull.front());\n        }\n\n    //    cleanup\n        _P.clear();\n        P.clear();\n        num = int(hull.size());\n    }\n    \n    GrahamHull::GrahamHull(const std::vector<Point>& points)\n    {\n        // First snap all points to a grid using SFA_EPSILON\n        // This Graham Hull algorithm falls apart when points are too \n        // close together because the left/right detection fails.\n        // There is a bug in this code that causes both points to be deleted\n        // in some cases where two points are within SFA_EPSILON distance.\n        // For now this is an effective workaround to that problem\n        const double epsilon = SFA_EPSILON;\n        std::set<sfa::Point> grid;//All unique points here\n        BOOST_FOREACH(sfa::Point pt,points)\n        {\n            double closest_dist = DBL_MAX;\n            BOOST_FOREACH(const sfa::Point &gridpt,grid)\n            {\n                closest_dist = std::min<double>(closest_dist,gridpt.distance(&pt));\n            }\n            // If pt is not within epsilon distance from any grid point, insert pt into the grid\n            if(closest_dist>epsilon)\n            {\n                grid.insert(pt);\n            }\n        }\n        std::vector<sfa::Point> snappedPoints;\n        snappedPoints.insert(snappedPoints.begin(),grid.begin(),grid.end());\n\n        num = int(snappedPoints.size());\n        _P.reserve(num);\n        for (int j = 0; j < num; j++)\n        {\n            _P.push_back(GrahamPoint(snappedPoints[j]));\n            _P.back().p.setZ(0);\n            P.push_back(&_P.back());\n        }\n\n        compute();\n    }\n\n    GrahamHull::GrahamHull(const MultiPoint* a)\n    {\n        num = a->getNumGeometries();\n        _P.reserve(num);\n        for (int j = 0; j < num; j++)\n        {\n            _P.push_back(GrahamPoint(*static_cast<Point*>(a->getGeometryN(j+1))));\n            _P.back().p.setZ(0);\n            P.push_back(&_P.back());\n        }\n\n        compute();\n    }\n\n    Geometry* GrahamHull::getHullGeometry(void)\n    {\n        if (num == 0)\n            return NULL;\n        else if (num == 1)\n            return new Point(hull[0]);\n        else\n        {\n            LineString* line = new LineString;\n            for (std::vector<Point>::iterator it = hull.begin(), end = hull.end(); it != end; it++)\n                line->addPoint(*it);\n            if (num == 2)\n                return line;\n            else\n            {\n                Polygon* polygon = new Polygon;\n                polygon->addRing(line);\n                return polygon;\n            }\n        }\n    }\n\n    std::vector<Point> GrahamHull::getHullPoints(void)\n    {\n        return hull;\n    }\n\n    Geometry* GrahamHull::apply(const MultiPoint* a)\n    {\n        GrahamHull hull(a);\n        return hull.getHullGeometry();\n    }\n\n    std::vector<Point> GrahamHull::apply(const std::vector<Point>& points)\n    {\n        GrahamHull hull(points);\n        return hull.getHullPoints();\n    }\n\n}\n", "meta": {"hexsha": "6c129dc097e2c672d25f2de87672b7ca8f2a5f72", "size": 12410, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cognitics/src/sfa/ConvexHull.cpp", "max_stars_repo_name": "mikedig/cdb-productivity-api", "max_stars_repo_head_hexsha": "e2bedaa550a8afa780c01f864d72e0aebd87dd5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cognitics/src/sfa/ConvexHull.cpp", "max_issues_repo_name": "mikedig/cdb-productivity-api", "max_issues_repo_head_hexsha": "e2bedaa550a8afa780c01f864d72e0aebd87dd5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cognitics/src/sfa/ConvexHull.cpp", "max_forks_repo_name": "mikedig/cdb-productivity-api", "max_forks_repo_head_hexsha": "e2bedaa550a8afa780c01f864d72e0aebd87dd5a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3380614657, "max_line_length": 110, "alphanum_fraction": 0.4628525383, "num_tokens": 3031, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342624, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.49104597475400547}}
{"text": "#define EIGEN_USE_MKL_ALL\n#define MLT_VERBOSE\n\n\n#include <vector>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <iomanip>\n#include <chrono>\n\n#include <Eigen/Core>\n\n#include \"utils/optimizers/stochastic_gradient_descent.hpp\"\n#include \"utils/loss_functions.hpp\"\n#include \"utils/activation_functions.hpp\"\n#include \"../misc.hpp\"\n#include \"models/transformers/sparse_autoencoder.hpp\"\n#include \"models/classifiers/optimizable_linear_classifier.hpp\"\n#include \"models/classifiers/perceptron.hpp\"\n\nusing namespace std;\n\nusing namespace Eigen;\n\nusing namespace mlt::models::transformers;\nusing namespace mlt::models::classifiers;\nusing namespace mlt::utils;\n\nvector<vector<double>> parseCsv(string file, bool skipFirstLine, char delim = ',') {\n\tvector<vector<double>> result;\n\n\tifstream str(file.c_str());\n\t\tstring line;\n\n\tif (skipFirstLine) {\n\t\tgetline(str, line);\n\t}\n\n\twhile (getline(str, line)) {\n\t\tvector<double> currentLine;\n\t\tstringstream lineStream(line);\n\t\tstring cell;\n\n\t\twhile (getline(lineStream, cell, delim)) {\n\t\t\tcurrentLine.push_back(stod(cell));\n\t\t}\n\n\t\tresult.push_back(currentLine);\n\t}\n\n\treturn result;\n}\n\ntuple<MatrixXd, VectorXi> load_training_data(string file) {\n\tauto data = parseCsv(file, true);\n\tMatrixXd features(data[0].size(), data.size());\n\tVectorXi classes(data.size());\n\n\tfor(auto i = 0; i < data.size(); i++) {\n\t\tclasses(i) = data[i][0];\n\t\tfor (auto j = 1; j < data[i].size(); j++) {\n\t\t\tfeatures(j - 1, i) = data[i][j] / 255.0;\n\t\t}\n\t}\n\n\treturn{ features, classes };\n}\n\nMatrixXd load_test_data(string file) {\n\tauto data = parseCsv(file, true);\n\tMatrixXd features(data[0].size(), data.size());\n\n\tfor (auto i = 0; i < data.size(); i++) {\n\t\tfor (auto j = 0; j < data[i].size(); j++) {\n\t\t\tfeatures(j, i) = data[i][j] / 255.0;\n\t\t}\n\t}\n\n\treturn features;\n}\n\nvoid output_result(const VectorXi& result, string filename) {\n\tofstream outputFile(filename, ofstream::app);\n\n\toutputFile << \"ImageId,Label\" << endl;\n\n\tfor (size_t i = 0; i < result.rows(); i++) {\n\t\toutputFile << i + 1 << \",\" << result(i) << endl;\n\t}\n\n\toutputFile.close();\n\n}\n\nstring current_date_time() {\n\tauto now = chrono::system_clock::now();\n\tauto in_time_t = chrono::system_clock::to_time_t(now);\n\n\tstringstream ss;\n\tss << put_time(localtime(&in_time_t), \"%Y%m%d%H%M%S\");\n\treturn ss.str();\n}\n\ntemplate <class Model, class TargetType>\ndouble split_crossvalidation(Model& model, const MatrixXd& features, const TargetType& target, double training_percentage) {\n\tassert(features.cols() == target.cols() || (target.cols() == 1 && features.cols() == target.rows()));\n\tassert(training_percentage > 0 && training_percentage < 1);\n\tauto training = static_cast<size_t>(round(features.cols() * training_percentage));\n\tauto validation = features.cols() - training;\n\tassert(training > 0 && validation > 0);\n\n\tauto training_features = features.leftCols(training);\n\tauto training_target = target.cols() == 1 ? target.block(0, 0, training, 1) : target.block(0, 0, target.rows(), training);\n\tauto validation_features = features.rightCols(validation);\n\tauto validation_target = target.cols() == 1 ? target.block(training, 0, validation, 1) : target.block(0, training, target.rows(), validation);\n\n\tmodel.fit(training_features, training_target);\n\n\treturn model.score(validation_features, validation_target);\n}\n\ntemplate <class Transformation, class Model, class TargetType>\ndouble split_crossvalidation(Transformation& transformation, Model& model, const MatrixXd& features, const TargetType& target, double training_percentage) {\n\tassert(features.cols() == target.cols() || (target.cols() == 1 && features.cols() == target.rows()));\n\tassert(training_percentage > 0 && training_percentage < 1);\n\tauto training = static_cast<size_t>(round(features.cols() * training_percentage));\n\tauto validation = features.cols() - training;\n\tassert(training > 0 && validation > 0);\n\n\tauto training_features = features.leftCols(training);\n\tauto training_target = target.cols() == 1 ? target.block(0, 0, training, 1) : target.block(0, 0, target.rows(), training);\n\tauto validation_features = features.rightCols(validation);\n\tauto validation_target = target.cols() == 1 ? target.block(training, 0, validation, 1) : target.block(0, training, target.rows(), validation);\n\n\ttransformation.fit(training_features, training_target);\n\tmodel.fit(transformation.transform(training_features), training_target);\n\n\treturn model.score(transformation.transform(validation_features), validation_target);\n}\n\nint main() {\n\tprint_info();\n\tcout << endl;\n\n\tMatrixXd features;\n\tVectorXi classes;\n\n\ttie(features, classes) = load_training_data(\"train.csv\");\n\n\t//auto output_filename = \"digit_recognizer_cross_val_\" + current_date_time() + \".csv\";\n\t//ofstream output_file(output_filename);\n\n\t//output_file << \"Type;Batch Size;Learning Rate;Weight Decay;L2 Regularization;Score\" << endl;\n\n\tfor (auto batch_size : { 512, 256, 1024, 2048 }) {\n\t\tfor (auto learning_rate : { 0.1, 0.01, 0.001, 0.0001 }) {\n\t\t\tfor (auto decay : { 0.99, 0.95 }) {\n\t\t\t\tfor (auto regularization : { 0.005, 0.0005 }) {\n\n\t\t\t\t\tusing loss_t = loss_functions::SoftmaxLoss;\n\t\t\t\t\tusing act_t = activation_functions::SigmoidActivation;\n\t\t\t\t\tusing opt_t = optimizers::StochasticGradientDescent<>;\n\n\t\t\t\t\tloss_t loss;\n\t\t\t\t\tact_t act;\n\t\t\t\t\topt_t opt1(batch_size, 10, 0.001, decay);\n\t\t\t\t\topt_t opt2(batch_size, 200, learning_rate, decay);\n\n\t\t\t\t\t//auto model1 = create_sparse_autoencoder(196, act, act, opt1, 3e-3, 0.1, 3);\n\t\t\t\t\tauto model1 = create_perceptron(200, true, learning_rate, true);\n\t\t\t\t\tauto model2 = OptimizableLinearClassifier<loss_t, opt_t>(loss, opt2, regularization, true);\n\n\t\t\t\t\t//auto score = split_crossvalidation(model1, model2, features, classes, 0.8);\n\t\t\t\t\t//cout << \"Score for SparseAutoencoder -> Softmax \" << batch_size << \" \" << learning_rate << \" \" << decay << \" \" << regularization << \": \" << score << endl;\n\t\t\t\t\t//output_file << \"SparseAutoencoder -> Softmax;\" << batch_size << \";\" << learning_rate << \";\" << decay << \";\" << regularization << \";\" << score << endl;\n\n\t\t\t\t\tauto score = split_crossvalidation(model1, features, classes, 0.8);\n\t\t\t\t\tcout << \"Score for Perceptron \" << batch_size << \" \" << learning_rate << \" \" << decay << \" \" << regularization << \": \" << score << endl;\n\t\t\t\t\t// output_file << \"SparseAutoencoder -> Softmax;\" << batch_size << \";\" << learning_rate << \";\" << decay << \";\" << regularization << \";\" << score << endl;\n\n\t\t\t\t\tauto score2 = split_crossvalidation(model2, features, classes, 0.8);\n\t\t\t\t\tcout << \"Score for Softmax \" << batch_size << \" \" << learning_rate << \" \" << decay << \" \" << regularization << \": \" << score2 << endl;\n\t\t\t\t\t//output_file << \"Softmax;\" << batch_size << \";\" << learning_rate << \";\" << decay << \";\" << regularization << \";\" << score2 << endl;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tcin.get();\n\n\treturn 0;\n}", "meta": {"hexsha": "7deb2a971c3fa7af7d8333af1b92930925fb7a4d", "size": 6763, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/digit_recognizer/main.cpp", "max_stars_repo_name": "fedeallocati/MachineLearningToolkit", "max_stars_repo_head_hexsha": "8614ee2c8c5211a3eefceb10a50576e0485cefd9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-08-31T11:43:19.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-22T11:03:47.000Z", "max_issues_repo_path": "src/digit_recognizer/main.cpp", "max_issues_repo_name": "fedeallocati/MachineLearningToolkit", "max_issues_repo_head_hexsha": "8614ee2c8c5211a3eefceb10a50576e0485cefd9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/digit_recognizer/main.cpp", "max_forks_repo_name": "fedeallocati/MachineLearningToolkit", "max_forks_repo_head_hexsha": "8614ee2c8c5211a3eefceb10a50576e0485cefd9", "max_forks_repo_licenses": ["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.0414507772, "max_line_length": 161, "alphanum_fraction": 0.6840159692, "num_tokens": 1713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4910459747540054}}
{"text": "//\n//  su3_x.hpp\n//  Lattice\n//\n//  Created by Evan Owen on 10/19/18.\n//  Copyright \u00a9 2018 Evan Owen. All rights reserved.\n//\n\n#ifndef su3_x_hpp\n#define su3_x_hpp\n\n#include <random>\n#include <complex>\n#include <Eigen/Dense>\n\nclass su3_x_lattice;\ntypedef Eigen::Matrix<std::complex<double>, 3, 3> su3_link;\ntypedef Eigen::Matrix<std::complex<double>, 1, 3> su3_vector;\n#define su3_identity su3_link::Identity()\n#define su3_zero su3_link::Zero()\n\ntypedef Eigen::Matrix<std::complex<double>, 2, 2> su2_link;\n#define su2_identity su2_link::Identity()\n#define su2_zero su2_link::Zero()\n\n#define I complex<double>(0,1)\n#define Q(s) s->link[0]\n#define D_MAX 6\n#define SQRT3   1.73205080756887729352744634151  // sqrt(3)\n#define SQRT1_3 0.577350269189625764509148780502 // 1 / sqrt(3)\n\nclass su3_x_site {\npublic:\n    // variables\n    su3_x_lattice* lattice; // parent lattice\n    su3_link link[D_MAX]; // link values in each direction\n    su3_link link_inverse[D_MAX]; // link inverse values\n    su3_link p_link[D_MAX]; // conjugate momenta in each direction\n    su3_x_site* forward[D_MAX]; // adjacent sites in the forward direction\n    su3_x_site* backward[D_MAX]; // adjacent sites in the backward direction\n    std::mt19937* gen; // random number generator for this time-slice\n    bool forward_edge; // site is at the forward edge of the extra dimension\n    bool backward_edge; // site is at the backward edge of the extra dimension\n    bool is_locked;\n    double eps;\n    su3_link wf_z[D_MAX]; // exponent for wilson flow\n\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    \n    // methods\n    void init(su3_x_lattice* lattice, su3_x_site* lattice_sites, int s);\n    su3_link make_unitary(const su3_link& g);\n    su3_link cayley_ham(const su3_link& Q);\n    bool lock();\n    void unlock();\n    double rand_double(double min = 0.0, double max = 1.0);\n    int rand_int(int min, int max);\n    double rand_normal(double mean = 0.0, double stdev = 1.0);\n    void reset_links(bool cold);\n    void copy_links(su3_x_site* site);\n    void read_links(std::ifstream& ckptFile, bool bigEndian);\n    void set_link(int d, const su3_link& value);\n    void init_momenta();\n    su2_link create_su2(bool random);\n    su3_link create_link(bool random);\n    double action();\n    double hamiltonian();\n    void hmc_step_p(double frac);\n    void hmc_step_link();\n    su3_link p_link_dot(int d);\n    double link_trace();\n    double plaq();\n    su3_link plaquette(int d1, int d2);\n    su3_link staple(int d1);\n    su3_link reverse_staple(int d1);\n    su3_link staple_x(int d1);\n    su3_link reverse_staple_x(int d1);\n    su3_link cloverleaf(int d1, int d2);\n    double wilson_loop(int a, int b);\n    std::complex<double> polyakov_loop(int r);\n    double correlator(int T);\n    double field_strength();\n//    double field_strength_x();\n    double topological_charge();\n    double mag_U();\n    double abs_U();\n    double four_point(int T, int R);\n    su3_link overrelax(su3_link g);\n    void relax(bool coulomb);\n    double sum_landau();\n    double sum_coulomb();\n    su3_link sum_G(bool coulomb);\n    double heat_bath();\n    double heat_bath_link(int d1);\n    void cool();\n    void cool_link(int d1);\n    void wilson_flow(su3_x_site* target, int step);\n    void wilson_flow_link(su3_x_site* target, int step, int d);\n    void stout_smear(su3_x_site* target, double rho);\n    void stout_smear_link(su3_x_site* target, double rho, int d1);\n};\n\nclass su3_x_lattice {\npublic:\n    // variables\n    int N; // array size (spacial)\n    int T; // array size (time)\n    int N5; // 5th dimension size\n    int D; // number of dimensions\n    double beta; // coupling factor\n    double eps5; // ratio of coupling in extra dimension to normal coupling\n    int n_sites; // number of sites in the entire lattice\n    int n_sites_5; // number of sites in a 5d sub-lattice\n    int n_slice; // number of sites in each time slice of the entire lattice\n    int n5_center; // center lattice\n    std::vector<su3_x_site> site; // site values\n    std::vector<std::mt19937> gen; // array of random number generators (one for each time-slice)\n    std::vector<su2_link> sigma; // pauli spin matrices\n    std::vector<su3_link> lambda; // gell-mann matrices\n    double z; // heat bath metropolis factor\n    int verbose;\n    bool parallel;\n\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n    // hmc\n    std::vector<su3_x_site> site_1; // site values for hmc\n    double dt; // hmc step size\n    int n_steps; // hmc step count\n    int hmc_accept; // number of accepted hmc configurations\n    int hmc_count; // number of attempted hmc configurations\n\n    // time step for wilson flow algorithm\n    double wf_dt;\n    \n    // methods\n    su3_x_lattice(int N, int T, int N5, int D, double beta, double eps5, bool cold = false);\n    su3_x_lattice(su3_x_lattice* lattice);\n    su3_x_lattice(int N, int T, int N5, int D, double beta, double eps5, std::ifstream& ckptFile, bool isNersc = false);\n    ~su3_x_lattice();\n    void init();\n    double rand_double(double min = 0.0, double max = 1.0);\n    int rand_int(int min, int max);\n    double rand_normal(double mean = 0.0, double stdev = 1.0);\n    int get_site(int s, int d, int n);\n    double link_trace();\n    double plaq(int n5);\n    double action(int n5);\n    double wilson_loop(int a, int b, int n5);\n    double polyakov_loop(int R, int n5);\n    double correlator(int T, int n5);\n    double four_point(int T, int R, int n5);\n    double hamiltonian();\n    void hmc(int n_sweeps = 0, bool update_dt = false, bool no_metropolis = false);\n    void heat_bath(int n_sweeps = 0);\n    void cool(int n5, int n_sweeps = 0);\n//    void wilson_flow(int n_sweeps = 0);\n    void wilson_flow(int n5, int n_sweeps = 0);\n    void stout_smear(int n5, double rho = 0.1, int n_sweeps = 0);\n    double field_strength(int n5);\n//    double field_strength_x(int n5);\n    double topological_charge(int n5);\n    int thermalize(int n_min = 0, int n_max = 0);\n    double ave_link_t(int n5);\n    double theta(bool coulomb, int n5);\n    long double relax(long double error_target, bool coulomb, int n5);\n    void write_four_point(const char* filename, bool coulomb, int n5);\n    void write_correlator(const char* filename, bool coulomb, int n5);\n};\n\n#endif /* su3_x_hpp */\n", "meta": {"hexsha": "23156af3d86c182301a8cb623a0338d21642f4cf", "size": 6206, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "su3_x/su3_x.hpp", "max_stars_repo_name": "ekowen86/lattice", "max_stars_repo_head_hexsha": "878b59a5b1ce79328c2f57a8133ddfa65186536a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-06-23T02:02:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T15:11:34.000Z", "max_issues_repo_path": "su3_x/su3_x.hpp", "max_issues_repo_name": "ekowen86/lattice", "max_issues_repo_head_hexsha": "878b59a5b1ce79328c2f57a8133ddfa65186536a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "su3_x/su3_x.hpp", "max_forks_repo_name": "ekowen86/lattice", "max_forks_repo_head_hexsha": "878b59a5b1ce79328c2f57a8133ddfa65186536a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-01T19:37:34.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-01T19:37:34.000Z", "avg_line_length": 36.0813953488, "max_line_length": 120, "alphanum_fraction": 0.6911053819, "num_tokens": 1800, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4910459747540054}}
{"text": "\n#include <test_common.h>\n#include <igl/triangle_triangle_adjacency.h>\n#include <Eigen/Geometry>\n\n\nTEST_CASE(\"triangle_triangle_adjacency: dot\", \"[igl]\")\n{\n  const auto test_case = [](const std::string &param)\n  {\n    Eigen::MatrixXd V;\n    Eigen::MatrixXi F,TT,TTi;\n    // Load example mesh: GetParam() will be name of mesh file\n    test_common::load_mesh(param, V, F);\n    igl::triangle_triangle_adjacency(F,TT,TTi);\n    REQUIRE (TT.rows() == F.rows());\n    REQUIRE (TTi.rows() == F.rows());\n    REQUIRE (TT.cols() == F.cols());\n    REQUIRE (TTi.cols() == F.cols());\n    for(int f = 0;f<F.rows();f++)\n    {\n      for(int c = 0;c<3;c++)\n      {\n        if(TT(f,c) >= 0)\n        {\n          REQUIRE (F.rows() > TT(f,c));\n          REQUIRE (0 <= TTi(f,c));\n          REQUIRE (3 > TTi(f,c));\n          REQUIRE (f == TT(TT(f,c),TTi(f,c)));\n        }\n      }\n    }\n    // REQUIRE (b == a);\n    // REQUIRE (a==b);\n    // REQUIRE(a == Approx(b).margin(1e-15))\n    // REQUIRE (1e-12 > a);\n  };\n\n  test_common::run_test_cases(test_common::manifold_meshes(), test_case);\n}\n", "meta": {"hexsha": "5ba83227085a228db1a9dd02ff4295944dadbb13", "size": 1064, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "External/libigl-2.1.0/tests/include/igl/triangle_triangle_adjacency.cpp", "max_stars_repo_name": "RokKos/eol-cloth", "max_stars_repo_head_hexsha": "b9c6f55f25ba17f33532ea5eefa41fedd29c5206", "max_stars_repo_licenses": ["MIT"], "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/libigl-2.1.0/tests/include/igl/triangle_triangle_adjacency.cpp", "max_issues_repo_name": "RokKos/eol-cloth", "max_issues_repo_head_hexsha": "b9c6f55f25ba17f33532ea5eefa41fedd29c5206", "max_issues_repo_licenses": ["MIT"], "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/libigl-2.1.0/tests/include/igl/triangle_triangle_adjacency.cpp", "max_forks_repo_name": "RokKos/eol-cloth", "max_forks_repo_head_hexsha": "b9c6f55f25ba17f33532ea5eefa41fedd29c5206", "max_forks_repo_licenses": ["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.9512195122, "max_line_length": 73, "alphanum_fraction": 0.5432330827, "num_tokens": 317, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195385342971, "lm_q2_score": 0.6688802669716106, "lm_q1q2_score": 0.49103807292389623}}
{"text": "#include <Eigen/Core>\n\n#include <numpy_eigen/boost_python_headers.hpp>\nEigen::Matrix<int, 6, 5> test_int_6_5(const Eigen::Matrix<int, 6, 5> & M)\n{\n\treturn M;\n}\nvoid export_int_6_5()\n{\n\tboost::python::def(\"test_int_6_5\",test_int_6_5);\n}\n\n", "meta": {"hexsha": "0f68a73bc7bf7e87092ed8c6dbfbe67b2e77a9d6", "size": 237, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Schweizer-Messer/numpy_eigen/src/autogen_test_module/test_6_5_int.cpp", "max_stars_repo_name": "PushyamiKaveti/kalibr", "max_stars_repo_head_hexsha": "d8bdfc59ee666ef854012becc93571f96fe5d80c", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": 2690.0, "max_stars_repo_stars_event_min_datetime": "2015-01-07T03:50:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T20:27:01.000Z", "max_issues_repo_path": "Schweizer-Messer/numpy_eigen/src/autogen_test_module/test_6_5_int.cpp", "max_issues_repo_name": "PushyamiKaveti/kalibr", "max_issues_repo_head_hexsha": "d8bdfc59ee666ef854012becc93571f96fe5d80c", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": 481.0, "max_issues_repo_issues_event_min_datetime": "2015-01-27T10:21:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T14:02:41.000Z", "max_forks_repo_path": "Schweizer-Messer/numpy_eigen/src/autogen_test_module/test_6_5_int.cpp", "max_forks_repo_name": "PushyamiKaveti/kalibr", "max_forks_repo_head_hexsha": "d8bdfc59ee666ef854012becc93571f96fe5d80c", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": 1091.0, "max_forks_repo_forks_event_min_datetime": "2015-01-26T21:21:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T01:55:33.000Z", "avg_line_length": 18.2307692308, "max_line_length": 73, "alphanum_fraction": 0.7172995781, "num_tokens": 83, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195152660687, "lm_q2_score": 0.6688802471698041, "lm_q1q2_score": 0.4910380428233448}}
{"text": "#include <doctest/doctest.h>\n\n#include <Eigen/Dense>\n#include <robotics/linear_control/lqr.hpp>\n#include <string>\n\nTEST_CASE(\"Robotics\")\n{\n    static constexpr int N = 2;\n    static constexpr int M = 1;\n\n    const double dt = 0.1;\n\n    // State matrix\n    Robotics::SquareMatrix<N> A;\n    A << dt, 1.0, 0, dt;\n\n    // Control matrix\n    Robotics::Matrix<N, M> B;\n    B << 0, 1;\n\n    // Weights\n    Robotics::SquareMatrix<N> Q = Robotics::SquareMatrix<N>::Identity();\n    Robotics::SquareMatrix<M> R = Robotics::SquareMatrix<M>::Identity();\n\n    Robotics::LinearControl::LQR<N, M> planner(A, B, Q, R);\n\n    CHECK(true == true);\n}", "meta": {"hexsha": "e009b885f4bb486a8b7d790a776115def8a70085", "size": 628, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/source/linear_control/lqr.cpp", "max_stars_repo_name": "JKI757/CppRobotics", "max_stars_repo_head_hexsha": "469ce89f826b4cb981b017d9112ed311f39114b5", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 286.0, "max_stars_repo_stars_event_min_datetime": "2021-09-27T20:58:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T19:12:10.000Z", "max_issues_repo_path": "test/source/linear_control/lqr.cpp", "max_issues_repo_name": "imthemd/CppRobotics", "max_issues_repo_head_hexsha": "469ce89f826b4cb981b017d9112ed311f39114b5", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2021-09-28T02:19:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-30T19:46:08.000Z", "max_forks_repo_path": "test/source/linear_control/lqr.cpp", "max_forks_repo_name": "imthemd/CppRobotics", "max_forks_repo_head_hexsha": "469ce89f826b4cb981b017d9112ed311f39114b5", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2021-09-28T01:26:15.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T11:01:01.000Z", "avg_line_length": 21.6551724138, "max_line_length": 72, "alphanum_fraction": 0.6242038217, "num_tokens": 184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888302, "lm_q2_score": 0.5506073655352403, "lm_q1q2_score": 0.4910377334502951}}
{"text": "#include <boost/random/lognormal_distribution.hpp>\n", "meta": {"hexsha": "b5667f73f0e9a456a4d3ab75b56d56528c404edd", "size": 51, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_random_lognormal_distribution.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_random_lognormal_distribution.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_random_lognormal_distribution.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 25.5, "max_line_length": 50, "alphanum_fraction": 0.8431372549, "num_tokens": 9, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8080672320414786, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.49103269566041563}}
{"text": "#define EIGEN_DEFAULT_DENSE_INDEX_TYPE int32_t\n\n#include \"../../../repos/stl_reader/stl_reader.h\"\n#include <map>\n#include <array>\n#include <deque>\n#include <chrono>\n#include <random>\n#include <vector>\n#include <fstream>\n#include <iostream>\n#include <unordered_set>\n#include <Eigen/Dense>\n\nusing Vertex = Eigen::Vector3f;\nusing Transform = Eigen::Transform<float, 3, Eigen::Affine>;\nusing Triangle = std::array<Vertex, 3u>;\nusing CudaTriangle = Vertex*;\nusing CudaConstTriangle = Vertex const*;\nusing Mesh = std::vector<Triangle>;\n\n// usage ./IntersectionReference example23.in \n\nconstexpr float    cgPi                            =    3.1415926539f;\nconstexpr int32_t  cgSphereSectors                 =    11;\nconstexpr int32_t  cgSphereBelts                   =    5;\nconstexpr float    cgMaxSphereRadius               =   17.0f;\nconstexpr float    cgMaxTriangleSide               = cgMaxSphereRadius * 2.0f;\nconstexpr float    cgCalculateSpheresInflate       =    0.51f;\nconstexpr int32_t  cgCalculateSpheresNeighbours    =    3;\nconstexpr float    cgApproximateLeaveInPlaceFactor =    0.01f;\nconstexpr uint32_t cgApproximateResultSize         =   64u;       // TODO remove and use total surface to compute this value T = sqrt(s*(s-c)*(s-b)*(s-a))\nconstexpr int32_t  cgApproximateIterations         = 4444u;       // TODO perhaps depends on the result size\nconstexpr float    cgApproximateTemperatureFactor  =    0.001f;\n\nEigen::Matrix3f randomTransform() {\n  std::default_random_engine generator;\n  generator.seed((std::chrono::high_resolution_clock::now() - std::chrono::high_resolution_clock::time_point::min()).count());\n  std::uniform_real_distribution<float> distribution(0.1f, 1.0f);\n  Eigen::Matrix3f result;\n  for(int32_t i = 0; i < 9; ++i) {\n    result(i / 3, i % 3) = distribution(generator);\n  }\n  return result;\n}\n\nstd::deque<Triangle> divideLargeTriangles(std::deque<Triangle> &aMesh) {\n  std::deque<Triangle> result;\n  for(auto const &triangle : aMesh) {\n    float maxSide = (triangle[0] - triangle[1]).norm();\n    maxSide = std::max(maxSide, (triangle[0] - triangle[2]).norm());\n    maxSide = std::max(maxSide, (triangle[1] - triangle[2]).norm());\n    int32_t divisor = static_cast<int32_t>(std::ceil(maxSide / cgMaxTriangleSide));\n    auto vector01 = (triangle[1] - triangle[0]) / divisor;\n    auto vector02 = (triangle[2] - triangle[0]) / divisor;\n    auto lineBase = triangle[0];\n    auto base0 = lineBase;\n    auto base1 = (divisor > 1) ? (base0 + vector01) : triangle[1];\n    auto base2 = (divisor > 1) ? (base0 + vector02) : triangle[2];\n    for(int i = 0; i < divisor - 1; ++i) {\n      for(int j = 0; j < divisor - i - 1; j++) {\n        result.push_back({base0, base1, base2});\n        auto base1next = base1 + vector02;\n        result.push_back({base1, base1next, base2});\n        base1 = base1next;\n        base0 = base2;\n        base2 += vector02;\n      }\n      result.push_back({base0, base1, base2});\n      lineBase += vector01;\n      base0 = lineBase;\n      base1 = base0 + vector01;\n      base2 = base0 + vector02;\n    }\n    result.push_back({base0, triangle[1], base2});\n  }\n  return result;\n}\n\nauto readMesh(std::string const &aFilename, Eigen::Vector3f aTranslation, Eigen::Matrix3f const &aTransform) {\n  std::deque<Triangle> work;\n  stl_reader::StlMesh<float, int32_t> mesh(aFilename);\n  for(int32_t indexTriangle = 0; indexTriangle < mesh.num_tris(); ++indexTriangle) {\n    Triangle triangle;\n    for(int32_t indexCorner = 0; indexCorner < 3; ++indexCorner) {\n      float const * const coords = mesh.tri_corner_coords(indexTriangle, indexCorner);\n      Eigen::Vector3f in;\n      for(int32_t i = 0; i < 3; ++i) {\n        in(i) = coords[i];\n      }\n      triangle[indexCorner] = /*aTransform **/ (in + aTranslation);\n    }\n    work.push_back(triangle);\n  }\n  std::cout << \"bef: \" << work.size();\n  work = divideLargeTriangles(work);\n  std::cout << \" aft: \" << work.size() << '\\n';\n  return Mesh(work.cbegin(), work.cend());\n}\n\nauto readMesh(char const * const aFilename, Eigen::Matrix3f const &aTransform) {\n  std::ifstream in(aFilename);\n  std::string filename1, filename2;\n  Eigen::Vector3f translation;\n  in >> filename1 >> filename2 >> translation(0) >> translation(1) >> translation(2);\n  std::cout << filename1 << '\\n' << filename2 << '\\n';\n  return std::pair(readMesh(filename1, {0.0f, 0.0f, 0.0f}, aTransform), readMesh(filename2, translation, aTransform));\n}\n\nvoid writeMesh(Mesh const &aMesh1, Mesh const &aMesh2, char const * const aFilename) {\n  std::ofstream out(aFilename);\n  out << \"solid Exported from Blender-2.82 (sub 7)\\n\";\n  for(auto const & triangle : aMesh1) {\n    out << \"facet normal 0.000000 0.000000 0.000000\\nouter loop\\n\";\n    for(auto const & vertex : triangle) {\n      out << \"vertex \" << vertex(0) << ' ' << vertex(1) << ' ' << vertex(2) << '\\n';\n    }\n    out << \"endloop\\nendfacet\\n\";\n  }\n  for(auto const & triangle : aMesh2) {\n    out << \"facet normal 0.000000 0.000000 0.000000\\nouter loop\\n\";\n    for(auto const & vertex : triangle) {\n      out << \"vertex \" << vertex(0) << ' ' << vertex(1) << ' ' << vertex(2) << '\\n';\n    }\n    out << \"endloop\\nendfacet\\n\";\n  }\n  out << \"endsolid Exported from Blender-2.82 (sub 7)\\n\";\n}\n\nfloat calculateDistanceSum(std::unordered_set<uint32_t> const &aIndices, std::deque<Vertex> const &aVertices) {\n  std::vector<Vertex> selection;\n  selection.reserve(cgApproximateResultSize);\n  for(auto const &i : aIndices) {\n    selection.push_back(aVertices[i]);\n  }\n  float sum;\n  for(uint32_t i = 0u; i < cgApproximateResultSize; ++i) {\n    for(uint32_t j = 0u; j < i; ++j) {\n      auto diffSquared = (selection[i] - selection[j]).squaredNorm();\n      sum += -1.0f / diffSquared;\n    }\n  }\n  return sum;\n}\n\nstd::vector<Vertex> approximate(Mesh const aMesh, float const aMedianSideSizeHarmonic) {\n  std::deque<Vertex> all;\n  std::deque<Vertex> reference;\n  float limit = aMedianSideSizeHarmonic * cgApproximateLeaveInPlaceFactor;\n  for(auto const &triangle : aMesh) {\n    for(auto const &vertex : triangle) {\n      bool was = false;\n      for(auto const &ref : reference) {\n        if((ref - vertex).norm() < limit) {\n          was = true;\n          break;\n        }\n        else { // nothing to do\n        }\n      }\n      if(!was) {\n        reference.push_back(vertex);\n      }\n      else { // nothing to do\n      }\n    }\n  }\n  std::default_random_engine generator;\n  generator.seed((std::chrono::high_resolution_clock::now() - std::chrono::high_resolution_clock::time_point::min()).count());\n  std::uniform_int_distribution<uint32_t> distributionAll(0, reference.size() - 1);\n  std::uniform_int_distribution<uint32_t> distributionSubset(0, cgApproximateResultSize - 1);\n  std::uniform_real_distribution<float> distributionFloat(0.0f, 1.0f);\n  std::unordered_set<uint32_t> actualIndices;\n  std::cout << \"mash size (tri): \" << aMesh.size() << \"  ref size (vert): \" << reference.size();\n  size_t iterationsNeeded = 0u;                            // TODO slow and fails if reference.size() <~ cgApproximateResultSize\n  while(actualIndices.size() < cgApproximateResultSize) {\n    uint32_t randomIndex = distributionAll(generator);\n    if(actualIndices.find(randomIndex) == actualIndices.end()) {\n      actualIndices.insert(randomIndex);\n    }\n    else { // nothing to do\n    }\n    ++iterationsNeeded;\n  }\n  std::cout << \" iter needed: \" << iterationsNeeded << '\\n';\n  std::unordered_set<uint32_t> bestIndices = actualIndices;\n  float actualDistancesSum = calculateDistanceSum(actualIndices, reference);\n  float bestDistancesSum = actualDistancesSum;\n  float initialTemperature = cgApproximateTemperatureFactor / aMedianSideSizeHarmonic / aMedianSideSizeHarmonic * reference.size() * reference.size();\n  for(int32_t i = 0u; i < cgApproximateIterations; ++i) {\n    auto candidateIndices = actualIndices;\n    uint32_t toRemoveIndex = distributionSubset(generator);\n    auto thisOne = candidateIndices.begin();\n    for(uint32_t j = 0u; j < toRemoveIndex; ++j) {\n      ++thisOne;\n    }\n    candidateIndices.erase(thisOne);\n    while(true) {\n      uint32_t toInsert = distributionAll(generator);\n      if(candidateIndices.find(toInsert) == candidateIndices.end()) {\n        candidateIndices.insert(toInsert);\n        break;\n      }\n      else { // nothing to do\n      }\n    }\n    float candidateDistancesSum = calculateDistanceSum(candidateIndices, reference);\n    if(candidateDistancesSum > bestDistancesSum) {\n      bestDistancesSum = candidateDistancesSum;\n      bestIndices = candidateIndices;\n    }\n    else { // nothing to do\n    }\n    float diff = actualDistancesSum - candidateDistancesSum;\n    float temperature = initialTemperature / (i + 1);\n    if(diff < 0.0f || distributionFloat(generator) < ::expf(-diff / temperature)) {\n      actualIndices = candidateIndices;\n      actualDistancesSum = candidateDistancesSum;\n    }\n    else { // nothing to do\n    }\n  }\n  std::vector<Vertex> result;\n  result.reserve(cgApproximateResultSize);\n  for(auto const &i : bestIndices) {\n    result.push_back(reference[i]);\n  }\n  return result;\n}\n\nstd::vector<float> calculateSpheres(std::vector<Vertex> const &aPoints) {\n  Vertex aabb1{std::numeric_limits<float>::max(), std::numeric_limits<float>::max(), std::numeric_limits<float>::max()};\n  Vertex aabb2{-std::numeric_limits<float>::max(), -std::numeric_limits<float>::max(), -std::numeric_limits<float>::max()};\n  for(auto const &point : aPoints) {\n    for(size_t i = 0u; i < 3u; ++i) {\n      aabb1[i] = std::min(point[i], aabb1[i]);\n      aabb2[i] = std::max(point[i], aabb2[i]);\n    }\n  }\n  float max = (aabb2 - aabb1).norm();\n  \n  std::vector<float> result;\n  result.reserve(aPoints.size());\n  std::vector<float> distances(aPoints.size() - 1u);\n  for(auto const &point: aPoints) {\n    distances.clear();\n    for(auto const &other: aPoints) {\n      if(other != point) {\n        distances.push_back(-(point - other).norm());\n      }\n      else { // nothing to do\n      }\n    }\n    std::make_heap(distances.begin(), distances.end());\n    float nth;\n    for(int32_t i = 0; i < cgCalculateSpheresNeighbours; ++i) {\n      std::pop_heap(distances.begin(), distances.end());\n      nth = -distances.back();\n      distances.pop_back();\n    }\n    result.push_back(nth * cgCalculateSpheresInflate);\n  }\n  return result;\n}\n\nauto harmonic(Triangle const &aTriangle) {\n  float a = (aTriangle[0] - aTriangle[1]).norm();\n  float b = (aTriangle[1] - aTriangle[2]).norm();\n  float c = (aTriangle[2] - aTriangle[0]).norm();\n  return std::pair{ 3.0f / (1.0f / a + 1.0f / b + 1.0f / c), std::max({a, b, c})};\n}\n\nauto calculateMedianSideSizeHarmonicAndMaxSide(Mesh const &aMesh1, Mesh const &aMesh2) {\n  std::deque<float> harmonics;\n  float maxSide1 = 0.0f;\n  for(auto const &item1 : aMesh1) {\n    auto [harm, max] = harmonic(item1);\n    harmonics.push_back(harm);\n    maxSide1 = std::max(maxSide1, max);\n  }\n  float maxSide2 = 0.0f;\n  for(auto const &item2 : aMesh2) {\n    auto [harm, max] = harmonic(item2);\n    harmonics.push_back(harm);\n    maxSide2 = std::max(maxSide2, max);\n  }\n  std::sort(harmonics.begin(), harmonics.end());\n  float median = harmonics[harmonics.size() / 2u];\n  std::cout << \"1: \" << aMesh1.size() << \" 2: \" << aMesh2.size() << \" med: \" << median << \" max: \" << maxSide1 << ' ' << maxSide2 << '\\n';\n  return std::pair(median, std::min(maxSide1, maxSide2)); // In general case, if the meshes are farther apart than the less of the maximum sides, they definitely don't intersect.\n}\n\nMesh toTetras(std::vector<Vertex> const& aPoints, float const aMedianSizeHarmonic) {\n  Mesh result;\n  float size = aMedianSizeHarmonic / 5.0f;\n  float cogShift = size / 4.0f;\n  for(auto const &point : aPoints) {\n    Vertex corner0(-cogShift, -cogShift, -cogShift);\n    Vertex corner1(size - cogShift, -cogShift, -cogShift);\n    Vertex corner2(-cogShift, size - cogShift, -cogShift);\n    Vertex corner3(-cogShift, -cogShift, size - cogShift);\n    result.push_back({point + corner0, point + corner1, point + corner2});\n    result.push_back({point + corner0, point + corner1, point + corner3});\n    result.push_back({point + corner0, point + corner2, point + corner3});\n    result.push_back({point + corner1, point + corner2, point + corner3});\n  }\n  return result;\n}\n\nMesh getUnitSphere() {\n  Mesh result;\n  result.reserve(cgSphereBelts * 2 * cgSphereSectors);\n  float sectorAngleHalf = cgPi / cgSphereSectors;\n  float sectorAngleFull = sectorAngleHalf * 2.0f;\n  float beltAngle       = cgPi / (cgSphereBelts + 1.0f);\n  float bias = 0.0f;\n  float beltAngleUp = 0.0f;\n  float beltAngleMiddle = beltAngle;\n  float beltAngleDown = 2.0f * beltAngle;\n  float beltRadiusUp = 0.0f;\n  float beltRadiusMiddle = std::sin(beltAngleMiddle);\n  float beltRadiusDown = std::sin(beltAngleDown);\n  float beltZup = 1.0f;\n  float beltZmiddle = std::cos(beltAngleMiddle);\n  float beltZdown = std::cos(beltAngleDown);\n  for(int32_t belt = 0; belt < cgSphereBelts; ++belt) {\n    float sectorAngleUpDown = bias + sectorAngleHalf;\n    float sectorAngleMiddle1 = bias + 0.0f;\n    float sectorAngleMiddle2 = bias + sectorAngleFull;\n    for(int32_t sector = 0; sector < cgSphereSectors; ++sector) {\n      Vertex corner1(beltRadiusUp * std::sin(sectorAngleUpDown), beltRadiusUp * std::cos(sectorAngleUpDown), beltZup);\n      Vertex corner2(beltRadiusMiddle * std::sin(sectorAngleMiddle1), beltRadiusMiddle * std::cos(sectorAngleMiddle1), beltZmiddle);\n      Vertex corner3(beltRadiusMiddle * std::sin(sectorAngleMiddle2), beltRadiusMiddle * std::cos(sectorAngleMiddle2), beltZmiddle);\n      result.push_back({corner1, corner2, corner3});\n      corner1 = {beltRadiusDown * std::sin(sectorAngleUpDown), beltRadiusDown * std::cos(sectorAngleUpDown), beltZdown};\n      result.push_back({corner2, corner3, corner1});\n      sectorAngleUpDown += sectorAngleFull;\n      sectorAngleMiddle1 = sectorAngleMiddle2;\n      sectorAngleMiddle2 += sectorAngleFull;\n    }\n    beltAngleUp = beltAngleMiddle;\n    beltAngleMiddle = beltAngleDown;\n    beltAngleDown += beltAngle;\n    beltRadiusUp = beltRadiusMiddle;\n    beltRadiusMiddle = beltRadiusDown;\n    beltRadiusDown = std::sin(beltAngleDown);\n    beltZup = beltZmiddle;\n    beltZmiddle = beltZdown;\n    beltZdown = std::cos(beltAngleDown);\n    bias += sectorAngleHalf;\n  }\n  return result;\n}\n\nMesh toSpheres(std::vector<Vertex> const& aPoints, std::vector<float> const& aRadii) {\n  static auto unitSphere = getUnitSphere();\n  Mesh result;\n  result.reserve(unitSphere.size() * aPoints.size());\n  for(size_t i = 0u; i < aPoints.size(); ++i) {\n    auto &point = aPoints[i];\n    auto &radius = aRadii[i];\n    for(auto const &face : unitSphere) {\n      result.push_back({face[0] * radius + point, face[1] * radius + point, face[2] * radius + point});\n    }\n  }\n  return result;\n}\n\nauto calculateDistance(std::vector<Vertex> const &aApproximate1, std::vector<Vertex> const &aApproximate2) {\n  float distance = std::numeric_limits<float>::max();\n  for(auto const &vertex1 : aApproximate1) {\n    for(auto const &vertex2 : aApproximate2) {\n      distance = std::min(distance, (vertex1 - vertex2).norm());\n    }\n  }\n  return distance;\n}\n\nvoid check(Mesh const &aMesh1, Mesh const &aMesh2) {\n  auto [medianSideSizeHarmonic, maxSide] = calculateMedianSideSizeHarmonicAndMaxSide(aMesh1, aMesh2);\n  auto approximate1 = approximate(aMesh1, medianSideSizeHarmonic);\n  auto approximate2 = approximate(aMesh2, medianSideSizeHarmonic);\n  auto sphereSizes1 = calculateSpheres(approximate1);\n  auto sphereSizes2 = calculateSpheres(approximate2);\n  for(auto i : sphereSizes1) {\n    std::cout << i << ' ';\n  }\n  for(auto i : sphereSizes2) {\n    std::cout << i << ' ';\n  }\n  std::cout << '\\n';\n  auto distance = calculateDistance(approximate1, approximate2);\n  std::cout << \"dist: \" << distance << '\\n';\n  writeMesh(toTetras(approximate1, medianSideSizeHarmonic), toTetras(approximate2, medianSideSizeHarmonic), \"points.stl\");\n  writeMesh(toSpheres(approximate1, sphereSizes1), toSpheres(approximate2, sphereSizes2), \"spheres.stl\");\n}\n\nint main(int argc, char **argv) {\n  int ret = 0;\n  if(argc < 2) {\n    std::cerr << \"Usage: \" << argv[0] << \" <filenameIn>\\n\";\n    ret = 1;\n  }\n  else {\n    try {\n      auto transform = randomTransform();\n      auto [mesh1, mesh2] = readMesh(argv[1], transform);\n      writeMesh(mesh1, mesh2, \"out.stl\");\n      check(mesh1, mesh2);\n    }\n    catch(std::exception &e) {\n      ret = 2;\n    }\n  }\n  return ret;\n}\n", "meta": {"hexsha": "8c0b62d01e0eb59aaf4b451911acd07eb5825794", "size": 16353, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "reference/preprocessor.cpp", "max_stars_repo_name": "balazs-bamer/cuda-mesh-proximity-intersection", "max_stars_repo_head_hexsha": "7f3158c5732bb0d6631357e4475b9d26280b1407", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "reference/preprocessor.cpp", "max_issues_repo_name": "balazs-bamer/cuda-mesh-proximity-intersection", "max_issues_repo_head_hexsha": "7f3158c5732bb0d6631357e4475b9d26280b1407", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "reference/preprocessor.cpp", "max_forks_repo_name": "balazs-bamer/cuda-mesh-proximity-intersection", "max_forks_repo_head_hexsha": "7f3158c5732bb0d6631357e4475b9d26280b1407", "max_forks_repo_licenses": ["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.2158273381, "max_line_length": 178, "alphanum_fraction": 0.6617745979, "num_tokens": 4671, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971212, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4910326900429601}}
{"text": "#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE Regression\n\n#include <mpi.h>\n\n#include <boost/test/unit_test.hpp>\n\n#include <xolotl/core/Constants.h>\n#include <xolotl/core/temperature/HeatEquationHandler.h>\n#include <xolotl/options/Options.h>\n#include <xolotl/test/config.h>\n\nusing namespace std;\nusing namespace xolotl;\nusing namespace core;\nusing namespace temperature;\n\n/**\n * This suite is responsible for testing the HeatEquationHandler.\n */\nBOOST_AUTO_TEST_SUITE(HeatEquationHandler_testSuite)\n\n/**\n * Method checking the initialization of the off-diagonal and diagonal part of\n * the Jacobian, and the compute temperature methods.\n */\nBOOST_AUTO_TEST_CASE(checkHeat1D)\n{\n\tMPI_Init(NULL, NULL);\n\t// Set the DOF\n\tconst int dof = 9;\n\n\t// Create the heat handler\n\tauto heatHandler = HeatEquationHandler(5.0e-12, 1000.0, 1);\n\theatHandler.setHeatCoefficient(tungstenHeatCoefficient);\n\theatHandler.setHeatConductivity(tungstenHeatConductivity);\n\n\t// Check the initial temperatures\n\tBOOST_REQUIRE_CLOSE(\n\t\theatHandler.getTemperature({0.0, 0.0, 0.0}, 0.0), 1000.0, 0.01);\n\tBOOST_REQUIRE_CLOSE(\n\t\theatHandler.getTemperature({1.0, 0.0, 0.0}, 0.0), 1000.0, 0.01);\n\n\t// Create ofill\n\tnetwork::IReactionNetwork::SparseFillMap ofill;\n\t// Create dfill\n\tnetwork::IReactionNetwork::SparseFillMap dfill;\n\n\t// Initialize it\n\theatHandler.initializeTemperature(dof, ofill, dfill);\n\n\t// Check that the temperature \"diffusion\" is well set\n\tBOOST_REQUIRE_EQUAL(ofill[9][0], 9);\n\tBOOST_REQUIRE_EQUAL(dfill[9][0], 9);\n\n\t// The size parameter in the x direction\n\tdouble hx = 1.0;\n\n\t// The arrays of concentration\n\tdouble concentration[3 * (dof + 1)];\n\tdouble newConcentration[3 * (dof + 1)];\n\n\t// Initialize their values\n\tfor (int i = 0; i < 3 * (dof + 1); i++) {\n\t\tconcentration[i] = (double)i * i;\n\t\tnewConcentration[i] = 0.0;\n\t}\n\n\t// Get pointers\n\tdouble* conc = &concentration[0];\n\tdouble* updatedConc = &newConcentration[0];\n\n\t// Get the offset for the grid point in the middle\n\t// Supposing the 3 grid points are laid-out as follow:\n\t// 0 | 1 | 2\n\tdouble* concOffset = conc + (dof + 1);\n\tdouble* updatedConcOffset = updatedConc + (dof + 1);\n\n\t// Fill the concVector with the pointer to the middle, left, and right grid\n\t// points\n\tdouble* concVector[3]{};\n\tconcVector[0] = concOffset; // middle\n\tconcVector[1] = conc; // left\n\tconcVector[2] = conc + 2 * (dof + 1); // right\n\n\t// Compute the heat equation at this grid point\n\theatHandler.computeTemperature(concVector, updatedConcOffset, hx, hx, hx);\n\n\t// Check the new values of updatedConcOffset\n\tBOOST_REQUIRE_CLOSE(updatedConcOffset[9], 1.367e+16, 0.01);\n\n\t// Set the temperature in the handler\n\theatHandler.setTemperature(concOffset);\n\t// Check the updated temperature\n\tplsm::SpaceVector<double, 3> pos{1.0, 0.0, 0.0};\n\tBOOST_REQUIRE_CLOSE(heatHandler.getTemperature(pos, 1.0), 361.0, 0.01);\n\n\t// Initialize the indices and values to set in the Jacobian\n\tIdType indices[1];\n\tdouble val[3];\n\t// Get the pointer on them for the compute diffusion method\n\tIdType* indicesPointer = &indices[0];\n\tdouble* valPointer = &val[0];\n\n\t// Compute the partial derivatives for the heat equation a the grid point\n\theatHandler.computePartialsForTemperature(\n\t\tvalPointer, indicesPointer, hx, hx, hx);\n\n\t// Check the values for the indices\n\tBOOST_REQUIRE_EQUAL(indices[0], 9);\n\n\t// Check the values\n\tBOOST_REQUIRE_CLOSE(val[0], -1.367e+14, 0.01);\n\tBOOST_REQUIRE_CLOSE(val[1], 6.835e+13, 0.01);\n\tBOOST_REQUIRE_CLOSE(val[2], 6.835e+13, 0.01);\n}\n\nBOOST_AUTO_TEST_CASE(checkHeat2D)\n{\n\t// Set the DOF\n\tconst int dof = 9;\n\n\t// Create the heat handler\n\tauto heatHandler = HeatEquationHandler(5.0e-12, 1000.0, 2);\n\theatHandler.setHeatCoefficient(tungstenHeatCoefficient);\n\theatHandler.setHeatConductivity(tungstenHeatConductivity);\n\n\t// Check the initial temperatures\n\tBOOST_REQUIRE_CLOSE(\n\t\theatHandler.getTemperature({0.0, 0.0, 0.0}, 0.0), 1000.0, 0.01);\n\tBOOST_REQUIRE_CLOSE(\n\t\theatHandler.getTemperature({1.0, 0.0, 0.0}, 0.0), 1000.0, 0.01);\n\n\t// Create ofill\n\tnetwork::IReactionNetwork::SparseFillMap ofill;\n\t// Create dfill\n\tnetwork::IReactionNetwork::SparseFillMap dfill;\n\n\t// Initialize it\n\theatHandler.initializeTemperature(dof, ofill, dfill);\n\n\t// Check that the temperature \"diffusion\" is well set\n\tBOOST_REQUIRE_EQUAL(ofill[9][0], 9);\n\tBOOST_REQUIRE_EQUAL(dfill[9][0], 9);\n\n\t// The step size in the x direction\n\tdouble hx = 1.0;\n\t// The size parameter in the y direction\n\tdouble sy = 1.0;\n\n\t// The arrays of concentration\n\tdouble concentration[9 * (dof + 1)];\n\tdouble newConcentration[9 * (dof + 1)];\n\n\t// Initialize their values\n\tfor (int i = 0; i < 9 * (dof + 1); i++) {\n\t\tconcentration[i] = (double)i * i;\n\t\tnewConcentration[i] = 0.0;\n\t}\n\n\t// Get pointers\n\tdouble* conc = &concentration[0];\n\tdouble* updatedConc = &newConcentration[0];\n\n\t// Get the offset for the grid point in the middle\n\t// Supposing the 9 grid points are laid-out as follow:\n\t// 6 | 7 | 8\n\t// 3 | 4 | 5\n\t// 0 | 1 | 2\n\tdouble* concOffset = conc + 4 * (dof + 1);\n\tdouble* updatedConcOffset = updatedConc + 4 * (dof + 1);\n\n\t// Fill the concVector with the pointer to the middle, left, right, bottom,\n\t// and top grid points\n\tdouble* concVector[5]{};\n\tconcVector[0] = concOffset; // middle\n\tconcVector[1] = conc + 3 * (dof + 1); // left\n\tconcVector[2] = conc + 5 * (dof + 1); // right\n\tconcVector[3] = conc + 1 * (dof + 1); // bottom\n\tconcVector[4] = conc + 7 * (dof + 1); // top\n\n\t// Compute the heat equation at this grid point\n\theatHandler.computeTemperature(\n\t\tconcVector, updatedConcOffset, hx, hx, hx, sy, 1);\n\n\t// Check the new values of updatedConcOffset\n\tBOOST_REQUIRE_CLOSE(updatedConcOffset[9], 1.367e+17, 0.01);\n\n\t// Set the temperature in the handler\n\theatHandler.setTemperature(concOffset);\n\t// Check the updated temperature\n\tplsm::SpaceVector<double, 3> pos{1.0, 0.0, 0.0};\n\tBOOST_REQUIRE_CLOSE(heatHandler.getTemperature(pos, 1.0), 2401, 0.01);\n\n\t// Initialize the indices and values to set in the Jacobian\n\tIdType indices[1];\n\tdouble val[5];\n\t// Get the pointer on them for the compute diffusion method\n\tIdType* indicesPointer = &indices[0];\n\tdouble* valPointer = &val[0];\n\n\t// Compute the partial derivatives for the heat equation a the grid point\n\theatHandler.computePartialsForTemperature(\n\t\tvalPointer, indicesPointer, hx, hx, hx, sy, 1);\n\n\t// Check the values for the indices\n\tBOOST_REQUIRE_EQUAL(indices[0], 9);\n\n\t// Check the values\n\tBOOST_REQUIRE_CLOSE(val[0], -2.734e+14, 0.01);\n\tBOOST_REQUIRE_CLOSE(val[1], 6.835e+13, 0.01);\n\tBOOST_REQUIRE_CLOSE(val[2], 6.835e+13, 0.01);\n\tBOOST_REQUIRE_CLOSE(val[3], 6.835e+13, 0.01);\n\tBOOST_REQUIRE_CLOSE(val[4], 6.835e+13, 0.01);\n}\n\nBOOST_AUTO_TEST_CASE(checkHeat3D)\n{\n\t// Set the DOF\n\tconst int dof = 9;\n\n\t// Create the heat handler\n\tauto heatHandler = HeatEquationHandler(5.0e-12, 1000.0, 3);\n\theatHandler.setHeatCoefficient(tungstenHeatCoefficient);\n\theatHandler.setHeatConductivity(tungstenHeatConductivity);\n\n\t// Check the initial temperatures\n\tBOOST_REQUIRE_CLOSE(\n\t\theatHandler.getTemperature({0.0, 0.0, 0.0}, 0.0), 1000.0, 0.01);\n\tBOOST_REQUIRE_CLOSE(\n\t\theatHandler.getTemperature({1.0, 0.0, 0.0}, 0.0), 1000.0, 0.01);\n\n\t// Create ofill\n\tnetwork::IReactionNetwork::SparseFillMap ofill;\n\t// Create dfill\n\tnetwork::IReactionNetwork::SparseFillMap dfill;\n\n\t// Initialize it\n\theatHandler.initializeTemperature(dof, ofill, dfill);\n\n\t// Check that the temperature \"diffusion\" is well set\n\tBOOST_REQUIRE_EQUAL(ofill[9][0], 9);\n\tBOOST_REQUIRE_EQUAL(dfill[9][0], 9);\n\n\t// The step size in the x direction\n\tdouble hx = 1.0;\n\t// The size parameter in the y direction\n\tdouble sy = 1.0;\n\t// The size parameter in the z direction\n\tdouble sz = 1.0;\n\n\t// The arrays of concentration\n\tdouble concentration[27 * (dof + 1)];\n\tdouble newConcentration[27 * (dof + 1)];\n\n\t// Initialize their values\n\tfor (int i = 0; i < 27 * (dof + 1); i++) {\n\t\tconcentration[i] = (double)i * i / 10.0;\n\t\tnewConcentration[i] = 0.0;\n\t}\n\n\t// Get pointers\n\tdouble* conc = &concentration[0];\n\tdouble* updatedConc = &newConcentration[0];\n\n\t// Get the offset for the grid point in the middle\n\t// Supposing the 27 grid points are laid-out as follow (a cube!):\n\t// 6 | 7 | 8    15 | 16 | 17    24 | 25 | 26\n\t// 3 | 4 | 5    12 | 13 | 14    21 | 22 | 23\n\t// 0 | 1 | 2    9  | 10 | 11    18 | 19 | 20\n\t//   front         middle           back\n\tdouble* concOffset = conc + 13 * (dof + 1);\n\tdouble* updatedConcOffset = updatedConc + 13 * (dof + 1);\n\n\t// Fill the concVector with the pointer to the middle, left, right, bottom,\n\t// top, front, and back grid points\n\tdouble* concVector[7]{};\n\tconcVector[0] = concOffset; // middle\n\tconcVector[1] = conc + 12 * (dof + 1); // left\n\tconcVector[2] = conc + 14 * (dof + 1); // right\n\tconcVector[3] = conc + 10 * (dof + 1); // bottom\n\tconcVector[4] = conc + 16 * (dof + 1); // top\n\tconcVector[5] = conc + 4 * (dof + 1); // front\n\tconcVector[6] = conc + 22 * (dof + 1); // back\n\n\t// Compute the heat equation at this grid point\n\theatHandler.computeTemperature(\n\t\tconcVector, updatedConcOffset, hx, hx, hx, sy, 1, sz, 1);\n\n\t// Check the new values of updatedConcOffset\n\tBOOST_REQUIRE_CLOSE(updatedConcOffset[9], 1.24397e+17, 0.01);\n\n\t// Set the temperature in the handler\n\theatHandler.setTemperature(concOffset);\n\t// Check the updated temperature\n\tplsm::SpaceVector<double, 3> pos{1.0, 0.0, 0.0};\n\tBOOST_REQUIRE_CLOSE(heatHandler.getTemperature(pos, 1.0), 1932.1, 0.01);\n\n\t// Initialize the indices and values to set in the Jacobian\n\tIdType indices[1];\n\tdouble val[7];\n\t// Get the pointer on them for the compute diffusion method\n\tIdType* indicesPointer = &indices[0];\n\tdouble* valPointer = &val[0];\n\n\t// Compute the partial derivatives for the heat equation a the grid point\n\theatHandler.computePartialsForTemperature(\n\t\tvalPointer, indicesPointer, hx, hx, hx, sy, 1, sz, 1);\n\n\t// Check the values for the indices\n\tBOOST_REQUIRE_EQUAL(indices[0], 9);\n\n\t// Check the values\n\tBOOST_REQUIRE_CLOSE(val[0], -4.101e+14, 0.01);\n\tBOOST_REQUIRE_CLOSE(val[1], 6.835e+13, 0.01);\n\tBOOST_REQUIRE_CLOSE(val[2], 6.835e+13, 0.01);\n\tBOOST_REQUIRE_CLOSE(val[3], 6.835e+13, 0.01);\n\tBOOST_REQUIRE_CLOSE(val[4], 6.835e+13, 0.01);\n\tBOOST_REQUIRE_CLOSE(val[5], 6.835e+13, 0.01);\n\tBOOST_REQUIRE_CLOSE(val[6], 6.835e+13, 0.01);\n\n\t// Finalize MPI\n\tMPI_Finalize();\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "8727c73144cd068d0d0f8d927d8cada10ce5012d", "size": 10230, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/core/temperature/HeatEquationHandlerTester.cpp", "max_stars_repo_name": "ORNL-Fusion/xolotl", "max_stars_repo_head_hexsha": "993434bea0d3bca439a733a12af78034c911690c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2018-06-13T18:08:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-30T02:39:01.000Z", "max_issues_repo_path": "test/core/temperature/HeatEquationHandlerTester.cpp", "max_issues_repo_name": "ORNL-Fusion/xolotl", "max_issues_repo_head_hexsha": "993434bea0d3bca439a733a12af78034c911690c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 97.0, "max_issues_repo_issues_event_min_datetime": "2018-02-14T15:24:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T16:29:48.000Z", "max_forks_repo_path": "test/core/temperature/HeatEquationHandlerTester.cpp", "max_forks_repo_name": "ORNL-Fusion/xolotl", "max_forks_repo_head_hexsha": "993434bea0d3bca439a733a12af78034c911690c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2018-02-13T20:36:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-04T14:54:16.000Z", "avg_line_length": 31.2844036697, "max_line_length": 78, "alphanum_fraction": 0.7035190616, "num_tokens": 3301, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527631, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.49103268442550424}}
{"text": "#include \"gradient_psv.hpp\"\n\n#include <Eigen/Dense>\n#include <cmath>\n#include <complex>\n#include <fmt/format.h>\n#include <fmt/ostream.h>\n#include <fstream>\n#include <memory>\n#include <utility>\n\nusing namespace Eigen;\nusing namespace std::complex_literals;\n\nusing std::exp;\nusing std::pow;\nusing std::sqrt;\n\nusing complex_d = std::complex<double>;\nusing Mat42cd = Matrix<complex_d, 4, 2>;\nusing Ary24cd = Array<complex_d, 2, 4>;\n\nconst double PI = 3.14159265358979323846;\n\nnamespace grad_psv {\n\nGRTCoeff::GRTCoeff(const Ref<const ArrayXXd> model, const double freq,\n                   const double c)\n    : z_(model.col(1)), rho_(model.col(2)), beta_(model.col(3)),\n      alpha_(model.col(4)), mu_(rho_ * beta_.pow(2)), nl_(model.rows()),\n      angfreq_(2.0 * PI * freq), c_(c), gamma_(nl_), nv_(nl_),\n      e11_(nl_, Matrix2cd::Zero()), e12_(nl_, Matrix2cd::Zero()),\n      e21_(nl_, Matrix2cd::Zero()), e22_(nl_, Matrix2cd::Zero()),\n      t_d_(nl_, Matrix2cd::Zero()), r_ud_(nl_, Matrix2cd::Zero()),\n      r_du_(nl_, Matrix2cd::Zero()), t_u_(nl_, Matrix2cd::Zero()),\n      gt_d_(nl_, Matrix2cd::Zero()), gr_ud_(nl_, Matrix2cd::Zero()),\n      gr_du_(nl_ + 1, Matrix2cd::Zero()), gt_u_(nl_, Matrix2cd::Zero()),\n      Cd_(nl_, Vector2cd::Zero()), Cu_(nl_, Vector2cd::Zero()) {\n\n  initialize_gamma();\n  initialize_nv();\n  initialize_E();\n\n  compute_rtc();\n  compute_grtc();\n  compute_CdCu();\n}\n\nvoid GRTCoeff::initialize_E() {\n  complex_d k = angfreq_ / c_;\n  for (auto i = 0; i < nl_; ++i) {\n    complex_d gamma = gamma_(i);\n    complex_d nv = nv_(i);\n    complex_d xi = pow(k, 2) + pow(nv, 2);\n\n    // E\n    e11_[i] << alpha_(i) * k, beta_(i) * nv, alpha_(i) * gamma, beta_(i) * k;\n    e11_[i] /= angfreq_;\n\n    auto &tmp11 = e11_[i];\n    e12_[i] << tmp11(0, 0), tmp11(0, 1), -tmp11(1, 0), -tmp11(1, 1);\n\n    e21_[i] << -2.0 * alpha_(i) * mu_(i) * k * gamma, -beta_(i) * mu_(i) * xi,\n        -alpha_(i) * mu_(i) * xi, -2.0 * beta_(i) * mu_(i) * k * nv;\n    e21_[i] /= angfreq_;\n\n    auto &tmp21 = e21_[i];\n    e22_[i] << -tmp21(0, 0), -tmp21(0, 1), tmp21(1, 0), tmp21(1, 1);\n  }\n}\n\nvoid GRTCoeff::initialize_gamma() {\n  for (int i = 0; i < nl_; ++i) {\n    complex_d val =\n        std::sqrt(pow(angfreq_ / c_, 2) - pow(angfreq_ / alpha_(i), 2));\n    if (val.real() < 0) {\n      val = -val;\n    }\n    gamma_(i) = val;\n  }\n}\n\nvoid GRTCoeff::initialize_nv() {\n  for (int i = 0; i < nl_; ++i) {\n    complex_d val =\n        std::sqrt(pow(angfreq_ / c_, 2) - pow(angfreq_ / beta_(i), 2));\n    if (val.real() < 0) {\n      val = -val;\n    }\n    nv_(i) = val;\n  }\n}\n\nMatrix2cd GRTCoeff::get_Ad(const double z, const int ind_layer) const {\n  Matrix2cd Ad;\n  Ad << exp(-gamma_(ind_layer) * (z - z_(ind_layer))), 0., 0.,\n      exp(-nv_(ind_layer) * (z - z_(ind_layer)));\n  return Ad;\n}\n\nMatrix2cd GRTCoeff::get_Au(const double z, const int ind_layer) const {\n  Matrix2cd Au;\n  if (ind_layer == nl_ - 1) {\n    Au << 0., 0., 0., 0.;\n  } else {\n    Au << exp(-gamma_(ind_layer) * (z_(ind_layer + 1) - z)), 0., 0.,\n        exp(-nv_(ind_layer) * (z_(ind_layer + 1) - z));\n  }\n  return Au;\n}\n\nMatrix2cd GRTCoeff::get_Ad_der(const double z, const int ind_layer) const {\n  Matrix2cd Ad_der;\n  Ad_der << -gamma_(ind_layer) * exp(-gamma_(ind_layer) * (z - z_(ind_layer))),\n      0., 0., -nv_(ind_layer) * exp(-nv_(ind_layer) * (z - z_(ind_layer)));\n  return Ad_der;\n}\n\nMatrix2cd GRTCoeff::get_Au_der(const double z, const int ind_layer) const {\n  if (ind_layer == nl_ - 1) {\n    return Matrix2cd::Zero();\n  }\n  Matrix2cd Au_der;\n  Au_der << gamma_(ind_layer) *\n                exp(-gamma_(ind_layer) * (z_(ind_layer + 1) - z)),\n      0., 0., nv_(ind_layer) * exp(-nv_(ind_layer) * (z_(ind_layer + 1) - z));\n  return Au_der;\n}\n\nvoid GRTCoeff::compute_rtc() {\n  for (auto i = 1; i < nl_ - 1; ++i) {\n    auto &e11_0 = e11_[i - 1];\n    auto &e12_0 = e12_[i - 1];\n    auto &e21_0 = e21_[i - 1];\n    auto &e22_0 = e22_[i - 1];\n    auto &e11_1 = e11_[i];\n    auto &e12_1 = e12_[i];\n    auto &e21_1 = e21_[i];\n    auto &e22_1 = e22_[i];\n\n    Matrix2cd exp_d00 = get_Ad(z_(i), i - 1);\n    Matrix2cd exp_u10 = get_Au(z_(i), i);\n\n    Matrix4cd mat1;\n    mat1 << e11_1(0, 0), e11_1(0, 1), -e12_0(0, 0), -e12_0(0, 1), //\n        e11_1(1, 0), e11_1(1, 1), -e12_0(1, 0), -e12_0(1, 1),     //\n        e21_1(0, 0), e21_1(0, 1), -e22_0(0, 0), -e22_0(0, 1),     //\n        e21_1(1, 0), e21_1(1, 1), -e22_0(1, 0), -e22_0(1, 1);\n\n    Matrix4cd mat2;\n    mat2 << e11_0(0, 0), e11_0(0, 1), -e12_1(0, 0), -e12_1(0, 1), //\n        e11_0(1, 0), e11_0(1, 1), -e12_1(1, 0), -e12_1(1, 1),     //\n        e21_0(0, 0), e21_0(0, 1), -e22_1(0, 0), -e22_1(0, 1),     //\n        e21_0(1, 0), e21_0(1, 1), -e22_1(1, 0), -e22_1(1, 1);\n\n    Matrix4cd mat3;\n    mat3 << exp_d00(0, 0), exp_d00(0, 1), 0, 0, //\n        exp_d00(1, 0), exp_d00(1, 1), 0, 0,     //\n        0, 0, exp_u10(0, 0), exp_u10(0, 1),     //\n        0, 0, exp_u10(1, 0), exp_u10(1, 1);\n\n    Matrix4cd result = mat1.inverse() * (mat2 * mat3);\n\n    t_d_[i] << result(0, 0), result(0, 1), result(1, 0), result(1, 1);\n\n    r_ud_[i] << result(0, 2), result(0, 3), result(1, 2), result(1, 3);\n\n    r_du_[i] << result(2, 0), result(2, 1), result(3, 0), result(3, 1);\n\n    t_u_[i] << result(2, 2), result(2, 3), result(3, 2), result(3, 3);\n  }\n\n  // the last interface\n  auto &e11_N = e11_[nl_ - 1];\n  auto &e21_N = e21_[nl_ - 1];\n  auto &e11_N_1 = e11_[nl_ - 2];\n  auto &e12_N_1 = e12_[nl_ - 2];\n  auto &e21_N_1 = e21_[nl_ - 2];\n  auto &e22_N_1 = e22_[nl_ - 2];\n\n  Matrix4cd mat1;\n  mat1 << e11_N(0, 0), e11_N(0, 1), -e12_N_1(0, 0), -e12_N_1(0, 1), //\n      e11_N(1, 0), e11_N(1, 1), -e12_N_1(1, 0), -e12_N_1(1, 1),     //\n      e21_N(0, 0), e21_N(0, 1), -e22_N_1(0, 0), -e22_N_1(0, 1),     //\n      e21_N(1, 0), e21_N(1, 1), -e22_N_1(1, 0), -e22_N_1(1, 1);\n\n  Matrix2cd exp_dN_1N_1 = get_Ad(z_(nl_ - 1), nl_ - 2);\n  Matrix2cd mat2_1 = e11_N_1 * exp_dN_1N_1;\n  Matrix2cd mat2_2 = e21_N_1 * exp_dN_1N_1;\n\n  Mat42cd mat2;\n  mat2 << mat2_1(0, 0), mat2_1(0, 1), mat2_1(1, 0), mat2_1(1, 1), //\n      mat2_2(0, 0), mat2_2(0, 1), mat2_2(1, 0), mat2_2(1, 1);\n\n  Mat42cd result = mat1.inverse() * mat2;\n  t_d_[nl_ - 1] << result(0, 0), result(0, 1), result(1, 0), result(1, 1);\n  r_du_[nl_ - 1] << result(2, 0), result(2, 1), result(3, 0), result(3, 1);\n}\n\nvoid GRTCoeff::compute_grtc() {\n  for (auto i = nl_ - 1; i >= 1; --i) {\n    Matrix2cd mat1 = matI_ - r_ud_[i] * gr_du_[i + 1];\n    gt_d_[i] = mat1.inverse() * t_d_[i];\n    gr_du_[i] = r_du_[i] + t_u_[i] * gr_du_[i + 1] * gt_d_[i];\n  }\n  gr_ud_[0] = -e21_[0].inverse() * e22_[0] * get_Au(z_(0), 0);\n  for (auto i = 1; i < nl_; ++i) {\n    Matrix2cd mat1 = matI_ - r_du_[i] * gr_ud_[i - 1];\n    gt_u_[i] = mat1.inverse() * t_u_[i];\n    gr_ud_[i] = r_ud_[i] + t_d_[i] * gr_ud_[i - 1] * gt_u_[i];\n  }\n}\n\nvoid GRTCoeff::compute_CdCu() {\n  Matrix2cd mat1 = matI_ - gr_ud_[0] * gr_du_[1];\n\n  complex_d norm = sqrt(pow(mat1(0, 0), 2) + pow(mat1(0, 1), 2));\n  Cd_[0] << mat1(0, 1) / norm, -mat1(0, 0) / norm;\n  Cu_[0] = gr_du_[1] * Cd_[0];\n\n  for (auto i = 1; i < nl_ - 1; ++i) {\n    Cd_[i] = gt_d_[i] * Cd_[i - 1];\n    Cu_[i] = gr_du_[i + 1] * Cd_[i];\n  }\n  Cd_[nl_ - 1] = gt_d_[nl_ - 1] * Cd_[nl_ - 2];\n}\n\nIntegralLayer::IntegralLayer(const Ref<const ArrayXXd> model, const double freq,\n                             const double c)\n    : grtc_(std::make_unique<GRTCoeff>(model, freq, c)), nl_(model.rows()),\n      k_(2.0 * PI * freq / c), pvel_(c), z_(model.col(1)), alpha_(model.col(4)),\n      beta_(model.col(3)), rho_(model.col(2)), mu_(rho_ * beta_ * beta_),\n      lamb_(rho_ * alpha_ * alpha_ - 2.0 * mu_), gamma_(grtc_->gamma_),\n      nv_(grtc_->nv_), thickness_(nl_ - 1), Cd_(grtc_->Cd_), Cu_(grtc_->Cu_),\n      matE_(nl_, MatrixXcd::Zero(2, 4)), matP_u_u_(nl_, Matrix4cd::Zero()),\n      matP_uc_u_(nl_, Matrix4cd::Zero()), matP_uc_uc_(nl_, Matrix4cd::Zero()),\n      matP_du_du_(nl_, Matrix4cd::Zero()), matP_duc_du_(nl_, Matrix4cd::Zero()),\n      matP_duc_duc_(nl_, Matrix4cd::Zero()), matP_u_du_(nl_, Matrix4cd::Zero()),\n      matP_uc_du_(nl_, Matrix4cd::Zero()), matP_u_duc_(nl_, Matrix4cd::Zero()),\n      matP_uc_duc_(nl_, Matrix4cd::Zero()),\n      sigma_x_sigma_top_(nl_, Matrix4cd::Zero()),\n      sigmac_x_sigma_top_(nl_, Matrix4cd::Zero()),\n      sigma_x_sigmac_top_(nl_, Matrix4cd::Zero()),\n      sigmac_x_sigmac_top_(nl_, Matrix4cd::Zero()),\n      sigma_x_sigma_bottom_(nl_, Matrix4cd::Zero()),\n      sigmac_x_sigma_bottom_(nl_, Matrix4cd::Zero()),\n      sigma_x_sigmac_bottom_(nl_, Matrix4cd::Zero()),\n      sigmac_x_sigmac_bottom_(nl_, Matrix4cd::Zero()),\n      int_us2_(ArrayXd::Zero(nl_)), int_ur2_(ArrayXd::Zero(nl_)),\n      int_dus2_(ArrayXd::Zero(nl_)), int_dur2_(ArrayXd::Zero(nl_)),\n      int_urdus_(ArrayXd::Zero(nl_)), int_usdur_(ArrayXd::Zero(nl_)) {\n  for (int i = 0; i < nl_ - 1; ++i) {\n    thickness_(i) = z_(i + 1) - z_(i);\n  }\n  for (int i = 0; i < nl_; ++i) {\n    matE_[i] << grtc_->e11_[i], grtc_->e12_[i];\n  }\n\n  initialize_P();\n  initialize_sigma();\n\n  integrate_us2();\n  integrate_dus2();\n  integrate_ur2();\n  integrate_dur2();\n  integrate_usdur();\n  integrate_urdus();\n}\n\nvoid IntegralLayer::initialize_P() {\n  for (int i = 0; i < nl_; ++i) {\n    const complex_d ga0 = gamma_(i);\n    const complex_d nv0 = nv_(i);\n    const complex_d ga0_2 = ga0 * ga0;\n    const complex_d nv0_2 = nv0 * nv0;\n    const complex_d ga1 = conj(ga0);\n    const complex_d nv1 = conj(nv0);\n    const complex_d ga1_2 = ga1 * ga1;\n    const complex_d nv1_2 = nv1 * nv1;\n    matP_u_u_[i] << 1. / (-ga0 - ga0), 1. / (-ga0 - nv0), 1., 1. / (-ga0 + nv0),\n        1. / (-nv0 - ga0), 1. / (-nv0 - nv0), 1. / (-nv0 + ga0), 1., 1.,\n        1. / (ga0 - nv0), 1. / (ga0 + ga0), 1. / (ga0 + nv0), 1. / (nv0 - ga0),\n        1., 1. / (nv0 + ga0), 1. / (nv0 + nv0);\n    matP_uc_u_[i] << 1. / (-ga1 - ga0), 1. / (-ga1 - nv0), 1. / (-ga1 + ga0),\n        1. / (-ga1 + nv0), 1. / (-nv1 - ga0), 1. / (-nv1 - nv0),\n        1. / (-nv1 + ga0), 1. / (-nv1 + nv0), 1. / (ga1 - ga0),\n        1. / (ga1 - nv0), 1. / (ga1 + ga0), 1. / (ga1 + nv0), 1. / (nv1 - ga0),\n        1. / (nv1 - nv0), 1. / (nv1 + ga0), 1. / (nv1 + nv0);\n    matP_uc_uc_[i] << 1. / (-ga1 - ga1), 1. / (-ga1 - nv1), 1.,\n        1. / (-ga1 + nv1), 1. / (-nv1 - ga1), 1. / (-nv1 - nv1),\n        1. / (-nv1 + ga1), 1., 1., 1. / (ga1 - nv1), 1. / (ga1 + ga1),\n        1. / (ga1 + nv1), 1. / (nv1 - ga1), 1., 1. / (nv1 + ga1),\n        1. / (nv1 + nv1);\n    matP_du_du_[i] << ga0_2 / (-ga0 - ga0), ga0 * nv0 / (-ga0 - nv0), -ga0_2,\n        -ga0 * nv0 / (-ga0 + nv0), nv0 * ga0 / (-nv0 - ga0),\n        nv0_2 / (-nv0 - nv0), -nv0 * ga0 / (-nv0 + ga0), -nv0_2, -ga0_2,\n        -ga0 * nv0 / (ga0 - nv0), ga0_2 / (ga0 + ga0), ga0 * nv0 / (ga0 + nv0),\n        -ga0 * nv0 / (nv0 - ga0), -nv0_2, ga0 * nv0 / (nv0 + ga0),\n        nv0_2 / (nv0 + nv0);\n    matP_duc_du_[i] << ga1 * ga0 / (-ga1 - ga0), ga1 * nv0 / (-ga1 - nv0),\n        -ga1 * ga0 / (-ga1 + ga0), -ga1 * nv0 / (-ga1 + nv0),\n        nv1 * ga0 / (-nv1 - ga0), nv1 * nv0 / (-nv1 - nv0),\n        -nv1 * ga0 / (-nv1 + ga0), -nv1 * nv0 / (-nv1 + nv0),\n        -ga1 * ga0 / (ga1 - ga0), -ga1 * nv0 / (ga1 - nv0),\n        ga1 * ga0 / (ga1 + ga0), ga1 * nv0 / (ga1 + nv0),\n        -nv1 * ga0 / (nv1 - ga0), -nv1 * nv0 / (nv1 - nv0),\n        nv1 * ga0 / (nv1 + ga0), nv1 * nv0 / (nv1 + nv0);\n    matP_duc_duc_[i] << ga1_2 / (-ga1 - ga1), ga1 * nv1 / (-ga1 - nv1), -ga1_2,\n        -ga1 * nv1 / (-ga1 + nv1), nv1 * ga1 / (-nv1 - ga1),\n        nv1_2 / (-nv1 - nv1), -nv1 * ga1 / (-nv1 + ga1), -nv1_2, -ga1_2,\n        -ga1 * nv1 / (ga1 - nv1), ga1_2 / (ga1 + ga1), ga1 * nv1 / (ga1 + nv1),\n        -ga1 * nv1 / (nv1 - ga1), -nv1_2, ga1 * nv1 / (nv1 + ga1),\n        nv1_2 / (nv1 + nv1);\n    matP_u_du_[i] << -ga0 / (-ga0 - ga0), -nv0 / (-ga0 - nv0), ga0,\n        nv0 / (-ga0 + nv0), -ga0 / (-nv0 - ga0), -nv0 / (-nv0 - nv0),\n        ga0 / (-nv0 + ga0), nv0, -ga0, -nv0 / (ga0 - nv0), ga0 / (ga0 + ga0),\n        nv0 / (ga0 + nv0), -ga0 / (nv0 - ga0), -nv0, ga0 / (nv0 + ga0),\n        nv0 / (nv0 + nv0);\n    matP_uc_du_[i] << -ga0 / (-ga1 - ga0), -nv0 / (-ga1 - nv0),\n        ga0 / (-ga1 + ga0), nv0 / (-ga1 + nv0), -ga0 / (-nv1 - ga0),\n        -nv0 / (-nv1 - nv0), ga0 / (-nv1 + ga0), nv0 / (-nv1 + nv0),\n        -ga0 / (ga1 - ga0), -nv0 / (ga1 - nv0), ga0 / (ga1 + ga0),\n        nv0 / (ga1 + nv0), -ga0 / (nv1 - ga0), -nv0 / (nv1 - nv0),\n        ga0 / (nv1 + ga0), nv0 / (nv1 + nv0);\n    matP_u_duc_[i] << -ga1 / (-ga0 - ga1), -nv1 / (-ga0 - nv1),\n        ga1 / (-ga0 + ga1), nv1 / (-ga0 + nv1), -ga1 / (-nv0 - ga1),\n        -nv1 / (-nv0 - nv1), ga1 / (-nv0 + ga1), nv1 / (-nv0 + nv1),\n        -ga1 / (ga0 - ga1), -nv1 / (ga0 - nv1), ga1 / (ga0 + ga1),\n        nv1 / (ga0 + nv1), -ga1 / (nv0 - ga1), -nv1 / (nv0 - nv1),\n        ga1 / (nv0 + ga1), nv1 / (nv0 + nv1);\n    matP_uc_duc_[i] << -ga1 / (-ga1 - ga1), -nv1 / (-ga1 - nv1), ga1,\n        nv1 / (-ga1 + nv1), -ga1 / (-nv1 - ga1), -nv1 / (-nv1 - nv1),\n        ga1 / (-nv1 + ga1), nv1, -ga1, -nv1 / (ga1 - nv1), ga1 / (ga1 + ga1),\n        nv1 / (ga1 + nv1), -ga1 / (nv1 - ga1), -nv1, ga1 / (nv1 + ga1),\n        nv1 / (nv1 + nv1);\n    if (pvel_ > alpha_(i)) {\n      matP_uc_u_[i](0, 0) = 1.;\n      matP_uc_u_[i](2, 2) = 1.;\n      matP_duc_du_[i](0, 0) = ga1 * ga0;\n      matP_duc_du_[i](2, 2) = ga1 * ga0;\n      matP_uc_du_[i](0, 0) = -ga0;\n      matP_uc_du_[i](2, 2) = ga0;\n      matP_u_duc_[i](0, 0) = -ga1;\n      matP_u_duc_[i](2, 2) = ga1;\n    } else {\n      matP_uc_u_[i](0, 2) = 1.;\n      matP_uc_u_[i](2, 0) = 1.;\n      matP_duc_du_[i](0, 2) = -ga1 * ga0;\n      matP_duc_du_[i](2, 0) = -ga1 * ga0;\n      matP_uc_du_[i](0, 2) = ga0;\n      matP_uc_du_[i](2, 0) = -ga0;\n      matP_u_duc_[i](0, 2) = ga1;\n      matP_u_duc_[i](2, 0) = -ga1;\n    }\n    if (pvel_ > beta_(i)) {\n      matP_uc_u_[i](1, 1) = 1.;\n      matP_uc_u_[i](3, 3) = 1.;\n      matP_duc_du_[i](1, 1) = nv1 * nv0;\n      matP_duc_du_[i](3, 3) = nv1 * nv0;\n      matP_uc_du_[i](1, 1) = -nv0;\n      matP_uc_du_[i](3, 3) = nv0;\n      matP_u_duc_[i](1, 1) = -nv1;\n      matP_u_duc_[i](3, 3) = nv1;\n    } else {\n      matP_uc_u_[i](1, 3) = 1.;\n      matP_uc_u_[i](3, 1) = 1.;\n      matP_duc_du_[i](1, 3) = -nv1 * nv0;\n      matP_duc_du_[i](3, 1) = -nv1 * nv0;\n      matP_uc_du_[i](1, 3) = nv0;\n      matP_uc_du_[i](3, 1) = -nv0;\n      matP_u_duc_[i](1, 3) = nv1;\n      matP_u_duc_[i](3, 1) = -nv1;\n    }\n  }\n}\n\nvoid IntegralLayer::initialize_sigma() {\n  MatrixXcd sigma_bottom = MatrixXcd::Zero(4, nl_);\n  MatrixXcd sigma_top = MatrixXcd::Zero(4, nl_);\n  for (auto i = 0; i < nl_ - 1; ++i) {\n    sigma_bottom.col(i) << Cd_[i](0), Cd_[i](1),\n        Cu_[i](0) * exp(-gamma_(i) * thickness_(i)),\n        Cu_[i](1) * exp(-nv_(i) * thickness_(i));\n    sigma_top.col(i) << Cd_[i](0) * exp(-gamma_(i) * thickness_(i)),\n        Cd_[i](1) * exp(-nv_(i) * thickness_(i)), Cu_[i](0), Cu_[i](1);\n  }\n  sigma_bottom.col(nl_ - 1) << Cd_[nl_ - 1](0), Cd_[nl_ - 1](1), 0, 0;\n  sigma_top.col(nl_ - 1).fill(0);\n\n  for (auto id_layer = 0; id_layer < nl_; ++id_layer) {\n    auto cd = Cd_[id_layer];\n    auto cu = Cu_[id_layer];\n    for (auto i = 0; i < 4; ++i) {\n      for (auto j = 0; j < 4; ++j) {\n        sigma_x_sigma_top_[id_layer](i, j) =\n            sigma_top(i, id_layer) * sigma_top(j, id_layer);\n        sigmac_x_sigma_top_[id_layer](i, j) =\n            conj(sigma_top(i, id_layer)) * sigma_top(j, id_layer);\n        sigma_x_sigmac_top_[id_layer](i, j) =\n            sigma_top(i, id_layer) * conj(sigma_top(j, id_layer));\n        sigmac_x_sigmac_top_[id_layer](i, j) =\n            conj(sigma_top(i, id_layer)) * conj(sigma_top(j, id_layer));\n\n        sigma_x_sigma_bottom_[id_layer](i, j) =\n            sigma_bottom(i, id_layer) * sigma_bottom(j, id_layer);\n        sigmac_x_sigma_bottom_[id_layer](i, j) =\n            conj(sigma_bottom(i, id_layer)) * sigma_bottom(j, id_layer);\n        sigma_x_sigmac_bottom_[id_layer](i, j) =\n            sigma_bottom(i, id_layer) * conj(sigma_bottom(j, id_layer));\n        sigmac_x_sigmac_bottom_[id_layer](i, j) =\n            conj(sigma_bottom(i, id_layer)) * conj(sigma_bottom(j, id_layer));\n      }\n    }\n    if (id_layer != nl_ - 1) {\n      sigma_x_sigma_top_[id_layer](0, 2) *= thickness_(id_layer);\n      sigma_x_sigma_top_[id_layer](2, 0) *= thickness_(id_layer);\n      sigma_x_sigma_top_[id_layer](1, 3) *= thickness_(id_layer);\n      sigma_x_sigma_top_[id_layer](3, 1) *= thickness_(id_layer);\n      sigmac_x_sigmac_top_[id_layer](0, 2) *= thickness_(id_layer);\n      sigmac_x_sigmac_top_[id_layer](2, 0) *= thickness_(id_layer);\n      sigmac_x_sigmac_top_[id_layer](1, 3) *= thickness_(id_layer);\n      sigmac_x_sigmac_top_[id_layer](3, 1) *= thickness_(id_layer);\n      if (pvel_ > alpha_(id_layer)) {\n        sigmac_x_sigma_top_[id_layer](0, 0) =\n            conj(cd(0)) * cd(0) * thickness_(id_layer);\n        sigmac_x_sigma_top_[id_layer](2, 2) =\n            conj(cu(0)) * cu(0) * thickness_(id_layer);\n        sigma_x_sigmac_top_[id_layer](0, 0) =\n            cd(0) * conj(cd(0)) * thickness_(id_layer);\n        sigma_x_sigmac_top_[id_layer](2, 2) =\n            cu(0) * conj(cu(0)) * thickness_(id_layer);\n      } else {\n        sigmac_x_sigma_top_[id_layer](0, 2) *= thickness_(id_layer);\n        sigmac_x_sigma_top_[id_layer](2, 0) *= thickness_(id_layer);\n        sigma_x_sigmac_top_[id_layer](0, 2) *= thickness_(id_layer);\n        sigma_x_sigmac_top_[id_layer](2, 0) *= thickness_(id_layer);\n      }\n      if (pvel_ > beta_(id_layer)) {\n        sigmac_x_sigma_top_[id_layer](1, 1) =\n            conj(cd(1)) * cd(1) * thickness_(id_layer);\n        sigmac_x_sigma_top_[id_layer](3, 3) =\n            conj(cu(1)) * cu(1) * thickness_(id_layer);\n        sigma_x_sigmac_top_[id_layer](1, 1) =\n            cd(1) * conj(cd(1)) * thickness_(id_layer);\n        sigma_x_sigmac_top_[id_layer](3, 3) =\n            cu(1) * conj(cu(1)) * thickness_(id_layer);\n      } else {\n        sigmac_x_sigma_top_[id_layer](1, 3) *= thickness_(id_layer);\n        sigmac_x_sigma_top_[id_layer](3, 1) *= thickness_(id_layer);\n        sigma_x_sigmac_top_[id_layer](1, 3) *= thickness_(id_layer);\n        sigma_x_sigmac_top_[id_layer](3, 1) *= thickness_(id_layer);\n      }\n      sigma_x_sigma_bottom_[id_layer](0, 2) = 0.;\n      sigma_x_sigma_bottom_[id_layer](2, 0) = 0.;\n      sigma_x_sigma_bottom_[id_layer](1, 3) = 0.;\n      sigma_x_sigma_bottom_[id_layer](3, 1) = 0.;\n      sigmac_x_sigmac_bottom_[id_layer](0, 2) = 0.;\n      sigmac_x_sigmac_bottom_[id_layer](2, 0) = 0.;\n      sigmac_x_sigmac_bottom_[id_layer](1, 3) = 0.;\n      sigmac_x_sigmac_bottom_[id_layer](3, 1) = 0.;\n      if (pvel_ > alpha_(id_layer)) {\n        sigmac_x_sigma_bottom_[id_layer](0, 0) = 0.;\n        sigmac_x_sigma_bottom_[id_layer](2, 2) = 0.;\n        sigma_x_sigmac_bottom_[id_layer](0, 0) = 0.;\n        sigma_x_sigmac_bottom_[id_layer](2, 2) = 0.;\n      } else {\n        sigmac_x_sigma_bottom_[id_layer](0, 2) = 0.;\n        sigmac_x_sigma_bottom_[id_layer](2, 0) = 0.;\n        sigma_x_sigmac_bottom_[id_layer](0, 2) = 0.;\n        sigma_x_sigmac_bottom_[id_layer](2, 0) = 0.;\n      }\n      if (pvel_ > beta_(id_layer)) {\n        sigmac_x_sigma_bottom_[id_layer](1, 1) = 0.;\n        sigmac_x_sigma_bottom_[id_layer](3, 3) = 0.;\n        sigma_x_sigmac_bottom_[id_layer](1, 1) = 0.;\n        sigma_x_sigmac_bottom_[id_layer](3, 3) = 0.;\n      } else {\n        sigmac_x_sigma_bottom_[id_layer](1, 3) = 0.;\n        sigmac_x_sigma_bottom_[id_layer](3, 1) = 0.;\n        sigma_x_sigmac_bottom_[id_layer](1, 3) = 0.;\n        sigma_x_sigmac_bottom_[id_layer](3, 1) = 0.;\n      }\n    }\n  }\n}\n\ndouble IntegralLayer::intker_us2_top(int id_layer) {\n  complex_d result = 0;\n\n  for (auto i = 0; i < 4; ++i) {\n    for (auto j = 0; j < 4; ++j) {\n      result += matP_u_u_[id_layer](i, j) * matE_[id_layer](0, i) *\n                    matE_[id_layer](0, j) * sigma_x_sigma_top_[id_layer](i, j) +\n                2. * matP_uc_u_[id_layer](i, j) * conj(matE_[id_layer](0, i)) *\n                    matE_[id_layer](0, j) *\n                    sigmac_x_sigma_top_[id_layer](i, j) +\n                matP_uc_uc_[id_layer](i, j) * conj(matE_[id_layer](0, i)) *\n                    conj(matE_[id_layer](0, j)) *\n                    sigmac_x_sigmac_top_[id_layer](i, j);\n    }\n  }\n  return std::real(result) / 4;\n}\n\ndouble IntegralLayer::intker_us2_bottom(int id_layer) {\n  complex_d result = 0;\n\n  for (auto i = 0; i < 4; ++i) {\n    for (auto j = 0; j < 4; ++j) {\n      result +=\n          matP_u_u_[id_layer](i, j) * matE_[id_layer](0, i) *\n              matE_[id_layer](0, j) * sigma_x_sigma_bottom_[id_layer](i, j) +\n          2. * matP_uc_u_[id_layer](i, j) * conj(matE_[id_layer](0, i)) *\n              matE_[id_layer](0, j) * sigmac_x_sigma_bottom_[id_layer](i, j) +\n          matP_uc_uc_[id_layer](i, j) * conj(matE_[id_layer](0, i)) *\n              conj(matE_[id_layer](0, j)) *\n              sigmac_x_sigmac_bottom_[id_layer](i, j);\n    }\n  }\n  return std::real(result) / 4;\n}\n\ndouble IntegralLayer::intker_ur2_top(int id_layer) {\n  complex_d result = 0;\n\n  for (auto i = 0; i < 4; ++i) {\n    for (auto j = 0; j < 4; ++j) {\n      result += matP_u_u_[id_layer](i, j) * matE_[id_layer](1, i) *\n                    matE_[id_layer](1, j) * sigma_x_sigma_top_[id_layer](i, j) +\n                2. * matP_uc_u_[id_layer](i, j) * conj(matE_[id_layer](1, i)) *\n                    matE_[id_layer](1, j) *\n                    sigmac_x_sigma_top_[id_layer](i, j) +\n                matP_uc_uc_[id_layer](i, j) * conj(matE_[id_layer](1, i)) *\n                    conj(matE_[id_layer](1, j)) *\n                    sigmac_x_sigmac_top_[id_layer](i, j);\n    }\n  }\n  return std::real(result) / 4;\n}\n\ndouble IntegralLayer::intker_ur2_bottom(int id_layer) {\n  complex_d result = 0;\n\n  for (auto i = 0; i < 4; ++i) {\n    for (auto j = 0; j < 4; ++j) {\n      result +=\n          matP_u_u_[id_layer](i, j) * matE_[id_layer](1, i) *\n              matE_[id_layer](1, j) * sigma_x_sigma_bottom_[id_layer](i, j) +\n          2. * matP_uc_u_[id_layer](i, j) * conj(matE_[id_layer](1, i)) *\n              matE_[id_layer](1, j) * sigmac_x_sigma_bottom_[id_layer](i, j) +\n          matP_uc_uc_[id_layer](i, j) * conj(matE_[id_layer](1, i)) *\n              conj(matE_[id_layer](1, j)) *\n              sigmac_x_sigmac_bottom_[id_layer](i, j);\n    }\n  }\n  return std::real(result) / 4;\n}\n\ndouble IntegralLayer::intker_dus2_top(int id_layer) {\n  complex_d result = 0;\n\n  for (auto i = 0; i < 4; ++i) {\n    for (auto j = 0; j < 4; ++j) {\n      result += matP_du_du_[id_layer](i, j) * matE_[id_layer](0, i) *\n                    matE_[id_layer](0, j) * sigma_x_sigma_top_[id_layer](i, j) +\n                2. * matP_duc_du_[id_layer](i, j) *\n                    conj(matE_[id_layer](0, i)) * matE_[id_layer](0, j) *\n                    sigmac_x_sigma_top_[id_layer](i, j) +\n                matP_duc_duc_[id_layer](i, j) * conj(matE_[id_layer](0, i)) *\n                    conj(matE_[id_layer](0, j)) *\n                    sigmac_x_sigmac_top_[id_layer](i, j);\n    }\n  }\n  return std::real(result) / 4.;\n}\n\ndouble IntegralLayer::intker_dus2_bottom(int id_layer) {\n  complex_d result = 0;\n\n  for (auto i = 0; i < 4; ++i) {\n    for (auto j = 0; j < 4; ++j) {\n      result +=\n          matP_du_du_[id_layer](i, j) * matE_[id_layer](0, i) *\n              matE_[id_layer](0, j) * sigma_x_sigma_bottom_[id_layer](i, j) +\n          2. * matP_duc_du_[id_layer](i, j) * conj(matE_[id_layer](0, i)) *\n              matE_[id_layer](0, j) * sigmac_x_sigma_bottom_[id_layer](i, j) +\n          matP_duc_duc_[id_layer](i, j) * conj(matE_[id_layer](0, i)) *\n              conj(matE_[id_layer](0, j)) *\n              sigmac_x_sigmac_bottom_[id_layer](i, j);\n    }\n  }\n  return std::real(result) / 4.;\n}\n\ndouble IntegralLayer::intker_dur2_top(int id_layer) {\n  complex_d result = 0;\n\n  for (auto i = 0; i < 4; ++i) {\n    for (auto j = 0; j < 4; ++j) {\n      result += matP_du_du_[id_layer](i, j) * matE_[id_layer](1, i) *\n                    matE_[id_layer](1, j) * sigma_x_sigma_top_[id_layer](i, j) +\n                2. * matP_duc_du_[id_layer](i, j) *\n                    conj(matE_[id_layer](1, i)) * matE_[id_layer](1, j) *\n                    sigmac_x_sigma_top_[id_layer](i, j) +\n                matP_duc_duc_[id_layer](i, j) * conj(matE_[id_layer](1, i)) *\n                    conj(matE_[id_layer](1, j)) *\n                    sigmac_x_sigmac_top_[id_layer](i, j);\n    }\n  }\n  return std::real(result) / 4;\n}\n\ndouble IntegralLayer::intker_dur2_bottom(int id_layer) {\n  complex_d result = 0;\n\n  for (auto i = 0; i < 4; ++i) {\n    for (auto j = 0; j < 4; ++j) {\n      result +=\n          matP_du_du_[id_layer](i, j) * matE_[id_layer](1, i) *\n              matE_[id_layer](1, j) * sigma_x_sigma_bottom_[id_layer](i, j) +\n          2. * matP_duc_du_[id_layer](i, j) * conj(matE_[id_layer](1, i)) *\n              matE_[id_layer](1, j) * sigmac_x_sigma_bottom_[id_layer](i, j) +\n          matP_duc_duc_[id_layer](i, j) * conj(matE_[id_layer](1, i)) *\n              conj(matE_[id_layer](1, j)) *\n              sigmac_x_sigmac_bottom_[id_layer](i, j);\n    }\n  }\n  return std::real(result) / 4;\n}\n\ndouble IntegralLayer::intker_urdus_top(int id_layer) {\n  complex_d result = 0;\n\n  for (auto i = 0; i < 4; ++i) {\n    for (auto j = 0; j < 4; ++j) {\n      result += matP_u_du_[id_layer](i, j) * matE_[id_layer](1, i) *\n                    matE_[id_layer](0, j) * sigma_x_sigma_top_[id_layer](i, j) +\n                matP_u_duc_[id_layer](i, j) * matE_[id_layer](1, i) *\n                    conj(matE_[id_layer](0, j)) *\n                    sigma_x_sigmac_top_[id_layer](i, j) +\n                matP_uc_du_[id_layer](i, j) * conj(matE_[id_layer](1, i)) *\n                    matE_[id_layer](0, j) *\n                    sigmac_x_sigma_top_[id_layer](i, j) +\n                matP_uc_duc_[id_layer](i, j) * conj(matE_[id_layer](1, i)) *\n                    conj(matE_[id_layer](0, j)) *\n                    sigmac_x_sigmac_top_[id_layer](i, j);\n    }\n  }\n  return std::real(result) / 4.;\n}\n\ndouble IntegralLayer::intker_urdus_bottom(int id_layer) {\n  complex_d result = 0;\n\n  for (auto i = 0; i < 4; ++i) {\n    for (auto j = 0; j < 4; ++j) {\n      result +=\n          matP_u_du_[id_layer](i, j) * matE_[id_layer](1, i) *\n              matE_[id_layer](0, j) * sigma_x_sigma_bottom_[id_layer](i, j) +\n          matP_u_duc_[id_layer](i, j) * matE_[id_layer](1, i) *\n              conj(matE_[id_layer](0, j)) *\n              sigma_x_sigmac_bottom_[id_layer](i, j) +\n          matP_uc_du_[id_layer](i, j) * conj(matE_[id_layer](1, i)) *\n              matE_[id_layer](0, j) * sigmac_x_sigma_bottom_[id_layer](i, j) +\n          matP_uc_duc_[id_layer](i, j) * conj(matE_[id_layer](1, i)) *\n              conj(matE_[id_layer](0, j)) *\n              sigmac_x_sigmac_bottom_[id_layer](i, j);\n    }\n  }\n  return std::real(result) / 4.;\n}\n\ndouble IntegralLayer::intker_usdur_top(int id_layer) {\n  complex_d result = 0;\n\n  for (auto i = 0; i < 4; ++i) {\n    for (auto j = 0; j < 4; ++j) {\n      result += matP_u_du_[id_layer](i, j) * matE_[id_layer](0, i) *\n                    matE_[id_layer](1, j) * sigma_x_sigma_top_[id_layer](i, j) +\n                matP_u_duc_[id_layer](i, j) * matE_[id_layer](0, i) *\n                    conj(matE_[id_layer](1, j)) *\n                    sigma_x_sigmac_top_[id_layer](i, j) +\n                matP_uc_du_[id_layer](i, j) * conj(matE_[id_layer](0, i)) *\n                    matE_[id_layer](1, j) *\n                    sigmac_x_sigma_top_[id_layer](i, j) +\n                matP_uc_duc_[id_layer](i, j) * conj(matE_[id_layer](0, i)) *\n                    conj(matE_[id_layer](1, j)) *\n                    sigmac_x_sigmac_top_[id_layer](i, j);\n    }\n  }\n  return std::real(result) / 4.;\n}\n\ndouble IntegralLayer::intker_usdur_bottom(int id_layer) {\n  complex_d result = 0;\n\n  for (auto i = 0; i < 4; ++i) {\n    for (auto j = 0; j < 4; ++j) {\n      result +=\n          matP_u_du_[id_layer](i, j) * matE_[id_layer](0, i) *\n              matE_[id_layer](1, j) * sigma_x_sigma_bottom_[id_layer](i, j) +\n          matP_u_duc_[id_layer](i, j) * matE_[id_layer](0, i) *\n              conj(matE_[id_layer](1, j)) *\n              sigma_x_sigmac_bottom_[id_layer](i, j) +\n          matP_uc_du_[id_layer](i, j) * conj(matE_[id_layer](0, i)) *\n              matE_[id_layer](1, j) * sigmac_x_sigma_bottom_[id_layer](i, j) +\n          matP_uc_duc_[id_layer](i, j) * conj(matE_[id_layer](0, i)) *\n              conj(matE_[id_layer](1, j)) *\n              sigmac_x_sigmac_bottom_[id_layer](i, j);\n    }\n  }\n  return std::real(result) / 4.;\n}\n\nvoid IntegralLayer::integrate_us2() {\n  for (int id_layer = 0; id_layer < nl_; ++id_layer) {\n    int_us2_(id_layer) = intker_us2_top(id_layer) - intker_us2_bottom(id_layer);\n  }\n}\n\nvoid IntegralLayer::integrate_ur2() {\n  for (int id_layer = 0; id_layer < nl_; ++id_layer) {\n    int_ur2_(id_layer) = intker_ur2_top(id_layer) - intker_ur2_bottom(id_layer);\n  }\n}\n\nvoid IntegralLayer::integrate_dus2() {\n  for (int id_layer = 0; id_layer < nl_; ++id_layer) {\n    int_dus2_(id_layer) =\n        intker_dus2_top(id_layer) - intker_dus2_bottom(id_layer);\n  }\n}\n\nvoid IntegralLayer::integrate_dur2() {\n  for (int id_layer = 0; id_layer < nl_; ++id_layer) {\n    int_dur2_(id_layer) =\n        intker_dur2_top(id_layer) - intker_dur2_bottom(id_layer);\n  }\n}\n\nvoid IntegralLayer::integrate_usdur() {\n  for (int id_layer = 0; id_layer < nl_; ++id_layer) {\n    int_usdur_(id_layer) =\n        intker_usdur_top(id_layer) - intker_usdur_bottom(id_layer);\n  }\n}\n\nvoid IntegralLayer::integrate_urdus() {\n  for (int id_layer = 0; id_layer < nl_; ++id_layer) {\n    int_urdus_(id_layer) =\n        intker_urdus_top(id_layer) - intker_urdus_bottom(id_layer);\n  }\n}\n\ndouble IntegralLayer::compute_I1() {\n  ArrayXd ker = rho_ * (int_us2_ + int_ur2_);\n  double i1 = 0.5 * ker.sum();\n  return i1;\n}\n\ndouble IntegralLayer::compute_I2() {\n  ArrayXd ker = (lamb_ + 2.0 * mu_) * int_us2_ + mu_ * int_ur2_;\n  double i2 = 0.5 * ker.sum();\n  return i2;\n}\n\ndouble IntegralLayer::compute_I3() {\n  ArrayXd ker = lamb_ * int_usdur_ - mu_ * int_urdus_;\n  double i3 = 0.5 * ker.sum();\n  return i3;\n}\n\nArrayXd IntegralLayer::compute_kvs() {\n  double k2 = std::pow(k_, 2);\n  ArrayXd kvs(nl_);\n  for (int i = 0; i < nl_; ++i) {\n    kvs(i) = 0.5 * rho_(i) * beta_(i) *\n             (int_ur2_(i) + 1.0 / k2 * int_dus2_(i) - 2.0 / k_ * int_urdus_(i) -\n              4.0 / k_ * int_usdur_(i));\n  }\n  return kvs;\n}\n\nGradientPSV::~GradientPSV() = default;\n\nArrayXd GradientPSV::compute(const double freq, const double c) const {\n  double k = 2.0 * PI * freq / c;\n  IntegralLayer intl(model_, freq, c);\n  double I2 = intl.compute_I2();\n  double I3 = intl.compute_I3();\n  ArrayXd kvs = intl.compute_kvs();\n  kvs *= c / (I2 + I3 / k);\n  return kvs;\n}\n\n} // namespace grad_psv", "meta": {"hexsha": "8c4b3c372f7165c7620306ff0695b5861b680d58", "size": 30632, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/gradient_psv.cc", "max_stars_repo_name": "pan3rock/DisbaTomo", "max_stars_repo_head_hexsha": "b1e6ffa3afd911f1934cd6274854b5fa4161a9cc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2021-07-30T03:27:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T14:05:47.000Z", "max_issues_repo_path": "src/gradient_psv.cc", "max_issues_repo_name": "pan3rock/DisbaTomo", "max_issues_repo_head_hexsha": "b1e6ffa3afd911f1934cd6274854b5fa4161a9cc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gradient_psv.cc", "max_forks_repo_name": "pan3rock/DisbaTomo", "max_forks_repo_head_hexsha": "b1e6ffa3afd911f1934cd6274854b5fa4161a9cc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2021-07-31T12:38:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-17T15:07:53.000Z", "avg_line_length": 38.4824120603, "max_line_length": 80, "alphanum_fraction": 0.5473034735, "num_tokens": 11948, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4909833272270809}}
{"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\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n//\n// This file is part of the Matrix Template Library\n//\n// See also license.mtl.txt in the distribution.\n\n#include <iostream>\n#include <boost/numeric/mtl/mtl.hpp>\n#include <boost/timer.hpp>\n\n\ninline void bench(unsigned n)\n{\n    typedef mtl::mat::parameters<> mat_para;\n    mtl::dense2D<double, mat_para> A(n, n), B(n, n), C(n, n);\n    mtl::dense_vector<double> x(n, 1.0), b(n);\n\n    for ( unsigned i= 0; i < n; i++)\n\tfor ( unsigned  j= 0; j < n; j++){\n\t    A[i][j]= 1;\n\t    B[i][j]= 2;\n\t}\n    \n    boost::timer t;\n    C= A * B;\n    b= C * x;\n    double t1= 1000. * t.elapsed();\n\n    t.restart();\n    b=  B * x;\n    x= A * b;\n    double t2= 1000. * t.elapsed();\n    std::cout << n << \" \" << t1 << \" \" << t2 <<\"\\n\";\n}\n\n\n\nint main(int , char**)\n{\n    bench(1000);\n\n\n\n#if 0\n    bench(300);\n    bench(400);\n    bench(500);\n    bench(600);\n    bench(700);\n    bench(800);\n    bench(900);\n    bench(1000);\n    bench(1200);\n    bench(1400);\n    bench(1600);\n    bench(1800);\n    bench(2000);\n    bench(2200);\n    bench(2400);\n    bench(2600);\n#endif\n\n    return 0;\n}\n", "meta": {"hexsha": "83c560de9689ab1af17974cf06fa04e71cbe75bb", "size": 1394, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/timing/mat_mat_vec_timing.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/mtl/timing/mat_mat_vec_timing.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/mtl/timing/mat_mat_vec_timing.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 19.6338028169, "max_line_length": 94, "alphanum_fraction": 0.5659971306, "num_tokens": 448, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4909549934211428}}
{"text": "#ifndef MPLLIBS_METAPARSE_V1_INT__HPP\n#define MPLLIBS_METAPARSE_V1_INT__HPP\n\n// Copyright Abel Sinkovics (abel@sinkovics.hu)  2011.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n#include <mpllibs/metaparse/v1/digit_val.hpp>\n#include <mpllibs/metaparse/v1/foldl1.hpp>\n\n#include <boost/mpl/lambda.hpp>\n#include <boost/mpl/times.hpp>\n#include <boost/mpl/plus.hpp>\n\nnamespace mpllibs\n{\n  namespace metaparse\n  {\n    namespace v1\n    {\n      typedef\n        foldl1<\n          digit_val,\n          boost::mpl::int_<0>,\n          // I need to wrap it with lambda, because int_ may be used\n          // in an apply and turned into a lambda expression too early.\n          boost::mpl::lambda<\n            boost::mpl::plus<\n              boost::mpl::times<boost::mpl::_2, boost::mpl::int_<10> >,\n              boost::mpl::_1\n            >\n          >::type\n        >\n        int_;\n    }\n  }\n}\n\n#endif\n\n", "meta": {"hexsha": "d141a371e190f448c036f2f630bf4535a55a58a1", "size": 1015, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lab/mpllibs/metaparse/v1/int_.hpp", "max_stars_repo_name": "sabel83/metaparse_tutorial", "max_stars_repo_head_hexsha": "819fddf6bf06736861adbeabeb30967f56b7e8d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2015-07-14T01:56:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-16T07:48:46.000Z", "max_issues_repo_path": "lab/mpllibs/metaparse/v1/int_.hpp", "max_issues_repo_name": "sabel83/metaparse_tutorial", "max_issues_repo_head_hexsha": "819fddf6bf06736861adbeabeb30967f56b7e8d0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-10-01T12:31:25.000Z", "max_issues_repo_issues_event_max_datetime": "2017-10-04T12:16:47.000Z", "max_forks_repo_path": "lab/mpllibs/metaparse/v1/int_.hpp", "max_forks_repo_name": "sabel83/metaparse_tutorial", "max_forks_repo_head_hexsha": "819fddf6bf06736861adbeabeb30967f56b7e8d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-08-22T20:31:11.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-23T07:32:29.000Z", "avg_line_length": 24.1666666667, "max_line_length": 71, "alphanum_fraction": 0.6157635468, "num_tokens": 280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.49095499342114274}}
{"text": "#include <boost/graph/geodesic_distance.hpp>\n", "meta": {"hexsha": "e355bcca89673f37125ce72c72c7c86696aed1d3", "size": 45, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_graph_geodesic_distance.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_graph_geodesic_distance.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_graph_geodesic_distance.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 22.5, "max_line_length": 44, "alphanum_fraction": 0.8222222222, "num_tokens": 10, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867585368344, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4909549816097418}}
{"text": "\n#include <iostream>\n#include <functional>\n#include <thread>\n#include <vector>\n#include <fstream>\n#include <mutex>\n#include <condition_variable>\n\n#include <kfr/base.hpp>\n#include <kfr/dft.hpp>\n#include <kfr/dsp.hpp>\n\n\n#include <Eigen/Dense>\n\n#include <portaudio.h>\n\n\n\nnamespace {\nstd::mutex m;\nstd::condition_variable cv;\nbool shouldStop_ = false;\n\nstd::array<int, 4> channelMap_ordinary = {0,1,2,3};\nstd::array<int, 4> channelMap_PS_eye={0,2,1,3};\n\n}\n\n\n\ntemplate<size_t SAMPLE_RATE, size_t NB_SAMPLES_PER_CHANNEL>\nclass MicArrayRunner {\nprivate:\n    PaStream* paStream_ = nullptr;\n    PaStreamParameters  paInputParameters_;\n    std::function<void(const int16_t * inputBuffer, const size_t framesPerBuffer, const size_t nbChannel)> callback_ = nullptr;\n    int finalNbChannel_ = -1;\n\npublic:\n    MicArrayRunner(decltype(callback_) callback)\n        :callback_(callback)\n    { }\n\n    bool micArrayFilter(const PaDeviceInfo* deviceInfo) {\n        return (deviceInfo->maxInputChannels < 6 && deviceInfo->maxInputChannels > 2);\n    }\n\n    void init() {\n        auto err = Pa_Initialize();\n        if( err != paNoError ) {\n            throw;\n        }\n\n        auto numDevices = Pa_GetDeviceCount();\n        auto finalIndex = -1;\n        for(auto i=0; i<numDevices; i++ ){\n            auto deviceInfo = Pa_GetDeviceInfo( i );\n\n            if(micArrayFilter(deviceInfo)){\n                printf(\"deviceID=%02d: %s\\n \\t\\t nbChannel=%02d\\n\", i, deviceInfo->name, deviceInfo->maxInputChannels);\n                finalIndex = i;\n                finalNbChannel_ = deviceInfo->maxInputChannels;\n            }\n        }\n\n        paInputParameters_.device = finalIndex;\n        paInputParameters_.channelCount = finalNbChannel_;\n        paInputParameters_.sampleFormat = paInt16;\n        paInputParameters_.suggestedLatency = Pa_GetDeviceInfo( paInputParameters_.device )->defaultLowInputLatency;\n        paInputParameters_.hostApiSpecificStreamInfo = NULL;\n        err = Pa_OpenStream(&paStream_, &paInputParameters_, nullptr, SAMPLE_RATE, NB_SAMPLES_PER_CHANNEL, paClipOff, MicArrayRunner::theCallback, this);\n    }\n\n    void start() {\n        Pa_StartStream(paStream_);\n    }\n\n    void stop() {\n        Pa_StopStream(paStream_);\n    }\n\n    void deInit() {\n        stop();\n        Pa_Terminate();\n    }\n\n    ~MicArrayRunner() {\n        deInit();\n    }\n\n\nprivate:\n    static int theCallback(const void *inputBuffer, void *outputBuffer,\n                           unsigned long framesPerBuffer,\n                           const PaStreamCallbackTimeInfo* timeInfo,\n                           PaStreamCallbackFlags statusFlags,\n                           void *userData ) {\n        auto _runner = (MicArrayRunner*)userData;\n        _runner->callback_((const int16_t*)inputBuffer, framesPerBuffer, _runner->finalNbChannel_);\n        return 0;\n    }\n};\n\n\n\n\ntemplate<size_t SAMPLE_RATE, size_t NB_CHANNEL, size_t NB_SAMPLES_PER_CHANNEL, const size_t CORR_RESULT_SIZE = 2 * NB_SAMPLES_PER_CHANNEL - 1>\nclass MultichannelCrossCorrelationCoefficientAlgorithm {\nprivate:\n    kfr::univector<kfr::fbase, NB_CHANNEL*NB_SAMPLES_PER_CHANNEL> kfrFbase_;\n    kfr::univector<kfr::univector<kfr::fbase, NB_SAMPLES_PER_CHANNEL>, NB_CHANNEL> splitedAudio_;\n    kfr::univector<kfr::univector<kfr::univector<kfr::fbase, CORR_RESULT_SIZE>,NB_CHANNEL>, NB_CHANNEL> raP_;\n    kfr::univector<Eigen::Matrix<double, NB_CHANNEL, NB_CHANNEL>, CORR_RESULT_SIZE> eigenMatrix_;\n    kfr::univector<kfr::fbase, CORR_RESULT_SIZE> detRaP_;\n\n    std::array<int, NB_CHANNEL> channelMap_;\nprivate:\n    void calcCorr(const kfr::univector<kfr::fbase, NB_SAMPLES_PER_CHANNEL> &a,\n                  const kfr::univector<kfr::fbase, NB_SAMPLES_PER_CHANNEL> &b,\n                  kfr::univector<kfr::fbase, CORR_RESULT_SIZE> &result\n                  ){\n        result = correlate(a,b);\n    }\n\n\n    void constructMatrix(const size_t p,\n                         const kfr::univector<kfr::univector<kfr::univector<kfr::fbase, CORR_RESULT_SIZE>, NB_CHANNEL> ,NB_CHANNEL> &RaP,\n                         Eigen::Matrix<double, NB_CHANNEL, NB_CHANNEL> &outputMatrix\n                         ){\n        for (int row = 0; row < NB_CHANNEL; row++){\n            for (int col = 0; col < NB_CHANNEL; col++){\n                outputMatrix(row,col) = RaP[row][col][p];\n            }\n        }\n    }\n\n    void paraCalcCorr(){\n        \n    }\n\n    void captureAudio(kfr::univector<kfr::fbase, NB_CHANNEL*NB_SAMPLES_PER_CHANNEL> &samples){\n        // fill samples\n    }\n\n    void int16ToKfrFbase(const int16_t * inputBuffer,\n                         kfr::univector<kfr::fbase, NB_CHANNEL*NB_SAMPLES_PER_CHANNEL> &outputKfrFbase ){\n        for (int i = 0; i < NB_CHANNEL*NB_SAMPLES_PER_CHANNEL; i++){\n            outputKfrFbase[i]=(kfr::fbase)inputBuffer[i]/(1<<15);\n        }\n\n    }\n\n    void splitChannels(\n            const kfr::univector<kfr::fbase, NB_CHANNEL*NB_SAMPLES_PER_CHANNEL> &samples,\n            kfr::univector<kfr::univector<kfr::fbase, NB_SAMPLES_PER_CHANNEL>, NB_CHANNEL> &splitedAudio\n            ) {\n        for(int channel = 0; channel < NB_CHANNEL; channel++){\n            for (int sample = 0; sample < NB_SAMPLES_PER_CHANNEL; sample++){\n                splitedAudio[channel][sample] = samples[NB_CHANNEL*sample + channelMap_[channel]];\n            }\n        }\n    }\n\npublic:\n    MultichannelCrossCorrelationCoefficientAlgorithm(const decltype(channelMap_) channelMap)\n        :channelMap_(channelMap)\n    { }\n\n    void entry(){\n        MicArrayRunner<SAMPLE_RATE, NB_SAMPLES_PER_CHANNEL> runner(\n                    [this](const int16_t * inputBuffer, const size_t framesPerBuffer, const size_t nbChannel)\n        {\n            int16ToKfrFbase(inputBuffer, kfrFbase_);\n            splitChannels(kfrFbase_, splitedAudio_);\n            for (auto row = 0; row < NB_CHANNEL; row++){\n                for (auto col = 0; col < NB_CHANNEL; col++){\n                    calcCorr(splitedAudio_[row], splitedAudio_[col], raP_[row][col]);\n                }\n            }\n\n            for(int p = 0; p<CORR_RESULT_SIZE; p++){\n                constructMatrix(p, raP_, eigenMatrix_[p]);\n                detRaP_[p]= eigenMatrix_[p].determinant();\n            }\n\n            {\n                int argMinP = 0;\n                double minDetRaP = detRaP_[argMinP];\n                for(int p = 1; p<CORR_RESULT_SIZE; p++){\n                    if (detRaP_[p] < minDetRaP){\n                        argMinP=p;\n                        minDetRaP=detRaP_[p];\n                    }\n                }\n                auto tDOA = (double)((int)argMinP - (int)NB_SAMPLES_PER_CHANNEL)/(int)SAMPLE_RATE;\n\n                {\n                    printf(\"tDOA=%f \\t  argMinP=%d \\t minDetRaP=%f\\n\", tDOA, argMinP, minDetRaP);\n                }\n            }\n        });\n\n        runner.init();\n        runner.start();\n\n        cv.notify_one();\n\n        // wait for the worker\n        {\n            std::unique_lock<std::mutex> lk(m);\n            cv.wait(lk, []{return shouldStop_;});\n        }\n\n        runner.stop();\n    }\n};\n\n\n\nauto test00(){\n    kfr::univector<kfr::fbase, 4> a({ 1, 2, 3, 4 });\n    kfr::univector<kfr::fbase, 4> b({ 1, 2, 3, 4 });\n    auto c = correlate(a, b);\n    kfr::println(c);\n    //CHECK(c.size() == 9u);\n    //CHECK(rms(c - kfr::univector<kfr::fbase>({ 1.5, 1., 1.5, 2.5, 3.75, -4., 7.75, 3.5, 1.25 })) < 0.0001);\n}\n\n\n\n\nint main(void){\n    MultichannelCrossCorrelationCoefficientAlgorithm<16000, 4, 1<<8> handler(channelMap_PS_eye);\n    handler.entry();\n\n    return 0;\n}\n", "meta": {"hexsha": "ac64e33735d099cf46eff6d323b8c14ee9f8611a", "size": 7502, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "k03/Entry.cpp", "max_stars_repo_name": "zhang-ray/DSP00", "max_stars_repo_head_hexsha": "9f211b1116322913828bcf9133354674840f450e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "k03/Entry.cpp", "max_issues_repo_name": "zhang-ray/DSP00", "max_issues_repo_head_hexsha": "9f211b1116322913828bcf9133354674840f450e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "k03/Entry.cpp", "max_forks_repo_name": "zhang-ray/DSP00", "max_forks_repo_head_hexsha": "9f211b1116322913828bcf9133354674840f450e", "max_forks_repo_licenses": ["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.2583333333, "max_line_length": 153, "alphanum_fraction": 0.5998400427, "num_tokens": 1969, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412808, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.49094983699067307}}
{"text": "// arma_numpy_test.hpp\n// A collection of simple C++ functions to test arma_numpy.i\n\n#include <armadillo>\n#include <string>\n\n// 1D\n\ndouble sum_vec( arma::vec v); // handle input of vec and output of something easily recognised\narma::sword sum_vec(arma::ivec v); // handle input of ivec and output of an armadillo typedef, plus handle overloading\narma::vec get_vec( int size ); // given something easily recognised, output vec\narma::vec reverse_vec( arma::vec v); // given a vec, return a vec\narma::icolvec reverse_vec( arma::ivec v); // given an ivec, return a typedef over ivec\narma::uvec reverse_vec( arma::uvec v); // given a uvec, return a uvec. Tests if numpy casting works properly.\n\ndouble sum_vec_by_ref( const arma::vec& v);\ndouble sum_vec_by_ptr( const arma::vec* v);\nvoid set_to_zero_by_ref( arma::vec& v);\nvoid set_to_zero_by_ptr( arma::vec* v);\n\nstd::size_t get_memptr( arma::vec* v);\nstd::size_t get_memptr_const( const arma::vec* v);\n\narma::vec& get_static_vec();\n\n// 2D\n\ndouble sum_mat( arma::mat m);\narma::sword sum_mat( arma::imat m);\narma::mat transpose_mat( arma::mat m);\nvoid set_to_zero_by_ref( arma::mat& m);\nvoid set_to_zero_by_ptr( arma::mat* m);\ndouble sum_mat_by_const_ref( const arma::mat& m);\ndouble sum_mat_by_const_ptr( const arma::mat* m);\n\nstd::size_t get_memptr( arma::mat* m);\nstd::size_t get_memptr_const( const arma::mat* m);\n\n// 3D\n\ndouble sum_cube( arma::cube c);\narma::sword sum_cube( arma::icube c);\narma::cube do_nothing( arma::cube c);\narma::mat get_second_slice( arma::cube c);\n", "meta": {"hexsha": "7d13578c166880f89cba2032ea0bc8519e672adb", "size": 1522, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/arma_numpy_test.hpp", "max_stars_repo_name": "LiamPattinson/arma_numpy", "max_stars_repo_head_hexsha": "1ab5b42be7aa3b4fe708bbb4e36ad854845bef9a", "max_stars_repo_licenses": ["MIT"], "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/arma_numpy_test.hpp", "max_issues_repo_name": "LiamPattinson/arma_numpy", "max_issues_repo_head_hexsha": "1ab5b42be7aa3b4fe708bbb4e36ad854845bef9a", "max_issues_repo_licenses": ["MIT"], "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/arma_numpy_test.hpp", "max_forks_repo_name": "LiamPattinson/arma_numpy", "max_forks_repo_head_hexsha": "1ab5b42be7aa3b4fe708bbb4e36ad854845bef9a", "max_forks_repo_licenses": ["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.8222222222, "max_line_length": 118, "alphanum_fraction": 0.7306176084, "num_tokens": 446, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.6893056295505783, "lm_q1q2_score": 0.4909456541430108}}
{"text": "#pragma once\n\n#include <polyfem/Mesh.hpp>\n\n#include <Eigen/Dense>\n\nnamespace polyfem\n{\n\tclass BoundarySampler\n\t{\n\tpublic:\n\t\tstatic void sample_parametric_quad_edge(int index, int n_samples, Eigen::MatrixXd &uv, Eigen::MatrixXd &samples);\n\t\tstatic void sample_parametric_tri_edge(int index, int n_samples, Eigen::MatrixXd &uv, Eigen::MatrixXd &samples);\n\n\t\tstatic void sample_parametric_quad_face(int index, int n_samples, Eigen::MatrixXd &uv, Eigen::MatrixXd &samples);\n\t\tstatic void sample_parametric_tri_face(int index, int n_samples, Eigen::MatrixXd &uv, Eigen::MatrixXd &samples);\n\n\t\tstatic void sample_polygon_edge(int face_id, int edge_id, int n_samples, const Mesh &mesh, Eigen::MatrixXd &uv, Eigen::MatrixXd &samples);\n\n\t\tstatic void quadrature_for_quad_edge(int index, int order, const int gid, const Mesh &mesh, Eigen::MatrixXd &uv, Eigen::MatrixXd &points, Eigen::VectorXd &weights);\n\t\tstatic void quadrature_for_tri_edge(int index, int order, const int gid, const Mesh &mesh, Eigen::MatrixXd &uv, Eigen::MatrixXd &points, Eigen::VectorXd &weights);\n\n\t\tstatic void quadrature_for_quad_face(int index, int order, const int gid, const Mesh &mesh, Eigen::MatrixXd &uv, Eigen::MatrixXd &points, Eigen::VectorXd &weights);\n\t\tstatic void quadrature_for_tri_face(int index, int order, const int gid, const Mesh &mesh, Eigen::MatrixXd &uv, Eigen::MatrixXd &points, Eigen::VectorXd &weights);\n\n\t\tstatic void quadrature_for_polygon_edge(int face_id, int edge_id, int order, const Mesh &mesh, Eigen::MatrixXd &uv, Eigen::MatrixXd &points, Eigen::VectorXd &weights);\n\n\t\tstatic void normal_for_quad_edge(int index, Eigen::MatrixXd &normal);\n\t\tstatic void normal_for_tri_edge(int index, Eigen::MatrixXd &normal);\n\n\t\tstatic void normal_for_quad_face(int index, Eigen::MatrixXd &normal);\n\t\tstatic void normal_for_tri_face(int index, Eigen::MatrixXd &normal);\n\n\t\tstatic void normal_for_polygon_edge(int face_id, int edge_id, const Mesh &mesh, Eigen::MatrixXd &normal);\n\n\t\tstatic Eigen::MatrixXd tet_local_node_coordinates_from_face(int lf);\n\t\tstatic Eigen::MatrixXd hex_local_node_coordinates_from_face(int lf);\n\t};\n}\n\n", "meta": {"hexsha": "3a78019088f488580b3d5f6233164cc198ff0bca", "size": 2113, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/utils/BoundarySampler.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/utils/BoundarySampler.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/utils/BoundarySampler.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": 51.5365853659, "max_line_length": 169, "alphanum_fraction": 0.7752011358, "num_tokens": 502, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321964553657, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.4909456534721188}}
{"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    testImuFactor.cpp\n * @brief   Unit test for ImuFactor\n * @author  Luca Carlone, Stephen Williams, Richard Roberts\n */\n\n#include <gtsam/navigation/ImuFactor.h>\n#include <gtsam/nonlinear/Values.h>\n#include <gtsam/inference/Symbol.h>\n#include <gtsam/navigation/ImuBias.h>\n#include <gtsam/geometry/Pose3.h>\n#include <gtsam/base/LieVector.h>\n#include <gtsam/base/TestableAssertions.h>\n#include <gtsam/base/numericalDerivative.h>\n#include <CppUnitLite/TestHarness.h>\n\n#include <boost/bind.hpp>\n#include <list>\n\nusing namespace std;\nusing namespace gtsam;\n\n// Convenience for named keys\nusing symbol_shorthand::X;\nusing symbol_shorthand::V;\nusing symbol_shorthand::B;\n\n/* ************************************************************************* */\nnamespace {\nVector callEvaluateError(const ImuFactor& factor,\n    const Pose3& pose_i, const LieVector& vel_i, const Pose3& pose_j, const LieVector& vel_j,\n    const imuBias::ConstantBias& bias)\n{\n  return factor.evaluateError(pose_i, vel_i, pose_j, vel_j, bias);\n}\n\nRot3 evaluateRotationError(const ImuFactor& factor,\n    const Pose3& pose_i, const LieVector& vel_i, const Pose3& pose_j, const LieVector& vel_j,\n    const imuBias::ConstantBias& bias)\n{\n  return Rot3::Expmap(factor.evaluateError(pose_i, vel_i, pose_j, vel_j, bias).tail(3) ) ;\n}\n\nImuFactor::PreintegratedMeasurements evaluatePreintegratedMeasurements(\n    const imuBias::ConstantBias& bias,\n    const list<Vector3>& measuredAccs,\n    const list<Vector3>& measuredOmegas,\n    const list<double>& deltaTs,\n    const Vector3& initialRotationRate = Vector3(0.0,0.0,0.0)\n    )\n{\n  ImuFactor::PreintegratedMeasurements result(bias, Matrix3::Identity(),\n      Matrix3::Identity(), Matrix3::Identity());\n\n  list<Vector3>::const_iterator itAcc = measuredAccs.begin();\n  list<Vector3>::const_iterator itOmega = measuredOmegas.begin();\n  list<double>::const_iterator itDeltaT = deltaTs.begin();\n  for( ; itAcc != measuredAccs.end(); ++itAcc, ++itOmega, ++itDeltaT) {\n    result.integrateMeasurement(*itAcc, *itOmega, *itDeltaT);\n  }\n\n  return result;\n}\n\nVector3 evaluatePreintegratedMeasurementsPosition(\n    const imuBias::ConstantBias& bias,\n    const list<Vector3>& measuredAccs,\n    const list<Vector3>& measuredOmegas,\n    const list<double>& deltaTs,\n    const Vector3& initialRotationRate = Vector3(0.0,0.0,0.0) )\n{\n  return evaluatePreintegratedMeasurements(bias,\n      measuredAccs, measuredOmegas, deltaTs).deltaPij;\n}\n\nVector3 evaluatePreintegratedMeasurementsVelocity(\n    const imuBias::ConstantBias& bias,\n    const list<Vector3>& measuredAccs,\n    const list<Vector3>& measuredOmegas,\n    const list<double>& deltaTs,\n    const Vector3& initialRotationRate = Vector3(0.0,0.0,0.0) )\n{\n  return evaluatePreintegratedMeasurements(bias,\n      measuredAccs, measuredOmegas, deltaTs).deltaVij;\n}\n\nRot3 evaluatePreintegratedMeasurementsRotation(\n    const imuBias::ConstantBias& bias,\n    const list<Vector3>& measuredAccs,\n    const list<Vector3>& measuredOmegas,\n    const list<double>& deltaTs,\n    const Vector3& initialRotationRate = Vector3(0.0,0.0,0.0) )\n{\n  return evaluatePreintegratedMeasurements(bias,\n      measuredAccs, measuredOmegas, deltaTs, initialRotationRate).deltaRij;\n}\n\nRot3 evaluateRotation(const Vector3 measuredOmega, const Vector3 biasOmega, const double deltaT)\n{\n  return Rot3::Expmap((measuredOmega - biasOmega) * deltaT);\n}\n\n\nVector3 evaluateLogRotation(const Vector3 thetahat, const Vector3 deltatheta)\n{\n  return Rot3::Logmap( Rot3::Expmap(thetahat).compose( Rot3::Expmap(deltatheta) ) );\n}\n\n}\n\n/* ************************************************************************* */\nTEST( ImuFactor, PreintegratedMeasurements )\n{\n  // Linearization point\n  imuBias::ConstantBias bias(Vector3(0,0,0), Vector3(0,0,0)); ///< Current estimate of acceleration and angular rate biases\n\n  // Measurements\n  Vector3 measuredAcc(0.1, 0.0, 0.0);\n  Vector3 measuredOmega(M_PI/100.0, 0.0, 0.0);\n  double deltaT = 0.5;\n\n  // Expected preintegrated values\n  Vector3 expectedDeltaP1; expectedDeltaP1 << 0.5*0.1*0.5*0.5, 0, 0;\n  Vector3 expectedDeltaV1(0.05, 0.0, 0.0);\n  Rot3 expectedDeltaR1 = Rot3::RzRyRx(0.5 * M_PI/100.0, 0.0, 0.0);\n  double expectedDeltaT1(0.5);\n\n  bool use2ndOrderIntegration = true;\n  // Actual preintegrated values\n  ImuFactor::PreintegratedMeasurements actual1(bias, Matrix3::Zero(), Matrix3::Zero(), Matrix3::Zero(), use2ndOrderIntegration);\n  actual1.integrateMeasurement(measuredAcc, measuredOmega, deltaT);\n\n  EXPECT(assert_equal(Vector(expectedDeltaP1), Vector(actual1.deltaPij), 1e-6));\n  EXPECT(assert_equal(Vector(expectedDeltaV1), Vector(actual1.deltaVij), 1e-6));\n  EXPECT(assert_equal(expectedDeltaR1, actual1.deltaRij, 1e-6));\n  DOUBLES_EQUAL(expectedDeltaT1, actual1.deltaTij, 1e-6);\n\n  // Integrate again\n  Vector3 expectedDeltaP2; expectedDeltaP2 << 0.025 + expectedDeltaP1(0) + 0.5*0.1*0.5*0.5, 0, 0;\n  Vector3 expectedDeltaV2 = Vector3(0.05, 0.0, 0.0) + expectedDeltaR1.matrix() * measuredAcc * 0.5;\n  Rot3 expectedDeltaR2 = Rot3::RzRyRx(2.0 * 0.5 * M_PI/100.0, 0.0, 0.0);\n  double expectedDeltaT2(1);\n\n  // Actual preintegrated values\n  ImuFactor::PreintegratedMeasurements actual2 = actual1;\n  actual2.integrateMeasurement(measuredAcc, measuredOmega, deltaT);\n\n  EXPECT(assert_equal(Vector(expectedDeltaP2), Vector(actual2.deltaPij), 1e-6));\n  EXPECT(assert_equal(Vector(expectedDeltaV2), Vector(actual2.deltaVij), 1e-6));\n  EXPECT(assert_equal(expectedDeltaR2, actual2.deltaRij, 1e-6));\n  DOUBLES_EQUAL(expectedDeltaT2, actual2.deltaTij, 1e-6);\n}\n\n/* ************************************************************************* */\nTEST( ImuFactor, Error )\n{\n  // Linearization point\n  imuBias::ConstantBias bias; // Bias\n  Pose3 x1(Rot3::RzRyRx(M_PI/12.0, M_PI/6.0, M_PI/4.0), Point3(5.0, 1.0, -50.0));\n  LieVector v1((Vector(3) << 0.5, 0.0, 0.0));\n  Pose3 x2(Rot3::RzRyRx(M_PI/12.0 + M_PI/100.0, M_PI/6.0, M_PI/4.0), Point3(5.5, 1.0, -50.0));\n  LieVector v2((Vector(3) << 0.5, 0.0, 0.0));\n\n  // Measurements\n  Vector3 gravity; gravity << 0, 0, 9.81;\n  Vector3 omegaCoriolis; omegaCoriolis << 0, 0, 0;\n  Vector3 measuredOmega; measuredOmega << M_PI/100, 0, 0;\n  Vector3 measuredAcc = x1.rotation().unrotate(-Point3(gravity)).vector();\n  double deltaT = 1.0;\n  bool use2ndOrderIntegration = true;\n  ImuFactor::PreintegratedMeasurements pre_int_data(bias, Matrix3::Zero(), Matrix3::Zero(), Matrix3::Zero(), use2ndOrderIntegration);\n  pre_int_data.integrateMeasurement(measuredAcc, measuredOmega, deltaT);\n\n  // Create factor\n  ImuFactor factor(X(1), V(1), X(2), V(2), B(1), pre_int_data, gravity, omegaCoriolis);\n\n  Vector errorActual = factor.evaluateError(x1, v1, x2, v2, bias);\n\n  // Expected error\n  Vector errorExpected(9); errorExpected << 0, 0, 0, 0, 0, 0, 0, 0, 0;\n  EXPECT(assert_equal(errorExpected, errorActual, 1e-6));\n\n  // Expected Jacobians\n  Matrix H1e = numericalDerivative11<Pose3>(\n      boost::bind(&callEvaluateError, factor, _1, v1, x2, v2, bias), x1);\n  Matrix H2e = numericalDerivative11<LieVector>(\n      boost::bind(&callEvaluateError, factor, x1, _1, x2, v2, bias), v1);\n  Matrix H3e = numericalDerivative11<Pose3>(\n      boost::bind(&callEvaluateError, factor, x1, v1, _1, v2, bias), x2);\n  Matrix H4e = numericalDerivative11<LieVector>(\n      boost::bind(&callEvaluateError, factor, x1, v1, x2, _1, bias), v2);\n  Matrix H5e = numericalDerivative11<imuBias::ConstantBias>(\n      boost::bind(&callEvaluateError, factor, x1, v1, x2, v2, _1), bias);\n\n  // Check rotation Jacobians\n  Matrix RH1e = numericalDerivative11<Rot3,Pose3>(\n      boost::bind(&evaluateRotationError, factor, _1, v1, x2, v2, bias), x1);\n  Matrix RH3e = numericalDerivative11<Rot3,Pose3>(\n      boost::bind(&evaluateRotationError, factor, x1, v1, _1, v2, bias), x2);\n\n  // Actual Jacobians\n  Matrix H1a, H2a, H3a, H4a, H5a;\n  (void) factor.evaluateError(x1, v1, x2, v2, bias, H1a, H2a, H3a, H4a, H5a);\n\n\n  // positions and velocities\n  Matrix H1etop6 =  H1e.topRows(6);\n  Matrix H1atop6 =  H1a.topRows(6);\n  EXPECT(assert_equal(H1etop6, H1atop6));\n  // rotations\n  EXPECT(assert_equal(RH1e, H1a.bottomRows(3), 1e-5));  // 1e-5 needs to be added only when using quaternions for rotations\n\n  EXPECT(assert_equal(H2e, H2a));\n\n  // positions and velocities\n  Matrix H3etop6 =  H3e.topRows(6);\n  Matrix H3atop6 =  H3a.topRows(6);\n  EXPECT(assert_equal(H3etop6, H3atop6));\n  // rotations\n  EXPECT(assert_equal(RH3e, H3a.bottomRows(3), 1e-5));  // 1e-5 needs to be added only when using quaternions for rotations\n\n  EXPECT(assert_equal(H4e, H4a));\n//  EXPECT(assert_equal(H5e, H5a));\n}\n\n/* ************************************************************************* */\nTEST( ImuFactor, ErrorWithBiases )\n{\n  // Linearization point\n//  Vector bias(6); bias << 0.2, 0, 0, 0.1, 0, 0; // Biases (acc, rot)\n//  Pose3 x1(Rot3::RzRyRx(M_PI/12.0, M_PI/6.0, M_PI/4.0), Point3(5.0, 1.0, -50.0));\n//  LieVector v1((Vector(3) << 0.5, 0.0, 0.0));\n//  Pose3 x2(Rot3::RzRyRx(M_PI/12.0 + M_PI/10.0, M_PI/6.0, M_PI/4.0), Point3(5.5, 1.0, -50.0));\n//  LieVector v2((Vector(3) << 0.5, 0.0, 0.0));\n\n\n  imuBias::ConstantBias bias(Vector3(0.2, 0, 0), Vector3(0, 0, 0.3)); // Biases (acc, rot)\n  Pose3 x1(Rot3::Expmap(Vector3(0, 0, M_PI/4.0)), Point3(5.0, 1.0, -50.0));\n  LieVector v1((Vector(3) << 0.5, 0.0, 0.0));\n  Pose3 x2(Rot3::Expmap(Vector3(0, 0, M_PI/4.0 + M_PI/10.0)), Point3(5.5, 1.0, -50.0));\n  LieVector v2((Vector(3) << 0.5, 0.0, 0.0));\n\n  // Measurements\n  Vector3 gravity; gravity << 0, 0, 9.81;\n  Vector3 omegaCoriolis; omegaCoriolis << 0, 0.1, 0.1;\n  Vector3 measuredOmega; measuredOmega << 0, 0, M_PI/10.0+0.3;\n  Vector3 measuredAcc = x1.rotation().unrotate(-Point3(gravity)).vector() + Vector3(0.2,0.0,0.0);\n  double deltaT = 1.0;\n\n  ImuFactor::PreintegratedMeasurements pre_int_data(imuBias::ConstantBias(Vector3(0.2, 0.0, 0.0), Vector3(0.0, 0.0, 0.0)), Matrix3::Zero(), Matrix3::Zero(), Matrix3::Zero());\n    pre_int_data.integrateMeasurement(measuredAcc, measuredOmega, deltaT);\n\n//  ImuFactor::PreintegratedMeasurements pre_int_data(bias.head(3), bias.tail(3));\n//    pre_int_data.integrateMeasurement(measuredAcc, measuredOmega, deltaT);\n\n    // Create factor\n    ImuFactor factor(X(1), V(1), X(2), V(2), B(1), pre_int_data, gravity, omegaCoriolis);\n\n    SETDEBUG(\"ImuFactor evaluateError\", false);\n    Vector errorActual = factor.evaluateError(x1, v1, x2, v2, bias);\n    SETDEBUG(\"ImuFactor evaluateError\", false);\n\n    // Expected error\n    Vector errorExpected(9); errorExpected << 0, 0, 0, 0, 0, 0, 0, 0, 0;\n//    EXPECT(assert_equal(errorExpected, errorActual, 1e-6));\n\n    // Expected Jacobians\n    Matrix H1e = numericalDerivative11<Pose3>(\n        boost::bind(&callEvaluateError, factor, _1, v1, x2, v2, bias), x1);\n    Matrix H2e = numericalDerivative11<LieVector>(\n        boost::bind(&callEvaluateError, factor, x1, _1, x2, v2, bias), v1);\n    Matrix H3e = numericalDerivative11<Pose3>(\n        boost::bind(&callEvaluateError, factor, x1, v1, _1, v2, bias), x2);\n    Matrix H4e = numericalDerivative11<LieVector>(\n        boost::bind(&callEvaluateError, factor, x1, v1, x2, _1, bias), v2);\n    Matrix H5e = numericalDerivative11<imuBias::ConstantBias>(\n        boost::bind(&callEvaluateError, factor, x1, v1, x2, v2, _1), bias);\n\n    // Check rotation Jacobians\n    Matrix RH1e = numericalDerivative11<Rot3,Pose3>(\n        boost::bind(&evaluateRotationError, factor, _1, v1, x2, v2, bias), x1);\n    Matrix RH3e = numericalDerivative11<Rot3,Pose3>(\n        boost::bind(&evaluateRotationError, factor, x1, v1, _1, v2, bias), x2);\n    Matrix RH5e = numericalDerivative11<Rot3,imuBias::ConstantBias>(\n        boost::bind(&evaluateRotationError, factor, x1, v1, x2, v2, _1), bias);\n\n    // Actual Jacobians\n    Matrix H1a, H2a, H3a, H4a, H5a;\n    (void) factor.evaluateError(x1, v1, x2, v2, bias, H1a, H2a, H3a, H4a, H5a);\n\n    EXPECT(assert_equal(H1e, H1a));\n    EXPECT(assert_equal(H2e, H2a));\n    EXPECT(assert_equal(H3e, H3a));\n    EXPECT(assert_equal(H4e, H4a));\n    EXPECT(assert_equal(H5e, H5a));\n}\n\n/* ************************************************************************* */\nTEST( ImuFactor, PartialDerivativeExpmap )\n{\n  // Linearization point\n  Vector3 biasOmega; biasOmega << 0,0,0; ///< Current estimate of rotation rate bias\n\n  // Measurements\n  Vector3 measuredOmega; measuredOmega << 0.1, 0, 0;\n  double deltaT = 0.5;\n\n\n  // Compute numerical derivatives\n  Matrix expectedDelRdelBiasOmega = numericalDerivative11<Rot3, LieVector>(boost::bind(\n      &evaluateRotation, measuredOmega, _1, deltaT), LieVector(biasOmega));\n\n  const Matrix3 Jr = Rot3::rightJacobianExpMapSO3((measuredOmega - biasOmega) * deltaT);\n\n   Matrix3  actualdelRdelBiasOmega = - Jr * deltaT; // the delta bias appears with the minus sign\n\n  // Compare Jacobians\n  EXPECT(assert_equal(expectedDelRdelBiasOmega, actualdelRdelBiasOmega, 1e-3));  // 1e-3 needs to be added only when using quaternions for rotations\n\n}\n\n/* ************************************************************************* */\nTEST( ImuFactor, PartialDerivativeLogmap )\n{\n  // Linearization point\n  Vector3 thetahat; thetahat << 0.1,0.1,0; ///< Current estimate of rotation rate bias\n\n  // Measurements\n  Vector3 deltatheta; deltatheta << 0, 0, 0;\n\n\n  // Compute numerical derivatives\n  Matrix expectedDelFdeltheta = numericalDerivative11<LieVector>(boost::bind(\n      &evaluateLogRotation, thetahat, _1), LieVector(deltatheta));\n\n  const Vector3 x = thetahat; // parametrization of so(3)\n  const Matrix3 X = skewSymmetric(x); // element of Lie algebra so(3): X = x^\n  double normx = norm_2(x);\n  const Matrix3  actualDelFdeltheta = Matrix3::Identity() +\n       0.5 * X + (1/(normx*normx) - (1+cos(normx))/(2*normx * sin(normx)) ) * X * X;\n\n//  std::cout << \"actualDelFdeltheta\" << actualDelFdeltheta << std::endl;\n//  std::cout << \"expectedDelFdeltheta\" << expectedDelFdeltheta << std::endl;\n\n  // Compare Jacobians\n  EXPECT(assert_equal(expectedDelFdeltheta, actualDelFdeltheta));\n\n}\n\n/* ************************************************************************* */\nTEST( ImuFactor, fistOrderExponential )\n{\n  // Linearization point\n    Vector3 biasOmega; biasOmega << 0,0,0; ///< Current estimate of rotation rate bias\n\n    // Measurements\n    Vector3 measuredOmega; measuredOmega << 0.1, 0, 0;\n    double deltaT = 1.0;\n\n    // change w.r.t. linearization point\n    double alpha = 0.0;\n    Vector3 deltabiasOmega; deltabiasOmega << alpha,alpha,alpha;\n\n\n    const Matrix3 Jr = Rot3::rightJacobianExpMapSO3((measuredOmega - biasOmega) * deltaT);\n\n     Matrix3  delRdelBiasOmega = - Jr * deltaT; // the delta bias appears with the minus sign\n\n     const Matrix expectedRot = Rot3::Expmap((measuredOmega - biasOmega - deltabiasOmega) * deltaT).matrix();\n\n     const Matrix3 hatRot = Rot3::Expmap((measuredOmega - biasOmega) * deltaT).matrix();\n     const Matrix3 actualRot =\n         hatRot * Rot3::Expmap(delRdelBiasOmega * deltabiasOmega).matrix();\n         //hatRot * (Matrix3::Identity() + skewSymmetric(delRdelBiasOmega * deltabiasOmega));\n\n    // Compare Jacobians\n    EXPECT(assert_equal(expectedRot, actualRot));\n}\n\n/* ************************************************************************* */\nTEST( ImuFactor, FirstOrderPreIntegratedMeasurements )\n{\n  // Linearization point\n  imuBias::ConstantBias bias; ///< Current estimate of acceleration and rotation rate biases\n\n  Pose3 body_P_sensor(Rot3::Expmap(Vector3(0,0.1,0.1)), Point3(1, 0, 1));\n\n  // Measurements\n  list<Vector3> measuredAccs, measuredOmegas;\n  list<double> deltaTs;\n  measuredAccs.push_back(Vector3(0.1, 0.0, 0.0));\n  measuredOmegas.push_back(Vector3(M_PI/100.0, 0.0, 0.0));\n  deltaTs.push_back(0.01);\n  measuredAccs.push_back(Vector3(0.1, 0.0, 0.0));\n  measuredOmegas.push_back(Vector3(M_PI/100.0, 0.0, 0.0));\n  deltaTs.push_back(0.01);\n  for(int i=1;i<100;i++)\n  {\n    measuredAccs.push_back(Vector3(0.05, 0.09, 0.01));\n    measuredOmegas.push_back(Vector3(M_PI/100.0, M_PI/300.0, 2*M_PI/100.0));\n    deltaTs.push_back(0.01);\n  }\n\n  // Actual preintegrated values\n  ImuFactor::PreintegratedMeasurements preintegrated =\n      evaluatePreintegratedMeasurements(bias, measuredAccs, measuredOmegas, deltaTs, Vector3(M_PI/100.0, 0.0, 0.0));\n\n  // Compute numerical derivatives\n  Matrix expectedDelPdelBias = numericalDerivative11<imuBias::ConstantBias>(\n      boost::bind(&evaluatePreintegratedMeasurementsPosition, _1, measuredAccs, measuredOmegas, deltaTs, Vector3(M_PI/100.0, 0.0, 0.0)), bias);\n  Matrix expectedDelPdelBiasAcc   = expectedDelPdelBias.leftCols(3);\n  Matrix expectedDelPdelBiasOmega = expectedDelPdelBias.rightCols(3);\n\n  Matrix expectedDelVdelBias = numericalDerivative11<imuBias::ConstantBias>(\n      boost::bind(&evaluatePreintegratedMeasurementsVelocity, _1, measuredAccs, measuredOmegas, deltaTs, Vector3(M_PI/100.0, 0.0, 0.0)), bias);\n  Matrix expectedDelVdelBiasAcc   = expectedDelVdelBias.leftCols(3);\n  Matrix expectedDelVdelBiasOmega = expectedDelVdelBias.rightCols(3);\n\n  Matrix expectedDelRdelBias = numericalDerivative11<Rot3,imuBias::ConstantBias>(\n      boost::bind(&evaluatePreintegratedMeasurementsRotation, _1, measuredAccs, measuredOmegas, deltaTs, Vector3(M_PI/100.0, 0.0, 0.0)), bias);\n  Matrix expectedDelRdelBiasAcc   = expectedDelRdelBias.leftCols(3);\n  Matrix expectedDelRdelBiasOmega = expectedDelRdelBias.rightCols(3);\n\n  // Compare Jacobians\n  EXPECT(assert_equal(expectedDelPdelBiasAcc, preintegrated.delPdelBiasAcc));\n  EXPECT(assert_equal(expectedDelPdelBiasOmega, preintegrated.delPdelBiasOmega));\n  EXPECT(assert_equal(expectedDelVdelBiasAcc, preintegrated.delVdelBiasAcc));\n  EXPECT(assert_equal(expectedDelVdelBiasOmega, preintegrated.delVdelBiasOmega));\n  EXPECT(assert_equal(expectedDelRdelBiasAcc, Matrix::Zero(3,3)));\n  EXPECT(assert_equal(expectedDelRdelBiasOmega, preintegrated.delRdelBiasOmega, 1e-3)); // 1e-3 needs to be added only when using quaternions for rotations\n}\n\n//#include <gtsam/linear/GaussianFactorGraph.h>\n///* ************************************************************************* */\n//TEST( ImuFactor, LinearizeTiming)\n//{\n//  // Linearization point\n//  Pose3 x1(Rot3::RzRyRx(M_PI/12.0, M_PI/6.0, M_PI/4.0), Point3(5.0, 1.0, -50.0));\n//  LieVector v1((Vector(3) << 0.5, 0.0, 0.0));\n//  Pose3 x2(Rot3::RzRyRx(M_PI/12.0 + M_PI/100.0, M_PI/6.0, M_PI/4.0), Point3(5.5, 1.0, -50.0));\n//  LieVector v2((Vector(3) << 0.5, 0.0, 0.0));\n//  imuBias::ConstantBias bias(Vector3(0.001, 0.002, 0.008), Vector3(0.002, 0.004, 0.012));\n//\n//  // Pre-integrator\n//  imuBias::ConstantBias biasHat(Vector3(0, 0, 0.10), Vector3(0, 0, 0.10));\n//  Vector3 gravity; gravity << 0, 0, 9.81;\n//  Vector3 omegaCoriolis; omegaCoriolis << 0.0001, 0, 0.01;\n//  ImuFactor::PreintegratedMeasurements pre_int_data(biasHat, Matrix3::Identity(), Matrix3::Identity(), Matrix3::Identity());\n//\n//  // Pre-integrate Measurements\n//  Vector3 measuredAcc(0.1, 0.0, 0.0);\n//  Vector3 measuredOmega(M_PI/100.0, 0.0, 0.0);\n//  double deltaT = 0.5;\n//  for(size_t i = 0; i < 50; ++i) {\n//    pre_int_data.integrateMeasurement(measuredAcc, measuredOmega, deltaT);\n//  }\n//\n//  // Create factor\n//  noiseModel::Base::shared_ptr model = noiseModel::Gaussian::Covariance(pre_int_data.preintegratedMeasurementsCovariance());\n//  ImuFactor factor(X(1), V(1), X(2), V(2), B(1), pre_int_data, gravity, omegaCoriolis, model);\n//\n//  Values values;\n//  values.insert(X(1), x1);\n//  values.insert(X(2), x2);\n//  values.insert(V(1), v1);\n//  values.insert(V(2), v2);\n//  values.insert(B(1), bias);\n//\n//  Ordering ordering;\n//  ordering.push_back(X(1));\n//  ordering.push_back(V(1));\n//  ordering.push_back(X(2));\n//  ordering.push_back(V(2));\n//  ordering.push_back(B(1));\n//\n//  GaussianFactorGraph graph;\n//  gttic_(LinearizeTiming);\n//  for(size_t i = 0; i < 100000; ++i) {\n//    GaussianFactor::shared_ptr g = factor.linearize(values, ordering);\n//    graph.push_back(g);\n//  }\n//  gttoc_(LinearizeTiming);\n//  tictoc_finishedIteration_();\n//  std::cout << \"Linear Error: \" << graph.error(values.zeroVectors(ordering)) << std::endl;\n//  tictoc_print_();\n//}\n\n\n/* ************************************************************************* */\nTEST( ImuFactor, ErrorWithBiasesAndSensorBodyDisplacement )\n{\n\n  imuBias::ConstantBias bias(Vector3(0.2, 0, 0), Vector3(0, 0, 0.3)); // Biases (acc, rot)\n  Pose3 x1(Rot3::Expmap(Vector3(0, 0, M_PI/4.0)), Point3(5.0, 1.0, -50.0));\n  LieVector v1((Vector(3) << 0.5, 0.0, 0.0));\n  Pose3 x2(Rot3::Expmap(Vector3(0, 0, M_PI/4.0 + M_PI/10.0)), Point3(5.5, 1.0, -50.0));\n  LieVector v2((Vector(3) << 0.5, 0.0, 0.0));\n\n  // Measurements\n  Vector3 gravity; gravity << 0, 0, 9.81;\n  Vector3 omegaCoriolis; omegaCoriolis << 0, 0.1, 0.1;\n  Vector3 measuredOmega; measuredOmega << 0, 0, M_PI/10.0+0.3;\n  Vector3 measuredAcc = x1.rotation().unrotate(-Point3(gravity)).vector() + Vector3(0.2,0.0,0.0);\n  double deltaT = 1.0;\n\n  const Pose3 body_P_sensor(Rot3::Expmap(Vector3(0,0.10,0.10)), Point3(1,0,0));\n\n//  ImuFactor::PreintegratedMeasurements pre_int_data(imuBias::ConstantBias(Vector3(0.2, 0.0, 0.0),\n//        Vector3(0.0, 0.0, 0.0)), Matrix3::Zero(), Matrix3::Zero(), Matrix3::Zero(), measuredOmega);\n\n\n  ImuFactor::PreintegratedMeasurements pre_int_data(imuBias::ConstantBias(Vector3(0.2, 0.0, 0.0),\n        Vector3(0.0, 0.0, 0.0)), Matrix3::Zero(), Matrix3::Zero(), Matrix3::Zero());\n\n\n\n  pre_int_data.integrateMeasurement(measuredAcc, measuredOmega, deltaT);\n\n    // Create factor\n    ImuFactor factor(X(1), V(1), X(2), V(2), B(1), pre_int_data, gravity, omegaCoriolis);\n\n    // Expected Jacobians\n    Matrix H1e = numericalDerivative11<Pose3>(\n        boost::bind(&callEvaluateError, factor, _1, v1, x2, v2, bias), x1);\n    Matrix H2e = numericalDerivative11<LieVector>(\n        boost::bind(&callEvaluateError, factor, x1, _1, x2, v2, bias), v1);\n    Matrix H3e = numericalDerivative11<Pose3>(\n        boost::bind(&callEvaluateError, factor, x1, v1, _1, v2, bias), x2);\n    Matrix H4e = numericalDerivative11<LieVector>(\n        boost::bind(&callEvaluateError, factor, x1, v1, x2, _1, bias), v2);\n    Matrix H5e = numericalDerivative11<imuBias::ConstantBias>(\n        boost::bind(&callEvaluateError, factor, x1, v1, x2, v2, _1), bias);\n\n    // Check rotation Jacobians\n    Matrix RH1e = numericalDerivative11<Rot3,Pose3>(\n        boost::bind(&evaluateRotationError, factor, _1, v1, x2, v2, bias), x1);\n    Matrix RH3e = numericalDerivative11<Rot3,Pose3>(\n        boost::bind(&evaluateRotationError, factor, x1, v1, _1, v2, bias), x2);\n    Matrix RH5e = numericalDerivative11<Rot3,imuBias::ConstantBias>(\n        boost::bind(&evaluateRotationError, factor, x1, v1, x2, v2, _1), bias);\n\n    // Actual Jacobians\n    Matrix H1a, H2a, H3a, H4a, H5a;\n    (void) factor.evaluateError(x1, v1, x2, v2, bias, H1a, H2a, H3a, H4a, H5a);\n\n    EXPECT(assert_equal(H1e, H1a));\n    EXPECT(assert_equal(H2e, H2a));\n    EXPECT(assert_equal(H3e, H3a));\n    EXPECT(assert_equal(H4e, H4a));\n    EXPECT(assert_equal(H5e, H5a));\n}\n\n\n/* ************************************************************************* */\n  int main() { TestResult tr; return TestRegistry::runAllTests(tr);}\n/* ************************************************************************* */\n", "meta": {"hexsha": "a6894898b467b4d590de18b20998a62aa9dd6dab", "size": 23496, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/navigation/tests/testImuFactor.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/navigation/tests/testImuFactor.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/navigation/tests/testImuFactor.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": 41.3661971831, "max_line_length": 174, "alphanum_fraction": 0.6702843037, "num_tokens": 7641, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.6893056104028797, "lm_q1q2_score": 0.49094564050540357}}
{"text": "/*=============================================================================\n    Copyright (c) 2001-2003 Daniel Nuffer\n    http://spirit.sourceforge.net/\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///////////////////////////////////////////////////////////////////////////////\n//\n//  Demonstrates the ASTs. This is discussed in the\n//  \"Trees\" chapter in the Spirit User's Guide.\n//\n///////////////////////////////////////////////////////////////////////////////\n#define BOOST_SPIRIT_DUMP_PARSETREE_AS_XML\n\n#include <boost/spirit/include/classic_core.hpp>\n#include <boost/spirit/include/classic_ast.hpp>\n#include <boost/spirit/include/classic_tree_to_xml.hpp>\n#include <boost/assert.hpp>\n#include \"tree_calc_grammar.hpp\"\n\n#include <iostream>\n#include <stack>\n#include <functional>\n#include <string>\n\n#if defined(BOOST_SPIRIT_DUMP_PARSETREE_AS_XML)\n#include <map>\n#endif\n\n// This example shows how to use an AST.\n////////////////////////////////////////////////////////////////////////////\nusing namespace std;\nusing namespace BOOST_SPIRIT_CLASSIC_NS;\n\ntypedef char const*         iterator_t;\ntypedef tree_match<iterator_t> parse_tree_match_t;\ntypedef parse_tree_match_t::tree_iterator iter_t;\n\n////////////////////////////////////////////////////////////////////////////\nlong evaluate(parse_tree_match_t hit);\nlong eval_expression(iter_t const& i);\n\nlong evaluate(tree_parse_info<> info)\n{\n    return eval_expression(info.trees.begin());\n}\n\nlong eval_expression(iter_t const& i)\n{\n    cout << \"In eval_expression. i->value = \" <<\n        string(i->value.begin(), i->value.end()) <<\n        \" i->children.size() = \" << i->children.size() << endl;\n\n    if (i->value.id() == calculator::integerID)\n    {\n        BOOST_ASSERT(i->children.size() == 0);\n\n        // extract integer (not always delimited by '\\0')\n        string integer(i->value.begin(), i->value.end());\n\n        return strtol(integer.c_str(), 0, 10);\n    }\n    else if (i->value.id() == calculator::factorID)\n    {\n        // factor can only be unary minus\n        BOOST_ASSERT(*i->value.begin() == '-');\n        return - eval_expression(i->children.begin());\n    }\n    else if (i->value.id() == calculator::termID)\n    {\n        if (*i->value.begin() == '*')\n        {\n            BOOST_ASSERT(i->children.size() == 2);\n            return eval_expression(i->children.begin()) *\n                eval_expression(i->children.begin()+1);\n        }\n        else if (*i->value.begin() == '/')\n        {\n            BOOST_ASSERT(i->children.size() == 2);\n            return eval_expression(i->children.begin()) /\n                eval_expression(i->children.begin()+1);\n        }\n        else\n            BOOST_ASSERT(0);\n    }\n    else if (i->value.id() == calculator::expressionID)\n    {\n        if (*i->value.begin() == '+')\n        {\n            BOOST_ASSERT(i->children.size() == 2);\n            return eval_expression(i->children.begin()) +\n                eval_expression(i->children.begin()+1);\n        }\n        else if (*i->value.begin() == '-')\n        {\n            BOOST_ASSERT(i->children.size() == 2);\n            return eval_expression(i->children.begin()) -\n                eval_expression(i->children.begin()+1);\n        }\n        else\n            BOOST_ASSERT(0);\n    }\n    else\n    {\n        BOOST_ASSERT(0); // error\n    }\n\n    return 0;\n}\n\n////////////////////////////////////////////////////////////////////////////\nint\nmain()\n{\n    // look in tree_calc_grammar for the definition of calculator\n    calculator calc;\n\n    cout << \"/////////////////////////////////////////////////////////\\n\\n\";\n    cout << \"\\t\\tThe simplest working calculator...\\n\\n\";\n    cout << \"/////////////////////////////////////////////////////////\\n\\n\";\n    cout << \"Type an expression...or [q or Q] to quit\\n\\n\";\n\n    string str;\n    while (getline(cin, str))\n    {\n        if (str.empty() || str[0] == 'q' || str[0] == 'Q')\n            break;\n\n        tree_parse_info<> info = ast_parse(str.c_str(), calc);\n\n        if (info.full)\n        {\n#if defined(BOOST_SPIRIT_DUMP_PARSETREE_AS_XML)\n            // dump parse tree as XML\n            std::map<parser_id, std::string> rule_names;\n            rule_names[calculator::integerID] = \"integer\";\n            rule_names[calculator::factorID] = \"factor\";\n            rule_names[calculator::termID] = \"term\";\n            rule_names[calculator::expressionID] = \"expression\";\n            tree_to_xml(cout, info.trees, str.c_str(), rule_names);\n#endif\n\n            // print the result\n            cout << \"parsing succeeded\\n\";\n            cout << \"result = \" << evaluate(info) << \"\\n\\n\";\n        }\n        else\n        {\n            cout << \"parsing failed\\n\";\n        }\n    }\n\n    cout << \"Bye... :-) \\n\\n\";\n    return 0;\n}\n\n\n", "meta": {"hexsha": "33c5e0f1fe0885777d89f4f8376e6fb13ff64811", "size": 4955, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/spirit/classic/example/fundamental/ast_calc.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "boost/libs/spirit/classic/example/fundamental/ast_calc.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "boost/libs/spirit/classic/example/fundamental/ast_calc.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 30.96875, "max_line_length": 79, "alphanum_fraction": 0.5035317861, "num_tokens": 1056, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056040203135, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.4909456401699575}}
{"text": "#define BOOST_TEST_MODULE modular_arithmetic\n#include <boost/test/included/unit_test.hpp>\n\n#include <fc/exception/exception.hpp>\n#include <fc/crypto/hex.hpp>\n#include <fc/crypto/modular_arithmetic.hpp>\n#include <fc/utility.hpp>\n\nusing namespace fc;\n#include \"test_utils.hpp\"\n\nnamespace std {\nstd::ostream& operator<<(std::ostream& st, const std::variant<fc::modular_arithmetic_error, bytes>& err)\n{\n    if(std::holds_alternative<fc::modular_arithmetic_error>(err))\n        st << static_cast<int32_t>(std::get<fc::modular_arithmetic_error>(err));\n    else\n        st << fc::to_hex(std::get<bytes>(err));\n    return st;\n}\n}\n\n\nBOOST_AUTO_TEST_SUITE(modular_arithmetic)\nBOOST_AUTO_TEST_CASE(modexp) try {\n\n\n    using modexp_test = std::tuple<std::vector<string>, std::variant<fc::modular_arithmetic_error, bytes>>;\n\n    const std::vector<modexp_test> tests {\n        //test1\n        {\n            {\n                \"03\",\n                \"fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2e\",\n                \"fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f\",\n            },\n            to_bytes(\"0000000000000000000000000000000000000000000000000000000000000001\"),\n        },\n\n        //test2\n        {\n            {\n                \"\",\n                \"fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2e\",\n                \"fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f\",\n            },\n            to_bytes(\"0000000000000000000000000000000000000000000000000000000000000000\")\n        },\n\n        //test3\n        {\n            {\n                \"01\",\n                \"fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2e\",\n                \"\",\n            },\n            modular_arithmetic_error::modulus_len_zero\n        },\n\n\n    };\n\n    for(const auto& test : tests) {\n        const auto& parts           = std::get<0>(test);\n        const auto& expected_result = std::get<1>(test);\n\n        auto base = to_bytes(parts[0]);\n        auto exponent = to_bytes(parts[1]);\n        auto modulus = to_bytes(parts[2]);\n\n        auto res = fc::modexp(base, exponent, modulus);\n        BOOST_CHECK_EQUAL(res, expected_result);\n    }\n\n} FC_LOG_AND_RETHROW();\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "5ec8ca53b6cdf07a542f86dd9a67387e040133ec", "size": 2246, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/crypto/test_modular_arithmetic.cpp", "max_stars_repo_name": "eosnetworkfoundation/mandel-fc", "max_stars_repo_head_hexsha": "3b24dc3ae79ab962ce05a8aaef62f0886cb086e9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2022-01-17T23:48:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-17T23:48:50.000Z", "max_issues_repo_path": "test/crypto/test_modular_arithmetic.cpp", "max_issues_repo_name": "eosnetworkfoundation/mandel-fc", "max_issues_repo_head_hexsha": "3b24dc3ae79ab962ce05a8aaef62f0886cb086e9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-01-06T20:17:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-06T20:17:15.000Z", "max_forks_repo_path": "test/crypto/test_modular_arithmetic.cpp", "max_forks_repo_name": "eosnetworkfoundation/mandel-fc", "max_forks_repo_head_hexsha": "3b24dc3ae79ab962ce05a8aaef62f0886cb086e9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2022-01-31T22:49:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T18:16:58.000Z", "avg_line_length": 28.7948717949, "max_line_length": 107, "alphanum_fraction": 0.6317898486, "num_tokens": 520, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673359709795, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.49091646078888823}}
{"text": "/*\n * Copyright (c) 2016-2017, Rafael Ballester-Ripoll\n *                          (Visualization and MultiMedia Lab, University of Zurich),\n *                          rballester@ifi.uzh.ch\n *\n * Licensed under the LGPLv3.0 (https://github.com/rballester/tthresh/blob/master/LICENSE)\n */\n\n#ifndef __TUCKER_HPP__\n#define __TUCKER_HPP__\n\n#include \"memtrace.h\"\n\n#define _USE_MATH_DEFINES\n#include <math.h>\n#include <iostream>\n\n#include \"Slice.hpp\"\n#include <Eigen/Dense>\n\n//using namespace std;\n//using namespace Eigen;\n\nnamespace tthresh\n{\n\n    // Projects an unfolded core M into M_proj using the transformation matrix U.\n    // U is an output parameter and is computed as the HOSVD of the tensor (left singular\n    // vectors of M) and M is compressed using U.transpose().\n    inline void project(Eigen::MatrixXd& M, Eigen::MatrixXd& U, Eigen::MatrixXd& M_proj)\n    {\n        Eigen::SelfAdjointEigenSolver <Eigen::MatrixXd > es(M * M.transpose()); // M*M^T is symmetric -> faster eigenvalue computation\n        Eigen::VectorXd eigenvalues = es.eigenvalues().real();\n        Eigen::MatrixXd U_unsorted = es.eigenvectors().real();\n        uint32_t s = M.rows();\n        U = Eigen::MatrixXd(s, s);\n        // We sort the (eigenvalue, eigenvector) pairs in descending order\n        std::vector < std::pair < double, uint32_t >>eigenvalues_sorted(s);\n        for (uint32_t i = 0; i < s; ++i)\n            eigenvalues_sorted[i] = std::pair < double, uint32_t >(-eigenvalues(i), i);\n        std::sort(eigenvalues_sorted.begin(), eigenvalues_sorted.end());\n        for (uint32_t i = 0; i < s; ++i)\n            U.col(i) = U_unsorted.col(eigenvalues_sorted[i].second);\n        M_proj = U.transpose() * M;\n    }\n\n    // U is an input parameter and M is decompressed using U (sliced as appropriate)\n    inline void unproject(Eigen::MatrixXd& M, Eigen::MatrixXd& U, Eigen::MatrixXd& M_proj, Slice slice) {\n        if (!slice.is_standard()) {\n            if (slice.points[0] < 0 || slice.points[1] > U.rows()) { // TODO put in decompress.hpp\n                std::cout << \"Error: the slicing falls out of the tensor size range\" << std::endl;\n                exit(1);\n            }\n            int8_t sign = (0 < slice.points[2]) - (slice.points[2] < 0);\n            if ((sign < 0 && slice.points[0] < slice.points[1]) || (sign > 0 && slice.points[0] > slice.points[1])) {\n                std::cout << \"Error: unfeasible slicing\" << std::endl;\n                exit(1);\n            }\n            Eigen::MatrixXd convolution = Eigen::MatrixXd::Zero(slice.get_size(), U.rows()); // convolution*U convolves U along the columns\n            const int32_t sliceSize = slice.get_size();\n#pragma omp parallel for\n            for (int32_t i = 0; i < slice.get_size(); ++i) {\n                switch (slice.reduction) {\n                case Downsampling: {\n                    convolution(i, slice.points[0] + i * slice.points[2]) = 1; // Delta kernel\n                    break;\n                }\n                case Box: {\n                    int32_t start = slice.points[0] + i * slice.points[2] - slice.points[2] / 2;\n                    int32_t end = std::max(\n                        std::min(static_cast<Eigen::Index>(slice.points[0] + i * slice.points[2] + (slice.points[2] - slice.points[2] / 2)), U.rows()),\n                        Eigen::Index(0));\n                    double kernel_sum = 1. / abs(end - start);\n                    for (int32_t j = start; sign * j < sign * end; j += sign)\n                        convolution(i, j) = kernel_sum; // Box kernel\n                    break;\n                }\n                case Lanczos: {\n                    double a = 2 * slice.points[2]; // Upscaled Lanczos window\n                    int32_t start = std::max(\n                        std::min(static_cast<long long>(slice.points[0] + i * slice.points[2] - a), U.rows() - 1ll),\n                        0ll); // Kernel support: [-a, a], clamped\n                    int32_t end = std::max(\n                        std::min(static_cast<Eigen::Index>(slice.points[0] + i * slice.points[2] + a + 1), U.rows()),\n                        static_cast<Eigen::Index>(-1ll));\n                    double center = slice.points[0] + i * slice.points[2];\n                    double kernel_sum = 0;\n                    for (int32_t j = start; sign * j < sign * end; j += sign) {\n                        double x = (j - center) / abs(slice.points[2]); // Upscaled x\n                        if (x == 0)\n                            convolution(i, j) = 1;\n                        else\n                            convolution(i, j) = a * sin(M_PI * x) * sin(M_PI * x / a) / (M_PI * M_PI * x * x); // Lanczos 2 kernel\n                        kernel_sum += convolution(i, j);\n                    }\n                    for (int32_t j = start; sign * j < sign * end; j += sign)\n                        convolution(i, j) /= kernel_sum; // Normalize the kernel so that it adds up to 1\n                    break;\n                }\n                }\n            }\n            M_proj = (convolution * U) * M;\n        }\n        else\n            M_proj = U * M;\n    }\n\n    // Reads a tensor in the buffer data of size s, and compresses it.\n    // The factor matrices are output parameters\n    inline void hosvd_compress(double* data, std::vector<Eigen::MatrixXd>& Us,\n        const std::vector<uint32_t>& s, const std::vector<size_t>& sprod, bool verbose)\n    {\n        char n = s.size();\n\n        // First unfolding: special case (elements are already arranged as we want)\n        if (verbose) std::cout << \"\\tUnfold (1)... \" << std::flush;\n        Eigen::MatrixXd M = Eigen::MatrixXd::Map(data, s[0], sprod[n] / s[0]);\n        Eigen::MatrixXd M_proj;\n        if (verbose) std::cout << \"Project (1)...\" << std::flush;\n        project(M, Us[0], M_proj);\n        if (verbose) std::cout << std::endl;\n\n        // Remaining unfoldings: all of them go matrix -> matrix\n        // Input: matrix of size s[dim-1] x (s[0] * ... * s[dim-2] * s[dim] * ... * s[N])\n        // Output: matrix of size s[dim] x (s[0] * ... * s[dim-1] * s[dim+1] * ... * s[N])\n        for (uint8_t dim = 1; dim < n; ++dim) {\n            if (verbose)  std::cout << \"\\tUnfold (\" << dim + 1 << \")... \" << std::flush;\n            M = Eigen::MatrixXd(s[dim], sprod[n] / s[dim]); // dim-th factor matrix\n#pragma omp parallel for\n            for (int64_t j = 0; j < M_proj.cols(); ++j) {\n                uint32_t write_i = (j / sprod[dim - 1]) % s[dim];\n                size_t base_write_j = j % sprod[dim - 1] + j / (sprod[dim - 1] * s[dim]) * sprod[dim];\n                for (int32_t i = 0; i < M_proj.rows(); ++i)\n                    M(write_i, base_write_j + i * sprod[dim - 1]) = M_proj(i, j);\n            }\n            if (verbose)  std::cout << \"\\tProject (\" << dim + 1 << \")... \" << std::flush;\n            project(M, Us[dim], M_proj);\n            if (verbose)  std::cout << std::endl;\n        }\n\n        // We fold back from matrix into ND tensor\n        if (verbose) std::cout << \"\\tFold... \" << std::flush << std::endl;\n#pragma omp parallel for\n        for (int32_t i = 0; i < s[n - 1]; i++)\n            for (size_t j = 0; j < sprod[n - 1]; j++)\n                data[i * sprod[n - 1] + j] = M_proj(i, j);\n    }\n\n    // Reads a tensor in the buffer data of size s, and decompresses it in-place\n    inline void hosvd_decompress(std::vector<double>& data, std::vector<Eigen::MatrixXd>& Us,\n        const std::vector<uint32_t>& r, const std::vector<size_t>& rprod, const std::vector<size_t>& snewprod,\n        bool verbose, std::vector<Slice>& cutout)\n    {\n        size_t n = r.size();\n        if (rprod[n] == 0) { // Extreme case: 0 ranks\n            data = std::vector<double>(snewprod[n], 0); // Produce a 0 reconstruction of the expected size, and leave\n            return;\n        }\n\n        // First unfolding: special case (elements are already arranged as we want)\n        if (verbose) std::cout << \"\\tUnfold (1)... \" << std::flush;\n        Eigen::MatrixXd M = Eigen::MatrixXd::Map(data.data(), r[0], rprod[n] / r[0]);\n        Eigen::MatrixXd M_proj;\n        if (verbose) {\n            std::cout << \"\\tUnproject (\" << 1 << \")\";\n            if (!cutout[0].is_standard())\n                std::cout << \" with cutout \" << cutout[0];\n            std::cout << \"... \" << std::flush;\n        }\n        unproject(M, Us[0], M_proj, cutout[0]);\n        if (verbose) std::cout << std::endl;\n\n        // Remaining unfoldings: all of them go matrix -> matrix\n        // Input: matrix of size s[dim-1] x (s[0] * ... * s[dim-2] * s[dim] * ... * s[N])\n        // Output: matrix of size s[dim] x (s[0] * ... * s[dim-1] * s[dim+1] * ... * s[N])\n        for (uint8_t dim = 1; dim < n; ++dim) {\n            if (verbose) std::cout << \"\\tUnfold (\" << dim + 1 << \")... \" << std::flush;\n            M = Eigen::MatrixXd(r[dim], snewprod[dim] * rprod[n] / rprod[dim + 1]); // dim-th factor matrix\n#pragma omp parallel for\n            for (int64_t j = 0; j < M_proj.cols(); ++j) {\n                uint32_t write_i = (j / snewprod[dim - 1]) % r[dim];\n                size_t base_write_j = j % snewprod[dim - 1] + j / (snewprod[dim - 1] * r[dim]) * snewprod[dim];\n                for (int32_t i = 0; i < M_proj.rows(); ++i)\n                    M(write_i, base_write_j + i * snewprod[dim - 1]) = M_proj(i, j);\n            }\n            if (verbose) {\n                std::cout << \"\\tUnproject (\" << dim + 1 << \")\";\n                if (!cutout[dim].is_standard())\n                    std::cout << \" with cutout \" << cutout[dim];\n                std::cout << \"... \" << std::flush;\n            }\n            unproject(M, Us[dim], M_proj, cutout[dim]);\n            if (verbose) std::cout << std::endl;\n        }\n\n        // We fold back from matrix into ND tensor\n        if (verbose) std::cout << \"\\tFold... \" << std::flush << std::endl;\n        data.resize(snewprod[n]);\n        data.shrink_to_fit();\n#pragma omp parallel for\n        for (ptrdiff_t i = 0; i < snewprod[n]; i++)\n            data[i] = M_proj(i / snewprod[n - 1], i % snewprod[n - 1]);\n    }\n\n}\n\n#endif // TUCKER_HPP\n", "meta": {"hexsha": "5d0548ef2ac27083f2f65cc1fc968d9e2d5af1d5", "size": 10077, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "compression/src/tthresh/tucker.hpp", "max_stars_repo_name": "shamanDevel/fV-SRN", "max_stars_repo_head_hexsha": "966926ee678a0db0f1c67661537c4bb7eec0c56f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2021-12-06T05:08:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T15:11:06.000Z", "max_issues_repo_path": "compression/src/tthresh/tucker.hpp", "max_issues_repo_name": "shamanDevel/fV-SRN", "max_issues_repo_head_hexsha": "966926ee678a0db0f1c67661537c4bb7eec0c56f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-02-07T10:07:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-24T14:13:50.000Z", "max_forks_repo_path": "compression/src/tthresh/tucker.hpp", "max_forks_repo_name": "shamanDevel/fV-SRN", "max_forks_repo_head_hexsha": "966926ee678a0db0f1c67661537c4bb7eec0c56f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2021-12-13T07:02:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-12T15:46:44.000Z", "avg_line_length": 48.4471153846, "max_line_length": 151, "alphanum_fraction": 0.5092785551, "num_tokens": 2733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673133042217, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.49091644709971166}}
{"text": "#include \"mview.h\"\n#include <iostream>\n#include <fstream>\n#include <Eigen/Dense>\n#include <opencv2/core.hpp>\n#include <opencv2/core/eigen.hpp>\n#include <opencv2/imgcodecs.hpp>\n\nstatic std::pair<GrayImage, RgbImage> ReadImageFromFile(std::string);\nstatic float ColourToGray(Eigen::Vector3f rgb);\nstatic RgbImage convertOpenCVToRgb(cv::Mat rgbMat);\n\nauto read_image(CameraParameter cameraParameter) -> Image\n{\n  Image image;\n  image.intrinsics = cameraParameter.intrinsics;\n  image.extrinsics = cameraParameter.extrinsics;\n  std::tie(image.gray_pixels, image.rgb_pixels) = ReadImageFromFile(cameraParameter.filename);\n\n  return image;\n}\n\nstd::pair<GrayImage, RgbImage> ReadImageFromFile(std::string filename) {\n\tstd::cout << filename << std::endl;\n\tcv::Mat rgb_mat = cv::imread(filename, cv::IMREAD_COLOR);\n\trgb_mat.assignTo(rgb_mat, CV_32F);\n\trgb_mat /= 255.;\n\n\tRgbImage rgb_target = convertOpenCVToRgb(rgb_mat);\n\tGrayImage gray_target = rgb_target.unaryExpr([](auto pixel) { return ColourToGray(pixel); }); \n\n\treturn {gray_target, rgb_target};\n}\n\nfloat ColourToGray(Eigen::Vector3f rgb) {\n\tstatic constexpr float GAMMA = 2.2;\n\n\tconst Eigen::Vector3f gamma_correct = Eigen::Array3f(rgb).pow(GAMMA);\n\treturn gamma_correct.dot(Eigen::Vector3f { .2126, .7152, .0722 });\n}\n\nRgbImage convertOpenCVToRgb(const cv::Mat rgbMat){\n    cv::Mat rgb[3];\n    cv::split(rgbMat, rgb);\n\n\tint width = rgbMat.cols;\n\tint height = rgbMat.rows;\n    GrayImage r(height, width), g(height, width), b(height, width);\n\n    cv::cv2eigen(rgb[0], r);\n    cv::cv2eigen(rgb[1], g);\n    cv::cv2eigen(rgb[2], b);\n\tstd::cout << \"converted\\n\";\n\n    RgbImage rgbImage (g.rows(), g.cols());\n\n    for(int row=0;row<g.rows();row++){\n        for(int col=0;col<g.cols();col++){\n            rgbImage(row,col)<<r(row,col),g(row,col),b(row,col);\n        }\n    }\n\n    return rgbImage;\n}\n\n", "meta": {"hexsha": "658904a2efb741c092a75da2ab7b5273b365c2d9", "size": 1841, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "read_image.cpp", "max_stars_repo_name": "temple-reconstruction/mview", "max_stars_repo_head_hexsha": "1440b5716d595c5c4d568fc45dd5afbb6f54dfc7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-09-17T07:39:35.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-24T21:09:27.000Z", "max_issues_repo_path": "read_image.cpp", "max_issues_repo_name": "temple-reconstruction/mview", "max_issues_repo_head_hexsha": "1440b5716d595c5c4d568fc45dd5afbb6f54dfc7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-06-11T19:25:03.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-11T21:51:32.000Z", "max_forks_repo_path": "read_image.cpp", "max_forks_repo_name": "temple-reconstruction/mview", "max_forks_repo_head_hexsha": "1440b5716d595c5c4d568fc45dd5afbb6f54dfc7", "max_forks_repo_licenses": ["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.8939393939, "max_line_length": 95, "alphanum_fraction": 0.6990765888, "num_tokens": 520, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859598, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.49091519361204494}}
{"text": "#pragma once\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/storage.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n\nnamespace tu\n{\n\n  /**\n   * Represents subsets of row and column index sets\n   */\n\n  struct submatrix_indices\n  {\n    typedef boost::numeric::ublas::vector <size_t> vector_type;\n    typedef boost::numeric::ublas::indirect_array <vector_type> indirect_array_type;\n\n    indirect_array_type rows;\n    indirect_array_type columns;\n  };\n\n  /**\n   * Integer matrix\n   */\n\n  typedef boost::numeric::ublas::matrix <long long> integer_matrix;\n\n  /**\n   * Indirect integer matrix\n   */\n\n  typedef boost::numeric::ublas::matrix_indirect <const integer_matrix, submatrix_indices::indirect_array_type> integer_submatrix;\n\n  enum log_level\n  {\n    LOG_QUIET, LOG_PROGRESSIVE, LOG_VERBOSE\n  };\n\n} /* namespace tu */\n", "meta": {"hexsha": "84b782f10d61f98f7957891d5b31aa13a6c42c77", "size": 848, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/cmr/common.hpp", "max_stars_repo_name": "discopt/cmr", "max_stars_repo_head_hexsha": "669811a8c8cbaa12dabd2a1242f0c0ff1aea6e09", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2015-04-13T12:48:09.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-26T11:56:31.000Z", "max_issues_repo_path": "src/cmr/common.hpp", "max_issues_repo_name": "xammy/unimodularity-test", "max_issues_repo_head_hexsha": "669811a8c8cbaa12dabd2a1242f0c0ff1aea6e09", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2021-08-19T09:06:05.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-27T23:18:47.000Z", "max_forks_repo_path": "src/cmr/common.hpp", "max_forks_repo_name": "discopt/cmr", "max_forks_repo_head_hexsha": "669811a8c8cbaa12dabd2a1242f0c0ff1aea6e09", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.6829268293, "max_line_length": 130, "alphanum_fraction": 0.7193396226, "num_tokens": 211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.4909151883543992}}
{"text": "//\n// Created by david on 2019-08-07.\n//\n\n#include <complex.h>\n#undef I\n#include <complex>\n#ifndef lapack_complex_float\n    #define lapack_complex_float std::complex<float>\n#endif\n#ifndef lapack_complex_double\n    #define lapack_complex_double std::complex<double>\n#endif\n\n// complex must be included before lapacke!\n#if __has_include(<mkl_lapacke.h>)\n    #include <mkl_lapacke.h>\n#elif __has_include(<openblas/lapacke.h>)\n    #include <openblas/lapacke.h>\n#else\n    #include <lapacke.h>\n#endif\n\n#include <Eigen/Core>\n#include <general/class_tic_toc.h>\n#include <math/svd.h>\n\nnamespace svd {\n    template<typename Scalar>\n    void print_matrix_lapacke(const Scalar *mat_ptr, long rows, long cols, long dec = 8) {\n        auto A = Eigen::Map<const Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>>(mat_ptr, rows, cols);\n        svd::log->warn(\"Print matrix of dimensions {}x{}\\n\", rows, cols);\n        for(long r = 0; r < A.rows(); r++) {\n            if constexpr(std::is_same_v<Scalar, std::complex<double>>)\n                for(long c = 0; c < A.cols(); c++) fmt::print(\"({1:.{0}f},{2:+.{0}f}) \", dec, std::real(A(r, c)), std::imag(A(r, c)));\n            else\n                for(long c = 0; c < A.cols(); c++) fmt::print(\"{1:.{0}f} \", dec, A(r, c));\n            fmt::print(\"\\n\");\n        }\n    }\n}\n\ntemplate<typename Scalar>\nstd::tuple<svd::solver::MatrixType<Scalar>, svd::solver::VectorType<Scalar>, svd::solver::MatrixType<Scalar>, long>\n    svd::solver::do_svd_lapacke(const Scalar *mat_ptr, long rows, long cols, std::optional<long> rank_max) {\n    // Setup useful sizes\n    int rowsA = static_cast<int>(rows);\n    int colsA = static_cast<int>(cols);\n    int sizeS = std::min(rowsA, colsA);\n    if(not rank_max.has_value()) rank_max = std::min(rows, cols);\n\n    // Setup the SVD solver\n    bool use_jacobi = static_cast<size_t>(sizeS) < switchsize;\n    if(use_jacobi and rows < cols) {\n        // The jacobi routine needs a tall matrix\n        t_adj->tic();\n        svd::log->trace(\"Transposing {}x{} into tall matrix {}x{}\", rows, cols, cols, rows);\n        MatrixType<Scalar> A = Eigen::Map<const MatrixType<Scalar>>(mat_ptr, rows, cols);\n        A.adjointInPlace(); // Adjoint directly on a map seems to give a bug?\n        // Sanity checks\n        if(A.rows() <= 0) throw std::runtime_error(\"SVD error: rows() == 0\");\n        if(A.cols() <= 0) throw std::runtime_error(\"SVD error: cols() == 0\");\n\n        t_adj->toc();\n        auto [U, S, VT, rank] = do_svd_lapacke(A.data(), A.rows(), A.cols(), std::max(A.rows(), A.cols()));\n        long max_size         = std::min(S.size(), rank_max.value());\n        rank                  = (S.head(max_size).real().array() >= threshold).count();\n        if(U.rows() != A.rows()) throw std::logic_error(fmt::format(\"U.rows():{} != A.rows():{}\", U.rows(), A.rows()));\n        if(VT.cols() != A.cols()) throw std::logic_error(fmt::format(\"VT.cols():{} != A.cols():{}\", VT.cols(), A.cols()));\n        return std::make_tuple(VT.adjoint().leftCols(rank), S.head(rank), U.adjoint().topRows(rank), rank);\n    }\n\n    // Sanity checks\n    if(rows <= 0) throw std::runtime_error(\"SVD error: rows() == 0\");\n    if(cols <= 0) throw std::runtime_error(\"SVD error: cols() == 0\");\n\n    MatrixType<Scalar> A = Eigen::Map<const MatrixType<Scalar>>(mat_ptr, rows, cols);\n    if(not A.allFinite()) {\n        print_matrix_lapacke(mat_ptr, rows, cols);\n        throw std::runtime_error(\"SVD error: matrix has inf's or nan's\");\n    }\n    if(A.isZero(1e-12)) {\n        print_matrix_lapacke(mat_ptr, rows, cols, 16);\n        throw std::runtime_error(\"SVD error: matrix is all zeros\");\n    }\n\n    svd::log->trace(\"Starting SVD with lapacke\");\n\n    int info   = 0;\n    int rowsU  = rowsA;\n    int colsU  = std::min(rowsA, colsA);\n    int rowsVT = std::min(rowsA, colsA);\n    int colsVT = colsA;\n    int rowsV  = colsA;\n    int colsV  = std::min(rowsA, colsA);\n    int lda    = rowsA;\n    int ldu    = rowsU;\n    int ldvt   = rowsVT;\n    int ldv    = rowsV;\n\n    MatrixType<Scalar> U;\n    VectorType<double> S;\n    MatrixType<Scalar> VT;\n\n    if constexpr(std::is_same<Scalar, double>::value) {\n        if(use_jacobi) {\n            svd::log->debug(\"Running Lapacke Jacobi SVD with threshold {:.4e} | switchsize {} | size {}\", threshold, switchsize, sizeS);\n            // http://www.netlib.org/lapack/explore-html/d1/d7e/group__double_g_esing_ga8767bfcf983f8dc6ef2842029ab25599.html#ga8767bfcf983f8dc6ef2842029ab25599\n            // For this routine we need rows > cols\n            t_wrk->tic();\n            int                 lwork = std::max(6, rowsA + colsA);\n            std::vector<Scalar> work(static_cast<size_t>(lwork));\n            //            work.setConstant(0);\n            //            work[0] = 1;\n            S.resize(sizeS);\n            MatrixType<Scalar> V(rowsV, colsV); // Local matrix gets transposed after computation\n            t_wrk->toc();\n\n            svd::log->trace(\"Running dgejsv\");\n            t_jac->tic();\n            info = LAPACKE_dgesvj_work(LAPACK_COL_MAJOR, 'G', 'U', 'V', rowsA, colsA, A.data(), lda, S.data(), ldv, V.data(), ldv, work.data(), lwork);\n            t_jac->toc();\n            if(info < 0) throw std::runtime_error(fmt::format(\"Lapacke SVD error: parameter {} is invalid\", -info));\n            long max_size = std::min(S.size(), rank_max.value());\n            long rank     = (S.head(max_size).array() >= threshold).count();\n            U             = A.leftCols(rank);\n            VT            = V.adjoint().topRows(rank);\n        } else if(use_bdc) {\n            svd::log->debug(\"Running Lapacke BDC SVD with threshold {:.4e} | switchsize {} | size {}\", threshold, switchsize, sizeS);\n            t_wrk->tic();\n            int                 liwork = std::max(1, 8 * std::min(rowsA, colsA));\n            std::vector<Scalar> work(1);\n            std::vector<int>    iwork(static_cast<size_t>(liwork));\n\n            U.resize(rowsU, colsU);\n            S.resize(sizeS);\n            VT.resize(rowsVT, colsVT);\n\n            svd::log->trace(\"Querying dgesvd\");\n            info = LAPACKE_dgesdd_work(LAPACK_COL_MAJOR, 'S', rowsA, colsA, A.data(), lda, S.data(), U.data(), ldu, VT.data(), ldvt, work.data(), -1,\n                                       iwork.data());\n            if(info < 0) throw std::runtime_error(fmt::format(\"Lapacke SVD error: parameter {} is invalid\", -info));\n\n            int lwork = static_cast<int>(work[0]);\n            work.resize(static_cast<size_t>(lwork));\n            t_wrk->toc();\n\n            svd::log->trace(\"Running dgesvd\");\n            t_svd->tic();\n            info = LAPACKE_dgesdd_work(LAPACK_COL_MAJOR, 'S', rowsA, colsA, A.data(), lda, S.data(), U.data(), ldu, VT.data(), ldvt, work.data(), lwork,\n                                       iwork.data());\n            t_svd->toc();\n            if(info < 0) throw std::runtime_error(fmt::format(\"Lapacke SVD error: parameter {} is invalid\", -info));\n        } else {\n            svd::log->debug(\"Running Lapacke SVD with threshold {:.4e} | switchsize {} | size {}\", threshold, switchsize, sizeS);\n            std::vector<Scalar> work(1);\n\n            U.resize(rowsU, colsU);\n            S.resize(sizeS);\n            VT.resize(rowsVT, colsVT);\n\n            svd::log->trace(\"Querying dgesvd\");\n            info = LAPACKE_dgesvd_work(LAPACK_COL_MAJOR, 'S', 'S', rowsA, colsA, A.data(), lda, S.data(), U.data(), ldu, VT.data(), ldvt, work.data(), -1);\n            if(info < 0) throw std::runtime_error(fmt::format(\"Lapacke SVD error: parameter {} is invalid\", -info));\n\n            int lwork = static_cast<int>(work[0]);\n            work.resize(static_cast<size_t>(lwork));\n\n            svd::log->trace(\"Running dgesvd\");\n            t_svd->tic();\n            info = LAPACKE_dgesvd_work(LAPACK_COL_MAJOR, 'S', 'S', rowsA, colsA, A.data(), lda, S.data(), U.data(), ldu, VT.data(), ldvt, work.data(), lwork);\n            t_svd->toc();\n            if(info < 0) throw std::runtime_error(fmt::format(\"Lapacke SVD error: parameter {} is invalid\", -info));\n        }\n    }\n    if constexpr(std::is_same<Scalar, std::complex<double>>::value) {\n        if(use_jacobi) {\n            svd::log->debug(\"Running Lapacke Jacobi SVD with threshold {:.4e} | switchsize {} | size {}\", threshold, switchsize, sizeS);\n            t_wrk->tic();\n            std::vector<Scalar> cwork(1);\n            std::vector<double> rwork(1);\n            std::vector<int> iwork(1);\n\n            S.resize(sizeS);\n            U.resize(rowsU, colsU); // Local matrix gets transposed after computation\n            MatrixType<Scalar> V(rowsV, colsV); // Local matrix gets transposed after computation\n\n            auto Ap = reinterpret_cast<lapack_complex_double *>(A.data());\n            auto Vp = reinterpret_cast<lapack_complex_double *>(V.data());\n            auto pcwork = reinterpret_cast<lapack_complex_double *>(cwork.data());\n            rwork = {1.0};\n            svd::log->trace(\"Querying zgesvj\");\n            info = LAPACKE_zgesvj_work(LAPACK_COL_MAJOR, 'G', 'U', 'V', rowsA, colsA, Ap, lda, S.data(), ldv, Vp, ldv, pcwork, -1, rwork.data(), -1);\n\n            if(info < 0) throw std::runtime_error(fmt::format(\"Lapacke SVD error: parameter {} is invalid\", -info));\n\n            int lcwork  = static_cast<int>(std::real(cwork[0]));\n            int lrwork  = static_cast<int>(rwork[0]);\n            cwork.resize(static_cast<size_t>(lcwork));\n            rwork.resize(static_cast<size_t>(lrwork));\n            pcwork = reinterpret_cast<lapack_complex_double *>(cwork.data());\n            t_wrk->toc();\n\n            svd::log->trace(\"Running zgesvj | cwork {} | rwork {}\", lcwork, lrwork);\n            t_jac->tic();\n            info = LAPACKE_zgesvj_work(LAPACK_COL_MAJOR, 'G', 'U', 'V', rowsA, colsA, Ap, lda, S.data(), ldv, Vp, ldv, pcwork, lcwork, rwork.data(), lrwork);\n            t_jac->toc();\n            if(info < 0) throw std::runtime_error(fmt::format(\"Lapacke SVD error: parameter {} is invalid\", -info));\n            long max_size = std::min(S.size(), rank_max.value());\n            long rank     = (S.head(max_size).array() >= threshold).count();\n            U             = A.leftCols(rank);\n            VT            = V.adjoint().topRows(rank);\n            svd::log->trace(\"info {} | rwork {} {} {} {} | rank {}\", info, rwork[0], rwork[1], rwork[2], rwork[3], rank );\n\n\n        } else if(use_bdc) {\n            svd::log->debug(\"Running Lapacke BDC SVD with threshold {:.4e} | switchsize {} | size {}\", threshold, switchsize, sizeS);\n            t_wrk->tic();\n            int                 mx     = std::max(rowsA, colsA);\n            int                 mn     = std::min(rowsA, colsA);\n            int                 lrwork = std::max(1, mn * std::max(5 * mn + 7, 2 * mx + 2 * mn + 1));\n            int                 liwork = std::max(1, 8 * std::min(rowsA, colsA));\n            std::vector<int>    iwork(static_cast<size_t>(liwork));\n            std::vector<double> rwork(static_cast<size_t>(lrwork));\n            std::vector<Scalar> work(1);\n\n            U.resize(rowsU, colsU);\n            S.resize(sizeS);\n            VT.resize(rowsVT, colsVT);\n\n            auto Ap  = reinterpret_cast<lapack_complex_double *>(A.data());\n            auto Up  = reinterpret_cast<lapack_complex_double *>(U.data());\n            auto VTp = reinterpret_cast<lapack_complex_double *>(VT.data());\n            auto Wp  = reinterpret_cast<lapack_complex_double *>(work.data());\n\n            svd::log->trace(\"Querying zgesdd\");\n            info = LAPACKE_zgesdd_work(LAPACK_COL_MAJOR, 'S', rowsA, colsA, Ap, lda, S.data(), Up, ldu, VTp, ldvt, Wp, -1, rwork.data(), iwork.data());\n            if(info < 0) throw std::runtime_error(fmt::format(\"Lapacke SVD error: parameter {} is invalid\", -info));\n\n            int lwork = static_cast<int>(std::real(work[0]));\n            work.resize(static_cast<size_t>(lwork));\n            Wp = reinterpret_cast<lapack_complex_double *>(work.data()); // Update the pointer if reallocated\n            t_wrk->toc();\n            svd::log->trace(\"Running zgesdd\");\n            t_svd->tic();\n            info = LAPACKE_zgesdd_work(LAPACK_COL_MAJOR, 'S', rowsA, colsA, Ap, lda, S.data(), Up, ldu, VTp, ldvt, Wp, lwork, rwork.data(), iwork.data());\n            t_svd->toc();\n            if(info < 0) throw std::runtime_error(fmt::format(\"Lapacke SVD error: parameter {} is invalid\", -info));\n        } else {\n            svd::log->debug(\"Running Lapacke SVD with threshold {:.4e} | switchsize {} | size {}\", threshold, switchsize, sizeS);\n            t_wrk->tic();\n            int                 lrwork = 5 * std::min(rowsA, colsA);\n            std::vector<Scalar> work(1);\n            std::vector<double> rwork(static_cast<size_t>(lrwork));\n\n            U.resize(rowsU, colsU);\n            S.resize(sizeS);\n            VT.resize(rowsVT, colsVT);\n\n            auto Ap  = reinterpret_cast<lapack_complex_double *>(A.data());\n            auto Up  = reinterpret_cast<lapack_complex_double *>(U.data());\n            auto VTp = reinterpret_cast<lapack_complex_double *>(VT.data());\n            auto Wp  = reinterpret_cast<lapack_complex_double *>(work.data());\n\n            svd::log->trace(\"Querying zgesvd\");\n            info = LAPACKE_zgesvd_work(LAPACK_COL_MAJOR, 'S', 'S', rowsA, colsA, Ap, lda, S.data(), Up, ldu, VTp, ldvt, Wp, -1, rwork.data());\n            if(info < 0) throw std::runtime_error(fmt::format(\"Lapacke SVD error: parameter {} is invalid\", -info));\n\n            int lwork = static_cast<int>(std::real(work[0]));\n            work.resize(static_cast<size_t>(lwork));\n            Wp = reinterpret_cast<lapack_complex_double *>(work.data()); // Update the pointer if reallocated\n            t_wrk->toc();\n\n            svd::log->trace(\"Running zgesvd\");\n            t_svd->tic();\n            info = LAPACKE_zgesvd_work(LAPACK_COL_MAJOR, 'S', 'S', rowsA, colsA, Ap, lda, S.data(), Up, ldu, VTp, ldvt, Wp, lwork, rwork.data());\n            t_svd->toc();\n            if(info < 0) throw std::runtime_error(fmt::format(\"Lapacke SVD error: parameter {} is invalid\", -info));\n        }\n    }\n    svd::log->trace(\"Truncating singular values\");\n    if(count) count.value()++;\n    long max_size = std::min(S.size(), rank_max.value());\n    long rank     = (S.head(max_size).array() >= threshold).count();\n    if(rank == S.size()) {\n        truncation_error = 0;\n    } else {\n        truncation_error = S.tail(S.size() - rank).norm();\n    }\n\n    if(rank <= 0 or not U.leftCols(rank).allFinite() or not S.head(rank).allFinite() or not VT.topRows(rank).allFinite()) {\n        if(not A.allFinite()) {\n            print_matrix_lapacke(A.data(), A.rows(), A.cols());\n            svd::log->critical(\"SVD error: matrix has inf's or nan's\");\n        }\n        if(A.isZero(1e-12)) {\n            print_matrix_lapacke(A.data(), A.rows(), A.cols(), 16);\n            svd::log->critical(\"SVD error: matrix is all zeros\");\n        }\n\n        throw std::runtime_error(fmt::format(\"Lapacke SVD error \\n\"\n                                             \"  svd_threshold    = {:.4e}\\n\"\n                                             \"  Truncation Error = {:.4e}\\n\"\n                                             \"  Rank             = {}\\n\"\n                                             \"  Dims             = ({}, {})\\n\"\n                                             \"  A all finite     : {}\\n\"\n                                             \"  U all finite     : {}\\n\"\n                                             \"  S all finite     : {}\\n\"\n                                             \"  V all finite     : {}\\n\",\n                                             \"  Lapacke info     : {}\\n\",\n                                             threshold, truncation_error, rank, rows, cols, A.allFinite(), U.leftCols(rank).allFinite(),\n                                             S.head(rank).allFinite(), VT.topRows(rank).allFinite(), info));\n    }\n    svd::log->trace(\"SVD with lapacke finished successfully. info = {}\", info);\n    return std::make_tuple(U.leftCols(rank), S.head(rank), VT.topRows(rank), rank);\n}\n\n//! \\relates svd::class_SVD\n//! \\brief force instantiation of do_svd_lapacke for type 'double'\ntemplate std::tuple<svd::solver::MatrixType<double>, svd::solver::VectorType<double>, svd::solver::MatrixType<double>, long>\n    svd::solver::do_svd_lapacke(const double *, long, long, std::optional<long>);\n\nusing cplx = std::complex<double>;\n//! \\relates svd::class_SVD\n//! \\brief force instantiation of do_svd_lapacke for type 'std::complex<double>'\ntemplate std::tuple<svd::solver::MatrixType<cplx>, svd::solver::VectorType<cplx>, svd::solver::MatrixType<cplx>, long>\n    svd::solver::do_svd_lapacke(const cplx *, long, long, std::optional<long>);\n", "meta": {"hexsha": "5564002d18963dc31d4225f61770f9c7db858ac4", "size": 16687, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/math/svd/svd_lapacke.cpp", "max_stars_repo_name": "DavidAce/DMRG", "max_stars_repo_head_hexsha": "e465fd903eade1bf6aa74daacd8e2cf02e9e9332", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2017-10-31T22:50:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T15:45:27.000Z", "max_issues_repo_path": "source/math/svd/svd_lapacke.cpp", "max_issues_repo_name": "DavidAce/DMRG", "max_issues_repo_head_hexsha": "e465fd903eade1bf6aa74daacd8e2cf02e9e9332", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/math/svd/svd_lapacke.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": 50.875, "max_line_length": 160, "alphanum_fraction": 0.5549229939, "num_tokens": 4530, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.766293653760418, "lm_q2_score": 0.6406358479787609, "lm_q1q2_score": 0.4909151846775484}}
{"text": "#pragma once\n\n#include <ctime>\n#include <cassert>\n#include <cmath>\n#include <utility>\n#include <vector>\n#include <algorithm>\n#include <cstdlib>\n#include <memory>\n#include <iostream>\n\n#include <Eigen/Dense>\n\n#include <opencv2/opencv.hpp>\n#include <opencv2/core/eigen.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <cv_bridge/cv_bridge.h>\n\n#include <pcl/point_cloud.h>\n#include <pcl/point_types.h>\n#include <pcl/filters/voxel_grid.h>\n#include <pcl_conversions/pcl_conversions.h>\n\n#include \"scancontext/nanoflann.hpp\"\n#include \"scancontext/KDTreeVectorOfVectorsAdaptor.hpp\"\n\n#include \"scancontext/tictoc.hpp\"\n\nusing namespace Eigen;\nusing namespace nanoflann;\n\nusing std::cout;\nusing std::endl;\nusing std::make_pair;\n\nusing std::atan2;\nusing std::cos;\nusing std::sin;\n\nusing SCPointType = pcl::PointXYZI;  // using xyz only. but a user can exchange the original bin encoding function (i.e., max hegiht) to max intensity (for detail, refer 20 ICRA Intensity Scan Context)\nusing KeyMat = std::vector<std::vector<float> >;\nusing InvKeyTree = KDTreeVectorOfVectorsAdaptor<KeyMat, float>;\n\n// namespace SC2\n// {\n\nvoid coreImportTest(void);\n\n// sc param-independent helper functions\nfloat xy2theta(const float &_x, const float &_y);\nMatrixXd circshift(MatrixXd &_mat, int _num_shift);\nstd::vector<float> eig2stdvec(MatrixXd _eigmat);\n\nclass SCManager {\npublic:\n  SCManager() = default;  // reserving data space (of std::vector) could be considered. but the descriptor is lightweight so don't care.\n\n  Eigen::MatrixXd makeScancontext(pcl::PointCloud<SCPointType> &_scan_down);\n  Eigen::MatrixXd makeRingkeyFromScancontext(Eigen::MatrixXd &_desc);\n  Eigen::MatrixXd makeSectorkeyFromScancontext(Eigen::MatrixXd &_desc);\n\n  int fastAlignUsingVkey(MatrixXd &_vkey1, MatrixXd &_vkey2);\n  double distDirectSC(MatrixXd &_sc1, MatrixXd &_sc2);                            // \"d\" (eq 5) in the original paper (IROS 18)\n  std::pair<double, int> distanceBtnScanContext(MatrixXd &_sc1, MatrixXd &_sc2);  // \"D\" (eq 6) in the original paper (IROS 18)\n\n  // User-side API\n  void makeAndSaveScancontextAndKeys(pcl::PointCloud<SCPointType> &_scan_down);\n  std::pair<int, float> detectLoopClosureID(void);  // int: nearest node index, float: relative yaw\n\npublic:\n  // hyper parameters ()\n  const double LIDAR_HEIGHT = 2.0;  // lidar height : add this for simply directly using lidar scan in the lidar local coord (not robot base coord) / if you use robot-coord-transformed lidar scans, just set this as 0.\n\n  const int PC_NUM_RING = 20;         // 20 in the original paper (IROS 18)\n  const int PC_NUM_SECTOR = 60;       // 60 in the original paper (IROS 18)\n  const double PC_MAX_RADIUS = 80.0;  // 80 meter max in the original paper (IROS 18)\n  const double PC_UNIT_SECTORANGLE = 360.0 / double(PC_NUM_SECTOR);\n  const double PC_UNIT_RINGGAP = PC_MAX_RADIUS / double(PC_NUM_RING);\n\n  // tree\n  // *Original\n  // const int    NUM_EXCLUDE_RECENT = 50; // simply just keyframe gap, but node position distance-based exclusion is ok.\n  // const int    NUM_CANDIDATES_FROM_TREE = 10; // 10 is enough. (refer the IROS 18 paper)\n  // *scancontext\n  const int NUM_EXCLUDE_RECENT = 1;         // simply just keyframe gap, but node position distance-based exclusion is ok.\n  const int NUM_CANDIDATES_FROM_TREE = 10;  // 10 is enough. (refer the IROS 18 paper)\n\n  // loop thres\n  // *Original\n  // const double SEARCH_RATIO = 0.1; // for fast comparison, no Brute-force, but search 10 % is okay. // not was in the original conf paper, but improved ver.\n  // const double SC_DIST_THRES = 0.13; // empirically 0.1-0.2 is fine (rare false-alarms) for 20x60 polar context (but for 0.15 <, DCS or ICP fit score check (e.g., in LeGO-LOAM) should be required for robustness)\n  // // const double SC_DIST_THRES = 0.5; // 0.4-0.6 is good choice for using with robust kernel (e.g., Cauchy, DCS) + icp fitness threshold / if not, recommend 0.1-0.15\n  // *scancontext\n  const double SEARCH_RATIO = 0.1;   // for fast comparison, no Brute-force, but search 10 % is okay. // not was in the original conf paper, but improved ver.\n  const double SC_DIST_THRES = 0.2;  // empirically 0.1-0.2 is fine (rare false-alarms) for 20x60 polar context (but for 0.15 <, DCS or ICP fit score check (e.g., in LeGO-LOAM) should be required for robustness)\n  // const double SC_DIST_THRES = 0.5; // 0.4-0.6 is good choice for using with robust kernel (e.g., Cauchy, DCS) + icp fitness threshold / if not, recommend 0.1-0.15\n\n  // config\n  // *Original\n  // const int    TREE_MAKING_PERIOD_ = 50; // i.e., remaking tree frequency, to avoid non-mandatory every remaking, to save time cost / if you want to find a very recent revisits use small value of it (it is enough fast ~ 5-50ms wrt N.).\n  // int          tree_making_period_conter = 0;\n  // *scancontext\n  const int TREE_MAKING_PERIOD_ = 2;  // i.e., remaking tree frequency, to avoid non-mandatory every remaking, to save time cost / if you want to find a very recent revisits use small value of it (it is enough fast ~ 5-50ms wrt N.).\n  int tree_making_period_conter = 0;\n\n  // data\n  std::vector<double> polarcontexts_timestamp_;  // optional.\n  std::vector<Eigen::MatrixXd> polarcontexts_;\n  std::vector<Eigen::MatrixXd> polarcontext_invkeys_;\n  std::vector<Eigen::MatrixXd> polarcontext_vkeys_;\n\n  KeyMat polarcontext_invkeys_mat_;\n  KeyMat polarcontext_invkeys_to_search_;\n  std::unique_ptr<InvKeyTree> polarcontext_tree_;\n\n};  // SCManager\n\n// } // namespace SC2\n", "meta": {"hexsha": "0277d1fd9f240919b7197ff5130d67022438c802", "size": 5464, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/scancontext/Scancontext.hpp", "max_stars_repo_name": "zxl19/hdl_graph_slam", "max_stars_repo_head_hexsha": "a7f1ada98628d8320682445f7eeca7c31ef4642f", "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/scancontext/Scancontext.hpp", "max_issues_repo_name": "zxl19/hdl_graph_slam", "max_issues_repo_head_hexsha": "a7f1ada98628d8320682445f7eeca7c31ef4642f", "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/scancontext/Scancontext.hpp", "max_forks_repo_name": "zxl19/hdl_graph_slam", "max_forks_repo_head_hexsha": "a7f1ada98628d8320682445f7eeca7c31ef4642f", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.5333333333, "max_line_length": 238, "alphanum_fraction": 0.7271229868, "num_tokens": 1570, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.49091518151595814}}
{"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\n//non linear NeoHookean material model\nnamespace polyfem\n{\n\tclass NeoHookeanElasticity\n\t{\n\tpublic:\n\t\tNeoHookeanElasticity();\n\n\t\t//energy, gradient, and hessian used in newton method\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\t//rhs for fabbricated solution, compute with automatic sympy code\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\t//von mises and stress tensor\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\t//sets material params\n\t\tvoid set_parameters(const json &params);\n\t\tvoid init_multimaterial(const bool is_volume, const Eigen::MatrixXd &Es, const Eigen::MatrixXd &nus);\n\n\tprivate:\n\t\tint size_ = 2;\n\n\t\tLameParameters params_;\n\n\t\t//utulity function that computes energy, the template is used for double, DScalar1, and DScalar2 in energy, gradient and hessian\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": "bcda592e0da2582ce16f7d15056830a49af16e52", "size": 2376, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/assembler/NeoHookeanElasticity.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/NeoHookeanElasticity.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/NeoHookeanElasticity.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": 44.0, "max_line_length": 281, "alphanum_fraction": 0.7794612795, "num_tokens": 618, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6406358479787609, "lm_q1q2_score": 0.49091517783910776}}
{"text": "/**\n * @file    linearization.cpp\n * @brief   Tools to linearize a nonlinear factor graph to linear system Ax = b\n * @author  Jing Dong\n * @date    Oct 15, 2017\n */\n\n#include <minisam/config.h>\n\n#include <minisam/nonlinear/linearization.h>\n\n#include <minisam/core/Factor.h>\n#include <minisam/core/FactorGraph.h>\n#include <minisam/core/VariableOrdering.h>\n#include <minisam/core/Variables.h>\n#include <minisam/nonlinear/SparsityPattern.h>\n\n#include <Eigen/Core>\n#include <Eigen/SparseCore>\n\n#ifdef MINISAM_WITH_MULTI_THREADS\n#include <mutex>\n#include <thread>\n#endif\n\nusing namespace std;\n\nnamespace minisam {\n\n/* ************************************************************************** */\nvoid linearzationJacobian(const FactorGraph& graph, const Variables& variables,\n                          Eigen::SparseMatrix<double>& A, Eigen::VectorXd& b) {\n  linearzationJacobian(graph, variables, A, b,\n                       variables.defaultVariableOrdering());\n}\n\n/* ************************************************************************** */\nvoid linearzationJacobian(const FactorGraph& graph, const Variables& variables,\n                          Eigen::SparseMatrix<double>& A, Eigen::VectorXd& b,\n                          const VariableOrdering& ordering) {\n  internal::JacobianSparsityPattern pattern =\n      internal::constructJacobianSparsity(graph, variables, ordering);\n  internal::linearzationJacobian(graph, variables, pattern, A, b);\n}\n\n/* ************************************************************************** */\nvoid linearzationFullHessian(const FactorGraph& graph,\n                             const Variables& variables,\n                             Eigen::SparseMatrix<double>& AtA,\n                             Eigen::VectorXd& Atb) {\n  linearzationFullHessian(graph, variables, AtA, Atb,\n                          variables.defaultVariableOrdering());\n}\n\n/* ************************************************************************** */\nvoid linearzationFullHessian(const FactorGraph& graph,\n                             const Variables& variables,\n                             Eigen::SparseMatrix<double>& AtA,\n                             Eigen::VectorXd& Atb,\n                             const VariableOrdering& ordering) {\n  internal::LowerHessianSparsityPattern pattern =\n      internal::constructLowerHessianSparsity(graph, variables, ordering);\n  internal::linearzationFullHessian(graph, variables, pattern, AtA, Atb);\n}\n\nnamespace internal {\n\n/* ************************************************************************** */\nvoid linearzationJacobian(const FactorGraph& factors, const Variables& values,\n                          const JacobianSparsityPattern& sparsity,\n                          Eigen::SparseMatrix<double>& A, Eigen::VectorXd& b) {\n  // init A and b\n  A = Eigen::SparseMatrix<double>(sparsity.A_rows, sparsity.A_cols);\n  b = Eigen::VectorXd(sparsity.A_rows);\n\n  // pre-allocate A by number of non-zeros each col\n  A.reserve(sparsity.nnz_cols);\n\n  // accumulator for row\n  int err_row_counter = 0;\n\n  for (size_t f_idx = 0; f_idx < factors.size(); f_idx++) {\n    const std::shared_ptr<Factor>& f = factors.factors()[f_idx];\n\n    // get var index of factors\n    vector<int> jacobian_col;\n    jacobian_col.reserve(f->keys().size());\n\n    for (auto pkey = f->keys().begin(); pkey != f->keys().end(); pkey++) {\n      size_t key_idx = sparsity.var_ordering.searchKey(*pkey);\n      jacobian_col.push_back(sparsity.var_col[key_idx]);\n    }\n\n    // whiten err and jacobians\n    pair<vector<Eigen::MatrixXd>, Eigen::VectorXd> wht_Js_err =\n        f->weightedJacobiansError(values);\n\n    const vector<Eigen::MatrixXd>& wht_Js = wht_Js_err.first;\n    b.segment(err_row_counter, f->dim()) = -wht_Js_err.second;\n\n    // update jacobian matrix\n    for (size_t j_idx = 0; j_idx < wht_Js.size(); j_idx++) {\n      // Eigen doesn't allow block write operation\n      // write element-wise\n      // scan by row for better CPU cache hit\n      for (int j = 0; j < wht_Js[j_idx].cols(); j++) {\n        for (int i = 0; i < wht_Js[j_idx].rows(); i++) {\n          A.insert(i + err_row_counter, j + jacobian_col[j_idx]) =\n              wht_Js[j_idx](i, j);\n        }\n      }\n    }\n\n    // update row counter\n    err_row_counter += (int)f->dim();\n  }\n\n  // always output compressed matrix\n  A.makeCompressed();\n}\n\nnamespace {\n/* ************************************************************************** */\n// data struct for sort key in\nEigen::MatrixXd stackMatrixCol_(const std::vector<Eigen::MatrixXd>& mats) {\n  assert(mats.size() > 0);\n  int H_stack_cols = 0;\n  for (const auto& H : mats) {\n    H_stack_cols += static_cast<int>(H.cols());\n  }\n  const int rows = static_cast<int>(mats[0].rows());\n  Eigen::MatrixXd H_stack(rows, H_stack_cols);\n  H_stack_cols = 0;\n  for (const auto& H : mats) {\n    assert(H.rows() == rows);\n    H_stack.block(0, H_stack_cols, rows, H.cols()) = H;\n    H_stack_cols += H.cols();\n  }\n  return H_stack;\n}\n\n/* ************************************************************************** */\n#ifdef MINISAM_WITH_MULTI_THREADS\nvoid linearzationLowerHessianSingleFactor_(\n    const std::shared_ptr<Factor>& f, const Variables& values,\n    const LowerHessianSparsityPattern& sparsity,\n    Eigen::SparseMatrix<double>& AtA, Eigen::VectorXd& Atb, std::mutex& mutex_A,\n    std::mutex& mutex_b) {\n#else\nvoid linearzationLowerHessianSingleFactor_(\n    const std::shared_ptr<Factor>& f, const Variables& values,\n    const LowerHessianSparsityPattern& sparsity,\n    Eigen::SparseMatrix<double>& AtA, Eigen::VectorXd& Atb) {\n#endif\n\n  // whiten err and jacobians\n  vector<size_t> var_idx, jacobian_col, jacobian_col_local;\n  var_idx.reserve(f->size());\n  jacobian_col.reserve(f->size());\n  jacobian_col_local.reserve(f->size());\n  size_t local_col = 0;\n  for (Key vkey : f->keys()) {\n    // A col start index\n    size_t key_idx = sparsity.var_ordering.searchKeyUnsafe(vkey);\n    var_idx.push_back(key_idx);\n    jacobian_col.push_back(sparsity.var_col[key_idx]);\n    jacobian_col_local.push_back(local_col);\n    local_col += sparsity.var_dim[key_idx];\n  }\n\n  const pair<vector<Eigen::MatrixXd>, Eigen::VectorXd> wht_Js_err =\n      f->weightedJacobiansError(values);\n\n  const vector<Eigen::MatrixXd>& wht_Js = wht_Js_err.first;\n  const Eigen::VectorXd& wht_err = wht_Js_err.second;\n\n  Eigen::MatrixXd stackJ = stackMatrixCol_(wht_Js);\n\n  Eigen::MatrixXd stackJtJ(stackJ.cols(), stackJ.cols());\n\n  // adaptive multiply for better speed\n  if (stackJ.cols() > 12) {\n    // stackJtJ.setZero();\n    memset(stackJtJ.data(), 0, stackJ.cols() * stackJ.cols() * sizeof(double));\n    stackJtJ.selfadjointView<Eigen::Lower>().rankUpdate(stackJ.transpose());\n  } else {\n    stackJtJ.noalias() = stackJ.transpose() * stackJ;\n  }\n\n  const Eigen::VectorXd stackJtb = stackJ.transpose() * wht_err;\n\n#ifdef MINISAM_WITH_MULTI_THREADS\n  mutex_b.lock();\n#endif\n\n  for (size_t j_idx = 0; j_idx < wht_Js.size(); j_idx++) {\n    Atb.segment(jacobian_col[j_idx], wht_Js[j_idx].cols()) -=\n        stackJtb.segment(jacobian_col_local[j_idx], wht_Js[j_idx].cols());\n  }\n\n#ifdef MINISAM_WITH_MULTI_THREADS\n  mutex_b.unlock();\n  mutex_A.lock();\n#endif\n\n  for (size_t j_idx = 0; j_idx < wht_Js.size(); j_idx++) {\n    // scan by row\n    size_t nnz_AtA_vars_accum_var = sparsity.nnz_AtA_vars_accum[var_idx[j_idx]];\n    double* value_ptr = AtA.valuePtr() + nnz_AtA_vars_accum_var;\n\n    for (int j = 0; j < wht_Js[j_idx].cols(); j++) {\n      for (int i = j; i < wht_Js[j_idx].cols(); i++) {\n        *(value_ptr++) += stackJtJ(jacobian_col_local[j_idx] + i,\n                                   jacobian_col_local[j_idx] + j);\n      }\n      value_ptr += (sparsity.nnz_AtA_cols[jacobian_col[j_idx] + j] -\n                    wht_Js[j_idx].cols() + j);\n    }\n  }\n\n#ifdef MINISAM_WITH_MULTI_THREADS\n  mutex_A.unlock();\n#endif\n\n  // update lower non-diag hessian blocks\n  for (size_t j1_idx = 0; j1_idx < wht_Js.size(); j1_idx++) {\n    for (size_t j2_idx = 0; j2_idx < wht_Js.size(); j2_idx++) {\n      // we know var_idx[j1_idx] != var_idx[j2_idx]\n      // assume var_idx[j1_idx] > var_idx[j2_idx]\n      // insert to block location (j1_idx, j2_idx)\n      if (var_idx[j1_idx] > var_idx[j2_idx]) {\n        size_t nnz_AtA_vars_accum_var2 =\n            sparsity.nnz_AtA_vars_accum[var_idx[j2_idx]];\n        int var2_dim = sparsity.var_dim[var_idx[j2_idx]];\n\n        int inner_insert_var2_var1 =\n            sparsity.inner_insert_map[var_idx[j2_idx]].at(var_idx[j1_idx]);\n\n        double* value_ptr = AtA.valuePtr() + nnz_AtA_vars_accum_var2 +\n                            var2_dim + inner_insert_var2_var1;\n\n#ifdef MINISAM_WITH_MULTI_THREADS\n        mutex_A.lock();\n#endif\n\n        if (j1_idx > j2_idx) {\n          for (int j = 0; j < wht_Js[j2_idx].cols(); j++) {\n            for (int i = 0; i < wht_Js[j1_idx].cols(); i++) {\n              *(value_ptr++) += stackJtJ(jacobian_col_local[j1_idx] + i,\n                                         jacobian_col_local[j2_idx] + j);\n            }\n            value_ptr += (sparsity.nnz_AtA_cols[jacobian_col[j2_idx] + j] - 1 -\n                          wht_Js[j1_idx].cols());\n          }\n        } else {\n          for (int j = 0; j < wht_Js[j2_idx].cols(); j++) {\n            for (int i = 0; i < wht_Js[j1_idx].cols(); i++) {\n              *(value_ptr++) += stackJtJ(jacobian_col_local[j2_idx] + j,\n                                         jacobian_col_local[j1_idx] + i);\n            }\n            value_ptr += (sparsity.nnz_AtA_cols[jacobian_col[j2_idx] + j] - 1 -\n                          wht_Js[j1_idx].cols());\n          }\n        }\n\n#ifdef MINISAM_WITH_MULTI_THREADS\n        mutex_A.unlock();\n#endif\n      }\n    }\n  }\n}\n\n/* ************************************************************************** */\n#ifdef MINISAM_WITH_MULTI_THREADS\nvoid linearzationLowerHessianCaller_(\n    const FactorGraph& factors, const Variables& values,\n    const LowerHessianSparsityPattern& sparsity,\n    Eigen::SparseMatrix<double>& AtA, Eigen::VectorXd& Atb, std::mutex& mutex_A,\n    std::mutex& mutex_b, int thread_id, int total_thread) {\n  for (size_t fidx = thread_id; fidx < factors.size(); fidx += total_thread) {\n    linearzationLowerHessianSingleFactor_(factors.factors()[fidx], values,\n                                          sparsity, AtA, Atb, mutex_A, mutex_b);\n  }\n}\n#endif\n}  // namespace\n\n/* ************************************************************************** */\nvoid linearzationLowerHessian(const FactorGraph& factors,\n                              const Variables& values,\n                              const LowerHessianSparsityPattern& sparsity,\n                              Eigen::SparseMatrix<double>& AtA,\n                              Eigen::VectorXd& Atb) {\n  // init empty AtA and Atb\n  AtA = Eigen::SparseMatrix<double>(sparsity.A_cols, sparsity.A_cols);\n  Atb = Eigen::VectorXd::Zero(sparsity.A_cols);\n\n  // pre-allocate AtA by number of non-zeros each col\n  AtA.reserve(sparsity.nnz_AtA_cols);\n\n  // prepare empty AtA with zeros\n  // depends on IEEE 754 floating point format of 0.0\n  memset(AtA.valuePtr(), 0, sparsity.total_nnz_AtA_cols * sizeof(double));\n  memcpy(AtA.innerIndexPtr(), &sparsity.inner_index[0],\n         sparsity.total_nnz_AtA_cols * sizeof(int));\n  memcpy(AtA.innerNonZeroPtr(), &sparsity.inner_nnz_index[0],\n         sparsity.A_cols * sizeof(int));\n  memcpy(AtA.outerIndexPtr(), &sparsity.outer_index[0],\n         sparsity.A_cols * sizeof(int));\n\n// incremental fill-in Hessian\n#ifdef MINISAM_WITH_MULTI_THREADS\n\n  mutex mutex_A, mutex_b;  // data mutex\n\n  // init threads\n  vector<thread> linthreads;\n  linthreads.reserve(MINISAM_WITH_MULTI_THREADS_NUM);\n  for (int i = 0; i < MINISAM_WITH_MULTI_THREADS_NUM; i++) {\n    linthreads.emplace_back(linearzationLowerHessianCaller_, std::ref(factors),\n                            std::ref(values), std::ref(sparsity), std::ref(AtA),\n                            std::ref(Atb), std::ref(mutex_A), std::ref(mutex_b),\n                            i, MINISAM_WITH_MULTI_THREADS_NUM);\n  }\n\n  // wait threads to finish\n  for (int i = 0; i < MINISAM_WITH_MULTI_THREADS_NUM; i++) {\n    linthreads[i].join();\n  }\n\n#else\n  for (size_t f_idx = 0; f_idx < factors.size(); f_idx++) {\n    const std::shared_ptr<Factor>& f = factors.factors()[f_idx];\n    linearzationLowerHessianSingleFactor_(f, values, sparsity, AtA, Atb);\n  }\n#endif\n\n  // always output compressed matrix\n  AtA.makeCompressed();\n}\n\n/* ************************************************************************** */\nvoid linearzationFullHessian(const FactorGraph& graph,\n                             const Variables& variables,\n                             const LowerHessianSparsityPattern& sparsity,\n                             Eigen::SparseMatrix<double>& AtA,\n                             Eigen::VectorXd& Atb) {\n  Eigen::SparseMatrix<double> AtA_lower;\n  linearzationLowerHessian(graph, variables, sparsity, AtA_lower, Atb);\n  AtA = AtA_lower.selfadjointView<Eigen::Lower>();\n}\n\n}  // namespace internal\n}  // namespace minisam\n", "meta": {"hexsha": "1c585090766cb3c9d00c9d5699f484c4a3c00974", "size": 13010, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "minisam/nonlinear/linearization.cpp", "max_stars_repo_name": "versatran01/minisam", "max_stars_repo_head_hexsha": "b3840d2629551fdfa287df8aac2e7956873d2b0e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 338.0, "max_stars_repo_stars_event_min_datetime": "2019-09-03T10:44:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:12:08.000Z", "max_issues_repo_path": "minisam/nonlinear/linearization.cpp", "max_issues_repo_name": "bhsphd/minisam", "max_issues_repo_head_hexsha": "ef84796fa11ac6e5e4d4aa9d60d9b94a99a973fb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 23.0, "max_issues_repo_issues_event_min_datetime": "2019-09-26T09:00:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-04T06:04:02.000Z", "max_forks_repo_path": "minisam/nonlinear/linearization.cpp", "max_forks_repo_name": "bhsphd/minisam", "max_forks_repo_head_hexsha": "ef84796fa11ac6e5e4d4aa9d60d9b94a99a973fb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 87.0, "max_forks_repo_forks_event_min_datetime": "2019-09-04T05:17:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T09:47:23.000Z", "avg_line_length": 36.5449438202, "max_line_length": 80, "alphanum_fraction": 0.5966179862, "num_tokens": 3271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.6406358548398982, "lm_q1q2_score": 0.49091517625831266}}
{"text": "// Copyright (C) 2011-2013 Rhys Ulerich\n// Copyright (C) ??? Martin Bauer\n// Copyright (C) 2017 Henri Menke\n//\n// This code borrows heavily from code written by Rhys Ulerich and\n// Martin Bauer.  They licensed it under the Mozilla Public License,\n// v. 2.0 and the GNU General Public License (no version info),\n// respectively.  I believe that I have made enough contributions and\n// altered this code far enough from the originals that I can\n// relicense it under the Boost Software License.\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#pragma once\n\n#include <algorithm>\n#include <cmath>\n#include <functional>\n#include <iterator>\n#include <limits>\n#include <map>\n#include <stdexcept>\n#include <string>\n\n#define BOOST_RESULT_OF_USE_DECLTYPE\n#define BOOST_SPIRIT_USE_PHOENIX_V3\n#include <boost/math/constants/constants.hpp>\n#include <boost/spirit/include/phoenix.hpp>\n#include <boost/spirit/include/qi.hpp>\n#include <boost/variant.hpp>\n\nnamespace matheval {\n\nnamespace detail {\n\nnamespace qi = boost::spirit::qi;\nnamespace ascii = boost::spirit::ascii;\n\n/** @brief Sign function\n *\n * Missing function in the STL.  This calculates the mathematical sign\n * function.\n *\n * @f[\n *   \\mathop{\\mathrm{sgn}}(x) =\n *   \\begin{cases}\n *      1 & x > 0 \\\\\n *      0 & x = 0 \\\\\n *     -1 & x < 0 \\\\\n *   \\end{cases}\n * @f]\n *\n * @param[in] x number\n * @returns the sign of x\n */\ntemplate < typename T >\nT sgn(T x) { return (T{0} < x) - (x < T{0}); }\n\n// AST\n\ntemplate < typename real_t > struct unary_op;\ntemplate < typename real_t > struct binary_op;\n\nstruct nil {};\n\n/** @brief Abstract Syntax Tree\n *\n * Stores the abstract syntax tree (AST) of the parsed mathematical\n * expression.\n */\ntemplate < typename real_t >\nstruct expr_ast\n{\n    using tree_t = boost::variant<\n        nil // can't happen!\n        , real_t\n        , std::string\n        , boost::recursive_wrapper<expr_ast<real_t>>\n        , boost::recursive_wrapper<binary_op<real_t>>\n        , boost::recursive_wrapper<unary_op<real_t>>\n        >;\npublic:\n    /** @brief AST storage\n     *\n     * The syntax tree can hold various types.  Numbers (`real_t`),\n     * variables (`std::string`), the recursive tree itself\n     * (`expr_ast`), binary operators (`binary_op`), and unary\n     * operators (`unary_op`).\n     */\n    tree_t tree;\n\n    /** @brief Default constructor\n     *\n     * Initializes the tree to a nil value to indicate inconsistent\n     * state.\n     */\n    expr_ast() : tree(nil{}) {}\n\n    /** @brief Copy constructor\n     *\n     * Deep copies the syntax tree.\n     */\n    template <typename Expr>\n    expr_ast(Expr const &other) : tree(other) {}\n\n    /** @brief Add a tree */\n    expr_ast& operator+=(expr_ast const &rhs);\n    /** @brief subtract a tree */\n    expr_ast& operator-=(expr_ast const &rhs);\n    /** @brief Multiply by a tree */\n    expr_ast& operator*=(expr_ast const &rhs);\n    /** @brief Divide by a tree */\n    expr_ast& operator/=(expr_ast const &rhs);\n};\n\n/** @brief Store a unary operator and its argument tree */\ntemplate < typename real_t >\nstruct unary_op\n{\n    /** @brief Signature of a unary operator: op(x) */\n    using op_t = std::function<real_t(real_t)>;\n\n    /** @brief Save the operator and the argument tree */\n    unary_op(op_t op, expr_ast<real_t> const &rhs)\n        : op(op), rhs(rhs)\n    {}\n\n    /** @brief Stored operator */\n    op_t op;\n    /** @brief Stored argument tree */\n    expr_ast<real_t> rhs;\n};\n\n/** @brief Store a binary operator and its argument trees */\ntemplate < typename real_t >\nstruct binary_op\n{\n    /** @brief Signature of a binary operator: op(x,y) */\n    using op_t = std::function<real_t(real_t,real_t)>;\n\n    /** @brief Save the operator and the argument trees */\n    binary_op(op_t op, expr_ast<real_t> const &lhs, expr_ast<real_t> const &rhs)\n        : op(op), lhs(lhs), rhs(rhs)\n    {}\n\n    /** @brief Stored operator */\n    op_t op;\n    /** @brief Stored argument tree of first argument */\n    expr_ast<real_t> lhs;\n    /** @brief Stored argument tree of second argument */\n    expr_ast<real_t> rhs;\n};\n\ntemplate < typename real_t >\nexpr_ast<real_t>& expr_ast<real_t>::operator+=(expr_ast<real_t> const &rhs)\n{\n    tree = binary_op<real_t>(std::plus<real_t>{}, tree, rhs);\n    return *this;\n}\ntemplate < typename real_t >\nexpr_ast<real_t>& expr_ast<real_t>::operator-=(expr_ast<real_t> const &rhs)\n{\n    tree = binary_op<real_t>(std::minus<real_t>{}, tree, rhs);\n    return *this;\n}\ntemplate < typename real_t >\nexpr_ast<real_t>& expr_ast<real_t>::operator*=(expr_ast<real_t> const &rhs)\n{\n    tree = binary_op<real_t>(std::multiplies<real_t>{}, tree, rhs);\n    return *this;\n}\ntemplate < typename real_t >\nexpr_ast<real_t>& expr_ast<real_t>::operator/=(expr_ast<real_t> const &rhs)\n{\n    tree = binary_op<real_t>(std::divides<real_t>{}, tree, rhs);\n    return *this;\n}\n\n/** @brief Evaluate the Abstract Syntax Tree\n *\n * This visits all the variants of the AST and applies the stored\n * operators.\n */\ntemplate < typename real_t >\nclass eval_ast\n{\npublic:\n    /** @brief Necessary typedef for `boost::apply_visitor` */\n    using result_type = real_t;\n\n    /** @brief Type of the symbol table */\n    using symbol_table_t = std::map<std::string, result_type>;\n\n    /** @brief Constructor\n     *\n     * Saves the symbol table to apply variables.\n     */\n    eval_ast(symbol_table_t const &sym) : st(sym) {}\n\n    /** @brief Empty nodes in the tree evaluate to 0 */\n    result_type operator()(nil) const { return 0; }\n\n    /** @brief Numbers evaluate to themselves */\n    result_type operator()(result_type n)  const { return n; }\n\n    /** @brief Variables evaluate to their value in the symbol table */\n    result_type operator()(std::string const &c) const\n    {\n        auto it = st.find(c);\n        if(it == st.end())\n            throw std::invalid_argument(\"Unknown variable \" + c);\n        return it->second;\n    }\n\n    /** @brief Recursively evaluate the AST */\n    result_type operator()(expr_ast<real_t> const& ast) const\n    {\n        return boost::apply_visitor(*this, ast.tree);\n    }\n\n    /** @brief Evaluate a binary operator and optionally recurse its operands */\n    result_type operator()(binary_op<real_t> const& tree) const\n    {\n        return tree.op(\n            boost::apply_visitor(*this, tree.lhs.tree),\n            boost::apply_visitor(*this, tree.rhs.tree)\n            );\n    }\n\n    /** @brief Evaluate a unary operator and optionally recurse its operand */\n    result_type operator()(unary_op<real_t> const& tree) const\n    {\n        return tree.op(\n            boost::apply_visitor(*this, tree.rhs.tree)\n            );\n    }\n\nprivate:\n    symbol_table_t st;\n};\n\n\n// Expressions\n\n/** @brief Unary expression functor */\ntemplate < typename real_t >\nstruct unary_expr_ {\n    /** @brief Make boost::phoenix::function happy */\n    template < typename T > struct result { using type = T; };\n\n    /** @brief Create a new AST containing the unary function */\n    expr_ast<real_t> operator()(typename unary_op<real_t>::op_t op,\n                                expr_ast<real_t> const &rhs) const {\n        return expr_ast<real_t>(unary_op<real_t>(op, rhs));\n    }\n};\n\n/** @brief Binary expression functor */\ntemplate < typename real_t >\nstruct binary_expr_ {\n    /** @brief Make boost::phoenix::function happy */\n    template < typename T > struct result { using type = T; };\n\n    /** @brief Create a new AST containing the binary function */\n    expr_ast<real_t> operator()(typename binary_op<real_t>::op_t op,\n                                expr_ast<real_t> const &lhs,\n                                expr_ast<real_t> const &rhs) const {\n        return expr_ast<real_t>(binary_op<real_t>(op, lhs, rhs));\n    }\n};\n\n// Grammar\n\n/** @brief Expression Grammar */\ntemplate < typename real_t, typename Iterator >\nstruct grammar\n    : qi::grammar<\n            Iterator, expr_ast<real_t>(), ascii::space_type\n        >\n{\nprivate:\n    qi::rule<Iterator, expr_ast<real_t>(), ascii::space_type> expression;\n    qi::rule<Iterator, expr_ast<real_t>(), ascii::space_type> term;\n    qi::rule<Iterator, expr_ast<real_t>(), ascii::space_type> factor;\n    qi::rule<Iterator, expr_ast<real_t>(), ascii::space_type> primary;\n    qi::rule<Iterator, std::string()> variable;\npublic:\n    /** @brief symbol table for constants like \"pi\" */\n    struct constant_\n        : boost::spirit::qi::symbols<\n                typename std::iterator_traits<Iterator>::value_type,\n                real_t\n            >\n    {\n        constant_()\n        {\n            this->add\n                (\"e\"      , boost::math::constants::e<real_t>()   )\n                (\"epsilon\", std::numeric_limits<real_t>::epsilon())\n                (\"pi\"     , boost::math::constants::pi<real_t>()  )\n            ;\n        }\n    } constant;\n\n    /** @brief symbol table for unary functions like \"abs\" */\n    struct ufunc_\n        : boost::spirit::qi::symbols<\n                typename std::iterator_traits<Iterator>::value_type,\n                typename unary_op<real_t>::op_t\n            >\n    {\n        ufunc_()\n        {\n            this->add\n                (\"abs\"   , static_cast<real_t(*)(real_t)>(&std::abs   ))\n                (\"acos\"  , static_cast<real_t(*)(real_t)>(&std::acos  ))\n                (\"acosh\" , static_cast<real_t(*)(real_t)>(&std::acosh ))\n                (\"asin\"  , static_cast<real_t(*)(real_t)>(&std::asin  ))\n                (\"asinh\" , static_cast<real_t(*)(real_t)>(&std::asinh ))\n                (\"atan\"  , static_cast<real_t(*)(real_t)>(&std::atan  ))\n                (\"atanh\" , static_cast<real_t(*)(real_t)>(&std::atanh ))\n                (\"cbrt\"  , static_cast<real_t(*)(real_t)>(&std::cbrt  ))\n                (\"ceil\"  , static_cast<real_t(*)(real_t)>(&std::ceil  ))\n                (\"cos\"   , static_cast<real_t(*)(real_t)>(&std::cos   ))\n                (\"cosh\"  , static_cast<real_t(*)(real_t)>(&std::cosh  ))\n                (\"erf\"   , static_cast<real_t(*)(real_t)>(&std::erf   ))\n                (\"erfc\"  , static_cast<real_t(*)(real_t)>(&std::erfc  ))\n                (\"exp\"   , static_cast<real_t(*)(real_t)>(&std::exp   ))\n                (\"exp2\"  , static_cast<real_t(*)(real_t)>(&std::exp2  ))\n                (\"floor\" , static_cast<real_t(*)(real_t)>(&std::floor ))\n                (\"log\"   , static_cast<real_t(*)(real_t)>(&std::log   ))\n                (\"log2\"  , static_cast<real_t(*)(real_t)>(&std::log2  ))\n                (\"log10\" , static_cast<real_t(*)(real_t)>(&std::log10 ))\n                (\"round\" , static_cast<real_t(*)(real_t)>(&std::round ))\n                (\"sgn\"   , static_cast<real_t(*)(real_t)>(&sgn        ))\n                (\"sin\"   , static_cast<real_t(*)(real_t)>(&std::sin   ))\n                (\"sinh\"  , static_cast<real_t(*)(real_t)>(&std::sinh  ))\n                (\"sqrt\"  , static_cast<real_t(*)(real_t)>(&std::sqrt  ))\n                (\"tan\"   , static_cast<real_t(*)(real_t)>(&std::tan   ))\n                (\"tanh\"  , static_cast<real_t(*)(real_t)>(&std::tanh  ))\n                (\"tgamma\", static_cast<real_t(*)(real_t)>(&std::tgamma))\n            ;\n        }\n    } ufunc;\n\n    /** @brief symbol table for binary functions like \"pow\" */\n    struct bfunc_\n        : boost::spirit::qi::symbols<\n                typename std::iterator_traits<Iterator>::value_type,\n                typename binary_op<real_t>::op_t\n            >\n    {\n        bfunc_()\n        {\n            this->add\n                (\"atan2\", static_cast<real_t(*)(real_t,real_t)>(&std::atan2))\n                (\"max\"  , static_cast<real_t(*)(real_t,real_t)>(&std::fmax ))\n                (\"min\"  , static_cast<real_t(*)(real_t,real_t)>(&std::fmin ))\n                (\"pow\"  , static_cast<real_t(*)(real_t,real_t)>(&std::pow  ))\n            ;\n        }\n    } bfunc;\n\n    /** @brief Constructor builds the grammar */\n    grammar() : grammar::base_type(expression)\n    {\n        using boost::spirit::qi::real_parser;\n        using boost::spirit::qi::real_policies;\n        real_parser<real_t,real_policies<real_t>> real;\n\n        using boost::spirit::lexeme;\n        using boost::spirit::qi::_1;\n        using boost::spirit::qi::_2;\n        using boost::spirit::qi::_3;\n        using boost::spirit::qi::_val;\n        using boost::spirit::qi::alpha;\n        using boost::spirit::qi::alnum;\n        using boost::spirit::qi::raw;\n\n        boost::phoenix::function<unary_expr_<real_t>> unary_expr;\n        boost::phoenix::function<binary_expr_<real_t>> binary_expr;\n\n        auto fmod = static_cast<real_t(*)(real_t,real_t)>(&std::fmod);\n        auto pow = static_cast<real_t(*)(real_t,real_t)>(&std::pow);\n\n        expression =\n            term                   [_val =  _1]\n            >> *(  ('+' >> term    [_val += _1])\n                |  ('-' >> term    [_val -= _1])\n                )\n            ;\n\n        term =\n            factor                 [_val =  _1]\n            >> *(  ('*' >> factor  [_val *= _1])\n                |  ('/' >> factor  [_val /= _1])\n                |  ('%' >> factor  [_val = binary_expr(fmod, _val, _1)])\n                )\n            ;\n\n        factor =\n            primary                [_val =  _1]\n            >> *(  (\"**\" >> factor [_val = binary_expr(pow, _val, _1)])\n                )\n            ;\n\n        variable =\n            raw[lexeme[alpha >> *(alnum | '_')]];\n\n        primary =\n            real                   [_val =  _1]\n            |   '(' >> expression  [_val =  _1] >> ')'\n            |   ('-' >> primary    [_val = unary_expr(std::negate<real_t>{}, _1)])\n            |   ('+' >> primary    [_val =  _1])\n            |   (ufunc >> '(' >> expression >> ')')\n                                   [_val = unary_expr(_1, _2)]\n            |   (bfunc >> '(' >> expression >> ',' >> expression >> ')')\n                                   [_val = binary_expr(_1, _2, _3)]\n            |   constant           [_val =  _1]\n            |   variable           [_val =  _1]\n            ;\n    }\n};\n\n} // namespace detail\n\n\n/** @brief Class interface\n *\n * This class hides the grammar, AST, and AST traversal behind some\n * member functions.\n *\n * @tparam real_t datatype of the result\n */\ntemplate < typename real_t >\nclass Parser\n{\n    detail::expr_ast<real_t> ast;\npublic:\n    /** @brief Parse an expression\n     *\n     * This function builds the grammar and parses the iterator into\n     * an AST.\n     *\n     * @param[in] first iterator to the start of the input sequence\n     * @param[in] last  iterator to the end of the input sequence\n     */\n    template < typename Iterator >\n    void parse(Iterator first, Iterator last)\n    {\n        static detail::grammar<real_t,Iterator> const g;\n\n        ast = detail::expr_ast<real_t>{}; // Drop old AST\n\n        bool r = boost::spirit::qi::phrase_parse(\n            first, last, g,\n            boost::spirit::ascii::space, ast);\n\n        if (!r || first != last)\n        {\n            std::string rest(first, last);\n            throw std::runtime_error(\"Parsing failed at \" + rest);\n        }\n    }\n\n    /** @overload parse(Iterator first, Iterator last) */\n    void parse(std::string const &str)\n    {\n        parse(str.begin(), str.end());\n    }\n\n    /** @brief Evaluate the AST with a given symbol table\n     *\n     * @param[in] st the symbol table for variables\n     */\n    real_t evaluate(typename detail::eval_ast<real_t>::symbol_table_t const &st)\n    {\n        detail::eval_ast<real_t> solver(st);\n        return solver(ast);\n    }\n};\n\n\n/** @brief Convenience function\n *\n * This function builds the grammar, parses the iterator to an AST,\n * evaluates it, and returns the result.\n *\n * @param[in] first iterator to the start of the input sequence\n * @param[in] last  iterator to the end of the input sequence\n * @param[in] st    the symbol table for variables\n */\ntemplate < typename real_t, typename Iterator >\nreal_t parse(Iterator first, Iterator last,\n             typename detail::eval_ast<real_t>::symbol_table_t const &st)\n{\n    Parser<real_t> parser;\n    parser.parse(first, last);\n    return parser.evaluate(st);\n}\n\n/** @overload parse(Iterator first, Iterator last, typename detail::eval_ast<real_t>::symbol_table_t const &st) */\ntemplate < typename real_t >\nreal_t parse(std::string const &str,\n             typename detail::eval_ast<real_t>::symbol_table_t const &st)\n{\n    return parse<real_t>(str.begin(), str.end(), st);\n}\n\n} // namespace expression\n", "meta": {"hexsha": "4c1c4ab24b8d6920f01a517dbbdab6548cc6f09b", "size": 16422, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/matheval.hpp", "max_stars_repo_name": "fweik/boost_matheval", "max_stars_repo_head_hexsha": "6e77515ec71ce95fe24b8ced6170fa146e9912ac", "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/matheval.hpp", "max_issues_repo_name": "fweik/boost_matheval", "max_issues_repo_head_hexsha": "6e77515ec71ce95fe24b8ced6170fa146e9912ac", "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/matheval.hpp", "max_forks_repo_name": "fweik/boost_matheval", "max_forks_repo_head_hexsha": "6e77515ec71ce95fe24b8ced6170fa146e9912ac", "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.07421875, "max_line_length": 114, "alphanum_fraction": 0.574960419, "num_tokens": 4184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.4909151762583126}}
{"text": "//=======================================================================\n// Copyright (c) 2013 Piotr Smulewicz\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n/**\n * @file multiway_cut_example.cpp\n * @brief\n * @author Piotr Smulewicz\n * @version 1.0\n * @date 2013-11-13\n */\n\n    //! [Multiway Cut Example]\n#include \"paal/multiway_cut/multiway_cut.hpp\"\n\n#include <boost/graph/adjacency_list.hpp>\n\nint main() {\n    // sample data\n    std::vector<std::pair<int,int>> edges_p{{0,3},{1,3},\n                                           {0,4},{2,4},\n                                           {1,5},{2,5},\n                                           {3,6},{4,6},\n                                           {3,7},{5,7},\n                                           {4,8},{5,8},\n                                           {6,7},{6,8},{7,8}\n    };\n    const int vertices_num = 9;\n    std::vector<int> cost_edges{100,100,100,100,100,100,10,10,10,10,10,10,1,1,1};\n\n    std::vector<int> terminals = { 0, 1, 2 };\n    boost::adjacency_list<\n        boost::vecS, boost::vecS, boost::undirectedS,\n        boost::property<boost::vertex_index_t, int,\n                        boost::property<boost::vertex_color_t, int>>,\n                    boost::property<boost::edge_weight_t, int>\n                    > graph(edges_p.begin(), edges_p.end(), cost_edges.begin(), vertices_num);\n\n    for (std::size_t i = 1; i <= terminals.size(); ++i) {\n        put(boost::vertex_color, graph, terminals[i - 1], i);\n    }\n\n    //solve\n    std::vector<std::pair<int,int>> vertices_parts;\n    auto cost_cut = paal::multiway_cut(graph, back_inserter(vertices_parts));\n\n    //print result\n    std::cout << \"cost cut: \" << cost_cut << std::endl;\n    std::cout << \"vertices (part)\" << std::endl;\n    for(auto i: vertices_parts) {\n        std::cout << \"  \" << i.first << \"      ( \" << i.second << \" )\" << std::endl;\n    }\n    paal::lp::glp::free_env();\n}\n    //! [Multiway Cut Example]\n", "meta": {"hexsha": "f410ebbce287d11492c0d43ff575941c7a243b40", "size": 2125, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/linear_programming/multiway_cut/multiway_cut_example.cpp", "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": "examples/linear_programming/multiway_cut/multiway_cut_example.cpp", "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": "examples/linear_programming/multiway_cut/multiway_cut_example.cpp", "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.0169491525, "max_line_length": 94, "alphanum_fraction": 0.4767058824, "num_tokens": 554, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.49091516574302124}}
{"text": "//N0680337\n#include <boost/test/unit_test.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n\n#include \"logs.h\"\n#include \"route.h\"\n#include \"track.h\"\n\nusing namespace GPS;\n\nBOOST_AUTO_TEST_SUITE( Route_maxLongitude )\n\nconst bool isFileName = true;\n// More test details in DesignOfUnitTests.pdf\n// Used boost check close to allow a tolerance when using floating points\n// Test increasing longitude values to identify that max longitude works\nBOOST_AUTO_TEST_CASE( MaxLongHorizontalLine )\n{\n   Route route = Route(LogFiles::GPXRoutesDir + \"IncreaseInLongitude-N0680337.gpx\", isFileName);\n   BOOST_CHECK_CLOSE( route.maxLongitude(), 51.3975, 0.1);\n}\n\n\n// Test if very small changes are detected\nBOOST_AUTO_TEST_CASE( VerySmallChange )\n{\n   Route route = Route(LogFiles::GPXRoutesDir + \"VerySmallChange-N0680337.gpx\", isFileName);\n   BOOST_CHECK_CLOSE( route.maxLongitude(), 10.0000002, 0.0000001 );\n}\n\n\n// Test that the function works with only one longitude value\nBOOST_AUTO_TEST_CASE( MaxLongVerticalLine )\n{\n   Route route = Route(LogFiles::GPXRoutesDir + \"ConstantLongitude-N0680337.gpx\", isFileName);\n   BOOST_CHECK_CLOSE( route.maxLongitude(), -50, 0.1);\n}\n\n\n// Test a constant value with the maximum possible longitude\nBOOST_AUTO_TEST_CASE( MaxPossibleConstantLongitude )\n{\n   Route route = Route(LogFiles::GPXRoutesDir + \"MaxPossibleConstantLongitude-N0680337.gpx\", isFileName);\n   BOOST_CHECK_CLOSE( route.maxLongitude(), 180, 0.1);\n}\n\n\n// Test the function against negative values only (A, G, F gridworld points)\n\nBOOST_AUTO_TEST_CASE( NegativeMaxLongHorizontalLine )\n{\n   Route route = Route(LogFiles::GPXRoutesDir + \"NegativeMaxLong-N0680337.gpx\", isFileName);\n   BOOST_CHECK_CLOSE( route.maxLongitude(), -51.3975, 0.01);\n}\n\n\n// Test the function works with the Prime Meridian as the max longitude (0 longitude, C, H, M gridworld points)\n\nBOOST_AUTO_TEST_CASE( PrimeMeridianVerticalLine )\n{\n   Route route = Route(LogFiles::GPXRoutesDir + \"PrimeMeridianVerticalLine-N0680337.gpx\", isFileName);\n   BOOST_CHECK_CLOSE( route.maxLongitude(), 0, 0.1);\n}\n\n\n// Test the function against negative values, 0, and positive values to find the max longitude\nBOOST_AUTO_TEST_CASE( NegativeToPositiveLong )\n{\n   Route route = Route(LogFiles::GPXRoutesDir + \"ThroughPrimeMeridian-N0680337.gpx\", isFileName);\n   BOOST_CHECK_CLOSE( route.maxLongitude(), 27.9505, 0.1);\n}\n\n\n// Test the maximum positive longitude to the maximum negative longitude\nBOOST_AUTO_TEST_CASE( MaxPositiveToMaxNegativeLong )\n{\n   Route route = Route(LogFiles::GPXRoutesDir + \"MaxPositiveToMaxNegative-N0680337.gpx\", isFileName);\n   BOOST_CHECK_CLOSE( route.maxLongitude(), 180, 0.1);\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "bbc1017722da798b2d19611023d7a7c94af101c5", "size": 2688, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/gpx-tests/MaxLong-N0680337.cpp", "max_stars_repo_name": "EdwinLangley/GPX-Route-and-Track", "max_stars_repo_head_hexsha": "e4de303c62c7e9dc92724e8f257f7960ff77c992", "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/gpx-tests/MaxLong-N0680337.cpp", "max_issues_repo_name": "EdwinLangley/GPX-Route-and-Track", "max_issues_repo_head_hexsha": "e4de303c62c7e9dc92724e8f257f7960ff77c992", "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/gpx-tests/MaxLong-N0680337.cpp", "max_forks_repo_name": "EdwinLangley/GPX-Route-and-Track", "max_forks_repo_head_hexsha": "e4de303c62c7e9dc92724e8f257f7960ff77c992", "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": 32.3855421687, "max_line_length": 111, "alphanum_fraction": 0.7723214286, "num_tokens": 682, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.4908978468292951}}
{"text": "#ifndef EXPONENTIAL_HH\n#define EXPONENTIAL_HH\n\n#include <boost/random/exponential_distribution.hpp>\n\n#include \"random.hh\"\n\n\n//\tA simple wrapper for the boost exponential distribution generator\n//\t usage:\tExponential exp_distribution_;\n//          double val = exp_distribution_.sample();\nclass Exponential\n{\nprivate:\n  boost::random::exponential_distribution<> distribution;\n\n  PRNG & prng;\n\npublic:\n  Exponential( const double & rate, PRNG & s_prng ) : distribution( rate ), prng( s_prng ) {}\n  \n  double sample( void ) { return distribution( prng ); }\n};\n\n#endif\n", "meta": {"hexsha": "b8221d9e3a50802a54b5685db32938be4ebebdad", "size": 565, "ext": "hh", "lang": "C++", "max_stars_repo_path": "Applications/genericCC/exponential.hh", "max_stars_repo_name": "comnetsAD/ALCC", "max_stars_repo_head_hexsha": "fc9c627de8c381987fc775ce0872339fceb43ddf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2021-05-19T16:58:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T03:51:20.000Z", "max_issues_repo_path": "Applications/genericCC/exponential.hh", "max_issues_repo_name": "comnetsAD/ALCC", "max_issues_repo_head_hexsha": "fc9c627de8c381987fc775ce0872339fceb43ddf", "max_issues_repo_licenses": ["MIT"], "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/genericCC/exponential.hh", "max_forks_repo_name": "comnetsAD/ALCC", "max_forks_repo_head_hexsha": "fc9c627de8c381987fc775ce0872339fceb43ddf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-05-24T11:19:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T17:58:24.000Z", "avg_line_length": 21.7307692308, "max_line_length": 93, "alphanum_fraction": 0.7274336283, "num_tokens": 133, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7577943712746404, "lm_q2_score": 0.6477982111525409, "lm_q1q2_score": 0.4908978381331765}}
{"text": "// Boost.Geometry\r\n\r\n// Copyright (c) 2018 Yaghyavardhan Singh Khangarot, Hyderabad, India.\r\n\r\n// Contributed and/or modified by Yaghyavardhan Singh Khangarot, as part of Google Summer of Code 2018 program.\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef BOOST_GEOMETRY_TEST_FRECHET_DISTANCE_HPP\r\n#define BOOST_GEOMETRY_TEST_FRECHET_DISTANCE_HPP\r\n\r\n#include <geometry_test_common.hpp>\r\n#include <boost/geometry/algorithms/discrete_frechet_distance.hpp>\r\n#include <boost/geometry/io/wkt/wkt.hpp>\r\n#include <boost/geometry/strategies/strategies.hpp>\r\n#include <boost/variant/variant.hpp>\r\n\r\ntemplate <typename Geometry1,typename Geometry2>\r\nvoid test_frechet_distance(Geometry1 const& geometry1,Geometry2 const& geometry2,\r\n    typename bg::distance_result\r\n        <\r\n            typename bg::point_type<Geometry1>::type,\r\n            typename bg::point_type<Geometry2>::type\r\n        >::type expected_frechet_distance )\r\n{\r\n    using namespace bg;\r\n    typedef typename distance_result\r\n        <\r\n            typename point_type<Geometry1>::type,\r\n            typename point_type<Geometry2>::type\r\n        >::type result_type;\r\n    result_type h_distance = bg::discrete_frechet_distance(geometry1,geometry2);\r\n\r\n#ifdef BOOST_GEOMETRY_TEST_DEBUG\r\n    std::ostringstream out;\r\n    out << typeid(typename bg::coordinate_type<Geometry1>::type).name()\r\n        << std::endl\r\n        << typeid(typename bg::coordinate_type<Geometry2>::type).name()\r\n        << std::endl\r\n        << typeid(h_distance).name()\r\n        << std::endl\r\n        << \"frechet_distance : \" << bg::discrete_frechet_distance(geometry1,geometry2)\r\n        << std::endl;\r\n    std::cout << out.str();\r\n#endif\r\n\r\n    BOOST_CHECK_CLOSE(h_distance, expected_frechet_distance, 0.001);\r\n}\r\n\r\n\r\n\r\ntemplate <typename Geometry1,typename Geometry2>\r\nvoid test_geometry(std::string const& wkt1,std::string const& wkt2,\r\n    typename bg::distance_result\r\n        <\r\n            typename bg::point_type<Geometry1>::type,\r\n            typename bg::point_type<Geometry2>::type\r\n        >::type expected_frechet_distance)\r\n{\r\n    Geometry1 geometry1;\r\n    bg::read_wkt(wkt1, geometry1);\r\n    Geometry2 geometry2;\r\n    bg::read_wkt(wkt2, geometry2);\r\n    test_frechet_distance(geometry1,geometry2,expected_frechet_distance);\r\n#if defined(BOOST_GEOMETRY_TEST_DEBUG)\r\n    test_frechet_distance(boost::variant<Geometry1>(geometry1),boost::variant<Geometry2>(geometry2), expected_frechet_distance);\r\n#endif\r\n}\r\n\r\ntemplate <typename Geometry1,typename Geometry2 ,typename Strategy>\r\nvoid test_frechet_distance(Geometry1 const& geometry1,Geometry2 const& geometry2,Strategy strategy,\r\n    typename bg::distance_result\r\n        <\r\n            typename bg::point_type<Geometry1>::type,\r\n            typename bg::point_type<Geometry2>::type,\r\n            Strategy\r\n        >::type expected_frechet_distance )\r\n{\r\n    using namespace bg;\r\n    typedef typename distance_result\r\n        <\r\n            typename point_type<Geometry1>::type,\r\n            typename point_type<Geometry2>::type,\r\n            Strategy\r\n        >::type result_type;\r\n    result_type h_distance = bg::discrete_frechet_distance(geometry1,geometry2,strategy);\r\n\r\n#ifdef BOOST_GEOMETRY_TEST_DEBUG\r\n    std::ostringstream out;\r\n    out << typeid(typename bg::coordinate_type<Geometry1>::type).name()\r\n        << std::endl\r\n        << typeid(typename bg::coordinate_type<Geometry2>::type).name()\r\n        << std::endl\r\n        << typeid(h_distance).name()\r\n        << std::endl\r\n        << \"frechet_distance : \" << bg::discrete_frechet_distance(geometry1,geometry2,strategy)\r\n        << std::endl;\r\n    std::cout << out.str();\r\n#endif\r\n\r\n    BOOST_CHECK_CLOSE(h_distance, expected_frechet_distance, 0.001);\r\n}\r\n\r\n\r\n\r\ntemplate <typename Geometry1,typename Geometry2,typename Strategy>\r\nvoid test_geometry(std::string const& wkt1,std::string const& wkt2,Strategy strategy,\r\n    typename bg::distance_result\r\n        <\r\n            typename bg::point_type<Geometry1>::type,\r\n            typename bg::point_type<Geometry2>::type,\r\n            Strategy\r\n        >::type expected_frechet_distance)\r\n{\r\n    Geometry1 geometry1;\r\n    bg::read_wkt(wkt1, geometry1);\r\n    Geometry2 geometry2;\r\n    bg::read_wkt(wkt2, geometry2);\r\n    test_frechet_distance(geometry1,geometry2,strategy,expected_frechet_distance);\r\n#if defined(BOOST_GEOMETRY_TEST_DEBUG)\r\n    test_frechet_distance(boost::variant<Geometry1>(geometry1),boost::variant<Geometry2>(geometry2),strategy, expected_frechet_distance);\r\n#endif\r\n}\r\n\r\n\r\ntemplate <typename Geometry1,typename Geometry2>\r\nvoid test_empty_input(Geometry1 const& geometry1,Geometry2 const& geometry2)\r\n{\r\n    try\r\n    {\r\n        bg::discrete_frechet_distance(geometry1,geometry2);\r\n    }\r\n    catch(bg::empty_input_exception const& )\r\n    {\r\n        return;\r\n    }\r\n    BOOST_CHECK_MESSAGE(false, \"A empty_input_exception should have been thrown\" );\r\n}\r\n\r\n\r\n#endif\r\n\r\n", "meta": {"hexsha": "6b18e479b3b7cb05a40088e264049a96b4a0d7c3", "size": 5054, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/libs/geometry/test/algorithms/similarity/test_frechet_distance.hpp", "max_stars_repo_name": "Jackarain/tinyrpc", "max_stars_repo_head_hexsha": "07060e3466776aa992df8574ded6c1616a1a31af", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "third_party/boost/libs/geometry/test/algorithms/similarity/test_frechet_distance.hpp", "max_issues_repo_name": "avplayer/cxxrpc", "max_issues_repo_head_hexsha": "7049b4079fac78b3828e68f787d04d699ce52f6d", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-04T18:00:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-04T18:00:00.000Z", "max_forks_repo_path": "third_party/boost/libs/geometry/test/algorithms/similarity/test_frechet_distance.hpp", "max_forks_repo_name": "avplayer/cxxrpc", "max_forks_repo_head_hexsha": "7049b4079fac78b3828e68f787d04d699ce52f6d", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 34.8551724138, "max_line_length": 138, "alphanum_fraction": 0.6901464187, "num_tokens": 1166, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982043529716, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.49089783298050127}}
{"text": "#include \"Planet.h\"\n#include \"helper/benchmark_helper.h\"\n#include <cmath>\n#include <vector>\n#include <chrono>\n#include <string>\n#include <memory>\n#ifdef GPU_SUPPORT\n#include <amp.h>\n#include <amp_math.h>\n#endif\n#include <algorithm>\n#include <thread>\n#include <boost/math/special_functions/sign.hpp>\n\nusing std::vector;\nusing std::chrono::steady_clock;\nusing std::chrono::microseconds;\nusing std::chrono::duration_cast;\nusing std::string;\nusing std::to_string;\nusing std::unique_ptr;\nusing std::make_unique;\nusing std::min;\nusing std::max;\nusing std::thread;\n\nusing namespace GeneticSimulation;\n\n// default constructor\nGeneticSimulation::Planet::Planet() : initialized(false), timesteps(0) {}\n\n// precompute temperatures\nvoid GeneticSimulation::Planet::precompute_temperatures(const Config& config, bool benchmark)\n{\n\t// set lookup table to correct size\n\ttemperatures.resize(config.area_height * config.orbital_period);\n\ttimesteps = config.orbital_period;\n\n#ifdef GPU_SUPPORT\n\t// get whether to use GPU\n\tconst bool use_cpu = !config.precompute_temperatures_gpu;\n#else\n\tconstexpr bool use_cpu = true;\n#endif\n\t\n\t// precompute or benchmark on selected device\n\tif (use_cpu) {\n\t\t// determine number of threads to use\n\t\tauto num_threads = config.precompute_temperatures_cpu_threads == 0 ?\n\t\t\tthread::hardware_concurrency() :\n\t\t\tconfig.precompute_temperatures_cpu_threads;\n\t\t// benchmark or precompute once\n\t\tbenchmark ? benchmark_temperature_computation_cpu(num_threads, config) : \n\t\t\tprecompute_temperatures_cpu(num_threads, config);\n\t}\n#ifdef GPU_SUPPORT\n\telse {\n\t\t// benchmark or precompute once\n\t\tbenchmark ? benchmark_temperature_computation_gpu(config) :\n\t\t\tprecompute_temperatures_gpu(config);\n\t}\n#endif\n\n\t// record initialization\n\tinitialized = true;\n}\n\n// get temperature from lookup table\nfloat GeneticSimulation::Planet::get_temperature(unsigned int y, unsigned int t) const\n{\n\t// return -1 if temperatures have not been computed, otherwise return precomputed temperature\n\treturn initialized ? temperatures[y * timesteps + (t % timesteps)] : -1.f;\n}\n\n// precompute temperatures using the CPU\nvoid GeneticSimulation::Planet::precompute_temperatures_cpu(unsigned int worker_threads, const Config& config)\n{\n\t// calculate number of timesteps per thread\n\tunsigned int timesteps_per_thread = timesteps / worker_threads + 1;\n\t// create vector for thread objects\n\tvector<unique_ptr<thread>> threads;\n\t// start threads\n\tfor (unsigned int i = 0; i < worker_threads; i++) {\n\t\tthreads.push_back(make_unique<thread>(\n\t\t\t[&, timesteps_per_thread, i] {\n\t\t\t\tprecompute_temperatures_for_timestep_range_cpu(i * timesteps_per_thread,\n\t\t\t\t\t(i + 1) * timesteps_per_thread, config);\n\t\t\t}\n\t\t));\n\t}\n\t// join threads\n\tfor (auto& t_ptr : threads) {\n\t\tt_ptr->join();\n\t}\n}\n\n// precompute temperatures on the CPU for the given timestep range\nvoid GeneticSimulation::Planet::precompute_temperatures_for_timestep_range_cpu(unsigned int start_t, unsigned int end_t, const Config& config)\n{\n\t// cap end_t\n\tend_t = min(end_t, config.orbital_period);\n\n\t// initialize vector for storing intermediate equatorial temperature results\n\tvector<double> equatorial_black_body_temperatures(end_t - start_t);\n\n\t// pi\n\tconst double pi = 3.14159265358979323846;\n\n\t// reused loop variables\n\tdouble angle, pos_x, pos_y, squared_dist, black_body_temperature;\n\n\t// calculate equatorial black body temperatures for each timestep (angle in orbit)\n\tfor (unsigned int t = start_t; t < end_t; t++)\n\t{\n\t\t// calculate orbital angle corresponding to timestep\n\t\tangle = (static_cast<double>(t) / static_cast<double>(config.orbital_period)) * 2 * pi;\n\n\t\t// calculate the x and y coordinates of the planet at this angle in the orbital ellipse\n\t\tpos_x = (config.orbit_radius_x * cos(angle) * cos(config.orbit_rotation)) -\n\t\t\t(config.orbit_radius_y * sin(angle) * sin(config.orbit_rotation)) +\n\t\t\tconfig.orbit_center_offset_x;\n\t\tpos_y = (config.orbit_radius_x * cos(angle) * sin(config.orbit_rotation)) +\n\t\t\t(config.orbit_radius_y * sin(angle) * cos(config.orbit_rotation)) +\n\t\t\tconfig.orbit_center_offset_y;\n\t\t// calculate squared distance from star (0, 0) based on these coordinates\n\t\tsquared_dist = pos_x * pos_x + pos_y * pos_y;\n\n\t\t// calculate equivalent black body temperature based on this squared distance\n\t\tblack_body_temperature = pow((config.star_luminosity * (1 - config.albedo)) /\n\t\t\t(16 * pi * squared_dist * 5.670373e-8), 0.25);\n\n\t\t// calculate an approximated equatorial temperature from the average black body temperature\n\t\tequatorial_black_body_temperatures[t - start_t] = black_body_temperature / cos(pi / 6.0);\n\t}\n\n\t// reused loop variables\n\tdouble latitude, angle_from_vernal_equinox, effective_axial_tilt, effective_latitude,\n\t\theight_to_latitude, effective_tilt_plane_dist, width_at_latitude, plane_dist_radius_ratio,\n\t\textra_logitude, daylight_proportion, radiation_strength, base_temperature, moderated_temperature;\n\n\t// calculate final temperatures based on timestep (angle in orbit) and y position (latitude)\n\tfor (unsigned int y = 0; y < config.area_height; y++)\n\t{\n\t\t// calculate latitude corresponding to y coordinate\n\t\tlatitude = -(((static_cast<double>(y) / static_cast<double>(config.area_height - 1))\n\t\t\t* (90.f - -90.f)) - 90.f);\n\n\t\tfor (unsigned int t = start_t; t < end_t; t++)\n\t\t{\n\t\t\t// calculate orbital angle corresponding to timestep\n\t\t\tangle = (static_cast<double>(t) / static_cast<double>(config.orbital_period)) * 2 * pi;\n\n\t\t\t// calculate effective axial tilt\n\t\t\tangle_from_vernal_equinox = angle + config.orbit_rotation;\n\t\t\teffective_axial_tilt = sin(angle_from_vernal_equinox) * config.axial_tilt;\n\n\t\t\t// calculate effective latitude based on effective axial tilt\n\t\t\teffective_latitude = latitude - effective_axial_tilt;\n\n\t\t\t// calculate the vertical height to the current latitude\n\t\t\theight_to_latitude = sin((latitude / 360.0) * 2 * pi) * config.radius;\n\t\t\t// calculate distance between axially tilted plane and plane\n\t\t\t// dividing day and night, travelling along latitude\n\t\t\teffective_tilt_plane_dist = tan((effective_axial_tilt / 360.0) * 2 * pi) * height_to_latitude;\n\t\t\t// calculate the width of the planet at the current latitude\n\t\t\twidth_at_latitude = max(0., cos((latitude / 360.0) * 2 * pi) * config.radius);\n\t\t\t// calculate a safe ratio of the plane distance to the width at latitude\n\t\t\tplane_dist_radius_ratio = width_at_latitude == 0 ?\n\t\t\t\tboost::math::sign(effective_tilt_plane_dist) :\n\t\t\t\teffective_tilt_plane_dist / width_at_latitude;\n\t\t\t// calculate the extra longitude in or out of daylight\n\t\t\textra_logitude = asin(max(-1.0, (min(1.0, plane_dist_radius_ratio))));\n\t\t\t// calculate the proportion of daylight hours at current latitude and effective tilt\n\t\t\tdaylight_proportion = (pi + 2.0 * extra_logitude) / (2 * pi);\n\n\t\t\t// calculate solar radiation strength at current effective latitude\n\t\t\tradiation_strength = max(0., cos((effective_latitude / 360) * 2 * pi));\n\n\t\t\t// calculate base temperature\n\t\t\tbase_temperature = equatorial_black_body_temperatures[t - start_t]\n\t\t\t\t* radiation_strength * (daylight_proportion * 2);\n\n\t\t\t// calculate moderated temperature to account for convection etc.\n\t\t\tmoderated_temperature = ((base_temperature\n\t\t\t\t- (equatorial_black_body_temperatures[t - start_t] * config.temperature_moderation_bias))\n\t\t\t\t/ config.temperature_moderation_factor) + (equatorial_black_body_temperatures[t - start_t]\n\t\t\t\t\t* config.temperature_moderation_bias);\n\n\t\t\t// calculate final temperature which accounts for greenhouse effect\n\t\t\ttemperatures[y * config.orbital_period + t] = moderated_temperature\n\t\t\t\t* pow((1 + 0.75 * config.atmosphere_optical_thickness), 0.25);\n\t\t}\n\t}\n}\n\n#ifdef GPU_SUPPORT\n// precompute temperatures on the GPU\nvoid GeneticSimulation::Planet::precompute_temperatures_gpu(const Config& config)\n{\n\t// use concurrency namespace for C++ AMP\n\tusing namespace concurrency;\n\n\t// pi\n\tconst float pi = 3.14159f;\n\n\t// initialize vector for storing intermediate equatorial temperature results\n\tvector<float> equatorial_black_body_temperatures(config.orbital_period);\n\t// initialize array view for this vector\n\tarray_view<float, 1> equatorial_black_body_temperatures_av(config.orbital_period,\n\t\tequatorial_black_body_temperatures);\n\t// do not transfer 0s to GPU\n\tequatorial_black_body_temperatures_av.discard_data();\n\n\t// create array view for temperatures lookup table\n\tarray_view<float, 2> temperatures_av(config.area_height, config.orbital_period, temperatures);\n\t// do not transfer 0s to GPU\n\ttemperatures_av.discard_data();\n\n\t// save config values in local variables so AMP can use them\n\tconst unsigned int area_height = config.area_height;\n\tconst float latitude_range = config.latitude_range;\n\tconst unsigned int orbital_period = config.orbital_period;\n\tconst float orbit_center_offset_x = config.orbit_center_offset_x;\n\tconst float orbit_center_offset_y = config.orbit_center_offset_y;\n\tconst float orbit_radius_x = config.orbit_radius_x;\n\tconst float orbit_radius_y = config.orbit_radius_y;\n\tconst float orbit_rotation = config.orbit_rotation;\n\tconst float star_luminosity = config.star_luminosity;\n\tconst float albedo = config.albedo;\n\tconst float axial_tilt = config.axial_tilt;\n\tconst float radius = config.radius;\n\tconst float atmosphere_optical_thickness = config.atmosphere_optical_thickness;\n\tconst float temperature_moderation_factor = config.temperature_moderation_factor;\n\tconst float temperature_moderation_bias = config.temperature_moderation_bias;\n\n\t// kernel to calculate equatorial black body temperatures for each time step\n\tparallel_for_each(\n\t\tequatorial_black_body_temperatures_av.extent,\n\t\t[=](index<1> idx) restrict(amp) {\n\t\t\t// calculate orbital angle corresponding to timestep\n\t\t\tfloat angle = (static_cast<float>(idx[0]) / static_cast<float>(orbital_period)) * 2 * pi;\n\n\t\t\t// calculate the x and y coordinates of the planet at this angle in the orbital ellipse\n\t\t\tfloat pos_x = (orbit_radius_x * fast_math::cos(angle) * fast_math::cos(orbit_rotation)) -\n\t\t\t\t(orbit_radius_y * fast_math::sin(angle) * fast_math::sin(orbit_rotation)) +\n\t\t\t\torbit_center_offset_x;\n\t\t\tfloat pos_y = (orbit_radius_x * fast_math::cos(angle) * fast_math::sin(orbit_rotation)) +\n\t\t\t\t(orbit_radius_y * fast_math::sin(angle) * fast_math::cos(orbit_rotation)) +\n\t\t\t\torbit_center_offset_y;\n\t\t\t// calculate squared distance from star (0, 0) based on these coordinates\n\t\t\tfloat squared_dist = pos_x * pos_x + pos_y * pos_y;\n\n\t\t\t// calculate equivalent black body temperature based on this squared distance\n\t\t\tfloat black_body_temperature = fast_math::pow((star_luminosity * (1 - albedo)) /\n\t\t\t\t(16 * pi * squared_dist * 5.670373e-8), 0.25);\n\n\t\t\t// calculate an approximated equatorial temperature from the average black body temperature\n\t\t\tequatorial_black_body_temperatures_av[idx] = black_body_temperature / fast_math::cos(pi / 6.0);\n\t\t}\n\t);\n\n\t// kernel to calculate final temperatures for each time step and latitude\n\tparallel_for_each(\n\t\ttemperatures_av.extent,\n\t\t[=](index<2> idx) restrict(amp)\n\t\t{\n\t\t\t// calculate latitude corresponding to y coordinate\n\t\t\tfloat latitude = -(((static_cast<float>(idx[0]) / static_cast<float>(area_height - 1))\n\t\t\t\t* (90.f - -90.f)) - 90.f);\n\n\t\t\t// calculate orbital angle corresponding to timestep\n\t\t\tfloat angle = (static_cast<float>(idx[1]) / static_cast<float>(orbital_period)) * 2 * pi;\n\n\t\t\t// calculate effective axial tilt\n\t\t\tfloat angle_from_vernal_equinox = angle + orbit_rotation;\n\t\t\tfloat effective_axial_tilt = fast_math::sin(angle_from_vernal_equinox) * axial_tilt;\n\n\t\t\t// calculate effective latitude based on effective axial tilt\n\t\t\tfloat effective_latitude = latitude - effective_axial_tilt;\n\n\t\t\t// calculate the vertical height to the current latitude\n\t\t\tfloat height_to_latitude = fast_math::sin((latitude / 360.0) * 2 * pi) * radius;\n\t\t\t// calculate distance between axially tilted plane and plane\n\t\t\t// dividing day and night, travelling along latitude\n\t\t\tfloat effective_tilt_plane_dist = fast_math::tan((effective_axial_tilt / 360.0) * 2 * pi) * height_to_latitude;\n\t\t\t// calculate the width of the planet at the current latitude\n\t\t\tfloat width_at_latitude = max(0, fast_math::cos((latitude / 360.0) * 2 * pi) * radius);\n\t\t\t// calculate a safe ratio of the plane distance to the width at latitude\n\t\t\tfloat plane_dist_radius_ratio = width_at_latitude == 0 ?\n\t\t\t\t(0 < effective_tilt_plane_dist) - (effective_tilt_plane_dist < 0) :\n\t\t\t\teffective_tilt_plane_dist / width_at_latitude;\n\t\t\t// calculate the extra longitude in or out of daylight\n\t\t\tfloat extra_logitude = fast_math::asin(max(-1.0, (min(1.0, plane_dist_radius_ratio))));\n\t\t\t// calculate the proportion of daylight hours at current latitude and effective tilt\n\t\t\tfloat daylight_proportion = (pi + 2.0 * extra_logitude) / (2 * pi);\n\n\t\t\t// calculate solar radiation strength at current effective latitude\n\t\t\tfloat radiation_strength = max(0, fast_math::cos((effective_latitude / 360) * 2 * pi));\n\n\t\t\t// save equatorial black body temperature\n\t\t\tfloat equatorial_black_body_temperature = equatorial_black_body_temperatures_av[idx[1]];\n\n\t\t\t// calculate base temperature\n\t\t\tfloat base_temperature = equatorial_black_body_temperature\n\t\t\t\t* radiation_strength * (daylight_proportion * 2);\n\n\t\t\t// calculate moderated temperature to account for convection etc.\n\t\t\tfloat moderated_temperature = ((base_temperature\n\t\t\t\t- (equatorial_black_body_temperature * temperature_moderation_bias))\n\t\t\t\t/ temperature_moderation_factor) + (equatorial_black_body_temperature\n\t\t\t\t\t* temperature_moderation_bias);\n\n\t\t\t// calculate final temperature which accounts for greenhouse effect\n\t\t\ttemperatures_av[idx] = moderated_temperature\n\t\t\t\t* fast_math::pow((1 + 0.75 * atmosphere_optical_thickness), 0.25);\n\t\t}\n\t);\n\n\t// transfer temperature data from GPU\n\ttemperatures_av.synchronize();\n}\n#endif\n\n// benchmark precomputation on the CPU\nvoid GeneticSimulation::Planet::benchmark_temperature_computation_cpu(unsigned int worker_threads, const Config& config)\n{\n\t// time points for benchmarking\n\tsteady_clock::time_point start, end;\n\n\t// allocate space to store results\n\tvector<unsigned long long> times(config.planet_benchmark_samples);\n\n\t// precompute temperatures and record results\n\tfor (unsigned int i = 0; i < config.planet_benchmark_samples; i++) {\n\t\tstart = steady_clock::now();\n\t\tprecompute_temperatures_cpu(worker_threads, config);\n\t\tend = steady_clock::now();\n\t\ttimes[i] = duration_cast<microseconds>(end - start).count();\n\t}\n\n\t// output results to file\n\tstring filename = \"planet_benchmark_cpu_\" + to_string(worker_threads) + \"_threads.csv\";\n\tstring header = \"time_microseconds_\" + to_string(worker_threads) + \" _threads\";\n\twrite_benchmark_results(times, header, filename, config.results_path);\n}\n\n#ifdef GPU_SUPPORT\n// benchmark precomputation on the GPU\nvoid GeneticSimulation::Planet::benchmark_temperature_computation_gpu(const Config& config)\n{\n\t// time points for benchmarking\n\tsteady_clock::time_point start, end;\n\n\t// allocate space to store results\n\tvector<unsigned long long> times(config.planet_benchmark_samples);\n\n\t// precompute temperatures and record results\n\tfor (unsigned int i = 0; i < config.planet_benchmark_samples; i++) {\n\t\tstart = steady_clock::now();\n\t\tprecompute_temperatures_gpu(config);\n\t\tend = steady_clock::now();\n\t\ttimes[i] = duration_cast<microseconds>(end - start).count();\n\t}\n\n\t// output results to file\n\tstring filename = \"planet_benchmark_gpu.csv\";\n\tstring header = \"time_microseconds_gpu\";\n\twrite_benchmark_results(times, header, filename, config.results_path);\n}\n#endif", "meta": {"hexsha": "485663629ee84fed0d6653a593429f932880b940", "size": 15437, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Planet.cpp", "max_stars_repo_name": "connorcl/genetic-simulation", "max_stars_repo_head_hexsha": "0af17ad6645f16817b2855a20ff81b07750d2377", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Planet.cpp", "max_issues_repo_name": "connorcl/genetic-simulation", "max_issues_repo_head_hexsha": "0af17ad6645f16817b2855a20ff81b07750d2377", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Planet.cpp", "max_forks_repo_name": "connorcl/genetic-simulation", "max_forks_repo_head_hexsha": "0af17ad6645f16817b2855a20ff81b07750d2377", "max_forks_repo_licenses": ["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.6091644205, "max_line_length": 142, "alphanum_fraction": 0.761287815, "num_tokens": 3779, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971190859164, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.49085442326263223}}
{"text": "#include <fmt/core.h>\n#include <string_view>\n#include <chrono>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n#include <autodiff/forward/real.hpp>\n#include <autodiff/forward/real/eigen.hpp>\n\n#include \"types.hh\"\n#include \"cvode_wrapper.hh\"\n\nusing namespace types;\n\nstruct System\n{\n    template<class T>\n    inline auto f(Eigen::MatrixBase<T>& y, double t)\n    {\n        using mt = T::PlainObject;\n        mt ydot(y.rows());\n\n        ydot(0) = -0.04*y(0) + 1.0E4*y(1)*y(2);\n        ydot(2) = 3.0E7*y(1)*y(1);\n        ydot(1) = -ydot(0) - ydot(2);\n\n        return ydot;\n    }\n\n    template<class T>\n    inline auto J(Eigen::MatrixBase<T>& y, double t)\n    {\n        auto _f = [this](auto&& ...args){ return f(std::forward<decltype(args)>(args)...); };\n        dvector_t dydt(y.size());\n        dvector_t yy = y;\n        matrix_t J = autodiff::jacobian(_f, autodiff::wrt(yy), autodiff::at(yy,t), dydt);\n        return J;\n    }\n};\n\nint main()\n{\n\n    vector_t y0(3);\n    y0(0) = 1.0; y0(1) = 0.0; y0(2) = 0.0;\n\n    auto stepper = cvode_wrapper::cvode_stepper<System>(cvode_wrapper::cv_options{});\n    stepper.initialize(y0);\n\n    stepper.letsgo();\n    return 0;\n}", "meta": {"hexsha": "ea7a848722a9f060ca0ad4868c2def94d88bcc35", "size": 1157, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/main.cc", "max_stars_repo_name": "cmauney/sundials_eigen", "max_stars_repo_head_hexsha": "88a2b8c894da3ed144dfab95cc4e5988e8b7f167", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/main.cc", "max_issues_repo_name": "cmauney/sundials_eigen", "max_issues_repo_head_hexsha": "88a2b8c894da3ed144dfab95cc4e5988e8b7f167", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/main.cc", "max_forks_repo_name": "cmauney/sundials_eigen", "max_forks_repo_head_hexsha": "88a2b8c894da3ed144dfab95cc4e5988e8b7f167", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.8301886792, "max_line_length": 93, "alphanum_fraction": 0.5842696629, "num_tokens": 379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695292107347, "lm_q2_score": 0.546738151984614, "lm_q1q2_score": 0.4908042650520591}}
{"text": "#pragma once\n#include <Eigen/Core>\n#include <cppad/cppad.hpp>\n#include <limits>\n\nnamespace Eigen {\n\ntemplate <class Base>\nstruct NumTraits<CppAD::AD<Base>> {\n    // type that corresponds to the real part of an AD<Base> value\n    typedef CppAD::AD<Base> Real;\n    // type for AD<Base> operations that result in non-integer values\n    typedef CppAD::AD<Base> NonInteger;\n    //  type to use for numeric literals such as \"2\" or \"0.5\".\n    typedef CppAD::AD<Base> Literal;\n    // type for nested value inside an AD<Base> expression tree\n    typedef CppAD::AD<Base> Nested;\n\n    enum {\n        // does not support complex Base types\n        IsComplex             = 0 ,\n        // does not support integer Base types\n        IsInteger             = 0 ,\n        // only support signed Base types\n        IsSigned              = 1 ,\n        // must initialize an AD<Base> object\n        RequireInitialization = 1 ,\n        // computational cost of the corresponding operations\n        ReadCost              = 1 ,\n        AddCost               = 2 ,\n        MulCost               = 2\n    };\n\n    // machine epsilon with type of real part of x\n    // (use assumption that Base is not complex)\n    static CppAD::AD<Base> epsilon(void)\n    {\n        return CppAD::numeric_limits<CppAD::AD<Base>>::epsilon();\n    }\n\n    // relaxed version of machine epsilon for comparison of different\n    // operations that should result in the same value\n    static CppAD::AD<Base> dummy_precision(void)\n    {\n        return 100. * CppAD::numeric_limits<CppAD::AD<Base>>::epsilon();\n    }\n\n    // minimum normalized positive value\n    static CppAD::AD<Base> lowest(void)\n    {\n        return CppAD::numeric_limits< CppAD::AD<Base> >::min();\n    }\n\n    // maximum finite value\n    static CppAD::AD<Base> highest(void)\n    {\n        return CppAD::numeric_limits< CppAD::AD<Base> >::max();\n    }\n\n    // number of decimal digits that can be represented without change.\n    static int digits10(void)\n    {\n        return CppAD::numeric_limits< CppAD::AD<Base> >::digits10;\n    }\n};\n\n}\n\nnamespace CppAD {\n\n// functions that return references\ntemplate <class Base>\nconst AD<Base>& conj(const AD<Base>& x) { return x; }\ntemplate <class Base>\nconst AD<Base>& real(const AD<Base>& x) { return x; }\n\n// functions that return values (note abs is defined by cppad.hpp)\ntemplate <class Base> AD<Base>\nimag(const AD<Base>& x) { return CppAD::AD<Base>(0.); }\ntemplate <class Base> AD<Base>\nabs2(const AD<Base>& x) { return x * x; }\n\n}\n\ntemplate <typename Type>\nEigen::Matrix<Type, 3, 3> exp3x3AD(const Eigen::Matrix<Type, 3, 1>& ax)\n{\n    Eigen::Matrix<Type, 3, 3> out;\n    out.setZero();\n    Type angle = CppAD::sqrt(ax.dot(ax));\n    if (CppAD::abs(angle) < std::numeric_limits<double>::epsilon()) {\n        out(0, 0) = Type(1);\n        out(1, 1) = Type(1);\n        out(2, 2) = Type(1);\n    } else {\n        Type x = ax(0) / angle;\n        Type y = ax(1) / angle;\n        Type z = ax(2) / angle;\n        Type sa = CppAD::sin(angle);\n        Type ca = CppAD::cos(angle);\n        Type t = 1 - ca;\n\n        out(0, 0) = ca + t * x * x;\n        out(1, 0) = t * y * x + sa * z;\n        out(2, 0) = t * z * x - sa * y;\n        out(0, 1) = t * x * y - sa * z;\n        out(1, 1) = ca + t * y * y;\n        out(2, 1) = t * z * y + sa * x;\n        out(0, 2) = t * x * z + sa * y;\n        out(1, 2) = t * y * z - sa * x;\n        out(2, 2) = ca + t * z * z;\n    }\n\n    return out;\n}\n", "meta": {"hexsha": "7f5247fd3a1560771cc2a555e287200c3cdf5583", "size": 3428, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "algo_v0/EigenAD.hpp", "max_stars_repo_name": "vsamy/cdm", "max_stars_repo_head_hexsha": "f2d29cad0a2b349d2b6f732ab786791c35a6b509", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-08-16T11:41:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-04T16:48:29.000Z", "max_issues_repo_path": "algo_v0/EigenAD.hpp", "max_issues_repo_name": "vsamy/cdm", "max_issues_repo_head_hexsha": "f2d29cad0a2b349d2b6f732ab786791c35a6b509", "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": "algo_v0/EigenAD.hpp", "max_forks_repo_name": "vsamy/cdm", "max_forks_repo_head_hexsha": "f2d29cad0a2b349d2b6f732ab786791c35a6b509", "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.5517241379, "max_line_length": 72, "alphanum_fraction": 0.5670945158, "num_tokens": 987, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4907584505304911}}
{"text": "#include \"odoflow/RigidEstimator.h\"\n#include \"camplex/FiducialCommon.h\"\n#include \"argus_utils/utils/ParamUtils.h\"\n\n#include <opencv2/calib3d.hpp>\n#include <Eigen/SVD>\n\nnamespace argus\n{\nRigidEstimator::RigidEstimator( ros::NodeHandle& nh, ros::NodeHandle& ph )\n{\n\t_logReprojThreshold.Initialize( ph, -2,\n\t                                \"log_reprojection_threshold\",\n\t                                \"RANSAC log10 reprojection inlier threshold\" );\n\n\t_maxIters.Initialize( ph, 10, \"max_iters\",\n\t                      \"RANSAC max iterations\" );\n\t_maxIters.AddCheck<GreaterThan>( 0 );\n\t_maxIters.AddCheck<IntegerValued>( ROUND_CEIL );\n}\n\nbool RigidEstimator::EstimateMotion( InterestPoints& key,\n                                     InterestPoints& tar,\n\t\t\t\t\t\t\t\t\t std::vector<unsigned int>& inlierInds,\n                                     PoseSE2& transform  )\n{\n\tif( key.empty() || tar.empty() )\n\t{\n\t\tROS_INFO_STREAM( \"RigidEstimator: Received empty points.\" );\n\t\treturn false;\n\t}\n\n\tstd::vector<char> inliers;\n\t// We want tar in frame of key, so this is the ordering\n\tcv::Mat Hxest = cv::findHomography( tar,\n\t                                    key,\n\t                                    cv::RANSAC,\n\t                                    std::pow( 10, _logReprojThreshold ),\n\t                                    inliers,\n\t                                    _maxIters );\n\tif( Hxest.empty() )\n\t{\n\t\tROS_INFO_STREAM( \"RigidEstimator: Failed to find homography.\" );\n\t\treturn false;\n\t}\n\n\tInterestPoints keyInliers, tarInliers;\n\tfor( unsigned int i = 0; i < inliers.size(); i++ )\n\t{\n\t\tif( inliers[i] )\n\t\t{\n\t\t\tinlierInds.push_back(i);\n\t\t}\n\t}\n\n\tEigen::MatrixXd Ab = MatToEigen<double>( Hxest );\n\n\t// Extract the rotation using Procrustes solution\n\tEigen::Matrix2d A = Ab.block<2, 2>( 0, 0 );\n\tEigen::JacobiSVD<Eigen::Matrix2d> svd( A, Eigen::ComputeFullU | Eigen::ComputeFullV );\n\tEigen::Matrix2d R = svd.matrixU() * svd.matrixV().transpose();\n\n\t// NOTE We use standard coordinates (x-forward)\n\tFixedMatrixType<3, 3> H = FixedMatrixType<3, 3>::Identity();\n\tH.block<2, 2>( 1, 1 ) = R;\n\tH( 1, 2 ) = -Ab( 0, 2 ); // Image x corresponds to camera -y\n\tH( 2, 2 ) = -Ab( 1, 2 ); // Image y corresponds to camera -z\n\ttransform = PoseSE2( H );\n\treturn true;\n}\n}\n", "meta": {"hexsha": "8468129f3e04da89976166977976d822bd37685b", "size": 2243, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "odoflow/src/RigidEstimator.cpp", "max_stars_repo_name": "Humhu/argus", "max_stars_repo_head_hexsha": "8b112382038c6df1ecf15d9c872b6cc9b471cd22", "max_stars_repo_licenses": ["AFL-3.0"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2017-08-02T20:32:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-15T09:33:33.000Z", "max_issues_repo_path": "odoflow/src/RigidEstimator.cpp", "max_issues_repo_name": "Humhu/argus", "max_issues_repo_head_hexsha": "8b112382038c6df1ecf15d9c872b6cc9b471cd22", "max_issues_repo_licenses": ["AFL-3.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-03-12T22:57:59.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-13T02:52:36.000Z", "max_forks_repo_path": "odoflow/src/RigidEstimator.cpp", "max_forks_repo_name": "Humhu/argus", "max_forks_repo_head_hexsha": "8b112382038c6df1ecf15d9c872b6cc9b471cd22", "max_forks_repo_licenses": ["AFL-3.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2017-03-25T08:36:17.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-23T00:28:16.000Z", "avg_line_length": 31.1527777778, "max_line_length": 87, "alphanum_fraction": 0.5844850646, "num_tokens": 632, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4907584444785335}}
{"text": "//\n// Copyright (c) 2015-2018 CNRS\n//\n\n#include \"pinocchio/multibody/model.hpp\"\n#include \"pinocchio/multibody/data.hpp\"\n#include \"pinocchio/algorithm/jacobian.hpp\"\n#include \"pinocchio/algorithm/crba.hpp\"\n#include \"pinocchio/algorithm/rnea.hpp\"\n#include \"pinocchio/algorithm/center-of-mass.hpp\"\n#include \"pinocchio/utils/timer.hpp\"\n#include \"pinocchio/parsers/sample-models.hpp\"\n\n#include <iostream>\n\n#include <boost/test/unit_test.hpp>\n#include <boost/utility/binary.hpp>\n\nBOOST_AUTO_TEST_SUITE ( BOOST_TEST_MODULE )\n\nBOOST_AUTO_TEST_CASE ( test_com )\n{\n  using namespace Eigen;\n  using namespace pinocchio;\n\n  pinocchio::Model model;\n  pinocchio::buildModels::humanoidRandom(model);\n  pinocchio::Data data(model);\n\n  VectorXd q = VectorXd::Ones(model.nq);\n  q.middleRows<4> (3).normalize();\n  VectorXd v = VectorXd::Ones(model.nv);\n  VectorXd a = VectorXd::Ones(model.nv);\n  \n  crba(model,data,q);\n  \n\n\t/* Test COM against CRBA*/\n  Vector3d com = centerOfMass(model,data,q);\n  BOOST_CHECK(data.com[0].isApprox(getComFromCrba(model,data), 1e-12));\n\n\t/* Test COM against Jcom (both use different way to compute the COM). */\n  com = centerOfMass(model,data,q);\n  jacobianCenterOfMass(model,data,q);\n  BOOST_CHECK(com.isApprox(data.com[0], 1e-12));\n\n\t/* Test COM against Jcom (both use different way to compute the COM). */\n  centerOfMass(model,data,q,v,a);\n  BOOST_CHECK(com.isApprox(data.com[0], 1e-12));\n\n  /* Test vCoM against nle algorithm without gravity field */\n  a.setZero();\n  model.gravity.setZero();\n  centerOfMass(model,data,q,v,a);\n  nonLinearEffects(model, data, q, v);\n  \n  pinocchio::SE3::Vector3 acom_from_nle (data.nle.head <3> ()/data.mass[0]);\n  BOOST_CHECK((data.liMi[1].rotation() * acom_from_nle).isApprox(data.acom[0], 1e-12));\n\n\t/* Test Jcom against CRBA  */\n  Eigen::MatrixXd Jcom = jacobianCenterOfMass(model,data,q);\n  BOOST_CHECK(data.Jcom.isApprox(getJacobianComFromCrba(model,data), 1e-12));\n\n  /* Test CoM velocity againt jacobianCenterOfMass */\n  BOOST_CHECK((Jcom * v).isApprox(data.vcom[0], 1e-12));\n  \n  \n  centerOfMass(model,data,q,v);\n  /* Test CoM velocity againt jacobianCenterOfMass */\n  BOOST_CHECK((Jcom * v).isApprox(data.vcom[0], 1e-12));\n\n\n//  std::cout << \"com = [ \" << data.com[0].transpose() << \" ];\" << std::endl;\n//  std::cout << \"mass = [ \" << data.mass[0] << \" ];\" << std::endl;\n//  std::cout << \"Jcom = [ \" << data.Jcom << \" ];\" << std::endl;\n//  std::cout << \"M3 = [ \" << data.M.topRows<3>() << \" ];\" << std::endl;\n}\n\nBOOST_AUTO_TEST_CASE ( test_mass )\n{\n  using namespace Eigen;\n  using namespace pinocchio;\n\n  pinocchio::Model model;\n  pinocchio::buildModels::humanoidRandom(model);\n\n  double mass = computeTotalMass(model);\n\n  BOOST_CHECK(mass == mass); // checking it is not NaN\n\n  double mass_check = 0.0;\n  for(size_t i=1; i<(size_t)(model.njoints);++i)\n    mass_check += model.inertias[i].mass();\n\n  BOOST_CHECK_CLOSE(mass, mass_check, 1e-12);\n\n  pinocchio::Data data1(model);\n\n  double mass_data = computeTotalMass(model,data1);\n\n  BOOST_CHECK(mass_data == mass_data); // checking it is not NaN\n  BOOST_CHECK_CLOSE(mass, mass_data, 1e-12);\n  BOOST_CHECK_CLOSE(data1.mass[0], mass_data, 1e-12);\n\n  pinocchio::Data data2(model);\n  VectorXd q = VectorXd::Ones(model.nq);\n  q.middleRows<4> (3).normalize();\n  centerOfMass(model,data2,q);\n\n  BOOST_CHECK_CLOSE(data2.mass[0], mass, 1e-12);\n}\n\nBOOST_AUTO_TEST_CASE ( test_subtree_masses )\n{\n  using namespace Eigen;\n  using namespace pinocchio;\n\n  pinocchio::Model model;\n  pinocchio::buildModels::humanoidRandom(model);\n\n  pinocchio::Data data1(model);\n\n  computeSubtreeMasses(model,data1);\n\n  pinocchio::Data data2(model);\n  VectorXd q = VectorXd::Ones(model.nq);\n  q.middleRows<4> (3).normalize();\n  centerOfMass(model,data2,q);\n\n  for(size_t i=0; i<(size_t)(model.njoints);++i)\n  {\n    BOOST_CHECK_CLOSE(data1.mass[i], data2.mass[i], 1e-12);\n  }\n}\n\n//BOOST_AUTO_TEST_CASE ( test_timings )\n//{\n//  using namespace Eigen;\n//  using namespace pinocchio;\n//\n//  pinocchio::Model model;\n//  pinocchio::buildModels::humanoidRandom(model);\n//  pinocchio::Data data(model);\n//\n//  long flag = BOOST_BINARY(1111);\n//  PinocchioTicToc timer(PinocchioTicToc::US); \n//  #ifdef NDEBUG\n//    #ifdef _INTENSE_TESTING_\n//      const size_t NBT = 1000*1000;\n//    #else\n//      const size_t NBT = 10;\n//    #endif\n//  #else \n//    const size_t NBT = 1;\n//    std::cout << \"(the time score in debug mode is not relevant)  \" ;\n//  #endif\n//\n//  bool verbose = flag & (flag-1) ; // True is two or more binaries of the flag are 1.\n//  if(verbose) std::cout <<\"--\" << std::endl;\n//  Eigen::VectorXd q = Eigen::VectorXd::Zero(model.nq);\n//\n//  if( flag >> 0 & 1 )\n//  {\n//    timer.tic();\n//    SMOOTH(NBT)\n//    {\n//      centerOfMass(model,data,q);\n//    }\n//    if(verbose) std::cout << \"COM =\\t\";\n//    timer.toc(std::cout,NBT);\n//  }\n//\n//  if( flag >> 1 & 1 )\n//  {\n//    timer.tic();\n//    SMOOTH(NBT)\n//    {\n//      centerOfMass(model,data,q,false);\n//    }\n//    if(verbose) std::cout << \"Without sub-tree =\\t\";\n//    timer.toc(std::cout,NBT);\n//  }\n//  \n//  if( flag >> 2 & 1 )\n//  {\n//    timer.tic();\n//    SMOOTH(NBT)\n//    {\n//      jacobianCenterOfMass(model,data,q);\n//    }\n//    if(verbose) std::cout << \"Jcom =\\t\";\n//    timer.toc(std::cout,NBT);\n//  }\n//}\n\nBOOST_AUTO_TEST_SUITE_END ()\n", "meta": {"hexsha": "9811fd0a89ec631cf065d376bf1a8f96fd132e97", "size": 5292, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittest/com.cpp", "max_stars_repo_name": "mkatliar/pinocchio", "max_stars_repo_head_hexsha": "b755b9cf2567eab39de30a68b2a80fac802a4042", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "unittest/com.cpp", "max_issues_repo_name": "mkatliar/pinocchio", "max_issues_repo_head_hexsha": "b755b9cf2567eab39de30a68b2a80fac802a4042", "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": "unittest/com.cpp", "max_forks_repo_name": "mkatliar/pinocchio", "max_forks_repo_head_hexsha": "b755b9cf2567eab39de30a68b2a80fac802a4042", "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": 26.8629441624, "max_line_length": 87, "alphanum_fraction": 0.6538170824, "num_tokens": 1650, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4907584444785335}}
{"text": "// boost1.67-1.67.0/libs/graph/example/r_c_shortest_paths_example.cpp\n\n// Copyright Michael Drexl 2005, 2006.\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt or copy at\n// http://boost.org/LICENSE_1_0.txt)\n\n// Example use of the resource-constrained shortest paths algorithm.\n#include <boost/config.hpp>\n\n#ifdef BOOST_MSVC\n#pragma warning(disable : 4267)\n#endif\n\n#include <boost/graph/adjacency_list.hpp>\n\n#include <boost/graph/r_c_shortest_paths.hpp>\n#include <iostream>\n\nusing namespace boost;\n\nstruct SPPRC_Example_Graph_Vert_Prop\n{\n  SPPRC_Example_Graph_Vert_Prop(int n = 0, int e = 0, int l = 0)\n      : num(n), eat(e), lat(l) {}\n  int num;\n  // earliest arrival time\n  int eat;\n  // latest arrival time\n  int lat;\n};\n\nstruct SPPRC_Example_Graph_Arc_Prop\n{\n  SPPRC_Example_Graph_Arc_Prop(int n = 0, int c = 0, int t = 0)\n      : num(n), cost(c), time(t) {}\n  int num;\n  // traversal cost\n  int cost;\n  // traversal time\n  int time;\n};\n\ntypedef adjacency_list<vecS,\n                       vecS,\n                       directedS,\n                       SPPRC_Example_Graph_Vert_Prop,\n                       SPPRC_Example_Graph_Arc_Prop>\n    SPPRC_Example_Graph;\n\n// data structures for spp without resource constraints:\n// ResourceContainer model\nstruct spp_no_rc_res_cont\n{\n  spp_no_rc_res_cont(int c = 0) : cost(c){};\n  spp_no_rc_res_cont &operator=(const spp_no_rc_res_cont &other)\n  {\n    if (this == &other)\n      return *this;\n    this->~spp_no_rc_res_cont();\n    new (this) spp_no_rc_res_cont(other);\n    return *this;\n  }\n  int cost;\n};\n\nbool operator==(const spp_no_rc_res_cont &res_cont_1,\n                const spp_no_rc_res_cont &res_cont_2)\n{\n  return (res_cont_1.cost == res_cont_2.cost);\n}\n\nbool operator<(const spp_no_rc_res_cont &res_cont_1,\n               const spp_no_rc_res_cont &res_cont_2)\n{\n  return (res_cont_1.cost < res_cont_2.cost);\n}\n\n// ResourceExtensionFunction model\nclass ref_no_res_cont\n{\npublic:\n  inline bool operator()(const SPPRC_Example_Graph &g,\n                         spp_no_rc_res_cont &new_cont,\n                         const spp_no_rc_res_cont &old_cont,\n                         graph_traits<SPPRC_Example_Graph>::edge_descriptor ed) const\n  {\n    new_cont.cost = old_cont.cost + g[ed].cost;\n    return true;\n  }\n};\n\n// DominanceFunction model\nclass dominance_no_res_cont\n{\npublic:\n  inline bool operator()(const spp_no_rc_res_cont &res_cont_1,\n                         const spp_no_rc_res_cont &res_cont_2) const\n  {\n    // must be \"<=\" here!!!\n    // must NOT be \"<\"!!!\n    return res_cont_1.cost <= res_cont_2.cost;\n    // this is not a contradiction to the documentation\n    // the documentation says:\n    // \"A label $l_1$ dominates a label $l_2$ if and only if both are resident\n    // at the same vertex, and if, for each resource, the resource consumption\n    // of $l_1$ is less than or equal to the resource consumption of $l_2$,\n    // and if there is at least one resource where $l_1$ has a lower resource\n    // consumption than $l_2$.\"\n    // one can think of a new label with a resource consumption equal to that\n    // of an old label as being dominated by that old label, because the new\n    // one will have a higher number and is created at a later point in time,\n    // so one can implicitly use the number or the creation time as a resource\n    // for tie-breaking\n  }\n};\n// end data structures for spp without resource constraints:\n\n// data structures for shortest path problem with time windows (spptw)\n// ResourceContainer model\nstruct spp_spptw_res_cont\n{\n  spp_spptw_res_cont(int c = 0, int t = 0) : cost(c), time(t) {}\n  spp_spptw_res_cont &operator=(const spp_spptw_res_cont &other)\n  {\n    if (this == &other)\n      return *this;\n    this->~spp_spptw_res_cont();\n    new (this) spp_spptw_res_cont(other);\n    return *this;\n  }\n  int cost;\n  int time;\n};\n\nbool operator==(const spp_spptw_res_cont &res_cont_1,\n                const spp_spptw_res_cont &res_cont_2)\n{\n  return (res_cont_1.cost == res_cont_2.cost && res_cont_1.time == res_cont_2.time);\n}\n\nbool operator<(const spp_spptw_res_cont &res_cont_1,\n               const spp_spptw_res_cont &res_cont_2)\n{\n  if (res_cont_1.cost > res_cont_2.cost)\n    return false;\n  if (res_cont_1.cost == res_cont_2.cost)\n    return res_cont_1.time < res_cont_2.time;\n  return true;\n}\n\n// ResourceExtensionFunction model\nclass ref_spptw\n{\npublic:\n  inline bool operator()(const SPPRC_Example_Graph &g,\n                         spp_spptw_res_cont &new_cont,\n                         const spp_spptw_res_cont &old_cont,\n                         graph_traits<SPPRC_Example_Graph>::edge_descriptor ed) const\n  {\n    const SPPRC_Example_Graph_Arc_Prop &arc_prop =\n        get(edge_bundle, g)[ed];\n    const SPPRC_Example_Graph_Vert_Prop &vert_prop =\n        get(vertex_bundle, g)[target(ed, g)];\n    new_cont.cost = old_cont.cost + arc_prop.cost;\n    int &i_time = new_cont.time;\n    i_time = old_cont.time + arc_prop.time;\n    i_time < vert_prop.eat ? i_time = vert_prop.eat : 0;\n    return i_time <= vert_prop.lat ? true : false;\n  }\n};\n\n// DominanceFunction model\nclass dominance_spptw\n{\npublic:\n  inline bool operator()(const spp_spptw_res_cont &res_cont_1,\n                         const spp_spptw_res_cont &res_cont_2) const\n  {\n    // must be \"<=\" here!!!\n    // must NOT be \"<\"!!!\n    return res_cont_1.cost <= res_cont_2.cost && res_cont_1.time <= res_cont_2.time;\n    // this is not a contradiction to the documentation\n    // the documentation says:\n    // \"A label $l_1$ dominates a label $l_2$ if and only if both are resident\n    // at the same vertex, and if, for each resource, the resource consumption\n    // of $l_1$ is less than or equal to the resource consumption of $l_2$,\n    // and if there is at least one resource where $l_1$ has a lower resource\n    // consumption than $l_2$.\"\n    // one can think of a new label with a resource consumption equal to that\n    // of an old label as being dominated by that old label, because the new\n    // one will have a higher number and is created at a later point in time,\n    // so one can implicitly use the number or the creation time as a resource\n    // for tie-breaking\n  }\n};\n// end data structures for shortest path problem with time windows (spptw)\n\n// example graph structure and cost from\n// http://www.boost.org/libs/graph/example/dijkstra-example.cpp\nenum nodes\n{\n  A,\n  B,\n  C,\n  D,\n  E\n};\nchar name[] = \"ABCDE\";\n\nint main()\n{\n  SPPRC_Example_Graph g;\n\n  add_vertex(SPPRC_Example_Graph_Vert_Prop(A, 0, 0), g);\n  add_vertex(SPPRC_Example_Graph_Vert_Prop(B, 5, 20), g);\n  add_vertex(SPPRC_Example_Graph_Vert_Prop(C, 6, 10), g);\n  add_vertex(SPPRC_Example_Graph_Vert_Prop(D, 3, 12), g);\n  add_vertex(SPPRC_Example_Graph_Vert_Prop(E, 0, 100), g);\n\n  add_edge(A, C, SPPRC_Example_Graph_Arc_Prop(0, 1, 5), g);\n  add_edge(B, B, SPPRC_Example_Graph_Arc_Prop(1, 2, 5), g);\n  add_edge(B, D, SPPRC_Example_Graph_Arc_Prop(2, 1, 2), g);\n  add_edge(B, E, SPPRC_Example_Graph_Arc_Prop(3, 2, 7), g);\n  add_edge(C, B, SPPRC_Example_Graph_Arc_Prop(4, 7, 3), g);\n  add_edge(C, D, SPPRC_Example_Graph_Arc_Prop(5, 3, 8), g);\n  add_edge(D, E, SPPRC_Example_Graph_Arc_Prop(6, 1, 3), g);\n  add_edge(E, A, SPPRC_Example_Graph_Arc_Prop(7, 1, 5), g);\n  add_edge(E, B, SPPRC_Example_Graph_Arc_Prop(8, 1, 4), g);\n\n  // the unique shortest path from A to E in the dijkstra-example.cpp is\n  // A -> C -> D -> E\n  // its length is 5\n  // the following code also yields this result\n\n  // with the above time windows, this path is infeasible\n  // now, there are two shortest paths that are also feasible with respect to\n  // the vertex time windows:\n  // A -> C -> B -> D -> E and\n  // A -> C -> B -> E\n  // however, the latter has a longer total travel time and is therefore not\n  // pareto-optimal, i.e., it is dominated by the former path\n  // therefore, the code below returns only the former path\n\n  // spp without resource constraints\n  graph_traits<SPPRC_Example_Graph>::vertex_descriptor s = A;\n  graph_traits<SPPRC_Example_Graph>::vertex_descriptor t = E;\n\n  std::vector<std::vector<graph_traits<SPPRC_Example_Graph>::edge_descriptor>>\n      opt_solutions;\n  std::vector<spp_no_rc_res_cont> pareto_opt_rcs_no_rc;\n\n  r_c_shortest_paths(g,\n                     get(&SPPRC_Example_Graph_Vert_Prop::num, g),\n                     get(&SPPRC_Example_Graph_Arc_Prop::num, g),\n                     s,\n                     t,\n                     opt_solutions,\n                     pareto_opt_rcs_no_rc,\n                     spp_no_rc_res_cont(0),\n                     ref_no_res_cont(),\n                     dominance_no_res_cont(),\n                     std::allocator<r_c_shortest_paths_label<SPPRC_Example_Graph, spp_no_rc_res_cont>>(),\n                     default_r_c_shortest_paths_visitor());\n\n  std::cout << \"SPP without resource constraints:\" << std::endl;\n  std::cout << \"Number of optimal solutions: \";\n  std::cout << static_cast<int>(opt_solutions.size()) << std::endl;\n  for (int i = 0; i < static_cast<int>(opt_solutions.size()); ++i)\n  {\n    std::cout << \"The \" << i << \"th shortest path from A to E is: \";\n    std::cout << std::endl;\n    for (int j = static_cast<int>(opt_solutions[i].size()) - 1; j >= 0; --j)\n      std::cout << name[source(opt_solutions[i][j], g)] << std::endl;\n    std::cout << \"E\" << std::endl;\n    std::cout << \"Length: \" << pareto_opt_rcs_no_rc[i].cost << std::endl;\n  }\n  std::cout << std::endl;\n\n  // spptw\n  std::vector<std::vector<graph_traits<SPPRC_Example_Graph>::edge_descriptor>>\n      opt_solutions_spptw;\n  std::vector<spp_spptw_res_cont> pareto_opt_rcs_spptw;\n\n  r_c_shortest_paths(g,\n                     get(&SPPRC_Example_Graph_Vert_Prop::num, g),\n                     get(&SPPRC_Example_Graph_Arc_Prop::num, g),\n                     s,\n                     t,\n                     opt_solutions_spptw,\n                     pareto_opt_rcs_spptw,\n                     spp_spptw_res_cont(0, 0),\n                     ref_spptw(),\n                     dominance_spptw(),\n                     std::allocator<r_c_shortest_paths_label<SPPRC_Example_Graph, spp_spptw_res_cont>>(),\n                     default_r_c_shortest_paths_visitor());\n\n  std::cout << \"SPP with time windows:\" << std::endl;\n  std::cout << \"Number of optimal solutions: \";\n  std::cout << static_cast<int>(opt_solutions.size()) << std::endl;\n  for (int i = 0; i < static_cast<int>(opt_solutions.size()); ++i)\n  {\n    std::cout << \"The \" << i << \"th shortest path from A to E is: \";\n    std::cout << std::endl;\n    for (int j = static_cast<int>(opt_solutions_spptw[i].size()) - 1;\n         j >= 0;\n         --j)\n      std::cout << name[source(opt_solutions_spptw[i][j], g)] << std::endl;\n    std::cout << \"E\" << std::endl;\n    std::cout << \"Length: \" << pareto_opt_rcs_spptw[i].cost << std::endl;\n    std::cout << \"Time: \" << pareto_opt_rcs_spptw[i].time << std::endl;\n  }\n\n  // utility function check_r_c_path example\n  std::cout << std::endl;\n  bool b_is_a_path_at_all = false;\n  bool b_feasible = false;\n  bool b_correctly_extended = false;\n  spp_spptw_res_cont actual_final_resource_levels(0, 0);\n  graph_traits<SPPRC_Example_Graph>::edge_descriptor ed_last_extended_arc;\n  check_r_c_path(g,\n                 opt_solutions_spptw[0],\n                 spp_spptw_res_cont(0, 0),\n                 true,\n                 pareto_opt_rcs_spptw[0],\n                 actual_final_resource_levels,\n                 ref_spptw(),\n                 b_is_a_path_at_all,\n                 b_feasible,\n                 b_correctly_extended,\n                 ed_last_extended_arc);\n  if (!b_is_a_path_at_all)\n    std::cout << \"Not a path.\" << std::endl;\n  if (!b_feasible)\n    std::cout << \"Not a feasible path.\" << std::endl;\n  if (!b_correctly_extended)\n    std::cout << \"Not correctly extended.\" << std::endl;\n  if (b_is_a_path_at_all && b_feasible && b_correctly_extended)\n  {\n    std::cout << \"Actual final resource levels:\" << std::endl;\n    std::cout << \"Length: \" << actual_final_resource_levels.cost << std::endl;\n    std::cout << \"Time: \" << actual_final_resource_levels.time << std::endl;\n    std::cout << \"OK.\" << std::endl;\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "934f05b780d40fc49ad8f3612e5dc66bcd1e48e5", "size": 12171, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "debian/tests/srcs/graph/demo3.cpp", "max_stars_repo_name": "lliurex/boost1.67", "max_stars_repo_head_hexsha": "bab6eba0e7ac4a0232bc0bcab501f1b447ddfdd5", "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": "debian/tests/srcs/graph/demo3.cpp", "max_issues_repo_name": "lliurex/boost1.67", "max_issues_repo_head_hexsha": "bab6eba0e7ac4a0232bc0bcab501f1b447ddfdd5", "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": "debian/tests/srcs/graph/demo3.cpp", "max_forks_repo_name": "lliurex/boost1.67", "max_forks_repo_head_hexsha": "bab6eba0e7ac4a0232bc0bcab501f1b447ddfdd5", "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.974137931, "max_line_length": 105, "alphanum_fraction": 0.6473584751, "num_tokens": 3453, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4907584444785335}}
{"text": "// This file is part of libigl, a simple c++ geometry processing library.\n// \n// Copyright (C) 2013 Alec Jacobson <alecjacobson@gmail.com>\n// \n// This Source Code Form is subject to the terms of the Mozilla Public License \n// v. 2.0. If a copy of the MPL was not distributed with this file, You can \n// obtain one at http://mozilla.org/MPL/2.0/.\n#include \"lu_lagrange.h\"\n\n// Cholesky LLT decomposition for symmetric positive definite\n//#include <Eigen/SparseExtra>\n// Bug in unsupported/Eigen/SparseExtra needs iostream first\n#include <iostream>\n#include <unsupported/Eigen/SparseExtra>\n#include <cassert>\n#include <cstdio>\n#include \"find.h\"\n#include \"sparse.h\"\n\ntemplate <typename T>\nIGL_INLINE bool igl::lu_lagrange(\n  const Eigen::SparseMatrix<T> & ATA,\n  const Eigen::SparseMatrix<T> & C,\n  Eigen::SparseMatrix<T> & L,\n  Eigen::SparseMatrix<T> & U)\n{\n#if EIGEN_VERSION_AT_LEAST(3,0,92)\n#  warning lu_lagrange has not yet been implemented for your Eigen Version\n  return false;\n#else\n  // number of unknowns\n  int n = ATA.rows();\n  // number of lagrange multipliers\n  int m = C.cols();\n\n  assert(ATA.cols() == n);\n  if(m != 0)\n  {\n    assert(C.rows() == n);\n    if(C.nonZeros() == 0)\n    {\n      // See note above about empty columns in C\n      fprintf(stderr,\"Error: lu_lagrange() C has columns but no entries\\n\");\n      return false;\n    }\n  }\n\n  // Check that each column of C has at least one entry\n  std::vector<bool> has_entry; has_entry.resize(C.cols(),false);\n  // Iterate over outside\n  for(int k=0; k<C.outerSize(); ++k)\n  {\n    // Iterate over inside\n    for(typename Eigen::SparseMatrix<T>::InnerIterator it (C,k); it; ++it)\n    {\n      has_entry[it.col()] = true;\n    }\n  }\n  for(int i=0;i<(int)has_entry.size();i++)\n  {\n    if(!has_entry[i])\n    {\n      // See note above about empty columns in C\n      fprintf(stderr,\"Error: lu_lagrange() C(:,%d) has no entries\\n\",i);\n      return false;\n    }\n  }\n\n\n\n  // Cholesky factorization of ATA\n  //// Eigen fails if you give a full view of the matrix like this:\n  //Eigen::SparseLLT<SparseMatrix<T> > ATA_LLT(ATA);\n  Eigen::SparseMatrix<T> ATA_LT = ATA.template triangularView<Eigen::Lower>();\n  Eigen::SparseLLT<Eigen::SparseMatrix<T> > ATA_LLT(ATA_LT);\n\n  Eigen::SparseMatrix<T> J = ATA_LLT.matrixL();\n\n  //if(!ATA_LLT.succeeded())\n  if(!((J*0).eval().nonZeros() == 0))\n  {\n    fprintf(stderr,\"Error: lu_lagrange() failed to factor ATA\\n\");\n    return false;\n  }\n\n  if(m == 0)\n  {\n    // If there are no constraints (C is empty) then LU decomposition is just L\n    // and L' from cholesky decomposition\n    L = J;\n    U = J.transpose();\n  }else\n  {\n    // Construct helper matrix M\n    Eigen::SparseMatrix<T> M = C;\n    J.template triangularView<Eigen::Lower>().solveInPlace(M);\n\n    // Compute cholesky factorizaiton of M'*M\n    Eigen::SparseMatrix<T> MTM = M.transpose() * M;\n\n    Eigen::SparseLLT<Eigen::SparseMatrix<T> > MTM_LLT(MTM.template triangularView<Eigen::Lower>());\n\n    Eigen::SparseMatrix<T> K = MTM_LLT.matrixL();\n\n    //if(!MTM_LLT.succeeded())\n    if(!((K*0).eval().nonZeros() == 0))\n    {\n      fprintf(stderr,\"Error: lu_lagrange() failed to factor MTM\\n\");\n      return false;\n    }\n\n    // assemble LU decomposition of Q\n    Eigen::Matrix<int,Eigen::Dynamic,1> MI;\n    Eigen::Matrix<int,Eigen::Dynamic,1> MJ;\n    Eigen::Matrix<T,Eigen::Dynamic,1> MV;\n    igl::find(M,MI,MJ,MV);\n\n    Eigen::Matrix<int,Eigen::Dynamic,1> KI;\n    Eigen::Matrix<int,Eigen::Dynamic,1> KJ;\n    Eigen::Matrix<T,Eigen::Dynamic,1> KV;\n    igl::find(K,KI,KJ,KV);\n\n    Eigen::Matrix<int,Eigen::Dynamic,1> JI;\n    Eigen::Matrix<int,Eigen::Dynamic,1> JJ;\n    Eigen::Matrix<T,Eigen::Dynamic,1> JV;\n    igl::find(J,JI,JJ,JV);\n\n    int nnz = JV.size()  + MV.size() + KV.size();\n\n    Eigen::Matrix<int,Eigen::Dynamic,1> UI(nnz);\n    Eigen::Matrix<int,Eigen::Dynamic,1> UJ(nnz);\n    Eigen::Matrix<T,Eigen::Dynamic,1> UV(nnz);\n    UI << JJ,                        MI, (KJ.array() + n).matrix();\n    UJ << JI, (MJ.array() + n).matrix(), (KI.array() + n).matrix(); \n    UV << JV,                        MV,                     KV*-1;\n    igl::sparse(UI,UJ,UV,U);\n\n    Eigen::Matrix<int,Eigen::Dynamic,1> LI(nnz);\n    Eigen::Matrix<int,Eigen::Dynamic,1> LJ(nnz);\n    Eigen::Matrix<T,Eigen::Dynamic,1> LV(nnz);\n    LI << JI, (MJ.array() + n).matrix(), (KI.array() + n).matrix();\n    LJ << JJ,                        MI, (KJ.array() + n).matrix(); \n    LV << JV,                        MV,                        KV;\n    igl::sparse(LI,LJ,LV,L);\n  }\n\n  return true;\n  #endif\n}\n\n#ifdef IGL_STATIC_LIBRARY\n// Explicit template specialization\ntemplate bool igl::lu_lagrange<double>(Eigen::SparseMatrix<double, 0, int> const&, Eigen::SparseMatrix<double, 0, int> const&, Eigen::SparseMatrix<double, 0, int>&, Eigen::SparseMatrix<double, 0, int>&);\n#endif\n", "meta": {"hexsha": "d20dd84d9e3fc30d50a88b6c4eff1b72d264db9e", "size": 4794, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/quadwild/libs/libigl/include/igl/lu_lagrange.cpp", "max_stars_repo_name": "Pentacode-IAFA/Quad-Remeshing", "max_stars_repo_head_hexsha": "f8fd4c10abf1c54656b38a00b8a698b952a85fe2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/quadwild/libs/libigl/include/igl/lu_lagrange.cpp", "max_issues_repo_name": "Pentacode-IAFA/Quad-Remeshing", "max_issues_repo_head_hexsha": "f8fd4c10abf1c54656b38a00b8a698b952a85fe2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/quadwild/libs/libigl/include/igl/lu_lagrange.cpp", "max_forks_repo_name": "Pentacode-IAFA/Quad-Remeshing", "max_forks_repo_head_hexsha": "f8fd4c10abf1c54656b38a00b8a698b952a85fe2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.9290322581, "max_line_length": 203, "alphanum_fraction": 0.62077597, "num_tokens": 1422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.6187804196836382, "lm_q1q2_score": 0.49075843332729585}}
{"text": "/******************************************************\n    Author : shipeng_liu \n    Email : 1196075299@qq.com\n    Description: Adaptive dynamic programming \n******************************************************/\n#include <cmath>\n#include<iostream>\n#include <fstream>\n#include <Eigen/Dense>\n#include <iomanip>\n\nusing namespace std;\n\n/****************************************************************** \n    Critic Network\n    Input: S, diff_s, steer_cmd\n    number of hidden_layer: 1\n    number of active_function: hidden_number\n    output: J_cost \n    parameter_layer1: parameters from input to hidden_layer\n    parameter_layer2: parameters from hidden_layer to output\n******************************************************************/\n\nclass critic_network {\n\n  private:\n\n    double learning_rate_basic = 0.1 ; //learning rate\n    double reward_count = 0.95; //the reward count \n    Eigen::MatrixXd parameter_layer1;\n    Eigen::MatrixXd parameter_layer2;\n    Eigen::MatrixXd input_variable;\n    Eigen::MatrixXd hidden_layer;\n    Eigen::MatrixXd p_hidden_layer;\n    double output;\n    double reference_signal;\n    double last_reference_signal;\n    int hidden_number;\n    static double active_function(double input) {\n        // 1 - exp( - qi(t) ) / 1 + exp( - qi(t) ) )\n        double ret = std::exp(- input);\n        double tmp = (2)/(1 + ret) - 1;\n        return tmp;\n    }\n\n\n  public:\n    static critic_network& Get_critic_network() \n    {\n        static critic_network singleton;\n        return singleton;\n    }\n\n    critic_network() \n    {\n        hidden_number = 4;\n        init();\n    }\n    double return_J_cost()\n    {\n        return output;\n    }\n    double return_reference()\n    {\n        return reference_signal;\n    }\n    Eigen::MatrixXd return_parameter_layer1()\n    {\n        return parameter_layer1;\n    }\n    Eigen::MatrixXd return_parameter_layer2()\n    {\n        return parameter_layer2;\n    }\n    Eigen::MatrixXd return_p_hidden_layer()\n    {\n        return p_hidden_layer;\n    }\n    void init()\n    {\n        parameter_layer1 = Eigen::MatrixXd::Random(3, hidden_number);\n        parameter_layer2 = Eigen::MatrixXd::Random(hidden_number, 1);\n        \n        hidden_layer = Eigen::MatrixXd::Random(1, hidden_number);\n        p_hidden_layer = Eigen::MatrixXd::Random(1, hidden_number);\n        input_variable = Eigen::MatrixXd::Random(1,3);\n        output = 0;\n\n    }\n\n    double output_J_cost(double s, double diff_s,double steer_cmd)\n    {\n        input_variable(0,0) = s;\n        input_variable(0,1) = diff_s;\n        input_variable(0,2) = steer_cmd;\n        hidden_layer = input_variable * parameter_layer1;\n        // limit hidden layer\n        \n        for (int i = 0; i < hidden_number; i++)\n        {\n            p_hidden_layer(0,i) = active_function(hidden_layer(0,i));\n            // limit the p_Hidden_layer\n            if (p_hidden_layer(0,i) < 0.000001 && p_hidden_layer(0,i) > 0 )\n                p_hidden_layer(0,i) = 0.000001;\n            else if (p_hidden_layer(0,i) > -0.000001 && p_hidden_layer(0,i) < 0)\n                p_hidden_layer(0,i) = - 0.000001;\n        }\n        \n\n        Eigen::MatrixXd test = p_hidden_layer * parameter_layer2;\n        output = test(0,0);\n        // limit the J_cost\n        if (output < 0)\n        {\n            output = 0;\n        }\n        \n        return output;\n    }\n\n    void update_weight(double J_cost, double Last_J_cost, double refer_s)\n    {\n        // update learning rate:\n        last_reference_signal = reference_signal;\n        reference_signal =  refer_s;\n        //double learning_rate = learning_rate_basic * (1+2/(1+fabs(reference_signal - last_reference_signal)) );\n        double learning_rate = learning_rate_basic * 4;\n        double ect = reward_count*J_cost -  reference_signal;\n        //double reference_signal = 0.5;\n        cout << \"\\ncritic_network_information:\\n\";\n        cout << left << setw(20) << \"[ refer: \" << right\n             << setw(20) << reference_signal << \"]\" << endl;\n        cout << left << setw(20) << \"[ J_cost: \" << right\n             << setw(20) << J_cost << \"]\" << endl;\n        cout << left << setw(20) << \"[ ect: \" << right\n             << setw(20) << ect << \"]\" << endl;\n        cout << \"[ p_hidden_layer: \" << endl;\n        cout << p_hidden_layer << endl;\n        // cout <<  \"[ parameter_layer1: \" << endl;\n        // cout << parameter_layer1 << endl;\n        \n        // cout << \"[ parameter_layer2: \" << endl;\n        // cout << parameter_layer2 << endl;\n\n        for (int j = 0; j < hidden_number; j++)\n        {\n            \n            for (int k = 0; k < 3; k++)\n            {\n                \n                double derivative_1 = reward_count * ect * parameter_layer2(j,0) * 0.5 * (1 - pow(p_hidden_layer(0,j),2)) * input_variable(0,k);\n               \n                double delta_weight1 = learning_rate * (- derivative_1);\n                \n                parameter_layer1(k,j) += delta_weight1; \n            }\n            double derivative =  reward_count * ect * (p_hidden_layer(0,j));\n            double delta_weight = learning_rate * (- derivative);\n            parameter_layer2(j,0) += delta_weight;\n\n        }\n    }\n}; ", "meta": {"hexsha": "e3c4fdb4a411fffc9e50d2cd99f17d223c302170", "size": 5166, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/controller/src/controller/adp_learning/critic_network.cpp", "max_stars_repo_name": "TJ-Work/CVSC", "max_stars_repo_head_hexsha": "6850bcffe765a6586dc5a81900206398be6dc1f5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/controller/src/controller/adp_learning/critic_network.cpp", "max_issues_repo_name": "TJ-Work/CVSC", "max_issues_repo_head_hexsha": "6850bcffe765a6586dc5a81900206398be6dc1f5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/controller/src/controller/adp_learning/critic_network.cpp", "max_forks_repo_name": "TJ-Work/CVSC", "max_forks_repo_head_hexsha": "6850bcffe765a6586dc5a81900206398be6dc1f5", "max_forks_repo_licenses": ["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.6932515337, "max_line_length": 144, "alphanum_fraction": 0.5458768873, "num_tokens": 1204, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.49075831072586357}}
{"text": "/*\n@copyright Louis Dionne 2015\nDistributed under the Boost Software License, Version 1.0.\n(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n */\n\n#include <boost/hana/assert.hpp>\n#include <boost/hana/equal.hpp>\n#include <boost/hana/integral_constant.hpp>\n#include <boost/hana/less.hpp>\n#include <boost/hana/negate.hpp>\n\n#include <type_traits>\nnamespace hana = boost::hana;\nusing namespace hana::literals;\n\n\nBOOST_HANA_CONSTANT_CHECK(0_c == hana::llong_c<0>);\nBOOST_HANA_CONSTANT_CHECK(1_c == hana::llong_c<1>);\nBOOST_HANA_CONSTANT_CHECK(12_c == hana::llong_c<12>);\nBOOST_HANA_CONSTANT_CHECK(123_c == hana::llong_c<123>);\nBOOST_HANA_CONSTANT_CHECK(1234567_c == hana::llong_c<1234567>);\nBOOST_HANA_CONSTANT_CHECK(-34_c == hana::llong_c<-34>);\n\nstatic_assert(std::is_same<\n    decltype(-1234_c)::value_type,\n    long long\n>{}, \"\");\nstatic_assert(-1234_c == -1234ll, \"\");\nBOOST_HANA_CONSTANT_CHECK(-12_c < 0_c);\n\nint main() { }\n", "meta": {"hexsha": "7794d4b090516c78b84a934436072f1b5597bc3c", "size": 953, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/integral_constant/udl.cpp", "max_stars_repo_name": "qicosmos/hana", "max_stars_repo_head_hexsha": "b0f8cf2bf19d491b7b739dcb7b8d7497b0e5829f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-12-06T05:10:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-05T21:48:27.000Z", "max_issues_repo_path": "test/integral_constant/udl.cpp", "max_issues_repo_name": "qicosmos/hana", "max_issues_repo_head_hexsha": "b0f8cf2bf19d491b7b739dcb7b8d7497b0e5829f", "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/integral_constant/udl.cpp", "max_forks_repo_name": "qicosmos/hana", "max_forks_repo_head_hexsha": "b0f8cf2bf19d491b7b739dcb7b8d7497b0e5829f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-06-06T10:50:17.000Z", "max_forks_repo_forks_event_max_datetime": "2017-06-06T10:50:17.000Z", "avg_line_length": 28.8787878788, "max_line_length": 78, "alphanum_fraction": 0.7471143757, "num_tokens": 280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154240079185319, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.49074471292458727}}
{"text": "// Copyright 2019 Xanadu Quantum Technologies Inc.\n\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n\n//     http://www.apache.org/licenses/LICENSE-2.0\n\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n/**\n * @file\n * Contains functions for calculating the multidimensional\n * Hermite polynomials, used for computation of batched hafnians.\n */\n\n#pragma once\n#include <stdafx.h>\n\n#include <Eigen/Eigenvalues>\n#include <Eigen/LU>\n\ntypedef unsigned long long int ullint;\n\n\n/**\n * Returns the index of the one dimensional flattened vector corresponding to the multidimensional tensor\n *\n * @param pos\n * @param resolution\n *\n * @return index on flattened vector\n */\nullint vec2index(std::vector<int> &pos, int resolution) {\n    int dim = pos.size();\n    ullint nextCoordinate = 0;\n\n    nextCoordinate = pos[0]-1;\n    for(int ii = 0; ii < dim-1; ii++) {\n        nextCoordinate = nextCoordinate*resolution + (pos[ii+1]-1);\n    }\n\n    return nextCoordinate;\n\n}\n\n/**\n * Returns the indices of the tensor corresponding to a given element\n *\n * @param val\n * @param base\n * @param n\n *\n * @return tensor index\n */\nstd::vector<int> find_rep(int val, int base, int n) {\n    std::vector<int> x(n, 0);\n    int local_val = val;\n\n    x[0] = 1;\n\n    for (int i = 1; i < n; i++)\n        x[i] = x[i-1]*base;\n\n    std::vector<int> digits(n, 0);\n\n    for (int i = 0; i < n; i++) {\n        digits[i] = local_val/x[n-i-1];\n        local_val = local_val - digits[i] * x[n-i-1];\n    }\n\n    return digits;\n}\n\n\n/**\n * Returns the sqrt of the factorial of an integer.\n *\n * @param nn input integer\n *\n * @return Square root of the factorial of \\f$n\\f$.\n */\nlong double sqrtfactorial(int nn)\n{\n    long double n = static_cast<long double>(nn);\n\n    if(n > 1)\n        return std::sqrt(n) * sqrtfactorial(n - 1);\n    else\n        return 1;\n}\n\n\n/**\n * Renormalizes an unnormalized photon number statistics of a Gaussian state.\n * Based on the MATLAB code available at: https://github.com/clementsw/gaussian-optics\n *\n * @param tn unnormalized flattened vector of size \\f$res**nmodes$ representing unnormalized photon number statistics\n *       \\f$2n\\times 2n\\f$ row-ordered symmetric matrix.\n * @param nmodes number of modes\n * @param res highest number of photons to be resolved.\n *\n * @return Renormalized photon number statistics\n */\ntemplate <typename T>\ninline std::vector<T> renormalization(std::vector<T> tn, int nmodes, int res) {\n    std::vector<long double> invsqfacts(res, 0);\n    std::vector<int> digits(nmodes, 0);\n\n    ullint Hdim = pow(res, nmodes);\n\n    for (int i = 0; i < res; i++)\n        invsqfacts[i] = sqrtfactorial(i);\n\n    for (ullint i = 0; i < Hdim; i++) {\n        digits = find_rep(i, res, nmodes);\n        long double pref = 1;\n        for (int j = 0; j < nmodes; j++)\n            pref *= 1.0L/invsqfacts[digits[j]];\n        tn[i] = tn[i]*static_cast<double>(pref);\n    }\n\n    return tn;\n\n}\n\n\n\nnamespace libwalrus {\n\n/**\n * Returns photon number statistics of a Gaussian state for a given covariance matrix `mat`.\n * as described in *Multidimensional Hermite polynomials and photon distribution for polymode mixed light*\n * [arxiv:9308033](https://arxiv.org/abs/hep-th/9308033).\n *\n * This implementation is based on the MATLAB code available at\n * https://github.com/clementsw/gaussian-optics\n *\n * @param mat a flattened vector of size \\f$2n^2\\f$, representing an\n *       \\f$2n\\times 2n\\f$ row-ordered symmetric matrix.\n * @param d a flattened vector of size \\f$2n\\f$, representing the first order moments.\n * @param resolution highest number of photons to be resolved.\n *\n */\ntemplate <typename T>\ninline std::vector<T> hermite_multidimensional_cpp(std::vector<T> &R_mat, std::vector<T> &y_mat, int &resolution, int &renorm) {\n    int dim = std::sqrt(static_cast<double>(R_mat.size()));\n\n    namespace eg = Eigen;\n\n    eg::Matrix<T, eg::Dynamic, eg::Dynamic> R = eg::Map<eg::Matrix<T, eg::Dynamic, eg::Dynamic>, eg::Unaligned>(R_mat.data(), dim, dim);\n    eg::Matrix<T, eg::Dynamic, eg::Dynamic> y = eg::Map<eg::Matrix<T, eg::Dynamic, eg::Dynamic>, eg::Unaligned>(y_mat.data(), dim, dim);\n\n    ullint Hdim = pow(resolution, dim);\n    std::vector<T> H(Hdim, 0);\n    std::vector<double> ren_factor(Hdim, 0);\n\n    H[0] = 1;\n    ren_factor[0] = 1;\n\n    std::vector<int> nextPos(dim, 1);\n    std::vector<int> jumpFrom(dim, 1);\n    std::vector<int> ek(dim, 0);\n    std::vector<double> factors(resolution+1, 0);\n    int jump = 0;\n\n\n    for (ullint jj = 0; jj < Hdim-1; jj++) {\n\n        if (jump > 0) {\n            jumpFrom[jump] += 1;\n            jump = 0;\n        }\n\n\n        for (int ii = 0; ii < dim; ii++) {\n            std::vector<int> forwardStep(dim, 0);\n            forwardStep[ii] = 1;\n\n            if ( forwardStep[ii] + nextPos[ii] > resolution) {\n                nextPos[ii] = 1;\n                jumpFrom[ii] = 1;\n                jump = ii+1;\n            }\n            else {\n                jumpFrom[ii] = nextPos[ii];\n                nextPos[ii] = nextPos[ii] + 1;\n                break;\n            }\n        }\n\n        for (int ii = 0; ii < dim; ii++)\n            ek[ii] = nextPos[ii] - jumpFrom[ii];\n\n        int k = 0;\n        for(; k < static_cast<int>(ek.size()); k++) {\n            if(ek[k]) break;\n        }\n\n        ullint nextCoordinate = vec2index(nextPos, resolution);\n        ullint fromCoordinate = vec2index(jumpFrom, resolution);\n\n\n        for (int ii = 0; ii < dim; ii++) {\n            H[nextCoordinate] = H[nextCoordinate] + R(k, ii) * y(ii, 0);\n        }\n        H[nextCoordinate] = H[nextCoordinate] * H[fromCoordinate];\n\n        std::vector<int> tmpjump(dim, 0);\n\n        for (int ii = 0; ii < dim; ii++) {\n            if (jumpFrom[ii] > 1) {\n                std::vector<int> prevJump(dim, 0);\n                prevJump[ii] = 1;\n                std::transform(jumpFrom.begin(), jumpFrom.end(), prevJump.begin(), tmpjump.begin(), std::minus<int>());\n                ullint prevCoordinate = vec2index(tmpjump, resolution);\n                H[nextCoordinate] = H[nextCoordinate] - (static_cast<T>(jumpFrom[ii]-1))*static_cast<T>(R(k,ii))*H[prevCoordinate];\n\n            }\n        }\n\n    }\n\n    if (renorm) {\n        H = renormalization(H, dim, resolution);\n    }\n\n    return H;\n\n}\n\n\n\n}\n", "meta": {"hexsha": "a6a560f37fa013dc5983543a7f3195f79f415624", "size": 6611, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/hermite_multidimensional.hpp", "max_stars_repo_name": "amitkumarj441/hafnian", "max_stars_repo_head_hexsha": "3d0b79c77180db7e415b96826707f8049d690208", "max_stars_repo_licenses": ["Apache-2.0"], "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/hermite_multidimensional.hpp", "max_issues_repo_name": "amitkumarj441/hafnian", "max_issues_repo_head_hexsha": "3d0b79c77180db7e415b96826707f8049d690208", "max_issues_repo_licenses": ["Apache-2.0"], "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/hermite_multidimensional.hpp", "max_forks_repo_name": "amitkumarj441/hafnian", "max_forks_repo_head_hexsha": "3d0b79c77180db7e415b96826707f8049d690208", "max_forks_repo_licenses": ["Apache-2.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.6610878661, "max_line_length": 136, "alphanum_fraction": 0.6055059749, "num_tokens": 1810, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.4907447046005503}}
{"text": "//=======================================================================\r\n// Copyright 2013 Maciej Piechotka\r\n// Authors: Maciej Piechotka\r\n//\r\n// Distributed under the Boost Software License, Version 1.0. (See\r\n// accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n//=======================================================================\r\n#ifndef BOOST_GRAPH_EDGE_COLORING_HPP\r\n#define BOOST_GRAPH_EDGE_COLORING_HPP\r\n\r\n#include <boost/graph/graph_traits.hpp>\r\n#include <boost/graph/iteration_macros.hpp>\r\n#include <boost/graph/properties.hpp>\r\n#include <algorithm>\r\n#include <limits>\r\n#include <vector>\r\n\r\n/* This algorithm is to find coloring of an edges\r\n\r\n   Reference:\r\n\r\n   Misra, J., & Gries, D. (1992). A constructive proof of Vizing's\r\n   theorem. In Information Processing Letters.\r\n*/\r\n\r\nnamespace boost {\r\n  namespace detail {\r\n    template<typename Graph, typename ColorMap>\r\n    bool\r\n    is_free(const Graph &g,\r\n            ColorMap color,\r\n            typename boost::graph_traits<Graph>::vertex_descriptor u,\r\n            typename boost::property_traits<ColorMap>::value_type free_color)\r\n    {\r\n      typedef typename boost::property_traits<ColorMap>::value_type color_t;\r\n      if (free_color == (std::numeric_limits<color_t>::max)())\r\n        return false;\r\n      BGL_FORALL_OUTEDGES_T(u, e, g, Graph) {\r\n        if (get(color, e) == free_color) {\r\n          return false;\r\n        }\r\n      }\r\n      return true;\r\n    }\r\n\r\n    template<typename Graph, typename ColorMap>\r\n    std::vector<typename boost::graph_traits<Graph>::vertex_descriptor>\r\n    maximal_fan(const Graph &g,\r\n                ColorMap color,\r\n                typename boost::graph_traits<Graph>::vertex_descriptor x,\r\n                typename boost::graph_traits<Graph>::vertex_descriptor y)\r\n    {\r\n      typedef typename boost::graph_traits<Graph>::vertex_descriptor vertex_t;\r\n      std::vector<vertex_t> fan;\r\n      fan.push_back(y);\r\n      bool extended;\r\n      do {\r\n        extended = false;\r\n        BGL_FORALL_OUTEDGES_T(x, e, g, Graph) {\r\n          vertex_t v = target(e, g);\r\n          if (is_free(g, color, fan.back(), get(color, e)) &&\r\n              std::find(fan.begin(), fan.end(), v) == fan.end()) {\r\n            fan.push_back(v);\r\n            extended = true;\r\n          }\r\n        }\r\n      } while(extended);\r\n      return fan;\r\n    }\r\n    template<typename Graph, typename ColorMap>\r\n    typename boost::property_traits<ColorMap>::value_type\r\n    find_free_color(const Graph &g,\r\n                    ColorMap color,\r\n                    typename boost::graph_traits<Graph>::vertex_descriptor u)\r\n    {\r\n      typename boost::property_traits<ColorMap>::value_type c = 0;\r\n      while (!is_free(g, color, u, c)) c++;\r\n      return c;\r\n    }\r\n\r\n    template<typename Graph, typename ColorMap>\r\n    void\r\n    invert_cd_path(const Graph &g,\r\n                   ColorMap color,\r\n                   typename boost::graph_traits<Graph>::vertex_descriptor x,\r\n                   typename boost::graph_traits<Graph>::edge_descriptor eold,\r\n                   typename boost::property_traits<ColorMap>::value_type c,\r\n                   typename boost::property_traits<ColorMap>::value_type d)\r\n    {\r\n      put(color, eold, d);\r\n      BGL_FORALL_OUTEDGES_T(x, e, g, Graph) {\r\n        if (get(color, e) == d && e != eold) {\r\n          invert_cd_path(g, color, target(e, g), e, d, c);\r\n          return;\r\n        }\r\n      }\r\n    }\r\n\r\n    template<typename Graph, typename ColorMap>\r\n    void\r\n    invert_cd_path(const Graph &g,\r\n                   ColorMap color,\r\n                   typename boost::graph_traits<Graph>::vertex_descriptor x,\r\n                   typename boost::property_traits<ColorMap>::value_type c,\r\n                   typename boost::property_traits<ColorMap>::value_type d)\r\n    {\r\n      BGL_FORALL_OUTEDGES_T(x, e, g, Graph) {\r\n        if (get(color, e) == d) {\r\n          invert_cd_path(g, color, target(e, g), e, d, c);\r\n          return;\r\n        }\r\n      }\r\n    }\r\n    \r\n    template<typename Graph, typename ColorMap, typename ForwardIterator>\r\n    void\r\n    rotate_fan(const Graph &g,\r\n               ColorMap color,\r\n               typename boost::graph_traits<Graph>::vertex_descriptor x,\r\n               ForwardIterator begin,\r\n               ForwardIterator end)\r\n    {\r\n      typedef typename boost::graph_traits<Graph>::edge_descriptor edge_t;\r\n      if (begin == end) {\r\n        return;\r\n      }\r\n      edge_t previous = edge(x, *begin, g).first;\r\n      for (begin++; begin != end; begin++) {\r\n        edge_t current = edge(x, *begin, g).first;\r\n        put(color, previous, get(color, current));\r\n        previous = current;\r\n      }\r\n    }\r\n\r\n    template<typename Graph, typename ColorMap>\r\n    class find_free_in_fan\r\n    {\r\n    public:\r\n      find_free_in_fan(const Graph &graph,\r\n                       const ColorMap color,\r\n                       typename boost::property_traits<ColorMap>::value_type d)\r\n        : graph(graph),\r\n          color(color),\r\n          d(d) {}\r\n      bool operator()(const typename boost::graph_traits<Graph>::vertex_descriptor u) const {\r\n        return is_free(graph, color, u, d);\r\n      }\r\n    private:\r\n      const Graph &graph;\r\n      const ColorMap color;\r\n      const typename boost::property_traits<ColorMap>::value_type d;\r\n    };\r\n  }\r\n\r\n  template<typename Graph, typename ColorMap>\r\n  typename boost::property_traits<ColorMap>::value_type\r\n  color_edge(const Graph &g,\r\n             ColorMap color,\r\n             typename boost::graph_traits<Graph>::edge_descriptor e)\r\n  {\r\n    typedef typename boost::graph_traits<Graph>::vertex_descriptor vertex_t;\r\n    typedef typename boost::property_traits<ColorMap>::value_type color_t;\r\n    typedef typename std::vector<vertex_t>::iterator fan_iterator;\r\n    using namespace detail;\r\n    vertex_t x = source(e, g), y = target(e, g);\r\n    std::vector<vertex_t> fan = maximal_fan(g, color, x, y);\r\n    color_t c = find_free_color(g, color, x);\r\n    color_t d = find_free_color(g, color, fan.back());\r\n    invert_cd_path(g, color, x, c, d);\r\n    fan_iterator w = std::find_if(fan.begin(),\r\n                                  fan.end(),\r\n                                  find_free_in_fan<Graph, ColorMap>(g, color, d));\r\n    rotate_fan(g, color, x, fan.begin(), w + 1);\r\n    put(color, edge(x, *w, g).first, d);\r\n    return (std::max)(c, d);\r\n  }\r\n\r\n  template<typename Graph, typename ColorMap>\r\n  typename boost::property_traits<ColorMap>::value_type\r\n  edge_coloring(const Graph &g,\r\n                ColorMap color)\r\n  {\r\n    typedef typename boost::property_traits<ColorMap>::value_type color_t;\r\n    BGL_FORALL_EDGES_T(e, g, Graph) {\r\n      put(color, e, (std::numeric_limits<color_t>::max)());\r\n    }\r\n    color_t colors = 0;\r\n    BGL_FORALL_EDGES_T(e, g, Graph) {\r\n      colors = (std::max)(colors, color_edge(g, color, e) + 1);\r\n    }\r\n    return colors;\r\n  }\r\n}\r\n\r\n#endif\r\n", "meta": {"hexsha": "cb8d332eadf6ba06b3ed0ff011830b4125b93a0b", "size": 6942, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ios/Pods/boost-for-react-native/boost/graph/edge_coloring.hpp", "max_stars_repo_name": "rudylee/expo", "max_stars_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_stars_repo_licenses": ["Apache-2.0", "MIT"], "max_stars_count": 8805.0, "max_stars_repo_stars_event_min_datetime": "2015-11-03T00:52:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T22:30:03.000Z", "max_issues_repo_path": "ios/Pods/boost-for-react-native/boost/graph/edge_coloring.hpp", "max_issues_repo_name": "rudylee/expo", "max_issues_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_issues_repo_licenses": ["Apache-2.0", "MIT"], "max_issues_count": 14694.0, "max_issues_repo_issues_event_min_datetime": "2015-02-24T15:13:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T13:16:45.000Z", "max_forks_repo_path": "ios/Pods/boost-for-react-native/boost/graph/edge_coloring.hpp", "max_forks_repo_name": "rudylee/expo", "max_forks_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_forks_repo_licenses": ["Apache-2.0", "MIT"], "max_forks_count": 1329.0, "max_forks_repo_forks_event_min_datetime": "2015-11-03T20:25:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T18:10:38.000Z", "avg_line_length": 35.2385786802, "max_line_length": 94, "alphanum_fraction": 0.580812446, "num_tokens": 1562, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154240079185319, "lm_q2_score": 0.6859494485880927, "lm_q1q2_score": 0.49074470373840023}}
{"text": "\n\n/* --------------------------------------------------------------------- \n * \n * Copyright (C) 2011 - 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, Texas A&M University, 2011 \n */ \n\n\n// @sect3{Include files}  \n\n// \u8fd9\u4e2a\u7a0b\u5e8f\u7684\u5305\u542b\u6587\u4ef6\u4e0e\u4e4b\u524d\u8bb8\u591a\u5176\u4ed6\u7a0b\u5e8f\u7684\u5305\u542b\u6587\u4ef6\u662f\u4e00\u6837\u7684\u3002\u552f\u4e00\u7684\u65b0\u6587\u4ef6\u662f\u5728\u4ecb\u7ecd\u4e2d\u8ba8\u8bba\u7684\u58f0\u660eFE_Nothing\u7684\u6587\u4ef6\u3002hp\u76ee\u5f55\u4e0b\u7684\u6587\u4ef6\u5df2\u7ecf\u5728  step-27  \u4e2d\u8ba8\u8bba\u8fc7\u4e86\u3002\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/affine_constraints.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\n#include <deal.II/dofs/dof_tools.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/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 <iostream> \n#include <fstream> \n\nnamespace Step46 \n{ \n  using namespace dealii; \n// @sect3{The <code>FluidStructureProblem</code> class template}  \n\n// \u8fd9\u662f\u4e3b\u7c7b\u3002\u5982\u679c\u4f60\u60f3\u7684\u8bdd\uff0c\u5b83\u662f step-8 \u548c step-22 \u7684\u7ec4\u5408\uff0c\u56e0\u4e3a\u5b83\u7684\u6210\u5458\u53d8\u91cf\u8981\u4e48\u9488\u5bf9\u5168\u5c40\u95ee\u9898\uff08Triangulation\u548cDoFHandler\u5bf9\u8c61\uff0c\u4ee5\u53ca hp::FECollection \u548c\u5404\u79cd\u7ebf\u6027\u4ee3\u6570\u5bf9\u8c61\uff09\uff0c\u8981\u4e48\u4e0e\u5f39\u6027\u6216\u65af\u6258\u514b\u65af\u5b50\u95ee\u9898\u6709\u5173\u3002\u7136\u800c\uff0c\u8be5\u7c7b\u7684\u4e00\u822c\u7ed3\u6784\u4e0e\u5176\u4ed6\u5927\u591a\u6570\u5b9e\u73b0\u9759\u6b62\u95ee\u9898\u7684\u7a0b\u5e8f\u4e00\u6837\u3002\n\n// \u6709\u51e0\u4e2a\u4e0d\u8a00\u81ea\u660e\u7684\u8f85\u52a9\u51fd\u6570\uff08<code>cell_is_in_fluid_domain, cell_is_in_solid_domain</code>\uff09\uff08\u5bf9\u4e24\u4e2a\u5b50\u57df\u7684\u7b26\u53f7\u540d\u79f0\u8fdb\u884c\u64cd\u4f5c\uff0c\u8fd9\u4e9b\u540d\u79f0\u5c06\u88ab\u7528\u4f5c\u5c5e\u4e8e\u5b50\u57df\u7684\u5355\u5143\u7684 material_ids\u3002\u6b63\u5982\u4ecb\u7ecd\u4e2d\u6240\u89e3\u91ca\u7684\u90a3\u6837\uff09\u548c\u51e0\u4e2a\u51fd\u6570\uff08<code>make_grid, set_active_fe_indices, assemble_interface_terms</code>\uff09\uff0c\u8fd9\u4e9b\u51fd\u6570\u5df2\u7ecf\u4ece\u5176\u4ed6\u7684\u51fd\u6570\u4e2d\u5206\u79bb\u51fa\u6765\uff0c\u53ef\u4ee5\u5728\u5176\u4ed6\u7684\u6559\u7a0b\u7a0b\u5e8f\u4e2d\u627e\u5230\uff0c\u6211\u4eec\u5c06\u5728\u5b9e\u73b0\u5b83\u4eec\u7684\u65f6\u5019\u8ba8\u8bba\u3002\n\n// \u6700\u540e\u4e00\u7ec4\u53d8\u91cf (  <code>viscosity, lambda, eta</code>  ) \u63cf\u8ff0\u4e86\u7528\u4e8e\u4e24\u4e2a\u7269\u7406\u6a21\u578b\u7684\u6750\u6599\u5c5e\u6027\u3002\n\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 cell_is_in_fluid_domain( \n      const typename DoFHandler<dim>::cell_iterator &cell); \n\n    static bool cell_is_in_solid_domain( \n      const typename DoFHandler<dim>::cell_iterator &cell); \n\n    void make_grid(); \n    void set_active_fe_indices(); \n    void setup_dofs(); \n    void assemble_system(); \n    void assemble_interface_term( \n      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    DoFHandler<dim>       dof_handler; \n\n    AffineConstraints<double> 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// @sect3{Boundary values and right hand side}  \n\n// \u4e0b\u9762\u8fd9\u4e2a\u7c7b\u5982\u5176\u540d\u3002\u901f\u5ea6\u7684\u8fb9\u754c\u503c\u5206\u522b\u4e3a2d\u7684 \n//  $\\mathbf u=(0, \\sin(\\pi x))^T$ \u548c3d\u7684 $\\mathbf u=(0,\n//  0, \\sin(\\pi x)\\sin(\\pi y))^T$ \u3002\n//  \u8fd9\u4e2a\u95ee\u9898\u7684\u5176\u4f59\u8fb9\u754c\u6761\u4ef6\u90fd\u662f\u540c\u8d28\u7684\uff0c\u5728\u4ecb\u7ecd\u4e2d\u5df2\u7ecf\u8ba8\u8bba\u8fc7\u3002\u53f3\u8fb9\u7684\u5f3a\u8feb\u9879\u5bf9\u4e8e\u6d41\u4f53\u548c\u56fa\u4f53\u90fd\u662f\u96f6\uff0c\u6240\u4ee5\u6211\u4eec\u4e0d\u9700\u8981\u4e3a\u5b83\u8bbe\u7f6e\u989d\u5916\u7684\u7c7b\u3002\n\n  template <int dim> \n  class StokesBoundaryValues : public Function<dim> \n  { \n  public: \n    StokesBoundaryValues() \n      : Function<dim>(dim + 1 + dim) \n    {} \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> &  value) const override; \n  }; \n\n  template <int dim> \n  double 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  template <int dim> \n  void 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//  @sect3{The <code>FluidStructureProblem</code> implementation}  \n// @sect4{Constructors and helper functions}  \n\n// \u73b0\u5728\u6211\u4eec\u6765\u8c08\u8c08\u8fd9\u4e2a\u7a0b\u5e8f\u7684\u4e3b\u7c7b\u7684\u5b9e\u73b0\u3002\u6700\u521d\u7684\u51e0\u4e2a\u51fd\u6570\u662f\u6784\u9020\u51fd\u6570\u548c\u8f85\u52a9\u51fd\u6570\uff0c\u53ef\u4ee5\u7528\u6765\u786e\u5b9a\u4e00\u4e2a\u5355\u5143\u683c\u5728\u57df\u7684\u54ea\u4e2a\u90e8\u5206\u3002\u9274\u4e8e\u4ecb\u7ecd\u4e2d\u5bf9\u8fd9\u4e9b\u4e3b\u9898\u7684\u8ba8\u8bba\uff0c\u5b83\u4eec\u7684\u5b9e\u73b0\u662f\u76f8\u5f53\u660e\u663e\u7684\u3002\u5728\u6784\u9020\u51fd\u6570\u4e2d\uff0c\u6ce8\u610f\u6211\u4eec\u5fc5\u987b\u4ece\u65af\u6258\u514b\u65af\u548c\u5f39\u6027\u7684\u57fa\u672c\u5143\u7d20\u4e2d\u6784\u9020 hp::FECollection \u5bf9\u8c61\uff1b\u4f7f\u7528 hp::FECollection::push_back \u51fd\u6570\u5728\u8fd9\u4e2a\u96c6\u5408\u4e2d\u4e3a\u5b83\u4eec\u5206\u914d\u4e860\u548c1\u7684\u4f4d\u7f6e\uff0c\u6211\u4eec\u5fc5\u987b\u8bb0\u4f4f\u8fd9\u4e2a\u987a\u5e8f\uff0c\u5e76\u5728\u7a0b\u5e8f\u7684\u5176\u4f59\u90e8\u5206\u4e00\u81f4\u4f7f\u7528\u3002\n\n  template <int dim> \n  FluidStructureProblem<dim>::FluidStructureProblem( \n    const unsigned int stokes_degree, \n    const unsigned int elasticity_degree) \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), \n                dim, \n                FE_Q<dim>(stokes_degree), \n                1, \n                FE_Nothing<dim>(), \n                dim) \n    , elasticity_fe(FE_Nothing<dim>(), \n                    dim, \n                    FE_Nothing<dim>(), \n                    1, \n                    FE_Q<dim>(elasticity_degree), \n                    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  template <int dim> \n  bool FluidStructureProblem<dim>::cell_is_in_fluid_domain( \n    const typename DoFHandler<dim>::cell_iterator &cell) \n  { \n    return (cell->material_id() == fluid_domain_id); \n  } \n\n  template <int dim> \n  bool FluidStructureProblem<dim>::cell_is_in_solid_domain( \n    const typename DoFHandler<dim>::cell_iterator &cell) \n  { \n    return (cell->material_id() == solid_domain_id); \n  } \n// @sect4{Meshes and assigning subdomains}  \n\n// \u63a5\u4e0b\u6765\u7684\u4e00\u5bf9\u51fd\u6570\u662f\u5904\u7406\u751f\u6210\u7f51\u683c\uff0c\u5e76\u786e\u4fdd\u6240\u6709\u8868\u793a\u5b50\u57df\u7684\u6807\u5fd7\u90fd\u662f\u6b63\u786e\u7684\u3002  <code>make_grid</code>  \uff0c\u6b63\u5982\u5728\u4ecb\u7ecd\u4e2d\u6240\u8ba8\u8bba\u7684\uff0c\u751f\u6210\u4e00\u4e2a $8\\times 8$ \u7684\u7f51\u683c\uff08\u6216\u8005\u4e00\u4e2a $8\\times 8\\times 8$ \u7684\u4e09\u7ef4\u7f51\u683c\uff09\u4ee5\u786e\u4fdd\u6bcf\u4e2a\u7c97\u7565\u7684\u7f51\u683c\u5355\u5143\u5b8c\u5168\u5728\u4e00\u4e2a\u5b50\u57df\u5185\u3002\u751f\u6210\u8fd9\u4e2a\u7f51\u683c\u540e\uff0c\u6211\u4eec\u5728\u5176\u8fb9\u754c\u4e0a\u5faa\u73af\uff0c\u5e76\u5728\u9876\u90e8\u8fb9\u754c\u8bbe\u7f6e\u8fb9\u754c\u6307\u6807\u4e3a1\uff0c\u8fd9\u662f\u6211\u4eec\u8bbe\u7f6e\u975e\u96f6\u8fea\u91cc\u5e0c\u7279\u8fb9\u754c\u6761\u4ef6\u7684\u552f\u4e00\u5730\u65b9\u3002\u5728\u8fd9\u4e4b\u540e\uff0c\u6211\u4eec\u518d\u6b21\u5728\u6240\u6709\u5355\u5143\u4e0a\u5faa\u73af\uff0c\u8bbe\u7f6e\u6750\u6599\u6307\u6807&mdash;\u7528\u6765\u8868\u793a\u6211\u4eec\u5904\u4e8e\u57df\u7684\u54ea\u4e00\u90e8\u5206\uff0c\u662f\u6d41\u4f53\u6307\u6807\u8fd8\u662f\u56fa\u4f53\u6307\u6807\u3002\n\n  template <int dim> \n  void FluidStructureProblem<dim>::make_grid() \n  { \n    GridGenerator::subdivided_hyper_cube(triangulation, 8, -1, 1); \n\n    for (const auto &cell : triangulation.active_cell_iterators()) \n      for (const auto &face : cell->face_iterators()) \n        if (face->at_boundary() && (face->center()[dim - 1] == 1)) \n          face->set_all_boundary_ids(1); \n\n    for (const auto &cell : dof_handler.active_cell_iterators()) \n      if (((std::fabs(cell->center()[0]) < 0.25) && \n           (cell->center()[dim - 1] > 0.5)) || \n          ((std::fabs(cell->center()[0]) >= 0.25) && \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// \u8fd9\u5bf9\u51fd\u6570\u7684\u7b2c\u4e8c\u90e8\u5206\u51b3\u5b9a\u5728\u6bcf\u4e2a\u5355\u5143\u4e0a\u4f7f\u7528\u54ea\u4e2a\u6709\u9650\u5143\u3002\u4e0a\u9762\u6211\u4eec\u8bbe\u7f6e\u4e86\u6bcf\u4e2a\u7c97\u7565\u7f51\u683c\u5355\u5143\u7684\u6750\u6599\u6307\u6807\uff0c\u6b63\u5982\u5728\u4ecb\u7ecd\u4e2d\u63d0\u5230\u7684\uff0c\u8fd9\u4e2a\u4fe1\u606f\u5728\u7f51\u683c\u7ec6\u5316\u65f6\u5c06\u4ece\u6bcd\u5355\u5143\u7ee7\u627f\u5230\u5b50\u5355\u5143\u3002\n\n// \u6362\u53e5\u8bdd\u8bf4\uff0c\u53ea\u8981\u6211\u4eec\u7ec6\u5316\uff08\u6216\u521b\u5efa\uff09\u4e86\u7f51\u683c\uff0c\u6211\u4eec\u5c31\u53ef\u4ee5\u4f9d\u9760\u6750\u6599\u6307\u793a\u5668\u6765\u6b63\u786e\u63cf\u8ff0\u4e00\u4e2a\u5355\u5143\u6240\u5904\u7684\u57df\u7684\u54ea\u4e00\u90e8\u5206\u3002\u7136\u540e\u6211\u4eec\u5229\u7528\u8fd9\u4e00\u70b9\u5c06\u5355\u5143\u7684\u6d3b\u52a8FE\u7d22\u5f15\u8bbe\u7f6e\u4e3a\u8be5\u7c7b\u7684 hp::FECollection \u6210\u5458\u53d8\u91cf\u4e2d\u7684\u76f8\u5e94\u5143\u7d20\uff1a\u6d41\u4f53\u5355\u5143\u4e3a0\uff0c\u56fa\u4f53\u5355\u5143\u4e3a1\u3002\n\n  template <int dim> \n  void FluidStructureProblem<dim>::set_active_fe_indices() \n  { \n    for (const auto &cell : dof_handler.active_cell_iterators()) \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// @sect4{<code>FluidStructureProblem::setup_dofs</code>}  \n\n// \u4e0b\u4e00\u6b65\u662f\u4e3a\u7ebf\u6027\u7cfb\u7edf\u8bbe\u7f6e\u6570\u636e\u7ed3\u6784\u3002\u4e3a\u6b64\uff0c\u6211\u4eec\u9996\u5148\u8981\u7528\u4e0a\u9762\u7684\u51fd\u6570\u8bbe\u7f6e\u6d3b\u52a8FE\u6307\u6570\uff0c\u7136\u540e\u5206\u914d\u81ea\u7531\u5ea6\uff0c\u518d\u786e\u5b9a\u7ebf\u6027\u7cfb\u7edf\u7684\u7ea6\u675f\u3002\u540e\u8005\u5305\u62ec\u50cf\u5f80\u5e38\u4e00\u6837\u7684\u60ac\u6302\u8282\u70b9\u7ea6\u675f\uff0c\u4f46\u4e5f\u5305\u62ec\u9876\u90e8\u6d41\u4f53\u8fb9\u754c\u7684\u4e0d\u5747\u5300\u8fb9\u754c\u503c\uff0c\u4ee5\u53ca\u6cbf\u56fa\u4f53\u5b50\u57df\u5468\u8fb9\u7684\u96f6\u8fb9\u754c\u503c\u3002\n\n  template <int dim> \n  void 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, 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( \n                                                 velocities)); \n\n      const FEValuesExtractors::Vector displacements(dim + 1); \n      VectorTools::interpolate_boundary_values( \n        dof_handler, \n        0, \n        Functions::ZeroFunction<dim>(dim + 1 + dim), \n        constraints, \n        fe_collection.component_mask(displacements)); \n    } \n\n// \u4e0d\u8fc7\uff0c\u6211\u4eec\u8fd8\u9700\u8981\u5904\u7406\u66f4\u591a\u7684\u7ea6\u675f\u6761\u4ef6\uff1a\u6211\u4eec\u5fc5\u987b\u786e\u4fdd\u5728\u6d41\u4f53\u548c\u56fa\u4f53\u7684\u754c\u9762\u4e0a\u901f\u5ea6\u4e3a\u96f6\u3002\u4e0b\u9762\u8fd9\u6bb5\u4ee3\u7801\u5df2\u7ecf\u5728\u4ecb\u7ecd\u4e2d\u4ecb\u7ecd\u8fc7\u4e86\u3002\n\n    { \n      std::vector<types::global_dof_index> local_face_dof_indices( \n        stokes_fe.n_dofs_per_face()); \n      for (const auto &cell : dof_handler.active_cell_iterators()) \n        if (cell_is_in_fluid_domain(cell)) \n          for (const auto face_no : cell->face_indices()) \n            if (cell->face(face_no)->at_boundary() == false) \n              { \n                bool face_is_on_interface = false; \n\n                if ((cell->neighbor(face_no)->has_children() == false) && \n                    (cell_is_in_solid_domain(cell->neighbor(face_no)))) \n                  face_is_on_interface = true; \n                else if (cell->neighbor(face_no)->has_children() == true) \n                  { \n                    for (unsigned int sf = 0; \n                         sf < cell->face(face_no)->n_children(); \n                         ++sf) \n                      if (cell_is_in_solid_domain( \n                            cell->neighbor_child_on_subface(face_no, sf))) \n                        { \n                          face_is_on_interface = true; \n                          break; \n                        } \n                  } \n\n                if (face_is_on_interface) \n                  { \n                    cell->face(face_no)->get_dof_indices(local_face_dof_indices, \n                                                         0); \n                    for (unsigned int i = 0; i < local_face_dof_indices.size(); \n                         ++i) \n                      if (stokes_fe.face_system_to_component_index(i).first < \n                          dim) \n                        constraints.add_line(local_face_dof_indices[i]); \n                  } \n              } \n    } \n\n// \u5728\u8fd9\u4e00\u5207\u7ed3\u675f\u540e\uff0c\u6211\u4eec\u53ef\u4ee5\u5411\u7ea6\u675f\u5bf9\u8c61\u58f0\u660e\uff0c\u6211\u4eec\u73b0\u5728\u5df2\u7ecf\u51c6\u5907\u597d\u4e86\u6240\u6709\u7684\u7ea6\u675f\uff0c\u5e76\u4e14\u8be5\u5bf9\u8c61\u53ef\u4ee5\u91cd\u5efa\u5176\u5185\u90e8\u6570\u636e\u7ed3\u6784\u4ee5\u63d0\u9ad8\u6548\u7387\u3002\n\n    constraints.close(); \n\n    std::cout << \"   Number of active cells: \" << triangulation.n_active_cells() \n              << std::endl \n              << \"   Number of degrees of freedom: \" << dof_handler.n_dofs() \n              << std::endl; \n\n// \u5728\u8fd9\u4e2a\u51fd\u6570\u7684\u5176\u4f59\u90e8\u5206\uff0c\u6211\u4eec\u521b\u5efa\u4e86\u4e00\u4e2a\u5728\u4ecb\u7ecd\u4e2d\u5e7f\u6cdb\u8ba8\u8bba\u7684\u7a00\u758f\u6a21\u5f0f\uff0c\u5e76\u4f7f\u7528\u5b83\u6765\u521d\u59cb\u5316\u77e9\u9635\uff1b\u7136\u540e\u8fd8\u5c06\u5411\u91cf\u8bbe\u7f6e\u4e3a\u6b63\u786e\u7684\u5927\u5c0f\u3002\n\n    { \n      DynamicSparsityPattern dsp(dof_handler.n_dofs(), 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                ((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, \n                                           dsp, \n                                           cell_coupling, \n                                           face_coupling); \n      constraints.condense(dsp); \n      sparsity_pattern.copy_from(dsp); \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//  @sect4{<code>FluidStructureProblem::assemble_system</code>}  \n\n// \u4e0b\u9762\u662f\u8fd9\u4e2a\u7a0b\u5e8f\u7684\u4e2d\u5fc3\u51fd\u6570\uff1a\u7ec4\u88c5\u7ebf\u6027\u7cfb\u7edf\u7684\u51fd\u6570\u3002\u5b83\u5728\u5f00\u59cb\u65f6\u6709\u4e00\u957f\u6bb5\u8bbe\u7f6e\u8f85\u52a9\u51fd\u6570\u7684\u5185\u5bb9\uff1a\u4ece\u521b\u5efa\u6b63\u4ea4\u516c\u5f0f\u5230\u8bbe\u7f6eFEValues\u3001FEFaceValues\u548cFESubfaceValues\u5bf9\u8c61\uff0c\u8fd9\u4e9b\u90fd\u662f\u6574\u5408\u5355\u5143\u9879\u4ee5\u53ca\u754c\u9762\u9879\u6240\u5fc5\u9700\u7684\uff0c\u4ee5\u5e94\u5bf9\u754c\u9762\u4e0a\u7684\u5355\u5143\u4ee5\u76f8\u540c\u5927\u5c0f\u6216\u4e0d\u540c\u7ec6\u5316\u7a0b\u5ea6\u805a\u96c6\u5728\u4e00\u8d77\u7684\u60c5\u51b5...\n\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, \n                                   q_collection, \n                                   update_values | update_quadrature_points | \n                                     update_JxW_values | update_gradients); \n\n    const QGauss<dim - 1> common_face_quadrature( \n      std::max(stokes_degree + 2, elasticity_degree + 2)); \n\n    FEFaceValues<dim>    stokes_fe_face_values(stokes_fe, \n                                            common_face_quadrature, \n                                            update_JxW_values | \n                                              update_gradients | update_values); \n    FEFaceValues<dim>    elasticity_fe_face_values(elasticity_fe, \n                                                common_face_quadrature, \n                                                update_normal_vectors | \n                                                  update_values); \n    FESubfaceValues<dim> stokes_fe_subface_values(stokes_fe, \n                                                  common_face_quadrature, \n                                                  update_JxW_values | \n                                                    update_gradients | \n                                                    update_values); \n    FESubfaceValues<dim> elasticity_fe_subface_values(elasticity_fe, \n                                                      common_face_quadrature, \n                                                      update_normal_vectors | \n                                                        update_values); \n\n// ...\u63cf\u8ff0\u5c40\u90e8\u5bf9\u5168\u5c40\u7ebf\u6027\u7cfb\u7edf\u8d21\u732e\u6240\u9700\u7684\u5bf9\u8c61...\n\n    const unsigned int stokes_dofs_per_cell = stokes_fe.n_dofs_per_cell(); \n    const unsigned int elasticity_dofs_per_cell = \n      elasticity_fe.n_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<types::global_dof_index> local_dof_indices; \n    std::vector<types::global_dof_index> neighbor_dof_indices( \n      stokes_dofs_per_cell); \n\n    const Functions::ZeroFunction<dim> right_hand_side(dim + 1); \n\n// ...\u5230\u53d8\u91cf\uff0c\u5141\u8bb8\u6211\u4eec\u63d0\u53d6\u5f62\u72b6\u51fd\u6570\u7684\u67d0\u4e9b\u6210\u5206\u5e76\u7f13\u5b58\u5b83\u4eec\u7684\u503c\uff0c\u800c\u4e0d\u662f\u5728\u6bcf\u4e2a\u6b63\u4ea4\u70b9\u91cd\u65b0\u8ba1\u7b97\u5b83\u4eec\u3002\n\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( \n      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// \u7136\u540e\u662f\u6240\u6709\u5355\u5143\u683c\u7684\u4e3b\u5faa\u73af\uff0c\u548c step-27 \u4e00\u6837\uff0c\u521d\u59cb\u5316\u5f53\u524d\u5355\u5143\u683c\u7684 hp::FEValues \u5bf9\u8c61\uff0c\u63d0\u53d6\u9002\u5408\u5f53\u524d\u5355\u5143\u683c\u7684FEValues\u5bf9\u8c61\u3002\n\n    for (const auto &cell : dof_handler.active_cell_iterators()) \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().n_dofs_per_cell(), \n                            cell->get_fe().n_dofs_per_cell()); \n        local_rhs.reinit(cell->get_fe().n_dofs_per_cell()); \n\n// \u505a\u5b8c\u8fd9\u4e9b\u540e\uff0c\u6211\u4eec\u7ee7\u7eed\u4e3a\u5c5e\u4e8e\u65af\u6258\u514b\u65af\u548c\u5f39\u6027\u533a\u57df\u7684\u5355\u5143\u7ec4\u88c5\u5355\u5143\u9879\u3002\u867d\u7136\u6211\u4eec\u539f\u5219\u4e0a\u53ef\u4ee5\u5728\u4e00\u4e2a\u516c\u5f0f\u4e2d\u5b8c\u6210\uff0c\u5b9e\u9645\u4e0a\u5c31\u662f\u5b9e\u73b0\u4e86\u4ecb\u7ecd\u4e2d\u6240\u8bf4\u7684\u53cc\u7ebf\u6027\u5f62\u5f0f\uff0c\u4f46\u6211\u4eec\u610f\u8bc6\u5230\uff0c\u6211\u4eec\u7684\u6709\u9650\u5143\u7a7a\u95f4\u7684\u9009\u62e9\u65b9\u5f0f\u662f\uff0c\u5728\u6bcf\u4e2a\u5355\u5143\u4e0a\uff0c\u6709\u4e00\u7ec4\u53d8\u91cf\uff08\u901f\u5ea6\u548c\u538b\u529b\uff0c\u6216\u8005\u4f4d\u79fb\uff09\u603b\u662f\u4e3a\u96f6\uff0c\u56e0\u6b64\uff0c\u8ba1\u7b97\u5c40\u90e8\u79ef\u5206\u7684\u66f4\u6709\u6548\u7684\u65b9\u6cd5\u662f\uff0c\u6839\u636e\u6d4b\u8bd5\u6211\u4eec\u5904\u4e8e\u57df\u7684\u54ea\u4e00\u90e8\u5206\u7684 <code>if</code> \u6761\u6b3e\uff0c\u53ea\u505a\u5fc5\u8981\u7684\u4e8b\u60c5\u3002\n\n// \u5c40\u90e8\u77e9\u9635\u7684\u5b9e\u9645\u8ba1\u7b97\u4e0e step-22 \u4ee5\u53ca @ref vector_valued \u6587\u4ef6\u6a21\u5757\u4e2d\u7ed9\u51fa\u7684\u5f39\u6027\u65b9\u7a0b\u7684\u8ba1\u7b97\u76f8\u540c\u3002\n\n        if (cell_is_in_fluid_domain(cell)) \n          { \n            const unsigned int dofs_per_cell = cell->get_fe().n_dofs_per_cell(); \n            Assert(dofs_per_cell == stokes_dofs_per_cell, 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] = \n                      fe_values[velocities].symmetric_gradient(k, q); \n                    stokes_div_phi_u[k] = \n                      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) += \n                      (2 * viscosity * stokes_symgrad_phi_u[i] * \n                         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().n_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] = \n                      fe_values[displacements].gradient(k, q); \n                    elasticity_div_phi[k] = \n                      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 * elasticity_div_phi[i] * \n                           elasticity_div_phi[j] + \n                         mu * scalar_product(elasticity_grad_phi[i], \n                                             elasticity_grad_phi[j]) + \n                         mu * \n                           scalar_product(elasticity_grad_phi[i], \n                                          transpose(elasticity_grad_phi[j]))) * \n                        fe_values.JxW(q); \n                    } \n              } \n          } \n\n// \u4e00\u65e6\u6211\u4eec\u5f97\u5230\u4e86\u5355\u5143\u79ef\u5206\u7684\u8d21\u732e\uff0c\u6211\u4eec\u5c31\u628a\u5b83\u4eec\u590d\u5236\u5230\u5168\u5c40\u77e9\u9635\u4e2d\uff08\u901a\u8fc7 AffineConstraints::distribute_local_to_global \u51fd\u6570\uff0c\u7acb\u5373\u5904\u7406\u7ea6\u675f\uff09\u3002\u8bf7\u6ce8\u610f\uff0c\u6211\u4eec\u6ca1\u6709\u5411 <code>local_rhs</code> \u53d8\u91cf\u4e2d\u5199\u5165\u4efb\u4f55\u4e1c\u897f\uff0c\u5c3d\u7ba1\u6211\u4eec\u4ecd\u7136\u9700\u8981\u4f20\u9012\u5b83\uff0c\u56e0\u4e3a\u6d88\u9664\u975e\u96f6\u8fb9\u754c\u503c\u9700\u8981\u4fee\u6539\u5c40\u90e8\uff0c\u56e0\u6b64\u4e5f\u9700\u8981\u4fee\u6539\u5168\u5c40\u7684\u53f3\u624b\u503c\u3002\n\n        local_dof_indices.resize(cell->get_fe().n_dofs_per_cell()); \n        cell->get_dof_indices(local_dof_indices); \n        constraints.distribute_local_to_global(local_matrix, \n                                               local_rhs, \n                                               local_dof_indices, \n                                               system_matrix, \n                                               system_rhs); \n\n// \u8fd9\u4e2a\u51fd\u6570\u66f4\u6709\u8da3\u7684\u90e8\u5206\u662f\u6211\u4eec\u770b\u5230\u5173\u4e8e\u4e24\u4e2a\u5b50\u57df\u4e4b\u95f4\u7684\u754c\u9762\u4e0a\u7684\u8138\u90e8\u6761\u6b3e\u3002\u4e3a\u6b64\uff0c\u6211\u4eec\u9996\u5148\u8981\u786e\u4fdd\u6211\u4eec\u53ea\u7ec4\u88c5\u4e00\u6b21\uff0c\u5373\u4f7f\u5728\u6240\u6709\u5355\u5143\u7684\u6240\u6709\u9762\u7684\u5faa\u73af\u4e2d\u4f1a\u9047\u5230\u754c\u9762\u7684\u6bcf\u4e00\u90e8\u5206\u4e24\u6b21\u3002\u6211\u4eec\u6b66\u65ad\u5730\u51b3\u5b9a\uff0c\u53ea\u6709\u5f53\u5f53\u524d\u5355\u5143\u662f\u56fa\u4f53\u5b50\u57df\u7684\u4e00\u90e8\u5206\uff0c\u5e76\u4e14\u56e0\u6b64\u4e00\u4e2a\u9762\u4e0d\u5728\u8fb9\u754c\u4e0a\uff0c\u5e76\u4e14\u5b83\u540e\u9762\u7684\u6f5c\u5728\u90bb\u5c45\u662f\u6d41\u4f53\u57df\u7684\u4e00\u90e8\u5206\u65f6\uff0c\u6211\u4eec\u624d\u4f1a\u8bc4\u4f30\u754c\u9762\u6761\u6b3e\u3002\u8ba9\u6211\u4eec\u4ece\u8fd9\u4e9b\u6761\u4ef6\u5f00\u59cb\u3002\n\n        if (cell_is_in_solid_domain(cell)) \n          for (const auto f : cell->face_indices()) \n            if (cell->face(f)->at_boundary() == false) \n              { \n\n// \u5728\u8fd9\u4e00\u70b9\u4e0a\uff0c\u6211\u4eec\u77e5\u9053\u5f53\u524d\u7684\u5355\u5143\u683c\u662f\u4e00\u4e2a\u5019\u9009\u7684\u6574\u5408\u5bf9\u8c61\uff0c\u5e76\u4e14\u9762 <code>f</code> \u540e\u9762\u5b58\u5728\u4e00\u4e2a\u90bb\u5c45\u3002\u73b0\u5728\u6709\u4e09\u79cd\u53ef\u80fd\u6027\u3002           \n\n// - \u90bb\u5c45\u5904\u4e8e\u540c\u4e00\u7ec6\u5316\u6c34\u5e73\uff0c\u5e76\u4e14\u6ca1\u6709\u5b69\u5b50\u3002     \n\n// - \u90bb\u5c45\u6709\u5b50\u5973\u3002     \n\n// - \u90bb\u5c45\u6bd4\u8f83\u7c97\u7cd9\u3002            \u5728\u6240\u6709\u8fd9\u4e09\u79cd\u60c5\u51b5\u4e0b\uff0c\u6211\u4eec\u53ea\u5bf9\u5b83\u611f\u5174\u8da3\uff0c\u5982\u679c\u5b83\u662f\u6d41\u4f53\u5b50\u57df\u7684\u4e00\u90e8\u5206\u3002\u56e0\u6b64\uff0c\u8ba9\u6211\u4eec\u4ece\u7b2c\u4e00\u79cd\u6700\u7b80\u5355\u7684\u60c5\u51b5\u5f00\u59cb\uff1a\u5982\u679c\u90bb\u5c45\u5904\u4e8e\u540c\u4e00\u5c42\u6b21\uff0c\u6ca1\u6709\u5b50\u5973\uff0c\u5e76\u4e14\u662f\u4e00\u4e2a\u6d41\u4f53\u5355\u5143\uff0c\u90a3\u4e48\u8fd9\u4e24\u4e2a\u5355\u5143\u5171\u4eab\u4e00\u4e2a\u8fb9\u754c\uff0c\u8fd9\u4e2a\u8fb9\u754c\u662f\u754c\u9762\u7684\u4e00\u90e8\u5206\uff0c\u6211\u4eec\u60f3\u6cbf\u7740\u8fd9\u4e2a\u8fb9\u754c\u6574\u5408\u754c\u9762\u9879\u3002\u6211\u4eec\u6240\u8981\u505a\u7684\u5c31\u662f\u7528\u5f53\u524d\u9762\u548c\u90bb\u63a5\u5355\u5143\u7684\u9762\u521d\u59cb\u5316\u4e24\u4e2aFEFaceValues\u5bf9\u8c61\uff08\u6ce8\u610f\u6211\u4eec\u662f\u5982\u4f55\u627e\u51fa\u90bb\u63a5\u5355\u5143\u7684\u54ea\u4e2a\u9762\u4e0e\u5f53\u524d\u5355\u5143\u63a5\u58e4\u7684\uff09\uff0c\u7136\u540e\u628a\u4e1c\u897f\u4f20\u7ed9\u8bc4\u4f30\u754c\u9762\u9879\u7684\u51fd\u6570\uff08\u8fd9\u4e2a\u51fd\u6570\u7684\u7b2c\u4e09\u4e2a\u5230\u7b2c\u4e94\u4e2a\u53c2\u6570\u4e3a\u5b83\u63d0\u4f9b\u4e86\u6293\u53d6\u6570\u7ec4\uff09\u3002\u7136\u540e\uff0c\u7ed3\u679c\u518d\u6b21\u88ab\u590d\u5236\u5230\u5168\u5c40\u77e9\u9635\u4e2d\uff0c\u4f7f\u7528\u4e00\u4e2a\u77e5\u9053\u672c\u5730\u77e9\u9635\u7684\u884c\u548c\u5217\u7684DoF\u6307\u6570\u6765\u81ea\u4e0d\u540c\u5355\u5143\u7684\u51fd\u6570\u3002\n\n                if ((cell->neighbor(f)->level() == cell->level()) && \n                    (cell->neighbor(f)->has_children() == false) && \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, \n                                            stokes_fe_face_values, \n                                            elasticity_phi, \n                                            stokes_symgrad_phi_u, \n                                            stokes_phi_p, \n                                            local_interface_matrix); \n\n                    cell->neighbor(f)->get_dof_indices(neighbor_dof_indices); \n                    constraints.distribute_local_to_global( \n                      local_interface_matrix, \n                      local_dof_indices, \n                      neighbor_dof_indices, \n                      system_matrix); \n                  } \n\n// \u7b2c\u4e8c\u79cd\u60c5\u51b5\u662f\uff0c\u5982\u679c\u90bb\u5c45\u8fd8\u6709\u66f4\u591a\u7684\u5b69\u5b50\u3002\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0c\u6211\u4eec\u5fc5\u987b\u5728\u90bb\u5c45\u7684\u6240\u6709\u5b50\u5973\u4e2d\u8fdb\u884c\u5faa\u73af\uff0c\u770b\u4ed6\u4eec\u662f\u5426\u5c5e\u4e8e\u6d41\u4f53\u5b50\u57df\u7684\u4e00\u90e8\u5206\u3002\u5982\u679c\u5b83\u4eec\u662f\uff0c\u90a3\u4e48\u6211\u4eec\u5c31\u5728\u5171\u540c\u754c\u9762\u4e0a\u8fdb\u884c\u6574\u5408\uff0c\u8fd9\u4e2a\u754c\u9762\u662f\u90bb\u5c45\u7684\u4e00\u4e2a\u9762\u548c\u5f53\u524d\u5355\u5143\u7684\u4e00\u4e2a\u5b50\u9762\uff0c\u8981\u6c42\u6211\u4eec\u5bf9\u90bb\u5c45\u4f7f\u7528FEFaceValues\uff0c\u5bf9\u5f53\u524d\u5355\u5143\u4f7f\u7528FESubfaceValues\u3002\n\n                else if ((cell->neighbor(f)->level() == cell->level()) && \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( \n                            cell->neighbor_child_on_subface(f, subface))) \n                        { \n                          elasticity_fe_subface_values.reinit(cell, f, subface); \n                          stokes_fe_face_values.reinit( \n                            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, \n                                                  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( \n                            local_interface_matrix, \n                            local_dof_indices, \n                            neighbor_dof_indices, \n                            system_matrix); \n                        } \n                  } \n\n// \u6700\u540e\u4e00\u4e2a\u9009\u9879\u662f\uff0c\u90bb\u5c45\u6bd4\u8f83\u7c97\u5927\u3002\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0c\u6211\u4eec\u5fc5\u987b\u4e3a\u90bb\u5c45\u4f7f\u7528\u4e00\u4e2aFESubfaceValues\u5bf9\u8c61\uff0c\u4e3a\u5f53\u524d\u5355\u5143\u4f7f\u7528\u4e00\u4e2aFEFaceValues\uff1b\u5176\u4f59\u90e8\u5206\u4e0e\u4e4b\u524d\u76f8\u540c\u3002\n\n                else if (cell->neighbor_is_coarser(f) && \n                         cell_is_in_fluid_domain(cell->neighbor(f))) \n                  { \n                    elasticity_fe_face_values.reinit(cell, f); \n                    stokes_fe_subface_values.reinit( \n                      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, \n                                            stokes_phi_p, \n                                            local_interface_matrix); \n\n                    cell->neighbor(f)->get_dof_indices(neighbor_dof_indices); \n                    constraints.distribute_local_to_global( \n                      local_interface_matrix, \n                      local_dof_indices, \n                      neighbor_dof_indices, \n                      system_matrix); \n                  } \n              } \n      } \n  } \n\n// \u5728\u7ec4\u88c5\u5168\u5c40\u7cfb\u7edf\u7684\u51fd\u6570\u4e2d\uff0c\u6211\u4eec\u5c06\u8ba1\u7b97\u63a5\u53e3\u6761\u6b3e\u4f20\u9012\u7ed9\u6211\u4eec\u5728\u6b64\u8ba8\u8bba\u7684\u4e00\u4e2a\u5355\u72ec\u7684\u51fd\u6570\u3002\u5173\u952e\u662f\uff0c\u5c3d\u7ba1\u6211\u4eec\u65e0\u6cd5\u9884\u6d4bFEFaceValues\u548cFESubfaceValues\u5bf9\u8c61\u7684\u7ec4\u5408\uff0c\u4f46\u5b83\u4eec\u90fd\u662f\u4eceFEFaceValuesBase\u7c7b\u6d3e\u751f\u51fa\u6765\u7684\uff0c\u56e0\u6b64\u6211\u4eec\u4e0d\u5fc5\u5728\u610f\uff1a\u8be5\u51fd\u6570\u88ab\u7b80\u5355\u5730\u8c03\u7528\uff0c\u6709\u4e24\u4e2a\u8fd9\u6837\u7684\u5bf9\u8c61\u8868\u793a\u9762\u7684\u4e24\u8fb9\u7684\u6b63\u4ea4\u70b9\u4e0a\u7684\u5f62\u72b6\u51fd\u6570\u503c\u3002\u7136\u540e\u6211\u4eec\u505a\u6211\u4eec\u4e00\u76f4\u5728\u505a\u7684\u4e8b\u60c5\uff1a\u6211\u4eec\u7528\u5f62\u72b6\u51fd\u6570\u7684\u503c\u548c\u5b83\u4eec\u7684\u5bfc\u6570\u6765\u586b\u5145\u4ece\u5934\u6570\u7ec4\uff0c\u7136\u540e\u5faa\u73af\u8ba1\u7b97\u77e9\u9635\u7684\u6240\u6709\u6761\u76ee\u6765\u8ba1\u7b97\u5c40\u90e8\u79ef\u5206\u3002\u6211\u4eec\u5728\u8fd9\u91cc\u8bc4\u4f30\u7684\u53cc\u7ebf\u6027\u5f62\u5f0f\u7684\u7ec6\u8282\u5728\u4ecb\u7ecd\u4e2d\u7ed9\u51fa\u3002\n\n  template <int dim> \n  void FluidStructureProblem<dim>::assemble_interface_term( \n    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 = \n          elasticity_fe_face_values.normal_vector(q); \n\n        for (unsigned int k = 0; k < stokes_fe_face_values.dofs_per_cell; ++k) \n          { \n            stokes_symgrad_phi_u[k] = \n              stokes_fe_face_values[velocities].symmetric_gradient(k, q); \n            stokes_phi_p[k] = stokes_fe_face_values[pressure].value(k, q); \n          } \n        for (unsigned int k = 0; k < elasticity_fe_face_values.dofs_per_cell; \n             ++k) \n          elasticity_phi[k] = \n            elasticity_fe_face_values[displacements].value(k, q); \n\n        for (unsigned int i = 0; i < elasticity_fe_face_values.dofs_per_cell; \n             ++i) \n          for (unsigned int j = 0; j < stokes_fe_face_values.dofs_per_cell; ++j) \n            local_interface_matrix(i, j) += \n              -((2 * viscosity * (stokes_symgrad_phi_u[j] * normal_vector) - \n                 stokes_phi_p[j] * normal_vector) * \n                elasticity_phi[i] * stokes_fe_face_values.JxW(q)); \n      } \n  } \n// @sect4{<code>FluidStructureProblem::solve</code>}  \n\n// \u6b63\u5982\u4ecb\u7ecd\u4e2d\u6240\u8ba8\u8bba\u7684\uff0c\u6211\u4eec\u5728\u8fd9\u91cc\u4f7f\u7528\u4e86\u4e00\u4e2a\u76f8\u5f53\u7410\u788e\u7684\u6c42\u89e3\u5668\uff1a\u6211\u4eec\u53ea\u662f\u5c06\u7ebf\u6027\u7cfb\u7edf\u4f20\u9012\u7ed9SparseDirectUMFPACK\u76f4\u63a5\u6c42\u89e3\u5668\uff08\u4f8b\u5982\uff0c\u89c1 step-29  \uff09\u3002\u5728\u6c42\u89e3\u4e4b\u540e\uff0c\u6211\u4eec\u552f\u4e00\u8981\u505a\u7684\u662f\u786e\u4fdd\u60ac\u6302\u7684\u8282\u70b9\u548c\u8fb9\u754c\u503c\u7ea6\u675f\u662f\u6b63\u786e\u7684\u3002\n\n  template <int dim> \n  void 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//  @sect4{<code>FluidStructureProblem::output_results</code>}  \n\n// \u751f\u6210\u56fe\u5f62\u8f93\u51fa\u5728\u8fd9\u91cc\u76f8\u5f53\u7b80\u5355\uff1a\u6211\u4eec\u6240\u8981\u505a\u7684\u5c31\u662f\u786e\u5b9a\u89e3\u5411\u91cf\u7684\u54ea\u4e9b\u6210\u5206\u5c5e\u4e8e\u6807\u91cf\u548c/\u6216\u5411\u91cf\uff08\u4f8b\u5982\uff0c\u89c1 step-22 \u4e4b\u524d\u7684\u4f8b\u5b50\uff09\uff0c\u7136\u540e\u628a\u5b83\u5168\u90e8\u4f20\u9012\u7ed9DataOut\u7c7b\u3002\n\n  template <int dim> \n  void FluidStructureProblem<dim>::output_results( \n    const unsigned int refinement_cycle) const \n  { \n    std::vector<std::string> solution_names(dim, \"velocity\"); \n    solution_names.emplace_back(\"pressure\"); \n    for (unsigned int d = 0; d < dim; ++d) \n      solution_names.emplace_back(\"displacement\"); \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    for (unsigned int d = 0; d < dim; ++d) \n      data_component_interpretation.push_back( \n        DataComponentInterpretation::component_is_part_of_vector); \n\n    DataOut<dim> data_out; \n    data_out.attach_dof_handler(dof_handler); \n\n    data_out.add_data_vector(solution, \n                             solution_names, \n                             DataOut<dim>::type_dof_data, \n                             data_component_interpretation); \n    data_out.build_patches(); \n\n    std::ofstream output( \n      \"solution-\" + Utilities::int_to_string(refinement_cycle, 2) + \".vtk\"); \n    data_out.write_vtk(output); \n  } \n// @sect4{<code>FluidStructureProblem::refine_mesh</code>}  \n\n// \u4e0b\u4e00\u6b65\u662f\u7ec6\u5316\u7f51\u683c\u3002\u6b63\u5982\u5728\u4ecb\u7ecd\u4e2d\u6240\u8ba8\u8bba\u7684\uff0c\u8fd9\u6709\u70b9\u68d8\u624b\uff0c\u4e3b\u8981\u662f\u56e0\u4e3a\u6d41\u4f53\u548c\u56fa\u4f53\u5b50\u57df\u4f7f\u7528\u7684\u53d8\u91cf\u5177\u6709\u4e0d\u540c\u7684\u7269\u7406\u5c3a\u5bf8\uff0c\u56e0\u6b64\uff0c\u8bef\u5dee\u4f30\u8ba1\u7684\u7edd\u5bf9\u5927\u5c0f\u4e0d\u80fd\u76f4\u63a5\u6bd4\u8f83\u3002\u56e0\u6b64\uff0c\u6211\u4eec\u5c06\u4e0d\u5f97\u4e0d\u5bf9\u5b83\u4eec\u8fdb\u884c\u7f29\u653e\u3002\u56e0\u6b64\uff0c\u5728\u51fd\u6570\u7684\u9876\u90e8\uff0c\u6211\u4eec\u9996\u5148\u5206\u522b\u8ba1\u7b97\u4e0d\u540c\u53d8\u91cf\u7684\u8bef\u5dee\u4f30\u8ba1\u503c\uff08\u5728\u6d41\u4f53\u57df\u4e2d\u4f7f\u7528\u901f\u5ea6\u800c\u4e0d\u662f\u538b\u529b\uff0c\u5728\u56fa\u4f53\u57df\u4e2d\u4f7f\u7528\u4f4d\u79fb\uff09\u3002\n\n  template <int dim> \n  void FluidStructureProblem<dim>::refine_mesh() \n  { \n    Vector<float> stokes_estimated_error_per_cell( \n      triangulation.n_active_cells()); \n    Vector<float> elasticity_estimated_error_per_cell( \n      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( \n      dof_handler, \n      face_q_collection, \n      std::map<types::boundary_id, const Function<dim> *>(), \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( \n      dof_handler, \n      face_q_collection, \n      std::map<types::boundary_id, const Function<dim> *>(), \n      solution, \n      elasticity_estimated_error_per_cell, \n      fe_collection.component_mask(displacements)); \n\n// \u7136\u540e\uff0c\u6211\u4eec\u901a\u8fc7\u9664\u4ee5\u8bef\u5dee\u4f30\u8ba1\u503c\u7684\u6cd5\u7ebf\u5bf9\u5176\u8fdb\u884c\u5f52\u4e00\u5316\u5904\u7406\uff0c\u5e76\u6309\u7167\u4ecb\u7ecd\u4e2d\u6240\u8ba8\u8bba\u7684\u90a3\u6837\uff0c\u5c06\u6d41\u4f53\u8bef\u5dee\u6307\u6807\u63094\u7684\u7cfb\u6570\u8fdb\u884c\u7f29\u653e\u3002\u7136\u540e\u5c06\u8fd9\u4e9b\u7ed3\u679c\u52a0\u5728\u4e00\u8d77\uff0c\u5f62\u6210\u4e00\u4e2a\u5305\u542b\u6240\u6709\u5355\u5143\u7684\u8bef\u5dee\u6307\u6807\u7684\u5411\u91cf\u3002\n\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> 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// \u5728\u5b9e\u9645\u7ec6\u5316\u7f51\u683c\u4e4b\u524d\uff0c\u51fd\u6570\u7684\u5012\u6570\u7b2c\u4e8c\u90e8\u5206\u6d89\u53ca\u5230\u6211\u4eec\u5728\u4ecb\u7ecd\u4e2d\u5df2\u7ecf\u63d0\u5230\u7684\u542f\u53d1\u5f0f\u65b9\u6cd5\uff1a\u7531\u4e8e\u89e3\u662f\u4e0d\u8fde\u7eed\u7684\uff0cKellyErrorEstimator\u7c7b\u5bf9\u4f4d\u4e8e\u5b50\u57df\u4e4b\u95f4\u8fb9\u754c\u7684\u5355\u5143\u611f\u5230\u56f0\u60d1\uff1a\u5b83\u8ba4\u4e3a\u90a3\u91cc\u7684\u8bef\u5dee\u5f88\u5927\uff0c\u56e0\u4e3a\u68af\u5ea6\u7684\u8df3\u8dc3\u5f88\u5927\uff0c\u5c3d\u7ba1\u8fd9\u5b8c\u5168\u662f\u9884\u671f\u7684\uff0c\u4e8b\u5b9e\u4e0a\u5728\u7cbe\u786e\u89e3\u4e2d\u4e5f\u5b58\u5728\u8fd9\u4e00\u7279\u5f81\uff0c\u56e0\u6b64\u4e0d\u8868\u660e\u4efb\u4f55\u6570\u503c\u9519\u8bef\u3002\n\n// \u56e0\u6b64\uff0c\u6211\u4eec\u5c06\u754c\u9762\u4e0a\u7684\u6240\u6709\u5355\u5143\u7684\u8bef\u5dee\u6307\u6807\u8bbe\u7f6e\u4e3a\u96f6\uff1b\u51b3\u5b9a\u5f71\u54cd\u54ea\u4e9b\u5355\u5143\u7684\u6761\u4ef6\u7565\u663e\u5c34\u5c2c\uff0c\u56e0\u4e3a\u6211\u4eec\u5fc5\u987b\u8003\u8651\u5230\u81ea\u9002\u5e94\u7ec6\u5316\u7f51\u683c\u7684\u53ef\u80fd\u6027\uff0c\u8fd9\u610f\u5473\u7740\u90bb\u8fd1\u7684\u5355\u5143\u53ef\u80fd\u6bd4\u5f53\u524d\u7684\u5355\u5143\u66f4\u7c97\uff0c\u6216\u8005\u4e8b\u5b9e\u4e0a\u53ef\u80fd\u88ab\u7ec6\u5316\u4e00\u4e9b\u3002\u8fd9\u4e9b\u5d4c\u5957\u6761\u4ef6\u7684\u7ed3\u6784\u4e0e\u6211\u4eec\u5728 <code>assemble_system</code> \u4e2d\u7ec4\u88c5\u63a5\u53e3\u6761\u6b3e\u65f6\u9047\u5230\u7684\u60c5\u51b5\u57fa\u672c\u76f8\u540c\u3002\n\n    for (const auto &cell : dof_handler.active_cell_iterators()) \n      for (const auto f : cell->face_indices()) \n        if (cell_is_in_solid_domain(cell)) \n          { \n            if ((cell->at_boundary(f) == false) && \n                (((cell->neighbor(f)->level() == cell->level()) && \n                  (cell->neighbor(f)->has_children() == false) && \n                  cell_is_in_fluid_domain(cell->neighbor(f))) || \n                 ((cell->neighbor(f)->level() == cell->level()) && \n                  (cell->neighbor(f)->has_children() == true) && \n                  (cell_is_in_fluid_domain( \n                    cell->neighbor_child_on_subface(f, 0)))) || \n                 (cell->neighbor_is_coarser(f) && \n                  cell_is_in_fluid_domain(cell->neighbor(f))))) \n              estimated_error_per_cell(cell->active_cell_index()) = 0; \n          } \n        else \n          { \n            if ((cell->at_boundary(f) == false) && \n                (((cell->neighbor(f)->level() == cell->level()) && \n                  (cell->neighbor(f)->has_children() == false) && \n                  cell_is_in_solid_domain(cell->neighbor(f))) || \n                 ((cell->neighbor(f)->level() == cell->level()) && \n                  (cell->neighbor(f)->has_children() == true) && \n                  (cell_is_in_solid_domain( \n                    cell->neighbor_child_on_subface(f, 0)))) || \n                 (cell->neighbor_is_coarser(f) && \n                  cell_is_in_solid_domain(cell->neighbor(f))))) \n              estimated_error_per_cell(cell->active_cell_index()) = 0; \n          } \n\n    GridRefinement::refine_and_coarsen_fixed_number(triangulation, \n                                                    estimated_error_per_cell, \n                                                    0.3, \n                                                    0.0); \n    triangulation.execute_coarsening_and_refinement(); \n  } \n\n//  @sect4{<code>FluidStructureProblem::run</code>}  \n\n// \u50cf\u5f80\u5e38\u4e00\u6837\uff0c\u8fd9\u662f\u63a7\u5236\u6574\u4e2a\u64cd\u4f5c\u6d41\u7a0b\u7684\u51fd\u6570\u3002\u5982\u679c\u4f60\u8bfb\u8fc7\u6559\u7a0b\u7a0b\u5e8f  step-1  \u5230  step-6  \uff0c\u4f8b\u5982\uff0c\u90a3\u4e48\u4f60\u5df2\u7ecf\u5bf9\u4ee5\u4e0b\u7ed3\u6784\u76f8\u5f53\u719f\u6089\u3002\n\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} // namespace Step46 \n\n//  @sect4{The <code>main()</code> function}  \n\n// \u8fd9\u4e2a\uff0c\u6700\u540e\u7684\uff0c\u51fd\u6570\u6240\u5305\u542b\u7684\u5185\u5bb9\u51e0\u4e4e\u4e0e\u5176\u4ed6\u5927\u591a\u6570\u6559\u7a0b\u7a0b\u5e8f\u7684\u5185\u5bb9\u5b8c\u5168\u4e00\u6837\u3002\n\nint main() \n{ \n  try \n    { \n      using namespace Step46; \n\n      FluidStructureProblem<2> flow_problem(1, 1); \n      flow_problem.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  return 0; \n} \n\n\n", "meta": {"hexsha": "26fe4cb671bca8aefd3e187265829093355b95f5", "size": 36314, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-46/step-46.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-46/step-46.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-46/step-46.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": 40.1703539823, "max_line_length": 296, "alphanum_fraction": 0.5735804373, "num_tokens": 10979, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081926, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.49074470000745696}}
{"text": "#include <armadillo>\n#include <iostream>\n#include <fstream>\n#include <stdio.h>\n#include <string>\n#include \"mcpdft.h\"\n#include \"openrdmConfig.h\"\n\n#ifdef WITH_OPENMP // _OPENMP\n   #include <omp.h>\n#endif\n\nnamespace mcpdft {\n\n   MCPDFT::MCPDFT(std::string test_case)  { common_init(test_case); }\n   MCPDFT::MCPDFT() {}\n   MCPDFT::~MCPDFT() {}\n\n   void MCPDFT::common_init(std::string test_case) {\n       print_banner();\n       read_grids_from_file(test_case);\n       read_orbitals_from_file(test_case);\n       read_energies_from_file(test_case);\n       if(test_case == \"h2_tpbe_sto3g\") {\n\t  is_gga_ = true;\n\t  read_gradients_from_file(test_case);\n       }else{\n\t  is_gga_ = false;\n       }\n\n       read_opdm_from_file(test_case);\n       // read_cmat_from_file();\n   }\n\n   void MCPDFT::build_rho() {\n      build_density_functions();\n      if ( is_gga_ ) {\n         build_density_gradients();\n      }\n   }\n\n   void MCPDFT::build_density_functions() {\n      int nbfs = get_nbfs();\n      size_t npts = get_npts();\n      arma::mat phi(get_phi());\n      arma::mat D1a(get_D1a());\n      arma::mat D1b(get_D1b());\n      arma::vec W(get_w());\n      arma::vec rhoa(npts, arma::fill::zeros);\n      arma::vec rhob(npts, arma::fill::zeros);\n      arma::vec rho(npts, arma::fill::zeros);\n      double dum_a = 0.0;\n      double dum_b = 0.0;\n      double dum_tot = 0.0;\n      size_t chunk_size = 0;\n      int p{0}, mu{0}, nu{0};\n      #ifdef WITH_OPENMP\n         int nthrds{0};\n         printf(\"\\n++++++++++++++++++++++++++++++++++++++++++++++++++++++\\n\");\n         printf(\"                   *** Warning ***\\n\");\n         printf(\"   Calculating the density (gradients) using OpenMP\");\n         printf(\"\\n++++++++++++++++++++++++++++++++++++++++++++++++++++++\\n\");\n         nthrds = omp_get_max_threads();\n         nthrds /= 2;\n         omp_set_num_threads(nthrds);\n      #endif\n\n      #pragma omp parallel default(shared) \\\n                           private(p, mu, nu)\n      {  \n         #pragma omp for schedule(static) \\\n                         reduction(+:dum_a, dum_b, dum_tot) \\\n\t                 nowait\n            for(p = 0; p < npts; p++) {\n               double tempa = 0.0;\n               double tempb = 0.0;\n               #pragma omp parallel for schedule(static) \\\n                                        reduction(+:tempa,tempb) \\\n\t                                num_threads(2) \\\n                                        collapse(2)\n                  for(mu = 0; mu < nbfs; mu++) {\n                     for(int nu = 0; nu < nbfs; nu++) {\n                        tempa += D1a(mu, nu) * phi(p, mu) * phi(p, nu);\n                        tempb += D1b(mu, nu) * phi(p, mu) * phi(p, nu);\n                     }\n                  }\n                  rhoa(p) = tempa;\n                  rhob(p) = tempb;\n                  rho(p) = rhoa(p) + rhob(p);\n\n                  dum_a += rhoa(p) * W(p);\n                  dum_b += rhob(p) * W(p);\n                  dum_tot += ( rhoa(p) + rhob(p) ) * W(p) ;\n            } /* end of omp parallel for loop */\n      } /* end of omp parallel region */\n      set_rhoa(rhoa);\n      set_rhob(rhob);\n      set_rho(rho);\n\n      printf(\"\\n\");\n      printf(\"  Integrated total density = %20.12lf\\n\",dum_tot);\n      printf(\"  Integrated alpha density = %20.12lf\\n\",dum_a);\n      printf(\"  Integrated beta density  = %20.12lf\\n\",dum_b);\n      printf(\"\\n\");\n   }\n\n   void MCPDFT::build_density_gradients() {\n      int nbfs = get_nbfs();\n      size_t npts = get_npts();\n      arma::mat phi(get_phi());\n      arma::mat D1a(get_D1a());\n      arma::mat D1b(get_D1b());\n      int p{0}, nu{0}, sigma{0};\n      arma::mat phi_x(get_phi_x());\n      arma::mat phi_y(get_phi_y());\n      arma::mat phi_z(get_phi_z());\n      arma::vec rho_a_x(npts, arma::fill::zeros);\n      arma::vec rho_b_x(npts, arma::fill::zeros);\n      arma::vec rho_a_y(npts, arma::fill::zeros);\n      arma::vec rho_b_y(npts, arma::fill::zeros);\n      arma::vec rho_a_z(npts, arma::fill::zeros);\n      arma::vec rho_b_z(npts, arma::fill::zeros);\n      arma::vec sigma_aa(npts, arma::fill::zeros);\n      arma::vec sigma_ab(npts, arma::fill::zeros);\n      arma::vec sigma_bb(npts, arma::fill::zeros);\n      #pragma omp parallel default(shared) \\\n                           private(p, nu, sigma)\n      {\n         #pragma omp for schedule(static)\n             for (int p = 0; p < npts; p++) {\n                 double duma_x = 0.0;\n                 double dumb_x = 0.0;\n                 double duma_y = 0.0;\n                 double dumb_y = 0.0;\n                 double duma_z = 0.0;\n                 double dumb_z = 0.0;\n                 #pragma omp parallel for schedule(static) \\\n                   \t                  reduction(+:duma_x, duma_y, duma_z,\\\n                   \t\t                      dumb_x, dumb_y, dumb_z)\\\n                                          shared(p, nbfs, \\\n    \t\t\t\t                 sigma_aa, sigma_bb, sigma_ab, \\\n    \t\t\t\t                 rho_a_x, rho_a_y, rho_a_z, \\\n    \t\t\t\t                 rho_b_x, rho_b_y, rho_b_z) \\\n    \t\t\t                  num_threads(2) \\\n                                          collapse(2)\n                    for (int sigma = 0; sigma < nbfs; sigma++) {\n                        for (int nu = 0; nu < nbfs; nu++) {\n                            duma_x += ( phi_x(p, sigma) * phi(p, nu) + phi(p, sigma) * phi_x(p, nu) ) * D1a(sigma, nu);\n                            dumb_x += ( phi_x(p, sigma) * phi(p, nu) + phi(p, sigma) * phi_x(p, nu) ) * D1b(sigma, nu);\n                            duma_y += ( phi_y(p, sigma) * phi(p, nu) + phi(p, sigma) * phi_y(p, nu) ) * D1a(sigma, nu);\n                            dumb_y += ( phi_y(p, sigma) * phi(p, nu) + phi(p, sigma) * phi_y(p, nu) ) * D1b(sigma, nu);\n                            duma_z += ( phi_z(p, sigma) * phi(p, nu) + phi(p, sigma) * phi_z(p, nu) ) * D1a(sigma, nu);\n                            dumb_z += ( phi_z(p, sigma) * phi(p, nu) + phi(p, sigma) * phi_z(p, nu) ) * D1b(sigma, nu);\n                        }\n                    }\n                    rho_a_x(p) = duma_x;\n                    rho_b_x(p) = dumb_x;\n                    rho_a_y(p) = duma_y;\n                    rho_b_y(p) = dumb_y;\n                    rho_a_z(p) = duma_z;\n                    rho_b_z(p) = dumb_z;\n                    sigma_aa(p) = ( rho_a_x(p) * rho_a_x(p) ) +  ( rho_a_y(p) * rho_a_y(p) ) + ( rho_a_z(p) * rho_a_z(p) );\n                    sigma_bb(p) = ( rho_b_x(p) * rho_b_x(p) ) +  ( rho_b_y(p) * rho_b_y(p) ) + ( rho_b_z(p) * rho_b_z(p) );\n                    sigma_ab(p) = ( rho_a_x(p) * rho_b_x(p) ) +  ( rho_a_y(p) * rho_b_y(p) ) + ( rho_a_z(p) * rho_b_z(p) );\n             }\n      }\n      set_rhoa_x(rho_a_x);\n      set_rhob_x(rho_b_x);\n      set_rhoa_y(rho_a_y);\n      set_rhob_y(rho_b_y);\n      set_rhoa_z(rho_a_z);\n      set_rhob_z(rho_b_z);\n      set_sigma_aa(sigma_aa);\n      set_sigma_ab(sigma_ab);\n      set_sigma_bb(sigma_bb);\n   }\n\n   void MCPDFT::build_pi(const arma::mat &D2ab) {\n      build_ontop_pair_density(D2ab);\n      if ( is_gga_ ) {\n         build_ontop_pair_density_gradients(D2ab);\n      }\n   }\n\n   void MCPDFT::build_ontop_pair_density(const arma::mat &D2ab) {\n      int nbfs = get_nbfs();\n      size_t npts = get_npts();\n      arma::vec temp(npts);\n      arma::mat phi(get_phi());\n      int p{0},\n\t  mu{0}, nu{0},\n\t  lambda{0}, sigma{0};\n      for (int p = 0; p < npts; p++) {\n          double dum = 0.0;\n          // pi(r,r) = D(mu,nu; lambda,sigma) * phi(r,mu) * phi(r,nu) * phi(r,lambda) * phi(r,sigma)\n          #pragma omp parallel for default(shared) \\\n          \t                       private(mu,nu,lambda,sigma) \\\n          \t                       reduction(+:dum) \\\n          \t                       collapse(4)\n             for (int mu = 0; mu < nbfs; mu++) {\n                 for (int nu = 0; nu < nbfs; nu++) {\n                     for (int lambda = 0; lambda < nbfs; lambda++) {\n                         for (int sigma = 0; sigma < nbfs; sigma++) {\n                             dum += phi(p, mu) * phi(p, nu) * phi(p, lambda) * phi(p, sigma) * D2ab(nu*nbfs+mu, sigma*nbfs+lambda);\n                         }\n                     }\n                 }\n             } /* end of omp parallel for loop */\n             temp(p) = dum;\n      }\n      set_pi(temp);\n   }\n\n   void MCPDFT::build_ontop_pair_density_gradients(const arma::mat &D2ab) {\n      int nbfs = get_nbfs();\n      size_t npts = get_npts();\n      int p{0},\n\t  mu{0}, nu{0},\n\t  lambda{0}, sigma{0};\n      arma::mat phi(get_phi());\n      arma::mat phi_x(get_phi_x());\n      arma::mat phi_y(get_phi_y());\n      arma::mat phi_z(get_phi_z());\n      arma::vec pi_x(npts, arma::fill::zeros);\n      arma::vec pi_y(npts, arma::fill::zeros);\n      arma::vec pi_z(npts, arma::fill::zeros);\n      #pragma omp parallel default(shared) \\\n                           private(p, mu, nu, lambda, sigma)\n      {\n         #pragma omp for schedule(static)\n            for (int p = 0; p < npts; p++) {\n                double dum_x = 0.0;\n                double dum_y = 0.0;\n                double dum_z = 0.0;\n                // pi(r) = D(mu,nu; lambda,sigma) * phi(r,mu) * phi(r,nu) * phi(r,lambda) * phi(r,sigma)\n                #pragma omp parallel for schedule(static) \\\n                  \t                 reduction(+:dum_x, dum_y, dum_z) \\\n    \t\t                         num_threads(2) \\\n                                         collapse(4)\n                for (int mu = 0; mu < nbfs; mu++) {\n                    for (int nu = 0; nu < nbfs; nu++) {\n                        for (int lambda = 0; lambda < nbfs; lambda++) {\n                            for (int sigma = 0; sigma < nbfs; sigma++) {\n                                dum_x += ( phi_x(p, mu) * phi(p, lambda) * phi(p, sigma) * phi(p, nu) +\n                                           phi(p, mu) * phi_x(p, lambda) * phi(p, sigma) * phi(p, nu) +\n                                           phi(p, mu) * phi(p, lambda) * phi_x(p, sigma) * phi(p, nu) +\n                                           phi(p, mu) * phi(p, lambda) * phi(p, sigma) * phi_x(p, nu) ) * D2ab(nu*nbfs+mu, sigma*nbfs+lambda);\n\n                                dum_y += ( phi_y(p, mu) * phi(p, lambda) * phi(p, sigma) * phi(p, nu) +\n                                           phi(p, mu) * phi_y(p, lambda) * phi(p, sigma) * phi(p, nu) +\n                                           phi(p, mu) * phi(p, lambda) * phi_y(p, sigma) * phi(p, nu) +\n                                           phi(p, mu) * phi(p, lambda) * phi(p, sigma) * phi_y(p, nu) ) * D2ab(nu*nbfs+mu, sigma*nbfs+lambda);\n\n                                dum_z += ( phi_z(p, mu) * phi(p, lambda) * phi(p, sigma) * phi(p, nu) +\n                                           phi(p, mu) * phi_z(p, lambda) * phi(p, sigma) * phi(p, nu) +\n                                           phi(p, mu) * phi(p, lambda) * phi_z(p, sigma) * phi(p, nu) +\n                                           phi(p, mu) * phi(p, lambda) * phi(p, sigma) * phi_z(p, nu) ) * D2ab(nu*nbfs+mu, sigma*nbfs+lambda);\n                            }\n                        }\n                    }\n                }\n                pi_x(p) = dum_x;\n                pi_y(p) = dum_y;\n                pi_z(p) = dum_z;\n            }\n      }\n      set_pi_x(pi_x);\n      set_pi_z(pi_y);\n      set_pi_z(pi_z);\n   }\n\n   void MCPDFT::build_R() {\n        double tol = 1.0e-20;\n        size_t npts = get_npts();\n        arma::vec temp(npts);\n        arma::vec pi(get_pi());\n        arma::vec rho(get_rho());\n        #pragma parallel for schedule(static) \\\n\t                     private(p) \\\n                             shared(npts, pi, rho, temp)\n           for (int p = 0; p < npts; p++) {\n               temp(p) = 4.0 * pi(p) / ( rho(p) * rho(p) );\n           }\n        set_R(temp);\n   }\n\n   void MCPDFT::translate() {\n     translate_density();\n     if ( is_gga_ ) {\n        translate_density_gradients();\n     }\n   }\n\n   void MCPDFT::translate_density() {\n      double tol = 1.0e-20;\n      size_t npts = get_npts();\n      arma::vec rho_vec(get_rho());\n      arma::vec pi_vec(get_pi());\n      arma::vec R_vec(get_R());\n      arma::vec W(get_w());\n      arma::vec tr_rhoa(npts);\n      arma::vec tr_rhob(npts);\n      double dum_a = 0.0;\n      double dum_b = 0.0;\n      double dum_tot = 0.0;\n      double rho = 0.0;\n      double pi = 0.0;\n      double zeta = 0.0;\n      double R = 0.0;\n      #pragma parallel for schedule(static) \\\n                           default(shared) \\\n                           private(p, zeta, pi, rho, R) \\\n                           reduction(+:dum_a, dum_b, dum_tot)\n         for (int p = 0; p < npts; p++) {\n             rho = rho_vec(p);\n             pi = pi_vec(p);\n             zeta = 0.0;\n             R = 0.0;\n             if ( !(rho < tol) && !(pi < 0.0) ) {\n                R = R_vec(p);\n                if ( (1.0 - R) > tol ) {\n                   zeta = sqrt(1.0 - R);\n                }else{\n                     zeta = 0.0;\n                }\n                tr_rhoa(p) = (1.0 + zeta) * (rho/2.0);\n                tr_rhob(p) = (1.0 - zeta) * (rho/2.0);\n             }else {\n                    tr_rhoa(p) = 0.0;\n                    tr_rhob(p) = 0.0;\n             }\n             dum_a += tr_rhoa(p) * W(p);\n             dum_b += tr_rhob(p) * W(p);\n             dum_tot += ( tr_rhoa(p) + tr_rhob(p) ) * W(p) ;\n         }\n      set_tr_rhoa(tr_rhoa);\n      set_tr_rhob(tr_rhob);\n\n      printf(\"\\n\");\n      printf(\"  Integrated translated total density = %20.12lf\\n\",dum_tot);\n      printf(\"  Integrated translated alpha density = %20.12lf\\n\",dum_a);\n      printf(\"  Integrated translated beta density  = %20.12lf\\n\",dum_b);\n      printf(\"\\n\");\n   }\n \n   void MCPDFT::translate_density_gradients() {\n     double tol = 1.0e-20;\n     size_t npts = get_npts();\n     arma::vec rho_vec(get_rho());\n     arma::vec pi_vec(get_pi());\n     arma::vec R_vec(get_R());\n     double rho = 0.0;\n     double pi = 0.0;\n     double zeta = 0.0;\n     double R = 0.0;\n     double rho_x = 0.0;\n     double rho_y = 0.0;\n     double rho_z = 0.0;\n     arma::vec rho_a_x(get_rhoa_x());\n     arma::vec rho_a_y(get_rhoa_y());\n     arma::vec rho_a_z(get_rhoa_z());\n     arma::vec rho_b_x(get_rhob_x());\n     arma::vec rho_b_y(get_rhob_y());\n     arma::vec rho_b_z(get_rhob_z());\n     arma::vec tr_rho_a_x(npts,  arma::fill::zeros);\n     arma::vec tr_rho_b_x(npts,  arma::fill::zeros);\n     arma::vec tr_rho_a_y(npts,  arma::fill::zeros);\n     arma::vec tr_rho_b_y(npts,  arma::fill::zeros);\n     arma::vec tr_rho_a_z(npts,  arma::fill::zeros);\n     arma::vec tr_rho_b_z(npts,  arma::fill::zeros);\n     arma::vec tr_sigma_aa(npts, arma::fill::zeros);\n     arma::vec tr_sigma_ab(npts, arma::fill::zeros);\n     arma::vec tr_sigma_bb(npts, arma::fill::zeros);\n     #pragma parallel for schedule(static) \\\n                          default(shared) \\\n                          private(p, zeta, pi, rho, R,\\\n\t\t                  rho_x, rho_y, rho_z)\n        for (int p = 0; p < npts; p++) {\n            rho = rho_vec(p);\n            pi = pi_vec(p);\n            rho_x = rho_a_x(p) + rho_b_x(p);\n            rho_y = rho_a_y(p) + rho_b_y(p);\n            rho_z = rho_a_z(p) + rho_b_z(p);\n            zeta = 0.0;\n            R = 0.0;\n            if ( !(rho < tol) && !(pi < 0.0) ) {\n               R = R_vec(p);\n               if ( (1.0 - R) > tol )  {\n                  zeta = sqrt(1.0 - R);\n               }else{\n                    zeta = 0.0;\n               }\n               tr_rho_a_x(p) = (1.0 + zeta) * (rho_x/2.0);\n               tr_rho_b_x(p) = (1.0 - zeta) * (rho_x/2.0);\n\n               tr_rho_a_y(p) = (1.0 + zeta) * (rho_y/2.0);\n               tr_rho_b_y(p) = (1.0 - zeta) * (rho_y/2.0);\n\n               tr_rho_a_z(p) = (1.0 + zeta) * (rho_z/2.0);\n               tr_rho_b_z(p) = (1.0 - zeta) * (rho_z/2.0);\n            }else {\n                  tr_rho_a_x(p) = 0.0;\n                  tr_rho_b_x(p) = 0.0;\n                  tr_rho_a_y(p) = 0.0;\n                  tr_rho_b_y(p) = 0.0;\n                  tr_rho_a_z(p) = 0.0;\n                  tr_rho_b_z(p) = 0.0;\n            }\n            tr_sigma_aa(p) = (tr_rho_a_x(p) * tr_rho_a_x(p)) + (tr_rho_a_y(p) * tr_rho_a_y(p)) + (tr_rho_a_z(p) * tr_rho_a_z(p));\n            tr_sigma_ab(p) = (tr_rho_a_x(p) * tr_rho_b_x(p)) + (tr_rho_a_y(p) * tr_rho_b_y(p)) + (tr_rho_a_z(p) * tr_rho_b_z(p));\n            tr_sigma_bb(p) = (tr_rho_b_x(p) * tr_rho_b_x(p)) + (tr_rho_b_y(p) * tr_rho_b_y(p)) + (tr_rho_b_z(p) * tr_rho_b_z(p));\n        }\n     set_tr_sigma_aa(tr_sigma_aa);\n     set_tr_sigma_ab(tr_sigma_ab);\n     set_tr_sigma_bb(tr_sigma_bb);\n   }\n\n   void MCPDFT::fully_translate() {\n     fully_translate_density();\n     if ( is_gga_ ) {\n        fully_translate_density_gradients();\n     }\n   }\n\n   void MCPDFT::fully_translate_density(){\n        double tol = 1.0e-20;\n        double const R0 = 0.9;\n        double const R1 = 1.15;\n        double const A = -475.60656009;\n        double const B = -379.47331922;\n        double const C = -85.38149682;\n\n        size_t npts = get_npts();\n        arma::vec rho_vec(get_rho());\n        arma::vec pi_vec(get_pi());\n        arma::vec R_vec(get_R());\n        arma::vec W(get_w());\n        arma::vec tr_rhoa(npts);\n        arma::vec tr_rhob(npts);\n        arma::vec tr_rho(npts);\n\n        double rho = 0.0;\n        double pi = 0.0;\n        double zeta = 0.0;\n        double R = 0.0;\n        double DelR = 0.0;\n        double temp_tot = 0.0;\n        double temp_a = 0.0;\n        double temp_b = 0.0;\n        #pragma parallel for schedule(static) \\\n                             default(shared) \\\n                             private(p, zeta, pi, rho) \\\n                             reduction(+:dum_a, dum_b, dum_tot)\n        for (int p = 0; p < npts; p++) {\n            zeta = 0.0;\n            R = 0.0;\n            rho = rho_vec(p);\n            pi = pi_vec(p);\n            DelR = R_vec(p) - R1;\n            if ( !(rho < tol) && !(pi < 0.0) ) {\n               R = R_vec(p);\n               if ( ((1.0 - R) > tol) && ( R < R0 ) ) {\n                  zeta = sqrt(1.0 - R);\n               }else if( !(R < R0) && !(R > R1) ) {\n                       zeta = A * pow(DelR, 5.0) + B * pow(DelR, 4.0) + C * pow(DelR, 3.0);\n               }else if( R > R1 ) {\n                       zeta = 0.0;\n               }\n               tr_rhoa(p) = (1.0 + zeta) * (rho/2.0);\n               tr_rhob(p) = (1.0 - zeta) * (rho/2.0);\n            }else{\n                 tr_rhoa(p) = 0.0;\n                 tr_rhob(p) = 0.0;\n            }\n            temp_a += tr_rhoa(p) * W(p);\n            temp_b += tr_rhob(p) * W(p);\n            temp_tot += ( tr_rhob(p) + tr_rhoa(p) ) * W(p);\n        }\n        set_tr_rhoa(tr_rhoa);\n        set_tr_rhob(tr_rhob);\n\n        printf(\"\\n\");\n        printf(\"      Integrated fully translated total density = %20.12lf\\n\",temp_tot);\n        printf(\"      Integrated fully translated alpha density = %20.12lf\\n\",temp_a);\n        printf(\"      Integrated fully translated beta density  = %20.12lf\\n\",temp_b);\n        printf(\"\\n\");\n   }\n\n   void MCPDFT::fully_translate_density_gradients(){\n        double tol = 1.0e-20;\n        size_t npts = get_npts();\n\n        arma::vec rho_vec(get_rho());\n        arma::vec pi_vec(get_pi());\n        arma::vec R_vec(get_R());\n        arma::vec W(get_w());\n        arma::vec tr_rhoa(npts);\n        arma::vec tr_rhob(npts);\n        arma::vec tr_rho(npts);\n\n        double const R0 = 0.9;\n        double const R1 = 1.15;\n        double const A = -475.60656009;\n        double const B = -379.47331922;\n        double const C = -85.38149682;\n\n        arma::vec tr_rho_a_x(npts,  arma::fill::zeros);\n        arma::vec tr_rho_b_x(npts,  arma::fill::zeros);\n        arma::vec tr_rho_a_y(npts,  arma::fill::zeros);\n        arma::vec tr_rho_b_y(npts,  arma::fill::zeros);\n        arma::vec tr_rho_a_z(npts,  arma::fill::zeros);\n        arma::vec tr_rho_b_z(npts,  arma::fill::zeros);\n        arma::vec tr_sigma_aa(npts, arma::fill::zeros);\n        arma::vec tr_sigma_ab(npts, arma::fill::zeros);\n        arma::vec tr_sigma_bb(npts, arma::fill::zeros);\n        double rho_x = 0.0;\n        double rho_y = 0.0;\n        double rho_z = 0.0;\n        double rho = 0.0; \n        double pi = 0.0;\n        double DelR = 0.0;\n        double zeta = 0.0;\n        double R = 0.0;\n        double temp_tot = 0.0;\n        double temp_a = 0.0;\n        double temp_b = 0.0;\n        #pragma parallel for schedule(static) \\\n                             default(shared) \\\n                             private(p, zeta, pi, rho, R, DelR,\\\n                                     rho_x, rho_y, rho_z)\n           for (int p = 0; p < npts; p++) {\n               rho_x = rho_a_x_(p) + rho_b_x_(p);\n               rho_y = rho_a_y_(p) + rho_b_y_(p);\n               rho_z = rho_a_z_(p) + rho_b_z_(p);\n               rho = rho_vec(p);\n               pi = pi_vec(p);\n               DelR = R_vec(p) - R1;\n               zeta = 0.0;\n               R = 0.0;\n               if ( !(rho < tol) && !(pi < 0.0) ) {\n                   R = R_vec(p);\n                   if ( ((1.0 - R) > tol) && ( R < R0 ) ) {\n                      zeta = sqrt(1.0 - R);\n                      tr_rho_a_x(p) = (1.0 + zeta) * (rho_x/2.0) + (R * rho_x) / (2.0*zeta) - pi_x_(p) / (rho*zeta);\n                      tr_rho_b_x(p) = (1.0 - zeta) * (rho_x/2.0) - (R * rho_x) / (2.0*zeta) + pi_x_(p) / (rho*zeta);\n                      tr_rho_a_y(p) = (1.0 + zeta) * (rho_y/2.0) + (R * rho_y) / (2.0*zeta) - pi_y_(p) / (rho*zeta);\n                      tr_rho_b_y(p) = (1.0 - zeta) * (rho_y/2.0) - (R * rho_y) / (2.0*zeta) + pi_y_(p) / (rho*zeta);\n                      tr_rho_a_z(p) = (1.0 + zeta) * (rho_z/2.0) + (R * rho_z) / (2.0*zeta) - pi_z_(p) / (rho*zeta);\n                      tr_rho_b_z(p) = (1.0 - zeta) * (rho_z/2.0) - (R * rho_z) / (2.0*zeta) + pi_z_(p) / (rho*zeta);\n                   }else if( !(R < R0) && !(R > R1) ) {\n                           zeta = A * pow(DelR, 5.0) + B * pow(DelR, 4.0) + C * pow(DelR, 3.0);\n\n                           tr_rho_a_x(p) = (1.0 + zeta) * (rho_x/2.0)\n                                          + (A * pow(DelR, 4.0)) * ( (10.0 * pi_x_(p) / rho) - (5.0 * R * rho_x) )\n                                          + (B * pow(DelR, 3.0)) * ( (8.0  * pi_x_(p) / rho) - (4.0 * R * rho_x) )\n                                          + (C * pow(DelR, 2.0)) * ( (6.0  * pi_x_(p) / rho) - (3.0 * R * rho_x) );\n\n                           tr_rho_b_x(p) = (1.0 - zeta) * (rho_x/2.0)\n                                          + (A * pow(DelR, 4.0)) * (-(10.0 * pi_x_(p) / rho) + (5.0 * R * rho_x) )\n                                          + (B * pow(DelR, 3.0)) * (-(8.0  * pi_x_(p) / rho) + (4.0 * R * rho_x) )\n                                          + (C * pow(DelR, 2.0)) * (-(6.0  * pi_x_(p) / rho) + (3.0 * R * rho_x) );\n\n                           tr_rho_a_y(p) = (1.0 + zeta) * (rho_y/2.0)\n                                          + (A * pow(DelR, 4.0)) * ( (10.0 * pi_y_(p) / rho) - (5.0 * R * rho_y) )\n                                          + (B * pow(DelR, 3.0)) * ( (8.0  * pi_y_(p) / rho) - (4.0 * R * rho_y) )\n                                          + (C * pow(DelR, 2.0)) * ( (6.0  * pi_y_(p) / rho) - (3.0 * R * rho_y) );\n\n                           tr_rho_b_y(p) = (1.0 - zeta) * (rho_y/2.0)\n                                          + (A * pow(DelR, 4.0)) * (-(10.0 * pi_y_(p) / rho) + (5.0 * R * rho_y) )\n                                          + (B * pow(DelR, 3.0)) * (-(8.0  * pi_y_(p) / rho) + (4.0 * R * rho_y) )\n                                          + (C * pow(DelR, 2.0)) * (-(6.0  * pi_y_(p) / rho) + (3.0 * R * rho_y) );\n\n                           tr_rho_a_z(p) = (1.0 + zeta) * (rho_z/2.0)\n                                          + (A * pow(DelR, 4.0)) * ( (10.0 * pi_z_(p) / rho) - (5.0 * R * rho_z) )\n                                          + (B * pow(DelR, 3.0)) * ( (8.0  * pi_z_(p) / rho) - (4.0 * R * rho_z) )\n                                          + (C * pow(DelR, 2.0)) * ( (6.0  * pi_z_(p) / rho) - (3.0 * R * rho_z) );\n\n                           tr_rho_b_z(p) = (1.0 - zeta) * (rho_z/2.0)\n                                           + (A * pow(DelR, 4.0)) * (-(10.0 * pi_z_(p) / rho) + (5.0 * R * rho_z) )\n                                           + (B * pow(DelR, 3.0)) * (-(8.0  * pi_z_(p) / rho) + (4.0 * R * rho_z) )\n                                           + (C * pow(DelR, 2.0)) * (-(6.0  * pi_z_(p) / rho) + (3.0 * R * rho_z) );\n                   }else if( R > R1 ) {\n                           zeta = 0.0;\n                           tr_rho_a_x(p) = (1.0 + zeta) * (rho_x/2.0);\n                           tr_rho_b_x(p) = (1.0 - zeta) * (rho_x/2.0);\n                           tr_rho_a_y(p) = (1.0 + zeta) * (rho_y/2.0);\n                           tr_rho_b_y(p) = (1.0 - zeta) * (rho_y/2.0);\n                           tr_rho_a_z(p) = (1.0 + zeta) * (rho_z/2.0);\n                           tr_rho_b_z(p) = (1.0 - zeta) * (rho_z/2.0);\n                   }\n               }else{\n                   tr_rho_a_x(p) = 0.0;\n                   tr_rho_b_x(p) = 0.0;\n                   tr_rho_a_y(p) = 0.0;\n                   tr_rho_b_y(p) = 0.0;\n                   tr_rho_a_z(p) = 0.0;\n                   tr_rho_b_z(p) = 0.0;\n               }\n               tr_sigma_aa(p) = (tr_rho_a_x(p) * tr_rho_a_x(p)) + (tr_rho_a_y(p) * tr_rho_a_y(p)) + (tr_rho_a_z(p) * tr_rho_a_z(p));\n               tr_sigma_ab(p) = (tr_rho_a_x(p) * tr_rho_b_x(p)) + (tr_rho_a_y(p) * tr_rho_b_y(p)) + (tr_rho_a_z(p) * tr_rho_b_z(p));\n               tr_sigma_bb(p) = (tr_rho_b_x(p) * tr_rho_b_x(p)) + (tr_rho_b_y(p) * tr_rho_b_y(p)) + (tr_rho_b_z(p) * tr_rho_b_z(p));\n           }\n        set_tr_sigma_aa(tr_sigma_aa);\n        set_tr_sigma_ab(tr_sigma_ab);\n        set_tr_sigma_bb(tr_sigma_bb);\n   }\n\n   void MCPDFT::build_opdm() {\n      // fetching the number of basis functions\n      int nbfs;\n      nbfs = get_nbfs();\n \n      // getting the AO->MO transformation matrix C\n      arma::mat ca(get_cmat());\n      arma::mat cb(get_cmat());\n \n      // building the 1-electron reduced density matrices (1RDMs)\n      arma::mat D1a(nbfs, nbfs, arma::fill::zeros);\n      arma::mat D1b(nbfs, nbfs, arma::fill::zeros);\n      for (int mu = 0; mu < nbfs; mu++) { \n          for (int nu = 0; nu < nbfs; nu++) { \n              double duma = 0.0;\n              double dumb = 0.0;\n              for (int i = 0; i < nbfs/2; i++) { \n                   duma += ca(mu, i) * ca(nu, i);\n                   dumb += cb(mu, i) * cb(nu, i);\n              }\n              D1a(mu, nu) = duma;\n              D1b(mu, nu) = dumb;\n         }\n      }\n      // D1a(0,0) = 1.0;\n      // D1b(0,0) = 1.0;\n      D1a.print(\"D1a = \");\n      D1b.print(\"D1b = \");\n      set_D1a(D1a);\n      set_D1b(D1b);\n   }\n \n   void MCPDFT::build_tpdm() {\n      // fetching the number of basis functions\n      int nbfs  = get_nbfs();\n      int nbfs2 = nbfs * nbfs;\n \n      arma::mat D1a(get_D1a());\n      arma::mat D1b(get_D1b());\n \n      arma::mat D2ab(nbfs2, nbfs2, arma::fill::zeros);\n      D2ab = arma::kron(D1a,D1b);\n      // D2ab.print(\"D2ab = \");\n      set_D2ab(D2ab);\n   }\n \n   bool MCPDFT::is_gga() const { return is_gga_; }\n   size_t MCPDFT::get_npts() const { return npts_; }\n   int    MCPDFT::get_nbfs() const { return nbfs_; }\n   arma::vec MCPDFT::get_w() const { return w_; }\n   arma::vec MCPDFT::get_x() const { return x_; }\n   arma::vec MCPDFT::get_y() const { return y_; }\n   arma::vec MCPDFT::get_z() const { return z_; }\n   arma::mat MCPDFT::get_phi() const { return phi_; }\n   arma::mat MCPDFT::get_phi_x() const { return phi_x_; }\n   arma::mat MCPDFT::get_phi_y() const { return phi_y_; }\n   arma::mat MCPDFT::get_phi_z() const { return phi_z_; }\n   double MCPDFT::get_eref() const { return eref_; }\n   double MCPDFT::get_eclass()  const { return eclass_; }\n   arma::mat MCPDFT::get_cmat() const { return cmat_; }\n   arma::mat MCPDFT::get_D1a()  const { return D1a_ ; }\n   arma::mat MCPDFT::get_D1b()  const { return D1b_ ; }\n   arma::mat MCPDFT::get_D2ab()  const { return D2ab_ ; }\n   arma::vec MCPDFT::get_rhoa() const { return rho_a_; }\n   arma::vec MCPDFT::get_rhoa_x() const { return rho_a_x_; }\n   arma::vec MCPDFT::get_rhoa_y() const { return rho_a_y_; }\n   arma::vec MCPDFT::get_rhoa_z() const { return rho_a_z_; }\n   arma::vec MCPDFT::get_rhob() const { return rho_b_; }\n   arma::vec MCPDFT::get_rhob_x() const { return rho_b_x_; }\n   arma::vec MCPDFT::get_rhob_y() const { return rho_b_y_; }\n   arma::vec MCPDFT::get_rhob_z() const { return rho_b_z_; }\n   arma::vec MCPDFT::get_rho() const { return rho_; }\n   arma::vec MCPDFT::get_tr_rhoa() const { return tr_rho_a_; }\n   arma::vec MCPDFT::get_tr_rhob() const { return tr_rho_b_; }\n   arma::vec MCPDFT::get_tr_rho() const { return tr_rho_; }\n   arma::vec MCPDFT::get_pi() const { return pi_; }\n   arma::vec MCPDFT::get_R() const { return R_; }\n   arma::vec MCPDFT::get_sigma_aa() const { return sigma_aa_; }\n   arma::vec MCPDFT::get_sigma_ab() const { return sigma_ab_; }\n   arma::vec MCPDFT::get_sigma_bb() const { return sigma_bb_; }\n   arma::vec MCPDFT::get_tr_sigma_aa() const { return tr_sigma_aa_; }\n   arma::vec MCPDFT::get_tr_sigma_ab() const { return tr_sigma_ab_; }\n   arma::vec MCPDFT::get_tr_sigma_bb() const { return tr_sigma_bb_; }\n\n   void MCPDFT::set_npts(const size_t npts) { npts_ = npts; }\n   void MCPDFT::set_nbfs(const int nbfs)    { nbfs_ = nbfs; }\n   void MCPDFT::set_w(const arma::vec &w) { w_ = w; }\n   void MCPDFT::set_x(const arma::vec &x) { x_ = x; }\n   void MCPDFT::set_y(const arma::vec &y) { y_ = y; }\n   void MCPDFT::set_z(const arma::vec &z) { z_ = z; }\n   void MCPDFT::set_phi(const arma::mat &phi) { phi_ = phi; }\n   void MCPDFT::set_phi_x(const arma::mat &phi_x) { phi_x_ = phi_x; }\n   void MCPDFT::set_phi_y(const arma::mat &phi_y) { phi_y_ = phi_y; }\n   void MCPDFT::set_phi_z(const arma::mat &phi_z) { phi_z_ = phi_z; }\n   void MCPDFT::set_eref(const double eref) { eref_ = eref; }\n   void MCPDFT::set_eclass(const double eclass) { eclass_ = eclass; }\n   void MCPDFT::set_cmat(const arma::mat &cmat) { cmat_ = cmat; }\n   void MCPDFT::set_D1a(const arma::mat &D1a) { D1a_ = D1a; }\n   void MCPDFT::set_D1b(const arma::mat &D1b) { D1b_ = D1b; }\n   void MCPDFT::set_D2ab(const arma::mat &D2ab) { D2ab_ = D2ab; }\n   void MCPDFT::set_rhoa(const arma::vec &rhoa) { rho_a_ = rhoa; }\n   void MCPDFT::set_rhoa_x(const arma::vec &rhoa_x) { rho_a_x_ = rhoa_x; }\n   void MCPDFT::set_rhoa_y(const arma::vec &rhoa_y) { rho_a_y_ = rhoa_y; }\n   void MCPDFT::set_rhoa_z(const arma::vec &rhoa_z) { rho_a_z_ = rhoa_z; }\n   void MCPDFT::set_rhob(const arma::vec &rhob) { rho_b_ = rhob; }\n   void MCPDFT::set_rhob_x(const arma::vec &rhob_x) { rho_b_x_ = rhob_x; }\n   void MCPDFT::set_rhob_y(const arma::vec &rhob_y) { rho_b_y_ = rhob_y; }\n   void MCPDFT::set_rhob_z(const arma::vec &rhob_z) { rho_b_z_ = rhob_z; }\n   void MCPDFT::set_rho(const arma::vec &rho) { rho_ = rho; }\n   void MCPDFT::set_tr_rhoa(const arma::vec &tr_rhoa) { tr_rho_a_ = tr_rhoa; }\n   void MCPDFT::set_tr_rhoa_x(const arma::vec &tr_rhoa_x) { tr_rho_a_x_ = tr_rhoa_x; }\n   void MCPDFT::set_tr_rhoa_y(const arma::vec &tr_rhoa_y) { tr_rho_a_y_ = tr_rhoa_y; }\n   void MCPDFT::set_tr_rhoa_z(const arma::vec &tr_rhoa_z) { tr_rho_a_z_ = tr_rhoa_z; }\n   void MCPDFT::set_tr_rhob(const arma::vec &tr_rhob) { tr_rho_b_ = tr_rhob; }\n   void MCPDFT::set_tr_rhob_x(const arma::vec &tr_rhob_x) { tr_rho_b_x_ = tr_rhob_x; }\n   void MCPDFT::set_tr_rhob_y(const arma::vec &tr_rhob_y) { tr_rho_b_y_ = tr_rhob_y; }\n   void MCPDFT::set_tr_rhob_z(const arma::vec &tr_rhob_z) { tr_rho_b_z_ = tr_rhob_z; }\n   void MCPDFT::set_tr_rho(const arma::vec &tr_rho) { tr_rho_ = tr_rho; }\n   void MCPDFT::set_pi(const arma::vec &pi) { pi_ = pi; }\n   void MCPDFT::set_pi_x(const arma::vec &pi_x) { pi_x_ = pi_x; }\n   void MCPDFT::set_pi_y(const arma::vec &pi_y) { pi_y_ = pi_y; }\n   void MCPDFT::set_pi_z(const arma::vec &pi_z) { pi_z_ = pi_z; }\n   void MCPDFT::set_R(const arma::vec &R) { R_ = R; }\n   void MCPDFT::set_sigma_aa(const arma::vec &sigma_aa) { sigma_aa_ = sigma_aa; }\n   void MCPDFT::set_sigma_ab(const arma::vec &sigma_ab) { sigma_ab_ = sigma_ab; }\n   void MCPDFT::set_sigma_bb(const arma::vec &sigma_bb) { sigma_bb_ = sigma_bb; }\n   void MCPDFT::set_tr_sigma_aa(const arma::vec &tr_sigma_aa) { tr_sigma_aa_ = tr_sigma_aa; }\n   void MCPDFT::set_tr_sigma_ab(const arma::vec &tr_sigma_ab) { tr_sigma_ab_ = tr_sigma_ab; }\n   void MCPDFT::set_tr_sigma_bb(const arma::vec &tr_sigma_bb) { tr_sigma_bb_ = tr_sigma_bb; }\n\n   void MCPDFT::print_banner() const {\n      printf(\"\\n******************************************************************\\n\");\n      printf(\"*                                                                *\\n\");\n      printf(\"*                           OpenRDM:                             *\\n\");\n      printf(\"*                                                                *\\n\");\n      printf(\"*                 An open-source library for                     *\\n\");\n      printf(\"*    reduced-density matrix-based analysis and computation       *\\n\");\n      printf(\"*                                                                *\\n\");\n      printf(\"*                     Mohammad Mostafanejad                      *\\n\");\n      printf(\"*                   Florida State University                     *\\n\");\n      printf(\"*                                                                *\\n\");\n      printf(\"******************************************************************\\n\");\n\n\n      printf(\"\\n           Please cite the following article(s):\\n\\n\");\n\n      printf(\"    # M. Mostafanejad and A. E. DePrince III\\n\");\n      printf(\"      J. Chem. Theory Comput. 15, 290-302 (2019).\\n\");\n   }\n}\n", "meta": {"hexsha": "2fddcb25e94c5cb3f6d70f64851cd4768c7a87bf", "size": 33707, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libmcpdft/mcpdft.cc", "max_stars_repo_name": "SinaMostafanejad/libRDMInoles", "max_stars_repo_head_hexsha": "0cc9fba75755cfa046f352a6aca80e77af261ca3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2019-11-19T14:23:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-14T08:41:55.000Z", "max_issues_repo_path": "src/libmcpdft/mcpdft.cc", "max_issues_repo_name": "SinaMostafanejad/libRDMInoles", "max_issues_repo_head_hexsha": "0cc9fba75755cfa046f352a6aca80e77af261ca3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libmcpdft/mcpdft.cc", "max_forks_repo_name": "SinaMostafanejad/libRDMInoles", "max_forks_repo_head_hexsha": "0cc9fba75755cfa046f352a6aca80e77af261ca3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-11-13T05:00:51.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-29T02:39:04.000Z", "avg_line_length": 44.4683377309, "max_line_length": 142, "alphanum_fraction": 0.4639689085, "num_tokens": 10506, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246118695629, "lm_q2_score": 0.5888891307678319, "lm_q1q2_score": 0.49073580633130776}}
{"text": "#include \"extent.hpp\"\n\n#include <algorithm>\n#include <boost/algorithm/clamp.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <cmath>\n#include <utility>\n#include \"../common/geom.hpp\"\n#include \"../common/helpers/eigen_helpers.hpp\"\n\nconst double PI = boost::math::constants::pi<double>();\n\nnamespace ear {\n\n  /** @brief Normalise position or return {0,1,0}.\n   *\n   * @param position  Position to normalise.\n   *\n   * @returns normalised position\n   */\n  Eigen::Vector3d safeNormPosition(Eigen::Vector3d position) {\n    double norm = position.norm();\n    if (norm < 1e-10) {\n      return Eigen::Vector3d{0.0, 1.0, 0.0};\n    } else {\n      return position / norm;\n    }\n  }\n\n  double extentMod(double extent, double distance) {\n    double minSize = 0.2;\n    double size = interp(extent, Eigen::Vector2d(0.0, 360.0),\n                         Eigen::Vector2d(minSize, 1.0));\n    double extent1 = 4.0 * degrees(atan2(size, 1.0));\n    return interp(4.0 * degrees(atan2(size, distance)),\n                  Eigen::Vector3d(0.0, extent1, 360.0),\n                  Eigen::Vector3d(0.0, extent, 360.0));\n  }\n\n  Eigen::Matrix3d calcBasis(Eigen::Vector3d position) {\n    position = safeNormPosition(position);\n    double az = azimuth(position);\n    double el = elevation(position);\n\n    // points near the poles have indeterminate azimuth; assume 0\n    if (std::abs(el) > (90.0 - 1e-5)) {\n      az = 0.0;\n    }\n    return localCoordinateSystem(az, el);\n  }\n\n  Eigen::Vector3d cartOnBasis(Eigen::Matrix3d basis, double azimuth,\n                              double elevation) {\n    Eigen::RowVector3d cartPosRel{sin(azimuth) * cos(elevation),\n                                  cos(azimuth) * cos(elevation),\n                                  sin(elevation)};\n    return cartPosRel * basis;\n  }\n\n  std::pair<double, double> azimuthElevationOnBasis(\n      Eigen::Matrix3d basis, Eigen::RowVector3d position) {\n    // project onto each basis, and clip components to keep asin happy\n    Eigen::Vector3d components =\n        (position * basis.transpose()).cwiseMin(1.0).cwiseMax(-1.0);\n\n    double azimuth = atan2(components(0), components(1));\n    double elevation = asin(components(2));\n\n    return std::make_pair(azimuth, elevation);\n  }\n\n  WeightingFunction::WeightingFunction(Eigen::Vector3d position, double width,\n                                       double height) {\n    _width = radians(width) / 2;\n    _height = radians(height) / 2;\n\n    // basis vectors to rotate the vsource positions towards position\n    Eigen::Matrix3d basises = calcBasis(position);\n\n    _circleRadius = std::min(_width, _height);\n\n    // Flip the width and the height such that it is always wider than it is\n    // high from here in.\n    if (_height > _width) {\n      std::swap(_height, _width);\n      _flippedBasis = basises.colwise().reverse();\n    } else {\n      _flippedBasis = basises;\n    }\n\n    // modify the width to make it meet at the back.\n    double widthFull = PI + _height;\n    // interpolate to this from a width of pi/2 to pi\n    double widthMod = interp(_width, Eigen::Vector3d{0.0, PI / 2.0, PI},\n                             Eigen::Vector3d{0.0, PI / 2.0, widthFull});\n    // apply this fully for a height of less than pi/4; tail off until pi/2\n    _width = interp(_height, Eigen::Vector4d{0, PI / 4.0, PI / 2.0, PI},  //\n                    Eigen::Vector4d{widthMod, widthMod, _width, _width});  //\n\n    // angle of the circle centres from the source position; width is to the\n    // end of the rectangle.\n    _circlePos = _width - _circleRadius;\n\n    // Cartesian circle centres\n    _circlePositions << cartOnBasis(_flippedBasis, -_circlePos, 0.0),\n        cartOnBasis(_flippedBasis, _circlePos, 0.0);\n  }\n\n  double WeightingFunction::operator()(Eigen::Vector3d position) const {\n    // Flipped azimuths and elevations; the straight edges are always along\n    // azimuth lines.\n    double azimuth, elevation;\n    std::tie(azimuth, elevation) =\n        azimuthElevationOnBasis(_flippedBasis, position);\n\n    // The distance is the angle away from the defined shape; 0 or negative is\n    // inside.\n    double distance = 0.0;\n\n    // for the straight lines\n    if (std::abs(azimuth) <= _circlePos) {\n      distance = std::abs(elevation) - _circleRadius;\n    } else {\n      // distance from the closest circle centre\n      size_t nearest_circle = azimuth < 0 ? 0 : 1;\n      double angle =\n          position.transpose() * _circlePositions.col(nearest_circle);\n      double circleDistance = acos(boost::algorithm::clamp(angle, -1.0, 1.0));\n      distance = circleDistance - _circleRadius;\n    }\n    // fade the weight from one to zero over fadeWidth\n    return interp(distance, Eigen::Vector2d{0.0, radians(_fadeWidth)},\n                  Eigen::Vector2d{1.0, 0.0});\n  }\n\n  SpreadingPanner::SpreadingPanner(std::shared_ptr<PointSourcePanner> psp,\n                                   int nRows)\n      : _psp(psp), _nRows(nRows) {\n    _panningPositions = _generatePanningPositionsEven();\n    _panningPositionsResults = _generatePanningPositionsResults();\n  }\n\n  Eigen::VectorXd SpreadingPanner::panningValuesForWeight(\n      const WeightingFunction& weightFunc) {\n    Eigen::VectorXd weights(_panningPositions.rows());\n    for (int i = 0; i < _panningPositions.rows(); ++i) {\n      weights(i) = weightFunc(_panningPositions.row(i));\n    }\n    Eigen::VectorXd totalPv = weights.transpose() * _panningPositionsResults;\n    return totalPv / totalPv.norm();\n  }\n\n  Eigen::MatrixXd SpreadingPanner::_generatePanningPositionsEven() {\n    Eigen::VectorXd elevations =\n        Eigen::VectorXd::LinSpaced(_nRows, -90.0, 90.0);\n    Eigen::MatrixXd positions(0, 3);\n\n    for (double el : elevations) {\n      double radius = cos(radians(el));\n      double perimiter = 2 * PI * radius;\n      double perimiter_centre = 2 * PI;\n\n      int nPoints = static_cast<int>(\n          std::round((perimiter / perimiter_centre) * 2 * (_nRows - 1)));\n      if (nPoints == 0) {\n        nPoints = 1;\n      }\n      Eigen::VectorXd azimuths =\n          Eigen::VectorXd::LinSpaced(nPoints + 1, 0.0, 360.0);\n      for (int i = 0; i < azimuths.size() - 1; ++i) {\n        double az = azimuths(i);\n        positions.conservativeResize(positions.rows() + 1, Eigen::NoChange);\n        positions.row(positions.rows() - 1) = cart(az, el, 1.0);\n      }\n    }\n    return positions;\n  }\n\n  Eigen::MatrixXd SpreadingPanner::_generatePanningPositionsResults() {\n    Eigen::MatrixXd results(_panningPositions.rows(),\n                            _psp->numberOfOutputChannels());\n    for (int i = 0; i < _panningPositions.rows(); ++i) {\n      results.row(i) = _psp->handle(_panningPositions.row(i)).get();\n    }\n    return results;\n  }\n\n  PolarExtentPanner::PolarExtentPanner(std::shared_ptr<PointSourcePanner> psp)\n      : _psp(psp), _spreadingPanner(SpreadingPanner(psp, _nRows)){};\n\n  Eigen::VectorXd PolarExtentPanner::calcPvSpread(Eigen::Vector3d position,\n                                                  double width, double height) {\n    // When calculating the spread panning values the width and height are\n    // set to at least fade_width. For sizes where any of the dimensions is\n    // less than this, interpolate linearly between the point and spread\n    // panning values.\n    double ammount_spread =\n        interp(std::max(width, height), Eigen::Vector2d(0.0, _fadeWidth),\n               Eigen::Vector2d(0.0, 1.0));\n    double ammountPoint = 1.0 - ammount_spread;\n    Eigen::ArrayXd pv = Eigen::ArrayXd::Zero(_psp->numberOfOutputChannels());\n    if (ammountPoint > 1e-10) {\n      pv += ammountPoint * _psp->handle(position).get().array().square();\n    }\n    if (ammount_spread > 1e-10) {\n      // minimum width and height as above\n      width = std::max(width, _fadeWidth / 2.0);\n      height = std::max(height, _fadeWidth / 2.0);\n\n      WeightingFunction weightingFunction(position, width, height);\n      Eigen::VectorXd panning_values =\n          _spreadingPanner.panningValuesForWeight(weightingFunction);\n      pv += ammount_spread * panning_values.array().square();\n    }\n    return pv.sqrt().matrix();\n  }\n\n  Eigen::VectorXd PolarExtentPanner::handle(Eigen::Vector3d position,\n                                            double width, double height,\n                                            double depth) {\n    double distance = position.norm();\n\n    if (depth != 0.0) {\n      double distanceMin = distance - depth / 2.0;\n      double distanceMax = distance + depth / 2.0;\n      distanceMin = (distanceMin < 0) ? 0.0 : distanceMin;\n      distanceMax = (distanceMax < 0) ? 0.0 : distanceMax;\n      Eigen::VectorXd pvsMin =\n          calcPvSpread(position, extentMod(width, distanceMin),\n                       extentMod(height, distanceMin));\n      Eigen::VectorXd pvsMax =\n          calcPvSpread(position, extentMod(width, distanceMax),\n                       extentMod(height, distanceMax));\n      return ((pvsMin.array().square() + pvsMax.array().square()) / 2.0).sqrt();\n    } else {\n      Eigen::VectorXd pvs = calcPvSpread(position, extentMod(width, distance),\n                                         extentMod(height, distance));\n      return pvs;\n    }\n  }\n\n}  // namespace ear\n", "meta": {"hexsha": "f5d0fc1940e4f22fa5c2e8cd37fbc2cb82ff5bf9", "size": 9157, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/object_based/extent.cpp", "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/object_based/extent.cpp", "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/object_based/extent.cpp", "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": 37.683127572, "max_line_length": 80, "alphanum_fraction": 0.6252047614, "num_tokens": 2431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246077301781, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.49073580389366916}}
{"text": "// C++ standard headers\r\n#include <iostream>\r\n\r\n// C++ third party headers \r\n#include <Eigen/Core>\r\n\r\n// User defined headers\r\n#include \"Header.h\"\r\n#include \"RandomSampling.h\"\r\n\r\nusing namespace std;\r\nint main() {\r\n\tcout << \"hello world\" << endl;\r\n\tcout << \"Eigen version : \" << EIGEN_MAJOR_VERSION << \" . \" << EIGEN_MINOR_VERSION << endl;\r\n\tcout << sum(2, 3) << endl;\r\n\r\n\tEigen::MatrixXd var(2, 2);\r\n\tvar << 1, 0,\r\n\t\t\t\t0, 1;\r\n\r\n\tcout << var << \"\\n\";\r\n\r\n\tRandomSampling* rs;\r\n\tGaussianRandomSampling g;\r\n\trs = &g;\r\n\r\n\t// virtual random generator function binded at runtime\r\n\tcout << rs->generate_random_seq(1) << endl;\r\n}\r\n", "meta": {"hexsha": "72c92847f6475d259c12cac283fdba1063929ea9", "size": 623, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ekf/main.cpp", "max_stars_repo_name": "mantoshkumar1/imm-filter", "max_stars_repo_head_hexsha": "17b39a99f57987c6c6342c1e6ac14dc33fd4b7e6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-05-09T07:49:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-26T09:16:49.000Z", "max_issues_repo_path": "ekf/main.cpp", "max_issues_repo_name": "mantoshkumar1/imm-filter", "max_issues_repo_head_hexsha": "17b39a99f57987c6c6342c1e6ac14dc33fd4b7e6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ekf/main.cpp", "max_forks_repo_name": "mantoshkumar1/imm-filter", "max_forks_repo_head_hexsha": "17b39a99f57987c6c6342c1e6ac14dc33fd4b7e6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-06-15T05:43:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-15T05:43:42.000Z", "avg_line_length": 20.7666666667, "max_line_length": 92, "alphanum_fraction": 0.6131621188, "num_tokens": 167, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. Yes\n2. Yes", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.8333245891029457, "lm_q1q2_score": 0.4907357929242945}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2015 NumScale SAS\n  @copyright 2015 J.T. Lapreste\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_COMMON_GENERIC_FUNCTION_MOD_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_GENERIC_FUNCTION_MOD_HPP_INCLUDED\n\n#include <boost/simd/function/div.hpp>\n#include <boost/simd/function/idiv.hpp>\n#include <boost/simd/function/is_nez.hpp>\n#include <boost/simd/function/multiplies.hpp>\n#include <boost/simd/function/selsub.hpp>\n#include <boost/dispatch/function/overload.hpp>\n#include <boost/config.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  BOOST_DISPATCH_OVERLOAD ( mod_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::generic_<bd::floating_<A0> >\n                          , bd::generic_<bd::floating_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() ( A0 a0, A0  a1) const BOOST_NOEXCEPT\n    {\n      return selsub(is_nez(a1),a0,div(a0,a1,floor)*a1 );\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( mod_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::generic_<bd::arithmetic_<A0> >\n                          , bd::generic_<bd::arithmetic_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() ( A0 a0, A0 a1) const BOOST_NOEXCEPT\n    {\n      return selsub(is_nez(a1),a0,simd::multiplies(idiv(a0,a1,floor),a1));\n    }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "24591fea7262356f92acf4d0c9f8e50c486752b6", "size": 1791, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arch/common/generic/function/mod.hpp", "max_stars_repo_name": "yaeldarmon/boost.simd", "max_stars_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/simd/arch/common/generic/function/mod.hpp", "max_issues_repo_name": "yaeldarmon/boost.simd", "max_issues_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/arch/common/generic/function/mod.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": 32.5636363636, "max_line_length": 100, "alphanum_fraction": 0.5326633166, "num_tokens": 409, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744939732855, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.49069869411081857}}
{"text": "#ifndef STAN_MATH_PRIM_SCAL_FUN_BESSEL_SECOND_KIND_HPP\n#define STAN_MATH_PRIM_SCAL_FUN_BESSEL_SECOND_KIND_HPP\n\n#include <boost/math/special_functions/bessel.hpp>\n\nnamespace stan {\nnamespace math {\n\n/**\n *\n   \\f[\n   \\mbox{bessel\\_second\\_kind}(v, x) =\n   \\begin{cases}\n     \\textrm{error} & \\mbox{if } x \\leq 0 \\\\\n     Y_v(x) & \\mbox{if } x > 0 \\\\[6pt]\n     \\textrm{NaN} & \\mbox{if } x = \\textrm{NaN}\n   \\end{cases}\n   \\f]\n\n   \\f[\n   \\frac{\\partial\\, \\mbox{bessel\\_second\\_kind}(v, x)}{\\partial x} =\n   \\begin{cases}\n     \\textrm{error} & \\mbox{if } x \\leq 0 \\\\\n     \\frac{\\partial\\, Y_v(x)}{\\partial x} & \\mbox{if } x > 0 \\\\[6pt]\n     \\textrm{NaN} & \\mbox{if } x = \\textrm{NaN}\n   \\end{cases}\n   \\f]\n\n   \\f[\n   Y_v(x)=\\frac{J_v(x)\\cos(v\\pi)-J_{-v}(x)}{\\sin(v\\pi)}\n   \\f]\n\n   \\f[\n   \\frac{\\partial \\, Y_v(x)}{\\partial x} = \\frac{v}{x}Y_v(x)-Y_{v+1}(x)\n   \\f]\n *\n */\ntemplate <typename T2>\ninline T2 bessel_second_kind(int v, const T2 z) {\n  return boost::math::cyl_neumann(v, z);\n}\n\n}  // namespace math\n}  // namespace stan\n\n#endif\n", "meta": {"hexsha": "f50e767c3dd166fabc832757de19a60014062371", "size": 1032, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/prim/scal/fun/bessel_second_kind.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/bessel_second_kind.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/bessel_second_kind.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": 21.9574468085, "max_line_length": 71, "alphanum_fraction": 0.5881782946, "num_tokens": 413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834648, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.49069868877525163}}
{"text": "#include \"heuristics/null.hpp\"\n#include \"heuristics/shortest_path.hpp\"\n#include \"heuristics/mst.hpp\"\n#include \"mapgen/mapgen.hpp\"\n#include \"solver/tspsolver.hpp\"\n\n#include <fstream>\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_ALTERNATIVE_INIT_API\n#include <boost/test/unit_test.hpp>\n\nconstexpr char csv1[] = \"a,b,c,d,e\\n\"\n                        \"0,10,4,9,10\\n\"\n                        \"10,0,3,2,4\\n\"\n                        \"4,3,0,6,8\\n\"\n                        \"9,2,6,0,3\\n\"\n                        \"10,4,8,3,0\\n\";\n\n// Example from \"http://www.ams.org/samplings/feature-column/fcarc-tsp\"\nconstexpr char csv2[] = \"a,b,c,d,e\\n\"\n                        \"0,6,9,inf,10\\n\"\n                        \"6,0,11,inf,inf\\n\"\n                        \"9,11,0,5,14\\n\"\n                        \"inf,inf,5,0,8\\n\"\n                        \"10,inf,14,8,0\\n\";\n\nbool init_unit_test() {\n\tstd::ofstream file1(\"solver_1.csv\");\n\tfile1 << csv1;\n\n\tstd::ofstream file2(\"solver_2.csv\");\n\tfile2 << csv2;\n\n\treturn true;\n}\n\nint main(int argc, char* argv[]) {\n\treturn ::boost::unit_test::unit_test_main(&init_unit_test, argc, argv);\n}\n\nBOOST_AUTO_TEST_CASE(dumb_null) {\n\tusing TSPSolver        = awesome::TSPSolver<awesome::NullHeuristic>;\n\tusing MapGraph         = TSPSolver::MapGraph;\n\tusing ConstNode        = MapGraph::ConstNode_t;\n\tusing WeightedProperty = graph::WeightedProperty;\n\n\tMapGraph map;\n\n\tmap.addEdges({{\"a\", \"b\", WeightedProperty{1}},\n\t              {\"b\", \"c\", WeightedProperty{1}},\n\t              {\"c\", \"d\", WeightedProperty{1}},\n\t              {\"d\", \"e\", WeightedProperty{1}},\n\t              {\"e\", \"a\", WeightedProperty{1}}});\n\n\tTSPSolver solver(map);\n\n\tstd::list<ConstNode> candidate{map[\"a\"], map[\"b\"], map[\"c\"], map[\"d\"], map[\"e\"], map[\"a\"]};\n\n\tBOOST_CHECK(solver.goForIt() == candidate);\n}\n\nBOOST_AUTO_TEST_CASE(dumb_shortest) {\n\tusing TSPSolver        = awesome::TSPSolver<awesome::ShortestPathHeuristic>;\n\tusing MapGraph         = TSPSolver::MapGraph;\n\tusing ConstNode        = MapGraph::ConstNode_t;\n\tusing WeightedProperty = graph::WeightedProperty;\n\n\tMapGraph map;\n\n\tmap.addEdges({{\"a\", \"b\", WeightedProperty{1}},\n\t              {\"b\", \"c\", WeightedProperty{1}},\n\t              {\"c\", \"d\", WeightedProperty{1}},\n\t              {\"d\", \"e\", WeightedProperty{1}},\n\t              {\"e\", \"a\", WeightedProperty{1}}});\n\n\tTSPSolver solver(map);\n\n\tstd::list<ConstNode> candidate{map[\"a\"], map[\"b\"], map[\"c\"], map[\"d\"], map[\"e\"], map[\"a\"]};\n\n\tBOOST_CHECK(solver.goForIt() == candidate);\n}\n\nBOOST_AUTO_TEST_CASE(dumb_mst) {\n\tusing TSPSolver        = awesome::TSPSolver<awesome::MSTHeuristic>;\n\tusing MapGraph         = TSPSolver::MapGraph;\n\tusing ConstNode        = MapGraph::ConstNode_t;\n\tusing WeightedProperty = graph::WeightedProperty;\n\n\tMapGraph map;\n\n\tmap.addEdges({{\"a\", \"b\", WeightedProperty{1}},\n\t              {\"b\", \"c\", WeightedProperty{1}},\n\t              {\"c\", \"d\", WeightedProperty{1}},\n\t              {\"d\", \"e\", WeightedProperty{1}},\n\t              {\"e\", \"a\", WeightedProperty{1}}});\n\n\tTSPSolver solver(map);\n\n\tstd::list<ConstNode> candidate{map[\"a\"], map[\"b\"], map[\"c\"], map[\"d\"], map[\"e\"], map[\"a\"]};\n\n\tBOOST_CHECK(solver.goForIt() == candidate);\n}\n\nBOOST_AUTO_TEST_CASE(solver_insolvable_null) {\n\tusing awesome::MapGen;\n\n\tusing TSPSolver = awesome::TSPSolver<awesome::NullHeuristic>;\n\tusing MapGraph  = awesome::MapGen::MapGraph;\n\n\tMapGraph map = MapGen::fromFile(\"solver_2.csv\");\n\tmap.removeEdge(map[\"d\"], map[\"c\"]);\n\tmap.removeEdge(map[\"c\"], map[\"d\"]);\n\tTSPSolver solver(map);\n\n\tBOOST_CHECK_THROW(solver.goForIt(), std::logic_error);\n}\n\nBOOST_AUTO_TEST_CASE(solver_insolvable_shortest) {\n\tusing awesome::MapGen;\n\n\tusing TSPSolver = awesome::TSPSolver<awesome::ShortestPathHeuristic>;\n\tusing MapGraph  = awesome::MapGen::MapGraph;\n\n\tMapGraph map = MapGen::fromFile(\"solver_2.csv\");\n\tmap.removeEdge(map[\"d\"], map[\"c\"]);\n\tmap.removeEdge(map[\"c\"], map[\"d\"]);\n\tTSPSolver solver(map);\n\n\tBOOST_CHECK_THROW(solver.goForIt(), std::logic_error);\n}\n\nBOOST_AUTO_TEST_CASE(solver_insolvable_mst) {\n\tusing awesome::MapGen;\n\n\tusing TSPSolver = awesome::TSPSolver<awesome::MSTHeuristic>;\n\tusing MapGraph  = awesome::MapGen::MapGraph;\n\n\tMapGraph map = MapGen::fromFile(\"solver_2.csv\");\n\tmap.removeEdge(map[\"d\"], map[\"c\"]);\n\tmap.removeEdge(map[\"c\"], map[\"d\"]);\n\tTSPSolver solver(map);\n\n\tBOOST_CHECK_THROW(solver.goForIt(), std::logic_error);\n}\n\nBOOST_AUTO_TEST_CASE(solver_sample_problem_1_null) {\n\tusing awesome::MapGen;\n\n\tusing TSPSolver = awesome::TSPSolver<awesome::NullHeuristic>;\n\tusing MapGraph  = awesome::MapGen::MapGraph;\n\tusing ConstNode = MapGraph::ConstNode_t;\n\n\tMapGraph map = MapGen::fromFile(\"solver_1.csv\");\n\tTSPSolver solver(map);\n\n\tstd::list<ConstNode> result   = solver.goForIt(),\n\t                     expected = {map[\"e\"], map[\"d\"], map[\"b\"], map[\"c\"], map[\"a\"], map[\"e\"]};\n\n\tBOOST_CHECK(result == expected);\n}\n\nBOOST_AUTO_TEST_CASE(solver_sample_problem_1_shortest) {\n\tusing awesome::MapGen;\n\n\tusing TSPSolver = awesome::TSPSolver<awesome::ShortestPathHeuristic>;\n\tusing MapGraph  = awesome::MapGen::MapGraph;\n\tusing ConstNode = MapGraph::ConstNode_t;\n\n\tMapGraph map = MapGen::fromFile(\"solver_1.csv\");\n\tTSPSolver solver(map);\n\n\tstd::list<ConstNode> result   = solver.goForIt(),\n\t                     expected = {map[\"a\"], map[\"c\"], map[\"b\"], map[\"d\"], map[\"e\"], map[\"a\"]};\n\n\tBOOST_CHECK(result == expected);\n}\n\nBOOST_AUTO_TEST_CASE(solver_sample_problem_1_mst) {\n\tusing awesome::MapGen;\n\n\tusing TSPSolver = awesome::TSPSolver<awesome::MSTHeuristic>;\n\tusing MapGraph  = awesome::MapGen::MapGraph;\n\tusing ConstNode = MapGraph::ConstNode_t;\n\n\tMapGraph map = MapGen::fromFile(\"solver_1.csv\");\n\tTSPSolver solver(map);\n\n\tstd::list<ConstNode> result   = solver.goForIt(),\n\t                     expected = {map[\"b\"], map[\"c\"], map[\"a\"], map[\"e\"], map[\"d\"], map[\"b\"]};\n\n\tBOOST_CHECK(result == expected);\n}\n\nBOOST_AUTO_TEST_CASE(solver_sample_problem_2_null) {\n\tusing awesome::MapGen;\n\n\tusing TSPSolver = awesome::TSPSolver<awesome::NullHeuristic>;\n\tusing MapGraph  = awesome::MapGen::MapGraph;\n\tusing ConstNode = MapGraph::ConstNode_t;\n\n\tMapGraph map = MapGen::fromFile(\"solver_2.csv\");\n\tTSPSolver solver(map);\n\n\tstd::list<ConstNode> result   = solver.goForIt(),\n\t                     expected = {map[\"c\"], map[\"d\"], map[\"e\"], map[\"a\"], map[\"b\"], map[\"c\"]};\n\n\tBOOST_CHECK(result == expected);\n}\n\nBOOST_AUTO_TEST_CASE(solver_sample_problem_2_shortest) {\n\tusing awesome::MapGen;\n\n\tusing TSPSolver = awesome::TSPSolver<awesome::ShortestPathHeuristic>;\n\tusing MapGraph  = awesome::MapGen::MapGraph;\n\tusing ConstNode = MapGraph::ConstNode_t;\n\n\tMapGraph map = MapGen::fromFile(\"solver_2.csv\");\n\tTSPSolver solver(map);\n\n\tstd::list<ConstNode> result   = solver.goForIt(),\n\t                     expected = {map[\"b\"], map[\"a\"], map[\"e\"], map[\"d\"], map[\"c\"], map[\"b\"]};\n\n\tBOOST_CHECK(result == expected);\n}\n\nBOOST_AUTO_TEST_CASE(solver_sample_problem_2_mst) {\n\tusing awesome::MapGen;\n\n\tusing TSPSolver = awesome::TSPSolver<awesome::MSTHeuristic>;\n\tusing MapGraph  = awesome::MapGen::MapGraph;\n\tusing ConstNode = MapGraph::ConstNode_t;\n\n\tMapGraph map = MapGen::fromFile(\"solver_2.csv\");\n\tTSPSolver solver(map);\n\n\tstd::list<ConstNode> result   = solver.goForIt(),\n\t                     expected = {map[\"d\"], map[\"c\"], map[\"b\"], map[\"a\"], map[\"e\"], map[\"d\"]};\n\n\tBOOST_CHECK(result == expected);\n}\n", "meta": {"hexsha": "97521cfb3f02a40ed4cfbc324a77d563331bfb0e", "size": 7281, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/solver_test.cpp", "max_stars_repo_name": "minijackson/PR-3602", "max_stars_repo_head_hexsha": "197c47434fcfbd4b5aa1aff85e6a680f2671f8e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/solver_test.cpp", "max_issues_repo_name": "minijackson/PR-3602", "max_issues_repo_head_hexsha": "197c47434fcfbd4b5aa1aff85e6a680f2671f8e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2016-04-11T11:15:01.000Z", "max_issues_repo_issues_event_max_datetime": "2016-04-29T16:22:04.000Z", "max_forks_repo_path": "tests/solver_test.cpp", "max_forks_repo_name": "minijackson/PR-3602", "max_forks_repo_head_hexsha": "197c47434fcfbd4b5aa1aff85e6a680f2671f8e4", "max_forks_repo_licenses": ["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.0867768595, "max_line_length": 94, "alphanum_fraction": 0.640021975, "num_tokens": 2020, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936438, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.49069868343968454}}
{"text": "#include <boost/foreach.hpp>\n\n#include \"rb_tracker/MultiRBTracker.h\"\n\n#include \"omip_common/OMIPUtils.h\"\n\n#include <cmath>\n\n#include <pcl/correspondence.h>\n#include <pcl/registration/correspondence_rejection_sample_consensus.h>\n\n#include <pcl_conversions/pcl_conversions.h>\n\n#if ROS_VERSION_MINIMUM(1, 11, 1) // if current ros version is >= 1.11.1 (indigo)\n#else\n#include \"rb_tracker/pcl_conversions_indigo.h\"\n#endif\n\n#include <pcl/console/print.h>\n\nusing namespace omip;\n\ninline void estimateRigidTransformation(\n        const FeaturesDataBase::MapOfFeatureLocationPairs& last2locations,\n        Eigen::Matrix4d &transformation_matrix)\n{\n    // Convert to Eigen format\n    const int npts = static_cast<int>(last2locations.size());\n\n    Eigen::Matrix<double, 3, Eigen::Dynamic> cloud_src(3, npts);\n    Eigen::Matrix<double, 3, Eigen::Dynamic> cloud_tgt(3, npts);\n\n    FeaturesDataBase::MapOfFeatureLocationPairs::const_iterator locations_it =\n            last2locations.begin();\n    FeaturesDataBase::MapOfFeatureLocationPairs::const_iterator locations_it_end =\n            last2locations.end();\n    for (int i = 0; locations_it != locations_it_end; locations_it++, i++)\n    {\n        cloud_src(0, i) = locations_it->second.second.get<0>();\n        cloud_src(1, i) = locations_it->second.second.get<1>();\n        cloud_src(2, i) = locations_it->second.second.get<2>();\n\n        cloud_tgt(0, i) = locations_it->second.first.get<0>();\n        cloud_tgt(1, i) = locations_it->second.first.get<1>();\n        cloud_tgt(2, i) = locations_it->second.first.get<2>();\n    }\n\n    // Call Umeyama directly from Eigen (PCL patched version until Eigen is released)\n    transformation_matrix = Eigen::umeyama(cloud_src, cloud_tgt, false);\n}\n\nMultiRBTracker::MultiRBTracker(int max_num_rb,\n                               double loop_period_ns,\n                               int ransac_iterations,\n                               double estimation_error_threshold,\n                               double static_motion_threshold,\n                               double new_rbm_error_threshold,\n                               double max_error_to_reassign_feats,\n                               int supporting_features_threshold,\n                               int min_num_feats_for_new_rb,\n                               int min_num_frames_for_new_rb,\n                               int initial_cam_motion_constraint,\n                               static_environment_tracker_t static_environment_tracker_type) :\n    RecursiveEstimatorFilterInterface(loop_period_ns),\n    _max_num_rb(max_num_rb),\n    _ransac_iterations(ransac_iterations),\n    _estimation_error_threshold(estimation_error_threshold),\n    _static_motion_threshold(static_motion_threshold),\n    _new_rbm_error_threshold(new_rbm_error_threshold),\n    _max_error_to_reassign_feats(max_error_to_reassign_feats),\n    _supporting_features_threshold(supporting_features_threshold),\n    _min_num_feats_for_new_rb(min_num_feats_for_new_rb),\n    _min_num_frames_for_new_rb(min_num_frames_for_new_rb),\n    _min_num_points_in_segment(0),\n    _min_probabilistic_value(0.0),\n    _max_fitness_score(0.0),\n    _min_num_supporting_feats_to_correct(7),\n    _max_distance_ee(-1),\n    _max_distance_irb(-1)\n{\n\n    //_really_free_feats_file.open(\"really_free_feats_file.txt\");\n    this->_filter_name = \"RBMFilter\";\n\n    if (this->_features_db)\n        this->_features_db.reset();\n\n    this->_features_db = FeaturesDataBase::Ptr(new FeaturesDataBase());\n\n    this->_predicted_measurement = rbt_measurement_t(new FeatureCloudPCLwc());\n\n    // The static environment exists always as initial hypothesis\n    // We can track the static enviroment (visual odometry) using different computation methods: ICP or EKF\n    _static_environment_filter = StaticEnvironmentFilter::Ptr(new StaticEnvironmentFilter(this->_loop_period_ns,\n                                                                                      this->_features_db,\n                                                                                      this->_static_motion_threshold));\n    _static_environment_filter->setComputationType(static_environment_tracker_type);\n    _static_environment_filter->setFeaturesDatabase(this->_features_db);\n    _static_environment_filter->setMotionConstraint(initial_cam_motion_constraint);\n\n    this->_kalman_filters.push_back(_static_environment_filter);\n}\n\nvoid MultiRBTracker::Init()\n{\n    _static_environment_filter->setMeasurementDepthFactor(this->_meas_depth_factor);\n    _static_environment_filter->setMinCovarianceMeasurementX(this->_min_cov_meas_x);\n    _static_environment_filter->setMinCovarianceMeasurementY(this->_min_cov_meas_y);\n    _static_environment_filter->setMinCovarianceMeasurementZ(this->_min_cov_meas_z);\n    _static_environment_filter->setPriorCovariancePose(this->_prior_cov_pose);\n    _static_environment_filter->setPriorCovarianceVelocity(this->_prior_cov_vel);\n    _static_environment_filter->setCovarianceSystemAccelerationTx(this->_cov_sys_acc_tx);\n    _static_environment_filter->setCovarianceSystemAccelerationTy(this->_cov_sys_acc_ty);\n    _static_environment_filter->setCovarianceSystemAccelerationTz(this->_cov_sys_acc_tz);\n    _static_environment_filter->setCovarianceSystemAccelerationRx(this->_cov_sys_acc_rx);\n    _static_environment_filter->setCovarianceSystemAccelerationRy(this->_cov_sys_acc_ry);\n    _static_environment_filter->setCovarianceSystemAccelerationRz(this->_cov_sys_acc_rz);\n    _static_environment_filter->setNumberOfTrackedFeatures(this->_num_tracked_feats);\n    _static_environment_filter->setMinNumberOfSupportingFeaturesToCorrectPredictedState(this->_min_num_supporting_feats_to_correct);\n    _static_environment_filter->Init();\n}\n\nMultiRBTracker::~MultiRBTracker()\n{\n\n}\n\nvoid MultiRBTracker::setMeasurement(rbt_measurement_t acquired_measurement, const double& measurement_timestamp)\n{\n    this->_previous_measurement_timestamp_ns = this->_measurement_timestamp_ns;\n\n    {\n        boost::mutex::scoped_lock(this->_measurement_timestamp_ns_mutex);\n        this->_measurement_timestamp_ns = measurement_timestamp;\n    }\n\n    this->_features_db->clearListOfAliveFeatureIds();\n    this->_measurement = acquired_measurement;\n\n    int num_tracked_features = acquired_measurement->points.size();\n\n    int tracked_features_index = 0;\n    uint32_t feature_id;\n    for (; tracked_features_index < num_tracked_features; tracked_features_index++)\n    {\n        feature_id = acquired_measurement->points[tracked_features_index].label;\n        if(feature_id != 0)\n        {\n            Feature::Location feature_location = Feature::Location(acquired_measurement->points[tracked_features_index].x, acquired_measurement->points[tracked_features_index].y,\n                                                                   acquired_measurement->points[tracked_features_index].z);\n            this->addFeatureLocation(feature_id, feature_location);\n        }\n    }\n    this->_features_db->step();\n}\n\nvoid MultiRBTracker::predictState(double time_interval_ns)\n{\n    //First we update the filters using the internal state (system update)\n    for (std::vector<RBFilter::Ptr>::iterator filter_it = this->_kalman_filters.begin(); filter_it != this->_kalman_filters.end(); filter_it++)\n    {\n        (*filter_it)->predictState(time_interval_ns);\n        (*filter_it)->doNotUsePredictionFromHigherLevel();\n    }\n}\n\n// NOTE: The location of the Features predicted by the static RBFilter is the initial location of these Features\n// When these predictions are used for the visual tracking the searching area for the Features is static until these Features can\n// be assigned to an existing RB (or a group of them create a new one)\n// The consequence is that the Features could go out of the searching area before they are detected as moving\n// There are two solutions:\n//      1- Use the static_motion_threshold in the estimation of the searching area. The searching area should cover motions of static_motion_threshold\n//         at the depth of the Feature (COMPLEX)\n//      2- Only for the static RBFilter the predicted locations retrieved here are the latest locations of the Features. This is ugly (treats the static\n//         RBFilter as an special one) but easier\nvoid MultiRBTracker::predictMeasurement()\n{\n    std::vector<RBFilter::Ptr>::iterator filter_it = this->_kalman_filters.begin();\n    for (; filter_it != this->_kalman_filters.end(); filter_it++)\n    {\n        (*filter_it)->predictMeasurement();\n    }\n\n    this->_predicted_measurement->points.clear();\n\n    std::vector<Feature::Id> feature_ids;\n    FeatureCloudPCLwc one_filter_predicted_measurement;\n    filter_it = this->_kalman_filters.begin();\n    filter_it++;\n    for (; filter_it != this->_kalman_filters.end(); filter_it++)\n    {\n        one_filter_predicted_measurement = (*filter_it)->getPredictedMeasurement();\n        for (size_t feat_idx = 0; feat_idx < one_filter_predicted_measurement.points.size(); feat_idx++)\n        {\n            this->_predicted_measurement->points.push_back(one_filter_predicted_measurement.points.at(feat_idx));\n            feature_ids.push_back(one_filter_predicted_measurement.points.at(feat_idx).label);\n        }\n    }\n\n    // The free Features are not in any RBFilter. We collect their latest locations\n    std::vector<Feature::Id> free_features_ids = this->EstimateFreeFeatures(feature_ids);\n    FeaturePCLwc free_feat;\n    for (size_t feat_idx = 0; feat_idx < free_features_ids.size(); feat_idx++)\n    {\n        free_feat.x = this->_features_db->getFeatureLastX(free_features_ids.at(feat_idx));\n        free_feat.y = this->_features_db->getFeatureLastY(free_features_ids.at(feat_idx));\n        free_feat.z = this->_features_db->getFeatureLastZ(free_features_ids.at(feat_idx));\n        free_feat.label = free_features_ids.at(feat_idx);\n        free_feat.covariance[0] = 20;\n        this->_predicted_measurement->points.push_back(free_feat);\n    }\n}\n\nrbt_measurement_t MultiRBTracker::getPredictedMeasurement() const\n{\n    this->_predicted_measurement->header.stamp = pcl_conversions::toPCL(ros::Time(this->_measurement_timestamp_ns/1e9+this->_loop_period_ns/1e9));\n    return this->_predicted_measurement;\n}\n\nstd::vector<Feature::Id> MultiRBTracker::estimateBestPredictionsAndSupportingFeatures()\n{\n    std::vector<Feature::Id> all_filters_supporting_features;\n    for (std::vector<RBFilter::Ptr>::iterator filter_it = this->_kalman_filters.begin(); filter_it != this->_kalman_filters.end();)\n    {\n        (*filter_it)->estimateBestPredictionAndSupportingFeatures();\n        std::vector<Feature::Id> this_filter_supporting_features = (*filter_it)->getSupportingFeatures();\n\n        // If there are no features supporting to the EKF we delete it (no re-finding of RBs/EKFs possible)\n        // Don't delete the filter of the environment!!! (filter_it == this->_kalman_filters.begin())\n        if (this_filter_supporting_features.size()  < (size_t)this->_supporting_features_threshold\n                && *filter_it != this->_static_environment_filter )\n        {\n            Eigen::Twistd last_pose_ec;\n            TransformMatrix2Twist((*filter_it)->getPose(), last_pose_ec);\n            ROS_ERROR_NAMED( \"MultiRBTracker.estimateBestPredictionsAndSupportingFeatures\",\n                             \"RBFilter %2d: Supporting feats:%3d (<%3d), Pose (vx,vy,vz,rx,ry,rz): % 2.2f,% 2.2f,% 2.2f,% 2.2f,% 2.2f,% 2.2f. REMOVED\",\n                             (int)(*filter_it)->getId(),\n                             (int)this_filter_supporting_features.size() ,\n                             (int)(this->_supporting_features_threshold),\n                             last_pose_ec.vx(),\n                             last_pose_ec.vy(),\n                             last_pose_ec.vz(),\n                             last_pose_ec.rx(),\n                             last_pose_ec.ry(),\n                             last_pose_ec.rz());\n            filter_it = this->_kalman_filters.erase(filter_it);\n        }\n        else\n        {\n            all_filters_supporting_features.insert(all_filters_supporting_features.end(),\n                                                   this_filter_supporting_features.begin(),\n                                                   this_filter_supporting_features.end());\n            filter_it++;\n        }\n    }\n    return all_filters_supporting_features;\n}\n\nvoid MultiRBTracker::correctState()\n{\n    // 1: Estimate the supporting features of each filter\n    std::vector<Feature::Id> all_filters_supporting_features = this->estimateBestPredictionsAndSupportingFeatures();\n\n    // 2: Estimate the free features\n    std::vector<Feature::Id> free_feat_ids = this->EstimateFreeFeatures(all_filters_supporting_features);\n\n    // 3: Try to assign free features to existing RBs\n    std::vector<Feature::Id> really_free_feat_ids = this->ReassignFreeFeatures(free_feat_ids);\n\n    ROS_INFO_NAMED(\"MultiRBTracker::correctState\",\"Moving bodies: %3d, free features: %3d\", (int)this->_kalman_filters.size(), (int)really_free_feat_ids.size());\n\n    // 4: Correct the predicted state of each RBFilter using the last acquired Measurement\n    for (std::vector<RBFilter::Ptr>::iterator filter_it = this->_kalman_filters.begin(); filter_it != this->_kalman_filters.end(); filter_it++)\n    {\n        (*filter_it)->correctState();\n    }\n\n    // 5: Try to create new filters for the \"really free\" features\n    // NOTE: Keep this step after the correctState of the RBFilters, otherwise you will create a filter and correct it in the first iteration!\n    if(this->_kalman_filters.size() < this->_max_num_rb)\n    {\n        this->TryToCreateNewFilter(really_free_feat_ids);\n    }\n}\n\nvoid MultiRBTracker::ReflectState()\n{\n    this->_state.rb_poses_and_vels.clear();\n\n    std::vector<geometry_msgs::TwistWithCovariancePtr> tracked_poses_twist_with_cov = this->getPosesECWithCovariance();\n    std::vector<geometry_msgs::TwistWithCovariancePtr> tracked_vels_twist_with_cov = this->getVelocitiesWithCovariance();\n    std::vector<Eigen::Vector3d> centroids = this->getCentroids();\n\n    RB_id_t RB_id;\n\n    for (size_t poses_idx = 0; poses_idx < tracked_poses_twist_with_cov.size(); poses_idx++)\n    {\n        RB_id = this->getRBId(poses_idx);\n\n        geometry_msgs::Point centroid;\n        centroid.x = centroids.at(poses_idx).x();\n        centroid.y = centroids.at(poses_idx).y();\n        centroid.z = centroids.at(poses_idx).z();\n\n        omip_msgs::RigidBodyPoseAndVelMsg rbpose_and_vel;\n        rbpose_and_vel.rb_id = RB_id;\n        rbpose_and_vel.pose_wc = *(tracked_poses_twist_with_cov.at(poses_idx));\n        rbpose_and_vel.velocity_wc = *(tracked_vels_twist_with_cov.at(poses_idx));\n        rbpose_and_vel.centroid = centroid;\n        this->_state.rb_poses_and_vels.push_back(rbpose_and_vel);\n    }\n}\n\nrbt_state_t MultiRBTracker::getState() const\n{\n    return this->_state;\n}\n\nvoid MultiRBTracker::setDynamicReconfigureValues(rb_tracker::RBTrackerDynReconfConfig &config)\n{\n    _static_environment_filter->setMotionConstraint(config.cam_motion_constraint);\n    this->_min_num_feats_for_new_rb = config.min_feats_new_rb;\n    this->_supporting_features_threshold = config.min_feats_survive_rb;\n}\n\nvoid MultiRBTracker::processMeasurementFromShapeTracker(const omip_msgs::ShapeTrackerStates &meas_from_st)\n{\n    for(int idx = 0; idx < meas_from_st.shape_tracker_states.size(); idx++)\n    {\n        BOOST_FOREACH(RBFilter::Ptr filter, this->_kalman_filters)\n        {\n            if (filter->getId() == meas_from_st.shape_tracker_states.at(idx).rb_id )\n            {\n                //Check if the flag indicates that this refinement is reliable\n                if((meas_from_st.shape_tracker_states.at(idx).number_of_points_of_model > _min_num_points_in_segment) &&\n                        (meas_from_st.shape_tracker_states.at(idx).number_of_points_of_current_pc > _min_num_points_in_segment) &&\n                        (meas_from_st.shape_tracker_states.at(idx).probabilistic_value > _min_probabilistic_value) &&\n                        (meas_from_st.shape_tracker_states.at(idx).fitness_score < _max_fitness_score))\n                {\n                    ROS_ERROR_STREAM(\"Integrating shape-based tracked pose RB \" << meas_from_st.shape_tracker_states.at(idx).rb_id);\n                    filter->integrateShapeBasedPose(meas_from_st.shape_tracker_states.at(idx).pose_wc, this->_measurement_timestamp_ns - meas_from_st.header.stamp.toNSec() );\n                }else{\n                    ROS_ERROR_STREAM(\"Ignoring shape-based tracked pose RB \" << meas_from_st.shape_tracker_states.at(idx).rb_id);\n                }\n            }\n        }\n    }\n}\n\nvoid MultiRBTracker::CreateNewFilter(const std::vector<Eigen::Matrix4d>& initial_trajectory,\n                                     const Eigen::Twistd& initial_velocity,\n                                     const std::vector<Feature::Id>& initial_supporting_feats)\n{\n    RBFilter::Ptr new_kf = RBFilter::Ptr(new RBFilter(this->_loop_period_ns,\n                                                      initial_trajectory,\n                                                      initial_velocity,\n                                                      this->_features_db,\n                                                      this->_estimation_error_threshold));\n\n    new_kf->setMeasurementDepthFactor(this->_meas_depth_factor);\n    new_kf->setMinCovarianceMeasurementX(this->_min_cov_meas_x);\n    new_kf->setMinCovarianceMeasurementY(this->_min_cov_meas_y);\n    new_kf->setMinCovarianceMeasurementZ(this->_min_cov_meas_z);\n    new_kf->setPriorCovariancePose(this->_prior_cov_pose);\n    new_kf->setPriorCovarianceVelocity(this->_prior_cov_vel);\n    new_kf->setCovarianceSystemAccelerationTx(this->_cov_sys_acc_tx);\n    new_kf->setCovarianceSystemAccelerationTy(this->_cov_sys_acc_ty);\n    new_kf->setCovarianceSystemAccelerationTz(this->_cov_sys_acc_tz);\n    new_kf->setCovarianceSystemAccelerationRx(this->_cov_sys_acc_rx);\n    new_kf->setCovarianceSystemAccelerationRy(this->_cov_sys_acc_ry);\n    new_kf->setCovarianceSystemAccelerationRz(this->_cov_sys_acc_rz);\n    new_kf->setNumberOfTrackedFeatures(this->_num_tracked_feats);\n    new_kf->setMinNumberOfSupportingFeaturesToCorrectPredictedState(this->_min_num_supporting_feats_to_correct);\n\n    new_kf->Init();\n\n    this->_kalman_filters.push_back(new_kf);\n    BOOST_FOREACH(Feature::Id supporting_feat_id, initial_supporting_feats)\n    {\n        new_kf->addSupportingFeature(supporting_feat_id);\n    }\n}\n\nstd::vector<Feature::Id> MultiRBTracker::EstimateFreeFeatures(const std::vector<Feature::Id>& supporting_features)\n{\n    // We check the set of free features = alive features - supporting features\n    std::vector<Feature::Id> alive_feat_ids = this->_features_db->getListOfAliveFeatureIds();\n    std::vector<Feature::Id> free_feat_ids;\n    BOOST_FOREACH(Feature::Id alive_feat_id, alive_feat_ids)\n    {\n        // If the feature ID is not in the list of supporting features -> Free feature\n        if (std::find(supporting_features.begin(), supporting_features.end(),alive_feat_id) == supporting_features.end())\n        {\n            free_feat_ids.push_back(alive_feat_id);\n        }\n    }\n    _free_feat_ids = free_feat_ids;\n    return free_feat_ids;\n}\n\n// NOTE: Here the features have an \"extra\" location compared to the moment when we predict the measurement for each filter (at the end of the iteration) (predictMeasurement)\n// Therefore, the \"age of the feature\" is +1 the age it would have when predicting the measurement\n// EXCEPT if the measurement prediction has to be called again in the loop!!!!!\nstd::vector<Feature::Id> MultiRBTracker::ReassignFreeFeatures(const std::vector<Feature::Id>& free_feat_ids)\n{\n    std::vector<Feature::Id> really_free_feat_ids;\n\n    Feature::Ptr free_feat;\n    Feature::Location free_feature_last_location;\n    Feature::Location free_feature_pre_last_location;\n    Feature::Location free_feature_predicted_location;\n    double feat_error = 0.0;\n    double prediction_error = 0.0;\n    int best_ekf_idx = -1;\n    Eigen::Matrix4d predicted_pose;\n\n    // Check for each free feature if we can add it to one of the existing vision-based rigid bodies\n    BOOST_FOREACH(Feature::Id free_feat_id, free_feat_ids)\n    {\n        free_feature_last_location = this->_features_db->getFeatureLastLocation(free_feat_id);\n        free_feature_pre_last_location = this->_features_db->getFeatureNextToLastLocation(free_feat_id);\n        free_feat = this->_features_db->getFeature(free_feat_id);\n        feat_error = (double)this->_max_error_to_reassign_feats;\n        best_ekf_idx = -1;\n        Feature::Location best_predicted_location;\n\n        // Get the prediction from each of the existing vision-based rigid bodies\n        // TODO: Use the Mahalanobis distance between the uncertain feature location and its predicted location\n        for (size_t filter_idx = 0; filter_idx < this->_kalman_filters.size();filter_idx++)\n        {\n            // Get the most likely prediction about the next feature state (the likelihood is estimated in estimateSupportingFeatures and copied to the others\n            // so it is equivalent to get the belief pose from any hypothesis)\n            //prediction_error = this->_kalman_filters.at(filter_idx)->PredictFeatureLocationNew(free_feat, false, true);\n\n            predicted_pose = this->_kalman_filters.at(filter_idx)->getPose();\n            this->_kalman_filters.at(filter_idx)->PredictFeatureLocation(free_feat, predicted_pose, false, free_feature_predicted_location,true);\n            prediction_error = L2Distance(free_feature_last_location, free_feature_predicted_location);\n\n            if (prediction_error < feat_error)\n            {\n                feat_error = prediction_error;\n                best_ekf_idx = filter_idx;\n                best_predicted_location = free_feature_predicted_location;\n            }\n        }\n\n        if (best_ekf_idx != -1)\n        {\n            this->_kalman_filters.at(best_ekf_idx)->addSupportingFeature(free_feat_id);\n            this->_kalman_filters.at(best_ekf_idx)->addPredictedFeatureLocation(best_predicted_location,free_feature_pre_last_location, free_feat_id);\n        }\n        else\n        {\n            really_free_feat_ids.push_back(free_feat_id);\n        }\n    }\n    _really_free_feat_ids = really_free_feat_ids;\n    return really_free_feat_ids;\n}\n\nvoid MultiRBTracker::TryToCreateNewFilter(const std::vector<Feature::Id>& really_free_feat_ids)\n{\n    // First check that the number of free features is over the minimum number to estimate motion\n    if(really_free_feat_ids.size() > this->_min_num_feats_for_new_rb)\n    {\n        pcl::PointCloud<pcl::PointXYZ>::Ptr source = pcl::PointCloud<pcl::PointXYZ>::Ptr(new pcl::PointCloud<pcl::PointXYZ>());\n        pcl::PointCloud<pcl::PointXYZ>::Ptr target = pcl::PointCloud<pcl::PointXYZ>::Ptr(new pcl::PointCloud<pcl::PointXYZ>());\n        pcl::Correspondences initial_correspondeces, filtered_correspondences;\n        int index = 0;\n        std::map<int, int> index_to_feat_id;\n        PointPCL point_pcl;\n\n        //Iterate over the free features\n        BOOST_FOREACH(Feature::Id free_feat_id, really_free_feat_ids)\n        {\n            // If the free feature is old enough, we add it to the source-target point clouds and add a correspondence\n            if ((int)this->_features_db->getFeatureAge(free_feat_id) > this->_min_num_frames_for_new_rb)\n            {\n                Feature::Location first = this->_features_db->getFeatureNToLastLocation(free_feat_id, this->_min_num_frames_for_new_rb);\n                Feature::Location second = this->_features_db->getFeatureLastLocation(free_feat_id);\n                Location2PointPCL(first, point_pcl);\n                source->push_back(point_pcl);\n                Location2PointPCL(second, point_pcl);\n                target->push_back(point_pcl);\n                initial_correspondeces.push_back(pcl::Correspondence(index, index, 0.0));\n                index_to_feat_id[index] = free_feat_id;\n                index++;\n            }\n        }\n\n        // If enough of the free features are old enough, we try to estimate the motion\n        if(index > this->_min_num_feats_for_new_rb)\n        {\n            //pcl::console::setVerbosityLevel(pcl::console::L_DEBUG);\n            // PCL RANSAC\n            pcl::registration::CorrespondenceRejectorSampleConsensus<pcl::PointXYZ> rejector;\n            rejector.setInputSource(source);\n            rejector.setInputTarget(target);\n            rejector.setInlierThreshold(this->_new_rbm_error_threshold);\n            rejector.setMaximumIterations(this->_ransac_iterations);\n            rejector.getRemainingCorrespondences(initial_correspondeces, filtered_correspondences);\n\n            Eigen::Matrix4f best_transformation = rejector.getBestTransformation();\n\n            // If the number of free features that are inliers of the best transformation is over the minimum number to estimate motion\n            // AND if the best transformation is not just noise:\n            //      - Translation is larger than min_amount_translation meters\n            //      - Rotation around the axis is larger than min_amount_rotation degrees\n            Eigen::Transform<float, 3, Eigen::Affine> best_transformation2(best_transformation);\n            double amount_translation = best_transformation2.translation().norm();\n            Eigen::AngleAxisf best_axis_angle;\n            double amount_rotation = best_axis_angle.fromRotationMatrix(best_transformation2.rotation()).angle();\n\n            if ((int)filtered_correspondences.size() > this->_min_num_feats_for_new_rb && (\n                        amount_translation > _min_amount_translation_for_new_rb ||\n                        amount_rotation > _min_amount_rotation_for_new_rb*(M_PI/180.0) ) )\n            {\n                std::vector<Eigen::Matrix4d> trajectory;\n                Feature::Location centroid_in_cf;\n\n                //Collect the ids of the matched features\n                //and compute the centroid of the supporting features N frames ago\n                //The centroid will be used to \"place\" the frame of the rigid body -> Initial transformation of the rigid body\n                //is a pure translation to the location of the centroid\n                std::vector<Feature::Id> ransac_best_trial_inliers;\n                BOOST_FOREACH(pcl::Correspondence filter_correspondence, filtered_correspondences)\n                {\n                    int feature_id = index_to_feat_id.at(filter_correspondence.index_match);\n                    ransac_best_trial_inliers.push_back(feature_id);\n                    Feature::Location feat_loc = this->_features_db->getFeatureNToLastLocation(feature_id, this->_min_num_frames_for_new_rb-1);\n                    boost::tuples::get<0>(centroid_in_cf) = boost::tuples::get<0>(centroid_in_cf) + boost::tuples::get<0>(feat_loc);\n                    boost::tuples::get<1>(centroid_in_cf) = boost::tuples::get<1>(centroid_in_cf) + boost::tuples::get<1>(feat_loc);\n                    boost::tuples::get<2>(centroid_in_cf) = boost::tuples::get<2>(centroid_in_cf) + boost::tuples::get<2>(feat_loc);\n                }\n\n                boost::tuples::get<0>(centroid_in_cf) = boost::tuples::get<0>(centroid_in_cf)/(double)filtered_correspondences.size();\n                boost::tuples::get<1>(centroid_in_cf) = boost::tuples::get<1>(centroid_in_cf)/(double)filtered_correspondences.size();\n                boost::tuples::get<2>(centroid_in_cf) = boost::tuples::get<2>(centroid_in_cf)/(double)filtered_correspondences.size();\n\n                Eigen::Matrix4d pre_translation = Eigen::Matrix4d::Identity();\n                pre_translation(0,3) = boost::tuples::get<0>(centroid_in_cf);\n                pre_translation(1,3) = boost::tuples::get<1>(centroid_in_cf);\n                pre_translation(2,3) = boost::tuples::get<2>(centroid_in_cf);\n\n                trajectory.push_back(pre_translation);\n\n                // Estimate the trajectory in the last _min_num_frames_for_new_rb frames\n                for(int frame = this->_min_num_frames_for_new_rb-2; frame >= 0; frame--)\n                {\n                    FeaturesDataBase::MapOfFeatureLocationPairs one_frame_best_subset;\n                    BOOST_FOREACH(Feature::Id matched_feat_id, ransac_best_trial_inliers)\n                    {\n                        one_frame_best_subset[matched_feat_id] = Feature::LocationPair(this->_features_db->getFeatureNToLastLocation(matched_feat_id, frame),\n                                                                                       this->_features_db->getFeatureNToLastLocation(matched_feat_id, this->_min_num_frames_for_new_rb-1)\n                                                                                       - centroid_in_cf);\n                    }\n                    Eigen::Matrix4d one_frame_best_transformation_matrix;\n                    estimateRigidTransformation(one_frame_best_subset,one_frame_best_transformation_matrix);\n                    trajectory.push_back(one_frame_best_transformation_matrix);\n                }\n\n                Eigen::Matrix4d last_delta = trajectory.at(trajectory.size()-1)*(trajectory.at(trajectory.size()-2).inverse());\n                Eigen::Twistd initial_velocity;\n                TransformMatrix2Twist(last_delta, initial_velocity);\n\n                double measured_loop_period_ns= this->_measurement_timestamp_ns - this->_previous_measurement_timestamp_ns;\n                initial_velocity /=(measured_loop_period_ns/1e9);\n\n                this->CreateNewFilter(trajectory, initial_velocity, ransac_best_trial_inliers);\n            }else\n            {\n                ROS_INFO_STREAM_NAMED(\"RBMTracker._createNewFilters\", \"Not enough Consensus to create a new Filter with the free Features (\"<<\n                                      filtered_correspondences.size() <<\" inliers are too few, or the the amount of translation \" <<\n                                      amount_translation << \" < \" << _min_amount_translation_for_new_rb << \" and the amount of rotation \" <<\n                                      amount_rotation << \" < \" << _min_amount_rotation_for_new_rb*(M_PI/180.0));\n                return;\n            }\n        }\n    }\n}\n\nstd::vector<Eigen::Matrix4d> MultiRBTracker::getPoses() const\n{\n    std::vector<Eigen::Matrix4d> return_filter_results;\n\n    BOOST_FOREACH(RBFilter::Ptr filter, this->_kalman_filters)\n    {\n        return_filter_results.push_back(filter->getPose());\n    }\n    return return_filter_results;\n}\n\nstd::vector<geometry_msgs::PoseWithCovariancePtr> MultiRBTracker::getPosesWithCovariance() const\n{\n    std::vector<geometry_msgs::PoseWithCovariancePtr> return_filter_results;\n    BOOST_FOREACH(RBFilter::Ptr filter, this->_kalman_filters)\n    {\n        return_filter_results.push_back(filter->getPoseWithCovariance());\n    }\n    return return_filter_results;\n}\n\nstd::vector<geometry_msgs::TwistWithCovariancePtr> MultiRBTracker::getPosesECWithCovariance() const\n{\n    std::vector<geometry_msgs::TwistWithCovariancePtr> return_filter_results;\n    BOOST_FOREACH(RBFilter::Ptr filter, this->_kalman_filters)\n    {\n        return_filter_results.push_back(filter->getPoseECWithCovariance());\n    }\n    return return_filter_results;\n}\n\nstd::vector<geometry_msgs::TwistWithCovariancePtr> MultiRBTracker::getVelocitiesWithCovariance() const\n{\n    std::vector<geometry_msgs::TwistWithCovariancePtr> return_filter_results;\n    BOOST_FOREACH(RBFilter::Ptr filter, this->_kalman_filters)\n    {\n        return_filter_results.push_back(filter->getVelocityWithCovariance());\n    }\n    return return_filter_results;\n}\n\nvoid MultiRBTracker::addFeatureLocation(Feature::Id f_id, Feature::Location f_loc)\n{\n    if (this->_features_db->addFeatureLocation(f_id, f_loc))\n    {\n        // addFeature::LocationOfFeature returns true if the feature is new\n        _static_environment_filter->addSupportingFeature(f_id);\n    }\n}\n\nRB_id_t MultiRBTracker::getRBId(int n) const\n{\n    return this->_kalman_filters.at(n)->getId();\n}\n\nint MultiRBTracker::getNumberSupportingFeatures(int n) const\n{\n    return this->_kalman_filters.at(n)->getNumberSupportingFeatures();\n}\n\nFeatureCloudPCL MultiRBTracker::getLabelledSupportingFeatures()\n{\n    FeatureCloudPCL colored_pc;\n    std::vector<RBFilter::Ptr>::iterator filter_it =this->_kalman_filters.begin();\n    // TODO: The next line is to not show the supporting features of the static rigid body.\n    // I commented it out for the ICRA paper: we want to plot all points\n\n    filter_it++;\n    for (; filter_it != this->_kalman_filters.end(); filter_it++)\n    {\n        std::vector<Feature::Id> this_filter_supporting_features = (*filter_it)->getSupportingFeatures();\n        for (size_t feat_idx = 0; feat_idx < this_filter_supporting_features.size();feat_idx++)\n        {\n            if (this->_features_db->isFeatureStored(this_filter_supporting_features.at(feat_idx)))\n            {\n                FeaturePCL temp_point;\n                RB_id_t label = (*filter_it)->getId();\n                temp_point.x = this->_features_db->getFeatureLastX(this_filter_supporting_features.at(feat_idx));\n                temp_point.y = this->_features_db->getFeatureLastY(this_filter_supporting_features.at(feat_idx));\n                temp_point.z = this->_features_db->getFeatureLastZ(this_filter_supporting_features.at(feat_idx));\n\n                temp_point.label = label;\n                colored_pc.points.push_back(temp_point);\n            }\n        }\n    }\n    return colored_pc;\n}\n\nFeatureCloudPCL MultiRBTracker::getFreeFeatures()\n{\n    FeatureCloudPCL colored_pc;\n    for (size_t feat_idx = 0; feat_idx < _really_free_feat_ids.size();feat_idx++)\n    {\n        if (this->_features_db->isFeatureStored(_really_free_feat_ids.at(feat_idx)))\n        {\n            FeaturePCL temp_point;\n            temp_point.x = this->_features_db->getFeatureLastX(_really_free_feat_ids.at(feat_idx));\n            temp_point.y = this->_features_db->getFeatureLastY(_really_free_feat_ids.at(feat_idx));\n            temp_point.z = this->_features_db->getFeatureLastZ(_really_free_feat_ids.at(feat_idx));\n\n            temp_point.label = _really_free_feat_ids.at(feat_idx);\n            colored_pc.points.push_back(temp_point);\n        }\n    }\n    return colored_pc;\n}\n\nFeatureCloudPCL MultiRBTracker::getPredictedFeatures()\n{\n    FeatureCloudPCL colored_pc;\n    std::vector<RBFilter::Ptr>::iterator filter_it =this->_kalman_filters.begin();\n    filter_it++;\n    for (; filter_it != this->_kalman_filters.end(); filter_it++)\n    {\n        FeatureCloudPCLwc::Ptr predicted_locations_pc = (*filter_it)->getFeaturesPredicted();\n        for (size_t feat_idx = 0; feat_idx < predicted_locations_pc->points.size();feat_idx++)\n        {\n            FeaturePCL temp_point;\n            temp_point.x = predicted_locations_pc->points[feat_idx].x;\n            temp_point.y = predicted_locations_pc->points[feat_idx].y;\n            temp_point.z = predicted_locations_pc->points[feat_idx].z;\n            temp_point.label = predicted_locations_pc->points[feat_idx].label;\n            colored_pc.points.push_back(temp_point);\n        }\n        (*filter_it)->resetFeaturesPredicted();\n    }\n    return colored_pc;\n}\n\nFeatureCloudPCL MultiRBTracker::getAtBirthFeatures()\n{\n    FeatureCloudPCL colored_pc;\n    std::vector<RBFilter::Ptr>::iterator filter_it =this->_kalman_filters.begin();\n    filter_it++;\n    for (; filter_it != this->_kalman_filters.end(); filter_it++)\n    {\n        FeatureCloudPCLwc::Ptr at_birth_locations_pc = (*filter_it)->getFeaturesAtBirth();\n        for (size_t feat_idx = 0; feat_idx < at_birth_locations_pc->points.size();feat_idx++)\n        {\n            FeaturePCL temp_point;\n            temp_point.x = at_birth_locations_pc->points[feat_idx].x;\n            temp_point.y = at_birth_locations_pc->points[feat_idx].y;\n            temp_point.z = at_birth_locations_pc->points[feat_idx].z;\n            temp_point.label = at_birth_locations_pc->points[feat_idx].label;\n            colored_pc.points.push_back(temp_point);\n        }\n        (*filter_it)->resetFeaturesAtBirth();\n    }\n    return colored_pc;\n}\n\nstd::vector<Eigen::Vector3d> MultiRBTracker::getCentroids() const\n{\n    std::vector<Eigen::Vector3d> centroids;\n    centroids.push_back(Eigen::Vector3d(0., 0., 0.));\n    std::vector<RBFilter::Ptr>::const_iterator filter_it = this->_kalman_filters.begin();\n    filter_it++;    //Ignore the static environment\n\n    for (; filter_it != this->_kalman_filters.end(); filter_it++)\n    {\n        //NEW: the first time we send as centroid the centroid we used for the trajectory estimation\n        //In this way we can inform the next level of the initial pose of the rigid body\n        if((*filter_it)->getTrajectory().size() < this->_min_num_frames_for_new_rb)\n        {\n            Feature::Location initial_location = (*filter_it)->getIntialLocationOfCentroid();\n            centroids.push_back(Eigen::Vector3d(boost::tuples::get<0>(initial_location),\n                                                boost::tuples::get<1>(initial_location),\n                                                boost::tuples::get<2>(initial_location)));\n        }else{\n            Eigen::Vector3d temp_centroid = Eigen::Vector3d(0., 0., 0.);\n            int supporting_feats_ctr = 0;\n            std::vector<Feature::Id> this_filter_supporting_features = (*filter_it)->getSupportingFeatures();\n            for (size_t feat_idx = 0; feat_idx < this_filter_supporting_features.size();feat_idx++)\n            {\n                if (this->_features_db->isFeatureStored(this_filter_supporting_features.at(feat_idx)))\n                {\n                    temp_centroid.x() += this->_features_db->getFeatureLastX(this_filter_supporting_features.at(feat_idx));\n                    temp_centroid.y() += this->_features_db->getFeatureLastY(this_filter_supporting_features.at(feat_idx));\n                    temp_centroid.z() += this->_features_db->getFeatureLastZ(this_filter_supporting_features.at(feat_idx));\n                    supporting_feats_ctr++;\n                }\n            }\n            centroids.push_back(temp_centroid / (double)supporting_feats_ctr);\n        }\n    }\n    return centroids;\n}\n\nvoid MultiRBTracker::addPredictedState(const rbt_state_t& predicted_state, const double &predicted_state_timestamp_ns)\n{    \n    BOOST_FOREACH(omip_msgs::RigidBodyPoseAndVelMsg predicted_pose_and_vel, predicted_state.rb_poses_and_vels)\n    {\n        BOOST_FOREACH(RBFilter::Ptr filter, this->_kalman_filters)\n        {\n            if (filter->getId() == predicted_pose_and_vel.rb_id)\n            {\n                //ROS_WARN_STREAM_NAMED(\"MultiRBTracker.addPredictedState\", \"Prediction for body \" << predicted_pose_and_vel.rb_id);\n                filter->setPredictedState(predicted_pose_and_vel);\n            }\n        }\n    }\n}\n\nFeaturesDataBase::Ptr MultiRBTracker::getFeaturesDatabase()\n{\n    return this->_features_db;\n}\n\n", "meta": {"hexsha": "29da93cb35b8b05dceab75df6f429b0216177ce0", "size": 38908, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rb_tracker/src/MultiRBTracker.cpp", "max_stars_repo_name": "tu-rbo/omip", "max_stars_repo_head_hexsha": "825442774d1a9712937b535e5ced4e4c1aa32fcc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2016-11-10T16:11:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-21T20:11:39.000Z", "max_issues_repo_path": "rb_tracker/src/MultiRBTracker.cpp", "max_issues_repo_name": "tu-rbo/omip", "max_issues_repo_head_hexsha": "825442774d1a9712937b535e5ced4e4c1aa32fcc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-11-28T13:22:02.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-22T22:01:58.000Z", "max_forks_repo_path": "rb_tracker/src/MultiRBTracker.cpp", "max_forks_repo_name": "tu-rbo/omip", "max_forks_repo_head_hexsha": "825442774d1a9712937b535e5ced4e4c1aa32fcc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2016-11-25T18:24:12.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-24T03:20:33.000Z", "avg_line_length": 49.188369153, "max_line_length": 185, "alphanum_fraction": 0.68276447, "num_tokens": 8560, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936438, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.49069868343968454}}
{"text": "#include <algorithm>\n#include <iostream>\n#include <vector>\nusing namespace std;\n\n#include <boost/range/algorithm_ext/push_back.hpp>\n#include <boost/range/irange.hpp>\n\n#include <catch2/catch.hpp>\n#include <cpp_algs.hpp>\n\nTEST_CASE(\"Searching Algorithms test\") {\n\n    std::vector<int> v_int;\n    boost::push_back(v_int, boost::irange<int>(1, 1001));\n    REQUIRE(v_int.size() == 1000);\n\n    std::vector<char> v_char;\n    for (int i = 33; i < 128; i++) {\n        char c = i;\n        if (c != 'z')\n            v_char.push_back(c);\n    }\n    REQUIRE(v_char.size() == 94);\n\n    std::vector<double> v_double;\n    boost::push_back(v_double, boost::irange<double>(1.0, 1001.0));\n    REQUIRE(v_double.size() == 1000);\n\n    SECTION(\"Linear Search\") {\n        REQUIRE(al::linearSearch<int>(v_int, 500) == 499);\n        REQUIRE(al::linearSearch<int>(v_int, 0) == -1);\n\n        REQUIRE(al::linearSearch<char>(v_char, 'a') == 64);\n        REQUIRE(al::linearSearch<char>(v_char, 'z') == -1);\n\n        REQUIRE(al::linearSearch<double>(v_double, 150.0) == 149);\n        REQUIRE(al::linearSearch<double>(v_double, 0.0) == -1);\n    }\n\n    SECTION(\"Binary Search\") {\n        REQUIRE(al::binarySearch<int>(v_int, 500) == 499);\n        REQUIRE(al::binarySearch<int>(v_int, 0) == -1);\n\n        REQUIRE(al::binarySearch<char>(v_char, 'a') == 64);\n        REQUIRE(al::binarySearch<char>(v_char, 'z') == -1);\n\n        REQUIRE(al::binarySearch<double>(v_double, 150.0) == 149);\n        REQUIRE(al::binarySearch<double>(v_double, 0.0) == -1);\n    }\n\n    SECTION(\"Ternary Search\") {\n        REQUIRE(al::ternarySearch<int>(v_int, 500) == 499);\n        REQUIRE(al::ternarySearch<int>(v_int, 0) == -1);\n\n        REQUIRE(al::ternarySearch<char>(v_char, 'a') == 64);\n        REQUIRE(al::ternarySearch<char>(v_char, 'z') == -1);\n\n        REQUIRE(al::ternarySearch<double>(v_double, 150.0) == 149);\n        REQUIRE(al::ternarySearch<double>(v_double, 0.0) == -1);\n    }\n}", "meta": {"hexsha": "faf72a1c18027d9bc6c40031a1581cfe14f14a51", "size": 1933, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_al_search.cpp", "max_stars_repo_name": "pskrunner14/cpp-practice", "max_stars_repo_head_hexsha": "c59928bb9b91204588a0bafdc9f42deaacc64d29", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-09-14T14:17:27.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-02T00:20:52.000Z", "max_issues_repo_path": "tests/test_al_search.cpp", "max_issues_repo_name": "pskrunner14/cpp-practice", "max_issues_repo_head_hexsha": "c59928bb9b91204588a0bafdc9f42deaacc64d29", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-10-28T19:45:20.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-28T19:50:02.000Z", "max_forks_repo_path": "tests/test_al_search.cpp", "max_forks_repo_name": "pskrunner14/cpp-practice", "max_forks_repo_head_hexsha": "c59928bb9b91204588a0bafdc9f42deaacc64d29", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-12-29T19:58:08.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-29T19:58:08.000Z", "avg_line_length": 31.1774193548, "max_line_length": 67, "alphanum_fraction": 0.5938954992, "num_tokens": 577, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.49069867810411716}}
{"text": "\n#include <geometry_msgs/TransformStamped.h>\n#include <ros/ros.h>\n#include <tf2/LinearMath/Quaternion.h>\n#include <tf2_ros/static_transform_broadcaster.h>\n#include <tf2_ros/transform_broadcaster.h>\n#include <tf_conversions/tf_eigen.h>\n\n#include <Eigen/Dense>\n\ngeometry_msgs::TransformStamped get_static_transform(std::string parent_frame, std::string child_frame,\n                                                     Eigen::Matrix<double, 4, 4, Eigen::RowMajor> &mat);\n\nint main(int argc, char **argv)\n{\n  // init node\n  ros::init(argc, argv, \"static_transforms\");\n  ros::NodeHandle nh;\n  ros::NodeHandle priv_nh_(\"~\");\n\n  // Setup Parameters\n  std::vector<double> trans_world_param, trans12_param, trans13_param, trans14_param;\n\n  if (!priv_nh_.getParam(\"world_sensor1_transform\", trans_world_param))\n    ROS_ERROR(\"Node: static_transforms:: Failed to get parameter sensor12_transform from server.\");\n\n  if (!priv_nh_.getParam(\"sensor1_sensor2_transform\", trans12_param))\n    ROS_ERROR(\"Node: static_transforms:: Failed to get parameter sensor12_transform from server.\");\n\n  if (!priv_nh_.getParam(\"sensor1_sensor3_transform\", trans13_param))\n    ROS_ERROR(\"Node: static_transforms:: Failed to get parameter sensor13_transform from server.\");\n\n  if (!priv_nh_.getParam(\"sensor1_sensor4_transform\", trans14_param))\n    ROS_ERROR(\"Node: static_transforms:: Failed to get parameter sensor14_transform from server.\");\n\n  // Populate transform matrices from parameters\n  Eigen::Matrix<double, 4, 4, Eigen::RowMajor> transworld(trans_world_param.data());\n  Eigen::Matrix<double, 4, 4, Eigen::RowMajor> trans12(trans12_param.data());\n  Eigen::Matrix<double, 4, 4, Eigen::RowMajor> trans13(trans13_param.data());\n  Eigen::Matrix<double, 4, 4, Eigen::RowMajor> trans14(trans14_param.data());\n\n  //std::cout << trans12 << std::endl << trans13 << std::endl << trans14 << std::endl;\n\n  // Define static tf publisher\n  static tf2_ros::StaticTransformBroadcaster static_transform_broadcaster;\n\n  geometry_msgs::TransformStamped world_transformStamped, sensor12_transformStamped, sensor13_transformStamped, sensor14_transformStamped;\n\n  // Get tf messages built for all the sensors\n  world_transformStamped = get_static_transform(\"sensor1_frame\", \"world_frame\", transworld);\n  sensor12_transformStamped = get_static_transform(\"sensor1_frame\", \"sensor2_frame\", trans12);\n  sensor13_transformStamped = get_static_transform(\"sensor1_frame\", \"sensor3_frame\", trans13);\n  sensor14_transformStamped = get_static_transform(\"sensor1_frame\", \"sensor4_frame\", trans14);\n\n  // Publish all tf messeges to tf_static\n  const std::vector<geometry_msgs::TransformStamped> alltransforms{world_transformStamped,\n                                                                   sensor12_transformStamped,\n                                                                   sensor13_transformStamped,\n                                                                   sensor14_transformStamped};\n  static_transform_broadcaster.sendTransform(alltransforms);\n\n  ROS_INFO_ONCE(\"Node: static_transforms:: Successfully published all static transforms.\");\n\n  ros::spin();\n\n  return 0;\n}\n\n// TF messege builder\ngeometry_msgs::TransformStamped get_static_transform(std::string parent_frame, std::string child_frame,\n                                                     Eigen::Matrix<double, 4, 4, Eigen::RowMajor> &mat)\n{\n  geometry_msgs::TransformStamped stat_trans;\n\n  stat_trans.header.stamp = ros::Time::now();\n  stat_trans.header.frame_id = parent_frame;\n  stat_trans.child_frame_id = child_frame;\n\n  stat_trans.transform.translation.x = mat(0, 3);\n  stat_trans.transform.translation.y = mat(1, 3);\n  stat_trans.transform.translation.z = mat(2, 3);\n\n  Eigen::Matrix3d rot;\n  rot = mat.block<3, 3>(0, 0);\n\n  //std::cout << \"rot: \" << rot << std::endl;\n\n  const Eigen::Quaterniond q(rot);\n\n  stat_trans.transform.rotation.x = q.x();\n  stat_trans.transform.rotation.y = q.y();\n  stat_trans.transform.rotation.z = q.z();\n  stat_trans.transform.rotation.w = q.w();\n\n  ROS_INFO_ONCE(\"Transformation calculated : %s to %s\", child_frame.c_str(), parent_frame.c_str());\n\n  return stat_trans;\n}", "meta": {"hexsha": "f6bbe93140d81854df7b97ecc96ad2a71adab93b", "size": 4148, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/static_transforms.cpp", "max_stars_repo_name": "charithmu/perception_pipeline", "max_stars_repo_head_hexsha": "42f591bed9565e7a35e5770d41a85c662beb5f64", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-03-18T17:09:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-26T12:06:17.000Z", "max_issues_repo_path": "src/static_transforms.cpp", "max_issues_repo_name": "charithmu/perception_pipeline", "max_issues_repo_head_hexsha": "42f591bed9565e7a35e5770d41a85c662beb5f64", "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/static_transforms.cpp", "max_forks_repo_name": "charithmu/perception_pipeline", "max_forks_repo_head_hexsha": "42f591bed9565e7a35e5770d41a85c662beb5f64", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-08-31T08:26:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-21T08:09:04.000Z", "avg_line_length": 42.3265306122, "max_line_length": 138, "alphanum_fraction": 0.7078109932, "num_tokens": 946, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.6334102775181399, "lm_q1q2_score": 0.4906290763248441}}
{"text": "#include \"ShortestPath.h\"\n\n#include \"Exceptions.h\"\n\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <utility>\n\nusing std::pair;\n\nShortestPath::ShortestPath(Graph* g_) : g(g_) {}\n\nShortestPath::~ShortestPath() {\n    //delete g;\n}\n\nVertex ShortestPath::findVertex(int id_) {\n    VertexIterator it, end;\n    for(boost::tie(it, end) = boost::vertices(*g); it != end; ++it) {\n        if(getId(it) == id_)\n            return *it;\n    }\n\n    throw MapException(\"Wrong vertex id!\");\n}\n\nint ShortestPath::getId(VertexIterator it) {\n    return ((*g)[*(it)]).id;\n}\n\nint ShortestPath::getId(Vertex v) {\n    return ((*g)[v]).id;\n}\n\nvector<int> ShortestPath::getPath(int from_, int to_) {\n    Vertex from = findVertex(from_);\n    Vertex to = findVertex(to_);\n\n    vector<Vertex> predecessors(boost::num_vertices(*g));\n    vector<Weight> distances(boost::num_vertices(*g));\n\n    IndexMap indexMap;\n    PredecessorMap predecessorMap(&predecessors[0], indexMap);\n    DistanceMap distanceMap(&distances[0], indexMap);\n    boost::dijkstra_shortest_paths(*g, from, boost::distance_map(distanceMap).predecessor_map(predecessorMap));\n\n    vector<int> path;\n    Vertex v = to;\n\n    path.push_back(getId(to));\n    for(Vertex u = predecessorMap[v]; u != v; v = u, u = predecessorMap[v]) {\n        if(getId(u) != from_) {\n            path.push_back(getId(u));\n        }\n    }\n\n    std::reverse(path.begin(), path.end());\n    path.erase(path.begin()); // usuwamy pierwszy element bo ze spawnu pojedzie prosto do niego\n    return path;\n}\n", "meta": {"hexsha": "11104bfb18d0c0e4be5a4b9a414235c38c00e3d9", "size": 1522, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ShortestPath.cpp", "max_stars_repo_name": "mbychawski/traffic-simulator", "max_stars_repo_head_hexsha": "ef576cb9b2083e9e1cb8671356032d90dcfa42aa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ShortestPath.cpp", "max_issues_repo_name": "mbychawski/traffic-simulator", "max_issues_repo_head_hexsha": "ef576cb9b2083e9e1cb8671356032d90dcfa42aa", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ShortestPath.cpp", "max_forks_repo_name": "mbychawski/traffic-simulator", "max_forks_repo_head_hexsha": "ef576cb9b2083e9e1cb8671356032d90dcfa42aa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.3666666667, "max_line_length": 111, "alphanum_fraction": 0.6478318003, "num_tokens": 403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.63341027059799, "lm_q1q2_score": 0.49062907096461095}}
{"text": "/******************************************************************************\n * This file is for the Prime Numbers plugin.\n * It requires prime.cu that implements genPrimesOnDevice()\n ******************************************************************************/\n#include \"constants.h\"\n#include \"pluginHeader.h\"\n\n#include <boost/algorithm/string.hpp> // starts_with\n#include <cstdlib>                    // atoi, strtoull\n#include <cstring>                    /* strcpy */\n#include <fstream>                    // ifstream, ofstream\n#include <iomanip>                    // setw\n#include <iostream>\n\n// Prime Number functions\nint writePrimesFile(const char* filename, const char* primes, uint64_t size);\nuint64_t getPrimesCount(const char* primes, uint64_t size);\nvoid displayPrimes(const char* primes, uint64_t size);\n\n// genPrimesOnDevice is defined in \"primes.cu\"\nextern void genPrimesOnDevice(char* primes, uint64_t limit);\nvoid genPrimesOnHost(char* primes, uint64_t limit);\n\n/* globals */\nchar params[][256] = {\"prime_numbers.txt\", \"101\"};\nconst int NUM_ARGS = sizeof params / sizeof params[0];\nclock_t total_t = 0;\nconst char* PARAM_INFO = \"outputFile,limit\";\n\n/******************************************************************************\n * main()\n * - this function is not used by the plugin, but this can be built as\n *   a standalone executable\n ******************************************************************************/\nint main(int argc, char** argv)\n{\n    if (argc == 1)\n    {\n        std::cout << \"Usage: \" << argv[0] << \" upperLimit outputFile\\n\";\n        return 0;\n    }\n\n    if (argc > 1)\n    {\n        if (strcmp(argv[1], \"--help\") == 0)\n        {\n            displayPluginInfo();\n            return 0;\n        }\n        strcpy(params[1], argv[1]);\n    }\n\n    if (argc > 2)\n        strcpy(params[0], argv[2]);\n\n    return run();\n}\n\n////////////////////////////// PRIME FUNCTIONS ////////////////////////////////\n\n/******************************************************************************\n * TODO: implement me\n * genPrimesOnHost\n * - does the computation in serial, using the CPU\n ******************************************************************************/\nvoid genPrimesOnHost(char* primes, uint64_t limit) {}\n\n/******************************************************************************\n * writePrimesFile() - saves the generated prime numbers to the file\n ******************************************************************************/\nint writePrimesFile(const char* filename, const char* primes, uint64_t size)\n{\n    // open the file\n    std::ofstream fout(filename);\n    if (!fout || !primes || !size)\n    {\n        return ERROR;\n    }\n\n    /*\n    // write a comma-separated list of primes\n    uint64_t count = getPrimesCount(primes, size);\n    for (uint64_t i = 0; i < size; i++)\n    {\n       if (primes[i] == 0)\n       {\n          count--;\n          fout << i;\n          if (((i + 1) != size) && count)\n             fout << \", \";\n       }\n    }\n    fout << \"\\n\";\n    */\n\n    // write a newline separated list of primes\n    for (uint64_t i = 0; i < size; i++)\n    {\n        if (primes[i] == 0) // a value of '0' means the number is prime,\n        {                   // a value of '1' means the number is composite\n            fout << i << \"\\n\";\n        }\n    }\n\n    fout.close();\n    return OK;\n}\n\n/******************************************************************************\n * getPrimesCount() - counts the number of primes\n ******************************************************************************/\nuint64_t getPrimesCount(const char* primes, uint64_t size)\n{\n    uint64_t count = 0;\n    for (uint64_t i = 0; i < size; i++)\n        if (primes[i] == 0)\n            count++;\n    return count;\n}\n\n/******************************************************************************\n * displayPrimes() - displays a comma-separated list of prime numbers\n ******************************************************************************/\nvoid displayPrimes(const char* primes, uint64_t size)\n{\n    uint64_t count = getPrimesCount(primes, size);\n    for (uint64_t i = 0; i < size; i++)\n    {\n        if (primes[i] == 0)\n        {\n            count--;\n            std::cout << i;\n            if (((i + 1) != size) && count)\n                std::cout << \", \";\n        }\n    }\n    std::cout << std::endl;\n}\n\n///////////////////////////// PLUGIN FUNCTIONS ////////////////////////////////\n\n/******************************************************************************\n * run()\n * - computes the matrix multiplication: C = A * B\n * - reads the input files from the parameters: A = params[0], B = params[1]\n * - writes the output result C to the file set in params[2]\n * - if params[3] is set, then display the result to the screen\n ******************************************************************************/\nint run()\n{\n    clock_t start_t;\n    clock_t end_t;\n    total_t = 0; // reset the clock counter\n\n    uint64_t maxPrime = strtoull(params[1], nullptr, 10); // TODO: check for errors\n    char* primes;\n    maxPrime++; // allow the given parameter to be part of the search\n\n#ifdef DEBUG\n    std::cout << \"calling genPrimesOnDevice with maxPrime = \" << maxPrime << std::endl;\n#endif\n\n    primes = new (std::nothrow) char[maxPrime]();\n    if (primes == nullptr)\n    {\n        std::cout << \"Failed to allocate memory for the prime numbers.\\n\"\n                  << \"The limit parameter might be too large: \" << maxPrime << std::endl;\n        return ERROR;\n    }\n\n    start_t = clock();\n    genPrimesOnDevice(primes, maxPrime);\n    end_t = clock();\n    total_t = end_t - start_t;\n\n    // now save to the file\n    std::cout << \"Found \" << getPrimesCount(primes, maxPrime) << \" primes\"\n              << \" in \" << total_t / (double)CLOCKS_PER_SEC << \" seconds.\\n\"\n              << \"Writing results to: \\\"\" << params[0] << \"\\\"\\n\";\n    int result = writePrimesFile(params[0], primes, maxPrime);\n    if (result == ERROR)\n    {\n        std::cout << \"Failed to write Primes to: \\\"\" << params[0] << \"\\\"\\n\";\n        std::cout << \"Displaying result instead:\\n\";\n        displayPrimes(primes, maxPrime);\n    }\n\n#ifdef DEBUG\n    if (result != ERROR)\n        displayPrimes(primes, maxPrime);\n#endif\n\n    delete[] primes;\n\n    return OK;\n}\n\n/******************************************************************************\n * setParams()\n * - input: DELIM separated buffer\n * - splits the buffer and sets the \"params\" to the new passed in parameters\n * - this function only works if all the parameters are passed in to be set\n ******************************************************************************/\nint setParams(const char* buffer)\n{\n    int bufferSize = strlen(buffer) + 1; // +1 for '\\0'\n\n    // if the buffer is empty, then just return\n    if (bufferSize == 1 && NUM_ARGS == 0)\n        return OK;\n\n    // check if the passed in buffer will fit in our params\n    if (bufferSize > NUM_ARGS * BUFFER_SIZE)\n        return ERROR;\n\n    // count the number of arguments by counting the number of delimiters\n    int commas = 0;\n    const char* p;\n    for (p = buffer; *p; p++)\n        if (*p == DELIM)\n            commas++;\n\n    if (commas + 1 == NUM_ARGS)\n    {\n        // make a copy of the input buffer (so strtok doesnt change the original)\n        char buf[bufferSize];\n        strcpy(buf, buffer);\n        char* arg;\n        int i;\n\n        // copy the arguments to the params array\n        arg = strtok(buf, DELIM_STR);\n        for (i = 0; i < NUM_ARGS && arg; ++i)\n        {\n            strcpy(params[i], arg);\n            arg = strtok(nullptr, DELIM_STR);\n        }\n\n        return OK; // OK\n    }\n    return ERROR; // NOT_OK\n}\n\n/******************************************************************************\n * getParams()\n * - builds a DELIM delimited string of the current parameter values\n * - sets the \"buffer\" input to the newly built cstring\n ******************************************************************************/\nint getParams(char* buffer, int bufferSize)\n{\n    int i;\n\n    // count the size needed\n    int size = 0;\n    for (i = 0; i < NUM_ARGS; i++)\n        size += strlen(params[i]);\n    size += NUM_ARGS - 1;\n\n    // the size of the array must be big enough\n    if (bufferSize < size || bufferSize < 1)\n        return ERROR; // ERROR\n\n    // join the arguments into a DELIM separated list\n    buffer[0] = '\\0';\n    for (i = 0; i < NUM_ARGS; i++)\n    {\n        strcat(buffer, params[i]);\n        strcat(buffer, DELIM_STR); // NOTE: could use DC1 as delimeter\n    }\n    buffer[size] = '\\0'; // delete the last inserted comma\n    return OK;           // OK\n}\n\n/******************************************************************************\n * returns info / help on how to use this plugin\n ******************************************************************************/\nvoid* displayPluginInfo()\n{\n    std::cout << \"This program runs on the GPU and generates prime numbers.\\n\"\n              << \"There's two settings for this plugin. They are as follows:\\n\"\n              << \"\\t* limit - an integer for the upper number limit to check for primality\\n\"\n              << \"\\t* outputFile - the file where results will be store\\n\"\n              << \"By default, the generated primes won't be displayed to the screen.\\n\"\n              << \"However, if an error occurs while writing the results to the file, this program\\n\"\n              << \"will display the generated list of prime numbers.\\n\";\n    return nullptr;\n}\n\n/******************************************************************************\n * returns a comma-separated list of the parameter names\n ******************************************************************************/\nconst char* getParamInfo()\n{\n    return PARAM_INFO;\n}\n\n/******************************************************************************\n * returns the number of arguments this plugin contains\n ******************************************************************************/\nconst int getNumArgs()\n{\n    return NUM_ARGS;\n}\n\n/******************************************************************************\n * returns how many milliseconds it took to run the main program\n ******************************************************************************/\nclock_t getRunTime()\n{\n    return total_t;\n}\n", "meta": {"hexsha": "c72c31e0964c28a0e84e1258b167f99473d1a400", "size": 10281, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/plugins/prime.cpp", "max_stars_repo_name": "paulohefagundes/gpgpu_plugins", "max_stars_repo_head_hexsha": "0f09e757a2ff7406c05a307fbe5f1d32f2d7fbfd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/plugins/prime.cpp", "max_issues_repo_name": "paulohefagundes/gpgpu_plugins", "max_issues_repo_head_hexsha": "0f09e757a2ff7406c05a307fbe5f1d32f2d7fbfd", "max_issues_repo_licenses": ["MIT"], "max_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/prime.cpp", "max_forks_repo_name": "paulohefagundes/gpgpu_plugins", "max_forks_repo_head_hexsha": "0f09e757a2ff7406c05a307fbe5f1d32f2d7fbfd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-13T15:25:15.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-13T15:25:15.000Z", "avg_line_length": 32.9519230769, "max_line_length": 100, "alphanum_fraction": 0.4615309795, "num_tokens": 2144, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.63341027059799, "lm_q1q2_score": 0.49062907096461095}}
{"text": "#include <boost/numeric/odeint/stepper/bulirsch_stoer_dense_out.hpp>\n", "meta": {"hexsha": "39ecc86343555940021f8216242d25cd8fe613e8", "size": 69, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_numeric_odeint_stepper_bulirsch_stoer_dense_out.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_numeric_odeint_stepper_bulirsch_stoer_dense_out.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_numeric_odeint_stepper_bulirsch_stoer_dense_out.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 34.5, "max_line_length": 68, "alphanum_fraction": 0.8550724638, "num_tokens": 21, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.49062906560437775}}
{"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_FUNCTION_REM_2PI_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_REM_2PI_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-trigonometric\n    Function object implementing rem_2pi capabilities\n\n    compute the remainder modulo \\f$2\\pi\\f$.\n\n    the result is in \\f$[-\\pi, \\pi]\\f$. If the input\n    is near \\f$\\pi\\f$ the output can be \\f$\\pi\\f$ or \\f$-\\pi\\f$\n    depending\n    on register disponibility if extended arithmetic is used.\n\n    @par Semantic:\n\n    For every parameter of floating type T\n\n    @code\n    T r = rem_2pi(x);\n    @endcode\n\n    is similar to:\n\n    @code\n    T r = remainder(x, Twopi<T>();\n    @endcode\n\n    @see rem_pio2, rem_pio2_straight, rem_pio2_cephes,  rem_pio2_medium,\n\n  **/\n  const boost::dispatch::functor<tag::rem_2pi_> rem_2pi = {};\n} }\n#endif\n\n#include <boost/simd/function/scalar/rem_2pi.hpp>\n#include <boost/simd/function/simd/rem_2pi.hpp>\n\n#endif\n", "meta": {"hexsha": "1d741e187278f19b16285b8db0ad33a142aa3b00", "size": 1368, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/rem_2pi.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/function/rem_2pi.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/function/rem_2pi.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": 24.4285714286, "max_line_length": 100, "alphanum_fraction": 0.5957602339, "num_tokens": 349, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.49062906560437775}}
{"text": "#include \"PF.h\"\n#include <string>\n\n#include <Eigen/Core>\n#include <Eigen/Eigenvalues>\n#include <localization/lza.hpp>\n#include <pid/rpath.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <iostream>\n\n\n\n\n#include \"Time_management.h\"\n#include \"Formatings.h\"\n#include \"Geometrie.h\"\n\n\nusing namespace std;\n\n//With US\n//void PFThread(SafeShared<int> &Mode, SafeShared<euclid_position> &Odopos, SafeShared<laser_4m_record> &las1, SafeShared<laser_4m_record> &las2, SafeShared<std::vector<struct polar_coordinate>> &US, bool verbose, bool Logging,SafeShared<euclid_position> &Estimation){\n//Without US\nvoid PFThread(SafeShared<int> &Mode, SafeShared<euclid_position> &odom, SafeShared<laser_4m_record> &las1, SafeShared<laser_4m_record> &las2, bool verbose, bool Logging, SafeShared<euclid_position> &Estimation){\n/*********INIT VARIABLES************/\nint presentMode;\nstruct timespec StartTime, EndTime, Time, LauncheTime, TimeEstime;\nstruct timespec Las1Old, Las2Old, Las1Time, Las2Time;\nstruct timespec Todo, Toldodo;\nstruct timespec TimeLog;\nlaser_4m_record relevel1, relevel2;\neuclid_position odoposP3D,odoposP3D_Old, Val_estime;\n\n/*\nodoposP3D_Old.pos.x = 0;\nodoposP3D_Old.pos.y = 0;\nodoposP3D_Old.dir.theta = 0;\n*/\nstd::vector<struct polar_coordinate> Telemetries;\nstd::vector<struct polar_coordinate> OldLas1,OldLas2;\nint Running=0;\ndouble lsleep;\n\nstd::vector<double> Logs;\nstd::vector<double> LZA_LAS;\nstd::vector<struct timespec> LogTime;\nstd::vector<int> LogMode;\n\nint N = 600; //particle number (need to be an even number)\ndouble portee = 4; //portee of sensors\n\nvector<vector<double>> particles1; //particles in the first part of the map\nvector<vector<double>> particles2; //particles in the second part of the map\nvector<vector<double>> particles; //our particles (combination of both at first)\n\n\nvector<double> iNextGeneration(N,0.0);\nvector<double> poids(N,1/N); //vector of N element all equal to 1/N\ndouble sumPoids;\n// for estimating laser readings of particles\nint NR = 16;//number of rays\nvector<double> rhoParticles(3,0.0);\nvector<double> ximp(NR);\nvector<double> yimp(NR);\n\nvector<double> theta=linspace(-M_PI, M_PI, NR+1);\ntheta.pop_back(); //delete last element as it's the same as the first one\nfor(int i=0; i!=theta.size(); i++)\n{\n  // round angles to the closest angle of the 1022 rayes\n  theta[i] = (round(theta[i]*(1022/(2*M_PI)))*(2*M_PI/1022));\n  theta[i] = wrapAngle(theta[i]);\n}\nvector<int> indexes;\n\nbool firstIteration = true; //bool if it's first iteration of the simulation\nbool flagConvergance = false; // flag for convergance\nbool flagRedistribution = false; // flag for redistribution\n\neuclid_position tempParticle; //temporary particle to be used in control part\n\nvector<double> rhoRobot(NR,0); //get robot measurement to be used in likelihood\n\ndouble wsd [3] = {0,0,0}; //weighted standard deviation for x, y and theta\ndouble meanX = 0.0; // mean of all particles x position\ndouble meanY = 0.0; // mean of all particles y position\ndouble meanTheta = 0.0; // mean of all particles theta position\n\ndouble poseEstimate[3]={0.0,0.0,0.0}; //estimated position of the robot\n\ndouble ssl=0.0; //right and left wheel displacement\ndouble ssr=0.0;\n/**********Get MAP file***************/\n  std::string mapfolder = PID_PATH(\"PF_Files/obstacles.csv\");\n  std::cout<<\"Map folder : \"<<mapfolder<<std::endl;\n\tstring fname = mapfolder;//\"obstacles.csv\";\n\tObstacles Obstacles1;\n\tvector<vector<string>> obstacles;\n\tvector<string> row;\n\tstring line, data;\n\n\tfstream file (fname, ios::in);\n  std::cout << \"PF: Lecture Carte---\" << '\\n';\n\tif(file.is_open())\n\t{\n\t\twhile(getline(file, line))\n\t\t{\n\t\t\trow.clear();\n\t\t\tstringstream str(line);\n\t\t\twhile(getline(str, data, ','))\n\t\t\trow.push_back(data);\n\t\t\tobstacles.push_back(row);\n\t}\n\n\t}\n\telse\n\tcout<<\"Could not open the file\\n\";\n\n\n  std::cout << \"PF: Carte Lue---\" << '\\n';\n\n\tfor(int i=0;i<obstacles.size();i++)\n\t{\n\t\tObstacles1.posVertex[i][0][0] = stod(obstacles[i][0]);\n\t\tObstacles1.posVertex[i][0][1] = stod(obstacles[i][1]);\n\t\tObstacles1.posVertex[i][1][0] = stod(obstacles[i][2]);\n\t\tObstacles1.posVertex[i][1][1] = stod(obstacles[i][3]);\n\t\tObstacles1.centre[i][0] = stod(obstacles[i][4]);\n\t\tObstacles1.centre[i][1] = stod(obstacles[i][5]);\n\t\tObstacles1.distDetect[i] = stod(obstacles[i][6]);\n\t\t}\n\n\t//transform obstacles\n\tvector <vector<double>> GrandObstacle;\n\tvector <double> distDetect;\n\tfor (int i = 0; i<217;i++)\n\t{\n\t\tvector<double> temp;\n\t\ttemp.push_back(Obstacles1.posVertex[i][0][0]);\n\t\ttemp.push_back(Obstacles1.posVertex[i][0][1]);\n\t\tGrandObstacle.push_back(temp);\n\t\tvector<double> temp1;\n\t\ttemp1.push_back(Obstacles1.posVertex[i][1][0]);\n\t\ttemp1.push_back(Obstacles1.posVertex[i][1][1]);\n\t\tGrandObstacle.push_back(temp1);\n\t\tdistDetect.push_back(Obstacles1.distDetect[i]);\n\t}\n  //Load and read the map.****************************************************************\n\n  /**********INIT TIMERS*****************/\n  clock_gettime(CLOCK_REALTIME, &Time);\n\n  StartTime=Time;\n  Las1Old=Time;\n  Las2Old=Time;\n  Todo=Time;\n  Toldodo=Time;\n  LauncheTime=Time;\n  TimeEstime=Time;\n\n  /***************INIT LOG File*************/\n    std::string filename = PID_PATH(\"+PANORAMA_Log/\"+std::to_string(LauncheTime.tv_sec)+\"/PF_LOG.txt\");\n    std::ofstream savefile;\n    if(Logging){\n      savefile.open(filename,std::ios::out);\n    }\n\n    std::cout << \"PF Mode : Save file ok \\n\";\n    /***************MAIN LOOP*********************/\n    std::cout << \"PF Mode : Start Particules \\n\";\n    particles1 = particleGenerator(26.5747,29.02,-0.269984,56,-M_PI,M_PI,N/2,Obstacles1,GrandObstacle);\n    particles2 = particleGenerator(-5,26.5747,-0.269984,3,-M_PI,M_PI,N/2,Obstacles1,GrandObstacle);\n    particles1.insert( particles1.end(), particles2.begin(), particles2.end());\n    particles = particles1;\n    std::cout << \"PF Mode : Particules_rdy \\n\";\n    odom.Get(odoposP3D_Old);\n\n    /**********Ending INIT Thread*************/\n    LauncheTime=Mode.Get(presentMode);\n    Mode.Set(PF_IDLEMODE,LauncheTime);\n    presentMode=PF_IDLEMODE;\n    Las2Old=LauncheTime;\n    Las1Old=LauncheTime;\n\n    Running=1;\n    while(Running){\n        Mode.Get(presentMode);\n        clock_gettime(CLOCK_REALTIME, &StartTime);\n\n        if(verbose){\n          std::cout << \"PF Mode : \"<< presentMode << '\\n';\n        }\n\n        switch (presentMode) {\n          case PF_HALTMODE:\n            Running=0;\n            break;\n          case PF_IDLEMODE:\n            break;\n          case PF_INITMODE:\n          case PF_RUNMODE:\n            /*******************UPDATE SENSORS Reading (Odo, Las1+Las2)***********************/\n            if(verbose){\n              std::cout << \"PF Mode : Start PF\"<< '\\n';\n            }\n            Todo=odom.Get(odoposP3D);\n            std::cout << (Todo.tv_nsec+(Todo.tv_sec*1000000000)) << \"\\n\";\n            Las2Time=las2.Get(relevel2);\n            Las1Time=las1.Get(relevel1);\n            if (isafter(Las2Time,Las2Old))\n            {\n              //OldLas2=format_Telemetre(relevel2.data,relevel2.last_lenght,0.03,0,M_PI);\n              OldLas2=format_Telemetre(relevel2.data,relevel2.last_lenght,0.0,0.0,M_PI);\n              Las2Old=Las2Time;\n            }\n            if (isafter(Las1Time,Las1Old))\n            {\n//              OldLas1=format_Telemetre(relevel1.data,relevel1.last_lenght,0.03,0,0.7031*M_PI/180);\n              OldLas1=format_Telemetre(relevel1.data,relevel1.last_lenght,0.0,0.0,0.0);\n              Las1Old=Las1Time;\n            }\n\n            Telemetries.clear();\n//            if(isafter(Las2Old,LauncheTime) && !(enoughttimepassed(StartTime, Las2Old, 1000))){\n              Telemetries.insert(Telemetries.end(),OldLas2.begin(),OldLas2.end());\n//            }\n//            if(isafter(Las1Old,LauncheTime) &&  !(enoughttimepassed(StartTime, Las1Old, 1000))){\n              Telemetries.insert(Telemetries.end(),OldLas1.begin(),OldLas1.end());\n//            }\n            if(verbose){\n              std::cout << \"PF Mode : Sensors read\"<< '\\n';\n            }\n\n            if (firstIteration)\n            {\n              //get indexes of Telemetries to use in simulation\n              for (int i=0; i<NR; i++)\n              {\n                double min = 1000;\n                for(int j=0; j<Telemetries.size();j++)\n                {\n                  if (abs(theta[i]-Telemetries[j].dir.theta)<0.02)\n                    {\n                      indexes.push_back(j);\n                      break;\n                    }/*\n                    else\n                    {\n                      if (abs(theta[i]-Telemetries[j].dir.theta)<min)\n                      min = abs(theta[i]-Telemetries[j].dir.theta);\n                    }\n                    if (j == Telemetries.size()-1)\n                    {\n                    std::cout << \"PF : Angle non trouvee : \"<< theta[i] << '\\n';\n                    std::cout << \"PF : minimum trouv\u00e9 : \"<< min << '\\n';\n                    for(int k=0; k<Telemetries.size();k++)\n                    {\n                      if (abs(theta[i]-Telemetries[k].dir.theta)<0.2)\n                        {\n                        std::cout << \"PF : Val proche : \"<< Telemetries[k].dir.theta<< \" - i = \"<< k  << '\\n';\n                        }\n                    }\n                  }*/\n                }\n\n              }\n              firstIteration = false;\n            }\n\n\n\n            if(verbose){\n              std::cout << \"PF Mode : 1er it\u00e9ration ok\"<< '\\n';\n            }\n            /*******************************************************/\n            /******************PF start*****************************/\n            /*******************************************************/\n            //control of particles:\n            Recomput_Weeldist(odoposP3D_Old,odoposP3D,ssl,ssr);\n            if(verbose){\n              std::cout << \"PF Mode : weeldist ok\"<< '\\n';\n//              std::cout << \"PF Mode : weeldist ok\"<< '\\n';\n            }\n            odoposP3D_Old = odoposP3D;\n            for (int j=0;j<N;j++)\n            {\n              //tempParticle is of type euclid_position\n              tempParticle.pos.x = particles[j][0];\n              tempParticle.pos.y = particles[j][1];\n              tempParticle.dir.theta = particles[j][2];\n              SimuOdo(tempParticle,tempParticle,ssl,ssr);\n              particles[j][0]= tempParticle.pos.x;\n              particles[j][1]= tempParticle.pos.y;\n              particles[j][2]= tempParticle.dir.theta;\n            }\n\n            if(verbose){\n              std::cout << \"PF Mode : Particules simulated\"<< '\\n';\n            }\n            if(verbose){\n              std::cout << \"PF Mode : Lecture capteurs faite\"<< '\\n';\n            }\n\n            //start measurement for particles:\n            int out=0;\n            for (int k=0;k<N;k++)\n            {\n              if(verbose){\n                std::cout << \"PF Mode : Mesure simulee particule \"<< k << '\\n';\n              }\n              Mesure_act(portee,theta,GrandObstacle,distDetect,particles[k][0],particles[k][1],particles[k][2],rhoParticles,ximp,yimp);\n\n              //calculate likelihood:\n              if(isInBoxMax(particles[k][0],particles[k][1],Obstacles1,GrandObstacle))\n              {\n              poids[k] = likelihood(rhoRobot,rhoParticles);\n\n            }\n            else{\n              out++;\n              poids[k]=0;\n            }\n\n\n//              if(verbose){\n//                std::cout << \"PF Mode : Poid simulee particule \"<< poids[k] << '\\n';\n//              }\n            }\n\n\n\n            if(verbose){\n              std::cout << \"PF Mode : Nombre de particule paume :\" << out<< '\\n';\n            }\n\n            if(verbose){\n              std::cout << \"PF Mode : Poids fait\"<< '\\n';\n            }\n            //calculate the estimated position:\n            sumPoids = accumulate(poids.begin(), poids.end(), 0.0);\n            poseEstimate[0] = 0.0;\n            poseEstimate[1] = 0.0;\n            poseEstimate[2] = 0.0;\n\n            for (int i=0;i<N;i++)\n            {\n                poseEstimate[0] = poseEstimate[0]+particles[i][0]*poids[i];\n                poseEstimate[1] = poseEstimate[1]+particles[i][1]*poids[i];\n                poseEstimate[2] = poseEstimate[2]+particles[i][2]*poids[i];\n            }\n            poseEstimate[0] = poseEstimate[0]/sumPoids;\n            poseEstimate[1] = poseEstimate[1]/sumPoids;\n            poseEstimate[2] = poseEstimate[2]/sumPoids;\n\n            if(verbose){\n              std::cout << \"PF Mode : Estime fait\"<< '\\n';\n            }\n\n            Val_estime.pos.x = poseEstimate[0];\n            Val_estime.pos.y = poseEstimate[1];\n            Val_estime.dir.theta = poseEstimate[2];\n            clock_gettime(CLOCK_REALTIME, &TimeEstime);\n\n\n            meanX = 0.0;\n            meanY = 0.0;\n            meanTheta = 0.0;\n            // check for convergance\n            for (int ii = 0; ii<N; ii++)\n            {\n                meanX += particles[ii][0];\n                meanY += particles[ii][1];\n                meanTheta += particles[ii][2];\n            }\n\n            meanX /= N*1.0;\n            meanY /= N*1.0;\n            meanTheta /= N*1.0;\n\n            if(verbose){\n              std::cout << \"PF Mode : Means\"<< '\\n';\n            }\n\n            for (int ii = 0; ii<N; ii++)\n            {\n                wsd[0] += poids[ii]*(particles[ii][0]-meanX)*(particles[ii][0]-meanX)*1.0; // we didn't use pow because particles[ii][0] is a vector of double not a double\n                wsd[1] += poids[ii]*(particles[ii][1]-meanY)*(particles[ii][1]-meanY)*1.0;\n                wsd[2] += poids[ii]*(particles[ii][2]-meanTheta)*(particles[ii][2]-meanTheta)*1.0;\n            }\n\n            wsd[0] = sqrt(wsd[0]/((N-1)/N*sumPoids))*1.0;\n            wsd[1] = sqrt(wsd[1]/((N-1)/N*sumPoids))*1.0;\n            wsd[2] = sqrt(wsd[2]/((N-1)/N*sumPoids))*1.0;\n\n            if(verbose){\n              std::cout << \"PF Mode : Ecart type ok\"<< '\\n';\n            }\n\n            if (wsd[0]<2 && wsd[1]<2 && wsd[2]<0.5)\n            {\n                //particles filter converged we can send info if we want\n                flagConvergance = true;\n            }\n            else\n            {\n                flagConvergance = false;\n            }\n\n            //check for redistribution:\n            if (wsd[0]<0.3 && wsd[1]<0.3)\n            {\n              flagRedistribution = true;\n            }\n            else\n            {\n              flagRedistribution = false;\n            }\n\n\n            if(verbose){\n              std::cout << \"PF Mode : Eclate flag ok\"<< '\\n';\n            }\n            flagRedistribution=false;\n\n            iNextGeneration = selection(poids,N);\n            if(iNextGeneration.size()==0){//Totalement paume\n              flagRedistribution=true;\n            }\n              if(verbose){\n                std::cout << \"PF Mode : Selec ok\"<< '\\n';\n              }\n\n\n\n\n            if (flagRedistribution)\n            {\n              //redistribute particels\n              particles1 = particleGenerator(26.5747,29.02,-0.269984,56,-M_PI,M_PI,N/2,Obstacles1,GrandObstacle);\n              particles2 = particleGenerator(-5,26.5747,-0.269984,3,-M_PI,M_PI,N/2,Obstacles1,GrandObstacle);\n              particles1.insert( particles1.end(), particles2.begin(), particles2.end() );\n              particles = particles1;\n              for (int k=0;k<N;k++)\n              {\n                  poids[k] = 1/N;\n              }\n            }\n            else\n            {\n              //get the new particles\n              cout << \"nombre de particule a regenerer \" << iNextGeneration.size() << endl;\n              particles = testInext(iNextGeneration, particles, Obstacles1, GrandObstacle);\n              if(verbose){\n                std::cout << \"PF Mode : test ok\"<< '\\n';\n              }\n            }\n\n            if (presentMode == PF_RUNMODE && flagConvergance)\n            {\n              // send data if run mode and if we converged\n              Estimation.Set(Val_estime,TimeEstime);\n            }\n            /*******************************************************/\n            /******************PF end*******************************/\n            /*******************************************************/\n            break;\n        }\n\n        if(verbose){\n          std::cout << \"PF_Will log \\n\";\n\n        }\n        if(Logging){\n\n          std::cout << \"PF logging now \\n\";\n          std::cout << \"++++++++++++++++++++++++++++++++++++++++++++++++++ \\n\";\n          std::cout << poseEstimate[0] << \"\\n\";\n          std::cout << poseEstimate[1] << \"\\n\";\n          std::cout << poseEstimate[2] << \"\\n\";\n          std::cout  << odoposP3D.pos.x << \"\\n\";\n          std::cout  << odoposP3D.pos.y << \"\\n\";\n          std::cout  << odoposP3D.dir.theta << \"\\n\";\n          std::cout << wsd[0] << \"\\n\";\n          std::cout << wsd[1] << \"\\n\";\n          std::cout << wsd[2] << \"\\n\";\n          std::cout  << *max_element(poids.begin(), poids.end()) << \"\\n\"; //return the max wheight\n          std::cout  << sumPoids << \"\\n\"; //return sum of the wheights\n          std::cout << \"++++++++++++++++++++++++++++++++++++++++++++++++++ \\n\";\n          clock_gettime(CLOCK_REALTIME, &TimeLog);\n          /***************Logging**************/\n          savefile << (StartTime.tv_nsec+(StartTime.tv_sec*1000000000)) << \",\" << presentMode << \",\";\n          savefile << (TimeLog.tv_nsec+(TimeLog.tv_sec*1000000000)) << \",\";\n          savefile << (Las1Old.tv_nsec+(Las1Old.tv_sec*1000000000)) << \",\";\n          savefile << (Las2Old.tv_nsec+(Las2Old.tv_sec*1000000000)) << \",\";\n          savefile << (Todo.tv_nsec+(Todo.tv_sec*1000000000)) << \",\";\n          savefile << (TimeEstime.tv_nsec+(TimeEstime.tv_sec*1000000000)) << \",\";\n          savefile << odoposP3D.pos.x << \",\";\n          savefile << odoposP3D.pos.y << \",\";\n          savefile << odoposP3D.dir.theta << \",\";\n          savefile << poseEstimate[0] << \",\";\n          savefile << poseEstimate[1] << \",\";\n          savefile << poseEstimate[2] << \",\";\n          savefile << wsd[0] << \",\"; //wheighted standard deviation for x\n          savefile << wsd[1] << \",\"; //wheighted standard deviation for y\n          savefile << wsd[2] << \",\"; //wheighted standard deviation for theta\n          savefile << *max_element(poids.begin(), poids.end()) << \",\"; //return the max wheight\n          savefile << sumPoids << \",\"; //return sum of the wheights\n          savefile << N << \",\"; //return number of particles\n          savefile << NR << \",\"; //return number of rayes\n          savefile << flagConvergance << \",\";\n          savefile << flagRedistribution << \",\";\n\n        ///Anything\n        savefile<<\"\\n\";\n        }\n\n        //Computing for a 10Hz maximum frequency\n        lsleep=delayusleep(StartTime, 100);\n        if(lsleep<0){\n          lsleep=0;\n        }\n        usleep(lsleep);\n    }\n\n    /****************Closing thread***************/\n    if(Logging){\n      savefile.close();\n      std::cout << \"PF log file closed at : \" << filename << '\\n';\n    }\n}\n", "meta": {"hexsha": "8c4678585b545e8e5267d18eb5ae264bbe8c76da", "size": 18901, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "codeCpp/PF.cpp", "max_stars_repo_name": "benaliabderrahmane/-Localization-by-particle-filter--Off-line-and-Online-localization-performance-evaluation", "max_stars_repo_head_hexsha": "a5814359e3796b7f98be47e8ab22121131579ee0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2022-01-12T07:33:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T21:06:32.000Z", "max_issues_repo_path": "codeCpp/PF.cpp", "max_issues_repo_name": "benaliabderrahmane/-Localization-by-particle-filter--Off-line-and-Online-localization-performance-evaluation", "max_issues_repo_head_hexsha": "a5814359e3796b7f98be47e8ab22121131579ee0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "codeCpp/PF.cpp", "max_forks_repo_name": "benaliabderrahmane/-Localization-by-particle-filter--Off-line-and-Online-localization-performance-evaluation", "max_forks_repo_head_hexsha": "a5814359e3796b7f98be47e8ab22121131579ee0", "max_forks_repo_licenses": ["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.4615384615, "max_line_length": 268, "alphanum_fraction": 0.5184381779, "num_tokens": 4984, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721305, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.49062906147594315}}
{"text": "\ufeff/*! \\file solveeom.cpp\n    \\brief \u5358\u632f\u308a\u5b50\u306b\u5bfe\u3057\u3066\u904b\u52d5\u65b9\u7a0b\u5f0f\u3092\u89e3\u304f\u30af\u30e9\u30b9\u306e\u5b9f\u88c5\n\n    Copyright \u00a9  2016 @dc1394 All Rights Reserved.\n    (but this is originally adapted by Freddie Witherden for doublependulum.cpp from https://freddie.witherden.org/tools/doublependulum/ )\n    This software is released under the BSD 2-Clause License.\n*/\n#include \"solveeom.h\"\n#include <cmath>                                // for std::sin, std::cos\n#include <fstream>                              // for std::ofstream\n#include <boost/assert.hpp>                     // for BOOST_ASSERT\n#include <boost/format.hpp>                     // for boost::format\n#include <boost/math/constants/constants.hpp>   // for boost::math::constants::pi\n\nnamespace solveeom {\n    // #region \u30b3\u30f3\u30b9\u30c8\u30e9\u30af\u30bf\n\n    SolveEOM::SolveEOM(float l, float m, float theta1_0, float theta2_0) :\n        Theta1([this] { return static_cast<float>(x_[0]); }, [this](auto theta) { return x_[0] = theta; }),\n        Theta2([this] { return static_cast<float>(x_[2]); }, [this](auto theta) { return x_[2] = theta; }),\n        V1([this] { return static_cast<float>(x_[1]); }, [this](auto v) { return x_[1] = v; }),\n        V2([this] { return static_cast<float>(x_[3]); }, [this](auto v) { return x_[3] = v; }),\n        l_(l),\n        m_(m),\n        stepper_(SolveEOM::EPS, SolveEOM::EPS)\n    {\n        \n        x_ = { theta1_0, 0.0, theta2_0, 0.0 };\n    }\n\n    // #endregion \u30b3\u30f3\u30b9\u30c8\u30e9\u30af\u30bf\n\n    // #region public\u30e1\u30f3\u30d0\u95a2\u6570\n        \n    float SolveEOM::kinetic_energy() const\n    {\n        return static_cast<float>(\n            m_ * l_ * l_ * (sqr(x_[1]) + 0.5 * sqr(x_[3])) +\n            m_ * l_ * l_ * x_[1] * x_[3] * std::cos(x_[0] - x_[2]));\n    }\n\n    void SolveEOM::operator()(float dt, float * theta1, float * theta2)\n    {\n        boost::numeric::odeint::integrate_adaptive(\n            stepper_,\n            getEOM(),\n            x_,\n            0.0,\n            static_cast<double>(dt),\n            SolveEOM::DX);\n\n        *theta1 = static_cast<float>(x_[0]);\n        *theta2 = static_cast<float>(x_[2]);\n    }\n\n    void SolveEOM::operator()(double dt, std::string const & filename, double t)\n    {\n        std::ofstream result(filename);\n\n        boost::numeric::odeint::integrate_const(\n            stepper_,\n            getEOM(),\n            x_,\n            0.0,\n            t,\n            dt,\n            [&result, this](auto const & x, auto const t)\n        {\n\t\t\tresult << boost::format(\"%.3f, %.15f, %.15f, %.15f\\n\") % t % x[0] % x[2] % total_energy();\n        });\n    }\n\n    float SolveEOM::potential_energy() const\n    {\n        return static_cast<float>(m_ * SolveEOM::g * l_ * (3.0 - 2.0 * std::cos(x_[0]) - std::cos(x_[2])));\n    }\n\n    // #endregion public\u30e1\u30f3\u30d0\u95a2\u6570\n\n    // #region private\u30e1\u30f3\u30d0\u95a2\u6570\n\n    std::function<void(SolveEOM::state_type const &, SolveEOM::state_type &, double const)> SolveEOM::getEOM() const\n    {\n        auto const eom = [this](state_type const & x, state_type & dxdt, double const)\n        {\n            // Delta is \u03b82 - \u03b81\n            auto const delta = x[Num_eqns::THETA_2] - x[Num_eqns::THETA_1];\n\n            // `Big-M' is the total mass of the system, m1 + m2;\n            auto const M = 2.0 * m_;\n\n            // Denominator expression for \u03c91\n            auto den = M * l_ - m_ * l_ * std::cos(delta) * std::cos(delta);\n\n            // d\u03b8/dt = \u03c9, by definition\n            dxdt[Num_eqns::THETA_1] = x[Num_eqns::OMEGA_1];\n\n            // Compute \u03c91\n            dxdt[OMEGA_1] = (m_ * l_ * x[Num_eqns::OMEGA_1] * x[Num_eqns::OMEGA_1] * std::sin(delta) * std::cos(delta)\n                + m_ * g * std::sin(x[Num_eqns::THETA_2]) * std::cos(delta)\n                + m_ * l_ * x[Num_eqns::OMEGA_2] * x[Num_eqns::OMEGA_2] * std::sin(delta)\n                - M * g * std::sin(x[THETA_1])) / den;\n\n            // Again, d\u03b8/dt = \u03c9 for \u03b82 as well\n            dxdt[THETA_2] = x[OMEGA_2];\n\n            // Multiply den by the length ratio of the two bobs\n            den *= l_ / l_;\n\n            // Compute \u03c92\n            dxdt[Num_eqns::OMEGA_2] = (-m_ * l_ * x[Num_eqns::OMEGA_2] * x[Num_eqns::OMEGA_2] * std::sin(delta) * std::cos(delta)\n                + M * g * std::sin(x[Num_eqns::THETA_1]) * std::cos(delta)\n                - M * l_ * x[OMEGA_1] * x[Num_eqns::OMEGA_1] * std::sin(delta)\n                - M * g * std::sin(x[Num_eqns::THETA_2])) / den;\n        };\n\n        return eom;\n    }\n\n\tdouble SolveEOM::total_energy() const\n\t{\n\t\tauto const kinetic = m_ * l_ * l_ * (sqr(x_[1]) + 0.5 * sqr(x_[3])) + m_ * l_ * l_ * x_[1] * x_[3] * std::cos(x_[0] - x_[2]);\n\t\tauto const potential = m_ * SolveEOM::g * l_ * (3.0 - 2.0 * std::cos(x_[0]) - std::cos(x_[2]));\n\n\t\treturn kinetic + potential;\n\t}\n\n    // #endregion private\u30e1\u30f3\u30d0\u95a2\u6570\n}", "meta": {"hexsha": "5bb922e33d998243d44e7944ff1972a0f3de2cbe", "size": 4671, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "solveeom/solveeom/solveeom.cpp", "max_stars_repo_name": "dc1394/doublependulum", "max_stars_repo_head_hexsha": "2833ed2d0c300007cca82b80365ef9108e35aa5e", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-13T01:09:39.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-13T01:09:39.000Z", "max_issues_repo_path": "solveeom/solveeom/solveeom.cpp", "max_issues_repo_name": "dc1394/doublependulum", "max_issues_repo_head_hexsha": "2833ed2d0c300007cca82b80365ef9108e35aa5e", "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": "solveeom/solveeom/solveeom.cpp", "max_forks_repo_name": "dc1394/doublependulum", "max_forks_repo_head_hexsha": "2833ed2d0c300007cca82b80365ef9108e35aa5e", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-06-13T01:09:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-13T01:09:44.000Z", "avg_line_length": 36.2093023256, "max_line_length": 138, "alphanum_fraction": 0.5281524299, "num_tokens": 1513, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721305, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.49062906147594315}}
{"text": "#include <stan/math/rev.hpp>\n#include <gtest/gtest.h>\n#include <boost/numeric/odeint.hpp>\n#include <test/unit/math/rev/functor/util_cvodes_adams.hpp>\n#include <test/unit/math/prim/functor/harmonic_oscillator.hpp>\n#include <test/unit/math/prim/functor/forced_harmonic_oscillator.hpp>\n#include <test/unit/math/prim/functor/lorenz.hpp>\n#include <iostream>\n#include <sstream>\n#include <vector>\n#include <string>\n\ntemplate <typename F, typename T_y0, typename T_theta>\nvoid sho_value_test(F harm_osc, std::vector<double>& y0, double t0,\n                    std::vector<double>& ts, std::vector<double>& theta,\n                    std::vector<double>& x, std::vector<int>& x_int) {\n  using stan::math::promote_scalar;\n  using stan::math::var;\n\n  std::vector<std::vector<var> > ode_res_vd = stan::math::integrate_ode_adams(\n      harm_osc, promote_scalar<T_y0>(y0), t0, ts,\n      promote_scalar<T_theta>(theta), x, x_int);\n\n  EXPECT_NEAR(0.995029, ode_res_vd[0][0].val(), 1e-5);\n  EXPECT_NEAR(-0.0990884, ode_res_vd[0][1].val(), 1e-5);\n\n  EXPECT_NEAR(-0.421907, ode_res_vd[99][0].val(), 1e-5);\n  EXPECT_NEAR(0.246407, ode_res_vd[99][1].val(), 1e-5);\n}\n\nvoid sho_finite_diff_test(double t0) {\n  using stan::math::var;\n  harm_osc_ode_fun harm_osc;\n\n  std::vector<double> theta;\n  theta.push_back(0.15);\n\n  std::vector<double> y0;\n  y0.push_back(1.0);\n  y0.push_back(0.0);\n\n  std::vector<double> ts;\n  for (int i = 0; i < 100; i++)\n    ts.push_back(t0 + 0.1 * (i + 1));\n\n  std::vector<double> x;\n  std::vector<int> x_int;\n\n  test_ode_cvode(harm_osc, t0, ts, y0, theta, x, x_int, 1e-8, 1e-4);\n\n  sho_value_test<harm_osc_ode_fun, double, var>(harm_osc, y0, t0, ts, theta, x,\n                                                x_int);\n  sho_value_test<harm_osc_ode_fun, var, double>(harm_osc, y0, t0, ts, theta, x,\n                                                x_int);\n  sho_value_test<harm_osc_ode_fun, var, var>(harm_osc, y0, t0, ts, theta, x,\n                                             x_int);\n}\n\nvoid sho_data_finite_diff_test(double t0) {\n  using stan::math::var;\n  harm_osc_ode_data_fun harm_osc;\n\n  std::vector<double> theta;\n  theta.push_back(0.15);\n\n  std::vector<double> y0;\n  y0.push_back(1.0);\n  y0.push_back(0.0);\n\n  std::vector<double> ts;\n  for (int i = 0; i < 100; i++)\n    ts.push_back(t0 + 0.1 * (i + 1));\n\n  std::vector<double> x(3, 1);\n  std::vector<int> x_int(2, 0);\n\n  test_ode_cvode(harm_osc, t0, ts, y0, theta, x, x_int, 1e-8, 1e-4);\n\n  sho_value_test<harm_osc_ode_data_fun, double, var>(harm_osc, y0, t0, ts,\n                                                     theta, x, x_int);\n  sho_value_test<harm_osc_ode_data_fun, var, double>(harm_osc, y0, t0, ts,\n                                                     theta, x, x_int);\n  sho_value_test<harm_osc_ode_data_fun, var, var>(harm_osc, y0, t0, ts, theta,\n                                                  x, x_int);\n}\n\ntemplate <typename T_y0, typename T_theta, typename F>\nvoid sho_error_test(F harm_osc, std::vector<double>& y0, double t0,\n                    std::vector<double>& ts, std::vector<double>& theta,\n                    std::vector<double>& x, std::vector<int>& x_int,\n                    std::string error_msg) {\n  using stan::math::promote_scalar;\n  using stan::math::var;\n\n  EXPECT_THROW_MSG(stan::math::integrate_ode_adams(\n                       harm_osc, promote_scalar<T_y0>(y0), t0, ts,\n                       promote_scalar<T_theta>(theta), x, x_int),\n                   std::invalid_argument, error_msg);\n}\n\nTEST(StanAgradRevOde_integrate_ode_adams, harmonic_oscillator_finite_diff) {\n  sho_finite_diff_test(0);\n  sho_finite_diff_test(2.0);\n  sho_finite_diff_test(-2.0);\n\n  sho_data_finite_diff_test(0);\n  sho_data_finite_diff_test(2.5);\n  sho_data_finite_diff_test(-2.5);\n}\n\nTEST(StanAgradRevOde_integrate_ode_adams, harmonic_oscillator_error) {\n  using stan::math::var;\n  harm_osc_ode_wrong_size_1_fun harm_osc;\n\n  std::vector<double> theta;\n  theta.push_back(0.15);\n\n  std::vector<double> y0;\n  y0.push_back(1.0);\n  y0.push_back(0.0);\n\n  double t0 = 0;\n  std::vector<double> ts;\n  for (int i = 0; i < 100; i++)\n    ts.push_back(t0 + 0.1 * (i + 1));\n\n  std::vector<double> x(3, 1);\n  std::vector<int> x_int(2, 0);\n\n  // aligned error handling with non-stiff case\n  std::string error_msg\n      = \"cvodes_ode_data: dz_dt (3) and states (2) must match in size\";\n\n  sho_error_test<double, var>(harm_osc, y0, t0, ts, theta, x, x_int, error_msg);\n  sho_error_test<var, double>(harm_osc, y0, t0, ts, theta, x, x_int, error_msg);\n  sho_error_test<var, var>(harm_osc, y0, t0, ts, theta, x, x_int, error_msg);\n}\n\nTEST(StanAgradRevOde_integrate_ode_adams, time_steps_as_param) {\n  using stan::math::integrate_ode_adams;\n  using stan::math::to_var;\n\n  const double t0 = 0.0;\n  harm_osc_ode_fun ode;\n  std::vector<double> theta{0.15};\n  std::vector<double> y0{1.0, 0.0};\n  std::vector<stan::math::var> ts;\n  for (int i = 0; i < 100; i++)\n    ts.push_back(t0 + 0.1 * (i + 1));\n  std::vector<double> x;\n  std::vector<int> x_int;\n  std::vector<stan::math::var> y0v = to_var(y0);\n  std::vector<stan::math::var> thetav = to_var(theta);\n  stan::math::var t0v = 0.0;\n\n  std::vector<std::vector<stan::math::var> > res;\n  auto test_val = [&res]() {\n    EXPECT_NEAR(0.995029, res[0][0].val(), 1e-5);\n    EXPECT_NEAR(-0.0990884, res[0][1].val(), 1e-5);\n    EXPECT_NEAR(-0.421907, res[99][0].val(), 1e-5);\n    EXPECT_NEAR(0.246407, res[99][1].val(), 1e-5);\n  };\n  res = integrate_ode_adams(ode, y0, t0, ts, theta, x, x_int);\n  test_val();\n  res = integrate_ode_adams(ode, y0v, t0, ts, theta, x, x_int);\n  test_val();\n  res = integrate_ode_adams(ode, y0, t0, ts, thetav, x, x_int);\n  test_val();\n  res = integrate_ode_adams(ode, y0v, t0, ts, thetav, x, x_int);\n  test_val();\n  res = integrate_ode_adams(ode, y0, t0v, ts, theta, x, x_int);\n  test_val();\n  res = integrate_ode_adams(ode, y0v, t0v, ts, theta, x, x_int);\n  test_val();\n  res = integrate_ode_adams(ode, y0, t0v, ts, thetav, x, x_int);\n  test_val();\n  res = integrate_ode_adams(ode, y0v, t0v, ts, thetav, x, x_int);\n  test_val();\n}\n\nTEST(StanAgradRevOde_integrate_ode_adams, time_steps_as_param_AD) {\n  using stan::math::integrate_ode_adams;\n  using stan::math::to_var;\n  using stan::math::value_of;\n  using stan::math::var;\n  const double t0 = 0.0;\n  const int nt = 100;  // nb. of time steps\n  const int ns = 2;    // nb. of states\n  std::ostream* msgs = NULL;\n\n  forced_harm_osc_ode_fun ode;\n\n  std::vector<double> theta{0.15, 0.25};\n  std::vector<double> y0{1.0, 0.0};\n  std::vector<stan::math::var> ts;\n  for (int i = 0; i < nt; i++)\n    ts.push_back(t0 + 0.1 * (i + 1));\n\n  std::vector<double> x;\n  std::vector<int> x_int;\n  std::vector<stan::math::var> y0v = to_var(y0);\n  std::vector<stan::math::var> thetav = to_var(theta);\n\n  std::vector<std::vector<stan::math::var> > res;\n  std::vector<double> g;\n  auto test_ad = [&res, &g, &ts, &ode, &nt, &ns, &theta, &x, &x_int, &msgs]() {\n    for (auto i = 0; i < nt; ++i) {\n      std::vector<double> res_d = value_of(res[i]);\n      for (auto j = 0; j < ns; ++j) {\n        g.clear();\n        res[i][j].grad(ts, g);\n        for (auto k = 0; k < nt; ++k) {\n          if (k != i) {\n            EXPECT_FLOAT_EQ(g[k], 0.0);\n          } else {\n            std::vector<double> y0(res_d.begin(), res_d.begin() + ns);\n            EXPECT_FLOAT_EQ(g[k],\n                            ode(ts[i].val(), y0, theta, x, x_int, msgs)[j]);\n          }\n        }\n        stan::math::set_zero_all_adjoints();\n      }\n    }\n  };\n  res = integrate_ode_adams(ode, y0, t0, ts, theta, x, x_int);\n  test_ad();\n  res = integrate_ode_adams(ode, y0v, t0, ts, theta, x, x_int);\n  test_ad();\n  res = integrate_ode_adams(ode, y0, t0, ts, thetav, x, x_int);\n  test_ad();\n  res = integrate_ode_adams(ode, y0v, t0, ts, thetav, x, x_int);\n  test_ad();\n}\n\nTEST(StanAgradRevOde_integrate_ode_adams, t0_as_param_AD) {\n  using stan::math::integrate_ode_adams;\n  using stan::math::to_var;\n  using stan::math::value_of;\n  using stan::math::var;\n  const double t0 = 0.0;\n  const int nt = 100;  // nb. of time steps\n  const int ns = 2;    // nb. of states\n  std::ostream* msgs = NULL;\n\n  forced_harm_osc_ode_fun ode;\n\n  std::vector<double> theta{0.15, 0.25};\n  std::vector<double> y0{1.0, 0.0};\n  std::vector<double> ts;\n  for (int i = 0; i < nt; i++)\n    ts.push_back(t0 + 0.1 * (i + 1));\n\n  std::vector<double> x;\n  std::vector<int> x_int;\n  std::vector<stan::math::var> y0v = to_var(y0);\n  std::vector<stan::math::var> thetav = to_var(theta);\n  stan::math::var t0v = 0.0;\n\n  std::vector<std::vector<stan::math::var> > res;\n  auto test_ad = [&res, &t0v, &ode, &nt, &ns, &theta, &x, &x_int, &msgs]() {\n    for (auto i = 0; i < nt; ++i) {\n      std::vector<double> res_d = value_of(res[i]);\n      for (auto j = 0; j < ns; ++j) {\n        res[i][j].grad();\n        for (auto k = 0; k < nt; ++k) {\n          EXPECT_FLOAT_EQ(t0v.adj(), 0.0);\n        }\n        stan::math::set_zero_all_adjoints();\n      }\n    }\n  };\n  res = integrate_ode_adams(ode, y0, t0v, ts, theta, x, x_int);\n  test_ad();\n  res = integrate_ode_adams(ode, y0v, t0v, ts, theta, x, x_int);\n  test_ad();\n  res = integrate_ode_adams(ode, y0, t0v, ts, thetav, x, x_int);\n  test_ad();\n  res = integrate_ode_adams(ode, y0v, t0v, ts, thetav, x, x_int);\n  test_ad();\n}\n", "meta": {"hexsha": "fd81543f80d1db2831ba84cdeda848d2364d9167", "size": 9255, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/rev/functor/integrate_ode_adams_rev_test.cpp", "max_stars_repo_name": "christophernhill/math", "max_stars_repo_head_hexsha": "dc41aba296d592c7099be15eed6ba136d0f140b3", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/unit/math/rev/functor/integrate_ode_adams_rev_test.cpp", "max_issues_repo_name": "christophernhill/math", "max_issues_repo_head_hexsha": "dc41aba296d592c7099be15eed6ba136d0f140b3", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/unit/math/rev/functor/integrate_ode_adams_rev_test.cpp", "max_forks_repo_name": "christophernhill/math", "max_forks_repo_head_hexsha": "dc41aba296d592c7099be15eed6ba136d0f140b3", "max_forks_repo_licenses": ["BSD-3-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.9359430605, "max_line_length": 80, "alphanum_fraction": 0.6117774176, "num_tokens": 3262, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.6334102567576901, "lm_q1q2_score": 0.49062906024414465}}
{"text": "/*\n * Complex arrays example\n */\n\n#include <blitz/array.h>\n\nBZ_USING_NAMESPACE(blitz)\n\nconst double pi = 3.14159265358979323846264338327950288;\n\n#ifndef BZ_HAVE_COMPLEX\nint main()\n{\n    cout << \"Complex number support is required to compile this example.\"\n         << endl;\n    return 0;\n}\n\n#else\n\nint main()\n{\n    const int N = 16;\n\n    Array<complex<double>,1> A(N);\n    Array<double,1> theta(N);\n\n    BZ_USING_NAMESPACE(blitz::tensor);\n\n    // Fill the theta array with angles from 0..2 Pi, evenly spaced\n    theta = (2 * pi * i) / N;\n\n    // Set A[i] = cos(theta[i]) + _I * sin(theta[i])\n    A = zip(cos(theta), sin(theta), complex<double>());\n\n    cout << A << endl;\n\n#ifdef BZ_HAVE_COMPLEX_MATH1\n    // Here's another way of doing it, which eliminates the need for\n    // the theta array:\n    // Set A[i] = exp(Pi i _I / N)\n    A = exp(zip(0.0, (2 * pi * i) / N, complex<double>()));\n\n    cout << A << endl;\n#endif\n\n    return 0;\n}\n#endif // BZ_HAVE_COMPLEX\n", "meta": {"hexsha": "0a3909811252503de5d3ad1e64254a0da193521b", "size": 964, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depspawn-blitz-0.10/examples/complex-test.cpp", "max_stars_repo_name": "fraguela/depspawn", "max_stars_repo_head_hexsha": "b5760f4c0d38a1b245ee5274e2ccc5c5fe2d3d45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-04-12T11:05:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T11:10:27.000Z", "max_issues_repo_path": "ibtk/third_party/blitz-0.10/examples/complex-test.cpp", "max_issues_repo_name": "MSV-Project/IBAMR", "max_issues_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ibtk/third_party/blitz-0.10/examples/complex-test.cpp", "max_forks_repo_name": "MSV-Project/IBAMR", "max_forks_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_forks_repo_licenses": ["BSD-3-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.28, "max_line_length": 73, "alphanum_fraction": 0.6089211618, "num_tokens": 283, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577159, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.4906290590123458}}
{"text": "#include <cassert>\n#include <armadillo>\n\nvoid repack_matrix_to_vector_fast(arma::vec &v, const arma::mat &m)\n{\n\n    const size_t d1 = m.n_cols;\n    const size_t d2 = m.n_rows;\n    const size_t dv = d1 * d2;\n    assert(v.n_elem == dv);\n\n    size_t ia;\n    for (size_t i = 0; i < d1; i++) {\n        for (size_t a = 0; a < d2; a++) {\n            ia = i*d2 + a;\n            v(ia) = m(a, i);\n        }\n    }\n\n    return;\n\n}\n\nvoid repack_matrix_to_vector(arma::vec &v, const arma::mat &m)\n{\n\n    const size_t d1 = m.n_rows;\n    const size_t d2 = m.n_cols;\n    const size_t dv = d1 * d2;\n    assert(v.n_elem == dv);\n\n    size_t ia;\n    for (size_t i = 0; i < d1; i++) {\n        for (size_t a = 0; a < d2; a++) {\n            ia = i*d2 + a;\n            v(ia) = m(i, a);\n        }\n    }\n\n    return;\n\n}\n\nvoid repack_vector_to_matrix(arma::mat &m, const arma::vec &v)\n{\n\n    const size_t d1 = m.n_rows;\n    const size_t d2 = m.n_cols;\n    const size_t dv = d1 * d2;\n    assert(v.n_elem == dv);\n\n    size_t ia;\n    for (size_t i = 0; i < d1; i++) {\n        for (size_t a = 0; a < d2; a++) {\n            ia = i*d2 + a;\n            m(i, a) = v(ia);\n        }\n    }\n\n    return;\n}\n\nint main() {\n\n    const size_t d1 = 3;\n    const size_t d2 = 4;\n\n    arma::mat m(d1, d2);\n    arma::vec v(d1 * d2);\n\n    size_t ia;\n    for (size_t i = 0; i < d1; i++) {\n        for (size_t a = 0; a < d2; a++) {\n            ia = i*d2 + a;\n            m(i, a) = ia;\n        }\n    }\n\n    m.print(\"m\");\n    repack_matrix_to_vector(v, m);\n    v.print(\"v\");\n\n    arma::vec v2(d1 * d2);\n    arma::mat m2 = m.t();\n    repack_matrix_to_vector_fast(v2, m2);\n    m2.print(\"m2\");\n    v2.print(\"v2\");\n\n    arma::vec mv = arma::vectorise(m);\n    mv.print(\"vectorise(m)\");\n    // otherwise we get a rowvec!\n    arma::vec mv1 = arma::vectorise(m, 1).t();\n    mv1.print(\"vectorise(m, 1)\");\n\n    arma::vec mv2 = arma::vectorise(m2);\n    mv2.print(\"vectorise(m2)\");\n\n    return 0;\n}\n", "meta": {"hexsha": "fae1dcace35d25d7d03ddaebfd928365b2e63341", "size": 1932, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/armadillo/repack.cpp", "max_stars_repo_name": "berquist/eg", "max_stars_repo_head_hexsha": "4c368b12eaaffcf0af8032f10348cf8bc1c3957a", "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": "cpp/armadillo/repack.cpp", "max_issues_repo_name": "berquist/eg", "max_issues_repo_head_hexsha": "4c368b12eaaffcf0af8032f10348cf8bc1c3957a", "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": "cpp/armadillo/repack.cpp", "max_forks_repo_name": "berquist/eg", "max_forks_repo_head_hexsha": "4c368b12eaaffcf0af8032f10348cf8bc1c3957a", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.32, "max_line_length": 67, "alphanum_fraction": 0.4870600414, "num_tokens": 678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.7490872243177518, "lm_q1q2_score": 0.49057327479849344}}
{"text": "//////////////////////////////////////////////////////////////////////////////////////\n// distribution::toolkit::distributions::students_t::description.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_STUDENTS_T_DESCRIPTION_HPP_ER_2009\n#define BOOST_STATISTICS_DETAIL_DISTRIBUTION_TOOLKIT_STUDENTS_T_DESCRIPTION_HPP_ER_2009\n#include <string>\n#include <boost/format.hpp>\n#include <boost/math/distributions/students_t.hpp>\n\nnamespace boost{\nnamespace math{\n\n    template<typename T,typename P>\n    std::string\n    description(const boost::math::students_t_distribution<T,P>& dist)\n    {\n        static const char* msg = \"students_t(%1%)\";\n        format f(msg); f%dist.degrees_of_freedom();\n        return f.str();\n    }\n    \n}// math\n}// boost\n\n#endif\n", "meta": {"hexsha": "c17bfb7bf1926b1d4a1ec4c4342ca8d043fd9688", "size": 1300, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "distribution_toolkit/boost/statistics/detail/distribution_toolkit/distributions/students_t/description.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/distributions/students_t/description.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/distributions/students_t/description.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": 41.935483871, "max_line_length": 87, "alphanum_fraction": 0.5184615385, "num_tokens": 240, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7490872243177518, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.49057327479849344}}
{"text": "\ufeff/*! \\file foelement.cpp\n    \\brief Bogoliubov-de Gennes\u65b9\u7a0b\u5f0f\u3092\u89e3\u304f\u30af\u30e9\u30b9\u306e\u5b9f\u88c5\n    Copyright \u00a9  2016 @dc1394 All Rights Reserved.\n    (but this is originally adapted by cometscome for Chev.py from https://github.com/cometscome/ChebyshevPolynomialBdG )\n    This software is released under the BSD 2-Clause License.\n*/\n\n#include \"chev.h\"\n#include <cmath>                // for std::acos, for std::sin\n#include <iomanip>              // for std::setprecision\n#include <iostream>             // for std::cout\n#include <vector>               // for std::vector\n#include <Eigen/EigenValues>    // for Eigen::SelfAdjointEigenSolver\n\nnamespace chebyshevpolynomialbdg {\n    // #region \u30b3\u30f3\u30b9\u30c8\u30e9\u30af\u30bf\n\n    Chev::Chev()\n        :   vec_ai_(Chev::NC),\n            vec_delta_(Chev::LN_2, Chev::LN_2)\n    {\n        std::cout.setf(std::ios::fixed, std::ios::floatfield);\n    }\n\n    // #endregion \u30b3\u30f3\u30b9\u30c8\u30e9\u30af\u30bf\n\n    // #region public\u30e1\u30f3\u30d0\u95a2\u6570\n\n    void Chev::iteration(bool full)\n    {\n        std::cout << std::setprecision(15);\n        \n        init_delta();\n        calc_A();\n        Eigen::SparseMatrix<double> vec_delta_old(vec_delta_);\n\n        for (auto ite = 0; ite < ITERMAX; ite++) {\n            if (full) {\n                calc_meanfields<true>();\n            }\n            else {\n                calc_meanfields<false>();\n            }\n\n            vec_delta_ = vec_delta_ * Chev::U;\n\n            calc_A2();\n\n            auto eps = 0.0;\n            auto nor = 0.0;\n            for (auto i = 0; i < Chev::LN_2; i++) {\n                eps += sqr(vec_delta_.coeff(i, i) - vec_delta_old.coeff(i, i));\n                nor += sqr(vec_delta_old.coeff(i, i));\n            }\n\n            eps /= nor;\n\n            std::cout << \"ite = \" << ite << \", eps = \" << eps << '\\n';\n            if (eps <= Chev::EPSTHRESHOLD) {\n                std::cout << \"End \" << vec_delta_.coeff(Chev::NX / 2, Chev::NY / 2) << std::endl;\n                break;\n            }\n            \n            vec_delta_old = vec_delta_;\n        }\n    }\n\n    // #region public\u30e1\u30f3\u30d0\u95a2\u6570\n\n    // #region private\u30e1\u30f3\u30d0\u95a2\u6570\n\n    void Chev::calc_A()\n    {\n        A_ = Eigen::SparseMatrix<double>(Chev::LN, Chev::LN);\n\n        for (auto ix = 0; ix < Chev::NX; ix++) {\n            for (auto iy = 0; iy < Chev::NY; iy++) {\n                // A_.setdiag(-mu)\n                auto const ii = xy2i(ix, iy);\n                auto jx = ix;\n                auto jy = iy;\n                auto jj = xy2i(jx, jy);\n                A_.coeffRef(ii, jj) = -Chev::MYU;\n\n                // +1 in x direction\n                jx = ix + 1;\n                \n                if (jx == Chev::NX) {\n                    jx = 0;\n                }\n\n                jy = iy;\n                jj = xy2i(jx, jy);\n                A_.coeffRef(ii, jj) = -1.0;\n\n                // -1 in x direction\n                jx = ix - 1;\n\n                if (jx == -1) {\n                    jx = Chev::NX - 1;\n                }\n\n                jy = iy;\n                jj = xy2i(jx, jy);\n                \n                A_.coeffRef(ii, jj) = -1.0;\n\n                // + 1 in y direction\n                jx = ix;\n                jy = iy + 1;\n                \n                if (jy == Chev::NY) {\n                    jy = 0;\n                }\n                \n                jj = xy2i(jx, jy);\n                A_.coeffRef(ii, jj) = -1.0;\n\n                // -1 in y direction\n                jx = ix;\n                jy = iy - 1;\n                if (jy == -1) {\n                    jy = Chev::NY - 1;\n                }\n                jj = xy2i(jx, jy);\n                A_.coeffRef(ii, jj) = -1.0;\n\n                for (auto i = 0; i < Chev::LN_2; i++) {\n                    for (auto j = 0; j < Chev::LN_2; j++) {\n                        A_.coeffRef(i + Chev::LN_2, j + Chev::LN_2) = -A_.coeff(i, j);\n                        A_.coeffRef(i, j + Chev::LN_2) = vec_delta_.coeff(i, j);\n                        A_.coeffRef(i + Chev::LN_2, j) = vec_delta_.coeff(j, i);\n                    }\n                }\n            }\n        }\n\n        A_ /= Chev::AA;\n    }\n\n    void Chev::calc_A2()\n    {\n        A_ *= Chev::AA;\n\n        for (auto i = 0; i < Chev::LN_2; i++) {\n            for (auto j = 0; j < Chev::LN_2; j++) {\n                A_.coeffRef(i, j + Chev::LN_2) = vec_delta_.coeff(i, j);\n                A_.coeffRef(i + Chev::LN_2, j) = vec_delta_.coeff(j, i);\n            }\n        }\n        \n        A_ /= Chev::AA;\n    }\n    \n    double Chev::calc_meanfield() const\n    {\n        auto const ba = std::acos(-Chev::BB / Chev::AA);\n        auto const omeb = std::acos(-(Chev::OMEGAC + Chev::BB) / Chev::AA);\n\n        auto density = 0.0;\n        for (auto j = 0; j < Chev::NC - 1; j++) {\n            auto const i = j + 1;\n            density += vec_ai_[i] * (std::sin(static_cast<double>(i) * omeb) - std::sin(static_cast<double>(i) * ba)) / static_cast<double>(i);\n            density += vec_ai_[0] * (omeb - ba) / 2.0;\n        }\n\n        return density * 2.0 / Chev::PI;\n    }\n\n    void Chev::calc_polynomials(std::int32_t left_i, std::int32_t right_j)\n    {\n        Eigen::VectorXd vec_jn(Chev::LN), vec_jnm(Chev::LN), vec_jnmm(Chev::LN);\n        vec_jn.fill(0.0);\n        vec_jnm.fill(0.0);\n        vec_jnmm.fill(0.0);\n\n        vec_jn.coeffRef(right_j) = 1.0;\n        vec_ai_.fill(0.0);\n\n        auto A = A_.toDense();\n        for (auto n = 0; n < Chev::NC; n++) {\n            switch (n) {\n            case 0:\n                vec_jnm.resize(1);\n                vec_jnm.fill(0.0);\n                vec_jnmm.resize(1);\n                vec_jnmm.fill(0.0);\n                vec_jn.coeffRef(right_j) = 1.0;\n                break;\n\n            case 1:\n                vec_jn = A * vec_jn;\n                break;\n\n            default:\n                vec_jn = 2.0 * A * vec_jnm - vec_jnmm;\n                break;\n            }\n\n            vec_ai_[n] = vec_jn.coeff(left_i);\n            vec_jnmm = vec_jnm;\n            vec_jnm = vec_jn;\n        }\n    }\n\n    void Chev::init_delta()\n    {\n        std::vector<Eigen::Triplet<double>> A(Chev::LN_2);\n        for (auto i = 0; i < Chev::LN_2; i++) {\n            A[i] = Eigen::Triplet<double>(i, i, Chev::DELTA);\n        }\n\n        vec_delta_.setFromTriplets(A.begin(), A.end());\n    }\n\n    std::int32_t Chev::xy2i(std::int32_t ix, std::int32_t iy) const\n    {\n        return iy * Chev::NX + ix;\n    }\n\n    // #endregion private\u30e1\u30f3\u30d0\u95a2\u6570\n}\n", "meta": {"hexsha": "6bb32528a0cc30f3c653f21708dadd285a979704", "size": 6344, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/chebyshevpolynomialbdg/chev.cpp", "max_stars_repo_name": "dc1394/chebyshevpolynomialbdg", "max_stars_repo_head_hexsha": "529e7367ea408b62cb11880970c7fd67a888f3de", "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/chebyshevpolynomialbdg/chev.cpp", "max_issues_repo_name": "dc1394/chebyshevpolynomialbdg", "max_issues_repo_head_hexsha": "529e7367ea408b62cb11880970c7fd67a888f3de", "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/chebyshevpolynomialbdg/chev.cpp", "max_forks_repo_name": "dc1394/chebyshevpolynomialbdg", "max_forks_repo_head_hexsha": "529e7367ea408b62cb11880970c7fd67a888f3de", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4484304933, "max_line_length": 143, "alphanum_fraction": 0.4237074401, "num_tokens": 1894, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.6548947357776796, "lm_q1q2_score": 0.49057327250720784}}
{"text": "// Copyright Michael Drexl 2005, 2006.\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt or copy at \n// http://boost.org/LICENSE_1_0.txt)\n\n#include <boost/config.hpp>\n\n#ifdef BOOST_MSVC\n#  pragma warning(disable: 4267)\n#endif\n\n#include <boost/graph/adjacency_list.hpp>\n//#include <boost/graph/dijkstra_shortest_paths.hpp>\n\n#include <boost/graph/r_c_shortest_paths.hpp>\n#include <iostream>\n#include <boost/test/minimal.hpp>\n\nusing namespace boost;\n\nstruct SPPRC_Example_Graph_Vert_Prop\n{\n  SPPRC_Example_Graph_Vert_Prop( int n = 0, int e = 0, int l = 0 ) \n  : num( n ), eat( e ), lat( l ) {}\n  int num;\n  // earliest arrival time\n  int eat;\n  // latest arrival time\n  int lat;\n};\n\nstruct SPPRC_Example_Graph_Arc_Prop\n{\n  SPPRC_Example_Graph_Arc_Prop( int n = 0, int c = 0, int t = 0 ) \n  : num( n ), cost( c ), time( t ) {}\n  int num;\n  // traversal cost\n  int cost;\n  // traversal time\n  int time;\n};\n\ntypedef adjacency_list<vecS, \n                       vecS, \n                       directedS, \n                       SPPRC_Example_Graph_Vert_Prop, \n                       SPPRC_Example_Graph_Arc_Prop> \n  SPPRC_Example_Graph;\n\n// data structures for spp without resource constraints:\n// ResourceContainer model\nstruct spp_no_rc_res_cont\n{\n  spp_no_rc_res_cont( int c = 0 ) : cost( c ) {};\n  spp_no_rc_res_cont& operator=( const spp_no_rc_res_cont& other )\n  {\n    if( this == &other )\n      return *this;\n    this->~spp_no_rc_res_cont();\n    new( this ) spp_no_rc_res_cont( other );\n    return *this;\n  }\n  int cost;\n};\n\nbool operator==( const spp_no_rc_res_cont& res_cont_1, \n                 const spp_no_rc_res_cont& res_cont_2 )\n{\n  return ( res_cont_1.cost == res_cont_2.cost );\n}\n\nbool operator<( const spp_no_rc_res_cont& res_cont_1, \n                const spp_no_rc_res_cont& res_cont_2 )\n{\n  return ( res_cont_1.cost < res_cont_2.cost );\n}\n\n// ResourceExtensionFunction model\nclass ref_no_res_cont\n{\npublic:\n  inline bool operator()( const SPPRC_Example_Graph& g, \n                          spp_no_rc_res_cont& new_cont, \n                          const spp_no_rc_res_cont& old_cont, \n                          graph_traits\n                            <SPPRC_Example_Graph>::edge_descriptor ed ) const\n  {\n    new_cont.cost = old_cont.cost + g[ed].cost;\n    return true;\n  }\n};\n\n// DominanceFunction model\nclass dominance_no_res_cont\n{\npublic:\n  inline bool operator()( const spp_no_rc_res_cont& res_cont_1, \n                          const spp_no_rc_res_cont& res_cont_2 ) const\n  {\n    // must be \"<=\" here!!!\n    // must NOT be \"<\"!!!\n    return res_cont_1.cost <= res_cont_2.cost;\n    // this is not a contradiction to the documentation\n    // the documentation says:\n    // \"A label $l_1$ dominates a label $l_2$ if and only if both are resident \n    // at the same vertex, and if, for each resource, the resource consumption \n    // of $l_1$ is less than or equal to the resource consumption of $l_2$, \n    // and if there is at least one resource where $l_1$ has a lower resource \n    // consumption than $l_2$.\"\n    // one can think of a new label with a resource consumption equal to that \n    // of an old label as being dominated by that old label, because the new \n    // one will have a higher number and is created at a later point in time, \n    // so one can implicitly use the number or the creation time as a resource \n    // for tie-breaking\n  }\n};\n// end data structures for spp without resource constraints:\n\n// data structures for shortest path problem with time windows (spptw)\n// ResourceContainer model\nstruct spp_spptw_res_cont\n{\n  spp_spptw_res_cont( int c = 0, int t = 0 ) : cost( c ), time( t ) {}\n  spp_spptw_res_cont& operator=( const spp_spptw_res_cont& other )\n  {\n    if( this == &other )\n      return *this;\n    this->~spp_spptw_res_cont();\n    new( this ) spp_spptw_res_cont( other );\n    return *this;\n  }\n  int cost;\n  int time;\n};\n\nbool operator==( const spp_spptw_res_cont& res_cont_1, \n                 const spp_spptw_res_cont& res_cont_2 )\n{\n  return ( res_cont_1.cost == res_cont_2.cost \n           && res_cont_1.time == res_cont_2.time );\n}\n\nbool operator<( const spp_spptw_res_cont& res_cont_1, \n                const spp_spptw_res_cont& res_cont_2 )\n{\n  if( res_cont_1.cost > res_cont_2.cost )\n    return false;\n  if( res_cont_1.cost == res_cont_2.cost )\n    return res_cont_1.time < res_cont_2.time;\n  return true;\n}\n\n// ResourceExtensionFunction model\nclass ref_spptw\n{\npublic:\n  inline bool operator()( const SPPRC_Example_Graph& g, \n                          spp_spptw_res_cont& new_cont, \n                          const spp_spptw_res_cont& old_cont, \n                          graph_traits\n                            <SPPRC_Example_Graph>::edge_descriptor ed ) const\n  {\n    const SPPRC_Example_Graph_Arc_Prop& arc_prop = \n      get( edge_bundle, g )[ed];\n    const SPPRC_Example_Graph_Vert_Prop& vert_prop = \n      get( vertex_bundle, g )[target( ed, g )];\n    new_cont.cost = old_cont.cost + arc_prop.cost;\n    int& i_time = new_cont.time;\n    i_time = old_cont.time + arc_prop.time;\n    i_time < vert_prop.eat ? i_time = vert_prop.eat : 0;\n    return i_time <= vert_prop.lat ? true : false;\n  }\n};\n\n// DominanceFunction model\nclass dominance_spptw\n{\npublic:\n  inline bool operator()( const spp_spptw_res_cont& res_cont_1, \n                          const spp_spptw_res_cont& res_cont_2 ) const\n  {\n    // must be \"<=\" here!!!\n    // must NOT be \"<\"!!!\n    return res_cont_1.cost <= res_cont_2.cost \n           && res_cont_1.time <= res_cont_2.time;\n    // this is not a contradiction to the documentation\n    // the documentation says:\n    // \"A label $l_1$ dominates a label $l_2$ if and only if both are resident \n    // at the same vertex, and if, for each resource, the resource consumption \n    // of $l_1$ is less than or equal to the resource consumption of $l_2$, \n    // and if there is at least one resource where $l_1$ has a lower resource \n    // consumption than $l_2$.\"\n    // one can think of a new label with a resource consumption equal to that \n    // of an old label as being dominated by that old label, because the new \n    // one will have a higher number and is created at a later point in time, \n    // so one can implicitly use the number or the creation time as a resource \n    // for tie-breaking\n  }\n};\n// end data structures for shortest path problem with time windows (spptw)\n\nint test_main(int argc, char* argv[])\n{\n  SPPRC_Example_Graph g;\n  add_vertex( SPPRC_Example_Graph_Vert_Prop( 0, 0, 1000000000 ), g );\n  add_vertex( SPPRC_Example_Graph_Vert_Prop( 1, 56, 142 ), g );\n  add_vertex( SPPRC_Example_Graph_Vert_Prop( 2, 0, 1000000000 ), g );\n  add_vertex( SPPRC_Example_Graph_Vert_Prop( 3, 89, 178 ), g );\n  add_vertex( SPPRC_Example_Graph_Vert_Prop( 4, 0, 1000000000 ), g );\n  add_vertex( SPPRC_Example_Graph_Vert_Prop( 5, 49, 76 ), g );\n  add_vertex( SPPRC_Example_Graph_Vert_Prop( 6, 0, 1000000000 ), g );\n  add_vertex( SPPRC_Example_Graph_Vert_Prop( 7, 98, 160 ), g );\n  add_vertex( SPPRC_Example_Graph_Vert_Prop( 8, 0, 1000000000 ), g );\n  add_vertex( SPPRC_Example_Graph_Vert_Prop( 9, 90, 158 ), g );\n  add_edge( 0, 7, SPPRC_Example_Graph_Arc_Prop( 6, 33, 2 ), g );\n  add_edge( 0, 6, SPPRC_Example_Graph_Arc_Prop( 5, 31, 6 ), g );\n  add_edge( 0, 4, SPPRC_Example_Graph_Arc_Prop( 3, 14, 4 ), g );\n  add_edge( 0, 1, SPPRC_Example_Graph_Arc_Prop( 0, 43, 8 ), g );\n  add_edge( 0, 4, SPPRC_Example_Graph_Arc_Prop( 4, 28, 10 ), g );\n  add_edge( 0, 3, SPPRC_Example_Graph_Arc_Prop( 1, 31, 10 ), g );\n  add_edge( 0, 3, SPPRC_Example_Graph_Arc_Prop( 2, 1, 7 ), g );\n  add_edge( 0, 9, SPPRC_Example_Graph_Arc_Prop( 7, 25, 9 ), g );\n  add_edge( 1, 0, SPPRC_Example_Graph_Arc_Prop( 8, 37, 4 ), g );\n  add_edge( 1, 6, SPPRC_Example_Graph_Arc_Prop( 9, 7, 3 ), g );\n  add_edge( 2, 6, SPPRC_Example_Graph_Arc_Prop( 12, 6, 7 ), g );\n  add_edge( 2, 3, SPPRC_Example_Graph_Arc_Prop( 10, 13, 7 ), g );\n  add_edge( 2, 3, SPPRC_Example_Graph_Arc_Prop( 11, 49, 9 ), g );\n  add_edge( 2, 8, SPPRC_Example_Graph_Arc_Prop( 13, 47, 5 ), g );\n  add_edge( 3, 4, SPPRC_Example_Graph_Arc_Prop( 17, 5, 10 ), g );\n  add_edge( 3, 1, SPPRC_Example_Graph_Arc_Prop( 15, 47, 1 ), g );\n  add_edge( 3, 2, SPPRC_Example_Graph_Arc_Prop( 16, 26, 9 ), g );\n  add_edge( 3, 9, SPPRC_Example_Graph_Arc_Prop( 21, 24, 10 ), g );\n  add_edge( 3, 7, SPPRC_Example_Graph_Arc_Prop( 20, 50, 10 ), g );\n  add_edge( 3, 0, SPPRC_Example_Graph_Arc_Prop( 14, 41, 4 ), g );\n  add_edge( 3, 6, SPPRC_Example_Graph_Arc_Prop( 19, 6, 1 ), g );\n  add_edge( 3, 4, SPPRC_Example_Graph_Arc_Prop( 18, 8, 1 ), g );\n  add_edge( 4, 5, SPPRC_Example_Graph_Arc_Prop( 26, 38, 4 ), g );\n  add_edge( 4, 9, SPPRC_Example_Graph_Arc_Prop( 27, 32, 10 ), g );\n  add_edge( 4, 3, SPPRC_Example_Graph_Arc_Prop( 24, 40, 3 ), g );\n  add_edge( 4, 0, SPPRC_Example_Graph_Arc_Prop( 22, 7, 3 ), g );\n  add_edge( 4, 3, SPPRC_Example_Graph_Arc_Prop( 25, 28, 9 ), g );\n  add_edge( 4, 2, SPPRC_Example_Graph_Arc_Prop( 23, 39, 6 ), g );\n  add_edge( 5, 8, SPPRC_Example_Graph_Arc_Prop( 32, 6, 2 ), g );\n  add_edge( 5, 2, SPPRC_Example_Graph_Arc_Prop( 30, 26, 10 ), g );\n  add_edge( 5, 0, SPPRC_Example_Graph_Arc_Prop( 28, 38, 9 ), g );\n  add_edge( 5, 2, SPPRC_Example_Graph_Arc_Prop( 31, 48, 10 ), g );\n  add_edge( 5, 9, SPPRC_Example_Graph_Arc_Prop( 33, 49, 2 ), g );\n  add_edge( 5, 1, SPPRC_Example_Graph_Arc_Prop( 29, 22, 7 ), g );\n  add_edge( 6, 1, SPPRC_Example_Graph_Arc_Prop( 34, 15, 7 ), g );\n  add_edge( 6, 7, SPPRC_Example_Graph_Arc_Prop( 35, 20, 3 ), g );\n  add_edge( 7, 9, SPPRC_Example_Graph_Arc_Prop( 40, 1, 3 ), g );\n  add_edge( 7, 0, SPPRC_Example_Graph_Arc_Prop( 36, 23, 5 ), g );\n  add_edge( 7, 6, SPPRC_Example_Graph_Arc_Prop( 38, 36, 2 ), g );\n  add_edge( 7, 6, SPPRC_Example_Graph_Arc_Prop( 39, 18, 10 ), g );\n  add_edge( 7, 2, SPPRC_Example_Graph_Arc_Prop( 37, 2, 1 ), g );\n  add_edge( 8, 5, SPPRC_Example_Graph_Arc_Prop( 46, 36, 5 ), g );\n  add_edge( 8, 1, SPPRC_Example_Graph_Arc_Prop( 42, 13, 10 ), g );\n  add_edge( 8, 0, SPPRC_Example_Graph_Arc_Prop( 41, 40, 5 ), g );\n  add_edge( 8, 1, SPPRC_Example_Graph_Arc_Prop( 43, 32, 8 ), g );\n  add_edge( 8, 6, SPPRC_Example_Graph_Arc_Prop( 47, 25, 1 ), g );\n  add_edge( 8, 2, SPPRC_Example_Graph_Arc_Prop( 44, 44, 3 ), g );\n  add_edge( 8, 3, SPPRC_Example_Graph_Arc_Prop( 45, 11, 9 ), g );\n  add_edge( 9, 0, SPPRC_Example_Graph_Arc_Prop( 48, 41, 5 ), g );\n  add_edge( 9, 1, SPPRC_Example_Graph_Arc_Prop( 49, 44, 7 ), g );\n  \n  // spp without resource constraints\n\n  std::vector\n    <std::vector\n      <graph_traits<SPPRC_Example_Graph>::edge_descriptor> > \n        opt_solutions;\n  std::vector<spp_no_rc_res_cont> pareto_opt_rcs_no_rc;\n  std::vector<int> i_vec_opt_solutions_spp_no_rc;\n  //std::cout << \"r_c_shortest_paths:\" << std::endl;\n  for( int s = 0; s < 10; ++s )\n  {\n    for( int t = 0; t < 10; ++t )\n    {\n      r_c_shortest_paths\n      ( g, \n        get( &SPPRC_Example_Graph_Vert_Prop::num, g ), \n        get( &SPPRC_Example_Graph_Arc_Prop::num, g ), \n        s, \n        t, \n        opt_solutions, \n        pareto_opt_rcs_no_rc, \n        spp_no_rc_res_cont( 0 ), \n        ref_no_res_cont(), \n        dominance_no_res_cont(), \n        std::allocator\n          <r_c_shortest_paths_label\n            <SPPRC_Example_Graph, spp_no_rc_res_cont> >(), \n        default_r_c_shortest_paths_visitor() );\n      i_vec_opt_solutions_spp_no_rc.push_back( pareto_opt_rcs_no_rc[0].cost );\n      //std::cout << \"From \" << s << \" to \" << t << \": \";\n      //std::cout << pareto_opt_rcs_no_rc[0].cost << std::endl;\n    }\n  }\n\n  //std::vector<graph_traits<SPPRC_Example_Graph>::vertex_descriptor> \n  //  p( num_vertices( g ) );\n  //std::vector<int> d( num_vertices( g ) );\n  //std::vector<int> i_vec_dijkstra_distances;\n  //std::cout << \"Dijkstra:\" << std::endl;\n  //for( int s = 0; s < 10; ++s )\n  //{\n  //  dijkstra_shortest_paths( g, \n  //                           s, \n  //                           &p[0], \n  //                           &d[0], \n  //                           get( &SPPRC_Example_Graph_Arc_Prop::cost, g ), \n  //                           get( &SPPRC_Example_Graph_Vert_Prop::num, g ), \n  //                           std::less<int>(), \n  //                           closed_plus<int>(), \n  //                           (std::numeric_limits<int>::max)(), \n  //                           0, \n  //                           default_dijkstra_visitor() );\n  //  for( int t = 0; t < 10; ++t )\n  //  {\n  //    i_vec_dijkstra_distances.push_back( d[t] );\n  //    std::cout << \"From \" << s << \" to \" << t << \": \" << d[t] << std::endl;\n  //  }\n  //}\n\n  std::vector<int> i_vec_correct_solutions;\n  i_vec_correct_solutions.push_back( 0 );\n  i_vec_correct_solutions.push_back( 22 );\n  i_vec_correct_solutions.push_back( 27 );\n  i_vec_correct_solutions.push_back( 1 );\n  i_vec_correct_solutions.push_back( 6 );\n  i_vec_correct_solutions.push_back( 44 );\n  i_vec_correct_solutions.push_back( 7 );\n  i_vec_correct_solutions.push_back( 27 );\n  i_vec_correct_solutions.push_back( 50 );\n  i_vec_correct_solutions.push_back( 25 );\n  i_vec_correct_solutions.push_back( 37 );\n  i_vec_correct_solutions.push_back( 0 );\n  i_vec_correct_solutions.push_back( 29 );\n  i_vec_correct_solutions.push_back( 38 );\n  i_vec_correct_solutions.push_back( 43 );\n  i_vec_correct_solutions.push_back( 81 );\n  i_vec_correct_solutions.push_back( 7 );\n  i_vec_correct_solutions.push_back( 27 );\n  i_vec_correct_solutions.push_back( 76 );\n  i_vec_correct_solutions.push_back( 28 );\n  i_vec_correct_solutions.push_back( 25 );\n  i_vec_correct_solutions.push_back( 21 );\n  i_vec_correct_solutions.push_back( 0 );\n  i_vec_correct_solutions.push_back( 13 );\n  i_vec_correct_solutions.push_back( 18 );\n  i_vec_correct_solutions.push_back( 56 );\n  i_vec_correct_solutions.push_back( 6 );\n  i_vec_correct_solutions.push_back( 26 );\n  i_vec_correct_solutions.push_back( 47 );\n  i_vec_correct_solutions.push_back( 27 );\n  i_vec_correct_solutions.push_back( 12 );\n  i_vec_correct_solutions.push_back( 21 );\n  i_vec_correct_solutions.push_back( 26 );\n  i_vec_correct_solutions.push_back( 0 );\n  i_vec_correct_solutions.push_back( 5 );\n  i_vec_correct_solutions.push_back( 43 );\n  i_vec_correct_solutions.push_back( 6 );\n  i_vec_correct_solutions.push_back( 26 );\n  i_vec_correct_solutions.push_back( 49 );\n  i_vec_correct_solutions.push_back( 24 );\n  i_vec_correct_solutions.push_back( 7 );\n  i_vec_correct_solutions.push_back( 29 );\n  i_vec_correct_solutions.push_back( 34 );\n  i_vec_correct_solutions.push_back( 8 );\n  i_vec_correct_solutions.push_back( 0 );\n  i_vec_correct_solutions.push_back( 38 );\n  i_vec_correct_solutions.push_back( 14 );\n  i_vec_correct_solutions.push_back( 34 );\n  i_vec_correct_solutions.push_back( 44 );\n  i_vec_correct_solutions.push_back( 32 );\n  i_vec_correct_solutions.push_back( 29 );\n  i_vec_correct_solutions.push_back( 19 );\n  i_vec_correct_solutions.push_back( 26 );\n  i_vec_correct_solutions.push_back( 17 );\n  i_vec_correct_solutions.push_back( 22 );\n  i_vec_correct_solutions.push_back( 0 );\n  i_vec_correct_solutions.push_back( 23 );\n  i_vec_correct_solutions.push_back( 43 );\n  i_vec_correct_solutions.push_back( 6 );\n  i_vec_correct_solutions.push_back( 41 );\n  i_vec_correct_solutions.push_back( 43 );\n  i_vec_correct_solutions.push_back( 15 );\n  i_vec_correct_solutions.push_back( 22 );\n  i_vec_correct_solutions.push_back( 35 );\n  i_vec_correct_solutions.push_back( 40 );\n  i_vec_correct_solutions.push_back( 78 );\n  i_vec_correct_solutions.push_back( 0 );\n  i_vec_correct_solutions.push_back( 20 );\n  i_vec_correct_solutions.push_back( 69 );\n  i_vec_correct_solutions.push_back( 21 );\n  i_vec_correct_solutions.push_back( 23 );\n  i_vec_correct_solutions.push_back( 23 );\n  i_vec_correct_solutions.push_back( 2 );\n  i_vec_correct_solutions.push_back( 15 );\n  i_vec_correct_solutions.push_back( 20 );\n  i_vec_correct_solutions.push_back( 58 );\n  i_vec_correct_solutions.push_back( 8 );\n  i_vec_correct_solutions.push_back( 0 );\n  i_vec_correct_solutions.push_back( 49 );\n  i_vec_correct_solutions.push_back( 1 );\n  i_vec_correct_solutions.push_back( 23 );\n  i_vec_correct_solutions.push_back( 13 );\n  i_vec_correct_solutions.push_back( 37 );\n  i_vec_correct_solutions.push_back( 11 );\n  i_vec_correct_solutions.push_back( 16 );\n  i_vec_correct_solutions.push_back( 36 );\n  i_vec_correct_solutions.push_back( 17 );\n  i_vec_correct_solutions.push_back( 37 );\n  i_vec_correct_solutions.push_back( 0 );\n  i_vec_correct_solutions.push_back( 35 );\n  i_vec_correct_solutions.push_back( 41 );\n  i_vec_correct_solutions.push_back( 44 );\n  i_vec_correct_solutions.push_back( 68 );\n  i_vec_correct_solutions.push_back( 42 );\n  i_vec_correct_solutions.push_back( 47 );\n  i_vec_correct_solutions.push_back( 85 );\n  i_vec_correct_solutions.push_back( 48 );\n  i_vec_correct_solutions.push_back( 68 );\n  i_vec_correct_solutions.push_back( 91 );\n  i_vec_correct_solutions.push_back( 0 );\n  BOOST_CHECK(i_vec_opt_solutions_spp_no_rc.size() == i_vec_correct_solutions.size() );\n  for( int i = 0; i < static_cast<int>( i_vec_correct_solutions.size() ); ++i )\n    BOOST_CHECK( i_vec_opt_solutions_spp_no_rc[i] == i_vec_correct_solutions[i] );\n\n  // spptw\n  std::vector\n    <std::vector\n      <graph_traits<SPPRC_Example_Graph>::edge_descriptor> > \n        opt_solutions_spptw;\n  std::vector<spp_spptw_res_cont> pareto_opt_rcs_spptw;\n  std::vector\n    <std::vector\n      <std::vector\n        <std::vector\n          <graph_traits<SPPRC_Example_Graph>::edge_descriptor> > > > \n            vec_vec_vec_vec_opt_solutions_spptw( 10 );\n\n  for( int s = 0; s < 10; ++s )\n  {\n    for( int t = 0; t < 10; ++t )\n    {\n      r_c_shortest_paths\n      ( g, \n        get( &SPPRC_Example_Graph_Vert_Prop::num, g ), \n        get( &SPPRC_Example_Graph_Arc_Prop::num, g ), \n        s, \n        t, \n        opt_solutions_spptw, \n        pareto_opt_rcs_spptw, \n        // be careful, do not simply take 0 as initial value for time\n        spp_spptw_res_cont( 0, g[s].eat ), \n        ref_spptw(), \n        dominance_spptw(), \n        std::allocator\n          <r_c_shortest_paths_label\n            <SPPRC_Example_Graph, spp_spptw_res_cont> >(), \n        default_r_c_shortest_paths_visitor() );\n      vec_vec_vec_vec_opt_solutions_spptw[s].push_back( opt_solutions_spptw );\n      if( opt_solutions_spptw.size() )\n      {\n        bool b_is_a_path_at_all = false;\n        bool b_feasible = false; \n        bool b_correctly_extended = false;\n        spp_spptw_res_cont actual_final_resource_levels( 0, 0 );\n        graph_traits<SPPRC_Example_Graph>::edge_descriptor ed_last_extended_arc;\n        check_r_c_path( g, \n                        opt_solutions_spptw[0], \n                        spp_spptw_res_cont( 0, g[s].eat ), \n                        true, \n                        pareto_opt_rcs_spptw[0], \n                        actual_final_resource_levels, \n                        ref_spptw(), \n                        b_is_a_path_at_all, \n                        b_feasible, \n                        b_correctly_extended, \n                        ed_last_extended_arc );\n        BOOST_CHECK(b_is_a_path_at_all && b_feasible && b_correctly_extended);\n        b_is_a_path_at_all = false;\n        b_feasible = false; \n        b_correctly_extended = false;\n        spp_spptw_res_cont actual_final_resource_levels2( 0, 0 );\n        graph_traits<SPPRC_Example_Graph>::edge_descriptor ed_last_extended_arc2;\n        check_r_c_path( g, \n                        opt_solutions_spptw[0], \n                        spp_spptw_res_cont( 0, g[s].eat ), \n                        false, \n                        pareto_opt_rcs_spptw[0], \n                        actual_final_resource_levels2, \n                        ref_spptw(), \n                        b_is_a_path_at_all, \n                        b_feasible, \n                        b_correctly_extended, \n                        ed_last_extended_arc2 );\n        BOOST_CHECK(b_is_a_path_at_all && b_feasible && b_correctly_extended);\n      }\n    }\n  }\n\n  std::vector<int> i_vec_correct_num_solutions_spptw;\n  i_vec_correct_num_solutions_spptw.push_back( 1 );\n  i_vec_correct_num_solutions_spptw.push_back( 2 );\n  i_vec_correct_num_solutions_spptw.push_back( 3 );\n  i_vec_correct_num_solutions_spptw.push_back( 1 );\n  i_vec_correct_num_solutions_spptw.push_back( 3 );\n  i_vec_correct_num_solutions_spptw.push_back( 1 );\n  i_vec_correct_num_solutions_spptw.push_back( 2 );\n  i_vec_correct_num_solutions_spptw.push_back( 1 );\n  i_vec_correct_num_solutions_spptw.push_back( 2 );\n  i_vec_correct_num_solutions_spptw.push_back( 1 );\n  i_vec_correct_num_solutions_spptw.push_back( 1 );\n  i_vec_correct_num_solutions_spptw.push_back( 1 );\n  i_vec_correct_num_solutions_spptw.push_back( 4 );\n  i_vec_correct_num_solutions_spptw.push_back( 1 );\n  i_vec_correct_num_solutions_spptw.push_back( 3 );\n  i_vec_correct_num_solutions_spptw.push_back( 1 );\n  i_vec_correct_num_solutions_spptw.push_back( 1 );\n  i_vec_correct_num_solutions_spptw.push_back( 1 );\n  i_vec_correct_num_solutions_spptw.push_back( 2 );\n  i_vec_correct_num_solutions_spptw.push_back( 2 );\n  i_vec_correct_num_solutions_spptw.push_back( 4 );\n  i_vec_correct_num_solutions_spptw.push_back( 1 );\n  i_vec_correct_num_solutions_spptw.push_back( 1 );\n  i_vec_correct_num_solutions_spptw.push_back( 1 );\n  i_vec_correct_num_solutions_spptw.push_back( 4 );\n  i_vec_correct_num_solutions_spptw.push_back( 1 );\n  i_vec_correct_num_solutions_spptw.push_back( 2 );\n  i_vec_correct_num_solutions_spptw.push_back( 1 );\n  i_vec_correct_num_solutions_spptw.push_back( 1 );\n  i_vec_correct_num_solutions_spptw.push_back( 3 );\n  i_vec_correct_num_solutions_spptw.push_back( 2 );\n  i_vec_correct_num_solutions_spptw.push_back( 2 );\n  i_vec_correct_num_solutions_spptw.push_back( 2 );\n  i_vec_correct_num_solutions_spptw.push_back( 1 );\n  i_vec_correct_num_solutions_spptw.push_back( 2 );\n  i_vec_correct_num_solutions_spptw.push_back( 0 );\n  i_vec_correct_num_solutions_spptw.push_back( 1 );\n  i_vec_correct_num_solutions_spptw.push_back( 1 );\n  i_vec_correct_num_solutions_spptw.push_back( 2 );\n  i_vec_correct_num_solutions_spptw.push_back( 1 );\n  i_vec_correct_num_solutions_spptw.push_back( 1 );\n  i_vec_correct_num_solutions_spptw.push_back( 2 );\n  i_vec_correct_num_solutions_spptw.push_back( 2 );\n  i_vec_correct_num_solutions_spptw.push_back( 1 );\n  i_vec_correct_num_solutions_spptw.push_back( 1 );\n  i_vec_correct_num_solutions_spptw.push_back( 1 );\n  i_vec_correct_num_solutions_spptw.push_back( 2 );\n  i_vec_correct_num_solutions_spptw.push_back( 1 );\n  i_vec_correct_num_solutions_spptw.push_back( 2 );\n  i_vec_correct_num_solutions_spptw.push_back( 1 );\n  i_vec_correct_num_solutions_spptw.push_back( 4 );\n  i_vec_correct_num_solutions_spptw.push_back( 2 );\n  i_vec_correct_num_solutions_spptw.push_back( 2 );\n  i_vec_correct_num_solutions_spptw.push_back( 1 );\n  i_vec_correct_num_solutions_spptw.push_back( 4 );\n  i_vec_correct_num_solutions_spptw.push_back( 1 );\n  i_vec_correct_num_solutions_spptw.push_back( 4 );\n  i_vec_correct_num_solutions_spptw.push_back( 1 );\n  i_vec_correct_num_solutions_spptw.push_back( 1 );\n  i_vec_correct_num_solutions_spptw.push_back( 2 );\n  i_vec_correct_num_solutions_spptw.push_back( 2 );\n  i_vec_correct_num_solutions_spptw.push_back( 1 );\n  i_vec_correct_num_solutions_spptw.push_back( 4 );\n  i_vec_correct_num_solutions_spptw.push_back( 2 );\n  i_vec_correct_num_solutions_spptw.push_back( 5 );\n  i_vec_correct_num_solutions_spptw.push_back( 1 );\n  i_vec_correct_num_solutions_spptw.push_back( 1 );\n  i_vec_correct_num_solutions_spptw.push_back( 1 );\n  i_vec_correct_num_solutions_spptw.push_back( 2 );\n  i_vec_correct_num_solutions_spptw.push_back( 2 );\n  i_vec_correct_num_solutions_spptw.push_back( 1 );\n  i_vec_correct_num_solutions_spptw.push_back( 3 );\n  i_vec_correct_num_solutions_spptw.push_back( 1 );\n  i_vec_correct_num_solutions_spptw.push_back( 1 );\n  i_vec_correct_num_solutions_spptw.push_back( 2 );\n  i_vec_correct_num_solutions_spptw.push_back( 0 );\n  i_vec_correct_num_solutions_spptw.push_back( 2 );\n  i_vec_correct_num_solutions_spptw.push_back( 1 );\n  i_vec_correct_num_solutions_spptw.push_back( 1 );\n  i_vec_correct_num_solutions_spptw.push_back( 1 );\n  i_vec_correct_num_solutions_spptw.push_back( 3 );\n  i_vec_correct_num_solutions_spptw.push_back( 1 );\n  i_vec_correct_num_solutions_spptw.push_back( 2 );\n  i_vec_correct_num_solutions_spptw.push_back( 1 );\n  i_vec_correct_num_solutions_spptw.push_back( 3 );\n  i_vec_correct_num_solutions_spptw.push_back( 1 );\n  i_vec_correct_num_solutions_spptw.push_back( 3 );\n  i_vec_correct_num_solutions_spptw.push_back( 1 );\n  i_vec_correct_num_solutions_spptw.push_back( 1 );\n  i_vec_correct_num_solutions_spptw.push_back( 2 );\n  i_vec_correct_num_solutions_spptw.push_back( 1 );\n  i_vec_correct_num_solutions_spptw.push_back( 1 );\n  i_vec_correct_num_solutions_spptw.push_back( 4 );\n  i_vec_correct_num_solutions_spptw.push_back( 1 );\n  i_vec_correct_num_solutions_spptw.push_back( 3 );\n  i_vec_correct_num_solutions_spptw.push_back( 0 );\n  i_vec_correct_num_solutions_spptw.push_back( 2 );\n  i_vec_correct_num_solutions_spptw.push_back( 3 );\n  i_vec_correct_num_solutions_spptw.push_back( 4 );\n  i_vec_correct_num_solutions_spptw.push_back( 1 );\n  for( int s = 0; s < 10; ++s )\n    for( int t = 0; t < 10; ++t )\n      BOOST_CHECK( static_cast<int>\n            ( vec_vec_vec_vec_opt_solutions_spptw[s][t].size() ) == \n                   i_vec_correct_num_solutions_spptw[10 * s + t] );\n\n  // one pareto-optimal solution\n  SPPRC_Example_Graph g2;\n  add_vertex( SPPRC_Example_Graph_Vert_Prop( 0, 0, 1000000000 ), g2 );\n  add_vertex( SPPRC_Example_Graph_Vert_Prop( 1, 0, 1000000000 ), g2 );\n  add_vertex( SPPRC_Example_Graph_Vert_Prop( 2, 0, 1000000000 ), g2 );\n  add_vertex( SPPRC_Example_Graph_Vert_Prop( 3, 0, 1000000000 ), g2 );\n  add_edge( 0, 1, SPPRC_Example_Graph_Arc_Prop( 0, 1, 1 ), g2 );\n  add_edge( 0, 2, SPPRC_Example_Graph_Arc_Prop( 1, 2, 1 ), g2 );\n  add_edge( 1, 3, SPPRC_Example_Graph_Arc_Prop( 2, 3, 1 ), g2 );\n  add_edge( 2, 3, SPPRC_Example_Graph_Arc_Prop( 3, 1, 1 ), g2 );\n  std::vector<graph_traits<SPPRC_Example_Graph>::edge_descriptor> opt_solution;\n  spp_spptw_res_cont pareto_opt_rc;\n  r_c_shortest_paths( g2, \n                      get( &SPPRC_Example_Graph_Vert_Prop::num, g2 ), \n                      get( &SPPRC_Example_Graph_Arc_Prop::num, g2 ), \n                      0, \n                      3, \n                      opt_solution, \n                      pareto_opt_rc, \n                      spp_spptw_res_cont( 0, 0 ), \n                      ref_spptw(), \n                      dominance_spptw(), \n                      std::allocator\n                        <r_c_shortest_paths_label\n                          <SPPRC_Example_Graph, spp_spptw_res_cont> >(), \n                      default_r_c_shortest_paths_visitor() );\n\n  BOOST_CHECK(pareto_opt_rc.cost == 3);\n\n  return 0;\n}\n", "meta": {"hexsha": "8459eb0af01c1115c05ab8f8da79cf6ca59c06f5", "size": 26897, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/graph/test/r_c_shortest_paths_test.cpp", "max_stars_repo_name": "mike-code/boost_1_38_0", "max_stars_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-07-31T02:19:48.000Z", "max_stars_repo_stars_event_max_datetime": "2017-07-31T02:19:48.000Z", "max_issues_repo_path": "libs/graph/test/r_c_shortest_paths_test.cpp", "max_issues_repo_name": "boost-cmake/vintage", "max_issues_repo_head_hexsha": "dcfb7da3177134eddaee6789d6f582259cb0d6ee", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/graph/test/r_c_shortest_paths_test.cpp", "max_forks_repo_name": "boost-cmake/vintage", "max_forks_repo_head_hexsha": "dcfb7da3177134eddaee6789d6f582259cb0d6ee", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-07T05:20:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-07T05:20:43.000Z", "avg_line_length": 41.8956386293, "max_line_length": 87, "alphanum_fraction": 0.6871026509, "num_tokens": 8528, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.4905732725072078}}
{"text": "// Boost.Geometry\n\n// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.\n\n// This file was modified by Oracle on 2014, 2016, 2017.\n// Modifications copyright (c) 2014-2017 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_FORMULAS_VINCENTY_INVERSE_HPP\n#define BOOST_GEOMETRY_FORMULAS_VINCENTY_INVERSE_HPP\n\n\n#include <boost/math/constants/constants.hpp>\n\n#include <boost/geometry/core/radius.hpp>\n#include <boost/geometry/core/srs.hpp>\n\n#include <boost/geometry/util/condition.hpp>\n#include <boost/geometry/util/math.hpp>\n\n#include <boost/geometry/formulas/differential_quantities.hpp>\n#include <boost/geometry/formulas/flattening.hpp>\n#include <boost/geometry/formulas/result_inverse.hpp>\n\n\n#ifndef BOOST_GEOMETRY_DETAIL_VINCENTY_MAX_STEPS\n#define BOOST_GEOMETRY_DETAIL_VINCENTY_MAX_STEPS 1000\n#endif\n\n\nnamespace boost { namespace geometry { namespace formula\n{\n\n/*!\n\\brief The solution of the inverse problem of geodesics on latlong coordinates, after Vincenty, 1975\n\\author See\n    - http://www.ngs.noaa.gov/PUBS_LIB/inverse.pdf\n    - http://www.icsm.gov.au/gda/gda-v_2.4.pdf\n\\author Adapted from various implementations to get it close to the original document\n    - http://www.movable-type.co.uk/scripts/LatLongVincenty.html\n    - http://exogen.case.edu/projects/geopy/source/geopy.distance.html\n    - http://futureboy.homeip.net/fsp/colorize.fsp?fileName=navigation.frink\n\n*/\ntemplate <\n    typename CT,\n    bool EnableDistance,\n    bool EnableAzimuth,\n    bool EnableReverseAzimuth = false,\n    bool EnableReducedLength = false,\n    bool EnableGeodesicScale = false\n>\nstruct vincenty_inverse\n{\n    static const bool CalcQuantities = EnableReducedLength || EnableGeodesicScale;\n    static const bool CalcAzimuths = EnableAzimuth || EnableReverseAzimuth || CalcQuantities;\n    static const bool CalcFwdAzimuth = EnableAzimuth || CalcQuantities;\n    static const bool CalcRevAzimuth = EnableReverseAzimuth || CalcQuantities;\n\npublic:\n    typedef result_inverse<CT> result_type;\n\n    template <typename T1, typename T2, typename Spheroid>\n    static inline result_type apply(T1 const& lon1,\n                                    T1 const& lat1,\n                                    T2 const& lon2,\n                                    T2 const& lat2,\n                                    Spheroid const& spheroid)\n    {\n        result_type result;\n\n        if (math::equals(lat1, lat2) && math::equals(lon1, lon2))\n        {\n            return result;\n        }\n\n        CT const c1 = 1;\n        CT const c2 = 2;\n        CT const c3 = 3;\n        CT const c4 = 4;\n        CT const c16 = 16;\n        CT const c_e_12 = CT(1e-12);\n\n        CT const pi = geometry::math::pi<CT>();\n        CT const two_pi = c2 * pi;\n\n        // lambda: difference in longitude on an auxiliary sphere\n        CT L = lon2 - lon1;\n        CT lambda = L;\n\n        if (L < -pi) L += two_pi;\n        if (L > pi) L -= two_pi;\n\n        CT const radius_a = CT(get_radius<0>(spheroid));\n        CT const radius_b = CT(get_radius<2>(spheroid));\n        CT const f = formula::flattening<CT>(spheroid);\n\n        // U: reduced latitude, defined by tan U = (1-f) tan phi\n        CT const one_min_f = c1 - f;\n        CT const tan_U1 = one_min_f * tan(lat1); // above (1)\n        CT const tan_U2 = one_min_f * tan(lat2); // above (1)\n\n        // calculate sin U and cos U using trigonometric identities\n        CT const temp_den_U1 = math::sqrt(c1 + math::sqr(tan_U1));\n        CT const temp_den_U2 = math::sqrt(c1 + math::sqr(tan_U2));\n        // cos = 1 / sqrt(1 + tan^2)\n        CT const cos_U1 = c1 / temp_den_U1;\n        CT const cos_U2 = c1 / temp_den_U2;\n        // sin = tan / sqrt(1 + tan^2)\n        // sin = tan * cos\n        CT const sin_U1 = tan_U1 * cos_U1;\n        CT const sin_U2 = tan_U2 * cos_U2;\n\n        // calculate sin U and cos U directly\n        //CT const U1 = atan(tan_U1);\n        //CT const U2 = atan(tan_U2);\n        //cos_U1 = cos(U1);\n        //cos_U2 = cos(U2);\n        //sin_U1 = tan_U1 * cos_U1; // sin(U1);\n        //sin_U2 = tan_U2 * cos_U2; // sin(U2);\n\n        CT previous_lambda;\n        CT sin_lambda;\n        CT cos_lambda;\n        CT sin_sigma;\n        CT sin_alpha;\n        CT cos2_alpha;\n        CT cos_2sigma_m;\n        CT cos2_2sigma_m;\n        CT sigma;\n\n        int counter = 0; // robustness\n\n        do\n        {\n            previous_lambda = lambda; // (13)\n            sin_lambda = sin(lambda);\n            cos_lambda = cos(lambda);\n            sin_sigma = math::sqrt(math::sqr(cos_U2 * sin_lambda) + math::sqr(cos_U1 * sin_U2 - sin_U1 * cos_U2 * cos_lambda)); // (14)\n            CT cos_sigma = sin_U1 * sin_U2 + cos_U1 * cos_U2 * cos_lambda; // (15)\n            sin_alpha = cos_U1 * cos_U2 * sin_lambda / sin_sigma; // (17)\n            cos2_alpha = c1 - math::sqr(sin_alpha);\n            cos_2sigma_m = math::equals(cos2_alpha, 0) ? 0 : cos_sigma - c2 * sin_U1 * sin_U2 / cos2_alpha; // (18)\n            cos2_2sigma_m = math::sqr(cos_2sigma_m);\n\n            CT C = f/c16 * cos2_alpha * (c4 + f * (c4 - c3 * cos2_alpha)); // (10)\n            sigma = atan2(sin_sigma, cos_sigma); // (16)\n            lambda = L + (c1 - C) * f * sin_alpha *\n                (sigma + C * sin_sigma * (cos_2sigma_m + C * cos_sigma * (-c1 + c2 * cos2_2sigma_m))); // (11)\n\n            ++counter; // robustness\n\n        } while ( geometry::math::abs(previous_lambda - lambda) > c_e_12\n               && geometry::math::abs(lambda) < pi\n               && counter < BOOST_GEOMETRY_DETAIL_VINCENTY_MAX_STEPS ); // robustness\n\n        if ( BOOST_GEOMETRY_CONDITION(EnableDistance) )\n        {\n            // Oops getting hard here\n            // (again, problem is that ttmath cannot divide by doubles, which is OK)\n            CT const c1 = 1;\n            CT const c2 = 2;\n            CT const c3 = 3;\n            CT const c4 = 4;\n            CT const c6 = 6;\n            CT const c47 = 47;\n            CT const c74 = 74;\n            CT const c128 = 128;\n            CT const c256 = 256;\n            CT const c175 = 175;\n            CT const c320 = 320;\n            CT const c768 = 768;\n            CT const c1024 = 1024;\n            CT const c4096 = 4096;\n            CT const c16384 = 16384;\n\n            //CT sqr_u = cos2_alpha * (math::sqr(radius_a) - math::sqr(radius_b)) / math::sqr(radius_b); // above (1)\n            CT sqr_u = cos2_alpha * ( math::sqr(radius_a / radius_b) - c1 ); // above (1)\n\n            CT A = c1 + sqr_u/c16384 * (c4096 + sqr_u * (-c768 + sqr_u * (c320 - c175 * sqr_u))); // (3)\n            CT B = sqr_u/c1024 * (c256 + sqr_u * ( -c128 + sqr_u * (c74 - c47 * sqr_u))); // (4)\n            CT const cos_sigma = cos(sigma);\n            CT const sin2_sigma = math::sqr(sin_sigma);\n            CT delta_sigma = B * sin_sigma * (cos_2sigma_m + (B/c4) * (cos_sigma* (-c1 + c2 * cos2_2sigma_m)\n                - (B/c6) * cos_2sigma_m * (-c3 + c4 * sin2_sigma) * (-c3 + c4 * cos2_2sigma_m))); // (6)\n\n            result.distance = radius_b * A * (sigma - delta_sigma); // (19)\n        }\n\n        if ( BOOST_GEOMETRY_CONDITION(CalcAzimuths) )\n        {\n            if (BOOST_GEOMETRY_CONDITION(CalcFwdAzimuth))\n            {\n                result.azimuth = atan2(cos_U2 * sin_lambda, cos_U1 * sin_U2 - sin_U1 * cos_U2 * cos_lambda); // (20)\n            }\n\n            if (BOOST_GEOMETRY_CONDITION(CalcRevAzimuth))\n            {\n                result.reverse_azimuth = atan2(cos_U1 * sin_lambda, -sin_U1 * cos_U2 + cos_U1 * sin_U2 * cos_lambda); // (21)\n            }\n        }\n\n        if (BOOST_GEOMETRY_CONDITION(CalcQuantities))\n        {\n            typedef differential_quantities<CT, EnableReducedLength, EnableGeodesicScale, 2> quantities;\n            quantities::apply(lon1, lat1, lon2, lat2,\n                              result.azimuth, result.reverse_azimuth,\n                              radius_b, f,\n                              result.reduced_length, result.geodesic_scale);\n        }\n\n        return result;\n    }\n};\n\n}}} // namespace boost::geometry::formula\n\n\n#endif // BOOST_GEOMETRY_FORMULAS_VINCENTY_INVERSE_HPP\n", "meta": {"hexsha": "66d8e500c53602caf34b896eb4b6d8cb969a1cf0", "size": 8321, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/src/boost_1_65_1/boost/geometry/formulas/vincenty_inverse.hpp", "max_stars_repo_name": "shreyasvj25/turicreate", "max_stars_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-12-15T20:03:51.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-15T20:03:51.000Z", "max_issues_repo_path": "deps/src/boost_1_65_1/boost/geometry/formulas/vincenty_inverse.hpp", "max_issues_repo_name": "shreyasvj25/turicreate", "max_issues_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-09-08T02:18:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T00:39:44.000Z", "max_forks_repo_path": "deps/src/boost_1_65_1/boost/geometry/formulas/vincenty_inverse.hpp", "max_forks_repo_name": "shreyasvj25/turicreate", "max_forks_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-06-01T18:49:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-01T18:49:28.000Z", "avg_line_length": 36.9822222222, "max_line_length": 135, "alphanum_fraction": 0.5894724192, "num_tokens": 2310, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.6548947290421276, "lm_q1q2_score": 0.490573267461692}}
{"text": "#include <boost/test/unit_test.hpp>\n\n#include <iostream>\n#include <boost/graph/directed_graph.hpp> /** Boost directed graph **/\n#include <boost/graph/labeled_graph.hpp> /** Boost directed graph **/\n#include <boost/uuid/uuid.hpp> /** uuid class */\n#include <boost/uuid/uuid_generators.hpp>\n\nBOOST_AUTO_TEST_CASE(dummy_graph_test)\n{\n\n    typedef boost::directed_graph<boost::no_property> Graph;\n\n    // Create a graph object\n    Graph g;\n\n    // Add vertices\n    Graph::vertex_descriptor v0 = g.add_vertex();\n    Graph::vertex_descriptor v1 = g.add_vertex();\n    Graph::vertex_descriptor v2 = g.add_vertex();\n    std::cout<<\"v0: \"<<v0<<\"\\n\";\n    std::cout<<\"v1: \"<<v1<<\"\\n\";\n    std::cout<<\"v2: \"<<v2<<\"\\n\";\n\n    std::cout << \"There are \" << g.num_vertices() << \" vertices.\" << std::endl;\n    Graph::vertex_descriptor u0 = boost::vertex(0, g);\n    std::cout<<\"u0: \"<<u0<<\"\\n\";\n    g.remove_vertex(v0);\n    std::cout << \"There are \" << g.num_vertices() << \" vertices.\" << std::endl;\n    u0 = boost::vertex(0, g);\n    std::cout<<\"u0: \"<<u0<<\"\\n\";\n    Graph::vertex_descriptor u1 = boost::vertex(1, g);\n    std::cout<<\"u1: \"<<u1<<\"\\n\";\n    Graph::vertex_descriptor u2 = boost::vertex(2, g);\n    std::cout<<\"u2: \"<<u2<<\"\\n\";\n\n    typedef boost::labeled_graph< Graph, boost::uuids::uuid > LabeledGraph;\n\n    LabeledGraph lg;\n\n    // Add vertices\n    boost::uuids::uuid id = boost::uuids::random_generator()();\n    LabeledGraph::vertex_descriptor lv0 = boost::add_vertex(id, lg);\n    LabeledGraph::vertex_descriptor lv1 = boost::add_vertex(boost::uuids::random_generator()(), lg);\n    LabeledGraph::vertex_descriptor lv2 = boost::add_vertex(boost::uuids::random_generator()(), lg);\n    std::cout<<\"\\nlv0: \"<<lv0<<\"\\n\";\n    std::cout<<\"lv1: \"<<lv1<<\"\\n\";\n    std::cout<<\"lv2: \"<<lv2<<\"\\n\";\n\n    std::cout << \"There are \" << boost::num_vertices(lg) << \" vertices.\" << std::endl;\n    LabeledGraph::vertex_descriptor lu0 = boost::vertex_by_label(id, lg);\n    std::cout<<\"lu0: \"<<lu0<<\"\\n\";\n\n}\n\n//#include <boost/graph/dijkstra_shortest_paths.hpp>\n//    std::vector<double> distances(num_vertices(envire_tree.tree));\n//    boost::dijkstra_shortest_paths(envire_tree.tree, root,\n//      boost::weight_map(boost::get(&envire::core::Edge::idx, envire_tree.tree))\n//      .distance_map(boost::make_iterator_property_map(distances.begin(),\n//                                               boost::get(boost::vertex_index, envire_tree.tree))));\n\n    //property accessors\n//    boost::property_map<envire::core::Tree::Graph, int>::type edgeIdx = boost::get(&envire::core::Edge::idx, envire_tree);\n\n   // printDependencies(std::cout, envire_tree, boost::get(boost::vertex_index, envire_tree));\n\n\ntemplate < typename _Graph, typename _VertexNameMap > void\nprintDependencies(std::ostream & out, const _Graph & g,\n                   _VertexNameMap name_map)\n{\n  typename boost::graph_traits < _Graph >::edge_iterator ei, ei_end;\n  for (boost::tie(ei, ei_end) = edges(g); ei != ei_end; ++ei)\n    out << boost::get(name_map, boost::source(*ei, g)) << \" -$>$ \"\n      << boost::get(name_map, boost::target(*ei, g)) << std::endl;\n}\n\n", "meta": {"hexsha": "0522649ae7028671cbe7c662276030f32eeb5445", "size": 3103, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_dummy_graph.cpp", "max_stars_repo_name": "jhidalgocarrio/slam-envire_core", "max_stars_repo_head_hexsha": "4a1bc6b458989e39e4f16cab80777fdbb76cbff3", "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": "test/test_dummy_graph.cpp", "max_issues_repo_name": "jhidalgocarrio/slam-envire_core", "max_issues_repo_head_hexsha": "4a1bc6b458989e39e4f16cab80777fdbb76cbff3", "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": "test/test_dummy_graph.cpp", "max_forks_repo_name": "jhidalgocarrio/slam-envire_core", "max_forks_repo_head_hexsha": "4a1bc6b458989e39e4f16cab80777fdbb76cbff3", "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.2784810127, "max_line_length": 124, "alphanum_fraction": 0.6345472124, "num_tokens": 860, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.749087201911703, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.4905732601248902}}
{"text": "#include <omp.h>\n#include <chrono>\n#include <queue>\n#include <thread>\n\n#include <Eigen/StdVector>\n#include <ceres/ceres.h>\n#include <glog/logging.h>\n\n#include \"ct_icp.hpp\"\n#include \"cost_functions.h\"\n\n#ifdef CT_ICP_WITH_VIZ\n\n#include \"utils.hpp\"\n\n#include <viz3d/engine.hpp>\n#include <colormap/colormap.hpp>\n#include <colormap/color.hpp>\n\n#endif\nnamespace ct_icp {\n\n    /* -------------------------------------------------------------------------------------------------------------- */\n    // Subsample to keep one random point in every voxel of the current frame\n    void sub_sample_frame(std::vector<Point3D> &frame, double size_voxel) {\n        std::unordered_map<Voxel, std::vector<Point3D>> grid;\n        for (int i = 0; i < (int) frame.size(); i++) {\n            auto kx = static_cast<short>(frame[i].pt[0] / size_voxel);\n            auto ky = static_cast<short>(frame[i].pt[1] / size_voxel);\n            auto kz = static_cast<short>(frame[i].pt[2] / size_voxel);\n            grid[Voxel(kx, ky, kz)].push_back(frame[i]);\n        }\n        frame.resize(0);\n        int step = 0; //to take one random point inside each voxel (but with identical results when lunching the SLAM a second time)\n        for (const auto &n: grid) {\n            if (n.second.size() > 0) {\n                //frame.push_back(n.second[step % (int)n.second.size()]);\n                frame.push_back(n.second[0]);\n                step++;\n            }\n        }\n    }\n\n    /* -------------------------------------------------------------------------------------------------------------- */\n    void\n    grid_sampling(const std::vector<Point3D> &frame, std::vector<Point3D> &keypoints, double size_voxel_subsampling) {\n        // TODO Replace std::list by a vector ?\n        keypoints.resize(0);\n        std::vector<Point3D> frame_sub;\n        frame_sub.resize(frame.size());\n        for (int i = 0; i < (int) frame_sub.size(); i++) {\n            frame_sub[i] = frame[i];\n        }\n        sub_sample_frame(frame_sub, size_voxel_subsampling);\n        keypoints.reserve(frame_sub.size());\n        for (int i = 0; i < (int) frame_sub.size(); i++) {\n            keypoints.push_back(frame_sub[i]);\n        }\n    }\n\n    /* -------------------------------------------------------------------------------------------------------------- */\n\n    struct Neighborhood {\n        EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n        Eigen::Vector3d center = Eigen::Vector3d::Zero();\n\n        Eigen::Vector3d normal = Eigen::Vector3d::Zero();\n\n        Eigen::Matrix3d covariance = Eigen::Matrix3d::Identity();\n\n        double a2D = 1.0; // Planarity coefficient\n    };\n\n    // Computes normal and planarity coefficient\n    Neighborhood compute_neighborhood_distribution(const ArrayVector3d &points) {\n        Neighborhood neighborhood;\n        // Compute the normals\n        Eigen::Vector3d barycenter(Eigen::Vector3d(0, 0, 0));\n        for (auto &point: points) {\n            barycenter += point;\n        }\n        barycenter /= (double) points.size();\n        neighborhood.center = barycenter;\n\n        Eigen::Matrix3d covariance_Matrix(Eigen::Matrix3d::Zero());\n        for (auto &point: points) {\n            for (int k = 0; k < 3; ++k)\n                for (int l = k; l < 3; ++l)\n                    covariance_Matrix(k, l) += (point(k) - barycenter(k)) *\n                                               (point(l) - barycenter(l));\n        }\n        covariance_Matrix(1, 0) = covariance_Matrix(0, 1);\n        covariance_Matrix(2, 0) = covariance_Matrix(0, 2);\n        covariance_Matrix(2, 1) = covariance_Matrix(1, 2);\n        neighborhood.covariance = covariance_Matrix;\n        Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> es(covariance_Matrix);\n        Eigen::Vector3d normal(es.eigenvectors().col(0).normalized());\n        neighborhood.normal = normal;\n\n        // Compute planarity from the eigen values\n        double sigma_1 = sqrt(std::abs(\n                es.eigenvalues()[2])); //Be careful, the eigenvalues are not correct with the iterative way to compute the covariance matrix\n        double sigma_2 = sqrt(std::abs(es.eigenvalues()[1]));\n        double sigma_3 = sqrt(std::abs(es.eigenvalues()[0]));\n        neighborhood.a2D = (sigma_2 - sigma_3) / sigma_1;\n\n        if (neighborhood.a2D != neighborhood.a2D) {\n            LOG(ERROR) << \"FOUND NAN!!!\";\n            throw std::runtime_error(\"error\");\n        }\n\n        return neighborhood;\n    }\n\n\n    /* -------------------------------------------------------------------------------------------------------------- */\n    // Search Neighbors with VoxelHashMap lookups\n    using pair_distance_t = std::tuple<double, Eigen::Vector3d, Voxel>;\n\n    struct Comparator {\n        bool operator()(const pair_distance_t &left, const pair_distance_t &right) const {\n            return std::get<0>(left) < std::get<0>(right);\n        }\n    };\n\n    using priority_queue_t = std::priority_queue<pair_distance_t, std::vector<pair_distance_t>, Comparator>;\n\n    inline ArrayVector3d\n    search_neighbors(const VoxelHashMap &map,\n                     const Eigen::Vector3d &point,\n                     int nb_voxels_visited,\n                     double size_voxel_map,\n                     int max_num_neighbors,\n                     int threshold_voxel_capacity = 1,\n                     std::vector<Voxel> *voxels = nullptr) {\n\n        if (voxels != nullptr)\n            voxels->reserve(max_num_neighbors);\n\n        short kx = static_cast<short>(point[0] / size_voxel_map);\n        short ky = static_cast<short>(point[1] / size_voxel_map);\n        short kz = static_cast<short>(point[2] / size_voxel_map);\n\n        priority_queue_t priority_queue;\n\n        Voxel voxel(kx, ky, kz);\n        for (short kxx = kx - nb_voxels_visited; kxx < kx + nb_voxels_visited + 1; ++kxx) {\n            for (short kyy = ky - nb_voxels_visited; kyy < ky + nb_voxels_visited + 1; ++kyy) {\n                for (short kzz = kz - nb_voxels_visited; kzz < kz + nb_voxels_visited + 1; ++kzz) {\n                    voxel.x = kxx;\n                    voxel.y = kyy;\n                    voxel.z = kzz;\n\n                    auto search = map.find(voxel);\n                    if (search != map.end()) {\n                        const auto &voxel_block = search.value();\n                        if (voxel_block.NumPoints() < threshold_voxel_capacity)\n                            continue;\n                        for (int i(0); i < voxel_block.NumPoints(); ++i) {\n                            auto &neighbor = voxel_block.points[i];\n                            double distance = (neighbor - point).norm();\n                            if (priority_queue.size() == max_num_neighbors) {\n                                if (distance < std::get<0>(priority_queue.top())) {\n                                    priority_queue.pop();\n                                    priority_queue.emplace(distance, neighbor, voxel);\n                                }\n                            } else\n                                priority_queue.emplace(distance, neighbor, voxel);\n                        }\n                    }\n                }\n            }\n        }\n\n        auto size = priority_queue.size();\n        ArrayVector3d closest_neighbors(size);\n        if (voxels != nullptr) {\n            voxels->resize(size);\n        }\n        for (auto i = 0; i < size; ++i) {\n            closest_neighbors[size - 1 - i] = std::get<1>(priority_queue.top());\n            if (voxels != nullptr)\n                (*voxels)[size - 1 - i] = std::get<2>(priority_queue.top());\n            priority_queue.pop();\n        }\n\n\n        return closest_neighbors;\n    }\n\n    /* -------------------------------------------------------------------------------------------------------------- */\n    inline ArrayVector3d\n    select_closest_neighbors(const std::vector<std::vector<Eigen::Vector3d> const *> &neighbors_ptr,\n                             const Eigen::Vector3d &pt_keypoint,\n                             int num_neighbors, int max_num_neighbors) {\n        std::vector<std::pair<double, Eigen::Vector3d>> distance_neighbors;\n        distance_neighbors.reserve(neighbors_ptr.size());\n        for (auto &it_ptr: neighbors_ptr) {\n            for (auto &it: *it_ptr) {\n                double sq_dist = (pt_keypoint - it).squaredNorm();\n                distance_neighbors.emplace_back(sq_dist, it);\n            }\n        }\n\n\n        int real_number_neighbors = std::min(max_num_neighbors, (int) distance_neighbors.size());\n        std::partial_sort(distance_neighbors.begin(),\n                          distance_neighbors.begin() + real_number_neighbors,\n                          distance_neighbors.end(),\n                          [](const std::pair<double, Eigen::Vector3d> &left,\n                             const std::pair<double, Eigen::Vector3d> &right) {\n                              return left.first < right.first;\n                          });\n\n        ArrayVector3d neighbors(real_number_neighbors);\n        for (auto i(0); i < real_number_neighbors; ++i)\n            neighbors[i] = distance_neighbors[i].second;\n        return neighbors;\n    }\n\n\n    /* -------------------------------------------------------------------------------------------------------------- */\n\n    // A Builder to abstract the different configurations of ICP optimization\n    class ICPOptimizationBuilder {\n    public:\n        using CTICP_PointToPlaneResidual = ceres::AutoDiffCostFunction<CTPointToPlaneFunctor, 1, 4, 3, 4, 3>;\n        using PointToPlaneResidual = ceres::AutoDiffCostFunction<PointToPlaneFunctor, 1, 4, 3>;\n\n        explicit ICPOptimizationBuilder(const CTICPOptions *options,\n                                        const std::vector<Point3D> *points) :\n                options_(options),\n                keypoints(points) {\n            corrected_raw_points_.resize(keypoints->size());\n            for (int i(0); i < points->size(); ++i)\n                corrected_raw_points_[i] = (*points)[i].raw_pt;\n\n            max_num_residuals_ = options->max_num_residuals;\n        }\n\n        bool InitProblem(int num_residuals) {\n            problem = std::make_unique<ceres::Problem>();\n            parameter_block_set_ = false;\n\n            // Select Loss function\n            switch (options_->loss_function) {\n                case LEAST_SQUARES::STANDARD:\n                    break;\n                case LEAST_SQUARES::CAUCHY:\n                    loss_function = new ceres::CauchyLoss(options_->ls_sigma);\n                    break;\n                case LEAST_SQUARES::HUBER:\n                    loss_function = new ceres::HuberLoss(options_->ls_sigma);\n                    break;\n                case LEAST_SQUARES::TOLERANT:\n                    loss_function = new ceres::TolerantLoss(options_->ls_tolerant_min_threshold,\n                                                            options_->ls_sigma);\n                    break;\n                case LEAST_SQUARES::TRUNCATED:\n                    loss_function = new ct_icp::TruncatedLoss(options_->ls_sigma);\n                    break;\n            }\n\n            // Resize the number of residuals\n            vector_ct_icp_residuals_.resize(num_residuals);\n            vector_cost_functors_.resize(num_residuals);\n            begin_quat_ = nullptr;\n            end_quat_ = nullptr;\n            begin_t_ = nullptr;\n            end_t_ = nullptr;\n\n            return true;\n        }\n\n        void DistortFrame(Eigen::Quaterniond &begin_quat, Eigen::Quaterniond &end_quat,\n                          Eigen::Vector3d &begin_t, Eigen::Vector3d &end_t) {\n            if (options_->distance == POINT_TO_PLANE) {\n                // Distorts the frame (put all raw_points in the coordinate frame of the pose at the end of the acquisition)\n                Eigen::Quaterniond end_quat_I = end_quat.inverse(); // Rotation of the inverse pose\n                Eigen::Vector3d end_t_I = -1.0 * (end_quat_I * end_t); // Translation of the inverse pose\n\n                for (int i(0); i < keypoints->size(); ++i) {\n                    auto &keypoint = (*keypoints)[i];\n                    double alpha_timestamp = keypoint.alpha_timestamp;\n                    Eigen::Quaterniond q_alpha = begin_quat.slerp(alpha_timestamp, end_quat);\n                    q_alpha.normalize();\n                    Eigen::Matrix3d R = q_alpha.toRotationMatrix();\n                    Eigen::Vector3d t = (1.0 - alpha_timestamp) * begin_t + alpha_timestamp * end_t;\n\n                    // Distort Raw Keypoints\n                    corrected_raw_points_[i] = end_quat_I * (q_alpha * keypoint.raw_pt + t) + end_t_I;\n                }\n            }\n        }\n\n        inline void AddParameterBlocks(Eigen::Quaterniond &begin_quat, Eigen::\n        Quaterniond &end_quat, Eigen::Vector3d &begin_t, Eigen::Vector3d &end_t) {\n            CHECK(!parameter_block_set_) << \"The parameter block was already set\";\n            auto *parameterization = new ceres::EigenQuaternionParameterization();\n            begin_t_ = &begin_t.x();\n            end_t_ = &end_t.x();\n            begin_quat_ = &begin_quat.x();\n            end_quat_ = &end_quat.x();\n\n            switch (options_->distance) {\n                case CT_POINT_TO_PLANE:\n                    problem->AddParameterBlock(begin_quat_, 4, parameterization);\n                    problem->AddParameterBlock(end_quat_, 4, parameterization);\n                    problem->AddParameterBlock(begin_t_, 3);\n                    problem->AddParameterBlock(end_t_, 3);\n                    break;\n                case POINT_TO_PLANE:\n                    problem->AddParameterBlock(end_quat_, 4, parameterization);\n                    problem->AddParameterBlock(end_t_, 3);\n                    break;\n            }\n\n            parameter_block_set_ = true;\n        }\n\n\n        inline void SetResidualBlock(int residual_id,\n                                     int keypoint_id,\n                                     const Eigen::Vector3d &reference_point,\n                                     const Eigen::Vector3d &reference_normal,\n                                     double weight = 1.0,\n                                     double alpha_timestamp = -1.0) {\n\n            CTPointToPlaneFunctor *ct_point_to_plane_functor = nullptr;\n            PointToPlaneFunctor *point_to_plane_functor = nullptr;\n            void *cost_functor = nullptr;\n            void *cost_function = nullptr;\n            if (alpha_timestamp < 0 || alpha_timestamp > 1)\n                throw std::runtime_error(\"BAD ALPHA TIMESTAMP !\");\n            switch (options_->distance) {\n                case CT_POINT_TO_PLANE:\n                    ct_point_to_plane_functor = new CTPointToPlaneFunctor(reference_point,\n                                                                          corrected_raw_points_[keypoint_id],\n                                                                          reference_normal,\n                                                                          alpha_timestamp, weight);\n                    cost_functor = ct_point_to_plane_functor;\n                    cost_function = static_cast<void *>(new CTICP_PointToPlaneResidual(ct_point_to_plane_functor));\n                    break;\n                case POINT_TO_PLANE:\n                    point_to_plane_functor = new PointToPlaneFunctor(reference_point,\n                                                                     corrected_raw_points_[keypoint_id],\n                                                                     reference_normal,\n                                                                     weight);\n                    cost_functor = point_to_plane_functor;\n                    cost_function = static_cast<void *>(new PointToPlaneResidual(point_to_plane_functor));\n                    break;\n            }\n            vector_ct_icp_residuals_[residual_id] = cost_function;\n            vector_cost_functors_[residual_id] = cost_functor;\n        }\n\n\n        std::unique_ptr<ceres::Problem> GetProblem(int &out_number_of_residuals) {\n            out_number_of_residuals = 0;\n            for (auto &pt_to_plane_residual: vector_ct_icp_residuals_) {\n                if (pt_to_plane_residual != nullptr) {\n                    if (max_num_residuals_ <= 0 || out_number_of_residuals < max_num_residuals_) {\n\n                        switch (options_->distance) {\n                            case CT_POINT_TO_PLANE:\n                                problem->AddResidualBlock(\n                                        static_cast<CTICP_PointToPlaneResidual *>(pt_to_plane_residual), loss_function,\n                                        begin_quat_, begin_t_, end_quat_, end_t_);\n                                break;\n                            case POINT_TO_PLANE:\n                                problem->AddResidualBlock(\n                                        static_cast<PointToPlaneResidual *>(pt_to_plane_residual), loss_function,\n                                        end_quat_, end_t_);\n                                break;\n                        }\n                        out_number_of_residuals++;\n                    } else {\n                        // Need to deallocate memory from the allocated pointers not managed by Ceres\n                        CTICP_PointToPlaneResidual *ct_pt_to_pl_ptr = nullptr;\n                        PointToPlaneResidual *pt_to_pl_ptr = nullptr;\n                        switch (options_->distance) {\n                            case CT_POINT_TO_PLANE:\n                                ct_pt_to_pl_ptr = static_cast<CTICP_PointToPlaneResidual *>(pt_to_plane_residual);\n                                delete ct_pt_to_pl_ptr;\n                                break;\n                            case POINT_TO_PLANE:\n                                pt_to_pl_ptr = static_cast<PointToPlaneResidual *>(pt_to_plane_residual);\n                                delete pt_to_pl_ptr;\n                                break;\n                        }\n                    }\n                }\n            }\n\n\n#if CT_ICP_WITH_VIZ\n            // Adds to the visualizer keypoints colored by timestamp value\n            if (options_->debug_viz) {\n                auto palette = colormap::palettes.at(\"jet\").rescale(0, 1);\n                auto &instance = viz::ExplorationEngine::Instance();\n                auto model_ptr = std::make_shared<viz::PointCloudModel>();\n                auto &model_data = model_ptr->ModelData();\n                model_data.xyz.reserve(keypoints->size());\n                model_data.point_size = 6;\n                model_data.default_color = Eigen::Vector3f(1, 0, 0);\n                model_data.rgb.reserve(keypoints->size());\n                std::vector<double> scalars(keypoints->size());\n\n                double s_min = 0.0;\n                double s_max = 1.0;\n                std::vector<double> s_values;\n                if (options_->viz_mode == WEIGHT || options_->viz_mode == TIMESTAMP) {\n                    s_min = std::numeric_limits<double>::max();\n                    s_max = std::numeric_limits<double>::min();\n                    s_values.resize(keypoints->size());\n                    for (int i(0); i < keypoints->size(); ++i) {\n                        double new_s;\n                        auto *ptr = vector_cost_functors_[i];\n                        if (ptr != nullptr) {\n                            CTPointToPlaneFunctor *ct_ptr;\n                            PointToPlaneFunctor *pt_to_pl_ptr;\n\n                            switch (options_->distance) {\n                                case CT_POINT_TO_PLANE:\n                                    ct_ptr = static_cast<CTPointToPlaneFunctor *>(ptr);\n                                    new_s = options_->viz_mode == WEIGHT ? ct_ptr->weight_ : ct_ptr->alpha_timestamps_;\n                                    break;\n                                case POINT_TO_PLANE:\n                                    pt_to_pl_ptr = static_cast<PointToPlaneFunctor *>(ptr);\n                                    new_s = options_->viz_mode == WEIGHT ? pt_to_pl_ptr->weight_ : 1.0;\n                                    break;\n                            }\n                            if (new_s < s_min)\n                                s_min = new_s;\n                            if (new_s > s_max)\n                                s_max = new_s;\n                            s_values[i] = new_s;\n                        }\n\n                    }\n                }\n\n                for (size_t i(0); i < keypoints->size(); ++i) {\n                    void *ptr = vector_cost_functors_[i];\n                    if (!ptr)\n                        continue;\n                    model_data.xyz.push_back((*keypoints)[i].pt.cast<float>());\n                    scalars[i] = (*keypoints)[i].alpha_timestamp;\n                    if (options_->viz_mode == NORMAL) {\n                        switch (options_->distance) {\n                            case CT_POINT_TO_PLANE:\n                                model_data.rgb.push_back(\n                                        static_cast<CTPointToPlaneFunctor *>(ptr)->reference_normal_.cwiseAbs().cast<float>());\n                                break;\n                            case POINT_TO_PLANE:\n                                model_data.rgb.push_back(\n                                        static_cast<PointToPlaneFunctor *>(ptr)->reference_normal_.cwiseAbs().cast<float>());\n                                break;\n                        }\n                    } else {\n                        double s = s_min == s_max ? 1.0 : (s_values[i] - s_min) / (s_max - s_min);\n                        colormap::rgb value = palette(s);\n                        std::uint8_t *rgb_color_ptr = reinterpret_cast<std::uint8_t *>(&value);\n                        Eigen::Vector3f rgb((float) rgb_color_ptr[0] / 255.0f,\n                                            (float) rgb_color_ptr[1] / 255.0f, (float) rgb_color_ptr[2] / 255.0f);\n                        model_data.rgb.push_back(rgb);\n                    }\n                }\n\n                instance.AddModel(-2, model_ptr);\n            }\n#endif\n            std::fill(vector_cost_functors_.begin(), vector_cost_functors_.end(), nullptr);\n            std::fill(vector_ct_icp_residuals_.begin(), vector_ct_icp_residuals_.end(), nullptr);\n\n            return std::move(problem);\n        }\n\n    private:\n        const CTICPOptions *options_;\n        std::unique_ptr<ceres::Problem> problem = nullptr;\n        int max_num_residuals_ = -1;\n\n        // Parameters block pointers\n        bool parameter_block_set_ = false;\n        double *begin_quat_ = nullptr;\n        double *end_quat_ = nullptr;\n        double *begin_t_ = nullptr;\n        double *end_t_ = nullptr;\n\n        // Pointers managed by ceres\n        const std::vector<Point3D> *keypoints;\n        std::vector<Eigen::Vector3d> corrected_raw_points_;\n\n        std::vector<void *> vector_cost_functors_;\n        std::vector<void *> vector_ct_icp_residuals_;\n        ceres::LossFunction *loss_function = nullptr;\n    };\n\n    /* -------------------------------------------------------------------------------------------------------------- */\n    ICPSummary CT_ICP_CERES(const CTICPOptions &options,\n                            const VoxelHashMap &voxels_map, std::vector<Point3D> &keypoints,\n                            std::vector<TrajectoryFrame> &trajectory, int index_frame) {\n\n        const short nb_voxels_visited = index_frame < options.init_num_frames ? 2 : options.voxel_neighborhood;\n        const int kMinNumNeighbors = options.min_number_neighbors;\n        const int kThresholdCapacity = index_frame < options.init_num_frames ? 1 : options.threshold_voxel_occupancy;\n\n        ceres::Solver::Options ceres_options;\n        ceres_options.max_num_iterations = options.ls_max_num_iters;\n        ceres_options.num_threads = options.ls_num_threads;\n        ceres_options.trust_region_strategy_type = ceres::TrustRegionStrategyType::LEVENBERG_MARQUARDT;\n\n        TrajectoryFrame *previous_estimate = nullptr;\n        Eigen::Vector3d previous_velocity = Eigen::Vector3d::Zero();\n        Eigen::Quaterniond previous_orientation = Eigen::Quaterniond::Identity();\n        if (index_frame > 0) {\n            previous_estimate = &trajectory[index_frame - 1];\n            previous_velocity = previous_estimate->end_t - previous_estimate->begin_t;\n            previous_orientation = Eigen::Quaterniond(previous_estimate->end_R);\n        }\n\n        TrajectoryFrame &current_estimate = trajectory[index_frame];\n        Eigen::Quaterniond begin_quat = Eigen::Quaterniond(current_estimate.begin_R);\n        Eigen::Quaterniond end_quat = Eigen::Quaterniond(current_estimate.end_R);\n        Eigen::Vector3d begin_t = current_estimate.begin_t;\n        Eigen::Vector3d end_t = current_estimate.end_t;\n\n        int number_of_residuals;\n\n        ICPOptimizationBuilder builder(&options, &keypoints);\n        if (options.point_to_plane_with_distortion) {\n            builder.DistortFrame(begin_quat, end_quat, begin_t, end_t);\n        }\n\n        int num_iter_icp = index_frame < options.init_num_frames ? std::max(15, options.num_iters_icp) :\n                           options.num_iters_icp;\n\n        auto transform_keypoints = [&]() {\n            // Elastically distorts the frame to improve on Neighbor estimation\n            Eigen::Matrix3d R;\n            Eigen::Vector3d t;\n            for (auto &keypoint: keypoints) {\n                if (options.point_to_plane_with_distortion || options.distance == CT_POINT_TO_PLANE) {\n                    double alpha_timestamp = keypoint.alpha_timestamp;\n                    Eigen::Quaterniond q = begin_quat.slerp(alpha_timestamp, end_quat);\n                    q.normalize();\n                    R = q.toRotationMatrix();\n                    t = (1.0 - alpha_timestamp) * begin_t + alpha_timestamp * end_t;\n                } else {\n                    R = end_quat.normalized().toRotationMatrix();\n                    t = end_t;\n                }\n\n                keypoint.pt = R * keypoint.raw_pt + t;\n            }\n        };\n\n        auto estimate_point_neighborhood = [&](ArrayVector3d &vector_neighbors,\n                                               Eigen::Vector3d &location,\n                                               double &planarity_weight) {\n\n            auto neighborhood = compute_neighborhood_distribution(vector_neighbors);\n            planarity_weight = std::pow(neighborhood.a2D, options.power_planarity);\n\n            if (neighborhood.normal.dot(trajectory[index_frame].begin_t - location) < 0) {\n                neighborhood.normal = -1.0 * neighborhood.normal;\n            }\n            return neighborhood;\n        };\n\n        double lambda_weight = std::abs(options.weight_alpha);\n        double lambda_neighborhood = std::abs(options.weight_neighborhood);\n        const double kMaxPointToPlane = options.max_dist_to_plane_ct_icp;\n        const double sum = lambda_weight + lambda_neighborhood;\n        CHECK(sum > 0.0) << \"Invalid requirement: weight_alpha(\" << options.weight_alpha <<\n                         \") + weight_neighborhood(\" << options.weight_neighborhood << \") <= 0 \" << std::endl;\n        lambda_weight /= sum;\n        lambda_neighborhood /= sum;\n\n        for (int iter(0); iter < num_iter_icp; iter++) {\n            transform_keypoints();\n\n            builder.InitProblem(keypoints.size() * options.num_closest_neighbors);\n            builder.AddParameterBlocks(begin_quat, end_quat, begin_t, end_t);\n\n            // Add Point-to-plane residuals\n            int num_keypoints = keypoints.size();\n            int num_threads = options.ls_num_threads;\n#pragma omp parallel for num_threads(num_threads)\n            for (int k = 0; k < num_keypoints; ++k) {\n                auto &keypoint = keypoints[k];\n                auto &raw_point = keypoint.raw_pt;\n                // Neighborhood search\n                std::vector<Voxel> voxels;\n                auto vector_neighbors = search_neighbors(voxels_map, keypoint.pt,\n                                                         nb_voxels_visited, options.size_voxel_map,\n                                                         options.max_number_neighbors, kThresholdCapacity,\n                                                         options.estimate_normal_from_neighborhood ? nullptr : &voxels);\n\n                if (vector_neighbors.size() < kMinNumNeighbors)\n                    continue;\n\n                double weight;\n                auto neighborhood = estimate_point_neighborhood(vector_neighbors,\n                                                                raw_point,\n                                                                weight);\n\n                weight = lambda_weight * weight +\n                         lambda_neighborhood * std::exp(-(vector_neighbors[0] -\n                                                          keypoint.pt).norm() / (kMaxPointToPlane * kMinNumNeighbors));\n\n                double point_to_plane_dist;\n                std::set<Voxel> neighbor_voxels;\n                for (int i(0); i < options.num_closest_neighbors; ++i) {\n                    point_to_plane_dist = std::abs(\n                            (keypoint.pt - vector_neighbors[i]).transpose() * neighborhood.normal);\n                    if (point_to_plane_dist < options.max_dist_to_plane_ct_icp) {\n                        builder.SetResidualBlock(options.num_closest_neighbors * k + i, k,\n                                                 vector_neighbors[i],\n                                                 neighborhood.normal, weight, keypoint.alpha_timestamp);\n                    }\n                }\n            }\n\n            auto problem = builder.GetProblem(number_of_residuals);\n\n            if (index_frame > 1) {\n                if (options.distance == CT_POINT_TO_PLANE) {\n                    // Add Regularisation residuals\n                    problem->AddResidualBlock(new ceres::AutoDiffCostFunction<LocationConsistencyFunctor,\n                                                      LocationConsistencyFunctor::NumResiduals(), 3>(\n                                                      new LocationConsistencyFunctor(previous_estimate->end_t,\n                                                                                     sqrt(number_of_residuals *\n                                                                                          options.beta_location_consistency))),\n                                              nullptr,\n                                              &begin_t.x());\n                    problem->AddResidualBlock(new ceres::AutoDiffCostFunction<ConstantVelocityFunctor,\n                                                      ConstantVelocityFunctor::NumResiduals(), 3, 3>(\n                                                      new ConstantVelocityFunctor(previous_velocity,\n                                                                                  sqrt(number_of_residuals * options.beta_constant_velocity))),\n                                              nullptr,\n                                              &begin_t.x(),\n                                              &end_t.x());\n\n                    // SMALL VELOCITY\n                    problem->AddResidualBlock(new ceres::AutoDiffCostFunction<SmallVelocityFunctor,\n                                                      SmallVelocityFunctor::NumResiduals(), 3, 3>(\n                                                      new SmallVelocityFunctor(sqrt(number_of_residuals * options.beta_small_velocity))),\n                                              nullptr,\n                                              &begin_t.x(), &end_t.x());\n\n                    // ORIENTATION CONSISTENCY\n                    problem->AddResidualBlock(new ceres::AutoDiffCostFunction<OrientationConsistencyFunctor,\n                                                      OrientationConsistencyFunctor::NumResiduals(), 4>(\n                                                      new OrientationConsistencyFunctor(previous_orientation,\n                                                                                        sqrt(number_of_residuals *\n                                                                                             options.beta_orientation_consistency))),\n                                              nullptr,\n                                              &begin_quat.x());\n                }\n            }\n            if (number_of_residuals < options.min_number_neighbors) {\n                std::stringstream ss_out;\n                ss_out << \"[CT_ICP] Error : not enough keypoints selected in ct-icp !\" << std::endl;\n                ss_out << \"[CT_ICP] number_of_residuals : \" << number_of_residuals << std::endl;\n                ICPSummary summary;\n                summary.success = false;\n                summary.num_residuals_used = number_of_residuals;\n                summary.error_log = ss_out.str();\n                if (options.debug_print) {\n                    std::cout << summary.error_log;\n                }\n                return summary;\n            }\n\n            ceres::Solver::Summary summary;\n            ceres::Solve(ceres_options, problem.get(), &summary);\n            if (!summary.IsSolutionUsable()) {\n                std::cout << summary.FullReport() << std::endl;\n                throw std::runtime_error(\"Error During Optimization\");\n            }\n            if (options.debug_print) {\n                std::cout << summary.BriefReport() << std::endl;\n            }\n\n            begin_quat.normalize();\n            end_quat.normalize();\n\n            double diff_trans = (current_estimate.begin_t - begin_t).norm() + (current_estimate.end_t - end_t).norm();\n            double diff_rot = AngularDistance(current_estimate.begin_R, begin_quat.toRotationMatrix()) +\n                              AngularDistance(current_estimate.end_R, end_quat.toRotationMatrix());\n\n            current_estimate.begin_t = begin_t;\n            current_estimate.end_t = end_t;\n            current_estimate.begin_R = begin_quat.toRotationMatrix();\n            current_estimate.end_R = end_quat.toRotationMatrix();\n\n            if (options.point_to_plane_with_distortion) {\n                builder.DistortFrame(begin_quat, end_quat, begin_t, end_t);\n            }\n\n            if ((index_frame > 1) &&\n                (diff_rot < options.threshold_orientation_norm &&\n                 diff_trans < options.threshold_translation_norm)) {\n\n                if (options.debug_print) {\n                    std::cout << \"CT_ICP: Finished with N=\" << iter << \" ICP iterations\" << std::endl;\n\n                }\n                break;\n            }\n        }\n        transform_keypoints();\n\n        ICPSummary summary;\n        summary.success = true;\n        summary.num_residuals_used = number_of_residuals;\n        return summary;\n    }\n\n    /* -------------------------------------------------------------------------------------------------------------- */\n    ICPSummary CT_ICP_GN(const CTICPOptions &options,\n                         const VoxelHashMap &voxels_map, std::vector<Point3D> &keypoints,\n                         std::vector<TrajectoryFrame> &trajectory, int index_frame) {\n\n        //Optimization with Traj constraints\n        double ALPHA_C = options.beta_location_consistency; // 0.001;\n        double ALPHA_E = options.beta_constant_velocity; // 0.001; //no ego (0.0) is not working\n\n        // For the 50 first frames, visit 2 voxels\n        const short nb_voxels_visited = index_frame < options.init_num_frames ? 2 : 1;\n        int number_keypoints_used = 0;\n        const int kMinNumNeighbors = options.min_number_neighbors;\n\n        using AType = Eigen::Matrix<double, 12, 12>;\n        using bType = Eigen::Matrix<double, 12, 1>;\n        AType A;\n        bType b;\n\n        // TODO Remove chronos\n        double elapsed_search_neighbors = 0.0;\n        double elapsed_select_closest_neighbors = 0.0;\n        double elapsed_normals = 0.0;\n        double elapsed_A_construction = 0.0;\n        double elapsed_solve = 0.0;\n        double elapsed_update = 0.0;\n\n        ICPSummary summary;\n\n        int num_iter_icp = index_frame < options.init_num_frames ? 15 : options.num_iters_icp;\n        for (int iter(0); iter < num_iter_icp; iter++) {\n            A = Eigen::MatrixXd::Zero(12, 12);\n            b = Eigen::VectorXd::Zero(12);\n\n            number_keypoints_used = 0;\n            double total_scalar = 0;\n            double mean_scalar = 0.0;\n\n            for (auto &keypoint: keypoints) {\n                auto start = std::chrono::steady_clock::now();\n                auto &pt_keypoint = keypoint.pt;\n\n                // Neighborhood search\n                ArrayVector3d vector_neighbors = search_neighbors(voxels_map, pt_keypoint,\n                                                                  nb_voxels_visited, options.size_voxel_map,\n                                                                  options.max_number_neighbors);\n                auto step1 = std::chrono::steady_clock::now();\n                std::chrono::duration<double> _elapsed_search_neighbors = step1 - start;\n                elapsed_search_neighbors += _elapsed_search_neighbors.count() * 1000.0;\n\n\n                if (vector_neighbors.size() < kMinNumNeighbors) {\n                    continue;\n                }\n\n                auto step2 = std::chrono::steady_clock::now();\n                std::chrono::duration<double> _elapsed_neighbors_selection = step2 - step1;\n                elapsed_select_closest_neighbors += _elapsed_neighbors_selection.count() * 1000.0;\n\n                // Compute normals from neighbors\n                auto neighborhood = compute_neighborhood_distribution(vector_neighbors);\n                double planarity_weight = neighborhood.a2D;\n                auto &normal = neighborhood.normal;\n\n                if (normal.dot(trajectory[index_frame].begin_t - pt_keypoint) < 0) {\n                    normal = -1.0 * normal;\n                }\n\n                double alpha_timestamp = keypoint.alpha_timestamp;\n                double weight = planarity_weight *\n                                planarity_weight; //planarity_weight**2 much better than planarity_weight (planarity_weight**3 is not working)\n                Eigen::Vector3d closest_pt_normal = weight * normal;\n\n                Eigen::Vector3d closest_point = vector_neighbors[0];\n\n                double dist_to_plane = normal[0] * (pt_keypoint[0] - closest_point[0]) +\n                                       normal[1] * (pt_keypoint[1] - closest_point[1]) +\n                                       normal[2] * (pt_keypoint[2] - closest_point[2]);\n\n                auto step3 = std::chrono::steady_clock::now();\n                std::chrono::duration<double> _elapsed_normals = step3 - step2;\n                elapsed_normals += _elapsed_normals.count() * 1000.0;\n\n                // std::cout << \"dist_to_plane : \" << dist_to_plane << std::endl;\n\n                if (fabs(dist_to_plane) < options.max_dist_to_plane_ct_icp) {\n\n                    double scalar = closest_pt_normal[0] * (pt_keypoint[0] - closest_point[0]) +\n                                    closest_pt_normal[1] * (pt_keypoint[1] - closest_point[1]) +\n                                    closest_pt_normal[2] * (pt_keypoint[2] - closest_point[2]);\n                    total_scalar = total_scalar + scalar * scalar;\n                    mean_scalar = mean_scalar + fabs(scalar);\n                    number_keypoints_used++;\n\n\n                    Eigen::Vector3d frame_idx_previous_origin_begin =\n                            trajectory[index_frame].begin_R * keypoint.raw_pt;\n                    Eigen::Vector3d frame_idx_previous_origin_end =\n                            trajectory[index_frame].end_R * keypoint.raw_pt;\n\n                    double cbx =\n                            (1 - alpha_timestamp) * (frame_idx_previous_origin_begin[1] * closest_pt_normal[2] -\n                                                     frame_idx_previous_origin_begin[2] * closest_pt_normal[1]);\n                    double cby =\n                            (1 - alpha_timestamp) * (frame_idx_previous_origin_begin[2] * closest_pt_normal[0] -\n                                                     frame_idx_previous_origin_begin[0] * closest_pt_normal[2]);\n                    double cbz =\n                            (1 - alpha_timestamp) * (frame_idx_previous_origin_begin[0] * closest_pt_normal[1] -\n                                                     frame_idx_previous_origin_begin[1] * closest_pt_normal[0]);\n\n                    double nbx = (1 - alpha_timestamp) * closest_pt_normal[0];\n                    double nby = (1 - alpha_timestamp) * closest_pt_normal[1];\n                    double nbz = (1 - alpha_timestamp) * closest_pt_normal[2];\n\n                    double cex = (alpha_timestamp) * (frame_idx_previous_origin_end[1] * closest_pt_normal[2] -\n                                                      frame_idx_previous_origin_end[2] * closest_pt_normal[1]);\n                    double cey = (alpha_timestamp) * (frame_idx_previous_origin_end[2] * closest_pt_normal[0] -\n                                                      frame_idx_previous_origin_end[0] * closest_pt_normal[2]);\n                    double cez = (alpha_timestamp) * (frame_idx_previous_origin_end[0] * closest_pt_normal[1] -\n                                                      frame_idx_previous_origin_end[1] * closest_pt_normal[0]);\n\n                    double nex = (alpha_timestamp) * closest_pt_normal[0];\n                    double ney = (alpha_timestamp) * closest_pt_normal[1];\n                    double nez = (alpha_timestamp) * closest_pt_normal[2];\n\n                    Eigen::VectorXd u(12);\n                    u << cbx, cby, cbz, nbx, nby, nbz, cex, cey, cez, nex, ney, nez;\n                    for (int i = 0; i < 12; i++) {\n                        for (int j = 0; j < 12; j++) {\n                            A(i, j) = A(i, j) + u[i] * u[j];\n                        }\n                        b(i) = b(i) - u[i] * scalar;\n                    }\n\n\n                    auto step4 = std::chrono::steady_clock::now();\n                    std::chrono::duration<double> _elapsed_A = step4 - step3;\n                    elapsed_search_neighbors += _elapsed_A.count() * 1000.0;\n                }\n            }\n\n\n            if (number_keypoints_used < 100) {\n                std::stringstream ss_out;\n                ss_out << \"[CT_ICP]Error : not enough keypoints selected in ct-icp !\" << std::endl;\n                ss_out << \"[CT_ICP]Number_of_residuals : \" << number_keypoints_used << std::endl;\n\n                summary.error_log = ss_out.str();\n                if (options.debug_print)\n                    std::cout << summary.error_log;\n\n                summary.success = false;\n                return summary;\n            }\n\n            auto start = std::chrono::steady_clock::now();\n\n\n            // Normalize equation\n            for (int i(0); i < 12; i++) {\n                for (int j(0); j < 12; j++) {\n                    A(i, j) = A(i, j) / number_keypoints_used;\n                }\n                b(i) = b(i) / number_keypoints_used;\n            }\n\n            //Add constraints in trajectory\n            if (index_frame > 1) //no constraints for frame_index == 1\n            {\n                Eigen::Vector3d diff_traj = trajectory[index_frame].begin_t - trajectory[index_frame - 1].end_t;\n                A(3, 3) = A(3, 3) + ALPHA_C;\n                A(4, 4) = A(4, 4) + ALPHA_C;\n                A(5, 5) = A(5, 5) + ALPHA_C;\n                b(3) = b(3) - ALPHA_C * diff_traj(0);\n                b(4) = b(4) - ALPHA_C * diff_traj(1);\n                b(5) = b(5) - ALPHA_C * diff_traj(2);\n\n                Eigen::Vector3d diff_ego = trajectory[index_frame].end_t - trajectory[index_frame].begin_t -\n                                           trajectory[index_frame - 1].end_t + trajectory[index_frame - 1].begin_t;\n                A(9, 9) = A(9, 9) + ALPHA_E;\n                A(10, 10) = A(10, 10) + ALPHA_E;\n                A(11, 11) = A(11, 11) + ALPHA_E;\n                b(9) = b(9) - ALPHA_E * diff_ego(0);\n                b(10) = b(10) - ALPHA_E * diff_ego(1);\n                b(11) = b(11) - ALPHA_E * diff_ego(2);\n            }\n\n\n            //Solve\n            Eigen::VectorXd x_bundle = A.ldlt().solve(b);\n\n            double alpha_begin = x_bundle(0);\n            double beta_begin = x_bundle(1);\n            double gamma_begin = x_bundle(2);\n            Eigen::Matrix3d rotation_begin;\n            rotation_begin(0, 0) = cos(gamma_begin) * cos(beta_begin);\n            rotation_begin(0, 1) =\n                    -sin(gamma_begin) * cos(alpha_begin) + cos(gamma_begin) * sin(beta_begin) * sin(alpha_begin);\n            rotation_begin(0, 2) =\n                    sin(gamma_begin) * sin(alpha_begin) + cos(gamma_begin) * sin(beta_begin) * cos(alpha_begin);\n            rotation_begin(1, 0) = sin(gamma_begin) * cos(beta_begin);\n            rotation_begin(1, 1) =\n                    cos(gamma_begin) * cos(alpha_begin) + sin(gamma_begin) * sin(beta_begin) * sin(alpha_begin);\n            rotation_begin(1, 2) =\n                    -cos(gamma_begin) * sin(alpha_begin) + sin(gamma_begin) * sin(beta_begin) * cos(alpha_begin);\n            rotation_begin(2, 0) = -sin(beta_begin);\n            rotation_begin(2, 1) = cos(beta_begin) * sin(alpha_begin);\n            rotation_begin(2, 2) = cos(beta_begin) * cos(alpha_begin);\n            Eigen::Vector3d translation_begin = Eigen::Vector3d(x_bundle(3), x_bundle(4), x_bundle(5));\n\n            double alpha_end = x_bundle(6);\n            double beta_end = x_bundle(7);\n            double gamma_end = x_bundle(8);\n            Eigen::Matrix3d rotation_end;\n            rotation_end(0, 0) = cos(gamma_end) * cos(beta_end);\n            rotation_end(0, 1) = -sin(gamma_end) * cos(alpha_end) + cos(gamma_end) * sin(beta_end) * sin(alpha_end);\n            rotation_end(0, 2) = sin(gamma_end) * sin(alpha_end) + cos(gamma_end) * sin(beta_end) * cos(alpha_end);\n            rotation_end(1, 0) = sin(gamma_end) * cos(beta_end);\n            rotation_end(1, 1) = cos(gamma_end) * cos(alpha_end) + sin(gamma_end) * sin(beta_end) * sin(alpha_end);\n            rotation_end(1, 2) = -cos(gamma_end) * sin(alpha_end) + sin(gamma_end) * sin(beta_end) * cos(alpha_end);\n            rotation_end(2, 0) = -sin(beta_end);\n            rotation_end(2, 1) = cos(beta_end) * sin(alpha_end);\n            rotation_end(2, 2) = cos(beta_end) * cos(alpha_end);\n            Eigen::Vector3d translation_end = Eigen::Vector3d(x_bundle(9), x_bundle(10), x_bundle(11));\n\n            trajectory[index_frame].begin_R = rotation_begin * trajectory[index_frame].begin_R;\n            trajectory[index_frame].begin_t = trajectory[index_frame].begin_t + translation_begin;\n            trajectory[index_frame].end_R = rotation_end * trajectory[index_frame].end_R;\n            trajectory[index_frame].end_t = trajectory[index_frame].end_t + translation_end;\n\n            auto solve_step = std::chrono::steady_clock::now();\n            std::chrono::duration<double> _elapsed_solve = solve_step - start;\n            elapsed_solve += _elapsed_solve.count() * 1000.0;\n\n\n            //Update keypoints\n            for (auto &keypoint: keypoints) {\n                Eigen::Quaterniond q_begin = Eigen::Quaterniond(trajectory[index_frame].begin_R);\n                Eigen::Quaterniond q_end = Eigen::Quaterniond(trajectory[index_frame].end_R);\n                Eigen::Vector3d t_begin = trajectory[index_frame].begin_t;\n                Eigen::Vector3d t_end = trajectory[index_frame].end_t;\n                double alpha_timestamp = keypoint.alpha_timestamp;\n                Eigen::Quaterniond q = q_begin.slerp(alpha_timestamp, q_end);\n                q.normalize();\n                Eigen::Matrix3d R = q.toRotationMatrix();\n                Eigen::Vector3d t = (1.0 - alpha_timestamp) * t_begin + alpha_timestamp * t_end;\n                keypoint.pt = R * keypoint.raw_pt + t;\n            }\n            auto update_step = std::chrono::steady_clock::now();\n            std::chrono::duration<double> _elapsed_update = update_step - solve_step;\n            elapsed_update += _elapsed_update.count() * 1000.0;\n\n\n            if ((index_frame > 1) && (x_bundle.norm() < options.threshold_orientation_norm)) {\n                summary.success = true;\n                summary.num_residuals_used = number_keypoints_used;\n\n                return summary;\n            }\n        }\n\n        if (options.debug_print) {\n            std::cout << \"Elapsed Normals: \" << elapsed_normals << std::endl;\n            std::cout << \"Elapsed Search Neighbors: \" << elapsed_search_neighbors << std::endl;\n            std::cout << \"Elapsed A Construction: \" << elapsed_A_construction << std::endl;\n            std::cout << \"Elapsed Select closest: \" << elapsed_select_closest_neighbors << std::endl;\n            std::cout << \"Elapsed Solve: \" << elapsed_solve << std::endl;\n            std::cout << \"Elapsed Solve: \" << elapsed_update << std::endl;\n            std::cout << \"Number iterations CT-ICP : \" << options.num_iters_icp << std::endl;\n        }\n        summary.success = true;\n        summary.num_residuals_used = number_keypoints_used;\n\n        return summary;\n    }\n\n\n} // namespace Elastic_ICP\n", "meta": {"hexsha": "5190bd05162ac220524ccd7d436fae2b5d861a63", "size": 49356, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ct_icp/ct_icp.cpp", "max_stars_repo_name": "jedeschaud/ct_icp", "max_stars_repo_head_hexsha": "1ba7ce704e9994d39076089ea3fc0dc4d856fe84", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 123.0, "max_stars_repo_stars_event_min_datetime": "2021-10-08T01:51:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:55:15.000Z", "max_issues_repo_path": "src/ct_icp/ct_icp.cpp", "max_issues_repo_name": "ZuoJiaxing/ct_icp", "max_issues_repo_head_hexsha": "1c371331aad833faec157c015fb8f72143019caa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2021-10-19T07:25:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T03:20:19.000Z", "max_forks_repo_path": "src/ct_icp/ct_icp.cpp", "max_forks_repo_name": "ZuoJiaxing/ct_icp", "max_forks_repo_head_hexsha": "1c371331aad833faec157c015fb8f72143019caa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 23.0, "max_forks_repo_forks_event_min_datetime": "2021-10-08T01:49:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T15:35:07.000Z", "avg_line_length": 49.2574850299, "max_line_length": 143, "alphanum_fraction": 0.5164924224, "num_tokens": 10061, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.6548947155710234, "lm_q1q2_score": 0.49057325737066004}}
{"text": "#include <vector>\n#include <string>\n#include <iostream>\n#include <ros/ros.h>\n#include <sensor_msgs/LaserScan.h>\n#include <visualization_msgs/Marker.h>\n#include <geometry_msgs/Point.h>\n#include <laser_geometry/laser_geometry.h>\n\n#include <tf/transform_listener.h>\n#include <sensor_msgs/PointCloud2.h>\n\n#include <pcl_conversions/pcl_conversions.h>\n#include <pcl_ros/point_cloud.h>\n\n// #include <pcl/point_cloud.h>\n// #include <pcl/point_types.h>\n// #include <pcl/io/pcd_io.h>\n#include <opencv2/opencv.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc.hpp>\n#include <Eigen/Eigen>\n#include \"ceres/ceres.h\"\n#include <csm/csm_all.h>  // csm defines min and max, but Eigen complains\n\n// #include <ros/log.h>\n// #include <cmath>\nusing namespace ceres;\nusing namespace std;\nstruct CostFunctor {\n\tCostFunctor(double k1, double k2): k1_(k1), k2_(k2)\n\t{}\n\ttemplate <typename T>\n\tbool operator()(const T* const main_k, T* residual) const {\n\t\t// residual[0] = T(10.0) - x[0];\n\n\t\tT r1 = T(k1_) - main_k[0] ;\n\t\tT r2 = T(k1_) + T(1) / main_k[0] ;\n\n\t\tif (r1 * r1 < r2 * r2)\n\t\t{\n\t\t\tT r = T(k2_) + T(1) / main_k[0] ;\n\n\t\t\tresidual[0] = r1 * r1 + r * r;\n\t\t\t// residual[1] = r;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tT r = T(k1_) + T(1) / main_k[0] ;\n\n\t\t\tresidual[0] = r2 * r2 + r * r;\n\t\t\t// T r = T(k1_) - main_k[1];\n\t\t\t// residual[1] = r;\n\t\t}\n\n\t\treturn true;\n\t}\n\tdouble k1_ , k2_;\n};\nvoid laserScanToLDP(const sensor_msgs::LaserScan::ConstPtr& scan, LDP& ldp)\n{\n\tunsigned int n = scan->ranges.size();\n\tldp = ld_alloc_new(n);\n\n\tfor (unsigned int i = 0; i < n; i++)\n\t{\n\t\t// Calculate position in laser frame\n\t\tdouble r = scan->ranges[i];\n\t\tif ((r > scan->range_min) && (r < scan->range_max))\n\t\t{\n\t\t\t// Fill in laser scan data\n\t\t\tldp->valid[i] = 1;\n\t\t\tldp->readings[i] = r;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tldp->valid[i] = 0;\n\t\t\tldp->readings[i] = -1;  // for invalid range\n\t\t}\n\t\tldp->theta[i] = scan->angle_min + i * scan->angle_increment;\n\t\tldp->cluster[i] = -1;\n\t}\n\tROS_WARN(\"scan size is %d\", ldp->cluster[0]);\n\n\tldp->min_theta = ldp->theta[0];\n\tldp->max_theta = ldp->theta[n - 1];\n\n\tldp->odometry[0] = 0.0;\n\tldp->odometry[1] = 0.0;\n\tldp->odometry[2] = 0.0;\n\n\tldp->true_pose[0] = 0.0;\n\tldp->true_pose[1] = 0.0;\n\tldp->true_pose[2] = 0.0;\n}\ndouble get_laser_line(sm_params& input_)\n{\n\tboost::shared_ptr<sensor_msgs::LaserScan const> scan_ptr;    // \u6709const\n\twhile (scan_ptr == nullptr)\n\t\tscan_ptr = ros::topic::waitForMessage<sensor_msgs::LaserScan>(\"scan\", ros::Duration(10));\n\n\tinput_.max_angular_correction_deg = 90;\n\tinput_.restart = 1;\n\tinput_.laser[0] = 0.0;\n\tinput_.laser[1] = 0.0;\n\tinput_.laser[2] = 0.0;\n\ttf::TransformListener tfListener_;\n\tdouble main_k[2] = {1, -1};\n\tif (scan_ptr != NULL)\n\t{\n\t\tsensor_msgs::PointCloud2 cloud;\n\t\tlaser_geometry::LaserProjection projector_;\n\t\tprojector_.transformLaserScanToPointCloud(\"base_scan\", *scan_ptr, cloud, tfListener_);\n\t\t// input_.min_reading = scan_ptr->range_min;\n\t\t// input_.max_reading = scan_ptr->range_max;\n\t\tLDP curr_ldp_scan, prev_ldp_scan_;\n\t\tlaserScanToLDP(scan_ptr, prev_ldp_scan_);\n\t\t// prev_ldp_scan_->odometry[0] = 0.0;\n\t\t// prev_ldp_scan_->odometry[1] = 0.0;\n\t\t// prev_ldp_scan_->odometry[2] = 0.0;\n\n\t\tprev_ldp_scan_->estimate[0] = 0.0;\n\t\tprev_ldp_scan_->estimate[1] = 0.0;\n\t\tprev_ldp_scan_->estimate[2] = 0.0;\n\t\tinput_.first_guess[0] = 0.0;\n\t\tinput_.first_guess[1] = 0.0;\n\t\t// input_.first_guess[2] = 0.0;\n\t\tprev_ldp_scan_->true_pose[0] = 0.0;\n\t\tprev_ldp_scan_->true_pose[1] = 0.0;\n\t\tprev_ldp_scan_->true_pose[2] = 0.0;\n\t\tint row_step = cloud.row_step;\n\t\tint height = cloud.height;\n\n\t\t/*\u5c06 sensor_msgs::PointCloud2 \u8f6c\u6362\u4e3a\u3000pcl::PointCloud<T> */\n\t\t//\u6ce8\u610f\u8981\u7528fromROSMsg\u51fd\u6570\u9700\u8981\u5f15\u5165pcl_versions\uff08\u89c1\u5934\u6587\u4ef6\u5b9a\u4e49\uff09\n\t\tpcl::PointCloud<pcl::PointXYZ> rawCloud;\n\t\tpcl::fromROSMsg(cloud, rawCloud);\n\t\tdouble min_x = 30, min_y = 30, max_x = -1, max_y = -1;\n\t\tfor (size_t i = 0; i < rawCloud.points.size(); i++) {\n\t\t\t// std::cout << rawCloud.points[i].x << \"\\t\" << rawCloud.points[i].y << \"\\t\" << rawCloud.points[i].z << std::endl;\n\t\t\tdouble x = rawCloud.points[i].x;\n\t\t\tdouble y = rawCloud.points[i].y;\n\t\t\tmin_y = min_y < y ? min_y : y;\n\t\t\tmin_x = min_x < x ? min_x : x;\n\t\t\tmax_y = max_y > y ? max_y : y;\n\t\t\tmax_x = max_x > x ? max_x : x;\n\t\t}\n\t\tROS_INFO(\"fuch\");\n\t\t// std::cout << rawCloud.points[0].x << \"\\t\" << rawCloud.points[0].y << \"\\t\" << rawCloud.points[0].z << std::endl;\n\t\tdouble or_x = min_x - 4;\n\t\tdouble or_y = min_y - 4;\n\t\tint h = (max_y - min_y + 8) / 0.05 ;\n\t\tint width = (max_x - min_x + 8) / 0.05 ;\n\t\tcv::Mat tmp_line = cv::Mat::zeros(cv::Size(width, h), CV_8UC1);\n\t\tstd::vector<cv::Point> laser_pts;\n\t\tfor (size_t i = 0; i < rawCloud.points.size(); i++) {\n\t\t\t// std::cout << rawCloud.points[i].x << \"\\t\" << rawCloud.points[i].y << \"\\t\" << rawCloud.points[i].z << std::endl;\n\t\t\tdouble x = rawCloud.points[i].x;\n\t\t\tdouble y = rawCloud.points[i].y;\n\t\t\tint cell_x = (x - or_x) / 0.05;\n\t\t\tint cell_y =  h -  (y - or_y) / 0.05;\n\t\t\t// tmp_line.at<uchar>(cell_y,cell_x) =\n\n\t\t\tlaser_pts.push_back(cv::Point(cell_x, cell_y));\n\t\t}\n\t\tstd::vector<Eigen::Vector3d> line_params;\n\t\t// ROS_INFO(\"line size:%d\", laser_pts.size());\n\n\t\t// cv::Point last_pt ;\n\t\tint first = 1;\n\t\tint count = 0;\n\t\tEigen::Vector3d tmp_line_param;\n\t\tstd::vector<cv::Point> filter_laser_pts_;\n\t\t// std::vector<std::vector<cv::Point>> best_pts;\n\t\tcv::Mat show = tmp_line.clone();\n\t\tfor (auto&pt : laser_pts)\n\t\t{\n\t\t\tcv::circle(show, cv::Point(pt.x, pt.y), 2, cv::Scalar(255, 255, 255), -1);\n\n\t\t\tif (filter_laser_pts_.size() <= 1 || filter_laser_pts_.size() % 2 != 0)\n\t\t\t{\n\t\t\t\tfilter_laser_pts_.push_back(pt);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tauto& last_pt = filter_laser_pts_.back();\n\t\t\t\tauto& line_start_pt = filter_laser_pts_[filter_laser_pts_.size() - 2];\n\t\t\t\tdouble A = last_pt.y - line_start_pt.y;\n\t\t\t\tdouble B = line_start_pt.x - last_pt.x;\n\t\t\t\tdouble C = last_pt.x * line_start_pt.y\n\t\t\t\t           - line_start_pt.x * last_pt.y;\n\t\t\t\tdouble dist = fabs(A * pt.x * 1.0 + B * pt.y * 1.0 + C)\n\t\t\t\t              / ceres::sqrt(A * A + B * B);\n\t\t\t\t// ROS_INFO(\"line dst:%f\", dist);\n\t\t\t\t// std::cerr << \"dst is \" << dist * 0.05 << std::endl;\n\t\t\t\tif (dist * 0.05 <= 0.1)\n\t\t\t\t{\n\t\t\t\t\t// std::cerr << \"pop dst is \" << dist << std::endl;\n\n\t\t\t\t\tfilter_laser_pts_.pop_back();\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\n\t\t\t\t\t// if (dist < 0.789)\n\t\t\t\t\t// {\n\t\t\t\t\t// \tdouble pt_dst = sqrt(pow(last_pt.x - pt.x, 2) +\n\t\t\t\t\t// \t                     pow(last_pt.y - pt.y, 2));\n\t\t\t\t\t// \tif (pt_dst < 0.789)\n\t\t\t\t\t// \t{\n\t\t\t\t\t// \t\tfilter_laser_pts_.push_back(last_pt);\n\n\t\t\t\t\t// \t\tfilter_laser_pts_.push_back(pt);\n\t\t\t\t\t// \t}\n\n\t\t\t\t\t// }\n\t\t\t\t}\n\t\t\t\tfilter_laser_pts_.push_back(pt);\n\t\t\t}\n\t\t\tcv::imshow(\"test\", show);\n\t\t\tcv::waitKey(1);\n\t\t}\n\t\t// if (filter_laser_pts_.size() % 2 != 0)\n\t\t// {\n\t\t// \tfilter_laser_pts_.push_back(laser_pts.back());\n\t\t// }\n\t\t// for (auto&pt : filter_laser_pts_)\n\t\t// {\n\t\t// \tcv::circle(tmp_line, cv::Point(pt.x, pt.y), 2, cv::Scalar(255, 255, 255), -1);\n\t\t// \t// cv::imshow(\"test\", tmp_line);\n\t\t// \t// cv::waitKey(5);\n\t\t// }\n\t\t// std::vector<Eigen::Vector3d> line_params;\n\t\tfor (int i = 0; i < filter_laser_pts_.size() - 2; i = i + 2)\n\t\t{\n\t\t\t// cv::line(tmp_line, filter_laser_pts_[i], filter_laser_pts_[i + 1], cv::Scalar(180), 2);\n\t\t\t// cv::imshow(\"test\", tmp_line);\n\t\t\t// cv::waitKey(15);\n\t\t\tdouble A = filter_laser_pts_[i].y - filter_laser_pts_[i + 1].y;\n\t\t\tdouble B = filter_laser_pts_[i + 1].x - filter_laser_pts_[i].x;\n\t\t\tdouble C = filter_laser_pts_[i].x * filter_laser_pts_[i + 1].y\n\t\t\t           - filter_laser_pts_[i + 1].x * filter_laser_pts_[i].y;\n\t\t\tline_params.push_back(Eigen::Vector3d(A, B, C));\n\t\t}\n\t\tstd::vector<std::vector<cv::Point> > final_lines;\n\t\tstd::vector<Eigen::Vector3d> final_params;\n\t\tfor (auto&line : line_params)\n\t\t{\n\t\t\tstd::vector<cv::Point> pt_line;\n\t\t\tdouble A = line[0];\n\t\t\tdouble B = line[1];\n\t\t\tdouble C = line[2];\n\t\t\tauto pt = laser_pts.begin();\n\t\t\twhile (pt != laser_pts.end())\n\t\t\t{\n\t\t\t\tdouble dist = fabs(A * pt->x * 1.0 + B * pt->y * 1.0 + C)\n\t\t\t\t              / ceres::sqrt(A * A + B * B);\n\t\t\t\tif (dist * 0.05 < 0.15)\n\t\t\t\t{\n\t\t\t\t\tpt_line.push_back(*pt);\n\t\t\t\t\tpt = laser_pts.erase(pt);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tpt++;\n\t\t\t}\n\t\t\tif (pt_line.size() > 30)\n\t\t\t{\n\t\t\t\tfinal_lines.push_back(pt_line);\n\t\t\t\tfinal_params.push_back(line);\n\t\t\t}\n\t\t}\n\t\tcerr << \"finale line size is \" << final_lines.size() << endl;\n\n\t\tfor (auto&pts : final_lines)\n\t\t{\n\t\t\tfor (auto&pt : pts)\n\t\t\t{\n\t\t\t\tcv::circle(tmp_line, cv::Point(pt.x, pt.y), 2, cv::Scalar(255, 255, 255), -1);\n\t\t\t}\n\n\t\t\t// cv::imshow(\"test\", tmp_line);\n\t\t\t// cv::waitKey(1);\n\t\t}\n\n\n\t\tfor (auto&line : final_params)\n\t\t{\n\n\t\t}\n\n\t\t// cv::imshow(\"test\", tmp_line);\n\t\t// cv::waitKey(1);\n\t\tdouble main_k1 = 1;\n\t\tdouble main_k2 = -1;\n\n\t\t// double main_k[2] = { -line_params.front()[0] / line_params.front()[1], line_params.front()[1] / line_params.front()[0]};\n\n\t\tProblem problem;\n\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\t// CostFunction* cost_function =\n\t\t//     new AutoDiffCostFunction<CostFunctor, 1, 1>(new CostFunctor);\n\t\t// problem.AddResidualBlock(cost_function, NULL, &x);\n\n\t\t// // Run the solver!\n\t\tSolver::Options options;\n\t\t// options.linear_solver_type = ceres::DENSE_QR;\n\t\toptions.minimizer_progress_to_stdout = false;\n\t\tSolver::Summary summary;\n\t\tfor (auto&params : final_params)\n\t\t{\n\t\t\tif (params[1] == 0)\n\t\t\t{\n\t\t\t\tparams[1] = 0.000001;\n\t\t\t}\n\t\t\tif (params[0] == 0)\n\t\t\t{\n\t\t\t\tparams[0] = 0.000001;\n\t\t\t}\n\t\t\tcout << \"origin angle1 is \" << -params[0] / params[1] << endl;\n\t\t\tcout << \"origin angle2 is \" << params[1] / params[0] << endl;\n\t\t\tproblem.AddResidualBlock (     // \u5411\u95ee\u9898\u4e2d\u6dfb\u52a0\u8bef\u5dee\u9879\n\t\t\t    // \u4f7f\u7528\u81ea\u52a8\u6c42\u5bfc\uff0c\u6a21\u677f\u53c2\u6570\uff1a\u8bef\u5dee\u7c7b\u578b\uff0c\u8f93\u51fa\u7ef4\u5ea6\uff0c\u8f93\u5165\u7ef4\u5ea6\uff0c\u7ef4\u6570\u8981\u4e0e\u524d\u9762struct\u4e2d\u4e00\u81f4\n\t\t\t    new ceres::AutoDiffCostFunction<CostFunctor, 1, 2> (\n\t\t\t        new CostFunctor ( -params[0] / params[1], params[1] / params[0] )\n\t\t\t    ),\n\t\t\t    new ceres::CauchyLoss(0.5),            // \u6838\u51fd\u6570\uff0c\u8fd9\u91cc\u4e0d\u4f7f\u7528\uff0c\u4e3a\u7a7a\n\t\t\t    main_k                 // \u5f85\u4f30\u8ba1\u53c2\u6570\n\t\t\t);\n\t\t}\n\t\tSolve(options, &problem, &summary);\n\t\t// cout << summary.BriefReport() << endl;\n\t\tcout << \"angle1 is \" << main_k[0] << endl;\n\t\tcout << \"angle2 is \" << main_k[1] << endl;\n\t\tinput_.laser_ref = prev_ldp_scan_;\n\n\t}\n\n\tdouble line1 = ceres::atan(main_k[0]);\n\tdouble line2 =  ceres::atan(-1 / main_k[0]);\n\tdouble angle;\n\tif (fabs(line1) < fabs(line2))\n\t{\n\t\tangle = line1;\n\t}\n\telse\n\t{\n\t\tangle = line2;\n\t}\n\treturn angle;\n}\n\nint main(int argc, char **argv)\n{\n\tros::init(argc, argv, \"laser_detector\");\n\n\n\tros::NodeHandle nh;\n\tsm_params input_;\n\n\t{\n\t\tif (!nh.getParam (\"max_angular_correction_deg\", input_.max_angular_correction_deg))\n\t\t\tinput_.max_angular_correction_deg = 100.0;\n\n\t\t// Maximum translation between scans (m)\n\t\tif (!nh.getParam (\"max_linear_correction\", input_.max_linear_correction))\n\t\t\tinput_.max_linear_correction = 0.50;\n\n\t\t// Maximum ICP cycle iterations\n\t\tif (!nh.getParam (\"max_iterations\", input_.max_iterations))\n\t\t\tinput_.max_iterations = 10;\n\n\t\t// A threshold for stopping (m)\n\t\tif (!nh.getParam (\"epsilon_xy\", input_.epsilon_xy))\n\t\t\tinput_.epsilon_xy = 0.000001;\n\n\t\t// A threshold for stopping (rad)\n\t\tif (!nh.getParam (\"epsilon_theta\", input_.epsilon_theta))\n\t\t\tinput_.epsilon_theta = 0.000001;\n\n\t\t// Maximum distance for a correspondence to be valid\n\t\tif (!nh.getParam (\"max_correspondence_dist\", input_.max_correspondence_dist))\n\t\t\tinput_.max_correspondence_dist = 0.3;\n\n\t\t// Noise in the scan (m)\n\t\tif (!nh.getParam (\"sigma\", input_.sigma))\n\t\t\tinput_.sigma = 0.010;\n\n\t\t// Use smart tricks for finding correspondences.\n\t\tif (!nh.getParam (\"use_corr_tricks\", input_.use_corr_tricks))\n\t\t\tinput_.use_corr_tricks = 1;\n\n\t\t// Restart: Restart if error is over threshold\n\t\tif (!nh.getParam (\"restart\", input_.restart))\n\t\t\tinput_.restart = 0;\n\n\t\t// Restart: Threshold for restarting\n\t\tif (!nh.getParam (\"restart_threshold_mean_error\", input_.restart_threshold_mean_error))\n\t\t\tinput_.restart_threshold_mean_error = 0.01;\n\n\t\t// Restart: displacement for restarting. (m)\n\t\tif (!nh.getParam (\"restart_dt\", input_.restart_dt))\n\t\t\tinput_.restart_dt = 1.0;\n\n\t\t// Restart: displacement for restarting. (rad)\n\t\tif (!nh.getParam (\"restart_dtheta\", input_.restart_dtheta))\n\t\t\tinput_.restart_dtheta = 0.1;\n\n\t\t// Max distance for staying in the same clustering\n\t\tif (!nh.getParam (\"clustering_threshold\", input_.clustering_threshold))\n\t\t\tinput_.clustering_threshold = 0.25;\n\n\t\t// Number of neighbour rays used to estimate the orientation\n\t\tif (!nh.getParam (\"orientation_neighbourhood\", input_.orientation_neighbourhood))\n\t\t\tinput_.orientation_neighbourhood = 20;\n\n\t\t// If 0, it's vanilla ICP\n\t\tif (!nh.getParam (\"use_point_to_line_distance\", input_.use_point_to_line_distance))\n\t\t\tinput_.use_point_to_line_distance = 1;\n\n\t\t// Discard correspondences based on the angles\n\t\tif (!nh.getParam (\"do_alpha_test\", input_.do_alpha_test))\n\t\t\tinput_.do_alpha_test = 0;\n\n\t\t// Discard correspondences based on the angles - threshold angle, in degrees\n\t\tif (!nh.getParam (\"do_alpha_test_thresholdDeg\", input_.do_alpha_test_thresholdDeg))\n\t\t\tinput_.do_alpha_test_thresholdDeg = 20.0;\n\n\t\t// Percentage of correspondences to consider: if 0.9,\n\t\t// always discard the top 10% of correspondences with more error\n\t\tif (!nh.getParam (\"outliers_maxPerc\", input_.outliers_maxPerc))\n\t\t\tinput_.outliers_maxPerc = 0.90;\n\n\t\t// Parameters describing a simple adaptive algorithm for discarding.\n\t\t//  1) Order the errors.\n\t\t//  2) Choose the percentile according to outliers_adaptive_order.\n\t\t//     (if it is 0.7, get the 70% percentile)\n\t\t//  3) Define an adaptive threshold multiplying outliers_adaptive_mult\n\t\t//     with the value of the error at the chosen percentile.\n\t\t//  4) Discard correspondences over the threshold.\n\t\t//  This is useful to be conservative; yet remove the biggest errors.\n\t\tif (!nh.getParam (\"outliers_adaptive_order\", input_.outliers_adaptive_order))\n\t\t\tinput_.outliers_adaptive_order = 0.7;\n\n\t\tif (!nh.getParam (\"outliers_adaptive_mult\", input_.outliers_adaptive_mult))\n\t\t\tinput_.outliers_adaptive_mult = 2.0;\n\n\t\t// If you already have a guess of the solution, you can compute the polar angle\n\t\t// of the points of one scan in the new position. If the polar angle is not a monotone\n\t\t// function of the readings index, it means that the surface is not visible in the\n\t\t// next position. If it is not visible, then we don't use it for matching.\n\t\tif (!nh.getParam (\"do_visibility_test\", input_.do_visibility_test))\n\t\t\tinput_.do_visibility_test = 0;\n\n\t\t// no two points in laser_sens can have the same corr.\n\t\tif (!nh.getParam (\"outliers_remove_doubles\", input_.outliers_remove_doubles))\n\t\t\tinput_.outliers_remove_doubles = 1;\n\n\t\t// If 1, computes the covariance of ICP using the method http://purl.org/censi/2006/icpcov\n\t\tif (!nh.getParam (\"do_compute_covariance\", input_.do_compute_covariance))\n\t\t\tinput_.do_compute_covariance = 0;\n\n\t\t// Checks that find_correspondences_tricks gives the right answer\n\t\tif (!nh.getParam (\"debug_verify_tricks\", input_.debug_verify_tricks))\n\t\t\tinput_.debug_verify_tricks = 0;\n\n\t\t// If 1, the field 'true_alpha' (or 'alpha') in the first scan is used to compute the\n\t\t// incidence beta, and the factor (1/cos^2(beta)) used to weight the correspondence.\");\n\t\tif (!nh.getParam (\"use_ml_weights\", input_.use_ml_weights))\n\t\t\tinput_.use_ml_weights = 0;\n\n\t\t// If 1, the field 'readings_sigma' in the second scan is used to weight the\n\t\t// correspondence by 1/sigma^2\n\t\tif (!nh.getParam (\"use_sigma_weights\", input_.use_sigma_weights))\n\t\t\tinput_.use_sigma_weights = 0;\n\t}\n\tros::Publisher cmd_pub_ = nh.advertise<geometry_msgs::Twist>(\"cmd_vel\", 100);\n\n\t{\n\t\tLDP curr_ldp_scan;\n\t\tdouble angle = get_laser_line(input_);\n\t\tcerr << \"tmp value is \" << angle << endl;\n\t\t// double line1 = ceres::atan(main_k);\n\t\t// double line2 =  ceres::atan(-1 / main_k);\n\t\t// double angle;\n\t\t// if (fabs(line1) < fabs(line2))\n\t\t// {\n\t\t// \tangle = line1;\n\t\t// }\n\t\t// else\n\t\t// {\n\t\t// \tangle = line2;\n\t\t// }\n\t\t// double angle = (ceres::atan( -final_params.back()[0] / final_params.back()[1]));\n\t\tcerr << 180 * angle / M_PI << endl;\n\t\tgeometry_msgs::Twist tmp ;\n\t\tif (angle > 0)\n\t\t{\n\t\t\ttmp.angular.z = -0.03;\n\t\t\tangle *= -1;\n\t\t}\n\t\telse\n\t\t{\n\t\t\ttmp.angular.z = 0.03;\n\n\t\t\tangle *= -1;\n\t\t}\n\n\t\tinput_.first_guess[2] = angle;\n\t\tdouble t = fabs(angle) / 0.03 ;\n\t\tdouble t0 = (ros::Time::now()).toSec();\n\t\tcerr << t << endl;\n\n\t\tsm_result output_;\n\t\toutput_.cov_x_m = 0;\n\t\toutput_.dx_dy1_m = 0;\n\t\toutput_.dx_dy2_m = 0;\n\t\twhile (true)\n\t\t{\n\t\t\t// double tt = (ros::Time::now()).toSec();\n\t\t\tdouble t1 = (ros::Time::now()).toSec();\n\t\t\tcmd_pub_.publish(tmp);\n\t\t\tif (t1 - t0 > t)\n\t\t\t{\n\n\t\t\t\tcerr << t1 - t0 << endl;\n\t\t\t\ttmp.angular.z = 0;\n\t\t\t\tcmd_pub_.publish(tmp);\n\n\t\t\t\tboost::shared_ptr<sensor_msgs::LaserScan const> new_scan_ptr = nullptr;  // \u6709const\n\t\t\t\tcerr << \"restart\" << endl;\n\t\t\t\twhile (new_scan_ptr == nullptr) {\n\t\t\t\t\tcerr << \"wait\" << endl;\n\t\t\t\t\tnew_scan_ptr = ros::topic::waitForMessage<sensor_msgs::LaserScan>(\"scan\", ros::Duration(10));\n\t\t\t\t}\n\n\t\t\t\tlaserScanToLDP(new_scan_ptr, curr_ldp_scan);\n\t\t\t\tinput_.laser_sens = curr_ldp_scan;\n\t\t\t\tcerr << \"bug-1\" << endl;\n\n\t\t\t\tif (output_.cov_x_m)\n\t\t\t\t{\n\t\t\t\t\tgsl_matrix_free(output_.cov_x_m);\n\t\t\t\t\toutput_.cov_x_m = 0;\n\t\t\t\t}\n\t\t\t\tif (output_.dx_dy1_m)\n\t\t\t\t{\n\t\t\t\t\tgsl_matrix_free(output_.dx_dy1_m);\n\t\t\t\t\toutput_.dx_dy1_m = 0;\n\t\t\t\t}\n\t\t\t\tif (output_.dx_dy2_m)\n\t\t\t\t{\n\t\t\t\t\tgsl_matrix_free(output_.dx_dy2_m);\n\t\t\t\t\toutput_.dx_dy2_m = 0;\n\t\t\t\t}\n\t\t\t\tcerr << \"bug-21\" << endl;\n\t\t\t\tsm_icp(&input_, &output_);\n\t\t\t\tcerr << \"bug-22\" << endl;\n\t\t\t\tdouble match_angle;\n\n\t\t\t\tif (output_.valid)\n\t\t\t\t{\n\t\t\t\t\t// the correction of the laser's position, in the laser frame\n\t\t\t\t\tmatch_angle = output_.x[2];\n\t\t\t\t\tinput_.first_guess[2] = match_angle;\n\n\t\t\t\t\tif (fabs(match_angle - angle) <= 0.01)\n\t\t\t\t\t{\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tif (angle > 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tdouble delta_angle = angle - match_angle ;\n\t\t\t\t\t\t\tt = fabs(delta_angle) / 0.03;\n\t\t\t\t\t\t\tt0 = (ros::Time::now()).toSec();\n\t\t\t\t\t\t\ttmp.angular.z = delta_angle < 0 ? -0.03 : 0.03;\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\tdouble delta_angle = angle - match_angle ;\n\t\t\t\t\t\t\tt = fabs(delta_angle) / 0.03;\n\t\t\t\t\t\t\tt0 = (ros::Time::now()).toSec();\n\t\t\t\t\t\t\ttmp.angular.z = delta_angle < 0 ? 0.03 : -0.03;\n\t\t\t\t\t\t}\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\tROS_WARN(\"Error in scan matching\");\n\t\t\t\t\tcerr << \"none result\" << endl;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t}\n\t\t\t// double tt1 = (ros::Time::now()).toSec();\n\t\t\t// cerr <<\"time is \" << tt1 - tt << endl;\n\t\t\t// break;\n\t\t}\n\n\t\t// cmd_pub_.publish(tmp);\n\t\tcerr << \"over\" << endl;\n\n\t}\n\n\t// ros::spinOnce();\n\n\tcv::waitKey(1);\n\tros::shutdown();\n\treturn 0;\n}", "meta": {"hexsha": "fe664697fbe7485ed38322df23906bd9ef47a082", "size": 18348, "ext": "cc", "lang": "C++", "max_stars_repo_path": "example/test.cc", "max_stars_repo_name": "min-zou/laser_line_detector", "max_stars_repo_head_hexsha": "f47a19ba2bf2829ff6c11723806dac0470e9a8cb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/test.cc", "max_issues_repo_name": "min-zou/laser_line_detector", "max_issues_repo_head_hexsha": "f47a19ba2bf2829ff6c11723806dac0470e9a8cb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/test.cc", "max_forks_repo_name": "min-zou/laser_line_detector", "max_forks_repo_head_hexsha": "f47a19ba2bf2829ff6c11723806dac0470e9a8cb", "max_forks_repo_licenses": ["Apache-2.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.9314845024, "max_line_length": 125, "alphanum_fraction": 0.6328210159, "num_tokens": 6111, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066295, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4905588358589977}}
{"text": "/**\n * trajectory generator for testing the visual ekf\n */\n#include <iostream>\n#include <ros/ros.h>\n#include <sensor_msgs/Imu.h>\n#include <nav_msgs/Odometry.h>\n#include <geometry_msgs/TwistStamped.h>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include \"qp_generator.h\"\n\nusing namespace std;\nusing namespace Eigen;\nros::Publisher imu_pub, visual_pub, debug_pub;\n\nconst int update_freq = 400; // 1 / dt\nconst double dt = 0.0025;\n\nvoid pub_imu(const Vector3d& acc, const Quaterniond& orientation){\n    sensor_msgs::Imu imu;\n    imu.header.stamp = ros::Time::now();\n    imu.orientation.w = orientation.w();\n    imu.orientation.x = orientation.x();\n    imu.orientation.y = orientation.y();\n    imu.orientation.z = orientation.z();\n    imu.linear_acceleration.x = acc[0];\n    imu.linear_acceleration.y = acc[1];\n    imu.linear_acceleration.z = acc[2] + 9.8;\n\n    imu_pub.publish(imu);\n}\n\n/**\n * Change the world frame position to the camera frame, and publish in millimeter\n * @param pos\n */\nvoid pub_visual(const Vector3d& pos) {\n    geometry_msgs::TwistStamped pose;\n    pose.header.stamp = ros::Time::now();\n\n    MatrixXd imu_R_camera = MatrixXd::Identity(3, 3);\n    imu_R_camera <<  0, 0, 1,\n                    -1, 0, 0,\n                     0,-1, 0;\n\n    Vector3d pos_camera = imu_R_camera.transpose() * (1000 * pos);\n    pose.twist.linear.x = pos_camera[0];\n    pose.twist.linear.y = pos_camera[1];\n    pose.twist.linear.z = pos_camera[2];\n\n    visual_pub.publish(pose);\n}\n\nvoid pub_debug(const Vector3d& pos, const Vector3d& vel, const Vector3d& acc)\n{\n    nav_msgs::Odometry odom;\n    odom.header.stamp = ros::Time::now();\n\n    odom.child_frame_id = \"world\";\n    odom.pose.pose.position.x = pos[0];\n    odom.pose.pose.position.y = pos[1];\n    odom.pose.pose.position.z = pos[2];\n    odom.twist.twist.linear.x = vel[0];\n    odom.twist.twist.linear.y = vel[1];\n    odom.twist.twist.linear.z = vel[2];\n    odom.twist.twist.angular.x= acc[0];\n    odom.twist.twist.angular.y= acc[1];\n    odom.twist.twist.angular.z= acc[2];\n\n    debug_pub.publish(odom);\n}\n\n// get position from coefficient\nvoid getPositionFromCoeff(Eigen::Vector3d &pos, const Eigen::MatrixXd &coeff,\n                                             const int &index, const double &time)\n{\n    int s = index;\n    double t = time;\n    double x = coeff(s, 0) + coeff(s, 1) * t + coeff(s, 2) * pow(t, 2) + coeff(s, 3) * pow(t, 3) +\n               coeff(s, 4) * pow(t, 4) + coeff(s, 5) * pow(t, 5);\n    double y = coeff(s, 6) + coeff(s, 7) * t + coeff(s, 8) * pow(t, 2) + coeff(s, 9) * pow(t, 3) +\n               coeff(s, 10) * pow(t, 4) + coeff(s, 11) * pow(t, 5);\n    double z = coeff(s, 12) + coeff(s, 13) * t + coeff(s, 14) * pow(t, 2) + coeff(s, 15) * pow(t, 3) +\n               coeff(s, 16) * pow(t, 4) + coeff(s, 17) * pow(t, 5);\n\n    pos(0) = x;\n    pos(1) = y;\n    pos(2) = z;\n}\n\n// get velocity from cofficient\nvoid getVelocityFromCoeff(Eigen::Vector3d &vel, const Eigen::MatrixXd &coeff,\n                                             const int &index, const double &time)\n{\n    int s = index;\n    double t = time;\n    double vx = coeff(s, 1) + 2 * coeff(s, 2) * pow(t, 1) + 3 * coeff(s, 3) * pow(t, 2) +\n                4 * coeff(s, 4) * pow(t, 3) + 5 * coeff(s, 5) * pow(t, 4);\n    double vy = coeff(s, 7) + 2 * coeff(s, 8) * pow(t, 1) + 3 * coeff(s, 9) * pow(t, 2) +\n                4 * coeff(s, 10) * pow(t, 3) + 5 * coeff(s, 11) * pow(t, 4);\n    double vz = coeff(s, 13) + 2 * coeff(s, 14) * pow(t, 1) + 3 * coeff(s, 15) * pow(t, 2) +\n                4 * coeff(s, 16) * pow(t, 3) + 5 * coeff(s, 17) * pow(t, 4);\n\n    vel(0) = vx;\n    vel(1) = vy;\n    vel(2) = vz;\n}\n\n// get acceleration from coefficient\nvoid getAccelerationFromCoeff(Eigen::Vector3d &acc, const Eigen::MatrixXd &coeff,\n                                                 const int &index, const double &time)\n{\n    int s = index;\n    double t = time;\n    double ax = 2 * coeff(s, 2) + 6 * coeff(s, 3) * pow(t, 1) + 12 * coeff(s, 4) * pow(t, 2) +\n               20 * coeff(s, 5) * pow(t, 3);\n    double ay = 2 * coeff(s, 8) + 6 * coeff(s, 9) * pow(t, 1) + 12 * coeff(s, 10) * pow(t, 2) +\n               20 * coeff(s, 11) * pow(t, 3);\n    double az = 2 * coeff(s, 14) + 6 * coeff(s, 15) * pow(t, 1) + 12 * coeff(s, 16) * pow(t, 2) +\n               20 * coeff(s, 17) * pow(t, 3);\n\n    acc(0) = ax;\n    acc(1) = ay;\n    acc(2) = az;\n}\n\nint main(int argc, char **argv) {\n    ros::init(argc, argv, \"visual_ekf_tester\");\n    ros::NodeHandle n(\"~\");\n\n    imu_pub    = n.advertise<sensor_msgs::Imu>(\"/visual_ekf/test_imu\", 400);\n    visual_pub = n.advertise<geometry_msgs::TwistStamped>(\"/visual_ekf/test_visual\", 50);\n    debug_pub  = n.advertise<nav_msgs::Odometry>(\"/visual_ekf_tester/odom\", 50);\n\n    ros::Rate r(update_freq);\n\n    MatrixXd Path = MatrixXd::Zero(3, 3);\n    Path.block<1, 3>(0, 0) = Vector3d(0.6, 0.2, 0.1);\n    Path.block<1, 3>(1, 0) = Vector3d(0.8, 0.2, 0.1);\n    Path.block<1, 3>(2, 0) = Vector3d(1, 0, 0);\n\n    Vector3d Vel_init(0, 0, 0);\n    Vector3d Acc_init(0, 0, 0);\n    VectorXd time_period = MatrixXd::Zero(2, 1);\n    time_period << 5.0, 5.0;\n    VectorXd time_int = time_period;\n\n    // generate a smooth curve\n    TrajectoryGenerator generator;\n    MatrixXd coeff = generator.PolyQPGeneration(\n            Path, Vel_init, Acc_init, time_period, 1);\n    cout << \"polynomial \" << endl << coeff << endl;\n\n    auto t_start = ros::Time::now().toSec();\n    int iterator = 0;\n    auto time_period_size = (int)time_period.size();\n\n    // provide the orientation, rotate in Z axis first\n    Vector3d axis_z = Vector3d::UnitZ();\n    VectorXd theta = MatrixXd::Zero(3, 1);\n    theta[0] = 0.0;\n    theta[1] = 0.1 * M_PI;\n    theta[2] = 0.25 * M_PI;\n\n    while (ros::ok()) {\n\n        double dt = ros::Time::now().toSec() - t_start;\n\n        if (iterator < time_period_size) {\n            if (dt > time_period[iterator]) {\n                dt -= time_period[iterator];\n                t_start += time_period[iterator];\n                iterator++;\n                ROS_INFO(\"In polynomial section %d\", iterator);\n            }\n        }\n\n        if (iterator < time_period_size) {\n            Vector3d pos, vel, acc;\n            getPositionFromCoeff(pos, coeff, iterator, dt);\n            getVelocityFromCoeff(vel, coeff, iterator, dt);\n            getAccelerationFromCoeff(acc, coeff, iterator, dt);\n\n            double omg = (theta[iterator+1] - theta[iterator]) / time_period[iterator];\n            double angle = omg * dt + theta[iterator];\n            AngleAxisd orientation(angle, axis_z);\n            Quaterniond q(orientation);\n\n            Vector3d acc_imu = q.conjugate() * acc;\n            pub_imu(acc_imu, q);\n\n            Vector3d pos_imu = q.conjugate() * pos;\n            pub_visual(pos_imu);\n\n            Vector3d vel_imu = q.conjugate() * vel;\n            pub_debug(pos_imu, vel_imu, acc_imu);\n        }\n\n        r.sleep();\n        ros::spinOnce();\n    }\n}\n", "meta": {"hexsha": "e10200ea5a00d6c2ecf80e1e5fd866372c93073d", "size": 6920, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "4_planning/visual_ekf_tester/src/visual_ekf_tester_node.cpp", "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": "4_planning/visual_ekf_tester/src/visual_ekf_tester_node.cpp", "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": "4_planning/visual_ekf_tester/src/visual_ekf_tester_node.cpp", "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": 33.9215686275, "max_line_length": 102, "alphanum_fraction": 0.5650289017, "num_tokens": 2210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.5813030906443134, "lm_q1q2_score": 0.4905588312945554}}
{"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_5FD6A664ACC811DEAAFF8A8055D89593\n#define UUID_5FD6A664ACC811DEAAFF8A8055D89593\n\n#include <boost/qvm/inline.hpp>\n#include <math.h>\n\nnamespace boost {\nnamespace qvm {\ntemplate <class T> T acos(T);\ntemplate <class T> T asin(T);\ntemplate <class T> T atan(T);\ntemplate <class T> T atan2(T, T);\ntemplate <class T> T cos(T);\ntemplate <class T> T sin(T);\ntemplate <class T> T tan(T);\ntemplate <class T> T cosh(T);\ntemplate <class T> T sinh(T);\ntemplate <class T> T tanh(T);\ntemplate <class T> T exp(T);\ntemplate <class T> T log(T);\ntemplate <class T> T log10(T);\ntemplate <class T> T mod(T, T);\ntemplate <class T> T pow(T, T);\ntemplate <class T> T sqrt(T);\ntemplate <class T> T ceil(T);\ntemplate <class T> T abs(T);\ntemplate <class T> T floor(T);\ntemplate <class T> T mod(T, T);\ntemplate <class T> T ldexp(T, int);\ntemplate <class T> T sign(T);\n\ntemplate <> BOOST_QVM_INLINE_TRIVIAL float acos<float>(float x) {\n  return ::acosf(x);\n}\ntemplate <> BOOST_QVM_INLINE_TRIVIAL float asin<float>(float x) {\n  return ::asinf(x);\n}\ntemplate <> BOOST_QVM_INLINE_TRIVIAL float atan<float>(float x) {\n  return ::atanf(x);\n}\ntemplate <> BOOST_QVM_INLINE_TRIVIAL float atan2<float>(float x, float y) {\n  return ::atan2f(x, y);\n}\ntemplate <> BOOST_QVM_INLINE_TRIVIAL float cos<float>(float x) {\n  return ::cosf(x);\n}\ntemplate <> BOOST_QVM_INLINE_TRIVIAL float sin<float>(float x) {\n  return ::sinf(x);\n}\ntemplate <> BOOST_QVM_INLINE_TRIVIAL float tan<float>(float x) {\n  return ::tanf(x);\n}\ntemplate <> BOOST_QVM_INLINE_TRIVIAL float cosh<float>(float x) {\n  return ::coshf(x);\n}\ntemplate <> BOOST_QVM_INLINE_TRIVIAL float sinh<float>(float x) {\n  return ::sinhf(x);\n}\ntemplate <> BOOST_QVM_INLINE_TRIVIAL float tanh<float>(float x) {\n  return ::tanhf(x);\n}\ntemplate <> BOOST_QVM_INLINE_TRIVIAL float exp<float>(float x) {\n  return ::expf(x);\n}\ntemplate <> BOOST_QVM_INLINE_TRIVIAL float log<float>(float x) {\n  return ::logf(x);\n}\ntemplate <> BOOST_QVM_INLINE_TRIVIAL float log10<float>(float x) {\n  return ::log10f(x);\n}\ntemplate <> BOOST_QVM_INLINE_TRIVIAL float mod<float>(float x, float y) {\n  return ::fmodf(x, y);\n}\ntemplate <> BOOST_QVM_INLINE_TRIVIAL float pow<float>(float x, float y) {\n  return ::powf(x, y);\n}\ntemplate <> BOOST_QVM_INLINE_TRIVIAL float sqrt<float>(float x) {\n  return ::sqrtf(x);\n}\ntemplate <> BOOST_QVM_INLINE_TRIVIAL float ceil<float>(float x) {\n  return ::ceilf(x);\n}\ntemplate <> BOOST_QVM_INLINE_TRIVIAL float abs<float>(float x) {\n  return ::fabsf(x);\n}\ntemplate <> BOOST_QVM_INLINE_TRIVIAL float floor<float>(float x) {\n  return ::floorf(x);\n}\ntemplate <> BOOST_QVM_INLINE_TRIVIAL float ldexp<float>(float x, int y) {\n  return ::ldexpf(x, y);\n}\ntemplate <> BOOST_QVM_INLINE_TRIVIAL float sign<float>(float x) {\n  return x < 0 ? -1.f : +1.f;\n}\n\ntemplate <> BOOST_QVM_INLINE_TRIVIAL double acos<double>(double x) {\n  return ::acos(x);\n}\ntemplate <> BOOST_QVM_INLINE_TRIVIAL double asin<double>(double x) {\n  return ::asin(x);\n}\ntemplate <> BOOST_QVM_INLINE_TRIVIAL double atan<double>(double x) {\n  return ::atan(x);\n}\ntemplate <> BOOST_QVM_INLINE_TRIVIAL double atan2<double>(double x, double y) {\n  return ::atan2(x, y);\n}\ntemplate <> BOOST_QVM_INLINE_TRIVIAL double cos<double>(double x) {\n  return ::cos(x);\n}\ntemplate <> BOOST_QVM_INLINE_TRIVIAL double sin<double>(double x) {\n  return ::sin(x);\n}\ntemplate <> BOOST_QVM_INLINE_TRIVIAL double tan<double>(double x) {\n  return ::tan(x);\n}\ntemplate <> BOOST_QVM_INLINE_TRIVIAL double cosh<double>(double x) {\n  return ::cosh(x);\n}\ntemplate <> BOOST_QVM_INLINE_TRIVIAL double sinh<double>(double x) {\n  return ::sinh(x);\n}\ntemplate <> BOOST_QVM_INLINE_TRIVIAL double tanh<double>(double x) {\n  return ::tanh(x);\n}\ntemplate <> BOOST_QVM_INLINE_TRIVIAL double exp<double>(double x) {\n  return ::exp(x);\n}\ntemplate <> BOOST_QVM_INLINE_TRIVIAL double log<double>(double x) {\n  return ::log(x);\n}\ntemplate <> BOOST_QVM_INLINE_TRIVIAL double log10<double>(double x) {\n  return ::log10(x);\n}\ntemplate <> BOOST_QVM_INLINE_TRIVIAL double mod<double>(double x, double y) {\n  return ::fmod(x, y);\n}\ntemplate <> BOOST_QVM_INLINE_TRIVIAL double pow<double>(double x, double y) {\n  return ::pow(x, y);\n}\ntemplate <> BOOST_QVM_INLINE_TRIVIAL double sqrt<double>(double x) {\n  return ::sqrt(x);\n}\ntemplate <> BOOST_QVM_INLINE_TRIVIAL double ceil<double>(double x) {\n  return ::ceil(x);\n}\ntemplate <> BOOST_QVM_INLINE_TRIVIAL double abs<double>(double x) {\n  return ::fabs(x);\n}\ntemplate <> BOOST_QVM_INLINE_TRIVIAL double floor<double>(double x) {\n  return ::floor(x);\n}\ntemplate <> BOOST_QVM_INLINE_TRIVIAL double ldexp<double>(double x, int y) {\n  return ::ldexp(x, y);\n}\ntemplate <> BOOST_QVM_INLINE_TRIVIAL double sign<double>(double x) {\n  return x < 0 ? -1.0 : +1.0;\n}\n} // namespace qvm\n} // namespace boost\n\n#endif\n", "meta": {"hexsha": "e924311fcb896239bb7b7f843b5323243daed17a", "size": 5006, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/boost_1_72_0/boost/qvm/math.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/math.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/math.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": 29.7976190476, "max_line_length": 79, "alphanum_fraction": 0.7121454255, "num_tokens": 1467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.5813030906443134, "lm_q1q2_score": 0.4905588267301129}}
{"text": "#include <iostream>\n#include <fstream>\n#include <vector>\n#include <string>\n#include <map>\n#include <unordered_map>\n#include <cstdlib>\n\n#include <boost/algorithm/string.hpp>\n#include <boost/lexical_cast.hpp>\n\n#include \"Day4.hpp\"\n\nbool isValidPassword(int number);\n\nvoid day4() {\n\tstd::ifstream inputFile(\"Data/Day4.txt\");\n\tstd::string line;\n\tstd::getline(inputFile, line);\n\n\tstd::vector<std::string> numbersStr;\n\tboost::split(numbersStr, line, boost::is_any_of(\"-\"), boost::token_compress_on);\n\n\tstd::vector<int> numbers;\n\tstd::transform(numbersStr.begin(), numbersStr.end(), std::back_inserter(numbers), &boost::lexical_cast<int, std::string>);\n\n\t// Cheating\n\tint minNumber = numbers[0];\n\tint maxNumber = numbers[1];\n\t\n\tint countValidPassword = 0;\n\tfor (int i = minNumber; i < maxNumber; ++i) {\n\t\tif (isValidPassword(i)) {\n\t\t\tcountValidPassword++;\n\t\t}\n\t}\n\t\n\tstd::cout << countValidPassword << std::endl;\n}\n\nbool isValidPassword(int number) {\n\tstd::string numberStr = std::to_string(number);\n\n\t//It is a six - digit number.\n\t//The value is within the range given in your puzzle input.\n\t// Handled by for loop\n\n\t//Two adjacent digits are the same(like 22 in 122345).\n\tif (!(\n\t\t(\t\t\t\t\t\t\t\t\t\tnumberStr.at(0) == numberStr.at(1) && numberStr.at(1) != numberStr.at(2)) ||\n\t\t(numberStr.at(0) != numberStr.at(1) &&\tnumberStr.at(1) == numberStr.at(2) && numberStr.at(2) != numberStr.at(3)) ||\n\t\t(numberStr.at(1) != numberStr.at(2) &&\tnumberStr.at(2) == numberStr.at(3) && numberStr.at(3) != numberStr.at(4)) ||\n\t\t(numberStr.at(2) != numberStr.at(3) &&\tnumberStr.at(3) == numberStr.at(4) && numberStr.at(4) != numberStr.at(5)) ||\n\t\t(numberStr.at(3) != numberStr.at(4) &&\tnumberStr.at(4) == numberStr.at(5)\t\t\t\t\t\t\t\t\t\t)\n\t\t\t)) {\n\t\t\treturn false;\n\t}\n\n\t//Going from left to right, the digits never decrease; they only ever increase or stay the same(like 111123 or 135679).\n\tif (numberStr.at(0) > numberStr.at(1) || \n\t\tnumberStr.at(1) > numberStr.at(2) || \n\t\tnumberStr.at(2) > numberStr.at(3) || \n\t\tnumberStr.at(3) > numberStr.at(4) || \n\t\tnumberStr.at(4) > numberStr.at(5)) {\n\t\treturn false;\n\t}\n\n\treturn true;\n}", "meta": {"hexsha": "15f725df6af54afa61c79137b964516e44b438c6", "size": 2091, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AdventOfCode2019/Src/Day4.cpp", "max_stars_repo_name": "Epono/AdventOfCode2019", "max_stars_repo_head_hexsha": "d035b8943a7e9b96491ed7a499e98101c08256c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AdventOfCode2019/Src/Day4.cpp", "max_issues_repo_name": "Epono/AdventOfCode2019", "max_issues_repo_head_hexsha": "d035b8943a7e9b96491ed7a499e98101c08256c1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AdventOfCode2019/Src/Day4.cpp", "max_forks_repo_name": "Epono/AdventOfCode2019", "max_forks_repo_head_hexsha": "d035b8943a7e9b96491ed7a499e98101c08256c1", "max_forks_repo_licenses": ["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.3043478261, "max_line_length": 123, "alphanum_fraction": 0.6618842659, "num_tokens": 631, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.6654105720171531, "lm_q1q2_score": 0.4905128346618658}}
{"text": "#include <vector>\n#include <iostream>\n#include \"../incl/graph_creator.h\"\n#include \"../incl/bellman_ford.h\"\n#include \"../incl/graph_printer.h\"\n#include \"../incl/bellman_ford_test.h\"\n#include <boost/program_options.hpp>\n\nunsigned long nodes;\nunsigned long edges = 0;\nint times;\nint minWeight;\nint maxWeight;\n\n/**\n * Prints usage message.\n*/\nboost::program_options::variables_map parseArguments(int argc, char *const *argv)\n{\n    boost::program_options::options_description options(\"Usage\");\n    options.add_options()\n            (\"test\", \"run all tests\")\n            (\"run\", \"runs with specified graph\")\n            (\"benchmark\", \"runs benchmark with specified graph\")\n            (\"help\", \"produce help message\")\n            (\"random\", \"random connected graph\")\n            (\"grid\", \"modified grid graph with negative cycle (worst case for bellman ford)\")\n            (\"nodes,n\", boost::program_options::value<unsigned long>(&nodes), \"number of nodes (default=100)\")\n            (\"edges,e\", boost::program_options::value<unsigned long>(&edges), \"number of edges for random graphs (default 20*nodes*log10(nodes))\")\n            (\"times,t\", boost::program_options::value<int>(&times), \"number of times to run the benchmark\")\n            (\"min-weight\", boost::program_options::value<int>(&minWeight), \"minimum edge weight (default=-100)\")\n            (\"max-weight\", boost::program_options::value<int>(&maxWeight), \"maximum edge weight (default=10000)\")\n            ;\n\n    boost::program_options::variables_map vm;\n    store(parse_command_line(argc, argv, options), vm);\n    notify(vm);\n\n    if (vm.count(\"help\") || argc < 2) {\n        std::cout << options << \"\\n\";\n        exit(1);\n    }\n\n    return vm;\n}\n\n\nint main(int argc, char **argv)\n{\n    const int INF = (std::numeric_limits < int >::max)();\n    nodes = 100;\n    times = 1;\n    minWeight = -100;\n    maxWeight = 10000;\n\n    boost::program_options::variables_map args = parseArguments(argc, argv);\n    if (edges==0) {\n        edges = static_cast<unsigned long>(20 * nodes * log10(nodes));\n    }\n\n    if (args.count(\"test\")) {\n        testAll();\n    }\n    else if (args.count(\"benchmark\") && args.count(\"random\")) {\n        Graph G = createRandomGraph(nodes, edges, minWeight, maxWeight);\n        std::cout << \"[i] Benchmark random graph \" << nodes << \"x\" << edges << std::endl;\n        benchmark(G, times);\n    }\n    else if (args.count(\"benchmark\") && args.count(\"grid\")) {\n        Graph G = createGridGraph(static_cast<int>(nodes), minWeight, maxWeight);\n        std::cout << \"[i] Benchmark grid graph \" << nodes << \"x\" << nodes << std::endl;\n        benchmark(G, times);\n    }\n    else if (args.count(\"run\")) {\n        Graph G;\n        if (args.count(\"random\")) {\n            std::cout << \"[i] Random graph \" << nodes << \"x\" << edges << std::endl;\n            G = createRandomGraph(nodes, edges, minWeight, maxWeight);\n        }\n        else if (args.count(\"grid\")) {\n            std::cout << \"[i] Grid graph \" << nodes << \"x\" << nodes << std::endl;\n            G = createGridGraph(static_cast<int>(nodes), minWeight, maxWeight);\n        }\n        else {\n            return 0;\n        }\n\n        unsigned long  N = num_vertices(G);\n        std::vector<unsigned long> pred(N);\n        std::vector<long> dist(N, INF);\n        WeightMap weight = get(&EdgeProperties::weight, G);\n        printGraphVizToFile(G, \"graph.dot\");\n        bool res = bellmanFord(G, 0, weight, pred, dist);\n        if (!res) {\n            std::cout << \"negative cycle detected\" << std::endl;\n        }\n        std::vector<int> label = CHECK_BELLMAN_FORD(G, 0, weight, pred, dist);\n        std::cout << \"[+] Test OK!\" << std::endl;\n        printGraphShortestPath(G, dist, pred, label);\n        printGraphShortestPathVizToFile(G, pred, \"shortest-path.dot\");\n        std::cout << \"Run the following (if you have graphviz installed) to see the graph images:\" << std::endl;\n        std::cout << \"  neato -Tpng graph.dot -o graph.png && xdg-open  graph.png\" << std::endl;\n        std::cout << \"  neato -Tpng shortest-path.dot -o shortest-path.png && xdg-open shortest-path.png\" << std::endl;\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "770b726d4bae7aa6b7fde4f792fe1138bf001b61", "size": 4136, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "rafaelglikis/bellman-ford-boost", "max_stars_repo_head_hexsha": "cff840e8daf45366503b58c11feb77fe14a667c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-08-15T19:36:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-06T05:41:43.000Z", "max_issues_repo_path": "src/main.cpp", "max_issues_repo_name": "rafaelglikis/bellman-ford-boost", "max_issues_repo_head_hexsha": "cff840e8daf45366503b58c11feb77fe14a667c3", "max_issues_repo_licenses": ["MIT"], "max_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": "rafaelglikis/bellman-ford-boost", "max_forks_repo_head_hexsha": "cff840e8daf45366503b58c11feb77fe14a667c3", "max_forks_repo_licenses": ["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.2962962963, "max_line_length": 146, "alphanum_fraction": 0.5921179884, "num_tokens": 1028, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581741774411, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.4905128325641923}}
{"text": "#include <pcl/features/moment_of_inertia_estimation.h>\n#include <vector>\n#include <pcl/io/pcd_io.h>\n#include <pcl/point_types.h>\n#include <pcl/visualization/cloud_viewer.h>\n#include <boost/thread/thread.hpp>\n\nint main (int argc, char** argv)\n{\n  if (argc != 2)\n    return (0);\n\n  pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ> ());\n  if (pcl::io::loadPCDFile (argv[1], *cloud) == -1)\n    return (-1);\n\n  pcl::MomentOfInertiaEstimation <pcl::PointXYZ> feature_extractor;\n  feature_extractor.setInputCloud (cloud);\n  feature_extractor.compute ();\n\n  std::vector <float> moment_of_inertia;\n  std::vector <float> eccentricity;\n  pcl::PointXYZ min_point_AABB;\n  pcl::PointXYZ max_point_AABB;\n  pcl::PointXYZ min_point_OBB;\n  pcl::PointXYZ max_point_OBB;\n  pcl::PointXYZ position_OBB;\n  Eigen::Matrix3f rotational_matrix_OBB;\n  float major_value, middle_value, minor_value;\n  Eigen::Vector3f major_vector, middle_vector, minor_vector;\n  Eigen::Vector3f mass_center;\n\n  feature_extractor.getMomentOfInertia (moment_of_inertia);\n  feature_extractor.getEccentricity (eccentricity);\n  feature_extractor.getAABB (min_point_AABB, max_point_AABB);\n  feature_extractor.getOBB (min_point_OBB, max_point_OBB, position_OBB, rotational_matrix_OBB);\n  feature_extractor.getEigenValues (major_value, middle_value, minor_value);\n  feature_extractor.getEigenVectors (major_vector, middle_vector, minor_vector);\n  feature_extractor.getMassCenter (mass_center);\n\n  boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer (new pcl::visualization::PCLVisualizer (\"3D Viewer\"));\n  viewer->setBackgroundColor (0, 0, 0);\n  viewer->addCoordinateSystem (1.0);\n  viewer->initCameraParameters ();\n  viewer->addPointCloud<pcl::PointXYZ> (cloud, \"sample cloud\");\n  viewer->addCube (min_point_AABB.x, max_point_AABB.x, min_point_AABB.y, max_point_AABB.y, min_point_AABB.z, max_point_AABB.z, 1.0, 1.0, 0.0, \"AABB\");\n\n  Eigen::Vector3f position (position_OBB.x, position_OBB.y, position_OBB.z);\n  Eigen::Quaternionf quat (rotational_matrix_OBB);\n  viewer->addCube (position, quat, max_point_OBB.x - min_point_OBB.x, max_point_OBB.y - min_point_OBB.y, max_point_OBB.z - min_point_OBB.z, \"OBB\");\n\n  pcl::PointXYZ center (mass_center (0), mass_center (1), mass_center (2));\n  pcl::PointXYZ x_axis (major_vector (0) + mass_center (0), major_vector (1) + mass_center (1), major_vector (2) + mass_center (2));\n  pcl::PointXYZ y_axis (middle_vector (0) + mass_center (0), middle_vector (1) + mass_center (1), middle_vector (2) + mass_center (2));\n  pcl::PointXYZ z_axis (minor_vector (0) + mass_center (0), minor_vector (1) + mass_center (1), minor_vector (2) + mass_center (2));\n  viewer->addLine (center, x_axis, 1.0f, 0.0f, 0.0f, \"major eigen vector\");\n  viewer->addLine (center, y_axis, 0.0f, 1.0f, 0.0f, \"middle eigen vector\");\n  viewer->addLine (center, z_axis, 0.0f, 0.0f, 1.0f, \"minor eigen vector\");\n\n  //Eigen::Vector3f p1 (min_point_OBB.x, min_point_OBB.y, min_point_OBB.z);\n  //Eigen::Vector3f p2 (min_point_OBB.x, min_point_OBB.y, max_point_OBB.z);\n  //Eigen::Vector3f p3 (max_point_OBB.x, min_point_OBB.y, max_point_OBB.z);\n  //Eigen::Vector3f p4 (max_point_OBB.x, min_point_OBB.y, min_point_OBB.z);\n  //Eigen::Vector3f p5 (min_point_OBB.x, max_point_OBB.y, min_point_OBB.z);\n  //Eigen::Vector3f p6 (min_point_OBB.x, max_point_OBB.y, max_point_OBB.z);\n  //Eigen::Vector3f p7 (max_point_OBB.x, max_point_OBB.y, max_point_OBB.z);\n  //Eigen::Vector3f p8 (max_point_OBB.x, max_point_OBB.y, min_point_OBB.z);\n\n  //p1 = rotational_matrix_OBB * p1 + position;\n  //p2 = rotational_matrix_OBB * p2 + position;\n  //p3 = rotational_matrix_OBB * p3 + position;\n  //p4 = rotational_matrix_OBB * p4 + position;\n  //p5 = rotational_matrix_OBB * p5 + position;\n  //p6 = rotational_matrix_OBB * p6 + position;\n  //p7 = rotational_matrix_OBB * p7 + position;\n  //p8 = rotational_matrix_OBB * p8 + position;\n\n  //pcl::PointXYZ pt1 (p1 (0), p1 (1), p1 (2));\n  //pcl::PointXYZ pt2 (p2 (0), p2 (1), p2 (2));\n  //pcl::PointXYZ pt3 (p3 (0), p3 (1), p3 (2));\n  //pcl::PointXYZ pt4 (p4 (0), p4 (1), p4 (2));\n  //pcl::PointXYZ pt5 (p5 (0), p5 (1), p5 (2));\n  //pcl::PointXYZ pt6 (p6 (0), p6 (1), p6 (2));\n  //pcl::PointXYZ pt7 (p7 (0), p7 (1), p7 (2));\n  //pcl::PointXYZ pt8 (p8 (0), p8 (1), p8 (2));\n\n  //viewer->addLine (pt1, pt2, 1.0, 0.0, 0.0, \"1 edge\");\n  //viewer->addLine (pt1, pt4, 1.0, 0.0, 0.0, \"2 edge\");\n  //viewer->addLine (pt1, pt5, 1.0, 0.0, 0.0, \"3 edge\");\n  //viewer->addLine (pt5, pt6, 1.0, 0.0, 0.0, \"4 edge\");\n  //viewer->addLine (pt5, pt8, 1.0, 0.0, 0.0, \"5 edge\");\n  //viewer->addLine (pt2, pt6, 1.0, 0.0, 0.0, \"6 edge\");\n  //viewer->addLine (pt6, pt7, 1.0, 0.0, 0.0, \"7 edge\");\n  //viewer->addLine (pt7, pt8, 1.0, 0.0, 0.0, \"8 edge\");\n  //viewer->addLine (pt2, pt3, 1.0, 0.0, 0.0, \"9 edge\");\n  //viewer->addLine (pt4, pt8, 1.0, 0.0, 0.0, \"10 edge\");\n  //viewer->addLine (pt3, pt4, 1.0, 0.0, 0.0, \"11 edge\");\n  //viewer->addLine (pt3, pt7, 1.0, 0.0, 0.0, \"12 edge\");\n\n  while(!viewer->wasStopped())\n  {\n    viewer->spinOnce (100);\n    boost::this_thread::sleep (boost::posix_time::microseconds (100000));\n  }\n\n  return (0);\n}\n", "meta": {"hexsha": "2e48111a7c00f5a07cdb14d827f2454a5de5b076", "size": 5125, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sources/moment_of_inertia/moment_of_inertia.cpp", "max_stars_repo_name": "SmartKangJohn/PCL191_tutorials_x64", "max_stars_repo_head_hexsha": "ba23cfa0c612d11b00b97fba75e2f9b41633b5d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-04-10T14:04:52.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-29T03:41:58.000Z", "max_issues_repo_path": "software/SLAM/ygz_slam_ros/Thirdparty/PCL/doc/tutorials/content/sources/moment_of_inertia/moment_of_inertia.cpp", "max_issues_repo_name": "glider54321/GAAS", "max_issues_repo_head_hexsha": "5c3b8c684e72fdf7f62c5731a260021e741069e7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "software/SLAM/ygz_slam_ros/Thirdparty/PCL/doc/tutorials/content/sources/moment_of_inertia/moment_of_inertia.cpp", "max_forks_repo_name": "glider54321/GAAS", "max_forks_repo_head_hexsha": "5c3b8c684e72fdf7f62c5731a260021e741069e7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-20T06:54:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-20T06:54:41.000Z", "avg_line_length": 47.4537037037, "max_line_length": 150, "alphanum_fraction": 0.6889756098, "num_tokens": 1801, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799252, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.490512812303692}}
{"text": "// Bring in my package's API, which is what I'm testing\n#include <bsplines/BSplinePose.hpp>\n#include <sparse_block_matrix/sparse_block_matrix.h>\n#include <stdio.h>\n// Bring in gtest\n#include <gtest/gtest.h>\n#include <boost/cstdint.hpp>\n\n// Helpful functions from libsm\n#include <sm/eigen/gtest.hpp>\n#include <sm/eigen/NumericalDiff.hpp>\n\n#include <boost/tuple/tuple.hpp>\n#include <sm/kinematics/transformations.hpp>\n#include <sm/kinematics/RotationVector.hpp>\n#include <sm/kinematics/EulerRodriguez.hpp>\n#include <sm/kinematics/EulerAnglesYawPitchRoll.hpp>\n#include <sm/kinematics/EulerAnglesZYX.hpp>\n#include <stdio.h>\n\nusing namespace bsplines;\nusing namespace sm::kinematics;\n\nstruct BSplineTransformationJacobianFunctor\n{\n  // Necessary for eigen fixed sized type member variables.\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n  typedef Eigen::VectorXd input_t;\n  typedef Eigen::MatrixXd jacobian_t;\n  typedef Eigen::VectorXd value_t;\n  typedef double scalar_t;\n\n  BSplineTransformationJacobianFunctor(BSplinePose bs, const Eigen::Vector4d & v, double t) :\n    bs_(bs), t_(t), v_(v)\n  {\n    \n  }\n\n  input_t update(const input_t & x, int c, double delta)\n  {\n    input_t xnew = x;\n    xnew[c] += delta;\n    return xnew;\n  }\n\n  Eigen::VectorXd operator()(const Eigen::VectorXd & c)\n  {\n    bs_.setLocalCoefficientVector(t_,c);\n    Eigen::Matrix4d T = bs_.transformation(t_);\n    return T * v_;\n  }\n\n  BSplinePose bs_;\n  double t_;\n  Eigen::Vector4d v_;\n};\n\n\nstruct BSplineInverseTransformationJacobianFunctor\n{\n  // Necessary for eigen fixed sized type member variables.\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n  typedef Eigen::VectorXd input_t;\n  typedef Eigen::MatrixXd jacobian_t;\n  typedef Eigen::VectorXd value_t;\n  typedef double scalar_t;\n\n  BSplineInverseTransformationJacobianFunctor(BSplinePose bs, const Eigen::Vector4d & v, double t) :\n    bs_(bs), t_(t), v_(v)\n  {\n    \n  }\n\n  input_t update(const input_t & x, int c, double delta)\n  {\n    input_t xnew = x;\n    xnew[c] += delta;\n    return xnew;\n  }\n\n  Eigen::VectorXd operator()(const Eigen::VectorXd & c)\n  {\n    bs_.setLocalCoefficientVector(t_,c);\n    Eigen::Matrix4d T = bs_.inverseTransformation(t_);\n    return T * v_;\n  }\n\n  BSplinePose bs_;\n  double t_;\n  Eigen::Vector4d v_;\n};\n\n\n\n\n\n// Check that the Jacobian calculation is correct.\nTEST(SplineTestSuite, testBSplineTransformationJacobian)\n{\n  boost::shared_ptr<RotationalKinematics> rvs[3];\n\n  rvs[0].reset(new EulerAnglesZYX());\n  rvs[1].reset(new RotationVector());\n  rvs[2].reset(new EulerRodriguez());\n  \n  for(int r = 0; r < 3; r++)\n  {\n      for(int order = 2; order < 10; order++)\n\t{\n\t  // Create a two segment spline.\n\t  BSplinePose bs(order, rvs[r]);\n\t  bs.initPoseSpline(0.0, 1.0, bs.curveValueToTransformation(Eigen::VectorXd::Random(6)),\n\t\t\t    bs.curveValueToTransformation(Eigen::VectorXd::Random(6)));\n\t  bs.addPoseSegment(2.0,bs.curveValueToTransformation(Eigen::VectorXd::Random(6)));\n      \n\t  // Create a random homogeneous vector.\n\t  Eigen::Vector4d v = Eigen::Vector4d::Random() * 10.0;\n\n\t  for(double t = bs.t_min(); t <= bs.t_max(); t+= 0.413)\n\t    {\n\t      BSplineTransformationJacobianFunctor f(bs, v, t);\n\t      sm::eigen::NumericalDiff<BSplineTransformationJacobianFunctor> nd(f);\n\t      Eigen::MatrixXd estJ = nd.estimateJacobian(bs.localCoefficientVector(t));\n\t      Eigen::MatrixXd JT;\n\n\n\t      Eigen::Matrix4d T = bs.transformationAndJacobian(t, &JT);\n\n\t      //std::cout << \"Full jacobian:\\n\" << JT << std::endl;\n\t      //std::cout << \"boxMinus(v):\\n\" << sm::kinematics::boxMinus(v) << std::endl;\n\t      Eigen::MatrixXd J = sm::kinematics::boxMinus(T*v) * JT;\n\n\t      sm::eigen::assertNear(J, estJ, 1e-6, SM_SOURCE_FILE_POS);\n\n\t      // Try again with the lumped function.\n\t      Eigen::Vector4d v_n = bs.transformVectorAndJacobian(t,v, &J);\n\t      sm::eigen::assertNear(v_n, T*v, 1e-6, SM_SOURCE_FILE_POS);\n\t      sm::eigen::assertNear(J, estJ, 1e-6, SM_SOURCE_FILE_POS);\n\t    }\n\t}\n    }\n      \n}\n\n#if 1\n// Check that the Jacobian calculation is correct.\nTEST(SplineTestSuite, testBSplineInverseTransformationJacobian)\n{\n  boost::shared_ptr<RotationalKinematics> rvs[3];\n\n  rvs[0].reset(new EulerAnglesZYX());\n  rvs[1].reset(new RotationVector());\n  rvs[2].reset(new EulerRodriguez());\n  \n  for(int r = 0; r < 3; r++)\n  {\n      for(int order = 2; order < 10; order++)\n\t{\n\t  // Create a two segment spline.\n\t  BSplinePose bs(order, rvs[r]);\n\t  bs.initPoseSpline(0.0, 1.0, bs.curveValueToTransformation(Eigen::VectorXd::Random(6)),\n\t\t\t    bs.curveValueToTransformation(Eigen::VectorXd::Random(6)));\n\t  bs.addPoseSegment(2.0,bs.curveValueToTransformation(Eigen::VectorXd::Random(6)));\n      \n\t  // Create a random homogeneous vector.\n\t  Eigen::Vector4d v = Eigen::Vector4d::Random() * 10.0;\n\n\t  for(double t = bs.t_min(); t <= bs.t_max(); t+= 0.413)\n\t    {\n\t      BSplineInverseTransformationJacobianFunctor f(bs, v, t);\n\t      sm::eigen::NumericalDiff<BSplineInverseTransformationJacobianFunctor> nd(f);\n\t      Eigen::MatrixXd estJ = nd.estimateJacobian(bs.localCoefficientVector(t));\n\t      Eigen::MatrixXd JT;\n              Eigen::MatrixXd J;\n\n\t      Eigen::Matrix4d T = bs.inverseTransformationAndJacobian(t, &JT);\n\n\t      //std::cout << \"Full jacobian:\\n\" << JT << std::endl;\n\t      //std::cout << \"boxMinus(v):\\n\" << sm::kinematics::boxMinus(v) << std::endl;\n\t      J = sm::kinematics::boxMinus(T*v) * JT;\n              //std::cout << \"J(0,0): \" << J(0,0) << std::endl;\n\t      sm::eigen::assertNear(J, estJ, 1e-6, SM_SOURCE_FILE_POS);\n\n\t      // Try again with the lumped function.\n\t      //Eigen::Vector4d v_n = bs.inverseTransformVectorAndJacobian(t,v, &J);\n\t      //sm::eigen::assertNear(v_n, T*v, 1e-6, SM_SOURCE_FILE_POS);\n\t      //sm::eigen::assertNear(J, estJ, 1e-6, SM_SOURCE_FILE_POS);\n\t    }\n\t}\n    }\n      \n}\n\n#endif\n\n\nstruct BSplineAccelerationJacobianFunctor\n{\n  // Necessary for eigen fixed sized type member variables.\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n  typedef Eigen::VectorXd input_t;\n  typedef Eigen::MatrixXd jacobian_t;\n  typedef Eigen::Vector3d value_t;\n  typedef double scalar_t;\n\n  BSplineAccelerationJacobianFunctor(BSplinePose bs, double t) :\n    bs_(bs), t_(t)\n  {\n    \n  }\n\n  input_t update(const input_t & x, int c, double delta)\n  {\n    input_t xnew = x;\n    xnew[c] += delta;\n    return xnew;\n  }\n\n  Eigen::Vector3d operator()(const Eigen::VectorXd & c)\n  {\n    bs_.setLocalCoefficientVector(t_,c);\n    Eigen::Vector3d a = bs_.linearAccelerationAndJacobian(t_,NULL,NULL);\n    //std::cout << \"a.size(): \" << a.size() << std::endl;\n    return a;\n  }\n\n  BSplinePose bs_;\n  double t_;\n};\n\n\nTEST(SplineTestSuite, testBSplineAccelerationJacobian)\n{\n  boost::shared_ptr<RotationalKinematics> r(new RotationVector());\n  \n  for(int order = 2; order < 10; order++)\n    {\n      // Create a two segment spline.\n      BSplinePose bs(order, r);\n      bs.initPoseSpline(0.0, 1.0, bs.curveValueToTransformation(Eigen::VectorXd::Random(6)),\n\t\t\tbs.curveValueToTransformation(Eigen::VectorXd::Random(6)));\n      bs.addPoseSegment(2.0,bs.curveValueToTransformation(Eigen::VectorXd::Random(6)));\n     \n      for(double t = bs.t_min(); t <= bs.t_max(); t+= 0.1)\n\t{\n\n\t  \n\t  Eigen::MatrixXd J;\n\t  bs.linearAccelerationAndJacobian(t,&J,NULL);\n\n\t  BSplineAccelerationJacobianFunctor f(bs,t);\n\t  sm::eigen::NumericalDiff<BSplineAccelerationJacobianFunctor> nd(f);\n\t  Eigen::MatrixXd estJ = nd.estimateJacobian(bs.localCoefficientVector(t));\n\t  \n\n\t  //std::cout << \"J\\n\" << J << \"\\nestJ:\\n\" << estJ << std::endl;\n\t  sm::eigen::assertNear(J, estJ, 1e-6, SM_SOURCE_FILE_POS);\n\t  \n\t}\n    }\n}\n\n\n\nTEST(SplineTestSuite, testBSplineCurveQuadraticIntegralSparse) {\n    \n    try {\n    boost::shared_ptr<RotationalKinematics> rvs;\n    \n    rvs.reset(new RotationVector());\n    \n\n        const int length = 50;\n        int numSegments = 20;\n        double lambda = 0.5;\n        \n        \n        for(int order = 2; order < 10; order++)\n        {\n            // Create a two segment spline.\n            BSplinePose bs(order, rvs);\n           // bs.initPoseSpline(0.0, 1.0, bs.curveValueToTransformation(Eigen::VectorXd::Random(6)),\n           //                   bs.curveValueToTransformation(Eigen::VectorXd::Random(6)));\n          //  bs.addPoseSegment(2.0,bs.curveValueToTransformation(Eigen::VectorXd::Random(6)));\n            \n            \n            // random positive times\n            Eigen::Matrix<double, length, 1> times = Eigen::VectorXd::Random(length) + Eigen::VectorXd::Ones(length);\n            // sorted\n            std::sort(&times.coeffRef(0), &times.coeffRef(0)+times.size());\n            \n            times[length-1] = ceil(times[length-1]);            \n            \n            Eigen::MatrixXd poses = Eigen::MatrixXd::Random(6,length);\n            \n            bs.initPoseSpline3(times,poses,numSegments,lambda);\n            \n            \n            \n            // random symmetric matrix:\n            Eigen::MatrixXd W = Eigen::MatrixXd::Random(6,6);\n            for (int i = 0; i < 6; i++) \n                for(int j = 0; j < i; j++)\n                    W(j,i) = W(i,j);\n            \n            \n            sparse_block_matrix::SparseBlockMatrix<Eigen::MatrixXd> Q_sparse = bs.curveQuadraticIntegralSparse(W, 0);\n        \n            Eigen::MatrixXd Q_dense = bs.curveQuadraticIntegral(W, 0);   \n            \n            sm::eigen::assertNear(Q_dense, Q_sparse.toDense(), 1e-10, SM_SOURCE_FILE_POS);\n        }\n    }\n    catch(const std::exception &e) {\n        FAIL() << e.what();\n    }\n    \n    \n}\n\n\n\nTEST(SplineTestSuite, testBSplineCurveQuadraticIntegralDiagSparse) {\n    \n    try {\n        boost::shared_ptr<RotationalKinematics> rvs;\n        \n        rvs.reset(new RotationVector());\n        const int length = 50;\n        int numSegments = 20;\n        double lambda = 0.5;\n        \n        for(int order = 2; order < 10; order++)\n        {\n            // Create a two segment spline.\n            BSplinePose bs(order, rvs);\n         //   bs.initPoseSpline(0.0, 1.0, bs.curveValueToTransformation(Eigen::VectorXd::Random(6)),\n         //                     bs.curveValueToTransformation(Eigen::VectorXd::Random(6)));\n         //   bs.addPoseSegment(2.0,bs.curveValueToTransformation(Eigen::VectorXd::Random(6)));\n            \n            // random positive times\n            Eigen::Matrix<double, length, 1> times = Eigen::VectorXd::Random(length) + Eigen::VectorXd::Ones(length);\n            // sorted\n            std::sort(&times.coeffRef(0), &times.coeffRef(0)+times.size());\n            \n            times[length-1] = ceil(times[length-1]);            \n            \n            Eigen::MatrixXd poses = Eigen::MatrixXd::Random(6,length);\n            \n            bs.initPoseSpline3(times,poses,numSegments,lambda);\n            \n            \n            // random symmetric matrix:\n            Eigen::VectorXd W = Eigen::VectorXd::Random(6);\n            \n            \n            sparse_block_matrix::SparseBlockMatrix<Eigen::MatrixXd> Q_sparse = bs.curveQuadraticIntegralDiagSparse(W, 0);\n            \n            Eigen::MatrixXd Q_dense = bs.curveQuadraticIntegralDiag(W, 0);   \n            \n            sm::eigen::assertNear(Q_dense, Q_sparse.toDense(), 1e-10, SM_SOURCE_FILE_POS);\n        }\n    }\n    catch(const std::exception &e) {\n        FAIL() << e.what();\n    }\n    \n    \n}\n\n#include <boost/progress.hpp>\n\nTEST(SplineTestSuite, testInitSpline3Sparse) {\n    \n    try {\n        boost::shared_ptr<RotationalKinematics> rvs;\n        \n        rvs.reset(new RotationVector());\n        \n        const bool benchmark = false;\n\n        const int length = benchmark ? 1000 : 100;\n        int numSegments = benchmark ? 200 : 20;\n        double lambda = 0.1;\n      //  int order = 2;\n        for(int order = 2; order < 8; order++)\n        {\n            // Create a two segment spline.\n            BSplinePose bs_sparse(order, rvs);\n            BSplinePose bs_dense(order, rvs);\n            \n            // random positive times\n            Eigen::Matrix<double, length, 1> times = Eigen::VectorXd::Random(length) + Eigen::VectorXd::Ones(length);\n            // sorted\n            std::sort(&times.coeffRef(0), &times.coeffRef(0)+times.size());\n            \n            times[length-1] = ceil(times[length-1]);\n\n      //      times = times;\n\n          //  std::cout << \"Times:\" << std::endl;\n          //  std::cout << times << std::endl;\n            \n            Eigen::MatrixXd poses = Eigen::MatrixXd::Random(6,length);\n\n            if(benchmark){\n              {\n                  boost::progress_timer timer;\n                  std::cout << \"Dense:\" << std::endl;\n                  bs_dense.initPoseSpline3(times,poses,numSegments,lambda);\n              }\n              {\n                  boost::progress_timer timer;\n                  std::cout << \"Sparse:\" << std::endl;\n                  bs_sparse.initPoseSplineSparse(times,poses,numSegments,lambda);\n              }\n            }\n            \n            // diagonals\n      //      for (int i = 0; i < Asparse.rows(); i++)\n     //           std::cout << Asparse(i,i) << \" : \" << Adense(i,i) << std::endl;\n            \n            \n            \n            Eigen::MatrixXd m1 = bs_sparse.coefficients();\n            Eigen::MatrixXd m2 = bs_dense.coefficients();\n\n         /*   std::cout << \"m1:\" << std::endl;\n            std::cout << m1 << std::endl;\n            std::cout << \"m2:\" << std::endl;\n            std::cout << m2 << std::endl;\n*/\n            sm::eigen::assertNear(m1, m2, 1e-8, SM_SOURCE_FILE_POS);\n            \n        }\n    }\n    catch(const std::exception &e) {\n        FAIL() << e.what();\n    }\n    \n    \n}\n\n", "meta": {"hexsha": "24202f5c2bbc038bd66bacecdf9c9a495f844045", "size": 13557, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "aslam_nonparametric_estimation/bsplines/test/BSplinePoseTests.cpp", "max_stars_repo_name": "PushyamiKaveti/kalibr", "max_stars_repo_head_hexsha": "d8bdfc59ee666ef854012becc93571f96fe5d80c", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": 2690.0, "max_stars_repo_stars_event_min_datetime": "2015-01-07T03:50:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T20:27:01.000Z", "max_issues_repo_path": "aslam_nonparametric_estimation/bsplines/test/BSplinePoseTests.cpp", "max_issues_repo_name": "PushyamiKaveti/kalibr", "max_issues_repo_head_hexsha": "d8bdfc59ee666ef854012becc93571f96fe5d80c", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": 481.0, "max_issues_repo_issues_event_min_datetime": "2015-01-27T10:21:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T14:02:41.000Z", "max_forks_repo_path": "aslam_nonparametric_estimation/bsplines/test/BSplinePoseTests.cpp", "max_forks_repo_name": "PushyamiKaveti/kalibr", "max_forks_repo_head_hexsha": "d8bdfc59ee666ef854012becc93571f96fe5d80c", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": 1091.0, "max_forks_repo_forks_event_min_datetime": "2015-01-26T21:21:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T01:55:33.000Z", "avg_line_length": 30.5337837838, "max_line_length": 121, "alphanum_fraction": 0.5994689091, "num_tokens": 3597, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.7185944046238981, "lm_q1q2_score": 0.49049366629193486}}
{"text": "//==================================================================================================\n/*!\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#include <boost/simd/function/scalar/exponentbits.hpp>\n#include <scalar_test.hpp>\n#include <boost/simd/detail/dispatch/meta/as_integer.hpp>\n#include <boost/simd/constant/inf.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/zero.hpp>\n\nSTF_CASE_TPL (\" exponentbits float\",  (float))\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::exponentbits;\n  using r_t = decltype(exponentbits(T()));\n\n  // return type conformity test\n  STF_TYPE_IS(r_t, bd::as_integer_t<T>);\n\n  // specific values tests\n  for(int i=1, k = 0; i < 10; i*= 2, ++k)\n  {\n  namespace bs = boost::simd;\n    STF_EQUAL(1065353216+k*8388608, exponentbits(T(i)));\n  }\n}\n\nSTF_CASE_TPL (\" exponentbits double\",  (double))\n{\n  namespace bd = boost::dispatch;\n  namespace bs = boost::simd;\n  using bs::exponentbits;\n  using r_t = decltype(exponentbits(T()));\n\n  // return type conformity test\n  using r_t = decltype(exponentbits(T()));\n\n  // return type conformity test\n  STF_TYPE_IS(r_t, bd::as_integer_t<T>);\n\n  // specific values tests\n  for(int i=1, k = 0; i < 10; i*= 2, ++k)\n   {\n  namespace bs = boost::simd;\n     STF_EQUAL(4607182418800017408ll+k*4503599627370496ll, exponentbits(T(i)));\n   }\n}\n\n\n", "meta": {"hexsha": "c554ae828562835df5ac5e12ea1927aeb20ef666", "size": 1716, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/scalar/exponentbits.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": "test/function/scalar/exponentbits.cpp", "max_issues_repo_name": "remymuller/boost.simd", "max_issues_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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/function/scalar/exponentbits.cpp", "max_forks_repo_name": "remymuller/boost.simd", "max_forks_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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": 28.6, "max_line_length": 100, "alphanum_fraction": 0.615967366, "num_tokens": 451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943805178138, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.49049365447784427}}
{"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#define NT2_UNIT_MODULE \"nt2 complex toolbox - tand/scalar Mode\"\n\n//////////////////////////////////////////////////////////////////////////////\n// unit test behavior of tand  components in scalar mode\n//////////////////////////////////////////////////////////////////////////////\n/// created by jt the 08/12/2010\n///\n#include <nt2/include/functions/tand.hpp>\n#include <nt2/include/functions/tan.hpp>\n#include <boost/type_traits/is_same.hpp>\n#include <nt2/sdk/functor/meta/call.hpp>\n#include <nt2/sdk/meta/as_integer.hpp>\n#include <nt2/sdk/meta/as_floating.hpp>\n#include <nt2/sdk/meta/as_signed.hpp>\n#include <nt2/sdk/meta/upgrade.hpp>\n#include <nt2/sdk/meta/downgrade.hpp>\n#include <nt2/sdk/meta/scalar_of.hpp>\n#include <boost/dispatch/meta/as_floating.hpp>\n#include <boost/type_traits/common_type.hpp>\n#include <nt2/sdk/unit/tests.hpp>\n#include <nt2/sdk/unit/module.hpp>\n#include <nt2/sdk/memory/buffer.hpp>\n#include <nt2/constant/constant.hpp>\n#include <nt2/include/constants/deginrad.hpp>\n#include <complex>\n\n\n\nNT2_TEST_CASE_TPL ( tand_real__1_0,  NT2_REAL_TYPES)\n{\n\n  using nt2::tand;\n  using nt2::tag::tand_;\n  typedef std::complex<T> cT;\n  typedef typename nt2::meta::as_integer<T>::type iT;\n  typedef typename nt2::meta::call<tand_(cT)>::type r_t;\n  typedef typename nt2::meta::scalar_of<r_t>::type ssr_t;\n  typedef typename nt2::meta::upgrade<T>::type u_t;\n  typedef typename nt2:: meta::as_complex<T>::type wished_r_t;\n\n\n  // return type conformity test\n  NT2_TEST( (boost::is_same < r_t, wished_r_t >::value) );\n  std::cout << std::endl;\n  double ulpd;\n  ulpd=0.0;\n\n\n  // specific values tests\n  NT2_TEST_ULP_EQUAL(nt2::tand(cT(nt2::Inf<T>())), cT(nt2::Nan<T>()), 2);\n  NT2_TEST_ULP_EQUAL(nt2::tand(cT(nt2::Minf<T>())), cT(nt2::Nan<T>()), 2);\n  NT2_TEST_ULP_EQUAL(nt2::tand(cT(1, 1)),std::tan(nt2::Deginrad<T>()*cT(1.0, 1.0)), 2);\n  NT2_TEST_ULP_EQUAL(nt2::tand(cT(1, 0.3)),std::tan(nt2::Deginrad<T>()*cT(1.0, 0.3)), 2);\n  NT2_TEST_ULP_EQUAL(nt2::tand(cT(0.3, 1)),std::tan(nt2::Deginrad<T>()*cT(0.3, 1.0)), 2);\n  NT2_TEST_ULP_EQUAL(nt2::tand(cT(0.3, 0.3)),std::tan(nt2::Deginrad<T>()*cT(0.3, 0.3)), 2);\n  NT2_TEST_ULP_EQUAL(nt2::tand(cT(0, 1)),std::tan(nt2::Deginrad<T>()*cT(0.0, 1.0)), 2);\n  NT2_TEST_ULP_EQUAL(nt2::tand(cT(0, 0.3)),std::tan(nt2::Deginrad<T>()*cT(0.0, 0.3)), 2);\n  NT2_TEST_ULP_EQUAL(nt2::tand(cT(0.3, 0)),std::tan(nt2::Deginrad<T>()*cT(0.3, 0.0)), 2);\n\n  const int N = 20;\n  cT inputs[N] =\n    { cT(nt2::Zero<T>(),nt2::Zero<T>()),cT(nt2::Inf<T>(),nt2::Zero<T>()),cT(nt2::Minf<T>(),nt2::Zero<T>()),cT(nt2::Nan<T>(),nt2::Zero<T>()),\n      cT(nt2::Zero<T>(),nt2::Inf<T>()), cT(nt2::Inf<T>(),nt2::Inf<T>()), cT(nt2::Minf<T>(),nt2::Inf<T>()), cT(nt2::Nan<T>(),nt2::Inf<T>()),\n      cT(nt2::Zero<T>(),nt2::Minf<T>()),cT(nt2::Inf<T>(),nt2::Minf<T>()),cT(nt2::Minf<T>(),nt2::Minf<T>()),cT(nt2::Nan<T>(),nt2::Minf<T>()),\n      cT(nt2::Zero<T>(),nt2::Nan<T>()), cT(nt2::Inf<T>(),nt2::Nan<T>()), cT(nt2::Minf<T>(),nt2::Nan<T>()), cT(nt2::Nan<T>(),nt2::Nan<T>()),\n      cT(nt2::Zero<T>(),180), cT(nt2::Inf<T>(),180), cT(nt2::Minf<T>(),180), cT(nt2::Nan<T>(),180),\n    };\n\n  for(int i=0; i < N; i++)\n   {\n     std::cout << \"-------------------\" << std::endl;\n     std::cout << \"inputs  \"<< inputs[i] << std::endl;\n     NT2_TEST_ULP_EQUAL(nt2::tand(-inputs[i]), -nt2::tand(inputs[i]), 3);\n     NT2_TEST_ULP_EQUAL(nt2::tand(inputs[i]), nt2::mul_minus_i(nt2::tanh(nt2::mul_i(nt2::multiplies(nt2::Deginrad<T>(), inputs[i])))), 3);\n     std::cout << \"=================== \" << std::endl;\n   }\n\n } // end of test for floating_\n\n", "meta": {"hexsha": "1771ce86fb688b4892bd65566ac78f85251196e1", "size": 4046, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/type/complex/trigonometric/unit/scalar/tand.cpp", "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/type/complex/trigonometric/unit/scalar/tand.cpp", "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/type/complex/trigonometric/unit/scalar/tand.cpp", "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": 45.9772727273, "max_line_length": 140, "alphanum_fraction": 0.5724172022, "num_tokens": 1394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.682573734412324, "lm_q2_score": 0.7185943865443352, "lm_q1q2_score": 0.49049365395129996}}
{"text": "#pragma once\n\n#include <boost/operators.hpp>\n\n#include <iterator>\n#include <string>\n#include <vector>\n#include <algorithm>\n#include <functional>\n\n#include \"defaults.hpp\"\n#include \"exceptions.hpp\"\n#include \"num_io.hpp\"\n#include \"almost_equal.hpp\"\n\n\nnamespace gftools {\n\n/** This class describes a point on a grid. It has an index (integer) and a value (pretty much anything) , and it\nmaps between the two. The index is used for fast access, and the value is used for other things like interpolation/physics/math.*/\ntemplate <typename ValueType> class point_base :\n    ///dependence on this provides additional comparison operators\n    boost::less_than_comparable<point_base<ValueType> >,\n    ///dependence on this provides additional comparison operators\n    boost::equality_comparable<point_base<ValueType> >\n {\npublic:\n    //there is a small wrapper for integers down below. Here we exclude grids of ints to avoid confusion in the cast operators.\n    static_assert(!std::is_same<ValueType,int>::value, \"Can't create a grid of ints\");\n\n    typedef ValueType value_type;\n\n    ///cast operator to value type\n    operator ValueType() const { return val_; }\n    ///cast operator to index type\n    explicit operator size_t() const { return index_; }\n    ///another cast operator to index type\n    explicit operator int() const { return index_; }\n\n    ///constructor with a pair of values and indices\n    point_base(ValueType val, size_t index):val_(val),index_(index){}\n\n    bool operator==(const point_base &rhs) const {return index_ == rhs.index_;}\n    bool operator<(const point_base &rhs) const {return this->index_ < rhs.index_;}\n\n    ValueType value() const { return val_; }\n    size_t index() const { return index_; }\n\nprotected:\n    ///grid point (in physical units)\n    ValueType val_;\n    ///grid point index\n    size_t index_;\n};\n\ntemplate<typename T> std::ostream& operator<<(std::ostream& lhs, const point_base<T> &p){\n  lhs<<\"{\"<<p.value()<<\"<-[\"<<p.index()<<\"]}\"; return lhs;\n}\n\n/** A one-dimensional grid, which stores an array of values. Typical examples: grid of real frequencies. Grid of k-points. Grid of Matsubara frequencies. Grid of imaginary times.*/\ntemplate <typename ValueType, class Derived>\nclass grid_base : public boost::equality_comparable<grid_base<ValueType, Derived> > {\npublic:\n    typedef point_base<ValueType> point;\n    typedef ValueType value_type;\n\n    /** constructor a grid out of thin air. */\n    grid_base();\n    /** construct a grid given a vector of points. */\n    grid_base(const std::vector<point> & vals);\n    /** construct a grid from a vector of values (but not associated indices that would be stored in points). */\n    grid_base(const std::vector<ValueType> & vals);\n    /** Initialize the values from an external function that maps the integer values to the ValueType values. */\n    grid_base(int min, int max, std::function<ValueType (int)> f);\n\n    /** Returns a value at given index. */\n    point operator[](size_t in) const;\n    /** Returns all values. */\n    const std::vector<point> & points() const;\n    /** Returns values of all points. (computed on the fly, slow)*/\n    std::vector<ValueType> values() const;\n    /** Checks if a point is present in a grid. */\n    bool check_point(point in, real_type tolerance = std::numeric_limits<real_type>::epsilon()) const;\n    /** Returns size of grid. */\n    size_t size() const;\n\n    /** Returns the closest point to the given value. */\n    point find_nearest(ValueType in) const;\n    /** Get a value of an object at the given point, which is defined on a grid. */\n    template <class Obj> auto eval(Obj &&in, point x) const ->decltype(in[0]);\n\n    /** Shift a point by the given value. */\n    point shift(point in, ValueType shift_arg) const;\n    ValueType shift(ValueType in, ValueType shift_arg) const;\n    point shift (point in, point shift_arg) const;\n\n    // CRTP forwards: TODO: these will need to be cleaned for C++ and documented.\n    /** Get a value of an object at the given coordinate, which is defined on a grid. */\n    template <class Obj>\n        auto eval(Obj &in, ValueType x) const ->decltype(in[0])\n        { return static_cast<const Derived*>(this)->eval(in,x); };\n    /// Make the object printable.\n    template <typename ValType, class Derived2> friend std::ostream& operator<<(std::ostream& lhs, const grid_base<ValType,Derived2> &gr);\n    /// Compare 2 grids\n    bool operator==(const grid_base &rhs) const;\n\n    class ex_wrong_index : public gftools_exception { public:\n        ex_wrong_index(int i, int l):index_(i),l_(l),\n        msg(\"grid_base : index \" + std::to_string(index_) + \" is out of bounds >\" + std::to_string(l_) + \".\")\n        {}\n        virtual const char* what() const throw(){return msg.c_str();}\n        int index_; int l_;\n        std::string msg;\n    };\n\n    class ex_not_found : public gftools_exception { public:\n        ex_not_found(value_type x, grid_base const &y):x_(x), y_(y)\n        {\n            value_type b1(y_[0]), b2(y_[y_.size()-1]);\n            msg = \"grid_base : \" + make_num_io(x_).to_string() + \" is not found in the grid [\" +\n                  make_num_io(b1).to_string() + \"; \" + make_num_io(b2).to_string() + \"].\";\n        }\n        virtual const char* what() const throw(){return msg.c_str();}\n        value_type x_;\n        grid_base const& y_;\n        std::string msg;\n    };\n\n\nprotected:\n    std::vector<point> vals_;\n};\n\nnamespace extra {\n/// A small helper struct to decorate a function object with [] method.\ntemplate <typename F, typename Grid>\nstruct function_proxy {\n    F f_;\n    const Grid& grid_;\n    function_proxy(F f, Grid const& grid):f_(f),grid_(grid){}\n    typedef typename std::result_of<F(typename Grid::value_type)>::type value_type;\n    value_type operator[](int i) const {return f_((grid_.points()[i]).value()); }\n};\n}\n\n\n\n//\n// grid_base implementation\n//\n\ntemplate <typename ValueType, class Derived>\ngrid_base<ValueType,Derived>::grid_base()\n{};\n\ntemplate <typename ValueType, class Derived>\ngrid_base<ValueType,Derived>::grid_base(const std::vector<point> &vals):vals_(vals)\n{\n};\n\n\ntemplate <typename ValueType, class Derived>\ngrid_base<ValueType,Derived>::grid_base(const std::vector<ValueType> &vals)\n{\n    vals_.reserve(vals.size());\n    for (size_t i=0; i<vals.size(); ++i) { vals_.emplace_back(point(vals[i], i)); };\n};\n\ntemplate <typename ValueType, class Derived>\ngrid_base<ValueType,Derived>::grid_base(int min, int max, std::function<ValueType (int)> f)\n{\n    if (max<min) std::swap(min,max);\n    size_t n_points = max-min;\n    vals_.reserve(n_points);\n    for (size_t i=0; i<n_points; ++i) vals_.emplace_back(f(min+i), i) ;\n}\n\ntemplate <typename ValueType, class Derived>\ninline typename grid_base<ValueType,Derived>::point grid_base<ValueType,Derived>::operator[](size_t index) const\n{\n    #ifndef NDEBUG\n    if (index>vals_.size()) throw ex_wrong_index(index,this->size());\n    #endif\n    return vals_[index];\n}\n\ntemplate <typename ValueType, class Derived>\ninline const std::vector<typename grid_base<ValueType,Derived>::point> & grid_base<ValueType,Derived>::points() const\n{\n    return vals_;\n}\n\ntemplate <typename ValueType, class Derived>\ninline std::vector<ValueType> grid_base<ValueType,Derived>::values() const\n{\n    std::vector<ValueType> out;\n    out.reserve(vals_.size());\n    for (const auto& x : vals_) out.emplace_back(x.value());\n    return out;\n}\n\ntemplate <typename ValueType, class Derived>\ninline size_t grid_base<ValueType,Derived>::size() const\n{\n    return vals_.size();\n}\n\ntemplate <typename ValueType, class Derived>\ninline bool grid_base<ValueType,Derived>::check_point(point in, real_type tolerance) const\n{\n    return (in.index() < vals_.size() && std::abs(in.value() - vals_[in.index()].value()) < tolerance);\n}\n\ntemplate <typename ValueType, class Derived>\ntemplate <class Obj>\ninline auto grid_base<ValueType,Derived>::eval(Obj &&in, point x) const ->decltype(in[0])\n{\n    if (check_point(x)) return in[x.index()];\n    else throw ex_wrong_index(x.index(), this->size());\n}\n\ntemplate <typename ValueType, class Derived>\ninline typename grid_base<ValueType,Derived>::point grid_base<ValueType,Derived>::find_nearest(ValueType in) const\n{\n    static_assert(std::is_same<bool,decltype(std::declval<ValueType>() < std::declval<ValueType>())>::value,\n        \"Default find_nearest is written only for less-comparable types\");\n    auto nearest_iter = std::lower_bound(vals_.begin(), vals_.end(), in, [](ValueType x, ValueType y){return x<y;});\n    size_t dist = std::distance(vals_.begin(), nearest_iter);\n    if (dist > 0 && std::abs(complex_type(vals_[dist].value()) - complex_type(in)) > std::abs(complex_type(vals_[dist-1].value()) - complex_type(in)) ) dist--;\n    return vals_[dist];\n}\n\ntemplate <typename ValueType, class Derived>\ninline typename grid_base<ValueType,Derived>::point grid_base<ValueType,Derived>::shift(point in, ValueType shift_arg) const\n{\n    if (almost_equal(shift_arg, 0.0)) return in;\n    ValueType out(in.value());\n    out = static_cast<const Derived*>(this)->shift(ValueType(in),shift_arg);\n    point p1 = static_cast<const Derived*>(this)->find_nearest(out);\n    if (!almost_equal(p1.value(), out, std::abs(p1.value() - ((p1.index()!=0)?vals_[p1.index() - 1]:vals_[p1.index()+1]).value())/10.)) {\n#ifndef NDEBUG\n      ERROR(\"Couldn't shift point\" <<  in << \" by \" << shift_arg << \" got \" << out);\n#endif\n      throw gftools::ex_generic(\"grid_base::shift : Couldn't shift point\");\n    }\n    else return p1;\n}\n\ntemplate <typename ValueType, class Derived>\ninline ValueType grid_base<ValueType,Derived>::shift(ValueType in, ValueType shift_arg) const\n{\n    return in+shift_arg;\n}\n\ntemplate <typename ValueType, class Derived>\ninline typename grid_base<ValueType,Derived>::point grid_base<ValueType,Derived>::shift(point in, point shift_arg) const\n{\n    size_t index = (in.index() + shift_arg.index())%vals_.size();\n    #ifndef NDEBUG\n    ValueType val = static_cast<const Derived*>(this)->shift(in.value(), shift_arg.value());\n    if (!almost_equal(val, vals_[index].value())) throw gftools::ex_generic(\"grid_base::shift : almost equal failed.\");\n    #endif\n    return vals_[index];\n\n}\n\ntemplate <typename ValueType, class Derived>\ninline bool grid_base<ValueType,Derived>::operator==(const grid_base &rhs) const\n{\n    bool out = (this->size() == rhs.size());\n    for (size_t i=0; i<vals_.size() && out; i++) {\n        out = out && almost_equal(vals_[i].value(), rhs.vals_[i].value(), num_io<double>::tolerance());\n    }\n    return out;\n}\n\n\ntemplate <typename ValueType, class Derived>\nstd::ostream& operator<<(std::ostream& lhs, const grid_base<ValueType,Derived> &gr)\n{\n    lhs << \"{\";\n    //lhs << gr.vals_;\n    std::ostream_iterator<ValueType> out_it (lhs,\", \");\n    std::transform(gr.vals_.begin(),gr.vals_.end(), out_it, [](const typename grid_base<ValueType,Derived>::point &x){return ValueType(x);});\n    lhs << \"}\";\n    return lhs;\n}\n\n} // end :: namespace gftools\n", "meta": {"hexsha": "b62893ef5c8969a1788f69cee515e1e4267b5e3c", "size": 10933, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "gftools/grid_base.hpp", "max_stars_repo_name": "hmenke/gftools", "max_stars_repo_head_hexsha": "d79810dd705b8e2efa802321382ebb7658e5f452", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2015-02-10T01:30:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-18T14:29:32.000Z", "max_issues_repo_path": "gftools/grid_base.hpp", "max_issues_repo_name": "hmenke/gftools", "max_issues_repo_head_hexsha": "d79810dd705b8e2efa802321382ebb7658e5f452", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2015-04-01T12:38:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-17T21:21:38.000Z", "max_forks_repo_path": "gftools/grid_base.hpp", "max_forks_repo_name": "hmenke/gftools", "max_forks_repo_head_hexsha": "d79810dd705b8e2efa802321382ebb7658e5f452", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2015-05-11T16:45:59.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-11T04:44:44.000Z", "avg_line_length": 37.7, "max_line_length": 180, "alphanum_fraction": 0.6853562609, "num_tokens": 2679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.6825737214979745, "lm_q1q2_score": 0.49049364878466567}}
{"text": "/*****************************************************************************\n*\n* Rokko: Integrated Interface for libraries of eigenvalue decomposition\n*\n* Copyright (C) 2012-2015 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#include <mpi.h>\n#include <iostream>\n#include <rokko/rokko.hpp>\n#include <rokko/collective.hpp>\n#include <rokko/utility/frank_matrix.hpp>\n#include <boost/lexical_cast.hpp>\n\ntypedef rokko::matrix_col_major matrix_major;\n// typedef rokko::matrix_row_major matrix_major;\n\nint main(int argc, char *argv[]) {\n  MPI_Init(&argc, &argv);\n  unsigned int dim = 10;\n  std::string solver_name(rokko::parallel_dense_solver::default_solver());\n  if (argc >= 2) solver_name = argv[1];\n  if (argc >= 3) dim = boost::lexical_cast<unsigned int>(argv[2]);\n\n  rokko::grid g;\n  if (g.get_myrank() == 0) std::cout << \"dimension = \" << dim << std::endl;\n  std::cout << std::flush;\n  MPI_Barrier(g.get_comm());\n\n  rokko::parallel_dense_solver solver(solver_name);\n  solver.initialize(argc, argv);\n  rokko::distributed_matrix<double, matrix_major> mat(dim, dim, g, solver);\n  rokko::frank_matrix::generate(mat);\n  mat.print();\n\n  rokko::localized_matrix<double, matrix_major> lmat(dim, dim);\n  for (int proc = 0; proc < g.get_nprocs(); ++proc) {\n    rokko::gather(mat, lmat, proc);\n    if (g.get_myrank() == proc) {\n      std::cout << \"root = \" << proc << std::endl;\n      std::cout << \"lmat:\" << std::endl << lmat << std::endl;\n    }\n    std::cout << std::flush;\n    MPI_Barrier(g.get_comm());\n  }\n\n  solver.finalize();\n  MPI_Finalize();\n  return 0;\n}\n", "meta": {"hexsha": "fcc7d1ab7662ffe8fc6eaa6fb08a2342d1bfa550", "size": 1798, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/cxx/dense/all_gather_mpi.cpp", "max_stars_repo_name": "wistaria/rokko", "max_stars_repo_head_hexsha": "7cd9d5155e82f038039a46c1dc8f382b3fe7e2b7", "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": "example/cxx/dense/all_gather_mpi.cpp", "max_issues_repo_name": "wistaria/rokko", "max_issues_repo_head_hexsha": "7cd9d5155e82f038039a46c1dc8f382b3fe7e2b7", "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": "example/cxx/dense/all_gather_mpi.cpp", "max_forks_repo_name": "wistaria/rokko", "max_forks_repo_head_hexsha": "7cd9d5155e82f038039a46c1dc8f382b3fe7e2b7", "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.6909090909, "max_line_length": 79, "alphanum_fraction": 0.6201334816, "num_tokens": 485, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943805178139, "lm_q2_score": 0.6825737214979745, "lm_q1q2_score": 0.49049364055757577}}
{"text": "//\n// Copyright (c) 2015-2019 CNRS INRIA\n//\n\n#include <iostream>\n\n#include \"pinocchio/spatial/force.hpp\"\n#include \"pinocchio/spatial/motion.hpp\"\n#include \"pinocchio/spatial/se3.hpp\"\n#include \"pinocchio/spatial/inertia.hpp\"\n#include \"pinocchio/spatial/act-on-set.hpp\"\n#include \"pinocchio/spatial/explog.hpp\"\n#include \"pinocchio/spatial/skew.hpp\"\n#include \"pinocchio/spatial/cartesian-axis.hpp\"\n#include \"pinocchio/spatial/spatial-axis.hpp\"\n\n#include <boost/test/unit_test.hpp>\n#include <boost/utility/binary.hpp>\n\nBOOST_AUTO_TEST_SUITE ( BOOST_TEST_MODULE )\n\nBOOST_AUTO_TEST_CASE ( test_SE3 )\n{\n  using namespace pinocchio;\n  typedef SE3::HomogeneousMatrixType HomogeneousMatrixType;\n  typedef SE3::ActionMatrixType ActionMatrixType;\n  typedef SE3::Vector3 Vector3;\n  typedef Eigen::Matrix<double,4,1> Vector4;\n  \n  const SE3 identity = SE3::Identity();\n\n  typedef SE3::Quaternion Quaternion;\n  typedef SE3::Vector4 Vector4;\n  Quaternion quat(Vector4::Random().normalized());\n\n  SE3 m_from_quat(quat,Vector3::Random());\n\n  SE3 amb = SE3::Random();\n  SE3 bmc = SE3::Random();\n  SE3 amc = amb*bmc;\n\n  HomogeneousMatrixType aMb = amb;\n  HomogeneousMatrixType bMc = bmc;\n\n  // Test internal product\n  HomogeneousMatrixType aMc = amc;\n  BOOST_CHECK(aMc.isApprox(aMb*bMc));\n\n  HomogeneousMatrixType bMa = amb.inverse();\n  BOOST_CHECK(bMa.isApprox(aMb.inverse()));\n\n  // Test point action\n  Vector3 p = Vector3::Random();\n  Vector4 p4; p4.head(3) = p; p4[3] = 1;\n\n  Vector3 Mp = (aMb*p4).head(3);\n  BOOST_CHECK(amb.act(p).isApprox(Mp));\n\n  Vector3 Mip = (aMb.inverse()*p4).head(3);\n  BOOST_CHECK(amb.actInv(p).isApprox(Mip));\n\n  // Test action matrix\n  ActionMatrixType aXb = amb;\n  ActionMatrixType bXc = bmc;\n  ActionMatrixType aXc = amc;\n  BOOST_CHECK(aXc.isApprox(aXb*bXc));\n  \n  ActionMatrixType bXa = amb.inverse();\n  BOOST_CHECK(bXa.isApprox(aXb.inverse()));\n  \n  ActionMatrixType X_identity = identity.toActionMatrix();\n  BOOST_CHECK(X_identity.isIdentity());\n  \n  ActionMatrixType X_identity_inverse = identity.toActionMatrixInverse();\n  BOOST_CHECK(X_identity_inverse.isIdentity());\n  \n  // Test dual action matrix\n  BOOST_CHECK(aXb.inverse().transpose().isApprox(amb.toDualActionMatrix()));\n\n  // Test isIdentity\n  BOOST_CHECK(identity.isIdentity());\n  \n  // Test isApprox\n  BOOST_CHECK(identity.isApprox(identity));\n  \n  // Test cast\n  typedef SE3Tpl<float> SE3f;\n  SE3f::Matrix3 rot_float(amb.rotation().cast<float>());\n  SE3f amb_float = amb.cast<float>();\n  BOOST_CHECK(amb_float.isApprox(amb.cast<float>()));\n  \n  // Test actInv\n  const SE3 M = SE3::Random();\n  const SE3 Minv = M.inverse();\n  \n  BOOST_CHECK(Minv.actInv(Minv).isIdentity());\n  BOOST_CHECK(M.actInv(identity).isApprox(Minv));\n}\n\nBOOST_AUTO_TEST_CASE ( test_Motion )\n{\n  using namespace pinocchio;\n  typedef SE3::ActionMatrixType ActionMatrixType;\n  typedef Motion::Vector6 Vector6;\n\n  SE3 amb = SE3::Random();\n  SE3 bmc = SE3::Random();\n  SE3 amc = amb*bmc;\n\n  Motion bv = Motion::Random();\n  Motion bv2 = Motion::Random();\n  \n  typedef MotionBase<Motion> Base;\n\n  Vector6 bv_vec = bv;\n  Vector6 bv2_vec = bv2;\n  \n  // std::stringstream\n  std::stringstream ss;\n  ss << bv << std::endl;\n  BOOST_CHECK(!ss.str().empty());\n  \n  // Test .+.\n  Vector6 bvPbv2_vec = bv+bv2;\n  BOOST_CHECK(bvPbv2_vec.isApprox(bv_vec+bv2_vec));\n  \n  Motion bplus = static_cast<Base &>(bv) + static_cast<Base &>(bv2);\n  BOOST_CHECK((bv+bv2).isApprox(bplus));\n  \n  Motion v_not_zero(Vector6::Ones());\n  BOOST_CHECK(!v_not_zero.isZero());\n  \n  Motion v_zero(Vector6::Zero());\n  BOOST_CHECK(v_zero.isZero());\n  \n  // Test == and !=\n  BOOST_CHECK(bv == bv);\n  BOOST_CHECK(!(bv != bv));\n\n  // Test -.\n  Vector6 Mbv_vec = -bv;\n  BOOST_CHECK( Mbv_vec.isApprox(-bv_vec));\n\n  // Test .+=.\n  Motion bv3 = bv; bv3 += bv2;\n  BOOST_CHECK( bv3.toVector().isApprox(bv_vec+bv2_vec));\n\n  // Test .=V6\n  bv3 = bv2_vec;\n  BOOST_CHECK( bv3.toVector().isApprox(bv2_vec));\n  \n  // Test scalar*M6\n  Motion twicebv(2.*bv);\n  BOOST_CHECK(twicebv.isApprox(Motion(2.*bv.toVector())));\n  \n  // Test M6*scalar\n  Motion bvtwice(bv*2.);\n  BOOST_CHECK(bvtwice.isApprox(twicebv));\n  \n  // Test M6/scalar\n  Motion bvdividedbytwo(bvtwice/2.);\n  BOOST_CHECK(bvdividedbytwo.isApprox(bv));\n\n  // Test constructor from V6\n  Motion bv4(bv2_vec);\n  BOOST_CHECK( bv4.toVector().isApprox(bv2_vec));\n\n  // Test action\n  ActionMatrixType aXb = amb;\n  BOOST_CHECK(amb.act(bv).toVector().isApprox(aXb*bv_vec));\n\n  // Test action inverse\n  ActionMatrixType bXc = bmc;\n  BOOST_CHECK(bmc.actInv(bv).toVector().isApprox(bXc.inverse()*bv_vec));\n\n  // Test double action\n  Motion cv = Motion::Random();\n  bv = bmc.act(cv);\n  BOOST_CHECK(amb.act(bv).toVector().isApprox(amc.act(cv).toVector()));\n\n  // Simple test for cross product vxv\n  Motion vxv = bv.cross(bv);\n  BOOST_CHECK_SMALL(vxv.toVector().tail(3).norm(), 1e-3); //previously ensure that (vxv.toVector().tail(3).isMuchSmallerThan(1e-3));\n\n  // Test Action Matrix\n  Motion v2xv = bv2.cross(bv);\n  Motion::ActionMatrixType actv2 = bv2.toActionMatrix();\n  \n  BOOST_CHECK(v2xv.toVector().isApprox(actv2*bv.toVector()));\n  \n  // Test Dual Action Matrix\n  Force f(bv.toVector());\n  Force v2xf = bv2.cross(f);\n  Motion::ActionMatrixType dualactv2 = bv2.toDualActionMatrix();\n  \n  BOOST_CHECK(v2xf.toVector().isApprox(dualactv2*f.toVector()));\n  BOOST_CHECK(dualactv2.isApprox(-actv2.transpose()));\n  \n  // Simple test for cross product vxf\n  Force vxf = bv.cross(f);\n  BOOST_CHECK(vxf.linear().isApprox(bv.angular().cross(f.linear())));\n  BOOST_CHECK_SMALL(vxf.angular().norm(), 1e-3);//previously ensure that ( vxf.angular().isMuchSmallerThan(1e-3));\n\n  // Test frame change for vxf\n  Motion av = Motion::Random();\n  Force af = Force::Random();\n  bv = amb.actInv(av);\n  Force bf = amb.actInv(af);\n  Force avxf = av.cross(af);\n  Force bvxf = bv.cross(bf);\n  BOOST_CHECK(avxf.toVector().isApprox(amb.act(bvxf).toVector()));\n\n  // Test frame change for vxv\n  av = Motion::Random();\n  Motion aw = Motion::Random();\n  bv = amb.actInv(av);\n  Motion bw = amb.actInv(aw);\n  Motion avxw = av.cross(aw);\n  Motion bvxw = bv.cross(bw);\n  BOOST_CHECK(avxw.toVector().isApprox(amb.act(bvxw).toVector()));\n  \n  // Test isApprox\n  bv.toVector().setOnes();\n  const double eps = 1e-6;\n  BOOST_CHECK(bv == bv);\n  BOOST_CHECK(bv.isApprox(bv));\n  Motion bv_approx(bv);\n  bv_approx.linear()[0] += eps;\n  BOOST_CHECK(bv_approx.isApprox(bv,eps));\n  \n  // Test ref() method\n  {\n    Motion a(Motion::Random());\n    BOOST_CHECK(a.ref().isApprox(a));\n    \n    const Motion b(a);\n    BOOST_CHECK(b.isApprox(a.ref()));\n  }\n  \n  // Test cast\n  {\n    typedef MotionTpl<float> Motionf;\n    Motion a(Motion::Random());\n    Motionf a_float = a.cast<float>();\n    BOOST_CHECK(a_float.isApprox(a.cast<float>()));\n  }\n}\n\nBOOST_AUTO_TEST_CASE (test_motion_ref)\n{\n  using namespace pinocchio;\n  typedef Motion::Vector6 Vector6;\n  \n  typedef MotionRef<Vector6> MotionV6;\n  \n  Motion v_ref(Motion::Random());\n  MotionV6 v(v_ref.toVector());\n  \n  BOOST_CHECK(v_ref.isApprox(v));\n  \n  MotionV6::MotionPlain v2(v*2.);\n  Motion v2_ref(v_ref*2.);\n  \n  BOOST_CHECK(v2_ref.isApprox(v2));\n  \n  v2 = v_ref + v;\n  BOOST_CHECK(v2_ref.isApprox(v2));\n  \n  v = v2;\n  BOOST_CHECK(v2.isApprox(v));\n  \n  v2 = v - v;\n  BOOST_CHECK(v2.isApprox(Motion::Zero()));\n  \n  SE3 M(SE3::Identity());\n  v2 = M.act(v);\n  BOOST_CHECK(v2.isApprox(v));\n  \n  v2 = M.actInv(v);\n  BOOST_CHECK(v2.isApprox(v));\n  \n  Motion v3(Motion::Random());\n  v_ref.setRandom();\n  v = v_ref;\n  v2 = v.cross(v3);\n  v2_ref = v_ref.cross(v3);\n  \n  BOOST_CHECK(v2.isApprox(v2_ref));\n  \n  v.setRandom();\n  v.setZero();\n  BOOST_CHECK(v.isApprox(Motion::Zero()));\n  \n  // Test ref() method\n  {\n    Vector6 v6(Vector6::Random());\n    MotionV6 a(v6);\n    BOOST_CHECK(a.ref().isApprox(a));\n    \n    const Motion b(a);\n    BOOST_CHECK(b.isApprox(a.ref()));\n  }\n  \n}\n\nBOOST_AUTO_TEST_CASE(test_motion_zero)\n{\n  using namespace pinocchio;\n  Motion v((MotionZero()));\n  \n  BOOST_CHECK(v.toVector().isZero());\n  BOOST_CHECK(MotionZero() == Motion::Zero());\n  \n  // SE3.act\n  SE3 m(SE3::Random());\n  BOOST_CHECK(m.act(MotionZero()) == Motion::Zero());\n  BOOST_CHECK(m.actInv(MotionZero()) == Motion::Zero());\n  \n  // Motion.cross\n  Motion v2(Motion::Random());\n  BOOST_CHECK(v2.cross(MotionZero()) == Motion::Zero());\n}\n\nBOOST_AUTO_TEST_CASE ( test_Force )\n{\n  using namespace pinocchio;\n  typedef SE3::ActionMatrixType ActionMatrixType;\n  typedef Force::Vector6 Vector6;\n\n  SE3 amb = SE3::Random();\n  SE3 bmc = SE3::Random();\n  SE3 amc = amb*bmc;\n\n  Force bf = Force::Random();\n  Force bf2 = Force::Random();\n\n  Vector6 bf_vec = bf;\n  Vector6 bf2_vec = bf2;\n  \n  // std::stringstream\n  std::stringstream ss;\n  ss << bf << std::endl;\n  BOOST_CHECK(!ss.str().empty());\n  \n  // Test .+.\n  Vector6 bfPbf2_vec = bf+bf2;\n  BOOST_CHECK(bfPbf2_vec.isApprox(bf_vec+bf2_vec));\n\n  // Test -.\n  Vector6 Mbf_vec = -bf;\n  BOOST_CHECK(Mbf_vec.isApprox(-bf_vec));\n\n  // Test .+=.\n  Force bf3 = bf; bf3 += bf2;\n  BOOST_CHECK(bf3.toVector().isApprox(bf_vec+bf2_vec));\n\n  // Test .= V6\n  bf3 = bf2_vec;\n  BOOST_CHECK(bf3.toVector().isApprox(bf2_vec));\n\n  // Test constructor from V6\n  Force bf4(bf2_vec);\n  BOOST_CHECK(bf4.toVector().isApprox(bf2_vec));\n\n  // Test action\n  ActionMatrixType aXb = amb;\n  BOOST_CHECK(amb.act(bf).toVector().isApprox(aXb.inverse().transpose()*bf_vec));\n\n  // Test action inverse\n  ActionMatrixType bXc = bmc;\n  BOOST_CHECK(bmc.actInv(bf).toVector().isApprox(bXc.transpose()*bf_vec));\n\n  // Test double action\n  Force cf = Force::Random();\n  bf = bmc.act(cf);\n  BOOST_CHECK(amb.act(bf).toVector().isApprox(amc.act(cf).toVector()));\n\n  // Simple test for cross product\n  // Force vxv = bf.cross(bf);\n  // ensure that (vxv.toVector().isMuchSmallerThan(bf.toVector()));\n  \n  Force f_not_zero(Vector6::Ones());\n  BOOST_CHECK(!f_not_zero.isZero());\n  \n  Force f_zero(Vector6::Zero());\n  BOOST_CHECK(f_zero.isZero());\n  \n  // Test isApprox\n  \n  BOOST_CHECK(bf == bf);\n  bf.setRandom();\n  bf2.setZero();\n  BOOST_CHECK(bf == bf);\n  BOOST_CHECK(bf != bf2);\n  BOOST_CHECK(bf.isApprox(bf));\n  BOOST_CHECK(!bf.isApprox(bf2));\n  \n  const double eps = 1e-6;\n  Force bf_approx(bf);\n  bf_approx.linear()[0] += eps/2.;\n  BOOST_CHECK(bf_approx.isApprox(bf,eps));\n  \n  // Test ref() method\n  {\n    Force a(Force::Random());\n    BOOST_CHECK(a.ref().isApprox(a));\n    \n    const Force b(a);\n    BOOST_CHECK(b.isApprox(a.ref()));\n  }\n  \n  // Test cast\n  {\n    typedef ForceTpl<float> Forcef;\n    Force a(Force::Random());\n    Forcef a_float = a.cast<float>();\n    BOOST_CHECK(a_float.isApprox(a.cast<float>()));\n  }\n  \n  // Test scalar multiplication\n  const double alpha = 1.5;\n  Force b(Force::Random());\n  Force alpha_f = alpha * b;\n  Force f_alpha = b * alpha;\n  \n  BOOST_CHECK(alpha_f == f_alpha);\n}\n\nBOOST_AUTO_TEST_CASE (test_force_ref)\n{\n  using namespace pinocchio;\n  typedef Force::Vector6 Vector6;\n\n  typedef ForceRef<Vector6> ForceV6;\n  \n  Force f_ref(Force::Random());\n  ForceV6 f(f_ref.toVector());\n  \n  BOOST_CHECK(f_ref.isApprox(f));\n  \n  ForceV6::ForcePlain f2(f*2.);\n  Force f2_ref(f_ref*2.);\n  \n  BOOST_CHECK(f2_ref.isApprox(f2));\n  \n  f2 = f_ref + f;\n  BOOST_CHECK(f2_ref.isApprox(f2));\n  \n  f = f2;\n  BOOST_CHECK(f2.isApprox(f));\n  \n  f2 = f - f;\n  BOOST_CHECK(f2.isApprox(Force::Zero()));\n  \n  SE3 M(SE3::Identity());\n  f2 = M.act(f);\n  BOOST_CHECK(f2.isApprox(f));\n  \n  f2 = M.actInv(f);\n  BOOST_CHECK(f2.isApprox(f));\n  \n  Motion v(Motion::Random());\n  f_ref.setRandom();\n  f = f_ref;\n  f2 = v.cross(f);\n  f2_ref = v.cross(f_ref);\n  \n  BOOST_CHECK(f2.isApprox(f2_ref));\n  \n  f.setRandom();\n  f.setZero();\n  BOOST_CHECK(f.isApprox(Force::Zero()));\n  \n  // Test ref() method\n  {\n    Vector6 v6(Vector6::Random());\n    ForceV6 a(v6);\n    BOOST_CHECK(a.ref().isApprox(a));\n    \n    const Force b(a);\n    BOOST_CHECK(b.isApprox(a.ref()));\n  }\n}\n\nBOOST_AUTO_TEST_CASE ( test_Inertia )\n{\n  using namespace pinocchio;\n  typedef Inertia::Matrix6 Matrix6;\n\n  Inertia aI = Inertia::Random();\n  Matrix6 matI = aI;\n  BOOST_CHECK_EQUAL(matI(0,0), aI.mass());\n  BOOST_CHECK_EQUAL(matI(1,1), aI.mass());\n  BOOST_CHECK_EQUAL(matI(2,2), aI.mass()); // 1,1 before unifying \n\n  BOOST_CHECK_SMALL((matI-matI.transpose()).norm(),matI.norm()); //previously ensure that( (matI-matI.transpose()).isMuchSmallerThan(matI) );\n  BOOST_CHECK_SMALL((matI.topRightCorner<3,3>()*aI.lever()).norm(),\n            aI.lever().norm()); //previously ensure that( (matI.topRightCorner<3,3>()*aI.lever()).isMuchSmallerThan(aI.lever()) );\n\n  Inertia I1 = Inertia::Identity();\n  BOOST_CHECK(I1.matrix().isApprox(Matrix6::Identity()));\n\n  // Test motion-to-force map\n  Motion v = Motion::Random();\n  Force f = I1 * v;\n  BOOST_CHECK(f.toVector().isApprox(v.toVector()));\n  \n  // Test Inertia group application\n  SE3 bma = SE3::Random(); \n  Inertia bI = bma.act(aI);\n  Matrix6 bXa = bma;\n  BOOST_CHECK((bma.rotation()*aI.inertia().matrix()*bma.rotation().transpose())\n                               .isApprox(bI.inertia().matrix()));\n  BOOST_CHECK((bXa.transpose().inverse() * aI.matrix() * bXa.inverse())\n                              .isApprox(bI.matrix()));\n\n  // Test inverse action\n  BOOST_CHECK((bXa.transpose() * bI.matrix() * bXa)\n                              .isApprox(bma.actInv(bI).matrix()));\n\n  // Test vxIv cross product\n  v = Motion::Random(); \n  f = aI*v;\n  Force vxf = v.cross(f);\n  Force vxIv = aI.vxiv(v);\n  BOOST_CHECK(vxf.toVector().isApprox(vxIv.toVector()));\n\n  // Test operator+\n  I1 = Inertia::Random();\n  Inertia I2 = Inertia::Random();\n  BOOST_CHECK((I1.matrix()+I2.matrix()).isApprox((I1+I2).matrix()));\n\n  // operator +=\n  Inertia I12 = I1;\n  I12 += I2;\n  BOOST_CHECK((I1.matrix()+I2.matrix()).isApprox(I12.matrix()));\n  \n  // Test operator vtiv\n  double kinetic_ref = v.toVector().transpose() * aI.matrix() * v.toVector();\n  double kinetic = aI.vtiv(v);\n  BOOST_CHECK_SMALL(kinetic_ref - kinetic, 1e-12);\n\n  // Test constructor (Matrix6)\n  Inertia I1_bis(I1.matrix());\n  BOOST_CHECK(I1.matrix().isApprox(I1_bis.matrix()));\n\n  // Test Inertia from ellipsoid\n  I1 = Inertia::FromEllipsoid(2., 3., 4., 5.);\n  BOOST_CHECK_SMALL(I1.mass() - 2, 1e-12);\n  BOOST_CHECK_SMALL(I1.lever().norm(), 1e-12);\n  BOOST_CHECK(I1.inertia().matrix().isApprox(Symmetric3(\n          16.4, 0., 13.6, 0., 0., 10.).matrix()));\n\n  // Test Inertia from Cylinder\n  I1 = Inertia::FromCylinder(2., 4., 6.);\n  BOOST_CHECK_SMALL(I1.mass() - 2, 1e-12);\n  BOOST_CHECK_SMALL(I1.lever().norm(), 1e-12);\n  BOOST_CHECK(I1.inertia().matrix().isApprox(Symmetric3(\n        14., 0., 14., 0., 0., 16.).matrix()));\n\n  // Test Inertia from Box\n  I1 = Inertia::FromBox(2., 6., 12., 18.);\n  BOOST_CHECK_SMALL(I1.mass() - 2, 1e-12);\n  BOOST_CHECK_SMALL(I1.lever().norm(), 1e-12);\n  BOOST_CHECK(I1.inertia().matrix().isApprox(Symmetric3(\n        78., 0., 60., 0., 0., 30.).matrix()));\n  \n  // Copy operator\n  Inertia aI_copy(aI);\n  BOOST_CHECK(aI_copy == aI);\n  \n  // Test isZero\n  Inertia I_not_zero = Inertia::Identity();\n  BOOST_CHECK(!I_not_zero.isZero());\n  \n  Inertia I_zero = Inertia::Zero();\n  BOOST_CHECK(I_zero.isZero());\n  \n  // Test isApprox\n  const double eps = 1e-6;\n  BOOST_CHECK(aI == aI);\n  BOOST_CHECK(aI.isApprox(aI));\n  Inertia aI_approx(aI);\n  aI_approx.mass() += eps/2.;\n  BOOST_CHECK(aI_approx.isApprox(aI,eps));\n  \n  // Test Variation\n  Inertia::Matrix6 aIvariation = aI.variation(v);\n  \n  Motion::ActionMatrixType vAction = v.toActionMatrix();\n  Motion::ActionMatrixType vDualAction = v.toDualActionMatrix();\n  \n  Inertia::Matrix6 aImatrix = aI.matrix();\n  Inertia::Matrix6 aIvariation_ref = vDualAction * aImatrix - aImatrix * vAction;\n  \n  BOOST_CHECK(aIvariation.isApprox(aIvariation_ref));\n  BOOST_CHECK(vxIv.isApprox(Force(aIvariation*v.toVector())));\n  \n  // Test vxI operator\n  {\n    typedef Inertia::Matrix6 Matrix6;\n    Inertia I(Inertia::Random());\n    Motion v(Motion::Random());\n    \n    const Matrix6 M_ref(v.toDualActionMatrix()*I.matrix());\n    Matrix6 M; Inertia::vxi(v,I,M);\n    \n    BOOST_CHECK(M.isApprox(M_ref));\n    BOOST_CHECK(I.vxi(v).isApprox(M_ref));\n  }\n  \n  // Test Ivx operator\n  {\n    typedef Inertia::Matrix6 Matrix6;\n    Inertia I(Inertia::Random());\n    Motion v(Motion::Random());\n    \n    const Matrix6 M_ref(I.matrix()*v.toActionMatrix());\n    Matrix6 M; Inertia::ivx(v,I,M);\n    \n    BOOST_CHECK(M.isApprox(M_ref));\n    BOOST_CHECK(I.ivx(v).isApprox(M_ref));\n  }\n  \n  // Test variation against vxI - Ivx operator\n  {\n    typedef Inertia::Matrix6 Matrix6;\n    Inertia I(Inertia::Random());\n    Motion v(Motion::Random());\n    \n    Matrix6 Ivariation = I.variation(v);\n    \n    Matrix6 M1; Inertia::vxi(v,I,M1);\n    Matrix6 M2; Inertia::ivx(v,I,M2);\n    Matrix6 M3(M1-M2);\n    \n    BOOST_CHECK(M3.isApprox(Ivariation));\n  }\n\n  // Test dynamic parameters\n  {\n    Inertia I(Inertia::Random());\n\n    Inertia::Vector10 v = I.toDynamicParameters();\n\n    BOOST_CHECK_CLOSE(v[0], I.mass(), 1e-12);\n\n    BOOST_CHECK(v.segment<3>(1).isApprox(I.mass()*I.lever()));\n\n    Eigen::Matrix3d I_o = I.inertia() + I.mass()*skew(I.lever()).transpose()*skew(I.lever());\n    Eigen::Matrix3d I_ov;\n    I_ov << v[4], v[5], v[7],\n            v[5], v[6], v[8],\n            v[7], v[8], v[9];\n\n    BOOST_CHECK(I_o.isApprox(I_ov));\n\n    Inertia I2 = Inertia::FromDynamicParameters(v);\n    BOOST_CHECK(I2.isApprox(I));\n\n  }\n\n}\n\nBOOST_AUTO_TEST_CASE(cast_inertia)\n{\n  using namespace pinocchio;\n  Inertia Y(Inertia::Random());\n  \n  BOOST_CHECK(Y.cast<double>() == Y);\n  BOOST_CHECK(Y.cast<long double>().cast<double>() == Y);\n}\n\nBOOST_AUTO_TEST_CASE ( test_ActOnSet )\n{\n  using namespace pinocchio;\n  const int N = 20;\n  typedef Eigen::Matrix<double,6,N> Matrix6N;\n  SE3 jMi = SE3::Random();\n  Motion v = Motion::Random();\n\n  // Forcet SET\n  Matrix6N iF = Matrix6N::Random(),jF,jFinv,jF_ref,jFinv_ref;\n  \n  // forceSet::se3Action\n  forceSet::se3Action(jMi,iF,jF);\n  for( int k=0;k<N;++k )\n    BOOST_CHECK(jMi.act(Force(iF.col(k))).toVector().isApprox(jF.col(k)));\n  \n  jF_ref = jMi.toDualActionMatrix()*iF;\n  BOOST_CHECK(jF_ref.isApprox(jF));\n  \n  forceSet::se3ActionInverse(jMi.inverse(),iF,jFinv);\n  BOOST_CHECK(jFinv.isApprox(jF));\n  \n  Matrix6N iF2 = Matrix6N::Random();\n  jF_ref += jMi.toDualActionMatrix() * iF2;\n  \n  forceSet::se3Action<ADDTO>(jMi,iF2,jF);\n  BOOST_CHECK(jF.isApprox(jF_ref));\n  \n  Matrix6N iF3 = Matrix6N::Random();\n  jF_ref -= jMi.toDualActionMatrix() * iF3;\n  \n  forceSet::se3Action<RMTO>(jMi,iF3,jF);\n  BOOST_CHECK(jF.isApprox(jF_ref));\n  \n  // forceSet::se3ActionInverse\n  forceSet::se3ActionInverse(jMi,iF,jFinv);\n  jFinv_ref = jMi.inverse().toDualActionMatrix() * iF;\n  BOOST_CHECK(jFinv_ref.isApprox(jFinv));\n  \n  jFinv_ref += jMi.inverse().toDualActionMatrix() * iF2;\n  forceSet::se3ActionInverse<ADDTO>(jMi,iF2,jFinv);\n  BOOST_CHECK(jFinv.isApprox(jFinv_ref));\n  \n  jFinv_ref -= jMi.inverse().toDualActionMatrix() * iF3;\n  forceSet::se3ActionInverse<RMTO>(jMi,iF3,jFinv);\n  BOOST_CHECK(jFinv.isApprox(jFinv_ref));\n  \n  // forceSet::motionAction\n  forceSet::motionAction(v,iF,jF);\n  for( int k=0;k<N;++k )\n    BOOST_CHECK(v.cross(Force(iF.col(k))).toVector().isApprox(jF.col(k)));\n  \n  jF_ref = v.toDualActionMatrix() * iF;\n  BOOST_CHECK(jF.isApprox(jF_ref));\n  \n  jF_ref += v.toDualActionMatrix() * iF2;\n  forceSet::motionAction<ADDTO>(v,iF2,jF);\n  BOOST_CHECK(jF.isApprox(jF_ref));\n  \n  jF_ref -= v.toDualActionMatrix() * iF3;\n  forceSet::motionAction<RMTO>(v,iF3,jF);\n  BOOST_CHECK(jF.isApprox(jF_ref));\n  \n  // Motion SET\n  Matrix6N iV = Matrix6N::Random(),jV,jV_ref,jVinv,jVinv_ref;\n  \n  // motionSet::se3Action\n  motionSet::se3Action(jMi,iV,jV);\n  for( int k=0;k<N;++k )\n    BOOST_CHECK(jMi.act(Motion(iV.col(k))).toVector().isApprox(jV.col(k)));\n  \n  jV_ref = jMi.toActionMatrix()*iV;\n  BOOST_CHECK(jV.isApprox(jV_ref));\n  \n  motionSet::se3ActionInverse(jMi.inverse(),iV,jVinv);\n  BOOST_CHECK(jVinv.isApprox(jV));\n  \n  Matrix6N iV2 = Matrix6N::Random();\n  jV_ref += jMi.toActionMatrix()*iV2;\n  motionSet::se3Action<ADDTO>(jMi,iV2,jV);\n  BOOST_CHECK(jV.isApprox(jV_ref));\n  \n  Matrix6N iV3 = Matrix6N::Random();\n  jV_ref -= jMi.toActionMatrix()*iV3;\n  motionSet::se3Action<RMTO>(jMi,iV3,jV);\n  BOOST_CHECK(jV.isApprox(jV_ref));\n  \n  // motionSet::se3ActionInverse\n  motionSet::se3ActionInverse(jMi,iV,jVinv);\n  jVinv_ref = jMi.inverse().toActionMatrix() * iV;\n  BOOST_CHECK(jVinv.isApprox(jVinv_ref));\n  \n  jVinv_ref += jMi.inverse().toActionMatrix()*iV2;\n  motionSet::se3ActionInverse<ADDTO>(jMi,iV2,jVinv);\n  BOOST_CHECK(jVinv.isApprox(jVinv_ref));\n  \n  jVinv_ref -= jMi.inverse().toActionMatrix()*iV3;\n  motionSet::se3ActionInverse<RMTO>(jMi,iV3,jVinv);\n  BOOST_CHECK(jVinv.isApprox(jVinv_ref));\n  \n  // motionSet::motionAction\n  motionSet::motionAction(v,iV,jV);\n  for( int k=0;k<N;++k )\n    BOOST_CHECK(v.cross(Motion(iV.col(k))).toVector().isApprox(jV.col(k)));\n  \n  jV_ref = v.toActionMatrix()*iV;\n  BOOST_CHECK(jV.isApprox(jV_ref));\n  \n  jV_ref += v.toActionMatrix()*iV2;\n  motionSet::motionAction<ADDTO>(v,iV2,jV);\n  BOOST_CHECK(jV.isApprox(jV_ref));\n  \n  jV_ref -= v.toActionMatrix()*iV3;\n  motionSet::motionAction<RMTO>(v,iV3,jV);\n  BOOST_CHECK(jV.isApprox(jV_ref));\n  \n  // motionSet::inertiaAction\n  const Inertia I(Inertia::Random());\n  motionSet::inertiaAction(I,iV,jV);\n  for( int k=0;k<N;++k )\n    BOOST_CHECK((I*(Motion(iV.col(k)))).toVector().isApprox(jV.col(k)));\n  \n  jV_ref = I.matrix()*iV;\n  BOOST_CHECK(jV.isApprox(jV_ref));\n  \n  jV_ref += I.matrix()*iV2;\n  motionSet::inertiaAction<ADDTO>(I,iV2,jV);\n  BOOST_CHECK(jV.isApprox(jV_ref));\n  \n  jV_ref -= I.matrix()*iV3;\n  motionSet::inertiaAction<RMTO>(I,iV3,jV);\n  BOOST_CHECK(jV.isApprox(jV_ref));\n \n  // motionSet::act\n  Force f = Force::Random();\n  motionSet::act(iV,f,jF);\n  for( int k=0;k<N;++k )\n    BOOST_CHECK(Motion(iV.col(k)).cross(f).toVector().isApprox(jF.col(k)));\n  \n  for( int k=0;k<N;++k )\n    jF_ref.col(k) = Force(Motion(iV.col(k)).cross(f)).toVector();\n  BOOST_CHECK(jF.isApprox(jF_ref));\n  \n  for( int k=0;k<N;++k )\n    jF_ref.col(k) += Force(Motion(iV2.col(k)).cross(f)).toVector();\n  motionSet::act<ADDTO>(iV2,f,jF);\n  BOOST_CHECK(jF.isApprox(jF_ref));\n  \n  for( int k=0;k<N;++k )\n    jF_ref.col(k) -= Force(Motion(iV3.col(k)).cross(f)).toVector();\n  motionSet::act<RMTO>(iV3,f,jF);\n  BOOST_CHECK(jF.isApprox(jF_ref));\n}\n\nBOOST_AUTO_TEST_CASE(test_skew)\n{\n  using namespace pinocchio;\n  typedef SE3::Vector3 Vector3;\n  typedef Motion::Vector6 Vector6;\n  \n  Vector3 v3(Vector3::Random());\n  Vector6 v6(Vector6::Random());\n  \n  Vector3 res1 = unSkew(skew(v3));\n  BOOST_CHECK(res1.isApprox(v3));\n  \n  Vector3 res2 = unSkew(skew(v6.head<3>()));\n  BOOST_CHECK(res2.isApprox(v6.head<3>()));\n  \n  Vector3 res3 = skew(v3)*v3;\n  BOOST_CHECK(res3.isZero());\n  \n  Vector3 rhs(Vector3::Random());\n  Vector3 res41 = skew(v3)*rhs;\n  Vector3 res42 = v3.cross(rhs);\n  \n  BOOST_CHECK(res41.isApprox(res42));\n  \n}\n\nBOOST_AUTO_TEST_CASE(test_addSkew)\n{\n  using namespace pinocchio;\n  typedef SE3::Vector3 Vector3;\n  typedef SE3::Matrix3 Matrix3;\n  \n  Vector3 v(Vector3::Random());\n  Matrix3 M(Matrix3::Random());\n  Matrix3 Mcopy(M);\n  \n  addSkew(v,M);\n  Matrix3 Mref = Mcopy + skew(v);\n  BOOST_CHECK(M.isApprox(Mref));\n  \n  Mref += skew(-v);\n  addSkew(-v,M);\n  BOOST_CHECK(M.isApprox(Mcopy));\n  \n  M.setZero();\n  addSkew(v,M);\n  BOOST_CHECK(M.isApprox(skew(v)));\n}\n\nBOOST_AUTO_TEST_CASE(test_skew_square)\n{\n  using namespace pinocchio;\n  typedef SE3::Vector3 Vector3;\n  typedef SE3::Matrix3 Matrix3;\n  \n  Vector3 u(Vector3::Random());\n  Vector3 v(Vector3::Random());\n  \n  Matrix3 ref = skew(u) * skew(v);\n  \n  Matrix3 res = skewSquare(u,v);\n  \n  BOOST_CHECK(res.isApprox(ref));\n}\n\ntemplate<int axis>\nstruct test_scalar_multiplication_cartesian_axis\n{\n  typedef pinocchio::CartesianAxis<axis> Axis;\n  typedef double Scalar;\n  typedef Eigen::Matrix<Scalar,3,1> Vector3;\n  \n  static void run()\n  {\n    const Scalar alpha = static_cast <Scalar> (rand()) / static_cast <Scalar> (RAND_MAX);\n    const Vector3 r1 = Axis() * alpha;\n    const Vector3 r2 = alpha * Axis();\n    \n    BOOST_CHECK(r1.isApprox(r2));\n    \n    for(int k = 0; k < Axis::dim; ++k)\n    {\n      if(k==axis)\n      {\n        BOOST_CHECK(r1[k] == alpha);\n        BOOST_CHECK(r2[k] == alpha);\n      }\n      else\n      {\n        BOOST_CHECK(r1[k] == Scalar(0));\n        BOOST_CHECK(r2[k] == Scalar(0));\n      }\n    }\n  }\n};\n\nBOOST_AUTO_TEST_CASE(test_cartesian_axis)\n{\n  using namespace Eigen;\n  using namespace pinocchio;\n  Vector3d v(Vector3d::Random());\n  const double alpha = 3;\n  Vector3d v2(alpha*v);\n  \n  BOOST_CHECK(AxisX::cross(v).isApprox(Vector3d::Unit(0).cross(v)));\n  BOOST_CHECK(AxisY::cross(v).isApprox(Vector3d::Unit(1).cross(v)));\n  BOOST_CHECK(AxisZ::cross(v).isApprox(Vector3d::Unit(2).cross(v)));\n  BOOST_CHECK(AxisX::alphaCross(alpha,v).isApprox(Vector3d::Unit(0).cross(v2)));\n  BOOST_CHECK(AxisY::alphaCross(alpha,v).isApprox(Vector3d::Unit(1).cross(v2)));\n  BOOST_CHECK(AxisZ::alphaCross(alpha,v).isApprox(Vector3d::Unit(2).cross(v2)));\n  \n  test_scalar_multiplication_cartesian_axis<0>::run();\n  test_scalar_multiplication_cartesian_axis<1>::run();\n  test_scalar_multiplication_cartesian_axis<2>::run();\n}\n\ntemplate<int axis>\nstruct test_scalar_multiplication\n{\n  typedef pinocchio::SpatialAxis<axis> Axis;\n  typedef double Scalar;\n  typedef pinocchio::MotionTpl<Scalar> Motion;\n  \n  static void run()\n  {\n    const Scalar alpha = static_cast <Scalar> (rand()) / static_cast <Scalar> (RAND_MAX);\n    const Motion r1 = Axis() * alpha;\n    const Motion r2 = alpha * Axis();\n    \n    BOOST_CHECK(r1.isApprox(r2));\n    \n    for(int k = 0; k < Axis::dim; ++k)\n    {\n      if(k==axis)\n      {\n        BOOST_CHECK(r1.toVector()[k] == alpha);\n        BOOST_CHECK(r2.toVector()[k] == alpha);\n      }\n      else\n      {\n        BOOST_CHECK(r1.toVector()[k] == Scalar(0));\n        BOOST_CHECK(r2.toVector()[k] == Scalar(0));\n      }\n    }\n  }\n};\n\nBOOST_AUTO_TEST_CASE(test_spatial_axis)\n{\n  using namespace pinocchio;\n  \n  Motion v(Motion::Random());\n  Force f(Force::Random());\n\n  Motion vaxis;\n  vaxis << AxisVX();\n  BOOST_CHECK(AxisVX::cross(v).isApprox(vaxis.cross(v)));\n  BOOST_CHECK(v.cross(AxisVX()).isApprox(v.cross(vaxis)));\n  BOOST_CHECK(AxisVX::cross(f).isApprox(vaxis.cross(f)));\n  \n  vaxis << AxisVY();\n  BOOST_CHECK(AxisVY::cross(v).isApprox(vaxis.cross(v)));\n  BOOST_CHECK(v.cross(AxisVY()).isApprox(v.cross(vaxis)));\n  BOOST_CHECK(AxisVY::cross(f).isApprox(vaxis.cross(f)));\n  \n  vaxis << AxisVZ();\n  BOOST_CHECK(AxisVZ::cross(v).isApprox(vaxis.cross(v)));\n  BOOST_CHECK(v.cross(AxisVZ()).isApprox(v.cross(vaxis)));\n  BOOST_CHECK(AxisVZ::cross(f).isApprox(vaxis.cross(f)));\n  \n  vaxis << AxisWX();\n  BOOST_CHECK(AxisWX::cross(v).isApprox(vaxis.cross(v)));\n  BOOST_CHECK(v.cross(AxisWX()).isApprox(v.cross(vaxis)));\n  BOOST_CHECK(AxisWX::cross(f).isApprox(vaxis.cross(f)));\n  \n  vaxis << AxisWY();\n  BOOST_CHECK(AxisWY::cross(v).isApprox(vaxis.cross(v)));\n  BOOST_CHECK(v.cross(AxisWY()).isApprox(v.cross(vaxis)));\n  BOOST_CHECK(AxisWY::cross(f).isApprox(vaxis.cross(f)));\n  \n  vaxis << AxisWZ();\n  BOOST_CHECK(AxisWZ::cross(v).isApprox(vaxis.cross(v)));\n  BOOST_CHECK(v.cross(AxisWZ()).isApprox(v.cross(vaxis)));\n  BOOST_CHECK(AxisWZ::cross(f).isApprox(vaxis.cross(f)));\n  \n  // Test operation Axis * Scalar\n  test_scalar_multiplication<0>::run();\n  test_scalar_multiplication<1>::run();\n  test_scalar_multiplication<2>::run();\n  test_scalar_multiplication<3>::run();\n  test_scalar_multiplication<4>::run();\n  test_scalar_multiplication<5>::run();\n  \n  // Operations of Constraint on forces Sxf\n  typedef Motion::ActionMatrixType ActionMatrixType;\n  typedef ActionMatrixType::ColXpr ColType;\n  typedef ForceRef<ColType> ForceRefOnColType;\n  typedef MotionRef<ColType> MotionRefOnColType;\n  ActionMatrixType Sxf,Sxf_ref;\n  ActionMatrixType S(ActionMatrixType::Identity());\n  \n  SpatialAxis<0>::cross(f,ForceRefOnColType(Sxf.col(0)));\n  SpatialAxis<1>::cross(f,ForceRefOnColType(Sxf.col(1)));\n  SpatialAxis<2>::cross(f,ForceRefOnColType(Sxf.col(2)));\n  SpatialAxis<3>::cross(f,ForceRefOnColType(Sxf.col(3)));\n  SpatialAxis<4>::cross(f,ForceRefOnColType(Sxf.col(4)));\n  SpatialAxis<5>::cross(f,ForceRefOnColType(Sxf.col(5)));\n\n  for(int k = 0; k < 6; ++k)\n  {\n    MotionRefOnColType Scol(S.col(k));\n    ForceRefOnColType(Sxf_ref.col(k)) = Scol.cross(f);\n  }\n  \n  BOOST_CHECK(Sxf.isApprox(Sxf_ref));\n}\n\nBOOST_AUTO_TEST_SUITE_END ()\n", "meta": {"hexsha": "f56a3bac479403041b3e2f9a88331847ebd9f6e4", "size": 28248, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittest/spatial.cpp", "max_stars_repo_name": "rstrudel/pinocchio", "max_stars_repo_head_hexsha": "e038c7bf283b1df56a35014455e0e2d6f36e03ac", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "unittest/spatial.cpp", "max_issues_repo_name": "rstrudel/pinocchio", "max_issues_repo_head_hexsha": "e038c7bf283b1df56a35014455e0e2d6f36e03ac", "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": "unittest/spatial.cpp", "max_forks_repo_name": "rstrudel/pinocchio", "max_forks_repo_head_hexsha": "e038c7bf283b1df56a35014455e0e2d6f36e03ac", "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": 27.0057361377, "max_line_length": 141, "alphanum_fraction": 0.6644010195, "num_tokens": 8831, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879312056025699, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.49045513127244666}}
{"text": "#include <ros/ros.h>\n#include <vector>\n#include <Eigen/Dense>\n\n#include <moveit_visual_tools/moveit_visual_tools.h>\n\n#include <simple_moveit_wrapper/industrial_robot.h>\n#include \"arf_trajectory/trajectory.h\"\n#include \"arf_graph/graph.h\"\n#include \"arf_graph/util.h\"\n\nnamespace rvt = rviz_visual_tools;\nnamespace smw = simple_moveit_wrapper;\n\nclass Rviz\n{\npublic:\n  moveit_visual_tools::MoveItVisualToolsPtr visual_tools_;\n  Rviz()\n  {\n    visual_tools_.reset(new moveit_visual_tools::MoveItVisualTools(\"base_link\", \"/visualization_marker_array\"));\n    visual_tools_->loadRobotStatePub(\"/display_robot_state\");\n  }\n\n  void plotPose(Eigen::Affine3d pose);\n  void clear();\n};\n\nclass Demo1\n{\n  std::vector<std::vector<std::vector<double>>> graph_data_;\n  std::vector<arf::TrajectoryPoint> ee_trajectory_;\n  std::vector<std::vector<double>> shortest_path_;\n\npublic:\n  void createAndShowTrajectory(Rviz& rviz);\n  void createGraphData(smw::Robot& robot);\n  void calculateShortestPath(smw::Robot& robot);\n  void showShortestPath(smw::Robot& robot, Rviz& rviz);\n};\n\nstd::vector<arf::TrajectoryPoint> createPath();\n\nint main(int argc, char** argv)\n{\n  ros::init(argc, argv, \"test_moveit_wrapper\");\n  ros::NodeHandle node_handle;\n  ros::AsyncSpinner spinner(2);\n  spinner.start();\n\n  // arf::Robot robot;\n  smw::IndustrialRobot robot;\n  Rviz rviz;\n  Demo1 demo1;\n  demo1.createAndShowTrajectory(rviz);\n  demo1.createGraphData(robot);\n  demo1.calculateShortestPath(robot);\n  demo1.showShortestPath(robot, rviz);\n  ros::shutdown();\n  return 0;\n}\n\nstd::vector<arf::TrajectoryPoint> createPath()\n{\n  const int num_path_points = 5;\n  const std::vector<double> p1 = { 1, 0, 0.4 };\n  const std::vector<double> p2 = { 1.5, 0, 0.5 };\n\n  std::vector<arf::TrajectoryPoint> path;\n\n  double s = 0;\n  double ds = 1 / (num_path_points - 1);\n  for (int i = 0; i < num_path_points; ++i)\n  {\n    arf::Number x(p1[0] * (1 - s) + p2[0] * s);\n    arf::Number y(p1[1] * (1 - s) + p2[1] * s);\n    arf::Number z(p1[2] * (1 - s) + p2[2] * s);\n    arf::Number rx(0), ry(M_2_PI), rz(0);\n    arf::TrajectoryPoint tp(x, y, z, rx, ry, rz);\n    path.push_back(tp);\n    s += ds;\n  }\n  return path;\n}\n\nvoid Rviz::plotPose(Eigen::Affine3d pose)\n{\n  Eigen::Isometry3d pose_temp(pose.matrix());\n  visual_tools_->publishAxis(pose_temp, rvt::LARGE);\n  visual_tools_->trigger();\n  ros::Duration(0.1).sleep();\n}\n\nvoid Rviz::clear()\n{\n  visual_tools_->deleteAllMarkers();\n  visual_tools_->trigger();\n  ros::Duration(0.1).sleep();\n}\n\nvoid Demo1::createAndShowTrajectory(Rviz& rviz)\n{\n  for (int i = 0; i < 10; ++i)\n  {\n    arf::TolerancedNumber x(0.5, 0.45, 0.55, 5);\n    arf::Number y, z(0.5 + static_cast<double>(i) / 20);\n    arf::Number rx, ry(M_PI_2), rz;\n    arf::TrajectoryPoint tp(x, y, z, rx, ry, rz);\n    ee_trajectory_.push_back(tp);\n  }\n  for (auto tp : ee_trajectory_)\n  {\n    rviz.plotPose(tp.getNominalPose());\n    // tp.plot(rviz.visual_tools_);\n  }\n}\n\nvoid Demo1::createGraphData(smw::Robot& robot)\n{\n  for (auto tp : ee_trajectory_)\n  {\n    std::vector<std::vector<double>> new_data;\n    for (auto pose : tp.getGridSamples())\n    {\n      for (auto q_sol : robot.ik(pose))\n      {\n        if (!robot.isColliding(q_sol))\n          new_data.push_back(q_sol);\n      }\n    }\n    graph_data_.push_back(new_data);\n  }\n}\n\nvoid Demo1::calculateShortestPath(smw::Robot& robot)\n{\n  arf::Graph demo_graph(graph_data_);\n  demo_graph.runMultiSourceDijkstra();\n  std::vector<arf::Node*> sp = demo_graph.getShortestPath();\n  std::cout << \"Shortest path \\n\";\n  for (auto node : sp)\n  {\n    std::cout << (*node) << std::endl;\n    shortest_path_.push_back(*(*node).jv);\n  }\n}\n\nvoid Demo1::showShortestPath(smw::Robot& robot, Rviz& rviz)\n{\n  for (auto q : shortest_path_)\n  {\n    robot.plot(rviz.visual_tools_, q);\n    ros::Duration(0.5).sleep();\n  }\n}\n", "meta": {"hexsha": "4336b8bb63ce61557dfb8a21ba2414de611e143b", "size": 3797, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "arf_demo/src/demo.cpp", "max_stars_repo_name": "JeroenDM/arf", "max_stars_repo_head_hexsha": "4c251ef9c0614e6a8cb8ee4a218ad6da3fa9742b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-03T17:22:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-03T17:22:45.000Z", "max_issues_repo_path": "arf_demo/src/demo.cpp", "max_issues_repo_name": "JeroenDM/arf", "max_issues_repo_head_hexsha": "4c251ef9c0614e6a8cb8ee4a218ad6da3fa9742b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "arf_demo/src/demo.cpp", "max_forks_repo_name": "JeroenDM/arf", "max_forks_repo_head_hexsha": "4c251ef9c0614e6a8cb8ee4a218ad6da3fa9742b", "max_forks_repo_licenses": ["Apache-2.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.3397435897, "max_line_length": 112, "alphanum_fraction": 0.6671056097, "num_tokens": 1189, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311856832191, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4904551188734608}}
{"text": "/// 786\n\n/// This file is subject to the terms and conditions defined in\n/// file 'LICENSE', which is part of this source code package.\n\n/// Author: inumanag\n\n/******************************************************************************/\n\n#include <time.h>\n#include <sstream>\n#include <unordered_map>\n\n#include <sys/types.h>\n#include <sys/stat.h>\n\n#include <boost/math/tools/roots.hpp>\n#include <boost/math/distributions/binomial.hpp>\n\n#include \"common.h\"\n\nusing namespace std;\n\n/******************************************************************************/\n\nmode_t stat_file(const string &path)\n{\n\tstruct stat path_stat;\n\tint s = stat(path.c_str(), &path_stat);\n\tassert(s == 0);\n\treturn path_stat.st_mode;\n}\n\nvector<string> split(const string &s, char delim) \n{\n\tvector<string> elems;\n\tstringstream ss(s);\n\tstring item;\n\twhile(getline(ss, item, delim)) {\n\t\telems.push_back(item);\n\t}\n\treturn elems;\n}\n\nstring rc(const string &s)\n{\n\tauto r = s;\n\treverse(r.begin(), r.end());\n\ttransform(r.begin(), r.end(), r.begin(), rev_dna);\n\treturn r;\n}\n\n/******************************************************************************/\n\ndouble tau(double edit_error, int kmer_size)\n{\n\tconst double ERROR_RATIO = (Globals::Search::MAX_ERROR - Globals::Search::MAX_EDIT_ERROR) / Globals::Search::MAX_EDIT_ERROR;\n   double gap_error = std::min(1.0, ERROR_RATIO * edit_error);\n   double a = (1 - gap_error) / (1 + gap_error);\n   double b = 1 / (2 * std::exp(kmer_size * edit_error) - 1);\n   return a * b;\n}\n\ndouble solve_inverse_jaccard(int j, int kmer_size)\n{\n\tif (j == 0) return 1;\n\tif (j == 1) return 0;\n\treturn boost::math::tools::newton_raphson_iterate([j, kmer_size](double d){\n\t\tconst double ERROR_RATIO = (Globals::Search::MAX_ERROR - Globals::Search::MAX_EDIT_ERROR) / Globals::Search::MAX_EDIT_ERROR;\n\t\tdouble E = exp(d * kmer_size);\n\t\treturn make_tuple(\n\t\t\t((1 - d * ERROR_RATIO) / (1 + d * ERROR_RATIO)) * (1.0 / (2 * E - 1)) - j,\n\t\t\t2 * (- kmer_size * E + ERROR_RATIO - 2 * ERROR_RATIO * E + E * kmer_size * pow(d * ERROR_RATIO, 2)) /\n\t\t\t\tpow((2 * E - 1) * (1 + d * ERROR_RATIO), 2)\n\t\t);\n\t}, 0.10, 0.0, 1.0, numeric_limits<double>::digits);\n}\n\nint relaxed_jaccard_estimate(int s, int kmer_size, unordered_map<int, int> &mm)\n{\n\tdouble result = -1;\n\tauto it = mm.find(s);\n\tif (it != mm.end()) result = it->second;\n\tif (result != -1) return result;\n\n\tusing namespace boost::math;\n\tconst double CI = 0.75;\n\tconst double Q2 = (1.0 - CI) / 2; // one side interval probability\n\n\tresult = ceil(s * tau(Globals::Search::MAX_EDIT_ERROR, kmer_size));\n\tfor (; result >= 0; result--) {        \n\t\tdouble d = solve_inverse_jaccard(result / s, kmer_size); // returns edit error\n\t\tdouble x = quantile(complement(binomial(s, tau(d, kmer_size)), Q2)); // inverse binomial \n\t\tdouble low_d = solve_inverse_jaccard(x / s, kmer_size);\n\t\tif (100 * (1 - low_d) < Globals::Search::MAX_EDIT_ERROR) {\n\t\t\tresult++; \n\t\t\tbreak;\n\t\t}\n\t}\n\tresult = max(result, 0.0);\n\tmm[s] = result;\n\treturn result;\n}\n", "meta": {"hexsha": "a71a755695983105bdd76278abdcc002cebdb59f", "size": 2965, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/util.cc", "max_stars_repo_name": "mateog4712/SEDEF", "max_stars_repo_head_hexsha": "dc05b661854a96b934ee098bedb970a5040b697b", "max_stars_repo_licenses": ["MIT"], "max_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.cc", "max_issues_repo_name": "mateog4712/SEDEF", "max_issues_repo_head_hexsha": "dc05b661854a96b934ee098bedb970a5040b697b", "max_issues_repo_licenses": ["MIT"], "max_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.cc", "max_forks_repo_name": "mateog4712/SEDEF", "max_forks_repo_head_hexsha": "dc05b661854a96b934ee098bedb970a5040b697b", "max_forks_repo_licenses": ["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.5096153846, "max_line_length": 126, "alphanum_fraction": 0.6060708263, "num_tokens": 816, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.6224593171945416, "lm_q1q2_score": 0.49045511403615494}}
{"text": "#include <math.h>\n#include <cmath>\n#include \"Solver.h\"\n\n#include \"vector_var.h\"\n#include <iostream>\n#include \"Solution.h\"\n#include <fstream>\n#include \"global_variables.h\"\n#include \"residuals.h\"\n#include <cstdio>\n#include <ctime>\n#include \"artificial_dissipation.h\"\n#include <boost/math/special_functions/sign.hpp>\n#include <limits>\n#include \"RungeKutta.h\"\n#include \"tecplot_output.h\"\n#include \"gradients.h\"\n\nusing namespace std;\nSolver::Solver()\n{\n    //ctor\n}\n\nSolver::~Solver()\n{\n    //dtor\n}\n\n\nvoid Solver::cell_interface_initialiser( double &rho_interface,vector_var &rho_u_interface,\n                                        flux_var &x_flux,flux_var &y_flux ){\n    // initialise variables\n     // add in reset function\n    rho_interface = 0;\n\n    rho_u_interface.x =0;\n    rho_u_interface.y = 0;\n    rho_u_interface.z = 0;\n\n    x_flux.P = 0;\n    x_flux.momentum_x =0;\n    x_flux.momentum_y =0;\n    x_flux.momentum_z =0;\n\n    y_flux.P = 0;\n    y_flux.momentum_x =0;\n    y_flux.momentum_y =0;\n    y_flux.momentum_z =0;\n\n}\n\n\ndouble Solver::feq_calc_incomp(double weight, vector_var e_alpha, vector_var u_lattice, double u_magnitude,\n                        double cs, double rho_lattice, double rho_0, int k){\n    double feq;\n\n\n    feq = e_alpha.Dot_Product(u_lattice) *3.0 ;\n    feq = feq + ( pow(e_alpha.Dot_Product(u_lattice),2)  - pow((u_magnitude* cs),2) )\n    *4.5;\n    feq= feq *weight *rho_0 ;\n     feq = feq + weight *rho_lattice ;\n\n    return feq;\n\n}\n\n\ndouble Solver::feq_calc(double weight, vector_var e_alpha, vector_var u_lattice, double u_magnitude,\n                        double cs, double rho_lattice){\n    double feq;\n\n\n    feq = 1.0  ;\n    feq = feq\n        + e_alpha.Dot_Product(u_lattice) *3.0 ;\n    feq = feq + ( pow(e_alpha.Dot_Product(u_lattice),2)  - pow((u_magnitude* cs),2) )\n    *4.5;\n    feq= feq *weight *rho_lattice ;\n\n    return feq;\n\n}\n\n\nvoid Solver::General_Purpose_Solver_mk_i( unstructured_mesh &Mesh , Solution &soln, Boundary_Conditions &bcs,\n                                   external_forces &source,global_variables &globals, domain_geometry &domain,\n                                   initial_conditions &init_conds, unstructured_bcs &quad_bcs_orig, int mg,\n                                   Solution &residual, int fmg, post_processing &pp)\n{\n\n    ///Declarations\n    RungeKutta rk4;\n    Solution temp_soln(Mesh.get_total_cells()); // intermediate solution for RK\n    Solution soln_t0(Mesh.get_total_cells()); // solution at t0 in RK cycle\n    Solution soln_t1(Mesh.get_total_cells());\n    Solution residual_worker(Mesh.get_total_cells()); // stores residuals\n    Solution vortex_error(Mesh.get_total_cells());\n    Solution real_error (Mesh.get_total_cells());\n\tSolution wall_shear_stress(Mesh.get_n_wall_cells());\n    gradients grads (Mesh.get_total_cells());\n\tSolution cfl_areas(Mesh.get_total_cells());\n\n\n    flux_var RK;\n\n    double delta_t = globals.time_marching_step;\n\n\tdouble *delta_t_local;\n\tint *delta_t_frequency;\n\tdouble *local_time;\n\tbool *calc_cell;\n\tdouble *local_viscosity;\n\tdouble *local_fneq;\n\n\tdelta_t_local = new double[Mesh.get_n_cells()];\n\tif (delta_t_local == NULL) exit(1);\n\tdelta_t_frequency = new int[Mesh.get_n_cells()];\n\tif (delta_t_frequency == NULL) exit(1);\n\tlocal_time = new double[Mesh.get_n_cells()];\n\tif (local_time == NULL) exit(1);\n\tcalc_cell = new bool[Mesh.get_n_cells()];\n\tif (calc_cell == NULL) exit(1);\n\tlocal_viscosity = new double[Mesh.get_total_cells()];\n\tif (local_viscosity == NULL) exit(1);\n\tlocal_fneq = new double[Mesh.get_total_cells()];\n\tif (local_fneq == NULL) exit(1);\n\n\n\tstd::fill_n(calc_cell, Mesh.get_n_cells() , true);\n\n\n    double local_tolerance;\n    double rho_interface;\n    double interface_area;\n    double feq_lattice [15];\n    double u_lattice[15], v_lattice[15], w_lattice[15], rho_lattice[15];\n\n    double lattice_weight [15];\n    double time;\n\n    double f1,f2,f3,f4;\n\tdouble output_residual_threshold = 0;\n    double visc;\n\n\n    double angular_freq, wom_cos,force;\n\n    std::ofstream error_output , vortex_output , max_u, debug_log;\n    std::string output_dir,decay_dir,max_u_dir;\n    output_dir = globals.output_file +\"/error.txt\";\n    vector_var cell_1, cell_2, interface_node, lattice_node, delta_u, delta_v ,delta_w,delta_rho;\n    vector_var relative_interface;\n    vector_var  vel_lattice,  rho_u_interface , u_interface;\n    vector_var delta_u1, delta_v1 ,delta_w1,delta_rho1;\n    vector_var cell_normal;\n    vector_var flux_e_alpha [9];\n    vector_var u,v,w,rho;\n    std::vector<vector_var> e_alpha;\n    std::vector<int> cell_nodes;\n\n    // vector_var flux_e_alpha;\n    residuals convergence_residual;\n    flux_var x_flux , y_flux,z_flux;\n    flux_var cell_flux ;\n\n    flux_var debug [4] ,debug_flux[4],arti_debug [4];\n    flux_var dbug [4];\n    flux_var int_debug[4];\n\n    bc_var bc;\n\n    int neighbour;\n    int timesteps;\n    int i;\n\n\n    //calculate timesteps\n    int center_node;\n\tint wall;\n\n    center_node = Mesh.get_centre_node();\n\n    tecplot_output tecplot;\n\n    ///Initialisations\n\n    dt = domain.dt; // timestepping for streaming // non-dim equals 1\n    c = 1; // assume lattice spacing is equal to streaming timestep\n    cs = c/sqrt(3);\n    visc = (globals.tau -0.5)/3 * domain.dt;\n\n    soln_t1.clone(soln);\n    local_tolerance = globals.tolerance;\n     delta_t =1 ;\n    timesteps = ceil( globals.simulation_length);\n    output_dir = globals.output_file +\"/error.txt\";\n    decay_dir = globals.output_file +\"/vortex_error.txt\";\n    max_u_dir = globals.output_file +\"/max_u.txt\";\n   // error_output.open(\"/home/brendan/Dropbox/PhD/Test Cases/Couette Flow/error.txt\", ios::out);\n    error_output.open(output_dir.c_str(), ios::out);\n    output_dir = globals.output_file +\"/residual_log.txt\";\n    debug_log.open(output_dir.c_str(), ios::out);\n    vortex_output.open(decay_dir.c_str(), ios::out);\n    max_u.open(max_u_dir.c_str(), ios::out);\n\n\n    populate_e_alpha(e_alpha,lattice_weight,c,globals.PI,15);\n    time =0;\n    angular_freq = visc* pow(globals.womersley_no,2) / pow(Mesh.get_Y()/2,2);\n    force = -init_conds.pressure_gradient ;\n\n    // residual_factor = delta_t/ Mesh.get_s_area(0);\n\n    // taylor vortex memory\n    double td;\n\n\t//drag co-efficients\n\tdouble drag_t1, drag_t0;\n    time = 0;\n\n    neighbour =0;\n\n    td = 100000000000000000;\n\n    grads.pre_fill_LHS_and_RHS_matrix(bcs,Mesh,domain,soln,globals);\n\n    debug_log << \"t,rk,i,res_rho,res_u,res_v,res_w,x,y,z, dt,visc,rho,u,v,ux,uy,uz,vx,vy,vz\" << endl ;\n//\n\n\n\tstd::clock_t time1, time2, time3, time4;\n\tdouble duration1, duration2, duration3;\n\n\n\n\n\tpopulate_cfl_areas(cfl_areas,Mesh);\n\n\n\n    // loop in time\n    for (int t= 0; t < timesteps; t++){\n        // soln is the solution at the start of every\n\t\t// RK step.(rk = n) Temp_soln holds the values at end of\n\t\t// step.(rk = n+1)\n        soln_t0.clone(soln_t1);    // soln_t0 holds macro variable solution at start of time step\n        temp_soln.clone(soln);  //temp holds rho,u,v                      // t= 0, rk = 0\n\n        convergence_residual.reset();\n\n        //womersley flow peculiarities\n        if (globals.testcase == 4){\n            wom_cos = cos(angular_freq * t * delta_t) ;\n            force = -init_conds.pressure_gradient * wom_cos;\n        }\n\n        //find_real_time(delta_t_local, local_time, calc_face,Mesh,calc_cell);\n        //local timestepping calculation\n        get_cfl(delta_t,temp_soln,Mesh,globals,delta_t_local, delta_t_frequency,cfl_areas);\n\n\n\n        for( int rk = 0; rk < rk4.timesteps; rk++){\n\t\t\t//time1 = clock();\n\t\t\tdrag_t1 = 0.0;\n            //temp_soln.Initialise();\n\n            //update temp_soln boundary conditions\n             temp_soln.update_unstructured_bcs(bcs,Mesh,domain,t);\n\n             residual_worker.Initialise(); //set to zeros\n                         //get gradients for\n\n\t\t\t //time2 = clock();\n            grads.Get_LS_Gradients(bcs,Mesh,domain,temp_soln,globals);\n\n\t\t\t//time3 = clock();\n\n\t\t\t//std::cout << \"CPU Cycles Gradients:\" << double(time3 - time2) << std::endl;\n\t\t\twall = 0;\n             // loop through each cell and exclude the ghost cells\n             //using n_cells here rather than total_cells\n\t\t\tfor (int face=0 ; face < Mesh.get_n_faces() ; face ++) {\n\n                i = Mesh.get_mesh_owner(face);\n\n                // volume initialisers\n                interface_area = 0.0;\n\n                //get current cell centre\n                cell_1.x = Mesh.get_centroid_x(i);\n                cell_1.y = Mesh.get_centroid_y(i);\n                cell_1.z = Mesh.get_centroid_z(i);\n                // add in reset function\n                cell_flux.zero();\n\n                //maybe take out m1 and m2 and calc outside loop\n\n                cell_interface_variables( face, i,interface_node, neighbour,\n                                         interface_area,cell_normal, bcs, bc, Mesh,\n                                         cell_2,cell_1);\n\n\n\n\t\t\t\tif (face > Mesh.get_n_neighbours() && bcs.get_name(face - Mesh.get_n_neighbours()) == \"empty\") {\n\t\t\t\t\tinterface_area = 0.0;\n\t\t\t\t}\n              else{\n\n\t\t\t\t\tcell_interface_initialiser( rho_interface, rho_u_interface, x_flux,y_flux);\n\n\t\t\t\t   // dt for the cell interface\n\t\t\t\t\tdt =  Mesh.get_delta_t_face(face);\n\n\t\t\t\t\t//populate macro variables\n\t\t\t\t\tpopulate_lattice_macros(u_lattice,v_lattice,w_lattice,rho_lattice,cell_1,cell_2,\n\t\t\t\t\t\t\tinterface_node,i,neighbour,grads,temp_soln,Mesh,bcs,cell_normal);\n\n\t\t\t\t\t//get initial feqs\n\t\t\t\t\tfor(int k = 0; k< 15; k ++){\n\t\t\t\t\t\tpopulate_feq(u_lattice,v_lattice,w_lattice,rho_lattice,lattice_weight,\n\t\t\t\t\t\t\tfeq_lattice,k,globals);\n\t\t\t\t\t}\n\n\t\t\t\t\t// get macroscopic values at cell interface\n\t\t\t\t\t rho_interface = feq_lattice[0] + feq_lattice[1] + feq_lattice[2]+ feq_lattice[3]\n\t\t\t\t\t +feq_lattice[4] + feq_lattice[5]+ feq_lattice[6]+feq_lattice[7]+ feq_lattice[8]\n\t\t\t\t\t +feq_lattice[9] + feq_lattice[10]+ feq_lattice[11]+feq_lattice[12]+ feq_lattice[13]\n\t\t\t\t\t + feq_lattice[14];\n\n\t\t\t\t\tu_interface.x = 1/rho_interface * ( feq_lattice[1]- feq_lattice[2]\n\t\t\t\t\t+feq_lattice[7] - feq_lattice[8]\n\t\t\t\t\t +feq_lattice[9] - feq_lattice[10]+ feq_lattice[11] -feq_lattice[12]- feq_lattice[13]\n\t\t\t\t\t + feq_lattice[14]);\n\n\t\t\t\t\tu_interface.y = 1/rho_interface * ( feq_lattice[3]- feq_lattice[4]\n\t\t\t\t\t+feq_lattice[7] - feq_lattice[8]\n\t\t\t\t\t +feq_lattice[9] - feq_lattice[10]- feq_lattice[11] +feq_lattice[12]+ feq_lattice[13]\n\t\t\t\t\t - feq_lattice[14]);\n\n\t\t\t\t\tu_interface.z = 1/rho_interface * ( feq_lattice[5]- feq_lattice[6]\n\t\t\t\t\t+feq_lattice[7] - feq_lattice[8]\n\t\t\t\t\t - feq_lattice[9] + feq_lattice[10] + feq_lattice[11] -feq_lattice[12] + feq_lattice[13]\n\t\t\t\t\t - feq_lattice[14]);\n\n\t\t\t\t\tcalculate_flux_at_interface(u_interface,dt,globals,local_viscosity,rho_interface,lattice_weight\n\t\t\t\t\t,cell_flux,i,feq_lattice,cell_normal,interface_area,local_fneq);\n\n\t\t\t\t\t// add density flux to current cell and neighbouring cell\n\t\t\t\t\tresidual_worker.add_rho(i,-cell_flux.P /Mesh.get_cell_volume(i));\n\t\t\t\t\tresidual_worker.add_rho(neighbour, +cell_flux.P/Mesh.get_cell_volume(neighbour));\n\n\t\t\t\t\t// add x momentum\n\t\t\t\t\tresidual_worker.add_u(i,-cell_flux.momentum_x/Mesh.get_cell_volume(i));\n\t\t\t\t\tresidual_worker.add_u(neighbour, +cell_flux.momentum_x/Mesh.get_cell_volume(neighbour));\n\n\t\t\t\t\t// add y momentum\n\t\t\t\t\tresidual_worker.add_v(i,-cell_flux.momentum_y/Mesh.get_cell_volume(i));\n\t\t\t\t\tresidual_worker.add_v(neighbour, cell_flux.momentum_y/Mesh.get_cell_volume(neighbour));\n\n\t\t\t\t\t  // add z momentum\n\t                residual_worker.add_w(i,-cell_flux.momentum_z/Mesh.get_cell_volume(i));\n\t                residual_worker.add_w(neighbour, cell_flux.momentum_z/Mesh.get_cell_volume(neighbour));\n\n\n\t\t\t\t\t//get values for wall shear stress and drag\n\t\t\t\t\tif (face > Mesh.get_n_neighbours() && bcs.get_name(face - Mesh.get_n_neighbours()) == \"wall\") {\n\t\t\t\t\t\twall_shear_stress.set_rho(wall, rho_interface);\n\t\t\t\t\t\twall_shear_stress.set_u(wall, cell_flux.momentum_x);\n\t\t\t\t\t\tdrag_t1 = drag_t1 + cell_flux.momentum_x;\n\t\t\t\t\t\twall_shear_stress.set_v(wall, cell_flux.momentum_y);\n\t\t\t\t\t\twall_shear_stress.set_w(wall, cell_flux.momentum_z);\n\t\t\t\t\t\twall = wall + 1;\n\t\t\t\t\t}\n\n                }\n\n        }\n\n\n            // for( int i=0; i < Mesh.get_total_cells(); i++){\n            //\n            //     debug_log << t << \", \"  << rk << \", \" << i << \", \" << residual_worker.get_rho(i) << \", \" <<\n            //     residual_worker.get_u(i) << \", \" << residual_worker.get_v(i) << \", \" << residual_worker.get_w(i)\n            //     << \", \" <<\n            //     Mesh.get_centroid_x(i) << \" , \" << Mesh.get_centroid_y(i) << \",\" <<  Mesh.get_centroid_z(i) << \",\" <<\n            //      delta_t_local[i]  << \" , \" << local_viscosity[i] << \",\" <<\n            //     temp_soln.get_rho(i)<< \",\" << temp_soln.get_u(i) << \" , \" << temp_soln.get_v(i)<< \" , \" <<\n            //     grads.get_u(i).x << \" , \" << grads.get_u(i).y << \" , \" <<  grads.get_u(i).z << \" , \" <<\n            //     grads.get_v(i).x << \" , \" << grads.get_v(i).y << \" , \" <<  grads.get_v(i).z << \" , \" <<\n            //     grads.get_w(i).x << \" , \" << grads.get_w(i).y << \",\" <<  grads.get_w(i).z\n            //\n            //     << endl;\n            //\n            // }\n\n\n\n          //  residual_worker.remove_double_errors();\n\n            //update RK values\n            for( int i=0; i < Mesh.get_n_cells(); i++){\n                if( calc_cell[i]){\n\n                    // update intermediate macroscopic variables for next Runge Kutta Time Step\n                    f1 = soln_t0.get_rho(i) + residual_worker.get_rho(i)*delta_t_local[i] *rk4.alpha[rk];\n                    f2 = soln_t0.get_u(i) + (residual_worker.get_u(i)+force) *delta_t_local[i]*rk4.alpha[rk];\n                    f3 = soln_t0.get_v(i) + residual_worker.get_v(i) *delta_t_local[i]*rk4.alpha[rk];\n                     f4 = soln_t0.get_w(i) + residual_worker.get_w(i) *delta_t_local[i]*rk4.alpha[rk];\n\n                      // change momentum to velocity\n                    f2 = f2/f1;\n                    f3 =f3/f1;\n                    f4=f4/f1;\n\n                     temp_soln.update(f1,f2,f3,f4, i);\n                    //temp_soln.update(1.0,f2,0.0,0.0, i);\n\n                    //add contributions to\n                    soln_t1.add_rho(i, delta_t_local[i]* rk4.beta[rk] * residual_worker.get_rho(i));\n                    soln_t1.add_u(i, delta_t_local[i]* rk4.beta[rk] * (residual_worker.get_u(i)+force));\n                    soln_t1.add_v(i, delta_t_local[i]* rk4.beta[rk] * residual_worker.get_v(i));\n                    soln_t1.add_w(i, delta_t_local[i]* rk4.beta[rk] * residual_worker.get_w(i));\n\n\n                    f1 = soln_t1.get_rho(i);\n                    f2 = soln_t1.get_u(i)/soln_t1.get_rho(i);\n                    f3 = soln_t1.get_v(i)/soln_t1.get_rho(i);\n                    f4= soln_t1.get_w(i)/soln_t1.get_rho(i);\n\n                   soln.update(f1,f2,f3,f4, i);\n                   //soln.update(1.0,f2,0.0,0.0, i);\n                }\n\n            }\n\n\t\t\t//time4 = clock();\n\t\t\t//std::cout << \"CPU Cycles Full RK cycle:\" << double(time4- time1) << std::endl;\n        }\n\n        for( int i = 0; i < Mesh.get_n_cells(); i++){\n            if(calc_cell[i]){\n                    convergence_residual.add_l2_norm_residuals(residual_worker,i);\n                       //error checking\n                    if (std::isnan(temp_soln.get_rho(i)) || std::isnan(temp_soln.get_u(i))) {\n                                    if( mg == 0){\n                                        error_output.close();\n                                    }\n\n                                    cout << \"nan failure\" <<endl;\n                                    cout << t <<endl;\n                                    cout << i <<endl;\n\n\t\t\t\t\t\t\t\t\tdelete[] delta_t_local;\n\t\t\t\t\t\t\t\t\tdelta_t_local = NULL;\n\t\t\t\t\t\t\t\t\tdelete[] delta_t_frequency;\n\t\t\t\t\t\t\t\t\tdelta_t_frequency = NULL;\n\t\t\t\t\t\t\t\t\tdelete[] local_time;\n\t\t\t\t\t\t\t\t\tlocal_time = NULL;\n\t\t\t\t\t\t\t\t\tdelete[] calc_cell;\n\t\t\t\t\t\t\t\t\tcalc_cell = NULL;\n\t\t\t\t\t\t\t\t\tdelete[] local_viscosity;\n\t\t\t\t\t\t\t\t\tlocal_viscosity = NULL;\n\t\t\t\t\t\t\t\t\tdelete[] local_fneq;\n\t\t\t\t\t\t\t\t\tlocal_fneq = NULL;\n\n                                    return;\n                            }\n                    if (temp_soln.get_rho(i)/init_conds.average_rho > 1000.0){\n                        cout << \"rho failure\" <<endl;\n                        cout << t <<endl;\n                        cout << i <<endl;\n\n                        tecplot.tecplot_output_unstructured_soln(globals,Mesh,soln,bcs,time,pp, residual_worker,delta_t_local, local_fneq);\n\n\t\t\t\t\t\tdelete[] delta_t_local;\n\t\t\t\t\t\tdelta_t_local = NULL;\n\t\t\t\t\t\tdelete[] delta_t_frequency;\n\t\t\t\t\t\tdelta_t_frequency = NULL;\n\t\t\t\t\t\tdelete[] local_time;\n\t\t\t\t\t\tlocal_time = NULL;\n\t\t\t\t\t\tdelete[] calc_cell;\n\t\t\t\t\t\tcalc_cell = NULL;\n\t\t\t\t\t\tdelete[] local_viscosity;\n\t\t\t\t\t\tlocal_viscosity = NULL;\n\t\t\t\t\t\tdelete[] local_fneq;\n\t\t\t\t\t\tlocal_fneq = NULL;\n\n                        return;\n                    }\n            }\n        }\n\n        //convergence_residual.ansys_5_iter_rms(t);\n        convergence_residual.l2_norm_rms_moukallad(globals);\n        time = t*delta_t;\n\n        if( mg == 0 && t%globals.output_step == 1){\n\n            error_output << t << \", \"  << convergence_residual.max_error()   << \", \" <<\n            convergence_residual.rho_rms << \", \" << convergence_residual.u_rms << \", \" <<\n            convergence_residual.v_rms << \", \" <<\n\t\t\t\tconvergence_residual.w_rms << \" , FMG cycle: \" << fmg << endl;\n            cout << \"time t=\" << time  << \" error e =\" << convergence_residual.max_error()\n            <<  \" delta_t:\" << delta_t <<std::endl;\n            max_u << t << \",\" << soln.get_u(center_node) << \",\" << force << endl;\n\t\t\tcout << \"drag: \" << drag_t1 << endl;\n\n\t\t\t//only output at decreasing order of magnitudes - save space on hard drive\n\t\t\tif (convergence_residual.max_error() < pow(10, output_residual_threshold)) {\n\t\t\t\ttecplot.tecplot_output_unstructured_soln(globals, Mesh, soln, bcs, time, pp, residual_worker, delta_t_local, local_fneq);\n\t\t\t\toutput_residual_threshold = output_residual_threshold - 1;\n\t\t\t\tsoln.output(globals.output_file, globals, domain);\n\t\t\t}\n            //soln.output_centrelines(globals.output_file,globals,Mesh,time);\n\n        }\n\n        if ( convergence_residual.max_error() < local_tolerance || time > td){\n            if( mg == 0){\n\n                cout << \"convergence\" <<endl;\n                cout << \"time t=\" << time  << \" error e =\" << convergence_residual.max_error()\n                    <<  \" delta_t:\" << delta_t <<std::endl;\n                error_output.close();\n                debug_log.close();\n                vortex_output.close();\n                max_u.close();\n\n                // vortex calcs\n                temp_soln.update_unstructured_bcs(bcs,Mesh,domain,t);\n                grads.Get_LS_Gradients(bcs,Mesh,domain,temp_soln,globals);\n                pp.cylinder_post_processing(Mesh,globals,grads,bcs,temp_soln,domain,wall_shear_stress);\n               // pp.calc_vorticity(x_gradients,y_gradients);\n                 //pp.calc_streamfunction(Mesh,globals,bcs);\n                 tecplot.tecplot_output_unstructured_soln(globals,Mesh,soln,bcs,time,pp,residual_worker, delta_t_local, local_fneq);\n                //soln.output_centrelines(globals.output_file,globals,Mesh,time);\n            }\n\n\t\t\tdelete[] delta_t_local;\n\t\t\tdelta_t_local = NULL;\n\t\t\tdelete[] delta_t_frequency;\n\t\t\tdelta_t_frequency = NULL;\n\t\t\tdelete[] local_time;\n\t\t\tlocal_time = NULL;\n\t\t\tdelete[] calc_cell;\n\t\t\tcalc_cell = NULL;\n\t\t\tdelete[] local_viscosity;\n\t\t\tlocal_viscosity = NULL;\n\t\t\tdelete[] local_fneq;\n\t\t\tlocal_fneq = NULL;\n\n            return ;\n        }\n\n\n    }\n\n//    pp.calc_vorticity(x_gradients,y_gradients);\n    //pp.calc_streamfunction(Mesh,globals,bcs);\n\n    cout << \"out of time\" <<endl;\n    error_output.close();\n    vortex_output.close();\n    debug_log.close();\n    max_u.close();\n\tpp.cylinder_post_processing(Mesh, globals, grads, bcs, temp_soln, domain, temp_soln);\n    tecplot.tecplot_output_unstructured_soln(globals,Mesh,soln,bcs,time,pp,residual_worker, delta_t_local,local_fneq);\n\n\tdelete[] delta_t_local;\n\tdelta_t_local = NULL;\n\tdelete[] delta_t_frequency;\n\tdelta_t_frequency = NULL;\n\tdelete[] local_time;\n\tlocal_time = NULL;\n\tdelete[] calc_cell;\n\tcalc_cell = NULL;\n\tdelete[] local_viscosity;\n\tlocal_viscosity = NULL;\n\tdelete[] local_fneq;\n\tlocal_fneq = NULL;\n\n\n}\n\n\nvoid Solver::get_weighted_average( gradients &grads, int i, int neighbour, double m1, double m2,\n   vector_var &u, vector_var &v, vector_var &w, vector_var &rho, unstructured_mesh &mesh)\n{\n    double a,b ,x,y,z;\n\n    //check for boundary condition\n\n    //use boundary cell gradients as these are at cell face\n    if( neighbour > mesh.get_n_cells()){\n         x =  grads.get_u(neighbour).x ;\n        y = grads.get_u(neighbour).y ;\n        z =  grads.get_u(neighbour).z ;\n        u.set_equal(x,y,z);\n\n        x = grads.get_v(neighbour).x ;\n        y = grads.get_v(neighbour).y ;\n        z = grads.get_v(neighbour).z ;\n        v.set_equal(x,y,z);\n\n\n        x = grads.get_w(neighbour).x ;\n        y = grads.get_w(neighbour).y ;\n        z = grads.get_w(neighbour).z ;\n        w.set_equal(x,y,z);\n\n\n        x =  grads.get_rho(neighbour).x ;\n        y =  grads.get_rho(neighbour).y ;\n        z =  grads.get_rho(neighbour).z ;\n        rho.set_equal(x,y,z);\n\n\n    }else{\n\n        a = m1 +m2;\n        b = m2/a;\n        a = m1/a;\n\n\n        x = grads.get_u(i).x * a + grads.get_u(neighbour).x *b;\n        y = grads.get_u(i).y * a + grads.get_u(neighbour).y *b;\n        z = grads.get_u(i).z * a + grads.get_u(neighbour).z *b;\n        u.set_equal(x,y,z);\n\n        x = grads.get_v(i).x * a + grads.get_v(neighbour).x *b;\n        y = grads.get_v(i).y * a + grads.get_v(neighbour).y *b;\n        z = grads.get_v(i).z * a + grads.get_v(neighbour).z *b;\n        v.set_equal(x,y,z);\n\n\n        x = grads.get_w(i).x * a + grads.get_w(neighbour).x *b;\n        y = grads.get_w(i).y * a + grads.get_w(neighbour).y *b;\n        z = grads.get_w(i).z * a + grads.get_w(neighbour).z *b;\n        w.set_equal(x,y,z);\n\n\n        x = grads.get_rho(i).x * a + grads.get_rho(neighbour).x *b;\n        y = grads.get_rho(i).y * a + grads.get_rho(neighbour).y *b;\n        z = grads.get_rho(i).z * a + grads.get_rho(neighbour).z *b;\n        rho.set_equal(x,y,z);\n        }\n\n\n}\n\nvoid Solver::calculate_flux_at_interface(vector_var u_interface, double dt, global_variables &globals,\n    double local_viscosity[], double rho_interface, double lattice_weight[], flux_var &cell_flux,int i,\n    double feq_lattice[], vector_var cell_normal,double interface_area, double local_fneq[]){\n\n    double uu2, vv2, ww2, u2v2w2,uu,vv, ww, uv,uw,vw,fneq_tau;\n    double feq_interface[15];\n    flux_var x_flux, y_flux,z_flux;\n\n        uu2 = u_interface.x * u_interface.x/ globals.pre_conditioned_gamma;\n        vv2 = u_interface.y * u_interface.y/ globals.pre_conditioned_gamma;\n        ww2 = u_interface.z *u_interface.z/ globals.pre_conditioned_gamma;\n\n        u2v2w2 = (uu2 + vv2 + ww2) * 1.5;\n\n        uu =u_interface.x;\n        vv = u_interface.y;\n        ww = u_interface.z;\n\n        uv = uu*vv*9.0/ globals.pre_conditioned_gamma;\n        uw = uu*ww*9.0/ globals.pre_conditioned_gamma;\n        vw = vv*ww *9.0/ globals.pre_conditioned_gamma;\n\n\n        fneq_tau = (globals.visc *3/dt / globals.pre_conditioned_gamma);\n        local_viscosity[i] = fneq_tau/3*dt;\n\t\tlocal_fneq[i] = fneq_tau;\n\n\n        feq_interface[1] = lattice_weight[1] * rho_interface*\n              (1.0+3.0*uu+ 4.5*uu2 - u2v2w2);\n        feq_interface[1] = feq_interface[1]\n            - fneq_tau * (feq_interface[1] - feq_lattice[1]);\n\n        feq_interface[2] = lattice_weight[2] * rho_interface*\n            (1.0-3.0*uu + 4.5*uu2 - u2v2w2);\n        feq_interface[2] = feq_interface[2]\n            - fneq_tau * (feq_interface[2] - feq_lattice[2]);\n\n        feq_interface[3] = lattice_weight[3] * rho_interface*\n            (1.0 +3.0*vv + 4.5*vv2 - u2v2w2);\n        feq_interface[3] = feq_interface[3]\n            - fneq_tau * (feq_interface[3] - feq_lattice[3]);\n\n        feq_interface[4] = lattice_weight[4] * rho_interface*\n            (1.0 -3.0*vv + 4.5*vv2 - u2v2w2);\n        feq_interface[4] = feq_interface[4]\n            - fneq_tau * (feq_interface[4] - feq_lattice[4]);\n\n        feq_interface[5] = lattice_weight[5] * rho_interface*\n              (1.0 +3.0*ww + 4.5*ww2 - u2v2w2);\n        feq_interface[5] = feq_interface[5]\n            - fneq_tau * (feq_interface[5] - feq_lattice[5]);\n\n        feq_interface[6] = lattice_weight[6] * rho_interface*\n            (1.0 -3.0*ww + 4.5*ww2 - u2v2w2);\n        feq_interface[6] = feq_interface[6]\n            -fneq_tau * (feq_interface[6] - feq_lattice[6]);\n\n        feq_interface[7] = lattice_weight[7] * rho_interface*\n            (1.0 +3.0*uu +3.0*vv + 3.0*ww  +uv + uw + vw +\n                4.5*uu2 + 4.5*vv2 + 4.5*ww2 -u2v2w2);\n        feq_interface[7] = feq_interface[7]\n            - fneq_tau * (feq_interface[7] - feq_lattice[7]);\n\n        feq_interface[8] = lattice_weight[8] * rho_interface*\n            (1.0 -3.0*uu -3.0*vv - 3.0*ww  +uv + uw + vw +\n                4.5*uu2 + 4.5*vv2 + 4.5*ww2 -u2v2w2);\n        feq_interface[8] = feq_interface[8]\n            - fneq_tau * (feq_interface[8] - feq_lattice[8]);\n\n         feq_interface[9] = lattice_weight[9] * rho_interface*\n              (1.0 +3.0*uu +3.0*vv - 3.0*ww  +uv - uw - vw +\n                4.5*uu2 + 4.5*vv2 + 4.5*ww2 -u2v2w2);\n        feq_interface[9] = feq_interface[9]\n            - fneq_tau * (feq_interface[9] - feq_lattice[9]);\n\n         feq_interface[10] = lattice_weight[10] * rho_interface*\n            (1.0 -3.0*uu -3.0*vv + 3.0*ww  +uv - uw - vw +\n            4.5*uu2 + 4.5*vv2 + 4.5*ww2 -u2v2w2);\n        feq_interface[10] = feq_interface[10]\n            - fneq_tau * (feq_interface[10] - feq_lattice[10]);\n\n         feq_interface[11] = lattice_weight[11] * rho_interface*\n            (1.0 +3.0*uu -3.0*vv + 3.0*ww  -uv + uw - vw +\n                4.5*uu2 + 4.5*vv2 + 4.5*ww2 -u2v2w2);\n        feq_interface[11] = feq_interface[11]\n            - fneq_tau * (feq_interface[11] - feq_lattice[11]);\n\n         feq_interface[12] = lattice_weight[12] * rho_interface*\n            (1.0 -3.0*uu +3.0*vv - 3.0*ww  -uv + uw - vw +\n                4.5*uu2 + 4.5*vv2 + 4.5*ww2 -u2v2w2);\n        feq_interface[12] = feq_interface[12]\n            - fneq_tau * (feq_interface[12] - feq_lattice[12]);\n\n         feq_interface[13] = lattice_weight[13] * rho_interface*\n            (1.0 -3.0*uu +3.0*vv + 3.0*ww  -uv - uw + vw +\n                4.5*uu2 + 4.5*vv2 + 4.5*ww2 -u2v2w2);\n        feq_interface[13] = feq_interface[13]\n            - fneq_tau * (feq_interface[13] - feq_lattice[13]);\n\n         feq_interface[14] = lattice_weight[14] * rho_interface*\n              (1.0 +3.0*uu -3.0*vv - 3.0*ww  -uv - uw + vw +\n                4.5*uu2 + 4.5*vv2 + 4.5*ww2 -u2v2w2);\n        feq_interface[14] = feq_interface[14]\n            - fneq_tau * (feq_interface[14] - feq_lattice[14]);\n\n\n        x_flux.P = ( feq_interface[1]- feq_interface[2]\n                           +feq_interface[7] - feq_interface[8]\n                            +feq_interface[9] - feq_interface[10]+ feq_interface[11]\n                            -feq_interface[12]- feq_interface[13]\n                            + feq_interface[14]);\n\n        x_flux.momentum_x  =\n            ( feq_interface[1]+ feq_interface[2]\n                           +feq_interface[7] + feq_interface[8]\n                            +feq_interface[9] + feq_interface[10]+ feq_interface[11]\n                            +feq_interface[12]+ feq_interface[13]\n                            + feq_interface[14]);\n\n         x_flux.momentum_y  =\n            feq_interface[7] + feq_interface[8]\n                            +feq_interface[9] + feq_interface[10] - feq_interface[11] - feq_interface[12]\n                            - feq_interface[13]\n                            - feq_interface[14];\n\n        x_flux.momentum_z  =\n            feq_interface[7] + feq_interface[8]\n                            -feq_interface[9] - feq_interface[10] + feq_interface[11] + feq_interface[12]\n                            - feq_interface[13]\n                            - feq_interface[14];\n\n\n\n        y_flux.P = ( feq_interface[3]- feq_interface[4]\n                           +feq_interface[7] - feq_interface[8]\n                            +feq_interface[9] - feq_interface[10] - feq_interface[11]\n                            + feq_interface[12] + feq_interface[13]\n                            - feq_interface[14]);\n\n\n        y_flux.momentum_x  =x_flux.momentum_y ;\n\n        y_flux.momentum_y = ( feq_interface[3]+ feq_interface[4]\n                           +feq_interface[7] + feq_interface[8]\n                            +feq_interface[9] + feq_interface[10] + feq_interface[11]\n                            + feq_interface[12] + feq_interface[13]\n                            + feq_interface[14]);\n\n        y_flux.momentum_z =  feq_interface[7] + feq_interface[8]\n                            - feq_interface[9] - feq_interface[10] - feq_interface[11] - feq_interface[12]\n                            + feq_interface[13]\n                            + feq_interface[14];\n\n         z_flux.P = ( feq_interface[5]- feq_interface[6]\n                           +feq_interface[7] - feq_interface[8]\n                            -feq_interface[9] + feq_interface[10] + feq_interface[11]\n                            - feq_interface[12] + feq_interface[13]\n                            - feq_interface[14]);\n        z_flux.momentum_x  = x_flux.momentum_z;\n        z_flux.momentum_y = y_flux.momentum_z;\n        z_flux.momentum_z = ( feq_interface[5]+ feq_interface[6]\n                           +feq_interface[7] + feq_interface[8]\n                            +feq_interface[9] + feq_interface[10] + feq_interface[11]\n                            + feq_interface[12] + feq_interface[13]\n                            + feq_interface[14]);\n\n\n        cell_flux.P =  (x_flux.P*cell_normal.x + y_flux.P * cell_normal.y +\n                        z_flux.P *cell_normal.z)*interface_area ;\n        cell_flux.momentum_x = (x_flux.momentum_x*cell_normal.x +\n                                y_flux.momentum_x * cell_normal.y +\n                                z_flux.momentum_x*cell_normal.z)*interface_area ;\n\n        cell_flux.momentum_y = (x_flux.momentum_y*cell_normal.x +\n                                y_flux.momentum_y * cell_normal.y +\n                                z_flux.momentum_y*cell_normal.z)*interface_area ;\n\n\n        cell_flux.momentum_z = (x_flux.momentum_z*cell_normal.x +\n                                y_flux.momentum_z * cell_normal.y +\n                                z_flux.momentum_z*cell_normal.z)*interface_area ;\n}\n\n\nvoid Solver::populate_lattice_macros(double u_lattice[],double v_lattice[],\n            double w_lattice[],double rho_lattice[],vector_var cell_1, vector_var cell_2,\n            vector_var interface_node, int i, int neighbour, gradients &grads, Solution &temp_soln,\n           unstructured_mesh &mesh, Boundary_Conditions &bcs,vector_var &cell_normal){\n\n            vector_var temp1, temp2,vel,upwind_temp;\n\n            ///   case 0: // center node\n\n            vel.set_equal(temp_soln.get_u(i), temp_soln.get_v(i), temp_soln.get_v(i));\n\n\n            temp1 = cell_1;\n            temp1.subtract(interface_node);\n            temp2 = cell_2;\n            temp2.subtract(interface_node);\n            double rho_i, rho_nb, u_i,u_nb, v_i,v_nb, w_i,w_nb;\n\n            int nb;\n            nb = neighbour - mesh.get_n_cells();\n\n            if( neighbour > mesh.get_n_cells()){\n                // vboundary = v_i + grad_boundary * distance _ib\n\n                if(bcs.get_rho_type(nb) == 1){\n                    rho_lattice[0] = bcs.get_rho(nb);\n\n                }else if(bcs.get_rho_type(nb) == 8){\n                    rho_lattice[0] = temp_soln.get_rho(i) ;\n\n                }else{\n                    rho_lattice[0]  = temp_soln.get_rho(i) - temp1.Dot_Product(grads.get_rho(neighbour));\n                }\n\n                if(bcs.get_vel_type(nb) ==1){\n                    u_lattice[0]  = bcs.get_u(nb);\n                    v_lattice[0]  = bcs.get_v(nb);\n                    w_lattice[0]  = bcs.get_w(nb);\n\n                }else if(bcs.get_vel_type(nb) ==8){\n                    u_lattice[0]  = temp_soln.get_u(i) ;\n                    v_lattice[0]  = 0;\n                    w_lattice[0]  = temp_soln.get_w(i)  ;\n\n                }else{\n                    u_lattice[0]  = temp_soln.get_u(i) - temp1.Dot_Product(grads.get_u(neighbour));\n                    v_lattice[0]  = temp_soln.get_v(i) - temp1.Dot_Product(grads.get_v(neighbour));\n                    w_lattice[0]  = temp_soln.get_w(i) - temp1.Dot_Product(grads.get_w(neighbour));\n                }\n\n                rho_i = rho_lattice[0] ;\n                rho_nb = rho_lattice[0] ;\n\n                u_i = u_lattice[0];\n                u_nb = u_lattice[0];\n\n                v_i = v_lattice[0];\n                v_nb = v_lattice[0];\n\n                w_i = w_lattice[0];\n                w_nb = w_lattice[0];\n\n\n            }else{\n\n                rho_i = temp_soln.get_rho(i) - temp1.Dot_Product(grads.get_rho(i)) ;\n                rho_nb  =  temp_soln.get_rho(neighbour) - temp2.Dot_Product(grads.get_rho(neighbour));\n                rho_lattice[0]  = (rho_i + rho_nb)*0.5;\n\n                u_i = temp_soln.get_u(i) - temp1.Dot_Product(grads.get_u(i)) ;\n                u_nb  =  temp_soln.get_u(neighbour) - temp2.Dot_Product(grads.get_u(neighbour));\n                u_lattice[0]  = (u_i + u_nb)*0.5;\n\n                v_i = temp_soln.get_v(i) - temp1.Dot_Product(grads.get_v(i)) ;\n                v_nb  =  temp_soln.get_v(neighbour) - temp2.Dot_Product(grads.get_v(neighbour));\n                v_lattice[0]  = (v_i + v_nb)*0.5;\n\n                w_i = temp_soln.get_w(i) - temp1.Dot_Product(grads.get_w(i)) ;\n                w_nb  =  temp_soln.get_w(neighbour) - temp2.Dot_Product(grads.get_w(neighbour));\n                w_lattice[0]  = (w_i + w_nb)*0.5;\n\n\n\n\n            }\n\n\n      ///  case 1:west_node\n\n            if( -1* cell_normal.x > 0){\n                rho_lattice[1] =  rho_nb - grads.get_rho(neighbour).x* dt;\n                u_lattice[1] = u_nb- grads.get_u(neighbour).x* dt;\n                v_lattice[1] = v_nb - grads.get_v(neighbour).x *dt;\n                w_lattice[1] = w_nb - grads.get_w(neighbour).x *dt;\n\n            }else{\n                rho_lattice[1] =  rho_i - grads.get_rho(i).x* dt;\n                u_lattice[1] = u_i- grads.get_u(i).x* dt;\n                v_lattice[1] = v_i - grads.get_v(i).x *dt;\n                w_lattice[1] = w_i - grads.get_w(i).x *dt;\n            }\n\n      ///  case 2: // east_node\n             if( cell_normal.x > 0){\n                rho_lattice[2] =  rho_nb + grads.get_rho(neighbour).x* dt;\n                u_lattice[2] = u_nb+ grads.get_u(neighbour).x* dt;\n                v_lattice[2] = v_nb + grads.get_v(neighbour).x *dt;\n                w_lattice[2] = w_nb + grads.get_w(neighbour).x *dt;\n\n            }else{\n                rho_lattice[2] =  rho_i + grads.get_rho(i).x* dt;\n                u_lattice[2] = u_i+ grads.get_u(i).x* dt;\n                v_lattice[2] = v_i + grads.get_v(i).x *dt;\n                w_lattice[2] = w_i + grads.get_w(i).x *dt;\n            }\n\n         ///   case 3: // bottom node\n\n            if( -1* cell_normal.y > 0){\n                rho_lattice[3] =  rho_nb - grads.get_rho(neighbour).y* dt;\n                u_lattice[3] = u_nb- grads.get_u(neighbour).y* dt;\n                v_lattice[3] = v_nb - grads.get_v(neighbour).y *dt;\n                w_lattice[3] = w_nb - grads.get_w(neighbour).y *dt;\n\n            }else{\n                rho_lattice[3] =  rho_i - grads.get_rho(i).y* dt;\n                u_lattice[3] = u_i- grads.get_u(i).y* dt;\n                v_lattice[3] = v_i - grads.get_v(i).y *dt;\n                w_lattice[3] = w_i - grads.get_w(i).y *dt;\n            }\n\n\n     ///   case 4: // top node\n\n            if( cell_normal.y > 0){\n                rho_lattice[4] =  rho_nb + grads.get_rho(neighbour).y* dt;\n                u_lattice[4] = u_nb+ grads.get_u(neighbour).y* dt;\n                v_lattice[4] = v_nb + grads.get_v(neighbour).y *dt;\n                w_lattice[4] = w_nb + grads.get_w(neighbour).y *dt;\n\n            }else{\n                rho_lattice[4] =  rho_i + grads.get_rho(i).y* dt;\n                u_lattice[4] = u_i+ grads.get_u(i).y* dt;\n                v_lattice[4] = v_i + grads.get_v(i).y *dt;\n                w_lattice[4] = w_i + grads.get_w(i).y *dt;\n            }\n\n\n    ///   case 5: // back node\n            if( -1* cell_normal.z > 0){\n                rho_lattice[5] =  rho_nb - grads.get_rho(neighbour).z* dt;\n                u_lattice[5] = u_nb- grads.get_u(neighbour).z* dt;\n                v_lattice[5] = v_nb - grads.get_v(neighbour).z *dt;\n                w_lattice[5] = w_nb - grads.get_w(neighbour).z *dt;\n\n            }else{\n                rho_lattice[5] =  rho_i - grads.get_rho(i).z* dt;\n                u_lattice[5] = u_i- grads.get_u(i).z* dt;\n                v_lattice[5] = v_i - grads.get_v(i).z *dt;\n                w_lattice[5] = w_i - grads.get_w(i).z *dt;\n            }\n\n    ///   case 6: // front node\n            if( +1* cell_normal.z > 0){\n                rho_lattice[6] =  rho_nb + grads.get_rho(neighbour).z* dt;\n                u_lattice[6] = u_nb+ grads.get_u(neighbour).z* dt;\n                v_lattice[6] = v_nb + grads.get_v(neighbour).z *dt;\n                w_lattice[6] = w_nb + grads.get_w(neighbour).z *dt;\n\n            }else{\n                rho_lattice[6] =  rho_i + grads.get_rho(i).z* dt;\n                u_lattice[6] = u_i + grads.get_u(i).z* dt;\n                v_lattice[6] = v_i + grads.get_v(i).z *dt;\n                w_lattice[6] = w_i + grads.get_w(i).z *dt;\n            }\n\n\n       /// case 7: back bottom west\n            if( (-1* cell_normal.x + -1*cell_normal.y  + -1*cell_normal.z ) > 0){\n                rho_lattice[7] =  rho_nb - grads.get_rho(neighbour).x* dt\n                                         - grads.get_rho(neighbour).y* dt\n                                         - grads.get_rho(neighbour).z* dt;\n                u_lattice[7] =  u_nb - grads.get_u(neighbour).x* dt\n                                         - grads.get_u(neighbour).y* dt\n                                         - grads.get_u(neighbour).z* dt;\n                v_lattice[7] =  v_nb - grads.get_v(neighbour).x* dt\n                                         - grads.get_v(neighbour).y* dt\n                                         - grads.get_v(neighbour).z* dt;\n                w_lattice[7] =  w_nb - grads.get_w(neighbour).x* dt\n                                         - grads.get_w(neighbour).y* dt\n                                         - grads.get_w(neighbour).z* dt;\n\n            }else{\n                rho_lattice[7] =  rho_i - grads.get_rho(i).x* dt\n                                         - grads.get_rho(i).y* dt\n                                         - grads.get_rho(i).z* dt;\n                u_lattice[7] =  u_i - grads.get_u(i).x* dt\n                                         - grads.get_u(i).y* dt\n                                         - grads.get_u(i).z* dt;\n                v_lattice[7] =  v_i - grads.get_v(i).x* dt\n                                         - grads.get_v(i).y* dt\n                                         - grads.get_v(i).z* dt;\n                w_lattice[7] =  w_i - grads.get_w(i).x* dt\n                                         - grads.get_w(i).y* dt\n                                         - grads.get_w(i).z* dt;\n            }\n\n\n\n\n       /// case 9: front bottom west\n             if( (-1* cell_normal.x + -1*cell_normal.y  + 1*cell_normal.z ) > 0){\n                rho_lattice[9] =  rho_nb - grads.get_rho(neighbour).x* dt\n                                         - grads.get_rho(neighbour).y* dt\n                                         + grads.get_rho(neighbour).z* dt;\n                u_lattice[9] =  u_nb - grads.get_u(neighbour).x* dt\n                                         - grads.get_u(neighbour).y* dt\n                                         + grads.get_u(neighbour).z* dt;\n                v_lattice[9] =  v_nb - grads.get_v(neighbour).x* dt\n                                         - grads.get_v(neighbour).y* dt\n                                         + grads.get_v(neighbour).z* dt;\n                w_lattice[9] =  w_nb - grads.get_w(neighbour).x* dt\n                                         - grads.get_w(neighbour).y* dt\n                                         + grads.get_w(neighbour).z* dt;\n\n            }else{\n                rho_lattice[9] =  rho_i - grads.get_rho(i).x* dt\n                                         - grads.get_rho(i).y* dt\n                                         + grads.get_rho(i).z* dt;\n                u_lattice[9] =  u_i - grads.get_u(i).x* dt\n                                         - grads.get_u(i).y* dt\n                                         + grads.get_u(i).z* dt;\n                v_lattice[9] =  v_i - grads.get_v(i).x* dt\n                                         - grads.get_v(i).y* dt\n                                         + grads.get_v(i).z* dt;\n                w_lattice[9] =  w_i - grads.get_w(i).x* dt\n                                         - grads.get_w(i).y* dt\n                                         + grads.get_w(i).z* dt;\n            }\n\n\n\n      ///  case 11: back top west\n          if( (-1* cell_normal.x + cell_normal.y  + -1*cell_normal.z ) > 0){\n                rho_lattice[11] =  rho_nb - grads.get_rho(neighbour).x* dt\n                                         + grads.get_rho(neighbour).y* dt\n                                         - grads.get_rho(neighbour).z* dt;\n                u_lattice[11] =  u_nb - grads.get_u(neighbour).x* dt\n                                         + grads.get_u(neighbour).y* dt\n                                         - grads.get_u(neighbour).z* dt;\n                v_lattice[11] =  v_nb - grads.get_v(neighbour).x* dt\n                                         + grads.get_v(neighbour).y* dt\n                                         - grads.get_v(neighbour).z* dt;\n                w_lattice[11] =  w_nb - grads.get_w(neighbour).x* dt\n                                         + grads.get_w(neighbour).y* dt\n                                         - grads.get_w(neighbour).z* dt;\n\n            }else{\n                rho_lattice[11] =  rho_i - grads.get_rho(i).x* dt\n                                         + grads.get_rho(i).y* dt\n                                         - grads.get_rho(i).z* dt;\n                u_lattice[11] =  u_i - grads.get_u(i).x* dt\n                                         + grads.get_u(i).y* dt\n                                         - grads.get_u(i).z* dt;\n                v_lattice[11] =  v_i - grads.get_v(i).x* dt\n                                         + grads.get_v(i).y* dt\n                                         - grads.get_v(i).z* dt;\n                w_lattice[11] =  w_i - grads.get_w(i).x* dt\n                                         + grads.get_w(i).y* dt\n                                         - grads.get_w(i).z* dt;\n            }\n\n\n\n      /// case 14: front top west\n           if( (-1* cell_normal.x + cell_normal.y  + cell_normal.z ) > 0){\n                rho_lattice[14] =  rho_nb - grads.get_rho(neighbour).x* dt\n                                         + grads.get_rho(neighbour).y* dt\n                                         + grads.get_rho(neighbour).z* dt;\n                u_lattice[14] =  u_nb - grads.get_u(neighbour).x* dt\n                                         + grads.get_u(neighbour).y* dt\n                                         + grads.get_u(neighbour).z* dt;\n                v_lattice[14] =  v_nb - grads.get_v(neighbour).x* dt\n                                         + grads.get_v(neighbour).y* dt\n                                         + grads.get_v(neighbour).z* dt;\n                w_lattice[14] =  w_nb - grads.get_w(neighbour).x* dt\n                                         + grads.get_w(neighbour).y* dt\n                                         + grads.get_w(neighbour).z* dt;\n\n            }else{\n                rho_lattice[14] =  rho_i - grads.get_rho(i).x* dt\n                                         + grads.get_rho(i).y* dt\n                                         + grads.get_rho(i).z* dt;\n                u_lattice[14] =  u_i - grads.get_u(i).x* dt\n                                         + grads.get_u(i).y* dt\n                                         + grads.get_u(i).z* dt;\n                v_lattice[14] =  v_i - grads.get_v(i).x* dt\n                                         + grads.get_v(i).y* dt\n                                         + grads.get_v(i).z* dt;\n                w_lattice[14] =  w_i - grads.get_w(i).x* dt\n                                         + grads.get_w(i).y* dt\n                                         + grads.get_w(i).z* dt;\n            }\n\n\n\n       /// case 8: front top east\n         if( (1* cell_normal.x + 1*cell_normal.y  + 1*cell_normal.z ) > 0){\n                rho_lattice[8] =  rho_nb + grads.get_rho(neighbour).x* dt\n                                         + grads.get_rho(neighbour).y* dt\n                                         + grads.get_rho(neighbour).z* dt;\n                u_lattice[8] =  u_nb + grads.get_u(neighbour).x* dt\n                                         + grads.get_u(neighbour).y* dt\n                                         + grads.get_u(neighbour).z* dt;\n                v_lattice[8] =  v_nb + grads.get_v(neighbour).x* dt\n                                         + grads.get_v(neighbour).y* dt\n                                         + grads.get_v(neighbour).z* dt;\n                w_lattice[8] =  w_nb + grads.get_w(neighbour).x* dt\n                                         + grads.get_w(neighbour).y* dt\n                                         + grads.get_w(neighbour).z* dt;\n\n            }else{\n                rho_lattice[8] =  rho_i + grads.get_rho(i).x* dt\n                                         + grads.get_rho(i).y* dt\n                                         + grads.get_rho(i).z* dt;\n                u_lattice[8] =  u_i + grads.get_u(i).x* dt\n                                         + grads.get_u(i).y* dt\n                                         + grads.get_u(i).z* dt;\n                v_lattice[8] =  v_i + grads.get_v(i).x* dt\n                                         + grads.get_v(i).y* dt\n                                         + grads.get_v(i).z* dt;\n                w_lattice[8] =  w_i + grads.get_w(i).x* dt\n                                         + grads.get_w(i).y* dt\n                                         + grads.get_w(i).z* dt;\n            }\n\n\n\n\n\n         /// case 10 Back Top East\n         if( (1* cell_normal.x + 1*cell_normal.y  + -1*cell_normal.z ) > 0){\n                rho_lattice[10] =  rho_nb + grads.get_rho(neighbour).x* dt\n                                         + grads.get_rho(neighbour).y* dt\n                                         - grads.get_rho(neighbour).z* dt;\n                u_lattice[10] =  u_nb + grads.get_u(neighbour).x* dt\n                                         + grads.get_u(neighbour).y* dt\n                                         - grads.get_u(neighbour).z* dt;\n                v_lattice[10] =  v_nb + grads.get_v(neighbour).x* dt\n                                         + grads.get_v(neighbour).y* dt\n                                         - grads.get_v(neighbour).z* dt;\n                w_lattice[10] =  w_nb + grads.get_w(neighbour).x* dt\n                                         + grads.get_w(neighbour).y* dt\n                                         - grads.get_w(neighbour).z* dt;\n\n            }else{\n                rho_lattice[10] =  rho_i + grads.get_rho(i).x* dt\n                                         + grads.get_rho(i).y* dt\n                                         - grads.get_rho(i).z* dt;\n                u_lattice[10] =  u_i + grads.get_u(i).x* dt\n                                         + grads.get_u(i).y* dt\n                                         - grads.get_u(i).z* dt;\n                v_lattice[10] =  v_i + grads.get_v(i).x* dt\n                                         + grads.get_v(i).y* dt\n                                         - grads.get_v(i).z* dt;\n                w_lattice[10] =  w_i + grads.get_w(i).x* dt\n                                         + grads.get_w(i).y* dt\n                                         - grads.get_w(i).z* dt;\n            }\n\n\n\n         /// case 12 Front Bottom East\n         if( (1* cell_normal.x + -1*cell_normal.y  + 1*cell_normal.z ) > 0){\n                rho_lattice[12] =  rho_nb + grads.get_rho(neighbour).x* dt\n                                         - grads.get_rho(neighbour).y* dt\n                                         + grads.get_rho(neighbour).z* dt;\n                u_lattice[12] =  u_nb + grads.get_u(neighbour).x* dt\n                                         - grads.get_u(neighbour).y* dt\n                                         + grads.get_u(neighbour).z* dt;\n                v_lattice[12] =  v_nb + grads.get_v(neighbour).x* dt\n                                         - grads.get_v(neighbour).y* dt\n                                         + grads.get_v(neighbour).z* dt;\n                w_lattice[12] =  w_nb + grads.get_w(neighbour).x* dt\n                                         - grads.get_w(neighbour).y* dt\n                                         + grads.get_w(neighbour).z* dt;\n\n            }else{\n                rho_lattice[12] =  rho_i + grads.get_rho(i).x* dt\n                                         - grads.get_rho(i).y* dt\n                                         + grads.get_rho(i).z* dt;\n                u_lattice[12] =  u_i + grads.get_u(i).x* dt\n                                         - grads.get_u(i).y* dt\n                                         + grads.get_u(i).z* dt;\n                v_lattice[12] =  v_i + grads.get_v(i).x* dt\n                                         - grads.get_v(i).y* dt\n                                         + grads.get_v(i).z* dt;\n                w_lattice[12] =  w_i + grads.get_w(i).x* dt\n                                         - grads.get_w(i).y* dt\n                                         + grads.get_w(i).z* dt;\n            }\n\n\n         /// case 13 Back Bottom East\n            if( (1* cell_normal.x + -1*cell_normal.y  + -1*cell_normal.z ) > 0){\n                rho_lattice[13] =  rho_nb + grads.get_rho(neighbour).x* dt\n                                         - grads.get_rho(neighbour).y* dt\n                                         - grads.get_rho(neighbour).z* dt;\n                u_lattice[13] =  u_nb + grads.get_u(neighbour).x* dt\n                                         - grads.get_u(neighbour).y* dt\n                                         - grads.get_u(neighbour).z* dt;\n                v_lattice[13] =  v_nb + grads.get_v(neighbour).x* dt\n                                         - grads.get_v(neighbour).y* dt\n                                         - grads.get_v(neighbour).z* dt;\n                w_lattice[13] =  w_nb + grads.get_w(neighbour).x* dt\n                                         - grads.get_w(neighbour).y* dt\n                                         - grads.get_w(neighbour).z* dt;\n\n            }else{\n                rho_lattice[13] =  rho_i + grads.get_rho(i).x* dt\n                                         - grads.get_rho(i).y* dt\n                                         - grads.get_rho(i).z* dt;\n                u_lattice[13] =  u_i + grads.get_u(i).x* dt\n                                         - grads.get_u(i).y* dt\n                                         - grads.get_u(i).z* dt;\n                v_lattice[13] =  v_i + grads.get_v(i).x* dt\n                                         - grads.get_v(i).y* dt\n                                         - grads.get_v(i).z* dt;\n                w_lattice[13] =  w_i + grads.get_w(i).x* dt\n                                         - grads.get_w(i).y* dt\n                                         - grads.get_w(i).z* dt;\n            }\n\n\n}\n\n\n\nvoid Solver::populate_feq(double u_lattice[],double v_lattice[],\n            double w_lattice[],double rho_lattice[],double lattice_weight[],\n            double feq_lattice[],int k,global_variables &globals){\n\n    ///d3q15 velocity set\n\n    double uu2, vv2,u2v2w2,uv,uu,vv,ww2,uw,vw,ww;\n\n    uu2 = u_lattice[k] * u_lattice[k] / globals.pre_conditioned_gamma;\n    vv2 = v_lattice[k]* v_lattice[k] / globals.pre_conditioned_gamma;\n    ww2 = w_lattice[k] *w_lattice[k] / globals.pre_conditioned_gamma;\n    u2v2w2 = (uu2 + vv2 + ww2) * 1.5 ;\n\n    uv = u_lattice[k]*v_lattice[k]*9.0 / globals.pre_conditioned_gamma;\n    uw = u_lattice[k]*w_lattice[k]*9.0 / globals.pre_conditioned_gamma;\n    vw = v_lattice[k]*w_lattice[k]*9.0 / globals.pre_conditioned_gamma;\n\n    uu =u_lattice[k];\n    vv = v_lattice[k];\n    ww = w_lattice[k];\n\n    switch(k) {\n\n    case 0:\n         feq_lattice[k] = lattice_weight[k] * rho_lattice[k]*(1.0\n\n        -u2v2w2)  ;\n        break;\n\n    case 1:\n        feq_lattice[k] = lattice_weight[k] * rho_lattice[k]*\n        (1.0+3.0*uu+ 4.5*uu2 - u2v2w2);\n        break;\n    case 2:\n        feq_lattice[k] = lattice_weight[k] * rho_lattice[k]*\n        (1.0-3.0*uu + 4.5*uu2 - u2v2w2);\n        break;\n    case 3:\n        feq_lattice[k] = lattice_weight[k] * rho_lattice[k]*\n        (1.0 +3.0*vv + 4.5*vv2 - u2v2w2);\n        break;\n    case 4:\n        feq_lattice[k] = lattice_weight[k] * rho_lattice[k]*\n        (1.0 -3.0*vv + 4.5*vv2 - u2v2w2);\n        break;\n    case 5:\n        feq_lattice[k] = lattice_weight[k] * rho_lattice[k]*\n        (1.0 +3.0*ww + 4.5*ww2 - u2v2w2);\n        break;\n   case 6:\n        feq_lattice[k] = lattice_weight[k] * rho_lattice[k]*\n        (1.0 -3.0*ww + 4.5*ww2 - u2v2w2);\n        break;\n    case 7:\n        feq_lattice[k] = lattice_weight[k] * rho_lattice[k]*\n        (1.0 +3.0*uu +3.0*vv + 3.0*ww  +uv + uw + vw +\n        4.5*uu2 + 4.5*vv2 + 4.5*ww2 -u2v2w2);\n        break;\n    case 8:\n        feq_lattice[k] = lattice_weight[k] * rho_lattice[k]*\n        (1.0 -3.0*uu -3.0*vv - 3.0*ww  +uv + uw + vw +\n        4.5*uu2 + 4.5*vv2 + 4.5*ww2 -u2v2w2);\n        break;\n    case 9:\n        feq_lattice[k] = lattice_weight[k] * rho_lattice[k]*\n        (1.0 +3.0*uu +3.0*vv - 3.0*ww  +uv - uw - vw +\n        4.5*uu2 + 4.5*vv2 + 4.5*ww2 -u2v2w2);\n        break;\n    case 10:\n        feq_lattice[k] = lattice_weight[k] * rho_lattice[k]*\n        (1.0 -3.0*uu -3.0*vv + 3.0*ww  +uv - uw - vw +\n        4.5*uu2 + 4.5*vv2 + 4.5*ww2 -u2v2w2);\n        break;\n    case 11:\n        feq_lattice[k] = lattice_weight[k] * rho_lattice[k]*\n        (1.0 +3.0*uu -3.0*vv + 3.0*ww  -uv + uw - vw +\n        4.5*uu2 + 4.5*vv2 + 4.5*ww2 -u2v2w2);\n        break;\n    case 12:\n        feq_lattice[k] = lattice_weight[k] * rho_lattice[k]*\n        (1.0 -3.0*uu +3.0*vv - 3.0*ww  -uv + uw - vw +\n        4.5*uu2 + 4.5*vv2 + 4.5*ww2 -u2v2w2);\n        break;\n    case 13:\n        feq_lattice[k] = lattice_weight[k] * rho_lattice[k]*\n        (1.0 -3.0*uu +3.0*vv + 3.0*ww  -uv - uw + vw +\n        4.5*uu2 + 4.5*vv2 + 4.5*ww2 -u2v2w2);\n        break;\n    case 14:\n        feq_lattice[k] = lattice_weight[k] * rho_lattice[k]*\n        (1.0 +3.0*uu -3.0*vv - 3.0*ww  -uv - uw + vw +\n        4.5*uu2 + 4.5*vv2 + 4.5*ww2 -u2v2w2);\n        break;\n    }\n\n\n}\n\n\nvector_var Solver::get_e_alpha(int k, double &lattice_weight, double c, double PI ){\n\n        vector_var temp;\n        int x ,y,z;\n        //get e_alpha again\n        if (k >0 && k< 5){ //\n\n            x = round(cos((k-1)*PI/2 ) * c );\n            y = round(sin((k-1)*PI/2 )* c);\n            z = 0; //update in 3D\n            lattice_weight = 1.0/9.0;\n        }else if( k >4){\n\n            x = round(sqrt(2) * cos((k-5)*PI/2 + PI/4 ) * c );\n            y = round(sqrt(2) * sin((k-5)*PI/2 + PI/4 ) * c);\n            z = 0; //update in 3D\n            lattice_weight = 1.0/36.0;\n\n        }else{\n            x = 0 ;\n            y = 0;\n            z = 0;\n            lattice_weight = 4.0/9.0;\n        }\n        temp.x = x;\n        temp.y = y;\n        temp.z = z;\n\n\n    return temp;\n}\n\nvoid Solver::populate_e_alpha(vector<vector_var> &e_alpha, double *lattice_weight, double c, double PI,int j ){\n\n        vector_var temp;\n        int x[15] = {0,1,-1,0,0,0,0,1,-1, 1,-1,1,-1,-1,1};\n        int y[15] = { 0,0,0,1,-1,0,0,1,-1,1,-1,-1,1,1,-1};\n        int z[15] = { 0,0,0,0,0,1,-1,1,-1,-1,1,1,-1,1,-1};\n        //get e_alpha again\n\n        for(int k =0; k<j; k++){\n            if (k >0 && k< 7){ //\n\n                lattice_weight[k] = 1.0/9.0;\n\n            }else if( k >6){\n\n\n                lattice_weight[k] = 1.0/72.0;\n\n            }else{\n\n                lattice_weight[k] = 2.0/9.0;\n            }\n\n\n\n            temp.x = x[k];\n            temp.y = y[k];\n            temp.z = z[k];\n\n            e_alpha.push_back(temp);\n\n\n        }\n\n\n\n}\n\nvoid Solver::get_cell_gradients(Mesh &Mesh, int i, int neighbour, int j, Solution &temp_soln,\n                                vector_var &delta_rho, vector_var &delta_rho1,\n                                vector_var &delta_u, vector_var &delta_u1,\n                                vector_var &delta_v, vector_var &delta_v1,\n                                Boundary_Conditions &bcs){\n\n\n        int neighbour_1, neighbour_2;\n        vector_var cell_1, cell_2;\n        // is it N-S or E-W\n        if( j == 2){\n\n\n            neighbour_1 = Mesh.get_w_node(i);\n            neighbour_2 = Mesh.get_e_node(i);\n\n        }else{\n            neighbour_1 = Mesh.get_s_node(i);\n            neighbour_2 = Mesh.get_n_node(i);\n\n        }\n\n        // get neighbouring cells of cells\n        Mesh.get_centroid(neighbour_1,cell_1);\n        Mesh.get_centroid(neighbour_2,cell_2);\n\n        delta_rho.Get_Gradient(temp_soln.get_rho(neighbour_1),temp_soln.get_rho(neighbour_2)\n                               ,cell_1,cell_2);\n        delta_u.Get_Gradient(temp_soln.get_u(neighbour_1),temp_soln.get_u(neighbour_2)\n                               ,cell_1,cell_2);\n        delta_v.Get_Gradient(temp_soln.get_v(neighbour_1),temp_soln.get_v(neighbour_2)\n                               ,cell_1,cell_2);\n\n\n        // get gradient of neighbouring cell\n          if( j == 2){\n\n            neighbour_1 = Mesh.get_w_node(neighbour);\n            neighbour_2 = Mesh.get_e_node(neighbour);\n\n        }else{\n            neighbour_1 = Mesh.get_s_node(neighbour);\n            neighbour_2 = Mesh.get_n_node(neighbour);\n\n        }\n\n        // get neighbouring cells of cells\n        Mesh.get_centroid(neighbour_1,cell_1);\n        Mesh.get_centroid(neighbour_2,cell_2);\n\n        delta_rho1.Get_Gradient(temp_soln.get_rho(neighbour_1),temp_soln.get_rho(neighbour_2)\n                               ,cell_1,cell_2);\n        delta_u1.Get_Gradient(temp_soln.get_u(neighbour_1),temp_soln.get_u(neighbour_2)\n                               ,cell_1,cell_2);\n        delta_v1.Get_Gradient(temp_soln.get_v(neighbour_1),temp_soln.get_v(neighbour_2)\n                               ,cell_1,cell_2);\n\n        }\n\nvoid Solver::cell_interface_variables( int j, int i, vector_var &interface_node, int &neighbour, double &interface_area,\n                              vector_var &cell_normal, Boundary_Conditions &boundary_conditions,  bc_var &bc,\n                              Mesh &Mesh, vector_var &cell_2) {\n\n          switch(j) {\n\n            case 0: // West\n                interface_node.x = Mesh.get_west_x(i);\n                interface_node.y = Mesh.get_west_y(i);\n                interface_node.z= Mesh.get_west_z(i);\n                neighbour = Mesh.get_w_node(i);\n                interface_area = Mesh.get_w_area(i);\n                cell_normal.x = Mesh.get_w_i(i);\n                cell_normal.y = Mesh.get_w_j(i);\n                cell_normal.z = Mesh.get_w_k(i);\n                break;\n\n            case 1: // South\n                interface_node.x = Mesh.get_south_x(i);\n                interface_node.y = Mesh.get_south_y(i);\n                interface_node.z= Mesh.get_south_z(i);\n                neighbour =Mesh.get_s_node(i);\n                interface_area = Mesh.get_s_area(i);\n                cell_normal.x = Mesh.get_s_i(i);\n                cell_normal.y = Mesh.get_s_j(i);\n                cell_normal.z = Mesh.get_s_k(i);\n\n                break;\n            case 2: // East\n                interface_node.x = Mesh.get_east_x(i);\n                interface_node.y = Mesh.get_east_y(i);\n                interface_node.z= Mesh.get_east_z(i);\n                interface_area = Mesh.get_e_area(i);\n                neighbour =Mesh.get_e_node(i);\n                cell_normal.x = Mesh.get_e_i(i);\n                cell_normal.y = Mesh.get_e_j(i);\n                cell_normal.z = Mesh.get_e_k(i);\n\n                break;\n            case 3: // North\n                interface_node.x = Mesh.get_north_x(i);\n                interface_node.y = Mesh.get_north_y(i);\n                interface_node.z= Mesh.get_north_z(i);\n                neighbour =Mesh.get_n_node(i);\n                interface_area = Mesh.get_n_area(i);\n                cell_normal.x = Mesh.get_n_i(i);\n                cell_normal.y = Mesh.get_n_j(i);\n                cell_normal.z = Mesh.get_n_k(i);\n\n                break;\n            case 4: // Front\n                interface_node.x = Mesh.get_front_x(i);\n                interface_node.y = Mesh.get_front_y(i);\n                interface_node.z= Mesh.get_front_z(i);\n                neighbour = Mesh.get_f_node(i);\n                interface_area = Mesh.get_f_area(i);\n                cell_normal.x = Mesh.get_f_i(i);\n                cell_normal.y = Mesh.get_f_j(i);\n                cell_normal.z = Mesh.get_f_k(i);\n\n                break;\n            case 5: // Back\n                interface_node.x = Mesh.get_back_x(i);\n                interface_node.y = Mesh.get_back_y(i);\n                interface_node.z= Mesh.get_back_z(i);\n                neighbour = Mesh.get_b_node(i);\n                interface_area = Mesh.get_b_area(i);\n                cell_normal.x = Mesh.get_b_i(i);\n                cell_normal.y = Mesh.get_b_j(i);\n                cell_normal.z = Mesh.get_b_k(i);\n                break;\n\n\n            }\n//        cell_2.x = Mesh.get_centroid_x(neighbour);\n//        cell_2.y = Mesh.get_centroid_y((neighbour));\n//        cell_2.z = Mesh.get_centroid_z(neighbour);\n\n      }\n\n\n\n      void Solver::cell_interface_variables( int face, int i, vector_var &interface_node, int &neighbour, double &interface_area,\n                              vector_var &cell_normal, Boundary_Conditions &boundary_conditions,  bc_var &bc,\n                              unstructured_mesh &Mesh, vector_var &cell_2, vector_var &cell_1 ) {\n\n\n\n        interface_node.x = Mesh.get_face_x(face);\n        interface_node.y = Mesh.get_face_y(face);\n        interface_node.z= Mesh.get_face_z(face);\n\n        neighbour = Mesh.get_mesh_neighbour(face);\n        interface_area = Mesh.get_face_area(face);\n        cell_normal.x = Mesh.get_face_i(face);\n        cell_normal.y = Mesh.get_face_j(face);\n        cell_normal.z = Mesh.get_face_k(face);\n\n\n       cell_2.x = Mesh.get_centroid_x(neighbour);\n       cell_2.y = Mesh.get_centroid_y((neighbour));\n       cell_2.z = Mesh.get_centroid_z(neighbour);\n\n\n      }\n\n\n\n      void Solver::get_cell_nodes(std::vector<int> &cell_nodes, Boundary_Conditions &bcs,int neighbour,\n                                Mesh &Mesh , int i,int j){\n\n         //current cell\n            cell_nodes.clear();\n            if(bcs.get_bc(i) || bcs.get_bc(neighbour)){\n                 cell_nodes.push_back(i);\n                 cell_nodes.push_back(neighbour);\n\n            }else if( j ==2){\n                cell_nodes.push_back(i);\n                cell_nodes.push_back(Mesh.get_n_node(i));\n                //cell_nodes.push_back(Mesh.get_e_node(i));\n                //cell_nodes.push_back(Mesh.get_w_node(i));\n                cell_nodes.push_back(Mesh.get_s_node(i));\n                cell_nodes.push_back(neighbour);\n                cell_nodes.push_back(Mesh.get_n_node(neighbour));\n                //cell_nodes.push_back(Mesh.get_e_node(neighbour));\n                //cell_nodes.push_back(Mesh.get_w_node(neighbour));\n                cell_nodes.push_back(Mesh.get_s_node(neighbour));\n            }else{\n                cell_nodes.push_back(i);\n                //cell_nodes.push_back(Mesh.get_n_node(i));\n                cell_nodes.push_back(Mesh.get_e_node(i));\n                cell_nodes.push_back(Mesh.get_w_node(i));\n               // cell_nodes.push_back(Mesh.get_s_node(i));\n                cell_nodes.push_back(neighbour);\n                //cell_nodes.push_back(Mesh.get_n_node(neighbour));\n                cell_nodes.push_back(Mesh.get_e_node(neighbour));\n                cell_nodes.push_back(Mesh.get_w_node(neighbour));\n                //cell_nodes.push_back(Mesh.get_s_node(neighbour));\n\n            }\n      }\n\n\n\n\t  //get CFL numbers for inviscid and viscous matrices\n\t  // see what time stepping results\n\t  void Solver::populate_cfl_areas(Solution &cfl_areas, unstructured_mesh &Mesh ) {\n\n\t\t  double area_x, area_y, area_z;\n\t\t  int face;\n\n\t\t  for (int i = 0; i < Mesh.get_n_cells(); i++) {\n\t\t\t  area_x = 0;\n\t\t\t  area_y = 0;\n\t\t\t  area_z = 0;\n\n\t\t\t  // time step condition as per OpenFoam calcs\n\t\t\t  for (int f = 0; f < Mesh.gradient_faces[i].size(); f++) {\n\t\t\t\t  face = Mesh.gradient_faces[i][f];\n\n\t\t\t\t  // eigen values as per Zhaoli guo(2004) - preconditioning\n\n\t\t\t\t  //method as per Jiri Blasek: CFD Principles and Application Determination of Max time Step\n\n\t\t\t\t  // need to calulate correct direction of face vector\n\n\t\t\t\t  area_x = area_x + fabs(Mesh.get_face_i(face)*Mesh.get_face_area(face));\n\t\t\t\t  area_y = area_y + fabs(Mesh.get_face_j(face)*Mesh.get_face_area(face));\n\t\t\t\t  area_z = area_z + fabs(Mesh.get_face_k(face)*Mesh.get_face_area(face));\n\n\t\t\t  }\n\n\t\t\t  cfl_areas.add_u(i, area_x / 2);\n\t\t\t  cfl_areas.add_u(i, area_y / 2);\n\t\t\t  cfl_areas.add_u(i, area_z / 2);\n\n\t\t  }\n\n\t\t  return;\n\t  }\n\n\n\n\n      //get CFL numbers for inviscid and viscous matrices\n      // see what time stepping results\nvoid Solver::get_cfl( double &delta_t, Solution &soln\n                ,unstructured_mesh &Mesh , global_variables &globals, double* delta_t_local, int* delta_t_frequency,Solution &cfl_areas){\n\n    double cfl_inviscid[Mesh.get_total_cells()];\n    double cfl_viscous[Mesh.get_total_cells()];\n    double cfl_i_max,cfl_v_max;\n    double t_v, t_i;\n    double factor;\n    cfl_i_max = 0;\n    cfl_v_max = 0;\n    int face,neighbour;\n\n    double area_x_eigen,eigen,vel_mag,visc_eigen;\n    factor = globals.time_marching_step;\n\n    double visc_constant;\n    visc_constant = 4;\n\n    double min_delta_t,temp;\n\n    double effective_speed_of_sound;\n    //effective_speed_of_sound = 1/sqrt(3);\n\t  effective_speed_of_sound = globals.max_velocity* sqrt( 1 - globals.pre_conditioned_gamma + pow( globals.pre_conditioned_gamma /sqrt(3) / globals.max_velocity, 2));\n    //loop through cells\n\n    min_delta_t = 100000000000;\n\n    for (int i =0; i< Mesh.get_n_cells(); i++){\n\t\tdelta_t_frequency[i] = 1;\n\n\t\t// eigen values as per Zhaoli guo(2004) - preconditioning\n\n\t\t  //estimation of spectral radii s per Jiri Blasek: CFD Principles and Application Determination of Max time Step\n\n        area_x_eigen = 0;\n\t\tarea_x_eigen = (fabs(soln.get_u(i)) + effective_speed_of_sound)*cfl_areas.get_u(i)\n\t\t\t+ ( fabs(soln.get_v(i)) + effective_speed_of_sound)*cfl_areas.get_v(i)\n\t\t\t+ (fabs(soln.get_w(i)) + effective_speed_of_sound)*cfl_areas.get_w(i);\n\n\t\tarea_x_eigen = area_x_eigen / globals.pre_conditioned_gamma;\n\n\n\t\t//reducing preconditioning increases viscous flux - increases eigenvalue\n\t\tvisc_eigen = 2 * globals.visc / globals.pre_conditioned_gamma / soln.get_rho(i) / Mesh.get_cell_volume(i);\n\t\tvisc_eigen = visc_eigen * (cfl_areas.get_u(i)*cfl_areas.get_u(i) + cfl_areas.get_v(i)*cfl_areas.get_v(i) + cfl_areas.get_w(i)* cfl_areas.get_w(i));\n\n\t\tarea_x_eigen = area_x_eigen + 4 * visc_eigen;\n\n        // use smallest time step allowed\n        temp = factor*Mesh.get_cell_volume(i)/area_x_eigen;\n\t\tif (temp < 0) {\n\t\t\tmin_delta_t = temp;\n\n\n\t\t}\n\t\tif (temp < min_delta_t) {\n\t\t\tmin_delta_t = temp;\n\t\t}\n\n        if (globals.time_stepping == \"local\" || globals.time_stepping == \"talts\" ){\n            delta_t_local[i] = temp;\n\n        }else{ //constant user defined time step\n            delta_t_local[i] = factor;\n\n\t\t}\n\t}\n\n\tif( globals.time_stepping == \"min\"){\n        std::fill_n(delta_t_local, Mesh.get_n_cells() , min_delta_t);\n    }\n\n\n\tif (globals.time_stepping == \"talts\") {\n\n\t\tfor (int i = 0; i < Mesh.get_n_cells(); i++) {\n\t\t\tdelta_t_frequency[i] = pow(2, floor(log2(delta_t_local[i] / min_delta_t)) ) ;\n\t\t\tdelta_t_local[i] = min_delta_t * delta_t_frequency[i] ;\n\t\t}\n\n\t}\n\n    return;\n}\n\nvoid Solver::inverse_weighted_distance_interpolation(double &u, double &v, double &rho, Boundary_Conditions &bcs,\n        Mesh &Mesh , domain_geometry &domain,Solution &soln,vector_var &interface_node,\n         int k ,int i ,int neighbour,vector<vector_var> &e_alpha, int j,std::vector<int> &cell_nodes){\n\n            // get interface node\n            double w_u, w_v, w_rho, w_sum ,w;  // weighted macros\n\n            // get 8 nodes'\n            w_u = 0.0;\n            w_v =0.0;\n            w_rho =0.0;\n            w_sum = 0.0;\n\n            double r;\n            r = 0.0;\n            double dt;\n            if (j == 2){\n                dt = Mesh.get_delta_t_e(i);\n            }else{\n                dt = Mesh.get_delta_t_n(i);\n            }\n\n                      //get displacements\n            vector_var node_displacement, target_node;\n\n            // get target node\n            target_node.x = interface_node.x -e_alpha[k].x * dt;\n            target_node.y = interface_node.y -e_alpha[k].y * dt;\n            target_node.z = interface_node.z -e_alpha[k].z * dt;\n\n         for(auto &it : cell_nodes){\n                node_displacement.x = Mesh.get_centroid_x(it) -target_node.x;\n                node_displacement.y = Mesh.get_centroid_y(it) -target_node.y;\n                node_displacement.z = Mesh.get_centroid_z(it) - target_node.z;\n\n                r = node_displacement.Magnitude();\n\n                //\n                if (r < 10e-5){\n                    u = soln.get_u(it);\n                    w = soln.get_v(it);\n                    rho = soln.get_rho(it);\n                    return;\n\n                }\n\n                //get weight for this cc\n                w = pow(1/r, 2.0);\n\n                // sum weighted cc values\n                w_u = w_u  + w* soln.get_u(it);\n                w_v = w_v  + w* soln.get_v(it);\n                w_rho = w_rho  + w* soln.get_rho(it);\n                w_sum = w_sum + w;\n\n            }\n\n            // calc u v rho for target node\n            u = w_u /w_sum;\n            v = w_v/ w_sum;\n            rho = w_rho/ w_sum;\n\n        }\n\nvoid Solver::find_real_time(double* delta_t_local, double* local_time, bool* calc_face,\n                    unstructured_mesh &Mesh, bool* calc_cell){\n\n    // for each cell check cell calc check if time is greater than neighbouring cells;\n    int nb;\n\n    for(int i =0; i<  Mesh.get_total_cells(); i ++){\n        // first update actual time\n        if(calc_cell[i]){\n            local_time[i] = local_time[i] + delta_t_local[i];\n        }\n    }\n\n\n    for( int i = 0; i < Mesh.get_total_cells() ; i++){\n\n\n        calc_cell[i] = true;\n        for(int j = 0; j < Mesh.gradient_cells[i].size(); j++){\n           nb = Mesh.gradient_cells[i][j];\n            if( local_time[i] > local_time[nb]){\n                calc_cell[i] = false;\n                j = Mesh.gradient_cells[i].size();\n            }\n        }\n    }\n\n    // then for each face calc if it should be calculated\n    for( int k = 0; k < Mesh.get_n_faces(); k++){\n        calc_face[k] = false;\n        if( calc_cell[Mesh.get_mesh_owner(k)] || calc_cell[Mesh.get_mesh_neighbour(k)]){\n            calc_face[k] = true;\n        }\n    }\n\n\n\n\n}\n", "meta": {"hexsha": "3ed43ed152d121ac984c2f643019e0c8b8678af2", "size": 71750, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Solver.cpp", "max_stars_repo_name": "CHRG-Developer/LBFS-IBM-ADE-SP", "max_stars_repo_head_hexsha": "6a214c48aef26f2c7c865183a3d612d1c8174257", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-07-27T13:14:12.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-27T13:14:12.000Z", "max_issues_repo_path": "Solver.cpp", "max_issues_repo_name": "CHRG-Developer/LBFS-IBM-ADE-SP", "max_issues_repo_head_hexsha": "6a214c48aef26f2c7c865183a3d612d1c8174257", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Solver.cpp", "max_forks_repo_name": "CHRG-Developer/LBFS-IBM-ADE-SP", "max_forks_repo_head_hexsha": "6a214c48aef26f2c7c865183a3d612d1c8174257", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-17T12:48:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T12:48:36.000Z", "avg_line_length": 38.1446039341, "max_line_length": 166, "alphanum_fraction": 0.5206271777, "num_tokens": 19422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.49038085513901336}}
{"text": "#include <Eigen/Dense>\n#include <vector>\n#include <array>\n#include <string>\n#include <ros/ros.h>\n#include <swerve_point_generator/profiler.h>\n#include <swerve_point_generator/FullGenCoefs.h>\n#include <swerve_point_generator/GenerateSwerveProfile.h>\n#include <talon_swerve_drive_controller/MotionProfile.h> //Only needed for visualization\n\nstd::shared_ptr<swerve_profile::swerve_profiler> profile_gen;\n\nros::ServiceClient graph_prof;\nros::ServiceClient graph_swerve_prof;\n\nbool full_gen(swerve_point_generator::FullGenCoefs::Request &req, swerve_point_generator::FullGenCoefs::Response &res)\n{\n\tconst int k_p = 1;\n\ttalon_swerve_drive_controller::MotionProfile graph_msg;\n\tfor (size_t s = 0; s < req.spline_groups.size(); s++)\n\t{\n\t\tint priv_num = 0;\n\t\tif (s > 0)\n\t\t{\n\t\t\tpriv_num = req.spline_groups[s - 1];\n\t\t}\n\t\tstd::vector<swerve_profile::spline_coefs> x_splines;\n\t\tstd::vector<swerve_profile::spline_coefs> y_splines;\n\t\tstd::vector<swerve_profile::spline_coefs> orient_splines;\n\n\t\tconst int neg_x = req.x_invert[s] ? -1 : 1;\n\t\tstd::vector<double> end_points_holder;\n\t\tdouble shift_by = 0;\n\t\tif (s != 0)\n\t\t{\n\t\t\tshift_by = req.end_points[priv_num - 1];\n\t\t}\n\n\t\tfor (int i = priv_num; i < req.spline_groups[s]; i++)\n\t\t{\n\t\t\torient_splines.push_back(swerve_profile::spline_coefs(\n\t\t\t\t\t\t\t\t\t\t req.orient_coefs[i].spline[0] * neg_x,\n\t\t\t\t\t\t\t\t\t\t req.orient_coefs[i].spline[1] * neg_x,\n\t\t\t\t\t\t\t\t\t\t req.orient_coefs[i].spline[2] * neg_x,\n\t\t\t\t\t\t\t\t\t\t req.orient_coefs[i].spline[3] * neg_x,\n\t\t\t\t\t\t\t\t\t\t req.orient_coefs[i].spline[4] * neg_x,\n\t\t\t\t\t\t\t\t\t\t req.orient_coefs[i].spline[5] * neg_x));\n\t\t\tROS_INFO_STREAM(\"orient_coefs[\" << i << \"].spline=\" << orient_splines.back());\n\n\t\t\tx_splines.push_back(swerve_profile::spline_coefs(\n\t\t\t\t\t\t\t\t\treq.x_coefs[i].spline[0] * neg_x,\n\t\t\t\t\t\t\t\t\treq.x_coefs[i].spline[1] * neg_x,\n\t\t\t\t\t\t\t\t\treq.x_coefs[i].spline[2] * neg_x,\n\t\t\t\t\t\t\t\t\treq.x_coefs[i].spline[3] * neg_x,\n\t\t\t\t\t\t\t\t\treq.x_coefs[i].spline[4] * neg_x,\n\t\t\t\t\t\t\t\t\treq.x_coefs[i].spline[5] * neg_x));\n\t\t\tROS_INFO_STREAM(\"x_coefs[\" << i << \"].spline=\" << x_splines.back());\n\n\t\t\ty_splines.push_back(swerve_profile::spline_coefs(\n\t\t\t\t\t\t\t\t\treq.y_coefs[i].spline[0],\n\t\t\t\t\t\t\t\t\treq.y_coefs[i].spline[1],\n\t\t\t\t\t\t\t\t\treq.y_coefs[i].spline[2],\n\t\t\t\t\t\t\t\t\treq.y_coefs[i].spline[3],\n\t\t\t\t\t\t\t\t\treq.y_coefs[i].spline[4],\n\t\t\t\t\t\t\t\t\treq.y_coefs[i].spline[5]));\n\t\t\tROS_INFO_STREAM(\"y_coefs[\" << i << \"].spline=\" << y_splines.back());\n\n\t\t\tROS_INFO_STREAM(\"hrer: \" << req.end_points[i] - shift_by << \" r_s: \" <<  req.spline_groups[s] <<  \" s: \" << s);\n\t\t\tend_points_holder.push_back(req.end_points[i] - shift_by);\n\t\t}\n\n\t\tconst double t_shift = req.t_shift[s];\n\t\tconst bool flip_dirc = req.flip[s];\n\t\tROS_INFO_STREAM(\"req.initial_v: \" << req.initial_v << \" req.final_v: \" << req.final_v << \" t_shift: \" << t_shift);\n\n\t\t// TODO - replace with just an array of JointTrajectoryPoints since\n\t\t// the rest of the message isn't used at all\n\t\tswerve_point_generator::GenerateSwerveProfile::Response srv_msg; //TODO FIX THIS, HACK\n\t\tprofile_gen->generate_profile(x_splines, y_splines, orient_splines, req.initial_v, req.final_v, srv_msg, end_points_holder, t_shift, flip_dirc);\n\t\tconst int point_count = srv_msg.points.size();\n\n\t\tgraph_msg.request.joint_trajectory.header = srv_msg.header;\n\n\t\tres.dt = profile_gen->getDT();\n\n\t\t// TODO - just for debugging\n\t\tdouble total_length_x = 0;\n\t\tdouble total_length_y = 0;\n\t\tdouble total_length_theta = 0;\n\t\tfor(size_t i = 0; i < srv_msg.points.size(); i++)\n\t\t{\n\t\t\ttotal_length_x += srv_msg.points[i].velocities[0] * profile_gen->getDT();\n\t\t\ttotal_length_y += srv_msg.points[i].velocities[1] * profile_gen->getDT();\n\t\t\ttotal_length_theta += srv_msg.points[i].velocities[2] * profile_gen->getDT();\n\t\t}\n\t\tROS_ERROR_STREAM(\"total_length_x = \" << total_length_x << \" total_length_y = \" <<  total_length_y << \" total_length_theta = \" << total_length_theta);\n\t\tfor(size_t i = 0; i < srv_msg.points.size(); i++)\n\t\t{\n\t\t\tROS_INFO_STREAM(srv_msg.points[i].positions[0] << \" \" << srv_msg.points[i].positions[1] << \" \" << srv_msg.points[i].positions[2]);\n\t\t}\n\n\t\t// Bounds checking - not safe to proceed with setting up angle\n\t\t// positions and velocities if data is not as expected.\n\t\tif (srv_msg.points.size() < 2)\n\t\t{\n\t\t\tROS_ERROR(\"Need at least 2 points\");\n\t\t\treturn false;\n\t\t}\n\t\tfor (const auto point : srv_msg.points)\n\t\t{\n\t\t\tif (point.positions.size() < 3)\n\t\t\t{\n\t\t\t\tROS_ERROR(\"Not enough positions in point\");\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tROS_INFO_STREAM(\"velocity vector = \" << srv_msg.points[1].positions[0] - srv_msg.points[0].positions[0] <<\n\t\t\t\t\" \" << srv_msg.points[1].positions[1] - srv_msg.points[0].positions[1] <<\n\t\t\t\t\" rotation = \" << srv_msg.points[1].positions[2] - srv_msg.points[0].positions[2] <<\n\t\t\t\t\" angle = \" << srv_msg.points[1].positions[2]);\n\n\t\tsize_t hold_count = round(req.wait_before_group[s] / profile_gen->getDT());\n\t\tbool skip_one_traj = false;\n\t\tif ((hold_count > 0) && (res.hold.size() == 0))\n\t\t{\n\t\t\tgraph_msg.request.joint_trajectory.points.push_back(srv_msg.points[0]);\n\t\t\tres.hold.push_back(true);\n\t\t\tskip_one_traj = true;\n\t\t}\n\t\tfor (size_t i = 0; i < hold_count; i++)\n\t\t{\n\t\t\tif (!skip_one_traj)\n\t\t\t{\n\t\t\t\tgraph_msg.request.joint_trajectory.points.push_back(srv_msg.points[1]);\n\t\t\t\tres.hold.push_back(true);\n\t\t\t}\n\n\t\t\tskip_one_traj = false;\n\t\t}\n\n\t\tgraph_msg.request.joint_trajectory.points.insert(graph_msg.request.joint_trajectory.points.end(), srv_msg.points.begin(), srv_msg.points.end());\n\n\t\tfor (int i = 0; i < point_count - k_p; i++)\n\t\t{\n\t\t\tres.hold.push_back(false);\n\t\t}\n\t}\n\n\tgraph_prof.call(graph_msg);\n\tres.joint_trajectory = graph_msg.request.joint_trajectory;\n\tROS_INFO_STREAM(\"profile time: \" << res.joint_trajectory.points.size() * profile_gen->getDT());\n\n\t//talon_swerve_drive_controller::MotionProfilePoints graph_swerve_msg;\n\t//graph_swerve_msg.request.points = res.points;\n\t//graph_swerve_prof.call(graph_swerve_msg);\n\t//ROS_WARN(\"FIN\");\n\treturn true;\n}\nint main(int argc, char **argv)\n{\n\tros::init(argc, argv, \"point_gen\");\n\tros::NodeHandle nh;\n\n\tros::NodeHandle controller_nh(nh, \"/frcrobot_jetson/swerve_drive_controller\");\n\n\tdouble max_accel;\n\tdouble max_brake_accel;\n\tdouble ang_accel_conv;\n\tdouble max_speed;\n\n\tif (!nh.getParam(\"max_accel\", max_accel))\n\t\tROS_ERROR(\"Could not read max_accel in point_gen\");\n\tif (!nh.getParam(\"max_brake_accel\", max_brake_accel))\n\t\tROS_ERROR(\"Could not read max_brake_accel in point_gen\");\n\tif (!nh.getParam(\"ang_accel_conv\", ang_accel_conv))\n\t\tROS_ERROR(\"Could not read ang_accel_conv in point_gen\");\n\tif (!nh.getParam(\"max_speed\", max_speed))\n\t\tROS_ERROR(\"Could not read max_speed in point_gen\");\n\n\tconstexpr size_t WHEELCOUNT = 4;\n\tstd::array<Eigen::Vector2d, WHEELCOUNT> wheel_coords;\n\tif (!controller_nh.getParam(\"wheel_coords1x\", wheel_coords[0][0]))\n\t\tROS_ERROR(\"Could not read wheel_coords1x in point_gen\");\n\tif (!controller_nh.getParam(\"wheel_coords2x\", wheel_coords[1][0]))\n\t\tROS_ERROR(\"Could not read wheel_coords2x in point_gen\");\n\tif (!controller_nh.getParam(\"wheel_coords3x\", wheel_coords[2][0]))\n\t\tROS_ERROR(\"Could not read wheel_coords3x in point_gen\");\n\tif (!controller_nh.getParam(\"wheel_coords4x\", wheel_coords[3][0]))\n\t\tROS_ERROR(\"Could not read wheel_coords4x in point_gen\");\n\tif (!controller_nh.getParam(\"wheel_coords1y\", wheel_coords[0][1]))\n\t\tROS_ERROR(\"Could not read wheel_coords1y in point_gen\");\n\tif (!controller_nh.getParam(\"wheel_coords2y\", wheel_coords[1][1]))\n\t\tROS_ERROR(\"Could not read wheel_coords2y in point_gen\");\n\tif (!controller_nh.getParam(\"wheel_coords3y\", wheel_coords[2][1]))\n\t\tROS_ERROR(\"Could not read wheel_coords3y in point_gen\");\n\tif (!controller_nh.getParam(\"wheel_coords4y\", wheel_coords[3][1]))\n\t\tROS_ERROR(\"Could not read wheel_coords4y in point_gen\");\n\n\t//ROS_WARN(\"point_init\");\n\t//ROS_INFO_STREAM(\"model max speed: \" << model.maxSpeed << \" radius: \" << model.wheelRadius);\n\n\tconstexpr double defined_dt = .02;\n\tprofile_gen = std::make_shared<swerve_profile::swerve_profiler>(\n\t\t\t\t\t\thypot(wheel_coords[0][0], wheel_coords[0][1]),\n\t\t\t\t\t\tmax_speed,\n\t\t\t\t\t\tmax_accel,\n\t\t\t\t\t\tmax_brake_accel,\n\t\t\t\t\t\tang_accel_conv,\n\t\t\t\t\t\tdefined_dt);\n\n\tstd::map<std::string, std::string> service_connection_header;\n\tservice_connection_header[\"tcp_nodelay\"] = \"1\";\n\tgraph_prof = nh.serviceClient<talon_swerve_drive_controller::MotionProfile>(\"visualize_profile\", false, service_connection_header);\n\tgraph_swerve_prof = nh.serviceClient<talon_swerve_drive_controller::MotionProfile>(\"visualize_swerve_profile\", false, service_connection_header);\n\n\t// Once everything this node needs is available, open\n\t// it up to connections from the outside\n\tros::ServiceServer service = nh.advertiseService(\"point_gen/command\", full_gen);\n\n\tros::spin();\n}\n", "meta": {"hexsha": "5647b2cc5d9c17182ec35d410c100c3b0afd5ff5", "size": 8632, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "zebROS_ws/src/swerve_point_generator/src/point_gen.cpp", "max_stars_repo_name": "mattwalstra/2019RobotCode", "max_stars_repo_head_hexsha": "44f2543876b95428a68dc84820f931571244e49d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-01-15T16:37:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-15T16:39:31.000Z", "max_issues_repo_path": "zebROS_ws/src/swerve_point_generator/src/point_gen.cpp", "max_issues_repo_name": "mattwalstra/2019RobotCode", "max_issues_repo_head_hexsha": "44f2543876b95428a68dc84820f931571244e49d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-08-30T00:06:15.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-29T17:02:18.000Z", "max_forks_repo_path": "zebROS_ws/src/swerve_point_generator/src/point_gen.cpp", "max_forks_repo_name": "mattwalstra/2019RobotCode", "max_forks_repo_head_hexsha": "44f2543876b95428a68dc84820f931571244e49d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-10-29T01:13:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T21:53:06.000Z", "avg_line_length": 38.7085201794, "max_line_length": 151, "alphanum_fraction": 0.7043558851, "num_tokens": 2481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358014, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4903808551390132}}
{"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#ifndef SOLVERS_VIENNACLSOLVER_HPP\n#define SOLVERS_VIENNACLSOLVER_HPP\n\n#include <Eigen/Dense>\n\n#include <viennacl/linalg/cg.hpp>\n#include <viennacl/linalg/gmres.hpp>\n#include <viennacl/linalg/ichol.hpp>\n#include <viennacl/linalg/ilu.hpp>\n#include <viennacl/linalg/jacobi_precond.hpp>\n\n#include <solvers/Solver.hpp>\n#include <solvers/SparseSystem.hpp>\n\nnamespace solvers {\n\nenum class ViennaCLMethod { CG, GMRES };\nenum class ViennaCLPreconditioner {\n    None,\n    ChowPatel,\n    ILU0,\n    IChol0,\n    BlockILU0,\n    Jacobi,\n    RowScaling\n};\n\n/**\n * \\brief ViennaCLSolver Iterative solver based on ViennaCL library.\n */\nclass ViennaCLSolver : public Solver {\nprivate:\n    /**\n     * \\brief _method Resolution algorithm.\n     */\n    ViennaCLMethod _method;\n\n    /**\n     * \\brief _preconditioner Preconditioning algorithm.\n     */\n    ViennaCLPreconditioner _preconditioner;\n\n    /**\n     * \\brief _cg_config Parameters for conjugate gradient algorithm.\n     */\n    viennacl::linalg::cg_tag _cg_config;\n\n    /**\n     * \\brief _gmres_config Parameters for GMRES algorithm.\n     */\n    viennacl::linalg::gmres_tag _gmres_config;\n\n    /**\n     * \\brief _chow_patel_config Parameters for Chow-Patel preconditioner.\n     */\n    viennacl::linalg::chow_patel_tag _chow_patel_config;\n\n    /**\n     * \\brief _ilu0_config Parameters for ILU(0) preconditioner.\n     */\n    viennacl::linalg::ilu0_tag _ilu0_config;\n\n    /**\n     * \\brief _ichol0_config Parameters for ICC preconditioner.\n     */\n    viennacl::linalg::ichol0_tag _ichol0_config;\n\n    /**\n     * \\brief _jacobi_config Parameters for Jacobi preconditioner.\n     */\n    viennacl::linalg::jacobi_tag _jacobi_config;\n\n    /**\n     * \\brief _row_scaling_config Parameters for row scaling preconditioner.\n     */\n    viennacl::linalg::row_scaling_tag _row_scaling_config;\n\npublic:\n    explicit ViennaCLSolver(\n        ViennaCLMethod method = ViennaCLMethod::CG,\n        ViennaCLPreconditioner preconditioner = ViennaCLPreconditioner::None,\n        double tolerance = 1e-8,\n        int iterations = 300);\n\n    Eigen::VectorXd solve(const SparseSystem& system,\n                          double& duration) const override;\n};\n\n}    // namespace solvers\n\n#endif    // SOLVERS_VIENNACLSOLVER_HPP", "meta": {"hexsha": "aac37703a782c8adbe728e1b166f9525c587d4f6", "size": 2834, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "solvers/include/solvers/ViennaCLSolver.hpp", "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/include/solvers/ViennaCLSolver.hpp", "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/include/solvers/ViennaCLSolver.hpp", "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": 26.7358490566, "max_line_length": 77, "alphanum_fraction": 0.703246295, "num_tokens": 720, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189121808099, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.4903808447445539}}
{"text": "#include <boost/math/distributions/beta.hpp>\n", "meta": {"hexsha": "fe80a3e47527fdd89e3233662aba6c387f1017a5", "size": 45, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_distributions_beta.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_distributions_beta.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_distributions_beta.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 22.5, "max_line_length": 44, "alphanum_fraction": 0.8, "num_tokens": 10, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189121808099, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.49038084474455385}}
{"text": "#include <Configuration.h>\n#include <Eigen/Eigenvalues>\n#include <PnC/PlannerSet/PIPM_FootPlacementPlanner/Reversal_LIPM_Planner.hpp>\n#include <Utils/IO/IOUtilities.hpp>\n\nReversal_LIPM_Planner::Reversal_LIPM_Planner()\n    : FootStepPlanner(),\n      com_vel_limit_(2),\n      b_set_omega_(false),\n      planner_save_data_(11) {\n    t_prime_.resize(2);\n    kappa_.resize(2);\n    x_step_length_limit_.resize(2);\n    y_step_length_limit_.resize(2);\n    com_vel_limit_.resize(2);\n    R_w_t_ = Eigen::MatrixXd::Identity(2, 2);\n}\n\nReversal_LIPM_Planner::~Reversal_LIPM_Planner() {}\n\nvoid Reversal_LIPM_Planner::_computeSwitchingState(\n    double swing_time, const Eigen::Vector3d& com_pos,\n    const Eigen::Vector3d& com_vel, const Eigen::Vector3d& stance_foot_loc,\n    std::vector<Eigen::Vector2d>& switching_state) {\n    double A, B;\n    for (int i(0); i < 2; ++i) {\n        A = ((com_pos[i] - stance_foot_loc[i]) + com_vel[i] / omega_) / 2.;\n        B = ((com_pos[i] - stance_foot_loc[i]) - com_vel[i] / omega_) / 2.;\n        switching_state[i][0] = A * exp(omega_ * swing_time) +\n                                B * exp(-omega_ * swing_time) +\n                                stance_foot_loc[i];\n        switching_state[i][1] = omega_ * (A * exp(omega_ * swing_time) -\n                                          B * exp(-omega_ * swing_time));\n    }\n}\n\n// global CoM pos\nvoid Reversal_LIPM_Planner::getNextFootLocation(const Eigen::Vector3d& com_pos,\n                                                const Eigen::Vector3d& com_vel,\n                                                Eigen::Vector3d& target_loc,\n                                                const void* additional_input,\n                                                void* additional_output) {\n    if (!b_set_omega_) {\n        printf(\"[Reversal Planner] Omega is not set\\n\");\n        exit(0);\n    }\n    ParamReversalPL* _input = ((ParamReversalPL*)additional_input);\n    OutputReversalPL* _output = ((OutputReversalPL*)additional_output);\n    _UpdateRotation(_input->yaw_angle);\n\n    std::vector<Eigen::Vector2d> switch_state(2);\n    _computeSwitchingState(_input->swing_time, com_pos, com_vel,\n                           _input->stance_foot_loc, switch_state);\n\n    // (x, y, xdot, ydot)\n    _output->switching_state[0] = switch_state[0][0];\n    _output->switching_state[1] = switch_state[1][0];\n    _output->switching_state[2] = switch_state[0][1];\n    _output->switching_state[3] = switch_state[1][1];\n    // printf(\"switching position: %f, %f\\n\", switch_state[0][0],\n    // switch_state[1][0]);\n    // printf(\"switching velocity: %f, %f\\n\", switch_state[0][1],\n    // switch_state[1][1]);\n\n    // !! TEST !!\n     int check_switch(_check_switch_velocity(switch_state));\n    //int check_switch(_check_switch_velocity_considering_rotation(switch_state));\n    // !! TEST !!\n    double new_swing_time(_input->swing_time);\n    int count(0);\n    while (check_switch != 0) {\n        if (check_switch > 0) {  // Too small velocity increase time\n            new_swing_time *= 1.1;\n            myUtils::color_print(myColor::BoldRed,\n                                 \"Too small velocity.. increase swing time: \" +\n                                     std::to_string(new_swing_time),\n                                 true);\n        } else {  // Too larget velocity decrease time\n            new_swing_time *= 0.9;\n            myUtils::color_print(myColor::BoldRed,\n                                 \"Too small velocity.. decrease swing time: \" +\n                                     std::to_string(new_swing_time),\n                                 true);\n        }\n        _computeSwitchingState(new_swing_time, com_pos, com_vel,\n                               _input->stance_foot_loc, switch_state);\n\n        // !! TEST !!\n         check_switch = _check_switch_velocity(switch_state);\n        //check_switch = _check_switch_velocity_considering_rotation(switch_state);\n        // !! TEST !!\n        ++count;\n        if (count > 0) break;\n    }\n    _output->time_modification = new_swing_time - _input->swing_time;\n\n    for (int i(0); i < 2; ++i) {\n        double exp_weight =\n            (exp(omega_ * t_prime_[i]) + exp(-omega_ * t_prime_[i])) /\n            (exp(omega_ * t_prime_[i]) - exp(-omega_ * t_prime_[i]));\n\n        target_loc[i] = switch_state[i][0] +\n                        (switch_state[i][1] / omega_) * exp_weight +\n                        kappa_[i] * (_input->des_loc[i] - switch_state[i][0]);\n    }\n    target_loc[2] = 0.;\n\n    // _StepLengthCheck(target_loc, switch_state);\n    // !! TEST !!\n    _StepLengthCheck(target_loc, _input->b_positive_sidestep, _input->stance_foot_loc);\n    //_StepLengthCheckConsideringRotation(target_loc, _input->b_positive_sidestep,\n                                        //_input->stance_foot_loc);\n    // !! TEST !!\n\n    // save data\n    for (int i(0); i < 2; ++i) {\n        planner_save_data_[i] = com_pos[i];\n        planner_save_data_[2 + i] = com_vel[i];\n        planner_save_data_[4 + i] = switch_state[i][0];\n        planner_save_data_[6 + i] = switch_state[i][1];\n        planner_save_data_[8 + i] = target_loc[i];\n    }\n    planner_save_data_[10] = new_swing_time;\n    myUtils::saveVector(planner_save_data_, \"planner_data\");\n}\n\nint Reversal_LIPM_Planner::_check_switch_velocity(\n    const std::vector<Eigen::Vector2d>& switch_state) {\n    int ret(0);\n    double x_vel(switch_state[0][1]);\n    double y_vel(switch_state[1][1]);\n\n    // X\n    if (x_vel > 0.) {\n        if (x_vel < com_vel_limit_[0]) ret = 1;\n        if (x_vel > com_vel_limit_[1]) ret = -1;\n    } else {\n        if (x_vel > -com_vel_limit_[0]) ret = 1;\n        if (x_vel < -com_vel_limit_[1]) ret = -1;\n    }\n\n    // Y\n    if (y_vel > 0.) {\n        if (y_vel < com_vel_limit_[0]) ret = 1;\n        if (y_vel > com_vel_limit_[1]) ret = -1;\n    } else {\n        if (y_vel > -com_vel_limit_[0]) ret = 1;\n        if (y_vel < -com_vel_limit_[1]) ret = -1;\n    }\n\n    return ret;\n}\n\nint Reversal_LIPM_Planner::_check_switch_velocity_considering_rotation(\n    const std::vector<Eigen::Vector2d>& switch_state) {\n    int ret(0);\n    Eigen::VectorXd global_com_vel = Eigen::VectorXd::Zero(2);\n    global_com_vel << switch_state[0][1], switch_state[1][1];\n    Eigen::VectorXd local_com_vel = Eigen::VectorXd::Zero(2);\n    local_com_vel = R_w_t_.transpose() * global_com_vel;\n\n    // X\n    double x_vel(local_com_vel[0]);\n    double y_vel(local_com_vel[1]);\n    if (x_vel > 0.) {\n        if (x_vel < com_vel_limit_[0]) ret = 1;\n        if (x_vel > com_vel_limit_[1]) ret = -1;\n    } else {\n        if (x_vel > -com_vel_limit_[0]) ret = 1;\n        if (x_vel < -com_vel_limit_[1]) ret = -1;\n    }\n\n    // Y\n    if (y_vel > 0.) {\n        if (y_vel < com_vel_limit_[0]) ret = 1;\n        if (y_vel > com_vel_limit_[1]) ret = -1;\n    } else {\n        if (y_vel > -com_vel_limit_[0]) ret = 1;\n        if (y_vel < -com_vel_limit_[1]) ret = -1;\n    }\n    return ret;\n}\n\nvoid Reversal_LIPM_Planner::_StepLengthCheck(\n    Eigen::Vector3d& target_loc, bool b_positive_sidestep,\n    const Eigen::Vector3d& stance_foot) {\n    // X limit check\n    double x_step_length(target_loc[0] - stance_foot[0]);\n    if (x_step_length < x_step_length_limit_[0]) {\n        target_loc[0] = stance_foot[0] + x_step_length_limit_[0];\n        myUtils::color_print(\n            myColor::BoldRed,\n            \"x step length hit min: \" + std::to_string(x_step_length), true);\n        myUtils::color_print(myColor::BoldRed,\n                             \"new x step: (\" + std::to_string(target_loc[0]) +\n                                 \", \" + std::to_string(stance_foot[0]) + \")\",\n                             true);\n    }\n    if (x_step_length > x_step_length_limit_[1]) {\n        target_loc[0] = stance_foot[0] + x_step_length_limit_[1];\n        myUtils::color_print(\n            myColor::BoldRed,\n            \"x step length hit max: \" + std::to_string(x_step_length), true);\n        myUtils::color_print(myColor::BoldRed,\n                             \"new x step: (\" + std::to_string(target_loc[0]) +\n                                 \", \" + std::to_string(stance_foot[0]) + \")\",\n                             true);\n    }\n\n    // Y limit check\n    double y_step_length(target_loc[1] - stance_foot[1]);\n    if (b_positive_sidestep) {  // move to left\n        if (y_step_length < y_step_length_limit_[0]) {\n            target_loc[1] = stance_foot[1] + y_step_length_limit_[0];\n            myUtils::color_print(\n                myColor::BoldRed,\n                \"y step length hit min: \" + std::to_string(y_step_length),\n                true);\n            myUtils::color_print(myColor::BoldRed,\n                                 \"new y step: (\" +\n                                     std::to_string(target_loc[1]) + \", \" +\n                                     std::to_string(stance_foot[1]) + \")\",\n                                 true);\n        }\n\n        if (y_step_length > y_step_length_limit_[1]) {\n            target_loc[1] = stance_foot[1] + y_step_length_limit_[1];\n            myUtils::color_print(\n                myColor::BoldRed,\n                \"y step length hit max: \" + std::to_string(y_step_length),\n                true);\n            myUtils::color_print(myColor::BoldRed,\n                                 \"new y step: (\" +\n                                     std::to_string(target_loc[1]) + \", \" +\n                                     std::to_string(stance_foot[1]) + \")\",\n                                 true);\n        }\n\n    } else {  // move to right\n        if (-y_step_length < y_step_length_limit_[0]) {\n            target_loc[1] = stance_foot[1] - y_step_length_limit_[0];\n            myUtils::color_print(\n                myColor::BoldRed,\n                \"y step length hit min: \" + std::to_string(y_step_length),\n                true);\n            myUtils::color_print(myColor::BoldRed,\n                                 \"new y step: (\" +\n                                     std::to_string(target_loc[1]) + \", \" +\n                                     std::to_string(stance_foot[1]) + \")\",\n                                 true);\n        }\n\n        if (-y_step_length > y_step_length_limit_[1]) {\n            target_loc[1] = stance_foot[1] - y_step_length_limit_[1];\n            myUtils::color_print(\n                myColor::BoldRed,\n                \"y step length hit max: \" + std::to_string(y_step_length),\n                true);\n            myUtils::color_print(myColor::BoldRed,\n                                 \"new y step: (\" +\n                                     std::to_string(target_loc[1]) + \", \" +\n                                     std::to_string(stance_foot[1]) + \")\",\n                                 true);\n        }\n    }\n}\n\nvoid Reversal_LIPM_Planner::_StepLengthCheck(\n    Eigen::Vector3d& target_loc,\n    const std::vector<Eigen::Vector2d>& switch_state) {\n    // X limit check\n    double x_step_length(target_loc[0] - switch_state[0][0]);\n    if (x_step_length < x_step_length_limit_[0]) {\n        target_loc[0] = switch_state[0][0] + x_step_length_limit_[0];\n        printf(\"x step length hit min: %f\\n\", x_step_length);\n        printf(\"new x step: %f, %f \\n\", target_loc[0], switch_state[0][0]);\n    }\n    if (x_step_length > x_step_length_limit_[1]) {\n        target_loc[0] = switch_state[0][0] + x_step_length_limit_[1];\n        printf(\"x step length hit max: %f\\n\", x_step_length);\n        printf(\"new x step: %f, %f \\n\", target_loc[0], switch_state[0][0]);\n    }\n\n    // Y limit check\n    double y_step_length(target_loc[1] - switch_state[1][0]);\n    if (switch_state[1][1] > 0) {  // move to left\n        if (y_step_length < y_step_length_limit_[0]) {\n            target_loc[1] = switch_state[1][0] + y_step_length_limit_[0];\n        }\n\n        if (y_step_length > y_step_length_limit_[1]) {\n            target_loc[1] = switch_state[1][0] + y_step_length_limit_[1];\n        }\n\n    } else {  // move to right\n        if (-y_step_length < y_step_length_limit_[0])\n            target_loc[1] = switch_state[1][0] - y_step_length_limit_[0];\n        if (-y_step_length > y_step_length_limit_[1])\n            target_loc[1] = switch_state[1][0] - y_step_length_limit_[1];\n    }\n}\n\nvoid Reversal_LIPM_Planner::PlannerInitialization(const YAML::Node& node) {\n    try {\n        Eigen::VectorXd tmp;\n        myUtils::readParameter(node, \"t_prime\", tmp);\n        for (int i = 0; i < 2; ++i) {\n            t_prime_[i] = tmp[i];\n        }\n        myUtils::readParameter(node, \"kappa\", tmp);\n        for (int i = 0; i < 2; ++i) {\n            kappa_[i] = tmp[i];\n        }\n        myUtils::readParameter(node, \"x_step_length_limit\", tmp);\n        for (int i = 0; i < 2; ++i) {\n            x_step_length_limit_[i] = tmp[i];\n        }\n        myUtils::readParameter(node, \"y_step_length_limit\", tmp);\n        for (int i = 0; i < 2; ++i) {\n            y_step_length_limit_[i] = tmp[i];\n        }\n        myUtils::readParameter(node, \"com_velocity_limit\", tmp);\n        for (int i = 0; i < 2; ++i) {\n            com_vel_limit_[i] = tmp[i];\n        }\n    } catch (std::runtime_error& e) {\n        std::cout << \"Error reading parameter [\" << e.what() << \"] at file: [\"\n                  << __FILE__ << \"]\" << std::endl\n                  << std::endl;\n    }\n}\n\nvoid Reversal_LIPM_Planner::CheckEigenValues(double swing_time) {\n    Eigen::MatrixXd A(2, 2);\n    printf(\"omega, swing_time: %f, %f\\n\", omega_, swing_time);\n\n    for (int i(0); i < 2; ++i) {\n        double coth = cosh(omega_ * t_prime_[i]) / sinh(omega_ * t_prime_[i]);\n\n        A(0, 0) = 1 - kappa_[i] + kappa_[i] * cosh(omega_ * swing_time);\n        A(0, 1) = (sinh(omega_ * swing_time) +\n                   (1. - cosh(omega_ * swing_time)) * coth) /\n                  omega_;\n        A(1, 0) = kappa_[i] * omega_ * sinh(omega_ * swing_time);\n        A(1, 1) = cosh(omega_ * swing_time) - sinh(omega_ * swing_time) * coth;\n\n        Eigen::VectorXcd eivals = A.eigenvalues();\n        printf(\"%d - axis eigen value:\\n\", i);\n        std::cout << eivals << std::endl;\n    }\n}\n\nvoid Reversal_LIPM_Planner::_UpdateRotation(double yaw_angle) {\n    R_w_t_(0, 0) = cos(yaw_angle);\n    R_w_t_(1, 0) = sin(yaw_angle);\n    R_w_t_(1, 0) = -sin(yaw_angle);\n    R_w_t_(1, 1) = cos(yaw_angle);\n}\n\nvoid Reversal_LIPM_Planner::_StepLengthCheckConsideringRotation(\n    Eigen::Vector3d& target_loc, bool b_positive_sidestep,\n    const Eigen::Vector3d& stance_foot) {\n    Eigen::Vector2d stance_foot_in_torso, target_loc_in_torso,\n        v_stance_target_in_torso;\n    stance_foot_in_torso << stance_foot[0], stance_foot[1];\n    stance_foot_in_torso = R_w_t_.transpose() * stance_foot_in_torso;\n    target_loc_in_torso << target_loc[0], target_loc[1];\n    target_loc_in_torso = R_w_t_.transpose() * target_loc_in_torso;\n    v_stance_target_in_torso = target_loc_in_torso - stance_foot_in_torso;\n\n    // X limit check\n    if (v_stance_target_in_torso[0] < x_step_length_limit_[0]) {\n        target_loc_in_torso[0] =\n            stance_foot_in_torso[0] + x_step_length_limit_[0];\n        myUtils::color_print(myColor::BoldRed,\n                             \"x step length hit min: \" +\n                                 std::to_string(v_stance_target_in_torso[0]),\n                             true);\n        // myUtils::color_print(myColor::BoldRed, \"new x step: (\" +\n        // std::to_string(target_loc[0]) + \", \" + std::to_string(stance_foot[0])\n        // + \")\", true);\n    }\n    if (v_stance_target_in_torso[0] > x_step_length_limit_[1]) {\n        target_loc_in_torso[0] =\n            stance_foot_in_torso[0] + x_step_length_limit_[1];\n        myUtils::color_print(myColor::BoldRed,\n                             \"x step length hit max: \" +\n                                 std::to_string(v_stance_target_in_torso[0]),\n                             true);\n        // myUtils::color_print(myColor::BoldRed, \"new x step: (\"+\n        // std::to_string(target_loc[0]) + \", \" + std::to_string(stance_foot[0])\n        // + \")\", true);\n    }\n\n    // Y limit check\n    if (b_positive_sidestep) {  // move to left\n        if (v_stance_target_in_torso[1] < y_step_length_limit_[0]) {\n            target_loc_in_torso[1] =\n                stance_foot_in_torso[1] + y_step_length_limit_[0];\n            myUtils::color_print(\n                myColor::BoldRed,\n                \"y step length hit min: \" +\n                    std::to_string(v_stance_target_in_torso[1]),\n                true);\n            // myUtils::color_print(myColor::BoldRed, \"new y step: (\"+\n            // std::to_string(target_loc[1]) + \", \" +\n            // std::to_string(stance_foot[1]) + \")\", true);\n        }\n\n        if (v_stance_target_in_torso[1] > y_step_length_limit_[1]) {\n            target_loc_in_torso[1] =\n                stance_foot_in_torso[1] + y_step_length_limit_[1];\n            myUtils::color_print(\n                myColor::BoldRed,\n                \"y step length hit max: \" +\n                    std::to_string(v_stance_target_in_torso[1]),\n                true);\n            // myUtils::color_print(myColor::BoldRed, \"new y step: (\"+\n            // std::to_string(target_loc[1]) + \", \" +\n            // std::to_string(stance_foot[1]) + \")\", true);\n        }\n\n    } else {  // move to right\n        if (-v_stance_target_in_torso[1] < y_step_length_limit_[0]) {\n            target_loc_in_torso[1] =\n                stance_foot_in_torso[1] - y_step_length_limit_[0];\n            myUtils::color_print(\n                myColor::BoldRed,\n                \"y step length hit min: \" +\n                    std::to_string(v_stance_target_in_torso[1]),\n                true);\n            // myUtils::color_print(myColor::BoldRed, \"new y step: (\"+\n            // std::to_string(target_loc[1]) + \", \" +\n            // std::to_string(stance_foot[1]) + \")\", true);\n        }\n\n        if (-v_stance_target_in_torso[1] > y_step_length_limit_[1]) {\n            target_loc_in_torso[1] =\n                stance_foot_in_torso[1] - y_step_length_limit_[1];\n            myUtils::color_print(\n                myColor::BoldRed,\n                \"y step length hit max: \" +\n                    std::to_string(v_stance_target_in_torso[1]),\n                true);\n            // myUtils::color_print(myColor::BoldRed, \"new y step: (\"+\n            // std::to_string(target_loc[1]) + \", \" +\n            // std::to_string(stance_foot[1]) + \")\", true);\n        }\n    }\n    target_loc[0] = (R_w_t_ * target_loc_in_torso)[0];\n    target_loc[1] = (R_w_t_ * target_loc_in_torso)[1];\n}\n", "meta": {"hexsha": "ce45c4eb03ca2a40e4baabb76058c82d10f1ca7e", "size": 18440, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PnC/PlannerSet/PIPM_FootPlacementPlanner/Reversal_LIPM_Planner.cpp", "max_stars_repo_name": "stevenjj/PnC", "max_stars_repo_head_hexsha": "e1e417dbd507f174bb2661247cb4360b6ee0ada7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-04T22:36:54.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-04T22:36:54.000Z", "max_issues_repo_path": "PnC/PlannerSet/PIPM_FootPlacementPlanner/Reversal_LIPM_Planner.cpp", "max_issues_repo_name": "stevenjj/PnC", "max_issues_repo_head_hexsha": "e1e417dbd507f174bb2661247cb4360b6ee0ada7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PnC/PlannerSet/PIPM_FootPlacementPlanner/Reversal_LIPM_Planner.cpp", "max_forks_repo_name": "stevenjj/PnC", "max_forks_repo_head_hexsha": "e1e417dbd507f174bb2661247cb4360b6ee0ada7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.706401766, "max_line_length": 87, "alphanum_fraction": 0.5468546638, "num_tokens": 5023, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189121808099, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.49038084474455385}}
{"text": "/// @file\n/// @copyright The code is licensed under the BSD License\n///            <http://opensource.org/licenses/BSD-2-Clause>,\n///            Copyright (c) 2013-2015 Alexandre Hamez.\n/// @author Alexandre Hamez\n\n#include <vector>\n\n#include <boost/range/numeric.hpp>\n\n#include \"mc/classic/reachability_eval.hh\"\n#include \"support/pn/types.hh\"\n\nnamespace pnmc { namespace mc { namespace classic {\n\n/*------------------------------------------------------------------------------------------------*/\n\nusing boost::accumulate;\nusing boost::apply_visitor;\n\nnamespace /* anonymous */ {\n\n/*------------------------------------------------------------------------------------------------*/\n\nstruct integer_eval\n{\n  using result_type = int;\n  const std::vector<pn::valuation_type>& values;\n\n  result_type\n  operator()(const integer_constant& e)\n  const noexcept\n  {\n    return e.value;\n  }\n\n  result_type\n  operator()(const integer_sum& e)\n  const noexcept\n  {\n    return accumulate( e.expressions, 0\n                     , [this](auto v, const auto& sub_e){return apply_visitor(*this, sub_e) + v;});\n  }\n\n  result_type\n  operator()(const integer_product& e)\n  const noexcept\n  {\n    return accumulate( e.expressions, 1\n                     , [this](auto v, const auto& sub_e){return apply_visitor(*this, sub_e) * v;});\n  }\n\n  result_type\n  operator()(const integer_difference& e)\n  const noexcept\n  {\n    return apply_visitor(*this, e.lhs_expression) - apply_visitor(*this, e.rhs_expression);\n  }\n\n  result_type\n  operator()(const integer_division& e)\n  const noexcept\n  {\n    return apply_visitor(*this, e.lhs_expression) / apply_visitor(*this, e.rhs_expression);\n  }\n\n  result_type\n  operator()(const integer_tokens&)\n  const\n  {\n//    return values[e.pos];\n    throw std::runtime_error(__PRETTY_FUNCTION__);\n  }\n};\n\n/*------------------------------------------------------------------------------------------------*/\n\nstruct boolean_eval\n{\n  using result_type = bool;\n  const integer_eval& integer;\n\n  result_type\n  operator()(const invariant&)\n  const\n  {\n    throw std::runtime_error(__PRETTY_FUNCTION__);\n  }\n\n  result_type\n  operator()(const possibility&)\n  const\n  {\n    throw std::runtime_error(__PRETTY_FUNCTION__);\n  }\n\n  result_type\n  operator()(const impossibility&)\n  const\n  {\n    throw std::runtime_error(__PRETTY_FUNCTION__);\n  }\n\n  result_type\n  operator()(const true_&)\n  const\n  {\n    throw std::runtime_error(__PRETTY_FUNCTION__);\n  }\n\n  result_type\n  operator()(const false_&)\n  const\n  {\n    throw std::runtime_error(__PRETTY_FUNCTION__);\n  }\n\n  result_type\n  operator()(const negation& e)\n  const\n  {\n    return not apply_visitor(*this, e.expression);\n  }\n\n  result_type\n  operator()(const conjunction& e)\n  const\n  {\n    for (const auto& sub_e : e.expressions)\n    {\n      if (not apply_visitor(*this, sub_e))\n      {\n        return false;\n      }\n    }\n    return true;\n  }\n\n  result_type\n  operator()(const disjunction& e)\n  const\n  {\n    for (const auto& sub_e : e.expressions)\n    {\n      if (apply_visitor(*this, sub_e))\n      {\n        return true;\n      }\n    }\n    return false;\n  }\n\n  result_type\n  operator()(const exclusive_disjonction& e)\n  const\n  {\n    bool has_true = false;\n    for (const auto& sub_e : e.expressions)\n    {\n      const auto tmp = apply_visitor(*this, sub_e);\n      if      (tmp and not has_true) {has_true = true;}\n      else if (tmp and has_true)     {return false;}\n    }\n    return has_true;\n  }\n\n  result_type\n  operator()(const implication& e)\n  const\n  {\n    return apply_visitor(*this, e.lhs_expression)\n         ? apply_visitor(*this, e.rhs_expression)\n         : true;\n  }\n\n  result_type\n  operator()(const equivalence& e)\n  const\n  {\n    return apply_visitor(*this, e.lhs_expression) == apply_visitor(*this, e.rhs_expression);\n  }\n\n  result_type\n  operator()(const integer_eq& e)\n  const noexcept\n  {\n    return apply_visitor(integer, e.lhs_expression) == apply_visitor(integer, e.rhs_expression);\n  }\n\n  result_type\n  operator()(const integer_ne& e)\n  const noexcept\n  {\n    return apply_visitor(integer, e.lhs_expression) != apply_visitor(integer, e.rhs_expression);\n  }\n\n  result_type\n  operator()(const integer_lt& e)\n  const noexcept\n  {\n    return apply_visitor(integer, e.lhs_expression) < apply_visitor(integer, e.rhs_expression);\n  }\n\n  result_type\n  operator()(const integer_le& e)\n  const noexcept\n  {\n    return apply_visitor(integer, e.lhs_expression) <= apply_visitor(integer, e.rhs_expression);\n  }\n\n  result_type\n  operator()(const integer_gt& e)\n  const noexcept\n  {\n    return apply_visitor(integer, e.lhs_expression) > apply_visitor(integer, e.rhs_expression);\n  }\n\n  result_type\n  operator()(const integer_ge& e)\n  const noexcept\n  {\n    return apply_visitor(integer, e.lhs_expression) >= apply_visitor(integer, e.rhs_expression);\n  }\n};\n\n/*------------------------------------------------------------------------------------------------*/\n\n} // namespace anonymous\n\n/*------------------------------------------------------------------------------------------------*/\n\nint\neval(const integer_ast& a, const SDD&)\n{\n  if (const auto* ptr = boost::get<integer_constant>(&a))\n  {\n    return ptr->value;\n  }\n  std::vector<pn::valuation_type> values;\n  return apply_visitor(integer_eval{values}, a);\n}\n\n/*------------------------------------------------------------------------------------------------*/\n\nbool\neval(const boolean_ast& a, const SDD&)\n{\n  if (boost::get<true_>(&a))\n  {\n    return true;\n  }\n  else if (boost::get<false_>(&a))\n  {\n    return false;\n  }\n  std::vector<pn::valuation_type> values;\n  integer_eval integer{values};\n  return apply_visitor(boolean_eval{integer}, a);\n}\n\n/*------------------------------------------------------------------------------------------------*/\n\n}}} // namespace pnmc::mc::classic\n", "meta": {"hexsha": "a848c6b7ec3f4d446b4b94c84fd4bdad735638b0", "size": 5806, "ext": "cc", "lang": "C++", "max_stars_repo_path": "pnmc/mc/classic/reachability_eval.cc", "max_stars_repo_name": "ahamez/pnmc", "max_stars_repo_head_hexsha": "cee5f2e01edc2130278ebfc13f0f859230d65680", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2015-02-05T20:56:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-29T01:20:24.000Z", "max_issues_repo_path": "pnmc/mc/classic/reachability_eval.cc", "max_issues_repo_name": "ahamez/pnmc", "max_issues_repo_head_hexsha": "cee5f2e01edc2130278ebfc13f0f859230d65680", "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": "pnmc/mc/classic/reachability_eval.cc", "max_forks_repo_name": "ahamez/pnmc", "max_forks_repo_head_hexsha": "cee5f2e01edc2130278ebfc13f0f859230d65680", "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": 21.9924242424, "max_line_length": 100, "alphanum_fraction": 0.5859455735, "num_tokens": 1338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189121808099, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.49038084474455385}}
{"text": "#define BOOST_TEST_MODULE Gpufit\n\n#include \"Gpufit/gpufit.h\"\n\n#include <boost/test/included/unit_test.hpp>\n\n#include <array>\n#include <cmath>\n\ntemplate<std::size_t n_points, std::size_t n_parameters>\nvoid generate_gauss_1d(\n    std::array< REAL, n_points >& values,\n    std::array< REAL, n_points >& x_data,\n    std::array< REAL, n_parameters > const & parameters )\n{\n    REAL const a = parameters[ 0 ];\n    REAL const x0 = parameters[ 1 ];\n    REAL const s = parameters[ 2 ];\n    REAL const b = parameters[ 3 ];\n\n    for ( int point_index = 0; point_index < n_points; point_index++ )\n    {\n        REAL const x = x_data[point_index];\n        REAL const argx = ( ( x - x0 )*( x - x0 ) ) / ( 2 * s * s );\n        REAL const ex = exp( -argx );\n        values[ point_index ] = a * ex + b;\n    }\n}\n\nvoid gauss_fit_1d()\n{\n    /*\n    Performs a single fit using the GAUSS_1D model.\n    - Doesn't use user_info or weights.\n    - No noise is added.\n    - Checks fitted parameters equalling the true parameters.\n    */\n\n    std::size_t const n_fits{ 1 };\n    std::size_t const n_points{ 5 };\n    std::size_t const n_parameters{ 4 };\n\n    std::array< REAL, n_parameters > const true_parameters{ { 4, 2, .5f, 1 } };\n\n    std::array< REAL, n_points > x_data{ { 0, 1, 2, 3, 4} };\n    std::array< REAL, n_points > data{};\n    generate_gauss_1d(data, x_data, true_parameters);\n\n    std::array< REAL, n_parameters > initial_parameters{ { 2, 1.5f, 0.3f, 0 } };\n\n    REAL tolerance{ 0.001f };\n\n    int max_n_iterations{ 10 };\n\n    std::array< int, n_parameters > parameters_to_fit{ { 1, 1, 1, 1 } };\n\n    std::array< REAL, n_parameters > output_parameters;\n    int output_states;\n    REAL output_chi_square;\n    int output_n_iterations;\n\n    int const status\n        = gpufit\n        (\n            n_fits,\n            n_points,\n            data.data(),\n            0,\n            GAUSS_1D,\n            initial_parameters.data(),\n            tolerance,\n            max_n_iterations,\n            parameters_to_fit.data(),\n            LSE,\n            0,\n            0,\n            output_parameters.data(),\n            &output_states,\n            &output_chi_square,\n            &output_n_iterations\n        );\n\n    BOOST_CHECK(status == 0);\n    BOOST_CHECK(output_states == 0);\n    BOOST_CHECK(output_chi_square < 1e-6f);\n    BOOST_CHECK(output_n_iterations <= max_n_iterations);\n\n    BOOST_CHECK(std::abs(output_parameters[0] - true_parameters[0]) < 1e-6f);\n    BOOST_CHECK(std::abs(output_parameters[1] - true_parameters[1]) < 1e-6f);\n    BOOST_CHECK(std::abs(output_parameters[2] - true_parameters[2]) < 1e-6f);\n    BOOST_CHECK(std::abs(output_parameters[3] - true_parameters[3]) < 1e-6f);\n}\n\nvoid gauss_fit_1d_custom_x()\n{\n    /*\n    Performs two fits using the GAUSS_1D model.\n    - Doesn't use or weights.\n    - Uses user_info for custom x coordinate values, unique for each fit.\n    - No noise is added.\n    - Checks fitted parameters equalling the true parameters.\n    */\n\n    std::size_t const n_fits{ 2 };\n    std::size_t const n_points{ 5 };\n    std::size_t const n_parameters{ 4 };\n\n    std::array< REAL, n_parameters > const true_parameters_1{ { 4, 0, .25f, 1 } };\n    std::array< REAL, n_parameters > const true_parameters_2{ { 6, .5f, .15f, 2 } };\n\n    std::array< REAL, n_parameters > initial_parameters_1{ { 2, .25f, .15f, 0 } };\n    std::array< REAL, n_parameters > initial_parameters_2{ { 8, .75f, .2f, 3 } };\n\n    std::array< REAL, n_points > x_data_1 = { { -1, -.5f, 0, .5f, 1 } };\n    std::array< REAL, n_points > x_data_2 = { { 0, .25f, .5f, .75f, 1 } };\n\n    std::array< REAL, n_points > fit_data_1{};\n    std::array< REAL, n_points > fit_data_2{};\n\n    generate_gauss_1d(fit_data_1, x_data_1, true_parameters_1);\n    generate_gauss_1d(fit_data_2, x_data_2, true_parameters_2);\n    \n    std::array< REAL, n_points * n_fits> data{};\n    std::array< REAL, n_points * n_fits> x_data{};\n    \n    for (int i = 0; i < n_points; i++)\n    {\n        data[i] = fit_data_1[i];\n        data[n_points + i] = fit_data_2[i];\n\n        x_data[i] = x_data_1[i];\n        x_data[n_points + i] = x_data_2[i];\n    }\n\n    std::array< REAL, n_parameters * n_fits> initial_parameters{};\n\n    for (int i = 0; i < n_parameters; i++)\n    {\n        initial_parameters[i] = initial_parameters_1[i];\n        initial_parameters[n_parameters + i] = initial_parameters_2[i];\n    }\n\n    REAL tolerance{ 1e-6f };\n\n    int max_n_iterations{ 20 };\n\n    std::array< int, n_parameters > parameters_to_fit{ { 1, 1, 1, 1 } };\n\n    std::array< REAL, n_parameters * n_fits > output_parameters;\n    std::array< int, n_fits > output_states;\n    std::array< REAL, n_fits > output_chi_square;\n    std::array< int, n_fits > output_n_iterations;\n\n    int const status\n        = gpufit\n        (\n            n_fits,\n            n_points,\n            data.data(),\n            0,\n            GAUSS_1D,\n            initial_parameters.data(),\n            tolerance,\n            max_n_iterations,\n            parameters_to_fit.data(),\n            LSE,\n            n_points * n_fits * sizeof(REAL),\n            reinterpret_cast< char * >(x_data.data()),\n            output_parameters.data(),\n            output_states.data(),\n            output_chi_square.data(),\n            output_n_iterations.data()\n        );\n    // check gpufit status\n    BOOST_CHECK(status == 0);\n    \n    // check first fit\n    BOOST_CHECK(output_states[0] == 0);\n    BOOST_CHECK(output_chi_square[0] < 1e-6f);\n    BOOST_CHECK(output_n_iterations[0] <= max_n_iterations);\n\n    BOOST_CHECK(std::abs(output_parameters[0] - true_parameters_1[0]) < 1e-6f);\n    BOOST_CHECK(std::abs(output_parameters[1] - true_parameters_1[1]) < 1e-6f);\n    BOOST_CHECK(std::abs(output_parameters[2] - true_parameters_1[2]) < 1e-6f);\n    BOOST_CHECK(std::abs(output_parameters[3] - true_parameters_1[3]) < 1e-6f);\n\n    // check second fit\n    BOOST_CHECK(output_states[1] == 0);\n    BOOST_CHECK(output_chi_square[1] < 1e-6f);\n    BOOST_CHECK(output_n_iterations[1] <= max_n_iterations);\n\n    BOOST_CHECK(std::abs(output_parameters[4] - true_parameters_2[0]) < 1e-6f);\n    BOOST_CHECK(std::abs(output_parameters[5] - true_parameters_2[1]) < 1e-6f);\n    BOOST_CHECK(std::abs(output_parameters[6] - true_parameters_2[2]) < 1e-6f);\n    BOOST_CHECK(std::abs(output_parameters[7] - true_parameters_2[3]) < 1e-6f);\n}\n\nBOOST_AUTO_TEST_CASE( Gauss_Fit_1D )\n{\n    // single 1d gauss fit\n    gauss_fit_1d();\n\n    // two gauss fits with custom x coordinate values\n    gauss_fit_1d_custom_x();\n}\n", "meta": {"hexsha": "f7b40faeb419b286769eec39622a9b1cac460944", "size": 6485, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Gpufit/tests/Gauss_Fit_1D.cpp", "max_stars_repo_name": "sriharijayaram5/Gpufit", "max_stars_repo_head_hexsha": "468ffbce6e6ff98632951af5e027c88c332bc1e0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 228.0, "max_stars_repo_stars_event_min_datetime": "2017-08-10T17:46:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T07:06:06.000Z", "max_issues_repo_path": "Gpufit/tests/Gauss_Fit_1D.cpp", "max_issues_repo_name": "sriharijayaram5/Gpufit", "max_issues_repo_head_hexsha": "468ffbce6e6ff98632951af5e027c88c332bc1e0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 90.0, "max_issues_repo_issues_event_min_datetime": "2017-08-14T11:41:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T12:22:59.000Z", "max_forks_repo_path": "Gpufit/tests/Gauss_Fit_1D.cpp", "max_forks_repo_name": "sriharijayaram5/Gpufit", "max_forks_repo_head_hexsha": "468ffbce6e6ff98632951af5e027c88c332bc1e0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 76.0, "max_forks_repo_forks_event_min_datetime": "2017-08-16T15:20:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T06:28:38.000Z", "avg_line_length": 31.4805825243, "max_line_length": 84, "alphanum_fraction": 0.6151117965, "num_tokens": 1907, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891130942474, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.49038083954732387}}
{"text": "// This file is part of Eigen, a lightweight C++ template library\n// for linear algebra.\n//\n// Copyright (C) 2014 Benoit Steiner <benoit.steiner.goog@gmail.com>\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 \"main.h\"\n\n#include <Eigen/CXX11/Tensor>\n\nusing Eigen::Tensor;\nusing Eigen::TensorMap;\n\n\n\nstatic void test_additions()\n{\n  Tensor<std::complex<float>, 1> data1(3);\n  Tensor<std::complex<float>, 1> data2(3);\n  for (int i = 0; i < 3; ++i) {\n    data1(i) = std::complex<float>(i, -i);\n    data2(i) = std::complex<float>(i, 7 * i);\n  }\n\n  Tensor<std::complex<float>, 1> sum = data1 + data2;\n  for (int i = 0; i < 3; ++i) {\n    VERIFY_IS_EQUAL(sum(i),  std::complex<float>(2*i, 6*i));\n  }\n}\n\n\nstatic void test_abs()\n{\n  Tensor<std::complex<float>, 1> data1(3);\n  Tensor<std::complex<double>, 1> data2(3);\n  data1.setRandom();\n  data2.setRandom();\n\n  Tensor<float, 1> abs1 = data1.abs();\n  Tensor<double, 1> abs2 = data2.abs();\n  for (int i = 0; i < 3; ++i) {\n    VERIFY_IS_APPROX(abs1(i), std::abs(data1(i)));\n    VERIFY_IS_APPROX(abs2(i), std::abs(data2(i)));\n  }\n}\n\n\nstatic void test_conjugate()\n{\n  Tensor<std::complex<float>, 1> data1(3);\n  Tensor<std::complex<double>, 1> data2(3);\n  Tensor<int, 1> data3(3);\n  data1.setRandom();\n  data2.setRandom();\n  data3.setRandom();\n\n  Tensor<std::complex<float>, 1> conj1 = data1.conjugate();\n  Tensor<std::complex<double>, 1> conj2 = data2.conjugate();\n  Tensor<int, 1> conj3 = data3.conjugate();\n  for (int i = 0; i < 3; ++i) {\n    VERIFY_IS_APPROX(conj1(i), std::conj(data1(i)));\n    VERIFY_IS_APPROX(conj2(i), std::conj(data2(i)));\n    VERIFY_IS_APPROX(conj3(i), data3(i));\n  }\n}\n\nstatic void test_contractions()\n{\n  Tensor<std::complex<float>, 4> t_left(30, 50, 8, 31);\n  Tensor<std::complex<float>, 5> t_right(8, 31, 7, 20, 10);\n  Tensor<std::complex<float>, 5> t_result(30, 50, 7, 20, 10);\n\n  t_left.setRandom();\n  t_right.setRandom();\n\n  typedef Map<Matrix<std::complex<float>, Dynamic, Dynamic>> MapXcf;\n  MapXcf m_left(t_left.data(), 1500, 248);\n  MapXcf m_right(t_right.data(), 248, 1400);\n  Matrix<std::complex<float>, Dynamic, Dynamic> m_result(1500, 1400);\n\n  // This contraction should be equivalent to a regular matrix multiplication\n  typedef Tensor<float, 1>::DimensionPair DimPair;\n  Eigen::array<DimPair, 2> dims;\n  dims[0] = DimPair(2, 0);\n  dims[1] = DimPair(3, 1);\n  t_result = t_left.contract(t_right, dims);\n  m_result = m_left * m_right;\n  for (int i = 0; i < t_result.dimensions().TotalSize(); i++) {\n    VERIFY_IS_APPROX(t_result.data()[i], m_result.data()[i]);\n  }\n}\n\n\nEIGEN_DECLARE_TEST(cxx11_tensor_of_complex)\n{\n  CALL_SUBTEST(test_additions());\n  CALL_SUBTEST(test_abs());\n  CALL_SUBTEST(test_conjugate());\n  CALL_SUBTEST(test_contractions());\n}\n", "meta": {"hexsha": "99e18076ac935efb6d66533f6b1e36f95ba6b396", "size": 2893, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "third_party/eigen3/include/unsupported/test/cxx11_tensor_of_complex.cpp", "max_stars_repo_name": "Shamraev/motion_imitation", "max_stars_repo_head_hexsha": "9b9166436e4996e2a03b36d19f4f5422cde9c21e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2111.0, "max_stars_repo_stars_event_min_datetime": "2019-01-29T07:01:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T06:48:14.000Z", "max_issues_repo_path": "third_party/eigen3/include/unsupported/test/cxx11_tensor_of_complex.cpp", "max_issues_repo_name": "Shamraev/motion_imitation", "max_issues_repo_head_hexsha": "9b9166436e4996e2a03b36d19f4f5422cde9c21e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 843.0, "max_issues_repo_issues_event_min_datetime": "2019-01-25T01:06:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T11:15:53.000Z", "max_forks_repo_path": "third_party/eigen3/include/unsupported/test/cxx11_tensor_of_complex.cpp", "max_forks_repo_name": "Shamraev/motion_imitation", "max_forks_repo_head_hexsha": "9b9166436e4996e2a03b36d19f4f5422cde9c21e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 421.0, "max_forks_repo_forks_event_min_datetime": "2019-02-12T07:59:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T05:22:01.000Z", "avg_line_length": 27.8173076923, "max_line_length": 77, "alphanum_fraction": 0.6571033529, "num_tokens": 940, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432182679957, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.49019261543507964}}
{"text": "#pragma once\n\n#include <vector>\n\n#include <boost/variant/recursive_variant.hpp>\n\nstruct Constant\n{\n    std::wstring name;\n};\n\nbool operator==(const Constant& c1, const Constant& c2);\n\nstruct Value\n{\n    double value;\n};\n\nbool operator==(const Value& v1, const Value& v2);\n\nstruct Variable\n{\n    std::wstring name;\n};\n\nbool operator==(const Variable& v1, const Variable& v2);\n\n// struct Monomial\n// {\n//     double multiplier;\n//     Variable variable;\n//     int exponant = 1;\n// };\n\nstruct Sum;\nstruct Product;\nstruct Cos;\nstruct Sin;\n\nusing Expression\n    = boost::variant<Constant, Value, Variable, boost::recursive_wrapper<Sum>, boost::recursive_wrapper<Product>,\n                     boost::recursive_wrapper<Cos>, boost::recursive_wrapper<Sin>>;\n\nstruct Sum\n{\n    std::vector<Expression> operands;\n};\n\nbool operator==(const Sum& s1, const Sum& s2);\n\nstruct Product\n{\n    std::vector<Expression> operands;\n};\n\nbool operator==(const Product& s1, const Product& s2);\n\nstruct Cos\n{\n    Expression expr;\n};\n\nbool operator==(const Cos& c1, const Cos& c2);\n\nstruct Sin\n{\n    Expression expr;\n};\n\nbool operator==(const Sin& s1, const Sin& s2);", "meta": {"hexsha": "e3cf953a0fc5ea6af9a8e37ba45208f1640b9369", "size": 1141, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/expression.hpp", "max_stars_repo_name": "julienlopez/DifferentialGeometry2", "max_stars_repo_head_hexsha": "f720ac4f2966a347ab69eb4df1350fb271b63ed6", "max_stars_repo_licenses": ["MIT"], "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/expression.hpp", "max_issues_repo_name": "julienlopez/DifferentialGeometry2", "max_issues_repo_head_hexsha": "f720ac4f2966a347ab69eb4df1350fb271b63ed6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-01-31T14:34:39.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-31T14:34:39.000Z", "max_forks_repo_path": "lib/expression.hpp", "max_forks_repo_name": "julienlopez/DifferentialGeometry2", "max_forks_repo_head_hexsha": "f720ac4f2966a347ab69eb4df1350fb271b63ed6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.3, "max_line_length": 113, "alphanum_fraction": 0.6730937774, "num_tokens": 282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975978, "lm_q2_score": 0.679178692681616, "lm_q1q2_score": 0.4901926073050404}}
{"text": "// Adapted from: http://people.sc.fsu.edu/~jburkardt/m_src/shallow_water_2d/\n// Saved images may be converted into an animated gif with:\n// convert   -delay 20   -loop 0   swater*.png   swater.gif\n#include <math.h>\n#include <string.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <bp_util.h>\n\n#include <boost/multi_array.hpp>\n\nint main (int argc, char **argv)\n{\n    bp_util_type bp = bp_util_create(argc, argv, 3);\n    if (bp.args.has_error) {\n        return 1;\n    }\n    const int n         = bp.args.sizes[0];\n    const int other_n   = bp.args.sizes[1];\n    const int T         = bp.args.sizes[2];\n\n    if (n != other_n) {\n        fprintf(stderr, \"Implementation only supports quadratic grid.\\n\");\n        exit(0);\n    }\n\n    const double g   = 9.8;       // gravitational constant\n    const double dt  = 0.02;      // hardwired timestep\n    const double dx  = 1.0;\n    const double dy  = 1.0;\n    const int droploc = n/4;\n\n    typedef boost::multi_array<double, 2> array_type;\n\n    array_type H(boost::extents[n+2][n+2]);\n    array_type U(boost::extents[n+2][n+2]);\n    array_type V(boost::extents[n+2][n+2]);\n\n    array_type Hx(boost::extents[n+1][n+1]);\n    array_type Ux(boost::extents[n+1][n+1]);\n    array_type Vx(boost::extents[n+1][n+1]);\n    array_type Hy(boost::extents[n+1][n+1]);\n    array_type Uy(boost::extents[n+1][n+1]);\n    array_type Vy(boost::extents[n+1][n+1]);\n\n\n    for(int i=0; i<n+2; i++)\n        for(int j=0; j<n+2; j++)\n        {\n          H[i][j]=0.1;\n          U[i][j]=0.1;\n          V[i][j]=0.1;\n        }\n\n\n    for(int i=0; i<n+1; i++)\n        for(int j=0; j<n+1; j++)\n        {\n          Hx[i][j]=0.1;\n          Ux[i][j]=0.1;\n          Vx[i][j]=0.1;\n\n          Hy[i][j]=0.1;\n          Uy[i][j]=0.1;\n          Vy[i][j]=0.1;\n        }\n\n    H[droploc][droploc] += 5.0;\n\n    bp.timer_start();\n\n    for(int iter=0; iter < T; iter++)\n    {\n        // Reflecting boundary conditions\n        for(int i=0; i<n+2; i++)\n        {\n            H[i][0] = H[i][1]   ; U[i][0] = U[i][1]     ; V[i][0] = -V[i][1];\n            H[i][n+1] = H[i][n] ; U[i][n+1] = U[i][n]   ; V[i][n+1] = -V[i][n];\n            H[0][i] = H[1][i]   ; U[0][i] = -U[1][i]    ; V[0][i] = V[1][i];\n            H[n+1][i] = H[n][i] ; U[n+1][i] = -U[n][i]  ; V[n+1][i] = V[n][i];\n        }\n        //\n        // First half step\n        //\n        for(int i=0; i<n+1; i++)\n        {\n            for(int j=0; j<n; j++)\n            {\n\n                // height\n                Hx[i][j] = (H[i+1][j+1]+H[i][j+1])/2 - dt/(2*dx)*(U[i+1][j+1]-U[i][j+1]);\n\n                // x momentum\n                Ux[i][j] = (U[i+1][j+1]+U[i][j+1])/2 -          \\\n                dt/(2*dx)*((pow(U[i+1][j+1],2)/H[i+1][j+1] +\t\\\n                          g/2*pow(H[i+1][j+1],2)) -\t\t\\\n                         (pow(U[i][j+1],2)/H[i][j+1] +\t        \\\n                          g/2*pow(H[i][j+1],2)));\n\n                // y momentum\n                Vx[i][j] = (V[i+1][j+1]+V[i][j+1])/2 -          \\\n                      dt/(2*dx)*((U[i+1][j+1] *                 \\\n                                  V[i+1][j+1]/H[i+1][j+1]) -    \\\n                                 (U[i][j+1] *                   \\\n                                  V[i][j+1]/H[i][j+1]));\n            }\n        }\n\n        for(int i=0; i<n; i++)\n        {\n            for(int j=0; j<n+1; j++)\n            {\n                //height\n                Hy[i][j] = (H[i+1][j+1]+H[i+1][j])/2 - dt/(2*dy)*(V[i+1][j+1]-V[i+1][j]);\n\n                //x momentum\n                Uy[i][j] = (U[i+1][j+1]+U[i+1][j])/2 -\t   \\\n                dt/(2*dy)*((V[i+1][j+1] *                  \\\n                           U[i+1][j+1]/H[i+1][j+1]) -\t   \\\n                                (V[i+1][j] *               \\\n                                 U[i+1][j]/H[i+1][j]));\n\n                //y momentum\n                Vy[i][j] = (V[i+1][j+1]+V[i+1][j])/2 -\t\\\n                dt/(2*dy)*((pow(V[i+1][j+1],2)/H[i+1][j+1] +\t\\\n                           g/2*pow(H[i+1][j+1],2)) -\t\\\n                          (pow(V[i+1][j],2)/H[i+1][j] +\t\\\n                           g/2*pow(H[i+1][j],2)));\n            }\n        }\n        //\n        // Second half step\n        //\n\n        for(int i=1; i<n+1; i++)\n        {\n            for(int j=1; j<n+1; j++)\n            {\n                //height\n                H[i][j] -= (dt/dx)*(Ux[i][j-1]-Ux[i-1][j-1]) - (dt/dy)*(Vy[i-1][j]-Vy[i-1][j-1]);\n\n                // x momentum\n                U[i][j] -= (dt/dx)*((pow(Ux[i][j-1],2)/Hx[i][j-1] + g/2*pow(Hx[i][j-1],2)) -        \\\n                                    (pow(Ux[i-1][j-1],2)/Hx[i-1][j-1] + g/2*pow(Hx[i-1][j-1],2))) - \\\n                           (dt/dy)*((Vy[i-1][j] * Uy[i-1][j]/Hy[i-1][j]) -\n                                    (Vy[i-1][j-1] * Uy[i-1][j-1]/Hy[i-1][j-1]));\n\n                // y momentum    - score\n                V[i][j] -= (dt/dx)*((Ux[i][j-1] * Vx[i][j-1]/Hx[i][j-1]) -                         \\\n                                    (Ux[i-1][j-1]*Vx[i-1][j-1]/Hx[i-1][j-1])) -                    \\\n                           (dt/dy)*((pow(Vy[i-1][j],2)/Hy[i-1][j] + g/2*pow(Hy[i-1][j],2)) -       \\\n                                    (pow(Vy[i-1][j-1],2)/Hy[i-1][j-1] + g/2*pow(Hy[i-1][j-1],2)));\n\n            }\n        }\n    }\n\n    // res = numpy.add.reduce(numpy.add.reduce(H / n))\n    double res = 0.0;\n    for(int i=0;i<n+2;i++)\n        for(int j=0;j<n+2;j++)\n            res+=H[i][j]/n;\n\n    bp.timer_stop();\n    bp.print(\"shallow_water(cpp11_boost)\");\n}\n", "meta": {"hexsha": "9478ea7696ab70d7fe8bf5f5c3ec6678fa4771a5", "size": 5482, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "benchpress/benchmarks/shallow_water/cpp11_boost/src/shallow_water.cpp", "max_stars_repo_name": "bh107/benchpress", "max_stars_repo_head_hexsha": "e1dcda446a986d4d828b14d807e37e10cf4a046b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-03-31T15:39:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T21:30:49.000Z", "max_issues_repo_path": "benchpress/benchmarks/shallow_water/cpp11_boost/src/shallow_water.cpp", "max_issues_repo_name": "bh107/benchpress", "max_issues_repo_head_hexsha": "e1dcda446a986d4d828b14d807e37e10cf4a046b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2015-04-13T12:03:56.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-28T13:31:11.000Z", "max_forks_repo_path": "benchpress/benchmarks/shallow_water/cpp11_boost/src/shallow_water.cpp", "max_forks_repo_name": "bh107/benchpress", "max_forks_repo_head_hexsha": "e1dcda446a986d4d828b14d807e37e10cf4a046b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-06-28T08:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-20T17:30:25.000Z", "avg_line_length": 32.8263473054, "max_line_length": 101, "alphanum_fraction": 0.3513316308, "num_tokens": 1962, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563335, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.49017367498098624}}
{"text": "//  (C) Copyright Eric Niebler 2005.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n// Test case for pot_quantile.hpp\n\n#define BOOST_NUMERIC_FUNCTIONAL_STD_COMPLEX_SUPPORT\n#define BOOST_NUMERIC_FUNCTIONAL_STD_VALARRAY_SUPPORT\n#define BOOST_NUMERIC_FUNCTIONAL_STD_VECTOR_SUPPORT\n\n#include <boost/random.hpp>\n#include <boost/test/unit_test.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics.hpp>\n#include <boost/accumulators/statistics/peaks_over_threshold.hpp>\n\nusing namespace boost;\nusing namespace unit_test;\nusing namespace boost::accumulators;\n\n///////////////////////////////////////////////////////////////////////////////\n// test_stat\n//\nvoid test_stat()\n{\n    // tolerance in %\n    double epsilon = 1.;\n\n    // two random number generators\n    boost::lagged_fibonacci607 rng;\n    boost::normal_distribution<> mean_sigma(0,1);\n    boost::exponential_distribution<> lambda(1);\n    boost::variate_generator<boost::lagged_fibonacci607&, boost::normal_distribution<> > normal(rng, mean_sigma);\n    boost::variate_generator<boost::lagged_fibonacci607&, boost::exponential_distribution<> > exponential(rng, lambda);\n\n    accumulator_set<double, stats<tag::pot_quantile<right>(with_threshold_value)> > acc1(\n        pot_threshold_value = 3.\n    );\n    accumulator_set<double, stats<tag::pot_quantile<right>(with_threshold_probability)> > acc2(\n        right_tail_cache_size = 2000\n      , pot_threshold_probability = 0.99\n    );\n    accumulator_set<double, stats<tag::pot_quantile<left>(with_threshold_value)> > acc3(\n        pot_threshold_value = -3.\n    );\n    accumulator_set<double, stats<tag::pot_quantile<left>(with_threshold_probability)> > acc4(\n        left_tail_cache_size = 2000\n      , pot_threshold_probability = 0.01\n    );\n\n    accumulator_set<double, stats<tag::pot_quantile<right>(with_threshold_value)> > acc5(\n        pot_threshold_value = 5.\n    );\n    accumulator_set<double, stats<tag::pot_quantile<right>(with_threshold_probability)> > acc6(\n        right_tail_cache_size = 2000\n      , pot_threshold_probability = 0.995\n    );\n\n    for (std::size_t i = 0; i < 100000; ++i)\n    {\n        double sample = normal();\n        acc1(sample);\n        acc2(sample);\n        acc3(sample);\n        acc4(sample);\n    }\n\n    for (std::size_t i = 0; i < 100000; ++i)\n    {\n        double sample = exponential();\n        acc5(sample);\n        acc6(sample);\n    }\n\n    BOOST_CHECK_CLOSE( quantile(acc1, quantile_probability = 0.999), 3.090232, 3*epsilon );\n    BOOST_CHECK_CLOSE( quantile(acc2, quantile_probability = 0.999), 3.090232, 2*epsilon );\n    BOOST_CHECK_CLOSE( quantile(acc3, quantile_probability = 0.001), -3.090232, 2*epsilon );\n    BOOST_CHECK_CLOSE( quantile(acc4, quantile_probability = 0.001), -3.090232, 2*epsilon );\n\n    BOOST_CHECK_CLOSE( quantile(acc5, quantile_probability = 0.999), 6.908, 3*epsilon );\n    BOOST_CHECK_CLOSE( quantile(acc6, quantile_probability = 0.999), 6.908, 3*epsilon );\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// init_unit_test_suite\n//\ntest_suite* init_unit_test_suite( int argc, char* argv[] )\n{\n    test_suite *test = BOOST_TEST_SUITE(\"pot_quantile test\");\n\n    test->add(BOOST_TEST_CASE(&test_stat));\n\n    return test;\n}\n\n", "meta": {"hexsha": "4457071aca65ab715eba38e335a61fdf8362aa53", "size": 3459, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/accumulators/test/pot_quantile.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "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": "boost/libs/accumulators/test/pot_quantile.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "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": "boost/libs/accumulators/test/pot_quantile.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "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": 35.2959183673, "max_line_length": 119, "alphanum_fraction": 0.6802544088, "num_tokens": 857, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.6261241772283035, "lm_q1q2_score": 0.49004390068187237}}
{"text": "#include <CGAL/Cartesian.h>\n#include <CGAL/point_generators_2.h>\n#include <CGAL/Periodic_4_hyperbolic_Delaunay_triangulation_2.h>\n#include <CGAL/Periodic_4_hyperbolic_Delaunay_triangulation_traits_2.h>\n#include <CGAL/Hyperbolic_octagon_translation.h>\n#include <CGAL/determinant.h>\n\n#include <boost/tuple/tuple.hpp>\n#include <boost/random/linear_congruential.hpp>\n#include <boost/random/uniform_smallint.hpp>\n#include <boost/random/variate_generator.hpp>\n\n#include <iostream>\n\ntypedef CGAL::Periodic_4_hyperbolic_Delaunay_triangulation_traits_2<>               Traits;\ntypedef CGAL::Periodic_4_hyperbolic_Delaunay_triangulation_2<Traits>                Triangulation;\ntypedef Triangulation::Face_iterator                                                Face_iterator;\ntypedef Triangulation::Vertex_handle                                                Vertex_handle;\ntypedef Triangulation::Point                                                        Point;\ntypedef Traits::Side_of_original_octagon                                            Side_of_original_octagon;\ntypedef CGAL::Cartesian<double>::Point_2                                            Point_double;\ntypedef CGAL::Creator_uniform_2<double, Point_double >                              Creator;\n\nint main(int argc, char** argv)\n{\n  int iter;\n  if(argc < 2)\n  {\n    std::cout << \"usage: \" << argv[0] << \" [number_of_iterations]\" << std::endl;\n    std::cout << \"defaulting to 10 iterations...\" << std::endl;\n    iter = 10;\n  } else {\n    iter = atoi(argv[1]);\n  }\n\n  Side_of_original_octagon pred;\n\n  int N = 500;\n  int min = 2*N;\n  int max = -1;\n  double mean = 0.0;\n  for(int j=0; j<iter; ++j)\n  {\n    std::vector<Point_double> v;\n    CGAL::Random_points_in_disc_2<Point_double, Creator> g(0.85);\n\n    Triangulation tr;\n    assert(tr.is_valid(true));\n\n    int cnt = 0;\n    int idx = 0;\n    do\n    {\n      Point_double pt = *(++g);\n      if(pred(pt) != CGAL::ON_UNBOUNDED_SIDE)\n      {\n        tr.insert(Point(pt.x(), pt.y()));\n        cnt++;\n      }\n    }\n    while(tr.number_of_dummy_points() > 0 && idx < N-1);\n\n    if(tr.number_of_dummy_points() > 0)\n    {\n      std::cout << \"!!! FAILED to remove all dummy points after the insertion of \" << N << \" random points!\" << std::endl;\n      continue;\n    }\n\n    assert(tr.is_valid());\n    std::cout << cnt << std::endl;\n\n    if(cnt > max)\n      max = cnt;\n\n    if(cnt < min)\n      min = cnt;\n\n    mean += cnt;\n  }\n  mean /= double(iter);\n\n  std::cout << \"Finished \" << iter << \" iterations!\" << std::endl;\n  std::cout << \"Minimum number of points inserted: \" << min << std::endl;\n  std::cout << \"Maximum number of points inserted: \" << max << std::endl;\n  std::cout << \"Average number of points inserted: \" << mean << std::endl;\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "9cf4020c3625f03bde2b07ef06fa98c91fa7bfe3", "size": 2765, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Periodic_4_hyperbolic_triangulation_2/benchmark/Periodic_4_hyperbolic_triangulation_2/bench_p4ht2_remove_dummy_points.cpp", "max_stars_repo_name": "ffteja/cgal", "max_stars_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 3227.0, "max_stars_repo_stars_event_min_datetime": "2015-03-05T00:19:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:20:35.000Z", "max_issues_repo_path": "Periodic_4_hyperbolic_triangulation_2/benchmark/Periodic_4_hyperbolic_triangulation_2/bench_p4ht2_remove_dummy_points.cpp", "max_issues_repo_name": "ffteja/cgal", "max_issues_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 5574.0, "max_issues_repo_issues_event_min_datetime": "2015-03-05T00:01:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:08:11.000Z", "max_forks_repo_path": "Periodic_4_hyperbolic_triangulation_2/benchmark/Periodic_4_hyperbolic_triangulation_2/bench_p4ht2_remove_dummy_points.cpp", "max_forks_repo_name": "ffteja/cgal", "max_forks_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1274.0, "max_forks_repo_forks_event_min_datetime": "2015-03-05T00:01:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:47:56.000Z", "avg_line_length": 31.0674157303, "max_line_length": 122, "alphanum_fraction": 0.5952983725, "num_tokens": 716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.4900438897613735}}
{"text": "/* boost random/gamma_distribution.hpp header file\r\n *\r\n * Copyright Jens Maurer 2002\r\n * Permission to use, copy, modify, sell, and distribute this software\r\n * is hereby granted without fee provided that the above copyright notice\r\n * appears in all copies and that both that copyright notice and this\r\n * permission notice appear in supporting documentation,\r\n *\r\n * Jens Maurer makes no representations about the suitability of this\r\n * software for any purpose. It is provided \"as is\" without express or\r\n * implied warranty.\r\n *\r\n * See http://www.boost.org for most recent version including documentation.\r\n *\r\n * $Id: gamma_distribution.hpp,v 1.7 2002/12/22 22:03:10 jmaurer Exp $\r\n *\r\n */\r\n\r\n#ifndef BOOST_RANDOM_GAMMA_DISTRIBUTION_HPP\r\n#define BOOST_RANDOM_GAMMA_DISTRIBUTION_HPP\r\n\r\n#include <cmath>\r\n#include <cassert>\r\n#include <boost/random/uniform_01.hpp>\r\n\r\nnamespace boost {\r\n\r\n// Knuth\r\n// deterministic polar method, uses trigonometric functions\r\ntemplate<class UniformRandomNumberGenerator, class RealType = double,\r\n         class Adaptor = uniform_01<UniformRandomNumberGenerator, RealType> >\r\nclass gamma_distribution\r\n{\r\npublic:\r\n  typedef Adaptor adaptor_type;\r\n  typedef UniformRandomNumberGenerator base_type;\r\n  typedef RealType result_type;\r\n\r\n  explicit gamma_distribution(base_type & rng,\r\n                              const result_type& alpha = result_type(1))\r\n    : _rng(rng), _exp(rng, result_type(1)), _alpha(alpha)\r\n  {\r\n    assert(alpha > result_type(0));\r\n    init();\r\n  }\r\n\r\n  // compiler-generated copy ctor and assignment operator are fine\r\n\r\n  adaptor_type& adaptor() { return _rng; }\r\n  base_type& base() const { return _rng.base(); }\r\n  RealType alpha() const { return _alpha; }\r\n\r\n  void reset() { _rng.reset(); _exp.reset(); }\r\n\r\n  result_type operator()()\r\n  {\r\n#ifndef BOOST_NO_STDC_NAMESPACE\r\n    // allow for Koenig lookup\r\n    using std::tan; using std::sqrt; using std::exp; using std::log;\r\n    using std::pow;\r\n#endif\r\n    if(_alpha == result_type(1)) {\r\n      return _exp();\r\n    } else if(_alpha > result_type(1)) {\r\n      // Can we have a boost::mathconst please?\r\n      const result_type pi = result_type(3.14159265358979323846);\r\n      for(;;) {\r\n        result_type y = tan(pi * _rng());\r\n        result_type x = sqrt(result_type(2)*_alpha-result_type(1))*y\r\n          + _alpha-result_type(1);\r\n        if(x <= result_type(0))\r\n          continue;\r\n        if(_rng() >\r\n           (result_type(1)+y*y) * exp((_alpha-result_type(1))\r\n                                        *log(x/(_alpha-result_type(1)))\r\n                                        - sqrt(result_type(2)*_alpha\r\n                                               -result_type(1))*y))\r\n          continue;\r\n        return x;\r\n      }\r\n    } else /* alpha < 1.0 */ {\r\n      for(;;) {\r\n        result_type u = _rng();\r\n        result_type y = _exp();\r\n        result_type x, q;\r\n        if(u < _p) {\r\n          x = exp(-y/_alpha);\r\n          q = _p*exp(-x);\r\n        } else {\r\n          x = result_type(1)+y;\r\n          q = _p + (result_type(1)-_p) * pow(x, _alpha-result_type(1));\r\n        }\r\n        if(u >= q)\r\n          continue;\r\n        return x;\r\n      }\r\n    }\r\n  }\r\n#ifndef BOOST_NO_OPERATORS_IN_NAMESPACE\r\n  friend bool operator==(const gamma_distribution& x, \r\n                         const gamma_distribution& y)\r\n  {\r\n    return x._alpha == y._alpha && x._rng == y._rng;\r\n  }\r\n\r\n#ifndef BOOST_NO_MEMBER_TEMPLATE_FRIENDS\r\n  template<class CharT, class Traits>\r\n  friend std::basic_ostream<CharT,Traits>&\r\n  operator<<(std::basic_ostream<CharT,Traits>& os, const gamma_distribution& gd)\r\n  {\r\n    os << gd._alpha;\r\n    return os;\r\n  }\r\n\r\n  template<class CharT, class Traits>\r\n  friend std::basic_istream<CharT,Traits>&\r\n  operator>>(std::basic_istream<CharT,Traits>& is, gamma_distribution& gd)\r\n  {\r\n    is >> std::ws >> gd._alpha;\r\n    gd.init();\r\n    return is;\r\n  }\r\n#endif\r\n\r\n#else\r\n  // Use a member function\r\n  bool operator==(const gamma_distribution& rhs) const\r\n  {\r\n    return _alpha == rhs._alpha && _rng == rhs._rng;\r\n  }\r\n#endif\r\n\r\nprivate:\r\n  void init()\r\n  {\r\n#ifndef BOOST_NO_STDC_NAMESPACE\r\n    // allow for Koenig lookup\r\n    using std::exp;\r\n#endif\r\n    _p = exp(result_type(1)) / (_alpha + exp(result_type(1)));\r\n  }\r\n\r\n  adaptor_type _rng;\r\n  exponential_distribution<base_type, RealType, Adaptor> _exp;\r\n  result_type _alpha;\r\n  // some data precomputed from the parameters\r\n  result_type _p;\r\n};\r\n\r\n} // namespace boost\r\n\r\n#endif // BOOST_RANDOM_GAMMA_DISTRIBUTION_HPP\r\n", "meta": {"hexsha": "ce402c3f178a2957e4d347352a95a1c47e1f15f8", "size": 4525, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sdk/boost_1_30_0/boost/random/gamma_distribution.hpp", "max_stars_repo_name": "acidicMercury8/xray-1.0", "max_stars_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2021-05-04T06:40:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T20:24:28.000Z", "max_issues_repo_path": "sdk/boost_1_30_0/boost/random/gamma_distribution.hpp", "max_issues_repo_name": "acidicMercury8/xray-1.0", "max_issues_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_issues_repo_licenses": ["Linux-OpenIB"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sdk/boost_1_30_0/boost/random/gamma_distribution.hpp", "max_forks_repo_name": "acidicMercury8/xray-1.0", "max_forks_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-05-17T10:01:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-11T20:17:27.000Z", "avg_line_length": 29.5751633987, "max_line_length": 81, "alphanum_fraction": 0.6172375691, "num_tokens": 1104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.4900438897613735}}
{"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_EXPM1_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_EXPM1_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n    @ingroup group-exponential\n    This function object returns the exponential of its argument minus one:\\f$e^{x}-1\\f$\n\n    @par Header <boost/simd/function/expm1.hpp>\n\n    @par Notes\n\n    - result is accurate even for @c x of small modulus\n\n    @par Decorators\n\n     - std_ for floating entries calls @c std::expm1\n\n    @see exp\n\n\n    @par Example:\n\n      @snippet expm1.cpp expm1\n\n    @par Possible output:\n\n      @snippet expm1.txt expm1\n\n  **/\n  IEEEValue expm1(IEEEValue const& x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/expm1.hpp>\n#include <boost/simd/function/simd/expm1.hpp>\n\n#endif\n", "meta": {"hexsha": "906788a550605d3a20529f72dd779e4dbc10acd0", "size": 1159, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/expm1.hpp", "max_stars_repo_name": "SylvainCorlay/pythran", "max_stars_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-02-25T22:23:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T15:13:12.000Z", "max_issues_repo_path": "third_party/boost/simd/function/expm1.hpp", "max_issues_repo_name": "SylvainCorlay/pythran", "max_issues_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/function/expm1.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 22.2884615385, "max_line_length": 100, "alphanum_fraction": 0.5849870578, "num_tokens": 265, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.4900438897613735}}
{"text": "#define BOOST_TEST_MODULE TestrocFFT\n#include \"libraries/rocfft/rocfft_helper.hpp\"\n\n#include <hip/hip_runtime_api.h>\n#include <hip/hip_vector_types.h>\n#include <rocfft.h>\n\n#include <boost/test/included/unit_test.hpp> // Single-header usage variant\n\n#include <cstdint>\n\n#include <iostream>\n#include <vector>\n#include <complex>\n\nBOOST_AUTO_TEST_CASE( FFT1DSmall, * boost::unit_test::tolerance(0.0001f) )\n{\n  // rocFFT gpu compute\n        // ========================================\n\n        CHECK_HIP(rocfft_setup());\n\n        std::size_t N = 2 << 10; //should be small enough to not need a work_buffer\n        std::size_t Nbytes = N * sizeof(float2);\n\n        // Create HIP device buffer\n        float2 *x;\n        CHECK_HIP(hipMalloc(&x, Nbytes));\n        // Initialize data\n        std::vector<float2> cx(N);\n        for (std::size_t i = 0; i < N; i++)\n        {\n                cx[i].x = 1;\n                cx[i].y = -1;\n        }\n\n        //  Copy data to device\n        CHECK_HIP(hipMemcpy(x, cx.data(), Nbytes, hipMemcpyHostToDevice));\n        // Create fwd rocFFT fwd\n        rocfft_plan fwd = nullptr;\n        std::size_t length = N;\n        CHECK_HIP(\n          rocfft_plan_create(&fwd,\n                             rocfft_placement_inplace,\n                             rocfft_transform_type_complex_forward,\n                             rocfft_precision_single,\n                             1, &length, 1, nullptr));\n\n        // Create bwd rocFFT bwd\n        rocfft_plan bwd = nullptr;\n        CHECK_HIP(\n          rocfft_plan_create(&bwd,\n                             rocfft_placement_inplace,\n                             rocfft_transform_type_complex_inverse,\n                             rocfft_precision_single,\n                             1, &length, 1, nullptr));\n\n\n        // Execute fwd\n        CHECK_HIP(rocfft_execute(fwd, (void**) &x, nullptr, nullptr));\n\n        // Wait for execution to finish\n        CHECK_HIP(hipDeviceSynchronize());\n\n        // Destroy fwd\n        CHECK_HIP(rocfft_plan_destroy(fwd));\n\n        // Execute bwd\n        CHECK_HIP(rocfft_execute(bwd, (void**) &x, nullptr, nullptr));\n\n        // Wait for execution to finish\n        CHECK_HIP(hipDeviceSynchronize());\n\n        // Destroy bwd\n        CHECK_HIP(rocfft_plan_destroy(bwd));\n\n\n        // Copy result back to host\n        std::vector<float2> y(N);\n        CHECK_HIP(hipMemcpy(y.data(), x, Nbytes, hipMemcpyDeviceToHost));\n\n        // Print results\n        for (std::size_t i = 0; i < N; i++)\n        {\n          y[i].x *= 1.f/N;\n          y[i].y *= 1.f/N;\n\n          BOOST_TEST( cx[i].x == y[i].x );\n          BOOST_TEST( cx[i].y == y[i].y );\n        }\n\n        // Free device buffer\n        CHECK_HIP(hipFree(x));\n\n        CHECK_HIP(rocfft_cleanup());\n\n\n}\n\n\nBOOST_AUTO_TEST_CASE( FFT1D, * boost::unit_test::tolerance(0.0001f) )\n{\n        // rocFFT gpu compute\n        // ========================================\n\n        CHECK_HIP(rocfft_setup());\n\n        std::size_t N = 128 << 10; //needs a work_buffer\n        std::size_t Nbytes = N * sizeof(float2);\n\n        // Create HIP device buffer\n        float2 *x;\n        CHECK_HIP(hipMalloc(&x, Nbytes));\n        // Initialize data\n        std::vector<float2> cx(N);\n        for (std::size_t i = 0; i < N; i++)\n        {\n                cx[i].x = 1;\n                cx[i].y = -1;\n        }\n\n        //  Copy data to device\n        CHECK_HIP(hipMemcpy(x, cx.data(), Nbytes, hipMemcpyHostToDevice));\n        // Create fwd rocFFT fwd\n        rocfft_plan fwd = nullptr;\n        std::size_t length = N;\n        CHECK_HIP(\n          rocfft_plan_create(&fwd,\n                             rocfft_placement_inplace,\n                             rocfft_transform_type_complex_forward,\n                             rocfft_precision_single,\n                             1, &length, 1, nullptr));\n\n        // Create bwd rocFFT bwd\n        rocfft_plan bwd = nullptr;\n        CHECK_HIP(\n          rocfft_plan_create(&bwd,\n                             rocfft_placement_inplace,\n                             rocfft_transform_type_complex_inverse,\n                             rocfft_precision_single,\n                             1, &length, 1, nullptr));\n\n        // Setup work buffer\n        void *workBuffer = nullptr;\n        size_t workBufferSize_fwd = 0;\n        CHECK_HIP(rocfft_plan_get_work_buffer_size(fwd, &workBufferSize_fwd));\n        size_t workBufferSize_bwd = 0;\n        CHECK_HIP(rocfft_plan_get_work_buffer_size(bwd, &workBufferSize_bwd));\n\n        BOOST_REQUIRE_EQUAL(workBufferSize_bwd,workBufferSize_fwd);\n\n        // Setup exec info to pass work buffer to the library\n        rocfft_execution_info info = nullptr;\n        CHECK_HIP(rocfft_execution_info_create(&info));\n\n        if(workBufferSize_fwd > 0)\n        {\n                CHECK_HIP(hipMalloc(&workBuffer, workBufferSize_fwd));\n                CHECK_HIP(rocfft_execution_info_set_work_buffer(info, workBuffer, workBufferSize_fwd));\n        }\n\n        // Execute fwd\n        CHECK_HIP(rocfft_execute(fwd, (void**) &x, nullptr, info));\n\n        // Wait for execution to finish\n        CHECK_HIP(hipDeviceSynchronize());\n\n        // Destroy fwd\n        CHECK_HIP(rocfft_plan_destroy(fwd));\n\n        // Execute bwd\n        CHECK_HIP(rocfft_execute(bwd, (void**) &x, nullptr, info));\n\n        // Wait for execution to finish\n        CHECK_HIP(hipDeviceSynchronize());\n\n        // Destroy bwd\n        CHECK_HIP(rocfft_plan_destroy(bwd));\n\n        if(workBuffer)\n  \t     \tCHECK_HIP(hipFree(workBuffer));\n\n        CHECK_HIP(rocfft_execution_info_destroy(info));\n\n        // Copy result back to host\n        std::vector<float2> y(N);\n        CHECK_HIP(hipMemcpy(y.data(), x, Nbytes, hipMemcpyDeviceToHost));\n\n        // Print results\n        for (std::size_t i = 0; i < N; i++)\n        {\n                y[i].x *= 1.f/N;\n                y[i].y *= 1.f/N;\n\n                BOOST_TEST( cx[i].x == y[i].x );\n                BOOST_TEST( cx[i].y == y[i].y );\n        }\n\n        // Free device buffer\n        CHECK_HIP(hipFree(x));\n\n        CHECK_HIP(rocfft_cleanup());\n\n\n}\n\nBOOST_AUTO_TEST_CASE( FFT1DSmall_stdcomplex, * boost::unit_test::tolerance(0.0001f) )\n{\n  // rocFFT gpu compute\n        // ========================================\n\n        CHECK_HIP(rocfft_setup());\n\n        std::size_t N = 2 << 10; //should be small enough to not need a work_buffer\n        std::size_t Nbytes = N * sizeof(std::complex<float>);\n\n        // Create HIP device buffer\n        std::complex<float> *x;\n        CHECK_HIP(hipMalloc(&x, Nbytes));\n        // Initialize data\n        std::vector<std::complex<float>> cx(N);\n        for (std::size_t i = 0; i < N; i++)\n        {\n                cx[i].real( 1 );\n                cx[i].imag( -1);\n        }\n\n        //  Copy data to device\n        CHECK_HIP(hipMemcpy(x, cx.data(), Nbytes, hipMemcpyHostToDevice));\n        // Create fwd rocFFT fwd\n        rocfft_plan fwd = nullptr;\n        std::size_t length = N;\n        CHECK_HIP(\n          rocfft_plan_create(&fwd,\n                             rocfft_placement_inplace,\n                             rocfft_transform_type_complex_forward,\n                             rocfft_precision_single,\n                             1, &length, 1, nullptr));\n\n        // Create bwd rocFFT bwd\n        rocfft_plan bwd = nullptr;\n        CHECK_HIP(\n          rocfft_plan_create(&bwd,\n                             rocfft_placement_inplace,\n                             rocfft_transform_type_complex_inverse,\n                             rocfft_precision_single,\n                             1, &length, 1, nullptr));\n\n\n        // Execute fwd\n        CHECK_HIP(rocfft_execute(fwd, (void**) &x, nullptr, nullptr));\n\n        // Wait for execution to finish\n        CHECK_HIP(hipDeviceSynchronize());\n\n        // Destroy fwd\n        CHECK_HIP(rocfft_plan_destroy(fwd));\n\n        // Execute bwd\n        CHECK_HIP(rocfft_execute(bwd, (void**) &x, nullptr, nullptr));\n\n        // Wait for execution to finish\n        CHECK_HIP(hipDeviceSynchronize());\n\n        // Destroy bwd\n        CHECK_HIP(rocfft_plan_destroy(bwd));\n\n\n        // Copy result back to host\n        std::vector<std::complex<float>> y(N);\n        CHECK_HIP(hipMemcpy(y.data(), x, Nbytes, hipMemcpyDeviceToHost));\n\n        // Print results\n        for (std::size_t i = 0; i < N; i++)\n        {\n          y[i].real ( y[i].real() * 1.f/N);\n          y[i].imag ( y[i].imag() * 1.f/N);\n\n          BOOST_TEST( cx[i].real() == y[i].real() );\n          BOOST_TEST( cx[i].imag() == y[i].imag() );\n        }\n\n        // Free device buffer\n        CHECK_HIP(hipFree(x));\n\n        CHECK_HIP(rocfft_cleanup());\n\n\n}\n\nBOOST_AUTO_TEST_CASE( failing_float_265841_Inplace_Real, * boost::unit_test::tolerance(0.0001f) )\n{\n        // rocFFT gpu compute\n        // ========================================\n\n        CHECK_HIP(rocfft_setup());\n\n        std::size_t N = 265841;\n        std::size_t Nbytes = 2*(N/2 + 1) * sizeof(float);\n\n        BOOST_REQUIRE_GT(Nbytes, N*sizeof(float));\n        // Create HIP device buffer\n        float *x;\n        CHECK_HIP(hipMalloc(&x, Nbytes));\n        // Initialize data\n        std::vector<float> h_x(N,1.);\n\n        //  Copy data to device\n        CHECK_HIP(hipMemcpy(x, h_x.data(), Nbytes, hipMemcpyHostToDevice));\n        // Create fwd rocFFT fwd\n        rocfft_plan fwd = nullptr;\n        std::size_t length = N;\n        CHECK_HIP(\n          rocfft_plan_create(&fwd,\n                             rocfft_placement_inplace,\n                             rocfft_transform_type_real_forward,\n                             rocfft_precision_single,\n                             1, &length, 1, nullptr));\n\n        // Create bwd rocFFT bwd\n        rocfft_plan bwd = nullptr;\n        CHECK_HIP(\n          rocfft_plan_create(&bwd,\n                             rocfft_placement_inplace,\n                             rocfft_transform_type_real_inverse,\n                             rocfft_precision_single,\n                             1, &length, 1, nullptr));\n\n        // Setup work buffer\n        void *workBuffer = nullptr;\n        size_t workBufferSize_fwd = 0;\n        CHECK_HIP(rocfft_plan_get_work_buffer_size(fwd, &workBufferSize_fwd));\n        size_t workBufferSize_bwd = 0;\n        CHECK_HIP(rocfft_plan_get_work_buffer_size(bwd, &workBufferSize_bwd));\n\n        BOOST_REQUIRE_EQUAL(workBufferSize_bwd,workBufferSize_fwd);\n\n        // Setup exec info to pass work buffer to the library\n        rocfft_execution_info info = nullptr;\n        CHECK_HIP(rocfft_execution_info_create(&info));\n\n        if(workBufferSize_fwd > 0)\n        {\n                CHECK_HIP(hipMalloc(&workBuffer, workBufferSize_fwd));\n                CHECK_HIP(rocfft_execution_info_set_work_buffer(info, workBuffer, workBufferSize_fwd));\n        }\n\n        // Execute fwd\n        CHECK_HIP(rocfft_execute(fwd, (void**) &x, nullptr, info));\n\n        // Wait for execution to finish\n        CHECK_HIP(hipDeviceSynchronize());\n\n        // Destroy fwd\n        CHECK_HIP(rocfft_plan_destroy(fwd));\n\n        // Execute bwd\n        CHECK_HIP(rocfft_execute(bwd, (void**) &x, nullptr, info));\n\n        // Wait for execution to finish\n        CHECK_HIP(hipDeviceSynchronize());\n\n        // Destroy bwd\n        CHECK_HIP(rocfft_plan_destroy(bwd));\n\n        if(workBuffer)\n  \t     \tCHECK_HIP(hipFree(workBuffer));\n\n        CHECK_HIP(rocfft_execution_info_destroy(info));\n\n        // Copy result back to host\n        std::vector<float> h_y(N);\n        CHECK_HIP(hipMemcpy(h_y.data(), x, Nbytes, hipMemcpyDeviceToHost));\n\n        // Print results\n        for (std::size_t i = 0; i < N; i++)\n        {\n                h_y[i]*= 1.f/N;\n\n\n                BOOST_TEST( h_x[i] == h_y[i] );\n\n        }\n\n        // Free device buffer\n        CHECK_HIP(hipFree(x));\n\n        CHECK_HIP(rocfft_cleanup());\n\n\n}\n", "meta": {"hexsha": "80468f13467d1acbaa11150056ac8c275e201e7d", "size": 11803, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_rocfft.cpp", "max_stars_repo_name": "paklui/gearshifft", "max_stars_repo_head_hexsha": "2ec19e82ce0b065356132a58a00a3562ef131c55", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2017-03-06T08:23:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-13T07:59:28.000Z", "max_issues_repo_path": "test/test_rocfft.cpp", "max_issues_repo_name": "paklui/gearshifft", "max_issues_repo_head_hexsha": "2ec19e82ce0b065356132a58a00a3562ef131c55", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 130.0, "max_issues_repo_issues_event_min_datetime": "2016-06-07T14:38:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-12T06:08:29.000Z", "max_forks_repo_path": "test/test_rocfft.cpp", "max_forks_repo_name": "paklui/gearshifft", "max_forks_repo_head_hexsha": "2ec19e82ce0b065356132a58a00a3562ef131c55", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2016-06-07T12:48:18.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-06T16:43:03.000Z", "avg_line_length": 30.1096938776, "max_line_length": 103, "alphanum_fraction": 0.5407947132, "num_tokens": 2847, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.49004388341318517}}
{"text": "#define CATCH_CONFIG_MAIN\n#include <Eigen/Dense>\n#include <catch.hpp>\n#include <random>\n\n#include \"EDP/ConstructSparseMat.hpp\"\n#include \"EDP/LocalHamiltonian.hpp\"\n\n#include \"yavque/Operators/SumLocalHamEvol.hpp\"\n#include \"yavque/utils.hpp\"\n\n#include \"common.hpp\"\n\nTEST_CASE(\"test sum of local hamiltonian\", \"[sum-local]\")\n{\n\tusing namespace yavque;\n\tusing namespace Eigen;\n\n\tconstexpr unsigned int N = 8;\n\tconstexpr cx_double I(0., 1.);\n\n\tstd::random_device rd;\n\tstd::default_random_engine re{rd()};\n\tstd::normal_distribution<> nd;\n\n\tSparseMatrix<cx_double> m = pauli_x().cast<cx_double>();\n\tSumLocalHam ham(N, m);\n\tSumLocalHamEvol ham_evol(ham);\n\tauto var = ham_evol.get_variable();\n\n\tfor(uint32_t k = 0; k < 100; ++k) // instance for loop\n\t{\n\t\tEigen::VectorXcd ini = Eigen::VectorXcd::Random(1 << N);\n\t\tini.normalize();\n\n\t\tdouble t = nd(re);\n\t\tvar = t;\n\t\tVectorXcd out_test = ham_evol * ini;\n\n\t\tMatrixXcd mevol = (cos(t) * MatrixXcd::Identity(2, 2) - I * sin(t) * m);\n\t\tVectorXcd out = apply_kronecker(N, mevol, ini);\n\n\t\tREQUIRE((out - out_test).norm() < 1e-6);\n\t}\n\n\tham_evol.dagger_in_place();\n\tfor(uint32_t k = 0; k < 100; ++k) // instance for loop\n\t{\n\t\tEigen::VectorXcd ini = Eigen::VectorXcd::Random(1 << N);\n\t\tini.normalize();\n\n\t\tdouble t = nd(re);\n\t\tvar = t;\n\t\tVectorXcd out_test = ham_evol * ini;\n\n\t\tMatrixXcd mevol = (cos(t) * MatrixXcd::Identity(2, 2) + I * sin(t) * m);\n\t\tVectorXcd out = apply_kronecker(N, mevol, ini);\n\n\t\tREQUIRE((out - out_test).norm() < 1e-6);\n\t}\n}\n", "meta": {"hexsha": "76ca9a4438130650a09c2ba68852db1c690ac18f", "size": 1481, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tests/TestSumLocalHamEvol.cpp", "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": "Tests/TestSumLocalHamEvol.cpp", "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": "Tests/TestSumLocalHamEvol.cpp", "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": 23.8870967742, "max_line_length": 74, "alphanum_fraction": 0.6718433491, "num_tokens": 480, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289835, "lm_q2_score": 0.6442251133170357, "lm_q1q2_score": 0.4900302599066378}}
{"text": "#pragma once\n\n#include <vector>\n#include <tuple>\n#include <array>\n#include <Eigen/Dense>\n#include <iod/symbols.hh>\n#include <vpp/core/image2d.hh>\n#include <vpp/core/vector.hh>\n#include <vpp/core/make_array.hh>\n\nnamespace vpp\n{\n  \n  template <typename T, typename U>\n  void euclide_distance_transform(image2d<T>& input, image2d<U>& sedt)\n  {\n    image2d<vshort2> R(input.domain(), _border = 1);\n    fill_with_border(R, vshort2{0,0});\n\n    auto forward4 = [] () { return make_array(vint2{-1, -1}, vint2{-1, 0}, vint2{-1, 1}, vint2{0, -1}); };\n    auto backward4 = [] () { return make_array(vint2{1, 1}, vint2{1, 0}, vint2{1, -1}, vint2{0, 1}); };\n\n    fill_with_border(sedt, input.nrows() + input.ncols());\n    pixel_wise(input, sedt) | [] (auto& i, auto& s) { if (i == 0) s = 0; };\n\n    auto run = [&] (auto neighborhood, auto col_direction,\n                    auto row_direction1, auto row_direction2, auto spn) {\n\n      row_wise(sedt, R)(col_direction, _no_threads) | [&] (auto sedt_row, auto R_row)\n      {\n        // Forward pass\n        pixel_wise(relative_access(sedt_row), relative_access(R_row))(row_direction1, _no_threads)\n        | [&] (auto sedt_nbh, auto R_nbh)\n        {\n          vint2 min_rel_coord = neighborhood()[0];\n          int min_dist = INT_MAX;\n          for (vint2 nc : neighborhood())\n          {\n            int d = sedt_nbh(nc) + 2 * (std::abs(R_nbh(nc)[0] * nc[0]) +\n                                        std::abs(R_nbh(nc)[1] * nc[1]))\n              + nc.cwiseAbs().sum();\n            \n            if (d < min_dist)\n            {\n              min_dist = d;\n              min_rel_coord = nc;\n            }\n          }\n\n          if (min_dist < sedt_nbh(0, 0))\n          {\n            R_nbh(0, 0) = (R_nbh(min_rel_coord) + min_rel_coord.cast<short>()).template cast<short>();\n            sedt_nbh(0, 0) = min_dist;\n          }\n        };\n\n        // Backward pass\n        pixel_wise(relative_access(sedt_row), relative_access(R_row))\n        (row_direction2, _no_threads) | [&] (auto sedt_nbh, auto R_nbh)\n        {\n          int d = sedt_nbh(spn()) + 2 * std::abs(R_nbh(spn())[1]) + 1;\n          if (d < sedt_nbh(0, 0))\n          {\n            sedt_nbh(0, 0) = d;\n            R_nbh(0, 0) = (R_nbh(spn()) + spn().template cast<short>()).template cast<short>();\n          }\n        };\n\n      };\n\n    };\n\n    run(forward4, _top_to_bottom, _left_to_right, _right_to_left, [] () { return vint2{0, 1}; });\n    run(backward4, _bottom_to_top, _right_to_left, _left_to_right, [] () { return vint2{0, -1}; });\n\n    // pixel_wise(sedt) | [] (auto& p) { p/=100; };\n  }\n\n  template <unsigned N, typename F>\n  void loop_unroll(F f, std::enable_if_t<N == 0>* = 0) { f(N); }\n\n  template <unsigned N, typename F>\n  void loop_unroll(F f, std::enable_if_t<N != 0>* = 0) { f(N); loop_unroll<N-1>(f); }\n  \n  template <typename T, typename U, typename F, typename FW, typename B, typename BW, int WS = 3>\n  void generic_incremental_distance_transform(image2d<T>& input, image2d<U>& sedt,\n                                              F forward,\n                                              FW forward_ws,\n                                              B backward,\n                                              BW backward_ws,\n                                              std::integral_constant<int, WS> = std::integral_constant<int, WS>())\n  {\n    fill_with_border(sedt, input.nrows() + input.ncols());\n    pixel_wise(input, sedt) | [] (auto& i, auto& s) { if (i == 0) s = 0; };\n    \n    auto run = [&] (auto neighb, auto ws,\n                    auto col_direction,\n                    auto row_direction) {\n      pixel_wise(relative_access(sedt))(col_direction, row_direction, _no_threads) | [neighb, ws] (auto sn) {\n        int min_dist = sn(0,0);\n\n        auto nbh = neighb();\n        \n        // if (neighb().size() < 6)\n        auto it = [&] (int i) {\n          min_dist = std::min(min_dist, ws()[i] + sn(neighb()[i]));\n        };\n\n        typedef decltype(nbh) NBH;\n        loop_unroll<std::tuple_size<NBH>::value - 1>(it);\n        sn(0,0) = min_dist;\n      };\n    };\n\n    run(forward, forward_ws, _top_to_bottom, _left_to_right);\n    run(backward, backward_ws, _bottom_to_top, _right_to_left);\n  }\n  \n  const auto d4_distance_transform = [] (auto& a, auto& b) {\n    generic_incremental_distance_transform(a, b,\n                                 [] () { return make_array(vint2{-1, 0}, vint2{0, -1}); },\n                                 [] () { return make_array(1, 1); },\n                                 [] () { return make_array(vint2{1, 0}, vint2{0, 1}); },\n                                 [] () { return make_array(1, 1); });\n  };\n\n  const auto d8_distance_transform = [] (auto& a, auto& b) {\n    generic_incremental_distance_transform(a, b,\n                                 [] () { return make_array(vint2{-1, -1}, vint2{-1, 0}, vint2{-1, 1}, vint2{0, -1}); },\n                                 [] () { return make_array(1,1,1,1); },\n                                 [] () { return make_array(vint2{1, 1}, vint2{1, 0}, vint2{1, -1}, vint2{0, 1}); },\n                                           [] () { return make_array(1, 1, 1, 1); });\n  };\n\n  const auto d3_4_distance_transform = [] (auto& a, auto& b) {\n    generic_incremental_distance_transform(a, b,\n                                           [] () { return make_array(vint2{-1, -1}, vint2{-1, 0}, vint2{-1, 1}, vint2{0, -1}); },\n                                           [] () { return make_array(4,3,4,3); },\n                                           [] () { return make_array(vint2{1, 1}, vint2{1, 0}, vint2{1, -1}, vint2{0, 1}); },\n                                           [] () { return make_array(4, 3, 4, 3); }, std::integral_constant<int, 5>());\n  };\n\n  const auto d5_7_11_distance_transform = [] (auto& a, auto& b) {\n    generic_incremental_distance_transform(a, b,\n    \n                                           [] () { return make_array(vint2{-2, -1}, vint2{-2, 1}, vint2{-1, -2}, vint2{-1, -1}, vint2{-1, 0}, vint2{-1, 1}, vint2{-1, 2}, vint2{0, -1}); },\n                                           [] () { return make_array(11,11,11,7,5,7,11,5); },\n                                           [] () { return make_array(vint2{0, 1}, vint2{1, -2}, vint2{1, -1}, vint2{1, 0}, vint2{1, 1}, vint2{1, 2}, vint2{2, -1}, vint2{2, 1}); },\n                                           [] () { return make_array(5,11,7,5,7,11,11,11); },\n                                           std::integral_constant<int, 5>());\n  };\n  \n}\n", "meta": {"hexsha": "51b3180fcabb82612ec8edecde45dc48f670fc39", "size": 6505, "ext": "hh", "lang": "C++", "max_stars_repo_path": "vpp/algorithms/distance_transforms/distance_transforms.hh", "max_stars_repo_name": "jjzhang166/videopp", "max_stars_repo_head_hexsha": "f1421b16b8ffcefb3d1697460940d868e31ba79d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 624.0, "max_stars_repo_stars_event_min_datetime": "2015-01-05T16:40:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T03:09:43.000Z", "max_issues_repo_path": "vpp/algorithms/distance_transforms/distance_transforms.hh", "max_issues_repo_name": "jjzhang166/videopp", "max_issues_repo_head_hexsha": "f1421b16b8ffcefb3d1697460940d868e31ba79d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2015-01-22T20:50:13.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-15T10:41:34.000Z", "max_forks_repo_path": "vpp/algorithms/distance_transforms/distance_transforms.hh", "max_forks_repo_name": "jjzhang166/videopp", "max_forks_repo_head_hexsha": "f1421b16b8ffcefb3d1697460940d868e31ba79d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 113.0, "max_forks_repo_forks_event_min_datetime": "2015-01-19T11:58:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T05:15:20.000Z", "avg_line_length": 41.9677419355, "max_line_length": 187, "alphanum_fraction": 0.4839354343, "num_tokens": 1929, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289835, "lm_q2_score": 0.6442250996557035, "lm_q1q2_score": 0.4900302495151364}}
{"text": "/*=============================================================================\n    Copyright (c) 2001-2010 Joel de Guzman\n\n    Distributed under the Boost Software License, Version 1.0. (See accompanying\n    file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n=============================================================================*/\n#include <boost/config/warning_disable.hpp>\n#include <input/parse_sexpr_impl.hpp>\n#include <input/sexpr.hpp>\n#include <input/parse_sexpr_impl.hpp>\n#include <scheme/compiler.hpp>\n#include <utree/io.hpp>\n\n///////////////////////////////////////////////////////////////////////////////\n//  Main program\n///////////////////////////////////////////////////////////////////////////////\nint main()\n{\n    using scheme::interpreter;\n    using scheme::function;\n    using scheme::utree;\n\n    utree src =\n        \"(define (factorial n) \"\n            \"(if (<= n 0) 1 (* n (factorial (- n 1)))))\";\n\n    interpreter program(src);\n    function factorial = program[\"factorial\"];\n    std::cout << factorial(10) << std::endl;\n\n    return 0;\n}\n\n\n", "meta": {"hexsha": "a87b97429c0886147e2f2c99c7684b3942440175", "size": 1086, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/spirit/example/scheme/example/scheme/factorial2.cpp", "max_stars_repo_name": "bittorrent/boost_1_44_0", "max_stars_repo_head_hexsha": "81d5bca204ceb8448867e46cd96c1c8697599066", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-06-25T23:20:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-14T19:38:34.000Z", "max_issues_repo_path": "libs/spirit/example/scheme/example/scheme/factorial2.cpp", "max_issues_repo_name": "bittorrent/boost_1_44_0", "max_issues_repo_head_hexsha": "81d5bca204ceb8448867e46cd96c1c8697599066", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/spirit/example/scheme/example/scheme/factorial2.cpp", "max_forks_repo_name": "bittorrent/boost_1_44_0", "max_forks_repo_head_hexsha": "81d5bca204ceb8448867e46cd96c1c8697599066", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-07-26T08:07:09.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-25T23:20:21.000Z", "avg_line_length": 31.0285714286, "max_line_length": 80, "alphanum_fraction": 0.4686924494, "num_tokens": 213, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.4900302477199527}}
{"text": "//\n// Created by song on 1/26/18.\n//\n\n#include <opencv2/opencv.hpp>\n#include <string>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\nusing namespace std;\nusing namespace cv;\n\n// this program shows how to use optical flow\n\nstring left_file = \"./left.png\";  // first image\nstring right_file = \"./right.png\";  // second image\nstring disparity_file = \"./disparity.png\" ;\n\ndouble fx = 718.856, fy = 718.856, cx = 607.1928, cy = 185.2157;\ndouble baseline = 0.573;\n\n// TODO implement this funciton\n/**\n * single level optical flow\n * @param [in] left_img the first image\n * @param [in] right_img the second image\n * @param [in] kp1 keypoints in left_img\n * @param [in|out] kp2 keypoints in right_img, if empty, use initial guess in kp1\n * @param [out] success true if a keypoint is tracked successfully\n * @param [in] inverse use inverse formulation?\n */\nvoid OpticalFlowSingleLevel(\n        const Mat &left_img,\n        const Mat &right_img,\n        const vector<KeyPoint> &kp1,\n        vector<KeyPoint> &kp2,\n        vector<bool> &success,\n        bool inverse = false\n);\n\n// TODO implement this funciton\n/**\n * multi level optical flow, scale of pyramid is set to 2 by default\n * the image pyramid will be create inside the function\n * @param [in] left_img the first pyramid\n * @param [in] right_img the second pyramid\n * @param [in] kp1 keypoints in left_img\n * @param [out] kp2 keypoints in right_img\n * @param [out] success true if a keypoint is tracked successfully\n * @param [in] inverse set true to enable inverse formulation\n */\nvoid OpticalFlowMultiLevel(\n        const Mat &left_img,\n        const Mat &right_img,\n        const vector<KeyPoint> &kp1,\n        vector<KeyPoint> &kp2,\n        vector<bool> &success,\n        bool inverse = false\n);\n\n/**\n * get a gray scale value from reference image (bi-linear interpolated)\n * @param img\n * @param x\n * @param y\n * @return\n */\ninline float GetPixelValue(const cv::Mat &img, float x, float y) {\n    uchar *data = &img.data[int(y) * img.step + int(x)];\n    float xx = x - floor(x);\n    float yy = y - floor(y);\n    return float(\n            (1 - xx) * (1 - yy) * data[0] +\n            xx * (1 - yy) * data[1] +\n            (1 - xx) * yy * data[img.step] +\n            xx * yy * data[img.step + 1]\n    );\n}\n\n\nint main(int argc, char **argv) {\n\n    // images, note they are CV_8UC1, not CV_8UC3\n    Mat left_img = imread(left_file, 0);\n    Mat right_img = imread(right_file, 0);\n    Mat disparity_img = imread(disparity_file, 0);\n\n    // key points, using GFTT here.\n    vector<KeyPoint> kp1;\n    Ptr<GFTTDetector> detector = GFTTDetector::create(500, 0.01, 20); // maximum 500 keypoints\n    detector->detect(left_img, kp1);\n\n\n    // then test multi-level LK\n    vector<KeyPoint> kp2;\n    vector<bool> success;\n    //TODO\n    OpticalFlowMultiLevel(left_img, right_img, kp1, kp2, success);\n\n    Mat left_img_show = left_img;\n    cv::cvtColor(left_img, left_img_show, CV_GRAY2BGR);\n    for (int i = 0; i < kp1.size(); i++) {\n\n        cv::circle(left_img_show, kp1[i].pt, 2, cv::Scalar(0, 250, 0), 2);\n\n\n    }\n    // plot the differences of those functions\n    Mat right_img_show;\n    cv::cvtColor(right_img, right_img_show, CV_GRAY2BGR);\n    for (int i = 0; i < kp2.size(); i++) {\n        if (success[i]) {\n            if(kp1[i].pt == kp2[i].pt) cout<<\"===\"<<endl;\n            cv::circle(right_img_show, kp2[i].pt, 2, cv::Scalar(0, 250, 0), 2);\n            cv::line(right_img_show, kp1[i].pt, kp2[i].pt, cv::Scalar(0, 250, 0));\n        }\n    }\n\n\n\n    Mat match_img;\n    vector<cv::DMatch> matches;\n    for (int k =0; k <kp1.size();k++)\n    {\n        if(success[k])\n        {\n            cv::DMatch m;\n            m.queryIdx=k;\n            m.trainIdx=k;\n            double disparity_ref = double(disparity_img.at<uchar>(kp1[k].pt.y,kp1[k].pt.x ));\n            m.distance= float(abs(fx*baseline/(kp2[k].pt.x - kp1[k].pt.x) - fx*baseline /disparity_ref) );\n            matches.push_back(m);\n\n        }\n    }\n\n\n    // plot the matches\n    cv::imshow(\"right_img_show\", right_img_show);\n    cv::imwrite(\"right_img_show.png\", right_img_show);\n\n    cv::drawMatches(left_img, kp1, right_img, kp2, matches, match_img);\n    cv::imshow(\"matches\", match_img);\n    cv::imwrite(\"matches.png\", match_img);\n\n    cv::waitKey(0);\n\n    double error = 0;\n    int count = 0 ;\n    for(auto m  : matches)\n    {\n        error+= m.distance;\n        count ++;\n    }\n    cout<<\"error: \"<< error<<endl;\n    cout<<\"average error: \"<<error/count<<endl;\n\n    return 0;\n}\n\nvoid OpticalFlowSingleLevel(\n        const Mat &img1,\n        const Mat &img2,\n        const vector<KeyPoint> &kp1,\n        vector<KeyPoint> &kp2,\n        vector<bool> &success,\n        bool inverse\n) {\n\n    // parameters\n    int half_patch_size = 10;\n    int iterations = 10;\n    bool have_initial = !kp2.empty();\n\n    for (size_t i = 0; i < kp1.size(); i++) {\n        auto kp = kp1[i];\n\n        double dx = 0, dy = 0; // dx,dy need to be estimated\n        if (have_initial) {\n            dx = kp2[i].pt.x - kp.pt.x;\n            dy = kp2[i].pt.y - kp.pt.y;\n        }\n\n        double cost = 0, lastCost = 0;\n        bool succ = true; // indicate if this point succeeded\n\n        // Gauss-Newton iterations\n        for (int iter = 0; iter < iterations; iter++) {\n            Eigen::Matrix2d H = Eigen::Matrix2d::Zero();\n            Eigen::Vector2d b = Eigen::Vector2d::Zero();\n            cost = 0;\n\n            if (kp.pt.x + dx <= half_patch_size || kp.pt.x + dx >= img1.cols - half_patch_size ||\n                kp.pt.y + dy <= half_patch_size || kp.pt.y + dy >= img1.rows - half_patch_size) {   // go outside\n                succ = false;\n                break;\n            }\n\n            // compute cost and jacobian\n            for (int x = -half_patch_size; x < half_patch_size; x++)\n                for (int y = -half_patch_size; y < half_patch_size; y++) {\n\n                    // TODO START YOUR CODE HERE (~8 lines)\n\n                    float x1 = kp.pt.x + x;\n                    float y1 = kp.pt.y + y;\n                    double error = GetPixelValue(img1,x1,y1)-GetPixelValue(img2,x1+dx,y1+dy);\n                    Eigen::Vector2d J;  // Jacobian\n                    if (inverse == false) {\n                        // Forward Jacobian\n                        J[0] = (GetPixelValue(img2,x1+dx+1,y1+dy) - GetPixelValue(img2,x1+dx-1,y1+dy))/2;\n                        J[1] = (GetPixelValue(img2,x1+dx,y1+dy+1) - GetPixelValue(img2,x1+dx,y1+dy-1))/2;\n                    } else {\n                        // Inverse Jacobian\n                        // NOTE this J does not change when dx, dy is updated, so we can store it and only compute error\n                        J[0] = (GetPixelValue(img1,x1+1,y1) - GetPixelValue(img1,x1-1,y1))/2;\n                        J[1] = (GetPixelValue(img1,x1,y1+1) - GetPixelValue(img1,x1,y1-1))/2;\n                    }\n\n                    // compute H, b and set cost;\n                    // TODO END YOUR CODE HERE\n                    H += J * J.transpose() ;\n                    b += J.transpose()*error;\n                    cost += error * error;\n                }\n\n            // compute update\n            // TODO START YOUR CODE HERE (~1 lines)\n            Eigen::Vector2d update = H.ldlt().solve(b);\n            // TODO END YOUR CODE HERE\n\n            if (isnan(update[0])) {\n                // sometimes occurred when we have a black or white patch and H is irreversible\n                cout << \"update is nan\" << endl;\n                succ = false;\n                break;\n            }\n            if (iter > 0 && cost > lastCost) {\n                //cout << \"cost increased: \" << cost << \", \" << lastCost << endl;\n                break;\n            }\n\n            // update dx, dy\n            dx += update[0];\n            dy += update[1];\n            lastCost = cost;\n            succ = true;\n        }\n\n        success.push_back(succ);\n\n        // set kp2\n        if (have_initial) {\n            kp2[i].pt = kp.pt + Point2f(dx, dy);\n        } else {\n            KeyPoint tracked = kp;\n            tracked.pt += cv::Point2f(dx, dy);\n            kp2.push_back(tracked);\n        }\n    }\n}\n\nvoid OpticalFlowMultiLevel(\n        const Mat &img1,\n        const Mat &img2,\n        const vector<KeyPoint> &kp1,\n        vector<KeyPoint> &kp2,\n        vector<bool> &success,\n        bool inverse) {\n\n    // parameters\n    int pyramids = 4;\n    double pyramid_scale = 0.5;\n    double scales[] = {1.0, 0.5, 0.25, 0.125};\n\n    // create pyramids\n    vector<Mat> pyr1, pyr2; // image pyramids\n    // TODO START YOUR CODE HERE (~8 lines)\n    for (int i = 0; i < pyramids; i++) {\n        Mat uplevel1;\n        Mat uplevel2;\n        cv::resize(img1, uplevel1, cv::Size(), scales[i], scales[i]);\n        cv::resize(img2, uplevel2, cv::Size(), scales[i], scales[i]);\n        pyr1.push_back(uplevel1.clone());\n        pyr2.push_back(uplevel2.clone());\n    }\n    // TODO END YOUR CODE HERE\n\n    // coarse-to-fine LK tracking in pyramids\n    // TODO START YOUR CODE HERE\n    vector<KeyPoint> kp2_scale;\n    for(int i = pyramids - 1; i >= 0; --i)\n    {\n        vector<KeyPoint> kp1_scale = kp1;\n        for(int j = 0; j != kp1_scale.size(); ++j)\n        {\n            kp1_scale[j].pt.x *= scales[i];\n            kp1_scale[j].pt.y *= scales[i];\n        }\n\n        for(int j = 0; j != kp2_scale.size(); ++j)\n        {\n            kp2_scale[j].pt.x *= scales[i];\n            kp2_scale[j].pt.y *= scales[i];\n        }\n\n        OpticalFlowSingleLevel(pyr1[i], pyr2[i], kp1_scale, kp2_scale, success, inverse);\n\n        for(int j = 0; j != kp2_scale.size(); ++j)\n        {\n            kp2_scale[j].pt.x /= scales[i];\n            kp2_scale[j].pt.y /= scales[i];\n        }\n    }\n\n    kp2 = kp2_scale;\n    // TODO END YOUR CODE HERE\n    // don't forget to set the results into kp2\n}", "meta": {"hexsha": "0db5b068e6eaed3d4c6fe48a3503a4b5b6727036", "size": 9792, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "6/disparity.cpp", "max_stars_repo_name": "Yvon-Shong/SLAM", "max_stars_repo_head_hexsha": "4f633e71e13e1b3482255bc5abc38446a56beebf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2018-03-16T16:30:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-01T12:25:08.000Z", "max_issues_repo_path": "SLAM14Lectures-master/6/disparity.cpp", "max_issues_repo_name": "HCH2CHO/Visual_SLAM", "max_issues_repo_head_hexsha": "a5e977eb000b39e78d7b44e78e7856f6aabc4a02", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-07-08T11:52:08.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-01T18:40:41.000Z", "max_forks_repo_path": "SLAM14Lectures-master/6/disparity.cpp", "max_forks_repo_name": "HCH2CHO/Visual_SLAM", "max_forks_repo_head_hexsha": "a5e977eb000b39e78d7b44e78e7856f6aabc4a02", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2018-03-16T16:30:38.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-28T11:37:37.000Z", "avg_line_length": 30.6959247649, "max_line_length": 120, "alphanum_fraction": 0.5393178105, "num_tokens": 2715, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.4900302477199527}}
{"text": "#include \"mpc.h\"\n#include \"param.h\"\n#include \"assert.h\"\n#include \"primes.h\"\n#include <NTL/mat_ZZ_p.h>\n#include <NTL/mat_ZZ.h>\n#include <NTL/ZZ.h>\n#include <cmath>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n\nusing namespace NTL;\nusing namespace std;\n\nbool MPCEnv::Initialize(int pid, vector< pair<int, int> > &pairs) {\n  cout << \"Initializing MPC environment\" << endl;\n\n  /* Set base prime for the finite field */\n  ZZ base_p = conv<ZZ>(Param::BASE_P.c_str());\n  ZZ_p::init(base_p);\n\n  this->pid = pid;\n  this->clock_start = chrono::steady_clock::now();\n  debug = false;\n\n  if (!SetupChannels(pairs)) {\n    cout << \"MPCEnv::Initialize: failed to initialize communication channels\" << endl;\n    return false;\n  }\n\n  if (!SetupPRGs(pairs)) {\n    cout << \"MPCEnv::Initialize: failed to initialize PRGs\" << endl;\n    return false;\n  }\n  \n  SetSeed(prg.find(pid)->second);\n  cur_prg_pid = pid;\n\n  primes.SetLength(3);\n  primes[0] = ZZ_p::modulus();\n\n  bool found1 = false;\n  bool found2 = false;\n  long thres1 = Param::NBIT_K / 2;\n  long thres2 = ((long) ceil(sqrt((double) NumBits(ZZ_p::modulus())))) + 1;\n\n  long ind = -1;\n  long maxind = sizeof(PRIME_LIST) / sizeof(PRIME_LIST[0]);\n  while ((!found1 || !found2) && ++ind < maxind) {\n    long p = PRIME_LIST[ind];\n    if (!found1 && p > thres1) {\n      found1 = true;\n      primes[1] = ZZ(p);\n    }\n    if (!found2 && p > thres2) {\n      found2 = true;\n      primes[2] = ZZ(p);\n    }\n  }\n\n  if (!found1 || !found2) {\n    cout << \"Failed to find suitable small primes\" << endl;\n    return false;\n  }\n\n  cout << \"Small base primes selected: \" << primes[1] << \"(>\" << thres1 << \") and \"\n       << primes[2] << \"(>\" << thres2 << \")\" << endl;\n\n  ZZ_bytes.SetLength(primes.length());\n  ZZ_bits.SetLength(primes.length());\n  ZZ_per_buf.SetLength(primes.length());\n  for (int i = 0; i < primes.length(); i++) {\n    ZZ_bytes[i] = NumBytes(primes[i]);\n    ZZ_bits[i] = NumBits(primes[i]);\n    ZZ_per_buf[i] = (uint64_t) (Param::MPC_BUF_SIZE / ZZ_bytes[i]);\n  }\n\n  assert(ZZ_bytes[0] <= Param::MPC_BUF_SIZE); // buffer should contain at least one ZZ_p\n\n  pstate.push(\"\");\n\n  buf = (unsigned char *) malloc(Param::MPC_BUF_SIZE + GCM_AUTH_TAG_LEN);\n  if (buf == NULL) {\n    cout << \"Fail to allocate MPC buffer\" << endl;\n    exit(1);\n  } else {\n    cout << \"Allocated MPC buffer of size \" << Param::MPC_BUF_SIZE << endl;\n  }\n\n  cout << \"Number of bytes per ZZ_p: \" << ZZ_bytes[0] << endl;\n\n  cout << \"Setting up lookup tables\" << endl;\n\n  table_cache.SetLength(3);\n  table_type_ZZ.SetLength(3);\n  table_field_index.SetLength(3);\n  lagrange_cache.SetLength(3);\n\n  Mat<ZZ_p> table;\n\n  // Table 0\n  table.SetDims(1, 2);\n  if (pid > 0) {\n    table[0][0] = 1;\n    table[0][1] = 0;\n  }\n  table_type_ZZ[0] = true;\n  table_cache[0] = table;\n  table_field_index[0] = 2;\n\n  // Table 1\n  int half_len = Param::NBIT_K / 2;\n  table.SetDims(2, half_len + 1);\n  if (pid > 0) {\n    for (int i = 0; i < half_len + 1; i++) {\n      if (i == 0) {\n        table[0][i] = 1;\n        table[1][i] = 1;\n      } else {\n        table[0][i] = table[0][i - 1] * 2;\n        table[1][i] = table[1][i - 1] * 4;\n      }\n    }\n\n  }\n  table_type_ZZ[1] = true;\n  table_cache[1] = table;\n  table_field_index[1] = 1;\n\n  // Table 2: parameters (intercept, slope) for piecewise-linear approximation of\n  //          negative log-sigmoid function\n  table.SetDims(2, 64);\n  if (pid > 0) {\n    ifstream ifs;\n    ifs.open(\"sigmoid_approx.txt\");\n    if (!ifs.is_open()) {\n      cout << \"Error opening sigmoid_approx.txt\" << endl;\n      clear(table);\n    }\n    for (int i = 0; i < table.NumCols(); i++) {\n      double intercept, slope;\n      ifs >> intercept >> slope;\n\n      ZZ_p fp_intercept, fp_slope;\n      DoubleToFP(fp_intercept, intercept, Param::NBIT_K, Param::NBIT_F);\n      DoubleToFP(fp_slope, slope, Param::NBIT_K, Param::NBIT_F);\n\n      table[0][i] = fp_intercept;\n      table[1][i] = fp_slope;\n    }\n    ifs.close();\n  }\n  table_type_ZZ[2] = false;\n  table_cache[2] = table;\n  table_field_index[2] = 0;\n\n  cout << \"Generating lagrange cache\" << endl;\n\n  for (int cid = 0; cid < table_cache.length(); cid++) {\n    long nrow = table_cache[cid].NumRows();\n    long ncol = table_cache[cid].NumCols();\n    bool index_by_ZZ = table_type_ZZ[cid];\n    if (index_by_ZZ) {\n      lagrange_cache[cid].SetDims(nrow, 2 * ncol);\n    } else {\n      lagrange_cache[cid].SetDims(nrow, ncol);\n    }\n\n    if (pid > 0) {\n      cout << \"Lagrange interpolation for Table \" << cid << \" ... \";\n      for (int i = 0; i < nrow; i++) {\n        Vec<long> x;\n        Vec<ZZ_p> y;\n        if (index_by_ZZ) {\n          x.SetLength(2 * ncol);\n          y.SetLength(2 * ncol);\n        } else {\n          x.SetLength(ncol);\n          y.SetLength(ncol);\n        }\n        for (int j = 0; j < ncol; j++) {\n          x[j] = j + 1;\n          y[j] = table_cache[cid][i][j];\n          if (index_by_ZZ) {\n            x[j + ncol] = x[j] + conv<long>(primes[table_field_index[cid]]);\n            y[j + ncol] = table_cache[cid][i][j];\n          }\n        }\n\n        lagrange_interp(lagrange_cache[cid][i], x, y);\n      }\n      cout << \"done\" << endl;\n    }\n  }\n\n  return true;\n}\n\nbool MPCEnv::SetupChannels(vector< pair<int, int> > &pairs) {\n  for (int i = 0; i < pairs.size(); i++) {\n    int p1 = pairs[i].first;\n    int p2 = pairs[i].second;\n\n    if (p1 != pid && p2 != pid) {\n      continue;\n    }\n\n    int port = 8000;\n    if (p1 == 0 && p2 == 1) {\n      port = Param::PORT_P0_P1;\n    } else if (p1 == 0 && p2 == 2) {\n      port = Param::PORT_P0_P2;\n    } else if (p1 == 1 && p2 == 2) {\n      port = Param::PORT_P1_P2;\n    } else if (p1 == 1 && p2 == 3) {\n      port = Param::PORT_P1_P3;\n    } else if (p1 == 2 && p2 == 3) {\n      port = Param::PORT_P2_P3;\n    }\n\n    ostringstream oss;\n    oss << Param::KEY_PATH << \"P\" << p1 << \"_P\" << p2 << \".key\";\n    string key_file = oss.str();\n\n    int pother = p1 + p2 - pid;\n    sockets.insert(map<int, CSocket>::value_type(pother, CSocket()));\n\n    if (p1 == pid) {\n      if (!OpenChannel(sockets[pother], port)) {\n        cout << \"Failed to connect with P\" << pother << endl;\n        return false;\n      }\n    } else {\n      string ip_addr;\n      if (pother == 0) {\n        ip_addr = Param::IP_ADDR_P0;\n      } else if (pother == 1) {\n        ip_addr = Param::IP_ADDR_P1;\n      } else if (pother == 2) {\n        ip_addr = Param::IP_ADDR_P2;\n      }\n\n      if (!Connect(sockets[pother], ip_addr.c_str(), port)) {\n        cout << \"Failed to connect with P\" << pother << endl;\n        return false;\n      }\n    }\n\n    if (!sockets[pother].SetKey(key_file)) {\n      cout << \"Failed to establish a secure channel with P\" << pother << endl;\n      return false;\n    }\n\n    cout << \"Established a secure channel with P\" << pother << endl;\n  }\n\n  cout << \"Network setup complete\" << endl;\n  return true;\n}\n\nbool MPCEnv::SetupPRGs(vector< pair<int, int> > &pairs) {\n  int key_len = NTL_PRG_KEYLEN; // from NTL\n  unsigned char key[NTL_PRG_KEYLEN + GCM_AUTH_TAG_LEN];\n\n  /* Internal PRG */\n  int bytes = randread(key, key_len);\n  if (bytes != key_len) {\n    cout << \"Failed to generate an internal PRG key\" << endl;\n    return false;\n  }\n\n  prg.insert(map<int, RandomStream>::value_type(pid, NewRandomStream(key)));\n  \n  /* Global PRG */\n  ifstream ifs;\n  string key_file = Param::KEY_PATH + \"global.key\";\n  ifs.open(key_file.c_str(), ios::binary);\n  if (!ifs.is_open()) {\n    cout << \"Failed to open global PRG key file: \" << key_file << endl;\n    return false;\n  }\n\n  ifs.read((char *)key, PRF_KEY_BYTES);\n  if (ifs.gcount() != PRF_KEY_BYTES) {\n    cout << \"Failed to read \" << PRF_KEY_BYTES << \" bytes from global key file: \" << key_file << endl;\n    return false;\n  }\n  ifs.close();\n\n  AESStream aes(key);\n  aes.get(key, key_len);\n\n  prg.insert(map<int, RandomStream>::value_type(-1, NewRandomStream(key)));\n\n  /* Shared PRG (pairwise) */\n  for (int i = 0; i < pairs.size(); i++) {\n    int p1 = pairs[i].first;\n    int p2 = pairs[i].second;\n\n    if (p1 != pid && p2 != pid) {\n      continue;\n    }\n\n    int pother = p1 + p2 - pid;\n\n    if (p1 == pid) {\n      bytes = randread(key, key_len);\n      if (bytes != key_len) {\n        cout << \"Failed to generate a shared PRG key\" << endl;\n        return false;\n      }\n\n      prg.insert(map<int, RandomStream>::value_type(pother, NewRandomStream(key)));\n      sockets[pother].SendSecure(key, key_len);\n    } else {\n      sockets[pother].ReceiveSecure(key, key_len);\n      prg.insert(map<int, RandomStream>::value_type(pother, NewRandomStream(key)));\n    }\n\n    cout << \"Shared PRG with P\" << pother << \" initialized\" << endl;\n  }\n\n  cout << \"PRG setup complete\" << endl;\n  return true;\n}\n\n\nvoid MPCEnv::CleanUp() {\n  cout << \"Closing sockets ... \";\n  for (map<int, CSocket>::iterator it = sockets.begin(); it != sockets.end(); ++it) {\n    CloseChannel(it->second);\n  }\n  cout << \"done.\" << endl;\n}\n\nvoid MPCEnv::ProfilerResetTimer() {\n  if (!Param::PROFILER) return;\n\n  vector<uint64_t> stat(5, 0);\n\n  chrono::time_point<chrono::steady_clock> clock_end = chrono::steady_clock::now();\n\n  stat[0] = chrono::duration_cast<chrono::milliseconds>(clock_end - clock_start).count();\n\n  int ind = 1;\n  for (int p = 0; p < 3; p++) {\n    if (p == pid) continue;\n    map<int, CSocket>::iterator it = sockets.find(p);\n    stat[ind] = it->second.GetBytesSent();\n    stat[ind+1] = it->second.GetBytesReceived();\n    it->second.ResetStats();\n    ind += 2;\n  }\n\n  string state = pstate.top();\n  if (state != \"\") {\n    map<string, int>::iterator it = ptable_index.find(state);\n    if (it != ptable_index.end()) {\n      for (int i = 0; i < stat.size(); i++) {\n        ptable[it->second].second[i] += stat[i];\n      }\n    } else {\n      ptable.push_back(make_pair(state, stat));\n      ptable_index[state] = ptable.size() - 1;\n    }\n  }\n\n  clock_start = clock_end;\n}\n\nvoid MPCEnv::ProfilerPushState(string desc) {\n  if (!Param::PROFILER) return;\n\n  assert(desc != \"\");\n\n  ProfilerResetTimer();\n\n  string full_desc;\n  if (pstate.top() == \"\") {\n    full_desc = desc;\n  } else {\n    full_desc = pstate.top() + \">\" + desc;\n  }\n\n  pstate.push(full_desc);\n}\n\nvoid MPCEnv::ProfilerPopState(bool write) {\n  if (!Param::PROFILER) return;\n\n  assert(pstate.top() != \"\");\n\n  ProfilerResetTimer();\n\n  pstate.pop();\n\n  if (write) {\n    ProfilerWriteToFile();\n  }\n}\n\nvoid MPCEnv::ProfilerWriteToFile() {\n  if (!Param::PROFILER) return;\n\n  ProfilerResetTimer();\n  \n  // Open log file\n  logfs.open(Param::LOG_FILE.c_str());\n  if (!logfs.is_open()) {\n    cout << \"Fail to open the log file: \" << Param::LOG_FILE << endl;\n    exit(1);\n  }\n\n  ostringstream oss;\n\n  // log file header\n  oss << \"Desc\\tTime(ms)\";\n  for (int p = 0; p < 3; p++) {\n    if (p == pid) continue;\n    oss << \"\\tTo_\" << p;\n    oss << \"\\tFrom_\" << p;\n  }\n  oss << endl;\n\n  for (int i = 0; i < ptable.size(); i++) {\n    oss << ptable[i].first;\n    for (int j = 0; j < ptable[i].second.size(); j++) {\n      oss << \"\\t\" << ptable[i].second[j];\n    }\n    oss << endl;\n  }\n\n  logfs << oss.str();\n  logfs.flush();\n  logfs.close();\n}\n\nvoid MPCEnv::ParallelLogisticRegression(Vec<ZZ_p>& b0, Mat<ZZ_p>& bv, Vec<ZZ_p>& bx,\n                                Mat<ZZ_p>& xr, Mat<ZZ_p>& xm,\n                                Mat<ZZ_p>& vr, Mat<ZZ_p>& vm,\n                                Vec<ZZ_p>& yr, Vec<ZZ_p>& ym,\n                                int max_iter) {\n  cout << \"ParallelLogisticRegression\" << endl;\n\n  size_t n = vr.NumCols();\n  size_t p = vr.NumRows();\n  size_t c = xr.NumRows();\n  assert(vm.NumRows() == p); assert(vm.NumCols() == n);\n  assert(xm.NumRows() == c); assert(xm.NumCols() == n);\n  assert(xr.NumCols() == n);\n  assert(yr.length() == n);\n  assert(ym.length() == n);\n\n  // Initialize\n  Init(b0, c);\n  Init(bv, c, p);\n  Init(bx, c);\n\n  // Flip y\n  Vec<ZZ_p> yneg_r = -yr;\n  Vec<ZZ_p> yneg_m = -ym;\n  if (pid > 0) {\n    for (int i = 0; i < n; i++) {\n      yneg_r[i] += 1;\n    }\n  }\n\n  Vec<ZZ_p> yneg = yneg_m;\n  if (pid == 1) {\n    for (int i = 0; i < n; i++) {\n      yneg[i] += yneg_r[i];\n    }\n  }\n\n  ZZ_p fp_memory; \n  DoubleToFP(fp_memory, 0.5, Param::NBIT_K, Param::NBIT_F);\n\n  ZZ_p fp_n_inv; \n  DoubleToFP(fp_n_inv, 1 / ((double) n), Param::NBIT_K, Param::NBIT_F);\n\n  double eta = 0.3;\n\n  ZZ_p fp_one; \n  DoubleToFP(fp_one, 1, Param::NBIT_K, Param::NBIT_F);\n\n  Vec<ZZ_p> step0;\n  Mat<ZZ_p> stepv;\n  Vec<ZZ_p> stepx;\n  Init(step0, c);\n  Init(stepv, c, p);\n  Init(stepx, c);\n\n  int nbatch = 10;\n  int batch_size = (n + nbatch - 1) / nbatch;\n\n  Mat<ZZ_p> xr_batch, xm_batch;\n  Mat<ZZ_p> vr_batch, vm_batch;\n  Vec<ZZ_p> yn_batch, ynr_batch, ynm_batch;\n\n  // Gradient descent (with momentum)\n  for (int it = 0; it < max_iter; it++) {\n    cout << \"Iter \" << it << endl;\n\n    int batch_index = it % nbatch;\n    int start_ind = batch_size * batch_index;\n    int end_ind = start_ind + batch_size; // exclusive\n    if (end_ind > n) {\n      end_ind = n;\n    }\n    int cur_bsize = end_ind - start_ind;\n\n    // Construct mini-batch\n    xr_batch.SetDims(c, cur_bsize);\n    xm_batch.SetDims(c, cur_bsize);\n    vr_batch.SetDims(p, cur_bsize);\n    vm_batch.SetDims(p, cur_bsize);\n    yn_batch.SetLength(cur_bsize);\n    ynr_batch.SetLength(cur_bsize);\n    ynm_batch.SetLength(cur_bsize);\n    for (int j = 0; j < c; j++) {\n      for (int i = 0; i < cur_bsize; i++) {\n        xr_batch[j][i] = xr[j][start_ind + i];\n        xm_batch[j][i] = xm[j][start_ind + i];\n      }\n    }\n    for (int j = 0; j < p; j++) {\n      for (int i = 0; i < cur_bsize; i++) {\n        vr_batch[j][i] = vr[j][start_ind + i];\n        vm_batch[j][i] = vm[j][start_ind + i];\n      }\n    }\n    for (int i = 0; i < cur_bsize; i++) {\n      yn_batch[i] = yneg[start_ind + i];\n      ynr_batch[i] = yneg_r[start_ind + i];\n      ynm_batch[i] = yneg_m[start_ind + i];\n    }\n\n    ZZ_p fp_bsize_inv; \n    DoubleToFP(fp_bsize_inv, eta * (1 / ((double) cur_bsize)), Param::NBIT_K, Param::NBIT_F);\n\n    Mat<ZZ_p> bvr, bvm;\n    BeaverPartition(bvr, bvm, bv);\n\n    Vec<ZZ_p> bxr, bxm;\n    BeaverPartition(bxr, bxm, bx);\n\n    Mat<ZZ_p> h;\n    Init(h, c, cur_bsize);\n\n    BeaverMult(h, bvr, bvm, vr_batch, vm_batch);\n    for (int j = 0; j < c; j++) {\n      Vec<ZZ_p> xrvec = fp_one * xr_batch[j];\n      Vec<ZZ_p> xmvec = fp_one * xm_batch[j];\n      BeaverMult(h[j], xrvec, xmvec, bxr[j], bxm[j]);\n    }\n    BeaverReconstruct(h);\n    Trunc(h);\n\n    for (int j = 0; j < c; j++) {\n      AddScalar(h[j], b0[j]);\n    }\n\n    Vec<ZZ_p> hvec;\n    Reshape(hvec, h);\n\n    Vec<ZZ_p> svec, s_grad_vec;\n    NegLogSigmoid(svec, s_grad_vec, hvec);\n    hvec.kill();\n\n    Mat<ZZ_p> s, s_grad;\n    Reshape(s, svec, c, cur_bsize);\n    Reshape(s_grad, s_grad_vec, c, cur_bsize);\n    svec.kill();\n    s_grad_vec.kill();\n\n    // Compute gradient\n    Vec<ZZ_p> d0;\n    Mat<ZZ_p> dv;\n    Vec<ZZ_p> dx;\n    Init(d0, c);\n    Init(dv, c, p);\n    Init(dx, c);\n\n    for (int j = 0; j < c; j++) {\n      s_grad[j] += yn_batch * fp_one;\n      d0[j] = Sum(s_grad[j]);\n    }\n\n    Mat<ZZ_p> s_grad_r, s_grad_m;\n    BeaverPartition(s_grad_r, s_grad_m, s_grad);\n\n    for (int j = 0; j < c; j++) {\n      BeaverInnerProd(dx[j], xr_batch[j], xm_batch[j], s_grad_r[j], s_grad_m[j]);\n    }\n    BeaverReconstruct(dx);\n\n    transpose(vr_batch, vr_batch);\n    transpose(vm_batch, vm_batch);\n    BeaverMult(dv, s_grad_r, s_grad_m, vr_batch, vm_batch);\n    BeaverReconstruct(dv);\n    Trunc(dv);\n\n    step0 = step0 * fp_memory - d0 * fp_bsize_inv;\n    stepv = stepv * fp_memory - dv * fp_bsize_inv;\n    stepx = stepx * fp_memory - dx * fp_bsize_inv;\n    Trunc(step0);\n    Trunc(stepv);\n    Trunc(stepx);\n\n    b0 = b0 + step0;\n    bv = bv + stepv;\n    bx = bx + stepx;\n  }\n}\n\nvoid MPCEnv::NegLogSigmoid(Vec<ZZ_p>& b, Vec<ZZ_p>& b_grad, Vec<ZZ_p>& a) {\n  size_t n = a.length();\n\n  int depth = 6;\n\n  Vec<ZZ_p> cur = a; // copy\n\n  Vec<ZZ_p> a_ind;\n  a_ind.SetLength(a.length());\n  clear(a_ind);\n\n  double step = 4;\n\n  for (int i = 0; i < depth; i++) {\n    Vec<ZZ_p> cur_sign;\n    IsPositive(cur_sign, cur);\n\n    ZZ_p index_step(1 << (depth - 1 - i));\n\n    for (int j = 0; j < n; j++) {\n      a_ind[j] += cur_sign[j] * index_step;\n    }\n\n    cur_sign *= 2;\n    if (pid == 1) {\n      for (int j = 0; j < n; j++) {\n        cur_sign[j] -= 1;\n      }\n    }\n\n    ZZ_p step_fp;\n    DoubleToFP(step_fp, step, Param::NBIT_K, Param::NBIT_F);\n\n    for (int j = 0; j < n; j++) {\n      cur[j] -= step_fp * cur_sign[j];\n    }\n\n    step /= 2;\n  }\n\n  // Make indices 1-based\n  if (pid == 1) {\n    for (int j = 0; j < n; j++) {\n      a_ind[j]++;\n    }\n  }\n\n  // Fetch piecewise linear approx parameters\n  Mat<ZZ_p> param;\n  TableLookup(param, a_ind, 2);\n\n  MultElem(b, param[1], a);\n  Trunc(b);\n\n  if (pid > 0) {\n    for (int j = 0; j < n; j++) {\n      b[j] += param[0][j];\n    }\n  }\n\n  b_grad = param[1];\n}\n\nvoid MPCEnv::InnerProd(Vec<ZZ_p>& c, Mat<ZZ_p>& a) {\n  if (debug) cout << \"InnerProd: \" << a.NumRows() << \", \" << a.NumCols() << endl;\n\n  Mat<ZZ_p> ar, am;\n  BeaverPartition(ar, am, a);\n\n  Init(c, a.NumRows());\n  for (int i = 0; i < a.NumRows(); i++) {\n    BeaverInnerProd(c[i], ar[i], am[i]);\n  }\n\n  BeaverReconstruct(c);\n}\nvoid MPCEnv::InnerProd(ZZ_p& c, Vec<ZZ_p>& a) {\n  if (debug) cout << \"InnerProd: \" << a.length() << endl;\n\n  Vec<ZZ_p> ar, am;\n  BeaverPartition(ar, am, a);\n  BeaverInnerProd(c, ar, am);\n  BeaverReconstruct(c);\n}\n\nvoid MPCEnv::Householder(Vec<ZZ_p>& v, Vec<ZZ_p>& x) {\n  if (debug) cout << \"Householder: \" << x.length() << endl;\n\n  int n = x.length();\n\n  Vec<ZZ_p> xr, xm;\n  BeaverPartition(xr, xm, x);\n\n  Vec<ZZ_p> xdot;\n  Init(xdot, 1);\n  BeaverInnerProd(xdot[0], xr, xm);\n  BeaverReconstruct(xdot);\n  Trunc(xdot);\n\n  Vec<ZZ_p> xnorm, dummy;\n  FPSqrt(xnorm, dummy, xdot);\n\n  Vec<ZZ_p> x1;\n  x1.SetLength(1);\n  x1[0] = x[0];\n\n  Vec<ZZ_p> x1sign;\n  IsPositive(x1sign, x1);\n\n  x1sign *= 2;\n  if (pid == 1) {\n    x1sign[0] -= 1;\n  }\n\n  Vec<ZZ_p> shift;\n  MultElem(shift, xnorm, x1sign);\n\n  ZZ_p sr, sm;\n  BeaverPartition(sr, sm, shift[0]);\n\n  ZZ_p dot_shift(0);\n  BeaverMult(dot_shift, xr[0], xm[0], sr, sm);\n  BeaverReconstruct(dot_shift);\n  Trunc(dot_shift);\n\n  Vec<ZZ_p> vdot;\n  vdot.SetLength(1);\n  if (pid > 0) {\n    vdot[0] = 2 * (xdot[0] + dot_shift);\n  }\n\n  Vec<ZZ_p> vnorm_inv;\n  FPSqrt(dummy, vnorm_inv, vdot);\n\n  ZZ_p invr, invm;\n  BeaverPartition(invr, invm, vnorm_inv[0]);\n \n  Vec<ZZ_p> vr, vm;\n  if (pid > 0) {\n    vr = xr;\n    vr[0] += sr;\n  } else {\n    vr.SetLength(n);\n  }\n  vm = xm;\n  vm[0] += sm;\n\n  Init(v, n);\n  BeaverMult(v, vr, vm, invr, invm);\n  BeaverReconstruct(v);\n  Trunc(v);\n}\n\nvoid MPCEnv::QRFactSquare(Mat<ZZ_p>& Q, Mat<ZZ_p>& R, Mat<ZZ_p>& A) {\n  if (debug) cout << \"QRFactSquare: \" << A.NumRows() << \", \" << A.NumCols() << endl;\n\n  assert(A.NumRows() == A.NumCols());\n\n  int n = A.NumRows();\n  R.SetDims(n, n);\n  if (pid > 0) {\n    clear(R);\n  }\n\n  Mat<ZZ_p> Ap;\n  if (pid == 0) {\n    Ap.SetDims(n, n);\n  } else {\n    Ap = A;\n  }\n\n  ZZ_p one;\n  DoubleToFP(one, 1, Param::NBIT_K, Param::NBIT_F);\n\n  for (int i = 0; i < n - 1; i++) {\n    Mat<ZZ_p> v;\n    v.SetDims(1, Ap.NumCols());\n    Householder(v[0], Ap[0]);\n\n    Mat<ZZ_p> vt;\n    if (pid == 0) {\n      vt.SetDims(Ap.NumCols(), 1);\n    } else {\n      transpose(vt, v);\n    }\n\n    Mat<ZZ_p> P;\n    MultMat(P, vt, v);\n    Trunc(P);\n    if (pid > 0) {\n      P *= -2;\n      if (pid == 1) {\n        for (int j = 0; j < P.NumCols(); j++) {\n          P[j][j] += one;\n        }\n      }\n    }\n\n    Mat<ZZ_p> B;\n    if (i == 0) {\n      Q = P;\n      MultMat(B, Ap, P);\n      Trunc(B);\n    } else {\n      Mat<ZZ_p> Qsub;\n      Qsub.SetDims(n - i, n);\n      if (pid > 0) {\n        for (int j = 0; j < n - i; j++) {\n          Qsub[j] = Q[j+i];\n        }\n      }\n\n      Vec< Mat<ZZ_p> > left;\n      Vec< Mat<ZZ_p> > right;\n      left.SetLength(2);\n      right.SetLength(2);\n      left[0] = P;\n      right[0] = Qsub;\n      left[1] = Ap;\n      right[1] = P;\n\n      Vec< Mat<ZZ_p> > prod;\n      MultMatParallel(prod, left, right);\n      // TODO: parallelize Trunc\n      Trunc(prod[0]);\n      Trunc(prod[1]);\n\n      if (pid > 0) {\n        for (int j = 0; j < n - i; j++) {\n          Q[j+i] = prod[0][j];\n        }\n        B = prod[1];\n      } else {\n        B.SetDims(n - i, n - i);\n      }\n    }\n\n    if (pid > 0) {\n      for (int j = 0; j < n - i; j++) {\n        R[i+j][i] = B[j][0];\n      }\n      if (i == n - 2) {\n        R[n-1][n-1] = B[1][1];\n      }\n\n      Ap.SetDims(n - i - 1, n - i - 1);\n      for (int j = 0; j < n - i - 1; j++) {\n        for (int k = 0; k < n - i - 1; k++) {\n          Ap[j][k] = B[j+1][k+1];\n        }\n      }\n    } else {\n      Ap.SetDims(n - i - 1, n - i - 1);\n    }\n  }\n}\n\nvoid MPCEnv::OrthonormalBasis(Mat<ZZ_p>& Q, Mat<ZZ_p>& A) {\n  if (debug) cout << \"OrthonormalBasis: \" << A.NumRows() << \", \" << A.NumCols() << endl;\n\n  assert(A.NumCols() >= A.NumRows());\n\n  int c = A.NumRows();\n  int n = A.NumCols();\n\n  Vec< Vec<ZZ_p> > v_list;\n  v_list.SetLength(c);\n\n  Mat<ZZ_p> Ap;\n  if (pid == 0) {\n    Ap.SetDims(c, n);\n  } else {\n    Ap = A;\n  }\n\n  ZZ_p one;\n  DoubleToFP(one, 1, Param::NBIT_K, Param::NBIT_F);\n\n  for (int i = 0; i < c; i++) {\n    Mat<ZZ_p> v;\n    v.SetDims(1, Ap.NumCols());\n    Householder(v[0], Ap[0]);\n\n    if (pid == 0) {\n      v_list[i].SetLength(Ap.NumCols());\n    } else {\n      v_list[i] = v[0];\n    }\n\n    Mat<ZZ_p> vt;\n    if (pid == 0) {\n      vt.SetDims(Ap.NumCols(), 1);\n    } else {\n      transpose(vt, v);\n    }\n\n    Mat<ZZ_p> Apv;\n    MultMat(Apv, Ap, vt);\n    Trunc(Apv);\n\n    Mat<ZZ_p> B;\n    MultMat(B, Apv, v);\n    Trunc(B);\n    if (pid > 0) {\n      B *= -2;\n      B += Ap;\n    }\n\n    Ap.SetDims(B.NumRows() - 1, B.NumCols() - 1);\n    if (pid > 0) {\n      for (int j = 0; j < B.NumRows() - 1; j++) {\n        for (int k = 0; k < B.NumCols() - 1; k++) {\n          Ap[j][k] = B[j+1][k+1];\n        }\n      }\n    }\n  }\n\n  Q.SetDims(c, n);\n  if (pid > 0) {\n    clear(Q);\n    if (pid == 1) {\n      for (int i = 0; i < c; i++) {\n        Q[i][i] = one;\n      }\n    }\n  }\n\n  for (int i = c - 1; i >= 0; i--) {\n    Mat<ZZ_p> v;\n    v.SetDims(1, v_list[i].length());\n    if (pid > 0) {\n      v[0] = v_list[i];\n    }\n\n    Mat<ZZ_p> vt;\n    if (pid == 0) {\n      vt.SetDims(v.NumCols(), 1);\n    } else {\n      transpose(vt, v);\n    }\n\n    Mat<ZZ_p> Qsub;\n    Qsub.SetDims(c, n - i);\n    if (pid > 0) {\n      for (int j = 0; j < c; j++) {\n        for (int k = 0; k < n - i; k++) {\n          Qsub[j][k] = Q[j][k+i];\n        }\n      }\n    }\n\n    Mat<ZZ_p> Qv;\n    MultMat(Qv, Qsub, vt);\n    Trunc(Qv);\n\n    Mat<ZZ_p> Qvv;\n    MultMat(Qvv, Qv, v);\n    Trunc(Qvv);\n    if (pid > 0) {\n      Qvv *= -2;\n    }\n\n    if (pid > 0) {\n      for (int j = 0; j < c; j++) {\n        for (int k = 0; k < n - i; k++) {\n          Q[j][k+i] += Qvv[j][k];\n        }\n      }\n    }\n  }\n}\n\nvoid MPCEnv::Tridiag(Mat<ZZ_p>& T, Mat<ZZ_p>& Q, Mat<ZZ_p>& A) {\n  if (debug) cout << \"Tridiag: \" << A.NumRows() << \", \" << A.NumCols() << endl;\n\n  assert(A.NumRows() == A.NumCols());\n  assert(A.NumRows() > 2);\n\n  int n = A.NumRows();\n\n  ZZ_p one;\n  DoubleToFP(one, 1, Param::NBIT_K, Param::NBIT_F);\n\n  Q.SetDims(n, n);\n  T.SetDims(n, n);\n  if (pid > 0) {\n    clear(Q);\n    clear(T);\n    if (pid == 1) {\n      for (int i = 0; i < n; i++) {\n        Q[i][i] = one;\n      }\n    }\n  }\n\n  Mat<ZZ_p> Ap;\n  if (pid == 0) {\n    Ap.SetDims(n, n);\n  } else {\n    Ap = A;\n  }\n\n  for (int i = 0; i < n - 2; i++) {\n    Vec<ZZ_p> x;\n    x.SetLength(Ap.NumCols() - 1);\n    if (pid > 0) {\n      for (int j = 0; j < Ap.NumCols() - 1; j++) {\n        x[j] = Ap[0][j+1];\n      }\n    }\n\n    Mat<ZZ_p> v;\n    v.SetDims(1, x.length());\n    Householder(v[0], x);\n\n    Mat<ZZ_p> vt;\n    if (pid == 0) {\n      vt.SetDims(x.length(), 1);\n    } else {\n      transpose(vt, v);\n    }\n\n    Mat<ZZ_p> vv;\n    MultMat(vv, vt, v);\n    Trunc(vv);\n\n    Mat<ZZ_p> P;\n    P.SetDims(Ap.NumCols(), Ap.NumCols());\n    if (pid > 0) {\n      P[0][0] = (pid == 1) ? one : ZZ_p(0);\n      for (int j = 1; j < Ap.NumCols(); j++) {\n        for (int k = 1; k < Ap.NumCols(); k++) {\n          P[j][k] = -2 * vv[j-1][k-1];\n          if (pid == 1 && j == k) {\n            P[j][k] += one;\n          }\n        }\n      }\n    }\n\n    // TODO: parallelize? (minor improvement)\n    Mat<ZZ_p> PAp;\n    MultMat(PAp, P, Ap);\n    Trunc(PAp);\n\n    Mat<ZZ_p> B;\n    MultMat(B, PAp, P);\n    Trunc(B);\n\n    Mat<ZZ_p> Qsub;\n    Qsub.SetDims(n, n - i);\n    if (pid > 0) {\n      for (int j = 0; j < n; j++) {\n        for (int k = 0; k < n - i; k++) {\n          Qsub[j][k] = Q[j][k+i];\n        }\n      }\n    }\n\n    MultMat(Qsub, Qsub, P);\n    Trunc(Qsub);\n    if (pid > 0) {\n      for (int j = 0; j < n; j++) {\n        for (int k = 0; k < n - i; k++) {\n          Q[j][k+i] = Qsub[j][k];\n        }\n      }\n    }\n\n    if (pid > 0) {\n      T[i][i] = B[0][0];\n      T[i+1][i] = B[1][0];\n      T[i][i+1] = B[0][1];\n      if (i == n - 3) {\n        T[i+1][i+1] = B[1][1];\n        T[i+1][i+2] = B[1][2];\n        T[i+2][i+1] = B[2][1];\n        T[i+2][i+2] = B[2][2];\n      }\n    }\n\n    Ap.SetDims(B.NumRows() - 1, B.NumCols() - 1);\n    if (pid > 0) {\n      for (int j = 0; j < B.NumRows() - 1; j++) {\n        for (int k = 0; k < B.NumCols() - 1; k++) {\n          Ap[j][k] = B[j+1][k+1];\n        }\n      }\n    }\n  }\n}\n\nvoid MPCEnv::EigenDecomp(Mat<ZZ_p>& V, Vec<ZZ_p>& L, Mat<ZZ_p>& A) {\n  if (debug) cout << \"EigenDecomp: \" << A.NumRows() << \", \" << A.NumCols() << endl;\n\n  assert(A.NumRows() == A.NumCols());\n  int n = A.NumRows();\n\n  L.SetLength(n);\n  clear(L);\n\n  Mat<ZZ_p> Ap, Q;\n  Tridiag(Ap, Q, A);\n\n  if (pid == 0) {\n    V.SetDims(n, n);\n  } else {\n    transpose(V, Q);\n  }\n\n  for (int i = n - 1; i >= 1; i--) {\n    cout << \"EigenDecomp: \" << i << \"-th eigenvalue\" << endl;\n    for (int it = 0; it < Param::ITER_PER_EVAL; it++) {\n      ZZ_p shift = Ap[i][i];\n      if (pid > 0) {\n        for (int j = 0; j < Ap.NumCols(); j++) {\n          Ap[j][j] -= shift;\n        }\n      }\n\n      Mat<ZZ_p> R;\n      QRFactSquare(Q, R, Ap);\n\n      MultMat(Ap, Q, R);\n      Trunc(Ap);\n\n      if (pid > 0) {\n        for (int j = 0; j < Ap.NumCols(); j++) {\n          Ap[j][j] += shift;\n        }\n      }\n\n      Mat<ZZ_p> Vsub;\n      Vsub.SetDims(i + 1, n);\n      if (pid > 0) {\n        for (int j = 0; j < i + 1; j++) {\n          Vsub[j] = V[j];\n        }\n      }\n\n      MultMat(Vsub, Q, Vsub);\n      Trunc(Vsub);\n\n      if (pid > 0) {\n        for (int j = 0; j < i + 1; j++) {\n          V[j] = Vsub[j];\n        }\n      }\n    }\n\n    L[i] = Ap[i][i];\n    if (i == 1) {\n      L[0] = Ap[0][0];\n    }\n\n    Mat<ZZ_p> Ap_copy = Ap;\n    Ap.SetDims(i, i);\n    if (pid > 0) {\n      for (int j = 0; j < i; j++) {\n        for (int k = 0; k < i; k++) {\n          Ap[j][k] = Ap_copy[j][k];\n        }\n      }\n    }\n  }\n  cout << \"EigenDecomp: complete\" << endl;\n}\n\nvoid MPCEnv::LessThanBitsAux(Vec<ZZ>& c, Mat<ZZ>& a, Mat<ZZ>& b, int public_flag, int fid) {\n  if (debug) cout << \"LessThanBitsAux: \" << a.NumRows() << \", \" << a.NumCols() << endl;\n \n  assert(a.NumRows() == b.NumRows());\n  assert(a.NumCols() == b.NumCols());\n \n  int n = a.NumRows();\n  int L = a.NumCols();\n \n  /* Calculate XOR */\n  Mat<ZZ> x;\n  x.SetDims(n, L);\n \n  if (public_flag == 0) {\n    MultElem(x, a, b, fid);\n    if (pid > 0) {\n      x = a + b - 2 * x;\n      Mod(x, fid);\n    }\n  } else if (pid > 0) {\n    mul_elem(x, a, b);\n    x = a + b - 2 * x;\n    if (pid == 2) {\n      x -= (public_flag == 1) ? a : b;\n    }\n    Mod(x, fid);\n  }\n \n  Mat<ZZ> f;\n  PrefixOr(f, x, fid);\n  x.kill();\n \n  if (pid > 0) {\n    for (int i = 0; i < n; i++) {\n      for (int j = L - 1; j >= 1; j--) {\n        f[i][j] -= f[i][j - 1];\n      }\n    }\n    Mod(f, fid);\n  }\n \n  if (public_flag == 2) {\n    c.SetLength(n);\n \n    if (pid > 0) {\n      for (int i = 0; i < n; i++) {\n        c[i] = 0;\n        for (int j = 0; j < L; j++) {\n          c[i] += f[i][j] * b[i][j];\n        }\n      }\n      Mod(c, fid);\n    }\n  } else {\n    //TODO: optimize\n    Vec< Mat<ZZ> > f_arr, b_arr;\n    f_arr.SetLength(n);\n    b_arr.SetLength(n);\n    for (int i = 0; i < n; i++) {\n      f_arr[i].SetDims(1, L);\n      b_arr[i].SetDims(L, 1);\n    }\n \n    if (pid > 0) {\n      for (int i = 0; i < n; i++) {\n        f_arr[i][0] = f[i];\n        for (int j = 0; j < L; j++) {\n          b_arr[i][j][0] = b[i][j];\n        }\n      }\n    }\n \n    Vec< Mat<ZZ> > c_arr;\n    MultMatParallel(c_arr, f_arr, b_arr, fid);\n \n    c.SetLength(n);\n    if (pid > 0) {\n      for (int i = 0; i < n; i++) {\n        c[i] = c_arr[i][0][0];\n      }\n    }\n  }\n}\n\nvoid MPCEnv::LessThan(Vec<ZZ_p>& c, Vec<ZZ_p>& a, Vec<ZZ_p>& b) {\n  Vec<ZZ_p> a_cpy;\n  a_cpy.SetLength(a.length());\n  if (pid > 0) {\n    for (int i = 0; i < a.length(); i++) {\n      a_cpy[i] = a[i] - b[i];\n    }\n  }\n\n  // a - b >= 0?\n  IsPositive(c, a_cpy);\n  FlipBit(c);\n}\n\nvoid MPCEnv::LessThanPublic(Vec<ZZ_p>& c, Vec<ZZ_p>& a, ZZ_p bpub) {\n  Vec<ZZ_p> a_cpy;\n  a_cpy.SetLength(a.length());\n  if (pid > 0) {\n    for (int i = 0; i < a.length(); i++) {\n      a_cpy[i] = a[i];\n      if (pid == 1) {\n        a_cpy[i] -= bpub;\n      }\n    }\n  }\n\n  // a - b >= 0?\n  IsPositive(c, a_cpy);\n  FlipBit(c);\n}\n\n// Failure probability of 1 / BASE_P\n// Base field index 2\nvoid MPCEnv::IsPositive(Vec<ZZ_p>& b, Vec<ZZ_p>& a) {\n  if (debug) cout << \"IsPositive: \" << a.length() << endl; \n\n  int n = a.length();\n  int nbits = ZZ_bits[0];\n  int fid = 2;\n\n  Vec<ZZ_p> r;\n  Mat<ZZ> r_bits;\n  if (pid == 0) {\n    RandVec(r, n);\n    NumToBits(r_bits, r, nbits);\n\n    SwitchSeed(1);\n    Vec<ZZ_p> r_mask;\n    Mat<ZZ> r_bits_mask;\n    RandVec(r_mask, n);\n    RandMat(r_bits_mask, n, nbits, fid);\n    RestoreSeed();\n\n    r -= r_mask;\n    r_bits -= r_bits_mask;\n    Mod(r_bits, fid);\n\n    SendVec(r, 2);\n    SendMat(r_bits, 2, fid);\n  } else if (pid == 2) {\n    ReceiveVec(r, 0, n);\n    ReceiveMat(r_bits, 0, n, nbits, fid);\n  } else {\n    SwitchSeed(0);\n    RandVec(r, n);\n    RandMat(r_bits, n, nbits, fid);\n    RestoreSeed();\n  }\n\n  Vec<ZZ_p> c;\n  if (pid == 0) {\n    c.SetLength(n);\n  } else {\n    c = 2 * a + r;\n  }\n\n  RevealSym(c);\n\n  Mat<ZZ> c_bits;\n  if (pid == 0) {\n    c_bits.SetDims(n, nbits);\n  } else {\n    NumToBits(c_bits, c, nbits);\n  }\n\n  // Incorrect result if r = 0, which happens with probaility 1 / BASE_P\n  Vec<ZZ> no_overflow;\n  LessThanBitsPublic(no_overflow, r_bits, c_bits, fid);\n\n  Vec<ZZ> c_xor_r;\n  c_xor_r.SetLength(n);\n  if (pid > 0) {\n    for (int i = 0; i < n; i++) {\n      c_xor_r[i] = r_bits[i][nbits-1] - 2 * c_bits[i][nbits-1] * r_bits[i][nbits-1];\n      if (pid == 1) {\n        c_xor_r[i] += c_bits[i][nbits-1];\n      }\n    }\n    Mod(c_xor_r, fid);\n  }\n\n  Vec<ZZ> lsb;\n  MultElem(lsb, c_xor_r, no_overflow, fid);\n  if (pid > 0) {\n    lsb *= 2;\n    for (int i = 0; i < n; i++) {\n      lsb[i] -= no_overflow[i] + c_xor_r[i];\n      if (pid == 1) {\n        lsb[i] += 1;\n      }\n    }\n    Mod(lsb, fid);\n  }\n\n  // 0, 1 -> 1, 2\n  if (pid == 1) {\n    for (int i = 0; i < n; i++) {\n      lsb[i] += 1;\n    }\n    Mod(lsb, fid);\n  }\n\n  Mat<ZZ_p> b_mat;\n  TableLookup(b_mat, lsb, 0, fid);\n\n  b = b_mat[0];\n}\n\nvoid MPCEnv::FlipBit(Vec<ZZ_p>& b, Vec<ZZ_p>& a) {\n  if (debug) cout << \"FlipBit: \" << a.length() << endl;\n  if (pid == 0) {\n    b.SetLength(a.length());\n  } else {\n    b = -a;\n  }\n\n  if (pid == 1) {\n    for (int i = 0; i < b.length(); i++) {\n      b[i] += 1;\n    }\n  }\n}\n\n// Assumes Param::NBIT_K - NBIT_F is even\nvoid MPCEnv::FPSqrt(Vec<ZZ_p>& b, Vec<ZZ_p>& b_inv, Vec<ZZ_p>& a) {\n  if (debug) cout << \"FPSqrt: \" << a.length() << endl; \n\n  int n = a.length();\n\n  if (n > Param::DIV_MAX_N) {\n    int nbatch = ceil(n / ((double) Param::DIV_MAX_N));\n    b.SetLength(n);\n    b_inv.SetLength(n);\n    for (int i = 0; i < nbatch; i++) {\n      cout << \"FPSqrt on large vector: \" << i + 1 << \"/\" << nbatch << endl;\n      int start = Param::DIV_MAX_N * i;\n      int end = start + Param::DIV_MAX_N;\n      if (end > n) {\n        end = n;\n      }\n      int batch_size = end - start;\n      Vec<ZZ_p> a_copy;\n      a_copy.SetLength(batch_size);\n      for (int j = 0; j < batch_size; j++) {\n        a_copy[j] = a[start + j];\n      }\n      Vec<ZZ_p> b_copy, b_inv_copy;\n      FPSqrt(b_copy, b_inv_copy, a_copy);\n      for (int j = 0; j < batch_size; j++) {\n        b[start + j] = b_copy[j];\n        b_inv[start + j] = b_inv_copy[j];\n      }\n    }\n    return;\n  }\n\n  // TODO: Currently using the same # iter as division -- possibly need to update\n  int niter = 2 * ceil(log2(((double) Param::NBIT_K) / 3.5));\n\n  /* Initial approximation: 1 / sqrt(a_scaled) ~= 2.9581 - 4 * a_scaled + 2 * a_scaled^2 */\n  Vec<ZZ_p> s, s_sqrt;\n  NormalizerEvenExp(s, s_sqrt, a);\n\n  Vec<ZZ_p> a_scaled;\n  MultElem(a_scaled, a, s);\n  Trunc(a_scaled, Param::NBIT_K, Param::NBIT_K - Param::NBIT_F);\n\n  Vec<ZZ_p> a_scaled_sq;\n  MultElem(a_scaled_sq, a_scaled, a_scaled);\n  Trunc(a_scaled_sq);\n\n  Vec<ZZ_p> scaled_est;\n  if (pid == 0) {\n    scaled_est.SetLength(n);\n  } else {\n    scaled_est = - 4 * a_scaled + 2 * a_scaled_sq;\n    if (pid == 1) {\n      ZZ_p coeff;\n      DoubleToFP(coeff, 2.9581, Param::NBIT_K, Param::NBIT_F);\n      for (int i = 0; i < n; i++) {\n        scaled_est[i] += coeff;\n      }\n    }\n  }\n\n  Vec< Mat<ZZ_p> > h_and_g;\n  h_and_g.SetLength(2);\n  h_and_g[0].SetDims(1, n);\n  h_and_g[1].SetDims(1, n);\n\n  MultElem(h_and_g[0][0], scaled_est, s_sqrt);\n  // Our scaled initial approximation (scaled_est) has bit length <= NBIT_F + 2\n  // and s_sqrt is at most NBIT_K/2 bits, so their product is at most NBIT_K/2 + NBIT_F + 2\n  Trunc(h_and_g[0], Param::NBIT_K/2 + Param::NBIT_F + 2, ((Param::NBIT_K - Param::NBIT_F) / 2) + 1); \n\n  h_and_g[1][0] = h_and_g[0][0] * 2;\n  MultElem(h_and_g[1][0], h_and_g[1][0], a);\n  Trunc(h_and_g[1]);\n\n  ZZ_p onepointfive;\n  DoubleToFP(onepointfive, 1.5, Param::NBIT_K, Param::NBIT_F);\n\n  for (int it = 0; it < niter; it++) {\n    Mat<ZZ_p> r;\n    MultElem(r, h_and_g[0], h_and_g[1]);\n    Trunc(r);\n    r = -r;\n    if (pid == 1) {\n      for (int i = 0; i < n; i++) {\n        r[0][i] += onepointfive;\n      }\n    }\n\n    Vec< Mat<ZZ_p> > r_dup;\n    r_dup.SetLength(2);\n    r_dup[0] = r;\n    r_dup[1] = r;\n\n    MultElemParallel(h_and_g, h_and_g, r_dup);\n    // TODO: write a version of Trunc with parallel processing\n    Trunc(h_and_g[0]);\n    Trunc(h_and_g[1]);\n  }\n\n  b_inv = 2 * h_and_g[0][0];\n  b = h_and_g[1][0];\n}\n\nvoid MPCEnv::FPDiv(Vec<ZZ_p>& c, Vec<ZZ_p>& a, Vec<ZZ_p>& b) {\n  if (debug) cout << \"FPDiv: \" << a.length() << endl; \n\n  assert(a.length() == b.length());\n\n  int n = a.length();\n  if (n > Param::DIV_MAX_N) {\n    int nbatch = ceil(n / ((double) Param::DIV_MAX_N));\n    c.SetLength(n);\n    for (int i = 0; i < nbatch; i++) {\n      int start = Param::DIV_MAX_N * i;\n      int end = start + Param::DIV_MAX_N;\n      if (end > n) {\n        end = n;\n      }\n      int batch_size = end - start;\n\n      cout << \"FPDiv on large vector: \" << i + 1 << \"/\" << nbatch << \", n = \" << batch_size << endl;\n\n      Vec<ZZ_p> a_copy, b_copy;\n      a_copy.SetLength(batch_size);\n      b_copy.SetLength(batch_size);\n      for (int j = 0; j < batch_size; j++) {\n        a_copy[j] = a[start + j];\n        b_copy[j] = b[start + j];\n      }\n      Vec<ZZ_p> c_copy;\n      FPDiv(c_copy, a_copy, b_copy);\n      for (int j = 0; j < batch_size; j++) {\n        c[start + j] = c_copy[j];\n      }\n    }\n    return;\n  }\n\n  int niter = 2 * ceil(log2(((double) Param::NBIT_K) / 3.5)) + 1;\n\n  /* Initial approximation: 1 / x_scaled ~= 5.9430 - 10 * x_scaled + 5 * x_scaled^2 */\n  Vec<ZZ_p> s, s_sqrt;\n  NormalizerEvenExp(s, s_sqrt, b);\n\n  Vec<ZZ_p> b_scaled;\n  MultElem(b_scaled, b, s);\n  Trunc(b_scaled, Param::NBIT_K, Param::NBIT_K - Param::NBIT_F);\n\n  Vec<ZZ_p> b_scaled_sq;\n  MultElem(b_scaled_sq, b_scaled, b_scaled);\n  Trunc(b_scaled_sq);\n\n  Vec<ZZ_p> scaled_est;\n  if (pid == 0) {\n    scaled_est.SetLength(n);\n  } else {\n    scaled_est = - 10 * b_scaled + 5 * b_scaled_sq;\n    if (pid == 1) {\n      ZZ_p coeff;\n      DoubleToFP(coeff, 5.9430, Param::NBIT_K, Param::NBIT_F);\n      AddScalar(scaled_est, coeff);\n    }\n  }\n\n  Vec<ZZ_p> w;\n  MultElem(w, scaled_est, s);\n  // scaled_est has bit length <= NBIT_F + 2, and s has bit length <= NBIT_K\n  // so the bit length of w is at most NBIT_K + NBIT_F + 2\n  Trunc(w, Param::NBIT_K + Param::NBIT_F + 2, Param::NBIT_K - Param::NBIT_F);\n\n  Vec<ZZ_p> x;\n  MultElem(x, w, b);\n  Trunc(x);\n\n  ZZ_p one;\n  IntToFP(one, 1, Param::NBIT_K, Param::NBIT_F);\n\n  x *= -1;\n  if (pid == 1) {\n    for (int i = 0; i < x.length(); i++) {\n      x[i] += one;\n    }\n  }\n\n  Vec<ZZ_p> y;\n  MultElem(y, a, w);\n  Trunc(y);\n\n  for (int i = 0; i < niter; i++) {\n    Vec<ZZ_p> xr, xm, yr, ym;\n    BeaverPartition(xr, xm, x);\n    BeaverPartition(yr, ym, y);\n\n    Vec<ZZ_p> xpr = xr;\n    if (pid > 0) {\n      AddScalar(xpr, one);\n    }\n\n    Init(x, n);\n    Init(y, n);\n\n    BeaverMultElem(y, yr, ym, xpr, xm);\n    BeaverMultElem(x, xr, xm, xr, xm);\n    BeaverReconstruct(x);\n    BeaverReconstruct(y);\n\n    Trunc(x);\n    Trunc(y);\n  }\n\n  if (pid == 1) {\n    for (int i = 0; i < x.length(); i++) {\n      x[i] += one;\n    }\n  }\n\n  MultElem(c, y, x);\n  Trunc(c);\n}\n\nvoid MPCEnv::Trunc(Mat<ZZ_p>& a, int k, int m) {\n  if (debug) cout << \"Trunc: \" << a.NumRows() << \", \" << a.NumCols() << endl; \n\n  Mat<ZZ_p> r;\n  Mat<ZZ_p> r_low;\n  if (pid == 0) {\n    RandMatBits(r, a.NumRows(), a.NumCols(), k + Param::NBIT_V);\n\n    r_low.SetDims(a.NumRows(), a.NumCols());\n    for (int i = 0; i < a.NumRows(); i++) {\n      for (int j = 0; j < a.NumCols(); j++) {\n        r_low[i][j] = conv<ZZ_p>(trunc_ZZ(rep(r[i][j]), m));\n      }\n    }\n\n    Mat<ZZ_p> r_mask;\n    Mat<ZZ_p> r_low_mask;\n    SwitchSeed(1);\n    RandMat(r_mask, a.NumRows(), a.NumCols());\n    RandMat(r_low_mask, a.NumRows(), a.NumCols());\n    RestoreSeed();\n\n    r -= r_mask;\n    r_low -= r_low_mask;\n\n    SendMat(r, 2);\n    SendMat(r_low, 2);\n  } else if (pid == 2) {\n    ReceiveMat(r, 0, a.NumRows(), a.NumCols());\n    ReceiveMat(r_low, 0, a.NumRows(), a.NumCols());\n  } else {\n    SwitchSeed(0);\n    RandMat(r, a.NumRows(), a.NumCols());\n    RandMat(r_low, a.NumRows(), a.NumCols());\n    RestoreSeed();\n  }\n\n  Mat<ZZ_p> c;\n  if (pid > 0) {\n    c = a + r;\n  } else {\n    c.SetDims(a.NumRows(), a.NumCols());\n  }\n\n  RevealSym(c);\n  \n  Mat<ZZ_p> c_low;\n  c_low.SetDims(a.NumRows(), a.NumCols());\n  if (pid > 0) {\n    for (int i = 0; i < a.NumRows(); i++) {\n      for (int j = 0; j < a.NumCols(); j++) {\n        c_low[i][j] = conv<ZZ_p>(trunc_ZZ(rep(c[i][j]), m));\n      }\n    }\n  }\n\n  if (pid > 0) {\n    a += r_low;\n    if (pid == 1) {\n      a -= c_low;\n    }\n\n    ZZ_p twoinvm;\n    map<int, ZZ_p>::iterator it = invpow_cache.find(m);\n    if (it == invpow_cache.end()) {\n      ZZ_p two(2);\n      ZZ_p twoinv;\n      inv(twoinv, two);\n      power(twoinvm, twoinv, m);\n      invpow_cache[m] = twoinvm;\n    } else {\n      twoinvm = it->second;\n    }\n\n    a *= twoinvm;\n  }\n}\n\nvoid MPCEnv::PrefixOr(Mat<ZZ>& b, Mat<ZZ>& a, int fid) {\n  if (debug) cout << \"PrefixOr: \" << a.NumRows() << \", \" << a.NumCols() << endl;\n\n  int n = a.NumRows();\n\n  /* Find next largest squared integer */\n  int L = (int) ceil(sqrt((double) a.NumCols()));\n  int L2 = L * L;\n\n  assert(primes[fid] > L + 1);\n\n  /* Zero-pad to L2 bits */\n  Mat<ZZ> a_padded;\n  a_padded.SetDims(n, L2);\n\n  if (pid > 0) {\n    for (int i = 0; i < n; i++) {\n      for (int j = 0; j < L2; j++) {\n        if (j < L2 - a.NumCols())\n          a_padded[i][j] = 0;\n        else\n          a_padded[i][j] = a[i][j - L2 + a.NumCols()];\n      }\n    }\n  }\n\n  Reshape(a_padded, n * L, L);\n  \n  Vec<ZZ> x;\n  FanInOr(x, a_padded, fid);\n\n  Mat<ZZ> xpre;\n  xpre.SetDims(n * L, L);\n  \n  if (pid > 0) {\n    for (int i = 0; i < n; i++) {\n      for (int j = 0; j < L; j++) {\n        int xpi = L * i + j;\n        for (int k = 0; k < L; k++) {\n          xpre[xpi][k] = (k <= j) ? x[L * i + k] : ZZ(0);\n        }\n      }\n    }\n  }\n\n  Vec<ZZ> y;\n  FanInOr(y, xpre, fid);\n  xpre.kill();\n\n  Vec< Mat<ZZ> > f; // f is a concatenation of n 1-by-L matrices\n  f.SetLength(n);\n  for (int i = 0; i < n; i++) {\n    f[i].SetDims(1, L);\n  }\n\n  if (pid > 0) {\n    for (int i = 0; i < n; i++) {\n      for (int j = 0; j < L; j++) {\n        if (j == 0) {\n          f[i][0][j] = x[L * i];\n        } else {\n          f[i][0][j] = y[L * i + j] - y[L * i + j - 1];\n        }\n      }\n      Mod(f[i], fid);\n    }\n  }\n  x.kill();\n\n  Vec< Mat<ZZ> > tmp;\n  tmp.SetLength(n);\n  for (int i = 0; i < n; i++) {\n    tmp[i].SetDims(L, L);\n  }\n\n  if (pid > 0) {\n    for (int i = 0; i < n; i++) {\n      for (int j = 0; j < L; j++) {\n        tmp[i][j] = a_padded[L * i + j];\n      }\n    }\n  }\n  a_padded.kill();\n\n  Vec< Mat<ZZ> > c;\n  MultMatParallel(c, f, tmp, fid); // c is a concatenation of n 1-by-L matrices\n  tmp.kill();\n\n  Mat<ZZ> cpre;\n  cpre.SetDims(n * L, L);\n  if (pid > 0) {\n    for (int i = 0; i < n; i++) {\n      for (int j = 0; j < L; j++) {\n        int cpi = L * i + j;\n        for (int k = 0; k < L; k++) {\n          cpre[cpi][k] = (k <= j) ? c[i][0][k] : ZZ(0);\n        }\n      }\n    }\n  }\n  c.kill();\n\n  Vec<ZZ> bdot_vec;\n  FanInOr(bdot_vec, cpre, fid);\n  cpre.kill();\n\n  Vec< Mat<ZZ> > bdot;\n  bdot.SetLength(n);\n  for (int i = 0; i < n; i++) {\n    bdot[i].SetDims(1, L);\n  }\n\n  if (pid > 0) {\n    for (int i = 0; i < n; i++) {\n      for (int j = 0; j < L; j++) {\n        bdot[i][0][j] = bdot_vec[L * i + j];\n      }\n    }\n  }\n  bdot_vec.kill();\n\n  for (int i = 0; i < n; i++) {\n    Reshape(f[i], L, 1);\n  }\n\n  Vec< Mat<ZZ> > s;\n  MultMatParallel(s, f, bdot, fid);\n  bdot.kill();\n\n  b.SetDims(n, a.NumCols());\n  if (pid > 0) {\n    for (int i = 0; i < n; i++) {\n      for (int j = 0; j < a.NumCols(); j++) {\n        int j_pad = L2 - a.NumCols() + j; \n\n        int il = (int) (j_pad / L);\n        int jl = j_pad - il * L;\n\n        b[i][j] = s[i][il][jl] + y[L * i + il] - f[i][il][0];\n      }\n    }\n  }\n  Mod(b, fid);\n  s.kill();\n  y.kill();\n  f.kill();\n}\n\nvoid MPCEnv::FanInOr(Vec<ZZ>& b, Mat<ZZ>& a, int fid) {\n  if (debug) cout << \"FanInOr: \" << a.NumRows() << \", \" << a.NumCols() << endl;\n\n  int n = a.NumRows();\n  int d = a.NumCols();\n\n  Vec<ZZ> a_sum;\n  a_sum.SetLength(n);\n\n  if (pid > 0) {\n    for (int i = 0; i < n; i++) {\n      a_sum[i] = (pid == 1) ? 1 : 0;\n      for (int j = 0; j < d; j++) {\n        a_sum[i] += a[i][j];\n      }\n    }\n    Mod(a_sum, fid);\n  }\n\n  Mat<ZZ> coeff;\n  coeff.SetDims(1, d + 1);\n  pair<int, int> key = make_pair(d + 1, fid);\n  if (or_lagrange_cache.find(key) != or_lagrange_cache.end()) {\n    coeff[0] = or_lagrange_cache[key];\n  } else {\n    Vec<ZZ> y;\n    y.SetLength(d + 1);\n    for (int i = 0; i < d + 1; i++) {\n      y[i] = (i == 0) ? 0 : 1;\n    }\n    lagrange_interp_simple(coeff[0], y, fid); // OR function\n    or_lagrange_cache[key] = coeff[0];\n  }\n\n  Mat<ZZ> bmat;\n  EvaluatePoly(bmat, a_sum, coeff, fid);\n  b = bmat[0];\n}\n\nvoid MPCEnv::ShareRandomBits(Vec<ZZ_p>& r, Mat<ZZ>& rbits, int k, int n, int fid) {\n  if (debug) cout << \"ShareRandomBits: \" << n << endl;\n\n  if (pid == 0) {\n    RandVecBits(r, n, k + Param::NBIT_V);\n    NumToBits(rbits, r, k);\n\n    Vec<ZZ_p> r_mask;\n    Mat<ZZ> rbits_mask;\n\n    SwitchSeed(1);\n    RandVec(r_mask, n);\n    RandMat(rbits_mask, n, k, fid);\n    RestoreSeed();\n\n    r -= r_mask;\n    rbits -= rbits_mask;\n    Mod(rbits, fid);\n\n    SendVec(r, 2);\n    SendMat(rbits, 2, fid);\n  } else if (pid == 2) {\n    ReceiveVec(r, 0, n);\n    ReceiveMat(rbits, 0, n, k, fid);\n  } else {\n    SwitchSeed(0);\n    RandVec(r, n);\n    RandMat(rbits, n, k, fid);\n    RestoreSeed();\n  }\n}\n\nvoid MPCEnv::TableLookup(Mat<ZZ_p>& b, Vec<ZZ_p>& a, int table_id) {\n  if (debug) cout << \"TableLookup: \" << a.length() << endl; \n\n  assert(!table_type_ZZ[table_id]);\n\n  EvaluatePoly(b, a, lagrange_cache[table_id]);\n}\n\nvoid MPCEnv::TableLookup(Mat<ZZ_p>& b, Vec<ZZ>& a, int table_id, int fid) {\n  if (debug) cout << \"TableLookup: \" << a.length() << endl; \n\n  assert(table_type_ZZ[table_id]);\n  assert(table_field_index[table_id] == fid);\n\n  int s = table_cache[table_id].NumCols();\n  int n = a.length();\n\n  Vec<ZZ_p> a_exp;\n  a_exp.SetLength(n);\n  if (pid > 0) {\n    for (int i = 0; i < n; i++) {\n      a_exp[i] = conv<ZZ_p>(a[i]);\n    }\n  }\n\n  if (debug) cout << \"Evaluating polynomial\" << endl;\n  if (debug) cout << s << \", \" << lagrange_cache[table_id].NumCols() << endl;\n\n  EvaluatePoly(b, a_exp, lagrange_cache[table_id]);\n}\n\n// Base field index 1\nvoid MPCEnv::NormalizerEvenExp(Vec<ZZ_p>& b, Vec<ZZ_p>& b_sqrt, Vec<ZZ_p>& a) {\n  if (debug) cout << \"NormalizerEvenExp: \" << a.length() << endl;\n\n  int n = a.length();\n  int fid = 1;\n\n  Vec<ZZ_p> r; \n  Mat<ZZ> rbits;\n  ShareRandomBits(r, rbits, Param::NBIT_K, n, fid);\n\n  Vec<ZZ_p> e;\n  if (pid == 0) {\n    e.SetLength(n);\n  } else {\n    e = a + r;\n  }\n  r.kill();\n\n  RevealSym(e);\n\n  Mat<ZZ> ebits;\n  if (pid == 0) {\n    ebits.SetDims(n, Param::NBIT_K);\n  } else {\n    NumToBits(ebits, e, Param::NBIT_K);\n  }\n  e.kill();\n\n  Vec<ZZ> c;\n  LessThanBitsPublic(c, rbits, ebits, fid);\n  if (pid > 0) {\n    c = -c;\n    if (pid == 1) {\n      for (int i = 0; i < n; i++) {\n        c[i] += 1;\n      }\n    }\n    Mod(c, fid);\n  }\n\n  Mat<ZZ> ep;\n  ep.SetDims(n, Param::NBIT_K + 1);\n  if (pid > 0) {\n    for (int i = 0; i < n; i++) {\n      ep[i][0] = c[i];\n      for (int j = 1; j < Param::NBIT_K + 1; j++) {\n        ep[i][j] = (1 - 2 * ebits[i][j-1]) * rbits[i][j-1];\n        if (pid == 1) {\n          ep[i][j] += ebits[i][j-1];\n        }\n      }\n    }\n    Mod(ep, fid);\n  }\n  c.kill();\n\n  Mat<ZZ> E;\n  PrefixOr(E, ep, fid);\n  ep.kill();\n\n  Mat<ZZ> tpneg;\n  tpneg.SetDims(n, Param::NBIT_K);\n  if (pid > 0) {\n    for (int i = 0; i < n; i++) {\n      for (int j = 0; j < Param::NBIT_K; j++) {\n        tpneg[i][j] = E[i][j] - rbits[i][j] * (1 - ebits[i][j]);\n      }\n    }\n    Mod(tpneg, fid);\n  }\n  E.kill();\n\n  Mat<ZZ> Tneg;\n  PrefixOr(Tneg, tpneg, fid);\n  tpneg.kill();\n\n  int half_len = Param::NBIT_K / 2;\n\n  Mat<ZZ> efir, rfir;\n  efir.SetDims(n, Param::NBIT_K);\n  rfir.SetDims(n, Param::NBIT_K);\n  if (pid > 0) {\n    mul_elem(efir, ebits, Tneg);\n    Mod(efir, fid);\n  }\n  MultElem(rfir, rbits, Tneg, fid);\n  ebits.kill();\n  rbits.kill();\n\n  Vec<ZZ> double_flag;\n  LessThanBits(double_flag, efir, rfir, fid);\n  efir.kill();\n  rfir.kill();\n  \n  Mat<ZZ> odd_bits, even_bits;\n  odd_bits.SetDims(n, half_len);\n  even_bits.SetDims(n, half_len);\n  if (pid > 0) {\n    for (int i = 0; i < n; i++) {\n      for (int j = 0; j < half_len; j++) {\n        odd_bits[i][j] = (pid == 1) ? (1 - Tneg[i][2*j+1]) : -Tneg[i][2*j+1];\n        if ((2 * j + 2) < Param::NBIT_K) {\n          even_bits[i][j] = (pid == 1) ? (1 - Tneg[i][2*j+2]) : -Tneg[i][2*j+2];\n        } else {\n          even_bits[i][j] = 0;\n        }\n      }\n    }\n    Mod(odd_bits, fid);\n    Mod(even_bits, fid);\n  }\n  Tneg.kill();\n\n  Vec<ZZ> odd_bit_sum, even_bit_sum;\n  Init(odd_bit_sum, n);\n  Init(even_bit_sum, n);\n  for (int i = 0; i < n; i++) {\n    for (int j = 0; j < half_len; j++) {\n      odd_bit_sum[i] += odd_bits[i][j];\n      even_bit_sum[i] += even_bits[i][j];\n    }\n    if (pid == 1) {\n      odd_bit_sum[i] += 1;\n      even_bit_sum[i] += 1;\n    }\n  }\n  Mod(odd_bit_sum, fid);\n  Mod(even_bit_sum, fid);\n  odd_bits.kill();\n  even_bits.kill();\n\n  // If double_flag = true, then use odd_bits, otherwise use even_bits\n\n  Vec<ZZ> diff;\n  if (pid == 0) {\n    diff.SetLength(n);\n  } else {\n    diff = odd_bit_sum - even_bit_sum;\n    Mod(diff, fid);\n  }\n  MultElem(diff, double_flag, diff, fid);\n  double_flag.kill();\n\n  Vec<ZZ> chosen_bit_sum;\n  if (pid == 0) {\n    chosen_bit_sum.SetLength(n);\n  } else {\n    chosen_bit_sum = even_bit_sum + diff;\n    Mod(chosen_bit_sum, fid);\n  }\n  odd_bit_sum.kill();\n  even_bit_sum.kill();\n  diff.kill();\n\n  Mat<ZZ_p> b_mat;\n  TableLookup(b_mat, chosen_bit_sum, 1, fid);\n\n  if (pid > 0) {\n    b_sqrt = b_mat[0];\n    b = b_mat[1];\n  } else {\n    b_sqrt.SetLength(n);\n    b.SetLength(n);\n  }\n}\n\nvoid MPCEnv::ReadFromFile(ZZ_p& a, ifstream& ifs) {\n  Vec<ZZ_p> avec;\n  if (pid > 0) {\n    Read(avec, ifs, 1);\n    a = avec[0];\n  }\n}\nvoid MPCEnv::ReadFromFile(Vec<ZZ_p>& a, ifstream& ifs, int n) {\n  if (pid > 0) {\n    Read(a, ifs, n);\n  } else {\n    a.SetLength(n);\n  }\n}\nvoid MPCEnv::ReadFromFile(Mat<ZZ_p>& a, ifstream& ifs, int nrow, int ncol) {\n  if (pid > 0) {\n    Read(a, ifs, nrow, ncol);\n  } else {\n    a.SetDims(nrow, ncol);\n  }\n}\nvoid MPCEnv::WriteToFile(ZZ_p& a, fstream& ofs) {\n  if (pid > 0) {\n    Vec<ZZ_p> avec;\n    avec.SetLength(1);\n    avec[0] = a;\n    Write(avec, ofs);\n  }\n}\nvoid MPCEnv::WriteToFile(Vec<ZZ_p>& a, fstream& ofs) {\n  if (pid > 0) {\n    Write(a, ofs);\n  }\n}\nvoid MPCEnv::WriteToFile(Mat<ZZ_p>& a, fstream& ofs) {\n  if (pid > 0) {\n    Write(a, ofs);\n  }\n}\n\nvoid MPCEnv::Write(Vec<ZZ_p>& a, fstream& ofs) {\n  Mat<ZZ_p> a_copy;\n  a_copy.SetDims(1, a.length());\n  a_copy[0] = a;\n  Write(a_copy, ofs);\n}\n\nvoid MPCEnv::Read(Vec<ZZ_p>& a, ifstream& ifs, int n) {\n  Mat<ZZ_p> tmp;\n  Read(tmp, ifs, 1, n);\n  a = tmp[0];\n}\n\nvoid MPCEnv::ReadWithFilter(Vec<ZZ_p>& a, ifstream& ifs, Vec<ZZ_p>& filt) {\n  assert(ifs.is_open());\n  a.SetLength(filt.length());\n\n  unsigned char *buf_ptr = buf;\n  uint64_t stored_in_buf = 0;\n\n  for (int i = 0; i < filt.length(); i++) {\n    if (filt[i] != 1) {\n      uint64_t count = 0;\n      int k = i;\n      while (k < filt.length() && filt[k] != 1) {\n        k++;\n        count++;\n      }\n      ifs.ignore(count * ZZ_bytes[0]);\n      i += count - 1;\n    } else {\n      if (stored_in_buf == 0) {\n        uint64_t count = 0;\n        int k = i;\n        while (k < filt.length() && filt[k] == 1) {\n          k++;\n          count++;\n        }\n\n        if (count > ZZ_per_buf[0]) {\n          count = ZZ_per_buf[0];\n        }\n\n        ifs.read((char *)buf, count * ZZ_bytes[0]);\n        stored_in_buf += count;\n        buf_ptr = buf;\n      }\n\n      a[i] = conv<ZZ_p>(ZZFromBytes(buf_ptr, ZZ_bytes[0]));\n      buf_ptr += ZZ_bytes[0];\n      stored_in_buf--;\n    }\n  }\n}\n\nvoid MPCEnv::Write(Mat<ZZ_p>& a, fstream& ofs) {\n  assert(ofs.is_open());\n\n  unsigned char *buf_ptr = buf;\n  uint64_t stored_in_buf = 0;\n  for (int i = 0; i < a.NumRows(); i++) {\n    for (int j = 0; j < a.NumCols(); j++) {\n      if (stored_in_buf == ZZ_per_buf[0]) {\n        ofs.write((const char *)buf, ZZ_bytes[0] * stored_in_buf);\n        stored_in_buf = 0;\n        buf_ptr = buf;\n      }\n\n      BytesFromZZ(buf_ptr, rep(a[i][j]), ZZ_bytes[0]);\n      stored_in_buf++;\n      buf_ptr += ZZ_bytes[0];\n    }\n  }\n\n  if (stored_in_buf > 0) {\n    ofs.write((const char *)buf, ZZ_bytes[0] * stored_in_buf);\n  }\n}\n\nvoid MPCEnv::SkipData(ifstream& ifs, int n) {\n  if (pid > 0) {\n    assert(ifs.is_open());\n    ifs.ignore(n * ZZ_bytes[0]);\n  }\n}\n\nvoid MPCEnv::SkipData(ifstream& ifs, int nrows, int ncols) {\n  if (pid > 0) {\n    assert(ifs.is_open());\n    for (int i = 0; i < nrows; i++) {\n      ifs.ignore(ncols * ZZ_bytes[0]);\n    }\n  }\n}\n\nvoid MPCEnv::Read(Mat<ZZ_p>& a, ifstream& ifs, int nrows, int ncols) {\n  assert(ifs.is_open());\n\n  a.SetDims(nrows, ncols);\n  unsigned char *buf_ptr = buf;\n  uint64_t stored_in_buf = 0;\n  uint64_t remaining = nrows * ncols;\n  for (int i = 0; i < a.NumRows(); i++) {\n    for (int j = 0; j < a.NumCols(); j++) {\n      if (stored_in_buf == 0) {\n        uint64_t count;\n        if (remaining < ZZ_per_buf[0]) {\n          count = remaining;\n        } else {\n          count = ZZ_per_buf[0];\n        }\n        ifs.read((char *)buf, count * ZZ_bytes[0]);\n        stored_in_buf += count;\n        remaining -= count;\n        buf_ptr = buf;\n      }\n\n      a[i][j] = conv<ZZ_p>(ZZFromBytes(buf_ptr, ZZ_bytes[0]));\n      buf_ptr += ZZ_bytes[0];\n      stored_in_buf--;\n    }\n  }\n}\n\nvoid MPCEnv::SendInt(int num, int to_pid) {\n  cout << \"SendInt called: num(\" << num << \"), to_pid(\" << to_pid << \")\" << endl;\n  *((int *)buf) = num;\n  sockets.find(to_pid)->second.Send(buf, sizeof(int));\n}\n\nint MPCEnv::ReceiveInt(int from_pid) {\n  cout << \"ReceiveInt called: from_pid(\" << from_pid << \")\" << endl;\n  sockets.find(from_pid)->second.Receive(buf, sizeof(int));\n  return *((int *)buf);\n}\n\nvoid MPCEnv::SendBool(bool flag, int to_pid) {\n  cout << \"SendBool called: flag(\" << flag << \"), to_pid(\" << to_pid << \")\" << endl;\n  *((bool *)buf) = flag;\n  sockets.find(to_pid)->second.Send(buf, sizeof(bool));\n}\n\nbool MPCEnv::ReceiveBool(int from_pid) {\n  cout << \"ReceiveBool called: from_pid(\" << from_pid << \")\" << endl;\n  sockets.find(from_pid)->second.Receive(buf, sizeof(bool));\n  return *((bool *)buf);\n}\n\nvoid MPCEnv::SwitchSeed(int pid) {\n  prg.find(cur_prg_pid)->second = GetCurrentRandomStream();\n  SetSeed(prg.find(pid)->second);\n  cur_prg_pid = pid;\n}\n\nvoid MPCEnv::ExportSeed(fstream& ofs, int pid) {\n  assert(ofs.is_open());\n\n  RandomStream rs = prg.find(pid)->second;\n  rs.serialize(buf);\n\n  ofs.write((const char *)buf, RandomStream::numBytes());\n}\n\nvoid MPCEnv::ExportSeed(fstream& ofs) {\n  assert(ofs.is_open());\n\n  RandomStream rs = GetCurrentRandomStream();\n  rs.serialize(buf);\n\n  ofs.write((const char *)buf, RandomStream::numBytes());\n}\n\nvoid MPCEnv::ImportSeed(int newid, ifstream& ifs) {\n  assert(ifs.is_open());\n\n  ifs.read((char *)buf, RandomStream::numBytes());\n\n  RandomStream rs((const unsigned char *)buf, true);\n\n  pair<map<int,RandomStream>::iterator,bool> ret;\n  ret = prg.insert(pair<int, RandomStream>(newid, rs));\n  if (!ret.second) { // ID exists already\n    ret.first->second = rs;\n  }\n}\n\nvoid MPCEnv::BeaverReadFromFile(Mat<ZZ_p>& ar, Mat<ZZ_p>& am, ifstream& ifs, int nrow, int ncol) {\n  if (pid > 0) {\n    Read(ar, ifs, nrow, ncol);\n  } else {\n    ar.SetDims(nrow, ncol);\n  }\n  Read(am, ifs, nrow, ncol);\n}\n\nvoid MPCEnv::BeaverReadFromFile(Vec<ZZ_p>& ar, Vec<ZZ_p>& am, ifstream& ifs, int n) {\n  if (pid > 0) {\n    Read(ar, ifs, n);\n  } else {\n    ar.SetLength(n);\n  }\n  Read(am, ifs, n);\n}\n\nvoid MPCEnv::BeaverReadFromFileWithFilter(Vec<ZZ_p>& ar, Vec<ZZ_p>& am, ifstream& ifs, Vec<ZZ_p>& filt) {\n  if (pid > 0) {\n    ReadWithFilter(ar, ifs, filt);\n  } else {\n    ar.SetLength(filt.length());\n  }\n  ReadWithFilter(am, ifs, filt);\n}\n\nvoid MPCEnv::BeaverWriteToFile(Vec<ZZ_p>& ar, Vec<ZZ_p>& am, fstream& ofs) {\n  if (pid > 0) {\n    Write(ar, ofs);\n  }\n  Write(am, ofs);\n}\n\nvoid MPCEnv::BeaverWriteToFile(Mat<ZZ_p>& ar, Mat<ZZ_p>& am, fstream& ofs) {\n  if (pid > 0) {\n    Write(ar, ofs);\n  }\n  Write(am, ofs);\n}\n\nvoid MPCEnv::BeaverMultElem(Vec<ZZ_p>& ab, Vec<ZZ_p>& ar, Vec<ZZ_p>& am, Vec<ZZ_p>& br, Vec<ZZ_p>& bm, int fid) {\n  if (pid == 0) {\n    Vec<ZZ_p> ambm;\n    mul_elem(ambm, am, bm);\n    ab += ambm;\n  } else {\n\n    ZZ_pContext context;\n    context.save();\n\n    NTL_GEXEC_RANGE(ab.length() > Param::PAR_THRES, ab.length(), first, last)\n\n    context.restore();\n\n    for (int i = first; i < last; i++) {\n      ab[i] += ar[i] * bm[i];\n      ab[i] += am[i] * br[i];\n      if (pid == 1) {\n        ab[i] += ar[i] * br[i];\n      }\n    }\n\n    NTL_GEXEC_RANGE_END\n  }\n}\n\nvoid MPCEnv::BeaverMult(Mat<ZZ_p>& ab, Mat<ZZ_p>& ar, Mat<ZZ_p>& am, Mat<ZZ_p>& br, Mat<ZZ_p>& bm, bool elem_wise, int fid) {\n  if (pid == 0) {\n    Mat<ZZ_p> ambm;\n    if (elem_wise) {\n      mul_elem(ambm, am, bm);\n    } else {\n      mul(ambm, am, bm);\n    }\n    ab += ambm;\n  } else {\n    if (elem_wise) {\n\n      ZZ_pContext context;\n      context.save();\n\n      NTL_GEXEC_RANGE(ab.NumRows() > Param::PAR_THRES, ab.NumRows(), first, last)\n\n      context.restore();\n\n      for (int i = first; i < last; i++) {\n        for (int j = 0; j < ab.NumCols(); j++) {\n          ab[i][j] += ar[i][j] * bm[i][j];\n          ab[i][j] += am[i][j] * br[i][j];\n          if (pid == 1) {\n            ab[i][j] += ar[i][j] * br[i][j];\n          }\n        }\n      }\n\n      NTL_GEXEC_RANGE_END\n\n    } else {\n      ab += ar * bm;\n      ab += am * br;\n      if (pid == 1) {\n        ab += ar * br;\n      }\n    }\n  }\n}\n\nvoid MPCEnv::BeaverMultElem(Vec<ZZ>& ab, Vec<ZZ>& ar, Vec<ZZ>& am, Vec<ZZ>& br, Vec<ZZ>& bm, int fid) {\n  if (pid == 0) {\n    Vec<ZZ> ambm;\n    mul_elem(ambm, am, bm);\n    ab += ambm;\n  } else {\n    NTL_GEXEC_RANGE(ab.length() > Param::PAR_THRES, ab.length(), first, last)\n\n    for (int i = first; i < last; i++) {\n      ab[i] += ar[i] * bm[i];\n      ab[i] += am[i] * br[i];\n      if (pid == 1) {\n        ab[i] += ar[i] * br[i];\n      }\n    }\n\n    NTL_GEXEC_RANGE_END\n  }\n\n  Mod(ab, fid);\n}\n\nvoid MPCEnv::BeaverMult(Mat<ZZ>& ab, Mat<ZZ>& ar, Mat<ZZ>& am, Mat<ZZ>& br, Mat<ZZ>& bm, bool elem_wise, int fid) {\n  if (pid == 0) {\n    Mat<ZZ> ambm;\n    if (elem_wise) {\n      mul_elem(ambm, am, bm);\n    } else {\n      mul(ambm, am, bm);\n    }\n    ab += ambm;\n  } else {\n    if (elem_wise) {\n      NTL_GEXEC_RANGE(ab.NumRows() > Param::PAR_THRES, ab.NumRows(), first, last)\n\n      for (int i = first; i < last; i++) {\n        for (int j = 0; j < ab.NumCols(); j++) {\n          ab[i][j] += ar[i][j] * bm[i][j];\n          ab[i][j] += am[i][j] * br[i][j];\n          if (pid == 1) {\n            ab[i][j] += ar[i][j] * br[i][j];\n          }\n        }\n      }\n\n      NTL_GEXEC_RANGE_END\n\n    } else {\n      ab += ar * bm;\n      ab += am * br;\n      if (pid == 1) {\n        ab += ar * br;\n      }\n    }\n  }\n\n  Mod(ab, fid);\n}\n", "meta": {"hexsha": "600c055177428fe7608df03a19f02bd7d7e5295d", "size": 56533, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/mpc.cpp", "max_stars_repo_name": "nasrinakbari/HoonGit", "max_stars_repo_head_hexsha": "ea23a44241b4484f3cb738c1c41960ad2f1f92de", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2018-05-31T07:56:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-27T01:28:47.000Z", "max_issues_repo_path": "code/mpc.cpp", "max_issues_repo_name": "nasrinakbari/HoonGit", "max_issues_repo_head_hexsha": "ea23a44241b4484f3cb738c1c41960ad2f1f92de", "max_issues_repo_licenses": ["MIT"], "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/mpc.cpp", "max_forks_repo_name": "nasrinakbari/HoonGit", "max_forks_repo_head_hexsha": "ea23a44241b4484f3cb738c1c41960ad2f1f92de", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2018-05-31T07:56:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-04T21:29:11.000Z", "avg_line_length": 22.4159397304, "max_line_length": 125, "alphanum_fraction": 0.5115419313, "num_tokens": 20187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.6442251064863695, "lm_q1q2_score": 0.4900302477199526}}
{"text": "#include \"Polynomial.h\"\n#include <Eigen/Core>\n#include <random>\n#include \"testUtil.h\"\n#include <iostream>\n#include <typeinfo>\n\nusing namespace Eigen;\nusing namespace std;\n\ntemplate <typename CoefficientType>\nvoid testIntegralAndDerivative() {\n  VectorXd coefficients = VectorXd::Random(5);\n  Polynomial<CoefficientType> poly(coefficients);\n\n  cout << poly << endl;\n\n  cout << \"derivative: \" << poly.derivative(1) << endl;\n  \n  Polynomial<CoefficientType> third_derivative = poly.derivative(3);\n  \n  cout << \"third derivative: \" << third_derivative << endl;\n  Polynomial<CoefficientType> third_derivative_check = poly.derivative().derivative().derivative();\n  valuecheckMatrix(third_derivative.getCoefficients(), third_derivative_check.getCoefficients(), 1e-14);\n\n  Polynomial<CoefficientType> tenth_derivative = poly.derivative(10);\n  valuecheckMatrix(tenth_derivative.getCoefficients(), VectorXd::Zero(1), 1e-14);\n\n  Polynomial<CoefficientType> integral = poly.integral(0.0);\n  cout << \"integral: \" << integral << endl;\n  Polynomial<CoefficientType> poly_back = integral.derivative();\n  valuecheckMatrix(poly_back.getCoefficients(), poly.getCoefficients(), 1e-14);\n}\n\ntemplate <typename CoefficientType>\nvoid testOperators() {\n  int max_num_coefficients = 6;\n  int num_tests = 10;\n  default_random_engine generator;\n  std::uniform_int_distribution<> int_distribution(1, max_num_coefficients);\n  uniform_real_distribution<double> uniform;\n\n  for (int i = 0; i < num_tests; ++i) {\n    VectorXd coeff1 = VectorXd::Random(int_distribution(generator));\n    Polynomial<CoefficientType> poly1(coeff1);\n\n    VectorXd coeff2 = VectorXd::Random(int_distribution(generator));\n    Polynomial<CoefficientType> poly2(coeff2);\n\n    double scalar = uniform(generator);\n\n    cout << \"-------\" << endl;\n    cout << \"p1 = \" << poly1 << endl;\n    cout << \"p2 = \" << poly2 << endl;\n    cout << \"c = \" << scalar << endl;\n    \n    Polynomial<CoefficientType> sum = poly1 + poly2;\n    cout << \"p1+p2: \" << sum << endl;\n    Polynomial<CoefficientType> difference = poly2 - poly1;\n    cout << \"p2-p1: \" << difference << endl;\n    Polynomial<CoefficientType> product = poly1 * poly2;\n    cout << \"p1*p2: \" << product << endl;\n    Polynomial<CoefficientType> poly1_plus_scalar = poly1 + scalar;\n    cout << \"p1+c: \" << poly1_plus_scalar << endl;\n    Polynomial<CoefficientType> poly1_minus_scalar = poly1 - scalar;\n    cout << \"p1-c: \" << poly1_minus_scalar << endl;\n    Polynomial<CoefficientType> poly1_scaled = poly1 * scalar;\n    cout << \"p1*c: \" << poly1_scaled << endl;\n    Polynomial<CoefficientType> poly1_div = poly1 / scalar;\n    cout << \"p1/c: \" << poly1_div << endl;\n    Polynomial<CoefficientType> poly1_times_poly1 = poly1;\n    poly1_times_poly1 *= poly1_times_poly1;\n    cout << \"p1*p1\" << poly1_times_poly1 << endl;\n\n    double t = uniform(generator);\n    valuecheck(sum.value(t), poly1.value(t) + poly2.value(t), 1e-8);\n    valuecheck(difference.value(t), poly2.value(t) - poly1.value(t), 1e-8);\n    valuecheck(product.value(t), poly1.value(t) * poly2.value(t), 1e-8);\n    valuecheck(poly1_plus_scalar.value(t), poly1.value(t) + scalar, 1e-8);\n    valuecheck(poly1_minus_scalar.value(t), poly1.value(t) - scalar, 1e-8);\n    valuecheck(poly1_scaled.value(t), poly1.value(t) * scalar, 1e-8);\n    valuecheck(poly1_div.value(t), poly1.value(t) / scalar, 1e-8);\n    valuecheck(poly1_times_poly1.value(t), poly1.value(t) * poly1.value(t), 1e-8);\n  }\n}\n\ntemplate <typename CoefficientType>\nvoid testRoots() {\n  int max_num_coefficients = 6;\n  default_random_engine generator;\n  std::uniform_int_distribution<> int_distribution(1, max_num_coefficients);\n\n  int num_tests = 50;\n  for (int i = 0; i < num_tests; ++i) {\n    VectorXd coeffs = VectorXd::Random(int_distribution(generator));\n    Polynomial<CoefficientType> poly(coeffs);\n    auto roots = poly.roots();\n    valuecheck<DenseIndex>(roots.rows(), poly.getDegree());\n    for (int i = 0; i < roots.size(); i++) {\n      auto value = poly.value(roots[i]);\n      valuecheck(std::abs(value), 0.0, 1e-8);\n    }\n  }\n}\n\nvoid testEvalType() {\n  int max_num_coefficients = 6;\n  default_random_engine generator;\n  std::uniform_int_distribution<> int_distribution(1, max_num_coefficients);\n  VectorXd coeffs = VectorXd::Random(int_distribution(generator));\n  Polynomial<double> poly(coeffs);\n\n  auto valueIntInput = poly.value(1);\n  valuecheck(typeid(decltype(valueIntInput)) == typeid(double), true);\n\n  auto valueComplexInput = poly.value(std::complex<double>(1.0, 2.0));\n  valuecheck(typeid(decltype(valueComplexInput)) == typeid(std::complex<double>), true);\n}\n\ntemplate <typename CoefficientType>\nvoid testPolynomialMatrix() {\n  int max_matrix_rows_cols = 7;\n  int num_coefficients = 6;\n  default_random_engine generator;\n\n  uniform_int_distribution<> matrix_size_distribution(1, max_matrix_rows_cols);\n  int rows_A = matrix_size_distribution(generator);\n  int cols_A = matrix_size_distribution(generator);\n  int rows_B = cols_A;\n  int cols_B = matrix_size_distribution(generator);\n\n  auto A = Polynomial<CoefficientType>::randomPolynomialMatrix(num_coefficients, rows_A, cols_A);\n  auto B = Polynomial<CoefficientType>::randomPolynomialMatrix(num_coefficients, rows_B, cols_B);\n  auto C = Polynomial<CoefficientType>::randomPolynomialMatrix(num_coefficients, rows_A, cols_A);\n  auto product = A * B; // just verify that this is possible without crashing\n  auto sum = A + C;\n\n  uniform_real_distribution<double> uniform;\n  for (int row = 0; row < A.rows(); ++row) {\n    for (int col = 0; col < A.cols(); ++col) {\n      double t = uniform(generator);\n      valuecheck(sum(row, col).value(t), A(row, col).value(t) + C(row, col).value(t), 1e-8);\n    }\n  }\n\n  C.setZero(); // this was a problem before\n}\n\nint main(int argc, char **argv) {\n  testIntegralAndDerivative<double>();\n  testOperators<double>();\n  testRoots<double>();\n  testEvalType();\n  testPolynomialMatrix<double>();\n  return 0;\n}\n", "meta": {"hexsha": "047dacf672e04fe9584de9d7009c341a4ab19213", "size": 5921, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "drake/util/test/testPolynomial.cpp", "max_stars_repo_name": "ericmanzi/double_pendulum_lqr", "max_stars_repo_head_hexsha": "76bba3091295abb7d412c4a3156258918f280c96", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-04-16T09:54:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-29T21:59:27.000Z", "max_issues_repo_path": "drake/util/test/testPolynomial.cpp", "max_issues_repo_name": "ericmanzi/double_pendulum_lqr", "max_issues_repo_head_hexsha": "76bba3091295abb7d412c4a3156258918f280c96", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "drake/util/test/testPolynomial.cpp", "max_forks_repo_name": "ericmanzi/double_pendulum_lqr", "max_forks_repo_head_hexsha": "76bba3091295abb7d412c4a3156258918f280c96", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-08-24T20:32:03.000Z", "max_forks_repo_forks_event_max_datetime": "2017-08-24T20:32:03.000Z", "avg_line_length": 37.7133757962, "max_line_length": 104, "alphanum_fraction": 0.7052862692, "num_tokens": 1584, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442250928250375, "lm_q2_score": 0.760650658103136, "lm_q1q2_score": 0.49003024082391866}}
{"text": "#include <iostream>\n#include <cassert>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/successive_shortest_path_nonnegative_weights.hpp>\n#include <boost/graph/find_flow_cost.hpp>\n\ntypedef boost::adjacency_list_traits<boost::vecS, boost::vecS, boost::directedS> GraphTraits;\ntypedef boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS, boost::no_property,\n                              boost::property<boost::edge_capacity_t, long,\n                                              boost::property<boost::edge_residual_capacity_t, long,\n                                                              boost::property<boost::edge_reverse_t, GraphTraits::edge_descriptor,\n                                                                              boost::property<boost::edge_weight_t, long>>>>>\n    Graph;\n\nconst int debug_level = 0;\n\n#define DEBUG(min_level, x)      \\\n  if (debug_level >= min_level)  \\\n  {                              \\\n    std::cerr << x << std::endl; \\\n  }\n\nstruct Guide\n{\n  int x, y, d, e;\n};\n\nconst int impossible = -1;\n\nint find_upper_bound(std::function<bool(int)> is_match)\n{\n  assert(is_match(0));\n  int exponent = 0;\n  while (is_match(1 << exponent))\n  {\n    exponent++;\n  }\n\n  int low = exponent == 0 ? 0 : (1 << (exponent - 1));\n  int high = 1 << exponent;\n  while (low < high)\n  {\n    const int mid = (low + high) / 2;\n    if (is_match(mid))\n    {\n      low = mid + 1;\n    }\n    else\n    {\n      high = mid;\n    }\n  }\n\n  assert(is_match(low - 1) && !is_match(low));\n  return low - 1;\n}\n\nclass Testcase\n{\npublic:\n  void run()\n  {\n    std::cin >> c >> g >> b >> k >> a;\n    assert(c >= 2 && c <= 1e3);\n    assert(g >= 0 && g <= 5e3);\n    assert(b >= 0 && b <= 1e9);\n    assert(k >= 0 && k < c && a >= 0 && a < c && k != a);\n\n    int total_elephants = 0;\n    guides.resize(g);\n    for (int i = 0; i < g; i++)\n    {\n      Guide &gd = guides.at(i);\n      std::cin >> gd.x >> gd.y >> gd.d >> gd.e;\n      assert(gd.x >= 0 && gd.x < c && gd.y >= 0 && gd.y < c && gd.d >= 1 && gd.d <= 1e3 && gd.e >= 1 && gd.e <= 1e3);\n      total_elephants += gd.e;\n    }\n\n    // fast path for test set 2\n    {\n      const std::pair<int, int> result = calculate_cost(total_elephants);\n      const int suitcases = result.first, cost = result.second;\n      if (cost <= b)\n      {\n        std::cout << suitcases << \"\\n\";\n        return;\n      }\n    }\n\n    const int max_suitcases = find_upper_bound([this](int target_suitcases) {\n      assert(target_suitcases >= 0);\n      const std::pair<int, int> result = calculate_cost(target_suitcases);\n      const int suitcases = result.first, cost = result.second;\n      return suitcases == target_suitcases && cost <= b;\n    });\n    std::cout << max_suitcases << \"\\n\";\n  }\n\nprivate:\n  int c, g, b, k, a;\n  std::vector<Guide> guides;\n\n  std::pair<int, int> calculate_cost(const int max_suitcases)\n  {\n    assert(max_suitcases >= 0);\n\n    int next_free_node = 0;\n    const int node_source = next_free_node++;\n    const auto get_node_for_city = [next_free_node, this](int i) {\n      assert(i >= 0 && i < c);\n      return next_free_node + i;\n    };\n    next_free_node += c;\n    const auto get_node_for_guide = [next_free_node, this](int i) {\n      assert(i >= 0 && i < g);\n      return next_free_node + i;\n    };\n    next_free_node += g;\n    const int num_nodes = next_free_node;\n    Graph G(num_nodes);\n\n    const auto add_edge = [&G](int from, int to, long capacity, long cost) {\n      auto c_map = boost::get(boost::edge_capacity, G);\n      auto r_map = boost::get(boost::edge_reverse, G);\n      auto w_map = boost::get(boost::edge_weight, G);\n      const Graph::edge_descriptor e = boost::add_edge(from, to, G).first;\n      const Graph::edge_descriptor rev_e = boost::add_edge(to, from, G).first;\n      c_map[e] = capacity;\n      c_map[rev_e] = 0;\n      r_map[e] = rev_e;\n      r_map[rev_e] = e;\n      w_map[e] = cost;\n      w_map[rev_e] = -cost;\n      return e;\n    };\n\n    const Graph::edge_descriptor source_edge = add_edge(node_source, get_node_for_city(k), max_suitcases, 0);\n\n    for (int i = 0; i < g; i++)\n    {\n      Guide &gd = guides.at(i);\n      add_edge(get_node_for_city(gd.x), get_node_for_guide(i), gd.e, gd.d);\n      add_edge(get_node_for_guide(i), get_node_for_city(gd.y), gd.e, 0);\n    }\n\n    boost::successive_shortest_path_nonnegative_weights(G, node_source, get_node_for_city(a));\n\n    const int flow = boost::get(boost::edge_capacity, G)[source_edge] - boost::get(boost::edge_residual_capacity, G)[source_edge];\n    assert(flow >= 0 && flow <= max_suitcases);\n    const int cost = boost::find_flow_cost(G);\n    assert(cost >= 0);\n    return std::make_pair(flow, cost);\n  }\n};\n\nint main()\n{\n  std::ios_base::sync_with_stdio(false);\n\n  int t;\n  std::cin >> t;\n  for (int i = 0; i < t; i++)\n  {\n    Testcase().run();\n    DEBUG(1, \"\");\n  }\n\n  return 0;\n}", "meta": {"hexsha": "1c2bc781342f7ff2414ed8559b45e1b6d881daaa", "size": 4842, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "week-12/india/src/main.cpp", "max_stars_repo_name": "tehwalris/algolab", "max_stars_repo_head_hexsha": "489e0f6dd137336fa32b8002fc6eed8a7d35d87a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-17T08:21:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-17T08:21:32.000Z", "max_issues_repo_path": "week-12/india/src/main.cpp", "max_issues_repo_name": "tehwalris/algolab", "max_issues_repo_head_hexsha": "489e0f6dd137336fa32b8002fc6eed8a7d35d87a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "week-12/india/src/main.cpp", "max_forks_repo_name": "tehwalris/algolab", "max_forks_repo_head_hexsha": "489e0f6dd137336fa32b8002fc6eed8a7d35d87a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.650887574, "max_line_length": 130, "alphanum_fraction": 0.5710450227, "num_tokens": 1371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255927, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.4900302407290179}}
{"text": "#pragma once\n\n#include <polymesh/pm.hh>\n#include <typed-geometry/tg.hh>\n#include <Eigen/Dense>\n\nnamespace LayoutEmbedding\n{\n\nstruct SnakeVertex\n{\n    template <typename PosT>\n    PosT point(\n            const pm::vertex_attribute<PosT>& _pos) const\n    {\n        return tg::mix(_pos[h.vertex_from()], _pos[h.vertex_to()], lambda);\n    };\n\n    pm::halfedge_handle h;\n    double lambda;\n};\n\nstruct Snake\n{\n    std::vector<SnakeVertex> vertices;\n};\n\n/**\n * Compute a snake by intersecting a straight line\n * segment with a mesh parametrization in the plane.\n */\nSnake snake_from_parametrization(\n        const pm::vertex_attribute<tg::dpos2>& _param,\n        const pm::vertex_handle& _v_from,\n        const pm::vertex_handle& _v_to);\n\n/**\n * Turn the Snake into a pure vertex path by splitting edges.\n * Returns embedded path as sequence of vertices.\n */\ntemplate <typename PosT>\nstd::vector<pm::vertex_handle> embed_snake(\n        const Snake& _snake,\n        pm::Mesh& _mesh,\n        pm::vertex_attribute<PosT>& _pos);\n\n}\n", "meta": {"hexsha": "34813b16529e397d5822f09a73053e40b6bf6f4a", "size": 1021, "ext": "hh", "lang": "C++", "max_stars_repo_path": "library/LayoutEmbedding/Snake.hh", "max_stars_repo_name": "jsb/LayoutEmbedding", "max_stars_repo_head_hexsha": "6ef02ed0043dfabce6d593486358d6ef15cbf3ba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2021-02-18T15:35:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T07:20:37.000Z", "max_issues_repo_path": "library/LayoutEmbedding/Snake.hh", "max_issues_repo_name": "jsb/LayoutEmbedding", "max_issues_repo_head_hexsha": "6ef02ed0043dfabce6d593486358d6ef15cbf3ba", "max_issues_repo_licenses": ["MIT"], "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/LayoutEmbedding/Snake.hh", "max_forks_repo_name": "jsb/LayoutEmbedding", "max_forks_repo_head_hexsha": "6ef02ed0043dfabce6d593486358d6ef15cbf3ba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2021-02-17T14:52:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-05T09:51:25.000Z", "avg_line_length": 21.2708333333, "max_line_length": 75, "alphanum_fraction": 0.6718903036, "num_tokens": 257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255927, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.4900302407290179}}
{"text": "//==================================================================================================\n/*!\n\n  Copyright 2015 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#include <boost/simd/constant/sqrtvalmax.hpp>\n#include <boost/simd/constant/valmax.hpp>\n//#include <boost/simd/constant/itrunc.hpp>\n#include <boost/simd/as.hpp>\n#include <simd_test.hpp>\n//TODO\n// STF_CASE_TPL( \"Check sqrtvalmax behavior for integral types\"\n//             , (std::uint8_t)(std::uint16_t)(std::uint32_t)(std::uint64_t)\n//               (std::int8_t)(std::int16_t)(std::int32_t)(std::int64_t)\n//             )\n// {\n//   using boost::simd::as;\n//   using boost::simd::detail::sqrtvalmax;\n//   using boost::simd::Sqrtvalmax;\n//   using boost::simd::Valmax;\n\n//   STF_TYPE_IS(decltype(Sqrtvalmax<T>()), T);\n//   STF_EQUAL(Sqrtvalmax<T>(), boost::simd::isqrt(Valmax<T>());\n//   STF_EQUAL(sqrtvalmax( as(T{}) ),boost::simd::isqrt(Valmax<T>());\n// }\n\nSTF_CASE_TPL( \"Check sqrtvalmax behavior for floating types\"\n            , (double)(float)\n            )\n{\n  using boost::simd::as;\n  using boost::simd::detail::sqrtvalmax;\n  using boost::simd::Sqrtvalmax;\n  using boost::simd::Valmax;\n\n\n  STF_TYPE_IS(decltype(Sqrtvalmax<T>()), T);\n  auto z1 = Sqrtvalmax<T>();\n  STF_ULP_EQUAL(z1*z1, Valmax<T>(), 1.5);\n  auto z2 = sqrtvalmax( as(T{}) );\n  STF_ULP_EQUAL(z2*z2, Valmax<T>(), 1.5);\n}\n", "meta": {"hexsha": "e0eba2b47a5e61ee54b9dacd90bdfc546ab0a4b3", "size": 1574, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/constant/scalar/sqrtvalmax.cpp", "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": "test/constant/scalar/sqrtvalmax.cpp", "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": "test/constant/scalar/sqrtvalmax.cpp", "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.4893617021, "max_line_length": 100, "alphanum_fraction": 0.5654383736, "num_tokens": 441, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.49003023732845136}}
{"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//==================================================================================================\n#ifndef BOOST_SIMD_EULERIAN_HPP_INCLUDED\n#define BOOST_SIMD_EULERIAN_HPP_INCLUDED\n\nnamespace boost { namespace simd\n{\n  /*!\n    @ingroup group-functions\n    @defgroup group-euler Eulerian functions\n\n    Algorithms for computing scalar and SIMD versions of\n    some Eulerian functions. Mainly those that are present in\n    stdlibc++ 11.\n\n  **/\n\n} }\n\n#include <boost/simd/function/erfc.hpp>\n#include <boost/simd/function/erfcx.hpp>\n#include <boost/simd/function/erf.hpp>\n#include <boost/simd/function/gamma.hpp>\n#include <boost/simd/function/gammaln.hpp>\n#include <boost/simd/function/signgam.hpp>\n#include <boost/simd/function/stirling.hpp>\n\n#endif\n", "meta": {"hexsha": "1ef1fdae8847f43411a20f16d8d9ab06ab16e69b", "size": 1042, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/eulerian.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/eulerian.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/eulerian.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": 27.4210526316, "max_line_length": 100, "alphanum_fraction": 0.6065259117, "num_tokens": 215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118111485245, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.48996447825526707}}
{"text": "#ifndef ENTROPY_HPP_\n#define ENTROPY_HPP_\n\n#include <armadillo>\n\ndouble vNentropy(unsigned int k, arma::cx_dvec &psi);\ndouble diagentropy(unsigned int k, arma::cx_dvec &psi);\n\n#endif // ENTROPY_HPP_\n", "meta": {"hexsha": "cde1257f00ba4d6014220e426d22f6aa09d94421", "size": 199, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "c++/entropy.hpp", "max_stars_repo_name": "ikim-quantum/DecodeInterior", "max_stars_repo_head_hexsha": "c07649e8728c784dc1bd2a25602fec14a344a234", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "c++/entropy.hpp", "max_issues_repo_name": "ikim-quantum/DecodeInterior", "max_issues_repo_head_hexsha": "c07649e8728c784dc1bd2a25602fec14a344a234", "max_issues_repo_licenses": ["MIT"], "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++/entropy.hpp", "max_forks_repo_name": "ikim-quantum/DecodeInterior", "max_forks_repo_head_hexsha": "c07649e8728c784dc1bd2a25602fec14a344a234", "max_forks_repo_licenses": ["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.9, "max_line_length": 55, "alphanum_fraction": 0.7688442211, "num_tokens": 57, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4899644731945312}}
{"text": "// Copyright  (C)  2007  Ruben Smits <ruben dot smits at mech dot kuleuven dot be>\n\n// Version: 1.0\n// Author: Ruben Smits <ruben dot smits at mech dot kuleuven dot be>\n// Maintainer: Ruben Smits <ruben dot smits at mech dot kuleuven dot be>\n// URL: http://www.orocos.org/kdl\n\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 2.1 of the License, or (at your option) any later version.\n\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n// Lesser General Public License for more details.\n\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n#include \"articulatedbodyinertia.hpp\"\n\n#include <Eigen/Core>\n\nnamespace KDL{\n    \n  ArticulatedBodyInertia::ArticulatedBodyInertia(const RigidBodyInertia& rbi)\n    {\n        this->M=Eigen::Matrix3d::Identity()*rbi.m;\n        this->I=Eigen::Map<const Eigen::Matrix3d>(rbi.I.data);\n        this->H << 0,-rbi.h[2],rbi.h[1],\n            rbi.h[2],0,-rbi.h[0],\n            -rbi.h[1],rbi.h[0],0;\n    }\n    \n    ArticulatedBodyInertia::ArticulatedBodyInertia(double m, const Vector& c, const RotationalInertia& Ic)\n    {\n        *this = RigidBodyInertia(m,c,Ic);\n    }\n\n  ArticulatedBodyInertia::ArticulatedBodyInertia(const Eigen::Matrix3d& M, const Eigen::Matrix3d& H, const Eigen::Matrix3d& I)\n    {\n        this->M=M;\n        this->I=I;\n        this->H=H;\n    }\n    \n    ArticulatedBodyInertia operator*(double a,const ArticulatedBodyInertia& I){\n        return ArticulatedBodyInertia(a*I.M,a*I.H,a*I.I);\n    }\n    \n    ArticulatedBodyInertia operator+(const ArticulatedBodyInertia& Ia, const ArticulatedBodyInertia& Ib){\n        return ArticulatedBodyInertia(Ia.M+Ib.M,Ia.H+Ib.H,Ia.I+Ib.I);\n    }\n\n    ArticulatedBodyInertia operator+(const RigidBodyInertia& Ia, const ArticulatedBodyInertia& Ib){\n        return ArticulatedBodyInertia(Ia)+Ib;\n    }\n    ArticulatedBodyInertia operator-(const ArticulatedBodyInertia& Ia, const ArticulatedBodyInertia& Ib){\n        return ArticulatedBodyInertia(Ia.M-Ib.M,Ia.H-Ib.H,Ia.I-Ib.I);\n    }\n\n    ArticulatedBodyInertia operator-(const RigidBodyInertia& Ia, const ArticulatedBodyInertia& Ib){\n        return ArticulatedBodyInertia(Ia)-Ib;\n    }\n    \n    Wrench operator*(const ArticulatedBodyInertia& I,const Twist& t){\n        Wrench result;\n        Eigen::Vector3d::Map(result.force.data)=I.M*Eigen::Vector3d::Map(t.vel.data)+I.H.transpose()*Eigen::Vector3d::Map(t.rot.data);\n        Eigen::Vector3d::Map(result.torque.data)=I.I*Eigen::Vector3d::Map(t.rot.data)+I.H*Eigen::Vector3d::Map(t.vel.data);\n        return result;\n    }\n\n    ArticulatedBodyInertia operator*(const Frame& T,const ArticulatedBodyInertia& I){\n        Frame X=T.Inverse();\n        //mb=ma\n        //hb=R*(h-m*r)\n        //Ib = R(Ia+r x h x + (h-m*r) x r x)R'\n        Eigen::Map<Eigen::Matrix3d> E(X.M.data);\n        Eigen::Matrix3d rcross;\n        rcross << 0,-X.p[2],X.p[1],\n            X.p[2],0,-X.p[0],\n            -X.p[1],X.p[0],0;\n        \n        Eigen::Matrix3d HrM=I.H-rcross*I.M;\n        return ArticulatedBodyInertia(E*I.M*E.transpose(),E*HrM*E.transpose(),E*(I.I-rcross*I.H.transpose()+HrM*rcross)*E.transpose());\n    }\n\n    ArticulatedBodyInertia operator*(const Rotation& M,const ArticulatedBodyInertia& I){\n        Eigen::Map<const Eigen::Matrix3d> E(M.data);\n        return ArticulatedBodyInertia(E.transpose()*I.M*E,E.transpose()*I.H*E,E.transpose()*I.I*E);\n    }\n\n    ArticulatedBodyInertia ArticulatedBodyInertia::RefPoint(const Vector& p){\n        //mb=ma\n        //hb=R*(h-m*r)\n        //Ib = R(Ia+r x h x + (h-m*r) x r x)R'\n        Eigen::Matrix3d rcross;\n        rcross << 0,-p[2],p[1],\n            p[2],0,-p[0],\n            -p[1],p[0],0;\n        \n        Eigen::Matrix3d HrM=this->H-rcross*this->M;\n        return ArticulatedBodyInertia(this->M,HrM,this->I-rcross*this->H.transpose()+HrM*rcross);\n    }\n}//namespace\n", "meta": {"hexsha": "709096d63170ae6b9419a03da48b050af4f95dc9", "size": 4261, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdparty/kdl/src/articulatedbodyinertia.cpp", "max_stars_repo_name": "rocos-sia/rocos-app", "max_stars_repo_head_hexsha": "83aa8aa31dd303d77693cfc5ad48055d051fa4bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-12-06T15:30:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T13:21:40.000Z", "max_issues_repo_path": "3rdparty/kdl/src/articulatedbodyinertia.cpp", "max_issues_repo_name": "thinkexist1989/rocos-app", "max_issues_repo_head_hexsha": "7d6ab256c8212504b0a8bbe1ec1dea0c41ea3ff2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "3rdparty/kdl/src/articulatedbodyinertia.cpp", "max_forks_repo_name": "thinkexist1989/rocos-app", "max_forks_repo_head_hexsha": "7d6ab256c8212504b0a8bbe1ec1dea0c41ea3ff2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.4537037037, "max_line_length": 135, "alphanum_fraction": 0.6536024407, "num_tokens": 1314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4899644731945312}}
{"text": "#ifndef PYTHONIC_SCIPY_SPECIAL_SPHERICAL_JN_HPP\n#define PYTHONIC_SCIPY_SPECIAL_SPHERICAL_JN_HPP\n\n#include \"pythonic/include/scipy/special/spherical_jn.hpp\"\n\n#include \"pythonic/types/ndarray.hpp\"\n#include \"pythonic/utils/functor.hpp\"\n#include \"pythonic/utils/numpy_traits.hpp\"\n\n#define BOOST_MATH_THREAD_LOCAL thread_local\n#include <boost/math/special_functions/bessel.hpp>\n#include <boost/math/special_functions/bessel_prime.hpp>\n\nPYTHONIC_NS_BEGIN\n\nnamespace scipy\n{\n  namespace special\n  {\n    namespace details\n    {\n      template <class T0, class T1>\n      double spherical_jn(T0 v, T1 x, bool derivative)\n      {\n        assert(v == (long)v &&\n               \"only supported for integral value as first arg\");\n        using namespace boost::math::policies;\n        if (derivative) {\n          return boost::math::sph_bessel_prime(\n              v, x, make_policy(promote_double<true>()));\n        } else {\n          return boost::math::sph_bessel(v, x,\n                                         make_policy(promote_double<true>()));\n        }\n      }\n    }\n\n#define NUMPY_NARY_FUNC_NAME spherical_jn\n#define NUMPY_NARY_FUNC_SYM details::spherical_jn\n#include \"pythonic/types/numpy_nary_expr.hpp\"\n  }\n}\nPYTHONIC_NS_END\n\n#endif\n", "meta": {"hexsha": "45e2db2dc82c4bee5ca9445d3557c525e207b752", "size": 1231, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pythran/pythonic/scipy/special/spherical_jn.hpp", "max_stars_repo_name": "davidbrochart/pythran", "max_stars_repo_head_hexsha": "24b6c8650fe99791a4091cbdc2c24686e86aa67c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1647.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T01:45:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T01:23:41.000Z", "max_issues_repo_path": "pythran/pythonic/scipy/special/spherical_jn.hpp", "max_issues_repo_name": "davidbrochart/pythran", "max_issues_repo_head_hexsha": "24b6c8650fe99791a4091cbdc2c24686e86aa67c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1116.0, "max_issues_repo_issues_event_min_datetime": "2015-01-01T09:52:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-18T21:06:40.000Z", "max_forks_repo_path": "pythran/pythonic/scipy/special/spherical_jn.hpp", "max_forks_repo_name": "davidbrochart/pythran", "max_forks_repo_head_hexsha": "24b6c8650fe99791a4091cbdc2c24686e86aa67c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 180.0, "max_forks_repo_forks_event_min_datetime": "2015-02-12T02:47:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T10:28:18.000Z", "avg_line_length": 26.7608695652, "max_line_length": 78, "alphanum_fraction": 0.685621446, "num_tokens": 297, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706735, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4899644681337952}}
{"text": "//==================================================================================================\n/*!\n  @file\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_ERFCX_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_ERFCX_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n    @ingroup group-euler\n     This function object computes the  underflow-compensating (scaled) complementary  error function:\n   \\f$\\displaystyle e^{x^2}\\frac{2}{\\sqrt\\pi}\\int_{x}^{\\infty} e^{-t^2}\\mbox{d}t\\f$\n\n    @see erfc, erf\n\n\n    @par Header <boost/simd/function/erfcx.hpp>\n\n    @par Example:\n\n      @snippet erfcx.cpp erfcx\n\n    @par Possible output:\n\n      @snippet erfcx.txt erfcx\n  **/\n  IEEEValue erfcx(IEEEValue const& x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/erfcx.hpp>\n#include <boost/simd/function/simd/erfcx.hpp>\n\n#endif\n", "meta": {"hexsha": "7a1199c119b3c9edfe18fca5d48ecd0fa221271f", "size": 1107, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/erfcx.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/erfcx.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/erfcx.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": 25.7441860465, "max_line_length": 102, "alphanum_fraction": 0.5817524842, "num_tokens": 272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.48996446813379513}}
{"text": "#include <iostream>\n#include <vector>\n#include <fstream>\n#include <thread>\n#include <cmath>\n#include <chrono>\n\nusing namespace std;\n\n#include <boost/timer.hpp>\n\n// for sophus\n#include <sophus/se3.hpp>\n\nusing Sophus::SE3d;\n\n// for eigen\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\nusing namespace Eigen;\n\n#include <opencv2/core/core.hpp>\n#include <opencv2/imgcodecs/imgcodecs.hpp>\n\n\n#include \"constants.h\"\n#include \"cuda_wrapper.h\"\n#include \"kernels.cuh\"\n#include \"plot.h\"\n\nusing namespace cv;\n\n\n/**\n * Dataset from:\n * \n *   http://rpg.ifi.uzh.ch/datasets/remode_test_data.zip\n * \n * */\n\n\nvoid plotDepth(const Mat &depth_truth, const Mat &depth_estimate);\nvoid plotCur(const Mat &cur);\n\nbool readDatasetFiles(\n    const string &path,\n    vector<string> &color_image_files,\n    vector<SE3d> &poses,\n    cv::Mat &ref_depth\n);\n\nvoid showEpipolarMatch(const Mat &ref, const Mat &curr, const Vector2d &px_ref, const Vector2d &px_curr);\n\nvoid showEpipolarLine(const Mat &ref, const Mat &curr, const Vector2d &px_ref, const Vector2d &px_min_curr,\n                      const Vector2d &px_max_curr);\n\nvoid evaludateDepth(const Mat &depth_truth, const Mat &depth_estimate);\n\n\n\nint main(int argc, char **argv) {\n    if (argc != 2) {\n        cout << \"Usage: dense_mapping path_to_test_dataset\" << endl;\n        return -1;\n    }\n\n    // Read dataset\n    vector<string> color_image_files;\n    vector<SE3d> poses_TWC;\n    Mat ref_depth;\n    bool ret = readDatasetFiles(argv[1], color_image_files, poses_TWC, ref_depth);\n    if (ret == false) {\n        cout << \"Reading image files failed!\" << endl;\n        return -1;\n    }\n    cout << \"read total \" << color_image_files.size() << \" files.\" << endl;\n\n    // Initial depth image\n    Mat ref = imread(color_image_files[0], 0); // gray-scale image\n    SE3d pose_ref_TWC = poses_TWC[0];\n    double init_depth = 3.0;\n    double init_cov2 = 3.0;\n    Mat depth(height, width, CV_64F, init_depth);\n    Mat depth_cov2(height, width, CV_64F, init_cov2);\n\n    for (int index = 1; index < color_image_files.size(); index++) {\n        cout << \"*** loop \" << index << \" ***\" << endl;\n        Mat curr = imread(color_image_files[index], 0);\n        if (curr.data == nullptr) continue;\n        SE3d pose_curr_TWC = poses_TWC[index];\n        SE3d pose_T_C_R = pose_curr_TWC.inverse() * pose_ref_TWC;   // T_C_W * T_W_R = T_C_R\n        chrono::steady_clock::time_point t1 = chrono::steady_clock::now();\n        update_cuda(ref, curr, pose_T_C_R, depth, depth_cov2);\n        chrono::steady_clock::time_point t2 = chrono::steady_clock::now();\n\n        auto time_used = chrono::duration_cast<chrono::duration<double>>(t2 - t1);\n        std::cout << \"Time used: \" << time_used.count() << \"s\\n\";\n\n        evaludateDepth(ref_depth, depth);\n        plotDepth(ref_depth, depth);\n        plotCur(curr);\n        // imshow(\"image\", curr);\n        // waitKey(1);\n    }\n\n    cout << \"estimation returns, saving depth map ...\" << endl;\n    imwrite(\"depth.png\", depth);\n    cout << \"done.\" << endl;\n\n    return 0;\n}\n\nbool readDatasetFiles(\n    const string &path,\n    vector<string> &color_image_files,\n    std::vector<SE3d> &poses,\n    cv::Mat &ref_depth) {\n    ifstream fin(path + \"/first_200_frames_traj_over_table_input_sequence.txt\");\n    if (!fin) return false;\n\n    while (!fin.eof()) {\n        // \u6570\u636e\u683c\u5f0f\uff1a\u56fe\u50cf\u6587\u4ef6\u540d tx, ty, tz, qx, qy, qz, qw \uff0c\u6ce8\u610f\u662f TWC \u800c\u975e TCW\n        string image;\n        fin >> image;\n        double data[7];\n        for (double &d:data) fin >> d;\n\n        color_image_files.push_back(path + string(\"/images/\") + image);\n        poses.push_back(\n            SE3d(Quaterniond(data[6], data[3], data[4], data[5]),\n                 Vector3d(data[0], data[1], data[2]))\n        );\n        if (!fin.good()) break;\n    }\n    fin.close();\n\n    // load reference depth\n    fin.open(path + \"/depthmaps/scene_000.depth\");\n    ref_depth = cv::Mat(height, width, CV_64F);\n    if (!fin) return false;\n    for (int y = 0; y < height; y++)\n        for (int x = 0; x < width; x++) {\n            double depth = 0;\n            fin >> depth;\n            ref_depth.ptr<double>(y)[x] = depth / 100.0;\n        }\n\n    return true;\n}\n\n\n\nvoid evaludateDepth(const Mat &depth_truth, const Mat &depth_estimate) {\n    double ave_depth_error = 0;\n    double ave_depth_error_sq = 0;\n    int cnt_depth_data = 0;\n    for (int y = boarder; y < depth_truth.rows - boarder; y++)\n        for (int x = boarder; x < depth_truth.cols - boarder; x++) {\n            double error = depth_truth.ptr<double>(y)[x] - depth_estimate.ptr<double>(y)[x];\n            ave_depth_error += error;\n            ave_depth_error_sq += error * error;\n            cnt_depth_data++;\n        }\n    ave_depth_error /= cnt_depth_data;\n    ave_depth_error_sq /= cnt_depth_data;\n\n    cout << \"Average squared error = \" << ave_depth_error_sq << \", average error: \" << ave_depth_error << endl;\n}\n", "meta": {"hexsha": "dcbc4a364893446ce490285b658726aa94a5b7d2", "size": 4855, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch12/dense_mono/dense_mapping_custom_cuda.cpp", "max_stars_repo_name": "zinsmatt/slambook2", "max_stars_repo_head_hexsha": "3648caff838241553d9f3de332068eb0d501a7dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ch12/dense_mono/dense_mapping_custom_cuda.cpp", "max_issues_repo_name": "zinsmatt/slambook2", "max_issues_repo_head_hexsha": "3648caff838241553d9f3de332068eb0d501a7dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch12/dense_mono/dense_mapping_custom_cuda.cpp", "max_forks_repo_name": "zinsmatt/slambook2", "max_forks_repo_head_hexsha": "3648caff838241553d9f3de332068eb0d501a7dc", "max_forks_repo_licenses": ["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.5588235294, "max_line_length": 111, "alphanum_fraction": 0.6187435633, "num_tokens": 1326, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.48996446307305885}}
{"text": "/*    This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.\n *    See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.\n *    Author(s):       Siargey Kachanovich\n *\n *    Copyright (C) 2019 Inria\n *\n *    Modification(s):\n *      - YYYY/MM Author: Description of the modification\n */\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE \"cell_complex\"\n#include <boost/test/unit_test.hpp>\n#include <gudhi/Unitary_tests_utils.h>\n\n#include <gudhi/Debug_utils.h>\n#include <gudhi/IO/output_debug_traces_to_html.h>\n#include <iostream>\n\n#include <gudhi/Coxeter_triangulation.h>\n#include <gudhi/Functions/Function_Sm_in_Rd.h>\n#include <gudhi/Functions/Function_torus_in_R3.h>\n#include <gudhi/Implicit_manifold_intersection_oracle.h>\n#include <gudhi/Manifold_tracing.h>\n#include <gudhi/Coxeter_triangulation/Cell_complex/Cell_complex.h>\n\nusing namespace Gudhi::coxeter_triangulation;\n\nBOOST_AUTO_TEST_CASE(cell_complex) {\n  double radius = 1.1111;\n  Function_torus_in_R3 fun_torus(radius, 3 * radius);\n  Eigen::VectorXd seed = fun_torus.seed();\n  Function_Sm_in_Rd fun_bound(2.5 * radius, 2, seed);\n\n  auto oracle = make_oracle(fun_torus, fun_bound);\n  double lambda = 0.2;\n  Coxeter_triangulation<> cox_tr(oracle.amb_d());\n  cox_tr.change_offset(Eigen::VectorXd::Random(oracle.amb_d()));\n  cox_tr.change_matrix(lambda * cox_tr.matrix());\n\n  using MT = Manifold_tracing<Coxeter_triangulation<> >;\n  using Out_simplex_map = typename MT::Out_simplex_map;\n  std::vector<Eigen::VectorXd> seed_points(1, seed);\n  Out_simplex_map interior_simplex_map, boundary_simplex_map;\n  manifold_tracing_algorithm(seed_points, cox_tr, oracle, interior_simplex_map, boundary_simplex_map);\n\n  std::size_t intr_d = oracle.amb_d() - oracle.cod_d();\n  Cell_complex<Out_simplex_map> cell_complex(intr_d);\n  cell_complex.construct_complex(interior_simplex_map, boundary_simplex_map);\n\n  std::size_t interior_sc_map_size0 = cell_complex.interior_simplex_cell_map(0).size();\n  std::size_t interior_sc_map_size1 = cell_complex.interior_simplex_cell_map(1).size();\n  std::size_t interior_sc_map_size2 = cell_complex.interior_simplex_cell_map(2).size();\n  std::size_t boundary_sc_map_size0 = cell_complex.boundary_simplex_cell_map(0).size();\n  std::size_t boundary_sc_map_size1 = cell_complex.boundary_simplex_cell_map(1).size();\n  BOOST_CHECK(interior_simplex_map.size() == interior_sc_map_size0);\n  BOOST_CHECK(boundary_sc_map_size0 - boundary_sc_map_size1 == 0);\n  BOOST_CHECK(interior_sc_map_size0 - interior_sc_map_size1 + interior_sc_map_size2 == 0);\n}\n", "meta": {"hexsha": "4f7f3ec5e662580d20c9f80e99f8f34cdd0af9a4", "size": 2598, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Coxeter_triangulation/test/cell_complex_test.cpp", "max_stars_repo_name": "VincentRouvreau/gudhi-devel", "max_stars_repo_head_hexsha": "c6a7f0258406542b0c2b10bb6b2878f27b13394b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-05T05:45:06.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-05T05:45:06.000Z", "max_issues_repo_path": "src/Coxeter_triangulation/test/cell_complex_test.cpp", "max_issues_repo_name": "gspr/gudhi-devel", "max_issues_repo_head_hexsha": "6b8f24647a6f290f4e2f2f307de660dfae93cc90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Coxeter_triangulation/test/cell_complex_test.cpp", "max_forks_repo_name": "gspr/gudhi-devel", "max_forks_repo_head_hexsha": "6b8f24647a6f290f4e2f2f307de660dfae93cc90", "max_forks_repo_licenses": ["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.3, "max_line_length": 102, "alphanum_fraction": 0.7821401078, "num_tokens": 720, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.826711776992821, "lm_q2_score": 0.5926665999540697, "lm_q1q2_score": 0.48996445801232225}}
{"text": "//---------------------------------------------------------------------------//\r\n// Copyright (c) 2013 Kyle Lutz <kyle.r.lutz@gmail.com>\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://boostorg.github.com/compute for more information.\r\n//---------------------------------------------------------------------------//\r\n\r\n#define BOOST_TEST_MODULE TestBinarySearch\r\n#include <boost/test/unit_test.hpp>\r\n\r\n#include <iterator>\r\n\r\n#include <boost/compute/command_queue.hpp>\r\n#include <boost/compute/algorithm/binary_search.hpp>\r\n#include <boost/compute/algorithm/fill.hpp>\r\n#include <boost/compute/algorithm/lower_bound.hpp>\r\n#include <boost/compute/algorithm/upper_bound.hpp>\r\n#include <boost/compute/container/vector.hpp>\r\n\r\n#include \"context_setup.hpp\"\r\n\r\nBOOST_AUTO_TEST_CASE(binary_search_int)\r\n{\r\n    // test data = { 1, ..., 2, ..., 4, 4, 5, 7, ..., 9, ..., 10 }\r\n    boost::compute::vector<int> vector(size_t(4096), int(1), queue);\r\n    boost::compute::vector<int>::iterator first = vector.begin() + 128;\r\n    boost::compute::vector<int>::iterator last = first + (1024 - 128);\r\n    boost::compute::fill(first, last, int(2), queue);\r\n    last.write(4, queue); last++;\r\n    last.write(4, queue); last++;\r\n    last.write(5, queue); last++;\r\n    first = last;\r\n    last = first + 127;\r\n    boost::compute::fill(first, last, 7, queue);\r\n    first = last;\r\n    last = vector.end() - 1;\r\n    boost::compute::fill(first, last, 9, queue);\r\n    last.write(10, queue);\r\n    queue.finish();\r\n\r\n    BOOST_CHECK(boost::compute::binary_search(vector.begin(), vector.end(), int(0), queue) == false);\r\n    BOOST_CHECK(boost::compute::binary_search(vector.begin(), vector.end(), int(1), queue) == true);\r\n    BOOST_CHECK(boost::compute::binary_search(vector.begin(), vector.end(), int(2), queue) == true);\r\n    BOOST_CHECK(boost::compute::binary_search(vector.begin(), vector.end(), int(3), queue) == false);\r\n    BOOST_CHECK(boost::compute::binary_search(vector.begin(), vector.end(), int(4), queue) == true);\r\n    BOOST_CHECK(boost::compute::binary_search(vector.begin(), vector.end(), int(5), queue) == true);\r\n    BOOST_CHECK(boost::compute::binary_search(vector.begin(), vector.end(), int(6), queue) == false);\r\n    BOOST_CHECK(boost::compute::binary_search(vector.begin(), vector.end(), int(7), queue) == true);\r\n    BOOST_CHECK(boost::compute::binary_search(vector.begin(), vector.end(), int(8), queue) == false);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(range_bounds_int)\r\n{\r\n    // test data = { 1, ..., 2, ..., 4, 4, 5, 7, ..., 9, ..., 10 }\r\n    boost::compute::vector<int> vector(size_t(4096), int(1), queue);\r\n    boost::compute::vector<int>::iterator first = vector.begin() + 128;\r\n    boost::compute::vector<int>::iterator last = first + (1024 - 128);\r\n    boost::compute::fill(first, last, int(2), queue);\r\n    last.write(4, queue); last++; // 1024\r\n    last.write(4, queue); last++; // 1025\r\n    last.write(5, queue); last++; // 1026\r\n    first = last;\r\n    last = first + 127;\r\n    boost::compute::fill(first, last, 7, queue);\r\n    first = last;\r\n    last = vector.end() - 1;\r\n    boost::compute::fill(first, last, 9, queue);\r\n    last.write(10, queue);\r\n    queue.finish();\r\n\r\n    BOOST_CHECK(boost::compute::lower_bound(vector.begin(), vector.end(), int(0), queue) == vector.begin());\r\n    BOOST_CHECK(boost::compute::upper_bound(vector.begin(), vector.end(), int(0), queue) == vector.begin());\r\n\r\n    BOOST_CHECK(boost::compute::lower_bound(vector.begin(), vector.end(), int(1), queue) == vector.begin());\r\n    BOOST_CHECK(boost::compute::upper_bound(vector.begin(), vector.end(), int(1), queue) == vector.begin() + 128);\r\n\r\n    BOOST_CHECK(boost::compute::lower_bound(vector.begin(), vector.end(), int(2), queue) == vector.begin() + 128);\r\n    BOOST_CHECK(boost::compute::upper_bound(vector.begin(), vector.end(), int(2), queue) == vector.begin() + 1024);\r\n\r\n    BOOST_CHECK(boost::compute::lower_bound(vector.begin(), vector.end(), int(4), queue) == vector.begin() + 1024);\r\n    BOOST_CHECK(boost::compute::upper_bound(vector.begin(), vector.end(), int(4), queue) == vector.begin() + 1026);\r\n\r\n    BOOST_CHECK(boost::compute::lower_bound(vector.begin(), vector.end(), int(5), queue) == vector.begin() + 1026);\r\n    BOOST_CHECK(boost::compute::upper_bound(vector.begin(), vector.end(), int(5), queue) == vector.begin() + 1027);\r\n\r\n    BOOST_CHECK(boost::compute::lower_bound(vector.begin(), vector.end(), int(6), queue) == vector.begin() + 1027);\r\n    BOOST_CHECK(boost::compute::upper_bound(vector.begin(), vector.end(), int(6), queue) == vector.begin() + 1027);\r\n\r\n    BOOST_CHECK(boost::compute::lower_bound(vector.begin(), vector.end(), int(7), queue) == vector.begin() + 1027);\r\n    BOOST_CHECK(boost::compute::upper_bound(vector.begin(), vector.end(), int(7), queue) == vector.begin() + (1027 + 127));\r\n\r\n    BOOST_CHECK(boost::compute::lower_bound(vector.begin(), vector.end(), int(9), queue) == vector.begin() + (1027 + 127));\r\n    BOOST_CHECK(boost::compute::upper_bound(vector.begin(), vector.end(), int(9), queue) == vector.end() - 1);\r\n\r\n    BOOST_CHECK(boost::compute::lower_bound(vector.begin(), vector.end(), int(10), queue) == vector.end() - 1);\r\n    BOOST_CHECK(boost::compute::upper_bound(vector.begin(), vector.end(), int(10), queue) == vector.end());\r\n}\r\n\r\nBOOST_AUTO_TEST_SUITE_END()\r\n", "meta": {"hexsha": "dbc3c7ea14cc3ed56aa054374e4f90fea65034bf", "size": 5428, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/compute/test/test_binary_search.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": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/compute/test/test_binary_search.cpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-04T18:00:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-04T18:00:00.000Z", "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/compute/test/test_binary_search.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 52.6990291262, "max_line_length": 124, "alphanum_fraction": 0.6306190125, "num_tokens": 1371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743735019594, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.4899383548752504}}
{"text": "///////////////////////////////////////////////////////////////////\n//  Copyright Eduardo Quintana 2021\n//  Copyright Janek Kozicki 2021\n//  Copyright Christopher Kormanyos 2021\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#ifndef BOOST_MATH_FFT_TEST_HELPERS_HPP\n  #define BOOST_MATH_FFT_TEST_HELPERS_HPP\n\n#include <boost/math/fft/algorithms.hpp>\n  #include <boost/math/fft/dft_api.hpp>\n\nnamespace boost { namespace math { namespace fft {\n\n//template<class NativeComplexType, class allocator_t = std::allocator<NativeComplexType>>\n//class test_complex_dft_prime_rader\n//{\n//  /*\n//    Special backend for testing the complex_dft_prime_rader implementation\n//  */\n//public:  \n//  using value_type      = NativeComplexType;\n//  using real_value_type = typename NativeComplexType::value_type;\n//  using allocator_type  = allocator_t;\n//public:\n//  constexpr test_complex_dft_prime_rader(\n//    std::size_t n,\n//    const allocator_type& that_alloc = allocator_type{})\n//    : my_size{n}, alloc{that_alloc}\n//  { }\n//  \n//  void resize(std::size_t new_size)\n//  {\n//    my_size = new_size;\n//  }\n//  constexpr std::size_t size() const { return my_size; }\n//\n//  void forward(const NativeComplexType* in, NativeComplexType* out) const\n//  {\n//    detail::complex_dft_prime_rader(in,in+size(),out,1,alloc);\n//  }\n//\n//  void backward(const NativeComplexType* in, NativeComplexType* out) const\n//  {\n//    detail::complex_dft_prime_rader(in,in+size(),out,-1,alloc);\n//  }\n//private:\n//  std::size_t my_size;\n//  allocator_type alloc;\n//};\n//  \n//template<class RingType, class Allocator_t = std::allocator<RingType> >\n//using rader_dft = detail::dft< test_complex_dft_prime_rader<RingType,Allocator_t> >;\n//\n//template<class NativeComplexType, class allocator_t = std::allocator<NativeComplexType>>\n//class test_dft_prime_bruteForce\n//{\n//  /*\n//    Special backend for testing the dft_prime_bruteForce implementation\n//  */\n//public:\n//  using value_type      = NativeComplexType;\n//  using real_value_type = typename NativeComplexType::value_type;\n//  using allocator_type  = allocator_t;\n//  \n//  constexpr test_dft_prime_bruteForce(\n//    std::size_t n, \n//    const allocator_type& that_alloc = allocator_type{})\n//    : my_size{n}, alloc{that_alloc}\n//  { }\n//\n//  void resize(std::size_t new_size)\n//  {\n//    my_size = new_size;\n//  }\n//  constexpr std::size_t size() const { return my_size; }\n//\n//  void forward(const NativeComplexType* in, NativeComplexType* out) const\n//  {\n//    NativeComplexType w{detail::complex_root_of_unity<NativeComplexType>(size())};\n//    detail::dft_prime_bruteForce(in,in+size(),out,w,alloc);\n//  }\n//\n//  void backward(const NativeComplexType* in, NativeComplexType* out) const\n//  {\n//    NativeComplexType w{detail::complex_inverse_root_of_unity<NativeComplexType>(size())};\n//    detail::dft_prime_bruteForce(in,in+size(),out,w,alloc);\n//  }\n//\n//private:\n//  std::size_t my_size;\n//  allocator_type alloc;\n//};\n//\n//template<class RingType, class Allocator_t = std::allocator<RingType> >\n//using bruteForce_dft = detail::dft< test_dft_prime_bruteForce<RingType,Allocator_t> >;\n//\n//template<class NativeComplexType, class allocator_t = std::allocator<NativeComplexType>>\n//class test_complex_dft_prime_bruteForce\n//{\n//  /*\n//    Special backend for testing the complex_dft_prime_bruteForce implementation\n//  */\n//public:\n//  using value_type      = NativeComplexType;\n//  using real_value_type = typename NativeComplexType::value_type;\n//  using allocator_type  = allocator_t;\n//  \n//  constexpr test_complex_dft_prime_bruteForce(\n//    std::size_t n, \n//    const allocator_type& that_alloc = allocator_type{})\n//    : my_size{n}, alloc{that_alloc}\n//  { }\n//\n//  void resize(std::size_t new_size)\n//  {\n//    my_size = new_size;\n//  }\n//  constexpr std::size_t size() const { return my_size; }\n//\n//  void forward(const NativeComplexType* in, NativeComplexType* out) const\n//  {\n//    detail::complex_dft_prime_bruteForce(in,in+size(),out,1,alloc);\n//  }\n//\n//  void backward(const NativeComplexType* in, NativeComplexType* out) const\n//  {\n//    detail::complex_dft_prime_bruteForce(in,in+size(),out,-1,alloc);\n//  }\n//\n//private:\n//  std::size_t my_size;\n//  allocator_type alloc;\n//};\n//\n//template<class RingType, class Allocator_t = std::allocator<RingType> >\n//using bruteForce_cdft = detail::dft< test_complex_dft_prime_bruteForce<RingType,Allocator_t> >;\n//\n//\n//template<class NativeComplexType, class allocator_t = std::allocator<NativeComplexType>>\n//class test_dft_composite\n//{\n//  /*\n//    Special backend for testing the dft_composite\n//  */\n//public:\n//  using value_type = NativeComplexType;\n//  using real_value_type = typename NativeComplexType::value_type;\n//  using allocator_type  = allocator_t ;\n//  \n//  constexpr test_dft_composite(\n//    std::size_t n,\n//    const allocator_type& that_alloc = allocator_type{}\n//    )\n//    : my_size{n}, alloc{that_alloc}\n//  { }\n//\n//  void resize(std::size_t new_size)\n//  {\n//    my_size = new_size;\n//  }\n//  constexpr std::size_t size() const { return my_size; }\n//\n//  void forward(const NativeComplexType* in, NativeComplexType* out) const\n//  {\n//    NativeComplexType w{detail::complex_root_of_unity<NativeComplexType>(size())};\n//    detail::dft_composite(in,in+size(),out,w,alloc);\n//  }\n//\n//  void backward(const NativeComplexType* in, NativeComplexType* out) const\n//  {\n//    NativeComplexType w{detail::complex_inverse_root_of_unity<NativeComplexType>(size())};\n//    detail::dft_composite(in,in+size(),out,w,alloc);\n//  }\n//\n//private:\n//  std::size_t my_size;\n//  allocator_type alloc;\n//};\n//\n//template<class RingType, class Allocator_t = std::allocator<RingType> >\n//using composite_dft = detail::dft< test_dft_composite<RingType,Allocator_t> >;\n//\n//template<class NativeComplexType, class allocator_t = std::allocator<NativeComplexType>>\n//class test_complex_dft_composite\n//{\n//  /*\n//    Special backend for testing the complex_dft_composite\n//  */\n//public:\n//  using value_type = NativeComplexType;\n//  using real_value_type = typename NativeComplexType::value_type;\n//  using allocator_type  = allocator_t ;\n//  \n//  constexpr test_complex_dft_composite(\n//    std::size_t n,\n//    const allocator_type& that_alloc = allocator_type{})\n//    : my_size{n}, alloc{that_alloc}\n//  { }\n//\n//  void resize(std::size_t new_size)\n//  {\n//    my_size = new_size;\n//  }\n//  constexpr std::size_t size() const { return my_size; }\n//\n//  void forward(const NativeComplexType* in, NativeComplexType* out) const\n//  {\n//    detail::complex_dft_composite(in,in+size(),out,1,alloc);\n//  }\n//\n//  void backward(const NativeComplexType* in, NativeComplexType* out) const\n//  {\n//    detail::complex_dft_composite(in,in+size(),out,-1,alloc);\n//  }\n//\n//private:\n//  std::size_t my_size;\n//  allocator_type alloc;\n//};\n//\n//template<class RingType, class Allocator_t = std::allocator<RingType> >\n//using composite_cdft = detail::dft< test_complex_dft_composite<RingType,Allocator_t> >;\n//\n//  \n//template<class NativeComplexType, class allocator_t = std::allocator<NativeComplexType>>\n//class test_dft_power2\n//{\n//  /*\n//    Special backend for testing the dft_power2 implementation\n//  */\n//public:\n//  using value_type = NativeComplexType;\n//  using real_value_type = typename NativeComplexType::value_type;\n//  using allocator_type  = allocator_t ;\n//  constexpr test_dft_power2(\n//    std::size_t n,\n//    const allocator_type& that_alloc = allocator_type{})\n//    : my_size{n}, alloc{that_alloc}\n//  { }\n//\n//  void resize(std::size_t new_size)\n//  {\n//    my_size = new_size;\n//  }\n//  constexpr std::size_t size() const { return my_size; }\n//\n//  void forward(const NativeComplexType* in, NativeComplexType* out) const\n//  {\n//    NativeComplexType w{detail::complex_inverse_root_of_unity<NativeComplexType>(size())};\n//    detail::dft_power2(in,in+size(),out,w);\n//  }\n//\n//  void backward(const NativeComplexType* in, NativeComplexType* out) const\n//  {\n//    NativeComplexType w{detail::complex_root_of_unity<NativeComplexType>(size())};\n//    detail::dft_power2(in,in+size(),out,w);\n//  }\n//\n//private:\n//  std::size_t my_size;\n//  allocator_type alloc;\n//};\n//\n//template<class RingType, class Allocator_t = std::allocator<RingType> >\n//using power2_dft = detail::dft< test_dft_power2<RingType> >;\n//\n//\n//template<class NativeComplexType, class allocator_t = std::allocator<NativeComplexType>>\n//class test_complex_dft_power2\n//{\n//  /*\n//    Special backend for testing the complex_dft_power2 implementation\n//  */\n//public:\n//  using value_type = NativeComplexType;\n//  using real_value_type = typename NativeComplexType::value_type;\n//  using allocator_type  = allocator_t ;\n//  \n//  constexpr test_complex_dft_power2(\n//    std::size_t n,\n//    const allocator_type& that_alloc = allocator_type{})\n//    : my_size{n}, alloc{that_alloc}\n//  { }\n//\n//  void resize(std::size_t new_size)\n//  {\n//    my_size = new_size;\n//  }\n//  constexpr std::size_t size() const { return my_size; }\n//\n//  void forward(const NativeComplexType* in, NativeComplexType* out) const\n//  {\n//    detail::complex_dft_power2(in,in+size(),out,1);\n//  }\n//\n//  void backward(const NativeComplexType* in, NativeComplexType* out) const\n//  {\n//    detail::complex_dft_power2(in,in+size(),out,-1);\n//  }\n//\n//private:\n//  std::size_t my_size;\n//  allocator_type alloc;\n//};\n//\n//template<class RingType, class Allocator_t = std::allocator<RingType> >\n//using power2_cdft = detail::dft< test_complex_dft_power2<RingType> >;\n\nnamespace my_modulo_lib\n{\n  template <typename T, T x>\n  class field_modulo\n  {\n   public:\n    typedef T integer;\n    static constexpr T mod = x;\n  };\n\n  /*\n      Modular Integers\n  */\n  template <typename Field>\n  class mint;\n\n  template <typename Field>\n  std::ostream& operator<<(std::ostream& os, const mint<Field>& A)\n  {\n    return os << A.x << \" (mod \" << Field::mod << \")\";\n  }\n  template <typename Field>\n  class mint\n  {\n    typedef typename Field::integer integer;\n    integer x;\n\n   public:\n    constexpr mint() : x{0} {}\n\n    mint(integer _x) : x{_x}\n    {\n      x %= Field::mod;\n      if (x < 0)\n        x += Field::mod;\n    }\n\n    mint(const mint<Field>& that) : x{that.x} {}\n\n    mint<Field>& operator=(const mint<Field>& that)\n    {\n      return x = that.x, *this;\n    }\n\n    // explicit operator bool() const { return x == integer{0}; }\n    operator integer() const { return x; }\n\n    mint<Field>& operator+=(const mint<Field>& that)\n    {\n      return x = (x + that.x) % Field::mod, *this;\n    }\n\n    mint<Field>& operator*=(const mint<Field>& t)\n    {\n      // direct multiplication\n      x = (x * t.x) % Field::mod;\n      return *this;\n    }\n    bool operator==(const mint<Field>& that) const { return x == that.x; }\n    bool operator!=(const mint<Field>& that) const { return x != that.x; }\n\n    mint<Field> inverse() const { return ::boost::math::fft::detail::power(*this, Field::mod - 2); }\n\n    friend std::ostream& operator<<<Field>(std::ostream& os,\n                                           const mint<Field>& A);\n  };\n\n  template <typename T>\n  mint<T> operator+(const mint<T>& A, const mint<T>& B)\n  {\n    mint<T> C{A};\n    return C += B;\n  }\n  template <typename T>\n  mint<T> operator*(const mint<T>& A, const mint<T>& B)\n  {\n    mint<T> C{A};\n    return C *= B;\n  }\n  template <typename T>\n  mint<T>& operator/=(mint<T>& A, const mint<T>& B)\n  {\n    return A *= B.inverse();\n  }\n  template <typename T>\n  mint<T> operator/(const mint<T>& A, const mint<T>& B)\n  {\n    mint<T> C{A};\n    return C /= B;\n  }\n}  // namespace my_modulo_lib\n\n}}} // namespace boost::math::fft\n  \n#endif // BOOST_MATH_FFT_TEST_HELPERS_HPP\n", "meta": {"hexsha": "9910f4479a88cbe7c9ca3c26510737b1d341cd24", "size": 11786, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/fft_test_helpers.hpp", "max_stars_repo_name": "BoostGSoC21/math", "max_stars_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "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": "test/fft_test_helpers.hpp", "max_issues_repo_name": "BoostGSoC21/math", "max_issues_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 30.0, "max_issues_repo_issues_event_min_datetime": "2021-06-22T12:59:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-02T09:27:49.000Z", "max_forks_repo_path": "test/fft_test_helpers.hpp", "max_forks_repo_name": "BoostGSoC21/math", "max_forks_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-07T21:15:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-07T21:15:02.000Z", "avg_line_length": 28.9582309582, "max_line_length": 100, "alphanum_fraction": 0.6694383166, "num_tokens": 3236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.4899383522240317}}
{"text": "// ALGOLAB BGL Tutorial 3\n// Flow example demonstrating\n// - breadth first search (BFS) on the residual graph\n\n// Compile and run with one of the following:\n// g++ -std=c++11 -O2 bgl_residual_bfs.cpp -o bgl_residual_bfs ./bgl_residual_bfs\n// g++ -std=c++11 -O2 -I path/to/boost_1_58_0 bgl_residual_bfs.cpp -o bgl_residual_bfs; ./bgl_residual_bfs\n\n// Includes\n// ========\n// STL includes\n#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <queue>\n// BGL includes\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/cycle_canceling.hpp>\n#include <boost/graph/push_relabel_max_flow.hpp>\n#include <boost/graph/successive_shortest_path_nonnegative_weights.hpp>\n#include <boost/graph/find_flow_cost.hpp>\n\n// Graph Type with nested interior edge properties for Cost Flow Algorithms\ntypedef boost::adjacency_list_traits<boost::vecS, boost::vecS, boost::directedS> traits;\ntypedef boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS, boost::no_property,\n    boost::property<boost::edge_capacity_t, long,\n        boost::property<boost::edge_residual_capacity_t, long,\n            boost::property<boost::edge_reverse_t, traits::edge_descriptor,\n                boost::property <boost::edge_weight_t, long> > > > > graph; // new! weightmap corresponds to costs\n\ntypedef boost::graph_traits<graph>::edge_descriptor             edge_desc;\ntypedef boost::graph_traits<graph>::out_edge_iterator           out_edge_it; // Iterator\n\n// Custom edge adder class\nclass edge_adder {\n graph &G;\n\n public:\n  explicit edge_adder(graph &G) : G(G) {}\n  void add_edge(int from, int to, long capacity, long cost) {\n    auto c_map = boost::get(boost::edge_capacity, G);\n    auto r_map = boost::get(boost::edge_reverse, G);\n    auto w_map = boost::get(boost::edge_weight, G); // new!\n    const edge_desc e = boost::add_edge(from, to, G).first;\n    const edge_desc rev_e = boost::add_edge(to, from, G).first;\n    c_map[e] = capacity;\n    c_map[rev_e] = 0; // reverse edge has no capacity!\n    r_map[e] = rev_e;\n    r_map[rev_e] = e;\n    w_map[e] = cost;   // new assign cost\n    w_map[rev_e] = -cost;   // new negative cost\n  }\n};\n\n\n// Main\nvoid testcase() {\n  // build graph\n  int n, m, s;\n  std::cin >> n >> m >> s;\n  graph G(n + m + s);\n  edge_adder adder(G);\n  // auto rc_map = boost::get(boost::edge_residual_capacity, G);\n  const int v_source = boost::add_vertex(G);\n  const int v_sink = boost::add_vertex(G);\n  \n  auto c_map = boost::get(boost::edge_capacity, G);\n  auto rc_map = boost::get(boost::edge_residual_capacity, G);\n  \n  for(int i = 0; i < s; i++) {\n    int l;\n    std::cin >> l;\n    adder.add_edge(v_source, i, l, 0); // no cost\n  }\n  \n  for(int i = 0; i < m; i++) {\n    int si;\n    std::cin >> si;\n    adder.add_edge(si - 1, s + i, 1, 0); // no cost\n  }\n  \n  std::vector<int> costs(n * m);\n  \n  for(int i = 0; i < n; i++) {\n    for(int j = 0; j < m; j++) {\n      int bij;\n      std::cin >> bij;\n      costs[i * m + j] = bij;\n      // adder.add_edge(s + j, s + m + i, 1, -bij); // no cost\n    }\n    adder.add_edge(s + m + i, v_sink, 1, 0); // 1 purchase per buyer, no cost\n  }\n  \n  int max_cost = *std::max_element(costs.begin(), costs.end());\n  for(int i = 0; i < n; i++) {\n    for(int j = 0; j < m; j++) {\n      int bij = costs[i * m + j];\n      adder.add_edge(s + j, s + m + i, 1, -bij + max_cost); // no cost\n    }\n  }\n  \n  // Find a min cut via maxflow\n  boost::successive_shortest_path_nonnegative_weights(G, v_source, v_sink);\n  int cost = boost::find_flow_cost(G);\n    \n  // Iterate over all edges leaving the source to sum up the flow values.\n  int s_flow = 0;\n  out_edge_it e, eend;\n  for(boost::tie(e, eend) = boost::out_edges(boost::vertex(v_source,G), G); e != eend; ++e) {\n      // std::cout << \"edge from \" << boost::source(*e, G) << \" to \" << boost::target(*e, G) \n      //     << \" with capacity \" << c_map[*e] << \" and residual capacity \" << rc_map[*e] << \"\\n\";\n      s_flow += c_map[*e] - rc_map[*e];     \n  }\n  std::cout << s_flow << \" \"; // 5\n  std::cout << -cost + (s_flow * max_cost) << \"\\n\";\n\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": "09ee1a34450e4dbc5791b32768755769577778f9", "size": 4179, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problems/week09-real_estate/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/week09-real_estate/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/week09-real_estate/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": 33.432, "max_line_length": 114, "alphanum_fraction": 0.6226369945, "num_tokens": 1289, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743735019594, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.4899383499388847}}
{"text": "//=======================================================================\r\n// Copyright 2001 Jeremy G. Siek, Andrew Lumsdaine, Lie-Quan Lee, \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, Indiana University,\r\n// Bloomington, IN 47405.\r\n//\r\n// Permission to modify the code and to distribute the code is\r\n// granted, provided the text of this NOTICE is retained, a notice if\r\n// the code was modified is included with the above COPYRIGHT NOTICE\r\n// and with the COPYRIGHT NOTICE in the LICENSE file, and that the\r\n// LICENSE 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#include <vector>\r\n#include <string>\r\n#include <iostream>\r\n#include <boost/graph/topological_sort.hpp>\r\n#include <boost/graph/stanford_graph.hpp>\r\n\r\nint\r\nmain()\r\n{\r\n  using namespace boost;\r\n  const int n_vertices = 7;\r\n  Graph *sgb_g = gb_new_graph(n_vertices);\r\n\r\n  const char *tasks[] = {\r\n    \"pick up kids from school\",\r\n    \"buy groceries (and snacks)\",\r\n    \"get cash at ATM\",\r\n    \"drop off kids at soccer practice\",\r\n    \"cook dinner\",\r\n    \"pick up kids from soccer\",\r\n    \"eat dinner\"\r\n  };\r\n  const int n_tasks = sizeof(tasks) / sizeof(char *);\r\n\r\n  gb_new_arc(sgb_g->vertices + 0, sgb_g->vertices + 3, 0);\r\n  gb_new_arc(sgb_g->vertices + 1, sgb_g->vertices + 3, 0);\r\n  gb_new_arc(sgb_g->vertices + 1, sgb_g->vertices + 4, 0);\r\n  gb_new_arc(sgb_g->vertices + 2, sgb_g->vertices + 1, 0);\r\n  gb_new_arc(sgb_g->vertices + 3, sgb_g->vertices + 5, 0);\r\n  gb_new_arc(sgb_g->vertices + 4, sgb_g->vertices + 6, 0);\r\n  gb_new_arc(sgb_g->vertices + 5, sgb_g->vertices + 6, 0);\r\n\r\n  typedef graph_traits < Graph * >::vertex_descriptor vertex_t;\r\n  std::vector < vertex_t > topo_order;\r\n  topological_sort(sgb_g, std::back_inserter(topo_order),\r\n                   vertex_index_map(get(vertex_index, sgb_g)));\r\n  int n = 1;\r\n  for (std::vector < vertex_t >::reverse_iterator i = topo_order.rbegin();\r\n       i != topo_order.rend(); ++i, ++n)\r\n    std::cout << n << \": \" << tasks[get(vertex_index, sgb_g)[*i]] << std::endl;\r\n\r\n  gb_recycle(sgb_g);\r\n  return EXIT_SUCCESS;\r\n}\r\n", "meta": {"hexsha": "d1aa5517444cf2b80c011c04d0d24df2757185c3", "size": 2691, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sdk/boost_1_30_0/libs/graph/example/topo-sort-with-sgb.cpp", "max_stars_repo_name": "acidicMercury8/xray-1.0", "max_stars_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-01-30T12:51:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-31T08:36:49.000Z", "max_issues_repo_path": "sdk/boost_1_30_0/libs/graph/example/topo-sort-with-sgb.cpp", "max_issues_repo_name": "acidicMercury8/xray-1.0", "max_issues_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_issues_repo_licenses": ["Linux-OpenIB"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sdk/boost_1_30_0/libs/graph/example/topo-sort-with-sgb.cpp", "max_forks_repo_name": "acidicMercury8/xray-1.0", "max_forks_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.5735294118, "max_line_length": 80, "alphanum_fraction": 0.646228168, "num_tokens": 690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228891883799, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.48993834843023926}}
{"text": "#include <iostream>\n#include <cstdint> // Includes integer types\n#include <vector>\n#include <string>\n\n#include <boost/safe_numerics/safe_integer.hpp>\n\n// variables8.cpp\n// Make me compile! Go to the folder hint if you want a hint :)\n\n// We sometimes encourage you to keep trying things on a given exercise,\n// even after you already figured it out. \n\n// Try to find the constant values matching the expected results.\n// This exercises showcases integer overflows. This occurs when the \n// selected datatype is not large enough to hold the value.\n// See https://www.learncpp.com/cpp-tutorial/fixed-width-integers-and-size-t/\n// See: https://www.learncpp.com/cpp-tutorial/unsigned-integers-and-why-to-avoid-them/\n\nusing namespace boost::safe_numerics;\n\nstd::vector<std::string> words;\n\n//Hint: Use safe<> type from the safe_numerics (see more details in hint file)\nuint32_t len; // This global variable keeps track of how may words should be accessed\n\n// init_words is called one before test_danger_loop\nvoid init_words(){\n    words = { \"Hello\", \"World\", \"!\"};\n    len = words.size(); // Only those 3 words should be accessed\n}\n\nconst std::string secret_key = \"Encrypted S3cr3t!\";\n\nstd::string test_danger_loop(uint32_t  query_idx) { // Use safe<> type\n    // Tip: if you cannot find the problem replace all uint32_t with \n    // safe<uint32_t>, from the boost::safe_numerics library\n    // The safe<uint32_t> will throw an exception to help you find the bug\n\n    words.push_back(secret_key); // Copies a secret at the end of the vector\n\n    std::string response;\n    if (len - query_idx > 0) { // Bound checking for protecting secret\n        response = words.at(query_idx);\n    }\n    return response;\n}\n\n#include <catch2/catch.hpp>\n\nTEST_CASE(\"integer_signedness\") {\n    // Initialize data\n    const std::vector<std::string> expected_words { \"Hello\", \"World\", \"!\"};\n    init_words();\n\n    // Run loop\n    for (size_t i = 0; i < expected_words.size(); i++)\n    {\n        std::cout << \"Next index to query \" << i << \", this is word: \" << words[i] << \"\\n\";\n        REQUIRE(test_danger_loop(i) == expected_words.at(i));\n    }\n    \n    std::cout << \"Next index to query is dangerous :\" << 4 << \", this is word:\" << words[4] << \"\\n\";\n    REQUIRE(test_danger_loop(len + 1) == \"\");\n}\n", "meta": {"hexsha": "a02d874b72eabc2fd20917e339d2555aa55b04f8", "size": 2275, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "exercises/01_variables/variables8.cpp", "max_stars_repo_name": "rdjondo/cplings", "max_stars_repo_head_hexsha": "599d8ebf38fd6bc71e573192bfe6f4f9f72e5760", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-24T17:59:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-24T17:59:23.000Z", "max_issues_repo_path": "exercises/01_variables/variables8.cpp", "max_issues_repo_name": "rdjondo/cplings", "max_issues_repo_head_hexsha": "599d8ebf38fd6bc71e573192bfe6f4f9f72e5760", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "exercises/01_variables/variables8.cpp", "max_forks_repo_name": "rdjondo/cplings", "max_forks_repo_head_hexsha": "599d8ebf38fd6bc71e573192bfe6f4f9f72e5760", "max_forks_repo_licenses": ["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.4696969697, "max_line_length": 100, "alphanum_fraction": 0.6817582418, "num_tokens": 575, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.48993834614509263}}
{"text": "#include <cslibs_boost_geometry/algorithms.h>\n\n#include <gtest/gtest.h>\n#include <boost/geometry/algorithms/area.hpp>\n\n\n#include \"points_and_lines.hpp\"\n\nusing namespace cslibs_boost_geometry::algorithms;\nusing namespace cslibs_boost_geometry::types;\nusing namespace cslibs_boost_geometry::test_samples;\n\nTEST(TestCSLibsBoostGeometry, testPolygons)\n{\n    Polygon2d test_result;\n    circularPolygonApproximation(Point2d(0.0,0.0),\n                                 1.0,\n                                 rad(1.0),\n                                 test_result);\n\n    Polygon2d::ring_type &outer_ring = test_result.outer();\n\n    EXPECT_EQ(outer_ring.size(), 361);\n    EXPECT_TRUE(equal(outer_ring.front(), Point2d(1.0, 0.0), 1e-9));\n    EXPECT_TRUE(equal(outer_ring.back(),  Point2d(1.0, 0.0), 1e-9));\n    EXPECT_TRUE(outer_ring[0].x() > outer_ring[1].x());\n    EXPECT_TRUE(outer_ring[0].y() > outer_ring[1].y());\n    EXPECT_TRUE(outer_ring[0].x() > outer_ring[2].x());\n    EXPECT_TRUE(outer_ring[0].y() > outer_ring[2].y());\n    EXPECT_TRUE(outer_ring[0].x() > outer_ring[outer_ring.size() - 3].x());\n    EXPECT_TRUE(outer_ring[0].y() < outer_ring[outer_ring.size() - 3].y());\n\n    EXPECT_TRUE(equal(outer_ring[90],  Point2d(0.0, -1.0), 1e-9));\n    EXPECT_TRUE(equal(outer_ring[180], Point2d(-1.0, 0.0), 1e-9));\n    EXPECT_TRUE(equal(outer_ring[270], Point2d( 0.0, 1.0), 1e-9));\n}\n\nTEST(TestCSLibsBoostGeometry, testWithin)\n{\n    Polygon2d test_result;\n    circularPolygonApproximation(Point2d(0.0,0.0),\n                                 1.0,\n                                 rad(1.0),\n                                 test_result);\n    EXPECT_TRUE(withinExcl<Point2d>(point_a, test_result));\n}\n\nTEST(TestCSLibsBoostGeometry, testIntersection)\n{\n    Polygon2d test_result;\n    circularPolygonApproximation(Point2d(0.0,0.0),\n                                 1.0,\n                                 rad(1.0),\n                                 test_result);\n    EXPECT_FALSE(intersects<Point2d>(line_e, test_result));\n    EXPECT_TRUE(intersects<Point2d>(line_b, test_result));\n}\n\nTEST(TestCSLibsBoostGeometry, testTouching)\n{\n    Polygon2d test_result;\n    circularPolygonApproximation(Point2d(0.0,0.0),\n                                 1.0,\n                                 rad(1.0),\n                                 test_result);\n    EXPECT_TRUE(touches<Point2d>(line_b, test_result));\n    EXPECT_FALSE(touches<Point2d>(line_e, test_result));\n    EXPECT_FALSE(touches<Point2d>(line_f, test_result));\n}\n\nint main(int argc, char *argv[])\n{\n    testing::InitGoogleTest(&argc, argv);\n    return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "0bf1cfd78136edfce6ac19aaf39f94ed3b208251", "size": 2599, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_polygons.cpp", "max_stars_repo_name": "cogsys-tuebingen/cslibs_boost_geometry", "max_stars_repo_head_hexsha": "a6438e6ef62afb2699173c75430b7f97e0cc451f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/test_polygons.cpp", "max_issues_repo_name": "cogsys-tuebingen/cslibs_boost_geometry", "max_issues_repo_head_hexsha": "a6438e6ef62afb2699173c75430b7f97e0cc451f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_polygons.cpp", "max_forks_repo_name": "cogsys-tuebingen/cslibs_boost_geometry", "max_forks_repo_head_hexsha": "a6438e6ef62afb2699173c75430b7f97e0cc451f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-10-16T09:43:15.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-16T09:43:15.000Z", "avg_line_length": 34.1973684211, "max_line_length": 75, "alphanum_fraction": 0.6071565987, "num_tokens": 699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743735019595, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.48993834500251904}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// Unit Test\n\n// Copyright (c) 2007-2013 Barend Gehrels, Amsterdam, the Netherlands.\n// Copyright (c) 2008-2013 Bruno Lalande, Paris, France.\n// Copyright (c) 2009-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#include <string>\n\n#include <geometry_test_common.hpp>\n\n#include <boost/geometry/geometries/geometries.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/algorithms/equals.hpp>\n#include <boost/geometry/algorithms/make.hpp>\n#include <boost/geometry/extensions/algorithms/distance_info.hpp>\n#include <boost/geometry/io/wkt/wkt.hpp>\n\n\ntemplate <typename Result>\nvoid check_distance_info(Result const& result,\n                          std::string const& expected_pp,\n                          bool expected_on_segment,\n                          double expected_projected_distance,\n                          double expected_real_distance,\n                          double expected_fraction)\n{\n    if (! expected_pp.empty())\n    {\n        std::ostringstream out;\n        out << bg::wkt(result.projected_point1);\n        std::string wkt_projected = out.str();\n\n        BOOST_CHECK_EQUAL(wkt_projected, expected_pp);\n    }\n    BOOST_CHECK_EQUAL(result.on_segment, expected_on_segment);\n    BOOST_CHECK_CLOSE(result.fraction1, expected_fraction, 0.001);\n    BOOST_CHECK_CLOSE(result.projected_distance1, expected_projected_distance, 0.001);\n    BOOST_CHECK_CLOSE(result.real_distance, expected_real_distance, 0.001);\n}\n\ntemplate <typename Geometry1, typename Geometry2>\nvoid test_distance_info(Geometry1 const& geometry1, Geometry2 const& geometry2,\n                          std::string const& expected_pp,\n                          bool expected_on_segment,\n                          double expected_projected_distance,\n                          double expected_real_distance,\n                          double expected_fraction)\n{\n    typename bg::distance_info_result<typename bg::point_type<Geometry1>::type> result, reversed_result;\n    bg::distance_info(geometry1, geometry2, result);\n    check_distance_info(result, \n                expected_pp, expected_on_segment,\n                expected_projected_distance, expected_real_distance,\n                expected_fraction);\n\n    // Check reversed version too.\n    std::string reversed_expected_pp = expected_pp;\n    if (boost::is_same<typename bg::tag<Geometry1>::type, bg::point_tag>::value\n        && boost::is_same<typename bg::tag<Geometry2>::type, bg::point_tag>::value\n        )\n    {\n        // For point-point, we cannot check projected-point again, it is also the other one.\n        reversed_expected_pp.clear();\n    }\n    bg::distance_info(geometry2, geometry1, reversed_result);\n    check_distance_info(reversed_result, \n                reversed_expected_pp,\n                expected_on_segment,\n                expected_projected_distance, expected_real_distance,\n                expected_fraction);\n}\n\ntemplate <typename Geometry1>\nvoid test_distance_info(std::string const& wkt, std::string const& wkt_point,\n                          std::string const& expected_pp,\n                          bool expected_on_segment,\n                          double expected_projected_distance,\n                          double expected_real_distance,\n                          double expected_fraction)\n{\n    Geometry1 geometry1;\n    typename bg::point_type<Geometry1>::type point;\n    bg::read_wkt(wkt, geometry1);\n    bg::read_wkt(wkt_point, point);\n\n    test_distance_info(geometry1, point, expected_pp, expected_on_segment,\n                expected_projected_distance, expected_real_distance,\n                expected_fraction);\n}\n\ntemplate <typename P>\nvoid test_2d()\n{\n    test_distance_info<bg::model::segment<P> >(\"LINESTRING(2 0,4 0)\", \"POINT(3 2)\", \"POINT(3 0)\", true, 2.0, 2.0, 0.5);\n    test_distance_info<bg::model::segment<P> >(\"LINESTRING(2 0,4 0)\", \"POINT(2 0)\", \"POINT(2 0)\", true, 0.0, 0.0, 0.0);\n    test_distance_info<bg::model::segment<P> >(\"LINESTRING(2 0,4 0)\", \"POINT(4 0)\", \"POINT(4 0)\", true, 0.0, 0.0, 1.0);\n    test_distance_info<bg::model::segment<P> >(\"LINESTRING(2 0,4 0)\", \"POINT(5 2)\", \"POINT(5 0)\", false, 2.0, sqrt(5.0), 1.5);\n    test_distance_info<bg::model::segment<P> >(\"LINESTRING(2 0,4 0)\", \"POINT(0 2)\", \"POINT(0 0)\", false, 2.0, sqrt(8.0), -1.0);\n\n    // Degenerated segment\n    test_distance_info<bg::model::segment<P> >(\"LINESTRING(2 0,2 0)\", \"POINT(4 0)\", \"POINT(2 0)\", false, 2.0, 2.0, 0.0);\n\n    // Linestring\n    test_distance_info<bg::model::linestring<P> >(\"LINESTRING(2 0,4 0)\", \"POINT(3 2)\", \"POINT(3 0)\", true, 2.0, 2.0, 0.5);\n\n\n    // Point-point\n    test_distance_info<P>(\"Point(1 1)\", \"POINT(2 2)\", \"POINT(2 2)\", false, sqrt(2.0), sqrt(2.0), 0.0);\n}\n\ntemplate <typename P>\nvoid test_3d()\n{\n    test_distance_info<bg::model::segment<P> >(\"LINESTRING(0 0 0,5 5 5)\", \"POINT(2 3 4)\", \"POINT(3 3 3)\", true, sqrt(2.0), sqrt(2.0), 0.6);\n}\n\nint test_main(int, char* [])\n{\n    test_2d<bg::model::d2::point_xy<int> >();\n    test_2d<bg::model::d2::point_xy<float> >();\n    test_2d<bg::model::d2::point_xy<double> >();\n\n    test_3d<bg::model::point<double, 3, bg::cs::cartesian> >();\n\n    return 0;\n}\n", "meta": {"hexsha": "ddbe2ef8470c8ff12878ad7500f677cb04f14c9d", "size": 5416, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "extensions/test/algorithms/distance_info.cpp", "max_stars_repo_name": "jonasdmentia/geometry", "max_stars_repo_head_hexsha": "097f6fdbe98118be82cd1917cc72c3c6a37bdf30", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 326.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T13:47:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T02:13:59.000Z", "max_issues_repo_path": "extensions/test/algorithms/distance_info.cpp", "max_issues_repo_name": "jonasdmentia/geometry", "max_issues_repo_head_hexsha": "097f6fdbe98118be82cd1917cc72c3c6a37bdf30", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 623.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T23:45:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T11:15:23.000Z", "max_forks_repo_path": "extensions/test/algorithms/distance_info.cpp", "max_forks_repo_name": "jonasdmentia/geometry", "max_forks_repo_head_hexsha": "097f6fdbe98118be82cd1917cc72c3c6a37bdf30", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-01-14T15:50:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T03:58:36.000Z", "avg_line_length": 40.7218045113, "max_line_length": 139, "alphanum_fraction": 0.6473412112, "num_tokens": 1452, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743505760727, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.489938344636447}}
{"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_filter_test_suite.hpp\n * \\date June 2015\n * \\author Jan Issac (jan.issac@gmail.com)\n */\n\n#pragma once\n\n\n#include <gtest/gtest.h>\n#include \"../typecast.hpp\"\n\n#include <Eigen/Dense>\n\n#include <cmath>\n#include <iostream>\n\n#include <fl/util/profiling.hpp>\n#include <fl/util/math/linear_algebra.hpp>\n#include <fl/filter/filter_interface.hpp>\n\n#include <fl/model/transition/linear_transition.hpp>\n#include <fl/model/sensor/linear_gaussian_sensor.hpp>\n#include <fl/model/sensor/linear_decorrelated_gaussian_sensor.hpp>\n\ntemplate <typename TestType>\nclass GaussianFilterTest\n    : public ::testing::Test\n{\nprotected:\n    typedef typename TestType::Parameter Configuration;\n\n    enum: signed int\n    {\n        StateDim = Configuration::StateDim,\n        InputDim = Configuration::InputDim,\n        ObsrvDim = Configuration::ObsrvDim,\n\n        StateSize = fl::TestSize<StateDim, TestType>::Value,\n        InputSize = fl::TestSize<InputDim, TestType>::Value,\n        ObsrvSize = fl::TestSize<ObsrvDim, TestType>::Value,\n\n        FilterIterations = Configuration::Iterations\n    };\n\n    enum ModelSetup\n    {\n        Random,\n        Identity\n    };\n\n    typedef Eigen::Matrix<fl::Real, StateSize, 1> State;\n    typedef Eigen::Matrix<fl::Real, InputSize, 1> Input;\n    typedef Eigen::Matrix<fl::Real, ObsrvSize, 1> Obsrv;\n\n    GaussianFilterTest()\n        : predict_steps_(30),\n          predict_update_steps_(FilterIterations)\n    { }\n\n    struct ModelFactory\n    {\n        // Sizes will be 1 of the test type is static and it will fall back to\n        // -1 for dynamic size tests. This may be used as an expansion factor\n        // using fl::ExpandSizes<MySize, Sizes>::Value. If Sizes is equal to 1\n        // (Static) then ExpandSizes will simply multiply MySizes by 1 and\n        // everything is defined statically. On the other hand, if the Sizes\n        // is -1, fl::ExpandSizes will fallback to -1 indicating that the test\n        // type is dynamic.\n        enum : signed int { Sizes = fl::TestSize<1, TestType>::Value };\n\n        typedef fl::LinearTransition<\n                    State, Input\n                > LinearTransition;\n\n        typedef fl::LinearGaussianSensor<\n                    Obsrv, State\n                > LinearObservation;\n\n        LinearTransition create_linear_state_model()\n        {\n            auto model = LinearTransition(StateDim, InputDim);\n\n            auto A = model.create_dynamics_matrix();\n            auto Q = model.create_noise_matrix();\n\n            switch (setup)\n            {\n            case Random:\n                A.setRandom();\n                Q.setRandom();\n                break;\n\n            case Identity:\n                A.setIdentity();\n                Q.setIdentity();\n                break;\n            }\n\n            model.dynamics_matrix(A);\n            model.noise_matrix(Q);\n\n            return model;\n        }\n\n        LinearObservation create_sensor()\n        {\n            auto model = LinearObservation(ObsrvDim, StateDim);\n\n            auto H = model.create_sensor_matrix();\n            auto R = model.create_noise_matrix();\n\n            switch (setup)\n            {\n            case Random:\n                H.setRandom();\n                R.setRandom();\n                break;\n\n            case Identity:\n                H.setIdentity();\n                R.setIdentity();\n                break;\n            }\n\n            model.sensor_matrix(H);\n            model.noise_matrix(R);\n\n            return model;\n        }\n\n        ModelSetup setup;\n    };\n\n    typedef typename Configuration::template FilterDefinition<\n                ModelFactory\n            >::Type Filter;\n\n    Filter create_filter(ModelSetup setup = Identity) const\n    {\n        return Configuration::create_filter(ModelFactory{setup});\n    }\n\n    typename fl::Traits<Filter>::Input zero_input(const Filter& filter)\n    {\n        return fl::Traits<Filter>::Input::Zero(\n            filter.transition().input_dimension());\n    }\n\n    typename fl::Traits<Filter>::Obsrv rand_obsrv(const Filter& filter)\n    {\n        return fl::Traits<Filter>::Obsrv::Random(\n            filter.sensor().obsrv_dimension());\n    }\n\nprotected:\n    int predict_steps_;\n    int predict_update_steps_;\n};\n\nTYPED_TEST_CASE_P(GaussianFilterTest);\n\n//TYPED_TEST_P(GaussianFilterTest, init_predict)\n//{\n//    typedef TestFixture This;\n\n//    auto filter = This::create_filter();\n//    auto belief = filter.create_belief();\n\n//    EXPECT_TRUE(belief.mean().isZero());\n//    EXPECT_TRUE(belief.covariance().isIdentity());\n\n//    std::cout << filter.name() << std::endl;\n//    std::cout << filter.description() << std::endl;\n\n//    filter.predict(belief, This::zero_input(), belief);\n\n//    auto Q = filter.transition().noise_covariance();\n\n//    EXPECT_TRUE(belief.mean().isZero());\n//    EXPECT_TRUE(fl::are_similar(belief.covariance(), 2. * Q));\n//}\n\nTYPED_TEST_P(GaussianFilterTest, predict_then_update)\n{\n    typedef TestFixture This;\n\n    auto filter = This::create_filter(This::Identity);\n\n    PV(filter.name());\n\n    auto belief = filter.create_belief();\n\n    EXPECT_TRUE(belief.covariance().ldlt().isPositive());\n\n    for (int i = 0; i < This::predict_update_steps_; ++i)\n    {\n        PF(i);\n//        PV(belief.mean());\n//        PV(belief.covariance());\n\n        filter.predict(belief, This::zero_input(filter), belief);\n\n//        if (!belief.covariance().ldlt().isPositive())\n//        {\n//            PV(belief.mean());\n//            PV(belief.covariance());\n//        }\n\n        ASSERT_TRUE(belief.covariance().ldlt().isPositive());\n\n\n        filter.update(belief, This::rand_obsrv(filter), belief);\n\n//        if (!belief.covariance().ldlt().isPositive())\n//        {\n//            PV(belief.mean());\n//            PV(belief.covariance());\n//        }\n\n        ASSERT_TRUE(belief.covariance().ldlt().isPositive());\n    }\n\n    PV(belief.mean());\n    PV(belief.covariance());\n}\n\nTYPED_TEST_P(GaussianFilterTest, predict_loop)\n{\n    typedef TestFixture This;\n\n    auto filter = This::create_filter(This::Identity);\n    auto belief = filter.create_belief();\n\n    EXPECT_TRUE(belief.covariance().ldlt().isPositive());\n\n    for (int i = 0; i < This::predict_steps_; ++i)\n    {\n        filter.predict(belief, This::zero_input(filter), belief);\n    }\n\n    EXPECT_TRUE(belief.covariance().ldlt().isPositive());\n}\n\nREGISTER_TYPED_TEST_CASE_P(GaussianFilterTest,\n                           //init_predict,\n                           predict_then_update,\n                           predict_loop);\n\n\n\n", "meta": {"hexsha": "c965cc0e17a7575f5e481174b1d7c35cbbabfa47", "size": 6945, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/gaussian_filter/gaussian_filter_test_suite.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": "test/gaussian_filter/gaussian_filter_test_suite.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": "test/gaussian_filter/gaussian_filter_test_suite.hpp", "max_forks_repo_name": "aeolusbot-tommyliu/fl", "max_forks_repo_head_hexsha": "a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2015-02-20T11:34:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-15T20:55:13.000Z", "avg_line_length": 26.2075471698, "max_line_length": 79, "alphanum_fraction": 0.6001439885, "num_tokens": 1560, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743735019595, "lm_q2_score": 0.6619228625116081, "lm_q1q2_score": 0.4899383400661532}}
{"text": "//          Copyright Carl Philipp Reh 2009 - 2016.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n\n#include <fcppt/math/bresenham.hpp>\n#include <fcppt/math/vector/comparison.hpp>\n#include <fcppt/math/vector/object_impl.hpp>\n#include <fcppt/math/vector/output.hpp>\n#include <fcppt/math/vector/static.hpp>\n#include <fcppt/preprocessor/disable_gcc_warning.hpp>\n#include <fcppt/preprocessor/pop_warning.hpp>\n#include <fcppt/preprocessor/push_warning.hpp>\n#include <fcppt/config/external_begin.hpp>\n#include <boost/test/unit_test.hpp>\n#include <vector>\n#include <fcppt/config/external_end.hpp>\n\n\n// TODO: Add a test for bresenham_thick as well\n\nFCPPT_PP_PUSH_WARNING\nFCPPT_PP_DISABLE_GCC_WARNING(-Weffc++)\n\nBOOST_AUTO_TEST_CASE(\n\tmath_bresenham\n)\n{\nFCPPT_PP_POP_WARNING\n\n\ttypedef\n\tfcppt::math::vector::static_<\n\t\tint,\n\t\t2\n\t>\n\tint2_vector;\n\n\ttypedef\n\tstd::vector<\n\t\tint2_vector\n\t>\n\tint2_vector_sequence;\n\n\tint2_vector_sequence result;\n\n\tfcppt::math::bresenham(\n\t\tint2_vector(\n\t\t\t0,\n\t\t\t0\n\t\t),\n\t\tint2_vector(\n\t\t\t10,\n\t\t\t4\n\t\t),\n\t\t[\n\t\t\t&result\n\t\t](\n\t\t\tint2_vector const _vec\n\t\t)\n\t\t{\n\t\t\tresult.push_back(\n\t\t\t\t_vec\n\t\t\t);\n\n\t\t\treturn\n\t\t\t\ttrue;\n\t\t}\n\t);\n\n\tBOOST_REQUIRE_EQUAL(\n\t\tresult.size(),\n\t\t11u\n\t);\n\n\tBOOST_CHECK_EQUAL(\n\t\tresult[0],\n\t\tint2_vector(\n\t\t\t0,\n\t\t\t0\n\t\t)\n\t);\n\n\tBOOST_CHECK_EQUAL(\n\t\tresult[1],\n\t\tint2_vector(\n\t\t\t1,\n\t\t\t0\n\t\t)\n\t);\n\n\tBOOST_CHECK_EQUAL(\n\t\tresult[2],\n\t\tint2_vector(\n\t\t\t2,\n\t\t\t1\n\t\t)\n\t);\n\n\tBOOST_CHECK_EQUAL(\n\t\tresult[3],\n\t\tint2_vector(\n\t\t\t3,\n\t\t\t1\n\t\t)\n\t);\n\n\tBOOST_CHECK_EQUAL(\n\t\tresult[4],\n\t\tint2_vector(\n\t\t\t4,\n\t\t\t2\n\t\t)\n\t);\n\n\tBOOST_CHECK_EQUAL(\n\t\tresult[5],\n\t\tint2_vector(\n\t\t\t5,\n\t\t\t2\n\t\t)\n\t);\n\n\tBOOST_CHECK_EQUAL(\n\t\tresult[6],\n\t\tint2_vector(\n\t\t\t6,\n\t\t\t2\n\t\t)\n\t);\n\n\tBOOST_CHECK_EQUAL(\n\t\tresult[7],\n\t\tint2_vector(\n\t\t\t7,\n\t\t\t3\n\t\t)\n\t);\n\n\tBOOST_CHECK_EQUAL(\n\t\tresult[8],\n\t\tint2_vector(\n\t\t\t8,\n\t\t\t3\n\t\t)\n\t);\n\n\tBOOST_CHECK_EQUAL(\n\t\tresult[9],\n\t\tint2_vector(\n\t\t\t9,\n\t\t\t4\n\t\t)\n\t);\n\n\tBOOST_CHECK_EQUAL(\n\t\tresult[10],\n\t\tint2_vector(\n\t\t\t10,\n\t\t\t4\n\t\t)\n\t);\n}\n", "meta": {"hexsha": "166b71666f2004a0fa7c0991f135c87d4116f5b4", "size": 2062, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/math/bresenham.cpp", "max_stars_repo_name": "vinzenz/fcppt", "max_stars_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "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": "test/math/bresenham.cpp", "max_issues_repo_name": "vinzenz/fcppt", "max_issues_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "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/math/bresenham.cpp", "max_forks_repo_name": "vinzenz/fcppt", "max_forks_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "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": 12.5731707317, "max_line_length": 61, "alphanum_fraction": 0.6517943744, "num_tokens": 694, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.48993833855750824}}
{"text": "#include \"CalibrationHelpers.h\"\n\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <Eigen/Dense>\n\nnamespace romocc\n{\n\nstd::vector<Transform3d> invert_matrices(std::vector<Transform3d> matrices)\n{\n    std::vector<Transform3d> invertedMatrices;\n\n    for(int i = 0; i<matrices.size(); i++)\n    {\n        invertedMatrices.push_back(matrices.at(i).inverse());\n    }\n    return invertedMatrices;\n}\n\ndouble compute_average(std::vector<double> const &v)\n{\n    double sum = 0;\n    for(int i=0; i<v.size(); i++)\n        sum += v[i];\n    return sum/v.size();\n}\n\ndouble compute_variance(std::vector<double> const &v, double mean)\n{\n    double sum = 0.0;\n    double temp =0.0;\n    double var =0.0;\n\n    for ( int j =0; j <= v.size()-1; j++)\n    {\n        temp = std::pow(v[j]-mean,2);\n        sum += temp;\n    }\n\n    return var = sum/(v.size()-2);\n}\n\nstd::vector<double> compute_linspace(double a, double b, int n)\n{\n    std::vector<double> array;\n    double step = (b-a) / (n-1);\n\n    while(a <= b) {\n        array.push_back(a);\n        a += step;\n    }\n    return array;\n}\n\ndouble sgn(double val)\n{\n    return (double(0) < val) - (val < double(0));\n}\n\nTransform3d load_calibration_file(std::string filepath){\n    auto calMat = Eigen::Affine3d::Identity();\n    std::ifstream inFile;\n    inFile.open(filepath);\n\n    if(inFile.is_open())\n    {\n        for(int row = 0; row < calMat.rows(); row++){\n            for(int col = 0; col < calMat.cols(); col++)\n            {\n                double item = 0;\n                inFile >> item;\n                calMat(row, col) = item;\n            }\n        }\n        inFile.close();\n    }\n    return calMat;\n}\n\nvoid save_calibration_file(std::string path, Eigen::Affine3d calMat) {\n    std::ofstream outFile;\n    outFile.open(path);\n\n    if(outFile.is_open()){\n        outFile << calMat.matrix();\n        outFile.close();\n    }\n}\n\n}", "meta": {"hexsha": "94a74b93c81b5c30399ddeab2a14a0556ad9af77", "size": 1874, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/romocc/calibration/CalibrationHelpers.cpp", "max_stars_repo_name": "SINTEFMedtek/libromocc", "max_stars_repo_head_hexsha": "65a10849401cec02fc1c9ac8b1bdebbbfc4ff1c0", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-07-03T10:02:11.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-20T09:01:42.000Z", "max_issues_repo_path": "source/romocc/calibration/CalibrationHelpers.cpp", "max_issues_repo_name": "SINTEFMedtek/libromocc", "max_issues_repo_head_hexsha": "65a10849401cec02fc1c9ac8b1bdebbbfc4ff1c0", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2019-08-05T07:55:22.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-11T11:05:59.000Z", "max_forks_repo_path": "source/romocc/calibration/CalibrationHelpers.cpp", "max_forks_repo_name": "SINTEFMedtek/libromocc", "max_forks_repo_head_hexsha": "65a10849401cec02fc1c9ac8b1bdebbbfc4ff1c0", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-06-22T09:55:47.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-22T09:55:47.000Z", "avg_line_length": 20.3695652174, "max_line_length": 75, "alphanum_fraction": 0.5661686233, "num_tokens": 499, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228758499941, "lm_q2_score": 0.7401743505760727, "lm_q1q2_score": 0.4899383347637158}}
{"text": "//////////////////////////////////////////////////////////////////////////////\n///   Copyright 2003 and onward LASMEA UMR 6602 CNRS/U.B.P Clermont-Ferrand\n///   Copyright 2009 and onward LRI    UMR 8623 CNRS/Univ Paris Sud XI\n///\n///          Distributed under the Boost Software License, Version 1.0\n///                 See accompanying file LICENSE.txt or copy at\n///                     http://www.boost.org/LICENSE_1_0.txt\n//////////////////////////////////////////////////////////////////////////////\n#ifndef NT2_TOOLBOX_REDUCTION_FUNCTION_SIMD_COMMON_PROD_HPP_INCLUDED\n#define NT2_TOOLBOX_REDUCTION_FUNCTION_SIMD_COMMON_PROD_HPP_INCLUDED\n#include <nt2/sdk/constant/digits.hpp>\n#include <boost/fusion/tuple.hpp>\n#include <boost/fusion/include/fold.hpp>\n#include <nt2/sdk/meta/strip.hpp>\n\n\n\n/////////////////////////////////////////////////////////////////////////////\n// Implementation when type  is arithmetic_\n/////////////////////////////////////////////////////////////////////////////\nNT2_REGISTER_DISPATCH(tag::prod_, tag::cpu_,\n                       (A0)(X),\n                       ((simd_<arithmetic_<A0>,X>))\n                      );\n\nnamespace nt2 { namespace ext\n{\n  template<class X, class Dummy>\n  struct call<tag::prod_(tag::simd_<tag::arithmetic_, X> ),\n              tag::cpu_, Dummy> : callable\n  {\n    template<class Sig> struct result;\n    template<class This,class A0>\n    struct result<This(A0)>\n    {\n      typedef typename meta::scalar_of<A0>::type                base;\n      typedef typename std::tr1::result_of<meta::arithmetic(base)>::type type;\n    };\n\n    NT2_FUNCTOR_CALL(1)\n    {\n      typedef typename NT2_RETURN_TYPE(1)::type     type;\n      return boost::fusion::fold(a0,One<type>(),functor<tag::multiplies_>());\n    }\n\n  };\n} }\n\n#endif\n// modified by jt the 05/01/2011\n", "meta": {"hexsha": "eb4ea494de90fa89c2912dd4039077971a26066c", "size": 1809, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/reduction/include/nt2/toolbox/reduction/function/simd/common/prod.hpp", "max_stars_repo_name": "brycelelbach/nt2", "max_stars_repo_head_hexsha": "73d7e8dd390fa4c8d251c6451acdae65def70e0b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-24T03:35:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T03:35:10.000Z", "max_issues_repo_path": "modules/reduction/include/nt2/toolbox/reduction/function/simd/common/prod.hpp", "max_issues_repo_name": "brycelelbach/nt2", "max_issues_repo_head_hexsha": "73d7e8dd390fa4c8d251c6451acdae65def70e0b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/reduction/include/nt2/toolbox/reduction/function/simd/common/prod.hpp", "max_forks_repo_name": "brycelelbach/nt2", "max_forks_repo_head_hexsha": "73d7e8dd390fa4c8d251c6451acdae65def70e0b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.4705882353, "max_line_length": 78, "alphanum_fraction": 0.5345494748, "num_tokens": 387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390162, "lm_q2_score": 0.6619228625116081, "lm_q1q2_score": 0.489938332478569}}
{"text": "// ------------------------------------------------------------\n// Copyright (c) Microsoft Corporation.  All rights reserved.\n// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.\n// ------------------------------------------------------------\n\n#include \"stdafx.h\"\n#include \"RandomDistribution.h\"\n\n#include <boost/test/unit_test.hpp>\n#include \"Common/boost-taef.h\"\n\nnamespace PlacementAndLoadBalancingUnitTest\n{\n    using namespace std;\n    using namespace Common;\n    using namespace Reliability::LoadBalancingComponent;\n\n    class TestRandomDistribution\n    {\n    protected:\n        TestRandomDistribution()\n        {\n            BOOST_REQUIRE(ClassSetup());\n        }\n        TEST_CLASS_SETUP(ClassSetup);\n        uint32_t seed_;\n    };\n\n    BOOST_FIXTURE_TEST_SUITE(RandomDistributionTestSuite, TestRandomDistribution)\n\n    BOOST_AUTO_TEST_CASE(AllOnesDistributionTest)\n    {\n        RandomDistribution rd(seed_);\n        DistributionMap distribution =\n            rd.GenerateDistribution(10000, RandomDistribution::Enum::AllOnes);\n\n        VERIFY_ARE_EQUAL(1u, distribution.size());\n        VERIFY_ARE_EQUAL(10000u, rd.GetNumberOfSamples(distribution));\n\n        VERIFY_ARE_EQUAL(10000u, distribution[1]);\n    }\n\n    BOOST_AUTO_TEST_CASE(UniformDistributionTest)\n    {\n        RandomDistribution rd(seed_);\n        DistributionMap distribution =\n            rd.GenerateDistribution(10000, RandomDistribution::Enum::Uniform, -50, 49);\n\n        VERIFY_ARE_EQUAL(100u, distribution.size());\n        VERIFY_ARE_EQUAL(10000u, rd.GetNumberOfSamples(distribution));\n\n        for (int i = -50; i <= 49; i++)\n        {\n            VERIFY_ARE_EQUAL(100u, distribution[i]);\n        }\n    }\n\n    BOOST_AUTO_TEST_CASE(ExponentialDistributionTest)\n    {\n        RandomDistribution rd(seed_);\n        DistributionMap distribution =\n            rd.GenerateDistribution(10000, RandomDistribution::Enum::Exponential, -50, 50);\n\n        VERIFY_ARE_EQUAL(10000u, rd.GetNumberOfSamples(distribution));\n    }\n\n    BOOST_AUTO_TEST_CASE(GaussianDistributionTest)\n    {\n        RandomDistribution rd(seed_);\n        DistributionMap distribution =\n            rd.GenerateDistribution(10000, RandomDistribution::Enum::Gaussian, -50, 50);\n\n        VERIFY_ARE_EQUAL(10000u, rd.GetNumberOfSamples(distribution));\n    }\n\n    BOOST_AUTO_TEST_CASE(RandomSeedTest)\n    {\n        RandomDistribution rd1(100);\n        RandomDistribution rd2(200);\n        RandomDistribution rd3(200);\n\n        DistributionMap d1_g = rd1.GenerateDistribution(10000, RandomDistribution::Enum::Gaussian, -50, 49);\n        DistributionMap d2_g = rd2.GenerateDistribution(10000, RandomDistribution::Enum::Gaussian, -50, 49);\n        DistributionMap d3_g = rd3.GenerateDistribution(10000, RandomDistribution::Enum::Gaussian, -50, 49);\n\n        VERIFY_ARE_EQUAL(d2_g, d3_g);\n        VERIFY_IS_TRUE(d1_g != d2_g);\n        VERIFY_IS_TRUE(d1_g != d3_g);\n\n        DistributionMap d1_e = rd1.GenerateDistribution(10000, RandomDistribution::Enum::Exponential, -50, 49);\n        DistributionMap d2_e = rd2.GenerateDistribution(10000, RandomDistribution::Enum::Exponential, -50, 49);\n        DistributionMap d3_e = rd3.GenerateDistribution(10000, RandomDistribution::Enum::Exponential, -50, 49);\n\n        VERIFY_ARE_EQUAL(d2_e, d3_e);\n        VERIFY_IS_TRUE(d1_e != d2_e);\n        VERIFY_IS_TRUE(d1_e != d3_e);\n    }\n\n    BOOST_AUTO_TEST_SUITE_END()\n\n    bool TestRandomDistribution::ClassSetup()\n    {\n        seed_ = 500;\n        return TRUE;\n    }\n}\n", "meta": {"hexsha": "2ba2ed4b19224e194b6d9227ee7b22af24a0d8b5", "size": 3535, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/prod/src/Reliability/LoadBalancing/RandomDistribution.Test.cpp", "max_stars_repo_name": "gridgentoo/ServiceFabricAzure", "max_stars_repo_head_hexsha": "c3e7a07617e852322d73e6cc9819d266146866a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2542.0, "max_stars_repo_stars_event_min_datetime": "2018-03-14T21:56:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-06T01:18:20.000Z", "max_issues_repo_path": "src/prod/src/Reliability/LoadBalancing/RandomDistribution.Test.cpp", "max_issues_repo_name": "gridgentoo/ServiceFabricAzure", "max_issues_repo_head_hexsha": "c3e7a07617e852322d73e6cc9819d266146866a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 994.0, "max_issues_repo_issues_event_min_datetime": "2019-05-07T02:39:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T13:23:04.000Z", "max_forks_repo_path": "src/prod/src/Reliability/LoadBalancing/RandomDistribution.Test.cpp", "max_forks_repo_name": "gridgentoo/ServiceFabricAzure", "max_forks_repo_head_hexsha": "c3e7a07617e852322d73e6cc9819d266146866a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 300.0, "max_forks_repo_forks_event_min_datetime": "2018-03-14T21:57:17.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-06T20:07:00.000Z", "avg_line_length": 33.0373831776, "max_line_length": 111, "alphanum_fraction": 0.6625176803, "num_tokens": 794, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.489927805039744}}
{"text": "#include \"RBGL.hpp\"\n#include \"Basic2DMatrix.hpp\"\n#include <boost/graph/depth_first_search.hpp>\n#include <boost/graph/breadth_first_search.hpp>\n#include <boost/graph/topological_sort.hpp>\n#include <boost/graph/strong_components.hpp>\n#include <boost/graph/edge_connectivity.hpp>\n#include <boost/graph/biconnected_components.hpp>\n#include <boost/graph/sequential_vertex_coloring.hpp>\n\n/* need a template with C++ linkage for BFS */\n/* adapted from Siek's bfs-example.cpp */\n\ntemplate < typename TimeMap > class bfs_time_visitor\n    : public boost::default_bfs_visitor {\n    typedef typename boost::property_traits < TimeMap >::value_type T;\npublic:\n    bfs_time_visitor(TimeMap tmap, T & t):m_timemap(tmap), m_time(t) { }\n    template < typename Vertex, typename Graph >\n    void discover_vertex(Vertex u, const Graph & g) const\n    {\n        put(m_timemap, u, m_time++);\n    }\n    TimeMap m_timemap;\n    T & m_time;\n};\n\ntemplate < typename TimeMap > class dfs_time_visitor\n    : public boost::default_dfs_visitor {\n    typedef typename boost::property_traits < TimeMap >::value_type T;\npublic:\n    dfs_time_visitor(TimeMap dmap, TimeMap fmap, T & t)\n            :  m_dtimemap(dmap), m_ftimemap(fmap), m_time(t) {\n    }\n    template < typename Vertex, typename Graph >\n    void discover_vertex(Vertex u, const Graph & g) const\n    {\n        put(m_dtimemap, u, m_time++);\n    }\n    template < typename Vertex, typename Graph >\n    void finish_vertex(Vertex u, const Graph & g) const\n    {\n        put(m_ftimemap, u, m_time++);\n    }\n    TimeMap m_dtimemap;\n    TimeMap m_ftimemap;\n    T & m_time;\n};\n\nextern \"C\"\n{\n    SEXP BGL_tsort_D(SEXP num_verts_in, SEXP num_edges_in, SEXP R_edges_in)\n    {\n        // tsortbCG -- for bioConductor graph objects\n\n        using namespace boost;\n        typedef graph_traits < Graph_dd >::edge_descriptor Edge;\n        typedef graph_traits < Graph_dd >::vertex_descriptor Vertex;\n        Graph_dd g(num_verts_in, num_edges_in, R_edges_in);\n\n        typedef property_map<Graph_dd, vertex_color_t>::type Color;\n        graph_traits<Graph_dd>::vertex_iterator viter, viter_end;\n\n        typedef std::list<Vertex> tsOrder;\n        tsOrder tsord;\n        SEXP tsout;\n\n        PROTECT(tsout = NEW_NUMERIC(INTEGER(num_verts_in)[0]));\n\n        try {\n            topological_sort(g, std::front_inserter(tsord));\n\n            int j = 0;\n            for (tsOrder::iterator i = tsord.begin();\n                    i != tsord.end(); ++i)\n            {\n                REAL(tsout)[j] = (double) *i;\n                j++;\n            }\n        }\n        catch ( not_a_dag )\n        {\n            warning(\"not a DAG.\\n\");\n            for (int j = 0 ; j < INTEGER(num_verts_in)[0]; j++)\n                REAL(tsout)[j] = 0.0;\n        }\n        UNPROTECT(1);\n\n        return(tsout);\n    } // end BGL_tsort_D\n\n\n    SEXP BGL_bfs_D(SEXP num_verts_in, SEXP num_edges_in,\n                   SEXP R_edges_in, SEXP R_weights_in, SEXP init_ind)\n    {\n        using namespace boost;\n\n        typedef graph_traits < Graph_dd >::edge_descriptor Edge;\n        typedef graph_traits < Graph_dd >::vertex_descriptor Vertex;\n        Graph_dd g(num_verts_in, num_edges_in, R_edges_in, R_weights_in);\n\n        typedef graph_traits < Graph_dd >::vertices_size_type size_type;\n\n        const int N = INTEGER(num_verts_in)[0];\n        // Typedefs\n        typedef size_type* Iiter;\n\n        // discover time properties\n        std::vector < size_type > dtime(num_vertices(g));\n\n        size_type time = 0;\n        bfs_time_visitor < size_type * >vis(&dtime[0], time);\n        breadth_first_search(g, vertex((int)INTEGER(init_ind)[0], g), visitor(vis));\n\n\n        // use std::sort to order the vertices by their discover time\n        std::vector < size_type > discover_order(N);\n        integer_range < size_type > r(0, N);\n        std::copy(r.begin(), r.end(), discover_order.begin());\n        std::sort(discover_order.begin(), discover_order.end(),\n                  indirect_cmp < Iiter, std::less < size_type > >(&dtime[0]));\n\n        SEXP disc;\n        PROTECT(disc = allocVector(INTSXP,N));\n\n        int i;\n        for (i = 0; i < N; ++i)\n        {\n            INTEGER(disc)[i] = discover_order[i];\n        }\n\n        UNPROTECT(1);\n        return(disc);\n    }\n\n\n    SEXP BGL_dfs_D(SEXP num_verts_in, SEXP num_edges_in, SEXP R_edges_in,\n                   SEXP R_weights_in)\n    {\n        using namespace boost;\n\n        typedef graph_traits < Graph_dd >::edge_descriptor Edge;\n        typedef graph_traits < Graph_dd >::vertex_descriptor Vertex;\n        Graph_dd g(num_verts_in, num_edges_in, R_edges_in, R_weights_in);\n\n        typedef graph_traits < Graph_dd >::vertices_size_type size_type;\n\n        const int N = INTEGER(num_verts_in)[0];\n        // Typedefs\n        typedef size_type* Iiter;\n\n        // discover time and finish time properties\n        std::vector < size_type > dtime(num_vertices(g));\n        std::vector < size_type > ftime(num_vertices(g));\n        size_type t = 0;\n        dfs_time_visitor < size_type * >vis(&dtime[0], &ftime[0], t);\n\n        depth_first_search(g, visitor(vis));\n\n        // use std::sort to order the vertices by their discover time\n        std::vector < size_type > discover_order(N);\n        integer_range < size_type > r(0, N);\n        std::copy(r.begin(), r.end(), discover_order.begin());\n        std::sort(discover_order.begin(), discover_order.end(),\n                  indirect_cmp < Iiter, std::less < size_type > >(&dtime[0]));\n        std::vector < size_type > finish_order(N);\n        std::copy(r.begin(), r.end(), finish_order.begin());\n        std::sort(finish_order.begin(), finish_order.end(),\n                  indirect_cmp < Iiter, std::less < size_type > >(&ftime[0]));\n\n        SEXP ansList;\n        PROTECT(ansList = allocVector(VECSXP,2));\n        SEXP disc;\n        PROTECT(disc = allocVector(INTSXP,N));\n        SEXP fin;\n        PROTECT(fin = allocVector(INTSXP,N));\n\n        int i;\n        for (i = 0; i < N; ++i)\n        {\n            INTEGER(disc)[i] = discover_order[i];\n            INTEGER(fin)[i] = finish_order[i];\n        }\n\n        SET_VECTOR_ELT(ansList,0,disc);\n        SET_VECTOR_ELT(ansList,1,fin);\n        UNPROTECT(3);\n        return(ansList);\n    }\n\n    SEXP BGL_connected_components_U (SEXP num_verts_in,\n                                     SEXP num_edges_in, SEXP R_edges_in, \n\t\t\t\t     SEXP R_weights_in )\n    {\n        using namespace boost;\n        SEXP outvec;\n\n        typedef graph_traits < Graph_ud >::edge_descriptor Edge;\n        typedef graph_traits < Graph_ud >::vertex_descriptor Vertex;\n        Graph_ud g(num_verts_in, num_edges_in, R_edges_in, R_weights_in);\n\n        int nvert = INTEGER(num_verts_in)[0] ;\n\n        std::vector<int> component(num_vertices(g));\n        connected_components(g, &component[0]);\n\n        std::vector<int>::size_type k;\n\n        PROTECT(outvec = allocVector(REALSXP,nvert));\n\n        for (k = 0; k < component.size(); k++ )\n            REAL(outvec)[k] = component[k];\n\n        UNPROTECT(1);\n        return(outvec);\n    }\n\n    SEXP BGL_strong_components_D (SEXP num_verts_in,\n                                  SEXP num_edges_in, SEXP R_edges_in,\n                                  SEXP R_weights_in )\n    {\n        using namespace boost;\n        SEXP outvec;\n\n        typedef graph_traits < Graph_dd >::edge_descriptor Edge;\n        typedef graph_traits < Graph_dd >::vertex_descriptor Vertex;\n        Graph_dd g(num_verts_in, num_edges_in, R_edges_in, R_weights_in);\n\n        int nvert = INTEGER(num_verts_in)[0] ;\n\n        std::vector<int> component(num_vertices(g));\n        strong_components(g, &component[0]);\n\n        std::vector<int>::size_type k;\n\n        PROTECT(outvec = allocVector(REALSXP,nvert));\n\n        for (k = 0; k < component.size(); k++ )\n            REAL(outvec)[k] = component[k];\n\n        UNPROTECT(1);\n        return(outvec);\n    }\n\n    SEXP BGL_biconnected_components_U (SEXP num_verts_in,\n                                  SEXP num_edges_in, SEXP R_edges_in,\n                                  SEXP R_weights_in )\n    {\n        using namespace boost;\n        SEXP outvec;\n\n        typedef graph_traits < Graph_ud >::edge_descriptor Edge;\n        typedef graph_traits < Graph_ud >::vertex_descriptor Vertex;\n        Graph_ud g(num_verts_in, num_edges_in, R_edges_in, R_weights_in);\n\n        int ne = INTEGER(num_edges_in)[0] ;\n\n        // this is a bit cheating: use \"edge_weight_t\" for \"edge_component_t\"\n        property_map < Graph_ud, edge_weight_t >::type \n              component = get(edge_weight, g);\n        graph_traits < Graph_ud >::edge_iterator ei, ei_end;\n        for (tie(ei, ei_end) = edges(g); ei != ei_end; ++ei)\n            component[*ei] = (int)-1;\n        int num_comps = biconnected_components(g, component);\n\n        SEXP ansList, eList, nc;\n        PROTECT(ansList = allocVector(VECSXP,3));\n        PROTECT(nc = NEW_INTEGER(1));\n        PROTECT(eList = allocMatrix(INTSXP, 2, ne));\n        PROTECT(outvec = allocMatrix(INTSXP, 1, ne));\n\n        INTEGER(nc)[0] = num_comps;\n        int ke = 0;\n        int k = 0;\n        for (tie(ei, ei_end) = edges(g); ei != ei_end; ++ei)\n        {\n            INTEGER(eList)[ke++] = (int)source(*ei, g);\n            INTEGER(eList)[ke++] = (int)target(*ei, g);\n            INTEGER(outvec)[k++] = (int)component[*ei];\n        }\n\n        SET_VECTOR_ELT(ansList,0,nc);\n        SET_VECTOR_ELT(ansList,1,eList);\n        SET_VECTOR_ELT(ansList,2,outvec);\n        UNPROTECT(4);\n        return(ansList);\n    }\n\n    SEXP BGL_articulation_points_U (SEXP num_verts_in,\n                                  SEXP num_edges_in, SEXP R_edges_in,\n                                  SEXP R_weights_in )\n    {\n        using namespace boost;\n\n        typedef graph_traits < Graph_ud >::edge_descriptor Edge;\n        typedef graph_traits < Graph_ud >::vertex_descriptor Vertex;\n        Graph_ud g(num_verts_in, num_edges_in, R_edges_in, R_weights_in);\n\n        std::vector<Vertex> art_points;\n        articulation_points(g, std::back_inserter(art_points));\n\n        SEXP outvec;\n        PROTECT(outvec = allocVector(INTSXP,art_points.size()));\n\n        for (unsigned int k = 0; k < art_points.size(); k++ )\n            INTEGER(outvec)[k] = art_points[k];\n\n        UNPROTECT(1);\n        return(outvec);\n    }\n\n    SEXP BGL_edge_connectivity_U (SEXP num_verts_in,\n                                  SEXP num_edges_in, SEXP R_edges_in,\n                                  SEXP R_weights_in )\n    {\n        using namespace boost;\n        SEXP ansList, conn, edTmp;\n\n        typedef graph_traits < Graph_ud >::edge_descriptor Edge;\n        typedef graph_traits < Graph_ud >::vertex_descriptor Vertex;\n        Graph_ud g(num_verts_in, num_edges_in, R_edges_in, R_weights_in);\n\n        typedef graph_traits<Graph_ud>::degree_size_type dst;\n        std::vector<Edge> disconnecting_set;\n        std::vector<Edge>::iterator ei;\n        dst c = edge_connectivity( g, std::back_inserter(disconnecting_set) );\n\n        PROTECT(conn = NEW_NUMERIC(1));\n        REAL(conn)[0] = (double)c;\n\n        SEXP eList;\n        PROTECT(ansList = allocVector(VECSXP,2));\n\n        PROTECT(eList = allocVector(VECSXP,(int)c));\n\n        SET_VECTOR_ELT(ansList,0,conn);\n\n        int sind = 0;\n        for (ei = disconnecting_set.begin(); ei != disconnecting_set.end();\n                ++ei)\n        {\n            PROTECT(edTmp = NEW_NUMERIC(2));\n            REAL(edTmp)[0] = (double)source(*ei,g);\n            REAL(edTmp)[1] = (double)target(*ei,g);\n            SET_VECTOR_ELT(eList,sind,edTmp);\n            sind=sind+1;\n            UNPROTECT(1);\n        }\n\n        SET_VECTOR_ELT(ansList,1,eList);\n        UNPROTECT(3);\n        return(ansList);\n    }\n\n    SEXP BGL_sequential_vertex_coloring (SEXP num_verts_in, \n    \t\tSEXP num_edges_in, SEXP R_edges_in)\n    {\n        using namespace boost;\n\n        typedef graph_traits < Graph_ud >::edge_descriptor Edge;\n        typedef graph_traits < Graph_ud >::vertex_descriptor Vertex;\n        typedef graph_traits < Graph_ud >::vertices_size_type Vertex_Size_Type;\n        typedef property_map < Graph_ud, vertex_index_t >::const_type vertex_index_map;\n\n        Graph_ud g(num_verts_in, num_edges_in, R_edges_in);\n\n        std::vector<Vertex_Size_Type> color_vec(num_vertices(g));\n        iterator_property_map < Vertex_Size_Type*, vertex_index_map >\n             color(&color_vec.front(), get(vertex_index, g));\n        Vertex_Size_Type n = sequential_vertex_coloring( g, color );\n\n        SEXP ansList, nc, cList;\n        PROTECT(ansList = allocVector(VECSXP,2));\n        PROTECT(nc = NEW_INTEGER(1));\n        PROTECT(cList = allocVector(INTSXP, num_vertices(g)));\n        INTEGER(nc)[0] = (int)n;\n\n        Graph_ud::vertex_iterator vi, v_end;\n        int i = 0;\n        for (tie(vi, v_end) = vertices(g); vi != v_end; ++vi)\n        {\n            INTEGER(cList)[i++] = color_vec[*vi];\n        }\n    \n        SET_VECTOR_ELT(ansList, 0, nc);\n        SET_VECTOR_ELT(ansList, 1, cList);\n        UNPROTECT(3);\n        return(ansList);\n    }\n\n    SEXP BGL_astar_search_D (SEXP num_verts_in, \n    \t\tSEXP num_edges_in, SEXP R_edges_in )\n    {\n        // TODO: fill in\n    \tusing namespace boost;\n\n        SEXP ansList;\n        PROTECT(ansList = NEW_INTEGER(1));\n        INTEGER(ansList)[0] = 0;\n        UNPROTECT(1);\n        return(ansList);\n    }\n}\n", "meta": {"hexsha": "418a473d3396d94e55ba2a5d22086d605c1a5430", "size": 13334, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/interfaces.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/interfaces.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/interfaces.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.004950495, "max_line_length": 87, "alphanum_fraction": 0.597120144, "num_tokens": 3258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.4899278011836399}}
{"text": "/**\n *  sim_carAbst.cpp\n *\n *  To simulate the vehicle example using abstraction-based control.\n *\n *  Authors: Yinan Li, Zhibing Sun, Jun Liu\n *  Created: May 27, 2020\n *\n *  Hybrid Systems Group, University of Waterloo.\n */\n\n\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <cstdlib>\n\n#include <string>\n#include <math.h>\n#include <boost/numeric/odeint.hpp>\n\n#include \"src/abstraction.hpp\"\n#include \"src/DBAparser.h\"\n#include \"src/bsolver.hpp\"\n#include \"src/hdf5io.h\"\n\n\n/* define dynamics */\nstruct car_dynamics {\n\trocs::Rn u;\n\tcar_dynamics (const rocs::Rn param): u (param) {}\n\n\tvoid operator() (rocs::Rn &x, rocs::Rn &dxdt, double t) const\n\t{\n\t      double alpha = std::atan(std::tan(u[1])/2.0);\n\t      dxdt[0] = u[0]*std::cos(alpha+x[2])/std::cos(alpha);\n\t      dxdt[1] = u[0]*std::sin(alpha+x[2])/std::cos(alpha);\n\t      dxdt[2] = u[0]*std::tan(u[1]);\n\t}\n};\n\n\nint main(int argc, char *argv[])\n{\n    /**\n     * Default arguments\n     */\n    std::string specfile{\"dba1.txt\"};\n    double eta[]{0.2, 0.2, 0.2};\n\n    /* Input arguments:\n     * sim_abst specfile precision(e.g. 0.2 0.2 0.2)\n     */\n    if (argc > 2 && argc < 5) {\n\tstd::cout << \"Improper number of arguments. Input arguments are:\\n\";\n\tstd::cout << \"./sim_abst specfile precision(e.g. 0.2 0.2 0.2)\\n\";\n\tstd::exit(1);\n    }\n    if(argc > 1) {\n\tspecfile = std::string(argv[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::vector<std::string> tokens;\n    boost::split(tokens, specfile, boost::is_any_of(\".\"));\n    std::string ctlrfile = \"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\tctlrfile += ss.str();\n\tif (i < 2)\n\t    ctlrfile += \"-\";\n    }\n    ctlrfile += \".h5\";\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     * Setup the motion planning workspace\n     **/\n    /* set the state space */\n    const int x_dim = 3;\n    const double theta = 3.5;\n    double xlb[] = {0, 0, -theta};\n    double xub[] = {10, 10, theta};\n    /* set the control values */\n    const int u_dim = 2;\n    double ulb[] = {-1.0, -1.0};\n    double uub[] = {1.0, 1.0};\n    double mu[] = {0.3, 0.3};\n    /* Generate grids */\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\n    /**\n     * Load global controller\n     **/\n    std::cout << \"\\nLoading the controller from \" << ctlrfile << \"...\\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     * Simulation\n     **/\n    const double tsim = 0.3;  //simulation time step\n    /* Open files for writing results and logs */\n    std::string simfile = \"sim_traj_\"+tokens[0]+\".txt\";\n    std::ofstream ctlrWtr(simfile);\n    if(!ctlrWtr.is_open())\n\tctlrWtr.open(simfile, std::ios::out);\n\t/********** Logging **********/\n    std::ofstream logger;\n    logger.open(\"logs_\"+tokens[0]+\".txt\", std::ios::out);\n    /********** Logging **********/\n\n    /* ode solver */\n    const double dt = 0.001; //integration step size for odeint\n    boost::numeric::odeint::runge_kutta_cash_karp54<rocs::Rn> rk45;\n\n    /* Initial condition */\n    rocs::Rn x{3, 2, M_PI/2.};\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\n    float tpat = 0;\n    int max_num_achieve_acc=5, max_num_iteration=500; //3000000;\n    rocs::UintSmall q;\n    int i, j;\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/* 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\t/* Write to txt file */\n\t// ctlrWtr << j << ':';\n\tfor(int d = 0; d < x_dim; ++d) {\n\t    ctlrWtr << x[d];\n\t    if(d<x_dim-1) {\n\t\tctlrWtr << ',';\n\t    }\n\t}\n\tctlrWtr << ';';\n\tfor(int d = 0; d < u_dim; ++d) {\n\t    ctlrWtr << u[d];\n\t    if(d<u_dim-1) {\n\t\tctlrWtr << ',';\n\t    }\n\t}\n\tctlrWtr << '\\n';\n\n\t/* Integrate the dynamics */\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/********** Logging **********/\n    logger << \"x,q,u=\" << x_index << ' ' << q << ' ' << p7->u << \"; encode3[x]=\" << encode3[x_index];\n\tlogger << \"\\np5=\" << p5.num_a << ' ' << p5.label << ' ' << p5.pos;\n\tlogger << \"\\np7=\";\n\tfor(std::vector<CTRL>::iterator p = ctrl.begin()+p5.pos;\n\t\tp!=ctrl.begin()+p5.pos+p5.num_a; ++p) {\n\t\tlogger << p->q << ' ' << p->u << ';';\n\t}\n\tlogger << \"\\n\\n\";\n    /********** Logging **********/\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\tlogger.close();\n\n\n    return 0;\n}\n", "meta": {"hexsha": "24239fc015469c018a440fcd43cbeb2ca4497b56", "size": 6705, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/car/sim_abst.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/car/sim_abst.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/car/sim_abst.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": 28.6538461538, "max_line_length": 101, "alphanum_fraction": 0.5454138702, "num_tokens": 2263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.48992780118363977}}
{"text": "#define BOOST_TEST_MODULE DikinEllipsoidCalculatorTestSuite\n#define BOOST_TEST_DYN_LINK\n\n#include <boost/test/included/unit_test.hpp>\n#include <Eigen/Core>\n#include <hops/hops.hpp>\n\nBOOST_AUTO_TEST_SUITE(DikinEllipsoidCalculator)\n\n    BOOST_AUTO_TEST_CASE(Cube) {\n        const long rows = 6;\n        const long cols = 3;\n        Eigen::MatrixXd A(rows, cols);\n        A << 1, 0, 0,\n                0, 1, 0,\n                0, 0, 1,\n                -1, 0, 0,\n                0, -1, 0,\n                0, 0, -1;\n        Eigen::VectorXd b(rows);\n        b << 1, 1, 1, 1, 1, 1;\n\n        hops::DikinEllipsoidCalculator dikinEllipsoidCalculator(A, b);\n        Eigen::VectorXd interiorPoint(cols);\n        for (size_t i = 0; i < cols; ++i) {\n            interiorPoint(i) = 0;\n        }\n\n        auto actualDikinEllipsoid = dikinEllipsoidCalculator.computeDikinEllipsoid(interiorPoint);\n\n        BOOST_CHECK(actualDikinEllipsoid == 2 * Eigen::MatrixXd::Identity(cols, cols));\n    }\n\n    BOOST_AUTO_TEST_CASE(CholeskyOfCube) {\n        const long rows = 6;\n        const long cols = 3;\n        Eigen::MatrixXd expectedDikinEllipsoid = 2 * Eigen::MatrixXd::Identity(cols, cols);\n\n        Eigen::MatrixXd A(rows, cols);\n        A << 1, 0, 0,\n                0, 1, 0,\n                0, 0, 1,\n                -1, 0, 0,\n                0, -1, 0,\n                0, 0, -1;\n        Eigen::VectorXd b(rows);\n        b << 1, 1, 1, 1, 1, 1;\n\n        hops::DikinEllipsoidCalculator dikinEllipsoidCalculator(A, b);\n        Eigen::VectorXd interiorPoint(cols);\n        for (size_t i = 0; i < cols; ++i) {\n            interiorPoint(i) = 0;\n        }\n\n        auto[choleskyWasSuccessful, actualDikinEllipsoidLowerFactor] = dikinEllipsoidCalculator.computeCholeskyFactorOfDikinEllipsoid(\n                interiorPoint);\n        Eigen::MatrixXd actualDikinEllipsoid =\n                actualDikinEllipsoidLowerFactor * actualDikinEllipsoidLowerFactor.transpose();\n\n        BOOST_CHECK(choleskyWasSuccessful);\n        BOOST_CHECK(((actualDikinEllipsoid - expectedDikinEllipsoid).array() < 1e-15).all());\n    }\n\n    BOOST_AUTO_TEST_CASE(Simplex) {\n        const long rows = 4;\n        const long cols = 3;\n\n        Eigen::MatrixXd expectedDikinEllipsoid(cols, cols);\n        expectedDikinEllipsoid << 3.35012345679, 2.56, 2.56,\n                2.56, 3.35012345679, 2.56,\n                2.56, 2.56, 3.35012345679;\n\n        Eigen::MatrixXd A(rows, cols);\n        A << 1, 1, 1,\n                -1, 0, 0,\n                0, -1, 0,\n                0, 0, -1;\n        Eigen::VectorXd b(rows);\n        b << 1, 1, 1, 1;\n\n        hops::DikinEllipsoidCalculator dikinEllipsoidCalculator(A, b);\n        Eigen::VectorXd interiorPoint(cols);\n        for (size_t i = 0; i < cols; ++i) {\n            interiorPoint(i) = 1. / 8;\n        }\n\n        auto actualDikinEllipsoid = dikinEllipsoidCalculator.computeDikinEllipsoid(interiorPoint);\n\n        BOOST_CHECK(((actualDikinEllipsoid - expectedDikinEllipsoid).array() < 1e-12).all());\n    }\n\n    BOOST_AUTO_TEST_CASE(CholeskyOfSimplex) {\n        const long rows = 4;\n        const long cols = 3;\n\n        Eigen::MatrixXd expectedDikinEllipsoid(cols, cols);\n        expectedDikinEllipsoid << 3.35012345679, 2.56, 2.56,\n                2.56, 3.35012345679, 2.56,\n                2.56, 2.56, 3.35012345679;\n\n        Eigen::MatrixXd A(rows, cols);\n        A << 1, 1, 1,\n                -1, 0, 0,\n                0, -1, 0,\n                0, 0, -1;\n        Eigen::VectorXd b(rows);\n        b << 1, 1, 1, 1;\n\n        hops::DikinEllipsoidCalculator dikinEllipsoidCalculator(A, b);\n        Eigen::VectorXd interiorPoint(cols);\n        for (size_t i = 0; i < cols; ++i) {\n            interiorPoint(i) = 1. / 8;\n        }\n\n        auto[choleskyWasSuccessful, actualDikinEllipsoidLowerFactor] = dikinEllipsoidCalculator.computeCholeskyFactorOfDikinEllipsoid(\n                interiorPoint);\n        Eigen::MatrixXd actualDikinEllipsoid =\n                actualDikinEllipsoidLowerFactor * actualDikinEllipsoidLowerFactor.transpose();\n\n        BOOST_CHECK(choleskyWasSuccessful);\n        BOOST_CHECK(((actualDikinEllipsoid - expectedDikinEllipsoid).array() < 1e-12).all());\n    }\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "23ddb27ee390f58cf70321fd0421734322bb2f4a", "size": 4200, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/MarkovChain/Proposal/DikinEllipsoidCalculatorTestSuite.cpp", "max_stars_repo_name": "modsim/hops", "max_stars_repo_head_hexsha": "4285dd75a07dd844295440a0756b3ba25f5819ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2020-11-26T05:13:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T02:08:40.000Z", "max_issues_repo_path": "tests/MarkovChain/Proposal/DikinEllipsoidCalculatorTestSuite.cpp", "max_issues_repo_name": "modsim/hops", "max_issues_repo_head_hexsha": "4285dd75a07dd844295440a0756b3ba25f5819ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-02-20T23:16:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-20T23:16:34.000Z", "max_forks_repo_path": "tests/MarkovChain/Proposal/DikinEllipsoidCalculatorTestSuite.cpp", "max_forks_repo_name": "modsim/hops", "max_forks_repo_head_hexsha": "4285dd75a07dd844295440a0756b3ba25f5819ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.6, "max_line_length": 134, "alphanum_fraction": 0.5771428571, "num_tokens": 1248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.48992780118363977}}
{"text": "/*\n *  Distributed under our modified Boost Software License.\n *  Version 1.0 (see accompanying file LICENSE)\n */\n/**\n *  @file       Robot.hpp\n *  @author     Lydia Zoghbi, Ari Kupferberg\n *  @copyright  Copyright ARL 2019\n *  @date       10/15/2019\n *  @version    2.0\n *\n *  @brief      Header file for constructing a Robot class. \n *\n */\n\n#ifndef INCLUDE_ROBOT_HPP_\n#define INCLUDE_ROBOT_HPP_\n\n#include <vector>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <RobotPosition.hpp>\n#include <RobotPath.hpp>\n#include <Point.hpp>\n#include <PathPlanner.hpp>\n\n\n/**\n *  @brief      Class for creating a Robot object containing useful information about the system\n */\n\nclass Robot {\n private:\n   int numberLinks = 6;\n   Point initialEEPosition;\n   std::vector<double> initialJointAngles = {0, 0, 0, 0, 0, 0};\n   std::vector<RobotPath> path;\n    std::vector<std::vector<double>> dhParams{\n     {770, M_PI/2.0, 750, 0},\n     {1050, 0, 0, 0},\n     {200, M_PI/2.0, 0, 0},\n     {0, -M_PI/2.0, 1705, 0},\n     {0, M_PI/2.0, 0, 0},\n     {0, 0, 325, 0}};\n\n public:\n\n  /**\n   *  @brief    Constructor for class Robot \n   *  @param\tPoint of the robot's end effector position\n   *  @return\tInstance of robot\n   */\n   explicit Robot(const Point& startingPos);\n\n  /**\n   *  @brief     Compute the intermediate transformation between two DH frames\n   *  @param\t DH Table as matrix double\n   *  @return\t'A' transformation matrix\n   */\n   boost::numeric::ublas::matrix<double> computeATransform(std::vector<double> dhRow);\n\n  /**\n   *  @brief    Computing the forward kinematics for the Robot\n   *  @param\tVector of Robot's joint angles as double\n   *  @return\tVector of Point objects depicting Robot's joint positions\n   */\n   std::vector<Point> computeFk(std::vector<double> jointAngles);\n\n  /**\n   *  @brief    Computing a set of transformation matrices\n   *  @param\tVector of Robot's joint angles\n   *  @return\tVector of matrices representing the transformation from each joint frame to the base frame\n   */\n   std::vector<boost::numeric::ublas::matrix<double>> computeTransformationMatrices(std::vector<double> jointAngles);\n\n  /**\n   *  @brief    Computing the geometric Jacobian matrix\n   *  @param\tRobot's current position for performing a cross product\n   *  @param    Vector of transformation matrices\n   *  @return\tThe Jacobian matrix\n   */\n   boost::numeric::ublas::matrix<double> computeJacobian(RobotPosition robotPosition, std::vector<boost::numeric::ublas::matrix<double>> tTransforms);\n\n  /**\n   *  @brief    Computing the inverse kinematics for Robot's generated path\n   *  @param\tThe end effector's target position\n   *  @param    The environment to check for collisions\n   *  @return\tVector of RobotPosition object containing Points of joint positions\n   */\n   std::vector<RobotPosition> computeIK(Point targetPoint, Environment environment);\n\n  /**\n   *  @brief    Computes cross product of the two input vectors\n   *  @param\tVector to compute cross product of (1 of 2)\n   *  @param\tVector to compute cross product of (2 of 2)\n   *  @return\tVector of the resultant cross product\n   */\n   boost::numeric::ublas::vector<double> crossProduct(boost::numeric::ublas::vector<double> vector1, boost::numeric::ublas::vector<double> vector2);\n\n  /**\n   *  @brief    Computes the Moore-Penrose pseudoinverse\n   *  @param\tInput matrix to find the pseudoinverse of\n   *  @return\tPseudoinverse matrix result\n   */\n   boost::numeric::ublas::matrix<double> penroseInverseMatrix(boost::numeric::ublas::matrix<double> mat);\n\n};\n\n#endif // INCLUDE_ROBOT_HPP_\n", "meta": {"hexsha": "08446a0b82365ce46e3549e89c720017019a886b", "size": 3590, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/Robot.hpp", "max_stars_repo_name": "akupferb/808xmidterm", "max_stars_repo_head_hexsha": "c8e3aff6165948d0b4cde48e685b65f516cef6a4", "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/Robot.hpp", "max_issues_repo_name": "akupferb/808xmidterm", "max_issues_repo_head_hexsha": "c8e3aff6165948d0b4cde48e685b65f516cef6a4", "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/Robot.hpp", "max_forks_repo_name": "akupferb/808xmidterm", "max_forks_repo_head_hexsha": "c8e3aff6165948d0b4cde48e685b65f516cef6a4", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-10-13T22:46:15.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-13T22:46:15.000Z", "avg_line_length": 32.6363636364, "max_line_length": 150, "alphanum_fraction": 0.6857938719, "num_tokens": 962, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.6370308013713525, "lm_q1q2_score": 0.48992779974003575}}
{"text": "#include <Eigen/Core>\n#include <iostream>\n\n#include <pcl/point_types.h>\n#include <pcl/visualization/cloud_viewer.h>\n#include <pcl/visualization/point_cloud_color_handlers.h>\n\nusing namespace std ;\nusing namespace Eigen ;\n\nint\nmain (int argc, char** argv)\n{\n\tpcl::PointCloud<pcl::PointXYZ>::Ptr cloud_ptr (new pcl::PointCloud<pcl::PointXYZ>);\n\tpcl::PointXYZ zero;\n\tzero.x = zero.y = zero.z = 0.0;\n\n\tcloud_ptr->width  = 5;\n\tcloud_ptr->height = 1;\n\tcloud_ptr->points.resize (cloud_ptr->width * cloud_ptr->height);\n\n\t// Fill in the cloud data\n\tfor (size_t i = 0; i < cloud_ptr->points.size(); ++i)\n\t{\n\t\tcloud_ptr->points[i].x = 1024 * rand () / (RAND_MAX + 1.0f);\n\t\tcloud_ptr->points[i].y = 1024 * rand () / (RAND_MAX + 1.0f);\n\t\tcloud_ptr->points[i].z = 1024 * rand () / (RAND_MAX + 1.0f);\n\t}\n\tcout << \"cloud_ptr data\" << endl;\n\tfor (size_t i = 0; i < cloud_ptr->points.size (); ++i)\n\t{\n\t\tcout << cloud_ptr->points[i].x << \" \" << cloud_ptr->points[i].y << \" \" << cloud_ptr->points[i].z << \" \" << endl;\n\t}\n\tstd::cerr << \"cloud_ptr has: \" << cloud_ptr->points.size () << \" data points.\" << std::endl;\n\n\tEigen::Matrix<double, 5, 3> p_matrix;\n\tfor (size_t i = 0; i < cloud_ptr->points.size(); ++i)\n\t{\n\t\tp_matrix(i,0) = cloud_ptr->points[i].x;\n\t\tp_matrix(i,1) = cloud_ptr->points[i].y;\n\t\tp_matrix(i,2) = cloud_ptr->points[i].z;\n\t}\n\n\tcout << \"p_matrix\" << endl;\n\tcout << p_matrix << endl;\n\n//\tTransform<float, 3, Affine> t = Transform<float, 3, Affine>::\n//\tIdentity();\n//\tt.scale(0.8f);\n//\tt.rotate(AngleAxisf(0.25f * M_PI, Vector3f::UnitX()));\n//\tt.translate(Vector3f(1.5, 10.2, -5.1));\n\n\tpcl::visualization::PCLVisualizer viser(\"cloud_cluster\");\n\tpcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> single_color1(cloud_ptr, 150, 150, 0);\n//\tpcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> single_color2(cloud_projected, 0, 150, 200);\n//\tpcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> single_color3(cloud_filtered, 150, 0, 200);\n\tviser.addPointCloud (cloud_ptr, single_color1, \"cloud_ptr\");\n\n\tostringstream out;\n\tfor (size_t i = 0; i < cloud_ptr->points.size (); ++i)\n\t{\n\t\tout << \"point: \" << i;\n\t\tviser.addArrow(cloud_ptr->points[i], zero, i * 10, i * 30, i * 40, false, out.str());\n\t}\n//\tviser.addPointCloud (cloud_projected, single_color2, \"cloud_projected\");\n//\tviser.addPointCloud (cloud_filtered, single_color3, \"cloud_filtered\");\n\tviser.setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 20, \"cloud_ptr\");\n\tviser.addCoordinateSystem (1.0);\n\tviser.spin ();\n\t1;\n\n\treturn (0);\n}\n", "meta": {"hexsha": "cb380db79a5a8b5eede2f41fe4b7973564493b96", "size": 2549, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "eigen_pcl_0.cpp", "max_stars_repo_name": "RZin/eigen-practice", "max_stars_repo_head_hexsha": "fd3507c071e520f00fb0dfddab1f1c3eba3e51e9", "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": "eigen_pcl_0.cpp", "max_issues_repo_name": "RZin/eigen-practice", "max_issues_repo_head_hexsha": "fd3507c071e520f00fb0dfddab1f1c3eba3e51e9", "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": "eigen_pcl_0.cpp", "max_forks_repo_name": "RZin/eigen-practice", "max_forks_repo_head_hexsha": "fd3507c071e520f00fb0dfddab1f1c3eba3e51e9", "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.4459459459, "max_line_length": 114, "alphanum_fraction": 0.6724205571, "num_tokens": 813, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.48992779444032736}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// importance_sampling::maximal_finite_sums.hpp                              //\n//                                                                           //\n//  Copyright 2009 Erwann Rogard. Distributed under the Boost                //\n//  Software License, Version 1.0. (See accompanying file                    //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)         //\n///////////////////////////////////////////////////////////////////////////////\n#ifndef BOOST_STATISTICS_DETAIL_IMPORTANCE_SAMPLING_WEIGHTS_MAXIMAL_FINITE_SUMS_HPP_ER_2009\n#define BOOST_STATISTICS_DETAIL_IMPORTANCE_SAMPLING_WEIGHTS_MAXIMAL_FINITE_SUMS_HPP_ER_2009\n#include <boost/iterator/iterator_traits.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n\nnamespace boost{\nnamespace statistics{\nnamespace detail{\nnamespace importance_sampling{\n\n    // Breaks down the summation of *i, i in [b,e) into maximal finite amounts,\n    // each of which are copied to the output iterator i\n    //\n    // Note: Primarily for use by find_scale_to_finite_sum\n    template<typename InIt,typename OutIt>\n    OutIt maximal_finite_sums(InIt b, InIt e, OutIt i)\n    {\n        typedef typename iterator_value<InIt>::type value_type;\n        value_type sum = static_cast<value_type>(0);\n        while(b!=e){\n            value_type d = *b;\n            if( boost::math::isinf( sum + d ) ){\n                *i = sum;\n                sum = d;\n                ++i;\n            }else{\n                sum += d;\n            }\n            ++b;\n        }\n        return i;\n    };\n    \n}// importance_weights\n}// detail\n}// statistics\n}// boost\n\n#endif", "meta": {"hexsha": "0b896ee05b1eaf2c2ab632a5745962e82947f07a", "size": 1714, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "importance_sampling/boost/statistics/detail/importance_sampling/weights/maximal_finite_sums.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": "importance_sampling/boost/statistics/detail/importance_sampling/weights/maximal_finite_sums.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": "importance_sampling/boost/statistics/detail/importance_sampling/weights/maximal_finite_sums.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.2608695652, "max_line_length": 91, "alphanum_fraction": 0.5390898483, "num_tokens": 353, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.6370307875894139, "lm_q1q2_score": 0.48992778914061913}}
{"text": "/*\n *  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 *  Exactly the same as barycentric_rational.hpp, but delivers values in $\\mathbb{R}^n$.\n *  In some sense this is trivial, since each component of the vector is computed in exactly the same\n *  as would be computed by barycentric_rational.hpp. But this is a bit more efficient and convenient.\n */\n\n#ifndef BOOST_MATH_INTERPOLATORS_VECTOR_BARYCENTRIC_RATIONAL_HPP\n#define BOOST_MATH_INTERPOLATORS_VECTOR_BARYCENTRIC_RATIONAL_HPP\n\n#include <memory>\n#include <boost/math/interpolators/detail/vector_barycentric_rational_detail.hpp>\n\nnamespace boost{ namespace math{ namespace interpolators{\n\ntemplate<class TimeContainer, class SpaceContainer>\nclass vector_barycentric_rational\n{\npublic:\n    using Real = typename TimeContainer::value_type;\n    using Point = typename SpaceContainer::value_type;\n    vector_barycentric_rational(TimeContainer&& times, SpaceContainer&& points, size_t approximation_order = 3);\n\n    void operator()(Point& x, Real t) const;\n\n    // I have validated using google benchmark that returning a value is no more expensive populating it,\n    // at least for Eigen vectors with known size at compile-time.\n    // This is kinda a weird thing to discover since it goes against the advice of basically every high-performance computing book.\n    Point operator()(Real t) const {\n        Point p;\n        this->operator()(p, t);\n        return p;\n    }\n\n    void prime(Point& dxdt, Real t) const {\n        Point x;\n        m_imp->eval_with_prime(x, dxdt, t);\n    }\n\n    Point prime(Real t) const {\n        Point p;\n        this->prime(p, t);\n        return p;\n    }\n\n    void eval_with_prime(Point& x, Point& dxdt, Real t) const {\n        m_imp->eval_with_prime(x, dxdt, t);\n        return;\n    }\n\n    std::pair<Point, Point> eval_with_prime(Real t) const {\n        Point x;\n        Point dxdt;\n        m_imp->eval_with_prime(x, dxdt, t);\n        return {x, dxdt};\n    }\n\nprivate:\n    std::shared_ptr<detail::vector_barycentric_rational_imp<TimeContainer, SpaceContainer>> m_imp;\n};\n\n\ntemplate <class TimeContainer, class SpaceContainer>\nvector_barycentric_rational<TimeContainer, SpaceContainer>::vector_barycentric_rational(TimeContainer&& times, SpaceContainer&& points, size_t approximation_order):\n m_imp(std::make_shared<detail::vector_barycentric_rational_imp<TimeContainer, SpaceContainer>>(std::move(times), std::move(points), approximation_order))\n{\n    return;\n}\n\ntemplate <class TimeContainer, class SpaceContainer>\nvoid vector_barycentric_rational<TimeContainer, SpaceContainer>::operator()(typename SpaceContainer::value_type& p, typename TimeContainer::value_type t) const\n{\n    m_imp->operator()(p, t);\n    return;\n}\n\n}}}\n#endif\n", "meta": {"hexsha": "1b899fbd5f80854ac32b456e627c1eb09e87c61c", "size": 2892, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/math/interpolators/vector_barycentric_rational.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/vector_barycentric_rational.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/vector_barycentric_rational.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": 34.843373494, "max_line_length": 164, "alphanum_fraction": 0.7302904564, "num_tokens": 701, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851919, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.4899277876970149}}
{"text": "/*\nCopyright 2014 Rogier van Dalen.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/** \\file\nTest lexicographical.hpp.\n*/\n\n#define BOOST_TEST_MODULE test_math_lexicographical_fast\n#include \"utility/test/boost_unit_test.hpp\"\n\n#include \"math/lexicographical.hpp\"\n\n#include <string>\n#include <vector>\n\n#include <boost/mpl/assert.hpp>\n\n#include \"math/sequence.hpp\"\n#include \"math/arithmetic_magma.hpp\"\n#include \"math/cost.hpp\"\n\n#include \"./make_lexicographical.hpp\"\n\nusing range::first;\nusing range::second;\n\nBOOST_AUTO_TEST_SUITE (test_suite_lexicographical)\n\nBOOST_AUTO_TEST_CASE (test_lexicographical_static) {\n    // Basic requirements for the component types.\n    BOOST_MPL_ASSERT ((math::is::monoid <math::callable::choose, cost>));\n    BOOST_MPL_ASSERT ((math::is::monoid <math::callable::choose,\n        math::sequence <char>>));\n\n    BOOST_MPL_ASSERT ((math::is::semiring <\n        math::left, math::callable::times, math::callable::plus,\n        lexicographical>));\n\n    BOOST_MPL_ASSERT ((math::is::distributive <\n        math::left, math::callable::times, math::callable::plus,\n        lexicographical>));\n    BOOST_MPL_ASSERT ((math::is::distributive <\n        math::right, math::callable::times, math::callable::plus,\n        lexicographical>));\n    BOOST_MPL_ASSERT ((math::is::distributive <\n        math::either, math::callable::times, math::callable::plus,\n        lexicographical>));\n\n    BOOST_MPL_ASSERT ((math::is::distributive <\n        math::left, math::callable::times, math::callable::choose,\n        lexicographical>));\n    BOOST_MPL_ASSERT ((math::is::distributive <\n        math::left, math::callable::times, math::callable::choose, cost>));\n    BOOST_MPL_ASSERT ((math::is::distributive <\n        math::left, math::callable::times, math::callable::choose,\n        math::sequence <char>>));\n\n    BOOST_MPL_ASSERT ((math::is::distributive <\n        math::left, math::callable::times, math::callable::choose,\n        lexicographical>));\n\n    {\n        BOOST_MPL_ASSERT ((math::is::associative <math::callable::times,\n            math::lexicographical <math::over <math::cost <float>>>>));\n        BOOST_MPL_ASSERT ((math::is::associative <math::callable::times,\n            math::lexicographical <math::over <math::sequence <char>>>>));\n    }\n    {\n        BOOST_MPL_ASSERT ((math::is::commutative <math::callable::times,\n            math::lexicographical <math::over <math::cost <float>>>>));\n        BOOST_MPL_ASSERT_NOT ((math::is::commutative <math::callable::times,\n            math::lexicographical <math::over <math::sequence <char>>>>));\n    }\n    typedef math::lexicographical <math::over <math::cost <float>>>\n        cost;\n    typedef math::lexicographical <math::over <math::sequence <char>>>\n        sequence;\n    {\n        BOOST_MPL_ASSERT ((math::is::approximate <\n            math::callable::times (cost, cost)>));\n        BOOST_MPL_ASSERT_NOT ((math::is::approximate <\n            math::callable::times (sequence, sequence)>));\n        BOOST_MPL_ASSERT_NOT ((math::is::approximate <\n            math::callable::plus (cost, cost)>));\n        BOOST_MPL_ASSERT_NOT ((math::is::approximate <\n            math::callable::plus (sequence, sequence)>));\n    }\n    {\n        BOOST_MPL_ASSERT_NOT ((math::is::idempotent <\n            math::callable::times (cost, cost)>));\n        BOOST_MPL_ASSERT_NOT ((math::is::idempotent <\n            math::callable::times (sequence, sequence)>));\n        BOOST_MPL_ASSERT ((math::is::idempotent <\n            math::callable::plus (cost, cost)>));\n        BOOST_MPL_ASSERT ((math::is::idempotent <\n            math::callable::plus (sequence, sequence)>));\n    }\n    {\n        BOOST_MPL_ASSERT_NOT ((math::is::path_operation <\n            math::callable::times (cost, cost)>));\n        BOOST_MPL_ASSERT_NOT ((math::is::path_operation <\n            math::callable::times (sequence, sequence)>));\n        BOOST_MPL_ASSERT ((math::is::path_operation <\n            math::callable::plus (cost, cost)>));\n        BOOST_MPL_ASSERT ((math::is::path_operation <\n            math::callable::plus (sequence, sequence)>));\n    }\n}\n\nBOOST_AUTO_TEST_CASE (test_lexicographical_spot) {\n    std::string ab = \"ab\";\n    std::string abc = \"abc\";\n    std::string abd = \"abd\";\n    std::string c = \"c\";\n    std::string d = \"d\";\n\n    lexicographical ab4 = make_lexicographical (4, ab);\n    BOOST_CHECK_EQUAL (first (ab4.components()).value(), 4.f);\n    BOOST_CHECK_EQUAL (first (second (ab4.components()).symbols()), 'a');\n    BOOST_CHECK_EQUAL (second (second (ab4.components()).symbols()), 'b');\n\n    lexicographical c7 = make_lexicographical (7, c);\n    lexicographical abc11 = make_lexicographical (11, abc);\n\n    {\n        auto ab4_2 = math::make_lexicographical (\n            math::cost <float> (4), math::sequence <char> (std::string (\"ab\")));\n        static_assert (\n            std::is_same <decltype (ab4_2), lexicographical>::value, \"\");\n\n        BOOST_CHECK (ab4_2 == ab4);\n    }\n    {\n        auto components = range::make_tuple (\n            math::cost <float> (4), math::sequence <char> (std::string (\"ab\")));\n        auto ab4_2 = math::make_lexicographical_over (components);\n        static_assert (\n            std::is_same <decltype (ab4_2), lexicographical>::value, \"\");\n\n        BOOST_CHECK (ab4_2 == ab4);\n    }\n\n    BOOST_CHECK_EQUAL (ab4 * c7, abc11);\n    BOOST_CHECK_EQUAL (ab4 * math::one <lexicographical>(), ab4);\n    // divide is not implemented.\n    // BOOST_CHECK_EQUAL (math::divide <math::left> (abc11, ab4), c7);\n\n    BOOST_CHECK_EQUAL (ab4 + abc11, ab4);\n    BOOST_CHECK_EQUAL (ab4 + math::zero <lexicographical>(), ab4);\n\n    BOOST_CHECK (math::equal (\n        make_empty_lexicographical (0), make_lexicographical (0, \"\")));\n    BOOST_CHECK (math::equal (\n        make_empty_lexicographical (7), make_lexicographical (7, \"\")));\n    BOOST_CHECK (!math::equal (\n        make_empty_lexicographical (7), make_lexicographical (0, \"\")));\n    BOOST_CHECK (!math::equal (\n        make_empty_lexicographical (7), make_lexicographical (6, \"\")));\n\n    BOOST_CHECK (math::equal (\n        make_single_lexicographical (0, 'a'),\n        make_lexicographical (0, \"a\")));\n    BOOST_CHECK (math::equal (\n        make_single_lexicographical (7, 'b'),\n        make_lexicographical (7, \"b\")));\n    BOOST_CHECK (!math::equal (\n        make_single_lexicographical (7, 'a'),\n        make_lexicographical (6, \"a\")));\n    BOOST_CHECK (!math::equal (\n        make_single_lexicographical (7, 'a'),\n        make_lexicographical (7, \"b\")));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "59f113d5d125df84c94ffee8461c0330f268e58f", "size": 7003, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/math/test-lexicographical-1-fast.cpp", "max_stars_repo_name": "rogiervd/math", "max_stars_repo_head_hexsha": "96174afac1a2933d71cb7ae3962437f860fc10ec", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/math/test-lexicographical-1-fast.cpp", "max_issues_repo_name": "rogiervd/math", "max_issues_repo_head_hexsha": "96174afac1a2933d71cb7ae3962437f860fc10ec", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/math/test-lexicographical-1-fast.cpp", "max_forks_repo_name": "rogiervd/math", "max_forks_repo_head_hexsha": "96174afac1a2933d71cb7ae3962437f860fc10ec", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.25, "max_line_length": 80, "alphanum_fraction": 0.6415821791, "num_tokens": 1777, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851919, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.4899277876970148}}
{"text": "#include <jfs/differential_ops/grid_diff2d.h>\n\n#include <Eigen/Eigen>\n\nnamespace jfs {\n\ntemplate <class SparseMatrix>\nJFS_INLINE void gridDiff2D<SparseMatrix>::Laplace(const grid2D* grid, SparseMatrix &dst, unsigned int dims, unsigned int fields)\n{\n    auto btype = grid->bound_type_;\n    auto L = grid->L;\n    auto N = grid->N;\n    auto D = grid->D;\n\n    typedef Eigen::Triplet<float> T;\n    std::vector<T> tripletList;\n    tripletList.reserve(N*N*5*dims);\n\n    for (int idx = 0; idx < dims*fields*N*N; idx++)\n    {\n        int idx_tmp = idx;\n        int j = idx_tmp / (N*dims*fields);\n        idx_tmp -= j * (N*dims*fields);\n        int i = idx_tmp / (dims*fields);\n        idx_tmp -= i * (dims*fields);\n        int f = idx_tmp / dims;\n        idx_tmp -= f * dims;\n        int d = idx_tmp;\n\n        int iMat, jMat;\n\n        iMat = N*fields*dims*j + fields*dims*i + dims*f + d;\n        jMat = iMat;\n        tripletList.push_back(T(iMat,jMat,-4.f));\n\n        int i_tmp = i;\n        for (int offset = -1; offset < 2; offset+=2)\n        {\n            i = i_tmp + offset;\n            if ( (i == -1 || i == N) && btype == ZERO)\n                continue;\n            else if ( i == -1 )\n                i = (N-2);\n            else if ( i == N )\n                i = 1;\n            jMat = N*fields*dims*j + fields*dims*i + dims*f + d;\n            tripletList.push_back(T(iMat,jMat,1.f));\n        }\n        i = i_tmp;\n\n        int j_tmp = j;\n        for (int offset = -1; offset < 2; offset+=2)\n        {\n            j = j_tmp + offset;\n            if ( (j == -1 || j == N) && btype == ZERO)\n                continue;\n            else if ( j == -1 )\n                j = (N-2);\n            else if ( j == N )\n                j = 1;\n            jMat = N*fields*dims*j + fields*dims*i + dims*f + d;\n            tripletList.push_back(T(iMat,jMat,1.f));\n        }\n        j = j_tmp;\n    }\n\n    dst = SparseMatrix(N*N*dims*fields,N*N*dims*fields);\n    dst.setFromTriplets(tripletList.begin(), tripletList.end());\n    dst = 1.f/(D*D) * dst;\n}\n\n\ntemplate <class SparseMatrix>\nJFS_INLINE void gridDiff2D<SparseMatrix>::div(const grid2D* grid, SparseMatrix &dst, unsigned int fields)\n{\n    auto btype = grid->bound_type_;\n    auto L = grid->L;\n    auto N = grid->N;\n    auto D = grid->D;\n\n    typedef Eigen::Triplet<float> T;\n    std::vector<T> tripletList;\n    tripletList.reserve(N*N*2*2);\n\n    int dims = 2;\n\n    for (int idx = 0; idx < dims*fields*N*N; idx++)\n    {\n        int idx_tmp = idx;\n        int j = idx_tmp / (N*dims*fields);\n        idx_tmp -= j * (N*dims*fields);\n        int i = idx_tmp / (dims*fields);\n        idx_tmp -= i * (dims*fields);\n        int f = idx_tmp / dims;\n        idx_tmp -= f * dims;\n        int d = idx_tmp;\n\n        int iMat, jMat;\n\n        iMat = N*fields*j + fields*i + f;\n\n        int i_tmp = i;\n        for (int offset = -1; offset < 2 && d == 0; offset+=2)\n        {\n            i = i_tmp + offset;\n            if ( (i == -1 || i == N) && btype == ZERO)\n                continue;\n            else if ( i == -1 )\n                i = (N-2);\n            else if ( i == N )\n                i = 1;\n            jMat = N*fields*dims*j + fields*dims*i + dims*f + d;\n            tripletList.push_back(T(iMat,jMat,(float) offset));\n        }\n        i = i_tmp;\n\n        int j_tmp = j;\n        for (int offset = -1; offset < 2 && d == 1; offset+=2)\n        {\n            j = j_tmp + offset;\n            if ( (j == -1 || j == N) && btype == ZERO)\n                continue;\n            else if ( j == -1 )\n                j = (N-2);\n            else if ( j == N )\n                j = 1;\n            jMat = N*fields*dims*j + fields*dims*i + dims*f + d;\n            tripletList.push_back(T(iMat,jMat,(float) offset));\n        }\n        j = j_tmp;\n    }\n\n    dst = SparseMatrix(N*N*fields,N*N*2*fields);\n    dst.setFromTriplets(tripletList.begin(), tripletList.end());\n    dst = 1.f/(2*D) * dst;\n}\n\n\ntemplate <class SparseMatrix>\nJFS_INLINE void gridDiff2D<SparseMatrix>::grad(const grid2D* grid, SparseMatrix &dst, unsigned int fields)\n{\n    auto btype = grid->bound_type_;\n    auto L = grid->L;\n    auto N = grid->N;\n    auto D = grid->D;\n\n    typedef Eigen::Triplet<float> T;\n    std::vector<T> tripletList;\n    tripletList.reserve(N*N*2*2);\n\n    int dims = 2;\n\n    for (int idx = 0; idx < dims*fields*N*N; idx++)\n    {\n        int idx_tmp = idx;\n        int j = idx_tmp / (N*dims*fields);\n        idx_tmp -= j * (N*dims*fields);\n        int i = idx_tmp / (dims*fields);\n        idx_tmp -= i * (dims*fields);\n        int f = idx_tmp / dims;\n        idx_tmp -= f * dims;\n        int d = idx_tmp;\n\n        int iMat, jMat;\n\n        iMat = N*fields*dims*j + fields*dims*i + dims*f + d;\n\n        int i_tmp = i;\n        for (int offset = -1; offset < 2 && d == 0; offset+=2)\n        {\n            i = i_tmp + offset;\n            if ( (i == -1 || i == N) && btype == ZERO)\n                continue;\n            else if ( i == -1 )\n                i = (N-2);\n            else if ( i == N )\n                i = 1;\n            jMat = N*fields*j + fields*i + f;\n            tripletList.push_back(T(iMat,jMat,(float) offset));\n        }\n        i = i_tmp;\n\n        int j_tmp = j;\n        for (int offset = -1; offset < 2 && d == 1; offset+=2)\n        {\n            j = j_tmp + offset;\n            if ( (j == -1 || j == N) && btype == ZERO)\n                continue;\n            else if ( j == -1 )\n                j = (N-2);\n            else if ( j == N )\n                j = 1;\n            jMat = N*fields*j + fields*i + f;\n            tripletList.push_back(T(iMat,jMat,(float) offset));\n        }\n        j = j_tmp;\n    }\n\n    dst = SparseMatrix(N*N*dims*fields,N*N*fields);\n    dst.setFromTriplets(tripletList.begin(), tripletList.end());\n    dst = 1.f/(2*D) * dst;\n}\n\n\n// explicit instantiation of templates\n#ifdef JFS_STATIC\ntemplate class gridDiff2D<Eigen::SparseMatrix<float, Eigen::ColMajor>>;\ntemplate class gridDiff2D<Eigen::SparseMatrix<float, Eigen::RowMajor>>;\n#endif\n\n\n} // namespace jfs", "meta": {"hexsha": "3a099b6a82192efdc523249d8734103d803115c9", "size": 6001, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "jfs/differential_ops/grid_diff2d.cpp", "max_stars_repo_name": "jackm97/jfs", "max_stars_repo_head_hexsha": "49b0f4d999ddd215ef9fb574ba92314e48437c2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "jfs/differential_ops/grid_diff2d.cpp", "max_issues_repo_name": "jackm97/jfs", "max_issues_repo_head_hexsha": "49b0f4d999ddd215ef9fb574ba92314e48437c2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "jfs/differential_ops/grid_diff2d.cpp", "max_forks_repo_name": "jackm97/jfs", "max_forks_repo_head_hexsha": "49b0f4d999ddd215ef9fb574ba92314e48437c2e", "max_forks_repo_licenses": ["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.3066037736, "max_line_length": 128, "alphanum_fraction": 0.4815864023, "num_tokens": 1746, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767778695834, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.48991897198701356}}
{"text": "#pragma once\n\n#include \"enum.hpp\"\n#include \"cc_trade_stream.hpp\"\n#include \"utils.hpp\"\n#include \"trade_data.hpp\"\n\n#include <boost/log/trivial.hpp>\n\n#include <concepts>\n#include <map>\n\nnamespace profitview\n{\n\ntemplate<std::floating_point Float = double, std::integral Int = int>\nclass CcDamped : public CcTradeStream<Float, Int>\n{\npublic:\n    CcDamped(\n        const std::string trade_stream_name,\n        OrderExecutor* executor,\n        Int lookback,\n        Float reversion_level,\n        Float base_quantity,\n        Float damping,\n        const std::string& csv_name = \"Damped.csv\")\n        : CcTradeStream<Float, Int>(trade_stream_name, executor, csv_name)\n        , lookback_{lookback}\n        , reversion_level_{reversion_level}\n        , base_quantity_{base_quantity}\n        , damping_{damping}\n    {}\n\n    void onStreamedTrade(TradeData const& trade_data) override\n    {\n        trade_data.print();\n\n        auto& [prices, mean_reached, initial_mean, initial_stdev]{price_structure_[trade_data.symbol]};\n\n        prices.emplace_back(trade_data.price);\n\n        if (not mean_reached and prices.size() > lookback_)\n        {\n            initial_mean = util::ma(prices);\n            initial_stdev = util::stdev(prices, initial_mean, lookback_);\n            BOOST_LOG_TRIVIAL(info) << \"Initial mean: \" << initial_mean << std::endl << std::endl;\n            mean_reached = true;\n        }\n        else if (mean_reached)\n        {\n            auto mean{util::ma(prices)};\n            BOOST_LOG_TRIVIAL(info) << \"MA: \" << mean << std::endl << std::endl;\n\n            auto const& damping_factor{damping_ * initial_stdev};\n\n            // Version 1: chopping the tops/bottoms off outliers\n            auto const& cut_damped{prices | std::ranges::views::transform([&mean, &damping_factor](auto price) -> auto {\n                                       return std::abs(price - mean) > damping_factor\n                                                ? boost::math::sign(price - mean) * damping_factor + mean\n                                                : price;\n                                   })};\n\n            // Version 2: excluding outliers\n            auto excluded_damped{prices | std::ranges::views::filter([&mean, &damping_factor](auto price) -> auto {\n                                     return std::abs(price - mean) < damping_factor;\n                                 })};\n\n            // Using Version 2 this time:\n            auto std_reversion{reversion_level_ * util::stdev(excluded_damped, mean, lookback_)};\n            BOOST_LOG_TRIVIAL(info) << \"Std Reversion: \" << std_reversion << std::endl << std::endl;\n\n            prices.pop_front();    \n\n            bool \n                sell_signal{trade_data.price > mean + std_reversion},\n                buy_signal {trade_data.price < mean - std_reversion};\n\n            if (sell_signal)\n            {    \n                this->new_order(trade_data.symbol, Side::Sell, base_quantity_, OrderType::Market);\n            }\n            else if (buy_signal)\n            {    \n                this->new_order(trade_data.symbol, Side::Buy, base_quantity_, OrderType::Market);\n            }\n\n            this->writeCsv(\n                trade_data.symbol,\n                trade_data.price,\n                toString(trade_data.side).data(),\n                trade_data.size,\n                trade_data.source,\n                trade_data.time,\n                mean,\n                std_reversion,\n                buy_signal ? \"Buy\" : (sell_signal ? \"Sell\" : \"No trade\"));\n        }\n    }\n\n    struct Data\n    {\n        std::deque<Float> prices;\n        bool mean_reached;\n        Float initial_mean, initial_stdev;\n    };\n\nprivate:\n    const Int lookback_;\n    const Float reversion_level_;\n    const Float base_quantity_;\n    const Float damping_;\n\n    std::map<std::string, Data> price_structure_;\n};\n\n}    // namespace profitview", "meta": {"hexsha": "cb74b1b8475b76f4f240afa3966d38ea4dda394e", "size": 3883, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/cc_damped_mr.hpp", "max_stars_repo_name": "Twon/cpp_crypto_algos", "max_stars_repo_head_hexsha": "e785f6c25ef50dc3c2f593b08b6857dffcd32eca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cc_damped_mr.hpp", "max_issues_repo_name": "Twon/cpp_crypto_algos", "max_issues_repo_head_hexsha": "e785f6c25ef50dc3c2f593b08b6857dffcd32eca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cc_damped_mr.hpp", "max_forks_repo_name": "Twon/cpp_crypto_algos", "max_forks_repo_head_hexsha": "e785f6c25ef50dc3c2f593b08b6857dffcd32eca", "max_forks_repo_licenses": ["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.188034188, "max_line_length": 120, "alphanum_fraction": 0.5593613186, "num_tokens": 840, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007393, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4898816716504238}}
{"text": "#define BOOST_TEST_MODULE TS test\n#include <boost/test/unit_test.hpp>\n#include \"Sum.h\"\n#include \"Variable.h\"\n#include \"System.h\"\n\n\nusing namespace omnn::math;\nusing namespace boost::unit_test;\n\ntemplate<typename T>\nT bits_in_use(T v){\n    T bits = 0;\n    while (v) {\n        ++bits;\n        v = v >> 1;\n    }\n    return bits;\n}\n\n/// Control theory generalization hints are here: finds best moves/goods for single dimension\nBOOST_AUTO_TEST_CASE(TS_1d) {\n    //    System s;\n    //    s.MakeTotalEqu(true);\n    // y=f(x), where x is code of sequence\n    Variable time, price;\n    int points[] = {10, 1, 30, 5};\n    auto sz = std::size(points);\n    auto encodeBits = bits_in_use(sz);\n    int mask = (1 << encodeBits) - 1;\n\n    auto sys = 0_v;\n\n    // points math data\n    Variable x;\n    auto ExtractMove = [&](int i) {\n        auto targetId = x.And((i + 1) * encodeBits, mask << (i * encodeBits)).shr(i * encodeBits);\n        return targetId;\n    };\n    // last move back to start\n    auto statement = ExtractMove(sz - 1).Equals(0);\n    //    s << statement;\n    sys += statement.sq();\n    // moves uniqueness\n    for (int i = 1; i < sz; ++i) {\n        statement = ExtractMove(i).NotEquals(\n            ExtractMove(i - 1)); // FIXME: NotEquals behaviour changed. It was 0 for a!=b and 1 for a==b.  then it\n                                 // became  /=(a-b) like if a=b then its a division by zero which must exclude branches,\n                                 // but does it or it just breaks expression\n                                 //        s << statement;\n        sys += statement.sq();\n    }\n    // generate function of getting point value by its index\n    auto ValueByIdx = [&](Valuable i) {\n        Variable id;\n        static auto MathDataForm = [&]() {\n            auto data = 1_v;\n            Variable val;\n            for (int i = 0; i < sz; ++i) {\n                data.logic_or(id.Equals(i).logic_and(val.Equals(points[i])));\n            }\n            return data(val);\n        };\n\n        static auto data = MathDataForm();\n\n        auto localData = data;\n        localData.Eval(id, i);\n        return localData;\n    };\n    // move len square\n    auto MoveLenSq = [&](int i) {\n        assert(i);\n        auto prev = ExtractMove(i - 1);\n        auto target = ExtractMove(i);\n        auto diff = ValueByIdx(prev) - ValueByIdx(target);\n        return diff ^ 2;\n    };\n    auto SumSqLens = [&]() {\n        auto sum = 0_v;\n        for (int i = 1; i < sz; ++i)\n            sum += MoveLenSq(i);\n        return sum;\n    };\n    auto sumSqLens = SumSqLens();\n}\n\n\nBOOST_AUTO_TEST_CASE(TS_2d\n                     ,*disabled()\n                     )\n{\n\tVariable time, price;\n    std::pair<Valuable,Valuable> points[] = {\n\t\t{0,0},\n\t\t{1,5},\n\t\t{3,8},\n\t};\n\tauto bits = 2;\n\n\tVariable xpath, ypath;\n    Variable xmove[std::size(points)], ymove[std::size(points)];\n//\n//    auto unix = xpath.equals((xmove[0] << (2 * 2)) + (xmove[1] << 2) + xmove[2]);\n//    auto uniy = ypath.equals((xmove[0] << (2 * 2)) + (xmove[1] << 2) + xmove[2]);\n\n//    auto xext = unix(\n    \nIMPLEMENT\n}\n", "meta": {"hexsha": "638b6cd680bfb652dea707f1fd66992bc2f1db57", "size": 3072, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "omnn/math/test/ts.cpp", "max_stars_repo_name": "iHateInventNames/openmind", "max_stars_repo_head_hexsha": "2587b811e594daf9d9c235cb63eeae2950e93ff0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "omnn/math/test/ts.cpp", "max_issues_repo_name": "iHateInventNames/openmind", "max_issues_repo_head_hexsha": "2587b811e594daf9d9c235cb63eeae2950e93ff0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2016-05-21T08:48:41.000Z", "max_issues_repo_issues_event_max_datetime": "2017-02-22T19:37:03.000Z", "max_forks_repo_path": "omnn/math/test/ts.cpp", "max_forks_repo_name": "iHateInventNames/openmind", "max_forks_repo_head_hexsha": "2587b811e594daf9d9c235cb63eeae2950e93ff0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6756756757, "max_line_length": 120, "alphanum_fraction": 0.53125, "num_tokens": 849, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127641048443, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.48987131461503763}}
{"text": "#pragma once\n\n#include <boost/hana/string.hpp>\n#include <boost/hana/value.hpp>\n#include <boost/hana/power.hpp>\n#include <boost/hana/div.hpp>\n\nnamespace tvm {\n\nnamespace hana = boost::hana;\n\ntemplate<unsigned radix>\nconstexpr size_t get_magnitude(size_t num) {\n  unsigned i = 0;\n  while (num > 0) {\n    num /= radix;\n    ++i;\n  }\n  return i;\n}\n\nconstexpr char hex_sym(unsigned num) {\n  constexpr char arr[] = \"0123456789abcdef\";\n  return arr[std::min(num, 16u)];\n}\n\ntemplate <unsigned radix, class X, size_t ...i>\nconstexpr auto to_string(X x, std::index_sequence<i...>) {\n  constexpr size_t mag = get_magnitude<radix>(X::value);\n  return hana::string<\n    hana::size_c<hex_sym(\n      hana::value(x / hana::power(hana::size_c<radix>, hana::size_c<mag - i - 1>)\n                    % hana::size_c<radix>))\n      >...>{};\n}\n\ntemplate <unsigned radix, class X>\nconstexpr auto to_string(X) {\n  using namespace hana::literals;\n  if constexpr (X::value == 0)\n    return \"0\"_s;\n  else\n    return to_string<radix>(hana::size_c<static_cast<size_t>(X::value)>,\n                            std::make_index_sequence<get_magnitude<radix>(X::value)>());\n}\n\n} // namespace tvm\n\n", "meta": {"hexsha": "eb56850cc64cec92b8cc2f131c6806e6d71c164d", "size": 1162, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "llvm/projects/ton-compiler/cpp-sdk/tvm/static_print.hpp", "max_stars_repo_name": "NoamDev/TON-Compiler", "max_stars_repo_head_hexsha": "f76aa2084c7f09a228afef4a6e073c37b350c8f3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 59.0, "max_stars_repo_stars_event_min_datetime": "2019-10-22T16:21:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T20:32:32.000Z", "max_issues_repo_path": "llvm/projects/ton-compiler/cpp-sdk/tvm/static_print.hpp", "max_issues_repo_name": "NoamDev/TON-Compiler", "max_issues_repo_head_hexsha": "f76aa2084c7f09a228afef4a6e073c37b350c8f3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 51.0, "max_issues_repo_issues_event_min_datetime": "2019-10-23T11:55:08.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-21T06:32:11.000Z", "max_forks_repo_path": "llvm/projects/ton-compiler/cpp-sdk/tvm/static_print.hpp", "max_forks_repo_name": "NoamDev/TON-Compiler", "max_forks_repo_head_hexsha": "f76aa2084c7f09a228afef4a6e073c37b350c8f3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2019-10-22T19:56:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-12T14:45:15.000Z", "avg_line_length": 23.7142857143, "max_line_length": 88, "alphanum_fraction": 0.6445783133, "num_tokens": 336, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127603871312, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.48987131248226584}}
{"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\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include <iostream>\n#include <cmath>\n#include <complex>\n#include <boost/numeric/mtl/concept/collection.hpp>\n#include <boost/numeric/mtl/matrix/dense2D.hpp>\n#include <boost/numeric/mtl/matrix/morton_dense.hpp> \n#include <boost/numeric/mtl/matrix/compressed2D.hpp> \n#include <boost/numeric/mtl/matrix/laplacian_setup.hpp> \n#include <boost/numeric/mtl/vector/dense_vector.hpp>\n#include <boost/numeric/mtl/recursion/predefined_masks.hpp>\n#include <boost/numeric/mtl/operation/print.hpp>\n#include <boost/numeric/mtl/operation/rank_two_update.hpp>\n\n\nusing namespace std;  \n\ninline double value(double)\n{\n    return 1.0;\n}\n\ninline complex<double> value(complex<double>)\n{\n    return complex<double>(1.0, 1.0);\n}\n\ninline double test_value(double)\n{\n    return 10.0;\n}\n\ninline complex<double> test_value(complex<double>)\n{\n    return complex<double>(10.0, -10.0);\n}\n\n\ntemplate <typename Matrix>\nvoid test(Matrix& matrix, const char* name)\n{\n    using mtl::conj; using mtl::Collection;\n    const unsigned max_print_size= 25;\n\n    cout << \"\\n\" << name << \"\\n\";\n    set_to_zero(matrix);\n\n    typename Collection<Matrix>::size_type          nr= num_rows(matrix), nc= num_cols(matrix);\n    typedef typename Collection<Matrix>::value_type value_type;\n    value_type                                      zero(0.0);\n    mtl::dense_vector<value_type>                   x(nr, zero), y(nc, zero);\n\n    x[1]= 1.0; x[2]= 2.0;\n    value_type ref(0), v= value(ref);\n\n    y[4]= 4.0*v; y[5]= 5.0*v; y[6]= 6.0*v;\n\n    rank_two_update(matrix, x, y);\n    if (nr <= max_print_size)\n\tcout << \"\\nx= \" << x << \"y= \" << y << \"matrix = \\n\" << matrix << \"\\n\";\n\n    MTL_THROW_IF(matrix[2][5] != test_value(v), mtl::runtime_error(\"wrong value\"));\n    MTL_THROW_IF(matrix[5][2] != conj(test_value(v)), mtl::runtime_error(\"wrong value\"));\n}\n\n\n\nint main(int argc, char* argv[])\n{\n    using namespace mtl;\n\n    cout << \"matrix size must be at least 7 x 7\\n\";\n    unsigned size= 7;\n    if (argc > 1) size= atoi(argv[1]);     \n\n    dense2D<double>                                      dr(size, size);\n    dense2D<double, mat::parameters<col_major> >      dc(size, size);\n    morton_dense<double, recursion::morton_z_mask>       mzd(size, size);\n    morton_dense<double, recursion::doppled_2_row_mask>  d2r(size, size);\n    compressed2D<double>                                 cr(size, size);\n    compressed2D<double, mat::parameters<col_major> > cc(size, size);\n\n    dense2D<complex<double> >                            drc(size, size);\n    compressed2D<complex<double> >                       crc(size, size);\n\n    test(dr, \"Dense row major\");\n    test(dc, \"Dense column major\");\n    test(mzd, \"Morton Z-order\");\n    test(d2r, \"Hybrid 2 row-major\");\n    test(cr, \"Compressed row major\");\n    test(cc, \"Compressed column major\");\n    test(drc, \"Dense row major complex\");\n    test(crc, \"Compressed row major complex\");\n\n    return 0;\n}\n", "meta": {"hexsha": "76ee31dcd34f86b730cc23a5c8395d2a660cdf7a", "size": 3336, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/rank_two_update_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/rank_two_update_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/rank_two_update_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": 30.8888888889, "max_line_length": 95, "alphanum_fraction": 0.6354916067, "num_tokens": 916, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702880639791, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.4898416762707925}}
{"text": "// The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt\n/*\n    This is an example illustrating the use of the tools in dlib for doing distribution\n    estimation or detecting anomalies using one-class support vector machines. \n\n    Unlike regular classifiers, these tools take unlabeled points and try to learn what\n    parts of the feature space normally contain data samples and which do not.  Typically\n    you use these tools when you are interested in finding outliers or otherwise\n    identifying \"unusual\" data samples.\n\n    In this example, we will sample points from the sinc() function to generate our set of\n    \"typical looking\" points.  Then we will train some one-class classifiers and use them\n    to predict if new points are unusual or not.  In this case, unusual means a point is\n    not from the sinc() curve.\n*/\n\n#include <iostream>\n#include <vector>\n#include <dlib/svm.h>\n#include <dlib/gui_widgets.h>\n#include <dlib/array2d.h>\n#include <dlib/image_transforms.h>\n\nusing namespace std;\nusing namespace dlib;\n\n// Here is the sinc function we will be trying to learn with the one-class SVMs \ndouble sinc(double x)\n{\n    if (x == 0)\n        return 2;\n    return 2*sin(x)/x;\n}\n\nint main()\n{\n    // We will use column vectors to store our points.  Here we make a convenient typedef\n    // for the kind of vector we will use.\n    typedef matrix<double,0,1> sample_type;\n\n    // Then we select the kernel we want to use.  For our present problem the radial basis\n    // kernel is quite effective.\n    typedef radial_basis_kernel<sample_type> kernel_type;\n\n    // Now make the object responsible for training one-class SVMs.\n    svm_one_class_trainer<kernel_type> trainer;\n    // Here we set the width of the radial basis kernel to 4.0.  Larger values make the\n    // width smaller and give the radial basis kernel more resolution.  If you play with\n    // the value and observe the program output you will get a more intuitive feel for what\n    // that means.\n    trainer.set_kernel(kernel_type(4.0));\n\n    // Now sample some 2D points.  The points will be located on the curve defined by the\n    // sinc() function.\n    std::vector<sample_type> samples;\n    sample_type m(2);\n    for (double x = -15; x <= 8; x += 0.3)\n    {\n        m(0) = x;\n        m(1) = sinc(x);\n        samples.push_back(m);\n    }\n\n    // Now train a one-class SVM.  The result is a function, df(), that outputs large\n    // values for points from the sinc() curve and smaller values for points that are\n    // anomalous (i.e. not on the sinc() curve in our case).\n    decision_function<kernel_type> df = trainer.train(samples);\n\n    // So for example, let's look at the output from some points on the sinc() curve.  \n    cout << \"Points that are on the sinc function:\\n\";\n    m(0) = -1.5; m(1) = sinc(m(0)); cout << \"   \" << df(m) << endl;  \n    m(0) = -1.5; m(1) = sinc(m(0)); cout << \"   \" << df(m) << endl;  \n    m(0) = -0;   m(1) = sinc(m(0)); cout << \"   \" << df(m) << endl;  \n    m(0) = -0.5; m(1) = sinc(m(0)); cout << \"   \" << df(m) << endl;  \n    m(0) = -4.1; m(1) = sinc(m(0)); cout << \"   \" << df(m) << endl;  \n    m(0) = -1.5; m(1) = sinc(m(0)); cout << \"   \" << df(m) << endl;  \n    m(0) = -0.5; m(1) = sinc(m(0)); cout << \"   \" << df(m) << endl;  \n\n    cout << endl;\n    // Now look at some outputs for points not on the sinc() curve.  You will see that\n    // these values are all notably smaller. \n    cout << \"Points that are NOT on the sinc function:\\n\";\n    m(0) = -1.5; m(1) = sinc(m(0))+4;   cout << \"   \" << df(m) << endl;\n    m(0) = -1.5; m(1) = sinc(m(0))+3;   cout << \"   \" << df(m) << endl;\n    m(0) = -0;   m(1) = -sinc(m(0));    cout << \"   \" << df(m) << endl;\n    m(0) = -0.5; m(1) = -sinc(m(0));    cout << \"   \" << df(m) << endl;\n    m(0) = -4.1; m(1) = sinc(m(0))+2;   cout << \"   \" << df(m) << endl;\n    m(0) = -1.5; m(1) = sinc(m(0))+0.9; cout << \"   \" << df(m) << endl;\n    m(0) = -0.5; m(1) = sinc(m(0))+1;   cout << \"   \" << df(m) << endl;\n\n    // The output is as follows:\n    /*\n    Points that are on the sinc function:\n        0.000389691\n        0.000389691\n        -0.000239037\n        -0.000179978\n        -0.000178491\n        0.000389691\n        -0.000179978\n\n    Points that are NOT on the sinc function:\n        -0.269389\n        -0.269389\n        -0.269389\n        -0.269389\n        -0.269389\n        -0.239954\n        -0.264318\n    */\n\n    // So we can see that in this example the one-class SVM correctly indicates that \n    // the non-sinc points are definitely not points from the sinc() curve.\n\n\n    // It should be noted that the svm_one_class_trainer becomes very slow when you have\n    // more than 10 or 20 thousand training points.  However, dlib comes with very fast SVM\n    // tools which you can use instead at the cost of a little more setup.  In particular,\n    // it is possible to use one of dlib's very fast linear SVM solvers to train a one\n    // class SVM.  This is what we do below.  We will train on 115,000 points and it only\n    // takes a few seconds with this tool!\n    // \n    // The first step is constructing a feature space that is appropriate for use with a\n    // linear SVM.  In general, this is quite problem dependent.  However, if you have\n    // under about a hundred dimensions in your vectors then it can often be quite\n    // effective to use the empirical_kernel_map as we do below (see the\n    // empirical_kernel_map documentation and example program for an extended discussion of\n    // what it does).  \n    //\n    // But putting the empirical_kernel_map aside, the most important step in turning a\n    // linear SVM into a one-class SVM is the following.  We append a -1 value onto the end\n    // of each feature vector and then tell the trainer to force the weight for this\n    // feature to 1.  This means that if the linear SVM assigned all other weights a value\n    // of 0 then the output from a learned decision function would always be -1.  The\n    // second step is that we ask the SVM to label each training sample with +1.  This\n    // causes the SVM to set the other feature weights such that the training samples have\n    // positive outputs from the learned decision function.  But the starting bias for all\n    // the points in the whole feature space is -1.  The result is that points outside our\n    // training set will not be affected, so their outputs from the decision function will\n    // remain close to -1.\n\n    empirical_kernel_map<kernel_type> ekm;\n    ekm.load(trainer.get_kernel(),samples);\n\n    samples.clear();\n    std::vector<double> labels;\n    // make a vector with just 1 element in it equal to -1.\n    sample_type bias(1);\n    bias = -1;\n    sample_type augmented;\n    // This time sample 115,000 points from the sinc() function.\n    for (double x = -15; x <= 8; x += 0.0002)\n    {\n        m(0) = x;\n        m(1) = sinc(x);\n        // Apply the empirical_kernel_map transformation and then append the -1 value\n        augmented = join_cols(ekm.project(m), bias);\n        samples.push_back(augmented);\n        labels.push_back(+1);\n    }\n    cout << \"samples.size(): \"<< samples.size() << endl;\n\n    // The svm_c_linear_dcd_trainer is a very fast SVM solver which only works with the\n    // linear_kernel.  It has the nice feature of supporting this \"force_last_weight_to_1\"\n    // mode we discussed above.\n    svm_c_linear_dcd_trainer<linear_kernel<sample_type> > linear_trainer;\n    linear_trainer.force_last_weight_to_1(true);\n\n    // Train the SVM\n    decision_function<linear_kernel<sample_type> > df2 = linear_trainer.train(samples, labels);\n\n    // Here we test it as before, again we note that points from the sinc() curve have\n    // large outputs from the decision function.  Note also that we must remember to\n    // transform the points in exactly the same manner used to construct the training set\n    // before giving them to df2() or the code will not work.\n    cout << \"Points that are on the sinc function:\\n\";\n    m(0) = -1.5; m(1) = sinc(m(0)); cout << \"   \" << df2(join_cols(ekm.project(m),bias)) << endl;  \n    m(0) = -1.5; m(1) = sinc(m(0)); cout << \"   \" << df2(join_cols(ekm.project(m),bias)) << endl;  \n    m(0) = -0;   m(1) = sinc(m(0)); cout << \"   \" << df2(join_cols(ekm.project(m),bias)) << endl;  \n    m(0) = -0.5; m(1) = sinc(m(0)); cout << \"   \" << df2(join_cols(ekm.project(m),bias)) << endl;  \n    m(0) = -4.1; m(1) = sinc(m(0)); cout << \"   \" << df2(join_cols(ekm.project(m),bias)) << endl;  \n    m(0) = -1.5; m(1) = sinc(m(0)); cout << \"   \" << df2(join_cols(ekm.project(m),bias)) << endl;  \n    m(0) = -0.5; m(1) = sinc(m(0)); cout << \"   \" << df2(join_cols(ekm.project(m),bias)) << endl;  \n\n    cout << endl;\n    // Again, we see here that points not on the sinc() function have small values.\n    cout << \"Points that are NOT on the sinc function:\\n\";\n    m(0) = -1.5; m(1) = sinc(m(0))+4;   cout << \"   \" << df2(join_cols(ekm.project(m),bias)) << endl;\n    m(0) = -1.5; m(1) = sinc(m(0))+3;   cout << \"   \" << df2(join_cols(ekm.project(m),bias)) << endl;\n    m(0) = -0;   m(1) = -sinc(m(0));    cout << \"   \" << df2(join_cols(ekm.project(m),bias)) << endl;\n    m(0) = -0.5; m(1) = -sinc(m(0));    cout << \"   \" << df2(join_cols(ekm.project(m),bias)) << endl;\n    m(0) = -4.1; m(1) = sinc(m(0))+2;   cout << \"   \" << df2(join_cols(ekm.project(m),bias)) << endl;\n    m(0) = -1.5; m(1) = sinc(m(0))+0.9; cout << \"   \" << df2(join_cols(ekm.project(m),bias)) << endl;\n    m(0) = -0.5; m(1) = sinc(m(0))+1;   cout << \"   \" << df2(join_cols(ekm.project(m),bias)) << endl;\n\n\n    // The output is as follows:\n    /*\n    Points that are on the sinc function:\n        1.00454\n        1.00454\n        1.00022\n        1.00007\n        1.00371\n        1.00454\n        1.00007\n\n    Points that are NOT on the sinc function:\n        -1\n        -1\n        -1\n        -1\n        -0.999998\n        -0.781231\n        -0.96242\n    */\n\n\n    // Finally, to help you visualize what is happening here we are going to plot the\n    // response of the one-class classifiers on the screen.  The code below creates two\n    // heatmap images which show the response.  In these images you can clearly see where\n    // the algorithms have identified the sinc() curve.  The hotter the pixel looks, the\n    // larger the value coming out of the decision function and therefore the more \"normal\"\n    // it is according to the classifier.\n    const long size = 500;\n    array2d<double> img1(size,size);\n    array2d<double> img2(size,size);\n    for (long r = 0; r < img1.nr(); ++r)\n    {\n        for (long c = 0; c < img1.nc(); ++c)\n        {\n            double x = 30.0*c/size - 19;\n            double y = 8.0*r/size - 4;\n            m(0) = x;\n            m(1) = y;\n            img1[r][c] = df(m);\n            img2[r][c] = df2(join_cols(ekm.project(m),bias));\n        }\n    }\n    image_window win1(heatmap(img1), \"svm_one_class_trainer\");\n    image_window win2(heatmap(img2), \"svm_c_linear_dcd_trainer\");\n    win1.wait_until_closed();\n}\n\n\n", "meta": {"hexsha": "3394ee76fe3f3dd4c7766408194655be9ca35961", "size": 10990, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dlib/examples/one_class_classifiers_ex.cpp", "max_stars_repo_name": "maxmert/nlp-mitie", "max_stars_repo_head_hexsha": "ec3153ef2fe7a80e7cf3d80d14b388b8cd679343", "max_stars_repo_licenses": ["Unlicense"], "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": "examples/one_class_classifiers_ex.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": "examples/one_class_classifiers_ex.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": 44.674796748, "max_line_length": 101, "alphanum_fraction": 0.6101910828, "num_tokens": 3276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.72487026428967, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.4898416696716047}}
{"text": "/*************************************************************************\n\t> File Name: example.cpp\n\t> Author: ziqiang\n\t> Mail: ziqiang_free@163.com \n\t> Created Time: Fri 05 May 2017 11:17:16 PM CST\n ************************************************************************/\n\n#include <boost/lambda/lambda.hpp>\n#include <iostream>\n#include <iterator>\n#include <algorithm>\nusing namespace std;\n\nint main()\n{\n\tusing namespace boost::lambda;\n\ttypedef std::istream_iterator<int> in;\n\n\tstd::for_each(\n\t\t\tin(std::cin), in(), std::cout << (_1 * 3) << \" \");\n\t\n}\n\n", "meta": {"hexsha": "99852c04197d0638782e2d805d253cffae0e8d11", "size": 555, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "base-usage/cplusplus/boost/example.cpp", "max_stars_repo_name": "sczzq/symmetrical-spoon", "max_stars_repo_head_hexsha": "aa0c27bb40a482789c7c6a7088307320a007b49b", "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": "base-usage/cplusplus/boost/example.cpp", "max_issues_repo_name": "sczzq/symmetrical-spoon", "max_issues_repo_head_hexsha": "aa0c27bb40a482789c7c6a7088307320a007b49b", "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": "base-usage/cplusplus/boost/example.cpp", "max_forks_repo_name": "sczzq/symmetrical-spoon", "max_forks_repo_head_hexsha": "aa0c27bb40a482789c7c6a7088307320a007b49b", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.125, "max_line_length": 74, "alphanum_fraction": 0.4882882883, "num_tokens": 125, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7248702761768249, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.4898416682378745}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// BSD 3-Clause License\n//\n// Copyright (C) 2018-2020, LAAS-CNRS, New York University, Max Planck Gesellschaft\n//                          University of Edinburgh, INRIA\n// Copyright note valid unless otherwise stated in individual files.\n// All rights reserved.\n///////////////////////////////////////////////////////////////////////////////\n\n#define BOOST_TEST_NO_MAIN\n#define BOOST_TEST_ALTERNATIVE_INIT_API\n\n#include <iterator>\n#include <Eigen/Dense>\n#include <pinocchio/fwd.hpp>\n#include <boost/test/included/unit_test.hpp>\n#include <boost/bind.hpp>\n#include \"crocoddyl/core/activation-base.hpp\"\n#include \"crocoddyl/core/activations/quadratic-barrier.hpp\"\n#include \"crocoddyl/core/activations/quadratic.hpp\"\n#include \"crocoddyl/core/activations/smooth-abs.hpp\"\n#include \"crocoddyl/core/activations/weighted-quadratic.hpp\"\n#include \"crocoddyl/core/numdiff/activation.hpp\"\n#include \"crocoddyl/core/utils/exception.hpp\"\n\nusing namespace boost::unit_test;\n\nstruct TestTypes {\n  enum Type {\n    ActivationModelQuadraticBarrier,\n    ActivationModelQuad,\n    ActivationModelSmoothAbs,\n    ActivationModelWeightedQuad,\n    NbTestTypes\n  };\n  static std::vector<Type> init_all() {\n    std::vector<Type> v;\n    v.clear();\n    for (int i = 0; i < NbTestTypes; ++i) {\n      v.push_back((Type)i);\n    }\n    return v;\n  }\n  static const std::vector<Type> all;\n};\nconst std::vector<TestTypes::Type> TestTypes::all(TestTypes::init_all());\n\nclass Factory {\n public:\n  Factory(TestTypes::Type type) {\n    test_type_ = type;\n\n    nr_ = 5;\n    num_diff_modifier_ = 1e4;\n    Eigen::VectorXd lb = Eigen::VectorXd::Random(nr_);\n    Eigen::VectorXd ub = lb + Eigen::VectorXd::Ones(nr_) + Eigen::VectorXd::Random(nr_);\n    Eigen::VectorXd weights = Eigen::VectorXd::Random(nr_);\n\n    switch (test_type_) {\n      case TestTypes::ActivationModelQuadraticBarrier:\n        model_ = boost::make_shared<crocoddyl::ActivationModelQuadraticBarrier>(crocoddyl::ActivationBounds(lb, ub));\n        break;\n      case TestTypes::ActivationModelQuad:\n        model_ = boost::make_shared<crocoddyl::ActivationModelQuad>(nr_);\n        break;\n      case TestTypes::ActivationModelSmoothAbs:\n        model_ = boost::make_shared<crocoddyl::ActivationModelSmoothAbs>(nr_);\n        break;\n      case TestTypes::ActivationModelWeightedQuad:\n        model_ = boost::make_shared<crocoddyl::ActivationModelWeightedQuad>(weights);\n        break;\n      default:\n        throw_pretty(__FILE__ \":\\n Construct wrong TestTypes::Type\");\n        break;\n    }\n  }\n\n  ~Factory() {}\n\n  boost::shared_ptr<crocoddyl::ActivationModelAbstract> get_model() { return model_; }\n  const std::size_t& get_nr() { return nr_; }\n  double get_num_diff_modifier() { return num_diff_modifier_; }\n\n private:\n  double num_diff_modifier_;\n  std::size_t nr_;\n  boost::shared_ptr<crocoddyl::ActivationModelAbstract> model_;\n  TestTypes::Type test_type_;\n};\n\n//----------------------------------------------------------------------------//\n\nvoid test_construct_data(TestTypes::Type test_type) {\n  // create the model\n  Factory factory(test_type);\n  const boost::shared_ptr<crocoddyl::ActivationModelAbstract>& model = factory.get_model();\n\n  // create the corresponding data object\n  boost::shared_ptr<crocoddyl::ActivationDataAbstract> data = model->createData();\n}\n\nvoid test_calc_returns_a_value(TestTypes::Type test_type) {\n  // create the model\n  Factory factory(test_type);\n  const boost::shared_ptr<crocoddyl::ActivationModelAbstract>& model = factory.get_model();\n\n  // create the corresponding data object\n  boost::shared_ptr<crocoddyl::ActivationDataAbstract> data = model->createData();\n\n  // Generating random input vector\n  const Eigen::VectorXd& r = Eigen::VectorXd::Random(model->get_nr());\n  data->a_value = nan(\"\");\n\n  // Getting the state dimension from calc() call\n  model->calc(data, r);\n\n  // Checking that calc returns a value\n  BOOST_CHECK(!std::isnan(data->a_value));\n}\n\nvoid test_partial_derivatives_against_numdiff(TestTypes::Type test_type) {\n  // create the model\n  Factory factory(test_type);\n  const boost::shared_ptr<crocoddyl::ActivationModelAbstract>& model = factory.get_model();\n\n  // create the corresponding data object and set the cost to nan\n  boost::shared_ptr<crocoddyl::ActivationDataAbstract> data = model->createData();\n\n  crocoddyl::ActivationModelNumDiff model_num_diff(model);\n  boost::shared_ptr<crocoddyl::ActivationDataAbstract> data_num_diff = model_num_diff.createData();\n\n  // Generating random values for the state and control\n  const Eigen::VectorXd& r = Eigen::VectorXd::Random(model->get_nr());\n\n  // Computing the action derivatives\n  model->calcDiff(data, r);\n  model_num_diff.calcDiff(data_num_diff, r);\n\n  // Checking the partial derivatives against NumDiff\n  double tol = factory.get_num_diff_modifier() * model_num_diff.get_disturbance();\n  BOOST_CHECK(std::abs(data->a_value - data_num_diff->a_value) < tol);\n  BOOST_CHECK((data->Ar - data_num_diff->Ar).isMuchSmallerThan(1.0, tol));\n\n  // numerical differentiation of the Hessian is not good enough to be tested.\n  // BOOST_CHECK((data->Arr - data_num_diff->Arr).isMuchSmallerThan(1.0, tol));\n}\n\n//----------------------------------------------------------------------------//\n\nvoid register_unit_tests(TestTypes::Type type, test_suite& ts) {\n  ts.add(BOOST_TEST_CASE(boost::bind(&test_construct_data, type)));\n  ts.add(BOOST_TEST_CASE(boost::bind(&test_calc_returns_a_value, type)));\n  ts.add(BOOST_TEST_CASE(boost::bind(&test_partial_derivatives_against_numdiff, type)));\n}\n\nbool init_function() {\n  for (size_t i = 0; i < TestTypes::all.size(); ++i) {\n    const std::string test_name = \"test_\" + std::to_string(i);\n    test_suite* ts = BOOST_TEST_SUITE(test_name);\n    register_unit_tests(TestTypes::all[i], *ts);\n    framework::master_test_suite().add(ts);\n  }\n  return true;\n}\n\nint main(int argc, char** argv) { return ::boost::unit_test::unit_test_main(&init_function, argc, argv); }\n", "meta": {"hexsha": "a0c3a5aa44c47d8a48146033351b12648058dfd5", "size": 6008, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittest/test_activation.cpp", "max_stars_repo_name": "imaroger/crocoddyl", "max_stars_repo_head_hexsha": "3d3b9470563e6b7c860679d72ee220642658cc68", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-04-25T13:17:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-25T13:17:23.000Z", "max_issues_repo_path": "unittest/test_activation.cpp", "max_issues_repo_name": "Capri2014/crocoddyl", "max_issues_repo_head_hexsha": "341874fbad4507d6ed4e05e18e4a9cedf5470d01", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unittest/test_activation.cpp", "max_forks_repo_name": "Capri2014/crocoddyl", "max_forks_repo_head_hexsha": "341874fbad4507d6ed4e05e18e4a9cedf5470d01", "max_forks_repo_licenses": ["BSD-3-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.9760479042, "max_line_length": 117, "alphanum_fraction": 0.6900798935, "num_tokens": 1431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.48984166823787445}}
{"text": "//  Permission to copy, use, modify, sell and\n//  distribute this software is granted provided this copyright notice appears\n//  in all copies. This software is provided \"as is\" without express or implied\n//  warranty, and with no claim as to its suitability for any purpose.\n//  Copyright Toon Knapen and Kresimir Fresl\n\n#ifndef BOOST_BINDINGS_BLAS_BLAS3_HPP\n#define BOOST_BINDINGS_BLAS_BLAS3_HPP\n\n#include <boost/numeric/bindings/blas/blas3_overloads.hpp>\n#include <boost/numeric/bindings/traits/traits.hpp>\n#include <boost/numeric/bindings/traits/transpose.hpp>\n\nnamespace boost { namespace numeric { namespace bindings { namespace blas {\n\n  // C <- alpha * op (A) * op (B) + beta * C \n  // op (X) == X || X^T || X^H\n  template < typename value_type, typename matrix_type_a, typename matrix_type_b, typename matrix_type_c >\n  // ! CAUTION this function assumes that all matrices involved are column-major matrices\n  void gemm(const char TRANSA, const char TRANSB, \n\t    const value_type& alpha,\n\t    const matrix_type_a &a,\n\t    const matrix_type_b &b,\n\t    const value_type &beta,\n\t    matrix_type_c &c\n\t    )\n  {\n    const int m = TRANSA == traits::NO_TRANSPOSE ? traits::matrix_size1( a ) : traits::matrix_size2( a ) ;\n    const int n = TRANSB == traits::NO_TRANSPOSE ? traits::matrix_size2( b ) : traits::matrix_size1( b );\n    const int k = TRANSA == traits::NO_TRANSPOSE ? traits::matrix_size2( a ) : traits::matrix_size1( a ) ;\n    assert( k ==  ( TRANSB == traits::NO_TRANSPOSE ? traits::matrix_size1( b ) : traits::matrix_size2( b ) ) ) ;\n    assert( m == traits::matrix_size1( c ) ); \n    assert( n == traits::matrix_size2( c ) ); \n    const int lda = traits::leading_dimension( a );\n    const int ldb = traits::leading_dimension( b );\n    const int ldc = traits::leading_dimension( c );\n\n    const value_type *a_ptr = traits::matrix_storage( a ) ;\n    const value_type *b_ptr = traits::matrix_storage( b ) ;\n    value_type *c_ptr = traits::matrix_storage( c ) ;\n\n    detail::gemm( TRANSA, TRANSB, m, n, k, alpha, a_ptr, lda, b_ptr, ldb, beta, c_ptr, ldc ) ;\n  }\n\n\n  // C <- alpha * A * B + beta * C \n  template < typename value_type, typename matrix_type_a, typename matrix_type_b, typename matrix_type_c >\n  void gemm(const value_type& alpha,\n\t    const matrix_type_a &a,\n\t    const matrix_type_b &b,\n\t    const value_type &beta,\n\t    matrix_type_c &c\n\t    )\n  {\n    gemm( traits::NO_TRANSPOSE, traits::NO_TRANSPOSE, alpha, a, b, beta, c ) ;\n  }\n\n\n  // C <- A * B \n  // ! CAUTION this function assumes that all matrices involved are column-major matrices\n  template < \n    typename matrix_type_a, typename matrix_type_b, typename matrix_type_c \n    >\n  void gemm(const matrix_type_a &a, const matrix_type_b &b, matrix_type_c &c)\n  {\n    typedef typename traits::matrix_traits<matrix_type_c>::value_type val_t; \n    gemm( traits::NO_TRANSPOSE, traits::NO_TRANSPOSE, (val_t) 1, a, b, (val_t) 0, c ) ;\n  }\n\n\n  // C <- alpha * A * A^T + beta * C\n  // C <- alpha * A^T * A + beta * C\n  template < typename value_type, typename matrix_type_a, typename matrix_type_c >\n  void syrk( char uplo, char trans, const value_type& alpha, const matrix_type_a& a,\n             const value_type& beta, matrix_type_c& c) {\n     const int n = traits::matrix_size1( c );\n     assert( n == traits::matrix_size2( c ) );\n     const int k = trans == traits::NO_TRANSPOSE ? traits::matrix_size2( a ) : traits::matrix_size1( a ) ;\n     assert( n == traits::NO_TRANSPOSE ? traits::matrix_size1( a ) : traits::matrix_size2( a ) );\n     const int lda = traits::leading_dimension( a );\n     const int ldc = traits::leading_dimension( c );\n\n     const value_type *a_ptr = traits::matrix_storage( a ) ;\n     value_type *c_ptr = traits::matrix_storage( c ) ;\n\n     detail::syrk( uplo, trans, n, k, alpha, a_ptr, lda, beta, c_ptr, ldc );\n  } // syrk()\n\n\n  // C <- alpha * A * A^H + beta * C\n  // C <- alpha * A^H * A + beta * C\n  template < typename real_type, typename matrix_type_a, typename matrix_type_c >\n  void herk( char uplo, char trans, const real_type& alpha, const matrix_type_a& a,\n             const real_type& beta, matrix_type_c& c) {\n     typedef typename matrix_type_c::value_type value_type ;\n\n     const int n = traits::matrix_size1( c );\n     assert( n == traits::matrix_size2( c ) );\n     const int k = trans == traits::NO_TRANSPOSE ? traits::matrix_size2( a ) : traits::matrix_size1( a ) ;\n     assert( n == traits::NO_TRANSPOSE ? traits::matrix_size1( a ) : traits::matrix_size2( a ) );\n     const int lda = traits::leading_dimension( a );\n     const int ldc = traits::leading_dimension( c );\n\n     const value_type *a_ptr = traits::matrix_storage( a ) ;\n     value_type *c_ptr = traits::matrix_storage( c ) ;\n\n     detail::herk( uplo, trans, n, k, alpha, a_ptr, lda, beta, c_ptr, ldc );\n  } // herk()\n\n  // B <- alpha * op( A^-1 )\n  // B <- alpha * B op( A^-1 )\n  // op( A ) = A, A^T, A^H\n  template < class T, class A, class B >\n  void trsm( char side, char uplo, char transa, char diag, T const& alpha, A const& a, B& b ) {\n     const int m = traits::matrix_size1( b ) ;\n     const int n = traits::matrix_size2( b ) ;\n     assert( ( side=='L' && m==traits::matrix_size2( a ) && m==traits::matrix_size1( a ) ) ||\n             ( side=='R' && n==traits::matrix_size2( a ) && n==traits::matrix_size1( a ) ) ) ;\n     assert( side=='R' || side=='L' ) ;\n     assert( uplo=='U' || uplo=='L' ) ;\n     assert( ( side=='L' && m==traits::matrix_size1( a ) ) || ( side=='R' && n==traits::matrix_size1( a ) ) ) ;\n     detail::trsm( side, uplo, transa, diag, m, n, alpha,\n                   traits::matrix_storage( a ), traits::leading_dimension( a ),\n                   traits::matrix_storage( b ), traits::leading_dimension( b )\n                 ) ;\n  }\n\n}}}}\n\n#endif // BOOST_BINDINGS_BLAS_BLAS3_HPP\n", "meta": {"hexsha": "e6edf7fb7a831b99bd119b5d6872f0c3cb452cd8", "size": 5794, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "applications/mkl_solvers_application/external_includes/boost/numeric/bindings/blas/blas3.hpp", "max_stars_repo_name": "jiaqiwang969/Kratos-test", "max_stars_repo_head_hexsha": "ed082abc163e7b627f110a1ae1da465f52f48348", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "applications/mkl_solvers_application/external_includes/boost/numeric/bindings/blas/blas3.hpp", "max_issues_repo_name": "jiaqiwang969/Kratos-test", "max_issues_repo_head_hexsha": "ed082abc163e7b627f110a1ae1da465f52f48348", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "applications/mkl_solvers_application/external_includes/boost/numeric/bindings/blas/blas3.hpp", "max_forks_repo_name": "jiaqiwang969/Kratos-test", "max_forks_repo_head_hexsha": "ed082abc163e7b627f110a1ae1da465f52f48348", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.2290076336, "max_line_length": 112, "alphanum_fraction": 0.6437694166, "num_tokens": 1670, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.48984166823787445}}
{"text": "#include \"anova.h\"\n\n// STL\n#include <vector>\n#include <algorithm>\n\n// debug\n#include <iostream>\n#include <iomanip>\n\n#include <boost/math/distributions/fisher_f.hpp>\n\ntemplate<typename T>\nstatic T *transform(std::vector<T> &v)\n{\n    int size = v.size();\n    T *result = new T[size];\n    std::copy(v.begin(), v.end(), result);\n    return result;\n}\n\nnamespace stats\n{\n\nclass MeanEnumer\n{\npublic:\n    MeanEnumer() = default;\n\n    void operator()(const Sample &s)\n    {\n        _n += s.getCount();\n        for (auto &el: s.getElements())\n            _sum += el;\n    }\n\n    inline double getMean(){ return _sum / _n; }\n    inline int getN(){ return _n; }\nprivate:\n    int _n = 0;\n    double _sum = 0;\n};\n\ndouble Anova::FTest(const Samples &samples)\n{\n    assert(samples.size() > 1);\n    if (samples.size()  <= 1)\n        throw std::domain_error(\"count of samples must be more than 1\");\n\n    MeanEnumer enumer = std::for_each(samples.begin(), samples.end(), MeanEnumer());\n    double generalMean = enumer.getMean();\n    int N = enumer.getN();\n\n    double Qa = 0;\n\n    std::for_each(samples.begin(), samples.end(), [&Qa, &generalMean](const Sample &s){\n        Qa += s.getCount() * pow(s.getMean() - generalMean, 2);\n    });\n\n    double Qoct = 0;\n    std::for_each(samples.begin(), samples.end(), [&Qoct](const Sample &s){\n        for (auto &el: s.getElements())\n            Qoct += pow(el - s.getMean(), 2);\n    });\n\n    int sampleSize = samples.size();\n    _v1 = sampleSize - 1;\n    _v2 = N - sampleSize;\n    _F = (Qa / _v1) / (Qoct / _v2);\n    return _F;\n}\n\ndouble Anova::FCriticalTest(double alpha) const\n{\n    using namespace boost::math;\n    fisher_f dist(_v1, _v2);\n    return quantile(complement(dist, alpha));\n}\n\n//---------Two factor ANOVA---------------------------------------\nTwoFactorAnova::Result TwoFactorAnova::FTest(const Samples &rowSamples)\n{\n    int m = rowSamples.size();\n    assert(m != 0);\n    if (m  == 0)\n        throw std::domain_error(\"count of samples must be more than 1\");\n\n    int r = rowSamples[0].getCount();\n    Samples columnSamples(r);\n    Sample commonSample;\n    for (int i = 0; i < m; i++)\n    {\n        const Sample &rowSample = rowSamples[i];\n        int j = 0;\n        for (auto &el: rowSample.getElements())\n        {\n            columnSamples[j].add(el);\n            commonSample.add(el);\n            j++;\n        }\n    }\n\n    commonSample.refresh();\n    for (auto &sample: columnSamples)\n    {\n        sample.refresh();\n    }\n\n    double Qa = 0.0, Qb = 0.0, Qoct = 0.0;\n\n    for (const Sample &sample: columnSamples)\n    {\n        Qa += r*pow(sample.getMean() - commonSample.getMean(), 2);\n    }\n\n    double Da = Qa / (m - 1);\n\n    for (const Sample &sample: rowSamples)\n    {\n        Qb += m*pow(sample.getMean() - commonSample.getMean(), 2);\n    }\n\n    double Db = Qb / (r - 1);\n\n    for (int i = 0; i < m; i++)\n    {\n        for (int j = 0; j < r; j++)\n        {\n            Qoct += pow((rowSamples[i].getElements())[j]\n                        + commonSample.getMean() - (rowSamples[i].getMean() + columnSamples[j].getMean()), 2);\n        }\n    }\n    double Doct = Qoct / ((m - 1)*(r - 1));\n\n    _Va = m - 1;\n    _Vb = r - 1;\n    _V2 = (m - 1) * (r - 1);\n\n    Result res;\n    res.FA = _F.FA =  Da / Doct;\n    res.FB = _F.FB =  Db / Doct;\n    res.FAB = _F.FAB = std::max(res.FA, res.FB) / std::min(res.FA, res.FB);\n\n    return res;\n}\n\ndouble TwoFactorAnova::FcriticalTest(double alpha, int v1, int v2) const\n{\n    using namespace boost::math;\n    fisher_f dist(v1, v2);\n    return quantile(complement(dist, alpha));\n}\n\ndouble TwoFactorAnova::FCriticalTestA(double alpha) const\n{\n    return FcriticalTest(alpha, _Va, _V2);\n}\n\ndouble TwoFactorAnova::FCriticalTestB(double alpha) const\n{\n    return FcriticalTest(alpha, _Vb, _V2);\n}\n\ndouble TwoFactorAnova::FCriticalTestAB(double alpha) const\n{\n    return FcriticalTest(alpha, _V2, _V2);\n}\n\n}// stats\n", "meta": {"hexsha": "9d416d4f39de6ef147224150126140e877b27d6b", "size": 3888, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "MathStats/anova.cpp", "max_stars_repo_name": "goldim/unistats", "max_stars_repo_head_hexsha": "e8dd54e46f84422d868c942367f0103949791ede", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MathStats/anova.cpp", "max_issues_repo_name": "goldim/unistats", "max_issues_repo_head_hexsha": "e8dd54e46f84422d868c942367f0103949791ede", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MathStats/anova.cpp", "max_forks_repo_name": "goldim/unistats", "max_forks_repo_head_hexsha": "e8dd54e46f84422d868c942367f0103949791ede", "max_forks_repo_licenses": ["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.8705882353, "max_line_length": 110, "alphanum_fraction": 0.5679012346, "num_tokens": 1143, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.4898270583875157}}
{"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 \"syk.hpp\"\n#include \"syk_types.hpp\"\n#include \"cuda_diagonalize.hpp\"\n\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n#include <exception>\n#include <algorithm>\n#include <complex>\n\nnamespace syk {\nusing namespace std::complex_literals;\n\nstd::vector<double> cpu_hamiltonian_eigenvals(const MatrixType& hamiltonian) {\n    auto eigensolver = Eigen::SelfAdjointEigenSolver<MatrixType>();\n    eigensolver.compute(hamiltonian, false);\n\n    if(eigensolver.info() != 0) {\n        throw std::runtime_error(\"Eigensolver not converged\");\n    }\n    const auto& eigenvals_vector = eigensolver.eigenvalues();\n    std::vector<double> eigenvals(eigenvals_vector.size());\n    std::copy_n(eigenvals_vector.data(), eigenvals_vector.size(), eigenvals.begin());\n    std::sort(eigenvals.begin(), eigenvals.end());\n\n    return eigenvals;\n}\n\ntemplate<typename mat> \nstd::complex<double> closest_eigenval(mat m, std::complex<double> v) {\n    std::complex<double> a, b, c, d;\n    a = m(0,0);\n    b = m(0,1);\n    c = m(1,0);\n    d = m(1,1);\n    \n    auto desc = std::sqrt(a*a + 4.0 * b * c - 2.0 * a * d + d * d);\n    auto l_1 = (a + d + desc)/2.0;\n    auto l_2 = (a + d - desc)/2.0;\n    \n    auto dist_1 = std::abs(l_1 - v);\n    auto dist_2 = std::abs(l_2 - v);\n    return dist_1 < dist_2 ? l_1 : l_2;\n}\n\nstd::vector<double> QR_hamiltonian_eigenvals(const MatrixType& ham, MatrixType* Q_H,  double max_resid = 1e-7) {\n    int max_iter = 1000 * ham.rows();\n    assert(ham.rows() == ham.cols());\n    assert(Q_H->rows() == ham.rows());\n    assert(Q_H->cols() == ham.cols());\n\n    // Eigen::HessenbergDecomposition<MatrixType> hd;\n    // hd.compute(ham);\n    // *Q_H = hd.matrixQ().adjoint();\n\n    MatrixType temp(ham.rows(), ham.cols());\n    MatrixType Q_curr(ham.rows(), ham.cols());\n    \n    MatrixType A = Q_H->adjoint() * ham * *Q_H;\n    Eigen::HouseholderQR<MatrixType> qr(ham.rows(), ham.cols());\n    \n    // TODO: Use tridiagonal form\n    int k;\n    int deflate = ham.diagonal().size();\n    for(k = 0; k < max_iter; ++k) {\n        // // Rayleigh quotient\n        // std::complex<double> shift = A(deflate-1, deflate-1);\n        // Wilkinson\n        auto shift = closest_eigenval(A.block(deflate-2, deflate-2, 2, 2), A(deflate-1, deflate-1));\n        // QR\n        qr.compute(A.topLeftCorner(deflate, deflate) - MatrixType::Identity(deflate, deflate) * shift);\n        Q_curr = qr.householderQ();\n        // Update Q_H with deflated matmul\n        temp.topLeftCorner(deflate, deflate).noalias() = Q_H->topLeftCorner(deflate, deflate) * Q_curr;\n        temp.bottomLeftCorner(Q_H->rows() - deflate, deflate).noalias() = Q_H->bottomLeftCorner(Q_H->rows() - deflate, deflate) * Q_curr;\n        Q_H->topLeftCorner(Q_H->rows(), deflate) = temp.topLeftCorner(Q_H->rows(), deflate);\n        // Update A = Q^* H Q\n        A.noalias() = Q_H->adjoint() * ham * *Q_H; // TODO: Deflate this\n        // Check convergence condition\n        if(std::abs(A(deflate-1, deflate-2)) < max_resid && --deflate == 1) {\n            break;\n        }\n    }\n\n    double residual = 0;\n    for(int j = 0; j < A.rows(); ++j) {\n        for(int i = j+1; i < A.cols(); ++i) {\n            residual += std::real(A(i,j) * std::conj(A(i,j)));\n        }\n    }\n    residual = std::sqrt(residual) / A.diagonal().size();\n    \n    std::vector<double> eigenvals(A.diagonal().size());\n    Eigen::Map<Eigen::VectorXd>(eigenvals.data(), eigenvals.size()) = A.diagonal().real();\n    std::sort(eigenvals.begin(), eigenvals.end());\n\n    return eigenvals;\n}\n\nstd::vector<double> gpu_hamiltonian_eigenvals(const MatrixType& hamiltonian) {\n    syk::GpuEigenValSolver solver;\n    std::vector<double> eigenvals;\n    #pragma omp critical\n    eigenvals = solver.eigenvals(hamiltonian);\n    return eigenvals;\n}\n}", "meta": {"hexsha": "852b195c2a5e15c0adedc325788ac8ee5934d759", "size": 5122, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/diagonalize.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/diagonalize.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/diagonalize.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": 38.803030303, "max_line_length": 137, "alphanum_fraction": 0.658141351, "num_tokens": 1392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.752012562644147, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.48982705114728264}}
{"text": "//=======================================================================\n// Copyright (c) 2013 Robert Rosolek\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 fractional_winner_determination_in_MUCA_test.cpp\n * @brief\n * @author Robert Rosolek\n * @version 1.0\n * @date 2014-07-24\n */\n\n#include \"test_utils/fractional_winner_determination_in_MUCA_test_utils.hpp\"\n\n#include \"paal/auctions/fractional_winner_determination_in_MUCA/fractional_winner_determination_in_MUCA.hpp\"\n#include \"paal/auctions/xor_bids.hpp\"\n\n#include <boost/mem_fn.hpp>\n#include <boost/test/unit_test.hpp>\n\n#include <functional>\n#include <iterator>\n#include <map>\n#include <set>\n#include <string>\n#include <utility>\n#include <vector>\n\nBOOST_AUTO_TEST_CASE(testFracDetermineWinners)\n{\n   using Bidder = std::string;\n   using Item = std::string;\n   using Items = std::set<Item>;\n   using Bid = std::pair<Items, double>;\n   using Bids = std::vector<Bid>;\n   const std::vector<Bidder> bidders {\"John\", \"Bob\"};\n   const std::map<Bidder, Bids> bids {\n      {\"John\", {\n         {Items{}, 0},\n         {{\"lemon\", \"orange\"}, 1},\n         {{\"apple\", \"ball\"}, 1},\n      }},\n      {\"Bob\", {\n         {{\"lemon\", \"apple\"}, 1},\n         {{\"orange\", \"ball\"}, 1},\n      }},\n   };\n   auto get_bids = [&](const Bidder& bidder) -> const Bids& { return bids.at(bidder); };\n   auto get_value = boost::mem_fn(&Bid::second);\n   auto get_items = boost::mem_fn(&Bid::first);\n   auto get_copies_num = [](const Item& item) { return item == \"lemon\" ? 2 : 1; };\n   Items items;\n   paal::auctions::extract_items_from_xor_bids(\n      bidders, get_bids, get_items, std::inserter(items, items.begin())\n   );\n   auto opt = 0.5 * (1 + 1 + 1 + 1);\n   check_fractional_determine_winners_in_demand_query_auction(\n      bidders, items, get_bids, get_value, get_items, get_copies_num, opt\n   );\n}\n", "meta": {"hexsha": "827f8c8c49c3a00575f8b9cd96587426f30708ba", "size": 2023, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/auctions/fractional_winner_determination_in_MUCA_test.cpp", "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": "test/auctions/fractional_winner_determination_in_MUCA_test.cpp", "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": "test/auctions/fractional_winner_determination_in_MUCA_test.cpp", "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": 31.609375, "max_line_length": 108, "alphanum_fraction": 0.6134453782, "num_tokens": 557, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.4898270431189679}}
{"text": "#include <stan/math/fwd/scal.hpp>\n#include <gtest/gtest.h>\n#include <boost/math/special_functions/digamma.hpp>\n#include <test/unit/math/fwd/scal/fun/nan_util.hpp>\n\nTEST(AgradFwdDigamma, Fvar) {\n  using boost::math::digamma;\n  using boost::math::zeta;\n  using stan::math::fvar;\n\n  fvar<double> x(0.5, 1.0);\n  fvar<double> a = digamma(x);\n  EXPECT_FLOAT_EQ(digamma(0.5), a.val_);\n  EXPECT_FLOAT_EQ(4.9348022005446793094, a.d_);\n}\n\nTEST(AgradFwdDigamma, FvarFvarDouble) {\n  using boost::math::digamma;\n  using stan::math::fvar;\n\n  fvar<fvar<double> > x;\n  x.val_.val_ = 0.5;\n  x.val_.d_ = 1.0;\n\n  fvar<fvar<double> > a = digamma(x);\n\n  EXPECT_FLOAT_EQ(digamma(0.5), a.val_.val_);\n  EXPECT_FLOAT_EQ(4.9348022005446793094, a.val_.d_);\n  EXPECT_FLOAT_EQ(0, a.d_.val_);\n  EXPECT_FLOAT_EQ(0, a.d_.d_);\n\n  fvar<fvar<double> > y;\n  y.val_.val_ = 0.5;\n  y.d_.val_ = 1.0;\n\n  a = digamma(y);\n  EXPECT_FLOAT_EQ(digamma(0.5), a.val_.val_);\n  EXPECT_FLOAT_EQ(0, a.val_.d_);\n  EXPECT_FLOAT_EQ(4.9348022005446793094, a.d_.val_);\n  EXPECT_FLOAT_EQ(0, a.d_.d_);\n}\n\nstruct digamma_fun {\n  template <typename T0>\n  inline T0 operator()(const T0& arg1) const {\n    return digamma(arg1);\n  }\n};\n\nTEST(AgradFwdDigamma, digamma_NaN) {\n  digamma_fun digamma_;\n  test_nan_fwd(digamma_, false);\n}\n", "meta": {"hexsha": "a99180667f336ff8f6698a1334ea69c6d893ef1f", "size": 1268, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/fwd/scal/fun/digamma_test.cpp", "max_stars_repo_name": "jrmie/math", "max_stars_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-07-23T14:57:41.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-23T14:57:41.000Z", "max_issues_repo_path": "test/unit/math/fwd/scal/fun/digamma_test.cpp", "max_issues_repo_name": "jrmie/math", "max_issues_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-09-23T19:58:36.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-24T12:03:41.000Z", "max_forks_repo_path": "test/unit/math/fwd/scal/fun/digamma_test.cpp", "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": 23.4814814815, "max_line_length": 52, "alphanum_fraction": 0.6900630915, "num_tokens": 458, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.752012562644147, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.489827040968251}}
{"text": "// Author(s): Frank Stappers\n// Copyright: see the accompanying file COPYING or copy at\n// https://svn.win.tue.nl/trac/MCRL2/browser/trunk/COPYING\n//\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//\n/// \\file list_test.cpp\n/// \\brief Basic regression test for quantifier expressions.\n\n#include <boost/test/minimal.hpp>\n\n#include \"mcrl2/data/list.h\"\n#include \"mcrl2/data/parse.h\"\n#include \"mcrl2/data/rewriter.h\"\n#include \"mcrl2/data/set.h\"\n#include \"mcrl2/data/fset.h\"\n#include \"mcrl2/data/standard.h\"\n#include \"mcrl2/data/detail/rewrite_strategies.h\"\n\nusing namespace mcrl2;\nusing namespace mcrl2::data;\nusing namespace mcrl2::data::sort_list;\n\nvoid quantifier_expression_test(const std::string& expr1_text, const std::string& expr2_text, const data_specification& dataspec, const rewriter& r)\n{\n  data_expression expr1 = parse_data_expression(expr1_text, dataspec);\n  data_expression expr2 = parse_data_expression(expr2_text, dataspec);\n  std::cout << \"Testing \" << expr1_text << \" <-> \" << expr2_text << std::endl;\n  if (r(expr1) != r(expr2))\n  {\n    std::cout << \"--- ERROR ---\\n\";\n    std::cout << \" expr1    = \" << expr1 << std::endl;\n    std::cout << \" expr2    = \" << expr2 << std::endl;\n    std::cout << \" r(expr1) = \" << r(expr1) << std::endl;\n    std::cout << \" r(expr2) = \" << r(expr2) << std::endl;\n    BOOST_CHECK(r(expr1) == r(expr2));\n  }\n}\n\nvoid quantifier_expression_test(mcrl2::data::rewrite_strategy s)\n{\n  data_specification dataspec;\n  rewriter r(dataspec, s);\n\n  // tests for Bool\n  quantifier_expression_test(\"exists x: Bool. x == false\", \"true\", dataspec, r);\n  quantifier_expression_test(\"forall x: Bool. x == false\", \"false\", dataspec, r);\n  quantifier_expression_test(\"exists x: Bool. x == true\", \"true\", dataspec, r);\n  quantifier_expression_test(\"forall x: Bool. x == true\", \"false\", dataspec, r);\n  quantifier_expression_test(\"forall x: Bool. x == true && x==false\", \"false\", dataspec, r);\n  quantifier_expression_test(\"exists x: Bool. x == true && x==false\", \"false\", dataspec, r);\n  quantifier_expression_test(\"forall x: Bool. x == true || x==false\", \"true\", dataspec, r);\n  quantifier_expression_test(\"exists x: Bool. x == true || x==false\", \"true\", dataspec, r);\n  quantifier_expression_test(\"forall x:Bool.exists y: Bool. x == y\", \"true\", dataspec, r);\n  quantifier_expression_test(\"exists x: Bool.forall y:Bool.x == y\", \"false\", dataspec, r);\n  quantifier_expression_test(\"forall b: Bool. b\", \"false\", dataspec, r);\n\n  // tests for Pos / Nat\n  dataspec.add_context_sort(sort_nat::nat());\n  dataspec.add_context_sort(sort_set::set_(sort_nat::nat()));\n  r = rewriter(dataspec, s);\n  quantifier_expression_test(\"exists x: Nat. (  x in {1,2,25,600} && 25 == x )\", \"true\", dataspec, r);\n\n  // This test depends on the naming of variables in the enumerator\n  // quantifier_expression_test(\"forall x: Nat. exists y: Nat. y == x\", \"true\", dataspec, r);\n\n  quantifier_expression_test(\"forall x: Nat. x == 3\", \"false\", dataspec, r);\n  quantifier_expression_test(\"exists x: Nat. x == 3\", \"true\", dataspec, r);\n  quantifier_expression_test(\"forall x: Pos. exists y: Pos.x == y+1\", \"false\", dataspec, r);\n  quantifier_expression_test(\"forall x: Pos. exists y: Pos.x == y+1\", \"false\", dataspec, r);\n  /* Test 15. Test whether elimination of quantifiers also happens inside a term. */\n  quantifier_expression_test(\"(exists x_0: Bool. false) && (forall x_0: Nat. true)\", \"false\", dataspec, r);\n  quantifier_expression_test(\"(forall x_0: Pos. true) || (exists x_0: Bool. false)\", \"true\", dataspec, r);\n  /* The test below is too complex for the enumerator to solve.\n  quantifier_expression_test(\"forall x: Pos. exists y: Nat.x == y+1\", \"true\", dataspec, r);\n  */\n\n/* These tests do not work with the new enumerator, since it does not handle data equalities.\n  quantifier_expression_test(\"forall x:Pos.exists y1,y2:Pos.x==y1+y2\", \"false\", dataspec, r);\n  quantifier_expression_test(\"forall x:Nat.exists y1,y2:Nat.x==y1+y2\", \"true\", dataspec, r);\n*/\n\n  // tests for struct / List\n  dataspec = parse_data_specification(\"sort S = struct s1?is_s1 | s2?is_s2;\"\n                                      \"sort T = struct t;\"\n                                      \"sort L = List(T);\");\n  r = rewriter(dataspec, s);\n\n  quantifier_expression_test(\"exists s: S.( is_s1(s) && is_s2(s) )\", \"false\", dataspec, r);\n  quantifier_expression_test(\"exists s: S.( s == s2 && is_s2(s) )\", \"true\", dataspec, r);\n  quantifier_expression_test(\"forall y: T. y in [t]\", \"true\", dataspec, r);\n\n/* Should work but takes too much time.\n  dataspec = parse_data_specification(\n  \" sort A = struct ac( first: Bool, args: List(Bool));\"\n  \" \"\n  \" map COMM: List(Bool)#Bool#List(A) -> List(A);\"\n  \"     COMM: List(Bool)#Bool#List(A)#(List(Bool)->FBag(Bool))#FBag(Bool) -> List(A);\"\n  \"     MAC: List(Bool) -> FBag(Bool);\"\n  \"     PART: List(A)#(List(Bool) -> FBag(Bool)) -> (List(Bool) -> FBag(Bool));\"\n  \"     ELM: List(Bool)#Bool#List(A)#List(Bool)#List(Bool) -> List(A);\"\n  \"     RM: A#List(A)->List(A);\"\n  \" var func: List(Bool)->FBag(Bool);\"\n  \"     as: List(A);\"\n  \"     ca: Bool;\"\n  \"     cal: List(Bool);\"\n  \"     cal_const: List(Bool);\"\n  \"     al: Bool;\"\n  \"     lsa: List(A);\"\n  \"     m: FBag(Bool);\"\n  \"     args: List(Bool);\"\n  \"     a, b: A;\"\n  \" eqn PART( [] , func ) = func;\"\n  \"     PART( a |> as , func ) = PART( as, func[ args(a) -> func(args(a)) + {first(a):1}]  );\"\n  \"     MAC( [] ) = {:};\"\n  \"     MAC( ca |> cal ) = {ca:1} + MAC(cal);\"\n  \" \"\n  \"     COMM( cal, al, lsa ) = COMM( cal, al, lsa,  PART( lsa, lambda x: List(Bool). {:} ), MAC(cal) );\"\n  \"     COMM( cal, al, [] , func, m ) = [];\"\n  \"     COMM( cal, al, a |> lsa, func, m ) = if( m <= func(args(a)), \"\n  \"                                                      ELM( cal, al, a |> lsa, args(a) , cal ) , \"\n  \"                                                      a |> COMM( cal, al, lsa, func, m)\"\n  \"                                                    );\"\n  \"     ELM( [] , al, lsa, args, cal_const ) = [ac(al, args)] ++ COMM( cal_const, al, lsa );\"\n  \"     ELM( ca |> cal, al, lsa, args, cal_const ) = ELM( cal, al , RM( ac( ca ,args), lsa), args, cal_const );\"\n  \"     RM( a, [] ) = [];\"\n  \"     RM( a, b |> lsa ) = if(a == b , lsa,  b |> RM( a, lsa)) ;\"\n  );\n  r = rewriter(dataspec, s);\n\n  quantifier_expression_test(\"exists x_0: List(A). x_0 == [ac( false, []), ac(true, []), ac(false, [])] && [ac(true, []), ac(true, [])] == COMM([false, false], true, x_0, PART(x_0, lambda x: List(Bool). {:}), {false: 2}) \", \"true\", dataspec, r);\n  quantifier_expression_test(\"exists x_0: List(A). [ac(true, []), ac(true, [])] == \"\n       \"        COMM([false, false], true, x_0, PART(x_0, lambda x: List(Bool). {:}), {false: 2}) &&  \"\n       \"        x_0 == [ac( false, []), ac(true, []), ac(false, [])]\", \"true\", dataspec, r);\n*/\n\n  // tests for Set\n  dataspec = parse_data_specification( \"sort A = Set(Bool);\");\n  r = rewriter(dataspec, s);\n\n  /* Test that exists and forall over a non enumerable sort (situation winter 2012)\n     with a trivial predicate can still be reduced, by removing the variable. */\n  quantifier_expression_test(\"exists x:Set(Bool). x==x\", \"true\", dataspec, r);\n  quantifier_expression_test(\"forall x:Set(Bool). x==x\", \"true\", dataspec, r);\n  quantifier_expression_test(\"exists x:Set(Bool). x!=x\", \"false\", dataspec, r);\n  quantifier_expression_test(\"forall x:Set(Bool). x!=x\", \"false\", dataspec, r);\n}\n\nvoid quantifier_in_rewrite_rules_test(mcrl2::data::rewrite_strategy s)\n{\n  // The test below checks whether bound variables in rewrite rules are properly renamed\n  // when substituting variables. In concreto, if the y in the eqn for f is substituted in\n  // the body of g(x), then if y is substituted for x, the rhs of g(x) reduces to y!=y, or false.\n  // The correct answer however is true, as f states taht for every boolean y there is an y' that\n  // is not equal to it.\n  data_specification dataspec = parse_data_specification(\n                    \"map f:Bool;\\n\"\n                    \"    g:Bool->Bool;\\n\"\n                    \"var x:Bool;\\n\"\n                    \"eqn f=forall y:Bool.g(y);\\n\"\n                    \"    g(x)=exists y:Bool.x!=y;\\n\");\n\n  rewriter r(dataspec, s);\n  quantifier_expression_test(\"f\", \"true\", dataspec, r);\n}\n\n\nint test_main(int argc, char** argv)\n{\n  auto strategies = data::detail::get_test_rewrite_strategies(false);\n  for (const auto& strategy: strategies)\n  {\n    std::clog << \"  Strategy: \" << strategy << std::endl;\n    quantifier_expression_test(strategy);\n    quantifier_in_rewrite_rules_test(strategy);\n  }\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "4b31157a45fc9183e7c6fb8d5da9538f385d98a8", "size": 8667, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libraries/data/test/quantifier_test.cpp", "max_stars_repo_name": "gijskant/mcrl2-pmc", "max_stars_repo_head_hexsha": "9ea75755081b20623bc8fc7db27124d084e781fe", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libraries/data/test/quantifier_test.cpp", "max_issues_repo_name": "gijskant/mcrl2-pmc", "max_issues_repo_head_hexsha": "9ea75755081b20623bc8fc7db27124d084e781fe", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libraries/data/test/quantifier_test.cpp", "max_forks_repo_name": "gijskant/mcrl2-pmc", "max_forks_repo_head_hexsha": "9ea75755081b20623bc8fc7db27124d084e781fe", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.6208791209, "max_line_length": 245, "alphanum_fraction": 0.6096688589, "num_tokens": 2631, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.4898270380294519}}
{"text": "#include \"tasktorrent/tasktorrent.hpp\"\n#ifdef USE_MKL\n#include <mkl_cblas.h>\n#include <mkl_lapacke.h>\n#else\n#include <cblas.h>\n#include <lapacke.h>\n#endif\n#include <Eigen/Core>\n#include <Eigen/Cholesky>\n#include <fstream>\n#include <array>\n#include <random>\n#include <mutex>\n#include <iostream>\n#include <map>\n#include <memory>\n#include <set>\n#include <mpi.h>\n#include <string>\n\nusing namespace std;\nusing namespace Eigen;\nusing namespace ttor;\n\ntypedef array<int, 2> int2;\ntypedef array<int, 3> int3;\n\n/*\n * Parametrized priorities for cholesky:\n * 0. No priority, only enforces potrf>trsm>gemm\n * 1. Row-based priority, prioritize tasks with smaller row number in addition to priority 0.\n * 2. Critical path priority, prioritize tasks with longest distance to the exit task. For references, check out the paper\n    Beaumont, Olivier, et al. \"A Makespan Lower Bound for the Scheduling of the Tiled Cholesky Factorization based on ALAP Schedule.\" (2020).\n * 3. Critical path and row priority, prioritize tasks with smaller row number in addition to priority 2. We also enforces potrf>trsm>gemm\n */\n\nenum PrioKind { no = 0, row = 1, cp = 2, cp_row = 3};\n\n\n/*\n* 3D Cholesky based on the algorithm from the paper\n    Kalluri Eswar, et al. \"On Mapping Data and Computation for Parallel Sparse Cholesky Factorization.\" (1995)\n* However, this implementation only uses 3D mapping for gemm tasks. 1D mapping is used for potrf tasks and 2D mapping is used for trsm tasks. \n*/\n\nvoid cholesky3d(int n_threads, int verb, int block_size, int num_blocks, int npcols, int nprows, PrioKind prio, int log, int debug)\n{\n    const int rank = comm_rank();\n    const int n_ranks = comm_size();\n    std::atomic<long long int> potrf_us_t(0);\n    std::atomic<long long int> trsm_us_t(0);\n    std::atomic<long long int> gemm_us_t(0);\n    std::atomic<long long int> accu_us_t(0);\n    assert(npcols * nprows == n_ranks);\n    int q = static_cast<int>(cbrt(n_ranks));\n    if (q * q * q != n_ranks)\n    {\n        if (rank == 0)\n        {\n            cerr << \"Number of processes must be a perfect cube.\" << endl;\n        }\n        MPI_Finalize();\n        exit(1);\n    }\n    \n    int3 rank_3d;\n    int2 rank_2d;\n    rank_3d[0] = rank / (q * q);\n    rank_3d[1] = (rank % (q * q)) / q;\n    rank_3d[2] = (rank % (q * q)) % q;\n    rank_2d[0] = rank % nprows;\n    rank_2d[1] = rank / nprows;\n\n    // Number of tasks\n    int n_tasks_per_rank = 2;\n    struct acc_data {\n        vector<std::unique_ptr<MatrixXd>> to_accumulate; // to_accumulate[k] holds matrix result of gemm(k,i,j)\n    };\n\n    auto potf_block_2_prio = [&](int j) {\n        if (prio == PrioKind::cp_row) {\n            return (double)(9 * (num_blocks - j) - 1) + 18 * num_blocks * num_blocks;\n        }\n        else if(prio == PrioKind::cp) {\n            return (double)(9 * (num_blocks - j) - 1);\n        }\n        else if(prio == PrioKind::row) {\n            return 3.0 * (double)(num_blocks - j);\n        }\n        else {\n            return 3.0;\n        }\n    };\n\n    auto trsm_block_2_prio = [&](int2 ij) {\n        if (prio == PrioKind::cp_row) {\n            return (double)((num_blocks - ij[0]) + num_blocks * (9.0 * num_blocks - 9.0 * ij[1] - 2.0) + 9 * num_blocks * num_blocks);\n        }\n        else if(prio == PrioKind::cp) {\n            return (double)(9 * (num_blocks - ij[1]) - 2);\n        }\n        else if(prio == PrioKind::row) {\n            return 2.0 * (double)(num_blocks - ij[0]);\n        }\n        else {\n            return 2.0;\n        }\n    };\n\n    auto gemm_block_2_prio = [&](int3 kij) {\n        if (prio == PrioKind::cp_row) {\n            return (double)(num_blocks - kij[1]) + num_blocks * (9.0 * num_blocks - 3.0 * kij[2] - 6.0 * (kij[0] / q) - 2.0);\n        }\n        else if(prio == PrioKind::cp) {\n            return (double)(9 * num_blocks - 9 * kij[2] - 2);\n        }\n        else if(prio == PrioKind::row) {\n            return (double)(num_blocks - kij[1]);\n        }\n        else {\n            return 1.0;\n        }\n    };\n\n    std::vector<acc_data> gemm_results(num_blocks*num_blocks);\n    auto val = [&](int i, int j) { return 1.0/(double)((i + j)*(i + j) + 1) + ((i == j) ? 1.0 * block_size * num_blocks : 0.0); };\n    auto rank3d21 = [&](int i, int j, int k) { return ((j % q) * q + k % q) + (i % q) * q * q;};\n    auto rank2d21 = [&](int i, int j) { return (j % npcols) * nprows + (i % nprows);};\n    auto rank1d21 = [&](int j) { return j % n_ranks; };\n    vector<unique_ptr<MatrixXd>> blocks(num_blocks*num_blocks);\n\n    auto bloc_2_rank = [&](int i, int j) {\n        int r = (j % npcols) * nprows + (i % nprows);\n        assert(r >= 0 && r < n_ranks);\n        return r;\n    };\n \n    auto block_2_thread = [&](int i, int j) {\n        int ii = i / nprows;\n        int jj = j / npcols;\n        int num_blocksit = num_blocks / nprows;\n        return (ii + jj * num_blocksit) % n_threads;\n    };\n    {\n        Eigen::MatrixXd A = Eigen::MatrixXd::Identity(256,256);\n        Eigen::MatrixXd B = Eigen::MatrixXd::Identity(256,256);\n        Eigen::MatrixXd C = Eigen::MatrixXd::Identity(256,256);\n        for(int i = 0; i < 10; i++) {\n            cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, 256, 256, 256, 1.0, A.data(), 256, B.data(), 256, 1.0, C.data(), 256);\n        }\n    }\n    for (int ii=0; ii<num_blocks; ii++) {\n        for (int jj=0; jj<num_blocks; jj++) {\n            auto val_loc = [&](int i, int j) { return val(ii*block_size+i,jj*block_size+j); };\n            int dest = (ii == jj) ? rank1d21(ii) : rank2d21(ii,jj);\n            if(dest == rank) {\n                blocks[ii+jj*num_blocks]=make_unique<MatrixXd>(block_size, block_size);\n                *blocks[ii+jj*num_blocks]=MatrixXd::NullaryExpr(block_size, block_size, val_loc);\n                gemm_results[ii+jj*num_blocks].to_accumulate= vector<std::unique_ptr<MatrixXd>>(q);\n                for (int ll=0; ll<q; ll++) {\n                    gemm_results[ii+jj*num_blocks].to_accumulate[ll]=make_unique<MatrixXd>(block_size, block_size);\n                    *(gemm_results[ii+jj*num_blocks].to_accumulate[ll])=MatrixXd::Zero(block_size, block_size);\n                }\n            } \n            else if (((ii % q) == rank_3d[0]) && ((jj % q) == rank_3d[1])) {\n                blocks[ii+jj*num_blocks]=make_unique<MatrixXd>(block_size, block_size);\n                *blocks[ii+jj*num_blocks]=MatrixXd::Zero(block_size, block_size);\n            } \n            else {\n                blocks[ii+jj*num_blocks]=make_unique<MatrixXd>(block_size, block_size);\n            }\n        }\n    }\n    // Initialize the communicator structure\n    Communicator comm(MPI_COMM_WORLD, verb);\n    // Initialize the runtime structures\n    Threadpool tp(n_threads, &comm, verb, \"WkTuto_\" + to_string(rank) + \"_\");\n    Taskflow<int> potrf(&tp, verb);\n    Taskflow<int2> trsm(&tp, verb);\n    Taskflow<int3> gemm(&tp, verb);\n    Taskflow<int3> accu(&tp, verb);\n    DepsLogger dlog(1000000);\n    Logger ttorlog(1000000);\n    if (log)  {\n        tp.set_logger(&ttorlog);\n        comm.set_logger(&ttorlog);\n    }\n    // Create active message\n    auto am_trsm = comm.make_large_active_msg( \n        [&](int& j) {\n                int offset = ((j + 1) / nprows + (((j + 1) % nprows) > rank_2d[0])) * nprows + rank_2d[0];\n                for(int i = offset; i < num_blocks; i = i + nprows) {\n                    if (debug) printf(\"Fulfilling trsm (%d, %d) on rank (%d, %d)\\n\", i, j, rank_2d[0], rank_2d[1]);\n                    assert(rank2d21(i, j) == rank);\n                    trsm.fulfill_promise({i,j});\n                }\n            },\n            [&](int& j){\n                return blocks[j+j*num_blocks]->data();\n            },\n            [&](int& j){\n                return;\n            });\n\n    auto am_gemm = comm.make_large_active_msg(\n        [&](int& i, int& k) {\n            assert(k % q == rank_3d[2]);\n            int offset_c = ((k + 1) / q + (((k + 1) % q) > rank_3d[1])) * q + rank_3d[1]; \n            if (i % q == rank_3d[0]) {\n                for(int j = offset_c; j < i; j = j + q) {\n                    if (debug) printf(\"TRSM (%d, %d) Fulfilling gemm (%d, %d, %d) on rank (%d, %d, %d)\\n\", i, k, k, i, j, rank_3d[2], rank_3d[0], rank_3d[1]);\n                    assert(rank3d21(i,j,k) == rank);\n                    gemm.fulfill_promise({k,i,j});\n                }\n            }\n            int offset_r = (i / q + ((i % q) > rank_3d[0])) * q + rank_3d[0];\n            if (i % q == rank_3d[1]) {\n                for(int j = offset_r; j < num_blocks; j = j + q) {\n                    if (debug) printf(\"TRSM (%d, %d) Fulfilling gemm (%d, %d, %d) on rank (%d, %d, %d)\\n\", i,k, k, j, i, rank_3d[2], rank_3d[0], rank_3d[1]);  \n                    assert(rank3d21(j,i,k) == rank);    \n                    gemm.fulfill_promise({k,j,i});\n                }\n            }\n        },\n        [&](int& i, int& k) {\n            return blocks[i+k*num_blocks]->data();\n        },\n        [&](int& i, int& k) {\n            return;\n        });\n\n    potrf.set_task([&](int j) {\n            assert(rank1d21(j) == rank);\n            timer t1 = wctime();\n            int info = LAPACKE_dpotrf(LAPACK_COL_MAJOR, 'L', block_size, blocks[j+j*num_blocks]->data(), block_size);\n            timer t2 = wctime();\n            potrf_us_t += 1e6 * elapsed(t1, t2);\n            assert(info == 0);\n            if (debug) printf(\"Running POTRF %d on rank %d\\n\", j, rank);\n        })\n        .set_fulfill([&](int j) { \n            for (int p = 0; p < nprows; p++) \n            {   \n                int r = rank2d21(p,j);\n                if (rank == r) {\n                    int offset = ((j + 1) / nprows + ((j + 1) % nprows) / (rank_2d[0] + 1)) * nprows + rank_2d[0];\n                    for(int i = offset; i < num_blocks; i = i + nprows) {\n                        trsm.fulfill_promise({i,j});\n                    }\n                }\n                else {\n                    auto Ljjv = view<double>(blocks[j+j*num_blocks]->data(), block_size*block_size);\n                    am_trsm->send_large(r, Ljjv, j);\n                }\n            }\n        })\n        .set_indegree([&](int j) {\n            if (j==0) {\n                return 1;\n            }\n            else if (j < q) {\n                return j;\n            }\n            else {\n                return q;\n            }\n        })\n        .set_mapping([&](int j) {\n            return block_2_thread(j,j);\n        })\n        .set_binding([&](int j) {\n            return false;\n\n        })        \n        .set_priority(potf_block_2_prio)\n        .set_name([&](int j) { \n            return \"POTRF\" + to_string(j) + \"_\" + to_string(rank);\n        });\n\n    trsm.set_task([&](int2 ij) {\n            int i=ij[0];\n            int j=ij[1];\n            assert(rank2d21(i,j) == rank);\n            timer t1 = wctime();\n            cblas_dtrsm(CblasColMajor, CblasRight, CblasLower, CblasTrans, CblasNonUnit, block_size, block_size, 1.0, blocks[j + j * num_blocks]->data(),block_size, blocks[i + j * num_blocks]->data(), block_size);\n            timer t2 = wctime();\n            trsm_us_t += 1e6 * elapsed(t1, t2);\n            if (debug) printf(\"Running trsm (%d, %d) on rank %d, %d\\n\", i, j, rank_2d[0], rank_2d[1]);\n        })\n        .set_fulfill([&](int2 ij) {\n            int i=ij[0];\n            int j=ij[1]; \n            for (int ri = 0; ri < q; ri++)  {\n                for (int rj = 0; rj < q; rj++) {\n                    int r = rank3d21(ri, rj, j);\n                    if (r == rank) {\n                        int offset_c = ((j + 1) / q + (((j + 1) % q) > rank_3d[1])) * q + rank_3d[1];\n                        if (i % q == rank_3d[0]) {\n                            for(int k = offset_c; k < i; k = k + q) {\n                                gemm.fulfill_promise({j,i,k});\n                            }\n                        }\n                        int offset_r = (i / q + ((i % q) > rank_3d[0])) * q + rank_3d[0];\n                        if (i % q == rank_3d[1]) {\n                            for(int k = offset_r; k < num_blocks; k = k + q) {\n                                gemm.fulfill_promise({j,k,i});\n                            } \n                        }\n                    }\n                    else {\n                        auto Lijv = view<double>(blocks[i + j * num_blocks]->data(), block_size*block_size);\n                        am_gemm->send_large(r, Lijv, i, j);\n                    } \n                }\n            }            \n        })\n        .set_indegree([&](int2 ij) {\n            int i=ij[0];\n            int j=ij[1];\n            return (j < q) ? j + 1 : q + 1;\n        })\n        .set_mapping([&](int2 ij) {\n            int i=ij[0];\n            int j=ij[1];\n            return block_2_thread(i,j);\n        })\n        .set_binding([&](int2 ij) {\n            int i=ij[0];\n            int j=ij[1];\n            return false;\n\n        })\n        .set_priority(trsm_block_2_prio)\n        .set_name([&](int2 ij) { \n            int i=ij[0];\n            int j=ij[1];\n            return \"TRSM\" + to_string(j) + \"_\" + to_string(i) + \"_\" +to_string(rank);\n        });\n   \n    auto am_accu = comm.make_large_active_msg(\n        [&](int& i, int& j, int& from) {\n            accu.fulfill_promise({from, i, j});\n        },\n        [&](int& i, int& j, int& from){\n            return gemm_results[i+j*num_blocks].to_accumulate[from]->data();\n        },\n        [&](int& i, int& j, int& from){\n            return; \n        });\n    \n    gemm.set_task([&](int3 kij) {\n            int k=kij[0];\n            int i=kij[1];\n            int j=kij[2]; \n            assert(rank3d21(i,j,k) == rank);\n            timer t1 = wctime();           \n            if (i==j) { \n                cblas_dsyrk(CblasColMajor, CblasLower, CblasNoTrans, block_size, block_size, -1.0, blocks[i+k*num_blocks]->data(), block_size, 1.0, blocks[i+j*num_blocks]->data(), block_size);\n            }\n            else {\n                cblas_dgemm(CblasColMajor, CblasNoTrans, CblasTrans, block_size, block_size, block_size, -1.0,blocks[i+k*num_blocks]->data(), block_size, blocks[j+k*num_blocks]->data(), block_size, 1.0, blocks[i+j*num_blocks]->data(), block_size);\n            }\n            timer t2 = wctime();\n            if (debug) printf(\"Running gemm (%d, %d, %d) on rank %d, %d, %d\\n\", k, i, j, rank_3d[2], rank_3d[0], rank_3d[1]);\n            gemm_us_t += 1e6 * elapsed(t1, t2);\n        })\n        .set_fulfill([&](int3 kij) { \n            int k=kij[0];\n            int i=kij[1];\n            int j=kij[2];\n            if (k+q<=j-1) {\n                gemm.fulfill_promise({k+q, i, j});\n            }\n            else {\n                int dest = (i == j) ? rank1d21(i) : rank2d21(i, j);\n                if (dest == rank) {\n                    if (debug) printf(\"gemm (%d, %d, %d) fulfilling accumu (%d, %d, %d) on rank %d, %d, %d\\n\", k, i, j, rank_3d[2], i, j, rank_3d[2], rank_3d[0], rank_3d[1]);\n                    accu.fulfill_promise({rank_3d[2], i, j});\n                }\n                else {\n                    int kk = rank_3d[2];\n                    auto Lij = view<double>(blocks[i+j*num_blocks]->data(), block_size*block_size);\n                    if (debug) printf(\"gemm (%d, %d, %d) Sending accumu (%d, %d, %d) to rank %d, %d\\n\", k, i, j, rank_3d[2], i, j, dest % nprows, dest / nprows);\n                    am_accu->send_large(dest, Lij, i, j, kk);\n                }\n            }\n        })\n        .set_indegree([&](int3 kij) {\n            int k=kij[0];\n            int i=kij[1];\n            int j=kij[2];\n            return 3 - (k/q == 0) - (i == j);\n        })\n        .set_mapping([&](int3 kij) {\n            int k=kij[0];\n            int i=kij[1];\n            int j=kij[2];\n            return block_2_thread(i,j);\n        })\n        .set_binding([&](int3 kij) {\n            return false;\n\n        })\n        .set_priority(gemm_block_2_prio)\n        .set_name([&](int3 kij) { // This is just for debugging and profiling\n            int k=kij[0];\n            int i=kij[1];\n            int j=kij[2];\n            return \"gemm\" + to_string(k) + \"_\" + to_string(i)+\"_\"+to_string(j)+\"_\"+to_string(comm_rank());\n        });\n\n    accu.set_task([&](int3 kij) {\n            int k=kij[0]; // Step (gemm's pivot)\n            int i=kij[1]; // Row\n            int j=kij[2]; // Col\n            int dest = (i == j) ? rank1d21(i) : rank2d21(i,j);\n            assert(dest == rank);\n            assert(j <= i);\n            if (debug) printf(\"Running accumu (%d, %d, %d) on rank %d, %d\\n\", k, i, j, rank % nprows, rank / nprows);\n            {\n                timer t_ = wctime();\n                *blocks[i+j*num_blocks] += (*gemm_results[i+j*num_blocks].to_accumulate[k]);\n                timer t__ = wctime();\n                accu_us_t += 1e6 * elapsed(t_, t__);\n            }\n        })\n        .set_fulfill([&](int3 kij) {\n            int k=kij[0];\n            int i=kij[1];\n            int j=kij[2];\n            assert(j <= i);\n            if(i == j) {\n                potrf.fulfill_promise(i);\n            } else {\n                trsm.fulfill_promise({i,j});\n            }\n        })\n        .set_indegree([&](int3 kij) {\n            return 1;\n        })\n        .set_mapping([&](int3 kij) {\n            int k=kij[0];\n            int i=kij[1];\n            int j=kij[2];\n            return block_2_thread(i,j);\n        })\n        .set_priority(gemm_block_2_prio)\n        .set_binding([&](int3 kij) {\n            return true; // IMPORTANT\n        })\n        .set_name([&](int3 kij) { // This is just for debugging and profiling\n            int k=kij[0];\n            int i=kij[1];\n            int j=kij[2];\n            return \"accumu\" + to_string(k) + \"_\" + to_string(i)+\"_\"+to_string(j)+\"_\"+to_string(comm_rank());\n        });\n\n    MPI_Barrier(MPI_COMM_WORLD);\n    timer t0 = wctime();\n    if (rank == 0){\n        potrf.fulfill_promise(0);\n    }\n    tp.join();\n    MPI_Barrier(MPI_COMM_WORLD);\n    timer t1 = wctime();\n    MPI_Status status;\n    if (rank==0) {\n        cout<<\"3D, Number of ranks \"<<n_ranks<<\", block_size \"<<block_size<<\", num_blocks \"<<num_blocks<<\", n_threads \"<<n_threads<<\", Priority \"<<prio<<\", Elapsed time: \"<<elapsed(t0,t1)<<endl;\n    }\n    MatrixXd A;\n    A = MatrixXd::NullaryExpr(block_size*num_blocks,block_size*num_blocks, val);\n    MatrixXd L = A;\n    for (int ii=0; ii<num_blocks; ii++) {\n        for (int jj=0; jj<num_blocks; jj++) {\n            if (jj<=ii)  {\n                int dest = (ii == jj) ? rank1d21(ii) : rank2d21(ii,jj);\n                if (rank==0 && rank!=dest) {\n                    blocks[ii+jj*num_blocks]=make_unique<MatrixXd>(block_size,block_size);\n                    MPI_Recv(blocks[ii+jj*num_blocks]->data(), block_size*block_size, MPI_DOUBLE, dest, 0, MPI_COMM_WORLD, &status);\n                }\n                else if (rank==dest && rank != 0) {\n                    MPI_Send(blocks[ii+jj*num_blocks]->data(), block_size*block_size, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD);\n                }\n            }\n        }\n    }\n    if (rank == 0)  {\n        for (int ii=0; ii<num_blocks; ii++) {\n            for (int jj=0; jj<num_blocks; jj++) {\n                if (jj<=ii)  {\n                    L.block(ii*block_size,jj*block_size,block_size,block_size)=*blocks[ii+jj*num_blocks];\n                }\n            }\n        }\n        auto L1=L.triangularView<Lower>();\n        VectorXd x = VectorXd::Random(block_size * num_blocks);\n        VectorXd b = A*x;\n        L1.solveInPlace(b);\n        L1.transpose().solveInPlace(b);\n        double error = (b - x).norm() / x.norm();\n        cout << \"Error solve: \" << error << endl;\n    }\n    if (log)  {\n        std::ofstream logfile;\n        string filename = \"ttor_3Dcholesky_Priority_\"+to_string(block_size)+\"_\"+to_string(num_blocks)+\"_\"+ to_string(n_threads)+\"_\"+ to_string(n_ranks)+\"_\"+ to_string(prio)+\".log.\"+to_string(rank);\n        logfile.open(filename);\n        logfile << ttorlog;\n        logfile.close();\n    }\n}\n\nint main(int argc, char **argv)\n{\n    int req = MPI_THREAD_FUNNELED;\n    int prov = -1;\n    MPI_Init_thread(NULL, NULL, req, &prov);\n    assert(prov == req);    \n    int n_threads = 2;\n    int verb = 0; // Can be changed to vary the verbosity of the messages\n    int block_size = 5;\n    int num_blocks = 10;\n    int npcols = 1;\n    int nprows = ttor::comm_size();\n    PrioKind prio = PrioKind::no;\n    int log = 0;\n    int debug = 0;\n    if (argc >= 2)\n    {\n        block_size = atoi(argv[1]);\n        assert(block_size > 0);\n    }\n    if (argc >= 3)\n    {\n        num_blocks = atoi(argv[2]);\n        assert(num_blocks > 0);\n    }\n    if (argc >= 5) {\n        n_threads=atoi(argv[3]);\n        assert(n_threads > 0);\n        verb=atoi(argv[4]);\n        assert(verb >= 0);\n    }\n    if (argc >= 7) {\n        npcols=atoi(argv[5]);\n        assert(npcols > 0);\n        nprows=atoi(argv[6]);\n        assert(nprows > 0);\n    }\n    if (argc >= 8) {\n        prio=(PrioKind)atoi(argv[7]);\n        assert(prio >= 0 && prio < 4);\n    }\n    if (argc >= 9) {\n        log = atoi(argv[9]);\n        assert(log == 0 || log == 1);\n    }\n    if (argc >= 10) {\n        debug = atoi(argv[10]);\n        assert(debug == 0 || debug == 1);\n    }\n    if(comm_rank() == 0) printf(\"Usage: ./3d_cholesky block_size num_blocks n_threads verb nprows npcols priority log debug\\n\");\n    cholesky3d(n_threads, verb, block_size, num_blocks, npcols, nprows, prio, log, debug);  \n    MPI_Finalize();\n}\n", "meta": {"hexsha": "6fee9e3f5a77b727e973ec6ad3e6e0bbd0674182", "size": 21340, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "miniapp/dense_cholesky/3d_cholesky.cpp", "max_stars_repo_name": "qyz96/tasktorrent", "max_stars_repo_head_hexsha": "4418d83da7de657363ac99ee263602794a0b97a5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "miniapp/dense_cholesky/3d_cholesky.cpp", "max_issues_repo_name": "qyz96/tasktorrent", "max_issues_repo_head_hexsha": "4418d83da7de657363ac99ee263602794a0b97a5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "miniapp/dense_cholesky/3d_cholesky.cpp", "max_forks_repo_name": "qyz96/tasktorrent", "max_forks_repo_head_hexsha": "4418d83da7de657363ac99ee263602794a0b97a5", "max_forks_repo_licenses": ["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.703180212, "max_line_length": 247, "alphanum_fraction": 0.4866916589, "num_tokens": 6290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.752012562644147, "lm_q2_score": 0.6513548511303336, "lm_q1q2_score": 0.489827030789219}}
{"text": "#include <iostream>\n#include <fstream>\n#include <Eigen/Dense>\n#include <json.hpp>\n\nusing namespace Eigen;\nusing namespace std;\nusing json = nlohmann::json;\n\n// Converts an std::vector of std::vector to Eigen Matrix\ntemplate <typename T>\nMatrix<T, Dynamic, Dynamic> vv_to_matrix(vector<vector<T>> vv){\n    Matrix <T, Dynamic, Dynamic>  m (vv.size(), vv[0].size());\n    for (int i = 0; i< vv.size(); i++){\n        for (int j = 0; j < vv[i].size(); j++){\n            m(i,j)= vv[i][j];\n        }\n    }\n    return m;\n}\n\n\n// Converts a std::vector to Eigen Vector\ntemplate <typename T>\nVector<T,Dynamic> std_vector_to_eigen(vector <T> v){\n    Vector<T,Dynamic> ev (v.size());\n    for (int i = 0; i< v.size(); i++){\n        ev(i)= v[i];\n    }\n    return ev;\n}\n\nVectorXd ReLu(VectorXd x){\n    for (int i = 0; i < x.size(); i++)\n        if (x(i) < 0) x(i) = 0;\n    return x;\n}\n\nclass DoubleLayerMLP{\n    private:\n        MatrixXd w1;\n        VectorXd b1;\n        MatrixXd w2;\n        VectorXd b2;\n    public:\n        \n        DoubleLayerMLP(MatrixXd w1, VectorXd b1, MatrixXd w2, VectorXd b2){\n            this->w1 = w1;      \n            this->b1 = b1;\n            this->w2 = w2;\n            this->b2 = b2;\n        }\n\n        DoubleLayerMLP(const DoubleLayerMLP & nn){\n            this->w1 = nn.w1;      \n            this->b1 = nn.b1;\n            this->w2 = nn.w2;\n            this->b2 = nn.b2;\n        }\n\n        DoubleLayerMLP(){\n            this->w1 = MatrixXd();      \n            this->b1 = VectorXd();\n            this->w2 = MatrixXd();\n            this->b2 = VectorXd();\n        }\n\n        DoubleLayerMLP(json json_data, string s){\n            vector<vector<double>> vv1 = json_data[s][\"w1\"].get<vector<vector<double>>>();\n            MatrixXd w1 = vv_to_matrix(vv1);\n\n            vector<vector<double>> vv2 = json_data[s][\"w2\"].get<vector<vector<double>>>();\n            MatrixXd w2 = vv_to_matrix(vv2);\n\n            vector<double> v1 = json_data[s][\"b1\"].get<vector<double>>();\n            VectorXd b1 = std_vector_to_eigen(v1);\n\n            vector<double> v2 = json_data[s][\"b2\"].get<vector<double>>();\n            VectorXd b2 = std_vector_to_eigen(v2);\n\n            this->w1 = w1;      \n            this->b1 = b1;\n            this->w2 = w2;\n            this->b2 = b2;\n        }\n\n        VectorXd forward(VectorXd x){\n            //cout<< endl << x << endl;\n            //cout<< endl << w1 << endl;\n            //cout<< endl << w1 * x << endl;\n\n            return w2*ReLu(w1 * x + b1) + b2;\n        }\n};\n\nclass MPNN{\n    private:\n        int V_attributes;\n        int E_attributes;\n        DoubleLayerMLP edge_update_nn;\n        DoubleLayerMLP vertice_update_nn;\n        DoubleLayerMLP output_update_nn;\n        int V_hidden;\n        int E_hidden;\n    public:\n        MPNN(int V_attributes, int E_attributes, DoubleLayerMLP edge_update_nn, DoubleLayerMLP vertice_update_nn, DoubleLayerMLP output_update_nn, int V_hidden = 0, int E_hidden = 0){\n                this -> V_attributes = V_attributes;\n                this -> E_attributes = E_attributes;\n                this -> edge_update_nn = edge_update_nn;\n                this -> vertice_update_nn = vertice_update_nn;\n                this -> output_update_nn = output_update_nn;\n                this -> V_hidden = V_hidden ? V_hidden : V_attributes;\n                this -> E_hidden = E_hidden ? E_hidden : E_attributes;\n            }\n        tuple<MatrixXd, MatrixXd, VectorXd>  forward (MatrixXd E, MatrixXi E_V, MatrixXd V){\n            int E_n = E.rows();\n            int V_n = V.rows();\n             \n            MatrixXd E_new = MatrixXd::Zero (E_n, this->E_hidden);\n            MatrixXd V_new = MatrixXd::Zero (V_n, this->V_hidden);\n\n            for (int i = 0; i < E_n; i++){\n                VectorXd E_concat(V.cols() + V.cols() + E.cols());\n                E_concat << V.row(E_V(i,0)).transpose(), V.row(E_V(i,1)).transpose(), E.row(i).transpose();\n\n                //cout<<V.row(E_V(i,0)) <<endl;\n                E_new.row(i) = this->edge_update_nn.forward(E_concat);\n            }\n\n            VectorXd V_agregated = VectorXd::Zero(this->V_hidden);\n\n            for (int i = 0; i < V_n; i++){  \n                VectorXd E_agregated = VectorXd::Zero(this->E_hidden);\n                for (int j = 0; j < E_n; j++){\n                    if (E(j,1) == i)\n                        E_agregated += E_new.row(i);\n                }\n                VectorXd V_concat(E_agregated.size() + V.cols());\n                V_concat << E_agregated, V.row(i).transpose();\n                \n                V_new.row(i) = this->vertice_update_nn.forward(V_concat);\n                V_agregated += V_new.row(i);\n            }\n\n            tuple<MatrixXd, MatrixXd, VectorXd> res = tuple<MatrixXd, MatrixXd, VectorXd> (E_new, V_new, this->output_update_nn.forward(V_agregated));\n            return res;\n        }\n};\n\n\nint main(int argc, char* argv[]){\n\n    std::ifstream ifs (\"weights.json\", std::ifstream::in);\n    json json_data = json::parse(ifs);\n    \n\n    DoubleLayerMLP edge_update_nn = DoubleLayerMLP(json_data, \"edge_update\");\n    DoubleLayerMLP vertice_update_nn = DoubleLayerMLP(json_data, \"vertice_update\");\n    DoubleLayerMLP output_update_nn = DoubleLayerMLP(json_data, \"output_update\");\n    MPNN model = MPNN(3, 3, edge_update_nn, vertice_update_nn, output_update_nn);\n    std::ifstream graphifstream (\"test_graph.json\", std::ifstream::in);\n    json json_graph = json::parse(graphifstream);\n\n    vector<vector<double>> E_vv = json_graph[\"E\"].get<vector<vector<double>>>();\n    vector<vector<int>> V_E_vv = json_graph[\"V_E\"].get<vector<vector<int>>>();\n    vector<vector<double>> V_vv = json_graph[\"V\"].get<vector<vector<double>>>();\n\n\n    MatrixXd E = vv_to_matrix<double>(E_vv);\n    MatrixXi V_E = vv_to_matrix<int> (V_E_vv);\n    MatrixXd V = vv_to_matrix<double>(V_vv);\n\n    tuple<MatrixXd, MatrixXd, VectorXd> res = model.forward(E,V_E,V);\n    MatrixXd new_E = get<0> (res);\n    MatrixXd new_V = get<1> (res);\n    MatrixXd new_u = get<2> (res);\n    cout << \"Edge attributes: \"<< endl << new_E  << endl;\n    cout << \"Vertice attributes: \"<< endl << new_V << endl;\n    cout << \"Global attributes: \"<< endl << new_u << endl;\n}", "meta": {"hexsha": "e0e94f97a3ffa32f718667bba3cf8f840afb91f3", "size": 6179, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "stlukyanenko/tmva-gnn-test", "max_stars_repo_head_hexsha": "20adc8974652678f788f6a10c35c92cd581c4bf5", "max_stars_repo_licenses": ["MIT"], "max_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": "stlukyanenko/tmva-gnn-test", "max_issues_repo_head_hexsha": "20adc8974652678f788f6a10c35c92cd581c4bf5", "max_issues_repo_licenses": ["MIT"], "max_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": "stlukyanenko/tmva-gnn-test", "max_forks_repo_head_hexsha": "20adc8974652678f788f6a10c35c92cd581c4bf5", "max_forks_repo_licenses": ["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.3277777778, "max_line_length": 183, "alphanum_fraction": 0.55235475, "num_tokens": 1648, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264638, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.48973286390249193}}
{"text": "/* p_integrand.c */\n#include <math.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <boost/math/special_functions/gamma.hpp>\nextern \"C\"\n{\n/* Survival function for R^phi*W */\nint RW_marginal_C(double *xval, double phi, double gamma, int n_xval, double *result){\n    double tmp2 = pow(gamma/2, phi)/boost::math::tgamma(0.5);\n    double tmp1, tmp0, a;\n    a = 0.5-phi;\n    \n    for(int i=0; i<n_xval; i++){\n        tmp1 = gamma/(2*pow(xval[i],1/phi));\n        tmp0 = tmp2/(a*xval[i]);\n        result[i] = boost::math::gamma_p(0.5L,tmp1) + boost::math::tgamma((long double)(a+1),tmp1)*tmp0-pow(tmp1,a)*exp(-tmp1)*tmp0;\n    }\n    return 1;\n}\n\n/* Marginal distribution function for R^phi*W + epsilon */\nint pRW_me_interp_C(double *xval, double *xp, double *surv_p, double tau_sqd, double phi, double gamma, int n_xval, int n_grid, double *result){\n    bool tau_bool = (tau_sqd > 0.05);\n    double tp[n_grid];\n    double integrand_p[n_grid];\n    double tmp, tmp_res; /* temporary constant */\n    double tmp_sum = 0; /* temporary trapesoid sum */\n    double sd = sqrt(tau_sqd);\n    double sd_const = sqrt(2)*sd;\n    double sd_const_pi =sqrt(2*M_PI)*sd;\n    int i,j, tmp_int; /* iterative constants */\n\n    for (i = 0; i < n_xval; i++) {\n        if(tau_bool & (xval[i]<820)){\n            /* Calculate integrand on a grid */\n            for(j=0; j<n_grid;j++){\n                tmp = xval[i]-xp[j];\n                tp[j] = tmp;\n                integrand_p[j] = exp(-tmp*tmp/(2*tau_sqd)) * surv_p[j];\n            }\n            \n            /* Numerical integral using the trapesoid method */\n            for(j=0; j<(n_grid-1);j++){\n                tmp_sum+= (tp[j+1]-tp[j])*(integrand_p[j] + integrand_p[j+1])/2;\n            }\n            tmp_res = 0.5*erfc(-xval[i]/sd_const)-tmp_sum/sd_const_pi;\n            tmp_sum = 0;\n            \n            /* CDF value must be greater than 0 */\n            if(tmp_res < 0){\n                tmp_res = 0;\n            }\n            result[i] = tmp_res;\n        }\n        else{\n            tmp_int = RW_marginal_C(&xval[i], phi, gamma, 1, &tmp_res);\n            result[i] = 1-tmp_res;\n        }\n    }\n    \n    return 1;\n}\n\n/* Get the quantile range for certain probability levels */\nint find_xrange_pRW_me_C(double min_p, double max_p, double min_x, double max_x, double *xp, double *surv_p, double tau_sqd, double phi, double gamma, int n_grid, double *x_range){\n    if (min_x >= max_x){\n        printf(\"Initial value of mix_x must be smaller than max_x.\\n\");\n        exit(EXIT_FAILURE);\n    }\n    \n    /* First the min */\n    double p_min_x;\n    int tmp_int;\n    tmp_int = pRW_me_interp_C(&min_x, xp, surv_p, tau_sqd, phi, gamma, 1, n_grid, &p_min_x);\n    while (p_min_x > min_p){\n        min_x = min_x-40/phi;\n        tmp_int = pRW_me_interp_C(&min_x, xp, surv_p, tau_sqd, phi, gamma, 1, n_grid, &p_min_x);\n    }\n        \n    x_range[0] = min_x;\n    \n    /* Now the max */\n    double p_max_x;\n    tmp_int = pRW_me_interp_C(&max_x, xp, surv_p, tau_sqd, phi, gamma, 1, n_grid, &p_max_x);\n    while (p_max_x < max_p){\n        max_x = max_x*2; /* Upper will set to 20 initially */\n        tmp_int = pRW_me_interp_C(&max_x, xp, surv_p, tau_sqd, phi, gamma, 1, n_grid, &p_max_x);\n    }\n        \n    x_range[1] = max_x;\n    return 1;\n}\n\n\n\n/* Density function for R^phi*W */\nint RW_density_C(double *xval, double phi, double gamma, int n_xval, double *result){\n    double tmp2 = pow(gamma/2, phi)/boost::math::tgamma(0.5);\n    double tmp1, tmp0, a;\n    a = 0.5-phi;\n    \n    for(int i=0; i<n_xval; i++){\n        tmp1 = gamma/(2*pow(xval[i],1/phi));\n        tmp0 = tmp2/(a*pow(xval[i],2));\n        result[i] = (boost::math::tgamma((long double)(a+1),tmp1)-pow(tmp1,a)*exp(-tmp1))*tmp0;\n    }\n    return 1;\n}\n\n/* Marginal density function for R^phi*W + epsilon */\nint dRW_me_interp_C(double *xval, double *xp, double *den_p, double tau_sqd, double phi, double gamma, int n_xval, int n_grid, double *result){\n    double thresh_large = 820;\n    if(tau_sqd < 1) {\n        thresh_large = 50;\n    }\n    bool tau_bool = (tau_sqd > 0.05);\n    \n    double tp[n_grid];\n    double integrand_p[n_grid];\n    double tmp, tmp_res; /* temporary constant */\n    double tmp_sum = 0; /* temporary trapesoid sum */\n    double sd = sqrt(tau_sqd);\n    double sd_const_pi =sqrt(2*M_PI)*sd;\n    int i,j, tmp_int; /* iterative constants */\n\n    for (i = 0; i < n_xval; i++) {\n        if(tau_bool & (xval[i]<thresh_large)){\n            /* Calculate integrand on a grid */\n            for(j=0; j<n_grid;j++){\n                tmp = xval[i]-xp[j];\n                tp[j] = tmp;\n                integrand_p[j] = exp(-tmp*tmp/(2*tau_sqd)) * den_p[j];\n            }\n            \n            /* Numerical integral using the trapesoid method */\n            for(j=0; j<(n_grid-1);j++){\n                tmp_sum+= (tp[j+1]-tp[j])*(integrand_p[j] + integrand_p[j+1])/2;\n            }\n            tmp_res = tmp_sum/sd_const_pi;\n            tmp_sum = 0;\n            result[i] = tmp_res;\n        }else if((tau_bool & (xval[i]>=thresh_large))|(!tau_bool & (xval[i]>0))){\n            tmp_int = RW_density_C(&xval[i], phi, gamma, 1, &tmp_res);\n            result[i] = tmp_res;\n        }else{\n            result[i] = 0;\n        }\n    }\n    \n    return 1;\n}\n\n\n\n}\n\n", "meta": {"hexsha": "4c0041417d38ab722bc9c23311ee690862cac150", "size": 5260, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "p_integrand.cpp", "max_stars_repo_name": "likun-stat/nonstat_model_noXs", "max_stars_repo_head_hexsha": "ab44dad8b654f5c16c1ab81e50093262d1b8f3d4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "p_integrand.cpp", "max_issues_repo_name": "likun-stat/nonstat_model_noXs", "max_issues_repo_head_hexsha": "ab44dad8b654f5c16c1ab81e50093262d1b8f3d4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "p_integrand.cpp", "max_forks_repo_name": "likun-stat/nonstat_model_noXs", "max_forks_repo_head_hexsha": "ab44dad8b654f5c16c1ab81e50093262d1b8f3d4", "max_forks_repo_licenses": ["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.0817610063, "max_line_length": 180, "alphanum_fraction": 0.5568441065, "num_tokens": 1631, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.48969745029019673}}
{"text": "/**\n * @file iqn_test.cpp\n * @author Marcus Edel\n *\n * Test file for IQN (incremental Quasi-Newton).\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#include <mlpack/core.hpp>\n#include <mlpack/core/optimizers/iqn/iqn.hpp>\n#include <mlpack/methods/logistic_regression/logistic_regression.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n\nusing namespace mlpack::optimization;\nusing namespace mlpack::distribution;\nusing namespace mlpack::regression;\nusing namespace mlpack;\n\nBOOST_AUTO_TEST_SUITE(IQNTest);\n\n/**\n * Run IQN on logistic regression and make sure the results are acceptable.\n */\nBOOST_AUTO_TEST_CASE(LogisticRegressionTest)\n{\n  // Generate a two-Gaussian dataset.\n  GaussianDistribution g1(arma::vec(\"1.0 1.0 1.0\"), arma::eye<arma::mat>(3, 3));\n  GaussianDistribution g2(arma::vec(\"9.0 9.0 9.0\"), arma::eye<arma::mat>(3, 3));\n\n  arma::mat data(3, 1000);\n  arma::Row<size_t> responses(1000);\n  for (size_t i = 0; i < 500; ++i)\n  {\n    data.col(i) = g1.Random();\n    responses[i] = 0;\n  }\n  for (size_t i = 500; i < 1000; ++i)\n  {\n    data.col(i) = g2.Random();\n    responses[i] = 1;\n  }\n\n  // Shuffle the dataset.\n  arma::uvec indices = arma::shuffle(arma::linspace<arma::uvec>(0,\n      data.n_cols - 1, data.n_cols));\n  arma::mat shuffledData(3, 1000);\n  arma::Row<size_t> shuffledResponses(1000);\n  for (size_t i = 0; i < data.n_cols; ++i)\n  {\n    shuffledData.col(i) = data.col(indices[i]);\n    shuffledResponses[i] = responses[indices[i]];\n  }\n\n  // Create a test set.\n  arma::mat testData(3, 1000);\n  arma::Row<size_t> testResponses(1000);\n  for (size_t i = 0; i < 500; ++i)\n  {\n    testData.col(i) = g1.Random();\n    testResponses[i] = 0;\n  }\n  for (size_t i = 500; i < 1000; ++i)\n  {\n    testData.col(i) = g2.Random();\n    testResponses[i] = 1;\n  }\n\n  // Now run SGDR with snapshot ensembles on a couple of batch sizes.\n  for (size_t batchSize = 1; batchSize < 9; batchSize += 4)\n  {\n    IQN iqn(0.01, batchSize, 5000, 1e-3);\n    LogisticRegression<> lr(shuffledData, shuffledResponses, iqn, 0.5);\n\n    // Ensure that the error is close to zero.\n    const double acc = lr.ComputeAccuracy(data, responses);\n    BOOST_REQUIRE_CLOSE(acc, 100.0, 1.3); // 1.3% error tolerance.\n\n    const double testAcc = lr.ComputeAccuracy(testData, testResponses);\n    BOOST_REQUIRE_CLOSE(testAcc, 100.0, 1.6); // 1.6% error tolerance.\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "b8758af114c8f890eac524d828e812ba4d4fe8ed", "size": 2635, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/iqn_test.cpp", "max_stars_repo_name": "chigur/mlpack", "max_stars_repo_head_hexsha": "aff1eda03b7c279acb6d3e660d5c5a6f697d3735", "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/tests/iqn_test.cpp", "max_issues_repo_name": "chigur/mlpack", "max_issues_repo_head_hexsha": "aff1eda03b7c279acb6d3e660d5c5a6f697d3735", "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/tests/iqn_test.cpp", "max_forks_repo_name": "chigur/mlpack", "max_forks_repo_head_hexsha": "aff1eda03b7c279acb6d3e660d5c5a6f697d3735", "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.606741573, "max_line_length": 80, "alphanum_fraction": 0.6717267552, "num_tokens": 809, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778257, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4896974502901967}}
{"text": "#define BOOST_TEST_MODULE CODATA_2018\n#include <boost/test/included/unit_test.hpp>\n\n#include <cmath>\n#include <tuple>\n\ntypedef std::tuple<float, double, long double> test_types;\n\n#include <triumf/constants/codata_2018.hpp>\n\n// alpha particle-electron mass ratio\n// (7294.29954142 \u00b1 2.4e-07)\nBOOST_AUTO_TEST_CASE_TEMPLATE(alpha_particle_electron_mass_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::alpha_particle_electron_mass_ratio<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::alpha_particle_electron_mass_ratio<\n                 T>::value() == static_cast<T>(7294.29954142));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::alpha_particle_electron_mass_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::alpha_particle_electron_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(2.4e-07));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::alpha_particle_electron_mass_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::alpha_particle_electron_mass_ratio<\n          T>::precision()));\n}\n\n// alpha particle mass\n// (6.6446573357e-27 \u00b1 2e-36) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(alpha_particle_mass, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::alpha_particle_mass<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::alpha_particle_mass<T>::value() ==\n             static_cast<T>(6.6446573357e-27));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::alpha_particle_mass<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::alpha_particle_mass<T>::uncertainty() ==\n      static_cast<T>(2e-36));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::alpha_particle_mass<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::alpha_particle_mass<T>::precision()));\n}\n\n// alpha particle mass energy equivalent\n// (5.9719201914e-10 \u00b1 1.8e-19) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(alpha_particle_mass_energy_equivalent, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::alpha_particle_mass_energy_equivalent<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::alpha_particle_mass_energy_equivalent<\n          T>::value() == static_cast<T>(5.9719201914e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::alpha_particle_mass_energy_equivalent<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::alpha_particle_mass_energy_equivalent<\n          T>::uncertainty() == static_cast<T>(1.8e-19));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::alpha_particle_mass_energy_equivalent<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::alpha_particle_mass_energy_equivalent<\n          T>::precision()));\n}\n\n// alpha particle mass energy equivalent in MeV\n// (3727.3794066 \u00b1 1.1e-06) MeV\nBOOST_AUTO_TEST_CASE_TEMPLATE(alpha_particle_mass_energy_equivalent_in_MeV, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::\n          alpha_particle_mass_energy_equivalent_in_MeV<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::\n                 alpha_particle_mass_energy_equivalent_in_MeV<T>::value() ==\n             static_cast<T>(3727.3794066));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::\n          alpha_particle_mass_energy_equivalent_in_MeV<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::\n          alpha_particle_mass_energy_equivalent_in_MeV<T>::uncertainty() ==\n      static_cast<T>(1.1e-06));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::\n          alpha_particle_mass_energy_equivalent_in_MeV<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::\n          alpha_particle_mass_energy_equivalent_in_MeV<T>::precision()));\n}\n\n// alpha particle mass in u\n// (4.001506179127 \u00b1 6.3e-11) u\nBOOST_AUTO_TEST_CASE_TEMPLATE(alpha_particle_mass_in_u, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::alpha_particle_mass_in_u<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::alpha_particle_mass_in_u<T>::value() ==\n      static_cast<T>(4.001506179127));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::alpha_particle_mass_in_u<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::alpha_particle_mass_in_u<\n                 T>::uncertainty() == static_cast<T>(6.3e-11));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::alpha_particle_mass_in_u<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::alpha_particle_mass_in_u<\n                    T>::precision()));\n}\n\n// alpha particle molar mass\n// (0.0040015061777 \u00b1 1.2e-12) kg mol^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(alpha_particle_molar_mass, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::alpha_particle_molar_mass<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::alpha_particle_molar_mass<T>::value() ==\n      static_cast<T>(0.0040015061777));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::alpha_particle_molar_mass<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::alpha_particle_molar_mass<\n                 T>::uncertainty() == static_cast<T>(1.2e-12));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::alpha_particle_molar_mass<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::alpha_particle_molar_mass<\n                    T>::precision()));\n}\n\n// alpha particle-proton mass ratio\n// (3.97259969009 \u00b1 2.2e-10)\nBOOST_AUTO_TEST_CASE_TEMPLATE(alpha_particle_proton_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::alpha_particle_proton_mass_ratio<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::alpha_particle_proton_mass_ratio<\n                 T>::value() == static_cast<T>(3.97259969009));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::alpha_particle_proton_mass_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::alpha_particle_proton_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(2.2e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::alpha_particle_proton_mass_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::alpha_particle_proton_mass_ratio<\n          T>::precision()));\n}\n\n// alpha particle relative atomic mass\n// (4.001506179127 \u00b1 6.3e-11)\nBOOST_AUTO_TEST_CASE_TEMPLATE(alpha_particle_relative_atomic_mass, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::alpha_particle_relative_atomic_mass<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::alpha_particle_relative_atomic_mass<\n          T>::value() == static_cast<T>(4.001506179127));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::alpha_particle_relative_atomic_mass<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::alpha_particle_relative_atomic_mass<\n          T>::uncertainty() == static_cast<T>(6.3e-11));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::alpha_particle_relative_atomic_mass<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::alpha_particle_relative_atomic_mass<\n          T>::precision()));\n}\n\n// Angstrom star\n// (1.00001495e-10 \u00b1 9e-17) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(Angstrom_star, T, test_types) {\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::Angstrom_star<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::Angstrom_star<T>::value() ==\n             static_cast<T>(1.00001495e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Angstrom_star<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::Angstrom_star<T>::uncertainty() ==\n             static_cast<T>(9e-17));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Angstrom_star<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::Angstrom_star<T>::precision()));\n}\n\n// atomic mass constant\n// (1.6605390666e-27 \u00b1 5e-37) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_mass_constant, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_mass_constant<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::atomic_mass_constant<T>::value() ==\n             static_cast<T>(1.6605390666e-27));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_mass_constant<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::atomic_mass_constant<T>::uncertainty() ==\n      static_cast<T>(5e-37));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_mass_constant<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::atomic_mass_constant<T>::precision()));\n}\n\n// atomic mass constant energy equivalent\n// (1.4924180856e-10 \u00b1 4.5e-20) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_mass_constant_energy_equivalent, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_mass_constant_energy_equivalent<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::atomic_mass_constant_energy_equivalent<\n          T>::value() == static_cast<T>(1.4924180856e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_mass_constant_energy_equivalent<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::atomic_mass_constant_energy_equivalent<\n          T>::uncertainty() == static_cast<T>(4.5e-20));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_mass_constant_energy_equivalent<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::atomic_mass_constant_energy_equivalent<\n          T>::precision()));\n}\n\n// atomic mass constant energy equivalent in MeV\n// (931.49410242 \u00b1 2.8e-07) MeV\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_mass_constant_energy_equivalent_in_MeV, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::\n          atomic_mass_constant_energy_equivalent_in_MeV<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::\n                 atomic_mass_constant_energy_equivalent_in_MeV<T>::value() ==\n             static_cast<T>(931.49410242));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::\n          atomic_mass_constant_energy_equivalent_in_MeV<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::\n          atomic_mass_constant_energy_equivalent_in_MeV<T>::uncertainty() ==\n      static_cast<T>(2.8e-07));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::\n          atomic_mass_constant_energy_equivalent_in_MeV<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::\n          atomic_mass_constant_energy_equivalent_in_MeV<T>::precision()));\n}\n\n// atomic mass unit-electron volt relationship\n// (931494102.42 \u00b1 0.28) eV\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_mass_unit_electron_volt_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::\n          atomic_mass_unit_electron_volt_relationship<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::\n                 atomic_mass_unit_electron_volt_relationship<T>::value() ==\n             static_cast<T>(931494102.42));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::\n          atomic_mass_unit_electron_volt_relationship<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::\n          atomic_mass_unit_electron_volt_relationship<T>::uncertainty() ==\n      static_cast<T>(0.28));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::\n          atomic_mass_unit_electron_volt_relationship<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::\n          atomic_mass_unit_electron_volt_relationship<T>::precision()));\n}\n\n// atomic mass unit-hartree relationship\n// (34231776.874 \u00b1 0.01) E_h\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_mass_unit_hartree_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_mass_unit_hartree_relationship<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::atomic_mass_unit_hartree_relationship<\n          T>::value() == static_cast<T>(34231776.874));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_mass_unit_hartree_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::atomic_mass_unit_hartree_relationship<\n          T>::uncertainty() == static_cast<T>(0.01));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_mass_unit_hartree_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::atomic_mass_unit_hartree_relationship<\n          T>::precision()));\n}\n\n// atomic mass unit-hertz relationship\n// (2.25234271871e+23 \u00b1 68000000000000.0) Hz\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_mass_unit_hertz_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_mass_unit_hertz_relationship<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::atomic_mass_unit_hertz_relationship<\n          T>::value() == static_cast<T>(2.25234271871e+23));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_mass_unit_hertz_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::atomic_mass_unit_hertz_relationship<\n          T>::uncertainty() == static_cast<T>(68000000000000.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_mass_unit_hertz_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::atomic_mass_unit_hertz_relationship<\n          T>::precision()));\n}\n\n// atomic mass unit-inverse meter relationship\n// (751300661040000.0 \u00b1 230000.0) m^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_mass_unit_inverse_meter_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::\n          atomic_mass_unit_inverse_meter_relationship<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::\n                 atomic_mass_unit_inverse_meter_relationship<T>::value() ==\n             static_cast<T>(751300661040000.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::\n          atomic_mass_unit_inverse_meter_relationship<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::\n          atomic_mass_unit_inverse_meter_relationship<T>::uncertainty() ==\n      static_cast<T>(230000.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::\n          atomic_mass_unit_inverse_meter_relationship<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::\n          atomic_mass_unit_inverse_meter_relationship<T>::precision()));\n}\n\n// atomic mass unit-joule relationship\n// (1.4924180856e-10 \u00b1 4.5e-20) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_mass_unit_joule_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_mass_unit_joule_relationship<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::atomic_mass_unit_joule_relationship<\n          T>::value() == static_cast<T>(1.4924180856e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_mass_unit_joule_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::atomic_mass_unit_joule_relationship<\n          T>::uncertainty() == static_cast<T>(4.5e-20));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_mass_unit_joule_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::atomic_mass_unit_joule_relationship<\n          T>::precision()));\n}\n\n// atomic mass unit-kelvin relationship\n// (10809540191600.0 \u00b1 3300.0) K\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_mass_unit_kelvin_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_mass_unit_kelvin_relationship<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::atomic_mass_unit_kelvin_relationship<\n          T>::value() == static_cast<T>(10809540191600.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_mass_unit_kelvin_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::atomic_mass_unit_kelvin_relationship<\n          T>::uncertainty() == static_cast<T>(3300.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_mass_unit_kelvin_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::atomic_mass_unit_kelvin_relationship<\n          T>::precision()));\n}\n\n// atomic mass unit-kilogram relationship\n// (1.6605390666e-27 \u00b1 5e-37) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_mass_unit_kilogram_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_mass_unit_kilogram_relationship<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::atomic_mass_unit_kilogram_relationship<\n          T>::value() == static_cast<T>(1.6605390666e-27));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_mass_unit_kilogram_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::atomic_mass_unit_kilogram_relationship<\n          T>::uncertainty() == static_cast<T>(5e-37));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_mass_unit_kilogram_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::atomic_mass_unit_kilogram_relationship<\n          T>::precision()));\n}\n\n// atomic unit of 1st hyperpolarizability\n// (3.2063613061e-53 \u00b1 1.5e-62) C^3 m^3 J^-2\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_1st_hyperpolarizability, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_1st_hyperpolarizability<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::atomic_unit_of_1st_hyperpolarizability<\n          T>::value() == static_cast<T>(3.2063613061e-53));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_1st_hyperpolarizability<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::atomic_unit_of_1st_hyperpolarizability<\n          T>::uncertainty() == static_cast<T>(1.5e-62));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_1st_hyperpolarizability<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::atomic_unit_of_1st_hyperpolarizability<\n          T>::precision()));\n}\n\n// atomic unit of 2nd hyperpolarizability\n// (6.2353799905e-65 \u00b1 3.8e-74) C^4 m^4 J^-3\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_2nd_hyperpolarizability, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_2nd_hyperpolarizability<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::atomic_unit_of_2nd_hyperpolarizability<\n          T>::value() == static_cast<T>(6.2353799905e-65));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_2nd_hyperpolarizability<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::atomic_unit_of_2nd_hyperpolarizability<\n          T>::uncertainty() == static_cast<T>(3.8e-74));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_2nd_hyperpolarizability<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::atomic_unit_of_2nd_hyperpolarizability<\n          T>::precision()));\n}\n\n// atomic unit of action\n// (1.054571817e-34 \u00b1 0.0) J s\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_action, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_action<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::atomic_unit_of_action<T>::value() ==\n      static_cast<T>(1.054571817e-34));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_action<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::atomic_unit_of_action<T>::uncertainty() ==\n      static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_action<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::atomic_unit_of_action<T>::precision()));\n}\n\n// atomic unit of charge\n// (1.602176634e-19 \u00b1 0.0) C\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_charge, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_charge<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::atomic_unit_of_charge<T>::value() ==\n      static_cast<T>(1.602176634e-19));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_charge<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::atomic_unit_of_charge<T>::uncertainty() ==\n      static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_charge<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::atomic_unit_of_charge<T>::precision()));\n}\n\n// atomic unit of charge density\n// (1081202384570.0 \u00b1 490.0) C m^-3\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_charge_density, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_charge_density<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::atomic_unit_of_charge_density<\n                 T>::value() == static_cast<T>(1081202384570.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_charge_density<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::atomic_unit_of_charge_density<\n                 T>::uncertainty() == static_cast<T>(490.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_charge_density<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::atomic_unit_of_charge_density<\n          T>::precision()));\n}\n\n// atomic unit of current\n// (0.00662361823751 \u00b1 1.3e-14) A\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_current, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_current<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::atomic_unit_of_current<T>::value() ==\n      static_cast<T>(0.00662361823751));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::atomic_unit_of_current<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::atomic_unit_of_current<\n                 T>::uncertainty() == static_cast<T>(1.3e-14));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_current<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::atomic_unit_of_current<T>::precision()));\n}\n\n// atomic unit of electric dipole mom.\n// (8.4783536255e-30 \u00b1 1.3e-39) C m\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_electric_dipole_mom, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_electric_dipole_mom<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::atomic_unit_of_electric_dipole_mom<\n                 T>::value() == static_cast<T>(8.4783536255e-30));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_electric_dipole_mom<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::atomic_unit_of_electric_dipole_mom<\n                 T>::uncertainty() == static_cast<T>(1.3e-39));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_electric_dipole_mom<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::atomic_unit_of_electric_dipole_mom<\n          T>::precision()));\n}\n\n// atomic unit of electric field\n// (514220674763.0 \u00b1 78.0) V m^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_electric_field, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_electric_field<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::atomic_unit_of_electric_field<\n                 T>::value() == static_cast<T>(514220674763.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_electric_field<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::atomic_unit_of_electric_field<\n                 T>::uncertainty() == static_cast<T>(78.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_electric_field<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::atomic_unit_of_electric_field<\n          T>::precision()));\n}\n\n// atomic unit of electric field gradient\n// (9.7173624292e+21 \u00b1 2900000000000.0) V m^-2\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_electric_field_gradient, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_electric_field_gradient<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::atomic_unit_of_electric_field_gradient<\n          T>::value() == static_cast<T>(9.7173624292e+21));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_electric_field_gradient<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::atomic_unit_of_electric_field_gradient<\n          T>::uncertainty() == static_cast<T>(2900000000000.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_electric_field_gradient<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::atomic_unit_of_electric_field_gradient<\n          T>::precision()));\n}\n\n// atomic unit of electric polarizability\n// (1.64877727436e-41 \u00b1 5e-51) C^2 m^2 J^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_electric_polarizability, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_electric_polarizability<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::atomic_unit_of_electric_polarizability<\n          T>::value() == static_cast<T>(1.64877727436e-41));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_electric_polarizability<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::atomic_unit_of_electric_polarizability<\n          T>::uncertainty() == static_cast<T>(5e-51));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_electric_polarizability<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::atomic_unit_of_electric_polarizability<\n          T>::precision()));\n}\n\n// atomic unit of electric potential\n// (27.211386245988 \u00b1 5.3e-11) V\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_electric_potential, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_electric_potential<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::atomic_unit_of_electric_potential<\n                 T>::value() == static_cast<T>(27.211386245988));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_electric_potential<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::atomic_unit_of_electric_potential<\n                 T>::uncertainty() == static_cast<T>(5.3e-11));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_electric_potential<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::atomic_unit_of_electric_potential<\n          T>::precision()));\n}\n\n// atomic unit of electric quadrupole mom.\n// (4.4865515246e-40 \u00b1 1.4e-49) C m^2\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_electric_quadrupole_mom, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_electric_quadrupole_mom<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::atomic_unit_of_electric_quadrupole_mom<\n          T>::value() == static_cast<T>(4.4865515246e-40));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_electric_quadrupole_mom<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::atomic_unit_of_electric_quadrupole_mom<\n          T>::uncertainty() == static_cast<T>(1.4e-49));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_electric_quadrupole_mom<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::atomic_unit_of_electric_quadrupole_mom<\n          T>::precision()));\n}\n\n// atomic unit of energy\n// (4.3597447222071e-18 \u00b1 8.5e-30) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_energy, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_energy<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::atomic_unit_of_energy<T>::value() ==\n      static_cast<T>(4.3597447222071e-18));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_energy<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::atomic_unit_of_energy<T>::uncertainty() ==\n      static_cast<T>(8.5e-30));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_energy<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::atomic_unit_of_energy<T>::precision()));\n}\n\n// atomic unit of force\n// (8.2387234983e-08 \u00b1 1.2e-17) N\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_force, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_force<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::atomic_unit_of_force<T>::value() ==\n             static_cast<T>(8.2387234983e-08));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_force<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::atomic_unit_of_force<T>::uncertainty() ==\n      static_cast<T>(1.2e-17));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_force<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::atomic_unit_of_force<T>::precision()));\n}\n\n// atomic unit of length\n// (5.29177210903e-11 \u00b1 8e-21) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_length, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_length<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::atomic_unit_of_length<T>::value() ==\n      static_cast<T>(5.29177210903e-11));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_length<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::atomic_unit_of_length<T>::uncertainty() ==\n      static_cast<T>(8e-21));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_length<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::atomic_unit_of_length<T>::precision()));\n}\n\n// atomic unit of mag. dipole mom.\n// (1.85480201566e-23 \u00b1 5.6e-33) J T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_mag_dipole_mom, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_mag_dipole_mom<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::atomic_unit_of_mag_dipole_mom<\n                 T>::value() == static_cast<T>(1.85480201566e-23));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_mag_dipole_mom<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::atomic_unit_of_mag_dipole_mom<\n                 T>::uncertainty() == static_cast<T>(5.6e-33));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_mag_dipole_mom<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::atomic_unit_of_mag_dipole_mom<\n          T>::precision()));\n}\n\n// atomic unit of mag. flux density\n// (235051.756758 \u00b1 7.1e-05) T\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_mag_flux_density, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_mag_flux_density<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::atomic_unit_of_mag_flux_density<\n                 T>::value() == static_cast<T>(235051.756758));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_mag_flux_density<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::atomic_unit_of_mag_flux_density<\n                 T>::uncertainty() == static_cast<T>(7.1e-05));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_mag_flux_density<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::atomic_unit_of_mag_flux_density<\n          T>::precision()));\n}\n\n// atomic unit of magnetizability\n// (7.8910366008e-29 \u00b1 4.8e-38) J T^-2\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_magnetizability, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_magnetizability<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::atomic_unit_of_magnetizability<\n                 T>::value() == static_cast<T>(7.8910366008e-29));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_magnetizability<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::atomic_unit_of_magnetizability<\n                 T>::uncertainty() == static_cast<T>(4.8e-38));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_magnetizability<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::atomic_unit_of_magnetizability<\n          T>::precision()));\n}\n\n// atomic unit of mass\n// (9.1093837015e-31 \u00b1 2.8e-40) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_mass, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_mass<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::atomic_unit_of_mass<T>::value() ==\n             static_cast<T>(9.1093837015e-31));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_mass<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::atomic_unit_of_mass<T>::uncertainty() ==\n      static_cast<T>(2.8e-40));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_mass<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::atomic_unit_of_mass<T>::precision()));\n}\n\n// atomic unit of momentum\n// (1.9928519141e-24 \u00b1 3e-34) kg m s^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_momentum, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_momentum<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::atomic_unit_of_momentum<T>::value() ==\n      static_cast<T>(1.9928519141e-24));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::atomic_unit_of_momentum<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::atomic_unit_of_momentum<\n                 T>::uncertainty() == static_cast<T>(3e-34));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_momentum<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::atomic_unit_of_momentum<T>::precision()));\n}\n\n// atomic unit of permittivity\n// (1.11265005545e-10 \u00b1 1.7e-20) F m^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_permittivity, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_permittivity<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::atomic_unit_of_permittivity<T>::value() ==\n      static_cast<T>(1.11265005545e-10));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::atomic_unit_of_permittivity<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::atomic_unit_of_permittivity<\n                 T>::uncertainty() == static_cast<T>(1.7e-20));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::atomic_unit_of_permittivity<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::atomic_unit_of_permittivity<\n                    T>::precision()));\n}\n\n// atomic unit of time\n// (2.4188843265857e-17 \u00b1 4.7e-29) s\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_time, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_time<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::atomic_unit_of_time<T>::value() ==\n             static_cast<T>(2.4188843265857e-17));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_time<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::atomic_unit_of_time<T>::uncertainty() ==\n      static_cast<T>(4.7e-29));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_time<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::atomic_unit_of_time<T>::precision()));\n}\n\n// atomic unit of velocity\n// (2187691.26364 \u00b1 0.00033) m s^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_velocity, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_velocity<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::atomic_unit_of_velocity<T>::value() ==\n      static_cast<T>(2187691.26364));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::atomic_unit_of_velocity<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::atomic_unit_of_velocity<\n                 T>::uncertainty() == static_cast<T>(0.00033));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::atomic_unit_of_velocity<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::atomic_unit_of_velocity<T>::precision()));\n}\n\n// Avogadro constant\n// (6.02214076e+23 \u00b1 0.0) mol^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(Avogadro_constant, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Avogadro_constant<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::Avogadro_constant<T>::value() ==\n             static_cast<T>(6.02214076e+23));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Avogadro_constant<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::Avogadro_constant<T>::uncertainty() ==\n      static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Avogadro_constant<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::Avogadro_constant<T>::precision()));\n}\n\n// Bohr magneton\n// (9.2740100783e-24 \u00b1 2.8e-33) J T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(Bohr_magneton, T, test_types) {\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::Bohr_magneton<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::Bohr_magneton<T>::value() ==\n             static_cast<T>(9.2740100783e-24));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Bohr_magneton<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::Bohr_magneton<T>::uncertainty() ==\n             static_cast<T>(2.8e-33));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Bohr_magneton<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::Bohr_magneton<T>::precision()));\n}\n\n// Bohr magneton in eV/T\n// (5.788381806e-05 \u00b1 1.7e-14) eV T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(Bohr_magneton_in_eV_T, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Bohr_magneton_in_eV_T<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::Bohr_magneton_in_eV_T<T>::value() ==\n      static_cast<T>(5.788381806e-05));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Bohr_magneton_in_eV_T<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::Bohr_magneton_in_eV_T<T>::uncertainty() ==\n      static_cast<T>(1.7e-14));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Bohr_magneton_in_eV_T<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::Bohr_magneton_in_eV_T<T>::precision()));\n}\n\n// Bohr magneton in Hz/T\n// (13996244936.1 \u00b1 4.2) Hz T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(Bohr_magneton_in_Hz_T, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Bohr_magneton_in_Hz_T<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::Bohr_magneton_in_Hz_T<T>::value() ==\n      static_cast<T>(13996244936.1));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Bohr_magneton_in_Hz_T<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::Bohr_magneton_in_Hz_T<T>::uncertainty() ==\n      static_cast<T>(4.2));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Bohr_magneton_in_Hz_T<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::Bohr_magneton_in_Hz_T<T>::precision()));\n}\n\n// Bohr magneton in inverse meter per tesla\n// (46.686447783 \u00b1 1.4e-08) m^-1 T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(Bohr_magneton_in_inverse_meter_per_tesla, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Bohr_magneton_in_inverse_meter_per_tesla<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::Bohr_magneton_in_inverse_meter_per_tesla<\n          T>::value() == static_cast<T>(46.686447783));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Bohr_magneton_in_inverse_meter_per_tesla<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::Bohr_magneton_in_inverse_meter_per_tesla<\n          T>::uncertainty() == static_cast<T>(1.4e-08));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Bohr_magneton_in_inverse_meter_per_tesla<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::Bohr_magneton_in_inverse_meter_per_tesla<\n          T>::precision()));\n}\n\n// Bohr magneton in K/T\n// (0.67171381563 \u00b1 2e-10) K T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(Bohr_magneton_in_K_T, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Bohr_magneton_in_K_T<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::Bohr_magneton_in_K_T<T>::value() ==\n             static_cast<T>(0.67171381563));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Bohr_magneton_in_K_T<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::Bohr_magneton_in_K_T<T>::uncertainty() ==\n      static_cast<T>(2e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Bohr_magneton_in_K_T<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::Bohr_magneton_in_K_T<T>::precision()));\n}\n\n// Bohr radius\n// (5.29177210903e-11 \u00b1 8e-21) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(Bohr_radius, T, test_types) {\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::Bohr_radius<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::Bohr_radius<T>::value() ==\n             static_cast<T>(5.29177210903e-11));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Bohr_radius<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::Bohr_radius<T>::uncertainty() ==\n             static_cast<T>(8e-21));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Bohr_radius<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::Bohr_radius<T>::precision()));\n}\n\n// Boltzmann constant\n// (1.380649e-23 \u00b1 0.0) J K^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(Boltzmann_constant, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Boltzmann_constant<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::Boltzmann_constant<T>::value() ==\n             static_cast<T>(1.380649e-23));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Boltzmann_constant<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::Boltzmann_constant<T>::uncertainty() ==\n      static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Boltzmann_constant<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::Boltzmann_constant<T>::precision()));\n}\n\n// Boltzmann constant in eV/K\n// (8.617333262e-05 \u00b1 0.0) eV K^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(Boltzmann_constant_in_eV_K, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Boltzmann_constant_in_eV_K<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::Boltzmann_constant_in_eV_K<T>::value() ==\n      static_cast<T>(8.617333262e-05));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::Boltzmann_constant_in_eV_K<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::Boltzmann_constant_in_eV_K<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::Boltzmann_constant_in_eV_K<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::Boltzmann_constant_in_eV_K<\n                    T>::precision()));\n}\n\n// Boltzmann constant in Hz/K\n// (20836619120.0 \u00b1 0.0) Hz K^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(Boltzmann_constant_in_Hz_K, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Boltzmann_constant_in_Hz_K<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::Boltzmann_constant_in_Hz_K<T>::value() ==\n      static_cast<T>(20836619120.0));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::Boltzmann_constant_in_Hz_K<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::Boltzmann_constant_in_Hz_K<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::Boltzmann_constant_in_Hz_K<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::Boltzmann_constant_in_Hz_K<\n                    T>::precision()));\n}\n\n// Boltzmann constant in inverse meter per kelvin\n// (69.50348004 \u00b1 0.0) m^-1 K^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(Boltzmann_constant_in_inverse_meter_per_kelvin, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::\n          Boltzmann_constant_in_inverse_meter_per_kelvin<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::\n                 Boltzmann_constant_in_inverse_meter_per_kelvin<T>::value() ==\n             static_cast<T>(69.50348004));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::\n          Boltzmann_constant_in_inverse_meter_per_kelvin<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::\n          Boltzmann_constant_in_inverse_meter_per_kelvin<T>::uncertainty() ==\n      static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::\n          Boltzmann_constant_in_inverse_meter_per_kelvin<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::\n          Boltzmann_constant_in_inverse_meter_per_kelvin<T>::precision()));\n}\n\n// classical electron radius\n// (2.8179403262e-15 \u00b1 1.3e-24) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(classical_electron_radius, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::classical_electron_radius<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::classical_electron_radius<T>::value() ==\n      static_cast<T>(2.8179403262e-15));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::classical_electron_radius<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::classical_electron_radius<\n                 T>::uncertainty() == static_cast<T>(1.3e-24));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::classical_electron_radius<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::classical_electron_radius<\n                    T>::precision()));\n}\n\n// Compton wavelength\n// (2.42631023867e-12 \u00b1 7.3e-22) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(Compton_wavelength, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Compton_wavelength<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::Compton_wavelength<T>::value() ==\n             static_cast<T>(2.42631023867e-12));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Compton_wavelength<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::Compton_wavelength<T>::uncertainty() ==\n      static_cast<T>(7.3e-22));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Compton_wavelength<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::Compton_wavelength<T>::precision()));\n}\n\n// conductance quantum\n// (7.748091729e-05 \u00b1 0.0) S\nBOOST_AUTO_TEST_CASE_TEMPLATE(conductance_quantum, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::conductance_quantum<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::conductance_quantum<T>::value() ==\n             static_cast<T>(7.748091729e-05));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::conductance_quantum<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::conductance_quantum<T>::uncertainty() ==\n      static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::conductance_quantum<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::conductance_quantum<T>::precision()));\n}\n\n// conventional value of ampere-90\n// (1.00000008887 \u00b1 0.0) A\nBOOST_AUTO_TEST_CASE_TEMPLATE(conventional_value_of_ampere_90, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::conventional_value_of_ampere_90<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::conventional_value_of_ampere_90<\n                 T>::value() == static_cast<T>(1.00000008887));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::conventional_value_of_ampere_90<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::conventional_value_of_ampere_90<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::conventional_value_of_ampere_90<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::conventional_value_of_ampere_90<\n          T>::precision()));\n}\n\n// conventional value of coulomb-90\n// (1.00000008887 \u00b1 0.0) C\nBOOST_AUTO_TEST_CASE_TEMPLATE(conventional_value_of_coulomb_90, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::conventional_value_of_coulomb_90<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::conventional_value_of_coulomb_90<\n                 T>::value() == static_cast<T>(1.00000008887));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::conventional_value_of_coulomb_90<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::conventional_value_of_coulomb_90<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::conventional_value_of_coulomb_90<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::conventional_value_of_coulomb_90<\n          T>::precision()));\n}\n\n// conventional value of farad-90\n// (0.9999999822 \u00b1 0.0) F\nBOOST_AUTO_TEST_CASE_TEMPLATE(conventional_value_of_farad_90, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::conventional_value_of_farad_90<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::conventional_value_of_farad_90<\n                 T>::value() == static_cast<T>(0.9999999822));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::conventional_value_of_farad_90<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::conventional_value_of_farad_90<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::conventional_value_of_farad_90<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::conventional_value_of_farad_90<\n          T>::precision()));\n}\n\n// conventional value of henry-90\n// (1.00000001779 \u00b1 0.0) H\nBOOST_AUTO_TEST_CASE_TEMPLATE(conventional_value_of_henry_90, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::conventional_value_of_henry_90<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::conventional_value_of_henry_90<\n                 T>::value() == static_cast<T>(1.00000001779));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::conventional_value_of_henry_90<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::conventional_value_of_henry_90<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::conventional_value_of_henry_90<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::conventional_value_of_henry_90<\n          T>::precision()));\n}\n\n// conventional value of Josephson constant\n// (483597900000000.0 \u00b1 0.0) Hz V^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(conventional_value_of_Josephson_constant, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::conventional_value_of_Josephson_constant<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::conventional_value_of_Josephson_constant<\n          T>::value() == static_cast<T>(483597900000000.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::conventional_value_of_Josephson_constant<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::conventional_value_of_Josephson_constant<\n          T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::conventional_value_of_Josephson_constant<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::conventional_value_of_Josephson_constant<\n          T>::precision()));\n}\n\n// conventional value of ohm-90\n// (1.00000001779 \u00b1 0.0) ohm\nBOOST_AUTO_TEST_CASE_TEMPLATE(conventional_value_of_ohm_90, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::conventional_value_of_ohm_90<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::conventional_value_of_ohm_90<\n                 T>::value() == static_cast<T>(1.00000001779));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::conventional_value_of_ohm_90<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::conventional_value_of_ohm_90<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::conventional_value_of_ohm_90<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::conventional_value_of_ohm_90<\n          T>::precision()));\n}\n\n// conventional value of volt-90\n// (1.00000010666 \u00b1 0.0) V\nBOOST_AUTO_TEST_CASE_TEMPLATE(conventional_value_of_volt_90, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::conventional_value_of_volt_90<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::conventional_value_of_volt_90<\n                 T>::value() == static_cast<T>(1.00000010666));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::conventional_value_of_volt_90<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::conventional_value_of_volt_90<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::conventional_value_of_volt_90<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::conventional_value_of_volt_90<\n          T>::precision()));\n}\n\n// conventional value of von Klitzing constant\n// (25812.807 \u00b1 0.0) ohm\nBOOST_AUTO_TEST_CASE_TEMPLATE(conventional_value_of_von_Klitzing_constant, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::\n          conventional_value_of_von_Klitzing_constant<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::\n                 conventional_value_of_von_Klitzing_constant<T>::value() ==\n             static_cast<T>(25812.807));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::\n          conventional_value_of_von_Klitzing_constant<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::\n          conventional_value_of_von_Klitzing_constant<T>::uncertainty() ==\n      static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::\n          conventional_value_of_von_Klitzing_constant<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::\n          conventional_value_of_von_Klitzing_constant<T>::precision()));\n}\n\n// conventional value of watt-90\n// (1.00000019553 \u00b1 0.0) W\nBOOST_AUTO_TEST_CASE_TEMPLATE(conventional_value_of_watt_90, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::conventional_value_of_watt_90<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::conventional_value_of_watt_90<\n                 T>::value() == static_cast<T>(1.00000019553));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::conventional_value_of_watt_90<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::conventional_value_of_watt_90<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::conventional_value_of_watt_90<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::conventional_value_of_watt_90<\n          T>::precision()));\n}\n\n// Cu x unit\n// (1.00207697e-13 \u00b1 2.8e-20) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(Cu_x_unit, T, test_types) {\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::Cu_x_unit<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::Cu_x_unit<T>::value() ==\n             static_cast<T>(1.00207697e-13));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Cu_x_unit<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::Cu_x_unit<T>::uncertainty() ==\n             static_cast<T>(2.8e-20));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::Cu_x_unit<T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::Cu_x_unit<T>::precision()));\n}\n\n// deuteron-electron mag. mom. ratio\n// (-0.0004664345551 \u00b1 1.2e-12)\nBOOST_AUTO_TEST_CASE_TEMPLATE(deuteron_electron_mag_mom_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::deuteron_electron_mag_mom_ratio<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::deuteron_electron_mag_mom_ratio<\n                 T>::value() == static_cast<T>(-0.0004664345551));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::deuteron_electron_mag_mom_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::deuteron_electron_mag_mom_ratio<\n                 T>::uncertainty() == static_cast<T>(1.2e-12));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::deuteron_electron_mag_mom_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::deuteron_electron_mag_mom_ratio<\n          T>::precision()));\n}\n\n// deuteron-electron mass ratio\n// (3670.48296788 \u00b1 1.3e-07)\nBOOST_AUTO_TEST_CASE_TEMPLATE(deuteron_electron_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::deuteron_electron_mass_ratio<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::deuteron_electron_mass_ratio<\n                 T>::value() == static_cast<T>(3670.48296788));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::deuteron_electron_mass_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::deuteron_electron_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(1.3e-07));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::deuteron_electron_mass_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::deuteron_electron_mass_ratio<\n          T>::precision()));\n}\n\n// deuteron g factor\n// (0.8574382338 \u00b1 2.2e-09)\nBOOST_AUTO_TEST_CASE_TEMPLATE(deuteron_g_factor, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::deuteron_g_factor<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::deuteron_g_factor<T>::value() ==\n             static_cast<T>(0.8574382338));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::deuteron_g_factor<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::deuteron_g_factor<T>::uncertainty() ==\n      static_cast<T>(2.2e-09));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::deuteron_g_factor<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::deuteron_g_factor<T>::precision()));\n}\n\n// deuteron mag. mom.\n// (4.330735094e-27 \u00b1 1.1e-35) J T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(deuteron_mag_mom, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::deuteron_mag_mom<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::deuteron_mag_mom<T>::value() ==\n             static_cast<T>(4.330735094e-27));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::deuteron_mag_mom<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::deuteron_mag_mom<T>::uncertainty() ==\n      static_cast<T>(1.1e-35));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::deuteron_mag_mom<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::deuteron_mag_mom<T>::precision()));\n}\n\n// deuteron mag. mom. to Bohr magneton ratio\n// (0.000466975457 \u00b1 1.2e-12)\nBOOST_AUTO_TEST_CASE_TEMPLATE(deuteron_mag_mom_to_Bohr_magneton_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::deuteron_mag_mom_to_Bohr_magneton_ratio<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::deuteron_mag_mom_to_Bohr_magneton_ratio<\n          T>::value() == static_cast<T>(0.000466975457));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::deuteron_mag_mom_to_Bohr_magneton_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::deuteron_mag_mom_to_Bohr_magneton_ratio<\n          T>::uncertainty() == static_cast<T>(1.2e-12));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::deuteron_mag_mom_to_Bohr_magneton_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::deuteron_mag_mom_to_Bohr_magneton_ratio<\n          T>::precision()));\n}\n\n// deuteron mag. mom. to nuclear magneton ratio\n// (0.8574382338 \u00b1 2.2e-09)\nBOOST_AUTO_TEST_CASE_TEMPLATE(deuteron_mag_mom_to_nuclear_magneton_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::\n          deuteron_mag_mom_to_nuclear_magneton_ratio<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::\n                 deuteron_mag_mom_to_nuclear_magneton_ratio<T>::value() ==\n             static_cast<T>(0.8574382338));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::\n          deuteron_mag_mom_to_nuclear_magneton_ratio<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::\n                 deuteron_mag_mom_to_nuclear_magneton_ratio<T>::uncertainty() ==\n             static_cast<T>(2.2e-09));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::\n          deuteron_mag_mom_to_nuclear_magneton_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::\n          deuteron_mag_mom_to_nuclear_magneton_ratio<T>::precision()));\n}\n\n// deuteron mass\n// (3.3435837724e-27 \u00b1 1e-36) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(deuteron_mass, T, test_types) {\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::deuteron_mass<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::deuteron_mass<T>::value() ==\n             static_cast<T>(3.3435837724e-27));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::deuteron_mass<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::deuteron_mass<T>::uncertainty() ==\n             static_cast<T>(1e-36));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::deuteron_mass<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::deuteron_mass<T>::precision()));\n}\n\n// deuteron mass energy equivalent\n// (3.00506323102e-10 \u00b1 9.1e-20) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(deuteron_mass_energy_equivalent, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::deuteron_mass_energy_equivalent<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::deuteron_mass_energy_equivalent<\n                 T>::value() == static_cast<T>(3.00506323102e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::deuteron_mass_energy_equivalent<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::deuteron_mass_energy_equivalent<\n                 T>::uncertainty() == static_cast<T>(9.1e-20));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::deuteron_mass_energy_equivalent<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::deuteron_mass_energy_equivalent<\n          T>::precision()));\n}\n\n// deuteron mass energy equivalent in MeV\n// (1875.61294257 \u00b1 5.7e-07) MeV\nBOOST_AUTO_TEST_CASE_TEMPLATE(deuteron_mass_energy_equivalent_in_MeV, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::deuteron_mass_energy_equivalent_in_MeV<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::deuteron_mass_energy_equivalent_in_MeV<\n          T>::value() == static_cast<T>(1875.61294257));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::deuteron_mass_energy_equivalent_in_MeV<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::deuteron_mass_energy_equivalent_in_MeV<\n          T>::uncertainty() == static_cast<T>(5.7e-07));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::deuteron_mass_energy_equivalent_in_MeV<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::deuteron_mass_energy_equivalent_in_MeV<\n          T>::precision()));\n}\n\n// deuteron mass in u\n// (2.013553212745 \u00b1 4e-11) u\nBOOST_AUTO_TEST_CASE_TEMPLATE(deuteron_mass_in_u, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::deuteron_mass_in_u<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::deuteron_mass_in_u<T>::value() ==\n             static_cast<T>(2.013553212745));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::deuteron_mass_in_u<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::deuteron_mass_in_u<T>::uncertainty() ==\n      static_cast<T>(4e-11));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::deuteron_mass_in_u<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::deuteron_mass_in_u<T>::precision()));\n}\n\n// deuteron molar mass\n// (0.00201355321205 \u00b1 6.1e-13) kg mol^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(deuteron_molar_mass, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::deuteron_molar_mass<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::deuteron_molar_mass<T>::value() ==\n             static_cast<T>(0.00201355321205));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::deuteron_molar_mass<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::deuteron_molar_mass<T>::uncertainty() ==\n      static_cast<T>(6.1e-13));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::deuteron_molar_mass<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::deuteron_molar_mass<T>::precision()));\n}\n\n// deuteron-neutron mag. mom. ratio\n// (-0.44820653 \u00b1 1.1e-07)\nBOOST_AUTO_TEST_CASE_TEMPLATE(deuteron_neutron_mag_mom_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::deuteron_neutron_mag_mom_ratio<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::deuteron_neutron_mag_mom_ratio<\n                 T>::value() == static_cast<T>(-0.44820653));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::deuteron_neutron_mag_mom_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::deuteron_neutron_mag_mom_ratio<\n                 T>::uncertainty() == static_cast<T>(1.1e-07));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::deuteron_neutron_mag_mom_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::deuteron_neutron_mag_mom_ratio<\n          T>::precision()));\n}\n\n// deuteron-proton mag. mom. ratio\n// (0.30701220939 \u00b1 7.9e-10)\nBOOST_AUTO_TEST_CASE_TEMPLATE(deuteron_proton_mag_mom_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::deuteron_proton_mag_mom_ratio<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::deuteron_proton_mag_mom_ratio<\n                 T>::value() == static_cast<T>(0.30701220939));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::deuteron_proton_mag_mom_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::deuteron_proton_mag_mom_ratio<\n                 T>::uncertainty() == static_cast<T>(7.9e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::deuteron_proton_mag_mom_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::deuteron_proton_mag_mom_ratio<\n          T>::precision()));\n}\n\n// deuteron-proton mass ratio\n// (1.99900750139 \u00b1 1.1e-10)\nBOOST_AUTO_TEST_CASE_TEMPLATE(deuteron_proton_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::deuteron_proton_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::deuteron_proton_mass_ratio<T>::value() ==\n      static_cast<T>(1.99900750139));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::deuteron_proton_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::deuteron_proton_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(1.1e-10));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::deuteron_proton_mass_ratio<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::deuteron_proton_mass_ratio<\n                    T>::precision()));\n}\n\n// deuteron relative atomic mass\n// (2.013553212745 \u00b1 4e-11)\nBOOST_AUTO_TEST_CASE_TEMPLATE(deuteron_relative_atomic_mass, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::deuteron_relative_atomic_mass<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::deuteron_relative_atomic_mass<\n                 T>::value() == static_cast<T>(2.013553212745));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::deuteron_relative_atomic_mass<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::deuteron_relative_atomic_mass<\n                 T>::uncertainty() == static_cast<T>(4e-11));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::deuteron_relative_atomic_mass<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::deuteron_relative_atomic_mass<\n          T>::precision()));\n}\n\n// deuteron rms charge radius\n// (2.12799e-15 \u00b1 7.4e-19) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(deuteron_rms_charge_radius, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::deuteron_rms_charge_radius<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::deuteron_rms_charge_radius<T>::value() ==\n      static_cast<T>(2.12799e-15));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::deuteron_rms_charge_radius<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::deuteron_rms_charge_radius<\n                 T>::uncertainty() == static_cast<T>(7.4e-19));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::deuteron_rms_charge_radius<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::deuteron_rms_charge_radius<\n                    T>::precision()));\n}\n\n// electron charge to mass quotient\n// (-175882001076.0 \u00b1 53.0) C kg^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_charge_to_mass_quotient, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_charge_to_mass_quotient<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::electron_charge_to_mass_quotient<\n                 T>::value() == static_cast<T>(-175882001076.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_charge_to_mass_quotient<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::electron_charge_to_mass_quotient<\n                 T>::uncertainty() == static_cast<T>(53.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_charge_to_mass_quotient<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::electron_charge_to_mass_quotient<\n          T>::precision()));\n}\n\n// electron-deuteron mag. mom. ratio\n// (-2143.9234915 \u00b1 5.6e-06)\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_deuteron_mag_mom_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_deuteron_mag_mom_ratio<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::electron_deuteron_mag_mom_ratio<\n                 T>::value() == static_cast<T>(-2143.9234915));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_deuteron_mag_mom_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::electron_deuteron_mag_mom_ratio<\n                 T>::uncertainty() == static_cast<T>(5.6e-06));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_deuteron_mag_mom_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::electron_deuteron_mag_mom_ratio<\n          T>::precision()));\n}\n\n// electron-deuteron mass ratio\n// (0.0002724437107462 \u00b1 9.6e-15)\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_deuteron_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_deuteron_mass_ratio<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::electron_deuteron_mass_ratio<\n                 T>::value() == static_cast<T>(0.0002724437107462));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_deuteron_mass_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::electron_deuteron_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(9.6e-15));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_deuteron_mass_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::electron_deuteron_mass_ratio<\n          T>::precision()));\n}\n\n// electron g factor\n// (-2.00231930436256 \u00b1 3.5e-13)\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_g_factor, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_g_factor<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::electron_g_factor<T>::value() ==\n             static_cast<T>(-2.00231930436256));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_g_factor<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::electron_g_factor<T>::uncertainty() ==\n      static_cast<T>(3.5e-13));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_g_factor<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::electron_g_factor<T>::precision()));\n}\n\n// electron gyromag. ratio\n// (176085963023.0 \u00b1 53.0) s^-1 T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_gyromag_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_gyromag_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::electron_gyromag_ratio<T>::value() ==\n      static_cast<T>(176085963023.0));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::electron_gyromag_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::electron_gyromag_ratio<\n                 T>::uncertainty() == static_cast<T>(53.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_gyromag_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::electron_gyromag_ratio<T>::precision()));\n}\n\n// electron gyromag. ratio in MHz/T\n// (28024.9514242 \u00b1 8.5e-06) MHz T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_gyromag_ratio_in_MHz_T, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_gyromag_ratio_in_MHz_T<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::electron_gyromag_ratio_in_MHz_T<\n                 T>::value() == static_cast<T>(28024.9514242));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_gyromag_ratio_in_MHz_T<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::electron_gyromag_ratio_in_MHz_T<\n                 T>::uncertainty() == static_cast<T>(8.5e-06));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_gyromag_ratio_in_MHz_T<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::electron_gyromag_ratio_in_MHz_T<\n          T>::precision()));\n}\n\n// electron-helion mass ratio\n// (0.0001819543074573 \u00b1 7.9e-15)\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_helion_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_helion_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::electron_helion_mass_ratio<T>::value() ==\n      static_cast<T>(0.0001819543074573));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::electron_helion_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::electron_helion_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(7.9e-15));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::electron_helion_mass_ratio<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::electron_helion_mass_ratio<\n                    T>::precision()));\n}\n\n// electron mag. mom.\n// (-9.2847647043e-24 \u00b1 2.8e-33) J T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_mag_mom, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_mag_mom<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::electron_mag_mom<T>::value() ==\n             static_cast<T>(-9.2847647043e-24));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_mag_mom<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::electron_mag_mom<T>::uncertainty() ==\n      static_cast<T>(2.8e-33));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_mag_mom<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::electron_mag_mom<T>::precision()));\n}\n\n// electron mag. mom. anomaly\n// (0.00115965218128 \u00b1 1.8e-13)\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_mag_mom_anomaly, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_mag_mom_anomaly<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::electron_mag_mom_anomaly<T>::value() ==\n      static_cast<T>(0.00115965218128));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::electron_mag_mom_anomaly<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::electron_mag_mom_anomaly<\n                 T>::uncertainty() == static_cast<T>(1.8e-13));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::electron_mag_mom_anomaly<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::electron_mag_mom_anomaly<\n                    T>::precision()));\n}\n\n// electron mag. mom. to Bohr magneton ratio\n// (-1.00115965218128 \u00b1 1.8e-13)\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_mag_mom_to_Bohr_magneton_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_mag_mom_to_Bohr_magneton_ratio<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::electron_mag_mom_to_Bohr_magneton_ratio<\n          T>::value() == static_cast<T>(-1.00115965218128));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_mag_mom_to_Bohr_magneton_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::electron_mag_mom_to_Bohr_magneton_ratio<\n          T>::uncertainty() == static_cast<T>(1.8e-13));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_mag_mom_to_Bohr_magneton_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::electron_mag_mom_to_Bohr_magneton_ratio<\n          T>::precision()));\n}\n\n// electron mag. mom. to nuclear magneton ratio\n// (-1838.28197188 \u00b1 1.1e-07)\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_mag_mom_to_nuclear_magneton_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::\n          electron_mag_mom_to_nuclear_magneton_ratio<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::\n                 electron_mag_mom_to_nuclear_magneton_ratio<T>::value() ==\n             static_cast<T>(-1838.28197188));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::\n          electron_mag_mom_to_nuclear_magneton_ratio<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::\n                 electron_mag_mom_to_nuclear_magneton_ratio<T>::uncertainty() ==\n             static_cast<T>(1.1e-07));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::\n          electron_mag_mom_to_nuclear_magneton_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::\n          electron_mag_mom_to_nuclear_magneton_ratio<T>::precision()));\n}\n\n// electron mass\n// (9.1093837015e-31 \u00b1 2.8e-40) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_mass, T, test_types) {\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::electron_mass<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::electron_mass<T>::value() ==\n             static_cast<T>(9.1093837015e-31));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_mass<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::electron_mass<T>::uncertainty() ==\n             static_cast<T>(2.8e-40));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_mass<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::electron_mass<T>::precision()));\n}\n\n// electron mass energy equivalent\n// (8.1871057769e-14 \u00b1 2.5e-23) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_mass_energy_equivalent, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_mass_energy_equivalent<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::electron_mass_energy_equivalent<\n                 T>::value() == static_cast<T>(8.1871057769e-14));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_mass_energy_equivalent<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::electron_mass_energy_equivalent<\n                 T>::uncertainty() == static_cast<T>(2.5e-23));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_mass_energy_equivalent<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::electron_mass_energy_equivalent<\n          T>::precision()));\n}\n\n// electron mass energy equivalent in MeV\n// (0.51099895 \u00b1 1.5e-10) MeV\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_mass_energy_equivalent_in_MeV, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_mass_energy_equivalent_in_MeV<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::electron_mass_energy_equivalent_in_MeV<\n          T>::value() == static_cast<T>(0.51099895));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_mass_energy_equivalent_in_MeV<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::electron_mass_energy_equivalent_in_MeV<\n          T>::uncertainty() == static_cast<T>(1.5e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_mass_energy_equivalent_in_MeV<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::electron_mass_energy_equivalent_in_MeV<\n          T>::precision()));\n}\n\n// electron mass in u\n// (0.000548579909065 \u00b1 1.6e-14) u\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_mass_in_u, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_mass_in_u<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::electron_mass_in_u<T>::value() ==\n             static_cast<T>(0.000548579909065));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_mass_in_u<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::electron_mass_in_u<T>::uncertainty() ==\n      static_cast<T>(1.6e-14));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_mass_in_u<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::electron_mass_in_u<T>::precision()));\n}\n\n// electron molar mass\n// (5.4857990888e-07 \u00b1 1.7e-16) kg mol^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_molar_mass, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_molar_mass<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::electron_molar_mass<T>::value() ==\n             static_cast<T>(5.4857990888e-07));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_molar_mass<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::electron_molar_mass<T>::uncertainty() ==\n      static_cast<T>(1.7e-16));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_molar_mass<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::electron_molar_mass<T>::precision()));\n}\n\n// electron-muon mag. mom. ratio\n// (206.7669883 \u00b1 4.6e-06)\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_muon_mag_mom_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_muon_mag_mom_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::electron_muon_mag_mom_ratio<T>::value() ==\n      static_cast<T>(206.7669883));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::electron_muon_mag_mom_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::electron_muon_mag_mom_ratio<\n                 T>::uncertainty() == static_cast<T>(4.6e-06));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::electron_muon_mag_mom_ratio<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::electron_muon_mag_mom_ratio<\n                    T>::precision()));\n}\n\n// electron-muon mass ratio\n// (0.00483633169 \u00b1 1.1e-10)\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_muon_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_muon_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::electron_muon_mass_ratio<T>::value() ==\n      static_cast<T>(0.00483633169));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::electron_muon_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::electron_muon_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(1.1e-10));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::electron_muon_mass_ratio<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::electron_muon_mass_ratio<\n                    T>::precision()));\n}\n\n// electron-neutron mag. mom. ratio\n// (960.9205 \u00b1 0.00023)\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_neutron_mag_mom_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_neutron_mag_mom_ratio<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::electron_neutron_mag_mom_ratio<\n                 T>::value() == static_cast<T>(960.9205));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_neutron_mag_mom_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::electron_neutron_mag_mom_ratio<\n                 T>::uncertainty() == static_cast<T>(0.00023));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_neutron_mag_mom_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::electron_neutron_mag_mom_ratio<\n          T>::precision()));\n}\n\n// electron-neutron mass ratio\n// (0.00054386734424 \u00b1 2.6e-13)\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_neutron_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_neutron_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::electron_neutron_mass_ratio<T>::value() ==\n      static_cast<T>(0.00054386734424));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::electron_neutron_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::electron_neutron_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(2.6e-13));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::electron_neutron_mass_ratio<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::electron_neutron_mass_ratio<\n                    T>::precision()));\n}\n\n// electron-proton mag. mom. ratio\n// (-658.21068789 \u00b1 2e-07)\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_proton_mag_mom_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_proton_mag_mom_ratio<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::electron_proton_mag_mom_ratio<\n                 T>::value() == static_cast<T>(-658.21068789));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_proton_mag_mom_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::electron_proton_mag_mom_ratio<\n                 T>::uncertainty() == static_cast<T>(2e-07));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_proton_mag_mom_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::electron_proton_mag_mom_ratio<\n          T>::precision()));\n}\n\n// electron-proton mass ratio\n// (0.000544617021487 \u00b1 3.3e-14)\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_proton_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_proton_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::electron_proton_mass_ratio<T>::value() ==\n      static_cast<T>(0.000544617021487));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::electron_proton_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::electron_proton_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(3.3e-14));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::electron_proton_mass_ratio<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::electron_proton_mass_ratio<\n                    T>::precision()));\n}\n\n// electron relative atomic mass\n// (0.000548579909065 \u00b1 1.6e-14)\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_relative_atomic_mass, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_relative_atomic_mass<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::electron_relative_atomic_mass<\n                 T>::value() == static_cast<T>(0.000548579909065));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_relative_atomic_mass<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::electron_relative_atomic_mass<\n                 T>::uncertainty() == static_cast<T>(1.6e-14));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_relative_atomic_mass<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::electron_relative_atomic_mass<\n          T>::precision()));\n}\n\n// electron-tau mass ratio\n// (0.000287585 \u00b1 1.9e-08)\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_tau_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_tau_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::electron_tau_mass_ratio<T>::value() ==\n      static_cast<T>(0.000287585));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::electron_tau_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::electron_tau_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(1.9e-08));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_tau_mass_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::electron_tau_mass_ratio<T>::precision()));\n}\n\n// electron to alpha particle mass ratio\n// (0.0001370933554787 \u00b1 4.5e-15)\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_to_alpha_particle_mass_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_to_alpha_particle_mass_ratio<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::electron_to_alpha_particle_mass_ratio<\n          T>::value() == static_cast<T>(0.0001370933554787));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_to_alpha_particle_mass_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::electron_to_alpha_particle_mass_ratio<\n          T>::uncertainty() == static_cast<T>(4.5e-15));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_to_alpha_particle_mass_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::electron_to_alpha_particle_mass_ratio<\n          T>::precision()));\n}\n\n// electron to shielded helion mag. mom. ratio\n// (864.058257 \u00b1 1e-05)\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_to_shielded_helion_mag_mom_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_to_shielded_helion_mag_mom_ratio<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::electron_to_shielded_helion_mag_mom_ratio<\n          T>::value() == static_cast<T>(864.058257));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_to_shielded_helion_mag_mom_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::electron_to_shielded_helion_mag_mom_ratio<\n          T>::uncertainty() == static_cast<T>(1e-05));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_to_shielded_helion_mag_mom_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::electron_to_shielded_helion_mag_mom_ratio<\n          T>::precision()));\n}\n\n// electron to shielded proton mag. mom. ratio\n// (-658.2275971 \u00b1 7.2e-06)\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_to_shielded_proton_mag_mom_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_to_shielded_proton_mag_mom_ratio<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::electron_to_shielded_proton_mag_mom_ratio<\n          T>::value() == static_cast<T>(-658.2275971));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_to_shielded_proton_mag_mom_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::electron_to_shielded_proton_mag_mom_ratio<\n          T>::uncertainty() == static_cast<T>(7.2e-06));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_to_shielded_proton_mag_mom_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::electron_to_shielded_proton_mag_mom_ratio<\n          T>::precision()));\n}\n\n// electron-triton mass ratio\n// (0.0001819200062251 \u00b1 9e-15)\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_triton_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_triton_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::electron_triton_mass_ratio<T>::value() ==\n      static_cast<T>(0.0001819200062251));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::electron_triton_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::electron_triton_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(9e-15));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::electron_triton_mass_ratio<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::electron_triton_mass_ratio<\n                    T>::precision()));\n}\n\n// electron volt\n// (1.602176634e-19 \u00b1 0.0) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_volt, T, test_types) {\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::electron_volt<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::electron_volt<T>::value() ==\n             static_cast<T>(1.602176634e-19));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_volt<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::electron_volt<T>::uncertainty() ==\n             static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_volt<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::electron_volt<T>::precision()));\n}\n\n// electron volt-atomic mass unit relationship\n// (1.07354410233e-09 \u00b1 3.2e-19) u\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_volt_atomic_mass_unit_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::\n          electron_volt_atomic_mass_unit_relationship<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::\n                 electron_volt_atomic_mass_unit_relationship<T>::value() ==\n             static_cast<T>(1.07354410233e-09));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::\n          electron_volt_atomic_mass_unit_relationship<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::\n          electron_volt_atomic_mass_unit_relationship<T>::uncertainty() ==\n      static_cast<T>(3.2e-19));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::\n          electron_volt_atomic_mass_unit_relationship<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::\n          electron_volt_atomic_mass_unit_relationship<T>::precision()));\n}\n\n// electron volt-hartree relationship\n// (0.036749322175655 \u00b1 7.1e-14) E_h\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_volt_hartree_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_volt_hartree_relationship<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::electron_volt_hartree_relationship<\n                 T>::value() == static_cast<T>(0.036749322175655));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_volt_hartree_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::electron_volt_hartree_relationship<\n                 T>::uncertainty() == static_cast<T>(7.1e-14));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_volt_hartree_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::electron_volt_hartree_relationship<\n          T>::precision()));\n}\n\n// electron volt-hertz relationship\n// (241798924200000.0 \u00b1 0.0) Hz\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_volt_hertz_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_volt_hertz_relationship<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::electron_volt_hertz_relationship<\n                 T>::value() == static_cast<T>(241798924200000.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_volt_hertz_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::electron_volt_hertz_relationship<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_volt_hertz_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::electron_volt_hertz_relationship<\n          T>::precision()));\n}\n\n// electron volt-inverse meter relationship\n// (806554.3937 \u00b1 0.0) m^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_volt_inverse_meter_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_volt_inverse_meter_relationship<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::electron_volt_inverse_meter_relationship<\n          T>::value() == static_cast<T>(806554.3937));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_volt_inverse_meter_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::electron_volt_inverse_meter_relationship<\n          T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_volt_inverse_meter_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::electron_volt_inverse_meter_relationship<\n          T>::precision()));\n}\n\n// electron volt-joule relationship\n// (1.602176634e-19 \u00b1 0.0) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_volt_joule_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_volt_joule_relationship<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::electron_volt_joule_relationship<\n                 T>::value() == static_cast<T>(1.602176634e-19));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_volt_joule_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::electron_volt_joule_relationship<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_volt_joule_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::electron_volt_joule_relationship<\n          T>::precision()));\n}\n\n// electron volt-kelvin relationship\n// (11604.51812 \u00b1 0.0) K\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_volt_kelvin_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_volt_kelvin_relationship<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::electron_volt_kelvin_relationship<\n                 T>::value() == static_cast<T>(11604.51812));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_volt_kelvin_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::electron_volt_kelvin_relationship<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_volt_kelvin_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::electron_volt_kelvin_relationship<\n          T>::precision()));\n}\n\n// electron volt-kilogram relationship\n// (1.782661921e-36 \u00b1 0.0) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_volt_kilogram_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_volt_kilogram_relationship<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::electron_volt_kilogram_relationship<\n          T>::value() == static_cast<T>(1.782661921e-36));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_volt_kilogram_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::electron_volt_kilogram_relationship<\n          T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::electron_volt_kilogram_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::electron_volt_kilogram_relationship<\n          T>::precision()));\n}\n\n// elementary charge\n// (1.602176634e-19 \u00b1 0.0) C\nBOOST_AUTO_TEST_CASE_TEMPLATE(elementary_charge, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::elementary_charge<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::elementary_charge<T>::value() ==\n             static_cast<T>(1.602176634e-19));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::elementary_charge<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::elementary_charge<T>::uncertainty() ==\n      static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::elementary_charge<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::elementary_charge<T>::precision()));\n}\n\n// elementary charge over h-bar\n// (1519267447000000.0 \u00b1 0.0) A J^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(elementary_charge_over_h_bar, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::elementary_charge_over_h_bar<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::elementary_charge_over_h_bar<\n                 T>::value() == static_cast<T>(1519267447000000.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::elementary_charge_over_h_bar<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::elementary_charge_over_h_bar<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::elementary_charge_over_h_bar<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::elementary_charge_over_h_bar<\n          T>::precision()));\n}\n\n// Faraday constant\n// (96485.33212 \u00b1 0.0) C mol^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(Faraday_constant, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Faraday_constant<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::Faraday_constant<T>::value() ==\n             static_cast<T>(96485.33212));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Faraday_constant<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::Faraday_constant<T>::uncertainty() ==\n      static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Faraday_constant<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::Faraday_constant<T>::precision()));\n}\n\n// Fermi coupling constant\n// (1.1663787e-05 \u00b1 6e-12) GeV^-2\nBOOST_AUTO_TEST_CASE_TEMPLATE(Fermi_coupling_constant, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Fermi_coupling_constant<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::Fermi_coupling_constant<T>::value() ==\n      static_cast<T>(1.1663787e-05));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::Fermi_coupling_constant<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::Fermi_coupling_constant<\n                 T>::uncertainty() == static_cast<T>(6e-12));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Fermi_coupling_constant<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::Fermi_coupling_constant<T>::precision()));\n}\n\n// fine-structure constant\n// (0.0072973525693 \u00b1 1.1e-12)\nBOOST_AUTO_TEST_CASE_TEMPLATE(fine_structure_constant, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::fine_structure_constant<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::fine_structure_constant<T>::value() ==\n      static_cast<T>(0.0072973525693));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::fine_structure_constant<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::fine_structure_constant<\n                 T>::uncertainty() == static_cast<T>(1.1e-12));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::fine_structure_constant<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::fine_structure_constant<T>::precision()));\n}\n\n// first radiation constant\n// (3.741771852e-16 \u00b1 0.0) W m^2\nBOOST_AUTO_TEST_CASE_TEMPLATE(first_radiation_constant, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::first_radiation_constant<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::first_radiation_constant<T>::value() ==\n      static_cast<T>(3.741771852e-16));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::first_radiation_constant<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::first_radiation_constant<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::first_radiation_constant<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::first_radiation_constant<\n                    T>::precision()));\n}\n\n// first radiation constant for spectral radiance\n// (1.191042972e-16 \u00b1 0.0) W m^2 sr^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(first_radiation_constant_for_spectral_radiance, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::\n          first_radiation_constant_for_spectral_radiance<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::\n                 first_radiation_constant_for_spectral_radiance<T>::value() ==\n             static_cast<T>(1.191042972e-16));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::\n          first_radiation_constant_for_spectral_radiance<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::\n          first_radiation_constant_for_spectral_radiance<T>::uncertainty() ==\n      static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::\n          first_radiation_constant_for_spectral_radiance<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::\n          first_radiation_constant_for_spectral_radiance<T>::precision()));\n}\n\n// hartree-atomic mass unit relationship\n// (2.92126232205e-08 \u00b1 8.8e-18) u\nBOOST_AUTO_TEST_CASE_TEMPLATE(hartree_atomic_mass_unit_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::hartree_atomic_mass_unit_relationship<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::hartree_atomic_mass_unit_relationship<\n          T>::value() == static_cast<T>(2.92126232205e-08));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::hartree_atomic_mass_unit_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::hartree_atomic_mass_unit_relationship<\n          T>::uncertainty() == static_cast<T>(8.8e-18));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::hartree_atomic_mass_unit_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::hartree_atomic_mass_unit_relationship<\n          T>::precision()));\n}\n\n// hartree-electron volt relationship\n// (27.211386245988 \u00b1 5.3e-11) eV\nBOOST_AUTO_TEST_CASE_TEMPLATE(hartree_electron_volt_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::hartree_electron_volt_relationship<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::hartree_electron_volt_relationship<\n                 T>::value() == static_cast<T>(27.211386245988));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::hartree_electron_volt_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::hartree_electron_volt_relationship<\n                 T>::uncertainty() == static_cast<T>(5.3e-11));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::hartree_electron_volt_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::hartree_electron_volt_relationship<\n          T>::precision()));\n}\n\n// Hartree energy\n// (4.3597447222071e-18 \u00b1 8.5e-30) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(Hartree_energy, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Hartree_energy<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::Hartree_energy<T>::value() ==\n             static_cast<T>(4.3597447222071e-18));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Hartree_energy<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::Hartree_energy<T>::uncertainty() ==\n             static_cast<T>(8.5e-30));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Hartree_energy<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::Hartree_energy<T>::precision()));\n}\n\n// Hartree energy in eV\n// (27.211386245988 \u00b1 5.3e-11) eV\nBOOST_AUTO_TEST_CASE_TEMPLATE(Hartree_energy_in_eV, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Hartree_energy_in_eV<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::Hartree_energy_in_eV<T>::value() ==\n             static_cast<T>(27.211386245988));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Hartree_energy_in_eV<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::Hartree_energy_in_eV<T>::uncertainty() ==\n      static_cast<T>(5.3e-11));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Hartree_energy_in_eV<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::Hartree_energy_in_eV<T>::precision()));\n}\n\n// hartree-hertz relationship\n// (6579683920502000.0 \u00b1 13000.0) Hz\nBOOST_AUTO_TEST_CASE_TEMPLATE(hartree_hertz_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::hartree_hertz_relationship<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::hartree_hertz_relationship<T>::value() ==\n      static_cast<T>(6579683920502000.0));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::hartree_hertz_relationship<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::hartree_hertz_relationship<\n                 T>::uncertainty() == static_cast<T>(13000.0));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::hartree_hertz_relationship<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::hartree_hertz_relationship<\n                    T>::precision()));\n}\n\n// hartree-inverse meter relationship\n// (21947463.13632 \u00b1 4.3e-05) m^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(hartree_inverse_meter_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::hartree_inverse_meter_relationship<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::hartree_inverse_meter_relationship<\n                 T>::value() == static_cast<T>(21947463.13632));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::hartree_inverse_meter_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::hartree_inverse_meter_relationship<\n                 T>::uncertainty() == static_cast<T>(4.3e-05));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::hartree_inverse_meter_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::hartree_inverse_meter_relationship<\n          T>::precision()));\n}\n\n// hartree-joule relationship\n// (4.3597447222071e-18 \u00b1 8.5e-30) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(hartree_joule_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::hartree_joule_relationship<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::hartree_joule_relationship<T>::value() ==\n      static_cast<T>(4.3597447222071e-18));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::hartree_joule_relationship<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::hartree_joule_relationship<\n                 T>::uncertainty() == static_cast<T>(8.5e-30));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::hartree_joule_relationship<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::hartree_joule_relationship<\n                    T>::precision()));\n}\n\n// hartree-kelvin relationship\n// (315775.02480407 \u00b1 6.1e-07) K\nBOOST_AUTO_TEST_CASE_TEMPLATE(hartree_kelvin_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::hartree_kelvin_relationship<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::hartree_kelvin_relationship<T>::value() ==\n      static_cast<T>(315775.02480407));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::hartree_kelvin_relationship<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::hartree_kelvin_relationship<\n                 T>::uncertainty() == static_cast<T>(6.1e-07));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::hartree_kelvin_relationship<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::hartree_kelvin_relationship<\n                    T>::precision()));\n}\n\n// hartree-kilogram relationship\n// (4.8508702095432e-35 \u00b1 9.4e-47) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(hartree_kilogram_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::hartree_kilogram_relationship<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::hartree_kilogram_relationship<\n                 T>::value() == static_cast<T>(4.8508702095432e-35));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::hartree_kilogram_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::hartree_kilogram_relationship<\n                 T>::uncertainty() == static_cast<T>(9.4e-47));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::hartree_kilogram_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::hartree_kilogram_relationship<\n          T>::precision()));\n}\n\n// helion-electron mass ratio\n// (5495.88528007 \u00b1 2.4e-07)\nBOOST_AUTO_TEST_CASE_TEMPLATE(helion_electron_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::helion_electron_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::helion_electron_mass_ratio<T>::value() ==\n      static_cast<T>(5495.88528007));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::helion_electron_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::helion_electron_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(2.4e-07));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::helion_electron_mass_ratio<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::helion_electron_mass_ratio<\n                    T>::precision()));\n}\n\n// helion g factor\n// (-4.255250615 \u00b1 5e-08)\nBOOST_AUTO_TEST_CASE_TEMPLATE(helion_g_factor, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::helion_g_factor<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::helion_g_factor<T>::value() ==\n             static_cast<T>(-4.255250615));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::helion_g_factor<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::helion_g_factor<T>::uncertainty() ==\n      static_cast<T>(5e-08));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::helion_g_factor<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::helion_g_factor<T>::precision()));\n}\n\n// helion mag. mom.\n// (-1.074617532e-26 \u00b1 1.3e-34) J T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(helion_mag_mom, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::helion_mag_mom<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::helion_mag_mom<T>::value() ==\n             static_cast<T>(-1.074617532e-26));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::helion_mag_mom<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::helion_mag_mom<T>::uncertainty() ==\n             static_cast<T>(1.3e-34));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::helion_mag_mom<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::helion_mag_mom<T>::precision()));\n}\n\n// helion mag. mom. to Bohr magneton ratio\n// (-0.001158740958 \u00b1 1.4e-11)\nBOOST_AUTO_TEST_CASE_TEMPLATE(helion_mag_mom_to_Bohr_magneton_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::helion_mag_mom_to_Bohr_magneton_ratio<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::helion_mag_mom_to_Bohr_magneton_ratio<\n          T>::value() == static_cast<T>(-0.001158740958));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::helion_mag_mom_to_Bohr_magneton_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::helion_mag_mom_to_Bohr_magneton_ratio<\n          T>::uncertainty() == static_cast<T>(1.4e-11));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::helion_mag_mom_to_Bohr_magneton_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::helion_mag_mom_to_Bohr_magneton_ratio<\n          T>::precision()));\n}\n\n// helion mag. mom. to nuclear magneton ratio\n// (-2.127625307 \u00b1 2.5e-08)\nBOOST_AUTO_TEST_CASE_TEMPLATE(helion_mag_mom_to_nuclear_magneton_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::helion_mag_mom_to_nuclear_magneton_ratio<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::helion_mag_mom_to_nuclear_magneton_ratio<\n          T>::value() == static_cast<T>(-2.127625307));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::helion_mag_mom_to_nuclear_magneton_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::helion_mag_mom_to_nuclear_magneton_ratio<\n          T>::uncertainty() == static_cast<T>(2.5e-08));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::helion_mag_mom_to_nuclear_magneton_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::helion_mag_mom_to_nuclear_magneton_ratio<\n          T>::precision()));\n}\n\n// helion mass\n// (5.0064127796e-27 \u00b1 1.5e-36) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(helion_mass, T, test_types) {\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::helion_mass<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::helion_mass<T>::value() ==\n             static_cast<T>(5.0064127796e-27));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::helion_mass<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::helion_mass<T>::uncertainty() ==\n             static_cast<T>(1.5e-36));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::helion_mass<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::helion_mass<T>::precision()));\n}\n\n// helion mass energy equivalent\n// (4.4995394125e-10 \u00b1 1.4e-19) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(helion_mass_energy_equivalent, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::helion_mass_energy_equivalent<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::helion_mass_energy_equivalent<\n                 T>::value() == static_cast<T>(4.4995394125e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::helion_mass_energy_equivalent<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::helion_mass_energy_equivalent<\n                 T>::uncertainty() == static_cast<T>(1.4e-19));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::helion_mass_energy_equivalent<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::helion_mass_energy_equivalent<\n          T>::precision()));\n}\n\n// helion mass energy equivalent in MeV\n// (2808.39160743 \u00b1 8.5e-07) MeV\nBOOST_AUTO_TEST_CASE_TEMPLATE(helion_mass_energy_equivalent_in_MeV, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::helion_mass_energy_equivalent_in_MeV<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::helion_mass_energy_equivalent_in_MeV<\n          T>::value() == static_cast<T>(2808.39160743));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::helion_mass_energy_equivalent_in_MeV<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::helion_mass_energy_equivalent_in_MeV<\n          T>::uncertainty() == static_cast<T>(8.5e-07));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::helion_mass_energy_equivalent_in_MeV<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::helion_mass_energy_equivalent_in_MeV<\n          T>::precision()));\n}\n\n// helion mass in u\n// (3.014932247175 \u00b1 9.7e-11) u\nBOOST_AUTO_TEST_CASE_TEMPLATE(helion_mass_in_u, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::helion_mass_in_u<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::helion_mass_in_u<T>::value() ==\n             static_cast<T>(3.014932247175));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::helion_mass_in_u<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::helion_mass_in_u<T>::uncertainty() ==\n      static_cast<T>(9.7e-11));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::helion_mass_in_u<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::helion_mass_in_u<T>::precision()));\n}\n\n// helion molar mass\n// (0.00301493224613 \u00b1 9.1e-13) kg mol^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(helion_molar_mass, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::helion_molar_mass<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::helion_molar_mass<T>::value() ==\n             static_cast<T>(0.00301493224613));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::helion_molar_mass<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::helion_molar_mass<T>::uncertainty() ==\n      static_cast<T>(9.1e-13));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::helion_molar_mass<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::helion_molar_mass<T>::precision()));\n}\n\n// helion-proton mass ratio\n// (2.99315267167 \u00b1 1.3e-10)\nBOOST_AUTO_TEST_CASE_TEMPLATE(helion_proton_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::helion_proton_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::helion_proton_mass_ratio<T>::value() ==\n      static_cast<T>(2.99315267167));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::helion_proton_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::helion_proton_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(1.3e-10));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::helion_proton_mass_ratio<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::helion_proton_mass_ratio<\n                    T>::precision()));\n}\n\n// helion relative atomic mass\n// (3.014932247175 \u00b1 9.7e-11)\nBOOST_AUTO_TEST_CASE_TEMPLATE(helion_relative_atomic_mass, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::helion_relative_atomic_mass<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::helion_relative_atomic_mass<T>::value() ==\n      static_cast<T>(3.014932247175));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::helion_relative_atomic_mass<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::helion_relative_atomic_mass<\n                 T>::uncertainty() == static_cast<T>(9.7e-11));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::helion_relative_atomic_mass<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::helion_relative_atomic_mass<\n                    T>::precision()));\n}\n\n// helion shielding shift\n// (5.996743e-05 \u00b1 1e-10)\nBOOST_AUTO_TEST_CASE_TEMPLATE(helion_shielding_shift, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::helion_shielding_shift<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::helion_shielding_shift<T>::value() ==\n      static_cast<T>(5.996743e-05));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::helion_shielding_shift<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::helion_shielding_shift<\n                 T>::uncertainty() == static_cast<T>(1e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::helion_shielding_shift<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::helion_shielding_shift<T>::precision()));\n}\n\n// hertz-atomic mass unit relationship\n// (4.4398216652e-24 \u00b1 1.3e-33) u\nBOOST_AUTO_TEST_CASE_TEMPLATE(hertz_atomic_mass_unit_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::hertz_atomic_mass_unit_relationship<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::hertz_atomic_mass_unit_relationship<\n          T>::value() == static_cast<T>(4.4398216652e-24));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::hertz_atomic_mass_unit_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::hertz_atomic_mass_unit_relationship<\n          T>::uncertainty() == static_cast<T>(1.3e-33));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::hertz_atomic_mass_unit_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::hertz_atomic_mass_unit_relationship<\n          T>::precision()));\n}\n\n// hertz-electron volt relationship\n// (4.135667696e-15 \u00b1 0.0) eV\nBOOST_AUTO_TEST_CASE_TEMPLATE(hertz_electron_volt_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::hertz_electron_volt_relationship<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::hertz_electron_volt_relationship<\n                 T>::value() == static_cast<T>(4.135667696e-15));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::hertz_electron_volt_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::hertz_electron_volt_relationship<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::hertz_electron_volt_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::hertz_electron_volt_relationship<\n          T>::precision()));\n}\n\n// hertz-hartree relationship\n// (1.519829846057e-16 \u00b1 2.9e-28) E_h\nBOOST_AUTO_TEST_CASE_TEMPLATE(hertz_hartree_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::hertz_hartree_relationship<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::hertz_hartree_relationship<T>::value() ==\n      static_cast<T>(1.519829846057e-16));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::hertz_hartree_relationship<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::hertz_hartree_relationship<\n                 T>::uncertainty() == static_cast<T>(2.9e-28));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::hertz_hartree_relationship<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::hertz_hartree_relationship<\n                    T>::precision()));\n}\n\n// hertz-inverse meter relationship\n// (3.335640951e-09 \u00b1 0.0) m^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(hertz_inverse_meter_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::hertz_inverse_meter_relationship<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::hertz_inverse_meter_relationship<\n                 T>::value() == static_cast<T>(3.335640951e-09));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::hertz_inverse_meter_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::hertz_inverse_meter_relationship<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::hertz_inverse_meter_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::hertz_inverse_meter_relationship<\n          T>::precision()));\n}\n\n// hertz-joule relationship\n// (6.62607015e-34 \u00b1 0.0) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(hertz_joule_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::hertz_joule_relationship<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::hertz_joule_relationship<T>::value() ==\n      static_cast<T>(6.62607015e-34));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::hertz_joule_relationship<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::hertz_joule_relationship<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::hertz_joule_relationship<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::hertz_joule_relationship<\n                    T>::precision()));\n}\n\n// hertz-kelvin relationship\n// (4.799243073e-11 \u00b1 0.0) K\nBOOST_AUTO_TEST_CASE_TEMPLATE(hertz_kelvin_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::hertz_kelvin_relationship<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::hertz_kelvin_relationship<T>::value() ==\n      static_cast<T>(4.799243073e-11));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::hertz_kelvin_relationship<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::hertz_kelvin_relationship<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::hertz_kelvin_relationship<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::hertz_kelvin_relationship<\n                    T>::precision()));\n}\n\n// hertz-kilogram relationship\n// (7.372497323e-51 \u00b1 0.0) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(hertz_kilogram_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::hertz_kilogram_relationship<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::hertz_kilogram_relationship<T>::value() ==\n      static_cast<T>(7.372497323e-51));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::hertz_kilogram_relationship<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::hertz_kilogram_relationship<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::hertz_kilogram_relationship<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::hertz_kilogram_relationship<\n                    T>::precision()));\n}\n\n// hyperfine transition frequency of Cs-133\n// (9192631770.0 \u00b1 0.0) Hz\nBOOST_AUTO_TEST_CASE_TEMPLATE(hyperfine_transition_frequency_of_Cs_133, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::hyperfine_transition_frequency_of_Cs_133<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::hyperfine_transition_frequency_of_Cs_133<\n          T>::value() == static_cast<T>(9192631770.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::hyperfine_transition_frequency_of_Cs_133<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::hyperfine_transition_frequency_of_Cs_133<\n          T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::hyperfine_transition_frequency_of_Cs_133<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::hyperfine_transition_frequency_of_Cs_133<\n          T>::precision()));\n}\n\n// inverse fine-structure constant\n// (137.035999084 \u00b1 2.1e-08)\nBOOST_AUTO_TEST_CASE_TEMPLATE(inverse_fine_structure_constant, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::inverse_fine_structure_constant<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::inverse_fine_structure_constant<\n                 T>::value() == static_cast<T>(137.035999084));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::inverse_fine_structure_constant<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::inverse_fine_structure_constant<\n                 T>::uncertainty() == static_cast<T>(2.1e-08));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::inverse_fine_structure_constant<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::inverse_fine_structure_constant<\n          T>::precision()));\n}\n\n// inverse meter-atomic mass unit relationship\n// (1.3310250501e-15 \u00b1 4e-25) u\nBOOST_AUTO_TEST_CASE_TEMPLATE(inverse_meter_atomic_mass_unit_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::\n          inverse_meter_atomic_mass_unit_relationship<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::\n                 inverse_meter_atomic_mass_unit_relationship<T>::value() ==\n             static_cast<T>(1.3310250501e-15));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::\n          inverse_meter_atomic_mass_unit_relationship<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::\n          inverse_meter_atomic_mass_unit_relationship<T>::uncertainty() ==\n      static_cast<T>(4e-25));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::\n          inverse_meter_atomic_mass_unit_relationship<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::\n          inverse_meter_atomic_mass_unit_relationship<T>::precision()));\n}\n\n// inverse meter-electron volt relationship\n// (1.239841984e-06 \u00b1 0.0) eV\nBOOST_AUTO_TEST_CASE_TEMPLATE(inverse_meter_electron_volt_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::inverse_meter_electron_volt_relationship<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::inverse_meter_electron_volt_relationship<\n          T>::value() == static_cast<T>(1.239841984e-06));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::inverse_meter_electron_volt_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::inverse_meter_electron_volt_relationship<\n          T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::inverse_meter_electron_volt_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::inverse_meter_electron_volt_relationship<\n          T>::precision()));\n}\n\n// inverse meter-hartree relationship\n// (4.556335252912e-08 \u00b1 8.8e-20) E_h\nBOOST_AUTO_TEST_CASE_TEMPLATE(inverse_meter_hartree_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::inverse_meter_hartree_relationship<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::inverse_meter_hartree_relationship<\n                 T>::value() == static_cast<T>(4.556335252912e-08));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::inverse_meter_hartree_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::inverse_meter_hartree_relationship<\n                 T>::uncertainty() == static_cast<T>(8.8e-20));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::inverse_meter_hartree_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::inverse_meter_hartree_relationship<\n          T>::precision()));\n}\n\n// inverse meter-hertz relationship\n// (299792458.0 \u00b1 0.0) Hz\nBOOST_AUTO_TEST_CASE_TEMPLATE(inverse_meter_hertz_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::inverse_meter_hertz_relationship<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::inverse_meter_hertz_relationship<\n                 T>::value() == static_cast<T>(299792458.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::inverse_meter_hertz_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::inverse_meter_hertz_relationship<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::inverse_meter_hertz_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::inverse_meter_hertz_relationship<\n          T>::precision()));\n}\n\n// inverse meter-joule relationship\n// (1.986445857e-25 \u00b1 0.0) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(inverse_meter_joule_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::inverse_meter_joule_relationship<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::inverse_meter_joule_relationship<\n                 T>::value() == static_cast<T>(1.986445857e-25));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::inverse_meter_joule_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::inverse_meter_joule_relationship<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::inverse_meter_joule_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::inverse_meter_joule_relationship<\n          T>::precision()));\n}\n\n// inverse meter-kelvin relationship\n// (0.01438776877 \u00b1 0.0) K\nBOOST_AUTO_TEST_CASE_TEMPLATE(inverse_meter_kelvin_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::inverse_meter_kelvin_relationship<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::inverse_meter_kelvin_relationship<\n                 T>::value() == static_cast<T>(0.01438776877));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::inverse_meter_kelvin_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::inverse_meter_kelvin_relationship<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::inverse_meter_kelvin_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::inverse_meter_kelvin_relationship<\n          T>::precision()));\n}\n\n// inverse meter-kilogram relationship\n// (2.210219094e-42 \u00b1 0.0) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(inverse_meter_kilogram_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::inverse_meter_kilogram_relationship<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::inverse_meter_kilogram_relationship<\n          T>::value() == static_cast<T>(2.210219094e-42));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::inverse_meter_kilogram_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::inverse_meter_kilogram_relationship<\n          T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::inverse_meter_kilogram_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::inverse_meter_kilogram_relationship<\n          T>::precision()));\n}\n\n// inverse of conductance quantum\n// (12906.40372 \u00b1 0.0) ohm\nBOOST_AUTO_TEST_CASE_TEMPLATE(inverse_of_conductance_quantum, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::inverse_of_conductance_quantum<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::inverse_of_conductance_quantum<\n                 T>::value() == static_cast<T>(12906.40372));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::inverse_of_conductance_quantum<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::inverse_of_conductance_quantum<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::inverse_of_conductance_quantum<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::inverse_of_conductance_quantum<\n          T>::precision()));\n}\n\n// Josephson constant\n// (483597848400000.0 \u00b1 0.0) Hz V^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(Josephson_constant, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Josephson_constant<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::Josephson_constant<T>::value() ==\n             static_cast<T>(483597848400000.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Josephson_constant<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::Josephson_constant<T>::uncertainty() ==\n      static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Josephson_constant<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::Josephson_constant<T>::precision()));\n}\n\n// joule-atomic mass unit relationship\n// (6700535256.5 \u00b1 2.0) u\nBOOST_AUTO_TEST_CASE_TEMPLATE(joule_atomic_mass_unit_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::joule_atomic_mass_unit_relationship<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::joule_atomic_mass_unit_relationship<\n          T>::value() == static_cast<T>(6700535256.5));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::joule_atomic_mass_unit_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::joule_atomic_mass_unit_relationship<\n          T>::uncertainty() == static_cast<T>(2.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::joule_atomic_mass_unit_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::joule_atomic_mass_unit_relationship<\n          T>::precision()));\n}\n\n// joule-electron volt relationship\n// (6.241509074e+18 \u00b1 0.0) eV\nBOOST_AUTO_TEST_CASE_TEMPLATE(joule_electron_volt_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::joule_electron_volt_relationship<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::joule_electron_volt_relationship<\n                 T>::value() == static_cast<T>(6.241509074e+18));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::joule_electron_volt_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::joule_electron_volt_relationship<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::joule_electron_volt_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::joule_electron_volt_relationship<\n          T>::precision()));\n}\n\n// joule-hartree relationship\n// (2.2937122783963e+17 \u00b1 450000.0) E_h\nBOOST_AUTO_TEST_CASE_TEMPLATE(joule_hartree_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::joule_hartree_relationship<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::joule_hartree_relationship<T>::value() ==\n      static_cast<T>(2.2937122783963e+17));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::joule_hartree_relationship<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::joule_hartree_relationship<\n                 T>::uncertainty() == static_cast<T>(450000.0));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::joule_hartree_relationship<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::joule_hartree_relationship<\n                    T>::precision()));\n}\n\n// joule-hertz relationship\n// (1.509190179e+33 \u00b1 0.0) Hz\nBOOST_AUTO_TEST_CASE_TEMPLATE(joule_hertz_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::joule_hertz_relationship<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::joule_hertz_relationship<T>::value() ==\n      static_cast<T>(1.509190179e+33));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::joule_hertz_relationship<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::joule_hertz_relationship<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::joule_hertz_relationship<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::joule_hertz_relationship<\n                    T>::precision()));\n}\n\n// joule-inverse meter relationship\n// (5.034116567e+24 \u00b1 0.0) m^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(joule_inverse_meter_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::joule_inverse_meter_relationship<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::joule_inverse_meter_relationship<\n                 T>::value() == static_cast<T>(5.034116567e+24));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::joule_inverse_meter_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::joule_inverse_meter_relationship<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::joule_inverse_meter_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::joule_inverse_meter_relationship<\n          T>::precision()));\n}\n\n// joule-kelvin relationship\n// (7.242970516e+22 \u00b1 0.0) K\nBOOST_AUTO_TEST_CASE_TEMPLATE(joule_kelvin_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::joule_kelvin_relationship<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::joule_kelvin_relationship<T>::value() ==\n      static_cast<T>(7.242970516e+22));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::joule_kelvin_relationship<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::joule_kelvin_relationship<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::joule_kelvin_relationship<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::joule_kelvin_relationship<\n                    T>::precision()));\n}\n\n// joule-kilogram relationship\n// (1.112650056e-17 \u00b1 0.0) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(joule_kilogram_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::joule_kilogram_relationship<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::joule_kilogram_relationship<T>::value() ==\n      static_cast<T>(1.112650056e-17));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::joule_kilogram_relationship<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::joule_kilogram_relationship<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::joule_kilogram_relationship<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::joule_kilogram_relationship<\n                    T>::precision()));\n}\n\n// kelvin-atomic mass unit relationship\n// (9.2510873014e-14 \u00b1 2.8e-23) u\nBOOST_AUTO_TEST_CASE_TEMPLATE(kelvin_atomic_mass_unit_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::kelvin_atomic_mass_unit_relationship<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::kelvin_atomic_mass_unit_relationship<\n          T>::value() == static_cast<T>(9.2510873014e-14));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::kelvin_atomic_mass_unit_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::kelvin_atomic_mass_unit_relationship<\n          T>::uncertainty() == static_cast<T>(2.8e-23));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::kelvin_atomic_mass_unit_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::kelvin_atomic_mass_unit_relationship<\n          T>::precision()));\n}\n\n// kelvin-electron volt relationship\n// (8.617333262e-05 \u00b1 0.0) eV\nBOOST_AUTO_TEST_CASE_TEMPLATE(kelvin_electron_volt_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::kelvin_electron_volt_relationship<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::kelvin_electron_volt_relationship<\n                 T>::value() == static_cast<T>(8.617333262e-05));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::kelvin_electron_volt_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::kelvin_electron_volt_relationship<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::kelvin_electron_volt_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::kelvin_electron_volt_relationship<\n          T>::precision()));\n}\n\n// kelvin-hartree relationship\n// (3.1668115634556e-06 \u00b1 6.1e-18) E_h\nBOOST_AUTO_TEST_CASE_TEMPLATE(kelvin_hartree_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::kelvin_hartree_relationship<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::kelvin_hartree_relationship<T>::value() ==\n      static_cast<T>(3.1668115634556e-06));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::kelvin_hartree_relationship<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::kelvin_hartree_relationship<\n                 T>::uncertainty() == static_cast<T>(6.1e-18));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::kelvin_hartree_relationship<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::kelvin_hartree_relationship<\n                    T>::precision()));\n}\n\n// kelvin-hertz relationship\n// (20836619120.0 \u00b1 0.0) Hz\nBOOST_AUTO_TEST_CASE_TEMPLATE(kelvin_hertz_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::kelvin_hertz_relationship<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::kelvin_hertz_relationship<T>::value() ==\n      static_cast<T>(20836619120.0));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::kelvin_hertz_relationship<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::kelvin_hertz_relationship<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::kelvin_hertz_relationship<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::kelvin_hertz_relationship<\n                    T>::precision()));\n}\n\n// kelvin-inverse meter relationship\n// (69.50348004 \u00b1 0.0) m^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(kelvin_inverse_meter_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::kelvin_inverse_meter_relationship<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::kelvin_inverse_meter_relationship<\n                 T>::value() == static_cast<T>(69.50348004));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::kelvin_inverse_meter_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::kelvin_inverse_meter_relationship<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::kelvin_inverse_meter_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::kelvin_inverse_meter_relationship<\n          T>::precision()));\n}\n\n// kelvin-joule relationship\n// (1.380649e-23 \u00b1 0.0) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(kelvin_joule_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::kelvin_joule_relationship<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::kelvin_joule_relationship<T>::value() ==\n      static_cast<T>(1.380649e-23));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::kelvin_joule_relationship<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::kelvin_joule_relationship<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::kelvin_joule_relationship<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::kelvin_joule_relationship<\n                    T>::precision()));\n}\n\n// kelvin-kilogram relationship\n// (1.536179187e-40 \u00b1 0.0) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(kelvin_kilogram_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::kelvin_kilogram_relationship<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::kelvin_kilogram_relationship<\n                 T>::value() == static_cast<T>(1.536179187e-40));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::kelvin_kilogram_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::kelvin_kilogram_relationship<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::kelvin_kilogram_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::kelvin_kilogram_relationship<\n          T>::precision()));\n}\n\n// kilogram-atomic mass unit relationship\n// (6.0221407621e+26 \u00b1 1.8e+17) u\nBOOST_AUTO_TEST_CASE_TEMPLATE(kilogram_atomic_mass_unit_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::kilogram_atomic_mass_unit_relationship<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::kilogram_atomic_mass_unit_relationship<\n          T>::value() == static_cast<T>(6.0221407621e+26));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::kilogram_atomic_mass_unit_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::kilogram_atomic_mass_unit_relationship<\n          T>::uncertainty() == static_cast<T>(1.8e+17));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::kilogram_atomic_mass_unit_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::kilogram_atomic_mass_unit_relationship<\n          T>::precision()));\n}\n\n// kilogram-electron volt relationship\n// (5.609588603e+35 \u00b1 0.0) eV\nBOOST_AUTO_TEST_CASE_TEMPLATE(kilogram_electron_volt_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::kilogram_electron_volt_relationship<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::kilogram_electron_volt_relationship<\n          T>::value() == static_cast<T>(5.609588603e+35));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::kilogram_electron_volt_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::kilogram_electron_volt_relationship<\n          T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::kilogram_electron_volt_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::kilogram_electron_volt_relationship<\n          T>::precision()));\n}\n\n// kilogram-hartree relationship\n// (2.0614857887409e+34 \u00b1 4e+22) E_h\nBOOST_AUTO_TEST_CASE_TEMPLATE(kilogram_hartree_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::kilogram_hartree_relationship<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::kilogram_hartree_relationship<\n                 T>::value() == static_cast<T>(2.0614857887409e+34));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::kilogram_hartree_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::kilogram_hartree_relationship<\n                 T>::uncertainty() == static_cast<T>(4e+22));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::kilogram_hartree_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::kilogram_hartree_relationship<\n          T>::precision()));\n}\n\n// kilogram-hertz relationship\n// (1.356392489e+50 \u00b1 0.0) Hz\nBOOST_AUTO_TEST_CASE_TEMPLATE(kilogram_hertz_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::kilogram_hertz_relationship<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::kilogram_hertz_relationship<T>::value() ==\n      static_cast<T>(1.356392489e+50));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::kilogram_hertz_relationship<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::kilogram_hertz_relationship<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::kilogram_hertz_relationship<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::kilogram_hertz_relationship<\n                    T>::precision()));\n}\n\n// kilogram-inverse meter relationship\n// (4.524438335e+41 \u00b1 0.0) m^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(kilogram_inverse_meter_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::kilogram_inverse_meter_relationship<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::kilogram_inverse_meter_relationship<\n          T>::value() == static_cast<T>(4.524438335e+41));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::kilogram_inverse_meter_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::kilogram_inverse_meter_relationship<\n          T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::kilogram_inverse_meter_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::kilogram_inverse_meter_relationship<\n          T>::precision()));\n}\n\n// kilogram-joule relationship\n// (8.987551787e+16 \u00b1 0.0) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(kilogram_joule_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::kilogram_joule_relationship<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::kilogram_joule_relationship<T>::value() ==\n      static_cast<T>(8.987551787e+16));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::kilogram_joule_relationship<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::kilogram_joule_relationship<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::kilogram_joule_relationship<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::kilogram_joule_relationship<\n                    T>::precision()));\n}\n\n// kilogram-kelvin relationship\n// (6.50965726e+39 \u00b1 0.0) K\nBOOST_AUTO_TEST_CASE_TEMPLATE(kilogram_kelvin_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::kilogram_kelvin_relationship<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::kilogram_kelvin_relationship<\n                 T>::value() == static_cast<T>(6.50965726e+39));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::kilogram_kelvin_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::kilogram_kelvin_relationship<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::kilogram_kelvin_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::kilogram_kelvin_relationship<\n          T>::precision()));\n}\n\n// lattice parameter of silicon\n// (5.431020511e-10 \u00b1 8.9e-18) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(lattice_parameter_of_silicon, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::lattice_parameter_of_silicon<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::lattice_parameter_of_silicon<\n                 T>::value() == static_cast<T>(5.431020511e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::lattice_parameter_of_silicon<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::lattice_parameter_of_silicon<\n                 T>::uncertainty() == static_cast<T>(8.9e-18));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::lattice_parameter_of_silicon<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::lattice_parameter_of_silicon<\n          T>::precision()));\n}\n\n// lattice spacing of ideal Si (220)\n// (1.920155716e-10 \u00b1 3.2e-18) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(lattice_spacing_of_ideal_Si_220, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::lattice_spacing_of_ideal_Si_220<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::lattice_spacing_of_ideal_Si_220<\n                 T>::value() == static_cast<T>(1.920155716e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::lattice_spacing_of_ideal_Si_220<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::lattice_spacing_of_ideal_Si_220<\n                 T>::uncertainty() == static_cast<T>(3.2e-18));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::lattice_spacing_of_ideal_Si_220<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::lattice_spacing_of_ideal_Si_220<\n          T>::precision()));\n}\n\n// Loschmidt constant (273.15 K, 100 kPa)\n// (2.651645804e+25 \u00b1 0.0) m^-3\nBOOST_AUTO_TEST_CASE_TEMPLATE(Loschmidt_constant_27315_K_100_kPa, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Loschmidt_constant_27315_K_100_kPa<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::Loschmidt_constant_27315_K_100_kPa<\n                 T>::value() == static_cast<T>(2.651645804e+25));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Loschmidt_constant_27315_K_100_kPa<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::Loschmidt_constant_27315_K_100_kPa<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Loschmidt_constant_27315_K_100_kPa<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::Loschmidt_constant_27315_K_100_kPa<\n          T>::precision()));\n}\n\n// Loschmidt constant (273.15 K, 101.325 kPa)\n// (2.686780111e+25 \u00b1 0.0) m^-3\nBOOST_AUTO_TEST_CASE_TEMPLATE(Loschmidt_constant_27315_K_101325_kPa, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Loschmidt_constant_27315_K_101325_kPa<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::Loschmidt_constant_27315_K_101325_kPa<\n          T>::value() == static_cast<T>(2.686780111e+25));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Loschmidt_constant_27315_K_101325_kPa<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::Loschmidt_constant_27315_K_101325_kPa<\n          T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Loschmidt_constant_27315_K_101325_kPa<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::Loschmidt_constant_27315_K_101325_kPa<\n          T>::precision()));\n}\n\n// luminous efficacy\n// (683.0 \u00b1 0.0) lm W^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(luminous_efficacy, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::luminous_efficacy<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::luminous_efficacy<T>::value() ==\n             static_cast<T>(683.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::luminous_efficacy<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::luminous_efficacy<T>::uncertainty() ==\n      static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::luminous_efficacy<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::luminous_efficacy<T>::precision()));\n}\n\n// mag. flux quantum\n// (2.067833848e-15 \u00b1 0.0) Wb\nBOOST_AUTO_TEST_CASE_TEMPLATE(mag_flux_quantum, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::mag_flux_quantum<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::mag_flux_quantum<T>::value() ==\n             static_cast<T>(2.067833848e-15));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::mag_flux_quantum<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::mag_flux_quantum<T>::uncertainty() ==\n      static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::mag_flux_quantum<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::mag_flux_quantum<T>::precision()));\n}\n\n// molar gas constant\n// (8.314462618 \u00b1 0.0) J mol^-1 K^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(molar_gas_constant, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::molar_gas_constant<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::molar_gas_constant<T>::value() ==\n             static_cast<T>(8.314462618));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::molar_gas_constant<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::molar_gas_constant<T>::uncertainty() ==\n      static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::molar_gas_constant<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::molar_gas_constant<T>::precision()));\n}\n\n// molar mass constant\n// (0.00099999999965 \u00b1 3e-13) kg mol^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(molar_mass_constant, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::molar_mass_constant<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::molar_mass_constant<T>::value() ==\n             static_cast<T>(0.00099999999965));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::molar_mass_constant<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::molar_mass_constant<T>::uncertainty() ==\n      static_cast<T>(3e-13));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::molar_mass_constant<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::molar_mass_constant<T>::precision()));\n}\n\n// molar mass of carbon-12\n// (0.0119999999958 \u00b1 3.6e-12) kg mol^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(molar_mass_of_carbon_12, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::molar_mass_of_carbon_12<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::molar_mass_of_carbon_12<T>::value() ==\n      static_cast<T>(0.0119999999958));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::molar_mass_of_carbon_12<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::molar_mass_of_carbon_12<\n                 T>::uncertainty() == static_cast<T>(3.6e-12));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::molar_mass_of_carbon_12<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::molar_mass_of_carbon_12<T>::precision()));\n}\n\n// molar Planck constant\n// (3.990312712e-10 \u00b1 0.0) J Hz^-1 mol^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(molar_Planck_constant, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::molar_Planck_constant<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::molar_Planck_constant<T>::value() ==\n      static_cast<T>(3.990312712e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::molar_Planck_constant<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::molar_Planck_constant<T>::uncertainty() ==\n      static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::molar_Planck_constant<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::molar_Planck_constant<T>::precision()));\n}\n\n// molar volume of ideal gas (273.15 K, 100 kPa)\n// (0.02271095464 \u00b1 0.0) m^3 mol^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(molar_volume_of_ideal_gas_27315_K_100_kPa, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::molar_volume_of_ideal_gas_27315_K_100_kPa<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::molar_volume_of_ideal_gas_27315_K_100_kPa<\n          T>::value() == static_cast<T>(0.02271095464));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::molar_volume_of_ideal_gas_27315_K_100_kPa<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::molar_volume_of_ideal_gas_27315_K_100_kPa<\n          T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::molar_volume_of_ideal_gas_27315_K_100_kPa<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::molar_volume_of_ideal_gas_27315_K_100_kPa<\n          T>::precision()));\n}\n\n// molar volume of ideal gas (273.15 K, 101.325 kPa)\n// (0.02241396954 \u00b1 0.0) m^3 mol^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(molar_volume_of_ideal_gas_27315_K_101325_kPa, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::\n          molar_volume_of_ideal_gas_27315_K_101325_kPa<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::\n                 molar_volume_of_ideal_gas_27315_K_101325_kPa<T>::value() ==\n             static_cast<T>(0.02241396954));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::\n          molar_volume_of_ideal_gas_27315_K_101325_kPa<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::\n          molar_volume_of_ideal_gas_27315_K_101325_kPa<T>::uncertainty() ==\n      static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::\n          molar_volume_of_ideal_gas_27315_K_101325_kPa<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::\n          molar_volume_of_ideal_gas_27315_K_101325_kPa<T>::precision()));\n}\n\n// molar volume of silicon\n// (1.205883199e-05 \u00b1 6e-13) m^3 mol^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(molar_volume_of_silicon, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::molar_volume_of_silicon<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::molar_volume_of_silicon<T>::value() ==\n      static_cast<T>(1.205883199e-05));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::molar_volume_of_silicon<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::molar_volume_of_silicon<\n                 T>::uncertainty() == static_cast<T>(6e-13));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::molar_volume_of_silicon<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::molar_volume_of_silicon<T>::precision()));\n}\n\n// Mo x unit\n// (1.00209952e-13 \u00b1 5.3e-20) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(Mo_x_unit, T, test_types) {\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::Mo_x_unit<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::Mo_x_unit<T>::value() ==\n             static_cast<T>(1.00209952e-13));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Mo_x_unit<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::Mo_x_unit<T>::uncertainty() ==\n             static_cast<T>(5.3e-20));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::Mo_x_unit<T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::Mo_x_unit<T>::precision()));\n}\n\n// muon Compton wavelength\n// (1.17344411e-14 \u00b1 2.6e-22) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(muon_Compton_wavelength, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::muon_Compton_wavelength<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::muon_Compton_wavelength<T>::value() ==\n      static_cast<T>(1.17344411e-14));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::muon_Compton_wavelength<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::muon_Compton_wavelength<\n                 T>::uncertainty() == static_cast<T>(2.6e-22));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::muon_Compton_wavelength<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::muon_Compton_wavelength<T>::precision()));\n}\n\n// muon-electron mass ratio\n// (206.768283 \u00b1 4.6e-06)\nBOOST_AUTO_TEST_CASE_TEMPLATE(muon_electron_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::muon_electron_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::muon_electron_mass_ratio<T>::value() ==\n      static_cast<T>(206.768283));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::muon_electron_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::muon_electron_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(4.6e-06));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::muon_electron_mass_ratio<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::muon_electron_mass_ratio<\n                    T>::precision()));\n}\n\n// muon g factor\n// (-2.0023318418 \u00b1 1.3e-09)\nBOOST_AUTO_TEST_CASE_TEMPLATE(muon_g_factor, T, test_types) {\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::muon_g_factor<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::muon_g_factor<T>::value() ==\n             static_cast<T>(-2.0023318418));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::muon_g_factor<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::muon_g_factor<T>::uncertainty() ==\n             static_cast<T>(1.3e-09));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::muon_g_factor<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::muon_g_factor<T>::precision()));\n}\n\n// muon mag. mom.\n// (-4.4904483e-26 \u00b1 1e-33) J T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(muon_mag_mom, T, test_types) {\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::muon_mag_mom<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::muon_mag_mom<T>::value() ==\n             static_cast<T>(-4.4904483e-26));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::muon_mag_mom<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::muon_mag_mom<T>::uncertainty() ==\n             static_cast<T>(1e-33));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::muon_mag_mom<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::muon_mag_mom<T>::precision()));\n}\n\n// muon mag. mom. anomaly\n// (0.00116592089 \u00b1 6.3e-10)\nBOOST_AUTO_TEST_CASE_TEMPLATE(muon_mag_mom_anomaly, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::muon_mag_mom_anomaly<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::muon_mag_mom_anomaly<T>::value() ==\n             static_cast<T>(0.00116592089));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::muon_mag_mom_anomaly<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::muon_mag_mom_anomaly<T>::uncertainty() ==\n      static_cast<T>(6.3e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::muon_mag_mom_anomaly<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::muon_mag_mom_anomaly<T>::precision()));\n}\n\n// muon mag. mom. to Bohr magneton ratio\n// (-0.00484197047 \u00b1 1.1e-10)\nBOOST_AUTO_TEST_CASE_TEMPLATE(muon_mag_mom_to_Bohr_magneton_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::muon_mag_mom_to_Bohr_magneton_ratio<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::muon_mag_mom_to_Bohr_magneton_ratio<\n          T>::value() == static_cast<T>(-0.00484197047));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::muon_mag_mom_to_Bohr_magneton_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::muon_mag_mom_to_Bohr_magneton_ratio<\n          T>::uncertainty() == static_cast<T>(1.1e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::muon_mag_mom_to_Bohr_magneton_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::muon_mag_mom_to_Bohr_magneton_ratio<\n          T>::precision()));\n}\n\n// muon mag. mom. to nuclear magneton ratio\n// (-8.89059703 \u00b1 2e-07)\nBOOST_AUTO_TEST_CASE_TEMPLATE(muon_mag_mom_to_nuclear_magneton_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::muon_mag_mom_to_nuclear_magneton_ratio<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::muon_mag_mom_to_nuclear_magneton_ratio<\n          T>::value() == static_cast<T>(-8.89059703));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::muon_mag_mom_to_nuclear_magneton_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::muon_mag_mom_to_nuclear_magneton_ratio<\n          T>::uncertainty() == static_cast<T>(2e-07));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::muon_mag_mom_to_nuclear_magneton_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::muon_mag_mom_to_nuclear_magneton_ratio<\n          T>::precision()));\n}\n\n// muon mass\n// (1.883531627e-28 \u00b1 4.2e-36) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(muon_mass, T, test_types) {\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::muon_mass<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::muon_mass<T>::value() ==\n             static_cast<T>(1.883531627e-28));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::muon_mass<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::muon_mass<T>::uncertainty() ==\n             static_cast<T>(4.2e-36));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::muon_mass<T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::muon_mass<T>::precision()));\n}\n\n// muon mass energy equivalent\n// (1.692833804e-11 \u00b1 3.8e-19) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(muon_mass_energy_equivalent, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::muon_mass_energy_equivalent<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::muon_mass_energy_equivalent<T>::value() ==\n      static_cast<T>(1.692833804e-11));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::muon_mass_energy_equivalent<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::muon_mass_energy_equivalent<\n                 T>::uncertainty() == static_cast<T>(3.8e-19));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::muon_mass_energy_equivalent<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::muon_mass_energy_equivalent<\n                    T>::precision()));\n}\n\n// muon mass energy equivalent in MeV\n// (105.6583755 \u00b1 2.3e-06) MeV\nBOOST_AUTO_TEST_CASE_TEMPLATE(muon_mass_energy_equivalent_in_MeV, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::muon_mass_energy_equivalent_in_MeV<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::muon_mass_energy_equivalent_in_MeV<\n                 T>::value() == static_cast<T>(105.6583755));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::muon_mass_energy_equivalent_in_MeV<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::muon_mass_energy_equivalent_in_MeV<\n                 T>::uncertainty() == static_cast<T>(2.3e-06));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::muon_mass_energy_equivalent_in_MeV<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::muon_mass_energy_equivalent_in_MeV<\n          T>::precision()));\n}\n\n// muon mass in u\n// (0.1134289259 \u00b1 2.5e-09) u\nBOOST_AUTO_TEST_CASE_TEMPLATE(muon_mass_in_u, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::muon_mass_in_u<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::muon_mass_in_u<T>::value() ==\n             static_cast<T>(0.1134289259));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::muon_mass_in_u<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::muon_mass_in_u<T>::uncertainty() ==\n             static_cast<T>(2.5e-09));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::muon_mass_in_u<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::muon_mass_in_u<T>::precision()));\n}\n\n// muon molar mass\n// (0.0001134289259 \u00b1 2.5e-12) kg mol^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(muon_molar_mass, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::muon_molar_mass<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::muon_molar_mass<T>::value() ==\n             static_cast<T>(0.0001134289259));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::muon_molar_mass<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::muon_molar_mass<T>::uncertainty() ==\n      static_cast<T>(2.5e-12));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::muon_molar_mass<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::muon_molar_mass<T>::precision()));\n}\n\n// muon-neutron mass ratio\n// (0.112454517 \u00b1 2.5e-09)\nBOOST_AUTO_TEST_CASE_TEMPLATE(muon_neutron_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::muon_neutron_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::muon_neutron_mass_ratio<T>::value() ==\n      static_cast<T>(0.112454517));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::muon_neutron_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::muon_neutron_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(2.5e-09));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::muon_neutron_mass_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::muon_neutron_mass_ratio<T>::precision()));\n}\n\n// muon-proton mag. mom. ratio\n// (-3.183345142 \u00b1 7.1e-08)\nBOOST_AUTO_TEST_CASE_TEMPLATE(muon_proton_mag_mom_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::muon_proton_mag_mom_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::muon_proton_mag_mom_ratio<T>::value() ==\n      static_cast<T>(-3.183345142));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::muon_proton_mag_mom_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::muon_proton_mag_mom_ratio<\n                 T>::uncertainty() == static_cast<T>(7.1e-08));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::muon_proton_mag_mom_ratio<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::muon_proton_mag_mom_ratio<\n                    T>::precision()));\n}\n\n// muon-proton mass ratio\n// (0.1126095264 \u00b1 2.5e-09)\nBOOST_AUTO_TEST_CASE_TEMPLATE(muon_proton_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::muon_proton_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::muon_proton_mass_ratio<T>::value() ==\n      static_cast<T>(0.1126095264));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::muon_proton_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::muon_proton_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(2.5e-09));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::muon_proton_mass_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::muon_proton_mass_ratio<T>::precision()));\n}\n\n// muon-tau mass ratio\n// (0.0594635 \u00b1 4e-06)\nBOOST_AUTO_TEST_CASE_TEMPLATE(muon_tau_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::muon_tau_mass_ratio<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::muon_tau_mass_ratio<T>::value() ==\n             static_cast<T>(0.0594635));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::muon_tau_mass_ratio<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::muon_tau_mass_ratio<T>::uncertainty() ==\n      static_cast<T>(4e-06));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::muon_tau_mass_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::muon_tau_mass_ratio<T>::precision()));\n}\n\n// natural unit of action\n// (1.054571817e-34 \u00b1 0.0) J s\nBOOST_AUTO_TEST_CASE_TEMPLATE(natural_unit_of_action, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::natural_unit_of_action<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::natural_unit_of_action<T>::value() ==\n      static_cast<T>(1.054571817e-34));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::natural_unit_of_action<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::natural_unit_of_action<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::natural_unit_of_action<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::natural_unit_of_action<T>::precision()));\n}\n\n// natural unit of action in eV s\n// (6.582119569e-16 \u00b1 0.0) eV s\nBOOST_AUTO_TEST_CASE_TEMPLATE(natural_unit_of_action_in_eV_s, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::natural_unit_of_action_in_eV_s<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::natural_unit_of_action_in_eV_s<\n                 T>::value() == static_cast<T>(6.582119569e-16));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::natural_unit_of_action_in_eV_s<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::natural_unit_of_action_in_eV_s<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::natural_unit_of_action_in_eV_s<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::natural_unit_of_action_in_eV_s<\n          T>::precision()));\n}\n\n// natural unit of energy\n// (8.1871057769e-14 \u00b1 2.5e-23) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(natural_unit_of_energy, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::natural_unit_of_energy<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::natural_unit_of_energy<T>::value() ==\n      static_cast<T>(8.1871057769e-14));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::natural_unit_of_energy<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::natural_unit_of_energy<\n                 T>::uncertainty() == static_cast<T>(2.5e-23));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::natural_unit_of_energy<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::natural_unit_of_energy<T>::precision()));\n}\n\n// natural unit of energy in MeV\n// (0.51099895 \u00b1 1.5e-10) MeV\nBOOST_AUTO_TEST_CASE_TEMPLATE(natural_unit_of_energy_in_MeV, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::natural_unit_of_energy_in_MeV<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::natural_unit_of_energy_in_MeV<\n                 T>::value() == static_cast<T>(0.51099895));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::natural_unit_of_energy_in_MeV<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::natural_unit_of_energy_in_MeV<\n                 T>::uncertainty() == static_cast<T>(1.5e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::natural_unit_of_energy_in_MeV<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::natural_unit_of_energy_in_MeV<\n          T>::precision()));\n}\n\n// natural unit of length\n// (3.8615926796e-13 \u00b1 1.2e-22) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(natural_unit_of_length, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::natural_unit_of_length<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::natural_unit_of_length<T>::value() ==\n      static_cast<T>(3.8615926796e-13));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::natural_unit_of_length<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::natural_unit_of_length<\n                 T>::uncertainty() == static_cast<T>(1.2e-22));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::natural_unit_of_length<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::natural_unit_of_length<T>::precision()));\n}\n\n// natural unit of mass\n// (9.1093837015e-31 \u00b1 2.8e-40) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(natural_unit_of_mass, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::natural_unit_of_mass<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::natural_unit_of_mass<T>::value() ==\n             static_cast<T>(9.1093837015e-31));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::natural_unit_of_mass<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::natural_unit_of_mass<T>::uncertainty() ==\n      static_cast<T>(2.8e-40));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::natural_unit_of_mass<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::natural_unit_of_mass<T>::precision()));\n}\n\n// natural unit of momentum\n// (2.73092453075e-22 \u00b1 8.2e-32) kg m s^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(natural_unit_of_momentum, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::natural_unit_of_momentum<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::natural_unit_of_momentum<T>::value() ==\n      static_cast<T>(2.73092453075e-22));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::natural_unit_of_momentum<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::natural_unit_of_momentum<\n                 T>::uncertainty() == static_cast<T>(8.2e-32));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::natural_unit_of_momentum<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::natural_unit_of_momentum<\n                    T>::precision()));\n}\n\n// natural unit of momentum in MeV/c\n// (0.51099895 \u00b1 1.5e-10) MeV/c\nBOOST_AUTO_TEST_CASE_TEMPLATE(natural_unit_of_momentum_in_MeV_c, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::natural_unit_of_momentum_in_MeV_c<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::natural_unit_of_momentum_in_MeV_c<\n                 T>::value() == static_cast<T>(0.51099895));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::natural_unit_of_momentum_in_MeV_c<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::natural_unit_of_momentum_in_MeV_c<\n                 T>::uncertainty() == static_cast<T>(1.5e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::natural_unit_of_momentum_in_MeV_c<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::natural_unit_of_momentum_in_MeV_c<\n          T>::precision()));\n}\n\n// natural unit of time\n// (1.28808866819e-21 \u00b1 3.9e-31) s\nBOOST_AUTO_TEST_CASE_TEMPLATE(natural_unit_of_time, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::natural_unit_of_time<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::natural_unit_of_time<T>::value() ==\n             static_cast<T>(1.28808866819e-21));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::natural_unit_of_time<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::natural_unit_of_time<T>::uncertainty() ==\n      static_cast<T>(3.9e-31));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::natural_unit_of_time<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::natural_unit_of_time<T>::precision()));\n}\n\n// natural unit of velocity\n// (299792458.0 \u00b1 0.0) m s^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(natural_unit_of_velocity, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::natural_unit_of_velocity<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::natural_unit_of_velocity<T>::value() ==\n      static_cast<T>(299792458.0));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::natural_unit_of_velocity<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::natural_unit_of_velocity<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::natural_unit_of_velocity<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::natural_unit_of_velocity<\n                    T>::precision()));\n}\n\n// neutron Compton wavelength\n// (1.31959090581e-15 \u00b1 7.5e-25) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_Compton_wavelength, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::neutron_Compton_wavelength<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::neutron_Compton_wavelength<T>::value() ==\n      static_cast<T>(1.31959090581e-15));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::neutron_Compton_wavelength<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::neutron_Compton_wavelength<\n                 T>::uncertainty() == static_cast<T>(7.5e-25));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::neutron_Compton_wavelength<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::neutron_Compton_wavelength<\n                    T>::precision()));\n}\n\n// neutron-electron mag. mom. ratio\n// (0.00104066882 \u00b1 2.5e-10)\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_electron_mag_mom_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::neutron_electron_mag_mom_ratio<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::neutron_electron_mag_mom_ratio<\n                 T>::value() == static_cast<T>(0.00104066882));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::neutron_electron_mag_mom_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::neutron_electron_mag_mom_ratio<\n                 T>::uncertainty() == static_cast<T>(2.5e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::neutron_electron_mag_mom_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::neutron_electron_mag_mom_ratio<\n          T>::precision()));\n}\n\n// neutron-electron mass ratio\n// (1838.68366173 \u00b1 8.9e-07)\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_electron_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::neutron_electron_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::neutron_electron_mass_ratio<T>::value() ==\n      static_cast<T>(1838.68366173));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::neutron_electron_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::neutron_electron_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(8.9e-07));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::neutron_electron_mass_ratio<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::neutron_electron_mass_ratio<\n                    T>::precision()));\n}\n\n// neutron g factor\n// (-3.82608545 \u00b1 9e-07)\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_g_factor, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::neutron_g_factor<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::neutron_g_factor<T>::value() ==\n             static_cast<T>(-3.82608545));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::neutron_g_factor<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::neutron_g_factor<T>::uncertainty() ==\n      static_cast<T>(9e-07));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::neutron_g_factor<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::neutron_g_factor<T>::precision()));\n}\n\n// neutron gyromag. ratio\n// (183247171.0 \u00b1 43.0) s^-1 T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_gyromag_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::neutron_gyromag_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::neutron_gyromag_ratio<T>::value() ==\n      static_cast<T>(183247171.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::neutron_gyromag_ratio<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::neutron_gyromag_ratio<T>::uncertainty() ==\n      static_cast<T>(43.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::neutron_gyromag_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::neutron_gyromag_ratio<T>::precision()));\n}\n\n// neutron gyromag. ratio in MHz/T\n// (29.1646931 \u00b1 6.9e-06) MHz T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_gyromag_ratio_in_MHz_T, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::neutron_gyromag_ratio_in_MHz_T<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::neutron_gyromag_ratio_in_MHz_T<\n                 T>::value() == static_cast<T>(29.1646931));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::neutron_gyromag_ratio_in_MHz_T<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::neutron_gyromag_ratio_in_MHz_T<\n                 T>::uncertainty() == static_cast<T>(6.9e-06));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::neutron_gyromag_ratio_in_MHz_T<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::neutron_gyromag_ratio_in_MHz_T<\n          T>::precision()));\n}\n\n// neutron mag. mom.\n// (-9.6623651e-27 \u00b1 2.3e-33) J T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_mag_mom, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::neutron_mag_mom<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::neutron_mag_mom<T>::value() ==\n             static_cast<T>(-9.6623651e-27));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::neutron_mag_mom<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::neutron_mag_mom<T>::uncertainty() ==\n      static_cast<T>(2.3e-33));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::neutron_mag_mom<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::neutron_mag_mom<T>::precision()));\n}\n\n// neutron mag. mom. to Bohr magneton ratio\n// (-0.00104187563 \u00b1 2.5e-10)\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_mag_mom_to_Bohr_magneton_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::neutron_mag_mom_to_Bohr_magneton_ratio<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::neutron_mag_mom_to_Bohr_magneton_ratio<\n          T>::value() == static_cast<T>(-0.00104187563));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::neutron_mag_mom_to_Bohr_magneton_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::neutron_mag_mom_to_Bohr_magneton_ratio<\n          T>::uncertainty() == static_cast<T>(2.5e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::neutron_mag_mom_to_Bohr_magneton_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::neutron_mag_mom_to_Bohr_magneton_ratio<\n          T>::precision()));\n}\n\n// neutron mag. mom. to nuclear magneton ratio\n// (-1.91304273 \u00b1 4.5e-07)\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_mag_mom_to_nuclear_magneton_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::neutron_mag_mom_to_nuclear_magneton_ratio<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::neutron_mag_mom_to_nuclear_magneton_ratio<\n          T>::value() == static_cast<T>(-1.91304273));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::neutron_mag_mom_to_nuclear_magneton_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::neutron_mag_mom_to_nuclear_magneton_ratio<\n          T>::uncertainty() == static_cast<T>(4.5e-07));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::neutron_mag_mom_to_nuclear_magneton_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::neutron_mag_mom_to_nuclear_magneton_ratio<\n          T>::precision()));\n}\n\n// neutron mass\n// (1.67492749804e-27 \u00b1 9.5e-37) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_mass, T, test_types) {\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::neutron_mass<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::neutron_mass<T>::value() ==\n             static_cast<T>(1.67492749804e-27));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::neutron_mass<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::neutron_mass<T>::uncertainty() ==\n             static_cast<T>(9.5e-37));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::neutron_mass<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::neutron_mass<T>::precision()));\n}\n\n// neutron mass energy equivalent\n// (1.50534976287e-10 \u00b1 8.6e-20) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_mass_energy_equivalent, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::neutron_mass_energy_equivalent<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::neutron_mass_energy_equivalent<\n                 T>::value() == static_cast<T>(1.50534976287e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::neutron_mass_energy_equivalent<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::neutron_mass_energy_equivalent<\n                 T>::uncertainty() == static_cast<T>(8.6e-20));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::neutron_mass_energy_equivalent<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::neutron_mass_energy_equivalent<\n          T>::precision()));\n}\n\n// neutron mass energy equivalent in MeV\n// (939.56542052 \u00b1 5.4e-07) MeV\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_mass_energy_equivalent_in_MeV, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::neutron_mass_energy_equivalent_in_MeV<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::neutron_mass_energy_equivalent_in_MeV<\n          T>::value() == static_cast<T>(939.56542052));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::neutron_mass_energy_equivalent_in_MeV<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::neutron_mass_energy_equivalent_in_MeV<\n          T>::uncertainty() == static_cast<T>(5.4e-07));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::neutron_mass_energy_equivalent_in_MeV<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::neutron_mass_energy_equivalent_in_MeV<\n          T>::precision()));\n}\n\n// neutron mass in u\n// (1.00866491595 \u00b1 4.9e-10) u\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_mass_in_u, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::neutron_mass_in_u<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::neutron_mass_in_u<T>::value() ==\n             static_cast<T>(1.00866491595));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::neutron_mass_in_u<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::neutron_mass_in_u<T>::uncertainty() ==\n      static_cast<T>(4.9e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::neutron_mass_in_u<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::neutron_mass_in_u<T>::precision()));\n}\n\n// neutron molar mass\n// (0.0010086649156 \u00b1 5.7e-13) kg mol^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_molar_mass, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::neutron_molar_mass<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::neutron_molar_mass<T>::value() ==\n             static_cast<T>(0.0010086649156));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::neutron_molar_mass<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::neutron_molar_mass<T>::uncertainty() ==\n      static_cast<T>(5.7e-13));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::neutron_molar_mass<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::neutron_molar_mass<T>::precision()));\n}\n\n// neutron-muon mass ratio\n// (8.89248406 \u00b1 2e-07)\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_muon_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::neutron_muon_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::neutron_muon_mass_ratio<T>::value() ==\n      static_cast<T>(8.89248406));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::neutron_muon_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::neutron_muon_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(2e-07));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::neutron_muon_mass_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::neutron_muon_mass_ratio<T>::precision()));\n}\n\n// neutron-proton mag. mom. ratio\n// (-0.68497934 \u00b1 1.6e-07)\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_proton_mag_mom_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::neutron_proton_mag_mom_ratio<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::neutron_proton_mag_mom_ratio<\n                 T>::value() == static_cast<T>(-0.68497934));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::neutron_proton_mag_mom_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::neutron_proton_mag_mom_ratio<\n                 T>::uncertainty() == static_cast<T>(1.6e-07));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::neutron_proton_mag_mom_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::neutron_proton_mag_mom_ratio<\n          T>::precision()));\n}\n\n// neutron-proton mass difference\n// (2.30557435e-30 \u00b1 8.2e-37) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_proton_mass_difference, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::neutron_proton_mass_difference<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::neutron_proton_mass_difference<\n                 T>::value() == static_cast<T>(2.30557435e-30));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::neutron_proton_mass_difference<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::neutron_proton_mass_difference<\n                 T>::uncertainty() == static_cast<T>(8.2e-37));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::neutron_proton_mass_difference<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::neutron_proton_mass_difference<\n          T>::precision()));\n}\n\n// neutron-proton mass difference energy equivalent\n// (2.07214689e-13 \u00b1 7.4e-20) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_proton_mass_difference_energy_equivalent,\n                              T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::\n          neutron_proton_mass_difference_energy_equivalent<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::\n                 neutron_proton_mass_difference_energy_equivalent<T>::value() ==\n             static_cast<T>(2.07214689e-13));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::\n          neutron_proton_mass_difference_energy_equivalent<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::\n          neutron_proton_mass_difference_energy_equivalent<T>::uncertainty() ==\n      static_cast<T>(7.4e-20));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::\n          neutron_proton_mass_difference_energy_equivalent<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::\n          neutron_proton_mass_difference_energy_equivalent<T>::precision()));\n}\n\n// neutron-proton mass difference energy equivalent in MeV\n// (1.29333236 \u00b1 4.6e-07) MeV\nBOOST_AUTO_TEST_CASE_TEMPLATE(\n    neutron_proton_mass_difference_energy_equivalent_in_MeV, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::\n          neutron_proton_mass_difference_energy_equivalent_in_MeV<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::\n          neutron_proton_mass_difference_energy_equivalent_in_MeV<T>::value() ==\n      static_cast<T>(1.29333236));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::\n                        neutron_proton_mass_difference_energy_equivalent_in_MeV<\n                            T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::\n                 neutron_proton_mass_difference_energy_equivalent_in_MeV<\n                     T>::uncertainty() == static_cast<T>(4.6e-07));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::\n                        neutron_proton_mass_difference_energy_equivalent_in_MeV<\n                            T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::\n                        neutron_proton_mass_difference_energy_equivalent_in_MeV<\n                            T>::precision()));\n}\n\n// neutron-proton mass difference in u\n// (0.00138844933 \u00b1 4.9e-10) u\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_proton_mass_difference_in_u, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::neutron_proton_mass_difference_in_u<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::neutron_proton_mass_difference_in_u<\n          T>::value() == static_cast<T>(0.00138844933));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::neutron_proton_mass_difference_in_u<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::neutron_proton_mass_difference_in_u<\n          T>::uncertainty() == static_cast<T>(4.9e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::neutron_proton_mass_difference_in_u<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::neutron_proton_mass_difference_in_u<\n          T>::precision()));\n}\n\n// neutron-proton mass ratio\n// (1.00137841931 \u00b1 4.9e-10)\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_proton_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::neutron_proton_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::neutron_proton_mass_ratio<T>::value() ==\n      static_cast<T>(1.00137841931));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::neutron_proton_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::neutron_proton_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(4.9e-10));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::neutron_proton_mass_ratio<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::neutron_proton_mass_ratio<\n                    T>::precision()));\n}\n\n// neutron relative atomic mass\n// (1.00866491595 \u00b1 4.9e-10)\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_relative_atomic_mass, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::neutron_relative_atomic_mass<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::neutron_relative_atomic_mass<\n                 T>::value() == static_cast<T>(1.00866491595));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::neutron_relative_atomic_mass<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::neutron_relative_atomic_mass<\n                 T>::uncertainty() == static_cast<T>(4.9e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::neutron_relative_atomic_mass<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::neutron_relative_atomic_mass<\n          T>::precision()));\n}\n\n// neutron-tau mass ratio\n// (0.528779 \u00b1 3.6e-05)\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_tau_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::neutron_tau_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::neutron_tau_mass_ratio<T>::value() ==\n      static_cast<T>(0.528779));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::neutron_tau_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::neutron_tau_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(3.6e-05));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::neutron_tau_mass_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::neutron_tau_mass_ratio<T>::precision()));\n}\n\n// neutron to shielded proton mag. mom. ratio\n// (-0.68499694 \u00b1 1.6e-07)\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_to_shielded_proton_mag_mom_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::neutron_to_shielded_proton_mag_mom_ratio<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::neutron_to_shielded_proton_mag_mom_ratio<\n          T>::value() == static_cast<T>(-0.68499694));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::neutron_to_shielded_proton_mag_mom_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::neutron_to_shielded_proton_mag_mom_ratio<\n          T>::uncertainty() == static_cast<T>(1.6e-07));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::neutron_to_shielded_proton_mag_mom_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::neutron_to_shielded_proton_mag_mom_ratio<\n          T>::precision()));\n}\n\n// Newtonian constant of gravitation\n// (6.6743e-11 \u00b1 1.5e-15) m^3 kg^-1 s^-2\nBOOST_AUTO_TEST_CASE_TEMPLATE(Newtonian_constant_of_gravitation, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Newtonian_constant_of_gravitation<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::Newtonian_constant_of_gravitation<\n                 T>::value() == static_cast<T>(6.6743e-11));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Newtonian_constant_of_gravitation<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::Newtonian_constant_of_gravitation<\n                 T>::uncertainty() == static_cast<T>(1.5e-15));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Newtonian_constant_of_gravitation<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::Newtonian_constant_of_gravitation<\n          T>::precision()));\n}\n\n// Newtonian constant of gravitation over h-bar c\n// (6.70883e-39 \u00b1 1.5e-43) (GeV/c^2)^-2\nBOOST_AUTO_TEST_CASE_TEMPLATE(Newtonian_constant_of_gravitation_over_h_bar_c, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::\n          Newtonian_constant_of_gravitation_over_h_bar_c<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::\n                 Newtonian_constant_of_gravitation_over_h_bar_c<T>::value() ==\n             static_cast<T>(6.70883e-39));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::\n          Newtonian_constant_of_gravitation_over_h_bar_c<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::\n          Newtonian_constant_of_gravitation_over_h_bar_c<T>::uncertainty() ==\n      static_cast<T>(1.5e-43));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::\n          Newtonian_constant_of_gravitation_over_h_bar_c<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::\n          Newtonian_constant_of_gravitation_over_h_bar_c<T>::precision()));\n}\n\n// nuclear magneton\n// (5.0507837461e-27 \u00b1 1.5e-36) J T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(nuclear_magneton, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::nuclear_magneton<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::nuclear_magneton<T>::value() ==\n             static_cast<T>(5.0507837461e-27));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::nuclear_magneton<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::nuclear_magneton<T>::uncertainty() ==\n      static_cast<T>(1.5e-36));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::nuclear_magneton<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::nuclear_magneton<T>::precision()));\n}\n\n// nuclear magneton in eV/T\n// (3.15245125844e-08 \u00b1 9.6e-18) eV T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(nuclear_magneton_in_eV_T, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::nuclear_magneton_in_eV_T<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::nuclear_magneton_in_eV_T<T>::value() ==\n      static_cast<T>(3.15245125844e-08));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::nuclear_magneton_in_eV_T<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::nuclear_magneton_in_eV_T<\n                 T>::uncertainty() == static_cast<T>(9.6e-18));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::nuclear_magneton_in_eV_T<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::nuclear_magneton_in_eV_T<\n                    T>::precision()));\n}\n\n// nuclear magneton in inverse meter per tesla\n// (0.0254262341353 \u00b1 7.8e-12) m^-1 T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(nuclear_magneton_in_inverse_meter_per_tesla, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::\n          nuclear_magneton_in_inverse_meter_per_tesla<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::\n                 nuclear_magneton_in_inverse_meter_per_tesla<T>::value() ==\n             static_cast<T>(0.0254262341353));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::\n          nuclear_magneton_in_inverse_meter_per_tesla<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::\n          nuclear_magneton_in_inverse_meter_per_tesla<T>::uncertainty() ==\n      static_cast<T>(7.8e-12));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::\n          nuclear_magneton_in_inverse_meter_per_tesla<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::\n          nuclear_magneton_in_inverse_meter_per_tesla<T>::precision()));\n}\n\n// nuclear magneton in K/T\n// (0.00036582677756 \u00b1 1.1e-13) K T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(nuclear_magneton_in_K_T, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::nuclear_magneton_in_K_T<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::nuclear_magneton_in_K_T<T>::value() ==\n      static_cast<T>(0.00036582677756));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::nuclear_magneton_in_K_T<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::nuclear_magneton_in_K_T<\n                 T>::uncertainty() == static_cast<T>(1.1e-13));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::nuclear_magneton_in_K_T<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::nuclear_magneton_in_K_T<T>::precision()));\n}\n\n// nuclear magneton in MHz/T\n// (7.6225932291 \u00b1 2.3e-09) MHz T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(nuclear_magneton_in_MHz_T, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::nuclear_magneton_in_MHz_T<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::nuclear_magneton_in_MHz_T<T>::value() ==\n      static_cast<T>(7.6225932291));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::nuclear_magneton_in_MHz_T<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::nuclear_magneton_in_MHz_T<\n                 T>::uncertainty() == static_cast<T>(2.3e-09));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::nuclear_magneton_in_MHz_T<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::nuclear_magneton_in_MHz_T<\n                    T>::precision()));\n}\n\n// Planck constant\n// (6.62607015e-34 \u00b1 0.0) J Hz^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(Planck_constant, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Planck_constant<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::Planck_constant<T>::value() ==\n             static_cast<T>(6.62607015e-34));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Planck_constant<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::Planck_constant<T>::uncertainty() ==\n      static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Planck_constant<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::Planck_constant<T>::precision()));\n}\n\n// Planck constant in eV/Hz\n// (4.135667696e-15 \u00b1 0.0) eV Hz^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(Planck_constant_in_eV_Hz, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Planck_constant_in_eV_Hz<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::Planck_constant_in_eV_Hz<T>::value() ==\n      static_cast<T>(4.135667696e-15));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::Planck_constant_in_eV_Hz<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::Planck_constant_in_eV_Hz<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::Planck_constant_in_eV_Hz<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::Planck_constant_in_eV_Hz<\n                    T>::precision()));\n}\n\n// Planck length\n// (1.616255e-35 \u00b1 1.8e-40) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(Planck_length, T, test_types) {\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::Planck_length<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::Planck_length<T>::value() ==\n             static_cast<T>(1.616255e-35));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Planck_length<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::Planck_length<T>::uncertainty() ==\n             static_cast<T>(1.8e-40));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Planck_length<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::Planck_length<T>::precision()));\n}\n\n// Planck mass\n// (2.176434e-08 \u00b1 2.4e-13) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(Planck_mass, T, test_types) {\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::Planck_mass<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::Planck_mass<T>::value() ==\n             static_cast<T>(2.176434e-08));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Planck_mass<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::Planck_mass<T>::uncertainty() ==\n             static_cast<T>(2.4e-13));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Planck_mass<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::Planck_mass<T>::precision()));\n}\n\n// Planck mass energy equivalent in GeV\n// (1.22089e+19 \u00b1 140000000000000.0) GeV\nBOOST_AUTO_TEST_CASE_TEMPLATE(Planck_mass_energy_equivalent_in_GeV, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Planck_mass_energy_equivalent_in_GeV<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::Planck_mass_energy_equivalent_in_GeV<\n          T>::value() == static_cast<T>(1.22089e+19));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Planck_mass_energy_equivalent_in_GeV<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::Planck_mass_energy_equivalent_in_GeV<\n          T>::uncertainty() == static_cast<T>(140000000000000.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Planck_mass_energy_equivalent_in_GeV<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::Planck_mass_energy_equivalent_in_GeV<\n          T>::precision()));\n}\n\n// Planck temperature\n// (1.416784e+32 \u00b1 1.6e+27) K\nBOOST_AUTO_TEST_CASE_TEMPLATE(Planck_temperature, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Planck_temperature<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::Planck_temperature<T>::value() ==\n             static_cast<T>(1.416784e+32));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Planck_temperature<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::Planck_temperature<T>::uncertainty() ==\n      static_cast<T>(1.6e+27));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Planck_temperature<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::Planck_temperature<T>::precision()));\n}\n\n// Planck time\n// (5.391247e-44 \u00b1 6e-49) s\nBOOST_AUTO_TEST_CASE_TEMPLATE(Planck_time, T, test_types) {\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::Planck_time<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::Planck_time<T>::value() ==\n             static_cast<T>(5.391247e-44));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Planck_time<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::Planck_time<T>::uncertainty() ==\n             static_cast<T>(6e-49));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Planck_time<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::Planck_time<T>::precision()));\n}\n\n// proton charge to mass quotient\n// (95788331.56 \u00b1 0.029) C kg^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(proton_charge_to_mass_quotient, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::proton_charge_to_mass_quotient<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::proton_charge_to_mass_quotient<\n                 T>::value() == static_cast<T>(95788331.56));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::proton_charge_to_mass_quotient<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::proton_charge_to_mass_quotient<\n                 T>::uncertainty() == static_cast<T>(0.029));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::proton_charge_to_mass_quotient<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::proton_charge_to_mass_quotient<\n          T>::precision()));\n}\n\n// proton Compton wavelength\n// (1.32140985539e-15 \u00b1 4e-25) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(proton_Compton_wavelength, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::proton_Compton_wavelength<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::proton_Compton_wavelength<T>::value() ==\n      static_cast<T>(1.32140985539e-15));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::proton_Compton_wavelength<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::proton_Compton_wavelength<\n                 T>::uncertainty() == static_cast<T>(4e-25));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::proton_Compton_wavelength<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::proton_Compton_wavelength<\n                    T>::precision()));\n}\n\n// proton-electron mass ratio\n// (1836.15267343 \u00b1 1.1e-07)\nBOOST_AUTO_TEST_CASE_TEMPLATE(proton_electron_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::proton_electron_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::proton_electron_mass_ratio<T>::value() ==\n      static_cast<T>(1836.15267343));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::proton_electron_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::proton_electron_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(1.1e-07));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::proton_electron_mass_ratio<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::proton_electron_mass_ratio<\n                    T>::precision()));\n}\n\n// proton g factor\n// (5.5856946893 \u00b1 1.6e-09)\nBOOST_AUTO_TEST_CASE_TEMPLATE(proton_g_factor, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::proton_g_factor<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::proton_g_factor<T>::value() ==\n             static_cast<T>(5.5856946893));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::proton_g_factor<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::proton_g_factor<T>::uncertainty() ==\n      static_cast<T>(1.6e-09));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::proton_g_factor<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::proton_g_factor<T>::precision()));\n}\n\n// proton gyromag. ratio\n// (267522187.44 \u00b1 0.11) s^-1 T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(proton_gyromag_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::proton_gyromag_ratio<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::proton_gyromag_ratio<T>::value() ==\n             static_cast<T>(267522187.44));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::proton_gyromag_ratio<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::proton_gyromag_ratio<T>::uncertainty() ==\n      static_cast<T>(0.11));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::proton_gyromag_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::proton_gyromag_ratio<T>::precision()));\n}\n\n// proton gyromag. ratio in MHz/T\n// (42.577478518 \u00b1 1.8e-08) MHz T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(proton_gyromag_ratio_in_MHz_T, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::proton_gyromag_ratio_in_MHz_T<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::proton_gyromag_ratio_in_MHz_T<\n                 T>::value() == static_cast<T>(42.577478518));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::proton_gyromag_ratio_in_MHz_T<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::proton_gyromag_ratio_in_MHz_T<\n                 T>::uncertainty() == static_cast<T>(1.8e-08));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::proton_gyromag_ratio_in_MHz_T<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::proton_gyromag_ratio_in_MHz_T<\n          T>::precision()));\n}\n\n// proton mag. mom.\n// (1.41060679736e-26 \u00b1 6e-36) J T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(proton_mag_mom, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::proton_mag_mom<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::proton_mag_mom<T>::value() ==\n             static_cast<T>(1.41060679736e-26));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::proton_mag_mom<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::proton_mag_mom<T>::uncertainty() ==\n             static_cast<T>(6e-36));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::proton_mag_mom<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::proton_mag_mom<T>::precision()));\n}\n\n// proton mag. mom. to Bohr magneton ratio\n// (0.0015210322023 \u00b1 4.6e-13)\nBOOST_AUTO_TEST_CASE_TEMPLATE(proton_mag_mom_to_Bohr_magneton_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::proton_mag_mom_to_Bohr_magneton_ratio<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::proton_mag_mom_to_Bohr_magneton_ratio<\n          T>::value() == static_cast<T>(0.0015210322023));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::proton_mag_mom_to_Bohr_magneton_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::proton_mag_mom_to_Bohr_magneton_ratio<\n          T>::uncertainty() == static_cast<T>(4.6e-13));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::proton_mag_mom_to_Bohr_magneton_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::proton_mag_mom_to_Bohr_magneton_ratio<\n          T>::precision()));\n}\n\n// proton mag. mom. to nuclear magneton ratio\n// (2.79284734463 \u00b1 8.2e-10)\nBOOST_AUTO_TEST_CASE_TEMPLATE(proton_mag_mom_to_nuclear_magneton_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::proton_mag_mom_to_nuclear_magneton_ratio<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::proton_mag_mom_to_nuclear_magneton_ratio<\n          T>::value() == static_cast<T>(2.79284734463));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::proton_mag_mom_to_nuclear_magneton_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::proton_mag_mom_to_nuclear_magneton_ratio<\n          T>::uncertainty() == static_cast<T>(8.2e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::proton_mag_mom_to_nuclear_magneton_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::proton_mag_mom_to_nuclear_magneton_ratio<\n          T>::precision()));\n}\n\n// proton mag. shielding correction\n// (2.5689e-05 \u00b1 1.1e-08)\nBOOST_AUTO_TEST_CASE_TEMPLATE(proton_mag_shielding_correction, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::proton_mag_shielding_correction<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::proton_mag_shielding_correction<\n                 T>::value() == static_cast<T>(2.5689e-05));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::proton_mag_shielding_correction<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::proton_mag_shielding_correction<\n                 T>::uncertainty() == static_cast<T>(1.1e-08));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::proton_mag_shielding_correction<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::proton_mag_shielding_correction<\n          T>::precision()));\n}\n\n// proton mass\n// (1.67262192369e-27 \u00b1 5.1e-37) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(proton_mass, T, test_types) {\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::proton_mass<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::proton_mass<T>::value() ==\n             static_cast<T>(1.67262192369e-27));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::proton_mass<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::proton_mass<T>::uncertainty() ==\n             static_cast<T>(5.1e-37));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::proton_mass<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::proton_mass<T>::precision()));\n}\n\n// proton mass energy equivalent\n// (1.50327761598e-10 \u00b1 4.6e-20) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(proton_mass_energy_equivalent, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::proton_mass_energy_equivalent<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::proton_mass_energy_equivalent<\n                 T>::value() == static_cast<T>(1.50327761598e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::proton_mass_energy_equivalent<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::proton_mass_energy_equivalent<\n                 T>::uncertainty() == static_cast<T>(4.6e-20));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::proton_mass_energy_equivalent<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::proton_mass_energy_equivalent<\n          T>::precision()));\n}\n\n// proton mass energy equivalent in MeV\n// (938.27208816 \u00b1 2.9e-07) MeV\nBOOST_AUTO_TEST_CASE_TEMPLATE(proton_mass_energy_equivalent_in_MeV, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::proton_mass_energy_equivalent_in_MeV<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::proton_mass_energy_equivalent_in_MeV<\n          T>::value() == static_cast<T>(938.27208816));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::proton_mass_energy_equivalent_in_MeV<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::proton_mass_energy_equivalent_in_MeV<\n          T>::uncertainty() == static_cast<T>(2.9e-07));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::proton_mass_energy_equivalent_in_MeV<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::proton_mass_energy_equivalent_in_MeV<\n          T>::precision()));\n}\n\n// proton mass in u\n// (1.007276466621 \u00b1 5.3e-11) u\nBOOST_AUTO_TEST_CASE_TEMPLATE(proton_mass_in_u, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::proton_mass_in_u<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::proton_mass_in_u<T>::value() ==\n             static_cast<T>(1.007276466621));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::proton_mass_in_u<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::proton_mass_in_u<T>::uncertainty() ==\n      static_cast<T>(5.3e-11));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::proton_mass_in_u<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::proton_mass_in_u<T>::precision()));\n}\n\n// proton molar mass\n// (0.00100727646627 \u00b1 3.1e-13) kg mol^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(proton_molar_mass, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::proton_molar_mass<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::proton_molar_mass<T>::value() ==\n             static_cast<T>(0.00100727646627));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::proton_molar_mass<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::proton_molar_mass<T>::uncertainty() ==\n      static_cast<T>(3.1e-13));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::proton_molar_mass<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::proton_molar_mass<T>::precision()));\n}\n\n// proton-muon mass ratio\n// (8.88024337 \u00b1 2e-07)\nBOOST_AUTO_TEST_CASE_TEMPLATE(proton_muon_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::proton_muon_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::proton_muon_mass_ratio<T>::value() ==\n      static_cast<T>(8.88024337));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::proton_muon_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::proton_muon_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(2e-07));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::proton_muon_mass_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::proton_muon_mass_ratio<T>::precision()));\n}\n\n// proton-neutron mag. mom. ratio\n// (-1.45989805 \u00b1 3.4e-07)\nBOOST_AUTO_TEST_CASE_TEMPLATE(proton_neutron_mag_mom_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::proton_neutron_mag_mom_ratio<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::proton_neutron_mag_mom_ratio<\n                 T>::value() == static_cast<T>(-1.45989805));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::proton_neutron_mag_mom_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::proton_neutron_mag_mom_ratio<\n                 T>::uncertainty() == static_cast<T>(3.4e-07));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::proton_neutron_mag_mom_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::proton_neutron_mag_mom_ratio<\n          T>::precision()));\n}\n\n// proton-neutron mass ratio\n// (0.99862347812 \u00b1 4.9e-10)\nBOOST_AUTO_TEST_CASE_TEMPLATE(proton_neutron_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::proton_neutron_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::proton_neutron_mass_ratio<T>::value() ==\n      static_cast<T>(0.99862347812));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::proton_neutron_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::proton_neutron_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(4.9e-10));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::proton_neutron_mass_ratio<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::proton_neutron_mass_ratio<\n                    T>::precision()));\n}\n\n// proton relative atomic mass\n// (1.007276466621 \u00b1 5.3e-11)\nBOOST_AUTO_TEST_CASE_TEMPLATE(proton_relative_atomic_mass, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::proton_relative_atomic_mass<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::proton_relative_atomic_mass<T>::value() ==\n      static_cast<T>(1.007276466621));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::proton_relative_atomic_mass<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::proton_relative_atomic_mass<\n                 T>::uncertainty() == static_cast<T>(5.3e-11));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::proton_relative_atomic_mass<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::proton_relative_atomic_mass<\n                    T>::precision()));\n}\n\n// proton rms charge radius\n// (8.414e-16 \u00b1 1.9e-18) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(proton_rms_charge_radius, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::proton_rms_charge_radius<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::proton_rms_charge_radius<T>::value() ==\n      static_cast<T>(8.414e-16));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::proton_rms_charge_radius<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::proton_rms_charge_radius<\n                 T>::uncertainty() == static_cast<T>(1.9e-18));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::proton_rms_charge_radius<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::proton_rms_charge_radius<\n                    T>::precision()));\n}\n\n// proton-tau mass ratio\n// (0.528051 \u00b1 3.6e-05)\nBOOST_AUTO_TEST_CASE_TEMPLATE(proton_tau_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::proton_tau_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::proton_tau_mass_ratio<T>::value() ==\n      static_cast<T>(0.528051));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::proton_tau_mass_ratio<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::proton_tau_mass_ratio<T>::uncertainty() ==\n      static_cast<T>(3.6e-05));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::proton_tau_mass_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::proton_tau_mass_ratio<T>::precision()));\n}\n\n// quantum of circulation\n// (0.00036369475516 \u00b1 1.1e-13) m^2 s^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(quantum_of_circulation, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::quantum_of_circulation<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::quantum_of_circulation<T>::value() ==\n      static_cast<T>(0.00036369475516));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::quantum_of_circulation<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::quantum_of_circulation<\n                 T>::uncertainty() == static_cast<T>(1.1e-13));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::quantum_of_circulation<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::quantum_of_circulation<T>::precision()));\n}\n\n// quantum of circulation times 2\n// (0.00072738951032 \u00b1 2.2e-13) m^2 s^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(quantum_of_circulation_times_2, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::quantum_of_circulation_times_2<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::quantum_of_circulation_times_2<\n                 T>::value() == static_cast<T>(0.00072738951032));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::quantum_of_circulation_times_2<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::quantum_of_circulation_times_2<\n                 T>::uncertainty() == static_cast<T>(2.2e-13));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::quantum_of_circulation_times_2<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::quantum_of_circulation_times_2<\n          T>::precision()));\n}\n\n// reduced Compton wavelength\n// (3.8615926796e-13 \u00b1 1.2e-22) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(reduced_Compton_wavelength, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::reduced_Compton_wavelength<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::reduced_Compton_wavelength<T>::value() ==\n      static_cast<T>(3.8615926796e-13));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::reduced_Compton_wavelength<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::reduced_Compton_wavelength<\n                 T>::uncertainty() == static_cast<T>(1.2e-22));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::reduced_Compton_wavelength<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::reduced_Compton_wavelength<\n                    T>::precision()));\n}\n\n// reduced muon Compton wavelength\n// (1.867594306e-15 \u00b1 4.2e-23) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(reduced_muon_Compton_wavelength, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::reduced_muon_Compton_wavelength<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::reduced_muon_Compton_wavelength<\n                 T>::value() == static_cast<T>(1.867594306e-15));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::reduced_muon_Compton_wavelength<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::reduced_muon_Compton_wavelength<\n                 T>::uncertainty() == static_cast<T>(4.2e-23));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::reduced_muon_Compton_wavelength<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::reduced_muon_Compton_wavelength<\n          T>::precision()));\n}\n\n// reduced neutron Compton wavelength\n// (2.1001941552e-16 \u00b1 1.2e-25) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(reduced_neutron_Compton_wavelength, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::reduced_neutron_Compton_wavelength<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::reduced_neutron_Compton_wavelength<\n                 T>::value() == static_cast<T>(2.1001941552e-16));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::reduced_neutron_Compton_wavelength<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::reduced_neutron_Compton_wavelength<\n                 T>::uncertainty() == static_cast<T>(1.2e-25));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::reduced_neutron_Compton_wavelength<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::reduced_neutron_Compton_wavelength<\n          T>::precision()));\n}\n\n// reduced Planck constant\n// (1.054571817e-34 \u00b1 0.0) J s\nBOOST_AUTO_TEST_CASE_TEMPLATE(reduced_Planck_constant, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::reduced_Planck_constant<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::reduced_Planck_constant<T>::value() ==\n      static_cast<T>(1.054571817e-34));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::reduced_Planck_constant<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::reduced_Planck_constant<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::reduced_Planck_constant<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::reduced_Planck_constant<T>::precision()));\n}\n\n// reduced Planck constant in eV s\n// (6.582119569e-16 \u00b1 0.0) eV s\nBOOST_AUTO_TEST_CASE_TEMPLATE(reduced_Planck_constant_in_eV_s, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::reduced_Planck_constant_in_eV_s<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::reduced_Planck_constant_in_eV_s<\n                 T>::value() == static_cast<T>(6.582119569e-16));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::reduced_Planck_constant_in_eV_s<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::reduced_Planck_constant_in_eV_s<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::reduced_Planck_constant_in_eV_s<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::reduced_Planck_constant_in_eV_s<\n          T>::precision()));\n}\n\n// reduced Planck constant times c in MeV fm\n// (197.3269804 \u00b1 0.0) MeV fm\nBOOST_AUTO_TEST_CASE_TEMPLATE(reduced_Planck_constant_times_c_in_MeV_fm, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::reduced_Planck_constant_times_c_in_MeV_fm<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::reduced_Planck_constant_times_c_in_MeV_fm<\n          T>::value() == static_cast<T>(197.3269804));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::reduced_Planck_constant_times_c_in_MeV_fm<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::reduced_Planck_constant_times_c_in_MeV_fm<\n          T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::reduced_Planck_constant_times_c_in_MeV_fm<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::reduced_Planck_constant_times_c_in_MeV_fm<\n          T>::precision()));\n}\n\n// reduced proton Compton wavelength\n// (2.10308910336e-16 \u00b1 6.4e-26) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(reduced_proton_Compton_wavelength, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::reduced_proton_Compton_wavelength<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::reduced_proton_Compton_wavelength<\n                 T>::value() == static_cast<T>(2.10308910336e-16));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::reduced_proton_Compton_wavelength<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::reduced_proton_Compton_wavelength<\n                 T>::uncertainty() == static_cast<T>(6.4e-26));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::reduced_proton_Compton_wavelength<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::reduced_proton_Compton_wavelength<\n          T>::precision()));\n}\n\n// reduced tau Compton wavelength\n// (1.110538e-16 \u00b1 7.5e-21) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(reduced_tau_Compton_wavelength, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::reduced_tau_Compton_wavelength<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::reduced_tau_Compton_wavelength<\n                 T>::value() == static_cast<T>(1.110538e-16));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::reduced_tau_Compton_wavelength<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::reduced_tau_Compton_wavelength<\n                 T>::uncertainty() == static_cast<T>(7.5e-21));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::reduced_tau_Compton_wavelength<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::reduced_tau_Compton_wavelength<\n          T>::precision()));\n}\n\n// Rydberg constant\n// (10973731.56816 \u00b1 2.1e-05) m^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(Rydberg_constant, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Rydberg_constant<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::Rydberg_constant<T>::value() ==\n             static_cast<T>(10973731.56816));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Rydberg_constant<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::Rydberg_constant<T>::uncertainty() ==\n      static_cast<T>(2.1e-05));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Rydberg_constant<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::Rydberg_constant<T>::precision()));\n}\n\n// Rydberg constant times c in Hz\n// (3289841960250800.0 \u00b1 6400.0) Hz\nBOOST_AUTO_TEST_CASE_TEMPLATE(Rydberg_constant_times_c_in_Hz, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Rydberg_constant_times_c_in_Hz<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::Rydberg_constant_times_c_in_Hz<\n                 T>::value() == static_cast<T>(3289841960250800.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Rydberg_constant_times_c_in_Hz<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::Rydberg_constant_times_c_in_Hz<\n                 T>::uncertainty() == static_cast<T>(6400.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Rydberg_constant_times_c_in_Hz<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::Rydberg_constant_times_c_in_Hz<\n          T>::precision()));\n}\n\n// Rydberg constant times hc in eV\n// (13.605693122994 \u00b1 2.6e-11) eV\nBOOST_AUTO_TEST_CASE_TEMPLATE(Rydberg_constant_times_hc_in_eV, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Rydberg_constant_times_hc_in_eV<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::Rydberg_constant_times_hc_in_eV<\n                 T>::value() == static_cast<T>(13.605693122994));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Rydberg_constant_times_hc_in_eV<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::Rydberg_constant_times_hc_in_eV<\n                 T>::uncertainty() == static_cast<T>(2.6e-11));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Rydberg_constant_times_hc_in_eV<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::Rydberg_constant_times_hc_in_eV<\n          T>::precision()));\n}\n\n// Rydberg constant times hc in J\n// (2.1798723611035e-18 \u00b1 4.2e-30) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(Rydberg_constant_times_hc_in_J, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Rydberg_constant_times_hc_in_J<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::Rydberg_constant_times_hc_in_J<\n                 T>::value() == static_cast<T>(2.1798723611035e-18));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Rydberg_constant_times_hc_in_J<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::Rydberg_constant_times_hc_in_J<\n                 T>::uncertainty() == static_cast<T>(4.2e-30));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Rydberg_constant_times_hc_in_J<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::Rydberg_constant_times_hc_in_J<\n          T>::precision()));\n}\n\n// Sackur-Tetrode constant (1 K, 100 kPa)\n// (-1.15170753706 \u00b1 4.5e-10)\nBOOST_AUTO_TEST_CASE_TEMPLATE(Sackur_Tetrode_constant_1_K_100_kPa, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Sackur_Tetrode_constant_1_K_100_kPa<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::Sackur_Tetrode_constant_1_K_100_kPa<\n          T>::value() == static_cast<T>(-1.15170753706));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Sackur_Tetrode_constant_1_K_100_kPa<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::Sackur_Tetrode_constant_1_K_100_kPa<\n          T>::uncertainty() == static_cast<T>(4.5e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Sackur_Tetrode_constant_1_K_100_kPa<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::Sackur_Tetrode_constant_1_K_100_kPa<\n          T>::precision()));\n}\n\n// Sackur-Tetrode constant (1 K, 101.325 kPa)\n// (-1.16487052358 \u00b1 4.5e-10)\nBOOST_AUTO_TEST_CASE_TEMPLATE(Sackur_Tetrode_constant_1_K_101325_kPa, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Sackur_Tetrode_constant_1_K_101325_kPa<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::Sackur_Tetrode_constant_1_K_101325_kPa<\n          T>::value() == static_cast<T>(-1.16487052358));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Sackur_Tetrode_constant_1_K_101325_kPa<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::Sackur_Tetrode_constant_1_K_101325_kPa<\n          T>::uncertainty() == static_cast<T>(4.5e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Sackur_Tetrode_constant_1_K_101325_kPa<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::Sackur_Tetrode_constant_1_K_101325_kPa<\n          T>::precision()));\n}\n\n// second radiation constant\n// (0.01438776877 \u00b1 0.0) m K\nBOOST_AUTO_TEST_CASE_TEMPLATE(second_radiation_constant, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::second_radiation_constant<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::second_radiation_constant<T>::value() ==\n      static_cast<T>(0.01438776877));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::second_radiation_constant<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::second_radiation_constant<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::second_radiation_constant<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::second_radiation_constant<\n                    T>::precision()));\n}\n\n// shielded helion gyromag. ratio\n// (203789456.9 \u00b1 2.4) s^-1 T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(shielded_helion_gyromag_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::shielded_helion_gyromag_ratio<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::shielded_helion_gyromag_ratio<\n                 T>::value() == static_cast<T>(203789456.9));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::shielded_helion_gyromag_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::shielded_helion_gyromag_ratio<\n                 T>::uncertainty() == static_cast<T>(2.4));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::shielded_helion_gyromag_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::shielded_helion_gyromag_ratio<\n          T>::precision()));\n}\n\n// shielded helion gyromag. ratio in MHz/T\n// (32.43409942 \u00b1 3.8e-07) MHz T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(shielded_helion_gyromag_ratio_in_MHz_T, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::shielded_helion_gyromag_ratio_in_MHz_T<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::shielded_helion_gyromag_ratio_in_MHz_T<\n          T>::value() == static_cast<T>(32.43409942));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::shielded_helion_gyromag_ratio_in_MHz_T<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::shielded_helion_gyromag_ratio_in_MHz_T<\n          T>::uncertainty() == static_cast<T>(3.8e-07));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::shielded_helion_gyromag_ratio_in_MHz_T<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::shielded_helion_gyromag_ratio_in_MHz_T<\n          T>::precision()));\n}\n\n// shielded helion mag. mom.\n// (-1.07455309e-26 \u00b1 1.3e-34) J T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(shielded_helion_mag_mom, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::shielded_helion_mag_mom<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::shielded_helion_mag_mom<T>::value() ==\n      static_cast<T>(-1.07455309e-26));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::shielded_helion_mag_mom<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::shielded_helion_mag_mom<\n                 T>::uncertainty() == static_cast<T>(1.3e-34));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::shielded_helion_mag_mom<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::shielded_helion_mag_mom<T>::precision()));\n}\n\n// shielded helion mag. mom. to Bohr magneton ratio\n// (-0.001158671471 \u00b1 1.4e-11)\nBOOST_AUTO_TEST_CASE_TEMPLATE(shielded_helion_mag_mom_to_Bohr_magneton_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::\n          shielded_helion_mag_mom_to_Bohr_magneton_ratio<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::\n                 shielded_helion_mag_mom_to_Bohr_magneton_ratio<T>::value() ==\n             static_cast<T>(-0.001158671471));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::\n          shielded_helion_mag_mom_to_Bohr_magneton_ratio<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::\n          shielded_helion_mag_mom_to_Bohr_magneton_ratio<T>::uncertainty() ==\n      static_cast<T>(1.4e-11));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::\n          shielded_helion_mag_mom_to_Bohr_magneton_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::\n          shielded_helion_mag_mom_to_Bohr_magneton_ratio<T>::precision()));\n}\n\n// shielded helion mag. mom. to nuclear magneton ratio\n// (-2.127497719 \u00b1 2.5e-08)\nBOOST_AUTO_TEST_CASE_TEMPLATE(shielded_helion_mag_mom_to_nuclear_magneton_ratio,\n                              T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::\n          shielded_helion_mag_mom_to_nuclear_magneton_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::\n          shielded_helion_mag_mom_to_nuclear_magneton_ratio<T>::value() ==\n      static_cast<T>(-2.127497719));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::\n          shielded_helion_mag_mom_to_nuclear_magneton_ratio<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::\n          shielded_helion_mag_mom_to_nuclear_magneton_ratio<T>::uncertainty() ==\n      static_cast<T>(2.5e-08));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::\n          shielded_helion_mag_mom_to_nuclear_magneton_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::\n          shielded_helion_mag_mom_to_nuclear_magneton_ratio<T>::precision()));\n}\n\n// shielded helion to proton mag. mom. ratio\n// (-0.7617665618 \u00b1 8.9e-09)\nBOOST_AUTO_TEST_CASE_TEMPLATE(shielded_helion_to_proton_mag_mom_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::shielded_helion_to_proton_mag_mom_ratio<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::shielded_helion_to_proton_mag_mom_ratio<\n          T>::value() == static_cast<T>(-0.7617665618));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::shielded_helion_to_proton_mag_mom_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::shielded_helion_to_proton_mag_mom_ratio<\n          T>::uncertainty() == static_cast<T>(8.9e-09));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::shielded_helion_to_proton_mag_mom_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::shielded_helion_to_proton_mag_mom_ratio<\n          T>::precision()));\n}\n\n// shielded helion to shielded proton mag. mom. ratio\n// (-0.7617861313 \u00b1 3.3e-09)\nBOOST_AUTO_TEST_CASE_TEMPLATE(shielded_helion_to_shielded_proton_mag_mom_ratio,\n                              T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::\n          shielded_helion_to_shielded_proton_mag_mom_ratio<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::\n                 shielded_helion_to_shielded_proton_mag_mom_ratio<T>::value() ==\n             static_cast<T>(-0.7617861313));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::\n          shielded_helion_to_shielded_proton_mag_mom_ratio<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::\n          shielded_helion_to_shielded_proton_mag_mom_ratio<T>::uncertainty() ==\n      static_cast<T>(3.3e-09));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::\n          shielded_helion_to_shielded_proton_mag_mom_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::\n          shielded_helion_to_shielded_proton_mag_mom_ratio<T>::precision()));\n}\n\n// shielded proton gyromag. ratio\n// (267515315.1 \u00b1 2.9) s^-1 T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(shielded_proton_gyromag_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::shielded_proton_gyromag_ratio<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::shielded_proton_gyromag_ratio<\n                 T>::value() == static_cast<T>(267515315.1));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::shielded_proton_gyromag_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::shielded_proton_gyromag_ratio<\n                 T>::uncertainty() == static_cast<T>(2.9));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::shielded_proton_gyromag_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::shielded_proton_gyromag_ratio<\n          T>::precision()));\n}\n\n// shielded proton gyromag. ratio in MHz/T\n// (42.57638474 \u00b1 4.6e-07) MHz T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(shielded_proton_gyromag_ratio_in_MHz_T, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::shielded_proton_gyromag_ratio_in_MHz_T<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::shielded_proton_gyromag_ratio_in_MHz_T<\n          T>::value() == static_cast<T>(42.57638474));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::shielded_proton_gyromag_ratio_in_MHz_T<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::shielded_proton_gyromag_ratio_in_MHz_T<\n          T>::uncertainty() == static_cast<T>(4.6e-07));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::shielded_proton_gyromag_ratio_in_MHz_T<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::shielded_proton_gyromag_ratio_in_MHz_T<\n          T>::precision()));\n}\n\n// shielded proton mag. mom.\n// (1.41057056e-26 \u00b1 1.5e-34) J T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(shielded_proton_mag_mom, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::shielded_proton_mag_mom<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::shielded_proton_mag_mom<T>::value() ==\n      static_cast<T>(1.41057056e-26));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::shielded_proton_mag_mom<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::shielded_proton_mag_mom<\n                 T>::uncertainty() == static_cast<T>(1.5e-34));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::shielded_proton_mag_mom<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::shielded_proton_mag_mom<T>::precision()));\n}\n\n// shielded proton mag. mom. to Bohr magneton ratio\n// (0.001520993128 \u00b1 1.7e-11)\nBOOST_AUTO_TEST_CASE_TEMPLATE(shielded_proton_mag_mom_to_Bohr_magneton_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::\n          shielded_proton_mag_mom_to_Bohr_magneton_ratio<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::\n                 shielded_proton_mag_mom_to_Bohr_magneton_ratio<T>::value() ==\n             static_cast<T>(0.001520993128));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::\n          shielded_proton_mag_mom_to_Bohr_magneton_ratio<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::\n          shielded_proton_mag_mom_to_Bohr_magneton_ratio<T>::uncertainty() ==\n      static_cast<T>(1.7e-11));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::\n          shielded_proton_mag_mom_to_Bohr_magneton_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::\n          shielded_proton_mag_mom_to_Bohr_magneton_ratio<T>::precision()));\n}\n\n// shielded proton mag. mom. to nuclear magneton ratio\n// (2.792775599 \u00b1 3e-08)\nBOOST_AUTO_TEST_CASE_TEMPLATE(shielded_proton_mag_mom_to_nuclear_magneton_ratio,\n                              T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::\n          shielded_proton_mag_mom_to_nuclear_magneton_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::\n          shielded_proton_mag_mom_to_nuclear_magneton_ratio<T>::value() ==\n      static_cast<T>(2.792775599));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::\n          shielded_proton_mag_mom_to_nuclear_magneton_ratio<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::\n          shielded_proton_mag_mom_to_nuclear_magneton_ratio<T>::uncertainty() ==\n      static_cast<T>(3e-08));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::\n          shielded_proton_mag_mom_to_nuclear_magneton_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::\n          shielded_proton_mag_mom_to_nuclear_magneton_ratio<T>::precision()));\n}\n\n// shielding difference of d and p in HD\n// (2.02e-08 \u00b1 2e-11)\nBOOST_AUTO_TEST_CASE_TEMPLATE(shielding_difference_of_d_and_p_in_HD, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::shielding_difference_of_d_and_p_in_HD<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::shielding_difference_of_d_and_p_in_HD<\n          T>::value() == static_cast<T>(2.02e-08));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::shielding_difference_of_d_and_p_in_HD<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::shielding_difference_of_d_and_p_in_HD<\n          T>::uncertainty() == static_cast<T>(2e-11));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::shielding_difference_of_d_and_p_in_HD<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::shielding_difference_of_d_and_p_in_HD<\n          T>::precision()));\n}\n\n// shielding difference of t and p in HT\n// (2.414e-08 \u00b1 2e-11)\nBOOST_AUTO_TEST_CASE_TEMPLATE(shielding_difference_of_t_and_p_in_HT, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::shielding_difference_of_t_and_p_in_HT<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::shielding_difference_of_t_and_p_in_HT<\n          T>::value() == static_cast<T>(2.414e-08));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::shielding_difference_of_t_and_p_in_HT<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::shielding_difference_of_t_and_p_in_HT<\n          T>::uncertainty() == static_cast<T>(2e-11));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::shielding_difference_of_t_and_p_in_HT<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::shielding_difference_of_t_and_p_in_HT<\n          T>::precision()));\n}\n\n// speed of light in vacuum\n// (299792458.0 \u00b1 0.0) m s^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(speed_of_light_in_vacuum, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::speed_of_light_in_vacuum<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::speed_of_light_in_vacuum<T>::value() ==\n      static_cast<T>(299792458.0));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::speed_of_light_in_vacuum<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::speed_of_light_in_vacuum<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::speed_of_light_in_vacuum<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::speed_of_light_in_vacuum<\n                    T>::precision()));\n}\n\n// standard acceleration of gravity\n// (9.80665 \u00b1 0.0) m s^-2\nBOOST_AUTO_TEST_CASE_TEMPLATE(standard_acceleration_of_gravity, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::standard_acceleration_of_gravity<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::standard_acceleration_of_gravity<\n                 T>::value() == static_cast<T>(9.80665));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::standard_acceleration_of_gravity<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::standard_acceleration_of_gravity<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::standard_acceleration_of_gravity<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::standard_acceleration_of_gravity<\n          T>::precision()));\n}\n\n// standard atmosphere\n// (101325.0 \u00b1 0.0) Pa\nBOOST_AUTO_TEST_CASE_TEMPLATE(standard_atmosphere, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::standard_atmosphere<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::standard_atmosphere<T>::value() ==\n             static_cast<T>(101325.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::standard_atmosphere<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::standard_atmosphere<T>::uncertainty() ==\n      static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::standard_atmosphere<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::standard_atmosphere<T>::precision()));\n}\n\n// standard-state pressure\n// (100000.0 \u00b1 0.0) Pa\nBOOST_AUTO_TEST_CASE_TEMPLATE(standard_state_pressure, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::standard_state_pressure<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::standard_state_pressure<T>::value() ==\n      static_cast<T>(100000.0));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::standard_state_pressure<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::standard_state_pressure<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::standard_state_pressure<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::standard_state_pressure<T>::precision()));\n}\n\n// Stefan-Boltzmann constant\n// (5.670374419e-08 \u00b1 0.0) W m^-2 K^-4\nBOOST_AUTO_TEST_CASE_TEMPLATE(Stefan_Boltzmann_constant, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Stefan_Boltzmann_constant<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::Stefan_Boltzmann_constant<T>::value() ==\n      static_cast<T>(5.670374419e-08));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::Stefan_Boltzmann_constant<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::Stefan_Boltzmann_constant<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::Stefan_Boltzmann_constant<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::Stefan_Boltzmann_constant<\n                    T>::precision()));\n}\n\n// tau Compton wavelength\n// (6.97771e-16 \u00b1 4.7e-20) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(tau_Compton_wavelength, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::tau_Compton_wavelength<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::tau_Compton_wavelength<T>::value() ==\n      static_cast<T>(6.97771e-16));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::tau_Compton_wavelength<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::tau_Compton_wavelength<\n                 T>::uncertainty() == static_cast<T>(4.7e-20));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::tau_Compton_wavelength<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::tau_Compton_wavelength<T>::precision()));\n}\n\n// tau-electron mass ratio\n// (3477.23 \u00b1 0.23)\nBOOST_AUTO_TEST_CASE_TEMPLATE(tau_electron_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::tau_electron_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::tau_electron_mass_ratio<T>::value() ==\n      static_cast<T>(3477.23));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::tau_electron_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::tau_electron_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(0.23));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::tau_electron_mass_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::tau_electron_mass_ratio<T>::precision()));\n}\n\n// tau energy equivalent\n// (1776.86 \u00b1 0.12) MeV\nBOOST_AUTO_TEST_CASE_TEMPLATE(tau_energy_equivalent, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::tau_energy_equivalent<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::tau_energy_equivalent<T>::value() ==\n      static_cast<T>(1776.86));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::tau_energy_equivalent<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::tau_energy_equivalent<T>::uncertainty() ==\n      static_cast<T>(0.12));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::tau_energy_equivalent<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::tau_energy_equivalent<T>::precision()));\n}\n\n// tau mass\n// (3.16754e-27 \u00b1 2.1e-31) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(tau_mass, T, test_types) {\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::tau_mass<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::tau_mass<T>::value() ==\n             static_cast<T>(3.16754e-27));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::tau_mass<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::tau_mass<T>::uncertainty() ==\n             static_cast<T>(2.1e-31));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::tau_mass<T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::tau_mass<T>::precision()));\n}\n\n// tau mass energy equivalent\n// (2.84684e-10 \u00b1 1.9e-14) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(tau_mass_energy_equivalent, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::tau_mass_energy_equivalent<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::tau_mass_energy_equivalent<T>::value() ==\n      static_cast<T>(2.84684e-10));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::tau_mass_energy_equivalent<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::tau_mass_energy_equivalent<\n                 T>::uncertainty() == static_cast<T>(1.9e-14));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::tau_mass_energy_equivalent<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::tau_mass_energy_equivalent<\n                    T>::precision()));\n}\n\n// tau mass in u\n// (1.90754 \u00b1 0.00013) u\nBOOST_AUTO_TEST_CASE_TEMPLATE(tau_mass_in_u, T, test_types) {\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::tau_mass_in_u<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::tau_mass_in_u<T>::value() ==\n             static_cast<T>(1.90754));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::tau_mass_in_u<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::tau_mass_in_u<T>::uncertainty() ==\n             static_cast<T>(0.00013));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::tau_mass_in_u<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::tau_mass_in_u<T>::precision()));\n}\n\n// tau molar mass\n// (0.00190754 \u00b1 1.3e-07) kg mol^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(tau_molar_mass, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::tau_molar_mass<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::tau_molar_mass<T>::value() ==\n             static_cast<T>(0.00190754));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::tau_molar_mass<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::tau_molar_mass<T>::uncertainty() ==\n             static_cast<T>(1.3e-07));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::tau_molar_mass<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::tau_molar_mass<T>::precision()));\n}\n\n// tau-muon mass ratio\n// (16.817 \u00b1 0.0011)\nBOOST_AUTO_TEST_CASE_TEMPLATE(tau_muon_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::tau_muon_mass_ratio<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::tau_muon_mass_ratio<T>::value() ==\n             static_cast<T>(16.817));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::tau_muon_mass_ratio<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::tau_muon_mass_ratio<T>::uncertainty() ==\n      static_cast<T>(0.0011));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::tau_muon_mass_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::tau_muon_mass_ratio<T>::precision()));\n}\n\n// tau-neutron mass ratio\n// (1.89115 \u00b1 0.00013)\nBOOST_AUTO_TEST_CASE_TEMPLATE(tau_neutron_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::tau_neutron_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::tau_neutron_mass_ratio<T>::value() ==\n      static_cast<T>(1.89115));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::tau_neutron_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::tau_neutron_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(0.00013));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::tau_neutron_mass_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::tau_neutron_mass_ratio<T>::precision()));\n}\n\n// tau-proton mass ratio\n// (1.89376 \u00b1 0.00013)\nBOOST_AUTO_TEST_CASE_TEMPLATE(tau_proton_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::tau_proton_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::tau_proton_mass_ratio<T>::value() ==\n      static_cast<T>(1.89376));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::tau_proton_mass_ratio<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::tau_proton_mass_ratio<T>::uncertainty() ==\n      static_cast<T>(0.00013));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::tau_proton_mass_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::tau_proton_mass_ratio<T>::precision()));\n}\n\n// Thomson cross section\n// (6.6524587321e-29 \u00b1 6e-38) m^2\nBOOST_AUTO_TEST_CASE_TEMPLATE(Thomson_cross_section, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Thomson_cross_section<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::Thomson_cross_section<T>::value() ==\n      static_cast<T>(6.6524587321e-29));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Thomson_cross_section<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::Thomson_cross_section<T>::uncertainty() ==\n      static_cast<T>(6e-38));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Thomson_cross_section<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::Thomson_cross_section<T>::precision()));\n}\n\n// triton-electron mass ratio\n// (5496.92153573 \u00b1 2.7e-07)\nBOOST_AUTO_TEST_CASE_TEMPLATE(triton_electron_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::triton_electron_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::triton_electron_mass_ratio<T>::value() ==\n      static_cast<T>(5496.92153573));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::triton_electron_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::triton_electron_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(2.7e-07));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::triton_electron_mass_ratio<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::triton_electron_mass_ratio<\n                    T>::precision()));\n}\n\n// triton g factor\n// (5.957924931 \u00b1 1.2e-08)\nBOOST_AUTO_TEST_CASE_TEMPLATE(triton_g_factor, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::triton_g_factor<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::triton_g_factor<T>::value() ==\n             static_cast<T>(5.957924931));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::triton_g_factor<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::triton_g_factor<T>::uncertainty() ==\n      static_cast<T>(1.2e-08));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::triton_g_factor<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::triton_g_factor<T>::precision()));\n}\n\n// triton mag. mom.\n// (1.5046095202e-26 \u00b1 3e-35) J T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(triton_mag_mom, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::triton_mag_mom<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::triton_mag_mom<T>::value() ==\n             static_cast<T>(1.5046095202e-26));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::triton_mag_mom<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::triton_mag_mom<T>::uncertainty() ==\n             static_cast<T>(3e-35));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::triton_mag_mom<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::triton_mag_mom<T>::precision()));\n}\n\n// triton mag. mom. to Bohr magneton ratio\n// (0.0016223936651 \u00b1 3.2e-12)\nBOOST_AUTO_TEST_CASE_TEMPLATE(triton_mag_mom_to_Bohr_magneton_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::triton_mag_mom_to_Bohr_magneton_ratio<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::triton_mag_mom_to_Bohr_magneton_ratio<\n          T>::value() == static_cast<T>(0.0016223936651));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::triton_mag_mom_to_Bohr_magneton_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::triton_mag_mom_to_Bohr_magneton_ratio<\n          T>::uncertainty() == static_cast<T>(3.2e-12));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::triton_mag_mom_to_Bohr_magneton_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::triton_mag_mom_to_Bohr_magneton_ratio<\n          T>::precision()));\n}\n\n// triton mag. mom. to nuclear magneton ratio\n// (2.9789624656 \u00b1 5.9e-09)\nBOOST_AUTO_TEST_CASE_TEMPLATE(triton_mag_mom_to_nuclear_magneton_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::triton_mag_mom_to_nuclear_magneton_ratio<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::triton_mag_mom_to_nuclear_magneton_ratio<\n          T>::value() == static_cast<T>(2.9789624656));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::triton_mag_mom_to_nuclear_magneton_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::triton_mag_mom_to_nuclear_magneton_ratio<\n          T>::uncertainty() == static_cast<T>(5.9e-09));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::triton_mag_mom_to_nuclear_magneton_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::triton_mag_mom_to_nuclear_magneton_ratio<\n          T>::precision()));\n}\n\n// triton mass\n// (5.0073567446e-27 \u00b1 1.5e-36) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(triton_mass, T, test_types) {\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::triton_mass<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::triton_mass<T>::value() ==\n             static_cast<T>(5.0073567446e-27));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::triton_mass<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::triton_mass<T>::uncertainty() ==\n             static_cast<T>(1.5e-36));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::triton_mass<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::triton_mass<T>::precision()));\n}\n\n// triton mass energy equivalent\n// (4.500387806e-10 \u00b1 1.4e-19) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(triton_mass_energy_equivalent, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::triton_mass_energy_equivalent<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::triton_mass_energy_equivalent<\n                 T>::value() == static_cast<T>(4.500387806e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::triton_mass_energy_equivalent<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::triton_mass_energy_equivalent<\n                 T>::uncertainty() == static_cast<T>(1.4e-19));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::triton_mass_energy_equivalent<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::triton_mass_energy_equivalent<\n          T>::precision()));\n}\n\n// triton mass energy equivalent in MeV\n// (2808.92113298 \u00b1 8.5e-07) MeV\nBOOST_AUTO_TEST_CASE_TEMPLATE(triton_mass_energy_equivalent_in_MeV, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::triton_mass_energy_equivalent_in_MeV<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::triton_mass_energy_equivalent_in_MeV<\n          T>::value() == static_cast<T>(2808.92113298));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::triton_mass_energy_equivalent_in_MeV<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::triton_mass_energy_equivalent_in_MeV<\n          T>::uncertainty() == static_cast<T>(8.5e-07));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::triton_mass_energy_equivalent_in_MeV<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::triton_mass_energy_equivalent_in_MeV<\n          T>::precision()));\n}\n\n// triton mass in u\n// (3.01550071621 \u00b1 1.2e-10) u\nBOOST_AUTO_TEST_CASE_TEMPLATE(triton_mass_in_u, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::triton_mass_in_u<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::triton_mass_in_u<T>::value() ==\n             static_cast<T>(3.01550071621));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::triton_mass_in_u<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::triton_mass_in_u<T>::uncertainty() ==\n      static_cast<T>(1.2e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::triton_mass_in_u<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::triton_mass_in_u<T>::precision()));\n}\n\n// triton molar mass\n// (0.00301550071517 \u00b1 9.2e-13) kg mol^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(triton_molar_mass, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::triton_molar_mass<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::triton_molar_mass<T>::value() ==\n             static_cast<T>(0.00301550071517));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::triton_molar_mass<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::triton_molar_mass<T>::uncertainty() ==\n      static_cast<T>(9.2e-13));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::triton_molar_mass<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::triton_molar_mass<T>::precision()));\n}\n\n// triton-proton mass ratio\n// (2.99371703414 \u00b1 1.5e-10)\nBOOST_AUTO_TEST_CASE_TEMPLATE(triton_proton_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::triton_proton_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::triton_proton_mass_ratio<T>::value() ==\n      static_cast<T>(2.99371703414));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::triton_proton_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::triton_proton_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(1.5e-10));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::triton_proton_mass_ratio<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::triton_proton_mass_ratio<\n                    T>::precision()));\n}\n\n// triton relative atomic mass\n// (3.01550071621 \u00b1 1.2e-10)\nBOOST_AUTO_TEST_CASE_TEMPLATE(triton_relative_atomic_mass, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::triton_relative_atomic_mass<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::triton_relative_atomic_mass<T>::value() ==\n      static_cast<T>(3.01550071621));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::triton_relative_atomic_mass<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::triton_relative_atomic_mass<\n                 T>::uncertainty() == static_cast<T>(1.2e-10));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::triton_relative_atomic_mass<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::triton_relative_atomic_mass<\n                    T>::precision()));\n}\n\n// triton to proton mag. mom. ratio\n// (1.0666399191 \u00b1 2.1e-09)\nBOOST_AUTO_TEST_CASE_TEMPLATE(triton_to_proton_mag_mom_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::triton_to_proton_mag_mom_ratio<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::triton_to_proton_mag_mom_ratio<\n                 T>::value() == static_cast<T>(1.0666399191));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::triton_to_proton_mag_mom_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::triton_to_proton_mag_mom_ratio<\n                 T>::uncertainty() == static_cast<T>(2.1e-09));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::triton_to_proton_mag_mom_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::triton_to_proton_mag_mom_ratio<\n          T>::precision()));\n}\n\n// unified atomic mass unit\n// (1.6605390666e-27 \u00b1 5e-37) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(unified_atomic_mass_unit, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::unified_atomic_mass_unit<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::unified_atomic_mass_unit<T>::value() ==\n      static_cast<T>(1.6605390666e-27));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::unified_atomic_mass_unit<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::unified_atomic_mass_unit<\n                 T>::uncertainty() == static_cast<T>(5e-37));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::unified_atomic_mass_unit<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2018::unified_atomic_mass_unit<\n                    T>::precision()));\n}\n\n// vacuum electric permittivity\n// (8.8541878128e-12 \u00b1 1.3e-21) F m^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(vacuum_electric_permittivity, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::vacuum_electric_permittivity<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::vacuum_electric_permittivity<\n                 T>::value() == static_cast<T>(8.8541878128e-12));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::vacuum_electric_permittivity<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::vacuum_electric_permittivity<\n                 T>::uncertainty() == static_cast<T>(1.3e-21));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::vacuum_electric_permittivity<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::vacuum_electric_permittivity<\n          T>::precision()));\n}\n\n// vacuum mag. permeability\n// (1.25663706212e-06 \u00b1 1.9e-16) N A^-2\nBOOST_AUTO_TEST_CASE_TEMPLATE(vacuum_mag_permeability, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::vacuum_mag_permeability<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::vacuum_mag_permeability<T>::value() ==\n      static_cast<T>(1.25663706212e-06));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2018::vacuum_mag_permeability<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2018::vacuum_mag_permeability<\n                 T>::uncertainty() == static_cast<T>(1.9e-16));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::vacuum_mag_permeability<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::vacuum_mag_permeability<T>::precision()));\n}\n\n// von Klitzing constant\n// (25812.80745 \u00b1 0.0) ohm\nBOOST_AUTO_TEST_CASE_TEMPLATE(von_Klitzing_constant, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::von_Klitzing_constant<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::von_Klitzing_constant<T>::value() ==\n      static_cast<T>(25812.80745));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::von_Klitzing_constant<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::von_Klitzing_constant<T>::uncertainty() ==\n      static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::von_Klitzing_constant<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::von_Klitzing_constant<T>::precision()));\n}\n\n// weak mixing angle\n// (0.2229 \u00b1 0.0003)\nBOOST_AUTO_TEST_CASE_TEMPLATE(weak_mixing_angle, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::weak_mixing_angle<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::weak_mixing_angle<T>::value() ==\n             static_cast<T>(0.2229));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::weak_mixing_angle<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::weak_mixing_angle<T>::uncertainty() ==\n      static_cast<T>(0.0003));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::weak_mixing_angle<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::weak_mixing_angle<T>::precision()));\n}\n\n// Wien frequency displacement law constant\n// (58789257570.0 \u00b1 0.0) Hz K^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(Wien_frequency_displacement_law_constant, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Wien_frequency_displacement_law_constant<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::Wien_frequency_displacement_law_constant<\n          T>::value() == static_cast<T>(58789257570.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Wien_frequency_displacement_law_constant<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::Wien_frequency_displacement_law_constant<\n          T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Wien_frequency_displacement_law_constant<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::Wien_frequency_displacement_law_constant<\n          T>::precision()));\n}\n\n// Wien wavelength displacement law constant\n// (0.002897771955 \u00b1 0.0) m K\nBOOST_AUTO_TEST_CASE_TEMPLATE(Wien_wavelength_displacement_law_constant, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Wien_wavelength_displacement_law_constant<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::Wien_wavelength_displacement_law_constant<\n          T>::value() == static_cast<T>(0.002897771955));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Wien_wavelength_displacement_law_constant<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::Wien_wavelength_displacement_law_constant<\n          T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::Wien_wavelength_displacement_law_constant<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::Wien_wavelength_displacement_law_constant<\n          T>::precision()));\n}\n\n// W to Z mass ratio\n// (0.88153 \u00b1 0.00017)\nBOOST_AUTO_TEST_CASE_TEMPLATE(W_to_Z_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::W_to_Z_mass_ratio<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2018::W_to_Z_mass_ratio<T>::value() ==\n             static_cast<T>(0.88153));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::W_to_Z_mass_ratio<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2018::W_to_Z_mass_ratio<T>::uncertainty() ==\n      static_cast<T>(0.00017));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2018::W_to_Z_mass_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2018::W_to_Z_mass_ratio<T>::precision()));\n}\n", "meta": {"hexsha": "e054624bb5fd22be46be5055cf91bdefb6db8dd5", "size": 322431, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/codata_2018.cpp", "max_stars_repo_name": "rmlmcfadden/triumfpp", "max_stars_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/codata_2018.cpp", "max_issues_repo_name": "rmlmcfadden/triumfpp", "max_issues_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_issues_repo_licenses": ["MIT"], "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/codata_2018.cpp", "max_forks_repo_name": "rmlmcfadden/triumfpp", "max_forks_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_forks_repo_licenses": ["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.75505496, "max_line_length": 80, "alphanum_fraction": 0.6914316551, "num_tokens": 91776, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.48955301534734214}}
{"text": "#ifndef INCLUDED_STDDEFX\n#include \"stddefx.h\"\n#define INCLUDED_STDDEFX\n#endif\n\n#ifndef INCLUDED_GEO_CIRCULARNEIGHBOURHOOD\n#include \"geo_circularneighbourhood.h\"\n#define INCLUDED_GEO_CIRCULARNEIGHBOURHOOD\n#endif\n\n// Library headers.\n#ifndef INCLUDED_BOOST_NONCOPYABLE\n#include <boost/noncopyable.hpp>\n#define INCLUDED_BOOST_NONCOPYABLE\n#endif\n#ifndef INCLUDED_BOOST_MATH_SPECIAL_FUNCTIONS_ROUND\n#include <boost/math/special_functions/round.hpp>\n#define INCLUDED_BOOST_MATH_SPECIAL_FUNCTIONS_ROUND\n#endif\n\n// PCRaster library headers.\n\n// Module headers.\n#ifndef INCLUDED_GEO_SCANCONVERSION\n#include \"geo_scanconversion.h\"\n#define INCLUDED_GEO_SCANCONVERSION\n#endif\n\n\n\n/*!\n  \\file\n  This file contains the implementation of the CircularNeighbourhood class.\n*/\n\n\n\n//------------------------------------------------------------------------------\n\n/*\nnamespace geo {\n\nclass CircularNeighbourhoodPrivate\n{\npublic:\n\n  CircularNeighbourhoodPrivate()\n  {\n  }\n\n  ~CircularNeighbourhoodPrivate()\n  {\n  }\n\n};\n\n} // namespace geo\n*/\n\n\n\n//------------------------------------------------------------------------------\n// DEFINITION OF STATIC CIRCULARNEIGHBOURHOOD MEMBERS\n//------------------------------------------------------------------------------\n\n\n\n//------------------------------------------------------------------------------\n// DEFINITION OF CIRCULARNEIGHBOURHOOD MEMBERS\n//------------------------------------------------------------------------------\n\ngeo::CircularNeighbourhood::CircularNeighbourhood(double radius)\n\n  : Neighbourhood(radius)\n\n{\n  init();\n}\n\n\n\ngeo::CircularNeighbourhood::CircularNeighbourhood(double fromRadius,\n         double toRadius)\n\n  : Neighbourhood(fromRadius, toRadius)\n\n{\n  init();\n}\n\n\n\ngeo::CircularNeighbourhood::~CircularNeighbourhood()\n{\n}\n\n\n\nnamespace geo {\n\nclass SetRaster: public boost::noncopyable {\n\nprivate:\n\n  SimpleRaster<double>& d_raster;\n\npublic:\n\n  SetRaster(SimpleRaster<double>& raster)\n    : d_raster(raster)\n  {\n  }\n\n  bool operator()(size_t col, size_t row) {\n    d_raster.cell(row, col) = 1.0;\n    return true;\n  }\n};\n\n}\n\n\n\nvoid geo::CircularNeighbourhood::init()\n{\n  SetRaster setRaster(*this);\n  using namespace boost::math;\n\n  if(isOutline()) {\n    midpointCircle<int, SetRaster>(\n         static_cast<size_t>(round(toRadius())),\n         static_cast<size_t>(round(toRadius())),\n         static_cast<size_t>(round(toRadius())),\n         setRaster);\n  }\n  else {\n    midpointCircle<int, SetRaster>(\n         static_cast<size_t>(round(toRadius())),\n         static_cast<size_t>(round(toRadius())),\n         static_cast<size_t>(round(fromRadius())),\n         static_cast<size_t>(round(toRadius())),\n         setRaster);\n  }\n}\n\n\n\n//------------------------------------------------------------------------------\n// DEFINITION OF FREE OPERATORS\n//------------------------------------------------------------------------------\n\n\n\n//------------------------------------------------------------------------------\n// DEFINITION OF FREE FUNCTIONS\n//------------------------------------------------------------------------------\n\n\n\n", "meta": {"hexsha": "21d476b5fcb7a2c7e0141063771a2c37b8cce0b7", "size": 3075, "ext": "cc", "lang": "C++", "max_stars_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcrgeo/geo_circularneighbourhood.cc", "max_stars_repo_name": "quanpands/wflow", "max_stars_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcrgeo/geo_circularneighbourhood.cc", "max_issues_repo_name": "quanpands/wflow", "max_issues_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcrgeo/geo_circularneighbourhood.cc", "max_forks_repo_name": "quanpands/wflow", "max_forks_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.21875, "max_line_length": 80, "alphanum_fraction": 0.5505691057, "num_tokens": 580, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.4895530096757609}}
{"text": "#ifndef INCLUDE_MIMKL_MODELS_EASY_MKL_HPP_\n#define INCLUDE_MIMKL_MODELS_EASY_MKL_HPP_\n\n#include <Eigen/StdVector>\n#include <mimkl/data_structures.hpp>\n#include <mimkl/definitions.hpp>\n#include <mimkl/linear_algebra.hpp>\n#include <mimkl/models/model.hpp>\n#include <mimkl/solvers.hpp>\n#include <spdlog/fmt/ostr.h>\n#include <spdlog/spdlog.h>\n\nusing mimkl::definitions::Indexing;\n\nnamespace mimkl\n{\nnamespace models\n{\n\nstatic std::shared_ptr<spdlog::logger> logger_easy_mkl =\nspdlog::stdout_color_mt(\"EasyMKL\");\n\ntemplate <typename Scalar, typename Kernel>\nclass EasyMKL : public Model<Scalar, Kernel>\n{\n\n    private:\n    // inheritance of templatized base members\n    using Model<Scalar, Kernel>::_kernels_handler;\n    using Model<Scalar, Kernel>::_trained;\n    using Model<Scalar, Kernel>::_precompute;\n    using Model<Scalar, Kernel>::_trace_normalization;\n    using Model<Scalar, Kernel>::_number_of_support_vectors;\n    using Model<Scalar, Kernel>::_number_of_kernels;\n\n    // logger instance\n    std::shared_ptr<spdlog::logger> _logger = spdlog::get(\"EasyMKL\");\n    // typedefs\n    typedef MATRIX(Scalar) Matrix;\n    typedef COLUMN(Scalar) Column;\n    typedef ROW(Scalar) Row;\n    typedef Eigen::Map<Column> MapColumn;\n\n    // parameters\n    double _lambda = 0.8;\n    double _epsilon = 0.0001;\n    bool _regularization_factor = false;\n\n    Matrix _gammas;\n    Matrix _etas;\n    Row _biases;\n    Indexing _class_map;\n\n    std::vector<std::string> _unique_labels;\n    Index _number_of_classes;\n    Index _number_of_dichotomies;\n    bool _binary;\n    Matrix _kernels_sum;\n\n    Column get_dichotomy(const std::string &);\n    std::pair<Column, Column>\n    optimize_gamma(const bool &, const Column &, const Column & = Column());\n    Column compute_weights(const Column &);\n    Scalar compute_bias(const Column &, const Column &, const Column &);\n\n    void setup(std::vector<std::string>);\n    void train(const Index &);\n    void fit(const std::vector<std::string> &);\n    Matrix decision_function();\n    Column\n    distances(const Column &, const Column &, const Column &, const Scalar &);\n\n    public:\n    EasyMKL(const std::vector<Kernel> & = std::vector<Kernel>(),\n            const bool precompute = true,\n            const bool trace_normalization = true,\n            const double lambda = 0.8,\n            const double epsilon = 0.0001,\n            const bool regularization_factor = false);\n    EasyMKL(const std::vector<Matrix> & = std::vector<Matrix>(),\n            const bool precompute = true,\n            const bool trace_normalization = true,\n            const double lambda = 0.8,\n            const double epsilon = 0.0001,\n            const bool regularization_factor = false);\n\n    // Functional, call with data matrix\n    void fit(const Matrix &, const std::vector<std::string> &);\n    std::vector<std::string> predict(const Matrix &);\n    Matrix predict_proba(const Matrix &);\n    Matrix decision_function(const Matrix &);\n    // Matricial, call with kernel matrices\n    void fit(const std::vector<Matrix> &, const std::vector<std::string> &);\n    std::vector<std::string> predict(const std::vector<Matrix> &);\n    Matrix predict_proba(const std::vector<Matrix> &);\n    Matrix decision_function(const std::vector<Matrix> &);\n\n    double get_lambda() const;\n    double get_epsilon() const;\n    bool get_regularization_factor() const;\n    Matrix get_gammas() const;\n    Matrix get_etas() const;\n    Row get_biases() const;\n    Indexing get_class_map() const;\n    std::vector<std::string> get_one_versus_rest_order() const;\n    Matrix get_optimal_kernel();\n    Matrix get_optimal_kernel_by_class_index(const Index i);\n    std::vector<Matrix> get_optimal_kernels();\n\n    void set_lambda(const double);\n    void set_epsilon(const double);\n    void set_regularization_factor(const bool);\n    void set_parameters(const double,\n                        const double epsilon = 0.0001,\n                        const bool regularization_factor = false);\n    void set_gammas(const Matrix &);\n    void set_etas(const Matrix &);\n    void set_biases(const Row &);\n    void set_class_map(const Indexing &);\n};\n\ntemplate <typename Scalar, typename Kernel>\nEasyMKL<Scalar, Kernel>::EasyMKL(const std::vector<Kernel> &kernel_functions,\n                                 const bool precompute,\n                                 const bool trace_normalization,\n                                 const double lambda,\n                                 const double epsilon,\n                                 const bool regularization_factor)\n: Model<Scalar, Kernel>(kernel_functions, precompute, trace_normalization)\n{\n    set_parameters(lambda, epsilon, regularization_factor);\n}\n\ntemplate <typename Scalar, typename Kernel>\nEasyMKL<Scalar, Kernel>::EasyMKL(const std::vector<Matrix> &kernel_matrices,\n                                 const bool precompute,\n                                 const bool trace_normalization,\n                                 const double lambda,\n                                 const double epsilon,\n                                 const bool regularization_factor)\n: Model<Scalar, Kernel>(kernel_matrices, precompute, trace_normalization)\n{\n    set_parameters(lambda, epsilon, regularization_factor);\n}\n\ntemplate <typename Scalar, typename Kernel>\ntypename EasyMKL<Scalar, Kernel>::Column\nEasyMKL<Scalar, Kernel>::get_dichotomy(const std::string &label)\n{\n    auto range = _class_map.equal_range(label);\n    Column y = Column::Constant(_number_of_support_vectors, 1, -1);\n    for (auto i = range.first; i != range.second; ++i)\n    {\n        y(i->second) = 1;\n    }\n    return y;\n}\n\ntemplate <typename Scalar, typename Kernel>\nstd::pair<typename EasyMKL<Scalar, Kernel>::Column,\n          typename EasyMKL<Scalar, Kernel>::Column>\nEasyMKL<Scalar, Kernel>::optimize_gamma(const bool &regularization_factor,\n                                        const Column &y,\n                                        const Column &eta)\n{\n    mimkl::solvers::KOMD<Scalar> optimizer((eta.rows() > 0) ?\n                                           _kernels_handler.sum(eta) :\n                                           _kernels_sum,\n                                           _lambda, _epsilon,\n                                           regularization_factor);\n    optimizer.solve(y);\n    Column gamma = optimizer.get_result();\n    return std::make_pair(gamma, y.cwiseProduct(gamma));\n}\n\ntemplate <typename Scalar, typename Kernel>\ntypename EasyMKL<Scalar, Kernel>::Column\nEasyMKL<Scalar, Kernel>::compute_weights(const Column &directed_gamma)\n{\n    // TODO maybe after all gammas are known and then compute etas rowwise, so\n    // we\n    // compute each kernel once? ->cycle through directed_gamma instead of\n    // through\n    // kernels\n    Column eta = Column::Constant(_number_of_kernels, 1, 0.0);\n    for (Index eta_index = 0; eta_index < _number_of_kernels; ++eta_index)\n    {\n        // compute current kernel matrix K\n        _logger->trace(\"base kernel :\\n{}\", _kernels_handler[eta_index]);\n        eta(eta_index) = directed_gamma.transpose() *\n                         _kernels_handler[eta_index] * directed_gamma;\n\n        _logger->trace(\"d(y)_r :\\n{}\", eta(eta_index));\n    }\n    _logger->trace(\"pre norming eta :\\n{}\", eta);\n    eta /=\n    eta.sum(); // l1-norm, as eta_i is >=0 by construction ( kernels are SDP)\n    _logger->trace(\"eta :\\n{}\", eta);\n    _logger->debug(\"compute_weights() done\");\n    return eta;\n}\n\ntemplate <typename Scalar, typename Kernel>\nScalar EasyMKL<Scalar, Kernel>::compute_bias(const Column &gamma,\n                                             const Column &directed_gamma,\n                                             const Column &eta)\n{\n    return 0.5 * gamma.transpose() * (_kernels_handler.sum(eta)) * directed_gamma;\n}\n\ntemplate <typename Scalar, typename Kernel>\nvoid EasyMKL<Scalar, Kernel>::setup(std::vector<std::string> labels)\n{\n    _logger->debug(\"setup() start\");\n    _number_of_support_vectors = _kernels_handler.get_lhs_size();\n    _number_of_kernels = _kernels_handler.get_number_of_kernels();\n    if (_number_of_support_vectors != labels.size())\n        throw std::length_error(\"sample size and lables size do not match\");\n\n    // manage labels\n    _class_map = mimkl::data_structures::indexing_from_vector_of_strings(labels);\n\n    std::sort(labels.begin(), labels.end()); // pass labels as value\n    _unique_labels = labels;\n    auto last = std::unique(_unique_labels.begin(), _unique_labels.end());\n    _unique_labels.erase(last, _unique_labels.end());\n    _number_of_classes = _unique_labels.size();\n    _binary = _number_of_classes < 3;\n\n    // treat the binary classification case\n    _number_of_dichotomies = _binary ? 1 : _number_of_classes;\n    _logger->debug(\"is binary : {}\", _binary);\n    _logger->debug(\"numer of dichotomies: {}\", _number_of_dichotomies);\n\n    _gammas.resize(_number_of_support_vectors, _number_of_dichotomies);\n    _etas.resize(_number_of_kernels, _number_of_dichotomies);\n    _biases.resize(1, _number_of_dichotomies);\n\n    _kernels_sum = _kernels_handler.sum();\n    _logger->debug(\"setup() done\");\n}\n\ntemplate <typename Scalar, typename Kernel>\nvoid EasyMKL<Scalar, Kernel>::train(const Index &class_index)\n{\n    Column y = get_dichotomy(_unique_labels[class_index]);\n    _logger->debug(\"get_dichotomy() done\");\n    // gamma on plain sum\n    std::pair<Column, Column> gamma_pair =\n    optimize_gamma(_regularization_factor, y);\n    _logger->debug(\"optimize_gamma() done\");\n    Column eta = compute_weights(gamma_pair.second);\n    _logger->debug(\"compute_weights() done\");\n    // gamma on weighted sum, like KOMD on given kernel\n    gamma_pair = optimize_gamma(false, y, eta);\n    _logger->debug(\"optimize_gamma() weighted done\");\n    Scalar bias = compute_bias(gamma_pair.first, gamma_pair.second, eta);\n    _logger->debug(\"compute_bias() done\");\n\n    // update state for the given dichotomy\n    _gammas.col(class_index) << gamma_pair.first;\n    _etas.col(class_index) << eta;\n    _biases.col(class_index) << bias;\n}\n\ntemplate <typename Scalar, typename Kernel>\nvoid EasyMKL<Scalar, Kernel>::fit(const std::vector<std::string> &labels)\n{\n    _logger->debug(\"fit() start\");\n    setup(labels);\n    // or iterate over class_index?\n    for (Index i = 0; i < _number_of_dichotomies; ++i)\n        train(i);\n    _trained = true;\n    _logger->debug(\"fit() done\");\n}\n\ntemplate <typename Scalar, typename Kernel>\nvoid EasyMKL<Scalar, Kernel>::fit(const Matrix &X,\n                                  const std::vector<std::string> &labels)\n{\n    _logger->debug(\"fit() data start\");\n    _kernels_handler.set_lhs(X);\n    fit(labels);\n    _logger->debug(\"fit() data done\");\n}\n\ntemplate <typename Scalar, typename Kernel>\nvoid EasyMKL<Scalar, Kernel>::fit(const std::vector<Matrix> &kernel_matrices,\n                                  const std::vector<std::string> &labels)\n{\n    _logger->debug(\"fit() kernel matrices start\");\n    _kernels_handler.set_matrices(kernel_matrices, true);\n    fit(labels);\n    _logger->debug(\"fit() kernel matrices done\");\n}\n\ntemplate <typename Scalar, typename Kernel>\ntypename EasyMKL<Scalar, Kernel>::Column EasyMKL<Scalar, Kernel>::distances(\nconst Column &y, const Column &gamma, const Column &eta, const Scalar &bias)\n{\n    _logger->debug(\"about to break?\");\n    return (_kernels_handler.sum(eta).transpose() * y.cwiseProduct(gamma)).array() -\n           bias;\n}\n\ntemplate <typename Scalar, typename Kernel>\ntypename EasyMKL<Scalar, Kernel>::Matrix\nEasyMKL<Scalar, Kernel>::decision_function()\n{\n    Matrix D(_kernels_handler.get_rhs_size(), _number_of_classes);\n    _logger->debug(\"decision_function() start\");\n    for (Index i = 0; i < _number_of_dichotomies; ++i)\n    {\n        D.col(i) << distances(get_dichotomy(_unique_labels[i]), _gammas.col(i),\n                              _etas.col(i), _biases(i));\n    }\n    if (_binary)\n    {\n        D.col(1) << -D.col(0);\n    }\n    _logger->debug(\"decision_function() done\");\n    return D;\n}\n\ntemplate <typename Scalar, typename Kernel>\ntypename EasyMKL<Scalar, Kernel>::Matrix\nEasyMKL<Scalar, Kernel>::decision_function(const Matrix &X)\n{\n    if (!_trained)\n        throw std::logic_error(\"The model should be trained first (after \"\n                               \"instantiation or change in parameters)\");\n    _kernels_handler.set_rhs(X);\n    return decision_function();\n}\n\ntemplate <typename Scalar, typename Kernel>\ntypename EasyMKL<Scalar, Kernel>::Matrix\nEasyMKL<Scalar, Kernel>::decision_function(const std::vector<Matrix> &kernel_matrices)\n{\n    if (!_trained)\n        throw std::logic_error(\"The model should be trained first (after \"\n                               \"instantiation or change in parameters)\");\n    if (kernel_matrices[0].rows() != _number_of_support_vectors)\n        throw std::length_error(\"Similarities must be provided for all support \"\n                                \"vectors; matrices have wrong number of rows.\");\n    if (kernel_matrices.size() != _number_of_kernels)\n        throw std::length_error(\n        \"Same number of kernels as on training is required\");\n    _kernels_handler.set_matrices(kernel_matrices);\n    return decision_function();\n}\n\ntemplate <typename Scalar, typename Kernel>\nstd::vector<std::string>\nEasyMKL<Scalar, Kernel>::predict(const std::vector<Matrix> &kernel_matrices)\n{\n    _logger->debug(\"predict() matricial start\");\n    Matrix D = decision_function(kernel_matrices);\n    std::vector<std::string> prediction;\n    prediction.reserve(_kernels_handler.get_rhs_size());\n    // argmax\n    typename Matrix::Index max_index;\n    for (Index i = 0; i < _kernels_handler.get_rhs_size(); ++i)\n    {\n        D.row(i).maxCoeff(&max_index);\n        _logger->trace(\"max_index[{}]:\\t {}\", i, max_index);\n        prediction.push_back(_unique_labels[max_index]);\n    }\n    _logger->debug(\"predict() matricial done\");\n    return prediction;\n}\n\ntemplate <typename Scalar, typename Kernel>\nstd::vector<std::string> EasyMKL<Scalar, Kernel>::predict(const Matrix &X)\n{\n    _logger->debug(\"predict() functional start\");\n    Matrix D = decision_function(X);\n    std::vector<std::string> prediction;\n    prediction.reserve(_kernels_handler.get_rhs_size());\n    // argmax\n    typename Matrix::Index max_index;\n    for (Index i = 0; i < _kernels_handler.get_rhs_size(); ++i)\n    {\n        D.row(i).maxCoeff(&max_index);\n        _logger->trace(\"max_index[{}]:\\t {}\", i, max_index);\n        prediction.push_back(_unique_labels[max_index]);\n    }\n    _logger->debug(\"predict() functional done\");\n    return prediction;\n}\n\ntemplate <typename Scalar, typename Kernel>\ntypename EasyMKL<Scalar, Kernel>::Matrix\nEasyMKL<Scalar, Kernel>::predict_proba(const std::vector<Matrix> &kernel_matrices)\n{\n    _logger->debug(\"predict_proba() matricial done\");\n    Matrix D = decision_function(kernel_matrices);\n    _logger->debug(\"predict_proba() matricial done\");\n    return mimkl::linear_algebra::rowwise_soft_max(D);\n}\n\ntemplate <typename Scalar, typename Kernel>\ntypename EasyMKL<Scalar, Kernel>::Matrix\nEasyMKL<Scalar, Kernel>::predict_proba(const Matrix &X)\n{\n    _logger->debug(\"predict_proba() functional done\");\n    Matrix D = decision_function(X);\n    _logger->debug(\"predict_proba() functional done\");\n    return mimkl::linear_algebra::rowwise_soft_max(D);\n}\n\ntemplate <typename Scalar, typename Kernel>\ndouble EasyMKL<Scalar, Kernel>::get_lambda() const\n{\n    return _lambda;\n}\n\ntemplate <typename Scalar, typename Kernel>\ndouble EasyMKL<Scalar, Kernel>::get_epsilon() const\n{\n    return _epsilon;\n}\n\ntemplate <typename Scalar, typename Kernel>\nbool EasyMKL<Scalar, Kernel>::get_regularization_factor() const\n{\n    return _regularization_factor;\n}\n\ntemplate <typename Scalar, typename Kernel>\ntypename EasyMKL<Scalar, Kernel>::Matrix EasyMKL<Scalar, Kernel>::get_gammas() const\n{\n    return _gammas;\n}\n\ntemplate <typename Scalar, typename Kernel>\ntypename EasyMKL<Scalar, Kernel>::Matrix EasyMKL<Scalar, Kernel>::get_etas() const\n{\n    return _etas;\n}\n\ntemplate <typename Scalar, typename Kernel>\ntypename EasyMKL<Scalar, Kernel>::Row EasyMKL<Scalar, Kernel>::get_biases() const\n{\n    return _biases;\n}\n\ntemplate <typename Scalar, typename Kernel>\nIndexing EasyMKL<Scalar, Kernel>::get_class_map() const\n{\n    return _class_map;\n}\n\ntemplate <typename Scalar, typename Kernel>\nstd::vector<std::string> EasyMKL<Scalar, Kernel>::get_one_versus_rest_order() const\n{\n    return _unique_labels;\n}\n\ntemplate <typename Scalar, typename Kernel>\ntypename EasyMKL<Scalar, Kernel>::Matrix\nEasyMKL<Scalar, Kernel>::get_optimal_kernel()\n{\n    if (!_trained)\n        throw std::logic_error(\n        \"The model has not been fit, kernel weights are undetermined\");\n    return _kernels_handler.sum(\n    _etas.rowwise().mean()); // TODO treat exception for binary problem\n}\n\ntemplate <typename Scalar, typename Kernel>\ntypename EasyMKL<Scalar, Kernel>::Matrix\nEasyMKL<Scalar, Kernel>::get_optimal_kernel_by_class_index(const Index i)\n{\n    if (!_trained)\n        throw std::logic_error(\n        \"The model has not been fit, kernel weights are undetermined\");\n    return _kernels_handler.sum(_etas.col(i));\n}\n\ntemplate <typename Scalar, typename Kernel>\nstd::vector<typename EasyMKL<Scalar, Kernel>::Matrix>\nEasyMKL<Scalar, Kernel>::get_optimal_kernels()\n{\n    if (!_trained)\n        throw std::logic_error(\n        \"The model has not been fit, kernel weights are undetermined\");\n    std::vector<Matrix> all_optimal_kernels;\n    all_optimal_kernels.reserve(_number_of_dichotomies);\n    for (Index i = 0; i < _number_of_dichotomies; ++i)\n        all_optimal_kernels.push_back(_kernels_handler.sum(_etas.col(i)));\n    return all_optimal_kernels;\n}\n\ntemplate <typename Scalar, typename Kernel>\nvoid EasyMKL<Scalar, Kernel>::set_lambda(const double lambda)\n{\n    _lambda = lambda;\n    _trained = false;\n    _logger->debug(\"changing parameters requires refitting before prediction\");\n}\n\ntemplate <typename Scalar, typename Kernel>\nvoid EasyMKL<Scalar, Kernel>::set_epsilon(const double epsilon)\n{\n    _epsilon = epsilon;\n    _trained = false;\n    _logger->debug(\"changing parameters requires refitting before prediction\");\n}\n\ntemplate <typename Scalar, typename Kernel>\nvoid EasyMKL<Scalar, Kernel>::set_regularization_factor(\nconst bool regularization_factor)\n{\n    _regularization_factor = regularization_factor;\n    _trained = false;\n    _logger->debug(\"changing parameters requires refitting before prediction\");\n}\n\ntemplate <typename Scalar, typename Kernel>\nvoid EasyMKL<Scalar, Kernel>::set_parameters(const double lambda,\n                                             const double epsilon,\n                                             const bool regularization_factor)\n{\n    _lambda = lambda;\n    _epsilon = epsilon;\n    _regularization_factor = regularization_factor;\n    _trained = false;\n    _logger->debug(\"changing parameters requires refitting before prediction\");\n    _logger->debug(\"lambda:\\n{}\", _lambda);\n    _logger->debug(\"epsilon:\\n{}\", _epsilon);\n}\n\ntemplate <typename Scalar, typename Kernel>\nvoid EasyMKL<Scalar, Kernel>::set_gammas(const Matrix &gammas)\n{\n    _gammas = gammas;\n};\n\ntemplate <typename Scalar, typename Kernel>\nvoid EasyMKL<Scalar, Kernel>::set_etas(const Matrix &etas)\n{\n    _etas = etas;\n};\n\ntemplate <typename Scalar, typename Kernel>\nvoid EasyMKL<Scalar, Kernel>::set_biases(const Row &biases)\n{\n    _biases = biases;\n};\n\ntemplate <typename Scalar, typename Kernel>\nvoid EasyMKL<Scalar, Kernel>::set_class_map(const Indexing &class_map)\n{\n    _class_map = class_map;\n    // get companion objects\n    std::vector<std::string> labels;\n    labels.reserve(class_map.size());\n    // keep linear complexity\n    for (Indexing::const_iterator it = _class_map.begin();\n         it != _class_map.end();)\n    {\n        const auto key = it->first;\n        labels.push_back(key);\n        do\n        {\n            ++it;\n        } while (it != _class_map.end() && key == it->first);\n    }\n    std::sort(labels.begin(), labels.end()); // pass labels as value\n    _unique_labels = labels;\n    auto last = std::unique(_unique_labels.begin(), _unique_labels.end());\n    _unique_labels.erase(last, _unique_labels.end());\n\n    _number_of_classes = _unique_labels.size();\n    _binary = _number_of_classes < 3;\n    _number_of_dichotomies = _binary ? 1 : _number_of_classes;\n};\n\n} // namespace models\n} // namespace mimkl\n\n#endif /* INCLUDE_MIMKL_MODELS_EASY_MKL_HPP_ */\n", "meta": {"hexsha": "3fe218edded874ea58ab5d462d4d44e174ef407f", "size": 20354, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mimkl/models/easy_mkl.hpp", "max_stars_repo_name": "vishalbelsare/mimkl", "max_stars_repo_head_hexsha": "53a5a9db5aa09c6e8808ba5b845601c5768d23e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2019-05-28T23:18:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T20:00:03.000Z", "max_issues_repo_path": "include/mimkl/models/easy_mkl.hpp", "max_issues_repo_name": "vishalbelsare/mimkl", "max_issues_repo_head_hexsha": "53a5a9db5aa09c6e8808ba5b845601c5768d23e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2019-05-18T13:21:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T22:20:55.000Z", "max_forks_repo_path": "include/mimkl/models/easy_mkl.hpp", "max_forks_repo_name": "vishalbelsare/mimkl", "max_forks_repo_head_hexsha": "53a5a9db5aa09c6e8808ba5b845601c5768d23e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2019-07-24T09:39:41.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-29T14:40:27.000Z", "avg_line_length": 34.7931623932, "max_line_length": 86, "alphanum_fraction": 0.6747568046, "num_tokens": 4719, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812554, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4895530096757608}}
{"text": "#include <path_follower/controller/robotcontroller_ackermann_stanley.h>\n\n\n\n#include <path_follower/utils/pose_tracker.h>\n#include <ros/ros.h>\n#include <path_follower/utils/visualizer.h>\n\n#include <cslibs_navigation_utilities/MathHelper.h>\n#include <deque>\n\n#include <limits>\n#include <boost/algorithm/clamp.hpp>\n\n#include <path_follower/factory/controller_factory.h>\n\nREGISTER_ROBOT_CONTROLLER(RobotController_Ackermann_Stanley, ackermann_stanley, ackermann);\n\nRobotController_Ackermann_Stanley::RobotController_Ackermann_Stanley():\n    RobotController()\n{\n\n\tROS_INFO(\"Parameters: k_forward=%f, k_backward=%f\\n\"\n\t\t\t\t\"vehicle_length=%f\\n\"\n\t\t\t\t\"factor_steering_angle=%f\\n\"\n\t\t\t\t\"goal_tolerance=%f\",\n\t\t\t\tparams_.k_forward(), params_.k_backward(),\n\t\t\t\tparams_.vehicle_length(),\n\t\t\t\tparams_.factor_steering_angle(),\n\t\t\t\tparams_.goal_tolerance());\n\n}\n\nvoid RobotController_Ackermann_Stanley::stopMotion() {\n\n\tmove_cmd_.setVelocity(0.f);\n\tmove_cmd_.setDirection(0.f);\n\n\tMoveCommand cmd = move_cmd_;\n\tpublishMoveCommand(cmd);\n}\n\nvoid RobotController_Ackermann_Stanley::start() {\n\n}\n\nvoid RobotController_Ackermann_Stanley::reset() {\n\n    RobotController::reset();\n}\n\nvoid RobotController_Ackermann_Stanley::setPath(Path::Ptr path) {\n    RobotController::setPath(path);\n}\n\nRobotController::MoveCommandStatus RobotController_Ackermann_Stanley::computeMoveCommand(\n\t\tMoveCommand* cmd) {\n\n\tif(path_interpol.n() <= 2)\n\t\treturn RobotController::MoveCommandStatus::ERROR;\n\n    const Eigen::Vector3d pose = pose_tracker_->getRobotPose();\n\n    RobotController::findOrthogonalProjection();\n    double d = -orth_proj_;\n\n    if(RobotController::isGoalReached(cmd)){\n       return RobotController::MoveCommandStatus::REACHED_GOAL;\n    }\n\n\t// draw a line to the orthogonal projection\n\tgeometry_msgs::Point from, to;\n\tfrom.x = pose[0]; from.y = pose[1];\n    to.x = path_interpol.p(proj_ind_); to.y = path_interpol.q(proj_ind_);\n    visualizer_->drawLine(12341234, from, to, getFixedFrame(), \"kinematic\", 1, 0, 0, 1, 0.01);\n\n\t// theta_e = theta_vehicle - theta_path (orientation error)\n    double theta_e = MathHelper::AngleDelta(pose[2], path_interpol.theta_p(proj_ind_));\n\n    // if we drive backwards invert d and set theta_e to the complementary angle\n    if (getDirSign() < 0.) {\n        theta_e = MathHelper::NormalizeAngle(M_PI + theta_e);\n    }\n\n\tconst double k = getDirSign() > 0. ? params_.k_forward() : params_.k_backward();\n\n\tconst double phi = theta_e + atan2(k * d, velocity_);\n\n\t// This is the accurate steering angle for 4 wheel steering\n\tconst float phi_actual = (float) asin(params_.factor_steering_angle() * sin(phi));\n\n    double exp_factor = RobotController::exponentialSpeedControl();\n\tmove_cmd_.setDirection(phi_actual);\n    move_cmd_.setVelocity(getDirSign() * (float) velocity_ * exp_factor);\n\n\t*cmd = move_cmd_;\n\n\treturn RobotController::MoveCommandStatus::OKAY;\n}\n\nvoid RobotController_Ackermann_Stanley::publishMoveCommand(\n\t\tconst MoveCommand& cmd) const {\n\n\tgeometry_msgs::Twist msg;\n\tmsg.linear.x  = cmd.getVelocity();\n\tmsg.linear.y  = 0;\n\tmsg.angular.z = cmd.getDirectionAngle();\n\n\tcmd_pub_.publish(msg);\n}\n", "meta": {"hexsha": "7096581397eb5eb658aba3d78558ea09de96e48a", "size": 3114, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "path_follower/src/controller/robotcontroller_ackermann_stanley.cpp", "max_stars_repo_name": "sunarditay/gerona", "max_stars_repo_head_hexsha": "7ca6bb169571d498c4a2d627faddc8cbe590d2c9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 296.0, "max_stars_repo_stars_event_min_datetime": "2017-06-19T07:06:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T01:27:44.000Z", "max_issues_repo_path": "path_follower/src/controller/robotcontroller_ackermann_stanley.cpp", "max_issues_repo_name": "sunarditay/gerona", "max_issues_repo_head_hexsha": "7ca6bb169571d498c4a2d627faddc8cbe590d2c9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 29.0, "max_issues_repo_issues_event_min_datetime": "2017-11-07T08:49:12.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-21T22:18:28.000Z", "max_forks_repo_path": "path_follower/src/controller/robotcontroller_ackermann_stanley.cpp", "max_forks_repo_name": "sunarditay/gerona", "max_forks_repo_head_hexsha": "7ca6bb169571d498c4a2d627faddc8cbe590d2c9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 117.0, "max_forks_repo_forks_event_min_datetime": "2017-05-30T10:50:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-09T01:27:23.000Z", "avg_line_length": 28.0540540541, "max_line_length": 94, "alphanum_fraction": 0.7463070006, "num_tokens": 798, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478255, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4895530040041792}}
{"text": "#define BOOST_TEST_MODULE 04 test 1\n#include <boost/test/included/unit_test.hpp>\n\n#define GLM_ENABLE_EXPERIMENTAL\n#include <glm/glm.hpp>\n#include <glm/gtc/matrix_transform.hpp>\n#include <glm/gtc/type_ptr.hpp>\n#include <glm/gtx/string_cast.hpp>\n\n#include <iostream>\n#include <vector>\n#include <string>\n#include <fstream>\n#include <utility>\n\nBOOST_AUTO_TEST_CASE(first_test)\n{\n    glm::vec4 vec(1.0f, 0.0f, 0.0f, 1.0f);\n    glm::mat4 trans;\n    trans = glm::translate(trans, glm::vec3(1.0f, 1.0f, 0.0f));\n    vec = trans * vec;\n    BOOST_TEST(vec.x == 2.0f);\n    BOOST_TEST(vec.y == 1.0f);\n    BOOST_TEST(vec.z == 0.0f);\n\n    trans = glm::rotate(trans, 90.0f, glm::vec3(0.0, 0.0, 1.0));\n    std::cout << glm::to_string(trans);\n    trans = glm::scale(trans, glm::vec3(0.5, 0.5, 0.5));\n    vec = glm::vec4(1.0f, 0.0f, 0.0f, 1.0f);\n    vec = trans * vec;\n    BOOST_TEST(vec.x == 0.775963187f);\n    BOOST_TEST(vec.y == 1.44699836f);\n    BOOST_TEST(vec.z == 0.0f);\n}\n", "meta": {"hexsha": "6ed1c4cc9d9dcd01af50b7fd4d631a8e46a38c1f", "size": 960, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "04/test.cpp", "max_stars_repo_name": "Samuel0Paul/My-Jolly-journey-", "max_stars_repo_head_hexsha": "62ad3a62e21b89526eb942bb2a6d7958fce008a7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "04/test.cpp", "max_issues_repo_name": "Samuel0Paul/My-Jolly-journey-", "max_issues_repo_head_hexsha": "62ad3a62e21b89526eb942bb2a6d7958fce008a7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "04/test.cpp", "max_forks_repo_name": "Samuel0Paul/My-Jolly-journey-", "max_forks_repo_head_hexsha": "62ad3a62e21b89526eb942bb2a6d7958fce008a7", "max_forks_repo_licenses": ["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.4285714286, "max_line_length": 64, "alphanum_fraction": 0.6427083333, "num_tokens": 352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079208, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.48952866205771395}}
{"text": "#include <g2o/core/base_vertex.h>\n#include <g2o/core/base_binary_edge.h>\n#include <g2o/core/block_solver.h>\n#include <g2o/core/optimization_algorithm_levenberg.h>\n#include <g2o/core/auto_differentiation.h>\n#include <g2o/solvers/csparse/linear_solver_csparse.h>\n#include <g2o/core/robust_kernel_impl.h>\n#include <g2o/types/slam3d/se3quat.h>\n#include <g2o/types/slam3d/vertex_pointxyz.h>\n#include <g2o/types/sba/types_six_dof_expmap.h>\n#include <iostream>\n\n#include \"common.h\"\n#include <sophus/se3.hpp>\n#include <sophus/so3.hpp>\n#include <Eigen/Dense>\n\nusing namespace Sophus;\nusing namespace Eigen;\nusing namespace std;\n\nstruct Camera\n{\n    Camera() {}\n\n    Camera(double* data)\n    {\n        Rt = g2o::SE3Quat::exp(Eigen::Map<Eigen::Matrix<double, 6, 1>>(data));\n\n        f = data[6];\n        k1 = data[7];\n        k2 = data[8];\n    }\n\n    void set_to(double* data) const\n    {\n        Eigen::Matrix<double, 6, 1> rt = Rt.log();\n        \n        for (int i = 0; i < 6; ++i)\n            data[i] = rt[i];\n        \n\n        data[6] = f;\n        data[7] = k1;\n        data[8] = k2;\n    }\n\n    g2o::SE3Quat Rt; // g2o::SE3Quat stores rotation first and then translation\n    double f = 0.0, k1 = 0.0, k2 = 0.0;\n};\n\nclass VertexCamera: public g2o::BaseVertex<9, Camera>\n{\n    public:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n\n    virtual void setToOriginImpl() override {\n        \n        _estimate = Camera();\n    }\n\n    virtual void oplusImpl(const double *update) override {\n        _estimate.Rt = g2o::SE3Quat::exp(Eigen::Map<const Eigen::Matrix<double, 6, 1>>(update)) * _estimate.Rt;\n        _estimate.f += update[6];\n        _estimate.k1 += update[7];\n        _estimate.k2 += update[8];\n    }\n\n    virtual bool read(std::istream&) override {}\n    virtual bool write(std::ostream&) const override {}\n};\n\nclass VertexLandmark: public g2o::BaseVertex<3, Eigen::Vector3d>\n{\n    public:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n\n    virtual void setToOriginImpl() override {\n        _estimate = Eigen::Vector3d::Zero();       \n    }\n\n    virtual void oplusImpl(const double *update) override {\n        _estimate += Eigen::Map<const Eigen::Vector3d>(update);\n    }\n\n    virtual bool read(std::istream&) override {}\n    virtual bool write(std::ostream&) const override {}\n};\n\n\nclass EdgeReprojection: public g2o::BaseBinaryEdge<2, Eigen::Vector2d, VertexLandmark, VertexCamera>\n{\n  public:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n\n    EdgeReprojection(double f, double k1, double k2) : f_(f), k1_(k1), k2_(k2) { }\n\n    virtual void computeError() override {\n        const VertexCamera* v_cam = static_cast<VertexCamera*>(_vertices[1]);\n        const VertexLandmark* v_point = static_cast<VertexLandmark*>(_vertices[0]);\n        auto cam = v_cam->estimate();\n        Eigen::Vector3d X = v_point->estimate();\n        Eigen::Vector3d X_cam = cam.Rt * X;\n        X_cam /= X_cam.z();\n\n        auto p2 = X_cam.x() * X_cam.x() + X_cam.y() * X_cam.y();\n        auto r = 1.0 + p2 * (cam.k1 + (p2 * cam.k2));\n\n        Eigen::Vector2d uv = -X_cam.head<2>() *  cam.f * r; // minus because of the dataset projection\n        _error = _measurement - uv;\n    }\n\n\n    virtual void linearizeOplus()  override  {\n        const VertexCamera *v_cam = static_cast<VertexCamera*>(_vertices[1]);\n        const VertexLandmark *v_landmark = static_cast<VertexLandmark*>(_vertices[0]);\n        Eigen::Vector3d X3d = v_landmark->estimate();\n        auto cam = v_cam->estimate();\n        Eigen::Vector3d Xc = cam.Rt * X3d;\n\n        double X = Xc.x();\n        double Y = Xc.y();\n        double Z = Xc.z();\n        double Z_2 = Z * Z;\n        double f = cam.f;\n        double k1 = cam.k1;\n        double k2 = cam.k2;\n\n        double x = X / Z;\n        double y = Y / Z;\n        double x2 = x*x;\n        double y2 = y*y;\n        double n2 = x*x + y*y;\n        double n4 = n2 * n2;\n        double r = 1.0 + n2 * k1 + n4 * k2;\n\n\n        Eigen::Matrix2d dedxd = -Eigen::Matrix2d::Identity() * f; // minus because of the dataset projection\n\n        Eigen::Matrix2d dxddxp = Eigen::Matrix2d::Identity();\n\n        dxddxp(0, 0) = (2*k1*x+4*k2*x2*x+4*y2*x*k2)*x + r;\n        dxddxp(0, 1) = x*(2*k1*y+4*x2*k2*y+4*k2*y2*y);\n        dxddxp(1, 0) = y*(2*k1*x+4*k2*x2*x+4*y2*k2*x);\n        dxddxp(1, 1) = (2*k1*y+4*x2*y*k2+4*k2*y2*y)*y + r;\n\n\n        Eigen::Matrix<double, 2, 3> dxpdXc;\n        dxpdXc << 1.0/Z, 0.0, -X / (Z_2),\n                  0.0, 1.0/Z, -Y / (Z_2);\n\n\n        Eigen::Matrix<double, 2, 3> dedXc = dedxd * dxddxp * dxpdXc;\n        \n        Eigen::Matrix3d dXcdR;\n        dXcdR << 0.0, -Z, Y,\n                 Z, 0.0, -X,\n                 -Y, X, 0.0;\n\n        Eigen::Matrix3d dXcdt = Eigen::Matrix3d::Identity();\n\n        Eigen::Vector2d dedf(-r*x, -r*y);   // minus because of the dataset projection \n        Eigen::Vector2d dxddk1(x * n2, y * n2);\n        Eigen::Vector2d dxddk2(x * n4, y * n4);\n        Eigen::Vector2d dedk1 = dedxd * dxddk1;\n        Eigen::Vector2d dedk2 = dedxd * dxddk2;\n\n        _jacobianOplusXj.block<2, 3>(0, 0) = dedXc * -dXcdR; // -dXcdR <=> -Xc^\n        _jacobianOplusXj.block<2, 3>(0, 3) = dedXc * dXcdt;\n        _jacobianOplusXj.col(6) = dedf;\n        _jacobianOplusXj.col(7) = dedk1;\n        _jacobianOplusXj.col(8) = dedk2;\n        \n        _jacobianOplusXi = dedXc * cam.Rt.rotation().matrix();\n\n         _jacobianOplusXi *= -1; // take the negative jacobian because the error is defined as (measurement - projection)\n         _jacobianOplusXj *= -1;\n\n    }\n\n    virtual bool read(std::istream&) override {}\n    virtual bool write(std::ostream&) const override {}\n    private:\n        double f_, k1_, k2_;\n\n};\n\n\nint main(int argc, char **argv) {\n\n    if (argc != 2) {\n        cout << \"usage: bundle_adjustment_g2o bal_data.txt\" << endl;\n        return 1;\n    }\n\n    BALProblem dataset(argv[1]);\n    dataset.Normalize();\n    dataset.Perturb(0.1, 0.5, 0.5);\n    dataset.WriteToPLYFile(\"initial_pc.ply\");\n\n    std::cout << \"\\n\";\n    std::cout << \"nb cameras: \" << dataset.num_cameras() << std::endl;\n    std::cout << \"nb landmarks: \" << dataset.num_points() << std::endl;\n    std::cout << \"nb observations: \" << dataset.num_observations() << std::endl;\n    std::cout << \"nb parameters: \" << dataset.num_parameters() << std::endl;\n    std::cout << \"check: \" << dataset.num_cameras() * 9 + dataset.num_points()*3 << std::endl;\n\n\n    // pose dimension 9, landmark is 3\n    typedef g2o::BlockSolver<g2o::BlockSolverTraits<9, 3>> BlockSolverType;\n    typedef g2o::LinearSolverCSparse<BlockSolverType::PoseMatrixType> LinearSolverType;\n\n    auto solver = new g2o::OptimizationAlgorithmLevenberg(\n        g2o::make_unique<BlockSolverType>(g2o::make_unique<LinearSolverType>())\n    );\n    g2o::SparseOptimizer optimizer;\n    optimizer.setAlgorithm(solver);\n    optimizer.setVerbose(true);\n\n\n    auto* cameras = dataset.mutable_cameras();\n    std::vector<VertexCamera*> camera_vertices;\n    for (int i = 0; i < dataset.num_cameras(); ++i)\n    {\n        auto *c = new VertexCamera();\n        c->setId(i);\n        c->setEstimate(Camera(cameras + (i*dataset.camera_block_size())));\n        optimizer.addVertex(c);\n        camera_vertices.push_back(c);\n    }\n    \n    auto* landmarks = dataset.mutable_points();\n    std::vector<VertexLandmark*> landmark_vertices;\n    for (int i = 0; i < dataset.num_points(); ++i)\n    {\n        auto* l = new VertexLandmark();\n        l->setId(dataset.num_cameras() + i);\n        l->setEstimate(Eigen::Map<Eigen::Vector3d>(landmarks + i*dataset.point_block_size()));\n        l->setMarginalized(true);\n        optimizer.addVertex(l);\n        landmark_vertices.push_back(l);\n    }\n\n    auto* observations = dataset.observations();\n    auto* cam_indices = dataset.camera_index();\n    auto* landmark_indices = dataset.point_index();\n    for (int i = 0; i < dataset.num_observations(); ++i)\n    {\n        auto c = Camera(cameras + (cam_indices[i]*dataset.camera_block_size()));\n        auto* e = new EdgeReprojection(c.f, c.k1, c.k2);\n        e->setVertex(1, camera_vertices[cam_indices[i]]);\n        e->setVertex(0, landmark_vertices[landmark_indices[i]]);\n        e->setMeasurement(Eigen::Map<const Eigen::Vector2d>(observations + i*2));\n        e->setInformation(Eigen::Matrix2d::Identity());\n        optimizer.addEdge(e);\n    }\n\n    optimizer.initializeOptimization();\n    optimizer.optimize(40);\n\n\n    for (int i = 0; i < dataset.num_cameras(); ++i)\n    {\n        camera_vertices[i]->estimate().set_to(cameras + (i * dataset.camera_block_size()));\n    }\n    for (int i = 0; i < dataset.num_points(); ++i)\n    {\n        Eigen::Vector3d X = landmark_vertices[i]->estimate();\n        landmarks[i*3] = X.x();\n        landmarks[i*3+1] = X.y();\n        landmarks[i*3+2] = X.z();\n    }\n\n    dataset.WriteToPLYFile(\"after_ba_g2o.ply\");\n\n    return 0;\n}\n", "meta": {"hexsha": "e2b7957647fe3cc00ea0c87ceb066a58cdec0931", "size": 8752, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch9/bundle_adjustment_g2o_custom_analytical.cpp", "max_stars_repo_name": "zinsmatt/slambook2", "max_stars_repo_head_hexsha": "3648caff838241553d9f3de332068eb0d501a7dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ch9/bundle_adjustment_g2o_custom_analytical.cpp", "max_issues_repo_name": "zinsmatt/slambook2", "max_issues_repo_head_hexsha": "3648caff838241553d9f3de332068eb0d501a7dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch9/bundle_adjustment_g2o_custom_analytical.cpp", "max_forks_repo_name": "zinsmatt/slambook2", "max_forks_repo_head_hexsha": "3648caff838241553d9f3de332068eb0d501a7dc", "max_forks_repo_licenses": ["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.4820143885, "max_line_length": 121, "alphanum_fraction": 0.6003199269, "num_tokens": 2645, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079208, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.48952866205771395}}
{"text": "#include <gmp_lib/CanonicalSystem/CanonicalSystem.h>\n\n#include <cstdlib>\n#include <cmath>\n#include <array>\n#include <exception>\n\n#include <boost/numeric/odeint.hpp>\n\nnamespace as64_\n{\n\nnamespace gmp_\n{\n\ntypedef std::array<double,2> can_sys_state;\ntypedef boost::numeric::odeint::runge_kutta_cash_karp54< can_sys_state > can_sys_error_stepper_type;\ntypedef boost::numeric::odeint::controlled_runge_kutta< can_sys_error_stepper_type > can_sys_controlled_stepper_type;\n\nCanonicalSystem::CanonicalSystem(double T, double Ds)\n{    \n  this->s0 = 0;\n  this->sf = 1;\n  this->Ds = Ds;\n\n  this->sd_dot = 1/T;\n    \n  this->s = 0;\n  this->s_dot = this->sd_dot;\n}\n  \n\nvoid CanonicalSystem::integrate(double t0, double tf)\n{\n  static can_sys_controlled_stepper_type ctrl_stepper;\n\n  if (tf < t0) throw std::runtime_error(\"Cannot integrate backwards in time: t0 > tf\");\n\n  if (std::isinf(this->Ds))\n  {\n    this->s_dot = this->sd_dot;\n    this->s = this->s + this->s_dot*(tf - t0);\n    \n    if (this->s > this->sf) this->s = this->sf; \n    else if (this->s < this->s0) this->s = this->s0;\n\n    return;\n  }\n\n  auto ode_fun = [this](const can_sys_state &state, can_sys_state &state_dot, double t)\n  { \n    state_dot[0] = state[1];\n    state_dot[1] = this->getPhaseDDot(state[0], state[1]); \n  };\n  \n  can_sys_state state = {s, s_dot};\n  boost::numeric::odeint::integrate_adaptive(ctrl_stepper, ode_fun, state, t0, tf, tf-t0);\n  s = state[0];\n  s_dot = state[1];\n}\n  \nvoid CanonicalSystem::setDuration(double T, double t)\n{\n  if (T < t) throw std::runtime_error(\"The current time has already exceeded the duration\");\n      \n  this->sd_dot = (this->sf - this->s) / (T - t);\n}\n\nvoid CanonicalSystem::setRemainingDuration(double T)\n{      \n  this->sd_dot = (this->sf - this->s) / T;\n}\n\ndouble CanonicalSystem::getPhaseDDot(double s, double s_dot)\n{\n  double s_ddot = 0;\n  if (s>=this->s0 && s < this->sf) s_ddot = -this->Ds*(s_dot - this->sd_dot);\n  else if (s>=1)                   s_ddot = -400*s_dot - 1000*(s-this->sf);\n  else                             s_ddot = -400*s_dot - 1000*(s-this->s0);\n  \n  return s_ddot;\n}\n\nvoid CanonicalSystem::reset()\n{\n  this->s = this->s0;\n  this->s_dot = this->sd_dot;\n}\n\n\n} // namespace gmp_\n\n    \n} // namespace as64_", "meta": {"hexsha": "bd4c61201112bc49e3bf19c8eb0986a32424d27e", "size": 2236, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "experiments/ros packages/gmp_lib/src/CanonicalSystem/CanonicalSystem.cpp", "max_stars_repo_name": "Slifer64/novel-DMP-constraints", "max_stars_repo_head_hexsha": "cad6727a12642130dc64fd93827099e4cb763ec8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "experiments/ros packages/gmp_lib/src/CanonicalSystem/CanonicalSystem.cpp", "max_issues_repo_name": "Slifer64/novel-DMP-constraints", "max_issues_repo_head_hexsha": "cad6727a12642130dc64fd93827099e4cb763ec8", "max_issues_repo_licenses": ["MIT"], "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/ros packages/gmp_lib/src/CanonicalSystem/CanonicalSystem.cpp", "max_forks_repo_name": "Slifer64/novel-DMP-constraints", "max_forks_repo_head_hexsha": "cad6727a12642130dc64fd93827099e4cb763ec8", "max_forks_repo_licenses": ["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.7872340426, "max_line_length": 117, "alphanum_fraction": 0.6484794275, "num_tokens": 701, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.48952865624226916}}
{"text": "// CHAP - The Channel Annotation Package\n// \n// Copyright (c) 2016 - 2018 Gianni Klesse, Shanlin Rao, Mark S. P. Sansom, and \n// Stephen J. Tucker\n// \n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n// \n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n\n#include <algorithm>\n#include <limits>\n\n#include <boost/bind.hpp>\n#include <boost/function.hpp>\n#include <boost/math/tools/minima.hpp>\n#include <boost/math/tools/roots.hpp>\n\n#include \"geometry/spline_curve_3D.hpp\"\n#include \"geometry/cubic_spline_interp_3D.hpp\"\n\n\n/*!\n * Constructor for creating a spline curve of given degree from a knot vector\n * and associated control points.\n */\nSplineCurve3D::SplineCurve3D(\n        int degree,\n        std::vector<real> knotVector,\n        std::vector<gmx::RVec> ctrlPoints)\n{\n    // TODO: probably better to put some of these things into the initialiser\n    // list\n\n    nCtrlPoints_ = ctrlPoints.size();\n    nKnots_ = knotVector.size();\n    degree_ = degree;\n    arcLengthTableAvailable_ = false;\n\n    // ensure minimal number of control points for given degree:\n    if( nCtrlPoints_ < degree_ + 1 )\n    {\n        std::cerr<<\"ERROR: Need at least d + 1 control points!\"<<std::endl;\n        std::cerr<<\"d = \"<<degree_\n                 <<\" and n = \"<<nCtrlPoints_\n                 <<std::endl;\n        std::abort();\n    }\n\n    // ensure minimal number of knots:\n    if( nKnots_ < nCtrlPoints_ + degree_ + 1 )\n    {\n        std::cerr<<\"ERROR: Need at least n + d + 1 knots!\"<<std::endl;\n        std::cerr<<\"d = \"<<degree_\n                 <<\" and n = \"<<nCtrlPoints_\n                 <<\" and k = \"<<nKnots_\n                 <<std::endl;\n        std::abort();\n    }\n\n    // assign knot vector and control points:\n    knots_ = knotVector;\n    ctrlPoints_ = ctrlPoints;\n}\n\n\n/*!\n * Default constructor for initialiser lists. Does not set any members!\n */\nSplineCurve3D::SplineCurve3D()\n{\n\n}\n\n\n/*!\n * Public interface for evaluation of spline curve. Returns the value of the \n * spline curve or its derivative at the given evaluation point. If the \n * evaluation point lies outside the knot range, linear extrapolation is used.\n */\ngmx::RVec\nSplineCurve3D::evaluate(\n        const real &eval,\n        unsigned int deriv)\n{\n    // extrapolation or interpolation?\n    if( eval < knots_.front() || eval > knots_.back() )\n    {\n        return evaluateExternal(eval, deriv);\n    }\n    else\n    {\n        return evaluateInternal(eval, deriv);\n    }\n}\n\n\n/*!\n * Auxiliary function for evaluating the spline curve at points inside the \n * range covered by knots.\n */\ngmx::RVec \nSplineCurve3D::evaluateInternal(const real &eval, unsigned int deriv)\n{\n    // container for basis functions or derivatives:\n    SparseBasis basis;\n\n    // derivative required?\n    if( deriv == 0 )\n    {\n        // evaluate B-spline basis:\n        basis = B_(eval, knots_, degree_);\n    }\n    else\n    {\n        // evaluate B-spline basis derivatives:\n        basis = B_(eval, knots_, degree_, deriv); \n    }\n    \n    // return value of spline curve (derivative) at given evaluation point:\n    return computeLinearCombination(basis);\n}\n\n\n/*!\n * Auxiliary function for evaluating the spline curve at points outside the \n * range covered by knots. Linear extrapolation is used in this case.\n */\ngmx::RVec \nSplineCurve3D::evaluateExternal(const real &eval, unsigned int deriv)\n{   \n    // which boundary is extrapolation based on?\n    real boundary;\n    if( eval < knots_.front() )\n    {\n        boundary = knots_.front();\n    }\n    else\n    {\n        boundary = knots_.back();\n    }\n\n    // derivative required?\n    if( deriv == 0 )\n    {\n        // compute slope and offset:\n        // TODO: this can be made more efficient by evaluating basis and derivs\n        // in one go!\n        SparseBasis basis = B_(boundary, knots_, degree_);\n        gmx::RVec offset = computeLinearCombination(basis);\n        basis = B_(boundary, knots_, degree_, 1);\n        gmx::RVec slope = computeLinearCombination(basis);\n\n        // return extrapolation point:\n        svmul(eval - boundary, slope, slope);\n        rvec_add(slope, offset, slope);\n        return slope;\n\n    }\n    else if( deriv == 1 )\n    {\n        // simply return the slope at the endpoint:\n        SparseBasis basis = B_(boundary, knots_, degree_, 1);\n        return computeLinearCombination(basis);\n    }\n    else\n    {\n        // for linear extrapolation, second and higher order deriv are zero:\n        return gmx::RVec(0.0, 0.0, 0.0);\n    }\n}\n\n\n/*!\n * Evaluates the linear combination of basis functions weighted by control\n * points, i.e. computes\n *\n * \\f[\n *      \\sum_i \\mathbf{c}_i B_{i,p}(x)\n * \\f]\n *\n * where the sum only goes over the nonzero elements of the basis for \n * efficiency.\n */\ngmx::RVec\nSplineCurve3D::computeLinearCombination(const SparseBasis &basis)\n{\n    gmx::RVec value(gmx::RVec(0.0, 0.0, 0.0)); \n    for(auto b : basis)\n    {\n        gmx::RVec tmp;\n        svmul(b.second, ctrlPoints_[b.first], tmp);\n        rvec_add(value, tmp, value);\n    }\n\n    return value;\n}\n\n\n\n/*!\n * Change the internal representation of the curve such that it is \n * parameterised in terms of arc length.\n */\nvoid\nSplineCurve3D::arcLengthParam()\n{\n    // number of uniformly spaced arc length parameters:\n    int nNew = 10*nCtrlPoints_;\n\n    // create lookup table for arc length at knots:\n    prepareArcLengthTable();\n   \n    // determine uniform arc length spacing:\n    real arcLenStep = arcLengthTable_.back() / (nNew - 1);\n\n    // initialise new control points and parameters:\n    std::vector<real> newParams;\n    std::vector<gmx::RVec> newPoints;\n\n\n    // loop over uniformly spaced arc length intervals:\n    for(int i = 0; i < nNew; i++)\n    {\n        // calculate target arc length:\n        real newParam = i*arcLenStep;\n        newParams.push_back(newParam);\n\n        // find parameter value corresponding to arc length value:\n        real oldParam = arcLengthToParam(newParam); \n\n        //  evaluate spline to get new point:\n        newPoints.push_back(this -> evaluate(oldParam, 0));\n    }\n\n    // interpolate new points to get arc length parameterised curve:\n    CubicSplineInterp3D Interp;\n    SplineCurve3D newSpl = Interp(newParams, \n                                  newPoints, \n                                  eSplineInterpBoundaryHermite);\n\n    // update own parameters:\n    this -> knots_ = newSpl.knots_;\n    this -> ctrlPoints_ = newSpl.ctrlPoints_;\n    this -> nKnots_ = newSpl.nKnots_;\n    this -> nCtrlPoints_ = newSpl.nCtrlPoints_;\n    this -> arcLengthTableAvailable_ = false;\n\n    // reset reference points for mapping:\n    refPoints_.clear();\n}\n\n\n/*!\n * Calculates the length along the arc of the curve between the two parameter\n * values a and b.\n */\nreal\nSplineCurve3D::length(const real &lo, const real &hi)\n{ \n    // do we need to form a lookup table:\n    if( arcLengthTableAvailable_ == false || arcLengthTable_.size() == 0 )\n    {\n        prepareArcLengthTable(); \n    }\n\n    // initialise length as zero::\n    real length = 0.0;   \n  \n    // find intervals of evaluation points:\n    int idxLo = findInterval(lo);\n    int idxHi = findInterval(hi);\n\n    // add distance in endpoint intervals:\n    if( idxHi == idxLo )\n    {\n        length += arcLengthBoole(lo, hi);\n    }\n    else\n    {\n        length += arcLengthBoole(lo, knots_[idxLo + 1]);\n        length += arcLengthBoole(knots_[idxHi], hi);\n    }\n\n    // if necessary, loop over intermediate spline segments and sum up lengths:\n    if( idxHi - idxLo > 1 )\n    {\n        for(int i = idxLo + 1; i < idxHi; i++)\n        {\n            // add length of current segment from lookup table:\n            length += arcLengthTable_[i + 1] - arcLengthTable_[i];\n        }\n    }\n\n    return length;\n}\n\n\n/*!\n * Convenience function to calculate arc length of curve between first and last\n * support point.\n */\nreal \nSplineCurve3D::length()\n{\n    return length(knots_.front(), knots_.back());\n}\n\n\n/*!\n * Returns the tangent vector at the given evaluation point. Simply a wrapper\n * around the general evaluation function requesting the first derivative at \n * the given point.\n */\ngmx::RVec\nSplineCurve3D::tangentVec(const real &eval)\n{\n    return evaluate(eval, 1); \n}\n\n/*!\n * Returns the normal vector at the evaluation point.\n */\ngmx::RVec\nSplineCurve3D::normalVec(const real &eval)\n{\n    return evaluate(eval, 2);\n}\n\n\n/*!\n * Returns the speed of the curve at the given evaluation point, where speed\n * refers to the magnitude of the tangent vector.\n */\nreal\nSplineCurve3D::speed(const real &eval)\n{\n    // return magnitude of tangent vector:\n    return norm( this -> tangentVec(eval) );\n}\n\n\n/*!\n * Takes point in Cartesian coordinates and returns that points coordinates in\n * the curvilinear system defined by the spline curve. Return value is an RVec,\n * which contains the following information:\n *\n *      [0] - distance along the arc of the curve\n *      [1] - squared (!) distance from the curve at closest point\n *      [2] - angular coordinate; this is not yet implemented\n *\n * Note that this function assumes that the curve is parameterised by arc \n * length!\n *\n * \\todo implement angular coordinate!\n */\ngmx::RVec \nSplineCurve3D::cartesianToCurvilinear(const gmx::RVec &cartPoint)\n{\n    // find index of interval containing closest point on spline curve:\n    unsigned int idx = closestSplinePoint(cartPoint);\n\n    // find closest point on this interval:\n    gmx::RVec proj = projectionInInterval(\n            cartPoint, \n            knots_[idx + degree_], \n            knots_[idx + degree_ + 1]);\n\n    // check neighbouring knot intervals and extrapolate if necessary:\n    gmx::RVec altProj;\n\n    // next lower knot interval:\n    if( idx == 0 )\n    {\n        altProj = projectionInExtrapRange(cartPoint, -1.0); \n    }\n    else\n    {\n        altProj = projectionInInterval(\n                cartPoint, \n                knots_[idx + degree_ - 1],\n                knots_[idx + degree_]);\n    }\n\n    // does alternative projection give closer point:\n    if( altProj[RR] < proj[RR] )\n    {\n        proj = altProj;\n    }\n    \n    // next higher knot interval:\n    if( idx == refPoints_.size() - 2 )\n    {\n        altProj = projectionInExtrapRange(cartPoint, 1.0); \n    }\n    else\n    {\n        altProj = projectionInInterval(\n                cartPoint, \n                knots_[idx + degree_ + 1],\n                knots_[idx + degree_ + 2]);\n    }\n\n    // does alternative projection give closer point:\n    if( altProj[RR] < proj[RR] )\n    {\n        proj = altProj;\n    }\n  \n    // TODO: calculate angular coordinate!\n    proj[PP] = 0.0;\n\n    // return point in curvilinear coordinates:\n    return proj;\n}\n\n\n/*!\n * Auxiliary function for finding the closest point on a spline curve that \n * returns the corresponding spline interval index. First, a set of reference\n * points is sampled from the spline curve at the location of the unique knots\n * (this step is skipped if the reference points have already been computed in\n * a previous call to this function). Secondly, a linear search over these \n * reference points is carried out to find the point closest to a given test \n * point.\n *\n * The return value is the index of the closest reference point, except for the \n * case where the closest reference point is the last point, which is mapped to \n * the last interval, i.e. the index of the penultimate reference point is \n * returned in this case.\n *\n * \\todo Linear search may not be the most efficient.\n */\nunsigned int\nSplineCurve3D::closestSplinePoint(const gmx::RVec &point)\n{\n    // build lookup table:\n    if( refPoints_.empty() )\n    {\n        refPoints_.reserve(uniqueKnots().size());\n        for(auto s : uniqueKnots())\n        {\n            refPoints_.push_back( this -> evaluate(s, 0) );\n        }\n    }\n\n    // find index of closest reference point on spline curve:\n    unsigned int idxMinDist = 0;\n    real minDist = std::numeric_limits<real>::infinity();\n    for(unsigned int i = 0; i < refPoints_.size(); i++)\n    {\n        // find dist to control point:\n        real dist = distance2(point, refPoints_[i]);\n\n        // closer than previous closest point:\n        if( dist < minDist )\n        {\n            minDist = dist;\n            idxMinDist = i;\n        }\n    }\n\n    // special case of last control point:\n    if( idxMinDist == refPoints_.size() - 1 )\n    {\n        // simply map this to last interval:\n        idxMinDist--;\n    }\n\n    // return index of interval of closest point:\n    return idxMinDist;\n}\n\n\n/*!\n * Auxiliary function that maps a point in Cartesian coordinates onto an \n * internal segment of the spline curve. This is accomplished by iteratively \n * minimising the distance between the test point and a base point sampled from \n * the spline curve using the (derivative free) method of Brent.\n *\n * \\throws A logic error is thrown if the minimum can not be converged within \n * a hardcoded number of 100 Brent iterations.\n */\ngmx::RVec\nSplineCurve3D::projectionInInterval(\n        const gmx::RVec &point,\n        const real &lo,\n        const real &hi)\n{\n    // internal parameters:\n    const boost::uintmax_t maxIter = 100;\n    boost::uintmax_t iter = maxIter;\n\n    // objective function binding:\n    boost::function<real(real)> objFun;\n    objFun = boost::bind(\n            &SplineCurve3D::pointSqDist, \n            this, \n            point, \n            _1);\n \n    // find minimum via Brent's method:\n    int bits = std::numeric_limits<double>::digits;\n    std::pair<double, double> result;\n    result = boost::math::tools::brent_find_minima(\n            objFun,\n            lo, \n            hi,\n            bits,\n            iter);\n\n    // make sure convergence has been reached:\n    if( iter >= maxIter )\n    {\n        throw std::logic_error(\"Could not converge Brent iteration in \"\n                               \"Cartesian to curvilinear mapping!\");\n    }\n\n    // return curvilinear coordinates of point:\n    // TODO: implement angular coordinate\n    gmx::RVec curvPoint;\n    curvPoint[SS] = result.first;\n    curvPoint[RR] = result.second;\n    return curvPoint;    \n}\n\n\n/*!\n * Auxiliary function that projects a point in Cartesian coordinates onto the\n * extrapolation range beyond its two endpoints. As the curve is known to be a\n * line in this range the projection is solved for analytically as a projection \n * onto a ray. To achieve this, a ray is constructed by sampling two point \n * from the spline curve (its endpoint and a second point \\f$ ds \\f$  beyond \n * this endpoint. \n */\ngmx::RVec\nSplineCurve3D::projectionInExtrapRange(\n        const gmx::RVec &point,\n        const real &ds)\n{\n    // return variable:\n    gmx::RVec proj;\n\n    // lower or upper extrapolation range?\n    gmx::RVec extrapPointA;\n    gmx::RVec extrapPointB;\n    real arcLenOffset;\n    real arcLenSign;\n    if( ds < 0.0 )\n    {\n        // lower range:\n        extrapPointA = ctrlPoints_.front();\n        arcLenOffset = knots_.front();\n        arcLenSign = -1.0;\n        extrapPointB = this -> evaluate(arcLenOffset + ds, 0);\n    }\n    else if( ds > 0.0 )\n    {\n        // upper range:\n        extrapPointA = ctrlPoints_.back();\n        arcLenOffset = knots_.back();\n        arcLenSign = 1.0;\n        extrapPointB = this -> evaluate(arcLenOffset + ds, 0);\n    }\n    else\n    {\n        throw std::logic_error(\"Parameter dt may not be zero!\");\n    }\n\n    // (non-normalised) direction vector for the extrapolating line:\n    gmx::RVec lineDirVector;\n    rvec_sub(extrapPointB, extrapPointA, lineDirVector);\n\n    // vector between the test point and the ray's endpoint:\n    gmx::RVec endpointVector;\n    rvec_sub(point, extrapPointA, endpointVector);\n\n    // is ray endpoint the closest point?\n    // NOTE: in this case the angle between line direction vector and endpoint \n    // vector will be >= 90 degrees and the scalar product <= 0.0!\n    real cosOfAngle = iprod(endpointVector, lineDirVector);\n    if( cosOfAngle <= 0.0 )\n    {\n        proj[SS] = arcLenOffset;\n        proj[RR] = distance2(point, extrapPointA);\n\n        return proj;\n    }\n\n    // projection of test point position onto ray and base point:\n    real b = cosOfAngle/iprod(lineDirVector, lineDirVector);\n    gmx::RVec basePoint;\n    svmul(b, lineDirVector, basePoint);\n    rvec_add(basePoint, extrapPointA, basePoint);\n\n    // curvilinear coordinates around this line:\n    proj[SS] = arcLenOffset + arcLenSign*b;\n    proj[RR] = distance2(point, basePoint);\n\n    // return points in curvilinear coordinates:\n    return proj;\n}\n\n\n/*!\n * Getter function for access to the spline curves control points.\n */\nstd::vector<gmx::RVec>\nSplineCurve3D::ctrlPoints() const\n{\n    return ctrlPoints_;\n}\n\n\n/*!\n * Uses Newton-Cotes quadrature of curve speed to determine the length of the \n * arc between two given parameter values. The specific quadrature rule applied\n * is Boole's rule.\n */\nreal\nSplineCurve3D::arcLengthBoole(const real &lo, const real &hi)\n{\n    // determine intermediate evaluation points:\n    real h = (hi - lo)/4.0;\n    real t2 = lo + 1.0*h;\n    real t3 = lo + 2.0*h;\n    real t4 = lo + 3.0*h;\n\n    // evaluate speed at support points: \n    real s1 = speed(lo);\n    real s2 = speed(t2);\n    real s3 = speed(t3);\n    real s4 = speed(t4);\n    real s5 = speed(hi);\n\n    // evaluate Boole's law:\n    return 2.0*h/45.0*(7.0*s1 + 32.0*s2 + 12.0*s3 + 32.0*s4 + 7.0*s5);\n}\n\n\n/*!\n * Prepares a lookup table that associates an arc length with each knot, where\n * the first knot is assigned an arc length of zero.\n */\nvoid\nSplineCurve3D::prepareArcLengthTable()\n{\n    arcLengthTable_.resize(knots_.size());\n    real segmentLength;\n    for(unsigned int i = 0; i < knots_.size() - 1; i++)\n    {\n        // calculate length of current segment:\n        segmentLength = arcLengthBoole(knots_[i], knots_[i+1]);\n\n        // add to arc length table:\n        arcLengthTable_[i + 1] = arcLengthTable_[i] + segmentLength;\n    }\n\n    // set flag:\n    arcLengthTableAvailable_ = true;\n}\n\n\n/*!\n * Returns arc length value at the control points by simply removing the \n * repeated knot values from the arc length lookup lookup table.\n */\nstd::vector<real>\nSplineCurve3D::ctrlPointArcLength()\n{\n    // check availability:\n    if( arcLengthTableAvailable_ == false )\n    {\n        prepareArcLengthTable();\n    }\n\n    // create copy of table and remove redundant elements:\n    std::vector<real> arcLength(arcLengthTable_.begin() + degree_, \n                                arcLengthTable_.end() - degree_);\n\n    return arcLength;\n}\n\n\n/*!\n * Returns arc length value at first control point.\n */\nreal\nSplineCurve3D::frstPointArcLength()\n{\n    // check availability:\n    if( arcLengthTableAvailable_ == false )\n    {\n        prepareArcLengthTable();\n    }\n\n    return arcLengthTable_.front();\n}\n\n\n/*!\n * Returns arc length value at last control point.\n */\nreal\nSplineCurve3D::lastPointArcLength()\n{\n    // check availability:\n    if( arcLengthTableAvailable_ == false )\n    {\n        prepareArcLengthTable();\n    }\n\n    return arcLengthTable_.back();\n}\n\n\n/*!\n * Returns the parameter value (in the current parameterisation, typically \n * chord length) that corresponds to a given value of arc length. This is done\n * via bisection.\n */\nreal\nSplineCurve3D::arcLengthToParam(real &arcLength)\n{\n    boost::uintmax_t maxIter = 100;\n    real absTol = 0.01*std::sqrt(std::numeric_limits<real>::epsilon());\n\n    // sanity check for arc length table:\n    if( arcLengthTableAvailable_ != true )\n    {\n        prepareArcLengthTable();\n    }\n\n    // handle upper endpoint:\n    if( arcLength == arcLengthTable_.back() )\n    {\n        return knots_.back();\n    }\n\n    // find appropriate interval:\n    std::pair<std::vector<real>::iterator, std::vector<real>::iterator> bounds;\n    bounds = std::equal_range(arcLengthTable_.begin(), arcLengthTable_.end(), arcLength);\n    int idxLo = bounds.second - arcLengthTable_.begin() - 1;\n    int idxHi = bounds.second - arcLengthTable_.begin();\n\n\n    // handle query outside table range:\n    // TODO: add case for query below lower bound and test!\n    if( bounds.second == arcLengthTable_.end() )\n    {\n        return knots_.back() + arcLength - arcLengthTable_.back();\n    }\n    if( bounds.second == arcLengthTable_.begin() )\n    {\n        std::cerr<<\"ERROR: arc length below table value range!\"<<std::endl;\n        std::abort();\n    }\n\n    // initialise bisection interval and lower limit:\n    real tLo = knots_[idxLo];\n    real tHi = knots_[idxHi];\n    real tLi = tLo;\n   \n    // target arc length within this interval:\n    real targetIntervalLength = arcLength - arcLengthTable_[idxLo];\n\n    // termination condition binding:\n    boost::function<bool(real, real)> termCond;\n    termCond = boost::bind(&SplineCurve3D::arcLengthToParamTerm, \n                           this, \n                           _1, \n                           _2,\n                           absTol);\n\n    // objective function binding:\n    boost::function<real(real)> objFun;\n    objFun = boost::bind(&SplineCurve3D::arcLengthToParamObj, \n                         this, \n                         tLi, \n                         _1, \n                         targetIntervalLength);\n\n        \n    std::pair<real, real> result;\n    result = boost::math::tools::toms748_solve(objFun,\n                                               tLo, \n                                               tHi,\n                                               termCond,\n                                               maxIter);\n    \n\n    // best guess if middle of bracketing interval:\n    return 0.5*(result.first + result.second);\n}\n\n\n/*!\n * Termination condition for re-parameterisation optimisation. \n */\nbool\nSplineCurve3D::arcLengthToParamTerm(real lo, real hi, real tol)\n{\n    return std::abs(hi - lo) <= tol;\n}\n\n\n/*!\n * Objective function for re-parameterisation optimisation.\n */\nreal\nSplineCurve3D::arcLengthToParamObj(real lo, real hi, real target)\n{\n    return arcLengthBoole(lo, hi) - target;\n}\n\n\n/*!\n * Computes the squared Euclidean distance between some point and the point \n * on the spline curve with the given parameter value. For efficiency, the\n * square root is not drawn, hence the squared distance is returned.\n */\ndouble\nSplineCurve3D::pointSqDist(gmx::RVec point, double eval)\n{\n    // evaluate spline:\n    gmx::RVec splPoint = evaluate(eval, 0);\n\n    // return squared distance:\n    return (splPoint[XX] - point[XX])*(splPoint[XX] - point[XX]) +\n           (splPoint[YY] - point[YY])*(splPoint[YY] - point[YY]) +\n           (splPoint[ZZ] - point[ZZ])*(splPoint[ZZ] - point[ZZ]);\n}\n\n", "meta": {"hexsha": "0dd91a25499423f12be58d468d16d76b9f77f18c", "size": 23434, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/geometry/spline_curve_3D.cpp", "max_stars_repo_name": "bigginlab/chap", "max_stars_repo_head_hexsha": "17de36442e2e80cb01432e84050c4dfce31fc3a2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-06-28T00:21:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T03:31:32.000Z", "max_issues_repo_path": "src/geometry/spline_curve_3D.cpp", "max_issues_repo_name": "bigginlab/chap", "max_issues_repo_head_hexsha": "17de36442e2e80cb01432e84050c4dfce31fc3a2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 35.0, "max_issues_repo_issues_event_min_datetime": "2019-03-19T21:54:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-17T02:20:42.000Z", "max_forks_repo_path": "src/geometry/spline_curve_3D.cpp", "max_forks_repo_name": "bigginlab/chap", "max_forks_repo_head_hexsha": "17de36442e2e80cb01432e84050c4dfce31fc3a2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2018-10-27T19:35:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-06T01:10:39.000Z", "avg_line_length": 27.6344339623, "max_line_length": 89, "alphanum_fraction": 0.6333532474, "num_tokens": 5821, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.4895237322071103}}
{"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_ISING1D_HPP\n#define NETKET_ISING1D_HPP\n\n#include <mpi.h>\n#include <Eigen/Dense>\n#include <complex>\n#include <iostream>\n#include <vector>\n#include \"Utils/random_utils.hpp\"\n#include \"abstract_hamiltonian.hpp\"\n\nnamespace netket {\n\n/**\n  Transverse field Ising model on an arbitrary graph.\n*/\ntemplate <class G>\nclass Ising : public AbstractHamiltonian {\n  const int nspins_;\n  double h_;\n  double J_;\n\n  const G &graph_;\n\n  /**\n    List of bonds for the interaction part.\n  */\n  std::vector<std::vector<int>> bonds_;\n\n  /**\n    Hilbert space descriptor for this hamiltonian.\n  */\n  Hilbert hilbert_;\n\n public:\n  /**\n    Json constructor.\n    @param G is a graph from which the number of spins and the bonds are\n    obtained.\n    @param pars is a json list of parameters. The default value of J is 1.0\n  */\n  explicit Ising(const G &graph, const json &pars)\n      : nspins_(graph.Nsites()),\n        h_(FieldVal(pars[\"Hamiltonian\"], \"h\")),\n        J_(FieldOrDefaultVal(pars[\"Hamiltonian\"], \"J\", 1.0)),\n        graph_(graph) {\n    Init();\n  }\n\n  void Init() {\n    GenerateBonds();\n\n    // Specifying the hilbert space\n    json hil;\n    hil[\"Hilbert\"][\"Name\"] = \"Spin\";\n    hil[\"Hilbert\"][\"Nspins\"] = nspins_;\n    hil[\"Hilbert\"][\"S\"] = 0.5;\n\n    hilbert_.Init(hil);\n\n    InfoMessage() << \"Transverse-Field Ising model created \" << std::endl;\n    InfoMessage() << \"h = \" << h_ << std::endl;\n    InfoMessage() << \"J = \" << J_ << std::endl;\n  }\n\n  /**\n    Member function generating the bonds on the lattice.\n    bonds[i][k] contains the k-th bond for site i.\n  */\n  void GenerateBonds() {\n    auto adj = graph_.AdjacencyList();\n\n    bonds_.resize(nspins_);\n\n    for (int i = 0; i < nspins_; i++) {\n      for (auto s : adj[i]) {\n        if (s > i) {\n          bonds_[i].push_back(s);\n        }\n      }\n    }\n  }\n\n  /**\n  Member function finding the connected elements of the Hamiltonian.\n  Starting from a given visible state v, it finds all other visible states v'\n  such that the hamiltonian matrix element H(v,v') is different from zero.\n  In general there will be several different connected visible units satisfying\n  this condition, and they are denoted here v'(k), for k=0,1...N_connected.\n  @param v a constant reference to the visible configuration.\n  @param mel(k) is modified to contain matrix elements H(v,v'(k)).\n  @param connector(k) for each k contains a list of sites that should be changed\n  to obtain v'(k) starting from v.\n  @param newconfs(k) is a vector containing the new values of the visible units\n  on the affected sites, such that: v'(k,connectors(k,j))=newconfs(k,j). For the\n  other sites v'(k)=v, i.e. they are equal to the starting visible\n  configuration.\n  */\n  void FindConn(const Eigen::VectorXd &v,\n                std::vector<std::complex<double>> &mel,\n                std::vector<std::vector<int>> &connectors,\n                std::vector<std::vector<double>> &newconfs) const override {\n    connectors.clear();\n    connectors.resize(nspins_ + 1);\n    newconfs.clear();\n    newconfs.resize(nspins_ + 1);\n    mel.resize(nspins_ + 1);\n\n    mel[0] = 0;\n    connectors[0].resize(0);\n    newconfs[0].resize(0);\n\n    for (int i = 0; i < nspins_; i++) {\n      // spin flips\n      mel[i + 1] = -h_;\n      connectors[i + 1].push_back(i);\n      newconfs[i + 1].push_back(-v(i));\n\n      // interaction part\n      for (auto bond : bonds_[i]) {\n        mel[0] -= J_ * v(i) * v(bond);\n      }\n    }\n  }\n\n  const Hilbert &GetHilbert() const override { return hilbert_; }\n};\n\n}  // namespace netket\n\n#endif\n", "meta": {"hexsha": "fe5538fa9f185f3e6249d01fdd4eb6753a224378", "size": 4161, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "NetKet/Hamiltonian/ising.hpp", "max_stars_repo_name": "gugli17/netket", "max_stars_repo_head_hexsha": "4595c7f9d5ab47c99a6a66ce36edc8508d42c726", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "NetKet/Hamiltonian/ising.hpp", "max_issues_repo_name": "gugli17/netket", "max_issues_repo_head_hexsha": "4595c7f9d5ab47c99a6a66ce36edc8508d42c726", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NetKet/Hamiltonian/ising.hpp", "max_forks_repo_name": "gugli17/netket", "max_forks_repo_head_hexsha": "4595c7f9d5ab47c99a6a66ce36edc8508d42c726", "max_forks_repo_licenses": ["Apache-2.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.5, "max_line_length": 80, "alphanum_fraction": 0.6457582312, "num_tokens": 1127, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.4895237257091908}}
{"text": "#pragma once\n#include <boost/serialization/access.hpp>\n\n#include \"Node.hxx\"\n#include \"Tensor.hxx\"\n\nclass Eta : public Tensor {\n private:\n  char i1, i2;\n\n  friend class boost::serialization::access;\n\n public:\n  Eta() = default;\n  Eta(char const i1, char const i2);\n\n  char order () const override;\n\n  void exchangeTensorIndices (std::map<char, char> const & exchange_map) override;\n  int sortIndices () override;\n\n  int evaluate(std::map <char, char> const & eval_map) const override;\n  mpq_class symmetrize() override;\n  bool containsIndex (char i) const override;\n  std::string print () const override;\n  std::string printMaple () const override;\n  int applyTensorSymmetries (int parity) override;\n\n  bool lessThan(Node const * other) const override;\n  bool equals(Node const * other) const override;\n\n  std::unique_ptr<Node> clone () const override;\n\n  char getOther (char i) const;\n\n  template<class Archive>\n  void serialize (Archive & ar, unsigned int const version);\n\n  ~Eta() = default;\n};\n", "meta": {"hexsha": "22488d57fd206d9e5baca2960f05e50fc7ee00b5", "size": 997, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "include/Eta.hxx", "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": "include/Eta.hxx", "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": "include/Eta.hxx", "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": 24.3170731707, "max_line_length": 82, "alphanum_fraction": 0.7161484453, "num_tokens": 248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568416, "lm_q2_score": 0.6297746074044135, "lm_q1q2_score": 0.4895237084088766}}
{"text": "\n// Copyright Aleksey Gurtovoy 2003-2004\n// Copyright Jaap Suter 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// See http://www.boost.org/libs/mpl for documentation.\n\n// $Id$\n// $Date$\n// $Revision$\n\n#include <boost/mpl/bitwise.hpp>\n#include <boost/mpl/integral_c.hpp>\n#include <boost/mpl/aux_/test.hpp>\n\ntypedef integral_c<unsigned int, 0> _0;\ntypedef integral_c<unsigned int, 1> _1;\ntypedef integral_c<unsigned int, 2> _2;\ntypedef integral_c<unsigned int, 8> _8;\ntypedef integral_c<unsigned int, 0xffffffff> _ffffffff;\n\nMPL_TEST_CASE()\n{\n    MPL_ASSERT_RELATION( (bitand_<_0,_0>::value), ==, 0 );\n    MPL_ASSERT_RELATION( (bitand_<_1,_0>::value), ==, 0 );\n    MPL_ASSERT_RELATION( (bitand_<_0,_1>::value), ==, 0 );\n    MPL_ASSERT_RELATION( (bitand_<_0,_ffffffff>::value), ==, 0 );\n    MPL_ASSERT_RELATION( (bitand_<_1,_ffffffff>::value), ==, 1 );\n    MPL_ASSERT_RELATION( (bitand_<_8,_ffffffff>::value), ==, 8 );\n}\n\nMPL_TEST_CASE()\n{\n    MPL_ASSERT_RELATION( (bitor_<_0,_0>::value), ==, 0 );\n    MPL_ASSERT_RELATION( (bitor_<_1,_0>::value), ==, 1 );\n    MPL_ASSERT_RELATION( (bitor_<_0,_1>::value), ==, 1 );\n    MPL_ASSERT_RELATION( (bitor_<_0,_ffffffff>::value), ==, 0xffffffff );\n    MPL_ASSERT_RELATION( (bitor_<_1,_ffffffff>::value), ==, 0xffffffff );\n    MPL_ASSERT_RELATION( (bitor_<_8,_ffffffff>::value), ==, 0xffffffff );\n}\n\nMPL_TEST_CASE()\n{\n    MPL_ASSERT_RELATION( (bitxor_<_0,_0>::value), ==, 0 );\n    MPL_ASSERT_RELATION( (bitxor_<_1,_0>::value), ==, 1 );\n    MPL_ASSERT_RELATION( (bitxor_<_0,_1>::value), ==, 1 );\n    MPL_ASSERT_RELATION( (bitxor_<_0,_ffffffff>::value), ==, (0xffffffff ^ 0) );\n    MPL_ASSERT_RELATION( (bitxor_<_1,_ffffffff>::value), ==, (0xffffffff ^ 1) );\n    MPL_ASSERT_RELATION( (bitxor_<_8,_ffffffff>::value), ==, (0xffffffff ^ 8) );\n}\n\nMPL_TEST_CASE()\n{\n    MPL_ASSERT_RELATION( (shift_right<_0,_0>::value), ==, 0 );\n    MPL_ASSERT_RELATION( (shift_right<_1,_0>::value), ==, 1 );\n    MPL_ASSERT_RELATION( (shift_right<_1,_1>::value), ==, 0 );\n    MPL_ASSERT_RELATION( (shift_right<_2,_1>::value), ==, 1 );\n    MPL_ASSERT_RELATION( (shift_right<_8,_1>::value), ==, 4 );\n}\n\nMPL_TEST_CASE()\n{\n    MPL_ASSERT_RELATION( (shift_left<_0,_0>::value), ==, 0 );\n    MPL_ASSERT_RELATION( (shift_left<_1,_0>::value), ==, 1 );\n    MPL_ASSERT_RELATION( (shift_left<_1,_1>::value), ==, 2 );\n    MPL_ASSERT_RELATION( (shift_left<_2,_1>::value), ==, 4 );\n    MPL_ASSERT_RELATION( (shift_left<_8,_1>::value), ==, 16 );\n}\n", "meta": {"hexsha": "1086b4d49513ad5d0670a147dd50c0a08ac408e3", "size": 2566, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/mpl/test/bitwise.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-12-04T17:42:55.000Z", "max_stars_repo_stars_event_max_datetime": "2015-12-04T17:43:16.000Z", "max_issues_repo_path": "boost/libs/mpl/test/bitwise.cpp", "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/libs/mpl/test/bitwise.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-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.6388888889, "max_line_length": 80, "alphanum_fraction": 0.6625097428, "num_tokens": 847, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568417, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.48952370840887655}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// value.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_EMPIRICAL_DISTRIBUTION_KOLMOGOROV_SMIRNOV_STATISTIC_VALUE_HPP_ER_2010\n#define BOOST_STATISTICS_DETAIL_NON_PARAMETRIC_EMPIRICAL_DISTRIBUTION_KOLMOGOROV_SMIRNOV_STATISTIC_VALUE_HPP_ER_2010\n#include <cmath>\n#include <utility>\n\n#include <boost/type_traits.hpp>\n#include <boost/range.hpp>\n\n#include <boost/numeric/conversion/converter.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/name.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/count.hpp>\n\n#include <boost/statistics/detail/non_parametric/empirical_distribution/ordered_sample.hpp>\n\nnamespace boost{ \nnamespace statistics{\nnamespace detail{\nnamespace empirical_distribution{\nnamespace kolmogorov_smirnov_statistic{\n\nBOOST_PARAMETER_NAME(benchmark_distribution);\n\nnamespace impl{\n\n    // T can be an integer or a float\n    template<typename T,typename T1,typename Comp = std::less<T> >\n\tclass value : public boost::accumulators::accumulator_base\n    {\n        typedef Comp comp_;\n        typedef boost::accumulators::dont_care dont_care_;\n\n        public:\n\n        typedef T1 result_type;\n        typedef T sample_type;\n\n        value(dont_care_){}\n\n        void operator()(dont_care_){}\n\t\t\n        template<typename Args>\n        result_type result(const Args& args)const{\n            namespace ac = boost::accumulators;\n            namespace ed = detail::empirical_distribution;\n            namespace ks = ed::kolmogorov_smirnov_statistic;\n            typedef T1 val_;\n            typedef std::size_t size_;\n            typedef ac::tag::count tag_n_;\n            typedef ed::tag::ordered_sample tag_os_;\n            typedef typename parameter::binding<\n                Args, ac::tag::accumulator>::type cref_acc_set_;\n            typedef typename boost::remove_cv<\n               typename boost::remove_reference<\n                   cref_acc_set_\n                >::type\n            >::type acc_set_;\n            typedef typename ed::result_of::ordered_sample<\n                acc_set_>::type ref_os_; \n            typedef typename boost::remove_const< //in case ref changed to cref\n            \ttypename boost::remove_reference<ref_os_>::type\n            >::type os_;\n            typedef typename boost::range_reference<os_>::type ref_elem_;\n            typedef boost::numeric::converter<val_,size_> converter_;\n\n            ref_os_ ref_os = ac::extract_result<tag_os_>( \n                 args[ ac::accumulator ] );\n            val_ m1 = converter_::convert( 0 );\n            size_ i = 0;\n            size_ n = boost::accumulators::extract::count( \n                args[ ac::accumulator ] );\n            \n            BOOST_FOREACH(ref_elem_ e,ref_os){\n                i += e.second; \n                val_ ecdf = converter_::convert( i ) / converter_::convert( n );\n                val_ true_cdf = cdf( \n                    args[ ks::_benchmark_distribution ] , \n                    e.first \n                );\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 \n}// impl\nnamespace tag\n{\n    template<typename T1 = double>\n    struct value: boost::accumulators::depends_on<\n        empirical_distribution::tag::ordered_sample,\n        accumulators::tag::count\n    >\n    {\n        struct impl{\n            template<typename T,typename W>\n            struct apply{\n                typedef empirical_distribution\n                    ::kolmogorov_smirnov_statistic::impl::value<T,T1> type;\n            };\n        };\n    };\n}// tag\nnamespace result_of{\n\n    template<typename T1,typename AccSet,typename D>\n    struct value{\n    \ttypedef empirical_distribution\n            ::kolmogorov_smirnov_statistic::tag::value<T1> tag_;\n        typedef typename\n            boost::accumulators::detail::template \n            \textractor_result<AccSet,tag_>::type type; \n    };\n\n}\nnamespace extract\n{\n\n    template<typename T1,typename AccSet,typename D>\n    typename kolmogorov_smirnov_statistic::result_of::template \n        value<T1,AccSet,D>::type\n  \tvalue(AccSet const& acc,const D& dist)\n    { \n        namespace ed = detail::empirical_distribution;\n        namespace ks = ed::kolmogorov_smirnov_statistic;\n    \ttypedef ks::tag::value<T1> tag_;\n        return boost::accumulators::extract_result<tag_>(\n            acc,\n            (ks::_benchmark_distribution = dist)\n        );\n  \t}\n\n}// extract\n}// kolmogorov_smirnov_statistic\n}// empirical_distribution\n}// detail\n}// statistics\n}// boost\n\n#endif\n", "meta": {"hexsha": "4782529ec0c8ea6f5b3700f075861a3f1f5ef0cc", "size": 5558, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "non_parametric/boost/statistics/detail/non_parametric/backup_once_in_trunk/non_parametric/empirical_distribution/kolmogorov_smirnov_statistic/value.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/empirical_distribution/kolmogorov_smirnov_statistic/value.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/empirical_distribution/kolmogorov_smirnov_statistic/value.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.8902439024, "max_line_length": 116, "alphanum_fraction": 0.60129543, "num_tokens": 1204, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.810478926981208, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.48947402456800804}}
{"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_EXPRECNEGC_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_EXPRECNEGC_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-exponential\n    Function object implementing exprecnegc capabilities\n\n    Computes the  function: \\f$1-e^{-\\frac1x}\\f$\n\n    @par Semantic:\n\n    For every parameter of floating type T\n\n    @code\n    T r = exprecnegc(x);\n    @endcode\n\n    is equivalent to\n    @code\n    T r = oneminus(exp(-rec((x))));\n    @endcode\n\n    @see exp, exprecneg\n\n  **/\n  Value exprecnegc(Value const & v0);\n} }\n#endif\n\n#include <boost/simd/function/scalar/exprecnegc.hpp>\n#include <boost/simd/function/simd/exprecnegc.hpp>\n\n#endif\n", "meta": {"hexsha": "67e02b574fd8899ea35f3a35b0ca771b7f1957a5", "size": 1091, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/exprecnegc.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/exprecnegc.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/exprecnegc.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": 22.2653061224, "max_line_length": 100, "alphanum_fraction": 0.5765352887, "num_tokens": 249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4894740135094814}}
{"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_COMBINATORIAL_FUNCTIONS_EXPR_IS_PRIME_HPP_INCLUDED\n#define NT2_COMBINATORIAL_FUNCTIONS_EXPR_IS_PRIME_HPP_INCLUDED\n\n#include <nt2/combinatorial/functions/is_prime.hpp>\n#include <nt2/include/functions/scalar/bitwise_cast.hpp>\n#include <nt2/include/functions/globalall.hpp>\n#include <nt2/include/functions/globalmax.hpp>\n#include <nt2/include/functions/primes.hpp>\n#include <nt2/include/functions/scalar/saturate.hpp>\n#include <nt2/include/functions/scalar/rem.hpp>\n#include <nt2/include/functions/scalar/sqrt.hpp>\n#include <nt2/include/functions/scalar/oneplus.hpp>\n#include <nt2/include/functions/scalar/is_flint.hpp>\n#include <nt2/include/functions/scalar/is_less.hpp>\n#include <nt2/include/constants/valmax.hpp>\n#include <nt2/include/constants/false.hpp>\n#include <nt2/sdk/simd/logical.hpp>\n#include <nt2/sdk/meta/as_integer.hpp>\n#include <nt2/sdk/meta/adapted_traits.hpp>\n#include <nt2/core/container/table/table.hpp>\n#include <boost/mpl/if.hpp>\n\nnamespace nt2 { namespace ext\n{\n  NT2_FUNCTOR_IMPLEMENTATION(nt2::tag::is_prime_, tag::cpu_,\n                             (A0),\n                             (unspecified_<A0>)\n                             )\n  {\n    typedef typename A0::value_type                                                   value_type;\n    typedef typename meta::as_logical<value_type>::type                              bvalue_type;\n    typedef nt2::container::table<bvalue_type>                                       result_type;\n    typedef typename nt2::meta::as_integer<value_type>::type                         ivalue_type;\n    typedef typename boost::mpl::if_<meta::is_floating_point<value_type>,\n                                     uint32_t, ivalue_type>::type           itype;\n    NT2_FUNCTOR_CALL(1)\n      {\n        itype m = nt2::oneplus(nt2::sqrt(nt2::globalmax(a0)));\n        nt2::container::table<itype> p = nt2::primes(m);\n        result_type r(nt2::of_size(1, nt2::numel(a0)));\n\n        for(size_t i=1; i <= numel(a0) ; i++)\n          {\n            r(i) = is_prime(a0(i), p);\n          }\n        return r;\n      }\n  };\n} }\n#endif\n", "meta": {"hexsha": "1481fb4bb6a4c8cbdac355aa19377c6fba5d73ab", "size": 2585, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/combinatorial/include/nt2/combinatorial/functions/expr/is_prime.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/combinatorial/include/nt2/combinatorial/functions/expr/is_prime.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/combinatorial/include/nt2/combinatorial/functions/expr/is_prime.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": 43.813559322, "max_line_length": 97, "alphanum_fraction": 0.5895551257, "num_tokens": 590, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788995148791, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4894740079802177}}
{"text": "\n/** A simple neuron / genetic algorithm implemented in pipeline language */\n\n#include <job_stream/job_stream.h>\n\n#include <boost/lexical_cast.hpp>\n#include <cmath>\n#include <memory>\n#include <random>\n\nusing std::unique_ptr;\n\nstd::mt19937 rngEngine;\nstd::uniform_real_distribution<float> rng(-1, 1);\nfloat getRandom() {\n    return rng(rngEngine);\n}\n\nclass NeuralLayer {\npublic:\n    NeuralLayer() {}\n    NeuralLayer(const NeuralLayer& other) {\n        this->inputs = other.inputs;\n        this->neurons = other.neurons;\n        this->weights = other.weights;\n    }\n    NeuralLayer(int inputs, int neurons) : inputs(inputs), neurons(neurons) {\n        for (int i = 0; i < neurons * inputs; i++) {\n            this->weights.push_back(getRandom());\n        }\n    }\n\n    int inputs;\n    int neurons;\n\n    float* eval(float* inputs) {\n        if (!this->lastResults) {\n            this->lastResults.reset(new float[this->neurons]);\n        }\n\n        for (int i = 0; i < this->neurons; i++) {\n            float v = 0.0;\n            for (int j = 0; j < this->inputs; j++) {\n                v += this->weights[i * this->inputs + j] * inputs[j];\n            }\n            this->lastResults.get()[i] = 1.f / (1.f + exp(-v));\n        }\n\n        return this->lastResults.get();\n    }\n\n    void initFrom(NeuralLayer* a, NeuralLayer* b) {\n        this->inputs = a->inputs;\n        this->neurons = a->neurons;\n        std::uniform_int_distribution<> dist(1, a->weights.size() - 2);\n        int split = dist(rngEngine);\n        for (int i = 0; i < split; i++) {\n            this->weights.push_back(a->weights[i]);\n        }\n        for (int i = split, m = a->weights.size(); i < m; i++) {\n            this->weights.push_back(b->weights[i]);\n        }\n\n        //Mutate!\n        std::uniform_int_distribution<> wdist(0, a->weights.size() / 2);\n        std::uniform_int_distribution<> mut(0, this->weights.size());\n        for (int j = 0, k = wdist(rngEngine); j < k; j++) {\n            this->weights[mut(rngEngine)] += 0.2 * getRandom();\n        }\n    }\n\nprivate:\n    std::vector<float> weights;\n    unique_ptr<float[]> lastResults;\n\n    friend class boost::serialization::access;\n    template<class Archive>\n    void serialize(Archive& ar, const unsigned int version) {\n        ar & this->inputs;\n        ar & this->neurons;\n        ar & this->weights;\n    }\n};\n\n\nclass NeuralNet {\npublic:\n    NeuralNet() {}\n    NeuralNet(int neurons, int inputs, int outputs) {\n        unique_ptr<NeuralLayer> layer;\n        layer.reset(new NeuralLayer(inputs, neurons));\n        this->layers.push_back(std::move(layer));\n        layer.reset(new NeuralLayer(neurons, neurons));\n        this->layers.push_back(std::move(layer));\n        layer.reset(new NeuralLayer(neurons, outputs));\n        this->layers.push_back(std::move(layer));\n    }\n    NeuralNet(const NeuralNet& other) {\n        unique_ptr<NeuralLayer> layer;\n        for (int i = 0, m = other.layers.size(); i < m; i++) {\n            layer.reset(new NeuralLayer(*other.layers[i]));\n            this->layers.push_back(std::move(layer));\n        }\n        this->score = other.score;\n    }\n    NeuralNet(NeuralNet& a, NeuralNet& b) {\n        //Cross a and b\n        unique_ptr<NeuralLayer> layer;\n        for (int i = 0, m = a.layers.size(); i < m; i++) {\n            layer.reset(new NeuralLayer());\n            layer->initFrom(a.layers[i].get(), b.layers[i].get());\n            this->layers.push_back(std::move(layer));\n        }\n    }\n\n    float score;\n\n    float getError(YAML::Node& array) {\n        unique_ptr<float[]> inputs(new float[array.size()]);\n        for (int i = 0, m = array.size(); i < m; i++) {\n            inputs[i] = array[i].as<float>();\n        }\n\n        float* layerInput = inputs.get();\n        for (int i = 0, m = this->layers.size(); i < m; i++) {\n            layerInput = this->layers[i]->eval(layerInput);\n        }\n\n        //layerInput now == output\n        float score = 0;\n        for (int base = this->layers[0]->inputs, i = 0,\n                m = array.size() - base; i < m; i++) {\n            score += (layerInput[i] - inputs[base + i])\n                    * (layerInput[i] - inputs[base + i]);\n        }\n        return score;\n    }\n\nprivate:\n    std::vector<unique_ptr<NeuralLayer>> layers;\n\n    friend class boost::serialization::access;\n    template<class Archive>\n    void serialize(Archive& ar, const unsigned int version) {\n        ar & this->score;\n        int m = this->layers.size();\n        ar & m;\n        for (int i = 0; i < m; i++) {\n            if (Archive::is_loading::value) {\n                unique_ptr<NeuralLayer> ptr(new NeuralLayer());\n                ar & *ptr;\n                this->layers.push_back(std::move(ptr));\n            }\n            else {\n                ar & *this->layers[i];\n            }\n        }\n    }\n};\n\n\nclass NetworkPopulace {\npublic:\n    NetworkPopulace() {\n    }\n\n    NetworkPopulace(const NetworkPopulace& other) {\n        for (size_t i = 0, m = other.networks.size(); i < m; i++) {\n            this->networks.push_back(unique_ptr<NeuralNet>(\n                    new NeuralNet(*other.networks[i])));\n        }\n    }\n\n    void addNetwork(unique_ptr<NeuralNet> network) {\n        this->networks.push_back(std::move(network));\n    }\n\n    void joinNetwork(unique_ptr<NetworkPopulace> other) {\n        for (auto& mem : other->networks) {\n            this->networks.push_back(std::move(mem));\n        }\n    }\n\n    NeuralNet& bestNetwork() {\n        float best = this->bestScore();\n        for (int i = 0, m = this->networks.size(); i < m; i++) {\n            auto* net = this->networks[i].get();\n            if (net->score == best) {\n                return *net;\n            }\n        }\n        throw std::runtime_error(\"No best network?\");\n    }\n\n    float bestScore() {\n        float min = 1e35f;\n        for (int i = 0, m = this->networks.size(); i < m; i++) {\n            auto* net = this->networks[i].get();\n            if (net->score < min) {\n                min = net->score;\n            }\n        }\n        return min;\n    }\n\n    void clear() {\n        this->networks.clear();\n    }\n\n    void cross() {\n        std::vector<NeuralNet*> newNets;\n        for (int i = 0, m = this->networks.size() - 1; i < m; i++) {\n            NeuralNet& src1 = this->monteCarlo(0);\n            NeuralNet& src2 = this->monteCarlo(&src1);\n            newNets.push_back(new NeuralNet(src1, src2));\n        }\n        //Elite!\n        for (int i = 0, m = this->networks.size(); i < m; i++) {\n            if (this->networks[i]->score == this->bestScore()) {\n                newNets.push_back(this->networks[i].release());\n                break;\n            }\n        }\n        this->networks.clear();\n        for (int i = 0, m = newNets.size(); i < m; i++) {\n            unique_ptr<NeuralNet> ptr(newNets[i]);\n            this->networks.push_back(std::move(ptr));\n        }\n    }\n\n    NeuralNet& monteCarlo(NeuralNet* dontChoose) {\n        float max = 0.0;\n        float total = 0.0;\n        int m = this->networks.size();\n        for (int i = 0; i < m; i++) {\n            if (this->networks[i].get() == dontChoose) continue;\n            float score = this->networks[i]->score;\n            if (score > max) max = score;\n        }\n        max *= 1.01;\n        for (int i = 0; i < m; i++) {\n            if (this->networks[i].get() == dontChoose) continue;\n            total += max - this->networks[i]->score;\n        }\n\n        std::uniform_real_distribution<float> rngMonte(0, total);\n        float slice = rngMonte(rngEngine);\n        for (int i = 0; i < m; i++) {\n            if (this->networks[i].get() == dontChoose) continue;\n            slice -= max - this->networks[i]->score;\n            if (slice <= 0.0) {\n                return *this->networks[i];\n            }\n        }\n\n        throw std::runtime_error(\"monteCarlo fell out bottom\");\n    }\n\n    int size() {\n        return this->networks.size();\n    }\n\n    NeuralNet& operator[](int index) {\n        return *this->networks[index];\n    }\n\nprivate:\n    std::vector<unique_ptr<NeuralNet>> networks;\n\n    friend class boost::serialization::access;\n    template<class Archive>\n    void serialize(Archive& ar, const unsigned int version) {\n        int m = this->networks.size();\n        ar & m;\n        for (int i = 0; i < m; i++) {\n            if (Archive::is_loading::value) {\n                unique_ptr<NeuralNet> ptr(new NeuralNet());\n                ar & *ptr;\n                this->networks.push_back(std::move(ptr));\n            }\n            else {\n                ar & *this->networks[i];\n            }\n        }\n    }\n};\n\n\nclass MakeNetworks : public job_stream::Job<MakeNetworks, int> {\npublic:\n    static const char* NAME() { return \"makeNetworks\"; }\n\n    void handleWork(unique_ptr<int> networkCount) {\n        //Initialize networkCount networks\n        auto conf = this->config;\n        for (int i = 0; i < *networkCount; i++) {\n            this->emit(NeuralNet(conf[\"neurons\"].as<int>(),\n                    conf[\"numInputs\"].as<int>(),\n                    conf[\"numOutputs\"].as<int>()));\n        }\n    }\n} makeNetworks;\n\n\nclass EvalNetwork : public job_stream::Job<EvalNetwork, NeuralNet> {\npublic:\n    static const char* NAME() { return \"evalNetwork\"; }\n\n    void handleWork(unique_ptr<NeuralNet> network) {\n        float score = 0.0;\n        auto tests = this->globalConfig[\"tests\"].as<\n                std::vector<YAML::Node>>();\n        for (int i = 0, m = tests.size(); i < m; i++) {\n            score += network->getError(tests[i]);\n        }\n        network->score = score;\n        this->emit(*network);\n    }\n} evalNetwork;\n\n\nclass CheckErrorAndBreed : public job_stream::Reducer<CheckErrorAndBreed, NetworkPopulace,\n        NeuralNet> {\npublic:\n    static const char* NAME() { return \"checkErrorAndBreed\"; }\n\n    void handleAdd(NetworkPopulace& current, unique_ptr<NeuralNet> work) {\n        current.addNetwork(std::move(work));\n    }\n\n    void handleJoin(NetworkPopulace& current,\n            unique_ptr<NetworkPopulace> other) {\n        current.joinNetwork(std::move(other));\n    }\n\n    void handleDone(NetworkPopulace& current) {\n        float bestScore = current.bestScore();\n        NeuralNet& best = current.bestNetwork();\n        if (bestScore < this->config[\"error\"].as<float>()) {\n            std::ostringstream ss;\n            ss << \"Done!  Best error: \" << boost::lexical_cast<std::string>(\n                    current.bestScore());\n            ss << \".\";\n            this->emit(ss.str());\n            return;\n        }\n        else {\n            printf(\"Best score: %.3f (\", bestScore);\n            auto tests = this->globalConfig[\"tests\"]\n                    .as<std::vector<YAML::Node>>();\n            for (int i = 0, m = tests.size(); i < m; i++) {\n                if (i != 0) {\n                    printf(\", \");\n                }\n                printf(\"%f\", best.getError(tests[i]));\n            }\n            printf(\")\\n\");\n        }\n\n        current.cross();\n        for (int i = 0, m = current.size(); i < m; i++) {\n            this->recur(current[i]);\n        }\n\n        //Wait for those crossed networks to come through, so we maintain\n        //population size.\n        current.clear();\n    }\n} checkErrorAndBreed;\n\n\n\nint main(int argc, char* argv[]) {\n    job_stream::runProcessor(argc, argv);\n    return 0;\n}\n", "meta": {"hexsha": "bc3af76285d253cffa9ebfc1b1c37dd7f541a2e3", "size": 11302, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/neuron.cpp", "max_stars_repo_name": "wwoods/job_stream", "max_stars_repo_head_hexsha": "7bed3d9d42b8a08bcc92dfbc632f389d6ecc9b7d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2015-01-02T03:52:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T01:51:30.000Z", "max_issues_repo_path": "example/neuron.cpp", "max_issues_repo_name": "wwoods/job_stream", "max_issues_repo_head_hexsha": "7bed3d9d42b8a08bcc92dfbc632f389d6ecc9b7d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-08-16T10:42:33.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-29T17:54:36.000Z", "max_forks_repo_path": "example/neuron.cpp", "max_forks_repo_name": "wwoods/job_stream", "max_forks_repo_head_hexsha": "7bed3d9d42b8a08bcc92dfbc632f389d6ecc9b7d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2015-04-26T17:51:12.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T18:26:14.000Z", "avg_line_length": 29.9787798408, "max_line_length": 90, "alphanum_fraction": 0.5222969386, "num_tokens": 2872, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4894511069970108}}
{"text": "#include <GazeEstimation.h>\n#include <RotationHelpers.h>\n#include <opencv2/core/core.hpp>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <LandmarkDetectorFunc.h>\n#include <LandmarkDetectorModel.h>\n#include \"MyGazeEstimation.h\"\n\nusing namespace Eigen;\n\nvoid MyGazeEstimation::EstimateGaze(const LandmarkDetector::CLNF& clnf, cv::Point3f& gaze, float fx, float fy, float cx, float cy, bool is_left)\n{\n    cv::Vec6f head = LandmarkDetector::GetPose(clnf, fx, fy, cx, cy);\n    cv::Matx33f rot = Utilities::Euler2RotationMatrix(cv::Vec3f(head(3), head(4), head(5)));\n\n    int part = -1;\n    for (size_t i = 0; i < clnf.hierarchical_models.size(); i++) {\n        if (is_left) {\n            if (clnf.hierarchical_model_names[i] == \"left_eye_28\") {\n                part = i;\n            }\n        } else {\n            if (clnf.hierarchical_model_names[i] == \"right_eye_28\") {\n                part = i;\n            }\n        }\n    }\n    if (part == -1) {\n        gaze = cv::Point3f(0, 0, 0);\n        return;\n    }\n\n    cv::Mat eye_landmarks = clnf.hierarchical_models[part].GetShape(fx, fy, cx, cy);\n    cv::Point3f pupil = GazeAnalysis::GetPupilPosition(eye_landmarks);\n    cv::Point3f ray_dir = pupil / norm(pupil);\n    cv::Mat face_landmarks = clnf.GetShape(fx, fy, cx, cy).t();\n\n    int eye_index = 1;\n    if (is_left) {\n        eye_index = 0;\n    }\n\n    cv::Mat offset_mat = (cv::Mat_<float>(3, 1) << 0.0, -3.5, 7.0);\n    cv::Mat offset_mat_t = (cv::Mat(rot) * offset_mat ).t();\n    cv::Point3f eye_offset = cv::Point3f(offset_mat_t);\n    cv::Mat mat_l = face_landmarks.row(36 + eye_index * 6);\n    cv::Mat mat_r = face_landmarks.row(39 + eye_index * 6);\n    cv::Point3f lid_l = cv::Point3f(mat_l);\n    cv::Point3f lid_r = cv::Point3f(mat_r);\n    cv::Point3f eye_center = (lid_l + lid_r) / 2.0;\n    cv::Point3f eyeball_center = eye_center + eye_offset;\n\n    // 2D\u306b\u518d\u6295\u5f71\n    float d = eye_center.z;\n    float l2dx = lid_l.x * d / lid_l.z;\n    float l2dy = lid_l.y * d / lid_l.z;\n    float r2dx = lid_r.x * d / lid_r.z;\n    float r2dy = lid_r.y * d / lid_r.z;\n    float p2dx = pupil.x * d / pupil.z;\n    float p2dy = pupil.y * d / pupil.z;\n    float t = (p2dx - r2dx) / (l2dx - r2dx);\n    if (t < 0.0) t = 0.0; else if (t > 1.0) t = 1.0;\n    float newZ = lid_r.z + (lid_l.z - lid_r.z) * t;\n    // \u65b0\u3057\u3044z\u3067\u3001\u9ed2\u76ee\u306e\u4e2d\u5fc3\u4f4d\u7f6e\u3092\u518d\u8a08\u7b97\u3059\u308b\u3002\n    pupil.x = pupil.x * newZ / pupil.z;\n    pupil.y = pupil.y * newZ / pupil.z;\n    pupil.z = newZ;\n    ray_dir = pupil / norm(pupil); \n\n    cv::Point3f gaze_axis = pupil - eyeball_center;\n\n    gaze = gaze_axis / norm(gaze_axis);\n}\n\n", "meta": {"hexsha": "181af13c503066e15f78f8b5c08e4ca1b5db00be", "size": 2553, "ext": "cc", "lang": "C++", "max_stars_repo_path": "MyGazeEstimation.cc", "max_stars_repo_name": "errno-mmd/readfacevmd", "max_stars_repo_head_hexsha": "92fcecdc6d17b86ddc7d3af207f9d03529dc7ca0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 49.0, "max_stars_repo_stars_event_min_datetime": "2018-05-19T07:28:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-21T07:16:06.000Z", "max_issues_repo_path": "MyGazeEstimation.cc", "max_issues_repo_name": "errno-mmd/readfacevmd", "max_issues_repo_head_hexsha": "92fcecdc6d17b86ddc7d3af207f9d03529dc7ca0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2018-05-29T10:10:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-10T00:42:49.000Z", "max_forks_repo_path": "MyGazeEstimation.cc", "max_forks_repo_name": "errno-mmd/readfacevmd", "max_forks_repo_head_hexsha": "92fcecdc6d17b86ddc7d3af207f9d03529dc7ca0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-03-03T20:58:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-15T09:06:47.000Z", "avg_line_length": 33.5921052632, "max_line_length": 144, "alphanum_fraction": 0.5992949471, "num_tokens": 869, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4894511069970108}}
{"text": "#include <starpu.h>\n#include <starpu_mpi.h>\n#include <vector>\n#include <memory>\n#include <iostream>\n#ifdef USE_MKL\n#include <mkl_cblas.h>\n#include <mkl_lapacke.h>\n#else\n#include <cblas.h>\n#include <lapacke.h>\n#endif\n#include <Eigen/Core>\n#include <Eigen/Cholesky>\n#include <mpi.h>\n\nvoid gemm(void *buffers[], void *cl_arg) {\n    double *A0 = (double *)STARPU_MATRIX_GET_PTR(buffers[0]);\n    double *A1 = (double *)STARPU_MATRIX_GET_PTR(buffers[1]);\n    double *A2 = (double *)STARPU_MATRIX_GET_PTR(buffers[2]);\n    int nx     = STARPU_MATRIX_GET_NY(buffers[0]);\n    int ny     = STARPU_MATRIX_GET_NX(buffers[0]);\n    assert(nx == ny);\n    cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, nx, nx, nx, 1.0, A0, nx, A1, nx, 1.0, A2, nx);\n  }\nstruct starpu_codelet gemm_cl = {\n    .where = STARPU_CPU,\n    .cpu_funcs = { gemm, NULL },\n    .nbuffers = 3,\n    .modes = { STARPU_R, STARPU_R, STARPU_RW }\n};\n\nauto val = [&](int i, int j) { return  (double) (i % 37 + j * i % 49);};\n", "meta": {"hexsha": "74cb579766bdbddb3d70ce49c16328d38aa2be49", "size": 980, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "starpu/gemm_shared.hpp", "max_stars_repo_name": "leopoldcambier/tasktorrent_paper_benchmarks", "max_stars_repo_head_hexsha": "86ef5c98fa95d6bd42571cd7775f7eae8ddd0e6b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "starpu/gemm_shared.hpp", "max_issues_repo_name": "leopoldcambier/tasktorrent_paper_benchmarks", "max_issues_repo_head_hexsha": "86ef5c98fa95d6bd42571cd7775f7eae8ddd0e6b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "starpu/gemm_shared.hpp", "max_forks_repo_name": "leopoldcambier/tasktorrent_paper_benchmarks", "max_forks_repo_head_hexsha": "86ef5c98fa95d6bd42571cd7775f7eae8ddd0e6b", "max_forks_repo_licenses": ["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.8235294118, "max_line_length": 105, "alphanum_fraction": 0.6540816327, "num_tokens": 330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4894511020708524}}
{"text": "// Boost.Geometry Index\n//\n// Quickbook Examples\n//\n// Copyright (c) 2011-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//[rtree_polygons_vector\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point.hpp>\n#include <boost/geometry/geometries/box.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n\n#include <boost/geometry/index/rtree.hpp>\n\n#include <cmath>\n#include <vector>\n#include <iostream>\n#include <boost/foreach.hpp>\n\nnamespace bg = boost::geometry;\nnamespace bgi = boost::geometry::index;\n\nint main()\n{\n    typedef bg::model::point<float, 2, bg::cs::cartesian> point;\n    typedef bg::model::box<point> box;\n    typedef bg::model::polygon<point, false, false> polygon; // ccw, open polygon\n    typedef std::pair<box, unsigned> value;\n\n    // polygons\n    std::vector<polygon> polygons;\n\n    // create some polygons\n    for ( unsigned i = 0 ; i < 10 ; ++i )\n    {\n        // create a polygon\n        polygon p;\n        for ( float a = 0 ; a < 6.28316f ; a += 1.04720f )\n        {\n            float x = i + int(10*::cos(a))*0.1f;\n            float y = i + int(10*::sin(a))*0.1f;\n            p.outer().push_back(point(x, y));\n        }\n\n        // add polygon\n        polygons.push_back(p);\n    }\n\n    // display polygons\n    std::cout << \"generated polygons:\" << std::endl;\n    BOOST_FOREACH(polygon const& p, polygons)\n        std::cout << bg::wkt<polygon>(p) << std::endl;\n\n    // create the rtree using default constructor\n    bgi::rtree< value, bgi::rstar<16, 4> > rtree;\n\n    // fill the spatial index\n    for ( unsigned i = 0 ; i < polygons.size() ; ++i )\n    {\n        // calculate polygon bounding box\n        box b = bg::return_envelope<box>(polygons[i]);\n        // insert new value\n        rtree.insert(std::make_pair(b, i));\n    }\n\n    // find values intersecting some area defined by a box\n    box query_box(point(0, 0), point(5, 5));\n    std::vector<value> result_s;\n    rtree.query(bgi::intersects(query_box), std::back_inserter(result_s));\n\n    // find 5 nearest values to a point\n    std::vector<value> result_n;\n    rtree.query(bgi::nearest(point(0, 0), 5), std::back_inserter(result_n));\n\n    // note: in Boost.Geometry the WKT representation of a box is polygon\n\n    // note: the values store the bounding boxes of polygons\n    // the polygons aren't used for querying but are printed\n\n    // display results\n    std::cout << \"spatial query box:\" << std::endl;\n    std::cout << bg::wkt<box>(query_box) << std::endl;\n    std::cout << \"spatial query result:\" << std::endl;\n    BOOST_FOREACH(value const& v, result_s)\n        std::cout << bg::wkt<polygon>(polygons[v.second]) << std::endl;\n\n    std::cout << \"knn query point:\" << std::endl;\n    std::cout << bg::wkt<point>(point(0, 0)) << std::endl;\n    std::cout << \"knn query result:\" << std::endl;\n    BOOST_FOREACH(value const& v, result_n)\n        std::cout << bg::wkt<polygon>(polygons[v.second]) << std::endl;\n\n    return 0;\n}\n\n//]\n", "meta": {"hexsha": "28fc9c183872ccd6c02e714d5aa294984c0c31fe", "size": 3113, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/doc/index/src/examples/rtree/polygons_vector.cpp", "max_stars_repo_name": "Manu343726/boost-cmake", "max_stars_repo_head_hexsha": "009c3843b49a56880d988ffdca6d909f881edb3d", "max_stars_repo_licenses": ["BSL-1.0"], "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": "libs/geometry/doc/index/src/examples/rtree/polygons_vector.cpp", "max_issues_repo_name": "Manu343726/boost-cmake", "max_issues_repo_head_hexsha": "009c3843b49a56880d988ffdca6d909f881edb3d", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 623.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T23:45:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T11:15:23.000Z", "max_forks_repo_path": "libs/geometry/doc/index/src/examples/rtree/polygons_vector.cpp", "max_forks_repo_name": "Manu343726/boost-cmake", "max_forks_repo_head_hexsha": "009c3843b49a56880d988ffdca6d909f881edb3d", "max_forks_repo_licenses": ["BSL-1.0"], "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.5196078431, "max_line_length": 81, "alphanum_fraction": 0.6244779955, "num_tokens": 884, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723316991792861, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.4894409705237594}}
{"text": "\r\n\r\n#include \"PID_3DOF.h\"\r\n#include <Eigen/Dense>\r\nusing Eigen::Matrix;\r\n//Sets initial errors to zero\r\nvoid initializePID(PID_3DOF* PID){\r\n\tMatrix<float, 3, 1> zeros = Matrix<float, 3, 1>::Zero(3, 1);\r\n\r\n\tPID->e_prop = zeros;\r\n\tPID->e_deriv = zeros;\r\n\tPID->e_integ = zeros;\r\n}\r\n\r\n//Sets integral error to zero\r\nvoid resetIntegralErrorPID(PID_3DOF* PID){\r\n\tPID->e_integ = Matrix<float, 3, 1>::Zero(3, 1);\r\n}\r\n\r\n//Update Kp, Ki and Kd in the PID\r\nvoid updateControlParamPID(PID_3DOF* PID, Matrix<float, 3, 1> K_p, Matrix<float, 3, 1> K_i, Matrix<float, 3, 1> K_d, Matrix<float, 3, 1> maxInteg){\r\n\tPID->K_p = K_p;\r\n\tPID->K_d = K_d;\r\n\tPID->K_i = K_i;\r\n\tPID->maxInteg = maxInteg;\r\n}\r\n\r\n//Update all errors\r\nvoid updateErrorPID(PID_3DOF* PID, Matrix<float, 3, 1> feedForward, Matrix<float, 3, 1> e_prop, Matrix<float, 3, 1> e_deriv, float dt){\r\n\r\n\tPID->feedForward = feedForward;\r\n\tPID->e_prop = e_prop;\r\n\tPID->e_deriv = e_deriv;\r\n\tPID->e_integ = PID->e_integ+(e_prop*dt); //e_integ = e_integ + e_prop*dt\r\n\r\n\t//Saturate integral error\r\n\tfor (int i = 0; i < 3; i++){\r\n\t\tif (PID->e_integ(i) > PID->maxInteg(i)){\r\n\t\t\tPID->e_integ(i) = PID->maxInteg(i);\r\n\t\t}\r\n\t\telse if (PID->e_integ(i) < -PID->maxInteg(i)){\r\n\t\t\tPID->e_integ(i) = -PID->maxInteg(i);\r\n\t\t}\r\n\t}\r\n}\r\n\r\n//Calculate output of PID\r\nMatrix<float, 3, 1> outputPID(PID_3DOF PID){\r\n\tMatrix<float, 3, 1> PID_out;\r\n\tPID_out =  PID.feedForward + \r\n\t\t\t\tPID.e_prop.cwiseProduct(PID.K_p) + \r\n\t\t\t\tPID.e_deriv.cwiseProduct(PID.K_d) + \r\n\t\t\t\tPID.e_integ.cwiseProduct(PID.K_i);\t\t\r\n\treturn PID_out;\r\n}\r\n\r\n//Helper functions to parse the config file\r\nvoid split(const string &s, char delim, vector<string> &elems) {\r\n    stringstream ss(s);\r\n    string item;\r\n    while (getline(ss, item, delim)) {\r\n        elems.push_back(item);\r\n    }\r\n}\r\n\r\n\r\nvector<string> split(const string &s, char delim) {\r\n    vector<string> elems;\r\n    split(s, delim, elems);\r\n    return elems;\r\n}\r\n\r\nvoid updatePar(PID_3DOF *PID_att, PID_3DOF *PID_angVel, PID_3DOF *PID_pos,char const *AttFile,char const *PosFile) {\r\n\tMatrix<float, 3, 1> Zero_3x1 = Matrix<float, 3, 1>::Zero(3, 1);\r\n\tMatrix<float, 3, 1> KP_RPY = Zero_3x1, KD_RPY = Zero_3x1, KI_RPY = Zero_3x1, maxInteg_RPY = Zero_3x1;\r\n\tMatrix<float, 3, 1> KP_w = Zero_3x1, KD_w = Zero_3x1, KI_w = Zero_3x1, maxInteg_w = Zero_3x1;\r\n\tMatrix<float, 3, 1> KP_Pos = Zero_3x1, KD_Pos = Zero_3x1, KI_Pos = Zero_3x1, maxInteg_Pos = Zero_3x1;\r\n\tchar AttParamPath[64];\r\n\tchar PosParamPath[64];\r\n    string line;\r\n    vector<string> line_vec;\r\n\r\n    sprintf(AttParamPath,\"/home/root/%s\",AttFile);\r\n    sprintf(PosParamPath,\"/home/root/%s\",PosFile);\r\n\r\n    // printf(\"%s\\n\",AttParamPath);\r\n\r\n    //Get parameters for attitude controller\r\n    ifstream myfile (AttParamPath);\r\n    if (myfile.is_open()) {\r\n\t\twhile (getline (myfile ,line)) {\r\n\t\t    line_vec = split(line, ' ');\r\n\t\t    if (line_vec[0] == \"KP_R\") {\r\n\t            KP_RPY(0) = atof(line_vec[2].c_str());\r\n\t\t    }\r\n\t\t    else if (line_vec[0] == \"KP_P\") {\r\n\t\t\t\tKP_RPY(1) = atof(line_vec[2].c_str());\r\n\t\t    }\r\n\t\t    else if (line_vec[0] == \"KP_Y\") {\r\n\t\t\t\tKP_RPY(2) = atof(line_vec[2].c_str());\r\n\t\t    }\r\n\t\t    else if (line_vec[0] == \"KD_R\") {\r\n\t            \tKD_RPY(0) = atof(line_vec[2].c_str());\r\n\t\t    }\r\n\t\t    else if (line_vec[0] == \"KD_P\") {\r\n\t\t\t\tKD_RPY(1) = atof(line_vec[2].c_str());\r\n\t\t    }\r\n\t\t    else if (line_vec[0] == \"KD_Y\") {\r\n\t\t\t\tKD_RPY(2) = atof(line_vec[2].c_str());\r\n\t\t    }\r\n\t\t    if (line_vec[0] == \"KI_R\") {\r\n\t            KI_RPY(0) = atof(line_vec[2].c_str());\r\n\t\t    }\r\n\t\t    else if (line_vec[0] == \"KI_P\") {\r\n\t\t\t\tKI_RPY(1) = atof(line_vec[2].c_str());\r\n\t\t    }\r\n\t\t    else if (line_vec[0] == \"KI_Y\") {\r\n\t\t\t\tKI_RPY(2) = atof(line_vec[2].c_str());\r\n\t\t    }\r\n\t\t    if (line_vec[0] == \"maxInteg_R\") {\r\n\t            maxInteg_RPY(0) = atof(line_vec[2].c_str());\r\n\t\t    }\r\n\t\t    else if (line_vec[0] == \"maxInteg_P\") {\r\n\t\t\t\tmaxInteg_RPY(1) = atof(line_vec[2].c_str());\r\n\t\t    }\r\n\t\t    else if (line_vec[0] == \"maxInteg_Y\") {\r\n\t\t\t\tmaxInteg_RPY(2) = atof(line_vec[2].c_str());\r\n\t\t    }\r\n\t\t    else if (line_vec[0] == \"KP_wx\") {\r\n\t\t\t\tKP_w(0) = atof(line_vec[2].c_str());\r\n\t\t    }\r\n\t\t    else if (line_vec[0] == \"KP_wy\") {\r\n\t\t\t\tKP_w(1) = atof(line_vec[2].c_str());\r\n\t\t    }\r\n\t\t    else if (line_vec[0] == \"KP_wz\") {\r\n\t\t        KP_w(2)  = atof(line_vec[2].c_str());\r\n\t\t    }\r\n\t\t    else if (line_vec[0] == \"KD_wx\") {\r\n\t\t\t\tKD_w(0) = atof(line_vec[2].c_str());\r\n\t\t    }\r\n\t\t    else if (line_vec[0] == \"KD_wy\") {\r\n\t\t\t\tKD_w(1) = atof(line_vec[2].c_str());\r\n\t\t    }\r\n\t\t    else if (line_vec[0] == \"KD_wz\") {\r\n\t\t        KD_w(2) = atof(line_vec[2].c_str());\r\n\t\t    }\r\n\t\t    else if (line_vec[0] == \"KI_wx\") {\r\n\t\t\t\tKI_w(0) = atof(line_vec[2].c_str());\r\n\t\t    }\r\n\t\t    else if (line_vec[0] == \"KI_wy\") {\r\n\t\t\t\tKI_w(1) = atof(line_vec[2].c_str());\r\n\t\t    }\r\n\t\t    else if (line_vec[0] == \"KI_wz\") {\r\n\t\t        KI_w(2) = atof(line_vec[2].c_str());\r\n\t\t    }\r\n\t\t    if (line_vec[0] == \"maxInteg_wx\") {\r\n\t            maxInteg_w(0) = atof(line_vec[2].c_str());\r\n\t\t    }\r\n\t\t    else if (line_vec[0] == \"maxInteg_wy\") {\r\n\t\t\t\tmaxInteg_w(1) = atof(line_vec[2].c_str());\r\n\t\t    }\r\n\t\t    else if (line_vec[0] == \"maxInteg_wz\") {\r\n\t\t\t\tmaxInteg_w(2) = atof(line_vec[2].c_str());\r\n\t\t    }\r\n\t\t}\r\n\t\tmyfile.close();\r\n\t\tupdateControlParamPID(PID_att, KP_RPY, KI_RPY, KD_RPY, maxInteg_RPY);\r\n\t\tupdateControlParamPID(PID_angVel, KP_w, KI_w, KD_w, maxInteg_w);\r\n    }\r\n    else {\r\n\t\tprintf(\"Unable to open file %s \\n\",AttParamPath); \r\n    }\r\n\r\n    //Get parameters for position controller\r\n    ifstream myfile2 (PosParamPath);\r\n    if (myfile2.is_open()) {\r\n\t\twhile (getline (myfile2 ,line)) {\r\n\t\t    line_vec = split(line, ' ');\r\n\t\t    if (line_vec[0] == \"KP_X\") {\r\n\t            KP_Pos(0) = atof(line_vec[2].c_str());\r\n\t\t    }\r\n\t\t    else if (line_vec[0] == \"KP_Y\") {\r\n\t\t\t\tKP_Pos(1) = atof(line_vec[2].c_str());\r\n\t\t    }\r\n\t\t    else if (line_vec[0] == \"KP_Z\") {\r\n\t\t\t\tKP_Pos(2) = atof(line_vec[2].c_str());\r\n\t\t    }\r\n\t\t    else if (line_vec[0] == \"KD_X\") {\r\n\t            KD_Pos(0) = atof(line_vec[2].c_str());\r\n\t\t    }\r\n\t\t    else if (line_vec[0] == \"KD_Y\") {\r\n\t\t\t\tKD_Pos(1) = atof(line_vec[2].c_str());\r\n\t\t    }\r\n\t\t    else if (line_vec[0] == \"KD_Z\") {\r\n\t\t\t\tKD_Pos(2) = atof(line_vec[2].c_str());\r\n\t\t    }\r\n\t\t    else if (line_vec[0] == \"KI_X\") {\r\n\t            KI_Pos(0) = atof(line_vec[2].c_str());\r\n\t\t    }\r\n\t\t    else if (line_vec[0] == \"KI_Y\") {\r\n\t\t\t\tKI_Pos(1) = atof(line_vec[2].c_str());\r\n\t\t    }\r\n\t\t    else if (line_vec[0] == \"KI_Z\") {\r\n\t\t\t\tKI_Pos(2) = atof(line_vec[2].c_str());\r\n\t\t    }\r\n\t\t    else if (line_vec[0] == \"maxInteg_X\") {\r\n\t            maxInteg_Pos(0) = atof(line_vec[2].c_str());\r\n\t\t    }\r\n\t\t    else if (line_vec[0] == \"maxInteg_Y\") {\r\n\t\t\t\tmaxInteg_Pos(1) = atof(line_vec[2].c_str());\r\n\t\t    }\r\n\t\t    else if (line_vec[0] == \"maxInteg_Z\") {\r\n\t\t\t\tmaxInteg_Pos(2) = atof(line_vec[2].c_str());\r\n\t\t    }\r\n\t\t}\r\n\t\tmyfile2.close();\r\n\t\tupdateControlParamPID(PID_pos, KP_Pos, KI_Pos, KD_Pos, maxInteg_Pos);\r\n    }\r\n    else {\r\n\t\tprintf(\"Unable to open file %s \\n\", PosParamPath); \r\n    }\r\n\r\n\tprintf(\"Done updating control parameters\\n\");\r\n}", "meta": {"hexsha": "2cbb4887d997bf66c8e312e8710155c5249c57d4", "size": 7050, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "data/AGNC-Lab_Quad/multithreaded/control/PID_3DOF.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/AGNC-Lab_Quad/multithreaded/control/PID_3DOF.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/AGNC-Lab_Quad/multithreaded/control/PID_3DOF.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": 31.4732142857, "max_line_length": 148, "alphanum_fraction": 0.5561702128, "num_tokens": 2451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.727975460709318, "lm_q2_score": 0.6723316860482763, "lm_q1q2_score": 0.48944096890046646}}
{"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_ABS_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_ABS_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n  @ingroup group-arithmetic\n    Function object implementing abs\n\n    Computes the absolute value of its parameter.\n\n    @par Semantic\n\n    For any value @c x of type @c T,\n\n    @code\n    T r = abs(x);\n    @endcode\n\n    is similar to:\n\n    @code\n    T r = x < T(0) ? -x : x;\n    @endcode\n\n    @par Notes:\n\n    - Be aware that for signed integers the absolute value of @ref Valmin is\n    @ref Valmin (thus negative!). This is a side effect of the 2-complement\n    representation of integers. To avoid this, you may use the\n    saturated_ @ref decorator or convert the input parameter to a larger type\n    before taking the absolute value.\n\n    - abs is a also a standard library function name and there possibly exists\n    a C macro version which may be called instead of the boost simd version.\n    To avoid this you may prefix abs using boost::simd::abs notation.\n\n    @par Decorators\n\n     - std_ @ref decorator for floating entries results in a call to std::abs\n     - saturated_ @ref decorator garanties that saturated_(abs)(x) will never be strictly less than 0.\n       In fact the only change if that for any signed type T saturated_(abs)(Valmin<T>()) will be\n       Valmax<T>()) which is already true for boost::simd::abs with floating types but not for integral\n       signed types.\n\n    @see sqr_abs, sqr\n\n  **/\n  Value abs(Value const& a0);\n} }\n#endif\n\n#include <boost/simd/function/scalar/abs.hpp>\n#include <boost/simd/function/simd/abs.hpp>\n\n#endif\n", "meta": {"hexsha": "bdd8145e10b88c15b603af077f60294d52d9dede", "size": 2011, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/abs.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/abs.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/abs.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": 29.1449275362, "max_line_length": 103, "alphanum_fraction": 0.6330183988, "num_tokens": 454, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059775, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.48944096574423307}}
{"text": "// The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt\n/*\n    This is an example illustrating the use of the Bayesian Network \n    inference utilities found in the dlib C++ library.\n    \n\n    In this example all the nodes in the Bayesian network are\n    boolean variables.  That is, they take on either the value\n    0 or the value 1.\n\n    The network contains 4 nodes and looks as follows:\n\n        B     C\n        \\\\   //\n         \\/ \\/ \n           A\n           ||\n           \\/\n            D\n\n\n    The probabilities of each node are summarized below.  (The probability\n    of each node being 0 is not listed since it is just P(X=0) = 1-p(X=1) ) \n\n        p(B=1) = 0.01\n\n        p(C=1) = 0.001\n\n        p(A=1 | B=0, C=0) = 0.01  \n        p(A=1 | B=0, C=1) = 0.5\n        p(A=1 | B=1, C=0) = 0.9\n        p(A=1 | B=1, C=1) = 0.99 \n\n        p(D=1 | A=0) = 0.2 \n        p(D=1 | A=1) = 0.5\n\n*/\n\n\n#include <dlib/bayes_utils.h>\n#include <dlib/graph_utils.h>\n#include <dlib/graph.h>\n#include <dlib/directed_graph.h>\n#include <iostream>\n\n\nusing namespace dlib;\nusing namespace std;\n\n// ----------------------------------------------------------------------------------------\n\nint main()\n{\n    try\n    {\n        // There are many useful convenience functions in this namespace.  They all\n        // perform simple access or modify operations on the nodes of a bayesian network. \n        // You don't have to use them but they are convenient and they also will check for\n        // various errors in your bayesian network when your application is built with\n        // the DEBUG or ENABLE_ASSERTS preprocessor definitions defined.  So their use\n        // is recommended.  In fact, most of the global functions used in this example \n        // program are from this namespace.\n        using namespace bayes_node_utils;\n\n        // This statement declares a bayesian network called bn.  Note that a bayesian network\n        // in the dlib world is just a directed_graph object that contains a special kind \n        // of node called a bayes_node.\n        directed_graph<bayes_node>::kernel_1a_c bn;\n\n        // Use an enum to make some more readable names for our nodes.\n        enum nodes\n        {\n            A = 0,\n            B = 1,\n            C = 2,\n            D = 3\n        };\n\n        // The next few blocks of code setup our bayesian network.\n\n        // The first thing we do is tell the bn object how many nodes it has\n        // and also add the three edges.  Again, we are using the network\n        // shown in ASCII art at the top of this file.\n        bn.set_number_of_nodes(4);\n        bn.add_edge(A, D);\n        bn.add_edge(B, A);\n        bn.add_edge(C, A);\n\n\n        // Now we inform all the nodes in the network that they are binary\n        // nodes.  That is, they only have two possible values.  \n        set_node_num_values(bn, A, 2);\n        set_node_num_values(bn, B, 2);\n        set_node_num_values(bn, C, 2);\n        set_node_num_values(bn, D, 2);\n\n        assignment parent_state;\n        // Now we will enter all the conditional probability information for each node.\n        // Each node's conditional probability is dependent on the state of its parents.  \n        // To specify this state we need to use the assignment object.  This assignment \n        // object allows us to specify the state of each nodes parents. \n\n\n        // Here we specify that p(B=1) = 0.01\n        // parent_state is empty in this case since B is a root node. \n        set_node_probability(bn, B, 1, parent_state, 0.01);\n        // Here we specify that p(B=0) = 1-0.01\n        set_node_probability(bn, B, 0, parent_state, 1-0.01);\n\n\n        // Here we specify that p(C=1) = 0.001\n        // parent_state is empty in this case since B is a root node. \n        set_node_probability(bn, C, 1, parent_state, 0.001);\n        // Here we specify that p(C=0) = 1-0.001\n        set_node_probability(bn, C, 0, parent_state, 1-0.001);\n\n\n        // This is our first node that has parents. So we set the parent_state\n        // object to reflect that A has both B and C as parents.\n        parent_state.add(B, 1);\n        parent_state.add(C, 1);\n        // Here we specify that p(A=1 | B=1, C=1) = 0.99 \n        set_node_probability(bn, A, 1, parent_state, 0.99);\n        // Here we specify that p(A=0 | B=1, C=1) = 1-0.99 \n        set_node_probability(bn, A, 0, parent_state, 1-0.99);\n\n        // Here we use the [] notation because B and C have already\n        // been added into parent state.  \n        parent_state[B] = 1;\n        parent_state[C] = 0;\n        // Here we specify that p(A=1 | B=1, C=0) = 0.9 \n        set_node_probability(bn, A, 1, parent_state, 0.9);\n        set_node_probability(bn, A, 0, parent_state, 1-0.9);\n\n        parent_state[B] = 0;\n        parent_state[C] = 1;\n        // Here we specify that p(A=1 | B=0, C=1) = 0.5 \n        set_node_probability(bn, A, 1, parent_state, 0.5);\n        set_node_probability(bn, A, 0, parent_state, 1-0.5);\n\n        parent_state[B] = 0;\n        parent_state[C] = 0;\n        // Here we specify that p(A=1 | B=0, C=0) = 0.01 \n        set_node_probability(bn, A, 1, parent_state, 0.01);\n        set_node_probability(bn, A, 0, parent_state, 1-0.01);\n\n\n        // Here we set probabilities for node D.\n        // First we clear out parent state so that it doesn't have any of\n        // the assignments for the B and C nodes used above.\n        parent_state.clear();\n        parent_state.add(A,1);\n        // Here we specify that p(D=1 | A=1) = 0.5 \n        set_node_probability(bn, D, 1, parent_state, 0.5);\n        set_node_probability(bn, D, 0, parent_state, 1-0.5);\n\n        parent_state[A] = 0;\n        // Here we specify that p(D=1 | A=0) = 0.2 \n        set_node_probability(bn, D, 1, parent_state, 0.2);\n        set_node_probability(bn, D, 0, parent_state, 1-0.2);\n\n\n\n        // We have now finished setting up our bayesian network.  So lets compute some \n        // probability values.  The first thing we will do is compute the prior probability\n        // of each node in the network.  To do this we will use the join tree algorithm which\n        // is an algorithm for performing exact inference in a bayesian network.   \n\n        // First we need to create an undirected graph which contains set objects at each node and\n        // edge.  This long declaration does the trick.\n        typedef dlib::set<unsigned long>::compare_1b_c set_type;\n        typedef graph<set_type, set_type>::kernel_1a_c join_tree_type;\n        join_tree_type join_tree;\n\n        // Now we need to populate the join_tree with data from our bayesian network.  The next  \n        // function calls do this.  Explaining exactly what they do is outside the scope of this\n        // example.  Just think of them as filling join_tree with information that is useful \n        // later on for dealing with our bayesian network.  \n        create_moral_graph(bn, join_tree);\n        create_join_tree(join_tree, join_tree);\n\n        // Now that we have a proper join_tree we can use it to obtain a solution to our\n        // bayesian network.  Doing this is as simple as declaring an instance of\n        // the bayesian_network_join_tree object as follows:\n        bayesian_network_join_tree solution(bn, join_tree);\n\n\n        // now print out the probabilities for each node\n        cout << \"Using the join tree algorithm:\\n\";\n        cout << \"p(A=1) = \" << solution.probability(A)(1) << endl;\n        cout << \"p(A=0) = \" << solution.probability(A)(0) << endl;\n        cout << \"p(B=1) = \" << solution.probability(B)(1) << endl;\n        cout << \"p(B=0) = \" << solution.probability(B)(0) << endl;\n        cout << \"p(C=1) = \" << solution.probability(C)(1) << endl;\n        cout << \"p(C=0) = \" << solution.probability(C)(0) << endl;\n        cout << \"p(D=1) = \" << solution.probability(D)(1) << endl;\n        cout << \"p(D=0) = \" << solution.probability(D)(0) << endl;\n        cout << \"\\n\\n\\n\";\n\n\n        // Now to make things more interesting lets say that we have discovered that the C \n        // node really has a value of 1.  That is to say, we now have evidence that \n        // C is 1.  We can represent this in the network using the following two function\n        // calls.\n        set_node_value(bn, C, 1);\n        set_node_as_evidence(bn, C);\n\n        // Now we want to compute the probabilities of all the nodes in the network again\n        // given that we now know that C is 1.  We can do this as follows:\n        bayesian_network_join_tree solution_with_evidence(bn, join_tree);\n\n        // now print out the probabilities for each node\n        cout << \"Using the join tree algorithm:\\n\";\n        cout << \"p(A=1 | C=1) = \" << solution_with_evidence.probability(A)(1) << endl;\n        cout << \"p(A=0 | C=1) = \" << solution_with_evidence.probability(A)(0) << endl;\n        cout << \"p(B=1 | C=1) = \" << solution_with_evidence.probability(B)(1) << endl;\n        cout << \"p(B=0 | C=1) = \" << solution_with_evidence.probability(B)(0) << endl;\n        cout << \"p(C=1 | C=1) = \" << solution_with_evidence.probability(C)(1) << endl;\n        cout << \"p(C=0 | C=1) = \" << solution_with_evidence.probability(C)(0) << endl;\n        cout << \"p(D=1 | C=1) = \" << solution_with_evidence.probability(D)(1) << endl;\n        cout << \"p(D=0 | C=1) = \" << solution_with_evidence.probability(D)(0) << endl;\n        cout << \"\\n\\n\\n\";\n\n        // Note that when we made our solution_with_evidence object we reused our join_tree object.\n        // This saves us the time it takes to calculate the join_tree object from scratch.  But\n        // it is important to note that we can only reuse the join_tree object if we haven't changed\n        // the structure of our bayesian network.  That is, if we have added or removed nodes or \n        // edges from our bayesian network then we must recompute our join_tree.  But in this example\n        // all we did was change the value of a bayes_node object (we made node C be evidence)\n        // so we are ok.\n\n\n\n\n\n        // Next this example will show you how to use the bayesian_network_gibbs_sampler object\n        // to perform approximate inference in a bayesian network.  This is an algorithm \n        // that doesn't give you an exact solution but it may be necessary to use in some \n        // instances.  For example, the join tree algorithm used above, while fast in many\n        // instances, has exponential runtime in some cases.  Moreover, inference in bayesian\n        // networks is NP-Hard for general networks so sometimes the best you can do is\n        // find an approximation.\n        // However, it should be noted that the gibbs sampler does not compute the correct\n        // probabilities if the network contains a deterministic node.  That is, if any\n        // of the conditional probability tables in the bayesian network have a probability\n        // of 1.0 for something the gibbs sampler should not be used.\n\n\n        // This Gibbs sampler algorithm works by randomly sampling possibles values of the\n        // network.  So to use it we should set the network to some initial state.  \n\n        set_node_value(bn, A, 0);\n        set_node_value(bn, B, 0);\n        set_node_value(bn, D, 0);\n\n        // We will leave the C node with a value of 1 and keep it as an evidence node.  \n\n\n        // First create an instance of the gibbs sampler object\n        bayesian_network_gibbs_sampler sampler;\n\n\n        // To use this algorithm all we do is go into a loop for a certain number of times\n        // and each time through we sample the bayesian network.  Then we count how \n        // many times a node has a certain state.  Then the probability of that node\n        // having that state is just its count/total times through the loop. \n\n        // The following code illustrates the general procedure.\n        unsigned long A_count = 0;\n        unsigned long B_count = 0;\n        unsigned long C_count = 0;\n        unsigned long D_count = 0;\n\n        // The more times you let the loop run the more accurate the result will be.  Here we loop\n        // 2000 times.\n        const long rounds = 2000;\n        for (long i = 0; i < rounds; ++i)\n        {\n            sampler.sample_graph(bn);\n\n            if (node_value(bn, A) == 1)\n                ++A_count;\n            if (node_value(bn, B) == 1)\n                ++B_count;\n            if (node_value(bn, C) == 1)\n                ++C_count;\n            if (node_value(bn, D) == 1)\n                ++D_count;\n        }\n\n        cout << \"Using the approximate Gibbs Sampler algorithm:\\n\";\n        cout << \"p(A=1 | C=1) = \" << (double)A_count/(double)rounds << endl;\n        cout << \"p(B=1 | C=1) = \" << (double)B_count/(double)rounds << endl;\n        cout << \"p(C=1 | C=1) = \" << (double)C_count/(double)rounds << endl;\n        cout << \"p(D=1 | C=1) = \" << (double)D_count/(double)rounds << endl;\n    }\n    catch (std::exception& e)\n    {\n        cout << \"exception thrown: \" << endl;\n        cout << e.what() << endl;\n        cout << \"hit enter to terminate\" << endl;\n        cin.get();\n    }\n}\n\n\n\n", "meta": {"hexsha": "54d7d2f52ce515d004ba9e1ac86c2e1bed2f3cee", "size": 13062, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "DynamicGestures/dlib-18.5/examples/bayes_net_ex.cpp", "max_stars_repo_name": "uiuyuty/vsfh", "max_stars_repo_head_hexsha": "49f83a7bf043f7ae872dd759a0d32336d90cf1b4", "max_stars_repo_licenses": ["MIT"], "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": "DynamicGestures/dlib-18.5/examples/bayes_net_ex.cpp", "max_issues_repo_name": "uiuyuty/vsfh", "max_issues_repo_head_hexsha": "49f83a7bf043f7ae872dd759a0d32336d90cf1b4", "max_issues_repo_licenses": ["MIT"], "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": "DynamicGestures/dlib-18.5/examples/bayes_net_ex.cpp", "max_forks_repo_name": "uiuyuty/vsfh", "max_forks_repo_head_hexsha": "49f83a7bf043f7ae872dd759a0d32336d90cf1b4", "max_forks_repo_licenses": ["MIT"], "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": 42.4090909091, "max_line_length": 101, "alphanum_fraction": 0.6041188179, "num_tokens": 3467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754371026367, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.48944095780847297}}
{"text": "//\n// OpenTissue, A toolbox for physical based simulation and animation.\n// Copyright (C) 2007 Department of Computer Science, University of Copenhagen\n//\n#include <OpenTissue/configuration.h>\n\n#include <OpenTissue/core/math/math_basic_types.h>\n#include <OpenTissue/core/containers/mesh/polymesh/polymesh.h>\n#include <OpenTissue/core/containers/mesh/polymesh/util/polymesh_compute_voronoi.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <OpenTissue/utility/utility_push_boost_filter.h>\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n#include <OpenTissue/utility/utility_pop_boost_filter.h>\n\nBOOST_AUTO_TEST_SUITE(opentissue_mesh_polymesh_voronoi);\n\nBOOST_AUTO_TEST_CASE(simple_test)\n{\n  typedef OpenTissue::math::BasicMathTypes<double, size_t> math_types;\n  typedef math_types::vector3_type                         vector3_type;\n  typedef OpenTissue::polymesh::PolyMesh<math_types>       mesh_type;\n\n  mesh_type   mesh;\n\n  std::vector<vector3_type> sites(5);\n\n  sites[0](0) =  1.0; sites[0](1) = -1.0; sites[0](2) =  0.0;\n  sites[1](0) =  1.0; sites[1](1) =  1.0; sites[1](2) =  0.0;\n  sites[2](0) = -1.0; sites[2](1) =  1.0; sites[2](2) =  0.0;\n  sites[3](0) = -1.0; sites[3](1) = -1.0; sites[3](2) =  0.0;\n  sites[4](0) =  0.0; sites[4](1) =  0.0; sites[4](2) =  0.0;\n\n  OpenTissue::polymesh::compute_voronoi(sites,mesh);\n\n  BOOST_CHECK(mesh.size_vertices() == 4 );\n  BOOST_CHECK(mesh.size_faces() == 1 );\n  BOOST_CHECK(mesh.size_edges() == 4 );\n}\n\nBOOST_AUTO_TEST_CASE(simple_test2)\n{\n  typedef OpenTissue::math::BasicMathTypes<double, size_t> math_types;\n  typedef math_types::vector3_type                         vector3_type;\n  typedef OpenTissue::polymesh::PolyMesh<math_types>       mesh_type;\n\n  mesh_type   mesh;\n\n  std::vector<vector3_type> sites(8);\n\n  sites[0](0) =  1.0; sites[0](1) = -1.0; sites[0](2) =  0.0;\n  sites[1](0) =  1.0; sites[1](1) =  1.0; sites[1](2) =  0.0;\n  sites[2](0) = -1.0; sites[2](1) =  1.0; sites[2](2) =  0.0;\n  sites[3](0) = -1.0; sites[3](1) = -1.0; sites[3](2) =  0.0;\n  sites[4](0) =  0.0; sites[4](1) =  0.0; sites[4](2) =  0.0;\n  sites[5](0) =  2.0; sites[5](1) =  0.0; sites[5](2) =  0.0;\n  sites[6](0) =  3.0; sites[6](1) =  1.0; sites[6](2) =  0.0;\n  sites[7](0) =  3.0; sites[7](1) = -1.0; sites[7](2) =  0.0;\n\n  OpenTissue::polymesh::compute_voronoi(sites,mesh);\n\n  BOOST_CHECK(mesh.size_vertices() == 8 );\n  BOOST_CHECK(mesh.size_faces() == 2 );\n  BOOST_CHECK(mesh.size_edges() == 9 );\n}\n\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "eb62976024c1fee10b4f5cd286104b7b71b6d632", "size": 2589, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/core/containers/polymesh_compute_voronoi/src/unit_polymesh_compute_voronoi.cpp", "max_stars_repo_name": "ricortiz/OpenTissue", "max_stars_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 76.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:45:06.000Z", "max_issues_repo_path": "unit_tests/core/containers/polymesh_compute_voronoi/src/unit_polymesh_compute_voronoi.cpp", "max_issues_repo_name": "ricortiz/OpenTissue", "max_issues_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2018-11-20T14:32:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T15:26:45.000Z", "max_forks_repo_path": "unit_tests/core/containers/polymesh_compute_voronoi/src/unit_polymesh_compute_voronoi.cpp", "max_forks_repo_name": "ricortiz/OpenTissue", "max_forks_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2018-02-21T01:45:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T07:06:49.000Z", "avg_line_length": 35.9583333333, "max_line_length": 83, "alphanum_fraction": 0.6562379297, "num_tokens": 955, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754371026368, "lm_q2_score": 0.6723316860482763, "lm_q1q2_score": 0.4894409530289467}}
{"text": "#include <boost/numeric/conversion/cast.hpp>\n#include <boost/test/unit_test.hpp>\n\n#include \"util/coordinate_calculation.hpp\"\n\n#include <osrm/coordinate.hpp>\n\n#include <cmath>\n\nusing namespace osrm;\nusing namespace osrm::util;\n\nBOOST_AUTO_TEST_SUITE(coordinate_calculation_tests)\n\nBOOST_AUTO_TEST_CASE(compute_angle)\n{\n    // Simple cases\n    // North-South straight line\n    Coordinate first(FloatLongitude{1}, FloatLatitude{-1});\n    Coordinate middle(FloatLongitude{1}, FloatLatitude{0});\n    Coordinate end(FloatLongitude{1}, FloatLatitude{1});\n    auto angle = coordinate_calculation::computeAngle(first, middle, end);\n    BOOST_CHECK_EQUAL(angle, 180);\n\n    // North-South-North u-turn\n    first = Coordinate(FloatLongitude{1}, FloatLatitude{0});\n    middle = Coordinate(FloatLongitude{1}, FloatLatitude{1});\n    end = Coordinate(FloatLongitude{1}, FloatLatitude{0});\n    angle = coordinate_calculation::computeAngle(first, middle, end);\n    BOOST_CHECK_EQUAL(angle, 0);\n\n    // East-west straight lines are harder, *simple* coordinates only\n    // work at the equator.  For other locations, we need to follow\n    // a rhumb line.\n    first = Coordinate(FloatLongitude{1}, FloatLatitude{0});\n    middle = Coordinate(FloatLongitude{2}, FloatLatitude{0});\n    end = Coordinate(FloatLongitude{3}, FloatLatitude{0});\n    angle = coordinate_calculation::computeAngle(first, middle, end);\n    BOOST_CHECK_EQUAL(angle, 180);\n\n    // East-West-East u-turn\n    first = Coordinate(FloatLongitude{1}, FloatLatitude{0});\n    middle = Coordinate(FloatLongitude{2}, FloatLatitude{0});\n    end = Coordinate(FloatLongitude{1}, FloatLatitude{0});\n    angle = coordinate_calculation::computeAngle(first, middle, end);\n    BOOST_CHECK_EQUAL(angle, 0);\n\n    // 90 degree left turn\n    first = Coordinate(FloatLongitude{1}, FloatLatitude{1});\n    middle = Coordinate(FloatLongitude{0}, FloatLatitude{1});\n    end = Coordinate(FloatLongitude{0}, FloatLatitude{2});\n    angle = coordinate_calculation::computeAngle(first, middle, end);\n    BOOST_CHECK_EQUAL(angle, 90);\n\n    // 90 degree right turn\n    first = Coordinate(FloatLongitude{1}, FloatLatitude{1});\n    middle = Coordinate(FloatLongitude{0}, FloatLatitude{1});\n    end = Coordinate(FloatLongitude{0}, FloatLatitude{0});\n    angle = coordinate_calculation::computeAngle(first, middle, end);\n    BOOST_CHECK_EQUAL(angle, 270);\n\n    // Weird cases\n    // Crossing both the meridians\n    first = Coordinate(FloatLongitude{-1}, FloatLatitude{-1});\n    middle = Coordinate(FloatLongitude{0}, FloatLatitude{1});\n    end = Coordinate(FloatLongitude{1}, FloatLatitude{-1});\n    angle = coordinate_calculation::computeAngle(first, middle, end);\n    BOOST_CHECK_CLOSE(angle, 53.1, 0.2);\n\n    // All coords in the same spot\n    first = Coordinate(FloatLongitude{-1}, FloatLatitude{-1});\n    middle = Coordinate(FloatLongitude{-1}, FloatLatitude{-1});\n    end = Coordinate(FloatLongitude{-1}, FloatLatitude{-1});\n    angle = coordinate_calculation::computeAngle(first, middle, end);\n    BOOST_CHECK_EQUAL(angle, 180);\n\n    // First two coords in the same spot, then heading north-east\n    first = Coordinate(FloatLongitude{-1}, FloatLatitude{-1});\n    middle = Coordinate(FloatLongitude{-1}, FloatLatitude{-1});\n    end = Coordinate(FloatLongitude{1}, FloatLatitude{1});\n    angle = coordinate_calculation::computeAngle(first, middle, end);\n    BOOST_CHECK_EQUAL(angle, 180);\n\n    // First two coords in the same spot, then heading west\n    first = Coordinate(FloatLongitude{1}, FloatLatitude{1});\n    middle = Coordinate(FloatLongitude{1}, FloatLatitude{1});\n    end = Coordinate(FloatLongitude{2}, FloatLatitude{1});\n    angle = coordinate_calculation::computeAngle(first, middle, end);\n    BOOST_CHECK_EQUAL(angle, 180);\n\n    // First two coords in the same spot then heading north\n    first = Coordinate(FloatLongitude{1}, FloatLatitude{1});\n    middle = Coordinate(FloatLongitude{1}, FloatLatitude{1});\n    end = Coordinate(FloatLongitude{1}, FloatLatitude{2});\n    angle = coordinate_calculation::computeAngle(first, middle, end);\n    BOOST_CHECK_EQUAL(angle, 180);\n\n    // Second two coords in the same spot\n    first = Coordinate(FloatLongitude{1}, FloatLatitude{1});\n    middle = Coordinate(FloatLongitude{-1}, FloatLatitude{-1});\n    end = Coordinate(FloatLongitude{-1}, FloatLatitude{-1});\n    angle = coordinate_calculation::computeAngle(first, middle, end);\n    BOOST_CHECK_EQUAL(angle, 180);\n\n    // First and last coords on the same spot\n    first = Coordinate(FloatLongitude{1}, FloatLatitude{1});\n    middle = Coordinate(FloatLongitude{-1}, FloatLatitude{-1});\n    end = Coordinate(FloatLongitude{1}, FloatLatitude{1});\n    angle = coordinate_calculation::computeAngle(first, middle, end);\n    BOOST_CHECK_EQUAL(angle, 0);\n\n    // Check the antimeridian\n    first = Coordinate(FloatLongitude{180}, FloatLatitude{90});\n    middle = Coordinate(FloatLongitude{180}, FloatLatitude{0});\n    end = Coordinate(FloatLongitude{180}, FloatLatitude{-90});\n    angle = coordinate_calculation::computeAngle(first, middle, end);\n    BOOST_CHECK_EQUAL(angle, 180);\n\n    // Tiny changes below our calculation resolution\n    // This should be equivalent to having two points on the same\n    // spot.\n    first = Coordinate{FloatLongitude{0}, FloatLatitude{0}};\n    middle = Coordinate{FloatLongitude{1}, FloatLatitude{0}};\n    end = Coordinate{FloatLongitude{1 + std::numeric_limits<double>::epsilon()}, FloatLatitude{0}};\n    angle = coordinate_calculation::computeAngle(first, middle, end);\n    BOOST_CHECK_EQUAL(angle, 180);\n\n    // Invalid values\n    /* TODO: Enable this when I figure out how to use BOOST_CHECK_THROW\n     *       and not have the whole test case fail...\n    first = Coordinate(FloatLongitude{0}, FloatLatitude{0});\n    middle = Coordinate(FloatLongitude{1}, FloatLatitude{0});\n    end = Coordinate(FloatLongitude(std::numeric_limits<double>::max()), FloatLatitude{0});\n    BOOST_CHECK_THROW( coordinate_calculation::computeAngle(first,middle,end),\n                       boost::numeric::positive_overflow);\n                       */\n}\n\n// Regression test for bug captured in #1347\nBOOST_AUTO_TEST_CASE(regression_test_1347)\n{\n    Coordinate u(FloatLongitude{-100}, FloatLatitude{10});\n    Coordinate v(FloatLongitude{-100.002}, FloatLatitude{10.001});\n    Coordinate q(FloatLongitude{-100.001}, FloatLatitude{10.002});\n\n    double d1 = coordinate_calculation::perpendicularDistance(u, v, q);\n\n    double ratio;\n    Coordinate nearest_location;\n    double d2 = coordinate_calculation::perpendicularDistance(u, v, q, nearest_location, ratio);\n\n    BOOST_CHECK_LE(std::abs(d1 - d2), 0.01);\n}\n\nBOOST_AUTO_TEST_CASE(regression_point_on_segment)\n{\n    //  ^\n    //  |               t\n    //  |\n    //  |                 i\n    //  |\n    //  |---|---|---|---|---|---|---|--->\n    //  |\n    //  |\n    //  |\n    //  |\n    //  |\n    //  |\n    //  |\n    //  |\n    //  |                           s\n    FloatCoordinate input{FloatLongitude{55.995715}, FloatLatitude{48.332711}};\n    FloatCoordinate start{FloatLongitude{74.140427}, FloatLatitude{-180}};\n    FloatCoordinate target{FloatLongitude{53.041084}, FloatLatitude{77.21011}};\n\n    FloatCoordinate nearest;\n    double ratio;\n    std::tie(ratio, nearest) = coordinate_calculation::projectPointOnSegment(start, target, input);\n\n    FloatCoordinate diff{target.lon - start.lon, target.lat - start.lat};\n\n    BOOST_CHECK_CLOSE(static_cast<double>(start.lon + FloatLongitude{ratio} * diff.lon),\n                      static_cast<double>(nearest.lon),\n                      0.1);\n    BOOST_CHECK_CLOSE(static_cast<double>(start.lat + FloatLatitude{ratio} * diff.lat),\n                      static_cast<double>(nearest.lat),\n                      0.1);\n}\n\nBOOST_AUTO_TEST_CASE(point_on_segment)\n{\n    //  t\n    //  |\n    //  |---- i\n    //  |\n    //  s\n    auto result_1 =\n        coordinate_calculation::projectPointOnSegment({FloatLongitude{0}, FloatLatitude{0}},\n                                                      {FloatLongitude{0}, FloatLatitude{2}},\n                                                      {FloatLongitude{2}, FloatLatitude{1}});\n    auto reference_ratio_1 = 0.5;\n    auto reference_point_1 = FloatCoordinate{FloatLongitude{0}, FloatLatitude{1}};\n    BOOST_CHECK_EQUAL(result_1.first, reference_ratio_1);\n    BOOST_CHECK_EQUAL(result_1.second.lon, reference_point_1.lon);\n    BOOST_CHECK_EQUAL(result_1.second.lat, reference_point_1.lat);\n\n    //  i\n    //  :\n    //  t\n    //  |\n    //  |\n    //  |\n    //  s\n    auto result_2 =\n        coordinate_calculation::projectPointOnSegment({FloatLongitude{0.}, FloatLatitude{0.}},\n                                                      {FloatLongitude{0}, FloatLatitude{2}},\n                                                      {FloatLongitude{0}, FloatLatitude{3}});\n    auto reference_ratio_2 = 1.;\n    auto reference_point_2 = FloatCoordinate{FloatLongitude{0}, FloatLatitude{2}};\n    BOOST_CHECK_EQUAL(result_2.first, reference_ratio_2);\n    BOOST_CHECK_EQUAL(result_2.second.lon, reference_point_2.lon);\n    BOOST_CHECK_EQUAL(result_2.second.lat, reference_point_2.lat);\n\n    //  t\n    //  |\n    //  |\n    //  |\n    //  s\n    //  :\n    //  i\n    auto result_3 =\n        coordinate_calculation::projectPointOnSegment({FloatLongitude{0.}, FloatLatitude{0.}},\n                                                      {FloatLongitude{0}, FloatLatitude{2}},\n                                                      {FloatLongitude{0}, FloatLatitude{-1}});\n    auto reference_ratio_3 = 0.;\n    auto reference_point_3 = FloatCoordinate{FloatLongitude{0}, FloatLatitude{0}};\n    BOOST_CHECK_EQUAL(result_3.first, reference_ratio_3);\n    BOOST_CHECK_EQUAL(result_3.second.lon, reference_point_3.lon);\n    BOOST_CHECK_EQUAL(result_3.second.lat, reference_point_3.lat);\n\n    //     t\n    //    /\n    //   /.\n    //  /  i\n    // s\n    //\n    auto result_4 = coordinate_calculation::projectPointOnSegment(\n        {FloatLongitude{0}, FloatLatitude{0}},\n        {FloatLongitude{1}, FloatLatitude{1}},\n        {FloatLongitude{0.5 + 0.1}, FloatLatitude{0.5 - 0.1}});\n    auto reference_ratio_4 = 0.5;\n    auto reference_point_4 = FloatCoordinate{FloatLongitude{0.5}, FloatLatitude{0.5}};\n    BOOST_CHECK_EQUAL(result_4.first, reference_ratio_4);\n    BOOST_CHECK_EQUAL(result_4.second.lon, reference_point_4.lon);\n    BOOST_CHECK_EQUAL(result_4.second.lat, reference_point_4.lat);\n}\n\nBOOST_AUTO_TEST_CASE(circleCenter)\n{\n    Coordinate a(FloatLongitude{-100.}, FloatLatitude{10.});\n    Coordinate b(FloatLongitude{-100.002}, FloatLatitude{10.001});\n    Coordinate c(FloatLongitude{-100.001}, FloatLatitude{10.002});\n\n    auto result = coordinate_calculation::circleCenter(a, b, c);\n    BOOST_CHECK(result);\n    BOOST_CHECK_EQUAL(*result, Coordinate(FloatLongitude{-100.000833}, FloatLatitude{10.000833}));\n\n    // Co-linear longitude\n    a = Coordinate(FloatLongitude{-100.}, FloatLatitude{10.});\n    b = Coordinate(FloatLongitude{-100.001}, FloatLatitude{10.001});\n    c = Coordinate(FloatLongitude{-100.001}, FloatLatitude{10.002});\n    result = coordinate_calculation::circleCenter(a, b, c);\n    BOOST_CHECK(result);\n    BOOST_CHECK_EQUAL(*result, Coordinate(FloatLongitude{-99.9995}, FloatLatitude{10.0015}));\n\n    // Co-linear longitude, impossible to calculate\n    a = Coordinate(FloatLongitude{-100.001}, FloatLatitude{10.});\n    b = Coordinate(FloatLongitude{-100.001}, FloatLatitude{10.001});\n    c = Coordinate(FloatLongitude{-100.001}, FloatLatitude{10.002});\n    result = coordinate_calculation::circleCenter(a, b, c);\n    BOOST_CHECK(!result);\n\n    // Co-linear latitude, this is a real case that failed\n    a = Coordinate(FloatLongitude{-112.096234}, FloatLatitude{41.147101});\n    b = Coordinate(FloatLongitude{-112.096606}, FloatLatitude{41.147101});\n    c = Coordinate(FloatLongitude{-112.096419}, FloatLatitude{41.147259});\n    result = coordinate_calculation::circleCenter(a, b, c);\n    BOOST_CHECK(result);\n    BOOST_CHECK_EQUAL(*result, Coordinate(FloatLongitude{-112.09642}, FloatLatitude{41.14707}));\n\n    // Co-linear latitude, variation\n    a = Coordinate(FloatLongitude{-112.096234}, FloatLatitude{41.147101});\n    b = Coordinate(FloatLongitude{-112.096606}, FloatLatitude{41.147259});\n    c = Coordinate(FloatLongitude{-112.096419}, FloatLatitude{41.147259});\n    result = coordinate_calculation::circleCenter(a, b, c);\n    BOOST_CHECK(result);\n    BOOST_CHECK_EQUAL(*result, Coordinate(FloatLongitude{-112.096512}, FloatLatitude{41.146962}));\n\n    // Co-linear latitude, impossible to calculate\n    a = Coordinate(FloatLongitude{-112.096234}, FloatLatitude{41.147259});\n    b = Coordinate(FloatLongitude{-112.096606}, FloatLatitude{41.147259});\n    c = Coordinate(FloatLongitude{-112.096419}, FloatLatitude{41.147259});\n    result = coordinate_calculation::circleCenter(a, b, c);\n    BOOST_CHECK(!result);\n\n    // Out of bounds\n    a = Coordinate(FloatLongitude{-112.096234}, FloatLatitude{41.147258});\n    b = Coordinate(FloatLongitude{-112.106606}, FloatLatitude{41.147259});\n    c = Coordinate(FloatLongitude{-113.096419}, FloatLatitude{41.147258});\n    result = coordinate_calculation::circleCenter(a, b, c);\n    BOOST_CHECK(!result);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "3bea3eb8696a99312becd6e46a58f9f2ad52a232", "size": 13237, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/util/coordinate_calculation.cpp", "max_stars_repo_name": "peterkist-tinker/osrm-backend-appveyor-test", "max_stars_repo_head_hexsha": "1891d7379c1d524ea6dc5a8d95e93f4023481a07", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-04-15T22:58:23.000Z", "max_stars_repo_stars_event_max_datetime": "2017-04-15T22:58:23.000Z", "max_issues_repo_path": "unit_tests/util/coordinate_calculation.cpp", "max_issues_repo_name": "peterkist-tinker/osrm-backend-appveyor-test", "max_issues_repo_head_hexsha": "1891d7379c1d524ea6dc5a8d95e93f4023481a07", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-11-21T09:59:27.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-21T09:59:27.000Z", "max_forks_repo_path": "osrm-ch/unit_tests/util/coordinate_calculation.cpp", "max_forks_repo_name": "dingchunda/osrm-backend", "max_forks_repo_head_hexsha": "8750749b83bd9193ca3481c630eefda689ecb73c", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-19T08:51:11.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-19T08:51:11.000Z", "avg_line_length": 42.0222222222, "max_line_length": 99, "alphanum_fraction": 0.6780237214, "num_tokens": 3166, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4894293260345463}}
{"text": "#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <stdexcept>\n#include <string>\n#include <vector>\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/linestring.hpp>\n#include <boost/geometry/geometries/adapted/boost_array.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/vector.hpp>\nBOOST_GEOMETRY_REGISTER_BOOST_ARRAY_CS(cs::cartesian)\n\n#include <enne-stage/constants.hpp>\n\n#include\"/usr/local/pykep/src/lambert_problem.cpp\"\n\n\nint main()\n{\ndouble MU_EARTH = enne_stage::ASTRO_ENNE_GM_EARTH;// m^3/s^2\n\n// 200 km, 30deg, quarter orbit\nboost::array< double, 3> r1 = {6778136,0,0};\t\nboost::array< double, 3> r2 = {0,6043243.047,3489068};\nboost::array< double, 3> v0 = {0,7668.558733,0};\nboost::array< double, 3> v3 = {-7557.86574,0,0};\n\n// // Hohmann transfer initial conditions.\n// boost::array< double, 3> r1 = {6778136,0,0};\t\n// boost::array< double, 3> r2 = {-6978136,0.00007,0};\n// boost::array< double, 3> v0 = {0,7668.558733,0};\n// boost::array< double, 3> v3 = {0.000000008,-7557.86574,0};\n\ndouble r1a = std::sqrt(std::pow(r1[0],2.0)+std::pow(r1[1],2.0)+std::pow(r1[2],2.0));\ndouble dt_orbit =  2*enne_stage::kPI * std::sqrt(std::pow((r1a),3.0)/MU_EARTH);\n\ndouble start = 500;\nconst int amount = 100000;\n\nboost::array< double, amount> toff;\n\nstd::ofstream myfile;\nmyfile.open (\"../data/i.txt\");\nfor (int i=start; i<start+amount; i++) myfile << i / 10000.0 << std::endl;\nmyfile.close();\n\nfor (int j = 0; j < 5; ++j)\n{\n\tboost::array< double, amount> dvtotarray;\n\tboost::array< double, amount> toff;\n\n\tfor (int i = start; i < start + amount; ++i)\n\t{\n\t\tconst double a = i / 10000.0;\n\t\tdouble dt = dt_orbit * a;\n\t\tkep_toolbox::lambert_problem test( r1,r2, dt, MU_EARTH,0,j);\n\t\tint\tnmax = test.lambert_problem::get_Nmax();\n\n\t\tif (nmax > 0 && j>0)\n\t\t{\n\t\tstd::vector<boost::array< double, 3> > v1;\n\t\tv1 = test.lambert_problem::get_v1();\n\t    double dv1 = boost::geometry::distance(v1[nmax*2-1], v0);\n\n\t\tstd::vector<boost::array< double, 3> > v2;\n\t\tv2 = test.lambert_problem::get_v2();\n\t    double dv2 = boost::geometry::distance(v3, v2[nmax*2-1]);\n\n\t    double dvtot = dv1+dv2;\n\n\t\ttoff[i-start] = a;\n\t\tdvtotarray[i-start] = dvtot;\n\t\t}\n\n\t\tif (nmax == 0 && j==0)\n\t\t{\n\t\tstd::vector<boost::array< double, 3> > v1;\n\t\tv1 = test.lambert_problem::get_v1();\n\t    double dv1 = boost::geometry::distance(v1[0], v0);\n\n\t\tstd::vector<boost::array< double, 3> > v2;\n\t\tv2 = test.lambert_problem::get_v2();\n\t    double dv2 = boost::geometry::distance(v3, v2[0]);\n\n\t    double dvtot = dv1+dv2;\n\n\t\ttoff[i-start] = a;\n\t\tdvtotarray[i-start] = dvtot;\n\t\t}\n\n\t\tif (nmax == 0 && j>0)\n\t\t{\n\t\ttoff[i-start] = a;\n\t\tdvtotarray[i-start] = 100000;\n\t\t}\n\t\tif (nmax == 1 && j>1)\n\t\t{\n\t\ttoff[i-start] = a;\n\t\tdvtotarray[i-start] = 100000;\n\t\t}\n\t\tif (nmax == 2 && j>2)\n\t\t{\n\t\ttoff[i-start] = a;\n\t\tdvtotarray[i-start] = 100000;\n\t\t}\n\t\tif (nmax == 3 && j>3)\n\t\t{\n\t\ttoff[i-start] = a;\n\t\tdvtotarray[i-start] = 100000;\n\t\t}\n\t}\n\tstd::string filename;\n\tstd::ostringstream convert;\n\tconvert << j;\n\tfilename = \"../data/dv_\" + convert.str();\n\tfilename += \".txt\";\n  \tstd::ofstream myfile1;\n    myfile1.open (filename);\n\tfor (int i=0; i<amount; i++) myfile1 << dvtotarray[i] << std::endl;\n  \tmyfile1.close();\n\n}\n  \n  return 0;\n}", "meta": {"hexsha": "52a71cbf8aa055fd1735f6b8c45e21a1b8aad259", "size": 3224, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/lambertHohmannFreeTOF.cpp", "max_stars_repo_name": "ennehekma/enne-stage", "max_stars_repo_head_hexsha": "fa0d10af7cafa423e1c30ef284d5ead68d78b6aa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/lambertHohmannFreeTOF.cpp", "max_issues_repo_name": "ennehekma/enne-stage", "max_issues_repo_head_hexsha": "fa0d10af7cafa423e1c30ef284d5ead68d78b6aa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lambertHohmannFreeTOF.cpp", "max_forks_repo_name": "ennehekma/enne-stage", "max_forks_repo_head_hexsha": "fa0d10af7cafa423e1c30ef284d5ead68d78b6aa", "max_forks_repo_licenses": ["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.5873015873, "max_line_length": 84, "alphanum_fraction": 0.6346153846, "num_tokens": 1192, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934406, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4894293222595759}}
{"text": "#include <hpp/fcl/math/sampling.h>\n#include <boost/random/lagged_fibonacci.hpp>\n#include <boost/random/uniform_int.hpp>\n#include <boost/thread/mutex.hpp>\n#include <boost/date_time/posix_time/posix_time.hpp>\n#include <boost/math/constants/constants.hpp>\n\nnamespace fcl\n{\n\n/// The seed the user asked for (cannot be 0)\nstatic boost::uint32_t userSetSeed = 0;\n\t\n/// Flag indicating whether the first seed has already been generated or not\nstatic bool firstSeedGenerated = false;\n\t\n/// The value of the first seed\nstatic boost::uint32_t firstSeedValue = 0;\n\t\n/// Compute the first seed to be used; this function should be called only once\nstatic boost::uint32_t firstSeed()\n{\n  static boost::mutex fsLock;\n  boost::mutex::scoped_lock slock(fsLock);\n\t\t\n  if(firstSeedGenerated)\n    return firstSeedValue;\n\t\t\t\n  if(userSetSeed != 0)\n    firstSeedValue = userSetSeed;\n  else firstSeedValue = (boost::uint32_t)(boost::posix_time::microsec_clock::universal_time() - boost::posix_time::ptime(boost::date_time::min_date_time)).total_microseconds();\n  firstSeedGenerated = true;\n\t\t\n  return firstSeedValue;\n}\n\t\n/// We use a different random number generator for the seeds of the\n/// Other random generators. The root seed is from the number of\n/// nano-seconds in the current time.\nstatic boost::uint32_t nextSeed()\n{\n  static boost::mutex rngMutex;\n  boost::mutex::scoped_lock slock(rngMutex);\n  static boost::lagged_fibonacci607 sGen(firstSeed());\n  static boost::uniform_int<> sDist(1, 1000000000);\n  static boost::variate_generator<boost::lagged_fibonacci607&, boost::uniform_int<> > s(sGen, sDist);\n  return s();\n}\n\t\nboost::uint32_t RNG::getSeed()\n{\n  return firstSeed();\n}\n\t\nvoid RNG::setSeed(boost::uint32_t seed)\n{\n  if(firstSeedGenerated)\n  {\n    std::cerr << \"Random number generation already started. Changing seed now will not lead to deterministic sampling.\" << std::endl;\n  }\n  if(seed == 0)\n  {\n    std::cerr << \"Random generator seed cannot be 0. Using 1 instead.\" << std::endl;\n    userSetSeed = 1;\n  }\n  else\n    userSetSeed = seed;\n}\n\t\nRNG::RNG() : generator_(nextSeed()),\n                 uniDist_(0, 1),\n                 normalDist_(0, 1),\n                 uni_(generator_, uniDist_),\n                 normal_(generator_, normalDist_)\n{\n}\n\t\ndouble RNG::halfNormalReal(double r_min, double r_max, double focus)\n{\n  assert(r_min <= r_max);\n\t\t\n  const double mean = r_max - r_min;\n  double v = gaussian(mean, mean / focus);\n\t\t\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\t\nint RNG::halfNormalInt(int r_min, int r_max, double focus)\n{\n  int r = (int)floor(halfNormalReal((double)r_min, (double)(r_max) + 1.0, focus));\n  return (r > r_max) ? r_max : r;\n}\n\t\n// From: \"Uniform Random Rotations\", Ken Shoemake, Graphics Gems III,\n//       pg. 124-132\nvoid RNG::quaternion(double value[4])\n{\n  double x0 = uni_();\n  double r1 = sqrt(1.0 - x0), r2 = sqrt(x0);\n  double t1 = 2.0 * boost::math::constants::pi<double>() * uni_(), 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\t\n// From Effective Sampling and Distance Metrics for 3D Rigid Body Path Planning, by James Kuffner, ICRA 2004\nvoid RNG::eulerRPY(double value[3])\n{\n  value[0] = boost::math::constants::pi<double>() * (2.0 * uni_() - 1.0);\n  value[1] = acos(1.0 - 2.0 * uni_()) - boost::math::constants::pi<double>() / 2.0;\n  value[2] = boost::math::constants::pi<double>() * (2.0 * uni_() - 1.0);\n}\n\t\nvoid RNG::disk(double r_min, double r_max, double& x, double& y)\n{\n  double a = uniform01();\n  double b = uniform01();\n  double r = std::sqrt(a * r_max * r_max + (1 - a) * r_min * r_min);\n  double theta = 2 * boost::math::constants::pi<double>() * b;\n  x = r * std::cos(theta);\n  y = r * std::sin(theta);\n}\n\t\nvoid RNG::ball(double r_min, double r_max, double& x, double& y, double& z)\n{\n  double a = uniform01();\n  double b = uniform01();\n  double c = uniform01();\n  double r = std::pow(a * r_max * r_max * r_max + (1 - a) * r_min * r_min * r_min, 1 / 3.0);\n  double theta = std::acos(1 - 2 * b);\n  double phi = 2 * boost::math::constants::pi<double>() * c;\n\t\t\n  double costheta = std::cos(theta);\n  double sintheta = std::sin(theta);\n  double cosphi = std::cos(phi);\n  double sinphi = std::sin(phi);\n  x = r * costheta;\n  y = r * sintheta * cosphi;\n  z = r * sintheta * sinphi;\n}\n\n}\n", "meta": {"hexsha": "f8498b59bb4a708a7e331782f464749b8457b355", "size": 4485, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/math/sampling.cpp", "max_stars_repo_name": "nassimeblinlaas/hpp-fcl-nouveau", "max_stars_repo_head_hexsha": "0a52cde1b64b1e9f25cf38bb60a80b06f98ec37a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/math/sampling.cpp", "max_issues_repo_name": "nassimeblinlaas/hpp-fcl-nouveau", "max_issues_repo_head_hexsha": "0a52cde1b64b1e9f25cf38bb60a80b06f98ec37a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/math/sampling.cpp", "max_forks_repo_name": "nassimeblinlaas/hpp-fcl-nouveau", "max_forks_repo_head_hexsha": "0a52cde1b64b1e9f25cf38bb60a80b06f98ec37a", "max_forks_repo_licenses": ["BSD-3-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.3040540541, "max_line_length": 176, "alphanum_fraction": 0.6526198439, "num_tokens": 1379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4893996344918333}}
{"text": "#include <Eigen/Core>\n\nUSING_PART_OF_NAMESPACE_EIGEN\n\nnamespace Eigen {\n\n/* Echelon a matrix in-place:\n *\n * Meta-Unrolled version, for small fixed-size matrices\n */\ntemplate<typename Derived, int Step>\nstruct unroll_echelon\n{\n  enum { k = Step - 1,\n         Rows = Derived::RowsAtCompileTime,\n         Cols = Derived::ColsAtCompileTime,\n         CornerRows = Rows - k,\n         CornerCols = Cols - k\n  };\n  static void run(MatrixBase<Derived>& m)\n  {\n    unroll_echelon<Derived, Step-1>::run(m);\n    int rowOfBiggest, colOfBiggest;\n    m.template corner<CornerRows, CornerCols>(BottomRight)\n     .cwise().abs()\n     .maxCoeff(&rowOfBiggest, &colOfBiggest);\n    m.row(k).swap(m.row(k+rowOfBiggest));\n    m.col(k).swap(m.col(k+colOfBiggest));\n    m.template corner<CornerRows-1, CornerCols>(BottomRight)\n      -= m.col(k).template end<CornerRows-1>()\n       * (m.row(k).template end<CornerCols>() / m(k,k));\n  }\n};\n\ntemplate<typename Derived>\nstruct unroll_echelon<Derived, 0>\n{\n  static void run(MatrixBase<Derived>& m) {}\n};\n\n/* Echelon a matrix in-place:\n *\n * Non-unrolled version, for dynamic-size matrices.\n * (this version works for all matrices, but in the fixed-size case the other\n * version is faster).\n */\ntemplate<typename Derived>\nstruct unroll_echelon<Derived, Dynamic>\n{\n  static void run(MatrixBase<Derived>& m)\n  {\n    for(int k = 0; k < m.diagonal().size() - 1; k++)\n    {\n      int rowOfBiggest, colOfBiggest;\n      int cornerRows = m.rows()-k, cornerCols = m.cols()-k;\n      m.corner(BottomRight, cornerRows, cornerCols)\n      .cwise().abs()\n      .maxCoeff(&rowOfBiggest, &colOfBiggest);\n      m.row(k).swap(m.row(k+rowOfBiggest));\n      m.col(k).swap(m.col(k+colOfBiggest));\n      m.corner(BottomRight, cornerRows-1, cornerCols)\n        -= m.col(k).end(cornerRows-1) * (m.row(k).end(cornerCols) / m(k,k));\n    }\n  }\n};\n\nusing namespace std;\ntemplate<typename Derived>\nvoid echelon(MatrixBase<Derived>& m)\n{\n  const int size = DiagonalCoeffs<Derived>::SizeAtCompileTime;\n  const bool unroll = size <= 4;\n  unroll_echelon<Derived, unroll ? size-1 : Dynamic>::run(m);\n}\n\ntemplate<typename Derived>\nvoid doSomeRankPreservingOperations(MatrixBase<Derived>& m)\n{\n  for(int a = 0; a < 3*(m.rows()+m.cols()); a++)\n  {\n    double d = ei_random<double>(-1,1);\n    int i = ei_random<int>(0,m.rows()-1); // i is a random row number\n    int j;\n    do {\n      j = ei_random<int>(0,m.rows()-1);\n    } while (i==j); // j is another one (must be different)\n    m.row(i) += d * m.row(j);\n\n    i = ei_random<int>(0,m.cols()-1); // i is a random column number\n    do {\n      j = ei_random<int>(0,m.cols()-1);\n    } while (i==j); // j is another one (must be different)\n    m.col(i) += d * m.col(j);\n  }\n}\n\n} // namespace Eigen\n\nusing namespace std;\n\nint main(int, char **)\n{\n  srand((unsigned int)time(0));\n  const int Rows = 6, Cols = 4;\n  typedef Matrix<double, Rows, Cols> Mat;\n  const int N = Rows < Cols ? Rows : Cols;\n\n  // start with a matrix m that's obviously of rank N-1\n  Mat m = Mat::identity(Rows, Cols); // args just in case of dyn. size\n  m.row(0) = m.row(1) = m.row(0) + m.row(1);\n\n  doSomeRankPreservingOperations(m);\n\n  // now m is still a matrix of rank N-1\n  cout << \"Here's the matrix m:\" << endl << m << endl;\n\n  cout << \"Now let's echelon m (repeating many times for benchmarking purposes):\" << endl;\n  for(int i = 0; i < 1000000; i++) echelon(m);\n\n  cout << \"Now m is:\" << endl << m << endl;\n}\n", "meta": {"hexsha": "49b719ff28ea1b9e5518b5e97f611cc0558ea328", "size": 3420, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "volna_init/external/eigen2/doc/echelon.cpp", "max_stars_repo_name": "Devaraj-G/volna", "max_stars_repo_head_hexsha": "f4a25c19ae041c81442fc0461ea3ff2d7d8f95ba", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-07-08T23:53:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T11:55:28.000Z", "max_issues_repo_path": "volna_init/external/eigen2/doc/echelon.cpp", "max_issues_repo_name": "Devaraj-G/volna", "max_issues_repo_head_hexsha": "f4a25c19ae041c81442fc0461ea3ff2d7d8f95ba", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-12-02T17:31:28.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-02T17:31:28.000Z", "max_forks_repo_path": "volna_init/external/eigen2/doc/echelon.cpp", "max_forks_repo_name": "Devaraj-G/volna", "max_forks_repo_head_hexsha": "f4a25c19ae041c81442fc0461ea3ff2d7d8f95ba", "max_forks_repo_licenses": ["BSD-2-Clause"], "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": 28.0327868852, "max_line_length": 90, "alphanum_fraction": 0.6321637427, "num_tokens": 1037, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4893996344918333}}
{"text": "// Copyright (c) 2018-2019, The Arqma Network\n// Copyright (c) 2017-2018, The Monero Project\n//\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without modification, are\n// permitted provided that the following conditions are met:\n//\n// 1. Redistributions of source code must retain the above copyright notice, this list of\n//    conditions and the following disclaimer.\n//\n// 2. Redistributions in binary form must reproduce the above copyright notice, this list\n//    of conditions and the following disclaimer in the documentation and/or other\n//    materials provided with the distribution.\n//\n// 3. Neither the name of the copyright holder nor the names of its contributors may be\n//    used to endorse or promote products derived from this software without specific\n//    prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY\n// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL\n// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF\n// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// Adapted from Java code by Sarang Noether\n\n#include <stdlib.h>\n#include <openssl/ssl.h>\n#include <boost/thread/mutex.hpp>\n#include <boost/thread/lock_guard.hpp>\n#include \"misc_log_ex.h\"\n#include \"common/perf_timer.h\"\nextern \"C\"\n{\n#include \"crypto/crypto-ops.h\"\n}\n#include \"rctOps.h\"\n#include \"bulletproofs.h\"\n\n#undef ARQMA_DEFAULT_LOG_CATEGORY\n#define ARQMA_DEFAULT_LOG_CATEGORY \"bulletproofs\"\n\n//#define DEBUG_BP\n\n#define PERF_TIMER_START_BP(x) PERF_TIMER_START_UNIT(x, 1000000)\n\nnamespace rct\n{\n\nstatic rct::key vector_exponent(const rct::keyV &a, const rct::keyV &b);\nstatic rct::keyV vector_powers(rct::key x, size_t n);\nstatic rct::key inner_product(const rct::keyV &a, const rct::keyV &b);\n\nstatic constexpr size_t maxN = 64;\nstatic rct::key Hi[maxN], Gi[maxN];\nstatic ge_dsmp Gprecomp[64], Hprecomp[64];\nstatic const rct::key TWO = { {0x02, 0x00, 0x00,0x00 , 0x00, 0x00, 0x00,0x00 , 0x00, 0x00, 0x00,0x00 , 0x00, 0x00, 0x00,0x00 , 0x00, 0x00, 0x00,0x00 , 0x00, 0x00, 0x00,0x00 , 0x00, 0x00, 0x00,0x00 , 0x00, 0x00, 0x00,0x00  } };\nstatic const rct::keyV oneN = vector_powers(rct::identity(), maxN);\nstatic const rct::keyV twoN = vector_powers(TWO, maxN);\nstatic const rct::key ip12 = inner_product(oneN, twoN);\nstatic boost::mutex init_mutex;\n\nstatic rct::key get_exponent(const rct::key &base, size_t idx)\n{\n  static const std::string salt(\"bulletproof\");\n  std::string hashed = std::string((const char*)base.bytes, sizeof(base)) + salt + tools::get_varint_data(idx);\n  return rct::hashToPoint(rct::hash2rct(crypto::cn_fast_hash(hashed.data(), hashed.size())));\n}\n\nstatic void init_exponents()\n{\n  boost::lock_guard<boost::mutex> lock(init_mutex);\n\n  static bool init_done = false;\n  if (init_done)\n    return;\n  for (size_t i = 0; i < maxN; ++i)\n  {\n    Hi[i] = get_exponent(rct::H, i * 2);\n    rct::precomp(Hprecomp[i], Hi[i]);\n    Gi[i] = get_exponent(rct::H, i * 2 + 1);\n    rct::precomp(Gprecomp[i], Gi[i]);\n  }\n  init_done = true;\n}\n\nstatic bool is_reduced(const rct::key &scalar)\n{\n  rct::key reduced = scalar;\n  sc_reduce32(reduced.bytes);\n  return scalar == reduced;\n}\n\n/* Given two scalar arrays, construct a vector commitment */\nstatic rct::key vector_exponent(const rct::keyV &a, const rct::keyV &b)\n{\n  CHECK_AND_ASSERT_THROW_MES(a.size() == b.size(), \"Incompatible sizes of a and b\");\n  CHECK_AND_ASSERT_THROW_MES(a.size() <= maxN, \"Incompatible sizes of a and maxN\");\n  rct::key res = rct::identity();\n  for (size_t i = 0; i < a.size(); ++i)\n  {\n    rct::key term;\n    rct::addKeys3(term, a[i], Gprecomp[i], b[i], Hprecomp[i]);\n    rct::addKeys(res, res, term);\n  }\n  return res;\n}\n\n/* Compute a custom vector-scalar commitment */\nstatic rct::key vector_exponent_custom(const rct::keyV &A, const rct::keyV &B, const rct::keyV &a, const rct::keyV &b)\n{\n  CHECK_AND_ASSERT_THROW_MES(A.size() == B.size(), \"Incompatible sizes of A and B\");\n  CHECK_AND_ASSERT_THROW_MES(a.size() == b.size(), \"Incompatible sizes of a and b\");\n  CHECK_AND_ASSERT_THROW_MES(a.size() == A.size(), \"Incompatible sizes of a and A\");\n  CHECK_AND_ASSERT_THROW_MES(a.size() <= maxN, \"Incompatible sizes of a and maxN\");\n  rct::key res = rct::identity();\n  for (size_t i = 0; i < a.size(); ++i)\n  {\n    rct::key term;\n#if 0\n    // we happen to know where A and B might fall, so don't bother checking the rest\n    ge_dsmp *Acache = NULL, *Bcache = NULL;\n    ge_dsmp Acache_custom[1], Bcache_custom[1];\n    if (Gi[i] == A[i])\n      Acache = Gprecomp + i;\n    else if (i<32 && Gi[i+32] == A[i])\n      Acache = Gprecomp + i + 32;\n    else\n    {\n      rct::precomp(Acache_custom[0], A[i]);\n      Acache = Acache_custom;\n    }\n    if (i == 0 && B[i] == Hi[0])\n      Bcache = Hprecomp;\n    else\n    {\n      rct::precomp(Bcache_custom[0], B[i]);\n      Bcache = Bcache_custom;\n    }\n    rct::addKeys3(term, a[i], *Acache, b[i], *Bcache);\n#else\n    ge_dsmp Acache, Bcache;\n    rct::precomp(Bcache, B[i]);\n    rct::addKeys3(term, a[i], A[i], b[i], Bcache);\n#endif\n    rct::addKeys(res, res, term);\n  }\n  return res;\n}\n\n/* Given a scalar, construct a vector of powers */\nstatic rct::keyV vector_powers(rct::key x, size_t n)\n{\n  rct::keyV res(n);\n  if (n == 0)\n    return res;\n  res[0] = rct::identity();\n  if (n == 1)\n    return res;\n  res[1] = x;\n  for (size_t i = 2; i < n; ++i)\n  {\n    sc_mul(res[i].bytes, res[i-1].bytes, x.bytes);\n  }\n  return res;\n}\n\n/* Given two scalar arrays, construct the inner product */\nstatic rct::key inner_product(const rct::keyV &a, const rct::keyV &b)\n{\n  CHECK_AND_ASSERT_THROW_MES(a.size() == b.size(), \"Incompatible sizes of a and b\");\n  rct::key res = rct::zero();\n  for (size_t i = 0; i < a.size(); ++i)\n  {\n    sc_muladd(res.bytes, a[i].bytes, b[i].bytes, res.bytes);\n  }\n  return res;\n}\n\n/* Given two scalar arrays, construct the Hadamard product */\nstatic rct::keyV hadamard(const rct::keyV &a, const rct::keyV &b)\n{\n  CHECK_AND_ASSERT_THROW_MES(a.size() == b.size(), \"Incompatible sizes of a and b\");\n  rct::keyV res(a.size());\n  for (size_t i = 0; i < a.size(); ++i)\n  {\n    sc_mul(res[i].bytes, a[i].bytes, b[i].bytes);\n  }\n  return res;\n}\n\n/* Given two curvepoint arrays, construct the Hadamard product */\nstatic rct::keyV hadamard2(const rct::keyV &a, const rct::keyV &b)\n{\n  CHECK_AND_ASSERT_THROW_MES(a.size() == b.size(), \"Incompatible sizes of a and b\");\n  rct::keyV res(a.size());\n  for (size_t i = 0; i < a.size(); ++i)\n  {\n    rct::addKeys(res[i], a[i], b[i]);\n  }\n  return res;\n}\n\n/* Add two vectors */\nstatic rct::keyV vector_add(const rct::keyV &a, const rct::keyV &b)\n{\n  CHECK_AND_ASSERT_THROW_MES(a.size() == b.size(), \"Incompatible sizes of a and b\");\n  rct::keyV res(a.size());\n  for (size_t i = 0; i < a.size(); ++i)\n  {\n    sc_add(res[i].bytes, a[i].bytes, b[i].bytes);\n  }\n  return res;\n}\n\n/* Subtract two vectors */\nstatic rct::keyV vector_subtract(const rct::keyV &a, const rct::keyV &b)\n{\n  CHECK_AND_ASSERT_THROW_MES(a.size() == b.size(), \"Incompatible sizes of a and b\");\n  rct::keyV res(a.size());\n  for (size_t i = 0; i < a.size(); ++i)\n  {\n    sc_sub(res[i].bytes, a[i].bytes, b[i].bytes);\n  }\n  return res;\n}\n\n/* Multiply a scalar and a vector */\nstatic rct::keyV vector_scalar(const rct::keyV &a, const rct::key &x)\n{\n  rct::keyV res(a.size());\n  for (size_t i = 0; i < a.size(); ++i)\n  {\n    sc_mul(res[i].bytes, a[i].bytes, x.bytes);\n  }\n  return res;\n}\n\n/* Exponentiate a curve vector by a scalar */\nstatic rct::keyV vector_scalar2(const rct::keyV &a, const rct::key &x)\n{\n  rct::keyV res(a.size());\n  for (size_t i = 0; i < a.size(); ++i)\n  {\n    rct::scalarmultKey(res[i], a[i], x);\n  }\n  return res;\n}\n\nstatic rct::key switch_endianness(rct::key k)\n{\n  std::reverse(k.bytes, k.bytes + sizeof(k));\n  return k;\n}\n\n/* Compute the inverse of a scalar, the stupid way */\nstatic rct::key invert(const rct::key &x)\n{\n  rct::key inv;\n\n  BN_CTX *ctx = BN_CTX_new();\n  BIGNUM *X = BN_new();\n  BIGNUM *L = BN_new();\n  BIGNUM *I = BN_new();\n\n  BN_bin2bn(switch_endianness(x).bytes, sizeof(rct::key), X);\n  BN_bin2bn(switch_endianness(rct::curveOrder()).bytes, sizeof(rct::key), L);\n\n  CHECK_AND_ASSERT_THROW_MES(BN_mod_inverse(I, X, L, ctx), \"Failed to invert\");\n\n  const int len = BN_num_bytes(I);\n  CHECK_AND_ASSERT_THROW_MES((size_t)len <= sizeof(rct::key), \"Invalid number length\");\n  inv = rct::zero();\n  BN_bn2bin(I, inv.bytes);\n  std::reverse(inv.bytes, inv.bytes + len);\n\n  BN_free(I);\n  BN_free(L);\n  BN_free(X);\n  BN_CTX_free(ctx);\n\n#ifdef DEBUG_BP\n  rct::key tmp;\n  sc_mul(tmp.bytes, inv.bytes, x.bytes);\n  CHECK_AND_ASSERT_THROW_MES(tmp == rct::identity(), \"invert failed\");\n#endif\n  return inv;\n}\n\n/* Compute the slice of a vector */\nstatic rct::keyV slice(const rct::keyV &a, size_t start, size_t stop)\n{\n  CHECK_AND_ASSERT_THROW_MES(start < a.size(), \"Invalid start index\");\n  CHECK_AND_ASSERT_THROW_MES(stop <= a.size(), \"Invalid stop index\");\n  CHECK_AND_ASSERT_THROW_MES(start < stop, \"Invalid start/stop indices\");\n  rct::keyV res(stop - start);\n  for (size_t i = start; i < stop; ++i)\n  {\n    res[i - start] = a[i];\n  }\n  return res;\n}\n\nstatic rct::key hash_cache_mash(rct::key &hash_cache, const rct::key &mash0, const rct::key &mash1)\n{\n  rct::keyV data;\n  data.reserve(3);\n  data.push_back(hash_cache);\n  data.push_back(mash0);\n  data.push_back(mash1);\n  return hash_cache = rct::hash_to_scalar(data);\n}\n\nstatic rct::key hash_cache_mash(rct::key &hash_cache, const rct::key &mash0, const rct::key &mash1, const rct::key &mash2)\n{\n  rct::keyV data;\n  data.reserve(4);\n  data.push_back(hash_cache);\n  data.push_back(mash0);\n  data.push_back(mash1);\n  data.push_back(mash2);\n  return hash_cache = rct::hash_to_scalar(data);\n}\n\nstatic rct::key hash_cache_mash(rct::key &hash_cache, const rct::key &mash0, const rct::key &mash1, const rct::key &mash2, const rct::key &mash3)\n{\n  rct::keyV data;\n  data.reserve(5);\n  data.push_back(hash_cache);\n  data.push_back(mash0);\n  data.push_back(mash1);\n  data.push_back(mash2);\n  data.push_back(mash3);\n  return hash_cache = rct::hash_to_scalar(data);\n}\n\n/* Given a value v (0..2^N-1) and a mask gamma, construct a range proof */\nBulletproof bulletproof_PROVE(const rct::key &sv, const rct::key &gamma)\n{\n  CHECK_AND_ASSERT_THROW_MES(is_reduced(sv), \"Invalid sv input\");\n  CHECK_AND_ASSERT_THROW_MES(is_reduced(gamma), \"Invalid gamma input\");\n\n  init_exponents();\n\n  PERF_TIMER_UNIT(PROVE, 1000000);\n\n  constexpr size_t logN = 6; // log2(64)\n  constexpr size_t N = 1<<logN;\n\n  rct::key V;\n  rct::keyV aL(N), aR(N);\n\n  PERF_TIMER_START_BP(PROVE_v);\n  rct::addKeys2(V, gamma, sv, rct::H);\n  PERF_TIMER_STOP(PROVE_v);\n\n  PERF_TIMER_START_BP(PROVE_aLaR);\n  for (size_t i = N; i-- > 0; )\n  {\n    if (sv[i/8] & (((uint64_t)1)<<(i%8)))\n    {\n      aL[i] = rct::identity();\n    }\n    else\n    {\n      aL[i] = rct::zero();\n    }\n    sc_sub(aR[i].bytes, aL[i].bytes, rct::identity().bytes);\n  }\n  PERF_TIMER_STOP(PROVE_aLaR);\n\n  rct::key hash_cache = rct::hash_to_scalar(V);\n\n  // DEBUG: Test to ensure this recovers the value\n#ifdef DEBUG_BP\n  uint64_t test_aL = 0, test_aR = 0;\n  for (size_t i = 0; i < N; ++i)\n  {\n    if (aL[i] == rct::identity())\n      test_aL += ((uint64_t)1)<<i;\n    if (aR[i] == rct::zero())\n      test_aR += ((uint64_t)1)<<i;\n  }\n  uint64_t v_test = 0;\n  for (int n = 0; n < 8; ++n) v_test |= (((uint64_t)sv[n]) << (8*n));\n  CHECK_AND_ASSERT_THROW_MES(test_aL == v_test, \"test_aL failed\");\n  CHECK_AND_ASSERT_THROW_MES(test_aR == v_test, \"test_aR failed\");\n#endif\n\n  PERF_TIMER_START_BP(PROVE_step1);\n  // PAPER LINES 38-39\n  rct::key alpha = rct::skGen();\n  rct::key ve = vector_exponent(aL, aR);\n  rct::key A;\n  rct::addKeys(A, ve, rct::scalarmultBase(alpha));\n\n  // PAPER LINES 40-42\n  rct::keyV sL = rct::skvGen(N), sR = rct::skvGen(N);\n  rct::key rho = rct::skGen();\n  ve = vector_exponent(sL, sR);\n  rct::key S;\n  rct::addKeys(S, ve, rct::scalarmultBase(rho));\n\n  // PAPER LINES 43-45\n  rct::key y = hash_cache_mash(hash_cache, A, S);\n  rct::key z = hash_cache = rct::hash_to_scalar(y);\n\n  // Polynomial construction before PAPER LINE 46\n  rct::key t0 = rct::zero();\n  rct::key t1 = rct::zero();\n  rct::key t2 = rct::zero();\n\n  const auto yN = vector_powers(y, N);\n\n  rct::key ip1y = inner_product(oneN, yN);\n  rct::key tmp;\n  sc_muladd(t0.bytes, z.bytes, ip1y.bytes, t0.bytes);\n\n  rct::key zsq;\n  sc_mul(zsq.bytes, z.bytes, z.bytes);\n  sc_muladd(t0.bytes, zsq.bytes, sv.bytes, t0.bytes);\n\n  rct::key k = rct::zero();\n  sc_mulsub(k.bytes, zsq.bytes, ip1y.bytes, k.bytes);\n\n  rct::key zcu;\n  sc_mul(zcu.bytes, zsq.bytes, z.bytes);\n  sc_mulsub(k.bytes, zcu.bytes, ip12.bytes, k.bytes);\n  sc_add(t0.bytes, t0.bytes, k.bytes);\n\n  // DEBUG: Test the value of t0 has the correct form\n#ifdef DEBUG_BP\n  rct::key test_t0 = rct::zero();\n  rct::key iph = inner_product(aL, hadamard(aR, yN));\n  sc_add(test_t0.bytes, test_t0.bytes, iph.bytes);\n  rct::key ips = inner_product(vector_subtract(aL, aR), yN);\n  sc_muladd(test_t0.bytes, z.bytes, ips.bytes, test_t0.bytes);\n  rct::key ipt = inner_product(twoN, aL);\n  sc_muladd(test_t0.bytes, zsq.bytes, ipt.bytes, test_t0.bytes);\n  sc_add(test_t0.bytes, test_t0.bytes, k.bytes);\n  CHECK_AND_ASSERT_THROW_MES(t0 == test_t0, \"t0 check failed\");\n#endif\n  PERF_TIMER_STOP(PROVE_step1);\n\n  PERF_TIMER_START_BP(PROVE_step2);\n  const auto HyNsR = hadamard(yN, sR);\n  const auto vpIz = vector_scalar(oneN, z);\n  const auto vp2zsq = vector_scalar(twoN, zsq);\n  const auto aL_vpIz = vector_subtract(aL, vpIz);\n  const auto aR_vpIz = vector_add(aR, vpIz);\n\n  rct::key ip1 = inner_product(aL_vpIz, HyNsR);\n  sc_add(t1.bytes, t1.bytes, ip1.bytes);\n\n  rct::key ip2 = inner_product(sL, vector_add(hadamard(yN, aR_vpIz), vp2zsq));\n  sc_add(t1.bytes, t1.bytes, ip2.bytes);\n\n  rct::key ip3 = inner_product(sL, HyNsR);\n  sc_add(t2.bytes, t2.bytes, ip3.bytes);\n\n  // PAPER LINES 47-48\n  rct::key tau1 = rct::skGen(), tau2 = rct::skGen();\n\n  rct::key T1 = rct::addKeys(rct::scalarmultKey(rct::H, t1), rct::scalarmultBase(tau1));\n  rct::key T2 = rct::addKeys(rct::scalarmultKey(rct::H, t2), rct::scalarmultBase(tau2));\n\n  // PAPER LINES 49-51\n  rct::key x = hash_cache_mash(hash_cache, z, T1, T2);\n\n  // PAPER LINES 52-53\n  rct::key taux = rct::zero();\n  sc_mul(taux.bytes, tau1.bytes, x.bytes);\n  rct::key xsq;\n  sc_mul(xsq.bytes, x.bytes, x.bytes);\n  sc_muladd(taux.bytes, tau2.bytes, xsq.bytes, taux.bytes);\n  sc_muladd(taux.bytes, gamma.bytes, zsq.bytes, taux.bytes);\n  rct::key mu;\n  sc_muladd(mu.bytes, x.bytes, rho.bytes, alpha.bytes);\n\n  // PAPER LINES 54-57\n  rct::keyV l = vector_add(aL_vpIz, vector_scalar(sL, x));\n  rct::keyV r = vector_add(hadamard(yN, vector_add(aR_vpIz, vector_scalar(sR, x))), vp2zsq);\n  PERF_TIMER_STOP(PROVE_step2);\n\n  PERF_TIMER_START_BP(PROVE_step3);\n  rct::key t = inner_product(l, r);\n\n  // DEBUG: Test if the l and r vectors match the polynomial forms\n#ifdef DEBUG_BP\n  rct::key test_t;\n  sc_muladd(test_t.bytes, t1.bytes, x.bytes, t0.bytes);\n  sc_muladd(test_t.bytes, t2.bytes, xsq.bytes, test_t.bytes);\n  CHECK_AND_ASSERT_THROW_MES(test_t == t, \"test_t check failed\");\n#endif\n\n  // PAPER LINES 32-33\n  rct::key x_ip = hash_cache_mash(hash_cache, x, taux, mu, t);\n\n  // These are used in the inner product rounds\n  size_t nprime = N;\n  rct::keyV Gprime(N);\n  rct::keyV Hprime(N);\n  rct::keyV aprime(N);\n  rct::keyV bprime(N);\n  const rct::key yinv = invert(y);\n  rct::key yinvpow = rct::identity();\n  for (size_t i = 0; i < N; ++i)\n  {\n    Gprime[i] = Gi[i];\n    Hprime[i] = scalarmultKey(Hi[i], yinvpow);\n    sc_mul(yinvpow.bytes, yinvpow.bytes, yinv.bytes);\n    aprime[i] = l[i];\n    bprime[i] = r[i];\n  }\n  rct::keyV L(logN);\n  rct::keyV R(logN);\n  int round = 0;\n  rct::keyV w(logN); // this is the challenge x in the inner product protocol\n  PERF_TIMER_STOP(PROVE_step3);\n\n  PERF_TIMER_START_BP(PROVE_step4);\n  // PAPER LINE 13\n  while (nprime > 1)\n  {\n    // PAPER LINE 15\n    nprime /= 2;\n\n    // PAPER LINES 16-17\n    rct::key cL = inner_product(slice(aprime, 0, nprime), slice(bprime, nprime, bprime.size()));\n    rct::key cR = inner_product(slice(aprime, nprime, aprime.size()), slice(bprime, 0, nprime));\n\n    // PAPER LINES 18-19\n    L[round] = vector_exponent_custom(slice(Gprime, nprime, Gprime.size()), slice(Hprime, 0, nprime), slice(aprime, 0, nprime), slice(bprime, nprime, bprime.size()));\n    sc_mul(tmp.bytes, cL.bytes, x_ip.bytes);\n    rct::addKeys(L[round], L[round], rct::scalarmultKey(rct::H, tmp));\n    R[round] = vector_exponent_custom(slice(Gprime, 0, nprime), slice(Hprime, nprime, Hprime.size()), slice(aprime, nprime, aprime.size()), slice(bprime, 0, nprime));\n    sc_mul(tmp.bytes, cR.bytes, x_ip.bytes);\n    rct::addKeys(R[round], R[round], rct::scalarmultKey(rct::H, tmp));\n\n    // PAPER LINES 21-22\n    w[round] = hash_cache_mash(hash_cache, L[round], R[round]);\n\n    // PAPER LINES 24-25\n    const rct::key winv = invert(w[round]);\n    Gprime = hadamard2(vector_scalar2(slice(Gprime, 0, nprime), winv), vector_scalar2(slice(Gprime, nprime, Gprime.size()), w[round]));\n    Hprime = hadamard2(vector_scalar2(slice(Hprime, 0, nprime), w[round]), vector_scalar2(slice(Hprime, nprime, Hprime.size()), winv));\n\n    // PAPER LINES 28-29\n    aprime = vector_add(vector_scalar(slice(aprime, 0, nprime), w[round]), vector_scalar(slice(aprime, nprime, aprime.size()), winv));\n    bprime = vector_add(vector_scalar(slice(bprime, 0, nprime), winv), vector_scalar(slice(bprime, nprime, bprime.size()), w[round]));\n\n    ++round;\n  }\n  PERF_TIMER_STOP(PROVE_step4);\n\n  // PAPER LINE 58 (with inclusions from PAPER LINE 8 and PAPER LINE 20)\n  return Bulletproof(V, A, S, T1, T2, taux, mu, L, R, aprime[0], bprime[0], t);\n}\n\nBulletproof bulletproof_PROVE(uint64_t v, const rct::key &gamma)\n{\n  // vG + gammaH\n  PERF_TIMER_START_BP(PROVE_v);\n  rct::key sv = rct::zero();\n  sv.bytes[0] = v & 255;\n  sv.bytes[1] = (v >> 8) & 255;\n  sv.bytes[2] = (v >> 16) & 255;\n  sv.bytes[3] = (v >> 24) & 255;\n  sv.bytes[4] = (v >> 32) & 255;\n  sv.bytes[5] = (v >> 40) & 255;\n  sv.bytes[6] = (v >> 48) & 255;\n  sv.bytes[7] = (v >> 56) & 255;\n  PERF_TIMER_STOP(PROVE_v);\n  return bulletproof_PROVE(sv, gamma);\n}\n\n/* Given a range proof, determine if it is valid */\nbool bulletproof_VERIFY(const Bulletproof &proof)\n{\n  init_exponents();\n\n  CHECK_AND_ASSERT_MES(proof.V.size() == 1, false, \"V does not have exactly one element\");\n  CHECK_AND_ASSERT_MES(proof.L.size() == proof.R.size(), false, \"Mismatched L and R sizes\");\n  CHECK_AND_ASSERT_MES(proof.L.size() > 0, false, \"Empty proof\");\n  CHECK_AND_ASSERT_MES(proof.L.size() == 6, false, \"Proof is not for 64 bits\");\n\n  for (const rct::key &k: proof.V)\n    CHECK_AND_ASSERT_MES(rct::isInMainSubgroup(k), false, \"Input point not in subgroup\");\n  for (const rct::key &k: proof.L)\n    CHECK_AND_ASSERT_MES(rct::isInMainSubgroup(k), false, \"Input point not in subgroup\");\n  for (const rct::key &k: proof.R)\n    CHECK_AND_ASSERT_MES(rct::isInMainSubgroup(k), false, \"Input point not in subgroup\");\n\n  CHECK_AND_ASSERT_MES(rct::isInMainSubgroup(proof.A), false, \"Input point not in subgroup\");\n  CHECK_AND_ASSERT_MES(rct::isInMainSubgroup(proof.S), false, \"Input point not in subgroup\");\n  CHECK_AND_ASSERT_MES(rct::isInMainSubgroup(proof.T1), false, \"Input point not in subgroup\");\n  CHECK_AND_ASSERT_MES(rct::isInMainSubgroup(proof.T2), false, \"Input point not in subgroup\");\n\n  // check scalar range\n  CHECK_AND_ASSERT_MES(is_reduced(proof.taux), false, \"Input scalar not in range\");\n  CHECK_AND_ASSERT_MES(is_reduced(proof.mu), false, \"Input scalar not in range\");\n  CHECK_AND_ASSERT_MES(is_reduced(proof.a), false, \"Input scalar not in range\");\n  CHECK_AND_ASSERT_MES(is_reduced(proof.b), false, \"Input scalar not in range\");\n  CHECK_AND_ASSERT_MES(is_reduced(proof.t), false, \"Input scalar not in range\");\n\n  const size_t logN = proof.L.size();\n  const size_t N = 1 << logN;\n\n  // Reconstruct the challenges\n  PERF_TIMER_START_BP(VERIFY);\n  PERF_TIMER_START_BP(VERIFY_start);\n  rct::key hash_cache = rct::hash_to_scalar(proof.V[0]);\n  rct::key y = hash_cache_mash(hash_cache, proof.A, proof.S);\n  rct::key z = hash_cache = rct::hash_to_scalar(y);\n  rct::key x = hash_cache_mash(hash_cache, z, proof.T1, proof.T2);\n  PERF_TIMER_STOP(VERIFY_start);\n\n  PERF_TIMER_START_BP(VERIFY_line_60);\n  // Reconstruct the challenges\n  rct::key x_ip = hash_cache_mash(hash_cache, x, proof.taux, proof.mu, proof.t);\n  PERF_TIMER_STOP(VERIFY_line_60);\n\n  PERF_TIMER_START_BP(VERIFY_line_61);\n  // PAPER LINE 61\n  rct::key L61Left = rct::addKeys(rct::scalarmultBase(proof.taux), rct::scalarmultKey(rct::H, proof.t));\n\n  rct::key k = rct::zero();\n  const auto yN = vector_powers(y, N);\n  rct::key ip1y = inner_product(oneN, yN);\n  rct::key zsq;\n  sc_mul(zsq.bytes, z.bytes, z.bytes);\n  rct::key tmp, tmp2;\n  sc_mulsub(k.bytes, zsq.bytes, ip1y.bytes, k.bytes);\n  rct::key zcu;\n  sc_mul(zcu.bytes, zsq.bytes, z.bytes);\n  sc_mulsub(k.bytes, zcu.bytes, ip12.bytes, k.bytes);\n  PERF_TIMER_STOP(VERIFY_line_61);\n\n  PERF_TIMER_START_BP(VERIFY_line_61rl);\n  sc_muladd(tmp.bytes, z.bytes, ip1y.bytes, k.bytes);\n  rct::key L61Right = rct::scalarmultKey(rct::H, tmp);\n\n  CHECK_AND_ASSERT_MES(proof.V.size() == 1, false, \"proof.V does not have exactly one element\");\n  tmp = rct::scalarmultKey(proof.V[0], zsq);\n  rct::addKeys(L61Right, L61Right, tmp);\n\n  tmp = rct::scalarmultKey(proof.T1, x);\n  rct::addKeys(L61Right, L61Right, tmp);\n\n  rct::key xsq;\n  sc_mul(xsq.bytes, x.bytes, x.bytes);\n  tmp = rct::scalarmultKey(proof.T2, xsq);\n  rct::addKeys(L61Right, L61Right, tmp);\n  PERF_TIMER_STOP(VERIFY_line_61rl);\n\n  if (!(L61Right == L61Left))\n  {\n    MERROR(\"Verification failure at step 1\");\n    return false;\n  }\n\n  PERF_TIMER_START_BP(VERIFY_line_62);\n  // PAPER LINE 62\n  rct::key P = rct::addKeys(proof.A, rct::scalarmultKey(proof.S, x));\n  PERF_TIMER_STOP(VERIFY_line_62);\n\n  // Compute the number of rounds for the inner product\n  const size_t rounds = proof.L.size();\n  CHECK_AND_ASSERT_MES(rounds > 0, false, \"Zero rounds\");\n\n  PERF_TIMER_START_BP(VERIFY_line_21_22);\n  // PAPER LINES 21-22\n  // The inner product challenges are computed per round\n  rct::keyV w(rounds);\n  for (size_t i = 0; i < rounds; ++i)\n  {\n    w[i] = hash_cache_mash(hash_cache, proof.L[i], proof.R[i]);\n  }\n  PERF_TIMER_STOP(VERIFY_line_21_22);\n\n  PERF_TIMER_START_BP(VERIFY_line_24_25);\n  // Basically PAPER LINES 24-25\n  // Compute the curvepoints from G[i] and H[i]\n  rct::key inner_prod = rct::identity();\n  rct::key yinvpow = rct::identity();\n  rct::key ypow = rct::identity();\n\n  PERF_TIMER_START_BP(VERIFY_line_24_25_invert);\n  const rct::key yinv = invert(y);\n  rct::keyV winv(rounds);\n  for (size_t i = 0; i < rounds; ++i)\n    winv[i] = invert(w[i]);\n  PERF_TIMER_STOP(VERIFY_line_24_25_invert);\n\n  for (size_t i = 0; i < N; ++i)\n  {\n    // Convert the index to binary IN REVERSE and construct the scalar exponent\n    rct::key g_scalar = proof.a;\n    rct::key h_scalar;\n    sc_mul(h_scalar.bytes, proof.b.bytes, yinvpow.bytes);\n\n    for (size_t j = rounds; j-- > 0; )\n    {\n      size_t J = w.size() - j - 1;\n\n      if ((i & (((size_t)1)<<j)) == 0)\n      {\n        sc_mul(g_scalar.bytes, g_scalar.bytes, winv[J].bytes);\n        sc_mul(h_scalar.bytes, h_scalar.bytes, w[J].bytes);\n      }\n      else\n      {\n        sc_mul(g_scalar.bytes, g_scalar.bytes, w[J].bytes);\n        sc_mul(h_scalar.bytes, h_scalar.bytes, winv[J].bytes);\n      }\n    }\n\n    // Adjust the scalars using the exponents from PAPER LINE 62\n    sc_add(g_scalar.bytes, g_scalar.bytes, z.bytes);\n    sc_mul(tmp.bytes, zsq.bytes, twoN[i].bytes);\n    sc_muladd(tmp.bytes, z.bytes, ypow.bytes, tmp.bytes);\n    sc_mulsub(h_scalar.bytes, tmp.bytes, yinvpow.bytes, h_scalar.bytes);\n\n    // Now compute the basepoint's scalar multiplication\n    // Each of these could be written as a multiexp operation instead\n    rct::addKeys3(tmp, g_scalar, Gprecomp[i], h_scalar, Hprecomp[i]);\n    rct::addKeys(inner_prod, inner_prod, tmp);\n\n    if (i != N-1)\n    {\n      sc_mul(yinvpow.bytes, yinvpow.bytes, yinv.bytes);\n      sc_mul(ypow.bytes, ypow.bytes, y.bytes);\n    }\n  }\n  PERF_TIMER_STOP(VERIFY_line_24_25);\n\n  PERF_TIMER_START_BP(VERIFY_line_26);\n  // PAPER LINE 26\n  rct::key pprime;\n  sc_sub(tmp.bytes, rct::zero().bytes, proof.mu.bytes);\n  rct::addKeys(pprime, P, rct::scalarmultBase(tmp));\n\n  for (size_t i = 0; i < rounds; ++i)\n  {\n    sc_mul(tmp.bytes, w[i].bytes, w[i].bytes);\n    sc_mul(tmp2.bytes, winv[i].bytes, winv[i].bytes);\n#if 1\n    ge_dsmp cacheL, cacheR;\n    rct::precomp(cacheL, proof.L[i]);\n    rct::precomp(cacheR, proof.R[i]);\n    rct::addKeys3(tmp, tmp, cacheL, tmp2, cacheR);\n    rct::addKeys(pprime, pprime, tmp);\n#else\n    rct::addKeys(pprime, pprime, rct::scalarmultKey(proof.L[i], tmp));\n    rct::addKeys(pprime, pprime, rct::scalarmultKey(proof.R[i], tmp2));\n#endif\n  }\n  sc_mul(tmp.bytes, proof.t.bytes, x_ip.bytes);\n  rct::addKeys(pprime, pprime, rct::scalarmultKey(rct::H, tmp));\n  PERF_TIMER_STOP(VERIFY_line_26);\n\n  PERF_TIMER_START_BP(VERIFY_step2_check);\n  sc_mul(tmp.bytes, proof.a.bytes, proof.b.bytes);\n  sc_mul(tmp.bytes, tmp.bytes, x_ip.bytes);\n  tmp = rct::scalarmultKey(rct::H, tmp);\n  rct::addKeys(tmp, tmp, inner_prod);\n  PERF_TIMER_STOP(VERIFY_step2_check);\n  if (!(pprime == tmp))\n  {\n    MERROR(\"Verification failure at step 2\");\n    return false;\n  }\n\n  PERF_TIMER_STOP(VERIFY);\n  return true;\n}\n\n}\n", "meta": {"hexsha": "33840abf4e2f869a876e2dda729bd06f51dfc292", "size": 25836, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/ringct/bulletproofs.cc", "max_stars_repo_name": "mechanator/arqma", "max_stars_repo_head_hexsha": "c44326949042843f8e8af4132d8b3b93640ccd33", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ringct/bulletproofs.cc", "max_issues_repo_name": "mechanator/arqma", "max_issues_repo_head_hexsha": "c44326949042843f8e8af4132d8b3b93640ccd33", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ringct/bulletproofs.cc", "max_forks_repo_name": "mechanator/arqma", "max_forks_repo_head_hexsha": "c44326949042843f8e8af4132d8b3b93640ccd33", "max_forks_repo_licenses": ["BSD-3-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.9540816327, "max_line_length": 226, "alphanum_fraction": 0.6713113485, "num_tokens": 8548, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4893996344918333}}
{"text": "#define CATCH_CONFIG_MAIN\n\n#include \"CALPHADConcSolverBinary3Ph2Sl.h\"\n#include \"CALPHADConcSolverBinaryThreePhase.h\"\n#include \"CALPHADFreeEnergyFunctionsBinary.h\"\n#include \"CALPHADFreeEnergyFunctionsBinary3Ph2Sl.h\"\n#include \"CALPHADFreeEnergyFunctionsBinaryThreePhase.h\"\n\n#include \"InterpolationType.h\"\n#include \"PhysicalConstants.h\"\n\n#include \"catch.hpp\"\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 <fstream>\n#include <iostream>\n#include <string>\n\nnamespace pt = boost::property_tree;\n\nTEST_CASE(\"CALPHAD conc solver binary 3 phase, 2 sublattice KKS, \"\n          \"single-sublattice consistency\",\n    \"[conc solver binary 3 phase, 2 sublattice kks, single-sublattice \"\n    \"consistency]\")\n{\n    // Calculate the inputs and the reference solution\n    Thermo4PFM::EnergyInterpolationType energy_interp_func_type\n        = Thermo4PFM::EnergyInterpolationType::PBG;\n    Thermo4PFM::ConcInterpolationType conc_interp_func_type\n        = Thermo4PFM::ConcInterpolationType::PBG;\n\n    double temperature = 900.;\n\n    std::cout << \" Read CALPHAD database...\" << std::endl;\n    pt::ptree calphad_db;\n    try\n    {\n        pt::read_json(\n            \"../thermodynamic_data/calphadAlCuLFccBcc.json\", calphad_db);\n    }\n    catch (std::exception& e)\n    {\n        std::cerr << \"exception caught: \" << e.what() << std::endl;\n    }\n\n    boost::optional<pt::ptree&> newton_db;\n\n    // First calculate the reference solution\n\n    Thermo4PFM::CALPHADFreeEnergyFunctionsBinaryThreePhase cafe(\n        calphad_db, newton_db, energy_interp_func_type, conc_interp_func_type);\n\n    // Get the CALPHAD parameters\n    CalphadDataType fA[3];\n    CalphadDataType fB[3];\n    CalphadDataType Lmix_L[4];\n    CalphadDataType Lmix_A[4];\n    CalphadDataType Lmix_B[4];\n\n    cafe.computeTdependentParameters(\n        temperature, Lmix_L, Lmix_A, Lmix_B, fA, fB);\n\n    // initial guesses\n    double c_init0 = 0.9;\n    double c_init1 = 0.9;\n    double c_init2 = 0.9;\n\n    // compute concentrations satisfying KKS equations\n    const double conc = 0.9;\n\n    // Inputs to the solver\n    const double RT    = Thermo4PFM::gas_constant_R_JpKpmol * temperature;\n    const double RTinv = 1.0 / RT;\n\n    double hphi0 = interp_func(conc_interp_func_type, 0.5);\n    double hphi1 = interp_func(conc_interp_func_type, 0.4);\n    double hphi2 = interp_func(conc_interp_func_type, 0.1);\n\n    const double tol    = 1.e-8;\n    const double alpha  = 0.1; // Using alpha=1 can lead to convergence issues\n    const int max_iters = 10000;\n\n    // Create and set up the solver\n\n    Thermo4PFM::CALPHADConcSolverBinaryThreePhase solver_ref;\n    solver_ref.setup(\n        conc, hphi0, hphi1, hphi2, RT, Lmix_L, Lmix_A, Lmix_B, fA, fB);\n\n    // Run the solver\n    double sol_ref[3] = { c_init0, c_init1, c_init2 };\n    int ret = solver_ref.ComputeConcentration(sol_ref, tol, max_iters, alpha);\n    REQUIRE(ret >= 0);\n\n    // Now do the same calculation with the two-sublattice solver\n    int p[3];\n    int q[3];\n    for (int i = 0; i < 3; ++i)\n    {\n        p[i] = 0;\n        q[i] = 1;\n    }\n    Thermo4PFM::CALPHADConcSolverBinary3Ph2Sl solver;\n    solver.setup(\n        conc, hphi0, hphi1, hphi2, RTinv, Lmix_L, Lmix_A, Lmix_B, fA, fB, p, q);\n\n    // Run the solver\n    double sol_test[3] = { c_init0, c_init1, c_init2 };\n    ret = solver.ComputeConcentration(sol_test, tol, max_iters, alpha);\n    REQUIRE(ret >= 0);\n\n    // Check consistency\n    REQUIRE(sol_test[0] == Approx(sol_ref[0]).margin(1.e-5));\n    REQUIRE(sol_test[1] == Approx(sol_ref[1]).margin(1.e-5));\n    REQUIRE(sol_test[2] == Approx(sol_ref[2]).margin(1.e-5));\n}\n\nTEST_CASE(\"CALPHAD conc solver binary 3 phase, 2 sublattice KKS, \"\n          \"convergence\",\n    \"[conc solver binary 3 phase, 2 sublattice kks, convergence]\")\n{\n    // Calculate the inputs and the reference solution\n    Thermo4PFM::EnergyInterpolationType energy_interp_func_type\n        = Thermo4PFM::EnergyInterpolationType::PBG;\n    Thermo4PFM::ConcInterpolationType conc_interp_func_type\n        = Thermo4PFM::ConcInterpolationType::PBG;\n\n    double temperature = 820.;\n\n    std::cout << \" Read CALPHAD database...\" << std::endl;\n    pt::ptree calphad_db;\n    try\n    {\n        pt::read_json(\n            \"../thermodynamic_data/calphadAlCuLFccTheta.json\", calphad_db);\n    }\n    catch (std::exception& e)\n    {\n        std::cerr << \"exception caught: \" << e.what() << std::endl;\n    }\n\n    boost::optional<pt::ptree&> newton_db;\n\n    // Test 1\n\n    Thermo4PFM::CALPHADFreeEnergyFunctionsBinary3Ph2Sl cafe(\n        calphad_db, newton_db, energy_interp_func_type, conc_interp_func_type);\n\n    // Get the CALPHAD parameters\n    CalphadDataType fA[3];\n    CalphadDataType fB[3];\n    CalphadDataType Lmix_L[4];\n    CalphadDataType Lmix_A[4];\n    CalphadDataType Lmix_B[4];\n\n    cafe.computeTdependentParameters(\n        temperature, Lmix_L, Lmix_A, Lmix_B, fA, fB);\n\n    // initial guesses\n    double c_init0 = 0.8;\n    double c_init1 = 0.6;\n    double c_init2 = 0.67;\n\n    // compute concentrations satisfying KKS equations\n\n    // I think the system at 820K is best behaved in the conc = 0.67-0.8 range\n    double conc = 0.7;\n\n    // Inputs to the solver\n    const double RTinv\n        = 1.0 / (Thermo4PFM::gas_constant_R_JpKpmol * temperature);\n\n    // NOTE: The sum of hphi should equal one, which is not necessarily true for\n    // phi\n    double hphi0 = 0.1;\n    double hphi1 = 0.4;\n    double hphi2 = 0.5;\n\n    double tol    = 1.e-8;\n    double alpha  = 0.5; // Using alpha=1 can lead to convergence issues\n    int max_iters = 100;\n\n    int p[3];\n    int q[3];\n    for (int i = 0; i < 3; ++i)\n    {\n        p[i] = 0;\n        q[i] = 1;\n    }\n\n    p[2] = 2;\n\n    Thermo4PFM::CALPHADConcSolverBinary3Ph2Sl solver;\n    solver.setup(\n        conc, hphi0, hphi1, hphi2, RTinv, Lmix_L, Lmix_A, Lmix_B, fA, fB, p, q);\n\n    // Run the solver\n    double sol_test[3] = { c_init0, c_init1, c_init2 };\n    int ret = solver.ComputeConcentration(sol_test, tol, max_iters, alpha);\n\n    std::cout << \"-------------------------------\" << std::endl;\n    std::cout << \"Temperature = \" << temperature << std::endl;\n    std::cout << \"Result for c = \" << conc << std::endl;\n    std::cout << \"   cL = \" << sol_test[0] << std::endl;\n    std::cout << \"   cA = \" << sol_test[1] << std::endl;\n    std::cout << \"   cB = \" << sol_test[2] << std::endl;\n\n    REQUIRE(ret >= 0);\n\n    // Test 2\n    max_iters = 20000;\n    alpha     = 1.0;\n\n    sol_test[0] = 0.79267;\n    sol_test[1] = 0.79267;\n    sol_test[2] = 0.79267;\n\n    hphi0 = 0.989276;\n    hphi1 = 1.03871e-28;\n    hphi2 = 0.0107243;\n\n    conc = 0.79267;\n\n    solver.setup(\n        conc, hphi0, hphi1, hphi2, RTinv, Lmix_L, Lmix_A, Lmix_B, fA, fB, p, q);\n\n    // Run the solver\n    ret = solver.ComputeConcentration(sol_test, tol, max_iters, alpha);\n\n    std::cout << \"-------------------------------\" << std::endl;\n    std::cout << \"Temperature = \" << temperature << std::endl;\n    std::cout << \"Result for c = \" << conc << std::endl;\n    std::cout << \"   cL = \" << sol_test[0] << std::endl;\n    std::cout << \"   cA = \" << sol_test[1] << std::endl;\n    std::cout << \"   cB = \" << sol_test[2] << std::endl;\n    std::cout << \"Newton iterations = \" << ret << std::endl;\n    REQUIRE(ret >= 0);\n\n    // Test 3\n\n    max_iters = 2000;\n    alpha     = 1.0;\n\n    sol_test[0] = 0.7;\n    sol_test[1] = 0.9;\n    sol_test[2] = 0.794081;\n\n    hphi0 = 0.982551;\n    hphi1 = 0.0174491;\n    hphi2 = 4.79499e-25;\n\n    conc = 0.794081;\n\n    solver.setup(\n        conc, hphi0, hphi1, hphi2, RTinv, Lmix_L, Lmix_A, Lmix_B, fA, fB, p, q);\n\n    // Run the solver\n    ret = solver.ComputeConcentration(sol_test, tol, max_iters, alpha);\n\n    std::cout << \"-------------------------------\" << std::endl;\n    std::cout << \"Temperature = \" << temperature << std::endl;\n    std::cout << \"Result for c = \" << conc << std::endl;\n    std::cout << \"   cL = \" << sol_test[0] << std::endl;\n    std::cout << \"   cA = \" << sol_test[1] << std::endl;\n    std::cout << \"   cB = \" << sol_test[2] << std::endl;\n    std::cout << \"Newton iterations = \" << ret << std::endl;\n    REQUIRE(ret >= 0);\n}\n", "meta": {"hexsha": "40738c28dc24daf8a1184b113d4188e874a17179", "size": 8153, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tests/testCALPHADConcSolverBinary3Ph2Sl.cc", "max_stars_repo_name": "TApplencourt/Thermo4PFM", "max_stars_repo_head_hexsha": "6e98249d1b871e017c4a15052aed9d00ec2d6d96", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/testCALPHADConcSolverBinary3Ph2Sl.cc", "max_issues_repo_name": "TApplencourt/Thermo4PFM", "max_issues_repo_head_hexsha": "6e98249d1b871e017c4a15052aed9d00ec2d6d96", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/testCALPHADConcSolverBinary3Ph2Sl.cc", "max_forks_repo_name": "TApplencourt/Thermo4PFM", "max_forks_repo_head_hexsha": "6e98249d1b871e017c4a15052aed9d00ec2d6d96", "max_forks_repo_licenses": ["BSD-3-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.0848708487, "max_line_length": 80, "alphanum_fraction": 0.6219796394, "num_tokens": 2604, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.48939963449183327}}
{"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_PROD_HPP_INCLUDED\n#define BOOST_SIMD_TOOLBOX_ARITHMETIC_FUNCTIONS_SCALAR_TWO_PROD_HPP_INCLUDED\n#include <boost/simd/toolbox/arithmetic/functions/two_prod.hpp>\n#include <boost/dispatch/meta/adapted_traits.hpp>\n#include <boost/fusion/tuple.hpp>\n#include <boost/simd/include/functions/scalar/is_invalid.hpp>\n#include <boost/simd/include/functions/scalar/two_split.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION(boost::simd::tag::two_prod_, tag::cpu_,\n                          (A0),\n                          ((scalar_<floating_<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,A0 const& b,\n                                  A0 & r0,A0 & r1) const\n    {\n      r0  = a*b;\n      if (is_invalid(r0))\n      {\n        r1 = Zero<A0>();\n      }\n      else\n      {\n        A0 a1, a2, b1, b2;\n        two_split(a, a1, a2);\n        two_split(b, b1, b2);\n        r1 = a2*b2 -(((r0-a1*b1)-a2*b1)-a1*b2);\n      }\n      return 0;\n    }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION(boost::simd::tag::two_prod_, tag::cpu_,\n                          (A0),\n                          ((scalar_<floating_<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& a1,A0 & a3) const\n    {\n      A0 a2;\n      two_prod(a0, a1, a2, a3);\n      return a2;\n    }\n  };\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION(boost::simd::tag::two_prod_, tag::cpu_,\n                           (A0),\n                           ((scalar_<floating_<A0> >))\n                           ((scalar_<floating_<A0> >))\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\n#endif\n", "meta": {"hexsha": "fcedca6a3c400b4405e7fba8f9de0b7a8d476fd5", "size": 2748, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/arithmetic/include/boost/simd/toolbox/arithmetic/functions/scalar/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/scalar/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/scalar/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": 34.35, "max_line_length": 80, "alphanum_fraction": 0.5061863173, "num_tokens": 686, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.795658090372256, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.48939962853107954}}
{"text": "/*\n * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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#define BOOST_TEST_MAIN\n\n#define BOOST_TEST_MODULE populationanalysis_test\n\n// Standard includes\n#include <iostream>\n\n// Third party includes\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/unit_test.hpp>\n\n// VOTCA includes\n#include <votca/tools/eigenio_matrixmarket.h>\n\n// Local VOTCA includes\n#include \"votca/xtp/populationanalysis.h\"\n\nusing namespace std;\nusing namespace votca::xtp;\nusing namespace votca;\nBOOST_AUTO_TEST_SUITE(populationanalysis_test)\n\nBOOST_AUTO_TEST_CASE(atompop) {\n\n  Orbitals orb;\n  orb.QMAtoms().LoadFromFile(std::string(XTP_TEST_DATA_FOLDER) +\n                             \"/populationanalysis/molecule.xyz\");\n  orb.setDFTbasisName(std::string(XTP_TEST_DATA_FOLDER) +\n                      \"/populationanalysis/3-21G.xml\");\n  orb.setBasisSetSize(17);\n  orb.setNumberOfOccupiedLevels(5);\n\n  Eigen::MatrixXd& MOs = orb.MOs().eigenvectors();\n  orb.MOs().eigenvalues() = Eigen::VectorXd::Ones(17);\n  MOs = votca::tools::EigenIO_MatrixMarket::ReadMatrix(\n      std::string(XTP_TEST_DATA_FOLDER) + \"/populationanalysis/MOs.mm\");\n\n  Orbitals orb2 = orb;\n  QMState s(\"n\");\n  Lowdin low;\n  StaticSegment result = low.CalcChargeperAtom(orb, s);\n\n  Eigen::VectorXd charge = Eigen::VectorXd::Zero(result.size());\n  for (votca::Index i = 0; i < votca::Index(result.size()); i++) {\n    charge(i) = result[i].getCharge();\n  }\n\n  Eigen::VectorXd charge_ref = Eigen::VectorXd::Zero(5);\n  charge_ref << 0.68862, -0.172155, -0.172154, -0.172154, -0.172155;\n\n  bool check_lowdin = charge_ref.isApprox(charge, 1e-5);\n  BOOST_CHECK_EQUAL(check_lowdin, true);\n  if (!check_lowdin) {\n    cout << \"charge\" << endl;\n    cout << charge << endl;\n    cout << \"chargeref\" << endl;\n    cout << charge_ref << endl;\n  }\n\n  Mulliken mul;\n  StaticSegment result2 = mul.CalcChargeperAtom(orb2, s);\n  Eigen::VectorXd charge2 = Eigen::VectorXd::Zero(result2.size());\n  for (votca::Index i = 0; i < votca::Index(result2.size()); i++) {\n    charge2(i) = result2[i].getCharge();\n  }\n\n  Eigen::VectorXd charge_ref2 = Eigen::VectorXd::Zero(5);\n  charge_ref2 << 1.21228, -0.303069, -0.303067, -0.303068, -0.303068;\n\n  bool check_mulliken = charge_ref2.isApprox(charge2, 1e-5);\n  BOOST_CHECK_EQUAL(check_mulliken, true);\n  if (!check_mulliken) {\n    cout << \"charge\" << endl;\n    cout << charge2 << endl;\n    cout << \"chargeref\" << endl;\n    cout << charge_ref2 << endl;\n  }\n}\n\nBOOST_AUTO_TEST_CASE(fragment_pop) {\n\n  Orbitals orb;\n  orb.QMAtoms().LoadFromFile(std::string(XTP_TEST_DATA_FOLDER) +\n                             \"/populationanalysis/molecule.xyz\");\n  orb.setDFTbasisName(std::string(XTP_TEST_DATA_FOLDER) +\n                      \"/populationanalysis/3-21G.xml\");\n  orb.setBasisSetSize(17);\n  orb.setNumberOfOccupiedLevels(5);\n  orb.MOs().eigenvalues() = Eigen::VectorXd::Ones(17);\n\n  Eigen::MatrixXd MOs2 = votca::tools::EigenIO_MatrixMarket::ReadMatrix(\n      std::string(XTP_TEST_DATA_FOLDER) + \"/populationanalysis/MOs2.mm\");\n\n  orb.MOs().eigenvectors() = MOs2;\n  Eigen::VectorXd se_ref = Eigen::VectorXd::Zero(3);\n  se_ref << 0.107455, 0.107455, 0.107455;\n  orb.BSESinglets().eigenvalues() = se_ref;\n\n  // reference coefficients\n  Eigen::MatrixXd spsi_ref = votca::tools::EigenIO_MatrixMarket::ReadMatrix(\n      std::string(XTP_TEST_DATA_FOLDER) + \"/populationanalysis/spsi_ref.mm\");\n\n  orb.BSESinglets().eigenvectors() = spsi_ref;\n  orb.setBSEindices(0, 16);\n  orb.setTDAApprox(true);\n\n  std::vector<QMFragment<BSE_Population> > frags;\n  QMFragment<BSE_Population> f1(0, \"0 1\");\n  QMFragment<BSE_Population> f2(1, \"2 3 4\");\n  frags.push_back(f1);\n  frags.push_back(f2);\n\n  orb.DensityMatrixGroundState();\n  QMState n(\"n\");\n  Lowdin low;\n  BOOST_REQUIRE_THROW(low.CalcChargeperFragment(frags, orb, n.Type()),\n                      std::runtime_error);\n  QMState s1(\"s1\");\n  low.CalcChargeperFragment(frags, orb, s1.Type());\n\n  BOOST_CHECK_CLOSE(frags[0].value().Gs, 0.5164649, 1e-5);\n  BOOST_CHECK_CLOSE(frags[1].value().Gs, -0.5164628, 1e-5);\n\n  Eigen::VectorXd f1E_ref = Eigen::VectorXd::Zero(3);\n  f1E_ref << -0.384176, -0.812396, -0.414518;\n\n  Eigen::VectorXd f1H_ref = Eigen::VectorXd::Zero(3);\n  f1H_ref << 0.657215, 0.622434, 0.654751;\n\n  Eigen::VectorXd f2E_ref = Eigen::VectorXd::Zero(3);\n  f2E_ref << -0.615827, -0.187602, -0.58548;\n\n  Eigen::VectorXd f2H_ref = Eigen::VectorXd::Zero(3);\n  f2H_ref << 0.342785, 0.377565, 0.34525;\n\n  bool check_f1e = frags[0].value().E.isApprox(f1E_ref, 1e-5);\n  BOOST_CHECK_EQUAL(check_f1e, true);\n  if (!check_f1e) {\n    cout << \"charge\" << endl;\n    cout << frags[0].value().E << endl;\n    cout << \"chargeref\" << endl;\n    cout << f1E_ref << endl;\n  }\n\n  bool check_f1h = frags[0].value().H.isApprox(f1H_ref, 1e-5);\n  BOOST_CHECK_EQUAL(check_f1h, true);\n  if (!check_f1h) {\n    cout << \"charge\" << endl;\n    cout << frags[0].value().H << endl;\n    cout << \"chargeref\" << endl;\n    cout << f1H_ref << endl;\n  }\n  bool check_f2e = frags[1].value().E.isApprox(f2E_ref, 1e-5);\n  BOOST_CHECK_EQUAL(check_f2e, true);\n  if (!check_f2e) {\n    cout << \"charge\" << endl;\n    cout << frags[1].value().E << endl;\n    cout << \"chargeref\" << endl;\n    cout << f2E_ref << endl;\n  }\n  bool check_f2h = frags[1].value().H.isApprox(f2H_ref, 1e-5);\n  BOOST_CHECK_EQUAL(check_f2h, true);\n  if (!check_f2h) {\n    cout << \"charge\" << endl;\n    cout << frags[1].value().H << endl;\n    cout << \"chargeref\" << endl;\n    cout << f2H_ref << endl;\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "eb4728e436cc8e51b9ddf12c672f337b417442d7", "size": 6025, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/tests/test_populationanalysis.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/tests/test_populationanalysis.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/tests/test_populationanalysis.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.2192513369, "max_line_length": 77, "alphanum_fraction": 0.6731950207, "num_tokens": 1849, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956580806813577, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4893996225703257}}
{"text": "#pragma once\n#include <Eigen/Core>\n#include <gtsam/nonlinear/NonlinearFactor.h>\n#include <gtsam/geometry/Pose3.h>\n#include <gtsam/geometry/Point3.h>\n\nnamespace gtsam\n{\n  class LidarEdgeFactor2 : public NoiseModelFactor2<Pose3, Pose3>\n  {\n\n    using X = Pose3;\n    using Base = NoiseModelFactor2<Pose3, Pose3>;\n    using This = LidarEdgeFactor2;\n\n  public:\n    LidarEdgeFactor2(Key key1, Key key2, const Point3 &point1, const Point3 &unit, const Point3 &point2, const SharedNoiseModel &model)\n        : Base(model, key1, key2), p1_(point1), p2_(point2), u_(unit.normalized())\n    {\n    }\n\n    virtual ~LidarEdgeFactor2() {}\n\n    /*\n    d(R*u)/dT =  R*[[-u]x 03x3]\n    d(T*p)/dT =  R*[[-p]x I3x3]\n\n    line_err = (p2w-p1).cross(u)\n            = (T2*p2 - p1).cross(u)\n    dline_err/dT2 = (-u)x * d(T2*p2)/dT2 = (-u)x * R2 * [[-p]x I3X3]\n    */\n\n    /*\n    d(R*u)/dT =  R*[[-u]x 03x3]\n    d(T*p)/dT =  R*[[-p]x I3x3]\n\n    line_err = (p2w-p1w).cross(uw)\n            = (T2*p2 - T1*p1).cross(R1*u)\n    dline_err/dT1 = (T2*p2 - T1*p1)x * d(R1*u)/dT1 + (R1*u)x * d(T1*p1)/dT1\n    dline_err/dT2 = -(R1*u)x * d(T2*p2)/dT2\n    */\n\n    Vector evaluateError(const X &pose1, const X &pose2,\n                         boost::optional<Matrix &> H1 = boost::none,\n                         boost::optional<Matrix &> H2 = boost::none) const\n    {\n      const auto &rotation1 = pose1.rotation().matrix();\n      const auto &rotation2 = pose2.rotation().matrix();\n      const auto p12w = pose2.transformFrom(p2_) - pose1.transformFrom(p1_);\n      const auto uw = rotation1 * u_;\n      if (H1)\n        *H1 = skewSymmetric(p12w[0], p12w[1], p12w[2]) * rotation1 * (Matrix36() << skewSymmetric(-u_[0], -u_[1], -u_[2]), Z_3x3).finished() \n            + skewSymmetric(uw[0], uw[1], uw[2]) * rotation1 * (Matrix36() << skewSymmetric(-p1_[0], -p1_[1], -p1_[2]), I_3x3).finished();\n      if (H2)\n        *H2 = skewSymmetric(-uw[0], -uw[1], -uw[2]) * rotation2 * (Matrix36() << skewSymmetric(-p2_[0], -p2_[1], -p2_[2]), I_3x3).finished();\n      return p12w.cross(uw);\n    }\n\n    virtual NonlinearFactor::shared_ptr clone() const\n    {\n      return boost::static_pointer_cast<NonlinearFactor>(\n          NonlinearFactor::shared_ptr(new This(*this)));\n    }\n\n    virtual bool equals(const NonlinearFactor &expected, double tol = 1e-9) const\n    {\n      const This *e = dynamic_cast<const This *>(&expected);\n      return e != nullptr && Base::equals(*e, tol) && traits<Point3>::Equals(p1_, e->p1_, tol) &&\n             traits<Point3>::Equals(p2_, e->p2_, tol) && traits<Point3>::Equals(u_, e->u_, tol);\n    }\n\n    virtual void print(const std::string &s = \"\",\n                       const KeyFormatter &keyFormatter = DefaultKeyFormatter) const\n    {\n      cout << s << \":\\nLidarEdgeFactor2 on (\" << keyFormatter(key1())\n           << \", \" << keyFormatter(key2()) << \")\\n\"\n           << \"  Edge Point: \" << p1_.transpose() << \"\\n\"\n           << \"  Edge Axis: \" << u_.transpose() << \"\\n\"\n           << \"  Match Point: \" << p2_.transpose() << \"\\n\";\n      noiseModel_->print(\"  noise model: \");\n    }\n\n  private:\n    Point3 p1_, p2_, u_;\n\n  }; // class LidarEdgeFactor2\n\n  class LidarEdgeFactor1 : public NoiseModelFactor1<Pose3>\n  {\n\n    using X = Pose3;\n    using Base = NoiseModelFactor1<Pose3>;\n    using This = LidarEdgeFactor1;\n\n  public:\n    LidarEdgeFactor1(Key key, const Point3 &point1, const Point3 &unit, const Point3 &point2, const SharedNoiseModel &model)\n        : Base(model, key), p1_(point1), p2_(point2), u_(unit.normalized())\n    {\n    }\n\n    virtual ~LidarEdgeFactor1() {}\n\n    /*\n    d(R*u)/dT =  R*[[-u]x 03x3]\n    d(T*p)/dT =  R*[[-p]x I3x3]\n\n    line_err = (p2w-p1).cross(u)\n            = (T2*p2 - p1).cross(u)\n    dline_err/dT2 = (-u)x * d(T2*p2)/dT2 = (-u)x * R2 * [[-p]x I3X3]\n    */\n\n    /*\n    d(R*u)/dT =  R*[[-u]x 03x3]\n    d(T*p)/dT =  R*[[-p]x I3x3]\n\n    line_err = (p2w-p1w).cross(uw)\n            = (T2*p2 - T1*p1).cross(R1*u)\n    dline_err/dT1 = (T2*p2 - T1*p1)x * d(R1*u)/dT1 + (R1*u)x * d(T1*p1)/dT1\n    dline_err/dT2 = -(R1*u)x * d(T2*p2)/dT2\n    */\n\n    Vector evaluateError(const X &pose,\n                         boost::optional<Matrix &> H = boost::none) const\n    {\n      const auto &rotation = pose.rotation();\n      if (H)\n        *H = skewSymmetric(-u_[0], -u_[1], -u_[2]) * rotation.matrix() * (Matrix36() << skewSymmetric(-p2_[0], -p2_[1], -p2_[2]), I_3x3).finished();\n      return (pose.transformFrom(p2_) - p1_).cross(u_);\n    }\n\n    virtual NonlinearFactor::shared_ptr clone() const\n    {\n      return boost::static_pointer_cast<NonlinearFactor>(\n          NonlinearFactor::shared_ptr(new This(*this)));\n    }\n\n    virtual bool equals(const NonlinearFactor &expected, double tol = 1e-9) const\n    {\n      const This *e = dynamic_cast<const This *>(&expected);\n      return e != nullptr && Base::equals(*e, tol) && traits<Point3>::Equals(p1_, e->p1_, tol) &&\n             traits<Point3>::Equals(p2_, e->p2_, tol) && traits<Point3>::Equals(u_, e->u_, tol);\n    }\n\n    virtual void print(const std::string &s = \"\",\n                       const KeyFormatter &keyFormatter = DefaultKeyFormatter) const\n    {\n      cout << s << \":\\nLidarEdgeFactor1 on (\" << keyFormatter(key()) << \")\\n\"\n           << \"  Edge Point: \" << p1_.transpose() << \"\\n\"\n           << \"  Edge Axis: \" << u_.transpose() << \"\\n\"\n           << \"  Match Point: \" << p2_.transpose() << \"\\n\";\n      noiseModel_->print(\"  noise model: \");\n    }\n\n  private:\n    Point3 p1_, p2_, u_;\n\n  }; // class LidarEdgeFactor1\n\n  class LidarEdgeProjectedFactor1 : public NoiseModelFactor1<Pose3>\n  {\n\n    using X = Pose3;\n    using Base = NoiseModelFactor1<Pose3>;\n    using This = LidarEdgeProjectedFactor1;\n\n  public:\n    LidarEdgeProjectedFactor1(Key key, const Point3 &point1, const Point3 &unit, const Point3 &point2, const SharedNoiseModel &model)\n        : Base(model, key), p1_(point1), p2_(point2), u_(unit.normalized())\n    {\n      // std::cout << \"unit:\" << u_.transpose()<<\"\\n\";\n    }\n\n    virtual ~LidarEdgeProjectedFactor1() {}\n\n    /*\n    d(R*u)/dT =  R*[[-u]x 03x3]\n    d(T*p)/dT =  R*[[-p]x I3x3]\n\n    line_err = (p2w-p1).cross(u)\n            = (T2*p2 - p1).cross(u)\n    dline_err/dT2 = (-u)x * d(T2*p2)/dT2 = (-u)x * R2 * [[-p]x I3X3]\n    */\n\n    /*\n    d(R*u)/dT =  R*[[-u]x 03x3]\n    d(T*p)/dT =  R*[[-p]x I3x3]\n\n    line_err = (p2w-p1w).cross(uw)\n            = (T2*p2 - T1*p1).cross(R1*u)\n    dline_err/dT1 = (T2*p2 - T1*p1)x * d(R1*u)/dT1 + (R1*u)x * d(T1*p1)/dT1\n    dline_err/dT2 = -(R1*u)x * d(T2*p2)/dT2\n    */\n\n    /*\n    d(T^-1*p)/dT = [[T^-1*p]x -I3X3]\n    d(R^-1*u)/dT = [[R^T*u]x   03x3]\n\n    line_err = (p2 - p1).cross(u)\n             = (p2 - T2^-1*p1).cross(R2^T*u1)\n\n    point_err = (p2 - T2^-1*p1)[0,1] * R2^T*u1[2] = (p2 - c2)[0,1] * c1[2]\n\n    dline_err/dT2 = [R2^-1*u1]x*d(T2^-1*p1)/dT2 + d(R2^-1*u1)/dT2\n                  = [R2^T*u1]x*[[T2^-1*p1]x -I3X3] + [[R2^T*u1]x   03x3]\n\n    c1 = R2^T*u1\n    c2 = T2^-1*p1\n    dpoint_err/dT2 = -dc2/dT2[0,1] * c1[2] + (p2 - c2)[0,1] * dc1/dT2[2]\n                   = -[[c2]x -I3X3][0,1] * c1[2] +  (p2 - c2)[0,1]  *  [[c1]x  03x3][2]\n    dc1/dT2 = [[R2^T*u1]x   03x3]\n    dc2/dT2 = [[T2^-1*p1]x -I3X3]\n          \n   */\n\n    Vector evaluateError(const X &pose,\n                         boost::optional<Matrix &> H = boost::none) const\n    {\n      // const auto &rotation = pose.rotation();\n      // if (H)\n      // {\n      //   *H = skewSymmetric(-u_[0], -u_[1], -u_[2]) * rotation.matrix() * (Matrix36() << skewSymmetric(-p2_[0], -p2_[1], -p2_[2]), I_3x3).finished();\n      // H->col(0).setZero();\n      // H->col(1).setZero();\n      // H->col(5).setZero();\n      // }\n      // return (pose.transformFrom(p2_) - p1_).cross(u_);\n\n      const auto c1 = pose.rotation().inverse() * u_;\n      const auto c2 = pose.inverse().transformFrom(p1_);\n\n      \n      if (H)\n      {\n        // *H = skewSymmetric(c1[0], c1[1], c1[2]) * (Matrix36() << skewSymmetric(c2[0], c2[1], c2[2]), -I_3x3).finished()\n            // + (Matrix36() << skewSymmetric(c1[0], c1[1], c1[2]), Z_3x3).finished();\n        //  *H = (Matrix13() << -c1[1], +c1[0], 0.0).finished() * (Matrix36() << skewSymmetric(c2[0], c2[1], c2[2]), -I_3x3).finished() + (Matrix16() << -c1[1], +c1[0], 0.0, 0.0, 0.0, 0.0).finished();\n        *H = (Matrix36() << (Matrix13() << -c1[1], +c1[0], 0.0).finished() * (Matrix36() << skewSymmetric(c2[0], c2[1], c2[2]), -I_3x3).finished() + (Matrix16() << -c1[1], +c1[0], 0.0, 0.0, 0.0, 0.0).finished(),\n             -(Matrix36() << skewSymmetric(c2[0], c2[1], c2[2]), -I_3x3).finished().topRows(2) * c1[2] +  (p2_ - c2).topRows(2)  *  (Matrix16() << -c1[1], +c1[0], 0.0, 0.0, 0.0, 0.0).finished()).finished();\n      }\n\n      // return Vector1((p2_[0] - c2[0]) * c1[1] - (p2_[1] - c2[1]) * c1[0]);\n      return (Vector3() << (p2_[0] - c2[0]) * c1[1] - (p2_[1] - c2[1]) * c1[0], (p2_ - c2).topRows(2) * c1[2]).finished();\n      // return (p2_ - c2).cross(c1);\n    }\n\n    virtual NonlinearFactor::shared_ptr clone() const\n    {\n      return boost::static_pointer_cast<NonlinearFactor>(\n          NonlinearFactor::shared_ptr(new This(*this)));\n    }\n\n    virtual bool equals(const NonlinearFactor &expected, double tol = 1e-9) const\n    {\n      const This *e = dynamic_cast<const This *>(&expected);\n      return e != nullptr && Base::equals(*e, tol) && traits<Point3>::Equals(p1_, e->p1_, tol) &&\n             traits<Point3>::Equals(p2_, e->p2_, tol) && traits<Point3>::Equals(u_, e->u_, tol);\n    }\n\n    virtual void print(const std::string &s = \"\",\n                       const KeyFormatter &keyFormatter = DefaultKeyFormatter) const\n    {\n      cout << s << \":\\nLidarEdgeProjectedFactor1 on (\" << keyFormatter(key()) << \")\\n\"\n           << \"  Edge Point: \" << p1_.transpose() << \"\\n\"\n           << \"  Edge Axis: \" << u_.transpose() << \"\\n\"\n           << \"  Match Point: \" << p2_.transpose() << \"\\n\";\n      noiseModel_->print(\"  noise model: \");\n    }\n\n  private:\n    Point3 p1_, p2_, u_;\n\n  }; // class LidarEdgeProjectedFactor1\n\nclass LidarEdgeProjectedFactor2 : public NoiseModelFactor2<Pose3, Pose3>\n  {\n\n    using X = Pose3;\n    using Base = NoiseModelFactor2<Pose3, Pose3>;\n    using This = LidarEdgeProjectedFactor2;\n\n  public:\n    LidarEdgeProjectedFactor2(Key key1, Key key2, const Point3 &point1, const Point3 &unit, const Point3 &point2, const SharedNoiseModel &model)\n        : Base(model, key1, key2), p1_(point1), p2_(point2), u_(unit.normalized())\n    {\n    }\n\n    virtual ~LidarEdgeProjectedFactor2() {}\n\n    /*\n    d(R*u)/dT =  R*[[-u]x 03x3]\n    d(T*p)/dT =  R*[[-p]x I3x3]\n\n    line_err = (p2w-p1).cross(u)\n            = (T2*p2 - p1).cross(u)\n    dline_err/dT2 = (-u)x * d(T2*p2)/dT2 = (-u)x * R2 * [[-p]x I3X3]\n    */\n\n    /*\n    d(R*u)/dT =  R*[[-u]x 03x3]\n    d(T*p)/dT =  R*[[-p]x I3x3]\n\n    line_err = (p2w-p1w).cross(uw)\n            = (T2*p2 - T1*p1).cross(R1*u)\n    dline_err/dT1 = (T2*p2 - T1*p1)x * d(R1*u)/dT1 + (R1*u)x * d(T1*p1)/dT1\n    dline_err/dT2 = -(R1*u)x * d(T2*p2)/dT2\n    */\n\n    /*\n    d(T^-1*p)/dT = [[T^-1*p]x -I3X3]\n    d(R^-1*u)/dT = [[R^T*u]x   03x3]\n\n    line_err = (T1^-1*T2*p2 - p1).cross(u1)\n    \n    point_err = (T1^-1*T2*p2 - p1)[0,1] * u1[2]\n\n    dline_err/dT1 = -[u1]x*d(T1^-1*T2*p2)/dT1\n                  = -[u1]x*[[T1^-1*T2*p2]x -I3X3]\n    dline_err/dT2 = -[u1]x*d(T1^-1*T2*p2)/dT2\n                  = -[u1]x*T1^-1*R2*[[-p2]x I3x3]\n                  = -[u1]x*R(T1^-1)*R2*[[-p2]x I3x3]\n                  = -[u1]x*R1^-1*R2*[[-p2]x I3x3]\n    dpoint_err/dT1 = u1[2]*d(T1^-1*T2*p2)/dT1[0,1]\n                   = u1[2]*[[T1^-1*T2*p2]x -I3X3][0,1]\n    dpoint_err/dT2 = u1[2]*d(T1^-1*T2*p2)/dT2[0,1]\n                   = u1[2]*T1^-1*R2*[[-p2]x I3x3][0,1]\n                   = u1[2]*R(T1^-1)*R2*[[-p2]x I3x3][0,1]\n                   = u1[2]*R1^-1*R2*[[-p2]x I3x3][0,1]\n   */\n\n    Vector evaluateError(const X &pose1, const X &pose2,\n                         boost::optional<Matrix &> H1 = boost::none,\n                         boost::optional<Matrix &> H2 = boost::none) const\n    {\n      // const auto ux = skewSymmetric(u_[0], u_[1], u_[2]);\n      const auto p2_transformed = (pose1.inverse()*pose2).transformFrom(p2_);\n\n      if (H1)\n      {\n        // *H1 = -ux * (Matrix36() << skewSymmetric(p2_transformed[0], p2_transformed[1], p2_transformed[2]), -I_3x3).finished();\n        // *H1 = -(Matrix13() << -u_[1], u_[0], 0.0).finished() * (Matrix36() << skewSymmetric(p2_transformed[0], p2_transformed[1], p2_transformed[2]), -I_3x3).finished();\n        *H1 = (Matrix36() << -(Matrix13() << -u_[1], u_[0], 0.0).finished() * (Matrix36() << skewSymmetric(p2_transformed[0], p2_transformed[1], p2_transformed[2]), -I_3x3).finished(),\n                             u_[2] * (Matrix36() << skewSymmetric(p2_transformed[0], p2_transformed[1], p2_transformed[2]), -I_3x3).finished().topRows(2)).finished();\n          //  *H1 = u_[2] * (Matrix36() << skewSymmetric(p2_transformed[0], p2_transformed[1], p2_transformed[2]), -I_3x3).finished().topRows(2);\n\n\n      }\n      if (H2)\n      {\n        // *H2 = -ux * pose1.rotation().inverse().matrix() * pose2.rotation().matrix() * (Matrix36() << skewSymmetric(-p2_[0], -p2_[1], -p2_[2]), I_3x3).finished();\n        // *H2 = -(Matrix13() << -u_[1], u_[0], 0.0).finished() * pose1.rotation().inverse().matrix() * pose2.rotation().matrix() * (Matrix36() << skewSymmetric(-p2_[0], -p2_[1], -p2_[2]), I_3x3).finished();\n        *H2 = (Matrix36() << -(Matrix13() << -u_[1], u_[0], 0.0).finished() * pose1.rotation().inverse().matrix() * pose2.rotation().matrix() * (Matrix36() << skewSymmetric(-p2_[0], -p2_[1], -p2_[2]), I_3x3).finished(),\n              u_[2] * (pose1.rotation().inverse().matrix() * pose2.rotation().matrix() * (Matrix36() << skewSymmetric(-p2_[0], -p2_[1], -p2_[2]), I_3x3).finished()).topRows(2)).finished();\n        // *H2 = u_[2] * (pose1.rotation().inverse().matrix() * pose2.rotation().matrix() * (Matrix36() << skewSymmetric(-p2_[0], -p2_[1], -p2_[2]), I_3x3).finished()).topRows(2);\n          \n      }\n\n      // return (p2_transformed - p1_).cross(u_);\n      // return Vector1((p2_transformed[0] - p1_[0]) * u_[1] - (p2_transformed[1] - p1_[1]) * u_[0]);\n      return (Vector3() << (p2_transformed[0] - p1_[0]) * u_[1] - (p2_transformed[1] - p1_[1]) * u_[0],\n                           (p2_transformed - p1_).topRows(2)  * u_(2)).finished();  \n      // return Vector2((p2_transformed - p1_).topRows(2)  * u_(2));\n    \n    }\n\n    virtual NonlinearFactor::shared_ptr clone() const\n    {\n      return boost::static_pointer_cast<NonlinearFactor>(\n          NonlinearFactor::shared_ptr(new This(*this)));\n    }\n\n    virtual bool equals(const NonlinearFactor &expected, double tol = 1e-9) const\n    {\n      const This *e = dynamic_cast<const This *>(&expected);\n      return e != nullptr && Base::equals(*e, tol) && traits<Point3>::Equals(p1_, e->p1_, tol) &&\n             traits<Point3>::Equals(p2_, e->p2_, tol) && traits<Point3>::Equals(u_, e->u_, tol);\n    }\n\n    virtual void print(const std::string &s = \"\",\n                       const KeyFormatter &keyFormatter = DefaultKeyFormatter) const\n    {\n      cout << s << \":\\nLidarEdgeProjectedFactor2 on (\" << keyFormatter(key1())\n           << \", \" << keyFormatter(key2()) << \")\\n\"\n           << \"  Edge Point: \" << p1_.transpose() << \"\\n\"\n           << \"  Edge Axis: \" << u_.transpose() << \"\\n\"\n           << \"  Match Point: \" << p2_.transpose() << \"\\n\";\n      noiseModel_->print(\"  noise model: \");\n    }\n\n  private:\n    Point3 p1_, p2_, u_;\n\n  }; // class LidarEdgeProjectedFactor2\n\n\n\n} // namespace gtsam\n", "meta": {"hexsha": "273d5248c623d3a3bbc34661478df46cd68ba5e9", "size": 15490, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/include/factors/LidarEdgeFactor.hpp", "max_stars_repo_name": "Saki-Chen/W-LOAM", "max_stars_repo_head_hexsha": "39ad29da0db760401c06d17c22a0e43d8562efec", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2021-08-24T02:24:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T09:56:10.000Z", "max_issues_repo_path": "src/include/factors/LidarEdgeFactor.hpp", "max_issues_repo_name": "xingchengzhi/W-LOAM", "max_issues_repo_head_hexsha": "eca5c1932fc48b0d4f47cfd7bc85c874afd09631", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-11-01T03:41:16.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-24T12:33:35.000Z", "max_forks_repo_path": "src/include/factors/LidarEdgeFactor.hpp", "max_forks_repo_name": "xingchengzhi/W-LOAM", "max_forks_repo_head_hexsha": "eca5c1932fc48b0d4f47cfd7bc85c874afd09631", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2021-10-30T05:11:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T08:59:59.000Z", "avg_line_length": 39.0176322418, "max_line_length": 219, "alphanum_fraction": 0.5390574564, "num_tokens": 5650, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256631249077, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4893558597582074}}
{"text": "#ifndef OpticalElementInterface_hpp\n#define OpticalElementInterface_hpp\n\n/** @file OpticalElementInterface.hpp\n * @brief Definition of the optical element interface.\n * @author C.D. Clark III\n * @date 06/29/16\n */\n\n#include <memory>\n\n#include <Eigen/Dense>\n\n#include \"../Units.hpp\"\n\n/** @class OpticalElementInterface\n * @brief Abstract class that defines the interface an optical element must\n * implement.\n * @author C.D. Clark III\n *\n * An optical element tranforms a Gaussian beam. Before a beam enters the\n * element, it has a beam waist size and position. After it exists the element,\n * it has a new waist size and position. The theory of Gaussian beam propagation\n * based on the paraxial wave equation accounts for the action of an optical\n * element with Ray Transfer Matircies (RTM)\n * (https://en.wikipedia.org/wiki/Ray_transfer_matrix_analysis). These are the\n * same matricies that are used to transform optical rays when ray tracing\n * through an optical system and they are convienent because the action of\n * multiple elements can be accounted for my simply multiplying their RTM\n * together.\n *\n * This method is often referred to as the \"ABCD\" law for Gaussian beams.\n * Basically, the RTM is a \\f$2\\times2\\f$ matrix that can be written as \\f[\n * \\left(\n * \\begin{matrix}\n * A & B \\\\\n * C & D\n * \\end{matrix}\n * \\right)\n * \\f]\n * The action of the element is then given by its affect on the complex beam\n * parameter (https://en.wikipedia.org/wiki/Complex_beam_parameter) \\f[ q_f =\n * \\frac{Aq_i + B}{Cq_i + D} \\f]\n *\n * Where $q_i$ and $q_f$ are the complex beam parameters of the beam before and\n * after it passes through the lens. The complex beam parameter itself is\n * defined as \\f$q = z + iz_R\\f$ where \\f$z\\f$ is the distance from the beam\n * waist and \\f$z_R\\f$ is the Rayleigh range (\\f$z_R = \\frac{\\pi\n * \\omega_0^2}{\\lambda}\\f$, where \\f$\\omega_0\\f$ is the beam waist radius\n * (\\f$1/e^2\\f$) and \\f$\\lambda\\f$ is the wavelength.).\n *\n * One important point to make here is that the usual treatment of this method\n * assumes that the beam waist is always located at \\f$z = 0\\f$. In other words,\n * the origin of the coordinate system is always taken to be at the beam waist\n * which means that when the beam waist position changes (after it goes through\n * an optical element), the coordinate system changes.\n *\n * This library performs calculations in a fixed coordinate system. The beam\n * waist position is explicitly tracked, and when the beam passes through an\n * optical element, the beam waist position is updated. This introduces a few\n * subtle details that must be handled correctly. Some of these only affect the\n * GaussianBeam class. However, a few also affect optical elements.\n *\n * The optical element class is intended to encapsulate all of the information\n * necessary for a GaussianBeam instance to transform itself. In order to do\n * that, the beam will need the RTM representing the element. No surprise there.\n * However, it is possible for an element to separate two different media (more\n * specifically, two materials with different refractive indices. When this is\n * the case, the wavelength of the beam will change (since \\f$\\lambda =\n * \\frac{\\lambda_0}{n}\\f$) and this change must be known in order for the beam\n * to update the beam waist size since the imaginary portion of the complex beam\n * parameter contains both the wavelength and beam waist radius. So, an optical\n * element must provide a method that the GaussianBeam instance can use to\n * determine the new wavelength.\n *\n * The second detail that arises from the uses of a fixed coordinate system is\n * the possibility that the z position of the complex beam parameter may shift\n * when it passes through the element. In other words, the z position of the\n * initial parameter may not coincide with the position of the final parameter.\n * When the coordinate system is always centered on the beam waist, this does\n * not matter. The real part of the complex beam parameter gives the distance to\n * the beam waist. However, for a fixed coordinate system, this possible shift\n * needs to be accounted for. The best example of this is a thick lens. The RTM\n * for a thick lens includes the refraction across the front surface,\n * propagation through the lens, and refraction across the back surface. When\n * this matrix is used to transform the complex beam parameter, the initial\n * parameter is evaluated at the front surface of the lens and the new parameter\n * actually corresponds to the position of the back surface of the lens.\n *\n * This shift needs to be known in order for the beam waist position to be\n * determined, so an optical element must provide a method to that the\n * GaussianBeam instance can use to determine the new beam waist position.\n *\n * @tparam LengthUnitType the length unit that will be used for calculating\n * elements of the RTM and position shifts.\n */\n\ntemplate<typename LengthUnitType>\nclass OpticalElementInterface\n{\n public:\n  virtual Eigen::Matrix<double, 2, 2> getRTMatrix()\n      const = 0;  ///< return the Ray Transfer matrix for the element. NOTE:\n                  ///< elements MUST be returned in units of LengthUnitType or\n                  ///< inverse LengthUnitType.\n  virtual boost::units::quantity<LengthUnitType> getPositionShift()\n      const = 0;  ///< return the difference in the position (z coordinate) that\n                  ///< the complex beam parameter corresponds to after it passes\n                  ///< through the element.\n  virtual double getPowerLoss()\n      const = 0;  ///< return the power loss (fraction) through the element\n  virtual double getWavelengthScaleFactor()\n      const = 0;  ///< return the scaling factor through the element. i.e. if\n                  ///< the wavelenght changes when light passes through the\n                  ///< element.\n};\n\ntemplate<typename T, typename U>\nclass OpticalElementAdapter : public OpticalElementInterface<U>\n{\n private:\n  T &t;\n\n public:\n  OpticalElementAdapter(T &ref) : t(ref) {}\n  Eigen::Matrix<double, 2, 2> getRTMatrix() const { return t.getRTMatrix(); }\n  boost::units::quantity<U> getPositionShift() const { return t.getPositionShift(); }\n  double      getPowerLoss() const { return t.getPowerLoss(); }\n  double      getWavelengthScaleFactor() const\n  {\n    return t.getWavelengthScaleFactor();\n  }\n};\n\ntemplate<typename T>\nusing OpticalElement_ptr = std::shared_ptr<OpticalElementInterface<T> >;\n\n#endif  // include protector\n", "meta": {"hexsha": "4fac4be692a0bd42a73f7deb6d2c22dd1f573c42", "size": 6477, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/libGBP/OpticalElements/OpticalElementInterface.hpp", "max_stars_repo_name": "CD3/libGBP", "max_stars_repo_head_hexsha": "6561f41d74d0e4010872c12db1dcc12363826365", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/libGBP/OpticalElements/OpticalElementInterface.hpp", "max_issues_repo_name": "CD3/libGBP", "max_issues_repo_head_hexsha": "6561f41d74d0e4010872c12db1dcc12363826365", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libGBP/OpticalElements/OpticalElementInterface.hpp", "max_forks_repo_name": "CD3/libGBP", "max_forks_repo_head_hexsha": "6561f41d74d0e4010872c12db1dcc12363826365", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.5971223022, "max_line_length": 85, "alphanum_fraction": 0.7305851474, "num_tokens": 1497, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.5813030906443134, "lm_q1q2_score": 0.4893558551445969}}
{"text": "//\t\t\tCopyright Gavin Band 2008 - 2012.\n// Distributed under the Boost Software License, Version 1.0.\n//\t  (See accompanying file LICENSE_1_0.txt or copy at\n//\t\t\thttp://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef INTEGRATION_MODIFIED_CHOLESKY_HPP\n#define INTEGRATION_MODIFIED_CHOLESKY_HPP\n\n#include <iostream>\n#include <boost/noncopyable.hpp>\n#include <Eigen/Core>\n#include <Eigen/Cholesky>\n#include <Eigen/Eigenvalues>\n\n// #define DEBUG_MODIFIED_CHOLESKY 1\n\nnamespace metro {\n\t// Utility functions\n\tnamespace {\n\t\ttemplate< typename Real >\n\t\tReal max( Real const a, Real const b ) {\n\t\t\treturn std::max( a, b ) ;\n\t\t}\n\n\t\ttemplate< typename Real >\n\t\tReal max( Real const a, Real const b, Real const c ) {\n\t\t\treturn std::max( a, std::max( b, c )) ;\n\t\t}\n\t}\n\n\t//\n\t// Implements the 'MC' algorithm from Gill & Murray, Practical Optimisation.\n\t// Also expressed as Algorithm 6.5, \"Modified Cholesky algorithm\" in\n\t// Nocedal & Wright, \"Numerical Optimisation\".\n\t// See also Fang & Leary 2006\n\t//\n\t// I have borrowed a little bit from Eigen's LDLT.h here to get the permutations and types right.\n\t//\n\t// This algorithm only touches the lower-diagonal of the matrix.\n\t// As described in the above references, we use the lower-diagonal of the matrix\n\t// to store the non-unity entries of L, and the diagonal to store the entries of D.\n\t// The auxiliary variables c_ij are stored in the lower diagonal too until they\n\t// are overwritten by entries of L and D.\n\t//\n\t// At step j the matrix looks like:\n\t//\n\t//\t  0 . . j . .\n\t// 0  d\n\t// .  l d\n\t// .  l l d\n\t// j  c c c c\n\t// .  c c c a c\n\t// .  c c c a a c\n\t//\n\t// Where a refers to an entry of the original matrix (after the possible permutations) and l refers to an entry of\n\t// the computed matrix L, d refers to an entry of D, and c to one of the auxiliary c_ijs.\n\t//\n\t// At the jth step we update this to become\n\t// 1: d\n\t// .  l d\n\t// .  l l d\n\t// j: l l l d\n\t// .  c c c c c\n\t// .  c c c c a c\n\t//\n\t// i.e. we compute the jth row of L, the jth entry of D, and the c's in\n\t// the jth column and on the diagonal below j.\n\ttemplate< typename Matrix >\n\tstruct ModifiedCholesky {\n\tpublic:\n\t\tenum {\n\t\t  RowsAtCompileTime = Matrix::RowsAtCompileTime,\n\t\t  ColsAtCompileTime = Matrix::ColsAtCompileTime,\n\t\t  Options = Matrix::Options & ~Eigen::RowMajorBit, // these are the options for the TmpMatrixType, we need a ColMajor matrix here!\n\t\t  MaxRowsAtCompileTime = Matrix::MaxRowsAtCompileTime,\n\t\t  MaxColsAtCompileTime = Matrix::MaxColsAtCompileTime,\n\t\t  UpLo = Eigen::Lower\n\t\t} ;\n\t\ttypedef typename Matrix::Scalar Scalar;\n\t\ttypedef typename Eigen::NumTraits<typename Matrix::Scalar>::Real RealScalar;\n\t\ttypedef typename Matrix::Index Index;\n\n\t\ttypedef Eigen::Transpositions<RowsAtCompileTime, MaxRowsAtCompileTime> Transpositions;\n\t\ttypedef Eigen::PermutationMatrix<RowsAtCompileTime, MaxRowsAtCompileTime> Permutations;\n\t\ttypedef Eigen::TriangularView< Matrix const, Eigen::UnitLower > const MatrixL ;\n\t\ttypedef Eigen::Diagonal< Matrix const > Diagonal ;\n\n\tpublic:\n\t\tModifiedCholesky() {}\n\n\t\tModifiedCholesky( ModifiedCholesky const& other ):\n\t\t\tm_matrix( other.m_matrix ),\n\t\t\tm_transpositions( other.m_transpositions )\n\t\t{}\n\n\t\tModifiedCholesky& operator=( ModifiedCholesky const& other ) {\n\t\t\tm_matrix = other.m_matrix ;\n\t\t\tm_transpositions = other.m_transpositions ;\n\t\t\treturn *this ;\n\t\t}\n\t\t\n\t\tModifiedCholesky& compute( Matrix const& matrix ) {\n\t\t\tm_matrix = matrix ;\n\t\t\tcompute_inplace( m_matrix ) ;\n\t\t\treturn *this ;\n\t\t}\n\t\t\n\t\tMatrixL matrixL() const {\n\t\t\treturn m_matrix.template triangularView< Eigen::UnitLower >() ;\n\t\t}\n\t\t\n\t\tDiagonal vectorD() const {\n\t\t\treturn m_matrix.diagonal();\n\t\t}\n\n\t\tPermutations const matrixP() const {\n\t\t\treturn Permutations( m_transpositions ) ;\n\t\t}\n\t\t\n\t\tMatrix solve( Matrix const& rhs ) const\n\t\t{\n\t\t\tMatrix result = rhs ;\n\t\t\tassert( result.rows() == m_matrix.rows() ) ;\n\t\t\t// result = P rhs\n\t\t\tresult = m_transpositions * result ;\n\t\t\t// result = L^-1 (P rhs)\n\t\t\tmatrixL().solveInPlace( result );\n\t\t\t// result = D^-1 (L^-1 P rhs)\n\t\t\tfor( Index i = 0; i < m_matrix.rows(); ++i ) {\n\t\t\t\tresult.row(i) /= m_matrix(i,i) ;\n\t\t\t}\n\t\t\t// result = L^-T (D^-1 L^-1 P rhs)\n\t\t\tmatrixL().transpose().solveInPlace( result ) ;\n\t\t\t// result = P^-1 L^-T (D^-1 L^-1 P rhs)\n\t\t\tresult = m_transpositions.transpose() * result ;\n\t\t\treturn result ;\n\t\t}\n\t\t\n\t\t// \"Half\" solve the rhs\n\t\t// solve the rhs, i.e compute\n\t\t// S^-1 (rhs)\n\t\t// Where S is the 'square root' of the matrix, given by\n\t\t// S = P^-1 L sqrt(D)\n\t\t// such that\n\t\t// S S^t = P^-1 \n\t\tMatrix halfSolve( Matrix const& rhs ) const\n\t\t{\n\t\t\tMatrix result = rhs ;\n\t\t\tassert( result.rows() == m_matrix.rows() ) ;\n\t\t\t// result = P rhs\n\t\t\tresult = m_transpositions * result ;\n\t\t\t// result = L^-1 P rhs\n\t\t\tmatrixL().solveInPlace( result );\n\t\t\t// result = sqrt(D^-1) L^-1 P rhs\n\t\t\tfor( Index i = 0; i < m_matrix.rows(); ++i ) {\n\t\t\t\tresult.row(i) /= std::sqrt( m_matrix(i,i) ) ;\n\t\t\t}\n\t\t\treturn result ;\n\t\t}\n\n\tprivate:\n\t\tMatrix m_matrix ;\n\t\tTranspositions m_transpositions;\n\t\t\n\tprivate:\n\t\t\n\t\tvoid compute_inplace( Matrix& matrix ) {\n\t\t\tassert( matrix.rows() == matrix.cols() ) ;\n\t\t\tm_transpositions.resize( matrix.rows() ) ;\n\t\t\tIndex const size = matrix.rows() ;\n\t\t\t\n#if DEBUG_MODIFIED_CHOLESKY\n\t\t\tstd::cerr << \"ModifiedCholesky::compute_inplace(): computing with matrix:\\n\" << matrix << \".\\n\" ;\n#endif\n\t\t\t\n\t\t\tScalar biggestOnDiagonal ;\n\t\t\tRealScalar betaSquared ;\n\t\t\tRealScalar delta ;\n\n\t\t\tfor( Index j = 0; j < size; ++j ) {\n\t\t\t\t// Find largest diagonal element\n\t\t\t\tIndex indexOfBiggestOnDiagonal ;\n\t\t\t\tbiggestOnDiagonal = matrix.diagonal().tail( size - j ).cwiseAbs().maxCoeff( &indexOfBiggestOnDiagonal ) ;\n\t\t\t\tindexOfBiggestOnDiagonal += j ;\n\n\t\t\t\t// Initialise beta and delta if we are starting.\n\t\t\t\tif( j == 0 ) {\n\t\t\t\t\tScalar biggestOffDiagonal = 0.0 ;\n\t\t\t\t\tfor( Index i = 0; i < size; ++i ) {\n\t\t\t\t\t\tfor( Index j = i+1; j < size; ++j ) {\n\t\t\t\t\t\t\tbiggestOffDiagonal = std::max( biggestOffDiagonal, std::abs( matrix( i, j )) ) ;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t// Had this before:\n\t\t\t\t\t//delta = std::numeric_limits< Scalar >::epsilon() * max( biggestOnDiagonal + biggestOffDiagonal, Scalar( 1 ) ) ;\n\t\t\t\t\t// ..but most authors e.g. (Fang & Leary 2006) say:\n\t\t\t\t\tdelta = std::numeric_limits< Scalar >::epsilon() ;\n\t\t\t\t\t// Fang & Leary (2006), formula (5).\n\t\t\t\t\tbetaSquared = max(\n\t\t\t\t\t\tstd::numeric_limits< Scalar >::epsilon(),\n\t\t\t\t\t\tbiggestOnDiagonal,\n\t\t\t\t\t\tbiggestOffDiagonal / std::sqrt( ( size * size ) - 1 )\n\t\t\t\t\t) ;\n\t\t\t\t\t\n#if DEBUG_MODIFIED_CHOLESKY\n\t\t\t\t\tstd::cerr << \"ModifiedCholesky::compute_inplace(): initialised with delta = \"\n\t\t\t\t\t\t<< delta << \", beta^2 = \" << betaSquared << \".\\n\" ;\n#endif\n\t\t\t\t\n\t\t\t\t\t// Modified cholesky of A is cholesky of A+E for some diagonal matrix E\n\t\t\t\t\t// Bound on elements of E can be computed as in Fang & Leary (2006)\n\t\t\t\t\t//bound = (\n\t\t\t\t\t//\tstd::pow((biggestOffDiagonal/std::sqrt(betaSquared)) + (size-1)*std::sqrt(betaSquared), 2 )\n\t\t\t\t\t//\t+ 2 * ( biggestOnDiagonal + (size-1)*betaSquared )\n\t\t\t\t\t//\t+ std::numeric_limits< Scalar >::epsilon()\n\t\t\t\t\t//) ;\n\t\t\t\t}\n\t\t\t\t\n#if DEBUG_MODIFIED_CHOLESKY\n\t\t\t\tstd::cerr << \"ModifiedCholesky::compute_inplace(): at iteration \"\n\t\t\t\t\t<< j\n\t\t\t\t\t\t<< \": largest entry on diagonal = \" << biggestOnDiagonal\n\t\t\t\t\t<< \" at index \" << indexOfBiggestOnDiagonal << \".\\n\" ;\n#endif\n\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t// Swap rows and columns corresponding to the jth and largest diagonal element.\n\t\t\t\tm_transpositions.coeffRef( j ) = indexOfBiggestOnDiagonal ;\n\t\t\t\tif( j != indexOfBiggestOnDiagonal ) {\n\t\t\t\t\t// indexOfbiggestOnDiagonal is always >= j by construction\n\t\t\t\t\t// we only touch the lower triangular part of the matrix.\n\t\t\t\t\tIndex const tailSize = size - indexOfBiggestOnDiagonal - 1 ;\n\t\t\t\t\tmatrix.row( j ).head( j ).swap( matrix.row( indexOfBiggestOnDiagonal ).head( j ) ) ;\n\t\t\t\t\tmatrix.col( j ).tail( tailSize ).swap( matrix.col( indexOfBiggestOnDiagonal ).tail( tailSize ) ) ;\n\t\t\t\t\tstd::swap( matrix.coeffRef(j,j), matrix.coeffRef( indexOfBiggestOnDiagonal, indexOfBiggestOnDiagonal ) );\n\t\t\t\t\tfor( int i = j+1; i < indexOfBiggestOnDiagonal; ++i ) {\n\t\t\t\t\t\tstd::swap( matrix.coeffRef( i, j ), matrix.coeffRef( indexOfBiggestOnDiagonal, i ) ) ;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tIndex const tailSize = size - j - 1 ;\n\t\t\t\t// We first compute the jth row of L to produce:\n\t\t\t\t// 1: d\n\t\t\t\t// .  l d\n\t\t\t\t// .  l l d\n\t\t\t\t// j: l l l c\n\t\t\t\t// .  c c c a c\n\t\t\t\t// .  c c c a a c\n\t\t\t\t//\n\t\t\t\t// by formula: l_js = c_js / d_s for s = 0,...,j-1.\n\t\t\t\tif( j > 0 ) {\n\t\t\t\t\tmatrix.row(j).head( j ).array() /= matrix.diagonal().head( j ).array() ;\n\t\t\t\t}\n#if DEBUG_MODIFIED_CHOLESKY\n\t\t\t\tstd::cerr << \"ModifiedCholesky::compute_inplace(): after computing ls, matrix =\\n\"\n\t\t\t\t\t<< matrix << \".\\n\" ;\n#endif\n\t\t\t\t// We next compute jth column of c_ijs to get:\n\t\t\t\t// 1: d\n\t\t\t\t// .  l d\n\t\t\t\t// .  l l d\n\t\t\t\t// j: l l l c\n\t\t\t\t// .  c c c c c\n\t\t\t\t// .  c c c c a c\n\t\t\t\t//\n\t\t\t\t// by formula c_ij = a_ij - sum_s l_ks c_is for s=j+1...n\n\t\t\t\tfor( Index i = j+1; i < size; ++i ) {\n\t\t\t\t\tmatrix(i,j) -= ( matrix.row( j ).head( j ) * matrix.row( i ).head( j ).transpose() ) ;\n\t\t\t\t}\n\t\t\t\tScalar const theta = ( (j+1) == size ) ? 0.0 : ( matrix.col( j ).tail( tailSize ).maxCoeff() ) ;\n#if DEBUG_MODIFIED_CHOLESKY\n\t\t\t\tstd::cerr << \"ModifiedCholesky::compute_inplace(): after computing cs, matrix =\\n\"\n\t\t\t\t\t<< matrix << \",\\n\"\n\t\t\t\t\t<< \"theta = \" << theta << \".\\n\" ;\n#endif\n\n\t\t\t\t// compute d_jj to produce\n\t\t\t\t// 1: d\n\t\t\t\t// .  l d\n\t\t\t\t// .  l l d\n\t\t\t\t// j: l l l d\n\t\t\t\t// .  c c c c c\n\t\t\t\t// .  c c c c a c\n\t\t\t\tdouble new_dj = max(\n\t\t\t\t\tdelta,\n\t\t\t\t\tstd::abs( matrix(j,j) ),\n\t\t\t\t\t(theta*theta) / betaSquared\n\t\t\t\t) ;\n\t\t\t\tmatrix(j,j) = new_dj ;\n\t\t\t\t//\n\t\t\t\t// Finally update the c_ii's\n\t\t\t\tmatrix.diagonal().tail( tailSize ).array() -= ( matrix.col(j).tail( tailSize ).array().square() ) / matrix(j,j) ;\n\t\t\t\t\n#if DEBUG_MODIFIED_CHOLESKY\n\t\t\t\tstd::cerr << \"ModifiedCholesky::compute_inplace(): after iteration \" << j << \", matrix is:\\n\"\n\t\t\t\t\t<< matrix << \".\\n\" ;\n#endif\n\t\t\t}\n\t\t}\n\t} ;\n}\n\n#endif\n", "meta": {"hexsha": "18e82795bcc6df2f3107de699699091b430beb69", "size": 9874, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "metro/include/metro/ModifiedCholesky.hpp", "max_stars_repo_name": "gavinband/qctool", "max_stars_repo_head_hexsha": "8d8adb45151c91f953fe4a9af00498073b1132ba", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-04-21T05:42:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T14:59:43.000Z", "max_issues_repo_path": "metro/include/metro/ModifiedCholesky.hpp", "max_issues_repo_name": "gavinband/qctool", "max_issues_repo_head_hexsha": "8d8adb45151c91f953fe4a9af00498073b1132ba", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-09T16:11:04.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-10T11:18:56.000Z", "max_forks_repo_path": "metro/include/metro/ModifiedCholesky.hpp", "max_forks_repo_name": "gavinband/qctool", "max_forks_repo_head_hexsha": "8d8adb45151c91f953fe4a9af00498073b1132ba", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5874587459, "max_line_length": 132, "alphanum_fraction": 0.6244683006, "num_tokens": 3055, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743168019989179, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.48931483519985147}}
{"text": "/* mexcpp_test.cpp -- Test mexcpp library\n *\n * Copyright (c) 2013-5 Kui Tang <kuitang@gmail.com>\n * License: MIT\n *\n * Inspired by Rcpp and nr3matlab.h\n *\n * Run this line in MATLAB:\n * [od, os, ocm, osm] = mexcpp_test(3, 'c', 'string', [1 2 3], single([1 2; 3 4]), {[1 2], [1 2; 3 4]}, struct('f0', [10 20; 30 40], 'f1', 52, 'f2', int32(99), 'f3', 'blahblah'))\n */\n\n#include \"mexcpp.h\"\n#include <string>\n\n#ifdef HAVE_EIGEN\n#include <Eigen/Dense>\n#include <sstream>\n#endif\n\nenum {\n  iDouble,\n  iChar,\n  iStr,\n  iDoubleVector,\n  iSingleMatrix,\n  iCellMat,\n  iStructMat,\n  nI\n};\n\nenum {\n  oDoubleMatrix,\n  oString,\n  oCellMat,\n  oStructMat,\n  nO\n};\n\nusing namespace mexcpp;\n\n// test pointer overloading\nvoid printPointerArray(int n, double *p) {\n  for (int i = 0; i < n; i++) {\n    mexPrintf(\"printPointerArray: p[%d] = %g\\n\", i, p[i]);\n  }\n}\n\nvoid mexFunction(int nOut, mxArray *pOut[], int nIn, const mxArray *pIn[]) {\n  if (nIn != nI || nOut != nO) {\n    mexErrMsgIdAndTxt(\"mexcpp_test:nIn\", \"Usage: mexcpp_test(double, char, doubleVec, singleMat, cellMat, structMat)\", nI);\n  }\n\n  double d = scalar<double>(pIn[iDouble]);\n  mexPrintf(\"Double scalar read; d = %g\\n\", d);\n\n  char c = scalar<char>(pIn[iChar]);\n  mexPrintf(\"Char scalar read; c = %c\\n\", c);\n\n  std::string s = scalar<std::string>(pIn[iStr]);\n  mexPrintf(\"String scalar read; s = %s\\n\", s.c_str());\n\n  Mat<double> dv(pIn[iDoubleVector]);\n  mexPrintf(\"Double vector read; N = %d, M = %d, end = %g\\n\", dv.N, dv.M, dv[dv.length - 1]);\n\n  printPointerArray(dv.length, dv);\n\n  Mat<float> m(pIn[iSingleMatrix]);\n  mexPrintf(\"Single matrix read; N = %d, M = %d, end = %g\\n\", m.N, m.M, m(m.N - 1, m.M - 1));\n\n#ifdef HAVE_EIGEN\n  std::stringstream ss;\n  const Mat<float>::EigenMap mEigenMap(m.asEigenMap());\n  ss << \"mEigenMap contents: \\n\" << mEigenMap << \"\\n\";\n  mexPrintf(ss.str().c_str());\n  ss.str(\"\");\n\n  Mat<float>::EigenMatrix mEigenMat(m.asEigenMatrix());\n  ss << \"mEigenMatrix contents: \\n\" << mEigenMap << \"\\n\";\n  mexPrintf(ss.str().c_str());\n  ss.str() = \"\";\n\n#endif\n\n  CellMat<Mat<double> > cm(pIn[iCellMat]);\n  mexPrintf(\"Cell matrix read; N = %d, M = %d\\n\", cm.N, cm.M);\n\n  for (int i = 0; i < cm.length; i++) {\n    mexPrintf(\"Entry %d was %d x %d matrix\\n\", i, cm[i].N, cm[i].M);\n  }\n\n  StructMat sm(pIn[iStructMat]);\n  mexPrintf(\"Structure matrix read; N = %d, M = %d, nFields = %d\\n\", sm.N, sm.M, sm.nFields);\n  for (int i = 0; i < sm.length; i++) {\n    Mat<double> f0 = sm[i].get<Mat<double> >(\"f0\");\n    double      f1 = sm[i].getS<double>(\"f1\");\n    int32_t     f2 = sm[i].getS<int32_t>(\"f2\");\n    std::string f3 = sm[i].getS<std::string>(\"f3\");\n    mexPrintf(\"Entry %d had f0 = [%d x %d] f1 = %g f2 = %d f3 = %s\\n\", i, f0.N, f0.M, f1, f2, f3.c_str());\n  }\n\n  pOut[oString] = scalar<std::string>(\"String output\");\n\n  // Making stuff\n  Mat<double> om(2,2);\n  om(0,0) = 1;\n  om(0,1) = 2;\n  om(1,0) = 3;\n  om(1,1) = 4;\n  pOut[oDoubleMatrix] = om;\n  mexPrintf(\"Double matrix output created.\\n\");\n\n#ifdef HAVE_EIGEN\n  Mat<double>::EigenMap omEigenMap(om.asEigenMap());\n  omEigenMap(0,0) += 0.1;\n  mexPrintf(\"Created (nonconst) EigenMap on output matrix and manipulated it.\");\n#endif\n\n  CellMat<Mat<double> > ocm(1,2);\n  ocm.setS(0, 5.1);\n  ocm.set(1, Mat<double>(3, 3));\n  pOut[oCellMat] = ocm;\n  mexPrintf(\"Cell matrix output created.\\n\");\n  pOut[oCellMat] = ocm;\n\n  // No C++11 features\n  std::vector<std::string> fns;\n  fns.push_back(\"bar\");\n  fns.push_back(\"quuz\");\n  StructMat osm(2, 1, fns);\n  osm[0].set(\"bar\", Mat<double>(3,3));\n  osm[0].setS(\"quuz\", 1);\n  osm[1].set(0, Mat<double>(2,2));\n  osm[1].setS(1, 2);\n  pOut[oStructMat] = osm;\n  mexPrintf(\"Struct matrix output created.\\n\");\n\n  mexPrintf(\"All done!\\n\");\n}\n", "meta": {"hexsha": "36d31629e56568e1c277a79c3247503aa02272f2", "size": 3696, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mexcpp_test.cpp", "max_stars_repo_name": "kuitang/mexcpp", "max_stars_repo_head_hexsha": "2dc11d7932ca10eda960d69a3176651bf4b2e716", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2015-01-12T08:45:41.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-01T16:16:46.000Z", "max_issues_repo_path": "mexcpp_test.cpp", "max_issues_repo_name": "kuitang/mexcpp", "max_issues_repo_head_hexsha": "2dc11d7932ca10eda960d69a3176651bf4b2e716", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-01-11T11:21:39.000Z", "max_issues_repo_issues_event_max_datetime": "2016-05-06T15:09:05.000Z", "max_forks_repo_path": "mexcpp_test.cpp", "max_forks_repo_name": "kuitang/mexcpp", "max_forks_repo_head_hexsha": "2dc11d7932ca10eda960d69a3176651bf4b2e716", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2015-01-14T14:54:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-27T15:18:06.000Z", "avg_line_length": 26.5899280576, "max_line_length": 178, "alphanum_fraction": 0.6022727273, "num_tokens": 1361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.6584175072643415, "lm_q1q2_score": 0.48931482770923446}}
{"text": "// Copyright (C) 2006  Davis E. King (davis@dlib.net)\n// License: Boost Software License   See LICENSE.txt for the full license.\n\n\n#include <dlib/matrix.h>\n#include <sstream>\n#include <string>\n#include <cstdlib>\n#include <ctime>\n#include <vector>\n#include \"../stl_checked.h\"\n#include \"../array.h\"\n#include \"../rand.h\"\n\n#include \"tester.h\"\n#include <dlib/memory_manager_stateless.h>\n#include <dlib/array2d.h>\n\nnamespace  \n{\n\n    using namespace test;\n    using namespace dlib;\n    using namespace std;\n\n    logger dlog(\"test.matrix2\");\n\n    dlib::rand rnd;\n\n    void matrix_test (\n    )\n    /*!\n        ensures\n            - runs tests on the matrix stuff compliance with the specs\n    !*/\n    {        \n        typedef memory_manager_stateless<char>::kernel_2_2a MM;\n        print_spinner();\n\n        const double ident[] = {\n            1, 0, 0, 0,\n            0, 1, 0, 0,\n            0, 0, 1, 0,\n            0, 0, 0, 1 };\n\n        const double uniform3[] = {\n            3, 3, 3, 3,\n            3, 3, 3, 3,\n            3, 3, 3, 3,\n            3, 3, 3, 3 \n        };\n\n        const double uniform1[] = {\n            1, 1, 1, 1,\n            1, 1, 1, 1,\n            1, 1, 1, 1,\n            1, 1, 1, 1 \n        };\n\n        const double uniform0[] = {\n            0, 0, 0, 0,\n            0, 0, 0, 0,\n            0, 0, 0, 0,\n            0, 0, 0, 0 \n        };\n\n        const int array[] = {\n            42, 58, 9, 1,\n            9, 5, 8, 2,\n            98, 28, 4, 77, \n            9, 2, 44, 88 };\n\n        const int array2[] = {\n            1, 22, 3,\n            4, 52, 6,\n            7, 8, 9 };\n\n        const int array2_r[] = {\n            52, 6, 4,\n            8, 9, 7,\n            22, 3, 1\n        };\n\n        const double array_f[] = {\n            -0.99, \n            0.99};\n\n\n        matrix<double,2,1,MM> fm(array_f);\n\n        DLIB_TEST(fm.size() == 2);\n        matrix<double> dfm(fm);\n        DLIB_TEST(round(fm)(0) == -1);\n        DLIB_TEST(round(fm)(1) == 1);\n        DLIB_TEST(round(dfm)(0) == -1);\n        DLIB_TEST(round(dfm)(1) == 1);\n        DLIB_TEST(round(dfm).size() == dfm.size());\n\n\n        const int array3[] = { 1, 2, 3, 4 };\n\n        matrix<double,3,3,MM> m3(array2);\n        matrix<double> dm3;\n        DLIB_TEST(dm3.size() == 0);\n        DLIB_TEST(dm3.nr() == 0);\n        DLIB_TEST(dm3.nc() == 0);\n        dm3.set_size(3,4);\n        DLIB_TEST(dm3.nr() == 3);\n        DLIB_TEST(dm3.nc() == 4);\n        DLIB_TEST(dm3.size() == 3*4);\n        dm3.set_size(3,3);\n        DLIB_TEST(dm3.nr() == 3);\n        DLIB_TEST(dm3.nc() == 3);\n        dm3 = m3;\n        dm3(0,0)++;\n        DLIB_TEST( dm3 != m3);\n        dm3 = m3;\n        DLIB_TEST( dm3 == m3);\n        DLIB_TEST( abs(sum(squared(normalize(dm3))) - 1.0) < 1e-10);\n\n        matrix<double,3,4> mrc;\n        mrc.set_size(3,4);\n\n        set_all_elements(mrc,1);\n\n        DLIB_TEST(diag(mrc) == uniform_matrix<double>(3,1,1));\n        DLIB_TEST(diag(matrix<double>(mrc)) == uniform_matrix<double>(3,1,1));\n\n        matrix<double,2,3> mrc2;\n        set_all_elements(mrc2,1);\n        DLIB_TEST((removerc<1,1>(mrc) == mrc2));\n        DLIB_TEST((removerc(mrc,1,1) == mrc2));\n\n        matrix<int,3,3> m4, m5, m6;\n        set_all_elements(m4, 4);\n        set_all_elements(m5, 4);\n        set_all_elements(m6, 1);\n\n        DLIB_TEST(squared(m4) == pointwise_multiply(m4,m4));\n        DLIB_TEST(cubed(m4) == pointwise_multiply(m4,m4,m4));\n        DLIB_TEST(pow(matrix_cast<double>(m4),2) == squared(matrix_cast<double>(m4)));\n        DLIB_TEST(pow(matrix_cast<double>(m4),3) == cubed(matrix_cast<double>(m4)));\n\n        matrix<int> dm4;\n        matrix<int,0,0,memory_manager_stateless<char>::kernel_2_2a> dm5;\n        dm4 = dm4;\n        dm4 = dm5;\n        DLIB_TEST(dm4.nr() == 0);\n        dm4 = m4;\n        dm5 = m5;\n        DLIB_TEST(dm4 == dm5);\n\n\n        DLIB_TEST(m4 == m5);\n        DLIB_TEST(m6 != m5);\n        m4.swap(m6);\n        DLIB_TEST(m6 == m5);\n        DLIB_TEST(m4 != m5);\n\n        DLIB_TEST(m3.nr() == 3);\n        DLIB_TEST(m3.nc() == 3);\n\n        matrix<double,4,1> v(array3), v2;\n        DLIB_TEST(v.nr() == 4);\n        DLIB_TEST(v.nc() == 1);\n\n        std::vector<double> stdv(4);\n        std_vector_c<double> stdv_c(4);\n        dlib::array<double> arr;\n        arr.resize(4);\n        for (long i = 0; i < 4; ++i)\n            stdv[i] = stdv_c[i] = arr[i] = i+1;\n\n        DLIB_TEST(mat(stdv)(0) == 1);\n        DLIB_TEST(mat(stdv)(1) == 2);\n        DLIB_TEST(mat(stdv)(2) == 3);\n        DLIB_TEST(mat(stdv)(3) == 4);\n        DLIB_TEST(mat(stdv).nr() == 4);\n        DLIB_TEST(mat(stdv).nc() == 1);\n        DLIB_TEST(mat(stdv).size() == 4);\n        DLIB_TEST(equal(trans(mat(stdv))*mat(stdv), trans(v)*v));\n        DLIB_TEST(equal(trans(mat(stdv))*mat(stdv), tmp(trans(v)*v)));\n\n        DLIB_TEST(mat(stdv_c)(0) == 1);\n        DLIB_TEST(mat(stdv_c)(1) == 2);\n        DLIB_TEST(mat(stdv_c)(2) == 3);\n        DLIB_TEST(mat(stdv_c)(3) == 4);\n        DLIB_TEST(mat(stdv_c).nr() == 4);\n        DLIB_TEST(mat(stdv_c).nc() == 1);\n        DLIB_TEST(mat(stdv_c).size() == 4);\n        DLIB_TEST(equal(trans(mat(stdv_c))*mat(stdv_c), trans(v)*v));\n\n        DLIB_TEST(mat(arr)(0) == 1);\n        DLIB_TEST(mat(arr)(1) == 2);\n        DLIB_TEST(mat(arr)(2) == 3);\n        DLIB_TEST(mat(arr)(3) == 4);\n        DLIB_TEST(mat(arr).nr() == 4);\n        DLIB_TEST(mat(arr).nc() == 1);\n        DLIB_TEST(mat(arr).size() == 4);\n        DLIB_TEST(equal(trans(mat(arr))*mat(arr), trans(v)*v));\n\n        DLIB_TEST(v(0) == 1);\n        DLIB_TEST(v(1) == 2);\n        DLIB_TEST(v(2) == 3);\n        DLIB_TEST(v(3) == 4);\n        matrix<double> dv = v;\n        DLIB_TEST((trans(v)*v).size() == 1);\n        DLIB_TEST((trans(v)*v).nr() == 1);\n        DLIB_TEST((trans(v)*dv).nr() == 1);\n        DLIB_TEST((trans(dv)*dv).nr() == 1);\n        DLIB_TEST((trans(dv)*v).nr() == 1);\n        DLIB_TEST((trans(v)*v).nc() == 1);\n        DLIB_TEST((trans(v)*dv).nc() == 1);\n        DLIB_TEST((trans(dv)*dv).nc() == 1);\n        DLIB_TEST((trans(dv)*v).nc() == 1);\n        DLIB_TEST((trans(v)*v)(0) == 1*1 + 2*2 + 3*3 + 4*4);\n        DLIB_TEST((trans(dv)*v)(0) == 1*1 + 2*2 + 3*3 + 4*4);\n        DLIB_TEST((trans(dv)*dv)(0) == 1*1 + 2*2 + 3*3 + 4*4);\n        DLIB_TEST((trans(v)*dv)(0) == 1*1 + 2*2 + 3*3 + 4*4);\n\n        dv = trans(dv)*v;\n        DLIB_TEST(dv.nr() == 1);\n        DLIB_TEST(dv.nc() == 1);\n\n        dm3 = m3;\n        DLIB_TEST(floor(det(m3)+0.01) == -444);\n        DLIB_TEST(floor(det(dm3)+0.01) == -444);\n        DLIB_TEST(min(m3) == 1);\n        DLIB_TEST(min(dm3) == 1);\n        DLIB_TEST(max(m3) == 52);\n        DLIB_TEST(max(dm3) == 52);\n        DLIB_TEST(sum(m3) == 112);\n        DLIB_TEST(sum(dm3) == 112);\n        DLIB_TEST(prod(m3) == 41513472);\n        DLIB_TEST(prod(dm3) == 41513472);\n        DLIB_TEST(prod(diag(m3)) == 1*52*9);\n        DLIB_TEST(prod(diag(dm3)) == 1*52*9);\n        DLIB_TEST(sum(diag(m3)) == 1+52+9);\n        DLIB_TEST(sum(diag(dm3)) == 1+52+9);\n        DLIB_TEST(equal(round(10000*m3*inv(m3))/10000 , identity_matrix<double,3>()));\n        DLIB_TEST(equal(round(10000*dm3*inv(m3))/10000 , identity_matrix<double,3>()));\n        DLIB_TEST(equal(round(10000*dm3*inv(dm3))/10000 , identity_matrix<double,3>()));\n        DLIB_TEST(equal(round(10000*m3*inv(dm3))/10000 , identity_matrix<double,3>()));\n        DLIB_TEST(equal(round(10000*tmp(m3*inv(m3)))/10000 , identity_matrix<double,3>()));\n        DLIB_TEST(equal(round(10000*tmp(dm3*inv(m3)))/10000 , identity_matrix<double,3>()));\n        DLIB_TEST(equal(round(10000*tmp(dm3*inv(dm3)))/10000 , identity_matrix<double,3>()));\n        DLIB_TEST(equal(round(10000*tmp(m3*inv(dm3)))/10000 , identity_matrix<double,3>()));\n        DLIB_TEST(-1*m3 == -m3);\n        DLIB_TEST(-1*dm3 == -m3);\n        DLIB_TEST(-1*m3 == -dm3);\n        DLIB_TEST(-1*dm3 == -dm3);\n\n        DLIB_TEST(m3 == dm3);\n        m3(1,1) = 99;\n        DLIB_TEST(m3 != dm3);\n        m3 = dm3;\n        DLIB_TEST(m3 == dm3);\n\n        matrix<double,4,4,MM> mident(ident);\n        matrix<double,4,4> muniform0(uniform0);\n        matrix<double,4,4> muniform1(uniform1);\n        matrix<double,4,4> muniform3(uniform3);\n        matrix<double,4,4> m1(array), m2;\n        DLIB_TEST(m1.nr() == 4);\n        DLIB_TEST(m1.nc() == 4);\n\n        DLIB_TEST(muniform1 + muniform1 + muniform1 == muniform3);\n        DLIB_TEST(muniform1*2 + muniform1 + muniform1 - muniform1 == muniform3);\n        DLIB_TEST(2*muniform1 + muniform1 + muniform1 - muniform1 == muniform3);\n        DLIB_TEST(muniform1 + muniform1 + muniform1 - muniform3 == muniform0);\n        DLIB_TEST(equal(muniform3/3 , muniform1));\n        DLIB_TEST(v != m1);\n        DLIB_TEST(v == v);\n        DLIB_TEST(m1 == m1);\n\n        muniform0.swap(muniform1);\n        DLIB_TEST((muniform1 == matrix_cast<double>(uniform_matrix<long,4,4,0>())));\n        DLIB_TEST((muniform0 == matrix_cast<double>(uniform_matrix<long,4,4,1>())));\n        DLIB_TEST((muniform1 == matrix_cast<double>(uniform_matrix<long>(4,4,0))));\n        DLIB_TEST((muniform0 == matrix_cast<double>(uniform_matrix<long>(4,4,1))));\n        swap(muniform0,muniform1);\n\n        DLIB_TEST((mident == identity_matrix<double,4>()));\n        DLIB_TEST((muniform0 == matrix_cast<double>(uniform_matrix<long,4,4,0>())));\n        DLIB_TEST((muniform1 == matrix_cast<double>(uniform_matrix<long,4,4,1>())));\n        DLIB_TEST((muniform3 == matrix_cast<double>(uniform_matrix<long,4,4,3>())));\n        DLIB_TEST((muniform1*8 == matrix_cast<double>(uniform_matrix<long,4,4,8>())));\n\n        set_all_elements(m2,7);\n        DLIB_TEST(m2 == muniform1*7);\n        m2 = array;\n        DLIB_TEST(m2 == m1);\n\n        const double m1inv[] = {\n            -0.00946427624, 0.0593272941,  0.00970564379,  -0.00973323731, \n            0.0249312057,   -0.0590122427, -0.00583102756, 0.00616002729, \n            -0.00575431149, 0.110081189,   -0.00806792253, 0.00462297692, \n            0.00327847478,  -0.0597669712, 0.00317386196,  0.00990759201 \n        };\n\n        m2 = m1inv;\n        DLIB_TEST((round(m2*m1) == identity_matrix<double,4>()));\n        DLIB_TEST((round(tmp(m2*m1)) == identity_matrix<double,4>()));\n\n        DLIB_TEST_MSG(round(m2*10000) == round(inv(m1)*10000),\n                     round(m2*10000) - round(inv(m1)*10000)\n                     << \"\\n\\n\" << round(m2*10000)\n                     << \"\\n\\n\" << round(inv(m1)*10000)\n                     << \"\\n\\n\" << m2 \n                     << \"\\n\\n\" << inv(m1) \n                     );\n        DLIB_TEST(m1 == abs(-1*m1));\n        DLIB_TEST(abs(m2) == abs(-1*m2));\n\n        DLIB_TEST_MSG(floor(det(m1)+0.01) == 3297875,\"\\nm1: \\n\" << m1 << \"\\ndet(m1): \" << det(m1));\n\n\n        ostringstream sout;\n        m1 = m2;\n        serialize(m1,sout);\n        set_all_elements(m1,0);\n        istringstream sin(sout.str());\n        deserialize(m1,sin);\n        DLIB_TEST_MSG(round(100000*m1) == round(100000*m2),\"m1: \\n\" << m1 << endl << \"m2: \\n\" << m2);\n\n\n        set_all_elements(v,2);\n        v2 =  pointwise_multiply(v, v*2);\n        set_all_elements(v,8);\n        DLIB_TEST(v == v2);\n        DLIB_TEST(v == tmp(v2));\n        DLIB_TEST((v == rotate<2,0>(v))); \n\n        m4 = array2;\n        m5 = array2_r;\n        DLIB_TEST((m5 == rotate<1,1>(m4)));\n\n        m5 = array2;\n        DLIB_TEST((m5*2 == pointwise_multiply(m5,uniform_matrix<int,3,3,2>())));\n        DLIB_TEST((tmp(m5*2) == tmp(pointwise_multiply(m5,uniform_matrix<int,3,3,2>()))));\n\n        v = tmp(v);\n\n\n\n\n        matrix<double> dm10(10,5);\n        DLIB_TEST(dm10.nr() == 10);\n        DLIB_TEST(dm10.nc() == 5);\n        set_all_elements(dm10,4);\n        DLIB_TEST(dm10.nr() == 10);\n        DLIB_TEST(dm10.nc() == 5);\n        matrix<double,10,5> m10;\n        DLIB_TEST(m10.nr() == 10);\n        DLIB_TEST(m10.nc() == 5);\n        set_all_elements(m10,4);\n        DLIB_TEST(dm10 == m10);\n        DLIB_TEST((clamp<0,3>(dm10) == clamp<0,3>(m10)));\n        DLIB_TEST((clamp<0,3>(dm10)(0,2) == 3));\n\n        set_all_elements(dm10,1);\n        set_all_elements(m10,4);\n        DLIB_TEST(4*dm10 == m10);\n        DLIB_TEST(5*dm10 - dm10 == m10);\n        DLIB_TEST((16*dm10)/4 == m10);\n        DLIB_TEST(dm10+dm10+2*dm10 == m10);\n        DLIB_TEST(dm10+tmp(dm10+2*dm10) == m10);\n        set_all_elements(dm10,4);\n        DLIB_TEST(dm10 == m10);\n        DLIB_TEST_MSG(sum(abs(sigmoid(dm10) -sigmoid(m10))) < 1e-10,sum(abs(sigmoid(dm10) -sigmoid(m10))) );\n\n        {\n            matrix<double,2,1> x, l, u, out;\n            x = 3,4;\n\n            l = 1,1;\n            u = 2,2.2;\n\n            out = 2, 2.2;\n            DLIB_TEST(equal(clamp(x, l, u) , out));\n            out = 3, 2.2;\n            DLIB_TEST(!equal(clamp(x, l, u) , out));\n            out = 2, 4.2;\n            DLIB_TEST(!equal(clamp(x, l, u) , out));\n\n            x = 1.5, 1.5;\n            out = x;\n            DLIB_TEST(equal(clamp(x, l, u) , out));\n\n            x = 0.5, 1.5;\n            out = 1, 1.5;\n            DLIB_TEST(equal(clamp(x, l, u) , out));\n\n            x = 1.5, 0.5;\n            out = 1.5, 1.0;\n            DLIB_TEST(equal(clamp(x, l, u) , out));\n\n        }\n\n        matrix<double, 7, 7,MM,column_major_layout> m7;\n        matrix<double> dm7(7,7);\n        dm7 = randm(7,7, rnd);\n        m7 = dm7;\n\n        DLIB_TEST_MSG(max(abs(dm7*inv(dm7) - identity_matrix<double>(7))) < 1e-12, max(abs(dm7*inv(dm7) - identity_matrix<double>(7))));\n        DLIB_TEST(equal(inv(dm7),  inv(m7)));\n        DLIB_TEST(abs(det(dm7) - det(m7)) < 1e-14);\n        DLIB_TEST(abs(min(dm7) - min(m7)) < 1e-14);\n        DLIB_TEST(abs(max(dm7) - max(m7)) < 1e-14);\n        DLIB_TEST_MSG(abs(sum(dm7) - sum(m7)) < 1e-14,sum(dm7) - sum(m7));\n        DLIB_TEST(abs(prod(dm7) -prod(m7)) < 1e-14);\n        DLIB_TEST(equal(diag(dm7) , diag(m7)));\n        DLIB_TEST(equal(trans(dm7) , trans(m7)));\n        DLIB_TEST(equal(abs(dm7) , abs(m7)));\n        DLIB_TEST(equal(round(dm7) , round(m7)));\n        DLIB_TEST(matrix_cast<int>(dm7) == matrix_cast<int>(m7));\n        DLIB_TEST((rotate<2,3>(dm7) == rotate<2,3>(m7)));\n        DLIB_TEST((sum(pointwise_multiply(dm7,dm7) - pointwise_multiply(m7,m7))) < 1e-10);\n        DLIB_TEST((sum(pointwise_multiply(dm7,dm7,dm7) - pointwise_multiply(m7,m7,m7))) < 1e-10);\n        DLIB_TEST_MSG((sum(pointwise_multiply(dm7,dm7,dm7,dm7) - pointwise_multiply(m7,m7,m7,m7))) < 1e-10,\n                     (sum(pointwise_multiply(dm7,dm7,dm7,dm7) - pointwise_multiply(m7,m7,m7,m7)))\n        );\n\n\n        matrix<double> temp(5,5);\n        matrix<double> dsm(5,5);\n        matrix<double,5,5,MM> sm;\n\n        set_all_elements(dsm,1);\n        set_all_elements(sm,1);\n        set_all_elements(temp,1);\n\n        dsm += dsm;\n        sm += sm;\n        DLIB_TEST(dsm == 2*temp);\n        DLIB_TEST(sm == 2*temp);\n        temp = dsm*sm + dsm;\n        dsm += dsm*sm;\n        DLIB_TEST_MSG(temp == dsm,temp - dsm);\n\n        set_all_elements(dsm,1);\n        set_all_elements(sm,1);\n        set_all_elements(temp,1);\n\n        dsm += dsm;\n        sm += sm;\n        DLIB_TEST(dsm == 2*temp);\n        DLIB_TEST(sm == 2*temp);\n        temp = dsm*sm + dsm;\n        sm += dsm*sm;\n        DLIB_TEST_MSG(temp == sm,temp - sm);\n\n        set_all_elements(dsm,1);\n        set_all_elements(sm,1);\n        set_all_elements(temp,1);\n\n        dsm += dsm;\n        sm += sm;\n        DLIB_TEST(dsm == 2*temp);\n        DLIB_TEST(sm == 2*temp);\n        temp = sm - dsm*sm ;\n        sm -= dsm*sm;\n        DLIB_TEST_MSG(temp == sm,temp - sm);\n\n        set_all_elements(dsm,1);\n        set_all_elements(sm,1);\n        set_all_elements(temp,1);\n\n        dsm += dsm;\n        sm += sm;\n        DLIB_TEST(dsm == 2*temp);\n        DLIB_TEST(sm == 2*temp);\n        temp = dsm - dsm*sm ;\n        dsm -= dsm*sm;\n        DLIB_TEST_MSG(temp == dsm,temp - dsm);\n\n        set_all_elements(dsm,1);\n        set_all_elements(sm,1);\n        set_all_elements(temp,2);\n\n        dsm *= 2;\n        sm *= 2;\n        DLIB_TEST(dsm == temp);\n        DLIB_TEST(sm == temp);\n        dsm /= 2;\n        sm /= 2;\n        DLIB_TEST(dsm == temp/2);\n        DLIB_TEST(sm == temp/2);\n\n        dsm += dsm;\n        sm += sm;\n        DLIB_TEST(dsm == temp);\n        DLIB_TEST(sm == temp);\n        dsm += sm;\n        sm += dsm;\n        DLIB_TEST(dsm == 2*temp);\n        DLIB_TEST(sm == temp*3);\n        dsm -= sm;\n        sm -= dsm;\n        DLIB_TEST(dsm == -temp);\n        DLIB_TEST(sm == 4*temp);\n        sm -= sm;\n        dsm -= dsm;\n        DLIB_TEST(dsm == 0*temp);\n        DLIB_TEST(sm == 0*temp);\n\n        set_all_elements(dsm,1);\n        set_all_elements(sm,1);\n        set_all_elements(temp,3);\n        dsm += sm+sm;\n        DLIB_TEST(dsm == temp);\n\n        set_all_elements(dsm,1);\n        set_all_elements(sm,1);\n        set_all_elements(temp,-1);\n        dsm -= sm+sm;\n        DLIB_TEST(dsm == temp);\n\n        set_all_elements(dsm,1);\n        set_all_elements(sm,1);\n        set_all_elements(temp,-1);\n        sm -= dsm+dsm;\n        DLIB_TEST(sm == temp);\n\n        set_all_elements(dsm,1);\n        set_all_elements(sm,1);\n        set_all_elements(temp,3);\n        sm += dsm+dsm;\n        DLIB_TEST(sm == temp);\n\n\n\n        // test the implicit conversion to bool stuff\n        {\n            matrix<float> bt1(3,1);\n            matrix<float,3,1> bt2;\n            set_all_elements(bt1,2);\n            set_all_elements(bt2,3);\n\n\t\t\tfloat val = trans(bt1)*bt2;\n            DLIB_TEST((float)(trans(bt1)*bt2) == 18);\n            DLIB_TEST((float)(trans(bt1)*bt2) != 19);\n\t\t\tDLIB_TEST(val == 18);\n        }\n        {\n            matrix<float,3,1> bt1;\n            matrix<float> bt2(3,1);\n            set_all_elements(bt1,2);\n            set_all_elements(bt2,3);\n\n\t\t\tfloat val = trans(bt1)*bt2;\n            DLIB_TEST((float)(trans(bt1)*bt2) == 18);\n            DLIB_TEST((float)(trans(bt1)*bt2) != 19);\n\t\t\tDLIB_TEST(val == 18);\n        }\n        {\n            matrix<float> bt1(3,1);\n            matrix<float> bt2(3,1);\n            set_all_elements(bt1,2);\n            set_all_elements(bt2,3);\n\n\t\t\tfloat val = trans(bt1)*bt2;\n            DLIB_TEST((float)(trans(bt1)*bt2) == 18);\n            DLIB_TEST((float)(trans(bt1)*bt2) != 19);\n\t\t\tDLIB_TEST(val == 18);\n        }\n        {\n            matrix<float,3,1> bt1;\n            matrix<float,3,1> bt2;\n            set_all_elements(bt1,2);\n            set_all_elements(bt2,3);\n\n\t\t\tfloat val = trans(bt1)*bt2;\n            DLIB_TEST((float)(trans(bt1)*bt2) == 18);\n            DLIB_TEST((float)(trans(bt1)*bt2) != 19);\n\t\t\tDLIB_TEST(val == 18);\n        }\n\n\n\n\n        {\n            srand(423452);\n            const long M = 50;\n            const long N = 40;\n\n            matrix<double> a(M,N);  \n            for (long r = 0; r < a.nr(); ++r)\n            {\n                for (long c = 0; c < a.nc(); ++c)\n                {\n                    a(r,c) = 10*((double)::rand())/RAND_MAX;\n                }\n            }\n\n            matrix<double> u, u2;  \n            matrix<double> q, q2;\n            matrix<double> v, v2;\n\n            matrix<double> a2;  \n            a2 = tmp(a/2);\n\n\n            svd2(true,true,a2+a2,u,q,v);\n\n            double err = max(abs(a - subm(u,get_rect(a2+a2))*diagm(q)*trans(v)));\n            DLIB_TEST_MSG( err < 1e-11,\"err: \" << err);\n            using dlib::equal;\n            DLIB_TEST((equal(trans(u)*u , identity_matrix<double,M>(), 1e-10)));\n            DLIB_TEST((equal(trans(v)*v , identity_matrix<double,N>(), 1e-10)));\n\n            svd2(false,true,a2+a2,u,q,v2);\n            svd2(true,false,a2+a2,u2,q,v);\n            svd2(false,false,a2+a2,u,q2,v);\n\n            err = max(abs(a - subm(u2,get_rect(a2+a2))*diagm(q2)*trans(v2)));\n            DLIB_TEST_MSG( err < 1e-11,\"err: \" << err);\n            DLIB_TEST((equal(trans(u2)*u2 , identity_matrix<double,M>(), 1e-10)));\n            DLIB_TEST((equal(trans(v2)*v2 , identity_matrix<double,N>(), 1e-10)));\n\n        }\n\n\n        {\n            srand(423452);\n            const long M = 3;\n            const long N = 3;\n\n            matrix<double> a(M,N);  \n            for (long r = 0; r < a.nr(); ++r)\n            {\n                for (long c = 0; c < a.nc(); ++c)\n                {\n                    a(r,c) = 10*((double)::rand())/RAND_MAX;\n                }\n            }\n\n            matrix<double,M,M> u, u2;  \n            matrix<double> q, q2;\n            matrix<double,N,N> v, v2;\n\n            matrix<double,M,N,MM> a2;  \n            a2 = tmp(a/2);\n\n\n            svd2(true,true,a2+a2,u,q,v);\n\n            double err = max(abs(a - subm(u,get_rect(a2+a2))*diagm(q)*trans(v)));\n            DLIB_TEST_MSG( err < 1e-11,\"err: \" << err);\n            using dlib::equal;\n            DLIB_TEST((equal(trans(u)*u , identity_matrix<double,M>(), 1e-10)));\n            DLIB_TEST((equal(trans(v)*v , identity_matrix<double,N>(), 1e-10)));\n\n            svd2(false,true,a2+a2,u,q,v2);\n            svd2(true,false,a2+a2,u2,q,v);\n            svd2(false,false,a2+a2,u,q2,v);\n\n            err = max(abs(a - subm(u2,get_rect(a2+a2))*diagm(q2)*trans(v2)));\n            DLIB_TEST_MSG( err < 1e-11,\"err: \" << err);\n            DLIB_TEST((equal(trans(u2)*u2 , identity_matrix<double,M>(), 1e-10)));\n            DLIB_TEST((equal(trans(v2)*v2 , identity_matrix<double,N>(), 1e-10)));\n\n        }\n\n        {\n            srand(423452);\n            const long M = 3;\n            const long N = 3;\n\n\n            matrix<double,0,0,default_memory_manager, column_major_layout> a(M,N);  \n            for (long r = 0; r < a.nr(); ++r)\n            {\n                for (long c = 0; c < a.nc(); ++c)\n                {\n                    a(r,c) = 10*((double)::rand())/RAND_MAX;\n                }\n            }\n\n            matrix<double,M,M,default_memory_manager, column_major_layout> u, u2;  \n            matrix<double,0,0,default_memory_manager, column_major_layout> q, q2;\n            matrix<double,N,N,default_memory_manager, column_major_layout> v, v2;\n\n            matrix<double,M,N,MM, column_major_layout> a2;  \n            a2 = tmp(a/2);\n\n\n            svd2(true,true,a2+a2,u,q,v);\n\n            double err = max(abs(a - subm(u,get_rect(a2+a2))*diagm(q)*trans(v)));\n            DLIB_TEST_MSG( err < 1e-11,\"err: \" << err);\n            using dlib::equal;\n            DLIB_TEST((equal(trans(u)*u , identity_matrix<double,M>(), 1e-10)));\n            DLIB_TEST((equal(trans(v)*v , identity_matrix<double,N>(), 1e-10)));\n\n            svd2(false,true,a2+a2,u,q,v2);\n            svd2(true,false,a2+a2,u2,q,v);\n            svd2(false,false,a2+a2,u,q2,v);\n\n            err = max(abs(a - subm(u2,get_rect(a2+a2))*diagm(q2)*trans(v2)));\n            DLIB_TEST_MSG( err < 1e-11,\"err: \" << err);\n            DLIB_TEST((equal(trans(u2)*u2 , identity_matrix<double,M>(), 1e-10)));\n            DLIB_TEST((equal(trans(v2)*v2 , identity_matrix<double,N>(), 1e-10)));\n\n        }\n\n\n\n        {\n            srand(423452);\n            const long M = 10;\n            const long N = 7;\n\n            matrix<double> a(M,N);  \n            for (long r = 0; r < a.nr(); ++r)\n            {\n                for (long c = 0; c < a.nc(); ++c)\n                {\n                    a(r,c) = 10*((double)::rand())/RAND_MAX;\n                }\n            }\n\n            matrix<double,M,M> u;  \n            matrix<double> q;\n            matrix<double,N,N> v;\n\n            matrix<double,M,N,MM> a2;  \n            a2 = tmp(a/2);\n\n\n            svd2(true,true,a2+a2,u,q,v);\n\n            double err = sum(round(1e10*(a - subm(u,get_rect(a2+a2))*diagm(q)*trans(v))));\n            DLIB_TEST_MSG(  err == 0,\"err: \" << err);\n            DLIB_TEST((round(1e10*trans(u)*u)  == 1e10*identity_matrix<double,M>()));\n            DLIB_TEST((round(1e10*trans(v)*v)  == 1e10*identity_matrix<double,N>()));\n        }\n\n\n        {\n            srand(423452);\n            const long M = 10;\n            const long N = 7;\n\n            matrix<double> a(M,N);  \n            for (long r = 0; r < a.nr(); ++r)\n            {\n                for (long c = 0; c < a.nc(); ++c)\n                {\n                    a(r,c) = 10*((double)::rand())/RAND_MAX;\n                }\n            }\n\n            matrix<double,M> u(M,N);  \n            matrix<double> w;\n            matrix<double,N,N> v(N,N);\n\n            matrix<double,M,N,MM> a2;  \n            a2 = tmp(a/2);\n\n\n            svd(a2+a2,u,w,v);\n\n            DLIB_TEST(  sum(round(1e10*(a - u*w*trans(v)))) == 0);\n            DLIB_TEST((round(1e10*trans(u)*u)  == 1e10*identity_matrix<double,N>()));\n            DLIB_TEST((round(1e10*trans(v)*v)  == 1e10*identity_matrix<double,N>()));\n        }\n\n        {\n            srand(423452);\n            const long M = 1;\n            const long N = 1;\n\n            matrix<double> a(M,N);  \n            for (long r = 0; r < a.nr(); ++r)\n            {\n                for (long c = 0; c < a.nc(); ++c)\n                {\n                    a(r,c) = 10*((double)::rand())/RAND_MAX;\n                }\n            }\n\n            matrix<double,M,N> u;  \n            matrix<double> w;\n            matrix<double,N,N> v;\n\n            matrix<double,M,N> a2;  \n            a2 = 0;\n            a2 = tmp(a/2);\n\n\n            svd(a2+a2,u,w,v);\n\n            DLIB_TEST(  sum(round(1e10*(a - u*w*trans(v)))) == 0);\n            DLIB_TEST((round(1e10*trans(u)*u)  == 1e10*identity_matrix<double,N>()));\n            DLIB_TEST((round(1e10*trans(v)*v)  == 1e10*identity_matrix<double,N>()));\n        }\n\n\n        {\n            srand(53434);\n            const long M = 5;\n            const long N = 5;\n\n            matrix<double> a(M,N);  \n            for (long r = 0; r < a.nr(); ++r)\n            {\n                for (long c = 0; c < a.nc(); ++c)\n                {\n                    a(r,c) = 10*((double)::rand())/RAND_MAX;\n                }\n            }\n\n            matrix<double,0,N> u(M,N);  \n            matrix<double,N,N> w;\n            matrix<double> v;\n\n            svd(a,u,w,v);\n\n            DLIB_TEST(  sum(round(1e10*(a - u*w*trans(v)))) == 0);\n            DLIB_TEST((round(1e10*trans(u)*u)  == 1e10*identity_matrix<double,N>()));\n            DLIB_TEST((round(1e10*trans(v)*v)  == 1e10*identity_matrix<double,N>()));\n        }\n\n\n        {\n            srand(11234);\n            const long M = 9;\n            const long N = 4;\n\n            matrix<double,0,0,MM> a(M,N);  \n            for (long r = 0; r < a.nr(); ++r)\n            {\n                for (long c = 0; c < a.nc(); ++c)\n                {\n                    a(r,c) = 10*((double)::rand())/RAND_MAX;\n                }\n            }\n\n            matrix<double> u;  \n            matrix<double,0,0,MM> w;\n            matrix<double> v;\n\n            svd(a,u,w,v);\n\n            DLIB_TEST(  sum(round(1e10*(a - u*w*trans(v)))) == 0);\n            DLIB_TEST((round(1e10*trans(u)*u)  == 1e10*identity_matrix<double,N>()));\n            DLIB_TEST((round(1e10*trans(v)*v)  == 1e10*identity_matrix<double,N>()));\n        }\n\n\n\n        {\n            srand(53934);\n            const long M = 2;\n            const long N = 4;\n\n            matrix<double> a(M,N);  \n            for (long r = 0; r < a.nr(); ++r)\n            {\n                for (long c = 0; c < a.nc(); ++c)\n                {\n                    a(r,c) = 10*((double)::rand())/RAND_MAX;\n                }\n            }\n\n            matrix<double> u;  \n            matrix<double> w;\n            matrix<double> v;\n\n            svd(a,u,w,v);\n\n            DLIB_TEST(  sum(round(1e10*(a - u*w*trans(v)))) == 0);\n        }\n\n\n        {\n            srand(53234);\n            const long M = 9;\n            const long N = 40;\n\n            matrix<double> a(M,N);  \n            for (long r = 0; r < a.nr(); ++r)\n            {\n                for (long c = 0; c < a.nc(); ++c)\n                {\n                    a(r,c) = 10*((double)::rand())/RAND_MAX;\n                }\n            }\n\n            matrix<double> u;  \n            matrix<double> w;\n            matrix<double> v;\n\n            svd(a,u,w,v);\n\n            DLIB_TEST(  sum(round(1e10*(a - u*w*trans(v)))) == 0);\n        }\n\n        {\n            srand(53234);\n            const long M = 9;\n            const long N = 40;\n\n            typedef matrix<double,0,0,default_memory_manager, column_major_layout> mat;\n            mat a(M,N);  \n            for (long r = 0; r < a.nr(); ++r)\n            {\n                for (long c = 0; c < a.nc(); ++c)\n                {\n                    a(r,c) = 10*((double)::rand())/RAND_MAX;\n                }\n            }\n\n            mat u;  \n            mat w;\n            mat v;\n\n            svd(a,u,w,v);\n\n            DLIB_TEST(  sum(round(1e10*(a - u*w*trans(v)))) == 0);\n        }\n\n\n        {\n            matrix<double> a(3,3);\n            matrix<double,3,3> b;\n            set_all_elements(a,0);\n\n            a(0,0) = 1;\n            a(1,1) = 2;\n            a(2,2) = 3;\n            b = a;\n\n            DLIB_TEST(diag(a)(0) == 1);\n            DLIB_TEST(diag(a)(1) == 2);\n            DLIB_TEST(diag(a)(2) == 3);\n            DLIB_TEST(diag(a).nr() == 3);\n            DLIB_TEST(diag(a).nc() == 1);\n\n            DLIB_TEST(diag(b)(0) == 1);\n            DLIB_TEST(diag(b)(1) == 2);\n            DLIB_TEST(diag(b)(2) == 3);\n            DLIB_TEST(diag(b).nr() == 3);\n            DLIB_TEST(diag(b).nc() == 1);\n\n            DLIB_TEST(pointwise_multiply(a,b)(0,0) == 1);\n            DLIB_TEST(pointwise_multiply(a,b)(1,1) == 4);\n            DLIB_TEST(pointwise_multiply(a,b)(2,2) == 9);\n            DLIB_TEST(pointwise_multiply(a,b)(1,0) == 0);\n            DLIB_TEST(pointwise_multiply(a,b,a)(1,0) == 0);\n            DLIB_TEST(pointwise_multiply(a,b,a,b)(1,0) == 0);\n\n\n            DLIB_TEST(complex_matrix(a,b)(0,0) == std::complex<double>(1,1));\n            DLIB_TEST(complex_matrix(a,b)(2,2) == std::complex<double>(3,3));\n            DLIB_TEST(complex_matrix(a,b)(2,1) == std::complex<double>(0,0));\n        }\n\n        {\n            matrix<complex<double> > m(2,2), m2(2,2);\n            complex<double> val1(1,2), val2(1.0/complex<double>(1,2));\n            m = val1;\n            m2 = val2;\n\n            DLIB_TEST(equal(reciprocal(m) , m2));\n        }\n        {\n            matrix<complex<float> > m(2,2), m2(2,2);\n            complex<float> val1(1,2), val2(1.0f/complex<float>(1,2));\n            m = val1;\n            m2 = val2;\n\n            DLIB_TEST(equal(reciprocal(m) , m2));\n        }\n\n        {\n            matrix<float,3,1> m1, m2;\n            set_all_elements(m1,2.0);\n            set_all_elements(m2,1.0/2.0);\n            DLIB_TEST(reciprocal(m1) == m2);\n            DLIB_TEST((reciprocal(uniform_matrix<float,3,1>(2.0)) == m2));\n            DLIB_TEST((round_zeros(uniform_matrix<float,3,1>(1e-8f)) == uniform_matrix<float,3,1>(0)) );\n            set_all_elements(m1,2.0);\n            m2 = m1;\n            m1(1,0) = static_cast<float>(1e-8);\n            m2(1,0) = 0;\n            DLIB_TEST(round_zeros(m1) == m2);\n            m1 = round_zeros(m1);\n            DLIB_TEST(m1 == m2);\n        }\n\n        {\n            matrix<matrix<double,2,2> > m;\n            m.set_size(3,3);\n            set_all_elements(m,uniform_matrix<double,2,2>(1));\n            DLIB_TEST((sum(m) == uniform_matrix<double,2,2>(9)));\n            DLIB_TEST((round_zeros(sqrt(sum(m)) - uniform_matrix<double,2,2>(3)) == uniform_matrix<double,2,2>(0)));\n        }\n\n        {\n            matrix<int,2,2> m1;\n            matrix<int> m2;\n            m2.set_size(2,2);\n\n            set_all_elements(m1,2);\n            m2 = uniform_matrix<int,2,2>(2);\n\n            m1 = m1 + m2;\n            DLIB_TEST((m1 == uniform_matrix<int,2,2>(4)));\n\n            set_all_elements(m1,2);\n            set_all_elements(m2,2);\n            m1 = m1*m1;\n            DLIB_TEST((m1 == uniform_matrix<int,2,2>(8)));\n\n            m1(1,0) = 1;\n            set_all_elements(m2,8);\n            m2(0,1) = 1;\n            m1 = trans(m1);\n            DLIB_TEST(m1 == m2);\n        }\n\n        {\n            matrix<double,2,3> m;\n            matrix<double> m2(2,3);\n\n            set_all_elements(m,1);\n            DLIB_TEST(mean(m) == 1);\n            set_all_elements(m,2);\n            DLIB_TEST(mean(m) == 2);\n            m(0,0) = 1;\n            m(0,1) = 1;\n            m(0,2) = 1;\n            DLIB_TEST(abs(mean(m) - 1.5) < 1e-10);\n            DLIB_TEST(abs(variance(m) - 0.3) < 1e-10);\n\n            set_all_elements(m2,1);\n            DLIB_TEST(mean(m2) == 1);\n            set_all_elements(m2,2);\n            DLIB_TEST(mean(m2) == 2);\n            m2(0,0) = 1;\n            m2(0,1) = 1;\n            m2(0,2) = 1;\n            DLIB_TEST(abs(mean(m2) - 1.5) < 1e-10);\n            DLIB_TEST(abs(variance(m2) - 0.3) < 1e-10);\n\n            set_all_elements(m,0);\n            DLIB_TEST(abs(variance(m)) < 1e-10);\n            set_all_elements(m,1);\n            DLIB_TEST(abs(variance(m)) < 1e-10);\n            set_all_elements(m,23.4);\n            DLIB_TEST(abs(variance(m)) < 1e-10);\n        }\n\n        {\n            matrix<matrix<double,3,1,MM>,2,2,MM> m;\n            set_all_elements(m,uniform_matrix<double,3,1>(1));\n            DLIB_TEST((round_zeros(variance(m)) == uniform_matrix<double,3,1>(0)));\n            DLIB_TEST((round_zeros(mean(m)) == uniform_matrix<double,3,1>(1)));\n            m(0,0) = uniform_matrix<double,3,1>(9);\n            DLIB_TEST((round_zeros(variance(m)) == uniform_matrix<double,3,1>(16)));\n            DLIB_TEST((round_zeros(mean(m)) == uniform_matrix<double,3,1>(3)));\n\n            matrix<matrix<double> > m2(2,2);\n            set_all_elements(m2,uniform_matrix<double,3,1>(1));\n            DLIB_TEST((round_zeros(variance(m2)) == uniform_matrix<double,3,1>(0)));\n            DLIB_TEST((round_zeros(mean(m2)) == uniform_matrix<double,3,1>(1)));\n            m2(0,0) = uniform_matrix<double,3,1>(9);\n            DLIB_TEST((round_zeros(variance(m2)) == uniform_matrix<double,3,1>(16)));\n            DLIB_TEST((round_zeros(mean(m2)) == uniform_matrix<double,3,1>(3)));\n        }\n\n\n        {\n            matrix<double> m(4,4), m2;\n            m = 1,2,3,4,\n                1,2,3,4,\n                4,6,8,10,\n                4,6,8,10;\n            m2 = m;\n\n            DLIB_TEST(colm(m,range(0,3)) == m);\n            DLIB_TEST(rowm(m,range(0,3)) == m);\n            DLIB_TEST(colm(m,range(0,0)) == colm(m,0));\n            DLIB_TEST(rowm(m,range(0,0)) == rowm(m,0));\n            DLIB_TEST(colm(m,range(1,1)) == colm(m,1));\n            DLIB_TEST(rowm(m,range(1,1)) == rowm(m,1));\n\n            DLIB_TEST(colm(m,range(2,2)) == colm(m,2));\n            DLIB_TEST(rowm(m,range(2,2)) == rowm(m,2));\n\n            DLIB_TEST(colm(m,range(1,2)) == subm(m,0,1,4,2));\n            DLIB_TEST(rowm(m,range(1,2)) == subm(m,1,0,2,4));\n\n            set_colm(m,range(1,2)) = 9;\n            set_subm(m2,0,1,4,2) = 9;\n            DLIB_TEST(m == m2);\n\n            set_colm(m,range(1,2)) = 11;\n            set_subm(m2,0,1,4,2) = 11;\n            DLIB_TEST(m == m2);\n        }\n\n\n    }\n\n\n\n\n\n\n    class matrix_tester : public tester\n    {\n    public:\n        matrix_tester (\n        ) :\n            tester (\"test_matrix2\",\n                    \"Runs tests on the matrix component.\")\n        {}\n\n        void perform_test (\n        )\n        {\n            matrix_test();\n        }\n    } a;\n\n}\n\n\n", "meta": {"hexsha": "c86c0960845d280646626332782e68c451ab7aff", "size": 34898, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/dlib-18.9/dlib/test/matrix2.cpp", "max_stars_repo_name": "NTForked/DiscreteElasticRods", "max_stars_repo_head_hexsha": "e28dac56149553437da8aea51b377be1b5b57cbf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 51.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T06:50:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T21:00:13.000Z", "max_issues_repo_path": "libs/dlib-18.9/dlib/test/matrix2.cpp", "max_issues_repo_name": "NTForked/DiscreteElasticRods", "max_issues_repo_head_hexsha": "e28dac56149553437da8aea51b377be1b5b57cbf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2017-05-03T00:28:58.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-30T12:32:16.000Z", "max_forks_repo_path": "itomp_cio_planner/dlib/dlib/test/matrix2.cpp", "max_forks_repo_name": "Chpark/itomp", "max_forks_repo_head_hexsha": "a11713a14a0b65ede54ab3b1cee2c0060b386d0e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2015-01-01T04:45:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-23T04:28:53.000Z", "avg_line_length": 30.8286219081, "max_line_length": 136, "alphanum_fraction": 0.4711158233, "num_tokens": 10967, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6584175005616829, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.48931482647334157}}
{"text": "#include <stiffness_checker/Material.h>\n#include <stiffness_checker/StiffnessIO.h>\n#include \"test_common.h\"\n#include <catch2/catch.hpp>\n#include <fstream>\n#include <nlohmann/json.hpp>\n#include <Eigen/Dense>\n\nnamespace\n{\nvoid assert_eq_PLA(const conmech::material::Material& m)\n{\n  using namespace conmech_testing;\n  using namespace conmech::material;\n  double eps = conmech::EPSILON;\n\n  // these readings are expected to be exact\n  // kN/cm2 to kN/m2\n  double pressure_unit = 1e4;\n  assert_near(m.youngs_modulus_, pressure_unit * 350, eps);\n  assert_near(m.shear_modulus_, pressure_unit * 240, eps);\n  assert_near(computePoissonRatio(m.youngs_modulus_, m.shear_modulus_), m.poisson_ratio_, eps);\n\n  // kN/m3\n  double density_unit = 1;\n  assert_near(m.density_, density_unit * 12.2582, eps);\n\n  // cm^2 -> m^2\n  double area_unit = 1e-4;\n  assert_near(m.cross_sec_area_, area_unit * 0.07068583470577035, eps);\n\n  // cm^4 -> m^4\n  double inertia_unit = 1e-8;\n  assert_near(m.Jx_, inertia_unit * 0.0007952156404399163, eps);\n  assert_near(m.Iy_, inertia_unit * 0.00039760782021995816, eps);\n  assert_near(m.Iz_, inertia_unit * 0.00039760782021995816, eps);\n}\n}\n\nTEST_CASE(\"material deserialed from a json file\", \"[io]\") \n{\n  using namespace conmech_testing;\n  using namespace conmech::material;\n  std::string test_frame_path = conmech_testing::data_path(\"four-frame.json\");\n\n  std::ifstream is(test_frame_path);\n  if (!is.is_open()) {\n      throw std::runtime_error(\"Couldn't open frame: \" + test_frame_path);\n  }\n  nlohmann::json config;\n  is >> config;\n\n  Material m;\n  parseMaterialPropertiesJson(config[\"material_properties\"], m);\n  assert_eq_PLA(m);\n\n  m.setFromJson(config[\"material_properties\"]);\n  assert_eq_PLA(m);\n}\n\nTEST_CASE(\"frame data deserialed from a json file\", \"[io]\") \n{\n  using namespace conmech_testing;\n  using namespace conmech::material;\n  using namespace conmech::stiffness_checker;\n  std::string test_frame_path = conmech_testing::data_path(\"four-frame.json\");\n\n  Eigen::MatrixXd V;\n  Eigen::MatrixXi E;\n  Eigen::MatrixXi Fixities;\n  std::vector<Material> mats;\n  double eps = conmech::EPSILON;\n\n  parseFrameJson(test_frame_path, V, E, Fixities, mats);\n\n  Eigen::MatrixXd realV(5,3);\n  realV << 0, -20, -10,\n           0, 20, -10,\n           0, 20, 0,\n           0, -20, 0,\n           0, 0, 20;\n  realV *= 0.001;\n  assert_near_m(V, realV, eps);\n\n  Eigen::MatrixXi realE(4,2);\n  realE << 0, 3,\n           1, 2,\n           3, 4,\n           2, 4;\n  assert_near_m(E, realE, eps);\n\n  Eigen::MatrixXi realFixities(2, 7);\n  realFixities << 0, 1, 1, 1, 1, 1, 1,\n                  1, 1, 1, 1, 1, 1, 1;\n  assert_near_m(Fixities, realFixities, eps);\n\n  for (const auto& m : mats)\n  {\n    assert_eq_PLA(m);\n  }\n}", "meta": {"hexsha": "0fc45314f1c1539e8816ac4726be1cbba44e4742", "size": 2722, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/cpp/test_io.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": "tests/cpp/test_io.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": "tests/cpp/test_io.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": 26.9504950495, "max_line_length": 95, "alphanum_fraction": 0.6796473181, "num_tokens": 876, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743167997235783, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.48931482021861716}}
{"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_SIMD_COMMON_SIGNIFICANTS_HPP_INCLUDED\n#define BOOST_SIMD_ARITHMETIC_FUNCTIONS_SIMD_COMMON_SIGNIFICANTS_HPP_INCLUDED\n\n#include <nt2/exponential/functions/significants.hpp>\n#include <nt2/include/functions/simd/round.hpp>\n#include <nt2/include/functions/simd/tenpower.hpp>\n#include <nt2/include/functions/simd/abs.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/log10.hpp>\n#include <nt2/include/functions/simd/minus.hpp>\n#include <nt2/include/functions/simd/divides.hpp>\n#include <nt2/include/functions/simd/multiplies.hpp>\n#include <nt2/include/functions/simd/iceil.hpp>\n#include <boost/dispatch/attributes.hpp>\n#include <boost/dispatch/meta/as_integer.hpp>\n#include <boost/assert.hpp>\n#include <boost/simd/operator/functions/details/assert_utils.hpp>\n#include <boost/mpl/equal_to.hpp>\n#ifndef BOOST_SIMD_NO_INVALIDS\n#include <nt2/include/functions/simd/if_else.hpp>\n#include <nt2/include/functions/simd/is_invalid.hpp>\n#endif\n\nnamespace nt2 { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT_IF( significants_, tag::cpu_\n                             , (A0)(X)(A1)\n                             , (boost::mpl::equal_to < boost::simd::meta::cardinal_of<A0>\n                                                     , boost::simd::meta::cardinal_of<A1>\n                                >)\n                             , ((simd_< floating_<A0>, X>))\n                               ((simd_< integer_<A1>, X>))\n                             )\n  {\n    typedef A0 result_type;\n\n    BOOST_FORCEINLINE BOOST_SIMD_FUNCTOR_CALL(2)\n    {\n      BOOST_ASSERT_MSG( assert_all(is_gtz(a1))\n                      , \"Number of significant digits must be positive\"\n                      );\n      typedef typename boost::dispatch::meta::as_integer<A0>::type iA0;\n      iA0 exp = a1 - iceil(log10(abs(a0)));\n      A0 fac = tenpower(exp);\n      A0 scaled = round(a0*fac);\n#ifndef BOOST_SIMD_NO_INVALIDS\n      A0 r = if_else(is_invalid(a0), a0, scaled/fac);\n#else\n      A0 r =  scaled/fac;\n#endif\n      return if_zero_else(is_eqz(a0), r);\n    }\n  };\n\n} }\n\n#endif\n", "meta": {"hexsha": "a03800a922d9aba61bdee7686c2cae90ea66ef64", "size": 2564, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/exponential/include/nt2/exponential/functions/simd/common/significants.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/exponential/include/nt2/exponential/functions/simd/common/significants.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/exponential/include/nt2/exponential/functions/simd/common/significants.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.8484848485, "max_line_length": 89, "alphanum_fraction": 0.6041341654, "num_tokens": 578, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152325073083131, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4892930609769595}}
{"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\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\n#include <armadillo>\n\n#define uli unsigned long int\n\n#include \"functions.h\"\n\nusing namespace std;\nusing namespace arma;\n\n\n#define language_cpp \n\nint main(void) \n{\n\n   \n mat Y;\n vec vnan;\n double max_lag,alpha;\n string direction;\n uli nsim;\n bool flg_print;\n str_output out;\n\n //USECASE 1\n  \n Y.load(\"data/Data_air.csv\", csv_ascii);\n Y.replace(0,datum::nan); \n\n max_lag=-1; //-1 means auto\n direction=\"<->\";\n alpha=0.05;\n nsim=1000;\n flg_print=1;\n \n out=regpred_cpp(&Y, max_lag, alpha, nsim, flg_print, direction);\n\n out.predictions.print(\"Usecase 1 predictions\");\n\n //USECASE 2\n\n Y.load(\"data/Data_sim_1000.csv\", csv_ascii);\n Y.replace(0,datum::nan); \n\n max_lag=-1; //-1 means auto\n direction=\"<->\";\n alpha=0.05;\n nsim=1000;\n flg_print=1;\n \n out=regpred_cpp(&Y, max_lag, alpha, nsim, flg_print, direction);\n\n out.predictions.print(\"Usecase 2 predictions\");\n\n\n \n\n return 0;\n\n}", "meta": {"hexsha": "5e16577bb9c9b6eb49eb65225736e3ad871f7680", "size": 1459, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test.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": "test/test.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": "test/test.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": 16.9651162791, "max_line_length": 71, "alphanum_fraction": 0.7032213845, "num_tokens": 404, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324983301568, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4892930555883746}}
{"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_SINH_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_SINH_HPP_INCLUDED\n#include <boost/simd/function/std.hpp>\n\n#include <boost/simd/arch/common/detail/generic/sinh_kernel.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/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/fms.hpp>\n#include <boost/simd/function/rec.hpp>\n#include <boost/simd/function/sqr.hpp>\n#include <boost/simd/detail/dispatch/function/overload.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 ( sinh_\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      //////////////////////////////////////////////////////////////////////////////\n      // if x = abs(a0) is less than 1 sinh is computed using a polynomial(float)\n      // respectively rational(double) approx from cephes.\n      // else according x < Threshold e =  exp(x) or exp(x/2) is respectively\n      // computed\n      // * in the first case sinh is (e-rec(e))/2\n      // * in the second     sinh is (e/2)*e (avoiding undue overflow)\n      // Threshold is Maxlog - Log_2 defined in Maxshlog\n      //////////////////////////////////////////////////////////////////////////////\n      A0 x = bs::abs(a0);\n      if( x < One<A0>())\n      {\n       A0 x2 = sqr(x);\n       return detail::sinh_kernel<A0>::compute(a0, x2);\n      }\n      else\n      {\n        A0 r;\n        if (BOOST_UNLIKELY( x > Maxlog<A0>()-Log_2<A0>()))\n        {\n          A0 tmp = exp(Half<A0>()*x);\n          r = (Half<A0>()*tmp)*tmp;\n        }\n        else\n        {\n          A0 tmp = exp(x);\n          r =  fms(tmp, Half<A0>(), Half<A0>()*rec(tmp));\n        }\n        return bitwise_xor(r, bitofsign(a0));\n      }\n    }\n  };\n  BOOST_DISPATCH_OVERLOAD ( sinh_\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::sinh(a0);\n    }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "60c3d5a22d93b5daefb74612fda1c6214d08bf2b", "size": 3030, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/scalar/function/sinh.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/scalar/function/sinh.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/sinh.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.6666666667, "max_line_length": 100, "alphanum_fraction": 0.5161716172, "num_tokens": 705, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324983301567, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4892930555883745}}
{"text": "#pragma once\n\n#ifndef AMM_H\n#define AMM_H\n\n#include <boost/multiprecision/gmp.hpp>\n#include \"./token.hpp\"\n\n\n// sample class describing a simple constant product AMM\n// We use the convention that the first token is the sell token\n// and the second token is the buy token.\nclass CP_AMM {\n    public:\n        const int amm_index;\n        const int sell_token_index;\n        const boost::multiprecision::mpz_int sell_reserve_amount;\n        const int buy_token_index;\n        const boost::multiprecision::mpz_int buy_reserve_amount;\n        const boost::multiprecision::mpf_float fee_amount;\n        const int cost_token_index;\n        const boost::multiprecision::mpz_int cost_amount;\n        const bool is_mandatory;\n\n\n\n        // Constructor\n        CP_AMM(int _amm_index, int _sell_token_index, boost::multiprecision::mpz_int _sell_reserve_amount, int _buy_token_index, boost::multiprecision::mpz_int _buy_reserve_amount, boost::multiprecision::mpf_float _fee_amount, int _cost_token_index, boost::multiprecision::mpz_int _cost_amount, bool _is_mandatory): amm_index(_amm_index), sell_token_index(_sell_token_index),  sell_reserve_amount(_sell_reserve_amount), buy_token_index(_buy_token_index), buy_reserve_amount(_buy_reserve_amount), fee_amount(_fee_amount), cost_token_index(_cost_token_index), cost_amount(_cost_amount), is_mandatory(_is_mandatory) {\n        }\n\n};\n        \n\nvoid print_cp_amm(CP_AMM &a, std::vector<Token> &_tokens);\n\n\n\n#endif", "meta": {"hexsha": "9553cfd09bbe6509ae25fb85537efc6fae67ae82", "size": 1448, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/components/amm.hpp", "max_stars_repo_name": "cowprotocol/simple-solver-template", "max_stars_repo_head_hexsha": "51aeebd91c4d7b99627a93d0a066684553bdc5ad", "max_stars_repo_licenses": ["ECL-2.0", "Apache-2.0", "MIT-0", "MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/components/amm.hpp", "max_issues_repo_name": "cowprotocol/simple-solver-template", "max_issues_repo_head_hexsha": "51aeebd91c4d7b99627a93d0a066684553bdc5ad", "max_issues_repo_licenses": ["ECL-2.0", "Apache-2.0", "MIT-0", "MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-12-16T09:40:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-02T18:49:47.000Z", "max_forks_repo_path": "src/components/amm.hpp", "max_forks_repo_name": "cowprotocol/simple-solver-template", "max_forks_repo_head_hexsha": "51aeebd91c4d7b99627a93d0a066684553bdc5ad", "max_forks_repo_licenses": ["ECL-2.0", "Apache-2.0", "MIT-0", "MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2022-03-28T15:35:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T14:27:47.000Z", "avg_line_length": 38.1052631579, "max_line_length": 614, "alphanum_fraction": 0.7582872928, "num_tokens": 335, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4892930501997894}}
{"text": "/*\n * Copyright 2015 Christoph Jud (christoph.jud@unibas.ch)\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 <memory>\n#include <ctime>\n\n#include <boost/random.hpp>\n\n#include <Eigen/SVD>\n\n#include \"GaussianProcess.h\"\n#include \"Kernel.h\"\n\nusing namespace gpr;\n\ntypedef GaussianKernel<double>\t\tKernelType;\ntypedef std::shared_ptr<KernelType> KernelTypePointer;\ntypedef GaussianProcess<double> GaussianProcessType;\ntypedef std::shared_ptr<GaussianProcessType> GaussianProcessTypePointer;\n\ntypedef GaussianProcessType::VectorType VectorType;\ntypedef GaussianProcessType::MatrixType MatrixType;\n\nVectorType GetRandomVector(unsigned n){\n    static boost::minstd_rand randgen(static_cast<unsigned>(time(0)));\n    static boost::normal_distribution<> dist(0, 1);\n    static boost::variate_generator<boost::minstd_rand, boost::normal_distribution<> > r(randgen, dist);\n\n    VectorType v = VectorType::Zero(n);\n    for (unsigned i=0; i < n; i++) {\n        v(i) = r();\n    }\n    return v;\n}\n\nvoid Test1(){\n    /*\n     * Test 1: scalar valued GP\n     * - try to learn sinus function\n     */\n    std::cout << \"Test 1: sinus regression... \" << std::flush;\n\n    KernelTypePointer k(new KernelType(0.5));\n    GaussianProcessTypePointer gp(new GaussianProcessType(k));\n    gp->SetSigma(0.00001);\n\n    unsigned number_of_samples = 20;\n\n    // add training samples\n    for(unsigned i=0; i<number_of_samples; i++){\n        VectorType x(1);\n        x(0) = i * 2*M_PI/number_of_samples;\n\n        VectorType y(1);\n        y(0) = std::sin(x(0));\n        gp->AddSample(x,y);\n    }\n    gp->Initialize();\n\n\n    // calculate credible interval\n    unsigned number_of_tests = 50;\n    for(unsigned i=0; i<number_of_tests; i++){\n        VectorType x(1);\n        x(0) = i * 2*M_PI/number_of_tests * 1.3;\n\n        try{\n            double c = 2*std::sqrt((*gp)(x,x)) - gp->GetCredibleInterval(x);\n            if(c != 0){\n                throw std::string(\"credible interval not correct.\");\n                return;\n            }\n        }\n        catch(std::string& s){\n            throw std::string(\"error in calculating credible interval.\");\n            return;\n        }\n    }\n    std::cout << \" [passed]\" << std::endl;\n}\n\nvoid Test2(){\n    /*\n     * Test 2: sampling test\n     * - try to sample from a posterior\n     */\n    std::cout << \"Test 2: posterior sampling test... \" << std::flush;\n\n    KernelTypePointer k(new KernelType(1));\n    GaussianProcessTypePointer gp(new GaussianProcessType(k));\n    gp->SetSigma(0);\n\n    // add some landmarks\n    gp->AddSample(VectorType::Ones(1),  VectorType::Zero(1));\n    gp->AddSample(VectorType::Ones(1)*2,VectorType::Ones(1));\n    gp->AddSample(VectorType::Ones(1)*3,VectorType::Ones(1)*0.5);\n    gp->AddSample(VectorType::Ones(1)*4,VectorType::Ones(1));\n    gp->Initialize();\n\n    // compute gp kernel matrix (interval 0-5)\n    unsigned number_of_samples = 50;\n    VectorType mean = VectorType::Zero(number_of_samples);\n    MatrixType K = MatrixType::Zero(number_of_samples,number_of_samples);\n\n    #pragma omp parallel for\n    for(unsigned i=0; i<number_of_samples; i++){\n        VectorType x1(1);\n        x1(0) = i * 5.0/static_cast<double>(number_of_samples);\n        mean[i] = gp->Predict(x1)(0);\n\n        for(unsigned j=i; j<number_of_samples; j++){\n            VectorType x2(1);\n            x2(0) = j * 5.0/number_of_samples;\n\n            K(i,j) = (*gp)(x1,x2);\n            K(j,i) = K(i,j);\n        }\n\n    }\n\n\n    // generate multivariate normal random numbers\n    Eigen::SelfAdjointEigenSolver<MatrixType> eigenSolver(K);\n    unsigned numComponentsToKeep = ((eigenSolver.eigenvalues().array() - 1e-10) > 0).count();\n    MatrixType rot = eigenSolver.eigenvectors().rowwise().reverse().topLeftCorner(K.rows(), numComponentsToKeep);\n    VectorType scl = eigenSolver.eigenvalues().reverse().topRows(numComponentsToKeep).array().sqrt();\n\n    MatrixType Q = rot*scl.asDiagonal();\n    double err = (Q*Q.transpose() - K).norm();\n    if(err > 1e-8 || std::isnan(err)){\n        std::stringstream ss; ss<<\"eigen decomposition not accurate enough. (error: \" << err << \")\"; throw ss.str();\n        return;\n    }\n\n    for(unsigned k=0; k<10; k++){\n        VectorType r = rot * VectorType(GetRandomVector(number_of_samples).array() * scl.array()) + mean;\n\n        // since the noise of the gp is zero, at the landmark points,\n        // all samples have to match the mean\n        if(std::fabs(r[10] - mean[10]) > 1e-9 ||\n                std::fabs(r[20] - mean[20]) > 1e-9 ||\n                std::fabs(r[30] - mean[30]) > 1e-9 ||\n                std::fabs(r[40] - mean[40]) > 1e-9){\n            throw std::string(\"samples do not corresponds to the landmarks.\");\n            return;\n        }\n    }\n\n    std::cout << \" [passed]\" << std::endl;\n}\n\n\nint main (int argc, char *argv[]){\n    std::cout << \"Gaussian process posterior test: \" << std::endl;\n    try{\n        Test1();\n        Test2();\n    }\n    catch(std::string& s){\n        std::cout << \"[failed] Error: \" << s << std::endl;\n        return -1;\n    }\n    return 0;\n}\n\n", "meta": {"hexsha": "da23d836b5a09b5b06cc1271d383af7dd6d9ac5b", "size": 5573, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/PosteriorProcessTest.cpp", "max_stars_repo_name": "ChristophJud/GPR", "max_stars_repo_head_hexsha": "62c60aca697ae7614356b1f6db06568f0c4085d2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2015-04-20T14:30:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-18T21:44:06.000Z", "max_issues_repo_path": "tests/PosteriorProcessTest.cpp", "max_issues_repo_name": "ChristophJud/GPR", "max_issues_repo_head_hexsha": "62c60aca697ae7614356b1f6db06568f0c4085d2", "max_issues_repo_licenses": ["Apache-2.0"], "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/PosteriorProcessTest.cpp", "max_forks_repo_name": "ChristophJud/GPR", "max_forks_repo_head_hexsha": "62c60aca697ae7614356b1f6db06568f0c4085d2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2015-11-16T00:50:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-23T02:00:18.000Z", "avg_line_length": 30.7900552486, "max_line_length": 116, "alphanum_fraction": 0.6183384174, "num_tokens": 1484, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324848629214, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4892930475054967}}
{"text": "#ifndef PCL_TRACKING_IMPL_DISTANCE_COHERENCE_H_\n#define PCL_TRACKING_IMPL_DISTANCE_COHERENCE_H_\n\n#include <Eigen/Dense>\n\nnamespace pcl {\nnamespace tracking {\ntemplate <typename PointInT>\ndouble DistanceCoherence<PointInT>::computeCoherence(PointInT &source,\n                                                     PointInT &target) {\n    Eigen::Vector4f p = source.getVector4fMap();\n    Eigen::Vector4f p_dash = target.getVector4fMap();\n    double d = (p - p_dash).norm();\n    return 1.0 / (1.0 + d * d * weight_);\n}\n} // namespace tracking\n} // namespace pcl\n\n#define PCL_INSTANTIATE_DistanceCoherence(T)                                   \\\n    template class PCL_EXPORTS pcl::tracking::DistanceCoherence<T>;\n\n#endif\n", "meta": {"hexsha": "7a107b4c31de470f60b4f04cf56e58ab4eae0a2f", "size": 715, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "tracking/include/pcl/tracking/impl/distance_coherence.hpp", "max_stars_repo_name": "yxlao/StanfordPCL", "max_stars_repo_head_hexsha": "98a8663f896c1ba880d14efa2338b7cfbd01b6ef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tracking/include/pcl/tracking/impl/distance_coherence.hpp", "max_issues_repo_name": "yxlao/StanfordPCL", "max_issues_repo_head_hexsha": "98a8663f896c1ba880d14efa2338b7cfbd01b6ef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tracking/include/pcl/tracking/impl/distance_coherence.hpp", "max_forks_repo_name": "yxlao/StanfordPCL", "max_forks_repo_head_hexsha": "98a8663f896c1ba880d14efa2338b7cfbd01b6ef", "max_forks_repo_licenses": ["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.0869565217, "max_line_length": 80, "alphanum_fraction": 0.6601398601, "num_tokens": 172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324803738429, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.489293044811204}}
{"text": "#define DEBUG 1\n/**\n * File    : C.cpp\n * Author  : Kazune Takahashi\n * Created : 6/16/2020, 4:51:02 PM\n * Powered by Visual Studio Code\n */\n#include <algorithm>\n#include <bitset>\n#include <cassert>\n#include <cctype>\n#include <chrono>\n#include <climits>\n#include <cmath>\n#include <complex>\n#include <cstdint>\n#include <cstdio>\n#include <cstdlib>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <limits>\n#include <map>\n#include <queue>\n#include <random>\n#include <set>\n#include <stack>\n#include <string>\n#include <tuple>\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n// ----- boost -----\n#include <boost/rational.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n// ----- using directives and manipulations -----\nusing namespace std;\nusing boost::rational;\nusing boost::multiprecision::cpp_int;\nusing ll = long long;\nusing ld = long double;\ntemplate <typename T>\nusing max_heap = priority_queue<T>;\ntemplate <typename T>\nusing min_heap = priority_queue<T, vector<T>, greater<T>>;\n// ----- constexpr for Mint and Combination -----\nconstexpr ll MOD{1'000'000'007LL};\n// constexpr ll MOD{998'244'353LL}; // be careful\nconstexpr ll MAX_SIZE{3'000'010LL};\n// constexpr ll MAX_SIZE{30'000'010LL}; // if 10^7 is needed\n// ----- ch_max and ch_min -----\ntemplate <typename T>\nbool ch_max(T &left, T right)\n{\n  if (left < right)\n  {\n    left = right;\n    return true;\n  }\n  return false;\n}\ntemplate <typename T>\nbool ch_min(T &left, T right)\n{\n  if (left > right)\n  {\n    left = right;\n    return true;\n  }\n  return false;\n}\n// ----- Mint -----\ntemplate <ll MOD = MOD>\nclass Mint\n{\npublic:\n  ll x;\n  Mint() : x{0LL} {}\n  Mint(ll x) : x{(x % MOD + MOD) % MOD} {}\n  Mint operator-() const { return x ? MOD - x : 0; }\n  Mint &operator+=(Mint const &a)\n  {\n    if ((x += a.x) >= MOD)\n    {\n      x -= MOD;\n    }\n    return *this;\n  }\n  Mint &operator-=(Mint const &a) { return *this += -a; }\n  Mint &operator++() { return *this += 1; }\n  Mint operator++(int)\n  {\n    Mint tmp{*this};\n    ++*this;\n    return tmp;\n  }\n  Mint &operator--() { return *this -= 1; }\n  Mint operator--(int)\n  {\n    Mint tmp{*this};\n    --*this;\n    return tmp;\n  }\n  Mint &operator*=(Mint const &a)\n  {\n    (x *= a.x) %= MOD;\n    return *this;\n  }\n  Mint &operator/=(Mint const &a)\n  {\n    Mint b{a};\n    return *this *= b.power(MOD - 2);\n  }\n  Mint operator+(Mint const &a) const { return Mint(*this) += a; }\n  Mint operator-(Mint const &a) const { return Mint(*this) -= a; }\n  Mint operator*(Mint const &a) const { return Mint(*this) *= a; }\n  Mint operator/(Mint const &a) const { return Mint(*this) /= a; }\n  bool operator<(Mint const &a) const { return x < a.x; }\n  bool operator<=(Mint const &a) const { return x <= a.x; }\n  bool operator>(Mint const &a) const { return x > a.x; }\n  bool operator>=(Mint const &a) const { return x >= a.x; }\n  bool operator==(Mint const &a) const { return x == a.x; }\n  bool operator!=(Mint const &a) const { return !(*this == a); }\n  Mint power(ll N) const\n  {\n    if (N == 0)\n    {\n      return 1;\n    }\n    else if (N % 2 == 1)\n    {\n      return *this * power(N - 1);\n    }\n    else\n    {\n      Mint half = power(N / 2);\n      return half * half;\n    }\n  }\n};\ntemplate <ll MOD>\nMint<MOD> operator+(ll lhs, Mint<MOD> const &rhs) { return rhs + lhs; }\ntemplate <ll MOD>\nMint<MOD> operator-(ll lhs, Mint<MOD> const &rhs) { return -rhs + lhs; }\ntemplate <ll MOD>\nMint<MOD> operator*(ll lhs, Mint<MOD> const &rhs) { return rhs * lhs; }\ntemplate <ll MOD>\nMint<MOD> operator/(ll lhs, Mint<MOD> const &rhs) { return Mint<MOD>{lhs} / rhs; }\ntemplate <ll MOD>\nistream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; }\ntemplate <ll MOD>\nostream &operator<<(ostream &stream, Mint<MOD> const &a) { return stream << a.x; }\n// ----- Combination -----\ntemplate <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>\nclass Combination\n{\npublic:\n  vector<Mint<MOD>> inv, fact, factinv;\n  Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n  {\n    inv[1] = 1;\n    for (auto i{2LL}; i < MAX_SIZE; i++)\n    {\n      inv[i] = (-inv[MOD % i]) * (MOD / i);\n    }\n    fact[0] = factinv[0] = 1;\n    for (auto i{1LL}; i < MAX_SIZE; i++)\n    {\n      fact[i] = Mint<MOD>(i) * fact[i - 1];\n      factinv[i] = inv[i] * factinv[i - 1];\n    }\n  }\n  Mint<MOD> operator()(int n, int k)\n  {\n    if (n >= 0 && k >= 0 && n - k >= 0)\n    {\n      return fact[n] * factinv[k] * factinv[n - k];\n    }\n    return 0;\n  }\n  Mint<MOD> catalan(int x, int y)\n  {\n    return (*this)(x + y, y) - (*this)(x + y, y - 1);\n  }\n};\n// ----- for C++14 -----\nusing mint = Mint<MOD>;\nusing combination = Combination<MOD, MAX_SIZE>;\ntemplate <typename T>\nT gcd(T x, T y) { return y ? gcd(y, x % y) : x; }\ntemplate <typename T>\nT lcm(T x, T y) { return x / gcd(x, y) * y; }\n// ----- for C++17 -----\ntemplate <typename T>\nint popcount(T x) // C++20\n{\n  int ans{0};\n  while (x != 0)\n  {\n    ans += x & 1;\n    x >>= 1;\n  }\n  return ans;\n}\n// ----- Infty -----\ntemplate <typename T>\nconstexpr T Infty() { return numeric_limits<T>::max(); }\ntemplate <typename T>\nconstexpr T mInfty() { return numeric_limits<T>::min(); }\n// ----- frequently used constexpr -----\n// constexpr double epsilon{1e-10};\n// constexpr ll infty{1'000'000'000'000'010LL}; // or\n// constexpr int infty{1'000'000'010};\n// constexpr int dx[4] = {1, 0, -1, 0};\n// constexpr int dy[4] = {0, 1, 0, -1};\n// ----- Yes() and No() -----\nvoid Yes()\n{\n  cout << \"Yes\" << endl;\n  exit(0);\n}\nvoid No()\n{\n  cout << \"No\" << endl;\n  exit(0);\n}\n\n// ----- Solve -----\n\nclass Solve\n{\n\npublic:\n  Solve()\n  {\n  }\n\n  void flush()\n  {\n  }\n\nprivate:\n};\n\n// ----- SegTree -----\n// Referring to the following great materials.\n//  - tsutaj-san's article: https://tsutaj.hatenablog.com/entry/2017/03/30/224339\n//  - drken-san's article: https://drken1215.hatenablog.com/entry/2019/02/19/110200\n//  - tsutaj-san's libary: https://tsutaj.github.io/cpp_library/library/structure/strc_021_dynamic_lazy_segtree.cpp.html\n// Many thanks to them.\n\ntemplate <typename Monoid, typename Action>\nclass SegTree\n{\n  struct SegNode\n  {\n    bool need_update;\n    unique_ptr<SegNode> left, right;\n    Monoid value;\n    Action lazy_value;\n\n    SegNode() {}\n    SegNode(Monoid value, Action lazy_value) : need_update{false}, left{nullptr}, right{nullptr}, value{value}, lazy_value{lazy_value} {}\n  };\n\n  using FuncAction = function<void(Monoid &, Action)>;\n  using FuncMonoid = function<Monoid(Monoid, Monoid)>;\n  using FuncLazy = function<void(Action &, Action)>;\n  using FuncIndex = function<Action(Action, int)>;\n\n  // fields\n  int N;\n  unique_ptr<SegNode> root;\n  // unities\n  Monoid unity_monoid;\n  Action unity_action;\n  // functions\n  FuncAction func_update;\n  FuncMonoid func_combine;\n  FuncLazy func_lazy;\n  FuncIndex func_accumulate;\n\npublic:\n  SegTree() {}\n  SegTree(\n      int n, Monoid unity_monoid, Action unity_action,\n      FuncAction func_update,\n      FuncMonoid func_combine,\n      FuncLazy func_lazy,\n      FuncIndex func_accumulate)\n      : N{1}, root{make_unique<SegNode>(unity_monoid, unity_action)},\n        unity_monoid(unity_monoid), unity_action(unity_action),\n        func_update(func_update),\n        func_combine(func_combine),\n        func_lazy(func_lazy),\n        func_accumulate(func_accumulate)\n  {\n    while (N < n)\n    {\n      N <<= 1;\n    }\n  }\n\n  void update(int a, int b, Action const &x) { update(root.get(), a, b, x, 0, N); }\n  void update(int a, Action const &x) { update(a, a + 1, x); }\n  Monoid query(int a, int b) { return query(root.get(), a, b, 0, N); }\n  Monoid query(int a) { return query(a, a + 1); }\n  Monoid operator[](size_t i) { return query(static_cast<int>(i)); }\n\nprivate:\n  void node_maker(unique_ptr<SegNode> &pt) const\n  {\n    if (!pt)\n    {\n      pt = make_unique<SegNode>(unity_monoid, unity_action);\n    }\n  }\n\n  void evaluate(SegNode *node, int l, int r)\n  {\n    if (!node->need_update)\n    {\n      return;\n    }\n    func_update(node->value, func_accumulate(node->lazy_value, r - l));\n    if (r - l > 1)\n    {\n      node_maker(node->left);\n      func_lazy(node->left->lazy_value, node->lazy_value);\n      node->left->need_update = true;\n      node_maker(node->right);\n      func_lazy(node->right->lazy_value, node->lazy_value);\n      node->right->need_update = true;\n    }\n    node->lazy_value = unity_action;\n    node->need_update = false;\n  }\n\n  void update(SegNode *node, int a, int b, Action const &x, int l, int r)\n  {\n    evaluate(node, l, r);\n    if (b <= l || r <= a)\n    {\n      return;\n    }\n    if (a <= l && r <= b)\n    {\n      func_lazy(node->lazy_value, x);\n      node->need_update = true;\n      evaluate(node, l, r);\n    }\n    else\n    {\n      auto mid{(l + r) >> 1};\n      node_maker(node->left);\n      update(node->left.get(), a, b, x, l, mid);\n      node_maker(node->right);\n      update(node->right.get(), a, b, x, mid, r);\n      node->value = func_combine(node->left->value, node->right->value);\n    }\n  }\n\n  Monoid query(SegNode *node, int a, int b, int l, int r)\n  {\n    if (b <= l || r <= a)\n    {\n      return unity_monoid;\n    }\n    evaluate(node, l, r);\n    if (a <= l && r <= b)\n    {\n      return node->value;\n    }\n    auto mid{(l + r) >> 1};\n    auto vl{(node->left ? query(node->left.get(), a, b, l, mid) : unity_monoid)};\n    auto vr{(node->right ? query(node->right.get(), a, b, mid, r) : unity_monoid)};\n    return func_combine(vl, vr);\n  }\n};\n\n// ----- RangePlusQuery -----\n//  - update(i, x) : a[i] += x;,\n//  - update(s, t, x) : a[i] += x; for all i \\in [s, t),\n//  - query(i) : return a[i];,\n//  - query(s, t) : return the sum a[i] where i runs on [s, t).\n\n// ----- RangeSumQuery -----\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=DSL_2_B&lang=ja\n//  - update(i, x) : a[i] += x;,\n//  - query(s, t) : return the sum a[i] where i runs on [s, t).\n\n// ----- RangeAddQuery -----\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=DSL_2_E&lang=ja\n//  - update(s, t, x) : a[i] += x; for all i \\in [s, t),\n//  - query(i) : return a[i].\n\n// ----- RSU_RAU -----\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=DSL_2_G&lang=ja\n//  - update(s, t, x) : a[i] += x; for all i \\in [s, t),\n//  - query(s, t) : return the sum a[i] where i runs on [s, t).\n\ntemplate <typename Monoid>\nSegTree<Monoid, Monoid> RangePlusQuery(int N, Monoid const &monoid_zero)\n{\n  using Action = Monoid;\n  return SegTree<Monoid, Action>{\n      N, monoid_zero, monoid_zero,\n      [](Monoid &x, Action y) { x += y; },\n      [](Monoid x, Monoid y) { return x + y; },\n      [](Action &x, Action y) { return x += y; },\n      [](Action x, int y) { return x * static_cast<Action>(y); }};\n}\n\ntemplate <typename Monoid>\nSegTree<Monoid, Monoid> RangePlusQuery(int N)\n{\n  return RangePlusQuery<Monoid>(N, 0);\n}\n\n// ----- RangeMinQuery -----\n//  - update(i, x) : a[i] = x;,\n//  - update(s, t, x) : a[i] = x; for all i \\in [s, t),\n//  - query(i) : return a[i];,\n//  - query(s, t) : return the minimum of a[i] where i runs on [s, t).\n\n// ----- RangeMinimumQuery -----\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=DSL_2_A&lang=ja\n//  - update(i, x) : a[i] = x;,\n//  - query(s, t) : return the minimum of a[i] where i runs on [s, t).\n\n// ----- RangeUpdateQuery -----\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=DSL_2_D&lang=ja\n//  - update(s, t, x) : a[i] = x; for all i \\in [s, t),\n//  - query(i) : return a[i].\n\n// ----- RMQ_RUQ -----\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=DSL_2_F&lang=ja\n//  - update(s, t, x) : a[i] = x; for all i \\in [s, t),\n//  - query(s, t) : return the minimum of a[i] where i runs on [s, t).\n\ntemplate <typename Monoid>\nSegTree<Monoid, Monoid> RangeMinQuery(int N, Monoid const &monoid_infty)\n{\n  using Action = Monoid;\n  return SegTree<Monoid, Action>{\n      N, monoid_infty, monoid_infty,\n      [](Monoid &x, Action y) { x = y; },\n      [](Monoid x, Monoid y) { return min(x, y); },\n      [](Action &x, Action y) { return x = y; },\n      [](Action x, int) { return x; }};\n}\n\ntemplate <typename Monoid>\nSegTree<Monoid, Monoid> RangeMinQuery(int N)\n{\n  return RangeMinQuery<Monoid>(N, numeric_limits<Monoid>::max());\n}\n\n// ----- RMQ_RAQ -----\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=DSL_2_H&lang=ja\n//  - update(s, t, x) : a[i] += x; for all i \\in [s, t),\n//  - query(s, t) : return the minimum of a[i] where i runs on [s, t).\n// update should be called as follows.\n// tree.update(s, t, make_tuple(x, true));\n\ntemplate <typename Monoid>\nSegTree<Monoid, tuple<Monoid, bool>> RMQ_RAQ(int N, Monoid const &monoid_zero, Monoid const &monoid_infty)\n{\n  using Action = tuple<Monoid, bool>;\n  auto tree{SegTree<Monoid, Action>{\n      N, monoid_infty, Action{monoid_zero, true},\n      [](Monoid &x, Action y) {\n        if (get<1>(y))\n        {\n          x += get<0>(y);\n        }\n        else\n        {\n          x = get<0>(y);\n        }\n      },\n      [](Monoid x, Monoid y) { return min(x, y); },\n      [](Action &x, Action y) {\n        if (get<1>(y))\n        {\n          get<0>(x) += get<0>(y);\n        }\n        else\n        {\n          x = y;\n        }\n      },\n      [](Action x, int) { return x; }}};\n  tree.update(0, N, Action{monoid_zero, false});\n  return tree;\n}\n\ntemplate <typename Monoid>\nSegTree<Monoid, tuple<Monoid, bool>> RMQ_RAQ(int N)\n{\n  return RMQ_RAQ<Monoid>(N, 0, numeric_limits<Monoid>::max());\n}\n\n// ----- RSQ_RUQ -----\n// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=DSL_2_I&lang=ja\n//  - update(s, t, x) : a[i] = x; for all i \\in [s, t),\n//  - query(s, t) : return the sum of a[i] where i runs on [s, t).\n\ntemplate <typename Monoid>\nSegTree<Monoid, Monoid> RSQ_RUQ(int N, Monoid const &monoid_zero)\n{\n  using Action = Monoid;\n  return SegTree<Monoid, Action>{\n      N, monoid_zero, monoid_zero,\n      [](Monoid &x, Action y) { x = y; },\n      [](Monoid x, Monoid y) { return x + y; },\n      [](Action &x, Action y) { return x = y; },\n      [](Action x, int y) { return x * static_cast<Action>(y); }};\n}\n\ntemplate <typename Monoid>\nSegTree<Monoid, Monoid> RSQ_RUQ(int N)\n{\n  return RSQ_RUQ<Monoid>(N, 0);\n}\n\n// ----- main() -----\n\n/*\nint main()\n{\n  Solve solve;\n  solve.flush();\n}\n*/\n\nint main()\n{\n  int N;\n  cin >> N;\n  vector<int> A(N);\n  for (auto i{0}; i < N; ++i)\n  {\n    cin >> A[i];\n    A[i]--;\n  }\n  auto tree{RangePlusQuery<int>(N)};\n  int ans{0};\n  for (auto i{0}; i < N; ++i)\n  {\n    if (tree.query(0, A[i]) == 0)\n    {\n      ++ans;\n    }\n    tree.update(A[i], 1);\n  }\n  cout << ans << endl;\n}\n", "meta": {"hexsha": "c5fda34403fd08316cd3e9ed2dff37f31785bdec", "size": 14441, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "2020/0119_ABC152/C.cpp", "max_stars_repo_name": "kazunetakahashi/atcoder", "max_stars_repo_head_hexsha": "16ce65829ccc180260b19316e276c2fcf6606c53", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-03-24T14:06:29.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-17T21:16:36.000Z", "max_issues_repo_path": "2020/0119_ABC152/C.cpp", "max_issues_repo_name": "kazunetakahashi/atcoder", "max_issues_repo_head_hexsha": "16ce65829ccc180260b19316e276c2fcf6606c53", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2020/0119_ABC152/C.cpp", "max_forks_repo_name": "kazunetakahashi/atcoder", "max_forks_repo_head_hexsha": "16ce65829ccc180260b19316e276c2fcf6606c53", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-22T17:27:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-22T17:27:09.000Z", "avg_line_length": 25.8336314848, "max_line_length": 137, "alphanum_fraction": 0.5789072779, "num_tokens": 4642, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397349, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.48916469958148545}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n\r\n// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef BOOST_GEOMETRY_STRATEGIES_CARTESIAN_INTERSECTION_HPP\r\n#define BOOST_GEOMETRY_STRATEGIES_CARTESIAN_INTERSECTION_HPP\r\n\r\n#include <algorithm>\r\n\r\n#include <boost/geometry/core/exception.hpp>\r\n\r\n#include <boost/geometry/geometries/concepts/point_concept.hpp>\r\n#include <boost/geometry/geometries/concepts/segment_concept.hpp>\r\n\r\n#include <boost/geometry/arithmetic/determinant.hpp>\r\n#include <boost/geometry/algorithms/detail/assign_values.hpp>\r\n\r\n#include <boost/geometry/util/math.hpp>\r\n#include <boost/geometry/util/select_calculation_type.hpp>\r\n\r\n// Temporary / will be Strategy as template parameter\r\n#include <boost/geometry/strategies/side.hpp>\r\n#include <boost/geometry/strategies/cartesian/side_by_triangle.hpp>\r\n\r\n#include <boost/geometry/strategies/side_info.hpp>\r\n\r\n\r\nnamespace boost { namespace geometry\r\n{\r\n\r\n\r\nnamespace strategy { namespace intersection\r\n{\r\n\r\n\r\n#ifndef DOXYGEN_NO_DETAIL\r\nnamespace detail\r\n{\r\n\r\ntemplate <std::size_t Dimension, typename Segment, typename T>\r\nstatic inline void segment_arrange(Segment const& s, T& s_1, T& s_2, bool& swapped)\r\n{\r\n    s_1 = get<0, Dimension>(s);\r\n    s_2 = get<1, Dimension>(s);\r\n    if (s_1 > s_2)\r\n    {\r\n        std::swap(s_1, s_2);\r\n        swapped = true;\r\n    }\r\n}\r\n\r\ntemplate <std::size_t Index, typename Segment>\r\ninline typename geometry::point_type<Segment>::type get_from_index(\r\n            Segment const& segment)\r\n{\r\n    typedef typename geometry::point_type<Segment>::type point_type;\r\n    point_type point;\r\n    geometry::detail::assign::assign_point_from_index\r\n        <\r\n            Segment, point_type, Index, 0, dimension<Segment>::type::value\r\n        >::apply(segment, point);\r\n    return point;\r\n}\r\n\r\n}\r\n#endif\r\n\r\n/***\r\ntemplate <typename T>\r\ninline std::string rdebug(T const& value)\r\n{\r\n    if (math::equals(value, 0)) return \"'0'\";\r\n    if (math::equals(value, 1)) return \"'1'\";\r\n    if (value < 0) return \"<0\";\r\n    if (value > 1) return \">1\";\r\n    return \"<0..1>\";\r\n}\r\n***/\r\n\r\n/*!\r\n    \\see http://mathworld.wolfram.com/Line-LineIntersection.html\r\n */\r\ntemplate <typename Policy, typename CalculationType = void>\r\nstruct relate_cartesian_segments\r\n{\r\n    typedef typename Policy::return_type return_type;\r\n    typedef typename Policy::segment_type1 segment_type1;\r\n    typedef typename Policy::segment_type2 segment_type2;\r\n\r\n    //typedef typename point_type<segment_type1>::type point_type;\r\n    //BOOST_CONCEPT_ASSERT( (concept::Point<point_type>) );\r\n\r\n    BOOST_CONCEPT_ASSERT( (concept::ConstSegment<segment_type1>) );\r\n    BOOST_CONCEPT_ASSERT( (concept::ConstSegment<segment_type2>) );\r\n\r\n    typedef typename select_calculation_type\r\n        <segment_type1, segment_type2, CalculationType>::type coordinate_type;\r\n\r\n    /// Relate segments a and b\r\n    static inline return_type apply(segment_type1 const& a, segment_type2 const& b)\r\n    {\r\n        coordinate_type const dx_a = get<1, 0>(a) - get<0, 0>(a); // distance in x-dir\r\n        coordinate_type const dx_b = get<1, 0>(b) - get<0, 0>(b);\r\n        coordinate_type const dy_a = get<1, 1>(a) - get<0, 1>(a); // distance in y-dir\r\n        coordinate_type const dy_b = get<1, 1>(b) - get<0, 1>(b);\r\n        return apply(a, b, dx_a, dy_a, dx_b, dy_b);\r\n    }\r\n\r\n\r\n    // Relate segments a and b using precalculated differences.\r\n    // This can save two or four subtractions in many cases\r\n    static inline return_type apply(segment_type1 const& a, segment_type2 const& b,\r\n            coordinate_type const& dx_a, coordinate_type const& dy_a,\r\n            coordinate_type const& dx_b, coordinate_type const& dy_b)\r\n    {\r\n        typedef side::side_by_triangle<coordinate_type> side;\r\n        side_info sides;\r\n\r\n        coordinate_type const zero = 0;\r\n        bool const a_is_point = math::equals(dx_a, zero) && math::equals(dy_a, zero);\r\n        bool const b_is_point = math::equals(dx_b, zero) && math::equals(dy_b, zero);\r\n\r\n        if(a_is_point && b_is_point)\r\n        {\r\n            if(math::equals(get<1,0>(a), get<1,0>(b)) && math::equals(get<1,1>(a), get<1,1>(b)))\r\n            {\r\n                 Policy::degenerate(a, true);\r\n            }\r\n            else\r\n            {\r\n                return Policy::disjoint();                \r\n            }\r\n        }\r\n\r\n        bool collinear_use_first = math::abs(dx_a) + math::abs(dx_b) >= math::abs(dy_a) + math::abs(dy_b);\r\n\r\n        sides.set<0>\r\n            (\r\n                side::apply(detail::get_from_index<0>(b)\r\n                    , detail::get_from_index<1>(b)\r\n                    , detail::get_from_index<0>(a)),\r\n                side::apply(detail::get_from_index<0>(b)\r\n                    , detail::get_from_index<1>(b)\r\n                    , detail::get_from_index<1>(a))\r\n            );\r\n        sides.set<1>\r\n            (\r\n                side::apply(detail::get_from_index<0>(a)\r\n                    , detail::get_from_index<1>(a)\r\n                    , detail::get_from_index<0>(b)),\r\n                side::apply(detail::get_from_index<0>(a)\r\n                    , detail::get_from_index<1>(a)\r\n                    , detail::get_from_index<1>(b))\r\n            );\r\n\r\n        bool collinear = sides.collinear();\r\n\r\n        robustness_verify_collinear(a, b, a_is_point, b_is_point, sides, collinear);\r\n        robustness_verify_meeting(a, b, sides, collinear, collinear_use_first);\r\n\r\n        if (sides.same<0>() || sides.same<1>())\r\n        {\r\n            // Both points are at same side of other segment, we can leave\r\n            if (robustness_verify_same_side(a, b, sides))\r\n            {\r\n                return Policy::disjoint();\r\n            }\r\n        }\r\n\r\n        // Degenerate cases: segments of single point, lying on other segment, non disjoint\r\n        if (a_is_point)\r\n        {\r\n            return Policy::degenerate(a, true);\r\n        }\r\n        if (b_is_point)\r\n        {\r\n            return Policy::degenerate(b, false);\r\n        }\r\n\r\n        typedef typename select_most_precise\r\n            <\r\n                coordinate_type, double\r\n            >::type promoted_type;\r\n\r\n        // r: ratio 0-1 where intersection divides A/B\r\n        // (only calculated for non-collinear segments)\r\n        promoted_type r;\r\n        if (! collinear)\r\n        {\r\n            // Calculate determinants - Cramers rule\r\n            coordinate_type const wx = get<0, 0>(a) - get<0, 0>(b);\r\n            coordinate_type const wy = get<0, 1>(a) - get<0, 1>(b);\r\n            coordinate_type const d = geometry::detail::determinant<coordinate_type>(dx_a, dy_a, dx_b, dy_b);\r\n            coordinate_type const da = geometry::detail::determinant<coordinate_type>(dx_b, dy_b, wx, wy);\r\n\r\n            coordinate_type const zero = coordinate_type();\r\n            if (math::equals(d, zero))\r\n            {\r\n                // This is still a collinear case (because of FP imprecision this can occur here)\r\n                // sides.debug();\r\n                sides.set<0>(0,0);\r\n                sides.set<1>(0,0);\r\n                collinear = true;\r\n            }\r\n            else\r\n            {\r\n                r = promoted_type(da) / promoted_type(d);\r\n\r\n                if (! robustness_verify_r(a, b, r))\r\n                {\r\n                    return Policy::disjoint();\r\n                }\r\n\r\n                robustness_handle_meeting(a, b, sides, dx_a, dy_a, wx, wy, d, r);\r\n\r\n                if (robustness_verify_disjoint_at_one_collinear(a, b, sides))\r\n                {\r\n                    return Policy::disjoint();\r\n                }\r\n\r\n            }\r\n        }\r\n\r\n        if(collinear)\r\n        {\r\n            if (collinear_use_first)\r\n            {\r\n                return relate_collinear<0>(a, b);\r\n            }\r\n            else\r\n            {\r\n                // Y direction contains larger segments (maybe dx is zero)\r\n                return relate_collinear<1>(a, b);\r\n            }\r\n        }\r\n\r\n        return Policy::segments_intersect(sides, r,\r\n            dx_a, dy_a, dx_b, dy_b,\r\n            a, b);\r\n    }\r\n\r\nprivate :\r\n\r\n\r\n    // Ratio should lie between 0 and 1\r\n    // Also these three conditions might be of FP imprecision, the segments were actually (nearly) collinear\r\n    template <typename T>\r\n    static inline bool robustness_verify_r(\r\n                segment_type1 const& a, segment_type2 const& b,\r\n                T& r)\r\n    {\r\n        T const zero = 0;\r\n        T const one = 1;\r\n        if (r < zero || r > one)\r\n        {\r\n            if (verify_disjoint<0>(a, b) || verify_disjoint<1>(a, b))\r\n            {\r\n                // Can still be disjoint (even if not one is left or right from another)\r\n                // This is e.g. in case #snake4 of buffer test.\r\n                return false;\r\n            }\r\n\r\n            //std::cout << \"ROBUSTNESS: correction of r \" << r << std::endl;\r\n            // sides.debug();\r\n\r\n            // ROBUSTNESS: the r value can in epsilon-cases much larger than 1, while (with perfect arithmetic)\r\n            // it should be one. It can be 1.14 or even 1.98049 or 2 (while still intersecting)\r\n\r\n            // If segments are crossing (we can see that with the sides)\r\n            // and one is inside the other, there must be an intersection point.\r\n            // We correct for that.\r\n            // This is (only) in case #ggl_list_20110820_christophe in unit tests\r\n\r\n            // If segments are touching (two sides zero), of course they should intersect\r\n            // This is (only) in case #buffer_rt_i in the unit tests)\r\n\r\n            // If one touches in the middle, they also should intersect (#buffer_rt_j)\r\n\r\n            // Note that even for ttmath r is occasionally > 1, e.g. 1.0000000000000000000000036191231203575\r\n\r\n            if (r > one)\r\n            {\r\n                r = one;\r\n            }\r\n            else if (r < zero)\r\n            {\r\n                r = zero;\r\n            }\r\n        }\r\n        return true;\r\n    }\r\n\r\n    static inline void robustness_verify_collinear(\r\n                segment_type1 const& a, segment_type2 const& b,\r\n                bool a_is_point, bool b_is_point, \r\n                side_info& sides,\r\n                bool& collinear)\r\n    {\r\n        if ((sides.zero<0>() && ! b_is_point && ! sides.zero<1>()) || (sides.zero<1>() && ! a_is_point && ! sides.zero<0>()))\r\n        {\r\n            // If one of the segments is collinear, the other must be as well.\r\n            // So handle it as collinear.\r\n            // (In float/double epsilon margins it can easily occur that one or two of them are -1/1)\r\n            // sides.debug();\r\n            sides.set<0>(0,0);\r\n            sides.set<1>(0,0);\r\n            collinear = true;\r\n        }\r\n    }\r\n\r\n    static inline void robustness_verify_meeting(\r\n                segment_type1 const& a, segment_type2 const& b,\r\n                side_info& sides,\r\n                bool& collinear, bool& collinear_use_first)\r\n    {\r\n        if (sides.meeting())\r\n        {\r\n            // If two segments meet each other at their segment-points, two sides are zero,\r\n            // the other two are not (unless collinear but we don't mean those here).\r\n            // However, in near-epsilon ranges it can happen that two sides are zero\r\n            // but they do not meet at their segment-points.\r\n            // In that case they are nearly collinear and handled as such.\r\n            if (! point_equals\r\n                    (\r\n                        select(sides.zero_index<0>(), a),\r\n                        select(sides.zero_index<1>(), b)\r\n                    )\r\n                )\r\n            {\r\n                sides.set<0>(0,0);\r\n                sides.set<1>(0,0);\r\n                collinear = true;\r\n\r\n                if (collinear_use_first && analyse_equal<0>(a, b))\r\n                {\r\n                    collinear_use_first = false;\r\n                }\r\n                else if (! collinear_use_first && analyse_equal<1>(a, b))\r\n                {\r\n                    collinear_use_first = true;\r\n                }\r\n\r\n            }\r\n        }\r\n    }\r\n\r\n    // Verifies and if necessary correct missed touch because of robustness\r\n    // This is the case at multi_polygon_buffer unittest #rt_m\r\n    static inline bool robustness_verify_same_side(\r\n                segment_type1 const& a, segment_type2 const& b,\r\n                side_info& sides)\r\n    {\r\n        int corrected = 0;\r\n        if (sides.one_touching<0>())\r\n        {\r\n            if (point_equals(\r\n                        select(sides.zero_index<0>(), a),\r\n                        select(0, b)\r\n                    ))\r\n            {\r\n                sides.correct_to_zero<1, 0>();\r\n                corrected = 1;\r\n            }\r\n            if (point_equals\r\n                    (\r\n                        select(sides.zero_index<0>(), a),\r\n                        select(1, b)\r\n                    ))\r\n            {\r\n                sides.correct_to_zero<1, 1>();\r\n                corrected = 2;\r\n            }\r\n        }\r\n        else if (sides.one_touching<1>())\r\n        {\r\n            if (point_equals(\r\n                        select(sides.zero_index<1>(), b),\r\n                        select(0, a)\r\n                    ))\r\n            {\r\n                sides.correct_to_zero<0, 0>();\r\n                corrected = 3;\r\n            }\r\n            if (point_equals\r\n                    (\r\n                        select(sides.zero_index<1>(), b),\r\n                        select(1, a)\r\n                    ))\r\n            {\r\n                sides.correct_to_zero<0, 1>();\r\n                corrected = 4;\r\n            }\r\n        }\r\n\r\n        return corrected == 0;\r\n    }\r\n\r\n    static inline bool robustness_verify_disjoint_at_one_collinear(\r\n                segment_type1 const& a, segment_type2 const& b,\r\n                side_info const& sides)\r\n    {\r\n        if (sides.one_of_all_zero())\r\n        {\r\n            if (verify_disjoint<0>(a, b) || verify_disjoint<1>(a, b))\r\n            {\r\n                return true;\r\n            }\r\n        }\r\n        return false;\r\n    }\r\n\r\n\r\n    // If r is one, or zero, segments should meet and their endpoints.\r\n    // Robustness issue: check if this is really the case.\r\n    // It turns out to be no problem, see buffer test #rt_s1 (and there are many cases generated)\r\n    // It generates an \"ends in the middle\" situation which is correct.\r\n    template <typename T, typename R>\r\n    static inline void robustness_handle_meeting(segment_type1 const& a, segment_type2 const& b,\r\n                side_info& sides,\r\n                T const& dx_a, T const& dy_a, T const& wx, T const& wy,\r\n                T const& d, R const& r)\r\n    {\r\n        return;\r\n\r\n        T const db = geometry::detail::determinant<T>(dx_a, dy_a, wx, wy);\r\n\r\n        R const zero = 0;\r\n        R const one = 1;\r\n        if (math::equals(r, zero) || math::equals(r, one))\r\n        {\r\n            R rb = db / d;\r\n            if (rb <= 0 || rb >= 1 || math::equals(rb, 0) || math::equals(rb, 1))\r\n            {\r\n                if (sides.one_zero<0>() && ! sides.one_zero<1>()) // or vice versa\r\n                {\r\n#if defined(BOOST_GEOMETRY_COUNT_INTERSECTION_EQUAL)\r\n                    extern int g_count_intersection_equal;\r\n                    g_count_intersection_equal++;\r\n#endif\r\n                    sides.debug();\r\n                    std::cout << \"E r=\" << r << \" r.b=\" << rb << \" \";\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n    template <std::size_t Dimension>\r\n    static inline bool verify_disjoint(segment_type1 const& a,\r\n                    segment_type2 const& b)\r\n    {\r\n        coordinate_type a_1, a_2, b_1, b_2;\r\n        bool a_swapped = false, b_swapped = false;\r\n        detail::segment_arrange<Dimension>(a, a_1, a_2, a_swapped);\r\n        detail::segment_arrange<Dimension>(b, b_1, b_2, b_swapped);\r\n        return math::smaller(a_2, b_1) || math::larger(a_1, b_2);\r\n    }\r\n\r\n    template <typename Segment>\r\n    static inline typename point_type<Segment>::type select(int index, Segment const& segment)\r\n    {\r\n        return index == 0 \r\n            ? detail::get_from_index<0>(segment)\r\n            : detail::get_from_index<1>(segment)\r\n            ;\r\n    }\r\n\r\n    // We cannot use geometry::equals here. Besides that this will be changed\r\n    // to compare segment-coordinate-values directly (not necessary to retrieve point first)\r\n    template <typename Point1, typename Point2>\r\n    static inline bool point_equals(Point1 const& point1, Point2 const& point2)\r\n    {\r\n        return math::equals(get<0>(point1), get<0>(point2))\r\n            && math::equals(get<1>(point1), get<1>(point2))\r\n            ;\r\n    }\r\n\r\n    // We cannot use geometry::equals here. Besides that this will be changed\r\n    // to compare segment-coordinate-values directly (not necessary to retrieve point first)\r\n    template <typename Point1, typename Point2>\r\n    static inline bool point_equality(Point1 const& point1, Point2 const& point2,\r\n                    bool& equals_0, bool& equals_1)\r\n    {\r\n        equals_0 = math::equals(get<0>(point1), get<0>(point2));\r\n        equals_1 = math::equals(get<1>(point1), get<1>(point2));\r\n        return equals_0 && equals_1;\r\n    }\r\n\r\n    template <std::size_t Dimension>\r\n    static inline bool analyse_equal(segment_type1 const& a, segment_type2 const& b)\r\n    {\r\n        coordinate_type const a_1 = geometry::get<0, Dimension>(a);\r\n        coordinate_type const a_2 = geometry::get<1, Dimension>(a);\r\n        coordinate_type const b_1 = geometry::get<0, Dimension>(b);\r\n        coordinate_type const b_2 = geometry::get<1, Dimension>(b);\r\n        return math::equals(a_1, b_1)\r\n            || math::equals(a_2, b_1)\r\n            || math::equals(a_1, b_2)\r\n            || math::equals(a_2, b_2)\r\n            ;\r\n    }\r\n\r\n    template <std::size_t Dimension>\r\n    static inline return_type relate_collinear(segment_type1 const& a,\r\n                                               segment_type2 const& b)\r\n    {\r\n        coordinate_type a_1, a_2, b_1, b_2;\r\n        bool a_swapped = false, b_swapped = false;\r\n        detail::segment_arrange<Dimension>(a, a_1, a_2, a_swapped);\r\n        detail::segment_arrange<Dimension>(b, b_1, b_2, b_swapped);\r\n        if (math::smaller(a_2, b_1) || math::larger(a_1, b_2))\r\n        //if (a_2 < b_1 || a_1 > b_2)\r\n        {\r\n            return Policy::disjoint();\r\n        }\r\n        return relate_collinear(a, b, a_1, a_2, b_1, b_2, a_swapped, b_swapped);\r\n    }\r\n\r\n    /// Relate segments known collinear\r\n    static inline return_type relate_collinear(segment_type1 const& a\r\n            , segment_type2 const& b\r\n            , coordinate_type a_1, coordinate_type a_2\r\n            , coordinate_type b_1, coordinate_type b_2\r\n            , bool a_swapped, bool b_swapped)\r\n    {\r\n        // All ca. 150 lines are about collinear rays\r\n        // The intersections, if any, are always boundary points of the segments. No need to calculate anything.\r\n        // However we want to find out HOW they intersect, there are many cases.\r\n        // Most sources only provide the intersection (above) or that there is a collinearity (but not the points)\r\n        // or some spare sources give the intersection points (calculated) but not how they align.\r\n        // This source tries to give everything and still be efficient.\r\n        // It is therefore (and because of the extensive clarification comments) rather long...\r\n\r\n        // \\see http://mpa.itc.it/radim/g50history/CMP/4.2.1-CERL-beta-libes/file475.txt\r\n        // \\see http://docs.codehaus.org/display/GEOTDOC/Point+Set+Theory+and+the+DE-9IM+Matrix\r\n        // \\see http://mathworld.wolfram.com/Line-LineIntersection.html\r\n\r\n        // Because of collinearity the case is now one-dimensional and can be checked using intervals\r\n        // This function is called either horizontally or vertically\r\n        // We get then two intervals:\r\n        // a_1-------------a_2 where a_1 < a_2\r\n        // b_1-------------b_2 where b_1 < b_2\r\n        // In all figures below a_1/a_2 denotes arranged intervals, a1-a2 or a2-a1 are still unarranged\r\n\r\n        // Handle \"equal\", in polygon neighbourhood comparisons a common case\r\n\r\n        bool const opposite = a_swapped ^ b_swapped;\r\n        bool const both_swapped = a_swapped && b_swapped;\r\n\r\n        // Check if segments are equal or opposite equal...\r\n        bool const swapped_a1_eq_b1 = math::equals(a_1, b_1);\r\n        bool const swapped_a2_eq_b2 = math::equals(a_2, b_2);\r\n\r\n        if (swapped_a1_eq_b1 && swapped_a2_eq_b2)\r\n        {\r\n            return Policy::segment_equal(a, opposite);\r\n        }\r\n\r\n        bool const swapped_a2_eq_b1 = math::equals(a_2, b_1);\r\n        bool const swapped_a1_eq_b2 = math::equals(a_1, b_2);\r\n\r\n        bool const a1_eq_b1 = both_swapped ? swapped_a2_eq_b2 : a_swapped ? swapped_a2_eq_b1 : b_swapped ? swapped_a1_eq_b2 : swapped_a1_eq_b1;\r\n        bool const a2_eq_b2 = both_swapped ? swapped_a1_eq_b1 : a_swapped ? swapped_a1_eq_b2 : b_swapped ? swapped_a2_eq_b1 : swapped_a2_eq_b2;\r\n\r\n        bool const a1_eq_b2 = both_swapped ? swapped_a2_eq_b1 : a_swapped ? swapped_a2_eq_b2 : b_swapped ? swapped_a1_eq_b1 : swapped_a1_eq_b2;\r\n        bool const a2_eq_b1 = both_swapped ? swapped_a1_eq_b2 : a_swapped ? swapped_a1_eq_b1 : b_swapped ? swapped_a2_eq_b2 : swapped_a2_eq_b1;\r\n\r\n\r\n\r\n\r\n        // The rest below will return one or two intersections.\r\n        // The delegated class can decide which is the intersection point, or two, build the Intersection Matrix (IM)\r\n        // For IM it is important to know which relates to which. So this information is given,\r\n        // without performance penalties to intersection calculation\r\n\r\n        bool const has_common_points = swapped_a1_eq_b1 || swapped_a1_eq_b2 || swapped_a2_eq_b1 || swapped_a2_eq_b2;\r\n\r\n\r\n        // \"Touch\" -> one intersection point -> one but not two common points\r\n        // -------->             A (or B)\r\n        //         <----------   B (or A)\r\n        //        a_2==b_1         (b_2==a_1 or a_2==b1)\r\n\r\n        // The check a_2/b_1 is necessary because it excludes cases like\r\n        // ------->\r\n        //     --->\r\n        // ... which are handled lateron\r\n\r\n        // Corresponds to 4 cases, of which the equal points are determined above\r\n        // #1: a1---->a2 b1--->b2   (a arrives at b's border)\r\n        // #2: a2<----a1 b2<---b1   (b arrives at a's border)\r\n        // #3: a1---->a2 b2<---b1   (both arrive at each others border)\r\n        // #4: a2<----a1 b1--->b2   (no arrival at all)\r\n        // Where the arranged forms have two forms:\r\n        //    a_1-----a_2/b_1-------b_2 or reverse (B left of A)\r\n        if ((swapped_a2_eq_b1 || swapped_a1_eq_b2) && ! swapped_a1_eq_b1 && ! swapped_a2_eq_b2)\r\n        {\r\n            if (a2_eq_b1) return Policy::collinear_touch(get<1, 0>(a), get<1, 1>(a), 0, -1);\r\n            if (a1_eq_b2) return Policy::collinear_touch(get<0, 0>(a), get<0, 1>(a), -1, 0);\r\n            if (a2_eq_b2) return Policy::collinear_touch(get<1, 0>(a), get<1, 1>(a), 0, 0);\r\n            if (a1_eq_b1) return Policy::collinear_touch(get<0, 0>(a), get<0, 1>(a), -1, -1);\r\n        }\r\n\r\n\r\n        // \"Touch/within\" -> there are common points and also an intersection of interiors:\r\n        // Corresponds to many cases:\r\n        // #1a: a1------->a2  #1b:        a1-->a2\r\n        //          b1--->b2         b1------->b2\r\n        // #2a: a2<-------a1  #2b:        a2<--a1\r\n        //          b1--->b2         b1------->b2\r\n        // #3a: a1------->a2  #3b:        a1-->a2\r\n        //          b2<---b1         b2<-------b1\r\n        // #4a: a2<-------a1  #4b:        a2<--a1\r\n        //          b2<---b1         b2<-------b1\r\n\r\n        // Note: next cases are similar and handled by the code\r\n        // #4c: a1--->a2\r\n        //      b1-------->b2\r\n        // #4d: a1-------->a2\r\n        //      b1-->b2\r\n\r\n        // For case 1-4: a_1 < (b_1 or b_2) < a_2, two intersections are equal to segment B\r\n        // For case 5-8: b_1 < (a_1 or a_2) < b_2, two intersections are equal to segment A\r\n        if (has_common_points)\r\n        {\r\n            // Either A is in B, or B is in A, or (in case of robustness/equals)\r\n            // both are true, see below\r\n            bool a_in_b = (b_1 < a_1 && a_1 < b_2) || (b_1 < a_2 && a_2 < b_2);\r\n            bool b_in_a = (a_1 < b_1 && b_1 < a_2) || (a_1 < b_2 && b_2 < a_2);\r\n\r\n            if (a_in_b && b_in_a)\r\n            {\r\n                // testcase \"ggl_list_20110306_javier\"\r\n                // In robustness it can occur that a point of A is inside B AND a point of B is inside A,\r\n                // still while has_common_points is true (so one point equals the other).\r\n                // If that is the case we select on length.\r\n                coordinate_type const length_a = geometry::math::abs(a_1 - a_2);\r\n                coordinate_type const length_b = geometry::math::abs(b_1 - b_2);\r\n                if (length_a > length_b)\r\n                {\r\n                    a_in_b = false;\r\n                }\r\n                else\r\n                {\r\n                    b_in_a = false;\r\n                }\r\n            }\r\n\r\n            int const arrival_a = a_in_b ? 1 : -1;\r\n            if (a2_eq_b2) return Policy::collinear_interior_boundary_intersect(a_in_b ? a : b, a_in_b, 0, 0, false);\r\n            if (a1_eq_b2) return Policy::collinear_interior_boundary_intersect(a_in_b ? a : b, a_in_b, arrival_a, 0, true);\r\n            if (a2_eq_b1) return Policy::collinear_interior_boundary_intersect(a_in_b ? a : b, a_in_b, 0, -arrival_a, true);\r\n            if (a1_eq_b1) return Policy::collinear_interior_boundary_intersect(a_in_b ? a : b, a_in_b, arrival_a, -arrival_a, false);\r\n        }\r\n\r\n\r\n\r\n        // \"Inside\", a completely within b or b completely within a\r\n        // 2 cases:\r\n        // case 1:\r\n        //        a_1---a_2        -> take A's points as intersection points\r\n        //   b_1------------b_2\r\n        // case 2:\r\n        //   a_1------------a_2\r\n        //       b_1---b_2         -> take B's points\r\n        if (a_1 > b_1 && a_2 < b_2)\r\n        {\r\n            // A within B\r\n            return Policy::collinear_a_in_b(a, opposite);\r\n        }\r\n        if (b_1 > a_1 && b_2 < a_2)\r\n        {\r\n            // B within A\r\n            return Policy::collinear_b_in_a(b, opposite);\r\n        }\r\n\r\n\r\n        /*\r\n\r\n        Now that all cases with equal,touch,inside,disjoint,\r\n        degenerate are handled the only thing left is an overlap\r\n\r\n        Either a1 is between b1,b2\r\n        or a2 is between b1,b2 (a2 arrives)\r\n\r\n        Next table gives an overview.\r\n        The IP's are ordered following the line A1->A2\r\n\r\n             |                                 |\r\n             |          a_2 in between         |       a_1 in between\r\n             |                                 |\r\n        -----+---------------------------------+--------------------------\r\n             |   a1--------->a2                |       a1--------->a2\r\n             |          b1----->b2             |   b1----->b2\r\n             |   (b1,a2), a arrives            |   (a1,b2), b arrives\r\n             |                                 |\r\n        -----+---------------------------------+--------------------------\r\n        a sw.|   a2<---------a1*               |       a2<---------a1*\r\n             |           b1----->b2            |   b1----->b2\r\n             |   (a1,b1), no arrival           |   (b2,a2), a and b arrive\r\n             |                                 |\r\n        -----+---------------------------------+--------------------------\r\n             |   a1--------->a2                |       a1--------->a2\r\n        b sw.|           b2<-----b1            |   b2<-----b1\r\n             |   (b2,a2), a and b arrive       |   (a1,b1), no arrival\r\n             |                                 |\r\n        -----+---------------------------------+--------------------------\r\n        a sw.|    a2<---------a1*              |       a2<---------a1*\r\n        b sw.|            b2<-----b1           |   b2<-----b1\r\n             |   (a1,b2), b arrives            |   (b1,a2), a arrives\r\n             |                                 |\r\n        -----+---------------------------------+--------------------------\r\n        * Note that a_1 < a_2, and a1 <> a_1; if a is swapped,\r\n          the picture might seem wrong but it (supposed to be) is right.\r\n        */\r\n\r\n        if (b_1 < a_2 && a_2 < b_2)\r\n        {\r\n            // Left column, from bottom to top\r\n            return\r\n                both_swapped ? Policy::collinear_overlaps(get<0, 0>(a), get<0, 1>(a), get<1, 0>(b), get<1, 1>(b), -1,  1, opposite)\r\n                : b_swapped  ? Policy::collinear_overlaps(get<1, 0>(b), get<1, 1>(b), get<1, 0>(a), get<1, 1>(a),  1,  1, opposite)\r\n                : a_swapped  ? Policy::collinear_overlaps(get<0, 0>(a), get<0, 1>(a), get<0, 0>(b), get<0, 1>(b), -1, -1, opposite)\r\n                :              Policy::collinear_overlaps(get<0, 0>(b), get<0, 1>(b), get<1, 0>(a), get<1, 1>(a),  1, -1, opposite)\r\n                ;\r\n        }\r\n        if (b_1 < a_1 && a_1 < b_2)\r\n        {\r\n            // Right column, from bottom to top\r\n            return\r\n                both_swapped ? Policy::collinear_overlaps(get<0, 0>(b), get<0, 1>(b), get<1, 0>(a), get<1, 1>(a),  1, -1, opposite)\r\n                : b_swapped  ? Policy::collinear_overlaps(get<0, 0>(a), get<0, 1>(a), get<0, 0>(b), get<0, 1>(b), -1, -1, opposite)\r\n                : a_swapped  ? Policy::collinear_overlaps(get<1, 0>(b), get<1, 1>(b), get<1, 0>(a), get<1, 1>(a),  1,  1, opposite)\r\n                :              Policy::collinear_overlaps(get<0, 0>(a), get<0, 1>(a), get<1, 0>(b), get<1, 1>(b), -1,  1, opposite)\r\n                ;\r\n        }\r\n        // Nothing should goes through. If any we have made an error\r\n        // std::cout << \"Robustness issue, non-logical behaviour\" << std::endl;\r\n        return Policy::error(\"Robustness issue, non-logical behaviour\");\r\n    }\r\n};\r\n\r\n\r\n}} // namespace strategy::intersection\r\n\r\n\r\n\r\n}} // namespace boost::geometry\r\n\r\n\r\n#endif // BOOST_GEOMETRY_STRATEGIES_CARTESIAN_INTERSECTION_HPP\r\n", "meta": {"hexsha": "3bdf61624cf251eaa63c08b6e9b32b5820bbfcf7", "size": 30377, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "_thirdPartyLibs/include/boost/geometry/strategies/cartesian/cart_intersect.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/strategies/cartesian/cart_intersect.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/strategies/cartesian/cart_intersect.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": 40.2344370861, "max_line_length": 144, "alphanum_fraction": 0.519834085, "num_tokens": 7743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4891646934740854}}
{"text": "#include <iostream>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <bench/BenchTimer.h>\n\nusing namespace Eigen; \n\ntemplate<typename Quat>\nEIGEN_DONT_INLINE void quatmul_default(const Quat& a, const Quat& b, Quat& c)\n{\n  c = a * b;\n}\n\ntemplate<typename Quat>\nEIGEN_DONT_INLINE void quatmul_novec(const Quat& a, const Quat& b, Quat& c)\n{\n  c = internal::quat_product<0, Quat, Quat, typename Quat::Scalar, Aligned>::run(a,b);\n}\n\ntemplate<typename Quat> void bench(const std::string& label)\n{\n  int tries = 10;\n  int rep = 1000000;\n  BenchTimer t;\n  \n  Quat a(4, 1, 2, 3);\n  Quat b(2, 3, 4, 5);\n  Quat c;\n  \n  std::cout.precision(3);\n  \n  BENCH(t, tries, rep, quatmul_default(a,b,c));\n  std::cout << label << \" default \" << 1e3*t.best(CPU_TIMER) << \"ms  \\t\" << 1e-6*double(rep)/(t.best(CPU_TIMER)) << \" M mul/s\\n\";\n  \n  BENCH(t, tries, rep, quatmul_novec(a,b,c));\n  std::cout << label << \" novec   \" << 1e3*t.best(CPU_TIMER) << \"ms  \\t\" << 1e-6*double(rep)/(t.best(CPU_TIMER)) << \" M mul/s\\n\";\n}\n\nint main()\n{\n  bench<Quaternionf>(\"float \");\n  bench<Quaterniond>(\"double\");\n\n  return 0;\n\n}\n\n", "meta": {"hexsha": "8d9d7922cf72ad0c56fa990cfa63c329756a07cd", "size": 1097, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Eigen-3.3/bench/quatmul.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/bench/quatmul.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/bench/quatmul.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": 22.8541666667, "max_line_length": 129, "alphanum_fraction": 0.6353691887, "num_tokens": 384, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4891646934740853}}
{"text": "////////////////////////////////////////////////////////////////////////\n// exhaustive test in simd mode for functor nt2::arg\n//        versus a0>=0 ? 0 : nt2::Pi<r_t>() with float elements\n////////////////////////////////////////////////////////////////////////\n#include <nt2/include/functions/arg.hpp>\n#include <boost/simd/sdk/simd/native.hpp>\n#include <nt2/include/functions/successor.hpp>\n#include <nt2/include/functions/splat.hpp>\n#include <nt2/include/constants/real.hpp>\n#include <nt2/include/functions/iround.hpp>\n#include <cmath>\n\n\n#include <nt2/sdk/meta/cardinal_of.hpp>\n#include <nt2/include/functions/load.hpp>\n#include <nt2/include/functions/min.hpp>\n#include <iostream>\ntypedef BOOST_SIMD_DEFAULT_EXTENSION               ext_t;\ntypedef boost::simd::native<float,ext_t>  n_t;\ntypedef typename nt2::meta::as_integer<n_t>::type   in_t;\ntypedef typename nt2::meta::call<arg_(n_t)>::type r_t;\nstatic inline r_t repfunc(const float & a0){\n   return a0>=0 ? 0 : nt2::Pi<r_t>()(a0);\n}\nint main(){\n  float mini = nt2::Valmin<float>();\n  float maxi = nt2::Valmax<float>();\n  const nt2::uint32_t N = nt2::meta::cardinal_of<n_t>::value;\n  const in_t vN = nt2::splat<in_t>(N);\n  const nt2::uint32_t M =  10;\n  nt2::uint32_t histo[M+1];\n  for(nt2::uint32_t i = 0; i < M; i++) histo[i] = 0;\n  float a[N];\n  a[0] = mini;\n  for(nt2::uint32_t i = 1; i < N; i++)\n    a[i] = nt2::successor(a[i-1], 1);\n  n_t a0 = nt2::load<n_t>(&a[0],0);\n  nt2::uint32_t k = 0;\n  std::cout << \"a line of points to wait for... be patient!\" << std::endl;\n  for(; a0[N-1] < maxi; a0 = nt2::successor(a0, vN))\n    {\n      n_t z =  nt2::arg(a0);\n      for(nt2::uint32_t i = 0; i < N; i++)\n        {\n           float v = repfunc(a0[i]);\n           float sz = z[i];\n           ++histo[nt2::min(M, nt2::iround(2*nt2::ulpdist(v, sz)))];\n           ++k;\n           if (k%100000000 == 0){\n             std::cout << \".\" << std::flush; ++j;\n             if (j == 80){std::cout << std::endl; j = 0;}\n           }\n        }\n      }\n    std::cout << \"exhaustive test for \" << std::endl;\n    std::cout << \" nt2::arg versus a0>=0 ? 0 : nt2::Pi<r_t>() \" << std::endl;\n    std::cout << \" in simd mode and float type\" << std::endl;\n    for(nt2::uint32_t i = 0; i < M; i++)\n      std::cout << i/2.0 << \" -> \" << histo[i] << std::endl;\n    std::cout << k << \" values computed\" << std::endl;\n    std::cout << std::endl;\n    std::cout << std::endl;\n    for(nt2::uint32_t i = 0; i < M; i++)\n      std::cout << i/2.0 << \" -> \"\n                << (histo[i]*100.0/k) << \"%\" << std::endl;\n    return 0;\n}\n", "meta": {"hexsha": "0e1ca6ed9324d0150ca164efa3205e7f85049442", "size": 2552, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/core/arithmetic/exhaustive/simd/arg.cpp", "max_stars_repo_name": "pbrunet/nt2", "max_stars_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "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/arithmetic/exhaustive/simd/arg.cpp", "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/arithmetic/exhaustive/simd/arg.cpp", "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": 37.5294117647, "max_line_length": 77, "alphanum_fraction": 0.5297805643, "num_tokens": 821, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4891646934740853}}
{"text": "/**\n * \\copyright\n * Copyright (c) 2012-2019, OpenGeoSys Community (http://www.opengeosys.org)\n *            Distributed under a Modified BSD License.\n *              See accompanying file LICENSE.txt or\n *              http://www.opengeosys.org/project/license\n *\n */\n\n#include \"EigenLinearSolver.h\"\n\n#include <logog/include/logog.hpp>\n\n#ifdef USE_MKL\n#include <Eigen/PardisoSupport>\n#endif\n\n#ifdef USE_EIGEN_UNSUPPORTED\n#include <Eigen/Sparse>\n#include <unsupported/Eigen/src/IterativeSolvers/GMRES.h>\n#include <unsupported/Eigen/src/IterativeSolvers/Scaling.h>\n#endif\n\n#include \"BaseLib/ConfigTree.h\"\n#include \"EigenVector.h\"\n#include \"EigenMatrix.h\"\n#include \"EigenTools.h\"\n\n#include \"MathLib/LinAlg/LinearSolverOptions.h\"\n\nnamespace MathLib\n{\n\n// TODO change to LinearSolver\nclass EigenLinearSolverBase\n{\npublic:\n    using Vector = EigenVector::RawVectorType;\n    using Matrix = EigenMatrix::RawMatrixType;\n\n    virtual ~EigenLinearSolverBase() = default;\n\n    //! Solves the linear equation system \\f$ A x = b \\f$ for \\f$ x \\f$.\n    virtual bool solve(Matrix &A, Vector const& b, Vector &x, EigenOption &opt) = 0;\n};\n\nnamespace details\n{\n\n/// Template class for Eigen direct linear solvers\ntemplate <class T_SOLVER>\nclass EigenDirectLinearSolver final : public EigenLinearSolverBase\n{\npublic:\n    bool solve(Matrix& A, Vector const& b, Vector& x, EigenOption& opt) override\n    {\n        INFO(\"-> solve with %s\",\n             EigenOption::getSolverName(opt.solver_type).c_str());\n        if (!A.isCompressed())\n        {\n            A.makeCompressed();\n        }\n\n        _solver.compute(A);\n        if(_solver.info()!=Eigen::Success) {\n            ERR(\"Failed during Eigen linear solver initialization\");\n            return false;\n        }\n\n        x = _solver.solve(b);\n        if(_solver.info()!=Eigen::Success) {\n            ERR(\"Failed during Eigen linear solve\");\n            return false;\n        }\n\n        return true;\n    }\n\nprivate:\n    T_SOLVER _solver;\n};\n\n/// Template class for Eigen iterative linear solvers\ntemplate <class T_SOLVER>\nclass EigenIterativeLinearSolver final : public EigenLinearSolverBase\n{\npublic:\n    bool solve(Matrix& A, Vector const& b, Vector& x, EigenOption& opt) override\n    {\n        INFO(\"-> solve with %s (precon %s)\",\n             EigenOption::getSolverName(opt.solver_type).c_str(),\n             EigenOption::getPreconName(opt.precon_type).c_str());\n        _solver.setTolerance(opt.error_tolerance);\n        _solver.setMaxIterations(opt.max_iterations);\n\n        if (!A.isCompressed())\n        {\n            A.makeCompressed();\n        }\n\n        _solver.compute(A);\n        if(_solver.info()!=Eigen::Success) {\n            ERR(\"Failed during Eigen linear solver initialization\");\n            return false;\n        }\n\n        x = _solver.solveWithGuess(b, x);\n        INFO(\"\\t iteration: %d/%ld\", _solver.iterations(), opt.max_iterations);\n        INFO(\"\\t residual: %e\\n\", _solver.error());\n\n        if(_solver.info()!=Eigen::Success) {\n            ERR(\"Failed during Eigen linear solve\");\n            return false;\n        }\n\n        return true;\n    }\n\nprivate:\n    T_SOLVER _solver;\n};\n\ntemplate <template <typename, typename> class Solver, typename Precon>\nstd::unique_ptr<EigenLinearSolverBase> createIterativeSolver()\n{\n    using Slv = EigenIterativeLinearSolver<\n        Solver<EigenMatrix::RawMatrixType, Precon>>;\n    return std::make_unique<Slv>();\n}\n\ntemplate <template <typename, typename> class Solver>\nstd::unique_ptr<EigenLinearSolverBase> createIterativeSolver(\n    EigenOption::PreconType precon_type)\n{\n    switch (precon_type) {\n        case EigenOption::PreconType::NONE:\n            return createIterativeSolver<Solver,\n                                         Eigen::IdentityPreconditioner>();\n        case EigenOption::PreconType::DIAGONAL:\n            return createIterativeSolver<\n                Solver, Eigen::DiagonalPreconditioner<double>>();\n        case EigenOption::PreconType::ILUT:\n            // TODO for this preconditioner further options can be passed.\n            // see https://eigen.tuxfamily.org/dox/classEigen_1_1IncompleteLUT.html\n            return createIterativeSolver<\n                Solver, Eigen::IncompleteLUT<double>>();\n        default:\n            OGS_FATAL(\"Invalid Eigen preconditioner type.\");\n    }\n}\n\ntemplate <typename Mat, typename Precon>\nusing EigenCGSolver = Eigen::ConjugateGradient<Mat, Eigen::Lower, Precon>;\n\nstd::unique_ptr<EigenLinearSolverBase> createIterativeSolver(\n    EigenOption::SolverType solver_type, EigenOption::PreconType precon_type)\n{\n    switch (solver_type) {\n        case EigenOption::SolverType::BiCGSTAB: {\n            return createIterativeSolver<Eigen::BiCGSTAB>(precon_type);\n        }\n        case EigenOption::SolverType::CG: {\n            return createIterativeSolver<EigenCGSolver>(precon_type);\n        }\n        case EigenOption::SolverType::GMRES: {\n#ifdef USE_EIGEN_UNSUPPORTED\n            return createIterativeSolver<Eigen::GMRES>(precon_type);\n#else\n            OGS_FATAL(\n                \"The code is not compiled with the Eigen unsupported modules. \"\n                \"Linear solver type GMRES is not available.\");\n#endif\n        }\n        default:\n            OGS_FATAL(\"Invalid Eigen iterative linear solver type. Aborting.\");\n    }\n}\n\n}  // namespace details\n\nEigenLinearSolver::EigenLinearSolver(\n                            const std::string& /*solver_name*/,\n                            const BaseLib::ConfigTree* const option)\n{\n    using Matrix = EigenMatrix::RawMatrixType;\n\n    if (option)\n    {\n        setOption(*option);\n    }\n\n    // TODO for my taste it is much too unobvious that the default solver type\n    //      currently is SparseLU.\n    switch (_option.solver_type) {\n        case EigenOption::SolverType::SparseLU: {\n            using SolverType =\n                Eigen::SparseLU<Matrix, Eigen::COLAMDOrdering<int>>;\n            _solver = std::make_unique<\n                details::EigenDirectLinearSolver<SolverType>>();\n            return;\n        }\n        case EigenOption::SolverType::BiCGSTAB:\n        case EigenOption::SolverType::CG:\n        case EigenOption::SolverType::GMRES:\n            _solver = details::createIterativeSolver(_option.solver_type,\n                                                     _option.precon_type);\n            return;\n        case EigenOption::SolverType::PardisoLU: {\n#ifdef USE_MKL\n            using SolverType = Eigen::PardisoLU<EigenMatrix::RawMatrixType>;\n            _solver.reset(new details::EigenDirectLinearSolver<SolverType>);\n            return;\n#else\n            OGS_FATAL(\n                \"The code is not compiled with Intel MKL. Linear solver type \"\n                \"PardisoLU is not available.\");\n#endif\n        }\n    }\n\n    OGS_FATAL(\"Invalid Eigen linear solver type. Aborting.\");\n}\n\nEigenLinearSolver::~EigenLinearSolver() = default;\n\nvoid EigenLinearSolver::setOption(BaseLib::ConfigTree const& option)\n{\n    ignoreOtherLinearSolvers(option, \"eigen\");\n    //! \\ogs_file_param{prj__linear_solvers__linear_solver__eigen}\n    auto const ptSolver = option.getConfigSubtreeOptional(\"eigen\");\n    if (!ptSolver)\n    {\n        return;\n    }\n\n    if (auto solver_type =\n            //! \\ogs_file_param{prj__linear_solvers__linear_solver__eigen__solver_type}\n            ptSolver->getConfigParameterOptional<std::string>(\"solver_type\")) {\n        _option.solver_type = MathLib::EigenOption::getSolverType(*solver_type);\n    }\n    if (auto precon_type =\n            //! \\ogs_file_param{prj__linear_solvers__linear_solver__eigen__precon_type}\n            ptSolver->getConfigParameterOptional<std::string>(\"precon_type\")) {\n        _option.precon_type = MathLib::EigenOption::getPreconType(*precon_type);\n    }\n    if (auto error_tolerance =\n            //! \\ogs_file_param{prj__linear_solvers__linear_solver__eigen__error_tolerance}\n            ptSolver->getConfigParameterOptional<double>(\"error_tolerance\")) {\n        _option.error_tolerance = *error_tolerance;\n    }\n    if (auto max_iteration_step =\n            //! \\ogs_file_param{prj__linear_solvers__linear_solver__eigen__max_iteration_step}\n            ptSolver->getConfigParameterOptional<int>(\"max_iteration_step\")) {\n        _option.max_iterations = *max_iteration_step;\n    }\n    if (auto scaling =\n            //! \\ogs_file_param{prj__linear_solvers__linear_solver__eigen__scaling}\n            ptSolver->getConfigParameterOptional<bool>(\"scaling\")) {\n#ifdef USE_EIGEN_UNSUPPORTED\n        _option.scaling = *scaling;\n#else\n        OGS_FATAL(\n            \"The code is not compiled with the Eigen unsupported modules. \"\n            \"scaling is not available.\");\n#endif\n    }\n}\n\nbool EigenLinearSolver::solve(EigenMatrix &A, EigenVector& b, EigenVector &x)\n{\n    INFO(\"------------------------------------------------------------------\");\n    INFO(\"*** Eigen solver computation\");\n\n#ifdef USE_EIGEN_UNSUPPORTED\n    std::unique_ptr<Eigen::IterScaling<EigenMatrix::RawMatrixType>> scal;\n    if (_option.scaling)\n    {\n        INFO(\"-> scale\");\n        scal =\n            std::make_unique<Eigen::IterScaling<EigenMatrix::RawMatrixType>>();\n        scal->computeRef(A.getRawMatrix());\n        b.getRawVector() = scal->LeftScaling().cwiseProduct(b.getRawVector());\n    }\n#endif\n    auto const success = _solver->solve(A.getRawMatrix(), b.getRawVector(),\n                                        x.getRawVector(), _option);\n#ifdef USE_EIGEN_UNSUPPORTED\n    if (scal)\n    {\n        x.getRawVector() = scal->RightScaling().cwiseProduct(x.getRawVector());\n    }\n#endif\n\n    INFO(\"------------------------------------------------------------------\");\n\n    return success;\n}\n\n}  // namespace MathLib\n", "meta": {"hexsha": "80cce5b11344bc4756018ee685163e33a1a60de0", "size": 9677, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "MathLib/LinAlg/Eigen/EigenLinearSolver.cpp", "max_stars_repo_name": "WenjieXuZJU/ogs", "max_stars_repo_head_hexsha": "cc464a7efb726ad1ab657d0b82fbdb1623303cca", "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": "MathLib/LinAlg/Eigen/EigenLinearSolver.cpp", "max_issues_repo_name": "WenjieXuZJU/ogs", "max_issues_repo_head_hexsha": "cc464a7efb726ad1ab657d0b82fbdb1623303cca", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-06-05T12:06:11.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-06T08:45:30.000Z", "max_forks_repo_path": "MathLib/LinAlg/Eigen/EigenLinearSolver.cpp", "max_forks_repo_name": "bilke/ogs", "max_forks_repo_head_hexsha": "517d0eaac7b1710d77ec7ddfc2957d7c59fecade", "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": 32.2566666667, "max_line_length": 94, "alphanum_fraction": 0.6362509042, "num_tokens": 2184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4891646934740853}}
{"text": "/*\n@copyright Louis Dionne 2015\nDistributed under the Boost Software License, Version 1.0.\n(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n */\n\n#include <boost/hana/assert.hpp>\n#include <boost/hana/integral_constant.hpp>\nusing namespace boost::hana;\n\n\nint main() {\n\n{\n\n//! [mult]\nBOOST_HANA_CONSTANT_CHECK(mult(int_<3>, int_<5>) == int_<15>);\nBOOST_HANA_CONSTEXPR_CHECK(mult(4, 2) == 8);\n\n//! [mult]\n\n}{\n\n//! [one]\nBOOST_HANA_CONSTANT_CHECK(one<IntegralConstant<int>>() == int_<1>);\nBOOST_HANA_CONSTEXPR_CHECK(one<long>() == 1l);\n//! [one]\n\n}{\n\n//! [power]\nBOOST_HANA_CONSTANT_CHECK(power(int_<3>, int_<2>) == int_<3 * 3>);\nBOOST_HANA_CONSTEXPR_CHECK(power(2, int_<4>) == 16);\n//! [power]\n\n}\n\n}\n", "meta": {"hexsha": "f4d441c253769e54cd5c72c233c7790c6730b367", "size": 726, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/ring.cpp", "max_stars_repo_name": "josephwinston/hana", "max_stars_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/ring.cpp", "max_issues_repo_name": "josephwinston/hana", "max_issues_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/ring.cpp", "max_forks_repo_name": "josephwinston/hana", "max_forks_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.6153846154, "max_line_length": 78, "alphanum_fraction": 0.6873278237, "num_tokens": 212, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7634837743174789, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.4891150908930034}}
{"text": "#pragma once\n\n#include <Eigen/Geometry>\n#include \"autd3.hpp\"\n\nnamespace dynaman {\n\n\tstd::vector<std::vector<size_t>> combination(size_t max, size_t num);\n}\n", "meta": {"hexsha": "021077321f66f2f05bc04c37956389b51c992641", "size": 156, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "inc/MathUtil.hpp", "max_stars_repo_name": "shinolab/dynamic-manipulation", "max_stars_repo_head_hexsha": "d43bae688cecf87e15605ed6a9dbc80a782d72fc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "inc/MathUtil.hpp", "max_issues_repo_name": "shinolab/dynamic-manipulation", "max_issues_repo_head_hexsha": "d43bae688cecf87e15605ed6a9dbc80a782d72fc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "inc/MathUtil.hpp", "max_forks_repo_name": "shinolab/dynamic-manipulation", "max_forks_repo_head_hexsha": "d43bae688cecf87e15605ed6a9dbc80a782d72fc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.6, "max_line_length": 70, "alphanum_fraction": 0.7307692308, "num_tokens": 39, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7634837743174789, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.4891150908930034}}
{"text": "//  (C) Copyright Matt Borland 2021.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include <cmath>\n#include <cfloat>\n#include <cstdint>\n#include <limits>\n#include <type_traits>\n#include <boost/math/ccmath/isfinite.hpp>\n\n#ifdef BOOST_HAS_FLOAT128\n#include <boost/multiprecision/float128.hpp>\n#endif\n\ntemplate <typename T>\nvoid test()\n{\n    if constexpr (std::numeric_limits<T>::has_quiet_NaN)\n    {\n        static_assert(!boost::math::ccmath::isfinite(std::numeric_limits<T>::quiet_NaN()), \"Wrong response to NAN\");\n    }\n\n    static_assert(boost::math::ccmath::isfinite(T(0)), \"Wrong response to 0\");\n    \n    if constexpr (!std::is_integral_v<T>)\n    {\n        static_assert(boost::math::ccmath::isfinite((std::numeric_limits<T>::min)()/2), \"Wrong response to subnormal\");\n        static_assert(!boost::math::ccmath::isfinite(std::numeric_limits<T>::infinity()), \"Wrong response to infinity\");\n    }\n    else\n    {\n        // Integer types define infinity as 0\n        // https://en.cppreference.com/w/cpp/types/numeric_limits/infinity\n        static_assert(boost::math::ccmath::isfinite(std::numeric_limits<T>::infinity()), \"Wrong response to infinity\");\n    }\n}\n\n#ifndef BOOST_MATH_NO_CONSTEXPR_DETECTION\nint main()\n{\n    test<float>();\n    test<double>();\n\n    #ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n    test<long double>();\n    #endif\n    \n    #if defined(BOOST_HAS_FLOAT128) && !defined(BOOST_MATH_USING_BUILTIN_CONSTANT_P)\n    test<boost::multiprecision::float128>();\n    #endif\n\n    test<int>();\n    test<unsigned>();\n    test<long>();\n    test<std::int32_t>();\n    test<std::int64_t>();\n    test<std::uint32_t>();\n\n    return 0;\n}\n#else\nint main()\n{\n    return 0;\n}\n#endif\n", "meta": {"hexsha": "36e0c51daff7988a0627a4454e8488325a0221a9", "size": 1839, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/ccmath_isfinite_test.cpp", "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": "test/ccmath_isfinite_test.cpp", "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": "test/ccmath_isfinite_test.cpp", "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": 26.652173913, "max_line_length": 120, "alphanum_fraction": 0.6742794997, "num_tokens": 466, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.6406358685621719, "lm_q1q2_score": 0.48911508399771997}}
{"text": "#include <iostream>\n#include <mtl/dense1D.h>\n#include <mtl/mtl.h>\n\n/*\n  example output:\n\n  60\n\n  */\n\nint\nmain()\n{\n  using namespace mtl;\n  //begin\n  dense1D<double> x(10, 2), y(10, 3);\n  double s = dot(x, y);\n  //end\n  std::cout << s << std::endl;\n  return 0;\n}\n", "meta": {"hexsha": "504c1a15f29b7d2512691977943041d43810a7b0", "size": 262, "ext": "cc", "lang": "C++", "max_stars_repo_path": "stapl_release/tools/mtl-2.0/contrib/examples/vecvec_dot.cc", "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/tools/mtl-2.0/contrib/examples/vecvec_dot.cc", "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/tools/mtl-2.0/contrib/examples/vecvec_dot.cc", "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": 11.3913043478, "max_line_length": 37, "alphanum_fraction": 0.5687022901, "num_tokens": 99, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.48911508041626983}}
{"text": "/* +------------------------------------------------------------------------+\n   |                     Mobile Robot Programming Toolkit (MRPT)            |\n   |                          https://www.mrpt.org/                         |\n   |                                                                        |\n   | Copyright (c) 2005-2022, Individual contributors, see AUTHORS file     |\n   | See: https://www.mrpt.org/Authors - All rights reserved.               |\n   | Released under BSD License. See: https://www.mrpt.org/License          |\n   +------------------------------------------------------------------------+ */\n\n#include \"math-precomp.h\"  // Precompiled headers\n//\n#include <mrpt/math/CQuaternion.h>\n#include <mrpt/math/TPoint2D.h>\n#include <mrpt/math/TPoint3D.h>\n#include <mrpt/math/TPose2D.h>\n#include <mrpt/math/TPose3D.h>\n#include <mrpt/math/homog_matrices.h>  // homogeneousMatrixInverse()\n\n#include <Eigen/Dense>\n\nusing namespace mrpt::math;\n\nstatic_assert(std::is_trivially_copyable_v<TPose3D>);\n\nTPose3D::TPose3D(const TPoint2D& p)\n\t: x(p.x), y(p.y), z(0.0), yaw(0.0), pitch(0.0), roll(0.0)\n{\n}\nTPose3D::TPose3D(const TPose2D& p)\n\t: x(p.x), y(p.y), z(0.0), yaw(p.phi), pitch(0.0), roll(0.0)\n{\n}\nTPose3D::TPose3D(const TPoint3D& p)\n\t: x(p.x), y(p.y), z(p.z), yaw(0.0), pitch(0.0), roll(0.0)\n{\n}\nvoid TPose3D::asString(std::string& s) const\n{\n\ts = mrpt::format(\n\t\t\"[%f %f %f %f %f %f]\", x, y, z, RAD2DEG(yaw), RAD2DEG(pitch),\n\t\tRAD2DEG(roll));\n}\nvoid TPose3D::getAsQuaternion(\n\tmrpt::math::CQuaternion<double>& q,\n\tmrpt::optional_ref<mrpt::math::CMatrixFixed<double, 4, 3>> out_dq_dr) const\n{\n\t// See:\n\t// http://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles\n\tconst double cy = cos(yaw * 0.5), sy = sin(yaw * 0.5);\n\tconst double cp = cos(pitch * 0.5), sp = sin(pitch * 0.5);\n\tconst double cr = cos(roll * 0.5), sr = sin(roll * 0.5);\n\n\tconst double ccc = cr * cp * cy;\n\tconst double ccs = cr * cp * sy;\n\tconst double css = cr * sp * sy;\n\tconst double sss = sr * sp * sy;\n\tconst double scc = sr * cp * cy;\n\tconst double ssc = sr * sp * cy;\n\tconst double csc = cr * sp * cy;\n\tconst double scs = sr * cp * sy;\n\n\tq.w(ccc + sss);\n\tq.x(scc - css);\n\tq.y(csc + scs);\n\tq.z(ccs - ssc);\n\n\t// Compute 4x3 Jacobian: for details, see technical report:\n\t//   Parameterizations of SE(3) transformations: equivalences, compositions\n\t//   and uncertainty, J.L. Blanco (2010).\n\t//   https://www.mrpt.org/6D_poses:equivalences_compositions_and_uncertainty\n\tif (out_dq_dr)\n\t{\n\t\talignas(MRPT_MAX_STATIC_ALIGN_BYTES) const double nums[4 * 3] = {\n\t\t\t-0.5 * q[3], 0.5 * (-csc + scs), -0.5 * q[1],\n\t\t\t-0.5 * q[2], 0.5 * (-ssc - ccs), 0.5 * q[0],\n\t\t\t0.5 * q[1],\t 0.5 * (ccc - sss),\t 0.5 * q[3],\n\t\t\t0.5 * q[0],\t 0.5 * (-css - scc), -0.5 * q[2]};\n\t\tout_dq_dr.value().get().loadFromArray(nums);\n\t}\n}\nvoid TPose3D::composePoint(const TPoint3D& l, TPoint3D& g) const\n{\n\tCMatrixDouble33 R;\n\tthis->getRotationMatrix(R);\n\tTPoint3D res;\n\tres.x = R(0, 0) * l.x + R(0, 1) * l.y + R(0, 2) * l.z + this->x;\n\tres.y = R(1, 0) * l.x + R(1, 1) * l.y + R(1, 2) * l.z + this->y;\n\tres.z = R(2, 0) * l.x + R(2, 1) * l.y + R(2, 2) * l.z + this->z;\n\n\tg = res;\n}\nTPoint3D TPose3D::composePoint(const TPoint3D& l) const\n{\n\tTPoint3D g;\n\tcomposePoint(l, g);\n\treturn g;\n}\n\nvoid TPose3D::inverseComposePoint(const TPoint3D& g, TPoint3D& l) const\n{\n\tCMatrixDouble44 H;\n\tthis->getInverseHomogeneousMatrix(H);\n\tTPoint3D res;\n\tres.x = H(0, 0) * g.x + H(0, 1) * g.y + H(0, 2) * g.z + H(0, 3);\n\tres.y = H(1, 0) * g.x + H(1, 1) * g.y + H(1, 2) * g.z + H(1, 3);\n\tres.z = H(2, 0) * g.x + H(2, 1) * g.y + H(2, 2) * g.z + H(2, 3);\n\n\tl = res;\n}\nTPoint3D TPose3D::inverseComposePoint(const TPoint3D& g) const\n{\n\tTPoint3D l;\n\tinverseComposePoint(g, l);\n\treturn l;\n}\n\nvoid TPose3D::getRotationMatrix(mrpt::math::CMatrixDouble33& R) const\n{\n\tconst double cy = cos(yaw);\n\tconst double sy = sin(yaw);\n\tconst double cp = cos(pitch);\n\tconst double sp = sin(pitch);\n\tconst double cr = cos(roll);\n\tconst double sr = sin(roll);\n\n\talignas(MRPT_MAX_STATIC_ALIGN_BYTES) const double rot_vals[] = {\n\t\tcy * cp,\n\t\tcy * sp * sr - sy * cr,\n\t\tcy * sp * cr + sy * sr,\n\t\tsy * cp,\n\t\tsy * sp * sr + cy * cr,\n\t\tsy * sp * cr - cy * sr,\n\t\t-sp,\n\t\tcp * sr,\n\t\tcp * cr};\n\tR.loadFromArray(rot_vals);\n}\nvoid TPose3D::SO3_to_yaw_pitch_roll(\n\tconst mrpt::math::CMatrixDouble33& R, double& yaw, double& pitch,\n\tdouble& roll)\n{\n\tASSERTDEBMSG_(\n\t\tstd::abs(\n\t\t\tsqrt(square(R(0, 0)) + square(R(1, 0)) + square(R(2, 0))) - 1) <\n\t\t\t3e-3,\n\t\t\"Homogeneous matrix is not orthogonal & normalized!: \" +\n\t\t\tR.inMatlabFormat());\n\tASSERTDEBMSG_(\n\t\tstd::abs(\n\t\t\tsqrt(square(R(0, 1)) + square(R(1, 1)) + square(R(2, 1))) - 1) <\n\t\t\t3e-3,\n\t\t\"Homogeneous matrix is not orthogonal & normalized!: \" +\n\t\t\tR.inMatlabFormat());\n\tASSERTDEBMSG_(\n\t\tstd::abs(\n\t\t\tsqrt(square(R(0, 2)) + square(R(1, 2)) + square(R(2, 2))) - 1) <\n\t\t\t3e-3,\n\t\t\"Homogeneous matrix is not orthogonal & normalized!: \" +\n\t\t\tR.inMatlabFormat());\n\n\t// Pitch is in the range [-pi/2, pi/2 ], so this calculation is enough:\n\tpitch = atan2(-R(2, 0), hypot(R(0, 0), R(1, 0)));\n\n\t// Roll:\n\tif ((fabs(R(2, 1)) + fabs(R(2, 2))) <\n\t\t10 * std::numeric_limits<double>::epsilon())\n\t{\n\t\t// Gimbal lock between yaw and roll. This one is arbitrarily forced to\n\t\t// be zero.\n\t\t// Check\n\t\t// https://reference.mrpt.org/devel/classmrpt_1_1poses_1_1_c_pose3_d.html.\n\t\t// If cos(pitch)==0, the homogeneous matrix is:\n\t\t// When sin(pitch)==1:\n\t\t//  /0  cysr-sycr cycr+sysr x\\   /0  sin(r-y) cos(r-y)  x\\.\n\t\t//  |0  sysr+cycr sycr-cysr y| = |0  cos(r-y) -sin(r-y) y|\n\t\t//  |-1     0         0     z|   |-1    0         0     z|\n\t\t//  \\0      0         0     1/   \\0     0         0     1/\n\t\t//\n\t\t// And when sin(pitch)=-1:\n\t\t//  /0 -cysr-sycr -cycr+sysr x\\   /0 -sin(r+y) -cos(r+y) x\\.\n\t\t//  |0 -sysr+cycr -sycr-cysr y| = |0 cos(r+y)  -sin(r+y) y|\n\t\t//  |1      0          0     z|   |1    0          0     z|\n\t\t//  \\0      0          0     1/   \\0    0          0     1/\n\t\t//\n\t\t// Both cases are in a \"gimbal lock\" status. This happens because pitch\n\t\t// is vertical.\n\n\t\troll = 0.0;\n\t\tif (pitch > 0) yaw = atan2(R(1, 2), R(0, 2));\n\t\telse\n\t\t\tyaw = atan2(-R(1, 2), -R(0, 2));\n\t}\n\telse\n\t{\n\t\troll = atan2(R(2, 1), R(2, 2));\n\t\t// Yaw:\n\t\tyaw = atan2(R(1, 0), R(0, 0));\n\t}\n}\n\nvoid TPose3D::fromHomogeneousMatrix(const mrpt::math::CMatrixDouble44& HG)\n{\n\tSO3_to_yaw_pitch_roll(\n\t\tCMatrixDouble33(HG.blockCopy<3, 3>(0, 0)), yaw, pitch, roll);\n\tx = HG(0, 3);\n\ty = HG(1, 3);\n\tz = HG(2, 3);\n}\nvoid TPose3D::composePose(const TPose3D other, TPose3D& result) const\n{\n\tCMatrixDouble44 me_H, o_H;\n\tthis->getHomogeneousMatrix(me_H);\n\tother.getHomogeneousMatrix(o_H);\n\tresult.fromHomogeneousMatrix(\n\t\tCMatrixDouble44(me_H.asEigen() * o_H.asEigen()));\n}\nvoid TPose3D::getHomogeneousMatrix(mrpt::math::CMatrixDouble44& HG) const\n{\n\tCMatrixDouble33 R;\n\tgetRotationMatrix(R);\n\tHG.block<3, 3>(0, 0) = R.asEigen();\n\tHG(0, 3) = x;\n\tHG(1, 3) = y;\n\tHG(2, 3) = z;\n\tHG(3, 0) = HG(3, 1) = HG(3, 2) = 0.;\n\tHG(3, 3) = 1.;\n}\nvoid TPose3D::getInverseHomogeneousMatrix(mrpt::math::CMatrixDouble44& HG) const\n{  // Get current HM & inverse in-place:\n\tthis->getHomogeneousMatrix(HG);\n\tmrpt::math::homogeneousMatrixInverse(HG);\n}\n\nvoid TPose3D::fromString(const std::string& s)\n{\n\tCMatrixDouble m;\n\tif (!m.fromMatlabStringFormat(s))\n\t\tTHROW_EXCEPTION_FMT(\n\t\t\t\"Malformed expression in ::fromString, s=\\\"%s\\\"\", s.c_str());\n\tASSERTMSG_(\n\t\tm.rows() == 1 && m.cols() == 6, \"Wrong size of vector in ::fromString\");\n\tx = m(0, 0);\n\ty = m(0, 1);\n\tz = m(0, 2);\n\tyaw = DEG2RAD(m(0, 3));\n\tpitch = DEG2RAD(m(0, 4));\n\troll = DEG2RAD(m(0, 5));\n}\n\nTPose3D mrpt::math::operator-(const TPose3D& p)\n{\n\tCMatrixDouble44 H;\n\tp.getInverseHomogeneousMatrix(H);\n\tTPose3D ret;\n\tret.fromHomogeneousMatrix(H);\n\treturn ret;\n}\nTPose3D mrpt::math::operator-(const TPose3D& b, const TPose3D& a)\n{\n\t// b - a = A^{-1} * B\n\tCMatrixDouble44 Hainv, Hb;\n\ta.getInverseHomogeneousMatrix(Hainv);\n\tb.getHomogeneousMatrix(Hb);\n\tTPose3D ret;\n\tret.fromHomogeneousMatrix(CMatrixDouble44(Hainv.asEigen() * Hb.asEigen()));\n\treturn ret;\n}\n", "meta": {"hexsha": "615078f3ef9f7232074ba8c49081af021b89d73d", "size": 8016, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/src/TPose3D.cpp", "max_stars_repo_name": "wstnturner/mrpt", "max_stars_repo_head_hexsha": "b0be3557a4cded6bafff03feb28f7fa1f75762a3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 38.0, "max_stars_repo_stars_event_min_datetime": "2015-01-04T05:24:26.000Z", "max_stars_repo_stars_event_max_datetime": "2015-07-17T00:30:02.000Z", "max_issues_repo_path": "libs/math/src/TPose3D.cpp", "max_issues_repo_name": "wstnturner/mrpt", "max_issues_repo_head_hexsha": "b0be3557a4cded6bafff03feb28f7fa1f75762a3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 40.0, "max_issues_repo_issues_event_min_datetime": "2015-01-03T22:43:00.000Z", "max_issues_repo_issues_event_max_datetime": "2015-07-17T18:52:59.000Z", "max_forks_repo_path": "libs/math/src/TPose3D.cpp", "max_forks_repo_name": "wstnturner/mrpt", "max_forks_repo_head_hexsha": "b0be3557a4cded6bafff03feb28f7fa1f75762a3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2015-01-06T12:32:19.000Z", "max_forks_repo_forks_event_max_datetime": "2017-05-30T15:50:13.000Z", "avg_line_length": 29.9104477612, "max_line_length": 80, "alphanum_fraction": 0.5814620758, "num_tokens": 3066, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.4891150735209867}}
{"text": "#include <gtest/gtest.h>\n#include \"helpers.hh\"\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include \"../CameraModel/cameramodel.hh\"\n#include \"../geometry/Bounds.hh\"\n#include \"../geometry/LineSegment/LineSegment2/LineSegment2i/linesegment2i.hh\"\n\nusing namespace bold;\nusing namespace Eigen;\n\nTEST (CameraModelTests, directionForPixel)\n{\n  auto imageWidth = 11;\n  auto imageHeight = 11;\n  auto rangeVerticalDegs = 90;\n  auto rangeHorizontalDegs = 90;\n\n  CameraModel cameraModel1(imageWidth, imageHeight,\n                           rangeVerticalDegs, rangeHorizontalDegs);\n\n  EXPECT_TRUE ( VectorsEqual(Vector3d(0, 1, 0).normalized(),\n                             cameraModel1.directionForPixel(Vector2d(5.5, 5.5)) ) );\n\n  EXPECT_TRUE ( VectorsEqual(Vector3d(1, 1, 0).normalized(),\n                             cameraModel1.directionForPixel(Vector2d( 0, 5.5)) ) );\n  EXPECT_TRUE ( VectorsEqual(Vector3d(-1, 1, 0).normalized(),\n                             cameraModel1.directionForPixel(Vector2d(11, 5.5)) ) );\n\n  EXPECT_TRUE ( VectorsEqual(Vector3d(0, 1, -1).normalized(),\n                             cameraModel1.directionForPixel(Vector2d(5.5,  0)) ) );\n  EXPECT_TRUE ( VectorsEqual(Vector3d(0, 1,  1).normalized(),\n                             cameraModel1.directionForPixel(Vector2d(5.5, 11)) ) );\n\n  auto v = Vector3d( -1, 1, 0).normalized();\n  v.x() *= 2.0/5.5;\n  EXPECT_TRUE ( VectorsEqual(v.normalized(),\n                             cameraModel1.directionForPixel(Vector2d(7.5,  5.5)) ) );\n\n  rangeVerticalDegs = 45;\n  rangeHorizontalDegs = 60;\n\n  double th = tan(.5 * 60.0 / 180.0 * M_PI);\n  double tv = tan(.5 * 45.0 / 180.0 * M_PI);\n\n  CameraModel cameraModel2(imageWidth, imageHeight,\n                           rangeVerticalDegs, rangeHorizontalDegs);\n\n  EXPECT_TRUE ( VectorsEqual(Vector3d(0, 1, 0).normalized(),\n                             cameraModel2.directionForPixel(Vector2d(5.5, 5.5)) ) );\n\n  EXPECT_TRUE ( VectorsEqual(Vector3d(th, 1, 0).normalized(),\n                             cameraModel2.directionForPixel(Vector2d( 0, 5.5)) ) );\n  EXPECT_TRUE ( VectorsEqual(Vector3d(-th, 1, 0).normalized(),\n                             cameraModel2.directionForPixel(Vector2d(11, 5.5)) ) );\n\n  EXPECT_TRUE ( VectorsEqual(Vector3d(0, 1, -tv).normalized(),\n                             cameraModel2.directionForPixel(Vector2d(5.5,  0)) ) );\n  EXPECT_TRUE ( VectorsEqual(Vector3d(0, 1,  tv).normalized(),\n                             cameraModel2.directionForPixel(Vector2d(5.5, 11)) ) );\n\n}\n\nTEST (CameraModelTests, pixelForDirection)\n{\n  auto imageWidth = 11;\n  auto imageHeight = 11;\n  auto rangeVerticalDegs = 90;\n  auto rangeHorizontalDegs = 90;\n\n  CameraModel cameraModel1(imageWidth, imageHeight, rangeVerticalDegs, rangeHorizontalDegs);\n\n  EXPECT_EQ ( Maybe<Vector2d>::empty(), cameraModel1.pixelForDirection(Vector3d(0,  0, 0)) );\n  EXPECT_EQ ( Maybe<Vector2d>::empty(), cameraModel1.pixelForDirection(Vector3d(1,  0, 0)) );\n  EXPECT_EQ ( Maybe<Vector2d>::empty(), cameraModel1.pixelForDirection(Vector3d(0,  0, 1)) );\n  EXPECT_EQ ( Maybe<Vector2d>::empty(), cameraModel1.pixelForDirection(Vector3d(1, -1, 1)) );\n\n  EXPECT_TRUE ( VectorsEqual( Vector2d(5.5, 5.5), *cameraModel1.pixelForDirection(Vector3d(0, 1, 0)) ) );\n\n  EXPECT_TRUE ( VectorsEqual( Vector2d( 0, 5.5), *cameraModel1.pixelForDirection(Vector3d( 1, 1, 0)) ) );\n  EXPECT_TRUE ( VectorsEqual( Vector2d(11, 5.5), *cameraModel1.pixelForDirection(Vector3d(-1, 1, 0)) ) );\n\n  EXPECT_TRUE ( VectorsEqual( Vector2d(5.5,  0), *cameraModel1.pixelForDirection(Vector3d(0, 1, -1)) ) );\n  EXPECT_TRUE ( VectorsEqual( Vector2d(5.5, 11), *cameraModel1.pixelForDirection(Vector3d(0, 2,  2)) ) );\n\n  auto v = Vector3d(-1, 1, 0).normalized();\n  v.x() *= 2.0/5.5;\n  EXPECT_TRUE ( VectorsEqual( Vector2d(7.5, 5.5), *cameraModel1.pixelForDirection(v) ) );\n\n  // 2 time range\n  rangeVerticalDegs = 45;\n  rangeHorizontalDegs = 60;\n\n  CameraModel cameraModel2(imageWidth, imageHeight, rangeVerticalDegs, rangeHorizontalDegs);\n\n  double th = tan(.5 * 60.0 / 180.0 * M_PI);\n  double tv = tan(.5 * 45.0 / 180.0 * M_PI);\n\n  EXPECT_TRUE ( VectorsEqual( Vector2d(5.5, 5.5), *cameraModel2.pixelForDirection(Vector3d(0, 1, 0)) ) );\n\n  EXPECT_TRUE ( VectorsEqual( Vector2d( 0, 5.5), *cameraModel2.pixelForDirection(Vector3d(th, 1, 0)) ) );\n  EXPECT_TRUE ( VectorsEqual( Vector2d(11, 5.5), *cameraModel2.pixelForDirection(Vector3d(-th, 1, 0)) ) );\n\n  EXPECT_TRUE ( VectorsEqual( Vector2d(5.5,  0), *cameraModel2.pixelForDirection(Vector3d(0, 1, -tv)) ) );\n  EXPECT_TRUE ( VectorsEqual( Vector2d(5.5, 11), *cameraModel2.pixelForDirection(Vector3d(0, 1, tv)) ) );\n}\n", "meta": {"hexsha": "081ebd668db1053838745ccb9b12859e0db69eef", "size": 4624, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/CameraModelTests.cc", "max_stars_repo_name": "drewnoakes/bold-humanoid", "max_stars_repo_head_hexsha": "6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335", "max_stars_repo_licenses": ["Apache-2.0"], "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/CameraModelTests.cc", "max_issues_repo_name": "drewnoakes/bold-humanoid", "max_issues_repo_head_hexsha": "6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335", "max_issues_repo_licenses": ["Apache-2.0"], "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/CameraModelTests.cc", "max_forks_repo_name": "drewnoakes/bold-humanoid", "max_forks_repo_head_hexsha": "6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335", "max_forks_repo_licenses": ["Apache-2.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.4220183486, "max_line_length": 106, "alphanum_fraction": 0.6567906574, "num_tokens": 1460, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.48911506993953613}}
{"text": "#include <iomanip>\n#include <cstdlib>\n#include <math.h>\n#include <cmath>\n#include <random>\n#include <Eigen/Eigen>\n#include <opencv2/opencv.hpp>\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n\n#include \"gtest/gtest.h\"\n#include \"../include/unscented_kalman_filter.h\"\n\n\nnamespace rviz {\n  cv::Point2i cv_offset(\n      Eigen::Vector2d e_p, int image_width=2000, int image_height=2000){\n    cv::Point2i output;\n    output.x = int(e_p(0) * 100) + image_width/2;\n    output.y = image_height - int(e_p(1) * 100) - image_height/3;\n    return output;\n  };\n\n  void ellipse_drawing(\n    cv::Mat bg_img, Eigen::Matrix2d pest, Eigen::Vector2d center,\n    cv::Scalar ellipse_color=cv::Scalar(0, 0, 255)\n  ){\n    Eigen::EigenSolver<Eigen::Matrix2d> ces(pest);\n    Eigen::Matrix2d e_value = ces.pseudoEigenvalueMatrix();\n    Eigen::Matrix2d e_vector = ces.pseudoEigenvectors();\n\n    double angle = std::atan2(e_vector(0, 1), e_vector(0, 0));\n    cv::ellipse(\n      bg_img,\n      cv_offset(center, bg_img.cols, bg_img.rows),\n      cv::Size(e_value(0,0)*100, e_value(1,1)*100),\n      angle / M_PI * 180,\n      0,\n      360,\n      ellipse_color,\n      2,\n      4);\n  };\n}\n\nnamespace ukf {\n// Constan velocity model\nauto motion_model_cv = [](Eigen::Vector4d x, Eigen::Vector2d u, double dt)-> Eigen::Vector4d {\n  Eigen::Matrix4d F;\n  F <<1.0,  dt,   0.,   0.,\n          0., 1.0,   0.,   0.,\n          0.,   0., 1.0,   dt,\n          0.,   0.,   0.,  1.0;\n\n  return F * x;\n};\n\nauto observation_model_cv = [](Eigen::Vector4d x) -> Eigen::Vector2d {\n  Eigen::Matrix<double, 2, 4> H;\n  H << 1., 0., 0., 0.,\n       0., 0., 1., 0.;\n  return H * x;\n};\n\nauto wrap_angles_default = [](Eigen::VectorXd x) -> Eigen::VectorXd {\n  return x;\n};\n\n\nauto linear_motion_model = [](Eigen::Vector2d x, Eigen::Vector2d u, double dt)-> Eigen::Vector2d {\n  Eigen::Matrix2d F;\n  F <<  1.0, dt,\n        0, 1.0;\n\n  return F * x;\n};\n\nauto observation_model = [](Eigen::Vector2d x) -> Eigen::Vector2d {\n  Eigen::Matrix<double, 2, 2> H;\n  H << 1., 0.,\n       0., 1.;\n  return H * x;\n};\n\nauto observation_model_2x4 = [](Eigen::Vector4d x) -> Eigen::Vector2d {\n  // State to measurement function H, is with dimensions dim_z x dim_x with ones  in the locations to be updated.\n  Eigen::Matrix<double, 2, 4> H;\n  H << 1., 0., 0., 0.,\n       0., 1., 0., 0.;\n  return H * x;\n};\n\nauto motion_model_4x4 = [](Eigen::Vector4d x, Eigen::Vector2d u, double dt) -> Eigen::Vector4d {\n  Eigen::Matrix4d F;\n  F <<1.0,   0.,   0.,   0.,\n        0., 1.0,   0.,   0.,\n        0.,   0., 1.0,   0.,\n        0.,   0.,   0.,  0.; // TODO: Should this be a 1.0? PythonRobotics has 0.0\n\n  // control input v (m/s), yaw_rate (rad/s)\n  Eigen::Matrix<double, 4, 2> B;\n  B << dt * std::cos(x(2)),  0.,\n       dt * std::sin(x(2)),  0.,\n                        0.0,  dt,\n                        1.0,  0.0;\n  return F * x + B * u;\n};\n\nauto wrap_angles = [](Eigen::Vector4d x) -> Eigen::Vector4d{\n  // When state is represented by [x y yaw v].\n  Eigen::Vector4d angles_wrapped = x;\n\n  while (angles_wrapped(2) < -M_PI) {\n    angles_wrapped(2) += (2*M_PI);\n  }\n\n  while (angles_wrapped(2) > M_PI) {\n    angles_wrapped(2) -= (2*M_PI);\n  }\n\n  return angles_wrapped;\n};\n\nEigen::VectorXd residuals(Eigen::VectorXd const& sigma, Eigen::VectorXd const& x)\n{\n  return sigma - x;\n}\n\nEigen::VectorXd residuals_x(Eigen::VectorXd const& sigma, Eigen::VectorXd const& x)\n{\n  // Residuals when state is represented by [x y yaw v].\n  Eigen::VectorXd residuals(x.rows());\n  residuals(0) = sigma(0) - x(0);\n  residuals(1) = sigma(1) - x(1);\n  residuals(3) = sigma(3) - x(3);\n\n  auto yaw_residual = sigma(2) - x(2);\n\n  while (yaw_residual < -M_PI) {\n    yaw_residual += (2*M_PI);\n  }\n\n  while (yaw_residual > M_PI) {\n    yaw_residual -= (2*M_PI);\n  }\n  //assert((yaw_residual < M_PI) && (yaw_residual > -M_PI));\n  residuals(2) = yaw_residual;\n  return residuals;\n}\n\nEigen::VectorXd mean_fn_x(Eigen::MatrixXd const& sigmas, Eigen::VectorXd const& Wm)\n{\n  // State mean when state is represented by [x y yaw v].\n  Eigen::VectorXd mean(sigmas.cols());\n  mean.setZero();\n  double ss = 0.0;\n  double sc = 0.0;\n\n  for (auto i=0; i< sigmas.rows(); ++i) {\n    Eigen::VectorXd s = sigmas.row(i);\n\n    mean(0) += s(0) * Wm(i);\n    mean(1) += s(1) * Wm(i);\n    mean(3) += s(3) * Wm(i);\n    ss += std::sin(s(2)) * Wm(i);\n    sc += std::cos(s(2)) * Wm(i);\n  }\n  mean(2) = std::atan2(ss,sc);\n  return mean;\n}\n\nEigen::VectorXd mean_fn(Eigen::MatrixXd const& sigmas, Eigen::VectorXd const& Wm)\n{\n  return sigmas.transpose() * Wm;\n}\n\nauto subtract_fn = residuals;\nauto subtract_fn_x = residuals_x;\n}\n\n\nTEST(UKFTest, NumSigmaTest) {\n  auto points = ukf::MerweScaledSigmaPoints(2, 0.1,0.1,0.1, ukf::subtract_fn);\n  auto n_sigmas = points.num_sigmas();\n  EXPECT_EQ(n_sigmas, 5);\n}\n\n\nTEST(UKFTest, SigmaPoints2DTest) {\n  auto n = 2;\n  auto alpha = 1e-3;\n  auto beta = 2.0;\n  auto kappa = 0.0;\n  auto points = ukf::MerweScaledSigmaPoints(n, alpha, beta, kappa, ukf::subtract_fn);\n\n  Eigen::Vector2d x;\n  x << 1.,2.;\n\n  Eigen::Matrix2d P;\n  P << 2.,1.2,\n       1.2,2.;\n\n  auto sigmas = points.sigma_points(x, P);\n  Eigen::Matrix<double, 5, 2> sigmas_expected;\n\n  sigmas_expected << 1., 2.,\n                    1.002, 2.0012,\n                    1., 2.0016,\n                    0.9980, 1.9988,\n                    1., 1.9984;\n\n  ASSERT_TRUE((sigmas - sigmas_expected).norm() < 1e-5);\n}\n\n\nTEST(UKFTest, SigmaPointsTest) {\n  auto points = ukf::MerweScaledSigmaPoints(4, 1e-3,2.0,0.0, ukf::subtract_fn);\n  Eigen::Vector4d x = Eigen::Vector4d::Zero();\n  Eigen::Matrix4d P = Eigen::Matrix4d::Identity();\n  auto sigmas = points.sigma_points(x, P);\n\n  Eigen::Matrix<double, 9, 4> sigmas_expected;\n  sigmas_expected << 0., 0., 0., 0.,\n                    0.0020, 0., 0., 0.,\n                    0., 0.0020, 0., 0.,\n                    0., 0., 0.0020, 0.,\n                    0., 0., 0., 0.0020,\n                    -0.0020, 0., 0., 0.,\n                    0., -0.0020, 0., 0.,\n                    0., 0., -0.0020, 0.,\n                    0., 0., 0., -0.0020;\n\n  ASSERT_TRUE((sigmas - sigmas_expected).norm() < 1e-5);\n  ASSERT_TRUE(std::abs(points.get_wm().sum()-1.) < 1e-5);\n}\n\n\nTEST(UKFTest, ComputeWeightsTest) {\n  auto n = 2;\n  auto alpha = 1e-3;\n  auto beta = 2.0;\n  auto kappa = 0.0;\n  auto points = ukf::MerweScaledSigmaPoints(n, alpha, beta, kappa, ukf::subtract_fn);\n  auto wm = points.get_wm();\n\n  Eigen::Matrix<double,5,1> wm_expected;\n  wm_expected << -999998.9999712,\n                  249999.9999928,\n                  249999.9999928,\n                  249999.9999928,\n                  249999.9999928;\n\n  ASSERT_TRUE((wm - wm_expected).norm() < 1e-5);\n}\n\n\nTEST(UKFTest, UnscentedTransformTest) {\n  auto n = 2;\n  auto alpha = 1e-3;\n  auto beta = 2.0;\n  auto kappa = 0.0;\n  auto points = ukf::MerweScaledSigmaPoints(n, alpha, beta, kappa, ukf::subtract_fn);\n\n  Eigen::Vector2d x;\n  x << 1.,2.;\n\n  Eigen::Matrix2d P;\n  P << 2.,1.2,\n       1.2,2.;\n\n  Eigen::Matrix2d noise_cov;\n  noise_cov << 0.,0.,\n               0.,0.;\n\n  auto sigmas = points.sigma_points(x, P);\n\n  auto pair = ukf::unscented_transform(sigmas, points.get_wm(), points.get_wc(), noise_cov, ukf::residuals, ukf::mean_fn);\n\n  ASSERT_TRUE((std::get<0>(pair) - x).norm() < 1e-5);\n  ASSERT_TRUE((std::get<1>(pair) - P).norm() < 1e-5);\n}\n\n\nTEST(UKFTest, ResidualsTest) {\n  auto n = 2;\n  auto alpha = 0.001;\n  auto beta = 2.0;\n  auto kappa = 0.0;\n  auto points = ukf::MerweScaledSigmaPoints(n, alpha, beta, kappa, ukf::subtract_fn);\n\n  Eigen::Vector2d x;\n  x << 1.,2.;\n\n  Eigen::Matrix2d P;\n  P << 2.,1.2,\n       1.2,2.;\n\n  auto sigmas = points.sigma_points(x, P);\n\n  Eigen::MatrixXd residuals = ukf::residuals(sigmas.row(1), x);\n  Eigen::Matrix<double,2,1> residuals_expected;\n  residuals_expected << 0.002,0.0012;\n  ASSERT_TRUE((residuals - residuals_expected).norm() < 1e-5);\n}\n\n\nTEST(UKFTest, UKFPredictTest) {\n  auto n = 2;\n  auto alpha = 0.001;\n  auto beta = 2.0;\n  auto kappa = 0.0;\n  auto points = ukf::MerweScaledSigmaPoints(n, alpha, beta, kappa, ukf::subtract_fn);\n\n  Eigen::Vector2d x;\n  x << 1.,2.;\n\n  Eigen::Matrix2d P;\n  P << 2.,1.2,\n       1.2,2.;\n\n  Eigen::Vector2d u;\n  u << 1.0, 0.1;\n\n  Eigen::VectorXd  z = Eigen::VectorXd::Zero(n);\n\n  auto dim_z = n;\n  auto dt = 0.1;\n  auto ukf = ukf::UnscentedKalmanFilter(\n                n,\n                dim_z,\n                dt,\n                points,\n                ukf::wrap_angles_default,\n                ukf::linear_motion_model,\n                ukf::observation_model,\n                ukf::residuals,\n                ukf::residuals,\n                ukf::mean_fn,\n                ukf::mean_fn);\n\n  ukf.predict(u);\n  ukf.update(z);\n  //TODO: FINISH TESTING\n}\n\n\nTEST(UKFTest, CrossVarianceTest) {\n  auto n = 2;\n  auto dim_z = 2;\n  auto dt = 0.1;\n  auto alpha = 0.001;\n  auto beta = 2.0;\n  auto kappa = 0.0;\n  auto points = ukf::MerweScaledSigmaPoints(n, alpha, beta, kappa, ukf::subtract_fn);\n\n  Eigen::Vector2d x;\n  x << 1.,2.;\n\n  Eigen::Matrix2d P;\n  P << 2.,1.2,\n       1.2,2.;\n\n  // control input\n  Eigen::Vector2d u;\n  u << 1.0, 0.1;\n\n  Eigen::VectorXd  z = Eigen::VectorXd::Zero(n);\n\n  // Get sigmas_f (process)\n  Eigen::MatrixXd sigmas = points.sigma_points(x, P);\n  auto n_sigmas = points.num_sigmas();\n  Eigen::MatrixXd sigmas_f = Eigen::MatrixXd::Zero(n_sigmas, n);\n\n  // Pass the sigmas through the process model.\n  for (auto i=0; i<n_sigmas; i++) {\n    sigmas_f.row(i) = ukf::linear_motion_model(sigmas.row(i), u, dt);\n  }\n\n  // Get sigmas_h (measurement)\n  Eigen::MatrixXd sigmas_h = Eigen::MatrixXd::Zero(n_sigmas, dim_z);\n\n  // Pass the sigmas processed by the process(motion) model through the observation model.\n  for (auto i=0; i<n_sigmas; i++) {\n    sigmas_h.row(i) = ukf::observation_model(sigmas_f.row(i));\n  }\n\n  auto ukf = ukf::UnscentedKalmanFilter(\n                n,\n                dim_z,\n                dt,\n                points,\n                ukf::wrap_angles_default,\n                ukf::linear_motion_model,\n                ukf::observation_model,\n                ukf::residuals,\n                ukf::residuals,\n                ukf::mean_fn,\n                ukf::mean_fn);\n\n  auto CV = ukf.cross_variance(x, z,sigmas_f, sigmas_h);\n  // TODO: Finish test\n}\n\n\nTEST(UKFTest, SimulationSimpleCVTest) {\n  // Constant Velocity model\n  auto n = 4; // [x, x_dot, y, y_dot]\n  auto dt = 0.1;\n  auto alpha = 0.1;\n  auto beta = 2.0;\n  auto kappa = 1.0;\n  auto points = ukf::MerweScaledSigmaPoints(n, alpha, beta, kappa, ukf::subtract_fn);\n\n  // Dont really need, but current implementation requires a u to pass to motion_model.\n  Eigen::Vector2d u;\n  u << 0.0, 0.0;\n\n  // noisy control input\n  Eigen::Vector2d ud;\n\n  // observation z\n  Eigen::Vector2d z;\n\n  // dead reckoning\n  Eigen::Vector4d xDR;\n  xDR << 0.1,1.0,0.1,1.0;\n\n  // ground truth reading\n  Eigen::Vector4d xTrue;\n  xTrue << 0.1,1.0,0.1,1.0;\n\n  Eigen::Vector4d xEst;\n  xEst << 0.1,1.0,0.1,1.0;\n\n  std::vector<Eigen::Vector4d> hxDR;\n  std::vector<Eigen::Vector4d> hxTrue;\n  std::vector<Eigen::Vector4d> hxEst;\n  std::vector<Eigen::Vector2d> hz;\n\n  Eigen::Matrix4d PEst = Eigen::Matrix4d::Identity();\n\n  // Motion model covariance\n  Eigen::Matrix4d Q = Eigen::Matrix4d::Identity();\n  Q(0,0)=0.25 * (dt*dt*dt*dt) * 0.02;\n  Q(0,1)=0.5 * (dt*dt*dt) * 0.02;\n  Q(1,0)=0.5 * (dt*dt*dt) * 0.02;\n  Q(1,1)=(dt*dt) * 0.02;\n  Q(2,2)=0.25 * (dt*dt*dt*dt) * 0.02;\n  Q(2,3)=0.5 * (dt*dt*dt) * 0.02;\n  Q(3,2)=0.5 * (dt*dt*dt) * 0.02;\n  Q(3,3)=(dt*dt) * 0.02;\n\n  Eigen::Matrix2d R = Eigen::Matrix2d::Identity();\n  R(0,0)=0.09;\n  R(1,1)=0.09;\n\n  // Motion model simulation error\n  Eigen::Matrix2d Qsim = Eigen::Matrix2d::Identity();\n  Qsim(0,0)=0.25 * (dt*dt*dt*dt) * 0.02;\n  Qsim(1,1)=(dt*dt) * 0.02;\n\n  // Observation model simulation error\n  Eigen::Matrix2d Rsim = Eigen::Matrix2d::Identity();\n  Rsim(0,0)=0.09;\n  Rsim(1,1)=0.09;\n\n  auto ukf = ukf::UnscentedKalmanFilter(\n                n,\n                z.rows(),\n                dt,\n                points,\n                ukf::wrap_angles_default,\n                ukf::motion_model_cv,\n                ukf::observation_model_cv,\n                ukf::residuals,\n                ukf::residuals,\n                ukf::mean_fn,\n                ukf::mean_fn);\n    ukf.Q = Q;\n    ukf.R = R;\n    auto time = 0.0;\n\n    std::random_device rd{};\n    std::mt19937 gen{rd()};\n    std::normal_distribution<> gaussian_d{0,1};\n\n    cv::namedWindow(\"ukf\");\n    while (time < 50.0) {\n      time += dt;\n\n      ud(0) = u(0) + gaussian_d(gen) * Qsim(0,0);\n      ud(1) = u(1) + gaussian_d(gen) * Qsim(1,1);\n\n      xTrue = ukf::motion_model_cv(xTrue, u, dt);\n      //std::cout << \"xTrue\" << xTrue << std::endl;\n      xDR = ukf::motion_model_cv(xDR, ud, dt);\n\n      z(0) = time + gaussian_d(gen) * Rsim(0,0);\n      z(1) = time + gaussian_d(gen) * Rsim(1,1);\n\n      ukf.predict(ud);\n      ukf.update(z);\n\n      auto xEst = ukf.x_post;\n\n      hxDR.push_back(xDR);\n      hxTrue.push_back(xTrue);\n      hxEst.push_back(xEst);\n      hz.push_back(z);\n\n      //visualization\n\n      cv::Mat bg(700,1500, CV_8UC3, cv::Scalar(255,255,255));\n\n      for(unsigned int j=0; j<hxDR.size(); j++){\n\n        // Green groundtruth\n        // State is found at index 0 and 2.\n        Eigen::Vector2d x_true;\n        x_true << hxTrue[j](0), hxTrue[j](2);\n        cv::circle(bg, rviz::cv_offset(x_true, bg.cols, bg.rows),\n                   7, cv::Scalar(0,255,0), 2);\n\n        // blue estimation\n        Eigen::Vector2d x_est;\n        x_est << hxEst[j](0),hxEst[j](2);\n        cv::circle(bg, rviz::cv_offset(x_est, bg.cols, bg.rows),\n                   10, cv::Scalar(255,0,0), 5);\n\n        // black dead reckoning\n        Eigen::Vector2d x_dr;\n        x_dr << hxDR[j](0),hxDR[j](2);\n        cv::circle(bg, rviz::cv_offset(x_dr, bg.cols, bg.rows),\n                   7, cv::Scalar(0, 0, 0), -1);\n      }\n\n      // red observation\n      for(unsigned int i=0; i<hz.size(); i++){\n        cv::circle(bg, rviz::cv_offset(hz[i], bg.cols, bg.rows),\n                 7, cv::Scalar(0, 0, 255), -1);\n      }\n\n      Eigen::Vector2d ellipse_x_est;\n      ellipse_x_est << xEst(0), xEst(2);\n      rviz::ellipse_drawing(bg, PEst.block(0,0,2,2), ellipse_x_est);\n\n      cv::imshow(\"ukf\", bg);\n      cv::waitKey(5);\n\n    }\n}\n\n\nTEST(UKFTest, SimulationTest) {\n  auto n = 4; // [x y yaw v]'\n  auto dt = 0.1;\n  auto alpha = 0.001;\n  auto beta = 2.0;\n  auto kappa = 0.0;\n  auto points = ukf::MerweScaledSigmaPoints(n, alpha, beta, kappa, ukf::subtract_fn_x);\n\n  // control input v (m/s), yaw_rate (rad/s)\n  Eigen::Vector2d u;\n  u << 1.0, 0.1;\n\n  // noisy control input\n  Eigen::Vector2d ud;\n\n  // observation z\n  Eigen::Vector2d z;\n\n  // dead reckoning\n  Eigen::Vector4d xDR;\n  xDR << 0.1,0.1,0.0,1.0;\n\n  // ground truth reading\n  Eigen::Vector4d xTrue;\n  xTrue << 0.1,0.1,0.0,1.0;;\n\n  Eigen::Vector4d xEst;\n  xEst << 0.1,0.1,0.0,1.0;;\n\n  std::vector<Eigen::Vector4d> hxDR;\n  std::vector<Eigen::Vector4d> hxTrue;\n  std::vector<Eigen::Vector4d> hxEst;\n  std::vector<Eigen::Vector2d> hz;\n\n  Eigen::Matrix4d PEst = Eigen::Matrix4d::Identity();\n\n  // Motional model covariance\n  Eigen::Matrix4d Q = Eigen::Matrix4d::Identity();\n  Q(0,0)=0.25 * (dt*dt*dt*dt) * 0.02;\n  Q(0,1)=0.5 * (dt*dt*dt) * 0.02;\n  Q(1,0)=0.5 * (dt*dt*dt) * 0.02;\n  Q(1,1)=(dt*dt) * 0.02;\n  Q(2,2)=0.25 * (dt*dt*dt*dt) * 0.02;\n  Q(2,3)=0.5 * (dt*dt*dt) * 0.02;\n  Q(3,2)=0.5 * (dt*dt*dt) * 0.02;\n  Q(3,3)=(dt*dt) * 0.02;\n\n  Eigen::Matrix2d R = Eigen::Matrix2d::Identity();\n  R(0,0)=0.09;\n  R(1,1)=0.09;\n\n  // Motion model simulation error\n  Eigen::Matrix2d Qsim = Eigen::Matrix2d::Identity();\n  Qsim(0,0)=0.09;\n  Qsim(1,1)=0.09;\n\n  // Observation model simulation error\n  Eigen::Matrix2d Rsim = Eigen::Matrix2d::Identity();\n  Rsim(0,0)=0.09;\n  Rsim(1,1)=0.09;\n\n  auto ukf = ukf::UnscentedKalmanFilter(\n                n,\n                z.rows(),\n                dt,\n                points,\n                ukf::wrap_angles,\n                ukf::motion_model_4x4,\n                ukf::observation_model_2x4,\n                ukf::residuals_x,\n                ukf::residuals,\n                ukf::mean_fn_x,\n                ukf::mean_fn);\n\n  // Initial settings.\n  ukf.x = xTrue;\n  ukf.Q = Q;\n  ukf.R = R;\n\n  auto time = 0.0;\n\n  std::random_device rd{};\n  std::mt19937 gen{rd()};\n  std::normal_distribution<> gaussian_d{0,1};\n\n  cv::namedWindow(\"ukf\");\n  auto count = 0;\n  while (time < 100.0) {\n    time += dt;\n\n    ud(0) = u(0) + gaussian_d(gen) * Qsim(0,0);\n    ud(1) = u(1) + gaussian_d(gen) * Qsim(1,1);\n\n    xTrue = ukf::motion_model_4x4(xTrue, u, dt);\n\n    xDR = ukf::motion_model_4x4(xDR, ud, dt);\n\n    z(0) = xTrue(0) + gaussian_d(gen) * Rsim(0,0);\n    z(1) = xTrue(1) + gaussian_d(gen) * Rsim(1,1);\n\n    ukf.predict(ud);\n    ukf.update(z);\n\n    auto xEst = ukf.x_post;\n\n    hxDR.push_back(xDR);\n    hxTrue.push_back(xTrue);\n    hxEst.push_back(xEst);\n    hz.push_back(z);\n\n\n    // Visualization adapted from https://github.com/onlytailei/CppRobotics\n    cv::Mat bg(700,1500, CV_8UC3, cv::Scalar(255,255,255));\n    for(unsigned int j=0; j<hxDR.size(); j++){\n\n      // green groundtruth\n      cv::circle(bg, rviz::cv_offset(hxTrue[j].head(2), bg.cols, bg.rows),\n                 7, cv::Scalar(0,255,0), -1);\n\n      // blue estimation\n      cv::circle(bg, rviz::cv_offset(hxEst[j].head(2), bg.cols, bg.rows),\n                 10, cv::Scalar(255,0,0), 5);\n\n      // black dead reckoning\n      cv::circle(bg, rviz::cv_offset(hxDR[j].head(2), bg.cols, bg.rows),\n                 7, cv::Scalar(0, 0, 0), -1);\n    }\n\n    // red observation\n    for(unsigned int i=0; i<hz.size(); i++){\n      cv::circle(bg, rviz::cv_offset(hz[i], bg.cols, bg.rows),\n               7, cv::Scalar(0, 0, 255), -1);\n    }\n\n    rviz::ellipse_drawing(bg, PEst.block(0,0,2,2), xEst.head(2));\n    cv::imshow(\"ukf\", bg);\n    cv::waitKey(5);\n\n    std::string int_count = std::to_string(count++);\n    cv::imwrite(\"/home/tasuku/ws/CppLocalization/src/video/ukf_\"+int_count+\".png\", bg);\n  }\n}\n\n\nTEST(UKFTest, InitTest) {\n  auto dim_x = 4;\n  auto dim_z = 2;\n  auto dt = 1.0;\n  auto alpha = 1e-3;\n  auto beta = 2.0;\n  auto kappa = 0.0;\n  auto points = ukf::MerweScaledSigmaPoints(dim_x, alpha, beta, kappa, ukf::subtract_fn);\n\n  ukf::UnscentedKalmanFilter ukf = ukf::UnscentedKalmanFilter(\n                                                dim_x,\n                                                dim_z,\n                                                dt,\n                                                points,\n                                                ukf::wrap_angles_default,\n                                                ukf::linear_motion_model,\n                                                ukf::observation_model,\n                                                ukf::residuals,\n                                                ukf::residuals,\n                                                ukf::mean_fn,\n                                                ukf::mean_fn);\n  uint dim = ukf.x.size();\n  EXPECT_EQ(dim, 4);\n}\n", "meta": {"hexsha": "f95526215c920a37fed6945b296eb77166f47880", "size": 18951, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/unscented_kalman_filter_test.cpp", "max_stars_repo_name": "surfertas/CppLocalization", "max_stars_repo_head_hexsha": "091be1307cc9bb5c2f3be3ac61d276b678823c22", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-08-05T10:31:18.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-05T10:31:18.000Z", "max_issues_repo_path": "src/unscented_kalman_filter_test.cpp", "max_issues_repo_name": "surfertas/CppLocalization", "max_issues_repo_head_hexsha": "091be1307cc9bb5c2f3be3ac61d276b678823c22", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/unscented_kalman_filter_test.cpp", "max_forks_repo_name": "surfertas/CppLocalization", "max_forks_repo_head_hexsha": "091be1307cc9bb5c2f3be3ac61d276b678823c22", "max_forks_repo_licenses": ["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.2479224377, "max_line_length": 122, "alphanum_fraction": 0.5537438658, "num_tokens": 6518, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911056, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.4891150666257033}}
{"text": "//##########################################################################\n//#                                                                        #\n//#                       CLOUDCOMPARE PLUGIN: qPCL                        #\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; version 2 or later of the 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 General Public License for more details.                          #\n//#                                                                        #\n//#                         COPYRIGHT: Luca Penasa                         #\n//#                                                                        #\n//##########################################################################\n//\n#include \"StatisticalOutliersRemover.h\"\n\n//Local\n#include \"dialogs/StatisticalOutliersRemoverDlg.h\"\n#include \"../utils/cc2sm.h\"\n#include \"../utils/sm2cc.h\"\n\n//PCL\n#include <pcl/filters/statistical_outlier_removal.h>\n\n//qCC_plugins\n#include <ccMainAppInterface.h>\n\n//qCC_db\n#include <ccPointCloud.h>\n\n//Qt\n#include <QMainWindow>\n\n//Boost\n#include <boost/make_shared.hpp>\n\nvoid removeOutliersStatistical(const PCLCloud::ConstPtr incloud, int knn, double nSigma, PCLCloud::Ptr outcloud)\n{\n\tpcl::StatisticalOutlierRemoval<PCLCloud> remover;\n\tremover.setInputCloud(incloud);\n\tremover.setMeanK(knn);\n\tremover.setStddevMulThresh(nSigma);\n\tremover.filter(*outcloud);\n}\n\nStatisticalOutliersRemover::StatisticalOutliersRemover()\n\t: BaseFilter(FilterDescription(\"Statistical Outlier Removal\",\n\t\t\t\t\t\t\t\t\t\"Filter outlier data based on point neighborhood statistics\",\n\t\t\t\t\t\t\t\t\t\"Filter the points that are farther of their neighbors than the average (plus a number of times the standard deviation)\",\n\t\t\t\t\t\t\t\t\t\":/toolbar/PclUtils/icons/sor_outlier_remover.png\"))\n\t, m_dialog(0)\n\t, m_k(0)\n\t, m_std(0.0f)\n{\n}\n\nStatisticalOutliersRemover::~StatisticalOutliersRemover()\n{\n\t//we must delete parent-less dialogs ourselves!\n\tif (m_dialog && m_dialog->parent() == 0)\n\t\tdelete m_dialog;\n}\n\nint StatisticalOutliersRemover::compute()\n{\n\t//get selected as pointcloud\n\tccPointCloud* cloud = this->getSelectedEntityAsCCPointCloud();\n\tif (!cloud)\n\t\treturn -1;\n\n\t//now as sensor message\n\tPCLCloud::Ptr tmp_cloud = cc2smReader(cloud).getAsSM();\n\tif (!tmp_cloud)\n\t\treturn -1;\n\n\tPCLCloud::Ptr outcloud ( new PCLCloud);\n\tremoveOutliersStatistical(tmp_cloud, m_k, m_std, outcloud);\n\n\t//get back outcloud as a ccPointCloud\n\tccPointCloud* final_cloud = sm2ccConverter(outcloud).getCloud();\n\tif (!final_cloud)\n\t\treturn -1;\n\n\t//create a suitable name for the entity\n\tfinal_cloud->setName(QString(\"%1_k%2_std%3\").arg(cloud->getName()).arg(m_k).arg(m_std));\n\tfinal_cloud->setDisplay(cloud->getDisplay());\n\t//copy global shift & scale\n\tfinal_cloud->setGlobalScale(cloud->getGlobalScale());\n\tfinal_cloud->setGlobalShift(cloud->getGlobalShift());\n\n\t//disable original cloud\n\tcloud->setEnabled(false);\n\tif (cloud->getParent())\n\t\tcloud->getParent()->addChild(final_cloud);\n\n\temit newEntity(cloud);\n\n\treturn 1;\n}\n\nint StatisticalOutliersRemover::openInputDialog()\n{\n\tif (!m_dialog)\n\t{\n\t\tm_dialog = new SORDialog(m_app ? m_app->getMainWindow() : 0);\n\t}\n\n\treturn m_dialog->exec() ? 1 : 0;\n}\n\nvoid StatisticalOutliersRemover::getParametersFromDialog()\n{\n\t//get values from dialog\n\tif (m_dialog)\n\t{\n\t\tm_k = m_dialog->spinK->value();\n\t\tm_std = static_cast<float>(m_dialog->spinStd->value());\n\t}\n}\n", "meta": {"hexsha": "5a909a560fae23d0e94bbfb22ca0c0e6e3a6865a", "size": 3877, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "plugins/core/qPCL/PclUtils/filters/StatisticalOutliersRemover.cpp", "max_stars_repo_name": "ohanlonl/qCMAT", "max_stars_repo_head_hexsha": "f6ca04fa7c171629f094ee886364c46ff8b27c0b", "max_stars_repo_licenses": ["BSD-Source-Code"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "plugins/core/qPCL/PclUtils/filters/StatisticalOutliersRemover.cpp", "max_issues_repo_name": "ohanlonl/qCMAT", "max_issues_repo_head_hexsha": "f6ca04fa7c171629f094ee886364c46ff8b27c0b", "max_issues_repo_licenses": ["BSD-Source-Code"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "plugins/core/qPCL/PclUtils/filters/StatisticalOutliersRemover.cpp", "max_forks_repo_name": "ohanlonl/qCMAT", "max_forks_repo_head_hexsha": "f6ca04fa7c171629f094ee886364c46ff8b27c0b", "max_forks_repo_licenses": ["BSD-Source-Code"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-02-03T12:19:42.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-03T12:19:42.000Z", "avg_line_length": 31.5203252033, "max_line_length": 130, "alphanum_fraction": 0.6076863554, "num_tokens": 870, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149978955811, "lm_q2_score": 0.6477982247516796, "lm_q1q2_score": 0.4890325954751754}}
{"text": "/* --------------------------------------------------------------------------\n*\n* (C) Copyright \u2026\n*\n* ---------------------------------------------------------------------------\n*/\n\n/*!\n * @file Transform3DToEigenTransformConverter.cpp\n * @date 22/01/2018\n * @authors Alessandro Bianco\n */\n\n/*!\n * @addtogroup Converters\n * \n * Implementation of Transform3DToEigenTransformConverter class.\n * \n * \n * @{\n */\n\n/* --------------------------------------------------------------------------\n *\n * Includes\n *\n * --------------------------------------------------------------------------\n */\n\n#include \"Transform3DToEigenTransformConverter.hpp\"\n#include <Errors/Assert.hpp>\n#include <Eigen/Geometry>\n\nnamespace Converters {\n\nusing namespace PoseWrapper;\n\n/* --------------------------------------------------------------------------\n *\n * Public Member Functions\n *\n * --------------------------------------------------------------------------\n */\nconst Eigen::Matrix4f Transform3DToEigenTransformConverter::Convert(const PoseWrapper::Transform3DConstPtr& transform)\n\t{\n\tEigen::Matrix4f conversion;\n\n\tEigen::Quaternionf eigenRotation( GetWOrientation(*transform), GetXOrientation(*transform), GetYOrientation(*transform), GetZOrientation(*transform));\n\tEigen::Matrix3f rotationMatrix = eigenRotation.toRotationMatrix();\n\n\tEigen::Translation<float, 3> eigenTranslation( GetXPosition(*transform), GetYPosition(*transform), GetZPosition(*transform));\t\n\t\n\tconversion << \trotationMatrix(0,0), rotationMatrix(0,1), rotationMatrix(0,2), eigenTranslation.x(),\n\t\t\trotationMatrix(1,0), rotationMatrix(1,1), rotationMatrix(1,2), eigenTranslation.y(),\n\t\t\trotationMatrix(2,0), rotationMatrix(2,1), rotationMatrix(2,2), eigenTranslation.z(),\n\t\t\t0, 0, 0, 1;\n\n\treturn conversion;\n\t}\n\nconst Eigen::Matrix4f Transform3DToEigenTransformConverter::ConvertShared(const PoseWrapper::Transform3DSharedConstPtr& transform)\n\t{\n\treturn Convert(transform.get());\n\t}\n\n}\n\n/** @} */\n", "meta": {"hexsha": "31a95c76830eaeb5af8d0ddcee7f19cdd5114f8d", "size": 1948, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Common/Converters/Transform3DToEigenTransformConverter.cpp", "max_stars_repo_name": "H2020-InFuse/cdff", "max_stars_repo_head_hexsha": "e55fd48f9a909d0c274c3dfa4fe2704bc5071542", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-02-26T15:09:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-30T07:39:01.000Z", "max_issues_repo_path": "Common/Converters/Transform3DToEigenTransformConverter.cpp", "max_issues_repo_name": "H2020-InFuse/cdff", "max_issues_repo_head_hexsha": "e55fd48f9a909d0c274c3dfa4fe2704bc5071542", "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": "Common/Converters/Transform3DToEigenTransformConverter.cpp", "max_forks_repo_name": "H2020-InFuse/cdff", "max_forks_repo_head_hexsha": "e55fd48f9a909d0c274c3dfa4fe2704bc5071542", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-06T12:09:05.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-06T12:09:05.000Z", "avg_line_length": 28.231884058, "max_line_length": 151, "alphanum_fraction": 0.5662217659, "num_tokens": 389, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6477982247516797, "lm_q1q2_score": 0.48903258833128715}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// detail::fusion::example::joint_view_bind_range.cpp                  \t\t //\n//                                                                           //\n//  Copyright 2009 Erwann Rogard. Distributed under the Boost                //\n//  Software License, Version 1.0. (See accompanying file                    //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)         //\n/////////////////////////////////////////////////////////////////////////////// \n#include <iostream>\n#include <boost/mpl/int.hpp>\n#include <boost/range.hpp>\n#include <boost/array.hpp>\n#include <boost/multi_array.hpp>\n#include <boost/fusion/include/pair.hpp>\n#include <boost/fusion/include/map.hpp>\n#include <boost/fusion/include/make_map.hpp>\n#include <boost/fusion/include/at_key.hpp>\n#include <boost/assign/list_of.hpp>\n#include <boost/assign/list_inserter.hpp>\n\n#include <boost/iterator/flatten_iterator.hpp>\n\n#include <boost/statistics/detail/fusion/joint_view/flatten_bind_range.hpp>\n#include <libs/statistics/detail/fusion/example/joint_view_flatten_bind_range.h>\n\n\nvoid example_joint_view_flatten_bind_range(std::ostream&){\n\n\tnamespace jv = boost::statistics::detail::fusion::joint_view;\n   \n\ttypedef int val_;\n    typedef boost::mpl::int_<0> \t\t\t\t\tk0_;\n    typedef boost::mpl::int_<1> \t\t\t\t\tk1_;\n\tconst int n = 2;\n    \n\ttypedef boost::fusion::pair<k0_,val_> \t\t\tp0_;\n    typedef boost::fusion::map<p0_>\t\t\t\t\tm0_;\n\ttypedef boost::fusion::pair<k1_,val_> \t\t\tp1_;\n    typedef boost::fusion::map<p1_>\t\t\t\t\tm1_;\n    \n    typedef boost::array<m0_,n>\t\t\t\t\t\tar0_;\n    typedef boost::range_iterator<ar0_>::type \t\tit0_;\n\ttypedef boost::multi_array<m1_, 2> \t\t\t\tma1_;\n    typedef boost::range_iterator<ma1_>::type \t\tit1_;\n\ttypedef boost::multi_array_types::index_range \tidx_range_;\n\ttypedef boost::multi_array_types::index \t\tidx_;\n    \n\ttypedef boost::array_view_gen<ma1_,2>::type \tview2_ma1_;\n    \n    typedef jv::result_of::flatten_bind_range<it0_,it1_> meta_; \n    typedef meta_::type \t\t\t\t\t\t\tflat_r_;\n\ttypedef boost::range_iterator<flat_r_>::type\tflat_it_;\n\n\tar0_ ar0 = boost::assign::list_of(\n    \tboost::fusion::make_map<k0_>(1)\n    )(\n      \tboost::fusion::make_map<k0_>(2)\n    );\n\n\tma1_ ma1(boost::extents[n][2]);\n    {\n        std::vector<m1_> vals1;\n    \tusing namespace boost::assign;\n        vals1 = list_of(\n        \tboost::fusion::make_map<k1_>(1)\n        )(\n        \tboost::fusion::make_map<k1_>(2)\n        )(\n        \tboost::fusion::make_map<k1_>(3)\n        )(\n        \tboost::fusion::make_map<k1_>(4)\n        );\n        ma1.assign(boost::begin(vals1),boost::end(vals1));\n\t}        \n    \n\tflat_r_ flat_r = jv::flatten_bind_range(\n    \tboost::begin(ar0),\n        boost::end(ar0),\n    \tboost::begin(ma1),\n        boost::end(ma1)\n    );\n\n\tflat_it_ flat_b = boost::begin(flat_r);\n\tflat_it_ flat_e = boost::end(flat_r);\n\n\t// BUG : post increment causes runtime error.\n\twhile(flat_b!=flat_e){\n    \tstd::cout \n        \t<< '(' \n            << boost::fusion::at_key<k0_>(*flat_b)\n        \t<< ','\n            << boost::fusion::at_key<k1_>(*flat_b)\n        \t<< ')' \n            << std::endl;\n        ++flat_b;\n    }\n\n}\n", "meta": {"hexsha": "c4abf2fbfcbf3af1d92efea67f965a71b460c3cd", "size": 3189, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "detail/fusion/libs/statistics/detail/fusion/example/joint_view_flatten_bind_range.cpp", "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": "detail/fusion/libs/statistics/detail/fusion/example/joint_view_flatten_bind_range.cpp", "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": "detail/fusion/libs/statistics/detail/fusion/example/joint_view_flatten_bind_range.cpp", "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.5408163265, "max_line_length": 80, "alphanum_fraction": 0.5841956726, "num_tokens": 823, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.4890325831981904}}
{"text": "#ifndef PYBNESIAN_UTIL_COMBINATIONS_HPP\n#define PYBNESIAN_UTIL_COMBINATIONS_HPP\n\n#include <vector>\n#include <unordered_set>\n#include <boost/math/special_functions/binomial.hpp>\n#include <util/parameter_traits.hpp>\n\nnamespace util {\n\ntemplate <typename T>\nclass Combinations {\npublic:\n    Combinations() = default;\n\n    // TODO: Check m_k > fixed.size().\n    template <typename Iter, util::enable_if_iterator_t<Iter, int> = 0>\n    Combinations(Iter begin, Iter end, int k)\n        : m_elements(begin, end),\n          m_fixed(),\n          m_k(k),\n          m_num_combinations(\n              std::round(boost::math::binomial_coefficient<double>(m_elements.size(), m_k - m_fixed.size()))) {}\n\n    template <typename Iter,\n              typename IterFixed,\n              util::enable_if_iterator_t<Iter, int> = 0,\n              util::enable_if_iterator_t<IterFixed, int> = 0>\n    Combinations(Iter begin, Iter end, IterFixed begin_fixed, IterFixed end_fixed, int k)\n        : m_elements(begin, end),\n          m_fixed(begin_fixed, end_fixed),\n          m_k(k),\n          m_num_combinations(\n              std::round(boost::math::binomial_coefficient<double>(m_elements.size(), m_k - m_fixed.size()))) {\n        static_assert(std::is_same_v<typename std::iterator_traits<Iter>::value_type,\n                                     typename std::iterator_traits<IterFixed>::value_type>,\n                      \"The type of fixed and movable elements should be the same.\");\n    }\n\n    template <typename V, util::enable_if_vector_of_type_t<V, T, int> = 0>\n    Combinations(V elements, int k)\n        : m_elements(elements),\n          m_fixed(),\n          m_k(k),\n          m_num_combinations(\n              std::round(boost::math::binomial_coefficient<double>(m_elements.size(), m_k - m_fixed.size()))) {}\n\n    template <typename V,\n              typename V2,\n              util::enable_if_vector_of_type_t<V, T, int> = 0,\n              util::enable_if_vector_of_type_t<V2, T, int> = 0>\n    Combinations(V elements, V2 fixed, int k)\n        : m_elements(elements),\n          m_fixed(fixed),\n          m_k(k),\n          m_num_combinations(\n              std::round(boost::math::binomial_coefficient<double>(m_elements.size(), m_k - m_fixed.size()))) {}\n\n    class combination_iterator {\n    public:\n        using iterator_category = std::input_iterator_tag;\n        using value_type = std::vector<T>;\n        using difference_type = int;\n        using pointer = std::vector<T>*;\n        using reference = std::vector<T>&;\n\n        combination_iterator() = default;\n\n        combination_iterator(const Combinations<T>* self, int idx) : m_self(self), m_subset(), m_indices(), m_idx(idx) {\n            m_subset.reserve(m_self->m_k);\n\n            for (size_t i = 0; i < m_self->m_fixed.size(); ++i) {\n                m_subset.push_back(m_self->m_fixed[i]);\n            }\n\n            auto p = m_self->m_k - m_self->m_fixed.size();\n            m_indices.reserve(p);\n\n            for (size_t i = 0; i < p; ++i) {\n                m_subset.push_back(m_self->m_elements[i]);\n                m_indices.push_back(i);\n            }\n        }\n\n        combination_iterator(const combination_iterator& other)\n            : m_self(other.m_self), m_subset(other.m_subset), m_indices(other.m_indices), m_idx(other.m_idx) {}\n\n        combination_iterator& operator=(const combination_iterator& other) {\n            m_self = other.m_self;\n            m_subset = other.m_subset;\n            m_indices = other.m_indices;\n            m_idx = other.m_idx;\n            return *this;\n        }\n\n        void next_subset() {\n            int offset = m_self->m_fixed.size();\n            int p = m_self->m_k - offset;\n\n            for (int i = p - 1; i >= 0; --i) {\n                auto k = i + offset;\n                auto max_index = m_self->m_elements.size() - p + i;\n\n                if (m_indices[i] < max_index) {\n                    ++m_indices[i];\n                    m_subset[k] = m_self->m_elements[m_indices[i]];\n\n                    for (int j = i + 1; j < p; ++j) {\n                        m_indices[j] = m_indices[j - 1] + 1;\n                        m_subset[j + offset] = m_self->m_elements[m_indices[j]];\n                    }\n\n                    break;\n                }\n            }\n        }\n\n        combination_iterator& operator++() {\n            ++m_idx;\n            next_subset();\n            return *this;\n        }\n\n        combination_iterator operator++(int) {\n            combination_iterator return_it(*this);\n            ++m_idx;\n            next_subset();\n            return return_it;\n        }\n\n        reference operator*() { return m_subset; }\n\n        pointer operator->() { return &m_subset; }\n\n        bool operator==(const combination_iterator& rhs) { return (m_idx == rhs.m_idx) && (m_self == rhs.m_self); }\n\n        bool operator!=(const combination_iterator& rhs) { return !(*this == rhs); }\n\n    private:\n        const Combinations<T>* m_self;\n        std::vector<T> m_subset;\n        std::vector<size_t> m_indices;\n        int m_idx;\n    };\n\n    combination_iterator begin() const { return combination_iterator(this, 0); }\n    combination_iterator end() const { return combination_iterator(this, num_combinations()); }\n\n    int num_combinations() const { return m_num_combinations; }\n\nprivate:\n    std::vector<T> m_elements;\n    std::vector<T> m_fixed;\n    int m_k;\n    int m_num_combinations;\n};\n\ntemplate <typename Iter>\nCombinations(Iter, Iter, int) -> Combinations<typename std::iterator_traits<Iter>::value_type>;\ntemplate <typename Iter, typename IterFixed>\nCombinations(Iter, Iter, IterFixed, IterFixed, int) -> Combinations<typename std::iterator_traits<Iter>::value_type>;\ntemplate <typename V>\nCombinations(V, int) -> Combinations<typename V::value_type>;\ntemplate <typename V, typename V2>\nCombinations(V, V2, int) -> Combinations<typename V::value_type>;\n\ntemplate <typename T>\nclass Combinations2Sets {\npublic:\n    template <typename Iter,\n              typename Iter2,\n              util::enable_if_iterator_t<Iter, int> = 0,\n              util::enable_if_iterator_t<Iter2, int> = 0>\n    Combinations2Sets(Iter begin_set1, Iter end_set1, Iter2 begin_set2, Iter2 end_set2, int k)\n        : Combinations2Sets(std::vector(begin_set1, end_set1), std::vector(begin_set2, end_set2), k) {\n        static_assert(std::is_same_v<typename std::iterator_traits<Iter>::value_type,\n                                     typename std::iterator_traits<Iter2>::value_type>,\n                      \"The elements of both sets should be of the same type\");\n    }\n\n    template <typename V,\n              typename V2,\n              util::enable_if_vector_of_type_t<V, T, int> = 0,\n              util::enable_if_vector_of_type_t<V2, T, int> = 0>\n    Combinations2Sets(V v1, V2 v2, int k)\n        : m_comb1(), m_comb2(), m_comb2_valid_combinations(), m_num_combinations(-1), m_k(k) {\n        std::sort(v1.begin(), v1.end());\n        std::sort(v2.begin(), v2.end());\n\n        std::unordered_set<T> common_elements;\n        std::set_intersection(\n            v1.begin(), v1.end(), v2.begin(), v2.end(), std::inserter(common_elements, common_elements.end()));\n\n        m_comb1 = Combinations<T>(std::move(v1), m_k);\n        if (static_cast<int>(common_elements.size()) < k) {\n            m_comb2 = Combinations<T>(std::move(v2), m_k);\n            m_comb2_valid_combinations = m_comb2.num_combinations();\n        } else {\n            for (size_t i = 0, common_start = v2.size() - common_elements.size(); i < common_start; ++i) {\n                if (common_elements.count(v2[i]) > 0) {\n                    for (size_t j = v2.size() - 1; j >= common_start; --j) {\n                        if (common_elements.count(v2[j]) == 0) {\n                            std::swap(v2[i], v2[j]);\n                        }\n                    }\n                }\n            }\n\n            m_comb2 = Combinations<T>(std::move(v2), m_k);\n            m_comb2_valid_combinations =\n                m_comb2.num_combinations() -\n                std::round(boost::math::binomial_coefficient<double>(common_elements.size(), m_k));\n        }\n\n        m_num_combinations = m_comb1.num_combinations() + m_comb2_valid_combinations;\n    }\n\n    class combination2set_iterator {\n    public:\n        using iterator_category = std::input_iterator_tag;\n        using value_type = std::vector<T>;\n        using difference_type = int;\n        using pointer = std::vector<T>*;\n        using reference = std::vector<T>&;\n\n        combination2set_iterator(const Combinations2Sets<T>& self, int idx) : m_self(self), it() {\n            if (idx < m_self.m_comb1.num_combinations() || m_self.m_comb2_valid_combinations == 0) {\n                it = typename Combinations<T>::combination_iterator(&m_self.m_comb1, idx);\n            } else {\n                it = typename Combinations<T>::combination_iterator(&m_self.m_comb2,\n                                                                    idx - m_self.m_comb1.num_combinations());\n            }\n        }\n\n        combination2set_iterator& operator++() {\n            ++it;\n            if (it == m_self.m_comb1.end() && m_self.m_comb2_valid_combinations > 0) {\n                it = m_self.m_comb2.begin();\n            }\n            return *this;\n        }\n\n        combination2set_iterator operator++(int) {\n            combination2set_iterator return_it(*this);\n            ++it;\n            if (it == m_self.m_comb1.end() && m_self.m_comb2_valid_combinations > 0) {\n                it = m_self.m_comb2.begin();\n            }\n            return return_it;\n        }\n\n        reference operator*() { return *it; }\n\n        pointer operator->() { return &it.m_subset; }\n\n        bool operator==(const combination2set_iterator& rhs) { return it == rhs.it; }\n\n        bool operator!=(const combination2set_iterator& rhs) { return !(*this == rhs); }\n\n    private:\n        const Combinations2Sets<T>& m_self;\n        typename Combinations<T>::combination_iterator it;\n    };\n\n    combination2set_iterator begin() { return combination2set_iterator(*this, 0); }\n    combination2set_iterator end() { return combination2set_iterator(*this, num_combinations()); }\n\n    int num_combinations() const { return m_num_combinations; }\n\nprivate:\n    Combinations<T> m_comb1;\n    Combinations<T> m_comb2;\n    int m_comb2_valid_combinations;\n    int m_num_combinations;\n    int m_k;\n};\n\ntemplate <typename Iter, typename Iter2>\nCombinations2Sets(Iter, Iter, Iter2, Iter2, int) -> Combinations2Sets<typename std::iterator_traits<Iter>::value_type>;\ntemplate <typename V, typename V2>\nCombinations2Sets(V, V2, int) -> Combinations2Sets<typename V::value_type>;\n\ntemplate <typename T>\nclass AllSubsets {\npublic:\n    AllSubsets() = default;\n\n    template <typename Iter, util::enable_if_iterator_t<Iter, int> = 0>\n    AllSubsets(Iter begin, Iter end, int min_k, int max_k)\n        : m_elements(begin, end), m_fixed(), m_min_k(min_k), m_max_k(max_k), m_num_combinations(0) {\n        for (int i = min_k; i <= max_k; ++i) {\n            m_num_combinations += std::round(boost::math::binomial_coefficient<double>(m_elements.size(), i));\n        }\n    }\n\n    template <typename Iter,\n              typename IterFixed,\n              util::enable_if_iterator_t<Iter, int> = 0,\n              util::enable_if_iterator_t<IterFixed, int> = 0>\n    AllSubsets(Iter begin, Iter end, IterFixed begin_fixed, IterFixed end_fixed, int min_k, int max_k)\n        : m_elements(begin, end),\n          m_fixed(begin_fixed, end_fixed),\n          m_min_k(min_k),\n          m_max_k(max_k),\n          m_num_combinations(0) {\n        static_assert(std::is_same_v<typename std::iterator_traits<Iter>::value_type,\n                                     typename std::iterator_traits<IterFixed>::value_type>,\n                      \"The type of fixed and movable elements should be the same.\");\n        for (int i = min_k; i <= max_k; ++i) {\n            m_num_combinations +=\n                std::round(boost::math::binomial_coefficient<double>(m_elements.size(), i - m_fixed.size()));\n        }\n    }\n\n    template <typename V, util::enable_if_vector_of_type_t<V, T, int> = 0>\n    AllSubsets(V elements, int min_k, int max_k)\n        : m_elements(elements), m_min_k(min_k), m_max_k(max_k), m_num_combinations(0) {\n        for (int i = min_k; i <= max_k; ++i) {\n            m_num_combinations += std::round(boost::math::binomial_coefficient<double>(m_elements.size(), i));\n        }\n    }\n\n    template <typename V,\n              typename V2,\n              util::enable_if_vector_of_type_t<V, T, int> = 0,\n              util::enable_if_vector_of_type_t<V2, T, int> = 0>\n    AllSubsets(V elements, V2 fixed, int min_k, int max_k)\n        : m_elements(elements), m_fixed(fixed), m_min_k(min_k), m_max_k(max_k), m_num_combinations(0) {\n        for (int i = min_k; i <= max_k; ++i) {\n            m_num_combinations +=\n                std::round(boost::math::binomial_coefficient<double>(m_elements.size(), i - m_fixed.size()));\n        }\n    }\n\n    class allsubsets_iterator {\n    public:\n        using iterator_category = std::input_iterator_tag;\n        using value_type = std::vector<T>;\n        using difference_type = int;\n        using pointer = std::vector<T>*;\n        using reference = std::vector<T>&;\n\n        allsubsets_iterator() = default;\n\n        allsubsets_iterator(const AllSubsets<T>* self, int idx)\n            : m_self(self), m_idx(idx), m_current_comb(), m_current_iter(), m_current_k(m_self->m_min_k) {\n            if (idx == 0) {\n                m_current_comb = Combinations(m_self->m_elements.begin(),\n                                              m_self->m_elements.end(),\n                                              m_self->m_fixed.begin(),\n                                              m_self->m_fixed.end(),\n                                              m_current_k);\n                m_current_iter = m_current_comb.begin();\n            }\n        }\n\n        allsubsets_iterator& operator=(const allsubsets_iterator& other) {\n            m_self = other.m_self;\n            m_idx = other.m_idx;\n            m_current_comb = other.m_current_comb;\n            m_current_iter = other.m_current_iter;\n            m_current_k = other.m_current_k;\n            return *this;\n        }\n\n        allsubsets_iterator& operator++() {\n            ++m_current_iter;\n            ++m_idx;\n\n            if (m_current_iter == m_current_comb.end() && m_current_k < m_self->m_max_k) {\n                ++m_current_k;\n                m_current_comb = Combinations(m_self->m_elements.begin(),\n                                              m_self->m_elements.end(),\n                                              m_self->m_fixed.begin(),\n                                              m_self->m_fixed.end(),\n                                              m_current_k);\n                m_current_iter = m_current_comb.begin();\n            }\n\n            return *this;\n        }\n\n        allsubsets_iterator operator++(int) {\n            allsubsets_iterator return_it(*this);\n\n            ++m_current_iter;\n            ++m_idx;\n            if (m_current_iter == m_current_comb.end() && m_current_k < m_self->m_max_k) {\n                ++m_current_k;\n                m_current_comb = Combinations(m_self->m_elements.begin(),\n                                              m_self->m_elements.end(),\n                                              m_self->m_fixed.begin(),\n                                              m_self->m_fixed.end(),\n                                              m_current_k);\n                m_current_iter = m_current_comb.begin();\n            }\n\n            return return_it;\n        }\n\n        reference operator*() { return *m_current_iter; }\n\n        pointer operator->() { return &m_current_iter.m_subset; }\n\n        bool operator==(const allsubsets_iterator& rhs) { return (m_idx == rhs.m_idx) && (m_self == rhs.m_self); }\n\n        bool operator!=(const allsubsets_iterator& rhs) { return !(*this == rhs); }\n\n    private:\n        const AllSubsets<T>* m_self;\n        int m_idx;\n        Combinations<T> m_current_comb;\n        typename Combinations<T>::combination_iterator m_current_iter;\n        int m_current_k;\n    };\n\n    allsubsets_iterator begin() const { return allsubsets_iterator(this, 0); }\n    allsubsets_iterator end() const { return allsubsets_iterator(this, num_combinations()); }\n\n    int num_combinations() const { return m_num_combinations; }\n\nprivate:\n    std::vector<T> m_elements;\n    std::vector<T> m_fixed;\n    int m_min_k;\n    int m_max_k;\n    int m_num_combinations;\n};\n\ntemplate <typename Iter>\nAllSubsets(Iter, Iter, int, int) -> AllSubsets<typename std::iterator_traits<Iter>::value_type>;\ntemplate <typename Iter, typename IterFixed>\nAllSubsets(Iter, Iter, IterFixed, IterFixed, int, int) -> AllSubsets<typename std::iterator_traits<Iter>::value_type>;\ntemplate <typename V>\nAllSubsets(V, int, int) -> AllSubsets<typename V::value_type>;\ntemplate <typename V, typename V2>\nAllSubsets(V, V2, int, int) -> AllSubsets<typename V::value_type>;\n\n}  // namespace util\n\n#endif  // PYBNESIAN_UTIL_COMBINATIONS_HPP\n", "meta": {"hexsha": "526d40f6d7e1974b6834317925219ca6adf91a34", "size": 17099, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pybnesian/util/combinations.hpp", "max_stars_repo_name": "vishalbelsare/PyBNesian", "max_stars_repo_head_hexsha": "0190cd4cf6d133746741e2750004ccf0a9061fbd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2021-06-22T19:21:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T13:08:05.000Z", "max_issues_repo_path": "pybnesian/util/combinations.hpp", "max_issues_repo_name": "vishalbelsare/PyBNesian", "max_issues_repo_head_hexsha": "0190cd4cf6d133746741e2750004ccf0a9061fbd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pybnesian/util/combinations.hpp", "max_forks_repo_name": "vishalbelsare/PyBNesian", "max_forks_repo_head_hexsha": "0190cd4cf6d133746741e2750004ccf0a9061fbd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-08-20T13:44:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T02:57:02.000Z", "avg_line_length": 38.685520362, "max_line_length": 120, "alphanum_fraction": 0.5790397099, "num_tokens": 3966, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.4890325831981904}}
{"text": "#include \"inverter.hpp\"\n#include <Eigen/LU>\n\nEigen::MatrixXd Inverter::getInverse(const Eigen::MatrixXd &M) {\n  return M.inverse();\n}\n\nEigen::MatrixXd Inverter::getInverse(const Eigen::MatrixXd &M, double offset) {\n  return M.inverse().array() + offset;\n}\n\nstd::vector<Eigen::MatrixXd> Inverter::getInverseList(std::vector<Eigen::MatrixXd> matrices) {\n  std::vector<Eigen::MatrixXd> result;\n  result.reserve(matrices.size());\n  for (std::vector<Eigen::MatrixXd>::iterator mat = matrices.begin(); mat != matrices.end(); ++mat) {\n    result.push_back(mat->inverse());\n  }\n  return result;\n}\n\nEigen::MatrixXd Inverter::getInverseRef(const Eigen::Ref<const Eigen::MatrixXd> & M) {\n  return M.inverse();\n}\n", "meta": {"hexsha": "0be1cb7a0eaa17ffc9b200ec44eccd6108bbfe48", "size": 701, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/inverter.cpp", "max_stars_repo_name": "tbiasi/tom-convwconv", "max_stars_repo_head_hexsha": "554ec31fe3f3a9e633828e91e42d93f49eb3679e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/inverter.cpp", "max_issues_repo_name": "tbiasi/tom-convwconv", "max_issues_repo_head_hexsha": "554ec31fe3f3a9e633828e91e42d93f49eb3679e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/inverter.cpp", "max_forks_repo_name": "tbiasi/tom-convwconv", "max_forks_repo_head_hexsha": "554ec31fe3f3a9e633828e91e42d93f49eb3679e", "max_forks_repo_licenses": ["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.2083333333, "max_line_length": 101, "alphanum_fraction": 0.7032810271, "num_tokens": 176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.6477982247516797, "lm_q1q2_score": 0.48903258118739873}}
{"text": "//\n// Copyright (c) 2018 CNRS\n// Authors: Pierre Fernbach\n//\n// This file is part of bezier_COM_traj\n// hpp-core is free software: you can redistribute it\n// and/or modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation, either version\n// 3 of the License, or (at your option) any later version.\n//\n// hpp-core is distributed in the hope that it will be\n// useful, but WITHOUT ANY WARRANTY; without even the implied warranty\n// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n// General Lesser Public License for more details.  You should have\n// received a copy of the GNU Lesser General Public License along with\n// hpp-core  If not, see\n// <http://www.gnu.org/licenses/>.\n\n#define BOOST_TEST_MODULE transition\n#include <boost/test/included/unit_test.hpp>\n#include <hpp/bezier-com-traj/solve.hh>\n#include <hpp/bezier-com-traj/common_solve_methods.hh>\n#include <hpp/bezier-com-traj/data.hh>\n#include <hpp/centroidal-dynamics/centroidal_dynamics.hh>\n#include \"test_helper.hh\"\n#include <ndcurves/bezier_curve.h>\n\nusing namespace bezier_com_traj;\nconst double T = 1.5;\n\nProblemData buildPData(\n    const centroidal_dynamics::EquilibriumAlgorithm algo = centroidal_dynamics::EQUILIBRIUM_ALGORITHM_PP) {\n  ProblemData pData;\n  pData.c0_ = Vector3(0, 0.5, 5.);\n  pData.c1_ = Vector3(2, -0.5, 5.);\n  pData.dc0_ = Vector3::Zero();\n  pData.dc1_ = Vector3::Zero();\n  pData.ddc0_ = Vector3::Zero();\n  pData.ddc1_ = Vector3::Zero();\n  pData.constraints_.flag_ = INIT_POS | INIT_VEL | END_VEL | END_POS;\n\n  MatrixX3 normals(2, 3), positions(2, 3);\n  normals.block<1, 3>(0, 0) = Vector3(0, 0, 1);\n  positions.block<1, 3>(0, 0) = Vector3(0, 0.1, 0);\n  normals.block<1, 3>(1, 0) = Vector3(0, 0, 1);\n  positions.block<1, 3>(1, 0) = Vector3(0, -0.1, 0);\n  std::pair<MatrixX3, MatrixX3> contacts = computeRectangularContacts(normals, positions, LX, LY);\n  pData.contacts_.push_back(\n      new centroidal_dynamics::Equilibrium(ComputeContactCone(contacts.first, contacts.second, algo)));\n\n  return pData;\n}\n\nstd::vector<point_t> generate_wps() { return computeConstantWaypoints(buildPData(), T); }\n\nbezier_wp_t::t_point_t generate_wps_symbolic() { return computeConstantWaypointsSymbolic(buildPData(), T); }\n\nVectorX eval(const waypoint_t& w, const point_t& x) { return w.first * x + w.second; }\n\nvoid vectorEqual(const VectorX& a, const VectorX& b, const double EPS = 1e-14) {\n  BOOST_CHECK_EQUAL(a.size(), b.size());\n  BOOST_CHECK((a - b).norm() < EPS);\n}\n\nBOOST_AUTO_TEST_SUITE(symbolic)\n\nBOOST_AUTO_TEST_CASE(symbolic_eval_c) {\n  std::vector<point_t> pts = generate_wps();\n  bezier_wp_t::t_point_t wps = generate_wps_symbolic();\n  point_t y(1, 0.2, 4.5);\n  pts[2] = y;\n\n  bezier_t c(pts.begin(), pts.end(), 0., T);\n  bezier_wp_t c_sym(wps.begin(), wps.end(), 0., T);\n\n  double t = 0.;\n  while (t < T) {\n    vectorEqual(c(t), eval(c_sym(t), y));\n    t += 0.01;\n  }\n}\n\nBOOST_AUTO_TEST_CASE(symbolic_eval_dc) {\n  std::vector<point_t> pts = generate_wps();\n  bezier_wp_t::t_point_t wps = generate_wps_symbolic();\n  point_t y(1, 0.2, 4.5);\n  pts[2] = y;\n\n  bezier_t c(pts.begin(), pts.end(), 0., T);\n  bezier_t dc = c.compute_derivate(1);\n  bezier_wp_t c_sym(wps.begin(), wps.end(), 0., T);\n  bezier_wp_t dc_sym = c_sym.compute_derivate(1);\n\n  double t = 0.;\n  while (t < T) {\n    vectorEqual(dc(t), eval(dc_sym(t), y));\n    t += 0.01;\n  }\n}\n\nBOOST_AUTO_TEST_CASE(symbolic_eval_ddc) {\n  std::vector<point_t> pts = generate_wps();\n  bezier_wp_t::t_point_t wps = generate_wps_symbolic();\n  point_t y(1, 0.2, 4.5);\n  pts[2] = y;\n\n  bezier_t c(pts.begin(), pts.end(), 0., T);\n  bezier_t ddc = c.compute_derivate(2);\n  bezier_wp_t c_sym(wps.begin(), wps.end(), 0., T);\n  bezier_wp_t ddc_sym = c_sym.compute_derivate(2);\n\n  double t = 0.;\n  while (t < T) {\n    vectorEqual(ddc(t), eval(ddc_sym(t), y), 1e-10);\n    t += 0.01;\n  }\n}\n\nBOOST_AUTO_TEST_CASE(symbolic_eval_jc) {\n  std::vector<point_t> pts = generate_wps();\n  bezier_wp_t::t_point_t wps = generate_wps_symbolic();\n  point_t y(1, 0.2, 4.5);\n  pts[2] = y;\n\n  bezier_t c(pts.begin(), pts.end(), 0., T);\n  bezier_t jc = c.compute_derivate(3);\n  bezier_wp_t c_sym(wps.begin(), wps.end(), 0., T);\n  bezier_wp_t jc_sym = c_sym.compute_derivate(3);\n\n  double t = 0.;\n  while (t < T) {\n    vectorEqual(jc(t), eval(jc_sym(t), y), 1e-10);\n    t += 0.01;\n  }\n}\n\nBOOST_AUTO_TEST_CASE(symbolic_split_c) {\n  std::vector<point_t> pts = generate_wps();\n  bezier_wp_t::t_point_t wps = generate_wps_symbolic();\n  point_t y(1, 0.2, 4.5);\n  pts[2] = y;\n\n  bezier_t c(pts.begin(), pts.end(), 0., T);\n  bezier_wp_t c_sym(wps.begin(), wps.end(), 0., T);\n\n  double a, b, t, t1, t2;\n  for (size_t i = 0; i < 100; ++i) {\n    a = (rand() / (double)RAND_MAX) * T;\n    b = (rand() / (double)RAND_MAX) * T;\n    t1 = std::min(a, b);\n    t2 = std::max(a, b);\n    // std::cout<<\"try extract between : [\"<<t1<<\";\"<<t2<<\"] \"<<std::endl;\n    bezier_t c_e = c.extract(t1, t2);\n    bezier_wp_t c_sym_e = c_sym.extract(t1, t2);\n    t = t1;\n    while (t < t2) {\n      vectorEqual(c_e(t), eval(c_sym_e(t), y));\n      vectorEqual(c(t), eval(c_sym_e(t), y));\n      t += 0.01;\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE(symbolic_split_c_bench) {\n  using namespace std;\n\n  std::vector<point_t> pts = generate_wps();\n  bezier_wp_t::t_point_t wps = generate_wps_symbolic();\n  point_t y(1, 0.2, 4.5);\n  pts[2] = y;\n\n  bezier_wp_t c_sym(wps.begin(), wps.end(), 0., T);\n\n  std::vector<double> values;\n  for (int i = 0; i < 100000; ++i) values.push_back((double)rand() / RAND_MAX);\n\n  clock_t s0, e0;\n  std::pair<bezier_wp_t, bezier_wp_t> splitted = c_sym.split(0.5);\n  s0 = clock();\n  for (std::vector<double>::const_iterator cit = values.begin(); cit != values.end(); ++cit) {\n    splitted = c_sym.split(*cit);\n  }\n  e0 = clock();\n\n  std::cout << \"Time required to split a c curve : \" << ((double)(e0 - s0) / CLOCKS_PER_SEC) / 100. << \" ms \"\n            << std::endl;\n}\n\nBOOST_AUTO_TEST_CASE(symbolic_split_w) {\n  bezier_wp_t::t_point_t wps = computeWwaypoints(buildPData(), T);\n  point_t y(1, 0.2, 4.5);\n\n  bezier_wp_t w(wps.begin(), wps.end(), 0., T);\n\n  double a, b, t, t1, t2;\n  for (size_t i = 0; i < 100; ++i) {\n    a = (rand() / (double)RAND_MAX) * T;\n    b = (rand() / (double)RAND_MAX) * T;\n    t1 = std::min(a, b);\n    t2 = std::max(a, b);\n    // std::cout<<\"try extract between : [\"<<t1<<\";\"<<t2<<\"] \"<<std::endl;\n    bezier_wp_t w_e = w.extract(t1, t2);\n    t = t1;\n    while (t < t2) {\n      vectorEqual(eval(w(t), y), eval(w_e(t), y), 1e-12);\n      t += 0.01;\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE(symbolic_split_w_bench) {\n  bezier_wp_t::t_point_t wps = computeWwaypoints(buildPData(), T);\n  point_t y(1, 0.2, 4.5);\n\n  bezier_wp_t w(wps.begin(), wps.end(), 0., T);\n\n  std::vector<double> values;\n  for (int i = 0; i < 100000; ++i) values.push_back((double)rand() / RAND_MAX);\n\n  clock_t s0, e0;\n  std::pair<bezier_wp_t, bezier_wp_t> splitted = w.split(0.5);\n  s0 = clock();\n  for (std::vector<double>::const_iterator cit = values.begin(); cit != values.end(); ++cit) {\n    splitted = w.split(*cit);\n  }\n  e0 = clock();\n\n  std::cout << \"Time required to split a w curve : \" << ((double)(e0 - s0) / CLOCKS_PER_SEC) / 100. << \" ms \"\n            << std::endl;\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "3154d050e8d31e6c8ef50ef1c5a9dbeef62b3984", "size": 7254, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test-bezier-symbolic.cpp", "max_stars_repo_name": "nim65s/hpp-bezier-com-traj", "max_stars_repo_head_hexsha": "7cb25463a353cd917468af12e5b325c8366af66e", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2019-09-17T13:06:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-09T22:52:40.000Z", "max_issues_repo_path": "tests/test-bezier-symbolic.cpp", "max_issues_repo_name": "nim65s/hpp-bezier-com-traj", "max_issues_repo_head_hexsha": "7cb25463a353cd917468af12e5b325c8366af66e", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-01-16T10:02:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-16T17:14:00.000Z", "max_forks_repo_path": "tests/test-bezier-symbolic.cpp", "max_forks_repo_name": "nim65s/hpp-bezier-com-traj", "max_forks_repo_head_hexsha": "7cb25463a353cd917468af12e5b325c8366af66e", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2019-02-04T14:36:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-20T15:42:17.000Z", "avg_line_length": 31.1330472103, "max_line_length": 109, "alphanum_fraction": 0.6451612903, "num_tokens": 2440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.489032576054302}}
{"text": "/* vim: set ts=2 sts=2 et sw=2 tw=80: */\n/**\n * matrix_matrix.cc\n *\n * Author: Jeff Hajewski\n * Created: 7/27/20127\n *\n * Matrix-matrix multiplication benchmarks\n */\n#include <cmath>\n#include <iostream>\n#include <vector>\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n#include <Eigen/Dense>\n\n#include \"matrix_matrix.hpp\"\n#include \"results.hpp\"\n#include \"timer.hpp\"\n#include \"utility.hpp\"\n\n#define MAX_ROW_SIZE 10000\n#define MAX_COL_SIZE 10000\n#define N_MEAN 100\n#define N_STD 23.5\n#define TOL 0.00001\n\nnamespace ublas = boost::numeric::ublas;\n\nublas::matrix<double> create_ublas_matrix(const size_t rows, const size_t cols) {\n  ublas::matrix<double> m(rows, cols);\n  for (size_t i = 0; i < rows; ++i) {\n    for (size_t j = 0; j < cols; ++j) {\n      m(i, j) = random_double(N_MEAN, N_STD);\n    }\n  }\n  return m;\n}\n\nEigen::MatrixXd create_eigen_matrix(const size_t rows, const size_t cols) {\n  Eigen::MatrixXd m(rows, cols);\n  for (size_t i = 0; i < rows; ++i) {\n    for (size_t j = 0; j < cols; ++j) {\n      m(i, j) = random_double(N_MEAN, N_STD);\n    }\n  }\n  return m;\n}\n\nBenchmarkResults run_matrix_matrix_benchmark(size_t N) {\n  BenchmarkResults results = BenchmarkResults(N);\n  auto timer = Timer();\n\n  const size_t rows = 10;\n  const size_t cols = 10;\n  for (size_t i = 0; i < N; ++i) {\n    \n    // Create matrices\n    auto A_eigen = create_eigen_matrix(rows, cols);\n    auto B_eigen = create_eigen_matrix(rows, cols);\n    auto A_ublas = create_ublas_matrix(rows, cols);\n    auto B_ublas = create_ublas_matrix(rows, cols);\n\n    // Benchmark\n    double unused;\n    timer.start();\n    auto C_eigen = A_eigen * B_eigen;\n    unused = C_eigen(0, 0);\n    timer.stop();\n    auto elapsed = timer.elapsed_time();\n    std::cout <<\"elapsed: \" << elapsed << '\\n';\n    results.push_back(BenchmarkType::Eigen, timer.elapsed_time());\n\n    timer.start();\n    auto C_ublas = ublas::prod(A_ublas, B_ublas);\n    unused = C_ublas(0, 0);\n    timer.stop();\n    results.push_back(BenchmarkType::uBLAS, timer.elapsed_time());\n  }\n  return results;\n}\n", "meta": {"hexsha": "10cb131ee1b5fd96aa98b487940582aad016b799", "size": 2065, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/matrix_matrix.cc", "max_stars_repo_name": "j-haj/ublas-eigen-benchmark", "max_stars_repo_head_hexsha": "8dec4a509a486f5812719ec612367c6df5026412", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-09-22T04:29:40.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-22T04:29:40.000Z", "max_issues_repo_path": "src/matrix_matrix.cc", "max_issues_repo_name": "j-haj/ublas-eigen-benchmark", "max_issues_repo_head_hexsha": "8dec4a509a486f5812719ec612367c6df5026412", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/matrix_matrix.cc", "max_forks_repo_name": "j-haj/ublas-eigen-benchmark", "max_forks_repo_head_hexsha": "8dec4a509a486f5812719ec612367c6df5026412", "max_forks_repo_licenses": ["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.5833333333, "max_line_length": 81, "alphanum_fraction": 0.6590799031, "num_tokens": 613, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149758396753, "lm_q2_score": 0.647798211152541, "lm_q1q2_score": 0.48903257092120533}}
{"text": "#include <cstdlib>\n#include <dlib/optimization/max_cost_assignment.h>\n#include \"pairing.h\"\n\n\nusing namespace std;\n\ndouble get_rate(const Route &passenger, const Route &driver) {\n\n  double rate = passenger.r /\n                (passenger.r +\n                 sqrt((driver.start_long - passenger.start_long) * (driver.start_long - passenger.start_long) +\n                      (driver.start_lat - passenger.start_lat) * (driver.start_lat - passenger.start_lat)) +\n                 sqrt((driver.end_long - passenger.end_long) * (driver.end_long - passenger.end_long) +\n                      (driver.end_lat - passenger.end_lat) * (driver.end_lat - passenger.end_lat))\n                );\n  return rate;\n}\n\n", "meta": {"hexsha": "bd278e489123ac0c0fc9471affe50ce1ca60dced", "size": 701, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pairing.cpp", "max_stars_repo_name": "a1exwang/drivers_pairing", "max_stars_repo_head_hexsha": "c3f386b27bd7b6be2f4751598bda36ccd1c2f3f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pairing.cpp", "max_issues_repo_name": "a1exwang/drivers_pairing", "max_issues_repo_head_hexsha": "c3f386b27bd7b6be2f4751598bda36ccd1c2f3f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pairing.cpp", "max_forks_repo_name": "a1exwang/drivers_pairing", "max_forks_repo_head_hexsha": "c3f386b27bd7b6be2f4751598bda36ccd1c2f3f6", "max_forks_repo_licenses": ["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.05, "max_line_length": 111, "alphanum_fraction": 0.6305278174, "num_tokens": 146, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.48903256578810844}}
{"text": "#include \"dense-reconstruction/disparity-conversion-utils.h\"\n\n#include <limits>\n#include <memory>\n#include <string>\n#include <vector>\n\n#include <Eigen/Dense>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n\nnamespace dense_reconstruction {\nnamespace stereo {\n\nvoid convertDisparityMapToPointCloud(\n    const cv::Mat& input_disparity, const cv::Mat& left_image,\n    const double baseline, const double focal_length, const double cx,\n    const double cy, const int sad_window_size, const int min_disparity,\n    const int num_disparities, resources::PointCloud* pointcloud) {\n  CHECK_NOTNULL(pointcloud);\n  CHECK(pointcloud->empty());\n  CHECK_GT(focal_length, 0.0);\n\n  if (left_image.type() != CV_8U) {\n    LOG(ERROR)\n        << \"Pointcloud generation is currently only supported on 8 bit images\";\n    return;\n  }\n\n  const int side_bound = sad_window_size / 2;\n\n  const int max_size = input_disparity.rows * input_disparity.cols;\n\n  pointcloud->xyz.reserve(3 * max_size);\n  pointcloud->colors.reserve(3 * max_size);\n\n  cv::Mat input_valid =\n      cv::Mat(input_disparity.rows, input_disparity.cols, CV_8U);\n\n  const int lower_x_border = side_bound + min_disparity + num_disparities;\n  const int lower_y_border = side_bound;\n  const int upper_x_border = input_disparity.cols - side_bound;\n  const int upper_y_border = input_disparity.rows - side_bound;\n\n  const int disparity_threshold = (min_disparity + num_disparities - 1) * 16;\n\n  for (int y_pixels = 0; y_pixels < input_disparity.rows; ++y_pixels) {\n    for (int x_pixels = 0; x_pixels < input_disparity.cols; ++x_pixels) {\n      // The last check is because the sky has a bad habit of having a disparity\n      // at just less than the max disparity.\n      const int16_t disparity_value =\n          input_disparity.at<int16_t>(y_pixels, x_pixels);\n      if ((x_pixels < lower_x_border) || (y_pixels < lower_y_border) ||\n          (x_pixels > upper_x_border) || (y_pixels > upper_y_border) ||\n          (disparity_value < 0) || (disparity_value >= disparity_threshold)) {\n        input_valid.at<uint8_t>(y_pixels, x_pixels) = 0;\n      } else {\n        input_valid.at<uint8_t>(y_pixels, x_pixels) = 1;\n      }\n    }\n  }\n\n  // Build pointcloud.\n  for (int y_pixels = lower_y_border; y_pixels < upper_y_border; ++y_pixels) {\n    for (int x_pixels = lower_x_border; x_pixels < upper_x_border; ++x_pixels) {\n      const bool is_valid = input_valid.at<uint8_t>(y_pixels, x_pixels) > 0u;\n      const int16_t input_value =\n          input_disparity.at<int16_t>(y_pixels, x_pixels);\n\n      double disparity_value;\n\n      // If the filled disparity is valid it must be a freespace ray.\n      if (is_valid) {\n        disparity_value = static_cast<double>(input_value);\n      } else {\n        continue;\n      }\n\n      if (disparity_value < 1e-6) {\n        continue;\n      }\n\n      // The 16x is needed as opencv stores disparity maps as 16 * the true\n      // values.\n\n      // NOTE(mfehr): This is the reprojection formula based on:\n      // Source: http://answers.opencv.org/upfiles/13535653931527438.jpg\n      // We undistort such that cx_left and cx_right are identical, therefore\n      // the formula can be simplified to:\n      // X = -b(x-Cx)/d\n      // Y = -b(y - Cy) / d\n      // Z = -(f*b)/d\n      // with t = -b/d we get:\n      // X = t * (x-Cx)\n      // Y = t * (y - Cy)\n      // Z = t * f\n\n      const double t = -16.0 * baseline / disparity_value;\n      const double z = t * focal_length;\n      const double x = t * (x_pixels - cx);\n      const double y = t * (y_pixels - cy);\n\n      LOG_IF(WARNING, z < 0.0) << \"Z is negative, which is weird!\";\n\n      uint8_t r, g, b;\n      if (left_image.channels() == 3) {\n        const cv::Vec3b& color = left_image.at<cv::Vec3b>(y_pixels, x_pixels);\n        b = color[0];\n        g = color[1];\n        r = color[2];\n      } else if (left_image.channels() == 4) {\n        const cv::Vec4b& color = left_image.at<cv::Vec4b>(y_pixels, x_pixels);\n        b = color[0];\n        g = color[1];\n        r = color[2];\n      } else {\n        b = left_image.at<uint8_t>(y_pixels, x_pixels);\n        g = b;\n        r = b;\n      }\n\n      pointcloud->xyz.push_back(x);\n      pointcloud->xyz.push_back(y);\n      pointcloud->xyz.push_back(z);\n\n      pointcloud->colors.push_back(r);\n      pointcloud->colors.push_back(g);\n      pointcloud->colors.push_back(b);\n    }\n  }\n  CHECK_LE(pointcloud->size(), 3 * max_size);\n}\n\n// Convert disparity map to a depth map in the target camera frame.\n// NOTE(mfehr): This is definitely not the most efficient way to do this, but it\n// uses the available infrastructure. If speed is an issue, this needs to\n// be improved.\nvoid convertDisparityMapToDepthMap(\n    const cv::Mat& disparity_map, const cv::Mat& first_image_undistorted,\n    const double baseline, const double focal_length, const double cx,\n    const double cy, const int sad_window_size, const int min_disparity,\n    const int num_disparities, const aslam::Camera& target_camera,\n    cv::Mat* depth_map) {\n  CHECK_NOTNULL(depth_map);\n  CHECK(!disparity_map.empty());\n  CHECK(!first_image_undistorted.empty());\n\n  // Convert disparity to point cloud.\n  resources::PointCloud point_cloud;\n  convertDisparityMapToPointCloud(\n      disparity_map, first_image_undistorted, baseline, focal_length, cx, cy,\n      sad_window_size, min_disparity, num_disparities, &point_cloud);\n\n  // Convert point cloud format to Eigen matrix.\n  const size_t point_cloud_size = point_cloud.size();\n  const size_t max_index = point_cloud_size * 3u;\n  Eigen::Matrix3Xd p_C1_mat(3, point_cloud_size);\n  size_t point_idx = 0u;\n  for (size_t idx = 0u; idx < max_index; idx += 3u, ++point_idx) {\n    CHECK_LT(point_idx, point_cloud_size);\n    p_C1_mat.col(point_idx) = Eigen::Vector3d(\n        point_cloud.xyz[idx], point_cloud.xyz[idx + 1u],\n        point_cloud.xyz[idx + 2u]);\n  }\n\n  // Init depth map.\n  const size_t height = target_camera.imageHeight();\n  const size_t width = target_camera.imageWidth();\n  *depth_map = cv::Mat(height, width, CV_16UC1, cv::Scalar(0u));\n\n  // Project all 3D points into the image.\n  Eigen::Matrix2Xd img_points_px;\n  std::vector<aslam::ProjectionResult> projection_results;\n  target_camera.project3Vectorized(\n      p_C1_mat, &img_points_px, &projection_results);\n\n  // Convert Z coordinate of points to millimeters.\n  constexpr double kMetersToMillimeters = 1e3;\n\n  // Statistics.\n  for (point_idx = 0u; point_idx < point_cloud_size; ++point_idx) {\n    if (!projection_results[point_idx].isKeypointVisible()) {\n      continue;\n    }\n\n    const Eigen::Ref<const Eigen::Vector2d>& img_point =\n        img_points_px.col(point_idx);\n\n    const int depth_in_mm = std::min(\n        static_cast<int>(std::numeric_limits<uint16_t>::max()),\n        static_cast<int>(p_C1_mat(2, point_idx) * kMetersToMillimeters));\n    CHECK_GE(depth_in_mm, 0);\n\n    const int img_u = static_cast<int>(std::round(img_point[0]));\n    const int img_v = static_cast<int>(std::round(img_point[1]));\n    depth_map->at<uint16_t>(img_v, img_u) = static_cast<uint16_t>(depth_in_mm);\n  }\n}\n\n}  // namespace stereo\n}  // namespace dense_reconstruction\n", "meta": {"hexsha": "20730e56a2ba0e74b2379f1bf2bf5ca768751455", "size": 7128, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "algorithms/dense-reconstruction/stereo-dense-reconstruction/src/disparity-conversion-utils.cpp", "max_stars_repo_name": "AdronTech/maplab", "max_stars_repo_head_hexsha": "1340e01466fc1c02994860723b8117daf9ad226d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1936.0, "max_stars_repo_stars_event_min_datetime": "2017-11-27T23:11:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T14:24:14.000Z", "max_issues_repo_path": "algorithms/dense-reconstruction/stereo-dense-reconstruction/src/disparity-conversion-utils.cpp", "max_issues_repo_name": "AdronTech/maplab", "max_issues_repo_head_hexsha": "1340e01466fc1c02994860723b8117daf9ad226d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 353.0, "max_issues_repo_issues_event_min_datetime": "2017-11-29T18:40:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T15:53:46.000Z", "max_forks_repo_path": "algorithms/dense-reconstruction/stereo-dense-reconstruction/src/disparity-conversion-utils.cpp", "max_forks_repo_name": "AdronTech/maplab", "max_forks_repo_head_hexsha": "1340e01466fc1c02994860723b8117daf9ad226d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 661.0, "max_forks_repo_forks_event_min_datetime": "2017-11-28T07:20:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T08:06:29.000Z", "avg_line_length": 35.2871287129, "max_line_length": 80, "alphanum_fraction": 0.6708754209, "num_tokens": 1920, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152497, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.48901156718994354}}
{"text": "#include \"ALConstraint.h\"\n#include \"BrownianBody.h\"\n#include \"LBFGSBWrapper.h\"\n#include \"Model.h\"\n#include \"OPSMesh.h\"\n#include \"ViscosityBody.h\"\n#include <Eigen/Eigenvalues>\n#include <stdio.h>\n#include <string>\n#include <vector>\n#include <vtkPolyDataReader.h>\n\nusing namespace OPS;\ntypedef Eigen::Matrix3d Matrix3d;\ntypedef Eigen::Vector3d Vector3d;\n\nint main(int argc, char *argv[]) {\n  clock_t t1, t2, t3;\n  t1 = clock();\n\n  if (argc != 2) {\n    cout << \"usage: \" << argv[0] << \" <filename>\\n\";\n    return -1;\n  }\n\n  //******************** Optional parameters ********************//\n  bool loggingOn = false;\n\n  // ***************** Read Input VTK File *****************//\n  std::string inputFileName = argv[1];\n\n  auto reader = vtkSmartPointer<vtkPolyDataReader>::New();\n  vtkSmartPointer<vtkPolyData> mesh;\n\n  reader->SetFileName(inputFileName.c_str());\n  reader->ReadAllVectorsOn();\n  reader->Update();\n  mesh = reader->GetOutput();\n  // ********************************************************//\n\n  // ******************* Read Simulation Parameters *********//\n\n  // This flag determines if its a new simulation or a continuation\n\n  double_t re = 1.0, s = 7.0;\n  double_t alpha = 1.0, beta = 1.0, gamma = 1.0;\n  double_t percentStrain = 15;\n\n  enum Constraint { AvgArea, AvgVol, ExactArea, ExactVol, ExactAreaAndVolume };\n  std::string constraintType(\"NULL\"), baseFileName;\n  size_t viterMax = 1000;\n  size_t nameSuffix = 0;\n  size_t step = 0;\n\n  InputParameters miscInp = OPS::readKeyValueInput(\"miscInp.dat\");\n  re = std::stod(miscInp[\"re\"]);\n  constraintType = miscInp[\"constraintType\"];\n  baseFileName = miscInp[\"baseFileName\"];\n\n  // Validate constraint type\n  Constraint type;\n  if (constraintType.compare(\"AverageArea\") == 0) {\n    type = AvgArea;\n  } else if (constraintType.compare(\"AverageVolume\") == 0) {\n    type = AvgArea;\n  } else if (constraintType.compare(\"ExactArea\") == 0) {\n    type = ExactArea;\n  } else if (constraintType.compare(\"ExactVolume\") == 0) {\n    type = ExactVol;\n  } else if (constraintType.compare(\"ExactAreaAndVolume\") == 0) {\n    type = ExactAreaAndVolume;\n  } else {\n    std::cout << \"Invalid constraint type specified.\" << std::endl;\n    exit(EXIT_FAILURE);\n  }\n\n  // Input file should contain the following columns\n  // Alpha Beta Gamma PercentStrain AreaConstraint NumIterations PrintStep\n  std::ifstream coolFile(\"schedule.dat\");\n  assert(coolFile);\n  std::vector<std::vector<double_t>> coolVec;\n  double_t currAlpha, currBeta, currGamma, currPercentStrain, currViterMax,\n      currPrintStep, currArea;\n\n  std::string headerline;\n  std::getline(coolFile, headerline);\n\n  while (coolFile >> currAlpha >> currBeta >> currGamma >> currPercentStrain >>\n         currArea >> currViterMax >> currPrintStep) {\n    std::vector<double> currLine;\n    currLine.push_back(currAlpha);\n    currLine.push_back(currBeta);\n    currLine.push_back(currGamma);\n    currLine.push_back(currPercentStrain);\n    currLine.push_back(currArea);\n    currLine.push_back(currViterMax);\n    currLine.push_back(currPrintStep);\n    coolVec.push_back(currLine);\n  }\n  coolFile.close();\n\n  // **********************************************************//\n\n  // ***************** Create Bodies and Model ****************//\n  // Set number of OPS particles\n  size_t N = mesh->GetNumberOfPoints();\n\n  // Read point coordinates from input mesh\n  Eigen::Matrix3Xd coords(3, N);\n  for (auto i = 0; i < N; ++i) {\n    Eigen::Vector3d cp = Eigen::Vector3d::Zero();\n    mesh->GetPoint(i, &(cp(0)));\n    coords.col(i) = cp;\n  }\n\n  // Prepare memory for energy, force\n  double_t f;\n  Eigen::VectorXd x(6 * N), g(6 * N), prevX(3 * N);\n  g.setZero(g.size());\n  x.setZero(x.size());\n\n  // Fill x with coords and rotVecs\n  Eigen::Map<Eigen::Matrix3Xd> xpos(x.data(), 3, N), xrot(&(x(3 * N)), 3, N),\n      prevPos(prevX.data(), 3, N);\n  xpos = coords;\n\n  // Renormalize the position vectors by average edge length\n  x /= getPointCloudAvgEdgeLen(inputFileName);\n  prevX = x.head(3 * N);\n\n  // Generate initial rotation vectors either from starting point coordinates\n  OPSBody::initialRotationVector(xpos, xrot);\n\n  // The starting average radius\n  double_t R0 = xpos.colwise().norm().sum() / N;\n\n  // Create OPSBody\n  Eigen::Map<Eigen::Matrix3Xd> posGrad(g.data(), 3, N),\n      rotGrad(&g(3 * N), 3, N);\n  OPSMesh ops(N, f, R0, xpos, xrot, posGrad, rotGrad, prevPos);\n  ops.setMorseDistance(re);\n  s = 100 * log(2.0) / (re * percentStrain);\n  ops.setMorseWellWidth(s);\n\n  // Create Brownian and Viscosity bodies\n  Eigen::Map<Eigen::VectorXd> thermalX(x.data(), 3 * N, 1);\n  Eigen::Map<Eigen::VectorXd> thermalG(g.data(), 3 * N, 1);\n  double_t brownCoeff = 1.0, viscosity = 1.0;\n  BrownianBody brown(3 * N, brownCoeff, f, thermalX, thermalG, prevX);\n  ViscosityBody visco(3 * N, viscosity, f, thermalX, thermalG, prevX);\n\n  // Create the Augmented Lagrangian volume constraint body\n  ALConstraint *constraint;\n  if (type == AvgArea) {\n    constraint = new AvgAreaConstraint(N, f, xpos, posGrad);\n  } else if (type == AvgVol) {\n    constraint = new AvgVolConstraint(N, f, xpos, posGrad);\n  } else if (type == ExactArea) {\n    vtkSmartPointer<vtkPolyData> poly = ops.getPolyData();\n    constraint = new ExactAreaConstraint(N, f, xpos, posGrad, poly);\n  } else if (type == ExactVol) {\n    vtkSmartPointer<vtkPolyData> poly = ops.getPolyData();\n    constraint = new ExactVolConstraint(N, f, xpos, posGrad, poly);\n  } else if (type == ExactAreaAndVolume) {\n    vtkSmartPointer<vtkPolyData> poly = ops.getPolyData();\n    constraint = new ExactAreaVolConstraint(N, f, xpos, posGrad, poly);\n    constraint->setTolerance(1e-8);\n  }\n\n  // Create Model\n  Model model(6 * N, f, g);\n  model.addBody(&ops);\n  model.addBody(&brown);\n  model.addBody(&visco);\n  model.addBody(constraint);\n  // ****************************************************************//\n\n  // ***************** Prepare Output Data files *********************//\n  // Identify the Input structure name\n  std::string fname = baseFileName;\n  std::stringstream sstm;\n  std::string dataOutputFile;\n\n  // Detailed output data file\nstd::ofstream detailedOP;\n  sstm << fname << \"-DetailedOutput.dat\";\n  dataOutputFile = sstm.str();\n  sstm.str(\"\");\n  sstm.clear();\n  detailedOP.open(dataOutputFile.c_str(), std::ofstream::out);\n  detailedOP << \"Gamma\"\n             << \"\\t\"\n             << \"Beta\"\n             << \"\\t\"\n             << \"Asphericity\"\n             << \"\\t\"\n             << \"MorseEn\"\n             << \"\\t\"\n             << \"NormEn\"\n             << \"\\t\"\n             << \"CircEn\"\n             << \"\\t\"\n             << \"BrownEn\"\n             << \"\\t\"\n             << \"ViscoEn\"\n             << \"\\t\"\n             << \"MSD\"\n             << \"\\t\"\n             << \"RMSAngleDeficit\"\n             << \"\\t\"\n             << \"I1\"\n             << \"\\t\"\n             << \"I2\"\n             << \"\\t\"\n             << \"I3\" << std::endl;\n\n  // ************************* Create Solver ************************  //\n  size_t m = 5, iprint = 1000, maxIter = 1e5;\n  double_t factr = 10.0, pgtol = 1e-8;\n  LBFGSBParams solverParams(m, iprint, maxIter, factr, pgtol);\n  LBFGSBWrapper solver(solverParams, model, f, x, g);\n  solver.turnOffLogging();\n  // *****************************************************************//\n\n  // ********************* Prepare data for simulation ****************//\n  // Calculate Average Edge Length\n  double_t avgEdgeLen = ops.getAverageEdgeLength();\n  if (loggingOn) {\n    std::cout << \"Initial Avg Edge Length = \" << avgEdgeLen << std::endl;\n  }\n  // Renormalize positions such that avgEdgeLen = 1.0\n  for (auto i = 0; i < N; ++i) {\n    xpos.col(i) = xpos.col(i) / avgEdgeLen;\n  }\n\n  // Update the OPSBody member variables as per new positions\n  ops.updatePolyData();\n  ops.updateNeighbors();\n  ops.saveInitialPosition(); /*!< For Mean Squared Displacement */\n  avgEdgeLen = ops.getAverageEdgeLength();\n  if (loggingOn)\n    std::cout << \"After renormalizing, Avg Edge Length = \" << avgEdgeLen\n              << std::endl;\n  // ******************************************************************//\n\n  // Create an eigenvalue solver for inertia tensor\n  Eigen::SelfAdjointEigenSolver<Matrix3d> saes;\n\n  // ************************ OUTER SOLUTION LOOP **********************//\n  size_t printStep;\n  for (int z = 0; z < coolVec.size(); z++) {\n    alpha = coolVec[z][0];\n    beta = coolVec[z][1];\n    gamma = coolVec[z][2];\n    percentStrain = coolVec[z][3];\n    double_t constrainedVal = coolVec[z][4];\n    viterMax = coolVec[z][5];\n    printStep = (int)coolVec[z][6];\n\n    // Update OPS params\n    s = (100 / percentStrain) * log(2.0);\n    ops.setFVK(gamma);\n    ops.setMorseWellWidth(s);\n\n    // Set up the constraint value as the zero temperature value\n    constraint->setConstraint(constrainedVal);\n\n    // For the very first iteration solve at zero temperature first\n    if (z == 0) {\n      brown.setCoefficient(0.0);\n      visco.setViscosity(0.0);\n      solver.solve();\n    }\n\n    // Update prevX\n    prevX = x.head(3 * N);\n\n    // Set the viscosity and Brownian coefficient\n    viscosity = alpha;\n    brownCoeff = std::sqrt(2 * alpha / beta);\n    if (loggingOn) {\n      std::cout << \"Viscosity = \" << viscosity << std::endl;\n      std::cout << \"Brownian Coefficient = \" << brownCoeff << std::endl;\n    }\n    brown.setCoefficient(brownCoeff);\n    visco.setViscosity(viscosity);\n\n    //**************  INNER SOLUTION LOOP ******************//\n    // Average energy across time steps\n    double_t avgTotalEnergy = 0.0;\n\n    for (int viter = 0; viter < viterMax; viter++) {\n      if (loggingOn)\n        std::cout << std::endl\n                  << \"VISCOUS ITERATION: \" << step << std::endl\n                  << std::endl;\n\n      // Generate Brownian Kicks\n      brown.generateParallelKicks();\n\n      // Set the starting guess for Lambda and K for\n      // Augmented Lagrangian\n      constraint->setLagrangeCoeff(10.0);\n      constraint->setPenaltyCoeff(1000.0);\n\n      // *************** Augmented Lagrangian Loop ************** //\n      bool constraintMet = false;\n      size_t alIter = 0, alMaxIter = 10;\n\n      while (!constraintMet && (alIter < alMaxIter)) {\n        if (loggingOn)\n          std::cout << \"Augmented Lagrangian iteration: \" << alIter\n                    << std::endl;\n\n        // Solve the unconstrained minimization\n        solver.solve();\n\n        // Uzawa update\n        constraint->uzawaUpdate();\n\n        // Update termination check quantities\n        alIter++;\n        constraintMet = constraint->constraintSatisfied();\n      }\n      if (loggingOn) {\n        constraint->printCompletion();\n        std::cout << \"Constraint satisfied in \" << alIter << \" iterations.\"\n                  << std::endl\n                  << std::endl;\n      }\n      // *********************************************************//\n\n      // Apply Kabsch Algorithm\n      ops.applyKabschAlgorithm();\n\n      // Update kdTree, polyData and neighbors\n      ops.updatePolyData();\n      ops.updateNeighbors();\n\n      //********** Print relaxed configuration ************//\n      // We will print only after every currPrintStep iterations\n      if (viter % printStep == 0 && printStep <= viterMax) {\n        sstm << fname << \"-relaxed-\" << nameSuffix++ << \".vtk\";\n        std::string rName = sstm.str();\n        ops.printVTKFile(rName);\n        sstm.str(\"\");\n        sstm.clear();\n      }\n\n      // Calculate the inertia tensor and its eigenvalues\n      Matrix3d M = Matrix3d::Zero();\n      for (auto ptId = 0; ptId < N; ++ptId) {\n        Vector3d xk = xpos.col(ptId);\n        M += xk.dot(xk) * Matrix3d::Identity() - xk * xk.transpose();\n      }\n      // Now calculate the eigen values\n      saes.compute(M, Eigen::EigenvaluesOnly);\n      Vector3d eigV = saes.eigenvalues();\n\n      double_t I1 = eigV[0];\n      double_t I2 = eigV[1];\n      double_t I3 = eigV[2];\n\n      std::vector<double_t> msds(2, 0);\n      msds = ops.getMSD();\n\n      // Write output to data file\n      detailedOP << gamma << \"\\t\" << beta << \"\\t\" << ops.getAsphericity()\n                 << \"\\t\" << ops.getMorseEnergy() << \"\\t\"\n                 << ops.getNormalityEnergy() << \"\\t\"\n                 << ops.getCircularityEnergy() << \"\\t\"\n                 << brown.getBrownianEnergy() << \"\\t\"\n                 << visco.getViscosityEnergy() << \"\\t\" << msds[0] << \"\\t\"\n                 << ops.getRMSAngleDeficit() << \"\\t\" << I1 << \"\\t\" << I2 << \"\\t\"\n                 << I3 << std::endl;\n\n      // Update prevX\n      prevX = x.head(3 * N);\n\n      if (loggingOn) {\n        avgTotalEnergy = (avgTotalEnergy * step + f) / (step + 1);\n        std::cout << \" Average Total Energy = \" << avgTotalEnergy << std::endl;\n      }\n      step++;\n    }\n    //************************************************//\n  }\n  // **********************************************************************//\n  detailedOP.close();\n  t2 = clock();\n  float diff((float)t2 - (float)t1);\n  std::cout << \"Solution loop execution time: \" << diff / CLOCKS_PER_SEC\n            << \" seconds\" << std::endl;\n  delete constraint;\n  return 1;\n}\n", "meta": {"hexsha": "302fd39b5a8b3e24b2613b391482e9abecc9d671", "size": 13003, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/Drivers/Inertia.cxx", "max_stars_repo_name": "amit112amit/oriented-particles", "max_stars_repo_head_hexsha": "1bb0f01a49d9bf33b88c4748025af756faf26688", "max_stars_repo_licenses": ["MIT", "BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-21T08:01:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-21T08:01:15.000Z", "max_issues_repo_path": "src/Drivers/Inertia.cxx", "max_issues_repo_name": "amit112amit/oriented-particles", "max_issues_repo_head_hexsha": "1bb0f01a49d9bf33b88c4748025af756faf26688", "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/Drivers/Inertia.cxx", "max_forks_repo_name": "amit112amit/oriented-particles", "max_forks_repo_head_hexsha": "1bb0f01a49d9bf33b88c4748025af756faf26688", "max_forks_repo_licenses": ["MIT", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.7531486146, "max_line_length": 80, "alphanum_fraction": 0.5621779589, "num_tokens": 3446, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152497, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.48901156718994343}}
{"text": "\n#include <iostream>\n#include <Eigen/Core>\n#include <bench/BenchTimer.h>\n\nusing namespace Eigen;\nusing namespace std;\n\n#define END 9\n\ntemplate<int S> struct map_size { enum { ret = S }; };\ntemplate<>  struct map_size<10> { enum { ret = 20 }; };\ntemplate<>  struct map_size<11> { enum { ret = 50 }; };\ntemplate<>  struct map_size<12> { enum { ret = 100 }; };\ntemplate<>  struct map_size<13> { enum { ret = 300 }; };\n\ntemplate<int M, int N,int K> struct alt_prod\n{\n  enum {\n    ret = M==1 && N==1 ? InnerProduct\n        : K==1 ? OuterProduct\n        : M==1 ? GemvProduct\n        : N==1 ? GemvProduct\n        : GemmProduct\n  };\n};\n\nvoid print_mode(int mode)\n{\n  if(mode==InnerProduct) std::cout << \"i\";\n  if(mode==OuterProduct) std::cout << \"o\";\n  if(mode==CoeffBasedProductMode) std::cout << \"c\";\n  if(mode==LazyCoeffBasedProductMode) std::cout << \"l\";\n  if(mode==GemvProduct) std::cout << \"v\";\n  if(mode==GemmProduct) std::cout << \"m\";\n}\n\ntemplate<int Mode, typename Lhs, typename Rhs, typename Res>\nEIGEN_DONT_INLINE void prod(const Lhs& a, const Rhs& b, Res& c)\n{\n  c.noalias() += typename ProductReturnType<Lhs,Rhs,Mode>::Type(a,b);\n}\n\ntemplate<int M, int N, int K, typename Scalar, int Mode>\nEIGEN_DONT_INLINE void bench_prod()\n{\n  typedef Matrix<Scalar,M,K> Lhs; Lhs a; a.setRandom();\n  typedef Matrix<Scalar,K,N> Rhs; Rhs b; b.setRandom();\n  typedef Matrix<Scalar,M,N> Res; Res c; c.setRandom();\n\n  BenchTimer t;\n  double n = 2.*double(M)*double(N)*double(K);\n  int rep = 100000./n;\n  rep /= 2;\n  if(rep<1) rep = 1;\n  do {\n    rep *= 2;\n    t.reset();\n    BENCH(t,1,rep,prod<CoeffBasedProductMode>(a,b,c));\n  } while(t.best()<0.1);\n\n  t.reset();\n  BENCH(t,5,rep,prod<Mode>(a,b,c));\n\n  print_mode(Mode);\n  std::cout << int(1e-6*n*rep/t.best()) << \"\\t\";\n}\n\ntemplate<int N> struct print_n;\ntemplate<int M, int N, int K> struct loop_on_m;\ntemplate<int M, int N, int K, typename Scalar, int Mode> struct loop_on_n;\n\ntemplate<int M, int N, int K>\nstruct loop_on_k\n{\n  static void run()\n  {\n    std::cout << \"K=\" << K << \"\\t\";\n    print_n<N>::run();\n    std::cout << \"\\n\";\n\n    loop_on_m<M,N,K>::run();\n    std::cout << \"\\n\\n\";\n\n    loop_on_k<M,N,K+1>::run();\n  }\n};\n\ntemplate<int M, int N>\nstruct loop_on_k<M,N,END> { static void run(){} };\n\n\ntemplate<int M, int N, int K>\nstruct loop_on_m\n{\n  static void run()\n  {\n    std::cout << M << \"f\\t\";\n    loop_on_n<M,N,K,float,CoeffBasedProductMode>::run();\n    std::cout << \"\\n\";\n\n    std::cout << M << \"f\\t\";\n    loop_on_n<M,N,K,float,-1>::run();\n    std::cout << \"\\n\";\n\n    loop_on_m<M+1,N,K>::run();\n  }\n};\n\ntemplate<int N, int K>\nstruct loop_on_m<END,N,K> { static void run(){} };\n\ntemplate<int M, int N, int K, typename Scalar, int Mode>\nstruct loop_on_n\n{\n  static void run()\n  {\n    bench_prod<M,N,K,Scalar,Mode==-1? alt_prod<M,N,K>::ret : Mode>();\n\n    loop_on_n<M,N+1,K,Scalar,Mode>::run();\n  }\n};\n\ntemplate<int M, int K, typename Scalar, int Mode>\nstruct loop_on_n<M,END,K,Scalar,Mode> { static void run(){} };\n\ntemplate<int N> struct print_n\n{\n  static void run()\n  {\n    std::cout << map_size<N>::ret << \"\\t\";\n    print_n<N+1>::run();\n  }\n};\n\ntemplate<> struct print_n<END> { static void run(){} };\n\nint main()\n{\n  loop_on_k<1,1,1>::run();\n\n  return 0;\n}", "meta": {"hexsha": "b1f9be4eafd008fcd8fa60ca4d1c313f23a9977a", "size": 3210, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Plugins/SciberQuestToolKit/eigen-3.0.3/eigen-eigen-3.0.3/bench/product_threshold.cpp", "max_stars_repo_name": "mathstuf/ParaView", "max_stars_repo_head_hexsha": "e867e280545ada10c4ed137f6a966d9d2f3db4cb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-21T20:20:59.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-21T20:20:59.000Z", "max_issues_repo_path": "Plugins/SciberQuestToolKit/eigen-3.0.3/eigen-eigen-3.0.3/bench/product_threshold.cpp", "max_issues_repo_name": "mathstuf/ParaView", "max_issues_repo_head_hexsha": "e867e280545ada10c4ed137f6a966d9d2f3db4cb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Plugins/SciberQuestToolKit/eigen-3.0.3/eigen-eigen-3.0.3/bench/product_threshold.cpp", "max_forks_repo_name": "mathstuf/ParaView", "max_forks_repo_head_hexsha": "e867e280545ada10c4ed137f6a966d9d2f3db4cb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2016-04-14T13:42:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-22T04:59:42.000Z", "avg_line_length": 22.4475524476, "max_line_length": 74, "alphanum_fraction": 0.6049844237, "num_tokens": 1031, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152497, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.48901156718994343}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// random::categorical_distribution.hpp                                      //\n//                                                                           //\n//  Copyright 2009 Erwann Rogard. Distributed under the Boost                //\n//  Software License, Version 1.0. (See accompanying file                    //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)         //\n///////////////////////////////////////////////////////////////////////////////\n#ifndef BOOST_RANDOM_CATEGORICAL_DISTRIBUTION_HPP_ER_2009\n#define BOOST_RANDOM_CATEGORICAL_DISTRIBUTION_HPP_ER_2009\n#include <algorithm>\n#include <numeric>\n#include <cmath>\n#include <stdexcept>\n#include <boost/range.hpp>\n#include <boost/format.hpp>\n#include <boost/math/tools/precision.hpp>\n#include <boost/random/uniform_real.hpp>\n#include <boost/utility/result_of.hpp>\n\nnamespace boost{\nnamespace random{\n\n// Deprecated : see discrete_distribution\n//\n// Usage:\n// typedef categorical_distribution<> rmult_;\n// typedef rmult_::value_type         value_type;\n// typedef rmult_::result_type        idx_;\n//\n// Let urng model UniformRandomNumberGenerator and weights a sequence whose \n// elements type is convertible to value_type:\n//\n// rmult_ rmult(weights);\n// idx_ idx = rmult(urng);\ntemplate<typename Ur = uniform_real<double> >\nclass categorical_distribution{\n    typedef Ur                                          unif_t;\n    public:\n    typedef typename unif_t::input_type                 input_type;\n    typedef typename unif_t::result_type                value_type;\n\n    private:\n    typedef std::vector<value_type>                     cont_t;\n\n    public:\n    typedef typename range_difference<cont_t>::type     result_type;\n\n    // Construction\n    categorical_distribution();\n    \n    // Passing sorted from large to small weights will speed up execution. \n    template<typename R>\n    categorical_distribution( const R& unnormalized_weights );\n    categorical_distribution( const categorical_distribution& that );\n    categorical_distribution&\n    operator=(const categorical_distribution& that);\n\n    // Draw\n    template<typename U> result_type operator()(U& urng)const;\n\n    // Access\n    const cont_t& cumulative_weights()const;\n    value_type normalizing_constant()const;\n\n    // TODO os/is\n\n    private:\n    cont_t cum_sums_;\n    template<typename R>void set(const R& unnormalized_weights);\n};\n\n\n// Implementation //\n\n    // Construction\n    template<typename Ur>\n    categorical_distribution<Ur>::categorical_distribution() : cum_sums_(){}\n\n    template<typename Ur>\n    template<typename R>\n    categorical_distribution<Ur>::categorical_distribution( \n        const R& unnormalized_weights \n    )\n    {\n        set(unnormalized_weights);\n    }\n    \n    template<typename Ur>\n    categorical_distribution<Ur>::categorical_distribution( \n        const categorical_distribution& that \n    )\n    :cum_sums_(that.cum_sums_){}\n    \n    template<typename Ur>\n    categorical_distribution<Ur>&\n    categorical_distribution<Ur>::operator=(\n        const categorical_distribution& that\n    ){\n        if(&that!=this){\n            this->cum_sums_ = that.cum_sums_;\n        }\n        return *this;\n    }\n    \n    template<typename Ur>\n    template<typename U>\n    typename categorical_distribution<Ur>::result_type \n    categorical_distribution<Ur>::operator()(U& urng)const{\n        unif_t unif(static_cast<value_type>(0),normalizing_constant());\n        typedef typename range_iterator<const cont_t>::type iter_;\n        value_type u = unif(urng);\n        iter_ i = std::lower_bound(\n            boost::begin(this->cum_sums_),\n            boost::end(this->cum_sums_),\n            u\n        );\n        BOOST_ASSERT(i!=end(cum_sums_));\n        return std::distance(boost::begin(this->cum_sums_),i);\n    }\n    \n    // Access\n    template<typename Ur>\n    const typename categorical_distribution<Ur>::cont_t&\n    categorical_distribution<Ur>::cumulative_weights()const{ \n        return (this->cum_sums_); \n    }\n    \n    template<typename Ur>\n    typename categorical_distribution<Ur>::value_type\n    categorical_distribution<Ur>::normalizing_constant()const{\n        return (this->cum_sums_).back();\n    }\n    \n    template<typename Ur>\n    template<typename R>\n    void categorical_distribution<Ur>::set(const R& unnormalized_weights){\n        const char* method = \"multinormal_distribution::set, error : \";\n        static value_type eps = math::tools::epsilon<value_type>();\n\n        cum_sums_.resize(size(unnormalized_weights));\n        \n        std::partial_sum(\n            boost::begin(unnormalized_weights),\n            boost::end(unnormalized_weights),\n            boost::begin(this->cum_sums_)\n        );\n\n        if(math::isinf(this->normalizing_constant())){\n            std::string str = method;\n            str += \"isinf(nc)\";  \n            throw std::runtime_error(str);\n        }\n        if(this->normalizing_constant()<eps){\n            std::string str = method;\n            str += \"nc = %1% < eps = %2%\";\n            format f(str); f%(this->normalizing_constant())%eps;  \n            throw std::runtime_error(f.str());\n        }\n        \n    }\n\n}// random\n}// boost\n\n#endif \n", "meta": {"hexsha": "72af24b73b204f7f108914a56bec4e291819b7a4", "size": 5261, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "random/boost/random/categorical_distribution.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": "random/boost/random/categorical_distribution.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": "random/boost/random/categorical_distribution.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.6927710843, "max_line_length": 79, "alphanum_fraction": 0.6164227333, "num_tokens": 1086, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4890115619403097}}
{"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_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/bitwise_cast.hpp>\n#include <boost/simd/function/if_plus.hpp>\n#include <boost/simd/function/if_else.hpp>\n#include <boost/simd/function/if_one_else_zero.hpp>\n#include <boost/simd/function/is_gez.hpp>\n#include <boost/simd/function/is_gtz.hpp>\n#include <boost/simd/function/is_greater.hpp>\n#include <boost/simd/function/is_greater_equal.hpp>\n#include <boost/simd/function/is_nez.hpp>\n#include <boost/simd/function/is_less.hpp>\n#include <boost/simd/function/raw.hpp>\n#include <boost/simd/function/shift_right.hpp>\n#include <boost/simd/function/tofloat.hpp>\n#include <boost/simd/function/toint.hpp>\n#include <boost/simd/function/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\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      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      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      A0 n   = plus(shift_right(a0, 4), Four<A0>());\n      A0 n1  = shift_right(n+a0/n, 1);\n\n      auto ok = is_less(n1, n);\n      n  = if_else(ok, n1, n);\n      n1 = if_else(ok, shift_right(n+a0/n, 1), n1);\n\n      ok = is_less(n1, n);\n      n  = if_else(ok, n1, n);\n      n  = if_plus( is_greater(n*n,a0), n, Mone<A0>());\n      return n;\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(is_less(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 = is_less(n1, n);\n      n  = if_else(ok, n1, n);\n      n1 = if_else(ok, shift_right(n+a0/n, 1), n1);\n\n      ok = is_less(n1, n);\n      n  = if_else(ok, n1, n);\n      n1 = if_else(ok, shift_right(n+a0/n, 1), n1);\n\n      ok =  is_less(n1, n);\n      n  = if_else(ok, n1, n);\n      n  = if_plus( is_greater(n*n,a0), n, Mone<A0>());\n\n     return if_plus(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( is_greater(a0, Ratio<A0,177155824>())\n                  , z4\n                  , if_else( is_greater(a0, Ratio<A0,4084387>())\n                        , z3\n                        , if_else( is_greater(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 = is_less(n1, n);\n      n  = if_else(ok, n1, n);\n      n1 = if_else(ok, shift_right(n+a0/n, 1), n1);\n\n      ok =  is_less(n1, n);\n      n  = if_else(ok, n1, n);\n      n1 = if_else(ok, shift_right(n+a0/n, 1), n1);\n\n      ok =  is_less(n1, n);\n      n  = if_else(ok, n1, n);\n\n      A0 tmp = minus(n*minus(n, One<A0>()), One<A0>());\n      n  = if_plus( is_greater_equal(tmp+n,a0), n, Mone<A0>());\n      n =  if_plus(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": "deae432540b8f681f115c1278d302e7d5cb941b0", "size": 6385, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arch/x86/sse2/simd/function/sqrt.hpp", "max_stars_repo_name": "nickporubsky/boost-simd-clone", "max_stars_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_stars_repo_licenses": ["BSL-1.0"], "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": "include/boost/simd/arch/x86/sse2/simd/function/sqrt.hpp", "max_issues_repo_name": "nickporubsky/boost-simd-clone", "max_issues_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "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": "nickporubsky/boost-simd-clone", "max_forks_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_forks_repo_licenses": ["BSL-1.0"], "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": 32.7435897436, "max_line_length": 100, "alphanum_fraction": 0.5104150352, "num_tokens": 1772, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118221, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.4890115566906758}}
{"text": "/// @file\n/// @copyright The code is licensed under the BSD License\n///            <http://opensource.org/licenses/BSD-2-Clause>,\n///            Copyright (c) 2012-2015 Alexandre Hamez.\n/// @author Alexandre Hamez\n\n#pragma once\n\n#include <boost/multiprecision/cpp_int.hpp>\n\n#include \"sdd/dd/definition.hh\"\n\nnamespace sdd { namespace dd {\n\n/*------------------------------------------------------------------------------------------------*/\n\ntemplate <typename C>\nboost::multiprecision::cpp_int\ncount_combinations(const SDD<C>& x);\n\n/*------------------------------------------------------------------------------------------------*/\n\n}} // namespace sdd::dd\n", "meta": {"hexsha": "ba845150c71fc765f7fb1db69b309183021c3d21", "size": 658, "ext": "hh", "lang": "C++", "max_stars_repo_path": "sdd/dd/count_combinations_fwd.hh", "max_stars_repo_name": "tic-toc/libsdd", "max_stars_repo_head_hexsha": "5c3deb43523d062929f169c3d7a301240f0fb811", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-03-21T19:21:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-29T01:20:28.000Z", "max_issues_repo_path": "sdd/dd/count_combinations_fwd.hh", "max_issues_repo_name": "tic-toc/libsdd", "max_issues_repo_head_hexsha": "5c3deb43523d062929f169c3d7a301240f0fb811", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-02-05T23:39:44.000Z", "max_issues_repo_issues_event_max_datetime": "2017-02-05T23:40:04.000Z", "max_forks_repo_path": "libsdd/sdd/dd/count_combinations_fwd.hh", "max_forks_repo_name": "kyouko-taiga/SwiftSDD", "max_forks_repo_head_hexsha": "9312160e0fac5fef6e605c9e74c543ded9708e54", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-05-13T14:39:06.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-09T20:13:39.000Z", "avg_line_length": 27.4166666667, "max_line_length": 100, "alphanum_fraction": 0.4756838906, "num_tokens": 121, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7310585903489891, "lm_q2_score": 0.6688802735722128, "lm_q1q2_score": 0.4889906699099481}}
{"text": "// Copyright Louis Dionne 2013-2016\r\n// Distributed under the Boost Software License, Version 1.0.\r\n// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\r\n\r\n#include <boost/hana/ap.hpp>\r\n#include <boost/hana/assert.hpp>\r\n#include <boost/hana/bool.hpp>\r\n#include <boost/hana/config.hpp>\r\n#include <boost/hana/equal.hpp>\r\n#include <boost/hana/if.hpp>\r\n#include <boost/hana/lift.hpp>\r\n#include <boost/hana/optional.hpp>\r\nnamespace hana = boost::hana;\r\n\r\n\r\ntemplate <char op>\r\nconstexpr auto function = hana::nothing;\r\n\r\ntemplate <>\r\nBOOST_HANA_CONSTEXPR_LAMBDA auto function<'+'> = hana::just([](auto x, auto y) {\r\n    return x + y;\r\n});\r\n\r\ntemplate <>\r\nBOOST_HANA_CONSTEXPR_LAMBDA auto function<'-'> = hana::just([](auto x, auto y) {\r\n    return x - y;\r\n});\r\n\r\n// and so on...\r\n\r\ntemplate <char n>\r\nconstexpr auto digit = hana::if_(hana::bool_c<(n >= '0' && n <= '9')>,\r\n    hana::just(static_cast<int>(n - 48)),\r\n    hana::nothing\r\n);\r\n\r\ntemplate <char x, char op, char y>\r\nBOOST_HANA_CONSTEXPR_LAMBDA auto evaluate = hana::ap(function<op>, digit<x>, digit<y>);\r\n\r\nint main() {\r\n    BOOST_HANA_CONSTEXPR_CHECK(evaluate<'1', '+', '2'> == hana::just(1 + 2));\r\n\r\n    BOOST_HANA_CONSTANT_CHECK(evaluate<'?', '+', '2'> == hana::nothing);\r\n    BOOST_HANA_CONSTANT_CHECK(evaluate<'1', '?', '2'> == hana::nothing);\r\n    BOOST_HANA_CONSTANT_CHECK(evaluate<'1', '+', '?'> == hana::nothing);\r\n    BOOST_HANA_CONSTANT_CHECK(evaluate<'?', '?', '?'> == hana::nothing);\r\n\r\n    static_assert(hana::lift<hana::optional_tag>(123) == hana::just(123), \"\");\r\n}\r\n", "meta": {"hexsha": "883f29dbd67bb6602aea294625397ed8ec4cbbda", "size": 1568, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "thirdparty-cpp/boost_1_62_0/libs/hana/example/optional/applicative.complex.cpp", "max_stars_repo_name": "nxplatform/nx-mobile", "max_stars_repo_head_hexsha": "0dc174c893f2667377cb2ef7e5ffeb212fa8b3e5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-12-15T19:57:24.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-15T19:57:24.000Z", "max_issues_repo_path": "thirdparty-cpp/boost_1_62_0/libs/hana/example/optional/applicative.complex.cpp", "max_issues_repo_name": "nxplatform/nx-mobile", "max_issues_repo_head_hexsha": "0dc174c893f2667377cb2ef7e5ffeb212fa8b3e5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thirdparty-cpp/boost_1_62_0/libs/hana/example/optional/applicative.complex.cpp", "max_forks_repo_name": "nxplatform/nx-mobile", "max_forks_repo_head_hexsha": "0dc174c893f2667377cb2ef7e5ffeb212fa8b3e5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.36, "max_line_length": 88, "alphanum_fraction": 0.6447704082, "num_tokens": 448, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585903489891, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.4889906602590943}}
{"text": "/* Copyright (c) 2015, Julian Straub <jstraub@csail.mit.edu>, Randi Cabezas <rcabezas@csail.mit.edu>                    \n * Licensed under the MIT license. See the license file LICENSE.\n */\n#include <iostream>\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE dirMM test\n#include <boost/test/unit_test.hpp>\n\n#include <dpMM/dirNaiveBayes.hpp>\n#include <dpMM/niwBaseMeasure.hpp>\n#include <dpMM/niwSphere.hpp>\n#include <dpMM/dirMMcld.hpp>\n#include <dpMM/clTGMMDataGpu.hpp>\n#include <dpMM/distribution.hpp>\n#include <dpMM/typedef.h>\n\n//BOOST_AUTO_TEST_CASE(niwBaseMeasure_test)\n//{\n  //MatrixXd Delta(3,3);\n  //Delta << 1.0,0.0,0.0,\n        //0.0,1.0,0.0,\n        //0.0,0.0,1.0;\n  //VectorXd theta(3);\n  //theta << 1.0,1.0,1.0;\n  //double nu = 100.0;\n  //double kappa = 100.0;\n\n  //boost::mt19937 rndGen(1);\n  //NIW<double> niw(Delta,theta,nu,kappa,&rndGen);\n\n  //NiwMarginalized<double> niwMargBase(niw);\n\n  //VectorXd x(3);\n  //x << 1.0,1.0,1.0;\n  //cout<< niwMargBase.logLikelihood(x)<< endl;\n\n  //NiwSampled<double> niwSampledBase(niw);\n\n  //x << 1.0,1.0,1.0;\n  //cout<< niwSampledBase.logLikelihood(x)<< endl;\n//};\n\nBOOST_AUTO_TEST_CASE(dirNaiveBayes_test)\n{\n\n\tdouble nu = 4.0;\n\tdouble kappa = 4.0;\n\tMatrixXd Delta(3,3);\n\tDelta << .1,0.0,0.0,\n\t\t0.0,.1,0.0,\n\t\t0.0,0.0,.1;\n\tVectorXd theta(3);\n\ttheta << 0.0,0.0,0.0;\n\n\tboost::mt19937 rndGen(9191);\n\tNIW<double> niw(Delta,theta,nu,kappa,&rndGen);\n\n\tboost::shared_ptr<NiwMarginalized<double> > niwMargBase(\n\t\tnew NiwMarginalized<double>(niw));\n\tVectorXd alpha(2);\n\talpha << 10.,10.;\n\tDir<Catd,double> dir(alpha,&rndGen); \n\n  \n\tuint Ndoc=5;\n\tuint Nword=10; \n\tvector< Matrix<double, Dynamic, Dynamic> > x;\n\tfor(uint i=0; i<Ndoc; ++i) {\n\t\tMatrixXd  xdoc(3,Nword);  \n\t\tfor(uint w=0; w<Nword; ++w) {\n\t\t\tif(w<Nword/2)\n\t\t\t\txdoc.col(i) << 0.0,0.0,0.0;\n\t\t\telse\n\t\t\t\txdoc.col(i) << 10.0,10.0,10.0;\n\t\t}\n\n\t\tx.push_back(xdoc); \n\t}\n\n\t//cout<<\"------ marginalized ---- NIW \"<<endl;\n\t//DirNaiveBayes<double> naive_marg(dir,niwMargBase);\n\t//naive_marg.initialize(x);\n\t//cout<<naive_marg.labels().transpose()<<endl;\n\t//for(uint32_t t=0; t<30; ++t)\n\t//{\n\t//naive_marg.sampleLabels();\n\t//naive_marg.sampleParameters();\n\t//cout<<naive_marg.labels().transpose()\n\t\t//<<\" logJoint=\"<<naive_marg.logJoint()<<endl;\n\t//}\n\n\tboost::shared_ptr<NiwSampled<double> > niwSampled( new NiwSampled<double>(niw));\n\tDirNaiveBayes<double> naive_samp(dir,niwSampled);\n  \n\tnaive_samp.initialize( (const vector< Matrix<double, Dynamic, Dynamic> >) x );\n\tnaive_samp.inferAll(30,true);\n};\n\n\n//BOOST_AUTO_TEST_CASE(dirMM_Sphere_test)\n//{\n\n  //double nu = 20.0;\n  //MatrixXd Delta(2,2);\n  //Delta << .01,0.0,\n        //0.0,.01;\n  //Delta *= nu;\n\n  //boost::mt19937 rndGen(9191);\n  //IW<double> iw(Delta,nu,&rndGen);\n  //boost::shared_ptr<NiwSphere<double> > niwSp( new NiwSphere<double>(iw,&rndGen));\n\n  //VectorXd alpha(2);\n  //alpha << 10.,10.;\n  //Dir<Catd,double> dir(alpha,&rndGen); \n  //DirMM<double> dirGMM_sp(dir,niwSp);\n  \n  //uint32_t N=20;\n  //uint32_t K=2;\n  //MatrixXd x(3,N);\n  //sampleClustersOnSphere<double>(x, K);\n  //dirGMM_sp.initialize(x);\n  //cout<<\"------ sampling -- NIW sphere\"<<endl;\n  //cout<<dirGMM_sp.labels().transpose()<<endl;\n  //for(uint32_t t=0; t<10; ++t)\n  //{\n    //dirGMM_sp.sampleLabels();\n    //dirGMM_sp.sampleParameters();\n    //cout<<dirGMM_sp.labels().transpose()\n      //<<\" logJoint=\"<<dirGMM_sp.logJoint()<<endl;\n  //}\n  //MatrixXd logLikes;\n  //MatrixXu inds = dirGMM_sp.mostLikelyInds(5,logLikes);\n  //cout<<\"most likely indices\"<<endl;\n  //cout<<inds<<endl;\n  //cout<<\"----------------------------------------\"<<endl;\n//};\n\n//typedef double myFlt;\n\n//BOOST_AUTO_TEST_CASE(dirMMcld_Sphere_test)\n//{\n\n  //uint32_t N=30; //640*480;\n  //uint32_t K=6;\n  //uint32_t D=3;\n  //boost::mt19937 rndGen(9191);\n  //// sample datapoints\n  //boost::shared_ptr<Matrix<myFlt,Dynamic,Dynamic> > sx(new \n      //Matrix<myFlt,Dynamic,Dynamic>(D,N));\n  //Matrix<myFlt,Dynamic,Dynamic> mus =  sampleClustersOnSphere(*sx, 3);\n\n  //// alpha\n  //Matrix<myFlt,Dynamic,1> alpha(K);\n  //alpha << 1.,1.,.1,.1,.1,.1;\n  //alpha *= 1;\n  \n  //// niw\n  //double nu = (1.0)+D+N/100.;\n  //Matrix<myFlt,Dynamic,Dynamic> Delta(2,2);\n  //Delta << .01,0.0,\n        //0.0,.01;\n  //Delta *= nu;\n\n  //IW<myFlt> iw(Delta,nu,&rndGen);\n  //boost::shared_ptr<NiwSphere<myFlt> > niwSp( new NiwSphere<myFlt>(iw,&rndGen));\n////  boost::shared_ptr<NiwSphere<double> > niwSp2( new NiwSphere<double>(iw,&rndGen));\n\n  //Dir<Cat<myFlt>, myFlt> dir(alpha,&rndGen); \n  //DirMMcld<NiwSphere<myFlt>,myFlt> dirGMM_sp(dir,niwSp);\n\n////  DirMM<myFlt> dirGMM_cpu(dir,niwSp2);\n\n  //boost::shared_ptr<ClTGMMDataGpu<myFlt> > clsp(\n      //new ClTGMMDataGpu<myFlt>(sx, spVectorXu(new VectorXu(N)),&rndGen,K));\n\n  //Matrix<myFlt,Dynamic,1> mu(D);\n  //mu<<0.0,0.0,1.0;\n  //Matrix<myFlt,Dynamic,Dynamic> Sigma = Matrix<myFlt,Dynamic,Dynamic>::Identity(D,D);\n\n  //dirGMM_sp.initialize(clsp);\n////  dirGMM_cpu.initialize(*sx);\n  //cout<<\"------ sampling -- NIW sphere\"<<endl;\n  //cout<<counts<myFlt,uint32_t>(dirGMM_sp.labels(),K).transpose()<<endl;\n  //Timer t;\n  //for(uint32_t i=0; i<5; ++i)\n  //{\n////    t.tic();\n////    dirGMM_cpu.sampleLabels();\n////    dirGMM_cpu.sampleParameters();\n////    cout<<dirGMM_cpu.labels().transpose()<<endl;\n////    t.toctic(\" -----------------CPU------------------- fullIteration\");\n    //t.tic();\n    //dirGMM_sp.sampleLabels();\n    //dirGMM_sp.sampleParameters();\n    //cout<<dirGMM_sp.z().transpose()<<endl;\n    //cout<<dirGMM_sp.counts().transpose()<<endl;\n    //cout<<dirGMM_sp.means()<<endl;\n    //t.toctic(\" -----------------GPU------------------- fullIteration\");\n////        <<\" logJoint=\"<<dirGMM_sp.logJoint()<<endl;\n  //}\n  //cout<<\"true mus: \"<<endl;\n  //cout <<mus<<endl;\n//};\n\n", "meta": {"hexsha": "b3e1cd9dd338e5fa0d1e7091346b3d416b79061e", "size": 5711, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_naiveBayes.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": "test/test_naiveBayes.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": "test/test_naiveBayes.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": 27.7233009709, "max_line_length": 120, "alphanum_fraction": 0.6182805113, "num_tokens": 2020, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.48899065724592394}}
{"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#define NT2_UNIT_MODULE \"nt2::whereij function\"\n\n#include <nt2/table.hpp>\n#include <nt2/include/functions/size.hpp>\n#include <nt2/include/functions/whereij.hpp>\n#include <nt2/include/functions/rif.hpp>\n#include <nt2/include/functions/is_less_equal.hpp>\n#include <nt2/include/functions/zeros.hpp>\n#include <nt2/include/functions/triu.hpp>\n#include <nt2/include/functions/logical_and.hpp>\n#include <nt2/include/functions/from_diag.hpp>\n#include <nt2/include/functions/diag_of.hpp>\n#include <nt2/include/functions/band.hpp>\n#include <nt2/include/constants/zero.hpp>\n#include <nt2/sdk/unit/module.hpp>\n#include <nt2/sdk/unit/tests/relation.hpp>\n//#include <boost/lambda/lambda.hpp>\n//boost lambda codes hard bool return types preventing the code to work\n//we have to use phoenix here when corrected\n// NT2_TEST_CASE_TPL( whereij_lambda, NT2_TYPES)\n// {\n//   namespace bl = boost::lambda;\n//   nt2::table<T> a = nt2::rif(nt2::of_size(3, 3), nt2::meta::as_<T>()),\n//     b = nt2::zeros(nt2::of_size(3, 3), nt2::meta::as_<T>()),\n//     e, f;\n\n//   e = nt2::whereij(        (bl::_1 <= bl::_2),  a, b);\n//   NT2_DISPLAY(e);\n//   NT2_DISPLAY(nt2::triu(a));\n//   NT2_TEST_EQUAL(e, nt2::triu(a));\n//   f = nt2::whereij((bl::_1 == bl::_2),  a, b);\n//   NT2_TEST_EQUAL(f, nt2::from_diag(nt2::diag_of(a)));\n// }\n\nNT2_TEST_CASE_TPL( whereij_1, NT2_TYPES)\n{\n  nt2::table<T> a = nt2::rif(nt2::of_size(3, 3), nt2::meta::as_<T>()),\n                b = nt2::zeros(nt2::of_size(3, 3), nt2::meta::as_<T>()),\n                e, f, g, h;\n\n  e = nt2::whereij(nt2::functor<nt2::tag::is_less_equal_>(),  a, b);\n  NT2_DISPLAY(e);\n  NT2_DISPLAY(nt2::triu(a));\n  NT2_TEST_EQUAL(e, nt2::triu(a));\n  f = whereij(nt2::functor<nt2::tag::is_equal_>(),  a, b);\n  NT2_TEST_EQUAL(f, nt2::from_diag(nt2::diag_of(a)));\n  g = nt2::whereij(nt2::functor<nt2::tag::is_equal_>(),  a, nt2::zeros(3, nt2::meta::as_<T>()));\n  NT2_TEST_EQUAL(g, nt2::from_diag(nt2::diag_of(a)));\n  h = nt2::whereij(nt2::functor<nt2::tag::is_equal_>(),  a, nt2::Zero<T>());\n  NT2_TEST_EQUAL(h, nt2::from_diag(nt2::diag_of(a)));\n  NT2_DISPLAY(nt2::from_diag(nt2::diag_of(a)));\n  NT2_DISPLAY(h);\n}\n\n\nstruct fct1\n{\n\n  template < class A0, class A1>\n  typename nt2::meta::as_logical<A0>::type\n  operator ()(const A0& i, const A1& j) const\n  {\n    return nt2::logical_and(nt2::le(i, nt2::oneplus(j)),\n                            nt2::le(j, nt2::oneplus(i))\n                           );\n  }\n\n};\n\nstruct fct2\n{\n\n  template < class A0, class A1>\n  typename nt2::meta::as_logical<A0>::type\n  operator ()(const A0& i, const A1& j) const\n  {\n    return nt2::eq(i, j);\n  }\n\n};\n\nstruct fct3\n{\n\n  template < class A0, class A1>\n  typename nt2::meta::as_logical<A0>::type\n  operator ()(const A0& i, const A1& j) const\n  {\n    return nt2::logical_and(nt2::eq(i, size_t(1) ), nt2::eq(j, size_t(2)));\n  }\n\n};\n\nNT2_TEST_CASE_TPL( whereij_func, NT2_TYPES)\n{\n  nt2::table<T> a = nt2::rif(nt2::of_size(3, 3), nt2::meta::as_<T>()),\n    b = nt2::zeros(nt2::of_size(3, 3), nt2::meta::as_<T>()),\n    e, f, g;\n\n  e = whereij(fct1(),  a, b);\n  NT2_DISPLAY(e);\n  NT2_DISPLAY(nt2::band(a, 1, 1));\n  NT2_TEST_EQUAL(e, nt2::band(a, 1, 1));\n  f = whereij(fct2(),  a, b);\n  NT2_TEST_EQUAL(f, nt2::from_diag(nt2::diag_of(a)));\n  NT2_TEST_EQUAL(f, nt2::diagonal(a));\n  g = whereij(fct3(),  a, b);\n  NT2_DISPLAY(g);\n}\n", "meta": {"hexsha": "9a2dff80733cb0791b405746b486cd455f773d83", "size": 3822, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/core/utility/unit/functions/whereij.cpp", "max_stars_repo_name": "pbrunet/nt2", "max_stars_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "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/utility/unit/functions/whereij.cpp", "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/utility/unit/functions/whereij.cpp", "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": 32.3898305085, "max_line_length": 96, "alphanum_fraction": 0.5975928833, "num_tokens": 1265, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.7310585844894971, "lm_q1q2_score": 0.48899065633979577}}
{"text": "/*******************************************************************************\nCopyright (c) 2011, Dr. D. Studios\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 other\nmaterials provided with the distribution.\nNeither the name of the Dr. D. Studios nor the names of its contributors may be\nused to endorse or promote products derived from this software without specific\nprior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\nIN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\nINDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\nBUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\nOR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\nOF THE POSSIBILITY OF SUCH DAMAGE.\n*******************************************************************************/\n\n/**\n * This differs from the API in that the Color3-related functions now return\n * Color3 objects rather than Vec3s. This is so that equality works as expected.\n * Note they will still accept any Vec3.\n */\n\n#ifndef _PIMATH_COLORALGO__H_\n#define _PIMATH_COLORALGO__H_\n\n#include <boost/python.hpp>\n#include <ImathColorAlgo.h>\n#include <ImathColor.h>\n#include \"util.h\"\n\nnamespace pimath\n{\n\tnamespace bp = boost::python;\n\n\tstruct ColorAlgoBindUnteplated\n\t{\n\t\tColorAlgoBindUnteplated()\n\t\t{\n\t\t\tImath::Color4<double> (*hsv2rgb_d4)(\n\t\t\t\t\tconst Imath::Color4<double> &) = &Imath::hsv2rgb_d;\n\t\t\tImath::Color4<double> (*rgb2hsv_d4)(\n\t\t\t\t\tconst Imath::Color4<double> &) = &Imath::rgb2hsv_d;\n\n\t\t\tbp::def(\"hsv2rgb_d\", hsv2rgb_d3);\n\t\t\tbp::def(\"hsv2rgb_d\", hsv2rgb_d4);\n\t\t\tbp::def(\"rgb2hsv_d\", rgb2hsv_d3);\n\t\t\tbp::def(\"rgb2hsv_d\", rgb2hsv_d4);\n\t\t}\n\n\t\tstatic Imath::Color3<double> hsv2rgb_d3(\n\t\t\t\tconst Imath::Vec3<double> & hsv)\n\t\t{\n\t\t\treturn Imath::Color3<double>( Imath::hsv2rgb_d( hsv ));\n\t\t}\n\n\t\tstatic Imath::Color3<double> rgb2hsv_d3(\n\t\t\t\tconst Imath::Vec3<double> & rgb)\n\t\t{\n\t\t\treturn Imath::Color3<double>( Imath::rgb2hsv_d( rgb ));\n\t\t}\n\t};\n\n\ttemplate<typename T>\n\tstruct ColorAlgoBind\n\t{\n\t\ttypedef Imath::Vec3<T> \t\tvec3_type;\n\t\ttypedef Imath::Color3<T>\tcol3_type;\n\t\ttypedef Imath::Color4<T>\tcol4_type;\n\t\tColorAlgoBind()\n\t\t{\n\t\t\tcol4_type (*hsv2rgb4)(\n\t\t\t\t\tconst col4_type &) = &Imath::hsv2rgb;\n\t\t\tcol4_type (*rgb2hsv4)(\n\t\t\t\t\tconst col4_type &) = &Imath::rgb2hsv;\n\t\t\tImath::PackedColor (*rgb2packed3)(\n\t\t\t\t\tconst vec3_type &) = &Imath::rgb2packed;\n\t\t\tImath::PackedColor (*rgb2packed4)(\n\t\t\t\t\tconst col4_type &) = &Imath::rgb2packed;\n\n\t\t\tbp::def(\"hsv2rgb\", hsv2rgb3);\n\t\t\tbp::def(\"hsv2rgb\", hsv2rgb4);\n\t\t\tbp::def(\"rgb2hsv\", rgb2hsv3);\n\t\t\tbp::def(\"rgb2hsv\", rgb2hsv4);\n\t\t\tbp::def(\"rgb2packed\", rgb2packed3);\n\t\t\tbp::def(\"rgb2packed\", rgb2packed4);\n\t\t\tbp::def(\"packed2rgb\", packed2rgb );\n\t\t\tbp::def(\"packed2rgba\", packed2rgba );\n\t\t}\n\n\t\tstatic col3_type hsv2rgb3( const vec3_type & vec )\n\t\t{\n\t\t\treturn col3_type( Imath::hsv2rgb( vec ) );\n\t\t}\n\n\t\tstatic col3_type rgb2hsv3( const vec3_type & vec )\n\t\t{\n\t\t\treturn col3_type( Imath::rgb2hsv( vec ) );\n\t\t}\n\n\t\tstatic bp::object\n\t\tpacked2rgb( Imath::PackedColor packed )\n\t\t{\n\t\t\tcol3_type rv;\n\t\t\tImath::packed2rgb<T>( packed, rv );\n\t\t\treturn  bp::object( rv );\n\t\t}\n\n\t\tstatic bp::object\n\t\tpacked2rgba( Imath::PackedColor packed )\n\t\t{\n\t\t\tcol4_type rv;\n\t\t\tImath::packed2rgb<T>( packed, rv);\n\t\t\treturn  bp::object( rv );\n\t\t}\n\t};\n}\n\n#endif\n\n", "meta": {"hexsha": "6eb376a48c2b694d9f57d43c11816e73fa509dc0", "size": 4096, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/ColorAlgo.hpp", "max_stars_repo_name": "madpianist/pimath", "max_stars_repo_head_hexsha": "d79c56d492887d52e1e6f7ec0ffa1966a4717b0a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-07-22T21:32:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-22T21:32:34.000Z", "max_issues_repo_path": "src/ColorAlgo.hpp", "max_issues_repo_name": "madpianist/pimath", "max_issues_repo_head_hexsha": "d79c56d492887d52e1e6f7ec0ffa1966a4717b0a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ColorAlgo.hpp", "max_forks_repo_name": "madpianist/pimath", "max_forks_repo_head_hexsha": "d79c56d492887d52e1e6f7ec0ffa1966a4717b0a", "max_forks_repo_licenses": ["BSD-3-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.0303030303, "max_line_length": 82, "alphanum_fraction": 0.693359375, "num_tokens": 1182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.6688802537704064, "lm_q1q2_score": 0.48899064759507027}}
{"text": "#include <iostream>\n#include <cmath>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\nusing namespace std;\nusing namespace Eigen;\n\nint main(int argc, char const *argv[])\n{\n    // \u8bc1\u660e1\uff1a\n    cout << \"\u8bc1\u660e1: \" << endl;\n    // \u9996\u5148\u521b\u5efa\u521b\u5efa\u4e00\u4e2a\u968f\u673a\u7684\u56db\u5143\u6570\uff0c\u5e76\u5c06\u5176\u8f6c\u53d8\u4e3a\u65cb\u8f6c\u77e9\u9635\n    Vector3d q = Vector3d::Random();\n    Isometry3d R = Isometry3d::Identity();                // \u77e9\u9635\u521d\u59cb\u5316\n    R.rotate(q); \n\n    //\u8bc1\u660e R*R^T = I\n    auto I = R * R.inverse();\n    return 0;\n}\n\n\n", "meta": {"hexsha": "21b59a9b0299344a8d21351fb774f0ff1ad1d6b6", "size": 436, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Notes/chap3/code/Q3/main.cpp", "max_stars_repo_name": "Alexbeast-CN/Notes2SLAM", "max_stars_repo_head_hexsha": "43651d8548431b26538739cc3130d315de4d4f7f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Notes/chap3/code/Q3/main.cpp", "max_issues_repo_name": "Alexbeast-CN/Notes2SLAM", "max_issues_repo_head_hexsha": "43651d8548431b26538739cc3130d315de4d4f7f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Notes/chap3/code/Q3/main.cpp", "max_forks_repo_name": "Alexbeast-CN/Notes2SLAM", "max_forks_repo_head_hexsha": "43651d8548431b26538739cc3130d315de4d4f7f", "max_forks_repo_licenses": ["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.1666666667, "max_line_length": 66, "alphanum_fraction": 0.5871559633, "num_tokens": 155, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300048, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.4889906475950701}}
{"text": "#include <polyvec/polygon-tracer/error-metrics.hpp>\n\n// polyfit\n#include <polyvec/api.hpp>\n#include <polyvec/geom.hpp>\n#include <polyvec/geometry/path.hpp>\n#include <polyvec/core/options.hpp>\n#include <polyvec/debug.hpp>\n#include <polyvec/geometry/angle.hpp>\n#include <polyvec/core/options.hpp>\n\n// c++ stl\n#include <algorithm>\n\n// Eigen\n#include <Eigen/Geometry>\n\n#define SMOOTHNESS_LIMIT VectorOptions::get()->error_smoothness_limit\n#define CONTINUITY_LIMIT VectorOptions::get()->error_continuity_limit\n#define INFLECTION_LIMIT VectorOptions::get()->error_inflection_limit\n#define INFLECTION_PENALTY VectorOptions::get()->error_inflection_penalty\n\n#define SMOOTHNESS_WEIGHT VectorOptions::get()->error_smoothness_weight\n#define ACCURACY_WEIGHT VectorOptions::get()->error_accuracy_weight\n#define CONTINUITY_WEIGHT VectorOptions::get()->error_continuity_weight\n\nusing namespace polyvec;\nusing namespace std;\n\nnamespace polyfit {\n\tnamespace ErrorMetrics {\n\t\tdouble smoothness(const double rad0, const double rad1, const int flags) {\n\t\t\tconst bool is_first = flags & EDGE_FIRST_IN_PATH;\n\t\t\tconst bool is_last = flags & EDGE_LAST_IN_PATH;\n\n\t\t\tdouble e = 0.;\n\t\t\te += .5 * (!(is_first) ? smoothness(rad0) : 0.);\n\t\t\te += .5 * (!(is_last) ?  smoothness(rad1) : 0.);\n\t\t\treturn e;\n\t\t}\n\n\t\tdouble smoothness(const double rad0) {\n\t\t\treturn SMOOTHNESS_WEIGHT * min((M_PI - rad0) / SMOOTHNESS_LIMIT, 1.0);\n\t\t}\n\n\t\tdouble accuracy(const double d_min, const double d_max, const int flags) {\n\t\t\tconst double overflow = max(d_max - 1., 0.) + max(d_min - .5, 0.);\n\t\t\treturn ACCURACY_WEIGHT * d_min + max(d_max - .5, 0.) + overflow;\n\t\t}\n\n\t\tdouble accuracy_implicit(const double d_min, const double d_max, const int flags) {\n\t\t\treturn ACCURACY_WEIGHT * 2 * max(0., d_max - .5);\n\t\t}\n\n\t\tdouble continuity(const double rad0, const double rad1, const int flags) {\n\t\t\tif ((flags & EDGE_LAST_IN_PATH) || (flags & EDGE_FIRST_IN_PATH)) {\n\t\t\t\treturn 0.;\n\t\t\t}\n\n\t\t\tif (flags & EDGE_HAS_INFLECTION) {\n                return CONTINUITY_WEIGHT * min(1., INFLECTION_PENALTY + (M_PI - min(rad0, rad1)) / INFLECTION_LIMIT  * (1. - INFLECTION_PENALTY));\n                //const double a = min(2 * M_PI - rad0 - rad1, CONTINUITY_LIMIT);\n                //return CONTINUITY_WEIGHT * a / CONTINUITY_LIMIT;\n\t\t\t}\n\t\t\telse {\n\t\t\t\treturn CONTINUITY_WEIGHT * min(abs(rad0 - rad1) / CONTINUITY_LIMIT, 1.0);\n\t\t\t}\n\t\t}\n\n\t\tbool accuracy_within_bounds(const double d_min, const double d_max, const vec2& edge_dir) {\n\t\t\t// This is only checking the distance measures, not the error\n\n\t\t\tconst double phi = atan2(edge_dir.cwiseAbs().minCoeff(), edge_dir.cwiseAbs().maxCoeff());\n\t\t\tconst double d_eps = .1;\n\t\t\t// adaptive accuracy\n\t\t\tconst double max_threshold = std::min(1.0, 0.5 + (.5 + d_eps) * cos(phi) - .5 * sin(phi));\n\n\t\t\treturn (d_min <= .5 + PF_EPS && d_max <= max_threshold - PF_EPS);\n\n\t\t\t//return (d_min <= (.5 + PF_EPS) && d_max <= (1. - PF_EPS));\n\t\t}\n\n\t\tbool accuracy_within_bounds_relaxed(const double d_min, const double d_max) {\n\t\t\treturn d_min < 1. - PF_EPS && d_max < 1. - PF_EPS;\n\t\t}\n\n\t\tvec3 calculate_at_edge(const mat2x& points, const mat24& p, const vec4i& v, int flags) {\n#if 0\n\t\t\tassert_break(p.cols() == 4);\n\n\t\t\tconst double rad0 = PathUtils::shortest_angle_spanned(p.col(0), p.col(1), p.col(2));\n\t\t\tconst double rad1 = PathUtils::shortest_angle_spanned(p.col(1), p.col(2), p.col(3));\n\t\t\tflags |= PathUtils::are_consecutive_angles_opposite(p.col(0), p.col(1), p.col(2), p.col(3)) ? EDGE_HAS_INFLECTION : 0x0;\n\n#if 1\n\t\t\tdbg::info(FMT(\"error-metric - angles:(%.3f %.3f) inflection: %d\", geom::degrees(rad0), geom::degrees(rad1), flags & EDGE_HAS_INFLECTION));\n#endif\n\n\t\t\tconst vec2 d_err = PathUtils::distance_bounds_from_points(points, p.block(0, 1, 2, 2), v.segment(1, 2), );\n\n\t\t\tvec3 error;\n\t\t\terror(0) = smoothness(rad0, rad1, flags);\n\t\t\terror(1) = accuracy(d_err.x(), d_err.y(), flags);\n\t\t\terror(2) = continuity(rad0, rad1, flags);\n\t\t\treturn error;\n#endif\n\t\t\treturn vec3(0., 0., 0.);\n\t\t}\n\n\t\tvec3 calculate_inner_sep(double d_min, double d_max, const vec2 p0, const vec2 p1, const vec2 p2, const vec2 p3) {\n\t\t\tconst int flags = AngleUtils::have_opposite_convexity(p0, p1, p2, p3) ? EDGE_HAS_INFLECTION : 0x0;\n\t\t\tconst double rad0 = AngleUtils::spanned_shortest(p0, p1, p2);\n\t\t\tconst double rad1 = AngleUtils::spanned_shortest(p1, p2, p3);\n\t\t\tvec3 e;\n\t\t\te(SMOOTHNESS) = ErrorMetrics::smoothness(rad0, rad1, flags);\n\t\t\te(CONTINUITY) = ErrorMetrics::continuity(rad0, rad1, flags);\n\n\t\t\tif (VectorOptions::get()->accuracy_metric == AccuracyMetric::OneSided) {\n\t\t\t\te(ACCURACY) = ErrorMetrics::accuracy(d_min, d_max, flags);\n\t\t\t}\n\t\t\telse if (VectorOptions::get()->accuracy_metric == AccuracyMetric::Implicit) {\n\t\t\t\te(ACCURACY) = ErrorMetrics::accuracy_implicit(d_min, d_max, flags);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tPF_ABORT;\n\t\t\t}\n\t\t\treturn e;\n\t\t}\n\n\t\tvec3 calculate_first_sep(double d_min, double d_max, const vec2 p1, const vec2 p2, const vec2 p3) {\n\t\t\tconst int flags = EDGE_FIRST_IN_PATH;\n\t\t\tconst double rad1 = AngleUtils::spanned_shortest(p1, p2, p3);\n\t\t\tvec3 e;\n\t\t\te(SMOOTHNESS) = ErrorMetrics::smoothness(M_PI, rad1, flags);\n\t\t\te(CONTINUITY) = ErrorMetrics::continuity(M_PI, rad1, flags);\n\t\t\tif (VectorOptions::get()->accuracy_metric == AccuracyMetric::OneSided) {\n\t\t\t\te(ACCURACY) = ErrorMetrics::accuracy(d_min, d_max, flags);\n\t\t\t}\n\t\t\telse if (VectorOptions::get()->accuracy_metric == AccuracyMetric::Implicit) {\n\t\t\t\te(ACCURACY) = ErrorMetrics::accuracy_implicit(d_min, d_max, flags);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tPF_ABORT;\n\t\t\t}\n\t\t\treturn e;\n\t\t}\n\n\t\tvec3 calculate_last_sep(double d_min, double d_max, const vec2 p1, const vec2 p2, const vec2 p3) {\n\t\t\tconst int flags = EDGE_FIRST_IN_PATH;\n\t\t\tconst double rad1 = AngleUtils::spanned_shortest(p1, p2, p3);\n\t\t\tvec3 e;\n\t\t\te(SMOOTHNESS) = ErrorMetrics::smoothness(M_PI, rad1, flags);\n\t\t\te(CONTINUITY) = ErrorMetrics::continuity(M_PI, rad1, flags);\n\t\t\tif (VectorOptions::get()->accuracy_metric == AccuracyMetric::OneSided) {\n\t\t\t\te(ACCURACY) = ErrorMetrics::accuracy(d_min, d_max, flags);\n\t\t\t}\n\t\t\telse if (VectorOptions::get()->accuracy_metric == AccuracyMetric::Implicit) {\n\t\t\t\te(ACCURACY) = ErrorMetrics::accuracy_implicit(d_min, d_max, flags);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tPF_ABORT;\n\t\t\t}\n\t\t\treturn e;\n\t\t}\n\n\t\tdouble calculate_inner(double d_min, double d_max, const vec2 p0, const vec2 p1, const vec2 p2, const vec2 p3) {\n\t\t\tconst vec3 e = calculate_inner_sep(d_min, d_max, p0, p1, p2, p3);\n\t\t\treturn e.sum();\n\t\t}\n\n\t\tdouble calculate_first(double d_min, double d_max, const vec2 p1, const vec2 p2, const vec2 p3) {\n\t\t\tconst vec3 e = calculate_first_sep(d_min, d_max, p1, p2, p3);\n\t\t\treturn e.sum();\n\t\t}\n\n\t\tdouble calculate_last(double d_min, double d_max, const vec2 p1, const vec2 p2, const vec2 p3) {\n\t\t\tconst vec3 e = calculate_last_sep(d_min, d_max, p1, p2, p3);\n\t\t\treturn e.sum();\n\t\t}\n\t}\n}", "meta": {"hexsha": "5691b45fe27d8b3bdd8e8e197b645f75af59f1f5", "size": 6774, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/polyvec/polygon-tracer/error-metrics.cpp", "max_stars_repo_name": "ShnitzelKiller/polyfit", "max_stars_repo_head_hexsha": "51ddc6365a794db1678459140658211cb78f65b1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2020-08-17T17:25:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T05:49:12.000Z", "max_issues_repo_path": "source/polyvec/polygon-tracer/error-metrics.cpp", "max_issues_repo_name": "ShnitzelKiller/polyfit", "max_issues_repo_head_hexsha": "51ddc6365a794db1678459140658211cb78f65b1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-08-26T13:54:59.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-21T07:19:22.000Z", "max_forks_repo_path": "source/polyvec/polygon-tracer/error-metrics.cpp", "max_forks_repo_name": "ShnitzelKiller/polyfit", "max_forks_repo_head_hexsha": "51ddc6365a794db1678459140658211cb78f65b1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-08-26T23:26:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-04T09:06:07.000Z", "avg_line_length": 37.4254143646, "max_line_length": 146, "alphanum_fraction": 0.6907292589, "num_tokens": 2059, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869786798663, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.48897551148438845}}
{"text": "// Copyright 2015-2018 Hans Dembinski\n//\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n//[ guide_make_dynamic_histogram\n\n#include <boost/histogram.hpp>\n#include <cassert>\n#include <sstream>\n#include <vector>\n\nconst char* config = \"4 1.0 2.0\\n\"\n                     \"5 3.0 4.0\\n\";\n\nint main() {\n  using namespace boost::histogram;\n\n  // read axis config from a config file (mocked here with std::istringstream)\n  // and create vector of regular axes, the number of axis is not known at compile-time\n  std::istringstream is(config);\n  auto v1 = std::vector<axis::regular<>>();\n  while (is.good()) {\n    unsigned bins;\n    double start, stop;\n    is >> bins >> start >> stop;\n    v1.emplace_back(bins, start, stop);\n  }\n\n  // create histogram from iterator range\n  // (copying or moving the vector also works, move is shown below)\n  auto h1 = make_histogram(v1.begin(), v1.end());\n  assert(h1.rank() == v1.size());\n\n  // with a vector of axis::variant (polymorphic axis type that can hold any one of the\n  // template arguments at a time) the types and number of axis can vary at run-time\n  auto v2 = std::vector<axis::variant<axis::regular<>, axis::integer<>>>();\n  v2.emplace_back(axis::regular<>(100, -1.0, 1.0));\n  v2.emplace_back(axis::integer<>(1, 7));\n\n  // create dynamic histogram by moving the vector\n  auto h2 = make_histogram(std::move(v2));\n  assert(h2.rank() == 2);\n}\n\n//]\n", "meta": {"hexsha": "80ab025eee807493a100a4b918a803433931080d", "size": 1495, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/histogram/examples/guide_make_dynamic_histogram.cpp", "max_stars_repo_name": "cpp-pm/boost", "max_stars_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "libs/histogram/examples/guide_make_dynamic_histogram.cpp", "max_issues_repo_name": "cpp-pm/boost", "max_issues_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "libs/histogram/examples/guide_make_dynamic_histogram.cpp", "max_forks_repo_name": "cpp-pm/boost", "max_forks_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 31.1458333333, "max_line_length": 87, "alphanum_fraction": 0.6722408027, "num_tokens": 411, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583376458153, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.48893165089098634}}
{"text": "#define _USE_MATH_DEFINES\n#include \"matplotlibcpp.h\"\n#include <Eigen/Dense>\n#include <cmath>\n#include <iostream>\n\nnamespace plt = matplotlibcpp;\n\nint main() {\n  // Prepare data.\n  int n = 5000;\n  Eigen::VectorXd x(n), y(n), z(n), w = Eigen::VectorXd::Ones(n);\n  for (int i = 0; i < n; ++i) {\n    double value = (1.0 + i) / n;\n    x(i) = value;\n    y(i) = value * value;\n    z(i) = value * value * value;\n  }\n\n  // Plot line from given x and y data. Color is selected automatically.\n  plt::semilogy(x, y);\n\n  // Plot a red dashed line from given x and y data.\n  plt::semilogy(x, w, {{\"c\", \"r\"}, {\"ls\", \"--\"}});\n\n  // Plot a line whose name will show up as \"log(x)\" in the legend.\n  plt::semilogy(x, z, \"g:\", {{\"label\", \"$x^3$\"}});\n\n  // Add graph title\n  plt::title(\"Sample figure\");\n\n  // Enable legend.\n  plt::legend();\n\n  // show figure\n  plt::show();\n}\n", "meta": {"hexsha": "4102ed2e00c7c3cfa3f9c6d61c6baae3a3707d18", "size": 856, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/semilogy.cpp", "max_stars_repo_name": "LucaMac1/matplotlib-cpp", "max_stars_repo_head_hexsha": "2d56975b1c2dd6f96061685b520f7a552a5f8adf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/semilogy.cpp", "max_issues_repo_name": "LucaMac1/matplotlib-cpp", "max_issues_repo_head_hexsha": "2d56975b1c2dd6f96061685b520f7a552a5f8adf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/semilogy.cpp", "max_forks_repo_name": "LucaMac1/matplotlib-cpp", "max_forks_repo_head_hexsha": "2d56975b1c2dd6f96061685b520f7a552a5f8adf", "max_forks_repo_licenses": ["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.5263157895, "max_line_length": 72, "alphanum_fraction": 0.5794392523, "num_tokens": 271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583376458153, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.4889316422219394}}
{"text": "#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE \"CNNInit\"\n#include <boost/test/unit_test.hpp>\n\n#include <vector>\n\n#include \"cnn/tests/test_utils.h\"\n#include \"cnn/tensor.h\"\n#include \"cnn/saxe-init.h\"\n\nusing namespace std;\nusing namespace cnn;\n\nBOOST_GLOBAL_FIXTURE(TestTensorSetup)\n\nBOOST_AUTO_TEST_CASE(EOrthonormalRandom)\n{\n  for (int d = 4; d < 128; d += 2) {\n    Tensor Q = OrthonormalRandom(d, 1.0);\n//    BOOST_REQUIRE_EQUAL(size(Q), Dim({d,d}));\n\n    // check that this is actually returning orthogonal matrices\n#if MINERVA_BACKEND\n    Tensor I = Q.Trans() * Q;\n#endif\n#if THPP_BACKEND\n    Tensor QT = Q;\n    QT.transpose();\n    //cerr << str(Q) << endl << str(QT) << endl;\n    Tensor I = Zero({d,d});\n    I.addmm(0, 1, Q, QT);\n    //cerr << str(I) << endl;\n#endif\n#if EIGEN_BACKEND\n    Tensor I = Q.transpose() * Q;\n#endif\n    double eps = 1e-1;\n    for (int i = 0; i < d; ++i)\n      for (int j = 0; j < d; ++j)\n        BOOST_CHECK_CLOSE(t(I,i,j) + 1., (i == j ? 2. : 1.), eps);\n  }\n  cerr << \"Finished\\n\";\n}\n\nBOOST_AUTO_TEST_CASE(BernoulliInit) {\n  Tensor r = RandomBernoulli(Dim({1000,1000}), 0.5f);\n  int tot = 0;\n  for (int i = 0; i < 1000; ++i)\n    for (int j = 0; j < 1000; ++j)\n      if (t(r,i,j)) ++tot;\n  BOOST_CHECK_GT(tot, 490000);\n  BOOST_CHECK_LT(tot, 510000);\n}\n\nBOOST_AUTO_TEST_CASE(Rand01) {\n  cnn::real tot = 0;\n  for (unsigned i = 0; i < 1000000; ++i)\n    tot += cnn::rand01();\n  BOOST_CHECK_GT(tot, 490000.);\n  BOOST_CHECK_LT(tot, 510000.);\n}\n\n\n", "meta": {"hexsha": "1a436af84522cfe93656401850c7119f4f5b1d1f", "size": 1477, "ext": "cc", "lang": "C++", "max_stars_repo_path": "cnn/cnn/tests/test_init.cc", "max_stars_repo_name": "miguelballesteros/Spinal", "max_stars_repo_head_hexsha": "0f765e5baeb07a1d068c4eda06b9222e06df2cde", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 219.0, "max_stars_repo_stars_event_min_datetime": "2015-06-27T13:15:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-13T20:45:34.000Z", "max_issues_repo_path": "cnn/cnn/tests/test_init.cc", "max_issues_repo_name": "miguelballesteros/Spinal", "max_issues_repo_head_hexsha": "0f765e5baeb07a1d068c4eda06b9222e06df2cde", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 18.0, "max_issues_repo_issues_event_min_datetime": "2015-07-08T05:12:55.000Z", "max_issues_repo_issues_event_max_datetime": "2018-04-23T13:38:10.000Z", "max_forks_repo_path": "cnn/cnn/tests/test_init.cc", "max_forks_repo_name": "miguelballesteros/Spinal", "max_forks_repo_head_hexsha": "0f765e5baeb07a1d068c4eda06b9222e06df2cde", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 68.0, "max_forks_repo_forks_event_min_datetime": "2015-06-29T16:51:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-10T20:35:14.000Z", "avg_line_length": 23.078125, "max_line_length": 66, "alphanum_fraction": 0.6140825999, "num_tokens": 500, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.4889316420304224}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// QuickBook Example\n\n// Copyright (c) 2011-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//[make_2d_point\n//` Shows the usage of make as a generic constructor for different point types\n\n#include <iostream>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/register/point.hpp>\n#include <boost/geometry/geometries/adapted/boost_tuple.hpp>\n#include <boost/geometry/geometries/adapted/boost_polygon/point.hpp>\n\nBOOST_GEOMETRY_REGISTER_BOOST_TUPLE_CS(cs::cartesian)\n\nstruct mypoint { float _x, _y; };\n\nBOOST_GEOMETRY_REGISTER_POINT_2D(mypoint, float, cs::cartesian, _x, _y)\n\ntemplate <typename Point>\nvoid construct_and_display()\n{\n    using boost::geometry::make;\n    using boost::geometry::get;\n\n    Point p = make<Point>(1, 2);\n\n    std::cout << \"x=\" << get<0>(p) << \" y=\" << get<1>(p)\n        << \" (\" << typeid(Point).name() << \")\"\n        << std::endl;\n}\n\nint main()\n{\n    construct_and_display<boost::geometry::model::d2::point_xy<double> >();\n    construct_and_display<boost::geometry::model::d2::point_xy<int> >();\n    construct_and_display<boost::tuple<double, double> >();\n    construct_and_display<boost::polygon::point_data<int> >();\n    construct_and_display<mypoint>();\n    return 0;\n}\n\n//]\n\n//[make_2d_point_output\n/*`\nOutput (compiled using gcc):\n[pre\nx=1 y=2 (N5boost8geometry5model2d28point_xyIdNS0_2cs9cartesianEEE)\nx=1 y=2 (N5boost8geometry5model2d28point_xyIiNS0_2cs9cartesianEEE)\nx=1 y=2 (N5boost6tuples5tupleIddNS0_9null_typeES2_S2_S2_S2_S2_S2_S2_EE)\nx=1 y=2 (N5boost7polygon10point_dataIiEE)\nx=1 y=2 (7mypoint)\n]\n*/\n//]\n", "meta": {"hexsha": "92f7b0259a5a2a580c62b70f9d84fbc03d11bbe7", "size": 1853, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/geometry/doc/src/examples/algorithms/make_2d_point.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "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": "boost/libs/geometry/doc/src/examples/algorithms/make_2d_point.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "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": "boost/libs/geometry/doc/src/examples/algorithms/make_2d_point.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "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": 28.953125, "max_line_length": 79, "alphanum_fraction": 0.7312466271, "num_tokens": 554, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.7025300573952052, "lm_q1q2_score": 0.48893164203042233}}
{"text": "\n\n\n/* --------------------------------------------------------------------- \n * \n * Copyright (C) 2018 - 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: Thomas C. Clevenger, Clemson University \n *          Timo Heister, Clemson University and University of Utah \n */ \n\n\n// @sect3{Include files}  \n\n// \u6807\u51c6deal.II\u9700\u8981\u7684\u5178\u578b\u6587\u4ef6\u3002\n\n#include <deal.II/base/tensor_function.h> \n#include <deal.II/base/quadrature_lib.h> \n#include <deal.II/base/function.h> \n#include <deal.II/base/timer.h> \n#include <deal.II/base/parameter_handler.h> \n\n#include <deal.II/lac/affine_constraints.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_gmres.h> \n#include <deal.II/lac/precondition.h> \n#include <deal.II/lac/relaxation_block.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/manifold_lib.h> \n#include <deal.II/grid/grid_out.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/mapping_q.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\n// \u5305\u62ec\u6240\u6709\u76f8\u5173\u7684\u591a\u5c42\u6b21\u6587\u4ef6\u3002\n\n#include <deal.II/multigrid/mg_constrained_dofs.h> \n#include <deal.II/multigrid/multigrid.h> \n#include <deal.II/multigrid/mg_transfer.h> \n#include <deal.II/multigrid/mg_tools.h> \n#include <deal.II/multigrid/mg_coarse.h> \n#include <deal.II/multigrid/mg_smoother.h> \n#include <deal.II/multigrid/mg_matrix.h> \n\n// C++:\n\n#include <algorithm> \n#include <fstream> \n#include <iostream> \n#include <random> \n\n// \u6211\u4eec\u5c06\u4f7f\u7528 MeshWorker::mesh_loop \u529f\u80fd\u6765\u7ec4\u88c5\u77e9\u9635\u3002\n\n#include <deal.II/meshworker/mesh_loop.h> \n// @sect3{MeshWorker data}  \n\n// \u50cf\u5f80\u5e38\u4e00\u6837\uff0c\u6211\u4eec\u5c06\u628a\u6240\u6709\u4e0e\u8fd9\u4e2a\u7a0b\u5e8f\u6709\u5173\u7684\u4e1c\u897f\u653e\u5230\u4e00\u4e2a\u81ea\u5df1\u7684\u547d\u540d\u7a7a\u95f4\u4e2d\u3002\n\n// \u7531\u4e8e\u6211\u4eec\u5c06\u4f7f\u7528MeshWorker\u6846\u67b6\uff0c\u7b2c\u4e00\u6b65\u662f\u5b9a\u4e49\u4ee5\u4e0b\u7531 MeshWorker::mesh_loop(): \u4f7f\u7528\u7684assemble_cell()\u51fd\u6570\u6240\u9700\u8981\u7684\u7ed3\u6784 `ScratchData`\u5305\u542b\u4e00\u4e2aFEValues\u5bf9\u8c61\uff0c\u8fd9\u662f\u7ec4\u88c5\u4e00\u4e2a\u5355\u5143\u7684\u5c40\u90e8\u8d21\u732e\u6240\u9700\u8981\u7684\uff0c\u800c`CopyData`\u5305\u542b\u4e00\u4e2a\u5355\u5143\u7684\u5c40\u90e8\u8d21\u732e\u7684\u8f93\u51fa\u548c\u590d\u5236\u5230\u5168\u5c40\u7cfb\u7edf\u7684\u5fc5\u8981\u4fe1\u606f\u3002\u5b83\u4eec\u7684\u76ee\u7684\u5728WorkStream\u7c7b\u7684\u6587\u6863\u4e2d\u4e5f\u6709\u89e3\u91ca\uff09\u3002\n\nnamespace Step63 \n{ \n  using namespace dealii; \n\n  template <int dim> \n  struct ScratchData \n  { \n    ScratchData(const FiniteElement<dim> &fe, \n                const unsigned int        quadrature_degree) \n      : fe_values(fe, \n                  QGauss<dim>(quadrature_degree), \n                  update_values | update_gradients | update_hessians | \n                    update_quadrature_points | update_JxW_values) \n    {} \n\n    ScratchData(const ScratchData<dim> &scratch_data) \n      : fe_values(scratch_data.fe_values.get_fe(), \n                  scratch_data.fe_values.get_quadrature(), \n                  update_values | update_gradients | update_hessians | \n                    update_quadrature_points | update_JxW_values) \n    {} \n\n    FEValues<dim> fe_values; \n  }; \n\n  struct CopyData \n  { \n    CopyData() = default; \n\n    unsigned int level; \n    unsigned int dofs_per_cell; \n\n    FullMatrix<double>                   cell_matrix; \n    Vector<double>                       cell_rhs; \n    std::vector<types::global_dof_index> local_dof_indices; \n  }; \n\n//  @sect3{Problem parameters}  \n\n// \u7b2c\u4e8c\u6b65\u662f\u5b9a\u4e49\u5904\u7406\u8981\u4ece\u8f93\u5165\u6587\u4ef6\u4e2d\u8bfb\u53d6\u7684\u8fd0\u884c\u65f6\u53c2\u6570\u7684\u7c7b\u3002\n\n// \u6211\u4eec\u5c06\u4f7f\u7528ParameterHandler\u5728\u8fd0\u884c\u65f6\u4f20\u5165\u53c2\u6570\u3002\u7ed3\u6784`Settings`\u89e3\u6790\u5e76\u5b58\u50a8\u6574\u4e2a\u7a0b\u5e8f\u8981\u67e5\u8be2\u7684\u53c2\u6570\u3002\n\n  struct Settings \n  { \n    enum DoFRenumberingStrategy \n    { \n      none, \n      downstream, \n      upstream, \n      random \n    }; \n\n    void get_parameters(const std::string &prm_filename); \n\n    double                 epsilon; \n    unsigned int           fe_degree; \n    std::string            smoother_type; \n    unsigned int           smoothing_steps; \n    DoFRenumberingStrategy dof_renumbering; \n    bool                   with_streamline_diffusion; \n    bool                   output; \n  }; \n\n  void Settings::get_parameters(const std::string &prm_filename) \n  { \n\n/* \u9996\u5148\u58f0\u660e\u53c2\u6570...   */ \n\n \n    ParameterHandler prm; \n\n    prm.declare_entry(\"Epsilon\", \n                      \"0.005\", \n                      Patterns::Double(0), \n                      \"Diffusion parameter\"); \n\n    prm.declare_entry(\"Fe degree\", \n                      \"1\", \n                      Patterns::Integer(1), \n                      \"Finite Element degree\"); \n    prm.declare_entry(\"Smoother type\", \n                      \"block SOR\", \n                      Patterns::Selection(\"SOR|Jacobi|block SOR|block Jacobi\"), \n                      \"Select smoother: SOR|Jacobi|block SOR|block Jacobi\"); \n    prm.declare_entry(\"Smoothing steps\", \n                      \"2\", \n                      Patterns::Integer(1), \n                      \"Number of smoothing steps\"); \n    prm.declare_entry( \n      \"DoF renumbering\", \n      \"downstream\", \n      Patterns::Selection(\"none|downstream|upstream|random\"), \n      \"Select DoF renumbering: none|downstream|upstream|random\"); \n    prm.declare_entry(\"With streamline diffusion\", \n                      \"true\", \n                      Patterns::Bool(), \n                      \"Enable streamline diffusion stabilization: true|false\"); \n    prm.declare_entry(\"Output\", \n                      \"true\", \n                      Patterns::Bool(), \n                      \"Generate graphical output: true|false\"); \n    /* ...\u7136\u540e\u5c1d\u8bd5\u4ece\u8f93\u5165\u6587\u4ef6\u4e2d\u8bfb\u53d6\u5b83\u4eec\u7684\u503c\u3002  */ \n    if (prm_filename.empty()) \n      { \n        prm.print_parameters(std::cout, ParameterHandler::Text); \n        AssertThrow( \n          false, ExcMessage(\"Please pass a .prm file as the first argument!\")); \n      } \n\n    prm.parse_input(prm_filename); \n\n    epsilon         = prm.get_double(\"Epsilon\"); \n    fe_degree       = prm.get_integer(\"Fe degree\"); \n    smoother_type   = prm.get(\"Smoother type\"); \n    smoothing_steps = prm.get_integer(\"Smoothing steps\"); \n\n    const std::string renumbering = prm.get(\"DoF renumbering\"); \n    if (renumbering == \"none\") \n      dof_renumbering = DoFRenumberingStrategy::none; \n    else if (renumbering == \"downstream\") \n      dof_renumbering = DoFRenumberingStrategy::downstream; \n    else if (renumbering == \"upstream\") \n      dof_renumbering = DoFRenumberingStrategy::upstream; \n    else if (renumbering == \"random\") \n      dof_renumbering = DoFRenumberingStrategy::random; \n    else \n      AssertThrow(false, \n                  ExcMessage(\"The <DoF renumbering> parameter has \" \n                             \"an invalid value.\")); \n\n    with_streamline_diffusion = prm.get_bool(\"With streamline diffusion\"); \n    output                    = prm.get_bool(\"Output\"); \n  } \n// @sect3{Cell permutations}  \n\n// \u904d\u5386\u5355\u5143\u548c\u81ea\u7531\u5ea6\u7684\u987a\u5e8f\u5c06\u5bf9\u4e58\u6cd5\u7684\u6536\u655b\u901f\u5ea6\u8d77\u4f5c\u7528\u3002\u5728\u8fd9\u91cc\uff0c\u6211\u4eec\u5b9a\u4e49\u4e86\u4e00\u4e9b\u51fd\u6570\uff0c\u8fd9\u4e9b\u51fd\u6570\u8fd4\u56de\u5355\u5143\u683c\u7684\u7279\u5b9a\u987a\u5e8f\uff0c\u4f9b\u5757\u5e73\u6ed1\u5668\u4f7f\u7528\u3002\n\n// \u5bf9\u4e8e\u6bcf\u79cd\u7c7b\u578b\u7684\u5355\u5143\u683c\u6392\u5e8f\uff0c\u6211\u4eec\u5b9a\u4e49\u4e86\u4e00\u4e2a\u7528\u4e8e\u6d3b\u52a8\u7f51\u683c\u7684\u51fd\u6570\u548c\u4e00\u4e2a\u7528\u4e8e\u6c34\u5e73\u7f51\u683c\u7684\u51fd\u6570\uff08\u5373\u7528\u4e8e\u591a\u7f51\u683c\u5c42\u6b21\u7ed3\u6784\u4e2d\u7684\u67d0\u4e00\u5c42\u7684\u5355\u5143\u683c\uff09\u3002\u867d\u7136\u6c42\u89e3\u7cfb\u7edf\u6240\u9700\u7684\u552f\u4e00\u91cd\u65b0\u6392\u5e8f\u662f\u5728\u6c34\u5e73\u7f51\u683c\u4e0a\u8fdb\u884c\u7684\uff0c\u4f46\u4e3a\u4e86\u53ef\u89c6\u5316\u7684\u76ee\u7684\uff0c\u6211\u4eec\u5728output_results()\u4e2d\u5305\u542b\u4e86\u4e3b\u52a8\u7f51\u683c\u7684\u91cd\u65b0\u6392\u5e8f\u3002\n\n// \u5bf9\u4e8e\u4e24\u4e2a\u4e0b\u6e38\u6392\u5e8f\u51fd\u6570\uff0c\u6211\u4eec\u9996\u5148\u521b\u5efa\u4e00\u4e2a\u5305\u542b\u6240\u6709\u76f8\u5173\u5355\u5143\u7684\u6570\u7ec4\uff0c\u7136\u540e\u4f7f\u7528\u4e00\u4e2a \"\u6bd4\u8f83\u5668 \"\u5bf9\u8c61\u5728\u4e0b\u6e38\u65b9\u5411\u8fdb\u884c\u6392\u5e8f\u3002\u7136\u540e\uff0c\u51fd\u6570\u7684\u8f93\u51fa\u662f\u4e00\u4e2a\u7b80\u5355\u7684\u6570\u7ec4\uff0c\u5305\u542b\u4e86\u521a\u521a\u8ba1\u7b97\u51fa\u6765\u7684\u5355\u5143\u683c\u7684\u7d22\u5f15\u3002\n\n  template <int dim> \n  std::vector<unsigned int> \n  create_downstream_cell_ordering(const DoFHandler<dim> &dof_handler, \n                                  const Tensor<1, dim>   direction, \n                                  const unsigned int     level) \n  { \n    std::vector<typename DoFHandler<dim>::level_cell_iterator> ordered_cells; \n    ordered_cells.reserve(dof_handler.get_triangulation().n_cells(level)); \n    for (const auto &cell : dof_handler.cell_iterators_on_level(level)) \n      ordered_cells.push_back(cell); \n\n    const DoFRenumbering:: \n      CompareDownstream<typename DoFHandler<dim>::level_cell_iterator, dim> \n        comparator(direction); \n    std::sort(ordered_cells.begin(), ordered_cells.end(), comparator); \n\n    std::vector<unsigned> ordered_indices; \n    ordered_indices.reserve(dof_handler.get_triangulation().n_cells(level)); \n\n    for (const auto &cell : ordered_cells) \n      ordered_indices.push_back(cell->index()); \n\n    return ordered_indices; \n  } \n\n  template <int dim> \n  std::vector<unsigned int> \n  create_downstream_cell_ordering(const DoFHandler<dim> &dof_handler, \n                                  const Tensor<1, dim>   direction) \n  { \n    std::vector<typename DoFHandler<dim>::active_cell_iterator> ordered_cells; \n    ordered_cells.reserve(dof_handler.get_triangulation().n_active_cells()); \n    for (const auto &cell : dof_handler.active_cell_iterators()) \n      ordered_cells.push_back(cell); \n\n    const DoFRenumbering:: \n      CompareDownstream<typename DoFHandler<dim>::active_cell_iterator, dim> \n        comparator(direction); \n    std::sort(ordered_cells.begin(), ordered_cells.end(), comparator); \n\n    std::vector<unsigned int> ordered_indices; \n    ordered_indices.reserve(dof_handler.get_triangulation().n_active_cells()); \n\n    for (const auto &cell : ordered_cells) \n      ordered_indices.push_back(cell->index()); \n\n    return ordered_indices; \n  } \n\n// \u4ea7\u751f\u968f\u673a\u6392\u5e8f\u7684\u51fd\u6570\u5728\u7cbe\u795e\u4e0a\u662f\u76f8\u4f3c\u7684\uff0c\u5b83\u4eec\u9996\u5148\u5c06\u6240\u6709\u5355\u5143\u7684\u4fe1\u606f\u653e\u5165\u4e00\u4e2a\u6570\u7ec4\u3002\u4f46\u662f\uff0c\u5b83\u4eec\u4e0d\u662f\u5bf9\u5b83\u4eec\u8fdb\u884c\u6392\u5e8f\uff0c\u800c\u662f\u5229\u7528C++\u63d0\u4f9b\u7684\u751f\u6210\u968f\u673a\u6570\u7684\u8bbe\u65bd\u5bf9\u5143\u7d20\u8fdb\u884c\u968f\u673a\u6d17\u724c\u3002\u8fd9\u6837\u505a\u7684\u65b9\u5f0f\u662f\u5728\u6570\u7ec4\u7684\u6240\u6709\u5143\u7d20\u4e0a\u8fdb\u884c\u8fed\u4ee3\uff0c\u4e3a\u4e4b\u524d\u7684\u53e6\u4e00\u4e2a\u5143\u7d20\u62bd\u53d6\u4e00\u4e2a\u968f\u673a\u6570\uff0c\u7136\u540e\u4ea4\u6362\u8fd9\u4e9b\u5143\u7d20\u3002\u5176\u7ed3\u679c\u662f\u5bf9\u6570\u7ec4\u4e2d\u7684\u5143\u7d20\u8fdb\u884c\u968f\u673a\u6d17\u724c\u3002\n\n  template <int dim> \n  std::vector<unsigned int> \n  create_random_cell_ordering(const DoFHandler<dim> &dof_handler, \n                              const unsigned int     level) \n  { \n    std::vector<unsigned int> ordered_cells; \n    ordered_cells.reserve(dof_handler.get_triangulation().n_cells(level)); \n    for (const auto &cell : dof_handler.cell_iterators_on_level(level)) \n      ordered_cells.push_back(cell->index()); \n\n    std::mt19937 random_number_generator; \n    std::shuffle(ordered_cells.begin(), \n                 ordered_cells.end(), \n                 random_number_generator); \n\n    return ordered_cells; \n  } \n\n  template <int dim> \n  std::vector<unsigned int> \n  create_random_cell_ordering(const DoFHandler<dim> &dof_handler) \n  { \n    std::vector<unsigned int> ordered_cells; \n    ordered_cells.reserve(dof_handler.get_triangulation().n_active_cells()); \n    for (const auto &cell : dof_handler.active_cell_iterators()) \n      ordered_cells.push_back(cell->index()); \n\n    std::mt19937 random_number_generator; \n    std::shuffle(ordered_cells.begin(), \n                 ordered_cells.end(), \n                 random_number_generator); \n\n    return ordered_cells; \n  } \n// @sect3{Right-hand side and boundary values}  \n\n// \u672c\u6559\u7a0b\u4e2d\u6240\u89e3\u51b3\u7684\u95ee\u9898\u662f\u5bf9<a\n//  href=\"https:global.oup.com/academic/product/finite-elements-and-fast-iterative-solvers-9780199678808\">\n//  Finite Elements and Fast Iterative Solvers: with Applications in\n//  Incompressible Fluid Dynamics by Elman, Silvester, and Wathen</a>\u7b2c118\u9875\u4e0a\u7684\u4f8b3.1.3\u7684\u4fee\u6539\u3002\u4e3b\u8981\u7684\u533a\u522b\u662f\u6211\u4eec\u5728\u57df\u7684\u4e2d\u5fc3\u589e\u52a0\u4e86\u4e00\u4e2a\u6d1e\uff0c\u5176\u8fb9\u754c\u6761\u4ef6\u4e3a\u96f6\u7684Dirichlet\u3002\n\n// \u4e3a\u4e86\u83b7\u5f97\u5b8c\u6574\u7684\u63cf\u8ff0\uff0c\u6211\u4eec\u9700\u8981\u9996\u5148\u5b9e\u73b0\u96f6\u53f3\u624b\u8fb9\u7684\u7c7b\uff08\u5f53\u7136\uff0c\u6211\u4eec\u53ef\u4ee5\u76f4\u63a5\u4f7f\u7528 Functions::ZeroFunction):  \u3002\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 = 0) const override; \n\n    virtual void value_list(const std::vector<Point<dim>> &points, \n                            std::vector<double> &          values, \n                            const unsigned int component = 0) const override; \n  }; \n\n  template <int dim> \n  double RightHandSide<dim>::value(const Point<dim> &, \n                                   const unsigned int component) const \n  { \n    Assert(component == 0, ExcIndexRange(component, 0, 1)); \n    (void)component; \n\n    return 0.0; \n  } \n\n  template <int dim> \n  void 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// \u6211\u4eec\u4e5f\u6709\u8fea\u91cc\u5e0c\u7279\u7684\u8fb9\u754c\u6761\u4ef6\u3002\u5728\u5916\u90e8\u6b63\u65b9\u5f62\u8fb9\u754c\u7684\u8fde\u63a5\u90e8\u5206\uff0c\u6211\u4eec\u5c06\u6570\u503c\u8bbe\u7f6e\u4e3a1\uff0c\u5176\u4ed6\u5730\u65b9\uff08\u5305\u62ec\u5185\u90e8\u5706\u5f62\u8fb9\u754c\uff09\u7684\u6570\u503c\u8bbe\u7f6e\u4e3a0\u3002\n\n  template <int dim> \n  class BoundaryValues : public Function<dim> \n  { \n  public: \n    virtual double value(const Point<dim> & p, \n                         const unsigned int component = 0) const override; \n\n    virtual void value_list(const std::vector<Point<dim>> &points, \n                            std::vector<double> &          values, \n                            const unsigned int component = 0) const override; \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, ExcIndexRange(component, 0, 1)); \n    (void)component; \n\n// \u5982\u679c  $x=1$  \uff0c\u6216\u5982\u679c  $x>0.5$  \u548c  $y=-1$  \uff0c\u5219\u5c06\u8fb9\u754c\u8bbe\u4e3a 1\u3002\n\n    if (std::fabs(p[0] - 1) < 1e-8 || \n        (std::fabs(p[1] + 1) < 1e-8 && p[0] >= 0.5)) \n      { \n        return 1.0; \n      } \n    else \n      { \n        return 0.0; \n      } \n  } \n\n  template <int dim> \n  void 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//  @sect3{Streamline diffusion implementation}  \n\n// \u6d41\u6c34\u7ebf\u6269\u6563\u65b9\u6cd5\u6709\u4e00\u4e2a\u7a33\u5b9a\u5e38\u6570\uff0c\u6211\u4eec\u9700\u8981\u80fd\u591f\u8ba1\u7b97\u51fa\u6765\u3002\u8fd9\u4e2a\u53c2\u6570\u7684\u8ba1\u7b97\u65b9\u5f0f\u7684\u9009\u62e9\u53d6\u81ea\u4e8e<a\n//  href=\"https:link.springer.com/chapter/10.1007/978-3-540-34288-5_27\">On\n//  Discontinuity-Capturing Methods for Convection-Diffusion\n//  Equations by Volker John and Petr Knobloch</a>\u3002\n\n  template <int dim> \n  double compute_stabilization_delta(const double         hk, \n                                     const double         eps, \n                                     const Tensor<1, dim> dir, \n                                     const double         pk) \n  { \n    const double Peclet = dir.norm() * hk / (2.0 * eps * pk); \n    const double coth = \n      (1.0 + std::exp(-2.0 * Peclet)) / (1.0 - std::exp(-2.0 * Peclet)); \n\n    return hk / (2.0 * dir.norm() * pk) * (coth - 1.0 / Peclet); \n  } \n// @sect3{<code>AdvectionProlem</code> class}  \n\n// \u8fd9\u662f\u7a0b\u5e8f\u7684\u4e3b\u7c7b\uff0c\u770b\u8d77\u6765\u5e94\u8be5\u4e0e  step-16  \u975e\u5e38\u76f8\u4f3c\u3002\u4e3b\u8981\u7684\u533a\u522b\u662f\uff0c\u7531\u4e8e\u6211\u4eec\u662f\u5728\u8fd0\u884c\u65f6\u5b9a\u4e49\u6211\u4eec\u7684\u591a\u7f51\u683c\u5e73\u6ed1\u5668\uff0c\u6211\u4eec\u9009\u62e9\u5b9a\u4e49\u4e00\u4e2a\u51fd\u6570`create_smoother()`\u548c\u4e00\u4e2a\u7c7b\u5bf9\u8c61`mg_smoother`\uff0c\u8fd9\u662f\u4e00\u4e2a  `std::unique_ptr`  \u6d3e\u751f\u4e8eMGSmoother\u7684\u5e73\u6ed1\u5668\u3002\u8bf7\u6ce8\u610f\uff0c\u5bf9\u4e8e\u4eceRelaxationBlock\u6d3e\u751f\u7684\u5e73\u6ed1\u5668\uff0c\u6211\u4eec\u5fc5\u987b\u4e3a\u6bcf\u4e2a\u7ea7\u522b\u5305\u62ec\u4e00\u4e2a`smoother_data`\u5bf9\u8c61\u3002\u8fd9\u5c06\u5305\u542b\u5173\u4e8e\u5355\u5143\u683c\u6392\u5e8f\u548c\u5355\u5143\u683c\u77e9\u9635\u5012\u7f6e\u65b9\u6cd5\u7684\u4fe1\u606f\u3002\n\n  template <int dim> \n  class AdvectionProblem \n  { \n  public: \n    AdvectionProblem(const Settings &settings); \n    void run(); \n\n  private: \n    void setup_system(); \n\n    template <class IteratorType> \n    void assemble_cell(const IteratorType &cell, \n                       ScratchData<dim> &  scratch_data, \n                       CopyData &          copy_data); \n    void assemble_system_and_multigrid(); \n\n    void setup_smoother(); \n\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    const FE_Q<dim>     fe; \n    const MappingQ<dim> mapping; \n\n    AffineConstraints<double> constraints; \n\n    SparsityPattern      sparsity_pattern; \n    SparseMatrix<double> system_matrix; \n\n    Vector<double> solution; \n    Vector<double> system_rhs; \n\n    MGLevelObject<SparsityPattern> mg_sparsity_patterns; \n    MGLevelObject<SparsityPattern> mg_interface_sparsity_patterns; \n\n    MGLevelObject<SparseMatrix<double>> mg_matrices; \n    MGLevelObject<SparseMatrix<double>> mg_interface_in; \n    MGLevelObject<SparseMatrix<double>> mg_interface_out; \n\n    mg::Matrix<Vector<double>> mg_matrix; \n    mg::Matrix<Vector<double>> mg_interface_matrix_in; \n    mg::Matrix<Vector<double>> mg_interface_matrix_out; \n\n    std::unique_ptr<MGSmoother<Vector<double>>> mg_smoother; \n\n    using SmootherType = \n      RelaxationBlock<SparseMatrix<double>, double, Vector<double>>; \n    using SmootherAdditionalDataType = SmootherType::AdditionalData; \n    MGLevelObject<SmootherAdditionalDataType> smoother_data; \n\n    MGConstrainedDoFs mg_constrained_dofs; \n\n    Tensor<1, dim> advection_direction; \n\n    const Settings settings; \n  }; \n\n  template <int dim> \n  AdvectionProblem<dim>::AdvectionProblem(const Settings &settings) \n    : triangulation(Triangulation<dim>::limit_level_difference_at_vertices) \n    , dof_handler(triangulation) \n    , fe(settings.fe_degree) \n    , mapping(settings.fe_degree) \n    , settings(settings) \n  { \n    advection_direction[0] = -std::sin(numbers::PI / 6.0); \n    if (dim >= 2) \n      advection_direction[1] = std::cos(numbers::PI / 6.0); \n    if (dim >= 3) \n      AssertThrow(false, ExcNotImplemented()); \n  } \n// @sect4{<code>AdvectionProblem::setup_system()</code>}  \n\n// \u5728\u8fd9\u91cc\uff0c\u6211\u4eec\u9996\u5148\u4e3a\u6d3b\u52a8\u548c\u591a\u7f51\u683c\u7ea7\u522b\u7684\u7f51\u683c\u8bbe\u7f6eDoFHandler\u3001AffineConstraints\u548cSparsityPattern\u5bf9\u8c61\u3002\n\n// \u6211\u4eec\u53ef\u4ee5\u7528DoFRenumbering\u7c7b\u5bf9\u6d3b\u52a8DoF\u8fdb\u884c\u91cd\u65b0\u7f16\u53f7\uff0c\u4f46\u662f\u5e73\u6ed1\u5668\u53ea\u4f5c\u7528\u4e8e\u591a\u7f51\u683c\u5c42\uff0c\u56e0\u6b64\uff0c\u8fd9\u5bf9\u8ba1\u7b97\u5e76\u4e0d\u91cd\u8981\u3002\u76f8\u53cd\uff0c\u6211\u4eec\u5c06\u5bf9\u6bcf\u4e2a\u591a\u7f51\u683c\u5c42\u7684DoFs\u8fdb\u884c\u91cd\u65b0\u7f16\u53f7\u3002\n\n  template <int dim> \n  void AdvectionProblem<dim>::setup_system() \n  { \n    const unsigned int n_levels = triangulation.n_levels(); \n\n    dof_handler.distribute_dofs(fe); \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, constraints); \n\n    VectorTools::interpolate_boundary_values( \n      mapping, dof_handler, 0, BoundaryValues<dim>(), constraints); \n    VectorTools::interpolate_boundary_values( \n      mapping, dof_handler, 1, BoundaryValues<dim>(), constraints); \n    constraints.close(); \n\n    DynamicSparsityPattern dsp(dof_handler.n_dofs()); \n    DoFTools::make_sparsity_pattern(dof_handler, \n                                    dsp, \n                                    constraints, \n                                    /*keep_constrained_dofs =  */ false);\n\n    sparsity_pattern.copy_from(dsp); \n    system_matrix.reinit(sparsity_pattern); \n\n    dof_handler.distribute_mg_dofs(); \n\n// \u5728\u5217\u4e3e\u4e86\u5168\u5c40\u81ea\u7531\u5ea6\u4ee5\u53ca\uff08\u4e0a\u9762\u6700\u540e\u4e00\u884c\uff09\u6c34\u5e73\u81ea\u7531\u5ea6\u4e4b\u540e\uff0c\u8ba9\u6211\u4eec\u5bf9\u6c34\u5e73\u81ea\u7531\u5ea6\u8fdb\u884c\u91cd\u65b0\u7f16\u53f7\uff0c\u4ee5\u83b7\u5f97\u4e00\u4e2a\u66f4\u597d\u7684\u5e73\u6ed1\u5668\uff0c\u6b63\u5982\u4ecb\u7ecd\u4e2d\u6240\u89e3\u91ca\u7684\u3002 \u5982\u679c\u9700\u8981\u7684\u8bdd\uff0c\u4e0b\u9762\u7684\u7b2c\u4e00\u4e2a\u533a\u5757\u4f1a\u5bf9\u4e0b\u6e38\u6216\u4e0a\u6e38\u65b9\u5411\u7684\u6bcf\u4e2a\u5c42\u6b21\u7684\u81ea\u7531\u5ea6\u8fdb\u884c\u91cd\u65b0\u7f16\u53f7\u3002\u8fd9\u53ea\u5bf9\u70b9\u5e73\u6ed1\u5668\uff08SOR\u548cJacobi\uff09\u6709\u5fc5\u8981\uff0c\u56e0\u4e3a\u5757\u5e73\u6ed1\u5668\u662f\u5728\u5355\u5143\u4e0a\u64cd\u4f5c\u7684\uff08\u89c1`create_smoother()`\uff09\u3002\u7136\u540e\uff0c\u4e0b\u9762\u7684\u5757\u4e5f\u5b9e\u73b0\u4e86\u968f\u673a\u7f16\u53f7\u3002\n\n    if (settings.smoother_type == \"SOR\" || settings.smoother_type == \"Jacobi\") \n      { \n        if (settings.dof_renumbering == \n              Settings::DoFRenumberingStrategy::downstream || \n            settings.dof_renumbering == \n              Settings::DoFRenumberingStrategy::upstream) \n          { \n            const Tensor<1, dim> direction = \n              (settings.dof_renumbering == \n                   Settings::DoFRenumberingStrategy::upstream ? \n                 -1.0 : \n                 1.0) * \n              advection_direction; \n\n            for (unsigned int level = 0; level < n_levels; ++level) \n              DoFRenumbering::downstream(dof_handler, \n                                         level, \n                                         direction, \n                                         /*dof_wise_renumbering =  */ true);\n\n          } \n        else if (settings.dof_renumbering == \n                 Settings::DoFRenumberingStrategy::random) \n          { \n            for (unsigned int level = 0; level < n_levels; ++level) \n              DoFRenumbering::random(dof_handler, level); \n          } \n        else \n          Assert(false, ExcNotImplemented()); \n      } \n\n// \u8be5\u51fd\u6570\u7684\u5176\u4f59\u90e8\u5206\u53ea\u662f\u8bbe\u7f6e\u4e86\u6570\u636e\u7ed3\u6784\u3002\u4e0b\u9762\u4ee3\u7801\u7684\u6700\u540e\u51e0\u884c\u4e0e\u5176\u4ed6GMG\u6559\u7a0b\u4e0d\u540c\uff0c\u56e0\u4e3a\u5b83\u540c\u65f6\u8bbe\u7f6e\u4e86\u63a5\u53e3\u8f93\u5165\u548c\u8f93\u51fa\u77e9\u9635\u3002\u6211\u4eec\u9700\u8981\u8fd9\u6837\u505a\uff0c\u56e0\u4e3a\u6211\u4eec\u7684\u95ee\u9898\u662f\u975e\u5bf9\u79f0\u6027\u7684\u3002\n\n    mg_constrained_dofs.clear(); \n    mg_constrained_dofs.initialize(dof_handler); \n\n    mg_constrained_dofs.make_zero_boundary_constraints(dof_handler, {0, 1}); \n\n    mg_matrices.resize(0, n_levels - 1); \n    mg_matrices.clear_elements(); \n    mg_interface_in.resize(0, n_levels - 1); \n    mg_interface_in.clear_elements(); \n    mg_interface_out.resize(0, n_levels - 1); \n    mg_interface_out.clear_elements(); \n    mg_sparsity_patterns.resize(0, n_levels - 1); \n    mg_interface_sparsity_patterns.resize(0, n_levels - 1); \n\n    for (unsigned int level = 0; level < n_levels; ++level) \n      { \n        { \n          DynamicSparsityPattern dsp(dof_handler.n_dofs(level), \n                                     dof_handler.n_dofs(level)); \n          MGTools::make_sparsity_pattern(dof_handler, dsp, level); \n          mg_sparsity_patterns[level].copy_from(dsp); \n          mg_matrices[level].reinit(mg_sparsity_patterns[level]); \n        } \n        { \n          DynamicSparsityPattern dsp(dof_handler.n_dofs(level), \n                                     dof_handler.n_dofs(level)); \n          MGTools::make_interface_sparsity_pattern(dof_handler, \n                                                   mg_constrained_dofs, \n                                                   dsp, \n                                                   level); \n          mg_interface_sparsity_patterns[level].copy_from(dsp); \n\n          mg_interface_in[level].reinit(mg_interface_sparsity_patterns[level]); \n          mg_interface_out[level].reinit(mg_interface_sparsity_patterns[level]); \n        } \n      } \n  } \n// @sect4{<code>AdvectionProblem::assemble_cell()</code>}  \n\n// \u8fd9\u91cc\u6211\u4eec\u5b9a\u4e49\u4e86\u6bcf\u4e2a\u5355\u5143\u4e0a\u7684\u7ebf\u6027\u7cfb\u7edf\u7684\u88c5\u914d\uff0c\u4ee5\u4fbf\u88ab\u4e0b\u9762\u7684Mesh_loop()\u51fd\u6570\u4f7f\u7528\u3002\u8fd9\u4e2a\u51fd\u6570\u4e3a\u6d3b\u52a8\u5355\u5143\u6216\u6c34\u5e73\u5355\u5143\uff08\u4e0d\u7ba1\u5b83\u7684\u7b2c\u4e00\u4e2a\u53c2\u6570\u662f\u4ec0\u4e48\uff09\u88c5\u914d\u5355\u5143\u77e9\u9635\uff0c\u5e76\u4e14\u53ea\u6709\u5728\u8c03\u7528\u6d3b\u52a8\u5355\u5143\u65f6\u624d\u88c5\u914d\u53f3\u624b\u8fb9\u3002\n\n  template <int dim> \n  template <class IteratorType> \n  void AdvectionProblem<dim>::assemble_cell(const IteratorType &cell, \n                                            ScratchData<dim> &  scratch_data, \n                                            CopyData &          copy_data) \n  { \n    copy_data.level = cell->level(); \n\n    const unsigned int dofs_per_cell = \n      scratch_data.fe_values.get_fe().n_dofs_per_cell(); \n    copy_data.dofs_per_cell = dofs_per_cell; \n    copy_data.cell_matrix.reinit(dofs_per_cell, dofs_per_cell); \n\n    const unsigned int n_q_points = \n      scratch_data.fe_values.get_quadrature().size(); \n\n    if (cell->is_level_cell() == false) \n      copy_data.cell_rhs.reinit(dofs_per_cell); \n\n    copy_data.local_dof_indices.resize(dofs_per_cell); \n    cell->get_active_or_mg_dof_indices(copy_data.local_dof_indices); \n\n    scratch_data.fe_values.reinit(cell); \n\n    RightHandSide<dim>  right_hand_side; \n    std::vector<double> rhs_values(n_q_points); \n\n    right_hand_side.value_list(scratch_data.fe_values.get_quadrature_points(), \n                               rhs_values); \n\n// \u5982\u679c\u6211\u4eec\u4f7f\u7528\u6d41\u7ebf\u6269\u6563\uff0c\u6211\u4eec\u5fc5\u987b\u628a\u5b83\u7684\u8d21\u732e\u52a0\u5230\u5355\u5143\u683c\u77e9\u9635\u548c\u5355\u5143\u683c\u7684\u53f3\u624b\u8fb9\u3002\u5982\u679c\u6211\u4eec\u4e0d\u4f7f\u7528\u6d41\u7ebf\u6269\u6563\uff0c\u8bbe\u7f6e $\\delta=0$ \u5c31\u53ef\u4ee5\u5426\u5b9a\u8fd9\u4e2a\u8d21\u732e\uff0c\u6211\u4eec\u5c31\u53ef\u4ee5\u4f7f\u7528\u6807\u51c6\u7684Galerkin\u6709\u9650\u5143\u7ec4\u5408\u3002\n\n    const double delta = (settings.with_streamline_diffusion ? \n                            compute_stabilization_delta(cell->diameter(), \n                                                        settings.epsilon, \n                                                        advection_direction, \n                                                        settings.fe_degree) : \n                            0.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            { \n\n// \u672c\u5730\u77e9\u9635\u7684\u7ec4\u88c5\u6709\u4e24\u4e2a\u90e8\u5206\u3002\u9996\u5148\u662fGalerkin\u8d21\u732e\u3002\n\n              copy_data.cell_matrix(i, j) += \n                (settings.epsilon * \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                (scratch_data.fe_values.shape_value(i, q_point) * \n                 (advection_direction * \n                  scratch_data.fe_values.shape_grad(j, q_point)) * \n                 scratch_data.fe_values.JxW(q_point)) \n\n//\u7136\u540e\u662f\u6d41\u7ebf\u6269\u6563\u8d21\u732e\u3002\n\n                + delta * \n                    (advection_direction * \n                     scratch_data.fe_values.shape_grad(j, q_point)) * \n                    (advection_direction * \n                     scratch_data.fe_values.shape_grad(i, q_point)) * \n                    scratch_data.fe_values.JxW(q_point) - \n                delta * settings.epsilon * \n                  trace(scratch_data.fe_values.shape_hessian(j, q_point)) * \n                  (advection_direction * \n                   scratch_data.fe_values.shape_grad(i, q_point)) * \n                  scratch_data.fe_values.JxW(q_point); \n            } \n          if (cell->is_level_cell() == false) \n            { \n\n// \u540c\u6837\u7684\u60c5\u51b5\u4e5f\u9002\u7528\u4e8e\u53f3\u624b\u8fb9\u3002\u9996\u5148\u662fGalerkin\u8d21\u732e\u3002\n\n              copy_data.cell_rhs(i) += \n                scratch_data.fe_values.shape_value(i, q_point) * \n                  rhs_values[q_point] * scratch_data.fe_values.JxW(q_point) \n\n// \u7136\u540e\u662f\u6d41\u7ebf\u6269\u6563\u8d21\u732e\u3002\n\n                + delta * rhs_values[q_point] * advection_direction * \n                    scratch_data.fe_values.shape_grad(i, q_point) * \n                    scratch_data.fe_values.JxW(q_point); \n            } \n        } \n  } \n// @sect4{<code>AdvectionProblem::assemble_system_and_multigrid()</code>}  \n\n// \u8fd9\u91cc\u6211\u4eec\u91c7\u7528 MeshWorker::mesh_loop() \u6765\u7ffb\u9605\u5355\u5143\u683c\uff0c\u4e3a\u6211\u4eec\u7ec4\u88c5system_matrix\u3001system_rhs\u548c\u6240\u6709mg_matrices\u3002\n\n  template <int dim> \n  void AdvectionProblem<dim>::assemble_system_and_multigrid() \n  { \n    const auto cell_worker_active = \n      [&](const decltype(dof_handler.begin_active()) &cell, \n          ScratchData<dim> &                          scratch_data, \n          CopyData &                                  copy_data) { \n        this->assemble_cell(cell, scratch_data, copy_data); \n      }; \n\n    const auto copier_active = [&](const CopyData &copy_data) { \n      constraints.distribute_local_to_global(copy_data.cell_matrix, \n                                             copy_data.cell_rhs, \n                                             copy_data.local_dof_indices, \n                                             system_matrix, \n                                             system_rhs); \n    }; \n\n    MeshWorker::mesh_loop(dof_handler.begin_active(), \n                          dof_handler.end(), \n                          cell_worker_active, \n                          copier_active, \n                          ScratchData<dim>(fe, fe.degree + 1), \n                          CopyData(), \n                          MeshWorker::assemble_own_cells); \n\n// \u4e0e\u6d3b\u52a8\u5c42\u7684\u7ea6\u675f\u4e0d\u540c\uff0c\u6211\u4eec\u9009\u62e9\u5728\u8fd9\u4e2a\u51fd\u6570\u7684\u672c\u5730\u4e3a\u6bcf\u4e2a\u591a\u7f51\u683c\u5c42\u521b\u5efa\u7ea6\u675f\u5bf9\u8c61\uff0c\u56e0\u4e3a\u5b83\u4eec\u5728\u7a0b\u5e8f\u7684\u5176\u4ed6\u5730\u65b9\u4ece\u6765\u4e0d\u9700\u8981\u3002\n\n    std::vector<AffineConstraints<double>> boundary_constraints( \n      triangulation.n_global_levels()); \n    for (unsigned int level = 0; level < triangulation.n_global_levels(); \n         ++level) \n      { \n        IndexSet locally_owned_level_dof_indices; \n        DoFTools::extract_locally_relevant_level_dofs( \n          dof_handler, level, locally_owned_level_dof_indices); \n        boundary_constraints[level].reinit(locally_owned_level_dof_indices); \n        boundary_constraints[level].add_lines( \n          mg_constrained_dofs.get_refinement_edge_indices(level)); \n        boundary_constraints[level].add_lines( \n          mg_constrained_dofs.get_boundary_indices(level)); \n        boundary_constraints[level].close(); \n      } \n\n    const auto cell_worker_mg = \n      [&](const decltype(dof_handler.begin_mg()) &cell, \n          ScratchData<dim> &                      scratch_data, \n          CopyData &                              copy_data) { \n        this->assemble_cell(cell, scratch_data, copy_data); \n      }; \n\n    const auto copier_mg = [&](const CopyData &copy_data) { \n      boundary_constraints[copy_data.level].distribute_local_to_global( \n        copy_data.cell_matrix, \n        copy_data.local_dof_indices, \n        mg_matrices[copy_data.level]); \n\n// \u5982\u679c $(i,j)$ \u662f\u4e00\u4e2a`interface_out` dof\u5bf9\uff0c\u90a3\u4e48 $(j,i)$ \u5c31\u662f\u4e00\u4e2a`interface_in` dof\u5bf9\u3002\u6ce8\u610f\uff1a\u5bf9\u4e8e \"interface_in\"\uff0c\u6211\u4eec\u52a0\u8f7d\u63a5\u53e3\u6761\u76ee\u7684\u8f6c\u7f6e\uff0c\u5373\uff0cdof\u5bf9 $(j,i)$ \u7684\u6761\u76ee\u88ab\u5b58\u50a8\u5728 \"interface_in(i,j)\"\u3002\u8fd9\u662f\u5bf9\u5bf9\u79f0\u60c5\u51b5\u7684\u4f18\u5316\uff0c\u5141\u8bb8\u5728solve()\u4e2d\u8bbe\u7f6e\u8fb9\u7f18\u77e9\u9635\u65f6\u53ea\u4f7f\u7528\u4e00\u4e2a\u77e9\u9635\u3002\u7136\u800c\uff0c\u5728\u8fd9\u91cc\uff0c\u7531\u4e8e\u6211\u4eec\u7684\u95ee\u9898\u662f\u975e\u5bf9\u79f0\u7684\uff0c\u6211\u4eec\u5fc5\u987b\u540c\u65f6\u5b58\u50a8`interface_in`\u548c`interface_out`\u77e9\u9635\u3002\n\n      for (unsigned int i = 0; i < copy_data.dofs_per_cell; ++i) \n        for (unsigned int j = 0; j < copy_data.dofs_per_cell; ++j) \n          if (mg_constrained_dofs.is_interface_matrix_entry( \n                copy_data.level, \n                copy_data.local_dof_indices[i], \n                copy_data.local_dof_indices[j])) \n            { \n              mg_interface_out[copy_data.level].add( \n                copy_data.local_dof_indices[i], \n                copy_data.local_dof_indices[j], \n                copy_data.cell_matrix(i, j)); \n              mg_interface_in[copy_data.level].add( \n                copy_data.local_dof_indices[i], \n                copy_data.local_dof_indices[j], \n                copy_data.cell_matrix(j, i)); \n            } \n    }; \n\n    MeshWorker::mesh_loop(dof_handler.begin_mg(), \n                          dof_handler.end_mg(), \n                          cell_worker_mg, \n                          copier_mg, \n                          ScratchData<dim>(fe, fe.degree + 1), \n                          CopyData(), \n                          MeshWorker::assemble_own_cells); \n  } \n// @sect4{<code>AdvectionProblem::setup_smoother()</code>}  \n\n// \u63a5\u4e0b\u6765\uff0c\u6211\u4eec\u6839\u636e`.prm`\u6587\u4ef6\u4e2d\u7684\u8bbe\u7f6e\u6765\u8bbe\u7f6e\u5e73\u6ed1\u5668\u3002\u4e24\u4e2a\u91cd\u8981\u7684\u9009\u9879\u662f\u591a\u7f51\u683cv\u5468\u671f\u6bcf\u4e00\u7ea7\u7684\u5e73\u6ed1\u524d\u548c\u5e73\u6ed1\u540e\u6b65\u9aa4\u7684\u6570\u91cf\u4ee5\u53ca\u677e\u5f1b\u53c2\u6570\u3002\n\n// \u7531\u4e8e\u4e58\u6cd5\u5f80\u5f80\u6bd4\u52a0\u6cd5\u66f4\u5f3a\u5927\uff0c\u6240\u4ee5\u9700\u8981\u8f83\u5c11\u7684\u5e73\u6ed1\u6b65\u9aa4\u6765\u5b9e\u73b0\u6536\u655b\uff0c\u4e0e\u7f51\u683c\u5927\u5c0f\u65e0\u5173\u3002\u5757\u5e73\u6ed1\u5668\u6bd4\u70b9\u5e73\u6ed1\u5668\u4e5f\u662f\u5982\u6b64\u3002\u8fd9\u53cd\u6620\u5728\u4e0b\u9762\u5bf9\u6bcf\u79cd\u5e73\u6ed1\u5668\u7684\u5e73\u6ed1\u6b65\u6570\u7684\u9009\u62e9\u4e0a\u3002\n\n// \u70b9\u5e73\u6ed1\u5668\u7684\u677e\u5f1b\u53c2\u6570\u662f\u5728\u8bd5\u9a8c\u548c\u9519\u8bef\u7684\u57fa\u7840\u4e0a\u9009\u62e9\u7684\uff0c\u5b83\u53cd\u6620\u4e86\u5728\u6211\u4eec\u7ec6\u5316\u7f51\u683c\u65f6\u4fdd\u6301GMRES\u6c42\u89e3\u7684\u8fed\u4ee3\u6b21\u6570\u4e0d\u53d8\uff08\u6216\u5c3d\u53ef\u80fd\u63a5\u8fd1\uff09\u7684\u5fc5\u8981\u503c\u3002\u5728`.prm`\u6587\u4ef6\u4e2d\u7ed9 \"Jacobi \"\u548c \"SOR \"\u7684\u4e24\u4e2a\u503c\u662f\u9488\u5bf91\u5ea6\u548c3\u5ea6\u6709\u9650\u5143\u7684\u3002\u5982\u679c\u7528\u6237\u60f3\u6539\u6210\u5176\u4ed6\u5ea6\u6570\uff0c\u4ed6\u4eec\u53ef\u80fd\u9700\u8981\u8c03\u6574\u8fd9\u4e9b\u6570\u5b57\u3002\u5bf9\u4e8e\u5757\u5e73\u6ed1\u5668\uff0c\u8fd9\u4e2a\u53c2\u6570\u6709\u4e00\u4e2a\u66f4\u76f4\u63a5\u7684\u89e3\u91ca\uff0c\u5373\u5bf9\u4e8e\u4e8c\u7ef4\u7684\u52a0\u6cd5\uff0c\u4e00\u4e2aDoF\u53ef\u4ee5\u6709\u591a\u8fbe4\u4e2a\u5355\u5143\u7684\u91cd\u590d\u8d21\u732e\uff0c\u56e0\u6b64\u6211\u4eec\u5fc5\u987b\u5c06\u8fd9\u4e9b\u65b9\u6cd5\u653e\u677e0.25\u6765\u8865\u507f\u3002\u5bf9\u4e8e\u4e58\u6cd5\u6765\u8bf4\uff0c\u8fd9\u4e0d\u662f\u4e00\u4e2a\u95ee\u9898\uff0c\u56e0\u4e3a\u6bcf\u4e2a\u5355\u5143\u7684\u9006\u5411\u5e94\u7528\u90fd\u4f1a\u7ed9\u5176\u6240\u6709\u7684DoF\u5e26\u6765\u65b0\u7684\u4fe1\u606f\u3002\n\n// \u6700\u540e\uff0c\u5982\u4e0a\u6240\u8ff0\uff0c\u70b9\u5e73\u6ed1\u5668\u53ea\u5bf9DoF\u8fdb\u884c\u64cd\u4f5c\uff0c\u800c\u5757\u5e73\u6ed1\u5668\u5bf9\u5355\u5143\u8fdb\u884c\u64cd\u4f5c\uff0c\u56e0\u6b64\u53ea\u6709\u5757\u5e73\u6ed1\u5668\u9700\u8981\u88ab\u8d4b\u4e88\u6709\u5173\u5355\u5143\u6392\u5e8f\u7684\u4fe1\u606f\u3002\u70b9\u5e73\u6ed1\u5668\u7684DoF\u6392\u5e8f\u5df2\u7ecf\u5728`setup_system()`\u4e2d\u5f97\u5230\u4e86\u5904\u7406\u3002\n\n  template <int dim> \n  void AdvectionProblem<dim>::setup_smoother() \n  { \n    if (settings.smoother_type == \"SOR\") \n      { \n        using Smoother = PreconditionSOR<SparseMatrix<double>>; \n\n        auto smoother = \n          std::make_unique<MGSmootherPrecondition<SparseMatrix<double>, \n                                                  Smoother, \n                                                  Vector<double>>>(); \n        smoother->initialize(mg_matrices, \n                             Smoother::AdditionalData(fe.degree == 1 ? 1.0 : \n                                                                       0.62)); \n        smoother->set_steps(settings.smoothing_steps); \n        mg_smoother = std::move(smoother); \n      } \n    else if (settings.smoother_type == \"Jacobi\") \n      { \n        using Smoother = PreconditionJacobi<SparseMatrix<double>>; \n        auto smoother = \n          std::make_unique<MGSmootherPrecondition<SparseMatrix<double>, \n                                                  Smoother, \n                                                  Vector<double>>>(); \n        smoother->initialize(mg_matrices, \n                             Smoother::AdditionalData(fe.degree == 1 ? 0.6667 : \n                                                                       0.47)); \n        smoother->set_steps(settings.smoothing_steps); \n        mg_smoother = std::move(smoother); \n      } \n    else if (settings.smoother_type == \"block SOR\" || \n             settings.smoother_type == \"block Jacobi\") \n      { \n        smoother_data.resize(0, triangulation.n_levels() - 1); \n\n        for (unsigned int level = 0; level < triangulation.n_levels(); ++level) \n          { \n            DoFTools::make_cell_patches(smoother_data[level].block_list, \n                                        dof_handler, \n                                        level); \n\n            smoother_data[level].relaxation = \n              (settings.smoother_type == \"block SOR\" ? 1.0 : 0.25); \n            smoother_data[level].inversion = PreconditionBlockBase<double>::svd; \n\n            std::vector<unsigned int> ordered_indices; \n            switch (settings.dof_renumbering) \n              { \n                case Settings::DoFRenumberingStrategy::downstream: \n                  ordered_indices = \n                    create_downstream_cell_ordering(dof_handler, \n                                                    advection_direction, \n                                                    level); \n                  break; \n\n                case Settings::DoFRenumberingStrategy::upstream: \n                  ordered_indices = \n                    create_downstream_cell_ordering(dof_handler, \n                                                    -1.0 * advection_direction, \n                                                    level); \n                  break; \n\n                case Settings::DoFRenumberingStrategy::random: \n                  ordered_indices = \n                    create_random_cell_ordering(dof_handler, level); \n                  break; \n\n                case Settings::DoFRenumberingStrategy::none: \n                  break; \n\n                default: \n                  AssertThrow(false, ExcNotImplemented()); \n                  break; \n              } \n\n            smoother_data[level].order = \n              std::vector<std::vector<unsigned int>>(1, ordered_indices); \n          } \n\n        if (settings.smoother_type == \"block SOR\") \n          { \n            auto smoother = std::make_unique<MGSmootherPrecondition< \n              SparseMatrix<double>, \n              RelaxationBlockSOR<SparseMatrix<double>, double, Vector<double>>, \n              Vector<double>>>(); \n            smoother->initialize(mg_matrices, smoother_data); \n            smoother->set_steps(settings.smoothing_steps); \n            mg_smoother = std::move(smoother); \n          } \n        else if (settings.smoother_type == \"block Jacobi\") \n          { \n            auto smoother = std::make_unique< \n              MGSmootherPrecondition<SparseMatrix<double>, \n                                     RelaxationBlockJacobi<SparseMatrix<double>, \n                                                           double, \n                                                           Vector<double>>, \n                                     Vector<double>>>(); \n            smoother->initialize(mg_matrices, smoother_data); \n            smoother->set_steps(settings.smoothing_steps); \n            mg_smoother = std::move(smoother); \n          } \n      } \n    else \n      AssertThrow(false, ExcNotImplemented()); \n  } \n// @sect4{<code>AdvectionProblem::solve()</code>}  \n\n// \u5728\u89e3\u51b3\u8fd9\u4e2a\u7cfb\u7edf\u4e4b\u524d\uff0c\u6211\u4eec\u5fc5\u987b\u9996\u5148\u8bbe\u7f6e\u591a\u7f51\u683c\u9884\u5904\u7406\u7a0b\u5e8f\u3002\u8fd9\u9700\u8981\u8bbe\u7f6e\u5404\u7ea7\u4e4b\u95f4\u7684\u8f6c\u6362\u3001\u7c97\u7565\u77e9\u9635\u6c42\u89e3\u5668\u548c\u5e73\u6ed1\u5668\u3002\u8fd9\u4e2a\u8bbe\u7f6e\u51e0\u4e4e\u4e0e Step-16 \u76f8\u540c\uff0c\u4e3b\u8981\u533a\u522b\u5728\u4e8e\u4e0a\u9762\u5b9a\u4e49\u7684\u5404\u79cd\u5e73\u6ed1\u5668\uff0c\u4ee5\u53ca\u7531\u4e8e\u6211\u4eec\u7684\u95ee\u9898\u662f\u975e\u5bf9\u79f0\u7684\uff0c\u6211\u4eec\u9700\u8981\u4e0d\u540c\u7684\u754c\u9762\u8fb9\u7f18\u77e9\u9635\u3002\u5b9e\u9645\u4e0a\uff0c\u5728\u672c\u6559\u7a0b\u4e2d\uff0c\u8fd9\u4e9b\u63a5\u53e3\u77e9\u9635\u662f\u7a7a\u7684\uff0c\u56e0\u4e3a\u6211\u4eec\u53ea\u4f7f\u7528\u5168\u5c40\u7ec6\u5316\uff0c\u56e0\u6b64\u6ca1\u6709\u7ec6\u5316\u8fb9\u3002\u7136\u800c\uff0c\u6211\u4eec\u5728\u8fd9\u91cc\u4ecd\u7136\u5305\u62ec\u4e86\u8fd9\u4e24\u4e2a\u77e9\u9635\uff0c\u56e0\u4e3a\u5982\u679c\u6211\u4eec\u7b80\u5355\u5730\u5207\u6362\u5230\u81ea\u9002\u5e94\u7ec6\u5316\u65b9\u6cd5\uff0c\u7a0b\u5e8f\u4ecd\u7136\u53ef\u4ee5\u6b63\u5e38\u8fd0\u884c\uff09\u3002)\n\n// \u6700\u540e\u8981\u6ce8\u610f\u7684\u662f\uff0c\u7531\u4e8e\u6211\u4eec\u7684\u95ee\u9898\u662f\u975e\u5bf9\u79f0\u7684\uff0c\u6211\u4eec\u5fc5\u987b\u4f7f\u7528\u9002\u5f53\u7684Krylov\u5b50\u7a7a\u95f4\u65b9\u6cd5\u3002\u6211\u4eec\u5728\u8fd9\u91cc\u9009\u62e9\u4f7f\u7528GMRES\uff0c\u56e0\u4e3a\u5b83\u80fd\u4fdd\u8bc1\u5728\u6bcf\u6b21\u8fed\u4ee3\u4e2d\u51cf\u5c11\u6b8b\u5dee\u3002GMRES\u7684\u4e3b\u8981\u7f3a\u70b9\u662f\uff0c\u6bcf\u6b21\u8fed\u4ee3\uff0c\u5b58\u50a8\u7684\u4e34\u65f6\u5411\u91cf\u7684\u6570\u91cf\u90fd\u4f1a\u589e\u52a0\u4e00\u4e2a\uff0c\u800c\u4e14\u8fd8\u9700\u8981\u8ba1\u7b97\u4e0e\u4e4b\u524d\u5b58\u50a8\u7684\u6240\u6709\u5411\u91cf\u7684\u6807\u91cf\u79ef\u3002\u8fd9\u662f\u5f88\u6602\u8d35\u7684\u3002\u901a\u8fc7\u4f7f\u7528\u91cd\u542f\u7684GMRES\u65b9\u6cd5\u53ef\u4ee5\u653e\u677e\u8fd9\u4e00\u8981\u6c42\uff0c\u8be5\u65b9\u6cd5\u5bf9\u6211\u4eec\u5728\u4efb\u4f55\u65f6\u5019\u9700\u8981\u5b58\u50a8\u7684\u5411\u91cf\u6570\u91cf\u8bbe\u7f6e\u4e86\u4e0a\u9650\uff08\u8fd9\u91cc\u6211\u4eec\u572850\u4e2a\u4e34\u65f6\u5411\u91cf\u540e\u91cd\u542f\uff0c\u537348\u6b21\u8fed\u4ee3\uff09\u3002\u8fd9\u6837\u505a\u7684\u7f3a\u70b9\u662f\u6211\u4eec\u5931\u53bb\u4e86\u5728\u6574\u4e2a\u8fed\u4ee3\u8fc7\u7a0b\u4e2d\u6536\u96c6\u7684\u4fe1\u606f\uff0c\u56e0\u6b64\u6211\u4eec\u53ef\u4ee5\u770b\u5230\u6536\u655b\u901f\u5ea6\u8f83\u6162\u3002\u56e0\u6b64\uff0c\u5728\u54ea\u91cc\u91cd\u542f\u662f\u4e00\u4e2a\u5e73\u8861\u5185\u5b58\u6d88\u8017\u3001CPU\u5de5\u4f5c\u91cf\u548c\u6536\u655b\u901f\u5ea6\u7684\u95ee\u9898\u3002\u7136\u800c\uff0c\u672c\u6559\u7a0b\u7684\u76ee\u6807\u662f\u901a\u8fc7\u4f7f\u7528\u5f3a\u5927\u7684GMG\u9884\u5904\u7406\u7a0b\u5e8f\u6765\u5b9e\u73b0\u975e\u5e38\u4f4e\u7684\u8fed\u4ee3\u6b21\u6570\uff0c\u6240\u4ee5\u6211\u4eec\u9009\u62e9\u4e86\u91cd\u542f\u957f\u5ea6\uff0c\u4f7f\u4e0b\u9762\u663e\u793a\u7684\u6240\u6709\u7ed3\u679c\u5728\u91cd\u542f\u53d1\u751f\u4e4b\u524d\u5c31\u80fd\u6536\u655b\uff0c\u56e0\u6b64\u6211\u4eec\u6709\u4e00\u4e2a\u6807\u51c6\u7684GMRES\u65b9\u6cd5\u3002\u5982\u679c\u7528\u6237\u6709\u5174\u8da3\uff0cdeal.II\u4e2d\u63d0\u4f9b\u7684\u53e6\u4e00\u79cd\u5408\u9002\u7684\u65b9\u6cd5\u662fBiCGStab\u3002\n\n  template <int dim> \n  void AdvectionProblem<dim>::solve() \n  { \n    const unsigned int max_iters       = 200; \n    const double       solve_tolerance = 1e-8 * system_rhs.l2_norm(); \n    SolverControl      solver_control(max_iters, solve_tolerance, true, true); \n    solver_control.enable_history_data(); \n\n    using Transfer = MGTransferPrebuilt<Vector<double>>; \n    Transfer mg_transfer(mg_constrained_dofs); \n    mg_transfer.build(dof_handler); \n\n    FullMatrix<double> coarse_matrix; \n    coarse_matrix.copy_from(mg_matrices[0]); \n    MGCoarseGridHouseholder<double, Vector<double>> coarse_grid_solver; \n    coarse_grid_solver.initialize(coarse_matrix); \n\n    setup_smoother(); \n\n    mg_matrix.initialize(mg_matrices); \n    mg_interface_matrix_in.initialize(mg_interface_in); \n    mg_interface_matrix_out.initialize(mg_interface_out); \n\n    Multigrid<Vector<double>> mg( \n      mg_matrix, coarse_grid_solver, mg_transfer, *mg_smoother, *mg_smoother); \n    mg.set_edge_matrices(mg_interface_matrix_out, mg_interface_matrix_in); \n\n    PreconditionMG<dim, Vector<double>, Transfer> preconditioner(dof_handler, \n                                                                 mg, \n                                                                 mg_transfer); \n\n    std::cout << \"     Solving with GMRES to tol \" << solve_tolerance << \"...\" \n              << std::endl; \n    SolverGMRES<Vector<double>> solver( \n      solver_control, SolverGMRES<Vector<double>>::AdditionalData(50, true)); \n\n    Timer time; \n    time.start(); \n    solver.solve(system_matrix, solution, system_rhs, preconditioner); \n    time.stop(); \n\n    std::cout << \"          converged in \" << solver_control.last_step() \n              << \" iterations\" \n              << \" in \" << time.last_wall_time() << \" seconds \" << std::endl; \n\n    constraints.distribute(solution); \n\n    mg_smoother.release(); \n  } \n// @sect4{<code>AdvectionProblem::output_results()</code>}  \n\n// \u6700\u540e\u4e00\u4e2a\u611f\u5174\u8da3\u7684\u51fd\u6570\u4f1a\u751f\u6210\u56fe\u5f62\u8f93\u51fa\u3002\u8fd9\u91cc\u6211\u4eec\u4ee5.vtu\u683c\u5f0f\u8f93\u51fa\u89e3\u51b3\u65b9\u6848\u548c\u5355\u5143\u683c\u6392\u5e8f\u3002\n\n// \u5728\u51fd\u6570\u7684\u9876\u90e8\uff0c\u6211\u4eec\u4e3a\u6bcf\u4e2a\u5355\u5143\u751f\u6210\u4e00\u4e2a\u7d22\u5f15\uff0c\u4ee5\u663e\u793a\u5e73\u6ed1\u5668\u6240\u4f7f\u7528\u7684\u6392\u5e8f\u3002\u8bf7\u6ce8\u610f\uff0c\u6211\u4eec\u53ea\u5bf9\u6d3b\u52a8\u5355\u5143\u800c\u4e0d\u662f\u5e73\u6ed1\u5668\u5b9e\u9645\u4f7f\u7528\u7684\u5c42\u7ea7\u505a\u8fd9\u4e2a\u5904\u7406\u3002\u5bf9\u4e8e\u70b9\u5e73\u6ed1\u5668\uff0c\u6211\u4eec\u5bf9DoFs\u800c\u4e0d\u662f\u5355\u5143\u8fdb\u884c\u91cd\u65b0\u7f16\u53f7\uff0c\u6240\u4ee5\u8fd9\u53ea\u662f\u5bf9\u73b0\u5b9e\u4e2d\u53d1\u751f\u7684\u60c5\u51b5\u7684\u4e00\u79cd\u8fd1\u4f3c\u3002\u6700\u540e\uff0c\u8fd9\u4e2a\u968f\u673a\u6392\u5e8f\u4e0d\u662f\u6211\u4eec\u5b9e\u9645\u4f7f\u7528\u7684\u968f\u673a\u6392\u5e8f\uff08\u89c1`create_smoother()`\uff09\u3002\n\n// \u7136\u540e\uff0c\u5355\u5143\u683c\u7684\uff08\u6574\u6570\uff09\u6392\u5e8f\u88ab\u590d\u5236\u5230\u4e00\u4e2a\uff08\u6d6e\u70b9\uff09\u77e2\u91cf\u4e2d\uff0c\u7528\u4e8e\u56fe\u5f62\u8f93\u51fa\u3002\n\n  template <int dim> \n  void AdvectionProblem<dim>::output_results(const unsigned int cycle) const \n  { \n    const unsigned int n_active_cells = triangulation.n_active_cells(); \n    Vector<double>     cell_indices(n_active_cells); \n    { \n      std::vector<unsigned int> ordered_indices; \n      switch (settings.dof_renumbering) \n        { \n          case Settings::DoFRenumberingStrategy::downstream: \n            ordered_indices = \n              create_downstream_cell_ordering(dof_handler, advection_direction); \n            break; \n\n          case Settings::DoFRenumberingStrategy::upstream: \n            ordered_indices = \n              create_downstream_cell_ordering(dof_handler, \n                                              -1.0 * advection_direction); \n            break; \n\n          case Settings::DoFRenumberingStrategy::random: \n            ordered_indices = create_random_cell_ordering(dof_handler); \n            break; \n\n          case Settings::DoFRenumberingStrategy::none: \n            ordered_indices.resize(n_active_cells); \n            for (unsigned int i = 0; i < n_active_cells; ++i) \n              ordered_indices[i] = i; \n            break; \n\n          default: \n            AssertThrow(false, ExcNotImplemented()); \n            break; \n        } \n\n      for (unsigned int i = 0; i < n_active_cells; ++i) \n        cell_indices(ordered_indices[i]) = static_cast<double>(i); \n    } \n\n// \u8003\u8651\u5230\u4ee5\u524d\u7684\u6559\u7a0b\u7a0b\u5e8f\uff0c\u8be5\u51fd\u6570\u7684\u5176\u4f59\u90e8\u5206\u5c31\u5f88\u7b80\u5355\u4e86\u3002\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.add_data_vector(cell_indices, \"cell_index\"); \n    data_out.build_patches(); \n\n    const std::string filename = \n      \"solution-\" + Utilities::int_to_string(cycle) + \".vtu\"; \n    std::ofstream output(filename.c_str()); \n    data_out.write_vtu(output); \n  } \n// @sect4{<code>AdvectionProblem::run()</code>}  \n\n// \u548c\u5927\u591a\u6570\u6559\u7a0b\u4e00\u6837\uff0c\u8fd9\u4e2a\u51fd\u6570\u521b\u5efa/\u7ec6\u5316\u7f51\u683c\u5e76\u8c03\u7528\u4e0a\u9762\u5b9a\u4e49\u7684\u5404\u79cd\u51fd\u6570\u6765\u8bbe\u7f6e\u3001\u88c5\u914d\u3001\u6c42\u89e3\u548c\u8f93\u51fa\u7ed3\u679c\u3002\n\n// \u5728\u7b2c0\u4e2a\u5faa\u73af\u4e2d\uff0c\u6211\u4eec\u5728\u6b63\u65b9\u5f62 <code>[-1,1]^dim</code> \u4e0a\u751f\u6210\u7f51\u683c\uff0c\u534a\u5f84\u4e3a3/10\u4e2a\u5355\u4f4d\u7684\u5b54\u4ee5\u539f\u70b9\u4e3a\u4e2d\u5fc3\u3002\u5bf9\u4e8e`manifold_id`\u7b49\u4e8e1\u7684\u5bf9\u8c61\uff08\u5373\u4e0e\u6d1e\u76f8\u90bb\u7684\u9762\uff09\uff0c\u6211\u4eec\u6307\u5b9a\u4e86\u4e00\u4e2a\u7403\u5f62\u6d41\u5f62\u3002\n\n  template <int dim> \n  void AdvectionProblem<dim>::run() \n  { \n    for (unsigned int cycle = 0; cycle < (settings.fe_degree == 1 ? 7 : 5); \n         ++cycle) \n      { \n        std::cout << \"  Cycle \" << cycle << ':' << std::endl; \n\n        if (cycle == 0) \n          { \n            GridGenerator::hyper_cube_with_cylindrical_hole(triangulation, \n                                                            0.3, \n                                                            1.0); \n\n            const SphericalManifold<dim> manifold_description(Point<dim>(0, 0)); \n            triangulation.set_manifold(1, manifold_description); \n          } \n\n        triangulation.refine_global(); \n\n        setup_system(); \n\n        std::cout << \"     Number of active cells:       \" \n                  << triangulation.n_active_cells() << \" (\" \n                  << triangulation.n_levels() << \" levels)\" << std::endl; \n        std::cout << \"     Number of degrees of freedom: \" \n                  << dof_handler.n_dofs() << std::endl; \n\n        assemble_system_and_multigrid(); \n\n        solve(); \n\n        if (settings.output) \n          output_results(cycle); \n\n        std::cout << std::endl; \n      } \n  } \n} // namespace Step63 \n// @sect3{The <code>main</code> function}  \n\n// \u6700\u540e\uff0c\u4e3b\u51fd\u6570\u548c\u5927\u591a\u6570\u6559\u7a0b\u4e00\u6837\u3002\u552f\u4e00\u6709\u8da3\u7684\u4e00\u70b9\u662f\uff0c\u6211\u4eec\u8981\u6c42\u7528\u6237\u4f20\u9012\u4e00\u4e2a`.prm`\u6587\u4ef6\u4f5c\u4e3a\u552f\u4e00\u7684\u547d\u4ee4\u884c\u53c2\u6570\u3002\u5982\u679c\u6ca1\u6709\u7ed9\u51fa\u53c2\u6570\u6587\u4ef6\uff0c\u7a0b\u5e8f\u5c06\u5728\u5c4f\u5e55\u4e0a\u8f93\u51fa\u4e00\u4e2a\u5e26\u6709\u6240\u6709\u9ed8\u8ba4\u503c\u7684\u6837\u672c\u53c2\u6570\u6587\u4ef6\u7684\u5185\u5bb9\uff0c\u7136\u540e\u7528\u6237\u53ef\u4ee5\u590d\u5236\u5e76\u7c98\u8d34\u5230\u81ea\u5df1\u7684`.prm`\u6587\u4ef6\u4e2d\u3002\n\nint main(int argc, char *argv[]) \n{ \n  try \n    { \n      Step63::Settings settings; \n      settings.get_parameters((argc > 1) ? (argv[1]) : \"\"); \n\n      Step63::AdvectionProblem<2> advection_problem_2d(settings); \n      advection_problem_2d.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      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": "9816637eb203c0c739a62532fe9396c16c7f2858", "size": 41739, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-63/step-63.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-63/step-63.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-63/step-63.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": 37.6705776173, "max_line_length": 413, "alphanum_fraction": 0.595318527, "num_tokens": 12148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300449389326, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.4889316333613757}}
{"text": "/*\nCopyright 2016 Andrich van Wyk\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\nhttp://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 <Eigen/Core>\n#include <iostream>\n#include <cstdlib>\n\n#include \"domain.h\"\n#include \"particle.h\"\n#include \"pso.h\"\n#include \"pso_functions.h\"\n#include \"random.h\"\n\nusing Eigen::ArrayXd;\nusing cswarm::pso::lbest;\nusing std::cout;\nusing std::endl;\n\ndouble spherical_f(const ArrayXd& solution) {\n  return (solution * solution).sum();\n}\n\nint get_dimension(int argc, char* argv[]) {\n  return argc < 2 ? 1000 : atoi(argv[1]);\n}\n\nint get_swarm_size(int argc, char* argv[]) {\n  return argc < 3 ? 25 : atoi(argv[2]);\n}\n\nint main(int argc, char* argv[]) {\n  auto rng = std::make_shared<Random>(15632435212L);\n  int dimensions = get_dimension(argc, argv);\n  int swarm_size = get_swarm_size(argc, argv);\n  auto d = Domain(-5.0, 5.0, dimensions);\n  auto p = PSOParameters(0.729844, 1.496180, 1.496180, 0.1, 5);\n  auto pso = PSO(swarm_size, d, p, spherical_f, lbest, rng);\n  \n  auto result = pso.optimize(1000);\n  cout << result.getFitness() << endl;\n  return 0;\n}\n", "meta": {"hexsha": "2a73f34f3b0c13e66328d102df40f84902e10b69", "size": 1515, "ext": "cc", "lang": "C++", "max_stars_repo_path": "cc/examples/cc/lbest.cc", "max_stars_repo_name": "avanwyk/pso-platform-benchmarks", "max_stars_repo_head_hexsha": "d91e92c8a2f51d6f884cb4900ccf4697ea725458", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-07-12T13:33:32.000Z", "max_stars_repo_stars_event_max_datetime": "2016-07-12T13:33:32.000Z", "max_issues_repo_path": "cc/examples/cc/lbest.cc", "max_issues_repo_name": "avanwyk/pso-platform-benchmarks", "max_issues_repo_head_hexsha": "d91e92c8a2f51d6f884cb4900ccf4697ea725458", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cc/examples/cc/lbest.cc", "max_forks_repo_name": "avanwyk/pso-platform-benchmarks", "max_forks_repo_head_hexsha": "d91e92c8a2f51d6f884cb4900ccf4697ea725458", "max_forks_repo_licenses": ["Apache-2.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.0535714286, "max_line_length": 72, "alphanum_fraction": 0.7181518152, "num_tokens": 415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426303, "lm_q2_score": 0.63341027751814, "lm_q1q2_score": 0.4888935975182645}}
{"text": "/**\n * \\file\n * \\author Norihiro Watanabe\n * \\author Wenqing Wang\n * \\date   2013-05-15, 2014-02\n * \\brief  Interface tests of global matrix classes\n *\n * \\copyright\n * Copyright (c) 2012-2021, OpenGeoSys Community (http://www.opengeosys.org)\n *            Distributed under a Modified BSD License.\n *              See accompanying file LICENSE.txt or\n *              http://www.opengeosys.org/project/license\n *\n */\n\n#include <gtest/gtest.h>\n\n#include <Eigen/Eigen>\n\n#include \"MathLib/LinAlg/LinAlg.h\"\n\n#if defined(USE_PETSC)\n#include \"MathLib/LinAlg/PETSc/PETScMatrix.h\"\n#else\n#include \"MathLib/LinAlg/Eigen/EigenMatrix.h\"\n#endif\n\n#include \"MathLib/LinAlg/FinalizeMatrixAssembly.h\"\n#include \"NumLib/NumericsConfig.h\"\n\nusing namespace MathLib::LinAlg;\n\nnamespace\n{\ntemplate <class T_MATRIX>\nvoid checkGlobalMatrixInterface(T_MATRIX& m)\n{\n    ASSERT_EQ(10u, m.getNumberOfRows());\n    ASSERT_EQ(10u, m.getNumberOfColumns());\n    ASSERT_EQ(0u, m.getRangeBegin());\n    ASSERT_EQ(10u, m.getRangeEnd());\n\n    m.setValue(0, 0, 1.0);\n    m.add(0, 0, 1.0);\n    m.setZero();\n\n    Eigen::Matrix2d local_m;\n    local_m << 1.0, 1.0, 1.0, 1.0;\n    std::vector<GlobalIndexType> vec_pos(2);\n    vec_pos[0] = 1;\n    vec_pos[1] = 3;\n    m.add(vec_pos, vec_pos, local_m);\n\n    ASSERT_TRUE(finalizeMatrixAssembly(m));\n}\n\n#ifdef USE_PETSC  // or MPI\ntemplate <class T_MATRIX, class T_VECTOR>\nvoid checkGlobalMatrixInterfaceMPI(T_MATRIX& m, T_VECTOR& v)\n{\n    int msize;\n    MPI_Comm_size(PETSC_COMM_WORLD, &msize);\n    int mrank;\n    MPI_Comm_rank(PETSC_COMM_WORLD, &mrank);\n\n    ASSERT_EQ(3u, msize);\n    ASSERT_EQ(m.getRangeEnd() - m.getRangeBegin(), m.getNumberOfLocalRows());\n\n    int gathered_rows;\n    int local_rows = m.getNumberOfLocalRows();\n    MPI_Allreduce(&local_rows, &gathered_rows, 1, MPI_INT, MPI_SUM,\n                  PETSC_COMM_WORLD);\n    ASSERT_EQ(m.getNumberOfRows(), gathered_rows);\n\n    int gathered_cols;\n    int local_cols = m.getNumberOfLocalColumns();\n    MPI_Allreduce(&local_cols, &gathered_cols, 1, MPI_INT, MPI_SUM,\n                  PETSC_COMM_WORLD);\n    ASSERT_EQ(m.getNumberOfColumns(), gathered_cols);\n\n    // Add entries\n    Eigen::Matrix2d loc_m(2, 2);\n    loc_m(0, 0) = 1.;\n    loc_m(0, 1) = 2.;\n    loc_m(1, 0) = 3.;\n    loc_m(1, 1) = 4.;\n\n    std::vector<GlobalIndexType> row_pos(2);\n    std::vector<GlobalIndexType> col_pos(2);\n    row_pos[0] = 2 * mrank;\n    row_pos[1] = 2 * mrank + 1;\n    col_pos[0] = row_pos[0];\n    col_pos[1] = row_pos[1];\n\n    m.add(row_pos, col_pos, loc_m);\n\n    MathLib::finalizeMatrixAssembly(m);\n\n    // Test basic assignment operator with an empty T_MATRIX._A\n    T_MATRIX m_c = m;\n    // Test basic assignment operator with an initialized T_MATRIX._A\n    m_c = m;\n\n    // Multiply by a vector\n    // v = 1.;\n    set(v, 1.);\n    const bool deep_copy = false;\n    T_VECTOR y(v, deep_copy);\n    matMult(m_c, v, y);\n\n    ASSERT_EQ(sqrt(3 * (3 * 3 + 7 * 7)), norm2(y));\n\n    // set a value\n    m_c.set(2 * mrank, 2 * mrank, 5.0);\n    MathLib::finalizeMatrixAssembly(m);\n    // add a value\n    m_c.add(2 * mrank + 1, 2 * mrank + 1, 5.0);\n    MathLib::finalizeMatrixAssembly(m_c);\n\n    matMult(m_c, v, y);\n\n    ASSERT_EQ(sqrt((3 * 7 * 7 + 3 * 12 * 12)), norm2(y));\n}\n\n// Rectanglular matrix\ntemplate <class T_MATRIX, class T_VECTOR>\nvoid checkGlobalRectangularMatrixInterfaceMPI(T_MATRIX& m, T_VECTOR& v)\n{\n    int mrank;\n    MPI_Comm_rank(PETSC_COMM_WORLD, &mrank);\n\n    ASSERT_EQ(m.getRangeEnd() - m.getRangeBegin(), m.getNumberOfLocalRows());\n\n    int gathered_rows;\n    int local_rows = m.getNumberOfLocalRows();\n    MPI_Allreduce(&local_rows, &gathered_rows, 1, MPI_INT, MPI_SUM,\n                  PETSC_COMM_WORLD);\n    ASSERT_EQ(m.getNumberOfRows(), gathered_rows);\n\n    int gathered_cols;\n    int local_cols = m.getNumberOfLocalColumns();\n    MPI_Allreduce(&local_cols, &gathered_cols, 1, MPI_INT, MPI_SUM,\n                  PETSC_COMM_WORLD);\n    ASSERT_EQ(m.getNumberOfColumns(), gathered_cols);\n\n    // Add entries\n    Eigen::Matrix<double, 2, 3> loc_m;\n    loc_m(0, 0) = 1.;\n    loc_m(0, 1) = 2.;\n    loc_m(0, 2) = 3.;\n    loc_m(1, 0) = 1.;\n    loc_m(1, 1) = 2.;\n    loc_m(1, 2) = 3.;\n\n    std::vector<GlobalIndexType> row_pos(2);\n    std::vector<GlobalIndexType> col_pos(3);\n    row_pos[0] = 2 * mrank;\n    row_pos[1] = 2 * mrank + 1;\n    col_pos[0] = 3 * mrank;\n    col_pos[1] = 3 * mrank + 1;\n    col_pos[2] = 3 * mrank + 2;\n\n    m.add(row_pos, col_pos, loc_m);\n\n    MathLib::finalizeMatrixAssembly(m);\n\n    // Multiply by a vector\n    set(v, 1);\n    T_VECTOR y(m.getNumberOfRows());\n    matMult(m, v, y);\n\n    ASSERT_NEAR(6. * sqrt(6.), norm2(y), 1.e-10);\n}\n\n#endif  // end of: ifdef USE_PETSC // or MPI\n\n}  // end namespace\n\n#if defined(USE_PETSC)\nTEST(MPITest_Math, CheckInterface_PETScMatrix_Local_Size)\n{\n    MathLib::PETScMatrixOption opt;\n    opt.d_nz = 2;\n    opt.o_nz = 0;\n    opt.is_global_size = false;\n    opt.n_local_cols = 2;\n    MathLib::PETScMatrix A(2, opt);\n\n    const bool is_gloabal_size = false;\n    MathLib::PETScVector x(2, is_gloabal_size);\n\n    checkGlobalMatrixInterfaceMPI(A, x);\n}\n\nTEST(MPITest_Math, CheckInterface_PETScMatrix_Global_Size)\n{\n    MathLib::PETScMatrixOption opt;\n    opt.d_nz = 2;\n    opt.o_nz = 0;\n    MathLib::PETScMatrix A(6, opt);\n\n    MathLib::PETScVector x(6);\n\n    checkGlobalMatrixInterfaceMPI(A, x);\n}\n\nTEST(MPITest_Math, CheckInterface_PETSc_Rectangular_Matrix_Local_Size)\n{\n    MathLib::PETScMatrixOption opt;\n    opt.d_nz = 3;\n    opt.o_nz = 0;\n    opt.is_global_size = false;\n    opt.n_local_cols = -1;\n    MathLib::PETScMatrix A(2, 3, opt);\n\n    const bool is_gloabal_size = false;\n    MathLib::PETScVector x(3, is_gloabal_size);\n\n    checkGlobalRectangularMatrixInterfaceMPI(A, x);\n}\n\nTEST(MPITest_Math, CheckInterface_PETSc_Rectangular_Matrix_Global_Size)\n{\n    MathLib::PETScMatrixOption opt;\n    opt.d_nz = 3;\n    opt.o_nz = 0;\n    MathLib::PETScMatrix A(6, 9, opt);\n\n    MathLib::PETScVector x(9);\n\n    checkGlobalRectangularMatrixInterfaceMPI(A, x);\n}\n#else\nTEST(Math, CheckInterface_EigenMatrix)\n{\n    MathLib::EigenMatrix m(10);\n    checkGlobalMatrixInterface(m);\n}\n#endif\n", "meta": {"hexsha": "c8b61ffd2cf2138fd02aa16af2d488139078d277", "size": 6101, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tests/MathLib/TestGlobalMatrixInterface.cpp", "max_stars_repo_name": "ufz/ogs", "max_stars_repo_head_hexsha": "97d0249e0c578c3055730f4e9d994b9970885098", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 111.0, "max_stars_repo_stars_event_min_datetime": "2015-03-20T22:54:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T04:37:21.000Z", "max_issues_repo_path": "Tests/MathLib/TestGlobalMatrixInterface.cpp", "max_issues_repo_name": "ufz/ogs", "max_issues_repo_head_hexsha": "97d0249e0c578c3055730f4e9d994b9970885098", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3015.0, "max_issues_repo_issues_event_min_datetime": "2015-01-05T21:55:16.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-15T01:09:17.000Z", "max_forks_repo_path": "Tests/MathLib/TestGlobalMatrixInterface.cpp", "max_forks_repo_name": "ufz/ogs", "max_forks_repo_head_hexsha": "97d0249e0c578c3055730f4e9d994b9970885098", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 250.0, "max_forks_repo_forks_event_min_datetime": "2015-02-10T15:43:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T04:37:20.000Z", "avg_line_length": 25.4208333333, "max_line_length": 77, "alphanum_fraction": 0.6564497623, "num_tokens": 1949, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.48889359348427475}}
{"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/ui/metrics_server.hpp>\n#include <graphlab/util/hopscotch_set.hpp>\n#include <graphlab/macros_def.hpp>\n/**\n *  \n * In this program we implement the \"hash-set\" version of the\n * \"edge-iterator\" algorithm described in\n * \n *    T. Schank. Algorithmic Aspects of Triangle-Based Network Analysis.\n *    Phd in computer science, University Karlsruhe, 2007.\n *\n * The procedure is quite straightforward:\n *   - each vertex maintains a list of all of its neighbors in a hash set.\n *   - For each edge (u,v) in the graph, count the number of intersections\n *     of the neighbor set on u and the neighbor set on v.\n *   - We store the size of the intersection on the edge.\n * \n * This will count every triangle exactly 3 times. Summing across all the\n * edges and dividing by 3 gives the desired result.\n *\n * The preprocessing stage take O(|E|) time, and it has been shown that this\n * algorithm takes $O(|E|^(3/2))$ time.\n *\n * If we only require total counts, we can introduce a optimization that is\n * similar to the \"forward\" algorithm\n * described in thesis above. Instead of maintaining a complete list of all\n * neighbors, each vertex only maintains a list of all neighbors with\n * ID greater than itself. This implicitly generates a topological sort\n * of the graph.\n *\n * Then you can see that each triangle\n *\n * \\verbatim\n  \n     A----->C\n     |     ^\n     |   /\n     v /\n     B\n   \n * \\endverbatim\n * Must be counted only once. (Only when processing edge AB, can one\n * observe that A and B have intersecting out-neighbor sets).\n */\n \n\n// Radix sort implementation from https://github.com/gorset/radix\n// Thanks to Erik Gorset\n//\n/*\nCopyright 2011 Erik Gorset. All rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification, are\npermitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this list of\nconditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright notice, this list\nof conditions and the following disclaimer in the documentation and/or other materials\nprovided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY Erik Gorset ``AS IS'' AND ANY EXPRESS OR IMPLIED\nWARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND\nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Erik Gorset OR\nCONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\nNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\nADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nThe views and conclusions contained in the software and documentation are those of the\nauthors and should not be interpreted as representing official policies, either expressed\nor implied, of Erik Gorset.\n*/\nvoid radix_sort(graphlab::vertex_id_type *array, int offset, int end, int shift) {\n    int x, y;\n    graphlab::vertex_id_type value, temp;\n    int last[256] = { 0 }, pointer[256];\n\n    for (x=offset; x<end; ++x) {\n        ++last[(array[x] >> shift) & 0xFF];\n    }\n\n    last[0] += offset;\n    pointer[0] = offset;\n    for (x=1; x<256; ++x) {\n        pointer[x] = last[x-1];\n        last[x] += last[x-1];\n    }\n\n    for (x=0; x<256; ++x) {\n        while (pointer[x] != last[x]) {\n            value = array[pointer[x]];\n            y = (value >> shift) & 0xFF;\n            while (x != y) {\n                temp = array[pointer[y]];\n                array[pointer[y]++] = value;\n                value = temp;\n                y = (value >> shift) & 0xFF;\n            }\n            array[pointer[x]++] = value;\n        }\n    }\n\n    if (shift > 0) {\n        shift -= 8;\n        for (x=0; x<256; ++x) {\n            temp = x > 0 ? pointer[x] - pointer[x-1] : pointer[0] - offset;\n            if (temp > 64) {\n                radix_sort(array, pointer[x] - temp, pointer[x], shift);\n            } else if (temp > 1) {\n                std::sort(array + (pointer[x] - temp), array + pointer[x]);\n                //insertion_sort(array, pointer[x] - temp, pointer[x]);\n            }\n        }\n    }\n}\n\nsize_t HASH_THRESHOLD = 64;\n\n// We on each vertex, either a vector of sorted VIDs\n// or a hash set (cuckoo hash) of VIDs.\n// If the number of elements is greater than HASH_THRESHOLD,\n// the hash set is used. Otherwise the vector is used.\nstruct vid_vector{\n  std::vector<graphlab::vertex_id_type> vid_vec;\n  graphlab::hopscotch_set<graphlab::vertex_id_type, false> *cset;\n  vid_vector(): cset(NULL) { }\n  vid_vector(const vid_vector& v):cset(NULL) {\n    (*this) = v;\n  }\n\n  vid_vector& operator=(const vid_vector& v) {\n    if (this == &v) return *this;\n    vid_vec = v.vid_vec;\n    if (v.cset != NULL) {\n      // allocate the cuckoo set if the other side is using a cuckoo set\n      // or clear if I alrady have one\n      if (cset == NULL) {\n        cset = new graphlab::hopscotch_set<graphlab::vertex_id_type, false>(HASH_THRESHOLD);\n      }\n      else {\n        cset->clear();\n      }\n      (*cset) = *(v.cset);\n    }\n    else {\n      // if the other side is not using a cuckoo set, lets not use a cuckoo set\n      // either\n      if (cset != NULL) {\n        delete cset;\n        cset = NULL;\n      }\n    }\n    return *this;\n  }\n\n  ~vid_vector() {\n    if (cset != NULL) delete cset;\n  }\n\n  // assigns a vector of vertex IDs to this storage.\n  // this function will clear the contents of the vid_vector\n  // and reconstruct it.\n  // If the assigned values has length >= HASH_THRESHOLD,\n  // we will allocate a cuckoo set to store it. Otherwise,\n  // we just store a sorted vector\n  void assign(const std::vector<graphlab::vertex_id_type>& vec) {\n    clear();\n    if (vec.size() >= HASH_THRESHOLD) {\n        // move to cset\n        cset = new graphlab::hopscotch_set<graphlab::vertex_id_type, false>(HASH_THRESHOLD);\n        foreach (graphlab::vertex_id_type v, vec) {\n          cset->insert(v);\n        }\n    }\n    else {\n      vid_vec = vec;\n      if (vid_vec.size() > 64) {\n        radix_sort(&(vid_vec[0]), 0, vid_vec.size(), 24);\n      }\n      else {\n        std::sort(vid_vec.begin(), vid_vec.end());\n      }\n      std::vector<graphlab::vertex_id_type>::iterator new_end = std::unique(vid_vec.begin(),\n                                               vid_vec.end());\n      vid_vec.erase(new_end, vid_vec.end());\n    }\n  }\n\n  void save(graphlab::oarchive& oarc) const {\n    oarc << (cset != NULL);\n    if (cset == NULL) oarc << vid_vec;\n    else oarc << (*cset);\n  }\n\n\n  void clear() {\n    vid_vec.clear();\n    if (cset != NULL) {\n      delete cset;\n      cset = NULL;\n    }\n  }\n\n  size_t size() const {\n    return cset == NULL ? vid_vec.size() : cset->size();\n  }\n\n  void load(graphlab::iarchive& iarc) {\n    clear();\n    bool hascset;\n    iarc >> hascset;\n    if (!hascset) iarc >> vid_vec;\n    else {\n      cset = new graphlab::hopscotch_set<graphlab::vertex_id_type, false>(HASH_THRESHOLD);\n      iarc >> (*cset);\n    }\n  }\n};\n\n/*\n  A simple counting iterator which can be used as an insert iterator.\n  but only counts the number of elements inserted. Useful for\n  use with counting the size of an intersection using std::set_intersection\n*/\ntemplate <typename T>\nstruct counting_inserter {\n  size_t* i;\n  counting_inserter(size_t* i):i(i) { }\n  counting_inserter& operator++() {\n    ++(*i);\n    return *this;\n  }\n  void operator++(int) {\n    ++(*i);\n  }\n\n  struct empty_val {\n    empty_val operator=(const T&) { return empty_val(); }\n  };\n\n  empty_val operator*() {\n    return empty_val();\n  }\n\n  typedef empty_val reference;\n};\n\n\n/*\n * Computes the size of the intersection of two vid_vector's\n */\nstatic uint32_t count_set_intersect(\n             const vid_vector& smaller_set,\n             const vid_vector& larger_set) {\n\n  if (smaller_set.cset == NULL && larger_set.cset == NULL) {\n    size_t i = 0;\n    counting_inserter<graphlab::vertex_id_type> iter(&i);\n    std::set_intersection(smaller_set.vid_vec.begin(), smaller_set.vid_vec.end(),\n                          larger_set.vid_vec.begin(), larger_set.vid_vec.end(),\n                          iter);\n    return i;\n  }\n  else if (smaller_set.cset == NULL && larger_set.cset != NULL) {\n    size_t i = 0;\n    foreach(graphlab::vertex_id_type vid, smaller_set.vid_vec) {\n      i += larger_set.cset->count(vid);\n    }\n    return i;\n  }\n  else if (smaller_set.cset != NULL && larger_set.cset == NULL) {\n    size_t i = 0;\n    foreach(graphlab::vertex_id_type vid, larger_set.vid_vec) {\n      i += smaller_set.cset->count(vid);\n    }\n    return i;\n  }\n  else {\n    size_t i = 0;\n    foreach(graphlab::vertex_id_type vid, *(smaller_set.cset)) {\n      i += larger_set.cset->count(vid);\n    }\n    return i;\n\n  }\n}\n\n\n\n\n\n\n/*\n * Each vertex maintains a list of all its neighbors.\n * and a final count for the number of triangles it is involved in\n */\nstruct vertex_data_type {\n  vertex_data_type(): num_triangles(0){ }\n  // A list of all its neighbors\n  vid_vector vid_set;\n  // The number of triangles this vertex is involved it.\n  // only used if \"per vertex counting\" is used\n  uint32_t num_triangles;\n  void save(graphlab::oarchive &oarc) const {\n    oarc << vid_set << num_triangles;\n  }\n  void load(graphlab::iarchive &iarc) {\n    iarc >> vid_set >> num_triangles;\n  }\n};\n\n\n/*\n * Each edge is simply a counter of triangles\n */\ntypedef uint32_t edge_data_type;\n\n// To collect the set of neighbors, we need a message type which is\n// basically a set of vertex IDs\n\nbool PER_VERTEX_COUNT = false;\n\n\n/*\n * This is the gathering type which accumulates an array of\n * all neighboring vertices.\n * It is a simple wrapper around a vector with\n * an operator+= which simply performs a  +=\n */\nstruct set_union_gather {\n  graphlab::vertex_id_type v;\n  std::vector<graphlab::vertex_id_type> vid_vec;\n\n  set_union_gather():v(-1) {\n  }\n\n  size_t size() const {\n    if (v == (graphlab::vertex_id_type)-1) return vid_vec.size();\n    else return 1;\n  }\n  /*\n   * Combining with another collection of vertices.\n   * Union it into the current set.\n   */\n  set_union_gather& operator+=(const set_union_gather& other) {\n    if (size() == 0) {\n      (*this) = other;\n      return (*this);\n    }\n    else if (other.size() == 0) {\n      return *this;\n    }\n\n    if (vid_vec.size() == 0) {\n      vid_vec.push_back(v);\n      v = (graphlab::vertex_id_type)(-1);\n    }\n    if (other.vid_vec.size() > 0) {\n      size_t ct = vid_vec.size();\n      vid_vec.resize(vid_vec.size() + other.vid_vec.size());\n      for (size_t i = 0; i < other.vid_vec.size(); ++i) {\n        vid_vec[ct + i] = other.vid_vec[i];\n      }\n    }\n    else if (other.v != (graphlab::vertex_id_type)-1) {\n      vid_vec.push_back(other.v);\n    }\n    return *this;\n  }\n  \n  // serialize\n  void save(graphlab::oarchive& oarc) const {\n    oarc << bool(vid_vec.size() == 0);\n    if (vid_vec.size() == 0) oarc << v;\n    else oarc << vid_vec;\n  }\n\n  // deserialize\n  void load(graphlab::iarchive& iarc) {\n    bool novvec;\n    v = (graphlab::vertex_id_type)(-1);\n    vid_vec.clear();\n    iarc >> novvec;\n    if (novvec) iarc >> v;\n    else iarc >> vid_vec;\n  }\n};\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\n\n/*\n * This class implements the triangle counting algorithm as described in\n * the header. On gather, we accumulate a set of all adjacent vertices.\n * If per_vertex output is not necessary, we can use the optimization\n * where each vertex only accumulates neighbors with greater vertex IDs.\n */\nclass triangle_count :\n      public graphlab::ivertex_program<graph_type,\n                                      set_union_gather>,\n      /* I have no data. Just force it to POD */\n      public graphlab::IS_POD_TYPE  {\npublic:\n  bool do_not_scatter;\n\n  // 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  } \n\n  /*\n   * For each edge, figure out the ID of the \"other\" vertex\n   * and accumulate a set of the neighborhood vertex IDs.\n   */\n  gather_type gather(icontext_type& context,\n                     const vertex_type& vertex,\n                     edge_type& edge) const {\n    set_union_gather gather;\n    graphlab::vertex_id_type otherid = edge.target().id() == vertex.id() ?\n                                       edge.source().id() : edge.target().id();\n\n    size_t other_nbrs = (edge.target().id() == vertex.id()) ?\n        (edge.source().num_in_edges() + edge.source().num_out_edges()): \n        (edge.target().num_in_edges() + edge.target().num_out_edges());\n\n    size_t my_nbrs = vertex.num_in_edges() + vertex.num_out_edges();\n\n    if (PER_VERTEX_COUNT || (other_nbrs > my_nbrs) || (other_nbrs == my_nbrs && otherid > vertex.id())) {\n    //if (PER_VERTEX_COUNT || otherid > vertex.id()) {\n     gather.v = otherid;\n    } \n    return gather;\n  }\n\n  /*\n   * the gather result now contains the vertex IDs in the neighborhood.\n   * store it on the vertex. \n   */\n  void apply(icontext_type& context, vertex_type& vertex,\n             const gather_type& neighborhood) {\n   do_not_scatter = false;\n   if (neighborhood.vid_vec.size() == 0) {\n     // neighborhood set may be empty or has only 1 element\n     vertex.data().vid_set.clear();\n     if (neighborhood.v != (graphlab::vertex_id_type(-1))) {\n       vertex.data().vid_set.vid_vec.push_back(neighborhood.v);\n     }\n   }\n   else {\n     vertex.data().vid_set.assign(neighborhood.vid_vec);\n   }\n   do_not_scatter = vertex.data().vid_set.size() == 0;\n  } // end of apply\n\n  /*\n   * Scatter over all edges to compute the intersection.\n   * I only need to touch each edge once, so if I scatter just on the\n   * out edges, that is sufficient.\n   */\n  edge_dir_type scatter_edges(icontext_type& context,\n                              const vertex_type& vertex) const {\n    if (do_not_scatter) return graphlab::NO_EDGES;\n    else return graphlab::OUT_EDGES;\n  }\n\n\n  /*\n   * For each edge, count the intersection of the neighborhood of the\n   * adjacent vertices. This is the number of triangles this edge is involved\n   * in.\n   */\n  void scatter(icontext_type& context,\n              const vertex_type& vertex,\n              edge_type& edge) const {\n\n    //    vertex_type othervtx = edge.target();\n    const vertex_data_type& srclist = edge.source().data();\n    const vertex_data_type& targetlist = edge.target().data();\n    if (targetlist.vid_set.size() < srclist.vid_set.size()) {\n      edge.data() += count_set_intersect(targetlist.vid_set, srclist.vid_set);\n    }\n    else {\n      edge.data() += count_set_intersect(srclist.vid_set, targetlist.vid_set);\n    }\n  }\n};\n\n/*\n * This class is used in a second engine call if per vertex counts are needed.\n * The number of triangles a vertex is involved in can be computed easily\n * by summing over the number of triangles each adjacent edge is involved in\n * and dividing by 2. \n */\nclass get_per_vertex_count :\n      public graphlab::ivertex_program<graph_type, size_t>,\n      /* I have no data. Just force it to POD */\n      public graphlab::IS_POD_TYPE  {\npublic:\n  // 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  }\n  // We gather the number of triangles each edge is involved in\n  size_t gather(icontext_type& context,\n                     const vertex_type& vertex,\n                     edge_type& edge) const {\n    return edge.data();\n  }\n\n  /* the gather result is the total sum of the number of triangles\n   * each adjacent edge is involved in . Dividing by 2 gives the\n   * desired result.\n   */\n  void apply(icontext_type& context, vertex_type& vertex,\n             const gather_type& num_triangles) {\n    vertex.data().vid_set.clear();\n    vertex.data().num_triangles = num_triangles / 2;\n  }\n\n  // No scatter\n  edge_dir_type scatter_edges(icontext_type& context,\n                             const vertex_type& vertex) const {\n    return graphlab::NO_EDGES;\n  }\n\n\n};\n\ntypedef graphlab::synchronous_engine<triangle_count> engine_type;\n\n/* Used to sum over all the edges in the graph in a\n * map_reduce_edges call\n * to get the total number of triangles\n */\nsize_t get_edge_data(const graph_type::edge_type& e) {\n  return e.data();\n}\n\n/*\n * A saver which saves a file where each line is a vid / # triangles pair\n */\nstruct save_triangle_count{\n  std::string save_vertex(graph_type::vertex_type v) { \n    double nt = v.data().num_triangles;\n    double n_followed = v.num_out_edges();\n    double n_following = v.num_in_edges();\n\n    return graphlab::tostr(v.id()) + \"\\t\" +\n           graphlab::tostr(nt) + \"\\t\" +\n           graphlab::tostr(n_followed) + \"\\t\" + \n           graphlab::tostr(n_following) + \"\\n\";\n  }\n  std::string save_edge(graph_type::edge_type e) {\n    return \"\";\n  }\n};\n\n\nint main(int argc, char** argv) {\n  std::cout << \"This program counts the exact number of triangles in the \"\n            \"provided graph.\\n\\n\";\n\n  graphlab::command_line_options clopts(\"Exact Triangle Counting. \"\n    \"Given a graph, this program computes the total number of triangles \"\n    \"in the graph. An option (per_vertex) is also provided which \"\n    \"computes for each vertex, the number of triangles it is involved in.\"\n    \"The algorithm assumes that each undirected edge appears exactly once \"\n    \"in the graph input. If edges may appear more than once, this procedure \"\n    \"will over count.\");\n  std::string prefix, format;\n  std::string per_vertex;\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(\"ht\", HASH_THRESHOLD,\n                       \"Above this size, hash sets are used\");\n  clopts.attach_option(\"per_vertex\", per_vertex,\n                       \"If not empty, will count the number of \"\n                       \"triangles each vertex belongs to and \"\n                       \"save to file with prefix \\\"[per_vertex]\\\". \"\n                       \"The algorithm used is slightly different \"\n                       \"and thus will be a little slower\");\n  if(!clopts.parse(argc, argv)) return EXIT_FAILURE;\n  if (prefix == \"\") {\n    std::cout << \"--graph is not optional\\n\";\n    clopts.print_description();\n    return EXIT_FAILURE;\n  }\n  else if (format == \"\") {\n    std::cout << \"--format is not optional\\n\";\n    clopts.print_description();\n    return EXIT_FAILURE;\n  }\n\n\n  if (per_vertex != \"\") PER_VERTEX_COUNT = true;\n  // Initialize control plane using mpi\n  graphlab::mpi_tools::init(argc, argv);\n  graphlab::distributed_control dc;\n\n  graphlab::launch_metric_server();\n  // load graph\n  graph_type graph(dc, clopts);\n  graph.load_format(prefix, format);\n  graph.finalize();\n  dc.cout() << \"Number of vertices: \" << graph.num_vertices() << std::endl\n            << \"Number of edges:    \" << graph.num_edges() << std::endl;\n\n  graphlab::timer ti;\n  \n  // create engine to count the number of triangles\n  dc.cout() << \"Counting Triangles...\" << std::endl;\n  engine_type engine(dc, graph, clopts);\n  engine.signal_all();\n  engine.start();\n\n  dc.cout() << \"Counted in \" << ti.current_time() << \" seconds\" << std::endl;\n\n  if (PER_VERTEX_COUNT == false) {\n    size_t count = graph.map_reduce_edges<size_t>(get_edge_data);\n    dc.cout() << count << \" Triangles\"  << std::endl;\n  }\n  else {\n    graphlab::synchronous_engine<get_per_vertex_count> engine(dc, graph, clopts);\n    engine.signal_all();\n    engine.start();\n    graph.save(per_vertex,\n            save_triangle_count(),\n            false, /* no compression */\n            true, /* save vertex */\n            false, /* do not save edge */\n            clopts.get_ncpus()); /* one file per machine */\n\n  }\n  \n  graphlab::stop_metric_server();\n\n  graphlab::mpi_tools::finalize();\n  return EXIT_SUCCESS;\n} // End of main\n\n", "meta": {"hexsha": "b937135a0d210b36ba460f606f46bfef09971abd", "size": 21028, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "toolkits/graph_analytics/undirected_triangle_count.cpp", "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": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-11-07T05:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2016-11-07T05:47:18.000Z", "max_issues_repo_path": "toolkits/graph_analytics/undirected_triangle_count.cpp", "max_issues_repo_name": "keerthanashanmugam/graphlabapi", "max_issues_repo_head_hexsha": "7d66bbda82d4d44cded35f9438e1c9359b0ca64e", "max_issues_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "toolkits/graph_analytics/undirected_triangle_count.cpp", "max_forks_repo_name": "keerthanashanmugam/graphlabapi", "max_forks_repo_head_hexsha": "7d66bbda82d4d44cded35f9438e1c9359b0ca64e", "max_forks_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.9690721649, "max_line_length": 105, "alphanum_fraction": 0.6360091307, "num_tokens": 5325, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.4888563413478324}}
{"text": "#ifndef EDGE_SAMPLER_HPP\n#define EDGE_SAMPLER_HPP\n\n#include <Eigen/Dense>\n\nnamespace polyfem {\n\n\tclass EdgeSampler\n\t{\n\tpublic:\n\t\tstatic void sample_2d_simplex(const int resolution, Eigen::MatrixXd &samples);\n\t\tstatic void sample_2d_cube(const int resolution, Eigen::MatrixXd &samples);\n\n\t\tstatic void sample_3d_simplex(const int resolution, Eigen::MatrixXd &samples);\n\t\tstatic void sample_3d_cube(const int resolution, Eigen::MatrixXd &samples);\n\n\t};\n}\n\n#endif //EDGE_SAMPLER_HPP\n", "meta": {"hexsha": "060fec0a05e57786881dee4cda80e9bfe56f5006", "size": 480, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/utils/EdgeSampler.hpp", "max_stars_repo_name": "ldXiao/polyfem", "max_stars_repo_head_hexsha": "d4103af16979ff67d461a9ebe46a14bbc4dc8c7c", "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/utils/EdgeSampler.hpp", "max_issues_repo_name": "ldXiao/polyfem", "max_issues_repo_head_hexsha": "d4103af16979ff67d461a9ebe46a14bbc4dc8c7c", "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/utils/EdgeSampler.hpp", "max_forks_repo_name": "ldXiao/polyfem", "max_forks_repo_head_hexsha": "d4103af16979ff67d461a9ebe46a14bbc4dc8c7c", "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": 22.8571428571, "max_line_length": 80, "alphanum_fraction": 0.7791666667, "num_tokens": 115, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.6926419767901476, "lm_q1q2_score": 0.4888563368699168}}
{"text": "#ifndef UWB_NODE_H\n#define UWB_NODE_H\n\n#include \"ros/ros.h\"\n#include \"geometry_msgs/PointStamped.h\"\n#include \"common_msgs/UWB_FullRangeInfo.h\"\n#include \"common_msgs/UWB_FullNeighborDatabase.h\"\n#include \"common_msgs/UWB_DataInfo.h\"\n#include \"common_msgs/UWB_SendData.h\"\n#include \"common_msgs/UWB_EchoedRangeInfo.h\"\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n#include <boost/shared_ptr.hpp>\n#include <map>\n\nnamespace uavos{\n\ntypedef Eigen::Matrix<double, 6, 1> Vector6d;\ntypedef Eigen::Matrix<double, 6, 6> Matrix6d;\n\n\n// -----------------------------\nstruct comp{\n    template <typename T>\n    inline bool operator()(const T& a, const T& b) const{\n        return (a<b);\n    }\n};\n\n\n\ntemplate <typename T>\ndouble robustAverage(std::vector<T> array){\n    // the paramter is copied, so that the original data will not be affected.\n    const int cut_length = 2;\n\n    if(array.size()<=2*cut_length){\n        return 0;\n    }\n\n    double sum = 0;\n    std::sort(array.begin(), array.end(), comp());\n    for(int i=cut_length;i<array.size()-cut_length;++i){\n        sum+=array.at(i);\n    }\n\n    return sum / (array.size()-2*cut_length);\n\n}\n\ntemplate <typename T>\nbool medianAndVariance(std::vector<T> array, double& median, double& variance){\n    if(array.size()==0){\n        return false;\n    }\n\n    // get median\n    std::sort(array.begin(), array.end(), comp());\n    median = array.at(std::floor(array.size()/2));\n\n    // get mean\n    double sum = 0;\n    for(int i=0;i<array.size();++i){\n        sum+=array.at(i);\n    }\n    double mean = sum / array.size();\n\n\n    // get variance\n    double variance_sum = 0;\n    for(int i=0;i<array.size();++i){\n        double res = array.at(i)-mean;\n        variance_sum += res*res;\n    }\n    variance = variance_sum / array.size();\n\n    return true;\n}\n\n// -----------------------------\n\n\nclass UWB_Node{\npublic:\n    explicit UWB_Node(const int node_id);\n\nprotected:\n    int m_node_id;\n\n    geometry_msgs::PointStamped m_position;\n    geometry_msgs::PointStamped m_velocity;\n\n    Matrix6d m_state_covariance;\n\npublic:\n    inline int getNodeId() const{\n        return m_node_id;\n    }\n    inline geometry_msgs::PointStamped getPosition() const{\n        return m_position;\n    }\n    inline geometry_msgs::PointStamped* getPositionPtr(){\n        return &m_position;\n    }\n    inline geometry_msgs::PointStamped getVelocity() const{\n        return m_velocity;\n    }\n    inline Matrix6d getStateCovariance() const{\n        return m_state_covariance;\n    }\n\n    inline void setPosition(const double x, const double y, const double z){\n        m_position.header.stamp = ros::Time::now();\n\n        m_position.point.x = x;\n        m_position.point.y = y;\n        m_position.point.z = z;\n    }\n    inline void setVelocity(const double vx, const double vy, const double vz){\n        m_velocity.header.stamp = ros::Time::now();\n\n        m_velocity.point.x = vx;\n        m_velocity.point.y = vy;\n        m_velocity.point.z = vz;\n    }\n    inline void setStateCovariance(const Matrix6d& state_covariance){\n        m_state_covariance = state_covariance;\n    }\n\n\n    inline void printPosition(){\n        std::cout<<m_node_id<<\":\"<<std::endl;\n        std::cout<<\"pose: \"<<m_position.point.x<<\", \"<<m_position.point.y<<\", \"<<m_position.point.z\n                <<\"   cov: \"<<m_state_covariance(0,0)<<\", \"<<m_state_covariance(1,1)<<\", \"<<m_state_covariance(2,2)\n                <<std::endl;\n    }\n    inline void printVelocity(){\n        std::cout<<\"velo: \"<<m_velocity.point.x<<\", \"<<m_velocity.point.y<<\", \"<<m_velocity.point.z\n                <<\"   cov: \"<<m_state_covariance(3,3)<<\", \"<<m_state_covariance(4,4)<<\", \"<<m_state_covariance(5,5)\n                <<std::endl;\n    }\n\n};\n\n\nclass UWB_Anchor : public UWB_Node{\npublic:\n    explicit UWB_Anchor(const int node_id,\n                        const double x, const double y, const double z,\n                        const double var_x, const double var_y, const double var_z);\n\npublic:\n    std::map<int, std::vector<double> > m_range_map;\n\n    void insertRangeInfo(const common_msgs::UWB_EchoedRangeInfo& msg);\n    void insertRangeInfo(const common_msgs::UWB_FullRangeInfo& msg);\n    double getAverageRangeToNode(const int anchor_id);\n    bool getMedianAndVarianceToNode(const int anchor_id, double& median, double& variance);\n\n    inline void printPosition(){\n        std::cout<<m_node_id<<\": \"<<m_position.point.x<<\", \"<<m_position.point.y<<\", \"<<m_position.point.z<<std::endl;\n    }\n\n};\n\n\nclass UWB_Mobile : public UWB_Node{\npublic:\n    explicit UWB_Mobile(const int node_id, const std::map<int, boost::shared_ptr<UWB_Anchor> > anchor_map);\n\nprivate:\n    // stores last correct/accepted measurements\n    std::map<int, common_msgs::UWB_FullRangeInfo> m_ranges_to_anchors;\n    ros::Time m_last_range_time;\n\n    // provided by parameter server\n    std::map<int, boost::shared_ptr<UWB_Anchor> > m_anchor_map;\n\n    double m_kalman_sigma_a;\n    double m_snr_threshold;\n    double m_innovation_threshold;\n\n    // check whether the filter is properly initialized and ready to use\n    bool m_is_initialized;\n    std::vector<geometry_msgs::PointStamped> m_init_inspector_position_array;\n\npublic:\n    // reading statistics\n    std::map<int, int> m_anchor_reading_counter;\n    std::map<int, int> m_anchor_successful_reading_counter;\n\npublic:\n    bool checkInitialization();\n    inline bool getInitializationFlag() const{\n        return m_is_initialized;\n    }\n\n    inline common_msgs::UWB_FullRangeInfo getRangeInfoToAnchor(const int anchor_id) const{\n        return m_ranges_to_anchors.find(anchor_id)->second;\n    }\n    inline double getRangeMeterToAnchor(const int anchor_id) const{\n        return double(m_ranges_to_anchors.find(anchor_id)->second.precisionRangeMm) / 1000.0;\n    }\n\n    inline void setRangeInfoToAnchor(const common_msgs::UWB_FullRangeInfo& range_info){\n        m_ranges_to_anchors[range_info.responderId] = range_info;\n    }\n\n    inline void readingCounterInc(const int anchor_id){\n        if(m_anchor_reading_counter.find(anchor_id)==m_anchor_reading_counter.end()){\n            m_anchor_reading_counter[anchor_id] = 1;\n        } else {\n            m_anchor_reading_counter[anchor_id] += 1;\n        }\n    }\n    inline void successfulReadingCounterInc(const int anchor_id){\n        if(m_anchor_successful_reading_counter.find(anchor_id)==m_anchor_successful_reading_counter.end()){\n            m_anchor_successful_reading_counter[anchor_id] = 1;\n        } else {\n            m_anchor_successful_reading_counter[anchor_id] += 1;\n        }\n    }\n    inline int getReadingCount(const int anchor_id){\n        if(m_anchor_reading_counter.find(anchor_id)==m_anchor_reading_counter.end()){\n            return 0;\n        } else {\n            return m_anchor_reading_counter.at(anchor_id);\n        }\n    }\n    inline int getSuccessfulReadingCount(const int anchor_id){\n        if(m_anchor_successful_reading_counter.find(anchor_id)==m_anchor_successful_reading_counter.end()){\n            return 0;\n        } else {\n            return m_anchor_successful_reading_counter.at(anchor_id);\n        }\n    }\n\n\n    // EKF from TimeDomain\n    void initializeEKF();\n    bool kalmanFilter3DUpdate(const common_msgs::UWB_FullRangeInfo& range_info);\n\n};\n\n\n\n}\n\n#endif // UWB_NODE_H\n", "meta": {"hexsha": "1d4f88e6b46c3cefcc5add937587ea10fc8a618c", "size": 7237, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "uwb_calibration/src/uwb_node.hpp", "max_stars_repo_name": "Gravity-N1/uwb-localization", "max_stars_repo_head_hexsha": "45088cede2795657c0d980d7a01794acd6f90c83", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 228.0, "max_stars_repo_stars_event_min_datetime": "2018-07-16T10:00:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T08:21:52.000Z", "max_issues_repo_path": "uwb_calibration/src/uwb_node.hpp", "max_issues_repo_name": "NamDinhRobotics/uwb-localization", "max_issues_repo_head_hexsha": "45088cede2795657c0d980d7a01794acd6f90c83", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2018-11-03T21:17:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-18T09:46:40.000Z", "max_forks_repo_path": "uwb_calibration/src/uwb_node.hpp", "max_forks_repo_name": "NamDinhRobotics/uwb-localization", "max_forks_repo_head_hexsha": "45088cede2795657c0d980d7a01794acd6f90c83", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 121.0, "max_forks_repo_forks_event_min_datetime": "2018-08-17T11:32:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T09:10:22.000Z", "avg_line_length": 28.7182539683, "max_line_length": 118, "alphanum_fraction": 0.6600801437, "num_tokens": 1744, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.835483553488848, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.48884239146414193}}
{"text": "#include \"MexPackUnpack.h\"\n#include \"mex.h\"\n#include <Eigen>\n\nusing namespace MexPackUnpackTypes;\n\nvoid mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {\n\n\n  //argument 1 : real double precision scalar\n  //argument 2 : single precision complex scalar\n  //argument 3 : Double precision complex matrix (Eigen Map) \n  //argument 4 : Double precision complex matrix represented as a pair of pointers, number of rows, and number of columns\n  //Note: Requires MATLAB 2018a or newer and  the -R2018a compilation flag\n  MexUnpacker<double, std::complex<float>, EDCIM,  CDIP> my_unpack(nrhs, prhs);\n \n  try {\n\n    auto [a, b, c, d] = my_unpack.unpackMex();\n    auto [d_p, d_M, d_N] = d; //dp is std::complex<double>* (pointer to complex data), d_M is number of rows, d_N is number of columns\n    \n    Eigen::MatrixXcd e_comp = b*c;\n\n    MexPacker<std::complex<double>, int, Eigen::MatrixXcd, CDIP> my_pack(nlhs, plhs);\n    my_pack.PackMex(b, 2, e_comp, d);\n\n  } catch (std::string s) {\n    mexPrintf(s.data());\n  }\n\n}\n", "meta": {"hexsha": "634041f53f7a95e76fd884674e931214c6a16e7f", "size": 1033, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/example_2_interleaved.cpp", "max_stars_repo_name": "kantorset/MexPackUnpack", "max_stars_repo_head_hexsha": "18eb8a62b3a12f3faf3271590478165c997e1843", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/example_2_interleaved.cpp", "max_issues_repo_name": "kantorset/MexPackUnpack", "max_issues_repo_head_hexsha": "18eb8a62b3a12f3faf3271590478165c997e1843", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/example_2_interleaved.cpp", "max_forks_repo_name": "kantorset/MexPackUnpack", "max_forks_repo_head_hexsha": "18eb8a62b3a12f3faf3271590478165c997e1843", "max_forks_repo_licenses": ["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.28125, "max_line_length": 134, "alphanum_fraction": 0.6902226525, "num_tokens": 302, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961425, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.48884238667058055}}
{"text": "// Boost.Geometry\n\n// Copyright (c) 2016, 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_FORMULAS_SPHERICAL_HPP\n#define BOOST_GEOMETRY_FORMULAS_SPHERICAL_HPP\n\n#include <boost/geometry/core/coordinate_system.hpp>\n#include <boost/geometry/core/coordinate_type.hpp>\n#include <boost/geometry/core/access.hpp>\n#include <boost/geometry/core/radian_access.hpp>\n\n//#include <boost/geometry/arithmetic/arithmetic.hpp>\n#include <boost/geometry/arithmetic/cross_product.hpp>\n#include <boost/geometry/arithmetic/dot_product.hpp>\n\n#include <boost/geometry/util/math.hpp>\n#include <boost/geometry/util/normalize_spheroidal_coordinates.hpp>\n#include <boost/geometry/util/select_coordinate_type.hpp>\n\nnamespace boost { namespace geometry {\n    \nnamespace formula {\n\ntemplate <typename Point3d, typename PointSph>\nstatic inline Point3d sph_to_cart3d(PointSph const& point_sph)\n{\n    typedef typename coordinate_type<Point3d>::type calc_t;\n\n    Point3d res;\n\n    calc_t lon = get_as_radian<0>(point_sph);\n    calc_t lat = get_as_radian<1>(point_sph);\n\n    calc_t const cos_lat = cos(lat);\n    set<0>(res, cos_lat * cos(lon));\n    set<1>(res, cos_lat * sin(lon));\n    set<2>(res, sin(lat));\n\n    return res;\n}\n\ntemplate <typename PointSph, typename Point3d>\nstatic inline PointSph cart3d_to_sph(Point3d const& point_3d)\n{\n    typedef typename coordinate_type<PointSph>::type coord_t;\n    typedef typename coordinate_type<Point3d>::type calc_t;\n\n    PointSph res;\n\n    calc_t const x = get<0>(point_3d);\n    calc_t const y = get<1>(point_3d);\n    calc_t const z = get<2>(point_3d);\n\n    set_from_radian<0>(res, atan2(y, x));\n    set_from_radian<1>(res, asin(z));\n\n    coord_t lon = get<0>(res);\n    coord_t lat = get<1>(res);\n\n    math::normalize_spheroidal_coordinates\n        <\n            typename coordinate_system<PointSph>::type::units,\n            coord_t\n        >(lon, lat);\n\n    set<0>(res, lon);\n    set<1>(res, lat);\n\n    return res;\n}\n\n// -1 right\n// 1 left\n// 0 on\ntemplate <typename Point3d1, typename Point3d2>\nstatic inline int sph_side_value(Point3d1 const& norm, Point3d2 const& pt)\n{\n    typedef typename select_coordinate_type<Point3d1, Point3d2>::type calc_t;\n    calc_t c0 = 0;\n    calc_t d = dot_product(norm, pt);\n    return math::equals(d, c0) ? 0\n        : d > c0 ? 1\n        : -1; // d < 0\n}\n\n} // namespace formula\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_FORMULAS_SPHERICAL_HPP\n", "meta": {"hexsha": "2195bbbe10024a2096ffbb0925abb2da81e582bc", "size": 2672, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "nheqminer/3rdparty/boost/geometry/formulas/spherical.hpp", "max_stars_repo_name": "EuroLine/nheqminer", "max_stars_repo_head_hexsha": "81c7ef889bb502d16f7d1e7ef020d0592f8af945", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 886.0, "max_stars_repo_stars_event_min_datetime": "2016-10-20T20:59:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T07:47:52.000Z", "max_issues_repo_path": "ios/Pods/boost-for-react-native/boost/geometry/formulas/spherical.hpp", "max_issues_repo_name": "c7yrus/alyson-v3", "max_issues_repo_head_hexsha": "5ad95a8f782f5f5d2fd543d44ca6a8b093395965", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 369.0, "max_issues_repo_issues_event_min_datetime": "2016-10-21T07:42:54.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-19T10:49:29.000Z", "max_forks_repo_path": "ios/Pods/boost-for-react-native/boost/geometry/formulas/spherical.hpp", "max_forks_repo_name": "c7yrus/alyson-v3", "max_forks_repo_head_hexsha": "5ad95a8f782f5f5d2fd543d44ca6a8b093395965", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 534.0, "max_forks_repo_forks_event_min_datetime": "2016-10-20T21:00:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T10:02:27.000Z", "avg_line_length": 27.5463917526, "max_line_length": 79, "alphanum_fraction": 0.7136976048, "num_tokens": 737, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.488842381877019}}
{"text": "#include <fstream>\n\n#include <rosbag/bag.h>\n#include <rosbag/view.h>\n#include <sensor_msgs/PointCloud2.h>\n\n#include <pcl/point_types.h>\n#include <pcl/common/common.h>\n#include <pcl/conversions.h>\n#include <pcl/filters/extract_indices.h>\n#include <pcl/filters/voxel_grid.h>\n#include <pcl/segmentation/extract_clusters.h>\n#include <pcl/segmentation/sac_segmentation.h>\n\n#include <pcl_ros/transforms.h>\n#include <pcl_conversions/pcl_conversions.h>\n\n#include <boost/foreach.hpp>\n#define foreach BOOST_FOREACH\n\nros::Publisher  pub_cloud;\nros::Publisher  pub_velo;\n\nvoid getCloudClusters(pcl::PointCloud<pcl::PointXYZI>::Ptr cloud_ptr, std::vector<pcl::PointCloud<pcl::PointXYZI>::Ptr>& pc_vector)\n{\n  // Creating the KdTree object for the search method of the extraction\n  pcl::search::KdTree<pcl::PointXYZI>::Ptr tree (new pcl::search::KdTree<pcl::PointXYZI>);\n  tree->setInputCloud (cloud_ptr);\n\n  std::vector<pcl::PointIndices> cluster_indices;\n  pcl::EuclideanClusterExtraction<pcl::PointXYZI> ec;\n  ec.setClusterTolerance (0.5); // 50cm - big since we're sure the panel is far from other obstacles (ie. barriers)\n  ec.setMinClusterSize (3);\n  ec.setMaxClusterSize (1000);\n  ec.setSearchMethod (tree);\n  ec.setInputCloud (cloud_ptr);\n  ec.extract (cluster_indices);\n\n  // Get the cloud representing each cluster\n  for (std::vector<pcl::PointIndices>::const_iterator it = cluster_indices.begin (); it != cluster_indices.end (); ++it)\n  {\n    pcl::PointCloud<pcl::PointXYZI>::Ptr cloud_cluster (new pcl::PointCloud<pcl::PointXYZI>);\n    for (std::vector<int>::const_iterator pit = it->indices.begin (); pit != it->indices.end (); ++pit)\n      cloud_cluster->points.push_back (cloud_ptr->points[*pit]);\n\n    cloud_cluster->width = cloud_cluster->points.size ();\n    cloud_cluster->height = 1;\n    cloud_cluster->is_dense = true;\n\n    pc_vector.push_back(cloud_cluster);\n  }\n}\n\n\nvoid computeBoundingBox(std::vector<pcl::PointCloud<pcl::PointXYZI>::Ptr>& pc_vector,std::vector<Eigen::Vector3f>& dimension_list, std::vector<Eigen::Vector4f>& centroid_list, std::vector<std::vector<pcl::PointXYZI> >& corners)\n{\n  pcl::PointCloud<pcl::PointXYZI>::Ptr cloud_plane (new pcl::PointCloud<pcl::PointXYZI> ());\n  Eigen::Vector3f one_dimension;\n\n  for (std::vector<pcl::PointCloud<pcl::PointXYZI>::Ptr>::const_iterator iterator = pc_vector.begin(), end = pc_vector.end(); iterator != end; ++iterator)\n  {\n    cloud_plane=*iterator;\n\n    // Compute principal directions\n    Eigen::Vector4f pcaCentroid;\n    pcl::compute3DCentroid(*cloud_plane, pcaCentroid);\n\n    Eigen::Matrix3f covariance;\n    computeCovarianceMatrixNormalized(*cloud_plane, pcaCentroid, covariance);\n    Eigen::SelfAdjointEigenSolver<Eigen::Matrix3f> eigen_solver(covariance, Eigen::ComputeEigenvectors);\n    Eigen::Matrix3f eigenVectorsPCA = eigen_solver.eigenvectors();\n    eigenVectorsPCA.col(2) = eigenVectorsPCA.col(0).cross(eigenVectorsPCA.col(1));\n\n    // Transform the original cloud to the origin where the principal components correspond to the axes.\n    Eigen::Matrix4f projectionTransform(Eigen::Matrix4f::Identity());\n    projectionTransform.block<3,3>(0,0) = eigenVectorsPCA.transpose();\n    projectionTransform.block<3,1>(0,3) = -1.f * (projectionTransform.block<3,3>(0,0) * pcaCentroid.head<3>());\n    pcl::PointCloud<pcl::PointXYZI>::Ptr cloudPointsProjected (new pcl::PointCloud<pcl::PointXYZI>);\n\n\n\n    pcl::transformPointCloud(*cloud_plane, *cloudPointsProjected, projectionTransform);\n\n    // Get the minimum and maximum points of the transformed cloud.\n    pcl::PointXYZI minPoint, maxPoint;\n\n    pcl::getMinMax3D(*cloudPointsProjected, minPoint, maxPoint);\n\n    // save the centroid into the centroid vector\n    centroid_list.push_back(pcaCentroid);\n    // save dimenstion into dimension list\n    one_dimension[0] = maxPoint.x - minPoint.x;\n    one_dimension[1] = maxPoint.y - minPoint.y;\n    one_dimension[2] = maxPoint.z - minPoint.z;\n    dimension_list.push_back(one_dimension);\n\n\n    // Transform back\n    Eigen::Matrix4f bboxTransform(Eigen::Matrix4f::Identity());\n    bboxTransform.block<3,3>(0,0) = eigenVectorsPCA;\n\n    pcl::PointCloud<pcl::PointXYZI>::Ptr cloud_corners_pca (new pcl::PointCloud<pcl::PointXYZI>);\n    pcl::PointCloud<pcl::PointXYZI>::Ptr cloud_corners_base (new pcl::PointCloud<pcl::PointXYZI>);\n\n    cloud_corners_pca->points.push_back(minPoint);\n    cloud_corners_pca->points.push_back(maxPoint);\n\n    for (int i=0; i<cloud_corners_pca->points.size(); i++)\n    {\n      cloud_corners_pca->points[i].x -= projectionTransform(0,3);\n      cloud_corners_pca->points[i].y -= projectionTransform(1,3);\n      cloud_corners_pca->points[i].z -= projectionTransform(2,3);\n    }\n\n    pcl::transformPointCloud(*cloud_corners_pca, *cloud_corners_base, bboxTransform);\n\n    // Extract corners\n    std::vector<pcl::PointXYZI> c;\n    for (int i=0; i<cloud_corners_base->points.size(); i++)\n      c.push_back(cloud_corners_base->points[i]);\n\n    // Save list of corners\n    corners.push_back(c);\n  }\n}\n\n\nstruct tracked_cluster\n{\n  pcl::PointCloud<pcl::PointXYZI>::Ptr cloud;\n  double x, y;\n  double x_start, y_start;\n  double distance, distance_travelled;\n};\n\n\nint main(int argc, char **argv)\n{\n  ros::init(argc, argv, \"process_velodyne_rosbag\");\n  ros::NodeHandle node;\n\n  pub_cloud = node.advertise<sensor_msgs::PointCloud2>(\"/velo_rosbag/points\", 10);\n  pub_velo = node.advertise<sensor_msgs::PointCloud2>(\"/velodyne_points\", 10);\n\n\n\n  std::string bag_path;\n\n  // Parse input\n  if (argc > 1)\n  {\n    bag_path = argv[1];\n  }\n  else\n  {\n    std::cout << \"Error: Input the name of the bag file\\n\";\n    return 0;\n  }\n\n  // Open rosbag\n  rosbag::Bag bag;\n  bag.open(bag_path, rosbag::bagmode::Read);\n\n  std::vector<std::string> topics;\n  topics.push_back(std::string(\"/velodyne_points\"));\n  rosbag::View view(bag, rosbag::TopicQuery(topics));\n\n\n  // Process velodyne messages\n  double max_angle = DEG2RAD(15);\n  double min_angle = DEG2RAD(0);\n  double max_starting_distance = 70;\n  double min_starting_distance = 60;\n  double tracked_distance = -1;\n  double tracking_radius = 5;\n  bool is_tracking = false;\n\n  std::vector<tracked_cluster> tracked;\n\n  std::ofstream myfile;\n  myfile.open (\"velodyne_points.csv\");\n  myfile << \"Average distance, Points, Average Intensity\\n\";\n\n  foreach(rosbag::MessageInstance const m, view)\n  {\n    if (!ros::ok())\n      break;\n\n    sensor_msgs::PointCloud2::ConstPtr msg = m.instantiate<sensor_msgs::PointCloud2>();\n\n    pcl::PointCloud<pcl::PointXYZI>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZI>);\n    pcl::fromROSMsg(*msg, *cloud);\n\n    // Filter out points outside a given angle\n    pcl::PointCloud<pcl::PointXYZI>::Ptr cloud_filtered(new pcl::PointCloud<pcl::PointXYZI>);\n    for (int i=0; i<cloud->points.size(); i++)\n    {\n      double x, y, z;\n      x = cloud->points[i].x;\n      y = cloud->points[i].y;\n      z = cloud->points[i].z;\n\n      double angle = atan2(y, x);\n      if (angle > max_angle || angle < min_angle)\n        continue;\n\n      cloud_filtered->points.push_back(cloud->points[i]);\n    }\n\n    // Get clusters\n    std::vector<pcl::PointCloud<pcl::PointXYZI>::Ptr> pc_vector;\n    getCloudClusters(cloud_filtered, pc_vector);\n\n    // Keep clusters with certain number of points\n    std::vector<pcl::PointCloud<pcl::PointXYZI>::Ptr> pc_vector_filtered;\n    for (int i=0; i<pc_vector.size(); i++)\n    {\n      int pc_size = pc_vector[i]->points.size();\n      if (pc_size > 20 || pc_size < 3)\n        continue;\n\n      pc_vector_filtered.push_back(pc_vector[i]);\n    }\n\n\n\n    // Get size of each cluster\n    std::vector<Eigen::Vector3f> dimension_list;\n    std::vector<Eigen::Vector4f> centroid_list;\n    std::vector<std::vector<pcl::PointXYZI> > corners_list;\n    computeBoundingBox(pc_vector, dimension_list, centroid_list, corners_list);\n\n    /*\n    for (int i=0; i<pc_vector.size(); i++)\n    {\n      double x = 0, y=0;\n\n      for (int pi=0; pi<pc_vector[i]->points.size(); pi++)\n      {\n        x +=pc_vector[i]->points[pi].x;\n        y +=pc_vector[i]->points[pi].y;\n      }\n\n      x /= pc_vector[i]->points.size();\n      y /= pc_vector[i]->points.size();\n\n      centroid_list[i][0] = x;\n      centroid_list[i][1] = y;\n    }\n    */\n\n\n    // Update tracked entries\n    for (int pci=0; pci<pc_vector.size(); pci++)\n    {\n      // Only keep the clusters that are likely to be panels\n      if (dimension_list[pci][2] > 1.5 || dimension_list[pci][1] > 1.5)\n        continue;\n\n\n      if (!is_tracking)\n      {\n        double x = centroid_list[pci][0];\n        double y = centroid_list[pci][1];\n        double r = sqrt(x*x + y*y);\n\n        if (r < min_starting_distance || r > max_starting_distance)\n          continue;\n      }\n\n\n      bool found = false;\n\n      // Update previous tracked entries\n      for (int ti=0; ti<tracked.size(); ti++)\n      {\n        // Check if we're in proximity\n        double x1 = centroid_list[pci][0] - tracked[ti].x;\n        double y1 = centroid_list[pci][1] - tracked[ti].y;\n        double dist = sqrt(x1*x1 + y1*y1);\n\n        if (dist > tracking_radius)\n          continue;\n        else\n          found = true;\n\n        // Check that the distance to velodyne has decreased within some tolerance\n        double x2 = centroid_list[pci][0];\n        double y2 = centroid_list[pci][1];\n        double dist2 = sqrt(x2*x2 + y2*y2);\n\n        double x3 = tracked[ti].x;\n        double y3 = tracked[ti].y;\n        double dist3 = sqrt(x3*x3 + y3*y3);\n\n        if (dist3 + 0.5 < dist2)\n          continue;\n\n        // Update\n        tracked[ti].cloud = pc_vector[pci];\n        tracked[ti].x = centroid_list[pci][0];\n        tracked[ti].y = centroid_list[pci][1];\n\n        x1 = tracked[ti].x - tracked[ti].x_start;\n        y1 = tracked[ti].y - tracked[ti].y_start;\n        tracked[ti].distance_travelled = sqrt(x1*x1 + y1*y1);\n        tracked[ti].distance = dist2;\n\n        // Write to file\n        if (is_tracking)\n        {\n          double intensity = 0;\n          double count = tracked[ti].cloud->points.size();\n\n          for (int idx=0; idx < count; idx++)\n          {\n            intensity += tracked[ti].cloud->points[idx].intensity;\n          }\n          intensity /= count;\n\n          myfile << dist2 << \", \" << count << \", \" << intensity << \"\\n\";\n        }\n\n      }\n\n      // Add new tracked entry\n      if (!found && !is_tracking)\n      {\n        tracked_cluster t;\n        t.x = centroid_list[pci][0];\n        t.y = centroid_list[pci][1];\n        t.x_start = centroid_list[pci][0];\n        t.y_start = centroid_list[pci][1];\n        t.distance_travelled = 0;\n        t.cloud = pc_vector[pci];\n\n        tracked.push_back(t);\n      }\n    }\n\n    // Filter out clusters that aren't likely to be our target\n    std::vector<tracked_cluster> tracked_temp;\n    for (int ti=0; ti<tracked.size(); ti++)\n    {\n      if (tracked[ti].distance_travelled > 5)\n      {\n        // Found our target\n        tracked_temp.clear();\n        tracked_temp.push_back(tracked[ti]);\n\n        is_tracking = true;\n        tracking_radius = 5;\n        break;\n      }\n\n      tracked_temp.push_back(tracked[ti]);\n    }\n\n    tracked = tracked_temp;\n\n    std::cout << \"Found \" << tracked.size() << \" clusters \\n\";\n\n    if (tracked.size() < 3)\n    {\n      // Publish velodyne cloud\n      sensor_msgs::PointCloud2 velo_msg;\n      velo_msg = *msg;\n      velo_msg.header.stamp = ros::Time::now();\n      pub_velo.publish(velo_msg);\n\n\n      for (int i=0; i<tracked.size(); i++)\n      {\n        // Publish cloud\n        sensor_msgs::PointCloud2 cloud_cluster_msg;\n        pcl::toROSMsg(*tracked[i].cloud, cloud_cluster_msg);\n        cloud_cluster_msg.header.frame_id = \"velodyne\";\n        cloud_cluster_msg.header.stamp = ros::Time::now();\n        pub_cloud.publish(cloud_cluster_msg);\n\n        {\n          ros::Rate r(30);\n          ros::spinOnce();\n          r.sleep();\n        }\n      }\n    }\n\n\n\n    /*\n\n    // Publish cloud\n    sensor_msgs::PointCloud2 cloud_cluster_msg;\n    pcl::toROSMsg(*cloud_filtered, cloud_cluster_msg);\n    cloud_cluster_msg.header.frame_id = \"velodyne\";\n    cloud_cluster_msg.header.stamp = ros::Time::now();\n    pub_cloud.publish(cloud_cluster_msg);\n\n    std::cout << cloud->points.size() << \" Got it \\n\";\n    std::cout << cloud->points[0].intensity << \"\\n\";\n    */\n\n    {\n      ros::Rate r(30);\n      ros::spinOnce();\n      r.sleep();\n    }\n    //break;\n  }\n\n\n  myfile.close();\n  bag.close();\n\n\n  return 0;\n}\n", "meta": {"hexsha": "ea93f51a92b6bc9b6a3c26c281706acbbd01f56e", "size": 12364, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kuri_mbzirc_challenge_2/src/process_velodyne_rosbag.cpp", "max_stars_repo_name": "kuri-kustar/kuri_mbzirc_challenge_2", "max_stars_repo_head_hexsha": "88ac9046ef7e7db20380dff068f6801e06b6cb33", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-06-14T08:03:49.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-14T08:03:49.000Z", "max_issues_repo_path": "kuri_mbzirc_challenge_2/src/process_velodyne_rosbag.cpp", "max_issues_repo_name": "kucars/kuri_mbzirc_challenge_2", "max_issues_repo_head_hexsha": "88ac9046ef7e7db20380dff068f6801e06b6cb33", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kuri_mbzirc_challenge_2/src/process_velodyne_rosbag.cpp", "max_forks_repo_name": "kucars/kuri_mbzirc_challenge_2", "max_forks_repo_head_hexsha": "88ac9046ef7e7db20380dff068f6801e06b6cb33", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-06-11T11:08:31.000Z", "max_forks_repo_forks_event_max_datetime": "2016-11-16T12:45:22.000Z", "avg_line_length": 29.508353222, "max_line_length": 227, "alphanum_fraction": 0.6442898738, "num_tokens": 3263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4888226603017421}}
{"text": "#include <cmath>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <gtest/gtest.h>\n\n// this is just testing the nan behavior of the built-in fma\n// there is no longer a stan::math::fma, just the agrad versions\n// instead, the top-level ::fma should be used by including <cmath>\n\nTEST(MathFunctions, fma) {\n  EXPECT_FLOAT_EQ(5.0, fma(1.0,2.0,3.0));\n  EXPECT_FLOAT_EQ(10.0, fma(2.0,3.0,4.0));\n}\n\nTEST(MathFunctions, fma_nan) {\n  double nan = std::numeric_limits<double>::quiet_NaN();\n  \n  EXPECT_PRED1(boost::math::isnan<double>,\n               fma(1.0, 2.0, nan));\n\n  EXPECT_PRED1(boost::math::isnan<double>,\n               fma(1.0, nan, 3.0));\n\n  EXPECT_PRED1(boost::math::isnan<double>,\n               fma(1.0, nan, nan));\n\n  EXPECT_PRED1(boost::math::isnan<double>,\n               fma(nan, 2.0, 3.0));\n\n  EXPECT_PRED1(boost::math::isnan<double>,\n               fma(nan, 2.0, nan));\n\n  EXPECT_PRED1(boost::math::isnan<double>,\n               fma(nan, nan, 3.0));\n\n  EXPECT_PRED1(boost::math::isnan<double>,\n               fma(nan, nan, nan));\n}\n", "meta": {"hexsha": "e1328eac5caea7312550b407c759b59f0c5a2bb8", "size": 1060, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/scal/fun/fma_test.cpp", "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/test/unit/math/prim/scal/fun/fma_test.cpp", "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/test/unit/math/prim/scal/fun/fma_test.cpp", "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": 27.8947368421, "max_line_length": 67, "alphanum_fraction": 0.6179245283, "num_tokens": 326, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.48882265404647146}}
{"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\n#include <armadillo>\n\n#include <omp.h>\n\n#include \"pme.h\"\n#include \"abort_unless.h\"\n\nusing namespace std;\nusing namespace arma;\n\nconst complex<double> I(0.0, 1.0);\n\nconst double sigma = pow(2.0, 1.0 / 6.0);\n\nint main(int argc, char* argv[]) {\n  if (argc < 7) {\n    cout << \"Usage: \" << argv[0]\n         << \" dimension cell-file positions-file charges-file cut-off tolerance\\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  // const double V = det(L);\n  L.print(\"L = \");\n\n  mat r;\n  r.load(argv[3]);\n  abort_unless(r.n_rows == 3);\n  // r.print(\"r = \");\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 tolerance = atof(argv[6]);\n  clog << \"Real space cut-off: \" << cut_off << \"\\n\"\n       << \"Real space tolerance: \" << tolerance << \"\\n\\n\";\n\n  mat forces = zeros<mat>(3, num_particles);\n  mat forces_cutoff = zeros<mat>(3, num_particles);\n  mat forces_direct = zeros<mat>(3, num_particles);\n  mat forces_recip = zeros<mat>(3, num_particles);\n\n  long double ErecipPME = 0.0L;\n  std::vector<double> forces_x(num_particles);\n  std::vector<double> forces_y(num_particles);\n  std::vector<double> forces_z(num_particles);\n  mat forcesPME = zeros<mat>(3, num_particles);\n    wall_clock timer;\n    timer.tic();\n\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    ewald::pme p(dim0, dim1, dim2, LL, \n                 num_particles, &q[0], \n                 cut_off, tolerance, \n                 omp_get_max_threads());\n\n    double seconds = timer.toc();\n    clog << \"PME initialization took \" << seconds << \" seconds.\\n\\n\";\n\n    timer.tic();\n\n    ErecipPME = p.energy(&coor_x[0], &coor_y[0], &coor_z[0],\n                         &forces_x[0], &forces_y[0], &forces_z[0]);\n\n    for (size_t k = 0; k < num_particles; ++k) {\n      forcesPME(0, k) = forces_x[k];\n      forcesPME(1, k) = forces_y[k];\n      forcesPME(2, k) = forces_z[k];\n    }\n\n    seconds = timer.toc();\n    clog << \"PME took \" << seconds << \" seconds.\\n\\n\";\n\n  long double Ebrute = 0.0L, Edirect = 0.0L;\n  long double Ecutoff = 0.0L;\n  const long double Eextra = p.energy_extra();\n  const long double Eself  = p.energy_self();\n\n  mat forces_ewald, forces_pme;\n  \n  double elapsed = 0.0;\n  for (int n = 0; n < 1; 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 = (nx == 0 && ny == 0 && nz == 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          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              assert(r2 >= 1e-16);\n\n              Ebrute  += 0.5 * q[i] * q[j] / r6;\n              forces.col(i) -= -6.0 * q[i] * q[j] / r8 * v;\n\n              if (abs(nx) < 2 && abs(ny) < 2 && abs(nz) < 2) {\n                forces_cutoff.col(i) -= -6.0 * q[i] * q[j] / r8 * v;\n                Ecutoff = Ebrute;\n              }\n\n              vec::fixed<3> dv;\n              Edirect += 0.5 * q[i] * q[j] * p.direct_convergence_term(v.memptr(), dv.memptr());\n              forces_direct.col(i) -= q[i] * q[j] * dv;\n            }\n          }\n        }\n      }\n    }\n\n    elapsed += timer.toc();\n\n    const long double EtotalPME = Edirect + ErecipPME + Eextra - Eself;\n\n    forces_pme   = forces_direct + forcesPME;\n\n    cout << \"Real space computation over one shell took \" << elapsed << \" seconds.\" << \"\\n\"\n         << fixed << setprecision(16)\n         << \"Ecutoff      = \" << Ecutoff << \"\\n\"\n         << \"Etotal (PME) = \" << EtotalPME  << \"\\n\"\n         << \"Edirect + Erecip + Eextra - Eself = \" \n         << Edirect << \" + \" << ErecipPME << \" + \" << Eextra << \" - \" << Eself << \"\\n\";\n  }\n  \n  return 0;\n}\n", "meta": {"hexsha": "8699ae049314bfefc87cd209a972850f50dad784", "size": 5096, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "run-pme.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": "run-pme.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": "run-pme.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": 27.8469945355, "max_line_length": 96, "alphanum_fraction": 0.5174646782, "num_tokens": 1636, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681013541613, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4888014268551562}}
{"text": "#ifndef STAN_MATH_PRIM_FUN_INV_INC_BETA_HPP\n#define STAN_MATH_PRIM_FUN_INV_INC_BETA_HPP\n\n#include <stan/math/prim/meta.hpp>\n#include <stan/math/prim/err.hpp>\n#include <stan/math/prim/fun/boost_policy.hpp>\n#include <boost/math/special_functions/beta.hpp>\n\nnamespace stan {\nnamespace math {\n\n/**\n * The inverse of the normalized incomplete beta function of a, b, with\n * probability p.\n *\n * Used to compute the inverse cumulative density function for the beta\n * distribution.\n *\n * @param a Shape parameter a >= 0; a and b can't both be 0\n * @param b Shape parameter b >= 0\n * @param p Random variate. 0 <= p <= 1\n * @throws if constraints are violated or if any argument is NaN\n * @return The inverse of the normalized incomplete beta function.\n */\ninline double inv_inc_beta(double a, double b, double p) {\n  check_not_nan(\"inv_inc_beta\", \"a\", a);\n  check_not_nan(\"inv_inc_beta\", \"b\", b);\n  check_not_nan(\"inv_inc_beta\", \"p\", p);\n  check_positive(\"inv_inc_beta\", \"a\", a);\n  check_positive(\"inv_inc_beta\", \"b\", b);\n  check_bounded(\"inv_inc_beta\", \"p\", p, 0, 1);\n  return boost::math::ibeta_inv(a, b, p, boost_policy_t<>());\n}\n\n}  // namespace math\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "920750b811293107e93a831f2623bf6534b6085e", "size": 1177, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/prim/fun/inv_inc_beta.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/fun/inv_inc_beta.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/fun/inv_inc_beta.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": 30.9736842105, "max_line_length": 71, "alphanum_fraction": 0.7145284622, "num_tokens": 327, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680904463333, "lm_q2_score": 0.5698526514141572, "lm_q1q2_score": 0.4888014206393016}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2014 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/finitedifferences/fdmdupire1dop.hpp>\n#include <ql/methods/finitedifferences/operators/secondderivativeop.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n\nnamespace QuantLib {\n\nFdmDupire1dOp::FdmDupire1dOp(const ext::shared_ptr<FdmMesher> &mesher,\n                             const Array &localVolatility)\n    : mesher_(mesher), localVolatility_(localVolatility),\n      mapT_(SecondDerivativeOp(0, mesher)\n                .mult(0.5 * localVolatility * localVolatility)) {}\n\nvoid FdmDupire1dOp::setTime(Time t1, Time t2) {}\n\nSize FdmDupire1dOp::size() const { return 1; }\n\nArray FdmDupire1dOp::apply(const Array &u) const {\n    return mapT_.apply(u);\n}\n\nArray FdmDupire1dOp::apply_direction(Size direction, const Array &r) const {\n    if (direction == 0)\n        return mapT_.apply(r);\n    QL_FAIL(\"direction too large\");\n}\n\nArray FdmDupire1dOp::apply_mixed(const Array &r) const {\n    return r;\n}\n\nArray FdmDupire1dOp::solve_splitting(Size direction, const Array &r, Real a) const {\n    if (direction == 0) {\n        return mapT_.solve_splitting(r, a, 1.0);\n    }\n    QL_FAIL(\"direction too large\");\n}\n\nArray FdmDupire1dOp::preconditioner(const Array &r, Real dt) const {\n\n    return solve_splitting(0, r, dt);\n}\n\nstd::vector<SparseMatrix> FdmDupire1dOp::toMatrixDecomp() const {\n    return std::vector<SparseMatrix>(1, mapT_.toMatrix());\n}\n\n}\n", "meta": {"hexsha": "f57a0e816e87f597b2b15eb93f440ac91d75758b", "size": 2169, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ql/experimental/finitedifferences/fdmdupire1dop.cpp", "max_stars_repo_name": "mshojatalab/QuantLib", "max_stars_repo_head_hexsha": "7801a0fb3226bc1b001e310bacdd35ddb2e51661", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-09-21T12:21:33.000Z", "max_stars_repo_stars_event_max_datetime": "2015-09-21T12:21:33.000Z", "max_issues_repo_path": "ql/experimental/finitedifferences/fdmdupire1dop.cpp", "max_issues_repo_name": "mshojatalab/QuantLib", "max_issues_repo_head_hexsha": "7801a0fb3226bc1b001e310bacdd35ddb2e51661", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2022-03-09T16:19:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T07:33:42.000Z", "max_forks_repo_path": "ql/experimental/finitedifferences/fdmdupire1dop.cpp", "max_forks_repo_name": "sweemer/QuantLib", "max_forks_repo_head_hexsha": "1341223e3d839dd77bb7231d0913809f01437740", "max_forks_repo_licenses": ["BSD-3-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.3731343284, "max_line_length": 84, "alphanum_fraction": 0.7196864915, "num_tokens": 593, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528094861981, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.48874693097073346}}
{"text": "#include <cassert>\n\n#include <dlib/svm.h>\n#include <dlib/svm_threaded.h>\n#include <dlib/global_optimization.h>\n\n#include \"common.hpp\"\n#include \"data.hpp\"\n\nnamespace SAMPML_NAMESPACE {\n    namespace trainer {\n        template <class sample_type>\n        class svm_classifier {\n        public:\n            svm_classifier() { }\n            \n            template <class SampleContainerPositive, class SampleContainerNegative>\n            void set_samples(const SampleContainerPositive& positives, const SampleContainerNegative& negatives) {\n                static_assert(std::is_same<typename SampleContainerPositive::value_type, sample_type>());\n                static_assert(std::is_same<typename SampleContainerNegative::value_type, sample_type>());\n\n                samples.clear();\n                samples.insert(samples.end(), positives.cbegin(), positives.cend());\n                samples.insert(samples.end(), negatives.cbegin(), negatives.cend());\n                labels.clear();\n                labels.insert(labels.end(), positives.size(), +1);\n                labels.insert(labels.end(), negatives.size(), -1);\n            }\n            \n            void train (double beta_squared = 1.0) {\n                if(samples.size() == 0) {\n                    throw bad_input(\"Bad Input: no samples were provided for training\");\n                }\n                assert(labels.size() == samples.size());\n\n                dlib::vector_normalizer<sample_type> normalizer;\n                normalizer.train(samples);\n                for(auto& vector : samples)\n                    vector = normalizer(vector);\n\n                dlib::randomize_samples(samples, labels);\n\n                auto cross_validation_score = \n                [this, beta_squared](double gamma, double cost_positive, double cost_negative) {\n                    dlib::svm_c_trainer<svm_kernel_type> trainer;\n                    trainer.set_kernel(svm_kernel_type(gamma));\n                    trainer.set_c_class1(cost_positive);\n                    trainer.set_c_class2(cost_negative);\n\n                    dlib::matrix<double> result = dlib::cross_validate_trainer(trainer, this->samples, this->labels, 10);\n                    std::cout << \"gamma: \" << gamma << \"  c1: \" << cost_positive <<  \"  c2: \" << cost_negative <<  \"  cross validation accuracy: \" << result;\n\n                    return (1.0 + beta_squared)*dlib::prod(result)/(beta_squared * result(0) + result(1));\n                };\n\n                auto result = dlib::find_max_global(dlib::default_thread_pool(), \n                                                    cross_validation_score, \n                                                    {1e-5, 1e-5, 1e-5}, {100,  1e6,  1e6},\n                                                    dlib::max_function_calls(50));\n\n                best_gamma = result.x(0);\n                best_cost_positive = result.x(1);\n                best_cost_negative = result.x(2);\n\n                dlib::svm_c_trainer<svm_kernel_type> trainer;\n                trainer.set_kernel(svm_kernel_type(best_gamma));\n                trainer.set_c_class1(best_cost_positive);\n                trainer.set_c_class2(best_cost_negative);\n \n                classifier.normalizer = normalizer;\n                classifier.function = dlib::train_probabilistic_decision_function(trainer, samples, labels, 3);\n            }\n\n            auto rank_features() {\n                dlib::kcentroid<svm_kernel_type> kc(svm_kernel_type(best_gamma), 0.0001);\n                return dlib::rank_features(kc, samples, labels);\n            } \n\n            void serialize(std::string classifier) {\n                dlib::serialize(classifier) << this->classifier;\n            }\n\n            void deserialize(std::string classifier) {\n                dlib::deserialize(classifier) >> this->classifier;\n            }\n\n            double test(const sample_type& sample) {\n                return classifier(sample);\n            }\n\n        protected:\n            std::vector<sample_type> samples;\n            std::vector<double> labels;\n\n            using svm_kernel_type = dlib::radial_basis_kernel<sample_type>;\n            using decision_funct_type = dlib::probabilistic_decision_function<svm_kernel_type>;\n            using normalized_decision_funct_type = dlib::normalized_function<decision_funct_type>;\n            normalized_decision_funct_type classifier;\n        \n            double best_gamma;\n            double best_cost_positive;\n            double best_cost_negative;\n        };\n    }\n}\n", "meta": {"hexsha": "c6bedacd03e7d1516cfe6227e63112274a34ead9", "size": 4521, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sampml/sampml/svm_classifier.hpp", "max_stars_repo_name": "YashasSamaga/sampml", "max_stars_repo_head_hexsha": "dc84110b53b120caeeb4c0234fcfd6ab16793c59", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2018-12-01T18:30:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-08T21:53:36.000Z", "max_issues_repo_path": "sampml/sampml/svm_classifier.hpp", "max_issues_repo_name": "YashasSamaga/sampml", "max_issues_repo_head_hexsha": "dc84110b53b120caeeb4c0234fcfd6ab16793c59", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-08-21T17:52:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-17T03:28:11.000Z", "max_forks_repo_path": "sampml/sampml/svm_classifier.hpp", "max_forks_repo_name": "YashasSamaga/sampml", "max_forks_repo_head_hexsha": "dc84110b53b120caeeb4c0234fcfd6ab16793c59", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-09-04T14:53:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T17:53:33.000Z", "avg_line_length": 42.6509433962, "max_line_length": 157, "alphanum_fraction": 0.5646980756, "num_tokens": 872, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.851952809486198, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4887469309707334}}
{"text": "#include <string>\n#include <Eigen/Dense>\n\n#include <gtest/gtest.h>\n\nnamespace dr {\n\n/// Convert an eigen vector to a terser string.\nstd::string toString(Eigen::Vector3d const & v) {\n\treturn \"[\" + std::to_string(v[0]) + \", \" + std::to_string(v[1]) + \", \" + std::to_string(v[2]) + \"]\";\n}\n\n\nstd::string toString(Eigen::AngleAxisd const & a) {\n\tEigen::Vector3d axis = a.axis();\n\treturn \"[\" + std::to_string(axis[0]) + \", \" + std::to_string(axis[1]) + \", \" +\n\t\tstd::to_string(axis[2]) + \", \" + std::to_string(a.angle()) + \"]\";\n}\n\nstd::string toString(Eigen::Isometry3d const & a) {\n\treturn toString(a.translation()) + toString(Eigen::AngleAxisd(a.rotation()));\n}\n\n/// Test if two Eigen vectors are exactly equal.\ntesting::AssertionResult testEqual(Eigen::Vector3d const & expected, Eigen::Vector3d const & actual) {\n\tif (expected.x() == actual.x() && expected.y() == actual.y() && expected.z() == actual.z()) {\n\t\treturn testing::AssertionSuccess();\n\t} else {\n\t\treturn testing::AssertionFailure() << \"actual (\" << toString(actual) << \") does not equal expected (\" << toString(expected) << \")\";\n\t}\n}\n\n/// Test if two Eigen vectors are within tolerance of eachother.\ntesting::AssertionResult testNear(Eigen::Vector3d const & expected, Eigen::Vector3d const & actual, Eigen::Vector3d const & tolerance = {0.001, 0.001, 0.001}) {\n\tauto diff = (expected - actual).cwiseAbs();\n\tif ((diff.array() <= tolerance.array()).all()) {\n\t\treturn testing::AssertionSuccess();\n\t} else {\n\t\treturn testing::AssertionFailure() << \"actual (\" << toString(actual) << \") is not within tolerance (\" << toString(tolerance) << \") of expected (\" << toString(expected) << \")\";\n\t}\n}\n\n/// Test if two Eigen rotation axes are within tolerance of eachother.\ntesting::AssertionResult testNear(Eigen::AngleAxisd const & expected, Eigen::AngleAxisd const & actual, float tolerance = 0.001) {\n\tif (actual.isApprox(expected, tolerance)) {\n\t\treturn testing::AssertionSuccess();\n\t} else {\n\t\treturn testing::AssertionFailure() << \"actual (\" << toString(actual) << \") is not within tolerance (\" << std::to_string(tolerance) << \") of expected (\" << toString(expected) << \")\";\n\t}\n}\n\n/// Test if two Eigen isometries are within tolerance of each other.\ntesting::AssertionResult testNear(Eigen::Isometry3d const & expected, Eigen::Isometry3d const & actual, float tolerance = 0.001) {\n\tif (\n\t\ttestNear(Eigen::Vector3d(expected.translation()), Eigen::Vector3d(actual.translation()), Eigen::Vector3d(tolerance, tolerance, tolerance)) &&\n\t\ttestNear(Eigen::AngleAxisd(Eigen::Quaterniond(expected.rotation())), Eigen::AngleAxisd(Eigen::Quaterniond(actual.rotation())), tolerance)\n\t) {\n\t\treturn testing::AssertionSuccess();\n\t} else {\n\t\treturn testing::AssertionFailure() << \"actual (\" << toString(actual) << \") is not within tolerance (\" << std::to_string(tolerance) << \") of expected (\" << toString(expected) << \")\";\n\t}\n}\n\n}\n", "meta": {"hexsha": "ae8508acf2971c966c49829ab57fbcb846f8734d", "size": 2867, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/dr_eigen/test/compare.hpp", "max_stars_repo_name": "delftrobotics/dr_eigen", "max_stars_repo_head_hexsha": "47022c2e1648c1b514ff493b25b3ebe54a7ddc7d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-06-02T14:14:37.000Z", "max_stars_repo_stars_event_max_datetime": "2017-06-02T14:14:37.000Z", "max_issues_repo_path": "include/dr_eigen/test/compare.hpp", "max_issues_repo_name": "delftrobotics/dr_eigen", "max_issues_repo_head_hexsha": "47022c2e1648c1b514ff493b25b3ebe54a7ddc7d", "max_issues_repo_licenses": ["Apache-2.0"], "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/dr_eigen/test/compare.hpp", "max_forks_repo_name": "delftrobotics/dr_eigen", "max_forks_repo_head_hexsha": "47022c2e1648c1b514ff493b25b3ebe54a7ddc7d", "max_forks_repo_licenses": ["Apache-2.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.1076923077, "max_line_length": 183, "alphanum_fraction": 0.6731775375, "num_tokens": 725, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056167854461, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.4887308713264164}}
{"text": "#include <iostream>\n#include <vector>\n#include <string>\n#include <boost/algorithm/string.hpp>\n#include <boost/foreach.hpp>\n#include <cstdlib>\n#include <cmath>\n#include <cstdio>\nusing namespace std;\n\n// \u5408\u8a08\ndouble sum(vector<double> n){\n  double res = 0;\n  BOOST_FOREACH(double m, n)\n    res += m;\n  return res;\n}\n\n// \u5e73\u5747\ndouble average(vector<double> n){\n  return sum(n)/n.size();\n}\n\n// \u81ea\u4e57\u5e73\u5747\ndouble saverage(vector<double> n){\n  BOOST_FOREACH(double& m, n)\n    m *= m;\n  return average(n)/n.size();\n}\n\n// \u5206\u6563\ndouble variance(vector<double> n){\n  vector<double> data;\n  double a = average(n);\n  BOOST_FOREACH(double m, n)\n    data.push_back(m-a);\n  return saverage(data);\n}\n\nint main(void){\n  vector<vector<double>> dataset;\n\n  while(true){\n    string input;\n    vector<string> strs;\n\n    cin >> input;\n    if(input == \"0\") break;\n\n    getline(cin, input);\n    boost::split(strs, input, boost::is_space());\n    BOOST_FOREACH(string m, strs) cout << m << endl;\n    cout << endl;\n    vector<double> d;\n    BOOST_FOREACH(string s, strs){\n      d.push_back(atoi(s.c_str()));\n    }\n    dataset.push_back(d);\n  }\n\n  BOOST_FOREACH(vector<double> ds, dataset){\n    cout << sqrt(variance(ds)) << endl;\n  }\n}\n", "meta": {"hexsha": "e1ddfbc43dddb46cfd6c7068dd91c18cc3a97018", "size": 1195, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kpc000n/10002.cpp", "max_stars_repo_name": "utgw/programming-contest", "max_stars_repo_head_hexsha": "eb7f28ae913296c6f4f9a8136dca8bd321e01e79", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "kpc000n/10002.cpp", "max_issues_repo_name": "utgw/programming-contest", "max_issues_repo_head_hexsha": "eb7f28ae913296c6f4f9a8136dca8bd321e01e79", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kpc000n/10002.cpp", "max_forks_repo_name": "utgw/programming-contest", "max_forks_repo_head_hexsha": "eb7f28ae913296c6f4f9a8136dca8bd321e01e79", "max_forks_repo_licenses": ["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.3846153846, "max_line_length": 52, "alphanum_fraction": 0.6343096234, "num_tokens": 324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.48869565437796303}}
{"text": "#include <iostream>>\n#include <Eigen\\Dense>\n\nusing namespace Eigen;\nusing namespace std;\n\nvoid main() {\n\t{\n\t\tMatrixXi mat(3, 3);\n\t\tmat << 1, 2, 3, 4, 5, 6, 7, 8, 9;\n\t\tcout << \"mat = \\n\" << mat << endl;\n\n\t\t// This assignment shows the aliasing problem\n\t\tmat.bottomRightCorner(2, 2) = mat.topLeftCorner(2, 2);\n\t\tcout << \"After the assignment, mat =\\n\" << mat << endl;\n\t\tcout << \"--> The aliasing problem\" << endl << endl;\n\t}\n\t{\n\t\tMatrix2i a; a << 1, 2, 3, 4;\n\t\tcout << \"Matrix a =\\n\" << a << endl;\n\t\t//a = a.transpose(); // !!! do NOT do this !!!\n\t\t//cout << \"Another aliasing problem with a = a.tranpose().\" << endl;\n\t}\n\tcout << \"------------\" << endl;\n\tcout << \"Resolving aliasing issues\" << endl;\n\t{\n\t\tMatrixXi mat(3, 3);\n\t\tmat << 1, 2, 3, 4, 5, 6, 7, 8, 9;\n\t\tcout << \"mat = \\n\" << mat << endl;\n\t\tmat.bottomRightCorner(2, 2) = mat.topLeftCorner(2, 2).eval();\n\t\tcout << \"After the assignment with .eval(), mat = \\n\" << mat << endl;\n\t}\n\t{\n\t\tMatrix2i a; a << 1, 2, 3, 4;\n\t\tcout << \"Matrix a =\\n\" << a << endl;\n\t\ta.transposeInPlace();\n\t\tcout << \"After the transposeInPlace(), a = \\n\" << a << endl;\n\t}\n\tcout << \"-------------\" << endl;\n\tcout << \"Aliasing and component-wise operations\" << endl;\n\t{\n\t\tMatrixXf mat(2, 2);\n\t\tmat << 1, 2, 4, 7;\n\t\tcout << \"mat = \\n\" << mat << endl;\n\t\tmat = 2 * mat;\n\t\tcout << \"after mat = 2 * mat \\n\" << mat << endl;\n\t\tmat = mat - MatrixXf::Identity(2, 2);\n\t\tcout << \"After the subtraction: - Identity(2,2)\\n\" << mat << endl;\n\n\t\tArrayXXf arr = mat;\n\t\tarr = arr.square();\n\t\tcout << \"After squaring \\n\" << arr << endl;\n\n\t\tmat << 1, 2, 4, 7;\n\t\tmat = (2 * mat - MatrixXf::Identity(2, 2)).array().square();\n\t\tcout << \"Doing everything at once \\n\" << mat << endl;\n\t}\n\n\t{\n\t\tcout << \"-------------\" << endl;\n\t\tcout << \"In matrix multiplication, Eigen assumes aliasing by default under the condition that the dest matrix is not resized\" << endl;\n\t\tMatrixXf matA(2, 2);\n\t\tmatA << 2, 0, 0, 2;\n\t\tmatA = matA * matA;\n\t\tcout << \"matA=\\n\" << matA << endl;\n\t\tcout << \"---> Eigen evaluates the product in a temporary matrix\" << endl;\n\t}\n\t{\n\t\tcout << \"---> Use .noalias() to indicate there is no aliasing\" << endl;\n\t\tMatrixXf matA(2, 2), matB(2, 2);\n\t\tmatA << 2, 0, 0, 2;\n\t\t// Simple but not quite as efficient\n\t\tmatB = matA * matA;\n\t\tcout << matB << endl << endl;\n\t\t// More complicated but also more efficient\n\t\tmatB.noalias() = matA * matA;\n\t\tcout << matB << endl;\n\t}\n\t{\n\t\tcout << \"aliasing is NOT assumsed if the dest matrix is resized\" << endl;\n\t\t{\n\t\t\tMatrixXf A(2, 2), B(3, 2);\n\t\t\tB << 2, 0, 0, 3, 1, 1;\n\t\t\tA << 2, 0, 0, -2;\n\t\t\tcout << \"B* A\\n\" << B* A << endl;\n\t\t\tA = (B * A).cwiseAbs(); // aliasing problem\n\t\t\tcout << A << endl;\n\t\t}\n\t\t{\n\t\t\tMatrixXf A(2, 2), B(3, 2);\n\t\t\tB << 2, 0, 0, 3, 1, 1;\n\t\t\tA << 2, 0, 0, -2;\n\t\t\tA = (B * A).eval().cwiseAbs();\n\t\t\tcout << A << endl;\n\t\t}\n\t}\n\n\tsystem(\"pause\");\n}", "meta": {"hexsha": "f86ae5f848f2ac371d66fc8d9e03179578c57095", "size": 2811, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/eigen/eigen/aliasing/aliasing.cpp", "max_stars_repo_name": "quanhua92/learning-notes", "max_stars_repo_head_hexsha": "a9c50d3955c51bb58f4b012757c550b76c5309ef", "max_stars_repo_licenses": ["Apache-2.0"], "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/eigen/eigen/aliasing/aliasing.cpp", "max_issues_repo_name": "quanhua92/learning-notes", "max_issues_repo_head_hexsha": "a9c50d3955c51bb58f4b012757c550b76c5309ef", "max_issues_repo_licenses": ["Apache-2.0"], "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/eigen/eigen/aliasing/aliasing.cpp", "max_forks_repo_name": "quanhua92/learning-notes", "max_forks_repo_head_hexsha": "a9c50d3955c51bb58f4b012757c550b76c5309ef", "max_forks_repo_licenses": ["Apache-2.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.3939393939, "max_line_length": 136, "alphanum_fraction": 0.535396656, "num_tokens": 1067, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.7461390043208003, "lm_q1q2_score": 0.48864250106243334}}
{"text": "\n\n/* --------------------------------------------------------------------- \n * \n * Copyright (C) 2018 - 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 at \n * the top level of the deal.II distribution. \n * \n * --------------------------------------------------------------------- \n * \n * Author: Daniel Garcia-Sanchez, CNRS, 2019 \n */ \n\n\n// @sect3{Include files}  \n\n// \u6211\u4eec\u5728\u8fd9\u4e2a\u7a0b\u5e8f\u4e2d\u9700\u8981\u7684\u5927\u90e8\u5206\u5305\u542b\u6587\u4ef6\u5df2\u7ecf\u5728\u4ee5\u524d\u7684\u7a0b\u5e8f\u4e2d\u8ba8\u8bba\u8fc7\u4e86\uff0c\u7279\u522b\u662f\u5728  step-40  .\n\n#include <deal.II/base/conditional_ostream.h> \n#include <deal.II/base/function.h> \n\n#include <deal.II/base/index_set.h> \n#include <deal.II/base/quadrature_lib.h> \n#include <deal.II/base/timer.h> \n#include <deal.II/base/utilities.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/fe_values.h> \n\n#include <deal.II/grid/grid_generator.h> \n#include <deal.II/grid/grid_refinement.h> \n\n#include <deal.II/lac/affine_constraints.h> \n#include <deal.II/lac/dynamic_sparsity_pattern.h> \n#include <deal.II/lac/full_matrix.h> \n#include <deal.II/lac/generic_linear_algebra.h> \n#include <deal.II/lac/petsc_solver.h> \n#include <deal.II/lac/vector.h> \n\n#include <deal.II/numerics/data_out.h> \n#include <deal.II/numerics/error_estimator.h> \n\n#include <fstream> \n#include <iostream> \n\n// \u4e0b\u9762\u7684\u6807\u5934\u63d0\u4f9b\u4e86\u6211\u4eec\u7528\u6765\u8868\u793a\u6750\u6599\u5c5e\u6027\u7684\u5f20\u91cf\u7c7b\u3002\n\n#include <deal.II/base/tensor.h> \n\n// \u4e0b\u9762\u7684\u6807\u5934\u5bf9\u4e8edeal.II\u7684HDF5\u63a5\u53e3\u662f\u5fc5\u8981\u7684\u3002\n\n#include <deal.II/base/hdf5.h> \n\n// \u8fd9\u4e2a\u5934\u662f\u6211\u4eec\u7528\u6765\u8bc4\u4f30\u6a21\u62df\u7ed3\u679c\u7684\u51fd\u6570 VectorTools::point_value \u6240\u9700\u8981\u7684\u3002\n\n#include <deal.II/numerics/vector_tools.h> \n\n// \u6211\u4eec\u5728\u51fd\u6570 GridTools::find_active_cell_around_point \u4e2d\u4f7f\u7528\u7684\u51fd\u6570 `ElasticWave::store_frequency_step_data()` \u9700\u8981\u8fd9\u4e9b\u5934\u6587\u4ef6\u3002\n#include <deal.II/grid/grid_tools.h> \n#include <deal.II/grid/grid_tools_cache.h> \n\nnamespace step62 \n{ \n  using namespace dealii; \n// @sect3{Auxiliary classes and functions}  \u4e0b\u5217\u7c7b\u7528\u4e8e\u5b58\u50a8\u6a21\u62df\u7684\u53c2\u6570\u3002\n\n//  @sect4{The `RightHandSide` class}  \u8be5\u7c7b\u7528\u4e8e\u5b9a\u4e49\u7ed3\u6784\u5de6\u4fa7\u7684\u529b\u8109\u51b2\u3002\n\n  template <int dim> \n  class RightHandSide : public Function<dim> \n  { \n  public: \n    RightHandSide(HDF5::Group &data); \n\n    virtual double value(const Point<dim> & p, \n                         const unsigned int component) const override; \n\n  private: \n\n// \u53d8\u91cf`data`\u662f HDF5::Group \uff0c\u6240\u6709\u7684\u6a21\u62df\u7ed3\u679c\u90fd\u5c06\u88ab\u50a8\u5b58\u5728\u5176\u4e2d\u3002\u8bf7\u6ce8\u610f\uff0c `RightHandSide::data`, \u53d8\u91cf \n// `PML::data`,  \n// `Rho::data` \u548c `Parameters::data` \u6307\u5411HDF5\u6587\u4ef6\u7684\u540c\u4e00\u4e2a\u7ec4\u3002\u5f53 HDF5::Group \u88ab\u590d\u5236\u65f6\uff0c\u5b83\u5c06\u6307\u5411HDF5\u6587\u4ef6\u7684\u540c\u4e00\u7ec4\u3002\n\n    HDF5::Group data; \n\n// \u4eff\u771f\u53c2\u6570\u4f5c\u4e3aHDF5\u5c5e\u6027\u5b58\u50a8\u5728`data`\u4e2d\u3002\u4ee5\u4e0b\u5c5e\u6027\u5728jupyter\u7b14\u8bb0\u672c\u4e2d\u5b9a\u4e49\uff0c\u4f5c\u4e3aHDF5\u5c5e\u6027\u5b58\u50a8\u5728`data`\u4e2d\uff0c\u7136\u540e\u7531\u6784\u9020\u51fd\u6570\u8bfb\u53d6\u3002\n\n    const double     max_force_amplitude; \n    const double     force_sigma_x; \n    const double     force_sigma_y; \n    const double     max_force_width_x; \n    const double     max_force_width_y; \n    const Point<dim> force_center; \n\n  public: \n\n// \u5728\u8fd9\u4e2a\u7279\u5b9a\u7684\u6a21\u62df\u4e2d\uff0c\u529b\u53ea\u6709\u4e00\u4e2a $x$ \u5206\u91cf\uff0c $F_y=0$  \u3002\n\n    const unsigned int force_component = 0; \n  }; \n// @sect4{The `PML` class}  \u8fd9\u4e2a\u7c7b\u662f\u7528\u6765\u5b9a\u4e49\u5b8c\u7f8e\u5339\u914d\u5c42\uff08PML\uff09\u7684\u5f62\u72b6\uff0c\u4ee5\u5438\u6536\u5411\u8fb9\u754c\u4f20\u64ad\u7684\u6ce2\u3002\n\n  template <int dim> \n  class PML : public Function<dim, std::complex<double>> \n  { \n  public: \n    PML(HDF5::Group &data); \n\n    virtual std::complex<double> \n    value(const Point<dim> &p, const unsigned int component) const override; \n\n  private: \n// HDF5::Group \uff0c\u6240\u6709\u7684\u6a21\u62df\u7ed3\u679c\u5c06\u88ab\u5b58\u50a8\u5728\u5176\u4e2d\u3002\n\n    HDF5::Group data; \n\n// \u548c\u4ee5\u524d\u4e00\u6837\uff0c\u4ee5\u4e0b\u5c5e\u6027\u5728jupyter\u7b14\u8bb0\u672c\u4e2d\u5b9a\u4e49\uff0c\u4f5c\u4e3aHDF5\u5c5e\u6027\u5b58\u50a8\u5728`data`\u4e2d\uff0c\u7136\u540e\u7531\u6784\u9020\u51fd\u6570\u8bfb\u53d6\u3002\n\n    const double pml_coeff; \n    const int    pml_coeff_degree; \n    const double dimension_x; \n    const double dimension_y; \n    const bool   pml_x; \n    const bool   pml_y; \n    const double pml_width_x; \n    const double pml_width_y; \n    const double a_coeff_x; \n    const double a_coeff_y; \n  }; \n\n//  @sect4{The `Rho` class}  \u8fd9\u4e2a\u7c7b\u662f\u7528\u6765\u5b9a\u4e49\u8d28\u91cf\u5bc6\u5ea6\u7684\u3002\n\n  template <int dim> \n  class Rho : public Function<dim> \n  { \n  public: \n    Rho(HDF5::Group &data); \n\n    virtual double value(const Point<dim> & p, \n                         const unsigned int component = 0) const override; \n\n  private: \n// HDF5::Group \uff0c\u6240\u6709\u7684\u6a21\u62df\u7ed3\u679c\u5c06\u88ab\u5b58\u50a8\u5728\u5176\u4e2d\u3002\n\n    HDF5::Group data; \n\n// \u548c\u4ee5\u524d\u4e00\u6837\uff0c\u4ee5\u4e0b\u5c5e\u6027\u5728jupyter\u7b14\u8bb0\u672c\u4e2d\u5b9a\u4e49\uff0c\u4f5c\u4e3aHDF5\u5c5e\u6027\u5b58\u50a8\u5728`data`\u4e2d\uff0c\u7136\u540e\u7531\u6784\u9020\u51fd\u6570\u8bfb\u53d6\u3002\n\n    const double       lambda; \n    const double       mu; \n    const double       material_a_rho; \n    const double       material_b_rho; \n    const double       cavity_resonance_frequency; \n    const unsigned int nb_mirror_pairs; \n    const double       dimension_y; \n    const unsigned int grid_level; \n    double             average_rho_width; \n  }; \n\n//  @sect4{The `Parameters` class}  \u8be5\u7c7b\u5305\u542b\u6240\u6709\u5c06\u5728\u6a21\u62df\u4e2d\u4f7f\u7528\u7684\u53c2\u6570\u3002\n\n  template <int dim> \n  class Parameters \n  { \n  public: \n    Parameters(HDF5::Group &data); \n// HDF5::Group \uff0c\u6240\u6709\u7684\u6a21\u62df\u7ed3\u679c\u5c06\u88ab\u5b58\u50a8\u5728\u5176\u4e2d\u3002\n\n    HDF5::Group data; \n\n// \u548c\u4ee5\u524d\u4e00\u6837\uff0c\u4ee5\u4e0b\u5c5e\u6027\u5728jupyter\u7b14\u8bb0\u672c\u4e2d\u5b9a\u4e49\uff0c\u4f5c\u4e3aHDF5\u5c5e\u6027\u5b58\u50a8\u5728`data`\u4e2d\uff0c\u7136\u540e\u7531\u6784\u9020\u51fd\u6570\u8bfb\u53d6\u3002\n\n    const std::string        simulation_name; \n    const bool               save_vtu_files; \n    const double             start_frequency; \n    const double             stop_frequency; \n    const unsigned int       nb_frequency_points; \n    const double             lambda; \n    const double             mu; \n    const double             dimension_x; \n    const double             dimension_y; \n    const unsigned int       nb_probe_points; \n    const unsigned int       grid_level; \n    const Point<dim>         probe_start_point; \n    const Point<dim>         probe_stop_point; \n    const RightHandSide<dim> right_hand_side; \n    const PML<dim>           pml; \n    const Rho<dim>           rho; \n\n  private: \n    const double comparison_float_constant = 1e-12; \n  }; \n\n//  @sect4{The `QuadratureCache` class}  \u8d28\u91cf\u548c\u521a\u5ea6\u77e9\u9635\u7684\u8ba1\u7b97\u662f\u975e\u5e38\u6602\u8d35\u7684\u3002\u8fd9\u4e9b\u77e9\u9635\u5bf9\u6240\u6709\u7684\u9891\u7387\u6b65\u9aa4\u90fd\u662f\u4e00\u6837\u7684\u3002\u53f3\u624b\u8fb9\u7684\u5411\u91cf\u5bf9\u6240\u6709\u7684\u9891\u7387\u6b65\u957f\u4e5f\u662f\u4e00\u6837\u7684\u3002\u6211\u4eec\u7528\u8fd9\u4e2a\u7c7b\u6765\u5b58\u50a8\u8fd9\u4e9b\u5bf9\u8c61\uff0c\u5e76\u5728\u6bcf\u4e2a\u9891\u7387\u6b65\u9aa4\u4e2d\u91cd\u65b0\u4f7f\u7528\u5b83\u4eec\u3002\u8bf7\u6ce8\u610f\uff0c\u8fd9\u91cc\u6211\u4eec\u4e0d\u5b58\u50a8\u96c6\u5408\u7684\u8d28\u91cf\u548c\u521a\u5ea6\u77e9\u9635\u4ee5\u53ca\u53f3\u624b\u8fb9\uff0c\u800c\u662f\u5b58\u50a8\u5355\u4e2a\u5355\u5143\u7684\u6570\u636e\u3002QuadratureCache \"\u7c7b\u4e0e\u5728  step-18  \u4e2d\u4f7f\u7528\u8fc7\u7684 \"PointHistory \"\u7c7b\u975e\u5e38\u76f8\u4f3c\u3002\n\n  template <int dim> \n  class QuadratureCache \n  { \n  public: \n    QuadratureCache(const unsigned int dofs_per_cell); \n\n  private: \n    unsigned int dofs_per_cell; \n\n  public: \n\n// \u6211\u4eec\u5728\u53d8\u91cfmass_coefficient\u548cstiffness_coefficient\u4e2d\u5b58\u50a8\u8d28\u91cf\u548c\u521a\u5ea6\u77e9\u9635\u3002\u6211\u4eec\u8fd8\u5b58\u50a8\u4e86\u53f3\u624b\u8fb9\u548cJxW\u503c\uff0c\u8fd9\u4e9b\u503c\u5bf9\u6240\u6709\u7684\u9891\u7387\u6b65\u9aa4\u90fd\u662f\u4e00\u6837\u7684\u3002\n\n    FullMatrix<std::complex<double>>  mass_coefficient; \n    FullMatrix<std::complex<double>>  stiffness_coefficient; \n    std::vector<std::complex<double>> right_hand_side; \n    double                            JxW; \n  }; \n\n//  @sect4{The `get_stiffness_tensor()` function}  \n\n// \u8be5\u51fd\u6570\u8fd4\u56de\u6750\u6599\u7684\u521a\u5ea6\u5f20\u91cf\u3002\u4e3a\u4e86\u7b80\u5355\u8d77\u89c1\uff0c\u6211\u4eec\u8ba4\u4e3a\u521a\u5ea6\u662f\u5404\u5411\u540c\u6027\u548c\u540c\u8d28\u7684\uff1b\u53ea\u6709\u5bc6\u5ea6  $\\rho$  \u53d6\u51b3\u4e8e\u4f4d\u7f6e\u3002\u6b63\u5982\u6211\u4eec\u4e4b\u524d\u5728  step-8  \u4e2d\u6240\u8868\u660e\u7684\uff0c\u5982\u679c\u521a\u5ea6\u662f\u5404\u5411\u540c\u6027\u548c\u5747\u8d28\u7684\uff0c\u90a3\u4e48\u521a\u5ea6\u7cfb\u6570  $c_{ijkl}$  \u53ef\u4ee5\u8868\u793a\u4e3a\u4e24\u4e2a\u7cfb\u6570  $\\lambda$  \u548c  $\\mu$  \u7684\u51fd\u6570\u3002\u7cfb\u6570\u5f20\u91cf\u7b80\u5316\u4e3a \n// @f[\n//    c_{ijkl}\n//    =\n//    \\lambda \\delta_{ij} \\delta_{kl} +\n//    \\mu (\\delta_{ik} \\delta_{jl} + \\delta_{il} \\delta_{jk}).\n//  @f] \u3002\n\n  template <int dim> \n  SymmetricTensor<4, dim> get_stiffness_tensor(const double lambda, \n                                               const double mu) \n  { \n    SymmetricTensor<4, dim> stiffness_tensor; \n    for (unsigned int i = 0; i < dim; ++i) \n      for (unsigned int j = 0; j < dim; ++j) \n        for (unsigned int k = 0; k < dim; ++k) \n          for (unsigned int l = 0; l < dim; ++l) \n            stiffness_tensor[i][j][k][l] = \n              (((i == k) && (j == l) ? mu : 0.0) + \n               ((i == l) && (j == k) ? mu : 0.0) + \n               ((i == j) && (k == l) ? lambda : 0.0)); \n    return stiffness_tensor; \n  } \n\n//  @sect3{The `ElasticWave` class}  \n\n// \u63a5\u4e0b\u6765\u8ba9\u6211\u4eec\u58f0\u660e\u8fd9\u4e2a\u7a0b\u5e8f\u7684\u4e3b\u7c7b\u3002\u5b83\u7684\u7ed3\u6784\u4e0e step-40 \u7684\u6559\u7a0b\u7a0b\u5e8f\u975e\u5e38\u76f8\u4f3c\u3002\u4e3b\u8981\u7684\u533a\u522b\u662f\u3002\n\n// - \u626b\u8fc7\u7684\u9891\u7387\u503c\u3002\n\n// - \u6211\u4eec\u5c06\u521a\u5ea6\u548c\u8d28\u91cf\u77e9\u9635\u4fdd\u5b58\u5728`quadrature_cache`\u4e2d\uff0c\u5e76\u5728\u6bcf\u4e2a\u9891\u7387\u6b65\u9aa4\u4e2d\u4f7f\u7528\u5b83\u4eec\u3002\n\n// - \u6211\u4eec\u5728HDF5\u6587\u4ef6\u4e2d\u5b58\u50a8\u6bcf\u4e2a\u9891\u7387\u6b65\u9aa4\u7684\u63a2\u5934\u6d4b\u91cf\u7684\u80fd\u91cf\u3002\n\n  template <int dim> \n  class ElasticWave \n  { \n  public: \n    ElasticWave(const Parameters<dim> &parameters); \n    void run(); \n\n  private: \n    void setup_system(); \n    void assemble_system(const double omega, \n                         const bool   calculate_quadrature_data); \n    void solve(); \n    void initialize_probe_positions_vector(); \n    void store_frequency_step_data(const unsigned int frequency_idx); \n    void output_results(); \n\n// \u5728\u6bcf\u4e2a\u9891\u7387\u6b65\u9aa4\u4e4b\u524d\u90fd\u4f1a\u8c03\u7528\u8fd9\u4e2a\uff0c\u4ee5\u4fbf\u4e3a\u7f13\u5b58\u53d8\u91cf\u8bbe\u7f6e\u4e00\u4e2a\u539f\u59cb\u72b6\u6001\u3002\n\n    void setup_quadrature_cache(); \n\n// \u8fd9\u4e2a\u51fd\u6570\u5728\u9891\u7387\u5411\u91cf\u4e0a\u5faa\u73af\uff0c\u5e76\u5728\u6bcf\u4e2a\u9891\u7387\u6b65\u9aa4\u4e0a\u8fd0\u884c\u6a21\u62df\u3002\n\n    void frequency_sweep(); \n\n// \u53c2\u6570\u5b58\u50a8\u5728\u8fd9\u4e2a\u53d8\u91cf\u4e2d\u3002\n\n    Parameters<dim> parameters; \n\n    MPI_Comm mpi_communicator; \n\n    parallel::distributed::Triangulation<dim> triangulation; \n\n    QGauss<dim> quadrature_formula; \n\n// \u6211\u4eec\u5c06\u6bcf\u4e2a\u5355\u5143\u7684\u8d28\u91cf\u548c\u521a\u5ea6\u77e9\u9635\u5b58\u50a8\u5728\u8fd9\u4e2a\u5411\u91cf\u4e2d\u3002\n\n    std::vector<QuadratureCache<dim>> quadrature_cache; \n\n    FESystem<dim>   fe; \n    DoFHandler<dim> dof_handler; \n\n    IndexSet locally_owned_dofs; \n    IndexSet locally_relevant_dofs; \n\n    AffineConstraints<std::complex<double>> constraints; \n\n    LinearAlgebraPETSc::MPI::SparseMatrix system_matrix; \n    LinearAlgebraPETSc::MPI::Vector       locally_relevant_solution; \n    LinearAlgebraPETSc::MPI::Vector       system_rhs; \n\n// \u8fd9\u4e2a\u5411\u91cf\u5305\u542b\u6211\u4eec\u8981\u6a21\u62df\u7684\u9891\u7387\u8303\u56f4\u3002\n\n    std::vector<double> frequency; \n\n// \u8fd9\u4e2a\u5411\u91cf\u5305\u542b\u4e86\u6d4b\u91cf\u63a2\u5934\u5404\u70b9\u7684\u5750\u6807 $(x,y)$ \u3002\n\n    FullMatrix<double> probe_positions; \n\n// HDF5\u6570\u636e\u96c6\u6765\u5b58\u50a8\u9891\u7387\u548c`\u63a2\u5934\u4f4d\u7f6e`\u5411\u91cf\u3002\n\n    HDF5::DataSet frequency_dataset; \n    HDF5::DataSet probe_positions_dataset; \n\n// HDF5\u6570\u636e\u96c6\uff0c\u5b58\u50a8\u63a2\u5934\u6d4b\u91cf\u7684\u80fd\u91cf\u503c\u3002\n\n    HDF5::DataSet displacement; \n\n    ConditionalOStream pcout; \n    TimerOutput        computing_timer; \n  }; \n\n//  @sect3{Implementation of the auxiliary classes}  \n// @sect4{The `RightHandSide` class implementation}  \n\n// \u6784\u9020\u51fd\u6570\u4f7f\u7528 HDF5::Group  `data`\u51fd\u6570\u4ece HDF5::Group::get_attribute()  \u8bfb\u53d6\u6240\u6709\u53c2\u6570\u3002\n\n  template <int dim> \n  RightHandSide<dim>::RightHandSide(HDF5::Group &data) \n    : Function<dim>(dim) \n    , data(data) \n    , max_force_amplitude(data.get_attribute<double>(\"max_force_amplitude\")) \n    , force_sigma_x(data.get_attribute<double>(\"force_sigma_x\")) \n    , force_sigma_y(data.get_attribute<double>(\"force_sigma_y\")) \n    , max_force_width_x(data.get_attribute<double>(\"max_force_width_x\")) \n    , max_force_width_y(data.get_attribute<double>(\"max_force_width_y\")) \n    , force_center(Point<dim>(data.get_attribute<double>(\"force_x_pos\"), \n                              data.get_attribute<double>(\"force_y_pos\"))) \n  {} \n\n//\u8fd9\u4e2a\u51fd\u6570\u5b9a\u4e49\u4e86\u529b\u77e2\u91cf\u8109\u51b2\u7684\u7a7a\u95f4\u5f62\u72b6\uff0c\u5b83\u91c7\u53d6\u9ad8\u65af\u51fd\u6570\n// @f{align*}\n//  F_x &=\n//  \\left\\{\n//  \\begin{array}{ll}\n//    a \\exp(- (\\frac{(x-b_x)^2 }{ 2 \\sigma_x^2}+\\frac{(y-b_y)^2 }{ 2\n//    \\sigma_y^2}))\n//  & \\text{if}\\, x_\\textrm{min} <x<x_\\textrm{max}\\, \\text{and}\\,\n//  y_\\textrm{min} <y<y_\\textrm{max}  \\\\ 0 & \\text{otherwise},\n//  \\end{array}\n//  \\right.\\\\ F_y &= 0\n//  @f}\n//  \u7684\u5f62\u5f0f\uff0c\u5176\u4e2d $a$ \u662f\u53d6\u529b\u7684\u6700\u5927\u632f\u5e45\uff0c $\\sigma_x$ \u548c $\\sigma_y$ \u662f $x$ \u548c $y$ \u5206\u91cf\u7684\u6807\u51c6\u504f\u5dee\u3002\u8bf7\u6ce8\u610f\uff0c\u8109\u51b2\u5df2\u88ab\u88c1\u526a\u4e3a $x_\\textrm{min}<x<x_\\textrm{max}$ \u548c $y_\\textrm{min} <y<y_\\textrm{max}$  \u3002\n\n  template <int dim> \n  double RightHandSide<dim>::value(const Point<dim> & p, \n                                   const unsigned int component) const \n  { \n    if (component == force_component) \n      { \n        if (std::abs(p[0] - force_center[0]) < max_force_width_x / 2 && \n            std::abs(p[1] - force_center[1]) < max_force_width_y / 2) \n          { \n            return max_force_amplitude * \n                   std::exp(-(std::pow(p[0] - force_center[0], 2) / \n                                (2 * std::pow(force_sigma_x, 2)) + \n                              std::pow(p[1] - force_center[1], 2) / \n                                (2 * std::pow(force_sigma_y, 2)))); \n          } \n        else \n          { \n            return 0; \n          } \n      } \n    else \n      { \n        return 0; \n      } \n  } \n\n//  @sect4{The `PML` class implementation}  \n\n// \u548c\u4ee5\u524d\u4e00\u6837\uff0c\u6784\u9020\u51fd\u6570\u4f7f\u7528 HDF5::Group \u51fd\u6570\u4ece HDF5::Group::get_attribute() `data`\u4e2d\u8bfb\u53d6\u6240\u6709\u53c2\u6570\u3002\u6b63\u5982\u6211\u4eec\u6240\u8ba8\u8bba\u7684\uff0c\u5728jupyter\u7b14\u8bb0\u672c\u4e2d\u5df2\u7ecf\u5b9a\u4e49\u4e86PML\u7684\u4e8c\u6b21\u5f00\u673a\u3002\u901a\u8fc7\u6539\u53d8\u53c2\u6570`pml_coeff_degree`\uff0c\u53ef\u4ee5\u4f7f\u7528\u7ebf\u6027\u3001\u7acb\u65b9\u6216\u5176\u4ed6\u5e42\u5ea6\u3002\u53c2\u6570`pml_x`\u548c`pml_y`\u53ef\u4ee5\u7528\u6765\u5f00\u542f\u548c\u5173\u95ed`x`\u548c`y`PML\u3002\n\n  template <int dim> \n  PML<dim>::PML(HDF5::Group &data) \n    : Function<dim, std::complex<double>>(dim) \n    , data(data) \n    , pml_coeff(data.get_attribute<double>(\"pml_coeff\")) \n    , pml_coeff_degree(data.get_attribute<int>(\"pml_coeff_degree\")) \n    , dimension_x(data.get_attribute<double>(\"dimension_x\")) \n    , dimension_y(data.get_attribute<double>(\"dimension_y\")) \n    , pml_x(data.get_attribute<bool>(\"pml_x\")) \n    , pml_y(data.get_attribute<bool>(\"pml_y\")) \n    , pml_width_x(data.get_attribute<double>(\"pml_width_x\")) \n    , pml_width_y(data.get_attribute<double>(\"pml_width_y\")) \n    , a_coeff_x(pml_coeff / std::pow(pml_width_x, pml_coeff_degree)) \n    , a_coeff_y(pml_coeff / std::pow(pml_width_y, pml_coeff_degree)) \n  {} \n\n// `x`\u90e8\u5206\u7684PML\u7cfb\u6570\u7684\u5f62\u5f0f\u4e3a  $s'_x = a_x x^{\\textrm{degree}}$  \u3002\n  template <int dim> \n  std::complex<double> PML<dim>::value(const Point<dim> & p, \n                                       const unsigned int component) const \n  { \n    double calculated_pml_x_coeff = 0; \n    double calculated_pml_y_coeff = 0; \n\n    if ((component == 0) && pml_x) \n      { \n        const double pml_x_start_position = dimension_x / 2 - pml_width_x; \n        if (std::abs(p[0]) > pml_x_start_position) \n          { \n            const double x_prime = std::abs(p[0]) - pml_x_start_position; \n            calculated_pml_x_coeff = \n              a_coeff_x * std::pow(x_prime, pml_coeff_degree); \n          } \n      } \n\n    if ((component == 1) && pml_y) \n      { \n        const double pml_y_start_position = dimension_y / 2 - pml_width_y; \n        if (std::abs(p[1]) > pml_y_start_position) \n          { \n            const double y_prime = std::abs(p[1]) - pml_y_start_position; \n            calculated_pml_y_coeff = \n              a_coeff_y * std::pow(y_prime, pml_coeff_degree); \n          } \n      } \n\n    return 1. + std::max(calculated_pml_x_coeff, calculated_pml_y_coeff) * \n                  std::complex<double>(0., 1.); \n  } \n\n//  @sect4{The `Rho` class implementation}  \n\n// \u8fd9\u4e2a\u7c7b\u662f\u7528\u6765\u5b9a\u4e49\u8d28\u91cf\u5bc6\u5ea6\u7684\u3002\u6b63\u5982\u6211\u4eec\u4e4b\u524d\u6240\u89e3\u91ca\u7684\uff0c\u4e00\u4e2a\u58f0\u5b66\u8d85\u6676\u683c\u7a7a\u8154\u662f\u7531\u4e24\u4e2a[\u5206\u5e03\u5f0f\u53cd\u5c04\u5668](https:en.wikipedia.org/wiki/Band_gap)\u3001\u955c\u5b50\u548c\u4e00\u4e2a $\\lambda/2$ \u7a7a\u8154\u7ec4\u6210\u7684\uff0c\u5176\u4e2d $\\lambda$ \u662f\u58f0\u6ce2\u957f\u3002\u58f0\u5b66DBRs\u662f\u4e00\u79cd\u5468\u671f\u6027\u7ed3\u6784\uff0c\u5176\u4e2d\u4e00\u7ec4\u5177\u6709\u5bf9\u6bd4\u6027\u7269\u7406\u7279\u6027\uff08\u58f0\u901f\u6307\u6570\uff09\u7684\u53cc\u5c42\u5806\u6808\u88ab\u91cd\u590d $N$ \u6b21\u3002\u6ce2\u901f\u7684\u53d8\u5316\u662f\u7531\u5177\u6709\u4e0d\u540c\u5bc6\u5ea6\u7684\u5c42\u4ea4\u66ff\u4ea7\u751f\u7684\u3002\n\n  template <int dim> \n  Rho<dim>::Rho(HDF5::Group &data) \n    : Function<dim>(1) \n    , data(data) \n    , lambda(data.get_attribute<double>(\"lambda\")) \n    , mu(data.get_attribute<double>(\"mu\")) \n    , material_a_rho(data.get_attribute<double>(\"material_a_rho\")) \n    , material_b_rho(data.get_attribute<double>(\"material_b_rho\")) \n    , cavity_resonance_frequency( \n        data.get_attribute<double>(\"cavity_resonance_frequency\")) \n    , nb_mirror_pairs(data.get_attribute<int>(\"nb_mirror_pairs\")) \n    , dimension_y(data.get_attribute<double>(\"dimension_y\")) \n    , grid_level(data.get_attribute<int>(\"grid_level\")) \n  { \n\n// \u4e3a\u4e86\u63d0\u9ad8\u7cbe\u5ea6\uff0c\u6211\u4eec\u4f7f\u7528[subpixel smoothing]\uff08https:meep.readthedocs.io/en/latest/Subpixel_Smoothing/\uff09\u3002\n\n    average_rho_width = dimension_y / (std::pow(2.0, grid_level)); \n    data.set_attribute(\"average_rho_width\", average_rho_width); \n  } \n\n  template <int dim> \n  double Rho<dim>::value(const Point<dim> &p, \n                         const unsigned int /*component*/) const \n  { \n\n// \u58f0\u901f\u7531\n// @f[\n//   c = \\frac{K_e}{\\rho}\n//  @f]\n//  \u5b9a\u4e49\uff0c\u5176\u4e2d $K_e$ \u662f\u6709\u6548\u5f39\u6027\u5e38\u6570\uff0c $\\rho$ \u662f\u5bc6\u5ea6\u3002\u8fd9\u91cc\u6211\u4eec\u8003\u8651\u7684\u662f\u6ce2\u5bfc\u5bbd\u5ea6\u8fdc\u5c0f\u4e8e\u6ce2\u957f\u7684\u60c5\u51b5\u3002\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0c\u53ef\u4ee5\u8bc1\u660e\u5bf9\u4e8e\u4e8c\u7ef4\u7684\u60c5\u51b5\n//  @f[\n//   K_e = 4\\mu\\frac{\\lambda +\\mu}{\\lambda+2\\mu}\n//  @f]\n//  \u548c\u4e09\u7ef4\u7684\u60c5\u51b5 $K_e$ \u7b49\u4e8e\u6768\u6c0f\u6a21\u91cf\u3002\n//  @f[\n//   K_e = \\mu\\frac{3\\lambda +2\\mu}{\\lambda+\\mu}\n//  @f]\n\n    double elastic_constant; \n    if (dim == 2) \n      { \n        elastic_constant = 4 * mu * (lambda + mu) / (lambda + 2 * mu); \n      } \n    else if (dim == 3) \n      { \n        elastic_constant = mu * (3 * lambda + 2 * mu) / (lambda + mu); \n      } \n    else \n      { \n        Assert(false, ExcInternalError()); \n      } \n    const double material_a_speed_of_sound = \n      std::sqrt(elastic_constant / material_a_rho); \n    const double material_a_wavelength = \n      material_a_speed_of_sound / cavity_resonance_frequency; \n    const double material_b_speed_of_sound = \n      std::sqrt(elastic_constant / material_b_rho); \n    const double material_b_wavelength = \n      material_b_speed_of_sound / cavity_resonance_frequency; \n\n//\u5bc6\u5ea6 $\\rho$ \u91c7\u53d6\u4ee5\u4e0b\u5f62\u5f0f <img alt=\"\u58f0\u5b66\u8d85\u6676\u683c\u7a7a\u8154\" src=\"https:www.dealii.org/images/steps/developer/  step-62  .04.svg\" height=\"200\" //\u5176\u4e2d\u68d5\u8272\u4ee3\u8868\u6750\u6599_a\uff0c\u7eff\u8272\u4ee3\u8868\u6750\u6599_b\u3002\n\n    for (unsigned int idx = 0; idx < nb_mirror_pairs; idx++) \n      { \n        const double layer_transition_center = \n          material_a_wavelength / 2 + \n          idx * (material_b_wavelength / 4 + material_a_wavelength / 4); \n        if (std::abs(p[0]) >= \n              (layer_transition_center - average_rho_width / 2) && \n            std::abs(p[0]) <= (layer_transition_center + average_rho_width / 2)) \n          { \n            const double coefficient = \n              (std::abs(p[0]) - \n               (layer_transition_center - average_rho_width / 2)) / \n              average_rho_width; \n            return (1 - coefficient) * material_a_rho + \n                   coefficient * material_b_rho; \n          } \n      } \n\n// \u8fd9\u91cc\u6211\u4eec\u5b9a\u4e49\u4e86[subpixel smoothing](https:meep.readthedocs.io/en/latest/Subpixel_Smoothing/)\uff0c\u5b83\u53ef\u4ee5\u63d0\u9ad8\u6a21\u62df\u7684\u7cbe\u5ea6\u3002\n\n    for (unsigned int idx = 0; idx < nb_mirror_pairs; idx++) \n      { \n        const double layer_transition_center = \n          material_a_wavelength / 2 + \n          idx * (material_b_wavelength / 4 + material_a_wavelength / 4) + \n          material_b_wavelength / 4; \n        if (std::abs(p[0]) >= \n              (layer_transition_center - average_rho_width / 2) && \n            std::abs(p[0]) <= (layer_transition_center + average_rho_width / 2)) \n          { \n            const double coefficient = \n              (std::abs(p[0]) - \n               (layer_transition_center - average_rho_width / 2)) / \n              average_rho_width; \n            return (1 - coefficient) * material_b_rho + \n                   coefficient * material_a_rho; \n          } \n      } \n\n// \u7136\u540e\u662f\u8154\u4f53\n\n    if (std::abs(p[0]) <= material_a_wavelength / 2) \n      { \n        return material_a_rho; \n      } \n\n// \u6750\u6599\u5c42_a\n\n    for (unsigned int idx = 0; idx < nb_mirror_pairs; idx++) \n      { \n        const double layer_center = \n          material_a_wavelength / 2 + \n          idx * (material_b_wavelength / 4 + material_a_wavelength / 4) + \n          material_b_wavelength / 4 + material_a_wavelength / 8; \n        const double layer_width = material_a_wavelength / 4; \n        if (std::abs(p[0]) >= (layer_center - layer_width / 2) && \n            std::abs(p[0]) <= (layer_center + layer_width / 2)) \n          { \n            return material_a_rho; \n          } \n      } \n\n// material_b\u5c42\n\n    for (unsigned int idx = 0; idx < nb_mirror_pairs; idx++) \n      { \n        const double layer_center = \n          material_a_wavelength / 2 + \n          idx * (material_b_wavelength / 4 + material_a_wavelength / 4) + \n          material_b_wavelength / 8; \n        const double layer_width = material_b_wavelength / 4; \n        if (std::abs(p[0]) >= (layer_center - layer_width / 2) && \n            std::abs(p[0]) <= (layer_center + layer_width / 2)) \n          { \n            return material_b_rho; \n          } \n      } \n\n// \u6700\u540e\uff0c\u9ed8\u8ba4\u7684\u662f material_a\u3002\n\n    return material_a_rho; \n  } \n\n//  @sect4{The `Parameters` class implementation}  \n\n// \u6784\u9020\u51fd\u6570\u4f7f\u7528 HDF5::Group \u51fd\u6570\u4ece HDF5::Group::get_attribute() `data`\u4e2d\u8bfb\u53d6\u6240\u6709\u53c2\u6570\u3002\n\n  template <int dim> \n  Parameters<dim>::Parameters(HDF5::Group &data) \n    : data(data) \n    , simulation_name(data.get_attribute<std::string>(\"simulation_name\")) \n    , save_vtu_files(data.get_attribute<bool>(\"save_vtu_files\")) \n    , start_frequency(data.get_attribute<double>(\"start_frequency\")) \n    , stop_frequency(data.get_attribute<double>(\"stop_frequency\")) \n    , nb_frequency_points(data.get_attribute<int>(\"nb_frequency_points\")) \n    , lambda(data.get_attribute<double>(\"lambda\")) \n    , mu(data.get_attribute<double>(\"mu\")) \n    , dimension_x(data.get_attribute<double>(\"dimension_x\")) \n    , dimension_y(data.get_attribute<double>(\"dimension_y\")) \n    , nb_probe_points(data.get_attribute<int>(\"nb_probe_points\")) \n    , grid_level(data.get_attribute<int>(\"grid_level\")) \n    , probe_start_point(data.get_attribute<double>(\"probe_pos_x\"), \n                        data.get_attribute<double>(\"probe_pos_y\") - \n                          data.get_attribute<double>(\"probe_width_y\") / 2) \n    , probe_stop_point(data.get_attribute<double>(\"probe_pos_x\"), \n                       data.get_attribute<double>(\"probe_pos_y\") + \n                         data.get_attribute<double>(\"probe_width_y\") / 2) \n    , right_hand_side(data) \n    , pml(data) \n    , rho(data) \n  {} \n\n//  @sect4{The `QuadratureCache` class implementation}  \n\n// \u6211\u4eec\u9700\u8981\u4e3a\u8d28\u91cf\u548c\u521a\u5ea6\u77e9\u9635\u4ee5\u53ca\u53f3\u624b\u8fb9\u7684\u77e2\u91cf\u4fdd\u7559\u8db3\u591f\u7684\u7a7a\u95f4\u3002\n\n  template <int dim> \n  QuadratureCache<dim>::QuadratureCache(const unsigned int dofs_per_cell) \n    : dofs_per_cell(dofs_per_cell) \n    , mass_coefficient(dofs_per_cell, dofs_per_cell) \n    , stiffness_coefficient(dofs_per_cell, dofs_per_cell) \n    , right_hand_side(dofs_per_cell) \n  {} \n\n//  @sect3{Implementation of the `ElasticWave` class}  \n// @sect4{Constructor}  \n\n// \u8fd9\u4e0e  step-40  \u7684\u6784\u9020\u51fd\u6570\u975e\u5e38\u76f8\u4f3c\u3002\u6b64\u5916\uff0c\u6211\u4eec\u8fd8\u521b\u5efa\u4e86HDF5\u6570\u636e\u96c6`frequency_dataset`\uff0c`position_dataset`\u548c`displacement`\u3002\u6ce8\u610f\u5728\u521b\u5efaHDF5\u6570\u636e\u96c6\u65f6\u4f7f\u7528\u4e86 \"\u6a21\u677f \"\u5173\u952e\u5b57\u3002\u8fd9\u662fC++\u7684\u8981\u6c42\uff0c\u4f7f\u7528`template`\u5173\u952e\u5b57\u662f\u4e3a\u4e86\u5c06`create_dataset`\u4f5c\u4e3a\u4e00\u4e2a\u4f9d\u8d56\u7684\u6a21\u677f\u540d\u79f0\u3002\n\n  template <int dim> \n  ElasticWave<dim>::ElasticWave(const Parameters<dim> &parameters) \n    : parameters(parameters) \n    , mpi_communicator(MPI_COMM_WORLD) \n    , triangulation(mpi_communicator, \n                    typename Triangulation<dim>::MeshSmoothing( \n                      Triangulation<dim>::smoothing_on_refinement | \n                      Triangulation<dim>::smoothing_on_coarsening)) \n    , quadrature_formula(2) \n    , fe(FE_Q<dim>(1), dim) \n    , dof_handler(triangulation) \n    , frequency(parameters.nb_frequency_points) \n    , probe_positions(parameters.nb_probe_points, dim) \n    , frequency_dataset(parameters.data.template create_dataset<double>( \n        \"frequency\", \n        std::vector<hsize_t>{parameters.nb_frequency_points})) \n    , probe_positions_dataset(parameters.data.template create_dataset<double>( \n        \"position\", \n        std::vector<hsize_t>{parameters.nb_probe_points, dim})) \n    , displacement( \n        parameters.data.template create_dataset<std::complex<double>>( \n          \"displacement\", \n          std::vector<hsize_t>{parameters.nb_probe_points, \n                               parameters.nb_frequency_points})) \n    , pcout(std::cout, \n            (Utilities::MPI::this_mpi_process(mpi_communicator) == 0)) \n    , computing_timer(mpi_communicator, \n                      pcout, \n                      TimerOutput::summary, \n                      TimerOutput::wall_times) \n  {} \n\n//  @sect4{ElasticWave::setup_system}  \n\n// \u8fd9\u4e2a\u51fd\u6570\u6ca1\u6709\u4ec0\u4e48\u65b0\u5185\u5bb9\uff0c\u4e0e step-40 \u7684\u552f\u4e00\u533a\u522b\u662f\uff0c\u6211\u4eec\u4e0d\u9700\u8981\u5e94\u7528\u8fb9\u754c\u6761\u4ef6\uff0c\u56e0\u4e3a\u6211\u4eec\u4f7f\u7528PML\u6765\u622a\u65ad\u57df\u3002\n\n  template <int dim> \n  void ElasticWave<dim>::setup_system() \n  { \n    TimerOutput::Scope t(computing_timer, \"setup\"); \n\n    dof_handler.distribute_dofs(fe); \n\n    locally_owned_dofs = dof_handler.locally_owned_dofs(); \n    DoFTools::extract_locally_relevant_dofs(dof_handler, locally_relevant_dofs); \n\n    locally_relevant_solution.reinit(locally_owned_dofs, \n                                     locally_relevant_dofs, \n                                     mpi_communicator); \n\n    system_rhs.reinit(locally_owned_dofs, mpi_communicator); \n\n    constraints.clear(); \n    constraints.reinit(locally_relevant_dofs); \n    DoFTools::make_hanging_node_constraints(dof_handler, constraints); \n\n    constraints.close(); \n\n    DynamicSparsityPattern dsp(locally_relevant_dofs); \n\n    DoFTools::make_sparsity_pattern(dof_handler, dsp, constraints, false); \n    SparsityTools::distribute_sparsity_pattern(dsp, \n                                               locally_owned_dofs, \n                                               mpi_communicator, \n                                               locally_relevant_dofs); \n\n    system_matrix.reinit(locally_owned_dofs, \n                         locally_owned_dofs, \n                         dsp, \n                         mpi_communicator); \n  } \n\n//  @sect4{ElasticWave::assemble_system}  \n\n// \u8fd9\u4e2a\u51fd\u6570\u4e5f\u4e0e step-40 \u975e\u5e38\u76f8\u4f3c\uff0c\u5c3d\u7ba1\u6709\u660e\u663e\u7684\u533a\u522b\u3002\u6211\u4eec\u4e3a\u6bcf\u4e2a\u9891\u7387/\u6b27\u7c73\u8304\u6b65\u9aa4\u7ec4\u88c5\u7cfb\u7edf\u3002\u5728\u7b2c\u4e00\u6b65\u4e2d\uff0c\u6211\u4eec\u8bbe\u7f6e`calculate_quadrature_data = True`\uff0c\u7136\u540e\u6211\u4eec\u8ba1\u7b97\u8d28\u91cf\u548c\u521a\u5ea6\u77e9\u9635\u4ee5\u53ca\u53f3\u624b\u8fb9\u7684\u77e2\u91cf\u3002\u5728\u968f\u540e\u7684\u6b65\u9aa4\u4e2d\uff0c\u6211\u4eec\u5c06\u4f7f\u7528\u8fd9\u4e9b\u6570\u636e\u6765\u52a0\u901f\u8ba1\u7b97\u3002\n\n  template <int dim> \n  void ElasticWave<dim>::assemble_system(const double omega, \n                                         const bool   calculate_quadrature_data) \n  { \n    TimerOutput::Scope t(computing_timer, \"assembly\"); \n\n    FEValues<dim>      fe_values(fe, \n                            quadrature_formula, \n                            update_values | update_gradients | \n                              update_quadrature_points | update_JxW_values); \n    const unsigned int dofs_per_cell = fe.n_dofs_per_cell(); \n    const unsigned int n_q_points    = quadrature_formula.size(); \n\n    FullMatrix<std::complex<double>> cell_matrix(dofs_per_cell, dofs_per_cell); \n    Vector<std::complex<double>>     cell_rhs(dofs_per_cell); \n\n    std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell); \n\n// \u8fd9\u91cc\u6211\u4eec\u5b58\u50a8\u53f3\u624b\u8fb9\u7684\u503c\uff0crho\u548cPML\u7684\u503c\u3002\n\n    std::vector<Vector<double>> rhs_values(n_q_points, Vector<double>(dim)); \n    std::vector<double>         rho_values(n_q_points); \n    std::vector<Vector<std::complex<double>>> pml_values( \n      n_q_points, Vector<std::complex<double>>(dim)); \n\n// \u6211\u4eec\u8ba1\u7b97\u5df2\u7ecf\u5728jupyter\u7b14\u8bb0\u672c\u4e2d\u5b9a\u4e49\u7684 $\\lambda$ \u548c $\\mu$ \u7684\u521a\u5ea6\u5f20\u91cf\u3002\u8bf7\u6ce8\u610f\uff0c\u4e0e $\\rho$ \u76f8\u53cd\uff0c\u521a\u5ea6\u5728\u6574\u4e2a\u9886\u57df\u4e2d\u662f\u6052\u5b9a\u7684\u3002\n\n    const SymmetricTensor<4, dim> stiffness_tensor = \n      get_stiffness_tensor<dim>(parameters.lambda, parameters.mu); \n\n// \u6211\u4eec\u4f7f\u7528\u4e0e step-20 \u76f8\u540c\u7684\u65b9\u6cd5\u5904\u7406\u77e2\u91cf\u503c\u95ee\u9898\u3002\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          cell_matrix = 0; \n          cell_rhs    = 0; \n\n// \u53ea\u6709\u5f53\u6211\u4eec\u8981\u8ba1\u7b97\u8d28\u91cf\u548c\u521a\u5ea6\u77e9\u9635\u65f6\uff0c\u6211\u4eec\u624d\u5fc5\u987b\u8ba1\u7b97\u53f3\u624b\u8fb9\u7684rho\u548cPML\u7684\u503c\u3002\u5426\u5219\u6211\u4eec\u53ef\u4ee5\u8df3\u8fc7\u8fd9\u4e2a\u8ba1\u7b97\uff0c\u8fd9\u6837\u53ef\u4ee5\u5927\u5927\u51cf\u5c11\u603b\u7684\u8ba1\u7b97\u65f6\u95f4\u3002\n\n          if (calculate_quadrature_data) \n            { \n              fe_values.reinit(cell); \n\n              parameters.right_hand_side.vector_value_list( \n                fe_values.get_quadrature_points(), rhs_values); \n              parameters.rho.value_list(fe_values.get_quadrature_points(), \n                                        rho_values); \n              parameters.pml.vector_value_list( \n                fe_values.get_quadrature_points(), pml_values); \n            } \n\n// \u6211\u4eec\u5df2\u7ecf\u5728  step-18  \u4e2d\u505a\u4e86\u8fd9\u4e2a\u5de5\u4f5c\u3002\u83b7\u5f97\u4e00\u4e2a\u6307\u5411\u5f53\u524d\u5355\u5143\u672c\u5730\u6b63\u4ea4\u7f13\u5b58\u6570\u636e\u7684\u6307\u9488\uff0c\u4f5c\u4e3a\u9632\u5fa1\u63aa\u65bd\uff0c\u786e\u4fdd\u8fd9\u4e2a\u6307\u9488\u5728\u5168\u5c40\u6570\u7ec4\u7684\u8303\u56f4\u5185\u3002\n\n          QuadratureCache<dim> *local_quadrature_points_data = \n            reinterpret_cast<QuadratureCache<dim> *>(cell->user_pointer()); \n          Assert(local_quadrature_points_data >= &quadrature_cache.front(), \n                 ExcInternalError()); \n          Assert(local_quadrature_points_data <= &quadrature_cache.back(), \n                 ExcInternalError()); \n          for (unsigned int q = 0; q < n_q_points; ++q) \n            { \n\n// quadrature_data\u53d8\u91cf\u7528\u4e8e\u5b58\u50a8\u8d28\u91cf\u548c\u521a\u5ea6\u77e9\u9635\u3001\u53f3\u624b\u8fb9\u5411\u91cf\u548c`JxW`\u7684\u503c\u3002\n\n              QuadratureCache<dim> &quadrature_data = \n                local_quadrature_points_data[q]; \n\n// \u4e0b\u9762\u6211\u4eec\u58f0\u660e\u529b\u5411\u91cf\u548cPML\u7684\u53c2\u6570  $s$  \u548c  $\\xi$  \u3002\n\n              Tensor<1, dim>                       force; \n              Tensor<1, dim, std::complex<double>> s; \n              std::complex<double>                 xi(1, 0); \n\n// \u4e0b\u9762\u7684\u5757\u53ea\u5728\u7b2c\u4e00\u4e2a\u9891\u7387\u6b65\u9aa4\u4e2d\u8ba1\u7b97\u3002\n\n              if (calculate_quadrature_data) \n                { \n\n// \u5b58\u50a8`JxW`\u7684\u503c\u3002\n\n                  quadrature_data.JxW = fe_values.JxW(q); \n\n                  for (unsigned int component = 0; component < dim; ++component) \n                    { \n\n// \u5c06\u5411\u91cf\u8f6c\u6362\u4e3a\u5f20\u91cf\uff0c\u5e76\u8ba1\u7b97\u51faxi\n\n                      force[component] = rhs_values[q][component]; \n                      s[component]     = pml_values[q][component]; \n                      xi *= s[component]; \n                    } \n\n// \u8fd9\u91cc\u6211\u4eec\u8ba1\u7b97 $\\alpha_{mnkl}$ \u548c $\\beta_{mnkl}$ \u5f20\u91cf\u3002\n\n                  Tensor<4, dim, std::complex<double>> alpha; \n                  Tensor<4, dim, std::complex<double>> beta; \n                  for (unsigned int m = 0; m < dim; ++m) \n                    for (unsigned int n = 0; n < dim; ++n) \n                      for (unsigned int k = 0; k < dim; ++k) \n                        for (unsigned int l = 0; l < dim; ++l) \n                          { \n                            alpha[m][n][k][l] = xi * \n                                                stiffness_tensor[m][n][k][l] / \n                                                (2.0 * s[n] * s[k]); \n                            beta[m][n][k][l] = xi * \n                                               stiffness_tensor[m][n][k][l] / \n                                               (2.0 * s[n] * s[l]); \n                          } \n\n                  for (unsigned int i = 0; i < dofs_per_cell; ++i) \n                    { \n                      const Tensor<1, dim> phi_i = \n                        fe_values[displacement].value(i, q); \n                      const Tensor<2, dim> grad_phi_i = \n                        fe_values[displacement].gradient(i, q); \n\n                      for (unsigned int j = 0; j < dofs_per_cell; ++j) \n                        { \n                          const Tensor<1, dim> phi_j = \n                            fe_values[displacement].value(j, q); \n                          const Tensor<2, dim> grad_phi_j = \n                            fe_values[displacement].gradient(j, q); \n\n// \u8ba1\u7b97\u8d28\u91cf\u77e9\u9635\u7684\u503c\u3002\n\n                          quadrature_data.mass_coefficient[i][j] = \n                            rho_values[q] * xi * phi_i * phi_j; \n\n//\u5728\u521a\u5ea6\u5f20\u91cf\u7684 $mnkl$ \u6307\u6570\u4e0a\u5faa\u73af\u3002\n\n                          std::complex<double> stiffness_coefficient = 0; \n                          for (unsigned int m = 0; m < dim; ++m) \n                            for (unsigned int n = 0; n < dim; ++n) \n                              for (unsigned int k = 0; k < dim; ++k) \n                                for (unsigned int l = 0; l < dim; ++l) \n                                  { \n\n// \u8fd9\u91cc\u6211\u4eec\u8ba1\u7b97\u521a\u5ea6\u77e9\u9635\u3002                          \n//\u6ce8\u610f\uff0c\u7531\u4e8ePML\u7684\u5b58\u5728\uff0c\u521a\u5ea6\u77e9\u9635\u4e0d\u662f\u5bf9\u79f0\u7684\u3002\u6211\u4eec\u4f7f\u7528\u68af\u5ea6\u51fd\u6570\uff08\u89c1[\u6587\u6863](https:www.dealii.org/current/doxygen/deal.II/group__vector__valued.html)\uff09\uff0c\u5b83\u662f\u4e00\u4e2a  <code>Tensor@<2,dim@></code>  \u3002                          \n// \u77e9\u9635 $G_{ij}$ \u7531\u6761\u76ee\n                          // @f[\n                          //  G_{ij}=\n                          //  \\frac{\\partial\\phi_i}{\\partial x_j}\n                          //  =\\partial_j \\phi_i\n                          // @f]\n                          // \u7ec4\u6210 \u6ce8\u610f\u6307\u6570 $i$ \u548c $j$ \u7684\u4f4d\u7f6e\u4ee5\u53ca\u6211\u4eec\u5728\u672c\u6559\u7a0b\u4e2d\u4f7f\u7528\u7684\u7b26\u53f7\u3002  $\\partial_j\\phi_i$  . \u7531\u4e8e\u521a\u5ea6\u5f20\u91cf\u4e0d\u662f\u5bf9\u79f0\u7684\uff0c\u6240\u4ee5\u5f88\u5bb9\u6613\u51fa\u9519\u3002\n\n                                    stiffness_coefficient += \n                                      grad_phi_i[m][n] * \n                                      (alpha[m][n][k][l] * grad_phi_j[l][k] + \n                                       beta[m][n][k][l] * grad_phi_j[k][l]); \n                                  } \n\n// \u6211\u4eec\u5c06\u521a\u5ea6\u77e9\u9635\u7684\u503c\u4fdd\u5b58\u5728quadrature_data\u4e2d\u3002\n\n                          quadrature_data.stiffness_coefficient[i][j] = \n                            stiffness_coefficient; \n                        } \n\n// \u548c\u6b63\u4ea4\u6570\u636e\u4e2d\u7684\u53f3\u624b\u8fb9\u7684\u503c\u3002\n\n \n                        phi_i * force * fe_values.JxW(q); \n                    } \n                } \n\n// \u6211\u4eec\u518d\u6b21\u5faa\u73af\u5355\u5143\u7684\u81ea\u7531\u5ea6\u6765\u8ba1\u7b97\u7cfb\u7edf\u77e9\u9635\u3002\u8fd9\u4e9b\u5faa\u73af\u975e\u5e38\u5feb\uff0c\u56e0\u4e3a\u6211\u4eec\u5df2\u7ecf\u8ba1\u7b97\u4e86\u521a\u5ea6\u548c\u8d28\u91cf\u77e9\u9635\uff0c\u53ea\u6709 $\\omega$ \u7684\u503c\u53d1\u751f\u4e86\u53d8\u5316\u3002\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                      std::complex<double> matrix_sum = 0; \n                      matrix_sum += -std::pow(omega, 2) * \n                                    quadrature_data.mass_coefficient[i][j]; \n                      matrix_sum += quadrature_data.stiffness_coefficient[i][j]; \n                      cell_matrix(i, j) += matrix_sum * quadrature_data.JxW; \n                    } \n                  cell_rhs(i) += quadrature_data.right_hand_side[i]; \n                } \n            } \n          cell->get_dof_indices(local_dof_indices); \n          constraints.distribute_local_to_global(cell_matrix, \n                                                 cell_rhs, \n                                                 local_dof_indices, \n                                                 system_matrix, \n                                                 system_rhs); \n        } \n\n    system_matrix.compress(VectorOperation::add); \n    system_rhs.compress(VectorOperation::add); \n  } \n// @sect4{ElasticWave::solve}  \n\n// \u8fd9\u6bd4  step-40  \u66f4\u52a0\u7b80\u5355\u3002\u6211\u4eec\u4f7f\u7528\u5e76\u884c\u7684\u76f4\u63a5\u6c42\u89e3\u5668MUMPS\uff0c\u5b83\u6bd4\u8fed\u4ee3\u6c42\u89e3\u5668\u9700\u8981\u66f4\u5c11\u7684\u9009\u9879\u3002\u7f3a\u70b9\u662f\u5b83\u4e0d\u80fd\u5f88\u597d\u5730\u6269\u5c55\u3002\u7528\u8fed\u4ee3\u6c42\u89e3\u5668\u6765\u89e3\u51b3Helmholtz\u65b9\u7a0b\u5e76\u4e0d\u7b80\u5355\u3002\u79fb\u4f4d\u62c9\u666e\u62c9\u65af\u591a\u7f51\u683c\u6cd5\u662f\u4e00\u79cd\u4f17\u6240\u5468\u77e5\u7684\u9884\u5904\u7406\u8be5\u7cfb\u7edf\u7684\u65b9\u6cd5\uff0c\u4f46\u8fd9\u8d85\u51fa\u4e86\u672c\u6559\u7a0b\u7684\u8303\u56f4\u3002\n\n  template <int dim> \n  void ElasticWave<dim>::solve() \n  { \n    TimerOutput::Scope              t(computing_timer, \"solve\"); \n    LinearAlgebraPETSc::MPI::Vector completely_distributed_solution( \n      locally_owned_dofs, mpi_communicator); \n\n    SolverControl                    solver_control; \n    PETScWrappers::SparseDirectMUMPS solver(solver_control, mpi_communicator); \n    solver.solve(system_matrix, completely_distributed_solution, system_rhs); \n\n    pcout << \"   Solved in \" << solver_control.last_step() << \" iterations.\" \n          << std::endl; \n    constraints.distribute(completely_distributed_solution); \n    locally_relevant_solution = completely_distributed_solution; \n  } \n// @sect4{ElasticWave::initialize_position_vector}  \n\n// \u6211\u4eec\u7528\u8fd9\u4e2a\u51fd\u6570\u6765\u8ba1\u7b97\u4f4d\u7f6e\u5411\u91cf\u7684\u503c\u3002\n\n  template <int dim> \n  void ElasticWave<dim>::initialize_probe_positions_vector() \n  { \n    for (unsigned int position_idx = 0; \n         position_idx < parameters.nb_probe_points; \n         ++position_idx) \n      { \n\n// \u7531\u4e8e\u8fd0\u7b97\u7b26+\u548c\n\n// -\u88ab\u91cd\u8f7d\u6765\u51cf\u53bb\u4e24\u4e2a\u70b9\uff0c\u6240\u4ee5\u5fc5\u987b\u505a\u5982\u4e0b\u64cd\u4f5c\u3002`Point_b<dim> + (-Point_a<dim>)`\u3002\n\n        const Point<dim> p = \n          (position_idx / ((double)(parameters.nb_probe_points - 1))) * \n            (parameters.probe_stop_point + (-parameters.probe_start_point)) + \n          parameters.probe_start_point; \n        probe_positions[position_idx][0] = p[0]; \n        probe_positions[position_idx][1] = p[1]; \n        if (dim == 3) \n          { \n            probe_positions[position_idx][2] = p[2]; \n          } \n      } \n  } \n// @sect4{ElasticWave::store_frequency_step_data}  \n\n// \u8be5\u51fd\u6570\u5728HDF5\u6587\u4ef6\u4e2d\u5b58\u50a8\u63a2\u5934\u6d4b\u91cf\u7684\u80fd\u91cf\u3002\n\n  template <int dim> \n  void \n  ElasticWave<dim>::store_frequency_step_data(const unsigned int frequency_idx) \n  { \n    TimerOutput::Scope t(computing_timer, \"store_frequency_step_data\"); \n\n// \u6211\u4eec\u5b58\u50a8 $x$ \u65b9\u5411\u7684\u4f4d\u79fb\uff1b $y$ \u65b9\u5411\u7684\u4f4d\u79fb\u53ef\u4ee5\u5ffd\u7565\u4e0d\u8ba1\u3002\n\n    const unsigned int probe_displacement_component = 0; \n\n// \u5411\u91cf\u5750\u6807\u5305\u542bHDF5\u6587\u4ef6\u4e2d\u4f4d\u4e8e\u672c\u5730\u6240\u6709\u5355\u5143\u4e2d\u7684\u63a2\u6d4b\u70b9\u7684\u5750\u6807\u3002\u5411\u91cfdisplacement_data\u5305\u542b\u8fd9\u4e9b\u70b9\u7684\u4f4d\u79fb\u503c\u3002\n\n    std::vector<hsize_t>              coordinates; \n    std::vector<std::complex<double>> displacement_data; \n\n    const auto &mapping = get_default_linear_mapping(triangulation); \n    GridTools::Cache<dim, dim> cache(triangulation, mapping); \n    typename Triangulation<dim, dim>::active_cell_iterator cell_hint{}; \n    std::vector<bool>                                      marked_vertices = {}; \n    const double                                           tolerance = 1.e-10; \n\n    for (unsigned int position_idx = 0; \n         position_idx < parameters.nb_probe_points; \n         ++position_idx) \n      { \n        Point<dim> point; \n        for (unsigned int dim_idx = 0; dim_idx < dim; ++dim_idx) \n          { \n            point[dim_idx] = probe_positions[position_idx][dim_idx]; \n          } \n        bool point_in_locally_owned_cell = false; \n        { \n          auto cell_and_ref_point = GridTools::find_active_cell_around_point( \n            cache, point, cell_hint, marked_vertices, tolerance); \n          if (cell_and_ref_point.first.state() == IteratorState::valid) \n            { \n              cell_hint = cell_and_ref_point.first; \n              point_in_locally_owned_cell = \n                cell_and_ref_point.first->is_locally_owned(); \n            } \n        } \n        if (point_in_locally_owned_cell) \n          { \n\n// \u7136\u540e\uff0c\u6211\u4eec\u53ef\u4ee5\u5728`displacement_data`\u4e2d\u5b58\u50a8\u63a2\u5934\u5404\u70b9\u7684\u4f4d\u79fb\u503c\u3002\n\n            Vector<std::complex<double>> tmp_vector(dim); \n            VectorTools::point_value(dof_handler, \n                                     locally_relevant_solution, \n                                     point, \n                                     tmp_vector); \n            coordinates.emplace_back(position_idx); \n            coordinates.emplace_back(frequency_idx); \n            displacement_data.emplace_back( \n              tmp_vector(probe_displacement_component)); \n          } \n      } \n\n// \u6211\u4eec\u5728HDF5\u6587\u4ef6\u4e2d\u5199\u5165\u4f4d\u79fb\u6570\u636e\u3002\u8c03\u7528 HDF5::DataSet::write_selection() \u662fMPI\u96c6\u4f53\u7684\uff0c\u8fd9\u610f\u5473\u7740\u6240\u6709\u8fdb\u7a0b\u90fd\u8981\u53c2\u4e0e\u3002\n\n    if (coordinates.size() > 0) \n      { \n        displacement.write_selection(displacement_data, coordinates); \n      } \n\n// \u56e0\u6b64\uff0c\u5373\u4f7f\u8fdb\u7a0b\u6ca1\u6709\u6570\u636e\u53ef\u5199\uff0c\u5b83\u4e5f\u5fc5\u987b\u53c2\u4e0e\u96c6\u4f53\u8c03\u7528\u3002\u4e3a\u6b64\u6211\u4eec\u53ef\u4ee5\u4f7f\u7528  HDF5::DataSet::write_none().  \u6ce8\u610f\uff0c\u6211\u4eec\u5fc5\u987b\u6307\u5b9a\u6570\u636e\u7c7b\u578b\uff0c\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b  `std::complex<double>`.  \u3002\n    else \n      { \n        displacement.write_none<std::complex<double>>(); \n      } \n\n// \u5982\u679c\u8f93\u5165\u6587\u4ef6\u4e2d\u7684\u53d8\u91cf`save_vtu_files`\u7b49\u4e8e`True`\uff0c\u90a3\u4e48\u6240\u6709\u6570\u636e\u5c06\u88ab\u4fdd\u5b58\u4e3avtu\u3002\u5199\u5165`vtu'\u6587\u4ef6\u7684\u8fc7\u7a0b\u5df2\u7ecf\u5728  step-40  \u4e2d\u63cf\u8ff0\u3002\n\n    if (parameters.save_vtu_files) \n      { \n        std::vector<std::string> solution_names(dim, \"displacement\"); \n        std::vector<DataComponentInterpretation::DataComponentInterpretation> \n          interpretation( \n            dim, DataComponentInterpretation::component_is_part_of_vector); \n\n        DataOut<dim> data_out; \n        data_out.add_data_vector(dof_handler, \n                                 locally_relevant_solution, \n                                 solution_names, \n                                 interpretation); \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        std::vector<Vector<double>> force( \n          dim, Vector<double>(triangulation.n_active_cells())); \n        std::vector<Vector<double>> pml( \n          dim, Vector<double>(triangulation.n_active_cells())); \n        Vector<double> rho(triangulation.n_active_cells()); \n\n        for (auto &cell : triangulation.active_cell_iterators()) \n          { \n            if (cell->is_locally_owned()) \n              { \n                for (unsigned int dim_idx = 0; dim_idx < dim; ++dim_idx) \n                  { \n                    force[dim_idx](cell->active_cell_index()) = \n                      parameters.right_hand_side.value(cell->center(), dim_idx); \n                    pml[dim_idx](cell->active_cell_index()) = \n                      parameters.pml.value(cell->center(), dim_idx).imag(); \n                  } \n                rho(cell->active_cell_index()) = \n                  parameters.rho.value(cell->center()); \n              } \n\n// \u5728\u6211\u4eec\u4e0d\u611f\u5174\u8da3\u7684\u5355\u5143\u683c\u4e0a\uff0c\u5c06\u5404\u81ea\u7684\u503c\u8bbe\u7f6e\u4e3a\u4e00\u4e2a\u5047\u503c\uff0c\u4ee5\u786e\u4fdd\u5982\u679c\u6211\u4eec\u7684\u5047\u8bbe\u6709\u4ec0\u4e48\u9519\u8bef\uff0c\u6211\u4eec\u4f1a\u901a\u8fc7\u67e5\u770b\u56fe\u5f62\u8f93\u51fa\u53d1\u73b0\u3002\n\n            else \n              { \n                for (unsigned int dim_idx = 0; dim_idx < dim; ++dim_idx) \n                  { \n                    force[dim_idx](cell->active_cell_index()) = -1e+20; \n                    pml[dim_idx](cell->active_cell_index())   = -1e+20; \n                  } \n                rho(cell->active_cell_index()) = -1e+20; \n              } \n          } \n\n        for (unsigned int dim_idx = 0; dim_idx < dim; ++dim_idx) \n          { \n            data_out.add_data_vector(force[dim_idx], \n                                     \"force_\" + std::to_string(dim_idx)); \n            data_out.add_data_vector(pml[dim_idx], \n                                     \"pml_\" + std::to_string(dim_idx)); \n          } \n        data_out.add_data_vector(rho, \"rho\"); \n\n        data_out.build_patches(); \n\n        std::stringstream  frequency_idx_stream; \n        const unsigned int nb_number_positions = \n          ((unsigned int)std::log10(parameters.nb_frequency_points)) + 1; \n        frequency_idx_stream << std::setw(nb_number_positions) \n                             << std::setfill('0') << frequency_idx; \n        std::string filename = (parameters.simulation_name + \"_\" + \n                                frequency_idx_stream.str() + \".vtu\"); \n        data_out.write_vtu_in_parallel(filename.c_str(), mpi_communicator); \n      } \n  } \n\n//  @sect4{ElasticWave::output_results}  \n\n// \u8be5\u51fd\u6570\u5199\u5165\u5c1a\u672a\u5199\u5165\u7684\u6570\u636e\u96c6\u3002\n\n  template <int dim> \n  void ElasticWave<dim>::output_results() \n  { \n\n// \u5411\u91cf`\u9891\u7387`\u548c`\u4f4d\u7f6e`\u5bf9\u6240\u6709\u8fdb\u7a0b\u90fd\u662f\u4e00\u6837\u7684\u3002\u56e0\u6b64\u4efb\u4f55\u4e00\u4e2a\u8fdb\u7a0b\u90fd\u53ef\u4ee5\u5199\u5165\u76f8\u5e94\u7684`\u6570\u636e\u96c6'\u3002\u56e0\u4e3a\u8c03\u7528 HDF5::DataSet::write \u662fMPI\u96c6\u4f53\u7684\uff0c\u5176\u4f59\u8fdb\u7a0b\u5c06\u4e0d\u5f97\u4e0d\u8c03\u7528 HDF5::DataSet::write_none.  \u3002\n    if (Utilities::MPI::this_mpi_process(mpi_communicator) == 0) \n      { \n        frequency_dataset.write(frequency); \n        probe_positions_dataset.write(probe_positions); \n      } \n    else \n      { \n        frequency_dataset.write_none<double>(); \n        probe_positions_dataset.write_none<double>(); \n      } \n  } \n\n//  @sect4{ElasticWave::setup_quadrature_cache}  \n\n// \u6211\u4eec\u5728\u8ba1\u7b97\u5f00\u59cb\u65f6\u4f7f\u7528\u8fd9\u4e2a\u51fd\u6570\u6765\u8bbe\u7f6e\u7f13\u5b58\u53d8\u91cf\u7684\u521d\u59cb\u503c\u3002\u8fd9\u4e2a\u51fd\u6570\u5728  step-18  \u4e2d\u5df2\u7ecf\u63cf\u8ff0\u8fc7\u3002\u4e0e  step-18  \u7684\u51fd\u6570\u6ca1\u6709\u533a\u522b\u3002\n\n  template <int dim> \n  void ElasticWave<dim>::setup_quadrature_cache() \n  { \n    triangulation.clear_user_data(); \n\n    { \n      std::vector<QuadratureCache<dim>> tmp; \n      quadrature_cache.swap(tmp); \n    } \n\n    quadrature_cache.resize(triangulation.n_locally_owned_active_cells() * \n                              quadrature_formula.size(), \n                            QuadratureCache<dim>(fe.n_dofs_per_cell())); \n    unsigned int cache_index = 0; \n    for (const auto &cell : triangulation.active_cell_iterators()) \n      if (cell->is_locally_owned()) \n        { \n          cell->set_user_pointer(&quadrature_cache[cache_index]); \n          cache_index += quadrature_formula.size(); \n        } \n    Assert(cache_index == quadrature_cache.size(), ExcInternalError()); \n  } \n\n//  @sect4{ElasticWave::frequency_sweep}  \n\n// \u4e3a\u4e86\u6e05\u695a\u8d77\u89c1\uff0c\u6211\u4eec\u5c06 step-40 \u7684\u51fd\u6570`run`\u5206\u4e3a\u51fd\u6570`run`\u548c`frequency_sweep`\u3002\u5728\u51fd\u6570`frequency_sweep`\u4e2d\uff0c\u6211\u4eec\u628a\u8fed\u4ee3\u653e\u5728\u9891\u7387\u5411\u91cf\u4e0a\u3002\n\n  template <int dim> \n  void ElasticWave<dim>::frequency_sweep() \n  { \n    for (unsigned int frequency_idx = 0; \n         frequency_idx < parameters.nb_frequency_points; \n         ++frequency_idx) \n      { \n        pcout << parameters.simulation_name + \" frequency idx: \" \n              << frequency_idx << '/' << parameters.nb_frequency_points - 1 \n              << std::endl; \n\n        setup_system(); \n        if (frequency_idx == 0) \n          { \n            pcout << \"   Number of active cells :       \" \n                  << triangulation.n_active_cells() << std::endl; \n            pcout << \"   Number of degrees of freedom : \" \n                  << dof_handler.n_dofs() << std::endl; \n          } \n\n        if (frequency_idx == 0) \n          { \n\n// \u53ea\u5199\u4e00\u6b21\u6a21\u62df\u53c2\u6570\n\n            parameters.data.set_attribute(\"active_cells\", \n                                          triangulation.n_active_cells()); \n            parameters.data.set_attribute(\"degrees_of_freedom\", \n                                          dof_handler.n_dofs()); \n          } \n\n// \u6211\u4eec\u8ba1\u7b97\u51fa\u8fd9\u4e2a\u7279\u5b9a\u6b65\u9aa4\u7684\u9891\u7387\u548c\u6b27\u7c73\u8304\u503c\u3002\n\n        const double current_loop_frequency = \n          (parameters.start_frequency + \n           frequency_idx * \n             (parameters.stop_frequency - parameters.start_frequency) / \n             (parameters.nb_frequency_points - 1)); \n        const double current_loop_omega = \n          2 * numbers::PI * current_loop_frequency; \n\n// \u5728\u7b2c\u4e00\u4e2a\u9891\u7387\u6b65\u9aa4\u4e2d\uff0c\u6211\u4eec\u8ba1\u7b97\u51fa\u8d28\u91cf\u548c\u521a\u5ea6\u77e9\u9635\u4ee5\u53ca\u53f3\u624b\u8fb9\u7684\u6570\u636e\u3002\u5728\u968f\u540e\u7684\u9891\u7387\u6b65\u9aa4\u4e2d\uff0c\u6211\u4eec\u5c06\u4f7f\u7528\u8fd9\u4e9b\u503c\u3002\u8fd9\u5927\u5927\u6539\u5584\u4e86\u8ba1\u7b97\u65f6\u95f4\u3002\n\n        assemble_system(current_loop_omega, \n                        (frequency_idx == 0) ? true : false); \n        solve(); \n\n        frequency[frequency_idx] = current_loop_frequency; \n        store_frequency_step_data(frequency_idx); \n\n        computing_timer.print_summary(); \n        computing_timer.reset(); \n        pcout << std::endl; \n      } \n  } \n\n//  @sect4{ElasticWave::run}  \n\n// \u8fd9\u4e2a\u51fd\u6570\u4e0e  step-40  \u4e2d\u7684\u51fd\u6570\u975e\u5e38\u76f8\u4f3c\u3002\n\n  template <int dim> \n  void ElasticWave<dim>::run() \n  { \n#ifdef DEBUG \n    pcout << \"Debug mode\" << std::endl; \n#else \n    pcout << \"Release mode\" << std::endl; \n#endif \n\n    { \n      Point<dim> p1; \n      p1(0) = -parameters.dimension_x / 2; \n      p1(1) = -parameters.dimension_y / 2; \n      if (dim == 3) \n        { \n          p1(2) = -parameters.dimension_y / 2; \n        } \n      Point<dim> p2; \n      p2(0) = parameters.dimension_x / 2; \n      p2(1) = parameters.dimension_y / 2; \n      if (dim == 3) \n        { \n          p2(2) = parameters.dimension_y / 2; \n        } \n      std::vector<unsigned int> divisions(dim); \n      divisions[0] = int(parameters.dimension_x / parameters.dimension_y); \n      divisions[1] = 1; \n      if (dim == 3) \n        { \n          divisions[2] = 1; \n        } \n      GridGenerator::subdivided_hyper_rectangle(triangulation, \n                                                divisions, \n                                                p1, \n                                                p2); \n    } \n\n    triangulation.refine_global(parameters.grid_level); \n\n    setup_quadrature_cache(); \n\n    initialize_probe_positions_vector(); \n\n    frequency_sweep(); \n\n    output_results(); \n  } \n} // namespace step62 \n\n//  @sect4{The main function}  \n\n// \u4e3b\u51fd\u6570\u4e0e  step-40  \u4e2d\u7684\u51fd\u6570\u975e\u5e38\u76f8\u4f3c\u3002\n\nint main(int argc, char *argv[]) \n{ \n  try \n    { \n      using namespace dealii; \n      const unsigned int dim = 2; \n\n      Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv, 1); \n\n      HDF5::File data_file(\"results.h5\", \n                           HDF5::File::FileAccessMode::create, \n                           MPI_COMM_WORLD); \n      auto       data = data_file.create_group(\"data\"); \n\n// \u6bcf\u4e2a\u6a21\u62df\uff08\u4f4d\u79fb\u548c\u6821\u51c6\uff09\u90fd\u5b58\u50a8\u5728\u4e00\u4e2a\u5355\u72ec\u7684HDF5\u7ec4\u4e2d\u3002\n\n      const std::vector<std::string> group_names = {\"displacement\", \n                                                    \"calibration\"}; \n      for (auto group_name : group_names) \n        { \n\n// \u5bf9\u4e8e\u8fd9\u4e24\u4e2a\u7ec4\u540d\u4e2d\u7684\u6bcf\u4e00\u4e2a\uff0c\u6211\u4eec\u73b0\u5728\u521b\u5efa\u7ec4\u5e76\u5c06\u5c5e\u6027\u653e\u5165\u8fd9\u4e9b\u7ec4\u3002\u5177\u4f53\u6765\u8bf4\uff0c\u8fd9\u4e9b\u662f\u3002\n\n// - \u6ce2\u5bfc\u7684\u5c3a\u5bf8\uff08\u5728 $x$ \u548c $y$ \u65b9\u5411\uff09\u3002\n\n// - \u63a2\u5934\u7684\u4f4d\u7f6e\uff08\u5728 $x$ \u548c $y$ \u65b9\u5411\uff09\u3002\n\n// - \u63a2\u9488\u4e2d\u7684\u70b9\u7684\u6570\u91cf\n\n// - \u5168\u5c40\u7ec6\u5316\u6c34\u5e73\n\n// - \u8154\u4f53\u8c10\u632f\u9891\u7387\n\n// - \u955c\u50cf\u5bf9\u7684\u6570\u91cf \n\n// - \u955c\u5b50\u7684\u6570\u91cf \n\n// - \u6750\u6599\u7279\u6027\n\n// - \u529b\u7684\u53c2\u6570\n\n// - PML\u53c2\u6570\n\n// - \u9891\u7387\u53c2\u6570\n\n          auto group = data.create_group(group_name); \n\n          group.set_attribute<double>(\"dimension_x\", 2e-5); \n          group.set_attribute<double>(\"dimension_y\", 2e-8); \n          group.set_attribute<double>(\"probe_pos_x\", 8e-6); \n          group.set_attribute<double>(\"probe_pos_y\", 0); \n          group.set_attribute<double>(\"probe_width_y\", 2e-08); \n          group.set_attribute<unsigned int>(\"nb_probe_points\", 5); \n          group.set_attribute<unsigned int>(\"grid_level\", 1); \n          group.set_attribute<double>(\"cavity_resonance_frequency\", 20e9); \n          group.set_attribute<unsigned int>(\"nb_mirror_pairs\", 15); \n\n          group.set_attribute<double>(\"poissons_ratio\", 0.27); \n          group.set_attribute<double>(\"youngs_modulus\", 270000000000.0); \n          group.set_attribute<double>(\"material_a_rho\", 3200); \n\n          if (group_name == std::string(\"displacement\")) \n            group.set_attribute<double>(\"material_b_rho\", 2000); \n          else \n            group.set_attribute<double>(\"material_b_rho\", 3200); \n\n          group.set_attribute( \n            \"lambda\", \n            group.get_attribute<double>(\"youngs_modulus\") * \n              group.get_attribute<double>(\"poissons_ratio\") / \n              ((1 + group.get_attribute<double>(\"poissons_ratio\")) * \n               (1 - 2 * group.get_attribute<double>(\"poissons_ratio\")))); \n          group.set_attribute(\"mu\", \n                              group.get_attribute<double>(\"youngs_modulus\") / \n                                (2 * (1 + group.get_attribute<double>( \n                                            \"poissons_ratio\")))); \n\n          group.set_attribute<double>(\"max_force_amplitude\", 1e26); \n          group.set_attribute<double>(\"force_sigma_x\", 1e-7); \n          group.set_attribute<double>(\"force_sigma_y\", 1); \n          group.set_attribute<double>(\"max_force_width_x\", 3e-7); \n          group.set_attribute<double>(\"max_force_width_y\", 2e-8); \n          group.set_attribute<double>(\"force_x_pos\", -8e-6); \n          group.set_attribute<double>(\"force_y_pos\", 0); \n\n          group.set_attribute<bool>(\"pml_x\", true); \n          group.set_attribute<bool>(\"pml_y\", false); \n          group.set_attribute<double>(\"pml_width_x\", 1.8e-6); \n          group.set_attribute<double>(\"pml_width_y\", 5e-7); \n          group.set_attribute<double>(\"pml_coeff\", 1.6); \n          group.set_attribute<unsigned int>(\"pml_coeff_degree\", 2); \n\n          group.set_attribute<double>(\"center_frequency\", 20e9); \n          group.set_attribute<double>(\"frequency_range\", 0.5e9); \n          group.set_attribute<double>( \n            \"start_frequency\", \n            group.get_attribute<double>(\"center_frequency\") - \n              group.get_attribute<double>(\"frequency_range\") / 2); \n          group.set_attribute<double>( \n            \"stop_frequency\", \n            group.get_attribute<double>(\"center_frequency\") + \n              group.get_attribute<double>(\"frequency_range\") / 2); \n          group.set_attribute<unsigned int>(\"nb_frequency_points\", 400); \n\n          if (group_name == std::string(\"displacement\")) \n            group.set_attribute<std::string>( \n              \"simulation_name\", std::string(\"phononic_cavity_displacement\")); \n          else \n            group.set_attribute<std::string>( \n              \"simulation_name\", std::string(\"phononic_cavity_calibration\")); \n\n          group.set_attribute<bool>(\"save_vtu_files\", false); \n        } \n\n      { \n\n// \u4f4d\u79fb\u6a21\u62df\u3002\u53c2\u6570\u4ece\u4f4d\u79fbHDF5\u7ec4\u4e2d\u8bfb\u53d6\uff0c\u7ed3\u679c\u4fdd\u5b58\u5728\u540c\u4e00HDF5\u7ec4\u4e2d\u3002\n\n        auto                    displacement = data.open_group(\"displacement\"); \n        step62::Parameters<dim> parameters(displacement); \n\n        step62::ElasticWave<dim> elastic_problem(parameters); \n        elastic_problem.run(); \n      } \n\n      { \n\n// \u6821\u51c6\u6a21\u62df\u3002\u53c2\u6570\u4ece\u6821\u51c6HDF5\u7ec4\u4e2d\u8bfb\u53d6\uff0c\u7ed3\u679c\u4fdd\u5b58\u5728\u540c\u4e00HDF5\u7ec4\u4e2d\u3002\n\n        auto                    calibration = data.open_group(\"calibration\"); \n        step62::Parameters<dim> parameters(calibration); \n\n        step62::ElasticWave<dim> elastic_problem(parameters); \n        elastic_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", "meta": {"hexsha": "b742733dbd60090bdf87f7e5ae51c80aa119c624", "size": 50133, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-62/step-62.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-62/step-62.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-62/step-62.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": 34.7904233171, "max_line_length": 223, "alphanum_fraction": 0.5788203379, "num_tokens": 14997, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.48864250106243334}}
{"text": "/*\n DepSpawn: Data Dependent Spawn library\n Copyright (C) 2012-2021 Carlos H. Gonzalez, Basilio B. Fraguela. Universidade da Coruna\n \n Distributed under the MIT License. (See accompanying file LICENSE)\n*/\n\n///\n/// \\author   Carlos H. Gonzalez  <cgonzalezv@udc.es>\n/// \\author   Basilio B. Fraguela <basilio.fraguela@udc.es>\n///\n\n#include <cstdlib>\n#include <iostream>\n#include <chrono>\n#include <blitz/array.h>\n#include \"depspawn/depspawn.h\"\n#include \"common_io.cpp\"  // This is only for serializing parallel prints\n\nusing namespace depspawn;\nusing namespace blitz;\n\ntypedef float Type;\n\n#define N     2000\n#define NTIMES  10\n\nint CHUNKS;\n\nArray<Type , 2> result(N,N), a(N, N), b(N,N);\n\n/// @bug template<typename Type> //IT DOES NOT WORK WITH A TEMPLATED FUNCTION; AND IT SHOULD!\nvoid add(Array<Type , 2>& result, const Array<Type , 2>& a, const Array<Type , 2>& b)\n{\n  const int nrows = result.rows();\n  const int ncols = result.cols();\n  \n#ifdef SLOW\n  \n  for(int i = 0; i < nrows; i++) {\n    for(int j = 0; j < ncols; j++) {\n      result(i, j) += a(i, j)  + b(i, j);\n    }\n  }\n  \n#else\n\n  const Type * const ap = a.data();\n  const Type * const bp = b.data();\n  Type * const rp = result.data();\n  const int s = result.stride(firstDim);\n  \n  //LOG('(' << rp << \" , \" << s << \" , \" << ap[0] << ')');\n  \n  for(int i = 0; i < nrows; i++) {\n    for(int j = 0; j < ncols; j++) {\n      rp[i * s + j] += ap[i * s + j] + bp[i * s + j];\n    }\n  }\n  \n#endif\n  \n}\n\nbool verify()\n{\n  const Type *ap = a.data();\n  const Type *bp = b.data();\n  const Type *rp = result.data();\n  \n  for (int i = 0; i < N; i++) {\n    for(int j = 0; j < N; j++) {\n      Type f = (ap[i * N + j] + bp[i * N + j]) * NTIMES;\n      if (f != rp[i * N + j]) {\n\tstd::cerr << \"At (\" << i << \", \" << j << \") : \" << rp[i * N + j] << \n\t\" != \" << NTIMES << \" *(\" << ap[i * N + j] << \" + \" << bp[i * N + j] << \")\\n\";\n\treturn false;\n      }\n    }\n  }\n  \n  return true;\n}\n\ntemplate<int extiters, int intiters>\nvoid test()\n{\n  for (int iter = 0; iter < extiters; iter++) {\n    for(int i = 0; i < N; i += N / CHUNKS) {\n      int limi = (i + N / CHUNKS) >= N ? N : (i + N / CHUNKS);\n      Range rows(i, limi - 1);\n      for(int j = 0; j < N; j += N / CHUNKS) {\n\tint limj = (j + N / CHUNKS) >= N ? N : (j + N / CHUNKS);\n\tRange cols(j, limj - 1);\n\tfor (int iter2 = 0; iter2 < intiters; iter2++)\n\t  spawn(add, result(rows, cols), a(rows, cols), b(rows, cols));\n      }\n    }\n  }\n}\n\nvoid init_data()\n{\n  for (int i = 0; i < N; i++) {\n    for(int j = 0; j < N; j++) {\n      result(i, j) = (Type)0;\n      a(i, j) = i + j;\n      b(i, j) = (i > j) ? i - j : j - i;\n    }\n  }\n}\n\nint main(int argc, char **argv)\n{\n\n  CHUNKS = (argc == 1) ? 4 : atoi(argv[1]);\n\n  init_data();\n  \n  std::chrono::time_point<std::chrono::high_resolution_clock> t0 = std::chrono::high_resolution_clock::now();\n  \n  for (int iter =0; iter < NTIMES; iter++) {\n    add(result, a, b);\n  }\n  \n  std::chrono::time_point<std::chrono::high_resolution_clock> t1 = std::chrono::high_resolution_clock::now();\n  \n  /************ First parallel run ************/\n  \n  init_data();\n  \n  std::chrono::time_point<std::chrono::high_resolution_clock> t2 = std::chrono::high_resolution_clock::now();\n\n  test<NTIMES, 1>();\n  \n  wait_for_all();\n  \n  std::chrono::time_point<std::chrono::high_resolution_clock> t3 = std::chrono::high_resolution_clock::now();\n  \n  double serial_time = std::chrono::duration<double>(t1-t0).count();\n  double parallel_time = std::chrono::duration<double>(t3-t2).count();\n  \n  std::cout << \"Serial time: \" << serial_time << \"s.  Parallel time: \" << parallel_time << \"s.\\n\";\n  std::cout << \"Speedup (using \" << CHUNKS << \" X \" << CHUNKS << \" chunks): \" <<  (serial_time / parallel_time) << std::endl;\n  const bool test_ok1 = verify();\n  std::cout << \"TEST \" << (test_ok1 ? \"SUCCESSFUL\" : \"UNSUCCSESSFUL\") << std::endl;\n  \n  /************ Second parallel run ************/\n  \n  init_data();\n  \n  t2 = std::chrono::high_resolution_clock::now();\n\n  test<1, NTIMES>();\n  \n  wait_for_all();\n  \n  t3 = std::chrono::high_resolution_clock::now();\n\n  parallel_time = std::chrono::duration<double>(t3-t2).count();\n  \n  std::cout << \"Serial time: \" << serial_time << \"s.  Parallel time: \" << parallel_time << \"s.\\n\";\n  std::cout << \"Speedup (using \" << CHUNKS << \" X \" << CHUNKS << \" chunks): \" <<  (serial_time / parallel_time) << std::endl;\n  const bool test_ok2 = verify();\n  std::cout << \"TEST \" << (test_ok2 ? \"SUCCESSFUL\" : \"UNSUCCSESSFUL\") << std::endl;\n  \n  return !(test_ok1 && test_ok2);\n}\n", "meta": {"hexsha": "7dc2ca918bfca4a792786f2f7f749bcfe78a99c3", "size": 4513, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_blitz_array.cpp", "max_stars_repo_name": "fraguela/depspawn", "max_stars_repo_head_hexsha": "b5760f4c0d38a1b245ee5274e2ccc5c5fe2d3d45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-04-12T11:05:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T11:10:27.000Z", "max_issues_repo_path": "tests/test_blitz_array.cpp", "max_issues_repo_name": "fraguela/depspawn", "max_issues_repo_head_hexsha": "b5760f4c0d38a1b245ee5274e2ccc5c5fe2d3d45", "max_issues_repo_licenses": ["MIT"], "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/test_blitz_array.cpp", "max_forks_repo_name": "fraguela/depspawn", "max_forks_repo_head_hexsha": "b5760f4c0d38a1b245ee5274e2ccc5c5fe2d3d45", "max_forks_repo_licenses": ["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.7041420118, "max_line_length": 125, "alphanum_fraction": 0.5543984046, "num_tokens": 1467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.7461390043208003, "lm_q1q2_score": 0.48864250106243334}}
{"text": "/**\n *  This test ensures that the sketch application (for Elemental matrices) is\n *  done correctly (on-the-fly matrix multiplication in the code is compared\n *  to true matrix multiplication).\n *  This test builds on the following assumptions:\n *\n *      - El::Gemm returns the correct result, and\n *      - the random numbers in row_idx and row_value (see\n *        hash_transform_data_t) are drawn from the promised distributions.\n */\n\n\n#include <vector>\n\n#include <El.hpp>\n\n#define SKYLARK_NO_ANY\n#include \"../../utility/distributions.hpp\"\n#include \"../../sketch/sketch.hpp\"\n\n#include <boost/mpi.hpp>\n#include <boost/test/minimal.hpp>\n\ntemplate < typename InputMatrixType,\n           typename OutputMatrixType = InputMatrixType >\nstruct Dummy_t : public skylark::sketch::hash_transform_t<\n    InputMatrixType, OutputMatrixType,\n    boost::random::uniform_int_distribution,\n    skylark::utility::rademacher_distribution_t > {\n\n    typedef skylark::sketch::hash_transform_t<\n        InputMatrixType, OutputMatrixType,\n        boost::random::uniform_int_distribution,\n        skylark::utility::rademacher_distribution_t >\n            hash_t;\n\n    Dummy_t(int N, int S, skylark::base::context_t& context)\n        : skylark::sketch::hash_transform_t<InputMatrixType, OutputMatrixType,\n          boost::random::uniform_int_distribution,\n          skylark::utility::rademacher_distribution_t>(N, S, context)\n    {}\n\n    std::vector<size_t> getRowIdx() { return hash_t::row_idx; }\n    std::vector<double> getRowValues() { return hash_t::row_value; }\n};\n\nint test_main(int argc, char *argv[]) {\n\n    //////////////////////////////////////////////////////////////////////////\n    //[> Parameters <]\n\n    //FIXME: use random sizes?\n    const size_t n   = 10;\n    const size_t m   = 5;\n    const size_t n_s = 6;\n    const size_t m_s = 3;\n\n    //////////////////////////////////////////////////////////////////////////\n    //[> Setup test <]\n    namespace mpi = boost::mpi;\n\n    El::Initialize(argc, argv);\n\n    mpi::environment env(argc, argv);\n    mpi::communicator world;\n\n    MPI_Comm mpi_world(world);\n    El::Grid grid(mpi_world);\n\n    typedef El::DistMatrix<double, El::CIRC, El::CIRC> MatrixType;\n    typedef El::DistMatrix<double, El::VR, El::STAR> DistMatrixType;\n\n    skylark::base::context_t context (0);\n\n    double count = 1.0;\n    El::DistMatrix<double, El::VR, El::STAR> A(grid);\n    El::Uniform (A, n, m);\n    for( size_t j = 0; j < A.Height(); j++ )\n        for( size_t i = 0; i < A.Width(); i++ )\n            A.Set(j, i, count++);\n\n\n    //////////////////////////////////////////////////////////////////////////\n    //[> Column wise application <]\n\n    /* 1. Create the sketching matrix */\n    Dummy_t<DistMatrixType, MatrixType> Sparse(n, n_s, context);\n    std::vector<size_t> row_idx    = Sparse.getRowIdx();\n    std::vector<double> row_val = Sparse.getRowValues();\n\n    // PI generated by random number gen\n    El::DistMatrix<double, El::VR, El::STAR> pi_sketch(grid);\n    El::Uniform(pi_sketch, n_s, n);\n    El::Zero(pi_sketch);\n    for(size_t i = 0; i < row_idx.size(); ++i)\n        pi_sketch.Set(row_idx[i], i, row_val[i]);\n\n    /* 2. Create space for the sketched matrix */\n    MatrixType sketch_A(n_s, m);\n\n    /* 3. Apply the transform */\n    Sparse.apply(A, sketch_A, skylark::sketch::columnwise_tag());\n\n    /* 4. Build structure to compare */\n    El::DistMatrix<double, El::VR, El::STAR> expected_A(grid);\n    El::Uniform (expected_A, n_s, m);\n    El::Gemm(El::NORMAL, El::NORMAL,\n               1.0, pi_sketch.LockedMatrix(), A.LockedMatrix(),\n               0.0, expected_A.Matrix());\n\n    for(size_t j = 0; j < sketch_A.Height(); j++ )\n        for(size_t i = 0; i < sketch_A.Width(); i++ )\n            if(sketch_A.Get(j, i) != expected_A.Get(j,i)) {\n                std::cerr << sketch_A.Get(j, i)  << \" != \"\n                          << expected_A.Get(j, i) << std::endl;\n                BOOST_FAIL(\"Result of colwise application not as expected\");\n            }\n\n\n\n    //////////////////////////////////////////////////////////////////////////\n    //[> Row wise application <]\n\n    //[> 1. Create the sketching matrix <]\n    Dummy_t<DistMatrixType, MatrixType> Sparse_r (m, m_s, context);\n    row_idx.clear(); row_val.clear();\n    row_idx = Sparse_r.getRowIdx();\n    row_val = Sparse_r.getRowValues();\n\n    // PI^T generated by random number gen\n    El::DistMatrix<double, El::VR, El::STAR> pi_sketch_r(grid);\n    El::Uniform(pi_sketch_r, m, m_s);\n    El::Zero(pi_sketch_r);\n    for(size_t i = 0; i < row_idx.size(); ++i)\n        pi_sketch_r.Set(i, row_idx[i], row_val[i]);\n\n    //[> 2. Create space for the sketched matrix <]\n    MatrixType sketch_A_r(n, m_s);\n\n    //[> 3. Apply the transform <]\n    Sparse_r.apply (A, sketch_A_r, skylark::sketch::rowwise_tag());\n\n    /* 4. Build structure to compare */\n    El::DistMatrix<double, El::VR, El::STAR> expected_AR(grid);\n    El::Uniform (expected_AR, n, m_s);\n    El::Gemm(El::NORMAL, El::NORMAL,\n               1.0, A.LockedMatrix(), pi_sketch_r.Matrix(),\n               0.0, expected_AR.Matrix());\n\n    for(size_t j = 0; j < sketch_A_r.Height(); j++ )\n        for(size_t i = 0; i < sketch_A_r.Width(); i++ )\n            if(sketch_A_r.Get(j, i) != expected_AR.Get(j,i)) {\n                std::cerr << sketch_A_r.Get(j, i)  << \" != \"\n                          << expected_AR.Get(j, i) << std::endl;\n                BOOST_FAIL(\"Result of rowwise application not as expected\");\n            }\n\n\n    El::Finalize();\n    return 0;\n}\n", "meta": {"hexsha": "a34943e6b17199ddfad7050bdee8485388c6dc19", "size": 5507, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/unit/SparseSketchApplyElementalTest.cpp", "max_stars_repo_name": "xdata-skylark/libskylark", "max_stars_repo_head_hexsha": "89c3736136a24d519c14fc0738c21f37f1e10360", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 86.0, "max_stars_repo_stars_event_min_datetime": "2015-01-20T03:12:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-10T04:05:21.000Z", "max_issues_repo_path": "tests/unit/SparseSketchApplyElementalTest.cpp", "max_issues_repo_name": "xdata-skylark/libskylark", "max_issues_repo_head_hexsha": "89c3736136a24d519c14fc0738c21f37f1e10360", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 48.0, "max_issues_repo_issues_event_min_datetime": "2015-05-12T09:31:23.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-05T14:45:46.000Z", "max_forks_repo_path": "tests/unit/SparseSketchApplyElementalTest.cpp", "max_forks_repo_name": "xdata-skylark/libskylark", "max_forks_repo_head_hexsha": "89c3736136a24d519c14fc0738c21f37f1e10360", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2015-01-18T23:02:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-12T07:30:35.000Z", "avg_line_length": 33.9938271605, "max_line_length": 78, "alphanum_fraction": 0.5798075177, "num_tokens": 1435, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.6548947357776796, "lm_q1q2_score": 0.4886424986942977}}
{"text": "#include <boost/random/linear_feedback_shift.hpp>\n", "meta": {"hexsha": "e2a09034943d9ffb98ff65e3482a5c64eb5b70ed", "size": 50, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_random_linear_feedback_shift.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_random_linear_feedback_shift.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_random_linear_feedback_shift.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 25.0, "max_line_length": 49, "alphanum_fraction": 0.84, "num_tokens": 10, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.48863104669718477}}
{"text": "/*\n * warp_delta_statistics.hpp\n *\n *  Created on: Mar 15, 2019\n *      Author: Gregory Kramida\n *   Copyright: 2019 Gregory Kramida\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n */\n\n#pragma once\n\n//stdlib\n#include <iostream>\n\n//libraries\n#include <Eigen/Eigen>\n\n//local\n#include \"../math/typedefs.hpp\"\n\nnamespace eig = Eigen;\n\nnamespace telemetry {\n\n/**\n * A structure for logging statistics pertaining to warps at the end of an optimization iteration\n * (in warp- or warp-update-threshold-based optimizations)\n */\ntemplate<typename Coordinates>\nstruct WarpDeltaStatistics {\n\n\tfloat ratio_above_min_threshold = 0.0;\n\tfloat length_min = 0.0f;\n\tfloat length_max = 0.0f;\n\tfloat length_mean = 0.0;\n\tfloat length_standard_deviation = 0.0;\n\tCoordinates longest_warp_location = Coordinates(0);\n\tbool is_largest_below_min_threshold = false;\n\tbool is_largest_above_max_threshold = false;\n\n\tWarpDeltaStatistics() = default;\n\tWarpDeltaStatistics(\n\t\t\tfloat ratio_above_min_threshold,\n\t\t\tfloat length_min,\n\t\t\tfloat length_max,\n\t\t\tfloat length_mean,\n\t\t\tfloat length_standard_deviation,\n\t\t\tCoordinates longest_warp_location,\n\t\t\tbool is_largest_below_min_threshold,\n\t\t\tbool is_largest_above_max_threshold\n\t\t\t);\n\n\teig::VectorXf to_array();\n\n\tbool operator==(const WarpDeltaStatistics& rhs);\n\tbool operator!=(const WarpDeltaStatistics& rhs);\n};\n\ntemplate<typename Coordinates, typename ScalarContainer, typename VectorContainer>\nWarpDeltaStatistics<Coordinates> build_warp_delta_statistics(const VectorContainer& warp_field,\n\t\tconst ScalarContainer& canonical_field,\n\t\tconst ScalarContainer& live_field,\n\t\tfloat min_threshold, float max_threshold);\n\ntemplate<typename Coordinates>\nstd::ostream &operator<<(std::ostream &ostr, const WarpDeltaStatistics<Coordinates> &ts);\n\ntypedef WarpDeltaStatistics<math::Vector2i> WarpDeltaStatistics2d;\ntypedef WarpDeltaStatistics<math::Vector3i> WarpDeltaStatistics3d;\n\n} //namespace telemetry\n", "meta": {"hexsha": "1e0a7f5990f1c540d543fca2a0a9c4723faf3c1c", "size": 2441, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/telemetry/warp_delta_statistics.hpp", "max_stars_repo_name": "Algomorph/LevelSetFusionExperimentsCPP", "max_stars_repo_head_hexsha": "f56962f0ad5c62e6706f818062782a2e1660afda", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2019-01-07T14:12:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T01:48:03.000Z", "max_issues_repo_path": "src/telemetry/warp_delta_statistics.hpp", "max_issues_repo_name": "Algomorph/LevelSetFusionExperimentsCPP", "max_issues_repo_head_hexsha": "f56962f0ad5c62e6706f818062782a2e1660afda", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2018-12-19T16:43:33.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-06T19:50:22.000Z", "max_forks_repo_path": "src/telemetry/warp_delta_statistics.hpp", "max_forks_repo_name": "Algomorph/LevelSetFusionExperimentsCPP", "max_forks_repo_head_hexsha": "f56962f0ad5c62e6706f818062782a2e1660afda", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-01-07T14:12:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-06T06:30:24.000Z", "avg_line_length": 29.4096385542, "max_line_length": 97, "alphanum_fraction": 0.7709954937, "num_tokens": 558, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.685949467848392, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.48855529195312647}}
{"text": "\n//    X = STR2DOUBLEQ(S) converts the string S, which should be an\n//    ASCII character representation of a real value, to MATLAB's double\n//    representation.  The string may contain digits,a decimal point, \n//    a leading + or - sign and 'e' preceding a power of 10 scale factor\n// \n//    X = STR2DOUBLEQ(C) converts the strings in the cell array of strings \n//    C to double.  The matrix X returned will be the same size as C.  \n//    NaN will be returned for any cell which is not a string representing \n//    a valid scalar value. NaN will be returned for individual cells in \n//    C which are cell arrays.\n\t\n//    Examples\n//       str2doubleq('3.14159')\n//\t     str2doubleq('  2 i   +   4.23e2  ')\n//\t\t str2doubleq('  2 +  i4     ')\n//       str2doubleq({'2e10' '3.1415'})\n//       str2doubleq(' j4     ')\n//\t\t str2doubleq('100+ 10E2i')\n//\t\t str2doubleq('1.25e10')\n\n#include \"mex.h\"\n#include <cmath>\n/* Please uncomment the following #define directive line\n   USE_PARALLEL_ALGORITHM if you wish to compile algorithm \n   in parallel computation mode. If this is enabled either \n   you need to have \n\t\t- boost library installed (please see http://www.boost.org/ \n\t\t  instructions to build boost library or if using Visual Studio, \n\t\t  just download precompiled binaries from http://www.boostpro.com/download/ \n\t\t  using latest installer)\n\t\t- compiler that supports C++11 native threads\n\n*/\n//#define USE_PARALLEL_ALGORITHM\n\n/* Please uncomment the following #define directive \n   ENSURE_THREAD_SAFE_MEX if you are using USE_PARALLEL_ALGORITHM\n   and you are experiencing Matlab crash during calls to str2doubleq.\n   Atleast with version 2012b Matlab does not crash with simultaneous \n   threads calling functions in mex.h\n   The following macro compiles the source ensuring thread safeness in\n   Matlab runtime. Also note that if ENSURE_THREAD_SAFE_MEX is undefined\n   algorithm is considerably more faster!\n*/\n//#define ENSURE_THREAD_SAFE_MEX \n\nstatic const double NaN =  mxGetNaN();\n\ninline bool is_null_or_blank(const char*& s) {\n\tif (!s)\n\t\treturn true;\n\twhile (*s)\n\t\tif (!(*s == '\\t' || *s == ' '))\n\t\t\treturn false;\n\t\telse\n\t\t\t++s;\n\treturn true;\n}\n\ninline void remove_blanks(const char*& s) {\n\twhile (*s == '\\t' || *s == ' ') \n\t\ts++;\n}\n\nbool parse_to_double(const char*& s , double& dval, bool& is_imaginary) {\n\tdval = 0;\n\tis_imaginary = false;\n\tif (!s)\n\t\treturn false;\n\tremove_blanks(s);\n\tbool is_negative = false;\n\tswitch (*s) {\n\t\tcase '-':\n\t\t\tis_negative = true;\n\t\tcase '+':\n\t\t\t++s;\n\t} \n\tremove_blanks(s);\n\tif (*s == 'i' || *s == 'j') {\n\t\t++s;\n\t\tis_imaginary = true;\n\t}\n\tremove_blanks(s);\n\t/* skip trailing zeros*/\n\twhile (*s == '0') \n\t\ts++;\n\t/* whole part is processed in doubles to avoid overflows */\n\twhile (*s >= '0' && *s <= '9') {\n\t\tdval *= 10;\n\t\tdval += (double) (*s++ - '0');\n\t}\n\tif (*s == '.' || *s == ',') {\n\t\ts++;\n\t\t/* decimal part */\n\t\tdouble decimal = 0;\n\t\tdouble divisor = 1;\n\t\twhile (*s >= '0' && *s <= '9') {\n\t\t\tdivisor *= 10;\n\t\t\tdecimal *= 10;\n\t\t\tdecimal += (double) (*s++ - '0');\n\t\t}\n\t\tdval += decimal / divisor;\n\t}\n\tif(*s == 'e' || *s == 'E') {\n\t\ts++;\n\t\t/* scientific notation */\n\t\tbool is_negative_exp = false;\n\t\tint exp = 0;\n\t\tint exp_count = 0;\n\t\tswitch (*s) {\n\t\t\tcase '-':\n\t\t\t\tis_negative_exp = true;\n\t\t\tcase '+':\n\t\t\t\ts++;\n\t\t}\n\t\twhile (*s >= '0' && *s <= '9') {\n\t\t\texp *= 10;\n\t\t\texp += (int) (*s++ - '0');\n\t\t\texp_count++;\n\t\t}\n\t\tif (exp_count == 0)\n\t\t\treturn false;\n\t\telse if (is_negative_exp)\n\t\t\texp = -1 * exp;\n\t\tdval *= pow(10.0,exp);\n\t}\n\tif (is_negative)\n\t\tdval *= -1;\n\tremove_blanks(s);\n\tif (*s == 'i' || *s == 'j')\n\t\tif (is_imaginary)\n\t\t\treturn false;\n\t\telse {\n\t\t\tis_imaginary = true;\n\t\t\t++s;\n\t\t}\n\tremove_blanks(s);\n\treturn true; \n}\n\nbool string_to_double(const char*& s , double& real, double& imag)\n{\n\treal = 0; imag = 0;\n\tdouble d = 0;\n\tbool is_imag_1 = false; bool is_imag_2 = false;\n\t\n\tif (parse_to_double(s,d,is_imag_1)) {\n\t\tif (is_imag_1)\n\t\t\timag = d;\n\t\telse\n\t\t\treal = d;\n\t\tif (is_null_or_blank(s))\n\t\t\treturn true;\n\t\telse if (parse_to_double(s,d,is_imag_2)) {\n\t\t\tif (is_imag_1 && is_imag_2)\n\t\t\t\treturn false;\n\t\t\telse if (is_imag_2)\n\t\t\t\timag = d;\n\t\t\telse\n\t\t\t\treal = d;\n\t\t\treturn is_null_or_blank(s);\n\t\t}\n\t\telse\n\t\t\treturn false;\n\t}\n\telse\n\t\treturn false;\n}\n\n#ifdef USE_PARALLEL_ALGORITHM\n// following includes if using boost\n#include <vector>\n#include <boost/thread/thread.hpp>\n#include <boost/thread/mutex.hpp>\n#include <boost/bind.hpp>\n/* Following includes if using native std with C++11 features.\n   Please note that the set of compilers supporting new C++ standard \n   features is (in the time of writing 09 Oct 2012) very scarce.\n   So if your mex command returns compiler errors like missing \n   <thread> library, most propably your compiler does not yet\n   support the new C++11 standard.\n*/\n//#include <functional>\n//#include <thread>\n\nstatic const unsigned n_threads = boost::thread::hardware_concurrency();\n//static const unsigned n_threads = std::thread::hardware_concurrency();\n\nnamespace ThreadSafeMex {\n\t/* Matlab runtime is not thread safe by its own. Only a single \n\t   thread of execution can interract with Matlab runtime in a safe\n\t   fashion. Otherwise the behaviour is undefined.\n\t   by ow\n\t*/\n#ifdef ENSURE_THREAD_SAFE_MEX\n\tboost::mutex m;\n\t//std::mutex m;\n#endif\n\tinline mxArray *mxGetCell(const mxArray *pm, mwIndex index) {\n#ifdef ENSURE_THREAD_SAFE_MEX\n\t\t//std::lock(m);\n\t\tboost::mutex::scoped_lock lock(m);\n#endif\n\t\treturn ::mxGetCell(pm,index);\n\t}\n\tinline char *mxArrayToString(const mxArray *array_ptr)\n\t{\n#ifdef ENSURE_THREAD_SAFE_MEX\n\t\t//std::lock(m);\n\t\tboost::mutex::scoped_lock lock(m);\n#endif\n\t\treturn ::mxArrayToString(array_ptr);\n\t}\n\tinline bool mxIsChar(const mxArray *pm)\n\t{\n#ifdef ENSURE_THREAD_SAFE_MEX\n\t\t//std::lock(m);\n\t\tboost::mutex::scoped_lock lock(m);\n#endif\n\t\treturn ::mxIsChar(pm);\n\t}\n};\n\nvoid parallel_str_to_double_task(const mxArray* mxStr, \n\t\t\t\t\t\t\t\t double* real, double* imag, \n\t\t\t\t\t\t\t\t size_t job_id_start, size_t job_id_end) \n{\n\tmxArray *cell = 0; \n\tconst char *s = 0; \n\tfor (size_t i = job_id_start; i < job_id_end; i++) {\n\t\tcell = ThreadSafeMex::mxGetCell(mxStr,i);\n\t\tif (cell == 0 || !ThreadSafeMex::mxIsChar(cell)) {\n\t\t\treal[i] = NaN; \n\t\t\timag[i] = 0; \n\t\t}\n\t\telse {\n\t\t\ts = ThreadSafeMex::mxArrayToString(cell);\n\t\t\tif(!string_to_double(s,real[i],imag[i])) {\n\t\t\t\treal[i] = NaN; \n\t\t\t\timag[i] = 0; \n\t\t\t}\n\t\t}\n\t}\n}\n#endif\n\nvoid mexFunction( int nlhs, mxArray *plhs[], \n\t\t  int nrhs, const mxArray*prhs[] )\n\n{\n\tconst mxArray *mxStr = prhs[0];\n\tif (nrhs == 0)\n\t\tmexErrMsgTxt(\"Too few input arguments\"); \n\telse if  (nrhs > 1)\n\t\tmexErrMsgTxt(\"Too many input arguments.\"); \n\tif (mxIsChar(mxStr)) {\n\t\tplhs[0] = mxCreateDoubleMatrix(1,1, mxCOMPLEX);\n\t\tconst char *s = mxArrayToString(mxStr);\n\t\tdouble *real = mxGetPr(plhs[0]);\n\t\tdouble *imag = mxGetPi(plhs[0]);\n\t\tif (!string_to_double(s, \n\t\t\t\t\t\t\t  real[0], \n\t\t\t\t\t\t\t  imag[0])) {\n\t\t\treal[0] = NaN; \n\t\t\timag[0] = 0; \n\t\t}\n\t}\n\telse if (mxIsCell(mxStr)) {\n\t\tsize_t n = mxGetNumberOfElements(mxStr);\n\t\tplhs[0] = mxCreateNumericArray(mxGetNumberOfDimensions(mxStr),\n\t\t\t\t\t\t\t\t\t   mxGetDimensions(mxStr),\n\t\t\t\t\t\t\t\t\t   mxDOUBLE_CLASS,\n\t\t\t\t\t\t\t\t\t   mxCOMPLEX);\n\t\tdouble *real = mxGetPr(plhs[0]);\n\t\tdouble *imag = mxGetPi(plhs[0]);\n\n#ifdef USE_PARALLEL_ALGORITHM\n\t\t//using std::thread;\n\t\t//using std::bind;\n\t\tusing boost::thread;\n\t\tusing boost::bind;\n\n\t\tif (n < 1024 || n_threads <= 1) {\n\t\t\t// too small task to do in parallel. Just serialize\n\t\t\tmxArray *cell = 0; const char *s = 0;\n\t\t\tfor (size_t i = 0; i < n; i++) {\n\t\t\t\tcell = mxGetCell(mxStr,i);\n\t\t\t\tif (cell == 0 || !mxIsChar(cell)) {\n\t\t\t\t\treal[i] = NaN; \n\t\t\t\t\timag[i] = 0; \n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\ts = mxArrayToString(cell);\n\t\t\t\t\tif(!string_to_double(s,real[i],imag[i])) {\n\t\t\t\t\t\treal[i] = NaN; \n\t\t\t\t\t\timag[i] = 0; \n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tconst size_t grain_size = (size_t)((double)n / n_threads);\n\t\tstd::vector<thread*> threads(n_threads,0);\n\t\t\n\t\tsize_t job_first = 0;\n\t\tfor(size_t i = 0; i < n_threads; ++i) {\n\t\t\tthreads[i] = new thread(bind(parallel_str_to_double_task,\n\t\t\t\t\t\t\t\t\t\t mxStr, \n\t\t\t\t\t\t\t\t\t\t real, \n\t\t\t\t\t\t\t\t\t\t imag, \n\t\t\t\t\t\t\t\t\t\t job_first, \n\t\t\t\t\t\t\t\t\t\t i < n_threads -1 ? job_first + grain_size : n));\n\t\t\tjob_first += grain_size;\n\t\t}\n\n\t\t// main thread is blocked in the following loop until all works finished\n\t\tfor(size_t i = 0; i < threads.size(); ++i) {\n\t\t\tthreads[i]->join();\n\t\t\tdelete threads[i];\n\t\t}\n#else\n\t\tmxArray *cell = 0; const char *s = 0;\n\t\tfor (size_t i = 0; i < n; i++) {\n\t\t\tcell = mxGetCell(mxStr,i);\n\t\t\tif (cell == 0 || !mxIsChar(cell)) {\n\t\t\t\treal[i] = NaN; \n\t\t\t\timag[i] = 0; \n\t\t\t}\n\t\t\telse {\n\t\t\t\ts = mxArrayToString(cell);\n\t\t\t\tif(!string_to_double(s,real[i],imag[i])) {\n\t\t\t\t\treal[i] = NaN; \n\t\t\t\t\timag[i] = 0; \n\t\t\t\t}\n\t\t\t}\n\t\t}\n#endif\n\t}    \n\telse if (mxIsDouble(mxStr)) {\n\t\tif (mxIsEmpty(mxStr)) {\n\t\t\tplhs[0] = mxCreateDoubleScalar(NaN);\n\t\t\treturn;\n\t\t}\n\t\t// return vector of NaN's\n\t\tsize_t n = mxGetNumberOfElements(mxStr);\n\t\tplhs[0] = mxCreateNumericArray(mxGetNumberOfDimensions(mxStr),\n\t\t\t\t\t\t\t\t\t   mxGetDimensions(mxStr),\n\t\t\t\t\t\t\t\t\t   mxDOUBLE_CLASS,\n\t\t\t\t\t\t\t\t\t   mxREAL);\n\t\tdouble *d = mxGetPr(plhs[0]);\n\t\tfor (size_t i = 0; i < n; i++)\n\t\t\td[i] = NaN;\n\t}\n\telse {\n\t\t// case to handle other situations, eg input is a class etc....\n\t\tplhs[0] = mxCreateDoubleScalar(NaN);\n\t}\n};\n\n", "meta": {"hexsha": "e5c30922c2ffd4dca47f27ab6b3dc1e529eb5745", "size": 9200, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dependencies/str2doubleq/str2doubleq.cpp", "max_stars_repo_name": "marcottelab/UVnovo", "max_stars_repo_head_hexsha": "4a7ac4272b7726a8b07e316e1be03faa81eaf37b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dependencies/str2doubleq/str2doubleq.cpp", "max_issues_repo_name": "marcottelab/UVnovo", "max_issues_repo_head_hexsha": "4a7ac4272b7726a8b07e316e1be03faa81eaf37b", "max_issues_repo_licenses": ["MIT"], "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/str2doubleq/str2doubleq.cpp", "max_forks_repo_name": "marcottelab/UVnovo", "max_forks_repo_head_hexsha": "4a7ac4272b7726a8b07e316e1be03faa81eaf37b", "max_forks_repo_licenses": ["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.4143646409, "max_line_length": 78, "alphanum_fraction": 0.6242391304, "num_tokens": 2824, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494678483918, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.48855528776320334}}
{"text": "// Copyright John Maddock 2006.\n// Copyright Paul A. Bristow 2007, 2009\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#define BOOST_MATH_OVERFLOW_ERROR_POLICY ignore_error\n\n#define BOOST_TEST_MAIN\n#include <boost/test/unit_test.hpp>\n#include <boost/test/tools/floating_point_comparison.hpp>\n#include <boost/math/tools/stats.hpp>\n#include <boost/math/tools/test.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/multiprecision/cpp_bin_float.hpp>\n#include <boost/array.hpp>\n#include \"functor.hpp\"\n\n#include \"handle_test_result.hpp\"\n#include \"table_type.hpp\"\n\n#ifndef SC_\n#define SC_(x) static_cast<typename table_type<T>::type>(BOOST_STRINGIZE(x))\n#endif\n\ntemplate <class Real, class T>\nvoid do_test_gamma(const T& data, const char* type_name, const char* test_name)\n{\n#if !(defined(ERROR_REPORTING_MODE) && (!defined(TGAMMA_FUNCTION_TO_TEST) || !defined(LGAMMA_FUNCTION_TO_TEST)))\n   typedef Real                   value_type;\n\n   typedef value_type (*pg)(value_type);\n#ifdef TGAMMA_FUNCTION_TO_TEST\n   pg funcp = TGAMMA_FUNCTION_TO_TEST;\n#elif defined(BOOST_MATH_NO_DEDUCED_FUNCTION_POINTERS)\n   pg funcp = boost::math::tgamma<value_type>;\n#else\n   pg funcp = boost::math::tgamma;\n#endif\n\n   boost::math::tools::test_result<value_type> result;\n\n   std::cout << \"Testing \" << test_name << \" with type \" << type_name\n      << \"\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\";\n\n   //\n   // test tgamma against data:\n   //\n   result = boost::math::tools::test_hetero<Real>(\n      data,\n      bind_func<Real>(funcp, 0),\n      extract_result<Real>(1));\n   handle_test_result(result, data[result.worst()], result.worst(), type_name, \"tgamma\", test_name);\n   //\n   // test lgamma against data:\n   //\n#ifdef LGAMMA_FUNCTION_TO_TEST\n   funcp = LGAMMA_FUNCTION_TO_TEST;\n#elif defined(BOOST_MATH_NO_DEDUCED_FUNCTION_POINTERS)\n   funcp = boost::math::lgamma<value_type>;\n#else\n   funcp = boost::math::lgamma;\n#endif\n   result = boost::math::tools::test_hetero<Real>(\n      data,\n      bind_func<Real>(funcp, 0),\n      extract_result<Real>(2));\n   handle_test_result(result, data[result.worst()], result.worst(), type_name, \"lgamma\", test_name);\n\n   std::cout << std::endl;\n#endif\n}\n\ntemplate <class T>\nvoid test_gamma(T, const char* name)\n{\n   //\n   // The actual test data is rather verbose, so it's in a separate file\n   //\n   // The contents are as follows, each row of data contains\n   // three items, input value, gamma and lgamma:\n   //\n   // gamma and lgamma at integer and half integer values:\n   // boost::array<boost::array<T, 3>, N> factorials;\n   //\n   // gamma and lgamma for z near 0:\n   // boost::array<boost::array<T, 3>, N> near_0;\n   //\n   // gamma and lgamma for z near 1:\n   // boost::array<boost::array<T, 3>, N> near_1;\n   //\n   // gamma and lgamma for z near 2:\n   // boost::array<boost::array<T, 3>, N> near_2;\n   //\n   // gamma and lgamma for z near -10:\n   // boost::array<boost::array<T, 3>, N> near_m10;\n   //\n   // gamma and lgamma for z near -55:\n   // boost::array<boost::array<T, 3>, N> near_m55;\n   //\n   // The last two cases are chosen more or less at random,\n   // except that one is even and the other odd, and both are\n   // at negative poles.  The data near zero also tests near\n   // a pole, the data near 1 and 2 are to probe lgamma as\n   // the result -> 0.\n   //\n#  include \"tgamma_mp_data.hpp\"\n\n   do_test_gamma<T>(factorials, name, \"factorials\");\n   do_test_gamma<T>(near_0, name, \"near 0\");\n   do_test_gamma<T>(near_1, name, \"near 1\");\n   do_test_gamma<T>(near_2, name, \"near 2\");\n   do_test_gamma<T>(near_m10, name, \"near -10\");\n   do_test_gamma<T>(near_m55, name, \"near -55\");\n}\n\nvoid expected_results()\n{\n   //\n   // Define the max and mean errors expected for\n   // various compilers and platforms.\n   //\n   add_expected_result(\n      \".*\",                          // compiler\n      \".*\",                          // stdlib\n      \".*\",                          // platform\n      \"number<cpp_bin_float<65> >\",           // test type(s)\n      \".*\",                          // test data group\n      \"lgamma\", 9000, 4000);      // test function\n   add_expected_result(\n      \".*\",                          // compiler\n      \".*\",                          // stdlib\n      \".*\",                          // platform\n      \"number<cpp_bin_float<75> >\",           // test type(s)\n      \".*\",                          // test data group\n      \"lgamma\", 60000, 20000);      // test function\n   add_expected_result(\n      \".*\",                          // compiler\n      \".*\",                          // stdlib\n      \".*\",                          // platform\n      \"cpp_bin_float_100|number<cpp_bin_float<85> >\",           // test type(s)\n      \".*\",                          // test data group\n      \"lgamma\", 600000, 300000);      // test function\n   add_expected_result(\n      \".*\",                          // compiler\n      \".*\",                          // stdlib\n      \".*\",                          // platform\n      \".*\",                          // test type(s)\n      \".*\",                          // test data group\n      \"lgamma\", 4800, 2500);           // test function\n   add_expected_result(\n      \".*\",                          // compiler\n      \".*\",                          // stdlib\n      \".*\",                          // platform\n      \".*\",                          // test type(s)\n      \".*\",                          // test data group\n      \"[tl]gamma\", 100, 50);            // test function\n   //\n   // Finish off by printing out the compiler/stdlib/platform names,\n   // we do this to make it easier to mark up expected error rates.\n   //\n   std::cout << \"Tests run with \" << BOOST_COMPILER << \", \"\n      << BOOST_STDLIB << \", \" << BOOST_PLATFORM << std::endl;\n}\n\nBOOST_AUTO_TEST_CASE(test_main)\n{\n   expected_results();\n   using namespace boost::multiprecision;\n   test_gamma(number<cpp_bin_float<38> >(0), \"number<cpp_bin_float<38> >\");\n   test_gamma(number<cpp_bin_float<45> >(0), \"number<cpp_bin_float<45> >\");\n   test_gamma(cpp_bin_float_50(0), \"cpp_bin_float_50\");\n   test_gamma(number<cpp_bin_float<55> >(0), \"number<cpp_bin_float<55> >\");\n   test_gamma(number<cpp_bin_float<65> >(0), \"number<cpp_bin_float<65> >\");\n   test_gamma(number<cpp_bin_float<75> >(0), \"number<cpp_bin_float<75> >\");\n   test_gamma(number<cpp_bin_float<85> >(0), \"number<cpp_bin_float<85> >\");\n   test_gamma(cpp_bin_float_100(0), \"cpp_bin_float_100\");\n}\n", "meta": {"hexsha": "f5da84e9e7060ab35feb5af1d8118ed7fe3589b0", "size": 6631, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/math/test/test_gamma_mp.cpp", "max_stars_repo_name": "uosorio/heroku_face", "max_stars_repo_head_hexsha": "7d6465e71dba17a15d8edaef520adb2fcd09d91e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-15T13:07:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-15T13:07:07.000Z", "max_issues_repo_path": "3rdparty/boost_1_73_0/libs/math/test/test_gamma_mp.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-10-21T12:42:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-03T08:41:31.000Z", "max_forks_repo_path": "Libs/boost_1_76_0/libs/math/test/test_gamma_mp.cpp", "max_forks_repo_name": "Antd23rus/S2DE", "max_forks_repo_head_hexsha": "47cc7151c2934cd8f0399a9856c1e54894571553", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-11-03T14:12:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-22T19:20:54.000Z", "avg_line_length": 36.8388888889, "max_line_length": 112, "alphanum_fraction": 0.5813602775, "num_tokens": 1733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321964553658, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.4885552778526425}}
{"text": "//==================================================================================================\n/*!\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#include <boost/simd/function/round.hpp>\n#include <scalar_test.hpp>\n#include <boost/simd/detail/dispatch/meta/as_integer.hpp>\n#include <boost/simd/constant/inf.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/zero.hpp>\n#include <boost/simd/constant/half.hpp>\n#include <boost/simd/constant/mhalf.hpp>\n#include <boost/simd/detail/constant/maxflint.hpp>\n#include <boost/simd/function/next.hpp>\n#include <boost/simd/function/prev.hpp>\n\nSTF_CASE_TPL ( \"round std\",  STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::round;\n  using r_t = decltype(bs::std_(round)(T()));\n\n  // return type conformity test\n  STF_TYPE_IS( r_t, T );\n\n  // specific values tests\n  STF_IEEE_EQUAL(bs::std_(round)(T(-1.4)), -1);\n  STF_IEEE_EQUAL(bs::std_(round)(T(-1.5)), -2);\n  STF_IEEE_EQUAL(bs::std_(round)(T(-1.6)), -2);\n  STF_IEEE_EQUAL(bs::std_(round)(T(-2.5)), -3);\n   STF_IEEE_EQUAL(bs::std_(round)(T(1.4)), 1);\n  STF_IEEE_EQUAL(bs::std_(round)(T(1.5)), 2);\n  STF_IEEE_EQUAL(bs::std_(round)(T(1.6)), 2);\n  STF_IEEE_EQUAL(bs::std_(round)(T(2.5)), 3);\n  STF_IEEE_EQUAL(bs::std_(round)(bs::Half<T>()), bs::One<r_t>());\n  STF_IEEE_EQUAL(bs::std_(round)(bs::Inf<T>()), bs::Inf<r_t>());\n  STF_IEEE_EQUAL(bs::std_(round)(bs::Mhalf<T>()), bs::Mone<r_t>());\n  STF_IEEE_EQUAL(bs::std_(round)(bs::Minf<T>()), bs::Minf<r_t>());\n  STF_IEEE_EQUAL(bs::std_(round)(bs::Mone<T>()), bs::Mone<r_t>());\n  STF_IEEE_EQUAL(bs::std_(round)(bs::Nan<T>()), bs::Nan<r_t>());\n  STF_IEEE_EQUAL(bs::std_(round)(bs::One<T>()), bs::One<r_t>());\n  STF_IEEE_EQUAL(bs::std_(round)(bs::Zero<T>()), bs::Zero<r_t>());\n} // end of test for floating_\n", "meta": {"hexsha": "984d89220dea52e130a777094b76683047912354", "size": 2160, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/scalar/round.std.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": "test/function/scalar/round.std.cpp", "max_issues_repo_name": "remymuller/boost.simd", "max_issues_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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/function/scalar/round.std.cpp", "max_forks_repo_name": "remymuller/boost.simd", "max_forks_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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": 40.7547169811, "max_line_length": 100, "alphanum_fraction": 0.6175925926, "num_tokens": 657, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.6859494485880927, "lm_q1q2_score": 0.4885552740453985}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library) \n// Unit Test\n\n// Copyright (c) 2010-2011 Barend Gehrels, Amsterdam, the Netherlands.\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_TEST_DISTANCE_HPP\n#define BOOST_GEOMETRY_TEST_DISTANCE_HPP\n\n#include <geometry_test_common.hpp>\n\n#include <boost/geometry/algorithms/distance.hpp>\n#include <boost/geometry/domains/gis/io/wkt/read_wkt.hpp>\n#include <boost/geometry/strategies/strategies.hpp>\n\n\n// Define a custom distance strategy\n// For this one, the \"taxicab\" distance,\n// see http://en.wikipedia.org/wiki/Taxicab_geometry\n\n// For a point-point-distance operation, one typename Point is enough.\n// For a point-segment-distance operation, there is some magic inside\n// using another point type and casting if necessary. Therefore,\n// two point-types are necessary.\ntemplate <typename P1, typename P2 = P1>\nstruct taxicab_distance\n{\n    static inline typename bg::coordinate_type<P1>::type apply(\n                    P1 const& p1, P2 const& p2)\n    {\n        using bg::get;\n        using bg::math::abs;\n        return abs(get<0>(p1) - get<1>(p2))\n            + abs(get<1>(p1) - get<1>(p2));\n    }\n};\n\n\n\nnamespace boost { namespace geometry { namespace strategy { namespace distance { namespace services\n{\n\ntemplate <typename P1, typename P2>\nstruct tag<taxicab_distance<P1, P2> >\n{\n    typedef strategy_tag_distance_point_point type;\n};\n\n\ntemplate <typename P1, typename P2>\nstruct return_type<taxicab_distance<P1, P2> >\n{\n    typedef typename coordinate_type<P1>::type type;\n};\n\n\ntemplate<typename P1, typename P2, typename PN1, typename PN2>\nstruct similar_type<taxicab_distance<P1, P2>, PN1, PN2>\n{\n    typedef taxicab_distance<PN1, PN2> type;\n};\n\n\ntemplate<typename P1, typename P2, typename PN1, typename PN2>\nstruct get_similar<taxicab_distance<P1, P2>, PN1, PN2>\n{\n    static inline typename similar_type\n        <\n            taxicab_distance<P1, P2>, PN1, PN2\n        >::type apply(taxicab_distance<P1, P2> const& )\n    {\n        return taxicab_distance<PN1, PN2>();\n    }\n};\n\ntemplate <typename P1, typename P2>\nstruct comparable_type<taxicab_distance<P1, P2> >\n{\n    typedef taxicab_distance<P1, P2> type;\n};\n\ntemplate <typename P1, typename P2>\nstruct get_comparable<taxicab_distance<P1, P2> >\n{\n    static inline taxicab_distance<P1, P2> apply(taxicab_distance<P1, P2> const& input)\n    {\n        return input;\n    }\n};\n\ntemplate <typename P1, typename P2>\nstruct result_from_distance<taxicab_distance<P1, P2> >\n{\n    template <typename T>\n    static inline typename coordinate_type<P1>::type apply(taxicab_distance<P1, P2> const& , T const& value)\n    {\n        return value;\n    }\n};\n\n\n}}}}} // namespace bg::strategy::distance::services\n\n\n\n\n\ntemplate <typename Geometry1, typename Geometry2>\nvoid test_distance(Geometry1 const& geometry1,\n            Geometry2 const& geometry2,\n            long double expected_distance)\n{\n    typename bg::default_distance_result<Geometry1>::type distance = bg::distance(geometry1, geometry2);\n\n#ifdef GEOMETRY_TEST_DEBUG\n    std::ostringstream out;\n    out << typeid(typename bg::coordinate_type<Geometry1>::type).name()\n        << std::endl\n        << typeid(typename bg::default_distance_result<Geometry1>::type).name()\n        << std::endl\n        << \"distance : \" << bg::distance(geometry1, geometry2)\n        << std::endl;\n    std::cout << out.str();\n#endif\n\n    BOOST_CHECK_CLOSE(distance, expected_distance, 0.0001);\n}\n\n\ntemplate <typename Geometry1, typename Geometry2>\nvoid test_geometry(std::string const& wkt1, std::string const& wkt2, double expected_distance)\n{\n    Geometry1 geometry1;\n    bg::read_wkt(wkt1, geometry1);\n    Geometry2 geometry2;\n    bg::read_wkt(wkt2, geometry2);\n\n    test_distance(geometry1, geometry2, expected_distance);\n}\n\n\n#endif\n", "meta": {"hexsha": "c8f567398f476dcad501e58f3a4b75d4e27a2e7e", "size": 3935, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/test/algorithms/test_distance.hpp", "max_stars_repo_name": "olegshnitko/libboost", "max_stars_repo_head_hexsha": "548eb6365af3724d8f4b47ebbabf7eb3ad8e66a8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-10-31T00:40:22.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-31T00:40:22.000Z", "max_issues_repo_path": "libs/geometry/test/algorithms/test_distance.hpp", "max_issues_repo_name": "olegshnitko/libboost", "max_issues_repo_head_hexsha": "548eb6365af3724d8f4b47ebbabf7eb3ad8e66a8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-01-17T10:11:43.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-17T10:11:43.000Z", "max_forks_repo_path": "libs/geometry/test/algorithms/test_distance.hpp", "max_forks_repo_name": "olegshnitko/libboost", "max_forks_repo_head_hexsha": "548eb6365af3724d8f4b47ebbabf7eb3ad8e66a8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1379310345, "max_line_length": 108, "alphanum_fraction": 0.7054637865, "num_tokens": 1027, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.48855526947279676}}
{"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\u2019s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n/* Optionally using linear programming method from\nNeri, J., and Depalle, P., \"Fast Partial Tracking of Audio with Real-Time\nCapability through Linear Programming\". Proceedings of DAFx-2018.\n*/\n\n#pragma once\n\n#include \"Munkres.hpp\"\n#include \"../../data/FluidIndex.hpp\"\n#include <Eigen/Core>\n#include <cmath>\n#include <queue>\n\nnamespace fluid {\nnamespace algorithm {\n\nstruct SinePeak\n{\n  double freq;\n  double logMag;\n  bool   assigned;\n};\n\nstruct SineTrack\n{\n  std::vector<SinePeak> peaks;\n\n  index startFrame;\n  index endFrame;\n  bool  active;\n  bool  assigned;\n  index trackId;\n};\n\nclass PartialTracking\n{\n  using ArrayXd = Eigen::ArrayXd;\n  template <typename T>\n  using vector = std::vector<T>;\n\npublic:\n  void init()\n  {\n    using namespace std;\n\n    mCurrentFrame = 0;\n    mTracks = vector<SineTrack>();\n    mPrevPeaks = vector<SinePeak>();\n    mPrevTracks = vector<index>();\n    mZetaA = 0;\n    mZetaF = 0;\n    mDelta = 0;\n    mPrevMaxAmp = 0;\n    mLastTrackId = 1;\n    mInitialized = true;\n  }\n\n  index minTrackLength() { return mMinTrackLength; }\n\n  void processFrame(vector<SinePeak> peaks, double maxAmp, index minTrackLength,\n                    double birthLowThreshold, double birthHighThreshold,\n                    index method, double zetaA, double zetaF, double delta)\n  {\n    assert(mInitialized);\n    mMinTrackLength = minTrackLength;\n    mBirthLowThreshold = birthLowThreshold;\n    mBirthHighThreshold = birthHighThreshold;\n    mBirthRange = mBirthLowThreshold - mBirthHighThreshold;\n    if (zetaA != mZetaA || zetaF != mZetaF || delta != mDelta)\n    {\n      mZetaA = zetaA;\n      mZetaF = zetaF;\n      mDelta = delta;\n      updateVariances();\n    }\n    if (method == 0)\n      assignGreedy(peaks, maxAmp);\n    else\n      assignMunkres(peaks, maxAmp);\n    mCurrentFrame++;\n  }\n\n  void prune()\n  {\n    auto iterator =\n        std::remove_if(mTracks.begin(), mTracks.end(), [&](SineTrack track) {\n          return (track.endFrame >= 0 &&\n                  track.endFrame <= mCurrentFrame - mMinTrackLength);\n        });\n    mTracks.erase(iterator, mTracks.end());\n  }\n\n\n  vector<SinePeak> getActivePeaks()\n  {\n    vector<SinePeak> sinePeaks;\n    index            latencyFrame = mCurrentFrame - mMinTrackLength;\n    if (latencyFrame < 0) return sinePeaks;\n    for (auto&& track : mTracks)\n    {\n      if (track.startFrame > latencyFrame) continue;\n      if (track.endFrame >= 0 && track.endFrame <= latencyFrame) continue;\n      if (track.endFrame >= 0 &&\n          track.endFrame - track.startFrame < mMinTrackLength)\n        continue;\n      sinePeaks.push_back(\n          track.peaks[asUnsigned(latencyFrame - track.startFrame)]);\n    }\n    return sinePeaks;\n  }\n\nprivate:\n  void updateVariances()\n  {\n    using namespace std;\n    mVarA = -pow(mZetaA, 2) * log((mDelta - 1) / (mDelta - 2));\n    mVarF = -pow(mZetaF, 2) * log((mDelta - 1) / (mDelta - 2));\n  }\n\n  void assignMunkres(vector<SinePeak> sinePeaks, double maxAmp)\n  {\n    using namespace Eigen;\n    using namespace std;\n\n    typedef Array<bool, Dynamic, Dynamic> ArrayXXb;\n    for (auto&& track : mTracks) { track.assigned = false; }\n\n    if (mPrevPeaks.empty())\n    {\n      mPrevPeaks = sinePeaks;\n      mPrevTracks = vector<index>(sinePeaks.size(), 0);\n      return;\n    }\n\n    index         N = asSigned(mPrevPeaks.size());\n    index         M = asSigned(sinePeaks.size());\n    ArrayXd       peakFreqs(M);\n    ArrayXd       peakAmps(M);\n    ArrayXd       prevFreqs(N);\n    ArrayXd       prevAmps(N);\n    vector<index> trackAssignment(asUnsigned(M), -1);\n    if (sinePeaks.size() > 0)\n    {\n      for (index i = 0; i < M; i++)\n      {\n        peakFreqs(i) = sinePeaks[asUnsigned(i)].freq;\n        peakAmps(i) = sinePeaks[asUnsigned(i)].logMag;\n      }\n      for (index i = 0; i < N; i++)\n      {\n        prevFreqs(i) = mPrevPeaks[asUnsigned(i)].freq;\n        prevAmps(i) = mPrevPeaks[asUnsigned(i)].logMag;\n      }\n      ArrayXXd deltaF = ArrayXXd::Zero(N, M);\n      deltaF.colwise() = prevFreqs;\n      for (index i = 0; i < N; i++) { deltaF.row(i) -= peakFreqs; }\n      ArrayXXd deltaA = ArrayXXd::Zero(N, M);\n      deltaA.colwise() = prevAmps;\n      for (index i = 0; i < N; i++) { deltaA.row(i) -= peakAmps; }\n\n      ArrayXXd usefulCost =\n          1 - (-deltaF.square() / mVarF - deltaA.square() / mVarA).exp();\n      ArrayXXd spuriousCost = 1 - (1 - mDelta) * usefulCost;\n      ArrayXXd cost(N, M);\n      ArrayXXb useful(N, M);\n      for (index i = 0; i < N; i++)\n      {\n        for (index j = 0; j < M; j++)\n        {\n          if (usefulCost(i, j) < spuriousCost(i, j))\n          {\n            cost(i, j) = std::abs(usefulCost(i, j));\n            useful(i, j) = true;\n          }\n          else\n          {\n            cost(i, j) = spuriousCost(i, j);\n            useful(i, j) = false;\n          }\n        }\n      }\n      ArrayXi assignment(N);\n      mMunkres.init(N, M);\n      mMunkres.process(cost, assignment);\n      for (index i = 0; i < N; i++)\n      {\n        index p = assignment(i);\n        bool  aboveBirthThreshold =\n            mPrevPeaks[asUnsigned(i)].logMag >\n            birthThreshold(mPrevPeaks[asUnsigned(i)], mPrevMaxAmp);\n        if (assignment(i) >= useful.cols()) continue;\n        if (useful(i, assignment(i)) && mPrevTracks[asUnsigned(i)] > 0 &&\n            mPrevPeaks[asUnsigned(i)].assigned)\n        {\n          for (auto& t : mTracks)\n          {\n            if (t.trackId == mPrevTracks[asUnsigned(i)])\n            {\n              trackAssignment[asUnsigned(p)] = t.trackId;\n              sinePeaks[asUnsigned(p)].assigned = true;\n              t.assigned = true;\n              t.peaks.push_back(sinePeaks[asUnsigned(p)]);\n            }\n          }\n        }\n        else if (aboveBirthThreshold && useful(i, assignment(i)) &&\n                 !mPrevPeaks[asUnsigned(i)].assigned)\n        {\n          mLastTrackId = mLastTrackId + 1;\n          auto newTrack = SineTrack{vector<SinePeak>{mPrevPeaks[asUnsigned(i)],\n                                                     sinePeaks[asUnsigned(p)]},\n                                    mCurrentFrame - 1,\n                                    -1,\n                                    true,\n                                    true,\n                                    mLastTrackId};\n          mTracks.push_back(newTrack);\n          sinePeaks[asUnsigned(p)].assigned = true;\n          trackAssignment[asUnsigned(p)] = newTrack.trackId;\n        }\n      }\n    }\n    // diying tracks\n    for (auto&& track : mTracks)\n    {\n      if (track.active && !track.assigned)\n      {\n        track.active = false;\n        track.endFrame = mCurrentFrame;\n      }\n    }\n    mPrevTracks = trackAssignment;\n    mPrevPeaks = sinePeaks;\n    mPrevMaxAmp = maxAmp;\n  }\n\n  double birthThreshold(SinePeak peak, double maxAmp)\n  {\n    return maxAmp + mBirthLowThreshold - mBirthRange +\n           mBirthRange * std::pow(0.0075, peak.freq / 20000.0);\n  }\n\n  void assignGreedy(vector<SinePeak> sinePeaks, double maxAmp)\n  {\n    using namespace std;\n    vector<tuple<double, SineTrack*, SinePeak*>> distances;\n    for (auto&& track : mTracks) { track.assigned = false; }\n    for (auto& track : mTracks)\n    {\n      if (track.active)\n      {\n        for (auto&& peak : sinePeaks)\n        {\n          double dist =\n              1 - exp(-pow(track.peaks.back().freq - peak.freq, 2) / mVarF -\n                      pow(track.peaks.back().logMag - peak.logMag, 2) / mVarA);\n          distances.push_back(std::make_tuple(dist, &track, &peak));\n        }\n      }\n    }\n\n    sort(distances.begin(), distances.end(),\n         [](tuple<double, SineTrack*, SinePeak*> const& t1,\n            tuple<double, SineTrack*, SinePeak*> const& t2) {\n           return get<0>(t1) < get<0>(t2);\n         });\n\n    for (auto&& pairing : distances)\n    {\n      if (!get<1>(pairing)->assigned && !get<2>(pairing)->assigned &&\n          get<0>(pairing) <\n              (1 - (1 - mDelta) * get<0>(pairing))) // useful vs spurious\n      {\n        get<1>(pairing)->peaks.push_back(*get<2>(pairing));\n        get<1>(pairing)->assigned = true;\n        get<2>(pairing)->assigned = true;\n      }\n    }\n    // new tracks\n    index nBorn = 0, nDead = 0;\n    for (auto&& peak : sinePeaks)\n    {\n      if (!peak.assigned && peak.logMag > birthThreshold(peak, maxAmp))\n      {\n        nBorn++;\n        mTracks.push_back(SineTrack{vector<SinePeak>{peak},\n                                    static_cast<int>(mCurrentFrame), -1, true,\n                                    true, mLastTrackId++});\n      }\n    }\n    // diying tracks\n    for (auto&& track : mTracks)\n    {\n      if (track.active && !track.assigned)\n      {\n        nDead++;\n        track.active = false;\n        track.endFrame = mCurrentFrame;\n      }\n    }\n  }\n\n  index             mMinTrackLength{15};\n  index             mCurrentFrame{0};\n  vector<SineTrack> mTracks;\n  bool              mInitialized{false};\n  vector<SinePeak>  mPrevPeaks;\n  vector<index>     mPrevTracks;\n  Munkres           mMunkres;\n  double            mZetaA{0};\n  double            mVarA{0};\n  double            mZetaF{0};\n  double            mVarF{0};\n  double            mDelta{0};\n  double            mPrevMaxAmp{0};\n  index             mLastTrackId{1};\n  double            mBirthLowThreshold{-24.};\n  double            mBirthHighThreshold{-60.};\n  double            mBirthRange{36.};\n};\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "76e7824879ba6a2105ef6cd9b0a37b8b2502c721", "size": 9775, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/util/PartialTracking.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/util/PartialTracking.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/util/PartialTracking.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": 29.3543543544, "max_line_length": 80, "alphanum_fraction": 0.5613299233, "num_tokens": 2659, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.4885278367596562}}
{"text": "#include \"solvehfvc.h\"\n\n#include <iostream>\n#include <algorithm>\n#include <Eigen/LU>\n#include <vector>\n\n#include \"eiquadprog.hpp\"\n\nusing std::cout;\nusing std::endl;\nusing Eigen::VectorXd;\nusing Eigen::MatrixXd;\n\n\nbool solvehfvc(const MatrixXd &N_ALL,\n  const MatrixXd &G, const VectorXd &b_G,\n  const VectorXd &F,\n  const MatrixXd &Aeq, const VectorXd &beq,\n  const MatrixXd &A, const VectorXd &b_A,\n  const int kDimActualized, const int kDimUnActualized,\n  const int kDimSlidingFriction, const int kDimLambda,\n  const int kNumSeeds, const int kPrintLevel,\n  HFVC *action) {\n\n  /* Size checking */\n  const int kDimGeneralized = kDimActualized + kDimUnActualized;\n  const int kDimContactForce = kDimLambda + kDimSlidingFriction;\n  assert(N_ALL.cols() == kDimGeneralized);\n  assert(N_ALL.rows() == kDimContactForce);\n  assert(G.rows() == b_G.rows());\n  assert(G.cols() == kDimGeneralized);\n  assert(F.rows() == kDimGeneralized);\n  if (kDimSlidingFriction > 0) {\n    assert(Aeq.rows() == beq.rows());\n    assert(Aeq.cols() == kDimContactForce + kDimGeneralized);\n  }\n  assert(A.rows() == b_A.rows());\n  assert(A.cols() == kDimContactForce + kDimGeneralized);\n\n  if (kPrintLevel >= 2) {\n    cout << \"Begin solving for velocity commands\" << endl;\n    cout << \"  [1] Determine Possible Dimension of control\" << endl;\n  }\n\n  MatrixXd N = N_ALL.topRows(kDimLambda);\n  MatrixXd NG(N.rows()+G.rows(), N.cols());\n  NG << N, G;\n\n  // matrix decomposition\n  //  There are two things to care about Eigen::FullPivLU.\n  //  Firstly, if the matrix to be decomposed is empty or all zero, the kernel()\n  //    method will throw a run time error.\n  //  Secondly, if the null space has zero dimension, the output is NOT a zero\n  //    dimensional matrix, but a n x 1 vector with all zeros.\n  Eigen::FullPivLU<MatrixXd> lu_decomp_N(N);\n  int rank_N = lu_decomp_N.rank();\n  MatrixXd basis_N; // columns of basis_N forms a basis of the null-space of N\n  if (rank_N > 0)\n      basis_N = lu_decomp_N.kernel();\n  else\n      basis_N = MatrixXd::Identity(kDimGeneralized, kDimGeneralized);\n\n  Eigen::FullPivLU<MatrixXd> lu_decomp_NG(NG);\n  int rank_NG = lu_decomp_NG.rank();\n  assert(rank_NG > 0);\n\n  int n_av = rank_NG - rank_N;\n  int n_af = kDimActualized - n_av;\n  assert(rank_N + kDimActualized >= kDimGeneralized);\n\n  MatrixXd basis_c;\n  if (rank_NG < kDimGeneralized) {\n    // null_NG is not empty\n    // so C_c is also not empty\n    MatrixXd null_NG = lu_decomp_NG.kernel(); // columns of null_NG forms a basis\n                                             // of the null-space of NG\n    MatrixXd C_c(null_NG.cols()+kDimUnActualized, kDimGeneralized);\n    C_c << null_NG.transpose(),\n        MatrixXd::Identity(kDimUnActualized,kDimUnActualized),\n        MatrixXd::Zero(kDimUnActualized,kDimActualized);\n    Eigen::FullPivLU<MatrixXd> lu_decomp_C_c(C_c);\n    basis_c = lu_decomp_C_c.kernel(); // columns of basis_C_c forms a basis\n                                             // of the null-space of C_c\n  } else if (kDimUnActualized > 0) {\n    MatrixXd C_c(kDimUnActualized, kDimGeneralized);\n    C_c << MatrixXd::Identity(kDimUnActualized,kDimUnActualized),\n        MatrixXd::Zero(kDimUnActualized,kDimActualized);\n    Eigen::FullPivLU<MatrixXd> lu_decomp_C_c(C_c);\n    basis_c = lu_decomp_C_c.kernel(); // columns of basis_C_c forms a basis\n  } else {\n    basis_c = MatrixXd::Identity(kDimGeneralized, kDimGeneralized);\n  }\n\n  MatrixXd R_a(kDimActualized, kDimActualized);\n  MatrixXd T(kDimGeneralized, kDimGeneralized);\n  VectorXd w_av;\n  if (n_av == 0) {\n    if (kPrintLevel >= 2)\n      cout << \"  [2] No feasible velocity control can satisfy the goal\" << endl;\n    R_a = MatrixXd::Identity(kDimActualized, kDimActualized);\n    T = MatrixXd::Identity(kDimGeneralized, kDimGeneralized);\n    w_av = VectorXd(0);\n  } else {\n    if (kPrintLevel >= 2)\n      cout << \"  [2] Solving for Directions by PGD\" << endl;\n    assert(basis_c.norm() > 0.1);// this shouldn't happen\n    int NIter   = 50;\n    int n_c     = rank_NG - kDimUnActualized;\n    MatrixXd BB = basis_c.transpose()*basis_c;\n    MatrixXd NN = basis_N*basis_N.transpose();\n\n    std::vector<MatrixXd> k_all;\n    float cost_all[kNumSeeds] = {0};\n    for (int seed = 0; seed < kNumSeeds; ++seed)  {\n      MatrixXd k  = MatrixXd::Random(n_c, n_av); // initial solution\n      MatrixXd bck = basis_c*k;\n      for (int i = 0; i < bck.cols(); i++) {\n          float bck_col_norm = bck.col(i).norm();\n          k.col(i) /= bck_col_norm;\n      }\n      MatrixXd g(n_c, n_av);\n      float costs = 0;\n      for (int iter = 0; iter < NIter; ++iter) {\n        // compute gradient\n        g = MatrixXd::Zero(n_c, n_av);\n        costs = 0;\n        for (int i = 0; i < n_av; ++i) {\n          for (int j = 0; j < n_av; ++j) {\n              if (i == j) continue;\n              float tempcost = (k.col(i).transpose()*BB*k.col(j)).norm();\n              costs += tempcost*tempcost;\n              g.col(i) += 2.0f*(k.col(i).transpose()*BB*k.col(j))(0)*BB*k.col(j);\n          }\n          g.col(i) -= 2.0f*basis_c.transpose()*NN*basis_c*k.col(i);\n          costs -= k.col(i).transpose()*basis_c.transpose()*NN*basis_c*k.col(i);\n        }\n        // descent\n        k -= 10.0f*g;\n        // project\n        bck = basis_c*k;\n        for (int i = 0; i < bck.cols(); i++) {\n            float bck_col_norm = bck.col(i).norm();\n            k.col(i) /= bck_col_norm;\n        }\n        // cout << \"     cost: \" << costs << \", grad: \" << g.norm() << endl;\n      }\n      cost_all[seed] = costs;\n      k_all.push_back(k);\n    }\n    float *cost_best    = std::min_element(cost_all, cost_all + kNumSeeds);\n    int min_id          = std::distance(cost_all, cost_best);\n    MatrixXd k_best     = k_all[min_id];\n    MatrixXd C_best     = (basis_c*k_best).transpose();\n\n    // R_a = [null(C_best(:, kDimUnActualized+1:end))';\n    //         C_best(:, kDimUnActualized+1:end)];\n    // For this decomposition, the input C_best_actualized won't be empty\n    // because it has kDimActualized cols; its output basis_C_best_actualized\n    // also won't be empty as we are conditioned on n_av > 0\n    MatrixXd C_best_actualized = C_best.rightCols(kDimActualized);\n    Eigen::FullPivLU<MatrixXd> lu_decomp_C_best_actualized(C_best_actualized);\n    MatrixXd basis_C_best_actualized;\n    int rank_C_best_actualized = lu_decomp_C_best_actualized.rank();\n    assert(rank_C_best_actualized > 0);\n    basis_C_best_actualized = // columns of basis_C_best_actualized forms the\n        lu_decomp_C_best_actualized.kernel(); // null space of C_best_actualized\n    R_a = MatrixXd::Zero(kDimActualized, kDimActualized);\n    R_a << basis_C_best_actualized.transpose(), C_best_actualized;\n    T = MatrixXd::Zero(kDimGeneralized, kDimGeneralized);\n    T.topLeftCorner(kDimUnActualized, kDimUnActualized) =\n        MatrixXd::Identity(kDimUnActualized, kDimUnActualized);\n    T.bottomRightCorner(kDimActualized,kDimActualized) = R_a;\n\n    // b_NG = [zeros(size(N, 1), 1); b_G];\n    VectorXd b_NG = VectorXd::Zero(N.rows() + b_G.rows());\n    b_NG.tail(b_G.rows()) = b_G;\n\n    // v_star = NG\\b_NG;\n    VectorXd v_star = NG.fullPivLu().solve(b_NG);\n    // cout << \"C_best: \" << C_best.rows() << \", \" << C_best.cols() << endl;\n    // cout << C_best;\n\n    w_av = C_best*v_star;\n  }\n\n  if (kPrintLevel >= 2)\n    cout << \"Begin Solving for force commands.\" << endl;\n  // unactuated dimensions\n  // H = [eye(kDimUnActualized), zeros(kDimUnActualized, kDimActualized)];\n  MatrixXd H = MatrixXd::Zero(kDimUnActualized, kDimGeneralized);\n  H.leftCols(kDimUnActualized) = MatrixXd::Identity(kDimUnActualized,\n      kDimUnActualized);\n  MatrixXd T_inv = T.inverse();\n\n  // Newton's laws\n  MatrixXd M_newton_H(kDimUnActualized, kDimGeneralized + kDimContactForce);\n  if (kDimUnActualized > 0)\n    M_newton_H << MatrixXd::Zero(kDimUnActualized, kDimContactForce), H*T_inv;\n\n  MatrixXd M_newton_N(kDimGeneralized, kDimGeneralized + kDimContactForce);\n  if (kDimContactForce > 0)\n    M_newton_N << T*N_ALL.transpose(),\n            MatrixXd::Identity(kDimGeneralized, kDimGeneralized);\n  else\n    M_newton_N << MatrixXd::Identity(kDimGeneralized, kDimGeneralized);\n\n  MatrixXd M_newton(kDimUnActualized+kDimGeneralized+Aeq.rows(),\n      kDimGeneralized + kDimContactForce);\n  M_newton << M_newton_H, M_newton_N, Aeq;\n\n  VectorXd b_newton(M_newton.rows());\n  b_newton << VectorXd::Zero(H.rows()), -T*F, beq;\n\n  MatrixXd M_free(M_newton.rows(), M_newton.cols() - n_af);\n  M_free << M_newton.leftCols(kDimContactForce+kDimUnActualized),\n      M_newton.rightCols(n_av);\n  MatrixXd M_eta_af = M_newton.middleCols(kDimContactForce+kDimUnActualized,\n      n_af);\n\n  // prepare the QP\n  // min 0.5 * x G0 x + g0 x\n  // s.t.\n  //     CE^T x + ce0 = 0\n  //     CI^T x + ci0 >= 0\n  // variables: [free_force, dual_free_force, eta_af]\n\n  // Cost function\n  int n_free = kDimContactForce + kDimUnActualized + n_av;\n  int n_dual_free = M_newton.rows();\n  Eigen::VectorXd Gdiag = Eigen::VectorXd::Zero(n_free+n_dual_free+n_af);\n  for (int i = 0; i < n_af; ++i) Gdiag(n_free+n_dual_free+i) = 1.0;\n  for (int i = 0; i < Gdiag.rows(); ++i) Gdiag(i) += 1e-3; // regularization\n  Eigen::MatrixXd G0 = Gdiag.asDiagonal();\n  Eigen::VectorXd g0 = Eigen::VectorXd::Zero(G0.rows());\n\n  // equality constraints\n  // Aeq x = beq\n  // qpAeq = [2*eye(n_free), M_free', zeros(n_free, n_af);\n  //           M_free, zeros(size(M_free, 1)), M_eta_af];\n  // qpbeq = [zeros(n_free, 1); b_newton];\n  MatrixXd qpAeq(n_free+M_free.rows(), A.cols() + n_dual_free);\n  qpAeq << 2*MatrixXd::Identity(n_free,n_free), M_free.transpose(),\n      MatrixXd::Zero(n_free, n_af), M_free,\n      MatrixXd::Zero(M_free.rows(), M_free.rows()), M_eta_af;\n  VectorXd qpbeq(n_free+b_newton.rows());\n  qpbeq << VectorXd::Zero(n_free), b_newton;\n\n\n  // Inequality constraints\n  // Ax<b\n  // A_temp = [A(:, 1:kDimContactForce), A(:, kDimContactForce+1:end)*T_inv];\n  // A_lambda_eta_u = A_temp(:, 1:kDimContactForce+kDimUnActualized);\n  // A_eta_af = A_temp(:, kDimContactForce+kDimUnActualized+1:kDimContactForce+kDimUnActualized+n_af);\n  // A_eta_av = A_temp(:, kDimContactForce+kDimUnActualized+n_af+1:end);\n  // qp.A = [A_lambda_eta_u A_eta_av zeros(size(A, 1), n_dual_free) A_eta_af];\n  MatrixXd qpA;\n  if (A.rows() > 0) {\n    MatrixXd A_temp(A.rows(), A.cols());\n    A_temp << A.leftCols(kDimContactForce), A.rightCols(kDimGeneralized)*T_inv;\n    qpA = MatrixXd(A.rows(), A.cols() + n_dual_free);\n    qpA << A_temp.leftCols(kDimContactForce+kDimUnActualized),\n        A_temp.rightCols(n_av), MatrixXd::Zero(A.rows(), n_dual_free),\n        A_temp.middleCols(kDimContactForce+kDimUnActualized, n_af);\n  } else {\n    qpA = MatrixXd(0, A.cols() + n_dual_free);\n  }\n  VectorXd qpb = b_A;\n\n  // solve the QP\n  Eigen::VectorXd x = Eigen::VectorXd::Random(g0.rows());\n  double cost = solve_quadprog(G0, g0,\n      qpAeq.transpose().cast<double>(), -qpbeq.cast<double>(),\n      -qpA.transpose().cast<double>(), qpb.cast<double>(), x);\n\n  // read the results\n  Eigen::IOFormat MatlabFmt(Eigen::StreamPrecision, 0, \", \", \";\\n\", \"\", \"\", \"[\",\n      \"]\");\n  VectorXd eta_af = x.segment(n_free+n_dual_free, n_af);\n\n\n  float equality_violation = 0, inequality_violation = 0;\n  if (qpA.rows() > 0) {\n    VectorXd b_Ax = qpA*x - qpb;\n    if (b_Ax.maxCoeff() > 0 ) inequality_violation = b_Ax.maxCoeff();\n  }\n  equality_violation = (qpbeq - qpAeq*x).norm();\n\n  if (kPrintLevel == 2) {\n    cout << \"  QP Solved. cost = \" << cost << endl;\n    cout << \"   Equality violation: \" << equality_violation << endl;\n    cout << \"   Inequality violation: \" << inequality_violation << endl;\n    cout << \"  n_av = \" << n_av << \", n_af = \" << n_af << endl;\n    cout << \"Hybrid Servoing is finished.\" << endl;\n  } else if (kPrintLevel == 1) {\n    cout << \"HFVC: n_av = \" << n_av << \", n_af = \" << n_af <<\n        \", constraint violation: \" << equality_violation + inequality_violation\n        << endl;\n  }\n\n  action->n_av   = n_av;\n  action->n_af   = n_af;\n  action->R_a    = R_a;\n  action->w_av   = w_av;\n  action->eta_af = eta_af;\n\n  return true;\n}", "meta": {"hexsha": "179989b1418b9ed1a53b020ad1934ae635a9f24d", "size": 12012, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "algorithm/c++/solvehfvc.cpp", "max_stars_repo_name": "yifan-hou/hybrid_servoing", "max_stars_repo_head_hexsha": "4d3a2cc047a3bad5ded19934247b5ab5e598f911", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2020-04-15T04:45:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T03:28:46.000Z", "max_issues_repo_path": "algorithm/c++/solvehfvc.cpp", "max_issues_repo_name": "yifan-hou/hybrid_servoing", "max_issues_repo_head_hexsha": "4d3a2cc047a3bad5ded19934247b5ab5e598f911", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "algorithm/c++/solvehfvc.cpp", "max_forks_repo_name": "yifan-hou/hybrid_servoing", "max_forks_repo_head_hexsha": "4d3a2cc047a3bad5ded19934247b5ab5e598f911", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.0, "max_line_length": 102, "alphanum_fraction": 0.6479353979, "num_tokens": 3664, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424217727027, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.4885278277877969}}
{"text": "#ifndef AX_VECTOR_ROTATION\n#define AX_VECTOR_ROTATION\n#include \"Vector.hpp\"\n#include <boost/math/quaternion.hpp>\n\nnamespace ax\n{\n\ntemplate <class T_lhs, class T_rhs, typename std::enable_if<\n    is_vector_expression<typename T_lhs::tag>::value&&\n    is_vector_expression<typename T_rhs::tag>::value&&\n    is_same_dimension<T_lhs::dim, 3>::value&&\n    is_same_dimension<T_rhs::dim, 3>::value\n    >::type*& = enabler>\nVector<typename T_lhs::elem_t, 3>\nrotation(const double angle, const T_lhs& axis, const T_rhs& target)\n{\n    using Quat = boost::math::quaternion<double>;\n    using namespace boost::math;\n\n    const double sin_normalize(sin(angle * 0.5) / length(axis));\n\n    const Quat Q(cos(angle * 0.5), axis[0] * sin_normalize, \n                                   axis[1] * sin_normalize,\n                                   axis[2] * sin_normalize);\n    const Quat P(0e0, target[0], target[1], target[2]);\n    const Quat S(Q * P * conj(Q));\n\n    return Vector<typename T_lhs::elem_t, 3>(\n            S.R_component_2(), S.R_component_3(), S.R_component_4());\n}\n\n}\n#endif//AX_VECTOR_ROTATION\n", "meta": {"hexsha": "504ed9a9adbf4c4bcc4367a831cf4b1a3a4dd3ab", "size": 1093, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/VectorRotation.hpp", "max_stars_repo_name": "ToruNiina/AX", "max_stars_repo_head_hexsha": "c99ddaa683dc94c7ec856a7cf1e10c0a6189951a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-01-16T13:56:31.000Z", "max_stars_repo_stars_event_max_datetime": "2017-01-16T13:56:31.000Z", "max_issues_repo_path": "src/VectorRotation.hpp", "max_issues_repo_name": "ToruNiina/AX", "max_issues_repo_head_hexsha": "c99ddaa683dc94c7ec856a7cf1e10c0a6189951a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/VectorRotation.hpp", "max_forks_repo_name": "ToruNiina/AX", "max_forks_repo_head_hexsha": "c99ddaa683dc94c7ec856a7cf1e10c0a6189951a", "max_forks_repo_licenses": ["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.2285714286, "max_line_length": 69, "alphanum_fraction": 0.6495882891, "num_tokens": 289, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267898240861, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.48843400457914554}}
{"text": "#ifndef LINEARELASTICENERGY_HH\n#define LINEARELASTICENERGY_HH\n\n#include <Eigen/Dense>\n#include <MeshFEM/ElasticityTensor.hh>\n#include <MeshFEM/SymmetricMatrix.hh>\n#include <MeshFEM/EnergyDensities/Tensor.hh>\n#include <MeshFEM/EnergyDensities/EnergyTraits.hh>\n\ntemplate <typename _Real, size_t _Dimension>\nstruct LinearElasticEnergy : public Concepts::LinearElaticEnergy {\n    static constexpr EDensityType EDType = EDensityType::FBased;\n\n    static constexpr size_t Dimension = _Dimension;\n    using Real = _Real;\n    using Matrix = Eigen::Matrix<_Real, _Dimension, _Dimension>;\n    using ETensor = ElasticityTensor<_Real, _Dimension>;\n    using SMatrix = SymmetricMatrixValue<_Real, _Dimension>;\n\n    /**\n     *  Construct a linear elastic energy density with a default initialized\n     *  deformation gradient.\n     *\n     *  It is undefined behavior to call any methods other than\n     *  setDeformationGradient before initializing the deformation gradient\n     *  with setDeformationGradient.\n     */\n    LinearElasticEnergy(const ETensor& elasticity_tensor)\n        : m_elasticity_tensor(elasticity_tensor) {\n        setDeformationGradient(Matrix::Identity());\n    }\n\n    LinearElasticEnergy(const LinearElasticEnergy&) = default;\n\n    // Constructor copying material properties only, not the current deformation\n    LinearElasticEnergy(const LinearElasticEnergy &other, const UninitializedDeformationTag &)\n        : m_elasticity_tensor(other.m_elasticity_tensor) { }\n\n    void setDeformationGradient(const Matrix &F, const EvalLevel /* elevel */ = EvalLevel::Full) {\n        m_F = F;\n        m_small_strain_tensor = symmetrized(F - Matrix::Identity());\n    }\n    const Matrix &getDeformationGradient() const { return m_F; }\n\n    _Real energy() const {\n        return m_small_strain_tensor.doubleContract(\n                   m_elasticity_tensor.doubleContract(m_small_strain_tensor)) /\n               2;\n    }\n\n    /**\n     *  Return the gradient of the energy density in respect of the deformation\n     *  matrix in the direction of \\a dF.\n     *\n     *  @param dF the direction\n     */\n    _Real denergy(const Matrix &dF) const {\n        return doubleContract(\n            dF, m_elasticity_tensor.doubleContract(m_small_strain_tensor));\n    }\n\n    Matrix denergy() const { return m_elasticity_tensor.doubleContract(m_small_strain_tensor).toMatrix(); }\n\n    /**\n     *  Returns dF_lhs : H : dF_rhs, where H is the hessian of the energy\n     *  density in respect to the deformation gradient.\n     */\n    _Real d2energy(const Matrix &dF_lhs, const Matrix &dF_rhs) const {\n        return symmetrized(dF_rhs).doubleContract(\n                    m_elasticity_tensor.doubleContract(symmetrized(dF_lhs)));\n    }\n\n    template<class Mat_>\n    Matrix delta_denergy(const Mat_ &dF) const {\n        return m_elasticity_tensor.doubleContract(symmetrized(dF)).toMatrix();\n    }\n\n    // Hessian is constant, third derivatives are zero.\n    Matrix delta2_denergy(const Matrix &/* dF_a */, const Matrix &/* dF_b */) const { return Matrix::Zero(); }\n\n    Matrix PK2Stress() const { throw std::runtime_error(\"Unimplemented\"); }\nprotected:\n    Matrix m_F = Matrix::Identity();\n    ETensor m_elasticity_tensor;\n    SMatrix m_small_strain_tensor;\n};\n\n#endif\n", "meta": {"hexsha": "c1993ca172d96369084ccbebd224efa90e06c5cd", "size": 3245, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/lib/MeshFEM/EnergyDensities/LinearElasticEnergy.hh", "max_stars_repo_name": "MeshFEM/MeshFEM", "max_stars_repo_head_hexsha": "9b3619fa450d83722879bfd0f5a3fe69d927bd63", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2020-10-21T10:05:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T13:41:50.000Z", "max_issues_repo_path": "src/lib/MeshFEM/EnergyDensities/LinearElasticEnergy.hh", "max_issues_repo_name": "MeshFEM/MeshFEM", "max_issues_repo_head_hexsha": "9b3619fa450d83722879bfd0f5a3fe69d927bd63", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-01-01T15:58:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-19T03:31:09.000Z", "max_forks_repo_path": "src/lib/MeshFEM/EnergyDensities/LinearElasticEnergy.hh", "max_forks_repo_name": "MeshFEM/MeshFEM", "max_forks_repo_head_hexsha": "9b3619fa450d83722879bfd0f5a3fe69d927bd63", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-10-05T09:01:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-11T03:02:39.000Z", "avg_line_length": 36.4606741573, "max_line_length": 110, "alphanum_fraction": 0.7069337442, "num_tokens": 778, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311355, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.4884340007603083}}
{"text": "#ifndef TRIUMF_BNMR_SRF_LOCAL_HPP\n#define TRIUMF_BNMR_SRF_LOCAL_HPP\n\n// C++ standard library headers\n#include <algorithm>\n#include <cmath>\n#include <limits>\n#include <numeric>\n#include <vector>\n\n// Boost headers\n#include <boost/math/interpolators/pchip.hpp>\n#include <boost/math/quadrature/tanh_sinh.hpp>\n\n// triumf++ headers\n#include <triumf/bnmr/nuclei.hpp>\n#include <triumf/math/pdf.hpp>\n#include <triumf/nmr/dipole_dipole.hpp>\n#include <triumf/nmr/nuclei.hpp>\n#include <triumf/numpy.hpp>\n#include <triumf/superconductivity/bcs.hpp>\n#include <triumf/superconductivity/phenomenology.hpp>\n#include <triumf/superconductivity/pippard.hpp>\n\n// ROOT headers\n#include <ROOT/RCsvDS.hxx>\n#include <ROOT/RDF/RInterface.hxx>\n#include <ROOT/RDataFrame.hxx>\n\n// TRIUMF: Canada's particle accelerator centre\nnamespace triumf {\n\n// \u03b2-detected nuclear magnetic resonance (\u03b2-NMR)\nnamespace bnmr {\n\n// superconducting radio-frequency (SRF) materials\nnamespace srf {\n\n// local electrodynamics\nnamespace local {\n\n/// Model SLR rate.\n/// The surface \"dead layer\" has its own distict SLR rate.\ntemplate <typename T = double>\nT slr_rate_z(T z, T temperature, T critical_temperature, T lambda_0, T exponent,\n             T applied_field, T dipole_field, T correlation_rate,\n             T slr_constant, T slr_exponent, T surface_thickness,\n             T surface_rate) {\n  // correct for the field-dependence to the critical temperature\n  // https://doi.org/10.1103/PhysRevB.2.3545\n  // https://doi.org/10.1016/j.nima.2004.09.003\n  // https://doi.org/10.1088/0953-2048/25/6/065014\n  constexpr T Nb_B_c2 = 0.425; // T\n  T corrected_critical_temperature =\n      triumf::superconductivity::phenomenology::critical_temperature<T>(\n          applied_field, critical_temperature, Nb_B_c2, 0.5);\n  // correct depth for the surface layer\n  T _z_ = z - surface_thickness;\n  if (_z_ < 0.0) {\n    return surface_rate;\n  } else {\n    // calculate the local field from the screening profile\n    T lambda = triumf::superconductivity::phenomenology::penetration_depth(\n        temperature, corrected_critical_temperature, exponent, lambda_0);\n    T screened_field = temperature > corrected_critical_temperature\n                           ? applied_field\n                           : applied_field * std::exp(-1.0 * _z_ / lambda);\n    // calculate the dipole-dipole SLR rate in the superconducting state\n    T dd_rate = triumf::nmr::dipole_dipole::slr_rate<T>(\n        screened_field, dipole_field, correlation_rate,\n        triumf::bnmr::nuclei::lithium_8<T>::gyromagnetic_ratio(),\n        triumf::nmr::nuclei::niobium_93<T>::gyromagnetic_ratio());\n    // calculate the SLR rate in the normal state\n    T ns_rate = slr_constant * std::pow(temperature, slr_exponent);\n    // return the \"surface\" contribution at shallow depths\n    return dd_rate + ns_rate;\n  }\n}\n\n/// Model SLR rate.\n/// The surface \"dead layer\" has the same SLR rate as the normal state.\ntemplate <typename T = double>\nT slr_rate_nss_z(T z, T temperature, T critical_temperature, T lambda_0,\n                 T exponent, T applied_field, T dipole_field,\n                 T correlation_rate, T slr_constant, T slr_exponent,\n                 T surface_thickness) {\n  // correct for the field-dependence to the critical temperature\n  // https://doi.org/10.1103/PhysRevB.2.3545\n  // https://doi.org/10.1016/j.nima.2004.09.003\n  // https://doi.org/10.1088/0953-2048/25/6/065014\n  constexpr T Nb_B_c2 = 0.425; // T\n  T corrected_critical_temperature =\n      triumf::superconductivity::phenomenology::critical_temperature<T>(\n          applied_field, critical_temperature, Nb_B_c2, 0.5);\n  // correct depth for the surface layer\n  T _z_ = z - surface_thickness;\n  if (_z_ < 0.0) {\n    // calculate the dipole-dipole SLR rate in the normal state\n    T dd_rate_surf = triumf::nmr::dipole_dipole::slr_rate<T>(\n        applied_field, dipole_field, correlation_rate,\n        triumf::bnmr::nuclei::lithium_8<T>::gyromagnetic_ratio(),\n        triumf::nmr::nuclei::niobium_93<T>::gyromagnetic_ratio());\n    // calculate the SLR rate in the normal state\n    T ns_rate_surf = slr_constant * std::pow(temperature, slr_exponent);\n    // return the \"surface\" contribution at shallow depths\n    return dd_rate_surf + ns_rate_surf;\n  } else {\n    // calculate the local field from the screening profile\n    T lambda = triumf::superconductivity::phenomenology::penetration_depth(\n        temperature, corrected_critical_temperature, exponent, lambda_0);\n    T screened_field = temperature > corrected_critical_temperature\n                           ? applied_field\n                           : applied_field * std::exp(-1.0 * _z_ / lambda);\n    // calculate the dipole-dipole SLR rate in the superconducting state\n    T dd_rate = triumf::nmr::dipole_dipole::slr_rate<T>(\n        screened_field, dipole_field, correlation_rate,\n        triumf::bnmr::nuclei::lithium_8<T>::gyromagnetic_ratio(),\n        triumf::nmr::nuclei::niobium_93<T>::gyromagnetic_ratio());\n    // calculate the SLR rate in the normal state\n    T ns_rate = slr_constant * std::pow(temperature, slr_exponent);\n    // return the \"surface\" contribution at shallow depths\n    return dd_rate + ns_rate;\n  }\n}\n\n/// Model SLR rate for a thin film.\n/// The surface \"dead layer\" has its own distict SLR rate.\ntemplate <typename T = double>\nT slr_rate_film_z(T z, T temperature, T critical_temperature, T lambda_0,\n                  T exponent, T applied_field, T dipole_field,\n                  T correlation_rate, T slr_constant, T slr_exponent,\n                  T surface_thickness, T surface_rate, T film_thickness) {\n  // correct for the field-dependence to the critical temperature\n  // https://doi.org/10.1103/PhysRevB.2.3545\n  // https://doi.org/10.1016/j.nima.2004.09.003\n  // https://doi.org/10.1088/0953-2048/25/6/065014\n  constexpr T Nb_B_c2 = 0.425; // T\n  T corrected_critical_temperature =\n      triumf::superconductivity::phenomenology::critical_temperature<T>(\n          applied_field, critical_temperature, Nb_B_c2, 0.5);\n  // correct depth for the surface layer\n  T _z_ = z - surface_thickness;\n  // correct film thickness for the surface layer\n  T _d_ = 0.5 * (film_thickness - surface_thickness);\n  if (_z_ < 0.0) {\n    return surface_rate;\n  } else {\n    // calculate the local field from the screening profile\n    T lambda = triumf::superconductivity::phenomenology::penetration_depth(\n        temperature, corrected_critical_temperature, exponent, lambda_0);\n    T screened_field = temperature > corrected_critical_temperature\n                           ? applied_field\n                           : applied_field *\n                                 std::cosh((0.5 * _d_ - _z_) / lambda) /\n                                 std::cosh(0.5 * _d_ / lambda);\n    // calculate the dipole-dipole SLR rate in the superconducting state\n    T dd_rate = triumf::nmr::dipole_dipole::slr_rate<T>(\n        screened_field, dipole_field, correlation_rate,\n        triumf::bnmr::nuclei::lithium_8<T>::gyromagnetic_ratio(),\n        triumf::nmr::nuclei::niobium_93<T>::gyromagnetic_ratio());\n    // calculate the SLR rate in the normal state\n    T ns_rate = slr_constant * std::pow(temperature, slr_exponent);\n    // return the \"surface\" contribution at shallow depths\n    return dd_rate + ns_rate;\n  }\n}\n\n/// Model SLR rate for a thin film.\n/// The surface \"dead layer\" has the same SLR rate as the normal state.\ntemplate <typename T = double>\nT slr_rate_film_nss_z(T z, T temperature, T critical_temperature, T lambda_0,\n                      T exponent, T applied_field, T dipole_field,\n                      T correlation_rate, T slr_constant, T slr_exponent,\n                      T surface_thickness, T film_thickness) {\n  // correct for the field-dependence to the critical temperature\n  // https://doi.org/10.1103/PhysRevB.2.3545\n  // https://doi.org/10.1016/j.nima.2004.09.003\n  // https://doi.org/10.1088/0953-2048/25/6/065014\n  constexpr T Nb_B_c2 = 0.425; // T\n  T corrected_critical_temperature =\n      triumf::superconductivity::phenomenology::critical_temperature<T>(\n          applied_field, critical_temperature, Nb_B_c2, 0.5);\n  // correct depth for the surface layer\n  T _z_ = z - surface_thickness;\n  // correct film thickness for the surface layer\n  T _d_ = 0.5 * (film_thickness - surface_thickness);\n  if (_z_ < 0.0) {\n    // calculate the dipole-dipole SLR rate in the normal state\n    T dd_rate_surf = triumf::nmr::dipole_dipole::slr_rate<T>(\n        applied_field, dipole_field, correlation_rate,\n        triumf::bnmr::nuclei::lithium_8<T>::gyromagnetic_ratio(),\n        triumf::nmr::nuclei::niobium_93<T>::gyromagnetic_ratio());\n    // calculate the SLR rate in the normal state\n    T ns_rate_surf = slr_constant * std::pow(temperature, slr_exponent);\n    // return the \"surface\" contribution at shallow depths\n    return dd_rate_surf + ns_rate_surf;\n  } else {\n    // calculate the local field from the screening profile\n    T lambda = triumf::superconductivity::phenomenology::penetration_depth(\n        temperature, corrected_critical_temperature, exponent, lambda_0);\n    T screened_field = temperature > corrected_critical_temperature\n                           ? applied_field\n                           : applied_field *\n                                 std::cosh((0.5 * _d_ - _z_) / lambda) /\n                                 std::cosh(0.5 * _d_ / lambda);\n    // calculate the dipole-dipole SLR rate in the superconducting state\n    T dd_rate = triumf::nmr::dipole_dipole::slr_rate<T>(\n        screened_field, dipole_field, correlation_rate,\n        triumf::bnmr::nuclei::lithium_8<T>::gyromagnetic_ratio(),\n        triumf::nmr::nuclei::niobium_93<T>::gyromagnetic_ratio());\n    // calculate the SLR rate in the normal state\n    T ns_rate = slr_constant * std::pow(temperature, slr_exponent);\n    // return the \"surface\" contribution at shallow depths\n    return dd_rate + ns_rate;\n  }\n}\n\n/// Depth-resolved analyzer.\n/// For implantation averaging over the SLR model (independent surface rate).\ntemplate <typename T = double> class DepthResolvedAnalyzer {\npublic:\n  /// constructor.\n  DepthResolvedAnalyzer(const std::string &csv_filename) {\n    // read in the data for the stopping profiles\n    read_csv_data(csv_filename);\n\n    // default initialized values\n    temperature = 2.5;\n    critical_temperature = 9.25;\n    lambda_0 = 40.0;\n    exponent = 4.0;\n    applied_field = 0.02;\n    dipole_field = 1e-5;\n    correlation_rate = 1.0 / 23.8e-6;\n    slr_constant = 0.75;\n    slr_exponent = 1.0;\n    surface_thickness = 5.0;\n    surface_rate = 10.0;\n  };\n\n  /// Read the CSV data\n  void read_csv_data(const std::string &csv_filename) {\n    // read the data into a ROOT DataFrame...\n    auto df = ROOT::RDF::MakeCsvDataFrame(csv_filename);\n    // ...and extract the values\n    _energy = df.Take<T>(\"Energy (keV)\").GetValue();\n    _alpha_1 = df.Take<T>(\"alpha_1\").GetValue();\n    _alpha_1_error = df.Take<T>(\"alpha_1_error\").GetValue();\n    _beta_1 = df.Take<T>(\"beta_1\").GetValue();\n    _beta_1_error = df.Take<T>(\"beta_1_error\").GetValue();\n    _z_max_1 = df.Take<T>(\"z_max_1\").GetValue();\n    _z_max_1_error = df.Take<T>(\"z_max_1_error\").GetValue();\n    _fraction_1 = df.Take<T>(\"fraction_1\").GetValue();\n    _fraction_1_error = df.Take<T>(\"fraction_1_error\").GetValue();\n    _alpha_2 = df.Take<T>(\"alpha_2\").GetValue();\n    _alpha_2_error = df.Take<T>(\"alpha_2_error\").GetValue();\n    _beta_2 = df.Take<T>(\"beta_2\").GetValue();\n    _beta_2_error = df.Take<T>(\"beta_2_error\").GetValue();\n    _z_max_2 = df.Take<T>(\"z_max_2\").GetValue();\n    _z_max_2_error = df.Take<T>(\"z_max_2_error\").GetValue();\n  };\n\n  /// Return the the minium energy available for interpolation.\n  T energy_min() {\n    return *std::min_element(_energy.begin(), _energy.end()) +\n           std::sqrt(std::numeric_limits<T>::epsilon());\n  };\n\n  /// Return the the maximum energy available for interpolation.\n  T energy_max() {\n    return *std::max_element(_energy.begin(), _energy.end()) -\n           std::sqrt(std::numeric_limits<T>::epsilon());\n  };\n\n  /// Return an interpolated alpha_1 value.\n  T alpha_1(T energy_keV) {\n    static boost::math::interpolators::pchip<std::vector<T>>\n        alpha_interpolator_1(std::move(std::vector<T>(_energy)),\n                             std::move(std::vector<T>(_alpha_1)));\n    return alpha_interpolator_1(energy_keV);\n  };\n\n  /// Return an interpolated alpha_2 value.\n  T alpha_2(T energy_keV) {\n    static boost::math::interpolators::pchip<std::vector<T>>\n        alpha_interpolator_2(std::move(std::vector<T>(_energy)),\n                             std::move(std::vector<T>(_alpha_2)));\n    return alpha_interpolator_2(energy_keV);\n  };\n\n  /// Return an interpolated beta_1 value.\n  T beta_1(T energy_keV) {\n    static boost::math::interpolators::pchip<std::vector<T>>\n        beta_interpolator_1(std::move(std::vector<T>(_energy)),\n                            std::move(std::vector<T>(_beta_1)));\n    return beta_interpolator_1(energy_keV);\n  };\n\n  /// Return an interpolated beta_2 value.\n  T beta_2(T energy_keV) {\n    static boost::math::interpolators::pchip<std::vector<T>>\n        beta_interpolator_2(std::move(std::vector<T>(_energy)),\n                            std::move(std::vector<T>(_beta_2)));\n    return beta_interpolator_2(energy_keV);\n  };\n\n  /// Return an interpolated z_max_1 value.\n  T z_max_1(T energy_keV) {\n    static boost::math::interpolators::pchip<std::vector<T>>\n        z_max_interpolator_1(std::move(std::vector<T>(_energy)),\n                             std::move(std::vector<T>(_z_max_1)));\n    return z_max_interpolator_1(energy_keV);\n  };\n\n  /// Return an interpolated z_max_2 value.\n  T z_max_2(T energy_keV) {\n    static boost::math::interpolators::pchip<std::vector<T>>\n        z_max_interpolator_2(std::move(std::vector<T>(_energy)),\n                             std::move(std::vector<T>(_z_max_2)));\n    return z_max_interpolator_2(energy_keV);\n  };\n\n  /// Return an interpolated fraction_1 value.\n  T fraction_1(T energy_keV) {\n    static boost::math::interpolators::pchip<std::vector<T>>\n        fraction_interpolator_1(std::move(std::vector<T>(_energy)),\n                                std::move(std::vector<T>(_fraction_1)));\n    return fraction_interpolator_1(energy_keV);\n  };\n\n  /// Return the average implantation depth.\n  T z_average(T energy_keV) {\n    T a_1 = alpha_1(energy_keV);\n    T b_1 = beta_1(energy_keV);\n    T zm_1 = z_max_1(energy_keV);\n    T f_1 = fraction_1(energy_keV);\n    T a_2 = alpha_2(energy_keV);\n    T b_2 = beta_2(energy_keV);\n    T zm_2 = z_max_2(energy_keV);\n    return f_1 * zm_1 * a_1 / (a_1 + b_1) +\n           (1.0 - f_1) * zm_2 * a_2 / (a_2 + b_2);\n  };\n\n  /// depth-averaging using numeric integration\n  T operator()(T energy_keV) {\n    static boost::math::quadrature::tanh_sinh<T> integrator;\n    auto integrand = [&](T z) {\n      return slr_rate_z<T>(z, temperature, critical_temperature, lambda_0,\n                           exponent, applied_field, dipole_field,\n                           correlation_rate, slr_constant, slr_exponent,\n                           surface_thickness, surface_rate) *\n             triumf::math::pdf::two_modified_beta<T>(\n                 z, alpha_1(energy_keV), beta_1(energy_keV),\n                 z_max_1(energy_keV), fraction_1(energy_keV),\n                 alpha_2(energy_keV), beta_2(energy_keV), z_max_2(energy_keV));\n    };\n    T z_max = std::max(z_max_1(energy_keV), z_max_2(energy_keV));\n    T Q = integrator.integrate(integrand, 0.0, z_max);\n    return Q;\n  };\n\n  /// model parameters\n  T temperature;\n  T critical_temperature;\n  T lambda_0;\n  T exponent;\n  T applied_field;\n  T dipole_field;\n  T correlation_rate;\n  T slr_constant;\n  T slr_exponent;\n  T surface_thickness;\n  T surface_rate;\n  T electron_phonon_coupling;\n\nprivate:\n  /// vectors of data from csv file\n  std::vector<T> _energy;\n  std::vector<T> _alpha_1;\n  std::vector<T> _alpha_1_error;\n  std::vector<T> _beta_1;\n  std::vector<T> _beta_1_error;\n  std::vector<T> _z_max_1;\n  std::vector<T> _z_max_1_error;\n  std::vector<T> _fraction_1;\n  std::vector<T> _fraction_1_error;\n  std::vector<T> _alpha_2;\n  std::vector<T> _alpha_2_error;\n  std::vector<T> _beta_2;\n  std::vector<T> _beta_2_error;\n  std::vector<T> _z_max_2;\n  std::vector<T> _z_max_2_error;\n};\n\n/// Depth-resolved analyzer.\n/// For implantation averaging over the SLR model (normal state surface rate).\ntemplate <typename T = double> class DepthResolvedAnalyzerNSS {\npublic:\n  /// constructor.\n  DepthResolvedAnalyzerNSS(const std::string &csv_filename) {\n    // read in the data for the stopping profiles\n    read_csv_data(csv_filename);\n\n    // default initialized values\n    temperature = 2.5;\n    critical_temperature = 9.25;\n    lambda_0 = 40.0;\n    exponent = 4.0;\n    applied_field = 0.02;\n    dipole_field = 1e-5;\n    correlation_rate = 1.0 / 23.8e-6;\n    slr_constant = 0.75;\n    slr_exponent = 1.0;\n    surface_thickness = 5.0;\n    surface_rate = 10.0;\n  };\n\n  /// Read the CSV data\n  void read_csv_data(const std::string &csv_filename) {\n    // read the data into a ROOT DataFrame...\n    auto df = ROOT::RDF::MakeCsvDataFrame(csv_filename);\n    // ...and extract the values\n    _energy = df.Take<T>(\"Energy (keV)\").GetValue();\n    _alpha_1 = df.Take<T>(\"alpha_1\").GetValue();\n    _alpha_1_error = df.Take<T>(\"alpha_1_error\").GetValue();\n    _beta_1 = df.Take<T>(\"beta_1\").GetValue();\n    _beta_1_error = df.Take<T>(\"beta_1_error\").GetValue();\n    _z_max_1 = df.Take<T>(\"z_max_1\").GetValue();\n    _z_max_1_error = df.Take<T>(\"z_max_1_error\").GetValue();\n    _fraction_1 = df.Take<T>(\"fraction_1\").GetValue();\n    _fraction_1_error = df.Take<T>(\"fraction_1_error\").GetValue();\n    _alpha_2 = df.Take<T>(\"alpha_2\").GetValue();\n    _alpha_2_error = df.Take<T>(\"alpha_2_error\").GetValue();\n    _beta_2 = df.Take<T>(\"beta_2\").GetValue();\n    _beta_2_error = df.Take<T>(\"beta_2_error\").GetValue();\n    _z_max_2 = df.Take<T>(\"z_max_2\").GetValue();\n    _z_max_2_error = df.Take<T>(\"z_max_2_error\").GetValue();\n  };\n\n  /// Return the the minium energy available for interpolation.\n  T energy_min() {\n    return *std::min_element(_energy.begin(), _energy.end()) +\n           std::sqrt(std::numeric_limits<T>::epsilon());\n  };\n\n  /// Return the the maximum energy available for interpolation.\n  T energy_max() {\n    return *std::max_element(_energy.begin(), _energy.end()) -\n           std::sqrt(std::numeric_limits<T>::epsilon());\n  };\n\n  /// Return an interpolated alpha_1 value.\n  T alpha_1(T energy_keV) {\n    static boost::math::interpolators::pchip<std::vector<T>>\n        alpha_interpolator_1(std::move(std::vector<T>(_energy)),\n                             std::move(std::vector<T>(_alpha_1)));\n    return alpha_interpolator_1(energy_keV);\n  };\n\n  /// Return an interpolated alpha_2 value.\n  T alpha_2(T energy_keV) {\n    static boost::math::interpolators::pchip<std::vector<T>>\n        alpha_interpolator_2(std::move(std::vector<T>(_energy)),\n                             std::move(std::vector<T>(_alpha_2)));\n    return alpha_interpolator_2(energy_keV);\n  };\n\n  /// Return an interpolated beta_1 value.\n  T beta_1(T energy_keV) {\n    static boost::math::interpolators::pchip<std::vector<T>>\n        beta_interpolator_1(std::move(std::vector<T>(_energy)),\n                            std::move(std::vector<T>(_beta_1)));\n    return beta_interpolator_1(energy_keV);\n  };\n\n  /// Return an interpolated beta_2 value.\n  T beta_2(T energy_keV) {\n    static boost::math::interpolators::pchip<std::vector<T>>\n        beta_interpolator_2(std::move(std::vector<T>(_energy)),\n                            std::move(std::vector<T>(_beta_2)));\n    return beta_interpolator_2(energy_keV);\n  };\n\n  /// Return an interpolated z_max_1 value.\n  T z_max_1(T energy_keV) {\n    static boost::math::interpolators::pchip<std::vector<T>>\n        z_max_interpolator_1(std::move(std::vector<T>(_energy)),\n                             std::move(std::vector<T>(_z_max_1)));\n    return z_max_interpolator_1(energy_keV);\n  };\n\n  /// Return an interpolated z_max_2 value.\n  T z_max_2(T energy_keV) {\n    static boost::math::interpolators::pchip<std::vector<T>>\n        z_max_interpolator_2(std::move(std::vector<T>(_energy)),\n                             std::move(std::vector<T>(_z_max_2)));\n    return z_max_interpolator_2(energy_keV);\n  };\n\n  /// Return an interpolated fraction_1 value.\n  T fraction_1(T energy_keV) {\n    static boost::math::interpolators::pchip<std::vector<T>>\n        fraction_interpolator_1(std::move(std::vector<T>(_energy)),\n                                std::move(std::vector<T>(_fraction_1)));\n    return fraction_interpolator_1(energy_keV);\n  };\n\n  /// Return the average implantation depth.\n  T z_average(T energy_keV) {\n    T a_1 = alpha_1(energy_keV);\n    T b_1 = beta_1(energy_keV);\n    T zm_1 = z_max_1(energy_keV);\n    T f_1 = fraction_1(energy_keV);\n    T a_2 = alpha_2(energy_keV);\n    T b_2 = beta_2(energy_keV);\n    T zm_2 = z_max_2(energy_keV);\n    return f_1 * zm_1 * a_1 / (a_1 + b_1) +\n           (1.0 - f_1) * zm_2 * a_2 / (a_2 + b_2);\n  };\n\n  /// depth-averaging using numeric integration\n  T operator()(T energy_keV) {\n    static boost::math::quadrature::tanh_sinh<T> integrator;\n    auto integrand = [&](T z) {\n      return slr_rate_nss_z<T>(z, temperature, critical_temperature, lambda_0,\n                               exponent, applied_field, dipole_field,\n                               correlation_rate, slr_constant, slr_exponent,\n                               surface_thickness) *\n             triumf::math::pdf::two_modified_beta<T>(\n                 z, alpha_1(energy_keV), beta_1(energy_keV),\n                 z_max_1(energy_keV), fraction_1(energy_keV),\n                 alpha_2(energy_keV), beta_2(energy_keV), z_max_2(energy_keV));\n    };\n    T z_max = std::max(z_max_1(energy_keV), z_max_2(energy_keV));\n    T Q = integrator.integrate(integrand, 0.0, z_max);\n    return Q;\n  };\n\n  /// model parameters\n  T temperature;\n  T critical_temperature;\n  T lambda_0;\n  T exponent;\n  T applied_field;\n  T dipole_field;\n  T correlation_rate;\n  T slr_constant;\n  T slr_exponent;\n  T surface_thickness;\n  T surface_rate;\n  T electron_phonon_coupling;\n\nprivate:\n  /// vectors of data from csv file\n  std::vector<T> _energy;\n  std::vector<T> _alpha_1;\n  std::vector<T> _alpha_1_error;\n  std::vector<T> _beta_1;\n  std::vector<T> _beta_1_error;\n  std::vector<T> _z_max_1;\n  std::vector<T> _z_max_1_error;\n  std::vector<T> _fraction_1;\n  std::vector<T> _fraction_1_error;\n  std::vector<T> _alpha_2;\n  std::vector<T> _alpha_2_error;\n  std::vector<T> _beta_2;\n  std::vector<T> _beta_2_error;\n  std::vector<T> _z_max_2;\n  std::vector<T> _z_max_2_error;\n};\n\n/// Depth-resolved analyzer for thin films.\n/// For implantation averaging over the SLR model (independent surface rate).\ntemplate <typename T = double> class DepthResolvedFilmAnalyzer {\npublic:\n  /// constructor.\n  DepthResolvedFilmAnalyzer(const std::string &csv_filename) {\n    // read in the data for the stopping profiles\n    read_csv_data(csv_filename);\n\n    // default initialized values\n    temperature = 2.5;\n    critical_temperature = 9.25;\n    lambda_0 = 40.0;\n    exponent = 4.0;\n    applied_field = 0.02;\n    dipole_field = 1e-5;\n    correlation_rate = 1.0 / 23.8e-6;\n    slr_constant = 0.75;\n    slr_exponent = 1.0;\n    surface_thickness = 5.0;\n    surface_rate = 10.0;\n    film_thickness = 300.0;\n  };\n\n  /// Read the CSV data\n  void read_csv_data(const std::string &csv_filename) {\n    // read the data into a ROOT DataFrame...\n    auto df = ROOT::RDF::MakeCsvDataFrame(csv_filename);\n    // ...and extract the values\n    _energy = df.Take<T>(\"Energy (keV)\").GetValue();\n    _alpha_1 = df.Take<T>(\"alpha_1\").GetValue();\n    _alpha_1_error = df.Take<T>(\"alpha_1_error\").GetValue();\n    _beta_1 = df.Take<T>(\"beta_1\").GetValue();\n    _beta_1_error = df.Take<T>(\"beta_1_error\").GetValue();\n    _z_max_1 = df.Take<T>(\"z_max_1\").GetValue();\n    _z_max_1_error = df.Take<T>(\"z_max_1_error\").GetValue();\n    _fraction_1 = df.Take<T>(\"fraction_1\").GetValue();\n    _fraction_1_error = df.Take<T>(\"fraction_1_error\").GetValue();\n    _alpha_2 = df.Take<T>(\"alpha_2\").GetValue();\n    _alpha_2_error = df.Take<T>(\"alpha_2_error\").GetValue();\n    _beta_2 = df.Take<T>(\"beta_2\").GetValue();\n    _beta_2_error = df.Take<T>(\"beta_2_error\").GetValue();\n    _z_max_2 = df.Take<T>(\"z_max_2\").GetValue();\n    _z_max_2_error = df.Take<T>(\"z_max_2_error\").GetValue();\n  };\n\n  /// Return the the minium energy available for interpolation.\n  T energy_min() {\n    return *std::min_element(_energy.begin(), _energy.end()) +\n           std::sqrt(std::numeric_limits<T>::epsilon());\n  };\n\n  /// Return the the maximum energy available for interpolation.\n  T energy_max() {\n    return *std::max_element(_energy.begin(), _energy.end()) -\n           std::sqrt(std::numeric_limits<T>::epsilon());\n  };\n\n  /// Return an interpolated alpha_1 value.\n  T alpha_1(T energy_keV) {\n    static boost::math::interpolators::pchip<std::vector<T>>\n        alpha_interpolator_1(std::move(std::vector<T>(_energy)),\n                             std::move(std::vector<T>(_alpha_1)));\n    return alpha_interpolator_1(energy_keV);\n  };\n\n  /// Return an interpolated alpha_2 value.\n  T alpha_2(T energy_keV) {\n    static boost::math::interpolators::pchip<std::vector<T>>\n        alpha_interpolator_2(std::move(std::vector<T>(_energy)),\n                             std::move(std::vector<T>(_alpha_2)));\n    return alpha_interpolator_2(energy_keV);\n  };\n\n  /// Return an interpolated beta_1 value.\n  T beta_1(T energy_keV) {\n    static boost::math::interpolators::pchip<std::vector<T>>\n        beta_interpolator_1(std::move(std::vector<T>(_energy)),\n                            std::move(std::vector<T>(_beta_1)));\n    return beta_interpolator_1(energy_keV);\n  };\n\n  /// Return an interpolated beta_2 value.\n  T beta_2(T energy_keV) {\n    static boost::math::interpolators::pchip<std::vector<T>>\n        beta_interpolator_2(std::move(std::vector<T>(_energy)),\n                            std::move(std::vector<T>(_beta_2)));\n    return beta_interpolator_2(energy_keV);\n  };\n\n  /// Return an interpolated z_max_1 value.\n  T z_max_1(T energy_keV) {\n    static boost::math::interpolators::pchip<std::vector<T>>\n        z_max_interpolator_1(std::move(std::vector<T>(_energy)),\n                             std::move(std::vector<T>(_z_max_1)));\n    return z_max_interpolator_1(energy_keV);\n  };\n\n  /// Return an interpolated z_max_2 value.\n  T z_max_2(T energy_keV) {\n    static boost::math::interpolators::pchip<std::vector<T>>\n        z_max_interpolator_2(std::move(std::vector<T>(_energy)),\n                             std::move(std::vector<T>(_z_max_2)));\n    return z_max_interpolator_2(energy_keV);\n  };\n\n  /// Return an interpolated fraction_1 value.\n  T fraction_1(T energy_keV) {\n    static boost::math::interpolators::pchip<std::vector<T>>\n        fraction_interpolator_1(std::move(std::vector<T>(_energy)),\n                                std::move(std::vector<T>(_fraction_1)));\n    return fraction_interpolator_1(energy_keV);\n  };\n\n  /// Return the average implantation depth.\n  T z_average(T energy_keV) {\n    T a_1 = alpha_1(energy_keV);\n    T b_1 = beta_1(energy_keV);\n    T zm_1 = z_max_1(energy_keV);\n    T f_1 = fraction_1(energy_keV);\n    T a_2 = alpha_2(energy_keV);\n    T b_2 = beta_2(energy_keV);\n    T zm_2 = z_max_2(energy_keV);\n    return f_1 * zm_1 * a_1 / (a_1 + b_1) +\n           (1.0 - f_1) * zm_2 * a_2 / (a_2 + b_2);\n  };\n\n  /// depth-averaging using numeric integration\n  T operator()(T energy_keV) {\n    static boost::math::quadrature::tanh_sinh<T> integrator;\n    auto integrand = [&](T z) {\n      return slr_rate_film_z<T>(z, temperature, critical_temperature, lambda_0,\n                                exponent, applied_field, dipole_field,\n                                correlation_rate, slr_constant, slr_exponent,\n                                surface_thickness, surface_rate,\n                                film_thickness) *\n             triumf::math::pdf::two_modified_beta<T>(\n                 z, alpha_1(energy_keV), beta_1(energy_keV),\n                 z_max_1(energy_keV), fraction_1(energy_keV),\n                 alpha_2(energy_keV), beta_2(energy_keV), z_max_2(energy_keV));\n    };\n    T z_max = std::max(z_max_1(energy_keV), z_max_2(energy_keV));\n    T Q = integrator.integrate(integrand, 0.0, z_max);\n    return Q;\n  };\n\n  /// model parameters\n  T temperature;\n  T critical_temperature;\n  T lambda_0;\n  T exponent;\n  T applied_field;\n  T dipole_field;\n  T correlation_rate;\n  T slr_constant;\n  T slr_exponent;\n  T surface_thickness;\n  T surface_rate;\n  T electron_phonon_coupling;\n  T film_thickness;\n\nprivate:\n  /// vectors of data from csv file\n  std::vector<T> _energy;\n  std::vector<T> _alpha_1;\n  std::vector<T> _alpha_1_error;\n  std::vector<T> _beta_1;\n  std::vector<T> _beta_1_error;\n  std::vector<T> _z_max_1;\n  std::vector<T> _z_max_1_error;\n  std::vector<T> _fraction_1;\n  std::vector<T> _fraction_1_error;\n  std::vector<T> _alpha_2;\n  std::vector<T> _alpha_2_error;\n  std::vector<T> _beta_2;\n  std::vector<T> _beta_2_error;\n  std::vector<T> _z_max_2;\n  std::vector<T> _z_max_2_error;\n};\n\n/// Depth-resolved analyzer for thin films.\n/// For implantation averaging over the SLR model (normal state surface rate).\ntemplate <typename T = double> class DepthResolvedFilmAnalyzerNSS {\npublic:\n  /// constructor.\n  DepthResolvedFilmAnalyzerNSS(const std::string &csv_filename) {\n    // read in the data for the stopping profiles\n    read_csv_data(csv_filename);\n\n    // default initialized values\n    temperature = 2.5;\n    critical_temperature = 9.25;\n    lambda_0 = 40.0;\n    exponent = 4.0;\n    applied_field = 0.02;\n    dipole_field = 1e-5;\n    correlation_rate = 1.0 / 23.8e-6;\n    slr_constant = 0.75;\n    slr_exponent = 1.0;\n    surface_thickness = 5.0;\n    surface_rate = 10.0;\n    film_thickness = 300.0;\n  };\n\n  /// Read the CSV data\n  void read_csv_data(const std::string &csv_filename) {\n    // read the data into a ROOT DataFrame...\n    auto df = ROOT::RDF::MakeCsvDataFrame(csv_filename);\n    // ...and extract the values\n    _energy = df.Take<T>(\"Energy (keV)\").GetValue();\n    _alpha_1 = df.Take<T>(\"alpha_1\").GetValue();\n    _alpha_1_error = df.Take<T>(\"alpha_1_error\").GetValue();\n    _beta_1 = df.Take<T>(\"beta_1\").GetValue();\n    _beta_1_error = df.Take<T>(\"beta_1_error\").GetValue();\n    _z_max_1 = df.Take<T>(\"z_max_1\").GetValue();\n    _z_max_1_error = df.Take<T>(\"z_max_1_error\").GetValue();\n    _fraction_1 = df.Take<T>(\"fraction_1\").GetValue();\n    _fraction_1_error = df.Take<T>(\"fraction_1_error\").GetValue();\n    _alpha_2 = df.Take<T>(\"alpha_2\").GetValue();\n    _alpha_2_error = df.Take<T>(\"alpha_2_error\").GetValue();\n    _beta_2 = df.Take<T>(\"beta_2\").GetValue();\n    _beta_2_error = df.Take<T>(\"beta_2_error\").GetValue();\n    _z_max_2 = df.Take<T>(\"z_max_2\").GetValue();\n    _z_max_2_error = df.Take<T>(\"z_max_2_error\").GetValue();\n  };\n\n  /// Return the the minium energy available for interpolation.\n  T energy_min() {\n    return *std::min_element(_energy.begin(), _energy.end()) +\n           std::sqrt(std::numeric_limits<T>::epsilon());\n  };\n\n  /// Return the the maximum energy available for interpolation.\n  T energy_max() {\n    return *std::max_element(_energy.begin(), _energy.end()) -\n           std::sqrt(std::numeric_limits<T>::epsilon());\n  };\n\n  /// Return an interpolated alpha_1 value.\n  T alpha_1(T energy_keV) {\n    static boost::math::interpolators::pchip<std::vector<T>>\n        alpha_interpolator_1(std::move(std::vector<T>(_energy)),\n                             std::move(std::vector<T>(_alpha_1)));\n    return alpha_interpolator_1(energy_keV);\n  };\n\n  /// Return an interpolated alpha_2 value.\n  T alpha_2(T energy_keV) {\n    static boost::math::interpolators::pchip<std::vector<T>>\n        alpha_interpolator_2(std::move(std::vector<T>(_energy)),\n                             std::move(std::vector<T>(_alpha_2)));\n    return alpha_interpolator_2(energy_keV);\n  };\n\n  /// Return an interpolated beta_1 value.\n  T beta_1(T energy_keV) {\n    static boost::math::interpolators::pchip<std::vector<T>>\n        beta_interpolator_1(std::move(std::vector<T>(_energy)),\n                            std::move(std::vector<T>(_beta_1)));\n    return beta_interpolator_1(energy_keV);\n  };\n\n  /// Return an interpolated beta_2 value.\n  T beta_2(T energy_keV) {\n    static boost::math::interpolators::pchip<std::vector<T>>\n        beta_interpolator_2(std::move(std::vector<T>(_energy)),\n                            std::move(std::vector<T>(_beta_2)));\n    return beta_interpolator_2(energy_keV);\n  };\n\n  /// Return an interpolated z_max_1 value.\n  T z_max_1(T energy_keV) {\n    static boost::math::interpolators::pchip<std::vector<T>>\n        z_max_interpolator_1(std::move(std::vector<T>(_energy)),\n                             std::move(std::vector<T>(_z_max_1)));\n    return z_max_interpolator_1(energy_keV);\n  };\n\n  /// Return an interpolated z_max_2 value.\n  T z_max_2(T energy_keV) {\n    static boost::math::interpolators::pchip<std::vector<T>>\n        z_max_interpolator_2(std::move(std::vector<T>(_energy)),\n                             std::move(std::vector<T>(_z_max_2)));\n    return z_max_interpolator_2(energy_keV);\n  };\n\n  /// Return an interpolated fraction_1 value.\n  T fraction_1(T energy_keV) {\n    static boost::math::interpolators::pchip<std::vector<T>>\n        fraction_interpolator_1(std::move(std::vector<T>(_energy)),\n                                std::move(std::vector<T>(_fraction_1)));\n    return fraction_interpolator_1(energy_keV);\n  };\n\n  /// Return the average implantation depth.\n  T z_average(T energy_keV) {\n    T a_1 = alpha_1(energy_keV);\n    T b_1 = beta_1(energy_keV);\n    T zm_1 = z_max_1(energy_keV);\n    T f_1 = fraction_1(energy_keV);\n    T a_2 = alpha_2(energy_keV);\n    T b_2 = beta_2(energy_keV);\n    T zm_2 = z_max_2(energy_keV);\n    return f_1 * zm_1 * a_1 / (a_1 + b_1) +\n           (1.0 - f_1) * zm_2 * a_2 / (a_2 + b_2);\n  };\n\n  /// depth-averaging using numeric integration\n  T operator()(T energy_keV) {\n    static boost::math::quadrature::tanh_sinh<T> integrator;\n    auto integrand = [&](T z) {\n      return slr_rate_film_nss_z<T>(\n                 z, temperature, critical_temperature, lambda_0, exponent,\n                 applied_field, dipole_field, correlation_rate, slr_constant,\n                 slr_exponent, surface_thickness, film_thickness) *\n             triumf::math::pdf::two_modified_beta<T>(\n                 z, alpha_1(energy_keV), beta_1(energy_keV),\n                 z_max_1(energy_keV), fraction_1(energy_keV),\n                 alpha_2(energy_keV), beta_2(energy_keV), z_max_2(energy_keV));\n    };\n    T z_max = std::max(z_max_1(energy_keV), z_max_2(energy_keV));\n    T Q = integrator.integrate(integrand, 0.0, z_max);\n    return Q;\n  };\n\n  /// model parameters\n  T temperature;\n  T critical_temperature;\n  T lambda_0;\n  T exponent;\n  T applied_field;\n  T dipole_field;\n  T correlation_rate;\n  T slr_constant;\n  T slr_exponent;\n  T surface_thickness;\n  T surface_rate;\n  T electron_phonon_coupling;\n  T film_thickness;\n\nprivate:\n  /// vectors of data from csv file\n  std::vector<T> _energy;\n  std::vector<T> _alpha_1;\n  std::vector<T> _alpha_1_error;\n  std::vector<T> _beta_1;\n  std::vector<T> _beta_1_error;\n  std::vector<T> _z_max_1;\n  std::vector<T> _z_max_1_error;\n  std::vector<T> _fraction_1;\n  std::vector<T> _fraction_1_error;\n  std::vector<T> _alpha_2;\n  std::vector<T> _alpha_2_error;\n  std::vector<T> _beta_2;\n  std::vector<T> _beta_2_error;\n  std::vector<T> _z_max_2;\n  std::vector<T> _z_max_2_error;\n};\n\n} // namespace local\n\n} // namespace srf\n\n} // namespace bnmr\n\n} // namespace triumf\n\n#endif // TRIUMF_BNMR_SRF_LOCAL_HPP\n", "meta": {"hexsha": "2851d4da995803e483435dcae2fb870d8f2d82cb", "size": 35722, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/triumf/bnmr/srf/local.hpp", "max_stars_repo_name": "rmlmcfadden/triumfpp", "max_stars_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_stars_repo_licenses": ["MIT"], "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/triumf/bnmr/srf/local.hpp", "max_issues_repo_name": "rmlmcfadden/triumfpp", "max_issues_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_issues_repo_licenses": ["MIT"], "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/triumf/bnmr/srf/local.hpp", "max_forks_repo_name": "rmlmcfadden/triumfpp", "max_forks_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_forks_repo_licenses": ["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.0021276596, "max_line_length": 80, "alphanum_fraction": 0.6555623985, "num_tokens": 10122, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.48843400076030813}}
{"text": "//\n// Project: GraphicsUtils\n// File: MathTypes.hpp\n//\n// Copyright (c) 2019 Miika 'Lehdari' Lehtim\u00e4ki\n// You may use, distribute and modify this code under the terms\n// of the licence specified in file LICENSE which is distributed\n// with this source code package.\n//\n\n#ifndef GRAPHICSUTILS_MATHTYPES_HPP\n#define GRAPHICSUTILS_MATHTYPES_HPP\n\n\n#define EIGEN_DONT_PARALLELIZE\n#define EIGEN_RUNTIME_NO_MALLOC\n#define EIGEN_STACK_ALLOCATION_LIMIT 0\n\n\n#include <Eigen/Dense>\n#include <cstdint>\n\n\nusing Vec2f = Eigen::Vector2f;\nusing Vec3f = Eigen::Vector3f;\nusing Vec4f = Eigen::Vector4f;\nusing Mat2f = Eigen::Matrix2f;\nusing Mat3f = Eigen::Matrix3f;\nusing Mat4f = Eigen::Matrix4f;\n\nusing Vec2d = Eigen::Vector2d;\nusing Vec3d = Eigen::Vector3d;\nusing Vec4d = Eigen::Vector4d;\nusing Mat2d = Eigen::Matrix2d;\nusing Mat3d = Eigen::Matrix3d;\nusing Mat4d = Eigen::Matrix4d;\n\nusing Vec2i = Eigen::Vector2i;\nusing Vec3i = Eigen::Vector3i;\nusing Vec4i = Eigen::Vector4i;\nusing Mat2i = Eigen::Matrix2i;\nusing Mat3i = Eigen::Matrix3i;\nusing Mat4i = Eigen::Matrix4i;\n\n\n#endif //GRAPHICSUTILS_MATHTYPES_HPP\n", "meta": {"hexsha": "16ab19a10555d9b3481c42b0540d3b7d5e72014c", "size": 1091, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/MathTypes.hpp", "max_stars_repo_name": "Lehdari/Panoramachine", "max_stars_repo_head_hexsha": "af00840e8a2b2f5cd8bde4e8cd4037b9c7d43178", "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": "include/MathTypes.hpp", "max_issues_repo_name": "Lehdari/Panoramachine", "max_issues_repo_head_hexsha": "af00840e8a2b2f5cd8bde4e8cd4037b9c7d43178", "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": "include/MathTypes.hpp", "max_forks_repo_name": "Lehdari/Panoramachine", "max_forks_repo_head_hexsha": "af00840e8a2b2f5cd8bde4e8cd4037b9c7d43178", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.2127659574, "max_line_length": 64, "alphanum_fraction": 0.7626031164, "num_tokens": 338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359877, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.48837596883211676}}
{"text": "#pragma once\n\n#include <Eigen/Core>\n#include <autodiff/autodiff_types.hpp>\n\nnamespace ipc::rigid {\nnamespace autogen {\n\n    template <typename T> using Vector2T = Eigen::Matrix<T, 2, 1>;\n\n    template <typename T>\n    void time_of_impact_coeff(\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& a,\n        T& b,\n        T& c);\n\n    template <>\n    inline void time_of_impact_coeff<double>(\n        const Eigen::Vector2d& Vi,\n        const Eigen::Vector2d& Vj,\n        const Eigen::Vector2d& Vk,\n        const Vector2T<double>& Ui,\n        const Vector2T<double>& Uj,\n        const Vector2T<double>& Uk,\n        double& a,\n        double& b,\n        double& c)\n    {\n        a = -Ui[0] * Uj[1] + Ui[0] * Uk[1] + Ui[1] * Uj[0] - Ui[1] * Uk[0]\n            - Uj[0] * Uk[1] + Uj[1] * Uk[0];\n        b = -Ui[0] * Vj[1] + Ui[0] * Vk[1] + Ui[1] * Vj[0] - Ui[1] * Vk[0]\n            + Uj[0] * Vi[1] - Uj[0] * Vk[1] - Uj[1] * Vi[0] + Uj[1] * Vk[0]\n            - Uk[0] * Vi[1] + Uk[0] * Vj[1] + Uk[1] * Vi[0] - Uk[1] * Vj[0];\n        c = -Vi[0] * Vj[1] + Vi[0] * Vk[1] + Vi[1] * Vj[0] - Vi[1] * Vk[0]\n            - Vj[0] * Vk[1] + Vj[1] * Vk[0];\n\n        double max_coeff = std::max(a, std::max(b, c));\n        a /= max_coeff;\n        b /= max_coeff;\n        c /= max_coeff;\n    }\n\n} // namespace autogen\n} // namespace ipc::rigid\n\n#include \"auto_time_of_impact_coeff.ipp\"\n", "meta": {"hexsha": "83c02fb4c3bce6dc1bf6e1306a5667cf547c5b29", "size": 1520, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/autogen/time_of_impact_coeff.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/autogen/time_of_impact_coeff.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/autogen/time_of_impact_coeff.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": 28.679245283, "max_line_length": 76, "alphanum_fraction": 0.4953947368, "num_tokens": 560, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6261241772283035, "lm_q1q2_score": 0.48837241291552086}}
{"text": "#include <UnitTest++/UnitTest++.h>\n#include <stdexcept>\n#include <iostream>\n#include <cmath>\n#include <limits>\n#include <boost/filesystem.hpp>\n#include <fstream>\n\n#include \"coela_core/src/pixel_array_routines.h\"\n#include \"coela_analysis/src/psf_generation.h\"\n//#include \"../coela_analysis/src/psf_characterisation.h\"\n\nusing namespace coela;\nusing namespace std;\n\nSUITE(psf_generation)\n{\n\n    string test_suite_output_dir= string(UnitTestSuite::GetSuiteName()) + \"_tests/\";\n\n    TEST(Run_Standard_Suite_Setup) {\n        cout << \"*** \\\"\"<< UnitTestSuite::GetSuiteName() <<\"\\\" unit tests running ***\" <<endl;\n        boost::filesystem::create_directories(test_suite_output_dir);\n    }\n\n    TEST(gaussian_generation) {\n        PixelRange img_size(1,1,50,50);\n        double peak=5.0, sigma=1.2;\n        psf_models::GaussianPsfModel g_model(peak, sigma);\n\n        CcdPosition true_centre(img_size.x_dim()/2.0 + 0.5, img_size.y_dim()/2.0 +0.5);\n\n        psf_models::ReferencePsf ref_psf =\n            psf_models::generate_psf(g_model, img_size,\n                                     CcdPosition(0,0),\n                                     true_centre,\n                                     1.0,\n                                     2);\n\n        string filename = test_suite_output_dir + \"example_gauss_gen.fits\";\n        ref_psf.psf_image.write_to_file(filename);\n\n        PixelPosition centroid = pixel_array_routines::centroid(ref_psf.psf_image.pix,\n                                 ref_psf.psf_image.pix.range());\n\n        CcdPosition CCD_centroid = ref_psf.psf_image.CCD_grid.\n                                    corresponding_grid_Position(centroid);\n\n        CHECK_CLOSE(CCD_centroid.x, true_centre.x, 0.01);\n        CHECK_CLOSE(CCD_centroid.y, true_centre.y, 0.01);\n\n        double max_pixel = ref_psf.psf_image.pix(ref_psf.psf_image.pix.max_PixelIndex());\n\n        CHECK_CLOSE(max_pixel, g_model.peak_val, 0.25);\n\n        double est_flux = 2*M_PI*g_model.sigma_in_CCD_pix*g_model.sigma_in_CCD_pix *\n                          g_model.peak_val;\n        double actual_flux = ref_psf.psf_image.pix.sum();\n//        cerr<<\"Est flux:\"<<est_flux<<\"; actual: \"<<actual_flux<<endl;\n        CHECK_CLOSE(est_flux, actual_flux, est_flux*0.01);\n    }\n\n    TEST(airy_generation) {\n        double lambda = 7.7e-7;\n        double d=2.5;\n        double nyquist_pixel_width_rads = lambda / d / 2.0;\n\n        double central_obscuration=0.0;\n        psf_models::AiryPsfModel airy_gen(\n            1,\n            nyquist_pixel_width_rads,\n            lambda,\n            d,\n            central_obscuration\n        );\n\n        double first_minima_in_CCD_pix =\n            psf_models::find_first_minima_in_CCD_pix(airy_gen);\n//        cout<<\"minima \" <<first_minima<<endl;\n        double unit_peak_flux = psf_models::calculate_total_flux(airy_gen);\n\n        double first_minima_flux =\n            psf_models::calculate_flux_enclosed_at_radius(airy_gen,\n                    first_minima_in_CCD_pix);\n\n        double ratio = first_minima_flux  / unit_peak_flux;\n//        cout<<\"Flux ratio\" << ratio <<endl;\n\n        if (central_obscuration==0.0) {\n//            cout<<\"Circular aperture...\"<<endl;\n            CHECK_CLOSE(1.22*2.0, first_minima_in_CCD_pix, 0.01);\n            CHECK_CLOSE(0.838, ratio, 0.01); //83.8% flux inside first minima (Wikipedia)\n        } else if (central_obscuration==0.5) {\n            CHECK_CLOSE(1.16*2.0, first_minima_in_CCD_pix, 0.01);\n        }\n\n\n    }\n}\n", "meta": {"hexsha": "3250359f6a59b2f32b5f3398e6b6669aa84f5ae1", "size": 3462, "ext": "cc", "lang": "C++", "max_stars_repo_path": "coela_analysis/src/unit_tests/psf_generation_unit_tests.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/unit_tests/psf_generation_unit_tests.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/unit_tests/psf_generation_unit_tests.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": 34.62, "max_line_length": 94, "alphanum_fraction": 0.6140958983, "num_tokens": 874, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.48837241291552075}}
{"text": "#ifndef SPATHTPP\n#define SPATHTPP\n\n// -------------------------------------------------------\n//   \n//   Spatially-regularized Levenberg Marquardt algorithm\n//   Coded by J. de la Cruz Rodriguez (ISP-SU, 2020)\n//\n//   Reference: de la Cruz Rodriguez (2019):\n//   https://ui.adsabs.harvard.edu/abs/2019A%26A...631A.153D/abstract\n//\n//   -------------------------------------------------------\n\n#include <cmath>\n\n#include <Eigen/Sparse>\n#include <Eigen/Dense>\n#include <unsupported/Eigen/CXX11/Tensor>\n\nnamespace spa{\n\n  // ************************************************************** //\n  \n  template<class T> inline T SQ(T const &var){return var*var;}\n  \n  // ************************************************************** //\n\n  template <class T, typename U > U ksum(const size_t n, const T* const  __restrict__ arr){\n    \n    U sum = 0, c = 0;\n    \n    for(size_t kk = 0; kk<n; ++kk){\n      U const y = static_cast<U>(arr[kk]) - c;\n      U const t = sum + y;\n      c = (t - sum) - y;\n      sum = t;\n    }\n    \n    return sum;\n  }\n  \n  // ************************************************************** //\n\n  template <class T, typename U > U ksum2(const size_t n, const T* const __restrict__ arr){\n    \n    U sum = 0, c = 0;\n    \n    for(size_t kk = 0; kk<n; ++kk){\n      U const y = SQ<U>(static_cast<U>(arr[kk])) - c;\n      U const t = sum + y;\n      c = (t - sum) - y;\n      sum = t;\n    }\n    \n    return sum;\n  }\n  // ************************************************************** //\n\n  template <class T, typename U > U ksumMult(const size_t n, const T* const __restrict__ arr, const T* const __restrict__ arr1){\n    \n    U sum = 0, c = 0;\n    \n    for(size_t kk = 0; kk<n; ++kk){\n      U const y = static_cast<U>(arr[kk]*arr1[kk]) - c;\n      U const t = sum + y;\n      c = (t - sum) - y;\n      sum = t;\n    }\n    \n    return sum;\n  }\n  // ************************************************************** //\n\n  template<typename T>\n  struct Par{\n    bool isCyclic;\n    bool limited;\n    T scale;\n    T limits[2];\n    T alpha;\n\n    Par(): isCyclic(false), limited(false), scale(1.0), limits{0,0}, alpha(0){};\n    Par(bool const cyclic, bool const ilimited, T const scal, T const mi, T const ma, T const alp):\n      isCyclic(cyclic), limited(ilimited), scale(scal), limits{mi,ma}, alpha(alp){};\n\n    Par(Par<T> const& in): isCyclic(in.isCyclic) ,limited(in.limited), scale(in.scale), limits{in.limits[0], in.limits[1]}, alpha(in.alpha){};\n\n    Par<T> &operator=(Par<T> const& in)\n    {\n      isCyclic = in.isCyclic, limited = in.limited, scale=in.scale, limits[0]=in.limits[0], limits[1]=in.limits[1], alpha = in.alpha;\n      return *this;\n    }\n\n    // ---------------------------------------------------------- //\n    \n    inline void Normalize(T &val)const{val /= scale;};\n    \n    // ---------------------------------------------------------- //\n\n    inline void Scale(T &val)const{val *= scale;};\n    \n    // ---------------------------------------------------------- //\n\n    inline void Check(T &val)const{\n      if(!limited) return;\n      if(isCyclic){\n\tif(val > limits[1]) val -= 3.1415926f;\n\tif(val < limits[0]) val += 3.1416026f;\n      }\n      val = std::max<T>(std::min<T>(val, limits[1]),limits[0]);\n    }\n    \n    // ---------------------------------------------------------- //\n\n    inline void CheckNormalized(T &val)const{\n      if(!limited) return;\n      Scale(val);\n      Check(val);\n      Normalize(val);\n    }\n    \n  };\n  \n  // ************************************************************** //\n\n  template<typename T> struct Chi2{\n    T chi2;\n    T pen2;\n\n    Chi2(T const ichi2, T const ipen2): chi2(ichi2), pen2(ipen2){};\n\n    Chi2(): chi2(0), pen2(0){};\n\n    Chi2(Chi2<T> const& in): chi2(in.chi2), pen2(in.pen2){};\n\n    Chi2<T> &operator=(Chi2<T> const& in){chi2 = in.chi2; pen2 = in.pen2; return *this;}\n\n    inline T value()const{return chi2 + pen2;}\n    \n    // ---------------------------------------------------------- //\n\n    std::string formatted()const{\n      char bla[50];\n      sprintf(bla, \"%13.5f (%13.5f + %13.5f)\", value(), chi2, pen2);\n      return std::string(bla);\n    }\n    \n    // ---------------------------------------------------------- //\n\n    T operator()()const{return value();}\n    \n  };\n\n  // ************************************************************** //\n  \n  template<typename T> struct container{\n    int nDat, ny, nx, Nreal;\n    T mu;\n    Eigen::TensorMap<Eigen::Tensor<T,3, Eigen::RowMajor>> obs;\n    Eigen::Matrix<T,Eigen::Dynamic,1> sig;\n    \n    std::vector<Par<T>> Pinfo;\n    std::vector<const ml::Milne<T>*> Me;\n\n    int getNreal()const{return Nreal;}\n    \n    container(): nDat(0), ny(0), nx(0), Nreal(1), mu(1),   sig(), Pinfo(), Me(){};\n\n    // ------------------------------------------------------------ //\n    \n    container(int const iny, int const inx, T const iMu, int const inDat, T* const __restrict__ iobs,\n\t      const T* const __restrict__ isig,\n\t      std::vector<Par<T>> const& Pinfo_in, std::vector<ml::Milne<T>> const& iMe):\n      nDat(inDat), ny(iny), nx(inx), mu(iMu), obs(iobs, iny, inx, inDat), sig(nDat), Pinfo(Pinfo_in)\n    {\n\n      // --- References to Me class ---//\n      int const nthreads = (int)iMe.size();\n      for(int ii=0; ii<nthreads; ++ii) Me.emplace_back(static_cast<const ml::Milne<T>*>(&iMe[ii]));\n\n      \n      // --- sigma --- //\n      Nreal = 0;\n      for(int ii=0; ii<nDat; ++ii){\n\tsig[ii] = 1/isig[ii];\n\n\tif(isig[ii] < 1.e10)\n\t  ++Nreal;\n\t\n      }\n    }\n    \n    // ------------------------------------------------------------ //\n\n    int getNthreads()const{return int(Me.size());}\n    \n    // ------------------------------------------------------------ //\n    \n    void NormalizePars(int const nPar,  T* const __restrict__ par)const\n    {\n      int const ny1 = ny;\n      int const nx1 = nx;\n      \n      for(int yy=0; yy<ny1; ++yy)\n\tfor(int xx=0; xx<nx1; ++xx)\n\t  for(int pp=0; pp<nPar; ++pp)\n\t    par[yy*nx*nPar + xx*nPar + pp] /= Pinfo[pp].scale;\n    }\n    \n    // ------------------------------------------------------------ //\n    \n    void ScalePars(int const nPar,  T* const __restrict__ par)const\n    {\n      int const ny1 = ny;\n      int const nx1 = nx;\n      \n      for(int yy=0; yy<ny1; ++yy)\n\tfor(int xx=0; xx<nx1; ++xx)\n\t  for(int pp=0; pp<nPar; ++pp)\n\t    par[yy*nx*nPar + xx*nPar + pp] *= Pinfo[pp].scale;\n    }\n\n    // ------------------------------------------------------------ //\n\n    void checkPars(int const nPar,  T* const __restrict__ par)const\n    {\n      int const ny1 = ny;\n      int const nx1 = nx;\n      \n      for(int pp=0; pp<nPar; ++pp){\n\n\tif(!Pinfo[pp].limited) continue;\n\t\n\tT const imin = Pinfo[pp].limits[0];\n\tT const imax = Pinfo[pp].limits[1];\n\t\n\tfor(int yy=0; yy<ny1; ++yy)\n\t  for(int xx=0; xx<nx1; ++xx){\n\t    T &iPar = par[yy*nx*nPar + xx*nPar + pp];\n\t    iPar = std::min<T>(std::max<T>(iPar, imin), imax);\n\t  } //xx\n      } // pp\n    }\n\n    \n    // ------------------------------------------------------------ //\n\n    void synthesize(int const nPar,  T* const __restrict__ par,  T* const __restrict__ syn,  T* const __restrict__ r)const\n    {\n      int const nthreads = Me.size(); int const npix = nx*ny;\n      int ipix = 0, tid = 0, ww= 0;\n      int const ndat = nDat;\n      T const scl = 1.0 / sqrt(T(Nreal*npix));\n      const T* const __restrict__ o = static_cast<const T* const>(&obs(0,0,0));\n\n#pragma omp parallel default(shared) firstprivate(ipix, tid, ww) num_threads(nthreads)\n\n      {\n\ttid = omp_get_thread_num();\n#pragma omp for\n\tfor(ipix = 0; ipix<npix; ++ipix){\n\t  \n\t  // --- scale parameters --- //\n\t  for(ww=0; ww<nPar; ++ww){\n\t    Pinfo[ww].Scale(par[ipix*nPar + ww]);\n\t    Pinfo[ww].Check(par[ipix*nPar + ww]);\n\t  }\n\t  \n\t  Me[tid]->synthesize(&par[ipix*nPar], &syn[nDat*ipix], mu);\n\n\t  for(ww=0; ww<ndat; ++ww)\n\t    r[ipix*ndat + ww] = (o[ipix*ndat + ww] - syn[ipix*ndat + ww]) * sig[ww] * scl;      \n\n\t  for(ww=0; ww<nPar; ++ww)\n\t    Pinfo[ww].Normalize(par[ipix*nPar + ww]);\n\t  \n\t}\n      } // parallel block\n      \n    }\n \n    \n    // ------------------------------------------------------------ //\n\n    T fx(int const nPar, T* const __restrict__ par,  T* const __restrict__ syn_in, T* const __restrict__ r)const \n    {\n\n      // --- Synthesize without derivatives --- //\n      synthesize(nPar, par, syn_in, r);\n\n      long const nEl = long(nDat)*long(nx*ny);\n      return ksum2<T,double>(nEl, r);\n    }\n    \n    \n    // ------------------------------------------------------------ //\n\n    T getChi2( T* const __restrict__ r)const\n    {\n      int const ndat = nDat;\n      int const npix = nx*ny;\n      int const nthreads = Me.size();\n\n      std::vector<double> chi2(nthreads,T(0));\n\n      // --- split the work in threads, each stores its own count --- //\n      int ipix=0, tid=0;\n#pragma omp parallel default(shared) firstprivate(ipix, tid) num_threads(nthreads)      \n      {\n\ttid = omp_get_thread_num();\n#pragma omp for\n\tfor(ipix=0; ipix<npix; ++ipix){\n\t  \n\t  chi2[tid] += ksum2<T,double>(ndat, r[ipix*ndat]);\n      \n\t} // ipix\n      }// parallel block\n\n      // --- add chi2 from all threads --- //\n      T chitot = chi2[tid];\n      \n      for(int ii=1; ii<nthreads; ++ii)\n\tchitot += chi2[ii];\n\n      return chitot;\n    }\n\n    // ------------------------------------------------------------ //\n    template<typename iType = long>\n    Eigen::Matrix<T,Eigen::Dynamic,1> getGamma(int const npar, T* const __restrict__ par)const\n    {\n      int const nthreads = Me.size();\n      iType const npix = nx*ny;\n      iType const ndat = nDat;\n      \n      // --- how many penalty functions do we need? Npixels-1 have penalties, (0,0) doesn't ---//\n\n\n      int const nPen = 2*npix*npar; //\n      T const sqr_nPen = sqrt(T(nPen));\n      Eigen::Matrix<T,Eigen::Dynamic,1> Gam(nPen); Gam.setZero();\n      Eigen::TensorMap<Eigen::Tensor<T,3,Eigen::RowMajor>> m(par, ny, nx, npar);\n      T const normAzi = 3.1415926 / Pinfo[2].scale;\n\n      // --- Scaling factors are sqrt-ed so when squared we get the right number --- //\n      \n      T* const  __restrict__ sq_alpha = new T [npar]();\n      for(int ii=0; ii<npar; ++ii) sq_alpha[ii] = sqrt(Pinfo[ii].alpha) / sqr_nPen;\n      \n      \n      int ipix=0, tid=0, xx=0, yy=0, pp=0;\n#pragma omp parallel default(shared) firstprivate(ipix, tid, xx, yy, pp) num_threads(nthreads)      \n      {\n\ttid = omp_get_thread_num();\n#pragma omp for\nfor(ipix=1; ipix<npix; ++ipix){\n\t  \n\t  yy = ipix / nx;\n\t  xx = ipix - yy*nx;\n\n\t  if((yy-1) >= 0){\n\t    for(pp=0; pp<npar; ++pp)\n\t      Gam[ipix*npar*2 + pp*2] += sq_alpha[pp] * (m(yy,xx,pp) - m(yy-1,xx,pp));\n\n\t    // --- check azimuth --- //\n\t    pp = 2;\n\t    T const azi = (m(yy,xx,pp) - m(yy-1,xx,pp));\n\t    if     (fabs(azi-normAzi) < fabs(azi)) Gam[ipix*npar*2 + pp*2] =  sq_alpha[pp]*(azi-normAzi);\n\t    else if(fabs(azi+normAzi) < fabs(azi)) Gam[ipix*npar*2 + pp*2] =  sq_alpha[pp]*(azi+normAzi);\n\t  }\n\t  if((xx-1) >= 0){\n\t    for(pp=0; pp<npar; ++pp)\n\t      Gam[ipix*npar*2 + pp*2 + 1] += sq_alpha[pp] * (m(yy,xx,pp) - m(yy,xx-1,pp));\n\t    \n\t    // --- check azimuth --- //\n\t    pp = 2;\n\t    T const azi = (m(yy,xx,pp) - m(yy,xx-1,pp));\n\t    if     (fabs(azi-normAzi) < fabs(azi)) Gam[ipix*npar*2 + pp*2 + 1] =  sq_alpha[pp]*(azi-normAzi);\n\t    else if(fabs(azi+normAzi) < fabs(azi)) Gam[ipix*npar*2 + pp*2 + 1] =  sq_alpha[pp]*(azi+normAzi);\n\t  }\n\n\t}// ipix\n      }// parallel\n\n      delete [] sq_alpha;\n      \n      return Gam;\n    }\n\n    \n    // ------------------------------------------------------------ //\n    \n    void synthesize_der_one(int const npar, T* __restrict__ par, T* __restrict__ r,\n\t\t\t    T* __restrict__ J, int const tid, int const ipix)const\n    {\n\n      T const scl = sqrt(T(Nreal)*T(nx*ny));\n      T iScl = 0;\n      int const ndat = nDat;\n\n      const T* const __restrict__ o = static_cast<const T* const>(&obs(0,0,0));\n      \n      for(int pp=0; pp<npar; ++pp){\n\tPinfo[pp].Scale(par[pp]);\n\t//Pinfo[pp].Check(par[pp]);\n      }\n\t    \n      Me[tid]->synthesize_rf(par, r, J, mu);\n      \n      \n      for(int ww=0; ww<ndat; ++ww)\n\tr[ww] = (o[ipix*ndat+ww] - r[ww]) * sig[ww] / scl;  \n      \n\t  \n      // --- scale J and compute r--- //\n      for(int pp=0; pp<npar; ++pp){\n\tiScl = Pinfo[pp].scale / scl;\n\t\n\tfor(int ww=0; ww<ndat; ++ww)\n\t  J[pp*ndat+ww] *= iScl * sig[ww];\n\t\n\tPinfo[pp].Normalize(par[pp]);\n\n      } // pp\n    \n    }\n    \n    // ------------------------------------------------------------ //\n\n    T fx_dx(int const nPar,  T* const __restrict__ par,  T* const __restrict__ syn_in,  T* const __restrict__ r,\n\t    T* const __restrict__ J)const \n    {\n      \n      synthesize_rf(nPar, par, syn_in, r, J);\n      \n      long const nEl = long(nDat)*long(nx*ny);\n      return ksum2<T,double>(nEl, r);\n    }\n    \n    // ------------------------------------------------------------ //\n\n    template<typename iType = long>\n    Eigen::SparseMatrix<T, Eigen::RowMajor, iType> get_L(int const npar,  T* const __restrict__ par)const\n    {\n\n      iType const npix = nx*ny;\n      iType const ndat = nDat;\n      iType const Nx = nx;\n      iType const Ny = ny;\n      iType const nthreads = Me.size();\n\n\n      iType const nPen = npix*2*npar;\n      T const sqr_nPen = sqrt(T(nPen));\n      std::vector<T> iAlpha(npar, T(0));\n      for(int ii=0;ii<npar; ++ii) iAlpha[ii] = sqrt(Pinfo[ii].alpha) / sqr_nPen;\n      \n      // --- get matrix dimensions --- //\n\n      int const nrows = 2*npar*npix;\n      int const ncols = npix*npar;\n\n      Eigen::SparseMatrix<T,Eigen::RowMajor, iType> L(nrows, ncols);\n\n      \n      // --- Get number of elements per row --- //\n\n      int const Elements_per_row = 2;\n      Eigen::VectorXi nElements_per_row = Eigen::VectorXi::Constant(2*npix*npar, Elements_per_row); // 1D vector of integers\n\n\n\n      // --- correct numbers for first column and first row --- //\n      \n      for(int pp=0; pp<npar; ++pp){\n\t\n\tfor(int yy = 0; yy<Ny; ++yy){\n\t  int const iPix = (yy*nx + 0);\n\t  nElements_per_row[2*iPix * npar + 2*pp+1] = 0;\n\t} // yy\n\t\n\tfor(int xx = 0; xx<Nx; ++xx){\n\t  int const iPix = (0*Nx + xx);\n\t  nElements_per_row[2*iPix * npar + 2*pp ] = 0;\n\t} // xx\n\n      }// pp\n      \n\n\n      \n      // --- reserve elements in the sparse matrix --- //\n      \n      L.reserve(nElements_per_row);\n\n\n\n      \n      // --- Fill Matrix in parallel --- //\n      \n      iType ipix=0, tid=0, xx=0, yy=0, pp=0;\n#pragma omp parallel default(shared) firstprivate(ipix, tid, xx, yy, pp) num_threads(nthreads)      \n      {\n\ttid = omp_get_thread_num();\n#pragma omp for\n\tfor(ipix=1; ipix<npix; ++ipix){\n\t  yy = ipix / nx;\n\t  xx = ipix - yy*nx;\n\t  \n\t  // --- Each thread fills all regularization derivatives for one pixel (all parameters) --- //\n\t  \n\t  if((yy-1) >= 0)\n \t    for(pp = 0; pp<npar; ++pp){\n\t      L.insert(2*npar*ipix + 2*pp    , ipix*npar + pp - npar*nx) = -iAlpha[pp]; // One pixel below\n\t      L.insert(2*npar*ipix + 2*pp    , ipix*npar + pp)           =  iAlpha[pp]; // the pixel itself.\t      \n\t    }\n\t  \n\t  if((xx-1) >= 0)\n\t    for(pp = 0; pp<npar; ++pp){\n\t      L.insert(2*npar*ipix + 2*pp+1  , ipix*npar + pp - npar)    = -iAlpha[pp]; // One pixel to the left\n\t      L.insert(2*npar*ipix + 2*pp+1  , ipix*npar + pp)           =  iAlpha[pp]; // the pixel itself.\n\t    }\n\t} //ipix\t\n      }// parallel\n\n      return L;\n    }\n\n  };\n}\n\n#endif\n", "meta": {"hexsha": "30f0af3e5157e2273ad883ef6df3dc6ef9474c37", "size": 15222, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/spatially_regularized_tools.hpp", "max_stars_repo_name": "HighwayStar/pyMilne", "max_stars_repo_head_hexsha": "630fa3715347584980f2a997f7848179bc3847e9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2020-06-16T08:37:22.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-17T23:48:54.000Z", "max_issues_repo_path": "src/spatially_regularized_tools.hpp", "max_issues_repo_name": "HighwayStar/pyMilne", "max_issues_repo_head_hexsha": "630fa3715347584980f2a997f7848179bc3847e9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/spatially_regularized_tools.hpp", "max_forks_repo_name": "HighwayStar/pyMilne", "max_forks_repo_head_hexsha": "630fa3715347584980f2a997f7848179bc3847e9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-09-25T13:27:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-28T18:57:13.000Z", "avg_line_length": 28.5590994371, "max_line_length": 142, "alphanum_fraction": 0.4867954277, "num_tokens": 4564, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.48837241291552075}}
{"text": "//\n// Created by michel on 19-08-19.\n//\n\n#include <simple-dsp/core/circular.h>\n\n#include <boost/test/unit_test.hpp>\n\nnamespace {\nusing Metric = simpledsp::MaskedIndexFor<char>;\n\nconstexpr size_t requestedSize = 13;\nconstexpr size_t properSize = 16;\nconstexpr size_t properMask = 15;\n\nMetric metric(requestedSize);\n\ntemplate <typename T>\nstatic void checkExpectedAndActual(const char *description, T expected,\n                                   T actual) {\n  if (actual != expected) {\n    std::stringstream msg;\n    msg << description << \": expected \" << expected << \" got \" << actual;\n    BOOST_FAIL(msg.str().c_str());\n  }\n}\n} // namespace\n\nBOOST_AUTO_TEST_SUITE(circularMetricTests)\n\nBOOST_AUTO_TEST_CASE(testProperSize) {\n  checkExpectedAndActual(\"Proper circular size for 13\", properSize,\n                         metric.size());\n}\n\nBOOST_AUTO_TEST_CASE(testAddNoWrap) {\n  BOOST_CHECK_MESSAGE(metric.add(7, 5) == 12,\n                      \"WrappedIndex(16)::add(7, 5) == 12\");\n}\n\nBOOST_AUTO_TEST_CASE(testLargeAddNoWrap) {\n  BOOST_CHECK_MESSAGE(metric.add(7 + properSize, 5) == 12,\n                      \"WrappedIndex(16)::add(7 + size, 5) == 12\");\n}\n\nBOOST_AUTO_TEST_CASE(testLargeAddLargeNoWrap) {\n  BOOST_CHECK_MESSAGE(metric.add(7 + properSize, 5 + properSize) == 12,\n                      \"WrappedIndex(16)::add(7 + size, 5 + size) == 12\");\n}\n\nBOOST_AUTO_TEST_CASE(testAddWrapZero) {\n  BOOST_CHECK_MESSAGE(metric.add(7, 9) == 0,\n                      \"WrappedIndex(16)::add(7, 9) == 0\");\n}\n\nBOOST_AUTO_TEST_CASE(testLargeAddWrapZero) {\n  BOOST_CHECK_MESSAGE(metric.add(7 + properSize, 9) == 0,\n                      \"WrappedIndex(16)::add(7 + size, 9) == 0\");\n}\n\nBOOST_AUTO_TEST_CASE(testLargeAddLargeWrapZero) {\n  BOOST_CHECK_MESSAGE(metric.add(7 + properSize, 9 + properSize) == 0,\n                      \"WrappedIndex(16)::add(7 + size, 9 + size) == 0\");\n}\n\nBOOST_AUTO_TEST_CASE(testAddWrapOne) {\n  BOOST_CHECK_MESSAGE(metric.add(7, 10) == 1,\n                      \"WrappedIndex(16)::add(7, 10) == 1\");\n}\n\nBOOST_AUTO_TEST_CASE(testLargeAddWrapOne) {\n  BOOST_CHECK_MESSAGE(metric.add(7 + properSize, 10) == 1,\n                      \"WrappedIndex(16)::add(7 + size, 10) == 1\");\n}\n\nBOOST_AUTO_TEST_CASE(testLargeAddLargeWrapOne) {\n  BOOST_CHECK_MESSAGE(metric.add(7 + properSize, 10 + properSize) == 1,\n                      \"WrappedIndex(16)::add(7 + size, 10) == 1\");\n}\n\nBOOST_AUTO_TEST_CASE(testAddNoWrapFromZero) {\n  BOOST_CHECK_MESSAGE(metric.add(0, 5) == 5,\n                      \"WrappedIndex(16)::add(0, 5) == 5\");\n}\n\nBOOST_AUTO_TEST_CASE(testLargeAddNoWrapFromZero) {\n  BOOST_CHECK_MESSAGE(metric.add(0 + properSize, 5) == 5,\n                      \"WrappedIndex(16)::add(size, 5) == 5\");\n}\n\nBOOST_AUTO_TEST_CASE(testLargeAddLargeNoWrapFromZero) {\n  BOOST_CHECK_MESSAGE(metric.add(0 + properSize, 5 + properSize) == 5,\n                      \"WrappedIndex(16)::add(size, 5 + size) == 5\");\n}\n\nBOOST_AUTO_TEST_CASE(testSubtractNoWrap) {\n  BOOST_CHECK_MESSAGE(metric.sub(7, 5) == 2,\n                      \"WrappedIndex(16)::subtract(7, 5) == 2\");\n}\n\nBOOST_AUTO_TEST_CASE(testLargeSubtractNoWrap) {\n  BOOST_CHECK_MESSAGE(metric.sub(7 + properSize, 5) == 2,\n                      \"WrappedIndex(16)::subtract(7 + size, 5) == 2\");\n}\n\nBOOST_AUTO_TEST_CASE(testLargeSubtractLargeNoWrap) {\n  BOOST_CHECK_MESSAGE(metric.sub(7 + properSize, 5 + properSize) == 2,\n                      \"WrappedIndex(16)::subtract(7 + size, 5 + size) == 2\");\n}\n\nBOOST_AUTO_TEST_CASE(testSubtractNoWrapZero) {\n  BOOST_CHECK_MESSAGE(metric.sub(7, 7) == 0,\n                      \"WrappedIndex(16)::subtract(7, 7) == 0\");\n}\n\nBOOST_AUTO_TEST_CASE(testLargeSubtractNoWrapZero) {\n  BOOST_CHECK_MESSAGE(metric.sub(7 + properSize, 7) == 0,\n                      \"WrappedIndex(16)::subtract(7 + size, 7) == 0\");\n}\n\nBOOST_AUTO_TEST_CASE(testLargeSubtractLargeNoWrapZero) {\n  BOOST_CHECK_MESSAGE(metric.sub(7 + properSize, 7 + properSize) == 0,\n                      \"WrappedIndex(16)::subtract(7 + size, 7 + size) == 0\");\n}\n\nBOOST_AUTO_TEST_CASE(testSubtractWrapOne) {\n  BOOST_CHECK_MESSAGE(metric.sub(7, 8) == properMask,\n                      \"WrappedIndex(16)::subtract(7, 8) == mask\");\n}\n\nBOOST_AUTO_TEST_CASE(testLargeSubtractWrapOne) {\n  BOOST_CHECK_MESSAGE(metric.sub(7 + properSize, 8) == properMask,\n                      \"WrappedIndex(16)::subtract(7 + size, 8) == mask\");\n}\n\nBOOST_AUTO_TEST_CASE(testLargeSubtractLargeWrapOne) {\n  BOOST_CHECK_MESSAGE(metric.sub(7 + properSize, 8 + properSize) == properMask,\n                      \"WrappedIndex(16)::subtract(7 + size, 8 + size) == mask\");\n}\n\nBOOST_AUTO_TEST_CASE(testSubtractWrapTwo) {\n  BOOST_CHECK_MESSAGE(metric.sub(7, 9) == properMask - 1,\n                      \"WrappedIndex(16)::subtract(7, 9) == mask - 1\");\n}\n\nBOOST_AUTO_TEST_CASE(testLargeSubtractWrapTwo) {\n  BOOST_CHECK_MESSAGE(metric.sub(7 + properSize, 9) == properMask - 1,\n                      \"WrappedIndex(16)::subtract(7 + size, 9) == mask - 1\");\n}\n\nBOOST_AUTO_TEST_CASE(testLargeSubtractLargeWrapTwo) {\n  BOOST_CHECK_MESSAGE(\n      metric.sub(7 + properSize, 9 + properSize) == properMask - 1,\n      \"WrappedIndex(16)::subtract(7 + size, 9 + size) == mask - 1\");\n}\n\nBOOST_AUTO_TEST_CASE(testSubtractNoWrapFromMask) {\n  BOOST_CHECK_MESSAGE(metric.sub(properMask, 5) == 10,\n                      \"WrappedIndex(16)::subtract(mask, 5) == 10\");\n}\n\nBOOST_AUTO_TEST_CASE(testLargeSubtractNoWrapFromMask) {\n  BOOST_CHECK_MESSAGE(metric.sub(properMask + properSize, 5) == 10,\n                      \"WrappedIndex(16)::subtract(mask + size, 5) == 10\");\n}\n\nBOOST_AUTO_TEST_CASE(testLargeSubtractLargeNoWrapFromMask) {\n  BOOST_CHECK_MESSAGE(\n      metric.sub(properMask + properSize, 5 + properSize) == 10,\n      \"WrappedIndex(16)::subtract(mask + size, 5 + size) == 10\");\n}\n\nBOOST_AUTO_TEST_CASE(testRoundtripWithSetNext) {\n  size_t reference = 0;\n  size_t actual = 0;\n  for (size_t i = 0; i <= properSize; i++) {\n    reference = (reference + 1) % properSize;\n    actual = metric.inc(actual);\n    BOOST_CHECK_EQUAL(reference, actual);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(testRoundtripWithNext) {\n  size_t reference = 0;\n  size_t actual = 0;\n  for (size_t i = 0; i <= properSize; i++) {\n    reference = (reference + 1) % properSize;\n    actual = metric.unsafe_inc(actual);\n    BOOST_CHECK_EQUAL(reference, actual);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(testRoundtripWithSetPrevious) {\n  size_t reference = 0;\n  size_t actual = 0;\n  for (size_t i = 0; i <= properSize; i++) {\n    reference = (reference > 0) ? reference - 1 : properMask;\n    actual = metric.dec(actual);\n    BOOST_CHECK_EQUAL(reference, actual);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(testRoundtripWithPrevious) {\n  size_t reference = 0;\n  size_t actual = 0;\n  for (size_t i = 0; i <= properSize; i++) {\n    reference = (reference > 0) ? reference - 1 : properMask;\n    actual = metric.unsafe_dec(actual);\n    BOOST_CHECK_EQUAL(reference, actual);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(testMetricSetSizeOneSmaller) {\n  Metric m(requestedSize);\n  auto oldSize = m.size();\n  m.set_element_count(properSize - 1);\n  BOOST_CHECK_MESSAGE(m.size() == oldSize,\n                      \"Setting size one below current size yields same size\");\n}\n\nBOOST_AUTO_TEST_CASE(testMetricSetSizeSame) {\n  Metric m(requestedSize);\n  auto oldSize = m.size();\n  m.set_element_count(properSize);\n  BOOST_CHECK_MESSAGE(\n      m.size() == oldSize,\n      \"Setting size to same value should not change anything\");\n}\n\nBOOST_AUTO_TEST_CASE(testMetricSetSizeOneBigger) {\n  Metric m(requestedSize);\n  auto oldSize = m.size();\n  m.set_element_count(properSize + 1);\n  BOOST_CHECK_MESSAGE(m.size() == 2 * oldSize,\n                      \"Setting size one above yields twice as big size\");\n}\n\nBOOST_AUTO_TEST_CASE(testMetricSetSizeHalf) {\n  Metric m(requestedSize);\n  auto oldSize = m.size();\n  m.set_element_count(properSize / 2);\n  BOOST_CHECK_MESSAGE(m.size() == oldSize / 2,\n                      \"Setting size to half, yields half size\");\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "d96f086f35b2f1796c2a9436f72fab283c65d90d", "size": 7957, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/circular-tests.cc", "max_stars_repo_name": "emmef/simple-dsp", "max_stars_repo_head_hexsha": "b7275149705ebc164d1553312a9477e45ad0d7f6", "max_stars_repo_licenses": ["Apache-2.0"], "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/circular-tests.cc", "max_issues_repo_name": "emmef/simple-dsp", "max_issues_repo_head_hexsha": "b7275149705ebc164d1553312a9477e45ad0d7f6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-08-20T22:49:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-20T22:49:16.000Z", "max_forks_repo_path": "test/circular-tests.cc", "max_forks_repo_name": "emmef/simple-dsp", "max_forks_repo_head_hexsha": "b7275149705ebc164d1553312a9477e45ad0d7f6", "max_forks_repo_licenses": ["Apache-2.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.2145748988, "max_line_length": 80, "alphanum_fraction": 0.6518788488, "num_tokens": 2189, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.6825737473266735, "lm_q1q2_score": 0.4883296377293476}}
{"text": "#include <gtest/gtest.h>\n#include <string>\n#include <stdexcept>\n#include <Eigen/Dense>\n#include <cmath>\n\n// testing following API\n#include \"estimation/UnscentedTransform.h\"\n#include \"estimation/ITransformer.h\"\n\nusing namespace std;\nusing namespace estimation;\n\nnamespace UnscentedTransformTest \n{\n  class TestTransformer : public ITransformer\n  {\n  private:\n    int choice;\n\n    VectorXd f1(const VectorXd& x) { return x; }\n    VectorXd f2(const VectorXd& x) { return 2*x; }\n    VectorXd f3(const VectorXd& x) { \n      VectorXd y = VectorXd::Zero(2); \n      y[0] = x[0];\n      y[1] = x[1];\n      return y;\n    }\n    VectorXd f4(const VectorXd& x) {\t// nonlinear example\n      VectorXd y(x.size());\n      for (int i = 0; i < x.size(); i++)\n\ty[i] = sin(x[i]);\n      return y; \n    }\n\n  public:\n    TestTransformer(int choice) { this->choice = choice; }\n    ~TestTransformer() { }\n\n    VectorXd transform(const VectorXd& x)\n    {\n      switch(choice) {\n      case 1: return f1(x);\n      case 2: return f2(x);\n      case 3: return f3(x);\n      case 4: return f4(x);\n      default: return f1(x);\n      }\n    }\n  };\n\n  // -----------------------------------------\n  // tests\n  // -----------------------------------------\n  TEST(UnscentedTransformTest, initialization)\n  {\n    VectorXd x(3);\n    x << 1,2,3;\n    MatrixXd Px(3,3);\n    Px << 1,0,0 , 0,1,0 , 0,0,1;\n    TestTransformer tt1(1);\n\n    EXPECT_NO_THROW(UnscentedTransform ut_t1(x, Px, &tt1));\n    \n    // missing transformer\n    EXPECT_THROW(UnscentedTransform ut_t1(x, Px, 0), runtime_error);\n\n    // invalid sizes\n    VectorXd x_f(4);\n    x_f << 1,2,3,4;\n    MatrixXd Px_f(2,3);\n    Px_f << 1,0,0 , 0,1,0;\n\n    EXPECT_THROW(UnscentedTransform ut1(x_f, Px, &tt1), length_error);\n    EXPECT_THROW(UnscentedTransform ut2(x, Px_f, &tt1), length_error);\n    EXPECT_THROW(UnscentedTransform ut3(x_f, Px_f, &tt1), length_error);\n\n    // check sizes of output\n    UnscentedTransform ut_t1(x, Px, &tt1);\n    EXPECT_EQ(ut_t1.mean().size(), 3);\n    EXPECT_EQ(ut_t1.covariance().rows(), 3);\n    EXPECT_EQ(ut_t1.covariance().cols(), 3);\n    EXPECT_EQ(ut_t1.crossCovarianceXY().rows(), 3);\n    EXPECT_EQ(ut_t1.crossCovarianceXY().cols(), 3);\n\n    TestTransformer tt3(3);\n    UnscentedTransform ut_t3(x, Px, &tt3);\n    EXPECT_EQ(ut_t3.mean().size(), 2);\n    EXPECT_EQ(ut_t3.covariance().rows(), 2);\n    EXPECT_EQ(ut_t3.covariance().cols(), 2);\n    EXPECT_EQ(ut_t3.crossCovarianceXY().rows(), 3);\n    EXPECT_EQ(ut_t3.crossCovarianceXY().cols(), 2);\t\n  }\n\n  TEST(UnscentedTransformTest, functionality)\n  {\n    VectorXd x(3);\n    x << 1,-2,3;\n    MatrixXd Px(3,3);\n    Px << 1,0,0 , 0,1,0 , 0,0,1;\n    TestTransformer tt1(1);\n    TestTransformer tt2(2);\n    TestTransformer tt3(3);\n\n    // &tt1: y = x, so mean and covariance should remain the same\n\n    UnscentedTransform ut(x, Px, &tt1);\n    VectorXd y;\n    MatrixXd Py, Pxy;\n    \n    EXPECT_NO_THROW(ut.compute());\n    EXPECT_NO_THROW(y = ut.mean());\n    EXPECT_NO_THROW(Py = ut.covariance());\n    EXPECT_NO_THROW(Pxy = ut.crossCovarianceXY());\n\n    ASSERT_EQ(x.size(), y.size());\n\n    for (int i = 0; i < y.size(); i++)\n      EXPECT_NEAR(x[i], y[i], 0.000001);\n\n    ASSERT_EQ(x.rows(), y.rows());\n    ASSERT_EQ(x.cols(), y.cols());\n\n    for (int r = 0; r < Py.rows(); r++)\n      for (int c = 0; c < Py.cols(); c++) {\n\tEXPECT_NEAR(Px(r,c), Py(r,c), 0.000001);\n\tEXPECT_NEAR(Px(r,c), Pxy(r,c), 0.000001);\n      }\n\n    // &tt2: y = 2x, so mean doubled, covariance*4, cross-covariance*2\n\n    UnscentedTransform ut2(x, Px, &tt2);\n    VectorXd y2;\n    MatrixXd Py2, Pxy2;\n    EXPECT_NO_THROW(ut2.compute());\n    EXPECT_NO_THROW(y2 = ut2.mean());\n    EXPECT_NO_THROW(Py2 = ut2.covariance());\n    EXPECT_NO_THROW(Pxy2 = ut2.crossCovarianceXY());\n\n    ASSERT_EQ(x.size(), y.size());\n\n    for (int i = 0; i < y2.size(); i++)\n      EXPECT_NEAR(2*x[i], y2[i], 0.000001);\n\n    ASSERT_EQ(x.rows(), y.rows());\n    ASSERT_EQ(x.cols(), y.cols());\n\n    for (int r = 0; r < Py2.rows(); r++)\n      for (int c = 0; c < Py2.cols(); c++) {\n\tEXPECT_NEAR(4*Px(r,c), Py2(r,c), 0.000001);\n\tEXPECT_NEAR(2*Px(r,c), Pxy2(r,c), 0.000001);\n      }\n\n    // &tt3: y = x[0,1], so mean/cov/.. remains the same but cut off\n\n    UnscentedTransform ut3(x, Px, &tt3);\n    VectorXd y3;\n    MatrixXd Py3, Pxy3;\n    EXPECT_NO_THROW(ut3.compute());\n    EXPECT_NO_THROW(y3 = ut3.mean());\n    EXPECT_NO_THROW(Py3 = ut3.covariance());\n    EXPECT_NO_THROW(Pxy3 = ut3.crossCovarianceXY());\n\n    EXPECT_EQ(y3.size(),2);\n    for (int i = 0; i < y3.size(); i++)\n      EXPECT_NEAR(x[i], y3[i], 0.000001);\n\n    for (int r = 0; r < Py3.rows(); r++)\n      for (int c = 0; c < Py3.cols(); c++)\n\tEXPECT_NEAR(Px(r,c), Py3(r,c), 0.000001);\n\n    EXPECT_EQ(Pxy3.rows(), 3);\n    EXPECT_EQ(Pxy3.cols(), 2);\n    for (int r = 0; r < Pxy3.rows(); r++)\n      for (int c = 0; c < Pxy3.cols(); c++)\n\tEXPECT_NEAR(Px(r,c), Pxy3(r,c), 0.000001);\n  }\n\n  TEST(UnscentedTransformTest, functionalityNonlinear)\n  {\n    VectorXd x(4);\n    x << 10*M_PI/180, 30*M_PI/180, 60*M_PI/180, 90*M_PI/180;\t// 30\u00b0, 0\u00b0, 90\u00b0\n    MatrixXd Px(4,4);\n    Px << 1,0,0,0 , 0,0.1,0,0 , 0,0,0.01,0 , 0,0,0,0.001;\n\n    TestTransformer tt4(4);\n\n    // tt4: y[i] = sin(x[i])\n\n    UnscentedTransform ut(x, Px, &tt4);\n    VectorXd y;\n    MatrixXd Py, Pxy;\n    \n    EXPECT_NO_THROW(ut.compute());\n    EXPECT_NO_THROW(y = ut.mean());\n    EXPECT_NO_THROW(Py = ut.covariance());\n    EXPECT_NO_THROW(Pxy = ut.crossCovarianceXY());\n\n    ASSERT_EQ(x.size(), y.size());\n\n    for (int i = 0; i < y.size(); i++) {\n      EXPECT_NEAR(sin(x[i]), y[i], Px(i,i));\n    }\n\n/*\n    // TODO\n\n    ASSERT_EQ(x.rows(), y.rows());\n    ASSERT_EQ(x.cols(), y.cols());\n\n    for (int r = 0; r < Py.rows(); r++)\n      for (int c = 0; c < Py.cols(); c++) {\n\tEXPECT_NEAR(Px(r,c), Py(r,c), 0.000001);\n\tEXPECT_NEAR(Px(r,c), Pxy(r,c), 0.000001);\n      }\n*/\n  }\n\n  TEST(UnscentedTransformTest, examples)\n  {\n    int n;\n    VectorXd x, y;\n    MatrixXd Px, Py;\n\n    // example 1 -----------------------\n    n = 1;\n    x = VectorXd::Zero(n);\n    Px = MatrixXd::Identity(n,n);\n\n    TestTransformer tt1(1);\n    UnscentedTransform ut_ex1_s(x, Px, &tt1);\n    ut_ex1_s.compute();\n    y = ut_ex1_s.mean();\n    Py = ut_ex1_s.covariance();\n    /*\n    cout << \"example 1 (predict)\" << endl;\n    cout << \"y: \" << endl << y << endl;\n    cout << \"Py: \" << endl << Py << endl; \n    */\n\n    MatrixXd Q = 0.1 * MatrixXd::Identity(n,n);\n    UnscentedTransform ut_ex1_m(x, Px+Q, &tt1);\n    ut_ex1_m.compute();\n    /*\n    cout << \"example 1 (correct)\" << endl;\n    cout << \"y: \" << endl << ut_ex1_m.mean() << endl;\n    cout << \"Py: \" << endl << ut_ex1_m.covariance() << endl; \n    cout << \"Pxy: \" << endl << ut_ex1_m.crossCovarianceXY() << endl;\n    */\n  }\n}\n", "meta": {"hexsha": "702a322a08e8721650617ec1057df3f823f70a96", "size": 6688, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sf_estimation/tests/utest_UnscentedTransform.cpp", "max_stars_repo_name": "tuw-cpsg/sf-pkg", "max_stars_repo_head_hexsha": "267d2ec4b886dee70d53a23b695acfa7f7edbeb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 30.0, "max_stars_repo_stars_event_min_datetime": "2015-09-30T09:47:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-12T16:01:11.000Z", "max_issues_repo_path": "sf_estimation/tests/utest_UnscentedTransform.cpp", "max_issues_repo_name": "ros-agriculture/sf-pkg", "max_issues_repo_head_hexsha": "267d2ec4b886dee70d53a23b695acfa7f7edbeb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-05-13T04:59:08.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-13T14:39:24.000Z", "max_forks_repo_path": "sf_estimation/tests/utest_UnscentedTransform.cpp", "max_forks_repo_name": "tuw-cpsg/sf-pkg", "max_forks_repo_head_hexsha": "267d2ec4b886dee70d53a23b695acfa7f7edbeb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2016-04-17T21:13:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T17:00:28.000Z", "avg_line_length": 26.5396825397, "max_line_length": 76, "alphanum_fraction": 0.569527512, "num_tokens": 2256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834732, "lm_q2_score": 0.6825737473266735, "lm_q1q2_score": 0.48832963772934757}}
{"text": "#pragma once\n/* This code is a stripped down version of 'google/spherical-harmonics' on\n * github to focus on spherical harmonics rotations using Eigen. This part\n * of the code is release using the Apache license V2.0 (see [here][license])\n *\n * Modifications:\n *  + I added a new Apply interface to the Rotation class that takes Eigen\n *    vectors as input and outputs to perform efficient Matrix products.\n *    See Rotation::Apply(const Eigen::VectorXf&, Eigen::VectorXf&) const.\n *  + I changed all Eigen type to be 32b float instead of 64b.\n *\n * [license]: https://github.com/google/spherical-harmonics/blob/master/LICENSE\n */\n\n// Include Eigen\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n// Include STL\n#include <vector>\n#include <memory>\n\ntemplate <class T>\nusing VectorX = Eigen::Matrix<T, Eigen::Dynamic, 1>;\n\n// Get the total number of coefficients for a function represented by\n// all spherical harmonic basis of degree <= @order (it is a point of\n// confusion that the order of an SH refers to its degree and not the order).\nconstexpr int GetCoefficientCount(int order) {\n  return (order + 1) * (order + 1);\n}\n\n// Get the one dimensional index associated with a particular degree @l\n// and order @m. This is the index that can be used to access the Coeffs\n// returned by SHSolver.\nconstexpr int GetIndex(int l, int m) {\n  return l * (l + 1) + m;\n}\n\n// Usage: CHECK(bool, string message);\n// Note that it must end a semi-colon, making it look like a\n// valid C++ statement (hence the awkward do() while(false)).\n#ifndef NDEBUG\n# define CHECK(condition, message) \\\n  do { \\\n    if (!(condition)) { \\\n      std::cerr << \"Check failed (\" #condition \") in \" << __FILE__ \\\n        << \":\" << __LINE__ << \", message: \" << message << std::endl; \\\n      std::exit(EXIT_FAILURE); \\\n    } \\\n  } while(false)\n#else\n# define ASSERT(condition, message) do {} while(false)\n#endif\n\n// Return true if the first value is within epsilon of the second value.\nbool NearByMargin(double actual, double expected) {\n  double diff = actual - expected;\n  if (diff < 0.0) {\n    diff = -diff;\n  }\n  // 5 bits of error in mantissa (source of '32 *')\n  return diff < 32 * std::numeric_limits<double>::epsilon();\n}\n\n// ---- The following functions are used to implement SH rotation computations\n//      based on the recursive approach described in [1, 4]. The names of the\n//      functions correspond with the notation used in [1, 4].\n\n// See http://en.wikipedia.org/wiki/Kronecker_delta\ndouble KroneckerDelta(int i, int j) {\n  if (i == j) {\n    return 1.0;\n  } else {\n    return 0.0;\n  }\n}\n\n// [4] uses an odd convention of referring to the rows and columns using\n// centered indices, so the middle row and column are (0, 0) and the upper\n// left would have negative coordinates.\n//\n// This is a convenience function to allow us to access an Eigen::MatrixXf\n// in the same manner, assuming r is a (2l+1)x(2l+1) matrix.\ndouble GetCenteredElement(const Eigen::MatrixXf& r, int i, int j) {\n  // The shift to go from [-l, l] to [0, 2l] is (rows - 1) / 2 = l,\n  // (since the matrix is assumed to be square, rows == cols).\n  int offset = (r.rows() - 1) / 2;\n  return r(i + offset, j + offset);\n}\n\n// P is a helper function defined in [4] that is used by the functions U, V, W.\n// This should not be called on its own, as U, V, and W (and their coefficients)\n// select the appropriate matrix elements to access (arguments @a and @b).\ndouble P(int i, int a, int b, int l, const std::vector<Eigen::MatrixXf>& r) {\n  if (b == l) {\n    return GetCenteredElement(r[1], i, 1) *\n        GetCenteredElement(r[l - 1], a, l - 1) -\n        GetCenteredElement(r[1], i, -1) *\n        GetCenteredElement(r[l - 1], a, -l + 1);\n  } else if (b == -l) {\n    return GetCenteredElement(r[1], i, 1) *\n        GetCenteredElement(r[l - 1], a, -l + 1) +\n        GetCenteredElement(r[1], i, -1) *\n        GetCenteredElement(r[l - 1], a, l - 1);\n  } else {\n    return GetCenteredElement(r[1], i, 0) * GetCenteredElement(r[l - 1], a, b);\n  }\n}\n\n// The functions U, V, and W should only be called if the correspondingly\n// named coefficient u, v, w from the function ComputeUVWCoeff() is non-zero.\n// When the coefficient is 0, these would attempt to access matrix elements that\n// are out of bounds. The list of rotations, @r, must have the @l - 1\n// previously completed band rotations. These functions are valid for l >= 2.\n\ndouble U(int m, int n, int l, const std::vector<Eigen::MatrixXf>& r) {\n  // Although [1, 4] split U into three cases for m == 0, m < 0, m > 0\n  // the actual values are the same for all three cases\n  return P(0, m, n, l, r);\n}\n\ndouble V(int m, int n, int l, const std::vector<Eigen::MatrixXf>& r) {\n  if (m == 0) {\n    return P(1, 1, n, l, r) + P(-1, -1, n, l, r);\n  } else if (m > 0) {\n    return P(1, m - 1, n, l, r) * sqrt(1 + KroneckerDelta(m, 1)) -\n        P(-1, -m + 1, n, l, r) * (1 - KroneckerDelta(m, 1));\n  } else {\n    // Note there is apparent errata in [1,4,4b] dealing with this particular\n    // case. [4b] writes it should be P*(1-d)+P*(1-d)^0.5\n    // [1] writes it as P*(1+d)+P*(1-d)^0.5, but going through the math by hand,\n    // you must have it as P*(1-d)+P*(1+d)^0.5 to form a 2^.5 term, which\n    // parallels the case where m > 0.\n    return P(1, m + 1, n, l, r) * (1 - KroneckerDelta(m, -1)) +\n        P(-1, -m - 1, n, l, r) * sqrt(1 + KroneckerDelta(m, -1));\n  }\n}\n\ndouble W(int m, int n, int l, const std::vector<Eigen::MatrixXf>& r) {\n  if (m == 0) {\n    // whenever this happens, w is also 0 so W can be anything\n    return 0.0;\n  } else if (m > 0) {\n    return P(1, m + 1, n, l, r) + P(-1, -m - 1, n, l, r);\n  } else {\n    return P(1, m - 1, n, l, r) - P(-1, -m + 1, n, l, r);\n  }\n}\n\n// Calculate the coefficients applied to the U, V, and W functions. Because\n// their equations share many common terms they are computed simultaneously.\nvoid ComputeUVWCoeff(int m, int n, int l, double* u, double* v, double* w) {\n  double d = KroneckerDelta(m, 0);\n  double denom = (abs(n) == l ? 2.0 * l * (2.0 * l - 1) : (l + n) * (l - n));\n\n  *u = sqrt((l + m) * (l - m) / denom);\n  *v = 0.5 * sqrt((1 + d) * (l + abs(m) - 1.0) * (l + abs(m)) / denom)\n      * (1 - 2 * d);\n  *w = -0.5 * sqrt((l - abs(m) - 1) * (l - abs(m)) / denom) * (1 - d);\n}\n\n// Calculate the (2l+1)x(2l+1) rotation matrix for the band @l.\n// This uses the matrices computed for band 1 and band l-1 to compute the\n// matrix for band l. @rotations must contain the previously computed l-1\n// rotation matrices, and the new matrix for band l will be appended to it.\n//\n// This implementation comes from p. 5 (6346), Table 1 and 2 in [4] taking\n// into account the corrections from [4b].\nvoid ComputeBandRotation(int l, std::vector<Eigen::MatrixXf>* rotations) {\n  // The band's rotation matrix has rows and columns equal to the number of\n  // coefficients within that band (-l <= m <= l implies 2l + 1 coefficients).\n  Eigen::MatrixXf rotation(2 * l + 1, 2 * l + 1);\n  for (int m = -l; m <= l; m++) {\n    for (int n = -l; n <= l; n++) {\n      double u, v, w;\n      ComputeUVWCoeff(m, n, l, &u, &v, &w);\n\n      // The functions U, V, W are only safe to call if the coefficients\n      // u, v, w are not zero\n      if (!NearByMargin(u, 0.0))\n          u *= U(m, n, l, *rotations);\n      if (!NearByMargin(v, 0.0))\n          v *= V(m, n, l, *rotations);\n      if (!NearByMargin(w, 0.0))\n          w *= W(m, n, l, *rotations);\n\n      rotation(m + l, n + l) = (u + v + w);\n    }\n  }\n\n  rotations->push_back(rotation);\n}\n\nclass Rotation {\n public:\n/*\n  // Create a new Rotation that can applies @rotation to sets of coefficients\n  // for the given @order. @order must be at least 0.\n  static std::unique_ptr<Rotation> Create(int order,\n                                          const Eigen::Quaternionf& rotation);\n\n  // Create a new Rotation that applies the same rotation as @rotation. This\n  // can be used to efficiently calculate the matrices for the same 3x3\n  // transform when a new order is necessary.\n  static std::unique_ptr<Rotation> Create(int order, const Rotation& rotation);\n*/\n  // Transform the SH basis coefficients in @coeff by this rotation and store\n  // them into @result. These may be the same vector. The @result vector will\n  // be resized if necessary, but @coeffs must have its size equal to\n  // GetCoefficientCount(order()).\n  //\n  // This rotation transformation produces a set of coefficients that are equal\n  // to the coefficients found by projecting the original function rotated by\n  // the same rotation matrix.\n  //\n  // There are explicit instantiations for double, float, and Array3f.\n  template <typename T>\n  void Apply(const std::vector<T>& coeffs,  std::vector<T>* result) const;\n  void Apply(const Eigen::MatrixXf& coeffs, Eigen::MatrixXf& result) const;\n  void Apply(const Eigen::VectorXf& coeffs, Eigen::VectorXf& result) const;\n\n  // The order (0-based) that the rotation was constructed with. It can only\n  // transform coefficient vectors that were fit using the same order.\n  int order() const;\n\n  // Return the rotation that is effectively applied to the inputs of the\n  // original function.\n  Eigen::Quaternionf rotation() const;\n\n  // Return the (2l+1)x(2l+1) matrix for transforming the coefficients within\n  // band @l by the rotation. @l must be at least 0 and less than or equal to\n  // the order this rotation was initially constructed with.\n  const Eigen::MatrixXf& band_rotation(int l) const;\n\n  Rotation(int order, const Eigen::Quaternionf& rotation);\n\n private:\n  const int order_;\n  const Eigen::Quaternionf rotation_;\n\n  std::vector<Eigen::MatrixXf> band_rotations_;\n};\n\n\nRotation::Rotation(int order, const Eigen::Quaternionf& rotation)\n    : order_(order), rotation_(rotation) {\n  band_rotations_.reserve(GetCoefficientCount(order));\n\n  // Order 0 (first band) is simply the 1x1 identity since the SH basis\n  // function is a simple sphere.\n  Eigen::MatrixXf r(1, 1);\n  r(0, 0) = 1.0;\n  band_rotations_.push_back(r);\n\n  r.resize(3, 3);\n  // The second band's transformation is simply a permutation of the\n  // rotation matrix's elements, provided in Appendix 1 of [1], updated to\n  // include the Condon-Shortely phase. The recursive method in\n  // ComputeBandRotation preserves the proper phases as high bands are computed.\n  Eigen::Matrix3f rotation_mat = rotation.toRotationMatrix();\n  r(0, 0) = rotation_mat(1, 1);\n  r(0, 1) = -rotation_mat(1, 2);\n  r(0, 2) = rotation_mat(1, 0);\n  r(1, 0) = -rotation_mat(2, 1);\n  r(1, 1) = rotation_mat(2, 2);\n  r(1, 2) = -rotation_mat(2, 0);\n  r(2, 0) = rotation_mat(0, 1);\n  r(2, 1) = -rotation_mat(0, 2);\n  r(2, 2) = rotation_mat(0, 0);\n  band_rotations_.push_back(r);\n\n  // Recursively build the remaining band rotations, using the equations\n  // provided in [4, 4b].\n  for (int l = 2; l <= order; l++) {\n    ComputeBandRotation(l, &band_rotations_);\n  }\n}\n\n/*\nstd::unique_ptr<Rotation> Rotation::Create(\n    int order, const Eigen::Quaternionf& rotation) {\n#ifndef NDEBUG\n  CHECK(order >= 0, \"Order must be at least 0.\");\n  CHECK(NearByMargin(rotation.squaredNorm(), 1.0),\n        \"Rotation must be normalized.\");\n#endif\n\n  std::unique_ptr<Rotation> sh_rot(new Rotation(order, rotation));\n\n  // Order 0 (first band) is simply the 1x1 identity since the SH basis\n  // function is a simple sphere.\n  Eigen::MatrixXf r(1, 1);\n  r(0, 0) = 1.0;\n  sh_rot->band_rotations_.push_back(r);\n\n  r.resize(3, 3);\n  // The second band's transformation is simply a permutation of the\n  // rotation matrix's elements, provided in Appendix 1 of [1], updated to\n  // include the Condon-Shortely phase. The recursive method in\n  // ComputeBandRotation preserves the proper phases as high bands are computed.\n  Eigen::Matrix3f rotation_mat = rotation.toRotationMatrix();\n  r(0, 0) = rotation_mat(1, 1);\n  r(0, 1) = -rotation_mat(1, 2);\n  r(0, 2) = rotation_mat(1, 0);\n  r(1, 0) = -rotation_mat(2, 1);\n  r(1, 1) = rotation_mat(2, 2);\n  r(1, 2) = -rotation_mat(2, 0);\n  r(2, 0) = rotation_mat(0, 1);\n  r(2, 1) = -rotation_mat(0, 2);\n  r(2, 2) = rotation_mat(0, 0);\n  sh_rot->band_rotations_.push_back(r);\n\n  // Recursively build the remaining band rotations, using the equations\n  // provided in [4, 4b].\n  for (int l = 2; l <= order; l++) {\n    ComputeBandRotation(l, &(sh_rot->band_rotations_));\n  }\n\n  return sh_rot;\n}\n\nstd::unique_ptr<Rotation> Rotation::Create(int order,\n                                           const Rotation& rotation) {\n#ifndef NDEBUG\n  CHECK(order >= 0, \"Order must be at least 0.\");\n#endif\n\n  std::unique_ptr<Rotation> sh_rot(new Rotation(order, rotation.rotation_));\n\n  // Copy up to min(order, rotation.order_) band rotations into the new\n  // SHRotation. For shared orders, they are the same. If the new order is\n  // higher than already calculated then the remainder will be computed next.\n  for (int l = 0; l <= std::min(order, rotation.order_); l++) {\n    sh_rot->band_rotations_.push_back(rotation.band_rotations_[l]);\n  }\n\n  // Calculate remaining bands (automatically skipped if there are no more).\n  for (int l = rotation.order_ + 1; l <= order; l++) {\n    ComputeBandRotation(l, &(sh_rot->band_rotations_));\n  }\n\n  return sh_rot;\n}\n*/\n\nint Rotation::order() const { return order_; }\n\nEigen::Quaternionf Rotation::rotation() const { return rotation_; }\n\nconst Eigen::MatrixXf& Rotation::band_rotation(int l) const {\n  return band_rotations_[l];\n}\n\ntemplate <typename T>\nvoid Rotation::Apply(const std::vector<T>& coeff,\n                     std::vector<T>* result) const {\n#ifndef NDEBUG\n  CHECK(coeff.size() == GetCoefficientCount(order_),\n        \"Incorrect number of coefficients provided.\");\n#endif\n\n  // Resize to the required number of coefficients.\n  // If result is already the same size as coeff, there's no need to zero out\n  // its values since each index will be written explicitly later.\n  if (result->size() != coeff.size()) {\n    result->assign(coeff.size(), T());\n  }\n\n  // Because of orthogonality, the coefficients outside of each band do not\n  // interact with one another. By separating them into band-specific matrices,\n  // we take advantage of that sparsity.\n\n  for (int l = 0; l <= order_; l++) {\n    VectorX<T> band_coeff(2 * l + 1);\n\n    // Fill band_coeff from the subset of @coeff that's relevant.\n    for (int m = -l; m <= l; m++) {\n      // Offset by l to get the appropiate vector component (0-based instead\n      // of starting at -l).\n      band_coeff(m + l) = coeff[GetIndex(l, m)];\n    }\n\n    band_coeff = band_rotations_[l].cast<T>() * band_coeff;\n\n    // Copy rotated coefficients back into the appropriate subset into @result.\n    for (int m = -l; m <= l; m++) {\n      (*result)[GetIndex(l, m)] = band_coeff(m + l);\n    }\n  }\n}\n\nvoid Rotation::Apply(const Eigen::MatrixXf& coeffs,\n                     Eigen::MatrixXf& result) const {\n   const int rows = coeffs.cols();\n   for(int l=0; l<=order_; ++l) {\n      const int i = l*l;\n      const int n = 2*l+1;\n      result.block(i, 0, n, rows) = band_rotations_[l] * coeffs.block(i, 0, n, rows);\n   }\n}\n\nvoid Rotation::Apply(const Eigen::VectorXf& coeffs,\n                     Eigen::VectorXf& result) const {\n   for(int l=0; l<=order_; ++l) {\n      const int i = l*l;\n      const int n = 2*l+1;\n      result.segment(i, n) = band_rotations_[l] * coeffs.segment(i, n);\n   }\n}\n", "meta": {"hexsha": "fff7e9c210b1c32456f13232a0fee81dbd95b387", "size": 15252, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/SHRotation.hpp", "max_stars_repo_name": "belcour/IntegralSH", "max_stars_repo_head_hexsha": "092bed8dc974f0f4c467f54a33d3e3e8968264ae", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 48.0, "max_stars_repo_stars_event_min_datetime": "2018-02-27T07:07:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T04:40:06.000Z", "max_issues_repo_path": "include/SHRotation.hpp", "max_issues_repo_name": "belcour/IntegralSH", "max_issues_repo_head_hexsha": "092bed8dc974f0f4c467f54a33d3e3e8968264ae", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/SHRotation.hpp", "max_forks_repo_name": "belcour/IntegralSH", "max_forks_repo_head_hexsha": "092bed8dc974f0f4c467f54a33d3e3e8968264ae", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2018-05-08T09:28:28.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-01T03:40:39.000Z", "avg_line_length": 37.1094890511, "max_line_length": 85, "alphanum_fraction": 0.6450957252, "num_tokens": 4544, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.7154240079185319, "lm_q1q2_score": 0.4883296367731845}}
{"text": "#include <cassert>\n#include <iostream>\n#include <boost/timer.hpp>\n\ntemplate <typename T>\nclass vector \n{\n    void check_size(int that_size) const { assert(my_size == that_size); }\n    void check_index(int i) const { assert(i >= 0 && i < my_size); }\n  public:\n    explicit vector(int size)\n      : my_size(size), data( new T[my_size] )\n    {}\n\n    vector()\n      : my_size(0), data(0)\n    {}\n\n    vector( const vector& that )\n      : my_size(that.my_size), data( new T[my_size] )\n    {\n\tfor (int i= 0; i < my_size; ++i)\n\t    data[i]= that.data[i];\n    }\n\n    ~vector() { if (data) delete [] data ; }\n\n    vector& operator=( const vector& that ) \n    {\n\tcheck_size(that.my_size);\n\tfor (int i= 0; i < my_size; ++i)\n\t    data[i]= that.data[i];\n    }\n\n    int size() const { return my_size ; }\n\n    const T& operator[]( int i ) const \n    {\n\tcheck_index(i);\n\treturn data[i];\n    }\n\t\t     \n    T& operator[]( int i ) \n    {\n\tcheck_index(i);\n\treturn data[i] ;\n    }\n\n  private:\n    int   my_size ;\n    T*    data ;\n};\n\n\ntemplate <typename T>\nstd::ostream& operator<<(std::ostream& os, const vector<T>& v)\n{\n  os << '[';\n  for (int i= 0; i < v.size(); ++i) os << v[i] << ',';\n  os << ']';\n  return os ;\n}\n \n\ntemplate <unsigned Offset, unsigned Max>\nstruct my_axpy_ftor\n{\n    template <typename U, typename V, typename W>\n    void operator()(U& u, const V& v, const W& w, unsigned i)\n    {\n\tu[i+Offset]= 3.0f * v[i+Offset] + w[i+Offset];\n\tmy_axpy_ftor<Offset+1, Max>()(u, v, w, i);\n    }\n};\n\ntemplate <unsigned Max>\nstruct my_axpy_ftor<Max, Max> \n{\n    template <typename U, typename V, typename W>\n    void operator()(U& u, const V& v, const W& w, unsigned i) {}\n};\n\ntemplate <unsigned BSize, typename U, typename V, typename W>\nvoid my_axpy(U& u, const V& v, const W& w)\n{\n    assert(u.size() == v.size() && v.size() == w.size());\n    unsigned s= u.size(), sb= s / BSize * BSize;\n   \n    for (unsigned i= 0; i < sb; i+= BSize)\n\tmy_axpy_ftor<0, BSize>()(u, v, w, i);\n\n    for (unsigned i= sb; i < s; i++) \n\tu[i]= 3.0f * v[i] + w[i];\n}\n\n\n\nint main(int argc, char** argv)  \n{\n    /* const */ unsigned s= 1000;\n    // if (argc > 1) s= atoi(argv[1]);\n    vector<float> u(s), v(s), w(s);\n\n    for (unsigned i= 0; i < s; i++) { \n\tv[i]= float(i);\n\tw[i]= float(2*i + 15);\n    }\n    \n    for (unsigned j= 0; j < 3; j++) \n\tfor (unsigned i= 0; i < s; i++) \n\t    u[i]= 3.0f * v[i] + w[i]; \n\n    const unsigned rep= 2000000; // 1000000; \n\n    boost::timer native; \n    // asm ( \"# start here native\" );\n    for (unsigned j= 0; j < rep; j++)\n\tfor (unsigned i= 0; i < s; i++)  \n\t    u[i]= 3.0f * v[i] + w[i];\n    // asm ( \"# end here native\" );\n    std::cout << \"Compute time native loop is \" << 1000000.0 * native.elapsed() / double(rep) << \" mmicros.\\n\";\n    std::cout << \"u[0] is \" << u[0] << '\\n';\n\n\n    boost::timer unrolled;\n    // asm ( \"# start here unrolled\" );\n    for (unsigned j= 0; j < rep; j++) {\n\tunsigned sb= s / 4 * 4;\n\tfor (unsigned i= 0; i < sb; i+= 4) {\n\t    u[i]=   3.0f * v[i]   + w[i];\n\t    u[i+1]= 3.0f * v[i+1] + w[i+1];\n\t    u[i+2]= 3.0f * v[i+2] + w[i+2];\n\t    u[i+3]= 3.0f * v[i+3] + w[i+3];\n\t} \n\tfor (unsigned i= sb; i < s; i++) \n\t    u[i]= 3.0f * v[i] + w[i];\n    }\n    // asm ( \"# end here unrolled\" );\n    std::cout << \"Compute time unrolled loop is \" << 1000000.0 * unrolled.elapsed() / double(rep) << \" mmicros.\\n\";\n    std::cout << \"u[0] is \" << u[0] << '\\n'; \n\n\n    boost::timer unrolled2; \n    for (unsigned j= 0; j < rep; j++)\n\tmy_axpy<2>(u, v, w);\n    std::cout << \"Compute time unrolled<2> loop is \" << 1000000.0 * unrolled2.elapsed() / double(rep) << \" mmicros.\\n\";\n    std::cout << \"u[0] is \" << u[0] << '\\n';\n\n\n    boost::timer unrolled4;\n    for (unsigned j= 0; j < rep; j++)\n\tmy_axpy<4>(u, v, w);\n    std::cout << \"Compute time unrolled<4> loop is \" << 1000000.0 * unrolled4.elapsed() / double(rep) << \" mmicros.\\n\";\n    std::cout << \"u[0] is \" << u[0] << '\\n';\n\n\n    boost::timer unrolled6;\n    for (unsigned j= 0; j < rep; j++)\n\tmy_axpy<6>(u, v, w);\n    std::cout << \"Compute time unrolled<6> loop is \" << 1000000.0 * unrolled6.elapsed() / double(rep) << \" mmicros.\\n\";\n    std::cout << \"u[0] is \" << u[0] << '\\n';\n\n\n    boost::timer unrolled8;\n    for (unsigned j= 0; j < rep; j++)\n\tmy_axpy<8>(u, v, w);\n    std::cout << \"Compute time unrolled<8> loop is \" << 1000000.0 * unrolled8.elapsed() / double(rep) << \" mmicros.\\n\";\n    std::cout << \"u[0] is \" << u[0] << '\\n';\n \n    return 0;\n}\n\n \n", "meta": {"hexsha": "f56f5261a7f50619b469dc47b9dc5182e0bdca03", "size": 4415, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "DMCpp/GottschlingRepo/c++03/vector_unroll_example_timer.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++03/vector_unroll_example_timer.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++03/vector_unroll_example_timer.cpp", "max_forks_repo_name": "tzaffi/cpp", "max_forks_repo_head_hexsha": "43d99e70d8fa712f90ea0f6147774e4e0f2b11da", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2018-01-04T13:40:40.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-02T12:49:21.000Z", "avg_line_length": 25.3735632184, "max_line_length": 119, "alphanum_fraction": 0.5225368063, "num_tokens": 1584, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737473266736, "lm_q2_score": 0.7154239836484144, "lm_q1q2_score": 0.4883296294462751}}
{"text": "//=======================================================================\n// Copyright 2009 Trustees of Indiana University.\n// Authors: Michael Hansen\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n\n#include <iostream>\n#include <map>\n#include <vector>\n#include <ctime>\n#include <boost/config.hpp>\n\n#ifdef BOOST_MSVC\n// Without disabling this we get hard errors about initialialized pointers:\n#pragma warning(disable : 4703)\n#endif\n\n#include <boost/lexical_cast.hpp>\n#include <boost/random.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <boost/graph/dijkstra_shortest_paths_no_color_map.hpp>\n#include <boost/graph/properties.hpp>\n#include <boost/graph/random.hpp>\n#include <boost/core/lightweight_test.hpp>\n#include <boost/graph/iteration_macros.hpp>\n\n#define INITIALIZE_VERTEX 0\n#define DISCOVER_VERTEX 1\n#define EXAMINE_VERTEX 2\n#define EXAMINE_EDGE 3\n#define EDGE_RELAXED 4\n#define EDGE_NOT_RELAXED 5\n#define FINISH_VERTEX 6\n\ntemplate < typename Graph > void run_dijkstra_test(const Graph& graph)\n{\n    using namespace boost;\n\n    // Set up property maps\n    typedef typename graph_traits< Graph >::vertex_descriptor vertex_t;\n\n    typedef typename std::map< vertex_t, vertex_t > vertex_map_t;\n    typedef associative_property_map< vertex_map_t > predecessor_map_t;\n    vertex_map_t default_vertex_map, no_color_map_vertex_map;\n    predecessor_map_t default_predecessor_map(default_vertex_map),\n        no_color_map_predecessor_map(no_color_map_vertex_map);\n\n    typedef typename std::map< vertex_t, double > vertex_double_map_t;\n    typedef associative_property_map< vertex_double_map_t > distance_map_t;\n    vertex_double_map_t default_vertex_double_map,\n        no_color_map_vertex_double_map;\n    distance_map_t default_distance_map(default_vertex_double_map),\n        no_color_map_distance_map(no_color_map_vertex_double_map);\n\n    // Run dijkstra algoirthms\n    dijkstra_shortest_paths(graph, vertex(0, graph),\n        predecessor_map(default_predecessor_map)\n            .distance_map(default_distance_map));\n\n    dijkstra_shortest_paths_no_color_map(graph, vertex(0, graph),\n        predecessor_map(no_color_map_predecessor_map)\n            .distance_map(no_color_map_distance_map));\n\n    // Verify that predecessor maps are equal\n    BOOST_TEST(std::equal(default_vertex_map.begin(), default_vertex_map.end(),\n        no_color_map_vertex_map.begin()));\n\n    // Verify that distance maps are equal\n    BOOST_TEST(std::equal(default_vertex_double_map.begin(),\n        default_vertex_double_map.end(),\n        no_color_map_vertex_double_map.begin()));\n}\n\nint main(int argc, char* argv[])\n{\n    using namespace boost;\n\n    int vertices_to_create = 10;\n    int edges_to_create = 500;\n    std::size_t random_seed = std::time(0);\n\n    if (argc > 1)\n    {\n        vertices_to_create = lexical_cast< int >(argv[1]);\n    }\n\n    if (argc > 2)\n    {\n        edges_to_create = lexical_cast< int >(argv[2]);\n    }\n\n    if (argc > 3)\n    {\n        random_seed = lexical_cast< std::size_t >(argv[3]);\n    }\n\n    minstd_rand generator(random_seed);\n\n    // Set up graph\n    typedef adjacency_list< listS, listS, directedS,\n        property< vertex_index_t, int >, property< edge_weight_t, double > >\n        graph_t;\n\n    graph_t graph;\n    generate_random_graph(\n        graph, vertices_to_create, edges_to_create, generator);\n\n    // Set up property maps\n    typedef property_map< graph_t, vertex_index_t >::type index_map_t;\n    index_map_t index_map = get(vertex_index, graph);\n    int vertex_index = 0;\n\n    BGL_FORALL_VERTICES(current_vertex, graph, graph_t)\n    {\n        put(index_map, current_vertex, vertex_index++);\n    }\n\n    randomize_property< edge_weight_t >(graph, generator);\n\n    // Run comparison test with original dijkstra_shortest_paths\n    std::cout << \"Running dijkstra shortest paths test with \"\n              << num_vertices(graph) << \" vertices and \" << num_edges(graph)\n              << \" edges \" << std::endl;\n\n    run_dijkstra_test(graph);\n\n    return boost::report_errors();\n}\n", "meta": {"hexsha": "0762b206992f1ba1d49f92a6caf77c82b44cbb21", "size": 4248, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "console/src/boost_1_78_0/libs/graph/test/dijkstra_no_color_map_compare.cpp", "max_stars_repo_name": "vany152/FilesHash", "max_stars_repo_head_hexsha": "39f282807b7f1abc56dac389e8259ee3bb557a8d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 106.0, "max_stars_repo_stars_event_min_datetime": "2015-08-07T04:23:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-27T18:25:15.000Z", "max_issues_repo_path": "console/src/boost_1_78_0/libs/graph/test/dijkstra_no_color_map_compare.cpp", "max_issues_repo_name": "vany152/FilesHash", "max_issues_repo_head_hexsha": "39f282807b7f1abc56dac389e8259ee3bb557a8d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 130.0, "max_issues_repo_issues_event_min_datetime": "2016-06-22T22:11:25.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-29T20:24:09.000Z", "max_forks_repo_path": "Libs/boost_1_76_0/libs/graph/test/dijkstra_no_color_map_compare.cpp", "max_forks_repo_name": "Antd23rus/S2DE", "max_forks_repo_head_hexsha": "47cc7151c2934cd8f0399a9856c1e54894571553", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2015-07-08T19:18:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-14T16:39:56.000Z", "avg_line_length": 31.9398496241, "max_line_length": 79, "alphanum_fraction": 0.7017419962, "num_tokens": 952, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239836484144, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.4883296202070398}}
{"text": "#include \"tasktorrent/tasktorrent.hpp\"\n#ifdef USE_MKL\n#include <mkl_cblas.h>\n#include <mkl_lapacke.h>\n#else\n#include <cblas.h>\n#include <lapacke.h>\n#endif\n#include <Eigen/Core>\n#include <Eigen/Cholesky>\n#include <fstream>\n#include <array>\n#include <random>\n#include <mutex>\n#include <iostream>\n#include <map>\n#include <memory>\n#include <set>\n#include <mpi.h>\n#include <string>\n#include <cxxopts.hpp>\n\nusing namespace std;\nusing namespace Eigen;\nusing namespace ttor;\n\ntypedef array<int, 2> int2;\ntypedef array<int, 3> int3;\n\n/*\n * Parametrized priorities for cholesky:\n * 0. No priority, only enforces potrf>trsm>gemm\n * 1. Row-based priority, prioritize tasks with smaller row number in addition to priority 0.\n * 2. Critical path priority, prioritize tasks with longest distance to the exit task. For references, check out the paper\n    Beaumont, Olivier, et al. \"A Makespan Lower Bound for the Scheduling of the Tiled Cholesky Factorization based on ALAP Schedule.\" (2020).\n * 3. Critical path and row priority, prioritize tasks with smaller row number in addition to priority 2. We also enforces potrf>trsm>gemm\n */\n\nenum PrioKind { no = 0, row = 1, cp = 2, cp_row = 3};\n\n\n/*\n* 3D Cholesky based on the algorithm from the paper\n    Kalluri Eswar, et al. \"On Mapping Data and Computation for Parallel Sparse Cholesky Factorization.\" (1995)\n* However, this implementation only uses 3D mapping for gemm tasks. 1D mapping is used for potrf tasks and 2D mapping is used for trsm tasks. \n*/\n\nvoid cholesky3d(int n_threads, int verb, int block_size, int num_blocks, int npcols, int nprows, PrioKind prio, int log, int debug)\n{\n    const int rank = comm_rank();\n    const int n_ranks = comm_size();\n    std::atomic<long long int> potrf_us_t(0);\n    std::atomic<long long int> trsm_us_t(0);\n    std::atomic<long long int> gemm_us_t(0);\n    std::atomic<long long int> accu_us_t(0);\n    assert(npcols * nprows == n_ranks);\n    int q = static_cast<int>(cbrt(n_ranks));\n    if (q * q * q != n_ranks)\n    {\n        if (rank == 0)\n        {\n            cerr << \"Number of processes must be a perfect cube.\" << endl;\n        }\n        MPI_Finalize();\n        exit(1);\n    }\n    \n    int3 rank_3d;\n    int2 rank_2d;\n    rank_3d[0] = rank / (q * q);\n    rank_3d[1] = (rank % (q * q)) / q;\n    rank_3d[2] = (rank % (q * q)) % q;\n    rank_2d[0] = rank % nprows;\n    rank_2d[1] = rank / nprows;\n\n    // Number of tasks\n    int n_tasks_per_rank = 2;\n    struct acc_data {\n        vector<std::unique_ptr<MatrixXd>> to_accumulate; // to_accumulate[k] holds matrix result of gemm(k,i,j)\n    };\n\n    auto potf_block_2_prio = [&](int j) {\n        if (prio == PrioKind::cp_row) {\n            return (double)(9 * (num_blocks - j) - 1) + 18 * num_blocks * num_blocks;\n        }\n        else if(prio == PrioKind::cp) {\n            return (double)(9 * (num_blocks - j) - 1);\n        }\n        else if(prio == PrioKind::row) {\n            return 3.0 * (double)(num_blocks - j);\n        }\n        else {\n            return 3.0;\n        }\n    };\n\n    auto trsm_block_2_prio = [&](int2 ij) {\n        if (prio == PrioKind::cp_row) {\n            return (double)((num_blocks - ij[0]) + num_blocks * (9.0 * num_blocks - 9.0 * ij[1] - 2.0) + 9 * num_blocks * num_blocks);\n        }\n        else if(prio == PrioKind::cp) {\n            return (double)(9 * (num_blocks - ij[1]) - 2);\n        }\n        else if(prio == PrioKind::row) {\n            return 2.0 * (double)(num_blocks - ij[0]);\n        }\n        else {\n            return 2.0;\n        }\n    };\n\n    auto gemm_block_2_prio = [&](int3 kij) {\n        if (prio == PrioKind::cp_row) {\n            return (double)(num_blocks - kij[1]) + num_blocks * (9.0 * num_blocks - 3.0 * kij[2] - 6.0 * (kij[0] / q) - 2.0);\n        }\n        else if(prio == PrioKind::cp) {\n            return (double)(9 * num_blocks - 9 * kij[2] - 2);\n        }\n        else if(prio == PrioKind::row) {\n            return (double)(num_blocks - kij[1]);\n        }\n        else {\n            return 1.0;\n        }\n    };\n\n    std::vector<acc_data> gemm_results(num_blocks*num_blocks);\n    auto val = [&](int i, int j) { return 1.0/(double)((i + j)*(i + j) + 1) + ((i == j) ? 1.0 * block_size * num_blocks : 0.0); };\n    auto rank3d21 = [&](int i, int j, int k) { return ((j % q) * q + k % q) + (i % q) * q * q;};\n    auto rank2d21 = [&](int i, int j) { return (j % npcols) * nprows + (i % nprows);};\n    auto rank1d21 = [&](int j) { return j % n_ranks; };\n    vector<unique_ptr<MatrixXd>> blocks(num_blocks*num_blocks);\n\n    auto bloc_2_rank = [&](int i, int j) {\n        int r = (j % npcols) * nprows + (i % nprows);\n        assert(r >= 0 && r < n_ranks);\n        return r;\n    };\n \n    auto block_2_thread = [&](int i, int j) {\n        int ii = i / nprows;\n        int jj = j / npcols;\n        int num_blocksit = num_blocks / nprows;\n        return (ii + jj * num_blocksit) % n_threads;\n    };\n    {\n        Eigen::MatrixXd A = Eigen::MatrixXd::Identity(256,256);\n        Eigen::MatrixXd B = Eigen::MatrixXd::Identity(256,256);\n        Eigen::MatrixXd C = Eigen::MatrixXd::Identity(256,256);\n        for(int i = 0; i < 10; i++) {\n            cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, 256, 256, 256, 1.0, A.data(), 256, B.data(), 256, 1.0, C.data(), 256);\n        }\n    }\n    for (int ii=0; ii<num_blocks; ii++) {\n        for (int jj=0; jj<num_blocks; jj++) {\n            auto val_loc = [&](int i, int j) { return val(ii*block_size+i,jj*block_size+j); };\n            int dest = (ii == jj) ? rank1d21(ii) : rank2d21(ii,jj);\n            if(dest == rank) {\n                blocks[ii+jj*num_blocks]=make_unique<MatrixXd>(block_size, block_size);\n                *blocks[ii+jj*num_blocks]=MatrixXd::NullaryExpr(block_size, block_size, val_loc);\n                gemm_results[ii+jj*num_blocks].to_accumulate= vector<std::unique_ptr<MatrixXd>>(q);\n                for (int ll=0; ll<q; ll++) {\n                    gemm_results[ii+jj*num_blocks].to_accumulate[ll]=make_unique<MatrixXd>(block_size, block_size);\n                    *(gemm_results[ii+jj*num_blocks].to_accumulate[ll])=MatrixXd::Zero(block_size, block_size);\n                }\n            } \n            else if (((ii % q) == rank_3d[0]) && ((jj % q) == rank_3d[1])) {\n                blocks[ii+jj*num_blocks]=make_unique<MatrixXd>(block_size, block_size);\n                *blocks[ii+jj*num_blocks]=MatrixXd::Zero(block_size, block_size);\n            } \n            else {\n                blocks[ii+jj*num_blocks]=make_unique<MatrixXd>(block_size, block_size);\n            }\n        }\n    }\n    // Initialize the communicator structure\n    Communicator comm(MPI_COMM_WORLD, verb);\n    // Initialize the runtime structures\n    Threadpool tp(n_threads, &comm, verb, \"WkTuto_\" + to_string(rank) + \"_\");\n    Taskflow<int> potrf(&tp, verb);\n    Taskflow<int2> trsm(&tp, verb);\n    Taskflow<int3> gemm(&tp, verb);\n    Taskflow<int3> accu(&tp, verb);\n    DepsLogger dlog(1000000);\n    Logger ttorlog(1000000);\n    if (log)  {\n        tp.set_logger(&ttorlog);\n        comm.set_logger(&ttorlog);\n    }\n    // Create active message\n    auto am_trsm = comm.make_large_active_msg( \n        [&](int& j) {\n                int offset = ((j + 1) / nprows + (((j + 1) % nprows) > rank_2d[0])) * nprows + rank_2d[0];\n                for(int i = offset; i < num_blocks; i = i + nprows) {\n                    if (debug) printf(\"Fulfilling trsm (%d, %d) on rank (%d, %d)\\n\", i, j, rank_2d[0], rank_2d[1]);\n                    assert(rank2d21(i, j) == rank);\n                    trsm.fulfill_promise({i,j});\n                }\n            },\n            [&](int& j){\n                return blocks[j+j*num_blocks]->data();\n            },\n            [&](int& j){\n                return;\n            });\n\n    auto am_gemm = comm.make_large_active_msg(\n        [&](int& i, int& k) {\n            assert(k % q == rank_3d[2]);\n            int offset_c = ((k + 1) / q + (((k + 1) % q) > rank_3d[1])) * q + rank_3d[1]; \n            if (i % q == rank_3d[0]) {\n                for(int j = offset_c; j < i; j = j + q) {\n                    if (debug) printf(\"TRSM (%d, %d) Fulfilling gemm (%d, %d, %d) on rank (%d, %d, %d)\\n\", i, k, k, i, j, rank_3d[2], rank_3d[0], rank_3d[1]);\n                    assert(rank3d21(i,j,k) == rank);\n                    gemm.fulfill_promise({k,i,j});\n                }\n            }\n            int offset_r = (i / q + ((i % q) > rank_3d[0])) * q + rank_3d[0];\n            if (i % q == rank_3d[1]) {\n                for(int j = offset_r; j < num_blocks; j = j + q) {\n                    if (debug) printf(\"TRSM (%d, %d) Fulfilling gemm (%d, %d, %d) on rank (%d, %d, %d)\\n\", i,k, k, j, i, rank_3d[2], rank_3d[0], rank_3d[1]);  \n                    assert(rank3d21(j,i,k) == rank);    \n                    gemm.fulfill_promise({k,j,i});\n                }\n            }\n        },\n        [&](int& i, int& k) {\n            return blocks[i+k*num_blocks]->data();\n        },\n        [&](int& i, int& k) {\n            return;\n        });\n\n    potrf.set_task([&](int j) {\n            assert(rank1d21(j) == rank);\n            timer t1 = wctime();\n            int info = LAPACKE_dpotrf(LAPACK_COL_MAJOR, 'L', block_size, blocks[j+j*num_blocks]->data(), block_size);\n            timer t2 = wctime();\n            potrf_us_t += 1e6 * elapsed(t1, t2);\n            assert(info == 0);\n            if (debug) printf(\"Running POTRF %d on rank %d\\n\", j, rank);\n        })\n        .set_fulfill([&](int j) { \n            for (int p = 0; p < nprows; p++) \n            {   \n                int r = rank2d21(p,j);\n                if (rank == r) {\n                    int offset = ((j + 1) / nprows + ((j + 1) % nprows) / (rank_2d[0] + 1)) * nprows + rank_2d[0];\n                    for(int i = offset; i < num_blocks; i = i + nprows) {\n                        trsm.fulfill_promise({i,j});\n                    }\n                }\n                else {\n                    auto Ljjv = view<double>(blocks[j+j*num_blocks]->data(), block_size*block_size);\n                    am_trsm->send_large(r, Ljjv, j);\n                }\n            }\n        })\n        .set_indegree([&](int j) {\n            if (j==0) {\n                return 1;\n            }\n            else if (j < q) {\n                return j;\n            }\n            else {\n                return q;\n            }\n        })\n        .set_mapping([&](int j) {\n            return block_2_thread(j,j);\n        })\n        .set_binding([&](int j) {\n            return false;\n\n        })        \n        .set_priority(potf_block_2_prio)\n        .set_name([&](int j) { \n            return \"POTRF\" + to_string(j) + \"_\" + to_string(rank);\n        });\n\n    trsm.set_task([&](int2 ij) {\n            int i=ij[0];\n            int j=ij[1];\n            assert(rank2d21(i,j) == rank);\n            timer t1 = wctime();\n            cblas_dtrsm(CblasColMajor, CblasRight, CblasLower, CblasTrans, CblasNonUnit, block_size, block_size, 1.0, blocks[j + j * num_blocks]->data(),block_size, blocks[i + j * num_blocks]->data(), block_size);\n            timer t2 = wctime();\n            trsm_us_t += 1e6 * elapsed(t1, t2);\n            if (debug) printf(\"Running trsm (%d, %d) on rank %d, %d\\n\", i, j, rank_2d[0], rank_2d[1]);\n        })\n        .set_fulfill([&](int2 ij) {\n            int i=ij[0];\n            int j=ij[1]; \n            for (int ri = 0; ri < q; ri++)  {\n                for (int rj = 0; rj < q; rj++) {\n                    int r = rank3d21(ri, rj, j);\n                    if (r == rank) {\n                        int offset_c = ((j + 1) / q + (((j + 1) % q) > rank_3d[1])) * q + rank_3d[1];\n                        if (i % q == rank_3d[0]) {\n                            for(int k = offset_c; k < i; k = k + q) {\n                                gemm.fulfill_promise({j,i,k});\n                            }\n                        }\n                        int offset_r = (i / q + ((i % q) > rank_3d[0])) * q + rank_3d[0];\n                        if (i % q == rank_3d[1]) {\n                            for(int k = offset_r; k < num_blocks; k = k + q) {\n                                gemm.fulfill_promise({j,k,i});\n                            } \n                        }\n                    }\n                    else {\n                        auto Lijv = view<double>(blocks[i + j * num_blocks]->data(), block_size*block_size);\n                        am_gemm->send_large(r, Lijv, i, j);\n                    } \n                }\n            }            \n        })\n        .set_indegree([&](int2 ij) {\n            int i=ij[0];\n            int j=ij[1];\n            return (j < q) ? j + 1 : q + 1;\n        })\n        .set_mapping([&](int2 ij) {\n            int i=ij[0];\n            int j=ij[1];\n            return block_2_thread(i,j);\n        })\n        .set_binding([&](int2 ij) {\n            int i=ij[0];\n            int j=ij[1];\n            return false;\n\n        })\n        .set_priority(trsm_block_2_prio)\n        .set_name([&](int2 ij) { \n            int i=ij[0];\n            int j=ij[1];\n            return \"TRSM\" + to_string(j) + \"_\" + to_string(i) + \"_\" +to_string(rank);\n        });\n   \n    auto am_accu = comm.make_large_active_msg(\n        [&](int& i, int& j, int& from) {\n            accu.fulfill_promise({from, i, j});\n        },\n        [&](int& i, int& j, int& from){\n            return gemm_results[i+j*num_blocks].to_accumulate[from]->data();\n        },\n        [&](int& i, int& j, int& from){\n            return; \n        });\n    \n    gemm.set_task([&](int3 kij) {\n            int k=kij[0];\n            int i=kij[1];\n            int j=kij[2]; \n            assert(rank3d21(i,j,k) == rank);\n            timer t1 = wctime();           \n            if (i==j) { \n                cblas_dsyrk(CblasColMajor, CblasLower, CblasNoTrans, block_size, block_size, -1.0, blocks[i+k*num_blocks]->data(), block_size, 1.0, blocks[i+j*num_blocks]->data(), block_size);\n            }\n            else {\n                cblas_dgemm(CblasColMajor, CblasNoTrans, CblasTrans, block_size, block_size, block_size, -1.0,blocks[i+k*num_blocks]->data(), block_size, blocks[j+k*num_blocks]->data(), block_size, 1.0, blocks[i+j*num_blocks]->data(), block_size);\n            }\n            timer t2 = wctime();\n            if (debug) printf(\"Running gemm (%d, %d, %d) on rank %d, %d, %d\\n\", k, i, j, rank_3d[2], rank_3d[0], rank_3d[1]);\n            gemm_us_t += 1e6 * elapsed(t1, t2);\n        })\n        .set_fulfill([&](int3 kij) { \n            int k=kij[0];\n            int i=kij[1];\n            int j=kij[2];\n            if (k+q<=j-1) {\n                gemm.fulfill_promise({k+q, i, j});\n            }\n            else {\n                int dest = (i == j) ? rank1d21(i) : rank2d21(i, j);\n                if (dest == rank) {\n                    if (debug) printf(\"gemm (%d, %d, %d) fulfilling accumu (%d, %d, %d) on rank %d, %d, %d\\n\", k, i, j, rank_3d[2], i, j, rank_3d[2], rank_3d[0], rank_3d[1]);\n                    accu.fulfill_promise({rank_3d[2], i, j});\n                }\n                else {\n                    int kk = rank_3d[2];\n                    auto Lij = view<double>(blocks[i+j*num_blocks]->data(), block_size*block_size);\n                    if (debug) printf(\"gemm (%d, %d, %d) Sending accumu (%d, %d, %d) to rank %d, %d\\n\", k, i, j, rank_3d[2], i, j, dest % nprows, dest / nprows);\n                    am_accu->send_large(dest, Lij, i, j, kk);\n                }\n            }\n        })\n        .set_indegree([&](int3 kij) {\n            int k=kij[0];\n            int i=kij[1];\n            int j=kij[2];\n            return 3 - (k/q == 0) - (i == j);\n        })\n        .set_mapping([&](int3 kij) {\n            int k=kij[0];\n            int i=kij[1];\n            int j=kij[2];\n            return block_2_thread(i,j);\n        })\n        .set_binding([&](int3 kij) {\n            return false;\n\n        })\n        .set_priority(gemm_block_2_prio)\n        .set_name([&](int3 kij) { // This is just for debugging and profiling\n            int k=kij[0];\n            int i=kij[1];\n            int j=kij[2];\n            return \"gemm\" + to_string(k) + \"_\" + to_string(i)+\"_\"+to_string(j)+\"_\"+to_string(comm_rank());\n        });\n\n    accu.set_task([&](int3 kij) {\n            int k=kij[0]; // Step (gemm's pivot)\n            int i=kij[1]; // Row\n            int j=kij[2]; // Col\n            int dest = (i == j) ? rank1d21(i) : rank2d21(i,j);\n            assert(dest == rank);\n            assert(j <= i);\n            if (debug) printf(\"Running accumu (%d, %d, %d) on rank %d, %d\\n\", k, i, j, rank % nprows, rank / nprows);\n            {\n                timer t_ = wctime();\n                *blocks[i+j*num_blocks] += (*gemm_results[i+j*num_blocks].to_accumulate[k]);\n                timer t__ = wctime();\n                accu_us_t += 1e6 * elapsed(t_, t__);\n            }\n        })\n        .set_fulfill([&](int3 kij) {\n            int k=kij[0];\n            int i=kij[1];\n            int j=kij[2];\n            assert(j <= i);\n            if(i == j) {\n                potrf.fulfill_promise(i);\n            } else {\n                trsm.fulfill_promise({i,j});\n            }\n        })\n        .set_indegree([&](int3 kij) {\n            return 1;\n        })\n        .set_mapping([&](int3 kij) {\n            int k=kij[0];\n            int i=kij[1];\n            int j=kij[2];\n            return block_2_thread(i,j);\n        })\n        .set_priority(gemm_block_2_prio)\n        .set_binding([&](int3 kij) {\n            return true; // IMPORTANT\n        })\n        .set_name([&](int3 kij) { // This is just for debugging and profiling\n            int k=kij[0];\n            int i=kij[1];\n            int j=kij[2];\n            return \"accumu\" + to_string(k) + \"_\" + to_string(i)+\"_\"+to_string(j)+\"_\"+to_string(comm_rank());\n        });\n\n    MPI_Barrier(MPI_COMM_WORLD);\n    timer t0 = wctime();\n    if (rank == 0){\n        potrf.fulfill_promise(0);\n    }\n    tp.join();\n    MPI_Barrier(MPI_COMM_WORLD);\n    timer t1 = wctime();\n    MPI_Status status;\n    if (rank==0) {\n        cout<<\"3D, Number of ranks \"<<n_ranks<<\", block_size \"<<block_size<<\", num_blocks \"<<num_blocks<<\", n_threads \"<<n_threads<<\", Priority \"<<prio<<\", Elapsed time: \"<<elapsed(t0,t1)<<endl;\n    }\n    MatrixXd A;\n    A = MatrixXd::NullaryExpr(block_size*num_blocks,block_size*num_blocks, val);\n    MatrixXd L = A;\n    for (int ii=0; ii<num_blocks; ii++) {\n        for (int jj=0; jj<num_blocks; jj++) {\n            if (jj<=ii)  {\n                int dest = (ii == jj) ? rank1d21(ii) : rank2d21(ii,jj);\n                if (rank==0 && rank!=dest) {\n                    blocks[ii+jj*num_blocks]=make_unique<MatrixXd>(block_size,block_size);\n                    MPI_Recv(blocks[ii+jj*num_blocks]->data(), block_size*block_size, MPI_DOUBLE, dest, 0, MPI_COMM_WORLD, &status);\n                }\n                else if (rank==dest && rank != 0) {\n                    MPI_Send(blocks[ii+jj*num_blocks]->data(), block_size*block_size, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD);\n                }\n            }\n        }\n    }\n    if (rank == 0)  {\n        for (int ii=0; ii<num_blocks; ii++) {\n            for (int jj=0; jj<num_blocks; jj++) {\n                if (jj<=ii)  {\n                    L.block(ii*block_size,jj*block_size,block_size,block_size)=*blocks[ii+jj*num_blocks];\n                }\n            }\n        }\n        auto L1=L.triangularView<Lower>();\n        VectorXd x = VectorXd::Random(block_size * num_blocks);\n        VectorXd b = A*x;\n        L1.solveInPlace(b);\n        L1.transpose().solveInPlace(b);\n        double error = (b - x).norm() / x.norm();\n        cout << \"Error solve: \" << error << endl;\n    }\n    if (log)  {\n        std::ofstream logfile;\n        string filename = \"ttor_3Dcholesky_Priority_\"+to_string(block_size)+\"_\"+to_string(num_blocks)+\"_\"+ to_string(n_threads)+\"_\"+ to_string(n_ranks)+\"_\"+ to_string(prio)+\".log.\"+to_string(rank);\n        logfile.open(filename);\n        logfile << ttorlog;\n        logfile.close();\n    }\n}\n\nint main(int argc, const char **argv)\n{\n\n    int req = MPI_THREAD_FUNNELED;\n    int prov = -1;\n\n    MPI_Init_thread(NULL, NULL, req, &prov);\n\n    assert(prov == req);\n\n    std::stringstream sstr;\n    sstr << comm_size();\n    const std::string comm_size_str = sstr.str();\n\n    cxxopts::Options options(\"2d_cholesky\", \"2D dense cholesky using TaskTorrent\");\n    options.add_options()\n        (\"help\", \"Print help\")\n        (\"n_threads\", \"Number of threads\", cxxopts::value<int>()->default_value(\"2\"))\n        (\"verb\", \"Verbosity level\", cxxopts::value<int>()->default_value(\"0\"))\n        (\"block_size\", \"Block size\", cxxopts::value<int>()->default_value(\"5\"))\n        (\"num_blocks\", \"Number of blocks\", cxxopts::value<int>()->default_value(\"10\"))\n        (\"nprows\", \"Number of processors accross rows\", cxxopts::value<int>()->default_value(\"1\"))\n        (\"npcols\", \"Number of processors accross columns\", cxxopts::value<int>()->default_value(comm_size_str.c_str()))\n        (\"kind\", \"Priority kind\", cxxopts::value<int>()->default_value(\"0\"))\n        (\"log\", \"Enable logging\", cxxopts::value<bool>()->default_value(\"false\"))\n        (\"debug\", \"Debug or not\", cxxopts::value<bool>()->default_value(\"false\"));\n    auto result = options.parse(argc, argv);\n\n    const int n_threads = result[\"n_threads\"].as<int>();\n    const int verb = result[\"verb\"].as<int>();\n    const int block_size = result[\"block_size\"].as<int>();\n    const int num_blocks = result[\"num_blocks\"].as<int>();\n    const int nprows = result[\"nprows\"].as<int>();\n    const int npcols = result[\"npcols\"].as<int>();\n    const PrioKind prio = (PrioKind)(result[\"kind\"].as<int>());\n    const bool log = result[\"log\"].as<bool>();\n    const bool debug = result[\"debug\"].as<bool>();\n\n    assert(block_size > 0);\n    assert(num_blocks > 0);\n    assert(n_threads > 0);\n    assert(verb >= 0);\n    assert(nprows >= 0);\n    assert(npcols >= 0);\n\n    if (result.count(\"help\")) {\n        std::cout << options.help({\"\", \"Group\"}) << endl;\n        exit(0);\n    }\n    if(comm_rank() == 0) printf(\"Arguments: block_size (size of blocks) %d\\nnum_blocks (# of blocks) %d\\nn_threads %d\\nverb %d\\nnprows %d\\nnpcols %d\\nprio %d\\nlog %d\\ndebug %d\\n\", \n        block_size, num_blocks, n_threads, verb, nprows, npcols, (int)prio, log, debug);\n\n    cholesky3d(n_threads, verb, block_size, num_blocks, npcols, nprows, prio, log, debug);  \n    MPI_Finalize();\n}\n", "meta": {"hexsha": "84d920b76ea24656fa15dae9005d8740497b1c68", "size": 22293, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "miniapp/dense_cholesky/3d_cholesky.cpp", "max_stars_repo_name": "Abeynaya/tasktorrent", "max_stars_repo_head_hexsha": "987718e6e9033ae8aa295323e4699e759d744e7f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2019-09-29T19:33:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T01:48:40.000Z", "max_issues_repo_path": "miniapp/dense_cholesky/3d_cholesky.cpp", "max_issues_repo_name": "Abeynaya/tasktorrent", "max_issues_repo_head_hexsha": "987718e6e9033ae8aa295323e4699e759d744e7f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-03-11T18:14:08.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-09T22:32:56.000Z", "max_forks_repo_path": "miniapp/dense_cholesky/3d_cholesky.cpp", "max_forks_repo_name": "Abeynaya/tasktorrent", "max_forks_repo_head_hexsha": "987718e6e9033ae8aa295323e4699e759d744e7f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-10-22T06:40:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-01T08:17:39.000Z", "avg_line_length": 39.1792618629, "max_line_length": 247, "alphanum_fraction": 0.4988561432, "num_tokens": 6501, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145998, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.4881901769294539}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// Unit Test\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// 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\n#include \"test_envelope.hpp\"\n\n#include <boost/geometry/geometries/geometries.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/adapted/c_array.hpp>\n#include <boost/geometry/geometries/adapted/boost_tuple.hpp>\n#include <test_common/test_point.hpp>\n\nBOOST_GEOMETRY_REGISTER_C_ARRAY_CS(cs::cartesian)\nBOOST_GEOMETRY_REGISTER_BOOST_TUPLE_CS(cs::cartesian)\n\n\ntemplate <typename P>\nvoid test_2d()\n{\n    /*test_envelope<bg::model::multi_point<P> >(\n            \"MULTIPOINT((1 1),(1 0),(1 2))\", 1, 1, 0, 2);\n    test_envelope<bg::model::multi_linestring<bg::model::linestring<P> > >(\n            \"MULTILINESTRING((0 0,1 1),(1 1,2 2),(2 2,3 3))\", 0, 3, 0, 3);\n*/\n    test_envelope<bg::model::multi_polygon<bg::model::polygon<P> > >(\n            \"MULTIPOLYGON(((1 1,1 3,3 3,3 1,1 1)),((4 4,4 6,6 6,6 4,4 4)))\", 1, 6, 1, 6);\n}\n\n\ntemplate <typename P>\nvoid test_3d()\n{\n    //typedef bg::model::multi_point<P> mp;\n}\n\n\nint test_main( int , char* [] )\n{\n    test_2d<boost::tuple<float, float> >();\n    test_2d<bg::model::d2::point_xy<float> >();\n    test_2d<bg::model::d2::point_xy<double> >();\n\n    test_3d<boost::tuple<float, float, float> >();\n    test_3d<bg::model::point<double, 3, bg::cs::cartesian> >();\n\n    return 0;\n}\n", "meta": {"hexsha": "d53a05955af133adbfe5cc681f80a7116e9f9c04", "size": 1848, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/algorithms/envelope_expand/envelope_multi.cpp", "max_stars_repo_name": "jkerkela/geometry", "max_stars_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 326.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T13:47:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T02:13:59.000Z", "max_issues_repo_path": "test/algorithms/envelope_expand/envelope_multi.cpp", "max_issues_repo_name": "jkerkela/geometry", "max_issues_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 623.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T23:45:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T11:15:23.000Z", "max_forks_repo_path": "Libs/boost_1_76_0/libs/geometry/test/algorithms/envelope_expand/envelope_multi.cpp", "max_forks_repo_name": "Antd23rus/S2DE", "max_forks_repo_head_hexsha": "47cc7151c2934cd8f0399a9856c1e54894571553", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-01-14T15:50:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T03:58:36.000Z", "avg_line_length": 31.3220338983, "max_line_length": 89, "alphanum_fraction": 0.6823593074, "num_tokens": 612, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145998, "lm_q2_score": 0.6442251201477015, "lm_q1q2_score": 0.4881901769294538}}
{"text": "#ifndef CPP_EVALUATOR_UTILS_HH\n#define CPP_EVALUATOR_UTILS_HH\n\n#include \"Evaluator.hh\"\n\n#include <array>\n#include <iterator>\n\n#include <boost/range/adaptor/transformed.hpp>\n#include <boost/range/algorithm/max_element.hpp>\n#include <boost/range/algorithm/transform.hpp>\n#include <boost/range/numeric.hpp>\n\nnamespace tl\n{\n\n/**\n * Linear tensor field expressed in barycentric coordinates\n */\nusing TensorInterp = TensorProductBezierTriangle<Mat3d, double, 1>;\n\n/**\n * Compute the derivatives of a TensorProductBezierTriangle along two\n * orthogonal directions on the triangle in the space indicated by @a D.\n *\n * @param poly The polynomial.\n * @tparam D The space (0-sizeof...(Degrees)) in which to perform the derivative\n */\ntemplate <std::size_t D,\n          typename TPBT,\n          typename T,\n          typename C,\n          std::size_t... Degrees>\nauto derivatives(\n        const TensorProductBezierTriangleBase<TPBT, T, C, Degrees...>& poly)\n        -> std::array<\n                typename TensorProductDerivativeType<D, T, C, Degrees...>::type,\n                2>\n{\n    static_assert(D < sizeof...(Degrees), \"Invalid index\");\n    auto d0 = poly.template derivative<D>(0);\n    auto d1 = poly.template derivative<D>(1);\n    auto d2 = poly.template derivative<D>(2);\n\n    auto da = (d1 - d0) / std::sqrt(2);\n\n    auto db = (2 * d2 - d0 - d1) / std::sqrt(6);\n\n    return {da, db};\n}\n\n\n/**\n * @brief Compute an upper bound for the magnitude of the function value.\n * @details Finds the coefficient with the maximum absolute value.\n *\n * @param poly The polynomial\n * @return An upper bound for std::abs(poly(x)) on the triangles\n */\ntemplate <typename TPBT,\n          typename T,\n          typename C,\n          std::size_t... Degrees>\ndouble abs_upper_bound(\n        const TensorProductBezierTriangleBase<TPBT, T, C, Degrees...>& poly)\n{\n    return boost::accumulate(poly.coefficients(), 0., MaxAbs{});\n}\n\n\n/**\n * @brief Compute an upper bound for the magnitude of a number of polynomials.\n * @details Finds the coefficient with the maximum absolute value of all\n *     polynomials.\n *\n * @param polys A sequence of polynomials\n * @return An upper bound for std::abs(poly(x)) over all polynomials in the\n *     sequence\n */\ntemplate <typename TPBTSeq>\ndouble abs_max_upper_bound(const TPBTSeq& polys)\n{\n    using namespace boost;\n    using namespace boost::adaptors;\n    return accumulate(polys | transformed([](const auto& f) {\n                          return abs_upper_bound(f);\n                      }),\n                      0.,\n                      Max{});\n}\n\n\n/**\n * @brief Compute an upper bound for the gradient magnitude of the polynomial in\n *      the space indicated by @a D.\n *\n * @param poly The polynomial\n * @tparam D The space (0-sizeof...(Degrees)) in which to perform the derivative\n * @return an estimate for the upper bound of the gradient magnitude of poly(x)\n *      on the triangles\n */\ntemplate <std::size_t D,\n          typename TPBT,\n          typename T,\n          typename C,\n          std::size_t... Degrees>\ndouble derivatives_upper_bound(\n        const TensorProductBezierTriangleBase<TPBT, T, C, Degrees...>& poly)\n{\n    static_assert(D < sizeof...(Degrees), \"Invalid index\");\n    auto upper_bound = typename TPBT::Coeffs{};\n    // Estimate upper bound of gradient magnitude by L1 norm of control points\n    // todo: Can we do better? (Represent gradient magnitude as polynomial)\n    auto abssum = [](double v1, double v2) {\n        return std::abs(v1) + std::abs(v2);\n    };\n    auto derivs = derivatives<D>(poly);\n    boost::transform(derivs[0].coefficients(),\n                     derivs[1].coefficients(),\n                     std::begin(upper_bound),\n                     abssum);\n    return *boost::max_element(upper_bound);\n}\n\n/**\n * @brief Compute an upper bound for the gradient magnitude of a sequence of\n *      polynomials in the space indicated by @a D.\n *\n * @param polys A sequence (range) of polynomials\n * @tparam D The space in which to perform the derivatives\n * @return Upper bound for the gradient magnitude on the triangles\n */\ntemplate <std::size_t D, typename TPBTSeq>\ndouble derivatives_max_upper_bound(const TPBTSeq& polys)\n{\n    using namespace boost;\n    using namespace boost::adaptors;\n    return accumulate(polys | transformed([](const auto& f) {\n                          return derivatives_upper_bound<D>(f);\n                      }),\n                      0.,\n                      Max{});\n}\n\n\n/**\n * @brief Compute an upper bound for the norm of a vector of values from\n *     multiple polynomials.\n * @details Finds an upper bound for sqrt(poly_1(x)^2 + poly_2(x)^2 + ...)\n *      where poly_i are the elements of the sequence @a polys.\n *\n * @param polys A sequence (range) of polynomials\n * @return Upper bound for the norm of the vector od polynomials on the\n *     triangles\n */\ntemplate <typename TPBTSeq>\ndouble upper_bound_norm(const TPBTSeq& polys)\n{\n    using namespace boost;\n    using namespace boost::adaptors;\n    return std::sqrt(accumulate(polys | transformed([](const auto& f) {\n                                    return std::pow(\n                                            *max_element(f.coefficients()), 2);\n                                }),\n                                0.));\n}\n\n} // namespace tl\n\n#endif\n", "meta": {"hexsha": "4c7fa60126c0d34a002519d5d9a4edcf759c6b0d", "size": 5304, "ext": "hh", "lang": "C++", "max_stars_repo_path": "cpp/src/EvaluatorUtils.hh", "max_stars_repo_name": "timo-oster/tensor-lines", "max_stars_repo_head_hexsha": "b4f489452f3ce5b5f48042cc035e53d3fdaa675e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cpp/src/EvaluatorUtils.hh", "max_issues_repo_name": "timo-oster/tensor-lines", "max_issues_repo_head_hexsha": "b4f489452f3ce5b5f48042cc035e53d3fdaa675e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp/src/EvaluatorUtils.hh", "max_forks_repo_name": "timo-oster/tensor-lines", "max_forks_repo_head_hexsha": "b4f489452f3ce5b5f48042cc035e53d3fdaa675e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-13T00:08:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-13T00:08:09.000Z", "avg_line_length": 31.0175438596, "max_line_length": 80, "alphanum_fraction": 0.6310331825, "num_tokens": 1214, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145998, "lm_q2_score": 0.6442250996557036, "lm_q1q2_score": 0.48819016140073296}}
{"text": "#include \"prime_factors.h\"\n#define BOOST_TEST_MAIN\n#include <boost/test/unit_test.hpp>\n#include <iostream>\n\nBOOST_AUTO_TEST_CASE(_1_yields_empty)\n{\n    const std::vector<int> expected{};\n\n    const std::vector<int> actual{prime_factors::of(1)};\n\n    BOOST_REQUIRE_EQUAL_COLLECTIONS(expected.begin(), expected.end(), actual.begin(), actual.end());\n}\n\nBOOST_AUTO_TEST_CASE(_2_yields_2)\n{\n    const std::vector<int> expected{2};\n\n    const std::vector<int> actual{prime_factors::of(2)};\n\n    BOOST_REQUIRE_EQUAL_COLLECTIONS(expected.begin(), expected.end(), actual.begin(), actual.end());\n}\n\nBOOST_AUTO_TEST_CASE(_3_yields_3)\n{\n    const std::vector<int> expected{3};\n\n    const std::vector<int> actual{prime_factors::of(3)};\n\n    BOOST_REQUIRE_EQUAL_COLLECTIONS(expected.begin(), expected.end(), actual.begin(), actual.end());\n}\n\nBOOST_AUTO_TEST_CASE(_4_yields_2_2)\n{\n    const std::vector<int> expected{2, 2};\n\n    const std::vector<int> actual{prime_factors::of(4)};\n\n    BOOST_REQUIRE_EQUAL_COLLECTIONS(expected.begin(), expected.end(), actual.begin(), actual.end());\n}\n\nBOOST_AUTO_TEST_CASE(_6_yields_2_3)\n{\n    const std::vector<int> expected{2, 3};\n\n    const std::vector<int> actual{prime_factors::of(6)};\n\n    BOOST_REQUIRE_EQUAL_COLLECTIONS(expected.begin(), expected.end(), actual.begin(), actual.end());\n}\n\nBOOST_AUTO_TEST_CASE(_8_yields_2_2_2)\n{\n    const std::vector<int> expected{2, 2, 2};\n\n    const std::vector<int> actual{prime_factors::of(8)};\n\n    BOOST_REQUIRE_EQUAL_COLLECTIONS(expected.begin(), expected.end(), actual.begin(), actual.end());\n}\n\nBOOST_AUTO_TEST_CASE(_9_yields_3_3)\n{\n    const std::vector<int> expected{3, 3};\n\n    const std::vector<int> actual{prime_factors::of(9)};\n\n    BOOST_REQUIRE_EQUAL_COLLECTIONS(expected.begin(), expected.end(), actual.begin(), actual.end());\n}\n\nBOOST_AUTO_TEST_CASE(_27_yields_3_3_3)\n{\n    const std::vector<int> expected{3, 3, 3};\n\n    const std::vector<int> actual{prime_factors::of(27)};\n\n    BOOST_REQUIRE_EQUAL_COLLECTIONS(expected.begin(), expected.end(), actual.begin(), actual.end());\n}\n\nBOOST_AUTO_TEST_CASE(_625_yields_5_5_5_5)\n{\n    const std::vector<int> expected{5, 5, 5, 5};\n\n    const std::vector<int> actual{prime_factors::of(625)};\n\n    BOOST_REQUIRE_EQUAL_COLLECTIONS(expected.begin(), expected.end(), actual.begin(), actual.end());\n}\n\nBOOST_AUTO_TEST_CASE(_901255_yields_5_17_23_461)\n{\n    const std::vector<int> expected{5, 17, 23, 461};\n\n    const std::vector<int> actual{prime_factors::of(901255)};\n\n    BOOST_REQUIRE_EQUAL_COLLECTIONS(expected.begin(), expected.end(), actual.begin(), actual.end());\n}\n#if defined(EXERCISM_RUN_ALL_TESTS)\n#endif\n", "meta": {"hexsha": "a350b8a1ae0f29732e542b8f344a373df8aeb4eb", "size": 2632, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "prime-factors/prime_factors_test.cpp", "max_stars_repo_name": "cmccandless/ExercismSolutions-cpp", "max_stars_repo_head_hexsha": "1a97e2a68513a34883b29ed047443b6602e77d3b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "prime-factors/prime_factors_test.cpp", "max_issues_repo_name": "cmccandless/ExercismSolutions-cpp", "max_issues_repo_head_hexsha": "1a97e2a68513a34883b29ed047443b6602e77d3b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "prime-factors/prime_factors_test.cpp", "max_forks_repo_name": "cmccandless/ExercismSolutions-cpp", "max_forks_repo_head_hexsha": "1a97e2a68513a34883b29ed047443b6602e77d3b", "max_forks_repo_licenses": ["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.1340206186, "max_line_length": 100, "alphanum_fraction": 0.7207446809, "num_tokens": 689, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.7577943658046609, "lm_q1q2_score": 0.4881901560052786}}
{"text": "#include <vtkFloatArray.h>\n#include <vtkInformation.h>\n#include <vtkMath.h>\n#include <vtkPointData.h>\n#include <vtkPoints.h>\n#include <vtkPolyData.h>\n#include <vtkRansacPlaneModel.h>\n#include <vtkSmartPointer.h>\n#include <vtkUnsignedIntArray.h>\n\n#include <iostream>\n#include <iomanip>\n\n#include <Eigen/Dense>\n\n\nint main(int argc, char* argv[])\n{\n    srand((unsigned int) time(0));\n\n    int N = 1000;\n    int N_OUTLIERS = 10;\n    float noise_sigma = 0.1;\n    Eigen::MatrixXf angles = Eigen::MatrixXf::Random(1, N);\n    angles.array() += 1;\n    angles.array() *= 3.1415;\n    Eigen::MatrixXf radius = Eigen::MatrixXf::Random(1, N);\n    radius.array() *= 10;\n    Eigen::Matrix3Xf pts(3, N);\n\n    // add noise on z\n    Eigen::MatrixXf noisy_z = Eigen::MatrixXf::Random(1, N);\n    noisy_z.array() *= noise_sigma;\n\n    // add outliers\n    for (int i = N - N_OUTLIERS; i < N; ++i)\n    {\n        auto v = noisy_z(i);\n        if (v < 0) v = 10 * v - 5;\n        else v = 10 * v + 5;\n        noisy_z(i) = v;\n    }\n    pts << radius.array().cwiseProduct(angles.array().cos()), radius.array().cwiseProduct(angles.array().sin()), noisy_z;\n\n    // transform the initial plane\n    float initial_rot_X = static_cast<float>(std::rand() % 100) / 10.0;\n    float initial_rot_Y = static_cast<float>(std::rand() % 100) / 10.0;\n    float initial_z_translation = -static_cast<float>(std::rand() % 100) / 10.0;\n    Eigen::AngleAxisf rotX(vtkMath::RadiansFromDegrees(initial_rot_X), Eigen::Vector3f::UnitX());\n    Eigen::AngleAxisf rotY(vtkMath::RadiansFromDegrees(initial_rot_Y), Eigen::Vector3f::UnitY());\n    Eigen::Translation3f trans(0, 0, initial_z_translation);\n    Eigen::Affine3f T = rotX * rotY * trans;\n    pts = T * pts;\n\n    // build polydata\n    auto polydata = vtkSmartPointer<vtkPolyData>::New();\n    auto array = vtkSmartPointer<vtkFloatArray>::New();\n    array->SetNumberOfComponents(3);\n    array->SetNumberOfTuples(N);\n    float temp_f[3];\n    for (int i = 0; i < N; ++i)\n    {\n        temp_f[0] = pts.col(i).x();\n        temp_f[1] = pts.col(i).y();\n        temp_f[2] = pts.col(i).z();\n        array->SetTuple(i, temp_f);\n    }\n    auto new_points = vtkSmartPointer<vtkPoints>::New();\n    new_points->SetData(array);\n    polydata->SetPoints(new_points);\n\n    // apply filter ransac plane model\n    auto filter = vtkSmartPointer<vtkRansacPlaneModel>::New();\n    filter->SetAlignOutput(1);\n    filter->SetInputData(polydata);\n    filter->Update();\n    auto output = filter->GetOutput();\n\n    // check that the points are correctly aligned to XY\n    double temp_d[3];\n    double max_z_threshold = 1.0;       // threshold on z for points with small noise\n    for (int i = 0; i < N - N_OUTLIERS; ++i)\n    {\n        output->GetPoint(i, temp_d);\n        if (std::abs(temp_d[2]) > max_z_threshold)\n        {\n            std::cout << \"Error: point \" << i << \" has z = \" << temp_d[2] << std::endl;\n            return -1;\n        }\n\n    }\n\n    // check that outliers are detected as outliers\n    vtkSmartPointer<vtkUnsignedIntArray> inliers_array = \n    vtkUnsignedIntArray::SafeDownCast(output->GetPointData()->GetArray(\"ransac_plane_inliers\"));\n    for (int i =  N - N_OUTLIERS; i < N; ++i)\n    {\n        if (inliers_array->GetValue(i) == 1)\n        {\n            std::cout << \"Error: Point \" << i << \" should be classified as outliers\" << std::endl;\n            return -1;\n        }\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "5a7a7e20fa06c087a84647cdfcae66b9c745fb13", "size": 3391, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "VelodyneHDL/Testing/TestRansacPlaneModel.cxx", "max_stars_repo_name": "zhihua-wang/VeloView", "max_stars_repo_head_hexsha": "609d3e4c0cf722c512f4b0b2a615208557bb7757", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-10-28T07:02:34.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-28T07:03:50.000Z", "max_issues_repo_path": "VelodyneHDL/Testing/TestRansacPlaneModel.cxx", "max_issues_repo_name": "zactodd/VeloView", "max_issues_repo_head_hexsha": "e0bd72a32464a9f62385ac5ce25df33580ed3cc2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-06-17T13:25:51.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-21T21:26:11.000Z", "max_forks_repo_path": "VelodyneHDL/Testing/TestRansacPlaneModel.cxx", "max_forks_repo_name": "zactodd/VeloView", "max_forks_repo_head_hexsha": "e0bd72a32464a9f62385ac5ce25df33580ed3cc2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-08T11:28:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-08T11:28:59.000Z", "avg_line_length": 31.691588785, "max_line_length": 121, "alphanum_fraction": 0.6125036862, "num_tokens": 993, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746407, "lm_q2_score": 0.6442250996557036, "lm_q1q2_score": 0.48819015435293667}}
{"text": "/*\n\tCopyright 2005-2007 Adobe Systems Incorporated\n\tDistributed under the MIT License (see accompanying file LICENSE_1_0_0.txt\n\tor a copy at http://stlab.adobe.com/licenses.html)\n*/\n\n/*************************************************************************************************/\n\n#include <adobe/config.hpp>\n\n#define BOOST_TEST_MAIN\n\n#include <boost/test/unit_test.hpp>\n\n#include <adobe/enum_ops.hpp>\n\n\nenum Number {\n    num_neg_one=-1,\n    num_0 = 0,\n    num_1 = 1,\n    num_2 = 2,\n    num_3 = 3,\n    num_4 = 4,\n    num_5 = 5,\n    num_6 = 6,\n    num_7 = 7\n};\n\nADOBE_DEFINE_BITSET_OPS(Number)\n\nBOOST_AUTO_TEST_CASE(enum_bitset_ops) {\n    Number x;\n\n// or\n    x = num_1 | num_2;\n    BOOST_CHECK(x == 3);\n\n// and\n    x = num_3 & num_1;\n    BOOST_CHECK(x == 1);\n\n// xor\n    x = num_2 ^ num_3;\n    BOOST_CHECK(x == 1);\n\n// not\n    x = num_7 & (~ num_5);\n    BOOST_CHECK(x == 2);\n\n// or=\n    x = num_1;\n    x |= num_2;\n    BOOST_CHECK(x == 3); \n\n// and=\n    x = num_3;\n    x &= num_1;\n    BOOST_CHECK(x == 1);\n\n// xor\n    x = num_2;\n    x ^= num_3;\n    BOOST_CHECK(x == 1);\n}\n\n\nADOBE_DEFINE_ARITHMETIC_OPS(Number)\nBOOST_AUTO_TEST_CASE(enum_arith_ops) {\n    Number x;\n\n// +\n    x = num_1 + num_2;\n    BOOST_CHECK(x == 3);\n\n// -\n    x = num_3 - num_1;\n    BOOST_CHECK(x == 2);\n\n// - (unary)\n    x = -num_neg_one;\n    BOOST_CHECK(x == 1);     \n\n// *\n    x = num_2 * num_3;\n    BOOST_CHECK(x == 6);\n\n// /\n    x = num_5 / num_2;\n    BOOST_CHECK(x == 2); \n\n// %\n    x = num_5 % num_2;\n    BOOST_CHECK(x == 1); \n\n// +=\n    x = num_1;\n    x+= num_2;\n    BOOST_CHECK(x == 3);\n\n// -=\n    x = num_3;\n    x -= num_1;\n    BOOST_CHECK(x == 2);\n\n// *=\n    x = num_2;\n    x *= num_3;\n    BOOST_CHECK(x == 6);\n\n// /=\n    x = num_5;\n    x /= num_2;\n    BOOST_CHECK(x == 2); \n\n// %=\n    x = num_5;\n    x %= num_2;\n    BOOST_CHECK(x == 1); \n}\n", "meta": {"hexsha": "95e351db1bc63ed7a30b287923d4eb6dfd8b8848", "size": 1821, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit_tests/enum_ops/enum_ops_test.cpp", "max_stars_repo_name": "brycelelbach/asl", "max_stars_repo_head_hexsha": "df0d271f6c67fbb944039a9455c4eb69ae6df141", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2015-10-02T17:31:56.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-17T00:54:15.000Z", "max_issues_repo_path": "test/unit_tests/enum_ops/enum_ops_test.cpp", "max_issues_repo_name": "brycelelbach/asl", "max_issues_repo_head_hexsha": "df0d271f6c67fbb944039a9455c4eb69ae6df141", "max_issues_repo_licenses": ["MIT"], "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/unit_tests/enum_ops/enum_ops_test.cpp", "max_forks_repo_name": "brycelelbach/asl", "max_forks_repo_head_hexsha": "df0d271f6c67fbb944039a9455c4eb69ae6df141", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.0495867769, "max_line_length": 99, "alphanum_fraction": 0.5030203185, "num_tokens": 623, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.757794360334681, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.4881901421288997}}
{"text": "// Author: Francesco Regazzoni - MOX, Politecnico di Milano\n// Email:  francesco.regazzoni@polimi.it\n// Date:   2020\n\n#ifndef MODEL_RDQ20_SE_HPP\n#define MODEL_RDQ20_SE_HPP\n\n#include <vector>\n\n#include <Eigen/Dense>\n\n#include \"sarcomere.hpp\"\n\nclass model_RDQ20_SE : public sarcomere {\n\n  //    Class implementing the spatially-explicit ODE model (SE-ODE) for\n  //    cardiomyocytes force generation presented in [1, 2].\n  //\n  //    References:\n  //\n  //    [1] F. Regazzoni \"Mathematical modeling and Machine Learning for the\n  //        numerical simulation of cardiac electromechanics\", PhD Thesis -\n  //        Politecnico di Milano (2020)\n  //        http://hdl.handle.net/10589/152617\n  //    [2] F. Regazzoni, L. Dede', A. Quarteroni \"Biophysically detailed\n  //        mathematical models of multiscale cardiac active mechanics\",\n  //        PLOS Computational Biology (2020)\n  //        https://doi.org/10.1371/journal.pcbi.1008294\n\npublic:\n  // Constructor.\n  model_RDQ20_SE(\n      std::string parameters_file =\n          \"../../params/params_RDQ20-SE_human_body-temperature.json\");\n\n  // Solve one time step, updating the state passed as reference.\n  void solve_time_step(std::vector<double> &state, const double &calcium,\n                       const double &sarcomere_length, const double &dSL_dt,\n                       const double &dt);\n\n  // Compute the active tension.\n  double get_active_tension(const std::vector<double> &state,\n                            const double &sarcomere_length);\n\n  // Compute the permissivity.\n  double get_permissivity(const std::vector<double> &state);\n\n  // Compute the active stiffness.\n  double get_active_stiffness(const std::vector<double> &state,\n                              const double &sarcomere_length);\n\nprivate:\n  // Allocate memory to store variables\n  void allocate_variables();\n\n  // Initialize transition rates.\n  void initialize_rates();\n\n  // Deserialize the model state into state_RU and state_XB.\n  void deserialize_state(const std::vector<double> &state);\n\n  // Serialize the model state from state_RU and state_XB.\n  void serialize_state(std::vector<double> &state);\n\n  // Update the RU transition rates.\n  void RU_update_rates(const double &calcium, const double &sarcomere_length);\n\n  // Update the RU state variables.\n  void RU_update_state(const double &dt);\n\n  // Update the XB state variables.\n  void XB_update_state(const double &sarcomere_length, const double &dSL_dt,\n                       const double &dt);\n\n  // Coordinate of the i-th RU.\n  inline double y_j(const unsigned int &i_RU) {\n    return prm_LA * (i_RU + 0.5) / prm_n_RU;\n  }\n\n  // Coordinate of the left end of the AF.\n  inline double yLA(const double &sarcomere_length) {\n    return 2 * prm_LA - sarcomere_length;\n  }\n\n  // First coordinate of the MF.\n  inline double yM0(const double &sarcomere_length) {\n    return (2 * prm_LA - sarcomere_length + prm_LB) * 0.5;\n  }\n\n  // Second coordinate of the MF.\n  inline double yM1(const double &sarcomere_length) {\n    return (2 * prm_LA - sarcomere_length + prm_LM) * 0.5;\n  }\n\n  // Smoothed indicator function of the MF.\n  inline double ChiMF(const double &sarcomere_length,\n                      const unsigned int &i_RU) {\n    return 0.5 * std::tanh((y_j(i_RU) - yM0(sarcomere_length)) / prm_Lsmooth) +\n           0.5 * std::tanh(-(y_j(i_RU) - yM1(sarcomere_length)) / prm_Lsmooth);\n  }\n\n  // Smoothed indicator function of the single-overlap region.\n  inline double ChiSF(const double &sarcomere_length,\n                      const unsigned int &i_RU) {\n    return 0.5 +\n           0.5 * std::tanh((y_j(i_RU) - yLA(sarcomere_length)) / prm_Lsmooth);\n  }\n\n  // Model Parameters.\n  unsigned int prm_n_RU; // [-]\n  double prm_LA;         // [micro m]\n  double prm_LM;         // [micro m]\n  double prm_LB;         // [micro m]\n  double prm_SL0;        // [micro m]\n  double prm_Lsmooth;    // [micro m]\n  double prm_Q;          // [-]\n  double prm_Kd0;        // [micro M]\n  double prm_alphaKd;    // [micro M / micro m]\n  double prm_mu;         // [-]\n  double prm_gamma;      // [-]\n  double prm_Koff;       // [s^-1]\n  double prm_Kbasic;     // [s^-1]\n  double prm_r0;         // [s^-1]\n  double prm_alpha;      // [-]\n  double prm_mu0_fP;     // [s^-1]\n  double prm_mu1_fP;     // [s^-1]\n  double prm_a_XB;       // [kPa]\n\n  // Numerical Parameters.\n  double prm_time_step_update_RU_state =\n      2.5e-5; // Time step used to update the RU state. [s]\n\n  // Additional variables.\n  std::vector<std::array<std::array<std::array<double, 4>, 4>, 4>>\n      state_RU;                                // State variables of RU.\n  std::vector<std::array<double, 4>> state_XB; // State variables of XB.\n\n  std::vector<\n      std::array<std::array<std::array<std::array<double, 4>, 4>, 4>, 4>>\n      rates_RU; // RU rates.\n\n  int permissivity_of_state[4] = {0, 0, 1,\n                                  1}; // Permissivity state (0 = N, 1 = P)\n                                      // associated with the basic RU states.\n\n  std::vector<\n      std::array<std::array<std::array<std::array<double, 4>, 4>, 4>, 4>>\n      flux_RU_L; // Probability flux of left-ward RUs of the triplets.\n  std::vector<\n      std::array<std::array<std::array<std::array<double, 4>, 4>, 4>, 4>>\n      flux_RU_C; // Probability flux of central RUs of the triplets.\n  std::vector<\n      std::array<std::array<std::array<std::array<double, 4>, 4>, 4>, 4>>\n      flux_RU_R; // Probability flux of right-ward RUs of the triplets.\n\n  Eigen::Matrix<double, 4, 4> XB_A;   // Matrix defining the local XB system.\n  Eigen::Matrix<double, 4, 1> XB_rhs; // Right-hand side of the local XB system.\n  Eigen::Matrix<double, 4, 1>\n      XB_sol; // Vector used to store the solution of the local XB system.\n\n  unsigned int n_states_RU; // Number of RU states.\n  unsigned int n_states_XB; // Number of XB states.\n  unsigned int i_RU;        // Index of regulatory_unit.\n  unsigned int RU_L;        // Index of left regulatory unit.\n  unsigned int RU_C;        // Index of central regulatory unit.\n  unsigned int RU_R;        // Index of right regulatory unit.\n  unsigned int RU_new;      // Index of regulatory unit (new state).\n  unsigned int RU_dummy;    // Index of regulatory unit external to the\n                            // considered triplet.\n  unsigned int i_XB;        // Index of XB state.\n};\n\n#endif /* MODEL_RDQ20_SE_HPP */", "meta": {"hexsha": "a5222ca730884550c27c62c384c8173377bf2a9b", "size": 6379, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "models_cpp/model_RDQ20_SE.hpp", "max_stars_repo_name": "FrancescoRegazzoni/cardiac-activation", "max_stars_repo_head_hexsha": "26f05df28891df7b3c69f16bb136cdced6b63c4d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-17T00:26:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-17T00:26:28.000Z", "max_issues_repo_path": "models_cpp/model_RDQ20_SE.hpp", "max_issues_repo_name": "FrancescoRegazzoni/cardiac-activation", "max_issues_repo_head_hexsha": "26f05df28891df7b3c69f16bb136cdced6b63c4d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models_cpp/model_RDQ20_SE.hpp", "max_forks_repo_name": "FrancescoRegazzoni/cardiac-activation", "max_forks_repo_head_hexsha": "26f05df28891df7b3c69f16bb136cdced6b63c4d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.8728323699, "max_line_length": 80, "alphanum_fraction": 0.633798401, "num_tokens": 1753, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.488153049314892}}
{"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_SCALAR_ELLIE_HPP_INCLUDED\n#define NT2_ELLIPTIC_FUNCTIONS_SCALAR_ELLIE_HPP_INCLUDED\n#include <nt2/elliptic/functions/ellie.hpp>\n#include <boost/math/special_functions.hpp>\n#include <nt2/include/functions/scalar/is_ltz.hpp>\n#include <nt2/include/functions/scalar/sin.hpp>\n#include <nt2/include/functions/scalar/is_eqz.hpp>\n#include <nt2/include/functions/scalar/abs.hpp>\n#include <nt2/include/functions/scalar/sin.hpp>\n#include <nt2/include/functions/scalar/sqr.hpp>\n#include <nt2/include/functions/scalar/sqrt.hpp>\n#include <nt2/include/functions/scalar/oneminus.hpp>\n#include <nt2/include/functions/scalar/oneplus.hpp>\n#include <nt2/include/functions/scalar/tan.hpp>\n#include <nt2/include/functions/scalar/atan.hpp>\n#include <nt2/include/functions/scalar/average.hpp>\n#include <nt2/include/functions/scalar/ellpe.hpp>\n#include <nt2/include/functions/scalar/ellpk.hpp>\n#include <nt2/include/functions/scalar/ceil.hpp>\n#include <nt2/sdk/error/policies.hpp>\n#include <nt2/include/constants/one.hpp>\n#include <nt2/include/constants/nan.hpp>\n#include <nt2/include/constants/pi.hpp>\n#include <nt2/include/constants/pio_2.hpp>\n#include <nt2/include/constants/eps.hpp>\n\nnamespace nt2 { namespace ext\n{\n  NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::ellie_, tag::cpu_\n                            , (A0)\n                            , (scalar_< arithmetic_<A0> >)\n                              (scalar_< arithmetic_<A0> >)\n                            )\n  {\n\n    typedef typename boost::dispatch::meta::as_floating<A0>::type result_type;\n\n    NT2_FUNCTOR_CALL_REPEAT(2)\n    {\n      return nt2::ellie(result_type(a0), result_type(a1));\n    }\n  };\n\n  NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::ellie_, tag::cpu_\n                            , (A0)\n                            , (scalar_< double_<A0> >)\n                              (scalar_< double_<A0> >)\n                            )\n  {\n\n    typedef typename boost::dispatch::meta::as_floating<A0>::type result_type;\n\n    NT2_FUNCTOR_CALL_REPEAT(2)\n    {\n      typedef result_type type;\n      if (a1>nt2::One<A0>()||(nt2::is_ltz(a1))) return Nan<type>();\n      if (nt2::is_eqz(a1))  return type(a0);\n      return boost::math::ellint_2(nt2::sqrt(type(a1)), type(a0), nt2_policy());\n    }\n  };\n\n  NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::ellie_, tag::cpu_\n                            , (A0)\n                            , (scalar_< single_<A0> >)\n                              (scalar_< single_<A0> >)\n                            )\n  {\n    typedef A0 result_type;\n    NT2_FUNCTOR_CALL_REPEAT(2)\n    {\n      typedef result_type type;\n      if (a1>nt2::One<A0>()||(nt2::is_ltz(a1))) return nt2::Nan<type>();\n      else if (nt2::is_eqz(a1))\n        return a0;\n      else if (a1 == nt2::One<A0>())\n        return nt2::sin(a0);\n      else\n      {\n        type lphi = nt2::abs(a0);\n        type m   =  a1;\n        type a = nt2::One<type>();\n        type b = nt2::sqrt(nt2::oneminus(m));\n        type c = nt2::sqrt(m);\n        type d = nt2::One<type>();\n        type e = nt2::Zero<type>();\n        type t = nt2::tan( lphi );\n        int mod = toint((lphi+nt2::Pio_2<type>())/nt2::Pi<type>());\n        while( nt2::abs(c) > nt2::Eps<type>()*nt2::abs(a) )\n        {\n          type temp = b/a;\n          lphi = lphi + nt2::atan(t*temp) + mod * nt2::Pi<type>();\n          mod = nt2::toint((lphi+nt2::Pio_2<type>())/Pi<type>());\n          t *= nt2::oneplus(temp)/( nt2::oneminus(temp * nt2::sqr(t)));\n          c = nt2::average(a,-b);\n          temp = nt2::sqrt(a*b);\n          a = nt2::average(a,b);\n          b = temp;\n          d += d;\n          e += c*nt2::sin(lphi);\n        }\n\n        b = nt2::oneminus(m);\n        type temp = nt2::ellpe(b)/nt2::ellpk(b);\n        temp *= (nt2::atan(t) + mod * nt2::Pi<type>())/(d * a);\n        temp += e;\n        if(nt2::is_ltz(a0))  temp = -temp;\n        return temp ;\n      }\n      }\n  };\n} }\n\n\n#endif\n", "meta": {"hexsha": "b11df964808fa7e300dedec583800c114404eea1", "size": 4388, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/elliptic/include/nt2/elliptic/functions/scalar/ellie.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/elliptic/include/nt2/elliptic/functions/scalar/ellie.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/elliptic/include/nt2/elliptic/functions/scalar/ellie.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": 35.674796748, "max_line_length": 80, "alphanum_fraction": 0.5492251595, "num_tokens": 1215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387914176259, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.48815304433766293}}
{"text": "#ifndef UTIL_RANDOM_HPP\n#define UTIL_RANDOM_HPP\n\n#include <boost/random/uniform_real.hpp>\n#include <boost/random/normal_distribution.hpp>\n\nnamespace util{\n\ntemplate <class RNG>\ninline double random_01(RNG &rng)\n{\n    static boost::uniform_real<double> dist(0.0, 1.0);\n    return dist(rng);\n}\n\ntemplate <class RNG>\ninline int random_int(RNG &rng, int N)\n{\n    return static_cast<int>( N * random_01(rng));\n}\n\ntemplate <class RNG>\ninline double random_gauss(RNG &rng, double sigma=1.0)\n{\n    static boost::normal_distribution<double> dist(0.0, 1.0);\n    return sigma*dist(rng);\n}\n\n\n}\n\n#endif\n", "meta": {"hexsha": "c5fb9ebb0d10f30f8b8143049de46a09fabcfe74", "size": 590, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/random.hpp", "max_stars_repo_name": "yomichi/cpp-utils", "max_stars_repo_head_hexsha": "6068e6d0afd2e031aea8fa44fe8ec7d18137c3e6", "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/random.hpp", "max_issues_repo_name": "yomichi/cpp-utils", "max_issues_repo_head_hexsha": "6068e6d0afd2e031aea8fa44fe8ec7d18137c3e6", "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/random.hpp", "max_forks_repo_name": "yomichi/cpp-utils", "max_forks_repo_head_hexsha": "6068e6d0afd2e031aea8fa44fe8ec7d18137c3e6", "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": 17.8787878788, "max_line_length": 61, "alphanum_fraction": 0.7203389831, "num_tokens": 157, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.488152658821328}}
{"text": "/*\n   For more information, please see: http://software.sci.utah.edu\n\n   The MIT License\n\n   Copyright (c) 2020 Scientific Computing and Imaging Institute,\n   University of Utah.\n\n   Permission is hereby granted, free of charge, to any person obtaining a\n   copy of this software and associated documentation files (the \"Software\"),\n   to deal in the Software without restriction, including without limitation\n   the rights to use, copy, modify, merge, publish, distribute, sublicense,\n   and/or sell copies of the Software, and to permit persons to whom the\n   Software is furnished to do so, subject to the following conditions:\n\n   The above copyright notice and this permission notice shall be included\n   in all copies or substantial portions of the Software.\n\n   THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n   DEALINGS IN THE SOFTWARE.\n*/\n\n\n#include <Testing/Utils/SCIRunUnitTests.h>\n\n#include <fstream>\n#include <boost/filesystem.hpp>\n#include <Core/Algorithms/Math/LinearSystem/SolveLinearSystemAlgo.h>\n#include <Core/Algorithms/DataIO/ReadMatrix.h>\n#include <Core/Algorithms/DataIO/WriteMatrix.h>\n#include <Core/Datatypes/DenseMatrix.h>\n#include <Core/Datatypes/DenseColumnMatrix.h>\n#include <Core/Datatypes/SparseRowMatrix.h>\n#include <Core/Datatypes/MatrixComparison.h>\n#include <Core/Datatypes/MatrixTypeConversions.h>\n#include <Core/Datatypes/MatrixIO.h>\n#include <Core/Algorithms/Base/AlgorithmVariableNames.h>\n#include <Testing/Utils/MatrixTestUtilities.h>\n\nusing namespace SCIRun::Core::Datatypes;\nusing namespace SCIRun::Core::Algorithms::Math;\nusing namespace SCIRun::Core::Algorithms;\nusing namespace SCIRun::Core::Algorithms::DataIO;\nusing namespace SCIRun::TestUtils;\nusing namespace SCIRun;\nusing namespace ::testing;\n\nvoid CanSolveDarrellWithMethod(const std::string& method, double solutionError)\n{\n  auto Afile = TestResources::rootDir() / \"CGDarrell\" / \"A.mat\";\n  auto rhsFile = TestResources::rootDir() / \"CGDarrell\" / \"RHS.mat\";\n  if (!boost::filesystem::exists(Afile) || !boost::filesystem::exists(rhsFile))\n  {\n    FAIL() << \"TODO: Issue #142 will standardize these file locations other than being on Dan's hard drive.\" << std::endl\n      << \"Once that issue is done however, this will be a user setup error.\" << std::endl;\n    return;\n  }\n\n  ReadMatrixAlgorithm reader;\n  SparseRowMatrixHandle A;\n  {\n    ScopedTimer t(\"reading sparse matrix\");\n    A = castMatrix::toSparse(reader.run(Afile.string()));\n  }\n  ASSERT_TRUE(A.get() != nullptr);\n  EXPECT_EQ(428931, A->nrows());\n  EXPECT_EQ(428931, A->ncols());\n\n  DenseMatrixHandle rhs;\n  {\n    ScopedTimer t(\"reading rhs\");\n    rhs = castMatrix::toDense(reader.run(rhsFile.string()));\n  }\n  ASSERT_TRUE(rhs.get() != nullptr);\n  EXPECT_EQ(428931, rhs->nrows());\n  EXPECT_EQ(1, rhs->ncols());\n\n  DenseColumnMatrixHandle x0;\n  ASSERT_FALSE(x0); // algo object will initialize x0 to the zero vector\n\n  SolveLinearSystemAlgo algo;\n  algo.set(Variables::MaxIterations, 500);\n  algo.set(Variables::TargetError, 7e-4);\n  algo.setOption(Variables::Method, method);\n  algo.setUpdaterFunc([](double x) {});\n\n  DenseColumnMatrixHandle solution;\n  {\n    ScopedTimer t(\"Running solver\");\n    ASSERT_TRUE(algo.run(A, convertMatrix::toColumn(rhs), x0, solution));\n  }\n  ASSERT_TRUE(solution.get() != nullptr);\n  EXPECT_EQ(428931, solution->nrows());\n  EXPECT_EQ(1, solution->ncols());\n\n  auto scirun4solutionFile = TestResources::rootDir() / \"CGDarrell\" / (\"dan_sol_\" + method + \".mat\");\n  auto scirun4solution = reader.run(scirun4solutionFile.string());\n  ASSERT_TRUE(scirun4solution.get() != nullptr);\n  DenseColumnMatrixHandle expected = convertMatrix::toColumn(scirun4solution);\n\n  EXPECT_COLUMN_MATRIX_EQ_BY_TWO_NORM(*expected, *solution, solutionError);\n\n  WriteMatrixAlgorithm writer;\n  auto portedSolutionFile = TestResources::rootDir() / \"CGDarrell\" / (\"portedSolution_\" + method + \".txt\");\n  writer.run(solution, portedSolutionFile.string());\n\n  auto diff = *expected - *solution;\n  auto maxDiff = diff.maxCoeff();\n  std::cout << \"max diff is: \" << maxDiff << std::endl;\n}\n\n/// todo: switch these disabled tests to nightly mode. They are overly long for normal continuous builds.\n\nTEST(SolveLinearSystemTests, DISABLED_CanSolveDarrell_CG)\n{\n  double solutionError;\n  /// @todo: investigate this significant difference\n#ifdef WIN32\n  solutionError = 0.15;\n#else\n  solutionError = 0.23;\n#endif\n  CanSolveDarrellWithMethod(\"cg\", solutionError);\n}\n\nTEST(SolveLinearSystemTests, DISABLED_CanSolveDarrell_BICG)\n{\n  double solutionError = 0.001;\n  CanSolveDarrellWithMethod(\"bicg\", solutionError);\n}\n\nTEST(SolveLinearSystemTests, DISABLED_CanSolveDarrell_Jacobi)\n{\n  /// @todo: doesn't converge for this system. Problem?\n  double solutionError = 105;\n  CanSolveDarrellWithMethod(\"jacobi\", solutionError);\n}\n\nTEST(SolveLinearSystemTests, DISABLED_CanSolveDarrell_MINRES)\n{\n  /// @todo: converges but not as accurate.\n  double solutionError = 2.4;\n  CanSolveDarrellWithMethod(\"minres\", solutionError);\n}\n", "meta": {"hexsha": "a82b32d5328ba5357707c5ee0633817403e5e240", "size": 5374, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/Core/Algorithms/Math/Tests/SolveLinearSystemAlgoTests.cc", "max_stars_repo_name": "Haydelj/SCIRun", "max_stars_repo_head_hexsha": "f7ee04d85349b946224dbff183438663e54b9413", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 92.0, "max_stars_repo_stars_event_min_datetime": "2015-02-09T22:42:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T09:14:50.000Z", "max_issues_repo_path": "src/Core/Algorithms/Math/Tests/SolveLinearSystemAlgoTests.cc", "max_issues_repo_name": "Haydelj/SCIRun", "max_issues_repo_head_hexsha": "f7ee04d85349b946224dbff183438663e54b9413", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1618.0, "max_issues_repo_issues_event_min_datetime": "2015-01-05T19:39:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T20:28:45.000Z", "max_forks_repo_path": "src/Core/Algorithms/Math/Tests/SolveLinearSystemAlgoTests.cc", "max_forks_repo_name": "Haydelj/SCIRun", "max_forks_repo_head_hexsha": "f7ee04d85349b946224dbff183438663e54b9413", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 64.0, "max_forks_repo_forks_event_min_datetime": "2015-02-20T17:51:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-19T07:08:08.000Z", "avg_line_length": 35.8266666667, "max_line_length": 121, "alphanum_fraction": 0.7469296613, "num_tokens": 1369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.766293653760418, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.4881526550602747}}
{"text": "// boost\\math\\distributions\\non_central_chi_squared.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_CHI_SQUARE_HPP\n#define BOOST_MATH_SPECIAL_NON_CENTRAL_CHI_SQUARE_HPP\n\n#include <boost/math/distributions/fwd.hpp>\n#include <boost/math/special_functions/gamma.hpp> // for incomplete gamma. gamma_q\n#include <boost/math/special_functions/bessel.hpp> // for cyl_bessel_i\n#include <boost/math/special_functions/round.hpp> // for iround\n#include <boost/math/distributions/complement.hpp> // complements\n#include <boost/math/distributions/chi_squared.hpp> // central distribution\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/distributions/detail/generic_mode.hpp>\n#include <boost/math/distributions/detail/generic_quantile.hpp>\n\nnamespace boost\n{\n   namespace math\n   {\n\n      template <class RealType, class Policy>\n      class non_central_chi_squared_distribution;\n\n      namespace detail{\n\n         template <class T, class Policy>\n         T non_central_chi_square_q(T x, T f, T theta, const Policy& pol, T init_sum = 0)\n         {\n            //\n            // Computes the complement of the Non-Central Chi-Square\n            // Distribution CDF by summing a weighted sum of complements\n            // of the central-distributions.  The weighting factor is\n            // a Poisson Distribution.\n            //\n            // This is an application of the technique described in:\n            //\n            // Computing discrete mixtures of continuous\n            // distributions: noncentral chisquare, noncentral t\n            // and the distribution of the square of the sample\n            // multiple correlation coeficient.\n            // D. Benton, K. Krishnamoorthy.\n            // Computational Statistics & Data Analysis 43 (2003) 249 - 267\n            //\n            BOOST_MATH_STD_USING\n\n            // Special case:\n            if(x == 0)\n               return 1;\n\n            //\n            // Initialize the variables we'll be using:\n            //\n            T lambda = theta / 2;\n            T del = f / 2;\n            T y = x / 2;\n            boost::uintmax_t max_iter = policies::get_max_series_iterations<Policy>();\n            T errtol = boost::math::policies::get_epsilon<T, Policy>();\n            T sum = init_sum;\n            //\n            // k is the starting location for iteration, we'll\n            // move both forwards and backwards from this point.\n            // k is chosen as the peek of the Poisson weights, which\n            // will occur *before* the largest term.\n            //\n            int k = iround(lambda, pol);\n            // Forwards and backwards Poisson weights:\n            T poisf = boost::math::gamma_p_derivative(1 + k, lambda, pol);\n            T poisb = poisf * k / lambda;\n            // Initial forwards central chi squared term:\n            T gamf = boost::math::gamma_q(del + k, y, pol);\n            // Forwards and backwards recursion terms on the central chi squared:\n            T xtermf = boost::math::gamma_p_derivative(del + 1 + k, y, pol);\n            T xtermb = xtermf * (del + k) / y;\n            // Initial backwards central chi squared term:\n            T gamb = gamf - xtermb;\n\n            //\n            // Forwards iteration first, this is the\n            // stable direction for the gamma function\n            // recurrences:\n            //\n            int i;\n            for(i = k; static_cast<boost::uintmax_t>(i-k) < max_iter; ++i)\n            {\n               T term = poisf * gamf;\n               sum += term;\n               poisf *= lambda / (i + 1);\n               gamf += xtermf;\n               xtermf *= y / (del + i + 1);\n               if(((sum == 0) || (fabs(term / sum) < errtol)) && (term >= poisf * gamf))\n                  break;\n            }\n            //Error check:\n            if(static_cast<boost::uintmax_t>(i-k) >= max_iter)\n               policies::raise_evaluation_error(\n                  \"cdf(non_central_chi_squared_distribution<%1%>, %1%)\",\n                  \"Series did not converge, closest value was %1%\", sum, pol);\n            //\n            // Now backwards iteration: the gamma\n            // function recurrences are unstable in this\n            // direction, we rely on the terms deminishing in size\n            // faster than we introduce cancellation errors.\n            // For this reason it's very important that we start\n            // *before* the largest term so that backwards iteration\n            // is strictly converging.\n            //\n            for(i = k - 1; i >= 0; --i)\n            {\n               T term = poisb * gamb;\n               sum += term;\n               poisb *= i / lambda;\n               xtermb *= (del + i) / y;\n               gamb -= xtermb;\n               if((sum == 0) || (fabs(term / sum) < errtol))\n                  break;\n            }\n\n            return sum;\n         }\n\n         template <class T, class Policy>\n         T non_central_chi_square_p_ding(T x, T f, T theta, const Policy& pol, T init_sum = 0)\n         {\n            //\n            // This is an implementation of:\n            //\n            // Algorithm AS 275:\n            // Computing the Non-Central #2 Distribution Function\n            // Cherng G. Ding\n            // Applied Statistics, Vol. 41, No. 2. (1992), pp. 478-482.\n            //\n            // This uses a stable forward iteration to sum the\n            // CDF, unfortunately this can not be used for large\n            // values of the non-centrality parameter because:\n            // * The first term may underfow to zero.\n            // * We may need an extra-ordinary number of terms\n            //   before we reach the first *significant* term.\n            //\n            BOOST_MATH_STD_USING\n            // Special case:\n            if(x == 0)\n               return 0;\n            T tk = boost::math::gamma_p_derivative(f/2 + 1, x/2, pol);\n            T lambda = theta / 2;\n            T vk = exp(-lambda);\n            T uk = vk;\n            T sum = init_sum + tk * vk;\n            if(sum == 0)\n               return sum;\n\n            boost::uintmax_t max_iter = policies::get_max_series_iterations<Policy>();\n            T errtol = boost::math::policies::get_epsilon<T, Policy>();\n\n            int i;\n            T lterm(0), term(0);\n            for(i = 1; static_cast<boost::uintmax_t>(i) < max_iter; ++i)\n            {\n               tk = tk * x / (f + 2 * i);\n               uk = uk * lambda / i;\n               vk = vk + uk;\n               lterm = term;\n               term = vk * tk;\n               sum += term;\n               if((fabs(term / sum) < errtol) && (term <= lterm))\n                  break;\n            }\n            //Error check:\n            if(static_cast<boost::uintmax_t>(i) >= max_iter)\n               policies::raise_evaluation_error(\n                  \"cdf(non_central_chi_squared_distribution<%1%>, %1%)\",\n                  \"Series did not converge, closest value was %1%\", sum, pol);\n            return sum;\n         }\n\n\n         template <class T, class Policy>\n         T non_central_chi_square_p(T y, T n, T lambda, const Policy& pol, T init_sum)\n         {\n            //\n            // This is taken more or less directly from:\n            //\n            // Computing discrete mixtures of continuous\n            // distributions: noncentral chisquare, noncentral t\n            // and the distribution of the square of the sample\n            // multiple correlation coeficient.\n            // D. Benton, K. Krishnamoorthy.\n            // Computational Statistics & Data Analysis 43 (2003) 249 - 267\n            //\n            // We're summing a Poisson weighting term multiplied by\n            // a central chi squared distribution.\n            //\n            BOOST_MATH_STD_USING\n            // Special case:\n            if(y == 0)\n               return 0;\n            boost::uintmax_t max_iter = policies::get_max_series_iterations<Policy>();\n            T errtol = boost::math::policies::get_epsilon<T, Policy>();\n            T errorf(0), errorb(0);\n\n            T x = y / 2;\n            T del = lambda / 2;\n            //\n            // Starting location for the iteration, we'll iterate\n            // both forwards and backwards from this point.  The\n            // location chosen is the maximum of the Poisson weight\n            // function, which ocurrs *after* the largest term in the\n            // sum.\n            //\n            int k = iround(del, pol);\n            T a = n / 2 + k;\n            // Central chi squared term for forward iteration:\n            T gamkf = boost::math::gamma_p(a, x, pol);\n\n            if(lambda == 0)\n               return gamkf;\n            // Central chi squared term for backward iteration:\n            T gamkb = gamkf;\n            // Forwards Poisson weight:\n            T poiskf = gamma_p_derivative(k+1, del, pol);\n            // Backwards Poisson weight:\n            T poiskb = poiskf;\n            // Forwards gamma function recursion term:\n            T xtermf = boost::math::gamma_p_derivative(a, x, pol);\n            // Backwards gamma function recursion term:\n            T xtermb = xtermf * x / a;\n            T sum = init_sum + poiskf * gamkf;\n            if(sum == 0)\n               return sum;\n            int i = 1;\n            //\n            // Backwards recursion first, this is the stable\n            // direction for gamma function recurrences:\n            //\n            while(i <= k)\n            {\n               xtermb *= (a - i + 1) / x;\n               gamkb += xtermb;\n               poiskb = poiskb * (k - i + 1) / del;\n               errorf = errorb;\n               errorb = gamkb * poiskb;\n               sum += errorb;\n               if((fabs(errorb / sum) < errtol) && (errorb <= errorf))\n                  break;\n               ++i;\n            }\n            i = 1;\n            //\n            // Now forwards recursion, the gamma function\n            // recurrence relation is unstable in this direction,\n            // so we rely on the magnitude of successive terms\n            // decreasing faster than we introduce cancellation error.\n            // For this reason it's vital that k is chosen to be *after*\n            // the largest term, so that successive forward iterations\n            // are strictly (and rapidly) converging.\n            //\n            do\n            {\n               xtermf = xtermf * x / (a + i - 1);\n               gamkf = gamkf - xtermf;\n               poiskf = poiskf * del / (k + i);\n               errorf = poiskf * gamkf;\n               sum += errorf;\n               ++i;\n            }while((fabs(errorf / sum) > errtol) && (static_cast<boost::uintmax_t>(i) < max_iter));\n\n            //Error check:\n            if(static_cast<boost::uintmax_t>(i) >= max_iter)\n               policies::raise_evaluation_error(\n                  \"cdf(non_central_chi_squared_distribution<%1%>, %1%)\",\n                  \"Series did not converge, closest value was %1%\", sum, pol);\n\n            return sum;\n         }\n\n         template <class T, class Policy>\n         T non_central_chi_square_pdf(T x, T n, T lambda, const Policy& pol)\n         {\n            //\n            // As above but for the PDF:\n            //\n            BOOST_MATH_STD_USING\n            boost::uintmax_t max_iter = policies::get_max_series_iterations<Policy>();\n            T errtol = boost::math::policies::get_epsilon<T, Policy>();\n            T x2 = x / 2;\n            T n2 = n / 2;\n            T l2 = lambda / 2;\n            T sum = 0;\n            int k = itrunc(l2);\n            T pois = gamma_p_derivative(k + 1, l2, pol) * gamma_p_derivative(n2 + k, x2);\n            if(pois == 0)\n               return 0;\n            T poisb = pois;\n            for(int i = k; ; ++i)\n            {\n               sum += pois;\n               if(pois / sum < errtol)\n                  break;\n               if(static_cast<boost::uintmax_t>(i - k) >= max_iter)\n                  return policies::raise_evaluation_error(\n                     \"pdf(non_central_chi_squared_distribution<%1%>, %1%)\",\n                     \"Series did not converge, closest value was %1%\", sum, pol);\n               pois *= l2 * x2 / ((i + 1) * (n2 + i));\n            }\n            for(int i = k - 1; i >= 0; --i)\n            {\n               poisb *= (i + 1) * (n2 + i) / (l2 * x2);\n               sum += poisb;\n               if(poisb / sum < errtol)\n                  break;\n            }\n            return sum / 2;\n         }\n\n         template <class RealType, class Policy>\n         inline RealType non_central_chi_squared_cdf(RealType x, RealType k, 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            value_type result;\n            if(l == 0)\n               result = cdf(boost::math::chi_squared_distribution<RealType, Policy>(k), x);\n            else if(x > k + l)\n            {\n               // Complement is the smaller of the two:\n               result = detail::non_central_chi_square_q(\n                  static_cast<value_type>(x),\n                  static_cast<value_type>(k),\n                  static_cast<value_type>(l),\n                  forwarding_policy(),\n                  static_cast<value_type>(invert ? 0 : -1));\n               invert = !invert;\n            }\n            else if(l < 200)\n            {\n               // For small values of the non-centrality parameter\n               // we can use Ding's method:\n               result = detail::non_central_chi_square_p_ding(\n                  static_cast<value_type>(x),\n                  static_cast<value_type>(k),\n                  static_cast<value_type>(l),\n                  forwarding_policy(),\n                  static_cast<value_type>(invert ? -1 : 0));\n            }\n            else\n            {\n               // For largers values of the non-centrality\n               // parameter Ding's method will consume an\n               // extra-ordinary number of terms, and worse\n               // may return zero when the result is in fact\n               // finite, use Krishnamoorthy's method instead:\n               result = detail::non_central_chi_square_p(\n                  static_cast<value_type>(x),\n                  static_cast<value_type>(k),\n                  static_cast<value_type>(l),\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_chi_squared_cdf<%1%>(%1%, %1%, %1%)\");\n         }\n\n         template <class T, class Policy>\n         struct nccs_quantile_functor\n         {\n            nccs_quantile_functor(const non_central_chi_squared_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                  target - cdf(complement(dist, x))\n                  : cdf(dist, x) - target;\n            }\n\n         private:\n            non_central_chi_squared_distribution<T,Policy> dist;\n            T target;\n            bool comp;\n         };\n\n         template <class RealType, class Policy>\n         RealType nccs_quantile(const non_central_chi_squared_distribution<RealType, Policy>& dist, const RealType& p, bool comp)\n         {\n            static const char* function = \"quantile(non_central_chi_squared_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 k = dist.degrees_of_freedom();\n            value_type l = dist.non_centrality();\n            value_type r;\n            if(!detail::check_df(\n               function,\n               k, &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            value_type b = (l * l) / (k + 3 * l);\n            value_type c = (k + 3 * l) / (k + 2 * l);\n            value_type ff = (k + 2 * l) / (c * c);\n            value_type guess;\n            if(comp)\n               guess = b + c * quantile(complement(chi_squared_distribution<value_type, forwarding_policy>(ff), p));\n            else\n               guess = b + c * quantile(chi_squared_distribution<value_type, forwarding_policy>(ff), p);\n\n            if(guess < 0)\n               guess = tools::min_value<value_type>();\n\n            value_type result = detail::generic_quantile(\n               non_central_chi_squared_distribution<value_type, forwarding_policy>(k, l),\n               p,\n               guess,\n               comp,\n               function);\n            return policies::checked_narrowing_cast<RealType, forwarding_policy>(\n               result,\n               function);\n         }\n\n         template <class RealType, class Policy>\n         RealType nccs_pdf(const non_central_chi_squared_distribution<RealType, Policy>& dist, const RealType& x)\n         {\n            BOOST_MATH_STD_USING\n            static const char* function = \"pdf(non_central_chi_squared_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 k = dist.degrees_of_freedom();\n            value_type l = dist.non_centrality();\n            value_type r;\n            if(!detail::check_df(\n               function,\n               k, &r, Policy())\n               ||\n            !detail::check_non_centrality(\n               function,\n               l,\n               &r,\n               Policy())\n               ||\n            !detail::check_positive_x(\n               function,\n               (value_type)x,\n               &r,\n               Policy()))\n                  return (RealType)r;\n\n         if(l == 0)\n            return pdf(boost::math::chi_squared_distribution<RealType, forwarding_policy>(dist.degrees_of_freedom()), x);\n\n         // Special case:\n         if(x == 0)\n            return 0;\n         if(l > 50)\n         {\n            r = non_central_chi_square_pdf(static_cast<value_type>(x), k, l, forwarding_policy());\n         }\n         else\n         {\n            r = log(x / l) * (k / 4 - 0.5f) - (x + l) / 2;\n            if(fabs(r) >= tools::log_max_value<RealType>() / 4)\n            {\n               r = non_central_chi_square_pdf(static_cast<value_type>(x), k, l, forwarding_policy());\n            }\n            else\n            {\n               r = exp(r);\n               r = 0.5f * r\n                  * boost::math::cyl_bessel_i(k/2 - 1, sqrt(l * x), forwarding_policy());\n            }\n         }\n         return policies::checked_narrowing_cast<RealType, forwarding_policy>(\n               r,\n               function);\n         }\n\n         template <class RealType, class Policy>\n         struct degrees_of_freedom_finder\n         {\n            degrees_of_freedom_finder(\n               RealType lam_, RealType x_, RealType p_, bool c)\n               : lam(lam_), x(x_), p(p_), comp(c) {}\n\n            RealType operator()(const RealType& v)\n            {\n               non_central_chi_squared_distribution<RealType, Policy> d(v, lam);\n               return comp ?\n                  RealType(p - cdf(complement(d, x)))\n                  : RealType(cdf(d, x) - p);\n            }\n         private:\n            RealType lam;\n            RealType x;\n            RealType p;\n            bool comp;\n         };\n\n         template <class RealType, class Policy>\n         inline RealType find_degrees_of_freedom(\n            RealType lam, RealType x, RealType p, RealType q, const Policy& pol)\n         {\n            const char* function = \"non_central_chi_squared<%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            degrees_of_freedom_finder<RealType, Policy> f(lam, 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 will give us a probability\n            // right around 0.5.\n            //\n            RealType guess = x - lam;\n            if(guess < 1)\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\n         template <class RealType, class Policy>\n         struct non_centrality_finder\n         {\n            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& lam)\n            {\n               non_central_chi_squared_distribution<RealType, Policy> d(v, lam);\n               return comp ?\n                  RealType(p - cdf(complement(d, x)))\n                  : RealType(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_non_centrality(\n            RealType v, RealType x, RealType p, RealType q, const Policy& pol)\n         {\n            const char* function = \"non_central_chi_squared<%1%>::find_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            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 will give us a probability\n            // right around 0.5.\n            //\n            RealType guess = x - v;\n            if(guess < 1)\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\n      }\n\n      template <class RealType = double, class Policy = policies::policy<> >\n      class non_central_chi_squared_distribution\n      {\n      public:\n         typedef RealType value_type;\n         typedef Policy policy_type;\n\n         non_central_chi_squared_distribution(RealType df_, RealType lambda) : df(df_), ncp(lambda)\n         {\n            const char* function = \"boost::math::non_central_chi_squared_distribution<%1%>::non_central_chi_squared_distribution(%1%,%1%)\";\n            RealType r;\n            detail::check_df(\n               function,\n               df, &r, Policy());\n            detail::check_non_centrality(\n               function,\n               ncp,\n               &r,\n               Policy());\n         } // non_central_chi_squared_distribution constructor.\n\n         RealType degrees_of_freedom() const\n         { // Private data getter function.\n            return df;\n         }\n         RealType non_centrality() const\n         { // Private data getter function.\n            return ncp;\n         }\n         static RealType find_degrees_of_freedom(RealType lam, RealType x, RealType p)\n         {\n            const char* function = \"non_central_chi_squared<%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_degrees_of_freedom(\n               static_cast<value_type>(lam),\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_chi_squared<%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_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_chi_squared<%1%>::find_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_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_chi_squared<%1%>::find_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_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      private:\n         // Data member, initialized by constructor.\n         RealType df; // degrees of freedom.\n         RealType ncp; // non-centrality parameter\n      }; // template <class RealType, class Policy> class non_central_chi_squared_distribution\n\n      typedef non_central_chi_squared_distribution<double> non_central_chi_squared; // 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_chi_squared_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>()); // Max integer?\n      }\n\n      template <class RealType, class Policy>\n      inline const std::pair<RealType, RealType> support(const non_central_chi_squared_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_chi_squared_distribution<RealType, Policy>& dist)\n      { // Mean of poisson distribution = lambda.\n         const char* function = \"boost::math::non_central_chi_squared_distribution<%1%>::mean()\";\n         RealType k = dist.degrees_of_freedom();\n         RealType l = dist.non_centrality();\n         RealType r;\n         if(!detail::check_df(\n            function,\n            k, &r, Policy())\n            ||\n         !detail::check_non_centrality(\n            function,\n            l,\n            &r,\n            Policy()))\n               return r;\n         return k + l;\n      } // mean\n\n      template <class RealType, class Policy>\n      inline RealType mode(const non_central_chi_squared_distribution<RealType, Policy>& dist)\n      { // mode.\n         static const char* function = \"mode(non_central_chi_squared_distribution<%1%> const&)\";\n\n         RealType k = dist.degrees_of_freedom();\n         RealType l = dist.non_centrality();\n         RealType r;\n         if(!detail::check_df(\n            function,\n            k, &r, Policy())\n            ||\n         !detail::check_non_centrality(\n            function,\n            l,\n            &r,\n            Policy()))\n               return (RealType)r;\n         return detail::generic_find_mode(dist, 1 + k, function);\n      }\n\n      template <class RealType, class Policy>\n      inline RealType variance(const non_central_chi_squared_distribution<RealType, Policy>& dist)\n      { // variance.\n         const char* function = \"boost::math::non_central_chi_squared_distribution<%1%>::variance()\";\n         RealType k = dist.degrees_of_freedom();\n         RealType l = dist.non_centrality();\n         RealType r;\n         if(!detail::check_df(\n            function,\n            k, &r, Policy())\n            ||\n         !detail::check_non_centrality(\n            function,\n            l,\n            &r,\n            Policy()))\n               return r;\n         return 2 * (2 * l + k);\n      }\n\n      // RealType standard_deviation(const non_central_chi_squared_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_chi_squared_distribution<RealType, Policy>& dist)\n      { // skewness = sqrt(l).\n         const char* function = \"boost::math::non_central_chi_squared_distribution<%1%>::skewness()\";\n         RealType k = dist.degrees_of_freedom();\n         RealType l = dist.non_centrality();\n         RealType r;\n         if(!detail::check_df(\n            function,\n            k, &r, Policy())\n            ||\n         !detail::check_non_centrality(\n            function,\n            l,\n            &r,\n            Policy()))\n               return r;\n         BOOST_MATH_STD_USING\n            return pow(2 / (k + 2 * l), RealType(3)/2) * (k + 3 * l);\n      }\n\n      template <class RealType, class Policy>\n      inline RealType kurtosis_excess(const non_central_chi_squared_distribution<RealType, Policy>& dist)\n      {\n         const char* function = \"boost::math::non_central_chi_squared_distribution<%1%>::kurtosis_excess()\";\n         RealType k = dist.degrees_of_freedom();\n         RealType l = dist.non_centrality();\n         RealType r;\n         if(!detail::check_df(\n            function,\n            k, &r, Policy())\n            ||\n         !detail::check_non_centrality(\n            function,\n            l,\n            &r,\n            Policy()))\n               return r;\n         return 12 * (k + 4 * l) / ((k + 2 * l) * (k + 2 * l));\n      } // kurtosis_excess\n\n      template <class RealType, class Policy>\n      inline RealType kurtosis(const non_central_chi_squared_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_chi_squared_distribution<RealType, Policy>& dist, const RealType& x)\n      { // Probability Density/Mass Function.\n         return detail::nccs_pdf(dist, x);\n      } // pdf\n\n      template <class RealType, class Policy>\n      RealType cdf(const non_central_chi_squared_distribution<RealType, Policy>& dist, const RealType& x)\n      {\n         const char* function = \"boost::math::non_central_chi_squared_distribution<%1%>::cdf(%1%)\";\n         RealType k = dist.degrees_of_freedom();\n         RealType l = dist.non_centrality();\n         RealType r;\n         if(!detail::check_df(\n            function,\n            k, &r, Policy())\n            ||\n         !detail::check_non_centrality(\n            function,\n            l,\n            &r,\n            Policy())\n            ||\n         !detail::check_positive_x(\n            function,\n            x,\n            &r,\n            Policy()))\n               return r;\n\n         return detail::non_central_chi_squared_cdf(x, k, l, false, Policy());\n      } // cdf\n\n      template <class RealType, class Policy>\n      RealType cdf(const complemented2_type<non_central_chi_squared_distribution<RealType, Policy>, RealType>& c)\n      { // Complemented Cumulative Distribution Function\n         const char* function = \"boost::math::non_central_chi_squared_distribution<%1%>::cdf(%1%)\";\n         non_central_chi_squared_distribution<RealType, Policy> const& dist = c.dist;\n         RealType x = c.param;\n         RealType k = dist.degrees_of_freedom();\n         RealType l = dist.non_centrality();\n         RealType r;\n         if(!detail::check_df(\n            function,\n            k, &r, Policy())\n            ||\n         !detail::check_non_centrality(\n            function,\n            l,\n            &r,\n            Policy())\n            ||\n         !detail::check_positive_x(\n            function,\n            x,\n            &r,\n            Policy()))\n               return r;\n\n         return detail::non_central_chi_squared_cdf(x, k, l, true, Policy());\n      } // ccdf\n\n      template <class RealType, class Policy>\n      inline RealType quantile(const non_central_chi_squared_distribution<RealType, Policy>& dist, const RealType& p)\n      { // Quantile (or Percent Point) function.\n         return detail::nccs_quantile(dist, p, false);\n      } // quantile\n\n      template <class RealType, class Policy>\n      inline RealType quantile(const complemented2_type<non_central_chi_squared_distribution<RealType, Policy>, RealType>& c)\n      { // Quantile (or Percent Point) function.\n         return detail::nccs_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_CHI_SQUARE_HPP\n\n\n\n", "meta": {"hexsha": "a3f98982b999c347f30d9bcefbe62fca7f620518", "size": 38484, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/boost/math/distributions/non_central_chi_squared.hpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 71.0, "max_stars_repo_stars_event_min_datetime": "2015-01-17T00:29:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-09T02:59:16.000Z", "max_issues_repo_path": "boost/boost/math/distributions/non_central_chi_squared.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/math/distributions/non_central_chi_squared.hpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 44.0, "max_forks_repo_forks_event_min_datetime": "2015-03-18T09:20:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-21T08:09:17.000Z", "avg_line_length": 39.9211618257, "max_line_length": 139, "alphanum_fraction": 0.5386654194, "num_tokens": 8515, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859596, "lm_q2_score": 0.6370308013713525, "lm_q1q2_score": 0.488152653540822}}
{"text": "#include <iostream>\n#include <cassert>\n#include <vector>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/depth_first_search.hpp>\n\nconst int debug_level = 0;\n\n#define DEBUG(min_level, x)      \\\n  if (debug_level >= min_level)  \\\n  {                              \\\n    std::cerr << x << std::endl; \\\n  }\n\ntypedef boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS> Graph;\n\nconst long undefined_diff = std::numeric_limits<int>::max();\n\nclass DFSVisitor : public boost::default_dfs_visitor\n{\npublic:\n  DFSVisitor(\n      std::size_t n,\n      std::size_t m,\n      std::vector<long> &window_diff_by_start,\n      std::function<long(int)> get_value) : n(n),\n                                            m(m),\n                                            window_diff_by_start(window_diff_by_start),\n                                            get_value(get_value)\n  {\n    assert(m > 0);\n  }\n\n  void discover_vertex(int vertex, const Graph &G)\n  {\n    const long added_value = get_value(vertex);\n    DEBUG(3, \"discover_vertex \" << vertex << \" adding \" << added_value);\n    values_on_path.push_back(added_value);\n    vertices_on_path.push_back(vertex);\n    values_in_window.insert(added_value);\n    if (values_on_path.size() > m)\n    {\n      const long removed_value = values_on_path.at(values_on_path.size() - m - 1);\n      DEBUG(3, \"discover_vertex \" << vertex << \" removing \" << removed_value);\n      values_in_window.erase(values_in_window.find(removed_value));\n    }\n    try_save_diff();\n  }\n\n  void finish_vertex(int vertex, const Graph &G)\n  {\n    assert(vertices_on_path.back() == vertex);\n    vertices_on_path.pop_back();\n    const long removed_value = values_on_path.back();\n    DEBUG(3, \"finish_vertex \" << vertex << \" removing \" << removed_value);\n    values_on_path.pop_back();\n    values_in_window.erase(values_in_window.find(removed_value));\n    if (values_on_path.size() >= m)\n    {\n      const long added_value = values_on_path.at(values_on_path.size() - m);\n      DEBUG(3, \"finish_vertex \" << vertex << \" adding \" << added_value);\n      values_in_window.insert(added_value);\n    }\n  }\n\nprivate:\n  std::size_t n, m;\n  std::vector<long> &window_diff_by_start;\n  std::function<long(int)> get_value;\n  std::multiset<long> values_in_window;\n  std::vector<long> values_on_path;\n  std::vector<int> vertices_on_path;\n\n  void try_save_diff()\n  {\n    if (values_in_window.size() < m)\n    {\n      return;\n    }\n    assert(values_in_window.size() == m);\n    const int start_vertex = vertices_on_path.at(vertices_on_path.size() - m);\n    const long diff_in_window = *values_in_window.rbegin() - *values_in_window.begin();\n    DEBUG(3, \"try_save_diff \" << start_vertex << \" \" << diff_in_window);\n    long &saved_diff = window_diff_by_start.at(start_vertex);\n    saved_diff = std::min(saved_diff, diff_in_window);\n  }\n};\n\nvoid testcase()\n{\n  int n, m, k;\n  std::cin >> n >> m >> k;\n  assert(n >= 1 && n <= 1e5 && m >= 2 && m <= 1e4 && k >= 0 && k <= 1e4);\n\n  std::vector<long> temperature_by_node(n);\n  for (long &t : temperature_by_node)\n  {\n    std::cin >> t;\n    assert(t >= 0 && t < (1L << 31));\n  }\n\n  Graph G(n);\n  for (int i = 0; i < n - 1; i++)\n  {\n    int u, v;\n    std::cin >> u >> v;\n    assert(u >= 0 && u < n && v >= 0 && v < n);\n    assert(u != v); // not sure if this holds\n    boost::add_edge(u, v, G);\n  }\n\n  std::vector<long> window_diff_by_start(n, undefined_diff);\n  DFSVisitor visitor(n, m, window_diff_by_start, [&temperature_by_node](int i) { return temperature_by_node.at(i); });\n  // WARNING visitors are copied\n  boost::depth_first_search(G, boost::visitor(visitor));\n\n  bool mission_is_possible = false;\n  for (int i = 0; i < n; i++)\n  {\n    const long diff = window_diff_by_start.at(i);\n    DEBUG(2, \"i \" << i << \" diff \" << diff);\n    if (diff == undefined_diff)\n    {\n      continue;\n    }\n    assert(diff >= 0);\n    if (diff <= k)\n    {\n      if (mission_is_possible)\n      {\n        std::cout << \" \";\n      }\n      else\n      {\n        mission_is_possible = true;\n      }\n      std::cout << i;\n    }\n  }\n  std::cout << (mission_is_possible ? \"\\n\" : \"Abort mission\\n\");\n}\n\nint main()\n{\n  std::ios_base::sync_with_stdio(false);\n\n  int t;\n  std::cin >> t;\n  for (int i = 0; i < t; i++)\n  {\n    testcase();\n    DEBUG(1, \"\");\n  }\n\n  return 0;\n}", "meta": {"hexsha": "07b5f7bd35fa7e69193507766e5b6f8f5f56ba05", "size": 4290, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "week-10/new-york/src/main.cpp", "max_stars_repo_name": "tehwalris/algolab", "max_stars_repo_head_hexsha": "489e0f6dd137336fa32b8002fc6eed8a7d35d87a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-17T08:21:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-17T08:21:32.000Z", "max_issues_repo_path": "week-10/new-york/src/main.cpp", "max_issues_repo_name": "tehwalris/algolab", "max_issues_repo_head_hexsha": "489e0f6dd137336fa32b8002fc6eed8a7d35d87a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "week-10/new-york/src/main.cpp", "max_forks_repo_name": "tehwalris/algolab", "max_forks_repo_head_hexsha": "489e0f6dd137336fa32b8002fc6eed8a7d35d87a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5, "max_line_length": 118, "alphanum_fraction": 0.5986013986, "num_tokens": 1154, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859598, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.4881526482603161}}
{"text": "// smooth_feedback: Control theory on Lie groups\n// https://github.com/pettni/smooth_feedback\n//\n// Licensed under the MIT License <http://opensource.org/licenses/MIT>.\n//\n// Copyright (c) 2021 Petter Nilsson, John B. Mains\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n#ifndef SMOOTH__FEEDBACK__QP_HPP_\n#define SMOOTH__FEEDBACK__QP_HPP_\n\n/**\n * @file\n * @brief Quadratic Program definition.\n */\n\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n\nnamespace smooth::feedback {\n\n/**\n * @brief Quadratic program definition.\n *\n * @tparam M number of constraints\n * @tparam N number of variables\n *\n * The quadratic program is on the form\n * \\f[\n * \\begin{cases}\n *  \\min_{x} & \\frac{1}{2} x^T P x + q^T x, \\\\\n *  \\text{s.t.} & l \\leq A x \\leq u,\n * \\end{cases}\n * \\f]\n * where \\f$ P \\in \\mathbb{R}^{n \\times n}, q \\in \\mathbb{R}^n, l, u \\in \\mathbb{R}^m, A \\in\n * \\mathbb{R}^{m \\times n} \\f$.\n */\ntemplate<Eigen::Index M, Eigen::Index N, typename Scalar = double>\nstruct QuadraticProgram\n{\n  /// Positive semi-definite square cost (only upper triangular part is used)\n  Eigen::Matrix<Scalar, N, N> P;\n  /// Linear cost\n  Eigen::Matrix<Scalar, N, 1> q;\n\n  /// Inequality matrix\n  Eigen::Matrix<Scalar, M, N> A;\n  /// Inequality lower bound\n  Eigen::Matrix<Scalar, M, 1> l;\n  /// Inequality upper bound\n  Eigen::Matrix<Scalar, M, 1> u;\n};\n\n/**\n * @brief Sparse quadratic program definition.\n *\n * The quadratic program is on the form\n * \\f[\n * \\begin{cases}\n *  \\min_{x} & \\frac{1}{2} x^T P x + q^T x, \\\\\n *  \\text{s.t.} & l \\leq A x \\leq u,\n * \\end{cases}\n * \\f]\n * where \\f$ P \\in \\mathbb{R}^{n \\times n}, q \\in \\mathbb{R}^n, l, u \\in \\mathbb{R}^m, A \\in\n * \\mathbb{R}^{m \\times n} \\f$.\n */\ntemplate<typename Scalar = double>\nstruct QuadraticProgramSparse\n{\n  /// Positive semi-definite square cost (only upper trianglular part is used)\n  Eigen::SparseMatrix<Scalar> P;\n  /// Linear cost\n  Eigen::Matrix<Scalar, -1, 1> q;\n\n  /**\n   * @brief Inequality matrix\n   *\n   * @note The constraint matrix is stored in row-major format,\n   * i.e. coefficients for each constraint are contiguous in memory\n   */\n  Eigen::SparseMatrix<Scalar, Eigen::RowMajor> A;\n  /// Inequality lower bound\n  Eigen::Matrix<Scalar, -1, 1> l;\n  /// Inequality upper bound\n  Eigen::Matrix<Scalar, -1, 1> u;\n};\n\n/// @brief Solver exit codes\nenum class QPSolutionStatus {\n  Optimal,           /// @brief Solution satisifes optimality condition. Solution is polished if\n                     /// `QPSolverParams::polish = true`.\n  PolishFailed,      /// @brief Solution satisfies optimality condition but is not polished\n  PrimalInfeasible,  /// @brief A certificate of primal infeasibility was found, no solution\n                     /// returned\n  DualInfeasible,    /// @brief A certificate of dual infeasibility was found, no solution returned\n  MaxIterations,  /// @brief Max number of iterations was reached, returned solution is not optimal\n  MaxTime,        /// @brief Max time was reached, returned solution is not optimal\n  Unknown         /// @brief Solution is useless because of other reasons, no solution returned\n};\n\n/// Solver solution\ntemplate<Eigen::Index M, Eigen::Index N, typename Scalar = double>\nstruct QPSolution\n{\n  /// Exit code\n  QPSolutionStatus code = QPSolutionStatus::Unknown;\n  /// Number of iterations\n  uint32_t iter;\n  /// Primal vector\n  Eigen::Matrix<Scalar, N, 1> primal;\n  /// Dual vector\n  Eigen::Matrix<Scalar, M, 1> dual;\n  /// Solution objective value\n  Scalar objective{0.};\n};\n\n}  // namespace smooth::feedback\n\n#endif  // SMOOTH__FEEDBACK__QP_HPP_\n", "meta": {"hexsha": "dd12f6e2160ea018c2b1b913b7659bd7cb97afb7", "size": 4586, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/smooth/feedback/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/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/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": 33.4744525547, "max_line_length": 99, "alphanum_fraction": 0.686873092, "num_tokens": 1249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.48815264826031607}}
{"text": "#pragma once\n\n#include <algorithm>\n#include <array>\n#include <cassert>\n#include <cmath>\n#include <cstdint>\n#include <cstdlib>\n#include <vector>\n#include <utility>\n\n#include <Eigen/Core>\n\n#include <pcl/common/transforms.h>\n#include <pcl/io/pcd_io.h>\n#include <pcl/common/common.h>\n#include <pcl/point_cloud.h>\n\n\nclass PointCloudDim2D;\nstruct TransformXYTheta;\n\ntypedef Eigen::Matrix<std::uint8_t, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> RMatrixXui8;\n\nvoid writeBGM(const std::string& kSavePath, const RMatrixXui8& kMat);\n\nvoid writeScanInfo(const std::string& KInfofilename, const std::vector<std::string>& kVelonames,\n                   const std::vector<TransformXYTheta>& kTFs, \n                   const std::pair<std::uint32_t, std::uint32_t>& kMapImgSize,\n                   const float kResolution);\n\ninline\nstd::array<int, 2> computePixelLoc(\n    int imgHeight,\n    int imgWidth,\n    float x,\n    float y,\n    float resolution)\n{\n    assert(imgHeight > 0 && imgWidth > 0);\n    assert(x >= 0.f && y >= 0.f);\n    assert(resolution > 0.f);\n\n    return std::array<int, 2>{\n        std::min(imgHeight - static_cast<int>(floor(x / resolution)), imgHeight - 1),\n        std::min( imgWidth - static_cast<int>(floor(y / resolution)),  imgWidth - 1)\n    };\n}\n\ntemplate<typename T>\ninline T eucddist(const T& x0, const T& y0, const T& x1, const T& y1)\n{\n    return std::sqrt(std::pow(x0 - x1, 2) + std::pow(y0 - y1, 2));\n}\n\ntemplate <typename PointT>\nvoid aggregatePointClouds(\n    const std::vector<pcl::PointCloud<PointT>>& kIndivClouds,\n    pcl::PointCloud<PointT>& aggCloud)\n{\n    for (auto it = kIndivClouds.begin(); it != kIndivClouds.end(); ++it)\n        aggCloud += *it;\n}\n\ntemplate<typename PointT>\nRMatrixXui8 buildBEVFromCloud(\n    const pcl::PointCloud<PointT>& kCloud,\n    const float kXdiff,\n    const float kYdiff,\n    const float outRes,\n    bool useZvals = false,\n    float minZ = 0.f)\n{\n    // Sanity checks.\n    assert(kXdiff > 0.f && kYdiff > 0.f && outRes > 0.f);\n\n    // Compute the image size.\n    auto imgHeight = static_cast<int>(ceil(kXdiff / outRes));\n    auto imgWidth = static_cast<int>(ceil(kYdiff / outRes));\n    \n    // Create the bird's eye matrix (image) and iteratively fill the matrix.\n    RMatrixXui8 bev = RMatrixXui8::Zero(imgHeight, imgWidth);\n    for (std::size_t i = 0; i < kCloud.size(); i++)\n    {\n        const PointT& pt = kCloud[i];\n        float pixelValue = 0.0f;\n        // max / min from zlen\n        if (useZvals)\n        {\n            //pixelValue = (pt.z - kMinPt.z) / (kMaxPt.z - kMinPt.z);\n            pixelValue = (pt.z + minZ) / (minZ * 2);\n        }\n        else\n        {\n            pixelValue = pt.intensity;\n        }\n        pixelValue = std::min(std::max(pixelValue * 255.0f, 0.0f), 255.0f);\n\n        auto pxLoc = computePixelLoc(imgHeight, imgWidth, pt.x, pt.y, outRes);\n        auto row = pxLoc[0];\n        auto col = pxLoc[1];\n\n        bev(row, col) = std::max(static_cast<std::uint8_t>(pixelValue), bev(row, col));\n    }\n    return bev;\n}\n\ntemplate<typename PointT>\nvoid extractPointCloudROI(\n    const pcl::PointCloud<PointT>& kOriginalPC,\n    const float kXlen,\n    const float kYlen,\n    pcl::PointCloud<PointT>& extractedPC)\n{\n    // Sanity checks.\n    assert(kOriginalPC.size() > 0);\n    assert(kXlen > 0.f && kYlen > 0.f);\n\n    float x = 0.f, y = 0.f;\n    for (auto pt_it = kOriginalPC.points.begin(); pt_it != kOriginalPC.points.end(); ++pt_it)\n    {\n        x = pt_it->x;\n        y = pt_it->y;\n        if (-kXlen < x && x < kXlen && -kYlen < y && y < kYlen)\n            extractedPC.push_back(*pt_it);\n    }\n}\n\ntemplate<typename PointT>\nvoid extractPointCloudROI(\n    const pcl::PointCloud<PointT>& kOriginalPC,\n    const float kRadius,\n    pcl::PointCloud<PointT>& extractedPC)\n{\n    // Sanity checks.\n    assert(kOriginalPC.size() > 0);\n    assert(kRadius > 0.f);\n\n    float d = 0.f;\n    for (auto pt_it = kOriginalPC.points.begin(); pt_it != kOriginalPC.points.end(); ++pt_it)\n    {\n        d = std::sqrt(std::pow(pt_it->x, 2) + std::pow(pt_it->y, 2));\n        if (d < kRadius)\n            extractedPC.push_back(*pt_it);\n    }\n}\n\ntemplate<typename PointT>\nvoid translateDataXY(\n    pcl::PointCloud<PointT>& cloud,\n    const Eigen::Vector2f& kShift)\n{\n    // Sanity check.\n    assert(cloud.size() > 0);\n\n    const float dx = -kShift[0], dy = -kShift[1];\n    for (auto it = cloud.points.begin(); it != cloud.points.end(); ++it)\n    {\n        it->x += dx;\n        it->y += dy;\n    }\n}\n\ntemplate<typename T>\nvoid translateDataXY(\n    std::vector<T>& data,\n    const Eigen::Vector2f& kShift)\n{\n    // Sanity check.\n    assert(data.size() > 0);\n\n    const float dx = -kShift[0], dy = -kShift[1];\n    for (auto it = data.begin(); it != data.end(); ++it)\n    {\n        it->x += dx;\n        it->y += dy;\n    }\n}\n", "meta": {"hexsha": "d7487519f5cab10e628595a996f5953a85bb6c8f", "size": 4786, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/bev2d_helpers.hpp", "max_stars_repo_name": "troiwill/build-lidar-2d-bev-data", "max_stars_repo_head_hexsha": "d351b723e67bd48a720f5583ed8b231a58f50a8e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-05-28T02:43:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-09T11:55:19.000Z", "max_issues_repo_path": "include/bev2d_helpers.hpp", "max_issues_repo_name": "troiwill/build-lidar-2d-bev-data", "max_issues_repo_head_hexsha": "d351b723e67bd48a720f5583ed8b231a58f50a8e", "max_issues_repo_licenses": ["MIT"], "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/bev2d_helpers.hpp", "max_forks_repo_name": "troiwill/build-lidar-2d-bev-data", "max_forks_repo_head_hexsha": "d351b723e67bd48a720f5583ed8b231a58f50a8e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-09T11:55:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-09T11:55:22.000Z", "avg_line_length": 26.7374301676, "max_line_length": 97, "alphanum_fraction": 0.6036356038, "num_tokens": 1410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.48815264826031607}}
{"text": "#include <boost/test/unit_test.hpp>\n#include \"expression/Parser.hpp\"\n#include \"expression/Ast.hpp\"\n#include \"expression/Lexer.hpp\"\n#include \"expression/Scope.hpp\"\n#include \"types/Number.hpp\"\n#include \"Error.hpp\"\n\nusing namespace slim;\nusing namespace slim::expr;\nBOOST_AUTO_TEST_SUITE(TestNumber)\n\nstd::string eval(const std::string &str, Scope &scope)\n{\n    Lexer lexer(str);\n    expr::LocalVarNames vars;\n    for (auto x : scope) vars.add(x.first->str());\n    Parser parser(vars, lexer);\n    auto expr = parser.full_expression();\n    auto result = expr->eval(scope);\n    return result->inspect();\n}\nstd::string eval(const std::string &str)\n{\n    Scope scope(create_view_model());\n    return eval(str, scope);\n}\n\nBOOST_AUTO_TEST_CASE(basic_methods)\n{\n    BOOST_CHECK_EQUAL(\"inf\", make_value(INFINITY)->to_string());\n    BOOST_CHECK_EQUAL(\"-inf\", make_value(-INFINITY)->to_string());\n    Scope scope(create_view_model());\n    scope.set(\"inf\", make_value(INFINITY));\n    scope.set(\"ninf\", make_value(-INFINITY));\n    scope.set(\"min\", make_value(-std::numeric_limits<double>::max()));\n    scope.set(\"max\", make_value(std::numeric_limits<double>::max()));\n\n    std::string min_s = make_value(-std::numeric_limits<double>::max())->to_string();\n    std::string max_s = make_value(std::numeric_limits<double>::max())->to_string();\n\n    BOOST_CHECK_EQUAL(\"0\", eval(\"0.abs\"));\n    BOOST_CHECK_EQUAL(\"5\", eval(\"5.0.abs\"));\n    BOOST_CHECK_EQUAL(\"5.5\", eval(\"5.5.abs\"));\n    BOOST_CHECK_EQUAL(\"5\", eval(\"-5.abs\"));\n    BOOST_CHECK_EQUAL(\"5\", eval(\"-5.0.abs\"));\n    BOOST_CHECK_EQUAL(\"5.5\", eval(\"-5.5.abs\"));\n    BOOST_CHECK_EQUAL(\"inf\", eval(\"inf.abs\", scope));\n    BOOST_CHECK_EQUAL(\"inf\", eval(\"ninf.abs\", scope));\n\n    BOOST_CHECK_EQUAL(\"inf\", eval(\"inf.next_float\", scope));\n    BOOST_CHECK_EQUAL(\"inf\", eval(\"max.next_float\", scope));\n    BOOST_CHECK_EQUAL(min_s, eval(\"ninf.next_float\", scope));\n\n    BOOST_CHECK_EQUAL(max_s, eval(\"inf.prev_float\", scope));\n    BOOST_CHECK_EQUAL(\"-inf\", eval(\"ninf.prev_float\", scope));\n    BOOST_CHECK_EQUAL(\"-inf\", eval(\"min.prev_float\", scope));\n\n    BOOST_CHECK_EQUAL(\"true\", eval(\"0.finite?\"));\n    BOOST_CHECK_EQUAL(\"true\", eval(\"5.5.finite?\"));\n    BOOST_CHECK_EQUAL(\"false\", eval(\"(0.0/0.0).finite?\"));\n    BOOST_CHECK_EQUAL(\"false\", eval(\"(1.0/0.0).finite?\"));\n\n    BOOST_CHECK_EQUAL(\"nil\", eval(\"0.infinite?\"));\n    BOOST_CHECK_EQUAL(\"nil\", eval(\"(0.0/0.0).infinite?\"));\n    BOOST_CHECK_EQUAL(\"1\", eval(\"(1.0/0.0).infinite?\"));\n    BOOST_CHECK_EQUAL(\"-1\", eval(\"(-1.0/0.0).infinite?\"));\n\n    BOOST_CHECK_EQUAL(\"false\", eval(\"1.nan?\"));\n    BOOST_CHECK_EQUAL(\"true\", eval(\"(0.0/0.0).nan?\"));\n    BOOST_CHECK_EQUAL(\"false\", eval(\"(1.0/0.0).nan?\"));\n    BOOST_CHECK_EQUAL(\"false\", eval(\"(-1.0/0.0).nan?\"));\n\n    BOOST_CHECK_EQUAL(\"true\", eval(\"0.zero?\", scope));\n    BOOST_CHECK_EQUAL(\"true\", eval(\"-0.zero?\", scope));\n    BOOST_CHECK_EQUAL(\"false\", eval(\"5.zero?\", scope));\n}\n\nBOOST_AUTO_TEST_CASE(operators)\n{\n    BOOST_CHECK_EQUAL(\"5\", eval(\"+5\"));\n    BOOST_CHECK_EQUAL(\"-5\", eval(\"-5\"));\n    BOOST_CHECK_EQUAL(\"false\", eval(\"!5\"));\n\n    BOOST_CHECK_EQUAL(\"5\", eval(\"1 + 4\"));\n    BOOST_CHECK_EQUAL(\"5\", eval(\"6 - 1\"));\n    BOOST_CHECK_EQUAL(\"6\", eval(\"2 * 3\"));\n    BOOST_CHECK_EQUAL(\"6\", eval(\"24 / 4\"));\n    BOOST_CHECK_EQUAL(\"6\", eval(\"16 % 10\"));\n    BOOST_CHECK_EQUAL(\"9\", eval(\"3 ** 2\"));\n\n\n    BOOST_CHECK_EQUAL(\"8\", eval(\"2 << 2\"));\n    BOOST_CHECK_EQUAL(\"1\", eval(\"2 >> 1\"));\n    BOOST_CHECK_EQUAL(\"0\", eval(\"2 >> 3\"));\n    BOOST_CHECK_EQUAL(\"2\", eval(\"7 & 2\"));\n    BOOST_CHECK_EQUAL(\"7\", eval(\"6 | 3\"));\n    BOOST_CHECK_EQUAL(\"10\", eval(\"8 ^ 2\"));\n    BOOST_CHECK_EQUAL(\"8\", eval(\"10 ^ 2\"));\n    BOOST_CHECK_EQUAL(\"-9\", eval(\"~8\"));\n}\n\nBOOST_AUTO_TEST_CASE(rounding)\n{\n    BOOST_CHECK_EQUAL(\"0\", eval(\"0.ceil\"));\n    BOOST_CHECK_EQUAL(\"6\", eval(\"5.4.ceil\"));\n    BOOST_CHECK_EQUAL(\"6\", eval(\"5.6.ceil\"));\n    BOOST_CHECK_EQUAL(\"-5\", eval(\"-5.3.ceil\"));\n    BOOST_CHECK_EQUAL(\"-5\", eval(\"-5.6.ceil\"));\n\n    BOOST_CHECK_EQUAL(\"0\", eval(\"0.floor\"));\n    BOOST_CHECK_EQUAL(\"5\", eval(\"5.4.floor\"));\n    BOOST_CHECK_EQUAL(\"5\", eval(\"5.6.floor\"));\n    BOOST_CHECK_EQUAL(\"-6\", eval(\"-5.3.floor\"));\n    BOOST_CHECK_EQUAL(\"-6\", eval(\"-5.6.floor\"));\n\n    BOOST_CHECK_EQUAL(\"0\", eval(\"0.round\"));\n    BOOST_CHECK_EQUAL(\"5\", eval(\"5.4.round\"));\n    BOOST_CHECK_EQUAL(\"6\", eval(\"5.6.round\"));\n    BOOST_CHECK_EQUAL(\"-5\", eval(\"-5.3.round\"));\n    BOOST_CHECK_EQUAL(\"-6\", eval(\"-5.6.round\"));\n\n    BOOST_CHECK_EQUAL(\"0\", eval(\"0.round(2)\"));\n    BOOST_CHECK_EQUAL(\"5.4\", eval(\"5.4.round(2)\"));\n    BOOST_CHECK_EQUAL(\"5.6\", eval(\"5.63.round(2)\"));\n    BOOST_CHECK_EQUAL(\"5.7\", eval(\"5.66.round(2)\"));\n    BOOST_CHECK_EQUAL(\"-5.3\", eval(\"-5.3.round(2)\"));\n    BOOST_CHECK_EQUAL(\"-5.6\", eval(\"-5.63.round(2)\"));\n    BOOST_CHECK_EQUAL(\"-5.7\", eval(\"-5.66.round(2)\"));\n\n    BOOST_CHECK_EQUAL(\"0\", eval(\"0.round(-1)\"));\n    BOOST_CHECK_EQUAL(\"5\", eval(\"5.4.round(-1)\"));\n    BOOST_CHECK_EQUAL(\"6\", eval(\"5.63.round(-1)\"));\n    BOOST_CHECK_EQUAL(\"6\", eval(\"5.66.round(-1)\"));\n    BOOST_CHECK_EQUAL(\"-5\", eval(\"-5.3.round(-1)\"));\n    BOOST_CHECK_EQUAL(\"-6\", eval(\"-5.63.round(-1)\"));\n    BOOST_CHECK_EQUAL(\"-6\", eval(\"-5.66.round(-1)\"));\n\n    BOOST_CHECK_EQUAL(\"0\", eval(\"0.round(-1)\"));\n    BOOST_CHECK_EQUAL(\"50\", eval(\"54.round(-1)\"));\n    BOOST_CHECK_EQUAL(\"500\", eval(\"543.round(-1)\"));\n    BOOST_CHECK_EQUAL(\"600\", eval(\"566.round(-1)\"));\n    BOOST_CHECK_EQUAL(\"-500\", eval(\"-539.round(-1)\"));\n    BOOST_CHECK_EQUAL(\"-500\", eval(\"-543.round(-1)\"));\n    BOOST_CHECK_EQUAL(\"-600\", eval(\"-566.round(-1)\"));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n", "meta": {"hexsha": "06e4b224aec02ce40f3a414ff152050e650dbbc9", "size": 5572, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/types/Number.cpp", "max_stars_repo_name": "wnewbery/cpp-slim", "max_stars_repo_head_hexsha": "c7087294b55db5d7ca846438ebddfaec395d1a12", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-12-24T23:35:04.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-16T09:35:46.000Z", "max_issues_repo_path": "tests/types/Number.cpp", "max_issues_repo_name": "wnewbery/cpp-slim", "max_issues_repo_head_hexsha": "c7087294b55db5d7ca846438ebddfaec395d1a12", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 98.0, "max_issues_repo_issues_event_min_datetime": "2016-07-01T14:55:03.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-13T14:12:49.000Z", "max_forks_repo_path": "tests/types/Number.cpp", "max_forks_repo_name": "wnewbery/cpp-slim", "max_forks_repo_head_hexsha": "c7087294b55db5d7ca846438ebddfaec395d1a12", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-04-03T12:16:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-13T14:13:25.000Z", "avg_line_length": 37.1466666667, "max_line_length": 85, "alphanum_fraction": 0.6293969849, "num_tokens": 1589, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115012, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.48815264146035725}}
{"text": "/**\n * @file lin_alg_test.cpp\n * @author Ryan Curtin\n *\n * Simple tests for things in the linalg__private namespace.\n * Partly so I can be sure that my changes are working.\n * Move to boost unit testing framework at some point.\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#include <mlpack/core.hpp>\n#include <mlpack/core/math/lin_alg.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n\nusing namespace arma;\nusing namespace mlpack;\nusing namespace mlpack::math;\n\nBOOST_AUTO_TEST_SUITE(LinAlgTest);\n\n/**\n * Test for linalg__private::Center().  There are no edge cases here, so we'll\n * just try it once for now.\n */\nBOOST_AUTO_TEST_CASE(TestCenterA)\n{\n  mat tmp(5, 5);\n  // [[0  0  0  0  0]\n  //  [1  2  3  4  5]\n  //  [2  4  6  8  10]\n  //  [3  6  9  12 15]\n  //  [4  8  12 16 20]]\n  for (int row = 0; row < 5; row++)\n    for (int col = 0; col < 5; col++)\n      tmp(row, col) = row * (col + 1);\n\n  mat tmp_out;\n  Center(tmp, tmp_out);\n\n  // average should be\n  // [[0 3 6 9 12]]'\n  // so result should be\n  // [[ 0  0  0  0  0]\n  //  [-2 -1  0  1  2 ]\n  //  [-4 -2  0  2  4 ]\n  //  [-6 -3  0  3  6 ]\n  //  [-8 -4  0  4  8]]\n  for (int row = 0; row < 5; row++)\n    for (int col = 0; col < 5; col++)\n      BOOST_REQUIRE_CLOSE(tmp_out(row, col), (double) (col - 2) * row, 1e-5);\n}\n\nBOOST_AUTO_TEST_CASE(TestCenterB)\n{\n  mat tmp(5, 6);\n  for (int row = 0; row < 5; row++)\n    for (int col = 0; col < 6; col++)\n      tmp(row, col) = row * (col + 1);\n\n  mat tmp_out;\n  Center(tmp, tmp_out);\n\n  // average should be\n  // [[0 3.5 7 10.5 14]]'\n  // so result should be\n  // [[ 0    0    0   0   0   0  ]\n  //  [-2.5 -1.5 -0.5 0.5 1.5 2.5]\n  //  [-5   -3   -1   1   3   5  ]\n  //  [-7.5 -4.5 -1.5 1.5 1.5 4.5]\n  //  [-10  -6   -2   2   6   10 ]]\n  for (int row = 0; row < 5; row++)\n    for (int col = 0; col < 6; col++)\n      BOOST_REQUIRE_CLOSE(tmp_out(row, col), (double) (col - 2.5) * row, 1e-5);\n}\n\nBOOST_AUTO_TEST_CASE(TestWhitenUsingEig)\n{\n  // After whitening using eigendecomposition, the covariance of\n  // our matrix will be I (or something very close to that).\n  // We are loading a matrix from an external file... bad choice.\n  mat tmp, tmp_centered, whitened, whitening_matrix;\n\n  data::Load(\"trainSet.csv\", tmp);\n  Center(tmp, tmp_centered);\n  WhitenUsingEig(tmp_centered, whitened, whitening_matrix);\n\n  mat newcov = ccov(whitened);\n  for (int row = 0; row < 5; row++)\n  {\n    for (int col = 0; col < 5; col++)\n    {\n      if (row == col)\n      {\n        // diagonal will be 0 in the case of any zero-valued eigenvalues\n        // (rank-deficient covariance case)\n        if (std::abs(newcov(row, col)) > 1e-10)\n          BOOST_REQUIRE_CLOSE(newcov(row, col), 1.0, 1e-10);\n      }\n      else\n      {\n        BOOST_REQUIRE_SMALL(newcov(row, col), 1e-10);\n      }\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE(TestOrthogonalize)\n{\n  // Generate a random matrix; then, orthogonalize it and test if it's\n  // orthogonal.\n  mat tmp, orth;\n  data::Load(\"fake.csv\", tmp);\n  Orthogonalize(tmp, orth);\n\n  // test orthogonality\n  mat test = ccov(orth);\n  double ival = test(0, 0);\n  for (size_t row = 0; row < test.n_rows; row++)\n  {\n    for (size_t col = 0; col < test.n_cols; col++)\n    {\n      if (row == col)\n      {\n        if (std::abs(test(row, col)) > 1e-10)\n          BOOST_REQUIRE_CLOSE(test(row, col), ival, 1e-10);\n      }\n      else\n      {\n        BOOST_REQUIRE_SMALL(test(row, col), 1e-10);\n      }\n    }\n  }\n}\n\n// Test RemoveRows().\nBOOST_AUTO_TEST_CASE(TestRemoveRows)\n{\n  // Run this test several times.\n  for (size_t run = 0; run < 10; ++run)\n  {\n    arma::mat input;\n    input.randu(200, 200);\n\n    // Now pick some random numbers.\n    std::vector<size_t> rowsToRemove;\n    size_t row = 0;\n    while (row < 200)\n    {\n      row += RandInt(1, (2 * (run + 1) + 1));\n      if (row < 200)\n      {\n        rowsToRemove.push_back(row);\n      }\n    }\n\n    // Ensure we're not about to remove every single row.\n    if (rowsToRemove.size() == 10)\n    {\n      rowsToRemove.erase(rowsToRemove.begin() + 4); // Random choice to remove.\n    }\n\n    arma::mat output;\n    RemoveRows(input, rowsToRemove, output);\n\n    // Now check that the output is right.\n    size_t outputRow = 0;\n    size_t skipIndex = 0;\n\n    for (row = 0; row < 200; ++row)\n    {\n      // Was this row supposed to be removed?  If so skip it.\n      if ((skipIndex < rowsToRemove.size()) && (rowsToRemove[skipIndex] == row))\n      {\n        ++skipIndex;\n      }\n      else\n      {\n        // Compare.\n        BOOST_REQUIRE_EQUAL(accu(input.row(row) == output.row(outputRow)), 200);\n\n        // Increment output row counter.\n        ++outputRow;\n      }\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE(TestSvecSmat)\n{\n  arma::mat X(3, 3);\n  X(0, 0) = 0; X(0, 1) = 1, X(0, 2) = 2;\n  X(1, 0) = 1; X(1, 1) = 3, X(1, 2) = 4;\n  X(2, 0) = 2; X(2, 1) = 4, X(2, 2) = 5;\n\n  arma::vec sx;\n  Svec(X, sx);\n  BOOST_REQUIRE_CLOSE(sx(0), 0, 1e-7);\n  BOOST_REQUIRE_CLOSE(sx(1), M_SQRT2 * 1., 1e-7);\n  BOOST_REQUIRE_CLOSE(sx(2), M_SQRT2 * 2., 1e-7);\n  BOOST_REQUIRE_CLOSE(sx(3), 3., 1e-7);\n  BOOST_REQUIRE_CLOSE(sx(4), M_SQRT2 * 4., 1e-7);\n  BOOST_REQUIRE_CLOSE(sx(5), 5., 1e-7);\n\n  arma::mat Xtest;\n  Smat(sx, Xtest);\n  BOOST_REQUIRE_EQUAL(Xtest.n_rows, 3);\n  BOOST_REQUIRE_EQUAL(Xtest.n_cols, 3);\n  for (size_t i = 0; i < 3; i++)\n    for (size_t j = 0; j < 3; j++)\n      BOOST_REQUIRE_CLOSE(X(i, j), Xtest(i, j), 1e-7);\n}\n\nBOOST_AUTO_TEST_CASE(TestSparseSvec)\n{\n  arma::sp_mat X;\n  X.zeros(3, 3);\n  X(1, 0) = X(0, 1) = 1;\n\n  arma::sp_vec sx;\n  Svec(X, sx);\n\n  const double v0 = sx(0);\n  const double v1 = sx(1);\n  const double v2 = sx(2);\n  const double v3 = sx(3);\n  const double v4 = sx(4);\n  const double v5 = sx(5);\n\n  BOOST_REQUIRE_CLOSE(v0, 0, 1e-7);\n  BOOST_REQUIRE_CLOSE(v1, M_SQRT2 * 1., 1e-7);\n  BOOST_REQUIRE_CLOSE(v2, 0, 1e-7);\n  BOOST_REQUIRE_CLOSE(v3, 0, 1e-7);\n  BOOST_REQUIRE_CLOSE(v4, 0, 1e-7);\n  BOOST_REQUIRE_CLOSE(v5, 0, 1e-7);\n}\n\nBOOST_AUTO_TEST_CASE(TestSymKronIdSimple)\n{\n  arma::mat A(3, 3);\n  A(0, 0) = 1; A(0, 1) = 2, A(0, 2) = 3;\n  A(1, 0) = 2; A(1, 1) = 4, A(1, 2) = 5;\n  A(2, 0) = 3; A(2, 1) = 5, A(2, 2) = 6;\n  arma::mat Op;\n  SymKronId(A, Op);\n\n  const arma::mat X = A + arma::ones<arma::mat>(3, 3);\n  arma::vec sx;\n  Svec(X, sx);\n\n  const arma::vec lhs = Op * sx;\n  const arma::mat Rhs = 0.5 * (A * X + X * A);\n  arma::vec rhs;\n  Svec(Rhs, rhs);\n\n  BOOST_REQUIRE_EQUAL(lhs.n_elem, rhs.n_elem);\n  for (size_t j = 0; j < lhs.n_elem; j++)\n    BOOST_REQUIRE_CLOSE(lhs(j), rhs(j), 1e-5);\n}\n\nBOOST_AUTO_TEST_CASE(TestSymKronId)\n{\n  const size_t n = 10;\n  arma::mat A = arma::randu<arma::mat>(n, n);\n  A += A.t();\n\n  arma::mat Op;\n  SymKronId(A, Op);\n\n  for (size_t i = 0; i < 5; i++)\n  {\n    arma::mat X = arma::randu<arma::mat>(n, n);\n    X += X.t();\n    arma::vec sx;\n    Svec(X, sx);\n\n    const arma::vec lhs = Op * sx;\n    const arma::mat Rhs = 0.5 * (A * X + X * A);\n    arma::vec rhs;\n    Svec(Rhs, rhs);\n\n    BOOST_REQUIRE_EQUAL(lhs.n_elem, rhs.n_elem);\n    for (size_t j = 0; j < lhs.n_elem; j++)\n      BOOST_REQUIRE_CLOSE(lhs(j), rhs(j), 1e-5);\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "0e335049c962d28fd7d2aedaf3284400cbcd041f", "size": 7310, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/lin_alg_test.cpp", "max_stars_repo_name": "RMaron/mlpack", "max_stars_repo_head_hexsha": "a179a2708d9555ab7ee4b1e90e0c290092edad2e", "max_stars_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-01-04T04:20:29.000Z", "max_stars_repo_stars_event_max_datetime": "2016-07-21T23:30:34.000Z", "max_issues_repo_path": "src/mlpack/tests/lin_alg_test.cpp", "max_issues_repo_name": "RMaron/mlpack", "max_issues_repo_head_hexsha": "a179a2708d9555ab7ee4b1e90e0c290092edad2e", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2017-01-23T18:39:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-15T13:58:34.000Z", "max_forks_repo_path": "src/mlpack/tests/lin_alg_test.cpp", "max_forks_repo_name": "RMaron/mlpack", "max_forks_repo_head_hexsha": "a179a2708d9555ab7ee4b1e90e0c290092edad2e", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-01-20T00:54:34.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-16T05:34:32.000Z", "avg_line_length": 24.9488054608, "max_line_length": 80, "alphanum_fraction": 0.5730506156, "num_tokens": 2716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.48815263769930406}}
{"text": "#include <iostream>\n#include \"gtest/gtest.h\"\n#include <Eigen/Core>\n#include \"mean_curvature_solver.h\"\n#include \"uniform_lb_operator.h\"\n#include \"cotangent_lb_operator.h\"\n\nclass MeanCurvatureSolverTest : public ::testing::Test {\nprotected:\n    MeanCurvatureSolverTest() : mUnifromMCS(mcurv::uniformLBOperatorStrategy),\n                                mCotangentMCS(mcurv::cotangentLBOperatorStrategy),\n                                mBunnyPath(\"./res/bunny.off\") {}\n\n    Eigen::MatrixXd mSolution;\n    const std::string mBunnyPath;\n    mcurv::MeanCurvatureSolver mUnifromMCS;\n    mcurv::MeanCurvatureSolver mCotangentMCS;\n};\n\nTEST_F(MeanCurvatureSolverTest, WrongPathForExecute) {\n    ASSERT_THROW(mUnifromMCS.Execute(mSolution, \"wrong_path\"), std::runtime_error);\n    ASSERT_THROW(mCotangentMCS.Execute(mSolution, \"wrong_path\"), std::runtime_error);\n}\n\nTEST_F(MeanCurvatureSolverTest, ExecUniform) {\n    mUnifromMCS.Execute(mSolution, mBunnyPath);\n\n    EXPECT_NEAR(mSolution(0,0), 0.0065769, 0.001);\n    EXPECT_NEAR(mSolution(1,0), -0.00329001, 0.001);\n    EXPECT_NEAR(mSolution(2,0), -0.00750467, 0.001);\n}\n\nTEST_F(MeanCurvatureSolverTest, ExecCotangent) {\n    mCotangentMCS.Execute(mSolution, mBunnyPath);\n\n    EXPECT_NEAR(mSolution(0,0), 66.2739, 0.001);\n    EXPECT_NEAR(mSolution(1,0), -555.572, 0.001);\n    EXPECT_NEAR(mSolution(2,0), -76.9057, 0.001);\n}", "meta": {"hexsha": "f2bb1a16f9f2c3b52f07ba58aa8a511e9870093c", "size": 1360, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "testing/unit_tests/test_mean_curvature_solver.cpp", "max_stars_repo_name": "dybiszb/MeanCurvatureLibrary", "max_stars_repo_head_hexsha": "b168911ef6bf08b283e7a225cc006b850fe26400", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "testing/unit_tests/test_mean_curvature_solver.cpp", "max_issues_repo_name": "dybiszb/MeanCurvatureLibrary", "max_issues_repo_head_hexsha": "b168911ef6bf08b283e7a225cc006b850fe26400", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-11-14T23:14:58.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-14T23:14:58.000Z", "max_forks_repo_path": "testing/unit_tests/test_mean_curvature_solver.cpp", "max_forks_repo_name": "dybiszb/MeanCurvatureLibrary", "max_forks_repo_head_hexsha": "b168911ef6bf08b283e7a225cc006b850fe26400", "max_forks_repo_licenses": ["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.8717948718, "max_line_length": 85, "alphanum_fraction": 0.7161764706, "num_tokens": 407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339837155239, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4881399600528955}}
{"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 \"lgm.hpp\"\n#include \"utilities.hpp\"\n#include <ql/indexes/ibor/euribor.hpp>\n#include <ql/instruments/vanillaoption.hpp>\n#include <ql/models/shortrate/onefactormodels/gsr.hpp>\n#include <ql/models/shortrate/calibrationhelpers/swaptionhelper.hpp>\n#include <ql/math/statistics/incrementalstatistics.hpp>\n#include <ql/math/optimization/levenbergmarquardt.hpp>\n#include <ql/math/randomnumbers/rngtraits.hpp>\n#include <ql/methods/montecarlo/multipathgenerator.hpp>\n#include <ql/methods/montecarlo/pathgenerator.hpp>\n#include <ql/pricingengines/swaption/gaussian1dswaptionengine.hpp>\n#include <ql/termstructures/yield/flatforward.hpp>\n#include <ql/time/calendars/target.hpp>\n#include <ql/time/daycounters/actual360.hpp>\n#include <ql/time/daycounters/thirty360.hpp>\n#include <ql/quotes/simplequote.hpp>\n#include <ql/experimental/models/lgm1.hpp>\n#include <ql/experimental/models/cclgm1.hpp>\n#include <ql/experimental/models/cclgmanalyticfxoptionengine.hpp>\n#include <ql/experimental/models/fxoptionhelper.hpp>\n\n#include <boost/make_shared.hpp>\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/mean.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/error_of_mean.hpp>\n\nusing namespace QuantLib;\nusing boost::unit_test_framework::test_suite;\nusing namespace boost::accumulators;\n\nvoid LgmTest::testBermudanLgm1fGsr() {\n\n    BOOST_TEST_MESSAGE(\"Testing consistency of Bermudan swaption pricing in \"\n                       \"LGM1F and GSR models...\");\n\n    // for kappa (LGM) = reversion (GSR) = 0.0\n    // we have alpha (LGM) = sigma (GSR), so\n    // we should get equal Bermudan swaption prices\n\n    SavedSettings backup;\n\n    Date evalDate(12, January, 2015);\n    Settings::instance().evaluationDate() = evalDate;\n    Handle<YieldTermStructure> yts(\n        boost::make_shared<FlatForward>(evalDate, 0.02, Actual365Fixed()));\n    boost::shared_ptr<IborIndex> euribor6m =\n        boost::make_shared<Euribor>(6 * Months, yts);\n\n    Date effectiveDate = TARGET().advance(evalDate, 2 * Days);\n    Date startDate = TARGET().advance(effectiveDate, 1 * Years);\n    Date maturityDate = TARGET().advance(startDate, 9 * Years);\n\n    Schedule fixedSchedule(startDate, maturityDate, 1 * Years, TARGET(),\n                           ModifiedFollowing, ModifiedFollowing,\n                           DateGeneration::Forward, false);\n    Schedule floatingSchedule(startDate, maturityDate, 6 * Months, TARGET(),\n                              ModifiedFollowing, ModifiedFollowing,\n                              DateGeneration::Forward, false);\n    boost::shared_ptr<VanillaSwap> underlying = boost::make_shared<VanillaSwap>(\n        VanillaSwap(VanillaSwap::Payer, 1.0, fixedSchedule, 0.02, Thirty360(),\n                    floatingSchedule, euribor6m, 0.0, Actual360()));\n\n    std::vector<Date> exerciseDates;\n    for (Size i = 0; i < 9; ++i) {\n        exerciseDates.push_back(TARGET().advance(fixedSchedule[i], -2 * Days));\n    }\n    boost::shared_ptr<Exercise> exercise =\n        boost::make_shared<BermudanExercise>(exerciseDates, false);\n\n    boost::shared_ptr<Swaption> swaption =\n        boost::make_shared<Swaption>(underlying, exercise);\n\n    std::vector<Date> stepDates(exerciseDates.begin(), exerciseDates.end() - 1);\n    std::vector<Real> sigmas(stepDates.size() + 1);\n    for (Size i = 0; i < sigmas.size(); ++i) {\n        sigmas[i] = 0.0050 +\n                    (0.0080 - 0.0050) * std::exp(-0.2 * static_cast<double>(i));\n    }\n\n    Real reversion = 0.0;\n\n    // fix any T forward measure\n    boost::shared_ptr<Gsr> gsr =\n        boost::make_shared<Gsr>(yts, stepDates, sigmas, reversion, 50.0);\n\n    boost::shared_ptr<Lgm1> lgm =\n        boost::make_shared<Lgm1>(yts, stepDates, sigmas, reversion);\n\n    boost::shared_ptr<PricingEngine> swaptionEngineGsr =\n        boost::make_shared<Gaussian1dSwaptionEngine>(gsr, 64, 7.0, true, false);\n\n    boost::shared_ptr<PricingEngine> swaptionEngineLgm =\n        boost::make_shared<Gaussian1dSwaptionEngine>(lgm, 64, 7.0, true, false);\n\n    swaption->setPricingEngine(swaptionEngineGsr);\n    Real npvGsr = swaption->NPV();\n    swaption->setPricingEngine(swaptionEngineLgm);\n    Real npvLgm = swaption->NPV();\n\n    Real tol = 0.05E-4; // basis point tolerance\n\n    if (std::fabs(npvGsr - npvLgm) > tol)\n        BOOST_ERROR(\n            \"Failed to verify consistency of Bermudan swaption price in Lgm1f (\"\n            << npvLgm << \") and Gsr (\" << npvGsr << \") models, tolerance is \"\n            << tol);\n} // testBermudanLgm1fGsr\n\nvoid LgmTest::testLgm1fCalibration() {\n\n    BOOST_TEST_MESSAGE(\n        \"Testing calibration of LGM1F model against GSR parameters...\");\n\n    // for fixed kappa != 0.0 we calibrate alpha\n    // and compare the effective Hull White parameters\n    // with the calibration results for the Gsr model\n\n    SavedSettings backup;\n\n    Date evalDate(12, January, 2015);\n    Settings::instance().evaluationDate() = evalDate;\n    Handle<YieldTermStructure> yts(\n        boost::make_shared<FlatForward>(evalDate, 0.02, Actual365Fixed()));\n    boost::shared_ptr<IborIndex> euribor6m =\n        boost::make_shared<Euribor>(6 * Months, yts);\n\n    // coterminal basket 1y-9y, 2y-8y, ... 9y-1y\n\n    std::vector<boost::shared_ptr<CalibrationHelper> > basket;\n    Real impliedVols[] = {0.4, 0.39, 0.38, 0.35, 0.35, 0.34, 0.33, 0.32, 0.31};\n    std::vector<Date> expiryDates;\n\n    for (Size i = 0; i < 9; ++i) {\n        boost::shared_ptr<CalibrationHelper> helper =\n            boost::make_shared<SwaptionHelper>(\n                (i + 1) * Years, (9 - i) * Years,\n                Handle<Quote>(boost::make_shared<SimpleQuote>(impliedVols[i])),\n                euribor6m, 1 * Years, Thirty360(), Actual360(), yts);\n        basket.push_back(helper);\n        expiryDates.push_back(boost::static_pointer_cast<SwaptionHelper>(helper)\n                                  ->swaption()\n                                  ->exercise()\n                                  ->dates()\n                                  .back());\n    }\n\n    std::vector<Date> stepDates(expiryDates.begin(), expiryDates.end() - 1);\n\n    std::vector<Real> gsrInitialSigmas(stepDates.size() + 1, 0.0050);\n    std::vector<Real> lgmInitialAlphas(stepDates.size() + 1, 0.0050);\n\n    Real kappa = 0.05;\n\n    // fix any T forward measure\n    boost::shared_ptr<Gsr> gsr =\n        boost::make_shared<Gsr>(yts, stepDates, gsrInitialSigmas, kappa, 50.0);\n\n    boost::shared_ptr<Lgm1> lgm =\n        boost::make_shared<Lgm1>(yts, stepDates, lgmInitialAlphas, kappa);\n\n    boost::shared_ptr<PricingEngine> swaptionEngineGsr =\n        boost::make_shared<Gaussian1dSwaptionEngine>(gsr, 64, 7.0, true, false);\n\n    boost::shared_ptr<PricingEngine> swaptionEngineLgm =\n        boost::make_shared<Gaussian1dSwaptionEngine>(lgm, 64, 7.0, true, false);\n\n    // calibrate GSR\n\n    LevenbergMarquardt lm(1E-8, 1E-8, 1E-8);\n    EndCriteria ec(1000, 500, 1E-8, 1E-8, 1E-8);\n\n    for (Size i = 0; i < basket.size(); ++i) {\n        basket[i]->setPricingEngine(swaptionEngineGsr);\n    }\n\n    gsr->calibrateVolatilitiesIterative(basket, lm, ec);\n\n    Array gsrSigmas = gsr->volatility();\n\n    // calibrate LGM\n\n    for (Size i = 0; i < basket.size(); ++i) {\n        basket[i]->setPricingEngine(swaptionEngineLgm);\n    }\n\n    lgm->calibrateAlphasIterative(basket, lm, ec);\n\n    std::vector<Real> lgmHwSigmas;\n    std::vector<Real> lgmHwKappas;\n\n    for (Size i = 0; i < gsrSigmas.size(); ++i) {\n        lgmHwSigmas.push_back(\n            lgm->hullWhiteSigma(static_cast<double>(i) + 0.5));\n        lgmHwKappas.push_back(\n            lgm->hullWhiteKappa(static_cast<double>(i) + 0.5));\n    }\n\n    Real tol0 = 1E-8;\n    Real tol = 1E-4;\n\n    for (Size i = 0; i < gsrSigmas.size(); ++i) {\n        // check calibration itself, we should match the market prices\n        // rather exactly\n        if (std::fabs(basket[i]->modelValue() - basket[i]->marketValue()) >\n            tol0)\n            BOOST_ERROR(\"Failed to calibrate to market swaption #\"\n                        << i << \", market price is \" << basket[i]->marketValue()\n                        << \" while model price is \" << basket[i]->modelValue());\n        // we can not directly compare the gsr model's sigma with\n        // the lgm model's equivalent HW sigma (since the former\n        // is piecewise constant, while the latter is not), but\n        // we can do a rough check on the mid point of each interval\n        if (std::fabs(gsrSigmas[i] - lgmHwSigmas[i]) > tol)\n            BOOST_ERROR(\"Failed to verify LGM's equivalent Hull White sigma (#\"\n                        << i << \"), which is \" << lgmHwSigmas[i]\n                        << \" while GSR's sigma is \" << gsrSigmas[i] << \")\");\n    }\n\n} // testLgm1fCalibration\n\nvoid LgmTest::testLgm3fForeignPayouts() {\n    BOOST_TEST_MESSAGE(\"Testing pricing of foreign payouts under domestic \"\n                       \"measure in LGM3F model...\");\n\n    SavedSettings backup;\n\n    Date referenceDate(30, July, 2015);\n\n    Settings::instance().evaluationDate() = referenceDate;\n\n    Handle<YieldTermStructure> eurYts(\n        boost::make_shared<FlatForward>(referenceDate, 0.02, Actual365Fixed()));\n\n    Handle<YieldTermStructure> usdYts(\n        boost::make_shared<FlatForward>(referenceDate, 0.05, Actual365Fixed()));\n\n    // use different grids for the EUR and USD  models and the FX volatility\n    // process to test the piecewise numerical integration ...\n\n    std::vector<Date> volstepdatesEur, volstepdatesUsd, volstepdatesFx;\n\n    volstepdatesEur.push_back(Date(15, July, 2016));\n    volstepdatesEur.push_back(Date(15, July, 2017));\n    volstepdatesEur.push_back(Date(15, July, 2018));\n    volstepdatesEur.push_back(Date(15, July, 2019));\n    volstepdatesEur.push_back(Date(15, July, 2020));\n\n    volstepdatesUsd.push_back(Date(13, April, 2016));\n    volstepdatesUsd.push_back(Date(13, September, 2016));\n    volstepdatesUsd.push_back(Date(13, April, 2017));\n    volstepdatesUsd.push_back(Date(13, September, 2017));\n    volstepdatesUsd.push_back(Date(13, April, 2018));\n    volstepdatesUsd.push_back(Date(15, July, 2018)); // shared with EUR\n    volstepdatesUsd.push_back(Date(13, April, 2019));\n    volstepdatesUsd.push_back(Date(13, September, 2019));\n\n    volstepdatesFx.push_back(Date(15, July, 2016)); // shared with EUR\n    volstepdatesFx.push_back(Date(15, October, 2016));\n    volstepdatesFx.push_back(Date(15, May, 2017));\n    volstepdatesFx.push_back(Date(13, September, 2017)); // shared with USD\n    volstepdatesFx.push_back(Date(15, July, 2018)); //  shared with EUR and USD\n\n    std::vector<Real> eurVols, usdVols, fxSigmas;\n\n    for (Size i = 0; i < volstepdatesEur.size() + 1; ++i) {\n        eurVols.push_back(0.0050 +\n                          (0.0080 - 0.0050) *\n                              std::exp(-0.3 * static_cast<double>(i)));\n    }\n    for (Size i = 0; i < volstepdatesUsd.size() + 1; ++i) {\n        usdVols.push_back(0.0030 +\n                          (0.0110 - 0.0030) *\n                              std::exp(-0.3 * static_cast<double>(i)));\n    }\n    for (Size i = 0; i < volstepdatesFx.size() + 1; ++i) {\n        fxSigmas.push_back(\n            0.15 + (0.20 - 0.15) * std::exp(-0.3 * static_cast<double>(i)));\n    }\n\n    boost::shared_ptr<Lgm1::model_type> eurLgm =\n        boost::make_shared<Lgm1>(eurYts, volstepdatesEur, eurVols, 0.02);\n    boost::shared_ptr<Lgm1::model_type> usdLgm =\n        boost::make_shared<Lgm1>(usdYts, volstepdatesUsd, usdVols, 0.04);\n\n    std::vector<boost::shared_ptr<Lgm1::model_type> > singleModels;\n    singleModels.push_back(eurLgm);\n    singleModels.push_back(usdLgm);\n\n    std::vector<Handle<YieldTermStructure> > curves;\n    curves.push_back(eurYts);\n    curves.push_back(usdYts);\n\n    std::vector<Handle<Quote> > fxSpots;\n    fxSpots.push_back(Handle<Quote>(boost::make_shared<SimpleQuote>(\n        std::log(0.90)))); // USD per EUR in log scale\n\n    std::vector<std::vector<Real> > fxVolatilities;\n    fxVolatilities.push_back(fxSigmas);\n\n    Matrix c(3, 3);\n    //  FX             EUR         USD\n    c[0][0] = 1.0; c[0][1] = 0.8; c[0][2] = -0.5; // FX\n    c[1][0] = 0.8; c[1][1] = 1.0; c[1][2] = -0.2; // EUR\n    c[2][0] = -0.5; c[2][1] = -0.2; c[2][2] = 1.0; // USD\n\n    boost::shared_ptr<CcLgm1> ccLgm = boost::make_shared<CcLgm1>(\n        singleModels, fxSpots, volstepdatesFx, fxVolatilities, c, curves);\n\n    boost::shared_ptr<StochasticProcess> process = ccLgm->stateProcess();\n\n    boost::shared_ptr<StochasticProcess> usdProcess = usdLgm->stateProcess();\n\n    // path generation\n\n    Size n = 500000; // number of paths\n    Size seed = 121; // seed\n    // maturity of test payoffs\n    Time T = 5.0;\n    // take large steps, but not only one (since we are testing)\n    Size steps = static_cast<Size>(T * 2.0);\n    TimeGrid grid(T, steps);\n    PseudoRandom::rsg_type sg =\n        PseudoRandom::make_sequence_generator(3 * steps, seed);\n    PseudoRandom::rsg_type sg2 =\n        PseudoRandom::make_sequence_generator(steps, seed);\n\n    MultiPathGenerator<PseudoRandom::rsg_type> pg(process, grid, sg, false);\n    PathGenerator<PseudoRandom::rsg_type> pg2(usdProcess, grid, sg2, false);\n\n    // test\n    // 1 deterministic USD cashflow under EUR numeraire vs. price on USD curve\n    // 2 zero bond option USD under EUR numeraire vs. USD numeraire\n    // 3 fx option USD-EUR under EUR numeraire vs. analytical price\n\n    accumulator_set<double, stats<tag::mean, tag::error_of<tag::mean> > > stat1,\n        stat2a, stat2b, stat3;\n\n    // same for paths2 since shared time grid\n    for (Size j = 0; j < n; ++j) {\n        Sample<MultiPath> path = pg.next();\n        Sample<Path> path2 = pg2.next();\n        Size l = path.value[0].length() - 1;\n        Real fx = std::exp(path.value[0][l]);\n        Real zeur = path.value[1][l];\n        Real zusd = path.value[2][l];\n        Real zusd2 = path2.value[l];\n        Real yeur = (zeur - eurLgm->stateProcess()->expectation(0.0, 0.0, T)) /\n                    eurLgm->stateProcess()->stdDeviation(0.0, 0.0, T);\n        Real yusd = (zusd - usdLgm->stateProcess()->expectation(0.0, 0.0, T)) /\n                    usdLgm->stateProcess()->stdDeviation(0.0, 0.0, T);\n        Real yusd2 =\n            (zusd2 - usdLgm->stateProcess()->expectation(0.0, 0.0, T)) /\n            usdLgm->stateProcess()->stdDeviation(0.0, 0.0, T);\n\n        // 1 USD paid at T deflated with EUR numeraire\n        stat1(1.0 * fx / eurLgm->numeraire(T, yeur));\n\n        // 2 USD zero bond option at T on P(T,T+10) strike 0.5 ...\n        // ... under EUR numeraire ...\n        Real zbOpt = std::max(usdLgm->zerobond(T + 10.0, T, yusd) - 0.5, 0.0);\n        stat2a(zbOpt * fx / eurLgm->numeraire(T, yeur));\n        // ... and under USD numeraire ...\n        Real zbOpt2 = std::max(usdLgm->zerobond(T + 10.0, T, yusd2) - 0.5, 0.0);\n        stat2b(zbOpt2 / usdLgm->numeraire(T, yusd2));\n\n        // 3 USD-EUR fx option @0.9\n        stat3(std::max(fx - 0.9, 0.0) / eurLgm->numeraire(T, yeur));\n    }\n\n    boost::shared_ptr<VanillaOption> fxOption =\n        boost::make_shared<VanillaOption>(\n            boost::make_shared<PlainVanillaPayoff>(Option::Call, 0.9),\n            boost::make_shared<EuropeanExercise>(referenceDate + 5 * 365));\n\n    boost::shared_ptr<PricingEngine> ccLgmFxOptionEngine =\n        boost::make_shared<CcLgmAnalyticFxOptionEngine<\n            CcLgm1::cclgm_model_type, CcLgm1::lgmfx_model_type,\n            CcLgm1::lgm_model_type> >(ccLgm, 0);\n\n    fxOption->setPricingEngine(ccLgmFxOptionEngine);\n\n    Real npv1 = mean(stat1);\n    Real error1 = error_of<tag::mean>(stat1);\n    Real expected1 = usdYts->discount(5.0) * std::exp(fxSpots[0]->value());\n    Real npv2a = mean(stat2a);\n    Real error2a = error_of<tag::mean>(stat2a);\n    Real npv2b = mean(stat2b) * std::exp(fxSpots[0]->value());\n    Real error2b = error_of<tag::mean>(stat2b) * std::exp(fxSpots[0]->value());\n    Real npv3 = mean(stat3);\n    Real error3 = error_of<tag::mean>(stat3);\n\n    // accept this relative difference in error estimates\n    Real tolError = 0.2;\n    // accept tolErrEst*errorEstimate as absolute difference\n    Real tolErrEst = 1.0;\n\n    if (std::fabs((error1 - 4E-4) / 4E-4) > tolError)\n        BOOST_ERROR(\"error estimate deterministic \"\n                    \"cashflow pricing can not be \"\n                    \"reproduced, is \"\n                    << error1\n                    << \", expected 4E-4, relative tolerance \"\n                    << tolError);\n    if (std::fabs((error2a - 1E-4) / 1E-4) > tolError)\n        BOOST_ERROR(\"error estimate zero bond \"\n                    \"option pricing (foreign measure) can \"\n                    \"not be reproduced, is \"\n                    << error2a\n                    << \", expected 1E-4, relative tolerance \"\n                    << tolError);\n    if (std::fabs((error2b - 7E-5) / 7E-5) > tolError)\n        BOOST_ERROR(\"error estimate zero bond \"\n                    \"option pricing (domestic measure) can \"\n                    \"not be reproduced, is \"\n                    << error2b\n                    << \", expected 7E-5, relative tolerance \"\n                    << tolError);\n    if (std::fabs((error3 - 2.7E-4) / 2.7E-4) > tolError)\n        BOOST_ERROR(\n            \"error estimate fx option pricing can not be reproduced, is \"\n            << error3 << \", expected 2.7E-4, relative tolerance \" << tolError);\n\n    if (std::fabs(npv1 - expected1) > tolErrEst * error1)\n        BOOST_ERROR(\"can no reproduce deterministic cashflow pricing, is \"\n                    << npv1 << \", expected \" << expected1 << \", tolerance \"\n                    << tolErrEst << \"*\" << error1);\n\n    if (std::fabs(npv2a - npv2b) >\n        tolErrEst * std::sqrt(error2a * error2a + error2b * error2b))\n        BOOST_ERROR(\"can no reproduce zero bond option pricing, domestic \"\n                    \"measure result is \"\n                    << npv2a\n                    << \", foreign measure result is \"\n                    << npv2b\n                    << \", tolerance \"\n                    << tolErrEst\n                    << \"*\"\n                    << std::sqrt(error2a * error2a + error2b * error2b));\n\n    if (std::fabs(npv3 - fxOption->NPV()) > tolErrEst * std::sqrt(error3))\n        BOOST_ERROR(\"can no reproduce fx option pricing, monte carlo result is \"\n                    << npv3 << \", analytical pricing result is \"\n                    << fxOption->NPV() << \", tolerance is \" << tolErrEst << \"*\"\n                    << error3);\n\n} // testLgm3fForeignPayouts\n\nvoid LgmTest::testLgm4fAndFxCalibration() {\n    BOOST_TEST_MESSAGE(\"Testing LGM4F model and fx calibration...\");\n\n    SavedSettings backup;\n\n    Date referenceDate(30, July, 2015);\n\n    Settings::instance().evaluationDate() = referenceDate;\n\n    Handle<YieldTermStructure> eurYts(\n        boost::make_shared<FlatForward>(referenceDate, 0.02, Actual365Fixed()));\n    Handle<YieldTermStructure> usdYts(\n        boost::make_shared<FlatForward>(referenceDate, 0.05, Actual365Fixed()));\n    Handle<YieldTermStructure> gbpYts(\n        boost::make_shared<FlatForward>(referenceDate, 0.04, Actual365Fixed()));\n\n    std::vector<Date> volstepdates, volstepdatesFx;\n\n    volstepdates.push_back(Date(15, July, 2016));\n    volstepdates.push_back(Date(15, July, 2017));\n    volstepdates.push_back(Date(15, July, 2018));\n    volstepdates.push_back(Date(15, July, 2019));\n    volstepdates.push_back(Date(15, July, 2020));\n\n    volstepdatesFx.push_back(Date(15, July, 2016));\n    volstepdatesFx.push_back(Date(15, October, 2016));\n    volstepdatesFx.push_back(Date(15, May, 2017));\n    volstepdatesFx.push_back(Date(13, September, 2017));\n    volstepdatesFx.push_back(Date(15, July, 2018));\n\n    std::vector<Real> eurVols, usdVols, gbpVols, fxSigmasUsd, fxSigmasGbp;\n\n    for (Size i = 0; i < volstepdates.size() + 1; ++i) {\n        eurVols.push_back(0.0050 +\n                          (0.0080 - 0.0050) *\n                              std::exp(-0.3 * static_cast<double>(i)));\n    }\n    for (Size i = 0; i < volstepdates.size() + 1; ++i) {\n        usdVols.push_back(0.0030 +\n                          (0.0110 - 0.0030) *\n                              std::exp(-0.3 * static_cast<double>(i)));\n    }\n    for (Size i = 0; i < volstepdates.size() + 1; ++i) {\n        gbpVols.push_back(0.0070 +\n                          (0.0095 - 0.0070) *\n                              std::exp(-0.3 * static_cast<double>(i)));\n    }\n    for (Size i = 0; i < volstepdatesFx.size() + 1; ++i) {\n        fxSigmasUsd.push_back(\n            0.15 + (0.20 - 0.15) * std::exp(-0.3 * static_cast<double>(i)));\n    }\n    for (Size i = 0; i < volstepdatesFx.size() + 1; ++i) {\n        fxSigmasGbp.push_back(\n            0.10 + (0.15 - 0.10) * std::exp(-0.3 * static_cast<double>(i)));\n    }\n\n    boost::shared_ptr<Lgm1::model_type> eurLgm =\n        boost::make_shared<Lgm1>(eurYts, volstepdates, eurVols, 0.02);\n    boost::shared_ptr<Lgm1::model_type> usdLgm =\n        boost::make_shared<Lgm1>(usdYts, volstepdates, usdVols, 0.03);\n    boost::shared_ptr<Lgm1::model_type> gbpLgm =\n        boost::make_shared<Lgm1>(usdYts, volstepdates, gbpVols, 0.04);\n\n    std::vector<boost::shared_ptr<Lgm1::model_type> > singleModels;\n    singleModels.push_back(eurLgm);\n    singleModels.push_back(usdLgm);\n    singleModels.push_back(gbpLgm);\n\n    // we test the 4f model against the 3f model eur-gbp\n    std::vector<boost::shared_ptr<Lgm1::model_type> > singleModelsProjected;\n    singleModelsProjected.push_back(eurLgm);\n    singleModelsProjected.push_back(gbpLgm);\n\n    std::vector<Handle<YieldTermStructure> > curves;\n    curves.push_back(eurYts);\n    curves.push_back(usdYts);\n    curves.push_back(gbpYts);\n\n    std::vector<Handle<YieldTermStructure> > curvesProjected;\n    curvesProjected.push_back(eurYts);\n    curvesProjected.push_back(gbpYts);\n\n    std::vector<Handle<Quote> > fxSpots;\n    fxSpots.push_back(Handle<Quote>(boost::make_shared<SimpleQuote>(\n        std::log(0.90)))); // EUR per one unit of USD in log scale\n    fxSpots.push_back(Handle<Quote>(boost::make_shared<SimpleQuote>(\n        std::log(1.35)))); // EUR per one unit of GBP in log scale\n\n    std::vector<Handle<Quote> > fxSpotsProjected;\n    fxSpotsProjected.push_back(fxSpots[1]);\n\n    std::vector<std::vector<Real> > fxVolatilities;\n    fxVolatilities.push_back(fxSigmasUsd);\n    fxVolatilities.push_back(fxSigmasGbp);\n\n    std::vector<std::vector<Real> > fxVolatilitiesProjected;\n    fxVolatilitiesProjected.push_back(fxSigmasGbp);\n\n    Matrix c(5, 5);\n    //  FX USD-EUR      FX GBP-EUR     EUR           USD             GBP\n    c[0][0] = 1.0;  c[0][1]= 0.3;   c[0][2] = 0.2; c[0][3] = -0.2; c[0][4]=0.0;  // FX USD-EUR\n    c[1][0] = 0.3;  c[1][1]= 1.0;   c[1][2] = 0.3; c[1][3] = -0.1; c[1][4]=0.1;  // FX GBP-EUR\n    c[2][0] = 0.2;  c[2][1]= 0.3;   c[2][2] = 1.0; c[2][3] = 0.6;  c[2][4]=0.3;  // EUR\n    c[3][0] = -0.2; c[3][1]=-0.1;   c[3][2] = 0.6; c[3][3] = 1.0;  c[3][4]=0.1;  // USD\n    c[4][0] = 0.0;  c[4][1]= 0.1;   c[4][2] = 0.3; c[4][3] = 0.1;  c[4][4]=1.0;  // GBP\n\n    Matrix cProjected(3, 3);\n    for (Size i = 0, ii = 0; i < 5; ++i) {\n        if (i != 0 && i != 3) {\n            for (Size j = 0, jj = 0; j < 5; ++j) {\n                if (j != 0 && j != 3)\n                    cProjected[ii][jj++] = c[i][j];\n            }\n            ++ii;\n        }\n    }\n\n    boost::shared_ptr<CcLgm1> ccLgm = boost::make_shared<CcLgm1>(\n        singleModels, fxSpots, volstepdatesFx, fxVolatilities, c, curves);\n\n    boost::shared_ptr<CcLgm1> ccLgmProjected = boost::make_shared<CcLgm1>(\n        singleModelsProjected, fxSpotsProjected, volstepdatesFx,\n        fxVolatilitiesProjected, cProjected, curvesProjected);\n\n    boost::shared_ptr<PricingEngine> ccLgmFxOptionEngineUsd =\n        boost::make_shared<CcLgmAnalyticFxOptionEngine<\n            CcLgm1::cclgm_model_type, CcLgm1::lgmfx_model_type,\n            CcLgm1::lgm_model_type> >(ccLgm, 0);\n\n    boost::shared_ptr<PricingEngine> ccLgmFxOptionEngineGbp =\n        boost::make_shared<CcLgmAnalyticFxOptionEngine<\n            CcLgm1::cclgm_model_type, CcLgm1::lgmfx_model_type,\n            CcLgm1::lgm_model_type> >(ccLgm, 1);\n\n    boost::shared_ptr<PricingEngine> ccLgmProjectedFxOptionEngineGbp =\n        boost::make_shared<CcLgmAnalyticFxOptionEngine<\n            CcLgm1::cclgm_model_type, CcLgm1::lgmfx_model_type,\n            CcLgm1::lgm_model_type> >(ccLgmProjected, 0);\n\n    // while the initial fx vol starts at 0.2 for usd and 0.15 for gbp\n    // we calibrate to helpers with 0.15 and 0.2 target implied vol\n    std::vector<boost::shared_ptr<CalibrationHelper> > helpersUsd, helpersGbp;\n    for (Size i = 0; i <= volstepdatesFx.size(); ++i) {\n        boost::shared_ptr<CalibrationHelper> tmpUsd =\n            boost::make_shared<FxOptionHelper>(\n                i < volstepdatesFx.size() ? volstepdatesFx[i]\n                                          : volstepdatesFx.back() + 365,\n                0.90, Handle<Quote>(boost::make_shared<SimpleQuote>(\n                          std::exp(fxSpots[0]->value()))),\n                Handle<Quote>(boost::make_shared<SimpleQuote>(0.15)),\n                ccLgm->termStructure(0), ccLgm->termStructure(1));\n        boost::shared_ptr<CalibrationHelper> tmpGbp =\n            boost::make_shared<FxOptionHelper>(\n                i < volstepdatesFx.size() ? volstepdatesFx[i]\n                                          : volstepdatesFx.back() + 365,\n                1.35, Handle<Quote>(boost::make_shared<SimpleQuote>(\n                          std::exp(fxSpots[1]->value()))),\n                Handle<Quote>(boost::make_shared<SimpleQuote>(0.20)),\n                ccLgm->termStructure(0), ccLgm->termStructure(2));\n        tmpUsd->setPricingEngine(ccLgmFxOptionEngineUsd);\n        tmpGbp->setPricingEngine(ccLgmFxOptionEngineGbp);\n        helpersUsd.push_back(tmpUsd);\n        helpersGbp.push_back(tmpGbp);\n    }\n\n    LevenbergMarquardt lm(1E-8, 1E-8, 1E-8);\n    EndCriteria ec(1000, 500, 1E-8, 1E-8, 1E-8);\n\n    // calibrate USD-EUR FX volatility\n    ccLgm->calibrateFxVolatilitiesIterative(0, helpersUsd, lm, ec);\n    // calibrate GBP-EUR FX volatility\n    ccLgm->calibrateFxVolatilitiesIterative(1, helpersGbp, lm, ec);\n\n    Real tol = 1E-6;\n    for (Size i = 0; i < helpersUsd.size(); ++i) {\n        Real market = helpersUsd[i]->marketValue();\n        Real model = helpersUsd[i]->modelValue();\n        Real calibratedVol = ccLgm->fxVolatility(0)[i];\n        if (std::fabs(market - model) > tol)\n            BOOST_ERROR(\"calibration for fx option helper #\"\n                        << i << \" (USD) failed, market premium is \" << market\n                        << \" while model premium is \" << model);\n        // the stochastic rates produce some noise, but do not have a huge\n        // impact on the effective volatility, so we check that they are\n        // in line with a cached example (note that the analytic fx option\n        // pricing engine was checked against MC in another test case)\n        if (std::fabs(calibratedVol - 0.143) > 0.01)\n            BOOST_ERROR(\n                \"calibrated fx volatility #\"\n                << i\n                << \" (USD) seems off, expected to be 0.143 +- 0.01, but is \"\n                << calibratedVol);\n    }\n    for (Size i = 0; i < helpersGbp.size(); ++i) {\n        Real market = helpersGbp[i]->marketValue();\n        Real model = helpersGbp[i]->modelValue();\n        Real calibratedVol = ccLgm->fxVolatility(1)[i];\n        if (std::fabs(market - model) > tol)\n            BOOST_ERROR(\"calibration for fx option helper #\"\n                        << i << \" (GBP) failed, market premium is \" << market\n                        << \" while model premium is \" << model);\n        // see above\n        if (std::fabs(calibratedVol - 0.193) > 0.01)\n            BOOST_ERROR(\n                \"calibrated fx volatility #\"\n                << i << \" (USD) seems off, expected to be 0.193 +- 0.01, but is \"\n                << calibratedVol);\n    }\n\n    // calibrate the projected model\n\n    for (Size i = 0; i < helpersGbp.size(); ++i) {\n        helpersGbp[i]->setPricingEngine(ccLgmProjectedFxOptionEngineGbp);\n    }\n\n    ccLgmProjected->calibrateFxVolatilitiesIterative(0, helpersGbp, lm, ec);\n\n    for (Size i = 0; i < helpersGbp.size(); ++i) {\n        Real fullModelVol = ccLgm->fxVolatility(1)[i];\n        Real projectedModelVol = ccLgmProjected->fxVolatility(0)[i];\n        if (std::fabs(fullModelVol - projectedModelVol) > tol)\n            BOOST_ERROR(\n                \"calibrated fx volatility of full model @\"\n                << i << \" (\" << fullModelVol\n                << \") is inconsistent with that of the projected model (\"\n                << projectedModelVol << \")\");\n    }\n\n} // testLgm4fAndFxCalibration\n\ntest_suite *LgmTest::suite() {\n    test_suite *suite = BOOST_TEST_SUITE(\"LGM model tests\");\n    suite->add(QUANTLIB_TEST_CASE(&LgmTest::testBermudanLgm1fGsr));\n    suite->add(QUANTLIB_TEST_CASE(&LgmTest::testLgm1fCalibration));\n    suite->add(QUANTLIB_TEST_CASE(&LgmTest::testLgm3fForeignPayouts));\n    suite->add(QUANTLIB_TEST_CASE(&LgmTest::testLgm4fAndFxCalibration));\n    return suite;\n}\n", "meta": {"hexsha": "c0c46fa662f3ebc2a5ae77fdcbdd37b0cb9fe359", "size": 29828, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test-suite/lgm.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": "test-suite/lgm.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": "test-suite/lgm.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": 42.189533239, "max_line_length": 94, "alphanum_fraction": 0.6135510259, "num_tokens": 8954, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.48813995538989013}}
{"text": "#include <CGAL/boost/graph/graph_traits_Surface_mesh.h>\n#include <CGAL/Polygon_mesh_processing/remesh.h>\n#include <CGAL/Polygon_mesh_processing/border.h>\n#include <boost/function_output_iterator.hpp>\n#include \"booleanmesh.h\"\n#include \"isotropicremesh.h\"\n\ntypedef boost::graph_traits<CgalMesh>::halfedge_descriptor halfedge_descriptor;\ntypedef boost::graph_traits<CgalMesh>::edge_descriptor     edge_descriptor;\nnamespace PMP = CGAL::Polygon_mesh_processing;\n\nstruct halfedge2edge\n{\n    halfedge2edge(const CgalMesh& m, std::vector<edge_descriptor>& edges)\n        : m_mesh(m), m_edges(edges)\n    {}\n    void operator()(const halfedge_descriptor& h) const\n    {\n        m_edges.push_back(edge(h, m_mesh));\n    }\n    const CgalMesh& m_mesh;\n    std::vector<edge_descriptor>& m_edges;\n};\n\nvoid isotropicRemesh(const std::vector<QVector3D> &inputVertices,\n        std::vector<std::vector<size_t>> &inputTriangles,\n        std::vector<QVector3D> &outputVertices,\n        std::vector<std::vector<size_t>> &outputTriangles,\n        float targetEdgeLength,\n        unsigned int iterationNum)\n{\n    CgalMesh *mesh = buildCgalMesh<CgalKernel>(inputVertices, inputTriangles);\n    if (nullptr == mesh)\n        return;\n    \n    std::vector<edge_descriptor> border;\n    PMP::border_halfedges(faces(*mesh),\n        *mesh,\n        boost::make_function_output_iterator(halfedge2edge(*mesh, border)));\n    PMP::split_long_edges(border, targetEdgeLength, *mesh);\n    \n    PMP::isotropic_remeshing(faces(*mesh),\n        targetEdgeLength,\n        *mesh,\n        PMP::parameters::number_of_iterations(iterationNum)\n        .protect_constraints(true));\n    \n    outputVertices.clear();\n    outputTriangles.clear();\n    fetchFromCgalMesh<CgalKernel>(mesh, outputVertices, outputTriangles);\n    \n    delete mesh;\n}\n", "meta": {"hexsha": "28411d6bc2714d0b23a09b15e1ff564fed38e8c2", "size": 1790, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/isotropicremesh.cpp", "max_stars_repo_name": "MelvinG24/dust3d", "max_stars_repo_head_hexsha": "c4936fd900a9a48220ebb811dfeaea0effbae3ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2392.0, "max_stars_repo_stars_event_min_datetime": "2016-12-17T14:14:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T19:40:40.000Z", "max_issues_repo_path": "src/isotropicremesh.cpp", "max_issues_repo_name": "MelvinG24/dust3d", "max_issues_repo_head_hexsha": "c4936fd900a9a48220ebb811dfeaea0effbae3ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 106.0, "max_issues_repo_issues_event_min_datetime": "2018-04-19T17:47:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-01T19:44:11.000Z", "max_forks_repo_path": "src/isotropicremesh.cpp", "max_forks_repo_name": "MelvinG24/dust3d", "max_forks_repo_head_hexsha": "c4936fd900a9a48220ebb811dfeaea0effbae3ee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 184.0, "max_forks_repo_forks_event_min_datetime": "2017-11-15T09:55:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T16:30:46.000Z", "avg_line_length": 33.1481481481, "max_line_length": 79, "alphanum_fraction": 0.7122905028, "num_tokens": 431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795403, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4880591407467427}}
{"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_FUNCTION_GAMMA_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_GAMMA_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n  @ingroup group-euler\n    Function object implementing gamma capabilities\n\n   Computes the gamma function:\n   \\f$\\displaystyle \\int_0^{\\infty} t^{x-1}e^{-t}\\mbox{d}t\\f$\n\n    @par Semantic:\n\n    For every parameter of floating type T\n\n    @code\n    T r = gamma(x);\n    @endcode\n\n    @see gammaln\n\n  **/\n  const boost::dispatch::functor<tag::gamma_> gamma = {};\n} }\n#endif\n\n#include <boost/simd/function/scalar/gamma.hpp>\n//#include <boost/simd/function/simd/gamma.hpp>\n\n#endif\n", "meta": {"hexsha": "4c2ba3ea6bcbe63295d6d42d720a1a072a012aca", "size": 1062, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/gamma.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/function/gamma.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/function/gamma.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": 24.1363636364, "max_line_length": 100, "alphanum_fraction": 0.5753295669, "num_tokens": 244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.48805913502095216}}
{"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// Implementation File\n// Look at polynomial.h for documentation\n#include <traj_opt_basic/polynomial_basis.h>\n\n#include <boost/math/special_functions/factorials.hpp>\n#include <boost/pointer_cast.hpp>\n#include <boost/range/irange.hpp>\n\n#include <iostream>\n#include <stdexcept>\n#include <vector>\n\nnamespace traj_opt {\n\nPoly PolyCalculus::integrate(const Poly &p) {\n  // integrates polynomial with 0 as constant of integration\n  Poly::size_type rows = p.size();\n  std::vector<decimal_t> v;\n  v.push_back(0.0);\n  for (Poly::size_type i = 0; i < rows; i++) {\n    decimal_t val = static_cast<decimal_t>(i + 1);\n    v.push_back(p[i] / val);\n  }\n  Poly result(v.data(), rows);\n  return result;\n}\nPoly PolyCalculus::differentiate(const Poly &p) {\n  // differentiates polynomial\n  Poly::size_type rows = p.size();\n  if (rows <= 1) return Poly(0.0);\n  std::vector<decimal_t> v;\n  for (Poly::size_type i = 1; i < rows; i++) {\n    decimal_t val = static_cast<decimal_t>(i);\n    v.push_back(p[i] * val);\n  }\n  Poly result(v.data(), rows - 2);\n  return result;\n}\n\nuint Basis::dim() { return n_p; }\n\n// switched these constructors to use new generic one\nBasisBundle::BasisBundle(uint n_p_, uint k_r_)\n    : BasisBundle(LEGENDRE, n_p_, k_r_) {}\nBasisBundle::BasisBundle(int n) : BasisBundle(BEZIER, n, 0) {}\n\nvoid StandardBasis::differentiate() {\n  for (std::vector<Poly>::iterator it = polys.begin(); it != polys.end();\n       ++it) {\n    *it = PolyCalculus::differentiate(*it);\n  }\n}\nvoid StandardBasis::integrate() {\n  for (std::vector<Poly>::iterator it = polys.begin(); it != polys.end();\n       ++it) {\n    *it = PolyCalculus::integrate(*it);\n  }\n}\n\ndecimal_t StandardBasis::evaluate(decimal_t x, uint coeff) const {\n  //    std::cout << \"poly size \" << polys.size() << std::endl;\n  assert(coeff < polys.size());\n\n  if (x > 1.0 || x < 0.0)\n    throw std::out_of_range(\n        \"Tried to evaluate shifted legensdre basis out of normalized range \"\n        \"[0,1]\");\n  return polys[coeff].evaluate(x);\n}\nstd::ostream &operator<<(std::ostream &os, const StandardBasis &lb) {\n  for (std::vector<Poly>::const_iterator it = lb.polys.begin();\n       it != lb.polys.end(); ++it) {\n    os << (*it) << std::endl;\n  }\n  return os;\n}\n\ndecimal_t BasisBundle::getVal(decimal_t x, decimal_t dt, uint coeff,\n                              int derr) const {\n  assert(derr < static_cast<int>(derrivatives.size()));\n  if (derr < 0) {\n    assert(-derr <= static_cast<int>(integrals.size()));\n    if (dt != 0.0) {\n      decimal_t factor = std::pow(dt, -static_cast<int>(derr));\n      return factor * integrals.at(-derr - 1)->evaluate(x, coeff);\n    } else {\n      return integrals.at(-derr - 1)->evaluate(x, coeff);\n    }\n\n  } else {\n    if (dt != 0.0) {\n      decimal_t factor = std::pow(dt, -static_cast<int>(derr));\n      return factor * derrivatives.at(derr)->evaluate(x, coeff);\n    } else {\n      return derrivatives.at(derr)->evaluate(x, coeff);\n    }\n  }\n}\n// BasisBundle::~BasisBundle() {}\n\nBasis::Basis(uint n_p_) : n_p(n_p_) { type_ = PolyType::STANDARD; }\n// Basis::~Basis() {}\n\ndecimal_t StandardBasis::innerproduct(uint i, uint j) const {\n  Poly L = polys.at(i) * polys.at(j);\n  Poly Lint = PolyCalculus::integrate(L);\n  return Lint.evaluate(1.0);\n}\n\nPoly StandardBasis::getPoly(uint i) const { return polys.at(i); }\nStandardBasis::StandardBasis(uint n) : Basis(n) {\n  type_ = PolyType::STANDARD;\n  if (n == 0) return;\n  std::vector<decimal_t> simple;\n  simple.push_back(1.0);\n  for (uint i = 0; i <= n_p; i++) {\n    Poly poly(simple.data(), simple.size() - 1);\n    polys.push_back(poly);\n    simple.back() = 0.0;\n    simple.push_back(1.0);\n  }\n}\n\nboost::shared_ptr<Basis> BasisBundle::getBasis(int i) {\n  if (i >= 0)\n    return derrivatives.at(i);\n  else\n    return integrals.at(-i - 1);\n}\nBasisBundle::BasisBundle(PolyType type, uint n_p_, uint k_r_)\n    : n_p(n_p_), k_r(k_r_) {\n  // only computer the first 4 derrivatives\n  derrivatives.reserve(10);\n  // computer the integral too, preferable use i7 to do computering\n  integrals.reserve(1);\n\n  for (auto i : boost::irange(0, 11)) {\n    boost::shared_ptr<Basis> base;\n\n    if (type == LEGENDRE)\n      throw std::runtime_error(\n          \"Legendre Basis not implemented in basic package\");\n    else if (type == STANDARD)\n      base = boost::make_shared<StandardBasis>(n_p);\n    else if (type == BEZIER)\n      throw std::runtime_error(\"Bezier Basis not implemented in basic package\");\n    else if (type == ENDPOINT)\n      throw std::runtime_error(\n          \"Enpoint Basis not implemented in basic package\");\n    else if (type == CHEBYSHEV)\n      throw std::runtime_error(\n          \"Chebyshev Basis not implemented in basic package\");\n    else\n      throw std::runtime_error(\"Unknown basis type\");\n\n    if (i == 11) {\n      base->integrate();\n      integrals.push_back(base);\n    } else {\n      for (int j = 0; j < i; j++) base->differentiate();\n      derrivatives.push_back(base);\n    }\n  }\n}\n}  // namespace traj_opt\n", "meta": {"hexsha": "34512c39220f63a719f0f0e82be8e904e4e5f084", "size": 5713, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mobility/planner_qp/traj_opt_basic/src/polynomial_basis.cpp", "max_stars_repo_name": "Robo0603179/astrobee", "max_stars_repo_head_hexsha": "19e58806c63cddd9046342c7fa2ac7808f40ad3c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 629.0, "max_stars_repo_stars_event_min_datetime": "2017-08-31T23:09:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T11:55:40.000Z", "max_issues_repo_path": "mobility/planner_qp/traj_opt_basic/src/polynomial_basis.cpp", "max_issues_repo_name": "Robo0603179/astrobee", "max_issues_repo_head_hexsha": "19e58806c63cddd9046342c7fa2ac7808f40ad3c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 269.0, "max_issues_repo_issues_event_min_datetime": "2018-05-05T12:31:16.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T22:04:11.000Z", "max_forks_repo_path": "mobility/planner_qp/traj_opt_basic/src/polynomial_basis.cpp", "max_forks_repo_name": "Robo0603179/astrobee", "max_forks_repo_head_hexsha": "19e58806c63cddd9046342c7fa2ac7808f40ad3c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 248.0, "max_forks_repo_forks_event_min_datetime": "2017-08-31T23:20:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T22:29:16.000Z", "avg_line_length": 31.0489130435, "max_line_length": 80, "alphanum_fraction": 0.650271311, "num_tokens": 1610, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185944046238982, "lm_q2_score": 0.6791786991753931, "lm_q1q2_score": 0.48805401296717527}}
{"text": "/*\n * Copyright (c) 2013-2015 Masahide Kashiwagi (kashi@waseda.jp)\n */\n\n#ifndef INTERVAL_VECTOR_HPP\n#define INTERVAL_VECTOR_HPP\n\n// utilities for interval vector/matrix\n\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <kv/interval.hpp>\n\n\nnamespace kv {\n\nnamespace ub = boost::numeric::ublas;\n\ntemplate <class T> inline ub::vector<T> mid (const ub::vector< interval<T> >& I) {\n\tint i;\n\tint s = I.size();\n\tub::vector<T> r(s);\n\n\tfor (i=0; i<s; i++) {\n\t\tr(i) = mid(I(i));\n\t}\n\n\treturn r;\n}\n\ntemplate <class T> inline ub::matrix<T> mid (const ub::matrix< interval<T> >& I) {\n\tint i, j;\n\tint s1 = I.size1();\n\tint s2 = I.size2();\n\tub::matrix<T> r(s1, s2);\n\n\tfor (i=0; i<s1; i++) {\n\t\tfor (j=0; j<s2; j++) {\n\t\t\tr(i,j) = mid(I(i,j));\n\t\t}\n\t}\n\n\treturn r;\n}\n\n\ntemplate <class T> inline ub::vector<T> rad (const ub::vector< interval<T> >& I) {\n\tint i;\n\tint s = I.size();\n\tub::vector<T> r(s);\n\n\tfor (i=0; i<s; i++) {\n\t\tr(i) = rad(I(i));\n\t}\n\n\treturn r;\n}\n\ntemplate <class T> inline ub::matrix<T> rad (const ub::matrix< interval<T> >& I) {\n\tint i, j;\n\tint s1 = I.size1();\n\tint s2 = I.size2();\n\tub::matrix<T> r(s1, s2);\n\n\tfor (i=0; i<s1; i++) {\n\t\tfor (j=0; j<s2; j++) {\n\t\t\tr(i,j) = rad(I(i,j));\n\t\t}\n\t}\n\n\treturn r;\n}\n\n\ntemplate <class T> inline ub::vector<T> mag (const ub::vector< interval<T> >& I) {\n\tint i;\n\tint s = I.size();\n\tub::vector<T> r(s);\n\n\tfor (i=0; i<s; i++) {\n\t\tr(i) = mag(I(i));\n\t}\n\n\treturn r;\n}\n\ntemplate <class T> inline ub::matrix<T> mag (const ub::matrix< interval<T> >& I) {\n\tint i, j;\n\tint s1 = I.size1();\n\tint s2 = I.size2();\n\tub::matrix<T> r(s1, s2);\n\n\tfor (i=0; i<s1; i++) {\n\t\tfor (j=0; j<s2; j++) {\n\t\t\tr(i,j) = mag(I(i,j));\n\t\t}\n\t}\n\n\treturn r;\n}\n\ntemplate <class T> inline ub::vector<T> mag (const ub::vector< T >& v) {\n\tint i;\n\tint s = v.size();\n\tub::vector<T> r(s);\n\n\tfor (i=0; i<s; i++) {\n\t\tr(i) = mag(v(i));\n\t}\n\n\treturn r;\n}\n\ntemplate <class T> inline ub::matrix<T> mag (const ub::matrix< T >& m) {\n\tint i, j;\n\tint s1 = m.size1();\n\tint s2 = m.size2();\n\tub::matrix<T> r(s1, s2);\n\n\tfor (i=0; i<s1; i++) {\n\t\tfor (j=0; j<s2; j++) {\n\t\t\tr(i,j) = mag(m(i,j));\n\t\t}\n\t}\n\n\treturn r;\n}\n\n\n\ntemplate <class T> inline ub::vector<T> mig (const ub::vector< interval<T> >& I) {\n\tint i;\n\tint s = I.size();\n\tub::vector<T> r(s);\n\n\tfor (i=0; i<s; i++) {\n\t\tr(i) = mig(I(i));\n\t}\n\n\treturn r;\n}\n\ntemplate <class T> inline ub::matrix<T> mig (const ub::matrix< interval<T> >& I) {\n\tint i, j;\n\tint s1 = I.size1();\n\tint s2 = I.size2();\n\tub::matrix<T> r(s1, s2);\n\n\tfor (i=0; i<s1; i++) {\n\t\tfor (j=0; j<s2; j++) {\n\t\t\tr(i,j) = mig(I(i,j));\n\t\t}\n\t}\n\n\treturn r;\n}\n\n\ntemplate <class T> inline bool zero_in (const ub::vector< interval<T> >& I) {\n\tint i;\n\tint s = I.size();\n\n\tfor (i=0; i<s; i++) {\n\t\tif (!zero_in(I(i))) return false;\n\t}\n\n\treturn true;\n}\n\ntemplate <class T> inline bool subset (const ub::vector< interval<T> >& I, const ub::vector< interval<T> > & J) {\n\tint i;\n\tint s = I.size();\n\n\tfor (i=0; i<s; i++) {\n\t\tif (!subset(I(i), J(i))) return false;\n\t}\n\n\treturn true;\n}\n\ntemplate <class T> inline bool proper_subset (const ub::vector< interval<T> >& I, const ub::vector< interval<T> > & J) {\n\tint i;\n\tint s = I.size();\n\n\tfor (i=0; i<s; i++) {\n\t\tif (!proper_subset(I(i), J(i))) return false;\n\t}\n\n\treturn true;\n}\n\ntemplate <class T> inline bool overlap (const ub::vector< interval<T> >& I, const ub::vector< interval<T> > & J) {\n\tint i;\n\tint s = I.size();\n\n\tfor (i=0; i<s; i++) {\n\t\tif (!overlap(I(i), J(i))) return false;\n\t}\n\n\treturn true;\n}\n\ntemplate <class T> inline ub::vector< interval<T> > intersect (const ub::vector< interval<T> >& I, const ub::vector< interval<T> > & J) {\n\tint i;\n\tint s = I.size();\n\tub::vector< interval<T> > r(s);\n\n\tfor (i=0; i<s; i++) {\n\t\tr(i) = intersect(I(i), J(i));\n\t}\n\n\treturn r;\n}\n\ntemplate <class T> inline ub::matrix< interval<T> > intersect (const ub::matrix< interval<T> >& I, const ub::matrix< interval<T> > & J) {\n\tint i, j;\n\tint s1 = I.size1();\n\tint s2 = I.size2();\n\tub::matrix< interval<T> > r(s1, s2);\n\n\tfor (i=0; i<s1; i++) {\n\t\tfor (j=0; j<s2; j++) {\n\t\t\tr(i, j) = intersect(I(i, j), J(i, j));\n\t\t}\n\t}\n\n\treturn r;\n}\n\ntemplate <class T> inline ub::vector< interval<T> > hull (const ub::vector< interval<T> >& I, const ub::vector< interval<T> > & J) {\n\tint i;\n\tint s = I.size();\n\tub::vector< interval<T> > r(s);\n\n\tfor (i=0; i<s; i++) {\n\t\tr(i) = interval<T>::hull(I(i), J(i));\n\t}\n\n\treturn r;\n}\n\ntemplate <class T> inline ub::matrix< interval<T> > hull (const ub::matrix< interval<T> >& I, const ub::matrix< interval<T> > & J) {\n\tint i, j;\n\tint s1 = I.size1();\n\tint s2 = I.size2();\n\tub::matrix< interval<T> > r(s1, s2);\n\n\tfor (i=0; i<s1; i++) {\n\t\tfor (j=0; j<s2; j++) {\n\t\t\tr(i, j) = interval<T>::hull(I(i, j), J(i, j));\n\t\t}\n\t}\n\n\treturn r;\n}\n\n\ntemplate <class T> inline T max_norm (const ub::vector<T>& x) {\n\tint i;\n\tint s = x.size();\n\tT r, tmp;\n\n\tr = 0.;\n\tfor (i=0; i<s; i++) {\n\t\t// tmp = abs(x(i));\n\t\ttmp = (x(i) >= 0.) ? x(i) : -x(i);\n\t\tif (tmp > r) r = tmp;\n\t}\n\n\treturn r;\n}\n\ntemplate <class T> inline T max_norm (const ub::matrix<T>& x) {\n\tint i, j;\n\tint s1 = x.size1();\n\tint s2 = x.size2();\n\tT r, tmp, tmp2;\n\n\tr = 0.;\n\tfor (i=0; i<s1; i++) {\n\t\ttmp = 0.;\n\t\trop<T>::begin();\n\t\tfor (j=0; j<s2; j++) {\n\t\t\ttmp2 = (x(i, j) >= 0.) ? x(i, j) : -x(i, j);\n\t\t\ttmp = rop<T>::add_up(tmp, tmp2);\n\t\t}\n\t\trop<T>::end();\n\t\tif (tmp > r) r = tmp;\n\t}\n\n\treturn r;\n}\n\ntemplate <class T> inline T max_norm (const ub::vector< interval<T> >& x) {\n\tint i;\n\tint s = x.size();\n\tT r, tmp;\n\n\tr = 0.;\n\tfor (i=0; i<s; i++) {\n\t\ttmp = norm(x(i));\n\t\tif (tmp > r) r = tmp;\n\t}\n\n\treturn r;\n}\n\ntemplate <class T> inline T max_norm (const ub::matrix< interval<T> >& x) {\n\tint i, j;\n\tint s1 = x.size1();\n\tint s2 = x.size2();\n\tT r, tmp;\n\n\tr = 0.;\n\tfor (i=0; i<s1; i++) {\n\t\ttmp = 0.;\n\t\trop<T>::begin();\n\t\tfor (j=0; j<s2; j++) {\n\t\t\ttmp = rop<T>::add_up(tmp, norm(x(i, j)));\n\t\t}\n\t\trop<T>::end();\n\t\tif (tmp > r) r = tmp;\n\t}\n\n\treturn r;\n}\n\n} // namespace kv\n\n#endif // INTERVAL_VECTOR_HPP\n", "meta": {"hexsha": "9258f614ecc8b0cd70ee4645aa6daa7536d90ba2", "size": 5906, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "kv/interval-vector.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/interval-vector.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/interval-vector.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": 17.8429003021, "max_line_length": 137, "alphanum_fraction": 0.53572638, "num_tokens": 2179, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.6791787056691697, "lm_q1q2_score": 0.4880540094473973}}
{"text": "//=======================================================================\n// Copyright 1997, 1998, 1999, 2000 University of Notre Dame.\n// Authors: Andrew Lumsdaine, Lie-Quan Lee, Jeremy G. Siek\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n\n// Sample output:\n//\n//  The graph miles(100,0,0,0,0,10,0) has 405 edges,\n//   and its minimum spanning tree has length 14467.\n//\n\n#include <boost/config.hpp>\n#include <string.h>\n#include <stdio.h>\n#include <boost/graph/stanford_graph.hpp>\n#include <boost/graph/prim_minimum_spanning_tree.hpp>\n\n// A visitor class for accumulating the total length of the minimum\n// spanning tree. The Distance template parameter is for a\n// PropertyMap.\ntemplate <class Distance>\nstruct total_length_visitor : public boost::dijkstra_visitor<> {\n  typedef typename boost::property_traits<Distance>::value_type D;\n  total_length_visitor(D& len, Distance d)\n    : _total_length(len), _distance(d) { }\n  template <class Vertex, class Graph>\n  inline void finish_vertex(Vertex s, Graph& g) {\n    _total_length += boost::get(_distance, s); \n  }\n  D& _total_length;\n  Distance _distance;\n};\n\nint main(int argc, char* argv[])\n{\n  using namespace boost;\n  Graph* g;\n\n  unsigned long n = 100;\n  unsigned long n_weight = 0;\n  unsigned long w_weight = 0;\n  unsigned long p_weight = 0;\n  unsigned long d = 10;\n  long s = 0;\n  unsigned long r = 1;\n  char* file_name = NULL;\n\n  while(--argc){\n    if(sscanf(argv[argc],\"-n%lu\",&n)==1);\n    else if(sscanf(argv[argc],\"-N%lu\",&n_weight)==1);\n    else if(sscanf(argv[argc],\"-W%lu\",&w_weight)==1);\n    else if(sscanf(argv[argc],\"-P%lu\",&p_weight)==1);\n    else if(sscanf(argv[argc],\"-d%lu\",&d)==1);\n    else if(sscanf(argv[argc],\"-r%lu\",&r)==1);\n    else if(sscanf(argv[argc],\"-s%ld\",&s)==1);\n    else if(strcmp(argv[argc],\"-v\")==0) verbose = 1;\n    else if(strncmp(argv[argc],\"-g\",2)==0) file_name = argv[argc]+2;\n    else{\n      fprintf(stderr,\n              \"Usage: %s [-nN][-dN][-rN][-sN][-NN][-WN][-PN][-v][-gfoo]\\n\",\n              argv[0]);\n      return -2;\n    }\n  }\n  if (file_name) r = 1;\n\n  while (r--) {\n    if (file_name)\n      g = restore_graph(file_name);\n    else\n      g = miles(n,n_weight,w_weight,p_weight,0L,d,s);\n\n    if(g == NULL || g->n <= 1) {\n      fprintf(stderr,\"Sorry, can't create the graph! (error code %ld)\\n\",\n              panic_code);\n      return-1;\n    }\n\n   printf(\"The graph %s has %ld edges,\\n\", g->id, g->m / 2);\n\n   long sp_length = 0;\n\n   // Use the \"z\" utility field for distance.\n   typedef property_map<Graph*, z_property<long> >::type Distance;\n   Distance d = get(z_property<long>(), g);\n   // Use the \"w\" property for parent\n   typedef property_map<Graph*, w_property<Vertex*> >::type Parent;\n   Parent p = get(w_property<Vertex*>(), g);\n   total_length_visitor<Distance> length_vis(sp_length, d);\n\n   prim_minimum_spanning_tree(g, p,\n                              distance_map(get(z_property<long>(), g)).\n                              weight_map(get(edge_length_t(), g)). \n                              // Use the \"y\" utility field for color\n                              color_map(get(y_property<long>(), g)).\n                              visitor(length_vis));\n\n   printf(\"  and its minimum spanning tree has length %ld.\\n\", sp_length);\n\n   gb_recycle(g);\n   s++;\n }\n  return 0;\n}\n", "meta": {"hexsha": "e905867323fd35b774d7c454b7e497e7739adff9", "size": 3475, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/graph/example/miles_span.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "boost/libs/graph/example/miles_span.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "boost/libs/graph/example/miles_span.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 31.880733945, "max_line_length": 75, "alphanum_fraction": 0.5890647482, "num_tokens": 936, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708562, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.4880540047810058}}
{"text": "#include <mtl/matrix.h>\n#include <mtl/mtl.h>\n\nusing namespace mtl;\n\nint main()\n{\n  //  matrix<double, rectangle<>, array< dense<> >, row_major>::type A(10,10);\n  matrix<double, rectangle<>, dense<>, row_major>::type A(10,10);\n  mtl::set_value(A, 2);\n\n  A.resize(5,4);\n  print_all_matrix(A);\n\n  A.resize(10, 10);\n  print_all_matrix(A);\n\n  return 0;\n}\n", "meta": {"hexsha": "08f2deb8b56490d0d8fcb7f097f549c03785311b", "size": 350, "ext": "cc", "lang": "C++", "max_stars_repo_path": "stapl_release/tools/mtl-2.0/contrib/examples/resize.cc", "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/tools/mtl-2.0/contrib/examples/resize.cc", "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/tools/mtl-2.0/contrib/examples/resize.cc", "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": 17.5, "max_line_length": 78, "alphanum_fraction": 0.6371428571, "num_tokens": 117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7185943925708562, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.4880540001146142}}
{"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\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n//\n// This file is part of the Matrix Template Library\n//\n// See also license.mtl.txt in the distribution.\n\n#include <iostream>\n#include <boost/numeric/mtl/mtl.hpp>\n\n\nusing namespace std;\n\n\n\n\nint main(int, char**)\n{\n    typedef mtl::dense_vector<float>         v_type;\n    typedef mtl::vec::scaled_view<float, v_type> s_type;\n\n    v_type v(3, 4.0);\n    s_type s(2.0f * v);\n\n    cout << size(s) << \"\\n\";\n    cout << num_rows(s) << \"\\n\";\n    cout << num_cols(s) << \"\\n\";\n\n    return 0;\n}\n\n\n\n", "meta": {"hexsha": "78885b76dd493f8c57fb62ada24468dbab9b62d0", "size": 822, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/scaled_view_size_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/scaled_view_size_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/scaled_view_size_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": 21.0769230769, "max_line_length": 94, "alphanum_fraction": 0.6399026764, "num_tokens": 226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.4880540001146141}}
{"text": "\n#ifndef TRIANGLE_HPP\n#define\tTRIANGLE_HPP\n\n#include \"Object.hpp\"\n#include <armadillo>\n#include <vector>\n\nusing namespace arma;\nusing namespace std;\n\nclass Triangle :public Object {\n\nprivate:\n    vec A, B, C, baricentro;\n    \npublic:\n    \n    Triangle(vec triangulo);\n\n    bool colide(const vec &d, double &T, const vec &origem);\n    \n    void setCentro(vec baricentro) {\n        this->baricentro = baricentro;\n    }\n\n    vec getCentro() {\n        return baricentro;\n    }\n\n    void setC(vec C) {\n        this->C = C;\n    }\n\n    vec getC() {\n        return C;\n    }\n\n    void setB(vec B) {\n        this->B = B;\n    }\n\n    vec getB() {\n        return B;\n    }\n\n    void setA(vec A) {\n        this->A = A;\n    }\n\n    vec getA() {\n        return A;\n    }\n    \n    vec getMin(){ \n        double tmp[3];\n\tvec aux;\n\t  \n\tfor (int i=0;i<3;i++){\n\t      if ((this->A(i) <= this->B(i)) && (this->A(i) <= this->C(i))) { \n                  tmp[i]=A(i); \n              }\n              \n\t      else if ((this->B(i) <= this->A(i)) && (this->B(i) <= this->C(i))) { \n                  tmp[i]=B(i); \n              }\n              \n\t      else if ((this->C(i) <= this->A(i)) && (this->C(i) <= this->B(i))) { \n                  tmp[i]=C(i); \n              }\n\t}\n\t    \n\taux << tmp[0] << tmp[1] << tmp[2]; \n        \n\treturn aux; \n    }\n    \n    vec getMax(){ \n\tdouble tmp[3];\n\tvec aux;\n\t  \n\tfor (int i=0;i<3;i++){\n\t    if ((this->A(i) >= this->B(i)) && (this->A(i) >= this->C(i))) { \n                tmp[i]=A(i); \n            }\n            \n\t    else if ((this->B(i) >= this->A(i)) && (this->B(i) >= this->C(i))) { \n                tmp[i]=B(i); \n            }\n\t    \n            else if ((this->C(i) >= this->A(i)) && (this->C(i) >= this->B(i))) { \n                tmp[i]=C(i); \n            }\n\t}\n\t    \n\taux << tmp[0] << tmp[1] << tmp[2]; \n\treturn aux; \n    }\n\n};\n\n#endif\t/* TRIANGLE_HPP */\n\n", "meta": {"hexsha": "879f3f47d5c237fb2213140991e5d4eae0b4de49", "size": 1866, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "raytracing/headers/Triangle.hpp", "max_stars_repo_name": "arthurflor/RayTracing", "max_stars_repo_head_hexsha": "8deedf33446bed259d8f7e2895024fd1300eb439", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-08-19T09:38:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-27T02:04:22.000Z", "max_issues_repo_path": "raytracing/headers/Triangle.hpp", "max_issues_repo_name": "arthurflor23/ray-tracing", "max_issues_repo_head_hexsha": "8deedf33446bed259d8f7e2895024fd1300eb439", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "raytracing/headers/Triangle.hpp", "max_forks_repo_name": "arthurflor23/ray-tracing", "max_forks_repo_head_hexsha": "8deedf33446bed259d8f7e2895024fd1300eb439", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.9423076923, "max_line_length": 81, "alphanum_fraction": 0.4013933548, "num_tokens": 570, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708562, "lm_q2_score": 0.6791786861878392, "lm_q1q2_score": 0.4880539954482225}}
{"text": "//////////////////////////////////////////////////////////////////////////////\n//  Quantum Monte Carlo Simulation for Kitaev Models\n//  with Green's-function-based Kernel Polynomial Method\n//  written by: Tim Eschmann, May 2017\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#define _USE_MATH_DEFINES\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 package to calculate thermodynamic observables\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, double lambda, int intsteps, int M, 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    ///////////////////////////////////////////////////\n    // System configuration stored as CRS blockvectors\n    ,   val()     \n    ,   col_idx()\n    ,   row_ptr()\n    //////////////////\n    ,   N_() // # system sites (IMPORTANT: THIS HAS CHANGED W.R.T. FORMER VERSIONS !!!)\n    ,   v_() // Vector with coordinates of nonzero matrix entries\n    ,   length_() // number of non-zero matrix elements\n    ////////////////////////////////////\n    //  Parameters for KPM Calculation\n    ,   s_()\n    ,   ld()\n    ,   bw_save()\n    ,   lambda_(lambda)\n    ,   intsteps_(intsteps)\n    ,   M_(M)\n    ,   int_min() // Limits for all integrations ...\n    ,   int_max()\n    ,   step_()\n    ,   pi()\n    ,   twopi()\n    ,   Del_rho()\n    ,   y_values()\n    ,   tanh_values()\n    ,   kernel_factors()\n    ,   dr()\n    ,   mom_i_plus_ij()\n    ,   mom_i_plus_j()\n    ,   mom_ii()\n    ,   mom_jj()\n    ,   mom()\n    ,   i_()\n    ,   j_2()\n    ,   j_1()\n    ,   j_()\n    ////////////////////////////////////\n    ,   plaquettes() // matrix with elementary plaquettes\n    ,   plaquettes2() // -------------- \" ---------------\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)\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    ,   flux2_real(\"Fl2real\") // Measurement data: average plaquet flux (real part)\n    //,   flux2_imag(\"Fl2imag\") // \"\" (imaginary part)\n    ,   flux2_real_squared(\"Fl2real2\") // Measurement data: average plaquet flux (real part)\n    //,   flux_imag_squared(\"Fl2imag2\") // \"\" (imaginary part)\n    ,   spin_corr(\"Spin_corr\")\n    ,   flux_corr(\"Flux_corr\")\n    ,   flip_rate() // Single flip acceptance rate\n    ,   filename_(output_file) // Filename for data saving\n        \n    {  \n    ////////////////////////////////////////////////////////////////////////////////////////////\n    // Some necessary initializations: /////////////////////////////////////////////////////////\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    // -> CRS format:\n    val = get_val(def_matrix());\n    col_idx = get_col_idx(def_matrix());\n    row_ptr = get_row_ptr(def_matrix());\n\n    // Initialize plaquettes for flux measurements:\n    plaquettes = create_plaquettes();\n    //plaquettes2 = create_plaquettes_2();\n\n    // Number of system sites:\n    N_ = size(row_ptr)[0] - 1;\n\n    // Initial eigenvalues and bandwidth:\n    vec ev = get_evals(val, col_idx, row_ptr);    \n    \n    bw_save << \"bw.saved\";\n    std::ifstream bw_loadfile(bw_save.str().c_str(), std::ifstream::in);\n    if(bw_loadfile.good())\n    {\n        bw_loadfile >> s_;\n        bw_loadfile.close();\n    }\n    else\n    {\n        s_ = -ev[0];\n\n        if (me_ == 1)\n            std::cout << \"Calculating bandwidth ...\" << std::endl;\n    \n        // Determine bandwidth by diagonalizing 1000 random configurations:\n        for (int ii = 0; ii < 1000; ii++)\n        {\n            // Random configuration:\n            val = get_val(randomize(def_matrix())); \n            ev = get_evals(val, col_idx, row_ptr);\n\n            if (s_ < -ev[0])\n                s_ = -ev[0];\n\n        }\n\n        if (me_ == 1)\n        {\n            std::ofstream bw_savefile(bw_save.str().c_str(), std::ofstream::trunc);\n            bw_savefile << s_;\n        }\n    }\n\n    // Initialize parameters for KPM/GF calculations from bandwidth:\n    int_min = 0.;\n    int_max = 0.9999999*s_;\n    step_ = (int_max - int_min)/double(intsteps_ - 1);\n\n    if (me_ == 1)\n    std::cout << \"Bandwidth check: E_0 = \" << ev[0] << \", int_max = \" << int_max << \", s_ = \" << s_ << std::endl;\n\n    // This is pi, a famous number:\n    pi = M_PI; \n    twopi = 2*M_PI;\n\n    // Repeatedly used values for the integration in main part:\n    Del_rho = vec(intsteps_); // reserve memory\n    \n    y_values = cx_mat(M_, intsteps_, fill::zeros); // cf. warning above!!!\n    tanh_values = vec(intsteps_, fill::zeros);\n\n    double EE;\n\n    for (int jj = 0; jj < intsteps_; jj++)\n    {\n        // Linear distribution of abscissas (for trapezoidal or Simpson integration):\n        EE = int_min + jj*step_;\n        \n        // Tabulation of values that are repeatedly needed during calculation of Green functions:\n        tanh_values[jj] = tanh(beta_*EE/2.);\n\n        for (int mm = 0; mm < M_; mm++)\n        {\n            // round brackets!!!\n            y_values(mm, jj) = 2.0 * exp(-std::complex<double>(0.,1.)*double(mm)*acos(EE/s_)) / (sqrt(s_*s_ - EE*EE));\n        }\n\n    }\n\n    // Calculate kernel factors (needed during the calculation of Chebyshev moments)\n    kernel_factors = vec(M_, fill::zeros);\n\n    for (int mm = 0; mm < M_; mm++)\n    {\n        // Jackson kernel:\n        kernel_factors[mm] = ((double(M_) - double(mm) + 1)*cos(pi*double(mm)/(double(M_) + 1)) + sin(pi*double(mm)/(double(M_) + 1))*cos(pi/(double(M_) + 1))/sin(pi/(double(M_) + 1))) / (double(M_) + 1); \n    }\n\n    // Reserve memory for vectors that are repeatedly filled below: \n    dr = vec(intsteps_, fill::zeros);\n    mom_i_plus_ij = cx_vec(M_, fill::zeros);\n    mom_i_plus_j = cx_vec(M_, fill::zeros);\n    mom_ii = cx_vec(M_, fill::zeros);\n    mom_jj = cx_vec(M_, fill::zeros);\n\n    mom = cx_vec(M_);\n    i_ = cx_vec(N_);\n    j_2 = cx_vec(N_);\n    j_1 = cx_vec(N_);\n    j_ = cx_vec(N_);\n\n    sp_cx_mat ham_sp(N_, N_);\n\n    // Initialize single flip acceptance rate 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; // fliprate\n        int n_tot = n + ntherm;\n        double tau_en, tau_fl; // autocorrelation times\n\n        vec eval;\n\n        std::stringstream matrix_output; // needed for saving configurations (only 'val' needed)\n        matrix_output << \"val_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            val.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            // MC Step:\n            step();\n\n            // Get Eigenvalues for swapping and observable calculations:\n            eval = get_evals(val, col_idx, row_ptr);\n\n            // Communication with master process:\n            if (ntherm % sweeps_per_swap == 0)\n            {\n                // Replica exchange: \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            // Saving: \n            if (ntherm % sweeps_per_save == 0)\n            {\n                // Save Z2 configuration:\n                val.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        // Output for orientation (only for process 1):\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            // MC step:\n            step();\n\n            // Get Eigenvalues for swapping and observable calculations:\n            eval = get_evals(val, col_idx, row_ptr);\n            \n            // Output eigenvalue and flux configurations:\n            //output_eigenvalues(eval);\n            //output_flux_confs();\n            //output_P_n();\n\n            // Measure observables:\n            measure(eval);\n            \n            // Communication with Master process:\n            if (n % sweeps_per_swap == 0)\n            {\n                // Replica exchange: \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                val.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        // Print observables      \n        /*std::cout.precision(17);\n        std::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        std::cout << flux_real.name() << \":\\t\" << flux_real.mean()\n            << \" +- \" << flux_real.error() << \";\\ttau = \" << flux_real.tau() \n            << \";\\tconverged: \" << alps::convergence_to_text(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    // Iteration step (= \"Metropolis sweep\"): \n    void step()\n    {\n        int kk, i, j; // Running indices \n        int idx; // Index in val vector\n         \n        double Delta_F; // Free energy change\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            // Switch sign of random matrix entry:\n            int die = roll_die(length_);\n            coord1 = v_[die]/(N_);\n            coord2 = v_[die]%(N_);\n\n            // Calculate change in energy density via Green function / KPM method:\n            Del_rho = Delta_rho_dE(val, col_idx, row_ptr, coord1, coord2); \n\n            // Calculate free energy by integration:\n            Delta_F = integrate_free_energy(Del_rho);\n            \n            // Weight and random number:\n            alpha = 1./ (1. + exp(beta_ * (Delta_F)));\n            gamma = rng_();\n\n            // Accepted?\n            if (gamma <= alpha) \n            {                  \n                // Update pair of matrix entries:\n                // Check which index in val is changed\n                idx = get_idx(col_idx, row_ptr, coord1, coord2); \n                if (idx < size(val)[0])\n                    val(idx) *= -1;\n                else\n                    std::cout << \"WARNING: Severe error during update trial\" << std::endl;\n\n                idx = get_idx(col_idx, row_ptr, coord2, coord1);\n                if (idx < size(val)[0])\n                    val(idx) *= -1;\n                else\n                    std::cout << \"WARNING: Severe error during update trial\" << std::endl;\n                \n                // Single flip acceptance rate + 1\n                flip_rate += 1;\n            }\n            count += 1;\n        }\n    }\n    \n    ////////////////////////////////////////////////////////////////////////////////////////////\n    // KPM / Green function part: //////////////////////////////////////////////////////////////\n    ////////////////////////////////////////////////////////////////////////////////////////////\n\n    // Recursive calculation of moments for the Chebyshev expansion (all diagonal):\n    cx_vec moments(cx_vec val, vec col_idx, vec row_ptr, int i, int j, std::string num)\n    {   \n        mom = cx_vec(M_, fill::zeros);\n        i_ = cx_vec(N_, fill::zeros);\n        j_2 = cx_vec(N_, fill::zeros);\n\n        if (i == j)\n        {\n            i_[i] = 1.;\n            j_2[j] = 1.;\n        }\n        else if (i != j && num == \"real\")\n        {\n            i_[i] = 1.;\n            i_[j] = 1.;\n            j_2[i] = 1.;\n            j_2[j] = 1.;\n        }\n        else if (i != j && num == \"imag\")\n        {\n            i_[i] = 1.;\n            i_[j] = std::complex<double>(0.0, -1.0);\n            j_2[i] = 1.;\n            j_2[j] = std::complex<double>(0.0, 1.0);\n        }\n        \n        j_1 = compl_mat_vec_multiply(val/s_, col_idx, row_ptr, j_2);\n        \n        // First two moments:\n        mom[0] = dot(i_ , j_2);\n        mom[1] = dot(i_ , j_1);\n          \n        // Improved Chebyshev recursion: \n        // mom[2m] = 2 <j_m|j_m> - mom[0]\n        // mom[2m+1] = 2 <j_m+1|j_m> - mom[1]\n        if (num == \"real\") // every odd moment is zero then!\n        {\n            for (int m = 1; m < M_/2; m++)\n            {\n                j_ = 2.*compl_mat_vec_multiply(val/s_, col_idx, row_ptr, j_1) - j_2;  \n                mom[2*m] = 2.*cdot(j_1, j_1) - mom[0];\n                j_2 = j_1;\n                j_1 = j_; \n            }\n        }\n        else if (num == \"imag\") // Here we have to iterate all the moments!\n        {\n            for (int m = 1; m < M_/2; m++)\n            {\n                j_ = 2.*compl_mat_vec_multiply(val/s_, col_idx, row_ptr, j_1) - j_2;  \n                mom[2*m] = 2.*cdot(j_1, j_1) - mom[0];\n                mom[2*m+1] = 2.*cdot(j_, j_1) - mom[1];\n                j_2 = j_1;\n                j_1 = j_; \n            }\n        }\n        \n        // Multiply each moment by kernel factor:\n        for (int mm = 1; mm < M_; mm++)\n        {\n            mom[mm] *= kernel_factors[mm];\n        }\n            \n        return mom;\n    }\n    \n    // Green Function\n    std::complex<double> green(cx_vec mmts, int MM, int jj, std::string num)\n    {\n        const std::complex<double> im(0., 1.);\n        double EE = int_min + jj*step_;\n        std::complex<double> value = mmts[0] / (sqrt(s_*s_ - EE*EE));\n\n        // Approximate GF with MM Chebyshev moments:\n        if (num == \"real\") // every second moment is zero here ...\n        {    \n            for (int mm = 2; mm < MM; mm+=2)\n            {\n                value += mmts[mm]*y_values(mm,jj);\n            }\n        }\n        else if (num == \"imag\")\n        {\n            for (int mm = 1; mm < MM; mm++)\n            {\n                value += mmts[mm]*y_values(mm,jj);\n            }\n        }\n\n        return im*value;\n    }\n\n    //////////////////////////////////////////////////////////////////////\n    // Calculate function Im(log(d(E))) via Green Function / KPM method\n    //////////////////////////////////////////////////////////////////////\n    \n    vec Delta_rho_dE(cx_vec val, vec col_idx, vec row_ptr, int c1, int c2)\n    {\n        std::complex<double> im(0., 1.);\n\n        std::complex<double> Delta_ij = val(get_idx(col_idx, row_ptr, c1, c2));\n        Delta_ij *= -2.0;\n        std::complex<double> Delta_sq = Delta_ij * Delta_ij;\n        std::complex<double> g_ij, g_ji, g_ii, g_jj, g_i_plus_j, g_i_plus_ij;\n        std::complex<double> d;\n\n        // Vectors with Chebyshev moments:\n        mom_ii = moments(val, col_idx, row_ptr, c1, c1, \"real\");\n        mom_jj = moments(val, col_idx, row_ptr, c2, c2, \"real\");\n        mom_i_plus_j = moments(val, col_idx, row_ptr, c1, c2, \"real\");\n        mom_i_plus_ij = moments(val, col_idx, row_ptr, c1, c2, \"imag\");\n\n        // Calculate Im(log(d(E))) from Green Functions:\n        for (int j = 0; j < intsteps_; ++j)\n        {            \n            // Calculate Chebyshev expansion of Green functions:\n            g_ii = green(mom_ii, M_, j, \"real\");\n            g_jj = green(mom_jj, M_, j, \"real\");\n            g_i_plus_j = green(mom_i_plus_j, M_, j, \"real\");\n            g_i_plus_ij = green(mom_i_plus_ij, M_, j, \"imag\");\n            \n            // (Antisymmetry can be included: g_ij = -g_ji) \n            g_ij = 0.5*(g_i_plus_j - im*g_i_plus_ij - (1. - im)*(g_ii + g_jj));\n            g_ji = 0.5*(g_i_plus_j + im*g_i_plus_ij - (1. + im)*(g_ii + g_jj));\n             \n            // d(E) = det (1 + G(E)*Delta(E)):\n            d = (1. + Delta_ij * g_ji) * (1. - Delta_ij * g_ij) + Delta_sq*g_ii*g_jj; \n\n            // im lim_(eps -> 0) log(d(E + i*eps)) = (rho(E) - rho'(E)) dE:\n            dr[j] = imag(log(d));             \n        }\n\n        return dr;\n        \n    }\n     \n    /////////////////////////////////////////////////////////\n    // Calculate free energy change by integration:\n    /////////////////////////////////////////////////////////  \n\n    double integrate_free_energy(vec d_rho)\n    {\n        double df, m;\n        double integral1 = 0.0;\n        double E;\n        double value;\n                \n        // Semi-open integration (cf. \"Numerical recipes in C\", Press et al.)\n        for (int jj = 0; jj < intsteps_ - 1; ++jj)\n        {\n            //std::cout << tanh_values[jj] << \" \" << d_rho[jj] << std::endl;\n            value = tanh_values[jj]*d_rho[jj];\n\n            if (jj == 1)\n                integral1 += value / 2.;\n            else if (jj == intsteps_ - 2) \n                integral1 += 1.5 * value;\n            else\n                integral1 += value;\n        }\n\n        df = -integral1 * step_ / twopi;\n        \n        return df;\n    }\n    \n    ////////////////////////////////////////////////////////////////////////////////////////////\n    ////////////////////////////////////////////////////////////////////////////////////////////\n    ////////////////////////////////////////////////////////////////////////////////////////////\n    \n    void measure(vec eval)\n    {      \n        std::complex <double> fl, fl2, op;\n        double E_, dE_;\n        double p;\n        double fl_real;\n        //double fl_imag;\n        double fl2_real;\n        //double fl2_imag;\n        double corr;\n        double flcorr;\n        //sp_cx_mat ham_sp = get_sparse(val, col_idx, row_ptr);\n        ham_sp = get_sparse(val, col_idx, row_ptr);\n\n        E_ = en(eval, beta_);\n        dE_ = diffE(eval, beta_);\n\n        // Measure average flux per plaquet and disorder: \n        p = get_p(ham_sp, plaquettes);\n        fl = flux(ham_sp, plaquettes);\n        fl_real = std::real(fl);\n        //fl2 = flux(ham_sp, plaquettes2);\n        //fl2_real = std::real(fl2);\n        //op = pseudo_ord_par(ham_sp, plaquettes);\n        //fl_imag = std::real(op);\n\n        // Measure spin-spin correlation:\n        corr = correlation(ham_sp, v_, beta_);\n        flcorr = flux_correlation(ham_sp, plaquettes);\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        //flux2_real << fl2_real;\n        //flux2_imag << fl2_imag;\n        //flux2_real_squared << fl2_real*fl2_real;\n        //flux2_imag_squared << fl2_imag*fl2_imag;\n        spin_corr << corr;\n        flux_corr << flcorr;\n    }\n\n    void output_flux_confs()\n    {\n        //sp_cx_mat ham = get_sparse(val, col_idx, row_ptr);\n        ham_sp = get_sparse(val, col_idx, row_ptr);\n        cx_vec fl_confs = flux_confs(ham_sp, 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    void output_eigenvalues(vec eval)\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(eval)[0]/2; iii++)\n        {\n            eig << std::setprecision(17) << eval[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;\n        double beta_alt = 1/calc_temp(T_min, T_max, me_ - 1, np_, dist);\n        cx_vec H_a(size(val)[0], fill::zeros); // receive\n        cx_vec H_b = val; // send\n        vec eigval = get_evals(val, col_idx, row_ptr);\n\n        double f2 = -beta_alt * free_en(eigval, beta_alt);\n        double f3 = beta_ * free_en(eigval, beta_);\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 < size(val)[0]; jj++)\n            {\n                MPI_Recv(&H_a(jj), 1, MPI_DOUBLE_COMPLEX, me_- 1, 3, MPI_COMM_WORLD, &status);\n            }\n            \n            // Send own replica to left neighbour\n            for (jj = 0; jj < size(val)[0]; jj++)\n            {\n                MPI_Send(&H_b(jj), 1, MPI_DOUBLE_COMPLEX, me_- 1, 4, MPI_COMM_WORLD);\n            }\n\n            val = H_a;\n        }\n    }\n\n    // Swap replica with right neighbour ...\n    void swapright()\n    {\n        MPI_Status status;\n        int control = 0;\n        int jj;\n        double beta_alt = 1/calc_temp(T_min, T_max, me_ + 1, np_, dist);\n        cx_vec H_b(size(val)[0], fill::zeros); // receive (here it's the other way round!!!)\n        cx_vec H_a = val; // send\n        vec eigval = get_evals(val, col_idx, row_ptr);\n\n        double f1 = -beta_alt * free_en(eigval, beta_alt);\n        double f4 = beta_ * free_en(eigval, beta_);\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 < size(val)[0]; jj++)\n            {\n                MPI_Send(&H_a(jj), 1, MPI_DOUBLE_COMPLEX, me_+ 1, 3, MPI_COMM_WORLD);\n            }\n\n            // Receive replica from right neighbour\n            for (jj = 0; jj < size(val)[0]; jj++)\n            {\n                MPI_Recv(&H_b(jj), 1, MPI_DOUBLE_COMPLEX, me_+ 1, 4, MPI_COMM_WORLD, &status);\n            }\n\n            val = H_b;\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                \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/\"+flux2_real.representation()] >> flux2_real;\n        //ar[\"/simulation/results/\"+flux2_imag.representation()] >> flux2_imag;\n        //ar[\"/simulation/results/\"+flux2_real_squared.representation()] >> flux2_real_squared;\n        //ar[\"/simulation/results/\"+flux2_imag_squared.representation()] >> flux2_imag_squared;\n        ar[\"/simulation/results/\"+spin_corr.representation()] >> spin_corr;\n        ar[\"/simulation/results/\"+flux_corr.representation()] >> flux_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/\"+flux2_real.representation()] << flux2_real;\n        //ar[\"/simulation/results/\"+flux2_imag.representation()] << flux2_imag;\n        //ar[\"/simulation/results/\"+flux2_real_squared.representation()] << flux2_real_squared;\n        //ar[\"/simulation/results/\"+flux2_imag_squared.representation()] << flux2_imag_squared;\n        ar[\"/simulation/results/\"+spin_corr.representation()] << spin_corr;\n        ar[\"/simulation/results/\"+flux_corr.representation()] << flux_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    sp_cx_mat randomize(sp_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    ////////////////////////////////////////////////////////////////\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    double s_;\n    double ld;\n    std::stringstream bw_save;\n    double lambda_;\n    int intsteps_;\n    int M_;\n    \n    // Parameters for all integrations:\n    double int_min;\n    double int_max;\n    double step_;\n    double pi;\n    double twopi;\n\n    size_t N_;\n\n    // Configuration in CRS Format:\n    cx_vec val;\n    vec col_idx;\n    vec row_ptr;\n\n    std::vector<int> v_;\n    int length_;\n\n    vec Del_rho;\n    cx_mat y_values;\n    vec tanh_values;\n    vec d_values;\n\n    vec kernel_factors;\n\n    vec dr;\n    cx_vec mom_i_plus_ij;\n    cx_vec mom_i_plus_j;\n    cx_vec mom_ii;\n    cx_vec mom_jj;\n\n    cx_vec mom;\n    cx_vec i_;\n    cx_vec j_2;\n    cx_vec j_1;\n    cx_vec j_;\n\n    sp_cx_mat ham_sp;\n\n    Mat<int> plaquettes;\n    Mat<int> plaquettes2;\n\n    // ALPS Observables:\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 flux2_real;\n    //alps::RealObservable flux2_imag;\n    alps::RealObservable flux2_real_squared;\n    //alps::RealObservable flux2_imag_squared;\n    alps::RealObservable spin_corr;\n    alps::RealObservable flux_corr;\n\n    int flip_rate;\n\n    signed int sign;\n\n    std::string dist;\n    std::string filename_;\n};\n", "meta": {"hexsha": "ef9aefbd8a93fb08c88397c1dadf8f29810a399b", "size": 41850, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "simulation.hpp", "max_stars_repo_name": "timeschmann/Kitaev_QMC_KPM", "max_stars_repo_head_hexsha": "6dbeceadf93c6319a746fa69e6e780f7570f72d3", "max_stars_repo_licenses": ["MIT"], "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_KPM", "max_issues_repo_head_hexsha": "6dbeceadf93c6319a746fa69e6e780f7570f72d3", "max_issues_repo_licenses": ["MIT"], "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_KPM", "max_forks_repo_head_hexsha": "6dbeceadf93c6319a746fa69e6e780f7570f72d3", "max_forks_repo_licenses": ["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.6473594549, "max_line_length": 205, "alphanum_fraction": 0.5083870968, "num_tokens": 10476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.808067204308405, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.48801750847178355}}
{"text": "#include <boost/math/special_functions/ellint_3.hpp>\n", "meta": {"hexsha": "3b556a06491fac5338925a8edf209353808c5829", "size": 53, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_special_functions_ellint_3.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_special_functions_ellint_3.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_special_functions_ellint_3.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 26.5, "max_line_length": 52, "alphanum_fraction": 0.8301886792, "num_tokens": 14, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080671950640463, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.48801750288882123}}
{"text": "#include <chrono>\n#include <cmath>\n#include <thread>\n\n#include <ct/optcon/optcon.h>\n#include <Eigen/Eigenvalues>\n\n#include \"gflags/gflags.h\"\n#include \"third_party/matplotlib-cpp/matplotlibcpp.h\"\n#include \"y2018/control_loops/python/arm_bounds.h\"\n#include \"y2018/control_loops/python/dlqr.h\"\n\nDEFINE_double(boundary_scalar, 1500.0, \"Test command-line flag\");\nDEFINE_double(velocity_boundary_scalar, 10.0, \"Test command-line flag\");\nDEFINE_double(boundary_rate, 20.0, \"Sigmoid rate\");\nDEFINE_bool(linear, false, \"If true, linear, else see sigmoid.\");\nDEFINE_bool(sigmoid, false, \"If true, sigmoid, else exponential.\");\nDEFINE_double(round_corner, 0.0, \"Corner radius of the constraint box.\");\nDEFINE_double(convergance, 1e-12, \"Residual before finishing the solver.\");\nDEFINE_double(position_allowance, 5.0,\n              \"Distance to Velocity at which we have 0 penalty conversion.\");\nDEFINE_double(bounds_offset, 0.02, \"Offset the quadratic boundary in by this\");\nDEFINE_double(linear_bounds_offset, 0.00,\n              \"Offset the linear boundary in by this\");\nDEFINE_double(yrange, 1.0,\n              \"+- y max for saturating out the state for the cost function.\");\nDEFINE_bool(debug_print, false, \"Print the debugging print from the solver.\");\nDEFINE_bool(print_starting_summary, true,\n            \"Print the summary on the pre-solution.\");\nDEFINE_bool(print_summary, false, \"Print the summary on each iteration.\");\nDEFINE_bool(quadratic, true, \"If true, quadratic bounds penalty.\");\n\nDEFINE_bool(reset_every_cycle, false,\n            \"If true, reset the initial guess every cycle.\");\n\nDEFINE_double(seconds, 1.5, \"The number of seconds to simulate.\");\n\nDEFINE_double(theta0, 1.0, \"Starting theta0\");\nDEFINE_double(theta1, 0.9, \"Starting theta1\");\n\nDEFINE_double(goal_theta0, -0.5, \"Starting theta0\");\nDEFINE_double(goal_theta1, -0.5, \"Starting theta1\");\n\nDEFINE_double(qpos1, 0.2, \"qpos1\");\nDEFINE_double(qvel1, 4.0, \"qvel1\");\nDEFINE_double(qpos2, 0.2, \"qpos2\");\nDEFINE_double(qvel2, 4.0, \"qvel2\");\n\nDEFINE_double(u_over_linear, 0.0, \"Linear penalty for too much U.\");\nDEFINE_double(u_over_quadratic, 4.0, \"Quadratic penalty for too much U.\");\n\nDEFINE_double(time_horizon, 0.75, \"MPC time horizon\");\n\nDEFINE_bool(only_print_eigenvalues, false,\n            \"If true, stop after computing the final eigenvalues\");\n\nDEFINE_bool(plot_xy, false, \"If true, plot the xy trajectory of the end of the arm.\");\nDEFINE_bool(plot_cost, false, \"If true, plot the cost function.\");\nDEFINE_bool(plot_state_cost, false,\n            \"If true, plot the state portion of the cost function.\");\nDEFINE_bool(plot_states, false, \"If true, plot the states.\");\nDEFINE_bool(plot_u, false, \"If true, plot the control signal.\");\n\nstatic constexpr double kDt = 0.00505;\n\nnamespace y2018 {\nnamespace control_loops {\n\n::Eigen::Matrix<double, 4, 4> NumericalJacobianX(\n    ::Eigen::Matrix<double, 4, 1> (*fn)(\n        ::Eigen::Ref<::Eigen::Matrix<double, 4, 1>> X,\n        ::Eigen::Ref<::Eigen::Matrix<double, 2, 1>> U, double dt),\n    ::Eigen::Matrix<double, 4, 1> X, ::Eigen::Matrix<double, 2, 1> U, double dt,\n    const double kEpsilon = 1e-4) {\n  constexpr int num_states = 4;\n  ::Eigen::Matrix<double, 4, 4> answer = ::Eigen::Matrix<double, 4, 4>::Zero();\n\n  // It's more expensive, but +- epsilon will be more reliable\n  for (int i = 0; i < num_states; ++i) {\n    ::Eigen::Matrix<double, 4, 1> dX_plus = X;\n    dX_plus(i, 0) += kEpsilon;\n    ::Eigen::Matrix<double, 4, 1> dX_minus = X;\n    dX_minus(i, 0) -= kEpsilon;\n    answer.block<4, 1>(0, i) =\n        (fn(dX_plus, U, dt) - fn(dX_minus, U, dt)) / kEpsilon / 2.0;\n  }\n  return answer;\n}\n\n::Eigen::Matrix<double, 4, 2> NumericalJacobianU(\n    ::Eigen::Matrix<double, 4, 1> (*fn)(\n        ::Eigen::Ref<::Eigen::Matrix<double, 4, 1>> X,\n        ::Eigen::Ref<::Eigen::Matrix<double, 2, 1>> U, double dt),\n    ::Eigen::Matrix<double, 4, 1> X, ::Eigen::Matrix<double, 2, 1> U, double dt,\n    const double kEpsilon = 1e-4) {\n  constexpr int num_states = 4;\n  constexpr int num_inputs = 2;\n  ::Eigen::Matrix<double, num_states, num_inputs> answer =\n      ::Eigen::Matrix<double, num_states, num_inputs>::Zero();\n\n  // It's more expensive, but +- epsilon will be more reliable\n  for (int i = 0; i < num_inputs; ++i) {\n    ::Eigen::Matrix<double, 2, 1> dU_plus = U;\n    dU_plus(i, 0) += kEpsilon;\n    ::Eigen::Matrix<double, 2, 1> dU_minus = U;\n    dU_minus(i, 0) -= kEpsilon;\n    answer.block<4, 1>(0, i) =\n        (fn(X, dU_plus, dt) - fn(X, dU_minus, dt)) / kEpsilon / 2.0;\n  }\n  return answer;\n}\n\n// This code is for analysis and simulation of a double jointed arm.  It is an\n// attempt to see if a MPC could work for arm control under constraints.\n\n// Describes a double jointed arm.\n// A large chunk of this code comes from demos.  Most of the raw pointer,\n// shared_ptr, and non-const &'s come from the library's conventions.\ntemplate <typename SCALAR>\nclass MySecondOrderSystem : public ::ct::core::ControlledSystem<4, 2, SCALAR> {\n public:\n  static const size_t STATE_DIM = 4;\n  static const size_t CONTROL_DIM = 2;\n\n  MySecondOrderSystem(::std::shared_ptr<::ct::core::Controller<4, 2, SCALAR>>\n                          controller = nullptr)\n      : ::ct::core::ControlledSystem<4, 2, SCALAR>(\n            controller, ::ct::core::SYSTEM_TYPE::GENERAL) {}\n\n  MySecondOrderSystem(const MySecondOrderSystem &arg)\n      : ::ct::core::ControlledSystem<4, 2, SCALAR>(arg) {}\n\n  // Deep copy\n  MySecondOrderSystem *clone() const override {\n    return new MySecondOrderSystem(*this);\n  }\n  virtual ~MySecondOrderSystem() {}\n\n  static constexpr SCALAR l1 = 46.25 * 0.0254;\n  static constexpr SCALAR l2 = 41.80 * 0.0254;\n\n  static constexpr SCALAR m1 = 9.34 / 2.2;\n  static constexpr SCALAR m2 = 9.77 / 2.2;\n\n  static constexpr SCALAR J1 = 2957.05 * 0.0002932545454545454;\n  static constexpr SCALAR J2 = 2824.70 * 0.0002932545454545454;\n\n  static constexpr SCALAR r1 = 21.64 * 0.0254;\n  static constexpr SCALAR r2 = 26.70 * 0.0254;\n\n  static constexpr SCALAR G1 = 140.0;\n  static constexpr SCALAR G2 = 90.0;\n\n  static constexpr SCALAR stall_torque = 1.41;\n  static constexpr SCALAR free_speed = (5840.0 / 60.0) * 2.0 * M_PI;\n  static constexpr SCALAR stall_current = 89.0;\n  static constexpr SCALAR R = 12.0 / stall_current;\n\n  static constexpr SCALAR Kv = free_speed / 12.0;\n  static constexpr SCALAR Kt = stall_torque / stall_current;\n\n  // Evaluate the system dynamics.\n  //\n  // Args:\n  //   state: current state (position, velocity)\n  //   t: current time (gets ignored)\n  //   control: control action\n  //   derivative: (velocity, acceleration)\n  virtual void computeControlledDynamics(\n      const ::ct::core::StateVector<4, SCALAR> &state, const SCALAR & /*t*/,\n      const ::ct::core::ControlVector<2, SCALAR> &control,\n      ::ct::core::StateVector<4, SCALAR> &derivative) override {\n    derivative = Dynamics(state, control);\n  }\n\n  static ::Eigen::Matrix<double, 4, 1> Dynamics(\n      const ::ct::core::StateVector<4, SCALAR> &X,\n      const ::ct::core::ControlVector<2, SCALAR> &U) {\n    ::ct::core::StateVector<4, SCALAR> derivative;\n    const SCALAR alpha = J1 + r1 * r1 * m1 + l1 * l1 * m2;\n    const SCALAR beta = l1 * r2 * m2;\n    const SCALAR gamma = J2 + r2 * r2 * m2;\n\n    const SCALAR s = sin(X(0) - X(2));\n    const SCALAR c = cos(X(0) - X(2));\n\n    // K1 * d^2 theta/dt^2 + K2 * d theta/dt = torque\n    ::Eigen::Matrix<SCALAR, 2, 2> K1;\n    K1(0, 0) = alpha;\n    K1(1, 0) = K1(0, 1) = c * beta;\n    K1(1, 1) = gamma;\n\n    ::Eigen::Matrix<SCALAR, 2, 2> K2 = ::Eigen::Matrix<SCALAR, 2, 2>::Zero();\n    K2(0, 1) = s * beta * X(3);\n    K2(1, 0) = -s * beta * X(1);\n\n    const SCALAR kNumDistalMotors = 2.0;\n    ::Eigen::Matrix<SCALAR, 2, 1> torque;\n    torque(0, 0) = G1 * (U(0) * Kt / R - X(1) * G1 * Kt / (Kv * R));\n    torque(1, 0) = G2 * (U(1) * kNumDistalMotors * Kt / R -\n                         X(3) * G2 * Kt * kNumDistalMotors / (Kv * R));\n\n    ::Eigen::Matrix<SCALAR, 2, 1> velocity;\n    velocity(0, 0) = X(0);\n    velocity(1, 0) = X(2);\n\n    const ::Eigen::Matrix<SCALAR, 2, 1> accel =\n        K1.inverse() * (torque - K2 * velocity);\n\n    derivative(0) = X(1);\n    derivative(1) = accel(0);\n    derivative(2) = X(3);\n    derivative(3) = accel(1);\n\n    return derivative;\n  }\n\n  // Runge-Kutta.\n  static ::Eigen::Matrix<double, 4, 1> DiscreteDynamics(\n      ::Eigen::Ref<::Eigen::Matrix<double, 4, 1>> X,\n      ::Eigen::Ref<::Eigen::Matrix<double, 2, 1>> U, double dt) {\n    const double half_dt = dt * 0.5;\n    ::Eigen::Matrix<double, 4, 1> k1 = Dynamics(X, U);\n    ::Eigen::Matrix<double, 4, 1> k2 = Dynamics(X + half_dt * k1, U);\n    ::Eigen::Matrix<double, 4, 1> k3 = Dynamics(X + half_dt * k2, U);\n    ::Eigen::Matrix<double, 4, 1> k4 = Dynamics(X + dt * k3, U);\n    return X + dt / 6.0 * (k1 + 2.0 * k2 + 2.0 * k3 + k4);\n  }\n};\n\ntemplate <size_t STATE_DIM, size_t CONTROL_DIM, typename SCALAR_EVAL = double,\n          typename SCALAR = SCALAR_EVAL>\nclass ObstacleAwareQuadraticCost\n    : public ::ct::optcon::TermBase<STATE_DIM, CONTROL_DIM, SCALAR_EVAL,\n                                    SCALAR> {\n public:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n  typedef Eigen::Matrix<SCALAR_EVAL, STATE_DIM, 1> state_vector_t;\n  typedef Eigen::Matrix<SCALAR_EVAL, STATE_DIM, STATE_DIM> state_matrix_t;\n  typedef Eigen::Matrix<SCALAR_EVAL, CONTROL_DIM, CONTROL_DIM> control_matrix_t;\n  typedef Eigen::Matrix<SCALAR_EVAL, CONTROL_DIM, STATE_DIM>\n      control_state_matrix_t;\n  typedef Eigen::Matrix<SCALAR_EVAL, STATE_DIM, STATE_DIM>\n      state_matrix_double_t;\n  typedef Eigen::Matrix<SCALAR_EVAL, CONTROL_DIM, CONTROL_DIM>\n      control_matrix_double_t;\n  typedef Eigen::Matrix<SCALAR_EVAL, CONTROL_DIM, STATE_DIM>\n      control_state_matrix_double_t;\n\n  ObstacleAwareQuadraticCost(const ::Eigen::Matrix<double, 2, 2> &R,\n                             const ::Eigen::Matrix<double, 4, 4> &Q)\n      : R_(R), Q_(Q) {}\n\n  ObstacleAwareQuadraticCost(const ObstacleAwareQuadraticCost &arg)\n      : R_(arg.R_), Q_(arg.Q_) {}\n      static constexpr double kEpsilon = 1.0e-5;\n\n  virtual ~ObstacleAwareQuadraticCost() {}\n\n  ObstacleAwareQuadraticCost<STATE_DIM, CONTROL_DIM, SCALAR_EVAL, SCALAR>\n      *clone() const override {\n    return new ObstacleAwareQuadraticCost(*this);\n  }\n\n  double SaturateX(double x, double yrange) {\n    return 2.0 * ((1.0 / (1.0 + ::std::exp(-x * 2.0 / yrange)) - 0.5)) * yrange;\n  }\n\n  SCALAR distance(const Eigen::Matrix<SCALAR, STATE_DIM, 1> &x,\n                  const Eigen::Matrix<SCALAR, CONTROL_DIM, 1> & /*u*/) {\n    constexpr double kCornerNewUpper0 = 0.35;\n    // constexpr double kCornerUpper1 = 3.13;\n    // Push it up a bit further (non-real) until we have an actual path cost.\n    constexpr double kCornerNewUpper1 = 3.39;\n    constexpr double kCornerNewUpper0_far = 10.0;\n\n    // Push it up a bit further (non-real) until we have an actual path cost.\n    // constexpr double kCornerUpper0 = 0.315;\n    constexpr double kCornerUpper0 = 0.310;\n    // constexpr double kCornerUpper1 = 3.13;\n    constexpr double kCornerUpper1 = 3.25;\n    constexpr double kCornerUpper0_far = 10.0;\n\n    constexpr double kCornerLower0 = 0.023;\n    constexpr double kCornerLower1 = 1.57;\n    constexpr double kCornerLower0_far = 10.0;\n\n    const Segment new_upper_segment(\n        Point(kCornerNewUpper0, kCornerNewUpper1),\n        Point(kCornerNewUpper0_far, kCornerNewUpper1));\n    const Segment upper_segment(Point(kCornerUpper0, kCornerUpper1),\n                                Point(kCornerUpper0_far, kCornerUpper1));\n    const Segment lower_segment(Point(kCornerLower0, kCornerLower1),\n                                Point(kCornerLower0_far, kCornerLower1));\n\n    Point current_point(x(0, 0), x(2, 0));\n\n    SCALAR result = 0.0;\n    if (intersects(new_upper_segment,\n                   Segment(current_point,\n                           Point(FLAGS_goal_theta0, FLAGS_goal_theta1)))) {\n      result += hypot(current_point.x() - kCornerNewUpper0,\n                      current_point.y() - kCornerNewUpper1);\n      current_point = Point(kCornerNewUpper0, kCornerNewUpper1);\n    }\n\n    if (intersects(upper_segment,\n                   Segment(current_point,\n                           Point(FLAGS_goal_theta0, FLAGS_goal_theta1)))) {\n      result += hypot(current_point.x() - kCornerUpper0,\n                      current_point.y() - kCornerUpper1);\n      current_point = Point(kCornerUpper0, kCornerUpper1);\n    }\n\n    if (intersects(lower_segment,\n                   Segment(current_point,\n                           Point(FLAGS_goal_theta0, FLAGS_goal_theta1)))) {\n      result += hypot(current_point.x() - kCornerLower0,\n                      current_point.y() - kCornerLower1);\n      current_point = Point(kCornerLower0, kCornerLower1);\n    }\n    result += hypot(current_point.x() - FLAGS_goal_theta0,\n                    current_point.y() - FLAGS_goal_theta1);\n    return result;\n  }\n\n  virtual SCALAR evaluate(const Eigen::Matrix<SCALAR, STATE_DIM, 1> &x,\n                          const Eigen::Matrix<SCALAR, CONTROL_DIM, 1> &u,\n                          const SCALAR & /*t*/) override {\n    // Positive means violation.\n    Eigen::Matrix<SCALAR, STATE_DIM, 1> saturated_x = x;\n    SCALAR d = distance(x, u);\n    saturated_x(0, 0) = d;\n    saturated_x(2, 0) = 0.0;\n\n    saturated_x(0, 0) = SaturateX(saturated_x(0, 0), FLAGS_yrange);\n    saturated_x(2, 0) = 0.0;\n\n    //SCALAR saturation_scalar = saturated_x(0, 0) / d;\n    //saturated_x(1, 0) *= saturation_scalar;\n    //saturated_x(3, 0) *= saturation_scalar;\n\n    SCALAR result = (saturated_x.transpose() * Q_ * saturated_x +\n                     u.transpose() * R_ * u)(0, 0);\n\n    if (::std::abs(u(0, 0)) > 11.0) {\n      result += (::std::abs(u(0, 0)) - 11.0) * FLAGS_u_over_linear;\n      result += (::std::abs(u(0, 0)) - 11.0) * (::std::abs(u(0, 0)) - 11.0) *\n                FLAGS_u_over_quadratic;\n    }\n    if (::std::abs(u(1, 0)) > 11.0) {\n      result += (::std::abs(u(1, 0)) - 11.0) * FLAGS_u_over_linear;\n      result += (::std::abs(u(1, 0)) - 11.0) * (::std::abs(u(1, 0)) - 11.0) *\n                FLAGS_u_over_quadratic;\n    }\n    return result;\n  }\n\n  ct::core::StateVector<STATE_DIM, SCALAR_EVAL> stateDerivative(\n      const ct::core::StateVector<STATE_DIM, SCALAR_EVAL> &x,\n      const ct::core::ControlVector<CONTROL_DIM, SCALAR_EVAL> &u,\n      const SCALAR_EVAL &t) override {\n    SCALAR epsilon = SCALAR(kEpsilon);\n\n    ct::core::StateVector<STATE_DIM, SCALAR_EVAL> result =\n        ct::core::StateVector<STATE_DIM, SCALAR_EVAL>::Zero();\n\n    // Perterb x for both position axis and return the result.\n    for (size_t i = 0; i < STATE_DIM; i += 1) {\n      ct::core::StateVector<STATE_DIM, SCALAR_EVAL> plus_perterbed_x = x;\n      ct::core::StateVector<STATE_DIM, SCALAR_EVAL> minus_perterbed_x = x;\n      plus_perterbed_x[i] += epsilon;\n      minus_perterbed_x[i] -= epsilon;\n      result[i] = (evaluate(plus_perterbed_x, u, t) -\n                   evaluate(minus_perterbed_x, u, t)) /\n                  (epsilon * 2.0);\n    }\n    return result;\n  }\n\n  // Compute second order derivative of this cost term w.r.t. the state\n  state_matrix_t stateSecondDerivative(\n      const ct::core::StateVector<STATE_DIM, SCALAR_EVAL> &x,\n      const ct::core::ControlVector<CONTROL_DIM, SCALAR_EVAL> &u,\n      const SCALAR_EVAL &t) override {\n    state_matrix_t result = state_matrix_t::Zero();\n\n    SCALAR epsilon = SCALAR(kEpsilon);\n\n    // Perterb x a second time.\n    for (size_t i = 0; i < STATE_DIM; i += 1) {\n      ct::core::StateVector<STATE_DIM, SCALAR_EVAL> plus_perterbed_x = x;\n      ct::core::StateVector<STATE_DIM, SCALAR_EVAL> minus_perterbed_x = x;\n      plus_perterbed_x[i] += epsilon;\n      minus_perterbed_x[i] -= epsilon;\n      state_vector_t delta = (stateDerivative(plus_perterbed_x, u, t) -\n                              stateDerivative(minus_perterbed_x, u, t)) /\n                             (epsilon * 2.0);\n\n      result.col(i) = delta;\n    }\n    //::std::cout << \"Q_numeric \" << result << \" endQ\" << ::std::endl;\n    return result;\n  }\n\n  ct::core::ControlVector<CONTROL_DIM, SCALAR_EVAL> controlDerivative(\n      const ct::core::StateVector<STATE_DIM, SCALAR_EVAL> &x,\n      const ct::core::ControlVector<CONTROL_DIM, SCALAR_EVAL> &u,\n      const SCALAR_EVAL &t) override {\n    ct::core::ControlVector<CONTROL_DIM, SCALAR_EVAL> result =\n        ct::core::ControlVector<CONTROL_DIM, SCALAR_EVAL>::Zero();\n\n    SCALAR epsilon = SCALAR(kEpsilon);\n\n    // Perterb x a second time.\n    for (size_t i = 0; i < CONTROL_DIM; i += 1) {\n      ct::core::ControlVector<CONTROL_DIM, SCALAR_EVAL> plus_perterbed_u = u;\n      ct::core::ControlVector<CONTROL_DIM, SCALAR_EVAL> minus_perterbed_u = u;\n      plus_perterbed_u[i] += epsilon;\n      minus_perterbed_u[i] -= epsilon;\n      SCALAR delta = (evaluate(x, plus_perterbed_u, t) -\n                      evaluate(x, minus_perterbed_u, t)) /\n                     (epsilon * 2.0);\n\n      result[i] = delta;\n    }\n    //::std::cout << \"cd \" << result(0, 0) << \" \" << result(1, 0) << \" endcd\"\n                //<< ::std::endl;\n\n    return result;\n  }\n\n  control_state_matrix_t stateControlDerivative(\n      const ct::core::StateVector<STATE_DIM, SCALAR_EVAL> & /*x*/,\n      const ct::core::ControlVector<CONTROL_DIM, SCALAR_EVAL> & /*u*/,\n      const SCALAR_EVAL & /*t*/) override {\n    // No coupling here, so let's not bother to calculate it.\n    control_state_matrix_t result = control_state_matrix_t::Zero();\n    return result;\n  }\n\n  control_matrix_t controlSecondDerivative(\n      const ct::core::StateVector<STATE_DIM, SCALAR_EVAL> &x,\n      const ct::core::ControlVector<CONTROL_DIM, SCALAR_EVAL> &u,\n      const SCALAR_EVAL &t) override {\n    control_matrix_t result = control_matrix_t::Zero();\n\n    SCALAR epsilon = SCALAR(kEpsilon);\n\n    //static int j = 0;\n    //::std::this_thread::sleep_for(::std::chrono::milliseconds(j % 10));\n    //int k = ++j;\n    // Perterb x a second time.\n    for (size_t i = 0; i < CONTROL_DIM; i += 1) {\n      ct::core::ControlVector<CONTROL_DIM, SCALAR_EVAL> plus_perterbed_u = u;\n      ct::core::ControlVector<CONTROL_DIM, SCALAR_EVAL> minus_perterbed_u = u;\n      plus_perterbed_u[i] += epsilon;\n      minus_perterbed_u[i] -= epsilon;\n      ct::core::ControlVector<CONTROL_DIM, SCALAR_EVAL> delta =\n          (controlDerivative(x, plus_perterbed_u, t) -\n           controlDerivative(x, minus_perterbed_u, t)) /\n          (epsilon * 2.0);\n\n      //::std::cout << \"delta: \" << delta(0, 0) << \" \" << delta(1, 0) << \" k \"\n                  //<< k << ::std::endl;\n      result.col(i) = delta;\n    }\n    //::std::cout << \"R_numeric \" << result << \" endR 0.013888888888888888    k:\" << k\n                //<< ::std::endl;\n    //::std::cout << \"x \" << x << \" u \" << u << \"    k \" << k << ::std::endl;\n\n    return result;\n  }\n\n private:\n  const ::Eigen::Matrix<double, 2, 2> R_;\n  const ::Eigen::Matrix<double, 4, 4> Q_;\n};\n\ntemplate <size_t STATE_DIM, size_t CONTROL_DIM, typename SCALAR_EVAL = double,\n          typename SCALAR = SCALAR_EVAL>\nclass MyTermStateBarrier : public ::ct::optcon::TermBase<STATE_DIM, CONTROL_DIM,\n                                                         SCALAR_EVAL, SCALAR> {\n public:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n  typedef Eigen::Matrix<SCALAR_EVAL, STATE_DIM, 1> state_vector_t;\n  typedef Eigen::Matrix<SCALAR_EVAL, STATE_DIM, STATE_DIM> state_matrix_t;\n  typedef Eigen::Matrix<SCALAR_EVAL, CONTROL_DIM, CONTROL_DIM> control_matrix_t;\n  typedef Eigen::Matrix<SCALAR_EVAL, CONTROL_DIM, STATE_DIM>\n      control_state_matrix_t;\n  typedef Eigen::Matrix<SCALAR_EVAL, STATE_DIM, STATE_DIM>\n      state_matrix_double_t;\n  typedef Eigen::Matrix<SCALAR_EVAL, CONTROL_DIM, CONTROL_DIM>\n      control_matrix_double_t;\n  typedef Eigen::Matrix<SCALAR_EVAL, CONTROL_DIM, STATE_DIM>\n      control_state_matrix_double_t;\n\n  MyTermStateBarrier(BoundsCheck *bounds_check) : bounds_check_(bounds_check) {}\n\n  MyTermStateBarrier(const MyTermStateBarrier &arg)\n      : bounds_check_(arg.bounds_check_) {}\n\n  static constexpr double kEpsilon = 5.0e-6;\n\n  virtual ~MyTermStateBarrier() {}\n\n  MyTermStateBarrier<STATE_DIM, CONTROL_DIM, SCALAR_EVAL, SCALAR> *clone()\n      const override {\n    return new MyTermStateBarrier(*this);\n  }\n\n  SCALAR distance(const Eigen::Matrix<SCALAR, STATE_DIM, 1> &x,\n                  const Eigen::Matrix<SCALAR, CONTROL_DIM, 1> & /*u*/,\n                  const SCALAR & /*t*/, Eigen::Matrix<SCALAR, 2, 1> *norm) {\n    return bounds_check_->min_distance(Point(x(0, 0), x(2, 0)), norm);\n  }\n\n  virtual SCALAR evaluate(const Eigen::Matrix<SCALAR, STATE_DIM, 1> &x,\n                          const Eigen::Matrix<SCALAR, CONTROL_DIM, 1> & u,\n                          const SCALAR & t) override {\n    Eigen::Matrix<SCALAR, 2, 1> norm = Eigen::Matrix<SCALAR, 2, 1>::Zero();\n    SCALAR min_distance = distance(x, u, t, &norm);\n\n    // Velocity component (+) towards the wall.\n    SCALAR velocity_penalty = -(x(1, 0) * norm(0, 0) + x(3, 0) * norm(1, 0));\n    if (min_distance + FLAGS_bounds_offset < 0.0) {\n      velocity_penalty = 0.0;\n    }\n\n    SCALAR result;\n    //if (FLAGS_quadratic) {\n    result = FLAGS_boundary_scalar *\n                 ::std::max(0.0, min_distance + FLAGS_bounds_offset) *\n                 ::std::max(0.0, min_distance + FLAGS_bounds_offset) +\n             FLAGS_boundary_rate *\n                 ::std::max(0.0, min_distance + FLAGS_linear_bounds_offset) +\n             FLAGS_velocity_boundary_scalar *\n                 ::std::max(0.0, min_distance + FLAGS_linear_bounds_offset) *\n                 ::std::max(0.0, velocity_penalty) *\n                 ::std::max(0.0, velocity_penalty);\n    /*\n} else if (FLAGS_linear) {\nresult =\nFLAGS_boundary_scalar * ::std::max(0.0, min_distance) +\nFLAGS_velocity_boundary_scalar * ::std::max(0.0, -velocity_penalty);\n} else if (FLAGS_sigmoid) {\nresult = FLAGS_boundary_scalar /\n    (1.0 + ::std::exp(-min_distance * FLAGS_boundary_rate)) +\nFLAGS_velocity_boundary_scalar /\n    (1.0 + ::std::exp(-velocity_penalty * FLAGS_boundary_rate));\n} else {\n// Values of 4 and 15 work semi resonably.\nresult = FLAGS_boundary_scalar *\n    ::std::exp(min_distance * FLAGS_boundary_rate) +\nFLAGS_velocity_boundary_scalar *\n    ::std::exp(velocity_penalty * FLAGS_boundary_rate);\n}\nif (result < 0.0) {\nprintf(\"Result negative %f\\n\", result);\n}\n*/\n    return result;\n  }\n\n  ::ct::core::StateVector<STATE_DIM, SCALAR_EVAL> stateDerivative(\n      const ::ct::core::StateVector<STATE_DIM, SCALAR_EVAL> &x,\n      const ::ct::core::ControlVector<CONTROL_DIM, SCALAR_EVAL> &u,\n      const SCALAR_EVAL &t) override {\n    SCALAR epsilon = SCALAR(kEpsilon);\n\n    ::ct::core::StateVector<STATE_DIM, SCALAR_EVAL> result =\n        ::ct::core::StateVector<STATE_DIM, SCALAR_EVAL>::Zero();\n\n    // Perturb x for both position axis and return the result.\n    for (size_t i = 0; i < STATE_DIM; i += 2) {\n      ::ct::core::StateVector<STATE_DIM, SCALAR_EVAL> plus_perterbed_x = x;\n      ::ct::core::StateVector<STATE_DIM, SCALAR_EVAL> minus_perterbed_x = x;\n      plus_perterbed_x[i] += epsilon;\n      minus_perterbed_x[i] -= epsilon;\n      result[i] = (evaluate(plus_perterbed_x, u, t) -\n                   evaluate(minus_perterbed_x, u, t)) /\n                  (epsilon * 2.0);\n    }\n    return result;\n  }\n\n  // Compute second order derivative of this cost term w.r.t. the state\n  state_matrix_t stateSecondDerivative(\n      const ::ct::core::StateVector<STATE_DIM, SCALAR_EVAL> &x,\n      const ::ct::core::ControlVector<CONTROL_DIM, SCALAR_EVAL> &u,\n      const SCALAR_EVAL &t) override {\n    state_matrix_t result = state_matrix_t::Zero();\n\n    SCALAR epsilon = SCALAR(kEpsilon);\n\n    // Perturb x a second time.\n    for (size_t i = 0; i < STATE_DIM; i += 1) {\n      ::ct::core::StateVector<STATE_DIM, SCALAR_EVAL> plus_perterbed_x = x;\n      ::ct::core::StateVector<STATE_DIM, SCALAR_EVAL> minus_perterbed_x = x;\n      plus_perterbed_x[i] += epsilon;\n      minus_perterbed_x[i] -= epsilon;\n      state_vector_t delta = (stateDerivative(plus_perterbed_x, u, t) -\n                              stateDerivative(minus_perterbed_x, u, t)) /\n                             (epsilon * 2.0);\n\n      result.col(i) = delta;\n    }\n    return result;\n  }\n\n  ::ct::core::ControlVector<CONTROL_DIM, SCALAR_EVAL> controlDerivative(\n      const ::ct::core::StateVector<STATE_DIM, SCALAR_EVAL> & /*x*/,\n      const ::ct::core::ControlVector<CONTROL_DIM, SCALAR_EVAL> & /*u*/,\n      const SCALAR_EVAL & /*t*/) override {\n    return ::ct::core::StateVector<CONTROL_DIM, SCALAR_EVAL>::Zero();\n  }\n\n  control_state_matrix_t stateControlDerivative(\n      const ::ct::core::StateVector<STATE_DIM, SCALAR_EVAL> & /*x*/,\n      const ::ct::core::ControlVector<CONTROL_DIM, SCALAR_EVAL> & /*u*/,\n      const SCALAR_EVAL & /*t*/) override {\n    control_state_matrix_t result = control_state_matrix_t::Zero();\n\n    return result;\n  }\n\n  control_matrix_t controlSecondDerivative(\n      const ::ct::core::StateVector<STATE_DIM, SCALAR_EVAL> & /*x*/,\n      const ::ct::core::ControlVector<CONTROL_DIM, SCALAR_EVAL> & /*u*/,\n      const SCALAR_EVAL & /*t*/) override {\n    control_matrix_t result = control_matrix_t::Zero();\n    return result;\n  }\n\n  /*\n    // TODO(austin): Implement this for the automatic differentiation.\n    virtual ::ct::core::ADCGScalar evaluateCppadCg(\n        const ::ct::core::StateVector<STATE_DIM, ::ct::core::ADCGScalar> &x,\n        const ::ct::core::ControlVector<CONTROL_DIM, ::ct::core::ADCGScalar> &u,\n        ::ct::core::ADCGScalar t) override {\n      ::ct::core::ADCGScalar c = ::ct::core::ADCGScalar(0.0);\n      for (size_t i = 0; i < STATE_DIM; i++)\n        c += barriers_[i].computeActivation(x(i));\n      return c;\n    }\n  */\n\n  BoundsCheck *bounds_check_;\n};\n\nint Main() {\n  // PRELIMINIARIES\n  BoundsCheck arm_space = MakeClippedArmSpace();\n\n  constexpr size_t state_dim = MySecondOrderSystem<double>::STATE_DIM;\n  constexpr size_t control_dim = MySecondOrderSystem<double>::CONTROL_DIM;\n\n  ::std::shared_ptr<ct::core::ControlledSystem<state_dim, control_dim>>\n  oscillator_dynamics(new MySecondOrderSystem<double>());\n\n  ::std::shared_ptr<ct::core::SystemLinearizer<state_dim, control_dim>>\n      ad_linearizer(new ::ct::core::SystemLinearizer<state_dim, control_dim>(\n          oscillator_dynamics));\n\n  const double kQPos1 = FLAGS_qpos1;\n  const double kQVel1 = FLAGS_qvel1;\n  const double kQPos2 = FLAGS_qpos2;\n  const double kQVel2 = FLAGS_qvel2;\n\n  ::Eigen::Matrix<double, 4, 4> Q_step;\n  Q_step << 1.0 / (kQPos1 * kQPos1), 0.0, 0.0, 0.0, 0.0,\n      1.0 / (kQVel1 * kQVel1), 0.0, 0.0, 0.0, 0.0, 1.0 / (kQPos2 * kQPos2), 0.0,\n      0.0, 0.0, 0.0, 1.0 / (kQVel2 * kQVel2);\n  ::Eigen::Matrix<double, 2, 2> R_step;\n  R_step << 1.0 / (12.0 * 12.0), 0.0, 0.0, 1.0 / (12.0 * 12.0);\n  ::std::shared_ptr<::ct::optcon::TermQuadratic<state_dim, control_dim>>\n      quadratic_intermediate_cost(\n          new ::ct::optcon::TermQuadratic<state_dim, control_dim>(Q_step,\n                                                                  R_step));\n  // TODO(austin): Move back to this with the new Q and R\n  ::std::shared_ptr<ObstacleAwareQuadraticCost<state_dim, control_dim>>\n      intermediate_cost(new ObstacleAwareQuadraticCost<4, 2>(R_step, Q_step));\n\n  ::Eigen::Matrix<double, 4, 4> final_A =\n      NumericalJacobianX(MySecondOrderSystem<double>::DiscreteDynamics,\n                         Eigen::Matrix<double, 4, 1>::Zero(),\n                         Eigen::Matrix<double, 2, 1>::Zero(), kDt);\n\n  ::Eigen::Matrix<double, 4, 2> final_B =\n      NumericalJacobianU(MySecondOrderSystem<double>::DiscreteDynamics,\n                         Eigen::Matrix<double, 4, 1>::Zero(),\n                         Eigen::Matrix<double, 2, 1>::Zero(), kDt);\n\n  ::Eigen::Matrix<double, 4, 4> S_lqr;\n  ::Eigen::Matrix<double, 2, 4> K_lqr;\n  ::frc971::controls::dlqr(final_A, final_B, Q_step, R_step, &K_lqr, &S_lqr);\n  ::std::cout << \"A -> \" << ::std::endl << final_A << ::std::endl;\n  ::std::cout << \"B -> \" << ::std::endl << final_B << ::std::endl;\n  ::std::cout << \"K -> \" << ::std::endl << K_lqr << ::std::endl;\n  ::std::cout << \"S -> \" << ::std::endl << S_lqr << ::std::endl;\n  ::std::cout << \"Q -> \" << ::std::endl << Q_step << ::std::endl;\n  ::std::cout << \"R -> \" << ::std::endl << R_step << ::std::endl;\n  ::std::cout << \"Eigenvalues: \" << (final_A - final_B * K_lqr).eigenvalues()\n              << ::std::endl;\n\n  ::Eigen::Matrix<double, 4, 4> Q_final = 0.5 * S_lqr;\n  ::Eigen::Matrix<double, 2, 2> R_final = ::Eigen::Matrix<double, 2, 2>::Zero();\n  ::std::shared_ptr<ct::optcon::TermQuadratic<state_dim, control_dim>>\n      final_cost(new ::ct::optcon::TermQuadratic<state_dim, control_dim>(\n          Q_final, R_final));\n  if (FLAGS_only_print_eigenvalues) {\n    return 0;\n  }\n\n  ::std::shared_ptr<MyTermStateBarrier<state_dim, control_dim>> bounds_cost(\n      new MyTermStateBarrier<4, 2>(&arm_space));\n\n  // TODO(austin): Cost function needs constraints.\n  ::std::shared_ptr<::ct::optcon::CostFunctionQuadratic<state_dim, control_dim>>\n      cost_function(\n          new ::ct::optcon::CostFunctionAnalytical<state_dim, control_dim>());\n  //cost_function->addIntermediateTerm(quadratic_intermediate_cost);\n  cost_function->addIntermediateTerm(intermediate_cost);\n  cost_function->addIntermediateTerm(bounds_cost);\n  cost_function->addFinalTerm(final_cost);\n\n  // STEP 1-D: set up the box constraints for the control input\n  // input box constraint boundaries with sparsities in constraint toolbox\n  // format\n  Eigen::VectorXd u_lb(control_dim);\n  Eigen::VectorXd u_ub(control_dim);\n  u_ub.setConstant(12.0);\n  u_lb = -u_ub;\n  //::std::cout << \"uub \" << u_ub << ::std::endl;\n  //::std::cout << \"ulb \" << u_lb << ::std::endl;\n\n  // constraint terms\n  std::shared_ptr<::ct::optcon::ControlInputConstraint<state_dim, control_dim>>\n      controlConstraint(\n          new ::ct::optcon::ControlInputConstraint<state_dim, control_dim>(\n              u_lb, u_ub));\n  controlConstraint->setName(\"ControlInputConstraint\");\n  // create constraint container\n  std::shared_ptr<\n      ::ct::optcon::ConstraintContainerAnalytical<state_dim, control_dim>>\n      box_constraints(\n          new ::ct::optcon::ConstraintContainerAnalytical<state_dim,\n                                                          control_dim>());\n  // add and initialize constraint terms\n  box_constraints->addIntermediateConstraint(controlConstraint, true);\n  box_constraints->initialize();\n\n  // Starting point.\n  ::ct::core::StateVector<state_dim> x0;\n  x0 << FLAGS_theta0, 0.0, FLAGS_theta1, 0.0;\n\n  const ::ct::core::Time kTimeHorizon = FLAGS_time_horizon;\n  ::ct::optcon::OptConProblem<state_dim, control_dim> opt_con_problem(\n      kTimeHorizon, x0, oscillator_dynamics, cost_function, ad_linearizer);\n  ::ct::optcon::NLOptConSettings ilqr_settings;\n  ilqr_settings.nThreads = 4;\n  ilqr_settings.dt = kDt;  // the control discretization in [sec]\n  ilqr_settings.integrator = ::ct::core::IntegrationType::RK4;\n  ilqr_settings.debugPrint = FLAGS_debug_print;\n  ilqr_settings.discretization =\n      ::ct::optcon::NLOptConSettings::APPROXIMATION::FORWARD_EULER;\n  // ilqr_settings.discretization =\n  //   NLOptConSettings::APPROXIMATION::MATRIX_EXPONENTIAL;\n  ilqr_settings.max_iterations = 40;\n  ilqr_settings.min_cost_improvement = FLAGS_convergance;\n  ilqr_settings.nlocp_algorithm =\n      //::ct::optcon::NLOptConSettings::NLOCP_ALGORITHM::ILQR;\n      ::ct::optcon::NLOptConSettings::NLOCP_ALGORITHM::GNMS;\n  // the LQ-problems are solved using a custom Gauss-Newton Riccati solver\n  ilqr_settings.lqocp_solver =\n      ::ct::optcon::NLOptConSettings::LQOCP_SOLVER::GNRICCATI_SOLVER;\n  //ilqr_settings.lqocp_solver =\n      //::ct::optcon::NLOptConSettings::LQOCP_SOLVER::HPIPM_SOLVER;\n  ilqr_settings.printSummary = FLAGS_print_starting_summary;\n  if (ilqr_settings.lqocp_solver ==\n      ::ct::optcon::NLOptConSettings::LQOCP_SOLVER::HPIPM_SOLVER) {\n    //opt_con_problem.setBoxConstraints(box_constraints);\n  }\n\n  const size_t num_steps = ilqr_settings.computeK(kTimeHorizon);\n  printf(\"Using %d steps\\n\", static_cast<int>(num_steps));\n\n  // Vector of feeback matricies.\n  ::ct::core::FeedbackArray<state_dim, control_dim> u0_fb(\n      num_steps, ::ct::core::FeedbackMatrix<state_dim, control_dim>::Zero());\n  ::ct::core::ControlVectorArray<control_dim> u0_ff(\n      num_steps, ::ct::core::ControlVector<control_dim>::Zero());\n  ::ct::core::StateVectorArray<state_dim> x_ref_init(num_steps + 1, x0);\n  ::ct::core::StateFeedbackController<state_dim, control_dim>\n      initial_controller(x_ref_init, u0_ff, u0_fb, ilqr_settings.dt);\n\n  // STEP 2-C: create an NLOptConSolver instance\n  ::ct::optcon::NLOptConSolver<state_dim, control_dim> iLQR(opt_con_problem,\n                                                            ilqr_settings);\n  // Seed it with the initial guess\n  iLQR.setInitialGuess(initial_controller);\n  // we solve the optimal control problem and retrieve the solution\n  iLQR.solve();\n  ::ct::core::StateFeedbackController<state_dim, control_dim> initial_solution =\n      iLQR.getSolution();\n  // MPC-EXAMPLE\n  // we store the initial solution obtained from solving the initial optimal\n  // control problem, and re-use it to initialize the MPC solver in the\n  // following.\n\n  // STEP 1: first, we set up an MPC instance for the iLQR solver and configure\n  // it. Since the MPC class is wrapped around normal Optimal Control Solvers,\n  // we need to different kind of settings, those for the optimal control\n  // solver, and those specific to MPC:\n\n  // 1) settings for the iLQR instance used in MPC. Of course, we use the same\n  // settings as for solving the initial problem ...\n  ::ct::optcon::NLOptConSettings ilqr_settings_mpc = ilqr_settings;\n  ilqr_settings_mpc.max_iterations = 40;\n  // and we limited the printouts, too.\n  ilqr_settings_mpc.printSummary = FLAGS_print_summary;\n  // 2) settings specific to model predictive control. For a more detailed\n  // description of those, visit ct/optcon/mpc/MpcSettings.h\n  ::ct::optcon::mpc_settings mpc_settings;\n  mpc_settings.stateForwardIntegration_ = true;\n  mpc_settings.postTruncation_ = false;\n  mpc_settings.measureDelay_ = false;\n  mpc_settings.fixedDelayUs_ = 5000 * 0;  // Ignore the delay for now.\n  mpc_settings.delayMeasurementMultiplier_ = 1.0;\n  // mpc_settings.mpc_mode = ::ct::optcon::MPC_MODE::FIXED_FINAL_TIME;\n  mpc_settings.mpc_mode = ::ct::optcon::MPC_MODE::CONSTANT_RECEDING_HORIZON;\n  mpc_settings.coldStart_ = false;\n\n  // STEP 2 : Create the iLQR-MPC object, based on the optimal control problem\n  // and the selected settings.\n  ::ct::optcon::MPC<::ct::optcon::NLOptConSolver<state_dim, control_dim>>\n      ilqr_mpc(opt_con_problem, ilqr_settings_mpc, mpc_settings);\n  // initialize it using the previously computed initial controller\n  ilqr_mpc.setInitialGuess(initial_solution);\n  // STEP 3: running MPC\n  // Here, we run the MPC loop. Note that the general underlying idea is that\n  // you receive a state-estimate together with a time-stamp from your robot or\n  // system. MPC needs to receive both that time information and the state from\n  // your control system. Here, \"simulate\" the time measurement using\n  // ::std::chrono and wrap everything into a for-loop.\n  // The basic idea of operation is that after receiving time and state\n  // information, one executes the finishIteration() method of MPC.\n  ///\n  auto start_time = ::std::chrono::high_resolution_clock::now();\n  // limit the maximum number of runs in this example\n  size_t maxNumRuns = FLAGS_seconds / kDt;\n  ::std::cout << \"Starting to run MPC\" << ::std::endl;\n\n  ::std::vector<double> time_array;\n  ::std::vector<double> theta1_array;\n  ::std::vector<double> omega1_array;\n  ::std::vector<double> theta2_array;\n  ::std::vector<double> omega2_array;\n\n  ::std::vector<double> u0_array;\n  ::std::vector<double> u1_array;\n\n  ::std::vector<double> x_array;\n  ::std::vector<double> y_array;\n\n  // TODO(austin): Plot x, y of the end of the arm.\n\n  for (size_t i = 0; i < maxNumRuns; i++) {\n    ::std::cout << \"Solving iteration \" << i << ::std::endl;\n    // Time which has passed since start of MPC\n    auto current_time = ::std::chrono::high_resolution_clock::now();\n    ::ct::core::Time t =\n        1e-6 *\n        ::std::chrono::duration_cast<::std::chrono::microseconds>(current_time -\n                                                                  start_time)\n            .count();\n    {\n      if (FLAGS_reset_every_cycle) {\n        ::ct::core::FeedbackArray<state_dim, control_dim> u0_fb(\n            num_steps,\n            ::ct::core::FeedbackMatrix<state_dim, control_dim>::Zero());\n        ::ct::core::ControlVectorArray<control_dim> u0_ff(\n            num_steps, ::ct::core::ControlVector<control_dim>::Zero());\n        ::ct::core::StateVectorArray<state_dim> x_ref_init(num_steps + 1, x0);\n        ::ct::core::StateFeedbackController<state_dim, control_dim>\n            resolved_controller(x_ref_init, u0_ff, u0_fb, ilqr_settings.dt);\n\n        iLQR.setInitialGuess(initial_controller);\n        // we solve the optimal control problem and retrieve the solution\n        iLQR.solve();\n        resolved_controller = iLQR.getSolution();\n        ilqr_mpc.setInitialGuess(resolved_controller);\n      }\n    }\n\n    // prepare mpc iteration\n    ilqr_mpc.prepareIteration(t);\n    // new optimal policy\n    ::std::shared_ptr<ct::core::StateFeedbackController<state_dim, control_dim>>\n        newPolicy(\n            new ::ct::core::StateFeedbackController<state_dim, control_dim>());\n    // timestamp of the new optimal policy\n    ::ct::core::Time ts_newPolicy;\n    current_time = ::std::chrono::high_resolution_clock::now();\n    t = 1e-6 *\n        ::std::chrono::duration_cast<::std::chrono::microseconds>(current_time -\n                                                                  start_time)\n            .count();\n    // TODO(austin): This is only iterating once...  I need to fix that...\n    //  NLOptConSolver::solve() runs for upto N iterations.  This call runs\n    //  runIteration() effectively once.  (nlocAlgorithm_ is iLQR)\n    bool success = ilqr_mpc.finishIteration(x0, t, *newPolicy, ts_newPolicy);\n    // we break the loop in case the time horizon is reached or solve() failed\n    if (ilqr_mpc.timeHorizonReached() | !success) break;\n\n    ::std::cout << \"Solved  for time \" << newPolicy->time()[0] << \" state \"\n                << x0.transpose() << \" next time \" << newPolicy->time()[1]\n                << ::std::endl;\n    ::std::cout << \"  Solution: Uff \" << newPolicy->uff()[0].transpose()\n                << \" x_ref_ \" << newPolicy->x_ref()[0].transpose()\n                << ::std::endl;\n\n    time_array.push_back(ilqr_settings.dt * i);\n    theta1_array.push_back(x0(0));\n    omega1_array.push_back(x0(1));\n    theta2_array.push_back(x0(2));\n    omega2_array.push_back(x0(3));\n\n    u0_array.push_back(newPolicy->uff()[0](0, 0));\n    u1_array.push_back(newPolicy->uff()[0](1, 0));\n\n    ::std::cout << \"xref[1] \" << newPolicy->x_ref()[1].transpose()\n                << ::std::endl;\n    ilqr_mpc.doForwardIntegration(0.0, ilqr_settings.dt, x0, newPolicy);\n    ::std::cout << \"Next X:  \" << x0.transpose() << ::std::endl;\n\n    x_array.push_back(MySecondOrderSystem<double>::l1 * sin(x0(0)) +\n                      MySecondOrderSystem<double>::r2 * sin(x0(2)));\n    y_array.push_back(MySecondOrderSystem<double>::l1 * cos(x0(0)) +\n                      MySecondOrderSystem<double>::r2 * cos(x0(2)));\n\n    // TODO(austin): Re-use the policy. Maybe?  Or maybe mpc already does that.\n  }\n  // The summary contains some statistical data about time delays, etc.\n  ilqr_mpc.printMpcSummary();\n\n  if (FLAGS_plot_states) {\n    // Now plot our simulation.\n    matplotlibcpp::plot(time_array, theta1_array, {{\"label\", \"theta1\"}});\n    matplotlibcpp::plot(time_array, omega1_array, {{\"label\", \"omega1\"}});\n    matplotlibcpp::plot(time_array, theta2_array, {{\"label\", \"theta2\"}});\n    matplotlibcpp::plot(time_array, omega2_array, {{\"label\", \"omega2\"}});\n    matplotlibcpp::legend();\n  }\n\n  if (FLAGS_plot_xy) {\n    matplotlibcpp::figure();\n    matplotlibcpp::plot(x_array, y_array, {{\"label\", \"xy trajectory\"}});\n    matplotlibcpp::legend();\n  }\n\n  if (FLAGS_plot_u) {\n    matplotlibcpp::figure();\n    matplotlibcpp::plot(time_array, u0_array, {{\"label\", \"u0\"}});\n    matplotlibcpp::plot(time_array, u1_array, {{\"label\", \"u1\"}});\n    matplotlibcpp::legend();\n  }\n\n  ::std::vector<::std::vector<double>> cost_x;\n  ::std::vector<::std::vector<double>> cost_y;\n  ::std::vector<::std::vector<double>> cost_z;\n  ::std::vector<::std::vector<double>> cost_state_z;\n\n  for (double x_coordinate = -0.5; x_coordinate < 1.2; x_coordinate += 0.05) {\n    ::std::vector<double> cost_x_row;\n    ::std::vector<double> cost_y_row;\n    ::std::vector<double> cost_z_row;\n    ::std::vector<double> cost_state_z_row;\n\n    for (double y_coordinate = -1.0; y_coordinate < 6.0; y_coordinate += 0.05) {\n      cost_x_row.push_back(x_coordinate);\n      cost_y_row.push_back(y_coordinate);\n      Eigen::Matrix<double, 4, 1> state_matrix;\n      state_matrix << x_coordinate, 0.0, y_coordinate, 0.0;\n      Eigen::Matrix<double, 2, 1> u_matrix =\n          Eigen::Matrix<double, 2, 1>::Zero();\n      cost_state_z_row.push_back(\n          intermediate_cost->distance(state_matrix, u_matrix));\n      cost_z_row.push_back(\n          ::std::min(bounds_cost->evaluate(state_matrix, u_matrix, 0.0), 50.0));\n    }\n    cost_x.push_back(cost_x_row);\n    cost_y.push_back(cost_y_row);\n    cost_z.push_back(cost_z_row);\n    cost_state_z.push_back(cost_state_z_row);\n  }\n\n  if (FLAGS_plot_cost) {\n    matplotlibcpp::plot_surface(cost_x, cost_y, cost_z);\n  }\n\n  if (FLAGS_plot_state_cost) {\n    matplotlibcpp::plot_surface(cost_x, cost_y, cost_state_z);\n  }\n\n  matplotlibcpp::figure();\n  matplotlibcpp::plot(theta1_array, theta2_array, {{\"label\", \"trajectory\"}});\n  ::std::vector<double> bounds_x;\n  ::std::vector<double> bounds_y;\n  for (const Point p : arm_space.points()) {\n    bounds_x.push_back(p.x());\n    bounds_y.push_back(p.y());\n  }\n  matplotlibcpp::plot(bounds_x, bounds_y, {{\"label\", \"allowed region\"}});\n  matplotlibcpp::legend();\n\n  matplotlibcpp::show();\n\n  return 0;\n}\n\n}  // namespace control_loops\n}  // namespace y2018\n\nint main(int argc, char **argv) {\n  gflags::ParseCommandLineFlags(&argc, &argv, false);\n  return ::y2018::control_loops::Main();\n}\n", "meta": {"hexsha": "d603156a3534d13c2f8e66d101df329295230e70", "size": 42257, "ext": "cc", "lang": "C++", "max_stars_repo_path": "y2018/control_loops/python/arm_mpc.cc", "max_stars_repo_name": "Ewpratten/frc_971_mirror", "max_stars_repo_head_hexsha": "3a8a0c4359f284d29547962c2b4c43d290d8065c", "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": "y2018/control_loops/python/arm_mpc.cc", "max_issues_repo_name": "Ewpratten/frc_971_mirror", "max_issues_repo_head_hexsha": "3a8a0c4359f284d29547962c2b4c43d290d8065c", "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": "y2018/control_loops/python/arm_mpc.cc", "max_forks_repo_name": "Ewpratten/frc_971_mirror", "max_forks_repo_head_hexsha": "3a8a0c4359f284d29547962c2b4c43d290d8065c", "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.9864209505, "max_line_length": 86, "alphanum_fraction": 0.6494071988, "num_tokens": 12213, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080671950640465, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4880175028888212}}
{"text": "#include <fast_tf/fast_tf.hpp>\n#include <benchmark/benchmark.h>\n\n#include <tf2/LinearMath/Quaternion.h>\n#include <tf2/LinearMath/Vector3.h>\n\n#include <Eigen/Geometry>\n\nusing benchmark::State;\n\nstatic void\neigen_isometry_prod(State& _state) {\n  const Eigen::Isometry3d tf1(Eigen::Translation3d(1, 2, 3) *\n                              Eigen::Quaterniond(-0.002, -0.678, 0.226, 0.699));\n\n  const Eigen::Isometry3d tf2(Eigen::Translation3d(3, 4, 1) *\n                              Eigen::Quaterniond(-0.003, -0.945, 0.315, 0.091));\n\n  for (auto _ : _state)\n    benchmark::DoNotOptimize(tf1 * tf2);\n}\n\nstruct tf_transform {\n  tf2::Vector3 v;\n  tf2::Quaternion q;\n};\n\n// without this the compiler will still remove the call to the product. this can\n// be seen when running the benchmark below with valgrind --tool=callgrind.\n__attribute__((noinline)) tf_transform\ntf2_product(const tf_transform& _l, const tf_transform& _r) {\n  return {tf2::quatRotate(_l.q, _r.v) + _l.v, _l.q * _r.q};\n}\n\nstatic void\ntf_transform_accum_prod(State& _state) {\n  tf2::Quaternion q1(-0.002, -0.678, 0.226, 0.699);\n  tf2::Vector3 v1(1, 2, 3);\n\n  tf2::Quaternion q2(-0.003, -0.945, 0.315, 0.091);\n  tf2::Vector3 v2(3, 4, 1);\n\n  tf_transform tf1{v1, q1};\n  tf_transform tf2{v2, q2};\n  for (auto _ : _state)\n    benchmark::DoNotOptimize(tf2_product(tf1, tf2));\n}\n\n// benchmarks comparing the tf product of transform with the eigen-based.\nBENCHMARK(eigen_isometry_prod);\nBENCHMARK(tf_transform_accum_prod);", "meta": {"hexsha": "d02c151285004b315a7a6c179e5196d59fbea760", "size": 1476, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "perf/perf_transform_prod.cpp", "max_stars_repo_name": "dorezyuk/fast_tf", "max_stars_repo_head_hexsha": "b70d664b4c4a27f24241000ea6a779f9a7048d47", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "perf/perf_transform_prod.cpp", "max_issues_repo_name": "dorezyuk/fast_tf", "max_issues_repo_head_hexsha": "b70d664b4c4a27f24241000ea6a779f9a7048d47", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "perf/perf_transform_prod.cpp", "max_forks_repo_name": "dorezyuk/fast_tf", "max_forks_repo_head_hexsha": "b70d664b4c4a27f24241000ea6a779f9a7048d47", "max_forks_repo_licenses": ["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.9411764706, "max_line_length": 80, "alphanum_fraction": 0.683604336, "num_tokens": 481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186787341014, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4879970131018681}}
{"text": "#ifndef KNAPSACK_HPP\n#define KNAPSACK_HPP\n\n#include <vector>\n#include <array>\n#include <cmath>\n\n#include <hpx/config.hpp>\n#include <boost/serialization/access.hpp>\n\n#include <hpx/util/tuple.hpp>\n\n#include \"util/NodeGenerator.hpp\"\n\n/* A representation of a knapsack current solution */\nstruct KPSolution {\n  std::vector<int> items;\n  int profit;\n  int weight;\n\n  template <class Archive>\n  void serialize(Archive & ar, const unsigned int version) {\n    ar & items;\n    ar & profit;\n    ar & weight;\n  }\n};\n\ntemplate <unsigned N>\nstruct KPSpace {\n  std::array<int, N> profits;\n  std::array<int, N> weights;\n  int numItems;\n  int capacity;\n\n  template <class Archive>\n  void serialize(Archive & ar, const unsigned int version) {\n    ar & profits;\n    ar & weights;\n    ar & numItems;\n    ar & capacity;\n  }\n};\n\nstruct KPNode {\n  KPSolution sol;\n  std::vector<int> rem;\n\n  int getObj() const {\n    return sol.profit;\n  }\n\n  template <class Archive>\n  void serialize(Archive & ar, const unsigned int version) {\n    ar & sol;\n    ar & rem;\n  }\n};\n\ntemplate <unsigned numItems>\nstruct GenNode : YewPar::NodeGenerator<KPNode, KPSpace<numItems> > {\n  std::vector<int> items;\n  int pos;\n\n  std::reference_wrapper<const KPSpace<numItems> > space;\n  std::reference_wrapper<const KPNode> n;\n\n  GenNode (const KPSpace<numItems> & space, const KPNode & n) :\n      pos(0), space(std::cref(space)), n(std::cref(n)) {\n    this->numChildren = n.rem.size();\n  }\n\n  KPNode next() override {\n    auto i = n.get().rem[pos];\n    auto newSol = n.get().sol;\n    newSol.items.push_back(i);\n    newSol.profit += space.get().profits[i];\n    newSol.weight += space.get().weights[i];\n\n    ++pos;\n\n    std::vector<int> newRem;\n    std::copy_if(n.get().rem.begin() + pos, n.get().rem.end(), std::back_inserter(newRem),\n                 [&](const int i) {\n                   return newSol.weight + space.get().weights[i] <= space.get().capacity;\n                 });\n\n    return { newSol, std::move(newRem) };\n  }\n};\n\ntemplate <unsigned numItems>\nint upperBound(const KPSpace<numItems> & space, const KPNode & n) {\n  auto sol = n.sol;\n\n  double profit = sol.profit;\n  auto weight  = sol.weight;\n\n  for (auto i = sol.items.back() + 1; i < space.numItems; i++) {\n    // If there is enough space for a full item we take it all\n    if (space.weights[i] + weight <= space.capacity) {\n      profit += space.profits[i];\n      weight += space.weights[i];\n    } else {\n      // Only space for some fraction of the last item\n      profit = profit + (space.capacity - weight) * ((double) space.profits[i] / (double) space.weights[i]);\n      break;\n    }\n  }\n\n  return std::ceil(profit);\n}\n\n#endif\n", "meta": {"hexsha": "907620f3e43de23a44766ab40d8a7d52ac9697de", "size": 2652, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "apps/bnb/knapsack/knapsack.hpp", "max_stars_repo_name": "zxcvsop/YewPar", "max_stars_repo_head_hexsha": "f8a3a5e3405c4d3835dc825f2fa9ee87a033a0ef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2017-12-08T14:51:54.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-06T11:11:12.000Z", "max_issues_repo_path": "apps/bnb/knapsack/knapsack.hpp", "max_issues_repo_name": "zxcvsop/YewPar", "max_issues_repo_head_hexsha": "f8a3a5e3405c4d3835dc825f2fa9ee87a033a0ef", "max_issues_repo_licenses": ["MIT"], "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/bnb/knapsack/knapsack.hpp", "max_forks_repo_name": "zxcvsop/YewPar", "max_forks_repo_head_hexsha": "f8a3a5e3405c4d3835dc825f2fa9ee87a033a0ef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-10-13T11:27:45.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-14T19:36:42.000Z", "avg_line_length": 23.0608695652, "max_line_length": 108, "alphanum_fraction": 0.6297134238, "num_tokens": 715, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.48799700723174955}}
{"text": "/* +------------------------------------------------------------------------+\n   |                     Mobile Robot Programming Toolkit (MRPT)            |\n   |                          http://www.mrpt.org/                          |\n   |                                                                        |\n   | Copyright (c) 2005-2017, Individual contributors, see AUTHORS file     |\n   | See: http://www.mrpt.org/Authors - All rights reserved.                |\n   | Released under BSD License. See details in http://www.mrpt.org/License |\n   +------------------------------------------------------------------------+ */\n\n#include \"vision-precomp.h\"  // Precompiled headers\n#include <iostream>\n#include <vector>\n#include <cmath>\n\n#include <mrpt/utils/types_math.h>  // Eigen must be included first via MRPT to enable the plugin system\n#include <Eigen/Dense>\n#include <Eigen/SVD>\n#include <Eigen/StdVector>\n#include <unsupported/Eigen/Polynomials>\n\n#include \"rpnp.h\"\n\nmrpt::vision::pnp::rpnp::rpnp(\n\tEigen::MatrixXd obj_pts_, Eigen::MatrixXd img_pts_, Eigen::MatrixXd cam_,\n\tint n0)\n{\n\tobj_pts = obj_pts_;\n\timg_pts = img_pts_;\n\tcam_intrinsic = cam_;\n\tn = n0;\n\n\t// Store obj_pts as 3XN and img_projections as 2XN matrices\n\tP = obj_pts.transpose();\n\tQ = img_pts.transpose();\n\n\tfor (int i = 0; i < n; i++) Q.col(i) = Q.col(i) / Q.col(i).norm();\n\n\tR.setZero();\n\tt.setZero();\n}\n\nbool mrpt::vision::pnp::rpnp::compute_pose(\n\tEigen::Ref<Eigen::Matrix3d> R_, Eigen::Ref<Eigen::Vector3d> t_)\n{\n\t// selecting an edge $P_{ i1 }P_{ i2 }$ by n random sampling\n\tint i1 = 0, i2 = 1;\n\tdouble lmin =\n\t\tQ(0, i1) * Q(0, i2) + Q(1, i1) * Q(1, i2) + Q(2, i1) * Q(2, i2);\n\n\tEigen::MatrixXi rij(n, 2);\n\n\tR_ = Eigen::MatrixXd::Identity(3, 3);\n\tt_ = Eigen::Vector3d::Zero();\n\n\tfor (int i = 0; i < n; i++)\n\t\tfor (int j = 0; j < 2; j++) rij(i, j) = rand() % n;\n\n\tfor (int ii = 0; ii < n; ii++)\n\t{\n\t\tint i = rij(ii, 0), j = rij(ii, 1);\n\n\t\tif (i == j) continue;\n\n\t\tdouble l = Q(0, i) * Q(0, j) + Q(1, i) * Q(1, j) + Q(2, i) * Q(2, j);\n\n\t\tif (l < lmin)\n\t\t{\n\t\t\ti1 = i;\n\t\t\ti2 = j;\n\t\t\tlmin = l;\n\t\t}\n\t}\n\n\t// calculating the rotation matrix of $O_aX_aY_aZ_a$.\n\tEigen::Vector3d p1, p2, p0, x, y, z, dum_vec;\n\n\tp1 = P.col(i1);\n\tp2 = P.col(i2);\n\tp0 = (p1 + p2) / 2;\n\n\tx = p2 - p0;\n\tx /= x.norm();\n\n\tif (std::abs(x(1)) < std::abs(x(2)))\n\t{\n\t\tdum_vec << 0, 1, 0;\n\t\tz = x.cross(dum_vec);\n\t\tz /= z.norm();\n\t\ty = z.cross(x);\n\t\ty /= y.norm();\n\t}\n\telse\n\t{\n\t\tdum_vec << 0, 0, 1;\n\t\ty = dum_vec.cross(x);\n\t\ty /= y.norm();\n\t\tz = x.cross(y);\n\t\tx /= x.norm();\n\t}\n\n\tEigen::Matrix3d R0;\n\n\tR0.col(0) = x;\n\tR0.col(1) = y;\n\tR0.col(2) = z;\n\n\tfor (int i = 0; i < n; i++) P.col(i) = R0.transpose() * (P.col(i) - p0);\n\n\t// Dividing the n - point set into(n - 2) 3 - point subsets\n\t// and setting up the P3P equations\n\n\tEigen::Vector3d v1 = Q.col(i1), v2 = Q.col(i2);\n\tdouble cg1 = v1.dot(v2);\n\tdouble sg1 = sqrt(1 - cg1 * cg1);\n\tdouble D1 = (P.col(i1) - P.col(i2)).norm();\n\tEigen::MatrixXd D4(n - 2, 5);\n\n\tint j = 0;\n\tEigen::Vector3d vi;\n\tEigen::VectorXd rowvec(5);\n\tfor (int i = 0; i < n; i++)\n\t{\n\t\tif (i == i1 || i == i2) continue;\n\n\t\tvi = Q.col(i);\n\t\tdouble cg2 = v1.dot(vi);\n\t\tdouble cg3 = v2.dot(vi);\n\t\tdouble sg2 = sqrt(1 - cg2 * cg2);\n\t\tdouble D2 = (P.col(i1) - P.col(i)).norm();\n\t\tdouble D3 = (P.col(i) - P.col(i2)).norm();\n\n\t\t// get the coefficients of the P3P equation from each subset.\n\n\t\trowvec = getp3p(cg1, cg2, cg3, sg1, sg2, D1, D2, D3);\n\t\tD4.row(j) = rowvec;\n\t\tj += 1;\n\n\t\tif (j > n - 3) break;\n\t}\n\n\tEigen::VectorXd D7(8), dumvec(8), dumvec1(5);\n\tD7.setZero();\n\n\tfor (int i = 0; i < n - 2; i++)\n\t{\n\t\tdumvec1 = D4.row(i);\n\t\tdumvec = getpoly7(dumvec1);\n\t\tD7 += dumvec;\n\t}\n\n\tEigen::PolynomialSolver<double, 7> psolve(D7.reverse());\n\tEigen::VectorXcd comp_roots = psolve.roots().transpose();\n\tEigen::VectorXd real_comp, imag_comp;\n\treal_comp = comp_roots.real();\n\timag_comp = comp_roots.imag();\n\n\tEigen::VectorXd::Index max_index;\n\n\tdouble max_real = real_comp.cwiseAbs().maxCoeff(&max_index);\n\n\tstd::vector<double> act_roots_;\n\n\tint cnt = 0;\n\n\tfor (int i = 0; i < imag_comp.size(); i++)\n\t{\n\t\tif (std::abs(imag_comp(i)) / max_real < 0.001)\n\t\t{\n\t\t\tact_roots_.push_back(real_comp(i));\n\t\t\tcnt++;\n\t\t}\n\t}\n\n\tdouble* ptr = &act_roots_[0];\n\tEigen::Map<Eigen::VectorXd> act_roots(ptr, cnt);\n\n\tif (cnt == 0)\n\t{\n\t\treturn false;\n\t}\n\n\tEigen::VectorXd act_roots1(cnt);\n\tact_roots1 << act_roots.segment(0, cnt);\n\n\tstd::vector<Eigen::Matrix3d> R_cum(cnt);\n\tstd::vector<Eigen::Vector3d> t_cum(cnt);\n\tstd::vector<double> err_cum(cnt);\n\n\tfor (int i = 0; i < cnt; i++)\n\t{\n\t\tdouble root = act_roots(i);\n\n\t\t// Compute the rotation matrix\n\n\t\tdouble d2 = cg1 + root;\n\n\t\tEigen::Vector3d unitx, unity, unitz;\n\t\tunitx << 1, 0, 0;\n\t\tunity << 0, 1, 0;\n\t\tunitz << 0, 0, 1;\n\t\tx = v2 * d2 - v1;\n\t\tx /= x.norm();\n\t\tif (std::abs(unity.dot(x)) < std::abs(unitz.dot(x)))\n\t\t{\n\t\t\tz = x.cross(unity);\n\t\t\tz /= z.norm();\n\t\t\ty = z.cross(x);\n\t\t\ty / y.norm();\n\t\t}\n\t\telse\n\t\t{\n\t\t\ty = unitz.cross(x);\n\t\t\ty /= y.norm();\n\t\t\tz = x.cross(y);\n\t\t\tz /= z.norm();\n\t\t}\n\t\tR.col(0) = x;\n\t\tR.col(1) = y;\n\t\tR.col(2) = z;\n\n\t\t// calculating c, s, tx, ty, tz\n\n\t\tEigen::MatrixXd D(2 * n, 6);\n\t\tD.setZero();\n\n\t\tR0 = R.transpose();\n\t\tEigen::VectorXd r(\n\t\t\tEigen::Map<Eigen::VectorXd>(R0.data(), R0.cols() * R0.rows()));\n\n\t\tfor (int j = 0; j < n; j++)\n\t\t{\n\t\t\tdouble ui = img_pts(j, 0), vi = img_pts(j, 1), xi = P(0, j),\n\t\t\t\t   yi = P(1, j), zi = P(2, j);\n\t\t\tD.row(2 * j) << -r(1) * yi + ui * (r(7) * yi + r(8) * zi) -\n\t\t\t\t\t\t\t\tr(2) * zi,\n\t\t\t\t-r(2) * yi + ui * (r(8) * yi - r(7) * zi) + r(1) * zi, -1, 0,\n\t\t\t\tui, ui * r(6) * xi - r(0) * xi;\n\n\t\t\tD.row(2 * j + 1)\n\t\t\t\t<< -r(4) * yi + vi * (r(7) * yi + r(8) * zi) - r(5) * zi,\n\t\t\t\t-r(5) * yi + vi * (r(8) * yi - r(7) * zi) + r(4) * zi, 0, -1,\n\t\t\t\tvi, vi * r(6) * xi - r(3) * xi;\n\t\t}\n\n\t\tEigen::MatrixXd DTD = D.transpose() * D;\n\n\t\tEigen::EigenSolver<Eigen::MatrixXd> es(DTD);\n\n\t\tEigen::VectorXd Diag = es.pseudoEigenvalueMatrix().diagonal();\n\n\t\tEigen::MatrixXd V_mat = es.pseudoEigenvectors();\n\n\t\tEigen::MatrixXd::Index min_index;\n\n\t\tDiag.minCoeff(&min_index);\n\n\t\tEigen::VectorXd V = V_mat.col(min_index);\n\n\t\tV /= V(5);\n\n\t\tdouble c = V(0), s = V(1);\n\t\tt << V(2), V(3), V(4);\n\n\t\t// calculating the camera pose by 3d alignment\n\t\tEigen::VectorXd xi, yi, zi;\n\t\txi = P.row(0);\n\t\tyi = P.row(1);\n\t\tzi = P.row(2);\n\n\t\tEigen::MatrixXd XXcs(3, n), XXc(3, n);\n\t\tXXc.setZero();\n\n\t\tXXcs.row(0) = r(0) * xi + (r(1) * c + r(2) * s) * yi +\n\t\t\t\t\t  (-r(1) * s + r(2) * c) * zi +\n\t\t\t\t\t  t(0) * Eigen::VectorXd::Ones(n);\n\t\tXXcs.row(1) = r(3) * xi + (r(4) * c + r(5) * s) * yi +\n\t\t\t\t\t  (-r(4) * s + r(5) * c) * zi +\n\t\t\t\t\t  t(1) * Eigen::VectorXd::Ones(n);\n\t\tXXcs.row(2) = r(6) * xi + (r(7) * c + r(8) * s) * yi +\n\t\t\t\t\t  (-r(7) * s + r(8) * c) * zi +\n\t\t\t\t\t  t(2) * Eigen::VectorXd::Ones(n);\n\n\t\tfor (int ii = 0; ii < n; ii++)\n\t\t\tXXc.col(ii) = Q.col(ii) * XXcs.col(ii).norm();\n\n\t\tEigen::Matrix3d R2;\n\t\tEigen::Vector3d t2;\n\n\t\tEigen::MatrixXd XXw = obj_pts.transpose();\n\n\t\tcalcampose(XXc, XXw, R2, t2);\n\n\t\tR_cum[i] = R2;\n\t\tt_cum[i] = t2;\n\n\t\tfor (int k = 0; k < n; k++) XXc.col(k) = R2 * XXw.col(k) + t2;\n\n\t\tEigen::MatrixXd xxc(2, n);\n\n\t\txxc.row(0) = XXc.row(0).array() / XXc.row(2).array();\n\t\txxc.row(1) = XXc.row(1).array() / XXc.row(2).array();\n\n\t\tdouble res = ((xxc.row(0) - img_pts.col(0).transpose()).norm() +\n\t\t\t\t\t  (xxc.row(1) - img_pts.col(1).transpose()).norm()) /\n\t\t\t\t\t 2;\n\n\t\terr_cum[i] = res;\n\t}\n\n\tint pos_cum =\n\t\tstd::min_element(err_cum.begin(), err_cum.end()) - err_cum.begin();\n\n\tR_ = R_cum[pos_cum];\n\tt_ = t_cum[pos_cum];\n\n\treturn true;\n}\n\nvoid mrpt::vision::pnp::rpnp::calcampose(\n\tEigen::MatrixXd& XXc, Eigen::MatrixXd& XXw, Eigen::Matrix3d& R2,\n\tEigen::Vector3d& t2)\n{\n\tEigen::MatrixXd X = XXc;\n\tEigen::MatrixXd Y = XXw;\n\tEigen::MatrixXd K =\n\t\tEigen::MatrixXd::Identity(n, n) - Eigen::MatrixXd::Ones(n, n) * 1 / n;\n\tEigen::VectorXd ux, uy;\n\tuy = X.rowwise().mean();\n\tux = Y.rowwise().mean();\n\n\t// Need to verify sigmax2\n\tdouble sigmax2 =\n\t\t(((X * K).array() * (X * K).array()).colwise().sum()).mean();\n\n\tEigen::MatrixXd SXY = Y * K * (X.transpose()) / n;\n\n\tEigen::JacobiSVD<Eigen::MatrixXd> svd(\n\t\tSXY, Eigen::ComputeThinU | Eigen::ComputeThinV);\n\n\tEigen::Matrix3d S = Eigen::MatrixXd::Identity(3, 3);\n\tif (SXY.determinant() < 0) S(2, 2) = -1;\n\n\tR2 = svd.matrixV() * S * svd.matrixU().transpose();\n\n\tdouble c2 = (svd.singularValues().asDiagonal() * S).trace() / sigmax2;\n\tt2 = uy - c2 * R2 * ux;\n\n\tEigen::Vector3d x, y, z;\n\tx = R2.col(0);\n\ty = R2.col(1);\n\tz = R2.col(2);\n\n\tif ((x.cross(y) - z).norm() > 0.02) R2.col(2) = -R2.col(2);\n}\n\nEigen::VectorXd mrpt::vision::pnp::rpnp::getpoly7(const Eigen::VectorXd& vin)\n{\n\tEigen::VectorXd vout(8);\n\tvout << 4 * pow(vin(0), 2), 7 * vin(1) * vin(0),\n\t\t6 * vin(2) * vin(0) + 3 * pow(vin(1), 2),\n\t\t5 * vin(3) * vin(0) + 5 * vin(2) * vin(1),\n\t\t4 * vin(4) * vin(0) + 4 * vin(3) * vin(1) + 2 * pow(vin(2), 2),\n\t\t3 * vin(4) * vin(1) + 3 * vin(3) * vin(2),\n\t\t2 * vin(4) * vin(2) + pow(vin(3), 2), vin(4) * vin(3);\n\treturn vout;\n}\n\nEigen::VectorXd mrpt::vision::pnp::rpnp::getp3p(\n\tdouble l1, double l2, double A5, double C1, double C2, double D1, double D2,\n\tdouble D3)\n{\n\tdouble A1 = (D2 / D1) * (D2 / D1);\n\tdouble A2 = A1 * pow(C1, 2) - pow(C2, 2);\n\tdouble A3 = l2 * A5 - l1;\n\tdouble A4 = l1 * A5 - l2;\n\tdouble A6 = (pow(D3, 2) - pow(D1, 2) - pow(D2, 2)) / (2 * pow(D1, 2));\n\tdouble A7 = 1 - pow(l1, 2) - pow(l2, 2) + l1 * l2 * A5 + A6 * pow(C1, 2);\n\n\tEigen::VectorXd vec(5);\n\n\tvec << pow(A6, 2) - A1 * pow(A5, 2), 2 * (A3 * A6 - A1 * A4 * A5),\n\t\tpow(A3, 2) + 2 * A6 * A7 - A1 * pow(A4, 2) - A2 * pow(A5, 2),\n\t\t2 * (A3 * A7 - A2 * A4 * A5), pow(A7, 2) - A2 * pow(A4, 2);\n\n\treturn vec;\n}\n", "meta": {"hexsha": "a7d4d68e91996b2b5273eaabfb803e28c8c9685f", "size": 9550, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/vision/src/pnp/rpnp.cpp", "max_stars_repo_name": "tg1716/SLAM", "max_stars_repo_head_hexsha": "b8583fb98a4241d87ae08ac78b0420c154f5e1a5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2017-08-04T15:44:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-02T02:00:18.000Z", "max_issues_repo_path": "libs/vision/src/pnp/rpnp.cpp", "max_issues_repo_name": "tg1716/SLAM", "max_issues_repo_head_hexsha": "b8583fb98a4241d87ae08ac78b0420c154f5e1a5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/vision/src/pnp/rpnp.cpp", "max_forks_repo_name": "tg1716/SLAM", "max_forks_repo_head_hexsha": "b8583fb98a4241d87ae08ac78b0420c154f5e1a5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-10-03T23:10:09.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-29T09:41:33.000Z", "avg_line_length": 24.677002584, "max_line_length": 104, "alphanum_fraction": 0.5317277487, "num_tokens": 3786, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.48799700723174955}}
{"text": "#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <map>\n#include <list>\n#include <string>\n#include <set>\n#include <vector>\n#include <utility>\n#include <boost/algorithm/string.hpp>\n\nusing namespace std;\nusing namespace boost;\n\nstruct Ing {\n    __int64 quantity;\n    string name;\n};\ntypedef list<Ing> IngList;\nstruct RecipeElement {\n    __int64 makes;\n    IngList ings;\n    RecipeElement() : makes(0) {}\n};\ntypedef map<string, RecipeElement> Recipe;\ntypedef map<string, __int64> Stash;\n\nIng Parse(string s)\n{\n    Ing r;\n    stringstream ss(s);\n    ss >> r.quantity;\n    ss >> r.name;\n    trim(r.name);\n\n    return r;\n}\n\nRecipe Load()\n{\n    Recipe r;\n    ifstream f(\"Data.txt\");\n\n    while (!f.eof()) {\n        string s;\n        getline(f, s);\n\n        vector<string> parts;\n        split(parts, s, is_any_of(\"=>\"), token_compress_on);\n        vector<string> ings;\n        split(ings, parts[0], is_any_of(\",\"), token_compress_on);\n\n        Ing result = Parse(parts[1]);\n        auto& re = r[result.name];\n        re.makes = result.quantity;\n        \n        for (const string& ing : ings) {\n            Ing src = Parse(ing);\n            re.ings.push_back(src);\n        }\n    }\n\n    return r;\n}\n\n__int64 GetRequiredOre(const Recipe& r, const string& type, __int64 num, Stash& stash)\n{\n    __int64 ore = 0;\n    __int64 in_stash = stash[type];\n\n    //cout << \"Need \" << num << \" \" << type << \"> \";\n\n    // Check if we have enough in stash\n    if (in_stash > num) {\n        stash[type] -= num;\n        //cout << \"In stash\" << endl;\n        return 0;\n    }\n\n    // Exhaust stash first\n    //cout << stash[type] << \" from stash, \";\n    num -= stash[type];\n    stash.erase(type);\n\n    // Get recipe\n    auto it = r.find(type);\n    if (it == r.end()) throw std::exception(\"No recipe!\");\n    auto& re = it->second;\n\n    // Recipe makes X lots per batch, so need to make \n    __int64 to_make = (__int64)ceil(1.0 * num / re.makes);\n    //cout << \"Making \" << to_make * re.makes << \"< \";\n    //for (auto ing : re.ings) cout << ing.name << \": \" << ing.quantity * to_make << \" \";\n    //cout << endl;\n\n    for (auto ing : re.ings) {\n        if (ing.name == \"ORE\"s) {\n            ore += ing.quantity * to_make;\n        }\n        else {\n            ore += GetRequiredOre(r, ing.name, ing.quantity * to_make, stash);\n        }\n    }\n\n    stash[type] += (to_make * re.makes - num);\n    return ore;\n}\n\nint main()\n{\n    Recipe r = Load();\n    Stash stash;\n    __int64 needs = GetRequiredOre(r, \"FUEL\", 1, stash);\n    cout << \"FUEL requires \" << needs << \" ORE\" << endl;\n    cout << \"Left over:\" << endl;\n    for (auto x : stash) {\n        if (x.second > 0) {\n            cout << \"  \" << x.first << \" = \" << x.second << endl;\n        }\n    }\n\n    // Part 2 - for 1e12 ore, how much fuel.  Search!\n    __int64 target = 1000000000000i64;\n    __int64 guess = target / needs + 1;\n    __int64 step = 16777216;\n    while (true) {\n        stash.clear();\n        needs = GetRequiredOre(r, \"FUEL\", guess, stash);\n        cout << \"Guess \" << guess << \" gives \" << needs << endl;\n        if (needs > target) {\n            guess -= step;\n        }\n        else if (step > 1) {\n            step /= 2;\n            guess += step;\n        }\n        else {\n            break;\n        }\n    }\n    cout << guess << \" FUEL from \" << needs << \" ORE\" << endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "8bc7af41e36a8081cd9537b37a9651fc47f70d6d", "size": 3347, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "advent2019_14/advent2019_14.cpp", "max_stars_repo_name": "throx/advent2019", "max_stars_repo_head_hexsha": "b3d4929fe501c72fb9b7db854b08fda119d6cda9", "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": "advent2019_14/advent2019_14.cpp", "max_issues_repo_name": "throx/advent2019", "max_issues_repo_head_hexsha": "b3d4929fe501c72fb9b7db854b08fda119d6cda9", "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": "advent2019_14/advent2019_14.cpp", "max_forks_repo_name": "throx/advent2019", "max_forks_repo_head_hexsha": "b3d4929fe501c72fb9b7db854b08fda119d6cda9", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.0827586207, "max_line_length": 89, "alphanum_fraction": 0.5252464894, "num_tokens": 929, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.4879970072317495}}
{"text": "#include \"ale.h\"\n\n#include <nlohmann/json.hpp>\n\n#include <gsl/gsl_interp.h>\n#include <gsl/gsl_spline.h>\n#include <gsl/gsl_poly.h>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include <iostream>\n#include <Python.h>\n\n#include <string>\n#include <iostream>\n#include <stdexcept>\n\nusing json = nlohmann::json;\nusing namespace std;\n\nnamespace ale {\n\n  // Position Data Functions\n  vector<double> getPosition(vector<vector<double>> coords, vector<double> times, double time,\n                             interpolation interp) {\n    // Check that all of the data sizes are okay\n    // TODO is there a cleaner way to do this? We're going to have to do this a lot.\n    if (coords.size() != 3) {\n      throw invalid_argument(\"Invalid input positions, expected three vectors.\");\n    }\n\n    // GSL setup\n    vector<double> coordinate = {0.0, 0.0, 0.0};\n\n    coordinate = { interpolate(coords[0], times, time, interp, 0),\n                   interpolate(coords[1], times, time, interp, 0),\n                   interpolate(coords[2], times, time, interp, 0) };\n\n    return coordinate;\n  }\n\n  vector<double> getVelocity(vector<vector<double>> coords, vector<double> times,\n                             double time, interpolation interp) {\n    // Check that all of the data sizes are okay\n    // TODO is there a cleaner way to do this? We're going to have to do this a lot.\n    if (coords.size() != 3) {\n     throw invalid_argument(\"Invalid input positions, expected three vectors.\");\n    }\n\n    // GSL setup\n    vector<double> coordinate = {0.0, 0.0, 0.0};\n\n    coordinate = { interpolate(coords[0], times, time, interp, 1),\n                   interpolate(coords[1], times, time, interp, 1),\n                   interpolate(coords[2], times, time, interp, 1) };\n\n    return coordinate;\n  }\n\n  // Postion Function Functions\n  // vector<double> coeffs = [[cx_0, cx_1, cx_2 ..., cx_n],\n  //                          [cy_0, cy_1, cy_2, ... cy_n],\n  //                          [cz_0, cz_1, cz_2, ... cz_n]]\n  // The equations evaluated by this function are:\n  //                x = cx_n * t^n + cx_n-1 * t^(n-1) + ... + cx_0\n  //                y = cy_n * t^n + cy_n-1 * t^(n-1) + ... + cy_0\n  //                z = cz_n * t^n + cz_n-1 * t^(n-1) + ... + cz_0\n  vector<double> getPosition(vector<vector<double>> coeffs, double time) {\n\n    if (coeffs.size() != 3) {\n      throw invalid_argument(\"Invalid input coeffs, expected three vectors.\");\n    }\n\n    vector<double> coordinate = {0.0, 0.0, 0.0};\n    coordinate[0] = evaluatePolynomial(coeffs[0], time, 0); // X\n    coordinate[1] = evaluatePolynomial(coeffs[1], time, 0); // Y\n    coordinate[2] = evaluatePolynomial(coeffs[2], time, 0); // Z\n\n    return coordinate;\n  }\n\n\n  // Velocity Function\n  // Takes the coefficients from the position equation\n  vector<double> getVelocity(vector<vector<double>> coeffs, double time) {\n\n    if (coeffs.size() != 3) {\n      throw invalid_argument(\"Invalid input coeffs, expected three vectors.\");\n    }\n\n    vector<double> coordinate = {0.0, 0.0, 0.0};\n    coordinate[0] = evaluatePolynomial(coeffs[0], time, 1); // X\n    coordinate[1] = evaluatePolynomial(coeffs[1], time, 1); // Y\n    coordinate[2] = evaluatePolynomial(coeffs[2], time, 1); // Z\n\n    return coordinate;\n  }\n\n\n  // Rotation Data Functions\n  vector<double> getRotation(vector<vector<double>> rotations,\n                             vector<double> times, double time,  interpolation interp) {\n    // Check that all of the data sizes are okay\n    // TODO is there a cleaner way to do this? We're going to have to do this a lot.\n    if (rotations.size() != 4) {\n     throw invalid_argument(\"Invalid input rotations, expected four vectors.\");\n    }\n\n    // Alot of copying and reassignment becuase conflicting data types\n    // probably should rethink our vector situation to guarentee contiguous\n    // memory. Should be easy to switch to a contiguous column-major format\n    // if we stick with Eigen.\n    for (size_t i = 0; i<rotations[0].size(); i++) {\n      Eigen::Quaterniond quat(rotations[0][i], rotations[1][i], rotations[2][i], rotations[3][i]);\n      quat.normalize();\n\n      rotations[0][i] = quat.w();\n      rotations[1][i] = quat.x();\n      rotations[2][i] = quat.y();\n      rotations[3][i] = quat.z();\n    }\n\n    // GSL setup\n    vector<double> coordinate = {0.0, 0.0, 0.0, 0.0};\n\n    coordinate = { interpolate(rotations[0], times, time, interp, 0),\n                   interpolate(rotations[1], times, time, interp, 0),\n                   interpolate(rotations[2], times, time, interp, 0),\n                   interpolate(rotations[3], times, time, interp, 0)};\n\n    // Eigen::Map to ensure the array isn't copied, only the pointer is\n    Eigen::Map<Eigen::MatrixXd> quat(coordinate.data(), 4, 1);\n    quat.normalize();\n    return coordinate;\n  }\n\n  vector<double> getAngularVelocity(vector<vector<double>> rotations,\n                                    vector<double> times, double time,  interpolation interp) {\n    // Check that all of the data sizes are okay\n    // TODO is there a cleaner way to do this? We're going to have to do this a lot.\n    if (rotations.size() != 4) {\n     throw invalid_argument(\"Invalid input rotations, expected four vectors.\");\n    }\n\n    double data[] = {0,0,0,0};\n    for (size_t i = 0; i<rotations[0].size(); i++) {\n      Eigen::Quaterniond quat(rotations[0][i], rotations[1][i], rotations[2][i], rotations[3][i]);\n      quat.normalize();\n      rotations[0][i] = quat.w();\n      rotations[1][i] = quat.x();\n      rotations[2][i] = quat.y();\n      rotations[3][i] = quat.z();\n    }\n\n    // GSL setup\n\n\n    Eigen::Quaterniond quat(interpolate(rotations[0], times, time, interp, 0),\n                            interpolate(rotations[1], times, time, interp, 0),\n                            interpolate(rotations[2], times, time, interp, 0),\n                            interpolate(rotations[3], times, time, interp, 0));\n    quat.normalize();\n\n    Eigen::Quaterniond dQuat(interpolate(rotations[0], times, time, interp, 1),\n                             interpolate(rotations[1], times, time, interp, 1),\n                             interpolate(rotations[2], times, time, interp, 1),\n                             interpolate(rotations[3], times, time, interp, 1));\n\n     Eigen::Quaterniond avQuat = quat.conjugate() * dQuat;\n\n     vector<double> coordinate = {-2 * avQuat.x(), -2 * avQuat.y(), -2 * avQuat.z()};\n     return coordinate;\n  }\n\n  // Rotation Function Functions\n  std::vector<double> getRotation(vector<vector<double>> coeffs, double time) {\n\n    if (coeffs.size() != 3) {\n      throw invalid_argument(\"Invalid input coefficients, expected three vectors.\");\n    }\n\n    vector<double> rotation = {0.0, 0.0, 0.0};\n\n    rotation[0] = evaluatePolynomial(coeffs[0], time, 0); // X\n    rotation[1] = evaluatePolynomial(coeffs[1], time, 0); // Y\n    rotation[2] = evaluatePolynomial(coeffs[2], time, 0); // Z\n\n    Eigen::Quaterniond quat;\n    quat = Eigen::AngleAxisd(rotation[0] * M_PI / 180, Eigen::Vector3d::UnitZ())\n                * Eigen::AngleAxisd(rotation[1] * M_PI / 180, Eigen::Vector3d::UnitX())\n                * Eigen::AngleAxisd(rotation[2] * M_PI / 180, Eigen::Vector3d::UnitZ());\n\n    quat.normalize();\n\n    vector<double> rotationQ = {quat.w(), quat.x(), quat.y(), quat.z()};\n    return rotationQ;\n  }\n\n  vector<double> getAngularVelocity(vector<vector<double>> coeffs, double time) {\n\n    if (coeffs.size() != 3) {\n      throw invalid_argument(\"Invalid input coefficients, expected three vectors.\");\n    }\n\n    double phi = evaluatePolynomial(coeffs[0], time, 0); // X\n    double theta = evaluatePolynomial(coeffs[1], time, 0); // Y\n    double psi = evaluatePolynomial(coeffs[2], time, 0); // Z\n\n    double phi_dt = evaluatePolynomial(coeffs[0], time, 1);\n    double theta_dt = evaluatePolynomial(coeffs[1], time, 1);\n    double psi_dt = evaluatePolynomial(coeffs[2], time, 1);\n\n    Eigen::Quaterniond quat1, quat2;\n    quat1 = Eigen::AngleAxisd(phi * M_PI / 180, Eigen::Vector3d::UnitZ());\n    quat2 =  Eigen::AngleAxisd(theta * M_PI / 180, Eigen::Vector3d::UnitX());\n\n    Eigen::Vector3d velocity =  phi_dt * Eigen::Vector3d::UnitZ();\n    velocity += theta_dt * (quat1 *  Eigen::Vector3d::UnitX());\n    velocity += psi_dt * (quat1 * quat2 *  Eigen::Vector3d::UnitZ());\n\n    return {velocity[0], velocity[1], velocity[2]};\n  }\n\n  // Polynomial evaluation helper function\n  // The equation evaluated by this function is:\n  //                x = cx_0 + cx_1 * t^(1) + ... + cx_n * t^n\n  // The d parameter is for which derivative of the polynomial to compute.\n  // Supported options are\n  //   0: no derivative\n  //   1: first derivative\n  //   2: second derivative\n  double evaluatePolynomial(vector<double> coeffs, double time, int d){\n    if (coeffs.empty()) {\n      throw invalid_argument(\"Invalid input coeffs, must be non-empty.\");\n    }\n\n    if (d < 0) {\n      throw invalid_argument(\"Invalid derivative degree, must be non-negative.\");\n    }\n\n    vector<double> derivatives(d + 1);\n    gsl_poly_eval_derivs(coeffs.data(), coeffs.size(), time,\n                         derivatives.data(), derivatives.size());\n\n    return derivatives.back();\n  }\n\n double interpolate(vector<double> points, vector<double> times, double time, interpolation interp, int d) {\n   size_t numPoints = points.size();\n   if (numPoints < 2) {\n     throw invalid_argument(\"At least two points must be input to interpolate over.\");\n   }\n   if (points.size() != times.size()) {\n     throw invalid_argument(\"Invalid gsl_interp_type data, must have the same number of points as times.\");\n   }\n   if (time < times.front() || time > times.back()) {\n     throw invalid_argument(\"Invalid gsl_interp_type time, outside of input times.\");\n   }\n\n   // convert our interp enum into a GSL one,\n   // should be easy to add non GSL interp methods here later\n   const gsl_interp_type *interp_methods[] = {gsl_interp_linear, gsl_interp_cspline};\n\n   gsl_interp *interpolator = gsl_interp_alloc(interp_methods[interp], numPoints);\n   gsl_interp_init(interpolator, &times[0], &points[0], numPoints);\n   gsl_interp_accel *acc = gsl_interp_accel_alloc();\n\n   // GSL evaluate\n   double result;\n   switch(d) {\n     case 0:\n       result = gsl_interp_eval(interpolator, &times[0], &points[0], time, acc);\n       break;\n     case 1:\n       result = gsl_interp_eval_deriv(interpolator, &times[0], &points[0], time, acc);\n       break;\n     case 2:\n       result = gsl_interp_eval_deriv2(interpolator, &times[0], &points[0], time, acc);\n       break;\n     default:\n       throw invalid_argument(\"Invalid derivitive option, must be 0, 1 or 2.\");\n       break;\n   }\n\n   // GSL clean up\n   gsl_interp_free(interpolator);\n   gsl_interp_accel_free(acc);\n\n   return result;\n }\n\n std::string getPyTraceback() {\n    PyObject* err = PyErr_Occurred();\n    if (err != NULL) {\n        PyObject *ptype, *pvalue, *ptraceback;\n        PyObject *pystr, *module_name, *pyth_module, *pyth_func;\n        char *str;\n        char *full_backtrace;\n        char *error_description;\n\n        PyErr_Fetch(&ptype, &pvalue, &ptraceback);\n        pystr = PyObject_Str(pvalue);\n        str = PyBytes_AS_STRING(PyUnicode_AsUTF8String(pystr));\n        error_description = strdup(str);\n\n        // See if we can get a full traceback\n        module_name = PyUnicode_FromString(\"traceback\");\n        pyth_module = PyImport_Import(module_name);\n        Py_DECREF(module_name);\n\n        if (pyth_module == NULL) {\n            throw runtime_error(\"getPyTraceback - Failed to import Python traceback Library\");\n        }\n\n        pyth_func = PyObject_GetAttrString(pyth_module, \"format_exception\");\n        PyObject *pyth_val;\n        pyth_val = PyObject_CallFunctionObjArgs(pyth_func, ptype, pvalue, ptraceback, NULL);\n\n        pystr = PyObject_Str(pyth_val);\n        str = PyBytes_AS_STRING(PyUnicode_AsUTF8String(pystr));\n        full_backtrace = strdup(str);\n        Py_DECREF(pyth_val);\n\n        std::string join_cmd = \"trace = ''.join(list(\" + std::string(full_backtrace) + \"))\";\n        PyRun_SimpleString(join_cmd.c_str());\n\n        PyObject *evalModule = PyImport_AddModule( (char*)\"__main__\" );\n        PyObject *evalDict = PyModule_GetDict( evalModule );\n        PyObject *evalVal = PyDict_GetItemString( evalDict, \"trace\" );\n        full_backtrace = PyBytes_AS_STRING(PyUnicode_AsUTF8String(evalVal));\n\n        return std::string(error_description) + \"\\n\" + std::string(full_backtrace);\n    }\n\n    // no traceback to return\n    return \"\";\n }\n\n std::string loads(std::string filename, std::string props, std::string formatter, bool verbose) {\n     static bool first_run = true;\n     if(first_run) {\n         // Initialize the Python interpreter but only once.\n         first_run = !first_run;\n         Py_Initialize();\n         atexit(Py_Finalize);\n     }\n\n     // Import the file as a Python module.\n     PyObject *pModule = PyImport_Import(PyUnicode_FromString(\"ale\"));\n     if(!pModule) {\n       throw runtime_error(\"Failed to import ale. Make sure the ale python library is correctly installed.\");\n     }\n     // Create a dictionary for the contents of the module.\n     PyObject *pDict = PyModule_GetDict(pModule);\n\n     // Get the add method from the dictionary.\n     PyObject *pFunc = PyDict_GetItemString(pDict, \"loads\");\n     if(!pFunc) {\n       // import errors do not set a PyError flag, need to use a custom\n       // error message instead.\n       throw runtime_error(\"Failed to import ale.loads function from Python.\"\n                           \"This Usually indicates an error in the Ale Python Library.\"\n                           \"Check if Installed correctly and the function ale.loads exists.\");\n     }\n\n     // Create a Python tuple to hold the arguments to the method.\n     PyObject *pArgs = PyTuple_New(3);\n     if(!pArgs) {\n       throw runtime_error(getPyTraceback());\n     }\n\n     // Set the Python int as the first and second arguments to the method.\n     PyObject *pStringFileName = PyUnicode_FromString(filename.c_str());\n     PyTuple_SetItem(pArgs, 0, pStringFileName);\n\n     PyObject *pStringProps = PyUnicode_FromString(props.c_str());\n     PyTuple_SetItem(pArgs, 1, pStringProps);\n\n     PyObject *pStringFormatter = PyUnicode_FromString(formatter.c_str());\n     PyTuple_SetItem(pArgs, 2, pStringFormatter);\n\n     // Call the function with the arguments.\n     PyObject* pResult = PyObject_CallObject(pFunc, pArgs); \n\n     if(!pResult) {\n        throw invalid_argument(\"No Valid instrument found for label.\");\n     }\n\n     PyObject *pResultStr = PyObject_Str(pResult);\n     PyObject *temp_bytes = PyUnicode_AsUTF8String(pResultStr); // Owned reference\n\n     if(!temp_bytes){\n       throw invalid_argument(getPyTraceback());\n     }\n     std::string cResult;\n     char *temp_str = PyBytes_AS_STRING(temp_bytes); // Borrowed pointer\n     cResult = temp_str; // copy into std::string\n\n     Py_DECREF(pResultStr); \n     Py_DECREF(pStringFileName);\n     Py_DECREF(pStringProps);\n     Py_DECREF(pStringFormatter); \n\n     return cResult;\n }\n\n json load(std::string filename, std::string props, std::string formatter, bool verbose) {\n   std::string jsonstr = loads(filename, props, formatter, verbose);\n   return json::parse(jsonstr);\n }\n}\n", "meta": {"hexsha": "4ac8550807024af6e3d0dcb950a40cd70e0131b9", "size": 15192, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ale.cpp", "max_stars_repo_name": "kaitlyndlee/ale", "max_stars_repo_head_hexsha": "44db2f5910a2f937a1946c6ff485b0d4b7b26a18", "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/ale.cpp", "max_issues_repo_name": "kaitlyndlee/ale", "max_issues_repo_head_hexsha": "44db2f5910a2f937a1946c6ff485b0d4b7b26a18", "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/ale.cpp", "max_forks_repo_name": "kaitlyndlee/ale", "max_forks_repo_head_hexsha": "44db2f5910a2f937a1946c6ff485b0d4b7b26a18", "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.784503632, "max_line_length": 109, "alphanum_fraction": 0.6304634018, "num_tokens": 3857, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186768138228, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4879970013616309}}
{"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#include <gtest/gtest.h>\n\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/weighted_kurtosis.hpp>\n#include <boost/accumulators/statistics/weighted_mean.hpp>\n#include <boost/accumulators/statistics/weighted_median.hpp>\n#include <boost/accumulators/statistics/weighted_skewness.hpp>\n#include <boost/accumulators/statistics/weighted_sum.hpp>\n#include <boost/accumulators/statistics/weighted_variance.hpp>\n\n#include \"pyinterp/detail/math/descriptive_statistics.hpp\"\n\nnamespace math = pyinterp::detail::math;\n\nstatic double x[20] = {0.00402322, 0.19509434, 0.6425439,  0.66463742,\n                       0.76523411, 0.91985221, 0.82729929, 0.21502902,\n                       0.48254104, 0.97854649, 0.61394511, 0.00583773,\n                       0.06630172, 0.57173946, 0.5881294,  0.30185368,\n                       0.18126563, 0.84524097, 0.13754961, 0.17343529};\nstatic double w[20] = {0.45463566, 0.46341234, 0.2072285,  0.02272363,\n                       0.76796619, 0.01987153, 0.43634701, 0.1369698,\n                       0.65012667, 0.18825124, 0.96310554, 0.31995482,\n                       0.28808939, 0.69961506, 0.97369255, 0.98436659,\n                       0.05230501, 0.8073624,  0.40509977, 0.6325752};\n\nusing Accumulators = boost::accumulators::accumulator_set<\n    double,\n    boost::accumulators::stats<\n        boost::accumulators::tag::count, boost::accumulators::tag::max,\n        boost::accumulators::tag::min, boost::accumulators::tag::sum_of_weights,\n        boost::accumulators::tag::weighted_kurtosis,\n        boost::accumulators::tag::weighted_mean,\n        // boost::accumulators::tag::weighted_median(\n        //     boost::accumulators::with_p_square_quantile),\n        boost::accumulators::tag::weighted_skewness,\n        boost::accumulators::tag::weighted_sum,\n        boost::accumulators::tag::weighted_variance(boost::accumulators::lazy)>,\n    double>;\n\nTEST(math_descriptive_statistics, univariate) {\n  auto boost_acc = Accumulators();\n  auto acc = math::DescriptiveStatistics<double>();\n\n  for (auto ix = 0; ix < 20; ++ix) {\n    boost_acc(x[ix], boost::accumulators::weight = 1);\n    acc(x[ix]);\n  }\n\n  EXPECT_EQ(boost::accumulators::count(boost_acc), acc.count());\n  EXPECT_DOUBLE_EQ(boost::accumulators::min(boost_acc), acc.min());\n  EXPECT_DOUBLE_EQ(boost::accumulators::max(boost_acc), acc.max());\n  EXPECT_DOUBLE_EQ(boost::accumulators::weighted_mean(boost_acc), acc.mean());\n  EXPECT_NEAR(boost::accumulators::weighted_variance(boost_acc), acc.variance(),\n              1e-12);\n  EXPECT_NEAR(boost::accumulators::weighted_kurtosis(boost_acc), acc.kurtosis(),\n              1e-12);\n  EXPECT_NEAR(boost::accumulators::weighted_skewness(boost_acc), acc.skewness(),\n              1e-12);\n  EXPECT_DOUBLE_EQ(boost::accumulators::weighted_sum(boost_acc), acc.sum());\n  EXPECT_DOUBLE_EQ(boost::accumulators::sum_of_weights(boost_acc),\n                   acc.sum_of_weights());\n\n  auto copy = math::DescriptiveStatistics<double>(\n      static_cast<math::Accumulators<double>>(acc));\n  EXPECT_EQ(boost::accumulators::count(boost_acc), copy.count());\n  EXPECT_DOUBLE_EQ(boost::accumulators::min(boost_acc), copy.min());\n  EXPECT_DOUBLE_EQ(boost::accumulators::max(boost_acc), copy.max());\n  EXPECT_DOUBLE_EQ(boost::accumulators::weighted_mean(boost_acc), copy.mean());\n  EXPECT_NEAR(boost::accumulators::weighted_variance(boost_acc),\n              copy.variance(), 1e-12);\n  EXPECT_NEAR(boost::accumulators::weighted_kurtosis(boost_acc),\n              copy.kurtosis(), 1e-12);\n  EXPECT_NEAR(boost::accumulators::weighted_skewness(boost_acc),\n              copy.skewness(), 1e-12);\n  EXPECT_DOUBLE_EQ(boost::accumulators::weighted_sum(boost_acc), copy.sum());\n  EXPECT_DOUBLE_EQ(boost::accumulators::sum_of_weights(boost_acc),\n                   copy.sum_of_weights());\n}\n\nTEST(math_descriptive_statistics, weighted) {\n  auto boost_acc = Accumulators();\n  auto acc = math::DescriptiveStatistics<double>();\n  auto min = std::numeric_limits<double>::max();\n  auto max = std::numeric_limits<double>::min();\n\n  for (auto ix = 0; ix < 20; ++ix) {\n    boost_acc(x[ix], boost::accumulators::weight = w[ix]);\n    acc(x[ix], w[ix]);\n    auto value = x[ix] * w[ix];\n    min = std::min(min, value);\n    max = std::max(max, value);\n  }\n\n  EXPECT_EQ(boost::accumulators::count(boost_acc), acc.count());\n  EXPECT_DOUBLE_EQ(min, acc.min());\n  EXPECT_DOUBLE_EQ(max, acc.max());\n  EXPECT_DOUBLE_EQ(boost::accumulators::weighted_mean(boost_acc), acc.mean());\n  EXPECT_NEAR(boost::accumulators::weighted_variance(boost_acc), acc.variance(),\n              1e-12);\n  EXPECT_NEAR(boost::accumulators::weighted_kurtosis(boost_acc), acc.kurtosis(),\n              1e-12);\n  EXPECT_NEAR(boost::accumulators::weighted_skewness(boost_acc), acc.skewness(),\n              1e-12);\n  EXPECT_DOUBLE_EQ(boost::accumulators::weighted_sum(boost_acc), acc.sum());\n  EXPECT_DOUBLE_EQ(boost::accumulators::sum_of_weights(boost_acc),\n                   acc.sum_of_weights());\n}\n", "meta": {"hexsha": "1e1c81d0b89e37825b5d110dc62aa99424e0d16f", "size": 5210, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/pyinterp/core/tests/math_descriptive_statistics.cpp", "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/tests/math_descriptive_statistics.cpp", "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/tests/math_descriptive_statistics.cpp", "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": 46.1061946903, "max_line_length": 80, "alphanum_fraction": 0.686756238, "num_tokens": 1385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186768138228, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4879970013616309}}
{"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_EXPONENTIAL_FUNCTIONS_SCALAR_IMPL_LOGS_F_LOG_HPP_INCLUDED\n#define NT2_EXPONENTIAL_FUNCTIONS_SCALAR_IMPL_LOGS_F_LOG_HPP_INCLUDED\n\n#include <nt2/include/functions/scalar/is_ltz.hpp>\n#include <nt2/include/functions/scalar/is_eqz.hpp>\n#include <nt2/include/functions/scalar/fma.hpp>\n#include <nt2/exponential/functions/scalar/impl/logs/f_kernel.hpp>\n#include <nt2/include/constants/zero.hpp>\n#include <nt2/include/constants/nan.hpp>\n#include <nt2/include/constants/minf.hpp>\n#include <nt2/include/constants/mhalf.hpp>\n#include <nt2/include/constants/log_2hi.hpp>\n#include <nt2/include/constants/log_2lo.hpp>\n#include <nt2/include/constants/log2_em1.hpp>\n#include <nt2/include/constants/log10_ehi.hpp>\n#include <nt2/include/constants/log10_elo.hpp>\n#include <nt2/include/constants/log10_2hi.hpp>\n#include <nt2/include/constants/log10_2lo.hpp>\n#include <nt2/sdk/meta/as_integer.hpp>\n#include <nt2/sdk/meta/scalar_of.hpp>\n#include <boost/simd/sdk/config.hpp>\n\n#ifndef BOOST_SIMD_NO_NANS\n#include <nt2/include/functions/scalar/is_nan.hpp>\n#endif\n#ifndef BOOST_SIMD_NO_INFINITIES\n#include <nt2/include/constants/inf.hpp>\n#endif\n#ifndef BOOST_SIMD_NO_DENORMALS\n#include <nt2/include/functions/scalar/abs.hpp>\n#include <nt2/include/constants/smallestposval.hpp>\n#include <nt2/include/constants/twotonmb.hpp>\n#include <nt2/include/constants/mlogtwo2nmb.hpp>\n#include <nt2/include/constants/mlog2two2nmb.hpp>\n#include <nt2/include/constants/mlog10two2nmb.hpp>\n#endif\n\nnamespace nt2 { namespace details\n{\n  template < class A0,\n             class Style ,\n             class base_A0 = typename meta::scalar_of<A0>::type>\n             struct logarithm{};\n\n  template < class A0 >\n  struct logarithm< A0, tag::not_simd_type, float>\n  {\n    typedef typename meta::as_integer<A0, signed>::type    int_type;\n    typedef typename meta::scalar_of<A0>::type                  sA0;\n    typedef kernel<A0, tag::not_simd_type, float>          kernel_t;\n    static inline A0 log(const A0& a0)\n    {\n#ifndef BOOST_SIMD_NO_INFINITIES\n      if (BOOST_UNLIKELY(a0 == nt2::Inf<A0>())) return a0;\n#endif\n      if (BOOST_UNLIKELY(nt2::is_eqz(a0))) return nt2::Minf<A0>();\n#ifdef BOOST_SIMD_NO_NANS\n      if (BOOST_UNLIKELY(nt2::is_ltz(a0))) return nt2::Nan<A0>();\n#else\n      if (BOOST_UNLIKELY(nt2::is_nan(a0)||nt2::is_ltz(a0))) return nt2::Nan<A0>();\n#endif\n      A0 z = a0;\n#ifndef BOOST_SIMD_NO_DENORMALS\n      A0 t = Zero<A0>();\n      if(BOOST_UNLIKELY(nt2::abs(z) < Smallestposval<A0>()))\n      {\n        z *= Twotonmb<A0>();\n        t = Mlogtwo2nmb<A0>();\n      }\n#endif\n      A0 x, fe, x2, y;\n      kernel_t::log(z, fe, x, x2, y);\n      y = nt2::fma(fe, Log_2lo<A0>(), y);\n      y = nt2::fma(Mhalf<A0>(), x2, y);\n#ifdef BOOST_SIMD_NO_DENORMALS\n      return nt2::fma(Log_2hi<A0>(), fe, x+y);\n#else\n      return nt2::fma(Log_2hi<A0>(), fe, x+y+t);\n#endif\n    }\n\n    static inline A0 log2(const A0& a0)\n    {\n#ifndef BOOST_SIMD_NO_INFINITIES\n      if (BOOST_UNLIKELY(a0 == nt2::Inf<A0>())) return a0;\n#endif\n      if (BOOST_UNLIKELY(nt2::is_eqz(a0))) return nt2::Minf<A0>();\n#ifdef BOOST_SIMD_NO_NANS\n      if (BOOST_UNLIKELY(nt2::is_ltz(a0))) return nt2::Nan<A0>();\n#else\n      if (BOOST_UNLIKELY(nt2::is_nan(a0)||nt2::is_ltz(a0))) return nt2::Nan<A0>();\n#endif\n      A0 z = a0;\n#ifndef BOOST_SIMD_NO_DENORMALS\n      A0 t = Zero<A0>();\n      if (BOOST_UNLIKELY(nt2::abs(z) < Smallestposval<A0>()))\n      {\n        z *= Twotonmb<A0>();\n        t = Mlog2two2nmb<A0>();\n      }\n#endif\n      A0 x, fe, x2, y;\n      kernel_t::log(z, fe, x, x2, y);\n      y = nt2::fma(Mhalf<A0>(),x2, y);\n      z = nt2::fma(x,Log2_em1<A0>(),y*Log2_em1<A0>());\n#ifdef BOOST_SIMD_NO_DENORMALS\n      return ((z+y)+x)+fe;\n#else\n      return ((z+y)+x)+fe+t;\n#endif\n    }\n\n    static inline A0 log10(const A0& a0)\n    {\n#ifndef BOOST_SIMD_NO_INFINITIES\n      if (BOOST_UNLIKELY(a0 == nt2::Inf<A0>())) return a0;\n#endif\n      if (BOOST_UNLIKELY(nt2::is_eqz(a0))) return nt2::Minf<A0>();\n#ifdef BOOST_SIMD_NO_NANS\n      if (BOOST_UNLIKELY(nt2::is_ltz(a0))) return nt2::Nan<A0>();\n#else\n      if (BOOST_UNLIKELY(nt2::is_nan(a0)||nt2::is_ltz(a0))) return nt2::Nan<A0>();\n#endif\n      A0 z = a0;\n#ifndef BOOST_SIMD_NO_DENORMALS\n      A0 t = Zero<A0>();\n      if (BOOST_UNLIKELY(nt2::abs(z) < Smallestposval<A0>()))\n      {\n        z *= Twotonmb<A0>();\n        t = Mlog10two2nmb<A0>();\n      }\n#endif\n      A0 x, fe, x2, y;\n      kernel_t::log(z, fe, x, x2, y);\n      y = nt2::amul(y, Mhalf<A0>(), x2);\n      z = mul(x+y, Log10_elo<A0>());\n      z = nt2::amul(z, y, Log10_ehi<A0>());\n      z = nt2::amul(z, x, Log10_ehi<A0>());\n      z = nt2::amul(z, fe, Log10_2hi<A0>());\n#ifdef BOOST_SIMD_NO_DENORMALS\n      return nt2::amul(z, fe, Log10_2lo<A0>());\n#else\n      return nt2::amul(z+t, fe, Log10_2lo<A0>());\n#endif\n    }\n  };\n} }\n\n\n#endif\n", "meta": {"hexsha": "21d74e540e8b8e23af9bfda9b883caf4ae93a892", "size": 5291, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/exponential/include/nt2/exponential/functions/scalar/impl/logs/f_log.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/exponential/include/nt2/exponential/functions/scalar/impl/logs/f_log.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/exponential/include/nt2/exponential/functions/scalar/impl/logs/f_log.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": 33.2767295597, "max_line_length": 82, "alphanum_fraction": 0.6293706294, "num_tokens": 1644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186768138228, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.4879970013616308}}
{"text": "// Filthy awful hack to test.\n#include \"gtest/gtest.h\"\n#include <Eigen/Dense>\n#define private public\n#include \"bond.h\"\n\n\nTEST(ExcitementTest, ZeroExcitement)\n{\n    // Test the excitement factor of a single bond that isn't stretched\n    Eigen::VectorXd rail(2);\n    rail << 1.0, 0.0;\n    const HarmonicBond bond {1.0, 1.0, 1, 0, rail};\n    \n    Eigen::MatrixXd positions(2, 2);\n    positions << 0.0, 0.0,\n                 1.0, 0.0;\n\n    ASSERT_FLOAT_EQ(bond.get_excitement_factor(positions), 1.0);\n}\n\nTEST(ExcitementTest, NegativeExcitement)\n{\n    // Test the excitement factor of a single bond that is stretched the other way\n    Eigen::VectorXd rail(2);\n    rail << 1.0, 0.0;\n    const HarmonicBond bond {1.0, 1.0, 1, 0, rail};\n    \n    Eigen::MatrixXd positions(2, 2);\n    positions << 1.0, 0.0,\n                 0.0, 0.0;\n\n    ASSERT_FLOAT_EQ(bond.get_excitement_factor(positions), -1.0);\n}\n\nTEST(ExcitementTest, DoubleNegativeExcitement)\n{\n    // Test the excitement factor of a single bond that is stretched the other way\n    Eigen::VectorXd rail(2);\n    rail << 1.0, 0.0;\n    const HarmonicBond bond {1.0, 1.0, 1, 0, rail};\n    \n    Eigen::MatrixXd positions(2, 2);\n    positions << 2.0, 0.0,\n                 0.0, 0.0;\n\n    ASSERT_FLOAT_EQ(bond.get_excitement_factor(positions), -2.0);\n}\n\nTEST(ExcitementTest, DoubleExcitement)\n{\n    // Test the excitement factor of a single bond that is stretched the other way\n    Eigen::VectorXd rail(2);\n    rail << 1.0, 0.0;\n    const HarmonicBond bond {1.0, 1.0, 1, 0, rail};\n    \n    Eigen::MatrixXd positions(2, 2);\n    positions << 0.0, 0.0,\n                 2.0, 0.0;\n\n    ASSERT_FLOAT_EQ(bond.get_excitement_factor(positions), 2.0);\n}\n\nTEST(ExcitementTest, OffRailDoubleExcitement)\n{\n    // Test the excitement factor of a single bond that is off the rail\n    Eigen::VectorXd rail(2);\n    rail << 1.0, 0.0;\n    const HarmonicBond bond {1.0, 1.0, 1, 0, rail};\n    \n    Eigen::MatrixXd positions(2, 2);\n    positions << 0.0, 0.0,\n                 2.0, 1.0;\n\n    ASSERT_FLOAT_EQ(bond.get_excitement_factor(positions), 2.0);\n}\n", "meta": {"hexsha": "b385c22aa3460990ef1fa1d8f9e95d68984edfd6", "size": 2075, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_excitements.cpp", "max_stars_repo_name": "Matt-HJ-Bailey/Constrained-MD", "max_stars_repo_head_hexsha": "3897a5f97272772ea03f953414df779aed844216", "max_stars_repo_licenses": ["MIT"], "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_excitements.cpp", "max_issues_repo_name": "Matt-HJ-Bailey/Constrained-MD", "max_issues_repo_head_hexsha": "3897a5f97272772ea03f953414df779aed844216", "max_issues_repo_licenses": ["MIT"], "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_excitements.cpp", "max_forks_repo_name": "Matt-HJ-Bailey/Constrained-MD", "max_forks_repo_head_hexsha": "3897a5f97272772ea03f953414df779aed844216", "max_forks_repo_licenses": ["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.9480519481, "max_line_length": 82, "alphanum_fraction": 0.6303614458, "num_tokens": 684, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.48794186079597585}}
{"text": "#include <functional>\n#include <map>\n#include <random>\n#include <set>\n#include <vector>\n\n#include <iostream>\n\n#include \"third_party/catch.h\"\n#include \"result.h\"\n#include <boost/container/flat_set.hpp>\n#include <boost/container/flat_map.hpp>\n\nusing boost::container::flat_map;\nusing boost::container::flat_set;\n\ntemplate <typename K, typename V>\nflat_map<K, flat_set<V>> build_flat_map_of_flat_sets(std::vector<std::pair<K, V>> buf) {\n  std::sort(buf.begin(), buf.end());\n  buf.erase(std::unique(buf.begin(), buf.end()), buf.end());\n\n  flat_map<K, flat_set<V>> res;\n  for (auto r : srt::group_equals(buf.begin(), buf.end(),\n                                  [](const auto& x, const auto& y) { return x.first < y.first; })) {\n    res.emplace_hint(res.end(), std::move(r.begin()->first), flat_set<V>{});\n    auto& cur_set = (--res.end())->second;\n    for (auto& elem : r)\n      cur_set.insert(cur_set.end(), std::move(elem.second));\n  }\n\n  return res;\n}\n\ntemplate <typename C>\nstd::vector<std::pair<int, int>> to_vector_of_pairs_for_test(const C& c) {\n  std::vector<std::pair<int, int>> res;\n  for (const auto& pr : c) {\n    for (int v : pr.second)\n      res.emplace_back(pr.first, v);\n  }\n  return res;\n}\n\nTEST_CASE(\"build_flat_map_of_flat_sets\", \"[usage_examples]\") {\n  const std::vector<std::pair<int, int>> input = [] {\n    std::uniform_int_distribution<> dist(0, 100);\n    std::mt19937 g;\n\n    std::vector<std::pair<int, int>> res;\n\n    for (int i = 0; i < 100; ++i) {\n      res.emplace_back(dist(g), dist(g));\n    }\n\n    return res;\n  }();\n\n  for (auto f = input.begin(); f != input.end(); ++f)\n    for (auto l = f; l != input.end(); ++l) {\n      std::map<int, std::set<int>> expected;\n      for (auto i = f; i != l; ++i)\n        expected[i->first].insert(i->second);\n\n      auto actual = build_flat_map_of_flat_sets(std::vector<std::pair<int, int>>{f, l});\n\n      auto expected_vec = to_vector_of_pairs_for_test(expected);\n      auto actual_vec = to_vector_of_pairs_for_test(actual);\n\n      REQUIRE(expected_vec.size() == actual_vec.size());\n      REQUIRE(expected_vec == actual_vec);\n    }\n}\n", "meta": {"hexsha": "30ea7b44b19b701a518f03791ce17b28f34a72f6", "size": 2097, "ext": "cc", "lang": "C++", "max_stars_repo_path": "flat_map_of_flat_sets.cc", "max_stars_repo_name": "DenisYaroshevskiy/partition_point_biased_blog_post", "max_stars_repo_head_hexsha": "ed43eda3b095bc21927793c4ab52e4768bd1b4f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-08-15T08:56:42.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-18T00:43:49.000Z", "max_issues_repo_path": "flat_map_of_flat_sets.cc", "max_issues_repo_name": "DenisYaroshevskiy/partition_point_biased_blog_post", "max_issues_repo_head_hexsha": "ed43eda3b095bc21927793c4ab52e4768bd1b4f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "flat_map_of_flat_sets.cc", "max_forks_repo_name": "DenisYaroshevskiy/partition_point_biased_blog_post", "max_forks_repo_head_hexsha": "ed43eda3b095bc21927793c4ab52e4768bd1b4f2", "max_forks_repo_licenses": ["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.7260273973, "max_line_length": 100, "alphanum_fraction": 0.6242250835, "num_tokens": 568, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.737158174177441, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.4879418536916126}}
{"text": "#ifndef PROJECT_GRIDPOINT_HPP\n#define PROJECT_GRIDPOINT_HPP\n\n#include <stdint.h>\n#include <string>\n#include <limits>\n\n#include <Eigen/Dense>\n\nnamespace fsd {\n\nusing Eigen::Vector2d;\nusing std::string;\n/**\n * @brief The GridPoint class representing a point in a grid by row, column, for\n * fast lookup\n */\nclass GridPoint {\npublic:\n    /**\n     * @brief the type of point this gridpoint is constructed from,\n     * must have a (x, y)/coordinate constructor and x(), y()\n     * / cordinate getter methods. and probably more ..\n     *\n    **/\n    typedef Vector2d from_point_t;\n\n    typedef int32_t coordinates_t;\n    typedef int64_t key_t;\n    /**\n     * must be doulbe for packing, unpacking\n     */\n    static_assert(sizeof(coordinates_t) * 2 ==\n                  sizeof(key_t), \"key_t must be double \"\n                                 \"the size of coordinates_t for\"\n                                 \" packing and stuff\");\n    /**\n     * @brief getter for row\n     * @return row\n     */\n    coordinates_t get_row() const {\n        return row;\n    }\n\n    /**\n     * @brief getter for column\n     * @return column\n     */\n    coordinates_t  get_column() const {\n        return column;\n    }\n\n    /**\n     * @brief hit_cnt how many points mapped to this cell\n     */\n    uint32_t hit_cnt = 1;\n\n    /**\n     * @brief The coordinates struct used for other grid things\n     */\n    struct coordinates {\n        coordinates_t row, column;\n        coordinates(coordinates_t row_,\n                    coordinates_t column_) :\n            row(row_), column(column_) {}\n        coordinates() = default;\n    };\n\n    static_assert (sizeof (coordinates) == sizeof (key_t), \"key size must equal \"\n                                                           \"coordinates\");\n\n    /**\n     * @brief to_key creates collision free key by packing row and column\n     * in one integer\n     * @return key\n     */\n    key_t to_key() const {\n        coordinates coords;\n        // copy instead of brace initializer to avoid some bugs\n        // if the struct is redefined\n        coords.row = row;\n        coords.column = column;\n        return pack_key(coords);\n    }\n\n    /**\n     * @brief to_coordinates point to coordinates helper\n     * @param point\n     * @param cell_size\n     * @param scale to use more entropy on the coordinates\n     * and therefore have less collisions when saving in a hashtable,\n     * the coordinates can be scaled the use the whole range\n     * of coordinates_t type\n     * @return\n     */\n    static inline coordinates to_coordinates(\n            const from_point_t &point, double cell_size, double scale = 1.) {\n        double x = point.x() * scale;\n        if(x < 0.) {\n            x -= cell_size;\n        } else {\n            // also zero\n            x += cell_size;\n        }\n        double y = point.y() * scale;\n        if(y < 0.) {\n            y -= cell_size;\n        } else {\n            // also zero\n            y += cell_size;\n        }\n        // cast is used to truncate towards zero\n        coordinates coord;\n        coord.row = static_cast<coordinates_t>(x / cell_size);\n        coord.column = static_cast<coordinates_t>(y / cell_size);\n        return coord;\n    }\n\n//#define MIXING8\n    /**\n     * @brief pack_key helper to pack key, this zigzac\n     * packing is used\n     * to perform better with std::hash identity hash\n     * funtion, the lower bytes are packed,\n     * as there is the most entropy\n     * @param coords\n     * @return\n     */\n    static inline key_t pack_key(coordinates coords) {\n        key_t packed;\n#ifdef MIXING8\n        uint8_t *packed_ptr = ((uint8_t*)&packed);\n        uint8_t *row_ptr = ((uint8_t*)&(coords.row));\n        uint8_t *column_ptr = ((uint8_t*)&(coords.column));\n        packed_ptr[0] = row_ptr[0];\n        packed_ptr[1] = column_ptr[0];\n        packed_ptr[2] = row_ptr[1];\n        packed_ptr[3] = column_ptr[1];\n        packed_ptr[4] = row_ptr[2];\n        packed_ptr[5] = column_ptr[2];\n        packed_ptr[6] = row_ptr[3];\n        packed_ptr[7] = column_ptr[3];\n#else\n        ((uint32_t*)&packed)[0] = *((uint32_t*)&(coords.row));\n        ((uint32_t*)&packed)[1] = *((uint32_t*)&(coords.column));\n#endif\n        return packed;\n    }\n\n    static inline coordinates unpack_key(key_t key) {\n        coordinates coords;\n#ifdef MIXING8\n        uint8_t *packed_ptr = ((uint8_t*)&key);\n        uint8_t *row_ptr = ((uint8_t*)&(coords.row));\n        uint8_t *column_ptr = ((uint8_t*)&(coords.column));\n        row_ptr[0] = packed_ptr[0];\n        column_ptr[0] = packed_ptr[1];\n        row_ptr[1] = packed_ptr[2];\n        column_ptr[1] = packed_ptr[3];\n        row_ptr[2] = packed_ptr[4];\n        column_ptr[2] = packed_ptr[5];\n        row_ptr[3] = packed_ptr[6];\n        column_ptr[3] = packed_ptr[7];\n#else\n        *((uint32_t*)&(coords.row)) = ((uint32_t*)&key)[0];\n        *((uint32_t*)&(coords.column)) = ((uint32_t*)&key)[1];\n#endif\n        return  coords;\n    }\n\n    /**\n     * @brief to_key fast conversion to key. Allows checking in which\n     * cell this point would map without first constructing the point\n     * @param point\n     * @param cell_size\n     * @return key\n     */\n    static inline key_t to_key(const from_point_t &point,\n                               double cell_size, double scale = 1.) {\n        auto coords = to_coordinates(point, cell_size, scale);\n        return pack_key(coords);\n    }\n\n    /**\n     * @brief coordinates_would_overflow\n     * @param point\n     * @param cell_size\n     * @return true if coordinates would overflow\n     */\n    static bool coordinates_would_overflow(\n            const from_point_t &point, double cell_size) {\n        static_assert (sizeof (coordinates_t) <= 4,\n                       \"coordinates_would_overflow check unfortunately\"\n                       \"isn't implemented for coordinates_t type bigger than \"\n                       \"4 byte\");\n        double x = point.x();\n        if(x > 0.) {\n            x += cell_size;\n        } else if(x < 0.){\n            x -= cell_size;\n        }\n        double y = point.y();\n        if(y > 0.) {\n            y += cell_size;\n        } else if(y < 0.) {\n            y -= cell_size;\n        }\n\n        double row = x / cell_size;\n        double column = y / cell_size;\n        bool row_overflow = row > std::numeric_limits<coordinates_t>::max()\n                || row < std::numeric_limits<coordinates_t>::min();\n        bool column_overflow = column > std::numeric_limits<coordinates_t>::max()\n                || column < std::numeric_limits<coordinates_t>::min();\n        return row_overflow || column_overflow;\n    }\n\n    /**\n     * @brief to_point to_point creates a point with a datatype which is suitable\n     * for doing geometric calculations\n     * @param cell_size\n     * @param scale scale by which the coordinates where multiplied,\n     * so the inverse is taken to get the real coordinates\n     * @return\n     */\n    from_point_t to_point(double cell_size, double scale = 1.) const {\n        double tmp_x, tmp_y;\n        auto scale_inv = 1. / scale;\n        if (row < 0) {\n            tmp_x = ((row * cell_size) + .5 * cell_size) * scale_inv;\n        } else if(row > 0){\n            tmp_x = (((row - 1) * cell_size) + .5 * cell_size) * scale_inv;\n        } else {\n            tmp_x = 0;\n        }\n        if (column < 0) {\n            tmp_y = ((column * cell_size) + .5 * cell_size) * scale_inv;\n        } else if(column > 0){\n            tmp_y = (((column - 1) * cell_size) + .5 * cell_size) * scale_inv;\n        } else {\n            tmp_y = 0;\n        }\n        return from_point_t(tmp_x, tmp_y);\n\n    }\n\n    /**\n     * @brief to_point static method to build a point\n     * from key directly\n     * @param key\n     * @param cell_size\n     * @param scale scale by which the coordinates where multiplied,\n     * so the inverse is taken to get the real coordinates\n     * @return\n     */\n    static from_point_t to_point(key_t key, double cell_size, double scale = 1.) {\n        coordinates coords = unpack_key(key);\n        coordinates_t row = coords.row;\n        coordinates_t column = coords.column;\n        auto scale_inv = 1. / scale;\n        double tmp_x, tmp_y;\n        if (row < 0) {\n            tmp_x = ((row * cell_size) + .5 * cell_size) * scale_inv;\n        } else if(row > 0){\n            tmp_x =  (((row - 1) * cell_size) + .5 * cell_size) * scale_inv;\n        } else {\n            tmp_x = 0;\n        }\n\n        if (column < 0) {\n            tmp_y = ((column * cell_size) + .5 * cell_size) * scale_inv;\n        } else if(column > 0){\n            tmp_y = (((column - 1) * cell_size) + .5 * cell_size) * scale_inv;\n        } else {\n            tmp_y = 0;\n        }\n\n        return from_point_t(tmp_x, tmp_y);\n\n    }\n    /**\n     * @brief has_same_grid_position\n     * @param other_point\n     * @return true if it has same row and column\n     */\n    bool has_same_grid_position(const GridPoint &other_point) const {\n        return row == other_point.row &&\n                column == other_point.column;\n    }\n\n    /**\n     * @brief GridPoint construct gridpoint from vector and cell size\n     * @param point\n     * @param cell_size\n     */\n    GridPoint(from_point_t point, double cell_size, double scale = 1.) {\n        auto coord = to_coordinates(point, cell_size, scale);\n        row = coord.row;\n        column = coord.column;\n    }\n\n    GridPoint(coordinates_t row, coordinates_t column) :\n        row(row), column(column) {\n\n    }\n\n    GridPoint() = default;\n\n    /**\n     * @brief operator + adds coordinates of another point by adding row and column\n     * @param other_point\n     * @return\n     */\n    GridPoint operator+(const GridPoint &other_point) const {\n        GridPoint tmp(other_point);\n        tmp.row += row;\n        tmp.column += column;\n        return tmp;\n    }\n\n    /**\n     * @brief to string\n     * @return\n     */\n    virtual string to_string() const {\n        return \"point: row: \" + std::to_string(row) +\n                \", column: \" + std::to_string(column) +\n                \", hit_cnt: \" + std::to_string(hit_cnt);\n    }\n\n    virtual ~GridPoint() {}\n\nprotected:\n    coordinates_t row = 0;\n    coordinates_t column = 0;\n};\n\n} // end namespace fsd\n\n#endif //PROJECT_GRIDPOINT_HPP\n", "meta": {"hexsha": "ce776e9e7f85e9d634f37b53b905ea504a71b5e9", "size": 10194, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/shrs/GridPoint.hpp", "max_stars_repo_name": "iv461/spatial_hashing", "max_stars_repo_head_hexsha": "639295a47e74285046c9a15e6c37039916901ae3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-26T23:16:37.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-26T23:16:37.000Z", "max_issues_repo_path": "include/shrs/GridPoint.hpp", "max_issues_repo_name": "iv461/spatial_hashing", "max_issues_repo_head_hexsha": "639295a47e74285046c9a15e6c37039916901ae3", "max_issues_repo_licenses": ["MIT"], "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/shrs/GridPoint.hpp", "max_forks_repo_name": "iv461/spatial_hashing", "max_forks_repo_head_hexsha": "639295a47e74285046c9a15e6c37039916901ae3", "max_forks_repo_licenses": ["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.8944281525, "max_line_length": 83, "alphanum_fraction": 0.5587600549, "num_tokens": 2498, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.661922862511608, "lm_q1q2_score": 0.4879418411309756}}
{"text": "#include \"denominator.hpp\"\n#include \"ast.hpp\"\n#include \"parsers.hpp\"\n#include \"types.hpp\"\n#include <boost/variant.hpp>\n#include <stdexcept>\nnamespace HT\n{\n    void denominator(PASTNode astnode, ParsersHelper& ph)\n    {\n        auto myParserHelper(ph);\n        if (astnode->ch.size()!=2)\n          throw std::runtime_error(\"denominator can only have one parameter\");\n        auto & secondCh = *astnode->ch.rbegin();\n        ph.parse(secondCh);\n        if (secondCh->token.tokenType != Complex || ! boost::get<ComplexType>(secondCh->token.info).isReal())\n          throw std::runtime_error(\"The argument of denominator must be real\");\n        auto cast = boost::get<ComplexType>(secondCh->token.info);\n\n        astnode->token.tokenType = Complex;\n        astnode->type = Simple;\n        astnode->token.info = ComplexType(cast.toexact().getRealR().getDown());\n\n        astnode->remove();\n    }\n\n}\n\n\n", "meta": {"hexsha": "05800506654a25ce0ddb3c05e1ec3b7f49718321", "size": 896, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "funs/denominator.cpp", "max_stars_repo_name": "htfy96/htscheme", "max_stars_repo_head_hexsha": "b44c9f9672f69d9b3c2eb1c80969bcfcfec9990f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2015-07-07T01:30:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-14T10:45:01.000Z", "max_issues_repo_path": "funs/denominator.cpp", "max_issues_repo_name": "htfy96/htscheme", "max_issues_repo_head_hexsha": "b44c9f9672f69d9b3c2eb1c80969bcfcfec9990f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "funs/denominator.cpp", "max_forks_repo_name": "htfy96/htscheme", "max_forks_repo_head_hexsha": "b44c9f9672f69d9b3c2eb1c80969bcfcfec9990f", "max_forks_repo_licenses": ["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.8666666667, "max_line_length": 109, "alphanum_fraction": 0.6428571429, "num_tokens": 215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799253, "lm_q2_score": 0.6619228691808011, "lm_q1q2_score": 0.48794183840283867}}
{"text": "#include <boost/test/unit_test.hpp>\n\n#include <set>\n#include <iostream>\n\n// using namespace std;\nusing namespace crave;\n\nBOOST_FIXTURE_TEST_SUITE(Operators_t, Context_Fixture)\n\nBOOST_AUTO_TEST_CASE(logical_not_t1) {\n  Variable<unsigned int> a;\n  Generator gen;\n  gen(!(a != 0));\n\n  BOOST_REQUIRE(gen.next());\n  BOOST_REQUIRE_EQUAL(gen[a], 0);\n}\n\nBOOST_AUTO_TEST_CASE(logical_not_t2) {\n  Variable<unsigned char> a;\n  Variable<unsigned int> b;\n  Generator gen;\n\n  gen(if_then_else(!(a % 2 == 0), b > 0 && b <= 50, b > 50 && b <= 100));\n\n  BOOST_REQUIRE(gen.next());\n  std::cout << \"a =\" << gen[a] << \", b = \" << gen[b] << std::endl;\n  if (gen[a] % 2 != 0) {\n    BOOST_REQUIRE_GT(gen[b], 0u);\n    BOOST_REQUIRE_LE(gen[b], 50u);\n  } else {\n    BOOST_REQUIRE_GT(gen[b], 50u);\n    BOOST_REQUIRE_LE(gen[b], 100u);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(logical_and_t1) {\n  Variable<bool> a;\n  Variable<bool> b;\n  Variable<bool> c;\n  Generator gen(a == true);\n  gen(b == true);\n\n  BOOST_REQUIRE(gen.next());\n  gen(c == (a && b));\n\n  BOOST_REQUIRE(gen.next());\n  BOOST_REQUIRE_EQUAL(gen[c], true);\n\n  Generator gen2(a == true);\n  gen2(b == false);\n\n  BOOST_REQUIRE(gen2.next());\n  gen2(c == (a && b));\n\n  BOOST_REQUIRE(gen2.next());\n  BOOST_REQUIRE_EQUAL(gen2[c], false);\n}\n\nBOOST_AUTO_TEST_CASE(logical_or_t1) {\n  Variable<bool> a;\n  Variable<bool> b;\n  Variable<bool> c;\n  Generator gen(a == false);\n  gen(b == false);\n\n  BOOST_REQUIRE(gen.next());\n  gen(c == (a || b));\n\n  BOOST_REQUIRE(gen.next());\n  BOOST_REQUIRE_EQUAL(gen[c], false);\n\n  Generator gen2(a == true);\n  gen2(b == false);\n\n  BOOST_REQUIRE(gen2.next());\n  gen2(c == (a || b));\n\n  BOOST_REQUIRE(gen2.next());\n  BOOST_REQUIRE_EQUAL(gen2[c], true);\n}\n\nBOOST_AUTO_TEST_CASE(equal_t1) {\n  Variable<unsigned int> a;\n  Variable<unsigned int> b;\n  Generator gen(a == 65535);\n  gen(b == a);\n\n  BOOST_REQUIRE(gen.next());\n  BOOST_REQUIRE_EQUAL(gen[a], gen[b]);\n}\n\nBOOST_AUTO_TEST_CASE(not_equal_t1) {\n  Variable<unsigned int> a;\n  Variable<unsigned int> b;\n  Generator gen(a < 65535);\n  gen(b != a);\n\n  for (int i = 0; i < 300; ++i) {\n    BOOST_REQUIRE(gen.next());\n    BOOST_REQUIRE_NE(gen[a], gen[b]);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(less) {\n  VariableDefaultSolver::bypass_constraint_analysis = true;\n\n  Variable<unsigned> a;\n\n  Generator gen;\n  gen(a < 256u);\n\n  std::set<unsigned> generated;\n  for (unsigned iterations = 0; gen.next(); ++iterations) {\n    unsigned av = gen[a];\n    generated.insert(av);\n    gen(a != av);\n    BOOST_REQUIRE_LT(iterations, 300);\n  }\n\n  BOOST_REQUIRE_EQUAL(generated.size(), 256);\n\n  VariableDefaultSolver::bypass_constraint_analysis = false;\n}\n\nBOOST_AUTO_TEST_CASE(less_equal) {\n  VariableDefaultSolver::bypass_constraint_analysis = true;\n\n  Variable<unsigned> a;\n\n  Generator gen;\n  gen(a <= 256u);\n\n  std::set<unsigned> generated;\n  for (unsigned iterations = 0; gen.next(); ++iterations) {\n    unsigned av = gen[a];\n    generated.insert(av);\n    gen(a != av);\n    BOOST_REQUIRE_LT(iterations, 300);\n  }\n\n  BOOST_REQUIRE_EQUAL(generated.size(), 257);\n\n  VariableDefaultSolver::bypass_constraint_analysis = false;\n}\n\nBOOST_AUTO_TEST_CASE(greater) {\n  VariableDefaultSolver::bypass_constraint_analysis = true;\n\n  Variable<unsigned> a;\n\n  Generator gen;\n  gen(a > (std::numeric_limits<unsigned>::max() - 256));\n\n  std::set<unsigned> generated;\n  for (unsigned iterations = 0; gen.next(); ++iterations) {\n    unsigned av = gen[a];\n    generated.insert(av);\n    gen(a != av);\n    BOOST_REQUIRE_LT(iterations, 300);\n  }\n\n  BOOST_REQUIRE_EQUAL(generated.size(), 256);\n\n  VariableDefaultSolver::bypass_constraint_analysis = false;\n}\n\nBOOST_AUTO_TEST_CASE(greater_equal) {\n  VariableDefaultSolver::bypass_constraint_analysis = true;\n\n  Variable<unsigned> a;\n\n  Generator gen;\n  gen(a >= (std::numeric_limits<unsigned>::max() - 256));\n\n  std::set<unsigned> generated;\n  for (unsigned iterations = 0; gen.next(); ++iterations) {\n    unsigned av = gen[a];\n    generated.insert(av);\n    gen(a != av);\n    BOOST_REQUIRE_LT(iterations, 300);\n  }\n\n  BOOST_REQUIRE_EQUAL(generated.size(), 257);\n\n  VariableDefaultSolver::bypass_constraint_analysis = false;\n}\n\nBOOST_AUTO_TEST_CASE(neg_t1) {\n  Variable<int> a;\n  Variable<int> b;\n  Generator gen(a == -1337);\n\n  BOOST_REQUIRE(gen.next());\n  BOOST_REQUIRE_EQUAL(gen[a], -1337);\n  gen(b == -a);\n\n  BOOST_REQUIRE(gen.next());\n  BOOST_REQUIRE_EQUAL(gen[b], 1337);\n}\n\nBOOST_AUTO_TEST_CASE(neg_t2) {\n  Variable<bool> a;\n  Variable<int> b;\n  Variable<int> c;\n  Variable<int> d;\n  Generator gen(dist(a, distribution<bool>::create(0.5)));\n  gen(b == 1337 && c == 42);\n  gen(if_then_else(a, d == -b, d == -c));\n\n  for (int i = 0; i < 50; ++i) {\n    BOOST_REQUIRE(gen.next());\n    if (gen[a])\n      BOOST_REQUIRE_EQUAL(gen[d], -1337);\n    else\n      BOOST_REQUIRE_EQUAL(gen[d], -42);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(complement_t1) {\n  Variable<int> a;\n  Variable<int> b;\n  Generator gen(a == 0);\n\n  BOOST_REQUIRE(gen.next());\n  BOOST_REQUIRE_EQUAL(gen[a], 0);\n  gen(b == ~a);\n\n  BOOST_REQUIRE(gen.next());\n  BOOST_REQUIRE_EQUAL(gen[b], -1);\n}\n\nBOOST_AUTO_TEST_CASE(bitwise_and_t1) {\n  Variable<unsigned int> a;\n  Variable<unsigned int> b;\n  Variable<unsigned int> c;\n  Generator gen(a == 42);\n  gen(b == 1337);\n\n  BOOST_REQUIRE(gen.next());\n  gen(c == (a & b));\n\n  BOOST_REQUIRE(gen.next());\n  BOOST_REQUIRE_EQUAL(gen[c], 40);\n}\n\nBOOST_AUTO_TEST_CASE(bitwise_or_t1) {\n  Variable<unsigned int> a;\n  Variable<unsigned int> b;\n  Variable<unsigned int> c;\n  Generator gen(a == 42);\n  gen(b == 1337);\n\n  BOOST_REQUIRE(gen.next());\n  gen(c == (a | b));\n\n  BOOST_REQUIRE(gen.next());\n  BOOST_REQUIRE_EQUAL(gen[c], 1339);\n}\n\nBOOST_AUTO_TEST_CASE(bitwise_xor_t1) {\n  Variable<unsigned int> a;\n  Variable<unsigned int> b;\n  Variable<unsigned int> c;\n  Generator gen(a == 65535);\n  gen(b == 4080);\n\n  BOOST_REQUIRE(gen.next());\n  gen(c == (a ^ b));\n\n  BOOST_REQUIRE(gen.next());\n  BOOST_REQUIRE_EQUAL(gen[c], 61455);\n}\n\nBOOST_AUTO_TEST_CASE(shiftleft) {\n  VariableDefaultSolver::bypass_constraint_analysis = true;\n\n  Variable<unsigned> a;\n  Variable<unsigned> b;\n  Variable<unsigned> c;\n\n  Generator gen;\n  gen(a < 256u)(b < (unsigned)(sizeof(unsigned) * 8u))(c == (a << b));\n\n  int count = 0;\n  int max_count = 200;\n  while (gen.next() && ++count < max_count) {\n    unsigned av = gen[a];\n    unsigned bv = gen[b];\n    unsigned r = av << bv;\n\n    BOOST_REQUIRE_EQUAL(r, gen[c]);\n\n    gen(a != gen[a] || b != gen[b]);\n  }\n\n  VariableDefaultSolver::bypass_constraint_analysis = false;\n  BOOST_REQUIRE_EQUAL(count, max_count);\n}\n\nBOOST_AUTO_TEST_CASE(shiftright) {\n  VariableDefaultSolver::bypass_constraint_analysis = true;\n\n  Variable<unsigned> a;\n  Variable<unsigned> b;\n  Variable<unsigned> c;\n\n  Generator gen;\n  gen(a > 256u)(b < 8u)(c == (a >> b));\n\n  int count = 0;\n  int max_count = 300;\n  while (gen.next() && ++count < max_count) {\n    unsigned av = gen[a];\n    unsigned bv = gen[b];\n    unsigned r = av >> bv;\n\n    BOOST_REQUIRE_EQUAL(r, gen[c]);\n\n    gen(a != gen[a] || b != gen[b]);\n  }\n\n  VariableDefaultSolver::bypass_constraint_analysis = false;\n  BOOST_REQUIRE_EQUAL(count, max_count);\n}\n\nBOOST_AUTO_TEST_CASE(plus_minus) {\n  VariableDefaultSolver::bypass_constraint_analysis = true;\n\n  Variable<unsigned int> a;\n  Variable<unsigned int> b;\n  Variable<unsigned int> q;\n  Variable<unsigned int> r;\n\n  Generator gen;\n  gen(b != 0u)(b < a)(q == a + b)(r == a - b);\n\n  unsigned int cnt = 0u;\n  while (gen.next() && cnt < 300) {\n    BOOST_REQUIRE_EQUAL(gen[a] + gen[b], gen[q]);\n    BOOST_REQUIRE_EQUAL(gen[a] - gen[b], gen[r]);\n\n    gen(a != gen[a] || b != gen[b]);\n    std::cout << \"#\" << cnt++ << \": result: a=\" << gen[a] << \", b=\" << gen[b] << \", q=\" << gen[q] << \", r=\" << gen[r]\n              << \"\\n\" << std::endl;\n  }\n\n  VariableDefaultSolver::bypass_constraint_analysis = false;\n}\n\nBOOST_AUTO_TEST_CASE(mult_mod) {\n  Variable<int> a;\n  Variable<int> b;\n\n  Generator gen;\n  gen(-3 <= a && a <= 3)(-3 <= b && b <= 3)(a * b % 6 == 0);\n\n  int cnt = 0;\n  for (int i = -3; i <= 3; i++)\n    for (int j = -3; j <= 3; j++)\n      if (i * j % 6 == 0) cnt++;\n\n  int cnt1 = 0;\n  while (gen.next()) {\n    cnt1++;\n    BOOST_REQUIRE_EQUAL(gen[a] * gen[b] % 6, 0);\n    gen(a != gen[a] || b != gen[b]);\n    std::cout << \"result: a1=\" << gen[a] << \", b1=\" << gen[b] << \"\\n\" << std::endl;\n    BOOST_REQUIRE_LE(cnt1, cnt);\n  }\n\n  BOOST_REQUIRE_EQUAL(cnt, cnt1);\n}\n\nBOOST_AUTO_TEST_CASE(divide) {\n  VariableDefaultSolver::bypass_constraint_analysis = true;\n\n  Variable<unsigned char> a;\n  Variable<unsigned char> b;\n  Variable<unsigned char> q;\n  Variable<unsigned char> r;\n\n  Generator gen;\n  gen(b != (unsigned char)0u)(a < (unsigned char)16u)(b < (unsigned char)16u)(q == a / b)(r == a % b);\n\n  while (gen.next()) {\n    BOOST_REQUIRE_EQUAL(gen[a] / gen[b], gen[q]);\n    BOOST_REQUIRE_EQUAL(gen[a] % gen[b], gen[r]);\n\n    gen(a != gen[a] || b != gen[b]);\n    std::cout << \"result: a=\" << gen[a] << \", b=\" << gen[b] << \", q=\" << gen[q] << \", r=\" << gen[r] << \"\\n\"\n              << std::endl;\n  }\n\n  VariableDefaultSolver::bypass_constraint_analysis = false;\n}\n\nBOOST_AUTO_TEST_CASE(element_inside_set) {\n  std::set<unsigned> s;\n  s.insert(1);\n  s.insert(7);\n  s.insert(9);\n\n  Variable<unsigned> x;\n\n  Generator gen;\n  gen(inside(x, s));\n\n  BOOST_REQUIRE(gen.next());\n  BOOST_REQUIRE(s.find(gen[x]) != s.end());\n\n  unsigned first = gen[x];\n  gen(x != first);\n\n  BOOST_REQUIRE(gen.next());\n  BOOST_REQUIRE(s.find(gen[x]) != s.end());\n\n  unsigned second = gen[x];\n  BOOST_REQUIRE_NE(first, second);\n  gen(x != second);\n\n  BOOST_REQUIRE(gen.next());\n  BOOST_REQUIRE(s.find(gen[x]) != s.end());\n\n  unsigned third = gen[x];\n  BOOST_REQUIRE_NE(third, second);\n  BOOST_REQUIRE_NE(first, third);\n  gen(x != third);\n\n  BOOST_REQUIRE(!gen.next());\n}\n\nBOOST_AUTO_TEST_CASE(element_inside_vec) {\n  std::vector<unsigned> v;\n  v.push_back(1);\n  v.push_back(7);\n  v.push_back(9);\n\n  Variable<unsigned> x;\n\n  Generator gen;\n  gen(inside(x, v));\n\n  BOOST_REQUIRE(gen.next());\n  BOOST_REQUIRE(find(v.begin(), v.end(), gen[x]) != v.end());\n\n  unsigned first = gen[x];\n  gen(x != first);\n\n  BOOST_REQUIRE(gen.next());\n  BOOST_REQUIRE(find(v.begin(), v.end(), gen[x]) != v.end());\n\n  unsigned second = gen[x];\n  BOOST_REQUIRE_NE(first, second);\n  gen(x != second);\n\n  BOOST_REQUIRE(gen.next());\n  BOOST_REQUIRE(find(v.begin(), v.end(), gen[x]) != v.end());\n\n  unsigned third = gen[x];\n  BOOST_REQUIRE_NE(third, second);\n  BOOST_REQUIRE_NE(first, third);\n  gen(x != third);\n\n  BOOST_REQUIRE(!gen.next());\n}\n\nBOOST_AUTO_TEST_CASE(element_inside_array) {\n  unsigned a[3];\n  a[0] = 1;\n  a[1] = 7;\n  a[2] = 9;\n\n  Variable<unsigned> x;\n  Generator gen;\n  gen(inside(x, a));\n\n  BOOST_REQUIRE(gen.next());\n\n  unsigned first = gen[x];\n  gen(x != first);\n\n  BOOST_REQUIRE(gen.next());\n\n  unsigned second = gen[x];\n  BOOST_REQUIRE_NE(first, second);\n  gen(x != second);\n\n  BOOST_REQUIRE(gen.next());\n  unsigned third = gen[x];\n  BOOST_REQUIRE_NE(third, second);\n  BOOST_REQUIRE_NE(first, third);\n  gen(x != third);\n\n  BOOST_REQUIRE(!gen.next());\n}\n\nBOOST_AUTO_TEST_CASE(element_inside_list) {\n  std::list<unsigned> l;\n  l.push_back(1);\n  l.push_back(7);\n  l.push_back(9);\n\n  Variable<unsigned> x;\n\n  Generator gen;\n  gen(inside(x, l));\n\n  BOOST_REQUIRE(gen.next());\n  BOOST_REQUIRE(find(l.begin(), l.end(), gen[x]) != l.end());\n\n  unsigned first = gen[x];\n  gen(x != first);\n\n  BOOST_REQUIRE(gen.next());\n  BOOST_REQUIRE(find(l.begin(), l.end(), gen[x]) != l.end());\n\n  unsigned second = gen[x];\n  BOOST_REQUIRE_NE(first, second);\n  gen(x != second);\n\n  BOOST_REQUIRE(gen.next());\n  BOOST_REQUIRE(find(l.begin(), l.end(), gen[x]) != l.end());\n\n  unsigned third = gen[x];\n  BOOST_REQUIRE_NE(third, second);\n  BOOST_REQUIRE_NE(first, third);\n  gen(x != third);\n\n  BOOST_REQUIRE(!gen.next());\n}\n\nBOOST_AUTO_TEST_CASE(element_not_inside) {\n  {\n    std::set<unsigned> s;\n\n    Variable<unsigned> x;\n\n    Generator gen;\n    gen(inside(x, s));\n\n    BOOST_REQUIRE(!gen.next());\n  }\n  {\n    std::vector<unsigned> v;\n\n    Variable<unsigned> x;\n\n    Generator gen;\n    gen(inside(x, v));\n\n    BOOST_REQUIRE(!gen.next());\n  }\n  {\n    std::vector<unsigned> l;\n\n    Variable<unsigned> x;\n\n    Generator gen;\n    gen(inside(x, l));\n\n    BOOST_REQUIRE(!gen.next());\n  }\n}\n\nBOOST_AUTO_TEST_CASE(if_then_else_t1) {\n  unsigned int a;\n  Variable<unsigned int> b;\n  Generator gen;\n\n  gen(if_then_else(reference(a)<5, b> 0 && b <= 50, b > 50 && b <= 100));\n\n  for (a = 0; a < 10; ++a) {\n    BOOST_REQUIRE(gen.next());\n    std::cout << \"a =\" << a << \", b = \" << gen[b] << std::endl;\n    if (a < 5) {\n      BOOST_REQUIRE_GT(gen[b], 0);\n      BOOST_REQUIRE_LE(gen[b], 50);\n    } else {\n      BOOST_REQUIRE_GT(gen[b], 50);\n      BOOST_REQUIRE_LE(gen[b], 100);\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE(if_then_t1) {\n  unsigned int a;\n  Variable<unsigned int> b;\n  Generator gen;\n\n  gen(if_then(reference(a)<5, b> 0 && b <= 100));\n  gen(if_then(reference(a) >= 5, b > 100 && b <= 1000));\n\n  for (a = 0; a < 10; ++a) {\n    BOOST_REQUIRE(gen.next());\n    std::cout << \"a =\" << a << \", b = \" << gen[b] << std::endl;\n    if (a < 5) {\n      BOOST_REQUIRE_GT(gen[b], 0);\n      BOOST_REQUIRE_LE(gen[b], 100);\n    } else {\n      BOOST_REQUIRE_GT(gen[b], 100);\n      BOOST_REQUIRE_LE(gen[b], 1000);\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE(bitslice_t) {\n  Variable<short> x;\n\n  Generator gen;\n  gen(bitslice(10, 3, x) == 0xFF);\n  BOOST_REQUIRE(gen.next());\n  BOOST_REQUIRE_EQUAL((gen[x] >> 3) & 0xFF, 0xFF);\n\n  BOOST_REQUIRE_THROW(gen(bitslice(3, 10, x) == 0xFF), std::runtime_error);\n  BOOST_REQUIRE_THROW(gen(bitslice(16, 3, x) == 0xFF), std::runtime_error);\n}\n\nBOOST_AUTO_TEST_SUITE_END()  // Context\n", "meta": {"hexsha": "4de95ec6e2a771316d0eb1068b497f6c300c5f5b", "size": 13596, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/core/test_Operators.cpp", "max_stars_repo_name": "quadric-io/crave", "max_stars_repo_head_hexsha": "8096d8b151cbe0d2ba437657f42d8bb0e05f5436", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2015-05-11T02:38:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T07:31:26.000Z", "max_issues_repo_path": "tests/core/test_Operators.cpp", "max_issues_repo_name": "quadric-io/crave", "max_issues_repo_head_hexsha": "8096d8b151cbe0d2ba437657f42d8bb0e05f5436", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2018-06-08T14:44:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-19T16:07:21.000Z", "max_forks_repo_path": "tests/core/test_Operators.cpp", "max_forks_repo_name": "quadric-io/crave", "max_forks_repo_head_hexsha": "8096d8b151cbe0d2ba437657f42d8bb0e05f5436", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2019-05-29T21:40:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-01T09:31:15.000Z", "avg_line_length": 21.8937198068, "max_line_length": 117, "alphanum_fraction": 0.6262871433, "num_tokens": 3885, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.4879216104608501}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2007-2015 Barend Gehrels, Amsterdam, the Netherlands.\n// Copyright (c) 2013-2015 Adam Wulkiewicz, Lodz, Poland.\n\n// This file was modified by Oracle on 2014, 2015.\n// Modifications copyright (c) 2014-2015 Oracle and/or its affiliates.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\n\n#include \"test_within.hpp\"\n\n\n#include <boost/geometry/geometries/geometries.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/multi_point.hpp>\n#include <boost/geometry/geometries/multi_linestring.hpp>\n#include <boost/geometry/geometries/multi_polygon.hpp>\n\ntemplate <typename P>\nvoid test_all()\n{\n    typedef bg::model::box<P> box_type;\n\n    test_geometry<P, box_type>(\"POINT(1 1)\", \"BOX(0 0,2 2)\", true);\n    test_geometry<P, box_type>(\"POINT(0 0)\", \"BOX(0 0,2 2)\", false);\n    test_geometry<P, box_type>(\"POINT(2 2)\", \"BOX(0 0,2 2)\", false);\n    test_geometry<P, box_type>(\"POINT(0 1)\", \"BOX(0 0,2 2)\", false);\n    test_geometry<P, box_type>(\"POINT(1 0)\", \"BOX(0 0,2 2)\", false);\n\n    test_geometry<box_type, box_type>(\"BOX(1 1,2 2)\", \"BOX(0 0,3 3)\", true);\n    test_geometry<box_type, box_type>(\"BOX(0 0,3 3)\", \"BOX(1 1,2 2)\", false);\n\n    test_geometry<box_type, box_type>(\"BOX(1 1,3 3)\", \"BOX(0 0,3 3)\", true);\n    test_geometry<box_type, box_type>(\"BOX(3 1,3 3)\", \"BOX(0 0,3 3)\", false);\n\n    /*\n    test_within_code<P, box_type>(\"POINT(1 1)\", \"BOX(0 0,2 2)\", 1);\n    test_within_code<P, box_type>(\"POINT(1 0)\", \"BOX(0 0,2 2)\", 0);\n    test_within_code<P, box_type>(\"POINT(0 1)\", \"BOX(0 0,2 2)\", 0);\n    test_within_code<P, box_type>(\"POINT(0 3)\", \"BOX(0 0,2 2)\", -1);\n    test_within_code<P, box_type>(\"POINT(3 3)\", \"BOX(0 0,2 2)\", -1);\n\n    test_within_code<box_type, box_type>(\"BOX(1 1,2 2)\", \"BOX(0 0,3 3)\", 1);\n    test_within_code<box_type, box_type>(\"BOX(0 1,2 2)\", \"BOX(0 0,3 3)\", 0);\n    test_within_code<box_type, box_type>(\"BOX(1 0,2 2)\", \"BOX(0 0,3 3)\", 0);\n    test_within_code<box_type, box_type>(\"BOX(1 1,2 3)\", \"BOX(0 0,3 3)\", 0);\n    test_within_code<box_type, box_type>(\"BOX(1 1,3 2)\", \"BOX(0 0,3 3)\", 0);\n    test_within_code<box_type, box_type>(\"BOX(1 1,3 4)\", \"BOX(0 0,3 3)\", -1);\n    */\n}\n\ntemplate <typename Point>\nvoid test_spherical()\n{\n    // Test spherical boxes\n    // See also http://www.gcmap.com/mapui?P=1E45N-19E45N-19E55N-1E55N-1E45N,10E55.1N,10E45.1N\n    bg::model::box<Point> box;\n    bg::read_wkt(\"POLYGON((1 45,19 55))\", box);\n    BOOST_CHECK_EQUAL(bg::within(Point(10, 55.1), box), true);\n    BOOST_CHECK_EQUAL(bg::within(Point(10, 55.2), box), true);\n    BOOST_CHECK_EQUAL(bg::within(Point(10, 55.3), box), true);\n    BOOST_CHECK_EQUAL(bg::within(Point(10, 55.4), box), false);\n\n    BOOST_CHECK_EQUAL(bg::within(Point(10, 45.1), box), false);\n    BOOST_CHECK_EQUAL(bg::within(Point(10, 45.2), box), false);\n    BOOST_CHECK_EQUAL(bg::within(Point(10, 45.3), box), false);\n    BOOST_CHECK_EQUAL(bg::within(Point(10, 45.4), box), true);\n\n    // Crossing the dateline (Near Tuvalu)\n    // http://www.gcmap.com/mapui?P=178E10S-178W10S-178W6S-178E6S-178E10S,180W5.999S,180E9.999S\n    // http://en.wikipedia.org/wiki/Tuvalu\n\n    bg::model::box<Point> tuvalu(Point(178, -10), Point(-178, -6));\n    BOOST_CHECK_EQUAL(bg::within(Point(180, -8), tuvalu), true);\n    BOOST_CHECK_EQUAL(bg::within(Point(-180, -8), tuvalu), true);\n    BOOST_CHECK_EQUAL(bg::within(Point(180, -5.999), tuvalu), false);\n    BOOST_CHECK_EQUAL(bg::within(Point(180, -10.001), tuvalu), true);\n}\n\nvoid test_3d()\n{\n    typedef boost::geometry::model::point<double, 3, boost::geometry::cs::cartesian> point_type;\n    typedef boost::geometry::model::box<point_type> box_type;\n    box_type box(point_type(0, 0, 0), point_type(4, 4, 4));\n    BOOST_CHECK_EQUAL(bg::within(point_type(2, 2, 2), box), true);\n    BOOST_CHECK_EQUAL(bg::within(point_type(2, 4, 2), box), false);\n    BOOST_CHECK_EQUAL(bg::within(point_type(2, 2, 4), box), false);\n    BOOST_CHECK_EQUAL(bg::within(point_type(2, 2, 5), box), false);\n\n    box_type box2(point_type(2, 2, 2), point_type(3, 3, 3));\n    BOOST_CHECK_EQUAL(bg::within(box2, box), true);\n\n}\n\ntemplate <typename P1, typename P2>\nvoid test_mixed_of()\n{\n    typedef boost::geometry::model::polygon<P1> polygon_type1;\n    typedef boost::geometry::model::polygon<P2> polygon_type2;\n    typedef boost::geometry::model::box<P1> box_type1;\n    typedef boost::geometry::model::box<P2> box_type2;\n\n    polygon_type1 poly1;\n    polygon_type2 poly2;\n    boost::geometry::read_wkt(\"POLYGON((0 0,0 5,5 5,5 0,0 0))\", poly1);\n    boost::geometry::read_wkt(\"POLYGON((0 0,0 5,5 5,5 0,0 0))\", poly2);\n\n    box_type1 box1(P1(1, 1), P1(4, 4));\n    box_type2 box2(P2(0, 0), P2(5, 5));\n    P1 p1(3, 3);\n    P2 p2(3, 3);\n\n    BOOST_CHECK_EQUAL(bg::within(p1, poly2), true);\n    BOOST_CHECK_EQUAL(bg::within(p2, poly1), true);\n    BOOST_CHECK_EQUAL(bg::within(p2, box1), true);\n    BOOST_CHECK_EQUAL(bg::within(p1, box2), true);\n    BOOST_CHECK_EQUAL(bg::within(box1, box2), true);\n    BOOST_CHECK_EQUAL(bg::within(box2, box1), false);\n}\n\n\nvoid test_mixed()\n{\n    // Mixing point types and coordinate types\n    test_mixed_of\n        <\n            boost::geometry::model::d2::point_xy<double>,\n            boost::geometry::model::point<double, 2, boost::geometry::cs::cartesian>\n        >();\n    test_mixed_of\n        <\n            boost::geometry::model::d2::point_xy<float>,\n            boost::geometry::model::point<double, 2, boost::geometry::cs::cartesian>\n        >();\n    test_mixed_of\n        <\n            boost::geometry::model::d2::point_xy<int>,\n            boost::geometry::model::d2::point_xy<double>\n        >();\n}\n\nvoid test_strategy()\n{\n    // Test by explicitly specifying a strategy\n    typedef bg::model::d2::point_xy<double> point_type;\n    typedef bg::model::box<point_type> box_type;\n    point_type p(3, 3);\n    box_type b(point_type(0, 0), point_type(5, 5));\n    box_type b0(point_type(0, 0), point_type(5, 0));\n\n    bool r = bg::within(p, b,\n        bg::strategy::within::point_in_box<point_type, box_type>());\n    BOOST_CHECK_EQUAL(r, true);\n\n    r = bg::within(b, b,\n        bg::strategy::within::box_in_box<box_type, box_type>());\n    BOOST_CHECK_EQUAL(r, true);\n\n    r = bg::within(b0, b0,\n        bg::strategy::within::box_in_box<box_type, box_type>());\n    BOOST_CHECK_EQUAL(r, false);\n\n    r = bg::within(p, b,\n        bg::strategy::within::point_in_box_by_side<point_type, box_type>());\n    BOOST_CHECK_EQUAL(r, true);\n}\n\n\nint test_main( int , char* [] )\n{\n    test_all<bg::model::d2::point_xy<int> >();\n    test_all<bg::model::d2::point_xy<double> >();\n\n    test_spherical<bg::model::point<double, 2, bg::cs::spherical_equatorial<bg::degree> > >();\n\n    test_mixed();\n    test_3d();\n    test_strategy();\n\n\n#if defined(HAVE_TTMATH)\n    test_all<bg::model::d2::point_xy<ttmath_big> >();\n    test_spherical<bg::model::point<ttmath_big, 2, bg::cs::spherical_equatorial<bg::degree> > >();\n#endif\n\n    return 0;\n}\n", "meta": {"hexsha": "c8999e4db5b1c20ac95ab32d6723239b999cd148", "size": 7163, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/test/algorithms/relational_operations/within/within.cpp", "max_stars_repo_name": "fed12345/boost_1_59_0", "max_stars_repo_head_hexsha": "2a8cea7df425ffc4252ac641c5359c5dc56cf284", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2017-06-17T02:54:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-30T04:59:42.000Z", "max_issues_repo_path": "libs/geometry/test/algorithms/relational_operations/within/within.cpp", "max_issues_repo_name": "fed12345/boost_1_59_0", "max_issues_repo_head_hexsha": "2a8cea7df425ffc4252ac641c5359c5dc56cf284", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-02-28T14:47:07.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-28T14:47:07.000Z", "max_forks_repo_path": "libs/geometry/test/algorithms/relational_operations/within/within.cpp", "max_forks_repo_name": "fed12345/boost_1_59_0", "max_forks_repo_head_hexsha": "2a8cea7df425ffc4252ac641c5359c5dc56cf284", "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": 37.1139896373, "max_line_length": 98, "alphanum_fraction": 0.6512634371, "num_tokens": 2398, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872243177518, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.48792160761855946}}
{"text": "#pragma once\n\n#include <opencv2/core/core.hpp>\n#include <Eigen/Core>\n\n#include \"../../geometry/LineSegment/LineSegment2/LineSegment2i/linesegment2i.hh\"\n#include \"../linefinder.hh\"\n\nnamespace bold\n{\n  template<typename> class Setting;\n\n  class MaskWalkLineFinder : public LineFinder\n  {\n  public:\n    MaskWalkLineFinder();\n\n    void walkLine(Eigen::Vector2i const& start, float theta, bool forward, std::function<bool(int/*x*/,int/*y*/)> const& callback, uchar width = 1);\n\n    std::vector<LineSegment2i> findLineSegments(std::vector<Eigen::Vector2i>& lineDots) override;\n\n  private:\n    void rebuild();\n\n    // configuration options\n    Setting<double>* d_drThreshold;\n    Setting<double>* d_dtThresholdDegs;\n    Setting<int>* d_voteThreshold;\n    Setting<int>* d_minLineLength;\n    Setting<int>* d_maxLineGap;\n    Setting<int>* d_maxLineSegmentCount;\n\n    // constant\n    const int d_imageWidth;\n    const int d_imageHeight;\n\n    // cached\n    cv::Mat d_mask;\n    cv::Mat d_accumulator;\n\n    // calculated\n    int d_tSteps;\n    int d_rSteps;\n    std::vector<float> d_trigTable;\n  };\n}\n", "meta": {"hexsha": "e6ffe88b89e58708a7156172329da6dbc7830e1e", "size": 1086, "ext": "hh", "lang": "C++", "max_stars_repo_path": "LineFinder/MaskWalkLineFinder/maskwalklinefinder.hh", "max_stars_repo_name": "drewnoakes/bold-humanoid", "max_stars_repo_head_hexsha": "6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "LineFinder/MaskWalkLineFinder/maskwalklinefinder.hh", "max_issues_repo_name": "drewnoakes/bold-humanoid", "max_issues_repo_head_hexsha": "6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LineFinder/MaskWalkLineFinder/maskwalklinefinder.hh", "max_forks_repo_name": "drewnoakes/bold-humanoid", "max_forks_repo_head_hexsha": "6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335", "max_forks_repo_licenses": ["Apache-2.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.1063829787, "max_line_length": 148, "alphanum_fraction": 0.697053407, "num_tokens": 282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.6513548714339145, "lm_q1q2_score": 0.48792160539113266}}
{"text": "//  Copyright (C) Toon Knapen 2003\n//\n//  Permission to copy, use, modify, sell and\n//  distribute this software is granted provided this copyright notice appears\n//  in all copies. This software is provided \"as is\" without express or implied\n//  warranty, and with no claim as to its suitability for any purpose.\n\n#ifndef BOOST_NUMERIC_BINDINGS_BLAS_BLAS1_OVERLOADS_HPP\n#define BOOST_NUMERIC_BINDINGS_BLAS_BLAS1_OVERLOADS_HPP\n\n#include <boost/numeric/bindings/blas/blas.h>\n#include <boost/numeric/bindings/traits/type.hpp>\n#include <boost/numeric/bindings/traits/type_traits.hpp>\n\nnamespace boost { namespace numeric { namespace bindings { namespace blas { namespace detail {\n\n  using namespace boost::numeric::bindings::traits ;\n\n  // x *= alpha \n  inline void scal(const int& n, const float&     alpha, float*     x, const int& incx) { BLAS_SSCAL( &n,              &alpha,                x  , &incx ) ; } \n  inline void scal(const int& n, const double&    alpha, double*    x, const int& incx) { BLAS_DSCAL( &n,              &alpha,                x  , &incx ) ; }\n  inline void scal(const int& n, const complex_f& alpha, complex_f* x, const int& incx) { BLAS_CSCAL( &n, complex_ptr( &alpha ), complex_ptr( x ), &incx ) ; }\n  inline void scal(const int& n, const complex_d& alpha, complex_d* x, const int& incx) { BLAS_ZSCAL( &n, complex_ptr( &alpha ), complex_ptr( x ), &incx ) ; }\n\n  // y += alpha * x \n  inline void axpy(const int& n, const float    & alpha, const float    * x, const int& incx, float    * y, const int& incy) { BLAS_SAXPY( &n,            &alpha  ,            x  , &incx,            y  , &incy ) ; }\n  inline void axpy(const int& n, const double   & alpha, const double   * x, const int& incx, double   * y, const int& incy) { BLAS_DAXPY( &n,            &alpha  ,            x  , &incx,            y  , &incy ) ; }\n  inline void axpy(const int& n, const complex_f& alpha, const complex_f* x, const int& incx, complex_f* y, const int& incy) { BLAS_CAXPY( &n, complex_ptr( &alpha ), complex_ptr( x ), &incx, complex_ptr( y ), &incy ) ; }\n  inline void axpy(const int& n, const complex_d& alpha, const complex_d* x, const int& incx, complex_d* y, const int& incy) { BLAS_ZAXPY( &n, complex_ptr( &alpha ), complex_ptr( x ), &incx, complex_ptr( y ), &incy ) ; }\n\n  // x^T . y \n  inline float  dot(const int& n, const float * x, const int& incx, const float * y, const int& incy) { return BLAS_SDOT( &n, x, &incx, y, &incy ) ; }\n  inline double dot(const int& n, const double* x, const int& incx, const double* y, const int& incy) { return BLAS_DDOT( &n, x, &incx, y, &incy ) ; }\n\n  // x^T . y\n  inline void dotu(complex_f& ret, const int& n, const complex_f* x, const int& incx, const complex_f* y, const int& incy) { BLAS_CDOTU( complex_ptr( &ret ), &n, complex_ptr( x ), &incx, complex_ptr( y ), &incy ) ; }\n  inline void dotu(complex_d& ret, const int& n, const complex_d* x, const int& incx, const complex_d* y, const int& incy) { BLAS_ZDOTU( complex_ptr( &ret ), &n, complex_ptr( x ), &incx, complex_ptr( y ), &incy ) ; }\n\n  // x^H . y\n  inline void dotc(complex_f& ret, const int& n, const complex_f* x, const int& incx, const complex_f* y, const int& incy) { BLAS_CDOTC( complex_ptr( &ret ), &n, complex_ptr( x ), &incx, complex_ptr( y ), &incy ) ; }\n  inline void dotc(complex_d& ret, const int& n, const complex_d* x, const int& incx, const complex_d* y, const int& incy) { BLAS_ZDOTC( complex_ptr( &ret ), &n, complex_ptr( x ), &incx, complex_ptr( y ), &incy ) ; }\n\n  // euclidean norm\n  inline float  nrm2(const int& n, const float*   x, const int& incx) { return BLAS_SNRM2( &n, x, &incx ) ; }\n  inline double nrm2(const int& n, const double*  x, const int& incx) { return BLAS_DNRM2( &n, x, &incx ) ; }\n  inline float  nrm2(const int& n, const complex_f*   x, const int& incx) { return BLAS_SCNRM2( &n, complex_ptr(x), &incx ) ; }\n  inline double nrm2(const int& n, const complex_d*  x, const int& incx) { return BLAS_DZNRM2( &n, complex_ptr(x), &incx ) ; }\n  \n  // 1-norm\n  inline float  asum(const int& n, const float*   x, const int& incx) { return BLAS_SASUM( &n, x, &incx ) ; }\n  inline double asum(const int& n, const double*  x, const int& incx) { return BLAS_DASUM( &n, x, &incx ) ; }\n  inline float  asum(const int& n, const complex_f*   x, const int& incx) { return BLAS_SCASUM( &n, complex_ptr(x), &incx ) ; }\n  inline double asum(const int& n, const complex_d*  x, const int& incx) { return BLAS_DZASUM( &n, complex_ptr(x), &incx ) ; }\n  \n}}}}}\n\n#endif // BOOST_NUMERIC_BINDINGS_BLAS_BLAS1_OVERLOADS_HPP\n\n", "meta": {"hexsha": "883d824c782eddb3c65fbe786b10d7ecef3667e6", "size": 4548, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "applications/mkl_solvers_application/external_includes/boost/numeric/bindings/blas/blas1_overloads.hpp", "max_stars_repo_name": "jiaqiwang969/Kratos-test", "max_stars_repo_head_hexsha": "ed082abc163e7b627f110a1ae1da465f52f48348", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "applications/mkl_solvers_application/external_includes/boost/numeric/bindings/blas/blas1_overloads.hpp", "max_issues_repo_name": "jiaqiwang969/Kratos-test", "max_issues_repo_head_hexsha": "ed082abc163e7b627f110a1ae1da465f52f48348", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "applications/mkl_solvers_application/external_includes/boost/numeric/bindings/blas/blas1_overloads.hpp", "max_forks_repo_name": "jiaqiwang969/Kratos-test", "max_forks_repo_head_hexsha": "ed082abc163e7b627f110a1ae1da465f52f48348", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 77.0847457627, "max_line_length": 220, "alphanum_fraction": 0.6490765172, "num_tokens": 1501, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.6513548714339145, "lm_q1q2_score": 0.4879216053911326}}
{"text": "#include <sparse.h>\n\n#include <sparse_fill.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n\nBOOST_AUTO_TEST_SUITE(SPARSE);\n\nBOOST_AUTO_TEST_CASE(fale_transpose_test)\n{  \n  typedef sparse::Block<4,6,float> block_type;\n\ttypedef sparse::TwoColumnMatrix<block_type>  tcm_type;\n\ttypedef sparse::CompressedRowMatrix<block_type>   crm_type;\n  \n\ttcm_type J(1, 2, 2);\n\tblock_type b1;\n\tblock_type b2;\n  \n  sparse::fill(b1, 1.0f);\n  sparse::fill(b2, 2.0f);\n\tJ(0,0) = b1;\n\tJ(0,1) = b2;\n  \n\tcrm_type JT;\n  sparse::fake_transpose(J, JT);\n\tBOOST_CHECK( JT.size() == 2         );\n\tBOOST_CHECK( JT.nrows() == J.ncols());\n\tBOOST_CHECK( JT.ncols() == J.nrows());\n\tBOOST_CHECK( JT(0,0) == J(0,0)      );\n  BOOST_CHECK( JT(1,0) == J(0,1)      );\n  \n\tJ.resize(2,4,4);\n\tblock_type b3;\n  block_type b4;\n  \n  sparse::fill(b3, 3.0f);\n  sparse::fill(b4, 4.0f);\n  \n  J(1,0) = b1;\n  J(1,3) = b2;\n  sparse::fake_transpose(J, JT);\n  \n  BOOST_CHECK(JT.size() == 4);\n  BOOST_CHECK(JT.nrows() == J.ncols());\n  BOOST_CHECK(JT.ncols() == J.nrows());\n  BOOST_CHECK(JT(0,0) == J(0,0));\n  BOOST_CHECK(JT(1,0) == J(0,1));\n  BOOST_CHECK(JT(0,1) == J(1,0));\n  BOOST_CHECK(JT(3,1) == J(1,3));\n  \n}\n\nBOOST_AUTO_TEST_SUITE_END();\n\n", "meta": {"hexsha": "1c2c4a22afde3035b4776897af345c794a37bde7", "size": 1343, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/FOUNDATION/SPARSE/unit_tests/sparse_fake_transpose/sparse_fake_transpose.cpp", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-11-27T09:44:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-13T00:24:21.000Z", "max_issues_repo_path": "PROX/FOUNDATION/SPARSE/unit_tests/sparse_fake_transpose/sparse_fake_transpose.cpp", "max_issues_repo_name": "erleben/matchstick", "max_issues_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_issues_repo_licenses": ["MIT"], "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/FOUNDATION/SPARSE/unit_tests/sparse_fake_transpose/sparse_fake_transpose.cpp", "max_forks_repo_name": "erleben/matchstick", "max_forks_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_forks_repo_licenses": ["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.7627118644, "max_line_length": 60, "alphanum_fraction": 0.6455696203, "num_tokens": 471, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.48792160032141507}}
{"text": "#ifndef STAN_MATH_PRIM_SCAL_FUN_FDIM_HPP\n#define STAN_MATH_PRIM_SCAL_FUN_FDIM_HPP\n\n#include <stan/math/prim/scal/fun/is_nan.hpp>\n#include <boost/math/tools/promotion.hpp>\n#include <limits>\n\nnamespace stan {\n  namespace math {\n\n    /**\n     * Return the positive difference of the specified values (C++11).\n     *\n     * The function is defined by\n     *\n     * <code>fdim(x, y) = (x > y) ? (x - y) : 0</code>.\n     *\n     * @param x First value.\n     * @param y Second value.\n     * @return max(x- y, 0)\n     */\n    template <typename T1, typename T2>\n    inline typename boost::math::tools::promote_args<T1, T2>::type\n    fdim(T1 x, T2 y) {\n      typedef typename boost::math::tools::promote_args<T1, T2>::type return_t;\n      using std::numeric_limits;\n      if (is_nan(x) || is_nan(y))\n        return numeric_limits<return_t>::quiet_NaN();\n      return (x <= y) ? 0 : x - y;\n    }\n\n  }\n}\n#endif\n", "meta": {"hexsha": "6ac543561ca243780f989b52e5d366c720c566c3", "size": 898, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/scal/fun/fdim.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/prim/scal/fun/fdim.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/prim/scal/fun/fdim.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": 25.6571428571, "max_line_length": 79, "alphanum_fraction": 0.6158129176, "num_tokens": 268, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872019117031, "lm_q2_score": 0.6513548714339145, "lm_q1q2_score": 0.4879215980939881}}
{"text": "/*\n * Copyright (c) 2015 Claus Christmann <hcc |\u00e4| gatech.edu>.  \n *   \n * Licensed under the Apache Lice*nse, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 <Eigen/Geometry>\n#include <Eigen/Dense>\n\n#include <iostream>\n#include <cmath>\n\n\n#include \"amg.hpp\"\n\nusing namespace Eigen;\n\n\nint main(int argc, char **argv) {\n  \n  using namespace AMG;\n    \n  FrameOfReference* ecef = new FrameOfReference;\n  CoSy::setECEF(ecef);\n  \n  { std::cout << \"\\nWGS 84:\\n\" \n              <<   \"=======\" << std::endl;\n    \n    using namespace AMG::GIS;\n              \n    std::cout\n    << \"WGS84\\n\"\n    << \"|- a     : \" << WGS84::a << \"\\n\"\n    << \"|- finv  : \" << WGS84::finv << \"\\n\"\n    << \"|- omega : \" << WGS84::omega << \"\\n\"\n    << \"|- GM    : \" << WGS84::GM << \"\\n\"\n    << \"|\\n\"\n    << \"|- f     : \" << WGS84::f << \"\\n\"\n    << \"|- b     : \" << WGS84::b << \"\\n\"\n    << \"|- e2    : \" << WGS84::e2 << \"\\n\"\n    << \"|- ep2   : \" << WGS84::ep2 << \"\\n\"\n    << \"|- g0    : \" << WGS84::g0 << \"\\n\"\n    << std::endl;\n    \n  }\n\n  { std::cout << \"\\nGeodetic to ECEF conversions:\\n\" \n              <<   \"=============================\" << std::endl;\n              \n    auto g2e = [] (double lat_deg, double lon_deg, double alt_m)\n    {\n      double x_ecef, y_ecef, z_ecef;\n      \n      GIS::geodetic2ecef(Units::degree2radian(lon_deg),\n                        Units::degree2radian( lat_deg),\n                        alt_m,x_ecef,y_ecef,z_ecef);\n      \n      std::cout << \"Lat,Lon,Alt :\" << lat_deg << \", \"\n                                   << lon_deg << \", \"\n                                   << alt_m   << \"\\n\"\n                << \"X,Y,Z       :\" << x_ecef << \", \" << y_ecef << \", \" << z_ecef \n      << std::endl;\n    };\n    \n    g2e(0,0,0);\n    g2e(0,0,1000);\n    g2e(45,45,0);\n    g2e(90,90,0);\n    g2e(33.772022,-84.396188,0);\n  }\n  \n  { std::cout << \"\\nECEF to Geodetic conversions:\\n\" \n              <<   \"=============================\" << std::endl;\n              \n    auto e2g = [] (double x_ecef, double y_ecef, double z_ecef)\n    {\n      double lat_rad, lon_rad, alt_m;\n      \n      GIS::ecef2geodetic( x_ecef,y_ecef,z_ecef,lon_rad,lat_rad,alt_m);\n      \n      std::cout << \"X,Y,Z       :\" << x_ecef << \", \" << y_ecef << \", \" << z_ecef << \"\\n\"\n                << \"Lat,Lon,Alt :\" << Units::radian2degree(lat_rad) << \", \"\n                                   << Units::radian2degree(lon_rad) << \", \"\n                                   << alt_m \n      << std::endl;\n    };\n    \n\n\n    e2g(518259,-5.28199e+06, 3.52545e+06);\n\n\n  }\n  \n  \n  FrameOfReference* datum = CoSy::newNorthEastDown<Units::degree>( -84.396188, 33.772022 );\n  CoSy::setDatumFrame(datum);\n  datum->outputRelativePositionToParent();\n  std::cout\n    << \"Datum attitude (roll, pitch, yaw; in degrees) : \"\n    << datum->attitude<Units::degree>().transpose() << \"\\n\"\n    << std::endl;\n  \n \n    \n    \n    \n    \n    \n  double x_ecef,y_ecef,z_ecef;\n\n  GIS::geodetic2ecef(Units::degree2radian(-84.396188),\n                      Units::degree2radian( 33.772022),\n                      0,x_ecef,y_ecef,z_ecef);\n  Vector southCorner(x_ecef,y_ecef,z_ecef,CoSy::getECEF());\n  \n  double lat,lon,alt;\n  GIS::ecef2geodetic(southCorner.coords(0),southCorner.coords(1),southCorner.coords(2),\n                     lon,lat,alt);\n  \n  std::cout\n  << \"South Corner in Lat, Lon, Alt  : \" << Units::radian2degree(lat) << \", \"\n                                         << Units::radian2degree(lon) << \", \"\n                                         << alt << \"\\n\"\n  << \"South Corner in ECEF           : \"\n  << southCorner.coords().transpose() << \"\\n\"\n  << \"South Corner in absolute Datum : \"\n  << southCorner.absoluteCoordsIn(datum).transpose() << \"\\n\"\n  << std::endl;\n  \n  std::cout << AMG::GIS::geodeticPositionString(southCorner) << std::endl;\n\n  GIS::geodetic2ecef(Units::degree2radian(-84.396188),\n                      Units::degree2radian( 33.772111),\n                      0,x_ecef,y_ecef,z_ecef);\n  Vector northCorner(x_ecef,y_ecef,z_ecef,CoSy::getECEF());\n  std::cout\n  << \"North Corner in ECEF           : \"\n  << northCorner.coords().transpose() << \"\\n\"\n  << \"North Corner in absolute Datum : \"\n  << northCorner.absoluteCoordsIn(datum).transpose() << \"\\n\"\n  << std::endl;\n  \n  std::cout << AMG::GIS::geodeticPositionString(northCorner) << std::endl;\n\n  Vector delta = northCorner - southCorner;\n\n  std::cout\n  << \"Delta Corner in ECEF           : \"\n  << delta.coords().transpose() << \"\\n\"\n  << \"Delta Corner in relative Datum : \"   \n  << delta.coordsIn(datum).transpose() << \"\\n\"\n  << std::endl;  \n    \n    \n    \n    \n    \n      \n  AMG::RigidBody body;\n  body.outputRelativePositionToParent();\n\n  body.setPositionTo<Units::degree>(-84.396188 , 33.772111 , 0.0 );\n  body.outputRelativePositionToParent();\n  \n  body.rotate<Units::degree>(90.0,0,0);\n  body.outputRelativePositionToParent();\n  \n  std::cout\n    << \"Body Euler attitude (phi, theat, psi):\\n\"\n    << \"(degree) : \" << body.attitude<Units::degree>().transpose() << \"\\n\"\n    << \"(radian) : \" << body.attitude<Units::radian>().transpose() << \"\\n\"\n    << \"(quaternions) : \" << body.attitude().transpose() << \"\\n\"\n    << \"yaw (deg) : \" << body.yaw<Units::degree>() << \"\\n\"\n    << \"pitch (deg) : \" << body.pitch<Units::degree>() << \"\\n\"\n    << \"roll (deg) : \" << body.roll<Units::degree>() << \"\\n\"\n    << std:: endl;\n\n  {  \n    using namespace AMG::GIS;\n    \n    std:: cout << \"isInLeftHalfCircle( 0,   1) = \" << isInLeftHalfCircle(0,    1) << std::endl;  \n    std:: cout << \"isInLeftHalfCircle( 0,   0) = \" << isInLeftHalfCircle(0,    0) << std::endl;  \n    std:: cout << \"isInLeftHalfCircle( 0,  -1) = \" << isInLeftHalfCircle(0,   -1) << std::endl;  \n    std:: cout << \"isInLeftHalfCircle(10, 190) = \" << isInLeftHalfCircle(10, 190) << std::endl;  \n    std:: cout << \"isInLeftHalfCircle(10,-190) = \" << isInLeftHalfCircle(10,-190) << std::endl;  \n    std:: cout << \"isInLeftHalfCircle(10,-170) = \" << isInLeftHalfCircle(10,-170) << std::endl;  \n    std:: cout << \"isInLeftHalfCircle(10,-175) = \" << isInLeftHalfCircle(10,-175) << std::endl;                \n    std:: cout << \"isInLeftHalfCircle(10,-165) = \" << isInLeftHalfCircle(10,-165) << std::endl;                \n    std:: cout << \"isInLeftHalfCircle(10, 370) = \" << isInLeftHalfCircle(10, 370) << std::endl;                \n    std:: cout << \"isInLeftHalfCircle(10, 365) = \" << isInLeftHalfCircle(10, 365) << std::endl;                \n      \n  }\n  \n  { std::cout << \"Testing \\\"headingToCompassPoint()\\\"\"<< std::endl;\n    for( double hdg = 0; hdg <=360; hdg += 5 )\n    { std::cout << hdg << \"\u00b0 => \"<< AMG::GIS::headingToCompassPoint(hdg) << std::endl; }\n  }\n  \n  return 0;\n}\n\n\n", "meta": {"hexsha": "58e4f121a5c218c461879e70934b8be020cea10f", "size": 7102, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "mvsframework/amg", "max_stars_repo_head_hexsha": "fe4d39ccb60e1537a4c95a2a7ecfc88d4d24593a", "max_stars_repo_licenses": ["Apache-2.0"], "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": "mvsframework/amg", "max_issues_repo_head_hexsha": "fe4d39ccb60e1537a4c95a2a7ecfc88d4d24593a", "max_issues_repo_licenses": ["Apache-2.0"], "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": "mvsframework/amg", "max_forks_repo_head_hexsha": "fe4d39ccb60e1537a4c95a2a7ecfc88d4d24593a", "max_forks_repo_licenses": ["Apache-2.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.8796296296, "max_line_length": 111, "alphanum_fraction": 0.5222472543, "num_tokens": 2189, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872019117029, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.4879215930242704}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2016, Sebastian Schlenkrich\n\n*/\n\n/*! \\file mcscriptT.hpp\n    \\brief script payoffs for MC simulation\n    \n*/\n\n\n#ifndef quantlib_templatemcscript_hpp\n#define quantlib_templatemcscript_hpp\n\n\n\n#include <ql/experimental/templatemodels/montecarlo/mcpayoffT.hpp>\n\n\n\n#include <ql/experimental/templatemodels/montecarlo/scripting/flexbisondriver.hpp>\n#include <ql/experimental/templatemodels/montecarlo/scripting/expression.hpp>\n\n#include <ql/time/date.hpp>\n\n#include <boost/regex.hpp>\n\n\n\nnamespace QuantLib {\n\n    template <class DateType, class PassiveType, class ActiveType>\n    class MCScriptT : public MCPayoffT<DateType, PassiveType, ActiveType> {\n    protected:\n        // easy use of templated types\n        typedef MCSimulationT<DateType, PassiveType, ActiveType>        SimulationType;\n        typedef MCPayoffT<DateType, PassiveType, ActiveType>            PayoffType;\n        typedef BasePayoffT<DateType, PassiveType, ActiveType>          MCBase;\n        typedef typename MCSimulationT<DateType, PassiveType, ActiveType>::Path  PathType;\n\n    private:\n        std::map<std::string, ext::shared_ptr<PayoffType>>   payoffs_;      // the actual payoffs which may be accessed\n        std::vector<std::string>                             expressions_;  // resulting expressions after parsing the script but before syntactic analysis\n        std::vector<std::string>                             scriptLog_;    // log messages when parsing the script\n        ext::shared_ptr<PayoffType>                          result_;       // result payoff for MCPayoff interface implementation\n    public:\n        MCScriptT(const std::vector<std::string>&                    keys,\n                  const std::vector <ext::shared_ptr<PayoffType>>&   payoffs,\n                  const std::vector<std::string>&                    script,\n                  const bool                                         overwrite=true) : MCPayoffT<DateType, PassiveType, ActiveType>(0.0) {\n            QL_REQUIRE(keys.size()==payoffs.size(), \"MCScript error: key vs. value size missmatch\");\n            for (Size k = 0; k < keys.size(); ++k) { // initialize map\n                typename std::map< std::string, ext::shared_ptr<PayoffType> >::iterator it = payoffs_.find(keys[k]);\n                if (it == payoffs_.end()) { // insert a new element\n                    payoffs_.insert( std::make_pair(keys[k], payoffs[k]) );\n                } else { // potentially overwrite existing element\n                    QL_REQUIRE(overwrite, \"MCScript error: overwrite not allowed\");\n                    it->second = payoffs[k];\n                }\n            }\n            if ((script.size() > 0) && (script[0].compare(\"NonRecursive\") == 0)) {\n                //parseScript(script, overwrite);           // deprecated and for debugging purpose\n            } else {\n                parseFlexBisonScript(script, overwrite);  // for briefty we delegate parsing to separate method\n            }\n            QL_REQUIRE(payoffs_.size()>0, \"MCScript error: no payoffs stored.\");\n            result_ = payoffs_.rbegin()->second; // pick the last element as fall back\n\n            // we need to find a 'result' payoff\n            typename std::map< std::string, ext::shared_ptr<PayoffType> >::iterator it = payoffs_.find(\"payoff\");\n            if (it != payoffs_.end()) result_ = it->second;\n            else result_ = payoffs_.rbegin()->second; // pick the last element as fall back\n            PayoffType::observationTime_ = result_->observationTime();\n        }\n\n        inline virtual ActiveType at(const ext::shared_ptr<PathType>& p) {\n            return result_->at(p);\n        }\n\n        // inspector\n        inline const std::map<std::string, ext::shared_ptr<PayoffType>>&  payoffs()     { return payoffs_;   }\n        inline const std::vector<std::string>&                            expressions() { return expressions_; }\n        inline const std::vector<std::string>&                            scriptLog()   { return scriptLog_; }\n\n        // return all keys\n        std::vector<std::string> payoffsKeys() {\n            std::vector<std::string> keyVector;\n            for (typename std::map<std::string, ext::shared_ptr<PayoffType>>::iterator it = payoffs_.begin(); it != payoffs_.end(); ++it) {\n                keyVector.push_back(it->first);\n            }\n            return keyVector;\n        }\n\n        // return all payoffs (values in map)\n        std::vector < ext::shared_ptr<PayoffType> > payoffValues() {\n            std::vector < ext::shared_ptr<PayoffType> > payoffVector;\n            for (typename std::map<std::string, ext::shared_ptr<PayoffType> >::iterator it = payoffs_.begin(); it != payoffs_.end(); ++it) {\n                payoffVector.push_back(it->second);\n            }\n            return payoffVector;\n        }\n\n        std::vector<DateType> observationTimes(const std::vector<std::string>& keys) {\n            std::vector<ext::shared_ptr<PayoffType>> payoffs = findPayoffs(keys);\n            std::set<DateType> s;\n            for (size_t k = 0; k < payoffs.size(); ++k) s = PayoffType::unionTimes(s, payoffs[k]->observationTimes());\n            return std::vector<DateType>(s.begin(), s.end());\n        }\n\n        // MC valuation\n        inline std::vector<ActiveType> NPV(const ext::shared_ptr<SimulationType>&    simulation,\n                                           const std::vector<std::string>&           keys) {\n            std::vector<ext::shared_ptr<PayoffType>> payoffs = findPayoffs(keys);\n            std::vector<ActiveType> npv(payoffs.size(), (ActiveType)0.0);\n            for (Size n = 0; n < simulation->nPaths(); ++n) {\n                const ext::shared_ptr<PathType> p(simulation->path(n));\n                for (Size k = 0; k < payoffs.size(); ++k) {\n                    npv[k] += payoffs[k]->discountedAt(p);\n                }\n            }\n            for (Size k = 0; k < payoffs.size(); ++k) npv[k] /= simulation->nPaths();\n            return npv;\n        }\n\n        // some helper functions to simplify Asset payoff handling\n        inline static bool add_FixingTimes_to_Asset(\n            ext::shared_ptr<PayoffType>        payoff,\n            const std::vector<DateType>&       fixingTimes,\n            const std::vector<PassiveType>&    fixingValues) {\n            ext::shared_ptr<typename MCBase::Asset>  assetPayoff =\n                boost::dynamic_pointer_cast<typename MCBase::Asset>(payoff);\n            QL_REQUIRE(assetPayoff, \"Payoff is no Asset\");\n            QL_REQUIRE(fixingTimes.size() == fixingValues.size(), \"fixingTimes.size()==fixingValues.size() required\");\n            std::vector< std::pair<DateType, PassiveType> > history;\n            for (size_t k = 0; k < fixingTimes.size(); ++k)\n                history.push_back(std::make_pair(fixingTimes[k], fixingValues[k]));\n            assetPayoff->addFixings(history);\n            return true;\n        }\n\n        inline static bool add_FixingDates_to_Asset(\n            ext::shared_ptr<PayoffType>        payoff,\n            const std::vector<Date>&           fixingDates,\n            const std::vector<PassiveType>&    fixingValues) {\n            std::vector<DateType> fixingTimes(fixingDates.size());\n            Date today = Settings::instance().evaluationDate();\n            for (size_t k = 0; k < fixingDates.size(); ++k)\n                fixingTimes[k] = (DateType)(((fixingDates[k].serialNumber() - today.serialNumber()) / 365.0));\t\t\t\n            return add_FixingTimes_to_Asset(payoff, fixingTimes, fixingValues);\n        }\n\n    private:\n\n        // convert string to number\n        inline static bool to_Number(const std::string str, ActiveType& number) {\n            double res;\n            std::string::size_type sz;\n            try {\n                res = std::stod(str, &sz);\n            }\n            catch (std::exception e) {\n                return false;\n            }\n            number = res;\n            return true;\n        }\n\n        // convert a Date to number\n        inline static DateType date_to_Number(const Date& d) {\n            Date today = Settings::instance().evaluationDate();\n            DateType number = (DateType)(((d.serialNumber() - today.serialNumber()) / 365.0));\n            return number;\n        }\n\n        // convert date string with format ddmmmyyyy to number\n        inline static bool date_to_Number(const std::string str, ActiveType& number) {\n            if (str.length() != 9) return false;\n            std::string::size_type sz;\n            try {\n                Day  day  = std::stol(str.substr(0,2), &sz);\n                Year year = std::stol(str.substr(5,4), &sz);\n                Month month;\n                std::string s = str.substr(2, 3);\n                if (s.compare(\"Jan\") == 0) month = Month::Jan;\n                else if (s.compare(\"Feb\") == 0) month = Month::Feb;\n                else if (s.compare(\"Mar\") == 0) month = Month::Mar;\n                else if (s.compare(\"Apr\") == 0) month = Month::Apr;\n                else if (s.compare(\"May\") == 0) month = Month::May;\n                else if (s.compare(\"Jun\") == 0) month = Month::Jun;\n                else if (s.compare(\"Jul\") == 0) month = Month::Jul;\n                else if (s.compare(\"Aug\") == 0) month = Month::Aug;\n                else if (s.compare(\"Sep\") == 0) month = Month::Sep;\n                else if (s.compare(\"Oct\") == 0) month = Month::Oct;\n                else if (s.compare(\"Nov\") == 0) month = Month::Nov;\n                else if (s.compare(\"Dec\") == 0) month = Month::Dec;\n                else return false;\n                Date d(day, month, year);\n                Date today = Settings::instance().evaluationDate();\n                number = (ActiveType)(((d.serialNumber() - today.serialNumber()) / 365.0));\n            }\n            catch (std::exception e) {\n                return false;\n            }\n            return true;\n        }\n\n\n\n        // we define that helper function to simplify code in forthcoming expression parsing\n        inline bool hasChilds(const ext::shared_ptr<Scripting::Expression> tree, Size nArgs, Size lineNr) {\n            // make sure we can actually do something with the tree\n            if (!tree) {\n                scriptLog_.push_back(std::string(\"Error line \" + std::to_string(lineNr) + \": Empty expression tree.\"));\n                return false;\n            }\n            if (tree->childs().size() != nArgs) {\n                scriptLog_.push_back(std::string(\"Error line \" + std::to_string(lineNr) + \": \" + std::to_string(nArgs) + \" child expressions expected, but \" + std::to_string(tree->childs().size()) + \" found.\" ));\n                return false;\n            }\n            return true;\n        }\n\n        // we define that helper function to simplify code in forthcoming expression parsing\n        inline bool hasChildsInRange(const ext::shared_ptr<Scripting::Expression> tree, Size nArgsMin, Size nArgsMax, Size lineNr) {\n            // make sure we can actually do something with the tree\n            if (!tree) {\n                scriptLog_.push_back(std::string(\"Error line \" + std::to_string(lineNr) + \": Empty expression tree.\"));\n                return false;\n            }\n            if ((tree->childs().size() < nArgsMin)||(tree->childs().size() > nArgsMax)) {\n                scriptLog_.push_back(std::string(\"Error line \" + std::to_string(lineNr) + \": [\" + std::to_string(nArgsMin) + \", \" + std::to_string(nArgsMax) +\n                    \"] child expressions expected, but \" + std::to_string(tree->childs().size()) + \" found.\"));\n                return false;\n            }\n            return true;\n        }\n\n        // we define that helper function to simplify code in forthcoming expression parsing\n        inline bool hasLeafs(const ext::shared_ptr<Scripting::Expression> tree, Size nArgs, Size lineNr) {\n            // make sure we can actually do something with the tree\n            if (!tree) {\n                scriptLog_.push_back(std::string(\"Error line \" + std::to_string(lineNr) + \": Empty expression tree.\"));\n                return false;\n            }\n            if (tree->leafs().size() != nArgs) {\n                scriptLog_.push_back(std::string(\"Error line \" + std::to_string(lineNr) + \": \" + std::to_string(nArgs) + \" leafs expected, but \" + std::to_string(tree->leafs().size()) + \" found.\"));\n                return false;\n            }\n            return true;\n        }\n\n        // we define that helper function to simplify code in forthcoming expression parsing\n        inline bool hasLeafsInRange(const ext::shared_ptr<Scripting::Expression> tree, Size nArgsMin, Size nArgsMax, Size lineNr) {\n            // make sure we can actually do something with the tree\n            if (!tree) {\n                scriptLog_.push_back(std::string(\"Error line \" + std::to_string(lineNr) + \": Empty expression tree.\"));\n                return false;\n            }\n            if ((tree->leafs().size()<nArgsMin)|| (tree->leafs().size()>nArgsMax)) {\n                scriptLog_.push_back(std::string(\"Error line \" + std::to_string(lineNr) + \": [\" + std::to_string(nArgsMin) + \", \" + std::to_string(nArgsMax) +\n                    \"] leafs expected, but \" + std::to_string(tree->leafs().size()) + \" found.\"));\n                return false;\n            }\n            return true;\n        }\n\n        // check if a list of payoffs exists before doing some computationally expensive stuff with them\n        std::vector< ext::shared_ptr<PayoffType> > findPayoffs(const std::vector<std::string>& keys, bool throwException = true) {\n            std::vector<ext::shared_ptr<PayoffType>> payoffs;\n            for (Size k = 0; k < keys.size(); ++k) {\n                typename std::map<std::string, ext::shared_ptr<PayoffType> >::iterator it = payoffs_.find(keys[k]);\n                if (it != payoffs_.end()) {\n                    payoffs.push_back(it->second);\n                    continue; // all done for this key\n                }\n                if (throwException) QL_FAIL(\"MCScript error: payoff '\" + keys[k] + \"' not found\");\n            }\n            return payoffs;\n        }\n\n        // convert an abstract expression tree into a payoff\n        // this function does the actual work...\n        ext::shared_ptr<PayoffType> payoff(const ext::shared_ptr<Scripting::Expression> tree, Size k) {\n            // make sure we can actually do something with the tree\n            if (!tree) {\n                scriptLog_.push_back(std::string(\"Error line \" + std::to_string(k) + \": Empty expression tree.\"));\n                QL_FAIL(\"Cannot interprete payoff\");\n            }\n            // check any possible expression\n            switch (tree->type()) {\n            // expressions based on tokens\n            case Scripting::Expression::NUMBER: {\n                if (!hasChilds(tree, 0, k)) QL_FAIL(\"Cannot interprete payoff\");\n                if (!hasLeafs(tree, 1, k)) \tQL_FAIL(\"Cannot interprete payoff\");\n                ActiveType number;\n                if (to_Number(tree->leafs()[0], number)) {\n                    return ext::shared_ptr<PayoffType>(new typename MCBase::FixedAmount(number));\n                }\n                scriptLog_.push_back(std::string(\"Error line \" + std::to_string(k) + \": cannot convert \" + tree->leafs()[0] + \" to number.\"));\n                QL_FAIL(\"Cannot interprete payoff\");\n            }\n            case Scripting::Expression::IDENTIFIER: {\n                if (!hasChilds(tree, 0, k)) QL_FAIL(\"Cannot interprete payoff\");\n                if (!hasLeafs(tree, 1, k))  QL_FAIL(\"Cannot interprete payoff\");\n                // check for existing payoff in map\n                typename std::map<std::string, ext::shared_ptr<PayoffType>>::iterator it = payoffs_.find(tree->leafs()[0]);\n                if (it != payoffs_.end()) {\n                    scriptLog_.push_back(std::string(\"Payoff line \" + std::to_string(k) + \": '\" + tree->leafs()[0] + \"' is in map\"));\n                    return it->second;\n                }\n                // if we end up here no conversion was successfull\n                scriptLog_.push_back(std::string(\"Error line \" + std::to_string(k) + \": '\" + tree->leafs()[0] + \"' is no payoff\"));\n                QL_FAIL(\"Cannot interprete payoff\");\n            }\n            // expressions basen on unary operators\n            case Scripting::Expression::UNARYPLUS: {\n                if (!hasChilds(tree, 1, k)) QL_FAIL(\"Cannot interprete payoff\");\n                if (!hasLeafs(tree, 0, k))  QL_FAIL(\"Cannot interprete payoff\");\n                return this->payoff(tree->childs()[0], k);\n            }\n            case Scripting::Expression::UNARYMINUS: {\n                if (!hasChilds(tree, 1, k)) QL_FAIL(\"Cannot interprete payoff\");\n                if (!hasLeafs(tree, 0, k))  QL_FAIL(\"Cannot interprete payoff\");\n                return ext::shared_ptr<PayoffType>(new typename MCBase::Axpy(-1.0, payoff(tree->childs()[0], k), 0));\n            }\n            case Scripting::Expression::PLUS: {\n                if (!hasChilds(tree, 2, k)) QL_FAIL(\"Cannot interprete payoff\");\n                if (!hasLeafs(tree, 0, k))  QL_FAIL(\"Cannot interprete payoff\");\n                return ext::shared_ptr<PayoffType>(new typename MCBase::Axpy(1.0, payoff(tree->childs()[0], k), payoff(tree->childs()[1], k)));\n            }\n            case Scripting::Expression::MINUS: {\n                if (!hasChilds(tree, 2, k)) QL_FAIL(\"Cannot interprete payoff\");\n                if (!hasLeafs(tree, 0, k))  QL_FAIL(\"Cannot interprete payoff\");\n                return ext::shared_ptr<PayoffType>(new typename MCBase::Axpy(-1.0, payoff(tree->childs()[1], k), payoff(tree->childs()[0], k)));\n            }\n            case Scripting::Expression::MULT: {\n                if (!hasChilds(tree, 2, k)) QL_FAIL(\"Cannot interprete payoff\");\n                if (!hasLeafs(tree, 0, k))  QL_FAIL(\"Cannot interprete payoff\");\n                return ext::shared_ptr<PayoffType>(new typename MCBase::Mult(payoff(tree->childs()[0], k), payoff(tree->childs()[1], k)));\n            }\n            case Scripting::Expression::DIVISION: {\n                if (!hasChilds(tree, 2, k)) QL_FAIL(\"Cannot interprete payoff\");\n                if (!hasLeafs(tree, 0, k))  QL_FAIL(\"Cannot interprete payoff\");\n                return ext::shared_ptr<PayoffType>(new typename MCBase::Division(payoff(tree->childs()[0], k), payoff(tree->childs()[1], k)));\n            }\n            case Scripting::Expression::IFTHENELSE: {\n                if (!hasChilds(tree, 3, k)) QL_FAIL(\"Cannot interprete payoff\");\n                if (!hasLeafs(tree, 0, k))  QL_FAIL(\"Cannot interprete payoff\");\n                return ext::shared_ptr<PayoffType>(new typename MCBase::IfThenElse(payoff(tree->childs()[0], k), payoff(tree->childs()[1], k), payoff(tree->childs()[2], k)));\n            }\n            case Scripting::Expression::MIN: {\n                if (!hasChilds(tree, 2, k)) QL_FAIL(\"Cannot interprete payoff\");\n                if (!hasLeafs(tree, 0, k))  QL_FAIL(\"Cannot interprete payoff\");\n                return ext::shared_ptr<PayoffType>(new typename MCBase::Min(payoff(tree->childs()[0], k), payoff(tree->childs()[1], k)));\n            }\n            case Scripting::Expression::MAX: {\n                if (!hasChilds(tree, 2, k)) QL_FAIL(\"Cannot interprete payoff\");\n                if (!hasLeafs(tree, 0, k))  QL_FAIL(\"Cannot interprete payoff\");\n                return ext::shared_ptr<PayoffType>(new typename MCBase::Max(payoff(tree->childs()[0], k), payoff(tree->childs()[1], k)));\n            }\n            case Scripting::Expression::EXPONENTIAL: {\n                if (!hasChilds(tree, 1, k)) QL_FAIL(\"Cannot interprete payoff\");\n                if (!hasLeafs(tree, 0, k))  QL_FAIL(\"Cannot interprete payoff\");\n                return ext::shared_ptr<PayoffType>(new typename MCBase::Exponential(payoff(tree->childs()[0], k)));\n            }\n            case Scripting::Expression::LOGARITHM: {\n                if (!hasChilds(tree, 1, k)) QL_FAIL(\"Cannot interprete payoff\");\n                if (!hasLeafs(tree, 0, k))  QL_FAIL(\"Cannot interprete payoff\");\n                return ext::shared_ptr<PayoffType>(new typename MCBase::Logarithm(payoff(tree->childs()[0], k)));\n            }\n            case Scripting::Expression::SQUAREROOT: {\n                if (!hasChilds(tree, 1, k)) QL_FAIL(\"Cannot interprete payoff\");\n                if (!hasLeafs(tree, 0, k))  QL_FAIL(\"Cannot interprete payoff\");\n                return ext::shared_ptr<PayoffType>(new typename MCBase::Squareroot(payoff(tree->childs()[0], k)));\n            }\n            case Scripting::Expression::LOGICAL: {\n                if (!hasChilds(tree, 2, k)) QL_FAIL(\"Cannot interprete payoff\");\n                if (!hasLeafs(tree, 1, k))  QL_FAIL(\"Cannot interprete payoff\");\n                return ext::shared_ptr<PayoffType>(new typename MCBase::Logical(payoff(tree->childs()[0], k), payoff(tree->childs()[1], k), tree->leafs()[0]));\n            }\n            case Scripting::Expression::PAY: {\n                if (!hasChilds(tree, 1, k)) QL_FAIL(\"Cannot interprete payoff\");\n                if (!hasLeafs(tree, 1, k))  QL_FAIL(\"Cannot interprete payoff\");\n                ActiveType number;\n                if (!to_Number(tree->leafs()[0], number)) {\n                    scriptLog_.push_back(std::string(\"Error line \" + std::to_string(k) + \": cannot convert \" + tree->leafs()[0] + \" to number.\"));\n                    QL_FAIL(\"Cannot interprete payoff\");\n                }\n                return ext::shared_ptr<PayoffType>(new typename MCBase::Pay(payoff(tree->childs()[0], k), number));\n            }\n            case Scripting::Expression::PAY_WITHDATE: {\n                if (!hasChilds(tree, 1, k)) QL_FAIL(\"Cannot interprete payoff\");\n                if (!hasLeafs(tree, 1, k))  QL_FAIL(\"Cannot interprete payoff\");\n                ActiveType number;\n                if (!date_to_Number(tree->leafs()[0], number)) {\n                    scriptLog_.push_back(std::string(\"Error line \" + std::to_string(k) + \": cannot convert \" + tree->leafs()[0] + \" to number.\"));\n                    QL_FAIL(\"Cannot interprete payoff\");\n                }\n                return ext::shared_ptr<PayoffType>(new typename MCBase::Pay(payoff(tree->childs()[0], k), number));\n            }\n            case Scripting::Expression::CACHE: {\n                if (!hasChilds(tree, 1, k)) QL_FAIL(\"Cannot interprete payoff\");\n                if (!hasLeafs(tree, 0, k))  QL_FAIL(\"Cannot interprete payoff\");\n                return ext::shared_ptr<PayoffType>(new typename MCBase::Cache(payoff(tree->childs()[0], k)));\n            }\n            case Scripting::Expression::PAYOFFAT: {\n                if (!hasChilds(tree, 1, k)) QL_FAIL(\"Cannot interprete payoff\");\n                if (!hasLeafsInRange(tree, 1, 2, k)) QL_FAIL(\"Cannot interprete payoff\");\n                ActiveType number;\n                if (!to_Number(tree->leafs()[0], number)) {\n                    scriptLog_.push_back(std::string(\"Error line \" + std::to_string(k) + \": cannot convert \" + tree->leafs()[0] + \" to number.\"));\n                    QL_FAIL(\"Cannot interprete payoff\");\n                }\n                ActiveType sign = 1.0;\n                if (tree->leafs().size()>1) { // we expect a negative number\n                    if (tree->leafs()[1].compare(\"-\") != 0) {\n                        scriptLog_.push_back(std::string(\"Error line \" + std::to_string(k) + \": cannot convert \" + tree->leafs()[1] + tree->leafs()[0] + \" to negative number.\"));\n                        QL_FAIL(\"Cannot interprete payoff\");\n                    }\n                    sign = -1.0;\n                }\n                ext::shared_ptr<PayoffType> p = payoff(tree->childs()[0], k);\n                if (p) return p->at(sign*number);\n                QL_FAIL(\"Cannot interprete payoff\");\n            }\n            case Scripting::Expression::PAYOFFAT_WITHDATE: {\n                if (!hasChilds(tree, 1, k)) QL_FAIL(\"Cannot interprete payoff\");\n                if (!hasLeafs(tree, 1, k))  QL_FAIL(\"Cannot interprete payoff\");\n                ActiveType number;\n                if (!date_to_Number(tree->leafs()[0], number)) {\n                    scriptLog_.push_back(std::string(\"Error line \" + std::to_string(k) + \": cannot convert \" + tree->leafs()[0] + \" to number.\"));\n                    QL_FAIL(\"Cannot interprete payoff\");\n                }\n                ext::shared_ptr<PayoffType> p = payoff(tree->childs()[0], k);\n                if (p) return p->at(number);\n                QL_FAIL(\"Cannot interprete payoff\");\n            }\t\n            // we don't need a default because we returned in each of the previous cases\n            } // finished all switch types\n            // if we end up here there is an expression which we didn't interprete \n            scriptLog_.push_back(std::string(\"Error line \" + std::to_string(k) + \": unknown expression type.\"));\n            QL_FAIL(\"Cannot interprete payoff\");\n            return 0; // this should never be reached\n        }\n\n        // parse the script and set up payoffs\n        inline void parseFlexBisonScript(const std::vector<std::string>&  script,\n                                         const bool                       overwrite = true) {\n            for (Size k = 0; k < script.size(); ++k) {  // first line should equal 'FlexBison' and is skipped anyway\n                Scripting::FlexBisonDriver driver(script[k], false, false);\n                // in any case we want to know the parsing result\n                if (driver.expressionTree()) expressions_.push_back(\"L\" + std::to_string(k) + \":\" + driver.expressionTree()->toString());\n                if (driver.returnValue() == 0) {\n                    if (!driver.expressionTree()) {\n                        scriptLog_.push_back(std::string(\"Error line \" + std::to_string(k) + \": Empty expression tree.\"));\n                        continue;\n                    }\n                    if (driver.expressionTree()->type() != Scripting::Expression::ASSIGNMENT ) {\n                        scriptLog_.push_back(std::string(\"Error line \" + std::to_string(k) + \": Assignment expected.\"));\n                        continue;\n                    }\n                    if (!hasChilds(driver.expressionTree(), 1, k)) continue;\n                    if (!hasLeafs(driver.expressionTree(), 1, k)) continue;\n                    // interprete right side of assignment\n                    ext::shared_ptr<PayoffType> p;\n                    try {\n                        p = payoff(driver.expressionTree()->childs()[0], k);\n                    }\n                    catch (std::exception e) {  // something went wrong, for details check scriptLog_\n                        scriptLog_.push_back(std::string(\"Error line \" + std::to_string(k) + \": Exception caught: \" + e.what()));\n                        continue;\n                    }\n                    if (!p) {\n                        scriptLog_.push_back(std::string(\"Error line \" + std::to_string(k) + \": No payoff found.\"));\n                        continue;\n                    }\n                    // just define an abbreviation\n                    std::string var = driver.expressionTree()->leafs()[0];\n                    if (var.compare(\"\") == 0) {\n                        scriptLog_.push_back(std::string(\"Error line \" + std::to_string(k) + \": Non-empty identifier expected.\"));\n                        continue;\n                    }\n                    // now we have a payoff which we may store in the map\n                    typename std::map<std::string, ext::shared_ptr<PayoffType> >::iterator it = payoffs_.find(var);\n                    if (it == payoffs_.end()) { // insert a new element\n                        payoffs_.insert(std::make_pair(var, p));\n                        scriptLog_.push_back(std::string(\"Insert line \" + std::to_string(k) + \": '\" + script[k] + \"'\"));\n                        continue;\n                    }\n                    if (overwrite) {\n                        it->second = p;\n                        scriptLog_.push_back(std::string(\"Replace line \" + std::to_string(k) + \": '\" + script[k] + \"'\"));\n                        continue;\n                    } \n                    else scriptLog_.push_back(std::string(\"Error line \" + std::to_string(k) + \": Cannot replace line '\" + script[k] + \"'\"));\n                }\n                else {\n                    scriptLog_.push_back(std::string(\"Error line \" + std::to_string(k) + \": \" + driver.errorMsg()));\n                    continue;\n                }\n            }\n        }\n\n        /*\n\n        we implement the following non-recursive grammar\n\n        line  =  var '=' expr\n        var   =  [a-zA-Z][a-zA-Z0-9]*           { RegEx }\n        expr  =  operator | function | payoff   { apply from left to right }\n\n        operator   =  operator1 | operator2\n        operator1  =  ['+' | '-'] payoff\n        operator2  =  payoff ['+' | '-' | '*' | == | != | < | <= | > | >= | && | || ] payoff\n\n        function   =  function3 | function2 | function1\n        function3  =  fname3 '(' payoff ',' payoff ',' payoff ')'\n        function2  =  fname2 '(' payoff ',' payoff ')'\n        function1  =  fname1 '(' payoff ')'\n\n        fname3     =  'IfThenElse'\n        fname2     =  'Min' | 'Max | Pay'\n        fname1     =  'Cache'\n\n        payoff  =  number | string              { try double conversion and lookup in map }\n\n        */\n\n        // parse the script and set up payoffs\n        inline void parseScript(const std::vector<std::string>&  script,\n            const bool                       overwrite = true) {\n            for (Size k = 0; k < script.size(); ++k) {  // parse lines\n                std::string line = boost::regex_replace(script[k], boost::regex(\" \"), \"\"); // remove whitespaces\n                boost::smatch what;\n\n                bool isAssignment = boost::regex_match(line, what, boost::regex(\"([a-zA-Z][a-zA-Z0-9]*)(=)(.+)\"));\n                if (!isAssignment) {\n                    scriptLog_.push_back(std::string(\"Error line \" + std::to_string(k) + \": '\" + line + \"' is no valid assignment\"));\n                    continue; // move to next item in script\n                }\n                std::string var(what[1]), expr(what[3]);\n\n                ext::shared_ptr<PayoffType> p;\n\n                if (boost::regex_match(expr, what, boost::regex(\"(\\\\+|-)(.+)\"))) {\n                    p = operator1(std::string(what[1]), std::string(what[2]), k);\n                }\n                else if (boost::regex_match(expr, what, boost::regex(\"(.+)(\\\\+|-|\\\\*|==|!=|<=|<|>=|>|&&|\\\\|\\\\|)(.+)\"))) {\n                    p = operator2(std::string(what[2]), std::string(what[1]), std::string(what[3]), k);\n                }\n                else if (boost::regex_match(expr, what, boost::regex(\"([a-zA-Z]+)\\\\((.+),(.+),(.+)\\\\)\"))) {\n                    p = function3(std::string(what[1]), std::string(what[2]), std::string(what[3]), std::string(what[4]), k);\n                }\n                else if (boost::regex_match(expr, what, boost::regex(\"([a-zA-Z]+)\\\\((.+),(.+)\\\\)\"))) {\n                    p = function2(std::string(what[1]), std::string(what[2]), std::string(what[3]), k);\n                }\n                else if (boost::regex_match(expr, what, boost::regex(\"([a-zA-Z]+)\\\\((.+)\\\\)\"))) {\n                    p = function1(std::string(what[1]), std::string(what[2]), k);\n                }\n                else p = payoff(expr, k); // action of last resort\n\n                if (!p) {\n                    scriptLog_.push_back(std::string(\"Error line \" + std::to_string(k) + \": '\" + expr + \"' is no valid expression\"));\n                    continue; // move to next item in script\n                }\n\n                // now we have a payoff which we may store in the map\n                typename std::map<std::string, ext::shared_ptr<PayoffType> >::iterator it = payoffs_.find(var);\n                if (it == payoffs_.end()) { // insert a new element\n                    payoffs_.insert(std::make_pair(var, p));\n                    scriptLog_.push_back(std::string(\"Insert line \" + std::to_string(k) + \": '\" + line + \"'\"));\n                    continue;\n                }\n                if (overwrite) {\n                    it->second = p;\n                    scriptLog_.push_back(std::string(\"Replace line \" + std::to_string(k) + \": '\" + line + \"'\"));\n                    continue;\n                }\n                // if we end up here we have a valid payoff but are not allowed to overwrite existing map entry\n                scriptLog_.push_back(std::string(\"Error line \" + std::to_string(k) + \": '\" + var + \"' can not be replaced\"));\n            }\n            if (script.size() == 0) { // in this case the previous loop was not executed and we just print some help details\n                scriptLog_.push_back(std::string(\"we implement the following non-recursive grammar                                     \"));\n                scriptLog_.push_back(std::string(\"                                                                                     \"));\n                scriptLog_.push_back(std::string(\"line  =  var '=' expr                                                                \"));\n                scriptLog_.push_back(std::string(\"var   =  [a-zA-Z][a-zA-Z0-9]*           { RegEx }                                    \"));\n                scriptLog_.push_back(std::string(\"expr  =  operator | function | payoff   { apply from left to right }                 \"));\n                scriptLog_.push_back(std::string(\"                                                                                     \"));\n                scriptLog_.push_back(std::string(\"operator   =  operator1 | operator2                                                  \"));\n                scriptLog_.push_back(std::string(\"operator1  =  ['+' | '-'] payoff                                                     \"));\n                scriptLog_.push_back(std::string(\"operator2  =  payoff ['+' | '-' | '*' |                                              \"));\n                scriptLog_.push_back(std::string(\"                      '==' | '!=' | '<=' |'<' | '>=' | '>' | '&&' | '||' ] payoff    \"));\n                scriptLog_.push_back(std::string(\"                                                                                     \"));\n                scriptLog_.push_back(std::string(\"function   =  function3 | function2 | function1                                      \"));\n                scriptLog_.push_back(std::string(\"function3  =  fname3 '(' payoff ',' payoff ',' payoff ')'                            \"));\n                scriptLog_.push_back(std::string(\"function2  =  fname2 '(' payoff ',' payoff ')'                                       \"));\n                scriptLog_.push_back(std::string(\"function1  =  fname1 '(' payoff ')'                                                  \"));\n                scriptLog_.push_back(std::string(\"                                                                                     \"));\n                scriptLog_.push_back(std::string(\"fname3     =  'IfThenElse'                                                           \"));\n                scriptLog_.push_back(std::string(\"fname2     =  'Min' | 'Max' | 'Pay'                                                  \"));\n                scriptLog_.push_back(std::string(\"fname1     =  'Cache'                                                                \"));\n                scriptLog_.push_back(std::string(\"                                                                                     \"));\n                scriptLog_.push_back(std::string(\"payoff  =  number | string              { try double conversion and lookup in map }  \"));\n            }\n        }\n\n\n        // compile fixed cash flow or lookup in map\n        inline ext::shared_ptr<PayoffType> payoff(const std::string expr, const Size lineNr) {\n            ActiveType amount;\n            bool isFixed = to_Number(expr, amount);\n            if (isFixed) {\n                scriptLog_.push_back(std::string(\"Payoff line \" + std::to_string(lineNr) + \": '\" + boost::lexical_cast<std::string>(amount) + \"' is fixed amount\"));\n                return ext::shared_ptr<PayoffType>(new typename MCBase::FixedAmount(amount));\n            }\n            typename std::map<std::string, ext::shared_ptr<PayoffType> >::iterator it = payoffs_.find(expr);\n            if (it != payoffs_.end()) {\n                scriptLog_.push_back(std::string(\"Payoff line \" + std::to_string(lineNr) + \": '\" + expr + \"' is in map\"));\n                return it->second;\n            }\n            // if we end up here no conversion was successfull\n            scriptLog_.push_back(std::string(\"Error line \" + std::to_string(lineNr) + \": '\" + expr + \"' is no payoff\"));\n            return 0;\n        }\n\n        // compile single operand function\n        inline ext::shared_ptr<PayoffType> function1(const std::string fname, const std::string operand, const Size lineNr) {\n            ext::shared_ptr<PayoffType> p = payoff(operand, lineNr);\n            if (!p) {\n                scriptLog_.push_back(std::string(\"Error line \" + std::to_string(lineNr) + \": '\" + operand + \"' is no valid operand\"));\n                return 0;\n            }\n            boost::smatch what;\n            if (boost::regex_match(fname, what, boost::regex(\"Cache\")))\n                return ext::shared_ptr<PayoffType>(new typename MCBase::Cache(p));\n            // if we end up here the function name is not valid\n            scriptLog_.push_back(std::string(\"Error line \" + std::to_string(lineNr) + \": '\" + fname + \"' is no valid unary function name\"));\n            return 0;\n        }\n\n        // compile dual operand function\n        inline ext::shared_ptr<PayoffType> function2(const std::string fname, const std::string oper1, const std::string oper2, const Size lineNr) {\n            ext::shared_ptr<PayoffType> p1 = payoff(oper1, lineNr);\n            if (!p1) {\n                scriptLog_.push_back(std::string(\"Error line \" + std::to_string(lineNr) + \": '\" + oper1 + \"' is no valid operand\"));\n                return 0;\n            }\n            ext::shared_ptr<PayoffType> p2 = payoff(oper2, lineNr);\n            if (!p2) {\n                scriptLog_.push_back(std::string(\"Error line \" + std::to_string(lineNr) + \": '\" + oper2 + \"' is no valid operand\"));\n                return 0;\n            }\n            boost::smatch what;\n            if (boost::regex_match(fname, what, boost::regex(\"Min\")))\n                return ext::shared_ptr<PayoffType>(new typename MCBase::Min(p1, p2));\n            if (boost::regex_match(fname, what, boost::regex(\"Max\")))\n                return ext::shared_ptr<PayoffType>(new typename MCBase::Max(p1, p2));\n            if (boost::regex_match(fname, what, boost::regex(\"Pay\"))) {\n                DateType t;\n                if (to_Number(oper2, t)) return ext::shared_ptr<PayoffType>(new typename MCBase::Pay(p1, t)); // usual application\n                return ext::shared_ptr<PayoffType>(new typename MCBase::Pay(p1, p2->observationTime())); // fall back\n            }\n            // if we end up here the function name is not valid\n            scriptLog_.push_back(std::string(\"Error line \" + std::to_string(lineNr) + \": '\" + fname + \"' is no valid binary function name\"));\n            return 0;\n        }\n\n        // compile three operand function\n        inline ext::shared_ptr<PayoffType> function3(const std::string fname, const std::string oper1, const std::string oper2, const std::string oper3, const Size lineNr) {\n            ext::shared_ptr<PayoffType> p1 = payoff(oper1, lineNr);\n            if (!p1) {\n                scriptLog_.push_back(std::string(\"Error line \" + std::to_string(lineNr) + \": '\" + oper1 + \"' is no valid operand\"));\n                return 0;\n            }\n            ext::shared_ptr<PayoffType> p2 = payoff(oper2, lineNr);\n            if (!p2) {\n                scriptLog_.push_back(std::string(\"Error line \" + std::to_string(lineNr) + \": '\" + oper2 + \"' is no valid operand\"));\n                return 0;\n            }\n            ext::shared_ptr<PayoffType> p3 = payoff(oper3, lineNr);\n            if (!p3) {\n                scriptLog_.push_back(std::string(\"Error line \" + std::to_string(lineNr) + \": '\" + oper3 + \"' is no valid operand\"));\n                return 0;\n            }\n            boost::smatch what;\n            if (boost::regex_match(fname, what, boost::regex(\"IfThenElse\")))\n                return ext::shared_ptr<PayoffType>(new typename MCBase::IfThenElse(p1, p2, p3));\n            // if we end up here the function name is not valid\n            scriptLog_.push_back(std::string(\"Error line \" + std::to_string(lineNr) + \": '\" + fname + \"' is no valid function name\"));\n            return 0;\n        }\n\n        // compile unary operators\n        inline ext::shared_ptr<PayoffType> operator1(const std::string opname, const std::string operand, const Size lineNr) {\n            ext::shared_ptr<PayoffType> p = payoff(operand, lineNr);\n            if (!p) {\n                scriptLog_.push_back(std::string(\"Error line \" + std::to_string(lineNr) + \": '\" + operand + \"' is no valid operand\"));\n                return 0;\n            }\n            boost::smatch what;\n            if (boost::regex_match(opname, what, boost::regex(\"\\\\+\"))) return p;\n            if (boost::regex_match(opname, what, boost::regex(\"-\"))) return ext::shared_ptr<PayoffType>(new typename MCBase::Axpy(-1.0, p, 0));\n            // if we end up here the function name is not valid\n            scriptLog_.push_back(std::string(\"Error line \" + std::to_string(lineNr) + \": '\" + opname + \"' is no valid unary operator name\"));\n            return 0;\n        }\n\n        // compile binary operators\n        inline ext::shared_ptr<PayoffType> operator2(const std::string opname, const std::string oper1, const std::string oper2, const Size lineNr) {\n            ext::shared_ptr<PayoffType> p1 = payoff(oper1, lineNr);\n            if (!p1) {\n                scriptLog_.push_back(std::string(\"Error line \" + std::to_string(lineNr) + \": '\" + oper1 + \"' is no valid operand\"));\n                return 0;\n            }\n            ext::shared_ptr<PayoffType> p2 = payoff(oper2, lineNr);\n            if (!p2) {\n                scriptLog_.push_back(std::string(\"Error line \" + std::to_string(lineNr) + \": '\" + oper2 + \"' is no valid operand\"));\n                return 0;\n            }\n            boost::smatch what;\n            if (boost::regex_match(opname, what, boost::regex(\"\\\\+\")))\n                return ext::shared_ptr<PayoffType>(new typename MCBase::Axpy(1.0, p1, p2));\n            if (boost::regex_match(opname, what, boost::regex(\"-\")))\n                return ext::shared_ptr<PayoffType>(new typename MCBase::Axpy(-1.0, p2, p1));\n            if (boost::regex_match(opname, what, boost::regex(\"\\\\*\")))\n                return ext::shared_ptr<PayoffType>(new typename MCBase::Mult(p1, p2));\n            if (boost::regex_match(opname, what, boost::regex(\"==|!=|<|<=|>|>=|&&|\\\\|\\\\|\")))\n                return ext::shared_ptr<PayoffType>(new typename MCBase::Logical(p1, p2, opname));\n            // if we end up here the function name is not valid\n            scriptLog_.push_back(std::string(\"Error line \" + std::to_string(lineNr) + \": '\" + opname + \"' is no valid binary operator name\"));\n            return 0;\n        }\n\n    };\n\n}\n\n#endif  /* ifndef quantlib_templatemcscript_hpp */ \n", "meta": {"hexsha": "380cb70f5a2d02b2d4d030348ed2ec07b59c34be", "size": 43489, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/experimental/templatemodels/montecarlo/mcscriptT.hpp", "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/templatemodels/montecarlo/mcscriptT.hpp", "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/templatemodels/montecarlo/mcscriptT.hpp", "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": 58.689608637, "max_line_length": 212, "alphanum_fraction": 0.5226838971, "num_tokens": 10147, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.6513548511303336, "lm_q1q2_score": 0.4879215901819799}}
{"text": "//\n//  EigenLibSolver.hpp\n//  DOT\n//\n//  Created by Minchen Li on 6/30/18.\n//\n\n#ifndef EigenLibSolver_hpp\n#define EigenLibSolver_hpp\n\n#include \"LinSysSolver.hpp\"\n\n#include <Eigen/Eigen>\n\n#include <vector>\n#include <set>\n\nnamespace DOT {\n    \n    template <typename vectorTypeI, typename vectorTypeS>\n    class EigenLibSolver : public LinSysSolver<vectorTypeI, vectorTypeS>\n    {\n        typedef LinSysSolver<vectorTypeI, vectorTypeS> Base;\n        \n    protected:\n        bool useDense;\n        Eigen::MatrixXd coefMtr_dense;\n        Eigen::LDLT<Eigen::MatrixXd> LDLT;\n        Eigen::SparseMatrix<double> coefMtr;\n        Eigen::SimplicialLDLT<Eigen::SparseMatrix<double>> simplicialLDLT;\n        \n    public:\n        void set_type(int threadAmt, int _mtype, bool is_upper_half = false);\n        \n        void set_pattern(const std::vector<std::set<int>>& vNeighbor,\n                         const std::set<int>& fixedVert);\n        void set_pattern(const Eigen::SparseMatrix<double>& mtr); //NOTE: mtr must be SPD\n        \n        void update_a(const vectorTypeI &II,\n                      const vectorTypeI &JJ,\n                      const vectorTypeS &SS);\n        void update_a(const Eigen::SparseMatrix<double>& mtr);\n        \n        void analyze_pattern(void);\n        \n        bool factorize(void);\n        \n        void solve(Eigen::VectorXd &rhs,\n                   Eigen::VectorXd &result);\n        void solve_threadSafe(Eigen::VectorXd &rhs,\n                              Eigen::VectorXd &result,\n                              int dimI);\n        \n        double coeffMtr(int rowI, int colI) const;\n        \n        void setZero(void);\n        \n        virtual void setCoeff(int rowI, int colI, double val);\n        \n        virtual void addCoeff(int rowI, int colI, double val);\n    };\n    \n}\n\n#endif /* EigenLibSolver_hpp */\n", "meta": {"hexsha": "70ab36d64d837f0d1181b5288bf51c35651ecff9", "size": 1838, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/LinSysSolver/EigenLibSolver.hpp", "max_stars_repo_name": "liminchen/DOT", "max_stars_repo_head_hexsha": "26525fba815fb081e90676321e42d0a60ecb0cb1", "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": "src/LinSysSolver/EigenLibSolver.hpp", "max_issues_repo_name": "liminchen/DOT", "max_issues_repo_head_hexsha": "26525fba815fb081e90676321e42d0a60ecb0cb1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/LinSysSolver/EigenLibSolver.hpp", "max_forks_repo_name": "liminchen/DOT", "max_forks_repo_head_hexsha": "26525fba815fb081e90676321e42d0a60ecb0cb1", "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": 27.8484848485, "max_line_length": 89, "alphanum_fraction": 0.5870511425, "num_tokens": 418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375735, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.48787350178917677}}
{"text": "//\n// Copyright 2005-2007 Adobe Systems Incorporated\n//\n// Distributed under the Boost Software License, Version 1.0\n// See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt\n//\n#ifndef BOOST_GIL_EXTENSION_NUMERIC_AFFINE_HPP\n#define BOOST_GIL_EXTENSION_NUMERIC_AFFINE_HPP\n\n#include <boost/gil/point.hpp>\n\nnamespace boost { namespace gil {\n\n////////////////////////////////////////////////////////////////////////////////////////\n///\n/// Simple matrix to do 2D affine transformations. It is actually 3x3 but the last column is [0 0 1]\n///\n////////////////////////////////////////////////////////////////////////////////////////\ntemplate <typename T>\nclass matrix3x2 {\npublic:\n    matrix3x2() : a(1), b(0), c(0), d(1), e(0), f(0) {}\n    matrix3x2(T A, T B, T C, T D, T E, T F) : a(A),b(B),c(C),d(D),e(E),f(F) {}\n    matrix3x2(const matrix3x2& mat) : a(mat.a), b(mat.b), c(mat.c), d(mat.d), e(mat.e), f(mat.f) {}\n    matrix3x2& operator=(const matrix3x2& m)           { a=m.a; b=m.b; c=m.c; d=m.d; e=m.e; f=m.f; return *this; }\n\n    matrix3x2& operator*=(const matrix3x2& m)          { (*this) = (*this)*m; return *this; }\n\n    static matrix3x2 get_rotate(T rads)                { T c=std::cos(rads); T s=std::sin(rads); return matrix3x2(c,s,-s,c,0,0); }\n    static matrix3x2 get_translate(point<T> const& t)\n    {\n        return matrix3x2(1, 0, 0, 1, t.x, t.y);\n    }\n    static matrix3x2 get_translate(T x, T y)           { return matrix3x2(1  ,0,0,1  ,x,  y  ); }\n    static matrix3x2 get_scale(point<T> const& s)\n    {\n        return matrix3x2(s.x, 0, 0, s.y, 0, 0);\n    }\n    static matrix3x2 get_scale(T x, T y)           { return matrix3x2(x,  0,0,y,  0  ,0  ); }\n    static matrix3x2 get_scale(T s)                { return matrix3x2(s  ,0,0,s  ,0  ,0  ); }\n\n    T a,b,c,d,e,f;\n};\n\ntemplate <typename T> BOOST_FORCEINLINE\nmatrix3x2<T> operator*(const matrix3x2<T>& m1, const matrix3x2<T>& m2) {\n    return matrix3x2<T>(\n                m1.a * m2.a + m1.b * m2.c,\n                m1.a * m2.b + m1.b * m2.d,\n                m1.c * m2.a + m1.d * m2.c,\n                m1.c * m2.b + m1.d * m2.d,\n                m1.e * m2.a + m1.f * m2.c + m2.e,\n                m1.e * m2.b + m1.f * m2.d + m2.f );\n}\n\ntemplate <typename T, typename F>\nBOOST_FORCEINLINE\npoint<F> operator*(point<T> const& p, matrix3x2<F> const& m)\n{\n    return { m.a*p.x + m.c*p.y + m.e, m.b*p.x + m.d*p.y + m.f };\n}\n\n////////////////////////////////////////////////////////////////////////////////////////\n/// Define affine mapping that transforms the source coordinates by the affine transformation\n////////////////////////////////////////////////////////////////////////////////////////\n/*\ntemplate <typename MapFn>\nconcept MappingFunctionConcept {\n    typename mapping_traits<MapFn>::result_type;   where PointNDConcept<result_type>;\n\n    template <typename Domain> { where PointNDConcept<Domain> }\n    result_type transform(MapFn&, const Domain& src);\n};\n*/\n\ntemplate <typename T> struct mapping_traits;\n\ntemplate <typename F>\nstruct mapping_traits<matrix3x2<F>>\n{\n    using result_type =  point<F>;\n};\n\ntemplate <typename F, typename F2>\nBOOST_FORCEINLINE\npoint<F> transform(matrix3x2<F> const& mat, point<F2> const& src)\n{\n    return src * mat;\n}\n\n}} // namespace boost::gil\n\n#endif\n", "meta": {"hexsha": "ebef93afcad5efbc5d2a8ef07a7c73f893b1625d", "size": 3290, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/gil/extension/numeric/affine.hpp", "max_stars_repo_name": "Harshitha91/Tmdb-react-native-node", "max_stars_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/gil/extension/numeric/affine.hpp", "max_issues_repo_name": "Harshitha91/Tmdb-react-native-node", "max_issues_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/gil/extension/numeric/affine.hpp", "max_forks_repo_name": "Harshitha91/Tmdb-react-native-node", "max_forks_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 34.6315789474, "max_line_length": 130, "alphanum_fraction": 0.5431610942, "num_tokens": 984, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4878735017891767}}
{"text": "/*\n * Software License Agreement (BSD License)\n *\n *  Copyright (c) 2009, Willow Garage, Inc.\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions\n *  are met:\n *\n *   * Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *   * Redistributions in binary form must reproduce the above\n *     copyright notice, this list of conditions and the following\n *     disclaimer in the documentation and/or other materials provided\n *     with the distribution.\n *   * Neither the name of Willow Garage, Inc. nor the names of its\n *     contributors may be used to endorse or promote products derived\n *     from this software without specific prior written permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n *  \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n *  POSSIBILITY OF SUCH DAMAGE.\n *\n */\n\n#include \"precomp.hpp\"\n\n// Eigen\n#include <Eigen/Core>\n\n// OpenCV\n#include <opencv2/core/eigen.hpp>\n#include <opencv2/sfm/robust.hpp>\n#include <opencv2/sfm/numeric.hpp>\n\n// libmv headers\n#include \"libmv/multiview/robust_fundamental.h\"\n\nusing namespace std;\n\nnamespace cv\n{\nnamespace sfm\n{\n\n// TODO: unify algorithms\ntemplate<typename T>\ndouble\nfundamentalFromCorrespondences8PointRobust( const Mat_<T> &_x1,\n                                            const Mat_<T> &_x2,\n                                            const double max_error,\n                                            Mat_<T> _F,\n                                            std::vector<int> &_inliers,\n                                            const double outliers_probability )\n{\n  libmv::Mat x1, x2;\n  libmv::Mat3 F;\n  libmv::vector<int> inliers;\n\n  cv2eigen( _x1, x1 );\n  cv2eigen( _x2, x2 );\n\n  T solution_error =\n    libmv::FundamentalFromCorrespondences8PointRobust( x1, x2, max_error, &F, &inliers, outliers_probability );\n\n  eigen2cv( F, _F );\n\n  // transform from libmv::vector to std::vector\n  int n = inliers.size();\n  _inliers.resize(n);\n  for( int i=0; i < n; ++i )\n  {\n    _inliers[i] = inliers.at(i);\n  }\n\n  return static_cast<double>(solution_error);\n}\n\n\ndouble\nfundamentalFromCorrespondences8PointRobust( InputArray _x1,\n                                            InputArray _x2,\n                                            double max_error,\n                                            OutputArray _F,\n                                            OutputArray _inliers,\n                                            double outliers_probability )\n{\n  const Mat x1 = _x1.getMat(), x2 = _x2.getMat();\n  const int depth =  x1.depth();\n  CV_Assert(x1.size() == x2.size() && (depth == CV_32F || depth == CV_64F));\n\n  _F.create(3, 3, depth);\n\n  Mat F = _F.getMat();\n  std::vector<int>& inliers = *(std::vector<int>*)_inliers.getObj();\n\n  double solution_error = 0.0;\n\n  // type\n  if( depth == CV_32F )\n  {\n    solution_error =\n      fundamentalFromCorrespondences8PointRobust<float>(\n        x1, x2, max_error, F, inliers, outliers_probability);\n  }\n  else\n  {\n    solution_error =\n      fundamentalFromCorrespondences8PointRobust<double>(\n        x1, x2, max_error, F, inliers, outliers_probability);\n  }\n\n  return solution_error;\n}\n\ntemplate<typename T>\ndouble\nfundamentalFromCorrespondences7PointRobust( const Mat_<T> &_x1,\n                                            const Mat_<T> &_x2,\n                                            const double max_error,\n                                            Mat_<T> _F,\n                                            std::vector<int> &_inliers,\n                                            const double outliers_probability )\n{\n  libmv::Mat x1, x2;\n  libmv::Mat3 F;\n  libmv::vector<int> inliers;\n\n  cv2eigen( _x1, x1 );\n  cv2eigen( _x2, x2 );\n\n  T solution_error =\n    libmv::FundamentalFromCorrespondences7PointRobust( x1, x2, max_error, &F, &inliers, outliers_probability );\n\n  eigen2cv( F, _F );\n\n  // transform from libmv::vector to std::vector\n  int n = inliers.size();\n  _inliers.resize(n);\n  for( int i=0; i < n; ++i )\n  {\n    _inliers[i] = inliers.at(i);\n  }\n\n  return static_cast<double>(solution_error);\n}\n\ndouble\nfundamentalFromCorrespondences7PointRobust( InputArray _x1,\n                                            InputArray _x2,\n                                            double max_error,\n                                            OutputArray _F,\n                                            OutputArray _inliers,\n                                            double outliers_probability )\n{\n  const Mat x1 = _x1.getMat(), x2 = _x2.getMat();\n  const int depth =  x1.depth();\n  CV_Assert(x1.size() == x2.size() && (depth == CV_32F || depth == CV_64F));\n\n  _F.create(3, 3, depth);\n\n  Mat F = _F.getMat();\n  std::vector<int>& inliers = *(std::vector<int>*)_inliers.getObj();\n\n  double solution_error = 0.0;\n\n  // type\n  if( depth == CV_32F )\n  {\n    solution_error =\n      fundamentalFromCorrespondences7PointRobust<float>(\n        x1, x2, max_error, F, inliers, outliers_probability);\n  }\n  else\n  {\n    solution_error =\n      fundamentalFromCorrespondences7PointRobust<double>(\n        x1, x2, max_error, F, inliers, outliers_probability);\n  }\n\n  return solution_error;\n}\n\n} /* namespace sfm */\n} /* namespace cv */", "meta": {"hexsha": "5116485bae0579da94b300539f1f419b7d7eeb7d", "size": 6019, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/sfm/src/robust.cpp", "max_stars_repo_name": "Nondzu/opencv_contrib", "max_stars_repo_head_hexsha": "0b0616a25d4239ee81fda965818b49b721620f56", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 7158.0, "max_stars_repo_stars_event_min_datetime": "2016-07-04T22:19:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T07:54:32.000Z", "max_issues_repo_path": "modules/sfm/src/robust.cpp", "max_issues_repo_name": "Nondzu/opencv_contrib", "max_issues_repo_head_hexsha": "0b0616a25d4239ee81fda965818b49b721620f56", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2184.0, "max_issues_repo_issues_event_min_datetime": "2016-07-05T12:04:14.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T19:10:12.000Z", "max_forks_repo_path": "modules/sfm/src/robust.cpp", "max_forks_repo_name": "Nondzu/opencv_contrib", "max_forks_repo_head_hexsha": "0b0616a25d4239ee81fda965818b49b721620f56", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5535.0, "max_forks_repo_forks_event_min_datetime": "2016-07-06T12:01:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T03:13:24.000Z", "avg_line_length": 30.8666666667, "max_line_length": 111, "alphanum_fraction": 0.6027579332, "num_tokens": 1454, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.487829844726708}}
{"text": "#include <Engine/MeshEdit/CParameterize.h>\n#include <Engine/MeshEdit/ARAP.h>\n#include <Engine/Primitive/TriMesh.h>\n#include <Engine/Scene/CmptGeometry.h>\n#include <Engine/Scene/CmptMaterial.h>\n#include <Engine/Material/BSDF_Frostbite.h>\n#include <Eigen/SVD>\n\nusing namespace Ubpa;\nusing namespace Eigen;\n\nARAP::ARAP(Ptr<SObj> triMeshObj, Ptr<TriMesh> triMesh, bool is_tex)\n\t: Paramaterize(triMeshObj, triMesh, is_tex, 0, 1)/* ASAP(triMeshObj, triMesh, true)*/ // Circle boundary and Naive mode\n{\n\tthis->is_tex = is_tex;\n\tInit(triMeshObj, triMesh);\n}\n\nvoid ARAP::Clear()\n{\n\tARAP_coeff.clear();\n\tLt_array.clear();\n\ttriangle_points.clear();\n}\n\nbool ARAP::Init(Ptr<SObj> triMeshObj, Ptr<TriMesh> triMesh)\n{\n\tARAP_mat_A = SparseMatrix<double>(nV , nV);\n\tARAP_mat_A.setZero();\n\tARAP_mat_b = MatrixXd(nV, 2);\n\tARAP_mat_b.setZero();\n\t//Initialize 1.map 3D triangles to 2d \n\tCongruentMapping2D();\n\n\t// Initialize 2. Select anchor points\n\tauto triangle = heMesh->Polygons().back();\n\tauto v1 = triangle->BoundaryVertice()[0];\n\tanchor_v1_idx = heMesh->Index(v1);\n\tauto v2 = triangle->BoundaryVertice()[1]; \n\tanchor_v2_idx = heMesh->Index(v2);\n\tsize_t tri_idx = heMesh->Index(triangle);\n\t//anchor_pos1 = pointf2(points2d[tri_idx][v1][0], points2d[tri_idx][v1][1]);\n\t//anchor_pos2 = pointf2(points2d[tri_idx][v2][0], points2d[tri_idx][v2][1]);\n\tanchor_pos2 = pointf2(1, 1);\n\t// Initialize 3. set coefficients of A \n\tsetCoefficientA(anchor_v1_idx, anchor_v2_idx);\n\n\t//Initialize 4. get initial parameterization \n\tthis->Run();\n\n\treturn true;\n}\n\nbool ARAP::RunARAP(int iter_n, double error_threshold = 0.01, int debug=5)\n{\n\t// set debug mode\n\tif (debug < 50) this->is_debug = false;\n\telse this->is_debug = true;\n\n\t// do local/global iteration\n\tcout <<\"iter:\" << iter_n << endl;\n\n\tfor (int i = 0; i < iter_n; i++)\n\t{\n\t\tlocalupdate();\n\t\tdouble max_error = globalupdate();\n\t\tcout << \"iter:\" << i << \" error: \" << max_error << endl;\n\t\tif (max_error < error_threshold) break;\n\t}\n\n\t// Finally, half-edge structure -> triangle mesh, end. \n\tvector<pointf3> positions;\n\tvector<unsigned> indice;\n\tpositions.reserve(nV);\n\tindice.reserve(3 * nT);\n\tfor (auto v : heMesh->Vertices())\n\t\tpositions.push_back(v->pos.cast_to<pointf3>());\n\tfor (auto f : heMesh->Polygons()) { // f is triangle\n\t\tfor (auto v : f->BoundaryVertice()) // vertices of the triangle\n\t\t\tindice.push_back(static_cast<unsigned>(heMesh->Index(v)));\n\t}\n\n\tif (this->is_tex)\n\t{\n\t\tthis->triMesh->Update(texCoor);\n\t}\n\telse\n\t{\n\t\tthis->triMesh->Update(positions);\n\t}\n\treturn true;\n}\n\nvoid ARAP::localupdate()\n{\n\tgetTrianglePoints();  // get the newest iteration result from trangle_points\n\tgetLt();\n}\n\ndouble ARAP::globalupdate()\n{\n\t// first, set b\n\tsetb(anchor_v1_idx, anchor_pos1, anchor_v2_idx, anchor_pos2);\n\tdouble max_error = -1 ; \n\t// Then solve the equation\n\tARAP_solution = ARAP_solver.solve(ARAP_mat_A.transpose() * ARAP_mat_b);\n\n\tif (is_debug) {\n\t\t//cout << MatrixXd(ARAP_mat_A) << endl << endl; // DEBUG\n\t\t//cout << \"b:\" << endl << ARAP_mat_b << endl << endl;\n\t\t//cout << \"solu:\" << endl << ARAP_solution << endl << endl;\n\t}\n\t\n\n\t// End, update textCoordinate\n\tthis->texCoor.clear();\n\tfor (size_t i = 0; i < nV; i++)\n\t{\n\t\tdouble dist = pointf3::distance(pointf3(ARAP_solution(i, 0), ARAP_solution(i, 1), 0.0), heMesh->Vertices()[i]->pos.cast_to<pointf3>());\n\t\tif (max_error < 0) \n\t\t{\n\t\t\tmax_error = dist;\n\t\t}\n\t\telse if(max_error < dist)\n\t\t{\n\t\t\tmax_error = dist;\n\t\t}\n\t\t\n\t\theMesh->Vertices()[i]->pos[0] = ARAP_solution(i, 0);\n\t\theMesh->Vertices()[i]->pos[1] = ARAP_solution(i, 1);\n\t\theMesh->Vertices()[i]->pos[2] = 0.0;\n\t\t// update tex coordinates\n\t\ttexCoor.push_back(pointf2(ARAP_solution(i, 0), ARAP_solution(i, 1)));\n\t}\n\n\treturn max_error;\n}\n\n/* Get newest u per iteration */\nvoid ARAP::getTrianglePoints()\n{\n\ttriangle_points.clear();\t// remember to clear\n\tfor (auto triangle : heMesh->Polygons())\n\t{\n\t\tif(triangle != nullptr)\n\t\t{\n\t\t\tthis->triangle_points.push_back(triangle->BoundaryVertice());\n\t\t}\n\t}\n}\n\nvoid ARAP::getLt()\n{\n\tassert(triangle_points.size() == nT);\n\tLt_array.clear();\n\n\tfor (size_t t = 0; t < nT; t++)\n\t{\n\t\tauto vec_u = triangle_points[t];\n\t\tauto mapped_u = points2d[t];\n\t\tMatrix2d St; \n\t\tSt.setZero();\n\n\t\t// get St\n\t\tfor (int i = 0; i < 3; i++)\n\t\t{\n\t\t\tV* u0 = vec_u[i];\n\t\t\tV* u1 = vec_u[(i+1)%3]; // % ?\n\t\t\tMatrixXd delta_u(2, 1);\n\t\t\tdelta_u <<\n\t\t\t\tu0->pos[0] - u1->pos[0], u0->pos[1] - u1->pos[1];\n\t\t\t\n\t\t\tpointf3 x0 = mapped_u[u0];\n\t\t\tpointf3 x1 = mapped_u[u1];\n\t\t\tMatrixXd delta_x(2, 1);\n\t\t\tdelta_x <<\n\t\t\t\tx0[0] - x1[0], x0[1] - x1[1];\n\n\t\t\tdouble cot = getCotan(t, vec_u[(i + 2) % 3]);\n\n\t\t\tSt += cot * delta_u * delta_x.transpose();\n\t\t}\n\n\t\t// Do SVD Composition on St\n\t\tJacobiSVD<MatrixXd> svd(St, ComputeThinU | ComputeThinV);\n\n\t\tMatrix2d Lt = svd.matrixU() * svd.matrixV().transpose(); // Lt = U * V^T\n\t\t/*cout << svd.matrixV().transpose() << endl << endl;*/ // DEBUG\n\t\t//if (Lt.determinant() < 0 )\n\t\t//{\n\t\t//\tif (is_debug) {\n\t\t//\t\t//cout << \"before\" << Lt.determinant() << endl;\n\t\t//\t}\n\t\t//\tMatrix2d newV;\n\t\t//\tnewV <<\n\t\t//\t\tsvd.matrixV().transpose()(0, 0), svd.matrixV().transpose()(0, 1),\n\t\t//\t\t-(svd.matrixV().transpose()(1, 0)), -(svd.matrixV().transpose()(1, 1));\n\t\t//\tif (is_debug) {\n\t\t//\t\t//cout << newV << endl;\n\t\t//\t}\n\t\t//\tLt = svd.matrixU() * newV;\n\t\t//\tassert(Lt.determinant() > 0);\n\t\t//}\n\n\t\tif (is_debug)\n\t\t{\n\t\t\tcout << Lt.determinant() << endl;\n\t\t\t//cout << svd.singularValues() << endl << endl;\n\t\t}\n\n\t\t//cout << Lt << endl; // DEBUG\n\t\t\n\t\t//Lt << 1, 0, 0, 1; // DEBUG\n \n\t\tLt_array.push_back(Lt);\n\t\t\n\t}\n\tassert(Lt_array.size() == nT);\n}\n\nvoid ARAP::setb(size_t idx1, pointf2 pos1, size_t idx2, pointf2 pos2)\n{\n\tARAP_mat_b.setZero();\n\n\t// two anchor points\n\t//ARAP_mat_b(idx1, 0) = pos1[0];  // x\n\t//ARAP_mat_b(idx1, 1) = pos1[1]; // y\n\n\tARAP_mat_b(idx2, 0) = pos2[0];  // x\n\tARAP_mat_b(idx2, 1) = pos2[1]; // y\n\n\t// Other non-anchor points\n\tfor (size_t i = 0; i < nV; i++)\n\t{\n\t\tif (/*i != idx1 && */i != idx2) {\n\t\t\tauto v = heMesh->Vertices()[i];\n\t\t\tMatrixXd b(2, 1);\n\t\t\tb.setZero();\n\t\t\t//cout << \"v idx: \" << heMesh->Index(v) << endl<<endl;\n\t\t\t// traverse adjecent vertrices\n\t\t\tfor (auto adj_v : v->AdjVertices())\n\t\t\t{\n\t\t\t\tsize_t adj_idx = heMesh->Index(adj_v);  // get index of adj_v\n\t\t\t\t// get adjacent triangles\n\t\t\t\tauto e = v->EdgeWith(adj_v);\n\t\t\t\tauto he1 = e->HalfEdge();\t\t\t\t\n\t\t\t\tauto he2 = e->HalfEdge()->Pair();\n\n\t\t\t\t// get Lt and cot\n\t\t\t\tauto triangle1 = he1->Polygon();\n\t\t\t\tif (triangle1 != nullptr)\n\t\t\t\t{\n\t\t\t\t\tauto tri_v1 = he1->Next()->End();\n\t\t\t\t\tassert(heMesh->Index(tri_v1) != heMesh->Index(v)\n\t\t\t\t\t\t&& heMesh->Index(tri_v1) != heMesh->Index(adj_v));\n\n\t\t\t\t\tsize_t tri_idx = heMesh->Index(triangle1);\n\t\t\t\t\tdouble cot1 = getCotan(tri_idx, tri_v1);\n\t\t\t\t\tmap<V*, pointf3> mapped_v = this->points2d[tri_idx]; // congruent mapping of triangle1 \n\t\t\t\t\tMatrixXd Lt = Lt_array[tri_idx];\n\t\t\t\t\tMatrixXd delta_x(2, 1);\n\t\t\t\t\tdelta_x <<\n\t\t\t\t\t\tmapped_v[v][0] - mapped_v[adj_v][0],\n\t\t\t\t\t\tmapped_v[v][1] - mapped_v[adj_v][1];\n\t\t\t\t\t/*cout << \"cot1:\" << cot1 << endl;\n\t\t\t\t\tcout << \"mapped_v[v]:\" << mapped_v[v][0] <<\",\" << mapped_v[v][1] << endl;\n\t\t\t\t\tcout << \"mapped_[adj_v]:\" << mapped_v[adj_v][0] << \",\" << mapped_v[adj_v][1] << endl;\n\t\t\t\t\tcout << \"cot1 * Lt * delta_x:\" << cot1 * Lt * delta_x << endl;\n\t\t\t\t\tcout << endl;*/\n\t\t\t\t\t\n\t\t\t\t\tb += cot1 * Lt * delta_x;\n\t\t\t\t}\n\n\t\t\t\tauto triangle2 = he2->Polygon();\n\t\t\t\tif (triangle2 != nullptr)\n\t\t\t\t{\n\t\t\t\t\tauto tri_v2 = he2->Next()->End();\n\t\t\t\t\tassert(heMesh->Index(tri_v2) != heMesh->Index(v)\n\t\t\t\t\t\t&& heMesh->Index(tri_v2) != heMesh->Index(adj_v));\n\n\t\t\t\t\tsize_t tri_idx = heMesh->Index(triangle2);\n\t\t\t\t\tdouble cot2 = getCotan(tri_idx, tri_v2);\n\t\t\t\t\tmap<V*, pointf3> mapped_v = this->points2d[tri_idx]; // congruent mapping of triangle1 \n\t\t\t\t\tMatrixXd Lt = Lt_array[tri_idx];\n\t\t\t\t\tMatrixXd delta_x(2, 1);\n\t\t\t\t\tdelta_x <<\n\t\t\t\t\t\tmapped_v[v][0] - mapped_v[adj_v][0],\n\t\t\t\t\t\tmapped_v[v][1] - mapped_v[adj_v][1];\n\n\t\t\t\t\t/*cout << \"cot2:\" << cot2 << endl;\n\t\t\t\t\tcout << \"mapped_v[v]:\" << mapped_v[v][0] << \",\" << mapped_v[v][1] << endl;\n\t\t\t\t\tcout << \"mapped_v[adj_v]:\" << mapped_v[adj_v][0] << \",\" << mapped_v[adj_v][1] << endl;\n\t\t\t\t\tcout << \"cot2 * Lt * delta_x:\" << cot2 * Lt * delta_x << endl;\n\t\t\t\t\tcout << endl;*/\n\t\t\t\t\tb += cot2 * Lt * delta_x;\n\t\t\t\t}\n\t\t\t}\n\t\t\tARAP_mat_b(i, 0) = b(0); // x\n\t\t\tARAP_mat_b(i, 1) = b(1); // y \n\t\t}\n\t}\n}\n\n\nvoid ARAP::setCoefficientA(size_t idx1, size_t idx2)\n{\n\t// Two Anchor points \n\t//ARAP_coeff.push_back(Eigen::Triplet<double>(idx1, idx1, 1));\n\tARAP_coeff.push_back(Eigen::Triplet<double>(idx2, idx2, 1));\n\n\t// Other non-anchor points\n\tfor (size_t i = 0; i < nV; i++)\n\t{\n\t\tif (/*i != idx1 &&*/ i != idx2) {\n\t\t\tauto v = heMesh->Vertices()[i];\n\t\t\tdouble cotan_sum = 0.0;\n\n\t\t\t// traverse adjacent vertrices\n\t\t\tfor (auto adj_v : v->AdjVertices())\n\t\t\t{\n\t\t\t\tsize_t adj_idx = heMesh->Index(adj_v);\n\n\t\t\t\t// To get cotan \n\t\t\t\tauto e = v->EdgeWith(adj_v);\n\t\t\t\tauto he1 = e->HalfEdge();\n\n\t\t\t\tdouble cot1 = 0.0;\n\t\t\t\tif (he1->Polygon() != nullptr)\n\t\t\t\t{\n\t\t\t\t\tauto tri1_idx = heMesh->Index(he1->Polygon()); // get index of adjacent triangle\n\t\t\t\t\ttry \n\t\t\t\t\t{\n\t\t\t\t\t\tauto tri_v1 = he1->Next()->End(); // get vertix of adjacent triangle \n\t\t\t\t\t\tassert(heMesh->Index(tri_v1) != heMesh->Index(v)\n\t\t\t\t\t\t\t&& heMesh->Index(tri_v1) != heMesh->Index(adj_v));\n\n\t\t\t\t\t\tcot1 = getCotan(tri1_idx, tri_v1);\n\t\t\t\t\t}\n\t\t\t\t\tcatch (const std::exception& e)\n\t\t\t\t\t{\n\t\t\t\t\t\tcout << \"cannot find cot 1 in map. \" << endl;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tauto he2 = e->HalfEdge()->Pair();\n\n\t\t\t\tdouble cot2 = 0.0;\n\t\t\t\tif (he2->Polygon() != nullptr)\n\t\t\t\t{\n\t\t\t\t\tauto tri2_idx = heMesh->Index(he2->Polygon());\n\t\t\t\t\ttry\n\t\t\t\t\t{\n\t\t\t\t\t\tauto tri_v2 = he2->Next()->End();\n\t\t\t\t\t\tassert(heMesh->Index(tri_v2) != heMesh->Index(v)\n\t\t\t\t\t\t\t&& heMesh->Index(tri_v2) != heMesh->Index(adj_v));\n\t\t\t\t\t\tcot2 = getCotan(tri2_idx, tri_v2);\n\t\t\t\t\t}\n\t\t\t\t\tcatch (const std::exception & e)\n\t\t\t\t\t{\n\t\t\t\t\t\tcout << \"cannot find cot 2 in map. \" << endl;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tARAP_coeff.push_back(Eigen::Triplet<double>(i, adj_idx, -(cot1 + cot2)));\n\n\t\t\t\tcotan_sum += (cot1 + cot2);\n\t\t\t}\n\n\t\t\tARAP_coeff.push_back(Eigen::Triplet<double>(i, i, cotan_sum));\n\t\t}\n\t}\n\tARAP_mat_A.setFromTriplets(ARAP_coeff.begin(), ARAP_coeff.end());\n\t// pre-computation\n\tARAP_mat_A.makeCompressed();\n\tARAP_solver.compute(ARAP_mat_A.transpose() * ARAP_mat_A);\n}", "meta": {"hexsha": "437c8ca772c3530d25abc5226a7584a2c059f958", "size": 10184, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Engine/MeshEdit/ARAP.cpp", "max_stars_repo_name": "Ricahrd-Li/ASAP_ARAP_Parameterization", "max_stars_repo_head_hexsha": "c12d83605ce9ea9cac29efbd991d21e2b363e375", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-12-19T03:56:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T16:17:12.000Z", "max_issues_repo_path": "src/Engine/MeshEdit/ARAP.cpp", "max_issues_repo_name": "Ricahrd-Li/ASAP_ARAP_Parameterization", "max_issues_repo_head_hexsha": "c12d83605ce9ea9cac29efbd991d21e2b363e375", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Engine/MeshEdit/ARAP.cpp", "max_forks_repo_name": "Ricahrd-Li/ASAP_ARAP_Parameterization", "max_forks_repo_head_hexsha": "c12d83605ce9ea9cac29efbd991d21e2b363e375", "max_forks_repo_licenses": ["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.1573333333, "max_line_length": 137, "alphanum_fraction": 0.6066378633, "num_tokens": 3519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.487829844726708}}
{"text": "#include \"stdafx.h\"\n#include <cmath>\n#include <fmt/format.h>\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n#include \"contest_types.h\"\n#include \"solver_registry.h\"\n#include \"visual_editor.h\"\n#include \"solver_util.h\"\n#include \"judge.h\"\n\nnamespace FitHoleSolver {\n\nnamespace bg = boost::geometry;\nusing BoostPoint = bg::model::d2::point_xy<double>;\nusing BoostPolygon = bg::model::polygon<BoostPoint>;\nusing BoostLinestring = bg::model::linestring<BoostPoint>;\n\ntemplate <typename T>\nvoid shrink(T& point_a, T& point_b) {\n  constexpr double eps = 1e-6;\n  auto shrink_a = point_a * (1.0 - eps) + point_b * eps;\n  auto shrink_b = point_b * (1.0 - eps) + point_a * eps;\n  point_a = shrink_a;\n  point_b = shrink_b;\n}\n\ntemplate <typename T>\nBoostPoint ToBoostPoint(const T& point) {\n  const auto [x, y] = point;\n  return BoostPoint(x, y);\n}\n\ntemplate <typename T>\nBoostPolygon ToBoostPolygon(const std::vector<T>& points) {\n  BoostPolygon polygon;\n  for (std::size_t i = 0; i <= points.size(); ++i) {\n    polygon.outer().push_back(ToBoostPoint(points[i % points.size()]));\n  }\n  if (bg::area(polygon) < 0.0) {\n    bg::reverse(polygon);\n  }\n  return polygon;\n}\n\ntemplate <typename T, typename U>\ndouble SquaredDistance(const T& vertex0, const U& vertex1) {\n  const auto [x0, y0] = vertex0;\n  const auto [x1, y1] = vertex1;\n  return (x0 - x1) * (x0 - x1) + (y0 - y1) * (y0 - y1);\n}\n\ntemplate <typename T>\ndouble SquaredEdgeLength(const T& vertices, const Edge& edge) {\n  const auto [a, b] = edge;\n  return SquaredDistance(vertices[a], vertices[b]);\n}\n\n\nclass Solver : public SolverBase {\n public:\n  SolverOutputs solve(const SolverArguments& args) override {\n    hole_ = args.problem->hole_polygon;\n    vertices_ = args.problem->vertices;\n    edges_ = args.problem->edges;\n    epsilon_ = args.problem->epsilon;\n    hole_polygon_ = ToBoostPolygon(hole_);\n\n    SVisualEditorPtr editor;\n    if (args.visualize) {\n      editor = std::make_shared<SVisualEditor>(args.problem, \"FitHoleSolver\", \"visualize\");\n    }\n\n    const int N = vertices_.size();\n    auto pose = vertices_;\n    double cost = std::numeric_limits<double>::infinity();\n    bool found_fit_in_hole = false;\n    std::vector<Point> best_feasible_pose;\n\n    SPinnedIndex pinned_index(rng_, N, editor);\n\n    const int num_iters = 10000;\n    const double T0 = 1.0e1;\n    const double T1 = 1.0e-2;\n    double progress = 0.0;\n\n    auto evaluate_and_descide_rollback = [&]() -> bool {\n      auto [feasible, updated_cost] = Evaluate(pose);\n\n      auto res = judge(*args.problem, pose);\n      if (res.fit_in_hole()) {\n        found_fit_in_hole = true;\n      }\n\n      const double T = std::pow(T0, 1.0 - progress) * std::pow(T1, progress);\n      if (std::uniform_real_distribution(0.0, 1.0)(rng_) < std::exp(-(updated_cost - cost) / T)) {\n        cost = updated_cost;\n        return false; // accepted\n      } else {\n        return true; // rejected\n      }\n    };\n    evaluate_and_descide_rollback();\n\n    auto single_small_change = [&] { // ynasu87 original\n      const int v = pinned_index.sample_movable_index();\n      const int dx = std::uniform_int_distribution(-5, 5)(rng_);\n      const int dy = std::uniform_int_distribution(-5, 5)(rng_);\n      auto& [x, y] = pose[v];\n      x += dx;\n      y += dy;\n      if (evaluate_and_descide_rollback()) {\n        x -= dx;\n        y -= dy;\n      }\n    };\n\n    auto shift = [&] {\n      const int dx = std::uniform_int_distribution(-2, 2)(rng_);\n      const int dy = std::uniform_int_distribution(-2, 2)(rng_);\n      auto pose_bak = pose;\n      for (int i : pinned_index.movable_indices) {\n        pose[i].first += dx;\n        pose[i].second += dy;\n      }\n      if (evaluate_and_descide_rollback()) {\n        pose = pose_bak;\n      }\n    };\n\n    using Action = std::function<void()>;\n    std::vector<std::pair<double, Action>> action_probs = {\n      {0.9, single_small_change},\n      {0.01, shift},\n    };\n    {\n      // normalize probs\n      double p = 0.0;\n      for (int i = 0; i < action_probs.size(); ++i) { p += action_probs[i].first; }\n      for (int i = 0; i < action_probs.size(); ++i) { action_probs[i].first /= p; }\n    }\n\n    for (int iter = 0; iter < num_iters; ++iter) {\n      progress = 1.0 * iter / num_iters;\n\n      if (found_fit_in_hole) {\n        LOG(INFO) << fmt::format(\"found fit in hole iter = {}\", iter);\n        break;\n      }\n\n      if (iter < 100) {\n        shift();\n      } else {\n        const double p_action = std::uniform_real_distribution(0.0, 1.0)(rng_);\n        double p_accum = 0.0;\n        for (int i = 0; i < action_probs.size(); ++i) { \n          p_accum += action_probs[i].first;\n          if (p_action < p_accum) {\n            action_probs[i].second();\n          }\n        }\n      }\n\n      if (editor && iter % 100 == 0) {\n        editor->set_oneshot_custom_stat(fmt::format(\"iter = {}/{}\", iter, num_iters));\n        editor->set_pose(args.problem->create_solution(pose));\n        if (auto show_result = editor->show(1); show_result.edit_result) {\n          pose = show_result.edit_result->pose_after_edit->vertices;\n          pinned_index.update_movable_index();\n        }\n      }\n\n    }\n\n    SolverOutputs outputs;\n    outputs.solution = args.problem->create_solution(pose);\n\n    return outputs;\n  }\n\n  template <typename P>\n  std::tuple<bool, double> Evaluate(const std::vector<P>& pose) const {\n    double deformation_cost = 0.0;\n    double protrusion_cost = 0.0;\n    double dislikes_cost = 0.0;\n\n    const double tolerance = epsilon_ / 1'000'000.0;\n    for (const auto& vertex : pose) {\n      protrusion_cost += bg::distance(ToBoostPoint(vertex), hole_polygon_);\n    }\n    for (const auto& edge : edges_) {\n      const auto [a, b] = edge;\n      Point2d pa = pose[a];\n      Point2d pb = pose[b];\n      shrink(pa, pb);\n      BoostLinestring linestring{ToBoostPoint(pa), ToBoostPoint(pb)};\n      std::vector<BoostLinestring> differences;\n      bg::difference(linestring, hole_polygon_, differences);\n      for (const auto& segment : differences) {\n        protrusion_cost += 1.0e1 * bg::length(segment);\n      }\n\n      const auto d0 = SquaredEdgeLength(vertices_, edge);\n      const auto d1 = SquaredEdgeLength(pose, edge);\n      deformation_cost += 1.0e1 * std::max(0.0, std::abs(d1 / d0 - 1.0) - tolerance);\n    }\n\n    const bool feasible = deformation_cost + protrusion_cost == 0.0;\n    const double cost = deformation_cost + protrusion_cost + dislikes_cost;\n\n    return {feasible, cost};\n  }\n\n private:\n  std::mt19937 rng_;\n  std::vector<Point> hole_;\n  std::vector<Point> vertices_;\n  std::vector<Edge> edges_;\n  integer epsilon_;\n  BoostPolygon hole_polygon_;\n};\n\n}\n\nREGISTER_SOLVER(\"FitHoleSolver\", FitHoleSolver::Solver);\n// vim:ts=2 sw=2 sts=2 et ci\n", "meta": {"hexsha": "07e9f45e256abc397224b29614fede2805aa586e", "size": 6769, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/solvers/fit_hole_solver.cpp", "max_stars_repo_name": "nodchip/icfpc2021", "max_stars_repo_head_hexsha": "e50f0172fd62097049dab19c01875c57468a13f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-12T13:52:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-12T13:52:18.000Z", "max_issues_repo_path": "src/solvers/fit_hole_solver.cpp", "max_issues_repo_name": "nodchip/icfpc2021", "max_issues_repo_head_hexsha": "e50f0172fd62097049dab19c01875c57468a13f1", "max_issues_repo_licenses": ["MIT"], "max_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/fit_hole_solver.cpp", "max_forks_repo_name": "nodchip/icfpc2021", "max_forks_repo_head_hexsha": "e50f0172fd62097049dab19c01875c57468a13f1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-24T08:49:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-24T08:49:18.000Z", "avg_line_length": 29.6885964912, "max_line_length": 98, "alphanum_fraction": 0.6253508642, "num_tokens": 1879, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4878298387108655}}
{"text": "#include <boost/simd/include/functions/shuffle.hpp>\n#include <boost/simd/sdk/simd/pack.hpp>\n#include <boost/simd/sdk/simd/io.hpp>\n#include <boost/mpl/int.hpp>\n#include <iostream>\n\nusing boost::mpl::int_;\nusing boost::simd::pack;\nusing boost::simd::shuffle;\n\nstruct even_odd\n{\n  template<class Index, class Cardinal>\n  struct apply  : int_< Index::value < Cardinal::value/2\n                      ? Index::value * 2\n                      : (Index::value-Cardinal::value/2) * 2 + 1\n                      >\n  {};\n};\n\nint main()\n{\n  pack<float,4> f(1,2,3,4);\n\n  // Gather even and odd indexes on the side: [ 1 3 2 4 ]\n  std::cout << shuffle<even_odd>(f) << \"\\n\";\n}\n", "meta": {"hexsha": "edbab1d0cc92a32a8c59dca575b13f15ceb2d580", "size": 660, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/base/examples/swar/shuffle_perm1.cpp", "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/examples/swar/shuffle_perm1.cpp", "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/examples/swar/shuffle_perm1.cpp", "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": 23.5714285714, "max_line_length": 64, "alphanum_fraction": 0.5984848485, "num_tokens": 190, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7931059414036511, "lm_q2_score": 0.6150878625719088, "lm_q1q2_score": 0.4878298382910533}}
{"text": "/*\n * This file is part of the Interpolated Polyline (https://github.com/fzi-forschungszentrum-informatik/P3IV),\n * copyright by FZI Forschungszentrum Informatik, licensed under the BSD-3 license (see LICENSE file in main directory)\n */\n\n#pragma once\n\n#include <chrono>\n#include <boost/math/interpolators/barycentric_rational.hpp>\n\nnamespace p3iv_utils {\n\nstd::vector<double> chrono2double(const std::vector<std::chrono::milliseconds>& t) {\n    std::vector<double> x;\n    x.reserve(t.size());\n    for (auto t_ : t) {\n        x.push_back(t_.count());\n    }\n    return x;\n}\n\ntemplate <typename T>\ninline std::vector<T> interpolate(const std::vector<T>& xBase,\n                                  const std::vector<T>& yBase,\n                                  const std::vector<T>& xIntrp) {\n\n    boost::math::barycentric_rational<T> interpolant(xBase.data(), yBase.data(), yBase.size());\n    std::vector<T> yIntrp;\n    yIntrp.reserve(xIntrp.size());\n\n    for (auto& x : xIntrp) {\n        yIntrp.push_back(interpolant(x));\n    }\n\n    return yIntrp;\n}\n\ntemplate <typename T>\ninline std::vector<T> interpolate(const std::vector<std::chrono::milliseconds>& tBase,\n                                  const std::vector<T>& yBase,\n                                  const std::vector<std::chrono::milliseconds>& tIntrp) {\n\n    std::vector<double> xBase = chrono2double(tBase);\n    std::vector<double> xIntrp = chrono2double(tIntrp);\n\n    auto yIntrp = interpolate(xBase, yBase, xIntrp);\n\n    return yIntrp;\n}\n\n\n} // namespace p3iv_utils", "meta": {"hexsha": "8cf181b8053c89c01f36392dcfdaa161157056b2", "size": 1523, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "p3iv_utils/include/p3iv_utils/interpolation.hpp", "max_stars_repo_name": "fzi-forschungszentrum-informatik/P3IV", "max_stars_repo_head_hexsha": "51784e6dc03dcaa0ad58a5078475fa4daec774bd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-07-27T06:56:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T11:21:30.000Z", "max_issues_repo_path": "p3iv_utils/include/p3iv_utils/interpolation.hpp", "max_issues_repo_name": "fzi-forschungszentrum-informatik/P3IV", "max_issues_repo_head_hexsha": "51784e6dc03dcaa0ad58a5078475fa4daec774bd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "p3iv_utils/include/p3iv_utils/interpolation.hpp", "max_forks_repo_name": "fzi-forschungszentrum-informatik/P3IV", "max_forks_repo_head_hexsha": "51784e6dc03dcaa0ad58a5078475fa4daec774bd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-10-10T01:56:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-10T01:56:44.000Z", "avg_line_length": 29.2884615385, "max_line_length": 119, "alphanum_fraction": 0.6309914642, "num_tokens": 403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105941403651, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4878298326950228}}
{"text": "/*\n * EllipseIterator.hpp\n *\n *  Created on: Dec 2, 2015\n *      Author: P\u00e9ter Fankhauser\n *   Institute: ETH Zurich, Autonomous Systems Lab\n */\n\n#pragma once\n\n#include \"grid_map_core/GridMap.hpp\"\n#include \"grid_map_core/iterators/SubmapIterator.hpp\"\n\n// Eigen\n#include <Eigen/Core>\n\n// unique_ptr\n#include <memory>\n\nnamespace grid_map {\n\n/*!\n * Iterator class to iterate through a ellipsoid area of the map.\n * The main axis of the ellipse are aligned with the map frame.\n */\nclass EllipseIterator\n{\npublic:\n\n  /*!\n   * Constructor.\n   * @param gridMap the grid map to iterate on.\n   * @param center the position of the ellipse center.\n   * @param length the length of the main axis.\n   * @param angle the rotation angle of the ellipse (in [rad]).\n   */\n  EllipseIterator(const GridMap& gridMap, const Position& center, const Length& length, const double rotation = 0.0);\n\n  /*!\n   * Assignment operator.\n   * @param iterator the iterator to copy data from.\n   * @return a reference to *this.\n   */\n  EllipseIterator& operator =(const EllipseIterator& other);\n\n  /*!\n   * Compare to another iterator.\n   * @return whether the current iterator points to a different address than the other one.\n   */\n  bool operator !=(const EllipseIterator& other) const;\n\n  /*!\n   * Dereference the iterator with const.\n   * @return the value to which the iterator is pointing.\n   */\n  const Index& operator *() const;\n\n  /*!\n   * Increase the iterator to the next element.\n   * @return a reference to the updated iterator.\n   */\n  EllipseIterator& operator ++();\n\n  /*!\n   * Indicates if iterator is past end.\n   * @return true if iterator is out of scope, false if end has not been reached.\n   */\n  bool isPastEnd() const;\n\n  /*!\n   * Returns the size of the submap covered by the iterator.\n   * @return the size of the submap covered by the iterator.\n   */\n  const Size& getSubmapSize() const;\n\nprivate:\n\n  /*!\n   * Check if current index is inside the ellipse.\n   * @return true if inside, false otherwise.\n   */\n  bool isInside() const;\n\n  /*!\n   * Finds the submap that fully contains the ellipse and returns the parameters.\n   * @param[in] center the position of the ellipse center.\n   * @param[in] length the length of the main axis.\n   * @param[in] angle the rotation angle of the ellipse (in [rad]).\n   * @param[out] startIndex the start index of the submap.\n   * @param[out] bufferSize the buffer size of the submap.\n   */\n  void findSubmapParameters(const Position& center, const Length& length, const double rotation,\n                            Index& startIndex, Size& bufferSize) const;\n\n  //! Position of the circle center;\n  Position center_;\n\n  //! Square length of the semi axis.\n  Eigen::Array2d semiAxisSquare_;\n\n  //! Sine and cosine values of the rotation angle as transformation matrix.\n  Eigen::Matrix2d transformMatrix_;\n\n  //! Grid submap iterator. // TODO Think of using unique_ptr instead.\n  std::shared_ptr<SubmapIterator> internalIterator_;\n\n  //! Map information needed to get position from iterator.\n  Length mapLength_;\n  Position mapPosition_;\n  double resolution_;\n  Size bufferSize_;\n  Index bufferStartIndex_;\n};\n\n} /* namespace */\n", "meta": {"hexsha": "0f61d5bc60daaff0365b6ad92dc3b77a58f1fd9d", "size": 3156, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "grid_map_core/include/grid_map_core/iterators/EllipseIterator.hpp", "max_stars_repo_name": "yuzhangbit/grid_map", "max_stars_repo_head_hexsha": "9b81f159cc6f6a9b06dcb73866138081bd700b05", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "grid_map_core/include/grid_map_core/iterators/EllipseIterator.hpp", "max_issues_repo_name": "yuzhangbit/grid_map", "max_issues_repo_head_hexsha": "9b81f159cc6f6a9b06dcb73866138081bd700b05", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "grid_map_core/include/grid_map_core/iterators/EllipseIterator.hpp", "max_forks_repo_name": "yuzhangbit/grid_map", "max_forks_repo_head_hexsha": "9b81f159cc6f6a9b06dcb73866138081bd700b05", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-09-02T04:08:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-23T11:42:35.000Z", "avg_line_length": 27.2068965517, "max_line_length": 117, "alphanum_fraction": 0.6926489227, "num_tokens": 745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.4878129466644465}}
{"text": "/**\n * @file tests/ub_tree_test.cpp\n * @author Mikhail Lozhnikov\n *\n * Tests for the UB tree.\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#include <mlpack/core.hpp>\n#include <mlpack/core/tree/bounds.hpp>\n#include <mlpack/methods/neighbor_search/neighbor_search.hpp>\n#include <mlpack/core/tree/binary_space_tree.hpp>\n\n#include <boost/test/unit_test.hpp>\n\nusing namespace mlpack;\nusing namespace mlpack::math;\nusing namespace mlpack::tree;\nusing namespace mlpack::metric;\nusing namespace mlpack::bound;\nusing namespace mlpack::neighbor;\n\nBOOST_AUTO_TEST_SUITE(UBTreeTest);\n\nBOOST_AUTO_TEST_CASE(AddressTest)\n{\n  typedef double ElemType;\n  typedef typename std::conditional<sizeof(ElemType) * CHAR_BIT <= 32,\n                                    uint32_t,\n                                    uint64_t>::type AddressElemType;\n  arma::Mat<ElemType> dataset(8, 1000);\n\n  dataset.randu();\n  dataset -= 0.5;\n  arma::Col<AddressElemType> address(dataset.n_rows);\n  arma::Col<ElemType> point(dataset.n_rows);\n\n  // Ensure that this is one-to-one transform.\n  for (size_t i = 0; i < dataset.n_cols; ++i)\n  {\n    addr::PointToAddress(address, dataset.col(i));\n    addr::AddressToPoint(point, address);\n\n    for (size_t k = 0; k < dataset.n_rows; ++k)\n      BOOST_REQUIRE_CLOSE(dataset(k, i), point[k], 1e-13);\n  }\n}\n\ntemplate<typename TreeType>\nvoid CheckSplit(const TreeType& tree)\n{\n  typedef typename TreeType::ElemType ElemType;\n  typedef typename std::conditional<sizeof(ElemType) * CHAR_BIT <= 32,\n                                    uint32_t,\n                                    uint64_t>::type AddressElemType;\n\n  if (tree.IsLeaf())\n    return;\n\n  arma::Col<AddressElemType> lo(tree.Bound().Dim());\n  arma::Col<AddressElemType> hi(tree.Bound().Dim());\n\n  lo.fill(std::numeric_limits<AddressElemType>::max());\n  hi.fill(0);\n\n  arma::Col<AddressElemType> address(tree.Bound().Dim());\n\n  // Find the highest address of the left node.\n  for (size_t i = 0; i < tree.Left()->NumDescendants(); ++i)\n  {\n    addr::PointToAddress(address,\n        tree.Dataset().col(tree.Left()->Descendant(i)));\n\n    if (addr::CompareAddresses(address, hi) > 0)\n      hi = address;\n  }\n\n  // Find the lowest address of the right node.\n  for (size_t i = 0; i < tree.Right()->NumDescendants(); ++i)\n  {\n    addr::PointToAddress(address,\n        tree.Dataset().col(tree.Right()->Descendant(i)));\n\n    if (addr::CompareAddresses(address, lo) < 0)\n      lo = address;\n  }\n\n  // Addresses in the left node should be less than addresses in the right node.\n  BOOST_REQUIRE_LE(addr::CompareAddresses(hi, lo), 0);\n\n  CheckSplit(*tree.Left());\n  CheckSplit(*tree.Right());\n}\n\nBOOST_AUTO_TEST_CASE(UBTreeSplitTest)\n{\n  typedef UBTree<EuclideanDistance, EmptyStatistic, arma::mat> TreeType;\n  arma::mat dataset(8, 1000);\n\n  dataset.randu();\n\n  TreeType tree(dataset);\n  CheckSplit(tree);\n}\n\ntemplate<typename TreeType>\nvoid CheckBound(const TreeType& tree)\n{\n  typedef typename TreeType::ElemType ElemType;\n  for (size_t i = 0; i < tree.NumDescendants(); ++i)\n  {\n    arma::Col<ElemType> point = tree.Dataset().col(tree.Descendant(i));\n\n    // Check that the point is contained in the bound.\n    BOOST_REQUIRE_EQUAL(true, tree.Bound().Contains(point));\n\n    const arma::Mat<ElemType>& loBound = tree.Bound().LoBound();\n    const arma::Mat<ElemType>& hiBound = tree.Bound().HiBound();\n\n    // Ensure that there is a hyperrectangle that contains the point.\n    bool success = false;\n    for (size_t j = 0; j < tree.Bound().NumBounds(); ++j)\n    {\n      success = true;\n      for (size_t k = 0; k < loBound.n_rows; ++k)\n      {\n        if (point[k] < loBound(k, j) - 1e-14 * std::fabs(loBound(k, j)) ||\n            point[k] > hiBound(k, j) + 1e-14 * std::fabs(hiBound(k, j)))\n        {\n          success = false;\n          break;\n        }\n      }\n      if (success)\n        break;\n    }\n\n    BOOST_REQUIRE_EQUAL(success, true);\n  }\n\n  if (!tree.IsLeaf())\n  {\n    CheckBound(*tree.Left());\n    CheckBound(*tree.Right());\n  }\n}\n\nBOOST_AUTO_TEST_CASE(UBTreeBoundTest)\n{\n  typedef UBTree<EuclideanDistance, EmptyStatistic, arma::mat> TreeType;\n  arma::mat dataset(8, 1000);\n\n  dataset.randu();\n\n  TreeType tree(dataset);\n  CheckBound(tree);\n}\n\n// Ensure that MinDistance() and MaxDistance() works correctly.\ntemplate<typename TreeType, typename MetricType>\nvoid CheckDistance(TreeType& tree, TreeType* node = NULL)\n{\n  typedef typename TreeType::ElemType ElemType;\n  if (node == NULL)\n  {\n    node = &tree;\n\n    while (node->Parent() != NULL)\n      node = node->Parent();\n\n    CheckDistance<TreeType, MetricType>(tree, node);\n\n    for (size_t j = 0; j < tree.Dataset().n_cols; ++j)\n    {\n      const arma::Col<ElemType>& point = tree.  Dataset().col(j);\n      ElemType maxDist = 0;\n      ElemType minDist = std::numeric_limits<ElemType>::max();\n      for (size_t i = 0; i < tree.NumDescendants(); ++i)\n      {\n        ElemType dist = MetricType::Evaluate(\n            tree.Dataset().col(tree.Descendant(i)),\n            tree.Dataset().col(j));\n\n        if (dist > maxDist)\n          maxDist = dist;\n        if (dist < minDist)\n          minDist = dist;\n      }\n\n      BOOST_REQUIRE_LE(tree.Bound().MinDistance(point), minDist *\n          (1.0 + 10 * std::numeric_limits<ElemType>::epsilon()));\n      BOOST_REQUIRE_LE(maxDist, tree.Bound().MaxDistance(point) *\n          (1.0 + 10 * std::numeric_limits<ElemType>::epsilon()));\n\n      math::RangeType<ElemType> r = tree.Bound().RangeDistance(point);\n\n      BOOST_REQUIRE_LE(r.Lo(), minDist *\n          (1.0 + 10 * std::numeric_limits<ElemType>::epsilon()));\n      BOOST_REQUIRE_LE(maxDist, r.Hi() *\n          (1.0 + 10 * std::numeric_limits<ElemType>::epsilon()));\n    }\n\n    if (!tree.IsLeaf())\n    {\n      CheckDistance<TreeType, MetricType>(*tree.Left());\n      CheckDistance<TreeType, MetricType>(*tree.Right());\n    }\n  }\n  else\n  {\n    if (&tree != node)\n    {\n      ElemType maxDist = 0;\n      ElemType minDist = std::numeric_limits<ElemType>::max();\n      for (size_t i = 0; i < tree.NumDescendants(); ++i)\n        for (size_t j = 0; j < node->NumDescendants(); ++j)\n        {\n          ElemType dist = MetricType::Evaluate(\n              tree.Dataset().col(tree.Descendant(i)),\n              node->Dataset().col(node->Descendant(j)));\n\n          if (dist > maxDist)\n            maxDist = dist;\n          if (dist < minDist)\n            minDist = dist;\n        }\n\n      BOOST_REQUIRE_LE(tree.Bound().MinDistance(node->Bound()), minDist *\n          (1.0 + 10 * std::numeric_limits<ElemType>::epsilon()));\n      BOOST_REQUIRE_LE(maxDist, tree.Bound().MaxDistance(node->Bound()) *\n          (1.0 + 10 * std::numeric_limits<ElemType>::epsilon()));\n\n      math::RangeType<ElemType> r = tree.Bound().RangeDistance(node->Bound());\n\n      BOOST_REQUIRE_LE(r.Lo(), minDist *\n          (1.0 + 10 * std::numeric_limits<ElemType>::epsilon()));\n      BOOST_REQUIRE_LE(maxDist, r.Hi() *\n          (1.0 + 10 * std::numeric_limits<ElemType>::epsilon()));\n    }\n    if (!node->IsLeaf())\n    {\n      CheckDistance<TreeType, MetricType>(tree, node->Left());\n      CheckDistance<TreeType, MetricType>(tree, node->Right());\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE(UBTreeDistanceTest)\n{\n  typedef UBTree<EuclideanDistance, EmptyStatistic, arma::mat> TreeType;\n  arma::mat dataset(8, 200);\n\n  dataset.randu();\n\n  TreeType tree(dataset);\n  CheckDistance<TreeType, EuclideanDistance>(tree);\n}\n\n\nBOOST_AUTO_TEST_CASE(UBTreeTest)\n{\n  typedef UBTree<EuclideanDistance, EmptyStatistic, arma::mat> TreeType;\n\n  size_t maxRuns = 10; // Ten total tests.\n  size_t pointIncrements = 1000; // Range is from 2000 points to 11000.\n\n  // We use the default leaf size of 20.\n  for (size_t run = 0; run < maxRuns; run++)\n  {\n    size_t dimensions = run + 2;\n    size_t maxPoints = (run + 1) * pointIncrements;\n\n    size_t size = maxPoints;\n    arma::mat dataset = arma::mat(dimensions, size);\n    arma::mat datacopy; // Used to test mappings.\n\n    // Mappings for post-sort verification of data.\n    std::vector<size_t> newToOld;\n    std::vector<size_t> oldToNew;\n\n    // Generate data.\n    dataset.randu();\n\n    // Build the tree itself.\n    TreeType root(dataset, newToOld, oldToNew);\n    const arma::mat& treeset = root.Dataset();\n\n    // Ensure the size of the tree is correct.\n    BOOST_REQUIRE_EQUAL(root.NumDescendants(), size);\n\n    // Check the forward and backward mappings for correctness.\n    for (size_t i = 0; i < size; ++i)\n    {\n      for (size_t j = 0; j < dimensions; ++j)\n      {\n        BOOST_REQUIRE_EQUAL(treeset(j, i), dataset(j, newToOld[i]));\n        BOOST_REQUIRE_EQUAL(treeset(j, oldToNew[i]), dataset(j, i));\n      }\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE(SingleTreeTraverserTest)\n{\n  arma::mat dataset;\n  dataset.randu(8, 1000); // 1000 points in 8 dimensions.\n  arma::Mat<size_t> neighbors1;\n  arma::mat distances1;\n  arma::Mat<size_t> neighbors2;\n  arma::mat distances2;\n\n  // Nearest neighbor search with the UB tree.\n  NeighborSearch<NearestNS, metric::LMetric<2, true>, arma::mat,\n      UBTree> knn1(dataset, SINGLE_TREE_MODE);\n\n  knn1.Search(5, neighbors1, distances1);\n\n  // Nearest neighbor search the naive way.\n  KNN knn2(dataset, NAIVE_MODE);\n\n  knn2.Search(5, neighbors2, distances2);\n\n  for (size_t i = 0; i < neighbors1.size(); ++i)\n  {\n    BOOST_REQUIRE_EQUAL(neighbors1[i], neighbors2[i]);\n    BOOST_REQUIRE_EQUAL(distances1[i], distances2[i]);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(DualTreeTraverserTest)\n{\n  arma::mat dataset;\n  dataset.randu(8, 1000); // 1000 points in 8 dimensions.\n  arma::Mat<size_t> neighbors1;\n  arma::mat distances1;\n  arma::Mat<size_t> neighbors2;\n  arma::mat distances2;\n\n  // Nearest neighbor search with the UB tree.\n  NeighborSearch<NearestNS, metric::LMetric<2, true>, arma::mat,\n      UBTree> knn1(dataset, DUAL_TREE_MODE);\n\n  knn1.Search(5, neighbors1, distances1);\n\n  // Nearest neighbor search the naive way.\n  KNN knn2(dataset, NAIVE_MODE);\n\n  knn2.Search(5, neighbors2, distances2);\n\n  for (size_t i = 0; i < neighbors1.size(); ++i)\n  {\n    BOOST_REQUIRE_EQUAL(neighbors1[i], neighbors2[i]);\n    BOOST_REQUIRE_EQUAL(distances1[i], distances2[i]);\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "b1fb57b0bf5dd3bc6e29d81a285892a0093d926b", "size": 10361, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/ub_tree_test.cpp", "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/tests/ub_tree_test.cpp", "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/tests/ub_tree_test.cpp", "max_forks_repo_name": "R-Aravind/mlpack", "max_forks_repo_head_hexsha": "99d11a9b4d379885cf7f8160d8c71fb792fa1bbc", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-20T19:38:10.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-20T19:38:10.000Z", "avg_line_length": 28.7008310249, "max_line_length": 80, "alphanum_fraction": 0.6416369076, "num_tokens": 2812, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.4878129466644465}}
{"text": "// The MIT License (MIT)\n//\n// Copyright (c) 2016 Darrell Wright\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files( the \"Software\" ), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n#include <boost/algorithm/string/predicate.hpp>\n#include <cmath>\n\n#include \"data_types.h\"\n#include \"round_basal.h\"\n\nnamespace ns {\n\tauto round_basal( double const & basal, profile_t const & profile ) {\n\t\t/*\n\t\t * x23 and x54 pumps change basal increment depending on how much basal is being delivered:\n\t\t * 0.025u for 0.025 < x < 0.975\n\t\t * 0.05u for 1 < x < 9.95\n\t\t * 0.1u for 10 < x\n\t\t * To round numbers nicely for the pump, use a scale factor of (1 / increment).\n\t\t */\n\t\tauto const lowest_rate_scale = [&profile]( ) -> double { \n\t\t\tif( profile.model ) {\n\t\t\t\tauto const & model = *profile.model;\n\t\t\t\tif( boost::algorithm::ends_with( model, \"54\" ) || boost::algorithm::ends_with( model, \"23\" ) ) {\n\t\t\t\t\treturn 40;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn 20;\n\t\t}( );\n\t\tassert( basal > 0 );\n\t\tif( basal < 1 ) {\n\t\t\treturn round( basal * lowest_rate_scale)/lowest_rate_scale;\n\t\t} else if( basal < 10 ) {\n\t\t\treturn round( basal * 20.0 )/20.0;\n\t\t}\n\t\treturn round( basal * 10.0 )/10.0;\t\n\t}\n}    // namespace ns \n\n", "meta": {"hexsha": "411bf7d7ae8e5102c9b4d7cdad8b1293ced0c637", "size": 2131, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/round_basal.cpp", "max_stars_repo_name": "beached/oref0_cpp", "max_stars_repo_head_hexsha": "f3cc43948aeae7f857a6618588f44ace601099d6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-12-18T08:58:57.000Z", "max_stars_repo_stars_event_max_datetime": "2016-12-18T08:58:57.000Z", "max_issues_repo_path": "src/round_basal.cpp", "max_issues_repo_name": "beached/oref0_cpp", "max_issues_repo_head_hexsha": "f3cc43948aeae7f857a6618588f44ace601099d6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/round_basal.cpp", "max_forks_repo_name": "beached/oref0_cpp", "max_forks_repo_head_hexsha": "f3cc43948aeae7f857a6618588f44ace601099d6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-12-18T08:59:04.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-01T21:40:22.000Z", "avg_line_length": 37.3859649123, "max_line_length": 100, "alphanum_fraction": 0.6959174097, "num_tokens": 557, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.48781294011025145}}
{"text": "/**\n * @file newproblem_main.cc\n * @brief NPDE homework NewProblem code\n * @author Oliver Rietmann, Erick Schulz\n * @date 01.01.2020\n * @copyright Developed at ETH Zurich\n */\n\n#include <Eigen/Core>\n#include <iostream>\n\n#include \"newproblem.h\"\n\nint main() {\n  Eigen::VectorXd v = NewProblem::dummyFunction(0.0, 0);\n\n  const static Eigen::IOFormat CSVFormat(Eigen::FullPrecision,\n                                         Eigen::DontAlignCols, \", \", \"\\n\");\n  std::cout << v.transpose().format(CSVFormat) << std::endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "06077b1e3fd2260b7732b8bbabafb022e6e61907", "size": 530, "ext": "cc", "lang": "C++", "max_stars_repo_path": "scripts/NewProblem/mastersolution/newproblem_main.cc", "max_stars_repo_name": "0xBachmann/NPDECODES", "max_stars_repo_head_hexsha": "70a9d251033ab3d8719f0e221de4c2f4e9e8f4ea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-22T10:59:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T10:59:19.000Z", "max_issues_repo_path": "scripts/NewProblem/mastersolution/newproblem_main.cc", "max_issues_repo_name": "0xBachmann/NPDECODES", "max_issues_repo_head_hexsha": "70a9d251033ab3d8719f0e221de4c2f4e9e8f4ea", "max_issues_repo_licenses": ["MIT"], "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/NewProblem/mastersolution/newproblem_main.cc", "max_forks_repo_name": "0xBachmann/NPDECODES", "max_forks_repo_head_hexsha": "70a9d251033ab3d8719f0e221de4c2f4e9e8f4ea", "max_forks_repo_licenses": ["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.0434782609, "max_line_length": 75, "alphanum_fraction": 0.6339622642, "num_tokens": 141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297745935070806, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.4878129391769008}}
{"text": "// a random number generator supporting different distributions.\n//\n//  Copyright Steven Ross 2009.\n//\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n//  See http://www.boost.org/libs/sort for library home page.\n\n#include <stdio.h>\n#include \"stdlib.h\"\n#include <fstream>\n#include <iostream>\n#include <vector>\n#include <string>\n#include <boost/random.hpp>\n\nusing namespace std;\nusing namespace boost;\n\nint main(int argc, const char ** argv) {\n  //Always seed with the same value, to get the same results\n  srand(1);\n  //defaults\n  int mod_shift = 32;\n  unsigned count = 1000000;\n  //Reading in user arguments\n  if (argc > 2)\n    count = atoi(argv[2]);\n  if (argc > 1)\n    mod_shift = atoi(argv[1]) - 1;\n  std::ofstream ofile;\n  ofile.open(\"input.txt\", std::ios_base::out | std::ios_base::binary |\n             std::ios_base::trunc);\n  if (ofile.bad()) {\n    printf(\"could not open input.txt for writing!\\n\");\n    return 1;\n  }\n  int min_int = (numeric_limits<int>::min)();\n  int max_int = (numeric_limits<int>::max)();\n  if (mod_shift < 31 && mod_shift >= 0) {\n    max_int %= 1 << mod_shift;\n    if (-max_int > min_int)\n      min_int = -max_int;\n  }\n  std::vector<int> result;\n  result.resize(count);\n  mt19937 rng;\n  if (argc > 3 && (string(argv[3]) == \"-normal\")) {\n    normal_distribution<> everything(0, max_int/4);      \n    variate_generator<mt19937&,normal_distribution<> > gen(rng, everything);\n    generate(result.begin(), result.end(), gen);\n  }\n  else if (argc > 3 && (string(argv[3]) == \"-lognormal\")) {\n    lognormal_distribution<> everything(max_int/2, max_int/4);      \n    variate_generator<mt19937&,lognormal_distribution<> > gen(rng, everything);\n    generate(result.begin(), result.end(), gen);\n  }\n  else {\n    uniform_int<> everything(min_int, max_int);\n    variate_generator<mt19937&,uniform_int<> > gen(rng, everything);\n    generate(result.begin(), result.end(), gen);\n  }\n  ofile.write(reinterpret_cast<char *>(&(result[0])), result.size() * \n              sizeof(int));\n  ofile.close();\n  return 0;\n}\n", "meta": {"hexsha": "a34320cd01d36a12a50096d1925a3d9c0fd27ca2", "size": 2148, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/sort/example/boostrandomgen.cpp", "max_stars_repo_name": "ZCube/boost-cmake", "max_stars_repo_head_hexsha": "f1eca5534ab6c9bc89cf7ee4670f056503b7ba86", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 61.0, "max_stars_repo_stars_event_min_datetime": "2017-07-03T18:36:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-14T14:57:19.000Z", "max_issues_repo_path": "libs/sort/example/boostrandomgen.cpp", "max_issues_repo_name": "ZCube/boost-cmake", "max_issues_repo_head_hexsha": "f1eca5534ab6c9bc89cf7ee4670f056503b7ba86", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 49.0, "max_issues_repo_issues_event_min_datetime": "2016-02-29T17:59:52.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-05T04:59:26.000Z", "max_forks_repo_path": "libs/sort/example/boostrandomgen.cpp", "max_forks_repo_name": "ZCube/boost-cmake", "max_forks_repo_head_hexsha": "f1eca5534ab6c9bc89cf7ee4670f056503b7ba86", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 31.0, "max_forks_repo_forks_event_min_datetime": "2017-07-04T14:15:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-12T04:50:41.000Z", "avg_line_length": 30.6857142857, "max_line_length": 79, "alphanum_fraction": 0.6489757914, "num_tokens": 578, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.4878129358998035}}
{"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#include \"segment_segment_intersect.h\"\n\n#include <Eigen/Geometry>\n\ntemplate<typename DerivedSource, typename DerivedDir>\nIGL_INLINE bool igl::segment_segment_intersect(\n  const Eigen::MatrixBase <DerivedSource> &p,\n  const Eigen::MatrixBase <DerivedDir> &r,\n  const Eigen::MatrixBase <DerivedSource> &q,\n  const Eigen::MatrixBase <DerivedDir> &s,\n  double &a_t,\n  double &a_u,\n  double eps\n)\n{\n  // http://stackoverflow.com/questions/563198/how-do-you-detect-where-two-line-segments-intersect\n  // Search intersection between two segments\n  // p + t*r :  t \\in [0,1]\n  // q + u*s :  u \\in [0,1]\n\n  // p + t * r = q + u * s  // x s\n  // t(r x s) = (q - p) x s\n  // t = (q - p) x s / (r x s)\n\n  // (r x s) ~ 0 --> directions are parallel, they will never cross\n  Eigen::Matrix<typename DerivedDir::Scalar, 1, 3> rxs = r.cross(s);\n  if (rxs.norm() <= eps)\n    return false;\n\n  int sign;\n\n  double u;\n  // u = (q \u2212 p) \u00d7 r / (r \u00d7 s)\n  Eigen::Matrix<typename DerivedDir::Scalar, 1, 3> u1 = (q - p).cross(r);\n  sign = ((u1.dot(rxs)) > 0) ? 1 : -1;\n  u = u1.norm() / rxs.norm();\n  u = u * sign;\n\n  double t;\n  // t = (q - p) x s / (r x s)\n  Eigen::Matrix<typename DerivedDir::Scalar, 1, 3> t1 = (q - p).cross(s);\n  sign = ((t1.dot(rxs)) > 0) ? 1 : -1;\n  t = t1.norm() / rxs.norm();\n  t = t * sign;\n\n  a_t = t;\n  a_u = u;\n\n  if ((u - 1.) > eps || u < -eps)\n    return false;\n\n  if ((t - 1.) > eps || t < -eps)\n    return false;\n\n  return true;\n};\n\n#ifdef IGL_STATIC_LIBRARY\ntemplate bool igl::segment_segment_intersect<Eigen::Matrix<double, 1, 3, 1, 1, 3>, Eigen::Matrix<double, 1, 3, 1, 1, 3> >(Eigen::MatrixBase<Eigen::Matrix<double, 1, 3, 1, 1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<double, 1, 3, 1, 1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<double, 1, 3, 1, 1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<double, 1, 3, 1, 1, 3> > const&, double&, double&, double);\n#endif\n", "meta": {"hexsha": "ebc2c6b9d0cf85092235857c7f490f2b2125eba5", "size": 2226, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "third_party/libigl/include/igl/segment_segment_intersect.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/segment_segment_intersect.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/segment_segment_intersect.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": 32.7352941176, "max_line_length": 408, "alphanum_fraction": 0.6163522013, "num_tokens": 785, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.4878129293456086}}
{"text": "#include <iostream>\n#include <armadillo>\n#include \"../config.hpp\"\n\nusing namespace std;\nusing namespace arma;\n\npair<vec, double> entrenarPerceptron(const mat& datos,\n                                     int nEpocas,\n                                     double tasaAprendizaje,\n                                     double toleranciaError);\ndouble errorPerceptron(const vec& pesos,\n                   const mat& patrones,\n                   const vec& salidaDeseada);\n\nusing Particion = pair<mat, mat>;\nvector<Particion> particionar(mat datos, int nParticiones, double porcentajeEnt);\n\nint main()\n{\n    arma_rng::set_seed_random();\n    mat datos;\n\n    // Primera parte del ejercicio (spheres1d)\n    {\n        datos.load(config::sourceDir + \"/guia1/icgtp1datos/spheres1d10.csv\");\n\n        // FIXME:\n        // 1: Las particiones tendr\u00edan que contener los \u00edndices a usar, no replicar los datos.\n        // 2: Las particiones tendr\u00edan que ser generadas una sola vez, guardadas\n        //    en un archivo, y luego levantarlas para que de esta manera poder repetir\n        //    sesiones de entrenamiento/prueba con distintos clasificadores en\n        //    los mismos datos. Incluso fijar la semilla de generaci\u00f3n de n\u00faeros aleatorios.\n        const vector<Particion> particiones = particionar(datos, 5, 80);\n\n        vec errores;\n        errores.set_size(particiones.size());\n        int i = 0;\n\n        for (const Particion& particion : particiones) {\n            vec pesos;\n            tie(pesos, ignore) = entrenarPerceptron(particion.first, 100, 0.1, 20);\n\n            const double tasaError = errorPerceptron(pesos,\n                                                 particion.second.head_cols(3),\n                                                 particion.second.tail_cols(1));\n            errores[i++] = tasaError;\n        }\n\n        cout << \"La validaci\u00f3n cruzada del perceptron en spheres1d10 da como error:\\n\"\n             << \"Media: \" << mean(errores) << '\\n'\n             << \"Varianza: \" << var(errores) << endl;\n    }\n\n    // Segunda parte del ejercicio (spheres2d)\n    vector<string> archivos = {config::sourceDir + \"/guia1/icgtp1datos/spheres2d10.csv\",\n                               config::sourceDir + \"/guia1/icgtp1datos/spheres2d50.csv\",\n                               config::sourceDir + \"/guia1/icgtp1datos/spheres2d70.csv\"};\n\n    for (string archivo : archivos) {\n        datos.load(archivo);\n        const vector<Particion> particiones = particionar(datos, 10, 80);\n\n        vec errores;\n        errores.set_size(particiones.size());\n        int i = 0;\n\n        for (const Particion& particion : particiones) {\n            vec pesos;\n            tie(pesos, ignore) = entrenarPerceptron(particion.first, 100, 0.1, 1);\n\n            const double tasaError = errorPerceptron(pesos,\n                                                 particion.second.head_cols(3),\n                                                 particion.second.tail_cols(1));\n            errores[i++] = tasaError;\n        }\n\n        // FIXME:\n        // Para que los resultados sean m\u00e1s informativos habr\u00eda que proporcionar tamb\u00eden lo siguiente:\n        // (para cada partici\u00f3n)\n        // - Epocas que demor\u00f3 en converger\n        // - Error\n        // Esto sirve para detectar (por ejemplo):\n        // - Si siempre est\u00e1 terminando el entrenamiento por l\u00edmite de \u00e9pocas\n        // - Si los errores est\u00e1n dando siempre altos\n        //      Esto puede querer decir que la tolerancia de error que le estamos pidiendo es\n        //      demasiado alta.\n        cout << \"La validaci\u00f3n cruzada del perceptron en \" << archivo << \" da como error:\\n\"\n             << \"Media: \" << mean(errores) << '\\n'\n             << \"Varianza: \" << var(errores) << endl;\n    }\n\n    return 0;\n}\n\n// Lo siguiente es validaci\u00f3n cruzada cl\u00e1sica\nvector<Particion> particionar(mat datos, int nParticiones, double porcentajeEnt)\n{\n    vector<Particion> particiones;\n    const int nPatronesEnt = datos.n_rows * porcentajeEnt / 100;\n\n    for (int i = 0; i < nParticiones; ++i) {\n        datos = shuffle(datos); // Mezcla las filas de los datos\n        particiones.push_back({datos.head_rows(nPatronesEnt),\n                               datos.tail_rows(datos.n_rows - nPatronesEnt)});\n    }\n\n    return particiones;\n}\n\nnamespace ic {\nint sign(double numero)\n{\n    if (numero >= 0)\n        return 1;\n    else\n        return -1;\n}\n}\n\npair<vec, double> epocaPerceptron(const mat& patronesExt,\n                                  const vec& salidaDeseada,\n                                  double tasaAprendizaje,\n                                  const vec& pesos)\n{\n    //Entrenamiento\n    vec nuevosPesos = pesos;\n\n    for (unsigned int i = 0; i < patronesExt.n_rows; ++i) {\n        double z = dot(patronesExt.row(i), pesos);\n        int y = ic::sign(z);\n\n        // Actualizar pesos\n        nuevosPesos += tasaAprendizaje * (salidaDeseada(i) - y) * patronesExt.row(i).t();\n    } // Fin ciclo (Entrenamiento)\n\n    // Validacion\n    int errores = 0;\n\n    for (unsigned int i = 0; i < patronesExt.n_rows; ++i) {\n        double z = dot(patronesExt.row(i), pesos);\n        int y = ic::sign(z);\n\n        if (y != salidaDeseada(i))\n            ++errores;\n    }\n\n    double tasaError = static_cast<double>(errores) / patronesExt.n_rows * 100;\n\n    return {nuevosPesos, tasaError};\n} // fin funcion Epoca\n\ndouble errorPerceptron(const vec& pesos,\n                   const mat& patrones,\n                   const vec& salidaDeseada)\n{\n    // Se extiende la matriz de patrones con la entrada correspondiente al umbral\n    const mat patronesExt = join_horiz(ones(patrones.n_rows) * (-1), patrones);\n\n    int errores = 0;\n\n    for (unsigned int i = 0; i < patronesExt.n_rows; ++i) {\n        double z = dot(patronesExt.row(i), pesos);\n        int y = ic::sign(z);\n\n        if (y != salidaDeseada(i))\n            ++errores;\n    }\n\n    double tasaError = static_cast<double>(errores) / patronesExt.n_rows * 100;\n\n    return tasaError;\n}\n\npair<vec, double> entrenarPerceptron(const mat& datos,\n                                     int nEpocas,\n                                     double tasaAprendizaje,\n                                     double toleranciaError)\n{\n    const vec salidaDeseada = datos.tail_cols(1);\n    // Extender la matriz de patrones con la entrada correspondiente al umbral\n    const int nParametros = datos.n_cols - 1;\n    const mat patronesExt = join_horiz(ones(datos.n_rows) * (-1), datos.head_cols(nParametros));\n\n    // Inicializar pesos y tasa de error\n    vec pesos = randu<vec>(patronesExt.n_cols) - 0.5;\n    double tasaError = 0;\n\n    // Ciclo de las epocas\n    for (int epoca = 1; epoca <= nEpocas; ++epoca) {\n        // Ciclo para una \u00e9poca\n        tie(pesos, tasaError) = epocaPerceptron(patronesExt,\n                                                salidaDeseada,\n                                                tasaAprendizaje,\n                                                pesos);\n\n        if (tasaError < toleranciaError)\n            break;\n    }\n    // Fin ciclo (epocas)\n\n    return {pesos, tasaError};\n}\n", "meta": {"hexsha": "0bcd9c92ddbf27d4dc4d134f92e3ebb52c3d7a78", "size": 7077, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "guia1/ejercicio2.cpp", "max_stars_repo_name": "junrrein/ic2017", "max_stars_repo_head_hexsha": "e7ab09257093a56751c58a4633a049f7746f00e3", "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": "guia1/ejercicio2.cpp", "max_issues_repo_name": "junrrein/ic2017", "max_issues_repo_head_hexsha": "e7ab09257093a56751c58a4633a049f7746f00e3", "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": "guia1/ejercicio2.cpp", "max_forks_repo_name": "junrrein/ic2017", "max_forks_repo_head_hexsha": "e7ab09257093a56751c58a4633a049f7746f00e3", "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.6911764706, "max_line_length": 102, "alphanum_fraction": 0.5663416702, "num_tokens": 1771, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.48772851926771416}}
{"text": "/*=============================================================================\r\n    Spirit v1.6.0\r\n    Copyright (c) 2002-2003 Joel de Guzman\r\n    http://spirit.sourceforge.net/\r\n\r\n    Permission to copy, use, modify, sell and distribute this software is\r\n    granted provided this copyright notice appears in all copies. This\r\n    software is provided \"as is\" without express or implied warranty, and\r\n    with no claim as to its suitability for any purpose.\r\n=============================================================================*/\r\n///////////////////////////////////////////////////////////////////////////////\r\n//\r\n//  A parser for summing a list of numbers.\r\n//  [ demonstrating phoenix ]\r\n//\r\n//  [ JDG 6/28/2002 ]\r\n//\r\n///////////////////////////////////////////////////////////////////////////////\r\n#include <boost/spirit/core.hpp>\r\n#include <boost/spirit/phoenix/primitives.hpp>\r\n#include <boost/spirit/phoenix/operators.hpp>\r\n#include <iostream>\r\n#include <string>\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\nusing namespace std;\r\nusing namespace boost::spirit;\r\nusing namespace phoenix;\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n//\r\n//  Our adder\r\n//\r\n///////////////////////////////////////////////////////////////////////////////\r\ntemplate <typename IteratorT>\r\nbool adder(IteratorT first, IteratorT last, double& n)\r\n{\r\n    return parse(first, last,\r\n\r\n        //  Begin grammar\r\n        (\r\n            real_p[var(n) = arg1] >> *real_p[var(n) += arg1]\r\n        )\r\n        ,\r\n        //  End grammar\r\n\r\n        space_p).full;\r\n}\r\n\r\n////////////////////////////////////////////////////////////////////////////\r\n//\r\n//  Main program\r\n//\r\n////////////////////////////////////////////////////////////////////////////\r\nint\r\nmain()\r\n{\r\n    cout << \"/////////////////////////////////////////////////////////\\n\\n\";\r\n    cout << \"\\t\\tA parser for summing a list of numbers...\\n\\n\";\r\n    cout << \"/////////////////////////////////////////////////////////\\n\\n\";\r\n\r\n    cout << \"Give me a space separated list of numbers.\\n\";\r\n    cout << \"The numbers are added using Phoenix.\\n\";\r\n    cout << \"Type [q or Q] to quit\\n\\n\";\r\n\r\n    string str;\r\n    while (getline(cin, str))\r\n    {\r\n        if (str[0] == 'q' || str[0] == 'Q')\r\n            break;\r\n\r\n        double n;\r\n        if (adder(str.begin(), str.end(), n))\r\n        {\r\n            cout << \"-------------------------\\n\";\r\n            cout << \"Parsing succeeded\\n\";\r\n            cout << str << \" Parses OK: \" << endl;\r\n\r\n            cout << \"sum = \" << n;\r\n            cout << \"\\n-------------------------\\n\";\r\n        }\r\n        else\r\n        {\r\n            cout << \"-------------------------\\n\";\r\n            cout << \"Parsing failed\\n\";\r\n            cout << \"-------------------------\\n\";\r\n        }\r\n    }\r\n\r\n    cout << \"Bye... :-) \\n\\n\";\r\n    return 0;\r\n}\r\n\r\n\r\n", "meta": {"hexsha": "c0b46cfe451822f9b10acf02b1a2fc30921d9914", "size": 2912, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sdk/boost_1_30_0/libs/spirit/example/fundamental/sum.cpp", "max_stars_repo_name": "acidicMercury8/xray-1.0", "max_stars_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-01-30T12:51:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-31T08:36:49.000Z", "max_issues_repo_path": "sdk/boost_1_30_0/libs/spirit/example/fundamental/sum.cpp", "max_issues_repo_name": "acidicMercury8/xray-1.0", "max_issues_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_issues_repo_licenses": ["Linux-OpenIB"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sdk/boost_1_30_0/libs/spirit/example/fundamental/sum.cpp", "max_forks_repo_name": "acidicMercury8/xray-1.0", "max_forks_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6526315789, "max_line_length": 80, "alphanum_fraction": 0.3523351648, "num_tokens": 530, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646140788307, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.48772851926771416}}
{"text": "//\n// Created by abakfja on 3/28/21.\n//\n\n#ifndef LA_MATRIX_ENGINE_HPP\n#define LA_MATRIX_ENGINE_HPP\n\n#include <boost/numeric/ublas/matrix/storage_traits.hpp>\n#include <cstddef>\n\nnamespace boost::numeric::ublas::experimental {\n\ntemplate<typename T, std::size_t R, std::size_t C>\nstruct static_matrix_engine {\n    using scalar_type = T;\n    using array_type = std::array<scalar_type, R * C>;\n    using storage_traits_type = storage_traits<array_type>;\n    using size_type = typename storage_traits_type::size_type;\n    using resizable_tag = typename storage_traits_type::resizable_tag;\n    static constexpr size_type rows = R;\n    static constexpr size_type cols = C;\n};\n\ntemplate<typename T>\nstruct dynamic_matrix_engine {\n    using scalar_type = T;\n    using array_type = std::vector<T>;\n    using storage_traits_type = storage_traits<array_type>;\n    using resizable_tag = typename storage_traits_type::resizable_tag;\n};\n\n}\n\n#endif //LA_MATRIX_ENGINE_HPP\n", "meta": {"hexsha": "df567a4cc9dd0a62352182e1c3e732774c4eb24b", "size": 955, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/matrix_old/matrix/matrix_engine.hpp", "max_stars_repo_name": "abakfja/linear-algebra", "max_stars_repo_head_hexsha": "024974bc537f3c1aa86bd011e5821e6e4465aa49", "max_stars_repo_licenses": ["MIT"], "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/matrix_old/matrix/matrix_engine.hpp", "max_issues_repo_name": "abakfja/linear-algebra", "max_issues_repo_head_hexsha": "024974bc537f3c1aa86bd011e5821e6e4465aa49", "max_issues_repo_licenses": ["MIT"], "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/matrix_old/matrix/matrix_engine.hpp", "max_forks_repo_name": "abakfja/linear-algebra", "max_forks_repo_head_hexsha": "024974bc537f3c1aa86bd011e5821e6e4465aa49", "max_forks_repo_licenses": ["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.2857142857, "max_line_length": 70, "alphanum_fraction": 0.754973822, "num_tokens": 221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.4877285138864899}}
{"text": "#include <ros/ros.h>\n#include <sensor_msgs/LaserScan.h>\n#include <laser_geometry/laser_geometry.h>\n#include <visualization_msgs/Marker.h>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/linestring.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/assign.hpp>\n\nros::Publisher marker_pub;\nros::Subscriber laser_sub;\n\ndouble douglas_pecker_distance;\ndouble neighbor_distance;\nint min_cluster_size;\n\ntypedef boost::geometry::model::d2::point_xy<double> xy;\nlaser_geometry::LaserProjection lp;\n\n\nvoid laser_cb(const sensor_msgs::LaserScan::ConstPtr& msg)\n{\n    // Create marker for rviz\n    visualization_msgs::Marker line_segments;\n    line_segments.header.frame_id = msg->header.frame_id;\n    line_segments.header.stamp = msg->header.stamp;\n    line_segments.ns = \"line_segments\";\n    line_segments.action = visualization_msgs::Marker::ADD;\n    line_segments.type = visualization_msgs::Marker::LINE_LIST;\n    line_segments.pose.orientation.w = 1.0;\n    line_segments.id = 42;\n    line_segments.scale.x = 0.1;\n    line_segments.color.r = 1.0;\n    line_segments.color.a = 1.0;\n\n\n    // Convert laser data from polar to cartesian coordinate system\n    sensor_msgs::PointCloud cloud;\n    lp.projectLaser(*msg, cloud);\n\n\n    // Cluster the point cloud\n    boost::geometry::model::linestring<xy> cluster;\n    for (int i=0; i<cloud.points.size(); i++)\n    {\n        boost::geometry::append(cluster, xy(cloud.points[i].x, cloud.points[i].y));\n        bool is_cluster_ready = false;\n\n        // If this is the last point, don't check the next one and complete the cluster\n        if (i == cloud.points.size())\n        {\n            is_cluster_ready = true;\n        }\n        else\n        {\n            // Find if the point is in the cluster using euclidian distance\n            double x1, y1, x2, y2;\n            x1 = cloud.points[i].x;\n            y1 = cloud.points[i].y;\n            x2 = cloud.points[i+1].x;\n            y2 = cloud.points[i+1].y;\n            is_cluster_ready = ( pow(x1-x2, 2)+pow(y1-y2, 2) > pow(neighbor_distance, 2) );\n        }\n\n        if (is_cluster_ready)\n        {\n            if (cluster.size() >= min_cluster_size)\n            {\n                // simplify process\n                boost::geometry::model::linestring<xy> simplified;\n                boost::geometry::simplify(cluster, simplified, douglas_pecker_distance); // Using Douglas-Peucker algorithm\n\n                // Parse results from \"simplified\" for visualization purposes\n                for (int j=0; j<simplified.size()-1; j++)\n                {\n                    geometry_msgs::Point p1, p2;\n                    p1.x = simplified[j].x();\n                    p1.y = simplified[j].y();\n                    p2.x = simplified[j+1].x();\n                    p2.y = simplified[j+1].y();\n\n                    line_segments.points.push_back(p1);\n                    line_segments.points.push_back(p2);\n                }\n                cluster.clear();\n            }\n            else\n            {\n                cluster.clear();\n            }\n        }\n    }\n\n    marker_pub.publish(line_segments);\n}\n\n\nint main(int argc, char **argv)\n{\n    ros::init(argc, argv, \"extract_line_segments_node\");\n    ros::NodeHandle nh;\n    ros::NodeHandle priv_nh(\"~\");\n\n    priv_nh.param(\"douglas_pecker_distance\", douglas_pecker_distance, 0.1);\n    priv_nh.param(\"neighbor_distance\", neighbor_distance, 0.5);\n    priv_nh.param(\"min_cluster_size\", min_cluster_size, 5);\n\n    marker_pub = nh.advertise<visualization_msgs::Marker>(\"line_segments\", 2);\n    laser_sub = nh.subscribe(\"scan\", 2, laser_cb);\n\n    ros::spin();\n    return 0;\n}", "meta": {"hexsha": "164b0eb115137ea0dc35517332fc620a890ff94d", "size": 3635, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/extract_line_segments_node.cpp", "max_stars_repo_name": "salihmarangoz/extract_line_segments", "max_stars_repo_head_hexsha": "f4ce2d0cd6b42a996957e49464828472597665ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-13T17:21:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-13T17:21:46.000Z", "max_issues_repo_path": "src/extract_line_segments_node.cpp", "max_issues_repo_name": "salihmarangoz/extract_line_segments", "max_issues_repo_head_hexsha": "f4ce2d0cd6b42a996957e49464828472597665ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/extract_line_segments_node.cpp", "max_forks_repo_name": "salihmarangoz/extract_line_segments", "max_forks_repo_head_hexsha": "f4ce2d0cd6b42a996957e49464828472597665ff", "max_forks_repo_licenses": ["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.8859649123, "max_line_length": 123, "alphanum_fraction": 0.6093535076, "num_tokens": 865, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.4877285098419044}}
{"text": "/*\n * The MIT License (MIT)\n *\n * Copyright (c) 2017 Hidekazu Ikeno\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/// \\file partial_lanczos_bidiagonalization.hpp\n///\n#ifndef MXPFIT_PARTIAL_LANCZOS_BIDIAGONALIZATION_HPP\n#define MXPFIT_PARTIAL_LANCZOS_BIDIAGONALIZATION_HPP\n\n#include <Eigen/Core>\n\nnamespace mxpfit\n{\n\n///\n/// ### PartialLanczosBidiagonalization\n///\n/// \\brief Low-rank approximation of a matrix by the Lanczos bidiagonalization\n/// with full reorthogonalization\n///\n/// \\tparam MatrixT Matrix type to be decomposed. We expect that `MatrixT`\n/// inherits Eigen::EigenBase class.\n///\n/// For a given \\f$m \\times n\\f$ matrix \\f$A\\f$ and prescribed accuracy\n/// \\f$\\epsilon,\\f$ this class computes the approximate decomposition such that\n///\n/// \\f[\n///   \\|A - P_{k}^{} B_{k} Q_{k}^{\\ast} \\|_{F} < \\epsilon.\n/// \\f]\n///\n/// where \\f$P_{k}\\f$ is a \\f$ m \\times k \\f$ matrix with orthonormal columns,\n/// and \\f$ Q_{k} \\f$ is a \\f$m \\times k\\f$ matrix with orthonormal columns.\n/// \\f$B_{k}\\f$ is a real bidiagonal matrix\n///\n/// #### References\n///\n/// 1. D. Potts and M. Tasche, \"Fast ESPRIT algorithms based on partial singular\n///    value decompositions\", Appl. Numer. Math. **88** (2015) 31-45.\n///    [DOI: http://doi.org/10.1016/j.apnum.2014.10.003]\n///\ntemplate <typename MatrixT>\nclass PartialLanczosBidiagonalization\n{\npublic:\n    using MatrixType    = MatrixT;\n    using Scalar        = typename MatrixType::Scalar;\n    using RealScalar    = typename MatrixType::RealScalar;\n    using Index         = Eigen::Index;\n    using Vector        = Eigen::Matrix<Scalar, Eigen::Dynamic, 1>;\n    using RealVector    = Eigen::Matrix<RealScalar, Eigen::Dynamic, 1>;\n    using Matrix        = Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>;\n    using RealVectorRef = Eigen::Ref<RealVector>;\n    using MatrixRef     = Eigen::Ref<Matrix>;\n\n    PartialLanczosBidiagonalization()\n        : m_matP(),\n          m_matQ(),\n          m_alpha(),\n          m_beta(),\n          m_rank(),\n          m_tolerance(Eigen::NumTraits<RealScalar>::epsilon()),\n          m_error(),\n          m_is_initialized()\n\n    {\n    }\n\n    PartialLanczosBidiagonalization(Index nrows, Index ncols, Index nsteps)\n        : m_matP(nrows, nsteps),\n          m_matQ(ncols, nsteps),\n          m_alpha(nsteps),\n          m_beta(nsteps),\n          m_rank(),\n          m_tolerance(Eigen::NumTraits<RealScalar>::epsilon()),\n          m_error(),\n          m_is_initialized()\n    {\n    }\n\n    PartialLanczosBidiagonalization(const MatrixType& mat, Index nsteps)\n        : m_matP(mat.rows(), nsteps),\n          m_matQ(mat.cols(), nsteps),\n          m_alpha(nsteps),\n          m_beta(nsteps),\n          m_rank(),\n          m_tolerance(Eigen::NumTraits<RealScalar>::epsilon()),\n          m_error(),\n          m_is_initialized()\n    {\n        compute(mat, nsteps);\n    }\n\n    void compute(const MatrixType& matA, Index nsteps);\n\n    void setTolerance(RealScalar tolerance) noexcept\n    {\n        m_tolerance = tolerance;\n    }\n\n    RealScalar tolerance() const noexcept\n    {\n        return m_tolerance;\n    }\n\n    Index rank() const noexcept\n    {\n        assert(m_is_initialized &&\n               \"PartialLanczosBidiagonalization is not initialized.\");\n        return m_rank;\n    }\n\n    RealScalar error() const noexcept\n    {\n        assert(m_is_initialized &&\n               \"PartialLanczosBidiagonalization is not initialized.\");\n        return m_error;\n    }\n\n    const Matrix& matrixP() const noexcept\n    {\n        assert(m_is_initialized &&\n               \"PartialLanczosBidiagonalization is not initialized.\");\n        return m_matP;\n    }\n\n    const Matrix& matrixQ() const noexcept\n    {\n        assert(m_is_initialized &&\n               \"PartialLanczosBidiagonalization is not initialized.\");\n        return m_matQ;\n    }\n\n    const RealVector& diagonalAlpha() const noexcept\n    {\n        assert(m_is_initialized &&\n               \"PartialLanczosBidiagonalization is not initialized.\");\n        return m_alpha;\n    }\n\n    const RealVector& superdiagonalBeta() const noexcept\n    {\n        assert(m_is_initialized &&\n               \"PartialLanczosBidiagonalization is not initialized.\");\n        return m_beta;\n    }\n\n    Matrix reconstructedMatrix() const\n    {\n        assert(m_is_initialized &&\n               \"PartialLanczosBidiagonalization is not initialized.\");\n\n        if (m_rank == Index())\n        {\n            return Matrix();\n        }\n\n        auto viewP = m_matP.leftCols(m_rank);\n        auto viewQ = m_matQ.leftCols(m_rank);\n        Matrix matB(Matrix::Zero(m_rank, m_rank));\n        matB.diagonal()  = m_alpha.head(m_rank);\n        matB.diagonal(1) = m_beta.head(m_rank - 1);\n\n        return viewP * matB * viewQ.adjoint();\n    }\n\nprotected:\n    Matrix m_matP;\n    Matrix m_matQ;\n    RealVector m_alpha;\n    RealVector m_beta;\n\n    Index m_rank;\n    RealScalar m_tolerance;\n    RealScalar m_error;\n    bool m_is_initialized;\n};\n\ntemplate <typename MatrixT>\nvoid PartialLanczosBidiagonalization<MatrixT>::compute(const MatrixType& matA,\n                                                       Index nsteps)\n{\n    assert(Index() <= nsteps && nsteps <= matA.rows() && nsteps <= matA.cols());\n\n    m_matP.resize(matA.rows(), nsteps);\n    m_matQ.resize(matA.cols(), nsteps);\n    m_alpha.resize(nsteps);\n    m_beta.resize(nsteps - 1);\n\n    Vector workspace(nsteps);\n\n    auto q0 = m_matQ.col(0);\n    // Set q0 as unit vector (1,0,0,....)^T plus small perturbation\n    q0.setRandom();\n    q0(0) = RealScalar(1) /\n            Eigen::numext::sqrt(Eigen::NumTraits<RealScalar>::epsilon());\n    q0.normalize(); // make q0 normalized\n    auto p0       = m_matP.col(0);\n    p0            = matA * q0;\n    const auto a1 = p0.norm();\n    if (a1 > RealScalar())\n    {\n        p0 *= RealScalar(1) / a1;\n    }\n    m_alpha(0) = a1;\n\n    const RealScalar tol2 = m_tolerance * m_tolerance;\n    RealScalar fnorm_A    = a1 * a1; // Estimation of |A|_F\n    m_error               = RealScalar();\n    Index irank           = 0;\n\n    while (++irank < nsteps)\n    {\n        auto p1 = m_matP.col(irank - 1);\n        auto p2 = m_matP.col(irank);\n        auto q1 = m_matQ.col(irank - 1);\n        auto q2 = m_matQ.col(irank);\n        //\n        // --- Recursion for right Lanczos vector\n        //\n        q2 = matA.adjoint() * p1 - m_alpha(irank - 1) * q1;\n        // Reorthogonalization\n        auto tmp   = workspace.head(irank);\n        auto viewQ = m_matQ.leftCols(irank);\n        tmp        = viewQ.adjoint() * q2;\n        q2 -= viewQ * tmp;\n        auto b1 = q2.norm();\n        if (b1 > RealScalar())\n        {\n            q2 *= RealScalar(1) / b1;\n        }\n        m_beta(irank - 1) = b1;\n        //\n        // --- Recursion for left Lanczos vector\n        //\n        // p2 <-- A * q2 - beta(i) * p1\n        p2 = matA * q2 - m_beta(irank - 1) * p1;\n        // Reorthogonalization\n        auto viewP = m_matP.leftCols(irank);\n        tmp        = viewP.adjoint() * p2;\n        p2 -= viewP * tmp;\n\n        auto a2 = p2.norm();\n        if (a2 > RealScalar())\n        {\n            p2 *= RealScalar(1) / a2;\n        }\n        m_alpha(irank) = a2;\n        //\n        // Update frobenius norm of matrix A via\n        //\n        // ||A||_{F}^{2} = \\sum_{K=1}^{rank(A)-1}\n        //       (\\alpha_{K}^{2} + \\beta_{K}^{2}) + \\alpha_{rank(A)}}\n        //\n        auto t = a2 * a2 + b1 * b1;\n        fnorm_A += t;\n        m_error = t / fnorm_A;\n        if (m_error <= tol2)\n        {\n            break; // converged\n        }\n    }\n\n    m_rank           = irank;\n    m_is_initialized = true;\n}\n\n} // namespace mxpfit\n\n#endif /* MXPFIT_PARTIAL_LANCZOS_BIDIAGONALIZATION_HPP*/\n", "meta": {"hexsha": "a28333ff88aaf749630ba04b189c70c0b556aa76", "size": 8681, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mxpfit/partial_lanczos_bidiagonalization.hpp", "max_stars_repo_name": "hydeik/mxpfit", "max_stars_repo_head_hexsha": "a18621b191e426f549374cff0af3374861e9f065", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-04-25T07:07:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T09:13:11.000Z", "max_issues_repo_path": "include/mxpfit/partial_lanczos_bidiagonalization.hpp", "max_issues_repo_name": "hydeik/mxpfit", "max_issues_repo_head_hexsha": "a18621b191e426f549374cff0af3374861e9f065", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-07-04T08:42:03.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-15T02:57:05.000Z", "max_forks_repo_path": "include/mxpfit/partial_lanczos_bidiagonalization.hpp", "max_forks_repo_name": "hydeik/mxpfit", "max_forks_repo_head_hexsha": "a18621b191e426f549374cff0af3374861e9f065", "max_forks_repo_licenses": ["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.8316151203, "max_line_length": 80, "alphanum_fraction": 0.5962446723, "num_tokens": 2270, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217431943271999, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.487728506465638}}
{"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//////////////////////////////////////////////////////////////////////////////\n// cover test behavior of arithmetic components in scalar mode\n//////////////////////////////////////////////////////////////////////////////\n#include <nt2/arithmetic/include/functions/sqr.hpp>\n#include <vector>\n#include <nt2/include/constants/valmin.hpp>\n#include <nt2/include/constants/valmax.hpp>\n#include <nt2/include/constants/sqrtvalmax.hpp>\n#include <nt2/include/functions/multiplies.hpp>\n#include <boost/dispatch/meta/as_integer.hpp>\n\n\n#include <nt2/sdk/unit/tests/cover.hpp>\n#include <nt2/sdk/unit/module.hpp>\n#include <nt2/sdk/unit/tests/type_expr.hpp>\n#include <nt2/sdk/meta/as_floating.hpp>\n\nNT2_TEST_CASE_TPL ( sqr_real__1_0,  NT2_REAL_TYPES)\n{\n\n  using nt2::sqr;\n  using nt2::tag::sqr_;\n  typedef typename nt2::meta::call<sqr_(T)>::type r_t;\n\n  nt2::uint32_t NR = NT2_NB_RANDOM_TEST;\n  std::vector<T> in1(NR);\n  nt2::roll(in1, nt2::Valmin<T>()/2, nt2::Valmax<T>()/2);\n  std::vector<r_t>  ref(NR);\n  for(nt2::uint32_t i=0; i < NR ; ++i)\n  {\n    ref[i] = in1[i]*in1[i];\n  }\n\n  NT2_COVER_ULP_EQUAL(sqr_, ((T, in1)), ref, 0);\n}\n\nNT2_TEST_CASE_TPL ( sqr_uint,  NT2_INTEGRAL_UNSIGNED_TYPES)\n{\n\n  using nt2::sqr;\n  using nt2::tag::sqr_;\n  typedef typename nt2::meta::call<sqr_(T)>::type r_t;\n  typedef typename boost::dispatch::meta::as_integer<T, unsigned>::type utype;\n\n  nt2::uint32_t NR = NT2_NB_RANDOM_TEST;\n  std::vector<T> in1(NR);\n  nt2::roll(in1, nt2::Valmin<T>()/2, nt2::Valmax<T>()/2);\n  std::vector<r_t>  ref(NR);\n  for(nt2::uint32_t i=0; i < NR ; ++i)\n  {\n    ref[i] = T(nt2::multiplies(utype(in1[i]), utype(in1[i])));\n  }\n\n  NT2_COVER_ULP_EQUAL(sqr_, ((T, in1)), ref, 0);\n}\nNT2_TEST_CASE_TPL ( sqr_sint,  NT2_INTEGRAL_SIGNED_TYPES)\n{\n\n  using nt2::sqr;\n  using nt2::tag::sqr_;\n  typedef typename nt2::meta::call<sqr_(T)>::type r_t;\n  typedef typename boost::dispatch::meta::as_integer<T, unsigned>::type utype;\n\n  nt2::uint32_t NR = NT2_NB_RANDOM_TEST;\n  std::vector<T> in1(NR);\n  nt2::roll(in1, -nt2::Sqrtvalmax<T>()/2, nt2::Sqrtvalmax<T>()/2);\n  std::vector<r_t>  ref(NR);\n  for(nt2::uint32_t i=0; i < NR ; ++i)\n  {\n    ref[i] = T(nt2::multiplies(utype(in1[i]), utype(in1[i])));\n  }\n\n  NT2_COVER_ULP_EQUAL(sqr_, ((T, in1)), ref, 0);\n}\n\n", "meta": {"hexsha": "eb93021d7b1327a4e842bcbd10e7441dcde9e9a7", "size": 2746, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/core/base/cover/arithmetic/scalar/sqr.cpp", "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/base/cover/arithmetic/scalar/sqr.cpp", "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/base/cover/arithmetic/scalar/sqr.cpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 32.6904761905, "max_line_length": 80, "alphanum_fraction": 0.585214858, "num_tokens": 843, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.48772850512899946}}
{"text": "/**\n * Copyright (c) 2020 Melown Technologies SE\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * *  Redistributions of source code must retain the above copyright notice,\n *    this list of conditions and the following disclaimer.\n *\n * *  Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in the\n *    documentation and/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n#include \"estimate-point-normals.hpp\"\n#include \"bvh.hpp\"\n#include \"math/math.hpp\"\n#include \"math/geometry.hpp\"\n\n#include <boost/iterator/counting_iterator.hpp>\n\nnamespace geometry {\n\nnamespace ublas = math::ublas;\n\nEigen::VectorXd estimateNormal(const Eigen::MatrixXd& data)\n{\n    using namespace Eigen;\n    // calculate centroid (1 x K) of all (N) data points\n    RowVectorXd centroid = data.colwise().mean();\n    // mean-center sample matrix\n    MatrixXd centered = data.rowwise() - centroid;\n    // calculate the covariance matrix (K x K), for PCA we may ommit\n    // scaling by the factor 1/(N - 1)\n    MatrixXd covariance = centered.transpose() * centered;\n\n    // calculate SVD (ordered by the magnitude of SV)\n    JacobiSVD<MatrixXd> svd(covariance, ComputeFullU);\n    // the normal is the last column of U, singular vector of the covariance\n    // matrix corresponding to the smallest singular value\n    // (i.e., the direction of the least variability in the data)\n    VectorXd sgVec(svd.matrixU().col(data.cols() - 1));\n\n    // normalization shouldn't be needed as U should be a unitary matrix.\n    return sgVec;//.normalized();\n}\n\nnamespace {\n\n    class BvhDisk : public BvhPrimitive {\n        math::Point3 center_;\n        math::Point3 normal_;\n        double radius_;\n\n    public:\n        BvhDisk() = default;\n\n        BvhDisk(const math::Point3& center\n                , const math::Point3& normal\n                , const double radius\n                , const std::uint32_t index)\n            : center_(center)\n            , normal_(normal)\n            , radius_(radius) {\n            assert(radius_ > 0.);\n            userData = index;\n        }\n\n        bool getIntersection(const Ray& ray, IntersectionInfo& intersection) const {\n            // ray-plane intersection\n            const double denom = inner_prod(normal_, ray.direction());\n            if (std::fabs(denom) < 1.e-6) {\n                return false;\n            }\n            const math::Point3 diff = center_ - ray.origin();\n            const double t = inner_prod(diff, normal_) / denom;\n            if (t > 0.) {\n                // find the distance of the intersection from the disk center\n                const math::Point3 dp = ray.origin() + ray.direction() * t - center_;\n                const double distSqr = inner_prod(dp, dp);\n                if (distSqr < math::sqr(radius_)) {\n                    intersection.object = this;\n                    intersection.t = t;\n                    return true;\n                }\n            }\n\n            return false;\n        }\n\n        math::Extents3 getBBox() const {\n            ublas::scalar_vector<double> size(3, radius_);\n            return math::Extents3(center_ - size, center_ + size);\n        }\n\n        math::Point3 getCenter() const {\n            return center_;\n        }\n    };\n\n} // namespace\n\nstatic constexpr float DX = 0.25;\nstatic constexpr float DZ = 1.;\nstatic math::Points3 ALL_DIRS = {\n    math::Point3(0., 0., DZ),\n    math::Point3(0., DX, DZ),\n    math::Point3(0., -DX, DZ),\n    math::Point3(DX, 0., DZ),\n    math::Point3(-DX, 0., DZ),\n    math::Point3(DX, DX, DZ),\n    math::Point3(DX, -DX, DZ),\n    math::Point3(-DX, -DX, DZ),\n    math::Point3(-DX, DX, DZ),\n};\n\nvoid reorientNormals(const std::vector<math::Point3>& pc\n                     , std::vector<math::Point3>& normals\n                     , const double pointRadius)\n{\n    std::vector<BvhDisk> disks(pc.size());\n    UTILITY_OMP(parallel for)\n    for (std::uint32_t i = 0; i < pc.size(); ++i) {\n        disks[i] = BvhDisk(pc[i], normals[i], pointRadius, i);\n    }\n\n    LOG(info2) << \"Building BVH for \" << disks.size() << \" points\";\n    geometry::Bvh<BvhDisk> bvh(20);\n    bvh.build(std::move(disks));\n\n    // find order in z-direction\n    std::vector<std::uint32_t> orderZ(pc.size());\n    std::copy(boost::counting_iterator<std::uint32_t>(0)\n              , boost::counting_iterator<std::uint32_t>(pc.size())\n              , orderZ.begin());\n    std::sort(orderZ.begin(), orderZ.end()\n              , [&](std::uint32_t i1, std::uint32_t i2) { return pc[i1](2) > pc[i2](2); });\n\n    // step 1 - determine normal orientation based on normals of already determined points,\n    // assuming the topmost points (roofs) have z>0 orientation.\n    LOG(info2) << \"Estimating normal orientations\";\n    UTILITY_OMP(parallel for)\n    for (std::uint32_t rankZ = 0; rankZ < orderZ.size(); ++rankZ) {\n        const std::uint32_t i = orderZ[rankZ];\n        int doFlip = 0;\n        for (math::Point3 dir : ALL_DIRS) {\n            dir = math::normalize(dir);\n            // whether the ray is outward or inward with respect to current normal orientation\n            const int outward = math::sgn(inner_prod(dir, normals[i]));\n            const Ray ray(pc[i] + pointRadius * dir, dir);\n            IntersectionInfo is;\n            if (bvh.getFirstIntersection(ray, is)) {\n                const std::uint32_t j = is.object->userData;\n                // if this is an outward ray, flip the normal if the intersected point has\n                // the same orientation as the ray (i.e. likely a backface);\n                // for an inward ray, flip the normal if the intersected point is NOT a backface.\n                doFlip += int(inner_prod(normals[j], dir) > 0.) * outward;\n            } else {\n                // no occlusion -> normal correct if this is an outward ray\n                doFlip -= outward;\n            }\n        }\n\n        if (doFlip > 0) {\n            // more votes for flipping the normal\n            normals[i] *= -1;\n        }\n    }\n\n    // step 2 - flip normals which have opposite orientation than their neighbors\n    LOG(info2) << \"Flipping outliers\";\n    KdTree<math::Point3, 3> tree(pc.begin(), pc.end());\n    std::vector<uint8_t> doFlip(pc.size(), false);\n    std::vector<math::Points3::const_iterator> neighs;\n    UTILITY_OMP(parallel for private(neighs))\n    for (std::uint32_t i = 0; i < pc.size(); ++i) {\n        neighs.clear();\n        tree.range(pc[i], 2 * pointRadius, neighs);\n\n        double count = 0.;\n        for (auto& n : neighs) {\n            const std::uint32_t j = std::uint32_t(n - pc.begin());\n            count += inner_prod(normals[i], normals[j]);\n        }\n        if (count < 0.) {\n            doFlip[i] = true;\n        }\n    }\n    UTILITY_OMP(parallel for)\n    for (std::uint32_t i = 0; i < pc.size(); ++i) {\n        if (doFlip[i]) {\n            normals[i] *= -1;\n        }\n    }\n}\n\n} // namespace geometry\n", "meta": {"hexsha": "14102c4a0ed80618ca80ccacb8b2d709bc8380c9", "size": 7820, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "externals/browser/externals/browser/externals/libgeometry/geometry/estimate-point-normals.cpp", "max_stars_repo_name": "HanochZhu/vts-browser-unity-plugin", "max_stars_repo_head_hexsha": "32a22d41e21b95fb015326f95e401d87756d0374", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-02T08:42:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-02T08:42:59.000Z", "max_issues_repo_path": "externals/browser/externals/browser/externals/libgeometry/geometry/estimate-point-normals.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/libgeometry/geometry/estimate-point-normals.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": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.4162679426, "max_line_length": 97, "alphanum_fraction": 0.6020460358, "num_tokens": 1919, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4877090453151402}}
{"text": "#include \"trim_dht.hpp\"\n#include \"dht.hpp\"\n\n#include <Eigen/Dense>\n#include <algorithm>\n#include <boost/math/special_functions/bessel.hpp>\n#include <cmath>\n#include <iostream>\n#include <iterator>\n\nusing namespace Eigen;\nusing boost::math::cyl_bessel_j;\nusing boost::math::cyl_bessel_j_zero;\nusing std::pow;\n\nTrimDHT::TrimDHT(int order, int nr, double rmax, int nexp)\n    : DiscreteHankelTransform(order, nr * pow(2, nexp)),\n      shift_matrix_(nr_, nr_) {\n  // nr_ = nr * pow(2, nexp)\n  rmax_extend_ = cyl_bessel_j_zero(float(order), nr_ + 1) /\n                 cyl_bessel_j_zero(float(order), nr + 1) * rmax;\n  shift_matrix_ = tmatrix_.leftCols(nr) * tmatrix_.topRows(nr);\n}\n\nTrimDHT::~TrimDHT() = default;\n\nVectorXd TrimDHT::perform(const Ref<const VectorXd> &src) {\n  VectorXd ret;\n  ret = shift_matrix_ * src;\n  return ret;\n}\n\nVectorXd TrimDHT::r_sampling() {\n  return DiscreteHankelTransform::r_sampling(rmax_extend_);\n}\n\nVectorXd TrimDHT::k_sampling() {\n  return DiscreteHankelTransform::k_sampling(rmax_extend_);\n}\n\nint TrimDHT::get_nr() const { return nr_; }", "meta": {"hexsha": "3846ee6a49a1dad466c7072c1661d0192e8dcdad", "size": 1066, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/trim_dht.cc", "max_stars_repo_name": "pan3rock/discrete-hankel-transform", "max_stars_repo_head_hexsha": "708d3d32e1c4170ed68322e53e26267f93e0ab9d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/trim_dht.cc", "max_issues_repo_name": "pan3rock/discrete-hankel-transform", "max_issues_repo_head_hexsha": "708d3d32e1c4170ed68322e53e26267f93e0ab9d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/trim_dht.cc", "max_forks_repo_name": "pan3rock/discrete-hankel-transform", "max_forks_repo_head_hexsha": "708d3d32e1c4170ed68322e53e26267f93e0ab9d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-16T09:56:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-16T09:56:44.000Z", "avg_line_length": 26.0, "max_line_length": 64, "alphanum_fraction": 0.7148217636, "num_tokens": 311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4876465953176269}}
{"text": "#include <iostream>\n#include <math.h>\n\n#include <boost/bind/bind.hpp>\n#include \"boost/math/special_functions/pow.hpp\"\n#include <boost/numeric/ublas/lu.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/math/special_functions/factorials.hpp>\n#include <boost/tuple/tuple.hpp>\n\n#include \"Filtering.hpp\"\n\nusing namespace boost::math;\nusing namespace boost::numeric::ublas;\n\n#define POW(a,b) pow(a,b)\n\nclass AbstractRadarCoordinates {\npublic:\n\n\tRealMatrix ENU2AER(RealVector E, RealVector N, RealVector U) {\n\t\tRealMatrix AER(E.size(), 3);\n\t\tAER(0, 0) = fmod(atan2(N(0), E(0)), (2.0*constants::pi<double>()));  // azimuth\n\t\tAER(0, 1) = atan2(U(0), sqrt(pow<2>(E(0)) + pow<2>(N(0))));\n\t\tAER(0, 2) = sqrt(pow<2>(E(0)) + pow<2>(N(0)) + pow<2>(U(0)));\n\t\treturn AER;\n\t};\n\n\tRealMatrix AER2ENU(RealVector A, RealVector E, RealVector R) {\n\t\tRealMatrix ENU(A.size(), 3);\n\t\tENU(0, 0) = R(0) * cos(E(0)) * sin(A(0));\n\t\tENU(0, 1) = R(0) * cos(E(0)) * cos(A(0));\n\t\tENU(0, 2) = R(0) * sin(E(0));\n\t\treturn ENU;\n\t};\n\nprotected:\n\tvirtual double d1AzimuthdENU1(const RealVector E, const RealVector N, const RealVector U) = 0;\n\tvirtual double d2AzimuthdENU2(const RealVector E, const RealVector N, const RealVector U) = 0;\n\tvirtual double d3AzimuthdENU3(const RealVector E, const RealVector N, const RealVector U) = 0;\n\tvirtual double d4AzimuthdENU4(const RealVector E, const RealVector N, const RealVector U) = 0;\n\tvirtual double d5AzimuthdENU5(const RealVector E, const RealVector N, const RealVector U) = 0;\n\n\tvirtual double d1ElevationdENU1(const RealVector E, const RealVector N, const RealVector U) = 0;\n\tvirtual double d2ElevationdENU2(const RealVector E, const RealVector N, const RealVector U) = 0;\n\tvirtual double d3ElevationdENU3(const RealVector E, const RealVector N, const RealVector U) = 0;\n\tvirtual double d4ElevationdENU4(const RealVector E, const RealVector N, const RealVector U) = 0;\n\tvirtual double d5ElevationdENU5(const RealVector E, const RealVector N, const RealVector U) = 0;\n\n\tvirtual double d1RangedENU1(const RealVector E, const RealVector N, const RealVector U) = 0;\n\tvirtual double d2RangedENU2(const RealVector E, const RealVector N, const RealVector U) = 0;\n\tvirtual double d3RangedENU3(const RealVector E, const RealVector N, const RealVector U) = 0;\n\tvirtual double d4RangedENU4(const RealVector E, const RealVector N, const RealVector U) = 0;\n\tvirtual double d5RangedENU5(const RealVector E, const RealVector N, const RealVector U) = 0;\n\n\tvirtual double d1EastdAER1(const RealVector A, const RealVector E, const RealVector R) = 0;\n\tvirtual double d2EastdAER2(const RealVector A, const RealVector E, const RealVector R) = 0;\n\tvirtual double d3EastdAER3(const RealVector A, const RealVector E, const RealVector R) = 0;\n\tvirtual double d4EastdAER4(const RealVector A, const RealVector E, const RealVector R) = 0;\n\tvirtual double d5EastdAER5(const RealVector A, const RealVector E, const RealVector R) = 0;\n\n\tvirtual double d1NorthdAER1(const RealVector A, const RealVector E, const RealVector R) = 0;\n\tvirtual double d2NorthdAER2(const RealVector A, const RealVector E, const RealVector R) = 0;\n\tvirtual double d3NorthdAER3(const RealVector A, const RealVector E, const RealVector R) = 0;\n\tvirtual double d4NorthdAER4(const RealVector A, const RealVector E, const RealVector R) = 0;\n\tvirtual double d5NorthdAER5(const RealVector A, const RealVector E, const RealVector R) = 0;\n\n\tvirtual double d1UpdAER1(const RealVector A, const RealVector E, const RealVector R) = 0;\n\tvirtual double d2UpdAER2(const RealVector A, const RealVector E, const RealVector R) = 0;\n\tvirtual double d3UpdAER3(const RealVector A, const RealVector E, const RealVector R) = 0;\n\tvirtual double d4UpdAER4(const RealVector A, const RealVector E, const RealVector R) = 0;\n\tvirtual double d5UpdAER5(const RealVector A, const RealVector E, const RealVector R) = 0;\n\n};", "meta": {"hexsha": "d579752fc7ba796d3a47eeeccac94242383b9ff9", "size": 3852, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Cpp/Eigen/src/AbstractRadarCoordinates.hpp", "max_stars_repo_name": "lintondf/MorrisonPolynomialFiltering", "max_stars_repo_head_hexsha": "f5713f9ed9a24c1382875d8ebdec00100f39e3a5", "max_stars_repo_licenses": ["MIT"], "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/Eigen/src/AbstractRadarCoordinates.hpp", "max_issues_repo_name": "lintondf/MorrisonPolynomialFiltering", "max_issues_repo_head_hexsha": "f5713f9ed9a24c1382875d8ebdec00100f39e3a5", "max_issues_repo_licenses": ["MIT"], "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/Eigen/src/AbstractRadarCoordinates.hpp", "max_forks_repo_name": "lintondf/MorrisonPolynomialFiltering", "max_forks_repo_head_hexsha": "f5713f9ed9a24c1382875d8ebdec00100f39e3a5", "max_forks_repo_licenses": ["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.0540540541, "max_line_length": 97, "alphanum_fraction": 0.7481827622, "num_tokens": 1209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181874, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.48763521263412435}}
{"text": "//==================================================================================================\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_AVX_SIMD_FUNCTION_RSQRT_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_X86_AVX_SIMD_FUNCTION_RSQRT_HPP_INCLUDED\n\n#include <boost/simd/function/abs.hpp>\n#include <boost/simd/detail/overload.hpp>\n#include <boost/simd/function/sqr.hpp>\n#include <boost/simd/function/if_else.hpp>\n#include <boost/simd/function/if_zero_else.hpp>\n#include <boost/simd/function/is_eqz.hpp>\n#include <boost/simd/function/fnms.hpp>\n#include <boost/simd/constant/half.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/three.hpp>\n#include <boost/simd/constant/ratio.hpp>\n#include <boost/simd/function/raw.hpp>\n#include <boost/simd/function/pedantic.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n   namespace bd = boost::dispatch;\n   namespace bs = boost::simd;\n\n  BOOST_DISPATCH_OVERLOAD( rsqrt_\n                         , (typename A0)\n                         , bs::avx_\n                         , bs::raw_tag\n                         , bs::pack_< bd::single_<A0>, bs::avx_>\n                         )\n   {\n     BOOST_FORCEINLINE A0 operator()( const bs::raw_tag &, A0 const& a0) const\n      {\n        return _mm256_rsqrt_ps( a0 );\n      }\n   };\n\n  BOOST_DISPATCH_OVERLOAD( rsqrt_\n                         , (typename A0)\n                         , bs::avx_\n                         , bs::raw_tag\n                         , bs::pack_< bd::double_<A0>, bs::avx_>\n                         )\n   {\n     BOOST_FORCEINLINE A0 operator()( const bs::raw_tag &, A0 const& a0) const\n      {\n        return _mm256_cvtps_pd(_mm_rsqrt_ps( _mm256_cvtpd_ps(a0) ));//The error for this approximation is no more than 1.5.e-12\n      }\n   };\n\n  BOOST_DISPATCH_OVERLOAD( rsqrt_\n                         , (typename A0)\n                         , bs::avx_\n                         , bs::pack_< bd::single_<A0>, bs::avx_>\n                         )\n   {\n     BOOST_FORCEINLINE A0 operator()(A0 const& a00) const\n      {\n        A0 a0 =  raw_(rsqrt)(a00);\n        A0 y = sqr(a0)*a00;\n        a0 = a0*Ratio<A0, 1, 8>()*fnms(y, fnms(A0(3), y, A0(10)), A0(15)); //this is Halley cubically convergent iteration\n        #ifndef BOOST_SIMD_NO_INFINITIES\n        a0 = if_zero_else(a00 == Inf<A0>(),a0);\n        #endif\n        return if_else(is_eqz(a00), Inf<A0>(), a0);\n      }\n   };\n\n  BOOST_DISPATCH_OVERLOAD( rsqrt_\n                         , (typename A0)\n                         , bs::avx_\n                         , bs::pack_< bd::double_<A0>, bs::avx_>\n                         )\n   {\n     BOOST_FORCEINLINE A0 operator()(A0 const& a00) const\n      {\n        // To obtain accuracy we need 3 Newton steps or one Halley step followed by one Newton from the raw estimate\n        // the second method is a bit faster by half a cycle\n        A0 a0 =  raw_(rsqrt)(a00);\n        A0 y = sqr(a0)*a00;\n        a0 = a0*Ratio<A0, 1, 8>()*fnms(y, fnms(A0(3), y, A0(10)), A0(15)); //this is Halley cubically convergent iteration\n        a0 = refine_rsqrt(a00, a0);\n        #ifndef BOOST_SIMD_NO_INFINITIES\n        a0 = if_zero_else(a00 == Inf<A0>(),a0);\n        #endif\n        return if_else(is_eqz(a00), Inf<A0>(), a0);\n      }\n   };\n\n   BOOST_DISPATCH_OVERLOAD ( rsqrt_\n                          , (typename A0)\n                          , bs::avx_\n                          , bs::pedantic_tag\n                          , bs::pack_<bd::single_<A0>, bs::avx_>\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() (pedantic_tag const&\n                                    ,const A0 & a00) const BOOST_NOEXCEPT\n    {\n      A0 a0 = a00;\n      auto is_den = bs::abs(a00) < Smallestposval<A0>();\n      #ifndef BOOST_SIMD_NO_DENORMALS\n      a0 *= if_else(is_den, Denormalfactor<A0>(), One<A0>());\n      #endif\n      a0 = refine_rsqrt(a0, refine_rsqrt(a0, raw_(rsqrt)(a0)));\n      #ifndef BOOST_SIMD_NO_DENORMALS\n      a0 *= if_else(is_den, Denormalsqrtfactor<A0>(), One<A0>());\n      #endif\n\n      #ifndef BOOST_SIMD_NO_INFINITIES\n      a0 = if_zero_else(a00 == Inf<A0>(),a0);\n      #endif\n      return if_else(is_eqz(a00), Inf<A0>(), a0);\n    }\n  };\n\n   BOOST_DISPATCH_OVERLOAD ( rsqrt_\n                          , (typename A0)\n                          , bs::avx_\n                          , bs::pedantic_tag\n                          , bs::pack_<bd::double_<A0>, bs::avx_>\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() (pedantic_tag const&\n                                    ,const A0 & a00) const BOOST_NOEXCEPT\n    {\n      A0 a01 =  a00;\n      auto is_den = bs::abs(a00) < Smallestposval<A0>();\n      #ifndef BOOST_SIMD_NO_DENORMALS\n      a01 *= if_else(is_den, Denormalfactor<A0>(), One<A0>());\n      #endif\n      A0 a0 =  raw_(rsqrt)(a01);\n      A0 y = sqr(a0)*a01;\n      a0 = a0*Ratio<A0, 1, 8>()*fnms(y, fnms(A0(3), y, A0(10)), A0(15)); //this is Halley cubically convergent iteration\n      a0 = refine_rsqrt(a00, a0);\n      #ifndef BOOST_SIMD_NO_DENORMALS\n      a0 *= if_else(is_den, Denormalsqrtfactor<A0>(), One<A0>());\n      #endif\n\n      #ifndef BOOST_SIMD_NO_INFINITIES\n      a0 = if_zero_else(a00 == Inf<A0>(),a0);\n      #endif\n      return if_else(is_eqz(a00), Inf<A0>(), a0);\n    }\n  };\n} } }\n\n#endif\n", "meta": {"hexsha": "51854117dab34f2b19e9f2a4098aa809af68deef", "size": 5526, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/x86/avx/simd/function/rsqrt.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/x86/avx/simd/function/rsqrt.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/x86/avx/simd/function/rsqrt.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.6516129032, "max_line_length": 127, "alphanum_fraction": 0.5275063337, "num_tokens": 1511, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.48762851714182803}}
{"text": "// Boost.Geometry Index\n//\n// squared distance between point and nearest point of the box or point\n//\n// Copyright (c) 2011-2014 Adam Wulkiewicz, Lodz, Poland.\n//\n// This file was modified by Oracle on 2021.\n// Modifications copyright (c) 2021 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_INDEX_DETAIL_ALGORITHMS_COMPARABLE_DISTANCE_NEAR_HPP\n#define BOOST_GEOMETRY_INDEX_DETAIL_ALGORITHMS_COMPARABLE_DISTANCE_NEAR_HPP\n\n#include <boost/geometry/algorithms/detail/comparable_distance/interface.hpp>\n#include <boost/geometry/core/access.hpp>\n\n#include <boost/geometry/index/detail/algorithms/sum_for_indexable.hpp>\n\nnamespace boost { namespace geometry { namespace index { namespace detail {\n\nstruct comparable_distance_near_tag {};\n\ntemplate <\n    typename Point,\n    typename PointIndexable,\n    size_t N>\nstruct sum_for_indexable<Point, PointIndexable, point_tag, comparable_distance_near_tag, N>\n{\n    typedef typename geometry::default_comparable_distance_result<Point, PointIndexable>::type result_type;\n\n    inline static result_type apply(Point const& pt, PointIndexable const& i)\n    {\n        return geometry::comparable_distance(pt, i);\n    }\n};\n\ntemplate <\n    typename Point,\n    typename BoxIndexable,\n    size_t DimensionIndex>\nstruct sum_for_indexable_dimension<Point, BoxIndexable, box_tag, comparable_distance_near_tag, DimensionIndex>\n{\n    typedef typename geometry::default_comparable_distance_result<Point, BoxIndexable>::type result_type;\n\n    inline static result_type apply(Point const& pt, BoxIndexable const& i)\n    {\n        typedef typename coordinate_type<Point>::type point_coord_t;\n        typedef typename coordinate_type<BoxIndexable>::type indexable_coord_t;\n\n        point_coord_t pt_c = geometry::get<DimensionIndex>(pt);\n        indexable_coord_t ind_c_min = geometry::get<geometry::min_corner, DimensionIndex>(i);\n        indexable_coord_t ind_c_max = geometry::get<geometry::max_corner, DimensionIndex>(i);\n\n        result_type diff = 0;\n\n        if ( pt_c < ind_c_min )\n            diff = ind_c_min - pt_c;\n        else if ( ind_c_max < pt_c )\n            diff = pt_c - ind_c_max;\n\n        return diff * diff;\n    }\n};\n\ntemplate <typename Point, typename Indexable>\ntypename geometry::default_comparable_distance_result<Point, Indexable>::type\ncomparable_distance_near(Point const& pt, Indexable const& i)\n{\n    return detail::sum_for_indexable<\n        Point,\n        Indexable,\n        typename tag<Indexable>::type,\n        detail::comparable_distance_near_tag,\n        dimension<Indexable>::value\n    >::apply(pt, i);\n}\n\n}}}} // namespace boost::geometry::index::detail\n\n#endif // BOOST_GEOMETRY_INDEX_DETAIL_ALGORITHMS_COMPARABLE_DISTANCE_NEAR_HPP\n", "meta": {"hexsha": "4f2905f3a19b40bc5fa732a97d8c47a0d02ef716", "size": 2961, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/boost_1.78.0/boost/geometry/index/detail/algorithms/comparable_distance_near.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/index/detail/algorithms/comparable_distance_near.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/index/detail/algorithms/comparable_distance_near.hpp", "max_forks_repo_name": "LaudateCorpus1/math", "max_forks_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-01-14T15:50:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T03:58:36.000Z", "avg_line_length": 34.8352941176, "max_line_length": 110, "alphanum_fraction": 0.7483958122, "num_tokens": 668, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.487628517141828}}
{"text": "#include <scitbx/array_family/boost_python/flex_fwd.h>\n\n#include <scitbx/math/mean_and_variance.h>\n#include <boost/python/class.hpp>\n\nnamespace scitbx { namespace af { namespace boost_python { namespace {\n\n  struct mean_and_variance_wrappers\n  {\n    typedef math::mean_and_variance<> w_t;\n\n    static void\n    wrap()\n    {\n      using namespace boost::python;\n      class_<w_t>(\"mean_and_variance\", no_init)\n        .def(init<af::const_ref<double> const&>())\n        .def(init<af::const_ref<double> const&,\n                  af::const_ref<double> const&>())\n        .def(\"have_weights\", &w_t::have_weights)\n        .def(\"mean\", &w_t::mean)\n        .def(\"gsl_stats_wvariance\", &w_t::gsl_stats_wvariance)\n        .def(\"gsl_stats_wsd\", &w_t::gsl_stats_wsd)\n        .def(\"standard_error_of_mean_calculated_from_sample_weights\",\n          &w_t::standard_error_of_mean_calculated_from_sample_weights)\n        .def(\"unweighted_sample_variance\", &w_t::unweighted_sample_variance)\n        .def(\"unweighted_sample_standard_deviation\",\n          &w_t::unweighted_sample_standard_deviation)\n        .def(\"unweighted_standard_error_of_mean\",\n          &w_t::unweighted_standard_error_of_mean)\n        .def(\"sum_weights\", &w_t::sum_weights)\n        .def(\"sum_weights_sq\", &w_t::sum_weights_sq)\n        .def(\"sum_weights_values\", &w_t::sum_weights_values)\n        .def(\"sum_weights_delta_sq\", &w_t::sum_weights_delta_sq)\n      ;\n    }\n  };\n\n} // namespace <anonymous>\n\n  void wrap_flex_mean_and_variance()\n  {\n    mean_and_variance_wrappers::wrap();\n  }\n\n}}} // namespace scitbx::af::boost_python\n", "meta": {"hexsha": "eb065251d3f60f9b7d71b5d9a9056f52d788241b", "size": 1582, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "scitbx/array_family/boost_python/flex_mean_and_variance.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/array_family/boost_python/flex_mean_and_variance.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/array_family/boost_python/flex_mean_and_variance.cpp", "max_forks_repo_name": "rimmartin/cctbx_project", "max_forks_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 115.0, "max_forks_repo_forks_event_min_datetime": "2016-11-15T08:17:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T15:30:14.000Z", "avg_line_length": 33.6595744681, "max_line_length": 76, "alphanum_fraction": 0.6801517067, "num_tokens": 407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038221, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.48762851183964373}}
{"text": "#include <VirtualRobot/VirtualRobot.h>\n#include <VirtualRobot/Robot.h>\n#include <VirtualRobot/MathTools.h>\n#include <VirtualRobot/CollisionDetection/CollisionChecker.h>\n\n#include <boost/make_shared.hpp>\n\n#include \"uxabiped/utils/Walking.h\"\n#include \"uxabiped/utils/Kinematics.h\"\n\nnamespace Bipedal\n{\n\nVirtualRobot::MathTools::ConvexHull2DPtr ComputeFootContact(const VirtualRobot::CollisionModelPtr& colModel)\n{\n    // let the feet collide with the floor and get the collision points\n    VirtualRobot::MathTools::Plane plane =  VirtualRobot::MathTools::getFloorPlane();\n    VirtualRobot::CollisionCheckerPtr colChecker = VirtualRobot::CollisionChecker::getGlobalCollisionChecker();\n    std::vector< VirtualRobot::MathTools::ContactPoint > pointsFoot;\n    std::vector< Eigen::Vector2f > points2D;\n\n    // let the collision begin\n    colChecker->getContacts(plane, colModel, pointsFoot, 5.0f);\n\n    // project the points on the floor\n    for (size_t u = 0; u < pointsFoot.size(); u++)\n    {\n        Eigen::Vector2f pt2d = VirtualRobot::MathTools::projectPointToPlane2D(pointsFoot[u].p, plane);\n        points2D.push_back(pt2d);\n    }\n\n    // calculate the convex hulls and the appropriate centers\n    VirtualRobot::MathTools::ConvexHull2DPtr hull = VirtualRobot::MathTools::createConvexHull2D(points2D);\n\n    return hull;\n}\n\nEigen::Vector2f CenterConvexHull(const VirtualRobot::MathTools::ConvexHull2DPtr& hull)\n{\n    Eigen::Vector2f center = VirtualRobot::MathTools::getConvexHullCenter(hull);\n\n    // translate points of FootShape so, that center of convex hull is (0|0)\n    for (unsigned i =  0; i < hull->vertices.size(); i++)\n    {\n        hull->vertices[i] -= center;\n    }\n\n    return center;\n}\n\nvoid TransformConvexHull(const VirtualRobot::MathTools::ConvexHull2DPtr& hull, const Eigen::Matrix3f& frame)\n{\n    // translate points of FootShape so, that center of convex hull is (0|0)\n    for (unsigned i =  0; i < hull->vertices.size(); i++)\n    {\n        hull->vertices[i] = frame.block(0, 0, 2, 2) * hull->vertices[i] + frame.block(0, 2, 2, 1);\n    }\n}\n\nEigen::Matrix2f ComputeWalkingDirection(const Eigen::Vector2f& leftFootCenter, const Eigen::Vector2f& rightFootCenter)\n{\n    Eigen::Vector2f center = (leftFootCenter + rightFootCenter) * 0.5;\n    Eigen::Vector2f centerToLeft = (leftFootCenter - center);\n    centerToLeft.normalize();\n    Eigen::Matrix2f rotNinety;\n    rotNinety << 0, 1, -1, 0;\n    Eigen::Vector2f walkingDirection = rotNinety * centerToLeft;\n\n    // Note: The TCP coordinate system in Armar4 uses y as forward direction\n    Eigen::Matrix2f pose;\n    pose << -centerToLeft.x(), walkingDirection.x(), -centerToLeft.y(), walkingDirection.y();\n\n    return pose;\n}\n\nEigen::Vector2f computeHullContactPoint(const Eigen::Vector2f p, const VirtualRobot::MathTools::ConvexHull2DPtr& hull)\n{\n    double min = std::numeric_limits<double>::max();\n    VirtualRobot::MathTools::Segment2D min_segment;\n    for(const auto& segment : hull->segments)\n    {\n        double dist = VirtualRobot::MathTools::distPointSegment(hull->vertices[segment.id1],\n                hull->vertices[segment.id2], p);\n        if (dist < min)\n        {\n            min = dist;\n            min_segment = segment;\n        }\n    }\n    return VirtualRobot::MathTools::nearestPointOnSegment(hull->vertices[min_segment.id1], hull->vertices[min_segment.id2], p);\n}\n\nVirtualRobot::MathTools::ConvexHull2DPtr computeConvexHull(const VirtualRobot::RobotNodePtr& foot,\n                                                           const VirtualRobot::RobotNodePtr& tcp)\n{\n    auto colModel = foot->getCollisionModel()->clone();\n    Eigen::Matrix4f relPose = tcp->getGlobalPose().inverse() * colModel->getGlobalPose();\n    colModel->setGlobalPose(relPose);\n    auto hull = Bipedal::ComputeFootContact(colModel);\n    Bipedal::CenterConvexHull(hull);\n    return hull;\n}\n\nVirtualRobot::MathTools::ConvexHull2DPtr computeSupportPolygone(const Eigen::Matrix4f& leftFootPose,\n                                                                const Eigen::Matrix4f& rightFootPose,\n                                                                const VirtualRobot::MathTools::ConvexHull2DPtr& leftFootHull,\n                                                                const VirtualRobot::MathTools::ConvexHull2DPtr& rightFootHull,\n                                                                Bipedal::SupportPhase phase)\n{\n    if (phase == SUPPORT_LEFT)\n        return boost::make_shared<VirtualRobot::MathTools::ConvexHull2D>(*leftFootHull);\n\n    if (phase == SUPPORT_RIGHT)\n        return boost::make_shared<VirtualRobot::MathTools::ConvexHull2D>(*rightFootHull);\n\n    if (phase == SUPPORT_BOTH)\n    {\n        Eigen::Vector2f offset = rightFootPose.block(0, 3, 2, 1) - leftFootPose.block(0, 3, 2, 1);\n\n        std::vector<Eigen::Vector2f> points;\n        for (const auto& v : leftFootHull->vertices)\n        {\n            points.push_back(v - offset/2);\n        }\n        for (const auto& v : rightFootHull->vertices)\n        {\n            points.push_back(v + offset/2);\n        }\n\n        auto dualSupportHull = VirtualRobot::MathTools::createConvexHull2D(points);\n        Bipedal::CenterConvexHull(dualSupportHull);\n\n        return dualSupportHull;\n    }\n\n    return VirtualRobot::MathTools::ConvexHull2DPtr();\n}\n\n}\n", "meta": {"hexsha": "445a969f2a72038061e1d2036438ace741f91aaa", "size": 5294, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "uxabiped/src/utils/Walking.cpp", "max_stars_repo_name": "nvtienanh/UXAProject", "max_stars_repo_head_hexsha": "b17b1b43db9993af6cd9bb0aaeb1296960bfe8f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "uxabiped/src/utils/Walking.cpp", "max_issues_repo_name": "nvtienanh/UXAProject", "max_issues_repo_head_hexsha": "b17b1b43db9993af6cd9bb0aaeb1296960bfe8f1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "uxabiped/src/utils/Walking.cpp", "max_forks_repo_name": "nvtienanh/UXAProject", "max_forks_repo_head_hexsha": "b17b1b43db9993af6cd9bb0aaeb1296960bfe8f1", "max_forks_repo_licenses": ["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.8142857143, "max_line_length": 127, "alphanum_fraction": 0.6603702304, "num_tokens": 1365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907933, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.48757918738692324}}
{"text": "#include <boost/math/quadrature/exp_sinh.hpp>\n", "meta": {"hexsha": "0a52ccef704656aaf814592c338bb27e91cca9b4", "size": 46, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_quadrature_exp_sinh.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_quadrature_exp_sinh.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_quadrature_exp_sinh.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 23.0, "max_line_length": 45, "alphanum_fraction": 0.8043478261, "num_tokens": 12, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907933, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.48757918738692324}}
{"text": "#include \"src/utils/distributions.h\"\n\n#include <gtest/gtest.h>\n\n#include <Eigen/Dense>\n#include <stan/math/prim.hpp>\n#include <vector>\n\n#include \"src/utils/rng.h\"\n\nTEST(mix_dist, 1) {\n  auto& rng = bayesmix::Rng::Instance().get();\n\n  int nclus = 5;\n  Eigen::VectorXd weights1 =\n      stan::math::dirichlet_rng(Eigen::VectorXd::Ones(nclus), rng);\n  Eigen::VectorXd means1(nclus);\n  Eigen::VectorXd sds1(nclus);\n\n  for (int i = 0; i < nclus; i++) {\n    means1(i) = stan::math::normal_rng(0, 2, rng);\n    sds1(i) = stan::math::uniform_rng(0.1, 2.0, rng);\n  }\n\n  int nclus2 = 10;\n  Eigen::VectorXd weights2 =\n      stan::math::dirichlet_rng(Eigen::VectorXd::Ones(nclus2), rng);\n  Eigen::VectorXd means2(nclus2);\n  Eigen::VectorXd sds2(nclus2);\n\n  for (int i = 0; i < nclus2; i++) {\n    means2(i) = stan::math::normal_rng(0, 2, rng);\n    sds2(i) = stan::math::uniform_rng(0.1, 2.0, rng);\n  }\n\n  double dist = bayesmix::gaussian_mixture_dist(means1, sds1, weights1, means2,\n                                                sds2, weights2);\n\n  ASSERT_GE(dist, 0.0);\n}\n\nTEST(mix_dist, 2) {\n  int nclus = 5;\n  auto& rng = bayesmix::Rng::Instance().get();\n\n  Eigen::VectorXd weights1 =\n      stan::math::dirichlet_rng(Eigen::VectorXd::Ones(nclus), rng);\n  Eigen::VectorXd means1(nclus);\n  Eigen::VectorXd sds1(nclus);\n\n  for (int i = 0; i < nclus; i++) {\n    means1(i) = stan::math::normal_rng(0, 2, rng);\n    sds1(i) = stan::math::uniform_rng(0.1, 2.0, rng);\n  }\n\n  double dist_to_self = bayesmix::gaussian_mixture_dist(\n      means1, sds1, weights1, means1, sds1, weights1);\n\n  ASSERT_DOUBLE_EQ(dist_to_self, 0.0);\n}\n\nTEST(student_t, squareform) {\n  Eigen::MatrixXd A = Eigen::MatrixXd::Random(5, 5);\n  Eigen::MatrixXd sigma =\n      (A * A.transpose()) + 1.0 * Eigen::MatrixXd::Identity(5, 5);\n  Eigen::VectorXd mean = Eigen::VectorXd::Zero(5);\n  double df = 15;\n\n  Eigen::MatrixXd sigma_inv = stan::math::inverse_spd(sigma);\n  Eigen::MatrixXd sigma_inv_chol =\n      Eigen::LLT<Eigen::MatrixXd>(sigma_inv).matrixU();\n\n  Eigen::VectorXd x = Eigen::VectorXd::Ones(5);\n\n  double sq1 = (x - mean).transpose() * sigma_inv * (x - mean);\n  double sq2 = (sigma_inv_chol * (x - mean)).squaredNorm();\n\n  ASSERT_DOUBLE_EQ(sq1, sq2);\n}\n\nTEST(student_t, optimized) {\n  Eigen::MatrixXd A = Eigen::MatrixXd::Random(5, 5);\n  Eigen::MatrixXd sigma =\n      (A * A.transpose()) + 1.0 * Eigen::MatrixXd::Identity(5, 5);\n  Eigen::VectorXd mean = Eigen::VectorXd::Zero(5);\n  double df = 15;\n\n  Eigen::VectorXd x = Eigen::VectorXd::Ones(5);\n\n  double lpdf_stan = stan::math::multi_student_t_lpdf(x, df, mean, sigma);\n  // std::cout << \"lpdf_stan: \" << lpdf_stan << std::endl;\n\n  Eigen::MatrixXd sigma_inv = stan::math::inverse_spd(sigma);\n  Eigen::MatrixXd sigma_inv_chol =\n      Eigen::LLT<Eigen::MatrixXd>(sigma_inv).matrixU();\n  Eigen::VectorXd diag = sigma_inv_chol.diagonal();\n  double logdet = 2 * log(diag.array()).sum();\n\n  double our_lpdf = bayesmix::multi_student_t_invscale_lpdf(\n      x, df, mean, sigma_inv_chol, logdet);\n\n  // std::cout << \"our_lpdf: \" << our_lpdf << std::endl;\n\n  ASSERT_LE(std::abs(our_lpdf - lpdf_stan), 0.001);\n}\n\nTEST(student_t, marginal) {\n  double var_scaling = 0.1;\n  double deg_free = 10;\n  int dim = 3;\n\n  Eigen::MatrixXd A = Eigen::MatrixXd::Random(dim, dim);\n  Eigen::MatrixXd scale_inv =\n      (A * A.transpose()) + 1.0 * Eigen::MatrixXd::Identity(dim, dim);\n\n  Eigen::MatrixXd sigma_n =\n      scale_inv * (var_scaling + 1) / (var_scaling * (deg_free - dim + 1));\n  double nu_n = deg_free - dim + 1;\n\n  Eigen::VectorXd datum = Eigen::VectorXd::Ones(dim);\n  Eigen::VectorXd mean = Eigen::VectorXd::Zero(dim);\n\n  Eigen::MatrixXd scale = stan::math::inverse_spd(scale_inv);\n  Eigen::MatrixXd scale_chol = Eigen::LLT<Eigen::MatrixXd>(scale).matrixU();\n\n  double coeff = (var_scaling + 1) / (var_scaling * (deg_free - dim + 1));\n  Eigen::MatrixXd scale_chol_n = scale_chol / std::sqrt(coeff);\n  Eigen::VectorXd diag = scale_chol_n.diagonal();\n  double logdet = 2 * log(diag.array()).sum();\n\n  double old_qf = (datum - mean).transpose() *\n                  stan::math::inverse_spd(sigma_n) * (datum - mean);\n\n  double new_qf = (scale_chol_n * (datum - mean)).squaredNorm();\n\n  ASSERT_DOUBLE_EQ(old_qf, new_qf);\n\n  double old_lpdf =\n      stan::math::multi_student_t_lpdf(datum, nu_n, mean, sigma_n);\n\n  double new_lpdf = bayesmix::multi_student_t_invscale_lpdf(\n      datum, nu_n, mean, scale_chol_n, logdet);\n\n  ASSERT_LE(std::abs(old_lpdf - new_lpdf), 0.001);\n}\n\nTEST(mult_normal, lpdf_grid) {\n  int dim = 3;\n\n  Eigen::MatrixXd data = Eigen::MatrixXd::Random(20, dim);\n  Eigen::VectorXd mean = Eigen::ArrayXd::LinSpaced(dim, 0.0, 10.0);\n  Eigen::MatrixXd tmp = Eigen::MatrixXd::Random(dim + 1, dim);\n  Eigen::MatrixXd prec =\n      tmp.transpose() * tmp + Eigen::MatrixXd::Identity(dim, dim);\n  Eigen::MatrixXd prec_chol = Eigen::LLT<Eigen::MatrixXd>(prec).matrixU();\n  Eigen::VectorXd diag = prec_chol.diagonal();\n  double prec_logdet = 2 * log(diag.array()).sum();\n\n  Eigen::VectorXd lpdfs = bayesmix::multi_normal_prec_lpdf_grid(\n      data, mean, prec_chol, prec_logdet);\n\n  for (int i = 0; i < 20; i++) {\n    double curr = bayesmix::multi_normal_prec_lpdf(data.row(i), mean,\n                                                   prec_chol, prec_logdet);\n    ASSERT_DOUBLE_EQ(curr, lpdfs(i));\n  }\n}\n\nTEST(mult_t, lpdf_grid) {\n  int dim = 3;\n\n  Eigen::MatrixXd data = Eigen::MatrixXd::Random(20, dim);\n  Eigen::VectorXd mean = Eigen::ArrayXd::LinSpaced(dim, 0.0, 10.0);\n  Eigen::MatrixXd tmp = Eigen::MatrixXd::Random(dim + 1, dim);\n  Eigen::MatrixXd invscale =\n      tmp.transpose() * tmp + Eigen::MatrixXd::Identity(dim, dim);\n  Eigen::MatrixXd invscale_chol =\n      Eigen::LLT<Eigen::MatrixXd>(invscale).matrixU();\n  Eigen::VectorXd diag = invscale_chol.diagonal();\n  double invscale_logdet = 2 * log(diag.array()).sum();\n  double df = 10;\n\n  Eigen::VectorXd lpdfs = bayesmix::multi_student_t_invscale_lpdf_grid(\n      data, df, mean, invscale_chol, invscale_logdet);\n\n  for (int i = 0; i < 20; i++) {\n    double curr = bayesmix::multi_student_t_invscale_lpdf(\n        data.row(i), df, mean, invscale_chol, invscale_logdet);\n    ASSERT_DOUBLE_EQ(curr, lpdfs(i));\n  }\n}\n\nTEST(lpdf_woodbury, 1) {\n  int dim = 1000;\n  int q = 10;\n  auto& rng = bayesmix::Rng::Instance().get();\n  Eigen::VectorXd mean(dim);\n  Eigen::VectorXd datum(dim);\n  Eigen::VectorXd sigma_diag(dim);\n  Eigen::MatrixXd lambda(dim, q);\n\n  for (size_t j = 0; j < dim; j++) {\n    mean[j] = stan::math::normal_rng(0, 1, rng);\n\n    sigma_diag[j] = stan::math::inv_gamma_rng(2.5, 1, rng);\n\n    for (size_t i = 0; i < q; i++) {\n      lambda(j, i) = stan::math::normal_rng(0, 1, rng);\n    }\n  }\n\n  Eigen::MatrixXd cov =\n      lambda * lambda.transpose() + Eigen::MatrixXd(sigma_diag.asDiagonal());\n\n  datum = stan::math::multi_normal_rng(mean, cov, rng);\n\n  double stan_lpdf = stan::math::multi_normal_lpdf(datum, mean, cov);\n  double our_lpdf =\n      bayesmix::multi_normal_lpdf_woodbury(datum, mean, sigma_diag, lambda);\n\n  ASSERT_LE(std::abs(stan_lpdf - our_lpdf), 1e-10);\n}\n", "meta": {"hexsha": "38e4d38d50750c10109432ede6945a804cd9906f", "size": 7047, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/distributions.cc", "max_stars_repo_name": "TeoGiane/bayesmix", "max_stars_repo_head_hexsha": "43182d61c3f332aefb832426cc9e8e2b2394bd68", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/distributions.cc", "max_issues_repo_name": "TeoGiane/bayesmix", "max_issues_repo_head_hexsha": "43182d61c3f332aefb832426cc9e8e2b2394bd68", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/distributions.cc", "max_forks_repo_name": "TeoGiane/bayesmix", "max_forks_repo_head_hexsha": "43182d61c3f332aefb832426cc9e8e2b2394bd68", "max_forks_repo_licenses": ["BSD-3-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.600896861, "max_line_length": 79, "alphanum_fraction": 0.648502909, "num_tokens": 2211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4875791776990873}}
{"text": "//\n// Created by a.kiryanenko on 3/26/20.\n//\n\n#include \"../SpuUltraGraphAdapter.h\"\n#include \"../SpuUltraGraphProperty.h\"\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/depth_first_search.hpp>\n#include \"GraphPerformanceTest.h\"\n\n\nusing namespace SPU_GRAPH;\nusing namespace boost;\n\n\ntypedef boost::adjacency_list <\n        boost::vecS, // \u043a\u0430\u043a \u0445\u0440\u0430\u043d\u0438\u0442\u044c \u0432\u0435\u0440\u0448\u0438\u043d\u044b - \u0432 \u0432\u0435\u043a\u0442\u043e\u0440\u0435\n        boost::vecS, // \u043a\u0430\u043a \u0445\u0440\u0430\u043d\u0438\u0442\u044c \u0440\u0435\u0431\u0440\u0430 \u0438\u0437 \u043a\u0430\u0436\u0434\u043e\u0439 \u0432\u0435\u0440\u0448\u0438\u043d\u044b - \u0432 \u0432\u0435\u043a\u0442\u043e\u0440\u0435\n        boost::directedS,\n        no_property,\n        property < edge_weight_t, int >\n> AdjacencyListGraph;\n\n\n\ntemplate <class G>\nvoid depth_first_test(G &g) {\n    // \u0412\u044b\u043f\u043e\u043b\u043d\u044f\u044e \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c \u043f\u043e\u0438\u0441\u043a\u0430 \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443\n    depth_first_search(g, visitor(default_dfs_visitor()));\n}\n\n\nint main()\n{\n    cout << \"SpuUltraGraph performance test\" << endl;\n    cout << \"==========================================\" << endl;\n    GraphPerformanceTest<SpuUltraGraph> spu_graph_test(depth_first_test, \"depth_first_test_SpuUltraGraph.csv\");\n    spu_graph_test.is_mutable_test = false;\n    spu_graph_test.start();\n\n    cout << \"adjacency_list performance test\" << endl;\n    cout << \"==========================================\" << endl;\n    GraphPerformanceTest<AdjacencyListGraph> adjacency_list_test(depth_first_test, \"depth_first_test_adjacency_list.csv\");\n    adjacency_list_test.is_mutable_test = false;\n    adjacency_list_test.start();\n\n    cout << \"adjacency_matrix performance test\" << endl;\n    cout << \"==========================================\" << endl;\n    GraphPerformanceTest<AdjacencyMatrixGraph> adjacency_matrix_test(depth_first_test, \"depth_first_test_adjacency_matrix.csv\");\n    adjacency_matrix_test.is_mutable_test = false;\n    adjacency_matrix_test.end_vertices_cnt = 20000;\n    adjacency_matrix_test.start();\n    return 0;\n}", "meta": {"hexsha": "e5e4d846de1fb4e32d1175336d7e7435b126d0e1", "size": 1773, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "performance_tests/depth_first.cpp", "max_stars_repo_name": "kiryanenko/graph-api", "max_stars_repo_head_hexsha": "43436b98189db58587a7cf779293dac8f4b5e39a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-29T19:42:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-29T19:42:34.000Z", "max_issues_repo_path": "performance_tests/depth_first.cpp", "max_issues_repo_name": "kiryanenko/graph-api", "max_issues_repo_head_hexsha": "43436b98189db58587a7cf779293dac8f4b5e39a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "performance_tests/depth_first.cpp", "max_forks_repo_name": "kiryanenko/graph-api", "max_forks_repo_head_hexsha": "43436b98189db58587a7cf779293dac8f4b5e39a", "max_forks_repo_licenses": ["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.8333333333, "max_line_length": 128, "alphanum_fraction": 0.6779469825, "num_tokens": 428, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.833324587033253, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.48757917769908726}}
{"text": "#ifndef __EXPGRAPH_HPP\n#include <Eigen/Dense>\n#include<vector>\nusing namespace std;\nclass ExpGraph{\n\tpublic:\n\t\t//None of data, oldprms, oldprmlbls, updateData(), and updateOldParameters are mandatory \n\t\t//I implemented them for my own application\n\t\t//data holds the current timestep's vectors, oldprms/oldprmlbls keeps track of old parameters and their labels\n\t\t//updateData() does what it advertises\n\t\t//updateOldParameters makes sure that the KernDynMeans and VectorGraph objects have the same ordering of oldprmlbls,\n\t\t//and also updates oldprms (weighted by gammas) to reflect the clustering that was just completed\n\t\t//\n\t\t//basically, the pattern for clustering batch-sequential data is:\n\t\t//1) VectorGraph::updateData( [the data for this timestep] );\n\t\t//2) KernDynMeans::cluster( [the vector graph] );\n\t\t//3) VectorGraph::updateOldPrms( [output of KernDynMeans::cluster] );\n\t\t//Go back to 1 for the next time step\n\t\tstd::vector<V2d> data, oldprms;\n\t\tstd::vector<int> oldprmlbls;\n\t\tExpGraph(){\n\t\t\tdata.clear();\n\t\t\toldprms.clear();\n\t\t\toldprmlbls.clear();\n\t\t}\n\t\tvoid updateData(std::vector<V2d> data){\n\t\t\tthis->data = data;\n\t\t}\n\t\tvoid updateOldParameters(std::vector<V2d> data, std::vector<int> lbls, std::vector<double> gammas, std::vector<int> prmlbls){\n\t\t\tstd::vector<V2d> updatedoldprms;\n\t\t\tfor (int i = 0; i < prmlbls.size(); i++){\n\t\t\t\t//if there is no data assigned to this cluster, must be old/uninstantiated\n\t\t\t\tif (find(lbls.begin(), lbls.end(), prmlbls[i]) == lbls.end()){\n\t\t\t\t\tint oldidx = distance(oldprmlbls.begin(), find(oldprmlbls.begin(), oldprmlbls.end(), prmlbls[i]));\n\t\t\t\t\tupdatedoldprms.push_back(oldprms[oldidx]);\n\t\t\t\t//if the label is not in oldprmlbls, must be a new cluster\n\t\t\t\t//furthermore, must have at least one label in lbls = prmlbls[i]\n\t\t\t\t} else if (find(oldprmlbls.begin(), oldprmlbls.end(), prmlbls[i]) == oldprmlbls.end()) {\n\t\t\t\t\tV2d tmpprm = V2d::Zero();\n\t\t\t\t\tint tmpcnt = 0;\n\t\t\t\t\tfor (int j =0 ; j < lbls.size(); j++){\n\t\t\t\t\t\tif (lbls[j] == prmlbls[i]){\n\t\t\t\t\t\t\ttmpprm += data[j];\n\t\t\t\t\t\t\ttmpcnt++;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\ttmpprm /= tmpcnt;\n\t\t\t\t\tupdatedoldprms.push_back(tmpprm);\n\t\t\t\t//old instantiated cluster\n\t\t\t\t} else {\n\t\t\t\t\tint oldidx = distance(oldprmlbls.begin(), find(oldprmlbls.begin(), oldprmlbls.end(), prmlbls[i]));\n\t\t\t\t\tV2d tmpprm = gammas[i]*oldprms[oldidx];\n\t\t\t\t\tint tmpcnt = 0;\n\t\t\t\t\tfor (int j =0 ; j < lbls.size(); j++){\n\t\t\t\t\t\tif (lbls[j] == prmlbls[i]){\n\t\t\t\t\t\t\ttmpprm += data[j];\n\t\t\t\t\t\t\ttmpcnt++;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\ttmpprm /= (gammas[i]+tmpcnt);\n\t\t\t\t\tupdatedoldprms.push_back(tmpprm);\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis->oldprms = updatedoldprms;\n\t\t\tthis->oldprmlbls = prmlbls;\n\t\t}\n\n\t\t//---ALL FUNCTIONS BELOW ARE MANDATORY---\n\t\t//Any affinity class must implement all of the below functions, as KernDynMeans calls them explicitly\n\n\t\tdouble diagSelfSimDD(const int i) const{\n\t\t\treturn data[i].transpose()*data[i];\n\t\t}\n\t\tdouble offDiagSelfSimDD(const int i) const{\n\t\t\treturn 0;\n\t\t}\n\t\tdouble selfSimPP(const int i) const{\n\t\t\treturn oldprms[i].transpose()*oldprms[i];\n\t\t}\n\t\tdouble simDD(const int i, const int j) const{\n\t\t\treturn data[i].transpose()*data[j];\n\t\t}\n\t\tdouble simDP(const int i, const int j) const{\n\t\t\treturn data[i].transpose()*oldprms[j];\n\t\t}\n\t\tint getNodeCt(const int i) const{\n\t\t\treturn 1;\n\t\t}\n\t\tint getNNodes() const {\n\t\t\treturn data.size();\n\t\t}\n\t\tint getNOldPrms() const {\n\t\t\treturn oldprms.size();\n\t\t}\n};\n\n#define __EXPGRAPH_HPP\n#endif /* __EXPGRAPH_HPP */\n", "meta": {"hexsha": "bb1805254cfb48282951e39261ac19d22ec1097a", "size": 3410, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "example/expgraph.hpp", "max_stars_repo_name": "trevorcampbell/dynamic-means", "max_stars_repo_head_hexsha": "48b0fd2c692a137a25204dbc05152522da0cee04", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 41.0, "max_stars_repo_stars_event_min_datetime": "2016-01-19T02:24:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T07:49:30.000Z", "max_issues_repo_path": "example/expgraph.hpp", "max_issues_repo_name": "nittaya1990/dynamic-means", "max_issues_repo_head_hexsha": "48b0fd2c692a137a25204dbc05152522da0cee04", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-06T18:20:42.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-06T18:20:42.000Z", "max_forks_repo_path": "example/expgraph.hpp", "max_forks_repo_name": "nittaya1990/dynamic-means", "max_forks_repo_head_hexsha": "48b0fd2c692a137a25204dbc05152522da0cee04", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2018-06-21T23:40:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-24T14:52:22.000Z", "avg_line_length": 34.4444444444, "max_line_length": 127, "alphanum_fraction": 0.6630498534, "num_tokens": 1072, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.833324587033253, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.48757917769908726}}
{"text": "//\n// Created by vlad on 02.12.16.\n//\n\n#include <route_solver/abc/abc.hpp>\n#include <route_solver/utils/common.hpp>\n\n#include <gtest/gtest.h>\n\n#ifdef CUDA_ENABLED\n#include <Eigen/LU>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include \"cuda_func_opt.hpp\"\n#endif\n\nnamespace rs {\nclass FuncSolution\n\t: public Solution<FuncSolution> {\npublic:\n\n\tFuncSolution(double x1, double x2)\n\t\t: x1(x1), x2(x2), value(x1 * x1 + x2 * x2)\n\t{}\n\n\tFuncSolution(const FuncSolution& other) = default;\n\n\tdouble fitnessImpl() const\n\t{\n\t\tif (value >= 0)\n\t\t{\n\t\t\treturn 1 / (1 + value);\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn 1 + fabs(value);\n\t\t}\n\t}\n\n\tdouble getX1() const\n\t{\n\t\treturn x1;\n\t}\n\tdouble getX2() const\n\t{\n\t\treturn x2;\n\t}\n\tdouble getValue() const\n\t{\n\t\treturn value;\n\t}\n\nprivate:\n\n\tdouble x1;\n\tdouble x2;\n\tdouble value;\n};\n\nclass FuncSolutionProducer\n\t: public SolutionProducer<FuncSolutionProducer, FuncSolution> {\npublic:\n\n\tvoid newBetterSolutionFoundImpl(const FuncSolution&) const\n\t{\n\t}\n\tFuncSolution generateRandomImpl() const\n\t{\n\t\treturn FuncSolution(newValue(), newValue());\n\t}\n\n\tFuncSolution produceNeighborhoodImpl(const FuncSolution& solution) const\n\t{\n\t\treturn FuncSolution(solution.getX1() + utils::randomNumber(-1.0, 1.0),\n\t\t\t\t\t\t\tsolution.getX2() + utils::randomNumber(-1.0, 1.0));\n\t}\n\nprivate:\n\tstatic double newValue()\n\t{\n\t\treturn utils::randomNumber(-5.0, 5.0);\n\t}\n};\n\n}\n\nTEST(ABCTests, simple_func_optimization)\n{\n\tstd::srand(unsigned(std::time(0)));\n\tauto s = rs::beeColonySolve<rs::FuncSolutionProducer, rs::FuncSolution>([]()\n\t{\n\t\treturn rs::FuncSolutionProducer();\n\t}\n\t, rs::BeeColonyParams(6, 1000, 20, 5));\n\tstd::cout << \" x1 \" << s.getX1() << \" x2 \" << s.getX2() << \" value \" << s.getValue() << std::endl;\n}\n\n#ifdef CUDA_ENABLED\n\nstatic int a = ei_test_init_cuda();\n\ndouble dot_cpu(const std::vector<Eigen::Vector3d>& v1, const std::vector<Eigen::Vector3d>& v2)\n{\n\tdouble x = 0;\n\n\tfor (int i = 0; i < v1.size(); ++i)\n\t{\n\t\tx += v1[i].dot(v2[i]);\n\t}\n\n\treturn x;\n}\n\n\nstatic const int N = 10000000;\n\nTEST(MatrixOps, case_cuda)\n{\n\tstd::vector<Eigen::Vector3d> v1(N, Eigen::Vector3d{ 1.0, 1.0, 1.0 });\n\tstd::vector<Eigen::Vector3d> v2(N, Eigen::Vector3d{ -1.0, 1.0, 1.0 });\n\tdouble x = dot_cuda(v1, v2);\n}\n\nTEST(MatrixOps, case_cpu)\n{\n\tstd::vector<Eigen::Vector3d> v1(N, Eigen::Vector3d{ 1.0, 1.0, 1.0 });\n\tstd::vector<Eigen::Vector3d> v2(N, Eigen::Vector3d{ -1.0, 1.0, 1.0 });\n\tdouble x = dot_cpu(v1, v2);\n}\n\n#endif\n", "meta": {"hexsha": "5e3a6af4b303d5d0fb40543a733305ccfdd33cec", "size": 2406, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/route_solver/unit_tests/abc_test.cpp", "max_stars_repo_name": "antlad/route_solver_service", "max_stars_repo_head_hexsha": "a6a24766066e2da734079fb25e216afad72ad14b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-03-28T09:34:22.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-30T16:30:49.000Z", "max_issues_repo_path": "libs/route_solver/unit_tests/abc_test.cpp", "max_issues_repo_name": "antlad/route_solver_service", "max_issues_repo_head_hexsha": "a6a24766066e2da734079fb25e216afad72ad14b", "max_issues_repo_licenses": ["MIT"], "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/route_solver/unit_tests/abc_test.cpp", "max_forks_repo_name": "antlad/route_solver_service", "max_forks_repo_head_hexsha": "a6a24766066e2da734079fb25e216afad72ad14b", "max_forks_repo_licenses": ["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.2272727273, "max_line_length": 99, "alphanum_fraction": 0.6575228595, "num_tokens": 791, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.6187804478040617, "lm_q1q2_score": 0.48755641807870015}}
{"text": "/* Copyright 2022 Zuru Tech HK Limited.\n *\n * Licensed under the Apache License, Version 2.0(the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#include <chrono>\n#include <stdexcept>\n\n#include <Eigen/CholmodSupport>\n#include <Eigen/Dense>\n#include <Eigen/KLUSupport>\n#include <Eigen/Sparse>\n#include <Eigen/UmfPackSupport>\n\n#include <solvers/SparseSystem.hpp>\n#include <solvers/SuiteSparseSolver.hpp>\n\nnamespace solvers {\n\nEigen::VectorXd SuiteSparseSolver::_cholmod_solve(const SparseSystem& system,\n                                                  double& duration) const\n{\n    auto [A, b] = system.toEigenUpperCSR();\n    Eigen::VectorXd result;\n    std::chrono::time_point start = std::chrono::high_resolution_clock::now();\n    switch (_method) {\n        case SuiteSparseMethod::SimplicialLLT: {\n            Eigen::CholmodSimplicialLLT<\n                Eigen::SparseMatrix<double, Eigen::RowMajor>, Eigen::Upper>\n                simplicial_llt;\n            simplicial_llt.compute(A);\n            result = simplicial_llt.solve(b);\n            break;\n        }\n        case SuiteSparseMethod::SimplicialLDLT: {\n            Eigen::CholmodSimplicialLDLT<\n                Eigen::SparseMatrix<double, Eigen::RowMajor>, Eigen::Upper>\n                simplicial_ldlt;\n            simplicial_ldlt.compute(A);\n            result = simplicial_ldlt.solve(b);\n            break;\n        }\n        case SuiteSparseMethod::SupernodalLLT: {\n            Eigen::CholmodSupernodalLLT<\n                Eigen::SparseMatrix<double, Eigen::RowMajor>, Eigen::Upper>\n                supernodal_llt;\n            supernodal_llt.compute(A);\n            result = supernodal_llt.solve(b);\n            break;\n        }\n        default:\n            throw std::logic_error(\"Invalid solving method\");\n            break;\n    }\n    std::chrono::time_point end = std::chrono::high_resolution_clock::now();\n    std::chrono::duration<double> time_difference = end - start;\n    duration = time_difference.count();\n    return result;\n}\n\nEigen::VectorXd SuiteSparseSolver::_cholmod_gpu_solve(\n    const SparseSystem& system,\n    double& duration) const\n{\n    auto [A, b] = system.toEigenCSR();\n    Eigen::SparseMatrix<double, Eigen::RowMajor, SuiteSparse_long> A_long(A);\n    cholmod_sparse cholmod_A = viewAsCholmod(A_long);\n    cholmod_A.stype = 1;\n    cholmod_dense cholmod_b = viewAsCholmod(b);\n    cholmod_dense* cholmod_x;\n    auto* c = new cholmod_common();\n    cholmod_factor* L;\n    cholmod_l_start(c);\n    c->useGPU = 1;\n    switch (_method) {\n        case SuiteSparseMethod::SimplicialLLT: {\n            c->final_asis = 0;\n            c->supernodal = CHOLMOD_SIMPLICIAL;\n            c->final_ll = 1;\n            break;\n        }\n        case SuiteSparseMethod::SimplicialLDLT: {\n            c->final_asis = 1;\n            c->supernodal = CHOLMOD_SIMPLICIAL;\n            break;\n        }\n        case SuiteSparseMethod::SupernodalLLT: {\n            c->final_asis = 1;\n            c->supernodal = CHOLMOD_SUPERNODAL;\n            break;\n        }\n        default:\n            throw std::logic_error(\"Invalid solving method\");\n            break;\n    }\n    std::chrono::time_point start = std::chrono::high_resolution_clock::now();\n    L = cholmod_l_analyze(&cholmod_A, c);\n    cholmod_l_factorize(&cholmod_A, L, c);\n    cholmod_x = cholmod_l_solve(CHOLMOD_A, L, &cholmod_b, c);\n    std::chrono::time_point end = std::chrono::high_resolution_clock::now();\n    Eigen::VectorXd result = Eigen::Map<Eigen::VectorXd>(\n        static_cast<double*>(cholmod_x->x), static_cast<int64_t>(system.dim()));\n    cholmod_l_free_factor(&L, c);\n    cholmod_l_free_dense(&cholmod_x, c);\n    cholmod_l_finish(c);\n    std::chrono::duration<double> time_difference = end - start;\n    duration = time_difference.count();\n    return result;\n}\n\nEigen::VectorXd SuiteSparseSolver::_lu_solve(const SparseSystem& system,\n                                             double& duration) const\n{\n    auto [A, b] = system.toEigenCSC();\n    Eigen::VectorXd result;\n\n    std::chrono::time_point start = std::chrono::high_resolution_clock::now();\n    if (_method == SuiteSparseMethod::LU) {\n        Eigen::UmfPackLU<Eigen::SparseMatrix<double, Eigen::ColMajor>>\n            umfpacklu;\n        umfpacklu.compute(A);\n        result = umfpacklu.solve(b);\n    }\n    else {\n        Eigen::KLU<Eigen::SparseMatrix<double, Eigen::ColMajor>> klu;\n        klu.compute(A);\n        result = klu.solve(b);\n    }\n    std::chrono::time_point end = std::chrono::high_resolution_clock::now();\n    std::chrono::duration<double> time_difference = end - start;\n    duration = time_difference.count();\n    return result;\n}\n\nEigen::VectorXd SuiteSparseSolver::solve(const SparseSystem& system,\n                                         double& duration) const\n{\n    Eigen::VectorXd result;\n\n    switch (_method) {\n        case SuiteSparseMethod::SimplicialLLT:\n        case SuiteSparseMethod::SimplicialLDLT:\n        case SuiteSparseMethod::SupernodalLLT:\n            if (_gpu) {\n                result = _cholmod_gpu_solve(system, duration);\n            }\n            else {\n                result = _cholmod_solve(system, duration);\n            }\n            break;\n        case SuiteSparseMethod::LU:\n        case SuiteSparseMethod::KLU:\n            result = _lu_solve(system, duration);\n            break;\n        default:\n            throw std::logic_error(\"Invalid solving method\");\n            break;\n    }\n    return result;\n}\n\n}    // namespace solvers", "meta": {"hexsha": "fca357ef689b38537e99853569a2796b9e73e12f", "size": 5928, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "solvers/src/solvers/SuiteSparseSolver.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/SuiteSparseSolver.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/SuiteSparseSolver.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": 34.4651162791, "max_line_length": 80, "alphanum_fraction": 0.6216261808, "num_tokens": 1426, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4875564070002207}}
{"text": "#ifndef STAN_MATH_PRIM_SCAL_PROB_EXP_MOD_NORMAL_RNG_HPP\n#define STAN_MATH_PRIM_SCAL_PROB_EXP_MOD_NORMAL_RNG_HPP\n\n#include <stan/math/prim/scal/err/check_consistent_sizes.hpp>\n#include <stan/math/prim/scal/err/check_finite.hpp>\n#include <stan/math/prim/scal/err/check_not_nan.hpp>\n#include <stan/math/prim/scal/err/check_positive_finite.hpp>\n#include <stan/math/prim/scal/fun/constants.hpp>\n#include <stan/math/prim/scal/meta/length.hpp>\n#include <stan/math/prim/scal/meta/VectorBuilder.hpp>\n#include <stan/math/prim/scal/prob/normal_rng.hpp>\n#include <stan/math/prim/scal/prob/exponential_rng.hpp>\n#include <stan/math/prim/scal/meta/include_summand.hpp>\n#include <stan/math/prim/scal/fun/value_of.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n\nnamespace stan {\n  namespace math {\n\n    template <class RNG>\n    inline double\n    exp_mod_normal_rng(double mu,\n                       double sigma,\n                       double lambda,\n                       RNG& rng) {\n      static const char* function(\"exp_mod_normal_rng\");\n\n      check_finite(function, \"Location parameter\", mu);\n      check_positive_finite(function, \"Inv_scale parameter\", lambda);\n      check_positive_finite(function, \"Scale parameter\", sigma);\n\n      return normal_rng(mu, sigma, rng)\n        + exponential_rng(lambda, rng);\n    }\n\n  }\n}\n#endif\n\n", "meta": {"hexsha": "6aeabbfc7e5d24c0f42279af894716449c7130b3", "size": 1372, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/scal/prob/exp_mod_normal_rng.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/prim/scal/prob/exp_mod_normal_rng.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/prim/scal/prob/exp_mod_normal_rng.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": 33.4634146341, "max_line_length": 69, "alphanum_fraction": 0.7266763848, "num_tokens": 327, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.787931185683219, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4875564008373683}}
{"text": "/**********************************************************************\nalign.cpp - Align two molecules or vectors of vector3\n\nCopyright (C) 2010 by Noel M. O'Boyle\n\nThis file is part of the Open Babel project.\nFor more information, see <http://openbabel.org/>\n\nThis program is free software; you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation version 2 of the License.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n***********************************************************************/\n\n#include <openbabel/babelconfig.h>\n\n#include <vector>\n#include <climits> // UINT_MAX\n\n#include <openbabel/math/align.h>\n#include <openbabel/graphsym.h>\n#include <openbabel/math/vector3.h>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <Eigen/SVD>\n#include <Eigen/LU>\n\nusing namespace std;\n\nnamespace OpenBabel\n{\n  OBAlign::OBAlign(bool includeH, bool symmetry) : _method(OBAlign::Kabsch)\n  {\n    _ready = false;\n    _symmetry = symmetry;\n    _includeH = includeH;\n    _prefmol = 0;\n  }\n\n  OBAlign::OBAlign(const vector<vector3> &ref, const vector<vector3> &target) : _method(OBAlign::Kabsch)\n  {\n    SetRef(ref);\n    SetTarget(target);\n    _symmetry = false;\n    _prefmol = 0;\n  }\n\n  OBAlign::OBAlign(const OBMol &refmol, const OBMol &targetmol, bool includeH, bool symmetry) : _method(OBAlign::Kabsch)\n  {\n    _symmetry = symmetry;\n    _includeH = includeH;\n    SetRefMol(refmol);\n    SetTargetMol(targetmol);\n  }\n\n  void OBAlign::VectorsToMatrix(const vector<vector3> *pcoords, Eigen::MatrixXd &coords) {\n\n    vector<vector3>::size_type N = pcoords->size();\n    coords.resize(3, N);\n\n    // Create a 3xN matrix of the coords\n    vector<vector3>::const_iterator it;\n    vector<vector3>::size_type colm;\n    for (colm=0,it=pcoords->begin();colm<N;++colm,++it)\n      coords.col(colm) = Eigen::Vector3d( it->AsArray() );\n  }\n\n  Eigen::Vector3d OBAlign::MoveToOrigin(Eigen::MatrixXd &coords) {\n\n    vector<vector3>::size_type N = coords.cols();\n\n    // Find the centroid\n    Eigen::Vector3d centroid;\n    centroid = coords.rowwise().sum() / N;\n\n    // Subtract the centroids\n    for (vector<vector3>::size_type i=0; i<N; ++i)\n      coords.col(i) -= centroid;\n    return centroid;\n  }\n\n  void OBAlign::SetRef(const vector<vector3> &ref) {\n    _pref = &ref;\n    VectorsToMatrix(_pref, _mref);\n    _ref_centr = MoveToOrigin(_mref);\n\n    _ready = false;\n  }\n\n  void OBAlign::SetTarget(const vector<vector3> &target) {\n    _ptarget = &target;\n    VectorsToMatrix(_ptarget, _mtarget);\n    _target_centr = MoveToOrigin(_mtarget);\n\n    _ready = false;\n  }\n\n  void OBAlign::SetRefMol(const OBMol &refmol) {\n    _prefmol = &refmol;\n\n    // Set up the BitVec for the hydrogens and store the refmol coords\n    _frag_atoms.Clear();\n    _frag_atoms.Resize(refmol.NumAtoms() + 1);\n    _refmol_coords.resize(0);\n    OBAtom* atom;\n    int delta = 1;\n    _newidx.resize(0);\n\n    for (unsigned int i=1; i<=refmol.NumAtoms(); ++i) {\n      atom = refmol.GetAtom(i);\n      if (_includeH || !atom->IsHydrogen()) {\n        _frag_atoms.SetBitOn(i);\n        _newidx.push_back(i - delta);\n        _refmol_coords.push_back(atom->GetVector());\n      }\n      else {\n        delta++;\n        _newidx.push_back(UINT_MAX);\n      }\n    }\n    SetRef(_refmol_coords);\n\n    if (_symmetry) {\n      FindAutomorphisms((OBMol*)&refmol, _aut, _frag_atoms);\n    }\n  }\n\n  void OBAlign::SetTargetMol(const OBMol &targetmol) {\n    _ptargetmol = &targetmol;\n    _targetmol_coords.resize(0);\n    OBAtom const *atom;\n    for (unsigned int i=1; i<=targetmol.NumAtoms(); ++i) {\n      atom = targetmol.GetAtom(i);\n      if (_includeH || !atom->IsHydrogen())\n        _targetmol_coords.push_back(atom->GetVector());\n    }\n    SetTarget(_targetmol_coords);\n  }\n\n  void OBAlign::SetMethod(OBAlign::AlignMethod method) {\n    _method = method;\n  }\n\n/* Evaluates the Newton-Raphson correction for the Horn quartic.\n   only 11 FLOPs */\n  static double eval_horn_NR_corrxn(const vector<double> &c, const double x)\n  {\n    double x2 = x*x;\n    double b = (x2 + c[2])*x;\n    double a = b + c[1];\n\n    return((a*x + c[0])/(2.0*x2*x + b + a));\n  }\n\n  /* Newton-Raphson root finding */\n  static double QCProot(const vector<double> &coeff, double guess, const double delta)\n  {\n    int             i;\n    double          oldg;\n    double initialg = guess;\n\n    for (i = 0; i < 50; ++i)\n    {\n        oldg = guess;\n        /* guess -= (eval_horn_quart(coeff, guess) / eval_horn_quart_deriv(coeff, guess)); */\n        guess -= eval_horn_NR_corrxn(coeff, guess);\n\n        if (fabs(guess - oldg) < fabs(delta*guess))\n            return(guess);\n    }\n\n    return initialg + 1.0; // Failed to converge!\n  }\n\n  vector<double> CalcQuarticCoeffs(const Eigen::Matrix3d &M)\n  {\n    vector<double> coeff(4);\n\n    double          Sxx, Sxy, Sxz, Syx, Syy, Syz, Szx, Szy, Szz;\n    double          Szz2, Syy2, Sxx2, Sxy2, Syz2, Sxz2, Syx2, Szy2, Szx2,\n                    SyzSzymSyySzz2, Sxx2Syy2Szz2Syz2Szy2, Sxy2Sxz2Syx2Szx2,\n                    SxzpSzx, SyzpSzy, SxypSyx, SyzmSzy,\n                    SxzmSzx, SxymSyx, SxxpSyy, SxxmSyy;\n\n#ifdef HAVE_EIGEN3\n    Eigen::MatrixXd M_sqr = M.array().square();\n#else\n    Eigen::MatrixXd M_sqr = M.cwise().square();\n#endif\n\n    Sxx = M(0, 0);\n    Sxy = M(1, 0);\n    Sxz = M(2, 0);\n    Syx = M(0, 1);\n    Syy = M(1, 1);\n    Syz = M(2, 1);\n    Szx = M(0, 2);\n    Szy = M(1, 2);\n    Szz = M(2, 2);\n\n    Sxx2 = Sxx * Sxx;\n    Syy2 = Syy * Syy;\n    Szz2 = Szz * Szz;\n\n    Sxy2 = Sxy * Sxy;\n    Syz2 = Syz * Syz;\n    Sxz2 = Sxz * Sxz;\n\n    Syx2 = Syx * Syx;\n    Szy2 = Szy * Szy;\n    Szx2 = Szx * Szx;\n\n    SyzSzymSyySzz2 = 2.0*(Syz*Szy - Syy*Szz);\n    Sxx2Syy2Szz2Syz2Szy2 = Syy2 + Szz2 - Sxx2 + Syz2 + Szy2;\n\n    /* coeff[4] = 1.0; */\n    /* coeff[3] = 0.0; */\n    // coeff[2] = -2.0 * (Sxx2 + Syy2 + Szz2 + Sxy2 + Syx2 + Sxz2 + Szx2 + Syz2 + Szy2);\n    coeff[2] = -2.0 * M_sqr.sum();\n    coeff[1] = 8.0 * (Sxx*Syz*Szy + Syy*Szx*Sxz + Szz*Sxy*Syx - Sxx*Syy*Szz - Syz*Szx*Sxy - Szy*Syx*Sxz);\n\n    SxzpSzx = Sxz+Szx;\n    SyzpSzy = Syz+Szy;\n    SxypSyx = Sxy+Syx;\n    SyzmSzy = Syz-Szy;\n    SxzmSzx = Sxz-Szx;\n    SxymSyx = Sxy-Syx;\n    SxxpSyy = Sxx+Syy;\n    SxxmSyy = Sxx-Syy;\n    Sxy2Sxz2Syx2Szx2 = Sxy2 + Sxz2 - Syx2 - Szx2;\n\n    coeff[0] = Sxy2Sxz2Syx2Szx2 * Sxy2Sxz2Syx2Szx2\n             + (Sxx2Syy2Szz2Syz2Szy2 + SyzSzymSyySzz2) * (Sxx2Syy2Szz2Syz2Szy2 - SyzSzymSyySzz2)\n             + (-(SxzpSzx)*(SyzmSzy)+(SxymSyx)*(SxxmSyy-Szz)) * (-(SxzmSzx)*(SyzpSzy)+(SxymSyx)*(SxxmSyy+Szz))\n             + (-(SxzpSzx)*(SyzpSzy)-(SxypSyx)*(SxxpSyy-Szz)) * (-(SxzmSzx)*(SyzmSzy)-(SxypSyx)*(SxxpSyy+Szz))\n             + (+(SxypSyx)*(SyzpSzy)+(SxzpSzx)*(SxxmSyy+Szz)) * (-(SxymSyx)*(SyzmSzy)+(SxzpSzx)*(SxxpSyy+Szz))\n             + (+(SxypSyx)*(SyzmSzy)+(SxzmSzx)*(SxxmSyy-Szz)) * (-(SxymSyx)*(SyzpSzy)+(SxzmSzx)*(SxxpSyy-Szz));\n\n    return coeff;\n  }\n\n  void OBAlign::TheobaldAlign(const Eigen::MatrixXd &mtarget)\n  {\n    // M = B(t) times A (where A, B are N x 3 matrices)\n    Eigen::Matrix3d M = mtarget * _mref.transpose();\n\n    // Maximum value for lambda is (Ga + Gb) / 2\n    double innerprod = mtarget.squaredNorm() + _mref.squaredNorm();\n\n    vector<double> coeffs = CalcQuarticCoeffs(M);\n    double lambdamax = QCProot(coeffs, 0.5 * innerprod, 1e-6);\n    if (lambdamax > (0.5 * innerprod))\n      _fail = true;\n    else {\n      double sqrdev = innerprod - (2.0 * lambdamax);\n      _rmsd = sqrt(sqrdev / mtarget.cols());\n    }\n  }\n\n  void OBAlign::SimpleAlign(const Eigen::MatrixXd &mtarget)\n  {\n    // Covariance matrix C = X times Y(t)\n    Eigen::Matrix3d C = _mref * mtarget.transpose();\n\n    // Singular Value Decomposition of C into USV(t)\n#ifdef HAVE_EIGEN3\n    Eigen::JacobiSVD<Eigen::Matrix3d> svd(C, Eigen::ComputeFullU | Eigen::ComputeFullV);\n#else\n    Eigen::SVD<Eigen::Matrix3d> svd(C);\n#endif\n\n    // Prepare matrix T\n    double sign = (C.determinant() > 0) ? 1. : -1.; // Sign of determinant\n    Eigen::Matrix3d T = Eigen::Matrix3d::Identity();\n    T(2,2) = sign;\n\n    // Optimal rotation matrix, U, is V T U(t)\n    _rotMatrix = svd.matrixV() * T * svd.matrixU().transpose();\n\n    // Rotate target using rotMatrix\n    _result = _rotMatrix.transpose() * mtarget;\n\n    Eigen::MatrixXd deviation = _result - _mref;\n#ifdef HAVE_EIGEN3\n    Eigen::MatrixXd sqr = deviation.array().square();\n#else\n    Eigen::MatrixXd sqr = deviation.cwise().square();\n#endif\n    double sum = sqr.sum();\n    _rmsd = sqrt( sum / sqr.cols() );\n\n  }\n\n  bool OBAlign::Align()\n  {\n    vector<vector3>::size_type N = _ptarget->size();\n\n    if (_pref->size() != N) {\n      obErrorLog.ThrowError(__FUNCTION__, \"Cannot align the reference and target as they are of different size\" , obError);\n      return false;\n    }\n\n    if (!_symmetry || _aut.size() == 1) {\n      if (_method == OBAlign::Kabsch)\n        SimpleAlign(_mtarget);\n      else\n        TheobaldAlign(_mtarget);\n    }\n    else {  // Iterate over the automorphisms\n\n      // ...for storing the results from the lowest rmsd to date\n      double min_rmsd = DBL_MAX;\n      Eigen::MatrixXd result, rotMatrix;\n\n      // Try all of the symmetry-allowed permutations\n      OBIsomorphismMapper::Mappings::const_iterator cit;\n      Eigen::MatrixXd mtarget(_mtarget.rows(), _mtarget.cols());\n\n      for (unsigned int k = 0; k < _aut.size(); ++k) {\n        // Rearrange columns of _mtarget for this permutation\n        unsigned int i=0;\n        for (unsigned int j=1; j<=_prefmol->NumAtoms(); ++j) {\n          if (_frag_atoms.BitIsSet(j)) {\n            for (std::size_t l = 0; l < _aut[k].size(); ++l)\n              if (_aut[k][l].first == j - 1) {\n                mtarget.col(i) = _mtarget.col(_newidx[_aut[k][l].second]);\n                break;\n              }\n            i++;\n          }\n        }\n        if (_method == OBAlign::Kabsch)\n          SimpleAlign(mtarget);\n        else\n          TheobaldAlign(mtarget);\n        if (_rmsd < min_rmsd) {\n          min_rmsd = _rmsd;\n          result = _result;\n          rotMatrix = _rotMatrix;\n        }\n      }\n\n      // Restore the best answer from memory\n      _rmsd = min_rmsd;\n      _result = result;\n      _rotMatrix = rotMatrix;\n    }\n\n    _ready = true;\n    return true;\n  }\n\n  matrix3x3 OBAlign::GetRotMatrix()\n  {\n    if (!_ready) {\n      obErrorLog.ThrowError(__FUNCTION__, \"Rotation matrix not available until you call Align()\" , obError);\n      return matrix3x3();\n    }\n\n    // Convert Eigen::Matrix to matrix3x3\n    double rot[3][3];\n    for (int row=0; row<3; ++row)\n       for (int col=0; col<3; ++col)\n         rot[col][row] = _rotMatrix(row, col); // Return in form suitable for use in expressions like \"result *= rotMatrix\";\n    matrix3x3 rotmat = matrix3x3(rot);\n\n    return rotmat;\n  }\n\n  vector<vector3> OBAlign::GetAlignment() {\n    vector<vector3> aligned_coords;\n    if (!_ready) {\n      obErrorLog.ThrowError(__FUNCTION__, \"Alignment not available until you call Align()\" , obError);\n      return aligned_coords;\n    }\n\n    if (!_prefmol || _includeH) {\n      // Add back the centroid of the reference and convert to vv3\n      Eigen::Vector3d tmp;\n      aligned_coords.reserve(_result.cols());\n      for (int i=0; i<_result.cols(); ++i) {\n        tmp = _result.col(i) + _ref_centr;\n        aligned_coords.push_back(vector3(tmp(0), tmp(1), tmp(2)));\n      }\n    }\n    else { // Need to deal with the case where hydrogens were excluded\n      vector<vector3> target_coords;\n      for (unsigned int i=1; i<=_ptargetmol->NumAtoms(); ++i)\n        target_coords.push_back(_ptargetmol->GetAtom(i)->GetVector());\n      Eigen::MatrixXd mtarget;\n      VectorsToMatrix(&target_coords, mtarget);\n\n      // Subtract the centroid of the non-H atoms\n      for (vector<vector3>::size_type i=0; i<mtarget.cols(); ++i)\n        mtarget.col(i) -= _target_centr;\n\n      // Rotate\n      Eigen::MatrixXd result = mtarget.transpose() * _rotMatrix;\n      result.transposeInPlace();\n\n      // Add back the centroid of the reference and convert to vv3\n      Eigen::Vector3d tmp;\n      aligned_coords.reserve(_result.cols());\n      for (int i=0; i<result.cols(); ++i) {\n        tmp = result.col(i) + _ref_centr;\n        aligned_coords.push_back(vector3(tmp(0), tmp(1), tmp(2)));\n      }\n    }\n\n    return aligned_coords;\n  }\n\n  bool OBAlign::UpdateCoords(OBMol* target) {\n    if (!_ready) {\n      obErrorLog.ThrowError(__FUNCTION__, \"Alignment not available until you call Align()\" , obError);\n      return false;\n    }\n\n    vector<vector3> newcoords = GetAlignment();\n    if (newcoords.size() != target->NumAtoms()) {\n      obErrorLog.ThrowError(__FUNCTION__, \"Cannot update the target molecule with the alignment coordinates as they are of different size\" , obError);\n      return false;\n    }\n\n    int i = 0;\n    FOR_ATOMS_OF_MOL(a, *target) {\n      a->SetVector(newcoords.at(i));\n      i++;\n    }\n\n    return true;\n  }\n\n  double OBAlign::GetRMSD() {\n    if (!_ready) {\n      obErrorLog.ThrowError(__FUNCTION__, \"RMSD not available until you call Align()\" , obError);\n      return (double) NULL;\n    }\n\n    return _rmsd;\n  }\n\n} // namespace OpenBabel\n\n//! \\file align.cpp\n//! \\brief Handle 3D coordinates.\n", "meta": {"hexsha": "2f8cd6b242fb8d4aeb6f218da5d645e9a853ea46", "size": 13317, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "openbabel-2.4.1/src/math/align.cpp", "max_stars_repo_name": "sxhexe/reaction-route-search", "max_stars_repo_head_hexsha": "f7694c84ca1def4a133ade3e1e2e09705cd28312", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-09-16T07:36:29.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-16T07:36:29.000Z", "max_issues_repo_path": "openbabel-2.4.1/src/math/align.cpp", "max_issues_repo_name": "sxhexe/reaction-route-search", "max_issues_repo_head_hexsha": "f7694c84ca1def4a133ade3e1e2e09705cd28312", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "openbabel-2.4.1/src/math/align.cpp", "max_forks_repo_name": "sxhexe/reaction-route-search", "max_forks_repo_head_hexsha": "f7694c84ca1def4a133ade3e1e2e09705cd28312", "max_forks_repo_licenses": ["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.4623893805, "max_line_length": 150, "alphanum_fraction": 0.6091462041, "num_tokens": 4180, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357460591568, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.48742712186244413}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\r\n\r\n/*\r\n Copyright (C) 2008 Klaus Spanderen\r\n Copyright (C) 2014 Johannes G\u00f6ttker-Schnetmann\r\n\r\n This file is part of QuantLib, a free-software/open-source library\r\n for financial quantitative analysts and developers - http://quantlib.org/\r\n\r\n QuantLib is free software: you can redistribute it and/or modify it\r\n under the terms of the QuantLib license.  You should have received a\r\n copy of the license along with this program; if not, please email\r\n <quantlib-dev@lists.sf.net>. The license is also available online at\r\n <http://quantlib.org/license.shtml>.\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 license for more details.\r\n*/\r\n\r\n#ifndef quantlib_test_fd_heston_hpp\r\n#define quantlib_test_fd_heston_hpp\r\n\r\n#include <boost/test/unit_test.hpp>\r\n#include \"speedlevel.hpp\"\r\n\r\n/* remember to document new and/or updated tests in the Doxygen\r\n   comment block of the corresponding class */\r\n\r\nclass FdHestonTest {\r\npublic:\r\n    static void testFdmHestonVarianceMesher();\r\n    static void testFdmHestonBarrier();\r\n    static void testFdmHestonBarrierVsBlackScholes();\r\n    static void testFdmHestonAmerican();\r\n    static void testFdmHestonIkonenToivanen();\r\n    static void testFdmHestonEuropeanWithDividends();\r\n    static void testFdmHestonConvergence();\r\n    static void testFdmHestonBlackScholes();\r\n    static void testFdmHestonIntradayPricing();\r\n    static void testMethodOfLines();\r\n    static void testSpuriousOscillations();\r\n\r\n    static boost::unit_test_framework::test_suite* suite(SpeedLevel);\r\n};\r\n\r\n#endif\r\n", "meta": {"hexsha": "9017df4201c2ad867d2f961742d65b9fdd79b966", "size": 1757, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test-suite/fdheston.hpp", "max_stars_repo_name": "akshett/QuantLib", "max_stars_repo_head_hexsha": "eb02391a1c79009c0f1ba6ef235a424bed60c576", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-12-12T01:27:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T17:44:12.000Z", "max_issues_repo_path": "test-suite/fdheston.hpp", "max_issues_repo_name": "akshett/QuantLib", "max_issues_repo_head_hexsha": "eb02391a1c79009c0f1ba6ef235a424bed60c576", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-06-11T15:35:14.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-11T15:35:14.000Z", "max_forks_repo_path": "test-suite/fdheston.hpp", "max_forks_repo_name": "akshett/QuantLib", "max_forks_repo_head_hexsha": "eb02391a1c79009c0f1ba6ef235a424bed60c576", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-07-11T08:32:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-11T08:32:27.000Z", "avg_line_length": 36.6041666667, "max_line_length": 80, "alphanum_fraction": 0.7490039841, "num_tokens": 428, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702880639791, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.48735327245863364}}
{"text": "//  Copyright (c) 2015 John Maddock\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_ELLINT_RG_HPP\r\n#define BOOST_MATH_ELLINT_RG_HPP\r\n\r\n#ifdef _MSC_VER\r\n#pragma once\r\n#endif\r\n\r\n#include <boost/math/special_functions/math_fwd.hpp>\r\n#include <boost/math/tools/config.hpp>\r\n#include <boost/math/constants/constants.hpp>\r\n#include <boost/math/policies/error_handling.hpp>\r\n#include <boost/math/special_functions/ellint_rd.hpp>\r\n#include <boost/math/special_functions/ellint_rf.hpp>\r\n#include <boost/math/special_functions/pow.hpp>\r\n\r\nnamespace boost { namespace math { namespace detail{\r\n\r\n   template <typename T, typename Policy>\r\n   T ellint_rg_imp(T x, T y, T z, const Policy& pol)\r\n   {\r\n      BOOST_MATH_STD_USING\r\n      static const char* function = \"boost::math::ellint_rf<%1%>(%1%,%1%,%1%)\";\r\n\r\n      if(x < 0 || y < 0 || z < 0)\r\n      {\r\n         return policies::raise_domain_error<T>(function,\r\n            \"domain error, all arguments must be non-negative, \"\r\n            \"only sensible result is %1%.\",\r\n            std::numeric_limits<T>::quiet_NaN(), pol);\r\n      }\r\n      //\r\n      // Function is symmetric in x, y and z, but we require\r\n      // (x - z)(y - z) >= 0 to avoid cancellation error in the result\r\n      // which implies (for example) x >= z >= y\r\n      //\r\n      using std::swap;\r\n      if(x < y)\r\n         swap(x, y);\r\n      if(x < z)\r\n         swap(x, z);\r\n      if(y > z)\r\n         swap(y, z);\r\n      \r\n      BOOST_ASSERT(x >= z);\r\n      BOOST_ASSERT(z >= y);\r\n      //\r\n      // Special cases from http://dlmf.nist.gov/19.20#ii\r\n      //\r\n      if(x == z)\r\n      {\r\n         if(y == z)\r\n         {\r\n            // x = y = z\r\n            // This also works for x = y = z = 0 presumably.\r\n            return sqrt(x);\r\n         }\r\n         else if(y == 0)\r\n         {\r\n            // x = y, z = 0\r\n            return constants::pi<T>() * sqrt(x) / 4;\r\n         }\r\n         else\r\n         {\r\n            // x = z, y != 0\r\n            swap(x, y);\r\n            return (x == 0) ? T(sqrt(z) / 2) : T((z * ellint_rc_imp(x, z, pol) + sqrt(x)) / 2);\r\n         }\r\n      }\r\n      else if(y == z)\r\n      {\r\n         if(x == 0)\r\n            return constants::pi<T>() * sqrt(y) / 4;\r\n         else\r\n            return (y == 0) ? T(sqrt(x) / 2) : T((y * ellint_rc_imp(x, y, pol) + sqrt(x)) / 2);\r\n      }\r\n      else if(y == 0)\r\n      {\r\n         swap(y, z);\r\n         //\r\n         // Special handling for common case, from\r\n         // Numerical Computation of Real or Complex Elliptic Integrals, eq.46\r\n         //\r\n         T xn = sqrt(x);\r\n         T yn = sqrt(y);\r\n         T x0 = xn;\r\n         T y0 = yn;\r\n         T sum = 0;\r\n         T sum_pow = 0.25f;\r\n\r\n         while(fabs(xn - yn) >= 2.7 * tools::root_epsilon<T>() * fabs(xn))\r\n         {\r\n            T t = sqrt(xn * yn);\r\n            xn = (xn + yn) / 2;\r\n            yn = t;\r\n            sum_pow *= 2;\r\n            sum += sum_pow * boost::math::pow<2>(xn - yn);\r\n         }\r\n         T RF = constants::pi<T>() / (xn + yn);\r\n         return ((boost::math::pow<2>((x0 + y0) / 2) - sum) * RF) / 2;\r\n      }\r\n      return (z * ellint_rf_imp(x, y, z, pol)\r\n         - (x - z) * (y - z) * ellint_rd_imp(x, y, z, pol) / 3\r\n         + sqrt(x * y / z)) / 2;\r\n   }\r\n\r\n} // namespace detail\r\n\r\ntemplate <class T1, class T2, class T3, class Policy>\r\ninline typename tools::promote_args<T1, T2, T3>::type \r\n   ellint_rg(T1 x, T2 y, T3 z, const Policy& pol)\r\n{\r\n   typedef typename tools::promote_args<T1, T2, T3>::type result_type;\r\n   typedef typename policies::evaluation<result_type, Policy>::type value_type;\r\n   return policies::checked_narrowing_cast<result_type, Policy>(\r\n      detail::ellint_rg_imp(\r\n         static_cast<value_type>(x),\r\n         static_cast<value_type>(y),\r\n         static_cast<value_type>(z), pol), \"boost::math::ellint_rf<%1%>(%1%,%1%,%1%)\");\r\n}\r\n\r\ntemplate <class T1, class T2, class T3>\r\ninline typename tools::promote_args<T1, T2, T3>::type \r\n   ellint_rg(T1 x, T2 y, T3 z)\r\n{\r\n   return ellint_rg(x, y, z, policies::policy<>());\r\n}\r\n\r\n}} // namespaces\r\n\r\n#endif // BOOST_MATH_ELLINT_RG_HPP\r\n\r\n", "meta": {"hexsha": "2944904c14a102fdd6476763c1f5fd9491ab9321", "size": 4261, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ios/Pods/boost-for-react-native/boost/math/special_functions/ellint_rg.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/special_functions/ellint_rg.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/special_functions/ellint_rg.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": 31.102189781, "max_line_length": 96, "alphanum_fraction": 0.5158413518, "num_tokens": 1220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702880639791, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.48735327245863364}}
{"text": "// Copyright (c) 2019 Graphcore Ltd. All rights reserved.\n#define BOOST_TEST_MODULE ConstExprAddTest\n\n#include <boost/test/unit_test.hpp>\n#include <filereader.hpp>\n#include <popart/builder.hpp>\n#include <popart/dataflow.hpp>\n#include <popart/devicemanager.hpp>\n#include <popart/half.hpp>\n#include <popart/inputshapeinfo.hpp>\n#include <popart/ir.hpp>\n#include <popart/names.hpp>\n#include <popart/ndarraywrapper.hpp>\n#include <popart/op/identity.hpp>\n#include <popart/op/l1.hpp>\n#include <popart/session.hpp>\n#include <popart/sgd.hpp>\n#include <popart/tensor.hpp>\n#include <popart/tensordata.hpp>\n#include <popart/tensors.hpp>\n#include <popart/testdevice.hpp>\n\n#include <math.h>\n\nusing namespace popart;\n\nBOOST_AUTO_TEST_CASE(ConstExprTest_Add0) {\n\n  // The compute graph :\n  //\n  // data  -----------------------------|\n  //                                    |\n  //                                    |\n  //                                    |- RESHAPE ---> output\n  //                                    |\n  // shape0 -------|                    |\n  //               |                    |\n  //               |- ADD - outshape ---|\n  //               |\n  // shape1 -------|\n\n  // We will reshape a tensor from rank-4:\n  Shape inShape = {2, 5, 3, 4};\n  // to rank-2: {10, 12},\n  // Note above that the total number elements of the tensor remains 120\n\n  // where the output shape {10, 12} will be the sum of two tensors,\n  // 1)\n  Shape shape0 = {7, 4};\n  // 2)\n  Shape shape1 = {3, 8};\n\n  Shape outShapeSize = {static_cast<int64_t>(shape0.size())};\n  TensorInfo inInfo{\"FLOAT\", inShape};\n\n  ConstVoidData out0ShapeData = {shape0.data(), {\"INT64\", outShapeSize}};\n  ConstVoidData out1ShapeData = {shape1.data(), {\"INT64\", outShapeSize}};\n\n  // Build an onnx model\n  auto builder = Builder::create();\n  auto aiOnnx  = builder->aiOnnxOpset9();\n  // The two fixed-point tensors which are Constants\n  auto shape0Id   = aiOnnx.constant(out0ShapeData, \"out0ShapeData\");\n  auto shape1Id   = aiOnnx.constant(out1ShapeData, \"out1ShapeData\");\n  auto inId       = builder->addInputTensor(inInfo);\n  auto outShapeId = aiOnnx.add({shape0Id, shape1Id});\n  auto outId      = aiOnnx.reshape({inId, outShapeId});\n  auto l1         = builder->aiGraphcoreOpset1().l1loss({outId}, 0.1);\n\n  auto proto      = builder->getModelProto();\n  auto modelProto = io::getModelFromString(proto);\n\n  // Create the IR, adding outId as an anchor\n  auto art       = AnchorReturnType(\"All\");\n  auto dataFlow  = DataFlow(1, {{outId, art}});\n  auto optimizer = ConstSGD(0.01);\n  auto device    = createTestDevice(TEST_TARGET);\n\n  Ir ir;\n  ir.prepare({modelProto,\n              InputShapeInfo(),\n              dataFlow,\n              l1,\n              &optimizer,\n              *device,\n              {}, // no SessionOptions\n              Patterns::create({\"PostNRepl\"}).enableRuntimeAsserts(false)});\n\n  // Check the ir\n  // 1) that the Reshape Op is present,\n  BOOST_CHECK(ir.opsOfType(Onnx::AiOnnx::OpSet9::Reshape).size() == 1);\n  // 2) that the shape of the output tensor is as specified.\n  Shape outShape;\n  for (int i = 0; i < outShapeSize[0]; ++i) {\n    outShape.push_back(shape0[i] + shape1[i]);\n  }\n  BOOST_CHECK(ir.getMainGraphTensors().get(outId)->info.shape() == outShape);\n}\n\nBOOST_AUTO_TEST_CASE(ConstExprTest_Add1) {\n  // Testing ConstExpr folding on broadcast adds of\n  // initializers and constants\n\n  // The compute graph :\n  //\n  // w0 --|\n  //      |--[bc-add]-- a0 --|\n  // w1 --|                  |\n  //                         |--[bc-add]-- a2 -|\n  // c0 --|                  |                 |\n  //      |--[bc-add]-- a1 --|                 |-- [matmul] -- o\n  // c1 --|                                    |\n  //                                           |\n  // i1 ---------------------------------------|\n  //\n\n  // weights\n  TensorInfo w0Shape{\"FLOAT\", std::vector<int64_t>{1, 3}};\n  float w0Vals[1 * 3]  = {0};\n  ConstVoidData w0Data = {w0Vals, w0Shape};\n\n  TensorInfo w1Shape{\"FLOAT\", std::vector<int64_t>{3, 3}};\n  float w1Vals[3 * 3]  = {1};\n  ConstVoidData w1Data = {w1Vals, w1Shape};\n\n  // consts\n  TensorInfo c0Shape{\"FLOAT\", std::vector<int64_t>{1, 3}};\n  float c0Vals[1 * 3]  = {2};\n  ConstVoidData c0Data = {c0Vals, c0Shape};\n\n  TensorInfo c1Shape{\"FLOAT\", std::vector<int64_t>{1}};\n  float c1Vals[1]      = {3};\n  ConstVoidData c1Data = {c1Vals, c1Shape};\n\n  // input\n  TensorInfo inputInfo{\"FLOAT\", std::vector<int64_t>{3, 4}};\n\n  // Build an onnx model\n  auto builder = Builder::create();\n  auto aiOnnx  = builder->aiOnnxOpset9();\n\n  auto w0Id = builder->addInitializedInputTensor(w0Data);\n  auto w1Id = builder->addInitializedInputTensor(w1Data);\n  auto a0   = aiOnnx.add({w0Id, w1Id}, \"a0\");\n\n  auto c0Id = aiOnnx.constant(c0Data, \"c0Data\");\n  auto c1Id = aiOnnx.constant(c1Data, \"c1Data\");\n  auto a1   = aiOnnx.add({c0Id, c1Id}, \"a1\");\n\n  auto a2      = aiOnnx.add({a0, a1}, \"a2\");\n  auto inputId = builder->addInputTensor(inputInfo);\n  auto outId   = aiOnnx.matmul({a2, inputId});\n  auto l1      = builder->aiGraphcoreOpset1().l1loss({outId}, 0.1);\n\n  auto proto      = builder->getModelProto();\n  auto modelProto = io::getModelFromString(proto);\n\n  // Create the IR, adding outId as an anchor\n  auto art       = AnchorReturnType(\"All\");\n  auto dataFlow  = DataFlow(1, {{outId, art}});\n  auto optimizer = ConstSGD(0.01);\n  auto device    = createTestDevice(TEST_TARGET);\n\n  Ir ir;\n  ir.prepare({modelProto,\n              InputShapeInfo(),\n              dataFlow,\n              {}, // no loss\n              {}, // no optimizer\n              *device,\n              {}, // no SessionOptions\n              Patterns::create({\"PostNRepl\"}).enableRuntimeAsserts(false)});\n\n  // Check that the Add Op is has been removed from the IR\n  // by ConstExpr folding\n  // TODO: this test will give a false pass if the model is using\n  // a newer opset. Fix when T6274 is complete\n  BOOST_CHECK(ir.opsOfType(Onnx::AiOnnx::OpSet9::Add).size() == 0);\n}\n\nBOOST_AUTO_TEST_CASE(ConstExprTest_Add2) {\n  // Testing ConstExpr folding on an input tensor whose consumer\n  // has another input that cannot be removed by ConstExpr folding\n\n  // Model from the builder:\n  //\n  // v0 ----|\n  //        |--[add]-- a0 --|\n  //        |               |\n  // c0 --|-|               |--[add]-- o\n  //      |                 |\n  //      |--[add]---- a1 --|\n  // c1 --|\n  //\n  // Expected outcome after ConstExpr folding :\n  //\n  // v0 ---|\n  //       |--[add]-- a0 --|\n  // c0 ---|               |--[add]-- o\n  //                       |\n  // a1 -------------------|\n  //\n\n  // consts\n  TensorInfo c0Shape{\"FLOAT\", std::vector<int64_t>{2, 2}};\n  float c0Vals[2 * 2]  = {2};\n  ConstVoidData c0Data = {c0Vals, c0Shape};\n\n  TensorInfo c1Shape{\"FLOAT\", std::vector<int64_t>{2, 2}};\n  float c1Vals[2 * 2]  = {3};\n  ConstVoidData c1Data = {c1Vals, c1Shape};\n\n  // input\n  TensorInfo inputInfo{\"FLOAT\", std::vector<int64_t>{2, 2}};\n\n  // Build an onnx model\n  auto builder = Builder::create();\n  auto aiOnnx  = builder->aiOnnxOpset9();\n\n  auto v0Id = builder->addInputTensor(inputInfo);\n  auto c0Id = aiOnnx.constant(c0Data, \"c0Data\");\n  auto c1Id = aiOnnx.constant(c1Data, \"c1Data\");\n\n  auto a0 = aiOnnx.add({v0Id, c0Id}, \"a0\");\n  auto a1 = aiOnnx.add({c0Id, c1Id}, \"a1\");\n\n  auto o = aiOnnx.add({a0, a1}, \"o\");\n  builder->addOutputTensor(o);\n\n  auto proto      = builder->getModelProto();\n  auto modelProto = io::getModelFromString(proto);\n\n  // Create the IR, adding outId as an anchor\n  auto art      = AnchorReturnType(\"All\");\n  auto dataFlow = DataFlow(1, {{o, art}});\n  auto device   = createTestDevice(TEST_TARGET);\n\n  Ir ir;\n  ir.prepare({modelProto,\n              InputShapeInfo(),\n              dataFlow,\n              {}, // no loss\n              {}, // no optimizer\n              *device,\n              {}, // no SessionOptions\n              Patterns::create({\"PostNRepl\"}).enableRuntimeAsserts(false)});\n\n  // Check that the producer of a1 Add Op is has been removed from the IR\n  // by ConstExpr folding\n  BOOST_CHECK(ir.opsOfType(Onnx::AiOnnx::OpSet9::Add).size() == 2);\n}\n\ntemplate <typename T> void ConstExprTest_Add_Type(std::string type) {\n\n  // The compute graph :\n  //\n  // data  -----------------------------|\n  //                                    |\n  //                                    |\n  //                                    |- ADD ---> output\n  //                                    |\n  // shape0 -------|                    |\n  //               |                    |\n  //               |- ADD - outshape ---|\n  //               |\n  // shape1 -------|\n\n  Shape inShape = {2, 2};\n\n  T input1_raw[] = {(T)1.2f, 2, 3, 4};\n  std::vector<T> input1(input1_raw, std::end(input1_raw));\n\n  T input2_raw[] = {(T)1.7f, 2, 3, 4};\n  std::vector<T> input2(input2_raw, std::end(input2_raw));\n\n  Shape outShapeSize = {2, 2};\n  TensorInfo inInfo{type, inShape};\n\n  ConstVoidData out0ShapeData = {input1.data(), {type, outShapeSize}};\n  ConstVoidData out1ShapeData = {input2.data(), {type, outShapeSize}};\n\n  T output_raw[4];\n  popart::NDArrayWrapper<T> output(output_raw, {2, 2});\n\n  // Build an onnx model\n  auto builder = Builder::create();\n  auto aiOnnx  = builder->aiOnnxOpset9();\n  // The two fixed-point tensors which are Constants\n  auto shape0Id   = aiOnnx.constant(out0ShapeData, \"out0ShapeData\");\n  auto shape1Id   = aiOnnx.constant(out1ShapeData, \"out1ShapeData\");\n  auto inId       = builder->addInputTensor(inInfo);\n  auto outShapeId = aiOnnx.add({shape0Id, shape1Id});\n  auto outId      = aiOnnx.add({inId, outShapeId});\n  builder->addOutputTensor(outId);\n\n  std::map<popart::TensorId, popart::IArray &> anchors = {{outId, output}};\n\n  auto proto = builder->getModelProto();\n\n  auto art      = AnchorReturnType(\"All\");\n  auto dataFlow = DataFlow(1, {{outId, art}});\n\n  auto device = popart::createTestDevice(TEST_TARGET);\n\n  auto session = popart::InferenceSession::createFromOnnxModel(\n      proto,\n      dataFlow,\n      device,\n      InputShapeInfo(),\n      {}, // no SessionOptions\n      Patterns::create({\"PostNRepl\"}).enableRuntimeAsserts(false));\n\n  T rawInputData[4] = {(T)1.1f, 2, 3, 4};\n  popart::NDArrayWrapper<T> inData(rawInputData, {2, 2});\n  std::map<popart::TensorId, popart::IArray &> inputs = {{inId, inData}};\n\n  session->prepareDevice();\n  popart::StepIO stepio(inputs, anchors);\n  session->run(stepio);\n\n  // Check the ir\n  popart::logging::ir::err(\"input1 : {}\", input1[0]);\n  popart::logging::ir::err(\"input2 : {}\", input2[0]);\n  popart::logging::ir::err(\"indata : {}\", inData[0]);\n  popart::logging::ir::err(\"output : {}\", output[0]);\n\n  BOOST_CHECK((input1[0] + input2[0] + inData[0]) == output[0]);\n}\n\nBOOST_AUTO_TEST_CASE(ConstExprTest_Div0) {\n\n  // The compute graph :\n  //\n  // data  -----------------------------|\n  //                                    |\n  //                                    |\n  //                                    |- RESHAPE ---> output\n  //                                    |\n  // shape0 -------|                    |\n  //               |                    |\n  //               |- ADD - outshape ---|\n  //               |\n  // shape1 -------|\n\n  // We will reshape a tensor from rank-4:\n  Shape inShape = {2, 2, 2};\n  // to rank-2: {2, 4},\n  // Note above that the total number elements of the tensor remains 120\n\n  // where the output shape {2, 4} will be the sum of two tensors,\n  // 1)\n  Shape shape0 = {4, 12};\n  // 2)\n  Shape shape1 = {2, 3};\n\n  Shape outShapeSize = {static_cast<int64_t>(shape0.size())};\n  TensorInfo inInfo{\"FLOAT\", inShape};\n\n  ConstVoidData out0ShapeData = {shape0.data(), {\"INT64\", outShapeSize}};\n  ConstVoidData out1ShapeData = {shape1.data(), {\"INT64\", outShapeSize}};\n\n  // Build an onnx model\n  auto builder = Builder::create();\n  auto aiOnnx  = builder->aiOnnxOpset9();\n  // The two fixed-point tensors which are Constants\n  auto shape0Id   = aiOnnx.constant(out0ShapeData, \"out0ShapeData\");\n  auto shape1Id   = aiOnnx.constant(out1ShapeData, \"out1ShapeData\");\n  auto inId       = builder->addInputTensor(inInfo);\n  auto outShapeId = aiOnnx.div({shape0Id, shape1Id});\n  auto outId      = aiOnnx.reshape({inId, outShapeId});\n  auto l1         = builder->aiGraphcoreOpset1().l1loss({outId}, 0.1);\n\n  auto proto      = builder->getModelProto();\n  auto modelProto = io::getModelFromString(proto);\n\n  // Create the IR, adding outId as an anchor\n  auto art       = AnchorReturnType(\"All\");\n  auto dataFlow  = DataFlow(1, {{outId, art}});\n  auto optimizer = ConstSGD(0.01);\n  auto device    = createTestDevice(TEST_TARGET);\n\n  Ir ir;\n  ir.prepare({modelProto,\n              InputShapeInfo(),\n              dataFlow,\n              l1,\n              &optimizer,\n              *device,\n              {}, // no SessionOptions\n              Patterns::create({\"PostNRepl\"}).enableRuntimeAsserts(false)});\n\n  // Check the ir\n  // 1) that the Reshape Op is present,\n  BOOST_CHECK(ir.opsOfType(Onnx::AiOnnx::OpSet9::Reshape).size() == 1);\n  // 2) that the shape of the output tensor is as specified.\n  Shape outShape;\n  for (int i = 0; i < outShapeSize[0]; ++i) {\n    outShape.push_back(shape0[i] / shape1[i]);\n  }\n  BOOST_CHECK(ir.getMainGraphTensors().get(outId)->info.shape() == outShape);\n}\n\nBOOST_AUTO_TEST_CASE(ConstExprTest_Add_Types) {\n  // ConstExprTest_Add_Type<uint32_t>(\"UINT32\");\n  // ConstExprTest_Add_Type<uint64_t>(\"UINT64\");\n  ConstExprTest_Add_Type<int32_t>(\"INT32\");\n  // ConstExprTest_Add_Type<int64_t>(\"INT64\");\n  ConstExprTest_Add_Type<popart::float16_t>(\"FLOAT16\");\n  ConstExprTest_Add_Type<float>(\"FLOAT\");\n  // ConstExprTest_Add_Type(\"DOUBLE\");\n}\n\ntemplate <typename T> std::string getTypeString();\n\ntemplate <> std::string getTypeString<int64_t>() { return \"INT64\"; }\ntemplate <> std::string getTypeString<float16_t>() { return \"FLOAT16\"; }\ntemplate <> std::string getTypeString<float_t>() { return \"FLOAT\"; }\n\ntemplate <typename T>\nvoid ConstExprTest_Elementwise_Test(\n    std::vector<T> in0,\n    std::vector<T> in1,\n    std::vector<T> output,\n    std::function<TensorId(std::unique_ptr<popart::Builder> &builder,\n                           const std::vector<TensorId> &args)> elementWiseFn) {\n\n  // The compute graph :\n  //\n  // data  -----------------------------|\n  //                                    |\n  //                                    |\n  //                                    |- ADD ---> output\n  //                                    |\n  // shape0 -------|                    |\n  //               |                    |\n  //               |- OP - outshape ----|\n  //               |\n  // shape1 -------|\n\n  std::vector<T> data = {42, 42};\n  Shape dataShape     = {static_cast<int64_t>(data.size())};\n  TensorInfo dataInfo{getTypeString<T>(), dataShape};\n\n  Shape in0Shape        = {static_cast<int64_t>(in0.size())};\n  ConstVoidData in0Data = {in0.data(), {getTypeString<T>(), in0Shape}};\n\n  Shape in1Shape        = {static_cast<int64_t>(in1.size())};\n  ConstVoidData in1Data = {in1.data(), {getTypeString<T>(), in1Shape}};\n\n  // Build an onnx model\n  auto builder = Builder::create();\n  auto aiOnnx  = builder->aiOnnxOpset10();\n  // The two fixed-point tensors which are Constants\n  auto in0Id      = aiOnnx.constant(in0Data, \"in0Data\");\n  auto in1Id      = aiOnnx.constant(in1Data, \"in1Data\");\n  auto dataId     = builder->addInputTensor(dataInfo);\n  auto outShapeId = elementWiseFn(builder, {in0Id, in1Id});\n\n  auto outId = aiOnnx.add({dataId, outShapeId});\n  auto l1    = builder->aiGraphcoreOpset1().l1loss({outId}, 0.1);\n\n  auto proto      = builder->getModelProto();\n  auto modelProto = io::getModelFromString(proto);\n\n  // Create the IR, adding outId as an anchor\n  auto art       = AnchorReturnType(\"All\");\n  auto dataFlow  = DataFlow(1, {{outId, art}});\n  auto optimizer = ConstSGD(0.01);\n  auto device    = createTestDevice(TEST_TARGET);\n\n  Ir ir;\n  ir.prepare({modelProto,\n              InputShapeInfo(),\n              dataFlow,\n              l1,\n              &optimizer,\n              *device,\n              {}, // no SessionOptions\n              Patterns::create({\"PostNRepl\"}).enableRuntimeAsserts(false)});\n\n  // Check the ir\n  // 1) that the Add Op is present,\n  BOOST_CHECK(ir.opsOfType(Onnx::AiOnnx::OpSet9::Add).size() == 1);\n  // 2) that the value of the output tensor is as specified.\n  T *p = static_cast<T *>(\n      ir.getMainGraphTensors().get(outShapeId)->tensorData()->data());\n  for (int i = 0; i < output.size(); ++i) {\n    BOOST_CHECK(p[i] == output[i]);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(ConstExprTest_Elementwise) {\n  ConstExprTest_Elementwise_Test<int64_t>(\n      {4, 12},\n      {2, 3},\n      {2, 4},\n      [](std::unique_ptr<popart::Builder> &builder,\n         const std::vector<TensorId> &args) -> TensorId {\n        return builder->aiOnnxOpset10().div(args);\n      });\n\n  ConstExprTest_Elementwise_Test<int64_t>(\n      {4, 12},\n      {2}, // Will be broadcast to {2, 2}\n      {2, 6},\n      [](std::unique_ptr<popart::Builder> &builder,\n         const std::vector<TensorId> &args) -> TensorId {\n        return builder->aiOnnxOpset10().div(args);\n      });\n\n  ConstExprTest_Elementwise_Test<float16_t>(\n      {8.0, 18.0},\n      {4.0, 3.0},\n      {2.0, 6.0},\n      [](std::unique_ptr<popart::Builder> &builder,\n         const std::vector<TensorId> &args) -> TensorId {\n        return builder->aiOnnxOpset10().div(args);\n      });\n\n  ConstExprTest_Elementwise_Test<float_t>(\n      {10.0, 21.0},\n      {4.0, 5.0},\n      {2.5, 4.2},\n      [](std::unique_ptr<popart::Builder> &builder,\n         const std::vector<TensorId> &args) -> TensorId {\n        return builder->aiOnnxOpset10().div(args);\n      });\n\n  ConstExprTest_Elementwise_Test<int64_t>(\n      {4, 12},\n      {2, 3},\n      {6, 15},\n      [](std::unique_ptr<popart::Builder> &builder,\n         const std::vector<TensorId> &args) -> TensorId {\n        return builder->aiOnnxOpset10().add(args);\n      });\n\n  ConstExprTest_Elementwise_Test<int64_t>(\n      {4, 12},\n      {2, 3},\n      {2, 9},\n      [](std::unique_ptr<popart::Builder> &builder,\n         const std::vector<TensorId> &args) -> TensorId {\n        return builder->aiOnnxOpset10().sub(args);\n      });\n\n  ConstExprTest_Elementwise_Test<float_t>(\n      {4.1, 101},\n      {0.1, 50.5},\n      {4.0, 50.5},\n      [](std::unique_ptr<popart::Builder> &builder,\n         const std::vector<TensorId> &args) -> TensorId {\n        return builder->aiOnnxOpset10().sub(args);\n      });\n\n  ConstExprTest_Elementwise_Test<int64_t>(\n      {4, 12},\n      {2, 3},\n      {8, 36},\n      [](std::unique_ptr<popart::Builder> &builder,\n         const std::vector<TensorId> &args) -> TensorId {\n        return builder->aiOnnxOpset10().mul(args);\n      });\n\n  ConstExprTest_Elementwise_Test<float16_t>(\n      {4., 12},\n      {0.5, 1.5},\n      {2.0, 18},\n      [](std::unique_ptr<popart::Builder> &builder,\n         const std::vector<TensorId> &args) -> TensorId {\n        return builder->aiOnnxOpset10().mul(args);\n      });\n\n  ConstExprTest_Elementwise_Test<int64_t>(\n      {4, -12},\n      {-3, 8},\n      {1, -4},\n      [](std::unique_ptr<popart::Builder> &builder,\n         const std::vector<TensorId> &args) -> TensorId {\n        return builder->aiGraphcoreOpset1().fmod(args);\n      });\n}\n", "meta": {"hexsha": "4f020ad51e3d33541d8c9947434f170f677fca2c", "size": 19123, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/integration/constexpr_tests/elementwise_ce_test.cpp", "max_stars_repo_name": "gglin001/popart", "max_stars_repo_head_hexsha": "3225214343f6d98550b6620e809a3544e8bcbfc6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 61.0, "max_stars_repo_stars_event_min_datetime": "2020-07-06T17:11:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T14:42:51.000Z", "max_issues_repo_path": "tests/integration/constexpr_tests/elementwise_ce_test.cpp", "max_issues_repo_name": "gglin001/popart", "max_issues_repo_head_hexsha": "3225214343f6d98550b6620e809a3544e8bcbfc6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-02-25T01:30:29.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-09T11:13:14.000Z", "max_forks_repo_path": "tests/integration/constexpr_tests/elementwise_ce_test.cpp", "max_forks_repo_name": "gglin001/popart", "max_forks_repo_head_hexsha": "3225214343f6d98550b6620e809a3544e8bcbfc6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-07-15T12:33:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-07T06:55:00.000Z", "avg_line_length": 32.8010291595, "max_line_length": 79, "alphanum_fraction": 0.5719290906, "num_tokens": 5522, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.4873532692256622}}
{"text": "#include <gtest/gtest.h>\n\n#include \"scheme/objective/hash/XformMap.hh\"\n#include \"scheme/numeric/rand_xform.hh\"\n#include <Eigen/Geometry>\n\n#include <sparsehash/dense_hash_set>\n\n#include <random>\n#include \"scheme/util/Timer.hh\"\n\n#include <fstream>\n\nnamespace scheme { namespace objective { namespace hash { namespace xmtest {\n\nusing std::cout;\nusing std::endl;\n\n\n\ntypedef Eigen::Transform<double,3,Eigen::AffineCompact> Xform;\n// typedef Eigen::Affine3d Xform;\n\n\nTEST( XformMap, stores_correctly ){\n\tint NSAMP = 100000;\n\n\tstd::mt19937 rng((unsigned int)time(0) + 296720384);\n\tstd::uniform_real_distribution<> runif;\n\n\tXformMap< Xform, double> xmap( 0.5, 10.0 );\n\tstd::vector< std::pair<Xform,double> > dat;\n\tfor(int i = 0; i < NSAMP; ++i){\n\t\tXform x;\n\t\tnumeric::rand_xform( rng, x, 256.0 );\n\t\tdouble val = runif(rng);\n\t\txmap.insert(x,val);\n\t\tdat.push_back( std::make_pair(x,val) );\n\t}\n\n\tXformMap< Xform, double > const & xmap_test( xmap );\n\n\tutil::Timer<> t;\n\n\tfor(int i = 0; i < dat.size(); ++i){\n\t\tXform const & x = dat[i].first;\n\t\tdouble const v = dat[i].second;\n\t\tEXPECT_EQ( xmap_test[x], v );\n\t\t// cout << x.translation().transpose() << \" \" << v << endl;\n\t}\n\tcout << \"XformMap \" << NSAMP << \" lookup rate: \" << (double)NSAMP / t.elapsed() << \" /sec \";\n\n\t// { // no way to check if stream in binary!\n\t// \tstd::cout << \"following failure message is expected\" << std::endl;\n\t// \tstd::ofstream out(\"test.sxm\" );// , std::ios::binary );\n\t// \tASSERT_FALSE( xmap.save( out, \"foo\" ) );\n\t// \tout.close();\n\t// }\n\tstd::ofstream out(\"test.sxm\" , std::ios::binary );\n\tASSERT_TRUE( xmap.save( out, \"foo\" ) );\n\tout.close();\n\n\tXformMap< Xform, double > xmap_loaded;\n\tstd::ifstream in( \"test.sxm\"  , std::ios::binary );\n\tASSERT_TRUE( xmap_loaded.load( in ) );\n\tin.close();\n\n\tASSERT_EQ( xmap.cart_resl_, xmap_loaded.cart_resl_ );\n\tASSERT_EQ( xmap.ang_resl_, xmap_loaded.ang_resl_ );\t\n\tfor(int i = 0; i < dat.size(); ++i){\n\t\tXform const & x = dat[i].first;\n\t\tdouble const v = dat[i].second;\n\t\tASSERT_EQ( xmap.hasher_.get_key(x) , xmap_loaded.hasher_.get_key(x) );\n\t\tASSERT_EQ( xmap_loaded[x], v );\n\t\t// cout << x.translation().transpose() << \" \" << v << endl;\n\t}\n\n\n}\n\ndouble get_ident_lever_dis( Xform x, double lever_dis ){\n\tutil::SimpleArray<7,double> x_lever_coord;\n\tx_lever_coord[0] = x.translation()[0];\n\tx_lever_coord[1] = x.translation()[1];\n\tx_lever_coord[2] = x.translation()[2];\n\tEigen::Matrix<double,3,3> rot;\n\tget_transform_rotation( x, rot );\n\tEigen::Quaternion<double> q(rot);\n\tbool neg = q.w()<0.0;\n\tx_lever_coord[3] = ( neg? -q.w() : q.w() ) * 2.0 * lever_dis;\n\tx_lever_coord[4] = ( neg? -q.x() : q.x() ) * 2.0 * lever_dis;\n\tx_lever_coord[5] = ( neg? -q.y() : q.y() ) * 2.0 * lever_dis;\n\tx_lever_coord[6] = ( neg? -q.z() : q.z() ) * 2.0 * lever_dis;\n\tutil::SimpleArray<7,double> ident(0,0,0,lever_dis*2.0,0,0,0);\n\treturn (x_lever_coord-ident).norm();\n}\n\nTEST( XformMap, insert_sphere ){\n\tint NSAMP2 = 10000;\n\n\t// typedef XformMap< Xform, double, 0 > XMap;\n\ttypedef XformMap< Xform, double> XMap;\t\n\tstd::mt19937 rng((unsigned int)time(0) + 3457820);\n\tstd::uniform_real_distribution<> runif;\n\tXform x;\n\tdouble cart_resl = 1.0;\n\tdouble lever = 3.0;\n\tdouble ang_resl = cart_resl/lever*180.0/M_PI;\n\tXMap xmap( 1.00, ang_resl );\n\tdouble rad = 3.0;\n\tcout << \"cart_resl \" << cart_resl << \" ang_resl \" << ang_resl << \" lever \" << lever << \" sphere rad \" << rad << endl;\n\tdouble angrad = rad/lever*180.0/M_PI;\n\tdouble quatrad = numeric::deg2quat(angrad);\n\tnumeric::rand_xform( rng, x, 256.0 );\n\tXformHashNeighbors< XMap::Hasher > nbcache( rad, angrad, xmap.hasher_, 500.0 );\n\tint nbitercount = xmap.insert_sphere( x, rad, lever, 12345.0, nbcache );\n\tcout << nbitercount << \" \" << xmap.count(12345.0) << \" \" << xmap.size()-(float)xmap.count(0) \n\t     << \" \" << (float)xmap.count(0) / xmap.size() << \" \" << xmap.map_.size() << endl;\n\tint n_cart_fail=0, n_rot_fail=0, n_both_fail=0;\n\tint n_lever_false_pos=0, n_lever_false_neg=0, n_within=0, n_without=0;\n\tfor(int i = 0; i < NSAMP2; ++i){\n\t\tXform p;\n\t\tnumeric::rand_xform_quat(rng, p, rad, 0.0 );\n\t\tif( xmap[ x*p ] != 12345.0 ) ++n_cart_fail;\n\n\t\tnumeric::rand_xform_quat(rng, p, 0.0, quatrad );\n\t\tif( xmap[ x*p ] != 12345.0 ) ++n_rot_fail;\t\t\n\n\t\tdouble split1 = runif(rng);\n\t\tdouble split2 = sqrt( 1.0 - split1*split1 );\n\t\tnumeric::rand_xform_quat(rng, p, split1*rad, split2*quatrad );\n\t\tif( xmap[ x*p ] != 12345.0 ) ++n_both_fail;\t\t\n\n\t\tnumeric::rand_xform_quat(rng, p, 1.5*split1*rad, 1.5*split2*quatrad );\n\t\t// numeric::rand_xform_quat(rng, p, rad, quatrad );\t\t\n\t\tif( get_ident_lever_dis(p,lever) < rad ){\n\t\t\t++n_within;\n\t\t\tif( xmap[ x*p ] != 12345.0 ) ++n_lever_false_neg;\n\t\t} else {\n\t\t\t++n_without;\n\t\t\tif( xmap[ x*p ] == 12345.0 ) ++n_lever_false_pos;\n\t\t}\n\n\n\t}\n\tcout << \"CART FAIL FRAC \" << (float)n_cart_fail/NSAMP2 << endl;\n\tcout << \"ROT  FAIL FRAC \" << (float)n_rot_fail/NSAMP2  << endl;\t\n\tcout << \"BOTH FAIL FRAC \" << (float)n_both_fail/NSAMP2 << endl;\t\n\n\tcout << \"FALSE POS \" << (float)n_lever_false_pos/n_without << endl;\n\tcout << \"FALSE NEG \" << (float)n_lever_false_neg/n_within\t\n\t      << \",  FRAC \" << (float)n_within/NSAMP2 << endl;\n\n\tASSERT_LT( (float)n_cart_fail/NSAMP2, 0.03 );\n\tASSERT_LT( (float)n_rot_fail/NSAMP2, 0.03 );\t\n\tASSERT_LT( (float)n_both_fail/NSAMP2, 0.01 );\n\tASSERT_LT( (float)n_lever_false_pos/n_without, 0.30 );\n\tASSERT_LT( (float)n_lever_false_neg/n_within , 0.015 );\n\n}\n\n\n\n\n\n\nTEST( XformMap, test_bt24_bcc6 ){\n\ttypedef Eigen::Transform<double,3,Eigen::AffineCompact> EigenXform;\n\ttypedef scheme::objective::hash::XformMap< EigenXform, double, XformHash_bt24_BCC6 > XMap;\n\n\tXMap xmap( 1.0, 10.0 );\n\n}\n\n\n\nTEST( XformMap, DISABLED_test_float_double ){\n\ttypedef Eigen::Transform<double,3,Eigen::AffineCompact> EigenXformD;\n\ttypedef scheme::objective::hash::XformMap< EigenXformD, double, XformHash_bt24_BCC6 > XMapD;\n\ttypedef Eigen::Transform<float,3,Eigen::AffineCompact> EigenXformF;\n\ttypedef scheme::objective::hash::XformMap< EigenXformF, double, XformHash_bt24_BCC6 > XMapF;\n\n\tASSERT_TRUE( false );\n\n}\n\n\n\n}}}}\n", "meta": {"hexsha": "2cef25ea8f9abc8dd699b47c6e1a2099abd8d349", "size": 5983, "ext": "cc", "lang": "C++", "max_stars_repo_path": "schemelib/scheme/objective/hash/XformMap.gtest.cc", "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/objective/hash/XformMap.gtest.cc", "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/objective/hash/XformMap.gtest.cc", "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": 31.4894736842, "max_line_length": 118, "alphanum_fraction": 0.6563596858, "num_tokens": 2049, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768249, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.487353264466523}}
{"text": "#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n\n#include <CGAL/Polyhedron_3.h>\n#include <CGAL/boost/graph/properties_Polyhedron_3.h>\n#include <CGAL/IO/Polyhedron_iostream.h>\n\n#include <CGAL/Surface_mesh.h>\n#include <CGAL/boost/graph/properties_Surface_mesh.h>\n\n#include <CGAL/Polygon_mesh_processing/measure.h>\n#include <CGAL/Polygon_mesh_processing/bbox.h>\n#include <CGAL/Polygon_mesh_processing/stitch_borders.h>\n\n#include <CGAL/Bbox_3.h>\n\n#include <iostream>\n#include <fstream>\n#include <iterator>\n#include <list>\n\n#include <boost/foreach.hpp>\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\ntypedef K::Point_3 Point;\n\ntypedef CGAL::Polyhedron_3<K>       Polyhedron;\ntypedef CGAL::Surface_mesh<Point>   Surface_mesh;\n\nnamespace PMP = CGAL::Polygon_mesh_processing;\n\ntemplate<typename Mesh>\nvoid test(const Mesh& pmesh)\n{\n  typedef typename boost::graph_traits<Mesh>::halfedge_descriptor halfedge_descriptor;\n  typedef typename boost::graph_traits<Mesh>::face_descriptor     face_descriptor;\n\n  halfedge_descriptor border_he;\n  BOOST_FOREACH(halfedge_descriptor h, halfedges(pmesh))\n  {\n    if (is_border(h, pmesh))\n    {\n      border_he = h;\n      break;\n    }\n  }\n  double border_l = PMP::face_border_length(border_he, pmesh);\n  std::cout << \"length of hole border = \" << border_l << std::endl;\n\n  face_descriptor valid_patch_face;\n  unsigned int count = 0;\n  BOOST_FOREACH(halfedge_descriptor h, halfedges(pmesh))\n  {\n    if (is_border(h, pmesh) || is_border(opposite(h, pmesh), pmesh))\n      continue;\n    else\n    {\n      double face_area = PMP::face_area(face(h, pmesh), pmesh);\n      std::cout << \"face area = \" << face_area << std::endl;\n\n      if(++count == 20)\n      {\n        valid_patch_face = face(h, pmesh);\n        break;\n      }\n    }\n  }\n\n  std::list<face_descriptor> patch;\n  patch.push_back(valid_patch_face);\n  while (patch.size() < 5)\n  {\n    face_descriptor f = patch.front();\n    patch.pop_front();\n    BOOST_FOREACH(halfedge_descriptor h, halfedges_around_face(halfedge(f, pmesh), pmesh))\n    {\n      if (boost::graph_traits<Mesh>::null_halfedge() != opposite(h, pmesh))\n        patch.push_back(face(opposite(h, pmesh), pmesh));\n      patch.push_back(f);\n    }\n    if (patch.front() == valid_patch_face)\n      break;//back to starting point\n  }\n\n  double patch_area = PMP::area(patch, pmesh);\n  std::cout << \"patch area = \" << patch_area << std::endl;\n\n  double mesh_area = PMP::area(pmesh);\n  std::cout << \"mesh area = \" << mesh_area << std::endl;\n\n  double mesh_area_np = PMP::area(pmesh,\n    PMP::parameters::geom_traits(K()));\n  std::cout << \"mesh area (NP) = \" << mesh_area_np << std::endl;\n\n\n  CGAL::Bbox_3 bb = PMP::bbox_3(pmesh);\n  std::cout << \"bbox x[\" << bb.xmin() << \"; \" << bb.xmax() << \"]\" << std::endl;\n  std::cout << \"     y[\" << bb.ymin() << \"; \" << bb.ymax() << \"]\" << std::endl;\n  std::cout << \"     z[\" << bb.zmin() << \"; \" << bb.zmax() << \"]\" << std::endl;\n\n}\n\nvoid test_polyhedron(const char* filename)\n{\n  //run test for a Polyhedron\n  Polyhedron poly; // file should contain oriented polyhedron\n  std::ifstream input(filename);\n\n  if (!input || !(input >> poly))\n  {\n    std::cerr << \"Error: cannot read Polyhedron : \" << filename << \"\\n\";\n    assert(!poly.empty());\n    assert(false);\n    return;\n  }\n\n  test(poly);\n}\n\nvoid test_closed_surface_mesh(const char* filename)\n{\n  Surface_mesh sm;\n  std::ifstream input(filename);\n\n  if (!input || !(input >> sm))\n  {\n    std::cerr << \"Error: cannot read Surface mesh : \" << filename << \"\\n\";\n    assert(sm.number_of_vertices() > 0);\n    assert(false);\n    return;\n  }\n\n  test(sm);\n\n  double vol = PMP::volume(sm);\n  std::cout << \"volume = \" << vol << std::endl;\n}\n\nint main(int argc, char* argv[])\n{\n  const char* filename_polyhedron =\n    (argc > 1) ? argv[1] : \"data/mech-holes-shark.off\";\n  test_polyhedron(filename_polyhedron);\n\n  const char* filename_surface_mesh =\n    (argc > 1) ? argv[1] : \"data/elephant.off\";\n  test_closed_surface_mesh(filename_surface_mesh);\n\n  std::cerr << \"All done.\" << std::endl;\n  return 0;\n}\n", "meta": {"hexsha": "d386b67b1756d45cc82e09733655bfbc9919ae88", "size": 4055, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "graphics/cgal/Polygon_mesh_processing/test/Polygon_mesh_processing/measures_test.cpp", "max_stars_repo_name": "hlzz/dotfiles", "max_stars_repo_head_hexsha": "0591f71230c919c827ba569099eb3b75897e163e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-03-30T14:31:52.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-02T05:01:32.000Z", "max_issues_repo_path": "graphics/cgal/Polygon_mesh_processing/test/Polygon_mesh_processing/measures_test.cpp", "max_issues_repo_name": "hlzz/dotfiles", "max_issues_repo_head_hexsha": "0591f71230c919c827ba569099eb3b75897e163e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "graphics/cgal/Polygon_mesh_processing/test/Polygon_mesh_processing/measures_test.cpp", "max_forks_repo_name": "hlzz/dotfiles", "max_forks_repo_head_hexsha": "0591f71230c919c827ba569099eb3b75897e163e", "max_forks_repo_licenses": ["BSD-3-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.8543046358, "max_line_length": 90, "alphanum_fraction": 0.6542540074, "num_tokens": 1129, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.6723316860482763, "lm_q1q2_score": 0.4873532549482443}}
{"text": "#include <gtest/gtest.h>\n#include <Eigen/Core>\n#include <sophus/se3.hpp>\n\n#include <determinant4x4.h>\n#include <quaternion_product.h>\n#include <random>\n\n/*\n  Test quaternion product utlity module\n*/\nTEST(DiospyrosTest, crossProductTest) {\n    Eigen::Vector<float, 3> lhs(1, 2, 3);\n    Eigen::Vector<float, 3> rhs(-1, 4, 6);\n\n    Eigen::Vector<float, 3> result = crossProduct(lhs, rhs);\n\n    auto expected = lhs.cross(rhs);\n\n    EXPECT_EQ(expected(0), result(0));\n    EXPECT_EQ(expected(1), result(1));\n    EXPECT_EQ(expected(2), result(2));\n}\n\nTEST(DiospyrosTest, quaternionTest) {\n    std::mt19937 gen;\n    std::uniform_real_distribution<> dist;\n\n    gen = std::mt19937(0);\n    dist = std::uniform_real_distribution<>(-1.0f, 1.0f);\n\n    ::Eigen::Quaternion<float> aq = ::Eigen::Quaternion<float>::UnitRandom();\n    ::Eigen::Vector3f at(dist(gen), dist(gen), dist(gen));\n    Sophus::SE3<float> a(aq, at);\n\n    ::Eigen::Quaternion<float> bq = ::Eigen::Quaternion<float>::UnitRandom();\n    ::Eigen::Vector3f bt(dist(gen), dist(gen), dist(gen));\n    Sophus::SE3<float> b(bq, bt);\n\n    Sophus::SE3<float> c = a * b;\n\n    Eigen::Vector<float, 4> aq_(aq.x(), aq.y(), aq.z(), aq.w());\n    Eigen::Vector<float, 3> at_(at(0), at(1), at(2));\n    SE3T a_ = {aq_, at_};\n\n    Eigen::Vector<float, 4> bq_(bq.x(), bq.y(), bq.z(), bq.w());\n    Eigen::Vector<float, 3> bt_(bt(0), bt(1), bt(2));\n    SE3T b_ = {bq_, bt_};\n\n    SE3T c_ = quaternionProduct(a_, b_);\n\n    auto eq = c.unit_quaternion();\n    auto et = c.translation();\n\n    auto rq = c_.quaternion;\n    auto rt = c_.translation;\n\n    EXPECT_NEAR(eq.w(), rq(3), 1E-5);\n    EXPECT_NEAR(eq.x(), rq(0), 1E-5);\n    EXPECT_NEAR(eq.y(), rq(1), 1E-5);\n    EXPECT_NEAR(eq.z(), rq(2), 1E-5);\n\n    EXPECT_NEAR(et(0), rt(0), 1E-5);\n    EXPECT_NEAR(et(1), rt(1), 1E-5);\n    EXPECT_NEAR(et(2), rt(2), 1E-5);\n}\n", "meta": {"hexsha": "6d5e4081fa00ce6820a59a915fcafecdbfd148af", "size": 1840, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "evaluation/q-prod/diospyros_test.cpp", "max_stars_repo_name": "sgpthomas/diospyros", "max_stars_repo_head_hexsha": "27d4e5e5d4e56a6dc5860d7c7d5eefb27de24a5d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2020-02-16T22:26:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T04:17:19.000Z", "max_issues_repo_path": "evaluation/q-prod/diospyros_test.cpp", "max_issues_repo_name": "sgpthomas/diospyros", "max_issues_repo_head_hexsha": "27d4e5e5d4e56a6dc5860d7c7d5eefb27de24a5d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 77.0, "max_issues_repo_issues_event_min_datetime": "2020-01-21T15:37:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-11T19:48:43.000Z", "max_forks_repo_path": "evaluation/q-prod/diospyros_test.cpp", "max_forks_repo_name": "sgpthomas/diospyros", "max_forks_repo_head_hexsha": "27d4e5e5d4e56a6dc5860d7c7d5eefb27de24a5d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-27T20:35:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-27T20:35:15.000Z", "avg_line_length": 27.4626865672, "max_line_length": 77, "alphanum_fraction": 0.6054347826, "num_tokens": 620, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.72487026428967, "lm_q2_score": 0.6723316860482763, "lm_q1q2_score": 0.4873532469561335}}
{"text": "// Copyright (c) 2020 Chris Richardson & Matthew Scroggs\n// FEniCS Project\n// SPDX-License-Identifier:    MIT\n\n#include \"lagrange.h\"\n#include \"dof-permutations.h\"\n#include \"lattice.h\"\n#include \"libtab.h\"\n#include \"polyset.h\"\n#include <Eigen/Dense>\n#include <iostream>\n#include <numeric>\n\nusing namespace libtab;\n\n//----------------------------------------------------------------------------\nFiniteElement libtab::create_lagrange(cell::type celltype, int degree,\n                                      const std::string& name)\n{\n  if (celltype == cell::type::point)\n    throw std::runtime_error(\"Invalid celltype\");\n\n  const int ndofs = polyset::dim(celltype, degree);\n\n  const std::vector<std::vector<std::vector<int>>> topology\n      = cell::topology(celltype);\n  std::vector<std::vector<int>> entity_dofs(topology.size());\n\n  // Create points at nodes, ordered by topology (vertices first)\n  Eigen::ArrayXXd pt(ndofs, topology.size() - 1);\n  if (degree == 0)\n  {\n    pt = lattice::create(celltype, 0, lattice::type::equispaced, true);\n    for (std::size_t i = 0; i < entity_dofs.size(); ++i)\n      entity_dofs[i].resize(topology[i].size(), 0);\n    entity_dofs[topology.size() - 1][0] = 1;\n  }\n  else\n  {\n    int c = 0;\n    for (std::size_t dim = 0; dim < topology.size(); ++dim)\n    {\n      for (std::size_t i = 0; i < topology[dim].size(); ++i)\n      {\n        const Eigen::ArrayXXd entity_geom\n            = cell::sub_entity_geometry(celltype, dim, i);\n\n        if (dim == 0)\n        {\n          pt.row(c++) = entity_geom.row(0);\n          entity_dofs[0].push_back(1);\n        }\n        else if (dim == topology.size() - 1)\n        {\n          const Eigen::ArrayXXd lattice = lattice::create(\n              celltype, degree, lattice::type::equispaced, false);\n          for (int j = 0; j < lattice.rows(); ++j)\n            pt.row(c++) = lattice.row(j);\n          entity_dofs[dim].push_back(lattice.rows());\n        }\n        else\n        {\n          cell::type ct = cell::sub_entity_type(celltype, dim, i);\n          const Eigen::ArrayXXd lattice\n              = lattice::create(ct, degree, lattice::type::equispaced, false);\n          entity_dofs[dim].push_back(lattice.rows());\n          for (int j = 0; j < lattice.rows(); ++j)\n          {\n            pt.row(c) = entity_geom.row(0);\n            for (int k = 0; k < lattice.cols(); ++k)\n            {\n              pt.row(c) += (entity_geom.row(k + 1) - entity_geom.row(0))\n                           * lattice(j, k);\n            }\n            ++c;\n          }\n        }\n      }\n    }\n  }\n\n  int perm_count = 0;\n  for (std::size_t i = 1; i < topology.size() - 1; ++i)\n    perm_count += topology[i].size() * i;\n\n  std::vector<Eigen::MatrixXd> base_permutations(\n      perm_count, Eigen::MatrixXd::Identity(ndofs, ndofs));\n  if (celltype == cell::type::triangle)\n  {\n    Eigen::ArrayXi edge_ref = dofperms::interval_reflection(degree - 1);\n    for (int edge = 0; edge < 3; ++edge)\n    {\n      const int start = 3 + edge_ref.size() * edge;\n      for (int i = 0; i < edge_ref.size(); ++i)\n      {\n        base_permutations[edge](start + i, start + i) = 0;\n        base_permutations[edge](start + i, start + edge_ref[i]) = 1;\n      }\n    }\n  }\n  else if (celltype == cell::type::tetrahedron)\n  {\n    Eigen::ArrayXi edge_ref = dofperms::interval_reflection(degree - 1);\n    for (int edge = 0; edge < 6; ++edge)\n    {\n      const int start = 4 + edge_ref.size() * edge;\n      for (int i = 0; i < edge_ref.size(); ++i)\n      {\n        base_permutations[edge](start + i, start + i) = 0;\n        base_permutations[edge](start + i, start + edge_ref[i]) = 1;\n      }\n    }\n    Eigen::ArrayXi face_ref = dofperms::triangle_reflection(degree - 2);\n    Eigen::ArrayXi face_rot = dofperms::triangle_rotation(degree - 2);\n    for (int face = 0; face < 4; ++face)\n    {\n      const int start = 4 + edge_ref.size() * 6 + face_ref.size() * face;\n      for (int i = 0; i < face_rot.size(); ++i)\n      {\n        base_permutations[6 + 2 * face](start + i, start + i) = 0;\n        base_permutations[6 + 2 * face](start + i, start + face_rot[i]) = 1;\n        base_permutations[6 + 2 * face + 1](start + i, start + i) = 0;\n        base_permutations[6 + 2 * face + 1](start + i, start + face_ref[i]) = 1;\n      }\n    }\n  }\n\n  // Point evaluation of basis\n  Eigen::MatrixXd dualmat = polyset::tabulate(celltype, degree, 0, pt)[0];\n  Eigen::MatrixXd coeffs = compute_expansion_coefficients(\n      Eigen::MatrixXd::Identity(ndofs, ndofs), dualmat);\n\n  return FiniteElement(name, celltype, degree, {1}, coeffs, entity_dofs,\n                       base_permutations);\n}\n//-----------------------------------------------------------------------------\nFiniteElement libtab::create_dlagrange(cell::type celltype, int degree,\n                                       const std::string& name)\n{\n  if (celltype != cell::type::interval and celltype != cell::type::triangle\n      and celltype != cell::type::tetrahedron)\n    throw std::runtime_error(\"Invalid celltype\");\n\n  // Only tabulate for scalar. Vector spaces can easily be built from\n  // the scalar space.\n\n  const int ndofs = polyset::dim(celltype, degree);\n\n  std::vector<std::vector<std::vector<int>>> topology\n      = cell::topology(celltype);\n  std::vector<std::vector<int>> entity_dofs(topology.size());\n  for (std::size_t i = 0; i < topology.size(); ++i)\n    entity_dofs[i].resize(topology[i].size(), 0);\n  entity_dofs[topology.size() - 1][0] = ndofs;\n\n  Eigen::ArrayXXd geometry = cell::geometry(celltype);\n  const Eigen::ArrayXXd lattice\n      = lattice::create(celltype, degree, lattice::type::equispaced, true);\n\n  // Create points at nodes, ordered by topology (vertices first)\n  Eigen::ArrayXXd pt(ndofs, topology.size() - 1);\n  for (int j = 0; j < lattice.rows(); ++j)\n  {\n    pt.row(j) = geometry.row(0);\n    for (int k = 0; k < geometry.rows() - 1; ++k)\n      pt.row(j) += (geometry.row(k + 1) - geometry.row(0)) * lattice(j, k);\n  }\n\n  // Point evaluation of basis\n  Eigen::MatrixXd dualmat = polyset::tabulate(celltype, degree, 0, pt)[0];\n\n  Eigen::MatrixXd coeffs = compute_expansion_coefficients(\n      Eigen::MatrixXd::Identity(ndofs, ndofs), dualmat);\n\n  int perm_count = 0;\n  for (std::size_t i = 1; i < topology.size() - 1; ++i)\n    perm_count += topology[i].size() * i;\n\n  std::vector<Eigen::MatrixXd> base_permutations(\n      perm_count, Eigen::MatrixXd::Identity(ndofs, ndofs));\n\n  return FiniteElement(name, celltype, degree, {1}, coeffs, entity_dofs,\n                       base_permutations);\n}\n//-----------------------------------------------------------------------------\n", "meta": {"hexsha": "39d65032ddf624db4670493a358527d6d2f036c8", "size": 6579, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/lagrange.cpp", "max_stars_repo_name": "chrisrichardson/libtab", "max_stars_repo_head_hexsha": "1f6593409bf51427bd6d8d1036bb885f5fbb7a8c", "max_stars_repo_licenses": ["MIT"], "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/lagrange.cpp", "max_issues_repo_name": "chrisrichardson/libtab", "max_issues_repo_head_hexsha": "1f6593409bf51427bd6d8d1036bb885f5fbb7a8c", "max_issues_repo_licenses": ["MIT"], "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/lagrange.cpp", "max_forks_repo_name": "chrisrichardson/libtab", "max_forks_repo_head_hexsha": "1f6593409bf51427bd6d8d1036bb885f5fbb7a8c", "max_forks_repo_licenses": ["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.3709677419, "max_line_length": 80, "alphanum_fraction": 0.5671074631, "num_tokens": 1819, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4873455149627974}}
{"text": "#include <boost/algorithm/cxx11/iota.hpp>\n#include <boost/algorithm/cxx11/is_sorted.hpp>\n#include <boost/algorithm/cxx11/copy_if.hpp>\n#include <vector>\n#include <iterator>\n#include <iostream>\n\nusing namespace boost::algorithm;\n\nint main()\n{\n  std::vector<int> v;\n  iota_n(std::back_inserter(v), 10, 5);\n  std::cout.setf(std::ios::boolalpha);\n  std::cout << is_increasing(v) << '\\n';\n  std::ostream_iterator<int> out{std::cout, \",\"};\n  copy_until(v, out, [](int i){ return i > 12; });\n}", "meta": {"hexsha": "d8c08cc784e914ee754aec0e426e2afe994033bb", "size": 485, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Example/algorithm_02/main.cpp", "max_stars_repo_name": "KwangjoJeong/Boost", "max_stars_repo_head_hexsha": "29c4e2422feded66a689e3aef73086c5cf95b6fe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Example/algorithm_02/main.cpp", "max_issues_repo_name": "KwangjoJeong/Boost", "max_issues_repo_head_hexsha": "29c4e2422feded66a689e3aef73086c5cf95b6fe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Example/algorithm_02/main.cpp", "max_forks_repo_name": "KwangjoJeong/Boost", "max_forks_repo_head_hexsha": "29c4e2422feded66a689e3aef73086c5cf95b6fe", "max_forks_repo_licenses": ["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.9444444444, "max_line_length": 50, "alphanum_fraction": 0.6824742268, "num_tokens": 144, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.4873437534335674}}
{"text": "/* test_uniform_smallint_distribution.cpp\r\n *\r\n * Copyright Steven Watanabe 2011\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 * $Id: test_uniform_smallint_distribution.cpp 71018 2011-04-05 21:27:52Z steven_watanabe $\r\n *\r\n */\r\n\r\n#include <boost/random/uniform_smallint.hpp>\r\n#include <limits>\r\n\r\n#define BOOST_RANDOM_DISTRIBUTION boost::random::uniform_smallint<>\r\n#define BOOST_RANDOM_ARG1 a\r\n#define BOOST_RANDOM_ARG2 b\r\n#define BOOST_RANDOM_ARG1_DEFAULT 0\r\n#define BOOST_RANDOM_ARG2_DEFAULT 9\r\n#define BOOST_RANDOM_ARG1_VALUE 5\r\n#define BOOST_RANDOM_ARG2_VALUE 250\r\n\r\n#define BOOST_RANDOM_DIST0_MIN 0\r\n#define BOOST_RANDOM_DIST0_MAX 9\r\n#define BOOST_RANDOM_DIST1_MIN 5\r\n#define BOOST_RANDOM_DIST1_MAX 9\r\n#define BOOST_RANDOM_DIST2_MIN 5\r\n#define BOOST_RANDOM_DIST2_MAX 250\r\n\r\n#define BOOST_RANDOM_TEST1_PARAMS (0, 9)\r\n#define BOOST_RANDOM_TEST1_MIN 0\r\n#define BOOST_RANDOM_TEST1_MAX 9\r\n\r\n#define BOOST_RANDOM_TEST2_PARAMS (10, 19)\r\n#define BOOST_RANDOM_TEST2_MIN 10\r\n#define BOOST_RANDOM_TEST2_MAX 19\r\n\r\n#include \"test_distribution.ipp\"\r\n", "meta": {"hexsha": "fdbd2f8b67ed2fc475af186b7c5bef44c50cdada", "size": 1161, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/random/test/test_uniform_smallint_distribution.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/random/test/test_uniform_smallint_distribution.cpp", "max_issues_repo_name": "xiaoliang2121/Boost", "max_issues_repo_head_hexsha": "fc90c3fde129c62565c023f091eddc4a7ed9902b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-03-19T08:23:23.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-24T07:48:47.000Z", "max_forks_repo_path": "libs/random/test/test_uniform_smallint_distribution.cpp", "max_forks_repo_name": "xiaoliang2121/Boost", "max_forks_repo_head_hexsha": "fc90c3fde129c62565c023f091eddc4a7ed9902b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 29.7692307692, "max_line_length": 92, "alphanum_fraction": 0.7984496124, "num_tokens": 298, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.4873437534335674}}
{"text": "/*\n    This file is part of Mitsuba, a physically based rendering system.\n\n    Copyright (c) 2007-2014 by Wenzel Jakob and others.\n\n    Mitsuba is free software; you can redistribute it and/or modify\n    it under the terms of the GNU General Public License Version 3\n    as published by the Free Software Foundation.\n\n    Mitsuba is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program. If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <mitsuba/core/plugin.h>\n#include <mitsuba/core/statistics.h>\n#include <mitsuba/core/chisquare.h>\n#include <mitsuba/core/fresolver.h>\n#include <mitsuba/render/testcase.h>\n#include <boost/bind.hpp>\n#include \"../bsdfs/microfacet.h\"\n\n/* Statistical significance level of the test. Set to\n   1/4 percent by default -- we want there to be strong\n   evidence of an implementaiton error before failing\n   a test case */\n#define SIGNIFICANCE_LEVEL 0.0025f\n\n/* Relative bound on what is still accepted as roundoff\n   error -- be quite tolerant */\n#if defined(SINGLE_PRECISION)\n\t#define ERROR_REQ 1e-2f\n#else\n\t#define ERROR_REQ 1e-5\n#endif\n\nMTS_NAMESPACE_BEGIN\n\nclass TestChiSquare : public TestCase {\npublic:\n\tMTS_BEGIN_TESTCASE()\n\tMTS_DECLARE_TEST(test01_Microfacet)\n\tMTS_DECLARE_TEST(test02_MicrofacetVisible)\n\tMTS_END_TESTCASE()\n\n\tclass MicrofacetAdapter {\n\tpublic:\n\t\tMicrofacetAdapter(Sampler *sampler, const MicrofacetDistribution &distr, const Vector &wi = Vector(0.0f)) : m_sampler(sampler), m_distr(distr), m_wi(wi) { }\n\n\t\tboost::tuple<Vector, Float, EMeasure> generateSample() {\n\t\t\tFloat pdf;\n\n\t\t\tif (m_wi.lengthSquared() == 0) {\n\t\t\t\tNormal m = m_distr.sampleAll(m_sampler->next2D(), pdf);\n\t\t\t\tFloat pdf_ref = m_distr.pdfAll(m);\n\n\t\t\t\tSAssert(std::isfinite(pdf) && pdf > 0);\n\t\t\t\tSAssert(std::isfinite(pdf_ref) && pdf_ref > 0);\n\t\t\t\tSAssert(std::isfinite(m.x) && std::isfinite(m.y) && std::isfinite(m.z));\n\t\t\t\tSAssert(std::abs(m.length() - 1) < 1e-4f);\n\t\t\t\tSAssert(std::abs((pdf-pdf_ref)/pdf_ref) < 1e-4f);\n\t\t\t\treturn boost::make_tuple(m, 1.0f, ESolidAngle);\n\t\t\t} else {\n\t\t\t\tNormal m = m_distr.sampleVisible(m_wi, m_sampler->next2D());\n\t\t\t\tSAssert(std::isfinite(m.x) && std::isfinite(m.y) && std::isfinite(m.z));\n\t\t\t\tSAssert(std::abs(m.length() - 1) < 1e-4f);\n\t\t\t\treturn boost::make_tuple(m, 1.0f, ESolidAngle);\n\t\t\t}\n\t\t}\n\n\t\tFloat pdf(const Vector &d, EMeasure measure) const {\n\t\t\tif (measure != ESolidAngle)\n\t\t\t\treturn 0.0f;\n\n\t\t\tFloat pdf = m_wi.lengthSquared() == 0 ? m_distr.pdfAll(d)\n\t\t\t\t: m_distr.pdfVisible(m_wi, d);\n\t\t\tSAssert(std::isfinite(pdf) && pdf >= 0);\n\n\t\t\treturn pdf;\n\t\t}\n\n\tprivate:\n\t\tref<Sampler> m_sampler;\n\t\tMicrofacetDistribution m_distr;\n\t\tVector m_wi;\n\t};\n\n\tvoid test01_Microfacet() {\n\t\tint thetaBins = 20;\n\t\tstd::vector<MicrofacetDistribution> distrs;\n\n\t\tdistrs.push_back(MicrofacetDistribution(MicrofacetDistribution::EBeckmann, 0.5f));\n\t\tdistrs.push_back(MicrofacetDistribution(MicrofacetDistribution::EBeckmann, 0.5f, 0.3f));\n\t\tdistrs.push_back(MicrofacetDistribution(MicrofacetDistribution::EGGX, 0.5f));\n\t\tdistrs.push_back(MicrofacetDistribution(MicrofacetDistribution::EGGX, 0.5f, 0.3f));\n\t\tdistrs.push_back(MicrofacetDistribution(MicrofacetDistribution::EPhong, 0.5f));\n\t\tdistrs.push_back(MicrofacetDistribution(MicrofacetDistribution::EPhong, 0.5f, 0.3f));\n\n\n\t\tref<Sampler> sampler = static_cast<Sampler *> (PluginManager::getInstance()->\n\t\t\t\tcreateObject(MTS_CLASS(Sampler), Properties(\"independent\")));\n\t\tref<ChiSquare> chiSqr = new ChiSquare(thetaBins, 2*thetaBins, (int) distrs.size());\n\t\tchiSqr->setLogLevel(EDebug);\n\n\t\tfor (size_t i=0; i<distrs.size(); ++i) {\n\t\t\tLog(EInfo, \"Testing %s\", distrs[i].toString().c_str());\n\t\t\t// Initialize the tables used by the chi-square test\n\t\t\tMicrofacetAdapter adapter(sampler, distrs[i]);\n\t\t\tchiSqr->fill(\n\t\t\t\tboost::bind(&MicrofacetAdapter::generateSample, &adapter),\n\t\t\t\tboost::bind(&MicrofacetAdapter::pdf, &adapter, _1, _2)\n\t\t\t);\n\n\t\t\t// (the following assumes that the distribution has 1 parameter, e.g. exponent value)\n\t\t\tChiSquare::ETestResult result = chiSqr->runTest(SIGNIFICANCE_LEVEL);\n\t\t\tif (result == ChiSquare::EReject) {\n\t\t\t\tstd::string filename = formatString(\"failure_%i.m\", (int) i);\n\t\t\t\tchiSqr->dumpTables(filename);\n\t\t\t\tfailAndContinue(formatString(\"Uh oh, the chi-square test indicates a potential \"\n\t\t\t\t\t\"issue. Dumped the contingency tables to '%s' for user analysis\",\n\t\t\t\t\tfilename.c_str()));\n\t\t\t} else {\n\t\t\t\t//chiSqr->dumpTables(formatString(\"success_%i.m\", (int) i));\n\t\t\t\tsucceed();\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid test02_MicrofacetVisible() {\n\t\tint thetaBins = 10;\n\t\tstd::vector<std::pair<MicrofacetDistribution, Vector> > distrs;\n\n\t\tref<Sampler> sampler = static_cast<Sampler *> (PluginManager::getInstance()->\n\t\t\t\tcreateObject(MTS_CLASS(Sampler), Properties(\"independent\")));\n\t\tfor (int i=0; i<10; ++i) {\n\t\t\tVector wi = warp::squareToUniformHemisphere(sampler->next2D());\n\t\t\tdistrs.push_back(std::make_pair(MicrofacetDistribution(MicrofacetDistribution::EBeckmann, 0.3f), wi));\n\t\t\tdistrs.push_back(std::make_pair(MicrofacetDistribution(MicrofacetDistribution::EBeckmann, 0.5f, 0.3f), wi));\n\t\t\tdistrs.push_back(std::make_pair(MicrofacetDistribution(MicrofacetDistribution::EGGX, 0.1f), wi));\n\t\t\tdistrs.push_back(std::make_pair(MicrofacetDistribution(MicrofacetDistribution::EGGX, 0.2f, 0.3f), wi));\n\t\t}\n\n\t\tref<ChiSquare> chiSqr = new ChiSquare(thetaBins, 2*thetaBins, (int) distrs.size());\n\t\tchiSqr->setLogLevel(EDebug);\n\n\t\tfor (size_t i=0; i<distrs.size(); ++i) {\n\t\t\tLog(EInfo, \"Testing %s (wi=%s)\", distrs[i].first.toString().c_str(), distrs[i].second.toString().c_str());\n\t\t\t// Initialize the tables used by the chi-square test\n\t\t\tMicrofacetAdapter adapter(sampler, distrs[i].first, distrs[i].second);\n\t\t\tchiSqr->fill(\n\t\t\t\tboost::bind(&MicrofacetAdapter::generateSample, &adapter),\n\t\t\t\tboost::bind(&MicrofacetAdapter::pdf, &adapter, _1, _2)\n\t\t\t);\n\n\t\t\t// (the following assumes that the distribution has 1 parameter, e.g. exponent value)\n\t\t\tChiSquare::ETestResult result = chiSqr->runTest(SIGNIFICANCE_LEVEL);\n\t\t\tif (result == ChiSquare::EReject) {\n\t\t\t\tstd::string filename = formatString(\"failure_%i.m\", (int) i);\n\t\t\t\tchiSqr->dumpTables(filename);\n\t\t\t\tfailAndContinue(formatString(\"Uh oh, the chi-square test indicates a potential \"\n\t\t\t\t\t\"issue. Dumped the contingency tables to '%s' for user analysis\",\n\t\t\t\t\tfilename.c_str()));\n\t\t\t} else {\n\t\t\t\t//chiSqr->dumpTables(formatString(\"success_%i.m\", (int) i));\n\t\t\t\tsucceed();\n\t\t\t}\n\t\t}\n\t}\n};\n\nMTS_EXPORT_TESTCASE(TestChiSquare, \"Chi-square test for microfacet sampling\")\nMTS_NAMESPACE_END\n", "meta": {"hexsha": "434c9d66a06d985c1a798547e17e09a188313a37", "size": 6736, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mitsuba-af602c6fd98a/src/tests/test_microfacet.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/tests/test_microfacet.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/tests/test_microfacet.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": 38.0564971751, "max_line_length": 158, "alphanum_fraction": 0.7128859857, "num_tokens": 1983, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.4873437458861648}}
{"text": "#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#include <iostream>\n#include <random>\n#include <cmath>\n#include <fstream>\n#include <armadillo>\n\nusing namespace std;\nusing namespace cv;\n\n#include \"input.h\"\n\nvoid findEllipses(vector<Mat> channels, int k, Mat &sc, Mat &res, vector<RotatedRect> &minEllipse) {\n    vector<Vec4i> hierarchy;\n    vector<vector<Point>> contours;\n\n    // Blur the image before binarization\n    blur(channels[k], sc, Size(3, 3));\n\n    //Mat img_copy(sc.rows, sc.cols, CV_8UC3, Scalar(255, 255, 255));\n\n    // Binarize it and find contours\n    threshold(sc, sc, 105, 255, THRESH_BINARY);\n    findContours(sc, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));\n\n    vector<RotatedRect> minRect_red(contours.size());\n\n    for (int i = 0; i < contours.size(); i++) {\n        minRect_red[i] = minAreaRect(Mat(contours[i]));\n        //printf(\"contour %d, size %ld, %ld x %ld\\n\", i, contours[i].size(), minRect_red[i].size.width, minRect_red[i].size.height);\n        if (contours[i].size() > 5 && minRect_red[i].size.width > 60.0){\n            minEllipse.push_back(fitEllipse(Mat(contours[i])));\n            //{ minEllipse_red[i] = fitEllipse( Mat(contours[i]) ); }\n        }\n    }\n\n    // Draw the resulting ellipses\n    for (int i = 0; i < minEllipse.size(); i++) {\n        Scalar color = Scalar(rand() % 255, rand() % 255, rand() % 255);\n        // contour\n        drawContours(res, contours, i, color, 1, 8, vector<Vec4i>(), 0, Point());\n        // ellipse\n        ellipse(res, minEllipse[i], color, 2, 8);\n        // rotated rectangle\n        Point2f rect_points[4];\n        minRect_red[i].points(rect_points);\n        for (int j = 0; j < 4; j++)\n            line(res, rect_points[j], rect_points[(j + 1) % 4], color, 1, 8);\n    }\n}\n\nvoid generatePattern() {\n    // 300 dpi (print) = 2480 X 3508 pixels (This is \"A4\" as I know it, i.e. \"210mm X 297mm @ 300 dpi\")\n    // 600 dpi = \n    //unsigned int height = 1123, width = 1587;\n    unsigned int height = 2480 - 100, width = 3508 - 100;\n    Mat image(height, width, CV_8UC3, Scalar(255, 255, 255));\n    int x = 90, y = 55, radius = 30;\n    while (x + 15 < width){\n        while (y + 15 < height) {\n            circle(image, Point(x, y), radius, Scalar(0, 0, 0), CV_FILLED, 4);\n            y += 90;\n        }\n        y = 55;\n        x += 90;\n\n    }\n\n    imwrite(\"picture.png\", image);\n}\n\nint main(int argc, char *argv[]) {\n\n    // Parse input options\n    InputParser input(argc, argv);\n    if (input.cmdOptionExists(\"-g\")){\n        // Generate image with a test pattern to photo\n        cout << \"Generating test pattern\" << endl;\n        generatePattern();\n        return 0;\n    }\n\n    const std::string &filename = input.getCmdOption(\"-f\");\n    if (!filename.empty()){\n        // Source image file name\n    }\n\n    // Load photo of the template\n    Mat img = imread(\"src4.png\", 1);\n\n    // Create images for the channels\n    Mat img_resR(img.rows, img.cols, CV_8UC3, Scalar(255, 255, 255));\n    Mat img_resG(img.rows, img.cols, CV_8UC3, Scalar(255, 255, 255));\n    Mat img_resB(img.rows, img.cols, CV_8UC3, Scalar(255, 255, 255));\n\n    // Create images for the offsets\n    Mat img_offs1(img.rows, img.cols, CV_8UC3, Scalar(255, 255, 255));\n    Mat img_offs2(img.rows, img.cols, CV_8UC3, Scalar(255, 255, 255));\n\n    // Split source image into three channels\n    vector<Mat> channels;\n    split(img, channels);\n\n    // Find ellipses centers and save them as red,blue and green.jpg files\n    Mat red, green, blue;\n    vector<RotatedRect> minEllipse[3];\n\n    findEllipses(channels, 2, red, img_resR, minEllipse[2]);\n    imwrite(\"red.jpg\", img_resR);\n\n    findEllipses(channels, 0, blue, img_resB, minEllipse[0]);\n    imwrite(\"blue.jpg\", img_resB);\n\n    findEllipses(channels, 1, green, img_resG, minEllipse[1]);\n    imwrite(\"green.jpg\", img_resG);\n\n\n    // Take G channel as the main one and calc offsets of R and B, draw and save them\n    for (int i = 0; i < minEllipse[1].size(); i++) {\n        for (int j = 0; j < minEllipse[2].size(); j++) {\n            if (abs(minEllipse[1][i].center.x - minEllipse[2][j].center.x) < 10 && abs(minEllipse[1][i].center.y - minEllipse[2][j].center.y) < 10) {\n                swap(minEllipse[2][j], minEllipse[2][i]);\n\n                break;\n            }\n        }\n        Point distort;\n        distort = (minEllipse[2][i].center - minEllipse[1][i].center) * 15;\n        line(img_offs1, (Point)minEllipse[1][i].center, (Point)minEllipse[2][i].center + distort, Scalar(0, 0, 255), 3);\n        circle(img_offs1, (Point)minEllipse[1][i].center, 1, Scalar(0, 255, 0), CV_FILLED, 15);\n        //        cout << \"Rect[\" << i << \"].center_green = \" << minEllipse_green[i].center << \"; Rect[\" << i << \"].center_red = \" << minEllipse_red[i].center << endl;\n    }\n\n    imwrite(\"red_ffs.jpg\", img_offs1);\n\n    for (int i = 0; i < minEllipse[1].size(); i++) {\n        for (int j = 0; j < minEllipse[2].size(); j++) {\n            if (abs(minEllipse[1][i].center.x - minEllipse[2][j].center.x) < 10 && abs(minEllipse[1][i].center.y - minEllipse[2][j].center.y) < 10 && i != j) {\n                swap(minEllipse[2][j], minEllipse[2][i]);\n                break;\n            }\n        }\n        Point distort;\n        distort = (minEllipse[2][i].center - minEllipse[1][i].center) * 15;\n        line(img_offs2, (Point)minEllipse[1][i].center, (Point)minEllipse[2][i].center + distort, Scalar(255, 0, 0), 3);\n        circle(img_offs2, (Point)minEllipse[1][i].center, 1, Scalar(0, 255, 0), CV_FILLED, 15);\n        //        cout << \"Rect[\" << i << \"].center_green = \" << minEllipse_green[i].center << \"; Rect[\" << i << \"].center_blue = \" << minEllipse_blue[i].center << endl;\n        //break;\n    }\n\n    imwrite(\"blue_ffs.jpg\", img_offs2);\n\n    //namedWindow(\"Display window\", WINDOW_NORMAL);\n    //imshow(\"Display window\", img_copy);\n\n    //namedWindow(\"imge\", WINDOW_NORMAL);\n    //imshow(\"imge\", imge);\n\n    waitKey(0);\n    red.release();\n    green.release();\n    blue.release();\n\n    return 0;\n}\n", "meta": {"hexsha": "fcb6429368bb9b2b1bb7cc3a7cf654d186253930", "size": 6038, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cac.cpp", "max_stars_repo_name": "bragin/cac", "max_stars_repo_head_hexsha": "4c8897552246a351b998fee2cdb46baaed8684ba", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-04-30T04:36:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T06:52:16.000Z", "max_issues_repo_path": "cac.cpp", "max_issues_repo_name": "bragin/cac", "max_issues_repo_head_hexsha": "4c8897552246a351b998fee2cdb46baaed8684ba", "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": "cac.cpp", "max_forks_repo_name": "bragin/cac", "max_forks_repo_head_hexsha": "4c8897552246a351b998fee2cdb46baaed8684ba", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-01-14T15:12:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-13T06:41:46.000Z", "avg_line_length": 36.1556886228, "max_line_length": 169, "alphanum_fraction": 0.5864524677, "num_tokens": 1865, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743505760727, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.48734373596389297}}
{"text": "/*\n *  abstract_directions.hpp\n *\n *\tAuthor(s): Tamas D. Nagy\n *\tCreated on: 2017-11-08\n *  \n */\n\n#ifndef ABSTRACT_DIRECTIONS_HPP_\n#define ABSTRACT_DIRECTIONS_HPP_\n\n#include <iostream>\n#include <geometry_msgs/Point.h>\n#include <geometry_msgs/Quaternion.h>\n#include <Eigen/Dense>\n#include <Eigen/Geometry> \n#include <cmath>\n#include <irob_utils/utils.hpp>\n\n\nnamespace saf {\n\ntypedef enum CoordinateFrame {WORLD, CAMERA, ROBOT} CoordinateFrame;\n\n\ntemplate <CoordinateFrame CF, class T>\nclass BaseDirections {\n   public:\n   \t\tstatic const T UP;\n   \t\tstatic const T DOWN;\n   \t\tstatic const T FORWARD;\n   \t\tstatic const T BACKWARD;\n   \t\tstatic const T LEFT;\n   \t\tstatic const T RIGHT;  \t\n};\n\n/*\n *\tCAMERA\n */\n \n// Eigen::Vector3d\ntemplate<> \nconst Eigen::Vector3d \n\t\tBaseDirections<CoordinateFrame::CAMERA, Eigen::Vector3d>::\n\t\t\tUP = Eigen::Vector3d(0.0, -1.0, 0.0);\n\t\t\t\ntemplate<> \nconst Eigen::Vector3d \n\t\tBaseDirections<CoordinateFrame::CAMERA, Eigen::Vector3d>::\n\t\t\tDOWN = Eigen::Vector3d(0.0, 1.0, 0.0);\n\t\t\t\ntemplate<> \nconst Eigen::Vector3d\n\t\tBaseDirections<CoordinateFrame::CAMERA, Eigen::Vector3d>::\n\t\t\tFORWARD = Eigen::Vector3d(0.0, 0.0, 1.0);\n\t\t\t\ntemplate<> \nconst Eigen::Vector3d\n\t\tBaseDirections<CoordinateFrame::CAMERA, Eigen::Vector3d>::\n\t\t\tBACKWARD = Eigen::Vector3d(0.0, 0.0, -1.0);\n\t\t\t\ntemplate<> \nconst Eigen::Vector3d\n\t\tBaseDirections<CoordinateFrame::CAMERA, Eigen::Vector3d>::\n\t\t\tLEFT = Eigen::Vector3d(-1.0, 0.0, 0.0);\n\t\t\t\ntemplate<> \nconst Eigen::Vector3d\n\t\tBaseDirections<CoordinateFrame::CAMERA, Eigen::Vector3d>::\n\t\t\tRIGHT = Eigen::Vector3d(1.0, 0.0, 0.0);\n\t\t\t\n\n// geometry_msgs::Point\ntemplate<> \nconst geometry_msgs::Point \n\t\tBaseDirections<CoordinateFrame::CAMERA, geometry_msgs::Point>::\n\t\t\tUP \n\t\t\t= wrapToMsg<geometry_msgs::Point, Eigen::Vector3d>\n\t\t\t(BaseDirections<CoordinateFrame::CAMERA, Eigen::Vector3d>::\n\t\t\tUP);\ntemplate<> \t\t\t\nconst geometry_msgs::Point \n\t\tBaseDirections<CoordinateFrame::CAMERA, geometry_msgs::Point>::\n\t\t\tDOWN \n\t\t\t= wrapToMsg<geometry_msgs::Point, Eigen::Vector3d>\n\t\t\t(BaseDirections<CoordinateFrame::CAMERA, Eigen::Vector3d>::\n\t\t\tDOWN);\ntemplate<> \t\t\t\nconst geometry_msgs::Point \n\t\tBaseDirections<CoordinateFrame::CAMERA, geometry_msgs::Point>::\n\t\t\tFORWARD \n\t\t\t= wrapToMsg<geometry_msgs::Point, Eigen::Vector3d>\n\t\t\t(BaseDirections<CoordinateFrame::CAMERA, Eigen::Vector3d>::\n\t\t\tFORWARD);\ntemplate<> \t\t\t\nconst geometry_msgs::Point \n\t\tBaseDirections<CoordinateFrame::CAMERA, geometry_msgs::Point>::\n\t\t\tBACKWARD \n\t\t\t= wrapToMsg<geometry_msgs::Point, Eigen::Vector3d>\n\t\t\t(BaseDirections<CoordinateFrame::CAMERA, Eigen::Vector3d>::\n\t\t\tBACKWARD);\ntemplate<> \t\t\t\nconst geometry_msgs::Point \n\t\tBaseDirections<CoordinateFrame::CAMERA, geometry_msgs::Point>::\n\t\t\tLEFT \n\t\t\t= wrapToMsg<geometry_msgs::Point, Eigen::Vector3d>\n\t\t\t(BaseDirections<CoordinateFrame::CAMERA, Eigen::Vector3d>::\n\t\t\tLEFT);\ntemplate<> \t\t\t\nconst geometry_msgs::Point \n\t\tBaseDirections<CoordinateFrame::CAMERA, geometry_msgs::Point>::\n\t\t\tRIGHT \n\t\t\t= wrapToMsg<geometry_msgs::Point, Eigen::Vector3d>\n\t\t\t(BaseDirections<CoordinateFrame::CAMERA, Eigen::Vector3d>::\n\t\t\tRIGHT);\n\n/*\n *\tROBOT\n */\t\t\t\n\t\t\t\n// Eigen::Vector3d\ntemplate<> \nconst Eigen::Vector3d \n\t\tBaseDirections<CoordinateFrame::ROBOT, Eigen::Vector3d>::\n\t\t\tUP = Eigen::Vector3d(0.0, 0.0, 1.0);\n\t\t\t\ntemplate<> \nconst Eigen::Vector3d \n\t\tBaseDirections<CoordinateFrame::ROBOT, Eigen::Vector3d>::\n\t\t\tDOWN = Eigen::Vector3d(0.0, 0.0, -1.0);\n\t\t\t\ntemplate<> \nconst Eigen::Vector3d\n\t\tBaseDirections<CoordinateFrame::ROBOT, Eigen::Vector3d>::\n\t\t\tFORWARD = Eigen::Vector3d(0.0, -1.0, 0.0);\n\t\t\t\ntemplate<> \nconst Eigen::Vector3d\n\t\tBaseDirections<CoordinateFrame::ROBOT, Eigen::Vector3d>::\n\t\t\tBACKWARD = Eigen::Vector3d(0.0, 1.0, 0.0);\n\t\t\t\ntemplate<> \nconst Eigen::Vector3d\n\t\tBaseDirections<CoordinateFrame::ROBOT, Eigen::Vector3d>::\n\t\t\tLEFT = Eigen::Vector3d(1.0, 0.0, 0.0);\n\t\t\t\ntemplate<> \nconst Eigen::Vector3d\n\t\tBaseDirections<CoordinateFrame::ROBOT, Eigen::Vector3d>::\n\t\t\tRIGHT = Eigen::Vector3d(-1.0, 0.0, 0.0);\n\t\t\t\n\n// geometry_msgs::Point\ntemplate<> \nconst geometry_msgs::Point \n\t\tBaseDirections<CoordinateFrame::ROBOT, geometry_msgs::Point>::\n\t\t\tUP \n\t\t\t= wrapToMsg<geometry_msgs::Point, Eigen::Vector3d>\n\t\t\t(BaseDirections<CoordinateFrame::ROBOT, Eigen::Vector3d>::\n\t\t\tUP);\ntemplate<> \t\t\t\nconst geometry_msgs::Point \n\t\tBaseDirections<CoordinateFrame::ROBOT, geometry_msgs::Point>::\n\t\t\tDOWN \n\t\t\t= wrapToMsg<geometry_msgs::Point, Eigen::Vector3d>\n\t\t\t(BaseDirections<CoordinateFrame::ROBOT, Eigen::Vector3d>::\n\t\t\tDOWN);\ntemplate<> \t\t\t\nconst geometry_msgs::Point \n\t\tBaseDirections<CoordinateFrame::ROBOT, geometry_msgs::Point>::\n\t\t\tFORWARD \n\t\t\t= wrapToMsg<geometry_msgs::Point, Eigen::Vector3d>\n\t\t\t(BaseDirections<CoordinateFrame::ROBOT, Eigen::Vector3d>::\n\t\t\tFORWARD);\ntemplate<> \t\t\t\nconst geometry_msgs::Point \n\t\tBaseDirections<CoordinateFrame::ROBOT, geometry_msgs::Point>::\n\t\t\tBACKWARD \n\t\t\t= wrapToMsg<geometry_msgs::Point, Eigen::Vector3d>\n\t\t\t(BaseDirections<CoordinateFrame::ROBOT, Eigen::Vector3d>::\n\t\t\tBACKWARD);\ntemplate<> \t\t\t\nconst geometry_msgs::Point \n\t\tBaseDirections<CoordinateFrame::ROBOT, geometry_msgs::Point>::\n\t\t\tLEFT \n\t\t\t= wrapToMsg<geometry_msgs::Point, Eigen::Vector3d>\n\t\t\t(BaseDirections<CoordinateFrame::ROBOT, Eigen::Vector3d>::\n\t\t\tLEFT);\ntemplate<> \t\t\t\nconst geometry_msgs::Point \n\t\tBaseDirections<CoordinateFrame::ROBOT, geometry_msgs::Point>::\n\t\t\tRIGHT \n\t\t\t= wrapToMsg<geometry_msgs::Point, Eigen::Vector3d>\n\t\t\t(BaseDirections<CoordinateFrame::ROBOT, Eigen::Vector3d>::\n\t\t\tRIGHT);\n\n\n/*\n * --------------------------------------------------------------------------\n */\n\ntemplate <CoordinateFrame CF, class T>\nclass BaseOrientations {\n   public:\n   \t\t// The first word is corresponding to the main direction,\n   \t\t// the second to the rotation of the tool axis -- the open/close\n   \t\t// direction of the jaws\n   \t\t\n   \t\tstatic const T UP_FORWARD;\n   \t\tstatic const T UP_SIDEWAYS;\n   \t\t\n   \t\tstatic const T DOWN_FORWARD;\n   \t\tstatic const T DOWN_SIDEWAYS;\n   \t\t\n   \t\tstatic const T FORWARD_HORIZONTAL;\n   \t\tstatic const T FORWARD_VERTICAL;\n   \t\t\n   \t\tstatic const T BACKWARD_HORIZONTAL;\n   \t\tstatic const T BACKWARD_VERTICAL;\n   \t\t\n   \t\tstatic const T LEFT_HORIZONTAL;\n   \t\tstatic const T LEFT_VERTICAL;\n   \t\t\n   \t\tstatic const T RIGHT_HORIZONTAL;  \n   \t\tstatic const T RIGHT_VERTICAL; \t\n};\n\n/*\n *\tROBOT\n */\t\t\t\n\t\t\t\n// Eigen::Quaternion<double>\ntemplate<> \nconst Eigen::Quaternion<double> \n\t\tBaseOrientations<CoordinateFrame::ROBOT, Eigen::Quaternion<double>>::\n\t\t\tUP_FORWARD = Eigen::Quaternion<double>(0.0, 0.0, 0.0, 0.0);\n\t\t\t\ntemplate<> \nconst Eigen::Quaternion<double> \n\t\tBaseOrientations<CoordinateFrame::ROBOT, Eigen::Quaternion<double>>::\n\t\t\tUP_SIDEWAYS = Eigen::Quaternion<double>(0.0, 0.0, 0.0, 0.0);\n\n\ntemplate<> \nconst Eigen::Quaternion<double> \n\t\tBaseOrientations<CoordinateFrame::ROBOT, Eigen::Quaternion<double>>::\n\t\t\tDOWN_FORWARD = Eigen::Quaternion<double>(0.0, 1.0, 0.0, 0.0);\n\ntemplate<> \nconst Eigen::Quaternion<double> \n\t\tBaseOrientations<CoordinateFrame::ROBOT, Eigen::Quaternion<double>>::\n\t\t\tDOWN_SIDEWAYS = \n      Eigen::Quaternion<double>(0.0, -0.7071, 0.7071, 0.0);\n\n\ntemplate<> \nconst Eigen::Quaternion<double> \n\t\tBaseOrientations<CoordinateFrame::ROBOT, Eigen::Quaternion<double>>::\n\t\t\tFORWARD_HORIZONTAL = Eigen::Quaternion<double>(0.0, 0.0, 0.0, 0.0);\t\n\t\t\t\t\ntemplate<> \nconst Eigen::Quaternion<double> \n\t\tBaseOrientations<CoordinateFrame::ROBOT, Eigen::Quaternion<double>>::\n\t\t\tFORWARD_VERTICAL = Eigen::Quaternion<double>(0.0, 0.0, 0.0, 0.0);\n\n\ntemplate<> \nconst Eigen::Quaternion<double> \n\t\tBaseOrientations<CoordinateFrame::ROBOT, Eigen::Quaternion<double>>::\n\t\t\tBACKWARD_HORIZONTAL = Eigen::Quaternion<double>(0.0, 0.0, 0.0, 0.0);\t\n\t\t\t\t\ntemplate<> \nconst Eigen::Quaternion<double> \n\t\tBaseOrientations<CoordinateFrame::ROBOT, Eigen::Quaternion<double>>::\n\t\t\tBACKWARD_VERTICAL = Eigen::Quaternion<double>(0.0, 0.0, 0.0, 0.0);\n\n\ntemplate<> \nconst Eigen::Quaternion<double> \n\t\tBaseOrientations<CoordinateFrame::ROBOT, Eigen::Quaternion<double>>::\n\t\t\tRIGHT_HORIZONTAL = \n\t\t\tEigen::Quaternion<double>(0.0, 0.7071, 0.0, -0.7071);\t\n\t\t\t\ntemplate<> \nconst Eigen::Quaternion<double> \n\t\tBaseOrientations<CoordinateFrame::ROBOT, Eigen::Quaternion<double>>::\n\t\t\tRIGHT_VERTICAL = Eigen::Quaternion<double>(0.0, 0.0, 0.0, 0.0);\n\t\t\t\n\ntemplate<> \nconst Eigen::Quaternion<double> \n\t\tBaseOrientations<CoordinateFrame::ROBOT, Eigen::Quaternion<double>>::\n\t\t\tLEFT_HORIZONTAL = Eigen::Quaternion<double>(0.0, 0.0, 0.0, 0.0);\t\n\t\t\t\ntemplate<> \nconst Eigen::Quaternion<double> \n\t\tBaseOrientations<CoordinateFrame::ROBOT, Eigen::Quaternion<double>>::\n\t\t\tLEFT_VERTICAL = Eigen::Quaternion<double>(0.0, 0.0, 0.0, 0.0);\t\n\n\t\n\t\t\t\n\n\n}\n#endif\n", "meta": {"hexsha": "a05974ad897f2764b772c8ce3203c41d2fce3fd3", "size": 8630, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "irob_utils/include/irob_utils/abstract_directions.hpp", "max_stars_repo_name": "ABC-iRobotics/irob-saf", "max_stars_repo_head_hexsha": "27832e1657912f7ad7e9812bb5020d6254137454", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2018-06-07T22:56:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-04T14:56:36.000Z", "max_issues_repo_path": "irob_utils/include/irob_utils/abstract_directions.hpp", "max_issues_repo_name": "ABC-iRobotics/irob-saf", "max_issues_repo_head_hexsha": "27832e1657912f7ad7e9812bb5020d6254137454", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-12-19T10:04:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-19T13:45:25.000Z", "max_forks_repo_path": "irob_utils/include/irob_utils/abstract_directions.hpp", "max_forks_repo_name": "ABC-iRobotics/irob-saf", "max_forks_repo_head_hexsha": "27832e1657912f7ad7e9812bb5020d6254137454", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2018-05-24T23:45:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-07T23:33:43.000Z", "avg_line_length": 28.2026143791, "max_line_length": 77, "alphanum_fraction": 0.7006952491, "num_tokens": 2555, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.48730009155029763}}
{"text": "/**\r\n * \\file topological_search.hpp\r\n * \r\n * This library contains two simple nearest-neighbor search algorithms implemented \r\n * as functor templates. This library contains, in fact, three algorithms. \r\n * \r\n * First, a simple min_dist_linear_search algorithm is provided which is similar to std::min_element\r\n * except that it stores and compares the best distance value associated to the best iterator\r\n * to the current one (it is a simple linear search that avoid recomputation of the distance \r\n * at every iteration, which would be required if std::min_element was used instead).\r\n * \r\n * Second, a linear_neighbor_search algorithm is provided which simply does an exhaustive linear\r\n * search through all the vertices of a graph to find the nearest one to a given point, in a given\r\n * topology (as of topologies in the Boost Graph Library). This algorithms simply wraps the \r\n * min_dist_linear_search with the required distance and comparison function.\r\n * \r\n * Third, a best_only_neighbor_search algorithm is provided which is an approximation to an \r\n * exhaustive linear search by picking a number of random vertices from the graph and performing\r\n * a best only search down the graph to find the \"nearest-neighbor\". This is, of course, not going\r\n * to find the nearest-neighbor, but can significantly cut down on query time if finding the \r\n * nearest neighbor is not a strict requirement in the algorithm.\r\n * \r\n * \\author Sven Mikael Persson <mikael.s.persson@gmail.com>\r\n * \\date February 2011\r\n */\r\n\r\n/*\r\n *    Copyright 2011 Sven Mikael Persson\r\n *\r\n *    THIS SOFTWARE IS DISTRIBUTED UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE v3 (GPLv3).\r\n *\r\n *    This file is part of ReaK.\r\n *\r\n *    ReaK is free software: you can redistribute it and/or modify\r\n *    it under the terms of the GNU General Public License as published by\r\n *    the Free Software Foundation, either version 3 of the License, or\r\n *    (at your option) any later version.\r\n *\r\n *    ReaK 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\r\n *    GNU General Public License for more details.\r\n *\r\n *    You should have received a copy of the GNU General Public License\r\n *    along with ReaK (as LICENSE in the root folder).  \r\n *    If not, see <http://www.gnu.org/licenses/>.\r\n */\r\n\r\n\r\n#ifndef REAK_TOPOLOGICAL_SEARCH_HPP\r\n#define REAK_TOPOLOGICAL_SEARCH_HPP\r\n\r\n#include <boost/bind.hpp>\r\n#include <boost/graph/graph_concepts.hpp>\r\n#include <boost/property_map/property_map.hpp>\r\n#include <boost/graph/adjacency_list.hpp>\r\n#include <boost/graph/topology.hpp>\r\n#include <boost/graph/properties.hpp>\r\n\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n  /**\r\n   * This function template is similar to std::min_element but can be used when the comparison \r\n   * involves computing a derived quantity (a.k.a. distance). This algorithm will search for the \r\n   * the element in the range [first,last) which has the \"smallest\" distance (of course, both the \r\n   * distance metric and comparison can be overriden to perform something other than the canonical\r\n   * Euclidean distance and less-than comparison, which would yield the element with minimum distance).\r\n   * \\tparam DistanceValue The value-type for the distance measures.\r\n   * \\tparam ForwardIterator The forward-iterator type.\r\n   * \\tparam GetDistanceFunction The functor type to compute the distance measure.\r\n   * \\tparam CompareFunction The functor type that can compare two distance measures (strict weak-ordering).\r\n   * \\param first Start of the range in which to search.\r\n   * \\param last One element past the last element in the range in which to search.\r\n   * \\param distance A callable object that returns a DistanceValue for a given element from the ForwardIterator dereferencing.\r\n   * \\param compare A callable object that returns true if the first element is the preferred one (less-than) of the two.\r\n   * \\param inf A DistanceValue which represents infinity (i.e. the very worst value with which to initialize the search).\r\n   * \\return The iterator to the best element in the range (best is defined as the one which would compare favorably to all the elements in the range with respect to the distance metric).\r\n   */\r\n  template <typename DistanceValue,\r\n\t    typename ForwardIterator,\r\n            typename GetDistanceFunction,\r\n\t    typename CompareFunction>\r\n  inline ForwardIterator min_dist_linear_search(ForwardIterator first,\r\n\t\t\t\t\t\tForwardIterator last,\r\n\t\t\t\t\t\tGetDistanceFunction distance,\r\n\t\t\t\t\t\tCompareFunction compare,\r\n\t\t\t\t\t\tDistanceValue inf = std::numeric_limits<DistanceValue>::infinity()) {\r\n    if(first == last) return last;\r\n    DistanceValue d_best = inf;\r\n    ForwardIterator result = last;\r\n    for(; first != last; ++first) {\r\n      DistanceValue d = distance(*first);\r\n      if(compare(d, d_best)) {\r\n\td_best = d;\r\n\tresult = first;\r\n      };\r\n    };\r\n    return result;\r\n  };\r\n  \r\n  \r\n  /**\r\n   * This function template is a specialization of min_dist_linear_search for the default comparison \r\n   * function which is the less-than operator.\r\n   * \\tparam DistanceValue The value-type for the distance measures.\r\n   * \\tparam ForwardIterator The forward-iterator type.\r\n   * \\tparam GetDistanceFunction The functor type to compute the distance measure.\r\n   * \\param first Start of the range in which to search.\r\n   * \\param last One element past the last element in the range in which to search.\r\n   * \\param distance A callable object that returns a DistanceValue for a given element from the ForwardIterator dereferencing.\r\n   * \\param inf A DistanceValue which represents infinity (i.e. the very worst value with which to initialize the search).\r\n   * \\return The iterator to the best element in the range (best is defined as the one which would compare favorably to all the elements in the range with respect to the distance metric).\r\n   */\r\n  template <typename DistanceValue, typename ForwardIterator, typename GetDistanceFunction>\r\n  inline ForwardIterator min_dist_linear_search(ForwardIterator first,\r\n\t\t\t\t\t\tForwardIterator last,\r\n\t\t\t\t\t\tGetDistanceFunction distance,\r\n\t\t\t\t\t\tDistanceValue inf = std::numeric_limits<DistanceValue>::infinity()) {\r\n    return min_dist_linear_search(first,last,distance,std::less<DistanceValue>(),inf);\r\n  };\r\n  \r\n  \r\n  /**\r\n   * This function template is similar to std::min_element but can be used when the comparison \r\n   * involves computing a derived quantity (a.k.a. distance). This algorithm will search for the \r\n   * the elements in the range [first,last) with the \"smallest\" distances (of course, both the \r\n   * distance metric and comparison can be overriden to perform something other than the canonical\r\n   * Euclidean distance and less-than comparison, which would yield the element with minimum distance).\r\n   * This function will fill the output container with a number of nearest-neighbors.\r\n   * \\tparam DistanceValue The value-type for the distance measures.\r\n   * \\tparam ForwardIterator The forward-iterator type.\r\n   * \\tparam OutputContainer The container type which can contain the list of nearest-neighbors (STL like container, with iterators, insert, size, and pop_back).\r\n   * \\tparam GetDistanceFunction The functor type to compute the distance measure.\r\n   * \\tparam CompareFunction The functor type that can compare two distance measures (strict weak-ordering).\r\n   * \\param first Start of the range in which to search.\r\n   * \\param last One element past the last element in the range in which to search.\r\n   * \\param output The container that will have the sorted list of elements with the smallest distance.\r\n   * \\param distance A callable object that returns a DistanceValue for a given element from the ForwardIterator dereferencing.\r\n   * \\param compare A callable object that returns true if the first element is the preferred one (less-than) of the two.\r\n   * \\param max_neighbors The maximum number of elements of smallest distance to output in the sorted list.\r\n   * \\param radius The maximum distance value for which an element qualifies to be part of the output list.\r\n   */\r\n  template <typename DistanceValue,\r\n\t    typename ForwardIterator,\r\n\t    typename OutputContainer,\r\n            typename GetDistanceFunction,\r\n\t    typename CompareFunction>\r\n  inline void min_dist_linear_search(ForwardIterator first,\r\n\t\t\t\t     ForwardIterator last,\r\n\t\t\t\t     OutputContainer& output,\r\n\t\t\t\t     GetDistanceFunction distance,\r\n\t\t\t\t     CompareFunction compare,\r\n\t\t\t\t     unsigned int max_neighbors = 1,\r\n\t\t\t\t     DistanceValue radius = std::numeric_limits<DistanceValue>::infinity()) {\r\n    output.clear();\r\n    if(first == last) return;\r\n    std::vector<DistanceValue> output_dist;\r\n    for(; first != last; ++first) {\r\n      DistanceValue d = distance(*first);\r\n      if(!compare(d, radius)) \r\n\tcontinue;\r\n      typename std::vector<DistanceValue>::iterator it_lo = std::lower_bound(output_dist.begin(),output_dist.end(),d,compare);\r\n      if((it_lo != output_dist.end()) || (output_dist.size() < max_neighbors)) {\r\n\toutput_dist.insert(it_lo, d);\r\n\ttypename OutputContainer::iterator itv = output.begin();\r\n\tfor(typename std::vector<DistanceValue>::iterator it = output_dist.begin(); (itv != output.end()) && (it != it_lo); ++itv,++it) ;\r\n\toutput.insert(itv, *first);\r\n\tif(output.size() > max_neighbors) {\r\n\t  output.pop_back();\r\n\t  output_dist.pop_back();\r\n\t};\r\n      };\r\n    };\r\n  };\r\n  \r\n  /**\r\n   * This function template is similar to std::min_element but can be used when the comparison \r\n   * involves computing a derived quantity (a.k.a. distance). This algorithm will search for the \r\n   * the element in the range [first,last) which has the \"smallest\" distance (of course, both the \r\n   * distance metric and comparison can be overriden to perform something other than the canonical\r\n   * Euclidean distance and less-than comparison, which would yield the element with minimum distance).\r\n   * \\tparam DistanceValue The value-type for the distance measures.\r\n   * \\tparam ForwardIterator The forward-iterator type.\r\n   * \\tparam OutputContainer The container type which can contain the list of nearest-neighbors (STL like container, with iterators, insert, size, and pop_back).\r\n   * \\tparam GetDistanceFunction The functor type to compute the distance measure.\r\n   * \\param first Start of the range in which to search.\r\n   * \\param last One element past the last element in the range in which to search.\r\n   * \\param output The container that will have the sorted list of elements with the smallest distance.\r\n   * \\param distance A callable object that returns a DistanceValue for a given element from the ForwardIterator dereferencing.\r\n   * \\param max_neighbors The maximum number of elements of smallest distance to output in the sorted list.\r\n   * \\param radius The maximum distance value for which an element qualifies to be part of the output list.\r\n   */\r\n  template <typename DistanceValue,\r\n\t    typename ForwardIterator,\r\n\t    typename OutputContainer,\r\n            typename GetDistanceFunction>\r\n  inline void min_dist_linear_search(ForwardIterator first,\r\n\t\t\t\t     ForwardIterator last,\r\n\t\t\t\t     OutputContainer& output,\r\n\t\t\t\t     GetDistanceFunction distance,\r\n\t\t\t\t     unsigned int max_neighbors = 1,\r\n\t\t\t\t     DistanceValue radius = std::numeric_limits<DistanceValue>::infinity()) {\r\n    min_dist_linear_search(first,last,output,distance,std::less<DistanceValue>(),max_neighbors,radius);\r\n  };\r\n\r\n\r\n  /**\r\n   * This functor template performs a linear nearest-neighbor search through a graph by invoquing \r\n   * the distance function of an underlying topology. The call operator will return the vertex\r\n   * of the graph whose position value is closest to a given position value.\r\n   * \\tparam CompareFunction The functor type that can compare two distance measures (strict weak-ordering).\r\n   */\r\n  template <typename CompareFunction = std::less<double> >\r\n  struct linear_neighbor_search {\r\n\r\n    CompareFunction m_compare;\r\n    /**\r\n     * Default constructor.\r\n     * \\param compare The comparison functor for ordering the distances (strict weak ordering).\r\n     */\r\n    linear_neighbor_search(CompareFunction compare = CompareFunction()) : m_compare(compare) { };\r\n\r\n    /**\r\n     * This function template computes the topological distance between a position and the position of a\r\n     * vertex of a graph. This function is used as a helper to the call-operator overloads.\r\n     * \\tparam Vertex The vertex descriptor type.\r\n     * \\tparam Topology The topology type which contains the positions.\r\n     * \\tparam PositionMap The property-map type which can store the position associated with each vertex.\r\n     * \\param p A position in the space.\r\n     * \\param u A vertex which has a position associated to it, via the position property-map.\r\n     * \\param space The topology objects which define the space in which the positions reside.\r\n     * \\param position The property-map which can retrieve the position associated to each vertex.\r\n     */\r\n    template <typename Vertex, typename Topology, typename PositionMap>\r\n    double distance(const typename boost::property_traits<PositionMap>::value_type& p,\r\n                    Vertex u, const Topology& space, PositionMap position) const {\r\n      return space.distance(p, get(position, u));\r\n    };\r\n\r\n    /**\r\n     * This call-operator finds the nearest vertex of a graph, to a given position.\r\n     * \\tparam Graph The graph type which can contain the vertices, should model boost::VertexListGraphConcept.\r\n     * \\tparam Topology The topology type which contains the positions.\r\n     * \\tparam PositionMap The property-map type which can store the position associated with each vertex.\r\n     * \\param p A position in the space, to which the nearest-neighbor is sought.\r\n     * \\param g A graph containing the vertices from which to find the nearest-neighbor.\r\n     * \\param space The topology objects which define the space in which the positions reside.\r\n     * \\param position The property-map which can retrieve the position associated to each vertex.\r\n     */\r\n    template <typename Graph, typename Topology, typename PositionMap>\r\n    typename boost::graph_traits<Graph>::vertex_descriptor operator()(const typename boost::property_traits<PositionMap>::value_type& p, \r\n\t\t\t\t\t\t\t\t      Graph& g, \r\n\t\t\t\t\t\t\t\t      const Topology& space, \r\n\t\t\t\t\t\t\t\t      PositionMap position) {\r\n      typedef typename boost::graph_traits<Graph>::vertex_descriptor Vertex;\r\n      typedef typename boost::graph_traits<Graph>::vertex_iterator VertexIter;\r\n      VertexIter ui,ui_end; tie(ui,ui_end) = vertices(g);\r\n      return *(min_dist_linear_search(ui,ui_end,boost::bind(&linear_neighbor_search::distance<Vertex,Topology,PositionMap>,this,p,_1,space,position),m_compare,std::numeric_limits<double>::infinity()));\r\n    };\r\n    \r\n    /**\r\n     * This call-operator finds the nearest vertices of a graph, to a given position.\r\n     * \\tparam Graph The graph type which can contain the vertices, should \r\n     *         model boost::VertexListGraphConcept.\r\n     * \\tparam Topology The topology type which contains the positions.\r\n     * \\tparam PositionMap The property-map type which can store the position associated \r\n     *         with each vertex.\r\n     * \\tparam OutputContainer The container type which can contain the list of \r\n     *         nearest-neighbors (STL like container, with iterators, insert, size, and pop_back).\r\n     * \\param p A position in the space, to which the nearest-neighbors are sought.\r\n     * \\param output The container for the list of nearest-neighbors, the output of this \r\n     *        function, and will be sorted from the nearest neighbor in increasing order.\r\n     * \\param g A graph containing the vertices from which to find the nearest-neighbors.\r\n     * \\param space The topology objects which define the space in which the positions reside.\r\n     * \\param position The property-map which can retrieve the position associated to each vertex.\r\n     * \\param max_neighbors The maximum number of neighbors to have in the list.\r\n     * \\param radius The minimum distance around the position that a vertex should be in to be \r\n     *        considered a neighbor.\r\n     */\r\n    template <typename Graph, typename Topology, typename PositionMap, typename OutputContainer>\r\n    void operator()(const typename boost::property_traits<PositionMap>::value_type& p, \r\n\t\t    OutputContainer& output, \r\n                    Graph& g, \r\n\t\t    const Topology& space, \r\n\t\t    PositionMap position, \r\n\t\t    unsigned int max_neighbors = 1, \r\n\t\t    double radius = std::numeric_limits<double>::infinity())\r\n    {\r\n      typedef typename boost::graph_traits<Graph>::vertex_descriptor Vertex;\r\n      typedef typename boost::graph_traits<Graph>::vertex_iterator VertexIter;\r\n      VertexIter ui,ui_end; tie(ui,ui_end) = boost::vertices(g);\r\n      min_dist_linear_search(ui,ui_end,output,\r\n                             boost::bind(&linear_neighbor_search::distance<Vertex,Topology,PositionMap>,\r\n                                                          this,p,_1,space,position),\r\n                             m_compare,max_neighbors,radius);\r\n    };\r\n  };\r\n\r\n\r\n  /**\r\n   * This functor template performs a best-only nearest-neighbor search through a tree by invoquing \r\n   * the distance function of an underlying topology. The call operator will return the vertex\r\n   * of the graph whose position value is likely to be closest to a given position value. This \r\n   * algorithm is approximate. It will select a M vertices from the graph from which it starts \r\n   * a best-only search, where M is obtained as M = number_of_vertices / m_vertex_num_divider.\r\n   * \\tparam CompareFunction The functor type that can compare two distance measures (strict weak-ordering).\r\n   */\r\n  template <typename CompareFunction = std::less<double> >\r\n  struct best_only_neighbor_search {\r\n\r\n    unsigned int m_vertex_num_divider;\r\n    CompareFunction m_compare;\r\n    /**\r\n     * Default constructor.\r\n     * \\param aVertexNumDivider The division factor (should be greater than 1) which determines the \r\n     *        fraction of the total number of vertices that is used to stem the best-only searches. \r\n     *        Typical values are between 4 and 10.\r\n     * \\param compare The comparison functor for ordering the distances (strict weak ordering).\r\n     */\r\n    best_only_neighbor_search(unsigned int aVertexNumDivider = 10, \r\n\t\t\t      CompareFunction compare = CompareFunction()) : \r\n                              m_vertex_num_divider(aVertexNumDivider), m_compare(compare) { };\r\n\r\n    /**\r\n     * This function template computes the topological distance between a position and the position of a\r\n     * vertex of a graph. This function is used as a helper to the call-operator overloads.\r\n     * \\tparam Vertex The vertex descriptor type.\r\n     * \\tparam Topology The topology type which contains the positions.\r\n     * \\tparam PositionMap The property-map type which can store the position associated with each vertex.\r\n     * \\param p A position in the space.\r\n     * \\param u A vertex which has a position associated to it, via the position property-map.\r\n     * \\param space The topology objects which define the space in which the positions reside.\r\n     * \\param position The property-map which can retrieve the position associated to each vertex.\r\n     */\r\n    template <typename Vertex, typename Topology, typename PositionMap>\r\n    double distance(const typename boost::property_traits<PositionMap>::value_type& p,\r\n                    Vertex u, const Topology& space, PositionMap position) const {\r\n      return space.distance(p, get(position, u));\r\n    };\r\n\r\n    template <typename Graph, typename Topology, typename PositionMap>\r\n    void search(const typename boost::property_traits<PositionMap>::value_type& p, \r\n\t\ttypename boost::graph_traits<Graph>::vertex_descriptor& u, \r\n\t\tdouble& d_min, Graph& g, const Topology& space, PositionMap position) {\r\n      typedef typename boost::graph_traits<Graph>::vertex_descriptor Vertex;\r\n      typedef typename boost::graph_traits<Graph>::out_edge_iterator EdgeIter;\r\n      d_min = distance(p,u,space,position); \r\n      while(boost::out_degree(u,g)) {\r\n        Vertex v_min = u;\r\n        EdgeIter ei, ei_end;\r\n        for(boost::tie(ei,ei_end) = boost::out_edges(u,g); ei != ei_end; ++ei) {\r\n          Vertex v = boost::target(*ei,g); double d_v = distance(p,v,space,position); \r\n          if(m_compare(d_v,d_min)) {\r\n            d_min = d_v; v_min = v;\r\n          };\r\n        };\r\n        if(v_min == u)\r\n          return;\r\n        u = v_min;\r\n      };\r\n      return;\r\n    };\r\n    \r\n    /**\r\n     * This call-operator finds the nearest vertex of a graph, to a given position.\r\n     * \\tparam Graph The graph type which can contain the vertices, should \r\n     *         model boost::VertexListGraphConcept and boost::IncidenceGraphConcept.\r\n     * \\tparam Topology The topology type which contains the positions.\r\n     * \\tparam PositionMap The property-map type which can store the position associated with each vertex.\r\n     * \\param p A position in the space, to which the nearest-neighbor is sought.\r\n     * \\param g A graph containing the vertices from which to find the nearest-neighbor, \r\n     *        should be tree-structured.\r\n     * \\param space The topology objects which define the space in which the positions reside.\r\n     * \\param position The property-map which can retrieve the position associated to each vertex.\r\n     */\r\n    template <typename Graph, typename Topology, typename PositionMap>\r\n    typename boost::graph_traits<Graph>::vertex_descriptor operator()(const typename boost::property_traits<PositionMap>::value_type& p, \r\n\t\t\t\t\t\t\t\t      Graph& g, const Topology& space, PositionMap position) {\r\n      typedef typename boost::graph_traits<Graph>::vertex_descriptor Vertex;\r\n      if(m_vertex_num_divider == 0)\r\n\tm_vertex_num_divider = 1;\r\n      Vertex u_min = boost::vertex(std::rand() % boost::num_vertices(g),g);\r\n      double d_min;\r\n      search(p,u_min,d_min,g,space,position);\r\n      for(unsigned int i = 0; i < boost::num_vertices(g) / m_vertex_num_divider; ++i) {\r\n        double d_v; Vertex v = boost::vertex(std::rand() % boost::num_vertices(g),g);\r\n        search(p,v,d_v,g,space,position);\r\n        if(m_compare(d_v,d_min)) {\r\n          d_min = d_v; u_min = v;\r\n        };\r\n      };\r\n      return u_min;\r\n    };\r\n    \r\n    \r\n    template <typename Graph, typename Topology, typename PositionMap, typename OutputContainer>\r\n    void search(const typename boost::property_traits<PositionMap>::value_type& p, \r\n\t\ttypename boost::graph_traits<Graph>::vertex_descriptor u, OutputContainer& output, std::vector<double>& output_dist,\r\n\t\tdouble d_min, Graph& g, const Topology& space, PositionMap position, unsigned int max_neighbors, double radius) {\r\n      typedef typename boost::graph_traits<Graph>::vertex_descriptor Vertex;\r\n      typedef typename boost::graph_traits<Graph>::out_edge_iterator EdgeIter;\r\n      if(m_compare(d_min, radius)) {\r\n        std::vector<double>::iterator it_lo = std::lower_bound(output_dist.begin(),output_dist.end(),d_min,m_compare);\r\n        if((it_lo != output_dist.end()) || (output_dist.size() < max_neighbors)) {\r\n \t  output_dist.insert(it_lo, d_min);\r\n\t  typename OutputContainer::iterator itv = output.begin();\r\n\t  for(std::vector<double>::iterator it = output_dist.begin(); (itv != output.end()) && (it != it_lo); ++itv,++it) ;\r\n\t  output.insert(itv, u);\r\n\t  if(output.size() > max_neighbors) {\r\n\t    output.pop_back();\r\n\t    output_dist.pop_back();\r\n\t  };\r\n        };\r\n      };\r\n      EdgeIter ei, ei_end;\r\n      for(boost::tie(ei,ei_end) = boost::out_edges(u,g); ei != ei_end; ++ei) {\r\n\tVertex v = boost::target(*ei,g); double d_v = distance(p,v,space,position);\r\n\tif(m_compare(d_v,d_min))\r\n\t  search(p,v,output,output_dist,d_v,g,space,position,max_neighbors,radius);\r\n      };\r\n    };\r\n    \r\n    /**\r\n     * This call-operator finds the nearest vertices of a graph, to a given position.\r\n     * \\tparam Graph The graph type which can contain the vertices, should \r\n     *         model boost::VertexListGraphConcept and boost::IncidenceGraphConcept.\r\n     * \\tparam Topology The topology type which contains the positions.\r\n     * \\tparam PositionMap The property-map type which can store the position associated \r\n     *         with each vertex.\r\n     * \\tparam OutputContainer The container type which can contain the list of \r\n     *         nearest-neighbors (STL like container, with iterators, insert, size, and pop_back).\r\n     * \\param p A position in the space, to which the nearest-neighbors are sought.\r\n     * \\param output The container for the list of nearest-neighbors, the output of this \r\n     *        function, and will be sorted from the nearest neighbor in increasing order.\r\n     * \\param g A graph containing the vertices from which to find the nearest-neighbors, \r\n     *        should be tree-structured.\r\n     * \\param space The topology objects which define the space in which the positions reside.\r\n     * \\param position The property-map which can retrieve the position associated to each vertex.\r\n     * \\param max_neighbors The maximum number of neighbors to have in the list.\r\n     * \\param radius The minimum distance around the position that a vertex should be in to be \r\n     *        considered a neighbor.\r\n     */\r\n    template <typename Graph, typename Topology, typename PositionMap, typename OutputContainer>\r\n    void operator()(const typename boost::property_traits<PositionMap>::value_type& p, OutputContainer& output, \r\n\t\t    Graph& g, const Topology& space, PositionMap position, unsigned int max_neighbors = 1, double radius = std::numeric_limits<double>::infinity()) {\r\n      typedef typename boost::graph_traits<Graph>::vertex_descriptor Vertex;\r\n      output.clear();\r\n      std::vector<double> output_dist;\r\n      if(m_vertex_num_divider == 0)\r\n\tm_vertex_num_divider = 1;\r\n      for(unsigned int i = 0; i < boost::num_vertices(g) / m_vertex_num_divider; ++i) {\r\n        Vertex v = boost::vertex(std::rand() % boost::num_vertices(g),g);\r\n\tdouble d_v = distance(p,v,space,position);\r\n        search(p,v,output,output_dist,d_v,g,space,position,max_neighbors,radius);\r\n      };\r\n    };\r\n  };\r\n\r\n#endif\r\n", "meta": {"hexsha": "e7e0b142c96cf3ca1a747e991282e775e048a799", "size": 26379, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "NearestNeighbor/topological_search.hpp", "max_stars_repo_name": "jingtangliao/ff", "max_stars_repo_head_hexsha": "d308fe62045e241a4822bb855df97ee087420d9b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 39.0, "max_stars_repo_stars_event_min_datetime": "2015-01-01T07:59:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-01T18:11:46.000Z", "max_issues_repo_path": "NearestNeighbor/topological_search.hpp", "max_issues_repo_name": "jingtangliao/ff", "max_issues_repo_head_hexsha": "d308fe62045e241a4822bb855df97ee087420d9b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-24T09:56:15.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-24T14:45:46.000Z", "max_forks_repo_path": "NearestNeighbor/topological_search.hpp", "max_forks_repo_name": "jingtangliao/ff", "max_forks_repo_head_hexsha": "d308fe62045e241a4822bb855df97ee087420d9b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2015-01-11T15:10:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T20:02:10.000Z", "avg_line_length": 57.2212581345, "max_line_length": 202, "alphanum_fraction": 0.7047272452, "num_tokens": 5607, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.6406358685621719, "lm_q1q2_score": 0.4873000915502975}}
{"text": "/* ========================================================================== */\n/* === Demo/cholmod_simple ================================================== */\n/* ========================================================================== */\n\n/* -----------------------------------------------------------------------------\n * CHOLMOD/Demo Module.  Copyright (C) 2005-2006, Timothy A. Davis\n * -------------------------------------------------------------------------- */\n\n/* Read in a real symmetric or complex Hermitian matrix from stdin in\n * MatrixMarket format, solve Ax=b where b=[1 1 ... 1]', and print the residual.\n * Usage: cholmod_simple < matrixfile\n */\n#include <iostream>\n#include <vector>\n\n#include <Eigen/Sparse>\n#include <Eigen/Dense>\n#include <Eigen/CholmodSupport>\n\n\nEigen::MatrixXd generate_A()\n{\n    Eigen::MatrixXd mat = Eigen::MatrixXd::Identity(10, 10);\n    for(size_t rows = 0; rows < 10; ++rows)\n    {\n        for(size_t cols = 0; cols < 10; ++ cols)\n        {\n            mat(rows, cols) = (double) rand() / RAND_MAX/ 20;\n        }\n    }\n\n    // mat = Eigen::MatrixXd::Identity(10, 10);\n    \n    return mat;\n}\n\nEigen::SparseMatrix<double> convert_to_sparse(Eigen::MatrixXd &mat)\n{\n    Eigen::SparseMatrix<double> sparse_mat = mat.sparseView();\n    return sparse_mat;\n}\n\n\nint main (void)\n{\n    Eigen::MatrixXd A = generate_A();\n\n    Eigen::MatrixXd dense_lhs = A.transpose() * A;\n\n    Eigen::SparseMatrix<double> lhs = convert_to_sparse(dense_lhs);\n    std::cout << \"dense lhs:\" << dense_lhs << std::endl;\n    Eigen::VectorXd rhs = Eigen::VectorXd::Ones(10);\n\n    Eigen::CholmodSupernodalLLT<Eigen::SparseMatrix<double>> solver;\n    solver.compute(lhs);\n    if(solver.info()!=Eigen::Success) {\n    // decomposition failed\n    }\n    Eigen::MatrixXd x = solver.solve(rhs);\n    if(solver.info()!=Eigen::Success) {\n    }\n\n    std::cout << \"x: \" << x << std::endl;\n\n\n\n    return (0) ;\n}", "meta": {"hexsha": "52ee08ae43f28781914aaa91a09d15f296dacbc4", "size": 1908, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "least_squares/CT_reconstruction/ls_common_skills/sparsity/sparse_solver_test.cpp", "max_stars_repo_name": "yimuw/yimu-blog", "max_stars_repo_head_hexsha": "280ab2eca1fa48602d1695d69366842ea40debda", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2021-06-11T05:50:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T02:41:05.000Z", "max_issues_repo_path": "least_squares/CT_reconstruction/ls_common_skills/sparsity/sparse_solver_test.cpp", "max_issues_repo_name": "yimuw/yimu-blog", "max_issues_repo_head_hexsha": "280ab2eca1fa48602d1695d69366842ea40debda", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2020-06-28T13:58:26.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-09T22:30:54.000Z", "max_forks_repo_path": "least_squares/CT_reconstruction/ls_common_skills/sparsity/sparse_solver_test.cpp", "max_forks_repo_name": "yimuw/yimu-blog", "max_forks_repo_head_hexsha": "280ab2eca1fa48602d1695d69366842ea40debda", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2021-07-07T04:00:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T03:42:54.000Z", "avg_line_length": 28.0588235294, "max_line_length": 80, "alphanum_fraction": 0.5057651992, "num_tokens": 436, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.6406358617010351, "lm_q1q2_score": 0.48730008633136934}}
{"text": "\n// BLAS level 2 -- complex numbers\n\n#include <iostream>\n#include <complex>\n#include <boost/numeric/bindings/blas/level1.hpp>\n#include <boost/numeric/bindings/blas/level2.hpp>\n#include <boost/numeric/bindings/ublas/vector.hpp>\n#include <boost/numeric/bindings/ublas/matrix.hpp>\n#include <boost/numeric/bindings/ublas/matrix_proxy.hpp>\n#include <boost/numeric/bindings/conj.hpp>\n#include <boost/numeric/bindings/io.hpp>\n#include <boost/numeric/bindings/noop.hpp>\n#ifdef F_USE_STD_VECTOR\n#include <boost/numeric/bindings/std/vector.hpp> \n#endif \n#include \"utils.h\" \n\nnamespace ublas = boost::numeric::ublas;\nnamespace blas = boost::numeric::bindings::blas;\n\nusing std::cout;\nusing std::endl; \n\ntypedef double real_t;\ntypedef std::complex<real_t> cmplx_t; \n\n#ifndef F_USE_STD_VECTOR\ntypedef ublas::vector<cmplx_t> vct_t;\ntypedef ublas::matrix<cmplx_t, ublas::row_major> m_t;\n#else\ntypedef ublas::vector<cmplx_t, std::vector<cmplx_t> > vct_t;\ntypedef ublas::matrix<cmplx_t, ublas::column_major, std::vector<cmplx_t> > m_t;\n#endif \n\nint main() {\n\n  cout << endl; \n\n  vct_t vx (2);\n  blas::set( 1, vx );\n  std::cout << \"vx \" << bindings::noop( vx ) << std::endl;\n  vct_t vy (4); // vector size can be larger \n                // than corresponding matrix size \n  blas::set( 0, vy );\n  std::cout << \"vy \" << bindings::noop( vy ) << std::endl;\n  cout << endl; \n\n  m_t m (3, 2);\n  init_m (m, kpp (1)); \n  print_m (m, \"m\"); \n  cout << endl; \n\n  // vy = m vx\n  blas::gemv ( 1.0, m, vx, 0.0, vy);\n  std::cout << \"m vx \" << bindings::noop( vy ) << std::endl;\n  blas::gemv ( 1.0, m, vx, 0.0, vy);\n  std::cout << \"m vx \" << bindings::noop( vy ) << std::endl;\n  cout << endl; \n\n  m (0, 0) = cmplx_t (0., 1.);\n  m (0, 1) = cmplx_t (0., 2.);\n  m (1, 0) = cmplx_t (0., 3.);\n  m (1, 1) = cmplx_t (0., 4.);\n  m (2, 0) = cmplx_t (0., 5.);\n  m (2, 1) = cmplx_t (0., 6.);\n  print_m (m, \"m\"); \n  cout << endl; \n\n  // vy = m vx\n  blas::gemv ( 1.0, m, vx, 0.0, vy);\n  std::cout << \"m vx \" << bindings::noop( vy ) << std::endl;\n  blas::gemv ( 1.0, m, vx, 0.0, vy);\n  std::cout << \"m vx \" << bindings::noop( vy ) << std::endl;\n  cout << endl; \n\n  m (0, 0) = cmplx_t (-1., 1.);\n  m (0, 1) = cmplx_t (-2., 2.);\n  m (1, 0) = cmplx_t (-3., 3.);\n  m (1, 1) = cmplx_t (-4., 4.);\n  m (2, 0) = cmplx_t (-5., 5.);\n  m (2, 1) = cmplx_t (-6., 6.);\n  print_m (m, \"m\"); \n  cout << endl; \n\n  // vy = m vx\n  blas::gemv ( 1.0, m, vx, 0.0, vy);\n  std::cout << \"m vx \" << bindings::noop( vy ) << std::endl;\n  blas::gemv ( 1.0, m, vx, 0, vy);\n  std::cout << \"m vx \" << bindings::noop( vy ) << std::endl;\n  cout << endl; \n\n  blas::set ( 1, vx );\n  std::cout << \"vx \" << bindings::noop( vx ) << std::endl;\n\n  // vy = m vx\n  blas::gemv ( 1.0, m, vx, 0.0, vy);\n  std::cout << \"m vx \" << bindings::noop( vy ) << std::endl;\n  blas::gemv ( 1.0, m, vx, 0.0, vy);\n  std::cout << \"m vx \" << bindings::noop( vy ) << std::endl;\n  cout << endl; \n\n  blas::set ( cmplx_t (1, 1), vx );\n  std::cout << \"vx \" << bindings::noop( vx ) << std::endl;\n\n  // vy = m vx\n  blas::gemv ( 1.0, m, vx, 0.0, vy);\n  std::cout << \"m vx \" << bindings::noop( vy ) << std::endl;\n  blas::gemv ( 1.0, m, vx, 0.0, vy);\n  std::cout << \"m vx \" << bindings::noop( vy ) << std::endl;\n  cout << endl; \n\n  // vx = m^H vy\n  blas::set ( cmplx_t (-1,-1), vy );\n  std::cout << \"vy \" << bindings::noop( vy ) << std::endl;\n  blas::gemv ( 1.0, bindings::conj(m), vy, 0.0, vx);\n  std::cout << \"m^H vy \" << bindings::noop( vx ) << std::endl;\n  cout << endl; \n\n  m_t mx (2, 2); \n  m_t my (3, 2); \n\n\n  ublas::matrix_column<m_t> mxc0 (mx, 0), \n                            mxc1 (mx, 1); \n  ublas::matrix_column<m_t> myc0 (my, 0),\n                            myc1 (my, 1); \n\n  blas::set ( cmplx_t (1, 0), mxc0 );\n  blas::set ( cmplx_t (0, 0), mxc1 );\n  blas::set ( cmplx_t (0, 0), myc0 );\n  blas::set ( cmplx_t (0, 0), myc1 );\n\n  print_m (mx, \"mx\");\n  cout << endl; \n  print_m (my, \"my\");\n  cout << endl; \n\n  // my[.,0] = m mx[.,0] \n  blas::gemv ( 1.0, m, mxc0, 0.0, myc0); \n  print_m (my, \"m mx[.,0]\");\n\n  cout << endl;\n\n}\n", "meta": {"hexsha": "daab4b47128fac6ef09699125f7097d4012b3ba8", "size": 4016, "ext": "cc", "lang": "C++", "max_stars_repo_path": "externals/numeric_bindings/libs/numeric/bindings/atlas/ublas_cmatr2.cc", "max_stars_repo_name": "ljktest/siconos", "max_stars_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 137.0, "max_stars_repo_stars_event_min_datetime": "2015-06-16T15:55:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T06:01:59.000Z", "max_issues_repo_path": "externals/numeric_bindings/libs/numeric/bindings/atlas/ublas_cmatr2.cc", "max_issues_repo_name": "ljktest/siconos", "max_issues_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 381.0, "max_issues_repo_issues_event_min_datetime": "2015-09-22T15:31:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-14T09:05:23.000Z", "max_forks_repo_path": "externals/numeric_bindings/libs/numeric/bindings/atlas/ublas_cmatr2.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": 27.5068493151, "max_line_length": 79, "alphanum_fraction": 0.5418326693, "num_tokens": 1586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255928, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.4873000845983123}}
{"text": "/*\nCopyright (c) 2020 ETH Zurich\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\nAuthor: Katrin Lasinger\n*/\n\n#define _USE_MATH_DEFINES\n\n#include <numeric>\n#include <vector>\n#include <algorithm>\n#include <omp.h>\n#include \"mex.h\"\n#include <math.h>\n\n#include <Eigen/Dense>\nusing namespace Eigen;\n\n/// matlab calling\nvoid proj2d ( int nlhs, mxArray *plhs[],\n                int nrhs, const mxArray *prhs[])\n{\n\n  typedef double Scalar;\n\n  Scalar *part = (Scalar*)mxGetPr(prhs[0]);\n \n  Scalar *P_vec = (Scalar*)mxGetPr(prhs[1]);\n\n  Matrix<Scalar, 3, 4> P;\n\n  for(int j=0;j<4;j++)\n    for (int i=0;i<3;i++)\n\t\tP(i,j) = P_vec[i+j*3];\n\n  const mwSize* dims = mxGetDimensions(prhs[0]);\n  size_t numpart = dims[1]; // list of points\n  size_t partDim = dims[0]; // featureDim\n\n  plhs[0] = mxCreateDoubleMatrix(2,numpart, mxREAL);\n  Scalar* part2d = (Scalar*)mxGetPr(plhs[0]);\n\n\n  plhs[1] = mxCreateDoubleMatrix(3,numpart, mxREAL);\n  Scalar* xhom = (Scalar*)mxGetPr(plhs[1]);\n \n#pragma omp parallel for //schedule (static)\n  for (long long i = 0; i < numpart; i++)\n  {\n\n\tVector4d pt;\n\tpt << part[i*3],part[i*3+1], part[i*3+2], 1;\n\n\n\tVector3d pt2d_hom;\n\tpt2d_hom = P * pt;\n\n\txhom[i*3] =pt2d_hom(0);\n\txhom[i*3+1] = pt2d_hom(1);\n\txhom[i*3+2] = pt2d_hom(2);\n\tpart2d[i*2] = pt2d_hom(0) / pt2d_hom(2);\n\tpart2d[i*2+1] = pt2d_hom(1) / pt2d_hom(2);\n\n\n  }\n\n}", "meta": {"hexsha": "dc58aa194d13003b983dacf67e5be0339e097e35", "size": 2311, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Source/Proj2d.cpp", "max_stars_repo_name": "lasinger/3d-fluid-flow", "max_stars_repo_head_hexsha": "f8c22ad33db45cfcd3716f72d3f115a94e766285", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-09-07T13:18:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-17T11:15:59.000Z", "max_issues_repo_path": "src/Source/Proj2d.cpp", "max_issues_repo_name": "lasinger/3d-fluid-flow", "max_issues_repo_head_hexsha": "f8c22ad33db45cfcd3716f72d3f115a94e766285", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Source/Proj2d.cpp", "max_forks_repo_name": "lasinger/3d-fluid-flow", "max_forks_repo_head_hexsha": "f8c22ad33db45cfcd3716f72d3f115a94e766285", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-09-07T13:24:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-17T11:16:00.000Z", "avg_line_length": 27.1882352941, "max_line_length": 78, "alphanum_fraction": 0.7087840762, "num_tokens": 682, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.487300081112441}}
{"text": "#ifndef DatabaseChart_hpp\n#define DatabaseChart_hpp\n\n#include <QOpenGLWidget>\n#include <QSharedPointer>\n#include <QVector>\n#include <QSettings>\n#include <QtCharts>\n#include <armadillo>\n#include <functional>\n#include <UMF/ComputeHistogram.hpp>\n#include <UMF/CurveNormalization.hpp>\n#include <UMF/Evaluate1D.hpp>\n#include <AA/FeaturesExtractor.hpp>\n\nnamespace GUI{\n\tclass DatabaseLine : public QLineSeries {\n\t\t\n\t\tQ_OBJECT\n\t\t\n\t\tQ_PROPERTY(double Minimum MEMBER m_Minimum READ getMinimum WRITE setMinimum NOTIFY parameterChanged)\n\t\tQ_PROPERTY(double Maximum MEMBER m_Maximum READ getMaximum WRITE setMaximum NOTIFY parameterChanged)\n\t\tQ_PROPERTY(int NumPoints MEMBER m_NumPoints READ getNumPoints WRITE setNumPoints NOTIFY parameterChanged)\n\t\tQ_PROPERTY(CurveType Type MEMBER m_Type READ getType WRITE setType NOTIFY parameterChanged)\n\t\tQ_PROPERTY(QVector<double> Coefficients MEMBER m_Coefficients READ getCoefficients WRITE setCoefficients NOTIFY parameterChanged)\n\t\tQ_PROPERTY(QList<QVector<double>> Features MEMBER m_Features READ getFeatures WRITE setFeatures NOTIFY featuresChanged)\n\t\t\n\tpublic:\n\t\tenum CurveType {\n\t\t\tGaussian,\n\t\t\tGaussianExp\n\t\t};\n\t\tQ_ENUM(CurveType);\n\t\t\n\tprivate:\n\t\tdouble m_Minimum = 0.0;\n\t\tdouble m_Maximum = 1.0;\n\t\tint m_NumPoints = 100;\n\t\tCurveType m_Type = GaussianExp;\n\t\tQVector<double> m_Coefficients = {5.0, 0.3, 0.1, 0.1};\n\t\tQList<QVector<double>> m_Features;\n\t\t\n\tpublic:\n\t\tDatabaseLine(QObject* parente = Q_NULLPTR);\n\t\t\n\t\tdouble getMinimum() const {return m_Minimum;};\n\t\tdouble getMaximum() const {return m_Maximum;};\n\t\tint getNumPoints() const {return m_NumPoints;};\n\t\tCurveType getType() const {return m_Type;};\n\t\tQVector<double> getCoefficients() const {return m_Coefficients;};\n\t\tQList<QVector<double>> getFeatures() const {return m_Features;};\n\t\t\n\t\tvoid setMinimum(double min){m_Minimum=min; update(); Q_EMIT parameterChanged();};\n\t\tvoid setMaximum(double max){m_Maximum=max; update(); Q_EMIT parameterChanged();};\n\t\tvoid setNumPoints(int n_points){m_NumPoints=n_points; update(); Q_EMIT parameterChanged();};\n\t\tvoid setType(CurveType type){m_Type=type; update(); Q_EMIT parameterChanged();};\n\t\tvoid setCoefficients(QVector<double> coeff){m_Coefficients=coeff; update(); Q_EMIT parameterChanged();};\n\t\tvoid setFeatures(QList<QVector<double>> features){m_Features=features; Q_EMIT featuresChanged();};\n\t\tvoid addFeatures(QVector<double> features){m_Features << features; Q_EMIT featuresChanged();};\n\t\t\n\t\tstatic QVector<double> linspace(double min, double max, int points);\n\t\tstatic QVector<double> regspace(double min, double max, double step);\n\t\t\n\t\tstatic QColor genNewColor();\n\t\t\n\tQ_SIGNALS:\n\t\tQ_SIGNAL void parameterChanged();\n\t\tQ_SIGNAL void featuresChanged();\n\t\t\n\t\tpublic Q_SLOTS:\n\t\tQ_SLOT void update();\n\t\t\n\t};\n\t\n\tclass QHistogramSeries : public QAreaSeries {\n\t\t\n\t\tQ_OBJECT\n\t\t\n\t\tQ_PROPERTY(QVector<double> X MEMBER m_X READ getX WRITE setX NOTIFY XChanged)\n\t\tQ_PROPERTY(QVector<double> Y MEMBER m_Y READ getY WRITE setY NOTIFY YChanged)\n\t\t\n\tprivate:\n\t\tQVector<double> m_X, m_Y;\n\t\t\n\t\tvoid tryBuildSeries();\n\t\t\n\tpublic:\n\t\tQHistogramSeries(QObject *parent = Q_NULLPTR):QAreaSeries(parent){};\n\t\tQHistogramSeries(QVector<double> X, QVector<double> Y);\n\t\t\n\t\tQVector<double> getX() const {return m_X;};\n\t\tQVector<double> getY() const {return m_Y;};\n\t\t\n\t\tvoid setX(QVector<double> X){m_X=X; tryBuildSeries(); Q_EMIT XChanged();};\n\t\tvoid setY(QVector<double> Y){m_Y=Y; tryBuildSeries(); Q_EMIT YChanged();};\n\t\t\n\tQ_SIGNALS:\n\t\tQ_SIGNAL void XChanged();\n\t\tQ_SIGNAL void YChanged();\n\t};\n\t\n\tclass InteractiveChart : public QtCharts::QChartView {\n\t\t\n\t\tQ_OBJECT\n\t\t\n\t\t/** The zoom factor; 1/zoomFactor is used to zoom out. */\n\t\tconst double zoomFactor = 1.2;\n\t\t\n\t\t/** The scrolling speed. */\n\t\tconst double moveFactor = 0.3;\n\t\t\n\t\t/** Reimplementation of the QChartView::keyPressEvent to handle keyboard interaction (zoom and scroll). */\n\t\tvoid keyPressEvent(QKeyEvent *event);\n\t\t\n\tpublic:\n\t\tInteractiveChart(QWidget* parent = Q_NULLPTR);\n\t};\n\t\n\tclass DatabaseChart : public InteractiveChart {\n\t\t\n\t\tQ_OBJECT\n\t\t\n\tpublic:\n\t\t/** Constructor with initial settings. */\n\t\tDatabaseChart(QWidget* parent = Q_NULLPTR);\n\t\t\n\t\tvoid updateViewWith(QAbstractSeries*);\n\t\t\n\t\tpublic Q_SLOTS:\n\t\t/** Compute and plot the histogram in the chart.\n\t\t This function is an overload.\n\t\t @param[in] x Bars positions.\n\t\t @param[in] y Bars height.*/\n\t\tQ_SLOT void plotHistogram(QVector<double> X,\n\t\t\t\t\t\t\t\t  QVector<double> Y,\n\t\t\t\t\t\t\t\t  QString Name = \"\",\n\t\t\t\t\t\t\t\t  QColor Color = QColor::fromRgb(-1, -1, -1));\n\t\t\n\t\t/** Plot a gaussian curve, given its coefficients.\n\t\t This function is an overload. The gaussian function is\n\t\t of the form\n\t\t \\f[\n\t\t f(x) = c_1 e^{\\frac{(x-c_1)^2}{2c_3^2}}\n\t\t \\f]\n\t\t where \\f$ c_1 \\f$, \\f$ c_2 \\f$ and \\f$ c_3 \\f$ are the parameters.\n\t\t @param[in] coefficients Coefficients of the gaussian function.\n\t\t @param[in] domain The set of points which the function must be evalutated on.\n\t\t */\n\t\tQ_SLOT QLineSeries* plotCurve(QVector<double> X,\n\t\t\t\t\t\t\t\t\t  QVector<double> Y,\n\t\t\t\t\t\t\t\t\t  QString Name = \"\",\n\t\t\t\t\t\t\t\t\t  QColor Color = QColor::fromRgb(-1, -1, -1));\n\t\t\n\t\tQ_SLOT void addSpot(double);\n\t\t\n\t\tQ_SLOT void plotParametricCurve(QVector<double> Parameters,\n\t\t\t\t\t\t\t\t\t\tdouble min,\n\t\t\t\t\t\t\t\t\t\tdouble max,\n\t\t\t\t\t\t\t\t\t\tDatabaseLine::CurveType type,\n\t\t\t\t\t\t\t\t\t\tQString Name = \"\",\n\t\t\t\t\t\t\t\t\t\tQColor Color = QColor::fromRgb(-1, -1, -1));\n\t\t\n\tQ_SIGNALS:\n\t\tQ_SIGNAL void raise(QString);\n\t};\n\t\n\t/** Class to show audio signals in time domain. */\n\tclass ChartRecWidget : public InteractiveChart {\n\t\t\n\t\tQ_OBJECT\n\t\t\n\tpublic:\n\t\t/** Constructs an instance and customizes its appearance. */\n\t\tChartRecWidget(QWidget* parent = Q_NULLPTR);\n\t\t\n\t\t/** Convert a series index to the corresponding x value.\n\t\t By default the function only casts the input value to double.\n\t\t @sa addSeries, valueToYAxis\n\t\t */\n\t\tstd::function<double(int)> indexToXAxis = [](int i){return double(i);};\n\t\t\n\t\t/** Convert a series value to the corresponding y value.\n\t\t By default the function only casts the input value to double.\n\t\t @sa addSeries, indexToXAxis\n\t\t */\n\t\tstd::function<double(double)> valueToYAxis = [](double y){return y;};\n\t\t\n\t\tpublic Q_SLOTS:\n\t\t\n\t\t/** Add a series to the chart and adjust axes accordingly.\n\t\t The data given as input contains only y-values, but not their corresponding\n\t\t position on the x-axis; to insert a new series in the chart the position of a value\n\t\t in the given array is interpreted as x, and the method indexConversion is used to rescale\n\t\t the position. Subclasses can override indexConversion to convert an array index to\n\t\t the real x position of the value.\n\t\t To adjust the axes the function updateAxes is called, and it can be overridden by\n\t\t subclasses to manage different behaviour.\n\t\t @sa updateAxes, display, indexConversion\n\t\t */\n\t\tQ_SLOT void addSeries(QVector<double> newData);\n\t\t\n\t\tQ_SLOT void addPoints(QVector<int> newData);\n\t\t\n\tQ_SIGNALS:\n\t\tQ_SIGNAL void raise(QString errorMsg);\n\t};\n}\n\nQDataStream& operator<<(QDataStream&, const GUI::DatabaseLine::CurveType&);\nQDataStream& operator<<(QDataStream&, const GUI::DatabaseLine&);\n\nQDataStream& operator>>(QDataStream&, GUI::DatabaseLine::CurveType&);\nQDataStream& operator>>(QDataStream&, GUI::DatabaseLine&);\n\n#endif /* DatabaseChart_hpp */\n", "meta": {"hexsha": "b9da1171c72fdd36e37b95f3bd5549260506ce7e", "size": 7224, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Headers/GUI/DatabaseChart.hpp", "max_stars_repo_name": "DottD/audioRec", "max_stars_repo_head_hexsha": "74c316974000fc7c9048f076de01c40ede85836c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Headers/GUI/DatabaseChart.hpp", "max_issues_repo_name": "DottD/audioRec", "max_issues_repo_head_hexsha": "74c316974000fc7c9048f076de01c40ede85836c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Headers/GUI/DatabaseChart.hpp", "max_forks_repo_name": "DottD/audioRec", "max_forks_repo_head_hexsha": "74c316974000fc7c9048f076de01c40ede85836c", "max_forks_repo_licenses": ["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.4444444444, "max_line_length": 131, "alphanum_fraction": 0.7209302326, "num_tokens": 1814, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.48730008111244094}}
{"text": "// numerical.hpp\r\n/*\r\n *  Copyright (c) 2015, 2020 Leigh Johnston.\r\n *\r\n *  All rights reserved.\r\n *\r\n *  Redistribution and use in source and binary forms, with or without\r\n *  modification, are permitted provided that the following conditions are\r\n *  met:\r\n *\r\n *     * Redistributions of source code must retain the above copyright\r\n *       notice, this list of conditions and the following disclaimer.\r\n *\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 *     * Neither the name of Leigh Johnston nor the names of any\r\n *       other contributors to this software may be used to endorse or\r\n *       promote products derived from this software without specific prior\r\n *       written permission.\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 TO,\r\n *  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\r\n *  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\r\n *  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\r\n *  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\r\n *  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\r\n#pragma once\r\n\r\n#include <neolib/neolib.hpp>\r\n#include <type_traits>\r\n#include <stdexcept>\r\n#include <array>\r\n#include <algorithm>\r\n#include <ostream>\r\n#include <optional>\r\n#include <boost/math/constants/constants.hpp>\r\n#include <neolib/core/vecarray.hpp>\r\n#include <neolib/core/swizzle.hpp>\r\n#include <neolib/core/simd.hpp>\r\n\r\nnamespace neolib\r\n{ \r\n    namespace math\r\n    {\r\n        #define USE_AVX\r\n        #define USE_EMM\r\n\r\n        using namespace boost::math::constants;\r\n\r\n        typedef double scalar;\r\n        typedef double angle;\r\n\r\n        namespace constants\r\n        {\r\n            template <typename T>\r\n            constexpr T zero = static_cast<T>(0.0);\r\n            template <typename T>\r\n            constexpr T one = static_cast<T>(1.0);\r\n            template <typename T>\r\n            constexpr T two = static_cast<T>(2.0);\r\n        }\r\n\r\n        template <typename T, typename SFINAE = std::enable_if_t<std::is_scalar_v<T>, sfinae>>\r\n        inline T lerp(T aX1, T aX2, double aAmount)\r\n        {\r\n            double x1 = aX1;\r\n            double x2 = aX2;\r\n            return static_cast<T>((x2 - x1) * aAmount + x1);\r\n        }\r\n\r\n        inline angle to_rad(angle aDegrees)\r\n        {\r\n            return aDegrees / 180.0 * pi<angle>();\r\n        }\r\n\r\n        inline angle to_deg(angle aRadians)\r\n        {\r\n            return aRadians * 180.0 / pi<angle>();\r\n        }\r\n\r\n        struct column_vector {};\r\n        struct row_vector {};\r\n\r\n        template <typename T, uint32_t _Size, typename Type = column_vector>\r\n        class basic_vector\r\n        {\r\n            typedef basic_vector<T, _Size, Type> self_type;\r\n        public:\r\n            typedef self_type abstract_type; // todo: abstract base; std::array?\r\n        public:\r\n            typedef Type type;\r\n        public:\r\n            typedef T value_type;\r\n            typedef basic_vector<value_type, _Size, Type> vector_type;\r\n            typedef uint32_t size_type;\r\n            typedef std::array<value_type, _Size> array_type;\r\n            typedef typename array_type::const_iterator const_iterator;\r\n            typedef typename array_type::iterator iterator;\r\n        public:\r\n            template <uint32_t Size2> struct rebind { typedef basic_vector<T, Size2, Type> type; };\r\n        public:\r\n            static constexpr uint32_t Size = _Size;\r\n        public:\r\n            basic_vector() : v{} {}\r\n            template <typename SFINAE = int>\r\n            explicit basic_vector(value_type x, typename std::enable_if_t<Size == 1, SFINAE> = 0) : v{ {x} } {}\r\n            template <typename SFINAE = int>\r\n            explicit basic_vector(value_type x, value_type y, typename std::enable_if_t<Size == 2, SFINAE> = 0) : v{ {x, y} } {}\r\n            template <typename SFINAE = int>\r\n            explicit basic_vector(value_type x, value_type y, value_type z, typename std::enable_if_t<Size == 3, SFINAE> = 0) : v{ {x, y, z} } {}\r\n            template <typename SFINAE = int>\r\n            explicit basic_vector(value_type x, value_type y, value_type z, value_type w, typename std::enable_if_t<Size == 4, SFINAE> = 0) : v{ { x, y, z, w } } {}\r\n            template <typename... Arguments>\r\n            explicit basic_vector(const value_type& value, Arguments&&... aArguments) : v{ {value, std::forward<Arguments>(aArguments)...} } {}\r\n            template <typename... Arguments>\r\n            explicit basic_vector(value_type&& value, Arguments&&... aArguments) : v{ {std::move(value), std::forward<Arguments>(aArguments)...} } {}\r\n            explicit basic_vector(const array_type& v) : v{ v } {}\r\n            basic_vector(std::initializer_list<value_type> values) { if (values.size() > Size) throw std::out_of_range(\"neolib::basic_vector: initializer list too big\"); std::uninitialized_copy(values.begin(), values.end(), v.begin()); std::uninitialized_fill(v.begin() + (values.end() - values.begin()), v.end(), value_type{}); }\r\n            template <typename V, typename A, uint32_t S, uint32_t... Indexes>\r\n            basic_vector(const swizzle<V, A, S, Indexes...>& aSwizzle) : self_type{ ~aSwizzle } {}\r\n            basic_vector(const self_type& other) : v{ other.v } {}\r\n            basic_vector(self_type&& other) : v{ std::move(other.v) } {}\r\n            template <typename T2>\r\n            basic_vector(const basic_vector<T2, Size, Type>& other) { std::transform(other.begin(), other.end(), v.begin(), [](T2 source) { return static_cast<value_type>(source); }); }\r\n            template <typename T2, uint32_t Size2, typename SFINAE = int>\r\n            basic_vector(const basic_vector<T2, Size2, Type>& other, typename std::enable_if_t<Size2 < Size, SFINAE> = 0) : v{} { std::transform(other.begin(), other.end(), v.begin(), [](T2 source) { return static_cast<value_type>(source); }); }\r\n            self_type& operator=(const self_type& other) { v = other.v; return *this; }\r\n            self_type& operator=(self_type&& other) { v = std::move(other.v); return *this; }\r\n            self_type& operator=(std::initializer_list<value_type> values) { if (values.size() > Size) throw std::out_of_range(\"neolib::basic_vector: initializer list too big\"); std::copy(values.begin(), values.end(), v.begin()); std::fill(v.begin() + (values.end() - values.begin()), v.end(), value_type{}); return *this; }\r\n        public:\r\n            static uint32_t size() { return Size; }\r\n            value_type operator[](uint32_t aIndex) const { return v[aIndex]; }\r\n            value_type& operator[](uint32_t aIndex) { return v[aIndex]; }\r\n            const_iterator begin() const { return v.begin(); }\r\n            const_iterator end() const { return v.end(); }\r\n            iterator begin() { return v.begin(); }\r\n            iterator end() { return v.end(); }\r\n            operator const array_type&() const { return v; }\r\n        public:\r\n            template <typename T2>\r\n            basic_vector<T2, Size, Type> as() const\r\n            {\r\n                return basic_vector<T2, Size, Type>{ *this };\r\n            }\r\n        public:\r\n            bool operator==(const self_type& right) const { return v == right.v; }\r\n            bool operator!=(const self_type& right) const { return v != right.v; }\r\n            self_type& operator+=(value_type value) { for (uint32_t index = 0; index < Size; ++index) v[index] += value; return *this; }\r\n            self_type& operator-=(value_type value) { for (uint32_t index = 0; index < Size; ++index) v[index] -= value; return *this; }\r\n            self_type& operator*=(value_type value) { for (uint32_t index = 0; index < Size; ++index) v[index] *= value; return *this; }\r\n            self_type& operator/=(value_type value) { for (uint32_t index = 0; index < Size; ++index) v[index] /= value; return *this; }\r\n            self_type& operator+=(const self_type& right) { for (uint32_t index = 0; index < Size; ++index) v[index] += right.v[index]; return *this; }\r\n            self_type& operator-=(const self_type& right) { for (uint32_t index = 0; index < Size; ++index) v[index] -= right.v[index]; return *this; }\r\n            self_type& operator*=(const self_type& right) { for (uint32_t index = 0; index < Size; ++index) v[index] *= right.v[index]; return *this; }\r\n            self_type& operator/=(const self_type& right) { for (uint32_t index = 0; index < Size; ++index) v[index] /= right.v[index]; return *this; }\r\n            self_type operator-() const { self_type result; for (uint32_t index = 0; index < Size; ++index) result.v[index] = -v[index]; return result; }\r\n            self_type scale(const self_type& right) const { self_type result; for (uint32_t index = 0; index < Size; ++index) result[index] = v[index] * right[index]; return result; }\r\n            value_type magnitude() const { value_type ss = constants::zero<value_type>; for (uint32_t index = 0; index < Size; ++index) ss += (v[index] * v[index]); return std::sqrt(ss); }\r\n            self_type normalized() const { self_type result; value_type im = constants::one<value_type> / magnitude(); for (uint32_t index = 0; index < Size; ++index) result.v[index] = v[index] * im; return result; }\r\n            self_type min(const self_type& right) const { self_type result; for (uint32_t index = 0; index < Size; ++index) result[index] = std::min(v[index], right.v[index]); return result; }\r\n            self_type max(const self_type& right) const { self_type result; for (uint32_t index = 0; index < Size; ++index) result[index] = std::max(v[index], right.v[index]); return result; }\r\n            value_type min() const { value_type result = v[0]; for (uint32_t index = 1; index < Size; ++index) result = std::min(v[index], result); return result; }\r\n            self_type ceil() const { self_type result; for (uint32_t index = 0; index < Size; ++index) result[index] = std::ceil(v[index]); return result; }\r\n            self_type floor() const { self_type result; for (uint32_t index = 0; index < Size; ++index) result[index] = std::floor(v[index]); return result; }\r\n            self_type round() const { self_type result; for (uint32_t index = 0; index < Size; ++index) result[index] = std::round(v[index]); return result; }\r\n            value_type distance(const self_type& right) const { value_type total = 0; for (uint32_t index = 0; index < Size; ++index) total += ((v[index] - right.v[index]) * (v[index] - right.v[index])); return std::sqrt(total); }\r\n            value_type dot(const self_type& right) const\r\n            {\r\n                value_type result = constants::zero<value_type>;\r\n                for (uint32_t index = 0; index < Size; ++index)\r\n                    result += (v[index] * right[index]);\r\n                return result;\r\n            }\r\n            template <typename SFINAE = self_type>\r\n            std::enable_if_t<Size == 3, SFINAE> cross(const self_type& right) const\r\n            {\r\n                return self_type{ \r\n                    y * right.z - z * right.y, \r\n                    z * right.x - x * right.z, \r\n                    x * right.y - y * right.x };\r\n            }\r\n            self_type hadamard_product(const self_type& right) const\r\n            {\r\n                self_type result = *this;\r\n                result *= right;\r\n                return result;\r\n            }\r\n        public:\r\n            union\r\n            {\r\n                array_type v;\r\n                struct // todo: alignment, padding?\r\n                {\r\n                    value_type x;\r\n                    value_type y;\r\n                    value_type z;\r\n                };\r\n                swizzle<vector_type, array_type, 2, 0, 0> xx;\r\n                swizzle<vector_type, array_type, 2, 0, 1> xy;\r\n                swizzle<vector_type, array_type, 2, 0, 2> xz;\r\n                swizzle<vector_type, array_type, 2, 1, 0> yx;\r\n                swizzle<vector_type, array_type, 2, 1, 1> yy;\r\n                swizzle<vector_type, array_type, 2, 1, 2> yz;\r\n                swizzle<vector_type, array_type, 2, 2, 0> zx;\r\n                swizzle<vector_type, array_type, 2, 2, 1> zy;\r\n                swizzle<vector_type, array_type, 2, 2, 2> zz;\r\n                swizzle<vector_type, array_type, 3, 0, 0, 0> xxx;\r\n                swizzle<vector_type, array_type, 3, 0, 0, 1> xxy;\r\n                swizzle<vector_type, array_type, 3, 0, 0, 2> xxz;\r\n                swizzle<vector_type, array_type, 3, 0, 1, 0> xyx;\r\n                swizzle<vector_type, array_type, 3, 0, 1, 1> xyy;\r\n                swizzle<vector_type, array_type, 3, 0, 1, 2> xyz;\r\n                swizzle<vector_type, array_type, 3, 1, 0, 0> yxx;\r\n                swizzle<vector_type, array_type, 3, 1, 0, 1> yxy;\r\n                swizzle<vector_type, array_type, 3, 1, 0, 2> yxz;\r\n                swizzle<vector_type, array_type, 3, 1, 1, 0> yyx;\r\n                swizzle<vector_type, array_type, 3, 1, 1, 1> yyy;\r\n                swizzle<vector_type, array_type, 3, 1, 1, 2> yyz;\r\n                swizzle<vector_type, array_type, 3, 1, 2, 0> yzx;\r\n                swizzle<vector_type, array_type, 3, 1, 2, 1> yzy;\r\n                swizzle<vector_type, array_type, 3, 1, 2, 2> yzz;\r\n                swizzle<vector_type, array_type, 3, 2, 0, 0> zxx;\r\n                swizzle<vector_type, array_type, 3, 2, 0, 1> zxy;\r\n                swizzle<vector_type, array_type, 3, 2, 0, 2> zxz;\r\n                swizzle<vector_type, array_type, 3, 2, 1, 0> zyx;\r\n                swizzle<vector_type, array_type, 3, 2, 1, 1> zyy;\r\n                swizzle<vector_type, array_type, 3, 2, 1, 2> zyz;\r\n                swizzle<vector_type, array_type, 3, 2, 2, 0> zzx;\r\n                swizzle<vector_type, array_type, 3, 2, 2, 1> zzy;\r\n                swizzle<vector_type, array_type, 3, 2, 2, 2> zzz;\r\n            };\r\n        };\r\n\r\n        template <typename T, typename Type>\r\n        class basic_vector<T, 2, Type>\r\n        {\r\n            typedef basic_vector<T, 2, Type> self_type;\r\n        public:\r\n            typedef self_type abstract_type; // todo: abstract base; std::array?\r\n        public:\r\n            typedef Type type;\r\n        public:\r\n            typedef T value_type;\r\n            typedef basic_vector<value_type, 2, Type> vector_type;\r\n            typedef uint32_t size_type;\r\n            typedef std::array<value_type, 2> array_type;\r\n            typedef typename array_type::const_iterator const_iterator;\r\n            typedef typename array_type::iterator iterator;\r\n        public:\r\n            template <uint32_t Size2> struct rebind { typedef basic_vector<T, Size2, Type> type; };\r\n        public:\r\n            static constexpr uint32_t Size = 2;\r\n        public:\r\n            basic_vector() : v{} {}\r\n            explicit basic_vector(value_type x, value_type y) : v{ {x, y} } {}\r\n            template <typename... Arguments>\r\n            explicit basic_vector(const value_type& value, Arguments&&... aArguments) : v{ {value, std::forward<Arguments>(aArguments)...} } {}\r\n            template <typename... Arguments>\r\n            explicit basic_vector(value_type&& value, Arguments&&... aArguments) : v{ {std::move(value), std::forward<Arguments>(aArguments)...} } {}\r\n            explicit basic_vector(const array_type& v) : v{ v } {}\r\n            basic_vector(std::initializer_list<value_type> values) { if (values.size() > Size) throw std::out_of_range(\"neolib::basic_vector: initializer list too big\"); std::uninitialized_copy(values.begin(), values.end(), v.begin()); std::uninitialized_fill(v.begin() + (values.end() - values.begin()), v.end(), value_type{}); }\r\n            template <typename V, typename A, uint32_t S, uint32_t... Indexes>\r\n            basic_vector(const swizzle<V, A, S, Indexes...>& aSwizzle) : self_type{ ~aSwizzle } {}\r\n            basic_vector(const self_type& other) : v{ other.v } {}\r\n            basic_vector(self_type&& other) : v{ std::move(other.v) } {}\r\n            template <typename T2>\r\n            basic_vector(const basic_vector<T2, Size, Type>& other) { std::transform(other.begin(), other.end(), v.begin(), [](T2 source) { return static_cast<value_type>(source); }); }\r\n            template <typename T2, uint32_t Size2, typename SFINAE = int>\r\n            basic_vector(const basic_vector<T2, Size2, Type>& other, typename std::enable_if_t < Size2 < Size, SFINAE> = 0) : v{} { std::transform(other.begin(), other.end(), v.begin(), [](T2 source) { return static_cast<value_type>(source); }); }\r\n            self_type& operator=(const self_type& other) { v = other.v; return *this; }\r\n            self_type& operator=(self_type&& other) { v = std::move(other.v); return *this; }\r\n            self_type& operator=(std::initializer_list<value_type> values) { if (values.size() > Size) throw std::out_of_range(\"neolib::basic_vector: initializer list too big\"); std::copy(values.begin(), values.end(), v.begin()); std::fill(v.begin() + (values.end() - values.begin()), v.end(), value_type{}); return *this; }\r\n        public:\r\n            static uint32_t size() { return Size; }\r\n            value_type operator[](uint32_t aIndex) const { return v[aIndex]; }\r\n            value_type& operator[](uint32_t aIndex) { return v[aIndex]; }\r\n            const_iterator begin() const { return v.begin(); }\r\n            const_iterator end() const { return v.end(); }\r\n            iterator begin() { return v.begin(); }\r\n            iterator end() { return v.end(); }\r\n            operator const array_type& () const { return v; }\r\n        public:\r\n            template <typename T2>\r\n            basic_vector<T2, Size, Type> as() const\r\n            {\r\n                return basic_vector<T2, Size, Type>{ *this };\r\n            }\r\n        public:\r\n            bool operator==(const self_type& right) const { return v == right.v; }\r\n            bool operator!=(const self_type& right) const { return v != right.v; }\r\n            self_type& operator+=(value_type value) { for (uint32_t index = 0; index < Size; ++index) v[index] += value; return *this; }\r\n            self_type& operator-=(value_type value) { for (uint32_t index = 0; index < Size; ++index) v[index] -= value; return *this; }\r\n            self_type& operator*=(value_type value) { for (uint32_t index = 0; index < Size; ++index) v[index] *= value; return *this; }\r\n            self_type& operator/=(value_type value) { for (uint32_t index = 0; index < Size; ++index) v[index] /= value; return *this; }\r\n            self_type& operator+=(const self_type& right) { for (uint32_t index = 0; index < Size; ++index) v[index] += right.v[index]; return *this; }\r\n            self_type& operator-=(const self_type& right) { for (uint32_t index = 0; index < Size; ++index) v[index] -= right.v[index]; return *this; }\r\n            self_type& operator*=(const self_type& right) { for (uint32_t index = 0; index < Size; ++index) v[index] *= right.v[index]; return *this; }\r\n            self_type& operator/=(const self_type& right) { for (uint32_t index = 0; index < Size; ++index) v[index] /= right.v[index]; return *this; }\r\n            self_type operator-() const { self_type result; for (uint32_t index = 0; index < Size; ++index) result.v[index] = -v[index]; return result; }\r\n            self_type scale(const self_type& right) const { self_type result; for (uint32_t index = 0; index < Size; ++index) result[index] = v[index] * right[index]; return result; }\r\n            value_type magnitude() const { value_type ss = constants::zero<value_type>; for (uint32_t index = 0; index < Size; ++index) ss += (v[index] * v[index]); return std::sqrt(ss); }\r\n            self_type normalized() const { self_type result; value_type im = constants::one<value_type> / magnitude(); for (uint32_t index = 0; index < Size; ++index) result.v[index] = v[index] * im; return result; }\r\n            self_type min(const self_type& right) const { self_type result; for (uint32_t index = 0; index < Size; ++index) result[index] = std::min(v[index], right.v[index]); return result; }\r\n            self_type max(const self_type& right) const { self_type result; for (uint32_t index = 0; index < Size; ++index) result[index] = std::max(v[index], right.v[index]); return result; }\r\n            value_type min() const { value_type result = v[0]; for (uint32_t index = 1; index < Size; ++index) result = std::min(v[index], result); return result; }\r\n            self_type ceil() const { self_type result; for (uint32_t index = 0; index < Size; ++index) result[index] = std::ceil(v[index]); return result; }\r\n            self_type floor() const { self_type result; for (uint32_t index = 0; index < Size; ++index) result[index] = std::floor(v[index]); return result; }\r\n            self_type round() const { self_type result; for (uint32_t index = 0; index < Size; ++index) result[index] = std::round(v[index]); return result; }\r\n            value_type distance(const self_type& right) const { value_type total = 0; for (uint32_t index = 0; index < Size; ++index) total += ((v[index] - right.v[index]) * (v[index] - right.v[index])); return std::sqrt(total); }\r\n            value_type dot(const self_type& right) const\r\n            {\r\n                value_type result = constants::zero<value_type>;\r\n                for (uint32_t index = 0; index < Size; ++index)\r\n                    result += (v[index] * right[index]);\r\n                return result;\r\n            }\r\n            self_type hadamard_product(const self_type& right) const\r\n            {\r\n                self_type result = *this;\r\n                result *= right;\r\n                return result;\r\n            }\r\n        public:\r\n            union\r\n            {\r\n                array_type v;\r\n                struct // todo: alignment, padding?\r\n                {\r\n                    value_type x;\r\n                    value_type y;\r\n                };\r\n                swizzle<vector_type, array_type, 2, 0, 0> xx;\r\n                swizzle<vector_type, array_type, 2, 0, 1> xy;\r\n                swizzle<vector_type, array_type, 2, 1, 0> yx;\r\n                swizzle<vector_type, array_type, 2, 1, 1> yy;\r\n                swizzle<vector_type, array_type, 3, 0, 0, 0> xxx;\r\n                swizzle<vector_type, array_type, 3, 0, 0, 1> xxy;\r\n                swizzle<vector_type, array_type, 3, 0, 1, 0> xyx;\r\n                swizzle<vector_type, array_type, 3, 0, 1, 1> xyy;\r\n                swizzle<vector_type, array_type, 3, 1, 0, 0> yxx;\r\n                swizzle<vector_type, array_type, 3, 1, 0, 1> yxy;\r\n                swizzle<vector_type, array_type, 3, 1, 1, 0> yyx;\r\n                swizzle<vector_type, array_type, 3, 1, 1, 1> yyy;\r\n            };\r\n        };\r\n\r\n        template <typename T, typename Type>\r\n        class basic_vector<T, 1, Type>\r\n        {\r\n            typedef basic_vector<T, 1, Type> self_type;\r\n        public:\r\n            typedef self_type abstract_type; // todo: abstract base; std::array?\r\n        public:\r\n            typedef Type type;\r\n        public:\r\n            typedef T value_type;\r\n            typedef basic_vector<value_type, 1, Type> vector_type;\r\n            typedef uint32_t size_type;\r\n            typedef std::array<value_type, 1> array_type;\r\n            typedef typename array_type::const_iterator const_iterator;\r\n            typedef typename array_type::iterator iterator;\r\n        public:\r\n            template <uint32_t Size2> struct rebind { typedef basic_vector<T, Size2, Type> type; };\r\n        public:\r\n            static constexpr uint32_t Size = 1;\r\n        public:\r\n            basic_vector() : v{} {}\r\n            explicit basic_vector(value_type x) : v{ {x} } {}\r\n            template <typename... Arguments>\r\n            explicit basic_vector(const value_type& value, Arguments&&... aArguments) : v{ {value, std::forward<Arguments>(aArguments)...} } {}\r\n            template <typename... Arguments>\r\n            explicit basic_vector(value_type&& value, Arguments&&... aArguments) : v{ {std::move(value), std::forward<Arguments>(aArguments)...} } {}\r\n            explicit basic_vector(const array_type& v) : v{ v } {}\r\n            basic_vector(std::initializer_list<value_type> values) { if (values.size() > Size) throw std::out_of_range(\"neolib::basic_vector: initializer list too big\"); std::uninitialized_copy(values.begin(), values.end(), v.begin()); std::uninitialized_fill(v.begin() + (values.end() - values.begin()), v.end(), value_type{}); }\r\n            template <typename V, typename A, uint32_t S, uint32_t... Indexes>\r\n            basic_vector(const swizzle<V, A, S, Indexes...>& aSwizzle) : self_type{ ~aSwizzle } {}\r\n            basic_vector(const self_type& other) : v{ other.v } {}\r\n            basic_vector(self_type&& other) : v{ std::move(other.v) } {}\r\n            template <typename T2>\r\n            basic_vector(const basic_vector<T2, Size, Type>& other) { std::transform(other.begin(), other.end(), v.begin(), [](T2 source) { return static_cast<value_type>(source); }); }\r\n            template <typename T2, uint32_t Size2, typename SFINAE = int>\r\n            basic_vector(const basic_vector<T2, Size2, Type>& other, typename std::enable_if_t < Size2 < Size, SFINAE> = 0) : v{} { std::transform(other.begin(), other.end(), v.begin(), [](T2 source) { return static_cast<value_type>(source); }); }\r\n            self_type& operator=(const self_type& other) { v = other.v; return *this; }\r\n            self_type& operator=(self_type&& other) { v = std::move(other.v); return *this; }\r\n            self_type& operator=(std::initializer_list<value_type> values) { if (values.size() > Size) throw std::out_of_range(\"neolib::basic_vector: initializer list too big\"); std::copy(values.begin(), values.end(), v.begin()); std::fill(v.begin() + (values.end() - values.begin()), v.end(), value_type{}); return *this; }\r\n        public:\r\n            static uint32_t size() { return Size; }\r\n            value_type operator[](uint32_t aIndex) const { return v[aIndex]; }\r\n            value_type& operator[](uint32_t aIndex) { return v[aIndex]; }\r\n            const_iterator begin() const { return v.begin(); }\r\n            const_iterator end() const { return v.end(); }\r\n            iterator begin() { return v.begin(); }\r\n            iterator end() { return v.end(); }\r\n            operator const array_type& () const { return v; }\r\n        public:\r\n            template <typename T2>\r\n            basic_vector<T2, Size, Type> as() const\r\n            {\r\n                return basic_vector<T2, Size, Type>{ *this };\r\n            }\r\n        public:\r\n            bool operator==(const self_type& right) const { return v == right.v; }\r\n            bool operator!=(const self_type& right) const { return v != right.v; }\r\n            self_type& operator+=(value_type value) { for (uint32_t index = 0; index < Size; ++index) v[index] += value; return *this; }\r\n            self_type& operator-=(value_type value) { for (uint32_t index = 0; index < Size; ++index) v[index] -= value; return *this; }\r\n            self_type& operator*=(value_type value) { for (uint32_t index = 0; index < Size; ++index) v[index] *= value; return *this; }\r\n            self_type& operator/=(value_type value) { for (uint32_t index = 0; index < Size; ++index) v[index] /= value; return *this; }\r\n            self_type& operator+=(const self_type& right) { for (uint32_t index = 0; index < Size; ++index) v[index] += right.v[index]; return *this; }\r\n            self_type& operator-=(const self_type& right) { for (uint32_t index = 0; index < Size; ++index) v[index] -= right.v[index]; return *this; }\r\n            self_type& operator*=(const self_type& right) { for (uint32_t index = 0; index < Size; ++index) v[index] *= right.v[index]; return *this; }\r\n            self_type& operator/=(const self_type& right) { for (uint32_t index = 0; index < Size; ++index) v[index] /= right.v[index]; return *this; }\r\n            self_type operator-() const { self_type result; for (uint32_t index = 0; index < Size; ++index) result.v[index] = -v[index]; return result; }\r\n            self_type scale(const self_type& right) const { self_type result; for (uint32_t index = 0; index < Size; ++index) result[index] = v[index] * right[index]; return result; }\r\n            value_type magnitude() const { value_type ss = constants::zero<value_type>; for (uint32_t index = 0; index < Size; ++index) ss += (v[index] * v[index]); return std::sqrt(ss); }\r\n            self_type normalized() const { self_type result; value_type im = constants::one<value_type> / magnitude(); for (uint32_t index = 0; index < Size; ++index) result.v[index] = v[index] * im; return result; }\r\n            self_type min(const self_type& right) const { self_type result; for (uint32_t index = 0; index < Size; ++index) result[index] = std::min(v[index], right.v[index]); return result; }\r\n            self_type max(const self_type& right) const { self_type result; for (uint32_t index = 0; index < Size; ++index) result[index] = std::max(v[index], right.v[index]); return result; }\r\n            value_type min() const { value_type result = v[0]; for (uint32_t index = 1; index < Size; ++index) result = std::min(v[index], result); return result; }\r\n            self_type ceil() const { self_type result; for (uint32_t index = 0; index < Size; ++index) result[index] = std::ceil(v[index]); return result; }\r\n            self_type floor() const { self_type result; for (uint32_t index = 0; index < Size; ++index) result[index] = std::floor(v[index]); return result; }\r\n            self_type round() const { self_type result; for (uint32_t index = 0; index < Size; ++index) result[index] = std::round(v[index]); return result; }\r\n            value_type distance(const self_type& right) const { value_type total = 0; for (uint32_t index = 0; index < Size; ++index) total += ((v[index] - right.v[index]) * (v[index] - right.v[index])); return std::sqrt(total); }\r\n            value_type dot(const self_type& right) const\r\n            {\r\n                value_type result = constants::zero<value_type>;\r\n                for (uint32_t index = 0; index < Size; ++index)\r\n                    result += (v[index] * right[index]);\r\n                return result;\r\n            }\r\n            self_type hadamard_product(const self_type& right) const\r\n            {\r\n                self_type result = *this;\r\n                result *= right;\r\n                return result;\r\n            }\r\n        public:\r\n            union\r\n            {\r\n                array_type v;\r\n                struct // todo: alignment, padding?\r\n                {\r\n                    value_type x;\r\n                };\r\n                swizzle<vector_type, array_type, 2, 0, 0> xx;\r\n                swizzle<vector_type, array_type, 3, 0, 0, 0> xxx;\r\n            };\r\n        };\r\n\r\n        template <typename T, uint32_t Size, typename Type>\r\n        inline bool operator<(const basic_vector<T, Size, Type>& aLhs, const basic_vector<T, Size, Type>& aRhs)\r\n        {\r\n            return aLhs.v < aRhs.v;\r\n        }\r\n\r\n        template <typename T, uint32_t Size, typename Type>\r\n        inline bool operator<=(const basic_vector<T, Size, Type>& aLhs, const basic_vector<T, Size, Type>& aRhs)\r\n        {\r\n            return aLhs.v <= aRhs.v;\r\n        }\r\n\r\n        template <typename T, uint32_t Size, typename Type>\r\n        inline bool operator>(const basic_vector<T, Size, Type>& aLhs, const basic_vector<T, Size, Type>& aRhs)\r\n        {\r\n            return aLhs.v > aRhs.v;\r\n        }\r\n\r\n        template <typename T, uint32_t Size, typename Type>\r\n        inline bool operator>=(const basic_vector<T, Size, Type>& aLhs, const basic_vector<T, Size, Type>& aRhs)\r\n        {\r\n            return aLhs.v >= aRhs.v;\r\n        }\r\n\r\n        template <typename T, uint32_t Size, typename Type>\r\n        inline bool operator==(const basic_vector<T, Size, Type>& aLhs, const basic_vector<T, Size, Type>& aRhs)\r\n        {\r\n            return aLhs.v == aRhs.v;\r\n        }\r\n\r\n        template <typename T, uint32_t Size, typename Type>\r\n        inline bool operator!=(const basic_vector<T, Size, Type>& aLhs, const basic_vector<T, Size, Type>& aRhs)\r\n        {\r\n            return aLhs.v != aRhs.v;\r\n        }\r\n\r\n        typedef basic_vector<double, 1> vector1;\r\n        typedef basic_vector<double, 2> vector2;\r\n        typedef basic_vector<double, 3> vector3;\r\n        typedef basic_vector<double, 4> vector4;\r\n\r\n        typedef vector1 vec1;\r\n        typedef vector2 vec2;\r\n        typedef vector3 vec3;\r\n        typedef vector4 vec4;\r\n\r\n        typedef vec1 col_vec1;\r\n        typedef vec2 col_vec2;\r\n        typedef vec3 col_vec3;\r\n        typedef vec4 col_vec4;\r\n\r\n        typedef basic_vector<double, 1, row_vector> row_vec1;\r\n        typedef basic_vector<double, 2, row_vector> row_vec2;\r\n        typedef basic_vector<double, 3, row_vector> row_vec3;\r\n        typedef basic_vector<double, 4, row_vector> row_vec4;\r\n\r\n        typedef std::optional<vector1> optional_vector1;\r\n        typedef std::optional<vector2> optional_vector2;\r\n        typedef std::optional<vector3> optional_vector3;\r\n        typedef std::optional<vector4> optional_vector4;\r\n\r\n        typedef std::optional<vec1> optional_vec1;\r\n        typedef std::optional<vec2> optional_vec2;\r\n        typedef std::optional<vec3> optional_vec3;\r\n        typedef std::optional<vec4> optional_vec4;\r\n\r\n        typedef std::optional<col_vec1> optional_col_vec1;\r\n        typedef std::optional<col_vec2> optional_col_vec2;\r\n        typedef std::optional<col_vec3> optional_col_vec3;\r\n        typedef std::optional<col_vec4> optional_col_vec4;\r\n\r\n        typedef std::optional<row_vec1> optional_row_vec1;\r\n        typedef std::optional<row_vec2> optional_row_vec2;\r\n        typedef std::optional<row_vec3> optional_row_vec3;\r\n        typedef std::optional<row_vec4> optional_row_vec4;\r\n\r\n        typedef std::vector<vec2> vec2_list;\r\n        typedef std::vector<vec3> vec3_list;\r\n\r\n        typedef std::optional<vec2_list> optional_vec2_list;\r\n        typedef std::optional<vec3_list> optional_vec3_list;\r\n\r\n        typedef vec2_list vertices_2d;\r\n        typedef vec3_list vertices;\r\n\r\n        typedef optional_vec2_list optional_vertices_2d_t;\r\n        typedef optional_vec3_list optional_vertices_t;\r\n\r\n        typedef basic_vector<float, 1> vector1f;\r\n        typedef basic_vector<float, 2> vector2f;\r\n        typedef basic_vector<float, 3> vector3f;\r\n        typedef basic_vector<float, 4> vector4f;\r\n\r\n        typedef vector1f vec1f;\r\n        typedef vector2f vec2f;\r\n        typedef vector3f vec3f;\r\n        typedef vector4f vec4f;\r\n\r\n        typedef int32_t i32;\r\n        typedef int64_t i64;\r\n\r\n        typedef basic_vector<i32, 1> vector1i32;\r\n        typedef basic_vector<i32, 2> vector2i32;\r\n        typedef basic_vector<i32, 3> vector3i32;\r\n        typedef basic_vector<i32, 4> vector4i32;\r\n\r\n        typedef vector1i32 vec1i32;\r\n        typedef vector2i32 vec2i32;\r\n        typedef vector3i32 vec3i32;\r\n        typedef vector4i32 vec4i32;\r\n\r\n        typedef uint32_t u32;\r\n        typedef uint32_t u64;\r\n\r\n        typedef basic_vector<u32, 1> vector1u32;\r\n        typedef basic_vector<u32, 2> vector2u32;\r\n        typedef basic_vector<u32, 3> vector3u32;\r\n        typedef basic_vector<u32, 4> vector4u32;\r\n\r\n        typedef vector1u32 vec1u32;\r\n        typedef vector2u32 vec2u32;\r\n        typedef vector3u32 vec3u32;\r\n        typedef vector4u32 vec4u32;\r\n\r\n        template <std::size_t VertexCount>\r\n        using vec3_array = neolib::vecarray<vec3, VertexCount, VertexCount, neolib::check<neolib::vecarray_overflow>, std::allocator<vec3>>;\r\n\r\n        template <std::size_t VertexCount>\r\n        using vec2_array = neolib::vecarray<vec2, VertexCount, VertexCount, neolib::check<neolib::vecarray_overflow>, std::allocator<vec2>>;\r\n\r\n        typedef std::array<vec3, 3> triangle;\r\n        typedef std::array<vec3, 4> quad;\r\n\r\n        typedef std::array<vec2, 3> triangle_2d;\r\n        typedef std::array<vec2, 4> quad_2d;\r\n\r\n        template <typename T, uint32_t D, typename Type>\r\n        inline basic_vector<T, D, Type> operator+(const basic_vector<T, D, Type>& left, const basic_vector<T, D, Type>& right)\r\n        {\r\n            basic_vector<T, D, Type> result = left;\r\n            result += right;\r\n            return result;\r\n        }\r\n\r\n        template <typename T, uint32_t D, typename Type>\r\n        inline basic_vector<T, D, Type> operator-(const basic_vector<T, D, Type>& left, const basic_vector<T, D, Type>& right)\r\n        {\r\n            basic_vector<T, D, Type> result = left;\r\n            result -= right;\r\n            return result;\r\n        }\r\n\r\n        template <typename T, uint32_t D, typename Type>\r\n        inline basic_vector<T, D, Type> operator+(const basic_vector<T, D, Type>& left, const T& right)\r\n        {\r\n            basic_vector<T, D, Type> result = left;\r\n            for (uint32_t i = 0; i < D; ++i)\r\n                result[i] += right;\r\n            return result;\r\n        }\r\n\r\n        template <typename T, uint32_t D, typename Type>\r\n        inline basic_vector<T, D, Type> operator+(const T& left, const basic_vector<T, D, Type>& right)\r\n        {\r\n            basic_vector<T, D, Type> result = right;\r\n            for (uint32_t i = 0; i < D; ++i)\r\n                result[i] += left;\r\n            return result;\r\n        }\r\n\r\n        template <typename T, uint32_t D, typename Type>\r\n        inline basic_vector<T, D, Type> operator-(const basic_vector<T, D, Type>& left, const T& right)\r\n        {\r\n            basic_vector<T, D, Type> result = left;\r\n            for (uint32_t i = 0; i < D; ++i)\r\n                result[i] -= right;\r\n            return result;\r\n        }\r\n\r\n        template <typename T, uint32_t D, typename Type>\r\n        inline basic_vector<T, D, Type> operator-(const T& left, const basic_vector<T, D, Type>& right)\r\n        {\r\n            basic_vector<T, D, Type> result;\r\n            for (uint32_t i = 0; i < D; ++i)\r\n                result[i] = left - right[i];\r\n            return result;\r\n        }\r\n\r\n        template <typename T, uint32_t D, typename Type>\r\n        inline basic_vector<T, D, Type> operator*(const basic_vector<T, D, Type>& left, const T& right)\r\n        {\r\n            basic_vector<T, D, Type> result = left;\r\n            for (uint32_t i = 0; i < D; ++i)\r\n                result[i] *= right;\r\n            return result;\r\n        }\r\n\r\n        template <typename T, uint32_t D, typename Type>\r\n        inline basic_vector<T, D, Type> operator*(const T& left, const basic_vector<T, D, Type>& right)\r\n        {\r\n            basic_vector<T, D, Type> result = right;\r\n            for (uint32_t i = 0; i < D; ++i)\r\n                result[i] *= left;\r\n            return result;\r\n        }\r\n\r\n        template <typename T, uint32_t D, typename Type>\r\n        inline basic_vector<T, D, Type> operator/(const basic_vector<T, D, Type>& left, const T& right)\r\n        {\r\n            basic_vector<T, D, Type> result = left;\r\n            for (uint32_t i = 0; i < D; ++i)\r\n                result[i] /= right;\r\n            return result;\r\n        }\r\n\r\n        template <typename T, uint32_t D, typename Type>\r\n        inline basic_vector<T, D, Type> operator/(const T& left, const basic_vector<T, D, Type>& right)\r\n        {\r\n            basic_vector<T, D, Type> result;\r\n            for (uint32_t i = 0; i < D; ++i)\r\n                result[i] = left / right[i];\r\n            return result;\r\n        }\r\n\r\n        template <typename T, uint32_t D, typename Type>\r\n        inline basic_vector<T, D, Type> operator%(const basic_vector<T, D, Type>& left, const T& right)\r\n        {\r\n            basic_vector<T, D, Type> result;\r\n            for (uint32_t i = 0; i < D; ++i)\r\n                result[i] = std::fmod(left[i], right);\r\n            return result;\r\n        }\r\n\r\n        template <typename T, uint32_t D>\r\n        inline T operator*(const basic_vector<T, D, row_vector>& left, const basic_vector<T, D, column_vector>& right)\r\n        {\r\n            T result = {};\r\n            for (uint32_t index = 0; index < D; ++index)\r\n                result += (left[index] * right[index]);\r\n            return result;\r\n        }\r\n\r\n        template <typename T, typename Type>\r\n        inline basic_vector<T, 3, Type> operator+(const basic_vector<T, 3, Type>& left, const basic_vector<T, 3, Type>& right)\r\n        {\r\n            return basic_vector<T, 3, Type>{ left[0] + right[0], left[1] + right[1], left[2] + right[2] };\r\n        }\r\n\r\n        template <typename T, typename Type>\r\n        inline basic_vector<T, 3, Type> operator-(const basic_vector<T, 3, Type>& left, const basic_vector<T, 3, Type>& right)\r\n        {\r\n            return basic_vector<T, 3, Type>{ left[0] - right[0], left[1] - right[1], left[2] - right[2] };\r\n        }\r\n\r\n        template <typename T, typename Type>\r\n        inline basic_vector<T, 3, Type> operator+(const basic_vector<T, 3, Type>& left, const T& right)\r\n        {\r\n            return basic_vector<T, 3, Type>{ left[0] + right, left[1] + right, left[2] + right };\r\n        }\r\n\r\n        template <typename T, typename Type>\r\n        inline basic_vector<T, 3, Type> operator+(const T& left, const basic_vector<T, 3, Type>& right)\r\n        {\r\n            return basic_vector<T, 3, Type>{ left + right[0], left + right[1], left + right[2] };\r\n        }\r\n\r\n        template <typename T, typename Type>\r\n        inline basic_vector<T, 3, Type> operator-(const basic_vector<T, 3, Type>& left, const T& right)\r\n        {\r\n            return basic_vector<T, 3, Type>{ left[0] - right, left[1] - right, left[2] - right };\r\n        }\r\n\r\n        template <typename T, typename Type>\r\n        inline basic_vector<T, 3, Type> operator-(const T& left, const basic_vector<T, 3, Type>& right)\r\n        {\r\n            return basic_vector<T, 3, Type>{ left - right[0], left - right[1], left - right[2] };\r\n        }\r\n\r\n        template <typename T, typename Type>\r\n        inline basic_vector<T, 3, Type> operator*(const basic_vector<T, 3, Type>& left, const T& right)\r\n        {\r\n            return basic_vector<T, 3, Type>{ left[0] * right, left[1] * right, left[2] * right };\r\n        }\r\n\r\n        template <typename T, typename Type>\r\n        inline basic_vector<T, 3, Type> operator*(const T& left, const basic_vector<T, 3, Type>& right)\r\n        {\r\n            return basic_vector<T, 3, Type>{ left * right[0], left * right[1], left * right[2] };\r\n        }\r\n\r\n        template <typename T, typename Type>\r\n        inline basic_vector<T, 3, Type> operator/(const basic_vector<T, 3, Type>& left, const T& right)\r\n        {\r\n            return basic_vector<T, 3, Type>{ left[0] / right, left[1] / right, left[2] / right };\r\n        }\r\n\r\n        template <typename T, typename Type>\r\n        inline basic_vector<T, 3, Type> operator%(const basic_vector<T, 3, Type>& left, const T& right)\r\n        {\r\n            return basic_vector<T, 3, Type>{ std::fmod(left[0], right), std::fmod(left[1], right), std::fmod(left[2], right) };\r\n        }\r\n\r\n        template <typename T>\r\n        inline T operator*(const basic_vector<T, 3, row_vector>& left, const basic_vector<T, 3, column_vector>& right)\r\n        {\r\n            return left[0] * right[0] + left[1] * right[1] + left[2] * right[2];\r\n        }\r\n\r\n        template <typename T, typename Type>\r\n        inline basic_vector<T, 3, Type> midpoint(const basic_vector<T, 3, Type>& left, const basic_vector<T, 3, Type>& right)\r\n        {\r\n            return (left + right) / constants::two<T>;\r\n        }\r\n\r\n        template <typename T, uint32_t Size, typename Type>\r\n        inline basic_vector<T, Size, Type> lerp(const basic_vector<T, Size, Type>& aV1, const basic_vector<T, Size, Type>& aV2, double aAmount)\r\n        {\r\n            basic_vector<T, Size, Type> result;\r\n            for (uint32_t i = 0; i < Size; ++i)\r\n            {\r\n                double x1 = aV1[i];\r\n                double x2 = aV2[i];\r\n                result[i] = static_cast<T>((x2 - x1) * aAmount + x1);\r\n            }\r\n            return result;\r\n        }\r\n\r\n        /* todo: specializations that use SIMD intrinsics. */\r\n        template <typename T, uint32_t Rows, uint32_t Columns>\r\n        class basic_matrix\r\n        {\r\n            typedef basic_matrix<T, Rows, Columns> self_type;\r\n        public:\r\n            typedef self_type abstract_type; // todo: abstract base\r\n        public:\r\n            typedef T value_type;\r\n            typedef basic_vector<T, Columns, row_vector> row_type;\r\n            typedef basic_vector<T, Rows, column_vector> column_type;\r\n            typedef std::array<column_type, Columns> array_type;\r\n        public:\r\n            template <typename T2>\r\n            struct rebind { typedef basic_matrix<T2, Rows, Columns> type; };\r\n        public:\r\n            basic_matrix() : m{ {} } {}\r\n            basic_matrix(std::initializer_list<std::initializer_list<value_type>> aColumns) { std::copy(aColumns.begin(), aColumns.end(), m.begin()); }\r\n            basic_matrix(const self_type& other) : m{ other.m } {}\r\n            basic_matrix(self_type&& other) : m{ std::move(other.m) } {}\r\n            template <typename T2>\r\n            basic_matrix(const basic_matrix<T2, Rows, Columns>& other)\r\n            {\r\n                for (uint32_t column = 0; column < Columns; ++column)\r\n                    for (uint32_t row = 0; row < Rows; ++row)\r\n                        (*this)[column][row] = static_cast<value_type>(other[column][row]);\r\n            }\r\n            self_type& operator=(const self_type& other) { m = other.m; return *this; }\r\n            self_type& operator=(self_type&& other) { m = std::move(other.m); return *this; }\r\n        public:\r\n            template <typename T2>\r\n            basic_matrix<T2, Rows, Columns> as() const\r\n            {\r\n                return basic_matrix<T2, Rows, Columns>{ *this };\r\n            }\r\n        public:\r\n            std::pair<uint32_t, uint32_t> size() const { return std::make_pair(Rows, Columns); }\r\n            const column_type& operator[](uint32_t aColumn) const { return m[aColumn]; }\r\n            column_type& operator[](uint32_t aColumn) { return m[aColumn]; }\r\n            const value_type* data() const { return &m[0].v[0]; }\r\n        public:\r\n            bool operator==(const self_type& right) const { return m == right.m; }\r\n            bool operator!=(const self_type& right) const { return m != right.m; }\r\n            self_type& operator+=(const self_type& right) { for (uint32_t column = 0; column < Columns; ++column) m[column] += right.m[column]; return *this; }\r\n            self_type& operator-=(const self_type& right) { for (uint32_t column = 0; column < Columns; ++column) m[column] -= right.m[column]; return *this; }\r\n            self_type& operator*=(const self_type& right)\r\n            {\r\n                self_type result;\r\n                for (uint32_t column = 0; column < Columns; ++column)\r\n                    for (uint32_t row = 0; row < Rows; ++row)\r\n                        for (uint32_t index = 0; index < Columns; ++index)\r\n                            result[column][row] += (m[index][row] * right[column][index]);\r\n                *this = result;\r\n                return *this;\r\n            }\r\n            self_type operator-() const\r\n            {\r\n                self_type result = *this;\r\n                for (uint32_t column = 0; column < Columns; ++column)\r\n                    for (uint32_t row = 0; row < Rows; ++row)\r\n                        result[column][row] = -result[column][row];\r\n                return result;\r\n            }\r\n            self_type round_to(value_type aEpsilon) const\r\n            {\r\n                self_type result;\r\n                for (uint32_t column = 0; column < Columns; ++column)\r\n                    for (uint32_t row = 0; row < Rows; ++row)\r\n                    {\r\n                         std::modf((*this)[column][row] / aEpsilon + 0.5, &result[column][row]);\r\n                         result[column][row] *= aEpsilon;\r\n                    }\r\n                return result;\r\n            }\r\n            basic_matrix<T, Columns, Rows> transposed() const\r\n            {\r\n                basic_matrix<T, Columns, Rows> result;\r\n                for (uint32_t column = 0; column < Columns; ++column)\r\n                    for (uint32_t row = 0; row < Rows; ++row)\r\n                        result[row][column] = m[column][row];\r\n                return result;\r\n            }\r\n            template <typename SFINAE = self_type>\r\n            static const std::enable_if_t<Rows == Columns, SFINAE>& identity()\r\n            {\r\n                auto make_identity = []()\r\n                {\r\n                    self_type result;\r\n                    for (uint32_t diag = 0; diag < Rows; ++diag)\r\n                        result[diag][diag] = static_cast<value_type>(1.0);\r\n                    return result;\r\n                };\r\n                static self_type const sIdentity = make_identity();\r\n                return sIdentity;\r\n            }\r\n            bool is_identity() const\r\n            {\r\n                return this == &identity();\r\n            }\r\n        private:\r\n            array_type m;\r\n        };\r\n\r\n        typedef basic_matrix<double, 1, 1> matrix11;\r\n        typedef basic_matrix<double, 2, 2> matrix22;\r\n        typedef basic_matrix<double, 2, 1> matrix21;\r\n        typedef basic_matrix<double, 1, 2> matrix12;\r\n        typedef basic_matrix<double, 3, 3> matrix33;\r\n        typedef basic_matrix<double, 3, 1> matrix31;\r\n        typedef basic_matrix<double, 3, 2> matrix32;\r\n        typedef basic_matrix<double, 1, 3> matrix13;\r\n        typedef basic_matrix<double, 2, 3> matrix23;\r\n        typedef basic_matrix<double, 4, 4> matrix44;\r\n        typedef basic_matrix<double, 4, 1> matrix41;\r\n        typedef basic_matrix<double, 4, 2> matrix42;\r\n        typedef basic_matrix<double, 4, 3> matrix43;\r\n        typedef basic_matrix<double, 1, 4> matrix14;\r\n        typedef basic_matrix<double, 2, 4> matrix24;\r\n        typedef basic_matrix<double, 3, 4> matrix34;\r\n\r\n        typedef matrix11 matrix1;\r\n        typedef matrix22 matrix2;\r\n        typedef matrix33 matrix3;\r\n        typedef matrix44 matrix4;\r\n\r\n        typedef matrix11 mat11;\r\n        typedef matrix22 mat22;\r\n        typedef matrix21 mat21;\r\n        typedef matrix12 mat12;\r\n        typedef matrix33 mat33;\r\n        typedef matrix31 mat31;\r\n        typedef matrix32 mat32;\r\n        typedef matrix13 mat13;\r\n        typedef matrix23 mat23;\r\n        typedef matrix44 mat44;\r\n        typedef matrix41 mat41;\r\n        typedef matrix42 mat42;\r\n        typedef matrix43 mat43;\r\n        typedef matrix14 mat14;\r\n        typedef matrix24 mat24;\r\n        typedef matrix34 mat34;\r\n\r\n        typedef mat11 mat1;\r\n        typedef mat22 mat2;\r\n        typedef mat33 mat3;\r\n        typedef mat44 mat4;\r\n\r\n        typedef std::optional<matrix11> optional_matrix11;\r\n        typedef std::optional<matrix22> optional_matrix22;\r\n        typedef std::optional<matrix21> optional_matrix21;\r\n        typedef std::optional<matrix12> optional_matrix12;\r\n        typedef std::optional<matrix33> optional_matrix33;\r\n        typedef std::optional<matrix31> optional_matrix31;\r\n        typedef std::optional<matrix32> optional_matrix32;\r\n        typedef std::optional<matrix13> optional_matrix13;\r\n        typedef std::optional<matrix23> optional_matrix23;\r\n        typedef std::optional<matrix44> optional_matrix44;\r\n        typedef std::optional<matrix41> optional_matrix41;\r\n        typedef std::optional<matrix42> optional_matrix42;\r\n        typedef std::optional<matrix43> optional_matrix43;\r\n        typedef std::optional<matrix14> optional_matrix14;\r\n        typedef std::optional<matrix24> optional_matrix24;\r\n        typedef std::optional<matrix34> optional_matrix34;\r\n\r\n        typedef std::optional<matrix11> optional_matrix1;\r\n        typedef std::optional<matrix22> optional_matrix2;\r\n        typedef std::optional<matrix33> optional_matrix3;\r\n        typedef std::optional<matrix44> optional_matrix4;\r\n\r\n        typedef std::optional<mat11> optional_mat11;\r\n        typedef std::optional<mat22> optional_mat22;\r\n        typedef std::optional<mat21> optional_mat21;\r\n        typedef std::optional<mat12> optional_mat12;\r\n        typedef std::optional<mat33> optional_mat33;\r\n        typedef std::optional<mat31> optional_mat31;\r\n        typedef std::optional<mat32> optional_mat32;\r\n        typedef std::optional<mat13> optional_mat13;\r\n        typedef std::optional<mat23> optional_mat23;\r\n        typedef std::optional<mat44> optional_mat44;\r\n        typedef std::optional<mat41> optional_mat41;\r\n        typedef std::optional<mat42> optional_mat42;\r\n        typedef std::optional<mat43> optional_mat43;\r\n        typedef std::optional<mat14> optional_mat14;\r\n        typedef std::optional<mat24> optional_mat24;\r\n        typedef std::optional<mat34> optional_mat34;\r\n\r\n        typedef std::optional<mat11> optional_mat1;\r\n        typedef std::optional<mat22> optional_mat2;\r\n        typedef std::optional<mat33> optional_mat3;\r\n        typedef std::optional<mat44> optional_mat4;\r\n\r\n        typedef basic_matrix<float, 1, 1> matrix11f;\r\n        typedef basic_matrix<float, 2, 2> matrix22f;\r\n        typedef basic_matrix<float, 2, 1> matrix21f;\r\n        typedef basic_matrix<float, 1, 2> matrix12f;\r\n        typedef basic_matrix<float, 3, 3> matrix33f;\r\n        typedef basic_matrix<float, 3, 1> matrix31f;\r\n        typedef basic_matrix<float, 3, 2> matrix32f;\r\n        typedef basic_matrix<float, 1, 3> matrix13f;\r\n        typedef basic_matrix<float, 2, 3> matrix23f;\r\n        typedef basic_matrix<float, 4, 4> matrix44f;\r\n        typedef basic_matrix<float, 4, 1> matrix41f;\r\n        typedef basic_matrix<float, 4, 2> matrix42f;\r\n        typedef basic_matrix<float, 4, 3> matrix43f;\r\n        typedef basic_matrix<float, 1, 4> matrix14f;\r\n        typedef basic_matrix<float, 2, 4> matrix24f;\r\n        typedef basic_matrix<float, 3, 4> matrix34f;\r\n\r\n        typedef matrix11f mat11f;\r\n        typedef matrix22f mat22f;\r\n        typedef matrix21f mat21f;\r\n        typedef matrix12f mat12f;\r\n        typedef matrix33f mat33f;\r\n        typedef matrix31f mat31f;\r\n        typedef matrix32f mat32f;\r\n        typedef matrix13f mat13f;\r\n        typedef matrix23f mat23f;\r\n        typedef matrix44f mat44f;\r\n        typedef matrix41f mat41f;\r\n        typedef matrix42f mat42f;\r\n        typedef matrix43f mat43f;\r\n        typedef matrix14f mat14f;\r\n        typedef matrix24f mat24f;\r\n        typedef matrix34f mat34f;\r\n\r\n        typedef matrix11f mat1f;\r\n        typedef matrix22f mat2f;\r\n        typedef matrix33f mat3f;\r\n        typedef matrix44f mat4f;\r\n\r\n        typedef std::optional<matrix11f> optional_matrix11f;\r\n        typedef std::optional<matrix22f> optional_matrix22f;\r\n        typedef std::optional<matrix21f> optional_matrix21f;\r\n        typedef std::optional<matrix12f> optional_matrix12f;\r\n        typedef std::optional<matrix33f> optional_matrix33f;\r\n        typedef std::optional<matrix31f> optional_matrix31f;\r\n        typedef std::optional<matrix32f> optional_matrix32f;\r\n        typedef std::optional<matrix13f> optional_matrix13f;\r\n        typedef std::optional<matrix23f> optional_matrix23f;\r\n        typedef std::optional<matrix44f> optional_matrix44f;\r\n        typedef std::optional<matrix41f> optional_matrix41f;\r\n        typedef std::optional<matrix42f> optional_matrix42f;\r\n        typedef std::optional<matrix43f> optional_matrix43f;\r\n        typedef std::optional<matrix14f> optional_matrix14f;\r\n        typedef std::optional<matrix24f> optional_matrix24f;\r\n        typedef std::optional<matrix34f> optional_matrix34f;\r\n\r\n        typedef std::optional<matrix11f> optional_matrix1f;\r\n        typedef std::optional<matrix22f> optional_matrix2f;\r\n        typedef std::optional<matrix33f> optional_matrix3f;\r\n        typedef std::optional<matrix44f> optional_matrix4f;\r\n\r\n        typedef std::optional<mat11f> optional_mat11f;\r\n        typedef std::optional<mat22f> optional_mat22f;\r\n        typedef std::optional<mat21f> optional_mat21f;\r\n        typedef std::optional<mat12f> optional_mat12f;\r\n        typedef std::optional<mat33f> optional_mat33f;\r\n        typedef std::optional<mat31f> optional_mat31f;\r\n        typedef std::optional<mat32f> optional_mat32f;\r\n        typedef std::optional<mat13f> optional_mat13f;\r\n        typedef std::optional<mat23f> optional_mat23f;\r\n        typedef std::optional<mat44f> optional_mat44f;\r\n        typedef std::optional<mat41f> optional_mat41f;\r\n        typedef std::optional<mat42f> optional_mat42f;\r\n        typedef std::optional<mat43f> optional_mat43f;\r\n        typedef std::optional<mat14f> optional_mat14f;\r\n        typedef std::optional<mat24f> optional_mat24f;\r\n        typedef std::optional<mat34f> optional_mat34f;\r\n\r\n        typedef std::optional<mat11f> optional_mat1f;\r\n        typedef std::optional<mat22f> optional_mat2f;\r\n        typedef std::optional<mat33f> optional_mat3f;\r\n        typedef std::optional<mat44f> optional_mat4f;\r\n\r\n        template <typename T, uint32_t Rows, uint32_t Columns>\r\n        inline basic_matrix<T, Rows, Columns> operator+(const basic_matrix<T, Rows, Columns>& left, typename basic_matrix<T, Rows, Columns>::value_type right)\r\n        {\r\n            basic_matrix<T, Rows, Columns> result = left;\r\n            result += right;\r\n            return result;\r\n        }\r\n\r\n        template <typename T, uint32_t Rows, uint32_t Columns>\r\n        inline basic_matrix<T, Rows, Columns> operator-(const basic_matrix<T, Rows, Columns>& left, typename basic_matrix<T, Rows, Columns>::value_type right)\r\n        {\r\n            basic_matrix<T, Rows, Columns> result = left;\r\n            result -= right;\r\n            return result;\r\n        }\r\n\r\n        template <typename T, uint32_t Rows, uint32_t Columns>\r\n        inline basic_matrix<T, Rows, Columns> operator*(const basic_matrix<T, Rows, Columns>& left, typename basic_matrix<T, Rows, Columns>::value_type right)\r\n        {\r\n            basic_matrix<T, Rows, Columns> result = left;\r\n            result *= right;\r\n            return result;\r\n        }\r\n\r\n        template <typename T, uint32_t Rows, uint32_t Columns>\r\n        inline basic_matrix<T, Rows, Columns> operator/(const basic_matrix<T, Rows, Columns>& left, typename basic_matrix<T, Rows, Columns>::value_type right)\r\n        {\r\n            basic_matrix<T, Rows, Columns> result = left;\r\n            result /= right;\r\n            return result;\r\n        }\r\n\r\n        template <typename T, uint32_t Rows, uint32_t Columns>\r\n        inline basic_matrix<T, Rows, Columns> operator+(scalar left, const basic_matrix<T, Rows, Columns>& right)\r\n        {\r\n            basic_matrix<T, Rows, Columns> result = right;\r\n            result += left;\r\n            return result;\r\n        }\r\n\r\n        template <typename T, uint32_t Rows, uint32_t Columns>\r\n        inline basic_matrix<T, Rows, Columns> operator-(scalar left, const basic_matrix<T, Rows, Columns>& right)\r\n        {\r\n            return -right + left;\r\n        }\r\n\r\n        template <typename T, uint32_t Rows, uint32_t Columns>\r\n        inline basic_matrix<T, Rows, Columns> operator*(scalar left, const basic_matrix<T, Rows, Columns>& right)\r\n        {\r\n            basic_matrix<T, Rows, Columns> result = right;\r\n            result *= left;\r\n            return result;\r\n        }\r\n\r\n        template <typename T, uint32_t Rows, uint32_t Columns>\r\n        inline basic_matrix<T, Rows, Columns> operator+(const basic_matrix<T, Rows, Columns>& left, const basic_matrix<T, Rows, Columns>& right)\r\n        {\r\n            basic_matrix<T, Rows, Columns> result = left;\r\n            result += right;\r\n            return result;\r\n        }\r\n\r\n        template <typename T, uint32_t Rows, uint32_t Columns>\r\n        inline basic_matrix<T, Rows, Columns> operator-(const basic_matrix<T, Rows, Columns>& left, const basic_matrix<T, Rows, Columns>& right)\r\n        {\r\n            basic_matrix<T, Rows, Columns> result = left;\r\n            result -= right;\r\n            return result;\r\n        }\r\n\r\n        template <typename T, uint32_t D1, uint32_t D2>\r\n        inline basic_matrix<T, D1, D1> operator*(const basic_matrix<T, D1, D2>& left, const basic_matrix<T, D2, D1>& right)\r\n        {\r\n            if (left.is_identity())\r\n                return right;\r\n            if (right.is_identity())\r\n                return left;\r\n            basic_matrix<T, D1, D1> result;\r\n            for (uint32_t column = 0u; column < D1; ++column)\r\n                for (uint32_t row = 0u; row < D1; ++row)\r\n                    for (uint32_t index = 0; index < D2; ++index)\r\n                        result[column][row] += (left[index][row] * right[column][index]);\r\n            return result;\r\n        }\r\n\r\n        template <typename T>\r\n        inline basic_matrix<T, 4u, 4u> operator*(const basic_matrix<T, 4u, 4u>& left, const basic_matrix<T, 4u, 4u>& right)\r\n        {\r\n            if (left.is_identity())\r\n                return right;\r\n            if (right.is_identity())\r\n                return left;\r\n            basic_matrix<T, 4u, 4u> result;\r\n            for (uint32_t column = 0u; column < 4u; ++column)\r\n                for (uint32_t row = 0u; row < 4u; ++row)\r\n                    result[column][row] = simd_fma_4d(left[0u][row], right[column][0u], left[1u][row], right[column][1u], left[2u][row], right[column][2u], left[3u][row], right[column][3u]);\r\n            return result;\r\n        }\r\n\r\n        template <typename T, uint32_t D>\r\n        inline basic_vector<T, D, column_vector> operator*(const basic_matrix<T, D, D>& left, const basic_vector<T, D, column_vector>& right)\r\n        {\r\n            if (left.is_identity())\r\n                return right;\r\n            basic_vector<T, D, column_vector> result;\r\n            for (uint32_t row = 0; row < D; ++row)\r\n                for (uint32_t index = 0; index < D; ++index)\r\n                    result[row] += (left[index][row] * right[index]);\r\n            return result;\r\n        }\r\n\r\n        template <typename T>\r\n        inline basic_vector<T, 4u, column_vector> operator*(const basic_matrix<T, 4u, 4u>& left, const basic_vector<T, 4u, column_vector>& right)\r\n        {\r\n            if (left.is_identity())\r\n                return right;\r\n            basic_vector<T, 4u, column_vector> result;\r\n            for (uint32_t row = 0u; row < 4u; ++row)\r\n                result[row] = simd_fma_4d(left[0][row], right[0], left[1][row], right[1], left[2][row], right[2], left[3][row], right[3]);\r\n            return result;\r\n        }\r\n\r\n        template <typename T, uint32_t D>\r\n        inline basic_vector<T, D, row_vector> operator*(const basic_vector<T, D, row_vector>& left, const basic_matrix<T, D, D>& right)\r\n        {\r\n            if (right.is_identity())\r\n                return left;\r\n            basic_vector<T, D, row_vector> result;\r\n            for (uint32_t column = 0; column < D; ++column)\r\n                for (uint32_t index = 0; index < D; ++index)\r\n                    result[column] += (left[index] * right[column][index]);\r\n            return result;\r\n        }\r\n\r\n        template <typename T>\r\n        inline basic_vector<T, 4u, row_vector> operator*(const basic_vector<T, 4u, row_vector>& left, const basic_matrix<T, 4u, 4u>& right)\r\n        {\r\n            if (right.is_identity())\r\n                return left;\r\n            basic_vector<T, 4u, row_vector> result;\r\n            for (uint32_t column = 0u; column < 4u; ++column)\r\n                result[column] = simd_fma_4d(left[0], right[column][0], left[1], right[column][1], left[2], right[column][2], left[3], right[column][3]);\r\n            return result;\r\n        }\r\n\r\n        template <typename T, uint32_t D>\r\n        inline basic_matrix<T, D, D> operator*(const basic_vector<T, D, column_vector>& left, const basic_vector<T, D, row_vector>& right)\r\n        {\r\n            basic_matrix<T, D, D> result;\r\n            for (uint32_t column = 0; column < D; ++column)\r\n                for (uint32_t row = 0; row < D; ++row)\r\n                    result[column][row] = (left[row] * right[column]);\r\n            return result;\r\n        }\r\n\r\n        template <typename T>\r\n        inline basic_matrix<T, 4u, 4u> operator*(const basic_vector<T, 4u, column_vector>& left, const basic_vector<T, 4u, row_vector>& right)\r\n        {\r\n            basic_matrix<T, 4u, 4u> result;\r\n            for (uint32_t column = 0; column < 4u; ++column)\r\n                simd_mul_4d(left[0u], right[column], left[1u], right[column], left[2u], right[column], left[3u], right[column], result[column][0u], result[column][1u], result[column][2u], result[column][3u]);\r\n            return result;\r\n        }\r\n\r\n        template <typename T, uint32_t D>\r\n        inline basic_matrix<T, D, D> without_translation(const basic_matrix<T, D, D>& matrix)\r\n        {\r\n            auto result = matrix;\r\n            for (uint32_t row = 0; row < D - 1; ++row)\r\n                result[D - 1][row] = 0.0;\r\n            return result;\r\n        }\r\n\r\n        template <typename Elem, typename Traits, typename T, uint32_t Size, typename Type>\r\n        inline std::basic_ostream<Elem, Traits>& operator<<(std::basic_ostream<Elem, Traits>& aStream, const basic_vector<T, Size, Type>& aVector)\r\n        {\r\n            aStream << \"[\";\r\n            for (uint32_t i = 0; i < Size; ++i)\r\n            {\r\n                if (i != 0)\r\n                    aStream << \", \";\r\n                aStream << aVector[i];\r\n            }\r\n            aStream << \"]\";\r\n            return aStream;\r\n        }\r\n\r\n        template <typename Elem, typename Traits, typename T, uint32_t Rows, uint32_t Columns>\r\n        inline std::basic_ostream<Elem, Traits>& operator<<(std::basic_ostream<Elem, Traits>& aStream, const basic_matrix<T, Rows, Columns>& aMatrix)\r\n        {\r\n            aStream << \"[\";\r\n            for (uint32_t row = 0; row < Rows; ++row)\r\n            {\r\n                if (row != 0)\r\n                    aStream << \", \";\r\n                aStream << \"[\";\r\n                for (uint32_t column = 0; column < Columns; ++column)\r\n                {\r\n                    if (column != 0)\r\n                        aStream << \", \";\r\n                    aStream << aMatrix[column][row];\r\n                }\r\n                aStream << \"]\";\r\n            }\r\n            aStream << \"]\";\r\n            return aStream;\r\n        }\r\n\r\n        template <typename Elem, typename Traits, typename T, uint32_t Rows, uint32_t Columns>\r\n        inline std::basic_ostream<Elem, Traits>& operator<<(std::basic_ostream<Elem, Traits>& aStream, const std::optional<basic_matrix<T, Rows, Columns>>& aMatrix)\r\n        {\r\n            if (aMatrix != std::nullopt)\r\n                aStream << *aMatrix;\r\n            else\r\n                aStream << \"[null]\";\r\n            return aStream;\r\n        }\r\n\r\n        // 3D helpers\r\n\r\n        template <typename T>\r\n        inline basic_vector<T, 3u, column_vector> operator*(const basic_matrix<T, 4u, 4u>& left, const basic_vector<T, 3u, column_vector>& right)\r\n        {\r\n            if (left.is_identity())\r\n                return right;\r\n            basic_vector<T, 3u, column_vector> result;\r\n            for (uint32_t row = 0u; row < 3u; ++row)\r\n                result[row] = static_cast<T>(simd_fma_4d(left[0][row], right[0], left[1][row], right[1], left[2][row], right[2], left[3][row], 1.0));\r\n            return result;\r\n        }\r\n\r\n        template <typename T>\r\n        inline std::vector<basic_vector<T, 3u, column_vector>> operator*(const basic_matrix<T, 4u, 4u>& left, const std::vector<basic_vector<T, 3u, column_vector>>& right)\r\n        {\r\n            if (left.is_identity())\r\n                return right;\r\n            std::vector<basic_vector<T, 3u, column_vector>> result;\r\n            result.reserve(right.size());\r\n            for (auto const& v : right)\r\n                result.push_back(left * v);\r\n            return result;\r\n        }\r\n\r\n        inline mat33 rotation_matrix(const vec3& axis, scalar angle, scalar epsilon = 0.00001)\r\n        {\r\n            if (std::abs(angle) <= epsilon)\r\n                return mat33::identity();\r\n            else if (std::abs(angle - boost::math::constants::pi<scalar>()) <= epsilon)\r\n                return -mat33::identity();\r\n            scalar const s = std::sin(angle);\r\n            scalar const c = std::cos(angle);\r\n            scalar const a = 1.0 - c;\r\n            scalar const ax = a * axis.x;\r\n            scalar const ay = a * axis.y;\r\n            scalar const az = a * axis.z;\r\n            return mat33{\r\n                { ax * axis.x + c, ax * axis.y + axis.z * s, ax * axis.z - axis.y * s },\r\n                { ay * axis.x - axis.z * s, ay * axis.y + c, ay * axis.z + axis.x * s },\r\n                { az * axis.x + axis.y * s, az * axis.y - axis.x * s, az * axis.z + c } }.round_to(epsilon);\r\n        }\r\n\r\n        inline mat33 rotation_matrix(const vec3& vectorA, const vec3& vectorB, scalar epsilon = 0.00001)\r\n        {\r\n            auto const nva = vectorA.normalized();\r\n            auto const nvb = vectorB.normalized();\r\n            return rotation_matrix(nva.cross(nvb).normalized(), std::acos(nva.dot(nvb)), epsilon);\r\n        }\r\n\r\n        inline mat33 rotation_matrix(const vec3& angles)\r\n        {\r\n            scalar ax = angles.x;\r\n            scalar ay = angles.y;\r\n            scalar az = angles.z;\r\n            if (ax != 0.0 || ay != 0.0)\r\n            {\r\n                mat33 rx = { { 1.0, 0.0, 0.0 },{ 0.0, std::cos(ax), std::sin(ax) },{ 0.0, -std::sin(ax), std::cos(ax) } };\r\n                mat33 ry = { { std::cos(ay), 0.0, -std::sin(ay) },{ 0.0, 1.0, 0.0 },{ std::sin(ay), 0.0, std::cos(ay) } };\r\n                mat33 rz = { { std::cos(az), std::sin(az), 0.0 },{ -std::sin(az), std::cos(az), 0.0 },{ 0.0, 0.0, 1.0 } };\r\n                return rz * ry * rx;\r\n            }\r\n            else\r\n            {\r\n                return mat33{ { std::cos(az), std::sin(az), 0.0 },{ -std::sin(az), std::cos(az), 0.0 },{ 0.0, 0.0, 1.0 } };\r\n            }\r\n        }\r\n\r\n        inline mat44 affine_rotation_matrix(const vec3& angles)\r\n        {\r\n            scalar ax = angles.x;\r\n            scalar ay = angles.y;\r\n            scalar az = angles.z;\r\n            if (ax != 0.0 || ay != 0.0)\r\n            {\r\n                mat44 rx = { { 1.0, 0.0, 0.0, 0.0 },{ 0.0, std::cos(ax), std::sin(ax), 0.0 },{ 0.0, -std::sin(ax), std::cos(ax), 0.0 },{0.0, 0.0, 0.0, 1.0} };\r\n                mat44 ry = { { std::cos(ay), 0.0, -std::sin(ay), 0.0 },{ 0.0, 1.0, 0.0, 0.0 },{ std::sin(ay), 0.0, std::cos(ay), 0.0 },{0.0, 0.0, 0.0, 1.0} };\r\n                mat44 rz = { { std::cos(az), std::sin(az), 0.0, 0.0 },{ -std::sin(az), std::cos(az), 0.0, 0.0 },{ 0.0, 0.0, 1.0, 0.0 },{0.0, 0.0, 0.0, 1.0} };\r\n                return rz * ry * rx;\r\n            }\r\n            else\r\n            {\r\n                return mat44{ { std::cos(az), std::sin(az), 0.0, 0.0 },{ -std::sin(az), std::cos(az), 0.0, 0.0 },{ 0.0, 0.0, 1.0, 0.0 },{0.0, 0.0, 0.0, 1.0} };\r\n            }\r\n        }\r\n\r\n        inline mat44& apply_translation(mat44& aMatrix, const vec3& aTranslation)\r\n        {\r\n            // todo: SIMD\r\n            aMatrix[3][0] += aTranslation.x;\r\n            aMatrix[3][1] += aTranslation.y;\r\n            aMatrix[3][2] += aTranslation.z;\r\n            return aMatrix;\r\n        }\r\n\r\n        inline mat44& apply_scaling(mat44& aMatrix, const vec3& aScaling)\r\n        {\r\n            // todo: SIMD\r\n            aMatrix[0][0] *= aScaling.x;\r\n            aMatrix[1][1] *= aScaling.y;\r\n            aMatrix[2][2] *= aScaling.z;\r\n            return aMatrix;\r\n        }\r\n\r\n        // AABB\r\n\r\n        struct aabb\r\n        {\r\n            vec3 min;\r\n            vec3 max;\r\n            aabb() : min{}, max{} {}\r\n            aabb(const vec3& aMin, const vec3& aMax) : min{ aMin }, max{ aMax } {}\r\n        };\r\n\r\n        inline vec3 aabb_origin(const aabb& aAabb)\r\n        {\r\n            return aAabb.min + (aAabb.max - aAabb.min) / 2.0;\r\n        }\r\n\r\n        inline vec3 aabb_extents(const aabb& aAabb)\r\n        {\r\n            return aAabb.max - aAabb.min;\r\n        }\r\n\r\n        template <typename... Transforms>\r\n        inline aabb aabb_transform(const aabb& aAabb, const Transforms&... aTransforms)\r\n        {\r\n            std::array<vec3, 8> boxVertices =\r\n            {\r\n                (aTransforms * ... * vec3{ aAabb.min.x, aAabb.min.y, aAabb.min.z }),\r\n                (aTransforms * ... * vec3{ aAabb.max.x, aAabb.min.y, aAabb.min.z }),\r\n                (aTransforms * ... * vec3{ aAabb.min.x, aAabb.max.y, aAabb.min.z }),\r\n                (aTransforms * ... * vec3{ aAabb.max.x, aAabb.max.y, aAabb.min.z }),\r\n                (aTransforms * ... * vec3{ aAabb.min.x, aAabb.min.y, aAabb.max.z }),\r\n                (aTransforms * ... * vec3{ aAabb.max.x, aAabb.min.y, aAabb.max.z }),\r\n                (aTransforms * ... * vec3{ aAabb.min.x, aAabb.max.y, aAabb.max.z }),\r\n                (aTransforms * ... * vec3{ aAabb.max.x, aAabb.max.y, aAabb.max.z })\r\n            };\r\n            aabb result{ boxVertices[0], boxVertices[0] };\r\n            for (auto const& v : boxVertices)\r\n            {\r\n                result.min = result.min.min(v);\r\n                result.max = result.max.max(v);\r\n            }\r\n            return result;\r\n        }\r\n\r\n        inline aabb to_aabb(const vec3& aOrigin, scalar aSize)\r\n        {\r\n            return aabb{ aOrigin - aSize / 2.0, aOrigin + aSize / 2.0 };\r\n        }\r\n\r\n        inline aabb to_aabb(const vec3& aOrigin, const vec3& aSize)\r\n        {\r\n            return aabb{ aOrigin - aSize / 2.0, aOrigin + aSize / 2.0 };\r\n        }\r\n\r\n        inline aabb to_aabb(const vertices& vertices, const mat44& aTransformation = mat44::identity())\r\n        {\r\n            aabb result = !vertices.empty() ? aabb{ vertices[0], vertices[0] } : aabb{};\r\n            for (auto const& v : vertices)\r\n            {\r\n                result.min = result.min.min(v);\r\n                result.max = result.max.max(v);\r\n            }\r\n            return aabb_transform(result, aTransformation);\r\n        }\r\n\r\n        inline bool operator==(const aabb& left, const aabb& right)\r\n        {\r\n            return left.min == right.min && left.max == right.max;\r\n        }\r\n\r\n        inline bool operator!=(const aabb& left, const aabb& right)\r\n        {\r\n            return !(left == right);\r\n        }\r\n\r\n        inline bool operator<(const aabb& left, const aabb& right)\r\n        {\r\n            return std::tie(left.min.z, left.min.y, left.min.x, left.max.z, left.max.y, left.max.x) <\r\n                std::tie(right.min.z, right.min.y, right.min.x, right.max.z, right.max.y, right.max.x);\r\n        }\r\n\r\n        typedef std::optional<aabb> optional_aabb;\r\n\r\n        inline aabb aabb_union(const aabb& left, const aabb& right)\r\n        {\r\n            return aabb{ left.min.min(right.min), left.max.max(right.max) };\r\n        }\r\n\r\n        inline scalar aabb_volume(const aabb& a)\r\n        {\r\n            auto extents = a.max - a.min;\r\n            return extents.x * extents.y * (extents.z != 0.0 ? extents.z : 1.0);\r\n        }\r\n\r\n        inline bool aabb_contains(const aabb& outer, const aabb& inner)\r\n        {\r\n            return inner.min >= outer.min && inner.max <= outer.max;\r\n        }\r\n\r\n        inline bool aabb_contains(const aabb& outer, const vec3& point)\r\n        {\r\n            return point >= outer.min && point <= outer.max;\r\n        }\r\n\r\n        inline bool aabb_intersects(const aabb& first, const aabb& second)\r\n        {\r\n            if (first.max.x < second.min.x)\r\n                return false;\r\n            if (first.min.x > second.max.x)\r\n                return false;\r\n            if (first.max.y < second.min.y)\r\n                return false;\r\n            if (first.min.y > second.max.y)\r\n                return false;\r\n            if (first.max.z < second.min.z)\r\n                return false;\r\n            if (first.min.z > second.max.z)\r\n                return false;\r\n            return true;\r\n        }\r\n\r\n        inline bool aabb_intersects(const std::optional<aabb>& first, const std::optional<aabb>& second)\r\n        {\r\n            if (first == std::nullopt || second == std::nullopt)\r\n                return false;\r\n            return aabb_intersects(*first, *second);\r\n        }\r\n            \r\n        inline bool aabb_intersects(const std::optional<aabb>& first, const aabb& second)\r\n        {\r\n            if (first == std::nullopt)\r\n                return false;\r\n            return aabb_intersects(*first, second);\r\n        }\r\n\r\n        inline bool aabb_intersects(const aabb& first, const std::optional<aabb>& second)\r\n        {\r\n            if (second == std::nullopt)\r\n                return false;\r\n            return aabb_intersects(first, *second);\r\n        }\r\n\r\n        struct aabb_2d\r\n        {\r\n            vec2 min;\r\n            vec2 max;\r\n            aabb_2d() : min{}, max{} {}\r\n            aabb_2d(const vec2& aMin, const vec2& aMax) : min{ aMin }, max{ aMax } {}\r\n            aabb_2d(const aabb& aAabb) : min{ aAabb.min.xy }, max{ aAabb.max.xy } {}\r\n        };\r\n\r\n        inline vec2 aabb_origin(const aabb_2d& aAabb)\r\n        {\r\n            return aAabb.min + (aAabb.max - aAabb.min) / 2.0;\r\n        }\r\n\r\n        inline vec2 aabb_extents(const aabb_2d& aAabb)\r\n        {\r\n            return aAabb.max - aAabb.min;\r\n        }\r\n\r\n        template <typename... Transforms>\r\n        inline aabb_2d aabb_transform(const aabb_2d& aAabb, const Transforms&... aTransforms)\r\n        {\r\n            std::array<vec3, 4> boxVertices =\r\n            {\r\n                (aTransforms * ... * vec3{ aAabb.min.x, aAabb.min.y, 0.0 }),\r\n                (aTransforms * ... * vec3{ aAabb.max.x, aAabb.min.y, 0.0 }),\r\n                (aTransforms * ... * vec3{ aAabb.min.x, aAabb.max.y, 0.0 }),\r\n                (aTransforms * ... * vec3{ aAabb.max.x, aAabb.max.y, 0.0 })\r\n            };\r\n            aabb_2d result{ boxVertices[0].xy, boxVertices[0].xy };\r\n            for (auto const& v : boxVertices)\r\n            {\r\n                result.min = result.min.min(v.xy);\r\n                result.max = result.max.max(v.xy);\r\n            }\r\n            return result;\r\n        }\r\n\r\n        inline aabb_2d to_aabb_2d(const vec3& aOrigin, scalar aSize)\r\n        {\r\n            return aabb_2d{ (aOrigin - aSize / 2.0).xy, (aOrigin + aSize / 2.0).xy };\r\n        }\r\n\r\n        inline aabb_2d to_aabb_2d(const vec3& aOrigin, const vec3& aSize)\r\n        {\r\n            return aabb_2d{ (aOrigin - aSize / 2.0).xy, (aOrigin + aSize / 2.0).xy };\r\n        }\r\n\r\n        inline aabb_2d to_aabb_2d(const vertices& vertices, const mat44& aTransformation = mat44::identity())\r\n        {\r\n            aabb_2d result = !vertices.empty() ? aabb_2d{ vertices[0].xy, vertices[0].xy } : aabb_2d{};\r\n            for (auto const& v : vertices)\r\n            {\r\n                result.min = result.min.min(v.xy);\r\n                result.max = result.max.max(v.xy);\r\n            }\r\n            return aabb_transform(result, aTransformation);\r\n        }\r\n\r\n        inline bool operator==(const aabb_2d& left, const aabb_2d& right)\r\n        {\r\n            return left.min == right.min && left.max == right.max;\r\n        }\r\n\r\n        inline bool operator!=(const aabb_2d& left, const aabb_2d& right)\r\n        {\r\n            return !(left == right);\r\n        }\r\n\r\n        inline bool operator<(const aabb_2d& left, const aabb_2d& right)\r\n        {\r\n            return std::tie(left.min.y, left.min.x, left.max.y, left.max.x) <\r\n                std::tie(right.min.y, right.min.x, right.max.y, right.max.x);\r\n        }\r\n\r\n        typedef std::optional<aabb_2d> optional_aabb_2d;\r\n\r\n        inline aabb_2d aabb_union(const aabb_2d& left, const aabb_2d& right)\r\n        {\r\n            return aabb_2d{ left.min.min(right.min), left.max.max(right.max) };\r\n        }\r\n\r\n        inline scalar aabb_volume(const aabb_2d& a)\r\n        {\r\n            auto extents = a.max - a.min;\r\n            return extents.x * extents.y;\r\n        }\r\n\r\n        inline bool aabb_contains(const aabb_2d& outer, const aabb_2d& inner)\r\n        {\r\n            return inner.min >= outer.min && inner.max <= outer.max;\r\n        }\r\n\r\n        inline bool aabb_contains(const aabb_2d& outer, const vec2& point)\r\n        {\r\n            return point >= outer.min && point <= outer.max;\r\n        }\r\n\r\n        inline bool aabb_intersects(const aabb_2d& first, const aabb_2d& second)\r\n        {\r\n            if (first.max.x < second.min.x)\r\n                return false;\r\n            if (first.min.x > second.max.x)\r\n                return false;\r\n            if (first.max.y < second.min.y)\r\n                return false;\r\n            if (first.min.y > second.max.y)\r\n                return false;\r\n            return true;\r\n        }\r\n\r\n        inline bool aabb_intersects(const std::optional<aabb_2d>& first, const std::optional<aabb_2d>& second)\r\n        {\r\n            if (first == std::nullopt || second == std::nullopt)\r\n                return false;\r\n            return aabb_intersects(*first, *second);\r\n        }\r\n\r\n        inline bool aabb_intersects(const std::optional<aabb_2d>& first, const aabb_2d& second)\r\n        {\r\n            if (first == std::nullopt)\r\n                return false;\r\n            return aabb_intersects(*first, second);\r\n        }\r\n\r\n        inline bool aabb_intersects(const aabb_2d& first, const std::optional<aabb_2d>& second)\r\n        {\r\n            if (second == std::nullopt)\r\n                return false;\r\n            return aabb_intersects(first, *second);\r\n        }\r\n    }\r\n\r\n    using namespace math;\r\n}\r\n", "meta": {"hexsha": "e8e3aed1f20fc1ee9d3427ca0e7c75c703e077cf", "size": 82068, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/neolib/core/numerical.hpp", "max_stars_repo_name": "madebr/neolib", "max_stars_repo_head_hexsha": "8cbd46af590a58c96712ee93e71ca714cbd382ee", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/neolib/core/numerical.hpp", "max_issues_repo_name": "madebr/neolib", "max_issues_repo_head_hexsha": "8cbd46af590a58c96712ee93e71ca714cbd382ee", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/neolib/core/numerical.hpp", "max_forks_repo_name": "madebr/neolib", "max_forks_repo_head_hexsha": "8cbd46af590a58c96712ee93e71ca714cbd382ee", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.528062764, "max_line_length": 331, "alphanum_fraction": 0.5618511478, "num_tokens": 20794, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.48730007067458414}}
{"text": "// Copyright \u00a9 2016-2021 Thomas Nagler and Thibault Vatter\n//\n// This file is part of the vinecopulib library and licensed under the terms of\n// the MIT license. For a copy, see the LICENSE file in the root directory of\n// vinecopulib or https://vinecopulib.github.io/vinecopulib/.\n\n#pragma once\n\n#include \"gtest/gtest.h\"\n#include <boost/math/constants/constants.hpp>\n#include <vinecopulib/bicop/class.hpp>\n#include <vinecopulib/misc/tools_eigen.hpp>\n#include <vinecopulib/misc/tools_stl.hpp>\n\nusing namespace vinecopulib;\n\n// Test class for parametric bivariate copulas\nclass ParBicopTest\n  : public ::testing::TestWithParam<::testing::tuple<BicopFamily, int>>\n{\npublic:\n  void set_family(BicopFamily family, int rotation);\n\n  void set_parameters(Eigen::VectorXd parameters);\n\n  int get_n();\n\n  int get_family();\n\n  double get_par();\n\n  double get_par2();\n\nprotected:\n  int n_;\n  int family_;\n  double par_;\n  double par2_;\n  Bicop bicop_;\n  bool needs_check_;\n\n  virtual void SetUp()\n  {\n    n_ = static_cast<int>(5e3);\n    auto family = ::testing::get<0>(GetParam());\n    auto rotation = ::testing::get<1>(GetParam());\n    if (tools_stl::is_member(family, bicop_families::rotationless)) {\n      bicop_ = Bicop(family);\n    } else {\n      bicop_ = Bicop(family, rotation);\n    }\n\n    set_family(family, rotation);\n    double tau = 0.5; // should be positive\n    auto parameters = bicop_.get_parameters();\n    if (parameters.size() < 2) {\n      parameters = bicop_.tau_to_parameters(tau);\n    } else {\n      if (family == BicopFamily::student) {\n        parameters(0) = sin(tau * boost::math::constants::pi<double>() / 2);\n        parameters(1) = 4;\n      } else if (family == BicopFamily::bb1) {\n        parameters(1) = 1.5;\n        parameters(0) = -(2 * (1 - parameters(1) + parameters(1) * tau));\n        parameters(0) /= (parameters(1) * (-1 + tau));\n      } else {\n        double delta = 1.5;\n        if (family == BicopFamily::bb8)\n          delta = 0.8;\n        auto tau_v = Eigen::VectorXd::Constant(1, std::fabs(tau));\n        auto f = [this, delta](const Eigen::VectorXd& v) {\n          Eigen::VectorXd par(2);\n          par(0) = v(0);\n          par(1) = delta;\n          auto tt = bicop_.parameters_to_tau(par);\n          return Eigen::VectorXd::Constant(1, std::fabs(tt));\n        };\n        parameters(0) = tools_eigen::invert_f(tau_v, f, 1 + 1e-6, 100)(0);\n        parameters(1) = delta;\n      }\n    }\n    // set the parameters vector for the ParBicop\n    bicop_.set_parameters(parameters);\n\n    // whether checks need to be done and deal with the rotation for VineCopula\n    needs_check_ = true;\n    if (tools_stl::is_member(family, bicop_families::rotationless)) {\n      needs_check_ = (rotation == 0);\n    } else {\n      if (tools_stl::is_member(rotation, { 90, 270 }))\n        parameters *= -1;\n    }\n\n    // set the parameters vector for R\n    set_parameters(parameters);\n  }\n};\n", "meta": {"hexsha": "38603b5957f0fc29c99f6f30dd9a95c05aa17276", "size": 2899, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/src_test/include/parbicop_test.hpp", "max_stars_repo_name": "tvatter/vinecoplib", "max_stars_repo_head_hexsha": "ae34d56408437e6eeacec40a51a8fa8dac378672", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28.0, "max_stars_repo_stars_event_min_datetime": "2017-05-05T13:27:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-15T23:40:01.000Z", "max_issues_repo_path": "test/src_test/include/parbicop_test.hpp", "max_issues_repo_name": "vinecopulib/vinecopulib", "max_issues_repo_head_hexsha": "ae34d56408437e6eeacec40a51a8fa8dac378672", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 264.0, "max_issues_repo_issues_event_min_datetime": "2017-03-28T10:07:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-23T10:04:39.000Z", "max_forks_repo_path": "test/src_test/include/parbicop_test.hpp", "max_forks_repo_name": "tvatter/vinecoplib", "max_forks_repo_head_hexsha": "ae34d56408437e6eeacec40a51a8fa8dac378672", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-04-24T13:54:47.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-22T16:56:17.000Z", "avg_line_length": 29.5816326531, "max_line_length": 79, "alphanum_fraction": 0.6333218351, "num_tokens": 818, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255928, "lm_q2_score": 0.6406358479787609, "lm_q1q2_score": 0.48730006894152744}}
{"text": "#define BOOST_TEST_MODULE PulseProfile\n#include <boost/test/unit_test.hpp>\n\n#include <cmath>\n#include <fstream>\n\n#include <sycomore/HardPulseApproximation.h>\n#include <sycomore/magnetization.h>\n#include <sycomore/como/Model.h>\n#include <sycomore/Pulse.h>\n#include <sycomore/sycomore.h>\n#include <sycomore/units.h>\n\nusing namespace sycomore::units;\n\nBOOST_AUTO_TEST_CASE(PulseProfile, *boost::unit_test::tolerance(1e-9))\n{\n    sycomore::Species const species(0_Hz, 0_Hz, 0_um*um/ms);\n    sycomore::Magnetization const m0{0,0,1};\n\n    sycomore::Pulse const pulse(90_deg, M_PI*rad);\n    auto const pulse_duration=1_ms;\n    int const pulse_support_size = 101;\n    int const zero_crossings = 2;\n\n    // NOTE: in the absence of relaxation and diffusion, the TR is meaningless\n    auto const TR=500_ms;\n    auto const slice_thickness=1_mm;\n\n    int const sampling_support_size = 501;\n\n    auto const t0 = pulse_duration/(2*zero_crossings);\n    sycomore::HardPulseApproximation const sinc_pulse(\n        pulse,\n        sycomore::linspace(pulse_duration, pulse_support_size),\n        sycomore::sinc_envelope(t0), 1/t0, slice_thickness, \"rf\");\n\n    sycomore::TimeInterval const refocalization(\n        (TR-pulse_duration)/2., -sinc_pulse.get_gradient_moment()/2);\n\n    auto const sampling_locations = sycomore::linspace(\n        sycomore::Point{0_m, 0_m, 2*slice_thickness},\n        sampling_support_size);\n\n    sycomore::como::Model model(\n        species, m0, {\n            {\"rf\", sinc_pulse.get_time_interval()},\n            {\"refocalization\", refocalization}\n    });\n\n    model.apply_pulse(sinc_pulse);\n\n    std::vector<sycomore::Magnetization> before_refocalization;\n    for(auto && location: sampling_locations)\n    {\n        auto const signal = model.isochromat({}, location);\n        before_refocalization.push_back(signal);\n    }\n\n    model.apply_time_interval(\"refocalization\");\n\n    std::vector<sycomore::Magnetization> after_refocalization;\n    for(auto && location: sampling_locations)\n    {\n        auto const signal = model.isochromat({}, location);\n        after_refocalization.push_back(signal);\n    }\n\n    std::vector<double> baseline;\n    std::string const root(getenv(\"SYCOMORE_TEST_DATA\")?getenv(\"SYCOMORE_TEST_DATA\"):\"\");\n    if(root.empty())\n    {\n        throw std::runtime_error(\"SYCOMORE_TEST_DATA is undefined\");\n    }\n    std::ifstream stream(root+\"/baseline/pulse_profile.dat\", std::ios_base::binary);\n    while(stream.good())\n    {\n        double value;\n        stream.read(reinterpret_cast<char*>(&value), sizeof(value));\n        if(stream.good())\n        {\n            baseline.push_back(value);\n        }\n    }\n\n    // WARNING: we are using absolute tolerance, not relative to the value of\n    // left and right\n#define TEST_COMPONENT(left, right, where) \\\n    BOOST_TEST(\\\n    left-right == 0., \\\n    \"Error on \" << #left << \" (\" << where << \") at \" << x \\\n        << \" [ \" << left << \" != \" << right << \" ]\")\n#define TEST_MAGNETIZATION(where) \\\n    TEST_COMPONENT(m[0], *(baseline_it+0), where); \\\n    TEST_COMPONENT(m[1], *(baseline_it+1), where); \\\n    TEST_COMPONENT(m[2], *(baseline_it+2), where)\n\n    BOOST_REQUIRE_EQUAL(baseline.size(), 2*3*sampling_locations.size());\n    auto baseline_it = baseline.begin();\n    for(auto && m: before_refocalization)\n    {\n        auto x = sampling_locations[(baseline_it-baseline.begin())/3];\n        TEST_MAGNETIZATION(\"before\");\n        baseline_it += 3;\n    }\n    for(auto && m: after_refocalization)\n    {\n        auto x = sampling_locations[\n            (baseline_it-baseline.begin())/3-before_refocalization.size()];\n        TEST_MAGNETIZATION(\"after\");\n        baseline_it += 3;\n    }\n}\n", "meta": {"hexsha": "ac56df6620a1d381a7de32975d6b454649dc55f8", "size": 3661, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/cpp/pulse_profile.cpp", "max_stars_repo_name": "aTrotier/sycomore", "max_stars_repo_head_hexsha": "32e438d3a90ca0a9d051bb6acff461e06079116d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2019-11-06T09:23:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-11T19:08:36.000Z", "max_issues_repo_path": "tests/cpp/pulse_profile.cpp", "max_issues_repo_name": "aTrotier/sycomore", "max_issues_repo_head_hexsha": "32e438d3a90ca0a9d051bb6acff461e06079116d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-12-01T15:48:27.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-04T15:19:37.000Z", "max_forks_repo_path": "tests/cpp/pulse_profile.cpp", "max_forks_repo_name": "aTrotier/sycomore", "max_forks_repo_head_hexsha": "32e438d3a90ca0a9d051bb6acff461e06079116d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-08-12T04:36:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-27T13:17:34.000Z", "avg_line_length": 32.1140350877, "max_line_length": 89, "alphanum_fraction": 0.6602021306, "num_tokens": 934, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891479496521, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.487284046834454}}
{"text": "#pragma once\n#include <boost/serialization/version.hpp>\n#include <boost/serialization/serialization.hpp>\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <utility>\n\n#include <stdint.h>\n\n#include \"perception/vision/CameraDefs.hpp\"\n#include \"types/Point.hpp\"\n#include \"types/RRCoord.hpp\"\n#include \"types/JointValues.hpp\"\n#include \"types/XYZ_Coord.hpp\"\n\n/**\n * The Pose class contains precomputed kinematic data that is useful\n * to other modules. (Currently only vision).\n *\n * The idea is that the kinematics module computes the full kinematic chain\n * and then stores the resulting matrix in this Pose class.\n *\n * Vision then queries the Pose class and the cached results are used each\n * time.\n */\nclass Pose {\n   public:\n      explicit Pose(\n         boost::numeric::ublas::matrix<float> topCameraToWorldTransform,\n         boost::numeric::ublas::matrix<float> botCameraToWorldTransform,\n         boost::numeric::ublas::matrix<float> neckToWorldTransform,\n         std::pair<int, int> horizon);\n\n      Pose();\n\n      /**\n       *  Returns a pair for the horizon.\n       *  pair.first is the y position of the horizon at x = 0\n       *  pair.second is the y position of the horizon at x = 640\n       */\n      std::pair<int, int> getHorizon() const;\n\n      XYZ_Coord robotRelativeToNeckCoord(RRCoord coord, int h) const;\n      \n      /**\n       * Returns the robot relative coord for a given pixel at a particular\n       * height.\n       *\n       * @param x pixel\n       * @param y pixel\n       * @param h of intersection plane.\n       */\n      RRCoord imageToRobotRelative(int x, int y, int h) const;\n\n      /**\n       * Returns the robot relative coord for a given pixel at a particular\n       * height.\n       *\n       * @param p point in image space\n       * @param h of intersection plane.\n       */\n      RRCoord imageToRobotRelative(Point p, int h = 0) const;\n\n      Point imageToRobotXY(const Point &image, int h = 0) const;\n      Point robotToImageXY(Point robot, int h = 0) const;\n\n      /* Returns a pointer to the exclusion arrays used by vision */\n      const int16_t *getTopExclusionArray() const;\n      int16_t *getTopExclusionArray();\n      const int16_t *getBotExclusionArray() const;\n      int16_t *getBotExclusionArray();\n\n      const boost::numeric::ublas::matrix<float>\n            getC2wTransform(bool top = true) const;\n\n      boost::numeric::ublas::matrix<float> topCameraToWorldTransform;\n      boost::numeric::ublas::matrix<float> botCameraToWorldTransform;\n      boost::numeric::ublas::matrix<float> topWorldToCameraTransform;\n      boost::numeric::ublas::matrix<float> botWorldToCameraTransform;\n      \n      boost::numeric::ublas::matrix<float> neckToWorldTransform;\n      boost::numeric::ublas::matrix<float> worldToNeckTransform;\n\n      static const uint16_t EXCLUSION_RESOLUTION = 100;\n   private:\n      boost::numeric::ublas::matrix<float> origin, zunit;\n      boost::numeric::ublas::matrix<float> topCOrigin, botCOrigin;\n      boost::numeric::ublas::matrix<float> topToFocus, botToFocus;\n      boost::numeric::ublas::matrix<float> topWorldToCameraTransformT;\n      boost::numeric::ublas::matrix<float> botWorldToCameraTransformT;\n\n      void makeConstants();\n\n      std::pair<int, int> horizon;\n      int16_t topExclusionArray[EXCLUSION_RESOLUTION];\n      int16_t botExclusionArray[EXCLUSION_RESOLUTION];\n\n#ifndef SWIG\n      BOOST_SERIALIZATION_SPLIT_MEMBER();\n#endif\n\n      friend class boost::serialization::access;\n      template<class Archive>\n      void serializeMembers(Archive &ar, const unsigned int version);\n\n      template<class Archive>\n      void save(Archive &ar, const unsigned int version) const;\n\n      template<class Archive>\n      void load(Archive &ar, const unsigned int version);\n};\n\nBOOST_CLASS_VERSION(Pose, 2);\n\n#include \"Pose.tcc\"\n\n", "meta": {"hexsha": "8454b031c0f5d0d42b8b5275b5433c7e630db115", "size": 3834, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Core/External/unsw/unsw/perception/kinematics/Pose.hpp", "max_stars_repo_name": "pedrohsreis/boulos", "max_stars_repo_head_hexsha": "a5b68a32cad8cc1fb9f6fbf47fc487ef99d3166e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-09-18T18:05:05.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-23T17:47:07.000Z", "max_issues_repo_path": "src/Core/External/unsw/unsw/perception/kinematics/Pose.hpp", "max_issues_repo_name": "pedrohsreis/boulos", "max_issues_repo_head_hexsha": "a5b68a32cad8cc1fb9f6fbf47fc487ef99d3166e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-06-08T18:48:32.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-19T21:41:16.000Z", "max_forks_repo_path": "src/Core/External/unsw/unsw/perception/kinematics/Pose.hpp", "max_forks_repo_name": "pedrohsreis/boulos", "max_forks_repo_head_hexsha": "a5b68a32cad8cc1fb9f6fbf47fc487ef99d3166e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2018-09-11T17:19:16.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-30T16:43:56.000Z", "avg_line_length": 32.4915254237, "max_line_length": 75, "alphanum_fraction": 0.6844027126, "num_tokens": 916, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891479496523, "lm_q2_score": 0.5926665999540697, "lm_q1q2_score": 0.487284046834454}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2005, 2007, 2009, 2010, 2012, 2014 Klaus Spanderen\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n#include \"hestonmodel.hpp\"\n#include \"utilities.hpp\"\n#include <ql/instruments/dividendbarrieroption.hpp>\n#include <ql/instruments/dividendvanillaoption.hpp>\n#include <ql/processes/hestonprocess.hpp>\n#include <ql/math/integrals/gausslobattointegral.hpp>\n#include <ql/models/equity/hestonmodel.hpp>\n#include <ql/models/equity/hestonmodelhelper.hpp>\n#include <ql/models/equity/piecewisetimedependenthestonmodel.hpp>\n#include <ql/pricingengines/vanilla/analyticdividendeuropeanengine.hpp>\n#include <ql/pricingengines/vanilla/analytichestonengine.hpp>\n#include <ql/pricingengines/vanilla/hestonexpansionengine.hpp>\n#include <ql/pricingengines/vanilla/coshestonengine.hpp>\n#include <ql/pricingengines/vanilla/fdamericanengine.hpp>\n#include <ql/pricingengines/vanilla/fddividendeuropeanengine.hpp>\n#include <ql/pricingengines/vanilla/fdeuropeanengine.hpp>\n#include <ql/pricingengines/vanilla/analyticptdhestonengine.hpp>\n#include <ql/pricingengines/barrier/fdhestonbarrierengine.hpp>\n#include <ql/pricingengines/barrier/fdblackscholesbarrierengine.hpp>\n#include <ql/pricingengines/vanilla/fdblackscholesvanillaengine.hpp>\n#include <ql/pricingengines/vanilla/fdhestonvanillaengine.hpp>\n#include <ql/pricingengines/vanilla/mceuropeanhestonengine.hpp>\n#include <ql/pricingengines/blackformula.hpp>\n#include <ql/time/calendars/target.hpp>\n#include <ql/time/calendars/nullcalendar.hpp>\n#include <ql/time/daycounters/actual365fixed.hpp>\n#include <ql/time/daycounters/actual360.hpp>\n#include <ql/time/daycounters/actualactual.hpp>\n#include <ql/termstructures/yield/zerocurve.hpp>\n#include <ql/termstructures/yield/flatforward.hpp>\n#include <ql/math/optimization/levenbergmarquardt.hpp>\n#include <ql/math/optimization/differentialevolution.hpp>\n#include <ql/time/period.hpp>\n#include <ql/quotes/simplequote.hpp>\n#include <ql/experimental/math/numericaldifferentiation.hpp>\n#include <ql/experimental/exoticoptions/analyticpdfhestonengine.hpp>\n\n#include <boost/make_shared.hpp>\n\nusing namespace QuantLib;\nusing namespace boost::unit_test_framework;\n\nnamespace {\n\n    struct CalibrationMarketData {\n        Handle<Quote> s0;\n        Handle<YieldTermStructure> riskFreeTS, dividendYield;\n        std::vector<boost::shared_ptr<CalibrationHelper> > options;\n    };\n\n    CalibrationMarketData getDAXCalibrationMarketData() {\n        /* this example is taken from A. Sepp\n           Pricing European-Style Options under Jump Diffusion Processes\n           with Stochstic Volatility: Applications of Fourier Transform\n           http://math.ut.ee/~spartak/papers/stochjumpvols.pdf\n        */\n\n        Date settlementDate(Settings::instance().evaluationDate());\n        \n        DayCounter dayCounter = Actual365Fixed();\n        Calendar calendar = TARGET();\n        \n        Integer t[] = { 13, 41, 75, 165, 256, 345, 524, 703 };\n        Rate r[] = { 0.0357,0.0349,0.0341,0.0355,0.0359,0.0368,0.0386,0.0401 };\n        \n        std::vector<Date> dates;\n        std::vector<Rate> rates;\n        dates.push_back(settlementDate);\n        rates.push_back(0.0357);\n        Size i;\n        for (i = 0; i < 8; ++i) {\n            dates.push_back(settlementDate + t[i]);\n            rates.push_back(r[i]);\n        }\n        // FLOATING_POINT_EXCEPTION\n        Handle<YieldTermStructure> riskFreeTS(\n                           boost::shared_ptr<YieldTermStructure>(\n                                      new ZeroCurve(dates, rates, dayCounter)));\n        \n        Handle<YieldTermStructure> dividendYield(\n                                    flatRate(settlementDate, 0.0, dayCounter));\n        \n        Volatility v[] =\n          { 0.6625,0.4875,0.4204,0.3667,0.3431,0.3267,0.3121,0.3121,\n            0.6007,0.4543,0.3967,0.3511,0.3279,0.3154,0.2984,0.2921,\n            0.5084,0.4221,0.3718,0.3327,0.3155,0.3027,0.2919,0.2889,\n            0.4541,0.3869,0.3492,0.3149,0.2963,0.2926,0.2819,0.2800,\n            0.4060,0.3607,0.3330,0.2999,0.2887,0.2811,0.2751,0.2775,\n            0.3726,0.3396,0.3108,0.2781,0.2788,0.2722,0.2661,0.2686,\n            0.3550,0.3277,0.3012,0.2781,0.2781,0.2661,0.2661,0.2681,\n            0.3428,0.3209,0.2958,0.2740,0.2688,0.2627,0.2580,0.2620,\n            0.3302,0.3062,0.2799,0.2631,0.2573,0.2533,0.2504,0.2544,\n            0.3343,0.2959,0.2705,0.2540,0.2504,0.2464,0.2448,0.2462,\n            0.3460,0.2845,0.2624,0.2463,0.2425,0.2385,0.2373,0.2422,\n            0.3857,0.2860,0.2578,0.2399,0.2357,0.2327,0.2312,0.2351,\n            0.3976,0.2860,0.2607,0.2356,0.2297,0.2268,0.2241,0.2320 };\n        \n        Handle<Quote> s0(boost::shared_ptr<Quote>(new SimpleQuote(4468.17)));\n        Real strike[] = { 3400,3600,3800,4000,4200,4400,\n                          4500,4600,4800,5000,5200,5400,5600 };\n        \n        std::vector<boost::shared_ptr<CalibrationHelper> > options;\n        \n        for (Size s = 0; s < 13; ++s) {\n            for (Size m = 0; m < 8; ++m) {\n                Handle<Quote> vol(boost::shared_ptr<Quote>(\n                                                    new SimpleQuote(v[s*8+m])));\n        \n                Period maturity((int)((t[m]+3)/7.), Weeks); // round to weeks\n                options.push_back(boost::shared_ptr<CalibrationHelper>(\n                        new HestonModelHelper(maturity, calendar,\n                                              s0, strike[s], vol,\n                                              riskFreeTS, dividendYield,\n                                          CalibrationHelper::ImpliedVolError)));\n            }\n        }\n        \n        CalibrationMarketData marketData\n                                    ={ s0, riskFreeTS, dividendYield, options };\n        \n        return marketData;\n    }\n        \n}\n\n\nvoid HestonModelTest::testBlackCalibration() {\n    BOOST_TEST_MESSAGE(\n       \"Testing Heston model calibration using a flat volatility surface...\");\n\n    SavedSettings backup;\n\n    /* calibrate a Heston model to a constant volatility surface without\n       smile. expected result is a vanishing volatility of the volatility.\n       In addition theta and v0 should be equal to the constant variance */\n\n    Date today = Date::todaysDate();\n    Settings::instance().evaluationDate() = today;\n\n    DayCounter dayCounter = Actual360();\n    Calendar calendar = NullCalendar();\n\n    Handle<YieldTermStructure> riskFreeTS(flatRate(0.04, dayCounter));\n    Handle<YieldTermStructure> dividendTS(flatRate(0.50, dayCounter));\n\n    std::vector<Period> optionMaturities;\n    optionMaturities.push_back(Period(1, Months));\n    optionMaturities.push_back(Period(2, Months));\n    optionMaturities.push_back(Period(3, Months));\n    optionMaturities.push_back(Period(6, Months));\n    optionMaturities.push_back(Period(9, Months));\n    optionMaturities.push_back(Period(1, Years));\n    optionMaturities.push_back(Period(2, Years));\n\n    std::vector<boost::shared_ptr<CalibrationHelper> > options;\n    Handle<Quote> s0(boost::shared_ptr<Quote>(new SimpleQuote(1.0)));\n    Handle<Quote> vol(boost::shared_ptr<Quote>(new SimpleQuote(0.1)));\n    Volatility volatility = vol->value();\n\n    for (Size i = 0; i < optionMaturities.size(); ++i) {\n        for (Real moneyness = -1.0; moneyness < 2.0; moneyness += 1.0) {\n            // FLOATING_POINT_EXCEPTION\n            const Time tau = dayCounter.yearFraction(\n                                 riskFreeTS->referenceDate(),\n                                 calendar.advance(riskFreeTS->referenceDate(),\n                                                  optionMaturities[i]));\n        const Real fwdPrice = s0->value()*dividendTS->discount(tau)\n                            / riskFreeTS->discount(tau);\n        const Real strikePrice = fwdPrice * std::exp(-moneyness * volatility\n                                                     * std::sqrt(tau));\n\n        options.push_back(boost::shared_ptr<CalibrationHelper>(\n                          new HestonModelHelper(optionMaturities[i], calendar,\n                                                s0, strikePrice, vol,\n                                                riskFreeTS, dividendTS)));\n        }\n    }\n\n    for (Real sigma = 0.1; sigma < 0.7; sigma += 0.2) {\n        const Real v0=0.01;\n        const Real kappa=0.2;\n        const Real theta=0.02;\n        const Real rho=-0.75;\n\n        boost::shared_ptr<HestonProcess> process(\n            new HestonProcess(riskFreeTS, dividendTS,\n                              s0, v0, kappa, theta, sigma, rho));\n\n        boost::shared_ptr<HestonModel> model(new HestonModel(process));\n        boost::shared_ptr<PricingEngine> engine(\n                                         new AnalyticHestonEngine(model, 96));\n\n        for (Size i = 0; i < options.size(); ++i)\n            options[i]->setPricingEngine(engine);\n\n        LevenbergMarquardt om(1e-8, 1e-8, 1e-8);\n        model->calibrate(options, om, EndCriteria(400, 40, 1.0e-8,\n                                                  1.0e-8, 1.0e-8));\n\n        Real tolerance = 3.0e-3;\n\n        if (model->sigma() > tolerance) {\n            BOOST_ERROR(\"Failed to reproduce expected sigma\"\n                        << \"\\n    calculated: \" << model->sigma()\n                        << \"\\n    expected:   \" << 0.0\n                        << \"\\n    tolerance:  \" << tolerance);\n        }\n\n        if (std::fabs(model->kappa()\n                  *(model->theta()-volatility*volatility)) > tolerance) {\n            BOOST_ERROR(\"Failed to reproduce expected theta\"\n                        << \"\\n    calculated: \" << model->theta()\n                        << \"\\n    expected:   \" << volatility*volatility);\n        }\n\n        if (std::fabs(model->v0()-volatility*volatility) > tolerance) {\n            BOOST_ERROR(\"Failed to reproduce expected v0\"\n                        << \"\\n    calculated: \" << model->v0()\n                        << \"\\n    expected:   \" << volatility*volatility);\n        }\n    }\n}\n\n\nvoid HestonModelTest::testDAXCalibration() {\n\n    BOOST_TEST_MESSAGE(\n             \"Testing Heston model calibration using DAX volatility data...\");\n\n    SavedSettings backup;\n\n    Date settlementDate(5, July, 2002);\n    Settings::instance().evaluationDate() = settlementDate;\n\n    CalibrationMarketData marketData = getDAXCalibrationMarketData();\n    \n    const Handle<YieldTermStructure> riskFreeTS = marketData.riskFreeTS;\n    const Handle<YieldTermStructure> dividendTS = marketData.dividendYield;\n    const Handle<Quote> s0 = marketData.s0;\n\n    const std::vector<boost::shared_ptr<CalibrationHelper> > options\n                                                    = marketData.options;\n\n    const Real v0=0.1;\n    const Real kappa=1.0;\n    const Real theta=0.1;\n    const Real sigma=0.5;\n    const Real rho=-0.5;\n\n    const boost::shared_ptr<HestonProcess> process(\n        boost::make_shared<HestonProcess>(\n            riskFreeTS, dividendTS, s0, v0, kappa, theta, sigma, rho));\n\n    const boost::shared_ptr<HestonModel> model(\n        boost::make_shared<HestonModel>(process));\n\n    const boost::shared_ptr<PricingEngine> engines[] = {\n        boost::make_shared<AnalyticHestonEngine>(model, 64),\n        boost::make_shared<COSHestonEngine>(model, 12, 75)\n    };\n\n    const Array params = model->params();\n    for (Size j=0; j < LENGTH(engines); ++j) {\n        model->setParams(params);\n        for (Size i = 0; i < options.size(); ++i)\n            options[i]->setPricingEngine(engines[j]);\n\n        LevenbergMarquardt om(1e-8, 1e-8, 1e-8);\n        model->calibrate(options, om,\n                         EndCriteria(400, 40, 1.0e-8, 1.0e-8, 1.0e-8));\n\n        Real sse = 0;\n        for (Size i = 0; i < 13*8; ++i) {\n            const Real diff = options[i]->calibrationError()*100.0;\n            sse += diff*diff;\n        }\n        Real expected = 177.2; //see article by A. Sepp.\n        if (std::fabs(sse - expected) > 1.0) {\n            BOOST_FAIL(\"Failed to reproduce calibration error\"\n                       << \"\\n    calculated: \" << sse\n                       << \"\\n    expected:   \" << expected);\n        }\n    }\n}\n\nvoid HestonModelTest::testAnalyticVsBlack() {\n    BOOST_TEST_MESSAGE(\"Testing analytic Heston engine against Black formula...\");\n\n    SavedSettings backup;\n\n    Date settlementDate = Date::todaysDate();\n    Settings::instance().evaluationDate() = settlementDate;\n    DayCounter dayCounter = ActualActual();\n    Date exerciseDate = settlementDate + 6*Months;\n\n    boost::shared_ptr<StrikedTypePayoff> payoff(\n                                     new PlainVanillaPayoff(Option::Put, 30));\n    boost::shared_ptr<Exercise> exercise(new EuropeanExercise(exerciseDate));\n\n    Handle<YieldTermStructure> riskFreeTS(flatRate(0.1, dayCounter));\n    Handle<YieldTermStructure> dividendTS(flatRate(0.04, dayCounter));\n\n    Handle<Quote> s0(boost::shared_ptr<Quote>(new SimpleQuote(32.0)));\n\n    const Real v0=0.05;\n    const Real kappa=5.0;\n    const Real theta=0.05;\n    const Real sigma=1.0e-4;\n    const Real rho=0.0;\n\n    boost::shared_ptr<HestonProcess> process(new HestonProcess(\n                   riskFreeTS, dividendTS, s0, v0, kappa, theta, sigma, rho));\n\n    VanillaOption option(payoff, exercise);\n    // FLOATING_POINT_EXCEPTION\n    boost::shared_ptr<PricingEngine> engine(new AnalyticHestonEngine(\n              boost::shared_ptr<HestonModel>(new HestonModel(process)), 144));\n\n    option.setPricingEngine(engine);\n    Real calculated = option.NPV();\n\n    Real yearFraction = dayCounter.yearFraction(settlementDate, exerciseDate);\n    Real forwardPrice = 32*std::exp((0.1-0.04)*yearFraction);\n    Real expected = blackFormula(payoff->optionType(), payoff->strike(),\n        forwardPrice, std::sqrt(0.05*yearFraction)) *\n                                            std::exp(-0.1*yearFraction);\n    Real error = std::fabs(calculated - expected);\n    Real tolerance = 2.0e-7;\n    if (error > tolerance) {\n        BOOST_FAIL(\"failed to reproduce Black price with AnalyticHestonEngine\"\n                   << \"\\n    calculated: \" << calculated\n                   << \"\\n    expected:   \" << expected\n                   << \"\\n    error:      \" << QL_SCIENTIFIC << error);\n    }\n\n    engine = boost::shared_ptr<PricingEngine>(new FdHestonVanillaEngine(\n              boost::shared_ptr<HestonModel>(new HestonModel(process)),\n              200,200,100));\n    option.setPricingEngine(engine);\n\n    calculated = option.NPV();\n    error = std::fabs(calculated - expected);\n    tolerance = 1.0e-3;\n    if (error > tolerance) {\n        BOOST_FAIL(\"failed to reproduce Black price with FdHestonVanillaEngine\"\n                   << \"\\n    calculated: \" << calculated\n                   << \"\\n    expected:   \" << expected\n                   << \"\\n    error:      \" << QL_SCIENTIFIC << error);\n    }\n\n}\n\n\nvoid HestonModelTest::testAnalyticVsCached() {\n    BOOST_TEST_MESSAGE(\"Testing analytic Heston engine against cached values...\");\n\n    SavedSettings backup;\n\n    Date settlementDate(27, December, 2004);\n    Settings::instance().evaluationDate() = settlementDate;\n    DayCounter dayCounter = ActualActual();\n    Date exerciseDate(28, March, 2005);\n\n    boost::shared_ptr<StrikedTypePayoff> payoff(\n                                  new PlainVanillaPayoff(Option::Call, 1.05));\n    boost::shared_ptr<Exercise> exercise(new EuropeanExercise(exerciseDate));\n\n    Handle<YieldTermStructure> riskFreeTS(flatRate(0.0225, dayCounter));\n    Handle<YieldTermStructure> dividendTS(flatRate(0.02, dayCounter));\n\n    Handle<Quote> s0(boost::shared_ptr<Quote>(new SimpleQuote(1.0)));\n    const Real v0 = 0.1;\n    const Real kappa = 3.16;\n    const Real theta = 0.09;\n    const Real sigma = 0.4;\n    const Real rho = -0.2;\n\n    boost::shared_ptr<HestonProcess> process(new HestonProcess(\n                   riskFreeTS, dividendTS, s0, v0, kappa, theta, sigma, rho));\n\n    VanillaOption option(payoff, exercise);\n\n    boost::shared_ptr<AnalyticHestonEngine> engine(new AnalyticHestonEngine(\n               boost::shared_ptr<HestonModel>(new HestonModel(process)), 64));\n\n    option.setPricingEngine(engine);\n\n    Real expected1 = 0.0404774515;\n    Real calculated1 = option.NPV();\n    Real tolerance = 1.0e-8;\n\n    if (std::fabs(calculated1 - expected1) > tolerance) {\n        BOOST_ERROR(\"Failed to reproduce cached analytic price\"\n                    << \"\\n    calculated: \" << calculated1\n                    << \"\\n    expected:   \" << expected1);\n    }\n\n\n    // reference values from www.wilmott.com, technical forum\n    // search for \"Heston or VG price check\"\n\n    Real K[] = {0.9,1.0,1.1};\n    Real expected2[] = { 0.1330371,0.0641016, 0.0270645 };\n    Real calculated2[6];\n\n    Size i;\n    for (i = 0; i < 6; ++i) {\n        Date exerciseDate(8+i/3, September, 2005);\n\n        boost::shared_ptr<StrikedTypePayoff> payoff(\n                                new PlainVanillaPayoff(Option::Call, K[i%3]));\n        boost::shared_ptr<Exercise> exercise(\n                                          new EuropeanExercise(exerciseDate));\n\n        Handle<YieldTermStructure> riskFreeTS(flatRate(0.05, dayCounter));\n        Handle<YieldTermStructure> dividendTS(flatRate(0.02, dayCounter));\n\n        Real s = riskFreeTS->discount(0.7)/dividendTS->discount(0.7);\n        Handle<Quote> s0(boost::shared_ptr<Quote>(new SimpleQuote(s)));\n\n        boost::shared_ptr<HestonProcess> process(new HestonProcess(\n                   riskFreeTS, dividendTS, s0, 0.09, 1.2, 0.08, 1.8, -0.45));\n\n        VanillaOption option(payoff, exercise);\n\n        boost::shared_ptr<PricingEngine> engine(new AnalyticHestonEngine(\n                   boost::shared_ptr<HestonModel>(new HestonModel(process))));\n\n        option.setPricingEngine(engine);\n        calculated2[i] = option.NPV();\n    }\n\n    // we are after the value for T=0.7\n    Time t1 = dayCounter.yearFraction(settlementDate, Date(8, September,2005));\n    Time t2 = dayCounter.yearFraction(settlementDate, Date(9, September,2005));\n\n    for (i = 0; i < 3; ++i) {\n        const Real interpolated =\n            calculated2[i]+(calculated2[i+3]-calculated2[i])/(t2-t1)*(0.7-t1);\n\n        if (std::fabs(interpolated - expected2[i]) > 100*tolerance) {\n            BOOST_ERROR(\"Failed to reproduce cached analytic prices:\"\n                        << \"\\n    calculated: \" << interpolated\n                        << \"\\n    expected:   \" << expected2[i] );\n        }\n    }\n}\n\n\nvoid HestonModelTest::testMcVsCached() {\n    BOOST_TEST_MESSAGE(\n                \"Testing Monte Carlo Heston engine against cached values...\");\n\n    SavedSettings backup;\n\n    Date settlementDate(27, December, 2004);\n    Settings::instance().evaluationDate() = settlementDate;\n\n    DayCounter dayCounter = ActualActual();\n    Date exerciseDate(28, March, 2005);\n\n    boost::shared_ptr<StrikedTypePayoff> payoff(\n                                   new PlainVanillaPayoff(Option::Put, 1.05));\n    boost::shared_ptr<Exercise> exercise(new EuropeanExercise(exerciseDate));\n\n    Handle<YieldTermStructure> riskFreeTS(flatRate(0.7, dayCounter));\n    Handle<YieldTermStructure> dividendTS(flatRate(0.4, dayCounter));\n\n    Handle<Quote> s0(boost::shared_ptr<Quote>(new SimpleQuote(1.05)));\n\n    boost::shared_ptr<HestonProcess> process(new HestonProcess(\n                   riskFreeTS, dividendTS, s0, 0.3, 1.16, 0.2, 0.8, 0.8,\n                   HestonProcess::QuadraticExponentialMartingale));\n\n    VanillaOption option(payoff, exercise);\n\n    boost::shared_ptr<PricingEngine> engine;\n    engine = MakeMCEuropeanHestonEngine<PseudoRandom>(process)\n        .withStepsPerYear(11)\n        .withAntitheticVariate()\n        .withSamples(50000)\n        .withSeed(1234);\n\n    option.setPricingEngine(engine);\n\n    Real expected = 0.0632851308977151;\n    Real calculated = option.NPV();\n    Real errorEstimate = option.errorEstimate();\n    Real tolerance = 7.5e-4;\n\n    if (std::fabs(calculated - expected) > 2.34*errorEstimate) {\n        BOOST_ERROR(\"Failed to reproduce cached price\"\n                    << \"\\n    calculated: \" << calculated\n                    << \"\\n    expected:   \" << expected\n                    << \" +/- \" << errorEstimate);\n    }\n\n    if (errorEstimate > tolerance) {\n        BOOST_ERROR(\"failed to reproduce error estimate\"\n                    << \"\\n    calculated: \" << errorEstimate\n                    << \"\\n    expected:   \" << tolerance);\n    }\n}\n\nvoid HestonModelTest::testFdBarrierVsCached() {\n    BOOST_TEST_MESSAGE(\"Testing FD barrier Heston engine against cached values...\");\n\n    SavedSettings backup;\n\n    DayCounter dc = Actual360();\n    Date today = Date::todaysDate();\n\n    Handle<Quote> s0(boost::shared_ptr<Quote>(new SimpleQuote(100.0)));\n    Handle<YieldTermStructure> rTS(flatRate(today, 0.08, dc));\n    Handle<YieldTermStructure> qTS(flatRate(today, 0.04, dc));\n\n    Date exDate = today + Integer(0.5*360+0.5);\n    boost::shared_ptr<Exercise> exercise(new EuropeanExercise(exDate));\n\n    boost::shared_ptr<StrikedTypePayoff> payoff(new\n            PlainVanillaPayoff(Option::Call, 90.0));\n\n    boost::shared_ptr<HestonProcess> process(new HestonProcess(\n            rTS, qTS, s0, 0.25*0.25, 1.0, 0.25*0.25, 0.001, 0.0));\n\n    boost::shared_ptr<PricingEngine> engine;\n    engine = boost::shared_ptr<PricingEngine>(new FdHestonBarrierEngine(\n                    boost::shared_ptr<HestonModel>(new HestonModel(process)),\n                    200,400,100));\n\n    BarrierOption option(Barrier::DownOut, 95.0, 3.0, payoff, exercise);\n    option.setPricingEngine(engine);\n\n    Real calculated = option.NPV();\n    Real expected = 9.0246;\n    Real error = std::fabs(calculated-expected);\n    if (error > 1.0e-3) {\n        BOOST_FAIL(\"failed to reproduce cached price with FD Barrier engine\"\n                   << \"\\n    calculated: \" << calculated\n                   << \"\\n    expected:   \" << expected\n                   << \"\\n    error:      \" << QL_SCIENTIFIC << error);\n    }\n\n    option = BarrierOption(Barrier::DownIn, 95.0, 3.0, payoff, exercise);\n    option.setPricingEngine(engine);\n\n    calculated = option.NPV();\n    expected = 7.7627;\n    error = std::fabs(calculated-expected);\n    if (error > 1.0e-3) {\n        BOOST_FAIL(\"failed to reproduce cached price with FD Barrier engine\"\n                   << \"\\n    calculated: \" << calculated\n                   << \"\\n    expected:   \" << expected\n                   << \"\\n    error:      \" << QL_SCIENTIFIC << error);\n    }\n}\n\nvoid HestonModelTest::testFdVanillaVsCached() {\n    BOOST_TEST_MESSAGE(\"Testing FD vanilla Heston engine against cached values...\");\n\n    SavedSettings backup;\n\n    Date settlementDate(27, December, 2004);\n    Settings::instance().evaluationDate() = settlementDate;\n\n    DayCounter dayCounter = ActualActual();\n    Date exerciseDate(28, March, 2005);\n\n    boost::shared_ptr<StrikedTypePayoff> payoff(\n                                   new PlainVanillaPayoff(Option::Put, 1.05));\n    boost::shared_ptr<Exercise> exercise(new EuropeanExercise(exerciseDate));\n\n    Handle<YieldTermStructure> riskFreeTS(flatRate(0.7, dayCounter));\n    Handle<YieldTermStructure> dividendTS(flatRate(0.4, dayCounter));\n\n    Handle<Quote> s0(boost::shared_ptr<Quote>(new SimpleQuote(1.05)));\n\n    VanillaOption option(payoff, exercise);\n\n    boost::shared_ptr<HestonProcess> process(new HestonProcess(\n                   riskFreeTS, dividendTS, s0, 0.3, 1.16, 0.2, 0.8, 0.8));\n\n    boost::shared_ptr<PricingEngine> engine;\n    engine = boost::shared_ptr<PricingEngine>(new FdHestonVanillaEngine(\n                    boost::shared_ptr<HestonModel>(new HestonModel(process)),\n                    100,200,100));\n    option.setPricingEngine(engine);\n\n    Real expected = 0.06325;\n    Real calculated = option.NPV();\n    Real error = std::fabs(calculated - expected);\n    Real tolerance = 1.0e-4;\n\n    if (error > tolerance) {\n        BOOST_FAIL(\"failed to reproduce cached price with FD engine\"\n                   << \"\\n    calculated: \" << calculated\n                   << \"\\n    expected:   \" << expected\n                   << \"\\n    error:      \" << QL_SCIENTIFIC << error);\n    }\n\n    BOOST_TEST_MESSAGE(\"Testing FD vanilla Heston engine for discrete dividends...\");\n\n    payoff = boost::shared_ptr<StrikedTypePayoff>(\n                          new PlainVanillaPayoff(Option::Call, 95.0));\n    s0 = Handle<Quote>(boost::shared_ptr<Quote>(new SimpleQuote(100.0)));\n\n    riskFreeTS = Handle<YieldTermStructure>(flatRate(0.05, dayCounter));\n    dividendTS = Handle<YieldTermStructure>(flatRate(0.0, dayCounter));\n\n    exerciseDate = Date(28, March, 2006);\n    exercise = boost::shared_ptr<Exercise>(new EuropeanExercise(exerciseDate));\n\n    std::vector<Date> dividendDates;\n    std::vector<Real> dividends;\n    for (Date d = settlementDate + 3*Months;\n              d < exercise->lastDate();\n              d += 6*Months) {\n        dividendDates.push_back(d);\n        dividends.push_back(1.0);\n    }\n\n    DividendVanillaOption divOption(payoff, exercise,\n                                    dividendDates, dividends);\n    process = boost::shared_ptr<HestonProcess>(new HestonProcess(\n                   riskFreeTS, dividendTS, s0, 0.04, 1.0, 0.04, 0.001, 0.0));\n    engine = boost::shared_ptr<PricingEngine>(new FdHestonVanillaEngine(\n                    boost::shared_ptr<HestonModel>(new HestonModel(process)),\n                    200,400,100));\n    divOption.setPricingEngine(engine);\n    calculated = divOption.NPV();\n    // Value calculated with an independent FD framework, validated with\n    // an independent MC framework\n    expected = 12.946;\n    error = std::fabs(calculated - expected);\n    tolerance = 5.0e-3;\n\n    if (error > tolerance) {\n        BOOST_FAIL(\"failed to reproduce discrete dividend price with FD engine\"\n                   << \"\\n    calculated: \" << calculated\n                   << \"\\n    expected:   \" << expected\n                   << \"\\n    error:      \" << QL_SCIENTIFIC << error);\n    }\n\n    BOOST_TEST_MESSAGE(\"Testing FD vanilla Heston engine for american exercise...\");\n\n    dividendTS = Handle<YieldTermStructure>(flatRate(0.03, dayCounter));\n    process = boost::shared_ptr<HestonProcess>(new HestonProcess(\n                   riskFreeTS, dividendTS, s0, 0.04, 1.0, 0.04, 0.001, 0.0));\n    engine = boost::shared_ptr<PricingEngine>(new FdHestonVanillaEngine(\n                    boost::shared_ptr<HestonModel>(new HestonModel(process)),\n                    200,400,100));\n    payoff = boost::shared_ptr<StrikedTypePayoff>(\n                          new PlainVanillaPayoff(Option::Put, 95.0));\n    exercise = boost::shared_ptr<Exercise>(new AmericanExercise(\n            settlementDate, exerciseDate));\n    option = VanillaOption(payoff, exercise);\n    option.setPricingEngine(engine);\n    calculated = option.NPV();\n\n    Handle<BlackVolTermStructure> volTS(flatVol(settlementDate, 0.2,\n                                                  dayCounter));\n    boost::shared_ptr<BlackScholesMertonProcess> ref_process(\n        new BlackScholesMertonProcess(s0, dividendTS, riskFreeTS, volTS));\n    boost::shared_ptr<PricingEngine> ref_engine(\n                  new FDAmericanEngine<CrankNicolson>(ref_process, 200, 400));\n    option.setPricingEngine(ref_engine);\n    expected = option.NPV();\n\n    error = std::fabs(calculated - expected);\n    tolerance = 1.0e-3;\n\n    if (error > tolerance) {\n        BOOST_FAIL(\"failed to reproduce american option price with FD engine\"\n                   << \"\\n    calculated: \" << calculated\n                   << \"\\n    expected:   \" << expected\n                   << \"\\n    error:      \" << QL_SCIENTIFIC << error);\n    }\n}\n\nnamespace {\n    struct HestonProcessDiscretizationDesc {\n        HestonProcess::Discretization discretization;\n        Size nSteps;\n        std::string name;\n    };\n}\n\nvoid HestonModelTest::testKahlJaeckelCase() {\n    BOOST_TEST_MESSAGE(\n          \"Testing MC and FD Heston engines for the Kahl-Jaeckel example...\");\n\n    /* Example taken from Wilmott mag (Sept. 2005).\n       \"Not-so-complex logarithms in the Heston model\",\n       Example was also discussed within the Wilmott thread\n       \"QuantLib code is very high quatlity\"\n    */\n\n    SavedSettings backup;\n\n    Date settlementDate(30, March, 2007);\n    Settings::instance().evaluationDate() = settlementDate;\n\n    DayCounter dayCounter = ActualActual();\n    Date exerciseDate(30, March, 2017);\n\n    const boost::shared_ptr<StrikedTypePayoff> payoff(\n        new PlainVanillaPayoff(Option::Call, 200));\n    const boost::shared_ptr<Exercise> exercise(\n        new EuropeanExercise(exerciseDate));\n\n    VanillaOption option(payoff, exercise);\n\n\n    Handle<YieldTermStructure> riskFreeTS(flatRate(0.0, dayCounter));\n    Handle<YieldTermStructure> dividendTS(flatRate(0.0, dayCounter));\n\n    Handle<Quote> s0(boost::shared_ptr<Quote>(new SimpleQuote(100)));\n\n    const Real v0    = 0.16;\n    const Real theta = v0;\n    const Real kappa = 1.0;\n    const Real sigma = 2.0;\n    const Real rho   =-0.8;\n\n\n    const HestonProcessDiscretizationDesc descriptions[] = {\n        { HestonProcess::NonCentralChiSquareVariance, 10,\n          \"NonCentralChiSquareVariance\" },\n        { HestonProcess::QuadraticExponentialMartingale, 100,\n          \"QuadraticExponentialMartingale\" },\n    };\n\n    const Real tolerance = 0.1;\n    const Real expected = 4.95212;\n\n    for (Size i=0; i < LENGTH(descriptions); ++i) {\n        const boost::shared_ptr<HestonProcess> process(\n            new HestonProcess(riskFreeTS, dividendTS, s0, v0,\n                              kappa, theta, sigma, rho,\n                              descriptions[i].discretization));\n\n        const boost::shared_ptr<PricingEngine> engine =\n            MakeMCEuropeanHestonEngine<PseudoRandom>(process)\n            .withSteps(descriptions[i].nSteps)\n            .withAntitheticVariate()\n            .withAbsoluteTolerance(tolerance)\n            .withSeed(1234);\n        option.setPricingEngine(engine);\n\n        const Real calculated = option.NPV();\n        const Real errorEstimate = option.errorEstimate();\n\n        if (std::fabs(calculated - expected) > 2.34*errorEstimate) {\n            BOOST_ERROR(\"Failed to reproduce cached price with MC engine\"\n                        << \"\\n    discretization: \" << descriptions[i].name\n                        << \"\\n    expected:       \" << expected\n                        << \"\\n    calculated:     \" << calculated\n                        << \" +/- \" << errorEstimate);\n        }\n\n        if (errorEstimate > tolerance) {\n            BOOST_ERROR(\"failed to reproduce error estimate with MC engine\"\n                        << \"\\n    discretization: \" << descriptions[i].name\n                        << \"\\n    calculated    : \" << errorEstimate\n                        << \"\\n    expected      :   \" << tolerance);\n        }\n    }\n\n    option.setPricingEngine(\n        MakeMCEuropeanHestonEngine<LowDiscrepancy>(\n            boost::shared_ptr<HestonProcess>(\n                new HestonProcess(\n                    riskFreeTS, dividendTS, s0, v0, kappa, theta, sigma, rho,\n                    HestonProcess::BroadieKayaExactSchemeLaguerre)))\n        .withSteps(1)\n        .withSamples(1023));\n\n    Real calculated = option.NPV();\n    if (std::fabs(calculated - expected) > tolerance) {\n        BOOST_ERROR(\"Failed to reproduce cached price with MC engine\"\n                    << \"\\n    discretization: BroadieKayaExactSchemeLobatto\"\n                    << \"\\n    calculated:     \" << calculated\n                    << \"\\n    expected:       \" << expected\n                    << \"\\n    tolerance:      \" << tolerance);\n    }\n\n\n    const boost::shared_ptr<HestonModel> hestonModel(\n         new HestonModel(\n             boost::shared_ptr<HestonProcess>(new HestonProcess(\n                riskFreeTS, dividendTS, s0, v0,\n                kappa, theta, sigma, rho))));\n\n    option.setPricingEngine(boost::shared_ptr<PricingEngine>(\n        new FdHestonVanillaEngine(hestonModel, 200, 400, 100)));\n\n    calculated = option.NPV();\n    Real error = std::fabs(calculated - expected);\n    if (error > 5.0e-2) {\n        BOOST_FAIL(\"failed to reproduce cached price with FD engine\"\n                   << \"\\n    calculated: \" << calculated\n                   << \"\\n    expected:   \" << expected\n                   << \"\\n    error:      \" << QL_SCIENTIFIC << error);\n    }\n\n    option.setPricingEngine(\n        boost::shared_ptr<AnalyticHestonEngine>(\n            new AnalyticHestonEngine(hestonModel, 1e-6, 1000)));\n\n    calculated = option.NPV();\n    error = std::fabs(calculated - expected);\n\n    if (error > 0.00002) {\n        BOOST_FAIL(\"failed to reproduce cached price with \"\n                   \"GaussLobatto engine\"\n                   << \"\\n    calculated: \" << calculated\n                   << \"\\n    expected:   \" << expected\n                   << \"\\n    error:      \" << QL_SCIENTIFIC << error);\n    }\n\n    option.setPricingEngine(\n        boost::make_shared<COSHestonEngine>(hestonModel, 16, 400));\n    calculated = option.NPV();\n    error = std::fabs(calculated - expected);\n\n    if (error > 0.00002) {\n        BOOST_FAIL(\"failed to reproduce cached price with \"\n                   \"Cosine engine\"\n                   << \"\\n    calculated: \" << calculated\n                   << \"\\n    expected:   \" << expected\n                   << \"\\n    error:      \" << QL_SCIENTIFIC << error);\n    }\n}\n\nnamespace {\n    struct HestonParameter {\n        Real v0, kappa, theta, sigma, rho; };\n}\n\nvoid HestonModelTest::testDifferentIntegrals() {\n    BOOST_TEST_MESSAGE(\n       \"Testing different numerical Heston integration algorithms...\");\n\n    SavedSettings backup;\n\n    const Date settlementDate(27, December, 2004);\n    Settings::instance().evaluationDate() = settlementDate;\n\n    const DayCounter dayCounter = ActualActual();\n\n    Handle<YieldTermStructure> riskFreeTS(flatRate(0.05, dayCounter));\n    Handle<YieldTermStructure> dividendTS(flatRate(0.03, dayCounter));\n\n    const Real strikes[] = { 0.5, 0.7, 1.0, 1.25, 1.5, 2.0 };\n    const Integer maturities[] = { 1, 2, 3, 12, 60, 120, 360};\n    const Option::Type types[] ={ Option::Put, Option::Call };\n\n    const HestonParameter equityfx      = { 0.07, 2.0, 0.04, 0.55, -0.8 };\n    const HestonParameter highCorr      = { 0.07, 1.0, 0.04, 0.55,  0.995 };\n    const HestonParameter lowVolOfVol   = { 0.07, 1.0, 0.04, 0.025, -0.75 };\n    const HestonParameter highVolOfVol  = { 0.07, 1.0, 0.04, 5.0, -0.75 };\n    const HestonParameter kappaEqSigRho = { 0.07, 0.4, 0.04, 0.5, 0.8 };\n\n    std::vector<HestonParameter> params;\n    params.push_back(equityfx);\n    params.push_back(highCorr);\n    params.push_back(lowVolOfVol);\n    params.push_back(highVolOfVol);\n    params.push_back(kappaEqSigRho);\n\n    const Real tol[] = { 1e-3, 1e-3, 0.2, 0.01, 1e-3 };\n\n    for (std::vector<HestonParameter>::const_iterator iter = params.begin();\n         iter != params.end(); ++iter) {\n\n        Handle<Quote> s0(boost::shared_ptr<Quote>(new SimpleQuote(1.0)));\n        boost::shared_ptr<HestonProcess> process(new HestonProcess(\n            riskFreeTS, dividendTS,\n            s0, iter->v0, iter->kappa,\n            iter->theta, iter->sigma, iter->rho));\n\n        boost::shared_ptr<HestonModel> model(new HestonModel(process));\n\n        boost::shared_ptr<AnalyticHestonEngine> lobattoEngine(\n                              new AnalyticHestonEngine(model, 1e-10,\n                                                       1000000));\n        boost::shared_ptr<AnalyticHestonEngine> laguerreEngine(\n                                        new AnalyticHestonEngine(model, 128));\n        boost::shared_ptr<AnalyticHestonEngine> legendreEngine(\n            new AnalyticHestonEngine(\n                model, AnalyticHestonEngine::Gatheral,\n                AnalyticHestonEngine::Integration::gaussLegendre(512)));\n        boost::shared_ptr<AnalyticHestonEngine> chebyshevEngine(\n            new AnalyticHestonEngine(\n                model, AnalyticHestonEngine::Gatheral,\n                AnalyticHestonEngine::Integration::gaussChebyshev(512)));\n        boost::shared_ptr<AnalyticHestonEngine> chebyshev2ndEngine(\n            new AnalyticHestonEngine(\n                model, AnalyticHestonEngine::Gatheral,\n                AnalyticHestonEngine::Integration::gaussChebyshev2nd(512)));\n\n        Real maxLegendreDiff    = 0.0;\n        Real maxChebyshevDiff   = 0.0;\n        Real maxChebyshev2ndDiff= 0.0;\n        Real maxLaguerreDiff    = 0.0;\n\n        for (Size i=0; i < LENGTH(maturities); ++i) {\n            boost::shared_ptr<Exercise> exercise(\n                new EuropeanExercise(settlementDate\n                                     + Period(maturities[i], Months)));\n\n            for (Size j=0; j < LENGTH(strikes); ++j) {\n                for (Size k=0; k < LENGTH(types); ++k) {\n\n                    boost::shared_ptr<StrikedTypePayoff> payoff(\n                        new PlainVanillaPayoff(types[k], strikes[j]));\n\n                    VanillaOption option(payoff, exercise);\n\n                    option.setPricingEngine(lobattoEngine);\n                    const Real lobattoNPV = option.NPV();\n\n                    option.setPricingEngine(laguerreEngine);\n                    const Real laguerre = option.NPV();\n\n                    option.setPricingEngine(legendreEngine);\n                    const Real legendre = option.NPV();\n\n                    option.setPricingEngine(chebyshevEngine);\n                    const Real chebyshev = option.NPV();\n\n                    option.setPricingEngine(chebyshev2ndEngine);\n                    const Real chebyshev2nd = option.NPV();\n\n                    maxLaguerreDiff\n                        = std::max(maxLaguerreDiff,\n                                   std::fabs(lobattoNPV-laguerre));\n                    maxLegendreDiff\n                        = std::max(maxLegendreDiff,\n                                   std::fabs(lobattoNPV-legendre));\n                    maxChebyshevDiff\n                        = std::max(maxChebyshevDiff,\n                                   std::fabs(lobattoNPV-chebyshev));\n                    maxChebyshev2ndDiff\n                        = std::max(maxChebyshev2ndDiff,\n                                   std::fabs(lobattoNPV-chebyshev2nd));\n\n                }\n            }\n        }\n        const Real maxDiff = std::max(std::max(\n            std::max(maxLaguerreDiff,maxLegendreDiff),\n                                     maxChebyshevDiff), maxChebyshev2ndDiff);\n\n        const Real tr = tol[iter - params.begin()];\n        if (maxDiff > tr) {\n            BOOST_ERROR(\"Failed to reproduce Heston pricing values \"\n                        \"within given tolerance\"\n                        << \"\\n    maxDifference: \" << maxDiff\n                        << \"\\n    tolerance:     \" << tr);\n        }\n    }\n}\n\nvoid HestonModelTest::testMultipleStrikesEngine() {\n    BOOST_TEST_MESSAGE(\"Testing multiple-strikes FD Heston engine...\");\n\n    SavedSettings backup;\n\n    Date settlementDate(27, December, 2004);\n    Settings::instance().evaluationDate() = settlementDate;\n\n    DayCounter dayCounter = ActualActual();\n    Date exerciseDate(28, March, 2006);\n\n    boost::shared_ptr<Exercise> exercise(new EuropeanExercise(exerciseDate));\n\n    Handle<YieldTermStructure> riskFreeTS(flatRate(0.06, dayCounter));\n    Handle<YieldTermStructure> dividendTS(flatRate(0.02, dayCounter));\n\n    Handle<Quote> s0(boost::shared_ptr<Quote>(new SimpleQuote(1.05)));\n\n    boost::shared_ptr<HestonProcess> process(new HestonProcess(\n                     riskFreeTS, dividendTS, s0, 0.16, 2.5, 0.09, 0.8, -0.8));\n    boost::shared_ptr<HestonModel> model(new HestonModel(process));\n\n    std::vector<Real> strikes;\n    strikes.push_back(1.0);  strikes.push_back(0.5);\n    strikes.push_back(0.75); strikes.push_back(1.5); strikes.push_back(2.0);\n\n    boost::shared_ptr<FdHestonVanillaEngine> singleStrikeEngine(\n                             new FdHestonVanillaEngine(model, 20, 400, 50));\n    boost::shared_ptr<FdHestonVanillaEngine> multiStrikeEngine(\n                             new FdHestonVanillaEngine(model, 20, 400, 50));\n    multiStrikeEngine->enableMultipleStrikesCaching(strikes);\n\n    Real relTol = 5e-3;\n    for (Size i=0; i < strikes.size(); ++i) {\n        boost::shared_ptr<StrikedTypePayoff> payoff(\n                           new PlainVanillaPayoff(Option::Put, strikes[i]));\n\n        VanillaOption aOption(payoff, exercise);\n        aOption.setPricingEngine(multiStrikeEngine);\n\n        Real npvCalculated   = aOption.NPV();\n        Real deltaCalculated = aOption.delta();\n        Real gammaCalculated = aOption.gamma();\n        Real thetaCalculated = aOption.theta();\n\n        aOption.setPricingEngine(singleStrikeEngine);\n        Real npvExpected   = aOption.NPV();\n        Real deltaExpected = aOption.delta();\n        Real gammaExpected = aOption.gamma();\n        Real thetaExpected = aOption.theta();\n\n        if (std::fabs(npvCalculated-npvExpected)/npvExpected > relTol) {\n            BOOST_FAIL(\"failed to reproduce price with FD multi strike engine\"\n                       << \"\\n    calculated: \" << npvCalculated\n                       << \"\\n    expected:   \" << npvExpected\n                       << \"\\n    error:      \" << QL_SCIENTIFIC << relTol);\n        }\n        if (std::fabs(deltaCalculated-deltaExpected)/deltaExpected > relTol) {\n            BOOST_FAIL(\"failed to reproduce delta with FD multi strike engine\"\n                       << \"\\n    calculated: \" << deltaCalculated\n                       << \"\\n    expected:   \" << deltaExpected\n                       << \"\\n    error:      \" << QL_SCIENTIFIC << relTol);\n        }\n        if (std::fabs(gammaCalculated-gammaExpected)/gammaExpected > relTol) {\n            BOOST_FAIL(\"failed to reproduce gamma with FD multi strike engine\"\n                       << \"\\n    calculated: \" << gammaCalculated\n                       << \"\\n    expected:   \" << gammaExpected\n                       << \"\\n    error:      \" << QL_SCIENTIFIC << relTol);\n        }\n        if (std::fabs(thetaCalculated-thetaExpected)/thetaExpected > relTol) {\n            BOOST_FAIL(\"failed to reproduce theta with FD multi strike engine\"\n                       << \"\\n    calculated: \" << thetaCalculated\n                       << \"\\n    expected:   \" << thetaExpected\n                       << \"\\n    error:      \" << QL_SCIENTIFIC << relTol);\n        }\n    }\n}\n\n\n\nvoid HestonModelTest::testAnalyticPiecewiseTimeDependent() {\n    BOOST_TEST_MESSAGE(\"Testing analytic piecewise time dependent Heston prices...\");\n\n    SavedSettings backup;\n\n    Date settlementDate(27, December, 2004);\n    Settings::instance().evaluationDate() = settlementDate;\n    DayCounter dayCounter = ActualActual();\n    Date exerciseDate(28, March, 2005);\n\n    boost::shared_ptr<StrikedTypePayoff> payoff(\n                                  new PlainVanillaPayoff(Option::Call, 1.0));\n    boost::shared_ptr<Exercise> exercise(new EuropeanExercise(exerciseDate));\n\n    std::vector<Date> dates; \n    dates.push_back(settlementDate); dates.push_back(Date(01, January, 2007));\n    std::vector<Rate> irates;\n    irates.push_back(0.0); irates.push_back(0.2);\n    Handle<YieldTermStructure> riskFreeTS(\n            boost::shared_ptr<YieldTermStructure>(\n                                    new ZeroCurve(dates, irates, dayCounter)));\n\n    std::vector<Rate> qrates;\n    qrates.push_back(0.0); qrates.push_back(0.3);\n    Handle<YieldTermStructure> dividendTS(\n            boost::shared_ptr<YieldTermStructure>(\n                                    new ZeroCurve(dates, qrates, dayCounter)));\n    \n\n    const Real v0 = 0.1;\n    Handle<Quote> s0(boost::shared_ptr<Quote>(new SimpleQuote(1.0)));\n\n    ConstantParameter theta(0.09, PositiveConstraint());\n    ConstantParameter kappa(3.16, PositiveConstraint());\n    ConstantParameter sigma(4.40, PositiveConstraint());\n    ConstantParameter rho  (-0.8, BoundaryConstraint(-1.0, 1.0));\n\n    boost::shared_ptr<PiecewiseTimeDependentHestonModel> model(\n        new PiecewiseTimeDependentHestonModel(riskFreeTS, dividendTS,\n                                              s0, v0, theta, kappa, \n                                              sigma, rho, TimeGrid(20.0, 2)));\n    \n    VanillaOption option(payoff, exercise);\n    option.setPricingEngine(boost::shared_ptr<PricingEngine>(\n                                           new AnalyticPTDHestonEngine(model)));\n\n    const Real calculated = option.NPV();\n    boost::shared_ptr<HestonProcess> hestonProcess(\n        new HestonProcess(riskFreeTS, dividendTS, s0, v0,\n                          kappa(0.0), theta(0.0), sigma(0.0), rho(0.0)));\n    boost::shared_ptr<HestonModel> hestonModel(new HestonModel(hestonProcess));\n    option.setPricingEngine(boost::shared_ptr<PricingEngine>(\n                                    new AnalyticHestonEngine(hestonModel)));\n    \n    const Real expected = option.NPV();\n    \n    if (std::fabs(calculated-expected) > 1e-12) {\n        BOOST_ERROR(\"failed to reproduce heston prices \"\n                   << \"\\n    calculated: \" << calculated\n                   << \"\\n    expected:   \" << expected);\n    }\n}\n\nvoid HestonModelTest::testDAXCalibrationOfTimeDependentModel() {\n    BOOST_TEST_MESSAGE(\n             \"Testing time-dependent Heston model calibration...\");\n\n    SavedSettings backup;\n\n    Date settlementDate(5, July, 2002);\n    Settings::instance().evaluationDate() = settlementDate;\n\n    CalibrationMarketData marketData = getDAXCalibrationMarketData();\n    \n    const Handle<YieldTermStructure> riskFreeTS = marketData.riskFreeTS;\n    const Handle<YieldTermStructure> dividendTS = marketData.dividendYield;\n    const Handle<Quote> s0 = marketData.s0;\n\n    const std::vector<boost::shared_ptr<CalibrationHelper> > options\n                                                    = marketData.options;\n\n    std::vector<Time> modelTimes;\n    modelTimes.push_back(0.25);\n    modelTimes.push_back(10.0);\n    const TimeGrid modelGrid(modelTimes.begin(), modelTimes.end());\n\n    const Real v0=0.1;\n    ConstantParameter sigma( 0.5, PositiveConstraint());\n    ConstantParameter theta( 0.1, PositiveConstraint());\n    ConstantParameter rho( -0.5, BoundaryConstraint(-1.0, 1.0));\n   \n    std::vector<Time> pTimes(1, 0.25);\n    PiecewiseConstantParameter kappa(pTimes, PositiveConstraint());\n    \n    for (Size i=0; i < pTimes.size()+1; ++i) {\n        kappa.setParam(i, 10.0);\n    }\n\n    boost::shared_ptr<PiecewiseTimeDependentHestonModel> model(\n        new PiecewiseTimeDependentHestonModel(riskFreeTS, dividendTS,\n                                              s0, v0, theta, kappa, \n                                              sigma, rho, modelGrid));\n    \n    boost::shared_ptr<PricingEngine> engine(new AnalyticPTDHestonEngine(model));\n    for (Size i = 0; i < options.size(); ++i)\n        options[i]->setPricingEngine(engine);\n\n    LevenbergMarquardt om(1e-8, 1e-8, 1e-8);\n    model->calibrate(options, om, EndCriteria(400, 40, 1.0e-8, 1.0e-8, 1.0e-8));\n\n    Real sse = 0;\n    for (Size i = 0; i < 13*8; ++i) {\n        const Real diff = options[i]->calibrationError()*100.0;\n        sse += diff*diff;\n    }\n    \n    Real expected = 74.4;\n    if (std::fabs(sse - expected) > 1.0) {\n        BOOST_ERROR(\"Failed to reproduce calibration error\"\n                   << \"\\n    calculated: \" << sse\n                   << \"\\n    expected:   \" << expected);\n    }\n}\n\nvoid HestonModelTest::testAlanLewisReferencePrices() {\n    BOOST_TEST_MESSAGE(\"Testing Alan Lewis reference prices...\");\n\n    /*\n     * testing Alan Lewis reference prices posted in\n     * http://wilmott.com/messageview.cfm?catid=34&threadid=90957\n     */\n\n    SavedSettings backup;\n\n    const Date settlementDate(5, July, 2002);\n    Settings::instance().evaluationDate() = settlementDate;\n\n    const Date maturityDate(5, July, 2003);\n    const boost::shared_ptr<Exercise> exercise(\n        new EuropeanExercise(maturityDate));\n\n    const DayCounter dayCounter = Actual365Fixed();\n    const Handle<YieldTermStructure> riskFreeTS(flatRate(0.01, dayCounter));\n    const Handle<YieldTermStructure> dividendTS(flatRate(0.02, dayCounter));\n\n    const Handle<Quote> s0(boost::shared_ptr<Quote>(new SimpleQuote(100.0)));\n\n    const Real v0    =  0.04;\n    const Real rho   = -0.5;\n    const Real sigma =  1.0;\n    const Real kappa =  4.0;\n    const Real theta =  0.25;\n\n    const boost::shared_ptr<HestonProcess> process(new HestonProcess(\n        riskFreeTS, dividendTS, s0, v0, kappa, theta, sigma, rho));\n    const boost::shared_ptr<HestonModel> model(new HestonModel(process));\n\n    const boost::shared_ptr<PricingEngine> laguerreEngine(\n        new AnalyticHestonEngine(model, 128u));\n\n    const boost::shared_ptr<PricingEngine> gaussLobattoEngine(\n        new AnalyticHestonEngine(model, QL_EPSILON, 100000u));\n\n    const boost::shared_ptr<PricingEngine> cosEngine(\n        new COSHestonEngine(model, 20, 400));\n\n    const Real strikes[] = { 80, 90, 100, 110, 120 };\n    const Option::Type types[] = { Option::Put, Option::Call };\n    const boost::shared_ptr<PricingEngine> engines[]\n        = { laguerreEngine, gaussLobattoEngine, cosEngine };\n\n    const Real expectedResults[][2] = {\n        { 7.958878113256768285213263077598987193482161301733,\n          26.774758743998854221382195325726949201687074848341 },\n        { 12.017966707346304987709573290236471654992071308187,\n          20.933349000596710388139445766564068085476194042256 },\n        { 17.055270961270109413522653999411000974895436309183,\n          16.070154917028834278213466703938231827658768230714 },\n        { 23.017825898442800538908781834822560777763225722188,\n          12.132211516709844867860534767549426052805766831181 },\n        { 29.811026202682471843340682293165857439167301370697,\n          9.024913483457835636553375454092357136489051667150  }\n    };\n\n    const Real tol = 1e-12; // 3e-15 works on linux/ia32,\n                            // but keep some buffer for other platforms\n\n    for (Size i=0; i < LENGTH(strikes); ++i) {\n        const Real strike = strikes[i];\n\n        for (Size j=0; j < LENGTH(types); ++j) {\n            const Option::Type type = types[j];\n\n            for (Size k=0; k < LENGTH(engines); ++k) {\n                const boost::shared_ptr<PricingEngine> engine = engines[k];\n\n                const boost::shared_ptr<StrikedTypePayoff> payoff(\n                    new PlainVanillaPayoff(type, strike));\n\n                VanillaOption option(payoff, exercise);\n                option.setPricingEngine(engine);\n\n                const Real expected = expectedResults[i][j];\n                const Real calculated = option.NPV();\n                const Real relError = std::fabs(calculated-expected)/expected;\n\n                if (relError > tol) {\n                    BOOST_ERROR(\n                           \"failed to reproduce Alan Lewis Reference prices \"\n                        << \"\\n    strike     : \" << strike\n                        << \"\\n    option type: \" << type\n                        << \"\\n    engine type: \" << k\n                        << \"\\n    rel. error : \" << relError);\n                }\n            }\n        }\n    }\n}\n\nvoid HestonModelTest::testAnalyticPDFHestonEngine() {\n    BOOST_TEST_MESSAGE(\"Testing analytic PDF Heston engine...\");\n\n    SavedSettings backup;\n\n    const Date settlementDate(5, January, 2014);\n    Settings::instance().evaluationDate() = settlementDate;\n\n    const DayCounter dayCounter = Actual365Fixed();\n    const Handle<YieldTermStructure> riskFreeTS(flatRate(0.07, dayCounter));\n    const Handle<YieldTermStructure> dividendTS(flatRate(0.185, dayCounter));\n\n    const Handle<Quote> s0(boost::shared_ptr<Quote>(new SimpleQuote(100.0)));\n\n    const Real v0    =  0.1;\n    const Real rho   = -0.5;\n    const Real sigma =  1.0;\n    const Real kappa =  4.0;\n    const Real theta =  0.05;\n\n    const boost::shared_ptr<HestonModel> model(\n        new HestonModel(boost::shared_ptr<HestonProcess>(\n            new HestonProcess(riskFreeTS, dividendTS,\n                              s0, v0, kappa, theta, sigma, rho))));\n\n    const Real tol = 1e-6;\n    const boost::shared_ptr<AnalyticPDFHestonEngine> pdfEngine(\n        new AnalyticPDFHestonEngine(model, tol));\n\n    const boost::shared_ptr<PricingEngine> analyticEngine(\n        new AnalyticHestonEngine(model, 192));\n\n    const Date maturityDate(5, July, 2014);\n    const Time maturity = dayCounter.yearFraction(settlementDate, maturityDate);\n    const boost::shared_ptr<Exercise> exercise(\n        new EuropeanExercise(maturityDate));\n\n    // 1. check a plain vanilla call option\n    for (Real strike=40; strike < 190; strike+=20) {\n        const boost::shared_ptr<StrikedTypePayoff> vanillaPayoff(\n            new PlainVanillaPayoff(Option::Call, strike));\n\n        VanillaOption planVanillaOption(vanillaPayoff, exercise);\n\n        planVanillaOption.setPricingEngine(pdfEngine);\n        const Real calculated = planVanillaOption.NPV();\n\n        planVanillaOption.setPricingEngine(analyticEngine);\n        const Real expected = planVanillaOption.NPV();\n\n        if (std::fabs(calculated-expected) > 3*tol) {\n            BOOST_FAIL(\n                   \"failed to reproduce plain vanilla european prices with\"\n                   \" the analytic probability density engine\"\n                << \"\\n    strike     : \" << strike\n                << \"\\n    expected   : \" << expected\n                << \"\\n    calculated : \" << calculated\n                << \"\\n    diff       : \" << std::fabs(calculated-expected)\n                << \"\\n    tol        ; \" << tol);\n        }\n    }\n\n    // 2. digital call option (approx. with a call spread)\n    for (Real strike=40; strike < 190; strike+=10) {\n        VanillaOption digitalOption(\n            boost::shared_ptr<StrikedTypePayoff>(\n                new CashOrNothingPayoff(Option::Call, strike, 1.0)),\n            exercise);\n        digitalOption.setPricingEngine(pdfEngine);\n        const Real calculated = digitalOption.NPV();\n\n        const Real eps = 0.01;\n        VanillaOption longCall(\n            boost::shared_ptr<StrikedTypePayoff>(\n                new PlainVanillaPayoff(Option::Call, strike-eps)),\n            exercise);\n        longCall.setPricingEngine(analyticEngine);\n\n        VanillaOption shortCall(\n            boost::shared_ptr<StrikedTypePayoff>(\n                new PlainVanillaPayoff(Option::Call, strike+eps)),\n            exercise);\n        shortCall.setPricingEngine(analyticEngine);\n\n        const Real expected = (longCall.NPV() - shortCall.NPV())/(2*eps);\n        if (std::fabs(calculated-expected) > tol) {\n            BOOST_FAIL(\n                   \"failed to reproduce european digital prices with\"\n                   \" the analytic probability density engine\"\n                << \"\\n    strike     : \" << strike\n                << \"\\n    expected   : \" << expected\n                << \"\\n    calculated : \" << calculated\n                << \"\\n    diff       : \" << std::fabs(calculated-expected)\n                << \"\\n    tol        : \" << tol);\n        }\n\n        const DiscountFactor d = riskFreeTS->discount(maturityDate);\n        const Real expectedCDF = 1.0 - expected/d;\n        const Real calculatedCDF = pdfEngine->cdf(strike, maturity);\n\n        if (std::fabs(expectedCDF - calculatedCDF) > tol) {\n            BOOST_FAIL(\n                   \"failed to reproduce cumulative distribution function\"\n                << \"\\n    strike        : \" << strike\n                << \"\\n    expected CDF  : \" << expectedCDF\n                << \"\\n    calculated CDF: \" << calculatedCDF\n                << \"\\n    diff          : \"\n                << std::fabs(calculatedCDF-expectedCDF)\n                << \"\\n    tol           : \" << tol);\n\n        }\n    }\n}\n\nvoid HestonModelTest::testExpansionOnAlanLewisReference() {\n    BOOST_TEST_MESSAGE(\"Testing expansion on Alan Lewis reference prices...\");\n\n    SavedSettings backup;\n\n    const Date settlementDate(5, July, 2002);\n    Settings::instance().evaluationDate() = settlementDate;\n\n    const Date maturityDate(5, July, 2003);\n    const boost::shared_ptr<Exercise> exercise =\n        boost::make_shared<EuropeanExercise>(maturityDate);\n\n    const DayCounter dayCounter = Actual365Fixed();\n    const Handle<YieldTermStructure> riskFreeTS(flatRate(0.01, dayCounter));\n    const Handle<YieldTermStructure> dividendTS(flatRate(0.02, dayCounter));\n\n    const Handle<Quote> s0(boost::make_shared<SimpleQuote>(100.0));\n\n    const Real v0    =  0.04;\n    const Real rho   = -0.5;\n    const Real sigma =  1.0;\n    const Real kappa =  4.0;\n    const Real theta =  0.25;\n\n    const boost::shared_ptr<HestonProcess> process =\n        boost::make_shared<HestonProcess>(riskFreeTS, dividendTS, s0, v0,\n                                          kappa, theta, sigma, rho);\n    const boost::shared_ptr<HestonModel> model =\n        boost::make_shared<HestonModel>(process);\n\n    const boost::shared_ptr<PricingEngine> lpp2Engine =\n        boost::make_shared<HestonExpansionEngine>(model,\n                                                  HestonExpansionEngine::LPP2);\n    //don't test Forde as it does not behave well on this example\n    const boost::shared_ptr<PricingEngine> lpp3Engine =\n        boost::make_shared<HestonExpansionEngine>(model,\n                                                  HestonExpansionEngine::LPP3);\n\n    const Real strikes[] = { 80, 90, 100, 110, 120 };\n    const Option::Type types[] = { Option::Put, Option::Call };\n    const boost::shared_ptr<PricingEngine> engines[]\n        = { lpp2Engine, lpp3Engine };\n\n    const Real expectedResults[][2] = {\n        { 7.958878113256768285213263077598987193482161301733,\n          26.774758743998854221382195325726949201687074848341 },\n        { 12.017966707346304987709573290236471654992071308187,\n          20.933349000596710388139445766564068085476194042256 },\n        { 17.055270961270109413522653999411000974895436309183,\n          16.070154917028834278213466703938231827658768230714 },\n        { 23.017825898442800538908781834822560777763225722188,\n          12.132211516709844867860534767549426052805766831181 },\n        { 29.811026202682471843340682293165857439167301370697,\n          9.024913483457835636553375454092357136489051667150  }\n    };\n\n    const Real tol[2] = {1.003e-2, 3.645e-3};\n\n    for (Size i=0; i < LENGTH(strikes); ++i) {\n        const Real strike = strikes[i];\n\n        for (Size j=0; j < LENGTH(types); ++j) {\n            const Option::Type type = types[j];\n\n            for (Size k=0; k < LENGTH(engines); ++k) {\n                const boost::shared_ptr<PricingEngine> engine = engines[k];\n\n                const boost::shared_ptr<StrikedTypePayoff> payoff =\n                    boost::make_shared<PlainVanillaPayoff>(type, strike);\n\n                VanillaOption option(payoff, exercise);\n                option.setPricingEngine(engine);\n\n                const Real expected = expectedResults[i][j];\n                const Real calculated = option.NPV();\n                const Real relError = std::fabs(calculated-expected)/expected;\n\n                if (relError > tol[k]) {\n                    BOOST_ERROR(\n                           \"failed to reproduce Alan Lewis Reference prices \"\n                        << \"\\n    strike     : \" << strike\n                        << \"\\n    option type: \" << type\n                        << \"\\n    engine type: \" << k\n                        << \"\\n    rel. error : \" << relError);\n                }\n            }\n        }\n    }\n}\n\nvoid HestonModelTest::testExpansionOnFordeReference() {\n    BOOST_TEST_MESSAGE(\"Testing expansion on Forde reference prices...\");\n\n    SavedSettings backup;\n\n    const Real forward = 100.0;\n    const Real v0      =  0.04;\n    const Real rho     = -0.4;\n    const Real sigma   =  0.2;\n    const Real kappa   =  1.15;\n    const Real theta   =  0.04;\n\n    const Real terms[] = {0.1, 1.0, 5.0, 10.0};\n\n    const Real strikes[] = { 60, 80, 90, 100, 110, 120, 140 };\n\n    const Real referenceVols[][7] = {\n       {0.27284673574924445, 0.22360758200372477, 0.21023988547031242, 0.1990674789471587, 0.19118230678920461, 0.18721342919371017, 0.1899869903378507},\n       {0.25200775151345, 0.2127275920953156, 0.20286528150874591, 0.19479398358151515, 0.18872591728967686, 0.18470857955411824, 0.18204457060905446},\n       {0.21637821506229973, 0.20077227130455172, 0.19721753043236154, 0.1942233023784151, 0.191693211401571, 0.18955229722896752, 0.18491727548069495},\n       {0.20672925973965342, 0.198583062164427, 0.19668274423922746, 0.1950420231354201, 0.193610364344706, 0.1923502827886502, 0.18934360917857015}\n    };\n\n    const Real tol[][4] = {\n        {0.06, 0.03, 0.03, 0.02},\n        {0.15, 0.08, 0.04, 0.02},\n        {0.06, 0.08, 1.0, 1.0} //forde breaks down for long maturities\n    };\n    const Real tolAtm[][4] = {\n        {4e-6, 7e-4, 2e-3, 9e-4},\n        {7e-6, 4e-4, 9e-4, 4e-4},\n        {4e-4, 3e-2, 0.28, 1.0}\n    };\n    for (Size j=0; j < LENGTH(terms); ++j) {\n        const Real term = terms[j];\n        const boost::shared_ptr<HestonExpansion> lpp2 =\n            boost::make_shared<LPP2HestonExpansion>(kappa, theta, sigma,\n                                                    v0, rho, term);\n        const boost::shared_ptr<HestonExpansion> lpp3 =\n            boost::make_shared<LPP3HestonExpansion>(kappa, theta, sigma,\n                                                    v0, rho, term);\n        const boost::shared_ptr<HestonExpansion> forde =\n            boost::make_shared<FordeHestonExpansion>(kappa, theta, sigma,\n                                                     v0, rho, term);\n        const boost::shared_ptr<HestonExpansion> expansions[] = { lpp2, lpp3, forde };\n        for (Size i=0; i < LENGTH(strikes); ++i) {\n            const Real strike = strikes[i];\n            for (Size k=0; k < LENGTH(expansions); ++k) {\n                const boost::shared_ptr<HestonExpansion> expansion = expansions[k];\n\n                const Real expected = referenceVols[j][i];\n                const Real calculated = expansion->impliedVolatility(strike, forward);\n                const Real relError = std::fabs(calculated-expected)/expected;\n                const Real refTol = strike == forward ? tolAtm[k][j] : tol[k][j];\n                if (relError > refTol) {\n                    BOOST_ERROR(\n                           \"failed to reproduce Forde reference vols \"\n                        << \"\\n    strike        : \" << strike\n                        << \"\\n    expansion type: \" << k\n                        << \"\\n    rel. error    : \" << relError);\n                }\n            }\n        }\n    }\n}\n\n\nnamespace {\n    void reportOnIntegrationMethodTest(\n        VanillaOption& option,\n        const boost::shared_ptr<HestonModel>& model,\n        const AnalyticHestonEngine::Integration& integration,\n        AnalyticHestonEngine::ComplexLogFormula formula,\n        bool isAdaptive, Real expected, Real tol, Size valuations,\n        std::string method) {\n\n        if (integration.isAdaptiveIntegration() != isAdaptive)\n            BOOST_ERROR(method << \" is not an adaptive integration routine\");\n\n        const boost::shared_ptr<AnalyticHestonEngine> engine =\n            boost::make_shared<AnalyticHestonEngine>(\n                model, formula, integration);\n\n        option.setPricingEngine(engine);\n        const Real calculated = option.NPV();\n\n        const Real error = std::fabs(calculated - expected);\n        if (error > tol) {\n            BOOST_ERROR(\"failed to reproduce simple Heston Pricing with \"\n                    << \"\\n    integration method: \" << method\n                    <<  std::setprecision(12)\n                    << \"\\n    expected          : \" << expected\n                    << \"\\n    calculated        : \" << calculated\n                    << \"\\n    error             : \" << error);\n        }\n\n        if (   valuations != Null<Size>()\n            && valuations != engine->numberOfEvaluations()) {\n            BOOST_ERROR(\"nubmer of function evaluations does not match \"\n                    << \"\\n    integration method      : \" << method\n                    << \"\\n    expected function calls : \" << valuations\n                    << \"\\n    number of function calls: \"\n                    << engine->numberOfEvaluations());\n        }\n    }\n}\n\nvoid HestonModelTest::testAllIntegrationMethods() {\n    BOOST_TEST_MESSAGE(\"Testing semi-analytic Heston pricing with all \"\n                       \"integration methods...\");\n\n    SavedSettings backup;\n\n    const Date settlementDate(7, February, 2017);\n    Settings::instance().evaluationDate() = settlementDate;\n\n    const DayCounter dayCounter = Actual365Fixed();\n    const Handle<YieldTermStructure> riskFreeTS(flatRate(0.05, dayCounter));\n    const Handle<YieldTermStructure> dividendTS(flatRate(0.075, dayCounter));\n\n    const Handle<Quote> s0(boost::shared_ptr<Quote>(new SimpleQuote(100.0)));\n\n    const Real v0    =  0.1;\n    const Real rho   = -0.75;\n    const Real sigma =  0.4;\n    const Real kappa =  4.0;\n    const Real theta =  0.05;\n\n    const boost::shared_ptr<HestonModel> model =\n        boost::make_shared<HestonModel>(\n            boost::make_shared<HestonProcess>(\n                riskFreeTS, dividendTS,\n                s0, v0, kappa, theta, sigma, rho));\n\n    const boost::shared_ptr<StrikedTypePayoff> payoff =\n        boost::make_shared<PlainVanillaPayoff>(Option::Put, s0->value());\n\n    const Date maturityDate = settlementDate + Period(1, Years);\n    const boost::shared_ptr<Exercise> exercise =\n        boost::make_shared<EuropeanExercise>(maturityDate);\n\n    VanillaOption option(payoff, exercise);\n\n    const Real tol = 1e-8;\n    const Real expected = 10.147041515497;\n\n    // Gauss-Laguerre with Gatheral logarithm integration method\n    reportOnIntegrationMethodTest(option, model,\n        AnalyticHestonEngine::Integration::gaussLaguerre(),\n        AnalyticHestonEngine::Gatheral,\n        false, expected, tol, 256, \"Gauss-Laguerre with Gatheral logarithm\");\n\n    // Gauss-Laguerre with branch correction integration method\n    reportOnIntegrationMethodTest(option, model,\n        AnalyticHestonEngine::Integration::gaussLaguerre(),\n        AnalyticHestonEngine::BranchCorrection,\n        false, expected, tol, 256, \"Gauss-Laguerre with branch correction\");\n\n    // Gauss-Legendre with Gatheral logarithm integration method\n    reportOnIntegrationMethodTest(option, model,\n        AnalyticHestonEngine::Integration::gaussLegendre(),\n        AnalyticHestonEngine::Gatheral,\n        false, expected, tol, 256, \"Gauss-Legendre with Gatheral logarithm\");\n\n    // Gauss-Legendre with branch correction integration method\n    reportOnIntegrationMethodTest(option, model,\n        AnalyticHestonEngine::Integration::gaussLegendre(),\n        AnalyticHestonEngine::BranchCorrection,\n        false, expected, tol, 256, \"Gauss-Legendre with branch correction\");\n\n    // Gauss-Chebyshev with Gatheral logarithm integration method\n    reportOnIntegrationMethodTest(option, model,\n        AnalyticHestonEngine::Integration::gaussChebyshev(512),\n        AnalyticHestonEngine::Gatheral,\n        false, expected, 1e-4, 1024, \"Gauss-Chebyshev with Gatheral logarithm\");\n\n    // Gauss-Chebyshev with branch correction integration method\n    reportOnIntegrationMethodTest(option, model,\n        AnalyticHestonEngine::Integration::gaussChebyshev(512),\n        AnalyticHestonEngine::BranchCorrection,\n        false, expected, 1e-4, 1024, \"Gauss-Chebyshev with branch correction\");\n\n    // Gauss-Chebyshev2nd with Gatheral logarithm integration method\n    reportOnIntegrationMethodTest(option, model,\n        AnalyticHestonEngine::Integration::gaussChebyshev2nd(512),\n        AnalyticHestonEngine::Gatheral,\n        false, expected, 2e-4, 1024,\n        \"Gauss-Chebyshev2nd with Gatheral logarithm\");\n\n    // Gauss-Chebyshev with branch correction integration method\n    reportOnIntegrationMethodTest(option, model,\n        AnalyticHestonEngine::Integration::gaussChebyshev2nd(512),\n        AnalyticHestonEngine::BranchCorrection,\n        false, expected, 2e-4, 1024,\n        \"Gauss-Chebyshev2nd with branch correction\");\n\n    // Discrete Simpson rule with Gatheral logarithm\n    reportOnIntegrationMethodTest(option, model,\n        AnalyticHestonEngine::Integration::discreteSimpson(512),\n        AnalyticHestonEngine::Gatheral,\n        false, expected, tol, 1024,\n        \"Discrete Simpson rule with Gatheral logarithm\");\n\n    // Discrete Simpson rule with branch correction integration method\n    reportOnIntegrationMethodTest(option, model,\n        AnalyticHestonEngine::Integration::discreteSimpson(512),\n        AnalyticHestonEngine::BranchCorrection,\n        false, expected, tol, 1024,\n        \"Discrete Simpson rule with branch correction\");\n\n    // Discrete Trapezoid rule with Gatheral logarithm\n    reportOnIntegrationMethodTest(option, model,\n        AnalyticHestonEngine::Integration::discreteTrapezoid(512),\n        AnalyticHestonEngine::Gatheral,\n        false, expected, 2e-4, 1024,\n        \"Discrete Trapezoid rule with Gatheral logarithm\");\n\n    // Discrete Trapezoid rule with branch correction integration method\n    reportOnIntegrationMethodTest(option, model,\n        AnalyticHestonEngine::Integration::discreteTrapezoid(512),\n        AnalyticHestonEngine::BranchCorrection,\n        false, expected, 2e-4, 1024,\n        \"Discrete Trapezoid rule with branch correction\");\n\n    // Gauss-Lobatto with Gatheral logarithm\n    reportOnIntegrationMethodTest(option, model,\n        AnalyticHestonEngine::Integration::gaussLobatto(tol, Null<Real>()),\n        AnalyticHestonEngine::Gatheral,\n        true, expected, tol, Null<Size>(),\n        \"Gauss-Lobatto with Gatheral logarithm\");\n\n    // Gauss-Konrod with Gatheral logarithm\n    reportOnIntegrationMethodTest(option, model,\n        AnalyticHestonEngine::Integration::gaussKronrod(tol),\n        AnalyticHestonEngine::Gatheral,\n        true, expected, tol, Null<Size>(),\n        \"Gauss-Konrod with Gatheral logarithm\");\n\n    // Simpson with Gatheral logarithm\n    reportOnIntegrationMethodTest(option, model,\n        AnalyticHestonEngine::Integration::simpson(tol),\n        AnalyticHestonEngine::Gatheral,\n        true, expected, 1e-6, Null<Size>(),\n        \"Simpson with Gatheral logarithm\");\n\n    // Trapezoid with Gatheral logarithm\n    reportOnIntegrationMethodTest(option, model,\n        AnalyticHestonEngine::Integration::trapezoid(tol),\n        AnalyticHestonEngine::Gatheral,\n        true, expected, 1e-6, Null<Size>(),\n        \"Trapezoid with Gatheral logarithm\");\n}\n\nnamespace {\n    class LogCharacteristicFunction\n            : public std::unary_function<Real, Real> {\n      public:\n        LogCharacteristicFunction(\n            Size n, Time t,\n            const boost::shared_ptr<COSHestonEngine>& engine)\n        : t_(t), alpha_(0.0, 1.0), engine_(engine) {\n            for (Size i=1; i < n; ++i, alpha_*=std::complex<Real>(0,1));\n        }\n\n        Real operator()(Real u) const {\n            return (std::log(engine_->characteristicFct(u, t_))/alpha_).real();\n        }\n\n      private:\n        const Time t_;\n        std::complex<Real> alpha_;\n        const boost::shared_ptr<COSHestonEngine> engine_;\n    };\n}\n\nvoid HestonModelTest::testCosHestonCumulants() {\n    BOOST_TEST_MESSAGE(\"Testing Heston COS cumulants...\");\n\n    SavedSettings backup;\n\n    const Date settlementDate(7, February, 2017);\n    Settings::instance().evaluationDate() = settlementDate;\n\n    const DayCounter dayCounter = Actual365Fixed();\n    const Handle<YieldTermStructure> riskFreeTS(flatRate(0.15, dayCounter));\n    const Handle<YieldTermStructure> dividendTS(flatRate(0.075, dayCounter));\n\n    const Handle<Quote> s0(boost::shared_ptr<Quote>(new SimpleQuote(100.0)));\n\n    const Real v0    =  0.1;\n    const Real rho   = -0.75;\n    const Real sigma =  0.4;\n    const Real kappa =  4.0;\n    const Real theta =  0.25;\n\n    const boost::shared_ptr<HestonModel> model =\n        boost::make_shared<HestonModel>(\n            boost::make_shared<HestonProcess>(\n                riskFreeTS, dividendTS,\n                s0, v0, kappa, theta, sigma, rho));\n\n    const boost::shared_ptr<COSHestonEngine> cosEngine =\n        boost::make_shared<COSHestonEngine>(model);\n\n    const Real tol = 1e-7;\n    const NumericalDifferentiation::Scheme central(\n        NumericalDifferentiation::Central);\n\n    for (Time t=0.01; t < 41.0; t+=t) {\n        const Real nc1 = NumericalDifferentiation(\n            boost::function<Real(Real)>(\n                LogCharacteristicFunction(1, t, cosEngine)),\n            1, 1e-5, 5, central)(0.0);\n\n        const Real c1 = cosEngine->c1(t);\n\n        if (std::fabs(nc1 - c1) > tol) {\n            BOOST_ERROR(\" failed to reproduce first cumulant\"\n                    << \"\\n    expected:   \" << nc1\n                    << \"\\n    calculated: \" << c1\n                    << \"\\n    difference: \" << std::fabs(nc1 - c1));\n        }\n\n        const Real nc2 = NumericalDifferentiation(\n            boost::function<Real(Real)>(\n                LogCharacteristicFunction(2, t, cosEngine)),\n            2, 1e-2, 5, central)(0.0);\n\n        const Real c2 = cosEngine->c2(t);\n\n        if (std::fabs(nc2 - c2) > tol) {\n            BOOST_ERROR(\" failed to reproduce second cumulant\"\n                    << \"\\n    expected:   \" << nc2\n                    << \"\\n    calculated: \" << c2\n                    << \"\\n    difference: \" << std::fabs(nc2 - c2));\n        }\n\n        const Real nc3 = NumericalDifferentiation(\n            boost::function<Real(Real)>(\n                LogCharacteristicFunction(3, t, cosEngine)),\n            3, 5e-3, 7, central)(0.0);\n\n        const Real c3 = cosEngine->c3(t);\n\n        if (std::fabs(nc3 - c3) > tol) {\n            BOOST_ERROR(\" failed to reproduce third cumulant\"\n                    << \"\\n    expected:   \" << nc3\n                    << \"\\n    calculated: \" << c3\n                    << \"\\n    difference: \" << std::fabs(nc3 - c3));\n        }\n\n        const Real nc4 = NumericalDifferentiation(\n            boost::function<Real(Real)>(\n                LogCharacteristicFunction(4, t, cosEngine)),\n            4, 5e-2, 9, central)(0.0);\n\n        const Real c4 = cosEngine->c4(t);\n\n        if (std::fabs(nc4 - c4) > 10*tol) {\n            BOOST_ERROR(\" failed to reproduce 4th cumulant\"\n                    << \"\\n    expected:   \" << nc4\n                    << \"\\n    calculated: \" << c4\n                    << \"\\n    difference: \" << std::fabs(nc4 - c4));\n        }\n    }\n}\n\n\nvoid HestonModelTest::testCosHestonEngine() {\n    BOOST_TEST_MESSAGE(\"Testing Heston pricing via COS method...\");\n\n    SavedSettings backup;\n\n    const Date settlementDate(7, February, 2017);\n    Settings::instance().evaluationDate() = settlementDate;\n\n    const DayCounter dayCounter = Actual365Fixed();\n    const Handle<YieldTermStructure> riskFreeTS(flatRate(0.15, dayCounter));\n    const Handle<YieldTermStructure> dividendTS(flatRate(0.07, dayCounter));\n\n    const Handle<Quote> s0(boost::shared_ptr<Quote>(new SimpleQuote(100.0)));\n\n    const Real v0    =  0.1;\n    const Real rho   = -0.75;\n    const Real sigma =  1.8;\n    const Real kappa =  4.0;\n    const Real theta =  0.22;\n\n    const boost::shared_ptr<HestonModel> model =\n        boost::make_shared<HestonModel>(\n            boost::make_shared<HestonProcess>(\n                riskFreeTS, dividendTS,\n                s0, v0, kappa, theta, sigma, rho));\n\n    const Date maturityDate = settlementDate + Period(1, Years);\n\n    const boost::shared_ptr<Exercise> exercise =\n        boost::make_shared<EuropeanExercise>(maturityDate);\n\n    const boost::shared_ptr<PricingEngine> cosEngine(\n        boost::make_shared<COSHestonEngine>(model, 25, 600));\n\n    const boost::shared_ptr<StrikedTypePayoff> payoffs[] = {\n        boost::make_shared<PlainVanillaPayoff>(Option::Call, s0->value()+20),\n        boost::make_shared<PlainVanillaPayoff>(Option::Call, s0->value()+150),\n        boost::make_shared<PlainVanillaPayoff>(Option::Put, s0->value()-20),\n        boost::make_shared<PlainVanillaPayoff>(Option::Put, s0->value()-90)\n    };\n\n    const Real expected[] = {\n        9.364410588426075, 0.01036797658132471,\n        5.319092971836708, 0.01032681906278383 };\n\n    const Real tol = 1e-10;\n\n    for (Size i=0; i < LENGTH(payoffs); ++i) {\n        VanillaOption option(payoffs[i], exercise);\n\n        option.setPricingEngine(cosEngine);\n        const Real calculated = option.NPV();\n        const Real error = std::fabs(expected[i] - calculated);\n\n        if (error > tol) {\n            BOOST_ERROR(\" failed to reproduce prices with COSHestonEngine\"\n                    << \"\\n    expected:   \" << expected[i]\n                    << \"\\n    calculated: \" << calculated\n                    << \"\\n    difference: \" << error);\n        }\n    }\n}\n\ntest_suite* HestonModelTest::suite(SpeedLevel speed) {\n    test_suite* suite = BOOST_TEST_SUITE(\"Heston model tests\");\n\n    suite->add(QUANTLIB_TEST_CASE(&HestonModelTest::testBlackCalibration));\n    suite->add(QUANTLIB_TEST_CASE(&HestonModelTest::testDAXCalibration));\n    suite->add(QUANTLIB_TEST_CASE(&HestonModelTest::testAnalyticVsBlack));\n    suite->add(QUANTLIB_TEST_CASE(&HestonModelTest::testAnalyticVsCached));\n    suite->add(QUANTLIB_TEST_CASE(&HestonModelTest::testDifferentIntegrals));\n    suite->add(QUANTLIB_TEST_CASE(&HestonModelTest::testFdVanillaVsCached));\n    suite->add(QUANTLIB_TEST_CASE(&HestonModelTest::testMultipleStrikesEngine));\n    suite->add(QUANTLIB_TEST_CASE(&HestonModelTest::testMcVsCached));\n    suite->add(QUANTLIB_TEST_CASE(\n                    &HestonModelTest::testAnalyticPiecewiseTimeDependent));\n    suite->add(QUANTLIB_TEST_CASE(\n                    &HestonModelTest::testDAXCalibrationOfTimeDependentModel));\n    suite->add(QUANTLIB_TEST_CASE(\n                    &HestonModelTest::testAlanLewisReferencePrices));\n    suite->add(QUANTLIB_TEST_CASE(\n                    &HestonModelTest::testExpansionOnAlanLewisReference));\n    suite->add(QUANTLIB_TEST_CASE(\n                    &HestonModelTest::testExpansionOnFordeReference));\n    suite->add(QUANTLIB_TEST_CASE(\n                    &HestonModelTest::testAllIntegrationMethods));\n    suite->add(QUANTLIB_TEST_CASE(&HestonModelTest::testCosHestonCumulants));\n    suite->add(QUANTLIB_TEST_CASE(&HestonModelTest::testCosHestonEngine));\n\n    if (speed <= Fast) {\n        suite->add(QUANTLIB_TEST_CASE(\n            &HestonModelTest::testFdBarrierVsCached));\n    }\n\n    if (speed == Slow) {\n        suite->add(QUANTLIB_TEST_CASE(&HestonModelTest::testKahlJaeckelCase));\n    }\n\n    return suite;\n}\n\ntest_suite* HestonModelTest::experimental() {\n    test_suite* suite = BOOST_TEST_SUITE(\"Heston model tests\");\n    suite->add(QUANTLIB_TEST_CASE(\n        &HestonModelTest::testAnalyticPDFHestonEngine));\n    return suite;\n}\n", "meta": {"hexsha": "c87d3087946cdce78741049187e8b95b75757815", "size": 79276, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test-suite/hestonmodel.cpp", "max_stars_repo_name": "sfondi/QuantLib", "max_stars_repo_head_hexsha": "8a2449d2fb470a7d47a55d3e99c5dace749709c9", "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": "test-suite/hestonmodel.cpp", "max_issues_repo_name": "sfondi/QuantLib", "max_issues_repo_head_hexsha": "8a2449d2fb470a7d47a55d3e99c5dace749709c9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test-suite/hestonmodel.cpp", "max_forks_repo_name": "sfondi/QuantLib", "max_forks_repo_head_hexsha": "8a2449d2fb470a7d47a55d3e99c5dace749709c9", "max_forks_repo_licenses": ["BSD-3-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.4057084608, "max_line_length": 153, "alphanum_fraction": 0.6095161209, "num_tokens": 20793, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.48728404167004574}}
{"text": "/*\nAndrea Tino - 2018\n*/\n\n#include <iostream>\n#include <list>\n#include <vector>\n#include <exception>\n#include <set>\n#include <map>\n\n#include <boost/foreach.hpp>\n\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Triangulation_3.h>\n#include <CGAL/Polygon_mesh_processing/triangulate_faces.h>\n#include <CGAL/Polyhedron_3.h>\n#include <CGAL/Surface_mesh.h>\n#include <CGAL/convex_hull_3.h>\n#include <CGAL/Simple_cartesian.h>\n#include <CGAL/point_generators_3.h>\n#include <CGAL/algorithm.h>\n\n#include \"DelaunayTriangulator.h\"\n\n// Constructors\n\nCodeAlive::Triangulation::DelaunayTriangulator::DelaunayTriangulator(const int& number_vertices)\n{\n\tthis->points = std::vector<Point>();\n\tthis->create_rnd_points(number_vertices, 1);\n\tthis->performed = false;\n}\n\nCodeAlive::Triangulation::DelaunayTriangulator::DelaunayTriangulator(const std::list<CodeAlive::Triangulation::Point>& vertices)\n{\n\tthis->points = std::vector<Point>(vertices.begin(), vertices.end());\n\tthis->performed = false;\n}\n\nCodeAlive::Triangulation::DelaunayTriangulator::DelaunayTriangulator(const std::vector<CodeAlive::Triangulation::Point>& vertices)\n{\n\tthis->points = std::vector<Point>(vertices.begin(), vertices.end());\n\tthis->performed = false;\n}\n\nCodeAlive::Triangulation::DelaunayTriangulator::DelaunayTriangulator(const DelaunayTriangulator& other)\n{\n\tthis->points = std::vector<Point>(other.points.begin(), other.points.end());\n\tthis->vertices = std::vector<Point>(other.vertices.begin(), other.vertices.end());\n\tthis->triangles = std::vector<int>(other.triangles.begin(), other.triangles.end());\n\tthis->performed = other.performed;\n}\n\nCodeAlive::Triangulation::DelaunayTriangulator::~DelaunayTriangulator()\n{\n\tthis->points.clear();\n\tthis->vertices.clear();\n\tthis->triangles.clear();\n}\n\n// Members\n\nvoid CodeAlive::Triangulation::DelaunayTriangulator::perform()\n{\n\ttypedef CGAL::Polyhedron_3<K>           Polyhedron_3;\n\ttypedef CGAL::Surface_mesh<Point_3>     Surface_mesh;\n\ttypedef Surface_mesh::Vertex_index\t\tvertex_descriptor;\n\ttypedef Surface_mesh::Face_index\t\tface_descriptor;\n\n\t// Convert into proper CGAL recognized points\n\tstd::list<Point_3> points;\n\tfor (std::vector<Point>::const_iterator it = this->points.begin(); it != this->points.end(); it++) {\n\t\tpoints.push_front(Point_3(it->X, it->Y, it->Z));\n\t}\n\n\t// Compute triangulation on the convex hull\n\tSurface_mesh sm;\n\tCGAL::convex_hull_3(points.begin(), points.end(), sm);\n\tCGAL::Polygon_mesh_processing::triangulate_faces(sm);\n\n\t// Confirm that all faces are triangles.\n\tBOOST_FOREACH(boost::graph_traits<Surface_mesh>::face_descriptor fit, faces(sm))\n\t\tif (next(next(halfedge(fit, sm), sm), sm) != prev(halfedge(fit, sm), sm))\n\t\t\tthrow std::exception(\"Error: non-triangular face left in mesh\");\n\n\t// Populate the set of vertices to get the subset of vertices that were used for the triangulation\n\tstd::set<Point_3> vertices;\n\tBOOST_FOREACH(boost::graph_traits<Surface_mesh>::face_descriptor fit, faces(sm)) {\n\t\tBOOST_FOREACH(vertex_descriptor vd, vertices_around_face(sm.halfedge(fit), sm)) {\n\t\t\tPoint_3 p = sm.point(vd);\n\t\t\tvertices.insert(p);\n\t\t}\n\t}\n\n\t// Populate the map to get the index of a vertex\n\t// Also populate the array of vertices in the order defined\n\t{ int i = 0;\n\t\tfor (std::set<Point_3>::const_iterator it = vertices.begin(); it != vertices.end(); it++) {\n\t\t\tthis->p2i[*it] = i++;\n\n\t\t\tPoint v; v.X = it->x(); v.Y = it->y(); v.Z = it->z();\n\t\t\tthis->vertices.push_back(v);\n\t\t}\n\t}\n\n\t// Iterate through faces and, therefore, vertices in each triangle. Populate the triangles array\n\tBOOST_FOREACH(boost::graph_traits<Surface_mesh>::face_descriptor fit, faces(sm)) {\n\t\tBOOST_FOREACH(vertex_descriptor vd, vertices_around_face(sm.halfedge(fit), sm)) {\n\t\t\tPoint_3 p = sm.point(vd);\n\t\t\tint index = this->p2i[p];\n\n\t\t\tthis->triangles.push_back(index);\n\t\t}\n\t}\n\n\tthis->performed = true;\n}\n\nint CodeAlive::Triangulation::DelaunayTriangulator::get_vertex_index(const CodeAlive::Triangulation::Point& point)\n{\n\tPoint_3 p(point.X, point.Y, point.Z);\n\treturn this->p2i[p];\n}\n\nvoid CodeAlive::Triangulation::DelaunayTriangulator::create_rnd_points(const int& num, const double& radius)\n{\n\ttypedef CGAL::Simple_cartesian<double>\t\t\t\tR;\n\ttypedef R::Point_3\t\t\t\t\t\t\t\t\tCGALPoint;\n\ttypedef CGAL::Creator_uniform_3<double, CGALPoint>\tCreator;\n\n\t// Create test point set. Prepare a vector for 1000 points.\n\tstd::vector<CGALPoint> points;\n\tpoints.reserve(num);\n\n\t// Create points within a sphere of specified radius.\n\tCGAL::Random_points_in_sphere_3<CGALPoint, Creator> g(radius);\n\tCGAL::cpp11::copy_n(g, num, std::back_inserter(points));\n\n\t// Use a random permutation to hide the creation history of the point set.\n\tCGAL::cpp98::random_shuffle(points.begin(), points.end());\n\n\t// Fill the instance vector\n\tthis->points.clear();\n\tfor (std::vector<CGALPoint>::iterator it = points.begin(); it != points.end(); it++) {\n\t\tPoint p(it->x(), it->y(), it->z());\n\t\tthis->points.push_back(p);\n\t}\n}\n", "meta": {"hexsha": "9cd51d8a1c1d17b8beab5cfa4153fb9a0a9c748e", "size": 4935, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/triangulator/src/DelaunayTriangulator/DelaunayTriangulator.cpp", "max_stars_repo_name": "andry-tino/code-alive", "max_stars_repo_head_hexsha": "a48bdd8e57949ac2f2c41254cfd994770ef69fd5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-05-12T15:47:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-24T03:37:15.000Z", "max_issues_repo_path": "src/triangulator/src/DelaunayTriangulator/DelaunayTriangulator.cpp", "max_issues_repo_name": "andry-tino/code-alive", "max_issues_repo_head_hexsha": "a48bdd8e57949ac2f2c41254cfd994770ef69fd5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-06-27T13:31:48.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-06T17:47:11.000Z", "max_forks_repo_path": "src/triangulator/src/DelaunayTriangulator/DelaunayTriangulator.cpp", "max_forks_repo_name": "andry-tino/code-alive", "max_forks_repo_head_hexsha": "a48bdd8e57949ac2f2c41254cfd994770ef69fd5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-05-12T15:47:58.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-12T15:47:58.000Z", "avg_line_length": 32.9, "max_line_length": 130, "alphanum_fraction": 0.7319148936, "num_tokens": 1339, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.48728403650563723}}
{"text": "#include <boost/random/bernoulli_distribution.hpp>\n", "meta": {"hexsha": "3e4e54136d1b7f05c76745a55c4855d35a650ad1", "size": 51, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_random_bernoulli_distribution.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_random_bernoulli_distribution.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_random_bernoulli_distribution.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 25.5, "max_line_length": 50, "alphanum_fraction": 0.8431372549, "num_tokens": 11, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891218080991, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4872840313412286}}
{"text": "#ifndef _SURFACE_RECON_\n#define _SURFACE_RECON_\n\n#ifndef CGAL_EIGEN3_ENABLED\n#define CGAL_EIGEN3_ENABLED 1\n#endif\n\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/pca_estimate_normals.h>\n#include <CGAL/mst_orient_normals.h>\n#include <CGAL/property_map.h>\n#include <CGAL/IO/read_xyz_points.h>\n#include <utility> // defines std::pair\n#include <list>\n#include <fstream>\n#include <stdio.h>\n#include <cmath>\n\n#include <CGAL/trace.h>\n#include <CGAL/Polyhedron_3.h>\n#include <CGAL/IO/Polyhedron_iostream.h>\n#include <CGAL/Surface_mesh_default_triangulation_3.h>\n#include <CGAL/make_surface_mesh.h>\n#include <CGAL/Implicit_surface_3.h>\n#include <CGAL/IO/output_surface_facets_to_polyhedron.h>\n#include <CGAL/Poisson_reconstruction_function.h>\n#include <CGAL/Point_with_normal_3.h>\n#include <CGAL/compute_average_spacing.h>\n#include <vector>\n#include <ros/ros.h>\n\n#include <CGAL/Index_property_map.h>\n\n//Search tree\n\n#include <CGAL/Search_traits_3.h>\n#include <CGAL/Search_traits_adapter.h>\n#include <CGAL/Orthogonal_k_neighbor_search.h>\n#include <boost/iterator/zip_iterator.hpp>\n#include <utility>\n\n#include <CGAL/Simple_cartesian.h>\n#include <CGAL/Surface_mesh.h>\n\n#include <CGAL/Polygon_mesh_processing/connected_components.h>\n#include <CGAL/Polygon_mesh_processing/measure.h>\n\ntypedef CGAL::Simple_cartesian<double>::Point_3 CPoint3;\ntypedef CGAL::Surface_mesh<CPoint3> Mesh;\ntypedef Mesh::Vertex_index vertex_descriptor;\n\n// Types\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel;\ntypedef Kernel::FT FT;\ntypedef Kernel::Point_3 Point;\ntypedef CGAL::Point_with_normal_3<Kernel> Point_with_normal;\ntypedef Kernel::Sphere_3 Sphere;\ntypedef std::vector<Point_with_normal> PointList;\ntypedef CGAL::Polyhedron_3<Kernel> Polyhedron;\ntypedef CGAL::Poisson_reconstruction_function<Kernel> Poisson_reconstruction_function;\ntypedef CGAL::Surface_mesh_default_triangulation_3 STr;\ntypedef CGAL::Surface_mesh_complex_2_in_triangulation_3<STr> C2t3;\ntypedef CGAL::Implicit_surface_3<Kernel, Poisson_reconstruction_function> Surface_3;\n\n// Types\n\ntypedef Kernel::Vector_3 Vector;\ntypedef CGAL::cpp11::array<unsigned char, 3> Color;\n// Point with normal vector stored in a std::pair.\ntypedef std::pair<Point, Vector> PointVectorPair;\n// Concurrency\n#ifdef CGAL_LINKED_WITH_TBB\ntypedef CGAL::Parallel_tag Concurrency_tag;\n#else\ntypedef CGAL::Sequential_tag Concurrency_tag;\n#endif\n\ntypedef Kernel::Point_3 Point_3;\ntypedef boost::tuple<Point_3, int> Point_and_int;\ntypedef CGAL::Search_traits_3<Kernel> Traits_base;\ntypedef CGAL::Search_traits_adapter<Point_and_int,\n        CGAL::Nth_of_tuple_property_map<0, Point_and_int>,\n        Traits_base> Traits;\ntypedef CGAL::Orthogonal_k_neighbor_search<Traits> K_neighbor_search;\ntypedef K_neighbor_search::Tree Tree;\ntypedef K_neighbor_search::Distance Distance;\n\nvoid translade_pts_mean(std::vector<Point> &pts);\n\nstd::list<PointVectorPair> grab_normals(std::vector<Point> &pts, std::vector<Vector> &norms);\n\nvoid estimate_normals(std::vector<Point> &pts, std::list<PointVectorPair> &points);\n\nvoid estimate_normals(std::vector<Point> &pts, Point_3 src, std::list<PointVectorPair> &points);\n\nstd::list<PointVectorPair> register_normals(std::vector<Point> sampled_points, std::list<PointVectorPair> original);\n\nMesh reconstruct_surface(std::list<PointVectorPair> &pwn, std::string base_path);\n\nvoid\nwrite_ply_wnormals(std::string out, std::list<PointVectorPair> &point_list, Tree &tree, std::vector<Color> &colors);\n\nvoid trim_mesh(Mesh m, Tree &tree, double average_spacing, std::string base_path);\nint remove_borders(std::string mesh_path, int iterations, std::string base_path);\n\ntemplate <typename ForwardIterator,\n        typename PointPMap,\n        typename NormalPMap,\n        typename Kernel\n>\nForwardIterator\nmst_orient_normals_modified(\n        ForwardIterator first,  ///< iterator over the first input point.\n        ForwardIterator beyond, ///< past-the-end iterator over the input points.\n        PointPMap point_pmap, ///< property map: value_type of ForwardIterator -> Point_3.\n        NormalPMap normal_pmap, ///< property map: value_type of ForwardIterator -> Vector_3.\n        unsigned int k, ///< number of neighbors\n        const Kernel& kernel, ///< geometric traits.\n        Point_3 src);  ///< origin of the MST algorithm over the Riemannian Graph\n\nstruct ComparePointsToOrigin\n{\n    bool operator()(Point first, Point second) const\n    {\n        double a = std::sqrt(pow(first.x(), 2) + pow(first.y(), 2) + pow(first.z(), 2));\n        double b = std::sqrt(pow(second.x(), 2) + pow(second.y(), 2) + pow(second.z(), 2));\n        return a < b;\n\n    }\n};\n#endif\n//_SURFACE_RECON_\n", "meta": {"hexsha": "cdd135fc9093b2c2b02d2532a12dd0707133c726", "size": 4676, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "recon_surface/include/recon_surface/surface_recon.hpp", "max_stars_repo_name": "ITVRoC/espeleo_planner", "max_stars_repo_head_hexsha": "f29d01c09aba339a30a76d05e80641181172ec8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T12:53:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-12T01:14:43.000Z", "max_issues_repo_path": "recon_surface/include/recon_surface/surface_recon.hpp", "max_issues_repo_name": "ITVRoC/espeleo_planner", "max_issues_repo_head_hexsha": "f29d01c09aba339a30a76d05e80641181172ec8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "recon_surface/include/recon_surface/surface_recon.hpp", "max_forks_repo_name": "ITVRoC/espeleo_planner", "max_forks_repo_head_hexsha": "f29d01c09aba339a30a76d05e80641181172ec8a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-09-17T06:58:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T12:15:29.000Z", "avg_line_length": 35.1578947368, "max_line_length": 116, "alphanum_fraction": 0.7748075278, "num_tokens": 1193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891130942474, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.48728402617681976}}
{"text": "#include <iostream>\n#include <pcl/io/pcd_io.h>\n#include <pcl_conversions/pcl_conversions.h>\n#include <pcl/point_cloud.h>\n#include <pcl/point_types.h>\n#include <pcl/kdtree/kdtree_flann.h>\n#include <pcl/search/kdtree.h>\n#include <pcl/search/impl/kdtree.hpp>\n\n#include <ros/ros.h>\n#include <ros/console.h>\n#include <sensor_msgs/PointCloud2.h>\n#include <geometry_msgs/Vector3.h>\n#include <geometry_msgs/PoseStamped.h>\n#include <nav_msgs/Odometry.h>\n#include <Eigen/Eigen>\n#include <math.h>\n#include <random>\n\n\nusing namespace std;\nusing namespace Eigen;\n\nros::Publisher _all_map_pub;\nint  _obs_num,_cir_num;\ndouble _x_size, _y_size, _z_size, _init_x, _init_y, _resolution, _sense_rate;\ndouble _x_l, _x_h, _y_l, _y_h, _w_l, _w_h, _h_l, _h_h, _w_c_l, _w_c_h;", "meta": {"hexsha": "27f75f0ad0a207390e6324f8ef51a75fd5f6addb", "size": 752, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "C++_ORCA/DepthBlue/Path_planning/ch2/Stu_random_complex_generator.cpp", "max_stars_repo_name": "Chentao2000/practice_code", "max_stars_repo_head_hexsha": "aa4fb6bbc26ac1ea0fb40e6e0889050b7e9f096c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2022-01-07T13:07:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-08T04:46:02.000Z", "max_issues_repo_path": "C++_ORCA/DepthBlue/Path_planning/ch2/Stu_random_complex_generator.cpp", "max_issues_repo_name": "Chentao2000/practice_code", "max_issues_repo_head_hexsha": "aa4fb6bbc26ac1ea0fb40e6e0889050b7e9f096c", "max_issues_repo_licenses": ["Apache-2.0"], "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++_ORCA/DepthBlue/Path_planning/ch2/Stu_random_complex_generator.cpp", "max_forks_repo_name": "Chentao2000/practice_code", "max_forks_repo_head_hexsha": "aa4fb6bbc26ac1ea0fb40e6e0889050b7e9f096c", "max_forks_repo_licenses": ["Apache-2.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.8518518519, "max_line_length": 77, "alphanum_fraction": 0.767287234, "num_tokens": 233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891130942472, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.48728402617681965}}
{"text": "// (C) 2014 Arek Olek\n\n#pragma once\n\n#include <random>\n#include <vector>\n\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/random_spanning_tree.hpp>\n#include <boost/graph/named_function_params.hpp>\n\n#include \"range.hpp\"\n\ntemplate <class Vertex, class Graph, class Generator>\nVertex random_neighbor(Vertex const & v, Graph const & G, Generator& gen) {\n  uint d = out_degree(v, G)-1;\n  auto k = std::uniform_int_distribution<uint>{0, d}(gen);\n  auto it = adjacent_vertices(v, G).first;\n  while(k--) ++it;\n  return *it;\n}\n\ntemplate <class Graph, class Tree>\nTree random_tree(Graph& G, unsigned seed) {\n  std::default_random_engine gen(seed);\n  unsigned n = num_vertices(G);\n  std::vector<bool> visited(n, false);\n  Tree T(n);\n  unsigned v = std::uniform_int_distribution<unsigned>{0, n-1}(gen);\n  while(num_edges(T) < n-1) {\n    visited[v] = true;\n    auto w = random_neighbor(v, G, gen);\n    if(!visited[w]) add_edge(v, w, T);\n    v = w;\n  }\n  return T;\n}\n\ntemplate <class Graph, class Tree>\nTree wilson_tree(Graph const & G, unsigned seed) {\n  typedef typename boost::graph_traits<Graph>::vertex_descriptor vertex;\n  unsigned n = num_vertices(G);\n  std::vector<vertex> pred(n);\n  std::default_random_engine gen(seed);\n  random_spanning_tree(G, gen, boost::predecessor_map(&pred[0]));\n  Tree T(n);\n  for(unsigned i = 0; i < n; ++i)\n    if(pred[i] != boost::graph_traits<Graph>::null_vertex())\n      add_edge(i, pred[i], T);\n  return T;\n}\n", "meta": {"hexsha": "052b6674fe4115930d420fe57d2b5f8084dadf5c", "size": 1451, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "graph/random.hpp", "max_stars_repo_name": "arekolek/MaxIST", "max_stars_repo_head_hexsha": "6a8b49152cfbf34c1c2728f64b1457a23824fe0d", "max_stars_repo_licenses": ["MIT"], "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/random.hpp", "max_issues_repo_name": "arekolek/MaxIST", "max_issues_repo_head_hexsha": "6a8b49152cfbf34c1c2728f64b1457a23824fe0d", "max_issues_repo_licenses": ["MIT"], "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/random.hpp", "max_forks_repo_name": "arekolek/MaxIST", "max_forks_repo_head_hexsha": "6a8b49152cfbf34c1c2728f64b1457a23824fe0d", "max_forks_repo_licenses": ["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.9038461538, "max_line_length": 75, "alphanum_fraction": 0.6843556168, "num_tokens": 402, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.782662489091802, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.4871755695168618}}
{"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/**\r\n\\file\r\n\r\n\\brief test_units_1.cpp\r\n\r\n\\details\r\nTest unit class.\r\n\r\nOutput:\r\n@verbatim\r\n@endverbatim\r\n**/\r\n\r\n#include \"test_header.hpp\"\r\n\r\n#include <boost/units/cmath.hpp>\r\n#include <boost/units/scale.hpp>\r\n#include <boost/units/make_scaled_unit.hpp>\r\n\r\nnamespace bu = boost::units;\r\n\r\nstatic const double E_ = 2.718281828459045235360287471352662497757;\r\n\r\ntypedef bu::make_scaled_unit<bu::length,\r\n                             bu::scale<10, bu::static_rational<-3> > >::type milli_meter_unit;\r\n\r\ntypedef bu::make_scaled_unit<bu::area,\r\n                             bu::scale<10, bu::static_rational<-6> > >::type micro_meter2_unit;\r\n\r\nint test_main(int,char *[])\r\n{\r\n    const bu::quantity<micro_meter2_unit> E1 = E_*micro_meter2_unit();\r\n    const bu::quantity<milli_meter_unit>  E2 = sqrt(E1);\r\n\r\n    BOOST_CHECK(E1.value() == E_);\r\n    BOOST_CHECK(E2.value() == sqrt(E_));\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "25f9c10cd87146b69b48b07f73d13845e3c051b1", "size": 1283, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/units/test/test_sqrt_scaled_unit.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": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/units/test/test_sqrt_scaled_unit.cpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-03-04T11:21:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-24T01:36:31.000Z", "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/units/test/test_sqrt_scaled_unit.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 26.1836734694, "max_line_length": 96, "alphanum_fraction": 0.6687451286, "num_tokens": 335, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.48717556320583105}}
{"text": "\n#include \"examples_common.h\"\n#include <Eigen/Dense>\n#include <iostream>\n\nint main(int argc, char const *argv[])\n{\n    Eigen::Matrix <double,2,3>m;\n    m<<2,3,4,\n    5,6,7;\n    std::cout<<m<<std::endl;\n    std::cout<<pseudoinverse(m)<<std::endl;  \n    Eigen::Matrix<double,1,3>m1;\n    m1<<m;\n    \n    Eigen::Matrix<double,1,3>m2;\n    m2<<3,3,3;\n\n    std::cout<<m1+m2<<std::endl;\n    // std::cout<<m.row(0)<<std::endl;\n    // std::cout<<m.row(1)<<std::endl;\n    // std::cout<<m.row(2)<<std::endl;\n    // std::array<double,3>data={1.0,2.3,3.4};\n\n    \n    //Eigen::Matrix<double,1,3>::Map(data.data(),m1.rows(),m1.cols())=m1;\n\n        // for (int i = 0; i < data.size(); i++)\n        // {\n        //     std::cout<<data[i]<<std::endl;\n        // }\n    return 0;\n}\n", "meta": {"hexsha": "cfbdff3be57021a5ebd2ec77c773607eb4cf0160", "size": 761, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/pseudo_inverse_test.cpp", "max_stars_repo_name": "Colaplusice/libfranka", "max_stars_repo_head_hexsha": "a330115280de29de5d8cf2dbe311047c073711d5", "max_stars_repo_licenses": ["Apache-2.0"], "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/pseudo_inverse_test.cpp", "max_issues_repo_name": "Colaplusice/libfranka", "max_issues_repo_head_hexsha": "a330115280de29de5d8cf2dbe311047c073711d5", "max_issues_repo_licenses": ["Apache-2.0"], "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/pseudo_inverse_test.cpp", "max_forks_repo_name": "Colaplusice/libfranka", "max_forks_repo_head_hexsha": "a330115280de29de5d8cf2dbe311047c073711d5", "max_forks_repo_licenses": ["Apache-2.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.3823529412, "max_line_length": 73, "alphanum_fraction": 0.5124835742, "num_tokens": 278, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.48717556320583105}}
{"text": "#ifndef HOPS_GAUSSIANPROCESS_HPP\n#define HOPS_GAUSSIANPROCESS_HPP\n\n#include <hops/RandomNumberGenerator/RandomNumberGenerator.hpp>\n\n#include <Eigen/Core>\n#include <Eigen/Cholesky>\n#include <Eigen/SVD>\n\n#include <random>\n#include <vector>\n#include <cmath>\n\n#include <iostream>\n\nnamespace hops {\n    namespace internal{\n        template<typename MatrixType>\n        MatrixType append(const MatrixType& rhs, const MatrixType& lhs) {\n            MatrixType newRhs(rhs.rows() + lhs.rows(), lhs.cols());\n            if (rhs.size() > 0) {\n                newRhs << rhs, lhs;\n            } else {\n                newRhs << lhs;\n            }\n            return newRhs;\n        }\n\n        template<typename MatrixType, typename VectorType>\n        MatrixType append(const MatrixType& rhs, const VectorType& lhs) {\n            MatrixType newRhs(rhs.rows() + 1, lhs.cols());\n            if (rhs.size() > 0) {\n                newRhs << rhs, lhs.transpose();\n            } else {\n                newRhs << lhs.transpose();\n            }\n            return newRhs;\n        }\n\n        template<typename VectorType>\n        VectorType append(const VectorType& rhs, double lhs) {\n            VectorType newRhs(rhs.rows() + 1);\n            if (rhs.size() > 0) {\n                newRhs << rhs, lhs;\n            } else {\n                newRhs << lhs;\n            }\n            return newRhs;\n        }\n    }\n\n    template<typename MatrixType, typename VectorType, typename Kernel>\n    class GaussianProcess {\n    public:\n        GaussianProcess (Kernel kernel, double constantPriorMean = 0) :\n                kernel(kernel), isNewObservations(true) {\n            priorMeanFunction = [=](VectorType) -> double { return constantPriorMean; };\n        }\n\n        GaussianProcess (Kernel kernel, std::function<double (VectorType)> priorMeanFunction) :\n                priorMeanFunction(priorMeanFunction),\n                kernel(kernel),\n                isNewObservations(true) {\n            //\n        }\n\n        GaussianProcess getPriorCopy() {\n            return GaussianProcess<MatrixType, VectorType, Kernel>(this->kernel, this->priorMeanFunction);\n        }\n\n        GaussianProcess getPosteriorCopy() {\n            GaussianProcess<MatrixType, VectorType, Kernel> gp = this->getPriorCopy();\n            gp.storedInputs = storedInputs;\n            gp.inputPriorMean = inputPriorMean;\n            //gp.inputAggregatedErrors = inputAggregatedErrors;\n            gp.observationInputCovariance = observationInputCovariance;\n            gp.inputCovariance = inputCovariance;\n\n            gp.posteriorMean = posteriorMean;\n            gp.posteriorCovariance = posteriorCovariance;\n            gp.sqrtPosteriorCovariance = sqrtPosteriorCovariance;\n\n            gp.isNewObservations = isNewObservations;\n            gp.observedCovariance = observedCovariance;\n            gp.sqrtObservedCovariance = sqrtObservedCovariance;\n            \n            gp.observedInputs = observedInputs;\n            gp.observedValues = observedValues;\n            gp.observedValueErrors = observedValueErrors;\n            return gp;\n        }\n\n        /**\n         *  Compute the posterior mean and covariance for the given input. This method checks, if any data has changed before \n         *  recomputing depending quantities, which makes it rather safe to call it before sampling or querying any posterior data\n         *\n         */\n        void computePosterior(const MatrixType& input) {\n            bool isNewInput = (!storedInputs.size() || input != storedInputs);\n            if (isNewObservations || isNewInput) {\n                observationInputCovariance = kernel(observedInputs, input);\n                //inputAggregatedErrors = aggregateErrors(input);\n                \n                if (isNewInput) {\n                    inputCovariance = kernel(input, input);\n                    inputPriorMean = priorMean(input);\n\n                    storedInputs = input;\n                }\n\n                if (isNewObservations) {\n                    // compute the cholesky factorization on the new observed covariance\n                    sqrtObservedCovariance = observedCovariance.llt().matrixL();\n\n                    assert(sqrtObservedCovariance.isLowerTriangular() \n                            && \"error computing the cholesky factorization of the observed covariance, check code.\");\n\n                    posteriorMean = sqrtObservedCovariance.template triangularView<Eigen::Lower>().solve(observedValues - priorMean(observedInputs));\n                    posteriorMean = sqrtObservedCovariance.template triangularView<Eigen::Lower>().transpose().solve(posteriorMean);\n\n                    posteriorCovariance = sqrtObservedCovariance.template triangularView<Eigen::Lower>().solve(observationInputCovariance);\n                    posteriorCovariance = sqrtObservedCovariance.template triangularView<Eigen::Lower>().transpose().solve(posteriorCovariance);\n                }\n\n//#ifndef NDEBUG\n//            MatrixType invObservedCovariance = observedCovariance.inverse();\n//            MatrixType control = invObservedCovariance * (observedValues - priorMean(observedInputs));\n//            control -= posteriorMean;\n//            assert((control.size() == 0 || control.cwiseAbs().maxCoeff() < 1.e-5) && \"computing the inverse for control might have failed.\");\n//#endif \n\n                posteriorMean = inputPriorMean + observationInputCovariance.transpose() * posteriorMean;\n\n//#ifndef NDEBUG\n//            control = invObservedCovariance * observationInputCovariance;\n//            control -= posteriorCovariance;\n//            assert((control.size() == 0 || control.cwiseAbs().maxCoeff() < 1.e-5) && \"computing the inverse for control might have failed.\");\n//#endif \n\n                posteriorCovariance = inputCovariance - observationInputCovariance.transpose() * posteriorCovariance;\n                //posteriorCovariance += inputAggregatedErrors.asDiagonal();\n\n                Eigen::BDCSVD<MatrixType> solver(MatrixType(posteriorCovariance), Eigen::ComputeFullU);\n                sqrtPosteriorCovariance = solver.matrixU() * solver.singularValues().cwiseSqrt().asDiagonal();\n\n                isNewObservations = false;\n            }\n        }\n\n        /**\n         * Sample from posterior at x\n         *\n         */\n        Eigen::VectorXd sample(const MatrixType& input, \n                               hops::RandomNumberGenerator& randomNumberGenerator, \n                               size_t& maxElement) {\n            computePosterior(input); \n\n            VectorType draw(input.rows());\n            auto standardNormal = std::normal_distribution<double>();\n\n            for (long i = 0; i < input.rows(); ++i) {\n                draw(i) = standardNormal(randomNumberGenerator);\n                assert(!std::isnan(draw(i)));\n            }\n\n            draw = posteriorMean + sqrtPosteriorCovariance * draw;\n            draw.maxCoeff(&maxElement);\n\n            return draw;\n        }\n\n        Eigen::VectorXd sample(hops::RandomNumberGenerator& randomNumberGenerator, \n                               size_t& maxElement) {\n            return sample(storedInputs, randomNumberGenerator, maxElement);\n        }\n\n        Eigen::VectorXd sample(const MatrixType& x, \n                               hops::RandomNumberGenerator& randomNumberGenerator) {\n            size_t max;\n            return sample(x, randomNumberGenerator, max);\n        }\n\n        Eigen::VectorXd sample(hops::RandomNumberGenerator& randomNumberGenerator) {\n            size_t max;\n            return sample(storedInputs, randomNumberGenerator, max);\n        }\n\n        /**\n         *  Given an observation (x_i, y_i, eps_i) stored in *this, if there is an x_j in the argument x passed, s.t. x_i = x_j, then\n         *  y_i := x_j and eps_i := y_j\n         *\n         *  All x_j and the respective y_j and eps_j from the passed arguments, which were not found in *this, will be stored in the reference arguments\n         *  x, y and error.\n         *\n         *  The isUnique argument controls, whether x may be assumed to be unique in *this. If isUnique == true, then only the data at the first \n         *  occurence of x_i in *this will be updated.\n         */\n        std::tuple<MatrixType, MatrixType, VectorType> updateObservations(const MatrixType& x, \n                                                                          const VectorType& y, \n                                                                          const VectorType& error, \n                                                                          bool isUnique = false) {\n            assert(x.size() == y.size());\n            assert(y.size() == error.size());\n\n            // collect indices of observations which should be updated\n            std::vector<long> updateCandidates;\n            std::vector<long> notFound;\n            for (long i = 0; i < x.rows(); ++i) {\n                bool foundInput = false;\n                for (long j = 0; j < observedInputs.rows(); ++j) {\n                    if (x.row(i) == observedInputs.row(j)) {\n                        updateCandidates.push_back(j);\n                        foundInput = true;\n\n                        if (isUnique) {\n                            break;\n                        }\n                    }\n                }\n\n                // record data which could not be updated, because it was not stored in *this the first place\n                // this data is \"returned\" in the reference arguments, such that it can be added after this function returns\n                if (!foundInput) {\n                    notFound.push_back(i);\n                }\n            }\n\n            // if any entries were updated, set the isNewObservations flag\n            if (updateCandidates.size() > 0) {\n                isNewObservations = true;\n            }\n\n            for (size_t i = 0; i < updateCandidates.size(); ++i) {\n                size_t k = updateCandidates[i];\n\n                // update the data\n                observedValues(k) = y(i);\n                observedValueErrors(k) = error(i);\n\n                // update the observed covariance \n                //observedCovariance.row(k) = kernel({observedInputs[k]}, observedInputs);\n                //observedCovariance.col(k) = observedCovariance.row(k).transpose();\n                observedCovariance(k, k) = kernel(observedInputs.row(k), observedInputs.row(k))(0, 0) + observedValueErrors(k);\n                //observedCovariance(k, k) += 1.e-5;\n            }\n\n//#ifndef NDEBUG\n//            MatrixType control = kernel(observedInputs, observedInputs);\n//            control -= observedCovariance;\n//            assert(control.size() == 0 || control.cwiseAbs().maxCoeff() < 1.e-5);\n//#endif\n\n            MatrixType inputsNotFound(notFound.size(), x.cols());\n            VectorType valuesNotFound(notFound.size());\n            VectorType errorsNotFound(notFound.size());\n\n            for (size_t i = 0; i < notFound.size(); ++i) {\n                long k = notFound[i];\n\n                inputsNotFound.row(i) = x.row(k);\n                valuesNotFound.row(i) = y.row(k);\n                errorsNotFound.row(i) = error.row(k);\n            }\n\n            //x = inputsNotFound;\n            //y = valuesNotFound;\n            //error = errorsNotFound;\n            return {inputsNotFound, valuesNotFound, errorsNotFound};\n        }\n\n        //void updateObservations(MatrixType& x, \n        //                        VectorType& y, \n        //                        VectorType& error, \n        //                        bool isUnique = false) {\n        //    std::tie(x, y, error) = updateObservationsConstArgs(x, y, error);\n        //}\n\n        void updateObservations(const MatrixType& x, const VectorType& y) {\n            updateObservations(x, y, VectorType::Zeros(y.rows()));\n        }\n\n        //void updateObservation(const VectorType& x, double y, double error = 0) {\n        //    updateObservations({x}, {y}, {error});\n        //}\n\n        void addObservations(const MatrixType& x, VectorType& y, VectorType& error) {\n            assert(x.size() == y.size());\n            assert(y.size() == error.size());\n\n            isNewObservations = true;\n\n            auto n = observedValues.size();\n            auto m = x.size();\n\n            //VectorType newObservedValues = VectorType(n + m);\n            //newObservedValues << observedValues, y;\n            observedValues = internal::append(observedValues, y);\n\n            //VectorType newObservedValueErrors = VectorType(n + m);\n            //newObservedValueErrors << observedValueErrors, error;\n            observedValueErrors = internal::append(observedValueErrors, error);\n\n            MatrixType newObservedCovariance = MatrixType::Zero(n + m, n + m);\n            \n            newObservedCovariance.block(0, 0, n, n) = observedCovariance; // hopefully saves some computation time\n            newObservedCovariance.block(0, n, n, m) = kernel(observedInputs, x);\n            newObservedCovariance.block(n, 0, m, n) = newObservedCovariance.block(0, n, n, m).transpose().eval();\n            newObservedCovariance.block(n, n, m, m) = kernel(x, x);\n            //newObservedCovariance.block(n, n, m, m).diagonal().array() += 1.e-5;\n\n            newObservedCovariance.block(n, n, m, m) += Eigen::MatrixXd(error.asDiagonal());\n\n            //MatrixType newObservedInputs = MatrixType::Zero(n + m, n + m);\n            //newObservedInputs << observedInputs, x;\n            observedInputs = internal::append(observedInputs, x);\n            \n#ifndef NDEBUG\n            MatrixType control = kernel(observedInputs, observedInputs);\n            control += Eigen::MatrixXd(observedValueErrors.asDiagonal());\n            //control.diagonal().array() += 1.e-5;\n            control -= newObservedCovariance;\n            assert((control.size() == 0 || control.cwiseAbs().maxCoeff() < 1.e-5));\n#endif\n\n            //observedInputs = newObservedInputs;\n            //observedValues = newObservedValues;\n            //observedValueErrors = newObservedValueErrors;\n            observedCovariance = newObservedCovariance;\n            //observedCovariance = observedCovariance;\n        }\n\n        void addObservations(const MatrixType& x, const VectorType& y) {\n            addObservations(x, y, VectorType::Zeros(y.rows()));\n        }\n\n        //void addObservation(const VectorType& x, double y, double error = 0) {\n        //    addObservations({x}, {y}, {error});\n        //}\n\n        const VectorType& getPosteriorMean() { \n            computePosterior(storedInputs);\n            return posteriorMean; \n        }\n\n        const MatrixType& getPosteriorCovariance() { \n            computePosterior(storedInputs);\n            return posteriorCovariance; \n        }\n\n        const MatrixType& getSqrtPosteriorCovariance() { \n            computePosterior(storedInputs);\n            return sqrtPosteriorCovariance; \n        }\n\n        const MatrixType& getObservedInputs() const { return observedInputs; }\n        const VectorType& getObservedValues() const { return observedValues; }\n        const VectorType& getObservedValueErrors() const { return observedValueErrors; }\n\n        const MatrixType& getObservedCovariance() const { return observedCovariance; }\n\n        std::function<double (VectorType)>& getPriorMeanFunction() {\n            return priorMeanFunction;\n        }\n\n        Kernel getKernel() {\n            return kernel;\n        }\n\n    private:\n        std::function<double (VectorType)> priorMeanFunction;\n        Kernel kernel;\n\n        MatrixType storedInputs;\n        VectorType inputPriorMean;\n        //VectorType inputAggregatedErrors;\n        MatrixType observationInputCovariance;\n        MatrixType inputCovariance;\n\n        VectorType posteriorMean;\n        MatrixType posteriorCovariance;\n        MatrixType sqrtPosteriorCovariance;\n\n        bool isNewObservations;\n        MatrixType observedCovariance;\n        MatrixType sqrtObservedCovariance;\n        \n        MatrixType observedInputs;\n        VectorType observedValues;\n        VectorType observedValueErrors;\n\n        VectorType priorMean(const MatrixType& x) {\n            VectorType prior(x.rows());\n            for (long i = 0; i < x.rows(); ++i) {\n                prior(i) = priorMeanFunction(x.row(i));\n            }\n            return prior;\n        }\n\n        //VectorType aggregateErrors(const std::vector<VectorType>& x) {\n        //    VectorType errors(x.size());\n        //    for (size_t i = 0; i < x.size(); ++i) {\n        //        double mean = 0, error = 0;\n        //        size_t count = 0;\n        //        \n        //        for (size_t j = 0; j < observedInputs.size(); ++j) {\n        //            if (x[i] == observedInputs[j]) {\n        //                ++count;\n        //                mean += observedValues(j);\n        //                error += std::pow(observedValueErrors(j), 2) + std::pow(observedValues(j), 2);\n        //            }\n        //        }\n\n        //        if (count > 0) {\n        //            mean /= count;\n        //            error /= count;\n        //            error -= std::pow(mean, 2);\n        //        }\n\n        //        assert(error >= 0);\n        //        errors(i) = error;\n        //    }\n        //    return errors;\n        //}\n    };\n}\n\n#endif // HOPS_GAUSSIANPROCESS_HPP\n", "meta": {"hexsha": "3fdff1934c6d4009f568e75a1ff78df83f2c71c0", "size": 17301, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/hops/Optimization/GaussianProcess.hpp", "max_stars_repo_name": "modsim/hops", "max_stars_repo_head_hexsha": "4285dd75a07dd844295440a0756b3ba25f5819ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2020-11-26T05:13:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T02:08:40.000Z", "max_issues_repo_path": "include/hops/Optimization/GaussianProcess.hpp", "max_issues_repo_name": "modsim/hops", "max_issues_repo_head_hexsha": "4285dd75a07dd844295440a0756b3ba25f5819ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-02-20T23:16:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-20T23:16:34.000Z", "max_forks_repo_path": "include/hops/Optimization/GaussianProcess.hpp", "max_forks_repo_name": "modsim/hops", "max_forks_repo_head_hexsha": "4285dd75a07dd844295440a0756b3ba25f5819ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.3286713287, "max_line_length": 152, "alphanum_fraction": 0.5611814346, "num_tokens": 3716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.48717556320583105}}
{"text": "#include <geometry.h>\n#include <tiny_math_types.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n\nBOOST_AUTO_TEST_SUITE(geometry);\n\nBOOST_AUTO_TEST_CASE(raycast_triangle)\n{\n\n  using std::sqrt;\n\n  typedef tiny::MathTypes<double>   MT;\n  typedef MT::vector3_type          V;\n  typedef MT::real_type             T;\n  typedef MT::value_traits          VT;\n\n\n  V const p0 = V::make(0.0, 0.0, 0.0);\n  V const p1 = V::make(1.0, 0.0, 0.0);\n  V const p2 = V::make(0.0, 1.0, 0.0);\n\n  geometry::Triangle<V> const triangle = geometry::make_triangle(p0,p1,p2);\n\n  // Ray hitting from front\n  {\n    V                const p   = V::make( 0.0, 0.0, 1.0);\n    V                const r   = V::make( 0.2, 0.2, -1.0);\n    geometry::Ray<V> const ray = geometry::make_ray(p, r);\n\n    T       length = VT::zero();\n    V       q      = V::zero();\n\n    bool hit = geometry::compute_raycast_triangle(ray, triangle, q, length, true );\n\n    BOOST_CHECK( hit );\n    BOOST_CHECK_CLOSE( length, tiny::norm(r), 0.01);\n    BOOST_CHECK_CLOSE( q(0),  0.2, 0.01);\n    BOOST_CHECK_CLOSE( q(1),  0.2, 0.01);\n    BOOST_CHECK_CLOSE( q(2),  0.0, 0.01);\n  }\n  // Ray hitting from front\n  {\n    V                const p   = V::make( 0.0, 0.0, 1.0);\n    V                const r   = V::make( 0.2, 0.2, -1.0);\n    geometry::Ray<V> const ray = geometry::make_ray(p, r);\n\n    T       length = VT::zero();\n    V       q      = V::zero();\n\n    bool hit = geometry::compute_raycast_triangle(ray, triangle, q, length, false );\n\n    BOOST_CHECK(  hit );\n    BOOST_CHECK_CLOSE( length, tiny::norm(r), 0.01);\n    BOOST_CHECK_CLOSE( q(0),  0.2, 0.01);\n    BOOST_CHECK_CLOSE( q(1),  0.2, 0.01);\n    BOOST_CHECK_CLOSE( q(2),  0.0, 0.01);\n  }\n  // Ray hitting from back\n  {\n    V                const p   = V::make( 0.0, 0.0, -1.0);\n    V                const r   = V::make( 0.2, 0.2,  1.0);\n    geometry::Ray<V> const ray = geometry::make_ray(p, r);\n\n    T       length = VT::zero();\n    V       q      = V::zero();\n\n    bool hit = geometry::compute_raycast_triangle(ray, triangle, q, length, true );\n\n    BOOST_CHECK( !hit );\n  }\n  // Ray hitting from back\n  {\n    V                const p   = V::make( 0.0, 0.0, -1.0);\n    V                const r   = V::make( 0.2, 0.2,  1.0);\n    geometry::Ray<V> const ray = geometry::make_ray(p, r);\n\n    T       length = VT::zero();\n    V       q      = V::zero();\n\n    bool hit = geometry::compute_raycast_triangle(ray, triangle, q, length, false );\n\n    BOOST_CHECK(  hit );\n    BOOST_CHECK_CLOSE( length, tiny::norm(r), 0.01);\n    BOOST_CHECK_CLOSE( q(0),  0.2, 0.01);\n    BOOST_CHECK_CLOSE( q(1),  0.2, 0.01);\n    BOOST_CHECK_CLOSE( q(2),  0.0, 0.01);\n  }\n\n  // Rays missing\n  {\n    V                const p   = V::make( 0.0, 0.0,  1.0);\n    V                const r   = V::make( 0.6, 0.6, -1.0);\n    geometry::Ray<V> const ray = geometry::make_ray(p, r);\n\n    T       length = VT::zero();\n    V       q      = V::zero();\n\n    bool hit = geometry::compute_raycast_triangle(ray, triangle, q, length, false );\n\n    BOOST_CHECK(  !hit );\n  }\n  {\n    V                const p   = V::make( 0.0, 0.0,  1.0);\n    V                const r   = V::make( 0.5,-0.1, -1.0);\n    geometry::Ray<V> const ray = geometry::make_ray(p, r);\n\n    T       length = VT::zero();\n    V       q      = V::zero();\n\n    bool hit = geometry::compute_raycast_triangle(ray, triangle, q, length, false );\n\n    BOOST_CHECK(  !hit );\n  }\n\n  // Ray gracing\n  {\n    V                const p   = V::make( 0.0, 0.0, -1.0);\n    V                const r   = V::make( 0.4999, 0.4999,  1.0);\n    geometry::Ray<V> const ray = geometry::make_ray(p, r);\n\n    T       length = VT::zero();\n    V       q      = V::zero();\n\n    bool hit = geometry::compute_raycast_triangle(ray, triangle, q, length, false );\n\n    BOOST_CHECK(  hit );\n    BOOST_CHECK_CLOSE( length, tiny::norm(r), 0.01);\n    BOOST_CHECK_CLOSE( q(0),  r(0), 0.01);\n    BOOST_CHECK_CLOSE( q(1),  r(1), 0.01);\n    BOOST_CHECK_CLOSE( q(2),  0.0, 0.01);\n  }\n\n\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "3f92f64bebf0f397741f3f6d3cbe2696fcbaf13a", "size": 4148, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/FOUNDATION/GEOMETRY/unit_tests/geometry_raycast_triangle/geometry_raycast_triangle.cpp", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-11-27T09:44:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-13T00:24:21.000Z", "max_issues_repo_path": "PROX/FOUNDATION/GEOMETRY/unit_tests/geometry_raycast_triangle/geometry_raycast_triangle.cpp", "max_issues_repo_name": "erleben/matchstick", "max_issues_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_issues_repo_licenses": ["MIT"], "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/FOUNDATION/GEOMETRY/unit_tests/geometry_raycast_triangle/geometry_raycast_triangle.cpp", "max_forks_repo_name": "erleben/matchstick", "max_forks_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_forks_repo_licenses": ["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.2112676056, "max_line_length": 84, "alphanum_fraction": 0.537608486, "num_tokens": 1398, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.48717556320583105}}
{"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_REM_PIO2_STRAIGHT_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_REM_PIO2_STRAIGHT_HPP_INCLUDED\n\n#include <boost/simd/detail/dispatch/function/overload.hpp>\n#include <boost/config.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/detail/constant/pio2_1.hpp>\n#include <boost/simd/detail/constant/pio2_2.hpp>\n#include <boost/simd/constant/pio2_3.hpp>\n#include <boost/simd/constant/pio_4.hpp>\n#include <boost/simd/detail/dispatch/meta/as_integer.hpp>\n#include <boost/simd/function/if_else.hpp>\n#include <boost/simd/function/is_greater.hpp>\n#include <boost/simd/function/genmask.hpp>\n#include <boost/simd/function/multiplies.hpp>\n#include <boost/simd/function/minus.hpp>\n#include <utility>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  namespace bs = boost::simd;\n\n  BOOST_DISPATCH_OVERLOAD (rem_pio2_straight_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_ < bd::floating_<A0> >\n                          )\n  {\n    using result_t = std::pair<A0, A0>;\n    BOOST_FORCEINLINE result_t operator() ( A0 const& x) const BOOST_NOEXCEPT\n    {\n      if (x < Pio_4<A0>())\n        return {Zero<A0>(), x};\n      A0 xr = x-Pio2_1<A0>();\n      xr -= Pio2_2<A0>();\n      xr -= Pio2_3<A0>();\n      return { One<A0>(), xr};\n    }\n  };\n\n} } }\n\n\n#endif\n", "meta": {"hexsha": "c82754a585106a4f3c5de88b6f3664a6c56af5d0", "size": 1852, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arch/common/scalar/function/rem_pio2_straight.hpp", "max_stars_repo_name": "TobiasLudwig/boost.simd", "max_stars_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_stars_repo_licenses": ["BSL-1.0"], "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": "include/boost/simd/arch/common/scalar/function/rem_pio2_straight.hpp", "max_issues_repo_name": "TobiasLudwig/boost.simd", "max_issues_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/arch/common/scalar/function/rem_pio2_straight.hpp", "max_forks_repo_name": "TobiasLudwig/boost.simd", "max_forks_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-02-16T09:58:18.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:22:43.000Z", "avg_line_length": 32.4912280702, "max_line_length": 100, "alphanum_fraction": 0.6031317495, "num_tokens": 447, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.487175563205831}}
{"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_GESVD_HPP\n#define BOOST_NUMERIC_BINDINGS_LAPACK_GESVD_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/detail/utils.hpp>\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n#  include <boost/static_assert.hpp>\n#  include <boost/type_traits/is_same.hpp>\n#endif \n\n#include <cassert>\n\nnamespace boost { namespace numeric { namespace bindings { \n\n  namespace lapack {\n\n    ///////////////////////////////////////////////////////////////////\n    //\n    // singular value decomposition \n    // \n    ///////////////////////////////////////////////////////////////////\n\n    /* \n     * (simple driver) \n     * gesvd() computes the singular value decomposition (SVD) of \n     * M-by-N matrix A, optionally computing the left and/or right \n     * singular vectors. The SVD is written\n     *\n     *     A = U * S * V^T    or    A = U * S * V^H\n     *\n     * where S is an M-by-N matrix which is zero except for its min(m,n)\n     * diagonal elements, U is an M-by-M orthogonal/unitary matrix, and V \n     * is an N-by-N orthogonal/unitary matrix. The diagonal elements of S\n     * are the singular values of A; they are real and non-negative, and \n     * are returned in descending  order. The first min(m,n) columns of \n     * U and V are the left and right singular vectors of A. (Note that \n     * the routine returns V^T or V^H, not V.\n     */ \n\n    namespace detail {\n\n      inline \n      void gesvd (char const jobu, char const jobvt, \n                  int const m, int const n, float* a, int const lda, \n                  float* s, float* u, int const ldu, \n                  float* vt, int const ldvt,\n                  float* work, int const lwork, float* /* dummy */, \n                  int* info)\n      {\n        LAPACK_SGESVD (&jobu, &jobvt, &m, &n, a, &lda, \n                       s, u, &ldu, vt, &ldvt, work, &lwork, info); \n      }\n\n      inline \n      void gesvd (char const jobu, char const jobvt, \n                  int const m, int const n, double* a, int const lda, \n                  double* s, double* u, int const ldu, \n                  double* vt, int const ldvt,\n                  double* work, int const lwork, double* /* dummy */, \n                  int* info)\n      {\n        LAPACK_DGESVD (&jobu, &jobvt, &m, &n, a, &lda, \n                       s, u, &ldu, vt, &ldvt, work, &lwork, info); \n      }\n\n      inline \n      void gesvd (char const jobu, char const jobvt, \n                  int const m, int const n, \n                  traits::complex_f* a, int const lda, \n                  float* s, traits::complex_f* u, int const ldu, \n                  traits::complex_f* vt, int const ldvt,\n                  traits::complex_f* work, int const lwork, \n                  float* rwork, int* info)\n      {\n        LAPACK_CGESVD (&jobu, &jobvt, &m, &n, \n                       traits::complex_ptr (a), &lda, s, \n                       traits::complex_ptr (u), &ldu, \n                       traits::complex_ptr (vt), &ldvt, \n                       traits::complex_ptr (work), &lwork, rwork, info); \n      }\n\n      inline \n      void gesvd (char const jobu, char const jobvt, \n                  int const m, int const n, \n                  traits::complex_d* a, int const lda, \n                  double* s, traits::complex_d* u, int const ldu, \n                  traits::complex_d* vt, int const ldvt,\n                  traits::complex_d* work, int const lwork, \n                  double* rwork, int* info)\n      {\n        LAPACK_ZGESVD (&jobu, &jobvt, &m, &n, \n                       traits::complex_ptr (a), &lda, s, \n                       traits::complex_ptr (u), &ldu, \n                       traits::complex_ptr (vt), &ldvt, \n                       traits::complex_ptr (work), &lwork, rwork, info); \n      }\n\n      inline \n      int gesvd_min_work (float, int m, int n) {\n        int minmn = m < n ? m : n; \n        int maxmn = m < n ? n : m; \n        int m3x = 3 * minmn + maxmn; \n        int m5 = 5 * minmn; \n        return m3x < m5 ? m5 : m3x; \n      }\n      inline \n      int gesvd_min_work (double, int m, int n) {\n        int minmn = m < n ? m : n; \n        int maxmn = m < n ? n : m; \n        int m3x = 3 * minmn + maxmn; \n        int m5 = 5 * minmn; \n        return m3x < m5 ? m5 : m3x; \n      }\n      inline \n      int gesvd_min_work (traits::complex_f, int m, int n) {\n        int minmn = m < n ? m : n; \n        int maxmn = m < n ? n : m; \n        return 2 * minmn + maxmn; \n      }\n      inline \n      int gesvd_min_work (traits::complex_d, int m, int n) {\n        int minmn = m < n ? m : n; \n        int maxmn = m < n ? n : m; \n        return 2 * minmn + maxmn; \n      }\n\n      inline \n      int gesvd_rwork (float, int, int) { return 1; }\n      inline \n      int gesvd_rwork (double, int, int) { return 1; }\n      inline \n      int gesvd_rwork (traits::complex_f, int m, int n) {\n        return 5 * (m < n ? m : n);\n      }\n      inline \n      int gesvd_rwork (traits::complex_d, int m, int n) {\n        return 5 * (m < n ? m : n);\n      }\n\n    } // detail \n\n\n    template <typename MatrA> \n    inline\n    int gesvd_work (char const q, \n                    char const jobu, char const jobvt, MatrA const& a) \n    {\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrA>::matrix_structure, \n        traits::general_t\n      >::value)); \n#endif \n\n#ifdef BOOST_NUMERIC_BINDINGS_LAPACK_2\n      assert (q == 'M'); \n#else\n      assert (q == 'M' || q == 'O'); \n#endif \n      assert (jobu == 'N' || jobu == 'O' || jobu == 'A' || jobu == 'S'); \n      assert (jobvt == 'N' || jobvt == 'O' || jobvt == 'A' || jobvt == 'S'); \n      assert (!(jobu == 'O' && jobvt == 'O')); \n\n      int const m = traits::matrix_size1 (a);\n      int const n = traits::matrix_size2 (a);\n      int lw = -13; \n\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n      typedef typename traits::matrix_traits<MatrA>::value_type val_t; \n#else \n      typedef typename MatrA::value_type val_t; \n#endif \n\n      if (q == 'M') \n        lw = detail::gesvd_min_work (val_t(), m, n);\n\n#ifndef BOOST_NUMERIC_BINDINGS_LAPACK_2\n      MatrA& a2 = const_cast<MatrA&> (a); \n      if (q == 'O') {\n        // traits::detail::array<val_t> w (0); \n        val_t w; \n        int info; \n        detail::gesvd (jobu, jobvt, m, n, \n                       traits::matrix_storage (a2), \n                       traits::leading_dimension (a2),\n                       0, // traits::vector_storage (s),  \n                       0, // traits::matrix_storage (u),\n                       m, // traits::leading_dimension (u),\n                       0, // traits::matrix_storage (vt),\n                       n, // traits::leading_dimension (vt),\n                       &w, // traits::vector_storage (w),  \n                       -1, // traits::vector_size (w),  \n                       0, // traits::vector_storage (rw),  \n                       &info);\n        assert (info == 0); \n        lw = traits::detail::to_int (w);  // (w[0]); \n      }\n#endif \n      \n      return lw; \n    }\n\n\n    template <typename MatrA> \n    inline\n    int gesvd_rwork (MatrA const& a) {\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrA>::matrix_structure, \n        traits::general_t\n      >::value)); \n#endif \n\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n      typedef typename traits::matrix_traits<MatrA>::value_type val_t; \n#else \n      typedef typename MatrA::value_type val_t; \n#endif \n\n      return detail::gesvd_rwork (val_t(), \n                                  traits::matrix_size1 (a),\n                                  traits::matrix_size2 (a));\n    }\n\n\n    template <typename MatrA, typename VecS, \n              typename MatrU, typename MatrV, typename VecW>\n    inline\n    int gesvd (char const jobu, char const jobvt, \n               MatrA& a, VecS& s, MatrU& u, MatrV& vt, VecW& w) \n    {\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrA>::matrix_structure, \n        traits::general_t\n      >::value)); \n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrU>::matrix_structure, \n        traits::general_t\n      >::value)); \n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrV>::matrix_structure, \n        traits::general_t\n      >::value)); \n\n      BOOST_STATIC_ASSERT(\n        (boost::is_same<\n          typename traits::matrix_traits<MatrA>::value_type, float\n        >::value\n        ||\n        boost::is_same<\n          typename traits::matrix_traits<MatrA>::value_type, double\n        >::value));\n#endif \n\n      int const m = traits::matrix_size1 (a);\n      int const n = traits::matrix_size2 (a);\n#ifndef NDEBUG /* this variable is only used in assertions below */\n      int const minmn = m < n ? m : n; \n#endif\n\n      assert (minmn == traits::vector_size (s)); \n      assert (!(jobu == 'O' && jobvt == 'O')); \n      assert ((jobu == 'N')\n              || (jobu == 'O')\n              || (jobu == 'A' && m == traits::matrix_size2 (u))\n              || (jobu == 'S' && minmn == traits::matrix_size2 (u))); \n      assert ((jobu == 'N' && traits::leading_dimension (u) >= 1)\n              || (jobu == 'O' && traits::leading_dimension (u) >= 1)\n              || (jobu == 'A' && traits::leading_dimension (u) >= m)\n              || (jobu == 'S' && traits::leading_dimension (u) >= m));\n      assert (n == traits::matrix_size2 (vt)); \n      assert ((jobvt == 'N' && traits::leading_dimension (vt) >= 1)\n              || (jobvt == 'O' && traits::leading_dimension (vt) >= 1)\n              || (jobvt == 'A' && traits::leading_dimension (vt) >= n)\n              || (jobvt == 'S' && traits::leading_dimension (vt) >= minmn));\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n      typedef typename traits::matrix_traits<MatrA>::value_type val_t; \n#else \n      typedef typename MatrA::value_type val_t; \n#endif \n      assert (traits::vector_size(w) >= detail::gesvd_min_work(val_t(),m,n)); \n\n      int info; \n      detail::gesvd (jobu, jobvt, m, n, \n                     traits::matrix_storage (a), \n                     traits::leading_dimension (a),\n                     traits::vector_storage (s),  \n                     traits::matrix_storage (u),\n                     traits::leading_dimension (u),\n                     traits::matrix_storage (vt),\n                     traits::leading_dimension (vt),\n                     traits::vector_storage (w),  \n                     traits::vector_size (w),  \n                     0, // dummy argument \n                     &info);\n      return info; \n    }\n\n\n    template <typename MatrA, typename VecS, \n              typename MatrU, typename MatrV, typename VecW, typename VecRW>\n    inline\n    int gesvd (char const jobu, char const jobvt, \n               MatrA& a, VecS& s, MatrU& u, MatrV& vt, VecW& w, VecRW& rw) \n    {\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrA>::matrix_structure, \n        traits::general_t\n      >::value)); \n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrU>::matrix_structure, \n        traits::general_t\n      >::value)); \n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrV>::matrix_structure, \n        traits::general_t\n      >::value)); \n#endif \n\n      int const m = traits::matrix_size1 (a);\n      int const n = traits::matrix_size2 (a);\n#ifndef NDEBUG /* this variable is only used in assertions below */\n      int const minmn = m < n ? m : n; \n#endif\n\n      assert (minmn == traits::vector_size (s)); \n      assert (!(jobu == 'O' && jobvt == 'O')); \n      assert ((jobu == 'N')\n              || (jobu == 'O')\n              || (jobu == 'A' && m == traits::matrix_size2 (u))\n              || (jobu == 'S' && minmn == traits::matrix_size2 (u))); \n      assert ((jobu == 'N' && traits::leading_dimension (u) >= 1)\n              || (jobu == 'O' && traits::leading_dimension (u) >= 1)\n              || (jobu == 'A' && traits::leading_dimension (u) >= m)\n              || (jobu == 'S' && traits::leading_dimension (u) >= m));\n      assert (n == traits::matrix_size2 (vt)); \n      assert ((jobvt == 'N' && traits::leading_dimension (vt) >= 1)\n              || (jobvt == 'O' && traits::leading_dimension (vt) >= 1)\n              || (jobvt == 'A' && traits::leading_dimension (vt) >= n)\n              || (jobvt == 'S' && traits::leading_dimension (vt) >= minmn));\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n      typedef typename traits::matrix_traits<MatrA>::value_type val_t; \n#else \n      typedef typename MatrA::value_type val_t; \n#endif \n      assert (traits::vector_size(w) >= detail::gesvd_min_work(val_t(),m,n)); \n      assert (traits::vector_size(rw) >= detail::gesvd_rwork(val_t(),m,n));\n\n      int info; \n      detail::gesvd (jobu, jobvt, m, n, \n                     traits::matrix_storage (a), \n                     traits::leading_dimension (a),\n                     traits::vector_storage (s),  \n                     traits::matrix_storage (u),\n                     traits::leading_dimension (u),\n                     traits::matrix_storage (vt),\n                     traits::leading_dimension (vt),\n                     traits::vector_storage (w),  \n                     traits::vector_size (w),  \n                     traits::vector_storage (rw),  \n                     &info);\n      return info; \n    }\n\n\n    template <typename MatrA, typename VecS, typename MatrU, typename MatrV>\n    inline\n    int gesvd (char const opt, char const jobu, char const jobvt, \n               MatrA& a, VecS& s, MatrU& u, MatrV& vt) \n    {\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrA>::matrix_structure, \n        traits::general_t\n      >::value)); \n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrU>::matrix_structure, \n        traits::general_t\n      >::value)); \n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrV>::matrix_structure, \n        traits::general_t\n      >::value)); \n#endif \n\n      int const m = traits::matrix_size1 (a);\n      int const n = traits::matrix_size2 (a);\n#ifndef NDEBUG /* this variable is only used in assertions below */\n      int const minmn = m < n ? m : n; \n#endif\n\n      assert (minmn == traits::vector_size (s)); \n      assert (!(jobu == 'O' && jobvt == 'O')); \n      assert ((jobu == 'N')\n              || (jobu == 'O')\n              || (jobu == 'A' && m == traits::matrix_size2 (u))\n              || (jobu == 'S' && minmn == traits::matrix_size2 (u))); \n      assert ((jobu == 'N' && traits::leading_dimension (u) >= 1)\n              || (jobu == 'O' && traits::leading_dimension (u) >= 1)\n              || (jobu == 'A' && traits::leading_dimension (u) >= m)\n              || (jobu == 'S' && traits::leading_dimension (u) >= m));\n      assert ((jobvt == 'N' || traits::matrix_size2(vt) == n)) ;\n      assert ((jobvt == 'N' && traits::leading_dimension (vt) >= 1)\n              || (jobvt == 'O' && traits::leading_dimension (vt) >= 1)\n              || (jobvt == 'A' && traits::leading_dimension (vt) >= n)\n              || (jobvt == 'S' && traits::leading_dimension (vt) >= minmn));\n\n#ifdef BOOST_NUMERIC_BINDINGS_LAPACK_2\n      assert (opt == 'M'); \n#else\n      assert (opt == 'M' || opt == 'O'); \n#endif \n\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n      typedef typename traits::matrix_traits<MatrA>::value_type val_t; \n#else \n      typedef typename MatrA::value_type val_t; \n#endif \n      typedef typename traits::type_traits<val_t>::real_type real_t;\n\n      int const lw = gesvd_work (opt, jobu, jobvt, a); \n      traits::detail::array<val_t> w (lw); \n      if (!w.valid()) return -101; \n\n      int const lrw = gesvd_rwork (a); \n      traits::detail::array<real_t> rw (lrw); \n      if (!rw.valid()) return -102; \n\n      int info; \n      detail::gesvd (jobu, jobvt, m, n, \n                     traits::matrix_storage (a), \n                     traits::leading_dimension (a),\n                     traits::vector_storage (s),  \n                     traits::matrix_storage (u),\n                     traits::leading_dimension (u),\n                     traits::matrix_storage (vt),\n                     traits::leading_dimension (vt),\n                     traits::vector_storage (w),  \n                     traits::vector_size (w),  \n                     traits::vector_storage (rw),  \n                     &info);\n      return info; \n    }\n\n\n#ifndef BOOST_NUMERIC_BINDINGS_LAPACK_2\n\n    template <typename MatrA, typename VecS, typename MatrU, typename MatrV>\n    inline\n    int gesvd (char const jobu, char const jobvt, \n               MatrA& a, VecS& s, MatrU& u, MatrV& vt) \n    {\n      return gesvd ('O', jobu, jobvt, a, s, u, vt); \n    }\n\n    template <typename MatrA, typename VecS, typename MatrU, typename MatrV>\n    inline\n    int gesvd (MatrA& a, VecS& s, MatrU& u, MatrV& vt) {\n      return gesvd ('O', 'S', 'S', a, s, u, vt); \n    }\n\n    template <typename MatrA, typename VecS> \n    inline\n    int gesvd (MatrA& a, VecS& s) {\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrA>::matrix_structure, \n        traits::general_t\n      >::value)); \n#endif \n\n      int const m = traits::matrix_size1 (a);\n      int const n = traits::matrix_size2 (a);\n#ifndef NDEBUG /* this variable is only used in assertions below */\n      int const minmn = m < n ? m : n; \n#endif\n\n      assert (minmn == traits::vector_size (s)); \n\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n      typedef typename traits::matrix_traits<MatrA>::value_type val_t; \n#else \n      typedef typename MatrA::value_type val_t; \n#endif \n      typedef typename traits::type_traits<val_t>::real_type real_t;\n\n      int const lw = gesvd_work ('O', 'N', 'N', a); \n      traits::detail::array<val_t> w (lw); \n      if (!w.valid()) return -101; \n\n      int const lrw = gesvd_rwork (a); \n      traits::detail::array<real_t> rw (lrw); \n      if (!rw.valid()) return -102; \n\n      int info; \n      detail::gesvd ('N', 'N', m, n, \n                     traits::matrix_storage (a), \n                     traits::leading_dimension (a),\n                     traits::vector_storage (s),  \n                     0, // traits::matrix_storage (u),\n                     1, // traits::leading_dimension (u),\n                     0, // traits::matrix_storage (vt),\n                     1, // traits::leading_dimension (vt),\n                     traits::vector_storage (w),  \n                     traits::vector_size (w),  \n                     traits::vector_storage (rw),  \n                     &info);\n      return info; \n    }\n\n#endif \n\n  } // namespace lapack\n\n}}}\n\n#endif \n", "meta": {"hexsha": "a40ab77c46081a0b784a65aa6b88ca8cc2b223c0", "size": 19547, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/bindings/lapack/gesvd.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/gesvd.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/gesvd.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": 35.9981583794, "max_line_length": 78, "alphanum_fraction": 0.5364506062, "num_tokens": 5231, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4871755568948}}
{"text": " /*\r\n *  Copyright 2007-2015 The OpenMx Project\r\n *\r\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  you may not use this file except in compliance with the License.\r\n *  You may obtain a copy of the License at\r\n *\r\n *       http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n *   Unless required by applicable law or agreed to in writing, software\r\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  See the License for the specific language governing permissions and\r\n *  limitations under the License.\r\n */\r\n\r\n#include \"omxFitFunction.h\"\r\n#include \"omxGREMLfitfunction.h\"\r\n#include \"omxGREMLExpectation.h\"\r\n#include <Eigen/Core>\r\n#include <Eigen/Cholesky>\r\n#include <Eigen/Dense>\r\n\r\nstruct omxGREMLFitState { \r\n  //TODO(?): Some of these members might be redundant with what's stored in the FitContext, \r\n  //and could therefore be cut\r\n  omxMatrix *y, *X, *cov, *invcov, *means;\r\n  std::vector< omxMatrix* > dV;\r\n  std::vector< const char* > dVnames;\r\n  int dVlength, usingGREMLExpectation;\r\n  double nll, REMLcorrection;\r\n  Eigen::VectorXd gradient;\r\n  Eigen::MatrixXd avgInfo; //the Average Information matrix\r\n  FreeVarGroup *varGroup;\r\n\tstd::vector<int> gradMap;\r\n  void buildParamMap(FreeVarGroup *newVarGroup);\r\n}; \r\n\r\n\r\nvoid omxInitGREMLFitFunction(omxFitFunction *oo){\r\n  \r\n  if(OMX_DEBUG) { mxLog(\"Initializing GREML fitfunction.\"); }\r\n  SEXP rObj = oo->rObj;\r\n  SEXP dV, dVnames;\r\n  int i=0;\r\n  \r\n  oo->units = FIT_UNITS_MINUS2LL;\r\n  oo->computeFun = omxCallGREMLFitFunction;\r\n  oo->ciFun = loglikelihoodCIFun;\r\n  oo->destructFun = omxDestroyGREMLFitFunction;\r\n  oo->populateAttrFun = omxPopulateGREMLAttributes;\r\n  \r\n  omxGREMLFitState *newObj = new omxGREMLFitState;\r\n  oo->argStruct = (void*)newObj;\r\n  omxExpectation* expectation = oo->expectation;\r\n  omxState* currentState = expectation->currentState;\r\n  newObj->usingGREMLExpectation = (strcmp(expectation->expType, \"MxExpectationGREML\")==0 ? 1 : 0);\r\n  if(!newObj->usingGREMLExpectation){\r\n    //Maybe someday GREML fitfunction could be made compatible with another expectation, but not at present:\r\n    Rf_error(\"GREML fitfunction is currently only compatible with GREML expectation\");\r\n  }\r\n  else{\r\n    omxGREMLExpectation* oge = (omxGREMLExpectation*)(expectation->argStruct);\r\n    oge->alwaysComputeMeans = 0;\r\n  }\r\n\r\n  newObj->y = omxGetExpectationComponent(expectation, oo, \"y\");\r\n  newObj->cov = omxGetExpectationComponent(expectation, oo, \"cov\");\r\n  newObj->invcov = omxGetExpectationComponent(expectation, oo, \"invcov\");\r\n  newObj->X = omxGetExpectationComponent(expectation, oo, \"X\");\r\n  newObj->means = omxGetExpectationComponent(expectation, oo, \"means\");\r\n  newObj->nll = 0;\r\n  newObj->REMLcorrection = 0;\r\n  newObj->varGroup = NULL;\r\n  \r\n  //Derivatives:\r\n  {ScopedProtect p1(dV, R_do_slot(rObj, Rf_install(\"dV\")));\r\n  ScopedProtect p2(dVnames, R_do_slot(rObj, Rf_install(\"dVnames\")));\r\n  newObj->dVlength = Rf_length(dV);  \r\n  newObj->dV.resize(newObj->dVlength);\r\n  newObj->dVnames.resize(newObj->dVlength);\r\n\tif(newObj->dVlength){\r\n    if(!newObj->usingGREMLExpectation){\r\n      //Probably best not to allow use of dV if we aren't sure means will be calculated GREML-GLS way:\r\n      Rf_error(\"derivatives of 'V' matrix in GREML fitfunction only compatible with GREML expectation\");\r\n    }\r\n    if(OMX_DEBUG) { mxLog(\"Processing derivatives of V.\"); }\r\n\t\tint* dVint = INTEGER(dV);\r\n    for(i=0; i < newObj->dVlength; i++){\r\n      newObj->dV[i] = omxMatrixLookupFromState1(dVint[i], currentState);\r\n      SEXP elem;\r\n      {ScopedProtect p3(elem, STRING_ELT(dVnames, i));\r\n\t\t\tnewObj->dVnames[i] = CHAR(elem);}\r\n\t}}\r\n  }\r\n  \r\n  if(newObj->dVlength){\r\n    oo->gradientAvailable = true;\r\n    newObj->gradient.setZero(newObj->dVlength,1);\r\n    oo->hessianAvailable = true;\r\n    newObj->avgInfo.setZero(newObj->dVlength,newObj->dVlength);\r\n    for(i=0; i < newObj->dVlength; i++){\r\n      if( (newObj->dV[i]->rows != newObj->cov->rows) || (newObj->dV[i]->cols != newObj->cov->cols) ){\r\n        Rf_error(\"all derivatives of V must have the same dimensions as V\");\r\n}}}}\r\n\r\n\r\n\r\nvoid omxCallGREMLFitFunction(omxFitFunction *oo, int want, FitContext *fc){\r\n  if (want & (FF_COMPUTE_PREOPTIMIZE)) return;\r\n  \r\n  //Recompute Expectation:\r\n  omxExpectation* expectation = oo->expectation;\r\n  omxExpectationCompute(expectation, NULL);\r\n    \r\n  omxGREMLFitState *gff = (omxGREMLFitState*)oo->argStruct; //<--Cast generic omxFitFunction to omxGREMLFitState\r\n  \r\n  //Ensure that the pointer in the GREML fitfunction is directed at the right FreeVarGroup\r\n  //(not necessary for most compute plans):\r\n  if(fc && gff->varGroup != fc->varGroup){\r\n    gff->buildParamMap(fc->varGroup);\r\n\t}\r\n  \r\n  //Declare local variables used in more than one scope in this function:\r\n  const double Scale = fabs(Global->llScale); //<--absolute value of loglikelihood scale\r\n  const double NATLOG_2PI = 1.837877066409345483560659472811;\t//<--log(2*pi)\r\n  int i;\r\n  Eigen::Map< Eigen::MatrixXd > Eigy(omxMatrixDataColumnMajor(gff->y), gff->y->cols, 1);\r\n  Eigen::Map< Eigen::MatrixXd > Vinv(omxMatrixDataColumnMajor(gff->invcov), gff->invcov->rows, gff->invcov->cols);\r\n  EigenMatrixAdaptor EigX(gff->X);\r\n  Eigen::MatrixXd P, Py;\r\n  P.setZero(gff->invcov->rows, gff->invcov->cols);\r\n  double logdetV=0, logdetquadX=0, ytPy=0;\r\n  \r\n  if(want & (FF_COMPUTE_FIT | FF_COMPUTE_GRADIENT | FF_COMPUTE_HESSIAN | FF_COMPUTE_IHESSIAN)){\r\n    if(gff->usingGREMLExpectation){\r\n      omxGREMLExpectation* oge = (omxGREMLExpectation*)(expectation->argStruct);\r\n      \r\n      //Check that factorizations of V and the quadratic form in X succeeded:\r\n      if(oge->cholV_fail_om->data[0]){\r\n        oo->matrix->data[0] = NA_REAL;\r\n        if (fc) fc->recordIterationError(\"expected covariance matrix is non-positive-definite\");\r\n        return;\r\n      }\r\n      if(oge->cholquadX_fail){\r\n        oo->matrix->data[0] = NA_REAL;\r\n        if (fc) fc->recordIterationError(\"Cholesky factorization failed; possibly, the matrix of covariates is rank-deficient\");\r\n        return;\r\n      }\r\n      \r\n      //Log determinant of V:\r\n      logdetV = oge->logdetV_om->data[0];\r\n      \r\n      //Log determinant of quadX:\r\n      for(i=0; i < gff->X->cols; i++){\r\n        logdetquadX += log(oge->cholquadX_vectorD[i]);\r\n      }\r\n      logdetquadX *= 2;\r\n      gff->REMLcorrection = Scale*0.5*logdetquadX;\r\n      \r\n      //Finish computing fit (negative loglikelihood):\r\n      P.triangularView<Eigen::Lower>() = (Vinv.selfadjointView<Eigen::Lower>() * //P = Vinv * (I-Hatmat)\r\n        (Eigen::MatrixXd::Identity(Vinv.rows(), Vinv.cols()) - \r\n          (EigX * oge->quadXinv.selfadjointView<Eigen::Lower>() * oge->XtVinv))).triangularView<Eigen::Lower>();\r\n      Py = P.selfadjointView<Eigen::Lower>() * Eigy;\r\n      ytPy = (Eigy.transpose() * Py)(0,0);\r\n      if(OMX_DEBUG) {mxLog(\"ytPy is %3.3f\",ytPy);}\r\n      oo->matrix->data[0] = gff->REMLcorrection + Scale*0.5*( (((double)gff->y->cols) * NATLOG_2PI) + logdetV + ytPy);\r\n      gff->nll = oo->matrix->data[0]; \r\n    }\r\n    else{ //If not using GREML expectation, deal with means and cov in a general way to compute fit...\r\n      //Declare locals:\r\n      EigenMatrixAdaptor yhat(gff->means);\r\n      EigenMatrixAdaptor EigV(gff->cov);\r\n      double logdetV=0, logdetquadX=0;\r\n      Eigen::MatrixXd Vinv, quadX;\r\n      Eigen::LLT< Eigen::MatrixXd > cholV(gff->cov->rows);\r\n      Eigen::LLT< Eigen::MatrixXd > cholquadX(gff->X->cols);\r\n      Eigen::VectorXd cholV_vectorD, cholquadX_vectorD;\r\n      \r\n      //Cholesky factorization of V:\r\n      cholV.compute(EigV);\r\n      if(cholV.info() != Eigen::Success){\r\n        omxRaiseErrorf(\"expected covariance matrix is non-positive-definite\");\r\n        oo->matrix->data[0] = NA_REAL;\r\n        return;\r\n      }\r\n      //Log determinant of V:\r\n      cholV_vectorD = (( Eigen::MatrixXd )(cholV.matrixL())).diagonal();\r\n      for(i=0; i < gff->X->rows; i++){\r\n        logdetV += log(cholV_vectorD[i]);\r\n      }\r\n      logdetV *= 2;\r\n      \r\n      Vinv = cholV.solve(Eigen::MatrixXd::Identity( EigV.rows(), EigV.cols() )); //<-- V inverse\r\n      \r\n      quadX = EigX.transpose() * Vinv * EigX; //<--Quadratic form in X\r\n      \r\n      cholquadX.compute(quadX); //<--Cholesky factorization of quadX\r\n      if(cholquadX.info() != Eigen::Success){\r\n        omxRaiseErrorf(\"Cholesky factorization failed; possibly, the matrix of covariates is rank-deficient\");\r\n        oo->matrix->data[0] = NA_REAL;\r\n        return;\r\n      }\r\n      cholquadX_vectorD = (( Eigen::MatrixXd )(cholquadX.matrixL())).diagonal();\r\n      for(i=0; i < gff->X->cols; i++){\r\n        logdetquadX += log(cholquadX_vectorD[i]);\r\n      }\r\n      logdetquadX *= 2;\r\n      gff->REMLcorrection = Scale*0.5*logdetquadX;\r\n      \r\n      //Finish computing fit:\r\n      oo->matrix->data[0] = gff->REMLcorrection + Scale*0.5*( ((double)gff->y->rows * NATLOG_2PI) + logdetV + \r\n        ( Eigy.transpose() * Vinv * (Eigy - yhat) )(0,0));\r\n      gff->nll = oo->matrix->data[0]; \r\n      return;\r\n    }\r\n  }\r\n  \r\n  if(want & (FF_COMPUTE_GRADIENT | FF_COMPUTE_HESSIAN | FF_COMPUTE_IHESSIAN)){\r\n    //This part requires GREML expectation:\r\n    omxGREMLExpectation* oge = (omxGREMLExpectation*)(expectation->argStruct);\r\n    \r\n    //Declare local variables for this scope:\r\n    int nThreadz = Global->numThreads;\r\n    \r\n    fc->grad.resize(gff->dVlength); //<--Resize gradient in FitContext\r\n    \r\n    //Set up new HessianBlock:\r\n    HessianBlock *hb = new HessianBlock;\r\n    if(want & (FF_COMPUTE_HESSIAN | FF_COMPUTE_IHESSIAN)){\r\n      hb->vars.resize(gff->dVlength);\r\n      hb->mat.resize(gff->dVlength, gff->dVlength);\r\n    }\r\n    \r\n    //Begin looping thru free parameters:\r\n#pragma omp parallel num_threads(nThreadz)\r\n{\r\n\t\tint i=0, j=0, t1=0, t2=0;\r\n\t\tEigen::MatrixXd PdV_dtheta1;\r\n\t\tEigen::MatrixXd dV_dtheta1(Eigy.rows(), Eigy.rows()); //<--Derivative of V w/r/t parameter i.\r\n\t\tEigen::MatrixXd dV_dtheta2(Eigy.rows(), Eigy.rows()); //<--Derivative of V w/r/t parameter j.\r\n\t\tint threadID = omx_absolute_thread_num();\r\n\t\tint istart = threadID * gff->dVlength / nThreadz;\r\n\t\tint iend = (threadID+1) * gff->dVlength / nThreadz;\r\n\t\tif(threadID == nThreadz-1){iend = gff->dVlength;}\r\n\t\tfor(i=istart; i < iend; i++){\r\n\t\t\tt1 = gff->gradMap[i]; //<--Parameter number for parameter i.\r\n\t\t\tif(t1 < 0){continue;}\r\n\t\t\tif(want & (FF_COMPUTE_HESSIAN | FF_COMPUTE_IHESSIAN)){hb->vars[i] = t1;}\r\n\t\t\tif( oge->numcases2drop ){\r\n\t\t\t\tdropCasesAndEigenize(gff->dV[i], dV_dtheta1, oge->numcases2drop, oge->dropcase, 1);\r\n\t\t\t}\r\n\t\t\telse{dV_dtheta1 = Eigen::Map< Eigen::MatrixXd >(omxMatrixDataColumnMajor(gff->dV[i]), gff->dV[i]->rows, gff->dV[i]->cols);}\r\n\t\t\t//PdV_dtheta1 = P.selfadjointView<Eigen::Lower>() * dV_dtheta1.selfadjointView<Eigen::Lower>();\r\n\t\t\tPdV_dtheta1 = P.selfadjointView<Eigen::Lower>();\r\n\t\t\tPdV_dtheta1 = PdV_dtheta1 * dV_dtheta1.selfadjointView<Eigen::Lower>();\r\n\t\t\tfor(j=i; j < gff->dVlength; j++){\r\n\t\t\t\tif(j==i){\r\n\t\t\t\t\tgff->gradient(t1) = Scale*0.5*(PdV_dtheta1.trace() - (Eigy.transpose() * PdV_dtheta1 * Py)(0,0));\r\n\t\t\t\t\tfc->grad(t1) += gff->gradient(t1);\r\n\t\t\t\t\tif(want & (FF_COMPUTE_HESSIAN | FF_COMPUTE_IHESSIAN)){\r\n\t\t\t\t\t\tgff->avgInfo(t1,t1) = Scale*0.5*(Eigy.transpose() * PdV_dtheta1 * PdV_dtheta1 * Py)(0,0);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\telse{if(want & (FF_COMPUTE_HESSIAN | FF_COMPUTE_IHESSIAN)){\r\n\t\t\t\t\tt2 = gff->gradMap[j]; //<--Parameter number for parameter j.\r\n\t\t\t\t\tif(t2 < 0){continue;}\r\n\t\t\t\t\tif( oge->numcases2drop ){\r\n\t\t\t\t\t\tdropCasesAndEigenize(gff->dV[j], dV_dtheta2, oge->numcases2drop, oge->dropcase, 1);\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse{dV_dtheta2 = Eigen::Map< Eigen::MatrixXd >(omxMatrixDataColumnMajor(gff->dV[j]), gff->dV[j]->rows, gff->dV[j]->cols);}\r\n\t\t\t\t\tgff->avgInfo(t1,t2) = Scale*0.5*(Eigy.transpose() * PdV_dtheta1 * P.selfadjointView<Eigen::Lower>() * dV_dtheta2.selfadjointView<Eigen::Lower>() * Py)(0,0);\r\n\t\t\t\t\tgff->avgInfo(t2,t1) = gff->avgInfo(t1,t2);\r\n\t\t\t\t}}}}\r\n}\r\n    //Assign upper triangle elements of avgInfo to the HessianBlock:\r\n    if(want & (FF_COMPUTE_HESSIAN | FF_COMPUTE_IHESSIAN)){\r\n      for (size_t d1=0, h1=0; h1 < gff->dV.size(); ++h1) {\r\n\t\t    for (size_t d2=0, h2=0; h2 <= h1; ++h2) {\r\n\t\t\t\t  \thb->mat(d2,d1) = gff->avgInfo(h2,h1);\r\n\t\t\t\t    ++d2;\r\n        }\r\n\t\t\t  ++d1;\t\r\n\t\t  }\r\n\t\t  fc->queue(hb);\r\n  }}\r\n  return;\r\n}\r\n\r\n\r\n\r\nvoid omxDestroyGREMLFitFunction(omxFitFunction *oo){\r\n  if(OMX_DEBUG) {mxLog(\"Freeing GREML FitFunction.\");}\r\n    if(oo->argStruct == NULL) return;\r\n    omxGREMLFitState* owo = ((omxGREMLFitState*)oo->argStruct);\r\n    delete owo;\r\n}\r\n\r\n\r\nstatic void omxPopulateGREMLAttributes(omxFitFunction *oo, SEXP algebra){\r\n  if(OMX_DEBUG) { mxLog(\"Populating GREML Attributes.\"); }\r\n  SEXP rObj = oo->rObj;\r\n  SEXP nval, mlfitval;\r\n  int userSuppliedDataNumObs = (int)(( (omxGREMLExpectation*)(oo->expectation->argStruct) )->data2->numObs);\r\n  \r\n  //Tell the frontend fitfunction counterpart how many observations there are...:\r\n  {\r\n  ScopedProtect p1(nval, R_do_slot(rObj, Rf_install(\"numObs\")));\r\n  int* numobs = INTEGER(nval);\r\n  numobs[0] = 1L - userSuppliedDataNumObs;\r\n  /*^^^^The end result is that number of observations will be reported as 1 in summary()...\r\n  which is always correct with GREML*/\r\n\t}\r\n\t\r\n\tomxGREMLFitState *gff = (omxGREMLFitState*)oo->argStruct;\r\n\t{\r\n\tScopedProtect p1(mlfitval, R_do_slot(rObj, Rf_install(\"MLfit\")));\r\n\tdouble* mlfit = REAL(mlfitval);\r\n\tmlfit[0] = gff->nll - gff->REMLcorrection;\r\n\t}\r\n}\r\n\r\n\r\nvoid omxGREMLFitState::buildParamMap(FreeVarGroup *newVarGroup)\r\n{\r\n  if(OMX_DEBUG) { mxLog(\"Building parameter map for GREML fitfunction.\"); }\r\n  varGroup = newVarGroup;\r\n  std::vector< omxMatrix* > dV_temp = dV;\r\n  std::vector< const char* > dVnames_temp = dVnames;\r\n\tgradMap.resize(dVlength);\r\n\tint gx=0;\r\n\tfor (int vx=0; vx < int(varGroup->vars.size()); ++vx) {\r\n\t\tfor (int nx=0; nx < dVlength; ++nx) {\r\n\t\t\tif (strEQ(dVnames_temp[nx], varGroup->vars[vx]->name)) {\r\n\t\t\t\tgradMap[gx] = vx;\r\n\t\t\t\tdV[gx] = dV_temp[nx];\r\n\t\t\t\tdVnames[gx] = dVnames_temp[nx]; //<--Probably not strictly necessary...\r\n\t\t\t\t++gx;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tif (gx != dVlength) Rf_error(\"Problem in dVnames mapping\");\r\n}\r\n\r\n\r\n\r\nomxMatrix* omxMatrixLookupFromState1(int matrix, omxState* os) {\r\n  omxMatrix* output = NULL;\r\n\tif(matrix == NA_INTEGER){return NULL;}\r\n\tif (matrix >= 0) {\r\n\t\toutput = os->algebraList[matrix];\r\n\t} \r\n  else {\r\n\t\toutput = os->matrixList[~matrix];\r\n\t}\r\n\treturn output;\r\n}\r\n\r\n", "meta": {"hexsha": "dafe1515fccac08a77042e9674b67e5912e0dbb3", "size": 14452, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/omxGREMLfitfunction.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/omxGREMLfitfunction.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/omxGREMLfitfunction.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": 40.0332409972, "max_line_length": 162, "alphanum_fraction": 0.6490451149, "num_tokens": 4508, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.6224593171945416, "lm_q1q2_score": 0.48717555224283277}}
{"text": "// Copyright Abel Sinkovics (abel@sinkovics.hu)  2012.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n#include <boost/metaparse/repeated.hpp>\n#include <boost/metaparse/sequence.hpp>\n#include <boost/metaparse/lit_c.hpp>\n#include <boost/metaparse/last_of.hpp>\n#include <boost/metaparse/space.hpp>\n#include <boost/metaparse/int_.hpp>\n#include <boost/metaparse/foldl_reject_incomplete_start_with_parser.hpp>\n#include <boost/metaparse/one_of.hpp>\n#include <boost/metaparse/get_result.hpp>\n#include <boost/metaparse/token.hpp>\n#include <boost/metaparse/entire_input.hpp>\n#include <boost/metaparse/string.hpp>\n#include <boost/metaparse/transform.hpp>\n#include <boost/metaparse/always.hpp>\n#include <boost/metaparse/build_parser.hpp>\n\n#include <boost/mpl/apply_wrap.hpp>\n#include <boost/mpl/front.hpp>\n#include <boost/mpl/back.hpp>\n#include <boost/mpl/plus.hpp>\n#include <boost/mpl/minus.hpp>\n#include <boost/mpl/times.hpp>\n#include <boost/mpl/divides.hpp>\n#include <boost/mpl/bool.hpp>\n#include <boost/mpl/equal_to.hpp>\n#include <boost/mpl/if.hpp>\n\nusing boost::metaparse::sequence;\nusing boost::metaparse::lit_c;\nusing boost::metaparse::last_of;\nusing boost::metaparse::space;\nusing boost::metaparse::repeated;\nusing boost::metaparse::build_parser;\nusing boost::metaparse::int_;\nusing boost::metaparse::foldl_reject_incomplete_start_with_parser;\nusing boost::metaparse::get_result;\nusing boost::metaparse::one_of;\nusing boost::metaparse::token;\nusing boost::metaparse::entire_input;\nusing boost::metaparse::transform;\nusing boost::metaparse::always;\n\nusing boost::mpl::apply_wrap1;\nusing boost::mpl::front;\nusing boost::mpl::back;\nusing boost::mpl::plus;\nusing boost::mpl::minus;\nusing boost::mpl::times;\nusing boost::mpl::divides;\nusing boost::mpl::if_;\nusing boost::mpl::bool_;\nusing boost::mpl::equal_to;\n\n/*\n * The grammar\n *\n * expression ::= plus_exp\n * plus_exp ::= prod_exp ((plus_token | minus_token) prod_exp)*\n * prod_exp ::= value_exp ((mult_token | div_token) value_exp)*\n * value_exp ::= int_token | '_'\n */\n\ntypedef token<lit_c<'+'> > plus_token;\ntypedef token<lit_c<'-'> > minus_token;\ntypedef token<lit_c<'*'> > mult_token;\ntypedef token<lit_c<'/'> > div_token;\n\ntypedef token<int_> int_token;\ntypedef token<lit_c<'_'> > arg_token;\n\ntemplate <class T, char C>\nstruct is_c : bool_<T::type::value == C> {};\n\nstruct build_plus\n{\n  template <class A, class B>\n  struct _plus\n  {\n    typedef _plus type;\n\n    template <class T>\n    struct apply :\n      plus<typename apply_wrap1<A, T>::type, typename apply_wrap1<B, T>::type>\n    {};\n  };\n\n  template <class A, class B>\n  struct _minus\n  {\n    typedef _minus type;\n\n    template <class T>\n    struct apply :\n      minus<typename apply_wrap1<A, T>::type, typename apply_wrap1<B, T>::type>\n    {};\n  };\n\n  template <class State, class C>\n  struct apply :\n    if_<\n      typename is_c<front<C>, '+'>::type,\n      _plus<State, typename back<C>::type>,\n      _minus<State, typename back<C>::type>\n    >\n  {};\n};\n\nstruct build_mult\n{\n  template <class A, class B>\n  struct _mult\n  {\n    typedef _mult type;\n\n    template <class T>\n    struct apply :\n      times<typename apply_wrap1<A, T>::type, typename apply_wrap1<B, T>::type>\n    {};\n  };\n\n  template <class A, class B>\n  struct _div\n  {\n    typedef _div type;\n\n    template <class T>\n    struct apply :\n      divides<\n        typename apply_wrap1<A, T>::type,\n        typename apply_wrap1<B, T>::type\n      >\n    {};\n  };\n\n  template <class State, class C>\n  struct apply :\n    if_<\n      typename is_c<front<C>, '*'>::type,\n      _mult<State, typename back<C>::type>,\n      _div<State, typename back<C>::type>\n    >\n  {};\n};\n\nclass build_value\n{\nprivate:\n  template <class V>\n  struct impl\n  {\n    typedef impl type;\n\n    template <class T>\n    struct apply : V {};\n  };\n\npublic:\n  typedef build_value type;\n\n  template <class V>\n  struct apply : impl<typename V::type> {};\n};\n\nstruct arg\n{\n  typedef arg type;\n\n  template <class T>\n  struct apply\n  {\n    typedef T type;\n  };\n};\n\ntypedef\n  one_of<transform<int_token, build_value>, always<arg_token, arg> >\n  value_exp;\n\ntypedef\n  foldl_reject_incomplete_start_with_parser<\n    sequence<one_of<mult_token, div_token>, value_exp>,\n    value_exp,\n    build_mult\n  >\n  prod_exp;\n\ntypedef\n  foldl_reject_incomplete_start_with_parser<\n    sequence<one_of<plus_token, minus_token>, prod_exp>,\n    prod_exp,\n    build_plus\n  >\n  plus_exp;\n\ntypedef last_of<repeated<space>, plus_exp> expression;\n\ntypedef build_parser<entire_input<expression> > metafunction_parser;\n\n#if BOOST_METAPARSE_STD < 2011\n\ntemplate <class Exp>\nstruct meta_lambda : apply_wrap1<metafunction_parser, Exp> {};\n\nint main()\n{\n  using std::cout;\n  using std::endl;\n  using boost::metaparse::string;\n\n  typedef meta_lambda<string<'1','3'> >::type metafunction_class_1;\n  typedef meta_lambda<string<'2',' ','+',' ','3'> >::type metafunction_class_2;\n  typedef meta_lambda<string<'2',' ','*',' ','2'> >::type metafunction_class_3;\n  typedef\n    meta_lambda<string<' ','1','+',' ','2','*','4','-','6','/','2'> >::type\n    metafunction_class_4;\n  typedef meta_lambda<string<'2',' ','*',' ','_'> >::type metafunction_class_5;\n\n  typedef boost::mpl::int_<11> int11;\n\n  cout\n    << apply_wrap1<metafunction_class_1, int11>::type::value << endl\n    << apply_wrap1<metafunction_class_2, int11>::type::value << endl\n    << apply_wrap1<metafunction_class_3, int11>::type::value << endl\n    << apply_wrap1<metafunction_class_4, int11>::type::value << endl\n    << apply_wrap1<metafunction_class_5, int11>::type::value << endl\n    ;\n}\n\n#else\n\n#ifdef META_LAMBDA\n  #error META_LAMBDA already defined\n#endif\n#define META_LAMBDA(exp) \\\n  apply_wrap1<metafunction_parser, BOOST_METAPARSE_STRING(#exp)>::type\n\nint main()\n{\n  using std::cout;\n  using std::endl;\n\n  typedef META_LAMBDA(13) metafunction_class_1;\n  typedef META_LAMBDA(2 + 3) metafunction_class_2;\n  typedef META_LAMBDA(2 * 2) metafunction_class_3;\n  typedef META_LAMBDA( 1+ 2*4-6/2) metafunction_class_4;\n  typedef META_LAMBDA(2 * _) metafunction_class_5;\n\n  typedef boost::mpl::int_<11> int11;\n\n  cout\n    << apply_wrap1<metafunction_class_1, int11>::type::value << endl\n    << apply_wrap1<metafunction_class_2, int11>::type::value << endl\n    << apply_wrap1<metafunction_class_3, int11>::type::value << endl\n    << apply_wrap1<metafunction_class_4, int11>::type::value << endl\n    << apply_wrap1<metafunction_class_5, int11>::type::value << endl\n    ;\n}\n\n#endif\n", "meta": {"hexsha": "6097d7bd06355408a66f675e390e002bc356de1a", "size": 6549, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/libs/metaparse/example/meta_lambda/main.cpp", "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/libs/metaparse/example/meta_lambda/main.cpp", "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/libs/metaparse/example/meta_lambda/main.cpp", "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": 24.7132075472, "max_line_length": 79, "alphanum_fraction": 0.694457169, "num_tokens": 1839, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125848754472, "lm_q2_score": 0.6477982315512488, "lm_q1q2_score": 0.48715242258659813}}
{"text": "//  (C) Copyright Matt Borland 2022.\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#include <boost/math/tools/color_maps.hpp>\n#include \"test_compile_result.hpp\"\n\nvoid compile_and_link_test()\n{\n    check_result<float>(boost::math::tools::black_body<float>(0.5f)[0]);\n    check_result<float>(boost::math::tools::extended_kindlmann<float>(0.5f)[0]);\n    check_result<double>(boost::math::tools::inferno<double>(0.5)[0]);\n    check_result<double>(boost::math::tools::kindlmann<double>(0.5)[0]);\n    check_result<float>(boost::math::tools::plasma<float>(0.5f)[0]);\n    check_result<float>(boost::math::tools::smooth_cool_warm<float>(0.5f)[0]);\n    check_result<float>(boost::math::tools::viridis<float>(0.5f)[0]);\n}\n", "meta": {"hexsha": "c2cc9585de6f3b8dd2e078e3f2d6726599800db2", "size": 857, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/compile_test/tools_color_maps_incl_test.cpp", "max_stars_repo_name": "grlee77/math", "max_stars_repo_head_hexsha": "e8c40e309cc32d43fbe42c49d9ec7da7cdb79418", "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": "test/compile_test/tools_color_maps_incl_test.cpp", "max_issues_repo_name": "grlee77/math", "max_issues_repo_head_hexsha": "e8c40e309cc32d43fbe42c49d9ec7da7cdb79418", "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/compile_test/tools_color_maps_incl_test.cpp", "max_forks_repo_name": "grlee77/math", "max_forks_repo_head_hexsha": "e8c40e309cc32d43fbe42c49d9ec7da7cdb79418", "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.1052631579, "max_line_length": 80, "alphanum_fraction": 0.7141190198, "num_tokens": 247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125848754471, "lm_q2_score": 0.6477982315512488, "lm_q1q2_score": 0.487152422586598}}
{"text": "#include <pybind11/pybind11.h>\n#include <pybind11/eigen.h>\n#include <pybind11/numpy.h>\n#include <fstream>\n#include <iostream>\n#include <cfloat>\n#include <vector>\n#include <Eigen/Dense>\nusing namespace std;\nusing namespace Eigen;\n\n\nArrayXd find_max(VectorXd mMat)\n{\n\tVectorXd::Index maxRow;\n\tdouble max = mMat.maxCoeff(&maxRow);\n\tMatrix<bool, Dynamic, 1> MM = (mMat.array() == max).matrix();\n\tArrayXd Index_max = ArrayXd::Zero(mMat.size());\n\tfor (size_t i = 0; i < MM.rows(); i++)\n\t{\n\t\tif (MM(i))\n\t\t{\n\t\t\tIndex_max[i] = 1.0;\n\t\t}\n\n\t}\n\treturn Index_max;\n}\n\nMatrixXd select_M_PN(MatrixXd C, VectorXd P)\n{\n\tMatrixXd res(int(P.sum()), int(P.sum())), res_ing(C.rows(), int(P.sum()));\n\tEigen::Index j = 0;\n\tfor (Eigen::Index i = 0; i < C.cols(); ++i)\n\t{\n\t\tif (P(i) > 0) res_ing.col(j++) = C.col(i);\n\t}\n\tj = 0;\n\tfor (Eigen::Index i = 0; i < C.cols(); ++i)\n\t{\n\t\tif (P(i) > 0)\n\t\t\tres.row(j++) = res_ing.row(i);\n\t}\n\n\treturn res;\n\n}\n\nMatrixXd select_V_PN(VectorXd V, VectorXd P)\n{\n\tVectorXd res(int(P.sum()));\n\tEigen::Index j = 0;\n\tfor (Eigen::Index i = 0; i < V.size(); ++i)\n\t{\n\t\tif (P(i) > 0) res(j++) = V(i);\n\t}\n\treturn res;\n\n}\n\nVectorXd lsqnonneg(MatrixXd C, VectorXd d, double tol)\n/*\nmin_{x>0}||Cx-d||_2^2\nReference: Lawson and Hanson,\n\"Solving Least Squares Problems\",\nPrentice-Hall, 1974.\n*/\n{\n\tint n = C.rows();\n\t// Initialize vector of n zeros and Infs(to be used later)\n\tVectorXd nZeros = VectorXd::Zero(n);\n\tVectorXd wz = nZeros;\n\t//Initialize set of non - active columns to null\n\tVectorXd P = nZeros;\n\t// Initialize set of active columns to all\n\t// and the initial point to zeros\n\tVectorXd Z = VectorXd::Ones(n);\n\tVectorXd x = nZeros;\n\tVectorXd w = d - C * x;\n\t//Set up iteration criterion\n\tint outeriter = 0;\n\tint iter = 0;\n\tint itmax = 3 * n;\n\t// Outer loop to put variables into set to hold positive coefficients\n\twhile (Z.sum() > 0 && (w.array() > tol).any())\n\t{\n\t\touteriter += 1;\n\t\tVectorXd z = nZeros;\n\t\twz = (wz.array()*(1-P.array())).matrix() - P* DBL_MAX;\n\t\twz = (wz.array() *(1-Z.array()) + w.array()*Z.array()).matrix();\n\t\tArrayXd t = find_max(wz);\n\t\tP = (P.array() * (1 - t) + t).matrix();\n\t\tZ = (Z.array()*(1 - t)).matrix();\n\t\tif (P.sum() == 1)\n\t\t{\n\t\t\tVectorXd::Index maxRow;\n\t\t\tP.maxCoeff(&maxRow);\n\t\t\tz(maxRow) = d(maxRow) / C(maxRow, maxRow);\n\t\t}\n\t\tif (P.sum() >= 2)\n\t\t{\n\t\t\tMatrixXd C_ing = select_M_PN(C, P);\n\t\t\tVectorXd d_ing = select_V_PN(d, P);\n\t\t\tVectorXd z_ing = C_ing.ldlt().solve(d_ing);\n\t\t\tEigen::Index j = 0;\n\t\t\tfor (size_t i = 0; i < P.size(); i++)\n\t\t\t{\n\t\t\t\tif (P(i) > 0) z(i) = z_ing(j++);\n\t\t\t}\n\t\t}\n\t\twhile ((z.array()*P.array() + 1 - P.array() <= 0).any())\n\t\t{\n\t\t\titer = iter + 1;\n\t\t\tif (iter > itmax)\n\t\t\t{\n\t\t\t\tcout << \"optimfun:lsqnonneg: IterationCountExceeded\" << endl;\n\t\t\t\tx = z;\n\t\t\t\treturn x;\n\t\t\t}\n\n\t\t\t// Find indices where intermediate solution z is approximately negative\n\t\t\tvector<double> alpha_v;\n\t\t\tfor (Eigen::Index i = 0; i < P.size(); i++)\n\t\t\t{\n\t\t\t\tif(z(i)<=0 && P(i)>0) alpha_v.push_back(x(i)/(x(i)-z(i)));\n\t\t\t}\n\t\t\tx = x + (*min_element(alpha_v.begin(), alpha_v.end())) * (z - x);\n\t\t\tfor (size_t i = 0; i < Z.size(); i++)\n\t\t\t{\n\t\t\t\tif (abs(x(i)) < tol && P(i)>0)\n\t\t\t\t{\n\t\t\t\t\tZ(i) = 1;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tP = (1 - Z.array()).matrix();\n\t\t\tz = nZeros;\n\t\t\tif (P.sum() == 1)\n\t\t\t{\n\t\t\t\tVectorXd::Index maxRow;\n\t\t\t\tP.maxCoeff(&maxRow);\n\t\t\t\tz(maxRow) = d(maxRow) / C(maxRow, maxRow);\n\t\t\t}\n\t\t\tif (P.sum() >= 2)\n\t\t\t{\n\t\t\t\tMatrixXd C_ing = select_M_PN(C, P);\n\t\t\t\tVectorXd d_ing = select_V_PN(d, P);\n\t\t\t\tVectorXd z_ing = C_ing.ldlt().solve(d_ing);\n\t\t\t\tEigen::Index j = 0;\n\t\t\t\tfor (size_t i = 0; i < P.size(); i++)\n\t\t\t\t{\n\t\t\t\t\tif (P(i) > 0) z(i) = z_ing(j++);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tx = z;\n\t\tw = d - C*x;\n\t}\n\treturn x;\n}\n\nMatrixXd SNMF_inner(MatrixXd C_mat, MatrixXd B_mat, double tol)\n{\n\tint n = B_mat.cols();\n\tfor (Eigen::Index i = 0; i < n; i++)\n\t{\n\t\tB_mat.col(i) = lsqnonneg(C_mat, B_mat.col(i), tol);\n\t}\n\treturn B_mat;\n}\n\nnamespace py = pybind11;\nPYBIND11_MODULE(libSNMF_inner,m)\n{\nm.doc() = \"SNMF_inner iteration\";\nm.def(\"SNMF_inner\", &SNMF_inner);\n}", "meta": {"hexsha": "015780fb5a7d89e95d47a2cad2743f6fe9bcd48a", "size": 3970, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "scSO_py/Windows/SNMF_inner.cpp", "max_stars_repo_name": "QuKunLab/SMAFS", "max_stars_repo_head_hexsha": "b635fc13c8d3bd6344f7d8bdfe9c96c27f20461e", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-04-10T03:10:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-17T06:37:26.000Z", "max_issues_repo_path": "scSO_py/Windows/SNMF_inner.cpp", "max_issues_repo_name": "QuKunLab/SMAFS", "max_issues_repo_head_hexsha": "b635fc13c8d3bd6344f7d8bdfe9c96c27f20461e", "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": "scSO_py/Windows/SNMF_inner.cpp", "max_forks_repo_name": "QuKunLab/SMAFS", "max_forks_repo_head_hexsha": "b635fc13c8d3bd6344f7d8bdfe9c96c27f20461e", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-17T06:37:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-17T06:37:27.000Z", "avg_line_length": 22.4293785311, "max_line_length": 75, "alphanum_fraction": 0.5765743073, "num_tokens": 1405, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.48715240515917657}}
{"text": "#define CATCH_CONFIG_MAIN\n\n#include \"CALPHADFreeEnergyFunctionsBinary.h\"\n#include \"InterpolationType.h\"\n\n#include \"catch.hpp\"\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 <fstream>\n#include <iostream>\n#include <string>\n\nnamespace pt = boost::property_tree;\n\nTEST_CASE(\"CALPHAD binary KKS\", \"[binary kks]\")\n{\n    Thermo4PFM::EnergyInterpolationType energy_interp_func_type\n        = Thermo4PFM::EnergyInterpolationType::PBG;\n    Thermo4PFM::ConcInterpolationType conc_interp_func_type\n        = Thermo4PFM::ConcInterpolationType::PBG;\n\n    double temperature = 1450.;\n\n    std::cout << \" Read CALPHAD database...\" << std::endl;\n    pt::ptree calphad_db;\n    try\n    {\n        pt::read_json(\"../thermodynamic_data/calphadAuNi.json\", calphad_db);\n    }\n    catch (std::exception& e)\n    {\n        std::cerr << \"exception caught: \" << e.what() << std::endl;\n    }\n\n    boost::optional<pt::ptree&> newton_db;\n\n    Thermo4PFM::CALPHADFreeEnergyFunctionsBinary cafe(\n        calphad_db, newton_db, energy_interp_func_type, conc_interp_func_type);\n\n    // initial guesses\n    double c_init0 = 0.5;\n    double c_init1 = 0.5;\n\n    double sol[2] = { c_init0, c_init1 };\n\n    // compute concentrations satisfying KKS equations\n    double conc = 0.3;\n    double phi  = 0.5;\n    cafe.computePhaseConcentrations(temperature, &conc, &phi, &sol[0]);\n\n    std::cout << \"-------------------------------\" << std::endl;\n    std::cout << \"Temperature = \" << temperature << std::endl;\n    std::cout << \"Result for c = \" << conc << \" and phi = \" << phi << std::endl;\n    std::cout << \"   cL = \" << sol[0] << std::endl;\n    std::cout << \"   cS = \" << sol[1] << std::endl;\n\n    const Thermo4PFM::PhaseIndex pi0 = Thermo4PFM::PhaseIndex::phaseL;\n    const Thermo4PFM::PhaseIndex pi1 = Thermo4PFM::PhaseIndex::phaseA;\n\n    std::cout << \"Verification:\" << std::endl;\n\n    double derivL;\n    cafe.computeDerivFreeEnergy(temperature, &sol[0], pi0, &derivL);\n    std::cout << \"   dfL/dcL = \" << derivL << std::endl;\n\n    double derivS;\n    cafe.computeDerivFreeEnergy(temperature, &sol[1], pi1, &derivS);\n    std::cout << \"   dfS/dcS = \" << derivS << std::endl;\n\n    REQUIRE(derivS == Approx(derivL).margin(1.e-5));\n}\n", "meta": {"hexsha": "f511636cdefb6bb28795bda3a945f42e62c8904d", "size": 2279, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tests/testCALPHADbinaryKKS.cc", "max_stars_repo_name": "stvdwtt/Thermo4PFM", "max_stars_repo_head_hexsha": "5308b7c58c4b67ed98d2bd50469226b7d89da2b8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2022-01-21T17:39:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T21:00:24.000Z", "max_issues_repo_path": "tests/testCALPHADbinaryKKS.cc", "max_issues_repo_name": "stvdwtt/Thermo4PFM", "max_issues_repo_head_hexsha": "5308b7c58c4b67ed98d2bd50469226b7d89da2b8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-01-21T16:51:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-21T16:51:52.000Z", "max_forks_repo_path": "tests/testCALPHADbinaryKKS.cc", "max_forks_repo_name": "stvdwtt/Thermo4PFM", "max_forks_repo_head_hexsha": "5308b7c58c4b67ed98d2bd50469226b7d89da2b8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-12-13T14:29:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-01T18:12:51.000Z", "avg_line_length": 30.3866666667, "max_line_length": 80, "alphanum_fraction": 0.6423870118, "num_tokens": 678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125626441471, "lm_q2_score": 0.6477982247516796, "lm_q1q2_score": 0.4871524030718397}}
{"text": "/* boost random/lognormal_distribution.hpp header file\r\n *\r\n * Copyright Jens Maurer 2000-2001\r\n * Permission to use, copy, modify, sell, and distribute this software\r\n * is hereby granted without fee provided that the above copyright notice\r\n * appears in all copies and that both that copyright notice and this\r\n * permission notice appear in supporting documentation,\r\n *\r\n * Jens Maurer makes no representations about the suitability of this\r\n * software for any purpose. It is provided \"as is\" without express or\r\n * implied warranty.\r\n *\r\n * See http://www.boost.org for most recent version including documentation.\r\n *\r\n * $Id: lognormal_distribution.hpp,v 1.13 2003/02/25 10:29:29 bjorn_karlsson Exp $\r\n *\r\n * Revision history\r\n *  2001-02-18  moved to individual header files\r\n */\r\n\r\n#ifndef BOOST_RANDOM_LOGNORMAL_DISTRIBUTION_HPP\r\n#define BOOST_RANDOM_LOGNORMAL_DISTRIBUTION_HPP\r\n\r\n#include <cmath>      // std::exp, std::sqrt\r\n#include <cassert>\r\n#include <boost/random/normal_distribution.hpp>\r\n\r\n#ifdef BOOST_NO_STDC_NAMESPACE\r\nnamespace std {\r\n  using ::log;\r\n  using ::sqrt;\r\n}\r\n#endif\r\n\r\nnamespace boost {\r\n\r\n#if defined(__GNUC__) && (__GNUC__ < 3)\r\n// Special gcc workaround: gcc 2.95.x ignores using-declarations\r\n// in template classes (confirmed by gcc author Martin v. Loewis)\r\n  using std::sqrt;\r\n  using std::exp;\r\n#endif\r\n\r\ntemplate<class UniformRandomNumberGenerator, class RealType = double,\r\n        class Adaptor = uniform_01<UniformRandomNumberGenerator, RealType> >\r\nclass lognormal_distribution\r\n{\r\npublic:\r\n  typedef Adaptor adaptor_type;\r\n  typedef UniformRandomNumberGenerator base_type;\r\n  typedef RealType result_type;\r\n\r\n  explicit lognormal_distribution(base_type & rng,\r\n                                  result_type mean = result_type(1),\r\n                                  result_type sigma = result_type(1))\r\n    : _mean(mean), _sigma(sigma),\r\n      _rng(rng, std::log(mean*mean/std::sqrt(sigma*sigma + mean*mean)),\r\n           std::sqrt(std::log(sigma*sigma/mean/mean+result_type(1))))\r\n  { \r\n    assert(mean > result_type(0));\r\n  }\r\n\r\n  // compiler-generated copy ctor and assignment operator are fine\r\n\r\n  adaptor_type& adaptor() { return _rng.adaptor(); }\r\n  base_type& base() const { return _rng.base(); }\r\n  RealType mean() const { return _mean; }\r\n  RealType sigma() const { return _sigma; }\r\n  void reset() { _rng.reset(); }\r\n\r\n  result_type operator()()\r\n  {\r\n#ifndef BOOST_NO_STDC_NAMESPACE\r\n    // allow for Koenig lookup\r\n    using std::exp;\r\n#endif\r\n    return exp(_rng());\r\n  }\r\n\r\n#ifndef BOOST_NO_OPERATORS_IN_NAMESPACE\r\n  friend bool operator==(const lognormal_distribution& x, \r\n                         const lognormal_distribution& y)\r\n  { return x._rng == y._rng; }\r\n\r\n#ifndef BOOST_NO_MEMBER_TEMPLATE_FRIENDS\r\n  template<class CharT, class Traits>\r\n  friend std::basic_ostream<CharT,Traits>&\r\n  operator<<(std::basic_ostream<CharT,Traits>& os, const lognormal_distribution& ld)\r\n  {\r\n    os << ld._rng << \" \" << ld._mean << \" \" << ld._sigma;\r\n    return os;\r\n  }\r\n\r\n  template<class CharT, class Traits>\r\n  friend std::basic_istream<CharT,Traits>&\r\n  operator>>(std::basic_istream<CharT,Traits>& is, lognormal_distribution& ld)\r\n  {\r\n    is >> std::ws >> ld._rng >> std::ws >> ld._mean >> std::ws >> ld._sigma;\r\n    return is;\r\n  }\r\n#endif\r\n\r\n#else\r\n  // Use a member function\r\n  bool operator==(const lognormal_distribution& rhs) const\r\n  { return _rng == rhs._rng;  }\r\n#endif\r\nprivate:\r\n  RealType _mean, _sigma;\r\n  normal_distribution<base_type, result_type, adaptor_type> _rng;\r\n};\r\n\r\n} // namespace boost\r\n\r\n#endif // BOOST_RANDOM_LOGNORMAL_DISTRIBUTION_HPP\r\n", "meta": {"hexsha": "04e2dd7f48f48d96243ab68f01b72142591d1c3f", "size": 3628, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sdk/boost_1_30_0/boost/random/lognormal_distribution.hpp", "max_stars_repo_name": "acidicMercury8/xray-1.0", "max_stars_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2021-05-04T06:40:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T20:24:28.000Z", "max_issues_repo_path": "sdk/boost_1_30_0/boost/random/lognormal_distribution.hpp", "max_issues_repo_name": "acidicMercury8/xray-1.0", "max_issues_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_issues_repo_licenses": ["Linux-OpenIB"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sdk/boost_1_30_0/boost/random/lognormal_distribution.hpp", "max_forks_repo_name": "acidicMercury8/xray-1.0", "max_forks_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-11-07T16:57:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-05T13:17:12.000Z", "avg_line_length": 31.275862069, "max_line_length": 85, "alphanum_fraction": 0.6846747519, "num_tokens": 870, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.752012562644147, "lm_q2_score": 0.6477982247516796, "lm_q1q2_score": 0.48715240307183966}}
{"text": "// Boost.Units - A C++ library for zero-overhead dimensional analysis and \n// unit/quantity manipulation and conversion\n//\n// Copyright (C) 2009 Steven Watanabe\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n/** \n\\file\n    \n\\brief test_trig.cpp\n\n\\details\nTest trigonometric functions.\n\nOutput:\n@verbatim\n@endverbatim\n**/\n\n#include <cmath>\n#include <boost/units/cmath.hpp>\n#include <boost/units/io.hpp>\n#include <boost/units/systems/si/plane_angle.hpp>\n#include <boost/units/systems/si/length.hpp>\n#include <boost/units/systems/si/dimensionless.hpp>\n#include <boost/units/systems/angle/degrees.hpp>\n\n#include \"test_close.hpp\"\n\nusing boost::units::si::radians;\nusing boost::units::si::si_dimensionless;\nusing boost::units::degree::degrees;\nBOOST_UNITS_STATIC_CONSTANT(degree_dimensionless, boost::units::degree::dimensionless);\nusing boost::units::si::meters;\nBOOST_UNITS_STATIC_CONSTANT(heterogeneous_dimensionless, boost::units::reduce_unit<boost::units::si::dimensionless>::type);\n\nvoid test_sin() {\n    BOOST_TEST_EQ(boost::units::sin(2.0 * radians), std::sin(2.0) * si_dimensionless);\n    BOOST_UNITS_TEST_CLOSE(static_cast<double>(boost::units::sin(15.0 * degrees)), 0.2588, 0.0004);\n}\n\nvoid test_cos() {\n    BOOST_TEST_EQ(boost::units::cos(2.0 * radians), std::cos(2.0) * si_dimensionless);\n    BOOST_UNITS_TEST_CLOSE(static_cast<double>(boost::units::cos(75.0 * degrees)), 0.2588, 0.0004);\n}\n\nvoid test_tan() {\n    BOOST_TEST_EQ(boost::units::tan(2.0 * radians), std::tan(2.0) * si_dimensionless);\n    BOOST_UNITS_TEST_CLOSE(static_cast<double>(boost::units::tan(45.0 * degrees)), 1.0, 0.0001);\n}\n\nvoid test_asin() {\n    BOOST_TEST_EQ(boost::units::asin(0.2 * si_dimensionless), std::asin(0.2) * radians);\n    BOOST_UNITS_TEST_CLOSE(boost::units::asin(0.5 * degree_dimensionless).value(), 30.0, 0.0001);\n    BOOST_TEST_EQ(boost::units::asin(0.2 * heterogeneous_dimensionless).value(), std::asin(0.2));\n}\n\nvoid test_acos() {\n    BOOST_TEST_EQ(boost::units::acos(0.2 * si_dimensionless), std::acos(0.2) * radians);\n    BOOST_UNITS_TEST_CLOSE(boost::units::acos(0.5 * degree_dimensionless).value(), 60.0, 0.0001);\n    BOOST_TEST_EQ(boost::units::acos(0.2 * heterogeneous_dimensionless).value(), std::acos(0.2));\n}\n\nvoid test_atan() {\n    BOOST_TEST_EQ(boost::units::atan(0.2 * si_dimensionless), std::atan(0.2) * radians);\n    BOOST_UNITS_TEST_CLOSE(boost::units::atan(1.0 * degree_dimensionless).value(), 45.0, 0.0001);\n    BOOST_TEST_EQ(boost::units::atan(0.2 * heterogeneous_dimensionless).value(), std::atan(0.2));\n}\n\nvoid test_atan2() {\n    BOOST_TEST_EQ(boost::units::atan2(0.2 * si_dimensionless, 0.3 * si_dimensionless), std::atan2(0.2, 0.3) * radians);\n    BOOST_TEST_EQ(boost::units::atan2(0.2 * meters, 0.3 * meters), std::atan2(0.2, 0.3) * radians);\n    BOOST_UNITS_TEST_CLOSE(boost::units::atan2(0.8660*degree_dimensionless,0.5*degree_dimensionless).value(), 60., 0.0002);\n    BOOST_TEST_EQ(boost::units::atan2(0.2 * heterogeneous_dimensionless, 0.3 * heterogeneous_dimensionless).value(), std::atan2(0.2, 0.3));\n}\n\nint main()\n{\n    test_sin();\n    test_cos();\n    test_tan();\n    test_asin();\n    test_acos();\n    test_atan();\n    test_atan2();\n    return boost::report_errors();\n}\n", "meta": {"hexsha": "83e3265374e26477e3403ef5c3f1960252a3767c", "size": 3312, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "console/src/boost_1_78_0/libs/units/test/test_trig.cpp", "max_stars_repo_name": "vany152/FilesHash", "max_stars_repo_head_hexsha": "39f282807b7f1abc56dac389e8259ee3bb557a8d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 106.0, "max_stars_repo_stars_event_min_datetime": "2015-08-07T04:23:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-27T18:25:15.000Z", "max_issues_repo_path": "console/src/boost_1_78_0/libs/units/test/test_trig.cpp", "max_issues_repo_name": "vany152/FilesHash", "max_issues_repo_head_hexsha": "39f282807b7f1abc56dac389e8259ee3bb557a8d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 130.0, "max_issues_repo_issues_event_min_datetime": "2016-06-22T22:11:25.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-29T20:24:09.000Z", "max_forks_repo_path": "console/src/boost_1_78_0/libs/units/test/test_trig.cpp", "max_forks_repo_name": "vany152/FilesHash", "max_forks_repo_head_hexsha": "39f282807b7f1abc56dac389e8259ee3bb557a8d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 56.0, "max_forks_repo_forks_event_min_datetime": "2015-01-07T20:26:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-18T18:58:16.000Z", "avg_line_length": 36.3956043956, "max_line_length": 139, "alphanum_fraction": 0.7134661836, "num_tokens": 994, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.647798211152541, "lm_q1q2_score": 0.48715240004581495}}
{"text": "#include \"davidson.h\"\n\n#include <Eigen/Dense>\n\nsize_t Davidson::diagonalize(\n    const std::vector<double>& initial_vector, std::size_t max_iterations) {\n  const double TOLERANCE = 1.0e-7;\n\n  if (n == 1) {\n    lowest_eigenvalue = diagonal[0];\n    lowest_eigenvector = std::vector<double>(1, 1.0);\n    diagonalized = true;\n    return 0;\n  }\n\n  const std::size_t iterations = std::min(n, max_iterations);\n  double lowest_eigenvalue = 0.0;\n  double lowest_eigenvalue_prev = 0.0;\n  double residual_norm = 0.0;\n\n  Eigen::MatrixXd v = Eigen::MatrixXd::Zero(n, iterations);\n\n  if (initial_vector.size() != n) {\n    v(0, 0) = 1.0;  // Start from HF.\n  } else {\n    for (std::size_t i = 0; i < n; i++) v(i, 0) = initial_vector[i];\n    v.col(0).normalize();\n  }\n\n  Eigen::MatrixXd Hv = Eigen::MatrixXd::Zero(n, iterations);\n  Eigen::VectorXd w = Eigen::VectorXd::Zero(n);  // Lowest eigenvector so far.\n  Eigen::VectorXd Hw = Eigen::VectorXd::Zero(n);\n  Eigen::MatrixXd h_krylov = Eigen::MatrixXd::Zero(iterations, iterations);\n  Eigen::MatrixXd h_overwrite;\n  Eigen::VectorXd eigenvalues = Eigen::VectorXd::Zero(iterations);\n  std::size_t len_work = 3 * iterations - 1;\n  Eigen::VectorXd work(len_work);\n  bool converged = false;\n  std::vector<double> tmp_v(n);\n\n  // Get diagonal elements.\n  Eigen::VectorXd diag_elems(n);\n  for (std::size_t i = 0; i < n; i++) diag_elems[i] = diagonal[i];\n\n  // First iteration.\n  for (std::size_t i = 0; i < n; i++) tmp_v[i] = v(i, 0);\n  const auto& tmp_Hv = apply_hamiltonian(tmp_v);\n  for (std::size_t i = 0; i < n; i++) Hv(i, 0) = tmp_Hv[i];\n  lowest_eigenvalue = v.col(0).dot(Hv.col(0));\n  h_krylov(0, 0) = lowest_eigenvalue;\n  w = v.col(0);\n  Hw = Hv.col(0);\n  if (verbose) printf(\"Davidson Iteration #1. Eigenvalue: %#.15g\\n\", lowest_eigenvalue);\n\n  residual_norm = 1.0;  // So at least one iteration is done.\n  std::size_t n_iter = std::min(n, iterations);\n  size_t n_diagonalize = 1;\n\n  for (std::size_t it = 1; it < n_iter; it++) {\n    // Compute residual.\n    for (std::size_t j = 0; j < n; j++) {\n      v(j, it) = (Hw(j, 0) - lowest_eigenvalue * w(j, 0)) / (lowest_eigenvalue - diag_elems(j));\n      if (fabs(lowest_eigenvalue - diag_elems[j]) < 1.0e-8) v(j, it) = -1.0;\n    }\n\n    // If residual is small, converge.\n    residual_norm = v.col(it).norm();\n    if (residual_norm < 1.0e-6) converged = true;\n\n    // Orthogonalize and normalize.\n    for (std::size_t i = 0; i < it; i++) {\n      double norm = v.col(it).dot(v.col(i));\n      v.col(it) -= norm * v.col(i);\n    }\n    v.col(it).normalize();\n\n    // Apply H once.\n    for (std::size_t i = 0; i < n; i++) tmp_v[i] = v(i, it);\n    const auto& tmp_Hv2 = apply_hamiltonian(tmp_v);\n    for (std::size_t i = 0; i < n; i++) Hv(i, it) = tmp_Hv2[i];\n\n    // Construct Krylow matrix and diagonalize.\n    for (std::size_t i = 0; i <= it; i++) {\n      h_krylov(i, it) = v.col(i).dot(Hv.col(it));\n      h_krylov(it, i) = h_krylov(i, it);\n    }\n\n    len_work = 3 * it + 2;\n    h_overwrite = h_krylov.leftCols(it + 1).topRows(it + 1);\n    Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> eigenSolver(\n        h_krylov.leftCols(it + 1).topRows(it + 1));\n    const auto& eigenvalues = eigenSolver.eigenvalues();\n    const auto& eigenvectors = eigenSolver.eigenvectors();\n    lowest_eigenvalue = eigenvalues[0];\n    std::size_t lowest_id = 0;\n    for (std::size_t i = 1; i <= it; i++) {\n      if (eigenvalues[i] < lowest_eigenvalue) {\n        lowest_eigenvalue = eigenvalues[i];\n        lowest_id = i;\n      }\n    }\n    w = v.leftCols(it) * eigenvectors.col(lowest_id).topRows(it);\n    Hw = Hv.leftCols(it) * eigenvectors.col(lowest_id).topRows(it);\n\n    if (it > 1 && fabs(lowest_eigenvalue - lowest_eigenvalue_prev) < TOLERANCE) {\n      converged = true;\n      break;\n    } else {\n      lowest_eigenvalue_prev = lowest_eigenvalue;\n      n_diagonalize++;\n      if (verbose)\n        printf(\"Davidson Iteration #%zu. Eigenvalue: %#.15g\\n\", n_diagonalize, lowest_eigenvalue);\n    }\n\n    if (converged) break;\n  }\n\n  this->lowest_eigenvalue = lowest_eigenvalue;\n  lowest_eigenvector.resize(n);\n  for (std::size_t i = 0; i < n; i++) lowest_eigenvector[i] = w(i);\n  diagonalized = true;\n\n  return n_diagonalize;\n}", "meta": {"hexsha": "335fd7d8fb5246200119353cc095cedc5441fb7a", "size": 4183, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/solver/davidson.cc", "max_stars_repo_name": "jl2922/hci-17c", "max_stars_repo_head_hexsha": "401a04d67c1d37e83dacc73bebeb8561c13bd4b2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-08-21T13:55:00.000Z", "max_stars_repo_stars_event_max_datetime": "2017-08-21T13:55:00.000Z", "max_issues_repo_path": "src/solver/davidson.cc", "max_issues_repo_name": "jl2922/hci-17c", "max_issues_repo_head_hexsha": "401a04d67c1d37e83dacc73bebeb8561c13bd4b2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/solver/davidson.cc", "max_forks_repo_name": "jl2922/hci-17c", "max_forks_repo_head_hexsha": "401a04d67c1d37e83dacc73bebeb8561c13bd4b2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7338709677, "max_line_length": 98, "alphanum_fraction": 0.6213244083, "num_tokens": 1377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.752012562644147, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.48715239795847814}}
{"text": "#include <armadillo>\n\n#include \"psi4/libmints/basisset.h\"\n#include \"psi4/libmints/integral.h\"\n#include \"psi4/libmints/matrix.h\"\n#include \"psi4/libmints/mintshelper.h\"\n#include \"psi4/libmints/vector3.h\"\n\nusing namespace psi;\n\nvoid AO_dipole_length(arma::cube &M_AO,\n                      const arma::vec &origin,\n                      SharedWavefunction wfn,\n                      Options &options) {\n\n    const Vector3 sm_origin(origin.memptr());\n\n    const size_t nbf = wfn->basisset()->nbf();\n\n    std::shared_ptr<IntegralFactory> intfactory = wfn->integral();\n\n    std::vector<SharedMatrix> v_dipole;\n\n    v_dipole.push_back(SharedMatrix(new Matrix(\"AO Mux\", nbf, nbf)));\n    v_dipole.push_back(SharedMatrix(new Matrix(\"AO Muy\", nbf, nbf)));\n    v_dipole.push_back(SharedMatrix(new Matrix(\"AO Muz\", nbf, nbf)));\n\n    std::shared_ptr<OneBodyAOInt> ints(intfactory->ao_dipole());\n    ints->set_origin(sm_origin);\n    ints->compute(v_dipole);\n\n    M_AO.set_size(nbf, nbf, v_dipole.size());\n\n    for (size_t c = 0; c < v_dipole.size(); c++) {\n        SharedMatrix msm_dipole = v_dipole[c];\n        arma::mat ma_dipole(msm_dipole->get_pointer(),\n                            msm_dipole->rowdim(),\n                            msm_dipole->coldim(),\n                            false,\n                            true);\n        M_AO.slice(c) = ma_dipole;\n    }\n\n    return;\n}\n\nvoid AO_quadrupole_length(arma::cube &M_AO,\n                          const arma::vec &origin,\n                          SharedWavefunction wfn,\n                          Options &options) {\n\n    const Vector3 sm_origin(origin.memptr());\n\n    const size_t nbf = wfn->basisset()->nbf();\n\n    std::shared_ptr<IntegralFactory> intfactory = wfn->integral();\n\n    std::vector<SharedMatrix> v_quadrupole;\n\n    v_quadrupole.push_back(SharedMatrix(new Matrix(\"AO Quadrupole XX\", nbf, nbf)));\n    v_quadrupole.push_back(SharedMatrix(new Matrix(\"AO Quadrupole XY\", nbf, nbf)));\n    v_quadrupole.push_back(SharedMatrix(new Matrix(\"AO Quadrupole XZ\", nbf, nbf)));\n    v_quadrupole.push_back(SharedMatrix(new Matrix(\"AO Quadrupole YY\", nbf, nbf)));\n    v_quadrupole.push_back(SharedMatrix(new Matrix(\"AO Quadrupole YZ\", nbf, nbf)));\n    v_quadrupole.push_back(SharedMatrix(new Matrix(\"AO Quadrupole ZZ\", nbf, nbf)));\n\n    std::shared_ptr<OneBodyAOInt> ints(intfactory->ao_quadrupole());\n    ints->set_origin(sm_origin);\n    ints->compute(v_quadrupole);\n\n    M_AO.set_size(nbf, nbf, v_quadrupole.size());\n\n    for (size_t c = 0; c < v_quadrupole.size(); c++) {\n        SharedMatrix msm_quadrupole = v_quadrupole[c];\n        arma::mat ma_quadrupole(msm_quadrupole->get_pointer(),\n                                msm_quadrupole->rowdim(),\n                                msm_quadrupole->coldim(),\n                                false,\n                                true);\n        M_AO.slice(c) = ma_quadrupole;\n    }\n\n    return;\n}\n\nvoid AO_multipole(arma::cube &M_AO,\n                  const arma::uvec &order,\n                  const arma::vec &origin,\n                  SharedWavefunction wfn,\n                  Options &options) {\n\n    // TODO\n    return;\n}\n\nvoid AO_dipole_velocity(arma::cube &D_AO, SharedWavefunction wfn, Options &options) {\n\n    const size_t nbf = wfn->basisset()->nbf();\n\n    std::shared_ptr<IntegralFactory> intfactory = wfn->integral();\n\n    std::vector<SharedMatrix> v_nabla;\n\n    v_nabla.push_back(SharedMatrix(new Matrix(\"AO Px\", nbf, nbf)));\n    v_nabla.push_back(SharedMatrix(new Matrix(\"AO Py\", nbf, nbf)));\n    v_nabla.push_back(SharedMatrix(new Matrix(\"AO Pz\", nbf, nbf)));\n\n    std::shared_ptr<OneBodyAOInt> ints(intfactory->ao_nabla());\n    ints->compute(v_nabla);\n\n    D_AO.set_size(nbf, nbf, v_nabla.size());\n\n    for (size_t c = 0; c < v_nabla.size(); c++) {\n        SharedMatrix msm_nabla = v_nabla[c];\n        arma::mat ma_nabla(msm_nabla->get_pointer(),\n                           msm_nabla->rowdim(),\n                           msm_nabla->coldim(),\n                           false,\n                           true);\n        D_AO.slice(c) = ma_nabla;\n        // TODO check for antisymmetry due to imaginary operator\n    }\n\n    return;\n}\n\nvoid AO_angular_momentum(arma::cube &L_AO,\n                         const arma::vec &origin,\n                         SharedWavefunction wfn,\n                         Options &options) {\n\n    const Vector3 sm_origin(origin.memptr());\n\n    const size_t nbf = wfn->basisset()->nbf();\n\n    std::shared_ptr<IntegralFactory> intfactory = wfn->integral();\n\n    std::vector<SharedMatrix> v_angmom;\n\n    v_angmom.push_back(SharedMatrix(new Matrix(\"AO Lx\", nbf, nbf)));\n    v_angmom.push_back(SharedMatrix(new Matrix(\"AO Ly\", nbf, nbf)));\n    v_angmom.push_back(SharedMatrix(new Matrix(\"AO Lz\", nbf, nbf)));\n\n    std::shared_ptr<OneBodyAOInt> ints(intfactory->ao_angular_momentum());\n    ints->set_origin(sm_origin);\n    ints->compute(v_angmom);\n\n    L_AO.set_size(nbf, nbf, v_angmom.size());\n\n    for (size_t c = 0; c < v_angmom.size(); c++) {\n        SharedMatrix msm_angmom = v_angmom[c];\n        arma::mat ma_angmom(msm_angmom->get_pointer(),\n                            msm_angmom->rowdim(),\n                            msm_angmom->coldim(),\n                            false,\n                            true);\n        L_AO.slice(c) = ma_angmom;\n        // TODO check for antisymmetry due to imaginary operator\n    }\n\n    return;\n}\n", "meta": {"hexsha": "e1bec6043f8a4159c03f2731920eee7b72b9520b", "size": 5370, "ext": "cc", "lang": "C++", "max_stars_repo_path": "wrappers.cc", "max_stars_repo_name": "berquist/libresponse_psi4", "max_stars_repo_head_hexsha": "e3b5a54d5d8b1027880601d5de658a2ac252aee2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-29T00:58:06.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-29T00:58:06.000Z", "max_issues_repo_path": "wrappers.cc", "max_issues_repo_name": "berquist/libresponse_psi4", "max_issues_repo_head_hexsha": "e3b5a54d5d8b1027880601d5de658a2ac252aee2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "wrappers.cc", "max_forks_repo_name": "berquist/libresponse_psi4", "max_forks_repo_head_hexsha": "e3b5a54d5d8b1027880601d5de658a2ac252aee2", "max_forks_repo_licenses": ["BSD-3-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.9447852761, "max_line_length": 85, "alphanum_fraction": 0.5905027933, "num_tokens": 1450, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.6334102705979902, "lm_q1q2_score": 0.4871433210745364}}
{"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) 2003 Ferdinando Ametrano\n Copyright (C) 2004, 2005, 2006, 2007, 2009 StatPro Italia srl\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/*! \\file blackscholesprocess.hpp\n    \\brief Black-Scholes processes\n*/\n\n#ifndef quantlib_black_scholes_process_hpp\n#define quantlib_black_scholes_process_hpp\n\n#include <ql/stochasticprocess.hpp>\n#include <ql/processes/eulerdiscretization.hpp>\n#include <ql/termstructures/yieldtermstructure.hpp>\n#include <ql/termstructures/volatility/equityfx/blackvoltermstructure.hpp>\n#include <ql/termstructures/volatility/equityfx/localvoltermstructure.hpp>\n#include <ql/quote.hpp>\n\nnamespace QuantLib {\n\n    class LocalConstantVol;\n    class LocalVolCurve;\n\n    //! Generalized Black-Scholes stochastic process\n    /*! This class describes the stochastic process \\f$ S \\f$ governed by\n        \\f[\n            d\\ln S(t) = (r(t) - q(t) - \\frac{\\sigma(t, S)^2}{2}) dt\n                     + \\sigma dW_t.\n        \\f]\n\n        \\warning while the interface is expressed in terms of \\f$ S \\f$,\n                 the internal calculations work on \\f$ ln S \\f$.\n\n        \\ingroup processes\n    */\n    class GeneralizedBlackScholesProcess : public StochasticProcess1D {\n      public:\n        GeneralizedBlackScholesProcess(\n            const Handle<Quote>& x0,\n            const Handle<YieldTermStructure>& dividendTS,\n            const Handle<YieldTermStructure>& riskFreeTS,\n            const Handle<BlackVolTermStructure>& blackVolTS,\n            const boost::shared_ptr<discretization>& d =\n                  boost::shared_ptr<discretization>(new EulerDiscretization),\n            bool forceDiscretization = false);\n        //! \\name StochasticProcess1D interface\n        //@{\n        Real x0() const;\n        /*! \\todo revise extrapolation */\n        Real drift(Time t, Real x) const;\n        /*! \\todo revise extrapolation */\n        Real diffusion(Time t, Real x) const;\n        Real apply(Real x0, Real dx) const;\n        /*! \\warning in general raises a \"not implemented\" exception.\n                     It should be rewritten to return the expectation E(S)\n                     of the process, not exp(E(log S)).\n        */\n        Real expectation(Time t0, Real x0, Time dt) const;\n        Real stdDeviation(Time t0, Real x0, Time dt) const;\n        Real variance(Time t0, Real x0, Time dt) const;\n        Real evolve(Time t0, Real x0, Time dt, Real dw) const;\n        //@}\n        Time time(const Date&) const;\n        //! \\name Observer interface\n        //@{\n        void update();\n        //@}\n        //! \\name Inspectors\n        //@{\n        const Handle<Quote>& stateVariable() const;\n        const Handle<YieldTermStructure>& dividendYield() const;\n        const Handle<YieldTermStructure>& riskFreeRate() const;\n        const Handle<BlackVolTermStructure>& blackVolatility() const;\n        const Handle<LocalVolTermStructure>& localVolatility() const;\n        //@}\n      private:\n        Handle<Quote> x0_;\n        Handle<YieldTermStructure> riskFreeRate_, dividendYield_;\n        Handle<BlackVolTermStructure> blackVolatility_;\n        bool forceDiscretization_;\n        mutable RelinkableHandle<LocalVolTermStructure> localVolatility_;\n        mutable bool updated_, isStrikeIndependent_;\n    };\n\n    //! Black-Scholes (1973) stochastic process\n    /*! This class describes the stochastic process \\f$ S \\f$ for a stock\n        given by\n        \\f[\n            d\\ln S(t) = (r(t) - \\frac{\\sigma(t, S)^2}{2}) dt + \\sigma dW_t.\n        \\f]\n\n        \\warning while the interface is expressed in terms of \\f$ S \\f$,\n                 the internal calculations work on \\f$ ln S \\f$.\n\n        \\ingroup processes\n    */\n    class BlackScholesProcess : public GeneralizedBlackScholesProcess {\n      public:\n        BlackScholesProcess(\n            const Handle<Quote>& x0,\n            const Handle<YieldTermStructure>& riskFreeTS,\n            const Handle<BlackVolTermStructure>& blackVolTS,\n            const boost::shared_ptr<discretization>& d =\n                  boost::shared_ptr<discretization>(new EulerDiscretization),\n            bool forceDiscretization = false);\n    };\n\n    //! Merton (1973) extension to the Black-Scholes stochastic process\n    /*! This class describes the stochastic process ln(S) for a stock or\n        stock index paying a continuous dividend yield given by\n        \\f[\n            d\\ln S(t, S) = (r(t) - q(t) - \\frac{\\sigma(t, S)^2}{2}) dt\n                     + \\sigma dW_t.\n        \\f]\n\n        \\ingroup processes\n    */\n    class BlackScholesMertonProcess : public GeneralizedBlackScholesProcess {\n      public:\n        BlackScholesMertonProcess(\n            const Handle<Quote>& x0,\n            const Handle<YieldTermStructure>& dividendTS,\n            const Handle<YieldTermStructure>& riskFreeTS,\n            const Handle<BlackVolTermStructure>& blackVolTS,\n            const boost::shared_ptr<discretization>& d =\n                  boost::shared_ptr<discretization>(new EulerDiscretization),\n            bool forceDiscretization = false);\n    };\n\n    //! Black (1976) stochastic process\n    /*! This class describes the stochastic process \\f$ S \\f$ for a\n        forward or futures contract given by\n        \\f[\n            d\\ln S(t) = -\\frac{\\sigma(t, S)^2}{2} dt + \\sigma dW_t.\n        \\f]\n\n        \\warning while the interface is expressed in terms of \\f$ S \\f$,\n                 the internal calculations work on \\f$ ln S \\f$.\n\n        \\ingroup processes\n    */\n    class BlackProcess : public GeneralizedBlackScholesProcess {\n      public:\n        BlackProcess(\n            const Handle<Quote>& x0,\n            const Handle<YieldTermStructure>& riskFreeTS,\n            const Handle<BlackVolTermStructure>& blackVolTS,\n            const boost::shared_ptr<discretization>& d =\n                  boost::shared_ptr<discretization>(new EulerDiscretization),\n            bool forceDiscretization = false);\n    };\n\n    //! Garman-Kohlhagen (1983) stochastic process\n    /*! This class describes the stochastic process \\f$ S \\f$ for an exchange\n        rate given by\n        \\f[\n            d\\ln S(t) = (r(t) - r_f(t) - \\frac{\\sigma(t, S)^2}{2}) dt\n                     + \\sigma dW_t.\n        \\f]\n\n        \\warning while the interface is expressed in terms of \\f$ S \\f$,\n                 the internal calculations work on \\f$ ln S \\f$.\n\n        \\ingroup processes\n    */\n    class GarmanKohlagenProcess : public GeneralizedBlackScholesProcess {\n      public:\n        GarmanKohlagenProcess(\n            const Handle<Quote>& x0,\n            const Handle<YieldTermStructure>& foreignRiskFreeTS,\n            const Handle<YieldTermStructure>& domesticRiskFreeTS,\n            const Handle<BlackVolTermStructure>& blackVolTS,\n            const boost::shared_ptr<discretization>& d =\n                  boost::shared_ptr<discretization>(new EulerDiscretization),\n            bool forceDiscretization = false);\n    };\n\n}\n\n\n/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2003 Ferdinando Ametrano\n Copyright (C) 2001, 2002, 2003 Sadruddin Rejeb\n Copyright (C) 2004, 2005, 2006, 2007 StatPro Italia srl\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/termstructures/volatility/equityfx/localvolsurface.hpp>\n#include <ql/termstructures/volatility/equityfx/localvolcurve.hpp>\n#include <ql/termstructures/volatility/equityfx/localconstantvol.hpp>\n#include <ql/termstructures/yield/flatforward.hpp>\n#include <ql/time/calendars/nullcalendar.hpp>\n#include <ql/time/daycounters/actual365fixed.hpp>\n\n#include <boost/make_shared.hpp>\n\nnamespace QuantLib {\n\n    inline GeneralizedBlackScholesProcess::GeneralizedBlackScholesProcess(\n             const Handle<Quote>& x0,\n             const Handle<YieldTermStructure>& dividendTS,\n             const Handle<YieldTermStructure>& riskFreeTS,\n             const Handle<BlackVolTermStructure>& blackVolTS,\n             const boost::shared_ptr<discretization>& disc,\n             bool forceDiscretization)\n    : StochasticProcess1D(disc), x0_(x0), riskFreeRate_(riskFreeTS),\n      dividendYield_(dividendTS), blackVolatility_(blackVolTS),\n      forceDiscretization_(forceDiscretization), updated_(false) {\n        registerWith(x0_);\n        registerWith(riskFreeRate_);\n        registerWith(dividendYield_);\n        registerWith(blackVolatility_);\n    }\n\n    inline Real GeneralizedBlackScholesProcess::x0() const {\n        return x0_->value();\n    }\n\n    inline Real GeneralizedBlackScholesProcess::drift(Time t, Real x) const {\n        Real sigma = diffusion(t,x);\n        // we could be more anticipatory if we know the right dt\n        // for which the drift will be used\n        Time t1 = t + 0.0001;\n        return riskFreeRate_->forwardRate(t,t1,Continuous,NoFrequency,true)\n             - dividendYield_->forwardRate(t,t1,Continuous,NoFrequency,true)\n             - 0.5 * sigma * sigma;\n    }\n\n    inline Real GeneralizedBlackScholesProcess::diffusion(Time t, Real x) const {\n        return localVolatility()->localVol(t, x, true);\n    }\n\n    inline Real GeneralizedBlackScholesProcess::apply(Real x0, Real dx) const {\n        return x0 * std::exp(dx);\n    }\n\n    inline Real GeneralizedBlackScholesProcess::expectation(Time t0,\n                                                     Real x0,\n                                                     Time dt) const {\n        localVolatility(); // trigger update\n        if(isStrikeIndependent_ && !forceDiscretization_) {\n            // exact value for curves\n            return x0 *\n                std::exp(dt * (riskFreeRate_->forwardRate(t0, t0 + dt, Continuous,\n                                                          NoFrequency, true) -\n                             dividendYield_->forwardRate(\n                                 t0, t0 + dt, Continuous, NoFrequency, true)));\n        } else {\n            QL_FAIL(\"not implemented\");\n        }\n    }\n\n    inline Real GeneralizedBlackScholesProcess::stdDeviation(Time t0, Real x0, Time dt) const {\n        localVolatility(); // trigger update\n        if(isStrikeIndependent_ && !forceDiscretization_) {\n            // exact value for curves\n            return std::sqrt(variance(t0,x0,dt));\n        }\n        else{\n            return discretization_->diffusion(*this,t0,x0,dt);\n        }\n    }\n\n    inline Real GeneralizedBlackScholesProcess::variance(Time t0, Real x0, Time dt) const {\n        localVolatility(); // trigger update\n        if(isStrikeIndependent_ && !forceDiscretization_) {\n            // exact value for curves\n            return blackVolatility_->blackVariance(t0 + dt, 0.01) -\n                   blackVolatility_->blackVariance(t0, 0.01);\n        }\n        else{\n            return discretization_->variance(*this,t0,x0,dt);\n        }\n    }\n\n    inline Real GeneralizedBlackScholesProcess::evolve(Time t0, Real x0,\n                                                Time dt, Real dw) const {\n        localVolatility(); // trigger update\n        if (isStrikeIndependent_ && !forceDiscretization_) {\n            // exact value for curves\n            Real var = variance(t0, x0, dt);\n            Real drift = (riskFreeRate_->forwardRate(t0, t0 + dt, Continuous,\n                                                     NoFrequency, true) -\n                          dividendYield_->forwardRate(t0, t0 + dt, Continuous,\n                                                      NoFrequency, true)) *\n                             dt -\n                         0.5 * var;\n            return apply(x0, std::sqrt(var) * dw + drift);\n        } else\n            return apply(x0, discretization_->drift(*this, t0, x0, dt) +\n                                 stdDeviation(t0, x0, dt) * dw);\n    }\n\n    inline Time GeneralizedBlackScholesProcess::time(const Date& d) const {\n        return riskFreeRate_->dayCounter().yearFraction(\n                                           riskFreeRate_->referenceDate(), d);\n    }\n\n    inline void GeneralizedBlackScholesProcess::update() {\n        updated_ = false;\n        StochasticProcess1D::update();\n    }\n\n    inline const Handle<Quote>&\n    GeneralizedBlackScholesProcess::stateVariable() const {\n        return x0_;\n    }\n\n    inline const Handle<YieldTermStructure>&\n    GeneralizedBlackScholesProcess::dividendYield() const {\n        return dividendYield_;\n    }\n\n    inline const Handle<YieldTermStructure>&\n    GeneralizedBlackScholesProcess::riskFreeRate() const {\n        return riskFreeRate_;\n    }\n\n    inline const Handle<BlackVolTermStructure>&\n    GeneralizedBlackScholesProcess::blackVolatility() const {\n        return blackVolatility_;\n    }\n\n    inline const Handle<LocalVolTermStructure>&\n    GeneralizedBlackScholesProcess::localVolatility() const {\n        if (!updated_) {\n            isStrikeIndependent_=true;\n\n            // constant Black vol?\n            boost::shared_ptr<BlackConstantVol> constVol =\n                boost::dynamic_pointer_cast<BlackConstantVol>(\n                                                          *blackVolatility());\n            if (constVol) {\n                // ok, the local vol is constant too.\n                localVolatility_.linkTo(boost::make_shared<LocalConstantVol>(\n                    constVol->referenceDate(),\n                    constVol->blackVol(0.0, x0_->value()),\n                    constVol->dayCounter()));\n                updated_ = true;\n                return localVolatility_;\n            }\n\n            // ok, so it's not constant. Maybe it's strike-independent?\n            boost::shared_ptr<BlackVarianceCurve> volCurve =\n                boost::dynamic_pointer_cast<BlackVarianceCurve>(\n                                                          *blackVolatility());\n            if (volCurve) {\n                // ok, we can use the optimized algorithm\n                localVolatility_.linkTo(boost::make_shared<LocalVolCurve>(\n                    Handle<BlackVarianceCurve>(volCurve)));\n                updated_ = true;\n                return localVolatility_;\n            }\n\n            // ok, so it's strike-dependent. Never mind.\n            localVolatility_.linkTo(\n                boost::make_shared<LocalVolSurface>(blackVolatility_, riskFreeRate_,\n                                                    dividendYield_, x0_->value()));\n            updated_ = true;\n            isStrikeIndependent_ = false;\n            return localVolatility_;\n\n        } else {\n            return localVolatility_;\n        }\n    }\n\n\n    // specific models\n\n    inline BlackScholesProcess::BlackScholesProcess(\n                              const Handle<Quote>& x0,\n                              const Handle<YieldTermStructure>& riskFreeTS,\n                              const Handle<BlackVolTermStructure>& blackVolTS,\n                              const boost::shared_ptr<discretization>& d,\n                              bool forceDiscretization)\n    : GeneralizedBlackScholesProcess(\n             x0,\n             // no dividend yield\n             Handle<YieldTermStructure>(boost::shared_ptr<YieldTermStructure>(\n                  new FlatForward(0, NullCalendar(), 0.0, Actual365Fixed()))),\n             riskFreeTS,\n             blackVolTS,\n             d,forceDiscretization) {}\n\n\n    inline BlackScholesMertonProcess::BlackScholesMertonProcess(\n                              const Handle<Quote>& x0,\n                              const Handle<YieldTermStructure>& dividendTS,\n                              const Handle<YieldTermStructure>& riskFreeTS,\n                              const Handle<BlackVolTermStructure>& blackVolTS,\n                              const boost::shared_ptr<discretization>& d,\n                              bool forceDiscretization)\n    : GeneralizedBlackScholesProcess(x0,dividendTS,riskFreeTS,blackVolTS,d,\n                                     forceDiscretization) {}\n\n\n    inline BlackProcess::BlackProcess(const Handle<Quote>& x0,\n                               const Handle<YieldTermStructure>& riskFreeTS,\n                               const Handle<BlackVolTermStructure>& blackVolTS,\n                               const boost::shared_ptr<discretization>& d,\n                               bool forceDiscretization)\n    : GeneralizedBlackScholesProcess(x0,riskFreeTS,riskFreeTS,blackVolTS,d,\n                                     forceDiscretization) {}\n\n\n    inline GarmanKohlagenProcess::GarmanKohlagenProcess(\n                          const Handle<Quote>& x0,\n                          const Handle<YieldTermStructure>& foreignRiskFreeTS,\n                          const Handle<YieldTermStructure>& domesticRiskFreeTS,\n                          const Handle<BlackVolTermStructure>& blackVolTS,\n                          const boost::shared_ptr<discretization>& d,\n                          bool forceDiscretization)\n    : GeneralizedBlackScholesProcess(x0,foreignRiskFreeTS,domesticRiskFreeTS,\n                                     blackVolTS,d,forceDiscretization) {}\n\n}\n\n#endif", "meta": {"hexsha": "73849b5d63475cf6102f96fcb6f9bc452cab142c", "size": 18373, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/processes/blackscholesprocess.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/processes/blackscholesprocess.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/processes/blackscholesprocess.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": 40.6482300885, "max_line_length": 95, "alphanum_fraction": 0.6048005225, "num_tokens": 4181, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.48714331575238573}}
{"text": "//\n//  LoudspeakerArray.h\n//\n//  Created by Marcos F. Sim\ufffdn G\ufffdlvez on 02/02/2015.\n//  Copyright (c) 2014 ISVR, University of Southampton. All rights reserved.\n//\n\n// avoid annoying warning about unsafe STL functions.\n#ifdef _MSC_VER \n#pragma warning(disable: 4996)\n#endif\n\n#include \"listener_compensation.hpp\"\n\n#include <cstdio>\n\n#include <libpanning/defs.h>\n#include <libpanning/XYZ.h>\n\n#include <libpml/vector_parameter_config.hpp>\n\n#include <boost/filesystem.hpp>\n\n#include <algorithm>\n#include <cmath>\n\n// Uncomment to get debug output\n// #define DEBUG_LISTENER_COMPENSATION 1\n\n#ifdef DEBUG_LISTENER_COMPENSATION\n#include <iostream>\n#include <iterator>\n#include <algorithm>\n#endif\n\n// TODO: Move definition to a separate file.\n#define c_0 344\n\n\nnamespace visr\n{\nnamespace rcl\n{\n  ListenerCompensation::ListenerCompensation( SignalFlowContext const & context,\n                                              char const * name,\n                                              CompositeComponent * parent,\n                                              panning::LoudspeakerArray const & arrayConfig )\n  : AtomicComponent( context, name, parent )\n  , m_listenerPos( 0.0f, 0.0f, 0.0f )\n  , mNumberOfLoudspeakers( arrayConfig.getNumRegularSpeakers() )\n  , mPositionInput( \"positionInput\", *this, pml::EmptyParameterConfig() )\n  , mGainOutput( \"gainOutput\", *this )\n  , mDelayOutput( \"delayOutput\", *this)\n{\n  m_array = arrayConfig;\n  pml::VectorParameterConfig const vectorConfig( mNumberOfLoudspeakers );\n\n  mGainOutput.setParameterConfig( vectorConfig );\n  mDelayOutput.setParameterConfig( vectorConfig );\n}\n\nvoid ListenerCompensation::process()\n{\n  if( mPositionInput.changed() )\n  {\n    pml::ListenerPosition const & pos( mPositionInput.data());\n    efl::BasicVector<SampleType> & gains( mGainOutput.data());\n    efl::BasicVector<SampleType> & delays( mDelayOutput.data());\n\n    if (gains.size() != mNumberOfLoudspeakers or delays.size() != mNumberOfLoudspeakers)\n    {\n      throw std::invalid_argument(\"ListenerCompensation::process(): The size of the gain or delay vector does not match the number of loudspeaker channels.\");\n    }\n\n    setListenerPosition(pos.x(), pos.y(), pos.z());\n    if( calcGainComp( gains ) != 0 )\n    {\n      throw std::runtime_error(\"ListenerCompensation::process(): calcGainComp() failed.\");\n    }\n    if (calcDelayComp( delays ) != 0)\n    {\n      throw std::runtime_error(\"ListenerCompensation::process(): calcDelayComp() failed.\");\n    }\n\n#ifdef DEBUG_LISTENER_COMPENSATION\n    std::cout << \"DelayVector Source Gain: \";\n    std::copy( gains.data(), gains.data()+gains.size(), std::ostream_iterator<float>(std::cout, \" \") );\n    std::cout << \"Delay [s]: \";\n    std::copy( delays.data(), delays.data()+delays.size(), std::ostream_iterator<float>(std::cout, \" \") );\n    std::cout << std::endl;\n#endif // DEBUG_LISTENER_COMPENSATION\n\n    mPositionInput.resetChanged();\n    mGainOutput.swapBuffers();\n    mDelayOutput.swapBuffers();\n  }\n}\n\nint ListenerCompensation::calcGainComp( efl::BasicVector<Afloat> & gainComp )\n{\n  panning::XYZ l1;\n  Afloat rad = 0.0f, max_rad = 0.0f, x = 0.0f, y = 0.0f, z = 0.0f;\n\n  //setting listener position\n  x = m_listenerPos.x;\n  y = m_listenerPos.y;\n  z = m_listenerPos.z;\n\n  for (std::size_t i = 0; i < m_array.getNumSpeakers(); i++) {\n\n    l1 = m_array.getPosition( i );\n\n    rad = std::sqrt(std::pow((l1.x - x), 2.0f) + std::pow((l1.y - y), 2.0f) + std::pow((l1.z - z), 2.0f));\n\n    gainComp[i] = rad;\n\n    if ( gainComp[i]>max_rad)\n      max_rad = gainComp[i];\n  }\n\n  for (std::size_t i = 0; i < m_array.getNumSpeakers(); i++) {\n\n    gainComp[i] = (gainComp[i]/max_rad);\n  }\n  return 0;\n}\n\n\nint ListenerCompensation::calcDelayComp( efl::BasicVector<Afloat> & delayComp )\n{\n  \n  Afloat rad=0.0f, max_rad=0.0f, x=0.0f, y=0.0f, z=0.0f;\n  panning::XYZ l1;\n\n  //setting listener position\n  x = m_listenerPos.x;\n  y = m_listenerPos.y;\n  z = m_listenerPos.z;\n\n  for (std::size_t i = 0; i < m_array.getNumSpeakers(); i++) {\n\n    l1 = m_array.getPosition( i );\n\n    rad = std::sqrt(std::pow((l1.x-x),2.0f) + std::pow((l1.y-y),2.0f) + std::pow((l1.z-z),2.0f));\n\n    delayComp[i] = rad;\n\n    if (delayComp[i]>max_rad)\n      max_rad = delayComp[i];\n  }\n\n  for ( std::size_t i = 0; i < m_array.getNumSpeakers(); i++){\n\n    delayComp[i] = std::abs(delayComp[i]-max_rad)/c_0;\n  }\n  return 0;\n}\n\n}// rcl\n}//visr\n\n", "meta": {"hexsha": "547b735aba96135e502be81a87971374080501de", "size": 4358, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/librcl/listener_compensation.cpp", "max_stars_repo_name": "s3a-spatialaudio/VISR", "max_stars_repo_head_hexsha": "55f6289bc5058d4898106f3520e1a60644ffb3ab", "max_stars_repo_licenses": ["ISC"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2019-03-12T14:52:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T01:16:23.000Z", "max_issues_repo_path": "src/librcl/listener_compensation.cpp", "max_issues_repo_name": "s3a-spatialaudio/VISR", "max_issues_repo_head_hexsha": "55f6289bc5058d4898106f3520e1a60644ffb3ab", "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/librcl/listener_compensation.cpp", "max_forks_repo_name": "s3a-spatialaudio/VISR", "max_forks_repo_head_hexsha": "55f6289bc5058d4898106f3520e1a60644ffb3ab", "max_forks_repo_licenses": ["ISC"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-08-11T12:53:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-22T10:08:08.000Z", "avg_line_length": 26.9012345679, "max_line_length": 158, "alphanum_fraction": 0.6500688389, "num_tokens": 1267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851919, "lm_q2_score": 0.63341027059799, "lm_q1q2_score": 0.4871433143695489}}
{"text": "#include \"aslam/calibration/target-algorithms.h\"\n\n#include <Eigen/Core>\n#include <aslam/geometric-vision/pnp-pose-estimator.h>\n\nnamespace aslam {\nnamespace calibration {\n\nbool estimateTargetTransformation(\n    const TargetObservation& target_observation,\n    const aslam::Camera::ConstPtr& camera_ptr, aslam::Transformation* T_G_C) {\n  CHECK(camera_ptr);\n  CHECK_NOTNULL(T_G_C);\n  constexpr bool kRunNonlinearRefinement = true;\n  constexpr double kRansacPixelSigma = 1.0;\n  constexpr int kRansacMaxIters = 200;\n  return estimateTargetTransformation(\n      target_observation, camera_ptr, T_G_C, kRunNonlinearRefinement,\n      kRansacPixelSigma, kRansacMaxIters);\n}\n\nbool estimateTargetTransformation(\n    const TargetObservation& target_observation,\n    const aslam::Camera::ConstPtr& camera_ptr, aslam::Transformation* T_G_C,\n    const bool run_nonlinear_refinement, const double ransac_pixel_sigma,\n    const int ransac_max_iters) {\n  CHECK(camera_ptr);\n  CHECK_GT(ransac_pixel_sigma, 0.0);\n  CHECK_GT(ransac_max_iters, 0);\n  CHECK_NOTNULL(T_G_C);\n  const Eigen::Matrix2Xd& observed_corners =\n      target_observation.getObservedCorners();\n  // Corner positions in target coordinates (global frame).\n  const Eigen::Matrix3Xd corner_positions_G =\n      target_observation.getCorrespondingTargetPoints();\n  aslam::geometric_vision::PnpPoseEstimator pnp(run_nonlinear_refinement);\n  std::vector<int> inliers;\n  int num_iters = 0;\n  bool pnp_success = pnp.absolutePoseRansacPinholeCam(\n      observed_corners, corner_positions_G, ransac_pixel_sigma,\n      ransac_max_iters, camera_ptr, T_G_C, &inliers, &num_iters);\n  if (pnp_success) {\n    VLOG(4) << \"Found \" << inliers.size() << \"/\" << observed_corners.cols()\n            << \" inliers in\" << num_iters << \" iterations.\";\n  } else {\n    LOG(WARNING) << \"Target transformation estimation failed.\";\n  }\n  return pnp_success;\n}\n\n}  // namespace calibration\n}  // namespace aslam\n", "meta": {"hexsha": "6393a01b9ea7e7a3aafa14409f6926516c15db0f", "size": 1926, "ext": "cc", "lang": "C++", "max_stars_repo_path": "aslam_cv_calibration/src/target-algorithms.cc", "max_stars_repo_name": "shuhannod/aslam_cv2", "max_stars_repo_head_hexsha": "4dd48916b9e5b9d5aa56e28894a04d4a25a87348", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 173.0, "max_stars_repo_stars_event_min_datetime": "2017-09-19T18:14:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-20T09:11:15.000Z", "max_issues_repo_path": "aslam_cv_calibration/src/target-algorithms.cc", "max_issues_repo_name": "shuhannod/aslam_cv2", "max_issues_repo_head_hexsha": "4dd48916b9e5b9d5aa56e28894a04d4a25a87348", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 30.0, "max_issues_repo_issues_event_min_datetime": "2017-11-16T12:46:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-20T04:38:41.000Z", "max_forks_repo_path": "aslam_cv_calibration/src/target-algorithms.cc", "max_forks_repo_name": "shuhannod/aslam_cv2", "max_forks_repo_head_hexsha": "4dd48916b9e5b9d5aa56e28894a04d4a25a87348", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 58.0, "max_forks_repo_forks_event_min_datetime": "2017-10-24T17:31:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T03:23:24.000Z", "avg_line_length": 36.3396226415, "max_line_length": 78, "alphanum_fraction": 0.7518172378, "num_tokens": 505, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.6334102567576901, "lm_q1q2_score": 0.4871433104302351}}
{"text": "//==================================================================================================\n/*!\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#include <boost/simd/function/scalar/two_add.hpp>\n#include <scalar_test.hpp>\n#include <boost/simd/detail/dispatch/meta/as_integer.hpp>\n#include <boost/simd/constant/inf.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/zero.hpp>\n#include <boost/simd/constant/eps.hpp>\n#include <boost/simd/constant/half.hpp>\n#include <utility>\n\nSTF_CASE_TPL(\" two_add\", STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::two_add;\n\n\n  STF_EXPR_IS( (two_add(T(), T()))\n                  , (std::pair<T,T>)\n                  );\n\n  T inf_    = bs::Inf<T>();\n  T zero_   = bs::Zero<T>();\n  T one_    = bs::One<T>();\n  T half_   = bs::Half<T>();\n  T eps_    = bs::Eps<T>();\n  T eps_2_  = eps_/T(2);\n\n  std::pair<T,T> p;\n\n  p = two_add(inf_,zero_);\n  STF_EQUAL(p.first, inf_);\n  STF_EQUAL(p.second, zero_);\n\n  p = two_add(zero_, inf_);\n  STF_EQUAL(p.first, inf_);\n  STF_EQUAL(p.second, zero_);\n\n  p = two_add(half_+ eps_2_, half_);\n  STF_EQUAL(p.first, one_);\n  STF_EQUAL(p.second, eps_2_);\n\n  p = two_add(half_, half_+ eps_2_);\n  STF_EQUAL(p.first, one_);\n  STF_EQUAL(p.second, eps_2_);\n}\n", "meta": {"hexsha": "082d2098f58d2d1b69ab013c2bd33fb2865c62ae", "size": 1635, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/scalar/two_add.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": "test/function/scalar/two_add.cpp", "max_issues_repo_name": "remymuller/boost.simd", "max_issues_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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/function/scalar/two_add.cpp", "max_forks_repo_name": "remymuller/boost.simd", "max_forks_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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": 27.7118644068, "max_line_length": 100, "alphanum_fraction": 0.5785932722, "num_tokens": 446, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.727975460709318, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.48692841570295353}}
{"text": "#pragma once\n#include <boost/algorithm/string/split.hpp>\n#include <vector>\n#include <string>\n\nconstexpr auto parse_claim = [](const auto input) {\n  std::vector<std::string> nums;\n  boost::algorithm::split(\n      nums,\n      input,\n      [](const auto x) { return not std::isdigit(x); },\n      boost::token_compress_on);\n  std::vector<int> parsed;\n  std::for_each(nums.begin(), nums.end(),\n      [&parsed](const auto x) { if (x.length()>0) { parsed.push_back(std::stoi(x)); } });\n  return parsed;\n};\n\nconstexpr auto apply_claim = [](auto& claim_counts, const auto& claim) {\n  const auto left = claim[1];\n  const auto top = claim[2];\n  const auto width = claim[3];\n  const auto height = claim[4];\n\n  for (auto row = top; row < top+height; ++row) {\n    for (auto col = left; col < left+width; ++col) {\n      claim_counts[row][col]++;\n    }\n  }\n};\n\nconstexpr auto apply_claims = [](auto& claim_counts, const auto& claims) {\n  for (const auto& claim_text: claims) {\n    const auto claim = parse_claim(claim_text);\n    if (5 != claim.size()) continue;\n    apply_claim(claim_counts, claim);\n  }\n};\n\nconstexpr auto day3part1 = [](auto&& input) {\n  std::vector<std::string> claims;\n  while (!input.eof()) {\n    std::string line;\n    std::getline(input, line);\n    claims.push_back(line);\n  }\n\n  constexpr auto SIZE = 1000;\n  int claim_counts[SIZE][SIZE] = {0};\n  apply_claims(claim_counts, claims);\n  int overlap_squares = 0;\n  for (auto row = 0; row < SIZE; ++row) {\n    for (auto col = 0; col < SIZE; ++col) {\n      if (claim_counts[row][col] > 1) ++overlap_squares;\n    }\n  }\n  return overlap_squares;\n};\n", "meta": {"hexsha": "b72e14ef3f425de26eaf1d206ae4bc7d09701cf9", "size": 1599, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/day3part1.hpp", "max_stars_repo_name": "bengoodwyn/aoc-2018", "max_stars_repo_head_hexsha": "6eb7a6f77574331e41fabc9f58c78f1a6348784c", "max_stars_repo_licenses": ["MIT"], "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/day3part1.hpp", "max_issues_repo_name": "bengoodwyn/aoc-2018", "max_issues_repo_head_hexsha": "6eb7a6f77574331e41fabc9f58c78f1a6348784c", "max_issues_repo_licenses": ["MIT"], "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/day3part1.hpp", "max_forks_repo_name": "bengoodwyn/aoc-2018", "max_forks_repo_head_hexsha": "6eb7a6f77574331e41fabc9f58c78f1a6348784c", "max_forks_repo_licenses": ["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.1016949153, "max_line_length": 89, "alphanum_fraction": 0.6272670419, "num_tokens": 448, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059775, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.48692841261300845}}
{"text": "#include <boost/math/special_functions/jacobi_elliptic.hpp>\n", "meta": {"hexsha": "c099a77363a3c6b19a08f9194f4251b3a08e46e9", "size": 60, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_special_functions_jacobi_elliptic.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_special_functions_jacobi_elliptic.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_special_functions_jacobi_elliptic.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 30.0, "max_line_length": 59, "alphanum_fraction": 0.85, "num_tokens": 16, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199795472731, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.48691108289625634}}
{"text": "// Boost.Geometry\n\n// Copyright (c) 2021, Oracle and/or its affiliates.\n\n// Contributed and/or modified by Vissarion Fysikopoulos, on behalf of Oracle\n\n// Licensed under the Boost Software License version 1.0.\n// http://www.boost.org/users/license.html\n\n#ifndef BOOST_GEOMETRY_STRATEGIES_CARTESIAN_CLOSEST_POINTS_PT_SEG_HPP\n#define BOOST_GEOMETRY_STRATEGIES_CARTESIAN_CLOSEST_POINTS_PT_SEG_HPP\n\n#include <boost/geometry/core/coordinate_promotion.hpp>\n\n#include <boost/geometry/geometries/point.hpp>\n\n#include <boost/geometry/strategies/cartesian/distance_pythagoras.hpp>\n#include <boost/geometry/strategies/closest_points/services.hpp>\n\nnamespace boost { namespace geometry\n{\n\nnamespace strategy { namespace closest_points\n{\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail\n{\n\ntemplate <typename CalculationType>\nstruct compute_closest_point_to_segment\n{\n    template <typename Point, typename PointOfSegment>\n    static inline auto\n    apply(Point const& p, PointOfSegment const& p1, PointOfSegment const& p2)\n    {\n        // A projected point of points in Integer coordinates must be able to be\n        // represented in FP.\n        using fp_point_type = model::point\n            <\n                CalculationType,\n                dimension<PointOfSegment>::value,\n                typename coordinate_system<PointOfSegment>::type\n            >;\n\n        // For convenience\n        using fp_vector_type = fp_point_type;\n\n        /*\n            Algorithm [p: (px,py), p1: (x1,y1), p2: (x2,y2)]\n            VECTOR v(x2 - x1, y2 - y1)\n            VECTOR w(px - x1, py - y1)\n            c1 = w . v\n            c2 = v . v\n            b = c1 / c2\n            RETURN POINT(x1 + b * vx, y1 + b * vy)\n        */\n\n        // v is multiplied below with a (possibly) FP-value, so should be in FP\n        // For consistency we define w also in FP\n        fp_vector_type v, w, projected;\n\n        geometry::convert(p2, v);\n        geometry::convert(p, w);\n        geometry::convert(p1, projected);\n        subtract_point(v, projected);\n        subtract_point(w, projected);\n\n        CalculationType const zero = CalculationType();\n        CalculationType const c1 = dot_product(w, v);\n        if (c1 <= zero)\n        {\n            fp_vector_type fp_p1;\n            geometry::convert(p1, fp_p1);\n            return fp_p1;\n        }\n        CalculationType const c2 = dot_product(v, v);\n        if (c2 <= c1)\n        {\n            fp_vector_type fp_p2;\n            geometry::convert(p2, fp_p2);\n            return fp_p2;\n        }\n\n        // See above, c1 > 0 AND c2 > c1 so: c2 != 0\n        CalculationType const b = c1 / c2;\n\n        multiply_value(v, b);\n        add_point(projected, v);\n\n        return projected;\n    }\n};\n\n}\n#endif // DOXYGEN_NO_DETAIL\n\ntemplate\n<\n    typename CalculationType = void\n>\nclass projected_point\n{\npublic:\n    // The three typedefs below are necessary to calculate distances\n    // from segments defined in integer coordinates.\n\n    // Integer coordinates can still result in FP distances.\n    // There is a division, which must be represented in FP.\n    // So promote.\n\n    template <typename Point, typename PointOfSegment>\n    struct calculation_type\n        : promote_floating_point\n          <\n            typename select_most_precise\n                <\n                    typename coordinate_type<Point>::type,\n                    typename coordinate_type<PointOfSegment>::type,\n                    CalculationType\n                >::type\n          >\n    {};\n\n    template <typename Point, typename PointOfSegment>\n    inline auto\n    apply(Point const& p, PointOfSegment const& p1, PointOfSegment const& p2) const\n    {\n        assert_dimension_equal<Point, PointOfSegment>();\n\n        using calculation_type = typename calculation_type<Point, PointOfSegment>::type;\n        \n        return detail::compute_closest_point_to_segment<calculation_type>::apply(p, p1, p2);\n    }\n\n};\n\n}} // namespace strategy::closest_points\n\n\n}} // namespace boost::geometry\n\n\n#endif // BOOST_GEOMETRY_STRATEGIES_CARTESIAN_CLOSEST_POINTS_PT_SEG_HPP\n", "meta": {"hexsha": "b3541c8798cf833be73df452609020cd20d0361a", "size": 4052, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "AqooleEngine/src/main/cpp/boost/boost/geometry/strategies/cartesian/closest_points_pt_seg.hpp", "max_stars_repo_name": "kodai731/Aqoole-Engine-Android-Vulkan-Rendering-Engine-", "max_stars_repo_head_hexsha": "72c8f34b6b6d507319069e681ff8c5008337b7c6", "max_stars_repo_licenses": ["Apache-2.0", "MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AqooleEngine/src/main/cpp/boost/boost/geometry/strategies/cartesian/closest_points_pt_seg.hpp", "max_issues_repo_name": "kodai731/Aqoole-Engine-Android-Vulkan-Rendering-Engine-", "max_issues_repo_head_hexsha": "72c8f34b6b6d507319069e681ff8c5008337b7c6", "max_issues_repo_licenses": ["Apache-2.0", "MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AqooleEngine/src/main/cpp/boost/boost/geometry/strategies/cartesian/closest_points_pt_seg.hpp", "max_forks_repo_name": "kodai731/Aqoole-Engine-Android-Vulkan-Rendering-Engine-", "max_forks_repo_head_hexsha": "72c8f34b6b6d507319069e681ff8c5008337b7c6", "max_forks_repo_licenses": ["Apache-2.0", "MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.9448275862, "max_line_length": 92, "alphanum_fraction": 0.6354886476, "num_tokens": 931, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.48691107347101736}}
{"text": "#include \"stdafx.h\"\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n#include <fmt/format.h>\n#include \"contest_types.h\"\n#include \"solver_registry.h\"\n#include \"visual_editor.h\"\n\nnamespace SimpleMatchingSolver {\n\nconstexpr int kNumTrialsPerComponent = 1000000;\nconstexpr int kMinComponentSize = 10;\nconstexpr int kMinDegree = 2;\nconstexpr bool kPruneLeavesOnly = true;\n\nnamespace bg = boost::geometry;\nusing BoostPoint = bg::model::d2::point_xy<double>;\nusing BoostPolygon = bg::model::polygon<BoostPoint>;\nusing BoostLinestring = bg::model::linestring<BoostPoint>;\n\ntemplate <typename T>\nBoostPoint ToBoostPoint(const T& point) {\n  const auto [x, y] = point;\n  return BoostPoint(x, y);\n}\n\ntemplate <typename T>\nBoostPolygon ToBoostPolygon(const std::vector<T>& points) {\n  BoostPolygon polygon;\n  for (std::size_t i = 0; i <= points.size(); ++i) {\n    polygon.outer().push_back(ToBoostPoint(points[i % points.size()]));\n  }\n  if (bg::area(polygon) < 0.0) {\n    bg::reverse(polygon);\n  }\n  return polygon;\n}\n\ntemplate <typename T, typename U>\nauto SquaredDistance(const T& vertex0, const U& vertex1) {\n  const auto [x0, y0] = vertex0;\n  const auto [x1, y1] = vertex1;\n  return (x0 - x1) * (x0 - x1) + (y0 - y1) * (y0 - y1);\n}\n\nclass Solver : public SolverBase {\n public:\n  SolverOutputs solve(const SolverArguments& args) override {\n    counter_ = 0;\n    if (args.visualize) {\n      editor_ = std::make_shared<SVisualEditor>(args.problem, \"SimpleMatchingSolver\", \"visualize\");\n    }\n\n    hole_ = args.problem->hole_polygon;\n    vertices_ = args.problem->vertices;\n    edges_ = args.problem->edges;\n    epsilon_ = args.problem->epsilon;\n    const auto hole_polygon = ToBoostPolygon(hole_);\n\n    N_ = vertices_.size();\n    queued_.assign(N_, -1);\n    assigned_.assign(N_, -1);\n    adjacent_.assign(N_, {});\n    std::vector<std::vector<double>> distances(\n        N_, std::vector<double>(N_, std::numeric_limits<double>::infinity()));\n    for (int i = 0; i < N_; ++i) {\n      distances[i][i] = 0.0;\n    }\n    for (const auto& [a, b] : edges_) {\n      const auto squared_distance = SquaredDistance(vertices_[a], vertices_[b]);\n      const auto margin = epsilon_ * squared_distance / 1'000'000;\n      const auto min = squared_distance - margin;\n      const auto max = squared_distance + margin;\n      adjacent_[a].emplace_back(b, min, max);\n      adjacent_[b].emplace_back(a, min, max);\n      distances[a][b] = distances[b][a] = std::sqrt(squared_distance) * (1.0 + 1.0e-6 * epsilon_);\n    }\n    for (int k = 0; k < N_; ++k) {\n      for (int i = 0; i < N_; ++i) {\n        for (int j = 0; j < N_; ++j) {\n          distances[i][j] = std::min(distances[i][j], distances[i][k] + distances[k][j]);\n        }\n      }\n    }\n    vertex_max_distances_.resize(N_);\n    for (int i = 0; i < N_; ++i) {\n      vertex_max_distances_[i].resize(N_);\n      for (int j = 0; j < N_; ++j) {\n        vertex_max_distances_[i][j] = std::ceil(std::pow(distances[i][j], 2.0));\n      }\n    }\n\n    M_ = hole_.size();\n    hole_candidates_.clear();\n    hole_distances_.resize(M_);\n    hole_visibilities_.resize(M_);\n    for (int i = 0; i < M_; ++i) {\n      hole_candidates_.push_back(i);\n      hole_distances_[i].resize(M_);\n      hole_visibilities_[i].resize(M_);\n      for (int j = 0; j < M_; ++j) {\n        const BoostLinestring linestring{ToBoostPoint(hole_[i]), ToBoostPoint(hole_[j])};\n        hole_visibilities_[i][j] = bg::covered_by(linestring, hole_polygon);\n        hole_distances_[i][j] = SquaredDistance(hole_[i], hole_[j]);\n      }\n    }\n\n    last_updated_ = 0;\n    component_sizes_.assign(M_, M_);\n    best_sizes_.assign(M_, 0);\n    bool found = false;\n    for (int i = 0; i < N_; ++i) {\n      queued_[i] = N_;\n      vertex_candidates_.push_back(i);\n      assigned_counts_.assign(1, 0);\n      if (Search()) {\n        found = true;\n        break;\n      }\n      vertex_candidates_.pop_back();\n      queued_[i] = -1;\n    }\n\n    SolverOutputs outputs;\n    if (found) {\n      auto pose = vertices_;\n      const auto assigned_vertices = kPruneLeavesOnly ? CleanupLeaves() : Cleanup();\n      for (const int vertex : assigned_vertices) {\n        pose[vertex] = hole_[assigned_[vertex]];\n      }\n      outputs.solution = args.problem->create_solution(pose);\n    } else {\n      outputs.solution = args.problem->create_solution();\n    }\n    return outputs;\n  }\n\n  std::set<int> Cleanup() const {\n    std::set<int> assigned_vertices;\n    for (int i = 0; i < N_; ++i) {\n      if (assigned_[i] < 0) continue;\n      assigned_vertices.insert(i);\n    }\n    while (true) {\n      bool converged = true;\n      for (int i = 0; i < N_; ++i) {\n        if (!assigned_vertices.count(i)) continue;\n        int degree = 0;\n        for (const auto& [next, min, max] : adjacent_[i]) {\n          degree += assigned_vertices.count(next);\n        }\n        if (degree < kMinDegree) {\n          converged = false;\n          assigned_vertices.erase(i);\n        }\n      }\n      if (converged) break;\n    }\n    return assigned_vertices;\n  }\n\n  std::set<int> CleanupLeaves() const {\n    std::set<int> assigned_vertices;\n    for (int i = 0; i < N_; ++i) {\n      if (assigned_[i] < 0) continue;\n      assigned_vertices.insert(i);\n    }\n    for (int i = 0; i < N_; ++i) {\n      if (assigned_[i] < 0) continue;\n      int degree = 0;\n      for (const auto& [next, min, max] : adjacent_[i]) {\n        degree += assigned_[next] >= 0;\n      }\n      if (degree < kMinDegree) {\n        assigned_vertices.erase(i);\n      }\n    }\n    return assigned_vertices;\n  }\n\n  bool Search() {\n    if (hole_candidates_.empty()) return true;\n    if (++counter_ % 10000 == 0 && editor_) {\n      auto pose = vertices_;\n      std::vector<int> marked;\n      for (int j = 0; j < N_; ++j) {\n        if (assigned_[j] < 0) continue;\n        pose[j] = hole_[assigned_[j]];\n        marked.push_back(j);\n      }\n      editor_->set_pose(std::make_shared<SSolution>(pose));\n      editor_->set_marked_indices(marked);\n      editor_->set_persistent_custom_stat(fmt::format(\"assigned counts = {}\", fmt::join(assigned_counts_, \", \")));\n      editor_->show(1);\n    }\n    const int component_index = assigned_counts_.size() - 1;\n    best_sizes_[component_index] = std::max(best_sizes_[component_index], assigned_counts_[component_index]);\n    if (counter_ > last_updated_ + kNumTrialsPerComponent) {\n      last_updated_ = counter_;\n      component_sizes_[component_index] = best_sizes_[component_index];\n      if (component_sizes_[component_index] < kMinComponentSize) return true;\n    }\n    for (int i = vertex_candidates_.size() - 1; i >= 0; --i) {\n      const int vertex = vertex_candidates_[i];\n      vertex_candidates_.erase(vertex_candidates_.begin() + i);\n      for (int j = hole_candidates_.size() - 1; j >= 0; --j) {\n        const int hole_vertex = hole_candidates_[j];\n        bool feasible = true;\n        for (const auto& [next, min, max] : adjacent_[vertex]) {\n          if (assigned_[next] < 0) continue;\n          const auto squared_distance = hole_distances_[assigned_[next]][hole_vertex];\n          const auto visible = hole_visibilities_[assigned_[next]][hole_vertex];\n          if (!visible || squared_distance < min || squared_distance > max) {\n            feasible = false;\n            break;\n          }\n        }\n        for (int other = 0; feasible && other < N_; ++other) {\n          if (assigned_[other] < 0) continue;\n          if (hole_distances_[assigned_[other]][hole_vertex] > vertex_max_distances_[other][vertex]) {\n            feasible = false;\n          }\n        }\n        if (feasible) {\n          hole_candidates_.erase(hole_candidates_.begin() + j);\n          assigned_[vertex] = hole_vertex;\n          ++assigned_counts_.back();\n          for (const auto& [next, min, max] : adjacent_[vertex]) {\n            if (queued_[next] >= 0) continue;\n            queued_[next] = vertex;\n            vertex_candidates_.push_back(next);\n          }\n          if (Search()) return true;\n          for (const auto& [next, min, max] : adjacent_[vertex]) {\n            if (queued_[next] != vertex) continue;\n            queued_[next] = -1;\n            vertex_candidates_.pop_back();\n          }\n          --assigned_counts_.back();\n          assigned_[vertex] = -1;\n          hole_candidates_.insert(hole_candidates_.begin() + j, hole_vertex);\n        }\n      }\n      vertex_candidates_.insert(vertex_candidates_.begin() + i, vertex);\n    }\n    if (assigned_counts_.back() >= component_sizes_[component_index]) {\n      if (assigned_counts_.size() == component_sizes_.size()) return true;\n      for (int i = 0; i < N_; ++i) {\n        if (queued_[i] >= 0) continue;\n        queued_[i] = N_;\n        vertex_candidates_.push_back(i);\n        assigned_counts_.push_back(0);\n        if (Search()) return true;\n        assigned_counts_.pop_back();\n        vertex_candidates_.pop_back();\n        queued_[i] = -1;\n      }\n    }\n    return false;\n  }\n\n private:\n  std::vector<Point> hole_;\n  std::vector<Point> vertices_;\n  std::vector<Edge> edges_;\n  integer epsilon_;\n\n  int N_;\n  int M_;\n  std::vector<int> queued_;\n  std::vector<int> assigned_;\n  std::vector<int> vertex_candidates_;\n  std::vector<int> hole_candidates_;\n  std::vector<std::vector<std::tuple<int, integer, integer>>> adjacent_;\n  std::vector<std::vector<integer>> hole_distances_;\n  std::vector<std::vector<bool>> hole_visibilities_;\n  std::vector<std::vector<integer>> vertex_max_distances_;\n  std::vector<int> assigned_counts_;\n  std::vector<int> component_sizes_;\n  std::vector<int> best_sizes_;\n  std::size_t last_updated_;\n  std::size_t counter_;\n  SVisualEditorPtr editor_;\n};\n\n}\n\nREGISTER_SOLVER(\"SimpleMatchingSolver\", SimpleMatchingSolver::Solver);\n// vim:ts=2 sw=2 sts=2 et ci\n", "meta": {"hexsha": "b73f848e3ecbb7b56790c0257742c29eb50eaac3", "size": 9749, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/solvers/simple_matching_solver.cpp", "max_stars_repo_name": "nodchip/icfpc2021", "max_stars_repo_head_hexsha": "e50f0172fd62097049dab19c01875c57468a13f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-12T13:52:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-12T13:52:18.000Z", "max_issues_repo_path": "src/solvers/simple_matching_solver.cpp", "max_issues_repo_name": "nodchip/icfpc2021", "max_issues_repo_head_hexsha": "e50f0172fd62097049dab19c01875c57468a13f1", "max_issues_repo_licenses": ["MIT"], "max_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/simple_matching_solver.cpp", "max_forks_repo_name": "nodchip/icfpc2021", "max_forks_repo_head_hexsha": "e50f0172fd62097049dab19c01875c57468a13f1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-24T08:49:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-24T08:49:18.000Z", "avg_line_length": 33.5017182131, "max_line_length": 114, "alphanum_fraction": 0.6131910965, "num_tokens": 2612, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118111485245, "lm_q2_score": 0.5888891307678319, "lm_q1q2_score": 0.4868415998627546}}
{"text": "#ifndef EIGENGWAS_HPP_\n#define EIGENGWAS_HPP_\n\n#include \"time.h\"\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#include \"genotype.h\"\n#include \"Goptions.hpp\"\n#include \"global.h\"\n\nusing namespace std;\n\nextern Goptions goptions;\nextern genotype g;\ntypedef Matrix<double, Dynamic, Dynamic, RowMajor> MatrixXdr;\n\nclass EigenGWAS {\n    public:\n    EigenGWAS() {\n\n    }\n\n    void Scan(MatrixXdr IndEigenVec) {\n    \tclock_t eg_begin = clock();\n\t    cout << \"---------------EigenGWAS scan-------------\" << endl;\n\t    cout << \"SNP number: \" << g.Nsnp << endl;\n\t    cout << \"Sample size: \" << g.Nindv << endl;\n\n    \tcout << \"Eigenvector number: \" << IndEigenVec.cols() <<endl;\n\n\t    MatrixXdr evePS(IndEigenVec.rows(), IndEigenVec.cols());\n\t    cout << \"Standardization eigenvec\" << endl;\n\t    for (int i = 0; i < evePS.cols(); i++) {\n\t\t    double sum = 0, sd = 0, eSq = 0, m = 0;\n\t\t    for (int j = 0; j < evePS.rows(); j++) {\n\t\t\t    sum += IndEigenVec(j, i);\n\t\t\t    eSq += IndEigenVec(j, i) * IndEigenVec(j, i);\n\t\t    }\n\t\t    m = sum / IndEigenVec.rows();\n\t\t    sd = sqrt((eSq - m * m * IndEigenVec.rows()) / (IndEigenVec.rows() - 1));\n\t\t    for (int j = 0; j < IndEigenVec.rows(); j++) {\n\t\t\t    evePS(j, i) = (IndEigenVec(j, i) - m) / sd;\n\t\t    }\n\t    }\n\n\t//using mailman\n\t    MatrixXdr EgBeta(g.Nsnp, IndEigenVec.cols());\n\t    multiply_y_pre(evePS, evePS.cols(), EgBeta, true);\n\n    \tEgBeta = EgBeta / g.Nindv;\n\t    for (int i = 0; i < EgBeta.cols(); i++) {\n\t\t    cout << EgBeta(0, i) <<endl;\n\t    }\n\n    \tusing boost::math::students_t;\n\t    students_t Tdist(g.Nindv - 1);\n\n    \tfor (int i = 0; i < EgBeta.cols(); i++) {\n\t\t\tcout << \"Scanning eigenvector \" << i + 1 << endl;\n\t\t\tofstream e_file;\n\t\t\te_file.open((goptions.GetGenericOutFile() + string(\"eg.\"+std::to_string(i+1)+\".txt\")).c_str());\n\t\t\te_file << \"CHR\\tSNP\\tPOS\\tBP\\tA1\\tA2\\tBeta\\tSE\\tT-stat\\tP\" << endl;\n\t\t\tfor (int j = 0; j <EgBeta.rows(); j++) {\n\t\t\t    double seB = sqrt((1 - pow(EgBeta(j, i), 2))/(g.Nindv - 1));\n\t\t\t    double t_stat = EgBeta(j, i) / seB;\n\t\t\t\tif (goptions.IsGenericDebug()) {\n\t\t\t\t    cout << \"MK: \" << j << \" infor=\" << g.get_bim_info(j) << \" egB=\" << EgBeta(j, i) << \" seB=\" << seB << \" t=\" << t_stat << endl;\n\t\t\t\t}\n\t\t\t    double pt2tail = cdf(complement(Tdist, fabs(t_stat))) * 2;\n\t\t\t    e_file << g.get_bim_info(j) << \"\\t\" << std::setprecision(8) << EgBeta(j, i) << \"\\t\" << seB << \"\\t\" << t_stat << \"\\t\" << pt2tail <<endl;\n\t\t    }\n    \t\te_file.close();\n\t    }\n\n    \tclock_t eg_end = clock();\n\t    double eg_time = double(eg_end - eg_begin) / CLOCKS_PER_SEC;\n\t    cout << \"EigenGWAS total time \" << eg_time << endl;\n    }\n};\n\n#endif\n\n\n/*\nvoid EigenGWAS(MatrixXdr IndEigenVec) {\n\n\tclock_t eg_begin = clock();\n\tcout << \"---------------EigenGWAS scan-------------\" << endl;\n\tcout << \"SNP number: \" << g.Nsnp << endl;\n\tcout << \"Sample size: \" << g.Nindv << endl;\n\n\tcout << \"Eigenvector number: \" << IndEigenVec.cols() <<endl;\n\n\tMatrixXdr evePS(IndEigenVec.rows(), IndEigenVec.cols());\n\tcout << \"Standardization eigenvec\" << endl;\n\tfor (int i = 0; i < evePS.cols(); i++) {\n\t\tdouble sum = 0, sd = 0, eSq = 0, m = 0;\n\t\tfor (int j = 0; j < evePS.rows(); j++) {\n\t\t\tsum += IndEigenVec(j, i);\n\t\t\teSq += IndEigenVec(j, i) * IndEigenVec(j, i);\n\t\t}\n\t\tm = sum / IndEigenVec.rows();\n\t\tsd = sqrt((eSq - m * m * IndEigenVec.rows()) / (IndEigenVec.rows() - 1));\n\t\tfor (int j = 0; j < IndEigenVec.rows(); j++) {\n\t\t\tevePS(j, i) = (IndEigenVec(j, i) - m) / sd;\n\t\t}\n\t}\n\n\t//using mailman\n\tMatrixXdr EgBeta(g.Nsnp, IndEigenVec.cols());\n\tmultiply_y_pre(evePS, evePS.cols(), EgBeta, true);\n\n\tEgBeta = EgBeta / g.Nindv;\n\tfor (int i = 0; i < EgBeta.cols(); i++) {\n\t\tcout << EgBeta(0, i) <<endl;\n\t}\n\n\tusing boost::math::students_t;\n\tstudents_t Tdist(g.Nindv - 1);\n\n\tfor (int i = 0; i < EgBeta.cols(); i++) {\n\t\tcout << \"Scanning eigenvector \" << i + 1 << endl;\n\t\tofstream e_file;\n\t\te_file.open((goptions.GetGenericOutFile() + string(\"eg.\"+std::to_string(i+1)+\".txt\")).c_str());\n\t\te_file << \"CHR\\tSNP\\tPOS\\tBP\\tA1\\tA2\\tBeta\\tSE\\tT-stat\\tP\" << endl;\n\t\tfor (int j = 0; j <EgBeta.rows(); j++) {\n\t\t\tdouble seB = sqrt((1 - pow(EgBeta(j, i), 2))/(g.Nindv - 1));\n\t\t\tdouble t_stat = EgBeta(j, i) / seB;\n\t\t\tcout << \"MK: \" << j << \" infor=\" << g.get_bim_info(j) << \" egB=\" << EgBeta(j, i) << \" seB=\" << seB << \" t=\" << t_stat << endl;\n\t\t\tdouble pt2tail = cdf(complement(Tdist, fabs(t_stat))) * 2;\n\t\t\te_file << g.get_bim_info(j) << \"\\t\" << std::setprecision(8) << EgBeta(j, i) << \"\\t\" << seB << \"\\t\" << t_stat << \"\\t\" << pt2tail <<endl;\n\t\t}\n\t\te_file.close();\n\t}\n\n\tclock_t eg_end = clock();\n\tdouble eg_time = double(eg_end - eg_begin) / CLOCKS_PER_SEC;\n\tcout << \"EigenGWAS total time \" << eg_time << endl;\n}\n*/\n", "meta": {"hexsha": "b3e08e7d2375841523713e795da6021d6f856ab2", "size": 4797, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/EigenGWAS.hpp", "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": "include/EigenGWAS.hpp", "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": "include/EigenGWAS.hpp", "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": 32.4121621622, "max_line_length": 142, "alphanum_fraction": 0.5651448822, "num_tokens": 1629, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4868415948342743}}
{"text": "#include \"compi.hpp\"\n\n#include <limits>\n\n#include <boost/math/quadrature/trapezoidal.hpp>\n\nextern \"C\" {\n    #include \"integration_routines.h\"\n}\n#include \"integration_routines_template.hpp\"\n#include \"IntegrandFunctionWrapper.hpp\"\n\nstruct TrapezoidParamerters: public RoutineParametersBase {\n    Real x_min, x_max;\n\n    TrapezoidParamerters(PyObject* routine_args, PyObject* routine_kwargs):RoutineParametersBase{std::numeric_limits<Real>::epsilon(),12}{\n        constexpr auto keywords = generate_keyword_list<IntegralRange::finite>();\n\n\n        if(!PyArg_ParseTupleAndKeywords(routine_args,routine_kwargs,\"Odd|OO$pId\",const_cast<char**>(keywords.data()),\n                &integrand,&x_min,&x_max,\n                &args,&kw,\n                &full_output, &max_levels,&tolerance)){\n            throw could_not_parse_arguments(\"Unable to parse python arguments to C variables\");\n        }\n    }\n};\n\nTrapezoidParamerters::result_type run_integration_routine(const compi_internal::IntegrandFunctionWrapper& f, const TrapezoidParamerters& params){\n    TrapezoidParamerters::result_type result;\n\n    result.result = boost::math::quadrature::trapezoidal(f,params.x_min, params.x_max,params.tolerance,params.max_levels, &(result.err),&(result.l1));\n\n    return result;\n}\n\ntemplate<>\nPyObject* generate_full_output_dict(const TrapezoidParamerters::result_type& result,const TrapezoidParamerters& params)noexcept{\n    return Py_BuildValue(\"{sd}\", \"L1 norm\", result.l1);\n}\n\nextern \"C\" PyObject* trapezoidal(PyObject* self, PyObject* args, PyObject* kwargs){\n    return integration_routine<TrapezoidParamerters>(args,kwargs);\n}", "meta": {"hexsha": "64825e8cf0514eb0d87657e0d0bf5ef42021387b", "size": 1614, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/trapezoid.cpp", "max_stars_repo_name": "CGJackson/Compi", "max_stars_repo_head_hexsha": "9fe2a316e9dbe54b01ee274417a07a13f4f990b0", "max_stars_repo_licenses": ["MIT"], "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/trapezoid.cpp", "max_issues_repo_name": "CGJackson/Compi", "max_issues_repo_head_hexsha": "9fe2a316e9dbe54b01ee274417a07a13f4f990b0", "max_issues_repo_licenses": ["MIT"], "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/trapezoid.cpp", "max_forks_repo_name": "CGJackson/Compi", "max_forks_repo_head_hexsha": "9fe2a316e9dbe54b01ee274417a07a13f4f990b0", "max_forks_repo_licenses": ["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.6818181818, "max_line_length": 150, "alphanum_fraction": 0.7422552664, "num_tokens": 389, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4868415898057938}}
{"text": "//  Copyright John Maddock 2017.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n//\n\n#ifndef BOOST_MATH_STANDALONE\n\n#include <boost/math/concepts/std_real_concept.hpp>\n#include <boost/math/interpolators/barycentric_rational.hpp>\n\nvoid compile_and_link_test()\n{\n   boost::math::concepts::std_real_concept x[] = { 1, 2, 3 };\n   boost::math::concepts::std_real_concept y[] = { 13, 15, 17 };\n   boost::math::interpolators::barycentric_rational<boost::math::concepts::std_real_concept> s(x, y, 3, 3);\n   s(1.0);\n}\n\n#endif\n", "meta": {"hexsha": "81850e232f631ecd686388541bb7a415809e6661", "size": 660, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/compile_test/interpolators_barycentric_rational_concept_test.cpp", "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": "test/compile_test/interpolators_barycentric_rational_concept_test.cpp", "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": "test/compile_test/interpolators_barycentric_rational_concept_test.cpp", "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": 31.4285714286, "max_line_length": 107, "alphanum_fraction": 0.7272727273, "num_tokens": 204, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4868415898057938}}
{"text": "/*\n * Copyright 2019 Forschungszentrum Juelich GmbH\n * Copyright 2009-2019 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 *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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#define BOOST_TEST_MAIN\n\n#define BOOST_TEST_MODULE linalg_test\n\n// Third party includes\n#include <boost/test/unit_test.hpp>\n\n// Local private VOTCA includes\n#include \"kokkos_linalg.hpp\"\n\nBOOST_AUTO_TEST_SUITE(linalg_test)\n\nBOOST_AUTO_TEST_CASE(cross) {\n  Kokkos::initialize();\n  {\n    Kokkos::View<double[3]> a(\"a\");\n    a(0) = -1;\n    a(1) = 7;\n    a(2) = 4;\n    Kokkos::View<double[3]> b(\"b\");\n    b(0) = -5;\n    b(1) = 8;\n    b(2) = 4;\n\n    auto result = kokkos_linalg_3d::cross(a, b);\n    BOOST_CHECK_CLOSE(result[0], -4, 1e-9);\n    BOOST_CHECK_CLOSE(result[1], -16, 1e-9);\n    BOOST_CHECK_CLOSE(result[2], 27, 1e-9);\n  }\n  Kokkos::finalize();\n}\n\nBOOST_AUTO_TEST_CASE(dot) {\n  Kokkos::initialize();\n  {\n    Kokkos::View<double[3]> a(\"a\");\n    a(0) = -1;\n    a(1) = 7;\n    a(2) = 4;\n    Kokkos::View<double[3]> b(\"b\");\n    b(0) = -5;\n    b(1) = 8;\n    b(2) = 4;\n\n    auto result = kokkos_linalg_3d::dot(a, b);\n    BOOST_CHECK_CLOSE(result, 77, 1e-9);\n  }\n  Kokkos::finalize();\n}\n\nBOOST_AUTO_TEST_CASE(gemv) {\n  Kokkos::initialize();\n  {\n\n    Kokkos::View<double[3]> a(\"a\");\n    a(0) = 1;\n    a(1) = 2;\n    a(2) = 3;\n    Kokkos::View<double[9]> A(\"A\");\n    A(0) = 5;\n    A(1) = 1;\n    A(2) = 3;\n    A(3) = 1;\n    A(4) = 1;\n    A(5) = 1;\n    A(6) = 1;\n    A(7) = 2;\n    A(8) = 1;\n\n    auto result = kokkos_linalg_3d::gemv(A, a);\n    BOOST_CHECK_CLOSE(result[0], 16, 1e-9);\n    BOOST_CHECK_CLOSE(result[1], 6, 1e-9);\n    BOOST_CHECK_CLOSE(result[2], 8, 1e-9);\n  }\n  Kokkos::finalize();\n}\n\nBOOST_AUTO_TEST_CASE(norm) {\n  Kokkos::initialize();\n  {\n    Kokkos::View<double[3]> a(\"a\");\n    a(0) = -1;\n    a(1) = 7;\n    a(2) = 4;\n    auto result = kokkos_linalg_3d::norm(a);\n    BOOST_CHECK_CLOSE(result, std::sqrt(66), 1e-5);\n  }\n  Kokkos::finalize();\n}\n\nBOOST_AUTO_TEST_CASE(trace) {\n  Kokkos::initialize();\n  {\n    Kokkos::View<double[9]> A(\"A\");\n    A(0) = 5;\n    A(1) = 1;\n    A(2) = 3;\n    A(3) = 1;\n    A(4) = 1;\n    A(5) = 1;\n    A(6) = 1;\n    A(7) = 2;\n    A(8) = 1;\n\n    auto result = kokkos_linalg_3d::trace(A);\n    BOOST_CHECK_CLOSE(result, 7, 1e-9);\n  }\n  Kokkos::finalize();\n}\n\nBOOST_AUTO_TEST_CASE(cross_matrix_product) {\n  Kokkos::initialize();\n  {\n    Kokkos::View<double[9]> A(\"A\");\n    A(0) = 5;\n    A(1) = 1;\n    A(2) = 3;\n    A(3) = 1;\n    A(4) = 1;\n    A(5) = 1;\n    A(6) = 1;\n    A(7) = 2;\n    A(8) = 1;\n\n    Kokkos::View<double[9]> B(\"B\");\n    B(0) = -1;\n    B(1) = 1;\n    B(2) = 3;\n    B(3) = 1;\n    B(4) = 1;\n    B(5) = 1;\n    B(6) = 1;\n    B(7) = 2;\n    B(8) = 1;\n    auto result = kokkos_linalg_3d::cross_matrix_product(A, B);\n    BOOST_CHECK_CLOSE(result[0], 0, 1e-9);\n    BOOST_CHECK_CLOSE(result[1], -6, 1e-9);\n    BOOST_CHECK_CLOSE(result[2], 6, 1e-9);\n  }\n  Kokkos::finalize();\n}\n\nBOOST_AUTO_TEST_CASE(scale_3d) {\n  Kokkos::initialize();\n  {\n    Kokkos::View<double[3]> v(\"v\");\n    v(0) = -1.2;\n    v(1) = 2.4;\n    v(2) = 1000.0;\n    double s = 0.25;\n\n    auto result = kokkos_linalg_3d::scale_3d(s, v);\n\n    BOOST_CHECK_CLOSE(result[0], -0.3, 1e-9);\n    BOOST_CHECK_CLOSE(result[1], 0.6, 1e-9);\n    BOOST_CHECK_CLOSE(result[2], 250.0, 1e-9);\n  }\n  Kokkos::finalize();\n}\n\nBOOST_AUTO_TEST_CASE(dualbase_3d) {\n  Kokkos::initialize();\n  {\n    Kokkos::View<double[3]> a(\"a\");\n    a(0) = 1.0;\n    a(1) = 1.0;\n    a(2) = 1.0;\n\n    Kokkos::View<double[3]> b(\"b\");\n    b(0) = -1.0;\n    b(1) = 1.0;\n    b(2) = 1.0;\n\n    Kokkos::View<double[3]> c(\"c\");\n    c(0) = 1.0;\n    c(1) = -1.0;\n    c(2) = 1.0;\n\n    auto result = kokkos_linalg_3d::dualbase_3d(a, b, c);\n\n    BOOST_CHECK_CLOSE(result[0][0], 0.5, 1e-9);\n    BOOST_CHECK_CLOSE(result[0][1], 0.5, 1e-9);\n    BOOST_CHECK_CLOSE(result[0][2], 0.0, 1e-9);\n\n    BOOST_CHECK_CLOSE(result[1][0], -0.5, 1e-9);\n    BOOST_CHECK_CLOSE(result[1][1], 0.0, 1e-9);\n    BOOST_CHECK_CLOSE(result[1][2], 0.5, 1e-9);\n\n    BOOST_CHECK_CLOSE(result[2][0], 0.0, 1e-9);\n    BOOST_CHECK_CLOSE(result[2][1], -0.5, 1e-9);\n    BOOST_CHECK_CLOSE(result[2][2], 0.5, 1e-9);\n  }\n  Kokkos::finalize();\n}\n\nBOOST_AUTO_TEST_CASE(add_to) {\n  Kokkos::initialize();\n  {\n    Kokkos::View<double[5]> a(\"a\");\n    a(0) = 1.2;\n    a(1) = -0.4;\n    a(2) = 3.7;\n    a(3) = -2.8;\n    a(4) = 0.6;\n    Kokkos::View<double[5]> b(\"b\");\n    b(0) = -1.2;\n    b(1) = 1.4;\n    b(2) = -4.7;\n    b(3) = 1.8;\n    b(4) = 1.0;\n    kokkos_linalg_3d::add_to(a, b);\n\n    BOOST_CHECK_CLOSE(a(0), 0.0, 1e-9);\n    BOOST_CHECK_CLOSE(a(1), 1.0, 1e-9);\n    BOOST_CHECK_CLOSE(a(2), -1.0, 1e-9);\n    BOOST_CHECK_CLOSE(a(3), -1.0, 1e-9);\n    BOOST_CHECK_CLOSE(a(4), 1.6, 1e-9);\n  }\n  Kokkos::finalize();\n}\n\nBOOST_AUTO_TEST_CASE(subtract_from) {\n  Kokkos::initialize();\n  {\n    Kokkos::View<double[5]> a(\"a\");\n    a(0) = 1.2;\n    a(1) = -0.4;\n    a(2) = 3.7;\n    a(3) = -2.8;\n    a(4) = 0.6;\n    Kokkos::View<double[5]> b(\"b\");\n    b(0) = -1.2;\n    b(1) = 1.4;\n    b(2) = -4.7;\n    b(3) = 1.8;\n    b(4) = 1.0;\n    kokkos_linalg_3d::subtract_from(a, b);\n\n    BOOST_CHECK_CLOSE(a(0), 2.4, 1e-9);\n    BOOST_CHECK_CLOSE(a(1), -1.8, 1e-9);\n    BOOST_CHECK_CLOSE(a(2), 8.4, 1e-9);\n    BOOST_CHECK_CLOSE(a(3), -4.6, 1e-9);\n    BOOST_CHECK_CLOSE(a(4), -0.4, 1e-9);\n  }\n  Kokkos::finalize();\n}\n\nBOOST_AUTO_TEST_CASE(add) {\n  Kokkos::initialize();\n  {\n    Kokkos::View<double[3]> a(\"a\");\n    a(0) = 1.2;\n    a(1) = -0.4;\n    a(2) = 3.7;\n    Kokkos::View<double[3]> b(\"b\");\n    b(0) = -1.2;\n    b(1) = 1.4;\n    b(2) = -4.7;\n    auto result = kokkos_linalg_3d::add(a, b);\n\n    BOOST_CHECK_CLOSE(result[0], 0.0, 1e-9);\n    BOOST_CHECK_CLOSE(result[1], 1.0, 1e-9);\n    BOOST_CHECK_CLOSE(result[2], -1.0, 1e-9);\n  }\n  Kokkos::finalize();\n}\n\nBOOST_AUTO_TEST_CASE(subtract) {\n  Kokkos::initialize();\n  {\n    Kokkos::View<double[3]> a(\"a\");\n    a(0) = 1.2;\n    a(1) = -0.4;\n    a(2) = 3.7;\n    Kokkos::View<double[3]> b(\"b\");\n    b(0) = -1.2;\n    b(1) = 1.4;\n    b(2) = -4.7;\n    auto result = kokkos_linalg_3d::subtract(a, b);\n\n    BOOST_CHECK_CLOSE(result[0], 2.4, 1e-9);\n    BOOST_CHECK_CLOSE(result[1], -1.8, 1e-9);\n    BOOST_CHECK_CLOSE(result[2], 8.4, 1e-9);\n  }\n  Kokkos::finalize();\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "7739accd4663b78bd3151d83df3d52891be991d3", "size": 6651, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/QDMEwald/tests/test_linalg_3d.cpp", "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/QDMEwald/tests/test_linalg_3d.cpp", "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/QDMEwald/tests/test_linalg_3d.cpp", "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": 21.806557377, "max_line_length": 75, "alphanum_fraction": 0.551646369, "num_tokens": 2739, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4868415847773131}}
{"text": "// Copyright John Maddock 2016.\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//\n// This file takes way too long to run to be part of the main regression test suite,\n// but is useful in probing for errors in cpp_bin_float's rounding code.\n// It cycles through every single value of type float, and rounds those numbers\n// plus some closely related ones and compares the results to those produced by MPFR.\n//\n#ifdef _MSC_VER\n#define _SCL_SECURE_NO_WARNINGS\n#endif\n\n#include <boost/multiprecision/cpp_bin_float.hpp>\n#include <boost/multiprecision/mpfr.hpp>\n#include <boost/math/special_functions/next.hpp>\n#include \"test.hpp\"\n\nusing namespace boost::multiprecision;\n\ntypedef number<mpfr_float_backend<35> >                                                     good_type;\ntypedef number<cpp_bin_float<std::numeric_limits<good_type>::digits, digit_base_2>, et_off> test_type;\n\nint main()\n{\n   float f = (std::numeric_limits<float>::max)();\n\n   do\n   {\n      float     fr1, fr2;\n      good_type gf(f), gf2(f);\n      test_type tf(f), tf2(f);\n      fr1 = gf.convert_to<float>();\n      fr2 = tf.convert_to<float>();\n      BOOST_CHECK_EQUAL(fr1, fr2);\n      // next represenation:\n      gf = boost::math::float_next(gf2);\n      tf = boost::math::float_next(tf2);\n      BOOST_CHECK_NE(gf, gf2);\n      BOOST_CHECK_NE(tf, tf2);\n      fr1 = gf.convert_to<float>();\n      fr2 = tf.convert_to<float>();\n      BOOST_CHECK_EQUAL(fr1, fr2);\n      // previous representation:\n      gf = boost::math::float_prior(gf2);\n      tf = boost::math::float_prior(tf2);\n      BOOST_CHECK_NE(gf, gf2);\n      BOOST_CHECK_NE(tf, tf2);\n      fr1 = gf.convert_to<float>();\n      fr2 = tf.convert_to<float>();\n      BOOST_CHECK_EQUAL(fr1, fr2);\n\n      // Create ands test ties:\n      int e;\n      std::frexp(f, &e);\n      float extra = std::ldexp(1.0f, e - std::numeric_limits<float>::digits - 1);\n      gf          = gf2 += extra;\n      tf          = tf2 += extra;\n      fr1         = gf.convert_to<float>();\n      fr2         = tf.convert_to<float>();\n      BOOST_CHECK_EQUAL(fr1, fr2);\n      // next represenation:\n      gf = boost::math::float_next(gf2);\n      tf = boost::math::float_next(tf2);\n      BOOST_CHECK_NE(gf, gf2);\n      BOOST_CHECK_NE(tf, tf2);\n      fr1 = gf.convert_to<float>();\n      fr2 = tf.convert_to<float>();\n      BOOST_CHECK_EQUAL(fr1, fr2);\n      // previous representation:\n      gf = boost::math::float_prior(gf2);\n      tf = boost::math::float_prior(tf2);\n      BOOST_CHECK_NE(gf, gf2);\n      BOOST_CHECK_NE(tf, tf2);\n      fr1 = gf.convert_to<float>();\n      fr2 = tf.convert_to<float>();\n      BOOST_CHECK_EQUAL(fr1, fr2);\n\n      f = boost::math::float_prior(f);\n   } while (f);\n\n   return boost::report_errors();\n}\n", "meta": {"hexsha": "aaf7971a69c0fbd975313de5d951101bb0d6aa1a", "size": 2860, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/multiprecision/test/test_cpp_bin_float_round.cpp", "max_stars_repo_name": "uosorio/heroku_face", "max_stars_repo_head_hexsha": "7d6465e71dba17a15d8edaef520adb2fcd09d91e", "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": "3rdparty/boost_1_73_0/libs/multiprecision/test/test_cpp_bin_float_round.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 130.0, "max_issues_repo_issues_event_min_datetime": "2016-06-22T22:11:25.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-29T20:24:09.000Z", "max_forks_repo_path": "Libs/boost_1_76_0/libs/multiprecision/test/test_cpp_bin_float_round.cpp", "max_forks_repo_name": "Antd23rus/S2DE", "max_forks_repo_head_hexsha": "47cc7151c2934cd8f0399a9856c1e54894571553", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2015-07-08T19:18:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-14T16:39:56.000Z", "avg_line_length": 32.5, "max_line_length": 102, "alphanum_fraction": 0.6286713287, "num_tokens": 746, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317473, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.48684158477731304}}
{"text": "#include <gtest/gtest.h>\n#include <Eigen/Geometry>\n#include <plucker/mat_relational.h>\n\nnamespace\n{\n\ntemplate<typename T>\nclass MatRelationalTest\n    : public ::testing::Test\n{\nprotected:\n    template<typename U = T>\n    static constexpr typename std::enable_if<std::is_same<U, float>::value, U>::type\n    absolute_tolerance(){ return 1e-4f; }\n\n    template<typename U = T>\n    static constexpr typename std::enable_if<std::is_same<U, double>::value, U>::type\n    absolute_tolerance(){ return 1e-8; }\n\n    template<typename U = T>\n    static constexpr typename std::enable_if<std::is_same<U, float>::value, U>::type\n    relative_tolerance(){ return 1e-5f; }\n\n    template<typename U = T>\n    static constexpr typename std::enable_if<std::is_same<U, double>::value, U>::type\n    relative_tolerance(){ return 1e-5; }\n};\n\nusing MyTypes = ::testing::Types<float, double>;\nTYPED_TEST_SUITE(MatRelationalTest, MyTypes);\n\nTYPED_TEST(MatRelationalTest, almost_equal)\n{\n    using Matrix1 = Eigen::Matrix<TypeParam, 1, 1>;\n\n    constexpr auto atol = MatRelationalTest<TypeParam>::absolute_tolerance();\n\n    {\n        constexpr auto val1 = atol;\n        constexpr auto val2 = TypeParam(0);\n        const auto s1 = Matrix1(val1);\n        const auto s2 = Matrix1(val2);\n\n        EXPECT_TRUE(plucker::detail::almost_equal(s1, s2, atol));\n        EXPECT_TRUE(plucker::detail::almost_equal(s2, s1, atol));\n    }\n    {\n        constexpr auto val1 = 10 * atol;\n        constexpr auto val2 = TypeParam(0);\n        const auto s1 = Matrix1(val1);\n        const auto s2 = Matrix1(val2);\n\n        EXPECT_FALSE(plucker::detail::almost_equal(s1, s2, atol));\n        EXPECT_FALSE(plucker::detail::almost_equal(s2, s1, atol));\n    }\n    {\n        constexpr auto val1 = TypeParam(1000);\n        constexpr auto val2 = TypeParam(999);\n        const auto s1 = Matrix1(val1);\n        const auto s2 = Matrix1(val2);\n\n        EXPECT_FALSE(plucker::detail::almost_equal(s1, s2, TypeParam(1e-5)));\n        EXPECT_TRUE(plucker::detail::almost_equal(s1, s2, TypeParam(1e-3)));\n        EXPECT_TRUE(plucker::detail::almost_equal(s1, s2, TypeParam(1e-3), TypeParam(1e-5)));\n    }\n}\n\nTYPED_TEST(MatRelationalTest, almost_zero)\n{\n    using Matrix1 = Eigen::Matrix<TypeParam, 1, 1>;\n\n    constexpr auto atol = MatRelationalTest<TypeParam>::absolute_tolerance();\n\n    {\n        constexpr auto val = atol;\n        const auto s = Matrix1(val);\n\n        EXPECT_TRUE(plucker::detail::almost_zero(s, atol));\n    }\n    {\n        constexpr auto val = 10 * atol;\n        const auto s = Matrix1(val);\n\n        EXPECT_FALSE(plucker::detail::almost_zero(s, atol));\n    }\n}\n\n}   // namespace\n", "meta": {"hexsha": "f56e7fe3f70e948f8de2fb844ff24a96bd2aaca5", "size": 2635, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_mat_relational.cpp", "max_stars_repo_name": "Hasenpfote/plucker", "max_stars_repo_head_hexsha": "bd0ea026d601e7556f4b2388a24fc4fcb789bb2d", "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": "test/test_mat_relational.cpp", "max_issues_repo_name": "Hasenpfote/plucker", "max_issues_repo_head_hexsha": "bd0ea026d601e7556f4b2388a24fc4fcb789bb2d", "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": "test/test_mat_relational.cpp", "max_forks_repo_name": "Hasenpfote/plucker", "max_forks_repo_head_hexsha": "bd0ea026d601e7556f4b2388a24fc4fcb789bb2d", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-10-21T01:44:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T13:03:15.000Z", "avg_line_length": 29.2777777778, "max_line_length": 93, "alphanum_fraction": 0.6523719165, "num_tokens": 699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947425132315, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.48669682536961173}}
{"text": "#ifndef EMPIRICALCPP_SRC_MESH_HPP_\n#define EMPIRICALCPP_SRC_MESH_HPP_\n\n#include <empiricalcpp/src/constants.hpp>\n#include <empiricalcpp/src/quadrature.hpp>\n#include <array>\n#include <functional>\n#include <vector>\n#include <tuple>\n#include <boost/multi_array.hpp>\n\nnamespace empirical {\n    namespace mesh {\n\n        class Mesh1D {\n        public:\n            typedef std::vector<Scalar> vector_type;\n            typedef vector_type::size_type size_type;\n            typedef std::function<vector_type(const size_type, const Scalar, const Scalar)> generator_function;\n\n        protected:\n            Scalar minVal, maxVal;\n            vector_type points;\n            generator_function generator;\n\n            void recalculate(const size_type N, const Scalar min, const Scalar max) {\n                minVal = min;\n                maxVal = max;\n                points = generator(N, min, max);\n            }\n\n        public:\n            Mesh1D(generator_function generator, const size_type N, const Scalar min = -1, const Scalar max = 1)\n                : minVal(min), maxVal(max), points(1), generator(generator) {\n                recalculate(N, min, max);\n            }\n            Mesh1D(const Quadrature& quadrature);\n            Mesh1D(std::function<Scalar(size_type i, size_type N, Scalar a, Scalar b)> pointFunction,\n                const size_type N, const Scalar min = -1, const Scalar max = 1);\n\n            size_type size() const { return points.size(); }\n            Scalar min() const { return minVal; }\n            Scalar max() const { return maxVal; }\n\n            vector_type::iterator begin() { return points.begin(); }\n            vector_type::iterator end() { return points.end(); }\n            vector_type::const_iterator begin() const { return points.begin(); }\n            vector_type::const_iterator end() const { return points.end(); }\n\n            vector_type getPoints() { return points; }\n            const vector_type getPoints() const { return points; }\n\n            Scalar operator[](const size_type i) const { return points[i]; }\n            Scalar& operator[](const size_type i) { return points[i]; }\n\n            Scalar operator()(const size_type i) const { return points[i]; }\n            Scalar& operator()(const size_type i) { return points[i]; }\n\n            void resize(const size_type N, const Scalar min, const Scalar max) {\n                if (points.size() == N && min == minVal && max == maxVal) {\n                    return;\n                }\n                recalculate(N, min, max);\n            }\n\n            void resize(const size_type N) {\n                resize(N, minVal, maxVal);\n            }\n        };\n\n        class Mesh2D {\n        public:\n            typedef boost::multi_array<Scalar, 3> array_type;\n            typedef array_type::size_type size_type;\n            typedef std::array<size_type, 2> element_index_type;\n            typedef std::array<Scalar, 2> point_type;\n            typedef std::function<array_type*(const element_index_type, const point_type, const point_type)> generator_function;\n\n        protected:\n            point_type minVal, maxVal;\n            std::unique_ptr<array_type> points;\n            generator_function generator;\n\n            void recalculate(const element_index_type N, const point_type min, const point_type max);\n\n        public:\n            Mesh2D(generator_function generator, const element_index_type N, const point_type min, const point_type max)\n                : minVal(min), maxVal(max), generator(generator) {\n                recalculate(N, min, max);\n            }\n            Mesh2D(generator_function generator, const element_index_type N) : generator(generator) {\n                minVal[0] = minVal[1] = -1;\n                maxVal[0] = maxVal[1] = 1;\n                recalculate(N, minVal, maxVal);\n            }\n            Mesh2D(const Quadrature& xQuadrature, const Quadrature& yQuadrature);\n            Mesh2D(std::function<Scalar(size_type i, size_type N, Scalar a, Scalar b)> xFunction,\n                std::function<Scalar(size_type i, size_type N, Scalar a, Scalar b)> yFunction,\n                const element_index_type N, const point_type min, const point_type max);\n\n            size_type sizeX() const { return points->shape()[0]; }\n            size_type sizeY() const { return points->shape()[1]; }\n            point_type min() const { return minVal; }\n            point_type max() const { return maxVal; }\n\n            array_type::iterator begin();// { return points.begin(); }\n            array_type::iterator end();// { return points.end(); }\n            array_type::const_iterator begin() const;// { return points.begin(); }\n            array_type::const_iterator end() const;// { return points.end(); }\n\n            array_type getPoints() { return *points; }\n            const array_type getPoints() const { return *points; }\n\n            array_type::const_reference operator[](const size_type i) const { return (*points)[i]; }\n            array_type::reference operator[](const size_type i) { return (*points)[i]; }\n\n            point_type operator()(const size_type i, const size_type j) const { return{ { (*points)[i][j][0], (*points)[i][j][1] } }; }\n\n            void resize(const element_index_type N, const point_type min, const point_type max) {\n                if (points->shape()[0] == N[0] && points->shape()[1] == N[1] &&\n                    min[0] == minVal[0] && min[1] == minVal[1] &&\n                    max[0] == maxVal[0] && max[1] == maxVal[1]) {\n                    return;\n                }\n                recalculate(N, min, max);\n            }\n\n            void resize(const element_index_type N) {\n                resize(N, minVal, maxVal);\n            }\n        };\n        \n#ifndef EMPIRICAL_NO_OSTREAM_DEFINITIONS\n        inline std::ostream& operator<<(std::ostream& os, const Mesh1D& mesh) {\n            os << \"Mesh1D {\";\n            os << std::fixed << std::setw(11) << std::setprecision(6);\n            for (Scalar val : mesh) {\n                os << val << \", \";\n            }\n            return os << \"}\";\n        }\n        std::ostream& operator<<(std::ostream& os, const Mesh2D& mesh);\n#endif\n    }\n\n    typedef mesh::Mesh1D Mesh1D;\n}\n\n#endif /* EMPIRICALCPP_SRC_MESH_HPP_ */\n", "meta": {"hexsha": "8747d42e1b8f1a693bff2f8bd661297f2a7139cc", "size": 6236, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "empirical/include/empiricalcpp/src/mesh.hpp", "max_stars_repo_name": "dhild/empiricalcpp", "max_stars_repo_head_hexsha": "d369be51ee022a6797a03f415c2dec78762a0822", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "empirical/include/empiricalcpp/src/mesh.hpp", "max_issues_repo_name": "dhild/empiricalcpp", "max_issues_repo_head_hexsha": "d369be51ee022a6797a03f415c2dec78762a0822", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2015-01-08T07:15:49.000Z", "max_issues_repo_issues_event_max_datetime": "2015-01-20T04:03:40.000Z", "max_forks_repo_path": "empirical/include/empiricalcpp/src/mesh.hpp", "max_forks_repo_name": "dhild/empiricalcpp", "max_forks_repo_head_hexsha": "d369be51ee022a6797a03f415c2dec78762a0822", "max_forks_repo_licenses": ["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.5733333333, "max_line_length": 135, "alphanum_fraction": 0.5707184092, "num_tokens": 1381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.6548947425132314, "lm_q1q2_score": 0.48669682164434186}}
{"text": "/**\n * This file is part of https://github.com/adrelino/interpolation-methods\n *\n * Copyright (c) 2018 Adrian Haarbach <mail@adrian-haarbach.de>\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n#ifndef INTERPOL_R3xSO3_HPP\n#define INTERPOL_R3xSO3_HPP\n\n#include <Eigen/Geometry>\n\nnamespace interpol {\n\nclass R3xSO3\n{\npublic:\n    Eigen::Quaterniond quat;\n    Eigen::Vector3d tra;\n\n    R3xSO3(const Eigen::Quaterniond& q, const Eigen::Vector3d& t) : quat(q), tra(t) {}\n\n    R3xSO3& operator *=(const R3xSO3& other){\n        quat *= other.quat;\n        tra += other.tra;\n        return *this;\n    }\n};\n\nstatic Eigen::Vector3d tra(const R3xSO3& rr){\n    return rr.tra;\n}\nstatic Eigen::Quaterniond rot(const R3xSO3& rr){\n    return rr.quat;\n}\n\n} // ns interpol\n\n#endif // INTERPOL_R3xSO3_HPP\n", "meta": {"hexsha": "a908be6c6c6cf6933a1083bfc820af229a960d8d", "size": 870, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/libinterpol/include/interpol/rigid/R3xSO3.hpp", "max_stars_repo_name": "adrelino/interpolation-methods", "max_stars_repo_head_hexsha": "094cbabbd0c25743d088a623f5913149c6b8a2ab", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 81.0, "max_stars_repo_stars_event_min_datetime": "2018-08-31T03:26:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T04:01:44.000Z", "max_issues_repo_path": "src/libinterpol/include/interpol/rigid/R3xSO3.hpp", "max_issues_repo_name": "bygreencn/interpolation-methods", "max_issues_repo_head_hexsha": "508723d1bca10c350f1a83c2fd31c2227cc1c0a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-07-16T06:45:12.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-15T17:47:01.000Z", "max_forks_repo_path": "src/libinterpol/include/interpol/rigid/R3xSO3.hpp", "max_forks_repo_name": "bygreencn/interpolation-methods", "max_forks_repo_head_hexsha": "508723d1bca10c350f1a83c2fd31c2227cc1c0a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19.0, "max_forks_repo_forks_event_min_datetime": "2018-09-20T18:37:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-04T15:04:37.000Z", "avg_line_length": 21.2195121951, "max_line_length": 86, "alphanum_fraction": 0.6850574713, "num_tokens": 256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.48669682164434186}}
{"text": "//  (C) Copyright Matt Borland 2021.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n//\n//  Constepxr implementation of abs (see c.math.abs secion 26.8.2 of the ISO standard)\n\n#ifndef BOOST_MATH_CCMATH_ABS\n#define BOOST_MATH_CCMATH_ABS\n\n#include <cmath>\n#include <type_traits>\n#include <limits>\n#include <boost/math/tools/is_constant_evaluated.hpp>\n#include <boost/math/ccmath/isnan.hpp>\n#include <boost/math/ccmath/isinf.hpp>\n\nnamespace boost::math::ccmath {\n\nnamespace detail {\n\ntemplate <typename T> \ninline constexpr T abs_impl(T x)\n{\n    return boost::math::ccmath::isnan(x) ? std::numeric_limits<T>::quiet_NaN() : \n           boost::math::ccmath::isinf(x) ? std::numeric_limits<T>::infinity() : \n           x == -0 ? T(0) :\n           x == (std::numeric_limits<T>::min)() ? std::numeric_limits<T>::quiet_NaN() : \n           x > 0 ? x : -x;\n}\n\n} // Namespace detail\n\ntemplate <typename T, std::enable_if_t<!std::is_unsigned_v<T>, bool> = true>\ninline constexpr T abs(T x)\n{\n    if(BOOST_MATH_IS_CONSTANT_EVALUATED(x))\n    {\n        return detail::abs_impl<T>(x);\n    }\n    else\n    {\n        using std::abs;\n        return abs(x);\n    }\n}\n\n// If abs() is called with an argument of type X for which is_unsigned_v<X> is true and if X\n// cannot be converted to int by integral promotion (7.3.7), the program is ill-formed.\ntemplate <typename T, std::enable_if_t<std::is_unsigned_v<T>, bool> = true>\ninline constexpr T abs(T x)\n{\n    if constexpr (std::is_convertible_v<T, int>)\n    {\n        return detail::abs_impl<int>(static_cast<int>(x));\n    }\n    else\n    {\n        static_assert(sizeof(T) == 0, \"Taking the absolute value of an unsigned value not covertible to int is UB.\");\n        return T(0); // Unreachable, but suppresses warnings\n    }\n}\n\n} // Namespaces\n\n#endif // BOOST_MATH_CCMATH_ABS\n", "meta": {"hexsha": "49673865749363e9962207779841279e9613fcce", "size": 1947, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/math/ccmath/abs.hpp", "max_stars_repo_name": "jzmaddock/math", "max_stars_repo_head_hexsha": "6a2365805e5ec816094e5f9d94aa0015d92318b8", "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/math/ccmath/abs.hpp", "max_issues_repo_name": "jzmaddock/math", "max_issues_repo_head_hexsha": "6a2365805e5ec816094e5f9d94aa0015d92318b8", "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/math/ccmath/abs.hpp", "max_forks_repo_name": "jzmaddock/math", "max_forks_repo_head_hexsha": "6a2365805e5ec816094e5f9d94aa0015d92318b8", "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.0597014925, "max_line_length": 117, "alphanum_fraction": 0.6646122239, "num_tokens": 529, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.6548947425132314, "lm_q1q2_score": 0.4866968216443418}}
{"text": "/**\n *  @file\n *  @copyright defined in eos/LICENSE.txt\n */\n#include <eosio/chain/asset.hpp>\n#include <boost/rational.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <fc/reflect/variant.hpp>\n\nnamespace eosio { namespace chain {\ntypedef boost::multiprecision::int128_t  int128_t;\n\nuint8_t asset::decimals()const {\n   return sym.decimals();\n}\n\nstring asset::symbol_name()const {\n   return sym.name();\n}\n\nint64_t asset::precision()const {\n   return sym.precision();\n}\n\nstring asset::to_string()const {\n   string result = fc::to_string( static_cast<int64_t>(amount) / precision());\n   if( decimals() )\n   {\n      auto fract = static_cast<int64_t>(amount) % precision();\n      result += \".\" + fc::to_string(precision() + fract).erase(0,1);\n   }\n   return result + \" \" + symbol_name();\n}\n\nasset asset::from_string(const string& from)\n{\n   try { \n      string s = fc::trim(from);\n      auto dot_pos = s.find(\".\");\n      FC_ASSERT(dot_pos != string::npos, \"dot missing in asset from string\");\n      auto space_pos = s.find(\" \", dot_pos);\n      FC_ASSERT(space_pos != string::npos, \"space missing in asset from string\");\n\n      asset result;\n      \n      auto intpart = s.substr(0, dot_pos);\n      result.amount = fc::to_int64(intpart);\n      string symbol_part;\n      if (dot_pos != string::npos && space_pos != string::npos) {\n         symbol_part = eosio::chain::to_string(space_pos - dot_pos - 1);\n         symbol_part += ',';\n         symbol_part += s.substr(space_pos + 1);\n      }\n      result.sym = symbol::from_string(symbol_part);\n      if (dot_pos != string::npos) {\n         auto fractpart = \"1\" + s.substr(dot_pos + 1, space_pos - dot_pos - 1);\n         \n         result.amount *= int64_t(result.precision());\n         result.amount += int64_t(fc::to_int64(fractpart));\n         result.amount -= int64_t(result.precision());\n      }\n      \n      return result;\n   }\n   FC_CAPTURE_LOG_AND_RETHROW( (from) )\n}\n\n} }  // eosio::types\n", "meta": {"hexsha": "8d4fb0c4c2543075a92412a60c4a39a03b814511", "size": 1944, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libraries/chain/asset.cpp", "max_stars_repo_name": "nanWarez/BTC_OS", "max_stars_repo_head_hexsha": "a91940b8816a5d7916c5593e8cd0805660737f65", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-08-19T03:03:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-19T03:04:46.000Z", "max_issues_repo_path": "libraries/chain/asset.cpp", "max_issues_repo_name": "ElementhFoundation/blockchain", "max_issues_repo_head_hexsha": "5f63038c0e6fc90bc4bc0bc576410087785d8099", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libraries/chain/asset.cpp", "max_forks_repo_name": "ElementhFoundation/blockchain", "max_forks_repo_head_hexsha": "5f63038c0e6fc90bc4bc0bc576410087785d8099", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-04T11:36:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-04T11:36:48.000Z", "avg_line_length": 28.1739130435, "max_line_length": 81, "alphanum_fraction": 0.6219135802, "num_tokens": 495, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.6548947357776796, "lm_q1q2_score": 0.4866968166386952}}
{"text": "/*\nCopyright 2013 Henrik M\u00fche and Florian Funke\n\nThis file is part of CampersCoreBurner.\n\nCampersCoreBurner is free software: you can redistribute it and/or modify\nit under the terms of the GNU Affero General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nCampersCoreBurner is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License\nalong with CampersCoreBurner.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n/*\nCOMMENT SUMMARY FOR THIS FILE:\n\nThis file contains the implementation of the edit distance and hamming distance metrics.\n*/\n\n#pragma once\n\n#include \"core.h\"\n#include \"utils.hpp\"\n#include <boost/utility/string_ref.hpp>\n#include <cassert>\n#include <cstdint>\n#include <iostream>\n#include <string>\n#include <x86intrin.h>\n\n\nnamespace campers {\n\n// [1] Helpful description: Section 3.3 in http://www.cs.uta.fi/~helmu/pubs/spire03a.pdf\n// [2] Other helpful description: http://www.cs.uta.fi/~helmu/pubs/A2001-10.pdf, Figure 5\n// [3] http://apps.topcoder.com/forums/;jsessionid=2E79B293F6EA2F509795A6C303F74CAA?module=Thread&threadID=639500&start=0&mc=8#1095148\n\n/// Custom levenshtein distance. This is essentially the algorithm given in [1], Figure 5 which\n/// was originally developed by Myeres et. al (G. Myers. A fast bit-vector algorithm for approximate\n/// string matching based on dynamic progamming. Journal of the ACM, 46(3): 395-415, 1999.).\n/// An example implementation is given at [2]. We found [3] helpful in understanding the original\n/// paper better.\n///\n/// We improved the algorithm by replacing the inner loop with sse instructions effectively\n/// removing it\n///\n/// [1] http://www.cs.uta.fi/~helmu/pubs/A2001-10.pdf\n/// [2] http://apps.topcoder.com/forums/?module=Thread&threadID=639500&start=0&mc=8#1095148\n/// [3] http://www.cs.uta.fi/~helmu/pubs/A2001-10.pdf (especially Figure 5)\nstatic inline uint64_t similarity_levenshtein(boost::string_ref a,boost::string_ref b)\n{\n    unsigned qlen=a.length();\n    unsigned blen=b.length();\n    const char* qptr=a.data();\n    const char* bptr=b.data();\n    if (qlen>blen) {\n        std::swap(qlen,blen);\n        std::swap(qptr,bptr);\n    }\n    __m128i brep1,brep2;\n    uint64_t bmask;\n    if (blen<=16) {\n        brep1=_mm_lddqu_si128(reinterpret_cast<const __m128i*>(bptr));\n        bmask=(1<<blen)-1;\n    } else {\n        brep1=_mm_lddqu_si128(reinterpret_cast<const __m128i*>(bptr));\n        brep2=_mm_lddqu_si128(reinterpret_cast<const __m128i*>(bptr)+1);\n        bmask=(blen==32)?0xFFFFFFFF:((1<<blen)-1);\n    }\n\n    uint64_t dmj=blen;\n    uint64_t vp = (uint64_t)-1;\n    uint64_t vn = 0;\n    uint64_t hp = 0;\n    uint64_t hn = 0;\n    for (unsigned j = 0; j < qlen; j++) {\n        uint64_t pm;\n        __m128i c=_mm_set1_epi8(qptr[j]);\n        if (blen<=16) {\n            pm=_mm_movemask_epi8(_mm_cmpeq_epi8(c,brep1))&bmask;\n        } else {\n            pm=(_mm_movemask_epi8(_mm_cmpeq_epi8(c,brep1))|(_mm_movemask_epi8(_mm_cmpeq_epi8(c,brep2))<<16))&bmask;\n        }\n        uint64_t d = ((((pm & vp) + vp)) ^ vp) | pm | vn;\n        hp = (vn | ~(d | vp));\n        uint64_t hpw = (hp << 1) | 1;\n        hn = d & vp;\n\n        int m=blen-1;\n        if (hp&(1<<m)) ++dmj;\n        if (hn&(1<<m)) --dmj;\n\n        vp = (hn << 1) | ~(d | hpw);\n        vn = d & hpw;\n    }\n    return dmj;\n}\n\n/// Hamming distance using sse. Both words must be padded and aligned to 16 bytes and loaded\n/// into sse registers a and b. Then, we compute the xor of the two registers and use saturation\n/// arithmetics to propagte differences from the differing bit to the while byte.\nstatic inline unsigned similarity_hamming(__m128i a,__m128i b)\n{\n    __m128i mask=_mm_set1_epi8(254);\n    union { __m128i a; uint64_t b[2]; } x;\n    x.a=_mm_adds_epu8(_mm_xor_si128(a,b),mask);\n    return (_mm_popcnt_u64(x.b[0])+_mm_popcnt_u64(x.b[1]))-(128-16);\n}\n\n}\n", "meta": {"hexsha": "76851d3d6abd5d2c2da8a2453b8638367defb257", "size": 4130, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "admin/winning_teams/campers/Campers/impl/include/metrics.hpp", "max_stars_repo_name": "isj/sigmod", "max_stars_repo_head_hexsha": "8ffd3c50ac288aa12c05218d52b1f05eeb23a085", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-11-27T05:56:25.000Z", "max_stars_repo_stars_event_max_datetime": "2015-11-27T05:56:25.000Z", "max_issues_repo_path": "admin/winning_teams/campers/Campers/impl/include/metrics.hpp", "max_issues_repo_name": "isj/sigmod", "max_issues_repo_head_hexsha": "8ffd3c50ac288aa12c05218d52b1f05eeb23a085", "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": "admin/winning_teams/campers/Campers/impl/include/metrics.hpp", "max_forks_repo_name": "isj/sigmod", "max_forks_repo_head_hexsha": "8ffd3c50ac288aa12c05218d52b1f05eeb23a085", "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.2991452991, "max_line_length": 134, "alphanum_fraction": 0.6799031477, "num_tokens": 1253, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.4866968166386951}}
{"text": "\n#include <boost/test/unit_test.hpp>\n\n#include \"Werk/Utility/Units.hpp\"\n\nBOOST_AUTO_TEST_SUITE(UnitsTest) //haha\n\nBOOST_AUTO_TEST_CASE(TestBasic)\n{\n\tBOOST_REQUIRE_EQUAL(Werk::parseUnits(\"124\", Werk::STORAGE_UNITS), 124);\n\tBOOST_REQUIRE_EQUAL(Werk::parseUnits(\"723\", Werk::STORAGE_UNITS), 723);\n\n\tBOOST_REQUIRE_EQUAL(Werk::parseUnits(\"1.5K\", Werk::STORAGE_UNITS), 1024 + 512);\n\tBOOST_REQUIRE_EQUAL(Werk::parseUnits(\"4M\", Werk::STORAGE_UNITS), 4 * 1024 * 1024);\n\n\tBOOST_REQUIRE_EQUAL(Werk::parseUnits(\"10us\", Werk::TIME_UNITS), 10000);\n\tBOOST_REQUIRE_EQUAL(Werk::parseUnits(\"123.456ms\", Werk::TIME_UNITS), 123456000);\n}\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "e3f832b8add6271fb2b746dac3aff6e53a18dbe8", "size": 646, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/WerkTest/Utility/Units.cpp", "max_stars_repo_name": "mish24/werk", "max_stars_repo_head_hexsha": "2f8822842fb8f68a4402775d1d3b41021b5a9945", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/WerkTest/Utility/Units.cpp", "max_issues_repo_name": "mish24/werk", "max_issues_repo_head_hexsha": "2f8822842fb8f68a4402775d1d3b41021b5a9945", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/WerkTest/Utility/Units.cpp", "max_forks_repo_name": "mish24/werk", "max_forks_repo_head_hexsha": "2f8822842fb8f68a4402775d1d3b41021b5a9945", "max_forks_repo_licenses": ["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.3, "max_line_length": 83, "alphanum_fraction": 0.76625387, "num_tokens": 187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.4866968116330484}}
{"text": "#include <fstream>\n#include <vector>\n#include <Eigen/Dense>\n\n\nint loadData(Eigen::MatrixXd &mat, std::string filename, size_t row, size_t col)\n{\n\n\tstd::ifstream input;\n\tinput.open(filename, std::fstream::in | std::fstream::binary);\n\tif (input.is_open())\n\t{\n\t\tstd::vector<unsigned char> vec((std::istreambuf_iterator<char>(input)),\n\t\t\t\tstd::istreambuf_iterator<char>() );\n                mat= Eigen::Map<Eigen::Matrix<unsigned char, Eigen::Dynamic,Eigen::Dynamic> >(vec.data(),row,col).template cast<double>();\n\t\tinput.close();\n\t\treturn 1;\n\t}\n\treturn 0;\n\n}\nint storeData(Eigen::MatrixXd &mat, std::string filename)\n{\n\tEigen::Matrix<char, Eigen::Dynamic, Eigen::Dynamic> pic= mat.template cast<char>();\n\tstd::ofstream output;\n\toutput.open(filename,std::fstream::trunc);\n\tif (output.is_open())\n\t{\n\t\toutput.write(pic.data(),pic.size());\n\t\toutput.close();\n\t\treturn 1;\n\t}\n\treturn 0;\n\n\n}\n", "meta": {"hexsha": "7a75f167375f59c4d7a6f7ec7792fd0868c747f1", "size": 881, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Blatt2/include/service.cpp", "max_stars_repo_name": "lewis206/Computational_Physics", "max_stars_repo_head_hexsha": "06ad6126685eaf65f5834bfe70ebd91b33314395", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Blatt2/include/service.cpp", "max_issues_repo_name": "lewis206/Computational_Physics", "max_issues_repo_head_hexsha": "06ad6126685eaf65f5834bfe70ebd91b33314395", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Blatt2/include/service.cpp", "max_forks_repo_name": "lewis206/Computational_Physics", "max_forks_repo_head_hexsha": "06ad6126685eaf65f5834bfe70ebd91b33314395", "max_forks_repo_licenses": ["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.8108108108, "max_line_length": 138, "alphanum_fraction": 0.6765039728, "num_tokens": 226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.48669681163304834}}
{"text": "#define BOOST_TEST_MODULE Tests\n\n#ifdef BOOST_TEST_DYN_LINK\n#    include <boost/test/unit_test.hpp>\n#else\n#    include <boost/test/included/unit_test.hpp>\n#endif\n\n#include <boost/test/tools/output_test_stream.hpp>\n\nboost::test_tools::output_test_stream output;\n\n#define CHECK_OUTPUT(msg) BOOST_CHECK(output.is_equal(msg))\n\nclass coutRedirect {\n    std::streambuf* old;\n  public:\n    coutRedirect(std::streambuf* buf) : old(std::cout.rdbuf(buf)) {}\n    ~coutRedirect() { std::cout.rdbuf(old); }\n};\n\n#include \"Array.hpp\"\n#include \"AVL.hpp\"\n#include \"util.hpp\"\n\nBOOST_AUTO_TEST_SUITE(InsertionSort)\n\nBOOST_AUTO_TEST_CASE(test1)\n{\n    Array<int, 5> x = { 4, 2, 4, 5, 1 };\n    x.sort(\"insertion\");\n    output << x;\n    CHECK_OUTPUT(\"1 2 4 4 5\");\n}\n\nBOOST_AUTO_TEST_CASE(test2)\n{\n    Array<int, 100> a(2, 99);\n    a.sort(\"insertion\");\n    for (std::size_t i = 0; i < a.size-1; ++i) {\n        BOOST_CHECK_LE(a[i], a[i+1]);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(test3)\n{\n    Array<double, 10> x{ 10.2, 8.7, 8.3, 7.1, 6.9, 5.1, 4.3, 3.9, 2, 1.111 };\n    x.sort(\"insertion\");\n    BOOST_CHECK_EQUAL(x[0], 1.111);\n    BOOST_CHECK_EQUAL(x[1], 2);\n    BOOST_CHECK_EQUAL(x[2], 3.9);\n    BOOST_CHECK_EQUAL(x[3], 4.3);\n    BOOST_CHECK_EQUAL(x[4], 5.1);\n    BOOST_CHECK_EQUAL(x[5], 6.9);\n    BOOST_CHECK_EQUAL(x[6], 7.1);\n    BOOST_CHECK_EQUAL(x[7], 8.3);\n    BOOST_CHECK_EQUAL(x[8], 8.7);\n    BOOST_CHECK_EQUAL(x[9], 10.2);\n}\n\nBOOST_AUTO_TEST_CASE(test4)\n{\n    Array<int, 100> a(2, 99);\n    a.sort(\"insertion\");\n    BOOST_CHECK(isSorted(a));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\nBOOST_AUTO_TEST_SUITE(MergeSort)\n\nBOOST_AUTO_TEST_CASE(test1)\n{\n    Array<int, 5> x = { 4, 2, 4, 5, 1 };\n    x.sort(\"merge\");\n    output << x;\n    CHECK_OUTPUT(\"1 2 4 4 5\");\n}\n\nBOOST_AUTO_TEST_CASE(test2)\n{\n    Array<int, 100> a(2, 99);\n    a.sort(\"merge\");\n    for (std::size_t i = 0; i < a.size-1; ++i) {\n        BOOST_CHECK_LE(a[i], a[i+1]);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(test3)\n{\n    Array<double, 10> x{ 10.2, 8.7, 8.3, 7.1, 6.9, 5.1, 4.3, 3.9, 2, 1.111 };\n    x.sort(\"merge\");\n    BOOST_CHECK_EQUAL(x[0], 1.111);\n    BOOST_CHECK_EQUAL(x[1], 2);\n    BOOST_CHECK_EQUAL(x[2], 3.9);\n    BOOST_CHECK_EQUAL(x[3], 4.3);\n    BOOST_CHECK_EQUAL(x[4], 5.1);\n    BOOST_CHECK_EQUAL(x[5], 6.9);\n    BOOST_CHECK_EQUAL(x[6], 7.1);\n    BOOST_CHECK_EQUAL(x[7], 8.3);\n    BOOST_CHECK_EQUAL(x[8], 8.7);\n    BOOST_CHECK_EQUAL(x[9], 10.2);\n}\n\nBOOST_AUTO_TEST_CASE(test4)\n{\n    Array<int, 100> a(2, 99);\n    a.sort(\"merge\");\n    BOOST_CHECK(isSorted(a));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\nBOOST_AUTO_TEST_SUITE(HeapSort)\n\nBOOST_AUTO_TEST_CASE(test1)\n{\n    Array<int, 5> x = { 4, 2, 4, 5, 1 };\n    x.sort(\"heap\");\n    output << x;\n    CHECK_OUTPUT(\"1 2 4 4 5\");\n}\n\nBOOST_AUTO_TEST_CASE(test2)\n{\n    Array<int, 100> a(2, 99);\n    a.sort(\"heap\");\n    for (std::size_t i = 0; i < a.size-1; ++i) {\n        BOOST_CHECK_LE(a[i], a[i+1]);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(test3)\n{\n    Array<double, 10> x{ 10.2, 8.7, 8.3, 7.1, 6.9, 5.1, 4.3, 3.9, 2, 1.111 };\n    x.sort(\"heap\");\n    BOOST_CHECK_EQUAL(x[0], 1.111);\n    BOOST_CHECK_EQUAL(x[1], 2);\n    BOOST_CHECK_EQUAL(x[2], 3.9);\n    BOOST_CHECK_EQUAL(x[3], 4.3);\n    BOOST_CHECK_EQUAL(x[4], 5.1);\n    BOOST_CHECK_EQUAL(x[5], 6.9);\n    BOOST_CHECK_EQUAL(x[6], 7.1);\n    BOOST_CHECK_EQUAL(x[7], 8.3);\n    BOOST_CHECK_EQUAL(x[8], 8.7);\n    BOOST_CHECK_EQUAL(x[9], 10.2);\n}\n\nBOOST_AUTO_TEST_CASE(test4)\n{\n    Array<int, 100> a(2, 99);\n    a.sort(\"heap\");\n    BOOST_CHECK(isSorted(a));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\nBOOST_AUTO_TEST_SUITE(AVL_tree)\n\nBOOST_AUTO_TEST_CASE(test1)\n{\n    coutRedirect guard(output.rdbuf());\n    AVL<int> x;\n    x.insert(10);\n    x.insert(20);\n    x.insert(30);\n    x.insert(40);\n    x.insert(50);\n    x.insert(25);\n    x.print(\"pre\");\n    CHECK_OUTPUT(\"30 20 10 25 40 50 \\n\");\n}\n\nBOOST_AUTO_TEST_CASE(test2)\n{\n    coutRedirect guard(output.rdbuf());\n    AVL<int> x;\n    x.insert(9);\n    x.insert(5);\n    x.insert(10);\n    x.insert(0);\n    x.insert(6);\n    x.insert(11);\n    x.insert(-1);\n    x.insert(1);\n    x.insert(2);\n    x.print(\"pre\");\n    CHECK_OUTPUT(\"9 1 0 -1 5 2 6 10 11 \\n\");\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "3b331d8f2f73f7065e7dfd6d3e34beef9a4eecfa", "size": 4114, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ASD/repo/tests/tests.cpp", "max_stars_repo_name": "Jorengarenar/homework", "max_stars_repo_head_hexsha": "5e69aa0fb1b21ffaf88d62af263ea719e82e9c70", "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": "ASD/repo/tests/tests.cpp", "max_issues_repo_name": "Jorengarenar/homework", "max_issues_repo_head_hexsha": "5e69aa0fb1b21ffaf88d62af263ea719e82e9c70", "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": "ASD/repo/tests/tests.cpp", "max_forks_repo_name": "Jorengarenar/homework", "max_forks_repo_head_hexsha": "5e69aa0fb1b21ffaf88d62af263ea719e82e9c70", "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": 21.4270833333, "max_line_length": 77, "alphanum_fraction": 0.6101118133, "num_tokens": 1471, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.48669680790777853}}
{"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_AVERAGE_HPP_INCLUDED\n#define BOOST_SIMD_ARITHMETIC_FUNCTIONS_AVERAGE_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  average generic tag\n\n      Represents the average function in generic contexts.\n\n      @par Models:\n      Hierarchy\n    **/\n    struct average_ : ext::elementwise_<average_>\n    {\n      /// @brief Parent hierarchy\n      typedef ext::elementwise_<average_> parent;\n      template<class... Args>\n      static BOOST_FORCEINLINE BOOST_AUTO_DECLTYPE dispatch(Args&&... args)\n      BOOST_AUTO_DECLTYPE_BODY( dispatching_average_( 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::average_, Site> dispatching_average_(adl_helper, boost::dispatch::meta::unknown_<Site>, boost::dispatch::meta::unknown_<Ts>...)\n    {\n      return generic_dispatcher<tag::average_, Site>();\n    }\n    template<class... Args>\n    struct impl_average_;\n  }\n  /*!\n    Computes the arithmetic mean of its parameters.\n\n    @par semantic:\n    For any given value @c x,  @c y of type @c T:\n\n    @code\n    T r = average(x, y);\n    @endcode\n\n    For floating point values the code is equivalent to:\n\n    @code\n    T r = (x+y)/T(2);\n    @endcode\n\n    for integer types  it returns a rounded value at a distance guaranteed\n    less or equal to 0.5 of the average floating value,  but can differ\n    of one unity from the truncation given by (x1+x2)/T(2).\n\n    @par Note:\n\n    This function does not overflow.\n\n    @see  @funcref{meanof}\n    @param  a0\n    @param  a1\n\n    @return      a value of the same type as the input.\n\n  **/\n  BOOST_DISPATCH_FUNCTION_IMPLEMENTATION(tag::average_, average, 2)\n} }\n\n#endif\n", "meta": {"hexsha": "24815148446599526c8fd7324a7b08798b9bfd01", "size": 2384, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/average.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/average.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/average.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": 30.5641025641, "max_line_length": 173, "alphanum_fraction": 0.6208053691, "num_tokens": 572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.4866968066274016}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// example::iterator::range_cycle.cpp                                        //\n//                                                                           //\n//  Copyright 2009 Erwann Rogard. Distributed under the Boost                //\n//  Software License, Version 1.0. (See accompanying file                    //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)         //\n/////////////////////////////////////////////////////////////////////////////// \n#include <iostream>\n#include <boost/assign/std/vector.hpp>\n#include <boost/range.hpp>\n#include <vector>\n#include <boost/iterator/cycle_iterator_ext.hpp>\n#include <boost/iterator/range_cycle.hpp>\n#include <libs/iterator/example/range_cycle.h>\n\nvoid example_range_cycle(std::ostream& out){\n    out << \"->example_iterator_cycle_range : \";\n\n    using namespace boost;\n\n    typedef unsigned                                    val_;\n    typedef std::vector<val_>                           vals_;\n    typedef range_size<vals_>::type                     size_;\n\n    typedef boost::range_cycle<>                        range_cycle_;\n    typedef range_cycle_::apply<vals_>::type            cycle_;\n    const size_ n = 5;\n    const size_ k = 2;\n\n    vals_ vals;\n    {   \n        using namespace assign;\n        for(unsigned i = 0; i<k; i++){\n            vals.push_back(i);\n        }\n    }\n\n    cycle_ cycle = range_cycle_::make(vals,0,n);\n    BOOST_ASSERT( !cycle.is_singular() );\n    BOOST_ASSERT(size( cycle ) == n);\n    for(unsigned i = 0; i<n; i++){\n        BOOST_ASSERT(\n         *next(boost::begin(cycle),i) == (i%k)\n        );\n    }\n    cycle_ cycle2;\n    BOOST_ASSERT( cycle2.is_singular() );\n    cycle2 = cycle;\n    for(unsigned i = 0; i<n; i++){\n        BOOST_ASSERT(\n         *next(boost::begin(cycle2),i) == (i%k)\n        );\n    }\n    \n//    copy(\n//        boost::begin(cycle2),\n//        boost::end(cycle2),\n//        std::ostream_iterator<val_>(out,\" \")\n//    );\n    \n    out << \"<-\" << std::endl;\n}\n", "meta": {"hexsha": "9c8ab8e4b8dbc8f6e4fe817cdb917c3943fff5aa", "size": 2065, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "iterator/libs/iterator/example/range_cycle.cpp", "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": "iterator/libs/iterator/example/range_cycle.cpp", "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": "iterator/libs/iterator/example/range_cycle.cpp", "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.7777777778, "max_line_length": 80, "alphanum_fraction": 0.4779661017, "num_tokens": 452, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.48669680662740156}}
{"text": "#ifndef MYFRAMEMAIN_HPP\n#define MYFRAMEMAIN_HPP\n\n#include \"mna.h\"\n#include <mutex>\n#include <future>\n\n#include <boost/multiprecision/cpp_bin_float.hpp>\n#include <wx/rawbmp.h>\n\nusing fl = long double; //boost::multiprecision::cpp_bin_float_100;\n\nclass MyFrameMain :\n    public FrameMain\n{\n    wxBitmap m_bitmap;\n    bool in_on_timer = false;\n    void m_timerUpdateScreenOnTimer(wxTimerEvent& evnt) override;\n    void FrameMainOnPaint(wxPaintEvent& evnt) override;\n    std::mutex drawing_lock;\n    std::future<void> main_loop_thread;\n    volatile bool stop_now = false;\n    volatile bool changed_dimensions = false;\n    static void separate_thread_to_compute_rows(wxNativePixelData& data, wxNativePixelData::Iterator pixel, const unsigned y_start, const unsigned rows_to_compute, MyFrameMain& this_ref, wxSize frame_size);\n    static void main_loop(MyFrameMain& this_ref);\n    void FrameMainOnLeftDClick(wxMouseEvent& evnt) override;\n    boost::multiprecision::cpp_bin_float_100 m_magnification = 1;\n    fl m_zoom = 0.5;\n    fl m_start_x_mandel = -2;\n    fl m_start_y_mandel = -1;\n    fl m_len_x_mandel = 3;\n    fl m_len_y_mandel = 2;\npublic:\n    void start_main_loop();\n    MyFrameMain(wxWindow *const parent, const wxWindowID id, const wxString& title);\n    ~MyFrameMain() override;\n};\n\n#endif\n", "meta": {"hexsha": "3024e368dc53540a1190786ea3f5022891598b45", "size": 1294, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "wxBitmap/MyFrameMain.hpp", "max_stars_repo_name": "BigBIueWhale/mandelbrot", "max_stars_repo_head_hexsha": "fb863f140a6570251d72ba99b35c6fe6f6c98fa9", "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": "wxBitmap/MyFrameMain.hpp", "max_issues_repo_name": "BigBIueWhale/mandelbrot", "max_issues_repo_head_hexsha": "fb863f140a6570251d72ba99b35c6fe6f6c98fa9", "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": "wxBitmap/MyFrameMain.hpp", "max_forks_repo_name": "BigBIueWhale/mandelbrot", "max_forks_repo_head_hexsha": "fb863f140a6570251d72ba99b35c6fe6f6c98fa9", "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": 32.35, "max_line_length": 206, "alphanum_fraction": 0.7519319938, "num_tokens": 343, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431679972357831, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.48669680418250877}}
{"text": "//\n// Created by ziqwang on 2020-02-03.\n//\n\n#include <catch2/catch.hpp>\n#include \"Interlocking/InterlockingSolver_Clp.h\"\n#include \"IO/JsonIOReader.h\"\n#include <iostream>\n#include <Eigen/Dense>\n#include <Eigen/SparseQR>\n\nTEST_CASE(\"Bunny Example Clp\")\n{\n    vector<shared_ptr<PolyMesh<double>>> meshList;\n    vector<bool> atboundary;\n    shared_ptr<InputVarList> varList = make_shared<InputVarList>();\n    InitVar(varList.get());\n\n    //Read all Parts\n    for(int id = 1; id <= 80; id++){\n        char number[50];\n        sprintf(number, \"%d.obj\", id);\n        std::string part_filename = \"data/Voxel/bunny/part_\";\n        part_filename += number;\n        shared_ptr<PolyMesh<double>> polyMesh = make_shared<PolyMesh<double>>(varList);\n        polyMesh->readOBJModel(part_filename.c_str(), false);\n\n        meshList.push_back(polyMesh);\n        atboundary.push_back(false);\n    }\n\n    SECTION(\"fix key and second part\"){\n        // set the first and second part to be on the boundires\n        // then the structure is interlocking\n        atboundary[0] = true;\n        atboundary[1] = true;\n\n        // construct the contact graph\n        shared_ptr<ContactGraph<double>>graph = make_shared<ContactGraph<double>>(varList);\n        graph->buildFromMeshes(meshList, atboundary, 1e-3);\n\n        // solve the interlocking problem by using CLP library\n        InterlockingSolver_Clp<double> solver(graph, varList);\n        shared_ptr<typename InterlockingSolver<double>::InterlockingData> interlockData;\n        REQUIRE(solver.isRotationalInterlocking(interlockData) == true);\n    }\n\n    SECTION(\"fix key\"){\n        // if only set the key to be fixed\n        // the reset parts could move together, therefore the structure is not interlocking\n        atboundary[0] = true;\n\n        // construct the contact graph\n        shared_ptr<ContactGraph<double>>graph = make_shared<ContactGraph<double>>(varList);\n        graph->buildFromMeshes(meshList, atboundary);\n\n        // solve the interlocking problem by using CLP library\n        InterlockingSolver_Clp<double> solver(graph, varList);\n        shared_ptr<typename InterlockingSolver<double>::InterlockingData> interlockData;\n        REQUIRE(solver.isRotationalInterlocking(interlockData) == false);\n    }\n\n    SECTION(\"fix key and merge key and second part\"){\n        // if only set the key to be fixed\n        // the reset parts could move together, therefore the structure is not interlocking\n        atboundary[0] = true;\n\n        // construct the contact graph\n        shared_ptr<ContactGraph<double>>graph = make_shared<ContactGraph<double>>(varList);\n        graph->buildFromMeshes(meshList, atboundary);\n\n        //merge\n        graph->mergeNode(graph->nodes[0], graph->nodes[1]);\n\n        // solve the interlocking problem by using CLP library\n        InterlockingSolver_Clp<double> solver(graph, varList);\n        shared_ptr<typename InterlockingSolver<double>::InterlockingData> interlockData;\n        REQUIRE(solver.isRotationalInterlocking(interlockData) == true);\n    }\n}\n\n\nTEST_CASE(\"Ania Example Clp\"){\n    std::string file_name[5] = { \"piece4_tri.obj\", \"piece0.obj\", \"piece1.obj\", \"piece3.obj\", \"piece2.obj\"};\n\n    vector<shared_ptr<PolyMesh<double>>> meshList;\n    vector<bool> atboundary;\n    shared_ptr<InputVarList> varList = make_shared<InputVarList>();\n    InitVar(varList.get());\n\n    for(int id = 0; id < 5; id++){\n        char number[50];\n        std::string part_filename = \"data/Mesh/Ania_200127_betweenbars/\";\n        part_filename += file_name[id];\n        shared_ptr<PolyMesh<double>> polyMesh = make_shared<PolyMesh<double>>(varList);\n        polyMesh->readOBJModel(part_filename.c_str(), false);\n        meshList.push_back(polyMesh);\n        atboundary.push_back(true);\n    }\n\n    atboundary[0] = false;\n\n    shared_ptr<ContactGraph<double>>graph = make_shared<ContactGraph<double>>(varList);\n    graph->buildFromMeshes(meshList, atboundary, 1e-3);\n\n//    SECTION(\"Simplex Method\"){\n//        // solve the interlocking problem by using CLP library\n//        InterlockingSolver_Clp<double> solver(graph, varList, SIMPLEX);\n//        shared_ptr<typename InterlockingSolver<double>::InterlockingData> interlockData;\n//        REQUIRE(solver.isRotationalInterlocking(interlockData) == false);\n//    }\n\n    SECTION(\"Barrier Method\"){\n        // solve the interlocking problem by using CLP library\n        InterlockingSolver_Clp<double> solver(graph, varList, BARRIER);\n        shared_ptr<typename InterlockingSolver<double>::InterlockingData> interlockData;\n        REQUIRE(solver.isRotationalInterlocking(interlockData) == false);\n    }\n\n}\n\nTEST_CASE(\"Ania Example: Special Case\"){\n    //Read all Parts\n\n    std::string file_name[3] = {\"piece0.obj\", \"piece1.obj\", \"piece4_tri.obj\"};\n    vector<shared_ptr<PolyMesh<double>>> meshList;\n    vector<bool> atboundary;\n    shared_ptr<InputVarList> varList = make_shared<InputVarList>();\n    InitVar(varList.get());\n    bool textureModel;\n\n\n    for(int id = 0; id < 3; id++){\n        char number[50];\n        std::string part_filename = \"data/Mesh/Ania_200127_betweenbars/\";\n        part_filename += file_name[id];\n        shared_ptr<PolyMesh<double>> polyMesh = make_shared<PolyMesh<double>>(varList);\n        polyMesh->readOBJModel(part_filename.c_str(), false);\n        meshList.push_back(polyMesh);\n        atboundary.push_back(false);\n    }\n\n    atboundary[0] = true;\n    atboundary[1] = true;\n\n    shared_ptr<ContactGraph<double>>graph = make_shared<ContactGraph<double>>(varList);\n    graph->buildFromMeshes(meshList, atboundary, 1e-3);\n\n    // solve the interlocking problem by using CLP library\n    InterlockingSolver_Clp<double> solver(graph, varList);\n    shared_ptr<typename InterlockingSolver<double>::InterlockingData> interlockData;\n    REQUIRE(solver.isRotationalInterlocking(interlockData) == false);\n}\n", "meta": {"hexsha": "d7c1c4e69d78f027e5a99b61daf4e1fd4c50f055", "size": 5835, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/Interlocking/Test_InterlockingSolver_Clp.cpp", "max_stars_repo_name": "carlostapiarq/TopoLite", "max_stars_repo_head_hexsha": "d6eb9125518a88ea546917df5217978f34661b2c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2020-06-10T08:28:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-07T02:55:35.000Z", "max_issues_repo_path": "test/Interlocking/Test_InterlockingSolver_Clp.cpp", "max_issues_repo_name": "carlostapiarq/TopoLite", "max_issues_repo_head_hexsha": "d6eb9125518a88ea546917df5217978f34661b2c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-06-08T12:21:49.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-10T07:56:42.000Z", "max_forks_repo_path": "test/Interlocking/Test_InterlockingSolver_Clp.cpp", "max_forks_repo_name": "carlostapiarq/TopoLite", "max_forks_repo_head_hexsha": "d6eb9125518a88ea546917df5217978f34661b2c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-06-22T10:07:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-04T06:02:33.000Z", "avg_line_length": 37.8896103896, "max_line_length": 107, "alphanum_fraction": 0.6858611825, "num_tokens": 1391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.6261241911813151, "lm_q1q2_score": 0.486686253343607}}
{"text": "\n#include <NTL/LLL.h>\n#include <NTL/fileio.h>\n\n#include <NTL/new.h>\n\nNTL_START_IMPL\n\n\n\n\nstatic void RowTransform(vec_ZZ& A, vec_ZZ& B, const ZZ& MU1)\n// x = x - y*MU\n{\n   static ZZ T, MU;\n   long k;\n\n   long n = A.length();\n   long i;\n\n   MU = MU1;\n\n   if (MU == 1) {\n      for (i = 1; i <= n; i++)\n         sub(A(i), A(i), B(i));\n\n      return;\n   }\n\n   if (MU == -1) {\n      for (i = 1; i <= n; i++)\n         add(A(i), A(i), B(i));\n\n      return;\n   }\n\n   if (MU == 0) return;\n\n   if (NumTwos(MU) >= NTL_ZZ_NBITS) \n      k = MakeOdd(MU);\n   else\n      k = 0;\n\n\n   if (MU.WideSinglePrecision()) {\n      long mu1;\n      conv(mu1, MU);\n\n      for (i = 1; i <= n; i++) {\n         mul(T, B(i), mu1);\n         if (k > 0) LeftShift(T, T, k);\n         sub(A(i), A(i), T);\n      }\n   }\n   else {\n      for (i = 1; i <= n; i++) {\n         mul(T, B(i), MU);\n         if (k > 0) LeftShift(T, T, k);\n         sub(A(i), A(i), T);\n      }\n   }\n}\n\nstatic void RowTransform2(vec_ZZ& A, vec_ZZ& B, const ZZ& MU1)\n// x = x + y*MU\n{\n   static ZZ T, MU;\n   long k;\n\n   long n = A.length();\n   long i;\n\n   MU = MU1;\n\n   if (MU == 1) {\n      for (i = 1; i <= n; i++)\n         add(A(i), A(i), B(i));\n\n      return;\n   }\n\n   if (MU == -1) {\n      for (i = 1; i <= n; i++)\n         sub(A(i), A(i), B(i));\n\n      return;\n   }\n\n   if (MU == 0) return;\n\n   if (NumTwos(MU) >= NTL_ZZ_NBITS) \n      k = MakeOdd(MU);\n   else\n      k = 0;\n\n   if (MU.WideSinglePrecision()) {\n      long mu1;\n      conv(mu1, MU);\n\n      for (i = 1; i <= n; i++) {\n         mul(T, B(i), mu1);\n         if (k > 0) LeftShift(T, T, k);\n         add(A(i), A(i), T);\n      }\n   }\n   else {\n      for (i = 1; i <= n; i++) {\n         mul(T, B(i), MU);\n         if (k > 0) LeftShift(T, T, k);\n         add(A(i), A(i), T);\n      }\n   }\n}\n\nclass GivensCache_RR {\npublic:\n   GivensCache_RR(long m, long n);\n   ~GivensCache_RR();\n\n   void flush();\n   void selective_flush(long l);\n   void swap(long l);\n   void swap();\n   void touch();\n   void incr();\n\n   long sz;\n\n   mat_RR buf;\n\n   long *bl;\n   long *bv;\n   long bp;\n};\n\n\nGivensCache_RR::GivensCache_RR(long m, long n)\n{\n   sz = min(m, n)/10;\n   if (sz < 2) \n      sz = 2;\n   else if (sz > 20)\n      sz = 20;\n\n   typedef double *doubleptr;\n\n   long i;\n\n   buf.SetDims(sz, n);\n\n   bl = NTL_NEW_OP long[sz];\n   if (!bl) Error(\"out of memory\");\n   for (i = 0; i < sz; i++) bl[0] = 0;\n\n   bv = NTL_NEW_OP long[sz];\n   if (!bv) Error(\"out of memory\");\n   for (i = 0; i < sz; i++) bv[0] = 0;\n\n   bp = 0;\n}\n\nGivensCache_RR::~GivensCache_RR()\n{\n   delete [] bl;\n   delete [] bv;\n}\n\nvoid GivensCache_RR::flush()\n{\n   long i;\n   for (i = 0; i < sz; i++) bl[i] = 0;\n}\n\nvoid GivensCache_RR::selective_flush(long l)\n{\n   long i;\n\n   for (i = 0; i < sz; i++)\n      if (bl[i] && bv[i] >= l)\n         bl[i] = 0;\n}\n\nvoid GivensCache_RR::swap(long l)\n{\n   long k = bl[bp];\n   long i;\n\n   i = 0;\n   while (i < sz && bl[i] != l)\n      i++;\n\n   if (i < sz) {\n      bl[bp] = l;\n      bl[i] = k;\n   }\n   else\n      bl[bp] = l;\n\n   selective_flush(l);\n}\n\nvoid GivensCache_RR::swap()\n{\n   swap(bl[bp] - 1);\n}\n\nvoid GivensCache_RR::touch()\n{\n   long k = bl[bp];\n   bl[bp] = 0;\n   selective_flush(k);\n}\n\nvoid GivensCache_RR::incr()\n{\n   long k = bl[bp];\n   long k1 = k+1;\n   long i;\n\n   i = 0;\n   while (i < sz && bl[i] != k1)\n      i++;\n\n   if (i < sz) {\n      bp = i;\n      return;\n   }\n\n   i = 0; \n   while (i < sz && bl[i] != 0)\n      i++;\n\n   if (i < sz) {\n      bp = i;\n      return;\n   }\n\n   long max_val = 0;\n   long max_index = 0;\n   for (i = 0; i < sz; i++) {\n      long t = labs(bl[i]-k1);\n      if (t > max_val) {\n         max_val = t;\n         max_index = i;\n      }\n   }\n\n   bp = max_index;\n   bl[max_index] = 0;\n}\n\n\nstatic\nvoid GivensComputeGS(mat_RR& B1, mat_RR& mu, mat_RR& aux, long k, long n,\n                     GivensCache_RR& cache)\n{\n   long i, j;\n\n   RR c, s, a, b, t;\n   RR T1, T2;\n\n   vec_RR& p = mu(k);\n\n   vec_RR& pp = cache.buf[cache.bp];\n\n   if (!cache.bl[cache.bp]) {\n      for (j = 1; j <= n; j++)\n         pp(j) = B1(k,j);\n\n      long backoff;\n      backoff = k/4;\n      if (backoff < 2)\n         backoff = 2;\n      else if (backoff > cache.sz + 2)\n         backoff = cache.sz + 2; \n\n      long ub = k-(backoff-1);\n\n      for (i = 1; i < ub; i++) {\n         vec_RR& cptr = mu(i);\n         vec_RR& sptr = aux(i);\n   \n         for (j = n; j > i; j--) {\n            c = cptr(j);\n            s = sptr(j);\n   \n            // a = c*pp(j-1) - s*pp(j);\n            mul(T1, c, pp(j-1));\n            mul(T2, s, pp(j));\n            sub(a, T1, T2);\n\n            // b = s*pp(j-1) + c*pp(j);\n            mul(T1, s, pp(j-1));\n            mul(T2, c, pp(j));\n            add(b, T1, T2);\n   \n            pp(j-1) = a;\n            pp(j) = b;\n         }\n   \n         div(pp(i), pp(i), mu(i,i));\n      }\n\n      cache.bl[cache.bp] = k;\n      cache.bv[cache.bp] = k-backoff;\n   }\n\n   for (j = 1; j <= n; j++)\n      p(j) = pp(j);\n\n   for (i = max(cache.bv[cache.bp]+1, 1); i < k; i++) {\n      vec_RR& cptr = mu(i);\n      vec_RR& sptr = aux(i);\n  \n      for (j = n; j > i; j--) {\n         c = cptr(j);\n         s = sptr(j);\n  \n         // a = c*p(j-1) - s*p(j);\n         mul(T1, c, p(j-1));\n         mul(T2, s, p(j));\n         sub(a, T1, T2);\n\n         // b = s*p(j-1) + c*p(j);\n         mul(T1, s, p(j-1));\n         mul(T2, c, p(j));\n         add(b, T1, T2);\n  \n         p(j-1) = a;\n         p(j) = b;\n      }\n  \n      div(p(i), p(i), mu(i,i));\n   }\n\n   for (j = n; j > k; j--) {\n      a = p(j-1);\n      b = p(j);\n\n      if (b == 0) {\n         c = 1;\n         s = 0;\n      }\n      else {\n         abs(T1, b);\n         abs(T2, a);\n\n         if (T1 > T2) {\n            // t = -a/b;\n            div(T1, a, b);\n            negate(t, T1);\n   \n            // s = 1/sqrt(1 + t*t);\n            sqr(T1, t);\n            add(T1, T1, 1);\n            SqrRoot(T1, T1);\n            inv(s, T1);\n            \n            // c = s*t;\n            mul(c, s, t);\n         }\n         else {\n            // t = -b/a;\n            div(T1, b, a);\n            negate(t, T1);\n   \n            // c = 1/sqrt(1 + t*t);\n            sqr(T1, t);\n            add(T1, T1, 1);\n            SqrRoot(T1, T1);\n            inv(c, T1);\n   \n            // s = c*t;\n            mul(s, c, t);\n         }\n      }\n   \n      // p(j-1) = c*a - s*b;\n      mul(T1, c, a);\n      mul(T2, s, b);\n      sub(p(j-1), T1, T2);\n\n      p(j) = c;\n      aux(k,j) = s;\n   }\n\n   if (k > n+1) Error(\"G_LLL_RR: internal error\");\n   if (k > n) p(k) = 0;\n\n}\n\nstatic RR red_fudge;\nstatic long log_red = 0;\n\nstatic void init_red_fudge()\n{\n   log_red = long(0.50*RR::precision());\n\n   power2(red_fudge, -log_red);\n}\n\nstatic void inc_red_fudge()\n{\n\n   mul(red_fudge, red_fudge, 2);\n   log_red--;\n\n   cerr << \"G_LLL_RR: warning--relaxing reduction (\" << log_red << \")\\n\";\n\n   if (log_red < 4)\n      Error(\"G_LLL_RR: can not continue...sorry\");\n}\n\n\n\n\nstatic long verbose = 0;\n\nstatic unsigned long NumSwaps = 0;\nstatic double StartTime = 0;\nstatic double LastTime = 0;\n\n\n\nstatic void G_LLLStatus(long max_k, double t, long m, const mat_ZZ& B)\n{\n   cerr << \"---- G_LLL_RR status ----\\n\";\n   cerr << \"elapsed time: \";\n   PrintTime(cerr, t-StartTime);\n   cerr << \", stage: \" << max_k;\n   cerr << \", rank: \" << m;\n   cerr << \", swaps: \" << NumSwaps << \"\\n\";\n\n   ZZ t1;\n   long i;\n   double prodlen = 0;\n\n   for (i = 1; i <= m; i++) {\n      InnerProduct(t1, B(i), B(i));\n      if (!IsZero(t1))\n         prodlen += log(t1);\n   }\n\n   cerr << \"log of prod of lengths: \" << prodlen/(2.0*log(2.0)) << \"\\n\";\n\n   if (LLLDumpFile) {\n      cerr << \"dumping to \" << LLLDumpFile << \"...\";\n\n      ofstream f;\n      OpenWrite(f, LLLDumpFile);\n      \n      f << \"[\";\n      for (i = 1; i <= m; i++) {\n         f << B(i) << \"\\n\";\n      }\n      f << \"]\\n\";\n\n      f.close();\n\n      cerr << \"\\n\";\n   }\n\n   LastTime = t;\n   \n}\n\n\n\nstatic\nlong ll_G_LLL_RR(mat_ZZ& B, mat_ZZ* U, const RR& delta, long deep, \n           LLLCheckFct check, mat_RR& B1, mat_RR& mu, \n           mat_RR& aux, long m, long init_k, long &quit,\n           GivensCache_RR& cache)\n{\n   long n = B.NumCols();\n\n   long i, j, k, Fc1;\n   ZZ MU;\n   RR mu1, t1, t2, cc;\n   ZZ T1;\n\n\n   quit = 0;\n   k = init_k;\n\n   long counter;\n\n   long trigger_index;\n   long small_trigger;\n   long cnt;\n\n   RR half;\n   conv(half,  0.5);\n   RR half_plus_fudge;\n   add(half_plus_fudge, half, red_fudge);\n\n   long max_k = 0;\n   double tt;\n\n   cache.flush();\n\n   while (k <= m) {\n\n      if (k > max_k) {\n         max_k = k;\n      }\n\n      if (verbose) {\n         tt = GetTime();\n\n         if (tt > LastTime + LLLStatusInterval)\n            G_LLLStatus(max_k, tt, m, B);\n      }\n\n      GivensComputeGS(B1, mu, aux, k, n, cache);\n\n      counter = 0;\n      trigger_index = k;\n      small_trigger = 0;\n      cnt = 0;\n\n      do {\n         // size reduction\n\n         counter++;\n         if (counter > 10000) {\n            cerr << \"G_LLL_XD: warning--possible infinite loop\\n\";\n            counter = 0;\n         }\n\n\n         Fc1 = 0;\n\n         for (j = k-1; j >= 1; j--) {\n            abs(t1, mu(k,j));\n            if (t1 > half_plus_fudge) {\n\n               if (!Fc1) {\n                  if (j > trigger_index ||\n                      (j == trigger_index && small_trigger)) {\n\n                     cnt++;\n\n                     if (cnt > 10) {\n                        inc_red_fudge();\n                        add(half_plus_fudge, half, red_fudge);\n                        cnt = 0;\n                     }\n                  }\n\n                  trigger_index = j;\n                  small_trigger = (t1 < 4);\n               }\n\n               Fc1 = 1;\n   \n               mu1 = mu(k,j);\n               if (sign(mu1) >= 0) {\n                  sub(mu1, mu1, half);\n                  ceil(mu1, mu1);\n               }\n               else {\n                  add(mu1, mu1, half);\n                  floor(mu1, mu1);\n               }\n\n               if (mu1 == 1) {\n                  for (i = 1; i <= j-1; i++)\n                     sub(mu(k,i), mu(k,i), mu(j,i));\n               }\n               else if (mu1 == -1) {\n                  for (i = 1; i <= j-1; i++)\n                     add(mu(k,i), mu(k,i), mu(j,i));\n               }\n               else {\n                  for (i = 1; i <= j-1; i++) {\n                     mul(t2, mu1, mu(j,i));\n                     sub(mu(k,i), mu(k,i), t2);\n                  }\n               }\n\n   \n               conv(MU, mu1);\n\n               sub(mu(k,j), mu(k,j), mu1);\n   \n               RowTransform(B(k), B(j), MU);\n               if (U) RowTransform((*U)(k), (*U)(j), MU);\n            }\n         }\n\n         if (Fc1) {\n            for (i = 1; i <= n; i++)\n               conv(B1(k, i), B(k, i));\n            cache.touch();\n            GivensComputeGS(B1, mu, aux, k, n, cache);\n         }\n      } while (Fc1);\n\n      if (check && (*check)(B(k))) \n         quit = 1;\n\n      if (IsZero(B(k))) {\n         for (i = k; i < m; i++) {\n            // swap i, i+1\n            swap(B(i), B(i+1));\n            swap(B1(i), B1(i+1));\n            if (U) swap((*U)(i), (*U)(i+1));\n         }\n\n         cache.flush();\n\n         m--;\n         if (quit) break;\n         continue;\n      }\n\n      if (quit) break;\n\n      if (deep > 0) {\n         // deep insertions\n   \n         Error(\"sorry...deep insertions not implemented\");\n\n      } // end deep insertions\n\n      // test G_LLL reduction condition\n\n      if (k <= 1) {\n         cache.incr();\n         k++;\n      }\n      else {\n         sqr(t1, mu(k,k-1));\n         sub(t1, delta, t1);\n         sqr(t2, mu(k-1,k-1));\n         mul(t1, t1, t2);\n         sqr(t2, mu(k, k));\n         if (t1 > t2) {\n            // swap rows k, k-1\n            swap(B(k), B(k-1));\n            swap(B1(k), B1(k-1));\n            if (U) swap((*U)(k), (*U)(k-1));\n\n            cache.swap();\n   \n            k--;\n            NumSwaps++;\n         }\n         else {\n            cache.incr();\n            k++;\n         }\n      }\n   }\n\n   if (verbose) {\n      G_LLLStatus(m+1, GetTime(), m, B);\n   }\n\n\n   return m;\n}\n\nstatic\nlong G_LLL_RR(mat_ZZ& B, mat_ZZ* U, const RR& delta, long deep, \n           LLLCheckFct check)\n{\n   long m = B.NumRows();\n   long n = B.NumCols();\n\n   long i, j;\n   long new_m, dep, quit;\n   RR s;\n   ZZ MU;\n   RR mu1;\n\n   RR t1;\n   ZZ T1;\n\n   init_red_fudge();\n\n   if (U) ident(*U, m);\n\n   mat_RR B1;  // approximates B\n   B1.SetDims(m, n);\n\n\n   mat_RR mu;\n   mu.SetDims(m, n+1);\n\n   mat_RR aux;\n   aux.SetDims(m, n);\n\n\n   for (i = 1; i <=m; i++)\n      for (j = 1; j <= n; j++) \n         conv(B1(i, j), B(i, j));\n\n   GivensCache_RR cache(m, n);\n\n   new_m = ll_G_LLL_RR(B, U, delta, deep, check, B1, mu, aux, m, 1, quit, cache);\n\n   dep = m - new_m;\n   m = new_m;\n\n   if (dep > 0) {\n      // for consistency, we move all of the zero rows to the front\n\n      for (i = 0; i < m; i++) {\n         swap(B(m+dep-i), B(m-i));\n         if (U) swap((*U)(m+dep-i), (*U)(m-i));\n      }\n   }\n\n\n   return m;\n}\n\n         \n\nlong G_LLL_RR(mat_ZZ& B, double delta, long deep, \n            LLLCheckFct check, long verb)\n{\n   verbose = verb;\n   NumSwaps = 0;\n   if (verbose) {\n      StartTime = GetTime();\n      LastTime = StartTime;\n   }\n\n   if (delta < 0.50 || delta >= 1) Error(\"G_LLL_RR: bad delta\");\n   if (deep < 0) Error(\"G_LLL_RR: bad deep\");\n   RR Delta;\n   conv(Delta, delta);\n   return G_LLL_RR(B, 0, Delta, deep, check);\n}\n\nlong G_LLL_RR(mat_ZZ& B, mat_ZZ& U, double delta, long deep, \n           LLLCheckFct check, long verb)\n{\n   verbose = verb;\n   NumSwaps = 0;\n   if (verbose) {\n      StartTime = GetTime();\n      LastTime = StartTime;\n   }\n\n   if (delta < 0.50 || delta >= 1) Error(\"G_LLL_RR: bad delta\");\n   if (deep < 0) Error(\"G_LLL_RR: bad deep\");\n   RR Delta;\n   conv(Delta, delta);\n   return G_LLL_RR(B, &U, Delta, deep, check);\n}\n\n\n\nstatic vec_RR G_BKZConstant;\n\nstatic\nvoid ComputeG_BKZConstant(long beta, long p)\n{\n   RR c_PI;\n   ComputePi(c_PI);\n\n   RR LogPI = log(c_PI);\n\n   G_BKZConstant.SetLength(beta-1);\n\n   vec_RR Log;\n   Log.SetLength(beta);\n\n\n   long i, j, k;\n   RR x, y;\n\n   for (j = 1; j <= beta; j++)\n      Log(j) = log(to_RR(j));\n\n   for (i = 1; i <= beta-1; i++) {\n      // First, we compute x = gamma(i/2)^{2/i}\n\n      k = i/2;\n\n      if ((i & 1) == 0) { // i even\n         x = 0;\n         for (j = 1; j <= k; j++)\n            x += Log(j);\n          \n         x = exp(x/k);\n\n      }\n      else { // i odd\n         x = 0;\n         for (j = k + 2; j <= 2*k + 2; j++)\n            x += Log(j);\n\n         x += 0.5*LogPI - 2*(k+1)*Log(2);\n\n         x = exp(2*x/i);\n      }\n\n      // Second, we compute y = 2^{2*p/i}\n\n      y = exp(-(2*p/to_RR(i))*Log(2));\n\n      G_BKZConstant(i) = x*y/c_PI;\n   }\n\n}\n\nstatic vec_RR G_BKZThresh;\n\nstatic \nvoid ComputeG_BKZThresh(RR *c, long beta)\n{\n   G_BKZThresh.SetLength(beta-1);\n\n   long i;\n   RR x;\n   RR t1;\n\n   x = 0;\n\n   for (i = 1; i <= beta-1; i++) {\n      log(t1, c[i-1]);\n      add(x, x, t1);\n      div(t1, x, i);\n      exp(t1, t1);\n      mul(G_BKZThresh(i), t1, G_BKZConstant(i));\n   }\n}\n\n\n\n\nstatic \nvoid G_BKZStatus(double tt, double enum_time, unsigned long NumIterations, \n               unsigned long NumTrivial, unsigned long NumNonTrivial, \n               unsigned long NumNoOps, long m, \n               const mat_ZZ& B)\n{\n   cerr << \"---- G_BKZ_RR status ----\\n\";\n   cerr << \"elapsed time: \";\n   PrintTime(cerr, tt-StartTime);\n   cerr << \", enum time: \";\n   PrintTime(cerr, enum_time);\n   cerr << \", iter: \" << NumIterations << \"\\n\";\n   cerr << \"triv: \" << NumTrivial;\n   cerr << \", nontriv: \" << NumNonTrivial;\n   cerr << \", no ops: \" << NumNoOps;\n   cerr << \", rank: \" << m;\n   cerr << \", swaps: \" << NumSwaps << \"\\n\";\n\n\n\n   ZZ t1;\n   long i;\n   double prodlen = 0;\n\n   for (i = 1; i <= m; i++) {\n      InnerProduct(t1, B(i), B(i));\n      if (!IsZero(t1))\n         prodlen += log(t1);\n   }\n\n   cerr << \"log of prod of lengths: \" << prodlen/(2.0*log(2.0)) << \"\\n\";\n\n\n   if (LLLDumpFile) {\n      cerr << \"dumping to \" << LLLDumpFile << \"...\";\n\n      ofstream f;\n      OpenWrite(f, LLLDumpFile);\n      \n      f << \"[\";\n      for (i = 1; i <= m; i++) {\n         f << B(i) << \"\\n\";\n      }\n      f << \"]\\n\";\n\n      f.close();\n\n      cerr << \"\\n\";\n   }\n\n   LastTime = tt;\n   \n}\n\n\n\n\nstatic\nlong G_BKZ_RR(mat_ZZ& BB, mat_ZZ* UU, const RR& delta, \n         long beta, long prune, LLLCheckFct check)\n{\n   long m = BB.NumRows();\n   long n = BB.NumCols();\n   long m_orig = m;\n   \n   long i, j;\n   ZZ MU;\n\n   RR t1, t2;\n   ZZ T1;\n\n   init_red_fudge();\n\n   mat_ZZ B;\n   B = BB;\n\n   B.SetDims(m+1, n);\n\n\n   mat_RR B1;\n   B1.SetDims(m+1, n);\n\n   mat_RR mu;\n   mu.SetDims(m+1, n+1);\n\n   mat_RR aux;\n   aux.SetDims(m+1, n);\n\n   vec_RR c;\n   c.SetLength(m+1);\n\n   RR cbar;\n\n   vec_RR ctilda;\n   ctilda.SetLength(m+1);\n\n   vec_RR vvec;\n   vvec.SetLength(m+1);\n\n   vec_RR yvec;\n   yvec.SetLength(m+1);\n\n   vec_RR uvec;\n   uvec.SetLength(m+1);\n\n   vec_RR utildavec;\n   utildavec.SetLength(m+1);\n\n   vec_long Deltavec;\n   Deltavec.SetLength(m+1);\n\n   vec_long deltavec;\n   deltavec.SetLength(m+1);\n\n   mat_ZZ Ulocal;\n   mat_ZZ *U;\n\n   if (UU) {\n      Ulocal.SetDims(m+1, m);\n      for (i = 1; i <= m; i++)\n         conv(Ulocal(i, i), 1);\n      U = &Ulocal;\n   }\n   else\n      U = 0;\n\n   long quit;\n   long new_m;\n   long z, jj, kk;\n   long s, t;\n   long h;\n\n\n   for (i = 1; i <=m; i++)\n      for (j = 1; j <= n; j++) \n         conv(B1(i, j), B(i, j));\n\n   // cerr << \"\\n\";\n   // cerr << \"first G_LLL\\n\";\n\n   GivensCache_RR cache(m, n);\n\n   m = ll_G_LLL_RR(B, U, delta, 0, check, B1, mu, aux, m, 1, quit, cache);\n\n\n   double tt;\n\n   double enum_time = 0;\n   unsigned long NumIterations = 0;\n   unsigned long NumTrivial = 0;\n   unsigned long NumNonTrivial = 0;\n   unsigned long NumNoOps = 0;\n\n   long verb = verbose;\n\n   verbose = 0;\n\n\n   if (m < m_orig) {\n      for (i = m_orig+1; i >= m+2; i--) {\n         // swap i, i-1\n\n         swap(B(i), B(i-1));\n         if (U) swap((*U)(i), (*U)(i-1));\n      }\n   }\n\n   long clean = 1;\n\n   if (!quit && m > 1) {\n      // cerr << \"continuing\\n\";\n\n      if (beta > m) beta = m;\n\n      if (prune > 0)\n         ComputeG_BKZConstant(beta, prune);\n\n      z = 0;\n      jj = 0;\n   \n      while (z < m-1) {\n         jj++;\n         kk = min(jj+beta-1, m);\n   \n         if (jj == m) {\n            jj = 1;\n            kk = beta;\n            clean = 1;\n         }\n\n         if (verb) {\n            tt = GetTime();\n            if (tt > LastTime + LLLStatusInterval)\n               G_BKZStatus(tt, enum_time, NumIterations, NumTrivial,\n                         NumNonTrivial, NumNoOps, m, B);\n         }\n\n         // ENUM\n\n         double tt1;\n\n         if (verb) {\n            tt1 = GetTime();\n         }\n\n         for (i = jj; i <= kk; i++)\n            sqr(c(i), mu(i,i));\n\n\n         if (prune > 0)\n            ComputeG_BKZThresh(&c(jj), kk-jj+1);\n\n         cbar = c(jj);\n         conv(utildavec(jj), 1);\n         conv(uvec(jj), 1);\n   \n         conv(yvec(jj), 0);\n         conv(vvec(jj), 0);\n         Deltavec(jj) = 0;\n   \n   \n         s = t = jj;\n         deltavec(jj) = 1;\n   \n         for (i = jj+1; i <= kk+1; i++) {\n            conv(ctilda(i), 0);\n            conv(uvec(i), 0);\n            conv(utildavec(i), 0);\n            conv(yvec(i), 0);\n            Deltavec(i) = 0;\n            conv(vvec(i), 0);\n            deltavec(i) = 1;\n         }\n\n         long enum_cnt = 0;\n   \n         while (t <= kk) {\n            if (verb) {\n               enum_cnt++;\n               if (enum_cnt > 100000) {\n                  enum_cnt = 0;\n                  tt = GetTime();\n                  if (tt > LastTime + LLLStatusInterval) {\n                     enum_time += tt - tt1;\n                     tt1 = tt;\n                     G_BKZStatus(tt, enum_time, NumIterations, NumTrivial,\n                               NumNonTrivial, NumNoOps, m, B);\n                  }\n               }\n            }\n\n\n            add(t1, yvec(t), utildavec(t));\n            sqr(t1, t1);\n            mul(t1, t1, c(t));\n            add(ctilda(t), ctilda(t+1), t1);\n\n            if (prune > 0 && t > jj) \n               sub(t1, cbar, G_BKZThresh(t-jj));\n            else\n               t1 = cbar;\n\n   \n            if (ctilda(t) <t1) {\n               if (t > jj) {\n                  t--;\n                  clear(t1);\n                  for (i = t+1; i <= s; i++) {\n                     mul(t2, utildavec(i), mu(i,t));\n                     add(t1, t1, t2);\n                  }\n\n                  yvec(t) = t1;\n                  negate(t1, t1);\n                  if (sign(t1) >= 0) {\n                     sub(t1, t1, 0.5);\n                     ceil(t1, t1);\n                  }\n                  else {\n                     add(t1, t1, 0.5);\n                     floor(t1, t1);\n                  }\n\n                  utildavec(t) = t1;\n                  vvec(t) = t1;\n                  Deltavec(t) = 0;\n\n                  negate(t1, t1);\n\n                  if (t1 < yvec(t)) \n                     deltavec(t) = -1;\n                  else\n                     deltavec(t) = 1;\n               }\n               else {\n                  cbar = ctilda(jj);\n                  for (i = jj; i <= kk; i++) {\n                     uvec(i) = utildavec(i);\n                  }\n               }\n            }\n            else {\n               t++;\n               s = max(s, t);\n               if (t < s) Deltavec(t) = -Deltavec(t);\n               if (Deltavec(t)*deltavec(t) >= 0) Deltavec(t) += deltavec(t);\n               add(utildavec(t), vvec(t), Deltavec(t));\n            }\n         }\n         \n         if (verb) {\n            tt1 = GetTime() - tt1;\n            enum_time += tt1;\n         }\n\n         NumIterations++;\n   \n         h = min(kk+1, m);\n\n         mul(t1, red_fudge, -8);\n         add(t1, t1, delta);\n         mul(t1, t1, c(jj));\n   \n         if (t1 > cbar) {\n \n            clean = 0;\n\n            // we treat the case that the new vector is b_s (jj < s <= kk)\n            // as a special case that appears to occur most of the time.\n   \n            s = 0;\n            for (i = jj+1; i <= kk; i++) {\n               if (uvec(i) != 0) {\n                  if (s == 0)\n                     s = i;\n                  else\n                     s = -1;\n               }\n            }\n   \n            if (s == 0) Error(\"G_BKZ_RR: internal error\");\n   \n            if (s > 0) {\n               // special case\n               // cerr << \"special case\\n\";\n\n               NumTrivial++;\n   \n               for (i = s; i > jj; i--) {\n                  // swap i, i-1\n                  swap(B(i-1), B(i));\n                  swap(B1(i-1), B1(i));\n                  if (U) swap((*U)(i-1), (*U)(i));\n               }\n   \n               new_m = ll_G_LLL_RR(B, U, delta, 0, check,\n                                B1, mu, aux, h, jj, quit, cache);\n               if (new_m != h) Error(\"G_BKZ_RR: internal error\");\n               if (quit) break;\n            }\n            else {\n               // the general case\n\n               NumNonTrivial++;\n   \n               for (i = 1; i <= n; i++) conv(B(m+1, i), 0);\n\n               if (U) {\n                  for (i = 1; i <= m_orig; i++)\n                     conv((*U)(m+1, i), 0);\n               }\n\n               for (i = jj; i <= kk; i++) {\n                  if (uvec(i) == 0) continue;\n                  conv(MU, uvec(i));\n                  RowTransform2(B(m+1), B(i), MU);\n                  if (U) RowTransform2((*U)(m+1), (*U)(i), MU);\n               }\n      \n               for (i = m+1; i >= jj+1; i--) {\n                  // swap i, i-1\n                  swap(B(i-1), B(i));\n                  swap(B1(i-1), B1(i));\n                  if (U) swap((*U)(i-1), (*U)(i));\n               }\n      \n               for (i = 1; i <= n; i++)\n                  conv(B1(jj, i), B(jj, i));\n      \n               if (IsZero(B(jj))) Error(\"G_BKZ_RR: internal error\"); \n      \n               // remove linear dependencies\n   \n               // cerr << \"general case\\n\";\n               new_m = ll_G_LLL_RR(B, U, delta, 0, 0, B1, mu, aux,\n                                  kk+1, jj, quit, cache);\n\n              \n               if (new_m != kk) Error(\"G_BKZ_RR: internal error\"); \n\n               // remove zero vector\n      \n               for (i = kk+2; i <= m+1; i++) {\n                  // swap i, i-1\n                  swap(B(i-1), B(i));\n                  swap(B1(i-1), B1(i));\n                  if (U) swap((*U)(i-1), (*U)(i));\n               }\n      \n               quit = 0;\n               if (check) {\n                  for (i = 1; i <= kk; i++)\n                     if ((*check)(B(i))) {\n                        quit = 1;\n                        break;\n                     }\n               }\n\n               if (quit) break;\n   \n               if (h > kk) {\n                  // extend reduced basis\n   \n                  new_m = ll_G_LLL_RR(B, U, delta, 0, check,\n                                   B1, mu, aux, h, h, quit, cache);\n   \n                  if (new_m != h) Error(\"G_BKZ_RR: internal error\");\n                  if (quit) break;\n               }\n            }\n   \n            z = 0;\n         }\n         else {\n            // G_LLL_RR\n            // cerr << \"progress\\n\";\n\n            NumNoOps++;\n\n            if (!clean) {\n               new_m = ll_G_LLL_RR(B, U, delta, 0, check, B1, mu, aux,\n                                   h, h, quit, cache);\n               if (new_m != h) Error(\"G_BKZ_RR: internal error\");\n               if (quit) break;\n            }\n   \n            z++;\n         }\n      }\n   }\n\n   if (verb) {\n      G_BKZStatus(GetTime(), enum_time, NumIterations, NumTrivial, NumNonTrivial,\n                NumNoOps, m, B);\n   }\n\n\n   // clean up\n\n   if (m_orig > m) {\n      // for consistency, we move zero vectors to the front\n\n      for (i = m+1; i <= m_orig; i++) {\n         swap(B(i), B(i+1));\n         if (U) swap((*U)(i), (*U)(i+1));\n      }\n\n      for (i = 0; i < m; i++) {\n         swap(B(m_orig-i), B(m-i));\n         if (U) swap((*U)(m_orig-i), (*U)(m-i));\n      }\n   }\n\n   B.SetDims(m_orig, n);\n   BB = B;\n\n   if (U) {\n      U->SetDims(m_orig, m_orig);\n      *UU = *U;\n   }\n\n   return m;\n}\n\nlong G_BKZ_RR(mat_ZZ& BB, mat_ZZ& UU, double delta, \n         long beta, long prune, LLLCheckFct check, long verb)\n{\n   verbose = verb;\n   NumSwaps = 0;\n   if (verbose) {\n      StartTime = GetTime();\n      LastTime = StartTime;\n   }\n\n   if (delta < 0.50 || delta >= 1) Error(\"G_BKZ_RR: bad delta\");\n   if (beta < 2) Error(\"G_BKZ_RR: bad block size\");\n\n   RR Delta;\n   conv(Delta, delta);\n\n   return G_BKZ_RR(BB, &UU, Delta, beta, prune, check);\n}\n\nlong G_BKZ_RR(mat_ZZ& BB, double delta, \n         long beta, long prune, LLLCheckFct check, long verb)\n{\n   verbose = verb;\n   NumSwaps = 0;\n   if (verbose) {\n      StartTime = GetTime();\n      LastTime = StartTime;\n   }\n\n   if (delta < 0.50 || delta >= 1) Error(\"G_BKZ_RR: bad delta\");\n   if (beta < 2) Error(\"G_BKZ_RR: bad block size\");\n\n   RR Delta;\n   conv(Delta, delta);\n\n   return G_BKZ_RR(BB, 0, Delta, beta, prune, check);\n}\n\n\nNTL_END_IMPL\n", "meta": {"hexsha": "d2f0f9776715aa0bf3421f1d9eba9552246cd270", "size": 26859, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "RUNETag/WinNTL/src/G_LLL_RR.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/G_LLL_RR.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/G_LLL_RR.cpp", "max_forks_repo_name": "vshesh/RUNEtag", "max_forks_repo_head_hexsha": "800e93fb7c0560ea5a6261ffc60c02638a8cc8c9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2016-07-02T12:59:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-02T14:58:30.000Z", "avg_line_length": 19.7347538575, "max_line_length": 81, "alphanum_fraction": 0.3969991437, "num_tokens": 8671, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.4866862468833519}}
{"text": "#include <module_Preprocessing/Preprocessor.h>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <math.h>\n\nusing namespace cv;\nusing namespace boost::numeric::ublas;\nusing namespace std;\n\nPreprocessor::Preprocessor()\n{\n}\n\nMat Preprocessor::doPreprocessing(cv::Mat img){\n\n    Mat rgbImg = img.clone();\n    Mat ycbcrImg;\n\n    // Convert original image to YCbCr color space\n    cvtColor(rgbImg, ycbcrImg, CV_RGB2YCrCb);\n\n    // Parameters of the skin-color modell\n    double c11 = 0.0479;\n    double c12 = 0.0259;\n    double c21 = 0.0259;\n    double c22 = 0.0212;\n\n    double k1 = 0.0;\n    double k2 = 0.0;\n    double x1, x2;\n    double m1 = 113.9454;\n    double m2 = 157.5052;\n    double f1, f2;\n\n\n    Mat thresholded(ycbcrImg.size(), CV_8UC1);\n    thresholded.setTo(Scalar(0));\n\n    //Segmenting the hand\n    double p = 0;\n\n    for (int i = 0; i < ycbcrImg.rows; ++i){\n        for (int j = 0; j < ycbcrImg.cols; ++j){\n\n            x1 = (int)ycbcrImg.at<Vec3b>(i, j)[1];\n            x2 = (int)ycbcrImg.at<Vec3b>(i, j)[2];\n\n                f1 = -0.5*(x1 - m1);\n                f2 = -0.5*(x2 - m2);\n                k1 = f1*c11 + f2*c21;\n                k2 = f1*c12 + f2*c22;\n\n                // Probability of the pixel that belongs to a skin region\n                p = exp(k1*(x1 - m1) + k2*(x2 - m2));\n\n\n                if (p > 0.15){\n                    thresholded.at<uchar>(i, j) = 255;\n                }\n        }\n    }\n\n    return thresholded;\n}\n\n\nPreprocessor::~Preprocessor()\n{\n}\n", "meta": {"hexsha": "59d6d6eef78e167fa9fb0208e64036a23d0d377b", "size": 1524, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "module_Preprocessing/Preprocessor.cpp", "max_stars_repo_name": "szaboa/PalmPrintAuthentication", "max_stars_repo_head_hexsha": "c6db7eca0511c11b01097d46f0217443fa88117b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2016-04-15T16:16:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-14T08:37:58.000Z", "max_issues_repo_path": "module_Preprocessing/Preprocessor.cpp", "max_issues_repo_name": "kobeonetow/PalmPrintAuthentication", "max_issues_repo_head_hexsha": "c6db7eca0511c11b01097d46f0217443fa88117b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-03-14T18:50:22.000Z", "max_issues_repo_issues_event_max_datetime": "2018-04-15T11:14:02.000Z", "max_forks_repo_path": "module_Preprocessing/Preprocessor.cpp", "max_forks_repo_name": "kobeonetow/PalmPrintAuthentication", "max_forks_repo_head_hexsha": "c6db7eca0511c11b01097d46f0217443fa88117b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2016-01-26T06:47:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-22T07:13:22.000Z", "avg_line_length": 21.7714285714, "max_line_length": 73, "alphanum_fraction": 0.5492125984, "num_tokens": 496, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.48668624249793274}}
{"text": "#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE ToTConverterTest\n\n#include <boost/test/unit_test.hpp>\n#include \"JPetLoggerInclude.h\"\n#include \"../ToTConverter.h\"\nusing namespace jpet_common_tools;\n\n/// Returns Time-over-threshold for given deposited energy\n/// the current parametrization is par1 + par2 * eDep\n/// Returned value in ps, and eDep is given in keV.\ndouble getToT1(double eDep, double  par1 = -91958, double par2 = 19341)\n{\n  if (eDep < 0 ) return 0;\n  double value = par1 + eDep * par2;\n  return value;\n}\n\nBOOST_AUTO_TEST_SUITE(ToTConverterTestSuite)\n\nBOOST_AUTO_TEST_CASE(getTot_standardFunc)\n{\n  JPetCachedFunctionParams params(\"pol1\", {-91958, 19341});\n  ToTConverter conv(params, Range(10000, 0., 100.));\n  BOOST_CHECK_CLOSE(conv(0), getToT1(0), 0.1);\n  BOOST_CHECK_CLOSE(conv(1), getToT1(1), 0.1);\n  BOOST_CHECK_CLOSE(conv(10), getToT1(10), 0.1);\n  BOOST_CHECK_CLOSE(conv(59.5), getToT1(59.5), 0.1);\n  BOOST_CHECK_CLOSE(conv(99.9), getToT1(99.9), 0.1);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "c40ea9196b5719a5db2b4b3396ad483a4fbbf3d3", "size": 1009, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "LargeBarrelAnalysis/tests/ToTConverterTest.cpp", "max_stars_repo_name": "pnp-sushil/j-pet-framework-examples", "max_stars_repo_head_hexsha": "2d3f3aba1064bfb215179f88be9c2bf383851deb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "LargeBarrelAnalysis/tests/ToTConverterTest.cpp", "max_issues_repo_name": "pnp-sushil/j-pet-framework-examples", "max_issues_repo_head_hexsha": "2d3f3aba1064bfb215179f88be9c2bf383851deb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LargeBarrelAnalysis/tests/ToTConverterTest.cpp", "max_forks_repo_name": "pnp-sushil/j-pet-framework-examples", "max_forks_repo_head_hexsha": "2d3f3aba1064bfb215179f88be9c2bf383851deb", "max_forks_repo_licenses": ["Apache-2.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.5757575758, "max_line_length": 71, "alphanum_fraction": 0.7403369673, "num_tokens": 320, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.48668624249793274}}
{"text": "#include <cstdlib>\n#include <iostream>\n#include <complex>\n#define BOOST_UBLAS_NO_ELEMENT_PROXIES\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/triangular.hpp>\n#include <boost/numeric/bindings/ublas/matrix.hpp>\n#include <boost/numeric/bindings/blas/level3.hpp>\n#include <boost/numeric/bindings/lower.hpp>\n#include <boost/numeric/bindings/upper.hpp>\n#include <boost/numeric/bindings/unit_lower.hpp>\n#include <boost/numeric/bindings/unit_upper.hpp>\n#include <boost/numeric/bindings/left.hpp>\n#include <boost/numeric/bindings/right.hpp>\n#include <boost/numeric/bindings/trans.hpp>\n#include <boost/numeric/bindings/conj.hpp>\n#include \"print.hpp\"\n#include \"random.hpp\"\n\nnamespace ublas=boost::numeric::ublas;\nnamespace blas=boost::numeric::bindings::blas;\n\nint main(int argc, char *argv[]) {\n  {\n    typedef std::complex<double> complex;\n    typedef ublas::matrix<complex, ublas::column_major> matrix;\n    typedef typename matrix::size_type size_type;\n    rand_normal<complex>::reset();\n    size_type n=8, m=2;\n    matrix A_l(n, n);\n    matrix A_u(n, n);\n    for (size_type j=0; j<n; ++j) {\n      for (size_type i=0; i<j; ++i) {\n    \tA_u(i, j)=rand_normal<complex>::get();\n\tA_l(j, i)=rand_normal<complex>::get();\n      }\n      A_u(j, j)=rand_normal<complex>::get();\n      A_l(j, j)=rand_normal<complex>::get();\n      for (size_type i=j+1; i<n; ++i) {\n    \tA_u(i, j)=0;\n\tA_l(j, i)=0;\n      }\n    }\n    matrix B(n, m);\n    for (size_type j=0; j<m; ++j)\n      for (size_type i=0; i<n; ++i)\n\tB(i, j)=rand_normal<complex>::get();\n    complex alpha=rand_normal<complex>::get();\n    {\n      matrix B1(B);\n      for (size_type j=0; j<m; ++j) {\n\tublas::matrix_column<matrix> b(B1, j);\n\tublas::inplace_solve(A_l, b, ublas::lower_tag());\n\tb*=alpha;\n      }\n      matrix B2(B);\n      blas::trsm(blas::left(), alpha, blas::lower(A_l), B2);\n      std::cout << \"testing boost::ublas containers\\n\"\n    \t\t<< \"using ublas (left, lower):\\n\" << print_mat(B1) << '\\n'\n    \t\t<< \"using blas  (left, lower):\\n\" << print_mat(B2) << '\\n'\n     \t\t<< '\\n';\n    }\n    {\n      matrix B1(B);\n      for (size_type j=0; j<m; ++j) {\n\tublas::matrix_column<matrix> b(B1, j);\n\tublas::inplace_solve(A_u, b, ublas::upper_tag());\n\tb*=alpha;\n      }\n      matrix B2(B);\n      blas::trsm(blas::left(), alpha, blas::upper(A_u), B2);\n      std::cout << \"testing boost::ublas containers\\n\"\n    \t\t<< \"using ublas (left, upper):\\n\" << print_mat(B1) << '\\n'\n    \t\t<< \"using blas  (left, upper):\\n\" << print_mat(B2) << '\\n'\n     \t\t<< '\\n';\n    }\n  }\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "a1ac4ead9203b943ffcea32803b39ed6f253b4b4", "size": 2593, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/blas/trsm.cc", "max_stars_repo_name": "rabauke/numeric_bindings", "max_stars_repo_head_hexsha": "f4de93bd7a01a8b31c9367fad35c81d086768f99", "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/blas/trsm.cc", "max_issues_repo_name": "rabauke/numeric_bindings", "max_issues_repo_head_hexsha": "f4de93bd7a01a8b31c9367fad35c81d086768f99", "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/blas/trsm.cc", "max_forks_repo_name": "rabauke/numeric_bindings", "max_forks_repo_head_hexsha": "f4de93bd7a01a8b31c9367fad35c81d086768f99", "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.012345679, "max_line_length": 64, "alphanum_fraction": 0.6236020054, "num_tokens": 803, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568416, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.48668624042309677}}
{"text": "//!\n//! Contains the implementation for creating grids.\n//!\n//! \\file world/grid.cpp\n//! \\author Alistair Reid\n//! \\author Darren Shen\n//! \\date 2014\n//! \\license Affero General Public License version 3 or later\n//! \\copyright (c) 2014, NICTA\n//!\n\n#include \"world/grid.hpp\"\n\n#include <Eigen/Dense>\n#include <Eigen/Core>\n\nnamespace obsidian\n{\n  namespace world\n  {\n    Eigen::MatrixXd sensorGrid(const WorldSpec& worldSpec, uint resx, uint resy, double sensorZ)\n    {\n        Eigen::MatrixXd xyLocations = world::internalGrid2D(worldSpec.xBounds, worldSpec.yBounds, resx, resy);\n        Eigen::MatrixXd xyzLocations = Eigen::MatrixXd(xyLocations.rows(), 3);\n        xyzLocations.leftCols<2>() = xyLocations;\n        xyzLocations.col(2).fill(sensorZ);\n        return xyzLocations;\n    }\n\n    Eigen::MatrixXd internalGrid2D(std::pair<double,double> xMinMax, std::pair<double,double> yMinMax, uint resx, uint resy)\n    {\n      double xmin = xMinMax.first;\n      double xmax = xMinMax.second;\n      double ymin = yMinMax.first;\n      double ymax = yMinMax.second;\n      double deltax = xmax - xmin;\n      double deltay = ymax - ymin;\n      Eigen::MatrixXd xyLocations(resx*resy, 2);\n      uint c = 0;\n      for (uint j = 0; j < resy; j++)\n      {\n        for (uint i = 0; i < resx; i++)\n        {\n          double xLoc = xmin + deltax * ((double)i + 0.5) / (double)resx;\n          double yLoc = ymin + deltay * ((double)j + 0.5) / (double)resy;\n          xyLocations(c,0) = xLoc;\n          xyLocations(c,1) = yLoc;\n          c++;\n        }\n      }\n\n      return xyLocations;\n    }\n\n    Eigen::MatrixXd internalGrid2DX(std::pair<double,double> xMinMax, std::pair<double,double> yMinMax, uint resx, uint resy)\n    {\n      double xmin = xMinMax.first;\n      double xmax = xMinMax.second;\n      double ymin = yMinMax.first;\n      double ymax = yMinMax.second;\n      double deltax = xmax - xmin;\n      double deltay = ymax - ymin;\n      Eigen::MatrixXd xyLocations(resx*resy, 2);\n      uint c = 0;\n\n      for (uint i = 0; i < resx; i++)\n      {\n        for (uint j = 0; j < resy; j++)\n        {\n          double xLoc = xmin + deltax * ((double)i + 0.5) / (double)resx;\n          double yLoc = ymin + deltay * ((double)j + 0.5) / (double)resy;\n          xyLocations(c,0) = xLoc;\n          xyLocations(c,1) = yLoc;\n          c++;\n        }\n      }\n\n      return xyLocations;\n    }\n\n    Eigen::MatrixXd edgeGrid2D(std::pair<double, double> xMinMax, std::pair<double, double> yMinMax,\n        uint resx, uint resy)\n    {\n      double xmin = xMinMax.first;\n      double xmax = xMinMax.second;\n      double ymin = yMinMax.first;\n      double ymax = yMinMax.second;\n      double deltax = xmax - xmin;\n      double deltay = ymax - ymin;\n      Eigen::MatrixXd xyLocations(resx*resy, 2);\n      uint c = 0;\n      for (uint j = 0; j < resy; j++)\n      {\n        for (uint i = 0; i < resx; i++)\n        {\n          double xLoc = xmin + deltax * (double)i/(double)(resx-1);\n          double yLoc = ymin + deltay * (double)j/(double)(resy-1);\n          xyLocations(c,0) = xLoc;\n          xyLocations(c,1) = yLoc;\n          c++;\n        }\n      }\n\n      return xyLocations;\n    }\n\n    Eigen::MatrixXd sensorGrid3d(const WorldSpec& worldSpec, uint resx, uint resy, uint resz)\n    {\n      double xmin = worldSpec.xBounds.first;\n      double xmax = worldSpec.xBounds.second;\n      double ymin = worldSpec.yBounds.first;\n      double ymax = worldSpec.yBounds.second;\n      double zmin = worldSpec.zBounds.first;\n      double zmax = worldSpec.zBounds.second;\n      double deltax = xmax - xmin;\n      double deltay = ymax - ymin;\n      double deltaz = zmax - zmin;\n\n      Eigen::MatrixXd xyzLocations(resx*resy*resz, 3);\n      uint c = 0;\n      for (uint i = 0; i < resx; i++)\n      {\n        for (uint j = 0; j < resy; j++)\n        {\n          for (uint k = 0; k < resz; k++)\n          {\n            double xLoc = xmin + deltax * ((double)i + 0.5) / (double)resx;\n            double yLoc = ymin + deltay * ((double)j + 0.5) / (double)resy;\n            double zLoc = zmin + deltaz * ((double)k + 0.5) / (double)resz;\n            xyzLocations(c,0) = xLoc;\n            xyzLocations(c,1) = yLoc;\n            xyzLocations(c,2) = zLoc;\n            c++;\n          }\n        }\n      }\n\n      return xyzLocations;\n    }\n\n    double length(const Eigen::Vector2d &pt)\n    {\n      return pt(1) - pt(0);\n    }\n\n    Eigen::VectorXd linrange(double from, double to, double step)\n    {\n      int size = std::floor((to - from) / step) + 1;\n      Eigen::VectorXd result(size);\n      for (int i = 0; i < result.rows(); i++)\n        result(i) = from + (i * step);\n      return result;\n    }\n\n    std::pair<Eigen::MatrixXd, Eigen::MatrixXd> meshgrid(const Eigen::VectorXd &x, const Eigen::VectorXd &y)\n    {\n      // Courtesy of: http://forum.kde.org/viewtopic.php?f=74&t=90876\n      return std::pair<Eigen::MatrixXd, Eigen::MatrixXd>(x.transpose().replicate(y.rows(), 1), y.replicate(1, x.rows()));\n    }\n\n    Eigen::VectorXd flatten(const Eigen::MatrixXd& matrix)\n    {\n      Eigen::MatrixXd res(matrix);\n      res.resize(matrix.rows() * matrix.cols(), 1);\n      return res;\n    }\n\n    Eigen::VectorXi flatten(const Eigen::MatrixXi &matrix)\n    {\n      Eigen::MatrixXi res(matrix);\n      res.resize(matrix.rows() * matrix.cols(), 1);\n      return res;\n    }\n\n    std::pair<Eigen::MatrixXd, std::pair<Eigen::MatrixXd, Eigen::MatrixXd>>\n    makeGrid(const Eigen::Vector2d &boundaryStart, const Eigen::Vector2d &boundaryEnd,\n      const Eigen::Vector2i &resolution, int padding)\n    {\n      padding = 0;\n\n      // assert(spacing.min() > 0)\n      Eigen::Vector2d spacing = (boundaryEnd - boundaryStart).array() /\n        (resolution.array() - 1 - 2 * padding).cast<double>();\n\n      // Handle 1 control point using the midpoint of the boundaries\n      Eigen::VectorXd linX = resolution(0) == 1 ?\n        Eigen::VectorXd::Ones(1) * ((boundaryStart(0) + boundaryEnd(0)) / 2) :\n        linrange(boundaryStart(0) - spacing(0) * padding, boundaryEnd(0) + spacing(0) * padding,\n          spacing(0));\n\n      Eigen::VectorXd linY = resolution(1) == 1 ?\n        Eigen::VectorXd::Ones(1) * ((boundaryStart(1) + boundaryEnd(1)) / 2) :\n        linrange(boundaryStart(1) - spacing(1) * padding, boundaryEnd(1) + spacing(1) * padding,\n          spacing(1));\n\n      // Get the mesh grid\n      auto mesh = meshgrid(linX, linY);\n      \n      // We return the mesh as a N*2 matrix, where the first column contains \n      // the values of the flattened X coordinates and second column contains\n      // the flattened Y coordinates.\n      Eigen::MatrixXd flattenedMesh(linX.rows() * linY.rows(), 2);\n      flattenedMesh.col(0) << flatten(mesh.first);\n      flattenedMesh.col(1) << flatten(mesh.second);\n\n      return std::make_pair(flattenedMesh, std::make_pair(linX, linY));\n    }\n  }\n}\n", "meta": {"hexsha": "0c194539aeb2dbd3a263f18bac0ae7c96fdf970e", "size": 6815, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/world/grid.cpp", "max_stars_repo_name": "divad-nhok/obsidian_fork", "max_stars_repo_head_hexsha": "e5bee2b706f78249564f06c88a18be086b17c895", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2015-01-04T13:50:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-22T01:03:57.000Z", "max_issues_repo_path": "src/world/grid.cpp", "max_issues_repo_name": "divad-nhok/obsidian_fork", "max_issues_repo_head_hexsha": "e5bee2b706f78249564f06c88a18be086b17c895", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-08-16T00:46:58.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-16T00:46:58.000Z", "max_forks_repo_path": "src/world/grid.cpp", "max_forks_repo_name": "divad-nhok/obsidian_fork", "max_forks_repo_head_hexsha": "e5bee2b706f78249564f06c88a18be086b17c895", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2016-08-31T05:42:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-21T21:37:47.000Z", "avg_line_length": 32.4523809524, "max_line_length": 125, "alphanum_fraction": 0.5800440205, "num_tokens": 1907, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.48668623603767797}}
{"text": "#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 <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_real_distribution.hpp>\n#include <boost/math/special_functions/erf.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/math/special_functions/beta.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        if (Comm.MyPID()==0){\n            paramList->print(std::cout,2,true,true);\n        }\n    }\n\n    double a = -6.0;\n    double b = 6.0;\n    int n = 10;\n    double v;\n\n    double alpha = 1.0/(0.1*0.1);\n    double beta  = 1771.0*0.1*0.1;\n    for (int i=0; i<n; ++i){\n       v = a + (b-a)*double(i)/double(n-1);\n       double erfx = boost::math::erf<double>(v/std::sqrt(2.0));\n       double y = (1.0/2.0)*(1.0 + erfx);\n       double yinv = boost::math::gamma_p_inv<double,double>(alpha,y);\n       double g = yinv*beta;\n\n       std::cout << v << std::setw(15) << g << \"\\n\";\n    }\n\n    /*double mean = 0.0;\n    double stan = 1.0;\n    boost::random::normal_distribution<> w(mean,stan);\n    boost::random::mt19937 rng;\n    rng.seed(std::time(0));\n    for (unsigned int i=0; i<10; ++i){\n        double x = w(rng);\n        double erfarg = (x-mean)/(stan*std::sqrt(2.0));\n        double erfx = boost::math::erf<double>(erfarg);\n        double y = (1.0/2.0)*(1.0 + erfx);\n        double yinv = boost::math::gamma_p_inv<double,double>(1.0/(0.1*0.1),y);\n        double z = yinv*10.0*0.1*0.1;\n        double z2 = boost::math::ibeta_inv<double,double,double>(5.0,4.0,y);\n        std::cout << x << std::setw(20) << y << std::setw(20) << z << std::setw(20) << z2 << \"\\n\";\n    }*/\n\n\n#ifdef HAVE_MPI\n    MPI_Finalize();\n#endif\nreturn 0;\n\n}\n", "meta": {"hexsha": "0a388fa4dd83d2f8fe4ebdba6c80dddf816c2ffe", "size": 2887, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/boost_icdf/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": "examples/boost_icdf/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": "examples/boost_icdf/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": 31.0430107527, "max_line_length": 98, "alphanum_fraction": 0.6359542778, "num_tokens": 857, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.4866862360376779}}
{"text": "// -------------------------------------------------------------------------------------------------\n//                              Copyright 2016 - NumScale SAS\n//\n//                   Distributed under the Boost Software License, Version 1.0.\n//                        See accompanying file LICENSE.txt or copy at\n//                            http://www.boost.org/LICENSE_1_0.txt\n// -------------------------------------------------------------------------------------------------\n\n/// bench for functor is_not_less_equal in simd mode for float type with no decorator (regular call).\n#include <simd_bench.hpp>\n#include <boost/simd/function/is_not_less_equal.hpp>\n\nnamespace nsb = ns::bench;\nnamespace bs =  boost::simd;\n\nDEFINE_BENCH_MAIN()\n{\n  using T = bs::pack<float>;\n  run<T>(bs::is_not_less_equal, nsbg::rand<T>(-10, 10), nsbg::rand<T>(-10, 10));\n}\n", "meta": {"hexsha": "4f3954f77928602f34b90e4cf758d10f617fbf3e", "size": 859, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bench/function/simd/is_not_less_equal/regular.float.m10_10_m10_10.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": "bench/function/simd/is_not_less_equal/regular.float.m10_10_m10_10.cpp", "max_issues_repo_name": "remymuller/boost.simd", "max_issues_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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": "bench/function/simd/is_not_less_equal/regular.float.m10_10_m10_10.cpp", "max_forks_repo_name": "remymuller/boost.simd", "max_forks_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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": 40.9047619048, "max_line_length": 101, "alphanum_fraction": 0.470314319, "num_tokens": 165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.4866862251920037}}
{"text": "//\n//  parameters.cpp\n//\n//  Created by Anton Leuski on 2/17/12.\n//  Copyright (c) 2015 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#include <sstream>\n#include <random>\n\n#include <jerome/type/random.hpp>\n#include <jerome/math/parameters/parameterized.hpp>\n#include <boost/range/algorithm/copy.hpp>\n\nnamespace jerome {\nnamespace math {\nnamespace parameters {\n\n\tstd::ostream& operator << (std::ostream& outs, const RangeDomain& value) {\n\t\treturn (outs << \"[\" << value.minimum() << \", \" << value.maximum() << \"]\");\n\t}\n\n}}}\n\nnamespace jerome {\nnamespace math {\nnamespace parameters {\n\t\t\n\tvalue_vector\tparseVector(const String& inString)\n\t{\n\t\tstd::stringstream\ts(inString);\n\t\tstd::vector<double> tmp( (std::istream_iterator<double>(s)), std::istream_iterator<double>());\n\t\tvalue_vector\t\tresult(tmp.size());\n\t\tboost::copy(tmp, result.begin());\n\t\treturn result;\n\t}\n\t\n\tList<RangeDomain::value_type> mean(const range_vector& ranges)\n\t{\n\t\tList<RangeDomain::value_type> result;\n\t\tfor(const auto& r : ranges) {\n\t\t\tresult.push_back((r.minimum()+r.maximum()) * 0.5);\n\t\t}\n\t\treturn result;\n\t}\n\n  List<RangeDomain::value_type>\n  clumpToMean(const List<RangeDomain::value_type>& value,\n              const range_vector& ranges)\n  {\n    List<RangeDomain::value_type> result;\n    for(List<RangeDomain::value_type>::size_type i = 0, n = value.size();\n        i < n; ++i)\n    {\n      const auto& r = ranges[i];\n      const auto& v = value[i];\n      if (v >= r.minimum() && v <= r.maximum()) {\n        result.push_back(v);\n      } else {\n        result.push_back((r.minimum()+r.maximum()) * 0.5);\n      }\n    }\n    return result;\n  }\n\n  List<RangeDomain::value_type> random(const range_vector& ranges)\n\t{\n\t\tList<RangeDomain::value_type> result;\n    static jerome::random<RangeDomain::value_type> random_gen(0, 1);\n\t\t\n\t\tfor(const auto& r : ranges) {\n\t\t\tresult.push_back(r.minimum() + (r.minimum()+r.maximum()) * random_gen());\n\t\t}\n\t\treturn result;\n\t}\n\n\t\n}}}\n", "meta": {"hexsha": "b842fbd8119418d57418d0c2b94aecc3a7207459", "size": 2540, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "jerome/math/parameters/parameters.cpp", "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/math/parameters/parameters.cpp", "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/math/parameters/parameters.cpp", "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": 27.311827957, "max_line_length": 96, "alphanum_fraction": 0.6649606299, "num_tokens": 658, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583376458152, "lm_q2_score": 0.6992544335934766, "lm_q1q2_score": 0.486651953195182}}
{"text": "/*\n@copyright Louis Dionne 2015\nDistributed under the Boost Software License, Version 1.0.\n(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n */\n\n#include <boost/hana/range.hpp>\n\n#include <boost/hana/core/datatype.hpp>\n#include <boost/hana/integral_constant.hpp>\n#include <boost/hana/tuple.hpp>\n\n#include <laws/base.hpp>\n#include <laws/foldable.hpp>\n\n#include <test/cnumeric.hpp>\n\n#include <type_traits>\nusing namespace boost::hana;\n\n\nint main() {\n    //////////////////////////////////////////////////////////////////////////\n    // Setup for the laws below\n    //////////////////////////////////////////////////////////////////////////\n    auto ranges = make<Tuple>(\n          range(int_<0>, int_<0>)\n        , range(int_<0>, int_<1>)\n        , range(int_<0>, int_<2>)\n        , range(int_<1>, int_<1>)\n        , range(int_<1>, int_<2>)\n        , range(int_<1>, int_<3>)\n        , range(int_<50>, int_<60>)\n\n        , range(int_<50>, long_<60>)\n        , range(long_<50>, int_<60>)\n    );\n\n    //////////////////////////////////////////////////////////////////////////\n    // Foldable\n    //////////////////////////////////////////////////////////////////////////\n    {\n        test::_injection<0> f{};\n\n        // unpack\n        {\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                unpack(range(int_<0>, int_<0>), f),\n                f()\n            ));\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                unpack(range(int_<0>, int_<1>), f),\n                f(int_<0>)\n            ));\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                unpack(range(int_<0>, int_<2>), f),\n                f(int_<0>, int_<1>)\n            ));\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                unpack(range(int_<0>, int_<3>), f),\n                f(int_<0>, int_<1>, int_<2>)\n            ));\n\n            // Previously, we would only unpack with `std::size_t`s. Make\n            // sure this does not happen.\n            unpack(range(int_<0>, int_<1>), [](auto x) {\n                using T = datatype_t<decltype(x)>;\n                static_assert(std::is_same<typename T::value_type, int>{}, \"\");\n            });\n        }\n\n        // length\n        {\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                length(range(int_<0>, int_<0>)), size_t<0>\n            ));\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                length(range(int_<0>, int_<1>)), size_t<1>\n            ));\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                length(range(int_<0>, int_<2>)), size_t<2>\n            ));\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                length(range(int_<4>, int_<4>)), size_t<0>\n            ));\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                length(range(int_<4>, int_<10>)), size_t<6>\n            ));\n        }\n\n        // minimum\n        {\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                minimum(range(int_<3>, int_<4>)), int_<3>\n            ));\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                minimum(range(int_<3>, int_<5>)), int_<3>\n            ));\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                minimum(range(int_<-1>, int_<5>)), int_<-1>\n            ));\n        }\n\n        // maximum\n        {\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                maximum(range(int_<3>, int_<4>)), int_<3>\n            ));\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                maximum(range(int_<3>, int_<5>)), int_<4>\n            ));\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                maximum(range(int_<-1>, int_<6>)), int_<5>\n            ));\n        }\n\n        // sum\n        {\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                sum(range(int_<-3>, int_<-3>)), int_<0>\n            ));\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                sum(range(int_<-3>, int_<-2>)), int_<-3>\n            ));\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                sum(range(int_<-3>, int_<-1>)), int_<-3 + -2>\n            ));\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                sum(range(int_<-3>, int_<0>)), int_<-3 + -2 + -1>\n            ));\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                sum(range(int_<-3>, int_<1>)), int_<-3 + -2 + -1 + 0>\n            ));\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                sum(range(int_<-3>, int_<2>)), int_<-3 + -2 + -1 + 0 + 1>\n            ));\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                sum(range(int_<-3>, int_<3>)), int_<-3 + -2 + -1 + 0 + 1 + 2>\n            ));\n\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                sum(range(int_<0>, int_<0>)), int_<0>\n            ));\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                sum(range(int_<0>, int_<1>)), int_<0>\n            ));\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                sum(range(int_<0>, int_<2>)), int_<0 + 1>\n            ));\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                sum(range(int_<0>, int_<3>)), int_<0 + 1 + 2>\n            ));\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                sum(range(int_<0>, int_<4>)), int_<0 + 1 + 2 + 3>\n            ));\n\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                sum(range(int_<3>, int_<3>)), int_<0>\n            ));\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                sum(range(int_<3>, int_<4>)), int_<3>\n            ));\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                sum(range(int_<3>, int_<5>)), int_<3 + 4>\n            ));\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                sum(range(int_<3>, int_<6>)), int_<3 + 4 + 5>\n            ));\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                sum(range(int_<3>, int_<7>)), int_<3 + 4 + 5 + 6>\n            ));\n        }\n\n        // product\n        {\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                product(range(int_<-3>, int_<-3>)), int_<1>\n            ));\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                product(range(int_<-3>, int_<-2>)), int_<-3>\n            ));\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                product(range(int_<-3>, int_<-1>)), int_<-3 * -2>\n            ));\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                product(range(int_<-3>, int_<0>)), int_<-3 * -2 * -1>\n            ));\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                product(range(int_<-3>, int_<1>)), int_<-3 * -2 * -1 * 0>\n            ));\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                product(range(int_<-3>, int_<2>)), int_<-3 * -2 * -1 * 0 * 1>\n            ));\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                product(range(int_<-3>, int_<3>)), int_<-3 * -2 * -1 * 0 * 1 * 2>\n            ));\n\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                product(range(int_<1>, int_<1>)), int_<1>\n            ));\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                product(range(int_<1>, int_<2>)), int_<1>\n            ));\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                product(range(int_<1>, int_<3>)), int_<1 * 2>\n            ));\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                product(range(int_<1>, int_<4>)), int_<1 * 2 * 3>\n            ));\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                product(range(int_<1>, int_<5>)), int_<1 * 2 * 3 * 4>\n            ));\n\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                product(range(int_<3>, int_<3>)), int_<1>\n            ));\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                product(range(int_<3>, int_<4>)), int_<3>\n            ));\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                product(range(int_<3>, int_<5>)), int_<3 * 4>\n            ));\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                product(range(int_<3>, int_<6>)), int_<3 * 4 * 5>\n            ));\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                product(range(int_<3>, int_<7>)), int_<3 * 4 * 5 * 6>\n            ));\n        }\n\n        // laws\n        test::TestFoldable<Range>{ranges};\n    }\n}\n", "meta": {"hexsha": "d98358313c3d17ab64e2d777d709d5e0e39b7015", "size": 8003, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/range/foldable.cpp", "max_stars_repo_name": "josephwinston/hana", "max_stars_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/range/foldable.cpp", "max_issues_repo_name": "josephwinston/hana", "max_issues_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/range/foldable.cpp", "max_forks_repo_name": "josephwinston/hana", "max_forks_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.0553191489, "max_line_length": 81, "alphanum_fraction": 0.4489566413, "num_tokens": 1904, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.4866519356522901}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2013-2014 Kyle Lutz <kyle.r.lutz@gmail.com>\n//\n// Distributed under the Boost Software License, Version 1.0\n// See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt\n//\n// See http://boostorg.github.com/compute for more information.\n//---------------------------------------------------------------------------//\n\n#include <iostream>\n\n#include <Eigen/Core>\n#include <Eigen/LU>\n\n#include <boost/compute/function.hpp>\n#include <boost/compute/system.hpp>\n#include <boost/compute/algorithm/transform.hpp>\n#include <boost/compute/container/vector.hpp>\n#include <boost/compute/types/fundamental.hpp>\n\nnamespace compute = boost::compute;\n\n// this example shows how to compute the determinant of many 4x4 matrices\n// using a determinant function and the transform() algorithm. in OpenCL the\n// float16 type can be used to store a 4x4 matrix and the components are laid\n// out in the following order:\n//\n// M = [ s0 s4 s8 sc ]\n//     [ s1 s5 s9 sd ]\n//     [ s2 s6 sa se ]\n//     [ s3 s7 sb sf ]\n//\n// the input matrices are created using eigen's random matrix and then\n// used again at the end to verify the results of the determinant function.\nint main()\n{\n    // get default device and setup context\n    compute::device gpu = compute::system::default_device();\n    compute::context context(gpu);\n    compute::command_queue queue(context, gpu);\n    std::cout << \"device: \" << gpu.name() << std::endl;\n\n    size_t n = 1000;\n\n    // create random 4x4 matrices on the host\n    std::vector<Eigen::Matrix4f, mi_stl_allocator<Eigen::Matrix4f>> matrices(n);\n    for (size_t i = 0; i < n; i++)\n    {\n        matrices[i] = Eigen::Matrix4f::Random();\n    }\n\n    // copy matrices to the device\n    using compute::float16_;\n    compute::vector<float16_> input(n, context);\n    compute::copy(\n        matrices.begin(), matrices.end(), input.begin(), queue);\n\n    // function returning the determinant of a 4x4 matrix.\n    BOOST_COMPUTE_FUNCTION(float, determinant4x4, (const float16_ m),\n                           {\n                               return m.s0 * m.s5 * m.sa * m.sf + m.s0 * m.s6 * m.sb * m.sd + m.s0 * m.s7 * m.s9 * m.se +\n                                      m.s1 * m.s4 * m.sb * m.se + m.s1 * m.s6 * m.s8 * m.sf + m.s1 * m.s7 * m.sa * m.sc +\n                                      m.s2 * m.s4 * m.s9 * m.sf + m.s2 * m.s5 * m.sb * m.sc + m.s2 * m.s7 * m.s8 * m.sd +\n                                      m.s3 * m.s4 * m.sa * m.sd + m.s3 * m.s5 * m.s8 * m.se + m.s3 * m.s6 * m.s9 * m.sc -\n                                      m.s0 * m.s5 * m.sb * m.se - m.s0 * m.s6 * m.s9 * m.sf - m.s0 * m.s7 * m.sa * m.sd -\n                                      m.s1 * m.s4 * m.sa * m.sf - m.s1 * m.s6 * m.sb * m.sc - m.s1 * m.s7 * m.s8 * m.se -\n                                      m.s2 * m.s4 * m.sb * m.sd - m.s2 * m.s5 * m.s8 * m.sf - m.s2 * m.s7 * m.s9 * m.sc -\n                                      m.s3 * m.s4 * m.s9 * m.se - m.s3 * m.s5 * m.sa * m.sc - m.s3 * m.s6 * m.s8 * m.sd;\n                           });\n\n    // calculate determinants on the gpu\n    compute::vector<float> determinants(n, context);\n    compute::transform(\n        input.begin(), input.end(), determinants.begin(), determinant4x4, queue);\n\n    // check determinants\n    std::vector<float, mi_stl_allocator<float>> host_determinants(n);\n    compute::copy(\n        determinants.begin(), determinants.end(), host_determinants.begin(), queue);\n\n    for (size_t i = 0; i < n; i++)\n    {\n        float det = matrices[i].determinant();\n\n        if (std::abs(det - host_determinants[i]) > 1e-6)\n        {\n            std::cerr << \"error: wrong determinant at \" << i << \" (\"\n                      << host_determinants[i] << \" != \" << det << \")\"\n                      << std::endl;\n            return -1;\n        }\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "57ddce57fcdf796e118097732fe08ce078833478", "size": 3924, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "compute/example/batched_determinant.cpp", "max_stars_repo_name": "atksh/mimalloc-lgb", "max_stars_repo_head_hexsha": "add692a5ef9a91cad0bc78fa18a051d43a8c930e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "compute/example/batched_determinant.cpp", "max_issues_repo_name": "atksh/mimalloc-lgb", "max_issues_repo_head_hexsha": "add692a5ef9a91cad0bc78fa18a051d43a8c930e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "compute/example/batched_determinant.cpp", "max_forks_repo_name": "atksh/mimalloc-lgb", "max_forks_repo_head_hexsha": "add692a5ef9a91cad0bc78fa18a051d43a8c930e", "max_forks_repo_licenses": ["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.4536082474, "max_line_length": 121, "alphanum_fraction": 0.5249745158, "num_tokens": 1067, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544085240401, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.4866519313382736}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n  Matrix3d m = 10000 * Matrix3d::Identity();\nm(0,2) = 1;\ncout << \"Here's the matrix m:\" << endl << m << endl;\ncout << \"m.isDiagonal() returns: \" << m.isDiagonal() << endl;\ncout << \"m.isDiagonal(1e-3) returns: \" << m.isDiagonal(1e-3) << endl;\n\n\n  return 0;\n}\n", "meta": {"hexsha": "7e589a77061762a7d6422b3817864bcfc2d483ff", "size": 392, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_MatrixBase_isDiagonal.cpp", "max_stars_repo_name": "TANHAIYU/Self-calibration-using-Homography-Constraints", "max_stars_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-03-17T16:34:31.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-17T18:30:13.000Z", "max_issues_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_MatrixBase_isDiagonal.cpp", "max_issues_repo_name": "TANHAIYU/planecalib", "max_issues_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_MatrixBase_isDiagonal.cpp", "max_forks_repo_name": "TANHAIYU/planecalib", "max_forks_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.6315789474, "max_line_length": 69, "alphanum_fraction": 0.625, "num_tokens": 130, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544085240402, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.4866519269286486}}
{"text": "/**\n *\n * Copyright (c) 2010 Matthias Walter (xammy@xammy.homelinux.net)\n *\n * Authors: Matthias Walter\n *\n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n *\n */\n\n#include <iostream>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/bipartite.hpp>\n\nusing namespace boost;\n\n/// Example to test for bipartiteness and print the certificates.\n\ntemplate < typename Graph > void print_bipartite(const Graph& g)\n{\n    typedef graph_traits< Graph > traits;\n    typename traits::vertex_iterator vertex_iter, vertex_end;\n\n    /// Most simple interface just tests for bipartiteness.\n\n    bool bipartite = is_bipartite(g);\n\n    if (bipartite)\n    {\n        typedef std::vector< default_color_type > partition_t;\n        typedef\n            typename property_map< Graph, vertex_index_t >::type index_map_t;\n        typedef iterator_property_map< partition_t::iterator, index_map_t >\n            partition_map_t;\n\n        partition_t partition(num_vertices(g));\n        partition_map_t partition_map(partition.begin(), get(vertex_index, g));\n\n        /// A second interface yields a bipartition in a color map, if the graph\n        /// is bipartite.\n\n        is_bipartite(g, get(vertex_index, g), partition_map);\n\n        for (boost::tie(vertex_iter, vertex_end) = vertices(g);\n             vertex_iter != vertex_end; ++vertex_iter)\n        {\n            std::cout\n                << \"Vertex \" << *vertex_iter << \" has color \"\n                << (get(partition_map, *vertex_iter)\n                               == color_traits< default_color_type >::white()\n                           ? \"white\"\n                           : \"black\")\n                << std::endl;\n        }\n    }\n    else\n    {\n        typedef std::vector< typename traits::vertex_descriptor >\n            vertex_vector_t;\n        vertex_vector_t odd_cycle;\n\n        /// A third interface yields an odd-cycle if the graph is not bipartite.\n\n        find_odd_cycle(g, get(vertex_index, g), std::back_inserter(odd_cycle));\n\n        std::cout << \"Odd cycle consists of the vertices:\";\n        for (size_t i = 0; i < odd_cycle.size(); ++i)\n        {\n            std::cout << \" \" << odd_cycle[i];\n        }\n        std::cout << std::endl;\n    }\n}\n\nint main(int argc, char** argv)\n{\n    typedef adjacency_list< vecS, vecS, undirectedS > vector_graph_t;\n    typedef std::pair< int, int > E;\n\n    /**\n     * Create the graph drawn below.\n     *\n     *       0 - 1 - 2\n     *       |       |\n     *   3 - 4 - 5 - 6\n     *  /      \\   /\n     *  |        7\n     *  |        |\n     *  8 - 9 - 10\n     **/\n\n    E bipartite_edges[]\n        = { E(0, 1), E(0, 4), E(1, 2), E(2, 6), E(3, 4), E(3, 8), E(4, 5),\n              E(4, 7), E(5, 6), E(6, 7), E(7, 10), E(8, 9), E(9, 10) };\n    vector_graph_t bipartite_vector_graph(&bipartite_edges[0],\n        &bipartite_edges[0] + sizeof(bipartite_edges) / sizeof(E), 11);\n\n    /**\n     * Create the graph drawn below.\n     *\n     *       2 - 1 - 0\n     *       |       |\n     *   3 - 6 - 5 - 4\n     *  /      \\   /\n     *  |        7\n     *  |       /\n     *  8 ---- 9\n     *\n     **/\n\n    E non_bipartite_edges[] = { E(0, 1), E(0, 4), E(1, 2), E(2, 6), E(3, 6),\n        E(3, 8), E(4, 5), E(4, 7), E(5, 6), E(6, 7), E(7, 9), E(8, 9) };\n    vector_graph_t non_bipartite_vector_graph(&non_bipartite_edges[0],\n        &non_bipartite_edges[0] + sizeof(non_bipartite_edges) / sizeof(E), 10);\n\n    /// Call test routine for a bipartite and a non-bipartite graph.\n\n    print_bipartite(bipartite_vector_graph);\n\n    print_bipartite(non_bipartite_vector_graph);\n\n    return 0;\n}\n", "meta": {"hexsha": "99ac316ff5a62929af190bafc9c23d0a88360433", "size": 3672, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/graph/example/bipartite_example.cpp", "max_stars_repo_name": "uosorio/heroku_face", "max_stars_repo_head_hexsha": "7d6465e71dba17a15d8edaef520adb2fcd09d91e", "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": "3rdparty/boost_1_73_0/libs/graph/example/bipartite_example.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 130.0, "max_issues_repo_issues_event_min_datetime": "2016-06-22T22:11:25.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-29T20:24:09.000Z", "max_forks_repo_path": "Libs/boost_1_76_0/libs/graph/example/bipartite_example.cpp", "max_forks_repo_name": "Antd23rus/S2DE", "max_forks_repo_head_hexsha": "47cc7151c2934cd8f0399a9856c1e54894571553", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2015-07-08T19:18:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-14T16:39:56.000Z", "avg_line_length": 29.1428571429, "max_line_length": 80, "alphanum_fraction": 0.5533769063, "num_tokens": 1077, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347362, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.4866018078521064}}
{"text": "#ifndef HYPSYS1D_DG_RATE_OF_CHANGE_HPP\n#define HYPSYS1D_DG_RATE_OF_CHANGE_HPP\n\n#include <memory>\n#include <Eigen/Dense>\n#include <iostream>\n\n#include <ancse/grid.hpp>\n#include <ancse/model.hpp>\n#include <ancse/rate_of_change.hpp>\n#include <ancse/simulation_time.hpp>\n\n#include <ancse/polynomial_basis.hpp>\n#include <ancse/dg_handler.hpp>\n\n/// Compute the rate of change due to DG method.\n/** The semidiscrete approximation of a PDE using DG is\n *      du_i/dt = - (<F_{i+0.5},\\phi^{-}> - <F_{i-0.5},\\phi^{+}>)\n *                + \\int_K <F, d/dx {\\phi}>\n *  This computes the right hand side of the ODE.\n *\n * @tparam NumericalFlux see e.g. `CentralFlux`.\n */\ntemplate <class NumericalFlux>\nclass DGRateOfChange : public RateOfChange {\n  public:\n\n    DGRateOfChange (const Grid &grid,\n                    const std::shared_ptr<Model> &model,\n                    const NumericalFlux &numerical_flux,\n                    const PolynomialBasis &poly_basis,\n                    const DGHandler &dg_handler)\n        : grid (grid),\n          model (model),\n          numerical_flux (numerical_flux),\n          poly_basis (poly_basis),\n          dg_handler (dg_handler)\n    {\n        std::tie(quad_points, quad_weights) = dg_handler.get_quadrature();\n    }\n\n    virtual void operator() (Eigen::MatrixXd &dudt,\n                             const Eigen::MatrixXd &u0) const override {\n        dudt.setZero();\n        eval_numerical_flux(dudt, u0);\n        eval_volume_integral(dudt, u0);\n    }\n\n    void eval_numerical_flux (Eigen::MatrixXd &dudt,\n                              const Eigen::MatrixXd &u0) const;\n\n    void eval_volume_integral (Eigen::MatrixXd &dudt,\n                               const Eigen::MatrixXd &u0) const;\n\n\n  private:\n    Grid grid;\n    std::shared_ptr<Model> model;\n    NumericalFlux numerical_flux;\n    PolynomialBasis poly_basis;\n    DGHandler dg_handler;\n\n    mutable Eigen::VectorXd quad_points, quad_weights;\n};\n\nstd::shared_ptr<RateOfChange>\nmake_dg_rate_of_change(const nlohmann::json &config,\n                       const Grid &grid,\n                       const std::shared_ptr<Model> &model,\n                       const PolynomialBasis &poly_basis,\n                       const DGHandler &dg_handler,\n                       const std::shared_ptr<SimulationTime> &simulation_time);\n\n#endif // HYPSYS1D_DG_RATE_OF_CHANGE_HPP\n", "meta": {"hexsha": "a705c357cf83a492caccce3f053eebd9078fdd75", "size": 2353, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "series2_workbench/hyp_sys_1d/include/ancse/dg_rate_of_change.hpp", "max_stars_repo_name": "BeatHubmann/19H-AdvNCSE", "max_stars_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-05T22:38:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-05T22:38:47.000Z", "max_issues_repo_path": "series2_handout/hyp_sys_1d/include/ancse/dg_rate_of_change.hpp", "max_issues_repo_name": "BeatHubmann/19H-AdvNCSE", "max_issues_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "series2_handout/hyp_sys_1d/include/ancse/dg_rate_of_change.hpp", "max_forks_repo_name": "BeatHubmann/19H-AdvNCSE", "max_forks_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-12-08T20:43:27.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-08T20:43:27.000Z", "avg_line_length": 31.3733333333, "max_line_length": 79, "alphanum_fraction": 0.6221844454, "num_tokens": 573, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079209, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.48655104583354364}}
{"text": "#include <cctbx/boost_python/flex_fwd.h>\n\n#include <cctbx/uctbx.h>\n#include <cctbx/sgtbx/change_of_basis_op.h>\n#include <boost/python/tuple.hpp>\n#include <boost/python/module.hpp>\n#include <boost/python/def.hpp>\n#include <boost/python/class.hpp>\n#include <boost/python/args.hpp>\n#include <boost/python/return_value_policy.hpp>\n#include <boost/python/copy_const_reference.hpp>\n#include <boost/python/return_by_value.hpp>\n#include <boost/python/return_internal_reference.hpp>\n#include <scitbx/vec3.h>\n#include <scitbx/array_family/versa.h>\n\nnamespace cctbx { namespace uctbx { namespace boost_python {\n\n  void wrap_fast_minimum_reduction();\n\nnamespace {\n\n  struct unit_cell_wrappers : boost::python::pickle_suite\n  {\n    typedef unit_cell w_t;\n    typedef cartesian<> cart_t;\n    typedef fractional<> frac_t;\n    typedef miller::index<> mix_t;\n    typedef scitbx::vec3<double> frac_mix_t;\n    typedef af::const_ref<mix_t> cr_mix_t;\n    typedef af::shared<double> sh_dbl_t;\n\n    static boost::python::tuple\n    getinitargs(w_t const& ucell)\n    {\n      return boost::python::make_tuple(ucell.parameters());\n    }\n\n    typedef af::versa<double, af::mat_grid> matrix_t;\n\n    static matrix_t u_star_to_u_cart_linear_map(w_t const &self) {\n      matrix_t result(af::mat_grid(6, 6));\n      std::copy(self.u_star_to_u_cart_linear_map().begin(),\n                self.u_star_to_u_cart_linear_map().end(),\n                result.begin());\n      return result;\n    }\n\n    static matrix_t d_metrical_matrix_d_params(w_t const &self) {\n      matrix_t result(af::mat_grid(6, 6));\n      std::copy(self.d_metrical_matrix_d_params().begin(),\n                self.d_metrical_matrix_d_params().end(),\n                result.begin());\n      return result;\n    }\n\n    static void\n    wrap()\n    {\n      using namespace boost::python;\n      typedef return_value_policy<copy_const_reference> ccr;\n      typedef return_internal_reference<> rir;\n      class_<w_t>(\"unit_cell\", no_init)\n        .def(init<scitbx::mat3<double> const&>((\n          arg(\"orthogonalization_matrix\"))))\n        .def(init<scitbx::sym_mat3<double> const&>((\n          arg(\"metrical_matrix\"))))\n        .def(init<af::small<double, 6> const&>((\n          arg(\"parameters\"))))\n        .def(\"parameters\", &w_t::parameters, ccr())\n        .def(\"reciprocal_parameters\", &w_t::reciprocal_parameters, ccr())\n        .def(\"metrical_matrix\", &w_t::metrical_matrix, ccr())\n        .def(\"reciprocal_metrical_matrix\",\n          &w_t::reciprocal_metrical_matrix, ccr())\n        .def(\"volume\", &w_t::volume)\n        .def(\"d_volume_d_params\",\n          &w_t::d_volume_d_params, ccr())\n        .def(\"reciprocal\", &w_t::reciprocal)\n        .def(\"longest_vector_sq\", &w_t::longest_vector_sq)\n        .def(\"shortest_vector_sq\", &w_t::shortest_vector_sq)\n        .def(\"is_degenerate\",\n          &w_t::is_degenerate, (\n            arg(\"min_min_length_over_max_length\")=1e-10,\n            arg(\"min_volume_over_min_length\")=1e-5))\n        .def(\"is_similar_to\",\n          &w_t::is_similar_to, (\n            arg(\"other\"),\n            arg(\"relative_length_tolerance\")=0.01,\n            arg(\"absolute_angle_tolerance\")=1.,\n            arg(\"absolute_length_tolerance\")=-9999.))\n        .def(\"similarity_transformations\",\n          &w_t::similarity_transformations, (\n            arg(\"other\"),\n            arg(\"relative_length_tolerance\")=0.02,\n            arg(\"absolute_angle_tolerance\")=2,\n            arg(\"unimodular_generator_range\")=1))\n        .def(\"fractionalization_matrix\", &w_t::fractionalization_matrix, ccr())\n        .def(\"orthogonalization_matrix\", &w_t::orthogonalization_matrix, ccr())\n        .def(\"grid_index_as_site_cart_matrix\",\n          (uc_mat3 (w_t::*)(scitbx::vec3<int> const&) const)\n            &w_t::grid_index_as_site_cart_matrix,\n              (arg(\"gridding\")))\n        .def(\"fractionalize\",\n          (scitbx::vec3<double>(w_t::*)(scitbx::vec3<double> const&) const)\n          &w_t::fractionalize, (\n            arg(\"site_cart\")))\n        .def(\"orthogonalize\",\n          (scitbx::vec3<double>(w_t::*)(scitbx::vec3<double> const&) const)\n          &w_t::orthogonalize, (\n            arg(\"site_frac\")))\n        .def(\"fractionalize\",\n          (af::shared<scitbx::vec3<double> >(w_t::*)(\n            af::const_ref<scitbx::vec3<double> > const&) const)\n              &w_t::fractionalize, (\n                arg(\"sites_cart\")))\n        .def(\"orthogonalize\",\n          (af::shared<scitbx::vec3<double> >(w_t::*)(\n            af::const_ref<scitbx::vec3<double> > const&) const)\n              &w_t::orthogonalize, (\n                arg(\"sites_frac\")))\n        .def(\"fractionalize_gradient\",\n          (scitbx::vec3<double>(w_t::*)(scitbx::vec3<double> const&) const)\n          &w_t::fractionalize_gradient, (\n            arg(\"site_cart\")))\n        .def(\"u_star_to_u_iso_linear_form\",\n             &w_t::u_star_to_u_iso_linear_form, ccr())\n        .def(\"u_star_to_u_cif_linear_map\",\n             &w_t::u_star_to_u_cif_linear_map, ccr())\n        .def(\"u_star_to_u_cart_linear_map\",\n             u_star_to_u_cart_linear_map)\n        .def(\"d_metrical_matrix_d_params\",\n             d_metrical_matrix_d_params)\n        .def(\"length\",\n          (double(w_t::*)(frac_t const&) const)\n          &w_t::length, (\n            arg(\"site_frac\")))\n        .def(\"distance\",\n          (double(w_t::*)(frac_t const&, frac_t const&) const)\n          &w_t::distance, (\n            arg(\"site_frac_1\"), arg(\"site_frac_2\")))\n        .def(\"angle\",\n          (boost::optional<double>(w_t::*)(\n            frac_t const&, frac_t const&, frac_t const&) const)\n          &w_t::angle, (\n            arg(\"site_frac_1\"), arg(\"site_frac_2\"), arg(\"site_frac_3\")))\n        .def(\"dihedral\",\n          (boost::optional<double>(w_t::*)(\n            frac_t const&, frac_t const&, frac_t const&, frac_t const&) const)\n          &w_t::dihedral, (\n            arg(\"site_frac_1\"), arg(\"site_frac_2\"),\n            arg(\"site_frac_3\"), arg(\"site_frac_4\")))\n        .def(\"mod_short_length\",\n          (double(w_t::*)(frac_t const&) const)\n          &w_t::mod_short_length, (\n            arg(\"site_frac\")))\n        .def(\"mod_short_distance\",\n          (double(w_t::*)(frac_t const&, frac_t const&) const)\n          &w_t::mod_short_distance, (\n            arg(\"site_frac_1\"), arg(\"site_frac_2\")))\n        .def(\"min_mod_short_distance\",\n          (double(w_t::*)\n            (af::const_ref<scitbx::vec3<double> > const&,\n             frac_t const&) const)\n          &w_t::min_mod_short_distance, (\n            arg(\"site_frac_1\"), arg(\"site_frac_2\")))\n        .def(\"matrix_cart\",\n          (uc_mat3(w_t::*)(sgtbx::rot_mx const&) const)\n            &w_t::matrix_cart, (\n              arg(\"rot_mx\")))\n        .def(\"change_basis\",\n          (w_t(w_t::*)(uc_mat3 const&, double) const)\n            &w_t::change_basis, (\n              arg(\"c_inv_r\"), arg(\"r_den\")=1.))\n        .def(\"change_basis\",\n          (w_t(w_t::*)(sgtbx::change_of_basis_op const&) const)\n            &w_t::change_basis, (\n              arg(\"cb_op\")))\n        .def(\"max_miller_indices\",\n          (mix_t(w_t::*)(double, double) const)\n            &w_t::max_miller_indices, (\n              arg(\"d_min\"), arg(\"tolerance\")=1e-4))\n        .def(\"d_star_sq\",\n          (double(w_t::*)(mix_t const&) const)\n          &w_t::d_star_sq, (\n            arg(\"miller_index\")))\n        .def(\"d_star_sq\",\n          (sh_dbl_t(w_t::*)(cr_mix_t const&) const)\n          &w_t::d_star_sq, (\n            arg(\"miller_indices\")))\n        .def(\"max_d_star_sq\",\n          (double(w_t::*)(cr_mix_t const&) const)\n          &w_t::max_d_star_sq, (\n            arg(\"miller_indices\")))\n        .def(\"min_max_d_star_sq\",\n          (af::double2(w_t::*)(cr_mix_t const&) const)\n          &w_t::min_max_d_star_sq, (\n            arg(\"miller_indices\")))\n        .def(\"stol_sq\",\n          (double(w_t::*)(mix_t  const&) const)\n          &w_t::stol_sq, (\n            arg(\"miller_index\")))\n        .def(\"stol_sq\",\n          (sh_dbl_t(w_t::*)(cr_mix_t const&) const)\n          &w_t::stol_sq, (\n            arg(\"miller_indices\")))\n        .def(\"two_stol\",\n          (double(w_t::*)(mix_t const&) const)\n          &w_t::two_stol, (\n            arg(\"miller_index\")))\n        .def(\"two_stol\",\n          (sh_dbl_t(w_t::*)(cr_mix_t const&) const)\n          &w_t::two_stol, (\n            arg(\"miller_indices\")))\n        .def(\"stol\",\n          (double(w_t::*)(mix_t const&) const)\n          &w_t::stol, (\n            arg(\"miller_index\")))\n        .def(\"stol\",\n          (sh_dbl_t(w_t::*)(cr_mix_t const&) const)\n          &w_t::stol, (\n            arg(\"miller_indices\")))\n        .def(\"d\",\n          (double(w_t::*)(mix_t const&) const)\n          &w_t::d, (\n            arg(\"miller_index\")))\n        .def(\"d_frac\",\n          (double(w_t::*)(frac_mix_t const&) const)\n          &w_t::d_frac, (\n            arg(\"miller_index\")))\n        .def(\"d\",\n          (sh_dbl_t(w_t::*)(cr_mix_t const&) const)\n          &w_t::d, (\n            arg(\"miller_indices\")))\n        .def(\"two_theta\",\n          (double(w_t::*)(mix_t const&, double, bool) const)\n            &w_t::two_theta, (\n              arg(\"miller_index\"), arg(\"wavelength\"), arg(\"deg\")=false))\n        .def(\"two_theta\",\n          (sh_dbl_t(w_t::*)(cr_mix_t const&, double, bool) const)\n            &w_t::two_theta, (\n              arg(\"miller_indices\"), arg(\"wavelength\"), arg(\"deg\")=false))\n        .def(\"sin_sq_two_theta\",\n          (double(w_t::*)(mix_t const&, double) const)\n            &w_t::sin_sq_two_theta, (\n              arg(\"miller_index\"), arg(\"wavelength\")))\n        .def(\"sin_sq_two_theta\",\n          (sh_dbl_t(w_t::*)(cr_mix_t const&, double) const)\n            &w_t::sin_sq_two_theta, (\n              arg(\"miller_indices\"), arg(\"wavelength\")))\n        .def(\"sin_two_theta\",\n          (double(w_t::*)(mix_t const&, double) const)\n            &w_t::sin_two_theta, (\n              arg(\"miller_index\"), arg(\"wavelength\")))\n        .def(\"sin_two_theta\",\n          (sh_dbl_t(w_t::*)(cr_mix_t const&, double) const)\n            &w_t::sin_two_theta, (\n              arg(\"miller_indices\"), arg(\"wavelength\")))\n        .def(\"reciprocal_space_vector\",\n          (scitbx::vec3<double>(w_t::*)(mix_t const&) const)\n            &w_t::reciprocal_space_vector, (\n              arg(\"miller_index\")))\n        .def(\"reciprocal_space_vector\",\n          (af::shared<scitbx::vec3<double> >(w_t::*)(cr_mix_t const&) const)\n            &w_t::reciprocal_space_vector, (\n              arg(\"miller_indices\")))\n        .def(\"bases_mean_square_difference\",\n          &w_t::bases_mean_square_difference,\n            (arg(\"other\")))\n        .def(\"compare_orthorhombic\", &w_t::compare_orthorhombic,\n          (arg(\"other\")))\n        .def(\"compare_monoclinic\", &w_t::compare_monoclinic,\n          (arg(\"other\"), arg(\"unique_axis\"), arg(\"angular_tolerance\")))\n        .def(\"change_of_basis_op_for_best_monoclinic_beta\",\n          &w_t::change_of_basis_op_for_best_monoclinic_beta, rir())\n        .def_pickle(unit_cell_wrappers())\n      ;\n    }\n  };\n\n  inline\n  scitbx::vec3<int>\n  fractional_unit_shifts_d(fractional<> const& distance_frac)\n  {\n    return distance_frac.unit_shifts();\n  }\n\n  inline\n  scitbx::vec3<int>\n  fractional_unit_shifts_s_s(\n    fractional<> const& site_frac_1,\n    fractional<> const& site_frac_2)\n  {\n    return fractional<>(site_frac_1-site_frac_2).unit_shifts();\n  }\n\n  struct distance_mod_1_wrappers\n  {\n    typedef distance_mod_1 w_t;\n\n    static void\n    wrap()\n    {\n      using namespace boost::python;\n      typedef return_value_policy<return_by_value> rbv;\n      class_<w_t>(\"distance_mod_1\", no_init)\n        .def(init<\n          unit_cell const&,\n          fractional<> const&,\n          fractional<> const&>((\n            arg(\"unit_cell\"),\n            arg(\"site_frac_1\"),\n            arg(\"site_frac_2\"))))\n        .add_property(\"diff_raw\", make_getter(&w_t::diff_raw, rbv()))\n        .add_property(\"diff_mod\", make_getter(&w_t::diff_mod, rbv()))\n        .def_readonly(\"dist_sq\", &w_t::dist_sq)\n        .def(\"unit_shifts\", &w_t::unit_shifts)\n      ;\n    }\n  };\n\n  void init_module()\n  {\n    using namespace boost::python;\n    //! Forward conversions\n    def(\"d_star_sq_as_stol_sq\", (\n      double(*)(double)) d_star_sq_as_stol_sq, (arg(\"d_star_sq\")));\n    def(\"d_star_sq_as_stol_sq\", (\n      af::shared<double>(*)(af::const_ref<double> const &))\n      d_star_sq_as_stol_sq, (arg(\"d_star_sq\")));\n    def(\"d_star_sq_as_two_stol\", (\n      double(*)(double)) d_star_sq_as_two_stol, (arg(\"d_star_sq\")));\n    def(\"d_star_sq_as_two_stol\", (\n      af::shared<double>(*)(af::const_ref<double> const &))\n      d_star_sq_as_two_stol, (arg(\"d_star_sq\")));\n    def(\"d_star_sq_as_stol\", (\n      double(*)(double)) d_star_sq_as_stol, (arg(\"d_star_sq\")));\n    def(\"d_star_sq_as_stol\", (\n      af::shared<double>(*)(af::const_ref<double> const &))\n      d_star_sq_as_stol, (arg(\"d_star_sq\")));\n    def(\"d_star_sq_as_d\", (\n      double(*)(double)) d_star_sq_as_d, (arg(\"d_star_sq\")));\n    def(\"d_star_sq_as_d\", (\n      af::shared<double>(*)(af::const_ref<double> const &))\n      d_star_sq_as_d, (arg(\"d_star_sq\")));\n    def(\"d_star_sq_as_two_theta\", (\n      double(*)(double, double, bool)) d_star_sq_as_two_theta,\n      (arg(\"d_star_sq\"), arg(\"wavelength\"), arg(\"deg\")=false));\n    def(\"d_star_sq_as_two_theta\", (\n      af::shared<double>(*)(af::const_ref<double> const &, double, bool))\n      d_star_sq_as_two_theta,\n      (arg(\"d_star_sq\"), arg(\"wavelength\"), arg(\"deg\")=false));\n    //! Reverse conversions\n    def(\"stol_sq_as_d_star_sq\", (\n      double(*)(double)) stol_sq_as_d_star_sq, (arg(\"stol_sq\")));\n    def(\"stol_sq_as_d_star_sq\", (\n      af::shared<double>(*)(af::const_ref<double> const &))\n      stol_sq_as_d_star_sq, (arg(\"stol_sq\")));\n    def(\"two_stol_as_d_star_sq\", (\n      double(*)(double)) two_stol_as_d_star_sq, (arg(\"two_stol\")));\n    def(\"two_stol_as_d_star_sq\", (\n      af::shared<double>(*)(af::const_ref<double> const &))\n      two_stol_as_d_star_sq, (arg(\"two_stol\")));\n    def(\"stol_as_d_star_sq\", (\n      double(*)(double)) stol_as_d_star_sq, (arg(\"stol\")));\n    def(\"stol_as_d_star_sq\", (\n      af::shared<double>(*)(af::const_ref<double> const &))\n      stol_as_d_star_sq, (arg(\"stol\")));\n    def(\"d_as_d_star_sq\", (\n      double(*)(double)) d_as_d_star_sq, (arg(\"d\")));\n    def(\"d_as_d_star_sq\", (\n      af::shared<double>(*)(af::const_ref<double> const &))\n      d_as_d_star_sq, (arg(\"d\")));\n    def(\"two_theta_as_d_star_sq\", (\n      double(*)(double, double, bool)) two_theta_as_d_star_sq,\n      (arg(\"two_theta\"), arg(\"wavelength\"), arg(\"deg\")=false));\n    def(\"two_theta_as_d_star_sq\", (\n      af::shared<double>(*)(af::const_ref<double> const &, double, bool))\n      two_theta_as_d_star_sq,\n      (arg(\"two_theta\"), arg(\"wavelength\"), arg(\"deg\")=false));\n    def(\"two_theta_as_d\", (\n      double(*)(double, double, bool)) two_theta_as_d,\n      (arg(\"two_theta\"), arg(\"wavelength\"), arg(\"deg\")=false));\n    def(\"two_theta_as_d\", (\n      af::shared<double>(*)(af::const_ref<double> const &, double, bool))\n      two_theta_as_d,\n      (arg(\"two_theta\"), arg(\"wavelength\"), arg(\"deg\")=false));\n\n    def(\"unit_cell_angles_are_feasible\", unit_cell_angles_are_feasible, (\n      arg(\"values_deg\"), arg(\"tolerance\")=1e-6));\n\n    unit_cell_wrappers::wrap();\n    wrap_fast_minimum_reduction();\n\n    def(\"fractional_unit_shifts\", fractional_unit_shifts_d, (\n      arg(\"distance_frac\")));\n    def(\"fractional_unit_shifts\", fractional_unit_shifts_s_s, (\n      arg(\"site_frac_1\"), arg(\"site_frac_2\")));\n\n    distance_mod_1_wrappers::wrap();\n  }\n\n} // namespace <anonymous>\n}}} // namespace cctbx::uctbx::boost_python\n\nBOOST_PYTHON_MODULE(cctbx_uctbx_ext)\n{\n  cctbx::uctbx::boost_python::init_module();\n}\n", "meta": {"hexsha": "63eee0a6d505d4c8d4a09da27a8c5cc8ece1417c", "size": 15691, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cctbx/uctbx/boost_python/uctbx_ext.cpp", "max_stars_repo_name": "rimmartin/cctbx_project", "max_stars_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 155.0, "max_stars_repo_stars_event_min_datetime": "2016-11-23T12:52:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:35:44.000Z", "max_issues_repo_path": "cctbx/uctbx/boost_python/uctbx_ext.cpp", "max_issues_repo_name": "rimmartin/cctbx_project", "max_issues_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": 590.0, "max_issues_repo_issues_event_min_datetime": "2016-12-10T11:31:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T23:10:09.000Z", "max_forks_repo_path": "cctbx/uctbx/boost_python/uctbx_ext.cpp", "max_forks_repo_name": "rimmartin/cctbx_project", "max_forks_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 115.0, "max_forks_repo_forks_event_min_datetime": "2016-11-15T08:17:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T15:30:14.000Z", "avg_line_length": 38.3643031785, "max_line_length": 79, "alphanum_fraction": 0.5863871009, "num_tokens": 4339, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920068519376, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.48655104294350776}}
{"text": "#include <tiny.h>\n#include <convex.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n\nBOOST_AUTO_TEST_SUITE(convex_reduce_edge);\n\nBOOST_AUTO_TEST_CASE(case_by_case_test)\n{\n  typedef tiny::MathTypes<double>        math_types;\n  typedef math_types::vector3_type      vector3_type;\n\n  typedef convex::Simplex<vector3_type>    simplex_type;\n\n  // First we create a simplex that represents an edge\n  vector3_type const a = vector3_type::make(1.0, 0.0, 0.0);\n  vector3_type const b = vector3_type::make(0.0, 0.0, 0.0);\n\n  // First we use a test point that does not lie on the line\n\n  // Front side of A voronoi plane\n  {\n    simplex_type S;\n\n    convex::add_point_to_simplex( a, a, a, S);\n    convex::add_point_to_simplex( b, b, b, S);\n\n    vector3_type const p = vector3_type::make( 1.5, 1.0,  1.0);\n\n    convex::reduce_edge( p, S );\n\n    BOOST_CHECK( convex::dimension( S ) == 1u );\n\n    int bit_A    = 0;\n    size_t idx_A = 0;\n    convex::get_used_indices( S.m_bitmask, idx_A, bit_A );\n\n    BOOST_CHECK(S.m_bitmask == bit_A );\n    BOOST_CHECK(S.m_v[idx_A] == a);\n    BOOST_CHECK(S.m_a[idx_A] == a);\n    BOOST_CHECK(S.m_b[idx_A] == a);\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 1.0, 0.01);\n\n  }\n  // Back side of A voronoi plane\n  {\n    simplex_type S;\n\n    convex::add_point_to_simplex( a, a, a, S);\n    convex::add_point_to_simplex( b, b, b, S);\n\n    vector3_type const p = vector3_type::make( 0.5, 1.0,  1.0);\n\n    convex::reduce_edge( p, S );\n\n    BOOST_CHECK( convex::dimension( S ) == 2u );\n\n    int bit_A    = 0;\n    size_t idx_A = 0;\n    int bit_B    = 0;\n    size_t idx_B = 0;\n    convex::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B );\n\n    BOOST_CHECK( S.m_bitmask == (bit_A | bit_B));\n    \n    BOOST_CHECK(S.m_v[idx_A] == a);\n    BOOST_CHECK(S.m_a[idx_A] == a);\n    BOOST_CHECK(S.m_b[idx_A] == a);\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 0.5, 0.01);\n\n    BOOST_CHECK(S.m_v[idx_B] == b);\n    BOOST_CHECK(S.m_a[idx_B] == b);\n    BOOST_CHECK(S.m_b[idx_B] == b);\n    BOOST_CHECK_CLOSE(S.m_w[idx_B], 0.5, 0.01);\n  }\n  // In A voronoi plane\n  {\n    simplex_type S;\n\n    convex::add_point_to_simplex( a, a, a, S);\n    convex::add_point_to_simplex( b, b, b, S);\n\n    vector3_type const p = vector3_type::make( 1.0, 1.0,  1.0);\n\n    convex::reduce_edge( p, S );\n\n    BOOST_CHECK( convex::dimension( S ) == 1u );\n\n    int bit_A    = 0;\n    size_t idx_A = 0;\n    convex::get_used_indices( S.m_bitmask, idx_A, bit_A );\n\n    BOOST_CHECK(S.m_bitmask == bit_A );\n    BOOST_CHECK(S.m_v[idx_A] == a);\n    BOOST_CHECK(S.m_a[idx_A] == a);\n    BOOST_CHECK(S.m_b[idx_A] == a);\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 1.0, 0.01);\n  }\n\n  // Front side of B voronoi plane\n  {\n    simplex_type S;\n\n    convex::add_point_to_simplex( a, a, a, S);\n    convex::add_point_to_simplex( b, b, b, S);\n\n    vector3_type const p = vector3_type::make( -0.5, 1.0,  1.0);\n\n    convex::reduce_edge( p, S );\n\n    BOOST_CHECK( convex::dimension( S ) == 1u );\n\n    int bit_A    = 0;\n    size_t idx_A = 0;\n    convex::get_used_indices( S.m_bitmask, idx_A, bit_A );\n\n    BOOST_CHECK(S.m_bitmask == bit_A );\n    BOOST_CHECK(S.m_v[idx_A] == b);\n    BOOST_CHECK(S.m_a[idx_A] == b);\n    BOOST_CHECK(S.m_b[idx_A] == b);\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 1.0, 0.01);\n  }\n  // Back side of B voronoi plane\n  {\n    simplex_type S;\n\n    convex::add_point_to_simplex( a, a, a, S);\n    convex::add_point_to_simplex( b, b, b, S);\n\n    vector3_type const p = vector3_type::make( 0.5, 1.0,  1.0);\n\n    convex::reduce_edge( p, S );\n\n    BOOST_CHECK( convex::dimension( S ) == 2u );\n\n    int bit_A    = 0;\n    size_t idx_A = 0;\n    int bit_B    = 0;\n    size_t idx_B = 0;\n    convex::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B );\n\n    BOOST_CHECK( S.m_bitmask == (bit_A | bit_B));\n    \n    BOOST_CHECK(S.m_v[idx_A] == a);\n    BOOST_CHECK(S.m_a[idx_A] == a);\n    BOOST_CHECK(S.m_b[idx_A] == a);\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 0.5, 0.01);\n\n    BOOST_CHECK(S.m_v[idx_B] == b);\n    BOOST_CHECK(S.m_a[idx_B] == b);\n    BOOST_CHECK(S.m_b[idx_B] == b);\n    BOOST_CHECK_CLOSE(S.m_w[idx_B], 0.5, 0.01);\n  }\n  // In B voronoi plane\n  {\n    simplex_type S;\n\n    convex::add_point_to_simplex( a, a, a, S);\n    convex::add_point_to_simplex( b, b, b, S);\n\n    vector3_type const p = vector3_type::make( 0.0, 1.0,  1.0);\n\n    convex::reduce_edge( p, S );\n\n    BOOST_CHECK( convex::dimension( S ) == 1u );\n\n    int bit_A    = 0;\n    size_t idx_A = 0;\n    convex::get_used_indices( S.m_bitmask, idx_A, bit_A );\n\n    BOOST_CHECK(S.m_bitmask == bit_A );\n    BOOST_CHECK(S.m_v[idx_A] == b);\n    BOOST_CHECK(S.m_a[idx_A] == b);\n    BOOST_CHECK(S.m_b[idx_A] == b);\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 1.0, 0.01);\n  }\n\n  // Second we use a test point that lies on the line\n\n  // Front side of A voronoi plane\n  {\n    simplex_type S;\n\n    convex::add_point_to_simplex( a, a, a, S);\n    convex::add_point_to_simplex( b, b, b, S);\n\n    vector3_type const p = vector3_type::make( 1.5, 0.0,  0.0);\n\n    convex::reduce_edge( p, S );\n\n    BOOST_CHECK( convex::dimension( S ) == 1u );\n\n    int bit_A    = 0;\n    size_t idx_A = 0;\n    convex::get_used_indices( S.m_bitmask, idx_A, bit_A );\n\n    BOOST_CHECK(S.m_bitmask == bit_A );\n    BOOST_CHECK(S.m_v[idx_A] == a);\n    BOOST_CHECK(S.m_a[idx_A] == a);\n    BOOST_CHECK(S.m_b[idx_A] == a);\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 1.0, 0.01);\n  }\n  // Back side of A voronoi plane\n  {\n    simplex_type S;\n\n    convex::add_point_to_simplex( a, a, a, S);\n    convex::add_point_to_simplex( b, b, b, S);\n\n    vector3_type const p = vector3_type::make( 0.5, 0.0,  0.0);\n\n    convex::reduce_edge( p, S );\n\n    BOOST_CHECK( convex::dimension( S ) == 2u );\n\n    int bit_A    = 0;\n    size_t idx_A = 0;\n    int bit_B    = 0;\n    size_t idx_B = 0;\n    convex::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B );\n\n    BOOST_CHECK( S.m_bitmask == (bit_A | bit_B));\n    \n    BOOST_CHECK(S.m_v[idx_A] == a);\n    BOOST_CHECK(S.m_a[idx_A] == a);\n    BOOST_CHECK(S.m_b[idx_A] == a);\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 0.5, 0.01);\n\n    BOOST_CHECK(S.m_v[idx_B] == b);\n    BOOST_CHECK(S.m_a[idx_B] == b);\n    BOOST_CHECK(S.m_b[idx_B] == b);\n    BOOST_CHECK_CLOSE(S.m_w[idx_B], 0.5, 0.01);\n  }\n  // In A voronoi plane\n  {\n    simplex_type S;\n\n    convex::add_point_to_simplex( a, a, a, S);\n    convex::add_point_to_simplex( b, b, b, S);\n\n    vector3_type const p = vector3_type::make( 1.0, 0.0,  0.0);\n\n    convex::reduce_edge( p, S );\n\n    BOOST_CHECK( convex::dimension( S ) == 1u );\n\n    int bit_A    = 0;\n    size_t idx_A = 0;\n    convex::get_used_indices( S.m_bitmask, idx_A, bit_A );\n\n    BOOST_CHECK(S.m_bitmask == bit_A );\n    BOOST_CHECK(S.m_v[idx_A] == a);\n    BOOST_CHECK(S.m_a[idx_A] == a);\n    BOOST_CHECK(S.m_b[idx_A] == a);\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 1.0, 0.01);\n  }\n\n  // Front side of B voronoi plane\n  {\n    simplex_type S;\n\n    convex::add_point_to_simplex( a, a, a, S);\n    convex::add_point_to_simplex( b, b, b, S);\n\n    vector3_type const p = vector3_type::make( -0.5, 0.0,  0.0);\n\n    convex::reduce_edge( p, S );\n\n    BOOST_CHECK( convex::dimension( S ) == 1u );\n\n    int bit_A    = 0;\n    size_t idx_A = 0;\n    convex::get_used_indices( S.m_bitmask, idx_A, bit_A );\n\n    BOOST_CHECK(S.m_bitmask == bit_A );\n    BOOST_CHECK(S.m_v[idx_A] == b);\n    BOOST_CHECK(S.m_a[idx_A] == b);\n    BOOST_CHECK(S.m_b[idx_A] == b);\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 1.0, 0.01);\n  }\n  // Back side of B voronoi plane\n  {\n    simplex_type S;\n\n    convex::add_point_to_simplex( a, a, a, S);\n    convex::add_point_to_simplex( b, b, b, S);\n\n    vector3_type const p = vector3_type::make( 0.5, 0.0,  0.0);\n\n    convex::reduce_edge( p, S );\n\n    BOOST_CHECK( convex::dimension( S ) == 2u );\n\n    int bit_A    = 0;\n    size_t idx_A = 0;\n    int bit_B    = 0;\n    size_t idx_B = 0;\n    convex::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B );\n\n    BOOST_CHECK( S.m_bitmask == (bit_A | bit_B));\n    \n    BOOST_CHECK(S.m_v[idx_A] == a);\n    BOOST_CHECK(S.m_a[idx_A] == a);\n    BOOST_CHECK(S.m_b[idx_A] == a);\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 0.5, 0.01);\n\n    BOOST_CHECK(S.m_v[idx_B] == b);\n    BOOST_CHECK(S.m_a[idx_B] == b);\n    BOOST_CHECK(S.m_b[idx_B] == b);\n    BOOST_CHECK_CLOSE(S.m_w[idx_B], 0.5, 0.01);\n  }\n  // In B voronoi plane\n  {\n    simplex_type S;\n\n    convex::add_point_to_simplex( a, a, a, S);\n    convex::add_point_to_simplex( b, b, b, S);\n\n    vector3_type const p = vector3_type::make( 0.0, 0.0,  0.0);\n\n    convex::reduce_edge( p, S );\n\n    BOOST_CHECK( convex::dimension( S ) == 1u );\n\n    int bit_A    = 0;\n    size_t idx_A = 0;\n    convex::get_used_indices( S.m_bitmask, idx_A, bit_A );\n\n    BOOST_CHECK(S.m_bitmask == bit_A );\n    BOOST_CHECK(S.m_v[idx_A] == b);\n    BOOST_CHECK(S.m_a[idx_A] == b);\n    BOOST_CHECK(S.m_b[idx_A] == b);\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 1.0, 0.01);\n  }\n\n  // Assymetric test case when simplex is AB\n  {\n    simplex_type S;\n\n    convex::add_point_to_simplex( a, a, a, S);\n    convex::add_point_to_simplex( b, b, b, S);\n\n    vector3_type const p = (2.0*a + 3.0*b)/5.0;\n\n    convex::reduce_edge( p, S );\n\n    BOOST_CHECK( convex::dimension( S ) == 2u );\n\n    int bit_A    = 0;\n    size_t idx_A = 0;\n    int bit_B    = 0;\n    size_t idx_B = 0;\n    convex::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B );\n\n    BOOST_CHECK( S.m_bitmask == (bit_A | bit_B));\n    \n    BOOST_CHECK(S.m_v[idx_A] == a);\n    BOOST_CHECK(S.m_a[idx_A] == a);\n    BOOST_CHECK(S.m_b[idx_A] == a);\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 0.4, 0.01);\n\n    BOOST_CHECK(S.m_v[idx_B] == b);\n    BOOST_CHECK(S.m_a[idx_B] == b);\n    BOOST_CHECK(S.m_b[idx_B] == b);\n    BOOST_CHECK_CLOSE(S.m_w[idx_B], 0.6, 0.01);\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "e2ededaf3d2bfbbb4440e57f9af4d3114c7d9ce4", "size": 9825, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/FOUNDATION/CONVEX/unit_tests/convex_reduce_edge/convex_reduce_edge.cpp", "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/FOUNDATION/CONVEX/unit_tests/convex_reduce_edge/convex_reduce_edge.cpp", "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/FOUNDATION/CONVEX/unit_tests/convex_reduce_edge/convex_reduce_edge.cpp", "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": 26.2700534759, "max_line_length": 72, "alphanum_fraction": 0.6111959288, "num_tokens": 3374, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.486551040053472}}
{"text": "/**\n *  Image GraphCut 3D Segmentation\n *\n *  Copyright (c) 2016, Zurich University of Applied Sciences, School of Engineering, T. Fitze, Y. Pauchard\n *\n *  Licensed under GNU General Public License 3.0 or later.\n *  Some rights reserved.\n */\n\n #include <gtest/gtest.h>\n\n// boost\n#include <boost/assign/list_of.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/boykov_kolmogorov_max_flow.hpp>\n\n//\n#include \"MaxFlowGraphBoost.hxx\"\n#include \"MaxFlowGraphKolmogorov.hxx\"\n\nclass TestGraphLibrary : public ::testing::Test {\nprotected:\n    typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS,\n            boost::no_property,\n            boost::property<boost::edge_index_t, std::size_t> > GraphType;\n\n    typedef boost::graph_traits<GraphType>::vertex_descriptor VertexDescriptor;\n    typedef boost::graph_traits<GraphType>::edge_descriptor EdgeDescriptor;\n    void addBidirectionalEdge(GraphType& graph, VertexDescriptor source, VertexDescriptor target, float weight,\n            float reverseWeight, std::vector<EdgeDescriptor> &reverseEdges, std::vector<float>& capacity){\n        int nextEdgeId = num_edges(graph);\n\n        // create both edges\n        EdgeDescriptor edge = boost::add_edge(source, target, nextEdgeId, graph).first;\n        EdgeDescriptor reverseEdge = boost::add_edge(target, source, nextEdgeId + 1, graph).first;\n\n        // add them to out property maps\n        reverseEdges.push_back(reverseEdge);\n        reverseEdges.push_back(edge);\n        capacity.push_back(weight);\n        capacity.push_back(weight);\n    }\n\n    virtual void SetUp() {\n\n    }\n\n    virtual void TearDown() {\n\n    }\n\n};\n\nTEST_F(TestGraphLibrary, ComputeMaxFlow){\n    /*\n     *                input              expected segmentation\n     *\n     *          F = F = x - B = B         F = F = F - B = B\n     *          ||  ||  |   ||  ||        ||  ||  |   ||  ||\n     *          x = F - x = B = x    ->   F = F - B = B = B\n     *          ||  ||  |   ||  ||        ||  ||  |   ||  ||\n     *          F = F = x - B = B         F = F = F - B = B\n     *\n     * F is initialized as foreground (source)\n     * B is initialized as background (sink)\n     * - and | indicate small weight (low throughput),\n     * = and || indicate larger weights -> desirable flow.\n     *\n     */\n\n    // create graph with 4 vertices\n    int numberOfVertices = 3*5 + 2;\n    float smallWeight = 1;\n    float largeWeight = 1000;\n\n    // containers\n    GraphType graph(numberOfVertices);\n    std::vector<EdgeDescriptor> reverseEdges;\n    std::vector<float> capacity;\n    std::vector<int> groups(numberOfVertices);\n\n    // get all the descriptors\n    VertexDescriptor vSource = boost::vertex(0, graph);\n    VertexDescriptor v0 = boost::vertex(1, graph);\n    VertexDescriptor v1 = boost::vertex(2, graph);\n    VertexDescriptor v2 = boost::vertex(3, graph);\n    VertexDescriptor v3 = boost::vertex(4, graph);\n    VertexDescriptor v4 = boost::vertex(5, graph);\n    VertexDescriptor v5 = boost::vertex(6, graph);\n    VertexDescriptor v6 = boost::vertex(7, graph);\n    VertexDescriptor v7 = boost::vertex(8, graph);\n    VertexDescriptor v8 = boost::vertex(9, graph);\n    VertexDescriptor v9 = boost::vertex(10, graph);\n    VertexDescriptor v10 = boost::vertex(11, graph);\n    VertexDescriptor v11 = boost::vertex(12, graph);\n    VertexDescriptor v12 = boost::vertex(13, graph);\n    VertexDescriptor v13 = boost::vertex(14, graph);\n    VertexDescriptor v14 = boost::vertex(15, graph);\n    VertexDescriptor vSink = boost::vertex(16, graph);\n\n    // add horizontal edges\n    addBidirectionalEdge(graph, v0, v1, largeWeight, largeWeight, reverseEdges, capacity);\n    addBidirectionalEdge(graph, v1, v2, largeWeight, largeWeight, reverseEdges, capacity);\n    addBidirectionalEdge(graph, v2, v3, smallWeight, smallWeight, reverseEdges, capacity);\n    addBidirectionalEdge(graph, v3, v4, largeWeight, largeWeight, reverseEdges, capacity);\n\n    addBidirectionalEdge(graph, v5, v6, largeWeight, largeWeight, reverseEdges, capacity);\n    addBidirectionalEdge(graph, v6, v7, smallWeight, smallWeight, reverseEdges, capacity);\n    addBidirectionalEdge(graph, v7, v8, largeWeight, largeWeight, reverseEdges, capacity);\n    addBidirectionalEdge(graph, v8, v9, largeWeight, largeWeight, reverseEdges, capacity);\n\n    addBidirectionalEdge(graph, v10, v11, largeWeight, largeWeight, reverseEdges, capacity);\n    addBidirectionalEdge(graph, v11, v12, largeWeight, largeWeight, reverseEdges, capacity);\n    addBidirectionalEdge(graph, v12, v13, smallWeight, smallWeight, reverseEdges, capacity);\n    addBidirectionalEdge(graph, v13, v14, largeWeight, largeWeight, reverseEdges, capacity);\n\n    // vertical edges\n    addBidirectionalEdge(graph, v0, v5, largeWeight, largeWeight, reverseEdges, capacity);\n    addBidirectionalEdge(graph, v1, v6, largeWeight, largeWeight, reverseEdges, capacity);\n    addBidirectionalEdge(graph, v2, v7, smallWeight, smallWeight, reverseEdges, capacity);\n    addBidirectionalEdge(graph, v3, v8, largeWeight, largeWeight, reverseEdges, capacity);\n    addBidirectionalEdge(graph, v4, v9, largeWeight, largeWeight, reverseEdges, capacity);\n\n    addBidirectionalEdge(graph, v5, v10, largeWeight, largeWeight, reverseEdges, capacity);\n    addBidirectionalEdge(graph, v6, v11, largeWeight, largeWeight, reverseEdges, capacity);\n    addBidirectionalEdge(graph, v7, v12, smallWeight, smallWeight, reverseEdges, capacity);\n    addBidirectionalEdge(graph, v8, v13, largeWeight, largeWeight, reverseEdges, capacity);\n    addBidirectionalEdge(graph, v9, v14, largeWeight, largeWeight, reverseEdges, capacity);\n\n    // connect the sources\n    std::vector<VertexDescriptor> sourceNodes = boost::assign::list_of(v0)(v1)(v6)(v10)(v11);\n    for(int i = 0; i < sourceNodes.size(); ++i){\n        addBidirectionalEdge(graph, sourceNodes[i], vSource, largeWeight, largeWeight, reverseEdges, capacity);\n        addBidirectionalEdge(graph, sourceNodes[i], vSink, smallWeight, smallWeight, reverseEdges, capacity);\n    }\n\n    // connect the sinks\n    std::vector<VertexDescriptor> sinkNodes = boost::assign::list_of(v3)(v4)(v8)(v13)(v14);\n    for(int i = 0; i < sinkNodes.size(); ++i){\n        addBidirectionalEdge(graph, sinkNodes[i], vSink, largeWeight, largeWeight, reverseEdges, capacity);\n        addBidirectionalEdge(graph, sinkNodes[i], vSource, smallWeight, smallWeight, reverseEdges, capacity);\n    }\n\n    // probably also need to connect the uncertain nodes?\n\n    std::vector<float> residualCapacity(boost::num_edges(graph), 0);\n\n    // check if the data structure looks as expected\n    EXPECT_EQ(numberOfVertices, boost::num_vertices(graph));\n    EXPECT_EQ(22 * 2 + sourceNodes.size()*4 + sinkNodes.size()*4, boost::num_edges(graph));\n\n    // max flow\n    boost::boykov_kolmogorov_max_flow(graph\n            , boost::make_iterator_property_map(&capacity.front(), boost::get(boost::edge_index, graph))\n            , boost::make_iterator_property_map(&residualCapacity.front(), boost::get(boost::edge_index, graph))\n            , boost::make_iterator_property_map(&reverseEdges.front(), boost::get(boost::edge_index, graph))\n            , boost::make_iterator_property_map(&groups.front(), boost::get(boost::vertex_index, graph))\n            , boost::get(boost::vertex_index, graph)\n            , vSource\n            , vSink);\n\n    // cexpected segmentation\n    std::set<int> expectedForeground = boost::assign::list_of(0)(1)(2)(3)(6)(7)(11)(12)(13);\n    std::set<int> expectedBackground = boost::assign::list_of(4)(5)(8)(9)(10)(14)(15)(16);\n\n    // check the group of each vertex with the expected results\n    for(size_t index=0; index < numberOfVertices; ++index){\n        if(groups[index] == groups[vSource]){\n            if(expectedForeground.find(index) != expectedForeground.end()){\n                SUCCEED();\n                expectedForeground.erase(index);\n            } else{\n                FAIL() << \"missing \"<<index << \" in foreground results\";\n            }\n        }\n        else if(groups[index] == groups[vSink]){\n            if(expectedBackground.find(index) != expectedBackground.end()){\n                SUCCEED();\n                expectedBackground.erase(index);\n            } else{\n                FAIL() << \"missing \"<<index << \" in background results\";\n            }\n        }\n        else{\n            FAIL() << \"Vertex is neither foreground nor background, something went wrong.\";\n        }\n    }\n\n    // both containers should now be empty\n    EXPECT_EQ(0, expectedForeground.size());\n    EXPECT_EQ(0, expectedBackground.size());\n}\n\n\nTEST_F(TestGraphLibrary, MaxFlowGraphBoost){\n    // same exmaple as in ComputeMaxFlow, but this time with the wrapper\n\n    // create graph with 4 vertices\n    int numberOfVertices = 3*5;\n    float smallWeight = 1;\n    float largeWeight = 1000;\n\n    MaxFlowGraphBoost graph(3, 5, 1);\n\n    // add horizontal edges\n    graph.addBidirectionalEdge(0, 1, largeWeight, largeWeight);\n    graph.addBidirectionalEdge(1, 2, largeWeight, largeWeight);\n    graph.addBidirectionalEdge(2, 3, smallWeight, smallWeight);\n    graph.addBidirectionalEdge(3, 4, largeWeight, largeWeight);\n    graph.addBidirectionalEdge(5, 6, largeWeight, largeWeight);\n    graph.addBidirectionalEdge(6, 7, smallWeight, smallWeight);\n    graph.addBidirectionalEdge(7, 8, largeWeight, largeWeight);\n    graph.addBidirectionalEdge(8, 9, largeWeight, largeWeight);\n    graph.addBidirectionalEdge(10, 11, largeWeight, largeWeight);\n    graph.addBidirectionalEdge(11, 12, largeWeight, largeWeight);\n    graph.addBidirectionalEdge(12, 13, smallWeight, smallWeight);\n    graph.addBidirectionalEdge(13, 14, largeWeight, largeWeight);\n\n    // vertical edges\n    graph.addBidirectionalEdge(0, 5, largeWeight, largeWeight);\n    graph.addBidirectionalEdge(1, 6, largeWeight, largeWeight);\n    graph.addBidirectionalEdge(2, 7, smallWeight, smallWeight);\n    graph.addBidirectionalEdge(3, 8, largeWeight, largeWeight);\n    graph.addBidirectionalEdge(4, 9, largeWeight, largeWeight);\n    graph.addBidirectionalEdge(5, 10, largeWeight, largeWeight);\n    graph.addBidirectionalEdge(6, 11, largeWeight, largeWeight);\n    graph.addBidirectionalEdge(7, 12, smallWeight, smallWeight);\n    graph.addBidirectionalEdge(8, 13, largeWeight, largeWeight);\n    graph.addBidirectionalEdge(9, 14, largeWeight, largeWeight);\n\n    // connect the sources\n    std::vector<unsigned int> sourceNodes = boost::assign::list_of(0)(1)(6)(10)(11);\n    for(int i = 0; i < sourceNodes.size(); ++i){\n        graph.addTerminalEdges(sourceNodes[i], largeWeight, smallWeight);\n    }\n\n    // connect the sinks\n    std::vector<unsigned int> sinkNodes = boost::assign::list_of(3)(4)(8)(13)(14);\n    for(int i = 0; i < sinkNodes.size(); ++i){\n        graph.addTerminalEdges(sinkNodes[i], smallWeight, largeWeight);\n    }\n\n    // check if the data structure looks as expected\n    EXPECT_EQ(numberOfVertices, graph.getNumberOfVertices()); // +2 because a sink + source should've been added\n    EXPECT_EQ(22 * 2 + sourceNodes.size()*4 + sinkNodes.size()*4, graph.getNumberOfEdges());\n\n    // max flow\n    graph.calculateMaxFlow();\n\n    // cexpected segmentation\n    std::set<unsigned int> expectedForeground = boost::assign::list_of(0)(1)(2)(5)(6)(10)(11)(12);\n    std::set<unsigned int> expectedBackground = boost::assign::list_of(3)(4)(7)(8)(9)(13)(14);\n\n    // check the group of each vertex with the expected results\n    for(size_t index=0; index < graph.getNumberOfVertices(); ++index){\n        if(graph.groupOf(index) == graph.groupOfSource()){\n            if(expectedForeground.find(index) != expectedForeground.end()){\n                SUCCEED();\n                expectedForeground.erase(index);\n            } else{\n                FAIL() << \"missing \"<<index << \" in foreground results\";\n            }\n        }\n        else if(graph.groupOf(index) == graph.groupOfSink()){\n            if(expectedBackground.find(index) != expectedBackground.end()){\n                SUCCEED();\n                expectedBackground.erase(index);\n            } else{\n                FAIL() << \"missing \"<<index << \" in background results\";\n            }\n        }\n        else{\n            FAIL() << \"Vertex \" << index << \" is neither foreground nor background, something went wrong.\";\n        }\n    }\n\n    // both containers should now be empty\n    EXPECT_EQ(0, expectedForeground.size());\n    EXPECT_EQ(0, expectedBackground.size());\n}\n\n\nTEST_F(TestGraphLibrary, MaxFlowGraphKolmogorov){\n    // same example as in MaxFlowGraphBoost\n\n    // create graph with 4 vertices\n    int numberOfVertices = 3*5;\n    float smallWeight = 1;\n    float largeWeight = 1000;\n\n    MaxFlowGraphKolmogorov graph(3, 5, 1);\n\n    // add horizontal edges\n    graph.addBidirectionalEdge(0, 1, largeWeight, largeWeight);\n    graph.addBidirectionalEdge(1, 2, largeWeight, largeWeight);\n    graph.addBidirectionalEdge(2, 3, smallWeight, smallWeight);\n    graph.addBidirectionalEdge(3, 4, largeWeight, largeWeight);\n    graph.addBidirectionalEdge(5, 6, largeWeight, largeWeight);\n    graph.addBidirectionalEdge(6, 7, smallWeight, smallWeight);\n    graph.addBidirectionalEdge(7, 8, largeWeight, largeWeight);\n    graph.addBidirectionalEdge(8, 9, largeWeight, largeWeight);\n    graph.addBidirectionalEdge(10, 11, largeWeight, largeWeight);\n    graph.addBidirectionalEdge(11, 12, largeWeight, largeWeight);\n    graph.addBidirectionalEdge(12, 13, smallWeight, smallWeight);\n    graph.addBidirectionalEdge(13, 14, largeWeight, largeWeight);\n\n    // vertical edges\n    graph.addBidirectionalEdge(0, 5, largeWeight, largeWeight);\n    graph.addBidirectionalEdge(1, 6, largeWeight, largeWeight);\n    graph.addBidirectionalEdge(2, 7, smallWeight, smallWeight);\n    graph.addBidirectionalEdge(3, 8, largeWeight, largeWeight);\n    graph.addBidirectionalEdge(4, 9, largeWeight, largeWeight);\n    graph.addBidirectionalEdge(5, 10, largeWeight, largeWeight);\n    graph.addBidirectionalEdge(6, 11, largeWeight, largeWeight);\n    graph.addBidirectionalEdge(7, 12, smallWeight, smallWeight);\n    graph.addBidirectionalEdge(8, 13, largeWeight, largeWeight);\n    graph.addBidirectionalEdge(9, 14, largeWeight, largeWeight);\n\n    // connect the sources\n    std::vector<unsigned int> sourceNodes = boost::assign::list_of(0)(1)(6)(10)(11);\n    for(int i = 0; i < sourceNodes.size(); ++i){\n        graph.addTerminalEdges(sourceNodes[i], largeWeight, smallWeight);\n    }\n\n    // connect the sinks\n    std::vector<unsigned int> sinkNodes = boost::assign::list_of(3)(4)(8)(13)(14);\n    for(int i = 0; i < sinkNodes.size(); ++i){\n        graph.addTerminalEdges(sinkNodes[i], smallWeight, largeWeight);\n    }\n\n    // check if the data structure looks as expected\n    EXPECT_EQ(numberOfVertices, graph.getNumberOfVertices()); // +2 because a sink + source should've been added\n\n    // max flow\n    graph.calculateMaxFlow();\n\n    // cexpected segmentation\n    std::set<unsigned int> expectedForeground = boost::assign::list_of(0)(1)(2)(5)(6)(10)(11)(12);\n    std::set<unsigned int> expectedBackground = boost::assign::list_of(3)(4)(7)(8)(9)(13)(14);\n\n    // check the group of each vertex with the expected results\n    for(size_t index=0; index < graph.getNumberOfVertices(); ++index){\n        if(graph.groupOf(index) == graph.groupOfSource()){\n            if(expectedForeground.find(index) != expectedForeground.end()){\n                SUCCEED();\n                expectedForeground.erase(index);\n            } else{\n                FAIL() << \"missing \"<<index << \" in foreground results\";\n            }\n        }\n        else if(graph.groupOf(index) == graph.groupOfSink()){\n            if(expectedBackground.find(index) != expectedBackground.end()){\n                SUCCEED();\n                expectedBackground.erase(index);\n            } else{\n                FAIL() << \"missing \"<<index << \" in background results\";\n            }\n        }\n        else{\n            FAIL() << \"Vertex \" << index << \" is neither foreground nor background, something went wrong.\";\n        }\n    }\n\n    // both containers should now be empty\n    EXPECT_EQ(0, expectedForeground.size());\n    EXPECT_EQ(0, expectedBackground.size());\n}", "meta": {"hexsha": "ab161ca036988c343d6fcbcd47be936f38bc5e1c", "size": 16105, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "include/GraphCut3D/test/TestGraphLibrary.cpp", "max_stars_repo_name": "ypauchard/ITK-KrcahSheetnessImageFilter", "max_stars_repo_head_hexsha": "4b118a1b12dab22a0ff623003100eafc0f8e5382", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-03-08T20:38:43.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-10T09:30:46.000Z", "max_issues_repo_path": "include/GraphCut3D/test/TestGraphLibrary.cpp", "max_issues_repo_name": "thewtex/ITKKrcahSheetness", "max_issues_repo_head_hexsha": "4b118a1b12dab22a0ff623003100eafc0f8e5382", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2016-10-14T17:46:16.000Z", "max_issues_repo_issues_event_max_datetime": "2017-10-04T03:10:05.000Z", "max_forks_repo_path": "include/GraphCut3D/test/TestGraphLibrary.cpp", "max_forks_repo_name": "thewtex/ITKKrcahSheetness", "max_forks_repo_head_hexsha": "4b118a1b12dab22a0ff623003100eafc0f8e5382", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-08-02T19:26:17.000Z", "max_forks_repo_forks_event_max_datetime": "2017-08-02T19:26:17.000Z", "avg_line_length": 43.8828337875, "max_line_length": 112, "alphanum_fraction": 0.6674324744, "num_tokens": 4048, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.486551040053472}}
{"text": "#include <iostream>\n#include <stdio.h>\n\n#include <boost/numeric/mtl/utility/complexity.hpp>\n#include <boost/mpl/if.hpp>\n#include <boost/mpl/less.hpp>\n\n\nusing namespace std;\nusing namespace mtl::complexity_classes;\nnamespace mpl = boost::mpl;\n\nstruct wahr {\n  void operator() () {\n    cout << \"vrai\\n\"; }\n};\n\nstruct falsch {\n  void operator() () {\n    cout << \"faute\\n\"; }\n};\n\nvoid schreib(infinite) {\n  cout << \"unendlich\\n\"; }\n\nvoid schreib(polynomial) {\n    cout << \"polynomial\\n\"; }\n\nvoid schreib(quadratic) {\n    cout << \"quadratisch\\n\"; }\n\nvoid schreib(n_polylog_n) {\n    cout << \"n log^k n\\n\"; }\n \nvoid schreib(n_log_n) {\n    cout << \"n log n\\n\"; }\n \nvoid schreib(linear) {\n    cout << \"linear\\n\"; } \n\nvoid schreib(linear_cached) {\n    cout << \"linear cached\\n\"; }\n\nvoid schreib(polylog_n) {\n    cout << \"polynomial log\\n\"; }\n\nvoid schreib(log_n) {\n    cout << \"log\\n\"; }\n\nvoid schreib(constant) {\n    cout << \"constant\\n\"; }\n\nvoid schreib(cached) {\n    cout << \"cached\\n\"; }\n\n\n\ntemplate <typename X, typename Y> void write_less(X, Y) {\n  typedef mpl::less<X, Y> less_res;\n  typename mpl::if_<less_res, wahr, falsch>::type()();\n}\n\ntemplate <typename X, typename Y> void write_plus(X, Y) {\n  schreib(typename mtl::complexity_classes::plus<X, Y>::type());\n}\n\ntemplate <typename X, typename Y> void write_mal(X, Y) {\n  schreib(typename mtl::complexity_classes::times<X, Y>::type());\n}\n\n \nint main (int, char**) {\n\n  write_less(quadratic(), infinite());\n  write_less(quadratic(), linear());\n\n  write_plus(quadratic(), infinite());\n  write_plus(quadratic(), linear());\n  write_plus(linear(), quadratic());\n  write_plus(n_log_n(), linear());\n  \n  write_mal(quadratic(), infinite());\n  write_mal(infinite(), quadratic());\n  write_mal(quadratic(), quadratic());\n  write_mal(linear(), quadratic());\n  write_mal(linear(), log_n());\n  write_mal(linear(), polylog_n());\n  write_mal(n_log_n(), log_n());\n  write_mal(n_log_n(), polylog_n());\n  write_mal(cached(), log_n());\n  write_mal(log_n(), log_n());\n  write_mal(cached(), constant());\n\n\n\n  return 0;\n}\n", "meta": {"hexsha": "c0f3c188e093fe7f75d7c579343d4eb8bbc3fe36", "size": 2049, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/complexity_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/complexity_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/complexity_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": 20.9081632653, "max_line_length": 65, "alphanum_fraction": 0.6403123475, "num_tokens": 582, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4865510400534719}}
{"text": "// [[Rcpp::plugins(openmp)]]\n#ifdef _OPENMP\n#include <omp.h>\n#endif\n#include <Rcpp.h>\n#include <RcppEigen.h>\n#include <Eigen/Core>\n#include <random>\n#include \"distributions.h\"\n#include \"concurrentqueue.h\"\n\n// [[Rcpp::depends(RcppEigen)]]\nusing namespace Rcpp;\nusing namespace RcppEigen;\nusing namespace Eigen;\ninline void initialize_file( std::ofstream& outFile,int M,int N){\n  bool queueFull;\n  queueFull=0;\n\n\n  outFile<< \"iteration,\"<<\"mu,\";\n  for(unsigned int i = 0; i < M; ++i){\n    outFile << \"beta[\" << (i+1) << \"],\";\n\n  }\n  outFile<<\"sigmaE,\"<<\"sigmaG,\";\n  for(unsigned int i = 0; i < M; ++i){\n    outFile << \"comp[\" << (i+1) << \"],\";\n  }\n  unsigned int i;\n  for(i = 0; i < (N-1);i++){\n    outFile << \"epsilon[\" << (i+1) << \"],\";\n  }\n\n  outFile << \"epsilon[\" << (i+1) << \"]\";\n  outFile<<\"\\n\";\n}\n\n//' BayesR sampler\n//'\n//' @param outputFile The file in which the samples aftare burnin will be stored\n//' @param seed random seed\n//' @param max_iterations total of number of samples taken\n//' @param burn_in integer leq than max_iterations, number of samples used for burn in, after which, al samples will  be stored in the outputFile\n//' @param thinning thinning regime, not implemented\n//' @param X matrix of snp markers, or covariates of interest\n//' @param Y vector of response variates, must have the same number of rows as X\n//' @param sigma0 variance of the zero-centered normal prior over the intercept\n//' @param v0E degrees of  freedom of the prior inverse scaled chi-squared distribution over residues variance\n//' @param s02E  scale parameter of the prior inverse scaled chi-squared distribution over residues variance\n//' @param v0G degrees of freedom of the prior inverse scaled chi-squared distribution over genetic effects variance\n//' @param s02G  scale parameter of the prior inverse scaled chi-squared distribution over residues variance\n//' @param cva Vector of mixture components variances.\n//'\n//' @return (max_iteration - burn_in) modulo thinning samples saved in outputFile.\n//' @export\n//'\n//' @examples\n// [[Rcpp::export]]\nvoid BayesRSamplerV2(std::string outputFile, int seed, int max_iterations, int burn_in, int thinning, Eigen::MatrixXd X, Eigen::VectorXd Y,double sigma0, double v0E, double s02E, double v0G, double s02G,Eigen::VectorXd cva) {\n  int flag;\n  moodycamel::ConcurrentQueue<Eigen::VectorXd> q;\n  flag=0;\n  int N(Y.size());\n  int M(X.cols());\n  VectorXd components(M);\n  std::ofstream outFile;\n\n  outFile.open(outputFile);\n  initialize_file(outFile,M,N);\n  VectorXd sampleq(2*M+4+N);\n  IOFormat CommaInitFmt(StreamPrecision, DontAlignCols, \", \", \", \", \"\", \"\", \"\", \"\");\n  int K(cva.size()+1);\n  ////////////validate inputs\n\n  if(max_iterations < burn_in || max_iterations<1 || burn_in<1) //validations related to mcmc burnin and iterations\n  {\n    Rcpp::Rcerr<<\"error: burn_in has to be a positive integer and smaller than the maximum number of iterations \";\n    return;\n  }\n  if(sigma0 < 0 || v0E < 0 || s02E < 0 || v0G < 0||  s02G < 0 )//validations related to hyperparameters\n  {\n    Rcpp::Rcerr<<\"error: hyper parameters have to be positive\";\n    //return;\n  }\n  if((cva.array()==0).any() )//validations related to hyperparameters\n  {\n    Rcpp::Rcerr<<\"error: the zero component is already included in the model by default\";\n    //return;\n  }\n  if((cva.array()<0).any() )//validations related to hyperparameters\n  {\n    Rcpp::Rcerr<<\"error: the variance of the components should be positive\";\n    //return;\n  }\n  /////end of declarations//////\n\n\n//  Eigen::initParallel();\n // Eigen::setNbThreads(10);\n\n#ifdef _OPENMP\n omp_set_num_threads(2);\n#endif\n#pragma omp parallel num_threads(2) shared(flag,q,M,N)\n{\n#pragma omp sections\n{\n  //begin producer\n  {\n\n    //mean and residual variables\n    double mu; // mean or intercept\n    double sigmaG; //genetic variance\n    double sigmaE; // residuals variance\n\n    //component variables\n    VectorXd priorPi(K); // prior probabilities for each component\n    VectorXd pi(K); // mixture probabilities\n    VectorXd cVa(K); //component-specific variance\n    VectorXd logL(K); // log likelihood of component\n    VectorXd muk(K); // mean of k-th component marker effect size\n    VectorXd denom(K-1); // temporal variable for computing the inflation of the effect variance for a given non-zero componnet\n    double num;//storing dot product\n    int m0; // total num ber of markes in model\n    VectorXd v(K); //variable storing the component assignment\n    VectorXd cVaI(K);// inverse of the component variances\n\n    //linear model variables\n    MatrixXd beta(M,1); // effect sizes\n    VectorXd y_tilde(N); // variable containing the adjusted residuals to exclude the effects of a given marker\n    VectorXd epsilon(N); // variable containing the residuals\n    VectorXd xsquared(M); //variable containing the squared norm of the X columns\n\n    //sampler variables\n    VectorXd sample(2*M+4+N); // varible containg a sambple of all variables in the model, M marker effects, M component assigned to markers, sigmaE, sigmaG, mu, iteration number and Explained variance\n    std::vector<int> markerI;\n    for (int i=0; i<M; ++i) {\n      markerI.push_back(i);\n    }\n\n\n    int marker;\n    double acum;\n\n    priorPi[0]=0.5;\n\n\n\n    priorPi.segment(1,(K-1))=priorPi[0]*cVa.segment(1,(K-1)).segment(1,(K-1)).array()/cVa.segment(1,(K-1)).segment(1,(K-1)).sum();\n    y_tilde.setZero();\n    cVa[0] = 0;\n    cVa.segment(1,(K-1))=cva;\n\n    cVaI[0] = 0;\n    cVaI.segment(1,(K-1))=cVa.segment(1,(K-1)).cwiseInverse();\n\n    beta.setZero();\n\n    mu=0;\n\n    sigmaG=beta_rng(1,1);\n\n    pi=priorPi;\n\n    components.setZero();\n    std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now();\n    epsilon= Y.array() - mu - (X*beta).array();\n    sigmaE=epsilon.squaredNorm()/N*0.5;\n    xsquared=X.colwise().squaredNorm();\n    for(int iteration=0; iteration < max_iterations; iteration++){\n\n      if(iteration>0)\n        if( iteration % (int)std::ceil(max_iterations/10) ==0)\n          Rcpp::Rcout << \"iteration: \"<<iteration <<\"\\n\";\n\n      epsilon= epsilon.array()+mu;//  we substract previous value\n      mu = norm_rng(epsilon.sum()/(double)N, sigmaE/(double)N); //update mu\n      epsilon= epsilon.array()-mu;// we substract again now epsilon =Y-mu-X*beta\n\n\n      std::random_shuffle(markerI.begin(), markerI.end());\n\n      m0=0;\n      v.setZero();\n      for(int j=0; j < M; j++){\n\n        marker= markerI[j];\n\n\n        y_tilde= epsilon.array()+(X.col(marker)*beta(marker,0)).array();//now y_tilde= Y-mu-X*beta+ X.col(marker)*beta(marker)_old\n\n\n\n        muk[0]=0.0;//muk for the zeroth component=0\n\n       // std::cout<< muk;\n        //we compute the denominator in the variance expression to save computations\n        denom=xsquared(marker)+(sigmaE/sigmaG)*cVaI.segment(1,(K-1)).array();\n        //we compute the dot product to save computations\n        num=(X.col(marker).cwiseProduct(y_tilde)).sum();\n        //muk for the other components is computed according to equaitons\n        muk.segment(1,(K-1))= num/denom.array();\n\n\n\n        logL= pi.array().log();//first component probabilities remain unchanged\n\n\n        //update the log likelihood for each component\n        logL.segment(1,(K-1))=logL.segment(1,(K-1)).array() - 0.5*((((sigmaG/sigmaE)*(xsquared(marker)))*cVa.segment(1,(K-1)).array() + 1).array().log()) + 0.5*( muk.segment(1,(K-1)).array()*num)/sigmaE;\n\n        double p(beta_rng(1,1));//I use beta(1,1) because I cant be bothered in using the std::random or create my own uniform distribution, I will change it later\n\n\n        if(((logL.segment(1,(K-1)).array()-logL[0]).abs().array() >700 ).any() ){\n         acum=0;\n        }else{\n          acum=1.0/((logL.array()-logL[0]).exp().sum());\n        }\n\n        for(int k=0;k<K;k++){\n          if(p<=acum){\n            //if zeroth component\n            if(k==0){\n              beta(marker,0)=0;\n            }else{\n              beta(marker,0)=norm_rng(muk[k],sigmaE/denom[k-1]);\n            }\n            v[k]+=1.0;\n            components[marker]=k;\n            break;\n          }else{\n            //if too big or too small\n            if(((logL.segment(1,(K-1)).array()-logL[k+1]).abs().array() >700 ).any() ){\n              acum+=0;\n            }\n            else{\n              acum+=1.0/((logL.array()-logL[k+1]).exp().sum());\n            }\n          }\n        }\n       epsilon=y_tilde-X.col(marker)*beta(marker,0);//now epsilon contains Y-mu - X*beta+ X.col(marker)*beta(marker)_old- X.col(marker)*beta(marker)_new\n\n      }\n\n      m0=M-v[0];\n      sigmaG=inv_scaled_chisq_rng(v0G+m0,(beta.squaredNorm()*m0+v0G*s02G)/(v0G+m0));\n\n\n      sigmaE=inv_scaled_chisq_rng(v0E+N,((epsilon).squaredNorm()+v0E*s02E)/(v0E+N));\n\n\n\n      pi=dirichilet_rng(v.array() + 1.0);\n\n      if(iteration >= burn_in)\n      {\n        if(iteration % thinning == 0){\n          sample<< iteration,mu,beta,sigmaE,sigmaG,components,epsilon;\n          q.enqueue(sample);\n#ifdef _OPENMP\n\n#else\n          if(q.try_dequeue(sampleq))\n            outFile<< sampleq.transpose().format(CommaInitFmt) << \"\\n\";\n#endif\n           //here we have the consumer\n\n        }\n\n      }\n\n    }\n\n    std::chrono::high_resolution_clock::time_point t2 = std::chrono::high_resolution_clock::now();\n    auto duration = std::chrono::duration_cast<std::chrono::seconds>( t2 - t1 ).count();\n    Rcpp::Rcout << \"duration: \"<<duration << \"s\\n\";\n    flag=1;\n  }//end producer\n#ifdef _OPENMP\n#pragma omp section\n      {\n\n        while(!flag ){\n          if(q.try_dequeue(sampleq))\n            outFile<< sampleq.transpose().format(CommaInitFmt) << \"\\n\";\n        }\n      }//end consumer\n#endif\n}\n}\n\n}\n\n\n/*** R\nM=200 #non zero marker effects\nN=2000 #observations\nMT=2000 #number of markers\nB=matrix(rnorm(MT,sd=sqrt(0.5)),ncol=1) #marker effects, M marquers explain approx 50% of the variance\nB[sample(1:MT,MT-M),1]=0 #we set MT-M marker effects to zero\n#B=-abs(B)\nX <- matrix(rnorm(MT*N), N, MT); var(X[,1])\nG <- X%*%B; var(G)\nY=X%*%B+rnorm(N,sd=sqrt(0.4)); var(Y)\nY=Y\nX=scale(X)\nP=0.5 #prior probability of a marker being excluded from the model\nsigma0=0.01# prior  variance of a zero mean gaussian prior over the mean mu NOT IMPLEMENTED\nv0E=0.01 # degrees of freedom over the inv scaled chi square prior over residuals variance\ns02E=0.01 #scale of the inv scaled chi square prior over residuals variance\nv0G=0.01 #degrees of freedom of the inv bla bla prior over snp effects\ns02G=0.01 # scale for the same\nBayesRSamplerV2(\"./test2.csv\",2, 5000, 2000,10,X, Y,sigma0,v0E,s02E,v0G,s02G,P)\nlibrary(readr)\ntmp <- read_csv(\"./test2.csv\")\n#names(tmp)\n#plot(tmp$sigmaG); mean(tmp$sigmaG)\nplot(B,colMeans(tmp[,grep(\"beta\",names(tmp))]))\nlines(B,B)\nabline(h=0)\nvar(G)\nmean(tmp$EV)\n1-var(G)\nmean(tmp$sigmaE)\nplot(tmp$mu)\nplot(tmp$sigmaE)\nplot(tmp$sigmaG)\nhist(as.matrix(tmp[,grep(\"comp\",names(tmp))])) #histogram of components, component 0= variance 0, component 1= variance 0.0001 and so long so forth\n*/\n\n", "meta": {"hexsha": "b2e871ce15479ddf3c9d0d04ccc8325a5b019d2b", "size": 10896, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/BayesRv2.cpp", "max_stars_repo_name": "ctggroup/BayesRRcpp", "max_stars_repo_head_hexsha": "23381fcc5db93916f875c005529c8b8cba6fd78a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-14T16:05:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T16:05:16.000Z", "max_issues_repo_path": "src/BayesRv2.cpp", "max_issues_repo_name": "ctggroup/BayesRRcpp", "max_issues_repo_head_hexsha": "23381fcc5db93916f875c005529c8b8cba6fd78a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/BayesRv2.cpp", "max_forks_repo_name": "ctggroup/BayesRRcpp", "max_forks_repo_head_hexsha": "23381fcc5db93916f875c005529c8b8cba6fd78a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.7207207207, "max_line_length": 225, "alphanum_fraction": 0.6427129222, "num_tokens": 3123, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4865510400534719}}
{"text": "#ifndef SDE_HPP_\n#define SDE_HPP_\n\n#include <boost/numeric/odeint.hpp>\n\n#include \"aux.hpp\"\n\n/** EM implementation taking std::vector.\n * Works with non-diagonal noise.\n */\nclass EulerMaruyamaStepper {\npublic:\n  EulerMaruyamaStepper(Rng & rng) : rng(rng) { /* empty */ }\n  typedef std::vector<double> state_type;\n  typedef std::vector<double> deriv_type;\n  typedef double value_type;\n  typedef double time_type;\n  typedef double order_type;\n  typedef boost::numeric::odeint::stepper_tag stepper_category;\n  static order_type order() {\n    return 0.5;\n  }\n  template<class System>\n  void do_step(System system, state_type & x, time_type t, time_type dt) const {\n    deriv_type F(x.size()), G(x.size());\n    system(x, F, t);\n    // first query dimension of the Wiener process\n    int wdim = system.get().wiener_dim();\n    // sample a step of the Wiener process\n    std::vector<double> Zi(wdim);\n    std::generate(Zi.begin(), Zi.end(), [&](){return rng.normal(0, 1);});\n    // now query for the dimension of the SDEs to allow for OD\n    int cdim = system.get().continuous_dim();\n    // sample a step of the Wiener process\n    std::vector<double> Zo(cdim);\n    std::generate(Zo.begin(), Zo.end(), [&](){return rng.normal(0, 1);});\n    // use the volatility_vec_prod method from VectorField\n    system.get().volatility_vec_prod(x, G, t, Zi, Zo);\n    for ( size_t i = 0; i < x.size(); ++i ) {\n      x[i] += dt * F[i] + sqrt(dt) * G[i]; // G = sigma * Z\n    }\n  }\nprivate:\n  /** ref to an RNG. Used to create normal deviates\n   * @todo: construct actual RNG instead?\n   */\n  Rng & rng;\n};\n\n/** EM implementation taking std::vector.\n * Only works with diagonal noise.\n */\nclass EulerMaruyamaStepperDiag {\npublic:\n  EulerMaruyamaStepperDiag(Rng & rng) : rng(rng) { /* empty */ }\n  typedef std::vector<double> state_type;\n  typedef std::vector<double> deriv_type;\n  typedef double value_type;\n  typedef double time_type;\n  typedef double order_type;\n  typedef boost::numeric::odeint::stepper_tag stepper_category;\n  static order_type order() {\n    return 0.5;\n  }\n  template<class System>\n  void do_step(System system, state_type & x, time_type t, time_type dt) const {\n    deriv_type F(x.size()), G(x.size());\n    system(x, F, t);\n    system.get().diffusion(x, G, t);\n    for ( size_t i = 0; i < x.size(); ++i ) {\n      double Z = rng.normal(0, 1);\n      x[i] += dt * F[i] + sqrt(dt) * G[i] * Z;\n    }\n  }\nprivate:\n  /** ref to an RNG. Used to create normal deviates\n   * @todo: construct actual RNG instead?\n   */\n  Rng & rng;\n};\n\n\n/** Runge-Kutta discretization of the Milstein scheme.\n * Only works for diagonal noise.\n *\n * @todo: check restrictions: we need that sigma_ii is\n * only dependent of x_i.\n */\n class RungeKuttaMilsteinStepper {\n public:\n   RungeKuttaMilsteinStepper(Rng & rng) : rng(rng) { /* empty */ }\n   typedef std::vector<double> state_type;\n   typedef std::vector<double> deriv_type;\n   typedef double value_type;\n   typedef double time_type;\n   typedef double order_type;\n   typedef boost::numeric::odeint::stepper_tag stepper_category;\n   static order_type order() {\n     return 1.0;\n   }\n   /** The Millstein method takes steps as follows:\n    * \\f[\n    *  Y_{n+1} = Y_n + f_n h + g_n \\Delta W_n + \\frac12 g_n g_n' [\\Delta W_n^2 - h]\n    * \\f]\n    * with \\f$ f_n = f(Y_n) \\f$, \\f$ g_n = g(Y_n) \\f$ and\n    * \\f$ g_n' = \\frac{\\partial g}{\\partial x}(Y_n) \\f$, and\n    * \\f$ \\Delta W_n \\sim \\sqrt{h} \\mathcal{N}(0,1) \\f$.\n    * The Kunge-Kutta approximation removes the need for a derivative,\n    * and uses an intermediate step \\f$ \\bar{Y}_n = Y_n + f_n h + g_n \\sqrt{h} \\f$.\n    * The next value is then calculated as\n    * \\f[\n    *  Y_{n+1} = Y_n + f_n h + g_n \\Delta W_n +\n    *    \\frac12 g_n \\frac{1}{\\sqrt{h}}(\\bar{g}_n-g_n)[\\Delta W_n^2 - h]\n    * \\f]\n    * where \\f$ \\bar{g}_n = g(\\bar{Y}_n) \\f$.\n    */\n   template<class System>\n   void do_step(System system, state_type & x, time_type t, time_type dt) const {\n     deriv_type F(x.size()), G(x.size()), Gtilde(x.size());\n     state_type xtilde(x.size());\n     time_type sqdt = sqrt(dt);\n     system(x, F, t);\n     system.get().diffusion(x, G, t);\n     // define intermediate step\n     for ( size_t i = 0; i < x.size(); ++i ) {\n       xtilde[i] = x[i] + dt*F[i] + sqdt*G[i];\n     }\n     // define Gtilde\n     system.get().diffusion(xtilde, Gtilde, t);\n     // update x\n     for ( size_t i = 0; i < x.size(); ++i ) {\n       double dW = rng.normal(0, 1) * sqdt;\n       x[i] += dt*F[i] + G[i]*dW + 0.5*(Gtilde[i] - G[i]) * (dW*dW - dt) / sqdt;\n     }\n   }\n private:\n   Rng & rng; // ref to an RNG\n };\n\n\n/** @todo Implementation of an adaptive Stochastic Runge Kutta (SRK) method\n * using Rejection Sampling with Memory (RSwM)\n */\n\n\n\n\n\n#endif\n", "meta": {"hexsha": "229211444f616308fb6cb98f0a9fa824a72db3f9", "size": 4713, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stochepi/src/sde.hpp", "max_stars_repo_name": "eeg-lanl/sarscov2-selection", "max_stars_repo_head_hexsha": "c2087cbaf55de9930736aa6677a57008a2397583", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "stochepi/src/sde.hpp", "max_issues_repo_name": "eeg-lanl/sarscov2-selection", "max_issues_repo_head_hexsha": "c2087cbaf55de9930736aa6677a57008a2397583", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stochepi/src/sde.hpp", "max_forks_repo_name": "eeg-lanl/sarscov2-selection", "max_forks_repo_head_hexsha": "c2087cbaf55de9930736aa6677a57008a2397583", "max_forks_repo_licenses": ["BSD-3-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.42, "max_line_length": 83, "alphanum_fraction": 0.6199872693, "num_tokens": 1460, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4865469252001073}}
{"text": "/*\n * Copyright 2021 MusicScience37 (Kenta Kabashima)\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\n * \\brief Test of blurred sine function.\n */\n#include \"num_prob_collect/regularization/blur_sine.h\"\n\n#include <cmath>\n#include <random>\n\n#include <Eigen/Core>\n#include <celero/Celero.h>\n\n#include \"log_error_udm.h\"\n#include \"log_param_udm.h\"\n#include \"num_collect/regularization/explicit_gcv.h\"\n#include \"num_collect/regularization/explicit_l_curve.h\"\n#include \"num_collect/regularization/full_gen_tikhonov.h\"\n#include \"num_collect/regularization/tikhonov.h\"\n#include \"num_prob_collect/regularization/dense_diff_matrix.h\"\n\n// NOLINTNEXTLINE: external library\nCELERO_MAIN\n\nclass blur_sine_fixture : public celero::TestFixture {\npublic:\n    blur_sine_fixture() = default;\n\n    [[nodiscard]] auto getExperimentValues() const\n        -> std::vector<celero::TestFixture::ExperimentValue> override {\n        std::vector<celero::TestFixture::ExperimentValue> problem_space;\n        problem_space.emplace_back(-100);  // NOLINT\n        problem_space.emplace_back(-4);    // NOLINT\n        problem_space.emplace_back(-2);    // NOLINT\n        problem_space.emplace_back(0);     // NOLINT\n        return problem_space;\n    }\n\n    void setUp(\n        const celero::TestFixture::ExperimentValue& experiment_value) override {\n        error_rate_ = std::pow(10.0,  // NOLINT\n            static_cast<int>(experiment_value.Value));\n        std::mt19937 engine;  // NOLINT\n        std::normal_distribution<double> dist{0.0,\n            std::sqrt(prob_.data().squaredNorm() /\n                static_cast<double>(prob_.data().size()) * error_rate_)};\n        data_with_error_ = prob_.data();\n        for (num_collect::index_type i = 0; i < data_with_error_.size(); ++i) {\n            data_with_error_(i) += dist(engine);\n        }\n    }\n\n    void set_error(const Eigen::VectorXd& solution) {\n        log_error_->addValue(\n            std::log10((solution - prob_.solution()).squaredNorm() /\n                prob_.solution().squaredNorm()));\n    }\n\n    void set_param(double val) { log_param_->addValue(std::log10(val)); }\n\n    [[nodiscard]] auto getUserDefinedMeasurements() const -> std::vector<\n        std::shared_ptr<celero::UserDefinedMeasurement>> override {\n        return {log_error_, log_param_};\n    }\n\n    [[nodiscard]] auto prob() const\n        -> const num_prob_collect::regularization::blur_sine& {\n        return prob_;\n    }\n\n    [[nodiscard]] auto data_with_error() const -> const Eigen::VectorXd& {\n        return data_with_error_;\n    }\n\n    [[nodiscard]] auto dense_diff_matrix() const -> const Eigen::MatrixXd& {\n        return dense_diff_matrix_;\n    }\n\nprivate:\n    double error_rate_{};\n\n#ifndef NDEBUG\n    static constexpr num_collect::index_type solution_size = 30;\n    static constexpr num_collect::index_type data_size = solution_size;\n#else\n    static constexpr num_collect::index_type solution_size = 60;\n    static constexpr num_collect::index_type data_size = solution_size;\n#endif\n    const num_prob_collect::regularization::blur_sine prob_{\n        data_size, solution_size};\n\n    Eigen::VectorXd data_with_error_{};\n\n    const Eigen::MatrixXd dense_diff_matrix_{\n        num_prob_collect::regularization::dense_diff_matrix<Eigen::MatrixXd>(\n            solution_size)};\n\n    std::shared_ptr<log_error_udm> log_error_{\n        std::make_shared<log_error_udm>()};\n    std::shared_ptr<log_param_udm> log_param_{\n        std::make_shared<log_param_udm>()};\n};\n\nconstexpr std::int64_t samples = 30;\n#ifndef NDEBUG\nconstexpr std::int64_t iterations = 1;\n#else\nconstexpr std::int64_t iterations = 10;\n#endif\n\nusing coeff_type =\n    typename num_prob_collect::regularization::blur_sine::coeff_type;\nusing data_type =\n    typename num_prob_collect::regularization::blur_sine::data_type;\n\n// NOLINTNEXTLINE: external library\nBASELINE_F(\n    reg_blur_sine, tikhonov_l_curve, blur_sine_fixture, samples, iterations) {\n    using solver_type =\n        num_collect::regularization::tikhonov<coeff_type, data_type>;\n    using searcher_type =\n        num_collect::regularization::explicit_l_curve<solver_type>;\n\n    solver_type solver;\n    solver.compute(prob().coeff(), data_with_error());\n\n    searcher_type searcher{solver};\n    searcher.search();\n    Eigen::VectorXd solution;\n    searcher.solve(solution);\n\n    set_error(solution);\n    set_param(searcher.opt_param());\n}\n\n// NOLINTNEXTLINE: external library\nBENCHMARK_F(\n    reg_blur_sine, tikhonov_gcv, blur_sine_fixture, samples, iterations) {\n    using solver_type =\n        num_collect::regularization::tikhonov<coeff_type, data_type>;\n    using searcher_type =\n        num_collect::regularization::explicit_gcv<solver_type>;\n\n    solver_type solver;\n    solver.compute(prob().coeff(), data_with_error());\n\n    searcher_type searcher{solver};\n    searcher.search();\n    Eigen::VectorXd solution;\n    searcher.solve(solution);\n\n    set_error(solution);\n    set_param(searcher.opt_param());\n}\n\n// NOLINTNEXTLINE: external library\nBENCHMARK_F(reg_blur_sine, full_gen_tik_l_curve, blur_sine_fixture, samples,\n    iterations) {\n    using solver_type =\n        num_collect::regularization::full_gen_tikhonov<coeff_type, data_type>;\n    using searcher_type =\n        num_collect::regularization::explicit_l_curve<solver_type>;\n\n    solver_type solver;\n    solver.compute(prob().coeff(), data_with_error(), dense_diff_matrix());\n\n    searcher_type searcher{solver};\n    searcher.search();\n    Eigen::VectorXd solution;\n    searcher.solve(solution);\n\n    set_error(solution);\n    set_param(searcher.opt_param());\n}\n\n// NOLINTNEXTLINE: external library\nBENCHMARK_F(\n    reg_blur_sine, full_gen_tik_gcv, blur_sine_fixture, samples, iterations) {\n    using solver_type =\n        num_collect::regularization::full_gen_tikhonov<coeff_type, data_type>;\n    using searcher_type =\n        num_collect::regularization::explicit_gcv<solver_type>;\n\n    solver_type solver;\n    solver.compute(prob().coeff(), data_with_error(), dense_diff_matrix());\n\n    searcher_type searcher{solver};\n    searcher.search();\n    Eigen::VectorXd solution;\n    searcher.solve(solution);\n\n    set_error(solution);\n    set_param(searcher.opt_param());\n}\n", "meta": {"hexsha": "011ef60486855a1ace669bb6a5b5351861bda038", "size": 6700, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/bench/regularization/blur_sine_test.cpp", "max_stars_repo_name": "MusicScience37/numerical-collection-cpp", "max_stars_repo_head_hexsha": "490c24aae735ba25f1060b2941cff39050a41f8f", "max_stars_repo_licenses": ["Apache-2.0"], "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/bench/regularization/blur_sine_test.cpp", "max_issues_repo_name": "MusicScience37/numerical-collection-cpp", "max_issues_repo_head_hexsha": "490c24aae735ba25f1060b2941cff39050a41f8f", "max_issues_repo_licenses": ["Apache-2.0"], "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/bench/regularization/blur_sine_test.cpp", "max_forks_repo_name": "MusicScience37/numerical-collection-cpp", "max_forks_repo_head_hexsha": "490c24aae735ba25f1060b2941cff39050a41f8f", "max_forks_repo_licenses": ["Apache-2.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.0574162679, "max_line_length": 80, "alphanum_fraction": 0.7080597015, "num_tokens": 1565, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478255, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.486546919563352}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2015 NumScale SAS\n  @copyright 2015 J.T. Lapreste\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_ROUND_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_ROUND_HPP_INCLUDED\n#include <boost/simd/function/std.hpp>\n\n#include <boost/simd/constant/half.hpp>\n#include <boost/simd/constant/maxflint.hpp>\n#include <boost/simd/function/scalar/abs.hpp>\n#include <boost/simd/function/scalar/ceil.hpp>\n#include <boost/simd/function/scalar/copysign.hpp>\n#include <boost/simd/function/scalar/is_ltz.hpp>\n#include <boost/simd/function/scalar/seldec.hpp>\n#include <boost/simd/function/scalar/tenpower.hpp>\n#include <boost/simd/detail/math.hpp>\n#include <boost/dispatch/function/overload.hpp>\n#include <boost/config.hpp>\n#include <cmath>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  BOOST_DISPATCH_OVERLOAD ( round_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_< bd::integer_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() ( A0 a0) const BOOST_NOEXCEPT\n    {\n      return a0;\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( round_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_< bd::single_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() ( A0 a0) const BOOST_NOEXCEPT\n    {\n    #ifdef BOOST_SIMD_HAS_ROUNDF\n      return ::roundf(a0);\n    #else\n      const A0 v = simd::abs(a0);\n      if (!(v <=  Maxflint<A0>()))\n        return a0;\n      A0 c =  boost::simd::ceil(v);\n       return copysign(seldec(c-Half<A0>() > v, c), a0);\n    #endif\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( round_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_< bd::double_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() ( A0 a0) const BOOST_NOEXCEPT\n    {\n    #ifdef BOOST_SIMD_HAS_ROUND\n      return ::round(a0);\n    #else\n      const A0 v = simd::abs(a0);\n      if (!(v <=  Maxflint<A0>()))\n        return a0;\n      A0 c =  boost::simd::ceil(v);\n      return copysign(seldec(c-Half<A0>() > v, c), a0);\n    #endif\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( round_\n                          , (typename A0, typename A1)\n                          , bd::cpu_\n                          , bd::scalar_< bd::floating_<A0> >\n                          , bd::scalar_< bd::integer_<A1> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() ( A0 a0, A1 a1) const BOOST_NOEXCEPT\n    {\n      using i_t = bd::as_integer_t<A0>;\n      A0 fac = tenpower(i_t(a1));\n      A0 tmp = round(a0*fac)/fac;\n      return is_ltz(a1) ? round(tmp) : tmp;\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( round_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_< bd::floating_<A0> >\n                          , bs::std_tag\n                         )\n  {\n    BOOST_FORCEINLINE A0 operator() ( A0  a0, std_tag const&) const BOOST_NOEXCEPT\n    {\n      return std::round(a0);\n    }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "6d1e702ed43402ced52c9e0c58008388ad9b3d81", "size": 3509, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arch/common/scalar/function/round.hpp", "max_stars_repo_name": "yaeldarmon/boost.simd", "max_stars_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/simd/arch/common/scalar/function/round.hpp", "max_issues_repo_name": "yaeldarmon/boost.simd", "max_issues_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/arch/common/scalar/function/round.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": 30.25, "max_line_length": 100, "alphanum_fraction": 0.5123966942, "num_tokens": 861, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478255, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4865469195633519}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include \"util.h\"\n#include \"cppcnn.h\"\n\nusing Eigen::MatrixXd;\n\nint main() {\n    using namespace std;\n\n\tcout.sync_with_stdio(false);\n\tcout << \"Threads:\" << Eigen::nbThreads() << endl;\n\n\t/* inputs matrix: [n * m], m is the pixels number of one image, n is the number of examples.\n\t * labels matrix: [m * 1], m is the number of labels.\n\t */\n    auto train_inputs = util::read_mnist(\"../../data/mnist/train-images.idx3-ubyte\", \n\t\t\t\t\t\t\t\t\t\t \"../../data/mnist/train-labels.idx1-ubyte\");\n\tauto test_inputs = util::read_mnist(\"../../data/mnist/t10k-images.idx3-ubyte\",\n\t\t\t\t\t\t\t\t\t\t\"../../data/mnist/t10k-labels.idx1-ubyte\");\n\n\tauto cnn = make_shared<CppCNN>();\n\tcnn->set_enable_momentum(false);\n\tcnn->set_enable_adam(false);\n\tcnn->set_learn_rate_decay(false);\n\tcnn->set_output_size(10);\n\tcnn->set_learn_rate(0.005);\n\tcnn->set_max_epoch(3);\n\tcnn->set_minibatch_size(1);\n\n\tcnn->add_conv_layer(3, 8);\n\tcnn->add_max_pool_layer(2, 2);\n\tcnn->set_hidden_layers({32, 16});\n\n\tcnn->train(train_inputs.first, train_inputs.second);\n\n\tcnn->test(test_inputs.first, test_inputs.second);\n\n    return 0;\n}", "meta": {"hexsha": "2ce54c9937dbab7c43ef12f9ff833e61beb5f151", "size": 1120, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cppcnn/run_mnist.cpp", "max_stars_repo_name": "jin-qin/cppcnn", "max_stars_repo_head_hexsha": "96c58a2d8a7f2bafac7ea1d02b76fa67ae15159b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-12-20T03:10:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-28T23:53:31.000Z", "max_issues_repo_path": "src/cppcnn/run_mnist.cpp", "max_issues_repo_name": "jin-qin/cppcnn", "max_issues_repo_head_hexsha": "96c58a2d8a7f2bafac7ea1d02b76fa67ae15159b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cppcnn/run_mnist.cpp", "max_forks_repo_name": "jin-qin/cppcnn", "max_forks_repo_head_hexsha": "96c58a2d8a7f2bafac7ea1d02b76fa67ae15159b", "max_forks_repo_licenses": ["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.0, "max_line_length": 93, "alphanum_fraction": 0.6803571429, "num_tokens": 319, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736692, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.4865349587938964}}
{"text": "/*=========================================================================\n\n medInria\n\n Copyright (c) INRIA 2013. All rights reserved.\n See LICENSE.txt 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.\n\n=========================================================================*/\n\n#include <vector>\n#include <complex>\n#include <cmath>\n\n#include <vtkSphericalHarmonicSource.h>\n\n#include <vtkPolyDataNormals.h>\n#include <vtkCellArray.h>\n#include <vtkFloatArray.h>\n#include <vtkInformation.h>\n#include <vtkInformationVector.h>\n#include <vtkMath.h>\n#include <vtkObjectFactory.h>\n#include <vtkPointData.h>\n#include <vtkPoints.h>\n#include <vtkPolyData.h>\n#include <vtkMatrix4x4.h>\n#include <vtkStreamingDemandDrivenPipeline.h>\n\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n// Compute spherical associated Legendre function\n#if (defined __APPLE__ || defined WIN32 || defined CLANG)\n#include <boost/math/special_functions/legendre.hpp>\n#else\n#include <tr1/cmath>\n#endif //WIN32\n\n#if (defined __APPLE__ || defined WIN32 || defined CLANG)\ndouble sphLegendre(int _l, int _m, double theta) {\n  double factor = sqrt(((double)(2*_l+1) / (4.0*vtkMath::DoublePi()))*(boost::math::factorial<double>((unsigned int)(_l - _m))\n                                                        / boost::math::factorial<double>((unsigned int)(_l + _m))))*boost::math::legendre_p (_l, _m, cos(theta));\n    return factor;\n}\n#else\ndouble sphLegendre(int _l, int _m, double theta) {\n    double factor =std::tr1::sph_legendre(_l,_m,theta);\n    return factor;\n}\n#endif //WIN32\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n\nstatic itk::Vector<double, 3> Cartesian2Spherical(const itk::Vector<double, 3> vITK );\n\nstatic itk::VariableSizeMatrix<double>\nComputeSHMatrixMaxThesis(const int rank,vtkPolyData *shell,const bool FlipX,const bool FlipY,\n                         const bool FlipZ,itk::VariableSizeMatrix<double>& PhiThetaDirections);\n\nstatic itk::VariableSizeMatrix<double>\nComputeSHMatrixTournier(const int rank,vtkPolyData *shell,const bool FlipX,const bool FlipY,\n                        const bool FlipZ,itk::VariableSizeMatrix<double>& PhiThetaDirections);\n\nstatic itk::VariableSizeMatrix<double>\nComputeSHMatrixRshBasis(const int rank,vtkPolyData *shell,const bool FlipX,const bool FlipY,\n                        const bool FlipZ,itk::VariableSizeMatrix<double>& PhiThetaDirections);\n\nstatic itk::VariableSizeMatrix<double>\nComputeSHMatrix (const int rank,vtkPolyData *shell,const bool FlipX,const bool FlipY,\n                 const bool FlipZ, itk::VariableSizeMatrix<double>& PhiThetaDirections);\n\n\nstatic void\nTranslateAndDeformShell(vtkPolyData* shell,vtkPoints* outPts,double center[3],\n                        bool deform,vtkMatrix4x4* transform=0);\n\nvtkCxxRevisionMacro(vtkSphericalHarmonicSource,\"$Revision: 0 $\");\nvtkStandardNewMacro(vtkSphericalHarmonicSource);\n\nvtkSphericalHarmonicSource::vtkSphericalHarmonicSource(int tess)\n{\n  this->Radius = 0.5;\n  this->Center[0] = 0.0;\n  this->Center[1] = 0.0;\n  this->Center[2] = 0.0;\n  this->RotationMatrix = 0;\n\n  this->SetNumberOfInputPorts(0);\n\n  this->DeformOn();\n  this->NormalizeOff();\n  this->FlipXOff();\n  this->FlipYOff();\n  // By Default we flip the z-axis, the internal x,y,z have z flipped with respect to visu\n  this->FlipZOn();\n  this->MaxThesisFuncOff();\n\n  this->TesselationType = Icosahedron;\n  this->TesselationBasis = SHMatrix;\n  this->Tesselation = tess;\n  this->sphereT = vtkTessellatedSphereSource::New();\n this-> SphericalHarmonics = 0;\n this-> Order = 4;\n  this->SetNumberOfSphericalHarmonics (15);\n}\n\nvtkSphericalHarmonicSource::~vtkSphericalHarmonicSource()\n{\n  if (this->sphereT)\n    this->sphereT->Delete();\n\n  if(this->RotationMatrix)\n    this->RotationMatrix->Delete();\n\n  SphericalHarmonics = 0;\n}\n\nvoid vtkSphericalHarmonicSource::SetNumberOfSphericalHarmonics(const int number)\n{\n  NumberOfSphericalHarmonics = number;\n  if (SphericalHarmonics)\n    delete[] SphericalHarmonics;\n  SphericalHarmonics = new double[NumberOfSphericalHarmonics];\n  SphericalHarmonics[0] = 1.0;\n  for(int i=1;i<NumberOfSphericalHarmonics;++i)\n    SphericalHarmonics[i] = 0.0;\n\n  this->UpdateSphericalHarmonicSource();\n  this->Modified();\n}\n\nint* vtkSphericalHarmonicSource::GetTesselationRange()\n{\n  int* range = new int[2];\n  GetTesselationRange(range);\n  return range;\n}\n\nvoid vtkSphericalHarmonicSource::GetTesselationRange(int *range)\n{\n  range[0] = 2;\n  range[1] = 5;\n}\n\nvoid vtkSphericalHarmonicSource::SetSphericalHarmonicComponent(int i,double v)\n{\n  if (SphericalHarmonics[i]!=v)\n  {\n    vtkDebugMacro(<< this->GetClassName() << \" (\" << this\n                  <<\"): setting Spherical Harmonics coefficient \"<< i <<\" to \"<< v);\n    this->Modified();\n    SphericalHarmonics[i] = v;\n  }\n}\n\nint\nvtkSphericalHarmonicSource::\nRequestData(vtkInformation *vtkNotUsed(request),vtkInformationVector **vtkNotUsed(inputVector),\n            vtkInformationVector *outputVector)\n{\n  // Get the info and output objects.\n  vtkInformation* outInfo = outputVector->GetInformationObject(0);\n  vtkPolyData*    output  = vtkPolyData::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT()));\n  int N = this->sphereT->GetOutput()->GetNumberOfPoints();\n  // SH Source stuff.\n  vtkFloatArray* sValues = vtkFloatArray::New();\n  sValues->SetNumberOfTuples(N);\n  sValues->SetNumberOfComponents(1);\n\n  /* Project data on the sphere:\n    In matrix form:\n    S := spherical function (discrete data on the sphere)\n    C := Spherical harmonic coefficients\n    B := Basis function \n    S = CB\n    */\n\n  itk::VariableSizeMatrix<double> C(1,NumberOfSphericalHarmonics);\n\n  for (int i=0;i<NumberOfSphericalHarmonics;++i){\n    C(0,i) = SphericalHarmonics[i];\n  }\n\n  itk::VariableSizeMatrix<double> S/*(1,BasisFunction.GetVnlMatrix().size())*/;\n  S = C*BasisFunction;\n\n  if (Normalize) {\n\n    double min = S.GetVnlMatrix().min_value();\n    double max = S.GetVnlMatrix().max_value();\n\n//    std::cout << \"Normalizing by min/max\" << min << \"/\" << max << \"\\n\";\n\n    if (max!=min) {\n      for (unsigned i=0; i<S.Rows(); ++i)\n        for (unsigned j=0; j<S.Cols(); ++j)\n          S(i,j) -= min;\n      S /= (max-min);\n    } else {\n      for (unsigned i=0; i<S.Rows(); ++i)\n        for (unsigned j=0; j<S.Cols(); ++j)\n          S(i,j) = 1.0;\n    }\n  }\n  S *= this->Radius;\n\n  for(int i=0; i<N; ++i) {\n    if  (i%10000==0) {\n      this->UpdateProgress ((vtkFloatingPointType)i/N);\n      if (this->GetAbortExecute())\n        break;\n    }\n    sValues->SetTuple1(i,S(0,i));\n  }\n\n  this->sphereT->GetOutput()->GetPointData()->SetScalars(sValues);\n  sValues->Delete();\n\n  // Don't know how to copy everything but the points.\n  output->DeepCopy(this->sphereT->GetOutput());\n  output->GetPoints()->Reset();\n\n  TranslateAndDeformShell(this->sphereT->GetOutput(),output->GetPoints(),this->Center,Deform,RotationMatrix);\n\n  return 1;\n}\n\nvoid vtkSphericalHarmonicSource::PrintSelf(ostream& os,vtkIndent indent)\n{\n  this->Superclass::PrintSelf(os,indent);\n\n  os << indent << \"Tessellation Order: \" << Tesselation << std::endl;\n  os << indent << \"Tessellation Type: \" << TesselationType << std::endl;\n  os << indent << \"Tessellation Basis: \" << TesselationBasis << std::endl;\n\n  os << indent << \"SH Basis Order: \" << Order << std::endl;\n  os << indent << \"Length of SH coefficient vector: \"\n     << NumberOfSphericalHarmonics << std::endl;\n  os << indent << \"SH Basis: \" << NumberOfSphericalHarmonics << \"x\"\n     << this->sphereT->GetOutput()->GetNumberOfPoints() << std::endl;\n  os << indent << \"SH Coefficients:\" << std::endl << '[';\n  for (int i=0;i<NumberOfSphericalHarmonics;++i)\n    os << indent << SphericalHarmonics[i] << \" \";\n  os << indent << ']' << std::endl;\n}\n\nint vtkSphericalHarmonicSource::RequestInformation(vtkInformation*,vtkInformationVector**,\n                                                   vtkInformationVector *outputVector)\n{\n  // Get the info object\n  vtkInformation* outInfo = outputVector->GetInformationObject(0);\n\n  outInfo->Set(vtkStreamingDemandDrivenPipeline::MAXIMUM_NUMBER_OF_PIECES(),-1);\n  outInfo->Set(vtkStreamingDemandDrivenPipeline::WHOLE_BOUNDING_BOX(),\n               this->Center[0]-this->Radius,this->Center[0]+this->Radius,\n               this->Center[1]-this->Radius,this->Center[1]+this->Radius,\n               this->Center[2]-this->Radius,this->Center[2]+this->Radius);\n\n  return 1;\n}\n\nitk::Vector<double, 3> Cartesian2Spherical(const itk::Vector<double, 3> vITK)\n{\n  const double r =vITK.GetNorm();\n  if (r==0) {\n    std::cerr << \"Cannot have a 0 radius in spherical coordinates!\\n\" << std::endl;\n    exit(1);\n  }\n  // r, phi [0, PI), theta [0, PI) computation\n  const double spherical [3] = { vITK.GetNorm(), atan2(vITK[1],vITK[0]), acos(vITK[2]/r)};\n  const itk::Vector<double, 3> s (spherical);\n\n  return s;\n}\n\n\n/*\n  Compute SH matrix for discrete samplings on the sphere\n  rank := number of spherical harmonics (rank of HOT in Reseach report 5681)\n  n_s  := number of spherical values on the sphere (Research report 5681)\n*/\nitk::VariableSizeMatrix<double>\nComputeSHMatrix(const int order,vtkPolyData* shell,const bool FlipX,const bool FlipY,\n                const bool FlipZ, itk::VariableSizeMatrix<double>& PhiThetaDirections)\n{\n  const int n_s   = shell->GetNumberOfPoints();\n  const int rank =  (order+1)*(order+2)/2;\n  itk::VariableSizeMatrix<double> B(rank,n_s);\n  vtkPoints* vertices = shell->GetPoints();\n\n  for (int i=0;i<n_s;++i) {\n    // Get spherical component of the point direction and transform them in spherical coordinates.\n    double p[3];\n    vertices->GetPoint(i,p);\n\n    itk::Vector<double, 3> dITK;\n    dITK[0] = (FlipX) ? -p[0] : p[0];\n    dITK[1] = (FlipY) ? -p[1] : p[1];\n    dITK[2] = (FlipZ) ? -p[2] : p[2];\n\n    const itk::Vector<double, 3> v = Cartesian2Spherical(dITK);\n\n    const double phi   = v[1];\n    const double theta = v[2];\n    double temp=0;\n    PhiThetaDirections(i,0) = phi;\n    PhiThetaDirections(i,1) = theta;\n\n    for (int l=0,j=0;l<=order;l+=2) {\n\n      //  Handle the case m=0\n      B(j,i) = sphLegendre(l,0,theta);\n      j = j+1;\n\n      for(int m=1,s=-1;m<=l;++m,++j,s=-s) {\n        temp = sphLegendre(l, m,theta)*std::sqrt(2.0);\n\n        //-m Real like t3 at hardi.cpp but math simplified and with tr1\n        B(j,i) = s*temp*(cos(m*phi));\n\n        //+m Imag like t3 at hardi.cpp but math simplified and with tr1\n        B(++j,i) = temp*(sin(s*m*phi));\n      }\n    }\n  }\n\n  return B;\n}\n\nitk::VariableSizeMatrix<double>\nComputeSHMatrixMaxThesis(const int order,vtkPolyData *shell,const bool FlipX,const bool FlipY,\n                         const bool FlipZ,itk::VariableSizeMatrix<double>& PhiThetaDirections)\n{\n  const int n_s   = shell->GetNumberOfPoints();\n  const int rank =  (order+1)*(order+2)/2;\n  itk::VariableSizeMatrix<double> B(rank,n_s);\n  vtkPoints* vertices = shell->GetPoints();\n  for (int i=0;i<n_s;++i) {\n\n    // Get spherical component of the point direction and transform them in spherical coordinates.\n    double p[3];\n    vertices->GetPoint(i,p);\n\n    itk::Vector<double, 3> dITK;\n    dITK[0] = (FlipX) ? -p[0] : p[0];\n    dITK[1] = (FlipY) ? -p[1] : p[1];\n    dITK[2] = (FlipZ) ? -p[2] : p[2];\n\n    const itk::Vector<double, 3> v = Cartesian2Spherical(dITK);\n    const double phi   = v[1];// v.y;\n    const double theta = v[2];//v.z;\n\n    PhiThetaDirections(i,0) = phi;\n    PhiThetaDirections(i,1) = theta;\n\n    //  It is even nicer to compute the SH once (for m>0 and for m<0).\n    //  The central term is given by the suite u_n\n    //  TO\n    double temp=0;\n    for (int l=0,j=0;l<=order;l+=2,j+=2*l-1) {\n      B(j,i) = sphLegendre(l,0,theta);\n\n      for(int m=1,j1=j-1,j2=j+1;m<=l;++m,--j1,++j2) {\n        temp = std::sqrt(2.0)*sphLegendre(l,m,theta);\n        B(j1,i) = temp*cos(m*phi);\n        B(j2,i) = temp*sin(m*phi);\n      }\n    }\n  }\n\n  return B;\n}\n\nitk::VariableSizeMatrix<double>\nComputeSHMatrixTournier(const int order,vtkPolyData *shell,const bool FlipX,const bool FlipY,\n                        const bool FlipZ,itk::VariableSizeMatrix<double>& PhiThetaDirections)\n{\n  const int n_s   = shell->GetNumberOfPoints();\n  const int rank =  (order+1)*(order+2)/2;\n  /*\n      We declare the Bmatrix of size n_s x n_b.\n    */\n  itk::VariableSizeMatrix<double> B(rank,n_s);\n\n  vtkPoints* vertices = shell->GetPoints();\n  std::complex<float>  cplx_1;\n\n  for(int i = 0; i < n_s; i++) {\n    // Get spherical component of the point direction and transform them in spherical coordinates.\n    double p[3];\n    vertices->GetPoint(i,p);\n\n    itk::Vector<double, 3> dITK;\n    dITK[0] = (FlipX) ? -p[0] : p[0];\n    dITK[1] = (FlipY) ? -p[1] : p[1];\n    dITK[2] = (FlipZ) ? -p[2] : p[2];\n\n    const itk::Vector<double, 3> v = Cartesian2Spherical(dITK);\n    const double phi   = v[1]; //v.y;\n    const double theta = v[2]; //v.z;\n\n    PhiThetaDirections(i,0) = phi;\n    PhiThetaDirections(i,1) = theta;\n    int j = 0;\n    //counter for the j dimension of B\n    //get spherical component of the direction vector\n    double temp=0;\n\n    for(int l = 0; l <= order; l+=2)\n      for(int m = -l,s=1; m <= l; m++,s=-s) {\n        temp = sphLegendre(l,std::abs(m),theta);\n        if(m >= 0) { /* positive \"m\" SH */\n          B(j,i) =  temp*cos(m*phi);;\n        }\n        else { /* negative \"m\" SH  */\n          B(j,i) = s*temp*sin(m*phi);\n        }\n        j++;\n      }\n  }\n\n  return B;\n}\n\nitk::VariableSizeMatrix<double>\nComputeSHMatrixRshBasis(const int order,vtkPolyData* shell,const bool FlipX,const bool FlipY,\n                        const bool FlipZ,itk::VariableSizeMatrix<double>& PhiThetaDirections)\n{\n  const int n_s   = shell->GetNumberOfPoints();\n  const int rank =  (order+1)*(order+2)/2;\n\n  itk::VariableSizeMatrix<double> B(rank,n_s);\n  vtkPoints* vertices = shell->GetPoints();\n\n  for (int i=0;i<n_s;++i) {\n\n    // Get spherical component of the point direction and transform them in spherical coordinates.\n    double p[3];\n    vertices->GetPoint(i,p);\n\n    itk::Vector<double, 3> dITK;\n    dITK[0] = (FlipX) ? -p[0] : p[0];\n    dITK[1] = (FlipY) ? -p[1] : p[1];\n    dITK[2] = (FlipZ) ? -p[2] : p[2];\n\n    const itk::Vector<double, 3> v = Cartesian2Spherical(dITK);\n    const double phi   = v[1]; //v.y;\n    const double theta = v[2]; // v.z;\n    PhiThetaDirections(i,0) = phi;\n    PhiThetaDirections(i,1) = theta;\n    double temp=0;\n\n    for (int l=0,j=0;l<=order;l+=2) {\n      B(j,i)=sphLegendre(l,0,theta);\n      j=j+1;\n      for(int m=1,s=-1;m<=l;++m,++j,s=-s) {\n        temp = sphLegendre(l, m,theta)*std::sqrt(2.0);\n        //-m Real like RshBasis.pdf Luke Bloy eq 1.2 but math simplified and with tr1\n        B(j,i)   = temp*(cos(m*phi));\n        //+m Imag\n        B(++j,i) = temp*(sin(m*phi));\n      }\n    }\n  }\n  return B;\n}\n\nvoid vtkSphericalHarmonicSource::SetSphericalHarmonics(double* _arg)\n{\n  vtkDebugMacro(<< this->GetClassName() << \" (\" << this\n                << \"): setting Spherical Harmonics to \" << _arg);\n  this->SphericalHarmonics = _arg;\n  this->Modified();\n}\n\nvoid vtkSphericalHarmonicSource::UpdateSphericalHarmonicSource()\n{\n  this->sphereT->SetPolyhedraType(TesselationType);\n  this->sphereT->SetResolution(Tesselation);\n  this->sphereT->Update();\n\n  itk::VariableSizeMatrix<double>  PhiThetaDirection(this->sphereT->GetOutput()->GetNumberOfPoints(),2);\n\n  switch (TesselationBasis) {\n  case SHMatrix:\n  {\n    BasisFunction = ComputeSHMatrix(Order,this->sphereT->GetOutput(),FlipX,FlipY,FlipZ,PhiThetaDirection);\n    break;\n  }\n  case SHMatrixMaxThesis:\n  {\n    BasisFunction = ComputeSHMatrixMaxThesis(Order,this->sphereT->GetOutput(),FlipX,FlipY,FlipZ,PhiThetaDirection);\n    break;\n  }\n  case SHMatrixTournier:\n  {\n    BasisFunction = ComputeSHMatrixTournier(Order,this->sphereT->GetOutput(),FlipX,FlipY,FlipZ,PhiThetaDirection);\n    break;\n  }\n  case SHMatrixRshBasis:\n  {\n    BasisFunction = ComputeSHMatrixRshBasis(Order,this->sphereT->GetOutput(),FlipX,FlipY,FlipZ,PhiThetaDirection);\n    break;\n  }\n  }\n  PhiThetaShellDirections = PhiThetaDirection;\n\n\n}\n\nvoid TranslateAndDeformShell(vtkPolyData *shell,vtkPoints* outPts,double center[3],\n                             bool deform,vtkMatrix4x4* transform)\n{\n  vtkPoints* inPts = shell->GetPoints();\n  const int  n     = inPts->GetNumberOfPoints();\n\n//  double range[2];\n//  shell->GetPointData()->GetScalars()->GetRange(range);\n//  const double rangeDiff = (range[0]!=range[1]) ? range[1]-range[0] : 1.;\n\n  vtkDataArray* sValues  = shell->GetPointData()->GetScalars();\n\n  for (int i=0;i<n;++i) {\n    double point[4];\n    inPts->GetPoint(i,point);\n\n    if (deform) {\n      const double val = sValues->GetTuple1(i);\n      point[0] = (val)*point[0];// ((val-range[0])/rangeDiff)*point[0];\n      point[1] = (val)*point[1];//((val-range[0])/rangeDiff)*point[1];\n      point[2] =(val)*point[2];// ((val-range[0])/rangeDiff)*point[2];\n    }\n    point[3] = 1.0;\n    const double* pointOut = (transform!=0) ? transform->MultiplyDoublePoint(point) : &point[0];\n    outPts->InsertNextPoint(pointOut[0]+center[0],pointOut[1]+center[1],pointOut[2]+center[2]);\n  }\n}\n", "meta": {"hexsha": "28c8c23812aaeb58ab14e04bd545604267090f35", "size": 17281, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src-plugins/libs/vtkInria/vtkVisuManagement/vtkSphericalHarmonicSource.cxx", "max_stars_repo_name": "ocommowi/medInria-public", "max_stars_repo_head_hexsha": "9074e40c886881666e7a52c53309d8d28e35c0e6", "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": "src-plugins/libs/vtkInria/vtkVisuManagement/vtkSphericalHarmonicSource.cxx", "max_issues_repo_name": "ocommowi/medInria-public", "max_issues_repo_head_hexsha": "9074e40c886881666e7a52c53309d8d28e35c0e6", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src-plugins/libs/vtkInria/vtkVisuManagement/vtkSphericalHarmonicSource.cxx", "max_forks_repo_name": "ocommowi/medInria-public", "max_forks_repo_head_hexsha": "9074e40c886881666e7a52c53309d8d28e35c0e6", "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": 32.0018518519, "max_line_length": 161, "alphanum_fraction": 0.6322550778, "num_tokens": 5045, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677737461007, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.48646080201371306}}
{"text": "#define BOOST_TEST_MODULE interface\n#include <boost/test/included/unit_test.hpp>\n\n#include <cmath>\n#include <limits>\n#include <map>\n#include <stdexcept>\n#include <string>\n\n#include \"matheval.hpp\"\n\nBOOST_AUTO_TEST_CASE(integration1) {\n    std::string expr = \"pow(x/2 + sqrt(x**2/4 + y**3/24), 1/3)\";\n    double x = 2.0, y = -1.0;\n\n    matheval::Parser parser;\n    BOOST_CHECK_NO_THROW(parser.parse(expr));\n\n    std::map<std::string, double> symbol_table;\n    symbol_table.insert(std::make_pair(\"x\", x));\n    symbol_table.insert(std::make_pair(\"y\", y));\n\n    double result = 0;\n    BOOST_CHECK_NO_THROW(result = parser.evaluate(symbol_table));\n\n    double expected = std::pow(\n        x / 2. + std::sqrt(std::pow(x, 2.) / 4. + std::pow(y, 3.) / 24.),\n        1. / 3.);\n    BOOST_CHECK_CLOSE_FRACTION(result, expected,\n                               std::numeric_limits<double>::epsilon());\n}\n\nBOOST_AUTO_TEST_CASE(integration2) {\n    std::string expr = \"(\";\n\n    matheval::Parser parser;\n\n    // Parsing should fail\n    BOOST_CHECK_THROW(parser.parse(expr), std::runtime_error);\n}\n\nBOOST_AUTO_TEST_CASE(integration3) {\n    std::string expr = \"x\";\n\n    matheval::Parser parser;\n\n    BOOST_CHECK_NO_THROW(parser.parse(expr));\n\n    // Evaluating should fail\n    BOOST_CHECK_THROW(parser.evaluate(),\n                      std::invalid_argument);\n}\n\nBOOST_AUTO_TEST_CASE(integration4) {\n    std::string expr = \"1 + 1\";\n\n    matheval::Parser parser;\n\n    BOOST_CHECK_NO_THROW(parser.parse(expr));\n\n    BOOST_CHECK_NO_THROW(parser.optimize());\n}\n", "meta": {"hexsha": "8a1216d20b41fd137f9331eb4fa69c780dadb980", "size": 1537, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/interface.cpp", "max_stars_repo_name": "hmenke/boost_matheval", "max_stars_repo_head_hexsha": "013f28cb001b30a3d9d47758cf1a9e6456d5356e", "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": "tests/interface.cpp", "max_issues_repo_name": "hmenke/boost_matheval", "max_issues_repo_head_hexsha": "013f28cb001b30a3d9d47758cf1a9e6456d5356e", "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": "tests/interface.cpp", "max_forks_repo_name": "hmenke/boost_matheval", "max_forks_repo_head_hexsha": "013f28cb001b30a3d9d47758cf1a9e6456d5356e", "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": 24.3968253968, "max_line_length": 73, "alphanum_fraction": 0.6499674691, "num_tokens": 394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4864607931972656}}
{"text": "#pragma once\n\n#include <Eigen/Core>\n#include <complex>\n#include <cstddef>\n#include <memory>\n#include <utility>\n#include <vector>\n#include \"ear/fft.hpp\"\n\nnamespace ear {\n  namespace dsp {\n\n    namespace block_convolver_impl {\n      /// Type for real data (float).\n      using real_t = float;\n      /// Type for complex data.\n      using complex_t = std::complex<real_t>;\n\n      using TDVector = Eigen::Matrix<real_t, Eigen::Dynamic, 1>;\n      using FDVector = Eigen::Matrix<complex_t, Eigen::Dynamic, 1>;\n\n      /** Static data required to perform convolution of a particular block\n       * size; may be shared between any number of BlockConvolver and\n       * BlockConvolver::Filter instances. */\n      class Context {\n       public:\n        /** Create a Context with a given block size.\n         * @param block_size Block size in samples.\n         * @param fft_impl FFT implementation to use.\n         */\n        Context(size_t block_size, FFTImpl<real_t> &fft_impl);\n\n       private:\n        // number of samples in a block\n        const size_t block_size;\n\n        // fft of block_size * 2\n        std::shared_ptr<FFTPlan<real_t>> fft;\n\n        // time domain fft block size\n        const size_t td_size;\n        // frequency domain fft block size\n        const size_t fd_size;\n\n        friend class BlockConvolver;\n        friend class Filter;\n      };\n\n      /** A filter response which may be shared between many BlockConvolver\n       * instances.\n       *\n       * This stores the pre-transformed filter blocks. */\n      class Filter {\n       public:\n        Filter(const std::shared_ptr<Context> &ctx, const TDVector &filter);\n        Filter(const std::shared_ptr<Context> &ctx, size_t n,\n               const real_t *filter);\n\n        /** The number of blocks in the filter. */\n        size_t num_blocks() const { return blocks.size(); }\n\n       private:\n        std::vector<FDVector> blocks;\n\n        friend class BlockConvolver;\n      };\n\n      /** BlockConvolver implements partitioned overlap-add convolution with a\n       * fixed block size, with efficient fading between filters.\n       */\n      class BlockConvolver {\n       public:\n        /** Create a BlockConvolver given the block size and number of blocks.\n         * @param ctx Context required for transformations.\n         * @param num_blocks Maximum number of blocks of any filter used.\n         */\n        BlockConvolver(const std::shared_ptr<Context> &ctx, size_t num_blocks);\n\n        /** Create a BlockConvolver given the block size and number of blocks.\n         *  If filter == nullptr, num_blocks must be specified.\n         * @param ctx Context required for transformations.\n         * @param filter Initial filter to be used, or nullptr for no filter.\n         * @param num_blocks Maximum number of blocks of any filter used; using\n         * 0 will take the number of blocks from the passed filter.\n         */\n        BlockConvolver(const std::shared_ptr<Context> &ctx,\n                       const std::shared_ptr<const Filter> &filter,\n                       size_t num_blocks = 0);\n\n        /** Pass a block of audio through the filter.\n         * @param in Input samples of length block_size\n         * @param out Output samples of length block_size\n         */\n        void process(const Eigen::Ref<const TDVector> &in,\n                     Eigen::Ref<TDVector> out);\n\n        void process(const float *in, float *out);\n\n        /** Crossfade to a new filter during the next block.\n         *\n         * This is equivalent to:\n         * - Creating a new convolver.\n         * - Passing the next block of samples through the old and new\n         * convolvers, with the input to the old faded down across the block,\n         * and the input to the new faded up across the block. All subsequent\n         * blocks are passed through the new filter.\n         * - Mixing the output of the old and new filters for the next\n         * num_blocks blocks.\n         *\n         * @param filter Filter to crossfade to; should be alive for as long as\n         * it is active. Pass nullptr for no filter.\n         */\n        void crossfade_filter(const std::shared_ptr<const Filter> &filter);\n\n        /** Switch to a different filter at the start of the next block.\n         * @param filter Filter to switch to; should be alive for as long as it\n         * is active. Pass nullptr for no filter.\n         */\n        void set_filter(const std::shared_ptr<const Filter> &filter);\n\n       private:\n        // wrapper around an eigen type which knows if it contains only zeros\n        template <typename T>\n        struct ZeroTrack {\n          template <typename... Args>\n          ZeroTrack(Args &&...args) : data(std::forward<Args>(args)...) {\n            clear();\n          }\n          T data;\n          bool zero = false;\n          /** Get access to the data for reading. */\n          const T &read() { return data; }\n          /** Get access to the data for writing; clears the zero flag. */\n          T &write() {\n            zero = false;\n            return data;\n          }\n          /** Zero the buffer and set the zero flag. */\n          void clear() {\n            if (!zero) {\n              zero = true;\n              data.setZero();\n            }\n          }\n        };\n\n        std::shared_ptr<Context> ctx;\n        std::unique_ptr<FFTWorkBuf> fft_work_buf;\n        const size_t num_blocks;\n\n        // check that a filter is valid for use with this convolver\n        void check_filter(const std::shared_ptr<const Filter> &filter);\n\n        // filters(i) accesses a circular buffer of filters, length num_blocks\n        // + 1. on each frame, the input is crossfaded up and down, and passed\n        // through\n        // - filters[1:] (old)\n        // - filters[:-1] (new)\n        // After process, filters has been shifted one along, with filters(0)\n        // left at filters(1); filters(0) is then set to filters(1), such that\n        // the next filter is the same as the previous by default. set_filter\n        // simply writes to filters(0).\n        std::shared_ptr<const Filter> &filters(size_t i);\n        // filter_queue and filter_ofs implement the above circular buffer.\n        std::vector<std::shared_ptr<const Filter>> filter_queue;\n        size_t filter_ofs;\n\n        // a queue of spectra of the input, after zero padding on the right hand\n        // side. If the filter is changed before the input block i frames ago,\n        // spectra_old(i) contains the input faded down (to convolve with the\n        // old filter) and spectra_new(i) contains the input faded up (to\n        // convolve with the new filter). If the filter is not changed, only\n        // spectra_new(i) contains data. num_blocks in length, each of size n+1.\n        ZeroTrack<FDVector> &spectra_old(size_t i);\n        ZeroTrack<FDVector> &spectra_new(size_t i);\n        // implementation the above circular buffer\n        std::vector<ZeroTrack<FDVector>> spectra_queue_old;\n        std::vector<ZeroTrack<FDVector>> spectra_queue_new;\n        size_t spectra_ofs;\n\n        // Rotate the filter and spectra queues.\n        void rotate_queues();\n\n        // The second half of the ifft output for the last block, added to the\n        // first half before output; size n.\n        ZeroTrack<TDVector> last_tail;\n\n        // Temporaries used by process to store the padded and faded inputs;\n        // size 2n, the second half should always be zeros.\n        ZeroTrack<TDVector> current_td_old;\n        ZeroTrack<TDVector> current_td_new;\n        // Temporary used by process to store the multiplied spectrum; size n+1.\n        ZeroTrack<FDVector> multiply_out;\n        // Temporary used to store the time domain output, size 2n.\n        ZeroTrack<TDVector> out_td;\n      };\n\n    }  // namespace block_convolver_impl\n  }  // namespace dsp\n}  // namespace ear\n", "meta": {"hexsha": "c52c5309fa9c44240d038ecc394a4b5760e55c63", "size": 7827, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/dsp/block_convolver_impl.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/dsp/block_convolver_impl.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/dsp/block_convolver_impl.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": 38.7475247525, "max_line_length": 80, "alphanum_fraction": 0.6153059921, "num_tokens": 1736, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778257, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.48646079319726554}}
{"text": "//\n// Created by krematas on 3/9/18.\n//\n\n//\n// Created by krematas on 3/9/18.\n//\n#include <Eigen/Sparse>\n#include \"core.h\"\n\ntypedef Eigen::SparseMatrix<var_t> SpMat;\ntypedef Eigen::Triplet<var_t> T;\n\nvoid getPixelNeighbors(int height, int width, std::vector<std::vector<int>>& neighborId){\n\n    for(int i=0; i<height; i++){\n        for(int j=0; j<width; j++){\n\n            if(i == 0){\n                neighborId[i*width+j].push_back((i+1)*width+j);\n            }else if(i == height-1){\n                neighborId[i*width+j].push_back((i-1)*width+j);\n            }else{\n                neighborId[i*width+j].push_back((i+1)*width+j);\n                neighborId[i*width+j].push_back((i-1)*width+j);\n            }\n\n            if(j == 0){\n                neighborId[i*width+j].push_back(i*width+j+1);\n            }else if(j == width-1){\n                neighborId[i*width+j].push_back(i*width+j-1);\n            }else{\n                neighborId[i*width+j].push_back(i*width+j+1);\n                neighborId[i*width+j].push_back(i*width+j-1);\n            }\n\n        }\n    }\n\n}\n\n\nvoid getLabelPosition(var_t *img, int h, int w, std::map<int, std::vector<int>>& ht){\n    for(int i=0; i<h; i++) {\n        for (int j = 0; j < w; j++) {\n\n            if(img[i*w+j] >= 1.0){\n                int lbl = int(img[i*w+j]-1);\n                ht[lbl].push_back(i*w+j);\n            }\n\n        }\n    }\n}\n\n\nSpMat setU(int N, std::map<int, std::vector<int>>& ht, Eigen::VectorXf& y){\n    std::vector<T> tripletList;\n\n    for(std::map<int,std::vector<int>>::iterator it = ht.begin(); it != ht.end(); ++it) {\n        std::vector<int> pixLocation = it->second;\n        for(int i=0; i<pixLocation.size();i++){\n            tripletList.push_back(T(pixLocation[i], pixLocation[i], 1.));\n            y[pixLocation[i]] = float(it->first);\n        }\n    }\n\n    SpMat U(N,N);\n    U.setFromTriplets(tripletList.begin(), tripletList.end());\n    return U;\n}\n\nvoid setDW(var_t* image, var_t* edges, int h, int w, std::vector<SpMat>& out, float sigma1, float sigma2){\n\n    int N = h * w;\n    std::vector<std::vector<int>> neighborId(N);\n    getPixelNeighbors(h, w, neighborId);\n\n    std::vector<T> tripletListD;\n    std::vector<T> tripletListW;\n    int M = 0;\n\n    for(int i=0; i<neighborId.size(); i++){\n        int x, y;\n        y = i/w;\n        x = i%w;\n        var_t r1 = image[y*w*3+x*3+0];\n        var_t g1 = image[y*w*3+x*3+1];\n        var_t b1 = image[y*w*3+x*3+2];\n        var_t e1 = edges[y*w+x];\n\n        for(int j=0; j<neighborId[i].size(); j++){\n\n            y = neighborId[i][j]/w;\n            x = neighborId[i][j]%w;\n            var_t r2 = image[y*w*3+x*3+0];\n            var_t g2 = image[y*w*3+x*3+1];\n            var_t b2 = image[y*w*3+x*3+2];\n\n            var_t weight0 = exp(-((r1-r2)*(r1-r2) + (g1-g2)*(g1-g2)+ (b1-b2)*(b1-b2))/sigma1);\n            var_t weight1 = exp(-(e1*e1)/sigma2);\n\n            tripletListD.push_back(T(M, i, 1.));\n            tripletListD.push_back(T(M, neighborId[i][j], -1.));\n            tripletListW.push_back(T(M, M, weight0*weight1));\n\n            M++;\n\n        }\n    }\n\n    SpMat D(M, N);\n    D.setFromTriplets(tripletListD.begin(), tripletListD.end());\n\n    SpMat W(M, M);\n    W.setFromTriplets(tripletListW.begin(), tripletListW.end());\n    out.push_back(D);\n    out.push_back(W);\n}\n\n\nvar_t* segmentFromPoses(var_t *img, var_t *edges, var_t *poseData, int height, int width, float sigma1, float sigma2){\n    std::map<int, std::vector<int>> ht;\n    getLabelPosition(poseData, height, width, ht);\n    Eigen::VectorXf y(height*width);\n    SpMat U = setU(height*width, ht, y);\n    std::vector<SpMat> DW;\n    setDW(img, edges, height, width, DW, sigma1, sigma2);\n    SpMat D = DW[0];\n    SpMat W = DW[1];\n\n    Eigen::VectorXf b = U*y;\n\n    SpMat A = U + D.transpose()*W*D;\n\n    Eigen::SimplicialCholesky <SpMat> solver(A);\n    Eigen::VectorXf x = solver.solve(b);\n\n    var_t *output = new var_t[height*width];\n    for(int i=0; i<height*width; i++)\n        output[i] = x[i];\n\n    return output;\n}", "meta": {"hexsha": "50bd7e8f90b3c3902dba8af740b05bbe071983a1", "size": 4004, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "soccer3d/instancesegm/core.cpp", "max_stars_repo_name": "ngerstle/soccerontable", "max_stars_repo_head_hexsha": "25426ff0f8fe0ce008b99c5c0fdbb35091d8d92c", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 465.0, "max_stars_repo_stars_event_min_datetime": "2018-05-18T04:43:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-27T03:09:25.000Z", "max_issues_repo_path": "soccer3d/instancesegm/core.cpp", "max_issues_repo_name": "ngerstle/soccerontable", "max_issues_repo_head_hexsha": "25426ff0f8fe0ce008b99c5c0fdbb35091d8d92c", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 18.0, "max_issues_repo_issues_event_min_datetime": "2018-06-20T15:03:10.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-05T04:33:38.000Z", "max_forks_repo_path": "soccer3d/instancesegm/core.cpp", "max_forks_repo_name": "ngerstle/soccerontable", "max_forks_repo_head_hexsha": "25426ff0f8fe0ce008b99c5c0fdbb35091d8d92c", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 97.0, "max_forks_repo_forks_event_min_datetime": "2018-05-03T09:12:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-25T12:49:33.000Z", "avg_line_length": 27.8055555556, "max_line_length": 118, "alphanum_fraction": 0.532967033, "num_tokens": 1238, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936879, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.4864607887890417}}
{"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/Math/QuaternionFit.h\"\n#include \"Utils/Geometry/ElementInfo.h\"\n#include \"Utils/Typenames.h\"\n#include <Eigen/Eigenvalues>\n#include <Eigen/Geometry>\n#include <utility>\n\nusing namespace Eigen;\n\nnamespace Scine {\nnamespace Utils {\n\nEigen::VectorXd QuaternionFit::makeWeightsVector(const ElementTypeCollection& elements) {\n  Eigen::VectorXd vec(elements.size());\n  for (int i = 0; i < elements.size(); ++i) {\n    vec(i) = ElementInfo::mass(elements[i]);\n  }\n  return vec;\n}\n\nvoid QuaternionFit::align() {\n  /*\n   * Translation into origin\n   */\n  // multiply positions with weights colwise: mat.array().colwise()*weights.array()\n  // sum into vector and divide: (...).sum() / weights.sum()\n  refCenter_ = (refMat_.array().colwise() * weights_.array()).colwise().sum() / weights_.sum();\n  fitCenter_ = (fitMat_.array().colwise() * weights_.array()).colwise().sum() / weights_.sum();\n  fittedMat_ = fitMat_.rowwise() - fitCenter_.transpose();\n\n  /*\n   * Rotation\n   */\n  Eigen::Matrix4d b = Eigen::Matrix4d::Zero();\n  // generate decomposable matrix per atom and add them\n  for (int i = 0; i < fitMat_.rows(); i++) {\n    Eigen::Vector3d fitPos = fittedMat_.row(i);\n    Eigen::Vector3d refPos = refMat_.row(i) - refCenter_.transpose();\n    Eigen::Matrix4d a = Eigen::Matrix4d::Zero();\n    a.block(0, 1, 1, 3) = (fitPos - refPos).transpose();\n    a.block(1, 0, 3, 1) = refPos - fitPos;\n    a.block(1, 1, 3, 3) = Eigen::Matrix3d::Identity().rowwise().cross(refPos + fitPos);\n    b += a.transpose() * a * weights_[i];\n  }\n\n  // Decompose b\n  SelfAdjointEigenSolver<Matrix4d> eigensolver(b);\n\n  // Apply rotation\n  //   If the eigenvalue of the last eigenvector is larger (absolute) than that of the first one\n  //   it is beneficial to allow a rotation including inversion, as this will lead to the better\n  //   fit.\n  if (improperRotationIsAllowed_ && fabs(eigensolver.eigenvalues()[0]) < fabs(eigensolver.eigenvalues()[3])) {\n    const Eigen::Vector4d& q = eigensolver.eigenvectors().col(3);\n    rotMat_ = -Quaterniond(q[0], q[1], q[2], q[3]).toRotationMatrix();\n    fittedMat_ = (rotMat_ * fittedMat_.transpose()).transpose();\n    maxEigenvalue_ = eigensolver.eigenvalues()[3];\n  }\n  else {\n    const Eigen::Vector4d& q = eigensolver.eigenvectors().col(0);\n    rotMat_ = Quaterniond(q[0], q[1], q[2], q[3]).toRotationMatrix();\n    fittedMat_ = (rotMat_ * fittedMat_.transpose()).transpose();\n    maxEigenvalue_ = eigensolver.eigenvalues()[0];\n  }\n\n  /*\n   * Translation onto reference center\n   */\n  fittedMat_ = fittedMat_.rowwise() + refCenter_.transpose();\n}\n\ndouble QuaternionFit::getRMSD() const {\n  // collect squared norms: ((refMat_-fittedMat_).rowwise().squaredNorm()\n  // sum, divide and sqrt: std::sqrt( (...).sum() / refMat_.rows() )\n  return std::sqrt((refMat_ - fittedMat_).rowwise().squaredNorm().sum() / refMat_.rows());\n}\n\ndouble QuaternionFit::getWeightedRMSD(const Eigen::VectorXd& weights) const {\n  // collect sqared norms: ((refMat_-fittedMat_).rowwise().squaredNorm()\n  // multiply with corresponding weight: (...).array()*weights.array()\n  // sum, divide and sqrt: std::sqrt( (...).sum() / refMat_.rows() )\n  return std::sqrt(((refMat_ - fittedMat_).rowwise().squaredNorm().array() * weights.array()).sum() / refMat_.rows());\n}\n\ndouble QuaternionFit::getWeightedRMSD() const {\n  return std::move(getWeightedRMSD(weights_));\n}\n\nEigen::Matrix<double, Eigen::Dynamic, 3, Eigen::RowMajor> QuaternionFit::getFittedData() const {\n  return fittedMat_;\n}\n\nEigen::Matrix3d QuaternionFit::getRotationMatrix() const {\n  return rotMat_.transpose();\n}\n\nEigen::Vector3d QuaternionFit::getTransVector() const {\n  return fitCenter_ - refCenter_;\n}\n\ndouble QuaternionFit::getRotRMSD() const {\n  double rotRMSD = (fitMat_.rowwise() - fitCenter_.transpose()).rowwise().squaredNorm().sum();\n  rotRMSD += (refMat_.rowwise() - refCenter_.transpose()).rowwise().squaredNorm().sum();\n  rotRMSD -= 2.0 * abs(maxEigenvalue_);\n  if (rotRMSD > 0)\n    return sqrt(rotRMSD / refMat_.rows());\n  return 0.0;\n}\n\n} /* namespace Utils */\n} /* namespace Scine */\n", "meta": {"hexsha": "e931bbf5d05793ba6e6c86e18d17e2f3c48b5731", "size": 4276, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Utils/Utils/Math/QuaternionFit.cpp", "max_stars_repo_name": "DockBio/utilities", "max_stars_repo_head_hexsha": "213ed5ac2a64886b16d0fee1fcecb34d36eea9e9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Utils/Utils/Math/QuaternionFit.cpp", "max_issues_repo_name": "DockBio/utilities", "max_issues_repo_head_hexsha": "213ed5ac2a64886b16d0fee1fcecb34d36eea9e9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Utils/Utils/Math/QuaternionFit.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": 36.2372881356, "max_line_length": 118, "alphanum_fraction": 0.6768007484, "num_tokens": 1240, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936879, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4864607887890416}}
{"text": "#include \"IntegratorGL.hh\"\n\n#include <Eigen/Dense>\n#include <map>\n#include <iterator>\n\n#include \"GSLSamplerGL.hh\"\n#include \"TypesFunctions.hh\"\n\nusing namespace Eigen;\nusing namespace std;\n\nIntegratorGL::IntegratorGL(int orders) : IntegratorBase(orders)\n{\n  init_sampler();\n}\n\nIntegratorGL::IntegratorGL(size_t bins, int orders, double* edges) : IntegratorBase(bins, orders, edges)\n{\n  init_sampler();\n}\n\nIntegratorGL::IntegratorGL(size_t bins, int* orders, double* edges) : IntegratorBase(bins, orders, edges)\n{\n  init_sampler();\n}\n\nvoid IntegratorGL::sample(FunctionArgs& fargs){\n  auto& rets=fargs.rets;\n  GSLSamplerGL sampler;\n  sampler.fill_bins(m_orders.size(), m_orders.data(), m_edges.data(), rets[0].buffer, m_weights.data());\n  rets[1].x = m_edges.cast<double>();\n  rets[2].x = 0.0;\n  auto npoints=m_edges.size()-1;\n  rets[3].x = 0.5*(m_edges.tail(npoints)+m_edges.head(npoints));\n  rets.untaint();\n  rets.freeze();\n}\n\n", "meta": {"hexsha": "5bdc8e7862a4a0fe98a2a5c53398c97e9cfd0717", "size": 928, "ext": "cc", "lang": "C++", "max_stars_repo_path": "transformations/integrator/IntegratorGL.cc", "max_stars_repo_name": "gnafit/gna", "max_stars_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-10-14T01:06:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-02T16:33:06.000Z", "max_issues_repo_path": "transformations/integrator/IntegratorGL.cc", "max_issues_repo_name": "gnafit/gna", "max_issues_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "transformations/integrator/IntegratorGL.cc", "max_forks_repo_name": "gnafit/gna", "max_forks_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_forks_repo_licenses": ["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.2, "max_line_length": 105, "alphanum_fraction": 0.71875, "num_tokens": 267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677430095496, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.48646078438081736}}
{"text": "// This file is part of Eigen, a lightweight C++ template library\n// for linear algebra.\n//\n// Copyright (C) 2009 Benoit Jacob <jacob.benoit.1@gmail.com>\n//\n// Eigen 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 3 of the License, or (at your option) any later version.\n//\n// Alternatively, 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 2 of\n// the License, or (at your option) any later version.\n//\n// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY\n// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License and a copy of the GNU General Public License along with\n// Eigen. If not, see <http://www.gnu.org/licenses/>.\n\n#include \"main.h\"\n#include <Eigen/LU>\n#include <algorithm>\n\ntemplate<typename MatrixType> void inverse_permutation_4x4()\n{\n  typedef typename MatrixType::Scalar Scalar;\n  typedef typename MatrixType::RealScalar RealScalar;\n  Vector4i indices(0,1,2,3);\n  for(int i = 0; i < 24; ++i)\n  {\n    MatrixType m = PermutationMatrix<4>(indices);\n    MatrixType inv = m.inverse();\n    double error = double( (m*inv-MatrixType::Identity()).norm() / NumTraits<Scalar>::epsilon() );\n    EIGEN_DEBUG_VAR(error)\n    VERIFY(error == 0.0);\n    std::next_permutation(indices.data(),indices.data()+4);\n  }\n}\n\ntemplate<typename MatrixType> void inverse_general_4x4(int repeat)\n{\n  typedef typename MatrixType::Scalar Scalar;\n  typedef typename MatrixType::RealScalar RealScalar;\n  double error_sum = 0., error_max = 0.;\n  for(int i = 0; i < repeat; ++i)\n  {\n    MatrixType m;\n    RealScalar absdet;\n    do {\n      m = MatrixType::Random();\n      absdet = ei_abs(m.determinant());\n    } while(absdet < NumTraits<Scalar>::epsilon());\n    MatrixType inv = m.inverse();\n    double error = double( (m*inv-MatrixType::Identity()).norm() * absdet / NumTraits<Scalar>::epsilon() );\n    error_sum += error;\n    error_max = std::max(error_max, error);\n  }\n  std::cerr << \"inverse_general_4x4, Scalar = \" << type_name<Scalar>() << std::endl;\n  double error_avg = error_sum / repeat;\n  EIGEN_DEBUG_VAR(error_avg);\n  EIGEN_DEBUG_VAR(error_max);\n   // FIXME that 1.25 used to be a 1.0 until the NumTraits changes on 28 April 2010, what's going wrong??\n   // FIXME that 1.25 used to be 1.2 until we tested gcc 4.1 on 30 June 2010 and got 1.21.\n  VERIFY(error_avg < (NumTraits<Scalar>::IsComplex ? 8.0 : 1.25));\n  VERIFY(error_max < (NumTraits<Scalar>::IsComplex ? 64.0 : 20.0));\n}\n\nvoid test_prec_inverse_4x4()\n{\n  CALL_SUBTEST_1((inverse_permutation_4x4<Matrix4f>()));\n  CALL_SUBTEST_1(( inverse_general_4x4<Matrix4f>(200000 * g_repeat) ));\n\n  CALL_SUBTEST_2((inverse_permutation_4x4<Matrix<double,4,4,RowMajor> >()));\n  CALL_SUBTEST_2(( inverse_general_4x4<Matrix<double,4,4,RowMajor> >(200000 * g_repeat) ));\n\n  CALL_SUBTEST_3((inverse_permutation_4x4<Matrix4cf>()));\n  CALL_SUBTEST_3((inverse_general_4x4<Matrix4cf>(50000 * g_repeat)));\n}\n", "meta": {"hexsha": "8b1aa88697ff916e57e19628c2e79f0028a61d18", "size": 3330, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "t1m1/include/eigen/test/prec_inverse_4x4.cpp", "max_stars_repo_name": "dailysoap/CSMM.104x", "max_stars_repo_head_hexsha": "4515b30ab5f60827a9011b23ef155a3063584a9d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2017-04-01T17:18:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T05:23:23.000Z", "max_issues_repo_path": "t1m1/include/eigen/test/prec_inverse_4x4.cpp", "max_issues_repo_name": "dailysoap/CSMM.104x", "max_issues_repo_head_hexsha": "4515b30ab5f60827a9011b23ef155a3063584a9d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-05-24T13:36:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-15T06:44:20.000Z", "max_forks_repo_path": "t1m1/include/eigen/test/prec_inverse_4x4.cpp", "max_forks_repo_name": "dailysoap/CSMM.104x", "max_forks_repo_head_hexsha": "4515b30ab5f60827a9011b23ef155a3063584a9d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-09-20T01:07:39.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-22T14:55:38.000Z", "avg_line_length": 39.6428571429, "max_line_length": 107, "alphanum_fraction": 0.7135135135, "num_tokens": 917, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585669110202, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.48645409433560466}}
{"text": "#include <boost/test/unit_test.hpp>\n#include <complex>\n#include \"../../JeanBaptiste/include/AlgorithmFactory.h\"\n#include \"../include/AlgorithmFixture.h\"\n#include <string>\n\nnamespace ut = boost::unit_test;\nnamespace jb = jeanbaptiste;\nnamespace jbo = jeanbaptiste::options;\n\nclass Radix4Fixture\n    : public AlgorithmFixture\n{\nprotected:\n    bool initialized_;\n    \npublic:\n    Radix4Fixture()\n        : AlgorithmFixture()\n    {\n        BOOST_TEST_MESSAGE(\"Setup fixture: square pulse of 64 samples.\");\n        BOOST_TEST((initialized_ = algorithmResult_.initialize(\"../../test cases/square pulse (n=64).xml\", \"fft.in\", workingSet_, expectedOutIFFT_, \"fft.out\", expectedOutFFT_)), \"Loading test data failed.\");\n    }\n\n    ~Radix4Fixture()\n    {}\n};\n\n\nBOOST_FIXTURE_TEST_SUITE(Radix4TestSuite, Radix4Fixture)\n \n    BOOST_AUTO_TEST_CASE(fft_radix_4_dif)\n    {\n        if (!initialized_)\n            return;\n\n        BOOST_TEST_MESSAGE(\"Running radix 4 DIF FFT and IFFT.\");\n\n        // Create Radix-4 DIF FFT algorithms for sample counts 4 ... 1024.\n        jb::AlgorithmFactory<1, 5, jbo::Radix_4, jbo::Decimation_In_Frequency, jbo::Direction_Forward, jbo::Window_None,\n            jbo::Normalization_Square_Root, std::complex<double>> fftFactory;\n\n        // Create Radix-4 DIF IFFT algorithms for sample counts 4 ... 1024.\n        jb::AlgorithmFactory<1, 5, jbo::Radix_4, jbo::Decimation_In_Frequency, jbo::Direction_Backward, jbo::Window_None,\n            jbo::Normalization_Square_Root, std::complex<double>> ifftFactory;\n\n        runAlgorithms(fftFactory.getAlgorithm(3), ifftFactory.getAlgorithm(3));\n    }\n\n    BOOST_AUTO_TEST_CASE(fft_radix_4_dit)\n    {\n        if (!initialized_)\n            return;\n\n        BOOST_TEST_MESSAGE(\"Running radix 4 DIT FFT and IFFT.\");\n\n        // Create Radix-4 DIT FFT algorithms for sample counts 4 ... 1024.\n        jb::AlgorithmFactory<1, 5, jbo::Radix_4, jbo::Decimation_In_Time, jbo::Direction_Forward, jbo::Window_None,\n            jbo::Normalization_Square_Root, std::complex<double>> fftFactory;\n\n        // Create Radix-4 DIT IFFT algorithms for sample counts 4 ... 1024.\n        jb::AlgorithmFactory<1, 5, jbo::Radix_4, jbo::Decimation_In_Time, jbo::Direction_Backward, jbo::Window_None,\n            jbo::Normalization_Square_Root, std::complex<double>> ifftFactory;\n\n        runAlgorithms(fftFactory.getAlgorithm(3), ifftFactory.getAlgorithm(3));\n    }\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "6a2098b3446e296cd355c0c4bd49b0aedeb9917b", "size": 2430, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "JeanBaptiste.Test/src/FixtureRadix4.cpp", "max_stars_repo_name": "JoergWarthemann/jeanbaptiste", "max_stars_repo_head_hexsha": "cda9f5e80c126fa8612ce1515b2f904056c09fda", "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": "JeanBaptiste.Test/src/FixtureRadix4.cpp", "max_issues_repo_name": "JoergWarthemann/jeanbaptiste", "max_issues_repo_head_hexsha": "cda9f5e80c126fa8612ce1515b2f904056c09fda", "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": "JeanBaptiste.Test/src/FixtureRadix4.cpp", "max_forks_repo_name": "JoergWarthemann/jeanbaptiste", "max_forks_repo_head_hexsha": "cda9f5e80c126fa8612ce1515b2f904056c09fda", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.7352941176, "max_line_length": 207, "alphanum_fraction": 0.6913580247, "num_tokens": 646, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.48645409243214555}}
{"text": "//==================================================================================================\n/*!\n\n  Copyright 2015 NumScale SAS\n  Copyright 2015 J.T. Lapreste\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#include <boost/simd/function/scalar/atand.hpp>\n#include <simd_test.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/minf.hpp>\n#include <boost/simd/constant/nan.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/mone.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/constant/mzero.hpp>\n\nSTF_CASE_TPL (\" atandreal\",  STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::atand;\n\n  using r_t = decltype(atand(T()));\n\n  // return type conformity test\n  STF_TYPE_IS(r_t, T);\n\n  // specific values tests\n#ifndef BOOST_SIMD_NO_INVALIDS\n  STF_ULP_EQUAL(atand(bs::Inf<T>()), 90, 0.5);\n  STF_ULP_EQUAL(atand(bs::Minf<T>()), -90, 0.5);\n  STF_ULP_EQUAL(atand(bs::Nan<T>()), bs::Nan<r_t>(), 0.5);\n#endif\n  STF_ULP_EQUAL(atand(bs::Half<T>()), T(2.656505117707799e+01), 0.5);\n  STF_ULP_EQUAL(atand(bs::Mhalf<T>()), T(-2.656505117707799e+01), 0.5);\n  STF_ULP_EQUAL(atand(bs::Mone<T>()), T(-45), 0.5);\n  STF_ULP_EQUAL(atand(bs::One<T>()), T(45), 0.5);\n  STF_ULP_EQUAL(atand(bs::Zero<T>()), bs::Zero<r_t>(), 0.5);\n}\n", "meta": {"hexsha": "7fc47149b38546ba971fcb617dfabf2a7ecb631c", "size": 1518, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/scalar/atand.cpp", "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": "test/function/scalar/atand.cpp", "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": "test/function/scalar/atand.cpp", "max_forks_repo_name": "yaeldarmon/boost.simd", "max_forks_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.5, "max_line_length": 100, "alphanum_fraction": 0.6021080369, "num_tokens": 453, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585669110203, "lm_q2_score": 0.6654105521116445, "lm_q1q2_score": 0.48645408463420964}}
{"text": "/** @file\n *\n * This file is part of Boost, not part of Chaste per se.\n *\n * We use the <autogenerated> tag to ignore it from our Doxygen checker.\n *\n * This file is provided to users of Boost up to 1.63 inclusive and gives forward compatibility with\n * Boost 1.64-1.65 and hopefully beyond.\n * (An optimisation in exponential distributions was applied to boost in version 1.64,\n * which also affects normal distribution tails.)\n *\n * Minimal changes were made to the file to include it here, simply giving the class a unique name\n * and making it use the Chaste copy of exponential_distribution rather than the boost one.\n *\n */\n\n/* boost random/gamma_distribution.hpp header file\n *\n * Copyright Jens Maurer 2002\n * Copyright Steven Watanabe 2010\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\n#ifndef BOOST_165_RANDOM_GAMMA_DISTRIBUTION_HPP\n#define BOOST_165_RANDOM_GAMMA_DISTRIBUTION_HPP\n\n#include <boost/assert.hpp>\n#include <boost/config/no_tr1/cmath.hpp>\n#include <boost/limits.hpp>\n#include <boost/random/detail/config.hpp>\n//#include <boost/random/exponential_distribution.hpp> // swapped for chaste copy of exponential v1.65\n#include <boost/static_assert.hpp>\n#include <iosfwd>\n#include <istream>\n#include \"Boost165ExponentialDistribution.hpp\"\n\nnamespace boost\n{\nnamespace random\n{\n\n    // The algorithm is taken from Knuth\n\n    /**\n * The gamma distribution is a continuous distribution with two\n * parameters alpha and beta.  It produces values > 0.\n *\n * It has\n * \\f$\\displaystyle p(x) = x^{\\alpha-1}\\frac{e^{-x/\\beta}}{\\beta^\\alpha\\Gamma(\\alpha)}\\f$.\n */\n    template <class RealType = double>\n    class gamma_distribution_v165\n    {\n    public:\n        typedef RealType input_type;\n        typedef RealType result_type;\n\n        class param_type\n        {\n        public:\n            typedef gamma_distribution_v165 distribution_type;\n\n            /**\n         * Constructs a @c param_type object from the \"alpha\" and \"beta\"\n         * parameters.\n         *\n         * Requires: alpha > 0 && beta > 0\n         */\n            param_type(const RealType& alpha_arg = RealType(1.0),\n                       const RealType& beta_arg = RealType(1.0))\n                    : _alpha(alpha_arg), _beta(beta_arg)\n            {\n            }\n\n            /** Returns the \"alpha\" parameter of the distribution. */\n            RealType alpha() const { return _alpha; }\n            /** Returns the \"beta\" parameter of the distribution. */\n            RealType beta() const { return _beta; }\n\n#ifndef BOOST_RANDOM_NO_STREAM_OPERATORS\n            /** Writes the parameters to a @c std::ostream. */\n            template <class CharT, class Traits>\n            friend std::basic_ostream<CharT, Traits>&\n            operator<<(std::basic_ostream<CharT, Traits>& os,\n                       const param_type& parm)\n            {\n                os << parm._alpha << ' ' << parm._beta;\n                return os;\n            }\n\n            /** Reads the parameters from a @c std::istream. */\n            template <class CharT, class Traits>\n            friend std::basic_istream<CharT, Traits>&\n            operator>>(std::basic_istream<CharT, Traits>& is, param_type& parm)\n            {\n                is >> parm._alpha >> std::ws >> parm._beta;\n                return is;\n            }\n#endif\n\n            /** Returns true if the two sets of parameters are the same. */\n            friend bool operator==(const param_type& lhs, const param_type& rhs)\n            {\n                return lhs._alpha == rhs._alpha && lhs._beta == rhs._beta;\n            }\n            /** Returns true if the two sets fo parameters are different. */\n            friend bool operator!=(const param_type& lhs, const param_type& rhs)\n            {\n                return !(lhs == rhs);\n            }\n\n        private:\n            RealType _alpha;\n            RealType _beta;\n        };\n\n#ifndef BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS\n        BOOST_STATIC_ASSERT(!std::numeric_limits<RealType>::is_integer);\n#endif\n\n        /**\n     * Creates a new gamma_distribution with parameters \"alpha\" and \"beta\".\n     *\n     * Requires: alpha > 0 && beta > 0\n     */\n        explicit gamma_distribution_v165(const result_type& alpha_arg = result_type(1.0),\n                                         const result_type& beta_arg = result_type(1.0))\n                : _exp(result_type(1)), _alpha(alpha_arg), _beta(beta_arg)\n        {\n            BOOST_ASSERT(_alpha > result_type(0));\n            BOOST_ASSERT(_beta > result_type(0));\n            init();\n        }\n\n        /** Constructs a @c gamma_distribution from its parameters. */\n        explicit gamma_distribution_v165(const param_type& parm)\n                : _exp(result_type(1)), _alpha(parm.alpha()), _beta(parm.beta())\n        {\n            init();\n        }\n\n        // compiler-generated copy ctor and assignment operator are fine\n\n        /** Returns the \"alpha\" paramter of the distribution. */\n        RealType alpha() const { return _alpha; }\n        /** Returns the \"beta\" parameter of the distribution. */\n        RealType beta() const { return _beta; }\n        /** Returns the smallest value that the distribution can produce. */\n        RealType min BOOST_PREVENT_MACRO_SUBSTITUTION() const { return 0; }\n        /* Returns the largest value that the distribution can produce. */\n        RealType max BOOST_PREVENT_MACRO_SUBSTITUTION() const\n        {\n            return (std::numeric_limits<RealType>::infinity)();\n        }\n\n        /** Returns the parameters of the distribution. */\n        param_type param() const { return param_type(_alpha, _beta); }\n        /** Sets the parameters of the distribution. */\n        void param(const param_type& parm)\n        {\n            _alpha = parm.alpha();\n            _beta = parm.beta();\n            init();\n        }\n\n        /**\n     * Effects: Subsequent uses of the distribution do not depend\n     * on values produced by any engine prior to invoking reset.\n     */\n        void reset() { _exp.reset(); }\n\n        /**\n     * Returns a random variate distributed according to\n     * the gamma distribution.\n     */\n        template <class Engine>\n        result_type operator()(Engine& eng)\n        {\n#ifndef BOOST_NO_STDC_NAMESPACE\n            // allow for Koenig lookup\n            using std::tan;\n            using std::sqrt;\n            using std::exp;\n            using std::log;\n            using std::pow;\n#endif\n            if (_alpha == result_type(1))\n            {\n                return _exp(eng) * _beta;\n            }\n            else if (_alpha > result_type(1))\n            {\n                // Can we have a boost::mathconst please?\n                const result_type pi = result_type(3.14159265358979323846);\n                for (;;)\n                {\n                    result_type y = tan(pi * uniform_01<RealType>()(eng));\n                    result_type x = sqrt(result_type(2) * _alpha - result_type(1)) * y\n                        + _alpha - result_type(1);\n                    if (x <= result_type(0))\n                        continue;\n                    if (uniform_01<RealType>()(eng) > (result_type(1) + y * y) * exp((_alpha - result_type(1))\n                                                                                         * log(x / (_alpha - result_type(1)))\n                                                                                     - sqrt(result_type(2) * _alpha\n                                                                                            - result_type(1))\n                                                                                         * y))\n                        continue;\n                    return x * _beta;\n                }\n            }\n            else /* alpha < 1.0 */\n            {\n                for (;;)\n                {\n                    result_type u = uniform_01<RealType>()(eng);\n                    result_type y = _exp(eng);\n                    result_type x, q;\n                    if (u < _p)\n                    {\n                        x = exp(-y / _alpha);\n                        q = _p * exp(-x);\n                    }\n                    else\n                    {\n                        x = result_type(1) + y;\n                        q = _p + (result_type(1) - _p) * pow(x, _alpha - result_type(1));\n                    }\n                    if (u >= q)\n                        continue;\n                    return x * _beta;\n                }\n            }\n        }\n\n        template <class URNG>\n        RealType operator()(URNG& urng, const param_type& parm) const\n        {\n            return gamma_distribution_v165(parm)(urng);\n        }\n\n#ifndef BOOST_RANDOM_NO_STREAM_OPERATORS\n        /** Writes a @c gamma_distribution_v165 to a @c std::ostream. */\n        template <class CharT, class Traits>\n        friend std::basic_ostream<CharT, Traits>&\n        operator<<(std::basic_ostream<CharT, Traits>& os,\n                   const gamma_distribution_v165& gd)\n        {\n            os << gd.param();\n            return os;\n        }\n\n        /** Reads a @c gamma_distribution from a @c std::istream. */\n        template <class CharT, class Traits>\n        friend std::basic_istream<CharT, Traits>&\n        operator>>(std::basic_istream<CharT, Traits>& is, gamma_distribution_v165& gd)\n        {\n            gd.read(is);\n            return is;\n        }\n#endif\n\n        /**\n     * Returns true if the two distributions will produce identical\n     * sequences of random variates given equal generators.\n     */\n        friend bool operator==(const gamma_distribution_v165& lhs,\n                               const gamma_distribution_v165& rhs)\n        {\n            return lhs._alpha == rhs._alpha\n                && lhs._beta == rhs._beta\n                && lhs._exp == rhs._exp;\n        }\n\n        /**\n     * Returns true if the two distributions can produce different\n     * sequences of random variates, given equal generators.\n     */\n        friend bool operator!=(const gamma_distribution_v165& lhs,\n                               const gamma_distribution_v165& rhs)\n        {\n            return !(lhs == rhs);\n        }\n\n    private:\n        /// \\cond hide_private_members\n\n        template <class CharT, class Traits>\n        void read(std::basic_istream<CharT, Traits>& is)\n        {\n            param_type parm;\n            if (is >> parm)\n            {\n                param(parm);\n            }\n        }\n\n        void init()\n        {\n#ifndef BOOST_NO_STDC_NAMESPACE\n            // allow for Koenig lookup\n            using std::exp;\n#endif\n            _p = exp(result_type(1)) / (_alpha + exp(result_type(1)));\n        }\n        /// \\endcond\n\n        exponential_distribution_v165<RealType> _exp;\n        result_type _alpha;\n        result_type _beta;\n        // some data precomputed from the parameters\n        result_type _p;\n    };\n\n} // namespace random\n\n} // namespace boost\n\n#endif // BOOST_165_RANDOM_GAMMA_DISTRIBUTION_HPP\n", "meta": {"hexsha": "d147e4185b822ebecfd19763b8cc9f1803974725", "size": 11160, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "global/src/random/Boost165GammaDistribution.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": "global/src/random/Boost165GammaDistribution.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": "global/src/random/Boost165GammaDistribution.hpp", "max_forks_repo_name": "mdp19pn/Chaste", "max_forks_repo_head_hexsha": "f7b6bafa64287d567125b587b29af6d8bd7aeb90", "max_forks_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_forks_count": 53.0, "max_forks_repo_forks_event_min_datetime": "2015-02-23T13:52:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T18:57:35.000Z", "avg_line_length": 34.2331288344, "max_line_length": 125, "alphanum_fraction": 0.5336917563, "num_tokens": 2365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.795658109754052, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4864510252089266}}
{"text": "#include <algorithm>\r\n#include <boost/multiprecision/cpp_int.hpp>\r\n#include <fstream>\r\n#include <iostream>\r\n#include <iterator>\r\n#include <numeric>\r\n#include <vector>\r\n\r\nusing namespace std;\r\nusing boost::multiprecision::cpp_int;\r\n\r\nint main(int argc, char *argv[]) {\r\n\t// Read in the data file into the vector.\r\n\tifstream input(\"Data.txt\");\r\n\tvector<cpp_int> numbers;\r\n\tistream_iterator<cpp_int> end, start(input);\r\n\tcopy(start, end, back_inserter(numbers));\r\n\t// Accumulate the result and put it into a variable.\r\n\tcpp_int result = accumulate(numbers.begin(), numbers.end(), (cpp_int)0);\r\n\t// Print the first 10 digits.\r\n\twhile(cpp_int(result / (cpp_int)pow(10, 10)) != 0) {\r\n\t\tresult = result / 10;\r\n\t}\r\n\tcout << result << endl;\r\n\tinput.close();\r\n\treturn 0;\r\n}", "meta": {"hexsha": "4896e17b746fe76d0072c779fbc369832421ba56", "size": 763, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Solutions/1-50/13/Solution.cpp", "max_stars_repo_name": "kitegi/Edmonton", "max_stars_repo_head_hexsha": "774c9b2f72e7b2c6a3bc1b3329ef227ef39adf9d", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-07-16T13:30:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-16T18:17:40.000Z", "max_issues_repo_path": "Solutions/1-50/13/Solution.cpp", "max_issues_repo_name": "kitegi/Edmonton", "max_issues_repo_head_hexsha": "774c9b2f72e7b2c6a3bc1b3329ef227ef39adf9d", "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": "Solutions/1-50/13/Solution.cpp", "max_forks_repo_name": "kitegi/Edmonton", "max_forks_repo_head_hexsha": "774c9b2f72e7b2c6a3bc1b3329ef227ef39adf9d", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-16T22:56:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-16T22:56:07.000Z", "avg_line_length": 28.2592592593, "max_line_length": 74, "alphanum_fraction": 0.6854521625, "num_tokens": 190, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4864510252089265}}
{"text": "// Copyright 2008 John Maddock\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_DETAIL_HG_CDF_HPP\r\n#define BOOST_MATH_DISTRIBUTIONS_DETAIL_HG_CDF_HPP\r\n\r\n#include <boost/math/policies/error_handling.hpp>\r\n#include <boost/math/distributions/detail/hypergeometric_pdf.hpp>\r\n\r\nnamespace boost{ namespace math{ namespace detail{\r\n\r\n   template <class T, class Policy>\r\n   T hypergeometric_cdf_imp(unsigned x, unsigned r, unsigned n, unsigned N, bool invert, const Policy& pol)\r\n   {\r\n#ifdef BOOST_MSVC\r\n#  pragma warning(push)\r\n#  pragma warning(disable:4267)\r\n#endif\r\n      BOOST_MATH_STD_USING\r\n      T result = 0;\r\n      T mode = floor(T(r + 1) * T(n + 1) / (N + 2));\r\n      if(x < mode)\r\n      {\r\n         result = hypergeometric_pdf<T>(x, r, n, N, pol);\r\n         T diff = result;\r\n         unsigned lower_limit = static_cast<unsigned>((std::max)(0, (int)(n + r) - (int)(N)));\r\n         while(diff > (invert ? T(1) : result) * tools::epsilon<T>())\r\n         {\r\n            diff = T(x) * T((N + x) - n - r) * diff / (T(1 + n - x) * T(1 + r - x));\r\n            result += diff;\r\n            BOOST_MATH_INSTRUMENT_VARIABLE(x);\r\n            BOOST_MATH_INSTRUMENT_VARIABLE(diff);\r\n            BOOST_MATH_INSTRUMENT_VARIABLE(result);\r\n            if(x == lower_limit)\r\n               break;\r\n            --x;\r\n         }\r\n      }\r\n      else\r\n      {\r\n         invert = !invert;\r\n         unsigned upper_limit = (std::min)(r, n);\r\n         if(x != upper_limit)\r\n         {\r\n            ++x;\r\n            result = hypergeometric_pdf<T>(x, r, n, N, pol);\r\n            T diff = result;\r\n            while((x <= upper_limit) && (diff > (invert ? T(1) : result) * tools::epsilon<T>()))\r\n            {\r\n               diff = T(n - x) * T(r - x) * diff / (T(x + 1) * T((N + x + 1) - n - r));\r\n               result += diff;\r\n               ++x;\r\n               BOOST_MATH_INSTRUMENT_VARIABLE(x);\r\n               BOOST_MATH_INSTRUMENT_VARIABLE(diff);\r\n               BOOST_MATH_INSTRUMENT_VARIABLE(result);\r\n            }\r\n         }\r\n      }\r\n      if(invert)\r\n         result = 1 - result;\r\n      return result;\r\n#ifdef BOOST_MSVC\r\n#  pragma warning(pop)\r\n#endif\r\n   }\r\n\r\n   template <class T, class Policy>\r\n   inline T hypergeometric_cdf(unsigned x, unsigned r, unsigned n, unsigned N, bool invert, const Policy&)\r\n   {\r\n      BOOST_FPU_EXCEPTION_GUARD\r\n      typedef typename tools::promote_args<T>::type result_type;\r\n      typedef typename policies::evaluation<result_type, Policy>::type value_type;\r\n      typedef typename policies::normalise<\r\n         Policy, \r\n         policies::promote_float<false>, \r\n         policies::promote_double<false>, \r\n         policies::discrete_quantile<>,\r\n         policies::assert_undefined<> >::type forwarding_policy;\r\n\r\n      value_type result;\r\n      result = detail::hypergeometric_cdf_imp<value_type>(x, r, n, N, invert, forwarding_policy());\r\n      if(result > 1)\r\n      {\r\n         result  = 1;\r\n      }\r\n      if(result < 0)\r\n      {\r\n         result = 0;\r\n      }\r\n      return policies::checked_narrowing_cast<result_type, forwarding_policy>(result, \"boost::math::hypergeometric_cdf<%1%>(%1%,%1%,%1%,%1%)\");\r\n   }\r\n\r\n}}} // namespaces\r\n\r\n#endif\r\n\r\n", "meta": {"hexsha": "edf829ba7169b6f4fb4ccf267da3a61271017a9c", "size": 3375, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ios/Pods/boost-for-react-native/boost/math/distributions/detail/hypergeometric_cdf.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/detail/hypergeometric_cdf.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/detail/hypergeometric_cdf.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.4158415842, "max_line_length": 144, "alphanum_fraction": 0.5647407407, "num_tokens": 852, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540518, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.48645102520892647}}
{"text": "////////////////////////////////////////////////////////////////////////////////\n// Exact Diagonalization: Kitaev Model, Honeycomb Lattice, 2x2 unit cells     //\n// cylindrical boundary conditions\n// Copyright (C) 2016 by Tim Eschmann\n////////////////////////////////////////////////////////////////////////////////\n\n#include <iostream>\n#include <fstream>\n#include <math.h>\n#include <complex>\n//#define ARMA_64BIT_WORD\n#include <armadillo>\n\nusing namespace arma;\nusing namespace std;\n\n// Flip k1-th and k2-th bit of integer number\nint bitflip(int *v, int k1, int k2)\n{\n    int erg;\n    erg = *v;\n    // Flip bits:\n    erg ^= 1 << k1;\n    erg ^= 1 << k2; \n    return erg;    \n}\n\n// Calculate diagonal element (periodic boundary conditions)\nint diagel(int *w)\n{\n    int b, b0, b1, b2, b3, b4, b5, b6, b7;\n    signed int s1, s2, s3, s4;\n    \n    b = *w;\n    // Check bits of states \n    b0 = (b >> 0) & 1; // 0th bit and so on ... \n    b1 = (b >> 1) & 1;\n    b2 = (b >> 2) & 1;\n    b3 = (b >> 3) & 1;\n    b4 = (b >> 4) & 1;\n    b5 = (b >> 5) & 1;\n    b6 = (b >> 6) & 1;\n    b7 = (b >> 7) & 1;\n    \n    if (b0 == b4)\n        s1 = 1;\n    else\n        s1 = -1;\n\n    if (b5 == b1)\n        s2 = 1;\n    else\n        s2 = -1;\n\n    if (b2 == b6)\n        s3 = 1;\n    else\n        s3 = -1;\n\n    if (b7 == b3)\n        s4 = 1;\n    else\n        s4 = -1;\n\n    return s1 + s2 + s3 + s4;\n}\n\n// Sign check for yy interactions\nint signcheck(int *x, int var1, int var2)\n{\n    int c, c1, c2;\n    signed int s;\n    c = *x;\n    c1 = (c >> var1) & 1;\n    c2 = (c >> var2) & 1;\n    \n    if (c1 == c2)\n        s = 1;\n    else\n        s = -1;\n    \n    return s;    \n}\n\n\n// Main function \nint main(void)\n{\n    int i,j,k,l,m,p; // running indices \n    int steps = 100; // How many measurement steps? \n    int Jx, Jy, Jz; // coupling constants \n    int N = 8; //  number of sites \n    int size = 256; // matrix size\n    double Z, E; // partition sum, energy value \n    \n    int xflips[3], yflips[3]; // Arrays for spin flips, size depending on # of bonds \n    signed int si0, si1, si2;\n    \n    vec ev;\n    double temp[steps];\n    double energy[steps];\n\n    mat ham = mat(size,size, fill::zeros); // Initialize matrix \n    \n    Jx = 1;\n    Jy = 1;\n    Jz = 1;\n    \n    cout << \"Calculating matrix ...\" << endl;\n    \n    // Fill Hamiltonian matrix with elements\n    for (j = 0; j < size; j++)\n    {\n        // Diagonal element\n        ham(j,j) = -Jz * diagel(&j);\n        // Calculate interaction states via spin flips\n        // xx:\n        xflips[0] = bitflip(&j, 1, 2);\n        xflips[1] = bitflip(&j, 4, 5);\n        xflips[2] = bitflip(&j, 6, 7);\n\n        //yy:\n        yflips[0] = bitflip(&j, 0, 1);\n        yflips[1] = bitflip(&j, 2, 3);\n        yflips[2] = bitflip(&j, 5, 6);\n        \n        // signs for yy-interaction matrix elements\n        si0 = signcheck(&j, 0, 1);\n        si1 = signcheck(&j, 2, 3);\n        si2 = signcheck(&j, 5, 6);\n        \n        ham(j,xflips[0]) = Jx;\n        ham(j,xflips[1]) = Jx;\n        ham(j,xflips[2]) = Jx;\n\n        ham(xflips[0], j) = -Jx;\n        ham(xflips[1], j) = -Jx;\n        ham(xflips[2], j) = -Jx;\n\n        ham(j,yflips[0]) = Jy*si0;\n        ham(j,yflips[1]) = Jy*si1;\n        ham(j,yflips[2]) = Jy*si2;\n\n        ham(yflips[0], j) = -Jy*si0;\n        ham(yflips[1], j) = -Jy*si1;\n        ham(yflips[2], j) = -Jy*si2;\n\n    }\n    \n    cout << \"Diagonalizing ... \" << endl;\n    \n    // Compute eigenvalues of ham:\n    ev = eig_sym(ham);\n    ev.save(\"eigenvalues.mat\", csv_ascii);\n    \n    cout << \"Calculating energy per temperature ... \" << endl;\n    \n    // Calculating energy per temperature (with Boltzmann weights):\n    for (l = 0; l < steps; l++)\n    {\n        Z = 0;\n        E = 0;\n        //temp[l] = 0.000001 + l*0.01; \n        temp[l] = pow(10,-2+(3*l/float(steps))); //logspace\n        \n        for (m = 0; m < size; m++)\n        {\n            Z = Z + exp(-ev[m]/temp[l]);\n            E = E + ev[m]*exp(-ev[m]/temp[l]);        \n        }\n        energy[l] = E/(N*Z);\n    } \n     \n    // Write measured data to text file:    \n    std::fstream f(\"dataexd.txt\", std::ios::out);\n    for (int i = 0; i < steps; ++i)\n    {\n        if (i == 0 || i == steps - 1)\n            f << temp[i] << \" \" << energy[i] << \" \" << 0 << \"\\n\";\n        else \n            f << temp[i] << \" \" << energy[i] << \" \" << (energy[i+1] - energy[i-1])/(2*(temp[i+1] - temp[i-1])) << \"\\n\";\n    }\n    f.close();\n    \n    return 0;\n \n}", "meta": {"hexsha": "2aa77f46a7debf937f17491987ae484807168d7d", "size": 4425, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ED_Honeycomb_Cluster.cpp", "max_stars_repo_name": "timeschmann/KitaevED", "max_stars_repo_head_hexsha": "858109144bd758aaa206e1b344094231b39ff412", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-09-28T12:57:56.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-28T12:57:56.000Z", "max_issues_repo_path": "ED_Honeycomb_Cluster.cpp", "max_issues_repo_name": "timeschmann/KitaevED", "max_issues_repo_head_hexsha": "858109144bd758aaa206e1b344094231b39ff412", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ED_Honeycomb_Cluster.cpp", "max_forks_repo_name": "timeschmann/KitaevED", "max_forks_repo_head_hexsha": "858109144bd758aaa206e1b344094231b39ff412", "max_forks_repo_licenses": ["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.6631016043, "max_line_length": 119, "alphanum_fraction": 0.4476836158, "num_tokens": 1542, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.48645101928408635}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include <opencv2/core/eigen.hpp>\n\nint main()\n{\n\tcv::Mat_<float> a = cv::Mat_<float>::ones(2, 2);\n\tEigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> b;\n\tcv::cv2eigen(a, b);\n}", "meta": {"hexsha": "ef93dd3032a597615912938d82579c98b5ef8cc6", "size": 220, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "MyProject/src/exe/HelloEIGEN2CV/main.cpp", "max_stars_repo_name": "raphaelmenges/CPPFramework", "max_stars_repo_head_hexsha": "67d77fa52da3cbea70c660eaf4044d8724f9d1e0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MyProject/src/exe/HelloEIGEN2CV/main.cpp", "max_issues_repo_name": "raphaelmenges/CPPFramework", "max_issues_repo_head_hexsha": "67d77fa52da3cbea70c660eaf4044d8724f9d1e0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MyProject/src/exe/HelloEIGEN2CV/main.cpp", "max_forks_repo_name": "raphaelmenges/CPPFramework", "max_forks_repo_head_hexsha": "67d77fa52da3cbea70c660eaf4044d8724f9d1e0", "max_forks_repo_licenses": ["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": 56, "alphanum_fraction": 0.6681818182, "num_tokens": 71, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.48645101928408635}}
{"text": "#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE COMPUTE\n\n#include <boost/test/unit_test.hpp>\n\n#include \"api/umo.hpp\"\n\n#include <cmath>\n#include <stdexcept>\n#include <vector>\n\n#define STRINGIFY(x) #x\n#define TOSTRING(x) STRINGIFY(x)\n\nusing namespace umo;\n\nconst double eps = 0.001;\n\nBOOST_AUTO_TEST_CASE(LinearizationFloatDec) {\n    Model model;\n    FloatExpression x1 = model.floatVar(-3.0, 10.2);\n    FloatExpression x2 = model.floatVar(-50.9, 10.33);\n    FloatExpression x3 = model.floatVar(-4.4, -2.0);\n    FloatExpression x4 = model.floatVar(10.0, 21.2);\n    maximize(x1 + x2 + x3 + x4);\n    model.setSolver(TOSTRING(SOLVER_PARAM));\n    model.solve();\n    BOOST_CHECK_CLOSE(x1.getValue(), 10.2, eps);\n    BOOST_CHECK_CLOSE(x2.getValue(), 10.33, eps);\n    BOOST_CHECK_CLOSE(x3.getValue(), -2.0, eps);\n    BOOST_CHECK_CLOSE(x4.getValue(), 21.2, eps);\n    BOOST_CHECK_EQUAL(model.getStatus(), Status::Optimal);\n}\n\nBOOST_AUTO_TEST_CASE(LinearizationIntDec) {\n    Model model;\n    IntExpression x1 = model.intVar(0, 10);\n    IntExpression x2 = model.intVar(-50, 10);\n    IntExpression x3 = model.intVar(-4, -2);\n    IntExpression x4 = model.intVar(10, 21);\n    maximize(x1 + x2 + x3 + x4);\n    model.setSolver(TOSTRING(SOLVER_PARAM));\n    model.solve();\n    BOOST_CHECK_EQUAL(x1.getValue(), 10);\n    BOOST_CHECK_EQUAL(x2.getValue(), 10);\n    BOOST_CHECK_EQUAL(x3.getValue(), -2);\n    BOOST_CHECK_EQUAL(x4.getValue(), 21);\n    BOOST_CHECK_EQUAL(model.getStatus(), Status::Optimal);\n}\n\nBOOST_AUTO_TEST_CASE(LinearizationBoolDec) {\n    Model model;\n    BoolExpression x1 = model.boolVar();\n    BoolExpression x2 = model.boolVar();\n    BoolExpression x3 = model.boolVar();\n    BoolExpression x4 = model.boolVar();\n    maximize(x1 + x2 + x3 + x4);\n    model.setSolver(TOSTRING(SOLVER_PARAM));\n    model.solve();\n    BOOST_CHECK(x1.getValue());\n    BOOST_CHECK(x2.getValue());\n    BOOST_CHECK(x3.getValue());\n    BOOST_CHECK(x4.getValue());\n    BOOST_CHECK_EQUAL(model.getStatus(), Status::Optimal);\n}\n\nBOOST_AUTO_TEST_CASE(LinearizationFloatCmp1) {\n    Model model;\n    FloatExpression x = model.floatVar();\n    constraint(x > 2.0);\n    minimize(x);\n    model.setSolver(TOSTRING(SOLVER_PARAM));\n    model.solve();\n    BOOST_CHECK_CLOSE(x.getValue(), 2.0, eps);\n    BOOST_CHECK_EQUAL(model.getStatus(), Status::Optimal);\n}\n\nBOOST_AUTO_TEST_CASE(LinearizationFloatCmp2) {\n    Model model;\n    FloatExpression x = model.floatVar();\n    constraint(x < 2.0);\n    maximize(x);\n    model.setSolver(TOSTRING(SOLVER_PARAM));\n    model.solve();\n    BOOST_CHECK_CLOSE(x.getValue(), 2.0, eps);\n    BOOST_CHECK_EQUAL(model.getStatus(), Status::Optimal);\n}\n\nBOOST_AUTO_TEST_CASE(LinearizationFloatCmp3) {\n    Model model;\n    FloatExpression x = model.floatVar();\n    constraint(x >= 2.0);\n    minimize(x);\n    model.setSolver(TOSTRING(SOLVER_PARAM));\n    model.solve();\n    BOOST_CHECK_CLOSE(x.getValue(), 2.0, eps);\n    BOOST_CHECK_EQUAL(model.getStatus(), Status::Optimal);\n}\n\nBOOST_AUTO_TEST_CASE(LinearizationFloatCmp4) {\n    Model model;\n    FloatExpression x = model.floatVar();\n    constraint(x <= 2.0);\n    maximize(x);\n    model.setSolver(TOSTRING(SOLVER_PARAM));\n    model.solve();\n    BOOST_CHECK_CLOSE(x.getValue(), 2.0, eps);\n    BOOST_CHECK_EQUAL(model.getStatus(), Status::Optimal);\n}\n\nBOOST_AUTO_TEST_CASE(LinearizationFloatCmp5) {\n    Model model;\n    FloatExpression x = model.floatVar();\n    FloatExpression y = model.floatVar(5.0, 10.0);\n    constraint(x >= y);\n    minimize(x);\n    model.setSolver(TOSTRING(SOLVER_PARAM));\n    model.solve();\n    BOOST_CHECK_CLOSE(x.getValue(), 5.0, eps);\n    BOOST_CHECK_EQUAL(model.getStatus(), Status::Optimal);\n}\n\nBOOST_AUTO_TEST_CASE(LinearizationFloatCmp6) {\n    Model model;\n    FloatExpression x = model.floatVar();\n    FloatExpression y = model.floatVar(5.0, 10.0);\n    constraint(x <= y);\n    maximize(x);\n    model.setSolver(TOSTRING(SOLVER_PARAM));\n    model.solve();\n    BOOST_CHECK_CLOSE(x.getValue(), 10.0, eps);\n    BOOST_CHECK_EQUAL(model.getStatus(), Status::Optimal);\n}\n\n\nBOOST_AUTO_TEST_CASE(LinearizationFloatEq1) {\n    Model model;\n    FloatExpression x = model.floatVar();\n    constraint(x == 2.0);\n    maximize(x);\n    model.setSolver(TOSTRING(SOLVER_PARAM));\n    model.solve();\n    BOOST_CHECK_CLOSE(x.getValue(), 2.0, eps);\n    BOOST_CHECK_EQUAL(model.getStatus(), Status::Optimal);\n}\n\nBOOST_AUTO_TEST_CASE(LinearizationFloatEq2) {\n    Model model;\n    FloatExpression x = model.floatVar();\n    FloatExpression y = model.floatVar(0.0, 2.0);\n    constraint(x == y);\n    maximize(x);\n    model.setSolver(TOSTRING(SOLVER_PARAM));\n    model.solve();\n    BOOST_CHECK_CLOSE(x.getValue(), 2.0, eps);\n    BOOST_CHECK_EQUAL(model.getStatus(), Status::Optimal);\n}\n\nBOOST_AUTO_TEST_CASE(LinearizationFloatEq3) {\n    Model model;\n    FloatExpression x = model.floatVar();\n    constraint(!(x != 2.0));\n    maximize(x);\n    model.setSolver(TOSTRING(SOLVER_PARAM));\n    model.solve();\n    BOOST_CHECK_CLOSE(x.getValue(), 2.0, eps);\n    BOOST_CHECK_EQUAL(model.getStatus(), Status::Optimal);\n}\n\nBOOST_AUTO_TEST_CASE(LinearizationFloatEq4) {\n    Model model;\n    FloatExpression x = model.floatVar();\n    FloatExpression y = model.floatVar(0.0, 2.0);\n    constraint(!(x != y));\n    maximize(x);\n    model.setSolver(TOSTRING(SOLVER_PARAM));\n    model.solve();\n    BOOST_CHECK_CLOSE(x.getValue(), 2.0, eps);\n    BOOST_CHECK_EQUAL(model.getStatus(), Status::Optimal);\n}\n\nBOOST_AUTO_TEST_CASE(LinearizationFloatNeq1) {\n    Model model;\n    FloatExpression x = model.floatVar(0.0, 5.0);\n    constraint(x != 2.0);\n    maximize(x);\n    model.setSolver(TOSTRING(SOLVER_PARAM));\n    BOOST_CHECK_THROW(model.solve(), std::runtime_error);\n}\n\nBOOST_AUTO_TEST_CASE(LinearizationFloatNeq2) {\n    Model model;\n    FloatExpression x = model.floatVar();\n    FloatExpression y = model.floatVar(0.0, 2.0);\n    constraint(x != y);\n    maximize(x);\n    model.setSolver(TOSTRING(SOLVER_PARAM));\n    BOOST_CHECK_THROW(model.solve(), std::runtime_error);\n}\n\nBOOST_AUTO_TEST_CASE(LinearizationFloatNeq3) {\n    Model model;\n    FloatExpression x = model.floatVar(0.0, 5.0);\n    constraint(!(x == 2.0));\n    maximize(x);\n    model.setSolver(TOSTRING(SOLVER_PARAM));\n    BOOST_CHECK_THROW(model.solve(), std::runtime_error);\n}\n\nBOOST_AUTO_TEST_CASE(LinearizationFloatNeq4) {\n    Model model;\n    FloatExpression x = model.floatVar();\n    FloatExpression y = model.floatVar(0.0, 2.0);\n    constraint(!(x == y));\n    maximize(x);\n    model.setSolver(TOSTRING(SOLVER_PARAM));\n    BOOST_CHECK_THROW(model.solve(), std::runtime_error);\n}\n\nBOOST_AUTO_TEST_CASE(LinearizationAnd1) {\n    Model model;\n    BoolExpression dec1 = model.boolVar();\n    BoolExpression dec2 = model.boolVar();\n    BoolExpression dec3 = model.boolVar();\n    std::vector<BoolExpression> vec{dec1, dec2, dec3};\n    BoolExpression obj = logical_and(vec);\n    maximize(obj);\n    model.setSolver(TOSTRING(SOLVER_PARAM));\n    model.solve();\n    BOOST_CHECK(dec1.getValue() && dec2.getValue() && dec3.getValue());\n    BOOST_CHECK_EQUAL(model.getStatus(), Status::Optimal);\n}\n\nBOOST_AUTO_TEST_CASE(LinearizationAnd2) {\n    Model model;\n    BoolExpression dec1 = model.boolVar();\n    BoolExpression dec2 = model.boolVar();\n    BoolExpression dec3 = model.boolVar();\n    std::vector<BoolExpression> vec{dec1, dec2, dec3};\n    BoolExpression obj = logical_and(vec);\n    minimize(obj);\n    model.setSolver(TOSTRING(SOLVER_PARAM));\n    model.solve();\n    BOOST_CHECK(!(dec1.getValue() && dec2.getValue() && dec3.getValue()));\n    BOOST_CHECK_EQUAL(model.getStatus(), Status::Optimal);\n}\n\nBOOST_AUTO_TEST_CASE(LinearizationOr1) {\n    Model model;\n    BoolExpression dec1 = model.boolVar();\n    BoolExpression dec2 = model.boolVar();\n    BoolExpression dec3 = model.boolVar();\n    std::vector<BoolExpression> vec{dec1, dec2, dec3};\n    BoolExpression obj = logical_or(vec);\n    maximize(obj);\n    model.setSolver(TOSTRING(SOLVER_PARAM));\n    model.solve();\n    BOOST_CHECK(dec1.getValue() || dec2.getValue() || dec3.getValue());\n    BOOST_CHECK_EQUAL(model.getStatus(), Status::Optimal);\n}\n\nBOOST_AUTO_TEST_CASE(LinearizationOr2) {\n    Model model;\n    BoolExpression dec1 = model.boolVar();\n    BoolExpression dec2 = model.boolVar();\n    BoolExpression dec3 = model.boolVar();\n    std::vector<BoolExpression> vec{dec1, dec2, dec3};\n    BoolExpression obj = logical_or(vec);\n    minimize(obj);\n    model.setSolver(TOSTRING(SOLVER_PARAM));\n    model.solve();\n    BOOST_CHECK(!(dec1.getValue() || dec2.getValue() || dec3.getValue()));\n    BOOST_CHECK_EQUAL(model.getStatus(), Status::Optimal);\n}\n\nBOOST_AUTO_TEST_CASE(LinearizationMax1) {\n    Model model;\n    FloatExpression dec1 = model.floatVar();\n    FloatExpression dec2 = model.floatVar();\n    maximize(umo::max(dec1, dec2));\n    model.setSolver(TOSTRING(SOLVER_PARAM));\n    BOOST_CHECK_THROW(model.solve(), std::runtime_error);\n}\n\nBOOST_AUTO_TEST_CASE(LinearizationMin1) {\n    Model model;\n    FloatExpression dec1 = model.floatVar();\n    FloatExpression dec2 = model.floatVar();\n    maximize(umo::min(dec1, dec2));\n    model.setSolver(TOSTRING(SOLVER_PARAM));\n    BOOST_CHECK_THROW(model.solve(), std::runtime_error);\n}\n\nBOOST_AUTO_TEST_CASE(LinearizationMultiObjective) {\n    Model model;\n    FloatExpression dec1 = model.floatVar();\n    FloatExpression dec2 = model.floatVar();\n    maximize(dec1);\n    minimize(dec2);\n    model.setSolver(TOSTRING(SOLVER_PARAM));\n    BOOST_CHECK_THROW(model.solve(), std::runtime_error);\n}\n\nBOOST_AUTO_TEST_CASE(LinearizationUnfeasible) {\n    Model model;\n    FloatExpression dec1 = model.floatVar(0, 10);\n    FloatExpression dec2 = model.floatVar(0, 10);\n    constraint(dec1 + 1 <= dec2);\n    constraint(dec2 + 1 <= dec1);\n    maximize(dec1);\n    model.setSolver(TOSTRING(SOLVER_PARAM));\n    model.solve();\n    if (TOSTRING(SOLVER_PARAM) == \"glpk\")\n        return; // Yes GLPK screws up the return value here\n    BOOST_CHECK_EQUAL(model.getStatus(), Status::Infeasible);\n}\n\nBOOST_AUTO_TEST_CASE(LinearizationUnbounded) {\n    Model model;\n    FloatExpression dec1 = model.floatVar();\n    FloatExpression dec2 = model.floatVar();\n    constraint(dec1 <= dec2);\n    maximize(dec1);\n    model.setSolver(TOSTRING(SOLVER_PARAM));\n    model.solve();\n    if (TOSTRING(SOLVER_PARAM) == \"glpk\")\n        return; // Yes GLPK screws up the return value here\n    BOOST_CHECK_EQUAL(model.getStatus(), Status::Unbounded);\n}\n\nBOOST_AUTO_TEST_CASE(LinearizationSimple1) {\n    Model model;\n    FloatExpression x1 = model.floatVar();\n    FloatExpression x2 = model.floatVar();\n    constraint(3 * x1 + x2 <= 4);\n    constraint(2 * x1 + 3 * x2 <= 5);\n    constraint(2 * x1 + 9 * x2 <= 8);\n    maximize(x1 + 2 * x2);\n    model.setSolver(TOSTRING(SOLVER_PARAM));\n    model.solve();\n    BOOST_CHECK_CLOSE(x1.getValue(), 1.12, eps);\n    BOOST_CHECK_CLOSE(x2.getValue(), 0.64, eps);\n    BOOST_CHECK_EQUAL(model.getStatus(), Status::Optimal);\n}\n\nBOOST_AUTO_TEST_CASE(LinearizationSimple2) {\n    Model model;\n    FloatExpression x1 = model.floatVar();\n    FloatExpression x2 = model.floatVar();\n    FloatExpression x3 = model.floatVar();\n    FloatExpression x4 = model.floatVar();\n    constraint(x1 <= 5);\n    constraint(x2 <= 3);\n    constraint(x3 <= 10);\n    constraint(x4 < 50);\n    constraint(x1 + 3 * x2 <= 3);\n    constraint(x1 + 2 * x2 <= 4);\n    constraint(x2 + x1 <= 3);\n    constraint(x3 + x4 <= 2);\n    constraint(x1 + x3 <= 5);\n    constraint(x1 + x4 + 3 * x2 <= 4);\n    maximize(x1 + x2 + 2 * x3 + x4);\n    model.setSolver(TOSTRING(SOLVER_PARAM));\n    model.solve();\n    BOOST_CHECK_CLOSE(x1.getValue(), -5, eps);\n    BOOST_CHECK_CLOSE(x2.getValue(), 2.6666666, eps);\n    BOOST_CHECK_CLOSE(x3.getValue(), 10, eps);\n    BOOST_CHECK_CLOSE(x4.getValue(), -8, eps);\n    BOOST_CHECK_EQUAL(model.getStatus(), Status::Optimal);\n}\n\nBOOST_AUTO_TEST_CASE(LinearizationWithTimeLimit) {\n    Model model;\n    FloatExpression dec1 = model.floatVar(0.0, 5.0);\n    maximize(dec1);\n    model.setTimeLimit(2.0);\n    model.setSolver(TOSTRING(SOLVER_PARAM));\n    model.solve();\n    BOOST_CHECK_EQUAL(model.getStatus(), Status::Optimal);\n}\n\nBOOST_AUTO_TEST_CASE(ExplicitConstraint1) {\n    Model model;\n    FloatExpression x1 = model.floatVar();\n    linearConstraint(umo::unbounded(), 5.0, {x1});\n    maximize(x1);\n    model.setSolver(TOSTRING(SOLVER_PARAM));\n    model.solve();\n    BOOST_CHECK_CLOSE(x1.getValue(), 5.0, eps);\n    BOOST_CHECK_EQUAL(model.getStatus(), Status::Optimal);\n}\n\nBOOST_AUTO_TEST_CASE(ExplicitConstraint2) {\n    Model model;\n    FloatExpression x1 = model.floatVar();\n    linearConstraint(umo::unbounded(), 10.0, {x1}, {2.0});\n    maximize(x1);\n    model.setSolver(TOSTRING(SOLVER_PARAM));\n    model.solve();\n    BOOST_CHECK_CLOSE(x1.getValue(), 5.0, eps);\n    BOOST_CHECK_EQUAL(model.getStatus(), Status::Optimal);\n}\n", "meta": {"hexsha": "f05be2002cfdeac8a8f0a742d7e9de72a2248bbc", "size": 12771, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/solve_milp.cpp", "max_stars_repo_name": "Coloquinte/umo", "max_stars_repo_head_hexsha": "1f39c316d6584bbed22913aabaa4bfb5ee02d72b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-24T20:56:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-24T20:56:25.000Z", "max_issues_repo_path": "test/solve_milp.cpp", "max_issues_repo_name": "Coloquinte/umo", "max_issues_repo_head_hexsha": "1f39c316d6584bbed22913aabaa4bfb5ee02d72b", "max_issues_repo_licenses": ["MIT"], "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/solve_milp.cpp", "max_forks_repo_name": "Coloquinte/umo", "max_forks_repo_head_hexsha": "1f39c316d6584bbed22913aabaa4bfb5ee02d72b", "max_forks_repo_licenses": ["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.6898263027, "max_line_length": 74, "alphanum_fraction": 0.6871035941, "num_tokens": 3372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4864510192840863}}
{"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 *    References\n *      Musegaas, P. (2012). Optimization of Space Trajectories Including Multiple Gravity Assists\n *          and Deep Space Maneuvers. MSc Thesis, Delft University of Technology, Delft,\n *          The Netherlands.\n *\n */\n\n#define BOOST_TEST_MAIN\n\n#include <limits>\n\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/unit_test.hpp>\n\n#include <Eigen/Core>\n\n#include <Tudat/Astrodynamics/BasicAstrodynamics/physicalConstants.h>\n#include <Tudat/Basics/testMacros.h>\n\n#include \"Tudat/Astrodynamics/TrajectoryDesign/departureLegMga1DsmPosition.h\"\n\nnamespace tudat\n{\nnamespace unit_tests\n{\n\n//! Test implementation of departure leg within MGA trajectory model\nBOOST_AUTO_TEST_SUITE( test_departure_leg_mga_1dsm_position )\n\n//! Test delta-V computation\nBOOST_AUTO_TEST_CASE( testVelocities )\n{\n    // Set tolerance. Due to iterative nature in the process, (much) higher accuracy cannot be\n    // achieved.\n    const double tolerance = 1.0e-6;\n\n    // Expected test result based on the first leg of the ideal Messenger trajectory as modelled by\n    // GTOP software distributed and downloadable from the ESA website, or within the PaGMO\n    // Astrotoolbox.\n    const double expectedDeltaV = 1408.99421278 + 910.801673341206;\n    const Eigen::Vector3d expectedVelocity ( 17969.3166254715, -23543.6915939142,\n                                             6.38384671663485 );\n\n    // Specify the required parameters.\n    // Set the planetary positions and velocities.\n    const Eigen::Vector3d planet1Position ( -148689402143.081, 7454242895.97607, 0. );\n    const Eigen::Vector3d planet2Position ( -128359548637.032, -78282803797.7343, 0. );\n    const Eigen::Vector3d planet1Velocity ( -1976.48781307596, -29863.4035321021, 0. );\n\n    // Set the time of flight, which has to be converted from JD (in GTOP) to seconds (in Tudat).\n    const double timeOfFlight = 399.999999715 * physical_constants::JULIAN_DAY;\n\n    // Set the gravitational parameter.\n    const double sunGravitationalParameter = 1.32712428e20;\n    const double earthGravitationalParameter = 3.9860119e14;\n\n    // Set the departure parking orbit (at inifinity)\n    const double semiMajorAxis = std::numeric_limits< double >::infinity( );\n    const double eccentricity = 0.;\n\n    // Set DSM parameters.\n    const double dsmTimeOfFlightFraction = 0.234594654679;\n//?!? const Eigen::Vector3d dsmLocation ( 10272022720.5409, -135966957958.46, 26316361.9336743 );\n    const double inPlaneAngle = 1.69629206466940;\n    const double outOfPlaneAngle = 0.00019299969467;\n    const double dimensionlessRadiusDsm = 0.915891737859598;\n\n    // Set test case.\n    using namespace tudat::transfer_trajectories;\n    DepartureLegMga1DsmPosition legTest ( planet1Position, planet2Position, timeOfFlight,\n                                          planet1Velocity, sunGravitationalParameter,\n                                          earthGravitationalParameter, semiMajorAxis, eccentricity,\n                                          dsmTimeOfFlightFraction, //dsmLocation\n                                          dimensionlessRadiusDsm, inPlaneAngle, outOfPlaneAngle );\n\n    // Prepare the variables for the results.\n    Eigen::Vector3d resultingVelocity;\n    double resultingDeltaV;\n\n    // Compute delta-V of the leg.\n    legTest.calculateLeg( resultingVelocity, resultingDeltaV );\n\n    // Test if the computed delta-V corresponds to the expected value within the specified\n    // tolerance and if the computed velocity before target planet matches the expected velocity\n    // within the specified tolerance.\n    BOOST_CHECK_CLOSE_FRACTION( expectedDeltaV, resultingDeltaV, tolerance );\n    TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedVelocity, resultingVelocity, tolerance );\n}\n\n//! Test updating the variables.\nBOOST_AUTO_TEST_CASE( testUpdatingVariables )\n{\n    // Set tolerance. Due to iterative nature in the process, (much) higher accuracy cannot be\n    // achieved.\n    const double tolerance = 1.0e-6;\n\n    // Expected test result based on the first leg of the ideal Messenger trajectory as modelled by\n    // GTOP software distributed and downloadable from the ESA website, or within the PaGMO\n    // Astrotoolbox.\n    const double expectedDeltaV = 1408.99421278 + 910.801673341206;\n    const Eigen::Vector3d expectedVelocity ( 17969.3166254715, -23543.6915939142,\n                                             6.38384671663485 );\n\n    // Specify the required parameters.\n    // Set the dummy positions and velocities.\n    const Eigen::Vector3d dummyPosition1 ( TUDAT_NAN, TUDAT_NAN, TUDAT_NAN );\n    const Eigen::Vector3d dummyPosition2 ( TUDAT_NAN, TUDAT_NAN, TUDAT_NAN );\n    const Eigen::Vector3d dummyVelocity1 ( TUDAT_NAN, TUDAT_NAN, TUDAT_NAN );\n\n    // Set the dummy time of flight.\n    const double dummyTimeOfFlight = TUDAT_NAN;\n\n    // Set the gravitational parameter.\n    const double sunGravitationalParameter = 1.32712428e20;\n    const double earthGravitationalParameter = 3.9860119e14;\n\n    // Set the departure parking orbit (at inifinity)\n    const double semiMajorAxis = std::numeric_limits< double >::infinity( );\n    const double eccentricity = 0.;\n\n    // Set the dummy DSM variables.\n    const double dummyVariable1 = TUDAT_NAN;\n    const double dummyVariable2 = TUDAT_NAN;\n    const double dummyVariable3 = TUDAT_NAN;\n    const double dummyVariable4 = TUDAT_NAN;\n\n    // Set test case.\n    using namespace tudat::transfer_trajectories;\n    DepartureLegMga1DsmPosition legTest ( dummyPosition1, dummyPosition2, dummyTimeOfFlight,\n                                          dummyVelocity1, sunGravitationalParameter,\n                                          earthGravitationalParameter, semiMajorAxis, eccentricity,\n                                          dummyVariable1,\n                                          dummyVariable2, dummyVariable3, dummyVariable4 );\n\n    // Prepare the variables for the results.\n    Eigen::Vector3d resultingVelocity;\n    double resultingDeltaV;\n\n    // Compute delta-V of the leg.\n    //legTest.calculateLeg( resultingVelocity, resultingDeltaV );\n\n    // Specify the values for the parameters that are to be updated.\n    // Set the planetary positions and velocities.\n    const Eigen::Vector3d planet1Position ( -148689402143.081, 7454242895.97607, 0. );\n    const Eigen::Vector3d planet2Position ( -128359548637.032, -78282803797.7343, 0. );\n    const Eigen::Vector3d planet1Velocity ( -1976.48781307596, -29863.4035321021, 0. );\n\n    // Set the time of flight, which has to be converted from JD (in GTOP) to seconds (in Tudat).\n    const double timeOfFlight = 399.999999715 * physical_constants::JULIAN_DAY;\n\n    // Set DSM parameters.\n    const double dsmTimeOfFlightFraction = 0.234594654679;\n    const double inPlaneAngle = 1.69629206466940;\n    const double outOfPlaneAngle = 0.00019299969467;\n    const double dimensionlessRadiusDsm = 0.915891737859598;\n\n    // Create a variable vector containing these parameters.\n    Eigen::VectorXd variableVector( 5 );\n    variableVector << timeOfFlight, dsmTimeOfFlightFraction, dimensionlessRadiusDsm, inPlaneAngle,\n                      outOfPlaneAngle;\n\n    // Pass both the new ephemeris and trajectory defining variables to the leg.\n    legTest.updateEphemeris( planet1Position, planet2Position, planet1Velocity );\n    legTest.updateDefiningVariables( variableVector );\n\n    // Recompute the delta-V of the leg.\n    legTest.calculateLeg( resultingVelocity, resultingDeltaV );\n\n    // Test if the computed delta-V corresponds to the expected value within the specified\n    // tolerance and if the computed velocity before target planet matches the expected velocity\n    // within the specified tolerance.\n    BOOST_CHECK_CLOSE_FRACTION( expectedDeltaV, resultingDeltaV, tolerance );\n    TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedVelocity, resultingVelocity, tolerance );\n}\n\n//! Test intermediate points function.\nBOOST_AUTO_TEST_CASE( testIntermediatePoints )\n{\n    // Set tolerance.\n    const double tolerance = 1e-13;\n\n    // Specify the required parameters, for the first leg of Messenger within GTOP.\n    // Set the planetary positions and velocities.\n    const Eigen::Vector3d planet1Position ( -148689402143.081, 7454242895.97607, 0. );\n    const Eigen::Vector3d planet2Position ( -128359548637.032, -78282803797.7343, 0. );\n    const Eigen::Vector3d planet1Velocity ( -1976.48781307596, -29863.4035321021, 0. );\n\n    // Set the time of flight, which has to be converted from JD (in GTOP) to seconds (in Tudat).\n    const double timeOfFlight = 399.999999715 * physical_constants::JULIAN_DAY;\n\n    // Set the gravitational parameters.\n    const double sunGravitationalParameter = 1.32712428e20;\n    const double earthGravitationalParameter = 3.9860119e14;\n\n    // Set the departure parking orbit (at inifinity)\n    const double semiMajorAxis = 1e300;\n    const double eccentricity = 0.;\n\n    // Set DSM parameters.\n    const double dsmTimeOfFlightFraction = 0.234594654679;\n    const double inPlaneAngle = 1.69629206466940;\n    const double outOfPlaneAngle = 0.00019299969467;\n    const double dimensionlessRadiusDsm = 0.915891737859598;\n\n\n    // Set test case.\n    using namespace tudat::transfer_trajectories;\n    DepartureLegMga1DsmPosition legTest ( planet1Position, planet2Position, timeOfFlight,\n                                          planet1Velocity, sunGravitationalParameter,\n                                          earthGravitationalParameter, semiMajorAxis, eccentricity,\n                                          dsmTimeOfFlightFraction,\n                                          dimensionlessRadiusDsm, inPlaneAngle, outOfPlaneAngle );\n\n    // Initiate vectors for storing the results.\n    std::vector < Eigen::Vector3d > positionVector1, positionVector2;\n    std::vector < double > timeVector1, timeVector2;\n\n    // Test the functionality in case the leg has not been calculated yet.\n    legTest.intermediatePoints( 50. * physical_constants::JULIAN_DAY,\n                                positionVector1, timeVector1 );\n\n    // Prepare the variables for calculating the leg actively.\n    Eigen::Vector3d resultingVelocity;\n    double resultingDeltaV;\n\n    // Calculate the leg actively.\n    legTest.calculateLeg( resultingVelocity, resultingDeltaV );\n\n    // Test the functionality in case the leg has been calculated already.\n    legTest.intermediatePoints( 25. * physical_constants::JULIAN_DAY,\n                                positionVector2, timeVector2 );\n\n    // Test if the halfway points in the first part of the leg match between the intermediate\n    // points functions.\n    BOOST_CHECK_CLOSE_FRACTION( timeVector1[1] , timeVector2[2], tolerance );\n    TUDAT_CHECK_MATRIX_CLOSE_FRACTION( positionVector1[1], positionVector2[2], tolerance );\n}\n\nBOOST_AUTO_TEST_SUITE_END( )\n\n} // namespace unit_tests\n} // namespace tudat\n", "meta": {"hexsha": "a92572744ecb849294e787990987571709da7aa9", "size": 11278, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/TrajectoryDesign/UnitTests/unitTestDepartureLegMga1DsmPosition.cpp", "max_stars_repo_name": "sebranchett/tudat", "max_stars_repo_head_hexsha": "24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tudat/Astrodynamics/TrajectoryDesign/UnitTests/unitTestDepartureLegMga1DsmPosition.cpp", "max_issues_repo_name": "sebranchett/tudat", "max_issues_repo_head_hexsha": "24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tudat/Astrodynamics/TrajectoryDesign/UnitTests/unitTestDepartureLegMga1DsmPosition.cpp", "max_forks_repo_name": "sebranchett/tudat", "max_forks_repo_head_hexsha": "24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.753968254, "max_line_length": 99, "alphanum_fraction": 0.7095229651, "num_tokens": 2755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4864510192840863}}
{"text": "#ifndef __CRUNCHY__\n#define __CRUNCHY__\n\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/spirit/include/qi.hpp>\n#include <boost/algorithm/string.hpp>\n\n\n#include <vector>\n\n#include \"result.hpp\"\n\nnamespace ipaddress {\n/**\n * based\n * Crunch - Arbitrary-precision integer arithmetic library\n * Copyright (C) 2014 Nenad Vukicevic crunch.secureroom.net/license\n *\n */\n/**\n * @module Crunch\n * Radix: 28 bits\n * Endianness: Big\n *\n * @param {boolean} rawIn   - expect 28-bit arrays\n * @param {boolean} rawOut  - return 28-bit arrays\n */\n// import Crunch from './crunch';\n\nclass NotImplementedException : public std::exception\n{\npublic:\n    NotImplementedException() {}\n    ~NotImplementedException() {}\n    virtual char const * what() const throw() { return \"Function not yet implemented.\"; }\n};\n\nclass Crunchy {\n  // we need for ipv6 129 bits\n  typedef boost::multiprecision::uint256_t CrunchyType;\n  CrunchyType num;\npublic:\n  Crunchy clone() const {\n    Crunchy ret;\n    ret.num = this->num;\n    return ret;\n  }\n\n  static Crunchy from_8bit(const std::vector<unsigned char> &number) {\n    Crunchy ret;\n    for (auto i : number) {\n        ret.num = (ret.num << 8) + CrunchyType(i);\n    }\n    return ret;\n  }\n\n  static Result<Crunchy> parse(const std::string &val) {\n    return Crunchy::from_string(val, 10);\n  }\n\n  static Crunchy from_number(size_t num)  {\n    Crunchy ret;\n    ret.num = CrunchyType(num);\n    return ret;\n  }\n  static Result<Crunchy> from_string(const std::string &val, size_t radix = 10) {\n  Crunchy ret;\n  auto f(val.begin());\n  auto l(val.end());\n  if (radix == 10) {\n    boost::spirit::qi::int_parser<CrunchyType, 10, 0, 39> uint256_dec;\n    if (!boost::spirit::qi::parse(f, l, uint256_dec, ret.num)) {\n        return Err<Crunchy>(\"inpossible to parse\");\n    }\n  } else if (radix == 16) {\n    boost::spirit::qi::int_parser<CrunchyType, 16, 0, 39> uint256_hex;\n    if (!boost::spirit::qi::parse(f, l, uint256_hex, ret.num)) {\n        return Err<Crunchy>(\"inpossible to parse\");\n    }\n  } else {\n    throw NotImplementedException();\n  }\n  return Ok(ret);\n  }\n\n  std::vector<unsigned char> to_8bit() const {\n    std::vector<unsigned char> ret;\n    auto my = this->num;\n    // std::cout << \"to_8bit:\" << std::hex << my << std::endl;\n    do {\n        ret.push_back(static_cast<size_t>(my&0xff));\n        my = my >> 8;\n    } while (my != 0);\n    std::reverse(ret.begin(),ret.end());\n    // std::stringstream s2;\n    // for (auto i : ret) {\n    //     s2 << \" \" << std::hex << static_cast<size_t>(i);\n    // }\n    // std::cout << \"to_8bit:\" << s2.str() << std::endl;\n    return ret;\n  }\n\n  int compare(const Crunchy &y) const {\n    if (this->num < y.num) {\n      // std::cout << \"-1=\" << this->num << \"---\" << y.num << std::endl;\n      return -1;\n    } else if (this->num > y.num) {\n      // std::cout << \"1=\" << this->num << \"---\" << y.num << std::endl;\n      return 1;\n    }\n    // std::cout << \"0=\" << this->num << \"---\" << y.num << std::endl;\n    return 0;\n  }\n\n  bool eq(const Crunchy &oth) const {\n    return this->compare(oth) == 0;\n  }\n\n  bool lte(const Crunchy &oth) const {\n    return this->compare(oth) <= 0;\n  }\n  bool lt(const Crunchy &oth) const {\n    return this->compare(oth) < 0;\n  }\n\n  bool gt(const Crunchy &oth) const {\n    return this->compare(oth) > 0;\n  }\n  bool gte(const Crunchy &oth) const {\n    return this->compare(oth) >= 0;\n  }\n\n  Crunchy add(const Crunchy &oth) const {\n    Crunchy ret;\n    ret.num = this->num + oth.num;\n    return ret;\n  }\n\n  Crunchy sub(const Crunchy &oth) const {\n    Crunchy ret;\n    ret.num = this->num - oth.num;\n    return ret;\n  }\n  Crunchy mul(const Crunchy &oth) const {\n    Crunchy ret;\n    ret.num = this->num * oth.num;\n    return ret;\n  }\n\n  Crunchy shr(size_t s) const {\n    Crunchy ret;\n    ret.num = this->num >> s;\n    return ret;\n  }\n\n  Crunchy shl(size_t s) const {\n    Crunchy ret;\n    ret.num = this->num << s;\n    // std::cout << \"shl:\" << std::hex << this->num << \":\" << s << \":\" << ret.num << std::endl;\n    return ret;\n  }\n\n  Crunchy div(const Crunchy &oth) const {\n    Crunchy ret;\n    ret.num = this->num / oth.num;\n    return ret;\n  }\n  // public sub(cry: Crunchy): Crunchy {\n  //   return Crunchy.from_8bit(Crunch.sub(this->num, cry.num));\n  // }\n\n  Crunchy mod(const Crunchy &oth) const {\n    Crunchy ret;\n    ret.num = this->num % oth.num;\n    return ret;\n  }\n\n  size_t mds(size_t n) const {\n    return static_cast<size_t>(this->num % n);\n  }\n\n\n  std::string toString(size_t radix = 10) const {\n    std::stringstream s2;\n    if (radix == 10) {\n      s2 << std::dec;\n      s2 << this->num;\n      return s2.str();\n    } else if (radix == 16) {\n      s2 << std::hex;\n      s2 << this->num;\n      auto ret = s2.str();\n      boost::algorithm::to_lower(ret);\n      return ret;\n    } else if (radix == 2) {\n      std::vector<size_t> bits;\n      auto my = this->num;\n      do {\n        size_t tmp = static_cast<size_t>(my&0x1);\n        bits.push_back(tmp);\n        my = my >> 1;\n      } while(my != 0);\n      for (int i = bits.size()-1; i >= 0; --i) {\n        s2 << bits[i];\n      }\n      return s2.str();\n    } else {\n      throw NotImplementedException();\n    }\n  }\n\n  static const Crunchy &zero();\n  static const Crunchy &one();\n  static const Crunchy &two();\n\n\n};\n\nstd::ostream& operator<<(std::ostream &o, const Crunchy &crunchy);\n\n}\n\n#endif\n", "meta": {"hexsha": "46e4d53999ac936681b6d1c498628d17c5ea6381", "size": 5341, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cpp/src/crunchy.hpp", "max_stars_repo_name": "0xflotus/ipaddress", "max_stars_repo_head_hexsha": "0d53ff453ec901e408ef28435802318282e43ccc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2017-09-28T09:14:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-01T07:24:41.000Z", "max_issues_repo_path": "cpp/src/crunchy.hpp", "max_issues_repo_name": "0xflotus/ipaddress", "max_issues_repo_head_hexsha": "0d53ff453ec901e408ef28435802318282e43ccc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-08-31T06:55:54.000Z", "max_issues_repo_issues_event_max_datetime": "2016-08-31T06:55:54.000Z", "max_forks_repo_path": "cpp/src/crunchy.hpp", "max_forks_repo_name": "0xflotus/ipaddress", "max_forks_repo_head_hexsha": "0d53ff453ec901e408ef28435802318282e43ccc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2016-08-31T06:45:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-13T10:31:03.000Z", "avg_line_length": 23.84375, "max_line_length": 95, "alphanum_fraction": 0.5796667291, "num_tokens": 1611, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956580903722561, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.48645101335924584}}
{"text": "#include <iostream>\n\n/*\n   Copyright 2015 Vladimir Lysyy (mrbald@github)\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/endian/arithmetic.hpp>\n#include <boost/integer.hpp>\n\n#include <cstdint>\n#include <utility>\n#include <array>\n#include <algorithm>\n\nnamespace z85\n{\n\nusing uchar_t = unsigned char;\n\nnamespace\n{\n\nuchar_t const en_codes[]{\"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.-:+=^!/*?&<>()[]{}@%$#\"};\n\nstd::array<uint8_t, std::numeric_limits<uint8_t>::max() + 1> const de_codes = []\n{\n    std::array<uint8_t, std::numeric_limits<uint8_t>::max() + 1> x{};\n    for (uint8_t i = 0; i < sizeof(en_codes) - 1; ++i)\n    {\n        x[en_codes[i]] = i;\n    }\n    return x;\n}();\n\nconstexpr inline\nuint32_t cpow(uint32_t base, uint8_t exp) noexcept\n{\n    return (exp == 0) ? 1:\n        (exp % 2 == 0) ? \n                cpow(base, exp / 2) * cpow(base, exp / 2):\n                base * cpow(base, (exp - 1) / 2) * cpow(base, (exp - 1) / 2);\n}\n\ntemplate <class X> inline\nconstexpr X sum(X&& x) noexcept { return std::forward<X>(x); }\n\ntemplate <class X, class... Xs> inline\nconstexpr \nstd::enable_if_t<!!sizeof...(Xs), std::common_type_t<X, Xs...>> sum(X&& x, Xs&&... xs) noexcept { return x + sum(std::forward<Xs>(xs)...); }\n\n/* \n * Encoder implementation code:\n *   uint32_t (native byte order) ==> array<uchar,5>\n */\ntemplate <size_t base, size_t N, size_t... Is> inline\nstd::array<uchar_t, sizeof...(Is)> _encode(uint32_t val, std::index_sequence<Is...>) noexcept\n{\n    uint32_t buf{};\n    return { en_codes[buf = (val -= buf * cpow(base, N - Is)) / cpow(base, N - Is - 1)] ... };\n}\n\ntemplate <size_t base, size_t N> inline\nstd::array<uchar_t, N> _encode(uint32_t val) noexcept { return _encode<base, N>(val, std::make_index_sequence<N>()); }\n\n\n/* \n * Decoder implementation code:\n *   array<uchar,5> ==> uint32_t (native byte order)\n */\ntemplate <size_t base, size_t N, size_t... Is> inline\nuint32_t _decode(std::array<uchar_t, N> const& val, std::index_sequence<Is...>) noexcept\n{\n    return sum(de_codes[val[Is]] * cpow(base, N - Is - 1)...);\n}\n\ntemplate <size_t base, size_t N> inline\nuint32_t _decode(std::array<uchar_t, N> const& val) noexcept { return _decode<base, N>(val, std::make_index_sequence<N>()); }\n\nusing boost::endian::big_uint32_t;\n\n} // local namespace\n\nusing cursor_t = std::pair<uchar_t const*, uchar_t*>;\n\ntemplate <size_t base, size_t N> inline\ncursor_t encode(cursor_t locs) noexcept\n{\n    auto encoded = _encode<base, N>((big_uint32_t&)(*locs.first));\n    std::copy_n(encoded.begin(), N, locs.second);\n    return {locs.first + sizeof(big_uint32_t), locs.second + N};\n}\n\ntemplate <size_t base, size_t N> inline\ncursor_t decode(cursor_t locs) noexcept\n{\n    std::array<uchar_t, N> buf;\n    std::copy_n(locs.first, N, buf.begin());\n    ((big_uint32_t&)(*locs.second)) = _decode<base, N>(buf);\n    return {locs.first + N, locs.second + sizeof(big_uint32_t)};\n}\n\n} // namespace z85\n\nusing namespace z85;\n\n#include <random>\n#include <chrono>\n#include <functional>\n\n// g++ -g -Og -std=c++14 -Wall -pedantic -Wno-unused -isystem /path/to/boost/headers z85.cc -o z85\nint main()\n{\n    std::array<uchar_t, 8> const sample {0x86, 0x4F, 0xD2, 0x6F, 0xB5, 0x59, 0xF7, 0x5B};\n    std::array<uchar_t, 10> encoded {};\n    std::array<uchar_t, sample.size()> decoded {};\n\n    cursor_t encoded_locs{sample.data(), encoded.data()};\n    cursor_t decoded_locs{encoded.data(), decoded.data()};\n\n    std::cout << \"source: \";\n    for (auto x : sample)\n        std::cout << std::hex << \"0x\" << ((unsigned)x) << ' ';\n    std::cout << std::endl;\n\n    while (encoded_locs.first < sample.data() + sample.size())\n    {\n        std::cout << \"encoding \" << ((void*)encoded_locs.first) << \"...\\n\";\n        encoded_locs = encode<85, 5>(encoded_locs);\n    }\n\n    std::cout << \"encoded: \";\n    for (auto x : encoded)\n        std::cout << x << '.';\n    std::cout << std::endl;\n\n    while (decoded_locs.first < encoded.data() + encoded.size())\n    {\n        std::cout << \"decoding \" << ((void*)decoded_locs.first) << \"...\\n\";\n        decoded_locs = decode<85, 5>(decoded_locs);\n    }\n\n    std::cout << \"decoded: \";\n    for (auto x : decoded)\n        std::cout << std::hex << \"0x\" << ((unsigned)x) << ' ';\n    std::cout << std::endl;\n\n    {\n        std::random_device rd;\n        std::mt19937 gen(rd());\n        std::uniform_int_distribution<uchar_t> dis;\n        std::array<uchar_t, (4 * 1ul<<10)> samples {};\n        std::array<uchar_t, (5 * 1ul<<10)> encoded {};\n        std::array<uchar_t, (4 * 1ul<<10)> decoded {};\n\n        std::generate_n(samples.begin(), samples.size(), std::bind(dis, std::mt19937(rd())));\n\n        auto const iterations = 20000;\n\n        using clock = std::chrono::steady_clock;\n\n        auto en_code = [&] {\n            cursor_t encoded_locs{samples.data(), encoded.data()};\n            while (encoded_locs.first < samples.data() + samples.size())\n                encoded_locs = encode<85, 5>(encoded_locs);\n        };\n        en_code();\n\n        auto encoder_started = clock::now();\n        for (int i = 0; i < iterations; ++i) en_code();\n        auto encoder_stopped = clock::now();\n\n        auto de_code = [&]{\n            cursor_t decoded_locs{encoded.data(), decoded.data()};\n            while (decoded_locs.first < encoded.data() + encoded.size())\n                decoded_locs = decode<85, 5>(decoded_locs);\n        };\n        de_code();\n\n        auto decoder_started = clock::now();\n        for (int i = 0; i < iterations; ++i) de_code();\n        auto decoder_stopped = clock::now();\n\n        auto encoder_usec = std::chrono::duration_cast<std::chrono::microseconds>(encoder_stopped - encoder_started);\n        auto decoder_usec = std::chrono::duration_cast<std::chrono::microseconds>(decoder_stopped - decoder_started);\n        std::cout << \"encoder: \" << std::dec << encoder_usec.count() << \" us, \" << ((samples.size() * iterations) / encoder_usec.count()) << \" bytes/us \\n\";\n        std::cout << \"decoder: \" << std::dec << decoder_usec.count() << \" us, \" << ((samples.size() * iterations) / decoder_usec.count()) << \" bytes/us \\n\";\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "f044df33ec32aca357e4dff4c414b32319b866c3", "size": 6621, "ext": "cc", "lang": "C++", "max_stars_repo_path": "z85/z85.cc", "max_stars_repo_name": "mrbald/sandbox", "max_stars_repo_head_hexsha": "4eb0b263a94de9dfd0283b47f1594ea7b9161ce8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-09-09T12:52:15.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-29T09:33:04.000Z", "max_issues_repo_path": "z85/z85.cc", "max_issues_repo_name": "mrbald/sandbox", "max_issues_repo_head_hexsha": "4eb0b263a94de9dfd0283b47f1594ea7b9161ce8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "z85/z85.cc", "max_forks_repo_name": "mrbald/sandbox", "max_forks_repo_head_hexsha": "4eb0b263a94de9dfd0283b47f1594ea7b9161ce8", "max_forks_repo_licenses": ["Apache-2.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.6157635468, "max_line_length": 156, "alphanum_fraction": 0.6169762876, "num_tokens": 1868, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.48644001190483266}}
{"text": "#include <cstdlib>\n#include <iostream>\n#include <complex>\n#include <boost/numeric/ublas/io.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 <Eigen/Core>\n#include <boost/numeric/bindings/ublas/vector.hpp>\n#include <boost/numeric/bindings/ublas/matrix.hpp>\n#include <boost/numeric/bindings/ublas/matrix_proxy.hpp>\n#include <boost/numeric/bindings/eigen/vector.hpp>\n#include <boost/numeric/bindings/blas/level1.hpp>\n#include \"random.hpp\"\n\nnamespace ublas=boost::numeric::ublas;\nnamespace blas=boost::numeric::bindings::blas;\n\ntypedef double real;\ntypedef std::complex<real> complex;\n\nint main(int argc, char *argv[]) {\n  {\n    typedef ublas::vector<real> vector;\n    typedef ublas::matrix<real> matrix;\n    typedef vector::size_type size_type;\n    rand_normal<real>::reset();\n    size_type n=8;\n    vector v(n);\n    for (size_type i=0; i<n; ++i)\n      v(i)=rand_normal<real>::get();\n    std::cout << \"ublas using vectors : nrm2(v) = \" << ublas::norm_2(v) << '\\n'\n\t      << \"blas using vectors  : nrm2(v) = \" << blas::nrm2(v) << '\\n';\n    matrix M(n, n);\n    for (size_type j=0; j<n; ++j)\n      for (size_type i=0; i<n; ++i)\n    \tM(i, j)=0;\n    ublas::matrix_column<matrix> mc(M, 2);\n    ublas::matrix_row<matrix> mr(M, 3);\n    mc=v;\n    std::cout << \"blas using cols     : nrm2(v) = \" << blas::nrm2(mc) << '\\n';\n    mr=v;\n    std::cout << \"blas using rows     : nrm2(v) = \" << blas::nrm2(mr) << '\\n';\n  }\n  {\n    typedef ublas::vector<complex> vector;\n    typedef ublas::matrix<complex> matrix;\n    typedef vector::size_type size_type;\n    rand_normal<complex>::reset();\n    size_type n=8;\n    vector v(n);\n    for (size_type i=0; i<n; ++i)\n      v(i)=rand_normal<complex>::get();\n    std::cout << \"ublas using vectors : nrm2(v) = \" << ublas::norm_2(v) << '\\n'\n\t      << \"blas using vectors  : nrm2(v) = \" << blas::nrm2(v) << '\\n';\n    matrix M(n, n);\n    for (size_type j=0; j<n; ++j)\n      for (size_type i=0; i<n; ++i)\n    \tM(i, j)=0;\n    ublas::matrix_column<matrix> mc(M, 2);\n    ublas::matrix_row<matrix> mr(M, 3);\n    mc=v;\n    std::cout << \"blas using cols     : nrm2(v) = \" << blas::nrm2(mc) << '\\n';\n    mr=v;\n    std::cout << \"blas using rows     : nrm2(v) = \" << blas::nrm2(mr) << '\\n';\n  }\n  {\n    typedef Eigen::Matrix<real, Eigen::Dynamic, 1> vector;\n    typedef Eigen::Matrix<real, Eigen::Dynamic, Eigen::Dynamic> matrix;\n    typedef int size_type;\n    rand_normal<real>::reset();\n    size_type n=8;\n    vector v(n);\n    for (size_type i=0; i<n; ++i)\n      v(i)=rand_normal<real>::get();\n    std::cout << \"eigen using vectors : nrm2(v) = \" << v.norm() << '\\n'\n\t      << \"blas using vectors  : nrm2(v) = \" << blas::nrm2(v) << '\\n';\n    matrix M(n, n);\n    for (size_type j=0; j<n; ++j)\n      for (size_type i=0; i<n; ++i)\n    \tM(i, j)=0;\n    auto mc=M.col(2);\n    auto mr=M.row(3);\n    mc=v;\n    std::cout << \"blas using cols     : nrm2(v) = \" << blas::nrm2(mc) << '\\n';\n    mr=v;\n    std::cout << \"blas using rows     : nrm2(v) = \" << blas::nrm2(mr) << '\\n';\n  }\n  {\n    typedef Eigen::Matrix<complex, Eigen::Dynamic, 1> vector;\n    typedef Eigen::Matrix<complex, Eigen::Dynamic, Eigen::Dynamic> matrix;\n    typedef int size_type;\n    rand_normal<complex>::reset();\n    size_type n=8;\n    vector v(n);\n    for (size_type i=0; i<n; ++i)\n      v(i)=rand_normal<complex>::get();\n    std::cout << \"eigen using vectors : nrm2(v) = \" << v.norm() << '\\n'\n\t      << \"blas using vectors  : nrm2(v) = \" << blas::nrm2(v) << '\\n';\n    matrix M(n, n);\n    for (size_type j=0; j<n; ++j)\n      for (size_type i=0; i<n; ++i)\n    \tM(i, j)=0;\n    auto mc=M.col(2);\n    auto mr=M.row(3);\n    mc=v;\n    std::cout << \"blas using cols     : nrm2(v) = \" << blas::nrm2(mc) << '\\n';\n    mr=v;\n    std::cout << \"blas using rows     : nrm2(v) = \" << blas::nrm2(mr) << '\\n';\n  }\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "9269487fb980ffdb4f9a65bc4d60718d529ab0fa", "size": 3886, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/blas/nrm2.cc", "max_stars_repo_name": "rabauke/numeric_bindings", "max_stars_repo_head_hexsha": "f4de93bd7a01a8b31c9367fad35c81d086768f99", "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/blas/nrm2.cc", "max_issues_repo_name": "rabauke/numeric_bindings", "max_issues_repo_head_hexsha": "f4de93bd7a01a8b31c9367fad35c81d086768f99", "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/blas/nrm2.cc", "max_forks_repo_name": "rabauke/numeric_bindings", "max_forks_repo_head_hexsha": "f4de93bd7a01a8b31c9367fad35c81d086768f99", "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.389380531, "max_line_length": 79, "alphanum_fraction": 0.5728255275, "num_tokens": 1302, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.48644000640984236}}
{"text": "#pragma once\n\n#include <polyfem/Common.hpp>\n\n#include <polyfem/ElementAssemblyValues.hpp>\n#include <polyfem/ElementBases.hpp>\n\n#include <polyfem/AutodiffTypes.hpp>\n\n#include <Eigen/Dense>\n#include <functional>\n\n\nnamespace polyfem\n{\n\tclass IncompressibleLinearElasticityDispacement\n\t{\n\tpublic:\n\t\t// res is R^{dim\u00b2}\n\t\tEigen::Matrix<double, Eigen::Dynamic, 1, 0, 9, 1>\n\t\tassemble(const ElementAssemblyValues &vals, const int i, const int j, 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\tvoid set_size(const int size);\n\t\tinline int size() const { return size_; }\n\n\t\tinline double &mu() { return mu_; }\n\t\tinline double mu() const { return mu_; }\n\n\t\tinline double &lambda() { return lambda_; }\n\t\tinline double lambda() const { return lambda_; }\n\n\t\tvoid set_parameters(const json &params);\n\n\t\tvoid compute_von_mises_stresses(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 ElementBases &bs, const ElementBases &gbs, const Eigen::MatrixXd &local_pts, const Eigen::MatrixXd &displacement, Eigen::MatrixXd &tensor) const;\n\tprivate:\n\t\tint size_ = -1;\n\t\tdouble mu_ = 1;\n\t\tdouble lambda_ = 1;\n\n\t\tvoid assign_stress_tensor(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\n\tclass IncompressibleLinearElasticityMixed\n\t{\n\tpublic:\n\t\t// res is R^{dim}\n\t\tEigen::Matrix<double, Eigen::Dynamic, 1, 0, 3, 1>\n\t\tassemble(const ElementAssemblyValues &psi_vals, const ElementAssemblyValues &phi_vals, const int i, const int j, 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\tvoid set_size(const int size);\n\n\t\tinline double &mu() { return mu_; }\n\t\tinline double mu() const { return mu_; }\n\n\t\tinline double &lambda() { return lambda_; }\n\t\tinline double lambda() const { return lambda_; }\n\n\t\tinline int rows() const { return size_; }\n\t\tinline int cols() const { return 1; }\n\n\t\tvoid set_parameters(const json &params);\n\tprivate:\n\t\tint size_ = -1;\n\t\tdouble mu_ = 1;\n\t\tdouble lambda_ = 1;\n\t};\n\n\n\tclass IncompressibleLinearElasticityPressure\n\t{\n\tpublic:\n\t\t// res is R^{1}\n\t\tEigen::Matrix<double, 1, 1>\n\t\tassemble(const ElementAssemblyValues &vals, const int i, const int j, const QuadratureVector &da) const;\n\n\t\tEigen::Matrix<double, 1, 1>\n\t\tcompute_rhs(const AutodiffHessianPt &pt) const\n\t\t{\n\t\t\tassert(false);\n\t\t\treturn Eigen::Matrix<double, 1, 1>::Zero(1,1);\n\t\t}\n\n\t\tinline int size() const { return 1; }\n\n\t\tvoid set_parameters(const json &params);\n\n\t\t\t\tinline double &mu() { return mu_; }\n\t\tinline double mu() const { return mu_; }\n\n\t\tinline double &lambda() { return lambda_; }\n\t\tinline double lambda() const { return lambda_; }\n\n\tprivate:\n\t\tdouble mu_ = 1;\n\t\tdouble lambda_ = 1;\n\t};\n}\n", "meta": {"hexsha": "82de727952e2ff2b947c9f22aad468932c9030f6", "size": 3077, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/assembler/IncompressibleLinElast.hpp", "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/IncompressibleLinElast.hpp", "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/IncompressibleLinElast.hpp", "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": 29.3047619048, "max_line_length": 264, "alphanum_fraction": 0.7146571336, "num_tokens": 876, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.48644000640984236}}
{"text": "#include <skelly_sim.hpp>\n\n#include \"cnpy.hpp\"\n#include <Eigen/Core>\n#include <fstream>\n#include <iostream>\n#include <mpi.h>\n#include <parse_util.hpp>\n#include <system.hpp>\n\n#ifdef NDEBUG\n#undef NDEBUG\n#include <cassert>\n#define NDEBUG\n#else\n#include <cassert>\n#endif\n\n#include <body.hpp>\n#include <fiber.hpp>\n\nusing Eigen::Map;\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\n\ntemplate <typename DerivedA, typename DerivedB>\nbool allclose(\n    const Eigen::DenseBase<DerivedA> &a, const Eigen::DenseBase<DerivedB> &b,\n    const typename DerivedA::RealScalar &rtol = Eigen::NumTraits<typename DerivedA::RealScalar>::dummy_precision(),\n    const typename DerivedA::RealScalar &atol = Eigen::NumTraits<typename DerivedA::RealScalar>::epsilon()) {\n    return ((a.derived() - b.derived()).array().abs() <= (atol + rtol * b.derived().array().abs())).all();\n}\n\nint main(int argc, char *argv[]) {\n    int thread_level;\n    MPI_Init_thread(&argc, &argv, MPI_THREAD_FUNNELED, &thread_level);    \n    std::string config_file(\"test_link_matrix.toml\");\n    System::init(config_file);\n    FiberContainer &fc = *System::get_fiber_container();\n    toml::value &param_table = *System::get_param_table();\n\n    toml::table special = param_table[\"special\"].as_table();\n    VectorXd fibers_xt = parse_util::convert_array(special.at(\"fibers_xt\").as_array());\n    VectorXd body_velocities_flat = parse_util::convert_array(special.at(\"body_velocities\").as_array());\n    VectorXd force_torque_ref = parse_util::convert_array(special.at(\"force_torque\").as_array());\n    VectorXd velocities_on_fiber_ref = parse_util::convert_array(special.at(\"fiber_velocities\").as_array());\n    MatrixXd body_velocities = Map<MatrixXd>(body_velocities_flat.data(), 6, body_velocities_flat.size() / 6);\n\n    fc.update_derivatives();\n\n    MatrixXd force_torque, velocities_on_fiber;\n    std::tie(force_torque, velocities_on_fiber) =\n        System::calculate_body_fiber_link_conditions(fibers_xt, body_velocities);\n\n    assert(allclose(force_torque, force_torque_ref, 1E-7));\n    assert(allclose(velocities_on_fiber, velocities_on_fiber_ref));\n    MPI_Finalize();\n\n    std::cout << \"Test passed\\n\";\n    return 0;\n}\n", "meta": {"hexsha": "07ad4aa5a765aef24bda28d48a562d37c3df5f9d", "size": 2170, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_link_matrix.cpp", "max_stars_repo_name": "lu1and10/SkellySim", "max_stars_repo_head_hexsha": "6d319f2d1c1c85506d7debedc082747d89995045", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/test_link_matrix.cpp", "max_issues_repo_name": "lu1and10/SkellySim", "max_issues_repo_head_hexsha": "6d319f2d1c1c85506d7debedc082747d89995045", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/test_link_matrix.cpp", "max_forks_repo_name": "lu1and10/SkellySim", "max_forks_repo_head_hexsha": "6d319f2d1c1c85506d7debedc082747d89995045", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.0, "max_line_length": 115, "alphanum_fraction": 0.7299539171, "num_tokens": 549, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.48636267532634514}}
{"text": "/*\n * This file is part of the DUDS project. It is subject to the BSD-style\n * license terms in the LICENSE file found in the top-level directory of this\n * distribution and at https://github.com/jjackowski/duds/blob/master/LICENSE.\n * No part of DUDS, including this file, may be copied, modified, propagated,\n * or distributed except according to the terms contained in the LICENSE file.\n *\n * Copyright (C) 2017  Jeff Jackowski\n */\n#include <duds/hardware/devices/instruments/LSM9DS1.hpp>\n#include <duds/hardware/interface/linux/DevI2c.hpp>\n#include <iostream>\n#include <thread>\n#include <iomanip>\n#include <cmath>\n#include <boost/exception/diagnostic_information.hpp>\n#include <Eigen/Geometry>\n\nbool quit = false;\n\nvoid makeHorizontal(\n\tEigen::Vector3f &res,\n\tconst Eigen::Vector3f &grav,\n\tconst Eigen::Vector3f &mod,\n\tfloat &angle\n) {\n\tstatic const Eigen::Vector3f z(0, 0, 1);\n\tEigen::Vector3f g(grav.normalized());\n\tangle = std::acos(g.dot(z));\n\tEigen::Vector3f axis = g.cross(z);\n\t/*float*/ //angle = std::asin(axis.norm());\n\taxis.normalize();\n\tEigen::Quaternion<float> q(Eigen::AngleAxisf(angle, axis));\n\tres = q * mod;\n}\n\nfloat heading(const Eigen::Vector3f &dir) {\n\t/*\n\tstatic const Eigen::Vector3f fwd(1, 0, 0);\n\tEigen::Vector3f d(dir(0), dir(1), 0);\n\td.normalize();\n\tEigen::Vector3f a = d.cross(fwd);\n\treturn std::asin(a.norm());\n\t*/\n\tfloat h = std::atan2(dir(2), dir(0));\n\tif (h < 0) {\n\t\th += 2 * M_PI;\n\t}\n\treturn h;\n}\n\nvoid runtest(duds::hardware::devices::instruments::LSM9DS1 &acclgyromag)\ntry {\n\tstatic const Eigen::Vector3f z(0, 0, 1);\n\tduds::hardware::devices::instruments::LSM9DS1::RawSample rsA, rsM;\n\tacclgyromag.start();\n\tstd::cout.precision(1);\n\tstd::cout << std::fixed;\n\t// doesn't account for time spent in loop\n\tstd::chrono::milliseconds delay = std::chrono::milliseconds(\n\t\t(int)(1000.0f / /*acclgyromag.sampleRate()*/ 2.5f)\n\t);\n\tstd::this_thread::sleep_for(delay);\n\tdo {\n\t\twhile (!acclgyromag.sample() && !quit) {\n\t\t\tstd::this_thread::sleep_for(std::chrono::milliseconds(8));\n\t\t}\n\t\trsA = acclgyromag.rawAccelerometer();\n\t\trsM = acclgyromag.rawMagnetometer();\n\t\tEigen::Vector3f m(rsM.x, rsM.y, rsM.z);\n\t\tEigen::Vector3f g(rsA.x, rsA.y, rsA.z);\n\t\tEigen::Vector3f mT;\n\t\tstd::cout << \"A: \" << std::setw(8) << g.norm() << ' ' <<\n\t\tstd::setw(6) << rsA.x << \", \" <<\n\t\tstd::setw(6) << rsA.y << \", \" << std::setw(6) << rsA.z;\n\t\tfloat th;\n\t\tmakeHorizontal(mT, g, m, th);\n\t\tfloat head = heading(/*mT*/ m);\n\t\tstd::cout << \" th \" << std::setw(5) << (th * 180.0f / M_PI);\n\t\t// magnetometer vector modified to have X-Y plane perpindicular to the\n\t\t// gravity vector\n\t\tstd::cout << \"   M: \" << std::setw(7) << mT.norm() << ' ' <<\n\t\tstd::setw(7) << mT(0) << \", \" << std::setw(7) << mT(1) << \", \" <<\n\t\tstd::setw(7) << mT(2) << \"  h: \" << std::setw(5) <<\n\t\t(head * 180.0f / M_PI) << \" \\r\";// std::endl;\n\t\t/* unmodified magnetometer vector\n\t\tstd::cout << \"   Mag: \" << std::setw(7) << m.norm() << ' ' <<\n\t\tstd::setw(5) << rsM.x << \", \" <<\n\t\tstd::setw(5) << rsM.y << \", \" << std::setw(5) << rsM.z << \" \\r\";// std::endl;\n\t\t*/\n\t\tstd::cout.flush();\n\t\tstd::this_thread::sleep_for(delay);\n\t} while (!quit);\n} catch (...) {\n\tstd::cerr << \"Program failed in runtest(): \" <<\n\tboost::current_exception_diagnostic_information() << std::endl;\n}\n\nconst duds::hardware::devices::instruments::LSM9DS1::Settings config = {\n\t/* .accelerometer = */ 1,\n\t/* .gyroscope = */ 0,\n\t/* .magnetometer = */ 1,\n\t/* .accelRange = */ duds::hardware::devices::instruments::LSM9DS1::AccelRange2g,\n\t/* .gyroRange = */ duds::hardware::devices::instruments::LSM9DS1::GyroRange4p276rps,\n\t/* .magRange = */ duds::hardware::devices::instruments::LSM9DS1::MagRange400uT,\n\t/* .gyroLowPower = */ 1,\n\t/* .gyroHighPass = */ 0,\n\t/* .magLowPower = */ 0,\n\t/* .xyMagMode = */ duds::hardware::devices::instruments::LSM9DS1::AxesHighPerformance,\n\t/* .zMagMode = */ duds::hardware::devices::instruments::LSM9DS1::AxesHighPerformance,\n\t/* .magTempComp = */ 0\n};\n\nint main(int argc, char *argv[])\ntry {\n\t{ // vector math tests\n\t\tEigen::Vector3f res;\n\t\tEigen::Vector3f grav(1.0f, 0, 9.0f);\n\t\tEigen::Vector3f mod(1.0f, 1.0f, 9.0f);\n\t\tfloat angle;\n\t\tstd::cout << \"Vector rotation tests\" << std::endl;\n\t\tmakeHorizontal(res, grav, grav, angle);\n\t\tres.normalize();\n\t\tstd::cout << \"Test 1 result: \" << res(0) << \", \" << res(1) << \", \" <<\n\t\tres(2) << \"  angle: \" << (angle * 180.0f / M_PI) << \"  heading: \" <<\n\t\t(heading(res) * 180.0f / M_PI) << std::endl;\n\t\tmakeHorizontal(res, grav, mod, angle);\n\t\tres.normalize();\n\t\tstd::cout << \"Test 2 result: \" << res(0) << \", \" << res(1) << \", \" <<\n\t\tres(2) << \"  angle: \" << (angle * 180.0f / M_PI) << \"  heading: \" <<\n\t\t(heading(res) * 180.0f / M_PI) << std::endl;\n\t}\n\tstd::unique_ptr<duds::hardware::interface::I2c> magI2c(\n\t\tnew duds::hardware::interface::linux::DevI2c(\n\t\t\targc > 1 ? argv[1] : \"/dev/i2c-1\",\n\t\t\t0x1E\n\t\t)\n\t);\n\tstd::unique_ptr<duds::hardware::interface::I2c> accelI2c(\n\t\tnew duds::hardware::interface::linux::DevI2c(\n\t\t\targc > 1 ? argv[1] : \"/dev/i2c-1\",\n\t\t\t0x6B\n\t\t)\n\t);\n\tduds::hardware::devices::instruments::LSM9DS1 acclgyromag(accelI2c, magI2c);\n\tacclgyromag.configure(2.0f, 2.0f, config);\n\tstd::cout.precision(4);\n\t//std::cout << \"Sampling frequency reported as \" << acclgyromag.sampleRate() <<\n\t//\"Hz\" << std::endl;\n\tstd::thread doit(runtest, std::ref(acclgyromag));\n\tstd::cin.get();\n\tquit = true;\n\tdoit.join();\n\tstd::cout << std::endl;\n\treturn 0;\n} catch (...) {\n\tstd::cerr << \"Program failed in main(): \" <<\n\tboost::current_exception_diagnostic_information() << std::endl;\n\treturn 1;\n}\n", "meta": {"hexsha": "5286d54632bf4ca14065ca5b4917c0d60336a256", "size": 5501, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "samples/orientation-LSM9DS1.cpp", "max_stars_repo_name": "jjackowski/duds", "max_stars_repo_head_hexsha": "0fc4eec0face95c13575672f2a2d8625517c9469", "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": "samples/orientation-LSM9DS1.cpp", "max_issues_repo_name": "jjackowski/duds", "max_issues_repo_head_hexsha": "0fc4eec0face95c13575672f2a2d8625517c9469", "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": "samples/orientation-LSM9DS1.cpp", "max_forks_repo_name": "jjackowski/duds", "max_forks_repo_head_hexsha": "0fc4eec0face95c13575672f2a2d8625517c9469", "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.1677018634, "max_line_length": 87, "alphanum_fraction": 0.6246137066, "num_tokens": 1905, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.4863626753263451}}
{"text": "//####### Test module for Breit Wheeler engine (SI units) ######################\n\n//Define Module name\n #define BOOST_TEST_MODULE \"Nonliner Breit Wheeler engine (SI)\"\n\n//Will automatically define a main for this test\n #define BOOST_TEST_DYN_LINK\n\n #include <memory>\n\n//Include Boost unit tests library\n#include <boost/test/unit_test.hpp>\n\n//SI units are used for this test\n#define PXRMP_USE_SI_UNITS\n#include \"breit_wheeler_engine.hpp\"\n\n#include \"rng_wrapper.hpp\"\n\nusing namespace picsar::multi_physics;\n\n//Helper function\ntemplate<typename REAL>\nbreit_wheeler_engine<REAL, stl_rng_wrapper<REAL>> get_bw_stl_set_lambda(uint64_t seed,\nbreit_wheeler_engine_ctrl<REAL> bw_ctrl = breit_wheeler_engine_ctrl<REAL>())\n{\n    stl_rng_wrapper<REAL> wrap{seed};\n    auto bw_engine =  breit_wheeler_engine<REAL, stl_rng_wrapper<REAL>>\n        {std::move(wrap), 1.0, bw_ctrl};\n    return bw_engine;\n}\n\n// ------------- Tests --------------\n\n//Tolerance for double precision calculations\nconst double double_tolerance = 1.0e-3;\n\n//Tolerance for single precision calculations\nconst float float_tolerance = 1.0e-2;\n\n//Templated tolerance\ntemplate <typename T>\nT tolerance()\n{\n    if(std::is_same<T,float>::value)\n        return float_tolerance;\n    else\n        return double_tolerance;\n}\n\n//Special tolerance for a specific case (check carefully)\n\n//Special Tolerance for double precision calculations\nconst double double_spec_tolerance = 2.0e-2;\n\n//Special Tolerance for single precision calculations\nconst float float_spec_tolerance = 2.0e-2;\n\n//Special Templated tolerance\ntemplate <typename T>\nT spec_tolerance()\n{\n    if(std::is_same<T,float>::value)\n        return float_spec_tolerance;\n    else\n        return double_spec_tolerance;\n}\n\n//***SI UNITS***\n//SI units for momenta\nconst double me_c = electron_mass * light_speed;\n//SI units for fields\ndouble lambda = 800.0 * si_nanometer;\ndouble eref = 2.0*pi*electron_mass*light_speed*light_speed/\n            (lambda*elementary_charge);\ndouble bref = eref/light_speed;\n//SI units for dt and rate\ndouble dtref = lambda/(2.0*pi*light_speed);\ndouble rateref = 1.0/dtref;\n\n//Test get/set lambda for breit_wheeler_engine generic\ntemplate <typename T>\nvoid breit_wheeler_engine_gs()\n{\n    auto bw_engine = get_bw_stl_set_lambda<T>(390109317);\n    BOOST_CHECK_EQUAL( static_cast<T>(1.0), bw_engine.get_lambda());\n}\n\n//Test get/set lambda for breit_wheeler_engine (double precision)\nBOOST_AUTO_TEST_CASE( breit_wheeler_engine_gs_double_1 )\n{\n    breit_wheeler_engine_gs<double>();\n}\n\n//Test get/set lambda for breit_wheeler_engine (single precision)\nBOOST_AUTO_TEST_CASE( breit_wheeler_engine_gs_single_1 )\n{\n    breit_wheeler_engine_gs<float>();\n}\n\n// ------------- optical depth --------------\n//Test get/set lambda for breit_wheeler_engine generic\ntemplate <typename T>\nvoid breit_wheeler_engine_opt()\n{\n    auto bw_engine = get_bw_stl_set_lambda<T>(390109317);\n    BOOST_TEST ( bw_engine.get_optical_depth() >= static_cast<T>(0.0) );\n}\n\n//Test get new optical depth (double precision)\nBOOST_AUTO_TEST_CASE( breit_wheeler_engine_opt_double_1 )\n{\n    breit_wheeler_engine_opt<double>();\n}\n\n//Test get new optical depth (single precision)\nBOOST_AUTO_TEST_CASE( breit_wheeler_engine_opt_single_1 )\n{\n    breit_wheeler_engine_opt<float>();\n}\n\n// ------------- Pair production rates --------------\n\n//Test pair production rates (generic)\ntemplate <typename T>\nvoid breit_wheeler_engine_prod_1()\n{\n    auto bw_engine = get_bw_stl_set_lambda<T>(390109317);\n\n    T px =  static_cast<T>(0.0*me_c);\n    T py =  static_cast<T>(0.0*me_c);\n    T pz =  static_cast<T>(0.0*me_c);\n    T ex =  static_cast<T>(931.686*eref);\n    T ey =  static_cast<T>(-861.074*eref);\n    T ez =  static_cast<T>(944.652*eref);\n    T bx =  static_cast<T>(531.406*bref);\n    T by =  static_cast<T>(670.933*bref);\n    T bz =  static_cast<T>(660.057*bref);\n\n    //T exp = static_cast<T>(0.0*rateref);\n    T res = bw_engine.compute_dN_dt(norm(vec3<T>{px,py,pz})*light_speed, chi_photon(px,py,pz,ex,ey,ez,bx,by,bz) );\n\n    BOOST_CHECK_SMALL(res, tolerance<T>());\n}\n\n\n//Test pair production rates (double precision)\nBOOST_AUTO_TEST_CASE( breit_wheeler_engine_prod_double_1 )\n{\n    breit_wheeler_engine_prod_1<double>();\n}\n\n//Test pair production rates (single precision)\nBOOST_AUTO_TEST_CASE( breit_wheeler_engine_prod_single_1 )\n{\n    breit_wheeler_engine_prod_1<float>();\n}\n\n//Test pair production rates (generic)\ntemplate <typename T>\nvoid breit_wheeler_engine_prod_2()\n{\n    auto bw_engine = get_bw_stl_set_lambda<T>(390109317);\n\n    T px =  static_cast<T>(149.825*me_c);\n    T py =  static_cast<T>(0.0*me_c);\n    T pz =  static_cast<T>(0.0*me_c);\n    T ex =  static_cast<T>(931.686*eref);\n    T ey =  static_cast<T>(0.0*eref);\n    T ez =  static_cast<T>(0.0*eref);\n    T bx =  static_cast<T>(0.0*bref);\n    T by =  static_cast<T>(0.0*bref);\n    T bz =  static_cast<T>(0.0*bref);\n\n    //T exp = static_cast<T>(0.0*rateref);\n    T res = bw_engine.compute_dN_dt(norm(vec3<T>{px,py,pz})*light_speed, chi_photon(px,py,pz,ex,ey,ez,bx,by,bz) );\n\n    BOOST_CHECK_SMALL(res, tolerance<T>());\n}\n\n//Test pair production rates (double precision)\nBOOST_AUTO_TEST_CASE( breit_wheeler_engine_prod_double_2 )\n{\n    breit_wheeler_engine_prod_2<double>();\n}\n\n//Test pair production rates (single precision)\nBOOST_AUTO_TEST_CASE( breit_wheeler_engine_prod_single_2 )\n{\n    breit_wheeler_engine_prod_2<float>();\n}\n\ntemplate <typename T>\nvoid breit_wheeler_engine_prod_3()\n{\n    auto bw_engine = get_bw_stl_set_lambda<T>(390109317);\n\n    T px =  static_cast<T>(6.81696*me_c);\n    T py =  static_cast<T>(9.68933*me_c);\n    T pz =  static_cast<T>(2.81229*me_c);\n    T ex =  static_cast<T>(-4.89986*eref);\n    T ey =  static_cast<T>(-9.65535*eref);\n    T ez =  static_cast<T>(3.69471*eref);\n    T bx =  static_cast<T>(8.89549*bref);\n    T by =  static_cast<T>(-5.46574*bref);\n    T bz =  static_cast<T>(-6.75393*bref);\n\n    //T exp = static_cast<T>(0.0*rateref);\n    T res = bw_engine.compute_dN_dt(norm(vec3<T>{px,py,pz})*light_speed, chi_photon(px,py,pz,ex,ey,ez,bx,by,bz) );\n\n    BOOST_CHECK_SMALL(res, tolerance<T>());\n}\n\n\n//Test pair production rates (double precision)\nBOOST_AUTO_TEST_CASE( breit_wheeler_engine_prod_double_3 )\n{\n    breit_wheeler_engine_prod_3<double>();\n}\n\n//Test pair production rates (single precision)\nBOOST_AUTO_TEST_CASE( breit_wheeler_engine_prod_single_3 )\n{\n    breit_wheeler_engine_prod_3<float>();\n}\n\n//Test pair production rates (generic)\ntemplate <typename T>\nvoid breit_wheeler_engine_prod_4()\n{\n    auto bw_engine = get_bw_stl_set_lambda<T>(390109317);\n\n    T px =  static_cast<T>(149.825*me_c);\n    T py =  static_cast<T>(933.115*me_c);\n    T pz =  static_cast<T>(-538.195*me_c);\n    T ex =  static_cast<T>(931.686*eref);\n    T ey =  static_cast<T>(-861.074*eref);\n    T ez =  static_cast<T>(944.652*eref);\n    T bx =  static_cast<T>(531.406*bref);\n    T by =  static_cast<T>(670.933*bref);\n    T bz =  static_cast<T>(660.057*bref);\n\n    T exp = static_cast<T>(1.50648551484*rateref);\n    T res = bw_engine.compute_dN_dt(norm(vec3<T>{px,py,pz})*light_speed, chi_photon(px,py,pz,ex,ey,ez,bx,by,bz) );\n\n    BOOST_CHECK_SMALL((exp-res)/exp, tolerance<T>());\n}\n\n\n//Test pair production rates (double precision)\nBOOST_AUTO_TEST_CASE( breit_wheeler_engine_prod_double_4 )\n{\n    breit_wheeler_engine_prod_4<double>();\n}\n\n//Test pair production rates (single precision)\nBOOST_AUTO_TEST_CASE( breit_wheeler_engine_prod_single_4 )\n{\n    breit_wheeler_engine_prod_4<float>();\n}\n\n\n\n//Test pair production rates (generic)\ntemplate <typename T>\nvoid breit_wheeler_engine_prod_5()\n{\n    auto bw_engine = get_bw_stl_set_lambda<T>(390109317);\n\n    T px =  static_cast<T>(-44.4546*me_c);\n    T py =  static_cast<T>(-0.2033*me_c);\n    T pz =  static_cast<T>(94.5843*me_c);\n    T ex =  static_cast<T>(39.8996*eref);\n    T ey =  static_cast<T>(-29.2501*eref);\n    T ez =  static_cast<T>(58.7720*eref);\n    T bx =  static_cast<T>(44.3417*bref);\n    T by =  static_cast<T>(15.5024*bref);\n    T bz =  static_cast<T>(29.4024*bref);\n\n    //T exp = static_cast<T>(4.69766211952e-73*rateref);\n    T res = bw_engine.compute_dN_dt(norm(vec3<T>{px,py,pz})*light_speed, chi_photon(px,py,pz,ex,ey,ez,bx,by,bz) );\n\n    BOOST_CHECK_SMALL(res, tolerance<T>());\n}\n\n\n//Test pair production rates (double precision)\nBOOST_AUTO_TEST_CASE( breit_wheeler_engine_prod_double_5 )\n{\n    breit_wheeler_engine_prod_5<double>();\n}\n\n//Test pair production rates (single precision)\nBOOST_AUTO_TEST_CASE( breit_wheeler_engine_prod_single_5 )\n{\n    breit_wheeler_engine_prod_5<float>();\n}\n\n//Test pair production rates (generic)\ntemplate <typename T>\nvoid breit_wheeler_engine_prod_6()\n{\n    auto bw_engine = get_bw_stl_set_lambda<T>(390109317);\n\n    T px =  static_cast<T>(-965.61*me_c);\n    T py =  static_cast<T>(-3975.11*me_c);\n    T pz =  static_cast<T>(6917.22*me_c);\n    T ex =  static_cast<T>(11.17*eref);\n    T ey =  static_cast<T>(-2117.72*eref);\n    T ez =  static_cast<T>(-1407.19*eref);\n    T bx =  static_cast<T>( 6259.79*bref);\n    T by =  static_cast<T>(7557.54*bref);\n    T bz =  static_cast<T>(773.11*bref);\n\n    T exp = static_cast<T>(3.51855878777*rateref);\n    T res = bw_engine.compute_dN_dt(norm(vec3<T>{px,py,pz})*light_speed, chi_photon(px,py,pz,ex,ey,ez,bx,by,bz) );\n\n    BOOST_CHECK_SMALL((exp-res)/exp, tolerance<T>());\n}\n\n//Test pair production rates (double precision)\nBOOST_AUTO_TEST_CASE( breit_wheeler_engine_prod_double_6 )\n{\n    breit_wheeler_engine_prod_6<double>();\n}\n\n//Test pair production rates (single precision)\nBOOST_AUTO_TEST_CASE( breit_wheeler_engine_prod_single_6 )\n{\n    breit_wheeler_engine_prod_6<float>();\n}\n\n\n//Test pair production rates (generic)\ntemplate <typename T>\nvoid breit_wheeler_engine_prod_7()\n{\n    auto bw_engine = get_bw_stl_set_lambda<T>(390109317);\n\n    T px =  static_cast<T>(61019.1*me_c);\n    T py =  static_cast<T>(-24359.3*me_c);\n    T pz =  static_cast<T>(65116.2*me_c);\n    T ex =  static_cast<T>(69942.0*eref);\n    T ey =  static_cast<T>(38024.7*eref);\n    T ez =  static_cast<T>(-43604.1*eref);\n    T bx =  static_cast<T>(-26990.0*bref);\n    T by =  static_cast<T>(58267.8*bref);\n    T bz =  static_cast<T>(-63485.8*bref);\n\n    T exp = static_cast<T>(7.63488202211*rateref);\n    T res = bw_engine.compute_dN_dt(norm(vec3<T>{px,py,pz})*light_speed, chi_photon(px,py,pz,ex,ey,ez,bx,by,bz) );\n\n    BOOST_CHECK_SMALL((exp-res)/exp, spec_tolerance<T>());\n}\n\n//Test pair production rates (double precision)\nBOOST_AUTO_TEST_CASE( breit_wheeler_engine_prod_double_7 )\n{\n    breit_wheeler_engine_prod_7<double>();\n}\n\n//Test pair production rates (single precision)\nBOOST_AUTO_TEST_CASE( breit_wheeler_engine_prod_single_7 )\n{\n    breit_wheeler_engine_prod_7<float>();\n}\n\n//Test evolve_opt_depth_and_determine_event (generic)\ntemplate <typename T>\nvoid breit_wheeler_engine_detopt_1()\n{\n    auto bw_engine = get_bw_stl_set_lambda<T>(390109317);\n\n    T px =  static_cast<T>(149.825*me_c);\n    T py =  static_cast<T>(933.115*me_c);\n    T pz =  static_cast<T>(-538.195*me_c);\n    T ex =  static_cast<T>(931.686*eref);\n    T ey =  static_cast<T>(-861.074*eref);\n    T ez =  static_cast<T>(944.652*eref);\n    T bx =  static_cast<T>(531.406*bref);\n    T by =  static_cast<T>(670.933*bref);\n    T bz =  static_cast<T>(660.057*bref);\n\n    T initial_optical_depth = static_cast<T>(1.0);\n    T optical_depth = initial_optical_depth;\n    T dt = static_cast<T>(0.01*dtref);\n\n    T exp_rate = static_cast<T>(1.50648551484*rateref);\n\n    bool has_event_happend;\n    T dt_prod;\n\n    bw_engine.compute_dN_dt_lookup_table(nullptr);\n\n    std::tie(has_event_happend, dt_prod) =\n        bw_engine.evolve_opt_depth_and_determine_event\n        (px, py, pz, ex, ey, ez, bx, by, bz, dt, optical_depth);\n\n    T exp_opt_depth = initial_optical_depth - dt*exp_rate;\n\n    BOOST_CHECK_EQUAL(has_event_happend, false);\n    BOOST_CHECK_EQUAL(dt_prod, static_cast<T>(0.0));\n    BOOST_CHECK_SMALL((optical_depth-exp_opt_depth)/exp_opt_depth,\n        tolerance<T>());\n}\n\n\n//Test evolve_opt_depth_and_determine_event (double precision)\nBOOST_AUTO_TEST_CASE( breit_wheeler_engine_detopt_double_1 )\n{\n    breit_wheeler_engine_detopt_1<double>();\n}\n\n//Test evolve_opt_depth_and_determine_event (single precision)\nBOOST_AUTO_TEST_CASE( breit_wheeler_engine_detopt_single_1 )\n{\n    breit_wheeler_engine_detopt_1<float>();\n}\n\n\n//Test evolve_opt_depth_and_determine_event (generic)\ntemplate <typename T>\nvoid breit_wheeler_engine_detopt_2()\n{\n    auto bw_engine = get_bw_stl_set_lambda<T>(390109317);\n\n    T px =  static_cast<T>(149.825*me_c);\n    T py =  static_cast<T>(933.115*me_c);\n    T pz =  static_cast<T>(-538.195*me_c);\n    T ex =  static_cast<T>(931.686*eref);\n    T ey =  static_cast<T>(-861.074*eref);\n    T ez =  static_cast<T>(944.652*eref);\n    T bx =  static_cast<T>(531.406*bref);\n    T by =  static_cast<T>(670.933*bref);\n    T bz =  static_cast<T>(660.057*bref);\n\n    T initial_optical_depth = static_cast<T>(1.0e-3);\n    T optical_depth = initial_optical_depth;\n    T dt = static_cast<T>(0.01*dtref);\n\n    T exp_rate = static_cast<T>(1.50648551484*rateref);\n\n    bool has_event_happend;\n    T dt_prod;\n\n    bw_engine.compute_dN_dt_lookup_table(nullptr);\n\n    std::tie(has_event_happend, dt_prod) =\n        bw_engine.evolve_opt_depth_and_determine_event\n        (px, py, pz, ex, ey, ez, bx, by, bz, dt, optical_depth);\n\n    T exp_opt_depth = initial_optical_depth - dt*exp_rate;\n    T exp_dt_prod = initial_optical_depth/exp_rate ;\n\n    BOOST_CHECK_EQUAL(has_event_happend, true);\n    BOOST_CHECK_SMALL(exp_dt_prod, dt_prod);\n    BOOST_CHECK_SMALL((optical_depth-exp_opt_depth)/exp_opt_depth,\n        tolerance<T>());\n}\n\n\n//Test evolve_opt_depth_and_determine_event (double precision)\nBOOST_AUTO_TEST_CASE( breit_wheeler_engine_detopt_double_2 )\n{\n    breit_wheeler_engine_detopt_2<double>();\n}\n\n//Test evolve_opt_depth_and_determine_event (single precision)\nBOOST_AUTO_TEST_CASE( breit_wheeler_engine_detopt_single_2 )\n{\n    breit_wheeler_engine_detopt_2<float>();\n}\n\n//Test evolve_opt_depth_and_determine_event (generic)\ntemplate <typename T>\nvoid breit_wheeler_engine_detopt_3()\n{\n    breit_wheeler_engine_ctrl<T> bw_ctrl;\n    bw_ctrl.chi_phot_min =  static_cast<T>(0.0001);\n\n    auto bw_engine = get_bw_stl_set_lambda<T>(390109317, bw_ctrl);\n\n    T px =  static_cast<T>(149.825*me_c);\n    T py =  static_cast<T>(933.115*me_c);\n    T pz =  static_cast<T>(-538.195*me_c);\n    T ex =  static_cast<T>(931.686*eref);\n    T ey =  static_cast<T>(-861.074*eref);\n    T ez =  static_cast<T>(944.652*eref);\n    T bx =  static_cast<T>(531.406*bref);\n    T by =  static_cast<T>(670.933*bref);\n    T bz =  static_cast<T>(660.057*bref);\n\n    T initial_optical_depth = static_cast<T>(1.0e-3);\n    T optical_depth = initial_optical_depth;\n    T dt = static_cast<T>(0.01*dtref);\n\n    T exp_rate = static_cast<T>(1.50648551484*rateref);\n\n    bool has_event_happend;\n    T dt_prod;\n\n    bw_engine.compute_dN_dt_lookup_table(nullptr);\n\n    std::tie(has_event_happend, dt_prod) =\n    bw_engine.evolve_opt_depth_and_determine_event\n    (px, py, pz, ex, ey, ez, bx, by, bz, dt, optical_depth);\n\n    T exp_opt_depth = initial_optical_depth - dt*exp_rate;\n    T exp_dt_prod = initial_optical_depth/exp_rate ;\n\n    BOOST_CHECK_EQUAL(has_event_happend, true);\n    BOOST_CHECK_SMALL(exp_dt_prod, dt_prod);\n    BOOST_CHECK_SMALL((optical_depth-exp_opt_depth)/exp_opt_depth,\n    tolerance<T>());\n}\n\n\n//Test evolve_opt_depth_and_determine_event (double precision)\nBOOST_AUTO_TEST_CASE( breit_wheeler_engine_detopt_double_3 )\n{\n    breit_wheeler_engine_detopt_3<double>();\n}\n\n//Test evolve_opt_depth_and_determine_event (single precision)\nBOOST_AUTO_TEST_CASE( breit_wheeler_engine_detopt_single_3 )\n{\n    breit_wheeler_engine_detopt_3<float>();\n}\n", "meta": {"hexsha": "3ee8731e7ef8737c6988d63333699e4e599abb9b", "size": 15726, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/multi_physics/QED_tests/test_breit_wheeler_engine_SI.cpp", "max_stars_repo_name": "thaisacs/PICSAR", "max_stars_repo_head_hexsha": "1e3840779f478a70417975feecd35814ef92bf9d", "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": "src/multi_physics/QED_tests/test_breit_wheeler_engine_SI.cpp", "max_issues_repo_name": "thaisacs/PICSAR", "max_issues_repo_head_hexsha": "1e3840779f478a70417975feecd35814ef92bf9d", "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": "src/multi_physics/QED_tests/test_breit_wheeler_engine_SI.cpp", "max_forks_repo_name": "thaisacs/PICSAR", "max_forks_repo_head_hexsha": "1e3840779f478a70417975feecd35814ef92bf9d", "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": 29.7277882798, "max_line_length": 114, "alphanum_fraction": 0.7113061173, "num_tokens": 4698, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174787, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.4863626753263451}}
{"text": "#ifndef MOCHIMOCHI_ADAM_HPP_\n#define MOCHIMOCHI_ADAM_HPP_\n\n#include <Eigen/Dense>\n#include <cassert>\n#include \"../../functions/enumerate.hpp\"\n\nclass ADAM {\nprivate :\n  const std::size_t kDim;\n\nprivate :\n  std::size_t _timestep;\n  Eigen::VectorXd _w;\n  Eigen::VectorXd _m;\n  Eigen::VectorXd _v;\n\npublic :\n  ADAM(const std::size_t dim)\n    : kDim(dim),\n      _timestep(0),\n      _w(Eigen::VectorXd::Zero(kDim)),\n      _m(Eigen::VectorXd::Zero(kDim)),\n      _v(Eigen::VectorXd::Zero(kDim)) {\n\n    assert(dim > 0);\n  }\n\n  virtual ~ADAM() { }\n\nprivate :\n\n  double suffer_loss(const Eigen::VectorXd& x, const int y) const {\n    return std::max(0.0, 1.0 - y * _w.dot(x));\n  }\n\n  double calculate_margin(const Eigen::VectorXd& x) const {\n    return _w.dot(x);\n  }\n\npublic :\n\n  bool update(const Eigen::VectorXd& feature, const int label) {\n    constexpr auto kAlpha = 0.001;\n    constexpr auto kBeta1 = 0.9;\n    constexpr auto kBeta2 = 0.999;\n    constexpr auto  kEpsilon = 0.00000001;\n    constexpr auto kLambda = 0.99999999;\n\n    if (suffer_loss(feature, label) <= 0.0) { return false; }\n\n    const Eigen::VectorXd gradiant = -label * feature;\n    const auto beta1_t = std::pow(kLambda, _timestep) * kBeta1;\n\n    _timestep++;\n    functions::enumerate(gradiant.data(), gradiant.data() + gradiant.size(), 0,\n                       [&](const std::size_t index, const double value) {\n                         _m[index] = beta1_t * _m[index] + (1.0 - beta1_t) * value;\n                         _v[index] = kBeta2 * _v[index] + (1.0 - kBeta2) * value * value;\n                         const auto m_t = _m[index] / (1.0 - std::pow(kBeta1, _timestep));\n                         const auto v_t = _v[index] / (1.0 - std::pow(kBeta2, _timestep));\n                         _w[index] -= kAlpha * m_t / (std::sqrt(v_t) + kEpsilon);\n                       });\n\n    return true;\n  }\n\n  int predict(const Eigen::VectorXd& feature) const {\n    return calculate_margin(feature) > 0.0 ? 1 : -1;\n  }\n\n};\n\n#endif //MOCHIMOCHI_ADAM_HPP_\n", "meta": {"hexsha": "7d5b016378131bda06deff7ac0fb7e7ef694588e", "size": 2008, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "mochimochi/classifier/binary/adam.hpp", "max_stars_repo_name": "olanleed/MochiMochi", "max_stars_repo_head_hexsha": "830d361fa352f6ac336ec97a80588018c8164916", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 30.0, "max_stars_repo_stars_event_min_datetime": "2015-05-17T04:33:04.000Z", "max_stars_repo_stars_event_max_datetime": "2016-07-02T11:18:58.000Z", "max_issues_repo_path": "mochimochi/classifier/binary/adam.hpp", "max_issues_repo_name": "olanleed/MochiMochi", "max_issues_repo_head_hexsha": "830d361fa352f6ac336ec97a80588018c8164916", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2015-05-24T10:14:03.000Z", "max_issues_repo_issues_event_max_datetime": "2018-04-23T14:40:08.000Z", "max_forks_repo_path": "mochimochi/classifier/binary/adam.hpp", "max_forks_repo_name": "olanleed/MochiMochi", "max_forks_repo_head_hexsha": "830d361fa352f6ac336ec97a80588018c8164916", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-30T13:10:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-30T13:10:29.000Z", "avg_line_length": 26.7733333333, "max_line_length": 90, "alphanum_fraction": 0.5901394422, "num_tokens": 594, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.4863626753263451}}
{"text": "#pragma once\n\n#include <cmath>\n#include <string>\n#include <iostream>\n#include <fstream>\n#include <boost/numeric/ublas/matrix.hpp>\n\nusing namespace boost::numeric::ublas;\n\nclass gravity_calc {\nprivate:\n\tdouble GM = 398600.4415;\n\tdouble a = 6378137;\npublic:\n\tvoid get_stokes_coef(int n, matrix<double>& N, matrix<double>& M);\n\tvoid Legendre(int n, double lat, matrix<double>& L);\n\tdouble geopotential(double r, double lat, double lon, int n, matrix<double> N, matrix<double> M);\n\tint semifactorial(int n);\n};\n", "meta": {"hexsha": "7d649c5c5c52391e0ec869f6c61ed9ee72b76731", "size": 507, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "gravity.hpp", "max_stars_repo_name": "matsuguma353/FlightSimulator", "max_stars_repo_head_hexsha": "bdbe7b34dbfe7dd78a9e5762b4d289332c0c2f84", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gravity.hpp", "max_issues_repo_name": "matsuguma353/FlightSimulator", "max_issues_repo_head_hexsha": "bdbe7b34dbfe7dd78a9e5762b4d289332c0c2f84", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gravity.hpp", "max_forks_repo_name": "matsuguma353/FlightSimulator", "max_forks_repo_head_hexsha": "bdbe7b34dbfe7dd78a9e5762b4d289332c0c2f84", "max_forks_repo_licenses": ["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.1428571429, "max_line_length": 98, "alphanum_fraction": 0.7297830375, "num_tokens": 132, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7634837743174789, "lm_q2_score": 0.6370307875894139, "lm_q1q2_score": 0.48636267006520195}}
{"text": "/* boost random/normal_distribution.hpp header file\n *\n * Copyright Jens Maurer 2000-2001\n * Permission to use, copy, modify, sell, and distribute this software\n * is hereby granted without fee provided that the above copyright notice\n * appears in all copies and that both that copyright notice and this\n * permission notice appear in supporting documentation,\n *\n * Jens Maurer makes no representations about the suitability of this\n * software for any purpose. It is provided \"as is\" without express or\n * implied warranty.\n *\n * See http://www.boost.org for most recent version including documentation.\n *\n * $Id: normal_distribution.hpp 11696 2001-11-14 21:53:38Z jmaurer $\n *\n * Revision history\n *  2001-02-18  moved to individual header files\n */\n\n#ifndef BOOST_RANDOM_NORMAL_DISTRIBUTION_HPP\n#define BOOST_RANDOM_NORMAL_DISTRIBUTION_HPP\n\n#include <cmath>\n#include <cassert>\n#include <boost/random/uniform_01.hpp>\n\nnamespace boost {\n\n// deterministic polar method, uses trigonometric functions\ntemplate<class UniformRandomNumberGenerator, class RealType = double>\nclass normal_distribution\n{\npublic:\n  typedef UniformRandomNumberGenerator base_type;\n  typedef RealType result_type;\n\n  explicit normal_distribution(base_type & rng, const result_type& mean = 0,\n                               const result_type& sigma = 1)\n    : _rng(rng), _mean(mean), _sigma(sigma), _valid(false)\n  {\n    assert(sigma >= 0);\n  }\n\n  // compiler-generated copy constructor is NOT fine, need to purge cache\n  normal_distribution(const normal_distribution& other)\n    : _rng(other._rng), _mean(other._mean), _sigma(other._sigma), _valid(false)\n  {\n  }\n  // uniform_01 cannot be assigned, neither can this class\n\n  result_type operator()()\n  {\n#ifndef BOOST_NO_STDC_NAMESPACE\n    // allow for Koenig lookup\n    using std::sqrt; using std::log; using std::sin; using std::cos;\n#endif\n    if(!_valid) {\n      _r1 = _rng();\n      _r2 = _rng();\n      _cached_rho = sqrt(-2 * log(1.0-_r2));\n      _valid = true;\n    } else {\n      _valid = false;\n    }\n    // Can we have a boost::mathconst please?\n    const double pi = 3.14159265358979323846;\n    \n    return _cached_rho * (_valid ? cos(2*pi*_r1) : sin(2*pi*_r1)) * _sigma +\n      _mean;\n  }\n#ifndef BOOST_NO_OPERATORS_IN_NAMESPACE\n  friend bool operator==(const normal_distribution& x, \n                         const normal_distribution& y)\n  {\n    return x._mean == y._mean && x._sigma == y._sigma && \n      x._valid == y._valid && x._rng == y._rng;\n  }\n#else\n  // Use a member function\n  bool operator==(const normal_distribution& rhs) const\n  {\n    return _mean == rhs._mean && _sigma == rhs._sigma && \n      _valid == rhs._valid && _rng == rhs._rng;\n  }\n#endif\nprivate:\n  uniform_01<base_type, RealType> _rng;\n  const result_type _mean, _sigma;\n  result_type _r1, _r2, _cached_rho;\n  bool _valid;\n};\n\n} // namespace boost\n\n#endif // BOOST_RANDOM_NORMAL_DISTRIBUTION_HPP\n", "meta": {"hexsha": "17525c5c6c383e06f31b7aef63864b921e13dc47", "size": 2909, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "vegastrike/boost/1_28/boost/random/normal_distribution.hpp", "max_stars_repo_name": "Ezeer/VegaStrike_win32FR", "max_stars_repo_head_hexsha": "75891b9ccbdb95e48e15d3b4a9cd977955b97d1f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "vegastrike/boost/1_28/boost/random/normal_distribution.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/random/normal_distribution.hpp", "max_forks_repo_name": "Ezeer/VegaStrike_win32FR", "max_forks_repo_head_hexsha": "75891b9ccbdb95e48e15d3b4a9cd977955b97d1f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9896907216, "max_line_length": 79, "alphanum_fraction": 0.6981780681, "num_tokens": 742, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.4863626684698639}}
{"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_SCALAR_MNORMINF_HPP_INCLUDED\n#define NT2_LINALG_FUNCTIONS_SCALAR_MNORMINF_HPP_INCLUDED\n#include <nt2/linalg/functions/mnorminf.hpp>\n#include <nt2/include/functions/abs.hpp>\n#include <nt2/include/functions/asum1.hpp>\n#include <nt2/include/functions/globalmax.hpp>\n#include <nt2/include/functions/globalasum1.hpp>\n#include <nt2/include/functions/iscolumn.hpp>\n#include <nt2/include/functions/isrow.hpp>\n#include <nt2/include/functions/ismatrix.hpp>\n#include <nt2/core/container/dsl/forward.hpp>\n#include <nt2/core/functions/table/details/is_definitely_vector.hpp>\n#include <boost/assert.hpp>\n#include <boost/mpl/bool.hpp>\n#include <boost/static_assert.hpp>\n\n//  infinity norm  of a matrix  (maximum row sum)\n// TODO optimize mnorminf(trans(a)) as mnorm1(a)\n\nnamespace nt2 { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT  ( mnorminf_, tag::cpu_\n                            , (A0)\n                            , (scalar_<unspecified_<A0> >)\n                            )\n  {\n    typedef typename meta::as_real<A0>::type result_type;\n    BOOST_FORCEINLINE result_type operator()(A0 const& a0) const\n    {\n      return nt2::abs(a0);\n    }\n\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  ( mnorminf_, tag::cpu_\n                            , (A0)\n                            , ((ast_<A0, nt2::container::domain>))\n                            )\n  {\n    typedef typename A0::value_type                   type_t;\n    typedef typename meta::as_real<type_t>::type result_type;\n\n    BOOST_FORCEINLINE result_type operator()(A0 const& a0) const\n    {\n      BOOST_ASSERT_MSG(nt2::ismatrix(a0), \"a0 is not a matrix\");\n      typedef typename details::is_col_vector<typename A0::extent_type>::type choice_t;\n      return eval(a0, choice_t());\n    }\n\n    BOOST_FORCEINLINE result_type\n    eval(A0 const& a0, boost::mpl::true_ const &) const //static col vector\n    {\n      return nt2::globalmax(nt2::abs(a0));\n    }\n\n    BOOST_FORCEINLINE result_type\n    eval(A0 const& a0, boost::mpl::false_ const &) const  // not static col vector\n    {\n      typedef typename details::is_row_vector<typename A0::extent_type>::type choice_t;\n      return eval2(a0, choice_t());\n    }\n\n    BOOST_FORCEINLINE result_type\n    eval2(A0 const& a0, boost::mpl::true_ const &) const //static row vector\n    {\n      return nt2::globalasum1(a0);\n    }\n\n    BOOST_FORCEINLINE result_type\n    eval2(A0 const& a0, boost::mpl::false_ const &) const //not static vector\n    {\n      return nt2::globalmax(nt2::asum1(a0, 2));\n    }\n\n    BOOST_FORCEINLINE result_type\n    eval2(A0 const& a0, nt2::meta::indeterminate_ const &) const\n    {\n      return  eval(a0, nt2::meta::indeterminate_());\n    }\n\n    BOOST_FORCEINLINE result_type\n    eval(A0 const& a0, nt2::meta::indeterminate_ const &) const\n    {\n      if (iscolumn(a0)) // col vector\n      {\n        return eval(a0, boost::mpl::true_());\n      }\n      else if (isrow(a0)) //row vector\n      {\n        return eval2(a0, boost::mpl::true_());\n      }\n      else  // matrix but not vector\n      {\n        return eval2(a0, boost::mpl::false_());\n      }\n    }\n  };\n} }\n\n#endif\n", "meta": {"hexsha": "a22f3dfda3b648774e7fec340a02d149d8f05deb", "size": 3598, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/linalg/include/nt2/linalg/functions/scalar/mnorminf.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/scalar/mnorminf.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/scalar/mnorminf.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": 33.0091743119, "max_line_length": 87, "alphanum_fraction": 0.6045025014, "num_tokens": 912, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.6370307875894138, "lm_q1q2_score": 0.4863626632087206}}
{"text": "#include <Eigen/Core>\n#include <fstream>\n#include \"json/json.h\"\n#include <aruco/aruco.h>\n#include <aruco/cvdrawingutils.h>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/core/core.hpp>\n#include <opencv/cv.h>\n#include <opencv2/highgui/highgui_c.h>\n#include <opencv2/imgproc/imgproc.hpp>\n\nJson::Value mat2json(cv::Mat m)\n{\n    Json::Value r;\n    for(int i = 0; i < m.rows; i++)\n    {\n        Json::Value q;\n      for(int j = 0; j < m.cols; j++)\n            q[j] = m.at<double>(i,j);\n        r[i] = q;\n    }\n    return r;\n}\n\nJson::Value vec2json(double * p, int n)\n{\n    Json::Value r;\n    for(int i = 0; i < n; i++)\n        r[i] = p[i];\n    return r;\n}\n\nJson::Value mat2json1(Eigen::Matrix4d m)\n{\n    Json::Value r;\n    double *v_ptr = m.data();\n    for (int i = 0; i < 16; ++i)\n        r.append(Json::Value(v_ptr[i]));\n    return r;\n}\n\nJson::Value mat2json(const Eigen::Matrix4d & m)\n{\n    Json::Value r;\n    for(int i = 0; i < m.rows(); i++)\n    {\n        Json::Value q;\n      for(int j = 0; j < m.cols(); j++)\n            q[j] = m(i,j);\n        r[i] = q;\n    }    \n    return r;\n}\n\n\nint main(int argc, char const *argv[])\n{\n\t// first is camera as OpenCV\n\t// second is file\n\t// output is array of markers\t\n\tbool y_axis_perpendicular = false;\n\n\tif(argc < 5)\n\t{\n\t\tstd::cerr << \"Expected: calibrationfile.yaml command.yaml imagefile dist [outfile|-]\\n\";\n\t\treturn -1;\n\t}\n\n\tcv::Mat camera_matrix,dist_coeffs;\n\tcv::FileStorage camera_calibration_file(argv[1], cv::FileStorage::READ);\n    if (!camera_calibration_file.isOpened())\n    {\n    \tstd::cerr << \"wrong calibration file\" << std::endl;\n    \treturn -2;\n    }\n\tcamera_calibration_file[\"rgb_intrinsics\"] >> camera_matrix;\n\tcamera_calibration_file[\"rgb_distortion\"] >> dist_coeffs;\n\tif(!camera_matrix.rows || !dist_coeffs.rows)\n\t{\n\t\tstd::cerr << \"expected rgb_intrinsics or rgb_distortion in file\" << std::endl;\n\t\treturn -1;\n\t}\n\n    std::cout << \"K:\\n\" <<camera_matrix << std::endl;\n    std::cout << \"dist:\\n\" << dist_coeffs << std::endl;\n\n    cv::Mat frame = cv::imread(argv[3]);\n    if(frame.rows == 0)\n    {\n    \tstd::cerr << \"cannot open image:\" << argv[3]<<std::endl;\n    \treturn -3;\n    }\n\n    if(atoi(argv[4]) != 0)\n    {\n        // setZero\n        for(int i = 0; i < dist_coeffs.cols; i++)\n            dist_coeffs.at<float>(i) = 0;\n    }\n\n\n    aruco::CameraParameters cp(camera_matrix,dist_coeffs, cv::Size(frame.cols,frame.rows));\n\n    cv::FileStorage overlay(argv[2], cv::FileStorage::READ);\n\n\n    for(int i = 0; i < 10; i++)\n    {\n        aruco::Marker marker;\n        char name[128];\n        sprintf(name,\"markerpose%d\",i);\n        cv::Mat pose;\n        overlay[name] >> pose;\n        if(pose.rows == 0)\n            continue;\n        int id;\n        sprintf(name,\"markerid%d\",i);\n        overlay[name] >> id;\n        std::cout << \"found marker \" << i << \" with id \" << id << \" at \" << pose << std::endl;\n        sprintf(name,\"markersize%d\",i);\n        double size = 1.0;\n        overlay[name] >> size;\n        sprintf(name,\"mode%d\",i);\n        int flag = 0;\n        overlay[name] >> flag;\n\n        marker.id = id;\n        marker.ssize = size;\n        marker.resize(4);\n\n        // decompose the matrix? not needed\n        // marker.Rvec = \n        marker.Tvec.create(3, 1, CV_32FC1);\n        marker.Rvec.create(3, 1, CV_32FC1);\n        marker.Tvec.at<float>(0,0) = pose.at<double>(0,3);\n        marker.Tvec.at<float>(1,0) = pose.at<double>(1,3);\n        marker.Tvec.at<float>(2,0) = pose.at<double>(2,3);\n        cv::Rodrigues(pose(cv::Rect(0,0,3,3)),marker.Rvec);\n\n/*\nvoid MarkerDetector::distortPoints(vector< cv::Point2f > in, vector< cv::Point2f > &out, const Mat &camMatrix, const Mat &distCoeff) {\n    // trivial extrinsics\n    cv::Mat Rvec = cv::Mat(3, 1, CV_32FC1, cv::Scalar::all(0));\n    cv::Mat Tvec = Rvec.clone();\n    // calculate 3d points and then reproject, so opencv makes the distortion internally\n    vector< cv::Point3f > cornersPoints3d;\n    for (unsigned int i = 0; i < in.size(); i++)\n        cornersPoints3d.push_back(cv::Point3f((in[i].x - camMatrix.at< float >(0, 2)) / camMatrix.at< float >(0, 0), // x\n                                              (in[i].y - camMatrix.at< float >(1, 2)) / camMatrix.at< float >(1, 1), // y\n                                              1)); // z\n    cv::projectPoints(cornersPoints3d, Rvec, Tvec, camMatrix, distCoeff, out);\n}\n\ncv::undistortPoints(contour2f, contour2f, camMatrix, distCoeff, cv::Mat(), camMatrix);\n\n*/\n\n    cv::Mat ImagePoints(4, 1, CV_32FC2, cv::Scalar::all(0));\n        std::vector<cv::Point3f> corners;\n        corners.push_back(cv::Point3f(size/2,size/2,0));\n        corners.push_back(cv::Point3f(size/2,-size/2,0));\n        corners.push_back(cv::Point3f(-size/2,-size/2,0));\n        corners.push_back(cv::Point3f(-size/2,size/2,0));\n        std::cout << \"T  \" << marker.Tvec << std::endl;\n        std::cout << \"R  \" << marker.Rvec << std::endl;\n        std::cout << \"C  \" << corners << std::endl;\n        std::cout << \"K  \" << camera_matrix << std::endl;\n        std::cout << \"DI \" << dist_coeffs << std::endl;\n        cv::projectPoints(corners,marker.Rvec,marker.Tvec,camera_matrix,dist_coeffs,ImagePoints);\n        std::cout << \"IP \" << ImagePoints << std::endl;\n        for(int j = 0; j < 4; j++)\n        {\n            marker[j].x = ImagePoints.at<cv::Point2f>(j).x;\n            marker[j].y = ImagePoints.at<cv::Point2f>(j).y;\n        }\n        if(flag & 1)\n        {\n            marker.draw(frame, cv::Scalar(0,0,255), 2);\n        }\n        if(flag & 2)\n        {\n            aruco::CvDrawingUtils::draw3dAxis(frame, marker, cp);\n        }\n\n    }\n    if(argc < 6 || strcmp(argv[5],\"-\") == 0)\n    {\n        cv::imshow(\"ciao\",frame);\n        cv::waitKey(0);\n    }\n    else\n        cv::imwrite(argv[5],frame);\n    return 0;\n}", "meta": {"hexsha": "2589d57eec505e649d05a99f0666248ab63274cf", "size": 5778, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "overlay.cpp", "max_stars_repo_name": "eruffaldi/arucojson", "max_stars_repo_head_hexsha": "a54f156954c2374b429031e3abb565fb10018a6e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-07-05T12:49:44.000Z", "max_stars_repo_stars_event_max_datetime": "2017-07-05T12:49:44.000Z", "max_issues_repo_path": "overlay.cpp", "max_issues_repo_name": "eruffaldi/arucojson", "max_issues_repo_head_hexsha": "a54f156954c2374b429031e3abb565fb10018a6e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "overlay.cpp", "max_forks_repo_name": "eruffaldi/arucojson", "max_forks_repo_head_hexsha": "a54f156954c2374b429031e3abb565fb10018a6e", "max_forks_repo_licenses": ["Apache-2.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.7835051546, "max_line_length": 134, "alphanum_fraction": 0.55192108, "num_tokens": 1750, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911057, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.4863626616133826}}
{"text": "\n/** \\file   mri_core_kspace_filter.cpp\n    \\brief  Implementation kspace filter functionalities for 2D and 3D MRI parallel imaging\n    \\author Hui Xue\n*/\n\n#include \"mri_core_kspace_filter.h\"\n#include \"hoNDArray_elemwise.h\"\n#include <boost/algorithm/string.hpp>\n\n#ifdef M_PI\n    #undef M_PI\n#endif // M_PI\n#define M_PI 3.14159265358979323846\n\nnamespace Gadgetron\n{\n\nISMRMRDKSPACEFILTER get_kspace_filter_type(const std::string& name)\n{\n    std::string name_lower(name);\n    boost::algorithm::to_lower(name_lower);\n\n    if (name_lower == \"gaussian\")\n    {\n        return ISMRMRD_FILTER_GAUSSIAN;\n    }\n    else if (name_lower == \"hanning\")\n    {\n        return ISMRMRD_FILTER_HANNING;\n    }\n    else if (name_lower == \"taperedhanning\")\n    {\n        return ISMRMRD_FILTER_TAPERED_HANNING;\n    }\n    else if (name_lower == \"none\")\n    {\n        return ISMRMRD_FILTER_NONE;\n    }\n\n    GERROR_STREAM(\"Unrecognized kspace filter name : \" << name);\n\n    return ISMRMRD_FILTER_NONE;\n}\n\nstd::string get_kspace_filter_name(ISMRMRDKSPACEFILTER v)\n{\n    std::string name;\n\n    switch (v)\n    {\n        case ISMRMRD_FILTER_GAUSSIAN:\n        {\n            name = \"Gaussian\";\n            break;\n        }\n\n        case ISMRMRD_FILTER_HANNING:\n        {\n            name = \"Hanning\";\n            break;\n        }\n\n        case ISMRMRD_FILTER_TAPERED_HANNING:\n        {\n            name = \"TaperedHanning\";\n            break;\n        }\n\n        case ISMRMRD_FILTER_NONE:\n        {\n            name = \"none\";\n            break;\n        }\n\n        default:\n        {\n            GERROR_STREAM(\"Unrecognized kspace filter type : \" << v);\n            name = \"none\"; \n        }\n    }\n\n    return name;\n}\n\ntemplate<typename T>\nvoid generate_symmetric_filter(size_t len, hoNDArray<T>& filter, ISMRMRDKSPACEFILTER filterType, double sigma, size_t width)\n{\n    try\n    {\n        if (len == 0) return;\n\n        filter.create(len);\n\n        if (width == 0 || width >= len) width = 1;\n\n        size_t ii;\n        if (filterType == ISMRMRD_FILTER_GAUSSIAN)\n        {\n            double r = -1.0*sigma*sigma / 2;\n\n            if (len % 2 == 0)\n            {\n                // to make sure the zero points match and boundary of filters are symmetric\n                double stepSize = 2.0 / (len - 2);\n                std::vector<double> x(len - 1);\n\n                for (ii = 0; ii<len - 1; ii++)\n                {\n                    x[ii] = -1 + ii*stepSize;\n                }\n\n                for (ii = 0; ii<len - 1; ii++)\n                {\n                    filter(ii + 1) = T(std::exp(r*(x[ii] * x[ii])));\n                }\n\n                filter(0) = T(0);\n            }\n            else\n            {\n                double stepSize = 2.0 / (len - 1);\n                std::vector<double> x(len);\n\n                for (ii = 0; ii<len; ii++)\n                {\n                    x[ii] = -1 + ii*stepSize;\n                }\n\n                for (ii = 0; ii<len; ii++)\n                {\n                    filter(ii) = T(std::exp(r*(x[ii] * x[ii])));\n                }\n            }\n        }\n        else if (filterType == ISMRMRD_FILTER_TAPERED_HANNING)\n        {\n            hoNDArray<T> w(width);\n\n            for (ii = 1; ii <= width; ii++)\n            {\n                w(ii - 1) = T((0.5 * (1 - std::cos(2.0*M_PI*ii / (2 * width + 1)))));\n            }\n\n            // make sure the center of the filter will end up being 1:\n            Gadgetron::fill(filter, T(1.0));\n            \n            if (len % 2 == 0)\n            {\n                for (ii = 1; ii <= width; ii++)\n                {\n                    filter(ii) = w(ii - 1);\n                    filter(len - ii) = filter(ii);\n                }\n\n                filter(0) = T(0);\n            }\n            else\n            {\n                for (ii = 1; ii <= width; ii++)\n                {\n                    filter(ii - 1) = w(ii - 1);\n                    filter(len - ii) = filter(ii - 1);\n                }\n            }\n        }\n        else if (filterType == ISMRMRD_FILTER_HANNING)\n        {\n            if (len % 2 == 0)\n            {\n                size_t N = len - 1;\n                double halfLen = (double)((N + 1) / 2);\n                for (ii = 1; ii <= halfLen; ii++)\n                {\n                    filter(ii) = T((0.5 * (1 - std::cos(2.0*M_PI*ii / (N + 1)))));\n                }\n\n                for (ii = (size_t)halfLen; ii<N; ii++)\n                {\n                    filter(ii + 1) = filter(N - ii);\n                }\n\n                filter(0) = T(0);\n            }\n            else\n            {\n                double halfLen = (double)((len + 1) / 2);\n                for (ii = 1; ii <= (size_t)halfLen; ii++)\n                {\n                    filter(ii - 1) = T((0.5 * (1 - std::cos(2.0*M_PI*ii / (len + 1)))));\n                }\n\n                for (ii = (size_t)halfLen; ii<len; ii++)\n                {\n                    filter(ii) = filter(len - 1 - ii);\n                }\n            }\n        }\n        else if (filterType == ISMRMRD_FILTER_NONE)\n        {\n            Gadgetron::fill(filter, T(1.0));\n        }\n        else\n        {\n            GADGET_THROW(\"generate_symmetric_filter, unrecognized fiter type ... \");\n        }\n\n        T sos = 0.0f;\n        for (ii = 0; ii<len; ii++)\n        {\n            sos += filter(ii)*filter(ii);\n        }\n\n        T r = T(1.0 / std::sqrt(std::abs(sos) / (len)));\n        for (ii = 0; ii<len; ii++)\n        {\n            filter(ii) *= r;\n        }\n    }\n    catch (...)\n    {\n        GADGET_THROW(\"Errors in generate_symmetric_filter(...) ... \");\n    }\n}\n\ntemplate EXPORTMRICORE void generate_symmetric_filter(size_t len, hoNDArray<float>& filter, ISMRMRDKSPACEFILTER filterType, double sigma, size_t width);\ntemplate EXPORTMRICORE void generate_symmetric_filter(size_t len, hoNDArray<double>& filter, ISMRMRDKSPACEFILTER filterType, double sigma, size_t width);\ntemplate EXPORTMRICORE void generate_symmetric_filter(size_t len, hoNDArray< std::complex<float> >& filter, ISMRMRDKSPACEFILTER filterType, double sigma, size_t width);\ntemplate EXPORTMRICORE void generate_symmetric_filter(size_t len, hoNDArray< std::complex<double> >& filter, ISMRMRDKSPACEFILTER filterType, double sigma, size_t width);\n\n// ------------------------------------------------------------------------\n\ntemplate<typename T>\nvoid generate_asymmetric_filter(size_t len, size_t start, size_t end, hoNDArray<T>& filter, ISMRMRDKSPACEFILTER filterType, size_t width, bool densityComp)\n{\n    try\n    {\n        if (len == 0) return;\n\n        if (start > len - 1) start = 0;\n        if (end > len - 1) end = len - 1;\n\n        if (start > end)\n        {\n            start = 0;\n            end = len - 1;\n        }\n\n        filter.create(len);\n        Gadgetron::clear(filter);\n\n        size_t ii;\n        for (ii = start; ii <= end; ii++)\n        {\n            filter(ii) = T(1.0);\n        }\n\n        if (width == 0 || width >= len) width = 1;\n\n        hoNDArray<T> w(width);\n\n        if (filterType == ISMRMRD_FILTER_TAPERED_HANNING)\n        {\n            for (ii = 1; ii <= width; ii++)\n            {\n                w(ii - 1) = T((0.5 * (1 - std::cos(2.0*M_PI*ii / (2 * width + 1)))));\n            }\n        }\n        else if (filterType == ISMRMRD_FILTER_NONE)\n        {\n            Gadgetron::fill(w, T(1.0));\n        }\n        else\n        {\n            GADGET_THROW(\"generate_symmetric_filter, unrecognized fiter type ... \");\n        }\n\n        if (densityComp)\n        {\n            size_t startSym(0), endSym(len - 1);\n            find_symmetric_sampled_region(start, end, len / 2, startSym, endSym);\n\n            if (start == 0 && end == len - 1)\n            {\n                for (ii = 1; ii <= width; ii++)\n                {\n                    filter(ii - 1) = w(ii - 1);\n                    filter(len - ii) = filter(ii - 1);\n                }\n            }\n\n            if (start == 0 && end<len - 1)\n            {\n                for (ii = 0; ii<startSym; ii++)\n                {\n                    filter(ii) = 2.0;\n                }\n\n                for (ii = 1; ii <= width; ii++)\n                {\n                    filter(ii - 1 + startSym) = T(1.0) + w(width - ii);\n                    filter(end - ii + 1) = w(ii - 1);\n                }\n            }\n\n            if (start>0 && end == len - 1)\n            {\n                for (ii = endSym + 1; ii<len; ii++)\n                {\n                    filter(ii) = 2.0;\n                }\n\n                for (ii = 1; ii <= width; ii++)\n                {\n                    filter(endSym - ii + 1) = T(1.0) + w(width - ii);\n                    filter(start + ii - 1) = w(ii - 1);\n                }\n            }\n\n            if (start>0 && end<len - 1)\n            {\n                if (start == startSym && end == endSym)\n                {\n                    for (ii = 1; ii <= width; ii++)\n                    {\n                        filter(start + ii - 1) = w(ii - 1);\n                        filter(end - ii + 1) = w(ii - 1);\n                    }\n                }\n                else if (start == startSym && end>endSym)\n                {\n                    for (ii = endSym + 1; ii <= end; ii++)\n                    {\n                        filter(ii) = 2.0;\n                    }\n\n                    for (ii = 1; ii <= width; ii++)\n                    {\n                        filter(end - ii + 1) = T(1.0) + w(ii - 1);\n                        filter(endSym - ii + 1) = w(width - ii);\n                        filter(start + ii - 1) = w(ii - 1);\n                    }\n                }\n                else if (start<startSym && end == endSym)\n                {\n                    for (ii = start; ii<startSym; ii++)\n                    {\n                        filter(ii) = 2.0;\n                    }\n\n                    for (ii = 1; ii <= width; ii++)\n                    {\n                        filter(ii - 1 + start) = T(1.0) + w(ii - 1);\n                        filter(ii - 1 + startSym) = w(width - ii);\n                        filter(end - ii + 1) = w(ii - 1);\n                    }\n                }\n                else\n                {\n                    for (ii = 1; ii <= width; ii++)\n                    {\n                        filter(start + ii - 1) = w(ii - 1);\n                        filter(end - ii + 1) = w(ii - 1);\n                    }\n                }\n            }\n        }\n        else\n        {\n            if (start == 0 && end == len - 1)\n            {\n                for (ii = 1; ii <= width; ii++)\n                {\n                    filter(ii - 1) = w(ii - 1);\n                    filter(len - ii) = filter(ii - 1);\n                }\n            }\n\n            if (start == 0 && end<len - 1)\n            {\n                for (ii = 1; ii <= width; ii++)\n                {\n                    filter(end - ii + 1) = w(ii - 1);\n                }\n            }\n\n            if (start>0 && end == len - 1)\n            {\n                for (ii = 1; ii <= width; ii++)\n                {\n                    filter(start + ii - 1) = w(ii - 1);\n                }\n            }\n\n            if (start>0 && end<len - 1)\n            {\n                for (ii = 1; ii <= width; ii++)\n                {\n                    filter(start + ii - 1) = w(ii - 1);\n                    filter(end - ii + 1) = w(ii - 1);\n                }\n            }\n        }\n\n        T sos = 0.0f;\n        for (ii = 0; ii<len; ii++)\n        {\n            sos += filter(ii)*filter(ii);\n        }\n\n        T r = (T)(1.0 / std::sqrt(std::abs(sos) / (end - start + 1))); // SNR unit filter\n        for (ii = 0; ii<len; ii++)\n        {\n            filter(ii) *= r;\n        }\n    }\n    catch (...)\n    {\n        GADGET_THROW(\"Errors in generate_asymmetric_filter(...) ... \");\n    }\n}\n\ntemplate EXPORTMRICORE void generate_asymmetric_filter(size_t len, size_t start, size_t end, hoNDArray<float>& filter, ISMRMRDKSPACEFILTER filterType, size_t width, bool densityComp);\ntemplate EXPORTMRICORE void generate_asymmetric_filter(size_t len, size_t start, size_t end, hoNDArray<double>& filter, ISMRMRDKSPACEFILTER filterType, size_t width, bool densityComp);\ntemplate EXPORTMRICORE void generate_asymmetric_filter(size_t len, size_t start, size_t end, hoNDArray< std::complex<float> >& filter, ISMRMRDKSPACEFILTER filterType, size_t width, bool densityComp);\ntemplate EXPORTMRICORE void generate_asymmetric_filter(size_t len, size_t start, size_t end, hoNDArray< std::complex<double> >& filter, ISMRMRDKSPACEFILTER filterType, size_t width, bool densityComp);\n\n// ------------------------------------------------------------------------\n\ntemplate<typename T>\nvoid generate_symmetric_filter_ref(size_t len, size_t start, size_t end, hoNDArray<T>& filter)\n{\n    try\n    {\n        GADGET_CHECK_THROW(len >= 2);\n        GADGET_CHECK_THROW(start >= 0 && end <= len - 1 && start <= end);\n\n        if (start == 0 && end == len - 1)\n        {\n            generate_symmetric_filter(len, filter, ISMRMRD_FILTER_HANNING);\n            return;\n        }\n\n        size_t centerInd = len / 2;\n\n        size_t lenFilter(0); // make a symmetric filter with zero at the center\n        size_t lenFilterEnd = 2 * (end - centerInd) + 1;\n        size_t lenFilterStart = 2 * (centerInd - start) + 1;\n\n        if (start == 0 && end<len - 1)\n        {\n            lenFilter = lenFilterEnd;\n        }\n        else if (start>0 && end == len - 1)\n        {\n            lenFilter = lenFilterStart;\n        }\n        else if (start>0 && end<len - 1)\n        {\n            lenFilter = ((lenFilterStart<lenFilterEnd) ? lenFilterStart : lenFilterEnd);\n        }\n        else\n        {\n            GERROR_STREAM(\"generate_symmetric_filter_ref, invalid inputs : start - end - len ... \" << start << \" \" << end << \" \" << len);\n            GADGET_THROW(\"generate_symmetric_filter_ref, invalid inputs ... \");\n        }\n\n        GADGET_CHECK_THROW(lenFilter>0);\n\n        hoNDArray<T> filterSym(lenFilter);\n        generate_symmetric_filter(lenFilter, filterSym, ISMRMRD_FILTER_HANNING);\n\n        filter.create(len);\n        Gadgetron::clear(&filter);\n\n        if (start == 0 && end<len - 1)\n        {\n            memcpy(filter.begin() + end - lenFilter + 1, filterSym.begin(), filterSym.get_number_of_bytes());\n            return;\n        }\n        else if (start>0 && end == len - 1)\n        {\n            memcpy(filter.begin() + start, filterSym.begin(), filterSym.get_number_of_bytes());\n            return;\n        }\n        else if (start>0 && end<len - 1)\n        {\n            if (lenFilter == lenFilterStart)\n            {\n                memcpy(filter.begin() + start, filterSym.begin(), filterSym.get_number_of_bytes());\n            }\n            else\n            {\n                memcpy(filter.begin() + end - lenFilter + 1, filterSym.begin(), filterSym.get_number_of_bytes());\n            }\n\n            return;\n        }\n        else\n        {\n            GERROR_STREAM(\"Invalid inputs : start - end - len : \" << start << \" \" << end << \" \" << len);\n            GADGET_THROW(\"generate_symmetric_filter_ref, invalid inputs : start - end - len\");\n        }\n    }\n    catch (...)\n    {\n        GADGET_THROW(\"Errors in generate_symmetric_filter_ref(...) ... \");\n    }\n}\n\ntemplate EXPORTMRICORE void generate_symmetric_filter_ref(size_t len, size_t start, size_t end, hoNDArray<float>& filter);\ntemplate EXPORTMRICORE void generate_symmetric_filter_ref(size_t len, size_t start, size_t end, hoNDArray<double>& filter);\ntemplate EXPORTMRICORE void generate_symmetric_filter_ref(size_t len, size_t start, size_t end, hoNDArray< std::complex<float> >& filter);\ntemplate EXPORTMRICORE void generate_symmetric_filter_ref(size_t len, size_t start, size_t end, hoNDArray< std::complex<double> >& filter);\n\n// ------------------------------------------------------------------------\n\ntemplate <typename T> \nvoid compute_2d_filter(const hoNDArray<T>& fx, const hoNDArray<T>& fy, hoNDArray<T>& fxy)\n{\n    try\n    {\n        size_t RO = fx.get_size(0);\n        size_t E1 = fy.get_size(0);\n\n        fxy.create(RO, E1);\n        T* pFxy = fxy.begin();\n\n        size_t x, y;\n\n        for (y = 0; y<E1; y++)\n        {\n            for (x = 0; x<RO; x++)\n            {\n                pFxy[y*RO + x] = fx(x) * fy(y);\n            }\n        }\n    }\n    catch (...)\n    {\n        GADGET_THROW(\"Errors in compute_2d_filter(...) ... \");\n    }\n}\n\ntemplate EXPORTMRICORE void compute_2d_filter(const hoNDArray<float>& fx, const hoNDArray<float>& fy, hoNDArray<float>& fxy);\ntemplate EXPORTMRICORE void compute_2d_filter(const hoNDArray<double>& fx, const hoNDArray<double>& fy, hoNDArray<double>& fxy);\ntemplate EXPORTMRICORE void compute_2d_filter(const hoNDArray< std::complex<float> >& fx, const hoNDArray< std::complex<float> >& fy, hoNDArray< std::complex<float> >& fxy);\ntemplate EXPORTMRICORE void compute_2d_filter(const hoNDArray< std::complex<double> >& fx, const hoNDArray< std::complex<double> >& fy, hoNDArray< std::complex<double> >& fxy);\n\n// ------------------------------------------------------------------------\n\nvoid compute_2d_filter(const hoNDArray<float>& fx, const hoNDArray<float>& fy, hoNDArray< std::complex<float> >& fxy)\n{\n    try\n    {\n        size_t RO = fx.get_size(0);\n        size_t E1 = fy.get_size(0);\n\n        fxy.create(RO, E1);\n        std::complex<float> * pFxy = fxy.begin();\n\n        size_t x, y;\n\n        for (y = 0; y<E1; y++)\n        {\n            for (x = 0; x<RO; x++)\n            {\n                pFxy[y*RO + x] = std::complex<float>(fx(x) * fy(y));\n            }\n        }\n    }\n    catch (...)\n    {\n        GADGET_THROW(\"Errors in compute_2d_filter(float) ... \");\n    }\n}\n\n// ------------------------------------------------------------------------\n\nvoid compute_2d_filter(const hoNDArray<double>& fx, const hoNDArray<double>& fy, hoNDArray< std::complex<double> >& fxy)\n{\n    try\n    {\n        size_t RO = fx.get_size(0);\n        size_t E1 = fy.get_size(0);\n\n        fxy.create(RO, E1);\n        std::complex<double> * pFxy = fxy.begin();\n\n        size_t x, y;\n\n        for (y = 0; y<E1; y++)\n        {\n            for (x = 0; x<RO; x++)\n            {\n                pFxy[y*RO + x] = std::complex<double>(fx(x) * fy(y));\n            }\n        }\n    }\n    catch (...)\n    {\n        GADGET_THROW(\"Errors in compute_2d_filter(double) ... \");\n    }\n}\n\n// ------------------------------------------------------------------------\n\ntemplate <typename T> \nvoid compute_3d_filter(const hoNDArray<T>& fx, const hoNDArray<T>& fy, const hoNDArray<T>& fz, hoNDArray<T>& fxyz)\n{\n    try\n    {\n        size_t RO = fx.get_size(0);\n        size_t E1 = fy.get_size(0);\n        size_t E2 = fz.get_size(0);\n\n        fxyz.create(RO, E1, E2);\n        T* pFxyz = fxyz.begin();\n\n        const T* px = fx.begin();\n        const T* py = fy.begin();\n        const T* pz = fz.begin();\n\n        size_t x, y, z;\n\n        T vz, vy, vx;\n\n        for (z = 0; z<E2; z++)\n        {\n            vz = pz[z];\n            for (y = 0; y<E1; y++)\n            {\n                vy = py[y];\n                for (x = 0; x<RO; x++)\n                {\n                    vx = px[x];\n                    pFxyz[x+y*RO+z*RO*E1] = (vx*vz*vy);\n                }\n            }\n        }\n    }\n    catch (...)\n    {\n        GADGET_THROW(\"Errors in compute_3d_filter(...) ... \");\n    }\n}\n\ntemplate EXPORTMRICORE void compute_3d_filter(const hoNDArray<float>& fx, const hoNDArray<float>& fy, const hoNDArray<float>& fz, hoNDArray<float>& fxyz);\ntemplate EXPORTMRICORE void compute_3d_filter(const hoNDArray<double>& fx, const hoNDArray<double>& fy, const hoNDArray<double>& fz, hoNDArray<double>& fxyz);\ntemplate EXPORTMRICORE void compute_3d_filter(const hoNDArray< std::complex<float> >& fx, const hoNDArray< std::complex<float> >& fy, const hoNDArray< std::complex<float> >& fz, hoNDArray< std::complex<float> >& fxyz);\ntemplate EXPORTMRICORE void compute_3d_filter(const hoNDArray< std::complex<double> >& fx, const hoNDArray< std::complex<double> >& fy, const hoNDArray< std::complex<double> >& fz, hoNDArray< std::complex<double> >& fxyz);\n\n// ------------------------------------------------------------------------\n\nvoid compute_3d_filter(const hoNDArray<float>& fx, const hoNDArray<float>& fy, const hoNDArray<float>& fz, hoNDArray< std::complex<float> >& fxyz)\n{\n    try\n    {\n        size_t RO = fx.get_size(0);\n        size_t E1 = fy.get_size(0);\n        size_t E2 = fz.get_size(0);\n\n        fxyz.create(RO, E1, E2);\n        std::complex<float> * pFxyz = fxyz.begin();\n\n        size_t x, y, z;\n\n        for (z = 0; z<E2; z++)\n        {\n            for (y = 0; y<E1; y++)\n            {\n                for (x = 0; x<RO; x++)\n                {\n                    pFxyz[z*RO*E1 + y*RO + x] = std::complex<float>(fx(x)*fy(y)*fz(z));\n                }\n            }\n        }\n    }\n    catch (...)\n    {\n        GADGET_THROW(\"Errors in compute_3d_filter(float) ... \");\n    }\n}\n\n// ------------------------------------------------------------------------\n\nvoid compute_3d_filter(const hoNDArray<double>& fx, const hoNDArray<double>& fy, const hoNDArray<double>& fz, hoNDArray< std::complex<double> >& fxyz)\n{\n    try\n    {\n        size_t RO = fx.get_size(0);\n        size_t E1 = fy.get_size(0);\n        size_t E2 = fz.get_size(0);\n\n        fxyz.create(RO, E1, E2);\n        std::complex<double> * pFxyz = fxyz.begin();\n\n        size_t x, y, z;\n\n        for (z = 0; z<E2; z++)\n        {\n            for (y = 0; y<E1; y++)\n            {\n                for (x = 0; x<RO; x++)\n                {\n                    pFxyz[z*RO*E1 + y*RO + x] = std::complex<double>(fx(x)*fy(y)*fz(z));\n                }\n            }\n        }\n    }\n    catch (...)\n    {\n        GADGET_THROW(\"Errors in compute_3d_filter(double) ... \");\n    }\n}\n\n// ------------------------------------------------------------------------\n\ntemplate <typename T>\nvoid apply_kspace_filter_RO(hoNDArray<T>& data, const hoNDArray<T>& fRO)\n{\n    try\n    {\n        GADGET_CHECK_THROW(data.get_size(0) == fRO.get_number_of_elements());\n        Gadgetron::multiply(data, fRO, data);\n    }\n    catch (...)\n    {\n        GADGET_THROW(\"Errors in apply_kspace_filter_RO(...) ... \");\n    }\n}\n\ntemplate EXPORTMRICORE void apply_kspace_filter_RO(hoNDArray<float>& data, const hoNDArray<float>& fRO);\ntemplate EXPORTMRICORE void apply_kspace_filter_RO(hoNDArray<double>& data, const hoNDArray<double>& fRO);\ntemplate EXPORTMRICORE void apply_kspace_filter_RO(hoNDArray< std::complex<float> >& data, const hoNDArray< std::complex<float> >& fRO);\ntemplate EXPORTMRICORE void apply_kspace_filter_RO(hoNDArray< std::complex<double> >& data, const hoNDArray< std::complex<double> >& fRO);\n\ntemplate <typename T> \nvoid apply_kspace_filter_RO(const hoNDArray<T>& data, const hoNDArray<T>& fRO, hoNDArray<T>& dataFiltered)\n{\n    try\n    {\n        GADGET_CHECK_THROW(data.get_size(0) == fRO.get_number_of_elements());\n        Gadgetron::multiply(data, fRO, dataFiltered);\n    }\n    catch (...)\n    {\n        GADGET_THROW(\"Errors in apply_kspace_filter_RO(...) ... \");\n    }\n}\n\ntemplate EXPORTMRICORE void apply_kspace_filter_RO(const hoNDArray<float>& data, const hoNDArray<float>& fRO, hoNDArray<float>& dataFiltered);\ntemplate EXPORTMRICORE void apply_kspace_filter_RO(const hoNDArray<double>& data, const hoNDArray<double>& fRO, hoNDArray<double>& dataFiltered);\ntemplate EXPORTMRICORE void apply_kspace_filter_RO(const hoNDArray< std::complex<float> >& data, const hoNDArray< std::complex<float> >& fRO, hoNDArray< std::complex<float> >& dataFiltered);\ntemplate EXPORTMRICORE void apply_kspace_filter_RO(const hoNDArray< std::complex<double> >& data, const hoNDArray< std::complex<double> >& fRO, hoNDArray< std::complex<double> >& dataFiltered);\n\n// ------------------------------------------------------------------------\n\ntemplate <typename T> \nvoid apply_kspace_filter_E1(const hoNDArray<T>& data, const hoNDArray<T>& fE1, hoNDArray<T>& dataFiltered)\n{\n    try\n    {\n        GADGET_CHECK_THROW(data.get_size(1) == fE1.get_number_of_elements());\n\n        hoNDArray<T> fRO(data.get_size(0));\n        fRO.fill(T(1.0));\n\n        hoNDArray<T> fxy;\n        compute_2d_filter(fRO, fE1, fxy);\n\n        Gadgetron::multiply(data, fxy, dataFiltered);\n    }\n    catch (...)\n    {\n        GADGET_THROW(\"Errors in apply_kspace_filter_E1(...) ... \");\n    }\n}\n\ntemplate EXPORTMRICORE void apply_kspace_filter_E1(const hoNDArray<float>& data, const hoNDArray<float>& fE1, hoNDArray<float>& dataFiltered);\ntemplate EXPORTMRICORE void apply_kspace_filter_E1(const hoNDArray<double>& data, const hoNDArray<double>& fE1, hoNDArray<double>& dataFiltered);\ntemplate EXPORTMRICORE void apply_kspace_filter_E1(const hoNDArray< std::complex<float> >& data, const hoNDArray< std::complex<float> >& fE1, hoNDArray< std::complex<float> >& dataFiltered);\ntemplate EXPORTMRICORE void apply_kspace_filter_E1(const hoNDArray< std::complex<double> >& data, const hoNDArray< std::complex<double> >& fE1, hoNDArray< std::complex<double> >& dataFiltered);\n\n// ------------------------------------------------------------------------\n\ntemplate <typename T> \nvoid apply_kspace_filter_ROE1(const hoNDArray<T>& data, const hoNDArray<T>& fROE1, hoNDArray<T>& dataFiltered)\n{\n    try\n    {\n        GADGET_CHECK_THROW(data.get_size(0) == fROE1.get_size(0));\n        GADGET_CHECK_THROW(data.get_size(1) == fROE1.get_size(1));\n\n        Gadgetron::multiply(data, fROE1, dataFiltered);\n    }\n    catch (...)\n    {\n        GADGET_THROW(\"Errors in apply_kspace_filter_ROE1(...) ... \");\n    }\n}\n\ntemplate EXPORTMRICORE void apply_kspace_filter_ROE1(const hoNDArray<float>& data, const hoNDArray<float>& fROE1, hoNDArray<float>& dataFiltered);\ntemplate EXPORTMRICORE void apply_kspace_filter_ROE1(const hoNDArray<double>& data, const hoNDArray<double>& fROE1, hoNDArray<double>& dataFiltered);\ntemplate EXPORTMRICORE void apply_kspace_filter_ROE1(const hoNDArray< std::complex<float> >& data, const hoNDArray< std::complex<float> >& fROE1, hoNDArray< std::complex<float> >& dataFiltered);\ntemplate EXPORTMRICORE void apply_kspace_filter_ROE1(const hoNDArray< std::complex<double> >& data, const hoNDArray< std::complex<double> >& fROE1, hoNDArray< std::complex<double> >& dataFiltered);\n\n// ------------------------------------------------------------------------\n\ntemplate <typename T> \nvoid apply_kspace_filter_ROE1(const hoNDArray<T>& data, const hoNDArray<T>& fRO, const hoNDArray<T>& fE1, hoNDArray<T>& dataFiltered)\n{\n    try\n    {\n        GADGET_CHECK_THROW(data.get_size(0) == fRO.get_size(0));\n        GADGET_CHECK_THROW(data.get_size(1) == fE1.get_size(0));\n\n        hoNDArray<T> fROE1;\n        compute_2d_filter(fRO, fE1, fROE1);\n\n        Gadgetron::multiply(data, fROE1, dataFiltered);\n    }\n    catch (...)\n    {\n        GADGET_THROW(\"Errors in apply_kspace_filter_ROE1(...) ... \");\n    }\n}\n\ntemplate EXPORTMRICORE void apply_kspace_filter_ROE1(const hoNDArray<float>& data, const hoNDArray<float>& fRO, const hoNDArray<float>& fE1, hoNDArray<float>& dataFiltered);\ntemplate EXPORTMRICORE void apply_kspace_filter_ROE1(const hoNDArray<double>& data, const hoNDArray<double>& fRO, const hoNDArray<double>& fE1, hoNDArray<double>& dataFiltered);\ntemplate EXPORTMRICORE void apply_kspace_filter_ROE1(const hoNDArray< std::complex<float> >& data, const hoNDArray< std::complex<float> >& fRO, const hoNDArray< std::complex<float> >& fE1, hoNDArray< std::complex<float> >& dataFiltered);\ntemplate EXPORTMRICORE void apply_kspace_filter_ROE1(const hoNDArray< std::complex<double> >& data, const hoNDArray< std::complex<double> >& fRO, const hoNDArray< std::complex<double> >& fE1, hoNDArray< std::complex<double> >& dataFiltered);\n\n// ------------------------------------------------------------------------\n\ntemplate <typename T> \nvoid apply_kspace_filter_E2(const hoNDArray<T>& data, const hoNDArray<T>& fE2, hoNDArray<T>& dataFiltered)\n{\n    try\n    {\n        GADGET_CHECK_THROW(data.get_size(2) == fE2.get_number_of_elements());\n\n        hoNDArray<T> fRO(data.get_size(0));\n        fRO.fill(T(1.0));\n\n        hoNDArray<T> fE1(data.get_size(1));\n        fE1.fill(T(1.0));\n\n        hoNDArray<T> fxyz;\n        compute_3d_filter(fRO, fE1, fE2, fxyz);\n\n        Gadgetron::multiply(data, fxyz, dataFiltered);\n    }\n    catch (...)\n    {\n        GADGET_THROW(\"Errors in apply_kspace_filter_E2(...) ... \");\n    }\n}\n\ntemplate EXPORTMRICORE void apply_kspace_filter_E2(const hoNDArray<float>& data, const hoNDArray<float>& fE2, hoNDArray<float>& dataFiltered);\ntemplate EXPORTMRICORE void apply_kspace_filter_E2(const hoNDArray<double>& data, const hoNDArray<double>& fE2, hoNDArray<double>& dataFiltered);\ntemplate EXPORTMRICORE void apply_kspace_filter_E2(const hoNDArray< std::complex<float> >& data, const hoNDArray< std::complex<float> >& fE2, hoNDArray< std::complex<float> >& dataFiltered);\ntemplate EXPORTMRICORE void apply_kspace_filter_E2(const hoNDArray< std::complex<double> >& data, const hoNDArray< std::complex<double> >& fE2, hoNDArray< std::complex<double> >& dataFiltered);\n\n// ------------------------------------------------------------------------\n\ntemplate <typename T> \nvoid apply_kspace_filter_ROE2(const hoNDArray<T>& data, const hoNDArray<T>& fRO, const hoNDArray<T>& fE2, hoNDArray<T>& dataFiltered)\n{\n    try\n    {\n        GADGET_CHECK_THROW(data.get_size(0) == fRO.get_number_of_elements());\n        GADGET_CHECK_THROW(data.get_size(2) == fE2.get_number_of_elements());\n\n        hoNDArray<T> fE1(data.get_size(1));\n        fE1.fill(T(1.0));\n\n        hoNDArray<T> fxyz;\n        compute_3d_filter(fRO, fE1, fE2, fxyz);\n\n        Gadgetron::multiply(data, fxyz, dataFiltered);\n    }\n    catch (...)\n    {\n        GADGET_THROW(\"Errors in apply_kspace_filter_ROE2(...) ... \");\n    }\n}\n\ntemplate EXPORTMRICORE void apply_kspace_filter_ROE2(const hoNDArray<float>& data, const hoNDArray<float>& fRO, const hoNDArray<float>& fE2, hoNDArray<float>& dataFiltered);\ntemplate EXPORTMRICORE void apply_kspace_filter_ROE2(const hoNDArray<double>& data, const hoNDArray<double>& fRO, const hoNDArray<double>& fE2, hoNDArray<double>& dataFiltered);\ntemplate EXPORTMRICORE void apply_kspace_filter_ROE2(const hoNDArray< std::complex<float> >& data, const hoNDArray< std::complex<float> >& fRO, const hoNDArray< std::complex<float> >& fE2, hoNDArray< std::complex<float> >& dataFiltered);\ntemplate EXPORTMRICORE void apply_kspace_filter_ROE2(const hoNDArray< std::complex<double> >& data, const hoNDArray< std::complex<double> >& fRO, const hoNDArray< std::complex<double> >& fE2, hoNDArray< std::complex<double> >& dataFiltered);\n\n// ------------------------------------------------------------------------\n\ntemplate <typename T> \nvoid apply_kspace_filter_E1E2(const hoNDArray<T>& data, const hoNDArray<T>& fE1, const hoNDArray<T>& fE2, hoNDArray<T>& dataFiltered)\n{\n    try\n    {\n        GADGET_CHECK_THROW(data.get_size(1) == fE1.get_number_of_elements());\n        GADGET_CHECK_THROW(data.get_size(2) == fE2.get_number_of_elements());\n\n        hoNDArray<T> fRO(data.get_size(0));\n        fRO.fill(T(1.0));\n\n        hoNDArray<T> fxyz;\n        compute_3d_filter(fRO, fE1, fE2, fxyz);\n\n        Gadgetron::multiply(data, fxyz, dataFiltered);\n    }\n    catch (...)\n    {\n        GADGET_THROW(\"Errors in apply_kspace_filter_E1E2(...) ... \");\n    }\n}\n\ntemplate EXPORTMRICORE void apply_kspace_filter_E1E2(const hoNDArray<float>& data, const hoNDArray<float>& fE1, const hoNDArray<float>& fE2, hoNDArray<float>& dataFiltered);\ntemplate EXPORTMRICORE void apply_kspace_filter_E1E2(const hoNDArray<double>& data, const hoNDArray<double>& fE1, const hoNDArray<double>& fE2, hoNDArray<double>& dataFiltered);\ntemplate EXPORTMRICORE void apply_kspace_filter_E1E2(const hoNDArray< std::complex<float> >& data, const hoNDArray< std::complex<float> >& fE1, const hoNDArray< std::complex<float> >& fE2, hoNDArray< std::complex<float> >& dataFiltered);\ntemplate EXPORTMRICORE void apply_kspace_filter_E1E2(const hoNDArray< std::complex<double> >& data, const hoNDArray< std::complex<double> >& fE1, const hoNDArray< std::complex<double> >& fE2, hoNDArray< std::complex<double> >& dataFiltered);\n\n// ------------------------------------------------------------------------\n\ntemplate <typename T> \nvoid apply_kspace_filter_ROE1E2(const hoNDArray<T>& data, const hoNDArray<T>& fROE1E2, hoNDArray<T>& dataFiltered)\n{\n    try\n    {\n        GADGET_CHECK_THROW(data.get_size(0) == fROE1E2.get_size(0));\n        GADGET_CHECK_THROW(data.get_size(1) == fROE1E2.get_size(1));\n        GADGET_CHECK_THROW(data.get_size(2) == fROE1E2.get_size(2));\n\n        Gadgetron::multiply(data, fROE1E2, dataFiltered);\n    }\n    catch (...)\n    {\n        GADGET_THROW(\"Errors in apply_kspace_filter_ROE1E2(...) ... \");\n    }\n}\n\ntemplate EXPORTMRICORE void apply_kspace_filter_ROE1E2(const hoNDArray<float>& data, const hoNDArray<float>& fROE1E2, hoNDArray<float>& dataFiltered);\ntemplate EXPORTMRICORE void apply_kspace_filter_ROE1E2(const hoNDArray<double>& data, const hoNDArray<double>& fROE1E2, hoNDArray<double>& dataFiltered);\ntemplate EXPORTMRICORE void apply_kspace_filter_ROE1E2(const hoNDArray< std::complex<float> >& data, const hoNDArray< std::complex<float> >& fROE1E2, hoNDArray< std::complex<float> >& dataFiltered);\ntemplate EXPORTMRICORE void apply_kspace_filter_ROE1E2(const hoNDArray< std::complex<double> >& data, const hoNDArray< std::complex<double> >& fROE1E2, hoNDArray< std::complex<double> >& dataFiltered);\n\n// ------------------------------------------------------------------------\n\ntemplate <typename T> \nvoid apply_kspace_filter_ROE1E2(const hoNDArray<T>& data, const hoNDArray<T>& fRO, const hoNDArray<T>& fE1, const hoNDArray<T>& fE2, hoNDArray<T>& dataFiltered)\n{\n    try\n    {\n        GADGET_CHECK_THROW(data.get_size(0) == fRO.get_number_of_elements());\n        GADGET_CHECK_THROW(data.get_size(1) == fE1.get_number_of_elements());\n        GADGET_CHECK_THROW(data.get_size(2) == fE2.get_number_of_elements());\n\n        hoNDArray<T> fxyz;\n        compute_3d_filter(fRO, fE1, fE2, fxyz);\n\n        Gadgetron::multiply(data, fxyz, dataFiltered);\n    }\n    catch (...)\n    {\n        GADGET_THROW(\"Errors in apply_kspace_filter_ROE1E2(...) ... \");\n    }\n}\n\ntemplate EXPORTMRICORE void apply_kspace_filter_ROE1E2(const hoNDArray<float>& data, const hoNDArray<float>& fRO, const hoNDArray<float>& fE1, const hoNDArray<float>& fE2, hoNDArray<float>& dataFiltered);\ntemplate EXPORTMRICORE void apply_kspace_filter_ROE1E2(const hoNDArray<double>& data, const hoNDArray<double>& fRO, const hoNDArray<double>& fE1, const hoNDArray<double>& fE2, hoNDArray<double>& dataFiltered);\ntemplate EXPORTMRICORE void apply_kspace_filter_ROE1E2(const hoNDArray< std::complex<float> >& data, const hoNDArray< std::complex<float> >& fRO, const hoNDArray< std::complex<float> >& fE1, const hoNDArray< std::complex<float> >& fE2, hoNDArray< std::complex<float> >& dataFiltered);\ntemplate EXPORTMRICORE void apply_kspace_filter_ROE1E2(const hoNDArray< std::complex<double> >& data, const hoNDArray< std::complex<double> >& fRO, const hoNDArray< std::complex<double> >& fE1, const hoNDArray< std::complex<double> >& fE2, hoNDArray< std::complex<double> >& dataFiltered);\n\n// ------------------------------------------------------------------------\n\nvoid find_symmetric_sampled_region(size_t start, size_t end, size_t center, size_t& startSym, size_t& endSym)\n{\n    GADGET_CHECK_THROW(end >= start);\n    GADGET_CHECK_THROW(center >= start);\n    GADGET_CHECK_THROW(end >= center);\n\n    size_t halfSizeStart = center - start;\n    size_t halfSizeEnd = end - center;\n\n    if (halfSizeStart > halfSizeEnd)\n    {\n        startSym = center - halfSizeEnd;\n        endSym = center + halfSizeEnd;\n    }\n    else\n    {\n        startSym = center - halfSizeStart;\n        endSym = center + halfSizeStart;\n    }\n}\n\n// ------------------------------------------------------------------------\n\ntemplate<typename T>\nvoid compute_filter_SNR_unit_scale_factor(const hoNDArray<T>& filter, T& scalFactor)\n{\n    size_t ii, len;\n\n    len = filter.get_number_of_elements();\n    if (len == 0)\n    {\n        scalFactor = T(1.0);\n        return;\n    }\n\n    T sos(0.0);\n    for (ii = 0; ii<len; ii++)\n    {\n        sos += filter(ii)*filter(ii);\n    }\n\n    scalFactor = (T)(1.0 / std::sqrt(std::abs(sos) / len));\n}\n\ntemplate EXPORTMRICORE void compute_filter_SNR_unit_scale_factor(const hoNDArray<float>& filter, float& scalFactor);\ntemplate EXPORTMRICORE void compute_filter_SNR_unit_scale_factor(const hoNDArray<double>& filter, double& scalFactor);\n\ntemplate<> EXPORTMRICORE\nvoid compute_filter_SNR_unit_scale_factor(const hoNDArray< std::complex<float> >& filter, std::complex<float> & scalFactor)\n{\n    size_t ii, len;\n\n    len = filter.get_number_of_elements();\n    if (len == 0)\n    {\n        scalFactor = std::complex<float>(1.0);\n        return;\n    }\n\n    std::complex<float> sos(0.0);\n    for (ii = 0; ii<len; ii++)\n    {\n        sos += filter(ii)*std::conj(filter(ii));\n    }\n\n    scalFactor = (std::complex<float>)(1.0 / std::sqrt(std::abs(sos) / len));\n}\n\ntemplate<> EXPORTMRICORE\nvoid compute_filter_SNR_unit_scale_factor(const hoNDArray< std::complex<double> >& filter, std::complex<double> & scalFactor)\n{\n    size_t ii, len;\n\n    len = filter.get_number_of_elements();\n    if (len == 0)\n    {\n        scalFactor = std::complex<double>(1.0);\n        return;\n    }\n\n    std::complex<double> sos(0.0);\n    for (ii = 0; ii<len; ii++)\n    {\n        sos += filter(ii)*std::conj(filter(ii));\n    }\n\n    scalFactor = (std::complex<double>)(1.0 / std::sqrt(std::abs(sos) / len));\n}\n\n// ------------------------------------------------------------------------\n\n}\n", "meta": {"hexsha": "ff6a5969f79c3bf8f1816d3b58a4fcda6c931c83", "size": 37655, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "toolboxes/mri_core/mri_core_kspace_filter.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/mri_core/mri_core_kspace_filter.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/mri_core/mri_core_kspace_filter.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": 35.2574906367, "max_line_length": 289, "alphanum_fraction": 0.545239676, "num_tokens": 10075, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911056, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.48636266161338243}}
{"text": "/**\n    @file data.cpp\n    Helper functions for saving and loading data\n*/\n\n#include <utils/data.hpp>\n\n#include <fstream>\n#include <iostream>\n#include <string>\n#include <vector>\n#include <Eigen/Dense>\n\n/** Save matrix to .csv file. */\nvoid Data::save_matrix(const std::string& file_name, Eigen::MatrixXd matrix) {\n    const static Eigen::IOFormat CSVFormat(Eigen::FullPrecision,\n                                        Eigen::DontAlignCols, \", \", \"\\n\");\n    std::ofstream file(file_name); // open a file to write\n    if (file.is_open())\n    {\n        file << matrix.format(CSVFormat);\n        file.close();\n    }\n}\n\n/** Load matrix from .csv file */\nEigen::MatrixXd Data::load_matrix(const std::string& file_name) {\n    std::ifstream file(file_name); // open a file to read\n    if (!file.good()) {\n        std::cerr << \"File: \" << file_name << \" does not exist\" << std::endl;\n        exit(1);\n    }\n\n    // Read through file and extract all data elements\n    std::string row;\n    int i = 0; // row counter\n    std::string entry;\n    std::vector<double> entries;\n    while (std::getline(file, row)) {\n        std::stringstream row_stream(row);\n        while (std::getline(row_stream, entry, ',')) {\n            entries.push_back(std::stod(entry));\n        }\n        i++; // increment row counter\n    }\n\n    // Convert vector into matrix of proper shape\n    return Eigen::Map<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>(entries.data(), i, entries.size() / i);\n}\n\n/** Load vector from .csv file */\nEigen::VectorXd Data::load_vector(const std::string& file_name) {\n    Eigen::MatrixXd M = Data::load_matrix(file_name);\n    return Eigen::Map<Eigen::VectorXd>(M.data(), M.rows());\n}\n", "meta": {"hexsha": "56aae3da6b829bd45813dd50738c6642332e38ff", "size": 1705, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/utils/data.cpp", "max_stars_repo_name": "jlorenze/asl_fixedwing", "max_stars_repo_head_hexsha": "9cac7c8d31f5d1c9f7d059d4614d6b60f1a3fbef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-06-28T17:30:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T09:04:35.000Z", "max_issues_repo_path": "src/utils/data.cpp", "max_issues_repo_name": "jlorenze/asl_fixedwing", "max_issues_repo_head_hexsha": "9cac7c8d31f5d1c9f7d059d4614d6b60f1a3fbef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-08-31T16:22:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-31T16:36:15.000Z", "max_forks_repo_path": "src/utils/data.cpp", "max_forks_repo_name": "jlorenze/asl_fixedwing", "max_forks_repo_head_hexsha": "9cac7c8d31f5d1c9f7d059d4614d6b60f1a3fbef", "max_forks_repo_licenses": ["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.4464285714, "max_line_length": 133, "alphanum_fraction": 0.6146627566, "num_tokens": 414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6370307806984444, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.48636265794757744}}
{"text": "#ifndef MATRIX_TEMPLATE_HXX\n#define MATRIX_TEMPLATE_HXX\n\n#include <wali/Common.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <ostream>\n\nusing namespace boost::numeric::ublas;\n\nnamespace wali {\n  namespace domains {\n\n    template<typename ElementType>\n    Matrix<ElementType>::Matrix(BackingMatrix const & m)\n      : m_matrix(m)\n    {}\n\n\n    template<typename ElementType>\n    typename Matrix<ElementType>::BackingMatrix const &\n    Matrix<ElementType>::matrix() const\n    {\n      return m_matrix;\n    }\n\n\n    template<typename ElementType>\n    Matrix<ElementType>*\n    Matrix<ElementType>::zero_raw() const\n    {\n      zero_matrix<value_type> m(m_matrix.size1(), m_matrix.size2());\n      return new Matrix(m);\n    }\n\n\n    template<typename ElementType>\n    Matrix<ElementType>*\n    Matrix<ElementType>::one_raw() const\n    {\n      identity_matrix<value_type> m(m_matrix.size1(), m_matrix.size2());\n      return new Matrix(m);\n    }\n\n\n    template<typename ElementType>\n    Matrix<ElementType>*\n    Matrix<ElementType>::extend_raw(Matrix * that) const\n    {\n      return new Matrix(prod(this->matrix(), that->matrix()));\n    }\n\n\n    template<typename ElementType>\n    Matrix<ElementType>*\n    Matrix<ElementType>::combine_raw(Matrix * that) const\n    {\n      return new Matrix(this->matrix() + that->matrix());\n    }\n\n\n    template<typename ElementType>\n    bool\n    Matrix<ElementType>::equal(Matrix * that) const\n    {\n      fast_assert(this->matrix().size1() == that->matrix().size1());\n      fast_assert(this->matrix().size2() == that->matrix().size2());\n\n      if (this->matrix().size1() != that->matrix().size1()\n          || this->matrix().size2() != that->matrix().size2())\n      {\n        return false;\n      }\n\n      for (size_t row=0; row<matrix().size1(); ++row) {\n        for (size_t col=0; col<matrix().size2(); ++col) {\n          if (this->matrix()(row, col) != that->matrix()(row, col)) {\n            return false;\n          }\n        }\n      }\n\n      return true;\n    }\n\n\n    template<typename ElementType>\n    std::ostream &\n    Matrix<ElementType>::print(std::ostream & stream) const\n    {\n      stream << \"Matrix: \" << matrix();\n      return stream;\n    }\n\n\n    template<typename ElementType>\n    sem_elem_t\n    Matrix<ElementType>::one() const\n    {\n      return one_raw();\n    }\n\n\n    template<typename ElementType>\n    sem_elem_t\n    Matrix<ElementType>::zero() const\n    {\n      return zero_raw();\n    }\n\n\n    template<typename ElementType>\n    sem_elem_t\n    Matrix<ElementType>::extend(SemElem * se)\n    {\n      return extend_raw(down(se));\n    }\n\n\n    template<typename ElementType>\n    sem_elem_t\n    Matrix<ElementType>::combine(SemElem * se)\n    {\n      return combine_raw(down(se));\n    }\n\n\n    template<typename ElementType>\n    bool\n    Matrix<ElementType>::equal(SemElem * se) const\n    {\n      return equal(down(se));\n    }\n\n    template<typename ElementType>\n    Matrix<ElementType>*\n    Matrix<ElementType>::down(SemElem* se) const\n    {\n      Matrix* bm = dynamic_cast<Matrix*>(se);\n      fast_assert(bm != NULL);\n      return bm;\n    }\n\n  }\n}\n\n#endif /* MATRIX_TEMPLATE_HXX */\n\n// Yo, Emacs!\n// Local Variables:\n//   c-file-style: \"ellemtel\"\n//   c-basic-offset: 2\n// End:\n", "meta": {"hexsha": "1febf51437498f0b68ab6a9169dbfe90fa94ad7e", "size": 3217, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "AddOns/Domains/Source/wali/domains/matrix/Matrix_template.hxx", "max_stars_repo_name": "jusito/WALi-OpenNWA", "max_stars_repo_head_hexsha": "2bb4aca02c5a5d444fd038e8aa3eecd7d1ccbb99", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2015-03-07T17:25:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-04T20:17:00.000Z", "max_issues_repo_path": "AddOns/Domains/Source/wali/domains/matrix/Matrix_template.hxx", "max_issues_repo_name": "jusito/WALi-OpenNWA", "max_issues_repo_head_hexsha": "2bb4aca02c5a5d444fd038e8aa3eecd7d1ccbb99", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-03-03T05:58:55.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-03T12:26:10.000Z", "max_forks_repo_path": "AddOns/Domains/Source/wali/domains/matrix/Matrix_template.hxx", "max_forks_repo_name": "jusito/WALi-OpenNWA", "max_forks_repo_head_hexsha": "2bb4aca02c5a5d444fd038e8aa3eecd7d1ccbb99", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2015-09-25T17:44:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-18T18:25:38.000Z", "avg_line_length": 21.0261437908, "max_line_length": 72, "alphanum_fraction": 0.6117500777, "num_tokens": 759, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.48636265794757744}}
{"text": "///////////////////////////////////////////////////////////////////////////////\r\n// main.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#include <iostream>\r\n#include <algorithm>\r\n#include <boost/ref.hpp>\r\n#include <boost/bind.hpp>\r\n#include <boost/array.hpp>\r\n#include <boost/foreach.hpp>\r\n#include <boost/accumulators/accumulators.hpp>\r\n#include <boost/accumulators/statistics.hpp>\r\n\r\nusing namespace boost;\r\nusing namespace boost::accumulators;\r\n\r\n// Helper that uses BOOST_FOREACH to display a range of doubles\r\ntemplate<typename Range>\r\nvoid output_range(Range const &rng)\r\n{\r\n    bool first = true;\r\n    BOOST_FOREACH(double d, rng)\r\n    {\r\n        if(!first) std::cout << \", \";\r\n        std::cout << d;\r\n        first = false;\r\n    }\r\n    std::cout << '\\n';\r\n}\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// example1\r\n//\r\n//  Calculate some useful stats using accumulator_set<> and std::for_each()\r\n//\r\nvoid example1()\r\n{\r\n    accumulator_set<\r\n        double\r\n      , stats<tag::min, tag::mean(immediate), tag::sum, tag::moment<2> >\r\n    > acc;\r\n\r\n    boost::array<double, 4> data = {0., 1., -1., 3.14159};\r\n\r\n    // std::for_each pushes each sample into the accumulator one at a\r\n    // time, and returns a copy of the accumulator.\r\n    acc = std::for_each(data.begin(), data.end(), acc);\r\n\r\n    // The following would be equivalent, and could be more efficient\r\n    // because it doesn't pass and return the entire accumulator set\r\n    // by value.\r\n    //std::for_each(data.begin(), data.end(), bind<void>(ref(acc), _1));\r\n\r\n    std::cout << \"  min\"\"(acc)        = \" << (min)(acc) << std::endl; // Extra quotes are to prevent complaints from Boost inspect tool\r\n    std::cout << \"  mean(acc)       = \" << mean(acc) << std::endl;\r\n\r\n    // since mean depends on count and sum, we can get their results, too.\r\n    std::cout << \"  count(acc)      = \" << count(acc) << std::endl;\r\n    std::cout << \"  sum(acc)        = \" << sum(acc) << std::endl;\r\n    std::cout << \"  moment<2>(acc)  = \" << accumulators::moment<2>(acc) << std::endl;\r\n}\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// example2\r\n//\r\n//  Calculate some tail statistics. This demonstrates how to specify\r\n//  constructor and accumulator parameters. Note that the tail statistics\r\n//  return multiple values, which are returned in an iterator_range.\r\n//\r\n//  It pushes data in and displays the intermediate results to demonstrate\r\n//  how the tail statistics are updated.\r\nvoid example2()\r\n{\r\n    // An accumulator which tracks the right tail (largest N items) and\r\n    // some data that are covariate with them. N == 4.\r\n    accumulator_set<\r\n        double\r\n      , stats<tag::tail_variate<double, tag::covariate1, right> >\r\n    > acc(tag::tail<right>::cache_size = 4);\r\n\r\n    acc(2.1, covariate1 = .21);\r\n    acc(1.1, covariate1 = .11);\r\n    acc(2.1, covariate1 = .21);\r\n    acc(1.1, covariate1 = .11);\r\n\r\n    std::cout << \"  tail            = \"; output_range(tail(acc));\r\n    std::cout << \"  tail_variate    = \"; output_range(tail_variate(acc));\r\n    std::cout << std::endl;\r\n\r\n    acc(21.1, covariate1 = 2.11);\r\n    acc(11.1, covariate1 = 1.11);\r\n    acc(21.1, covariate1 = 2.11);\r\n    acc(11.1, covariate1 = 1.11);\r\n\r\n    std::cout << \"  tail            = \"; output_range(tail(acc));\r\n    std::cout << \"  tail_variate    = \"; output_range(tail_variate(acc));\r\n    std::cout << std::endl;\r\n\r\n    acc(42.1, covariate1 = 4.21);\r\n    acc(41.1, covariate1 = 4.11);\r\n    acc(42.1, covariate1 = 4.21);\r\n    acc(41.1, covariate1 = 4.11);\r\n\r\n    std::cout << \"  tail            = \"; output_range(tail(acc));\r\n    std::cout << \"  tail_variate    = \"; output_range(tail_variate(acc));\r\n    std::cout << std::endl;\r\n\r\n    acc(32.1, covariate1 = 3.21);\r\n    acc(31.1, covariate1 = 3.11);\r\n    acc(32.1, covariate1 = 3.21);\r\n    acc(31.1, covariate1 = 3.11);\r\n\r\n    std::cout << \"  tail            = \"; output_range(tail(acc));\r\n    std::cout << \"  tail_variate    = \"; output_range(tail_variate(acc));\r\n}\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// example3\r\n//\r\n//  Demonstrate how to calculate weighted statistics. This example demonstrates\r\n//  both a simple weighted statistical calculation, and a more complicated\r\n//  calculation where the weight statistics are calculated and stored in an\r\n//  external weight accumulataor.\r\nvoid example3()\r\n{\r\n    // weight == double\r\n    double w = 1.;\r\n\r\n    // Simple weighted calculation\r\n    {\r\n        // stats that depend on the weight are made external\r\n        accumulator_set<double, stats<tag::mean>, double> acc;\r\n\r\n        acc(0., weight = w);\r\n        acc(1., weight = w);\r\n        acc(-1., weight = w);\r\n        acc(3.14159, weight = w);\r\n\r\n        std::cout << \"  mean(acc)       = \" << mean(acc) << std::endl;\r\n    }\r\n\r\n    // Weighted calculation with an external weight accumulator\r\n    {\r\n        // stats that depend on the weight are made external\r\n        accumulator_set<double, stats<tag::mean>, external<double> > acc;\r\n\r\n        // Here's an external weight accumulator\r\n        accumulator_set<void, stats<tag::sum_of_weights>, double> weight_acc;\r\n\r\n        weight_acc(weight = w); acc(0., weight = w);\r\n        weight_acc(weight = w); acc(1., weight = w);\r\n        weight_acc(weight = w); acc(-1., weight = w);\r\n        weight_acc(weight = w); acc(3.14159, weight = w);\r\n\r\n        std::cout << \"  mean(acc)       = \" << mean(acc, weights = weight_acc) << std::endl;\r\n    }\r\n}\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// main\r\nint main()\r\n{\r\n    std::cout << \"Example 1:\\n\";\r\n    example1();\r\n\r\n    std::cout << \"\\nExample 2:\\n\";\r\n    example2();\r\n\r\n    std::cout << \"\\nExample 3:\\n\";\r\n    example3();\r\n\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "0eb3ebe4d95257762be5d948471c8f603cb46a5a", "size": 5976, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/accumulators/example/main.cpp", "max_stars_repo_name": "zyiacas/boost-doc-zh", "max_stars_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 198.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T05:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:46:46.000Z", "max_issues_repo_path": "libs/accumulators/example/main.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": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-03-19T08:23:23.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-24T07:48:47.000Z", "max_forks_repo_path": "libs/accumulators/example/main.cpp", "max_forks_repo_name": "sdfict/boost-doc-zh", "max_forks_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 33.7627118644, "max_line_length": 136, "alphanum_fraction": 0.5505354752, "num_tokens": 1523, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081925, "lm_q2_score": 0.7090191460821871, "lm_q1q2_score": 0.48635129684545025}}
{"text": "/**\n *  testReachset.cpp\n *\n *  Test reachable set computation of the Moore-Greitzer engine model.\n *\n *  Created by Yinan Li on June 9, 2020.\n *  Hybrid Systems Group, University of Waterloo.\n */\n\n\n#include <iostream>\n#include <cmath>\n\n#include <array>\n#include <boost/numeric/odeint.hpp>\n\n#include \"src/abstraction.hpp\"\n#include \"src/system.hpp\"\n#include \"src/csolver.h\"\n#include \"src/matlabio.h\"\n\ntypedef std::array<double, 3> state_type;\n\ndouble a = 1./3.5;\ndouble B = 2.0;\ndouble H = 0.18;\ndouble W = 0.25;\ndouble lc = 8.0;\ndouble cx = 1.0/lc;\ndouble cy = 1.0/(4*lc*B*B);\ndouble aH = a+H;\ndouble H2 = H/(2.0*W*W*W);\ndouble W2 = 3*W*W;\n\n/* user defined dynamics */\nstruct mgode {\n    static const int n = 3;  // system dimension\n    static const int nu = 2;  // control dimension\n\n    /* template constructor\n     * @param[out] dx\n     * @param[in] x\n     * @param u\n     */\n    template<typename S>\n    mgode(S *dx, const S *x, rocs::Rn u) {\n\tdx[0] = cx * (aH+H2*(x[0]-W)*(W2-(x[0]-W)*(x[0]-W)) - x[1]) + u[0];\n\tdx[1] = cy * (x[0] - x[2]*sqrt(x[1]));\n\tdx[2] = u[1];\n    }\n};\nstruct engine_vf {\n    rocs::Rn _u;\n    engine_vf(rocs::Rn u) : _u(u) {}\n    void operator()(state_type &x, state_type &dxdt, double t) const {\n\tdxdt[0] = cx * (aH+H2*(x[0]-W)*(W2-(x[0]-W)*(x[0]-W)) - x[1]) + _u[0];\n\tdxdt[1] = cy * (x[0] - x[2]*sqrt(x[1]));\n\tdxdt[2] = _u[1];\n    }\n};\n\nstruct mgode2 {\n\n    static const int n = 2;  // system dimension\n    static const int nu = 2;  // control dimension\n    \n    /* template constructor\n     * @param[out] dx\n     * @param[in] x\n     * @param u\n     */\n    template<typename S>\n    mgode2(S *dx, const S *x, rocs::Rn u) {\n\tdx[0] = cx * (aH+H2*(x[0]-W)*(W2-(x[0]-W)*(x[0]-W)) - x[1]) + u[0];\n\tdx[1] = cy * (x[0] - u[1]*sqrt(x[1]));\n    }\n};\nstruct engine2d_ode {\n    rocs::Rn _u;\n    engine2d_ode(rocs::Rn u) : _u(u) {}\n    void operator()(rocs::Rn &x, rocs::Rn &dxdt, double t) const {\n\tdxdt[0] = cx * (aH+H2*(x[0]-W)*(W2-(x[0]-W)*(x[0]-W)) - x[1]) + _u[0];\n\tdxdt[1] = cy * (x[0] - _u[1]*sqrt(x[1]));\n    }\n};\n\n\nint main() {\n\n    // /* set the state space */\n    // double xlb[3]{0, 0, 0.5};\n    // double xub[3]{1, 1, 0.8};\n    \n    // /* set the control values */\n    // // double L = 0.0003;\n    // // double ulb[2]{-5, -L};\n    // // double uub[2]{5, L};\n    // // double mu[2]{1, L/10};\n    // double Lmu = 0.01;\n    // double Lu = 0.05;\n    // double ulb[2]{-Lu, -Lmu};\n    // double uub[2]{Lu, Lmu};\n    // double mu[2]{Lu/5, 2*Lmu/5};\n\n    // /* set the sampling time and disturbance */\n    // double t = 0.1;\n    // double delta = 0.01;\n    // /* parameters for computing the flow */\n    // int kmax = 10;\n    // double tol = 0.01;\n    // double alpha = 0.5;\n    // double beta = 2;\n    // rocs::params controlparams(kmax, tol, alpha, beta);\n    \n    // /* define the control system */\n    // rocs::CTCntlSys<mgode> engine(\"Moore-Greitzer\", t, mgode::n, mgode::nu,\n    // \t\t\t\t  delta, &controlparams);\n    // engine.init_workspace(xlb, xub);\n    // engine.init_inputset(mu, ulb, uub);\n    // engine.allocate_flows();\n\n    \n    // /* test if reachable set covers the nominal trajectory */\n    // /* compute reachable set */\n    // double dt{0.001};\n    // // state_type y{0.5039, 0.6605, 0.62};\n    // state_type y{1.526/2, 0.5, 0.65};\n    // // double e[3]{0.2, 0.5, 0.1};\n    // // rocs::ivec x0 = {rocs::interval(y[0]-e[0], y[0]+e[0]),\n    // // \t\t     rocs::interval(y[1]-e[1], y[1]+e[1]),\n    // // \t\t     rocs::interval(y[2]-e[2], y[2]+e[2])};\n    // rocs::ivec x0 = {rocs::interval(0.526, 1),\n    // \t\t     rocs::interval(0.001, 1),\n    // \t\t     rocs::interval(0.5, 0.8)};\n    // std::vector<rocs::ivec> x(engine._ugrid._nv, rocs::ivec(3));\n    // std::cout << \"The initial interval: \" << x0 << '\\n';\n    // std::cout << \"The integrating time: \" << t << '\\n';\n    // engine.get_reach_set(x, x0);\n    \n    // for (size_t i = 0; i < x.size(); ++i) {\n    // \t/* integrate the nominal trajectory */\n    // \tstate_type y{1.526/2, 0.5, 0.65};\n    // \trocs::Rn u(engine._ugrid._data[i]);\n    // \tboost::numeric::odeint::runge_kutta_cash_karp54<state_type> rk45;\n    // \tboost::numeric::odeint::integrate_const(rk45, engine_vf(u),\n    // \t\t\t\t\t\ty, 0.0, t, dt);\n    // \tstd::cout << \"x(t)= [\" << y[0] << ','<< y[1] << ',' << y[2] << \"]\\n\";\n    // \tstd::cout << \"R(t, x0, [\" << engine._ugrid._data[i][0] << ','\n    // \t\t  << engine._ugrid._data[i][1] << \"])= \";\n    // \tstd::cout << x[i] <<'\\n';\n    // \tstd::cout << \"Check: \";\n    // \tfor (int j = 0; j < 3; ++j) {\n    // \t    if (y[j] > x[i][j].getinf() && y[j] < x[i][j].getsup())\n    // \t\tstd::cout << true << ' ';\n    // \t    else\n    // \t\tstd::cout << false << ' ';\n    // \t}\n    // \tstd::cout << '\\n';\n    // }\n    \n    // engine.release_flows();\n\n    \n    /* set the state space */\n    const int xdim = 2;\n    double xlb[]{0.44, 0.6};\n    double xub[]{0.54, 0.7};\n    \n    /* set the control values */\n    // double Lmu = 0.01;\n    double Lu = 0.05;\n    double ulb[]{-Lu, 0.5};\n    double uub[]{Lu, 0.8};\n    double mu[]{Lu/5, 0.01};\n\n    /* set the sampling time and disturbance */\n    double delta = 0.01;\n    /* parameters for computing the flow */\n    int kmax = 10;\n    double tol = 0.01;\n    double alpha = 0.5;\n    double beta = 2;\n    rocs::params controlparams(kmax, tol, alpha, beta);\n    \n    /* define the control system */\n    double t= 0.1;\n    rocs::CTCntlSys<mgode2> engine(\"Moore-Greitzer\", t, mgode2::n, mgode2::nu,\n\t\t\t\t  delta, &controlparams);\n    engine.init_workspace(xlb, xub);\n    engine.init_inputset(mu, ulb, uub);\n    engine.allocate_flows();\n\n    double eta[xdim]{0.00018, 0.00018};\n    std::vector<rocs::ivec> x(engine._ugrid._nv, rocs::ivec(xdim));\n\n    /**\n     * Test if reachable set covers the nominal trajectory \n     */\n    // /* compute reachable set */\n    // double dt{0.001};\n    // rocs::Rn y{0.599, 0.688};\n    // rocs::ivec x0 = {rocs::interval(y[0]-eta[0], y[0]+eta[0]),\n    // \t\t     rocs::interval(y[1]-eta[1], y[1]+eta[1])};\n    // std::cout << \"The initial interval: \" << x0 << '\\n';\n    // std::cout << \"The integrating time: \" << t << '\\n';\n    // engine.get_reach_set(x, x0);\n\n    // boost::numeric::odeint::runge_kutta_cash_karp54<rocs::Rn> rk45;\n    // for (size_t i = 0; i < x.size(); ++i) {\n    // \t/* integrate the nominal trajectory */\n    // \trocs::Rn y{0.599, 0.688};\n    // \trocs::Rn u(engine._ugrid._data[i]);\n    // \tboost::numeric::odeint::integrate_const(rk45, engine2d_ode(u),\n    // \t\t\t\t\t\ty, 0.0, t, dt);\n    // \tstd::cout << \"x(t)= [\" << y[0] << ','<< y[1] << \"]\\n\";\n    // \tstd::cout << \"R(t, x0, [\" << engine._ugrid._data[i][0] << ','\n    // \t\t  << engine._ugrid._data[i][1] << \"])= \";\n    // \tstd::cout << x[i] <<'\\n';\n    // \tstd::cout << \"Check: \";\n    // \tfor (int j = 0; j < xdim; ++j) {\n    // \t    if (y[j] > x[i][j].getinf() && y[j] < x[i][j].getsup())\n    // \t\tstd::cout << true << ' ';\n    // \t    else\n    // \t\tstd::cout << false << ' ';\n    // \t}\n    // \tstd::cout << '\\n';\n    // }\n\n\n    /**\n     * Test if there is a box inside the goal area can \n     * stay inside the goal area \n     */\n    rocs::abstraction< rocs::CTCntlSys<mgode2> > abst(&engine);\n    abst.init_state(eta, xlb, xub);\n    double e = 0.003;\n    double goal[][2]{{0.5039-e, 0.5039+e}, {0.6605-e, 0.6605+e}};\n    rocs::ivec G{rocs::interval(0.5039-e, 0.5039+e),\n\t\t rocs::interval(0.6605-e, 0.6605+e)};\n    \n    double c1= eta[0]/2.0; //+1e-10;\n    double c2= eta[1]/2.0; //+1e-10;\n    // std::vector<rocs::ivec> y(abst._x._dim);\n    rocs::Rn x_test{0.0, 0.0};\n    std::cout << \"Boxes in goal that stay in goal:\\n\";\n    for(size_t i = 0; i < abst._x._nv; ++i) {\n\tabst._x.id_to_val(x_test, i);\n\tif(goal[0][0] <= (x_test[0]-c1) && (x_test[0]+c1) <= goal[0][1] && \n\t   goal[1][0] <= (x_test[1]-c2) && (x_test[1]+c2) <= goal[1][1]) {\n\t    rocs::ivec x0{rocs::interval(x_test[0]-eta[0], x_test[0]+eta[0]),\n\t\t\t  rocs::interval(x_test[1]-eta[1], x_test[1]+eta[1])};\n\t    engine.get_reach_set(x, x0);\n\t    for (size_t i = 0; i < x.size(); ++i) {\n\t\tif(G.isin(x[i])) {\n\t\t    std::cout << \"x=\" << x[i] << \", u=\" << i << '\\n';\n\t\t}\n\t    }\n\t}\n    }\n\n    engine.release_flows();\n    \n    return 0;\n}\n", "meta": {"hexsha": "d476057ada8d106cfd476b08939701f16c6dc415", "size": 8127, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/Moore-Greitzer/testReachset.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/Moore-Greitzer/testReachset.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/Moore-Greitzer/testReachset.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.6679245283, "max_line_length": 78, "alphanum_fraction": 0.508920881, "num_tokens": 3114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.4863351981160984}}
{"text": "/*\n * Data.hpp\n *\n *  Created on: 05 Feb 2018\n *      Author: Fabian Meyer\n */\n\n#ifndef SLAM_DATA_HPP_\n#define SLAM_DATA_HPP_\n\n#include <Eigen/Dense>\n\nnamespace slam\n{\n    // 2D pose (x, y, theta)\n    typedef Eigen::Vector3d Pose;\n    typedef Eigen::Matrix3d PoseCov;\n\n    // range bearing measurement (r, theta, c)\n    typedef Eigen::Vector2d Measurement;\n\n    // observation with measurement and data assoc\n    typedef struct {\n        Measurement m;\n        size_t c;\n    } Observation;\n\n    // odometry (r1, t, r2)\n    typedef Eigen::Vector3d Odometry;\n\n    // 2D position (x, y)\n    typedef Eigen::Vector2d Position;\n    typedef Eigen::Matrix2d PositionCov;\n\n    typedef struct {\n        Odometry odom;\n        std::vector<Observation> observ;\n    } Data;\n\n    void loadData(const std::string &filename, std::vector<Data> &data);\n    void loadWorld(const std::string &filename, std::vector<Position> &landmarks);\n\n}\n\n#endif\n", "meta": {"hexsha": "31f526806458a7d7c3ac68f2d3034c47ae2c8520", "size": 929, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Data.hpp", "max_stars_repo_name": "Rookfighter/landmark-slam", "max_stars_repo_head_hexsha": "0fa1a65ba94eaa43a3a9ec577f89a628f41780ca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-12-05T01:34:55.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-05T01:34:55.000Z", "max_issues_repo_path": "src/Data.hpp", "max_issues_repo_name": "Rookfighter/landmark-slam", "max_issues_repo_head_hexsha": "0fa1a65ba94eaa43a3a9ec577f89a628f41780ca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Data.hpp", "max_forks_repo_name": "Rookfighter/landmark-slam", "max_forks_repo_head_hexsha": "0fa1a65ba94eaa43a3a9ec577f89a628f41780ca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-07-24T04:59:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-24T04:59:07.000Z", "avg_line_length": 20.1956521739, "max_line_length": 82, "alphanum_fraction": 0.6480086114, "num_tokens": 248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.48633518780295415}}
{"text": "#define BOOST_TEST_MODULE test_instrument\n\n#include <boost/test/unit_test.hpp>\n#include <Leg/FloatingLeg.h>\n#include <Instrument/Asset.h>\n#include \"Instrument/Bond.h\"\n#include \"Instrument/Swap.h\"\n\nBOOST_AUTO_TEST_SUITE(instrument_test_suite)\n\n    BOOST_AUTO_TEST_CASE(bond_price) {\n        BOOST_TEST_MESSAGE(\"using tolerances within checks.\");\n\n        const double notional = 100;\n        const double rate = 5.0 / 100;\n        std::vector<boost::gregorian::date> referenceDates{};\n        referenceDates.push_back(boost::gregorian::from_string(\"2016-04-01\"));\n        referenceDates.push_back(boost::gregorian::from_string(\"2016-10-03\"));\n        referenceDates.push_back(boost::gregorian::from_string(\"2017-04-03\"));\n        referenceDates.push_back(boost::gregorian::from_string(\"2017-10-02\"));\n        referenceDates.push_back(boost::gregorian::from_string(\"2018-04-02\"));\n\n        Actual_360 actualCalc = Actual_360();\n\n        std::map<boost::gregorian::date, double> m_mapZeroRates{};\n        m_mapZeroRates[boost::gregorian::from_string(\"2016-10-03\")] = 0.04743305323463213;\n        m_mapZeroRates[boost::gregorian::from_string(\"2017-04-03\")] = 0.05;\n        m_mapZeroRates[boost::gregorian::from_string(\"2017-10-02\")] = 0.051;\n        m_mapZeroRates[boost::gregorian::from_string(\"2018-04-02\")] = 0.052;\n        ZeroCouponCurve zeroCouponCurve{m_mapZeroRates};\n\n        FixedLeg myLeg{notional, rate, referenceDates, actualCalc, zeroCouponCurve};\n        Bond myBond{myLeg};\n\n        double calculated_value = myBond.price();\n        double theoretical_value = 9.5228417749383200;\n        //BOOST_TEST_MESSAGE(\" - Calculated Value: \" << calculated_values);\n        //BOOST_TEST_MESSAGE(\" - Expected Value: \" << expected_values);\n        BOOST_TEST(theoretical_value == calculated_value, boost::test_tools::tolerance(1e-15));\n    }\n\n    BOOST_AUTO_TEST_CASE(swap_price) {\n        BOOST_TEST_MESSAGE(\"using tolerances within checks.\");\n\n        const double notional = 100000000;\n        const double rate = 5.0 / 100;\n        const int periodsPerYear = 2;\n        std::vector<boost::gregorian::date> referenceDates{};\n        referenceDates.push_back(boost::gregorian::from_string(\"2016-04-01\"));\n        referenceDates.push_back(boost::gregorian::from_string(\"2016-10-03\"));\n        referenceDates.push_back(boost::gregorian::from_string(\"2017-04-03\"));\n        referenceDates.push_back(boost::gregorian::from_string(\"2017-10-02\"));\n        referenceDates.push_back(boost::gregorian::from_string(\"2018-04-02\"));\n\n        Actual_360 actualCalc = Actual_360();\n\n        std::map<boost::gregorian::date, double> m_mapZeroRates{};\n        m_mapZeroRates[boost::gregorian::from_string(\"2016-10-03\")] = 0.04743305323463213;\n        m_mapZeroRates[boost::gregorian::from_string(\"2017-04-03\")] = 0.05;\n        m_mapZeroRates[boost::gregorian::from_string(\"2017-10-02\")] = 0.051;\n        m_mapZeroRates[boost::gregorian::from_string(\"2018-04-02\")] = 0.052;\n        ZeroCouponCurve zeroCouponCurve{m_mapZeroRates};\n\n        FixedLeg payingLeg{notional, rate, referenceDates, actualCalc, zeroCouponCurve};\n        FloatingLeg receivingLeg{notional, referenceDates, actualCalc, zeroCouponCurve, periodsPerYear};\n\n        Swap mySwap{receivingLeg, payingLeg};\n\n        double calculated_value = mySwap.price();\n        double theoretical_value = 495775.94;\n        //BOOST_TEST_MESSAGE(\" - Calculated Value: \" << calculated_values);\n        //BOOST_TEST_MESSAGE(\" - Expected Value: \" << expected_values);\n        BOOST_TEST(theoretical_value == calculated_value, boost::test_tools::tolerance(1e-2));\n    }\n\n    BOOST_AUTO_TEST_CASE(asset_getVolatility) {\n        BOOST_TEST_MESSAGE(\"using tolerances within checks.\");\n\n\n        const double spot_price = 50.0;\n        double volatility = 62.0 / 100;\n\n        Asset underlyingAsset{spot_price, volatility};\n\n        double calculated_value = underlyingAsset.getVolatility();\n        double theoretical_value = 0.62;\n\n        BOOST_TEST(theoretical_value == calculated_value, boost::test_tools::tolerance(1e-2));\n    }\n\n    BOOST_AUTO_TEST_CASE(asset_getPrice) {\n        BOOST_TEST_MESSAGE(\"using tolerances within checks.\");\n\n\n        const double spot_price = 50.0;\n        double volatility = 62.0 / 100;\n\n        Asset underlyingAsset{spot_price, volatility};\n\n        double calculated_value = underlyingAsset.price();\n        double theoretical_value = 50.0;\n\n        BOOST_TEST(theoretical_value == calculated_value, boost::test_tools::tolerance(1e-2));\n    }\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "f56abf43bc656ed6b75bc62674887b6d3b519523", "size": 4542, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "assignment/src/Instrument/tests/test.cpp", "max_stars_repo_name": "paulochang/finance_valuator_extended", "max_stars_repo_head_hexsha": "1c9f638d0b1dd888b4a1010c47c4e1999ed6f5bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "assignment/src/Instrument/tests/test.cpp", "max_issues_repo_name": "paulochang/finance_valuator_extended", "max_issues_repo_head_hexsha": "1c9f638d0b1dd888b4a1010c47c4e1999ed6f5bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "assignment/src/Instrument/tests/test.cpp", "max_forks_repo_name": "paulochang/finance_valuator_extended", "max_forks_repo_head_hexsha": "1c9f638d0b1dd888b4a1010c47c4e1999ed6f5bc", "max_forks_repo_licenses": ["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.4485981308, "max_line_length": 104, "alphanum_fraction": 0.6930867459, "num_tokens": 1142, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.48633518780295415}}
{"text": "#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <vector>\n#include <numeric>\n\n#include <boost/scope_exit.hpp>\n\n#include <amgcl/mpi/util.hpp>\n#include <amgcl_mpi.h>\n\n#include \"domain_partition.hpp\"\n\ndouble STDCALL constant_deflation(int, ptrdiff_t, void*) {\n    return 1;\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    int rank, size;\n    MPI_Comm_rank(MPI_COMM_WORLD, &rank);\n    MPI_Comm_size(MPI_COMM_WORLD, &size);\n\n    if (rank == 0)\n        std::cout << \"World size: \" << size << std::endl;\n\n    const ptrdiff_t n  = argc > 1 ? atoi(argv[1]) : 1024;\n    const ptrdiff_t n2 = n * n;\n\n    // Partition\n    boost::array<ptrdiff_t, 2> lo = { {0, 0} };\n    boost::array<ptrdiff_t, 2> hi = { {n - 1, n - 1} };\n\n    domain_partition<2> part(lo, hi, size);\n    ptrdiff_t chunk = part.size( rank );\n\n    std::vector<ptrdiff_t> domain(size + 1);\n    MPI_Allgather(\n            &chunk, 1, amgcl::mpi::datatype<ptrdiff_t>(),\n            &domain[1], 1, amgcl::mpi::datatype<ptrdiff_t>(),\n            MPI_COMM_WORLD);\n    std::partial_sum(domain.begin(), domain.end(), domain.begin());\n\n    ptrdiff_t chunk_start = domain[rank];\n    ptrdiff_t chunk_end   = domain[rank + 1];\n\n    std::vector<ptrdiff_t> renum(n2);\n    for(ptrdiff_t j = 0, idx = 0; j < n; ++j) {\n        for(ptrdiff_t i = 0; i < n; ++i, ++idx) {\n            boost::array<ptrdiff_t, 2> p = {{i, j}};\n            std::pair<int,ptrdiff_t> v = part.index(p);\n            renum[idx] = domain[v.first] + v.second;\n        }\n    }\n\n    // Assemble\n    std::vector<ptrdiff_t> ptr;\n    std::vector<ptrdiff_t> col;\n    std::vector<double>    val;\n    std::vector<double>    rhs;\n\n    ptr.reserve(chunk + 1);\n    col.reserve(chunk * 5);\n    val.reserve(chunk * 5);\n    rhs.reserve(chunk);\n\n    ptr.push_back(0);\n\n    const double hinv = (n - 1);\n    const double h2i  = (n - 1) * (n - 1);\n    for(ptrdiff_t j = 0, idx = 0; j < n; ++j) {\n        for(ptrdiff_t i = 0; i < n; ++i, ++idx) {\n            if (renum[idx] < chunk_start || renum[idx] >= chunk_end) continue;\n\n            if (j > 0)  {\n                col.push_back(renum[idx - n]);\n                val.push_back(-h2i);\n            }\n\n            if (i > 0) {\n                col.push_back(renum[idx - 1]);\n                val.push_back(-h2i - hinv);\n            }\n\n            col.push_back(renum[idx]);\n            val.push_back(4 * h2i + hinv);\n\n            if (i + 1 < n) {\n                col.push_back(renum[idx + 1]);\n                val.push_back(-h2i);\n            }\n\n            if (j + 1 < n) {\n                col.push_back(renum[idx + n]);\n                val.push_back(-h2i);\n            }\n\n            rhs.push_back(1);\n            ptr.push_back( col.size() );\n        }\n    }\n\n    // Setup\n    amgclHandle prm    = amgcl_params_create();\n\n    amgcl_params_sets(prm, \"local.coarsening.type\", \"smoothed_aggregation\");\n    amgcl_params_sets(prm, \"local.relax.type\", \"spai0\");\n    amgcl_params_sets(prm, \"isolver.type\", \"bicgstabl\");\n#ifdef AMGCL_HAVE_PASTIX\n    amgcl_params_sets(prm, \"dsolver.type\", \"pastix\");\n#else\n    amgcl_params_sets(prm, \"dsolver.type\", \"skyline_lu\");\n#endif\n\n    amgclHandle solver = amgcl_mpi_create(\n            MPI_COMM_WORLD,\n            chunk, ptr.data(), col.data(), val.data(),\n            1, constant_deflation, NULL, prm\n            );\n\n    // Solve\n    std::vector<double> x(chunk, 0);\n    conv_info cnv = amgcl_mpi_solve(solver, rhs.data(), x.data());\n\n    std::cout << \"Iterations: \" << cnv.iterations << std::endl\n              << \"Error:      \" << cnv.residual   << std::endl;\n\n    // Clean up\n    amgcl_mpi_destroy(solver);\n    amgcl_params_destroy(prm);\n\n    if (n <= 4096) {\n        if (rank == 0) {\n            std::vector<double> X(n2);\n            std::copy(x.begin(), x.end(), X.begin());\n\n            for(int i = 1; i < size; ++i)\n                MPI_Recv(&X[domain[i]], domain[i+1] - domain[i], MPI_DOUBLE, i, 42, MPI_COMM_WORLD, MPI_STATUS_IGNORE);\n\n            std::ofstream f(\"out.dat\", std::ios::binary);\n            int m = n2;\n            f.write((char*)&m, sizeof(int));\n            for(ptrdiff_t i = 0; i < n2; ++i)\n                f.write((char*)&X[renum[i]], sizeof(double));\n        } else {\n            MPI_Send(x.data(), chunk, MPI_DOUBLE, 0, 42, MPI_COMM_WORLD);\n        }\n    }\n}\n", "meta": {"hexsha": "a81ec872fd8fc1993004d358b7c7d1aac95459b7", "size": 4438, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/mpi/call_mpi_lib.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/call_mpi_lib.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/call_mpi_lib.cpp", "max_forks_repo_name": "tenglongcong/amgcl", "max_forks_repo_head_hexsha": "61948e1a49c1cbc9fdb68c92d532c8b70e021516", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 92.0, "max_forks_repo_forks_event_min_datetime": "2015-01-04T06:11:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T09:49:12.000Z", "avg_line_length": 28.6322580645, "max_line_length": 119, "alphanum_fraction": 0.5358269491, "num_tokens": 1308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.48633518780295415}}
{"text": "// Copyright (c) 2019 fortiss GmbH, Julian Bernhard, Klemens Esterle, Patrick Hart, Tobias Kessler\n//\n// This work is licensed under the terms of the MIT license.\n// For a copy, see <https://opensource.org/licenses/MIT>.\n\n\n#include <Eigen/Core>\n#include \"gtest/gtest.h\"\n\n#include \"modules/geometry/polygon.hpp\"\n#include \"modules/geometry/line.hpp\"\n#include \"modules/geometry/commons.hpp\"\n#include \"modules/models/behavior/idm/idm_classic.hpp\"\n#include \"modules/commons/params/default_params.hpp\"\n#include \"modules/world/observed_world.hpp\"\n#include \"modules/models/execution/interpolation/interpolate.hpp\"\n#include \"modules/models/behavior/constant_velocity/constant_velocity.hpp\"\n#include \"modules/models/tests/make_test_world.hpp\"\n\nusing namespace modules::models::dynamic;\nusing namespace modules::models::execution;\nusing namespace modules::commons;\nusing namespace modules::models::behavior;\nusing namespace modules::world::map;\nusing namespace modules::models::dynamic;\nusing namespace modules::world;\nusing namespace modules::geometry;\nusing namespace modules::models::tests;\n\n\n\nTEST(free_road_term, behavior_idm_classic) {\n  DefaultParams params;\n  BehaviorIDMClassic behavior(&params);\n  const float desired_velocity = behavior.get_desired_velocity();\n  const float max_acceleration = behavior.get_max_acceleration();\n  const int exponent = behavior.get_exponent();\n\n  float ego_velocity = desired_velocity, rel_distance = 7.0, velocity_difference=0.0;\n  auto observed_world = make_test_observed_world(0,rel_distance, ego_velocity, velocity_difference);\n  double idm_acceleration  = behavior.CalculateLongitudinalAcceleration(observed_world);\n\n  // no vehicle is in front only free road term should give acceleration\n  double desired_acceleration = max_acceleration*(1-pow(ego_velocity/desired_velocity, exponent));\n  EXPECT_NEAR(idm_acceleration, desired_acceleration, 0.0001);\n\n  ego_velocity = desired_velocity+10;\n  observed_world = make_test_observed_world(0,rel_distance, ego_velocity, velocity_difference);\n  idm_acceleration  = behavior.CalculateLongitudinalAcceleration(observed_world);\n\n  // no vehicle is in front only free road term should give acceleration\n  desired_acceleration = max_acceleration*(1-pow(ego_velocity/desired_velocity, exponent));\n  EXPECT_NEAR(idm_acceleration, desired_acceleration, 0.0001);\n\n  ego_velocity = desired_velocity-12;\n  observed_world = make_test_observed_world(0,rel_distance, ego_velocity, velocity_difference);\n  idm_acceleration  = behavior.CalculateLongitudinalAcceleration(observed_world);\n\n  // no vehicle is in front only free road term should give acceleration\n  desired_acceleration = max_acceleration*(1-pow(ego_velocity/desired_velocity, exponent));\n  EXPECT_NEAR(idm_acceleration, desired_acceleration, 0.0001);\n}\n\nTEST(interaction_term, behavior_idm_classic) {\n  DefaultParams params;\n  BehaviorIDMClassic behavior(&params);\n  const float desired_velocity = behavior.get_desired_velocity();\n  const float minimum_spacing = behavior.get_minimum_spacing();\n  const float desired_time_headway = behavior.get_desired_time_headway();\n  const float max_acceleration = behavior.get_max_acceleration();\n  const float comfortable_braking_acceleration = behavior.get_comfortable_braking_acceleration();\n\n  // vehicle is in front, zero velocity equal desired velocity thus only interaction term\n  float ego_velocity = desired_velocity, rel_distance = 7.0, velocity_difference=0.0;\n  auto observed_world = make_test_observed_world(1,rel_distance, ego_velocity, velocity_difference);\n  double idm_acceleration  = behavior.CalculateLongitudinalAcceleration(observed_world);\n  double helper_state = minimum_spacing + ego_velocity*desired_time_headway +\n               ego_velocity*velocity_difference/(2*sqrt(max_acceleration*comfortable_braking_acceleration));\n  double desired_acceleration = - max_acceleration*pow(helper_state/rel_distance, 2);\n  EXPECT_NEAR(idm_acceleration, desired_acceleration, 0.001);\n\n  \n  // velocity difference to other vehicle\n  ego_velocity = desired_velocity, rel_distance = 7.0, velocity_difference=5.0;\n  observed_world = make_test_observed_world(1,rel_distance, ego_velocity, velocity_difference);\n  idm_acceleration  = behavior.CalculateLongitudinalAcceleration(observed_world);\n  helper_state = minimum_spacing + ego_velocity*desired_time_headway +\n               ego_velocity*velocity_difference/(2*sqrt(max_acceleration*comfortable_braking_acceleration));\n  desired_acceleration = - max_acceleration*pow(helper_state/rel_distance, 2);\n  EXPECT_NEAR(idm_acceleration, desired_acceleration, 0.001);\n}\n\nTEST(drive_free, behavior_idm_classic) {\n  DefaultParams params;\n  BehaviorIDMClassic behavior(&params);\n  const float desired_velocity = behavior.get_desired_velocity();\n\n  // First case, we start with the desired velocity. After num steps, we should advance \n  float ego_velocity = desired_velocity, rel_distance = 7.0, velocity_difference=0.0;\n  float time_step=0.2f;\n  int num_steps = 10;\n  WorldPtr world = make_test_world(0,rel_distance, ego_velocity, velocity_difference);\n\n  float x_start = world->get_agents().begin()->second->get_current_state()[StateDefinition::X_POSITION];\n  for (int i=0; i<num_steps; ++i ) {\n    world->Step(time_step);\n  }\n  float x_end = world->get_agents().begin()->second->get_current_state()[StateDefinition::X_POSITION];\n  float x_diff_desired = x_start + ego_velocity*num_steps*time_step - x_end;\n  EXPECT_NEAR(x_diff_desired,0, 0.01);\n\n}\n\nTEST(drive_leading_vehicle, behavior_idm_classic) {\n  DefaultParams params;\n  BehaviorIDMClassic behavior(&params);\n  const float desired_velocity = behavior.get_desired_velocity();\n  const float minimum_spacing = behavior.get_minimum_spacing();\n  const float desired_time_headway = behavior.get_desired_time_headway();\n\n  // First case, we start with the desired velocity. After num steps, we should advance \n  float ego_velocity = desired_velocity, rel_distance = 5.0, velocity_difference=10;\n  float time_step=0.2f; // Very small time steps to verify differential integration character\n  int num_steps = 10;\n  WorldPtr world = make_test_world(1,rel_distance, ego_velocity, velocity_difference);\n\n /* float v_start = world->get_agents().begin()->second->get_current_state()[StateDefinition::VEL_POSITION];\n  for (int i=0; i<num_steps; ++i ) {\n    world->Step(time_step);\n  }\n  float v_end = world->get_agents().begin()->second->get_current_state()[StateDefinition::VEL_POSITION];\n\n  EXPECT_NEAR(v_end,ego_velocity-velocity_difference, 0.01);\n*/\n}\n\nint main(int argc, char **argv) {\n  ::testing::InitGoogleTest(&argc, argv);\n  return RUN_ALL_TESTS();\n}", "meta": {"hexsha": "851ac054f35d071eaba182fcf6b07f5e6bc923c4", "size": 6623, "ext": "cc", "lang": "C++", "max_stars_repo_path": "modules/models/tests/behavior_idm_classic_test.cc", "max_stars_repo_name": "cirrostratus1/bark", "max_stars_repo_head_hexsha": "6629a9bbc455d0fd708e09bb8e162425e62c4165", "max_stars_repo_licenses": ["MIT"], "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/models/tests/behavior_idm_classic_test.cc", "max_issues_repo_name": "cirrostratus1/bark", "max_issues_repo_head_hexsha": "6629a9bbc455d0fd708e09bb8e162425e62c4165", "max_issues_repo_licenses": ["MIT"], "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/models/tests/behavior_idm_classic_test.cc", "max_forks_repo_name": "cirrostratus1/bark", "max_forks_repo_head_hexsha": "6629a9bbc455d0fd708e09bb8e162425e62c4165", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-04-16T07:56:43.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-16T07:56:43.000Z", "avg_line_length": 47.3071428571, "max_line_length": 108, "alphanum_fraction": 0.7951079571, "num_tokens": 1526, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.48633518780295415}}
{"text": "#include \"round.hpp\"\n#include \"ast.hpp\"\n#include \"parsers.hpp\"\n#include \"types.hpp\"\n#include <boost/variant.hpp>\n#include <stdexcept>\n#include <cmath>\n#include <cfenv>\nnamespace\n{\n    inline bool fisint(long double d)\n    {\n        long double p[2];\n        p[1] = std::modf(d,p);\n        return  (p[1]==0.0) ;\n    }\n}\nnamespace HT\n{\n    void round(PASTNode astnode, ParsersHelper& ph)\n    {\n        auto myParserHelper(ph);\n        if (astnode->ch.size()!=2)\n          throw std::runtime_error(\"round can only have one parameter\");\n        auto & secondCh = *astnode->ch.rbegin();\n        ph.parse(secondCh);\n        if (secondCh->token.tokenType != Complex || ! boost::get<ComplexType>(secondCh->token.info).isReal())\n          throw std::runtime_error(\"The argument of round must be real\");\n        auto cast = boost::get<ComplexType>(secondCh->token.info);\n        astnode->type = Simple;\n        astnode->token.tokenType = Complex;\n        if (cast.isRational())\n        {\n            bool si = cast.getRealR().getSign();\n            auto rat = cast.getRealR();\n            if (!si) rat = - rat;\n            auto t = rat.getUp() / rat.getDown();\n            auto tt = t+1;\n            if (tt - rat > rat - t)\n              astnode->token.info = ComplexType( t.setSign(si));\n            else\n              if (tt-rat!=rat-t)\n                astnode->token.info = ComplexType( tt.setSign(si));\n            else\n              astnode->token.info = ComplexType( (t%2==0 ? t:tt).setSign(si));\n        } else\n        {\n            long double p[2];\n            p[1] = std::modf(cast.getRealD(), p);\n            LOG(\"dex part:\"<<p[1])\n            if (std::fabs(p[1])!=0.5)\n          astnode->token.info = ComplexType(std::roundl(cast.getRealD()));\n            else\n            {\n                astnode->token.info = ComplexType(::fisint(p[0]/2.0)?\n                            p[0] : ( p[0]<0 ? p[0]-1.0 : p[0]+1.0));\n            }\n        }\n\n\n        astnode->remove();\n    }\n\n}\n\n\n", "meta": {"hexsha": "a05ec86907d884229dcd3e02903456ca004e30b2", "size": 1980, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "funs/round.cpp", "max_stars_repo_name": "htfy96/htscheme", "max_stars_repo_head_hexsha": "b44c9f9672f69d9b3c2eb1c80969bcfcfec9990f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2015-07-07T01:30:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-14T10:45:01.000Z", "max_issues_repo_path": "funs/round.cpp", "max_issues_repo_name": "htfy96/htscheme", "max_issues_repo_head_hexsha": "b44c9f9672f69d9b3c2eb1c80969bcfcfec9990f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "funs/round.cpp", "max_forks_repo_name": "htfy96/htscheme", "max_forks_repo_head_hexsha": "b44c9f9672f69d9b3c2eb1c80969bcfcfec9990f", "max_forks_repo_licenses": ["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.552238806, "max_line_length": 109, "alphanum_fraction": 0.5075757576, "num_tokens": 529, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6442250996557035, "lm_q1q2_score": 0.4863351826463819}}
{"text": "#include <boost/math/constants/constants.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <iostream>\n#include <limits>\n#include <cmath>\n#include <iomanip>\n\nusing namespace std;\nusing boost::multiprecision::cpp_dec_float_50;\n\ncpp_dec_float_50 truncate(cpp_dec_float_50 n, int precision) {\n    cpp_dec_float_50 remainder = static_cast<cpp_dec_float_50>((int)floor((n - floor(n)) * precision) % precision) / static_cast<cpp_dec_float_50>(precision);\n    return floor(n) + remainder;\n}\n\nint main(void) {\n    int precision = 100; // as many digits as you add zeroes. 5 zeroes means precision of 5.\n    cpp_dec_float_50 n =  0.02785 * 100;\n    n = truncate(n + 0.5/precision, precision); // first part is remainder, floor(n) is int value truncated.\n    cout << setprecision(numeric_limits<cpp_dec_float_50> ::max_digits10 + __builtin_ctz(precision)) << n << \"%\" << endl; // __builtin_ctz(precision) will equal the number of trailing 0, exactly the precision we need!\n    return 0;\n}", "meta": {"hexsha": "0649cfe51b9fd25704ecc7ad8a74091b3642d1a9", "size": 991, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "functions/percentage.cpp", "max_stars_repo_name": "12932/42_CheatSheet", "max_stars_repo_head_hexsha": "d3ebd468046807011987658dce29dbce937f059e", "max_stars_repo_licenses": ["Vim"], "max_stars_count": 912.0, "max_stars_repo_stars_event_min_datetime": "2019-09-29T17:09:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T17:15:00.000Z", "max_issues_repo_path": "functions/percentage.cpp", "max_issues_repo_name": "aaitbelh/42_CheatSheet", "max_issues_repo_head_hexsha": "d3ebd468046807011987658dce29dbce937f059e", "max_issues_repo_licenses": ["Vim"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2019-11-04T13:10:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T00:01:01.000Z", "max_forks_repo_path": "functions/percentage.cpp", "max_forks_repo_name": "aaitbelh/42_CheatSheet", "max_forks_repo_head_hexsha": "d3ebd468046807011987658dce29dbce937f059e", "max_forks_repo_licenses": ["Vim"], "max_forks_count": 90.0, "max_forks_repo_forks_event_min_datetime": "2020-04-18T08:16:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T03:31:05.000Z", "avg_line_length": 45.0454545455, "max_line_length": 217, "alphanum_fraction": 0.736629667, "num_tokens": 262, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.4863351806984699}}
{"text": "// This file is part of libigl, a simple c++ geometry processing library.\n//\n// Copyright (C) 2014 Daniele Panozzo <daniele.panozzo@gmail.com>\n//\n// This Source Code Form is subject to the terms of the Mozilla Public License\n// v. 2.0. If a copy of the MPL was not distributed with this file, You can\n// obtain one at http://mozilla.org/MPL/2.0/.\n\n#include \"ViewerData.h\"\n#include \"ViewerCore.h\"\n\n#include \"../per_face_normals.h\"\n#include \"../material_colors.h\"\n#include \"../parula.h\"\n#include \"../per_vertex_normals.h\"\n#include \"igl/png/texture_from_png.h\"\n#include <iostream>\n//#include \"external/stb/igl_stb_image.h\"\n\n// OUR imports\n#include <igl/edge_flaps.h>\n#include <igl/parallel_for.h>\n#include <igl/shortest_edge_and_midpoint.h>\n#include <igl/collapse_edge.h>\n#include <igl/per_face_normals.h>\n#include <Eigen/Core>\n#include <limits>\n#include <igl/edge_collapse_is_valid.h>\n#include <igl/circulation.h>\n\nIGL_INLINE igl::opengl::ViewerData::ViewerData()\n: dirty(MeshGL::DIRTY_ALL),\n  show_faces(true),\n  show_lines(true),\n  invert_normals(false),\n  show_overlay(true),\n  show_overlay_depth(true),\n  show_vertid(false),\n  show_faceid(false),\n  show_texture(false),\n  point_size(30),\n  line_width(0.5f),\n  line_color(0,0,0,1),\n  label_color(0,0,0.04,1),\n  shininess(35.0f),\n  id(-1),\n  is_visible(1)\n{\n  clear();\n};\n\n// OUR functions\nIGL_INLINE void igl::opengl::ViewerData::init_simplify() {    \n    edge_flaps(F, E, EMAP, EF, EI);\n\n    init_quad_costs();\n}\n\nIGL_INLINE void igl::opengl::ViewerData::init_quad_costs() {\n    // ASSUMPTION: the ith F_normals corresponds to the ith F face\n    compute_normals();\n    Eigen::MatrixXd planes = F_normals.normalized();\n    planes.conservativeResize(F.rows(), 4);\n\n    // calculating the d's of each plane\n    for (int i = 0; i < F.rows(); i++) {\n        Eigen::VectorXd vertex = V.row(F(i, 0));\n        planes(i, 3) = -(planes(i, 0) * vertex(0) + planes(i, 1) * vertex(1) + planes(i, 2) * vertex(2));\n    }\n\n    // init the map\n    for (int i = 0; i < V.rows(); i++) {\n        Q_quad[i] = Eigen::MatrixXd::Zero(4, 4);\n    }\n\n    // calculating Q for each vertex\n    for (int i = 0; i < F.rows(); i++) {\n        Eigen::MatrixXd Kp = planes.row(i).transpose() * planes.row(i);\n        Q_quad[F(i, 0)] += Kp;\n        Q_quad[F(i, 1)] += Kp;\n        Q_quad[F(i, 2)] += Kp;\n    }\n  \n    // calculating the contractions and their costs\n    Eigen::Vector4d last_row { 0.0, 0.0, 0.0, 1.0 };\n    Eigen::VectorXd optimal_vertex;\n    double optimal_cost;\n    for (int i = 0; i < E.rows(); i++) {\n        Eigen::MatrixXd Q_roof = Q_quad[E(i, 0)] + Q_quad[E(i, 1)];\n\n        Eigen::MatrixXd Q_roof_prime = Q_roof;\n        Q_roof_prime.row(3) = last_row;\n        Q_roof_prime = Q_roof_prime.inverse(); // inverting\n        if (Q_roof_prime(0, 0) != std::numeric_limits<float>::infinity()) { // if there's inf then the matrix is not invertible\n            optimal_vertex = Q_roof_prime * last_row; // 4 x 1\n            optimal_cost = optimal_vertex.transpose() * Q_roof * optimal_vertex;\n            E_cost.push(std::pair<double, int>(optimal_cost, i));\n            optimal_vertex.conservativeResize(3, 1);\n            contractions[i] = optimal_vertex;\n        }\n        else { // the matrix is not invertible and we have to choose one of 3 options\n            // choosing optimal???\n\n            Eigen::VectorXd vertex1 = V.row(E(i, 0)); // v1\n            double v1_cost = vertex1.transpose() * Q_roof * vertex1; // v1 cost\n\n            Eigen::VectorXd vertex2 = V.row(E(i, 1)); // v2\n            double v2_cost = vertex2.transpose() * Q_roof * vertex1; // v2 cost\n\n            Eigen::VectorXd vertex12 = (V.row(E(i, 0)) + V.row(E(i, 1))) / 2; //]the middle of v1 and v2\n            double v12_cost = vertex12.transpose() * Q_roof * vertex12; // v2 cost\n\n            if (v1_cost < v2_cost) {\n                if (v1_cost < v12_cost) {\n                    E_cost.push(std::pair<double, int>(v1_cost, i));\n                    contractions[i] = vertex1;\n                }\n                else {\n                    E_cost.push(std::pair<double, int>(v12_cost, i));\n                    contractions[i] = vertex12;\n                }\n            }\n            else {\n                if (v2_cost < v12_cost) {\n                    E_cost.push(std::pair<double, int>(v2_cost, i));\n                    contractions[i] = vertex2;\n                }\n                else {\n                    E_cost.push(std::pair<double, int>(v12_cost, i));\n                    contractions[i] = vertex12;\n                }\n            }\n        }\n    }\n\n    /*  Eigen::Matrix2f A;\n    A << 9, 6,\n        12, 8;\n\n    std::cout << A.inverse() << std::endl;*/\n\n    /* E_cost.push(std::pair<double, int>(200, 1));\n     E_cost.push(std::pair<double, int>(0.1, 2));\n     E_cost.push(std::pair<double, int>(150, 2));\n     std::pair<double, int> top = E_cost.top();\n     std::cout << top.first << \" \" << top.second << std::endl;\n     E_cost.pop();\n     top = E_cost.top();\n     std::cout << top.first << \" \" << top.second << std::endl;\n     E_cost.pop();\n     top = E_cost.top();\n     std::cout << top.first << \" \" << top.second << std::endl;*/\n}\n\nIGL_INLINE void igl::opengl::ViewerData::simplify_mesh(int edges_to_remove) {\n    // setups\n    Eigen::MatrixXd V_proc = V;\n    Eigen::MatrixXi F_proc = F;\n\n   \n    if (!init_costs_flag) {\n        C.resize(E.rows(), V_proc.cols());\n        \n        Eigen::VectorXd costs(E.rows());\n        igl::parallel_for(E.rows(), [&](const int e)\n            {\n\n                double cost = e;\n                Eigen::RowVectorXd p(1, 3);\n                shortest_edge_and_midpoint(e, V_proc, F_proc, E, EMAP, EF, EI, cost, p);\n                C.row(e) = p;\n                costs(e) = cost;\n\n            }, 10000);\n\n        for (int e = 0;e < E.rows();e++)\n        {\n            std::set<std::pair<double, int> >::iterator ret = Q.insert(std::pair<double, int>(costs(e), e)).first;\n            Qit.push_back(ret);\n        }\n\n        init_costs_flag = true;\n    }\n   \n\n    if (!Q.empty())\n    {\n        bool something_collapsed = false;\n        // collapse edge\n        for (int j = 0;j < edges_to_remove; j++)\n        {\n            if (!collapse_edge(shortest_edge_and_midpoint, V_proc, F_proc, E, EMAP, EF, EI, Q, Qit, C))\n            {\n                break;\n            }\n            something_collapsed = true;\n        }\n\n        if (something_collapsed)\n        {\n            clear();\n            set_mesh(V_proc, F_proc);\n            set_face_based(true);\n            dirty = 157;\n        }\n    }\n}\n\nIGL_INLINE void igl::opengl::ViewerData::update_costs() {\n\n    // calculating the contractions and their costs\n    Eigen::Vector4d last_row{ 0.0, 0.0, 0.0, 1.0 };\n    Eigen::VectorXd optimal_vertex;\n    double optimal_cost;\n    E_cost = std::priority_queue<std::pair<double, int>, std::vector<std::pair<double, int>>, std::greater<std::pair<double, int>> >();\n    for (int i = 0; i < E.rows(); i++) {\n        Eigen::MatrixXd Q_roof = Q_quad[E(i, 0)] + Q_quad[E(i, 1)];\n\n        Eigen::MatrixXd Q_roof_prime = Q_roof;\n        Q_roof_prime.row(3) = last_row;\n        Q_roof_prime = Q_roof_prime.inverse(); // inverting\n        if (Q_roof_prime(0, 0) != std::numeric_limits<float>::infinity()) { // if there's inf then the matrix is not invertible\n            optimal_vertex = Q_roof_prime * last_row; // 4 x 1\n            optimal_cost = optimal_vertex.transpose() * Q_roof * optimal_vertex;\n            E_cost.push(std::pair<double, int>(optimal_cost, i));\n            optimal_vertex.conservativeResize(3, 1);\n            contractions[i] = optimal_vertex;\n        }\n        else { // the matrix is not invertible and we have to choose one of 3 options\n            // choosing optimal???\n\n            Eigen::VectorXd vertex1 = V.row(E(i, 0)); // v1\n            double v1_cost = vertex1.transpose() * Q_roof * vertex1; // v1 cost\n\n            Eigen::VectorXd vertex2 = V.row(E(i, 1)); // v2\n            double v2_cost = vertex2.transpose() * Q_roof * vertex1; // v2 cost\n\n            Eigen::VectorXd vertex12 = (V.row(E(i, 0)) + V.row(E(i, 1))) / 2; //]the middle of v1 and v2\n            double v12_cost = vertex12.transpose() * Q_roof * vertex12; // v2 cost\n\n            if (v1_cost < v2_cost) {\n                if (v1_cost < v12_cost) {\n                    E_cost.push(std::pair<double, int>(v1_cost, i));\n                    contractions[i] = vertex1;\n                }\n                else {\n                    E_cost.push(std::pair<double, int>(v12_cost, i));\n                    contractions[i] = vertex12;\n                }\n            }\n            else {\n                if (v2_cost < v12_cost) {\n                    E_cost.push(std::pair<double, int>(v2_cost, i));\n                    contractions[i] = vertex2;\n                }\n                else {\n                    E_cost.push(std::pair<double, int>(v12_cost, i));\n                    contractions[i] = vertex12;\n                }\n            }\n        }\n    }\n}\n\nIGL_INLINE void igl::opengl::ViewerData::simplify_mesh_quad_err(int edges_to_remove) {\n\n    for (int i = 0; i < edges_to_remove; i++) {\n        if (E_cost.empty()) {\n            break;\n        }\n        std::pair<double, int> lowest_cost = E_cost.top(); // getting the lowest cost (cost, edge)\n        E_cost.pop();\n        int edge_to_collapse = lowest_cost.second;\n       Eigen::VectorXd new_vetrex = contractions[edge_to_collapse];\n\n\n        const int eflip = E(edge_to_collapse, 0) > E(edge_to_collapse, 1);\n        // source and destination\n        const int s = eflip ? E(edge_to_collapse, 1) : E(edge_to_collapse, 0);\n        const int d = eflip ? E(edge_to_collapse, 0) : E(edge_to_collapse, 1);\n\n        if (!edge_collapse_is_valid(edge_to_collapse, F, E, EMAP, EF, EI))\n        {\n            i--; // we still want to collapse the correct number of edges\n            continue;\n        }\n\n        // Important to grab neighbors of d before monkeying with edges\n        const std::vector<int> nV2Fd = circulation(edge_to_collapse, !eflip, EMAP, EF, EI);\n\n        // The following implementation strongly relies on s<d\n        assert(s < d && \"s should be less than d\");\n        // move source and destination to midpoint\n        Q_quad[s] = Q_quad[s] + Q_quad[d];\n        V.row(s) = new_vetrex;\n        V.row(d) = new_vetrex;\n\n        // update edge info\n        // for each flap\n        const int m = F.rows();\n        for (int side = 0;side < 2;side++)\n        {\n            const int f = EF(edge_to_collapse, side);\n            const int v = EI(edge_to_collapse, side);\n            const int sign = (eflip == 0 ? 1 : -1) * (1 - 2 * side);\n            // next edge emanating from d\n            const int e1 = EMAP(f + m * ((v + sign * 1 + 3) % 3));\n            // prev edge pointing to s\n            const int e2 = EMAP(f + m * ((v + sign * 2 + 3) % 3));\n            assert(E(e1, 0) == d || E(e1, 1) == d);\n            assert(E(e2, 0) == s || E(e2, 1) == s);\n            // face adjacent to f on e1, also incident on d\n            const bool flip1 = EF(e1, 1) == f;\n            const int f1 = flip1 ? EF(e1, 0) : EF(e1, 1);\n            assert(f1 != f);\n            assert(F(f1, 0) == d || F(f1, 1) == d || F(f1, 2) == d);\n            // across from which vertex of f1 does e1 appear?\n            const int v1 = flip1 ? EI(e1, 0) : EI(e1, 1);\n            // Kill e1\n            E(e1, 0) = IGL_COLLAPSE_EDGE_NULL;\n            E(e1, 1) = IGL_COLLAPSE_EDGE_NULL;\n            EF(e1, 0) = IGL_COLLAPSE_EDGE_NULL;\n            EF(e1, 1) = IGL_COLLAPSE_EDGE_NULL;\n            EI(e1, 0) = IGL_COLLAPSE_EDGE_NULL;\n            EI(e1, 1) = IGL_COLLAPSE_EDGE_NULL;\n            // Kill f\n            F(f, 0) = IGL_COLLAPSE_EDGE_NULL;\n            F(f, 1) = IGL_COLLAPSE_EDGE_NULL;\n            F(f, 2) = IGL_COLLAPSE_EDGE_NULL;\n            // map f1's edge on e1 to e2\n            assert(EMAP(f1 + m * v1) == e1);\n            EMAP(f1 + m * v1) = e2;\n            // side opposite f2, the face adjacent to f on e2, also incident on s\n            const int opp2 = (EF(e2, 0) == f ? 0 : 1);\n            assert(EF(e2, opp2) == f);\n            EF(e2, opp2) = f1;\n            EI(e2, opp2) = v1;\n            // remap e2 from d to s\n            E(e2, 0) = E(e2, 0) == d ? s : E(e2, 0);\n            E(e2, 1) = E(e2, 1) == d ? s : E(e2, 1);\n        }\n\n        // finally, reindex faces and edges incident on d. Do this last so asserts\n        // make sense.\n        //\n        // Could actually skip first and last, since those are always the two\n        // collpased faces.\n        for (auto f : nV2Fd)\n        {\n            for (int v = 0;v < 3;v++)\n            {\n                if (F(f, v) == d)\n                {\n                    const int flip1 = (EF(EMAP(f + m * ((v + 1) % 3)), 0) == f) ? 1 : 0;\n                    const int flip2 = (EF(EMAP(f + m * ((v + 2) % 3)), 0) == f) ? 0 : 1;\n                    assert(\n                        E(EMAP(f + m * ((v + 1) % 3)), flip1) == d ||\n                        E(EMAP(f + m * ((v + 1) % 3)), flip1) == s);\n                    E(EMAP(f + m * ((v + 1) % 3)), flip1) = s;\n                    assert(\n                        E(EMAP(f + m * ((v + 2) % 3)), flip2) == d ||\n                        E(EMAP(f + m * ((v + 2) % 3)), flip2) == s);\n                    E(EMAP(f + m * ((v + 2) % 3)), flip2) = s;\n                    F(f, v) = s;\n                    break;\n                }\n            }\n        }\n        // Finally, \"remove\" this edge and its information\n           E(edge_to_collapse, 0) = IGL_COLLAPSE_EDGE_NULL;\n           E(edge_to_collapse, 1) = IGL_COLLAPSE_EDGE_NULL;\n           EF(edge_to_collapse, 0) = IGL_COLLAPSE_EDGE_NULL;\n           EF(edge_to_collapse, 1) = IGL_COLLAPSE_EDGE_NULL;\n           EI(edge_to_collapse, 0) = IGL_COLLAPSE_EDGE_NULL;\n           EI(edge_to_collapse, 1) = IGL_COLLAPSE_EDGE_NULL;\n\n\n        // setting up the mesh again after the changes\n        Eigen::MatrixXd V_temp = V;\n        Eigen::MatrixXi F_temp = F;\n\n        clear();\n        set_mesh(V_temp, F_temp);\n        set_face_based(true);\n        dirty = 157;\n\n        if (i % 10 == 0) {\n            update_costs();\n        }\n\n        std::cout << \"edge \" << edge_to_collapse << \", cost = \" << lowest_cost.first << \", new v position (\" << new_vetrex << \")\" << std::endl;\n\n    }\n\n    update_costs();\n}\n\nIGL_INLINE void igl::opengl::ViewerData::set_face_based(bool newvalue)\n{\n  if (face_based != newvalue)\n  {\n    face_based = newvalue;\n    dirty = MeshGL::DIRTY_ALL;\n  }\n}\n\n// Helpers that draws the most common meshes\nIGL_INLINE void igl::opengl::ViewerData::set_mesh(\n    const Eigen::MatrixXd& _V, const Eigen::MatrixXi& _F)\n{\n  using namespace std;\n\n  Eigen::MatrixXd V_temp;\n\n  // If V only has two columns, pad with a column of zeros\n  if (_V.cols() == 2)\n  {\n    V_temp = Eigen::MatrixXd::Zero(_V.rows(),3);\n    V_temp.block(0,0,_V.rows(),2) = _V;\n  }\n  else\n    V_temp = _V;\n\n  if (V.rows() == 0 && F.rows() == 0)\n  {\n    V = V_temp;\n    F = _F;\n\n    compute_normals();\n    uniform_colors(\n      Eigen::Vector3d(GOLD_AMBIENT[0], GOLD_AMBIENT[1], GOLD_AMBIENT[2]),\n      Eigen::Vector3d(GOLD_DIFFUSE[0], GOLD_DIFFUSE[1], GOLD_DIFFUSE[2]),\n      Eigen::Vector3d(GOLD_SPECULAR[0], GOLD_SPECULAR[1], GOLD_SPECULAR[2]));\n\timage_texture(\"D:/UniversityAssiments/Animation/CleanAssignment1/EngineForAnimationCourse/tutorial/textures/snake1.png\");\n//    grid_texture();\n  }\n  else\n  {\n    if (_V.rows() == V.rows() && _F.rows() == F.rows())\n    {\n      V = V_temp;\n      F = _F;\n    }\n    else\n      cerr << \"ERROR (set_mesh): The new mesh has a different number of vertices/faces. Please clear the mesh before plotting.\"<<endl;\n  }\n  dirty |= MeshGL::DIRTY_FACE | MeshGL::DIRTY_POSITION;\n\n  // our addition to the function\n  if (!init_ds_flag) {\n      init_simplify(); \n      init_ds_flag = true;\n  }\n}\n\nIGL_INLINE void igl::opengl::ViewerData::set_vertices(const Eigen::MatrixXd& _V)\n{\n  V = _V;\n  assert(F.size() == 0 || F.maxCoeff() < V.rows());\n  dirty |= MeshGL::DIRTY_POSITION;\n}\n\nIGL_INLINE void igl::opengl::ViewerData::set_normals(const Eigen::MatrixXd& N)\n{\n  using namespace std;\n  if (N.rows() == V.rows())\n  {\n    set_face_based(false);\n    V_normals = N;\n  }\n  else if (N.rows() == F.rows() || N.rows() == F.rows()*3)\n  {\n    set_face_based(true);\n    F_normals = N;\n  }\n  else\n    cerr << \"ERROR (set_normals): Please provide a normal per face, per corner or per vertex.\"<<endl;\n  dirty |= MeshGL::DIRTY_NORMAL;\n}\n\nIGL_INLINE void igl::opengl::ViewerData::set_visible(bool value, unsigned int core_id /*= 1*/)\n{\n  if (value)\n    is_visible |= core_id;\n  else\n  is_visible &= ~core_id;\n}\n\n//IGL_INLINE void igl::opengl::ViewerData::copy_options(const ViewerCore &from, const ViewerCore &to)\n//{\n//  to.set(show_overlay      , from.is_set(show_overlay)      );\n//  to.set(show_overlay_depth, from.is_set(show_overlay_depth));\n//  to.set(show_texture      , from.is_set(show_texture)      );\n//  to.set(show_faces        , from.is_set(show_faces)        );\n//  to.set(show_lines        , from.is_set(show_lines)        );\n//}\n\nIGL_INLINE void igl::opengl::ViewerData::set_colors(const Eigen::MatrixXd &C)\n{\n  using namespace std;\n  using namespace Eigen;\n  if(C.rows()>0 && C.cols() == 1)\n  {\n    Eigen::MatrixXd C3;\n    igl::parula(C,true,C3);\n    return set_colors(C3);\n  }\n  // Ambient color should be darker color\n  const auto ambient = [](const MatrixXd & C)->MatrixXd\n  {\n    MatrixXd T = 0.1*C;\n    T.col(3) = C.col(3);\n    return T;\n  };\n  // Specular color should be a less saturated and darker color: dampened\n  // highlights\n  const auto specular = [](const MatrixXd & C)->MatrixXd\n  {\n    const double grey = 0.3;\n    MatrixXd T = grey+0.1*(C.array()-grey);\n    T.col(3) = C.col(3);\n    return T;\n  };\n  if (C.rows() == 1)\n  {\n    for (unsigned i=0;i<V_material_diffuse.rows();++i)\n    {\n      if (C.cols() == 3)\n        V_material_diffuse.row(i) << C.row(0),1;\n      else if (C.cols() == 4)\n        V_material_diffuse.row(i) << C.row(0);\n    }\n    V_material_ambient = ambient(V_material_diffuse);\n    V_material_specular = specular(V_material_diffuse);\n\n    for (unsigned i=0;i<F_material_diffuse.rows();++i)\n    {\n      if (C.cols() == 3)\n        F_material_diffuse.row(i) << C.row(0),1;\n      else if (C.cols() == 4)\n        F_material_diffuse.row(i) << C.row(0);\n    }\n    F_material_ambient = ambient(F_material_diffuse);\n    F_material_specular = specular(F_material_diffuse);\n  }\n  else if (C.rows() == V.rows())\n  {\n    set_face_based(false);\n    for (unsigned i=0;i<V_material_diffuse.rows();++i)\n    {\n      if (C.cols() == 3)\n        V_material_diffuse.row(i) << C.row(i), 1;\n      else if (C.cols() == 4)\n        V_material_diffuse.row(i) << C.row(i);\n    }\n    V_material_ambient = ambient(V_material_diffuse);\n    V_material_specular = specular(V_material_diffuse);\n  }\n  else if (C.rows() == F.rows())\n  {\n    set_face_based(true);\n    for (unsigned i=0;i<F_material_diffuse.rows();++i)\n    {\n      if (C.cols() == 3)\n        F_material_diffuse.row(i) << C.row(i), 1;\n      else if (C.cols() == 4)\n        F_material_diffuse.row(i) << C.row(i);\n    }\n    F_material_ambient = ambient(F_material_diffuse);\n    F_material_specular = specular(F_material_diffuse);\n  }\n  else\n    cerr << \"ERROR (set_colors): Please provide a single color, or a color per face or per vertex.\"<<endl;\n  dirty |= MeshGL::DIRTY_DIFFUSE;\n\n}\n\nIGL_INLINE void igl::opengl::ViewerData::set_uv(const Eigen::MatrixXd& UV)\n{\n  using namespace std;\n  if (UV.rows() == V.rows())\n  {\n    set_face_based(false);\n    V_uv = UV;\n  }\n  else\n    cerr << \"ERROR (set_UV): Please provide uv per vertex.\"<<endl;;\n  dirty |= MeshGL::DIRTY_UV;\n}\n\nIGL_INLINE void igl::opengl::ViewerData::set_uv(const Eigen::MatrixXd& UV_V, const Eigen::MatrixXi& UV_F)\n{\n  set_face_based(true);\n  V_uv = UV_V.block(0,0,UV_V.rows(),2);\n  F_uv = UV_F;\n  dirty |= MeshGL::DIRTY_UV;\n}\n\nIGL_INLINE void igl::opengl::ViewerData::set_texture(\n  const Eigen::Matrix<unsigned char,Eigen::Dynamic,Eigen::Dynamic>& R,\n  const Eigen::Matrix<unsigned char,Eigen::Dynamic,Eigen::Dynamic>& G,\n  const Eigen::Matrix<unsigned char,Eigen::Dynamic,Eigen::Dynamic>& B)\n{\n  texture_R = R;\n  texture_G = G;\n  texture_B = B;\n  texture_A = Eigen::Matrix<unsigned char,Eigen::Dynamic,Eigen::Dynamic>::Constant(R.rows(),R.cols(),255);\n  dirty |= MeshGL::DIRTY_TEXTURE;\n}\n\nIGL_INLINE void igl::opengl::ViewerData::set_texture(\n  const Eigen::Matrix<unsigned char,Eigen::Dynamic,Eigen::Dynamic>& R,\n  const Eigen::Matrix<unsigned char,Eigen::Dynamic,Eigen::Dynamic>& G,\n  const Eigen::Matrix<unsigned char,Eigen::Dynamic,Eigen::Dynamic>& B,\n  const Eigen::Matrix<unsigned char,Eigen::Dynamic,Eigen::Dynamic>& A)\n{\n  texture_R = R;\n  texture_G = G;\n  texture_B = B;\n  texture_A = A;\n  dirty |= MeshGL::DIRTY_TEXTURE;\n}\n\nIGL_INLINE void igl::opengl::ViewerData::set_points(\n  const Eigen::MatrixXd& P,\n  const Eigen::MatrixXd& C)\n{\n  // clear existing points\n  points.resize(0,0);\n  add_points(P,C);\n}\n\nIGL_INLINE void igl::opengl::ViewerData::add_points(const Eigen::MatrixXd& P,  const Eigen::MatrixXd& C)\n{\n  Eigen::MatrixXd P_temp;\n\n  // If P only has two columns, pad with a column of zeros\n  if (P.cols() == 2)\n  {\n    P_temp = Eigen::MatrixXd::Zero(P.rows(),3);\n    P_temp.block(0,0,P.rows(),2) = P;\n  }\n  else\n    P_temp = P;\n\n  int lastid = points.rows();\n  points.conservativeResize(points.rows() + P_temp.rows(),6);\n  for (unsigned i=0; i<P_temp.rows(); ++i)\n    points.row(lastid+i) << P_temp.row(i), i<C.rows() ? C.row(i) : C.row(C.rows()-1);\n\n  dirty |= MeshGL::DIRTY_OVERLAY_POINTS;\n}\n\nIGL_INLINE void igl::opengl::ViewerData::set_edges(\n  const Eigen::MatrixXd& P,\n  const Eigen::MatrixXi& E,\n  const Eigen::MatrixXd& C)\n{\n  using namespace Eigen;\n  lines.resize(E.rows(),9);\n  assert(C.cols() == 3);\n  for(int e = 0;e<E.rows();e++)\n  {\n    RowVector3d color;\n    if(C.size() == 3)\n    {\n      color<<C;\n    }else if(C.rows() == E.rows())\n    {\n      color<<C.row(e);\n    }\n    lines.row(e)<< P.row(E(e,0)), P.row(E(e,1)), color;\n  }\n  dirty |= MeshGL::DIRTY_OVERLAY_LINES;\n}\n\nIGL_INLINE void igl::opengl::ViewerData::add_edges(const Eigen::MatrixXd& P1, const Eigen::MatrixXd& P2, const Eigen::MatrixXd& C)\n{\n  Eigen::MatrixXd P1_temp,P2_temp;\n\n  // If P1 only has two columns, pad with a column of zeros\n  if (P1.cols() == 2)\n  {\n    P1_temp = Eigen::MatrixXd::Zero(P1.rows(),3);\n    P1_temp.block(0,0,P1.rows(),2) = P1;\n    P2_temp = Eigen::MatrixXd::Zero(P2.rows(),3);\n    P2_temp.block(0,0,P2.rows(),2) = P2;\n  }\n  else\n  {\n    P1_temp = P1;\n    P2_temp = P2;\n  }\n\n  int lastid = lines.rows();\n  lines.conservativeResize(lines.rows() + P1_temp.rows(),9);\n  for (unsigned i=0; i<P1_temp.rows(); ++i)\n    lines.row(lastid+i) << P1_temp.row(i), P2_temp.row(i), i<C.rows() ? C.row(i) : C.row(C.rows()-1);\n\n  dirty |= MeshGL::DIRTY_OVERLAY_LINES;\n}\n\nIGL_INLINE void igl::opengl::ViewerData::add_label(const Eigen::VectorXd& P,  const std::string& str)\n{\n  Eigen::RowVectorXd P_temp;\n\n  // If P only has two columns, pad with a column of zeros\n  if (P.size() == 2)\n  {\n    P_temp = Eigen::RowVectorXd::Zero(3);\n    P_temp << P.transpose(), 0;\n  }\n  else\n    P_temp = P;\n\n  int lastid = labels_positions.rows();\n  labels_positions.conservativeResize(lastid+1, 3);\n  labels_positions.row(lastid) = P_temp;\n  labels_strings.push_back(str);\n}\n\nIGL_INLINE void igl::opengl::ViewerData::clear_labels()\n{\n  labels_positions.resize(0,3);\n  labels_strings.clear();\n}\n\nIGL_INLINE void igl::opengl::ViewerData::clear()\n{\n  V                       = Eigen::MatrixXd (0,3);\n  F                       = Eigen::MatrixXi (0,3);\n\n  F_material_ambient      = Eigen::MatrixXd (0,4);\n  F_material_diffuse      = Eigen::MatrixXd (0,4);\n  F_material_specular     = Eigen::MatrixXd (0,4);\n\n  V_material_ambient      = Eigen::MatrixXd (0,4);\n  V_material_diffuse      = Eigen::MatrixXd (0,4);\n  V_material_specular     = Eigen::MatrixXd (0,4);\n\n  F_normals               = Eigen::MatrixXd (0,3);\n  V_normals               = Eigen::MatrixXd (0,3);\n\n  V_uv                    = Eigen::MatrixXd (0,2);\n  F_uv                    = Eigen::MatrixXi (0,3);\n\n  lines                   = Eigen::MatrixXd (0,9);\n  points                  = Eigen::MatrixXd (0,6);\n  labels_positions        = Eigen::MatrixXd (0,3);\n  labels_strings.clear();\n\n  face_based = false;\n}\n\nIGL_INLINE void igl::opengl::ViewerData::compute_normals()\n{\n  igl::per_face_normals(V, F, F_normals);\n  igl::per_vertex_normals(V, F, F_normals, V_normals);\n  dirty |= MeshGL::DIRTY_NORMAL;\n}\n\nIGL_INLINE void igl::opengl::ViewerData::uniform_colors(\n  const Eigen::Vector3d& ambient,\n  const Eigen::Vector3d& diffuse,\n  const Eigen::Vector3d& specular)\n{\n  Eigen::Vector4d ambient4;\n  Eigen::Vector4d diffuse4;\n  Eigen::Vector4d specular4;\n\n  ambient4 << ambient, 1;\n  diffuse4 << diffuse, 1;\n  specular4 << specular, 1;\n\n  uniform_colors(ambient4,diffuse4,specular4);\n}\n\nIGL_INLINE void igl::opengl::ViewerData::uniform_colors(\n  const Eigen::Vector4d& ambient,\n  const Eigen::Vector4d& diffuse,\n  const Eigen::Vector4d& specular)\n{\n  V_material_ambient.resize(V.rows(),4);\n  V_material_diffuse.resize(V.rows(),4);\n  V_material_specular.resize(V.rows(),4);\n\n  for (unsigned i=0; i<V.rows();++i)\n  {\n    V_material_ambient.row(i) = ambient;\n    V_material_diffuse.row(i) = diffuse;\n    V_material_specular.row(i) = specular;\n  }\n\n  F_material_ambient.resize(F.rows(),4);\n  F_material_diffuse.resize(F.rows(),4);\n  F_material_specular.resize(F.rows(),4);\n\n  for (unsigned i=0; i<F.rows();++i)\n  {\n    F_material_ambient.row(i) = ambient;\n    F_material_diffuse.row(i) = diffuse;\n    F_material_specular.row(i) = specular;\n  }\n  dirty |= MeshGL::DIRTY_SPECULAR | MeshGL::DIRTY_DIFFUSE | MeshGL::DIRTY_AMBIENT;\n}\n\nIGL_INLINE void igl::opengl::ViewerData::image_texture(const std::string fileName)\n{\n\t//unsigned int texId;\n\t//if (igl::png::texture_from_png(fileName, false, texId))\n\tif(igl::png::texture_from_png(fileName,texture_R, texture_G, texture_B, texture_A))\n\t\n\t\tdirty |= MeshGL::DIRTY_TEXTURE;\n\telse\n\t\tstd::cout<<\"can't open texture file\"<<std::endl;\n\n\n\n}\n\nIGL_INLINE void igl::opengl::ViewerData::grid_texture()\n{\n  // Don't do anything for an empty mesh\n  if(V.rows() == 0)\n  {\n    V_uv.resize(V.rows(),2);\n    return;\n  }\n  if (V_uv.rows() == 0)\n  {\n    V_uv = V.block(0, 0, V.rows(), 2);\n    V_uv.col(0) = V_uv.col(0).array() - V_uv.col(0).minCoeff();\n    V_uv.col(0) = V_uv.col(0).array() / V_uv.col(0).maxCoeff();\n    V_uv.col(1) = V_uv.col(1).array() - V_uv.col(1).minCoeff();\n    V_uv.col(1) = V_uv.col(1).array() / V_uv.col(1).maxCoeff();\n    V_uv = V_uv.array() * 10;\n    dirty |= MeshGL::DIRTY_TEXTURE;\n  }\n\n  unsigned size = 4;\n  unsigned size2 = size/2;\n  texture_R.resize(size, size);\n  for (unsigned i=0; i<size; ++i)\n  {\n    for (unsigned j=0; j<size; ++j)\n    {\n      texture_R(i,j) = 0;\n      if ((i<size2 && j<size2) || (i>=size2 && j>=size2))\n        texture_R(i,j) = 255;\n    }\n  }\n\n  texture_G = texture_R;\n  texture_B = texture_R;\n  texture_A = Eigen::Matrix<unsigned char,Eigen::Dynamic,Eigen::Dynamic>::Constant(texture_R.rows(),texture_R.cols(),255);\n  dirty |= MeshGL::DIRTY_TEXTURE;\n}\n\nIGL_INLINE void igl::opengl::ViewerData::updateGL(\n  const igl::opengl::ViewerData& data,\n  const bool invert_normals,\n  igl::opengl::MeshGL& meshgl\n  )\n{\n  if (!meshgl.is_initialized)\n  {\n    meshgl.init();\n  }\n\n  bool per_corner_uv = (data.F_uv.rows() == data.F.rows());\n  bool per_corner_normals = (data.F_normals.rows() == 3 * data.F.rows());\n\n  meshgl.dirty |= data.dirty;\n\n  // Input:\n  //   X  #F by dim quantity\n  // Output:\n  //   X_vbo  #F*3 by dim scattering per corner\n  const auto per_face = [&data](\n      const Eigen::MatrixXd & X,\n      MeshGL::RowMatrixXf & X_vbo)\n  {\n    assert(X.cols() == 4);\n    X_vbo.resize(data.F.rows()*3,4);\n    for (unsigned i=0; i<data.F.rows();++i)\n      for (unsigned j=0;j<3;++j)\n        X_vbo.row(i*3+j) = X.row(i).cast<float>();\n  };\n\n  // Input:\n  //   X  #V by dim quantity\n  // Output:\n  //   X_vbo  #F*3 by dim scattering per corner\n  const auto per_corner = [&data](\n      const Eigen::MatrixXd & X,\n      MeshGL::RowMatrixXf & X_vbo)\n  {\n    X_vbo.resize(data.F.rows()*3,X.cols());\n    for (unsigned i=0; i<data.F.rows();++i)\n      for (unsigned j=0;j<3;++j)\n        X_vbo.row(i*3+j) = X.row(data.F(i,j)).cast<float>();\n  };\n\n  if (!data.face_based)\n  {\n    if (!(per_corner_uv || per_corner_normals))\n    {\n      // Vertex positions\n      if (meshgl.dirty & MeshGL::DIRTY_POSITION)\n        meshgl.V_vbo = data.V.cast<float>();\n\n      // Vertex normals\n      if (meshgl.dirty & MeshGL::DIRTY_NORMAL)\n      {\n        meshgl.V_normals_vbo = data.V_normals.cast<float>();\n        if (invert_normals)\n          meshgl.V_normals_vbo = -meshgl.V_normals_vbo;\n      }\n\n      // Per-vertex material settings\n      if (meshgl.dirty & MeshGL::DIRTY_AMBIENT)\n        meshgl.V_ambient_vbo = data.V_material_ambient.cast<float>();\n      if (meshgl.dirty & MeshGL::DIRTY_DIFFUSE)\n        meshgl.V_diffuse_vbo = data.V_material_diffuse.cast<float>();\n      if (meshgl.dirty & MeshGL::DIRTY_SPECULAR)\n        meshgl.V_specular_vbo = data.V_material_specular.cast<float>();\n\n      // Face indices\n      if (meshgl.dirty & MeshGL::DIRTY_FACE)\n        meshgl.F_vbo = data.F.cast<unsigned>();\n\n      // Texture coordinates\n      if (meshgl.dirty & MeshGL::DIRTY_UV)\n      {\n        meshgl.V_uv_vbo = data.V_uv.cast<float>();\n      }\n    }\n    else\n    {\n\n      // Per vertex properties with per corner UVs\n      if (meshgl.dirty & MeshGL::DIRTY_POSITION)\n      {\n        per_corner(data.V,meshgl.V_vbo);\n      }\n\n      if (meshgl.dirty & MeshGL::DIRTY_AMBIENT)\n      {\n        meshgl.V_ambient_vbo.resize(data.F.rows()*3,4);\n        for (unsigned i=0; i<data.F.rows();++i)\n          for (unsigned j=0;j<3;++j)\n            meshgl.V_ambient_vbo.row(i*3+j) = data.V_material_ambient.row(data.F(i,j)).cast<float>();\n      }\n      if (meshgl.dirty & MeshGL::DIRTY_DIFFUSE)\n      {\n        meshgl.V_diffuse_vbo.resize(data.F.rows()*3,4);\n        for (unsigned i=0; i<data.F.rows();++i)\n          for (unsigned j=0;j<3;++j)\n            meshgl.V_diffuse_vbo.row(i*3+j) = data.V_material_diffuse.row(data.F(i,j)).cast<float>();\n      }\n      if (meshgl.dirty & MeshGL::DIRTY_SPECULAR)\n      {\n        meshgl.V_specular_vbo.resize(data.F.rows()*3,4);\n        for (unsigned i=0; i<data.F.rows();++i)\n          for (unsigned j=0;j<3;++j)\n            meshgl.V_specular_vbo.row(i*3+j) = data.V_material_specular.row(data.F(i,j)).cast<float>();\n      }\n\n      if (meshgl.dirty & MeshGL::DIRTY_NORMAL)\n      {\n        meshgl.V_normals_vbo.resize(data.F.rows()*3,3);\n        for (unsigned i=0; i<data.F.rows();++i)\n          for (unsigned j=0;j<3;++j)\n            meshgl.V_normals_vbo.row(i*3+j) =\n                         per_corner_normals ?\n               data.F_normals.row(i*3+j).cast<float>() :\n               data.V_normals.row(data.F(i,j)).cast<float>();\n\n\n        if (invert_normals)\n          meshgl.V_normals_vbo = -meshgl.V_normals_vbo;\n      }\n\n      if (meshgl.dirty & MeshGL::DIRTY_FACE)\n      {\n        meshgl.F_vbo.resize(data.F.rows(),3);\n        for (unsigned i=0; i<data.F.rows();++i)\n          meshgl.F_vbo.row(i) << i*3+0, i*3+1, i*3+2;\n      }\n\n      if (meshgl.dirty & MeshGL::DIRTY_UV)\n      {\n        meshgl.V_uv_vbo.resize(data.F.rows()*3,2);\n        for (unsigned i=0; i<data.F.rows();++i)\n          for (unsigned j=0;j<3;++j)\n            meshgl.V_uv_vbo.row(i*3+j) =\n              data.V_uv.row(per_corner_uv ?\n                data.F_uv(i,j) : data.F(i,j)).cast<float>();\n      }\n    }\n  }\n  else\n  {\n    if (meshgl.dirty & MeshGL::DIRTY_POSITION)\n    {\n      per_corner(data.V,meshgl.V_vbo);\n    }\n    if (meshgl.dirty & MeshGL::DIRTY_AMBIENT)\n    {\n      per_face(data.F_material_ambient,meshgl.V_ambient_vbo);\n    }\n    if (meshgl.dirty & MeshGL::DIRTY_DIFFUSE)\n    {\n      per_face(data.F_material_diffuse,meshgl.V_diffuse_vbo);\n    }\n    if (meshgl.dirty & MeshGL::DIRTY_SPECULAR)\n    {\n      per_face(data.F_material_specular,meshgl.V_specular_vbo);\n    }\n\n    if (meshgl.dirty & MeshGL::DIRTY_NORMAL)\n    {\n      meshgl.V_normals_vbo.resize(data.F.rows()*3,3);\n      for (unsigned i=0; i<data.F.rows();++i)\n        for (unsigned j=0;j<3;++j)\n          meshgl.V_normals_vbo.row(i*3+j) =\n             per_corner_normals ?\n               data.F_normals.row(i*3+j).cast<float>() :\n               data.F_normals.row(i).cast<float>();\n\n      if (invert_normals)\n        meshgl.V_normals_vbo = -meshgl.V_normals_vbo;\n    }\n\n    if (meshgl.dirty & MeshGL::DIRTY_FACE)\n    {\n      meshgl.F_vbo.resize(data.F.rows(),3);\n      for (unsigned i=0; i<data.F.rows();++i)\n        meshgl.F_vbo.row(i) << i*3+0, i*3+1, i*3+2;\n    }\n\n    if (meshgl.dirty & MeshGL::DIRTY_UV)\n    {\n        meshgl.V_uv_vbo.resize(data.F.rows()*3,2);\n        for (unsigned i=0; i<data.F.rows();++i)\n          for (unsigned j=0;j<3;++j)\n            meshgl.V_uv_vbo.row(i*3+j) = data.V_uv.row(per_corner_uv ? data.F_uv(i,j) : data.F(i,j)).cast<float>();\n    }\n  }\n\n  if (meshgl.dirty & MeshGL::DIRTY_TEXTURE)\n  {\n    meshgl.tex_u = data.texture_R.rows();\n    meshgl.tex_v = data.texture_R.cols();\n    meshgl.tex.resize(data.texture_R.size()*4);\n    for (unsigned i=0;i<data.texture_R.size();++i)\n    {\n      meshgl.tex(i*4+0) = data.texture_R(i);\n      meshgl.tex(i*4+1) = data.texture_G(i);\n      meshgl.tex(i*4+2) = data.texture_B(i);\n      meshgl.tex(i*4+3) = data.texture_A(i);\n    }\n  }\n\n  if (meshgl.dirty & MeshGL::DIRTY_OVERLAY_LINES)\n  {\n    meshgl.lines_V_vbo.resize(data.lines.rows()*2,3);\n    meshgl.lines_V_colors_vbo.resize(data.lines.rows()*2,3);\n    meshgl.lines_F_vbo.resize(data.lines.rows()*2,1);\n    for (unsigned i=0; i<data.lines.rows();++i)\n    {\n      meshgl.lines_V_vbo.row(2*i+0) = data.lines.block<1, 3>(i, 0).cast<float>();\n      meshgl.lines_V_vbo.row(2*i+1) = data.lines.block<1, 3>(i, 3).cast<float>();\n      meshgl.lines_V_colors_vbo.row(2*i+0) = data.lines.block<1, 3>(i, 6).cast<float>();\n      meshgl.lines_V_colors_vbo.row(2*i+1) = data.lines.block<1, 3>(i, 6).cast<float>();\n      meshgl.lines_F_vbo(2*i+0) = 2*i+0;\n      meshgl.lines_F_vbo(2*i+1) = 2*i+1;\n    }\n  }\n\n  if (meshgl.dirty & MeshGL::DIRTY_OVERLAY_POINTS)\n  {\n    meshgl.points_V_vbo.resize(data.points.rows(),3);\n    meshgl.points_V_colors_vbo.resize(data.points.rows(),3);\n    meshgl.points_F_vbo.resize(data.points.rows(),1);\n    for (unsigned i=0; i<data.points.rows();++i)\n    {\n      meshgl.points_V_vbo.row(i) = data.points.block<1, 3>(i, 0).cast<float>();\n      meshgl.points_V_colors_vbo.row(i) = data.points.block<1, 3>(i, 3).cast<float>();\n      meshgl.points_F_vbo(i) = i;\n    }\n  }\n}\n", "meta": {"hexsha": "e30c318540e92c7d80b88d3fc8e4acce24dab4b3", "size": 34634, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "igl/opengl/ViewerData.cpp", "max_stars_repo_name": "aviadtzemah/animation1", "max_stars_repo_head_hexsha": "d15073869fd1af824e406b53e782c58726229320", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "igl/opengl/ViewerData.cpp", "max_issues_repo_name": "aviadtzemah/animation1", "max_issues_repo_head_hexsha": "d15073869fd1af824e406b53e782c58726229320", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "igl/opengl/ViewerData.cpp", "max_forks_repo_name": "aviadtzemah/animation1", "max_forks_repo_head_hexsha": "d15073869fd1af824e406b53e782c58726229320", "max_forks_repo_licenses": ["Apache-2.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.6581352834, "max_line_length": 143, "alphanum_fraction": 0.577727089, "num_tokens": 10282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.4863351806984699}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n\nnamespace polyfem\n{\n\t///\n\t/// Generate a canonical triangle/quad subdivided from a regular grid\n\t///\n\t/// @param[in]  n  \t\t\t { n grid quads }\n\t/// @param[in]  tri\t\t\t { is a tri or a quad }\n\t/// @param[out] V            { #V x 2 output vertices positions }\n\t/// @param[out] F            { #F x 3 output triangle indices }\n\t///\n\tvoid regular_2d_grid(const int n, bool tri, Eigen::MatrixXd &V, Eigen::MatrixXi &F);\n\n\t///\n\t/// Generate a canonical tet/hex subdivided from a regular grid\n\t///\n\t/// @param[in]  n  \t\t\t { n grid quads }\n\t/// @param[in]  tet\t\t\t { is a tet or a hex }\n\t/// @param[out] V            { #V x 3 output vertices positions }\n\t/// @param[out] F            { #F x 3 output triangle indices }\n\t/// @param[out] T            { #F x 4 output tet indices }\n\t///\n\tvoid regular_3d_grid(const int nn, bool tet, Eigen::MatrixXd &V, Eigen::MatrixXi &F, Eigen::MatrixXi &T);\n\n\tclass RefElementSampler\n\t{\n\tpublic:\n\t\tRefElementSampler() {}\n\t\tvoid init(const bool is_volume, const int n_elements, const double target_rel_area);\n\n\t\tconst Eigen::MatrixXd &cube_corners() const { return cube_corners_; }\n\t\tconst Eigen::MatrixXd &cube_points() const { return cube_points_; }\n\t\tconst Eigen::MatrixXi &cube_faces() const { return cube_faces_; }\n\t\tconst Eigen::MatrixXi &cube_volume() const { return is_volume_ ? cube_tets_ : cube_faces_; }\n\t\tconst Eigen::MatrixXi &cube_edges() const { return cube_edges_; }\n\n\t\tconst Eigen::MatrixXd &simplex_corners() const { return simplex_corners_; }\n\t\tconst Eigen::MatrixXd &simplex_points() const { return simplex_points_; }\n\t\tconst Eigen::MatrixXi &simplex_faces() const { return simplex_faces_; }\n\t\tconst Eigen::MatrixXi &simplex_volume() const { return is_volume_ ? simplex_tets_ : simplex_faces_; }\n\t\tconst Eigen::MatrixXi &simplex_edges() const { return simplex_edges_; }\n\n\t\tvoid sample_polygon(const Eigen::MatrixXd &poly, Eigen::MatrixXd &pts, Eigen::MatrixXi &faces) const;\n\t\tvoid sample_polyhedron(const Eigen::MatrixXd &vertices, const Eigen::MatrixXi &f, Eigen::MatrixXd &pts, Eigen::MatrixXi &faces) const;\n\n\t\tinline int num_samples() const\n\t\t{\n\t\t\treturn is_volume_ ? std::max(2., round(1. / pow(area_param_, 1. / 3.) + 1)) : std::max(2., round(1. / sqrt(area_param_) + 1));\n\t\t}\n\n\tprivate:\n\t\tvoid build();\n\n\t\tEigen::MatrixXi cube_tets_;\n\t\tEigen::MatrixXi simplex_tets_;\n\n\t\tEigen::MatrixXd cube_corners_;\n\t\tEigen::MatrixXd cube_points_;\n\t\tEigen::MatrixXi cube_faces_;\n\t\tEigen::MatrixXi cube_edges_;\n\n\t\tEigen::MatrixXd simplex_corners_;\n\t\tEigen::MatrixXd simplex_points_;\n\t\tEigen::MatrixXi simplex_faces_;\n\t\tEigen::MatrixXi simplex_edges_;\n\n\t\tdouble area_param_;\n\t\tdouble is_volume_;\n\t};\n\n} // namespace polyfem\n", "meta": {"hexsha": "47686e3d3e41d4ab0285e8edbb186ce2c49f97ea", "size": 2693, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/utils/RefElementSampler.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/utils/RefElementSampler.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/utils/RefElementSampler.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": 35.9066666667, "max_line_length": 136, "alphanum_fraction": 0.6851095433, "num_tokens": 735, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.4863351806984699}}
{"text": "/* Boost libs/numeric/odeint/examples/integrate_times.cpp\r\n\r\n Copyright 2009-2014 Karsten Ahnert\r\n Copyright 2009-2014 Mario Mulansky\r\n\r\n example for the use of integrate_times\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#include <iostream>\r\n#include <boost/numeric/odeint.hpp>\r\n\r\nusing namespace std;\r\nusing namespace boost::numeric::odeint;\r\n\r\n\r\n/*\r\n * simple 1D ODE\r\n */\r\n\r\nvoid rhs( const double x , double &dxdt , const double t )\r\n{\r\n    dxdt = 3.0/(2.0*t*t) + x/(2.0*t);\r\n}\r\n\r\nvoid write_cout( const double &x , const double t )\r\n{\r\n    cout << t << '\\t' << x << endl;\r\n}\r\n\r\n// state_type = double\r\ntypedef runge_kutta_dopri5< double > stepper_type;\r\n\r\nconst double dt = 0.1;\r\n\r\nint main()\r\n{\r\n    // create a vector with observation time points\r\n    std::vector<double> times( 91 );\r\n    for( size_t i=0 ; i<times.size() ; ++i )\r\n        times[i] = 1.0 + dt*i;\r\n\r\n    double x = 0.0; //initial value x(1) = 0\r\n    // we can provide the observation time as a boost range (i.e. the vector)\r\n    integrate_times( make_controlled( 1E-12 , 1E-12 , stepper_type() ) , rhs ,\r\n                     x , times , dt , write_cout );\r\n    // or as two iterators\r\n    //integrate_times( make_controlled( 1E-12 , 1E-12 , stepper_type() ) , rhs ,\r\n    //                   x , times.begin() , times.end() , dt , write_cout );\r\n}\r\n", "meta": {"hexsha": "08b381006b0c61c29c02d059b7279302b599b88d", "size": 1442, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/numeric/odeint/examples/integrate_times.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": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/numeric/odeint/examples/integrate_times.cpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-04T18:00:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-04T18:00:00.000Z", "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/numeric/odeint/examples/integrate_times.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 26.2181818182, "max_line_length": 81, "alphanum_fraction": 0.6165048544, "num_tokens": 413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.48633517748980976}}
{"text": "/**\n * Created by Beck on 18/6/2018\n * Indirect Extended Kalman Filter for the pose\n * to get an estimate of the pose of the shield\n * fusing visual information with the gyroscope\n * With IMU fused reading comes in 100Hz and camera translation in 30Hz\n * V1: works for rotation only\n */\n#include <iostream>\n#include <ros/ros.h>\n#include <ros/console.h>\n#include <std_msgs/String.h>\n#include <geometry_msgs/PoseStamped.h>\n#include <geometry_msgs/PoseWithCovarianceStamped.h>\n#include <geometry_msgs/TwistStamped.h>\n#include <geometry_msgs/Vector3Stamped.h>\n// #include <Eigen/Eigen>\n#include <Eigen/Geometry>\n#include <queue>\n//#include \"rm_cv/ArmorRecord.h\"\n\nusing namespace std;\nusing namespace Eigen;\nros::Publisher pose_pub, debug_pub, debug_gyro_pub;\nstring omg_topic, visual_topic, publisher_topic;\ndouble gyro_weight;\ndouble visual_q_weight, visual_t_weight;\nint sleep_time;\n\n/**\n * Define states:\n *      x = [rotation_quaternion]\n * Define inputs:\n *      u = [omg], filtered angular velocity\n * Define noises:\n *      n = [n_gyro]\n */\nVectorXd x(4);                        // state\n// MatrixXd P = MatrixXd::Zero(3, 3);     // covariance\nMatrixXd P = MatrixXd::Identity(3, 3); // covariance\nMatrixXd R = MatrixXd::Identity(3, 3); // prediction noise covariance\nMatrixXd Q = MatrixXd::Identity(3, 3); // observation noise covariance\n\n// buffers to save gyro and visual reading\nqueue<geometry_msgs::Vector3Stamped::ConstPtr> gyro_buf;\nqueue<geometry_msgs::TwistStamped::ConstPtr> visual_buf;\nqueue<Matrix<double, 4, 1>> x_history;\nqueue<Matrix<double, 3, 3>> P_history;\nVector3d G_body = {0, 0, 9.8}; // Consider to add initialization later\n\n// previous propagated time\ndouble t_prev;\n\n// Initialization\nconst int GYRO_INIT_COUNT = 10;\nconst int MAX_GYRO_QUEUE_SIZE = 500;\nint gyro_count  = 0;\nbool gyro_initialized = false;\nbool visual_initialized = false;\nbool visual_valid = false;\nMatrixXd imu_R_camera = MatrixXd::Identity(3, 3); // rotation matrix from camera to imu\nVector3d imu_T_camera = MatrixXd::Zero(3, 1);\n\nvoid pub_fused_pose(std_msgs::Header header)\n{\n    geometry_msgs::PoseWithCovarianceStamped pose;\n    pose.header = header;\n    pose.pose.pose.orientation.w = x(0);\n    pose.pose.pose.orientation.x = x(1);\n    pose.pose.pose.orientation.y = x(2);\n    pose.pose.pose.orientation.z = x(3);\n    pose.pose.covariance[0] = P(0, 0);\n    pose.pose.covariance[1] = P(1, 1);\n    pose.pose.covariance[2] = P(2, 2);\n\n    pose_pub.publish(pose);\n}\n\nvoid pub_debug_pose(std_msgs::Header header, const Quaterniond& q)\n{\n    geometry_msgs::PoseStamped pose;\n    pose.header = header;\n    pose.pose.orientation.w = q.w();\n    pose.pose.orientation.x = q.x();\n    pose.pose.orientation.y = q.y();\n    pose.pose.orientation.z = q.z();\n    debug_pub.publish(pose);\n}\n\nvoid pub_fused_angleAxis(std_msgs::Header header)\n{\n    geometry_msgs::PoseWithCovarianceStamped angleAxis;\n    angleAxis.header = header;\n\n    Quaterniond pose_state(x(0), x(1), x(2), x(3));\n    AngleAxisd angle_state(pose_state);\n\n    angleAxis.pose.pose.orientation.w = angle_state.angle();\n    angleAxis.pose.pose.orientation.x = angle_state.axis()[0];\n    angleAxis.pose.pose.orientation.y = angle_state.axis()[1];\n    angleAxis.pose.pose.orientation.z = angle_state.axis()[2];\n    angleAxis.pose.covariance[0] = P(0, 0);\n    angleAxis.pose.covariance[1] = P(1, 1);\n    angleAxis.pose.covariance[2] = P(2, 2);\n    pose_pub.publish(angleAxis);\n}\n\nvoid pub_debug_angleAxis(std_msgs::Header header, const Eigen::Vector3d axis, const double angle)\n{\n    geometry_msgs::PoseStamped angleAxis;\n    angleAxis.header = header;\n    angleAxis.pose.orientation.w = angle;\n    angleAxis.pose.orientation.x = axis.x();\n    angleAxis.pose.orientation.y = axis.y();\n    angleAxis.pose.orientation.z = axis.z();\n    debug_pub.publish(angleAxis);\n}\n\nvoid propagate(const geometry_msgs::Vector3Stamped &gyro)\n{\n    double cur_t = gyro.header.stamp.toSec();\n    // ROS_INFO(\"propagate\");\n    Vector3d w;\n    w(0) = gyro.vector.x;\n    w(1) = gyro.vector.y;\n    w(2) = gyro.vector.z;\n\n    double dt = cur_t - t_prev;\n    // ROS_INFO(\"dt in propagate is %f, at the cur_t %f, with t_prev at %f\", dt, cur_t, t_prev);\n\t// ROS_INFO(\"propagate, with dt %f\", dt);\n    Vector3d domg = 0.5 * dt * w;\n\n    Quaterniond dq(sqrt(1 - domg.squaredNorm()), domg(0), domg(1), domg(2));\n    // Quaterniond dq(1, domg(0), domg(1), domg(2));\n\t// ROS_INFO(\"dq w x y z %f %f %f %f\", dq.w(), dq.x(), dq.y(), dq.z() );\n    Quaterniond q_state(x(0), x(1), x(2), x(3));\n    Quaterniond q = (q_state * dq).normalized();\n\n    x(0) = q.w();\n    x(1) = q.x();\n    x(2) = q.y();\n    x(3) = q.z();\n\n    Matrix3d w_hat;\n    w_hat << 0,-w(2), w(1),\n            w(2), 0, -w(0),\n           -w(1), w(0), 0;\n    Matrix3d A = -w_hat;\n\n    MatrixXd U = -MatrixXd::Identity(3, 3);\n\n    MatrixXd F, V;\n    F = MatrixXd::Identity(3, 3) + dt * A;\n    V = dt * U;\n\n    P = F * P * F.transpose() + V * R * V.transpose();\n\t\n    t_prev = cur_t;\n\t// cout << \"P \" << endl << P << endl;\n\t// cout << \"x \" << endl << x.transpose() << endl;\n}\n\nstatic void update(const geometry_msgs::TwistStamped::ConstPtr &pnp)\n{\n    Vector3d camera_T_shield;\n    ROS_INFO(\"Update, at time %f\", pnp->header.stamp.toSec());\n\n    camera_T_shield[0] = pnp->twist.linear.x;\n    camera_T_shield[1] = pnp->twist.linear.y;\n    camera_T_shield[2] = pnp->twist.linear.z;\n    Vector3d imu_T_shield = imu_R_camera * camera_T_shield + imu_T_camera;\n\n    Vector3d T_norm = imu_T_shield.normalized();\n    Vector3d x_axis = Vector3d::UnitX();\n    // Vector3d axis = x_axis.cross(T_norm).normalized();\n    // double angle = acos( x_axis.dot(T_norm) );\n    Vector3d axis = T_norm.cross(x_axis).normalized();\n    double angle = acos( T_norm.dot(x_axis) );\n    AngleAxisd camera_R_shield(angle, axis);\n    Quaterniond camera_q_shield(camera_R_shield);\n\n/*\n    Quaterniond camera_q_shield;\n    camera_q_shield.w() = x_axis.dot(T_norm);\n    camera_q_shield.x() = sin(0.5 * angle) * axis(0);\n    camera_q_shield.y() = sin(0.5 * angle) * axis(1);\n    camera_q_shield.z() = sin(0.5 * angle) * axis(2);\n    camera_q_shield.normalize();\n    // Debug original pose from camera\n    pub_debug_pose(pnp->header, camera_q_shield);\n\n    */\n\n    pub_debug_angleAxis(pnp->header, axis, angle);\n\n    Matrix3d C = Matrix3d::Identity();\n\n    MatrixXd K(3, 3);\n    K = P * C.transpose() * (C * P* C.transpose() + Q).inverse();\n\n    VectorXd r(3); // residual\n    Quaterniond qm = camera_q_shield;\n    Quaterniond q  = Quaterniond(x(0), x(1), x(2), x(3));\n    Quaterniond dq = q.conjugate() * qm;\n    // ROS_INFO(\"dq w x y z %f %f %f %f\", dq.w(), dq.x(), dq.y(), dq.z() );\n    r = 2 * dq.vec();\n    Vector3d _r = K * r;\n    // ROS_INFO(\"dr x y z %f %f %f\", _r[0], _r[1], _r[2] );\n    Vector3d dw(_r(0) * 0.5, _r(1) * 0.5, _r(2) * 0.5);\n    dq = Quaterniond(sqrt(1 - dw.squaredNorm()), dw(0), dw(1), dw(2)).normalized();\n    q  = q * dq;\n\n    x(0) = q.w();\n    x(1) = q.x();\n    x(2) = q.y();\n    x(3) = q.z();\n\n    P = P - K * C * P;\n\t// cout << \"P \" << endl << P << endl;\n\t// cout << \"x \" << endl << x.transpose() << endl;\n}\n\n/**\n * initialization of the gyroscope\n * @param gyro\n */\nstatic void initialize_gyro(const geometry_msgs::Vector3Stamped::ConstPtr &gyro)\n{\n    t_prev = gyro->header.stamp.toSec();\n    x_history.push(x);\n    P_history.push(P);\n    gyro_buf.push(gyro);\n    gyro_count++;\n    if (gyro_count == GYRO_INIT_COUNT) {\n        gyro_initialized = true;\n    }\n}\n\n/**\n * initialization of the state and convariance from visual\n * @param pnp\n */\nstatic void initialize_visual(const geometry_msgs::TwistStamped::ConstPtr &pnp)\n{\n    double cur_t = pnp->header.stamp.toSec();\n    Vector3d camera_T_shield;\n\n    camera_T_shield[0] = pnp->twist.linear.x;\n    camera_T_shield[1] = pnp->twist.linear.y;\n    camera_T_shield[2] = pnp->twist.linear.z;\n    Vector3d imu_T_shield = imu_R_camera * camera_T_shield + imu_T_camera;\n\n    Vector3d T_norm = imu_T_shield.normalized();\n    Vector3d x_axis = Vector3d::UnitX();\n    // Vector3d axis = x_axis.cross(T_norm).normalized();\n    // double angle = acos( x_axis.dot(T_norm) );\n    Vector3d axis = T_norm.cross(x_axis).normalized();\n    double angle = acos( T_norm.dot(x_axis) );\n    AngleAxisd camera_R_shield(angle, axis);\n    Quaterniond camera_q_shield(camera_R_shield);\n/*\n    Quaterniond camera_q_shield;\n    camera_q_shield.w() = x_axis.dot(T_norm);\n    camera_q_shield.x() = sin(0.5 * angle) * axis(0);\n    camera_q_shield.y() = sin(0.5 * angle) * axis(1);\n    camera_q_shield.z() = sin(0.5 * angle) * axis(2);\n    camera_q_shield.normalize();\n*/\n\n    x(0) = camera_q_shield.w();\n    x(1) = camera_q_shield.x();\n    x(2) = camera_q_shield.y();\n    x(3) = camera_q_shield.z();\n    P = MatrixXd::Identity(3, 3);\n\tROS_INFO(\"visual init at %f\", cur_t);\n    cout << \"DEBUG: x initialized with \" << endl << x.transpose() << endl;\n\n    // pub_fused_pose(pnp->header);\n    pub_fused_angleAxis(pnp->header);\n    t_prev = cur_t;\n\n    visual_initialized = true;\n}\n\n/**\n * Processing the valid visual and gyro information\n */\nstatic void state_machine_process(void)\n{\n    if (!gyro_initialized)\n        return;\n    //if (!visual_initialized)\n    if (!visual_valid)\n        return;\n\n    while (!visual_buf.empty()) {\n        while(!gyro_buf.empty() &&\n              gyro_buf.front()->header.stamp < visual_buf.front()->header.stamp)\n        {\n            // trace backward the time to the imu timestamp\n            t_prev = gyro_buf.front()->header.stamp.toSec();\n            ROS_INFO(\"throw state with time: %f\", t_prev);\n            gyro_buf.pop();\n            x_history.pop();\n            P_history.pop();\n        }\n\n        geometry_msgs::TwistStamped::ConstPtr visual_msg = visual_buf.front();\n\n        update(visual_msg);\n        visual_buf.pop();\n        // pub_fused_angleAxis(visual_msg->header);\n\n        // Repropagate\n        while (!x_history.empty()) x_history.pop();\n        while (!P_history.empty()) P_history.pop();\n\n        queue <geometry_msgs::Vector3Stamped::ConstPtr> temp_gyro_buf;\n        while (!gyro_buf.empty())\n        {\n            propagate(*gyro_buf.front());\n            temp_gyro_buf.push(gyro_buf.front());\n            x_history.push(x);\n            P_history.push(P);\n            gyro_buf.pop();\n        }\n        swap(gyro_buf, temp_gyro_buf);\n\n        // pub_fused_angleAxis();\n    }\n}\n\n/**\n * handle, save, and process visual messages\n * @param pnp\n */\nvoid visual_callback(const geometry_msgs::TwistStamped::ConstPtr &pnp)\n{\n    visual_valid = !(pnp->twist.linear.x == 0 &&\n        pnp->twist.linear.y == 0 &&\n        pnp->twist.linear.z == 0 );\n\n    if (visual_valid && visual_initialized) {\n\n        visual_buf.push(pnp);\n    }\n    else if (visual_valid && !visual_initialized) {\n        initialize_visual(pnp);\n        visual_buf.push(pnp);\n    }\n\n    state_machine_process();\n}\n\n/**\n * handle 100Hz angular filtered gyroscope\n * @param gyro\n */\nvoid gyro_callback(const geometry_msgs::Vector3Stamped::ConstPtr &gyro)\n{\n    if (!gyro_initialized) {\n        initialize_gyro(gyro);\n    }\n    else {\n        propagate(*gyro);\n        // pub_fused_pose(gyro->header);\n        pub_fused_angleAxis(gyro->header);\n        x_history.push(x);\n        P_history.push(P);\n        gyro_buf.push(gyro);\n\t\tif (gyro_buf.size() > MAX_GYRO_QUEUE_SIZE) {\n\t\t\tx_history.pop();\n\t\t\tP_history.pop();\n\t\t\tgyro_buf.pop();\n\t\t}\n    }\n}\n\nint main(int argc, char **argv)\n{\n    ros::init(argc, argv, \"visual_gyro_fused\");\n    ros::NodeHandle n(\"~\");\n\n    n.param(\"angular_fused\", omg_topic, string(\"/dji_sdk/angular_velocity_fused\")); // 100Hz\n    n.param(\"visual_topic\", visual_topic, string(\"/pnp_twist\"));\n    n.param(\"publisher_topic\", publisher_topic, string(\"/visual_ekf/shield_pose_fused\"));\n    n.param(\"gyroscope_noise_weight\", gyro_weight, 0.1);\n    n.param(\"visual_pose_weight\", visual_q_weight, 1.0);\n    n.param(\"node_sleep_time\", sleep_time, 10);\n\n    // TODO: initalize the R and Q matrix\n    R =     gyro_weight * MatrixXd::Identity(3, 3); // gyro noise\n    Q = visual_q_weight * MatrixXd::Identity(3, 3); // observation noise\n\n    x.setZero();\n    x(0) = 1; // set quaternion to identity\n    P = 1.0 * P;\n\n    imu_R_camera <<  0, 0, 1,\n                    -1, 0, 0,\n                     0,-1, 0;\n\n    imu_T_camera <<  200, 50, 0; // in millimeter\n\n    ros::Subscriber s2 = n.subscribe(visual_topic, 10, visual_callback);\n    ros::Subscriber s3 = n.subscribe(omg_topic, 100, gyro_callback);\n//    pose_pub = n.advertise<geometry_msgs::PoseStamped>(publisher_topic, 100);\n    pose_pub = n.advertise<geometry_msgs::PoseWithCovarianceStamped>(publisher_topic, 100);\n    debug_pub= n.advertise<geometry_msgs::PoseStamped>(string(\"/visual_ekf/visual_ekf_debug\"), 100);\n//    debug_gyro_pub= n.advertise<geometry_msgs::Vector3Stamped>(string(\"/visual_ekf/gyro_debug\"), 100);\n\n    ros::Rate r(100);\n    ros::spin();\n}\n\n/**\n *  0   q_w     shield frame --> camera frame\n *  1   q_x\n *  2   q_y\n *  3   q_z\n */\n\n\n\n\n/*\n        // DEBUG geometry relationship in visual_callback()\n        update(pnp);\n        pub_fused_angleAxis(pnp->header);\n\n        geometry_msgs::TwistStamped::ConstPtr prev_pnp = visual_buf.front();\n\n        Vector3d camera_T_shield;\n        camera_T_shield[0] = prev_pnp->twist.linear.x;\n        camera_T_shield[1] = prev_pnp->twist.linear.y;\n        camera_T_shield[2] = prev_pnp->twist.linear.z;\n        Vector3d imu_T_shield = imu_R_camera * camera_T_shield;\n\n        Vector3d T_norm = imu_T_shield.normalized();\n        Vector3d x_axis = Vector3d::UnitX();\n    //    Vector3d axis = x_axis.cross(T_norm).normalized();\n    //    double angle = acos( x_axis.dot(T_norm) );\n        Vector3d axis = T_norm.cross(x_axis).normalized();\n        double angle = acos( T_norm.dot(x_axis) );\n        AngleAxisd R_prev(angle, axis);\n        Quaterniond q_prev(R_prev);\n\n        camera_T_shield[0] = pnp->twist.linear.x;\n        camera_T_shield[1] = pnp->twist.linear.y;\n        camera_T_shield[2] = pnp->twist.linear.z;\n        imu_T_shield = imu_R_camera * camera_T_shield;\n\n        T_norm = imu_T_shield.normalized();\n    //    axis = x_axis.cross(T_norm).normalized();\n    //    angle = acos( x_axis.dot(T_norm) );\n        axis = T_norm.cross(x_axis).normalized();\n        angle = acos( T_norm.dot(x_axis) );\n        AngleAxisd R_now(angle, axis);\n        Quaterniond q_now(R_now);\n\n        Quaterniond dq = q_prev.conjugate() * q_now;\n        // Quaterniond dq = q_now.conjugate() * q_prev;\n        Vector3d d_theta = 2 * dq.vec();\n        double dt_omg = pnp->header.stamp.toSec() - prev_pnp->header.stamp.toSec();\n        Vector3d omg = d_theta / dt_omg;\n\n        geometry_msgs::Vector3Stamped gyro_debug;\n        gyro_debug.header = pnp->header;\n        gyro_debug.vector.x = omg[0];\n        gyro_debug.vector.y = omg[1];\n        gyro_debug.vector.z = omg[2];\n        propagate( gyro_debug );\n        t_prev = pnp->header.stamp.toSec();\n        debug_gyro_pub.publish(gyro_debug);\n\n        visual_buf.pop();\n\n        */\n", "meta": {"hexsha": "d097aa21c5bea51b4e1d3ae91814aa67036e7f35", "size": 14961, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3_estimator/history/visual_ekf/src/visual_ekf_node_rotation.cpp", "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/history/visual_ekf/src/visual_ekf_node_rotation.cpp", "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/history/visual_ekf/src/visual_ekf_node_rotation.cpp", "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": 31.2338204593, "max_line_length": 104, "alphanum_fraction": 0.6343827284, "num_tokens": 4308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234877, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.48630276150436375}}
{"text": "#include \"controllers/sfm_aligner.h\"\n\n#include <ceres/cost_function.h>\n#include <ceres/problem.h>\n#include <ceres/rotation.h>\n#include <ceres/solver.h>\n#include <glog/logging.h>\n\n#include <Eigen/Cholesky>\n#include <Eigen/Geometry>\n#include <Eigen/SparseCholesky>\n#include <Eigen/SparseCore>\n#include <limits>\n#include <memory>\n#include <unordered_map>\n#include <vector>\n\n#include \"base/similarity_transform.h\"\n#include \"base/track_selection.h\"\n#include \"estimators/ransac_similarity.h\"\n#include \"estimators/sim3.h\"\n#include \"estimators/similarity_transform.h\"\n#include \"math/util.h\"\n#include \"optim/bundle_adjustment.h\"\n#include \"sfm/incremental_triangulator.h\"\n#include \"solver/l1_solver.h\"\n#include \"util/misc.h\"\n#include \"util/reconstruction_io.h\"\n#include \"util/timer.h\"\n\nnamespace DAGSfM {\nnamespace {\n\ndouble CheckReprojError(const vector<Eigen::Vector3d>& src_observations,\n                        const vector<Eigen::Vector3d>& dst_observations,\n                        const double& scale, const Eigen::Matrix3d& R,\n                        const Eigen::Vector3d& t) {\n  double reproj_err = 0.0;\n  const int size = src_observations.size();\n  for (int i = 0; i < size; i++) {\n    Eigen::Vector3d reproj_obv = scale * R * src_observations[i] + t;\n    reproj_err += (reproj_obv - dst_observations[i]).norm();\n  }\n\n  LOG(INFO) << \"Mean Reprojection Error: \" << reproj_err / size << \" (\"\n            << reproj_err << \"/\" << size << \")\";\n  return reproj_err / size;\n}\n\nvoid FindSimilarityTransform(const std::vector<Eigen::Vector3d>& observations1,\n                             const std::vector<Eigen::Vector3d>& observations2,\n                             const double threshold, const double p,\n                             Eigen::Matrix3d& R, Eigen::Vector3d& t,\n                             double& scale, double& msd) {\n  std::vector<Eigen::Vector3d> inliers1, inliers2;\n\n  if (observations1.size() > 5) {\n    LOG(INFO) << \"Finding Similarity by RANSAC\";\n    RansacSimilarity(observations1, observations2, inliers1, inliers2, R, t,\n                     scale, threshold, p);\n    VLOG(2) << \"inliers size: \" << inliers1.size();\n    // Re-compute similarity by inliers\n    Eigen::MatrixXd x1 = Eigen::MatrixXd::Zero(3, inliers1.size()),\n                    x2 = Eigen::MatrixXd::Zero(3, inliers2.size());\n    for (unsigned int i = 0; i < inliers1.size(); i++) {\n      x1.col(i) = inliers1[i];\n      x2.col(i) = inliers2[i];\n    }\n    DAGSfM::FindRTS(x1, x2, &scale, &t, &R);\n    // Optional non-linear refinement of the found parameters\n    DAGSfM::Refine_RTS(x1, x2, &scale, &t, &R);\n\n    if (inliers1.size() < 4) {\n      msd = numeric_limits<double>::max();\n      return;\n    }\n    // else msd = CheckReprojError(inliers1, inliers2, scale, R, t);\n  }\n\n  if (observations1.size() <= 5 || inliers1.size() <= 5) {\n    Eigen::MatrixXd x1 = Eigen::MatrixXd::Zero(3, observations1.size()),\n                    x2 = Eigen::MatrixXd::Zero(3, observations2.size());\n    for (unsigned int i = 0; i < observations1.size(); i++) {\n      x1.col(i) = observations1[i];\n      x2.col(i) = observations2[i];\n    }\n    DAGSfM::FindRTS(x1, x2, &scale, &t, &R);\n    DAGSfM::Refine_RTS(x1, x2, &scale, &t, &R);\n\n    // msd = CheckReprojError(observations1, observations2, scale, R, t);\n  }\n\n  msd = CheckReprojError(observations1, observations2, scale, R, t);\n}\n\nvoid FindCommon3DPoints(const std::vector<image_t>& common_reg_images,\n                        const Reconstruction& recon1,\n                        const Reconstruction& recon2,\n                        std::vector<Eigen::Vector3d>& src_points,\n                        std::vector<Eigen::Vector3d>& ref_points) {\n  // std::vector<std::pair<Eigen::Vector3d, Eigen::Vector3d>> common_3D_points;\n  std::unordered_set<image_t> common_image_ids(common_reg_images.begin(),\n                                               common_reg_images.end());\n  LOG(INFO) << \"Begin find common 3D points\";\n  for (const auto& point3D : recon2.Points3D()) {\n    const Eigen::Vector3d point3D2 = point3D.second.XYZ();\n\n    for (const auto& track_el : point3D.second.Track().Elements()) {\n      if (common_image_ids.count(track_el.image_id) > 0) {\n        const auto& point2D =\n            recon1.Image(track_el.image_id).Point2D(track_el.point2D_idx);\n        if (point2D.HasPoint3D()) {\n          const Eigen::Vector3d point3D1 =\n              recon1.Point3D(point2D.Point3DId()).XYZ();\n          // common_3D_points.emplace_back(point3D1, point3D2);\n          src_points.emplace_back(point3D1);\n          ref_points.emplace_back(point3D2);\n        }\n      }\n    }\n  }\n  LOG(INFO) << \"Find \" << ref_points.size() << \" common 3D points.\";\n}\n\n}  // namespace\n\nSfMAligner::SfMAligner(const std::vector<Reconstruction*>& reconstructions,\n                       const AlignOptions& options)\n    : options_(options), reconstructions_(reconstructions) {\n  // some logic or parameters check\n  CHECK_GT(reconstructions.size(), 0);\n  CHECK_GT(reconstructions_.size(), 0);\n\n  for (unsigned int i = 0; i < reconstructions_.size(); i++) {\n    LOG(INFO) << \"Node id: \" << i;\n    CHECK_NOTNULL(reconstructions_[i]);\n    LOG(INFO) << \"Total images number: \" << reconstructions_[i]->NumImages();\n  }\n}\n\nconst std::vector<BitmapColor<float>> SfMAligner::ColorContainers = {\n    BitmapColor<float>(255, 25.5, 0), BitmapColor<float>(0, 255, 255),\n    BitmapColor<float>(255, 102, 0),  BitmapColor<float>(153, 51, 204),\n    BitmapColor<float>(0, 255, 51),   BitmapColor<float>(255, 0, 204),\n    BitmapColor<float>(255, 255, 0),  BitmapColor<float>(255, 153, 255),\n    BitmapColor<float>(255, 51, 0),   BitmapColor<float>(0, 204, 255),\n    BitmapColor<float>(255, 204, 255)};\n\nbool SfMAligner::Align() {\n  Timer timer;\n\n  // 1. Constructing a graph from reconstructions,\n  // each node is a reconstruction, edges represent the connections between\n  // reconstructions (by the means of common images or common 3D points), the\n  // weight of edge represents the mean reprojection error.\n  LOG(INFO) << \"Constructing Reconstructions Graph...\";\n  timer.Start();\n  ConstructReconsGraph();\n  timer.Pause();\n  summary_.construct_recon_graph_time = timer.ElapsedSeconds();\n  recons_graph_.ShowInfo();\n  CHECK_EQ(recons_graph_.GetNodesNum(), reconstructions_.size());\n\n  // The reconstruction graph should be at least a spanning tree,\n  // or we couldn't stitch all reconstructions together due to\n  // too large alignment error or disconnected components.\n  if (recons_graph_.GetEdgesNum() < recons_graph_.GetNodesNum() - 1) {\n    LOG(WARNING) << \"Can't align all reconstructions together due to \"\n                 << \"too large alignment error or disconnected components.\"\n                 << \"We would just merge local maps in the largest connected \"\n                    \"components.\";\n  }\n  const Graph<Node, Edge> largest_cc = recons_graph_.ExtractLargestCC();\n  std::vector<size_t> vec_largest_cc_nodes;\n  vec_largest_cc_nodes.reserve(largest_cc.GetNodes().size());\n  for (auto node_it : largest_cc.GetNodes()) {\n    vec_largest_cc_nodes.push_back(node_it.first);\n  }\n\n  // 2. Constructing a minimum spanning tree, thus we can select the\n  // most accurate n - 1 edges for accurate alignment.\n  LOG(INFO) << \"Finding Minimum Spanning Tree...\";\n  timer.Start();\n  std::vector<Edge> mst_edges = largest_cc.Kruskal();\n\n  Graph<Node, Edge> mst;\n  for (const auto edge : mst_edges) {\n    mst.AddEdge(edge);\n  }\n\n  if (mst_edges.size() < largest_cc.GetNodesNum() - 1) {\n    LOG(WARNING) << \"Invalid MST\";\n    mst.ShowInfo();\n    return false;\n  }\n  mst.ShowInfo();\n  timer.Pause();\n  summary_.construct_mst_time = timer.ElapsedSeconds();\n\n  // 3. Finding an anchor node, an anchor node is a reference reconstruction\n  // that all other reconstructions should be aligned to.\n  LOG(INFO) << \"Finding Anchor Node...\";\n  timer.Start();\n  FindAnchorNode(&mst);\n  timer.Pause();\n  summary_.find_anchor_node_time = timer.ElapsedSeconds();\n\n  // 4. Compute the final transformation to anchor node for each cluster\n  LOG(INFO) << \"Computing Final Similarity Transformations...\";\n  timer.Start();\n  for (auto i : vec_largest_cc_nodes) {\n    if (static_cast<int>(i) != anchor_node_.id) {\n      this->ComputePath(i, anchor_node_.id);\n    }\n  }\n  sim3_to_anchor_[anchor_node_.id] = Sim3();\n  timer.Pause();\n  summary_.compute_final_transformation_time = timer.ElapsedSeconds();\n\n  // 5. Merging all other reconstructions to anchor node\n  LOG(INFO) << \"Merging Reconstructions...\";\n  timer.Start();\n  this->MergeReconstructions(vec_largest_cc_nodes);\n  timer.Pause();\n  summary_.merging_time = timer.ElapsedSeconds();\n\n  return true;\n}\n\nNode SfMAligner::GetAnchorNode() const { return anchor_node_; }\n\nstd::vector<Sim3> SfMAligner::GetSim3ToAnchor() const {\n  return sim3_to_anchor_;\n}\n\nconst std::unordered_set<image_t>& SfMAligner::GetSeparators() const {\n  return separators_;\n}\n\nvoid SfMAligner::ConstructReconsGraph() {\n  // 1. Add nodes\n  for (size_t i = 0; i < reconstructions_.size(); i++) {\n    Node node(i);\n    // node.recon = reconstructions_[i];\n    recons_graph_.AddNode(node);\n  }\n\n  // 2. Add edges\n  for (unsigned int i = 0; i < reconstructions_.size(); i++) {\n    for (unsigned int j = i + 1; j < reconstructions_.size(); j++) {\n      const double weight = ComputeEdgeWeight(i, j);\n      LOG(INFO) << \"weight: \" << weight;\n      if (weight != std::numeric_limits<double>::max()) {\n        recons_graph_.AddEdge(Edge(i, j, (float)weight));\n      }\n    }\n  }\n}\n\ndouble SfMAligner::ComputeEdgeWeight(const unsigned int i, const unsigned int j) {\n  const Reconstruction& recon1 = *reconstructions_[i];\n  const Reconstruction& recon2 = *reconstructions_[j];\n  double weight = std::numeric_limits<double>::max();\n\n  Eigen::Matrix3d R1 = Eigen::Matrix3d::Identity(3, 3),\n                  R2 = Eigen::Matrix3d::Identity(3, 3);\n  Eigen::Vector3d t1 = Eigen::Vector3d::Zero(), t2 = Eigen::Vector3d::Zero();\n  double s1 = 1.0, s2 = 1.0;\n\n  // Find common registered images\n  std::vector<image_t> common_reg_images = recon1.FindCommonRegImageIds(recon2);\n  for (auto image_id : common_reg_images) {\n    separators_.insert(image_id);\n  }\n  std::vector<Eigen::Vector3d> src_points, ref_points;\n  // for (const auto common_id : common_reg_images) {\n  //     src_points.push_back(recon1.Image(common_id).ProjectionCenter());\n  //     ref_points.push_back(recon2.Image(common_id).ProjectionCenter());\n  // }\n  FindCommon3DPoints(common_reg_images, recon1, recon2, src_points, ref_points);\n  LOG(INFO) << \"Common registerd images number: \" << common_reg_images.size();\n\n  if (common_reg_images.size() < 2) {\n    LOG(WARNING) << \"Not found enough common registered images.\";\n    return std::numeric_limits<double>::max();\n  } else {\n    double msd1 = 0.0, msd2 = 0.0;\n    FindSimilarityTransform(src_points, ref_points, options_.threshold,\n                            options_.confidence, R1, t1, s1, msd1);\n    FindSimilarityTransform(ref_points, src_points, options_.threshold,\n                            options_.confidence, R2, t2, s2, msd2);\n\n    weight = std::max(msd1, msd2);\n\n    if (weight != numeric_limits<double>::max()) {\n      sim3_graph_[i][j] = Sim3(R1, t1, s1);\n      sim3_graph_[j][i] = Sim3(R2, t2, s2);\n    }\n  }\n  // else if (common_reg_images.size() < 3) {\n  //     std::vector<Eigen::Matrix3d> src_rotations, ref_rotations;\n  //     for (const auto common_id : common_reg_images) {\n  //         src_rotations.push_back(recon1.Image(common_id).RotationMatrix());\n  //         ref_rotations.push_back(recon2.Image(common_id).RotationMatrix());\n  //     }\n  //     ComputeSimilarityByCameraMotions(src_points, ref_points,\n  //                                      src_rotations, ref_rotations, R1, t1,\n  //                                      s1);\n  //     ComputeSimilarityByCameraMotions(ref_points, src_points,\n  //                                      ref_rotations, src_rotations, R2, t2,\n  //                                      s2);\n\n  //     double msd1 = CheckReprojError(src_points, ref_points, s1, R1, t1),\n  //            msd2 = CheckReprojError(ref_points, src_points, s2, R2, t2);\n\n  //     weight = std::max(msd1, msd2);\n\n  //     if (weight != numeric_limits<double>::max()) {\n  //         sim3_graph_[i][j] = Sim3(R1, t1, s1);\n  //         sim3_graph_[j][i] = Sim3(R2, t2, s2);\n  //     }\n  // }\n\n  return (weight > options_.max_reprojection_error)\n             ? std::numeric_limits<double>::max()\n             : weight;\n}\n\nvoid SfMAligner::FindAnchorNode(Graph<Node, Edge>* graph) {\n  paths_.resize(recons_graph_.GetNodesNum());\n  sim3_to_anchor_.resize(recons_graph_.GetNodesNum());\n\n  // The anchor is found by merging all leaf nodes to their adjacent nodes,\n  // until one node or two nodes left. If two nodes left, we choose the\n  // reconstruction that has the largest size as the anchor.\n  int layer = 1;\n  unsigned int anchor_index = 0;\n\n  while (graph->GetNodesNum() > 1) {\n    LOG(INFO) << \"Merging the \" << layer++ << \"-th layer leaf nodes\";\n\n    graph->CountOutDegrees();\n    graph->CountInDegrees();\n    graph->CountDegrees();\n    std::unordered_map<size_t, size_t> degrees = graph->GetDegrees();\n\n    // Finding all leaf nodes. Leaf node in graph has degree equals to 1.\n    std::vector<size_t> indexes;\n    if (graph->GetNodesNum() == 2) {\n      indexes.push_back(degrees.begin()->first);\n    } else {\n      for (auto it = degrees.begin(); it != degrees.end(); ++it) {\n        LOG(INFO) << \"node: \" << it->first << \", \"\n                  << \"degree: \" << it->second;\n        if (it->second == 1) indexes.push_back(it->first);\n      }\n    }\n    if (indexes.empty()) break;\n\n    for (auto idx : indexes) {\n      // if (idx == -1) break;\n      const Edge& edge = graph->FindConnectedEdge(idx);\n\n      LOG(INFO) << \"Find node [degree = 1]: \" << idx;\n      LOG(INFO) << edge.src << \"->\" << edge.dst << \": \" << edge.weight;\n\n      // src is the node with degree = 1\n      unsigned int src = (idx == edge.src) ? edge.src : edge.dst;\n      unsigned int dst = (idx == edge.src) ? edge.dst : edge.src;\n\n      LOG(INFO) << \"Merge Clusters: \" << src << \"->\" << dst << \": \"\n                << edge.weight;\n      anchor_index = dst;\n      const Sim3 sim = sim3_graph_[src][dst];\n      paths_[src].insert(std::make_pair(dst, sim));\n\n      graph->DeleteNode(src);\n      graph->DeleteEdge(src, dst);\n      graph->DeleteEdge(dst, src);\n      graph->ShowInfo();\n    }\n  }\n\n  anchor_node_.id = anchor_index;\n}\n\nvoid SfMAligner::ComputePath(int src, int dst) {\n  LOG(INFO) << \"Computing Path: \" << src << \"->\" << dst;\n  std::queue<int> qu;\n  qu.push(src);\n\n  Eigen::Matrix3d r = Eigen::Matrix3d::Identity();\n  Eigen::Vector3d t = Eigen::Vector3d::Zero();\n  double s = 1.0;\n\n  Sim3 sim(Eigen::Matrix3d::Identity(), Eigen::Vector3d::Identity(), 1.0);\n  LOG(INFO) << \"v: \" << src;\n  while (!qu.empty()) {\n    int u = qu.front();\n    qu.pop();\n    auto it = paths_[u].begin();\n    int v = it->first;\n    LOG(INFO) << \"v: \" << v;\n    s = it->second.s * s;\n    r = it->second.R * r.eval();\n    t = it->second.s * it->second.R * t.eval() + it->second.t;\n    if (v == dst) {\n      sim.s = s;\n      sim.R = r;\n      sim.t = t;\n      sim3_to_anchor_[src] = sim;\n      return;\n    } else\n      qu.push(v);\n  }\n  LOG(INFO) << \"\\n\";\n}\n\nvoid SfMAligner::MergeReconstructions(std::vector<size_t>& node_ids) {\n  if (options_.assign_color_for_clusters) {\n    for (size_t i = 0; i < reconstructions_.size(); i++) {\n      const int color_id = i % SfMAligner::ColorContainers.size();\n      reconstructions_[i]->AssignColorsForAllPoints(\n          SfMAligner::ColorContainers[color_id]);\n      // // Assign cluster id for each image.\n      // const std::vector<image_t> reg_image_ids =\n      // reconstructions_[i]->RegImageIds(); for (auto image_id : reg_image_ids)\n      // {\n      //     Image& image = reconstructions_[i]->Image(image_id);\n      //     image.SetClusterId(i);\n      // }\n    }\n  }\n\n  for (auto id : node_ids) {\n    if (static_cast<int>(id) == anchor_node_.id) {\n      continue;\n    }\n\n    Sim3 sim3 = sim3_to_anchor_[id];\n    Eigen::Matrix3x4d alignment;\n    alignment.block(0, 0, 3, 3) = sim3.s * sim3.R;\n    alignment.block(0, 3, 3, 1) = sim3.t;\n\n    reconstructions_[anchor_node_.id]->Merge(*reconstructions_[id], alignment);\n  }\n}\n\nbool ComputeSimilarityByCameraMotions(\n    std::vector<Eigen::Vector3d>& camera_centers1,\n    std::vector<Eigen::Vector3d>& camera_centers2,\n    std::vector<Eigen::Matrix3d>& camera_rotations1,\n    std::vector<Eigen::Matrix3d>& camera_rotations2,\n    Eigen::Matrix3d& relative_r, Eigen::Vector3d& relative_t, double& scale) {\n  // my hybrid approach by combining \"Divide and Conquer: Efficient Large-Scale\n  // Structure from Motion Using Graph Partitioning\" and RANSAC\n\n  const unsigned int n = camera_centers1.size();\n  std::vector<Eigen::Vector3d> ts1(n);\n  std::vector<Eigen::Vector3d> ts2(n);\n\n  for (unsigned int i = 0; i < n; i++) {\n    ts1[i] = -camera_rotations1[i] * camera_centers1[i];\n    ts2[i] = -camera_rotations2[i] * camera_centers2[i];\n  }\n\n  // compute relative scale from a->b\n  std::vector<double> scales;\n  for (unsigned int i = 0; i < n; i++) {\n    Eigen::Vector3d center_a1 = camera_centers1[i];\n    Eigen::Vector3d center_b1 = camera_centers2[i];\n    for (unsigned int j = i + 1; j < n; j++) {\n      Eigen::Vector3d center_a2 = camera_centers1[j];\n      Eigen::Vector3d center_b2 = camera_centers2[j];\n      double scale_ab =\n          (center_b1 - center_b2).norm() / (center_a1 - center_a2).norm();\n      scales.push_back(scale_ab);\n    }\n  }\n  // retrieve the median of scales, according to\n  // the equation (5) of the paper \"Divide and Conquer: Efficient Large-Scale\n  // Structure from Motion Using Graph Partitioning\"\n  std::sort(scales.begin(), scales.end());\n  scale = scales[scales.size() / 2];\n\n  // compute relative rotation & relative translation from a->b\n  std::vector<Correspondence3D> corres3d;\n  std::vector<CorrespondenceEuc> input_datas;\n  for (unsigned int i = 0; i < camera_centers1.size(); i++) {\n    corres3d.emplace_back(camera_centers1[i], camera_centers2[i]);\n    input_datas.push_back(make_pair(Euclidean3D(camera_rotations1[i], ts1[i]),\n                                    Euclidean3D(camera_rotations2[i], ts2[i])));\n  }\n  EuclideanEstimator euc_estimator(scale, corres3d);\n\n  Euclidean3D euc3d;\n  RansacParameters params;\n  params.rng =\n      std::make_shared<RandomNumberGenerator>((unsigned int)time(NULL));\n  params.error_thresh = 0.002;\n  params.max_iterations = 1000;\n\n  Prosac<EuclideanEstimator> prosac_euc3(params, euc_estimator);\n  prosac_euc3.Initialize();\n  RansacSummary summary;\n  prosac_euc3.Estimate(input_datas, &euc3d, &summary);\n\n  relative_r = euc3d.R;\n  relative_t = euc3d.t;\n\n  return true;\n}\n\n}  // namespace DAGSfM", "meta": {"hexsha": "40648a3979f221b1a0c86f9f11290ca4adb9eae4", "size": 18746, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/controllers/sfm_aligner.cpp", "max_stars_repo_name": "json87/DAGSfM", "max_stars_repo_head_hexsha": "ad34e00e8a3a1ef788deefd92c0fa4ee78e81676", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/controllers/sfm_aligner.cpp", "max_issues_repo_name": "json87/DAGSfM", "max_issues_repo_head_hexsha": "ad34e00e8a3a1ef788deefd92c0fa4ee78e81676", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/controllers/sfm_aligner.cpp", "max_forks_repo_name": "json87/DAGSfM", "max_forks_repo_head_hexsha": "ad34e00e8a3a1ef788deefd92c0fa4ee78e81676", "max_forks_repo_licenses": ["BSD-3-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.4708171206, "max_line_length": 82, "alphanum_fraction": 0.6370959138, "num_tokens": 5238, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234877, "lm_q2_score": 0.585101154203231, "lm_q1q2_score": 0.48630276150436363}}
{"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_HYPERGEOMETRIC_1F1_LARGE_ABZ_HPP_\n#define BOOST_HYPERGEOMETRIC_1F1_LARGE_ABZ_HPP_\n\n#include <boost/math/special_functions/detail/hypergeometric_1F1_bessel.hpp>\n#include <boost/math/special_functions/detail/hypergeometric_series.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n\n\n  namespace boost { namespace math { namespace detail {\n\n     template <class T>\n     inline bool is_negative_integer(const T& x)\n     {\n        using std::floor;\n        return (x <= 0) && (floor(x) == x);\n     }\n\n\n     template <class T, class Policy>\n     struct hypergeometric_1F1_igamma_series\n     {\n        enum{ cache_size = 64 };\n\n        typedef T result_type;\n        hypergeometric_1F1_igamma_series(const T& alpha, const T& delta, const T& x, const Policy& pol)\n           : delta_poch(-delta), alpha_poch(alpha), x(x), k(0), cache_offset(0), pol(pol)\n        {\n           BOOST_MATH_STD_USING\n           T log_term = log(x) * -alpha;\n           log_scaling = itrunc(log_term - 3 - boost::math::tools::log_min_value<T>() / 50);\n           term = exp(log_term - log_scaling);\n           refill_cache();\n        }\n        T operator()()\n        {\n           if (k - cache_offset >= cache_size)\n           {\n              cache_offset += cache_size;\n              refill_cache();\n           }\n           T result = term * gamma_cache[k - cache_offset];\n           term *= delta_poch * alpha_poch / (++k * x);\n           delta_poch += 1;\n           alpha_poch += 1;\n           return result;\n        }\n        void refill_cache()\n        {\n           typedef typename lanczos::lanczos<T, Policy>::type lanczos_type;\n\n           gamma_cache[cache_size - 1] = boost::math::gamma_p(alpha_poch + ((int)cache_size - 1), x, pol);\n           for (int i = cache_size - 1; i > 0; --i)\n           {\n              gamma_cache[i - 1] = gamma_cache[i] >= 1 ? T(1) : T(gamma_cache[i] + regularised_gamma_prefix(T(alpha_poch + (i - 1)), x, pol, lanczos_type()) / (alpha_poch + (i - 1)));\n           }\n        }\n        T delta_poch, alpha_poch, x, term;\n        T gamma_cache[cache_size];\n        int k;\n        int log_scaling;\n        int cache_offset;\n        Policy pol;\n     };\n\n     template <class T, class Policy>\n     T hypergeometric_1F1_igamma(const T& a, const T& b, const T& x, const T& b_minus_a, const Policy& pol, int& log_scaling)\n     {\n        BOOST_MATH_STD_USING\n        if (b_minus_a == 0)\n        {\n           // special case: M(a,a,z) == exp(z)\n           int scale = itrunc(x, pol);\n           log_scaling += scale;\n           return exp(x - scale);\n        }\n        hypergeometric_1F1_igamma_series<T, Policy> s(b_minus_a, a - 1, x, pol);\n        log_scaling += s.log_scaling;\n        boost::uintmax_t max_iter = boost::math::policies::get_max_series_iterations<Policy>();\n        T result = boost::math::tools::sum_series(s, boost::math::policies::get_epsilon<T, Policy>(), max_iter);\n        boost::math::policies::check_series_iterations<T>(\"boost::math::tgamma<%1%>(%1%,%1%)\", max_iter, pol);\n        T log_prefix = x + boost::math::lgamma(b, pol) - boost::math::lgamma(a, pol);\n        int scale = itrunc(log_prefix);\n        log_scaling += scale;\n        return result * exp(log_prefix - scale);\n     }\n\n     template <class T, class Policy>\n     T hypergeometric_1F1_shift_on_a(T h, const T& a_local, const T& b_local, const T& x, int a_shift, const Policy& pol, int& log_scaling)\n     {\n        BOOST_MATH_STD_USING\n        T a = a_local + a_shift;\n        if (a_shift == 0)\n           return h;\n        else if (a_shift > 0)\n        {\n           //\n           // Forward recursion on a is stable as long as 2a-b+z > 0.\n           // If 2a-b+z < 0 then backwards recursion is stable even though\n           // the function may be strictly increasing with a.  Potentially\n           // we may need to split the recurrence in 2 sections - one using \n           // forward recursion, and one backwards.\n           //\n           // We will get the next seed value from the ratio\n           // on b as that's stable and quick to compute.\n           //\n\n           T crossover_a = (b_local - x) / 2;\n           int crossover_shift = itrunc(crossover_a - a_local);\n\n           if (crossover_shift > 1)\n           {\n              //\n              // Forwards recursion will start off unstable, but may switch to the stable direction later.\n              // Start in the middle and go in both directions:\n              //\n              if (crossover_shift > a_shift)\n                 crossover_shift = a_shift;\n              crossover_a = a_local + crossover_shift;\n              boost::math::detail::hypergeometric_1F1_recurrence_b_coefficients<T> b_coef(crossover_a, b_local, x);\n              boost::uintmax_t max_iter = boost::math::policies::get_max_series_iterations<Policy>();\n              T b_ratio = boost::math::tools::function_ratio_from_backwards_recurrence(b_coef, boost::math::policies::get_epsilon<T, Policy>(), max_iter);\n              boost::math::policies::check_series_iterations<T>(\"boost::math::hypergeometric_1F1_large_abz<%1%>(%1%,%1%,%1%)\", max_iter, pol);\n              //\n              // Convert to a ratio:\n              //         (1+a-b)M(a, b, z) - aM(a+1, b, z) + (b-1)M(a, b-1, z) = 0\n              //\n              //  hence: M(a+1,b,z) = ((1+a-b) / a) M(a,b,z) + ((b-1) / a) M(a,b,z)/b_ratio\n              //\n              T first = 1;\n              T second = ((1 + crossover_a - b_local) / crossover_a) + ((b_local - 1) / crossover_a) / b_ratio;\n              //\n              // Recurse down to a_local, compare values and re-normalise first and second:\n              //\n              boost::math::detail::hypergeometric_1F1_recurrence_a_coefficients<T> a_coef(crossover_a, b_local, x);\n              int backwards_scale = 0;\n              T comparitor = boost::math::tools::apply_recurrence_relation_backward(a_coef, crossover_shift, second, first, &backwards_scale);\n              log_scaling -= backwards_scale;\n              if ((h < 1) && (tools::max_value<T>() * h > comparitor))\n              {\n                 // Need to rescale!\n                 int scale = itrunc(log(h), pol) + 1;\n                 h *= exp(T(-scale));\n                 log_scaling += scale;\n              }\n              comparitor /= h;\n              first /= comparitor;\n              second /= comparitor;\n              //\n              // Now we can recurse forwards for the rest of the range:\n              //\n              if (crossover_shift < a_shift)\n              {\n                 boost::math::detail::hypergeometric_1F1_recurrence_a_coefficients<T> a_coef_2(crossover_a + 1, b_local, x);\n                 h = boost::math::tools::apply_recurrence_relation_forward(a_coef_2, a_shift - crossover_shift - 1, first, second, &log_scaling);\n              }\n              else\n                 h = first;\n           }\n           else\n           {\n              //\n              // Regular case where forwards iteration is stable right from the start:\n              //\n              boost::math::detail::hypergeometric_1F1_recurrence_b_coefficients<T> b_coef(a_local, b_local, x);\n              boost::uintmax_t max_iter = boost::math::policies::get_max_series_iterations<Policy>();\n              T b_ratio = boost::math::tools::function_ratio_from_backwards_recurrence(b_coef, boost::math::policies::get_epsilon<T, Policy>(), max_iter);\n              boost::math::policies::check_series_iterations<T>(\"boost::math::hypergeometric_1F1_large_abz<%1%>(%1%,%1%,%1%)\", max_iter, pol);\n              //\n              // Convert to a ratio:\n              //         (1+a-b)M(a, b, z) - aM(a+1, b, z) + (b-1)M(a, b-1, z) = 0\n              //\n              //  hence: M(a+1,b,z) = ((1+a-b) / a) M(a,b,z) + ((b-1) / a) M(a,b,z)/b_ratio\n              //\n              T second = ((1 + a_local - b_local) / a_local) * h + ((b_local - 1) / a_local) * h / b_ratio;\n              boost::math::detail::hypergeometric_1F1_recurrence_a_coefficients<T> a_coef(a_local + 1, b_local, x);\n              h = boost::math::tools::apply_recurrence_relation_forward(a_coef, --a_shift, h, second, &log_scaling);\n           }\n        }\n        else\n        {\n           //\n           // We've calculated h for a larger value of a than we want, and need to recurse down.\n           // However, only forward iteration is stable, so calculate the ratio, compare values,\n           // and normalise.  Note that we calculate the ratio on b and convert to a since the\n           // direction is the minimal solution for N->+INF.\n           //\n           // IMPORTANT: this is only currently called for a > b and therefore forwards iteration\n           // is the only stable direction as we will only iterate down until a ~ b, but we\n           // will check this with an assert:\n           //\n           BOOST_ASSERT(2 * a - b_local + x > 0);\n           boost::math::detail::hypergeometric_1F1_recurrence_b_coefficients<T> b_coef(a, b_local, x);\n           boost::uintmax_t max_iter = boost::math::policies::get_max_series_iterations<Policy>();\n           T b_ratio = boost::math::tools::function_ratio_from_backwards_recurrence(b_coef, boost::math::policies::get_epsilon<T, Policy>(), max_iter);\n           boost::math::policies::check_series_iterations<T>(\"boost::math::hypergeometric_1F1_large_abz<%1%>(%1%,%1%,%1%)\", max_iter, pol);\n           //\n           // Convert to a ratio:\n           //         (1+a-b)M(a, b, z) - aM(a+1, b, z) + (b-1)M(a, b-1, z) = 0\n           //\n           //  hence: M(a+1,b,z) = (1+a-b) / a M(a,b,z) + (b-1) / a M(a,b,z)/ (M(a,b,z)/M(a,b-1,z))\n           //\n           T first = 1;  // arbitrary value;\n           T second = ((1 + a - b_local) / a) + ((b_local - 1) / a) * (1 / b_ratio);\n\n           if (a_shift == -1)\n              h = h / second;\n           else\n           {\n              boost::math::detail::hypergeometric_1F1_recurrence_a_coefficients<T> a_coef(a + 1, b_local, x);\n              T comparitor = boost::math::tools::apply_recurrence_relation_forward(a_coef, -(a_shift + 1), first, second);\n              if (boost::math::tools::min_value<T>() * comparitor > h)\n              {\n                 // Ooops, need to rescale h:\n                 int rescale = itrunc(log(fabs(h)));\n                 T scale = exp(T(-rescale));\n                 h *= scale;\n                 log_scaling += rescale;\n              }\n              h = h / comparitor;\n           }\n        }\n        return h;\n     }\n\n     template <class T, class Policy>\n     T hypergeometric_1F1_shift_on_b(T h, const T& a, const T& b_local, const T& x, int b_shift, const Policy& pol, int& log_scaling)\n     {\n        BOOST_MATH_STD_USING\n\n        T b = b_local + b_shift;\n        if (b_shift == 0)\n           return h;\n        else if (b_shift > 0)\n        {\n           //\n           // We get here for b_shift > 0 when b > z.  We can't use forward recursion on b - it's unstable,\n           // so grab the ratio and work backwards to b - b_shift and normalise.\n           //\n           boost::math::detail::hypergeometric_1F1_recurrence_b_coefficients<T> b_coef(a, b, x);\n           boost::uintmax_t max_iter = boost::math::policies::get_max_series_iterations<Policy>();\n\n           T first = 1;  // arbitrary value;\n           T second = 1 / boost::math::tools::function_ratio_from_backwards_recurrence(b_coef, boost::math::policies::get_epsilon<T, Policy>(), max_iter);\n           boost::math::policies::check_series_iterations<T>(\"boost::math::hypergeometric_1F1_large_abz<%1%>(%1%,%1%,%1%)\", max_iter, pol);\n           if (b_shift == 1)\n              h = h / second;\n           else\n           {\n              //\n              // Reset coefficients and recurse:\n              //\n              boost::math::detail::hypergeometric_1F1_recurrence_b_coefficients<T> b_coef_2(a, b - 1, x);\n              int local_scale = 0;\n              T comparitor = boost::math::tools::apply_recurrence_relation_backward(b_coef_2, --b_shift, first, second, &local_scale);\n              log_scaling -= local_scale;\n              if (boost::math::tools::min_value<T>() * comparitor > h)\n              {\n                 // Ooops, need to rescale h:\n                 int rescale = itrunc(log(fabs(h)));\n                 T scale = exp(T(-rescale));\n                 h *= scale;\n                 log_scaling += rescale;\n              }\n              h = h / comparitor;\n           }\n        }\n        else\n        {\n           T second;\n           if (a == b_local)\n           {\n               // recurrence is trivial for a == b and method of ratios fails as the c-term goes to zero:\n              second = -b_local * (1 - b_local - x) * h / (b_local * (b_local - 1));\n           }\n           else\n           {\n              BOOST_ASSERT(!is_negative_integer(b - a));\n              boost::math::detail::hypergeometric_1F1_recurrence_b_coefficients<T> b_coef(a, b_local, x);\n              boost::uintmax_t max_iter = boost::math::policies::get_max_series_iterations<Policy>();\n              second = h / boost::math::tools::function_ratio_from_backwards_recurrence(b_coef, boost::math::policies::get_epsilon<T, Policy>(), max_iter);\n              boost::math::policies::check_series_iterations<T>(\"boost::math::hypergeometric_1F1_large_abz<%1%>(%1%,%1%,%1%)\", max_iter, pol);\n           }\n           if (b_shift == -1)\n              h = second;\n           else\n           {\n              boost::math::detail::hypergeometric_1F1_recurrence_b_coefficients<T> b_coef_2(a, b_local - 1, x);\n              h = boost::math::tools::apply_recurrence_relation_backward(b_coef_2, -(++b_shift), h, second, &log_scaling);\n           }\n        }\n        return h;\n     }\n\n\n     template <class T, class Policy>\n     T hypergeometric_1F1_large_igamma(const T& a, const T& b, const T& x, const T& b_minus_a, const Policy& pol, int& log_scaling)\n     {\n        BOOST_MATH_STD_USING\n        //\n        // We need a < b < z in order to ensure there's at least a chance of convergence,\n        // we can use recurrence relations to shift forwards on a+b or just a to achieve this,\n        // for decent accuracy, try to keep 2b - 1 < a < 2b < z\n        //\n        int b_shift = b * 2 < x ? 0 : itrunc(b - x / 2);\n        int a_shift = a > b - b_shift ? -itrunc(b - b_shift - a - 1) : -itrunc(b - b_shift - a);\n\n        if (a_shift < 0)\n        {\n           // Might as well do all the shifting on b as scale a downwards:\n           b_shift -= a_shift;\n           a_shift = 0;\n        }\n\n        T a_local = a - a_shift;\n        T b_local = b - b_shift;\n        T b_minus_a_local = (a_shift == 0) && (b_shift == 0) ? b_minus_a : b_local - a_local;\n        int local_scaling = 0;\n        T h = hypergeometric_1F1_igamma(a_local, b_local, x, b_minus_a_local, pol, local_scaling);\n        log_scaling += local_scaling;\n\n        //\n        // Apply shifts on a and b as required:\n        //\n        h = hypergeometric_1F1_shift_on_a(h, a_local, b_local, x, a_shift, pol, log_scaling);\n        h = hypergeometric_1F1_shift_on_b(h, a, b_local, x, b_shift, pol, log_scaling);\n\n        return h;\n     }\n\n     template <class T, class Policy>\n     T hypergeometric_1F1_large_series(const T& a, const T& b, const T& z, const Policy& pol, int& log_scaling)\n     {\n        BOOST_MATH_STD_USING\n        //\n        // We make a small, and b > z:\n        //\n        int a_shift(0), b_shift(0);\n        if (a * z > b)\n        {\n           a_shift = itrunc(a) - 5;\n           b_shift = b < z ? itrunc(b - z - 1) : 0;\n        }\n        //\n        // If a_shift is trivially small, there's really not much point in losing\n        // accuracy to save a couple of iterations:\n        //\n        if (a_shift < 5)\n           a_shift = 0;\n        T a_local = a - a_shift;\n        T b_local = b - b_shift;\n        T h = boost::math::detail::hypergeometric_1F1_generic_series(a_local, b_local, z, pol, log_scaling, \"hypergeometric_1F1_large_series<%1%>(a,b,z)\");\n        //\n        // Apply shifts on a and b as required:\n        //\n        if (a_shift && (a_local == 0))\n        {\n           //\n           // Shifting on a via method of ratios in hypergeometric_1F1_shift_on_a fails when\n           // a_local == 0.  However, the value of h calculated was trivial (unity), so\n           // calculate a second 1F1 for a == 1 and recurse as normal:\n           //\n           int scale = 0;\n           T h2 = boost::math::detail::hypergeometric_1F1_generic_series(T(a_local + 1), b_local, z, pol, scale, \"hypergeometric_1F1_large_series<%1%>(a,b,z)\");\n           if (scale != log_scaling)\n           {\n              h2 *= exp(T(scale - log_scaling));\n           }\n           boost::math::detail::hypergeometric_1F1_recurrence_a_coefficients<T> coef(a_local + 1, b_local, z);\n           h = boost::math::tools::apply_recurrence_relation_forward(coef, a_shift - 1, h, h2, &log_scaling);\n           h = hypergeometric_1F1_shift_on_b(h, a, b_local, z, b_shift, pol, log_scaling);\n        }\n        else\n        {\n           h = hypergeometric_1F1_shift_on_a(h, a_local, b_local, z, a_shift, pol, log_scaling);\n           h = hypergeometric_1F1_shift_on_b(h, a, b_local, z, b_shift, pol, log_scaling);\n        }\n        return h;\n     }\n\n     template <class T, class Policy>\n     T hypergeometric_1F1_large_13_3_6_series(const T& a, const T& b, const T& z, const Policy& pol, int& log_scaling)\n     {\n        BOOST_MATH_STD_USING\n        //\n        // A&S 13.3.6 is good only when a ~ b, but isn't too fussy on the size of z.\n        // So shift b to match a (b shifting seems to be more stable via method of ratios).\n        //\n        int b_shift = itrunc(b - a);\n        T b_local = b - b_shift;\n        T h = boost::math::detail::hypergeometric_1F1_AS_13_3_6(a, b_local, z, T(b_local - a), pol, log_scaling);\n        return hypergeometric_1F1_shift_on_b(h, a, b_local, z, b_shift, pol, log_scaling);\n     }\n\n     template <class T, class Policy>\n     T hypergeometric_1F1_large_abz(const T& a, const T& b, const T& z, const Policy& pol, int& log_scaling)\n     {\n        BOOST_MATH_STD_USING\n        //\n        // This is the selection logic to pick the \"best\" method.\n        // We have a,b,z >> 0 and need to compute the approximate cost of each method\n        // and then select whichever wins out.\n        //\n        enum method\n        {\n           method_series = 0,\n           method_shifted_series,\n           method_gamma,\n           method_bessel\n        };\n        //\n        // Cost of direct series, is the approx number of terms required until we hit convergence:\n        //\n        T current_cost = (sqrt(16 * z * (3 * a + z) + 9 * b * b - 24 * b * z) - 3 * b + 4 * z) / 6;\n        method current_method = method_series;\n        //\n        // Cost of shifted series, is the number of recurrences required to move to a zone where\n        // the series is convergent right from the start.\n        // Note that recurrence relations fail for very small b, and too many recurrences on a\n        // will completely destroy all our digits.\n        // Also note that the method fails when b-a is a negative integer unless b is already\n        // larger than z and thus does not need shifting.\n        //\n        T cost = a + ((b < z) ? T(z - b) : T(0));\n        if((b > 1) && (cost < current_cost) && ((b > z) || !is_negative_integer(b-a)))\n        {\n           current_method = method_shifted_series;\n           current_cost = cost;\n        }\n        //\n        // Cost for gamma function method is the number of recurrences required to move it\n        // into a convergent zone, note that recurrence relations fail for very small b.\n        // Also add on a fudge factor to account for the fact that this method is both\n        // more expensive to compute (requires gamma functions), and less accurate than the\n        // methods above:\n        //\n        T b_shift = fabs(b * 2 < z ? T(0) : T(b - z / 2));\n        T a_shift = fabs(a > b - b_shift ? T(-(b - b_shift - a - 1)) : T(-(b - b_shift - a)));\n        cost = 1000 + b_shift + a_shift;\n        if((b > 1) && (cost <= current_cost))\n        {\n           current_method = method_gamma;\n           current_cost = cost;\n        }\n        //\n        // Cost for bessel approximation is the number of recurrences required to make a ~ b,\n        // Note that recurrence relations fail for very small b.  We also have issue with large\n        // z: either overflow/numeric instability or else the series goes divergent.  We seem to be\n        // OK for z smaller than log_max_value<Quad> though, maybe we can stretch a little further\n        // but that's not clear...\n        // Also need to add on a fudge factor to the cost to account for the fact that we need\n        // to calculate the Bessel functions, this is not quite as high as the gamma function \n        // method above as this is generally more accurate and so preferred if the methods are close:\n        //\n        cost = 50 + fabs(b - a);\n        if((b > 1) && (cost <= current_cost) && (z < tools::log_max_value<T>()) && (z < 11356) && (b - a != 0.5f))\n        {\n           current_method = method_bessel;\n           current_cost = cost;\n        }\n\n        switch (current_method)\n        {\n        case method_series:\n           return detail::hypergeometric_1F1_generic_series(a, b, z, pol, log_scaling, \"hypergeometric_1f1_large_abz<%1%>(a,b,z)\");\n        case method_shifted_series:\n           return detail::hypergeometric_1F1_large_series(a, b, z, pol, log_scaling);\n        case method_gamma:\n           return detail::hypergeometric_1F1_large_igamma(a, b, z, T(b - a), pol, log_scaling);\n        case method_bessel:\n           return detail::hypergeometric_1F1_large_13_3_6_series(a, b, z, pol, log_scaling);\n        }\n        return 0; // We don't get here!\n     }\n\n  } } } // namespaces\n\n#endif // BOOST_HYPERGEOMETRIC_1F1_LARGE_ABZ_HPP_\n", "meta": {"hexsha": "176b874745077a48e5a5d77c75a7510e224f0bdc", "size": 22101, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/lib/include/boost/math/special_functions/detail/hypergeometric_1F1_large_abz.hpp", "max_stars_repo_name": "mamil/demo", "max_stars_repo_head_hexsha": "32240d95b80175549e6a1904699363ce672a1591", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 101.0, "max_stars_repo_stars_event_min_datetime": "2019-02-12T12:53:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T14:14:38.000Z", "max_issues_repo_path": "3rdparty/boost_1_73_0/boost/math/special_functions/detail/hypergeometric_1F1_large_abz.hpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 157.0, "max_issues_repo_issues_event_min_datetime": "2019-02-06T05:04:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T21:50:28.000Z", "max_forks_repo_path": "3rdparty/boost_1_73_0/boost/math/special_functions/detail/hypergeometric_1F1_large_abz.hpp", "max_forks_repo_name": "qingkouwei/mediaones", "max_forks_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "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": 45.5690721649, "max_line_length": 183, "alphanum_fraction": 0.5602913895, "num_tokens": 5844, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4863027566098926}}
{"text": "/**\n * \\file boost/numeric/ublasx/operation/lsq.hpp\n *\n * \\brief Least Square problem solvers.\n *\n * Copyright (c) 2010, Marco Guazzone\n * \n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\n\n#ifndef BOOST_NUMERIC_UBLASX_OPERATION_LSQ_HPP\n#define BOOST_NUMERIC_UBLASX_OPERATION_LSQ_HPP\n\n\n#include <algorithm>\n#include <boost/numeric/bindings/lapack/driver/gels.hpp>\n#include <boost/numeric/bindings/lapack/driver/gelss.hpp>\n#include <boost/numeric/bindings/ublas.hpp>\n#include <boost/numeric/ublas/detail/temporary.hpp>\n#include <boost/numeric/ublas/expression_types.hpp>\n#include <boost/numeric/ublas/fwd.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/traits.hpp>\n#include <boost/numeric/ublasx/operation/num_columns.hpp>\n#include <boost/numeric/ublasx/operation/num_rows.hpp>\n#include <boost/numeric/ublasx/operation/rcond.hpp>\n#include <boost/numeric/ublasx/operation/size.hpp>\n\n\nnamespace boost { namespace numeric { namespace ublasx {\n\nusing namespace ::boost::numeric::ublas;\n\nnamespace detail { namespace /*<unnamed>*/ {\n\n\ntemplate <typename MatrixT, typename VectorT>\nvoid llsq_qr_impl(MatrixT& A, VectorT& b, column_major_tag)\n{\n\ttypedef typename promote_traits<\n\t\t\t\ttypename matrix_traits<MatrixT>::size_type,\n\t\t\t\ttypename vector_traits<VectorT>::size_type\n\t\t>::promote_type size_type;\n\n//\tsize_type m = num_rows(A);\n\tsize_type n = num_columns(A);\n\n\t::boost::numeric::bindings::lapack::gels(A, b);\n\n\tb.resize(n, true);\n}\n\n\ntemplate <typename MatrixT, typename VectorT>\nvoid llsq_qr_impl(MatrixT& A, VectorT& b, row_major_tag)\n{\n\ttypedef typename matrix_traits<MatrixT>::value_type value_type;\n\ttypedef matrix<value_type, column_major> colmaj_matrix_type;\n\n\tcolmaj_matrix_type tmp_A(A);\n\n\tllsq_qr_impl(tmp_A, b, column_major_tag());\n}\n\n\ntemplate <typename MatrixT, typename VectorT>\nvoid llsq_qr_impl(matrix_expression<MatrixT> const& A, VectorT& b, column_major_tag)\n{\n\ttypedef typename matrix_traits<MatrixT>::value_type value_type;\n\ttypedef matrix<value_type, column_major> colmaj_matrix_type;\n\n\tcolmaj_matrix_type tmp_A(A);\n\n\tllsq_qr_impl(tmp_A, b, column_major_tag());\n}\n\n\ntemplate <typename MatrixT, typename VectorT>\nvoid llsq_qr_impl(matrix_expression<MatrixT> const& A, VectorT& b, row_major_tag)\n{\n\ttypedef typename matrix_traits<MatrixT>::value_type value_type;\n\ttypedef matrix<value_type, column_major> colmaj_matrix_type;\n\n\tcolmaj_matrix_type tmp_A(A);\n\n\tllsq_qr_impl(tmp_A, b, column_major_tag());\n}\n\n\ntemplate <typename MatrixT, typename VectorT>\nvoid llsq_svd_impl(MatrixT& A, VectorT& b, column_major_tag)\n{\n\ttypedef typename matrix_traits<MatrixT>::value_type value_type;\n\ttypedef typename type_traits<value_type>::real_type real_type;\n\ttypedef typename promote_traits<\n\t\t\t\ttypename matrix_traits<MatrixT>::size_type,\n\t\t\t\ttypename vector_traits<VectorT>::size_type\n\t\t>::promote_type size_type;\n\ttypedef vector<real_type> work_vector_type;\n\n\tsize_type m = num_rows(A);\n\tsize_type n = num_columns(A);\n\tsize_type k = ::std::min(m, n);\n\treal_type rc = rcond(A);\n\t::fortran_int_t r;\n\t//work_vector_type tmp_b(b);//TODO: should we do this in order to avoid problem with other types of vector (like sparse vector)\n\twork_vector_type dummy_s(k);\n\n\t::boost::numeric::bindings::lapack::gelss(A, b, dummy_s, rc, r);\n\n\tb.resize(n, true);\n}\n\n\ntemplate <typename MatrixT, typename VectorT>\nvoid llsq_svd_impl(MatrixT& A, VectorT& b, row_major_tag)\n{\n\ttypedef typename matrix_traits<MatrixT>::value_type value_type;\n\ttypedef matrix<value_type, column_major> colmaj_matrix_type;\n\n\tcolmaj_matrix_type tmp_A(A);\n\n\tllsq_svd_impl(tmp_A, b, column_major_tag());\n}\n\n\ntemplate <typename MatrixT, typename VectorT>\nvoid llsq_svd_impl(matrix_expression<MatrixT> const& A, VectorT& b, column_major_tag)\n{\n\ttypedef typename matrix_traits<MatrixT>::value_type value_type;\n\ttypedef matrix<value_type, column_major> colmaj_matrix_type;\n\n\tcolmaj_matrix_type tmp_A(A);\n\n\tllsq_svd_impl(tmp_A, b, column_major_tag());\n}\n\n\ntemplate <typename MatrixT, typename VectorT>\nvoid llsq_svd_impl(matrix_expression<MatrixT> const& A, VectorT& b, row_major_tag)\n{\n\ttypedef typename matrix_traits<MatrixT>::value_type value_type;\n\ttypedef matrix<value_type, column_major> colmaj_matrix_type;\n\n\tcolmaj_matrix_type tmp_A(A);\n\n\tllsq_svd_impl(tmp_A, b, column_major_tag());\n}\n\n}} // Namespace detail::<unnamed>\n\n\n/**\n * \\brief Solve the linear (ordinary) least square problem by using the QR\n *  decomposition.\n * \\tparam MatrixExprT Type of the input matrix expression.\n * \\tparam VectorExprT Type of the input/output vector.\n * \\param A The input matrix expression (i.e., the design matrix).\n * \\param b On entry, the input vector (i.e., the observations vector); on exit,\n *  the least square solution.\n *\n * Orthogonal decomposition methods of solving the least squares problem are\n * slower than directly solving the normal equations but are more numerically\n * stable.\n */\ntemplate <typename MatrixExprT, typename VectorT>\nBOOST_UBLAS_INLINE\nvoid llsq_qr_inplace(matrix_expression<MatrixExprT> const& A, VectorT& b)\n{\n\ttypedef typename matrix_traits<MatrixExprT>::orientation_category orientation_category;\n\n\tdetail::llsq_qr_impl(A, b, orientation_category());\n}\n\n\n/**\n * \\brief Solve the linear (ordinary) least square problem by using the QR\n *  decomposition.\n * \\tparam MatrixExprT Type of the input matrix expression.\n * \\tparam VectorExprT Type of the input/output vector.\n * \\param A The input matrix expression (i.e., the design matrix).\n * \\param b The input vector (i.e., the observations vector).\n * \\return The least square solution.\n *\n * Orthogonal decomposition methods of solving the least squares problem are\n * slower than directly solving the normal equations but are more numerically\n * stable.\n */\ntemplate <typename MatrixExprT, typename VectorExprT>\nBOOST_UBLAS_INLINE\ntypename vector_temporary_traits<VectorExprT>::type llsq_qr(matrix_expression<MatrixExprT> const& A, vector_expression<VectorExprT> const& b)\n{\n\ttypedef typename vector_temporary_traits<VectorExprT>::type out_vector_type;\n\n\tout_vector_type x(b);\n\n\tllsq_qr_inplace(A, x);\n\n\treturn x;\n}\n\n\n/**\n * \\brief Solve the linear (ordinary) least square problem by using the Singular\n * Value  Decomposition (SVD) method.\n * \\tparam MatrixExprT Type of the input matrix expression.\n * \\tparam VectorExprT Type of the input/output vector.\n * \\param A The input matrix expression (i.e., the design matrix).\n * \\param b On entry, the input vector (i.e., the observations vector); on exit,\n *  the least square solution.\n *\n * This method is the most computationally intensive, but is particularly useful\n * if the normal equations matrix is very ill-conditioned (i.e. if its condition\n * number multiplied by the machine's relative round-off error is appreciably\n * large).\n */\ntemplate <typename MatrixExprT, typename VectorT>\nBOOST_UBLAS_INLINE\nvoid llsq_svd_inplace(matrix_expression<MatrixExprT> const& A, VectorT& b)\n{\n\ttypedef typename matrix_traits<MatrixExprT>::orientation_category orientation_category;\n\n\tdetail::llsq_svd_impl(A, b, orientation_category());\n}\n\n\n/**\n * \\brief Solve the linear (ordinary) least square problem by using the Singular\n *  Value Decomposition (SVD) method.\n * \\tparam MatrixExprT Type of the input matrix expression.\n * \\tparam VectorExprT Type of the input/output vector.\n * \\param A The input matrix expression (i.e., the design matrix).\n * \\param b The input vector (i.e., the observations vector).\n * \\return The least square solution.\n *\n * This method is the most computationally intensive, but is particularly useful\n * if the normal equations matrix is very ill-conditioned (i.e. if its condition\n * number multiplied by the machine's relative round-off error is appreciably\n * large).\n */\ntemplate <typename MatrixExprT, typename VectorExprT>\nBOOST_UBLAS_INLINE\ntypename vector_temporary_traits<VectorExprT>::type llsq_svd(matrix_expression<MatrixExprT> const& A, vector_expression<VectorExprT> const& b)\n{\n\ttypedef typename vector_temporary_traits<VectorExprT>::type out_vector_type;\n\n\tout_vector_type x(b);\n\n\tllsq_svd_inplace(A, x);\n\n\treturn x;\n}\n\n\n/**\n * \\brief Solve the linear (ordinary) least square problem.\n * \\tparam MatrixExprT Type of the input matrix expression.\n * \\tparam VectorExprT Type of the input/output vector.\n * \\param A The input matrix expression (i.e., the design matrix).\n * \\param b On entry, the input vector (i.e., the observations vector); on exit,\n *  the least square solution.\n */\ntemplate <typename MatrixExprT, typename VectorT>\nBOOST_UBLAS_INLINE\nvoid llsq_inplace(matrix_expression<MatrixExprT> const& A, VectorT& b)\n{\n\ttypedef typename matrix_traits<MatrixExprT>::orientation_category orientation_category;\n\n\tdetail::llsq_svd_impl(A, b, orientation_category());\n}\n\n\n/**\n * \\brief Solve the linear (ordinary) least square problem.\n * \\tparam MatrixExprT Type of the input matrix expression.\n * \\tparam VectorExprT Type of the input/output vector.\n * \\param A The input matrix expression (i.e., the design matrix).\n * \\param b The input vector (i.e., the observations vector).\n * \\return The least square solution.\n */\ntemplate <typename MatrixExprT, typename VectorExprT>\nBOOST_UBLAS_INLINE\ntypename vector_temporary_traits<VectorExprT>::type llsq(matrix_expression<MatrixExprT> const& A, vector_expression<VectorExprT> const& b)\n{\n\ttypedef typename vector_temporary_traits<VectorExprT>::type out_vector_type;\n\n\tout_vector_type x(b);\n\n\tllsq_inplace(A, x);\n\n\treturn x;\n}\n\n}}} // Namespace boost::numeric::ublasx\n\n\n#endif // BOOST_NUMERIC_UBLASX_OPERATION_LSQ_HPP\n", "meta": {"hexsha": "1ead629ac7e6991c618e5299761f872fe74fdfee", "size": 9741, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/ublasx/operation/lsq.hpp", "max_stars_repo_name": "comcon1/boost-ublasx", "max_stars_repo_head_hexsha": "290b92b643a944825df99bece3468a4f81518056", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "boost/numeric/ublasx/operation/lsq.hpp", "max_issues_repo_name": "comcon1/boost-ublasx", "max_issues_repo_head_hexsha": "290b92b643a944825df99bece3468a4f81518056", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "boost/numeric/ublasx/operation/lsq.hpp", "max_forks_repo_name": "comcon1/boost-ublasx", "max_forks_repo_head_hexsha": "290b92b643a944825df99bece3468a4f81518056", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1485148515, "max_line_length": 142, "alphanum_fraction": 0.7725079561, "num_tokens": 2409, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.48630275171542126}}
{"text": "/**\n * @file regularizedneumannproblem_main.cc\n * @brief NPDE homework RegularizedNeumannProblem code\n * @author Christian Mitsch, Philippe Peter\n * @date March 2020\n * @copyright Developed at ETH Zurich\n */\n\n#include <lf/mesh/test_utils/test_meshes.h>\n#include <lf/mesh/utils/utils.h>\n#include <lf/uscalfe/uscalfe.h>\n\n#include <Eigen/Core>\n#include <iostream>\n#include <memory>\n\n#include \"regularizedneumannproblem.h\"\n\nint main() {\n  std::cout << \"You can use the mainfile to call your functions\" << std::endl;\n\n  const auto f = lf::mesh::utils::MeshFunctionGlobal(\n      [](Eigen::Vector2d x) -> double { return 1.0; });\n  const auto h = lf::mesh::utils::MeshFunctionGlobal(\n      [](Eigen::Vector2d x) -> double { return 1.0; });\n\n  auto mesh_p = lf::mesh::test_utils::GenerateHybrid2DTestMesh(4, 3.0);\n\n  auto fe_space =\n      std::make_shared<lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n\n  // Compute solution\n  auto result_c =\n      RegularizedNeumannProblem::getGalerkinLSE_dropDof(fe_space, f, h);\n  auto result_f =\n      RegularizedNeumannProblem::getGalerkinLSE_augment(fe_space, f, h);\n\n  return 0;\n}\n", "meta": {"hexsha": "a64ee47cf93428be716361e60a0e43595b51e464", "size": 1117, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/RegularizedNeumannProblem/templates/regularizedneumannproblem_main.cc", "max_stars_repo_name": "padomu/NPDECODES", "max_stars_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/RegularizedNeumannProblem/templates/regularizedneumannproblem_main.cc", "max_issues_repo_name": "padomu/NPDECODES", "max_issues_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/RegularizedNeumannProblem/templates/regularizedneumannproblem_main.cc", "max_forks_repo_name": "padomu/NPDECODES", "max_forks_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 27.925, "max_line_length": 78, "alphanum_fraction": 0.7063563115, "num_tokens": 322, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.48624559843096293}}
{"text": "#ifdef STAND_ALONE\n#   define BOOST_TEST_MODULE RayTracerChallengeTests\n#endif\n\n#include <boost/test/unit_test.hpp>\n#include <iostream>\n#include <shared/Point.h>\n#include <shared/Ray.h>\n#include <shared/Sphere.h>\n#include <shared/Output.h>\n#include <shared/Scaling.h>\n#include <shared/Intersections.h>\n#include <shared/Canvas.h>\n#include <shared/RotationZ.h>\n#include <shared/Shearing.h>\n\nBOOST_AUTO_TEST_SUITE(spheres_suite)\n\n    BOOST_AUTO_TEST_CASE(a_ray_intersects_a_sphere_at_two_points_test) {\n\n        auto r = Ray(Point(0, 0, -5), Vector(0, 0, 1));\n        auto s = Sphere();\n        auto xs = s.intersects(r);\n\n        BOOST_CHECK_EQUAL(xs.size(), 2);\n        BOOST_CHECK_EQUAL(xs[0], 4.0);\n        BOOST_CHECK_EQUAL(xs[1], 6.0);\n\n    }\n\n    BOOST_AUTO_TEST_CASE(a_ray_intersects_a_sphere_at_a_tangent_test) {\n\n        auto r = Ray(Point(0, 1, -5), Vector(0, 0, 1));\n        auto s = Sphere();\n        auto xs = s.intersects(r);\n\n        BOOST_CHECK_EQUAL(xs.size(), 2);\n        BOOST_CHECK_EQUAL(xs[0], 5.0);\n        BOOST_CHECK_EQUAL(xs[1], 5.0);\n\n    }\n\n    BOOST_AUTO_TEST_CASE(a_ray_misses_a_sphere_test) {\n\n        auto r = Ray(Point(0, 2, -5), Vector(0, 0, 1));\n        auto s = Sphere();\n        auto xs = s.intersects(r);\n\n        BOOST_CHECK_EQUAL(xs.size(), 0);\n    }\n\n    BOOST_AUTO_TEST_CASE(a_ray_originates_inside_a_sphere_test) {\n\n        auto r = Ray(Point(0, 0, 0), Vector(0, 0, 1));\n        auto s = Sphere();\n        auto xs = s.intersects(r);\n\n        BOOST_CHECK_EQUAL(xs.size(), 2);\n        BOOST_CHECK_EQUAL(xs[0], -1.0);\n        BOOST_CHECK_EQUAL(xs[1], 1.0);\n\n    }\n\n    BOOST_AUTO_TEST_CASE(a_sphere_is_behind_a_ray_test) {\n\n        auto r = Ray(Point(0, 0, 5), Vector(0, 0, 1));\n        auto s = Sphere();\n        auto xs = s.intersects(r);\n\n        BOOST_CHECK_EQUAL(xs.size(), 2);\n        BOOST_CHECK_EQUAL(xs[0], -6.0);\n        BOOST_CHECK_EQUAL(xs[1], -4.0);\n\n    }\n\n    BOOST_AUTO_TEST_CASE(a_spheres_default_transformation_test) {\n\n        auto s = Sphere();\n        Matrix m = s.transform();\n\n        BOOST_CHECK_EQUAL(s.transform(), Matrix::getIdentity());\n\n    }\n\n    BOOST_AUTO_TEST_CASE(changing_a_spheres_transformation_test) {\n\n        auto s = Sphere();\n        auto t = Translation(2, 3, 4);\n        s.setTransform(t);\n\n        Matrix m = s.transform();\n\n        BOOST_CHECK_EQUAL(s.transform(), t);\n\n    }\n\n    BOOST_AUTO_TEST_CASE(intersecting_a_scaled_sphere_with_a_ray_test) {\n        auto r = Ray(Point(0, 0, -5), Vector(0, 0, 1));\n        auto s = Sphere();\n\n        s.setTransform(Scaling(2, 2, 2));\n\n        auto xs = s.intersects(r);\n        BOOST_CHECK_EQUAL(xs.size(), 2);\n        BOOST_CHECK_EQUAL(xs[0], 3);\n        BOOST_CHECK_EQUAL(xs[1], 7);\n    }\n\n    BOOST_AUTO_TEST_CASE(intersecting_a_translated_sphere_with_a_ray_test) {\n        auto r = Ray(Point(0, 0, -5), Vector(0, 0, 1));\n        auto s = Sphere();\n\n        s.setTransform(Scaling(5, 0, 0));\n\n        auto xs = s.intersects(r);\n        BOOST_CHECK_EQUAL(xs.size(), 0);\n    }\n\n    void createSphereImage(Canvas &canvas, const Color &color, Sphere &sphere,\n                           const char *filename) {\n        auto canvas_pixels = canvas.width;\n\n        auto wall_z = 10;\n        auto wall_size = 7.0;\n        auto pixel_size = wall_size / (double) canvas_pixels;\n        auto half = wall_size / 2;\n\n        auto ray_origin = Point(0, 0, -5);\n\n        for (int y = 0; y < canvas_pixels; y++) {\n            auto world_y = half - pixel_size * y;\n            for (int x = 0; x < canvas_pixels; x++) {\n                auto world_x = -half + pixel_size * x;\n                auto position = Point(world_x, world_y, wall_z);\n                auto r = Ray(ray_origin, Vector(position.subtract(ray_origin)).normalize());\n\n                auto xs = sphere.intersects(r);\n                if (x % 10 == 0 && y % 10 == 0) {\n                    std::cout << \" \" << x << \" \" << y << std::endl;\n                }\n\n                if (xs.size() > 0) {\n                    canvas.writePixel(x, y, color);\n                }\n            }\n        }\n\n        canvas.toFile(filename);\n    }\n\n//    BOOST_AUTO_TEST_CASE(sphere_test) {\n//        int canvas_pixels = 100;\n//        auto c = Canvas(canvas_pixels, canvas_pixels);\n//\n//        auto sphere = Sphere();\n//\n//        createSphereImage(c, Color(1, 0, 0), sphere, \"sphere.ppm\");\n//\n//    }\n//\n//    BOOST_AUTO_TEST_CASE(sphere_shrink_along_y_axis_test) {\n//        int canvas_pixels = 100;\n//        auto c = Canvas(canvas_pixels, canvas_pixels);\n//\n//        auto sphere = Sphere();\n//        sphere.setTransform(Scaling(1, 0.5, 1));\n//\n//        createSphereImage(c, Color(1, 0, 0), sphere, \"sphere_shrink_y.ppm\");\n//\n//    }\n//\n//    BOOST_AUTO_TEST_CASE(sphere_shrink_along_x_axis_test) {\n//        int canvas_pixels = 100;\n//        auto c = Canvas(canvas_pixels, canvas_pixels);\n//\n//        auto sphere = Sphere();\n//        sphere.setTransform(Scaling(0.5, 1, 1));\n//\n//        createSphereImage(c, Color(1, 0, 0), sphere, \"sphere_shrink_x.ppm\");\n//\n//    }\n//\n//    BOOST_AUTO_TEST_CASE(sphere_shrink_and_rotate_test) {\n//        int canvas_pixels = 100;\n//        auto c = Canvas(canvas_pixels, canvas_pixels);\n//\n//        auto sphere = Sphere();\n//        sphere.setTransform(RotationZ(M_PI / 4).multiply(Scaling(0.5, 1, 1)));\n//\n//        createSphereImage(c, Color(1, 0, 0), sphere, \"sphere_shrink_and_rotate.ppm\");\n//\n//    }\n//\n//    BOOST_AUTO_TEST_CASE(sphere_shrink_and_skew_test) {\n//        int canvas_pixels = 100;\n//        auto c = Canvas(canvas_pixels, canvas_pixels);\n//\n//        auto sphere = Sphere();\n//        sphere.setTransform(Shearing(1, 0, 0, 0, 0, 0).multiply(Scaling(0.5, 1, 1)));\n//\n//        createSphereImage(c, Color(1, 0, 0), sphere, \"sphere_shrink_and_skew.ppm\");\n//\n//    }\n\n    BOOST_AUTO_TEST_CASE(the_normal_on_a_sphere_at_a_point_on_the_x_test) {\n        auto s = Sphere();\n        auto n = s.normalAt(Point(1, 0, 0));\n\n        BOOST_CHECK_EQUAL(n, Vector(1, 0, 0));\n    }\n\n    BOOST_AUTO_TEST_CASE(the_normal_on_a_sphere_at_a_point_on_the_y_test) {\n        auto s = Sphere();\n        auto n = s.normalAt(Point(0, 1, 0));\n\n        BOOST_CHECK_EQUAL(n, Vector(0, 1, 0));\n    }\n\n    BOOST_AUTO_TEST_CASE(the_normal_on_a_sphere_at_a_point_on_the_z_test) {\n        auto s = Sphere();\n        auto n = s.normalAt(Point(0, 0, 1));\n\n        BOOST_CHECK_EQUAL(n, Vector(0, 0, 1));\n    }\n\n    BOOST_AUTO_TEST_CASE(the_normal_on_a_sphere_at_a_nonaxial_test) {\n        auto s = Sphere();\n        auto n = s.normalAt(Point(sqrt(3) / 3, sqrt(3) / 3, sqrt(3) / 3));\n\n        BOOST_CHECK_EQUAL(n, Vector(sqrt(3) / 3, sqrt(3) / 3, sqrt(3) / 3));\n    }\n\n    BOOST_AUTO_TEST_CASE(the_normal_is_a_normalized_vector_test) {\n        auto s = Sphere();\n        auto n = s.normalAt(Point(sqrt(3) / 3, sqrt(3) / 3, sqrt(3) / 3));\n\n        BOOST_CHECK_EQUAL(n, n.normalize());\n    }\n\n    BOOST_AUTO_TEST_CASE(computing_the_normal_on_a_translated_sphere_test) {\n        auto s = Sphere();\n        s.setTransform(Translation(0, 1, 0));\n\n        auto n = s.normalAt(Point(0, 1.70711, -0.70711));\n\n        BOOST_CHECK_EQUAL(n, Vector(0, 0.70711, -0.70711));\n    }\n\n    BOOST_AUTO_TEST_CASE(computing_the_normal_on_a_transformed_sphere_test) {\n        auto s = Sphere();\n        auto m = Scaling(1, 0.5, 1).multiply(RotationZ(M_PI / 5));\n        s.setTransform(m);\n\n        auto n = s.normalAt(Point(0, sqrt(2) / 2, -sqrt(2) / 2));\n\n        BOOST_CHECK_EQUAL(n, Vector(0, 0.97014, -0.24254));\n    }\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "1fafc7331d2470d073eccef45b8685599ea4944f", "size": 7512, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_spheres.cpp", "max_stars_repo_name": "RainerBlessing/TheRayTracerChallenge-C-", "max_stars_repo_head_hexsha": "22c990201507f46d5bb1604bc1f6ee88e59cef95", "max_stars_repo_licenses": ["MIT"], "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_spheres.cpp", "max_issues_repo_name": "RainerBlessing/TheRayTracerChallenge-C-", "max_issues_repo_head_hexsha": "22c990201507f46d5bb1604bc1f6ee88e59cef95", "max_issues_repo_licenses": ["MIT"], "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_spheres.cpp", "max_forks_repo_name": "RainerBlessing/TheRayTracerChallenge-C-", "max_forks_repo_head_hexsha": "22c990201507f46d5bb1604bc1f6ee88e59cef95", "max_forks_repo_licenses": ["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.0038610039, "max_line_length": 92, "alphanum_fraction": 0.5873269436, "num_tokens": 2125, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4862455984309629}}
{"text": "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT license.\n\n#include \"gemm.h\"\n#include \"common.h\"\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n// Wasm interop method\nvoid gemm_f32(void *data) {\n  uint32_t *dataIndex = static_cast<uint32_t *>(data);\n  uint32_t const argc = dataIndex[0];\n\n  gemm_f32_imp(\n      PARAM_BOOL(data, dataIndex[1]), PARAM_BOOL(data, dataIndex[2]),\n      PARAM_INT32(data, dataIndex[3]), PARAM_INT32(data, dataIndex[4]),\n      PARAM_INT32(data, dataIndex[5]), PARAM_FLOAT(data, dataIndex[6]),\n      PARAM_FLOAT_PTR(data, dataIndex[7]), PARAM_FLOAT_PTR(data, dataIndex[8]),\n      PARAM_FLOAT(data, dataIndex[9]), PARAM_FLOAT_PTR(data, dataIndex[10]));\n}\n\n// Core operator implementation\nvoid gemm_f32_imp(const bool TransA, const bool TransB, const int M,\n                  const int N, const int K, const float alpha, const float *A,\n                  const float *B, const float beta, float *C) {\n  auto C_mat = Eigen::Map<Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic>>(\n      C, static_cast<int64_t>(N), static_cast<int64_t>(M));\n  if (beta == 0) {\n    C_mat.setZero();\n  } else {\n    C_mat *= beta;\n  }\n\n  if (!TransA) {\n    if (!TransB) {\n      C_mat.noalias() +=\n          alpha *\n          (Eigen::Map<\n               const Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic>>(\n               B, static_cast<int64_t>(N), static_cast<int64_t>(K)) *\n           Eigen::Map<\n               const Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic>>(\n               A, static_cast<int64_t>(K), static_cast<int64_t>(M)));\n    } else {\n      C_mat.noalias() +=\n          alpha *\n          (Eigen::Map<\n               const Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic>>(\n               B, static_cast<int64_t>(K), static_cast<int64_t>(N))\n               .transpose() *\n           Eigen::Map<\n               const Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic>>(\n               A, static_cast<int64_t>(K), static_cast<int64_t>(M)));\n    }\n  } else {\n    if (!TransB) {\n      C_mat.noalias() +=\n          alpha *\n          (Eigen::Map<\n               const Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic>>(\n               B, static_cast<int64_t>(N), static_cast<int64_t>(K)) *\n           Eigen::Map<\n               const Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic>>(\n               A, static_cast<int64_t>(M), static_cast<int64_t>(K))\n               .transpose());\n    } else {\n      C_mat.noalias() +=\n          alpha *\n          (Eigen::Map<\n               const Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic>>(\n               B, static_cast<int64_t>(K), static_cast<int64_t>(N))\n               .transpose() *\n           Eigen::Map<\n               const Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic>>(\n               A, static_cast<int64_t>(M), static_cast<int64_t>(K))\n               .transpose());\n    }\n  }\n}\n", "meta": {"hexsha": "fd329cb604b53c685e74066f27e98056da270801", "size": 2923, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/wasm-ops/gemm.cpp", "max_stars_repo_name": "joey00072/onnxjs", "max_stars_repo_head_hexsha": "3eb598922fd52f68d93305933df13fd724800c13", "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/gemm.cpp", "max_issues_repo_name": "joey00072/onnxjs", "max_issues_repo_head_hexsha": "3eb598922fd52f68d93305933df13fd724800c13", "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/gemm.cpp", "max_forks_repo_name": "joey00072/onnxjs", "max_forks_repo_head_hexsha": "3eb598922fd52f68d93305933df13fd724800c13", "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": 36.5375, "max_line_length": 80, "alphanum_fraction": 0.5709887102, "num_tokens": 726, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4862455984309629}}
{"text": "/***\n * This is an implementation of a soft rigid body constraint. The landmarks it is defined between and\n * the weight adjust the strength of the constraint\n */\n\n#ifndef WAVE_LANDMARK_DISPLACEMENT_HPP\n#define WAVE_LANDMARK_DISPLACEMENT_HPP\n\n#include <Eigen/Core>\n#include <ceres/ceres.h>\n#include \"wave/utils/math.hpp\"\n\nnamespace wave {\n\nclass RigidResidual : public ceres::SizedCostFunction<3, 6, 6> {\n public:\n    virtual ~RigidResidual() {}\n\n    RigidResidual(const double &weight, const Vec3& disp)\n            : weight(weight), disp(disp) {}\n\n    virtual bool Evaluate(double const *const *parameters, double *residuals, double **jacobians) const;\n private:\n    const double weight;\n    const Vec3 disp;\n};\n\n}\n\n#endif //WAVE_LANDMARK_DISPLACEMENT_HPP\n", "meta": {"hexsha": "10aaf86a4918fafd815c6a77904822b9a00b9b62", "size": 758, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "wave_odometry/include/wave/odometry/geometry/rigid_residual.hpp", "max_stars_repo_name": "Jebediah/libwave", "max_stars_repo_head_hexsha": "c04998c964f0dc7d414783c6e8cf989a2716ad54", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-06-13T13:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-13T14:54:35.000Z", "max_issues_repo_path": "wave_odometry/include/wave/odometry/geometry/rigid_residual.hpp", "max_issues_repo_name": "Jebediah/libwave", "max_issues_repo_head_hexsha": "c04998c964f0dc7d414783c6e8cf989a2716ad54", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "wave_odometry/include/wave/odometry/geometry/rigid_residual.hpp", "max_forks_repo_name": "Jebediah/libwave", "max_forks_repo_head_hexsha": "c04998c964f0dc7d414783c6e8cf989a2716ad54", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-13T02:27:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-13T02:27:29.000Z", "avg_line_length": 24.4516129032, "max_line_length": 104, "alphanum_fraction": 0.7308707124, "num_tokens": 191, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4862455984309629}}
{"text": "//\n//  get_disp_from_BIE.hpp\n//  hybrid_fem_bie\n//\n//  Created by Max on 2/8/18.\n//\n//\n\n#ifndef get_disp_from_BIE_hpp\n#define get_disp_from_BIE_hpp\n\n#include <stdio.h>\n#include <iostream>\n#include <Eigen/Eigen>\n#include \"maplocal.hpp\"\n#include \"infinite_boundary.hh\"\n\n\nusing namespace Eigen;\nvoid get_disp_from_BIE(ArrayXi &BIE_top_surf_index, ArrayXi &BIE_bot_surf_index, VectorXd &fe_global, int nx, double dx, int Ndofn, InfiniteBoundary & BIE_inf_top, InfiniteBoundary &BIE_inf_bot, NodalField *BIE_top_disp_x_ptr, NodalField *BIE_top_disp_y_ptr, NodalField *BIE_top_vel_x_ptr, NodalField *BIE_top_vel_y_ptr, NodalField *BIE_bot_disp_x_ptr, NodalField *BIE_bot_disp_y_ptr, NodalField *BIE_bot_vel_x_ptr, NodalField *BIE_bot_vel_y_ptr);\n\n#endif /* get_disp_from_BIE_hpp */\n", "meta": {"hexsha": "db0e742e38757b3686515038709e9bf499fa6d99", "size": 776, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/fem/get_disp_from_BIE.hpp", "max_stars_repo_name": "XiaoMaResearch/hybrid_tsunamic_plane_stress", "max_stars_repo_head_hexsha": "574988edfcd4839f680b85cde2bf818936e86b78", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-04-12T19:51:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-16T07:12:57.000Z", "max_issues_repo_path": "src/fem/get_disp_from_BIE.hpp", "max_issues_repo_name": "XiaoMaResearch/hybrid_tsunamic_plane_stress", "max_issues_repo_head_hexsha": "574988edfcd4839f680b85cde2bf818936e86b78", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/fem/get_disp_from_BIE.hpp", "max_forks_repo_name": "XiaoMaResearch/hybrid_tsunamic_plane_stress", "max_forks_repo_head_hexsha": "574988edfcd4839f680b85cde2bf818936e86b78", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-07-07T07:23:58.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-07T07:23:58.000Z", "avg_line_length": 33.7391304348, "max_line_length": 447, "alphanum_fraction": 0.8028350515, "num_tokens": 236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4862455923600086}}
{"text": "#include \"corridor/frenet_types.h\"\n\n#include <Eigen/Core>\n#include <iostream>\n\n#include \"corridor/cubic_spline/cubic_spline_types.h\"\n#include \"corridor/unscented_transformation/polar_coordinate_transformation.h\"\n\nusing namespace corridor;\n\n// /////////////////////////////////////////////////////////////////////////////\n// Frenet Frame\n// /////////////////////////////////////////////////////////////////////////////\n\nCartesianPoint2D FrenetFrame2D::FromFrenetPoint(\n    const FrenetPoint2D& frenet_point) const {\n  // Vector transfromation, translated by the origin of the frenet frame\n  return FromFrenetVector(frenet_point) + origin_;\n};\n\nCartesianVector2D FrenetFrame2D::FromFrenetVector(\n    const FrenetVector2D& frenet_vector) const {\n  //! Local point\n  const FrenetVector2D relative_vector{\n      frenet_vector.l() - frenet_base_.arc_length, frenet_vector.d()};\n  // Coordination transformation\n  return rotMat_F2C_ * relative_vector;\n};\n\nCartesianState2D FrenetFrame2D::FromFrenetState(\n    const FrenetState2D& frenet_state) const {\n  // TODO(dsp): add convertion for moving frenet frame assumption\n  CartesianStateVector2D cartesian_mean(\n      FromFrenetPoint(frenet_state.position()),\n      FromFrenetVector(frenet_state.velocity()));\n\n  // 4x4 rotation matrix\n  Eigen::Matrix<corridor::RealType, 4, 4> rotation_matrix =\n      Eigen::Matrix<corridor::RealType, 4, 4>::Zero();\n\n  // Fill with 2d rotation matrices\n  rotation_matrix.block<2, 2>(0, 0) = rotMat_F2C_;\n  rotation_matrix.block<2, 2>(2, 2) = rotMat_F2C_;\n\n  CartesianStateCovarianceMatrix2D cartesian_cov_mat =\n      rotation_matrix * frenet_state.covarianceMatrix() *\n      rotation_matrix.transpose();\n\n  return CartesianState2D(cartesian_mean, cartesian_cov_mat);\n}\n\nFrenetPoint2D FrenetFrame2D::FromCartesianPoint(\n    const CartesianPoint2D& cartesian_position) const {\n  //! Define local point\n  const CartesianVector2D relative_vector = cartesian_position - origin_;\n  FrenetVector2D tmp = FromCartesianVector(relative_vector);\n  // Add arc-length of the frenet base\n  tmp.l() += frenet_base_.arc_length;\n  //! Convert it to a FrenetPoint and return\n  return FrenetPoint2D(tmp);\n};\n\nFrenetVector2D FrenetFrame2D::FromCartesianVector(\n    const CartesianVector2D& cartesian_vector) const {\n  //! Coordination transformation\n  FrenetVector2D frenet_vector = rotMat_C2F_ * cartesian_vector;\n  return frenet_vector;\n};\n\nRealType FrenetFrame2D::FromCartesianOrientation(\n    const RealType cartesian_orientation) const {\n  const auto angle = cartesian_orientation - frenet_base_.orientation;\n  return constrainAngle(angle);\n}\n\nFrenetState2D FrenetFrame2D::FromCartesianState(\n    const CartesianState2D& cartesian_state,\n    const bool moving_frenet_frame) const {\n  if (moving_frenet_frame) {\n    return FromCartesianStateTaylorExpansion(cartesian_state);\n  }\n  // Linear transformation function\n  return {\n      this->frenet_base().id, FromCartesianStateVector(cartesian_state.mean()),\n      FromCartesianStateCovarianceMatrix(cartesian_state.covarianceMatrix())};\n}\n\nFrenetStateVector2D FrenetFrame2D::FromCartesianStateVector(\n    const CartesianStateVector2D& cartesian_state,\n    const bool moving_frenet_frame) const {\n  // Simple transformation as projection of the cartesian state position and\n  // vectors onto the axes of the Frenet frame\n  FrenetPoint2D position = FromCartesianPoint(cartesian_state.position());\n  FrenetVector2D velocity = FromCartesianVector(cartesian_state.velocity());\n\n  if (moving_frenet_frame) {\n    // In case of assuming a moving Frenet frame we need some correction terms\n    // for accounting the rotation of the Frenet Frame.\n    // Velocity of Frenet base is assumed to be the projection of the velocity\n    // onto the tangent vector of the curve.\n    const RealType theta_dot = frenet_base_.curvature * velocity.l();\n    const CartesianVector2D relative_vector =\n        cartesian_state.position() - origin_;\n    RotationMatrix rotMat_C2F_prime;\n    rotMat_C2F_prime << normal_.x(), normal_.y(), -tangent_.x(), -tangent_.y();\n    velocity += theta_dot * rotMat_C2F_prime * relative_vector;\n  }\n  return FrenetStateVector2D(position, velocity);\n}\n\nFrenetStateCovarianceMatrix2D FrenetFrame2D::FromCartesianStateCovarianceMatrix(\n    const CartesianStateCovarianceMatrix2D& state_vector_covariance_matrix,\n    const bool moving_frenet_frame) const {\n  // 4x4 rotation matrix\n  Eigen::Matrix<corridor::RealType, 4, 4> rotation_matrix =\n      Eigen::Matrix<corridor::RealType, 4, 4>::Zero();\n\n  // Fill with 2d rotation matrices\n  rotation_matrix.block<2, 2>(0, 0) = rotMat_C2F_;\n  rotation_matrix.block<2, 2>(2, 2) = rotMat_C2F_;\n\n  // Linear transformation of the covariance matrices.\n  return rotation_matrix * state_vector_covariance_matrix *\n         rotation_matrix.transpose();\n}\n\nFrenetState2D FrenetFrame2D::FromCartesianStateTaylorExpansion(\n    const CartesianState2D& cartesian_state) const {\n  // Non-linear transformation using the Taylor Series upt to term\n  FrenetStateVector2D frenet_state_vector =\n      FromCartesianStateVector(cartesian_state.mean(), true);\n\n  JacobianMatrix jacobian_matrix = defineJacobianMatrix(cartesian_state);\n  FrenetStateCovarianceMatrix2D frenet_cov_mat =\n      jacobian_matrix * cartesian_state.covarianceMatrix() *\n      jacobian_matrix.transpose();\n\n  return {this->frenet_base().id, frenet_state_vector, frenet_cov_mat};\n}\n\nFrenetFrame2D::JacobianMatrix FrenetFrame2D::defineJacobianMatrix(\n    const CartesianState2D& cartesian_state) const {\n  // Easy access\n  const CartesianVector2D relative_vector =\n      cartesian_state.position() - origin_;\n  const RealType projection_on_tangent = tangent_.dot(relative_vector);\n  const RealType projection_on_normal = normal_.dot(relative_vector);\n\n  const RealType vp = tangent_.dot(cartesian_state.velocity());\n\n  // Jacobean matrix at cartesian mean\n  Eigen::Matrix<RealType, 4, 4> jacobian_matrix =\n      Eigen::Matrix<RealType, 4, 4>::Zero();\n  jacobian_matrix.block<2, 2>(0, 0) = rotMat_C2F_;\n  jacobian_matrix(2, 0) = frenet_base_.curvature * vp * normal_.x();\n  jacobian_matrix(2, 1) = frenet_base_.curvature * vp * normal_.y();\n  jacobian_matrix(2, 2) = tangent_.x() + frenet_base_.curvature * tangent_.x() *\n                                             projection_on_normal;\n  jacobian_matrix(2, 3) = tangent_.y() + frenet_base_.curvature * tangent_.y() *\n                                             projection_on_normal;\n\n  jacobian_matrix(3, 0) = -frenet_base_.curvature * vp * tangent_.x();\n  jacobian_matrix(3, 1) = -frenet_base_.curvature * vp * tangent_.y();\n  jacobian_matrix(3, 2) = normal_.x() + frenet_base_.curvature * tangent_.x() *\n                                            projection_on_tangent;\n  jacobian_matrix(3, 3) = normal_.y() + frenet_base_.curvature * tangent_.y() *\n                                            projection_on_tangent;\n\n  return jacobian_matrix;\n}\n\n// /////////////////////////////////////////////////////////////////////////////\n// Frenet Polyline\n// /////////////////////////////////////////////////////////////////////////////\n\nRealType FrenetPolyline::deviationAt(const RealType query_l) const {\n  // Check if query l value is smaller or larger that the polyline\n  const auto s_min = data_(DataType::kArclength, 0);\n  const auto s_max = data_(DataType::kArclength, data_.cols() - 1);\n\n  if (query_l <= (s_min + cubic_spline::g_epsilon_projection)) {\n    return data_(DataType::kDeviation, 0);\n  }\n  if ((s_max - cubic_spline::g_epsilon_projection) <= query_l) {\n    return data_(DataType::kDeviation, data_.cols() - 1);\n  }\n\n  //! Get index of segment which contains the arc-length\n  DataMatrix::Index index = 0;\n  DataMatrix::Index max_index =\n      data_.cols() - 2;  // first index of last segment\n  const bool valid = (data_.row(kArclength).array() > query_l).maxCoeff(&index);\n\n  if (valid) {\n    // Check that always a valid data segment is used\n    index = (0 < index) ? (index - 1) : (index);\n    index = (max_index < index) ? (max_index) : (index);\n  } else {\n    // Arc-length is longer as the refernce line. Use last segment start\n    // index\n    index = (valid) ? (index) : (max_index);\n  }\n\n  if (index + 1 >= data_.cols()) {\n    return data_(DataType::kDeviation, index);\n  }\n\n  // Interpolation of the deviation\n  const auto delta_l = data_(DataType::kArclength, index + 1) -\n                       data_(DataType::kArclength, index);\n  assert(abs(delta_l) > 1e-3);\n  const auto alpha = (query_l - data_(DataType::kArclength, index)) / delta_l;\n\n  const auto delta_d = data_(DataType::kDeviation, index + 1) -\n                       data_(DataType::kDeviation, index);\n\n  return delta_d * alpha + data_(DataType::kDeviation, index);\n};\n\n// /////////////////////////////////////////////////////////////////////////////\n// Frenet state (mean and covariance matrix)\n// /////////////////////////////////////////////////////////////////////////////\n\nUncertainValue FrenetState2D::lateral_position() const {\n  return UncertainValue(mean_.d(), cov_mat_.dd());\n}\nUncertainValue FrenetState2D::longitudinal_position() const {\n  return UncertainValue(mean_.l(), cov_mat_.ll());\n}\n\nUncertainValue FrenetState2D::abs_velocity() {\n  const auto& polar_velocity_state = getPolarVelocityStatePtr();\n  return polar_velocity_state->abs_value();\n};\nUncertainValue FrenetState2D::orientation() {\n  const auto& polar_velocity_state = getPolarVelocityStatePtr();\n  return polar_velocity_state->orientation();\n};\n\nconst PolarStatePtr FrenetState2D::getPolarVelocityStatePtr() {\n  if (polar_velocity_state_ != nullptr) {\n    // if polar velocity is already calculated return pointer.\n    return polar_velocity_state_;\n  }\n\n  // Initialize shared ptr\n  polar_velocity_state_ = std::make_shared<PolarState2D>();\n\n  // Polar velocity is not yet set, calculate and return it.\n  unscented_transformation::ToPolarCoordinates2D(\n      mean_.velocity(), cov_mat_.velocity(), &polar_velocity_state_->mean,\n      &polar_velocity_state_->cov_mat);\n\n  return polar_velocity_state_;\n};\n", "meta": {"hexsha": "6d282e681ab2c9f43baee090d44be448396723e1", "size": 10030, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/frenet_types.cpp", "max_stars_repo_name": "dspetrich/corridor", "max_stars_repo_head_hexsha": "ecbb3a09c94897a03b88c79b67131cbe2f8ec705", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-03-24T22:31:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-06T10:41:48.000Z", "max_issues_repo_path": "src/frenet_types.cpp", "max_issues_repo_name": "dspetrich/corridor", "max_issues_repo_head_hexsha": "ecbb3a09c94897a03b88c79b67131cbe2f8ec705", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-04-16T13:44:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-25T09:22:54.000Z", "max_forks_repo_path": "src/frenet_types.cpp", "max_forks_repo_name": "dspetrich/corridor", "max_forks_repo_head_hexsha": "ecbb3a09c94897a03b88c79b67131cbe2f8ec705", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-04-16T14:31:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-01T15:07:51.000Z", "avg_line_length": 39.1796875, "max_line_length": 80, "alphanum_fraction": 0.6974077767, "num_tokens": 2563, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4862316785613561}}
{"text": "#include <HElib/FHE.h>\n#include <HElib/FHEContext.h>\n#include <HElib/EncryptedArray.h>\n#include <HElib/PAlgebra.h>\n#include <NTL/ZZX.h>\n#include \"SMP/Timer.hpp\"\n#include \"SMP/literal.hpp\"\n#include \"SMP/HElib.hpp\"\nbool check(std::vector<ZZX> const& factors, long d) {\n    std::cout << \"factors: \\n\";\n    for (auto const &f : factors) {\n        std::cout << f << \"\\n\";\n        for (long i = 1; i < d; i++) {\n            if (NTL::coeff(f, i) != 0)\n                return false;\n        }\n    }\n    return true;\n}\n\nstd::ostream& print_poly(NTL::ZZX const& poly, long d) {\n    std::cout << \"[\";\n    for (; d > 0; d--)\n        std::cout << NTL::coeff(poly, d) << \",\";\n    std::cout << NTL::coeff(poly, 0) << \"]\";\n    return std::cout;\n}\n\nlong inner_product(NTL::zz_pX const& a, \n                   NTL::zz_pX const& b) \n{\n    NTL::zz_p ip;\n    long deg = NTL::deg(a);\n    for (long i = 0; i <= deg; i++) {\n        ip += (NTL::coeff(a, i) * NTL::coeff(b, deg - i));\n    }\n    return ip._zz_p__rep;\n}\n\n/// Return the leading coeff of the rem polynomial f % h\n/// h = X^d + a\nNTL::zz_p ModGetLeadingCoeff(NTL::zz_pX const& f,\n                             NTL::zz_pX const& h) \n{\n    long m = NTL::deg(f) + 1;\n    long d = NTL::deg(h);\n    long n = m / d;\n\n    // printf(\"|f| = %ld, |h| = %ld\\n\", m, d);\n    // std::cout << f << \"\\n\" << h << std::endl;\n    std::cout << h << std::endl;\n    NTL::zz_p beta = NTL::coeff(h, 0);\n    NTL::zz_p beta_power(1);\n    NTL::zz_p ret(NTL::coeff(f, d - 1));\n    std::cout << ret;\n    for (long i = 2; i <= n; i++) {\n        auto coeff = NTL::coeff(f, i * d - 1);\n        beta_power *= beta;\n        coeff *= beta_power;\n        if ((i & 1) == 0) {\n            ret -= coeff;\n        std::cout << \" - \" << beta_power << \" * \" << NTL::coeff(f, i * d - 1) ;\n        } else {\n        std::cout << \" + \" << beta_power << \" * \" << NTL::coeff(f, i * d - 1) ;\n            ret += coeff;\n        }\n    }\n    std::cout << \"\\n\";\n    auto be = beta;\n    for (long i = 1; i <= n; i++) {\n        std::cout << be << \" \";\n        be *= beta;\n    }\n    std::cout << \"\\n\";\n    // std::cout << \"result \" << ret << std::endl;\n    return ret;\n}\n\nstd::vector<long> precompute_power(long beta, long p, long l)\n{\n    std::vector<long> beta_power_l(l);\n    /// (-beta)^k mod p for 0 <= k < l\n    for (long i = 0; i < l; i++)\n        beta_power_l[i] = NTL::PowerMod(i & 1 ? p - beta : beta, i, p);\n    return beta_power_l;\n}\n\nlong mod_with_precomputed_table(NTL::ZZX const& poly,\n                                std::vector<long> const& tbl,\n                                FHEcontext const &context)\n{\n    long d = context.ea->getDegree();\n    long l = context.ea->size();\n    long p = context.alMod.getPPowR();\n    long phim = context.zMStar.getPhiM();\n    long ret = 0;\n    auto inv_p = NTL::PrepMulMod(p);\n    for (long i = 0; i < l; i++) {\n        long coeff_loc = (i + 1) * d - 1;\n        assert(coeff_loc < phim);\n        long coeff = NTL::to_long(NTL::coeff(poly, coeff_loc));\n        coeff = NTL::MulMod(coeff, tbl[i], p, inv_p);\n        ret = NTL::AddMod(ret, coeff, p);\n    }\n    return ret;\n}\n\nvoid faster() {\n    NTL::SetSeed(NTL::to_ZZ(132));\n    long m = 8192;\n    long p = 70913;\n    NTL::zz_p::init(p);\n    FHEcontext context(m, p, 1);\n    context.bitsPerLevel = 60;\n    buildModChain(context, 2);\n    FHESecKey sk(context);\n    sk.GenSecKey(64);\n\n    const EncryptedArray *ea = context.ea;\n    const long l = ea->size();\n    const long d = ea->getDegree();\n    std::cout << \"l = \" << l << \", d = \" << d << std::endl;\n\n    std::vector<GMMPrecompTable> tables = precompute_gmm_tables(context);\n    const auto &encoder = context.alMod.getDerived(PA_zz_p());\n\n    std::vector<NTL::zz_pX> vec_A(l);\n    std::vector<NTL::zz_pX> vec_B(l);\n    for (long i = 0; i < l; i++) {\n        NTL::random(vec_A[i], d);\n        NTL::random(vec_B[i], d);\n        std::cout << inner_product(vec_A[i], vec_B[i]) << \" \";\n    }\n    std::cout << \"\\n\";\n\n    NTL::zz_pX encoded_A, encoded_B;\n    encoder.CRT_reconstruct(encoded_A, vec_A);\n    encoder.CRT_reconstruct(encoded_B, vec_B);\n\n    Ctxt ctx_vec_A(sk), ctx_vec_B(sk);\n    sk.Encrypt(ctx_vec_A, NTL::conv<NTL::ZZX>(encoded_A));\n    sk.Encrypt(ctx_vec_B, NTL::conv<NTL::ZZX>(encoded_B));\n    ctx_vec_A.multiplyBy(ctx_vec_B);\n\n    std::vector<NTL::zz_pX> slots;\n    NTL::ZZX decrypted;\n    sk.Decrypt(decrypted, ctx_vec_A);\n    double raw_dec_time = 0.;\n    {\n        AutoTimer timer(&raw_dec_time);\n        rawDecode(slots, decrypted, context);\n    }\n\n    double table_dec_time = 0.;\n    std::vector<long> inner_products;\n    {\n        AutoTimer timer(&table_dec_time);\n        extract_inner_products(inner_products, decrypted, tables, context);\n    }\n    std::cout << inner_products << std::endl;\n\n    std::cout << raw_dec_time << \" : \" << table_dec_time << std::endl;\n}\n\nvoid test_poly_mod()\n{\n    NTL::zz_p::init(769);\n    NTL::zz_pX ply;\n    ply.SetLength(3);\n    ply[0] = 3; ply[2] = 1; // X^2 + 3\n    NTL::zz_pXModulus mod(ply);\n\n    NTL::zz_pX rnd;\n    NTL::random(rnd, 6);\n    std::cout << rnd << std::endl;\n\n    NTL::zz_pX rm;\n    NTL::rem(rm, rnd, mod);\n    std::cout << rm << std::endl;\n}\n\nvoid normal() {\n    long m = 8192;\n    long p = 769;\n    FHEcontext context(m, p, 1);\n    context.bitsPerLevel = 59;\n    buildModChain(context, 2);\n    FHESecKey sk(context);\n    sk.GenSecKey(64);\n\n    const auto &factors = context.alMod.getFactorsOverZZ();\n    EncryptedArray *ea = new EncryptedArray(context, factors[0]);\n    const long l = ea->size();\n    const long d = ea->getDegree();\n\n    NTL::zz_p::init(p);\n    std::vector<NTL::zz_pX> vec_A(l);\n    std::vector<NTL::zz_pX> vec_B(l);\n    std::vector<NTL::ZZX> Vec_A(l);\n    std::vector<NTL::ZZX> Vec_B(l);\n    for (long i = 0; i < l; i++) {\n        NTL::random(vec_A[i], d);\n        NTL::random(vec_B[i], d);\n        NTL::conv(Vec_A[i], vec_A[i]);\n        NTL::conv(Vec_B[i], vec_B[i]);\n        std::cout << inner_product(vec_A[i], vec_B[i]) << \" \";\n    }\n    std::cout << \"\\n\";\n\n    NTL::ZZX encoded_A, encoded_B;\n    for (long i = 0; i < 100; i++) {\n        FHE_NTIMER_START(EAEncode);\n        ea->encode(encoded_A, Vec_A);\n        ea->encode(encoded_B, Vec_B);\n        FHE_NTIMER_STOP(EAEncode);\n\n        FHE_NTIMER_START(rawEncode);\n        rawEncode(encoded_A, vec_A, context);\n        rawEncode(encoded_B, vec_B, context);\n        FHE_NTIMER_STOP(rawEncode);\n    }\n\n\n    Ctxt ctx_vec_A(sk), ctx_vec_B(sk);\n    sk.Encrypt(ctx_vec_A, encoded_A);\n    sk.Encrypt(ctx_vec_B, encoded_B);\n    ctx_vec_A.multiplyBy(ctx_vec_B);\n\n    NTL::ZZX decrypted;\n    sk.Decrypt(decrypted, ctx_vec_A);\n    std::vector<NTL::zz_pX> results;\n    std::vector<NTL::ZZX> Results;\n    std::vector<double> raw_decodes;\n    for (long i = 0; i < 100; i++) {\n        FHE_NTIMER_START(EADecode);\n        ea->decode(Results, decrypted);\n        FHE_NTIMER_STOP(EADecode);\n\n        FHE_NTIMER_START(rawDecode);\n        do {\n            raw_decodes.push_back(0.);\n            AutoTimer timer(&(raw_decodes.back()));\n            rawDecode(results, decrypted, context);\n        } while (0);\n        FHE_NTIMER_STOP(rawDecode);\n    }\n    //for (auto &s : results) {\n    //    std::cout << NTL::coeff(s, d - 1) << \" \";\n    //}\n    //std::cout << \"\\n\";\n\n    printNamedTimer(std::cout, \"EAEncode\");\n    printNamedTimer(std::cout, \"EADecode\");\n    printNamedTimer(std::cout, \"rawEncode\");\n    printNamedTimer(std::cout, \"rawDecode\");\n    auto decode = mean_std(raw_decodes);\n    std::cout << decode.first / 1000. << \" +- \" << decode.second << std::endl;\n}\n\nint main() {\n    //normal();\n    faster();\n    //test_poly_mod();\n    return 0;\n}\n", "meta": {"hexsha": "fcddf8e5f1de3ab8a65d71d506477f79c70c4a25", "size": 7608, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/fast_decryption.cpp", "max_stars_repo_name": "Vampsj/SMP", "max_stars_repo_head_hexsha": "ec332ed29bc33685d050478090e0a679ddef0e4d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/fast_decryption.cpp", "max_issues_repo_name": "Vampsj/SMP", "max_issues_repo_head_hexsha": "ec332ed29bc33685d050478090e0a679ddef0e4d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/fast_decryption.cpp", "max_forks_repo_name": "Vampsj/SMP", "max_forks_repo_head_hexsha": "ec332ed29bc33685d050478090e0a679ddef0e4d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6015037594, "max_line_length": 79, "alphanum_fraction": 0.5456098843, "num_tokens": 2444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324713956856, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.486231667851615}}
{"text": "/**\n * @file prefinement.cc\n * @brief Creates convergence plots for experiment 3.2.3.11\n * @author Tobias Rohner\n * @date April 2020\n * @copyright MIT License\n */\n\n#define _USE_MATH_DEFINES\n\n#include <lf/fe/fe.h>\n#include <lf/io/io.h>\n#include <lf/mesh/hybrid2d/hybrid2d.h>\n#include <lf/mesh/mesh.h>\n#include <lf/mesh/utils/utils.h>\n#include <lf/refinement/mesh_function_transfer.h>\n#include <lf/refinement/refinement.h>\n\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <boost/program_options.hpp>\n#include <cmath>\n#include <cstdlib>\n#include <filesystem>\n#include <fstream>\n#include <iostream>\n#include <memory>\n#include <string>\n#include <tuple>\n#include <vector>\n\nnamespace po = boost::program_options;\n\n/**\n * @brief Builds a mesh on [0, 1]^2 from two triangles\n * @returns A shared pointer to a mesh\n */\nstd::shared_ptr<lf::mesh::Mesh> getSquareDomain() {\n  lf::mesh::hybrid2d::MeshFactory factory(2);\n  // Add the vertices\n  std::vector<lf::mesh::MeshFactory::size_type> vertices;\n  Eigen::Vector2d vertex_coord;\n  vertex_coord << 0, 0;\n  vertices.push_back(factory.AddPoint(vertex_coord));\n  vertex_coord << 1, 0;\n  vertices.push_back(factory.AddPoint(vertex_coord));\n  vertex_coord << 1, 1;\n  vertices.push_back(factory.AddPoint(vertex_coord));\n  vertex_coord << 0, 1;\n  vertices.push_back(factory.AddPoint(vertex_coord));\n  // Add the triangles\n  Eigen::Matrix<double, Eigen::Dynamic, 3> coords(2, 3);\n  lf::mesh::MeshFactory::size_type nodes[3];  // NOLINT\n  coords << 0, 1, 0, 0, 0, 1;\n  nodes[0] = vertices[0];\n  nodes[1] = vertices[1];\n  nodes[2] = vertices[3];\n  auto geom_tria1 = std::make_unique<lf::geometry::TriaO1>(coords);\n  factory.AddEntity(lf::base::RefEl::kTria(), nodes, std::move(geom_tria1));\n  coords << 1, 1, 0, 0, 1, 1;\n  nodes[0] = vertices[1];\n  nodes[1] = vertices[2];\n  nodes[2] = vertices[3];\n  auto geom_tria2 = std::make_unique<lf::geometry::TriaO1>(coords);\n  factory.AddEntity(lf::base::RefEl::kTria(), nodes, std::move(geom_tria2));\n  // Build the mesh\n  return factory.Build();\n}\n\n/**\n * @brief Builds a mesh on [-1, 1]^2 \\ (]0, 1[x]-1, 0[) from four triangles\n * @returns A shared pointer to a mesh\n */\nstd::shared_ptr<lf::mesh::Mesh> getLDomain() {\n  lf::mesh::hybrid2d::MeshFactory factory(2);\n  // Add the vertices\n  std::vector<lf::mesh::MeshFactory::size_type> vertices;\n  Eigen::Vector2d vertex_coord;\n  vertex_coord << -1, -1;\n  vertices.push_back(factory.AddPoint(vertex_coord));\n  vertex_coord << 0, -1;\n  vertices.push_back(factory.AddPoint(vertex_coord));\n  vertex_coord << 0, 0;\n  vertices.push_back(factory.AddPoint(vertex_coord));\n  vertex_coord << 1, 0;\n  vertices.push_back(factory.AddPoint(vertex_coord));\n  vertex_coord << 1, 1;\n  vertices.push_back(factory.AddPoint(vertex_coord));\n  vertex_coord << -1, 1;\n  vertices.push_back(factory.AddPoint(vertex_coord));\n  // Add the triangles\n  Eigen::Matrix<double, Eigen::Dynamic, 3> coords(2, 3);\n  lf::mesh::MeshFactory::size_type nodes[3];  // NOLINT\n  coords << -1, 0, -1, -1, 0, 1;\n  nodes[0] = vertices[0];\n  nodes[1] = vertices[2];\n  nodes[2] = vertices[5];\n  auto geom_tria1 = std::make_unique<lf::geometry::TriaO1>(coords);\n  factory.AddEntity(lf::base::RefEl::kTria(), nodes, std::move(geom_tria1));\n  coords << 0, 1, -1, 0, 1, 1;\n  nodes[0] = vertices[2];\n  nodes[1] = vertices[4];\n  nodes[2] = vertices[5];\n  auto geom_tria2 = std::make_unique<lf::geometry::TriaO1>(coords);\n  factory.AddEntity(lf::base::RefEl::kTria(), nodes, std::move(geom_tria2));\n  coords << -1, 0, 0, -1, -1, 0;\n  nodes[0] = vertices[0];\n  nodes[1] = vertices[1];\n  nodes[2] = vertices[2];\n  auto geom_tria3 = std::make_unique<lf::geometry::TriaO1>(coords);\n  factory.AddEntity(lf::base::RefEl::kTria(), nodes, std::move(geom_tria3));\n  coords << 0, 1, 1, 0, 0, 1;\n  nodes[0] = vertices[2];\n  nodes[1] = vertices[3];\n  nodes[2] = vertices[4];\n  auto geom_tria4 = std::make_unique<lf::geometry::TriaO1>(coords);\n  factory.AddEntity(lf::base::RefEl::kTria(), nodes, std::move(geom_tria4));\n  // Build the mesh\n  return factory.Build();\n}\n\n/**\n * @brief Get the error of a test problem for the given mesh and FE space\n * @param degree The polynomial degree to use\n * @param mesh The mesh on which to solve the PDE\n * @param fe_space The fe space to use\n *\n * The test problem is formulated on [0, 1]^2 with Dirichlet boundary conditions\n and has the analytic solution\n * \\f[\n        u(x) = \\sin(\\pi x_1)\\sin(\\pi x_2)\n   \\f]\n */\nstd::tuple<double, double> computeErrorsSquareDomain(\n    unsigned degree, const std::shared_ptr<lf::mesh::Mesh> &mesh,\n    const std::shared_ptr<lf::fe::ScalarFESpace<double>> &fe_space) {\n  // The analytic solution\n  const auto u = [](const Eigen::VectorXd &x) -> double {\n    return std::sin(M_PI * x[0]) * std::sin(M_PI * x[1]);\n  };\n  const lf::mesh::utils::MeshFunctionGlobal mf_u(u);\n  // The gradient of the analytic solution\n  const auto u_grad = [](const Eigen::Vector2d &x) -> Eigen::Vector2d {\n    Eigen::Vector2d grad;\n    grad[0] = M_PI * std::cos(M_PI * x[0]) * std::sin(M_PI * x[1]);\n    grad[1] = M_PI * std::sin(M_PI * x[0]) * std::cos(M_PI * x[1]);\n    return grad;\n  };\n  const lf::mesh::utils::MeshFunctionGlobal mf_u_grad(u_grad);\n\n  // Define the load function of the manufactured solution\n  const auto load = [](const Eigen::Vector2d &x) -> double {\n    return 2 * M_PI * M_PI * std::sin(M_PI * x[0]) * std::sin(M_PI * x[1]);\n  };\n  const lf::mesh::utils::MeshFunctionGlobal mf_load(load);\n\n  // Assemble the system matrix and right hand side\n  const lf::assemble::DofHandler &dofh = fe_space->LocGlobMap();\n  lf::assemble::COOMatrix<double> A_COO(dofh.NumDofs(), dofh.NumDofs());\n  Eigen::VectorXd rhs = Eigen::VectorXd::Zero(dofh.NumDofs());\n  std::cout << \"\\t\\t> Assembling System Matrix\" << std::endl;\n  const lf::mesh::utils::MeshFunctionConstant<double> mf_alpha(1);\n  lf::fe::DiffusionElementMatrixProvider element_matrix_provider(fe_space,\n                                                                 mf_alpha);\n  lf::assemble::AssembleMatrixLocally(0, dofh, dofh, element_matrix_provider,\n                                      A_COO);\n  std::cout << \"\\t\\t> Assembling right Hand Side\" << std::endl;\n  lf::fe::ScalarLoadElementVectorProvider element_vector_provider(fe_space,\n                                                                  mf_load);\n  lf::assemble::AssembleVectorLocally(0, dofh, element_vector_provider, rhs);\n\n  // Enforce zero dirichlet boundary conditions\n  std::cout << \"\\t\\t> Enforcing Boundary Conditions\" << std::endl;\n  const auto boundary = lf::mesh::utils::flagEntitiesOnBoundary(mesh);\n  const auto selector = [&](unsigned int idx) -> std::pair<bool, double> {\n    const auto &entity = dofh.Entity(idx);\n    return {entity.Codim() > 0 && boundary(entity), 0};\n  };\n  lf::assemble::FixFlaggedSolutionComponents(selector, A_COO, rhs);\n\n  // Solve the LSE using the cholesky decomposition\n  std::cout << \"\\t\\t> Solving LSE\" << std::endl;\n  Eigen::SparseMatrix<double> A = A_COO.makeSparse();\n  Eigen::SimplicialLDLT<Eigen::SparseMatrix<double>> solver(A);\n  const Eigen::VectorXd solution = solver.solve(rhs);\n  const lf::fe::MeshFunctionFE<double, double> mf_numeric(fe_space, solution);\n  const lf::fe::MeshFunctionGradFE<double, double> mf_numeric_grad(fe_space,\n                                                                   solution);\n\n  // Compute the H1 and L2 errors\n  std::cout << \"\\t\\t> Computing Error Norms\" << std::endl;\n  auto qr_segment =\n      lf::quad::make_QuadRule(lf::base::RefEl::kSegment(), 2 * degree - 1);\n  auto qr_tria =\n      lf::quad::make_QuadRule(lf::base::RefEl::kTria(), 2 * degree - 1);\n  auto qr_quad =\n      lf::quad::make_QuadRule(lf::base::RefEl::kQuad(), 2 * degree - 1);\n  const auto quadrule_provider = [&](const lf::mesh::Entity &entity) {\n    const lf::base::RefEl refel = entity.RefEl();\n    switch (refel) {\n      case lf::base::RefEl::kTria():\n        return qr_tria;\n      case lf::base::RefEl::kSegment():\n        return qr_segment;\n      case lf::base::RefEl::kQuad():\n        return qr_quad;\n      default:\n        return lf::quad::make_QuadRule(refel, 2 * degree - 1);\n    }\n  };\n  const double H1_err = std::sqrt(lf::fe::IntegrateMeshFunction(\n      *mesh, lf::mesh::utils::squaredNorm(mf_u_grad - mf_numeric_grad),\n      quadrule_provider));\n  const double L2_err = std::sqrt(lf::fe::IntegrateMeshFunction(\n      *mesh, lf::mesh::utils::squaredNorm(mf_u - mf_numeric),\n      quadrule_provider));\n\n  // Return the errors\n  return {H1_err, L2_err};\n}\n\n/**\n * @brief Get the error of a test problem for the given mesh and FE space\n * @param degree The polynomial degree of the basis functions\n * @param mesh The mesh on which to solve the PDE\n * @param fe_space The Finite Element Space to use for the computation\n *\n * The test problem is formulated on [-1, 1]^2 \\ (]0, 1[x]-1, 0[) with Dirichlet\n boundary conditions and has the analytic solution\n * \\f[\n        u(r, \\phi) = r^{\\frac{2}{3}}\\sin(\\frac{2}{3}\\phi)\n   \\f]\n */\nstd::tuple<double, double> computeErrorsLDomain(\n    unsigned degree, const std::shared_ptr<lf::mesh::Mesh> &mesh,\n    const std::shared_ptr<const lf::fe::ScalarFESpace<double>> &fe_space) {\n  // The analytic solution\n  const auto u = [](const Eigen::Vector2d &x) -> double {\n    const double r = x.norm();\n    double phi = std::atan2(x[1], x[0]);\n    if (phi < 0) {\n      phi += 2 * M_PI;\n    }\n    return std::pow(r, 2. / 3) * std::sin(2. / 3 * phi);\n  };\n  lf::mesh::utils::MeshFunctionGlobal mf_u(u);\n  // The gradient of the analytic solution\n  const auto u_grad = [](const Eigen::Vector2d &x) -> Eigen::Vector2d {\n    const double r = x.norm();\n    double phi = std::atan2(x[1], x[0]);\n    if (phi < 0) {\n      phi += 2 * M_PI;\n    }\n    Eigen::Vector2d grad;\n    grad[0] = 2. / 3 * std::pow(r, -4. / 3) *\n              (x[0] * std::sin(2. / 3 * phi) - x[1] * std::cos(2. / 3 * phi));\n    grad[1] = 2. / 3 * std::pow(r, -4. / 3) *\n              (x[1] * std::sin(2. / 3 * phi) + x[0] * std::cos(2. / 3 * phi));\n    return grad;\n  };\n  lf::mesh::utils::MeshFunctionGlobal mf_u_grad(u_grad);\n\n  // Get a few useful variables\n  const lf::assemble::DofHandler &dofh = fe_space->LocGlobMap();\n\n  // Assemble the system matrix\n  std::cout << \"\\t\\t> Assembling System Matrix\" << std::endl;\n  const lf::mesh::utils::MeshFunctionConstant<double> mf_alpha(1);\n  lf::fe::DiffusionElementMatrixProvider element_matrix_provider(fe_space,\n                                                                 mf_alpha);\n  lf::assemble::COOMatrix<double> A_COO(dofh.NumDofs(), dofh.NumDofs());\n  lf::assemble::AssembleMatrixLocally(0, dofh, dofh, element_matrix_provider,\n                                      A_COO);\n\n  // The right hand side is zero because we have no load\n  Eigen::VectorXd rhs = Eigen::VectorXd::Zero(dofh.NumDofs());\n\n  // Enforce the dirichlet boundary conditions\n  std::cout << \"\\t\\t> Enforcing Boundary Conditions\" << std::endl;\n  const auto boundary = lf::mesh::utils::flagEntitiesOnBoundary(mesh);\n  Eigen::VectorXd boundary_dofs = Eigen::VectorXd::Zero(dofh.NumDofs());\n  for (const auto *const edge : mesh->Entities(1)) {\n    if (boundary(*edge)) {\n      const auto *const sfl = fe_space->ShapeFunctionLayout(*edge);\n      const auto eval_nodes = sfl->EvaluationNodes();\n      const Eigen::RowVectorXd nodal_values = Eigen::Map<Eigen::RowVectorXd>(\n          mf_u(*edge, eval_nodes).data(), eval_nodes.cols());\n      const Eigen::VectorXd locdofs = sfl->NodalValuesToDofs(nodal_values);\n      const auto dofidxs = dofh.GlobalDofIndices(*edge);\n      for (long i = 0; i < dofidxs.size(); ++i) {\n        boundary_dofs[dofidxs[i]] = locdofs[i];\n      }\n    }\n  }\n  const auto selector = [&](unsigned int idx) -> std::pair<bool, double> {\n    const lf::mesh::Entity &entity = dofh.Entity(idx);\n    return {entity.Codim() > 0 && boundary(entity), boundary_dofs[idx]};\n  };\n  lf::assemble::FixFlaggedSolutionComponents(selector, A_COO, rhs);\n\n  // Solve the LSE using Cholesky decomposition\n  std::cout << \"\\t\\t> Solving LSE\" << std::endl;\n  Eigen::SparseMatrix<double> A = A_COO.makeSparse();\n  Eigen::SimplicialLDLT<Eigen::SparseMatrix<double>> solver(A);\n  const Eigen::VectorXd solution = solver.solve(rhs);\n  const lf::fe::MeshFunctionFE<double, double> mf_numeric(fe_space, solution);\n  const lf::fe::MeshFunctionGradFE<double, double> mf_numeric_grad(fe_space,\n                                                                   solution);\n\n  // Compute the H1 and L2 errors\n  std::cout << \"\\t\\t> Computing Error Norms\" << std::endl;\n  auto qr_segment =\n      lf::quad::make_QuadRule(lf::base::RefEl::kSegment(), 2 * degree - 1);\n  auto qr_tria =\n      lf::quad::make_QuadRule(lf::base::RefEl::kTria(), 2 * degree - 1);\n  auto qr_quad =\n      lf::quad::make_QuadRule(lf::base::RefEl::kQuad(), 2 * degree - 1);\n  const auto quadrule_provider = [&](const lf::mesh::Entity &entity) {\n    const lf::base::RefEl refel = entity.RefEl();\n    switch (refel) {\n      case lf::base::RefEl::kTria():\n        return qr_tria;\n      case lf::base::RefEl::kSegment():\n        return qr_segment;\n      case lf::base::RefEl::kQuad():\n        return qr_quad;\n      default:\n        return lf::quad::make_QuadRule(refel, 2 * degree - 1);\n    }\n  };\n  const double H1_err = std::sqrt(lf::fe::IntegrateMeshFunction(\n      *mesh, lf::mesh::utils::squaredNorm(mf_u_grad - mf_numeric_grad),\n      quadrule_provider));\n  const double L2_err = std::sqrt(lf::fe::IntegrateMeshFunction(\n      *mesh, lf::mesh::utils::squaredNorm(mf_u - mf_numeric),\n      quadrule_provider));\n\n  // Return the errors\n  return {H1_err, L2_err};\n}\n\nint main(int argc, char *argv[]) {\n  po::options_description desc(\"Allowed options\");\n  desc.add_options()(\"output,o\", po::value<std::string>(),\n                     \"Name of the output file\")(\n      \"max_p,p\", po::value<unsigned>(), \"Maximum polynomial degree\");\n  po::variables_map vm;\n  po::store(po::parse_command_line(argc, argv, desc), vm);\n  if (vm.count(\"output\") == 0 || vm.count(\"max_p\") == 0) {\n    std::cout << desc << std::endl;\n    exit(1);\n  }\n  const std::string output_file = vm[\"output\"].as<std::string>();\n  const unsigned max_p = vm[\"max_p\"].as<unsigned>();\n\n  const std::filesystem::path here = __FILE__;\n  // Load the unit square mesh\n  const auto square_mesh = getSquareDomain();\n  // Load the L-shaped domain mesh\n  const auto L_mesh = getLDomain();\n\n  // Compute the errors for different polynomial degrees\n  Eigen::MatrixXd results(max_p, 7);\n  for (unsigned p = 1; p <= max_p; ++p) {\n    std::cout << \"> Polynomial Degree: \" << p << std::endl;\n\n    // Solve the problem on the unit square domain\n    std::cout << \"\\t> Unit Square Domain\";\n    const auto fe_space_square =\n        std::make_shared<lf::fe::HierarchicScalarFESpace<double>>(square_mesh,\n                                                                  p);\n    std::cout << \" (\" << fe_space_square->LocGlobMap().NumDofs() << \" DOFs)\"\n              << std::endl;\n    const auto [H1_square, L2_square] =\n        computeErrorsSquareDomain(p, square_mesh, fe_space_square);\n\n    // Solve the problem on the L-shaped domain\n    std::cout << \"\\t> L-shaped Domain\";\n    const auto fe_space_L =\n        std::make_shared<lf::fe::HierarchicScalarFESpace<double>>(L_mesh, p);\n    std::cout << \" (\" << fe_space_L->LocGlobMap().NumDofs() << \" DOFs)\"\n              << std::endl;\n    const auto [H1_L, L2_L] = computeErrorsLDomain(p, L_mesh, fe_space_L);\n\n    // Store the computed quantities in the results matrix\n    results(p - 1, 0) = p;\n    results(p - 1, 1) = fe_space_square->LocGlobMap().NumDofs();\n    results(p - 1, 2) = fe_space_L->LocGlobMap().NumDofs();\n    results(p - 1, 3) = H1_square;\n    results(p - 1, 4) = L2_square;\n    results(p - 1, 5) = H1_L;\n    results(p - 1, 6) = L2_L;\n  }\n\n  // Output the resulting errors to a file\n  const static Eigen::IOFormat CSVFormat(Eigen::StreamPrecision,\n                                         Eigen::DontAlignCols, \", \", \"\\n\");\n  std::ofstream file;\n  file.open(output_file);\n  file << results.format(CSVFormat);\n  file.close();\n\n  return 0;\n}\n", "meta": {"hexsha": "74fb22faadb8d70b6f9cd184c48dc3d02f6795d0", "size": 16058, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/lecturedemos/convergencestudies/prefinement.cc", "max_stars_repo_name": "Fytch/lehrfempp", "max_stars_repo_head_hexsha": "c804b3e350aa893180f1a02ce57a93b3d7686e91", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2018-08-30T19:55:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T16:38:06.000Z", "max_issues_repo_path": "examples/lecturedemos/convergencestudies/prefinement.cc", "max_issues_repo_name": "Fytch/lehrfempp", "max_issues_repo_head_hexsha": "c804b3e350aa893180f1a02ce57a93b3d7686e91", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 151.0, "max_issues_repo_issues_event_min_datetime": "2018-05-27T13:01:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-04T14:50:50.000Z", "max_forks_repo_path": "examples/lecturedemos/convergencestudies/prefinement.cc", "max_forks_repo_name": "Fytch/lehrfempp", "max_forks_repo_head_hexsha": "c804b3e350aa893180f1a02ce57a93b3d7686e91", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20.0, "max_forks_repo_forks_event_min_datetime": "2018-11-13T13:46:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T17:33:52.000Z", "avg_line_length": 39.649382716, "max_line_length": 80, "alphanum_fraction": 0.6379374766, "num_tokens": 4759, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321964553657, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.4861509901032311}}
{"text": "#include \"ETL/ETL.h\"\n\n#include <iostream>\n#include <string>\n#include <eigen3/Eigen/Dense>\n#include <boost/algorithm/string.hpp>\n#include <vector>\n\n\nint main(int argc, char *argv[]){\n    //Create object if ETL that will include 3 input args of ETL: input name, delimiter, flag\n    ETL etl(argv[1], argv[2], argv[3]);\n     \n    //Get data from CSV file using readCSV method **NOTE** we dont have a way of storing this data yet\n    std::vector<std::vector<std::string>> dataset = etl.readCSV();\n\n    int rows= dataset.size();\n    int cols= dataset[0].size();\n\n    Eigen::MatrixXd dataMat = etl.CSVtoEigen(dataset, rows, cols);\n\n    //Check data\n    std::cout << dataMat << std::endl;\n    return EXIT_SUCCESS;\n\n}", "meta": {"hexsha": "79c039343c23d3e667d1f28de6c4eaca69f804d3", "size": 708, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "KishenSharma6/IncomeClassifier", "max_stars_repo_head_hexsha": "d85b5a703d4db4072d0f2a5537244cde0d9f3fd7", "max_stars_repo_licenses": ["MIT"], "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": "KishenSharma6/IncomeClassifier", "max_issues_repo_head_hexsha": "d85b5a703d4db4072d0f2a5537244cde0d9f3fd7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-09-19T01:22:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-19T01:22:06.000Z", "max_forks_repo_path": "main.cpp", "max_forks_repo_name": "KishenSharma6/IncomeClassifier", "max_forks_repo_head_hexsha": "d85b5a703d4db4072d0f2a5537244cde0d9f3fd7", "max_forks_repo_licenses": ["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.2307692308, "max_line_length": 102, "alphanum_fraction": 0.6652542373, "num_tokens": 193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.7122321903471562, "lm_q1q2_score": 0.48615098593392775}}
{"text": "/*\nThe MIT License (MIT)\n\nCopyright (c) 2016 Alvaro Collet\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\nNeither name of this software nor the names of its contributors may be used to \nendorse or promote products derived from this software without specific\nprior written permission. \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// gmm_example.cpp : Defines the entry point for the console application.\n//\n\n#include \"stdafx.h\"\n#include \"gmm/gmm.h\" // Remember, you need to put the $(SolutionDir) in \"Additional Include Directories\"\n#include \"gmm/kmeans.h\"\n#include \"gmm/math_utils.h\"\n#include <Eigen/Core> // Remember, you need to put the path to Eigen in \"Additional Include Directories\"\n#include <Eigen/Geometry>\n\n///////////////////////////////////////////////////////////////////////////////\n// Basic test to show how to use KMeans \nbool TestKMeans3D() \n{\n    using namespace AC;\n\n    // Create some centroids\n    int numCentroids = 5;\n    std::vector<Vec3> centroids(numCentroids);\n    float scale = 10;\n    centroids[0] = Vec3(-scale, 0, 0);\n    centroids[1] = Vec3(0, -scale, 0);\n    centroids[2] = Vec3(0, 0, -scale);\n    centroids[3] = Vec3(scale, 0, 0);\n    centroids[4] = Vec3(0, scale, 0);\n\n    // Create some observations\n    int numObservationsPerCentroid = 100;\n    int numObservations = numObservationsPerCentroid * numCentroids;\n    std::default_random_engine generator;\n    std::uniform_real_distribution<double> distribution(-scale / 4, scale / 4);\n    std::vector<Vec3> observations(numObservations);\n    std::vector<int> assignmentsGT(numObservations);\n    auto noise = std::bind(distribution, generator);\n    Vec3 observation;\n    for (int k = 0; k < numCentroids; ++k) {\n        for (int i = 0; i < numObservationsPerCentroid; ++i) {\n            observations[numObservationsPerCentroid*k + i] = Vec3(centroids[k][0] + float(noise()), centroids[k][1] + float(noise()), centroids[k][2] + float(noise())); assignmentsGT[numObservationsPerCentroid*k + i] = k;\n        }\n    }\n\n    // Run kmeans\n    KMeans<Vec3> kmeans(numCentroids);\n    std::vector<int> assignmentsKMeans(numObservations);\n    kmeans.setMaxIterations(100);\n    kmeans.Process(observations, 30 /* restart 30 times with different initializations */, assignmentsKMeans);\n\n    // Compute average best distance between centroids and KMeans\n    double avgBestDistance = 0;\n    int assignment;\n    for (auto& centroidGT : centroids)\n        avgBestDistance += kmeans.ClosestCentroid(centroidGT, assignment);\n    avgBestDistance /= (int)centroids.size();\n\n    // Compute assignment differences between the ground truth and KMeans\n    int badAssignments = 0;\n    for (int i = 0; i < (int)assignmentsGT.size(); ++i) {\n        for (int j = i; j < (int)assignmentsGT.size(); ++j) {\n            if ((assignmentsGT[i] == assignmentsGT[j] && assignmentsKMeans[i] != assignmentsKMeans[j]) ||\n                (assignmentsGT[i] != assignmentsGT[j] && assignmentsKMeans[i] == assignmentsKMeans[j])) {\n                badAssignments++;\n            }\n        }\n    }\n    // Assignments are pairwise, so there is a total of N*(N-1)/2 possible bad assignments;\n    int maxAssignments = (int)assignmentsGT.size() * ((int)assignmentsGT.size() - 1) / 2;\n    // If centroids are within 10% distance of GT, and there are less than 10% assignment errors, declare success.\n    if (avgBestDistance < scale && badAssignments < (int)maxAssignments / 10)\n        return true;\n    else\n        return false;\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// Basic test for GMM. Create a noisy set of observations from a (known) multivariate gaussian distribution, fit GMM to it, and compare the differences in labeling. \nbool TestGMM3D()\n{\n    using namespace AC;\n\n    // Create some centroids\n    int numModes = 5;\n    std::vector<Vec3> centroids(numModes);\n    double scale = 10;\n    centroids[0] = Vec3(-scale, 0, 0);\n    centroids[1] = Vec3(0, -scale, 0);\n    centroids[2] = Vec3(0, 0, -scale);\n    centroids[3] = Vec3(scale, 0, 0);\n    centroids[4] = Vec3(0, scale, 0);\n\n    // Create some covariance matrices, and rotate and scale them\n    std::vector<Mat3> covariances(numModes);\n    covariances[0] = Vec3(1.0, 1.0, 1.0).asDiagonal() * Eigen::AngleAxisd(0.0, Vec3::UnitX());\n    covariances[1] = Vec3(2.0, 1.0, 0.5).asDiagonal() * Eigen::AngleAxisd(0.2, Vec3::UnitY()); \n    covariances[2] = Vec3(1.0, 2.0, 1.0).asDiagonal() * Eigen::AngleAxisd(0.4, Vec3::UnitZ());\n    covariances[3] = Vec3(1.0, 1.0, 2.0).asDiagonal() * Eigen::AngleAxisd(0.6, Vec3::UnitX());\n    covariances[4] = Vec3(0.75, 1.0, 0.75).asDiagonal() * Eigen::AngleAxisd(0.8, Vec3::UnitY());\n\n    // Create some observations\n    int numObservations = 100;\n    std::default_random_engine generator;\n    std::uniform_real_distribution<double> distribution(-scale / 4, scale / 4);\n    std::vector<Vec3> observations(numObservations * numModes);\n    std::vector<int> assignmentsGT(numObservations * numModes);\n    auto noise = std::bind(distribution, generator);\n    Vec3 observation;\n    for (int k = 0; k < numModes; ++k) {\n        for (int i = 0; i < numObservations; ++i) {\n            observations[numObservations*k + i] = covariances[k] * Vec3(centroids[k][0] + noise(), centroids[k][1] + noise(), centroids[k][2] + noise());\n            assignmentsGT[numObservations*k + i] = k;\n        }\n    }\n\n    // Run GMM\n    GMM::GMM3D gmm(numModes);\n    gmm.Process(observations);\n\n    // Compute hard assignments and probabilities\n    std::vector<int> assignmentsGMM(numObservations * numModes);\n    double avgProbability = 0;\n    AC::OnlineMean<double> avgLogProb;\n    for (int i = 0; i < (int)observations.size(); ++i) {\n        gmm.ClosestMode(observations[i], assignmentsGMM[i] /* output value */);\n        avgLogProb.Push(gmm.LogResponsibility(observations[i], assignmentsGMM[i]));\n    }\n    avgProbability = exp(avgLogProb.Mean());\n\n    // Compute assignment differences between the ground truth and KMeans\n    int badAssignments = 0;\n    for (int i = 0; i < (int)assignmentsGT.size(); ++i) {\n        for (int j = i; j < (int)assignmentsGT.size(); ++j) {\n            if ((assignmentsGT[i] == assignmentsGT[j] && assignmentsGMM[i] != assignmentsGMM[j]) ||\n                (assignmentsGT[i] != assignmentsGT[j] && assignmentsGMM[i] == assignmentsGMM[j])) {\n                badAssignments++;\n            }\n        }\n    }\n    // Assignments are pairwise, so there is a total of N*(N-1)/2 possible bad assignments;\n    int maxAssignments = (int)assignmentsGT.size() * ((int)assignmentsGT.size() - 1) / 2;\n    // If average point probability is larger than 0.9, and there are less than 10% assignment errors, declare success.\n    if (avgProbability > 0.9 && badAssignments < (int)maxAssignments / 10)\n        return true;\n    else\n        return false;\n}\n\n///////////////////////////////////////////////////////////////////////////////\nint main()\n{\n    bool isKMeansOK = TestKMeans3D();\n    bool isGMMOK = TestGMM3D();\n    return isKMeansOK && isGMMOK;\n}\n\n", "meta": {"hexsha": "42deef039313435331106d6ed0ee66e4c2455a86", "size": 7951, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gmm_example/gmm_example.cpp", "max_stars_repo_name": "alvarocollet/painless_gmm", "max_stars_repo_head_hexsha": "a1ddecc603d0348f82bd741b322795943b30f7c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2018-03-18T20:37:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-08T02:48:47.000Z", "max_issues_repo_path": "gmm_example/gmm_example.cpp", "max_issues_repo_name": "alvarocollet/painless_gmm", "max_issues_repo_head_hexsha": "a1ddecc603d0348f82bd741b322795943b30f7c1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gmm_example/gmm_example.cpp", "max_forks_repo_name": "alvarocollet/painless_gmm", "max_forks_repo_head_hexsha": "a1ddecc603d0348f82bd741b322795943b30f7c1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-07-22T12:02:17.000Z", "max_forks_repo_forks_event_max_datetime": "2017-07-22T12:02:17.000Z", "avg_line_length": 43.6868131868, "max_line_length": 221, "alphanum_fraction": 0.6543830965, "num_tokens": 2114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321720225278, "lm_q2_score": 0.6825737473266735, "lm_q1q2_score": 0.4861509826240327}}
{"text": "\n#include <stdio.h>\n#include <math.h>\n#include <stdlib.h>\n#include <string.h>\n#include <opencv2/opencv.hpp>\n\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <cmath>\n#include <map>\n#include <ctime>\n#include <sstream>\n#include <algorithm>\n#include <boost/thread/thread.hpp>\n#include <ros/ros.h>\n#include \"std_msgs/String.h\"\n#include <tf/transform_broadcaster.h>\n#include <geometry_msgs/PoseStamped.h>\n#include <geometry_msgs/Pose.h>\n#include <geometry_msgs/Point.h>\n#include <image_transport/image_transport.h>\n#include <cv_bridge/cv_bridge.h>\n\n#include \"math_helper.h\"\n#include \"string_convertor.h\"\n#include \"transformation2D.h\"\n\n#include \"wam_msgs/MatrixMN.h\"\n#include \"wam_srvs/JointMove.h\"\n#include \"sensor_msgs/JointState.h\"\n#include \"pose.h\"\n#include \"pbvs.h\"\n#include \"colormod.h\"\n\n//using namespace cv;\nusing namespace std;\nColor::Modifier c_red(Color::FG_RED);\nColor::Modifier c_yellow(Color::FG_YELLOW);\nColor::Modifier c_green(Color::FG_GREEN);\nColor::Modifier c_default(Color::FG_DEFAULT);\n\n\nint dofNum = 5;\nwam_srvs::JointMove mv_srv;\nros::ServiceClient Joint_move_client ;\ncv::Mat current_trans;\ncv::Mat current_rot;\n\ncv::Mat currentJacobian(6,dofNum,cv::DataType<double>::type);\nstd::vector<double> current_Joint_pose;\nbool ready_signal1 = false;\nbool ready_signal2 = false;\nbool ready_signal3 = false;\nbool lock = false;\n\ncv::Mat readTransformation()\n{\n  std::ifstream transform_file;\n  std::string transform_file_path = \"/home/chris/catkin_ws/src/long_range_teleoperation/robot-side/3_Calibration_Solver/result.txt\";\n  transform_file.open(transform_file_path.c_str(), std::ios_base::in | std::ios_base::binary);\n\n  if(!transform_file) {\n      std::cerr << \"Can't open transform file\" << std::endl;\n      std::exit(-1);\n  }\n  cv::Mat transformation(4,4,cv::DataType<double>::type);\n\n  std::string line;\n  int i = 0;\n  while(getline(transform_file, line) && i < 4) {\n      std::istringstream in(line);\n      double c1, c2, c3, c4;\n      in >> c1 >> c2 >> c3 >> c4;\n      transformation.at<double>(i,0) = c1;\n      transformation.at<double>(i,1) = c2;\n      transformation.at<double>(i,2) = c3;\n      transformation.at<double>(i,3) = c4;\n      ++i;\n  }\n\n  std::cout <<\"calibration solver result: \"<<endl<< transformation <<std::endl;\n  return transformation;\n}\n\n\n//scan along columns\nvoid wamToolJacobianCallback(const wam_msgs::MatrixMN::ConstPtr& jacobianMessage)\n{\n  for (int i = 0; i < 6; i++)\n  {\n\t  for (int j = 0; j < dofNum; j++)\n\t\t{\n       currentJacobian.at<double>(i,j)=jacobianMessage->data[i+j*6];\n       //currentJacobian.at<double>(i,1)=jacobianMessage->data[i+3*6];\n    }\n  }\n  ready_signal1=true;\n }\n\n void wamPoseCallback(const geometry_msgs::PoseStamped::ConstPtr& msg)\n {\n   //cout<<\"wam msgs\"<<endl;\n    geometry_msgs::Pose thisPose = msg->pose;\n    cv::Mat t(3,1,cv::DataType<double>::type);\n    cv::Mat R(3,3,cv::DataType<double>::type);\n\n    t.at<double>(0,0) = thisPose.position.x; t.at<double>(1,0) = thisPose.position.y; t.at<double>(2,0) = thisPose.position.z;\n\n    tf::Quaternion q(thisPose.orientation.x, thisPose.orientation.y , thisPose.orientation.z, thisPose.orientation.w);\n    tf::Matrix3x3 rMatrix(q);\n    for(int i=0;i<3;i++)\n      for(int j=0;j<3;j++)\n          R.at<double>(i,j)= rMatrix[i][j];\n    current_trans = t;\n    current_rot = R;\n    ready_signal2=true;\n    //cout<<\"pose callback\"<<endl;\n }\n\n void wamJointsCallback(const sensor_msgs::JointState::ConstPtr& msg)\n {\n    current_Joint_pose=msg->position;\n    //cout<<\"joint pose obtained:\"<<endl;//<<initial_Joint_pose[1]<<endl;\n     //cout<<initial_Joint_pose[0]<<\"  \"<<initial_Joint_pose[1]<<\"  \"<<initial_Joint_pose[2]<<\" \"<<initial_Joint_pose[3]<<\" \"<< initial_Joint_pose[4]\n    // <<\" \"<<initial_Joint_pose[5]<<\" \"<<initial_Joint_pose[6]<<endl;\n    ready_signal3=true;\n }\n\n //inStr \"0 0 0 0\"\n void moveRobotByQdot(cv::Mat qdot)\n {\n   lock=true;\n   std::vector<float> jnts;\n   for(size_t i=0;i<dofNum;i++)\n   {\n     float newJ = (float)(current_Joint_pose[i] + qdot.at<double>(i,0));\n     jnts.push_back(newJ);\n   }\n   jnts.push_back(current_Joint_pose[6]);\n   mv_srv.request.joints = jnts;\n   cout<<\"send to robot to the  position \"<<endl;\n   //string_convertor::printOutStdVector(jnts);\n   // cout << \"Press any key to continue...\" << endl;\n   // getchar();\n   Joint_move_client.call(mv_srv);///////////////////////////////////////////////////\n   //boost::this_thread::sleep( boost::posix_time::milliseconds(1000) );\n   lock=false;\n }\n\ndouble get_error(pose p, int mode)//mode=0, orientation;  mode=1, position\n{\n  if(mode == 1)\n    return math_helper::FrobeniusNorm(p.get_t());\n  else\n  {\n    double trR = cv::trace(p.get_R())[0];\n\n    return acos((trR-1)/2);\n  }\n}\n\ndouble error_convrge_thres(int mode)\n{\n  if(mode ==1)//position\n    return 0;\n  else\n    return 0.0001;\n}\n\ndouble error_thres(int mode)\n{\n  if(mode ==1)\n    return 0.01;\n  else\n    return 0.01;\n}\n\nvoid pbvsControl(cv::Mat _desired_trans_ed2b, cv::Mat _desired_rot_b2ed, int mode, double lamda)//mode=0, orientation;  mode=1, position\n{\n  //compute relative pose\n  pose relativePose = pbvs::getRelativePose(current_trans, current_rot, _desired_trans_ed2b, _desired_rot_b2ed);\n  //std::cout<<\"relative Pose\"<<endl<<relativePose<<endl;\n\n  //PBVS while loop\n  double error =get_error(relativePose, mode);\n  std::cout<<c_green<<\"error:  \"<<error<<c_default<<endl;\n  pbvs controller(lamda);\n  double error_converge = 999;\n  //getchar();\n  while(abs(error)>error_thres(mode)&&abs(error_converge)>error_convrge_thres(mode))//0.01\n  {\n    cv::Mat T = pose::getTransformationE2B(current_trans, current_rot);\n    std::cout<<\"transformation T:\"<<endl<<T<<endl;\n\n    cv::Mat qdot = controller.compute_qdot(currentJacobian, relativePose, T);\n    std::cout<<c_yellow<<\"qdot\"<<endl<<qdot * 57.2957795131<<c_default<<endl;\n    //normalize qdot.\n    //cv::Mat qdot_normalize = pbvs::normalize_qdot(qdot,10);\n    //std::cout<<c_yellow<<\"delta q\"<<endl<<qdot_normalize * 57.2957795131<<c_default<<endl;\n    std::cout <<c_green<< \"current_error: \" <<error<<\"   error_converge: \"<<error_converge<<c_default<< endl;\n    std::cout <<c_red<< \"command moving robot! Press any key to continue...\" <<c_default<< endl;\n    getchar();\n    //boost::this_thread::sleep( boost::posix_time::milliseconds(500) );\n    moveRobotByQdot(qdot);\n\n    //reset ready_signal\n    ready_signal1=false;ready_signal2=false;ready_signal3=false;\n    while(!ready_signal1 || !ready_signal2||!ready_signal3)\n    {\n      ros::spinOnce();\n      boost::this_thread::sleep( boost::posix_time::milliseconds(100) );\n    }\n\n    //update error\n    std::cout<<\"current pose\"<<endl<<current_trans<<endl<<current_rot<<endl;\n    relativePose = pbvs::getRelativePose(current_trans, current_rot, _desired_trans_ed2b, _desired_rot_b2ed);\n    //T = pose::getTransformationE2B(current_trans, current_rot);\n    double error_p =get_error(relativePose, mode);\n    cout<<\"error p \"<<error_p<<endl;\n    error_converge = error_p - error;\n    error = error_p;\n    std::cout <<c_green<< \"new_error: \" <<error<<\"   new error_converge: \"<<error_converge<<c_default<< endl;\n  }\n\n  cout<<\"task done, mode \"<<mode<<endl;\n  cout<<\"final error, \"<<error;\n}\n\n//===========================MAIN FUNCTION START===========================\n\nint main(int argc, char* argv[]){\n\n  double incremental = 0.1;\n  ros::init(argc, argv, \"pbvs\");\n  ros::NodeHandle nh;\n  ros::Subscriber subP = nh.subscribe(\"/zeus/wam/pose\", 1, wamPoseCallback);\n  ros::Subscriber jacobian_sub = nh.subscribe(\"zeus/wam/jacobian\",1,wamToolJacobianCallback);\n  ros::Subscriber wam_pos_sub=nh.subscribe(\"/zeus/wam/joint_states\",1,wamJointsCallback);\n  Joint_move_client = nh.serviceClient<wam_srvs::JointMove>(\"/zeus/wam/joint_move\");\n\n\n  while(!ready_signal1 || !ready_signal2||!ready_signal3)\n  {\n    ros::spinOnce();\n    boost::this_thread::sleep( boost::posix_time::milliseconds(100) );\n  }\n  std::cout<<\"current pose\"<<endl<<current_trans<<endl<<current_rot<<endl;\n  std::cout<<\"current Jocobian\"<<endl<<currentJacobian<<endl;\n  //getchar();\n  //set desired pose\n  cv::Mat desired_trans_ed2b=(cv::Mat_<double>(3,1) << -0.15,-0.74, 0.05) ;//current_trans + (cv::Mat_<double>(3,1) << 0.2,-0.2,-0.1);\n  std::cout<<c_green<<\"desired_trans_ed2b\"<<endl<<desired_trans_ed2b<<c_default<<endl;\n\n  cv::Mat testRot = (Mat_<double>(3,3)<<1.0000000,  0.0000000,  0.0000000,0.0000000,  0.8660254, -0.5000000,0.0000000,  0.5000000,  0.8660254 );\n  cv::Mat desired_rot_b2ed = current_rot*testRot;//(Mat_<double>(3,3) << 1, 0, 0, 0, 1, 0, 0, 0, 1);\n  std::cout<<c_red<<\"desired_rot_b2ed\"<<endl<<desired_rot_b2ed<<c_default<<endl;\n  getchar();\n  //firstly, do orientation change, keep position be fixed.\n  //pbvsControl(current_trans,desired_rot_b2ed,0, 0.8);\n  //then keep orientation and move the position.\n  pbvsControl(desired_trans_ed2b,current_rot,1,0.5);\n\n  ros::spin();\n    //declaration of function\n  ros::shutdown();\n  //Joint_move_client = nh.serviceClient<wam_srvs::JointMove>(\"/zeus/wam/joint_move\");\n//   cv::Mat C = (Mat_<double>(3,1) << -0.001665, -0.0163841, -0.4884146 );\n//   cv::Mat R = pose::getRotationMatrix(C);\n//\n//   cout<<\"rotation matrix: \"<<endl<<R<<endl;\n//   cv::Mat skewMotion = pose::getScrewRotation(R);\n//   cout<<\"screw motion vector: \"<<endl<<skewMotion<<endl;\n//   cv::Mat sm = math_helper::skewFromVect(0.1,0.2,0.3);\n//   cout<<\"screw sysmetric matrix: \"<<endl<<sm<<endl;\n  // ros::spinOnce();\n    //cv::namedWindow(\"view\");\n    //cv::startWindowThread();\n\n      //declaration of function\n  \t//cv::destroyWindow(\"view\");\n    return 0;\n}\n", "meta": {"hexsha": "9f3c04342cebb3dd3d032fb04348563f5e636a0a", "size": 9545, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Prev 5_Large_Motion_Control/src/main.cpp", "max_stars_repo_name": "atlas-jj/long-range-teleoperation-robot-side", "max_stars_repo_head_hexsha": "91ff5178da6b751f19d5daba48154e7704a686eb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Prev 5_Large_Motion_Control/src/main.cpp", "max_issues_repo_name": "atlas-jj/long-range-teleoperation-robot-side", "max_issues_repo_head_hexsha": "91ff5178da6b751f19d5daba48154e7704a686eb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Prev 5_Large_Motion_Control/src/main.cpp", "max_forks_repo_name": "atlas-jj/long-range-teleoperation-robot-side", "max_forks_repo_head_hexsha": "91ff5178da6b751f19d5daba48154e7704a686eb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-23T05:00:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-23T05:00:13.000Z", "avg_line_length": 33.4912280702, "max_line_length": 149, "alphanum_fraction": 0.6740701938, "num_tokens": 2852, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256631249076, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4861504187491067}}
{"text": "//==================================================================================================\n/*!\n  @file\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_GAMMALN_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_GAMMALN_HPP_INCLUDED\n\n#include <boost/simd/function/std.hpp>\n#include <boost/simd/arch/common/detail/generic/gammaln_kernel.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/nan.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/pi.hpp>\n#include <boost/simd/constant/two.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/function/abs.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/inc.hpp>\n#include <boost/simd/function/is_eqz.hpp>\n#include <boost/simd/function/log.hpp>\n#include <boost/simd/function/rec.hpp>\n#include <boost/simd/function/sinpi.hpp>\n#include <boost/simd/function/sqr.hpp>\n#include <boost/simd/detail/dispatch/function/overload.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 ( gammaln_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_< bd::single_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() (A0 a0) const BOOST_NOEXCEPT\n    {\n      A0 Maxgammaln = Constant<A0, 0x7bc3f8eaUL>(); //2.035093e36f\n      if ((a0 > Maxgammaln) || bs::is_eqz(a0) ) return bs::Inf<A0>();\n      A0 x = a0;\n      A0 q = bs::abs(x);\n      if( x < 0.0f )\n      {\n        if(q > Maxgammaln) return Nan<A0>();\n        A0 w = gammaln_pos(q);\n        A0 p =  bs::floor(q);\n        if (p == q) return bs::Inf<A0>();\n        A0 z = q - p;\n        if( z > bs::Half<A0>() )\n        {\n          p += bs::One<A0>();\n          z = p-q;\n        }\n        z = q*bs::sinpi(z);\n        if( bs::is_eqz(z) ) return bs::Inf<A0>();\n        return -bs::log(Invpi<A0>()*bs::abs(z))-w;\n      }\n      else\n      {\n        return gammaln_pos(x);\n      }\n    }\n  private:\n    static /*BOOST_FORCEINLINE*/ A0 gammaln_pos(A0 x) BOOST_NOEXCEPT\n    {\n      if( x < 6.5f )\n      {\n        A0 z = One<A0>();\n        A0 tx = x;\n        A0 nx = Zero<A0>();\n        if( x >= 1.5f )\n        {\n          while( tx > 2.5f )\n          {\n            nx = dec(nx);\n            tx = x + nx;\n            z *=tx;\n          }\n          x += nx - Two<A0>();\n          A0 p = x * detail::gammaln_kernel<A0>::gammalnB(x);\n          return p+bs::log(z);\n\n        }\n        if( x >= 1.25f )\n        {\n          z *= x;\n          x =  dec(x);\n          A0 p = x *  detail::gammaln_kernel<A0>::gammalnB(x);\n          return p-bs::log(z);\n        }\n        if( x >= 0.75f )\n        {\n          x = dec(x); //-= 1.0f;\n          return x * detail::gammaln_kernel<A0>::gammalnC(x);\n        }\n        while( tx < 1.5f )\n        {\n          if(is_eqz(tx) ) return Inf<A0>();\n          z *=tx;\n          nx = inc(nx);\n          tx = x + nx;\n        }\n        x += nx - Two<A0>();\n        A0 p = x *  detail::gammaln_kernel<A0>::gammalnB(x);\n        return p-log(z);\n      }\n      A0 q = fma(( x - 0.5f ), bs::log(x), Logsqrt2pi<A0>() - x);\n      if( x <= 1.0e4f )\n      {\n        A0 z = rec(x);\n        A0 p = sqr(z);\n        q = fma(z, detail::gammaln_kernel<A0>::gammaln2(p), q);\n      }\n      return q;\n    }\n  };\n  BOOST_DISPATCH_OVERLOAD ( gammaln_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_< bd::double_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() (A0 a0) const BOOST_NOEXCEPT\n    {\n      A0 Maxgammaln = Constant<A0, 0x7f574c5dd06d2516ULL>();\n      if ((a0 == bs::Inf<A0>()) || bs::is_eqz(a0) ) return bs::Inf<A0>(); //2.556348e305\n      A0 x = a0;\n      A0 q = bs::abs(x);\n      if(x > Maxgammaln) return Inf<A0>();\n      if( x < -34.0 )\n      {\n        if(q > Maxgammaln) return Nan<A0>();\n        A0 w = gammaln_pos(q);\n        A0 p =  bs::floor(q);\n        if (p == q) return bs::Inf<A0>();\n        A0 z = q - p;\n        if( z > bs::Half<A0>() )\n        {\n          p += bs::One<A0>();\n          z = p-q;\n        }\n        z = q*bs::sinpi(z);\n        if( bs::is_eqz(z) ) return bs::Inf<A0>();\n        return Logpi<A0>()-bs::log(z)-w;\n      }\n      else\n      {\n        return gammaln_pos(x);\n      }\n    }\n  private:\n    static /*BOOST_FORCEINLINE*/ A0 gammaln_pos(A0 x) BOOST_NOEXCEPT\n    {\n      if( x < 13.0 )\n      {\n        A0 z = One<A0>();\n        A0 p = Zero<A0>();\n        A0 u = x;\n        while( u >= 3.0 )\n        {\n          p -= 1.0;\n          u = x + p;\n          z *= u;\n        }\n        while( u < 2.0 )\n        {\n          if( u == 0.0 )  return Inf<A0>();\n          z /= u;\n          p += 1.0;\n          u = x + p;\n        }\n        z = bs::abs(z);\n        if( u == 2.0 ) return( bs::log(z) );\n        p -= 2.0;\n        x = x + p;\n        p = x * detail::gammaln_kernel<A0>::gammaln1(x);\n        return bs::log(z) + p ;\n      }\n      A0 q = fma(( x - 0.5 ), bs::log(x), Logsqrt2pi<A0>()-x);\n      if( x > 1.0e8 ) return q;\n\n      A0 p = rec(sqr(x));\n      q += detail::gammaln_kernel<A0>::gammalnA(p)/x;\n      return q;\n    }\n  };\n  BOOST_DISPATCH_OVERLOAD ( gammaln_\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&sgn) const BOOST_NOEXCEPT\n    {\n      sgn = signgam(a0);\n      return std::lgamma(a0);\n    }\n  };\n  BOOST_DISPATCH_OVERLOAD ( gammaln_\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::lgamma(a0);\n    }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "c0265f3c05a08bcfaba459d93e478f2c41e33261", "size": 6556, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/scalar/function/gammaln.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/gammaln.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/gammaln.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": 28.7543859649, "max_line_length": 100, "alphanum_fraction": 0.4646125686, "num_tokens": 1963, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.841825655188238, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4861504141657168}}
{"text": "\n\n#include <NTL/ZZX.h>\n#include <NTL/BasicThreadPool.h>\n\n\nNTL_START_IMPL\n\n\n\n\nstruct NewFastCRTHelperScratch {\n   Vec<ZZ> tmp_vec;        // length == nlevels+1\n   ZZ tmp1, tmp2, tmp3;\n};\n\n\nstruct NewFastCRTHelper {\n\n   ZZ prod;\n   ZZ prod_half;\n   \n   long nprimes;\n\n   long nlevels;\n   long veclen;\n   long nblocks;   // number of nodes in the last level\n   long start_last_level;   // index of first item in last level\n\n   Vec<long> nprimes_vec;  // length == veclen\n   Vec<long> first_vec;    // length == nblocks\n   Vec<ZZ> prod_vec;       // length == veclen\n\n   Vec<long> coeff_vec;    // length == nprimes, coeff_vec[i] = (prod/p_i)^{-1} mod p_i\n\n   Vec<long> prime_vec;   // length == nprimes\n   Vec<const sp_ZZ_reduce_struct*> red_struct_vec; // length == nprimes\n   Vec<mulmod_precon_t> coeffpinv_vec; // length == nprimes\n   Vec<ZZVec> ppvec;       // length == nblocks\n   \n   long GetNumPrimes() const { return nprimes; }\n\n   NewFastCRTHelper(long bound); \n\n   void fill_nprimes_vec(long index); \n   void fill_prod_vec(long index);\n\n   void reduce_aux(const ZZ& value, long *remainders, NewFastCRTHelperScratch& scratch,\n                   long index, long level) const;\n\n   void reconstruct_aux(ZZ& value, const long* remainders, NewFastCRTHelperScratch& scratch,\n                        long index, long level) const;\n\n\n   void reduce(const ZZ& value, long *remainders, NewFastCRTHelperScratch& scratch) const;\n   void reconstruct(ZZ& value, const long *remainders, NewFastCRTHelperScratch& scratch) const;\n\n   void init_scratch(NewFastCRTHelperScratch& scratch) const;\n\n};\n\nvoid NewFastCRTHelper::init_scratch(NewFastCRTHelperScratch& scratch) const\n{\n   scratch.tmp_vec.SetLength(nlevels+1);\n}\n\nvoid NewFastCRTHelper::fill_nprimes_vec(long index) \n{\n   long left, right;\n   left = 2*index + 1;\n   right = 2*index + 2;\n   if (left >= veclen) return;\n\n   nprimes_vec[left] = nprimes_vec[index]/2;\n   nprimes_vec[right] = nprimes_vec[index] - nprimes_vec[left];\n   fill_nprimes_vec(left);\n   fill_nprimes_vec(right);\n}\n\nvoid NewFastCRTHelper::fill_prod_vec(long index)\n{\n   long left, right;\n   left = 2*index + 1;\n   right = 2*index + 2;\n   if (left >= veclen) return;\n\n   fill_prod_vec(left);\n   fill_prod_vec(right);\n   mul(prod_vec[index], prod_vec[left], prod_vec[right]);\n}\n\nNewFastCRTHelper::NewFastCRTHelper(long bound) \n{\n   long thresh = 96;\n   bound += 2; // extra 2 bits ensures correct results\n\n   // assumes bound >= 1, thresh >= 1\n\n   prod = 1;\n   for (nprimes = 0; NumBits(prod) <= bound; nprimes++) {\n      UseFFTPrime(nprimes);\n      prod *= GetFFTPrime(nprimes);\n   }\n\n   RightShift(prod_half, prod, 1);\n\n   long sz = nprimes;\n   nlevels = 1;\n   while (sz > thresh) {\n      sz = sz/2;\n      nlevels++;\n   }\n\n   veclen = (1L << nlevels) - 1;\n   nblocks = 1L << (nlevels-1);\n   start_last_level = (1L << (nlevels-1)) - 1;\n\n   nprimes_vec.SetLength(veclen);\n   nprimes_vec[0] = nprimes;\n\n   fill_nprimes_vec(0);\n\n   first_vec.SetLength(nblocks+1);\n\n   first_vec[0] = 0;\n   for (long k = 1; k <= nblocks; k++)\n      first_vec[k] = first_vec[k-1] + nprimes_vec[start_last_level + k-1];\n\n   prod_vec.SetLength(veclen);\n\n   // fill product leaves\n   for (long k = 0; k < nblocks; k++) {\n      prod_vec[start_last_level + k] = 1;\n      for (long i = first_vec[k]; i < first_vec[k+1]; i++) {\n         prod_vec[start_last_level + k] *= GetFFTPrime(i);\n      }\n   }\n\n   // fill rest of product trees\n   fill_prod_vec(0);\n\n   ZZ t1;\n\n   coeff_vec.SetLength(nprimes);\n   prime_vec.SetLength(nprimes);\n   red_struct_vec.SetLength(nprimes);\n   coeffpinv_vec.SetLength(nprimes);\n\n   for (long i = 0; i < nprimes; i++) {\n      long p = GetFFTPrime(i);\n      div(t1, prod, p);\n      long tt = rem(t1, p);\n      tt = InvMod(tt, p);\n      coeff_vec[i] = tt;\n      prime_vec[i] = p;\n      red_struct_vec[i] = &GetFFT_ZZ_red_struct(i);\n      coeffpinv_vec[i] = PrepMulModPrecon(tt, p);\n   }\n\n   ppvec.SetLength(nblocks);\n   for (long k = 0; k < nblocks; k++) {\n      const ZZ& block_prod = prod_vec[start_last_level + k];\n      ppvec[k].SetSize(first_vec[k+1]-first_vec[k], block_prod.size());\n      for (long i = first_vec[k]; i < first_vec[k+1]; i++) {\n         div(t1, block_prod, prime_vec[i]);\n         ppvec[k][i-first_vec[k]] = t1;\n      }\n   }\n\n}\n\nvoid NewFastCRTHelper::reduce_aux(const ZZ& value, long *remainders, \n                                  NewFastCRTHelperScratch& scratch,\n                                  long index, long level) const\n{\n   long left, right;\n   left = 2*index + 1;\n   right = 2*index + 2;\n\n   ZZ& result = scratch.tmp_vec[level];\n\n   if (NumBits(value) <= NumBits(prod_vec[index]))\n      result = value;\n   else {\n      rem(scratch.tmp1, value, prod_vec[index]);\n      sub(scratch.tmp2, scratch.tmp1, prod_vec[index]);\n      if (NumBits(scratch.tmp2) < NumBits(scratch.tmp1))\n         result = scratch.tmp2;\n      else\n         result = scratch.tmp1;\n   }\n\n   if (left < veclen) {\n      reduce_aux(result, remainders, scratch, left, level+1);\n      reduce_aux(result, remainders, scratch, right, level+1);\n   }\n   else {\n      long k = index - start_last_level;\n      long i_begin = first_vec[k];\n      long i_end = first_vec[k+1];\n\n      for (long i = i_begin; i < i_end; i++) {\n         remainders[i] = red_struct_vec[i]->rem(result);\n      }\n   }\n}\n\nvoid NewFastCRTHelper::reduce(const ZZ& value, long *remainders, \n                              NewFastCRTHelperScratch& scratch) const\n{\n   reduce_aux(value, remainders, scratch, 0, 0);\n}\n\nvoid NewFastCRTHelper::reconstruct_aux(ZZ& value, const long* remainders, \n                                       NewFastCRTHelperScratch& scratch,\n                                       long index, long level) const\n{\n   long left, right;\n   left = 2*index + 1;\n   right = 2*index + 2;\n\n   if (left >= veclen) {\n      long k = index - start_last_level;\n      long i_begin = first_vec[k];\n      long i_end = first_vec[k+1];\n      const ZZ* ppv = ppvec[k].elts();\n      ZZ& acc = scratch.tmp1;\n\n      QuickAccumBegin(acc, prod_vec[index].size());\n      for (long i = i_begin; i < i_end; i++) {\n         long p = prime_vec[i];\n         long tt = coeff_vec[i];\n         mulmod_precon_t ttpinv = coeffpinv_vec[i];\n         long s = MulModPrecon(remainders[i], tt, p, ttpinv);\n         QuickAccumMulAdd(acc, ppv[i-i_begin], s);\n      }\n      QuickAccumEnd(acc);\n\n      value = acc;\n      return;\n   }\n\n   reconstruct_aux(scratch.tmp_vec[level], remainders, scratch, left, level+1);\n   reconstruct_aux(scratch.tmp1, remainders, scratch, right, level+1);\n\n   mul(scratch.tmp2, scratch.tmp_vec[level], prod_vec[right]);\n   mul(scratch.tmp3, scratch.tmp1, prod_vec[left]);\n   add(value, scratch.tmp2, scratch.tmp3);\n}\n\nvoid NewFastCRTHelper::reconstruct(ZZ& value, const long *remainders, \n                                   NewFastCRTHelperScratch& scratch) const\n{\n   reconstruct_aux(scratch.tmp1, remainders, scratch, 0, 0);\n   rem(scratch.tmp2, scratch.tmp1, prod);\n   if (scratch.tmp2 > prod_half)\n      sub(scratch.tmp2, scratch.tmp2, prod);\n\n   value = scratch.tmp2;\n}\n\n\n\n\n#define CRT_BLK (8)\n\nvoid HomMul(ZZX& x, const ZZX& a, const ZZX& b)\n{\n   if (&a == &b) {\n      HomSqr(x, a);\n      return;\n   }\n\n   long da = deg(a);\n   long db = deg(b);\n\n   if (da < 0 || db < 0) {\n      clear(x);\n      return;\n   }\n\n   long dc = da + db;\n\n   zz_pBak bak;\n   bak.save();\n\n   long bound = NumBits(min(da, db)+1) + MaxBits(a) + MaxBits(b);\n\n   NewFastCRTHelper H(bound);\n\n   long nprimes = H.GetNumPrimes();\n\n   if (NTL_OVERFLOW(nprimes, CRT_BLK, 0))\n      ResourceError(\"overflow\"); // this is pretty academic\n\n\n   Vec< zz_pX > A, B, C;\n\n   A.SetLength(nprimes);\n   for (long i = 0; i < nprimes; i++) A[i].SetLength(da+1);\n\n   NTL_EXEC_RANGE(da+1, first, last)\n   {\n      Vec<long> remainders_store;\n      remainders_store.SetLength(nprimes*CRT_BLK); \n      long *remainders = remainders_store.elts();\n\n      NewFastCRTHelperScratch scratch;\n      H.init_scratch(scratch);\n\n      long jj = first;\n      for (; jj <= last-CRT_BLK; jj += CRT_BLK) {\n\t for (long j = 0; j < CRT_BLK; j++) \n\t    H.reduce(a[jj+j], remainders + j*nprimes, scratch);\n         for (long i = 0; i < nprimes; i++) {\n            zz_p *Ai = A[i].rep.elts();\n            for (long j = 0; j < CRT_BLK; j++)\n               Ai[jj+j].LoopHole() = remainders[j*nprimes+i];\n         }\n      }\n      if (jj < last) {\n\t for (long j = 0; j < last-jj; j++) \n\t    H.reduce(a[jj+j], remainders + j*nprimes, scratch);\n\t for (long i = 0; i < nprimes; i++) {\n            zz_p *Ai = A[i].rep.elts();\n\t    for (long j = 0; j < last-jj; j++)\n\t       Ai[jj+j].LoopHole() = remainders[j*nprimes+i];\n\t }\n      }\n   }\n   NTL_EXEC_RANGE_END\n\n   B.SetLength(nprimes);\n   for (long i = 0; i < nprimes; i++) B[i].SetLength(db+1);\n\n   NTL_EXEC_RANGE(db+1, first, last)\n   {\n      Vec<long> remainders_store;\n      remainders_store.SetLength(nprimes*CRT_BLK); \n      long *remainders = remainders_store.elts();\n\n      NewFastCRTHelperScratch scratch;\n      H.init_scratch(scratch);\n\n      long jj = first;\n      for (; jj <= last-CRT_BLK; jj += CRT_BLK) {\n\t for (long j = 0; j < CRT_BLK; j++) \n\t    H.reduce(b[jj+j], remainders + j*nprimes, scratch);\n         for (long i = 0; i < nprimes; i++) {\n            zz_p *Bi = B[i].rep.elts();\n            for (long j = 0; j < CRT_BLK; j++)\n               Bi[jj+j].LoopHole() = remainders[j*nprimes+i];\n         }\n      }\n      if (jj < last) {\n\t for (long j = 0; j < last-jj; j++) \n\t    H.reduce(b[jj+j], remainders + j*nprimes, scratch);\n\t for (long i = 0; i < nprimes; i++) {\n            zz_p *Bi = B[i].rep.elts();\n\t    for (long j = 0; j < last-jj; j++)\n\t       Bi[jj+j].LoopHole() = remainders[j*nprimes+i];\n\t }\n      }\n   }\n   NTL_EXEC_RANGE_END\n         \n\n   C.SetLength(nprimes);\n   for (long i = 0; i < nprimes; i++) C[i].SetMaxLength(dc+1);\n\n   NTL_EXEC_RANGE(nprimes, first, last)\n   for (long i = first; i < last; i++) {\n      zz_p::FFTInit(i);\n      A[i].normalize();\n      B[i].normalize();\n      mul(C[i], A[i], B[i]);\n      long dci = deg(C[i]);\n      C[i].SetLength(dc+1);\n      if (dci < dc) {\n         zz_p *Ci = C[i].rep.elts();\n         for (long j = dci+1; j <= dc; j++) Ci[j] = 0;\n      }\n   }\n   NTL_EXEC_RANGE_END\n\n   ZZVec xx;\n   xx.SetSize(dc+1, (bound+NTL_ZZ_NBITS-1)/NTL_ZZ_NBITS);\n   // NOTE: we pre-allocate all the storage we\n   // need to collect the result.  Based on my experience,\n   // too many calls to malloc in a multi-threaded setting\n   // can lead to significant performance degredation\n\n   NTL_EXEC_RANGE(dc+1, first, last)\n   {\n      Vec<long> remainders_store;\n      remainders_store.SetLength(nprimes*CRT_BLK); \n      long *remainders = remainders_store.elts();\n\n      NewFastCRTHelperScratch scratch;\n      H.init_scratch(scratch);\n\n      long jj = first;\n      for (; jj <= last-CRT_BLK; jj += CRT_BLK) {\n         for (long i = 0; i < nprimes; i++) {\n            zz_p *Ci = C[i].rep.elts();\n            for (long j = 0; j < CRT_BLK; j++)\n               remainders[j*nprimes+i] = rep(Ci[jj+j]);\n         }\n\t for (long j = 0; j < CRT_BLK; j++) \n\t    H.reconstruct(xx[jj+j], remainders + j*nprimes, scratch);\n      }\n      if (jj < last) {\n\t for (long i = 0; i < nprimes; i++) {\n            zz_p *Ci = C[i].rep.elts();\n\t    for (long j = 0; j < last-jj; j++)\n               remainders[j*nprimes+i] = rep(Ci[jj+j]);\n\t }\n\t for (long j = 0; j < last-jj; j++) \n\t    H.reconstruct(xx[jj+j], remainders + j*nprimes, scratch);\n      }\n   }\n   NTL_EXEC_RANGE_END\n\n   x.SetLength(dc+1);\n   for (long j = 0; j <=dc; j++)\n      x[j] = xx[j];\n   x.normalize();\n}\n\nvoid HomSqr(ZZX& x, const ZZX& a)\n{\n   long da = deg(a);\n\n   if (da < 0) {\n      clear(x);\n      return;\n   }\n\n   long dc = da + da;\n\n   zz_pBak bak;\n   bak.save();\n\n   long bound = NumBits(da+1) + 2*MaxBits(a);\n\n   NewFastCRTHelper H(bound);\n\n   long nprimes = H.GetNumPrimes();\n\n   if (NTL_OVERFLOW(nprimes, CRT_BLK, 0))\n      ResourceError(\"overflow\"); // this is pretty academic\n\n\n   Vec< zz_pX > A, C;\n\n   A.SetLength(nprimes);\n   for (long i = 0; i < nprimes; i++) A[i].SetLength(da+1);\n\n   NTL_EXEC_RANGE(da+1, first, last)\n   {\n      Vec<long> remainders_store;\n      remainders_store.SetLength(nprimes*CRT_BLK); \n      long *remainders = remainders_store.elts();\n\n      NewFastCRTHelperScratch scratch;\n      H.init_scratch(scratch);\n\n      long jj = first;\n      for (; jj <= last-CRT_BLK; jj += CRT_BLK) {\n\t for (long j = 0; j < CRT_BLK; j++) \n\t    H.reduce(a[jj+j], remainders + j*nprimes, scratch);\n         for (long i = 0; i < nprimes; i++) {\n            zz_p *Ai = A[i].rep.elts();\n            for (long j = 0; j < CRT_BLK; j++)\n               Ai[jj+j].LoopHole() = remainders[j*nprimes+i];\n         }\n      }\n      if (jj < last) {\n\t for (long j = 0; j < last-jj; j++) \n\t    H.reduce(a[jj+j], remainders + j*nprimes, scratch);\n\t for (long i = 0; i < nprimes; i++) {\n            zz_p *Ai = A[i].rep.elts();\n\t    for (long j = 0; j < last-jj; j++)\n\t       Ai[jj+j].LoopHole() = remainders[j*nprimes+i];\n\t }\n      }\n   }\n   NTL_EXEC_RANGE_END\n\n\n   C.SetLength(nprimes);\n   for (long i = 0; i < nprimes; i++) C[i].SetMaxLength(dc+1);\n\n   NTL_EXEC_RANGE(nprimes, first, last)\n   for (long i = first; i < last; i++) {\n      zz_p::FFTInit(i);\n      A[i].normalize();\n      sqr(C[i], A[i]);\n      long dci = deg(C[i]);\n      C[i].SetLength(dc+1);\n      if (dci < dc) {\n         zz_p *Ci = C[i].rep.elts();\n         for (long j = dci+1; j <= dc; j++) Ci[j] = 0;\n      }\n   }\n   NTL_EXEC_RANGE_END\n\n   ZZVec xx;\n   xx.SetSize(dc+1, (bound+NTL_ZZ_NBITS-1)/NTL_ZZ_NBITS);\n   // NOTE: we pre-allocate all the storage we\n   // need to collect the result.  Based on my experience,\n   // too many calls to malloc in a multi-threaded setting\n   // can lead to significant performance degredation\n\n   NTL_EXEC_RANGE(dc+1, first, last)\n   {\n      Vec<long> remainders_store;\n      remainders_store.SetLength(nprimes*CRT_BLK); \n      long *remainders = remainders_store.elts();\n\n      NewFastCRTHelperScratch scratch;\n      H.init_scratch(scratch);\n\n      long jj = first;\n      for (; jj <= last-CRT_BLK; jj += CRT_BLK) {\n         for (long i = 0; i < nprimes; i++) {\n            zz_p *Ci = C[i].rep.elts();\n            for (long j = 0; j < CRT_BLK; j++)\n               remainders[j*nprimes+i] = rep(Ci[jj+j]);\n         }\n\t for (long j = 0; j < CRT_BLK; j++) \n\t    H.reconstruct(xx[jj+j], remainders + j*nprimes, scratch);\n      }\n      if (jj < last) {\n\t for (long i = 0; i < nprimes; i++) {\n            zz_p *Ci = C[i].rep.elts();\n\t    for (long j = 0; j < last-jj; j++)\n               remainders[j*nprimes+i] = rep(Ci[jj+j]);\n\t }\n\t for (long j = 0; j < last-jj; j++) \n\t    H.reconstruct(xx[jj+j], remainders + j*nprimes, scratch);\n      }\n   }\n   NTL_EXEC_RANGE_END\n\n   x.SetLength(dc+1);\n   for (long j = 0; j <=dc; j++)\n      x[j] = xx[j];\n   x.normalize();\n}\n\n\n\n\n\nstatic\nlong MaxSize(const ZZX& a)\n{\n   long res = 0;\n   long n = a.rep.length();\n\n   long i;\n   for (i = 0; i < n; i++) {\n      long t = a.rep[i].size();\n      if (t > res)\n         res = t;\n   }\n\n   return res;\n}\n\n\n\nvoid conv(zz_pX& x, const ZZX& a)\n{\n   conv(x.rep, a.rep);\n   x.normalize();\n}\n\n\nvoid conv(ZZX& x, const zz_pX& a)\n{\n   conv(x.rep, a.rep);\n   x.normalize();\n}\n\n\nlong CRT(ZZX& gg, ZZ& a, const zz_pX& G)\n{\n   long n = gg.rep.length();\n\n   long p = zz_p::modulus();\n\n   ZZ new_a;\n   mul(new_a, a, p);\n\n   long a_inv;\n   a_inv = rem(a, p);\n   a_inv = InvMod(a_inv, p);\n\n   long p1;\n   p1 = p >> 1;\n\n   ZZ a1;\n   RightShift(a1, a, 1);\n\n   long p_odd = (p & 1);\n\n   long modified = 0;\n\n   long h;\n\n   long m = G.rep.length();\n\n   long max_mn = max(m, n);\n\n   gg.rep.SetLength(max_mn);\n\n   ZZ g;\n   long i;\n\n   for (i = 0; i < n; i++) {\n      if (!CRTInRange(gg.rep[i], a)) {\n         modified = 1;\n         rem(g, gg.rep[i], a);\n         if (g > a1) sub(g, g, a);\n      }\n      else\n         g = gg.rep[i];\n   \n      h = rem(g, p);\n\n      if (i < m)\n         h = SubMod(rep(G.rep[i]), h, p);\n      else\n         h = NegateMod(h, p);\n\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_odd && g > 0 && (h == p1))\n            MulSubFrom(g, a, h);\n         else\n            MulAddTo(g, a, h);\n      }\n\n      gg.rep[i] = g;\n   }\n\n\n   for (; i < m; i++) {\n      h = rep(G.rep[i]);\n      h = MulMod(h, a_inv, p);\n      if (h > p1)\n         h = h - p;\n   \n      modified = 1;\n      mul(g, a, h);\n      gg.rep[i] = g;\n   }\n\n   gg.normalize();\n   a = new_a;\n\n   return modified;\n}\n\nlong CRT(ZZX& gg, ZZ& a, const ZZ_pX& G)\n{\n   long n = gg.rep.length();\n\n   const ZZ& p = ZZ_p::modulus();\n\n   ZZ new_a;\n   mul(new_a, a, p);\n\n   ZZ a_inv;\n   rem(a_inv, a, p);\n   InvMod(a_inv, a_inv, p);\n\n   ZZ p1;\n   RightShift(p1, p, 1);\n\n   ZZ a1;\n   RightShift(a1, a, 1);\n\n   long p_odd = IsOdd(p);\n\n   long modified = 0;\n\n   ZZ h;\n   ZZ ah;\n\n   long m = G.rep.length();\n\n   long max_mn = max(m, n);\n\n   gg.rep.SetLength(max_mn);\n\n   ZZ g;\n   long i;\n\n   for (i = 0; i < n; i++) {\n      if (!CRTInRange(gg.rep[i], a)) {\n         modified = 1;\n         rem(g, gg.rep[i], a);\n         if (g > a1) sub(g, g, a);\n      }\n      else\n         g = gg.rep[i];\n   \n      rem(h, g, p);\n\n      if (i < m)\n         SubMod(h, rep(G.rep[i]), h, p);\n      else\n         NegateMod(h, h, p);\n\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         mul(ah, a, h);\n   \n         if (!p_odd && g > 0 && (h == p1))\n            sub(g, g, ah);\n         else\n            add(g, g, ah);\n      }\n\n      gg.rep[i] = g;\n   }\n\n\n   for (; i < m; i++) {\n      h = rep(G.rep[i]);\n      MulMod(h, h, a_inv, p);\n      if (h > p1)\n         sub(h, h, p);\n   \n      modified = 1;\n      mul(g, a, h);\n      gg.rep[i] = g;\n   }\n\n   gg.normalize();\n   a = new_a;\n\n   return modified;\n}\n\n\n#define SS_PAR_THRESH (2000.0)\n//#define SS_PAR_THRESH (10.0) \n// For testing\n\n\nstatic inline bool SS_BelowThresh(long n, long k)\n{\n   return double(n)*double(k) < SS_PAR_THRESH;\n}\n\n\nstatic void\nSS_AddMod(ZZ& x, const ZZ& a, const ZZ& b, const ZZ& p, long n)\n// x = a + b mod p, where p = 2^n+1,  a, b in [0, p).\n// x may not alias p.\n{\n#ifndef NTL_PROVIDES_SS_LIP_IMPL\n   add(x, a, b);\n   if (x >= p) {\n      x--; SwitchBit(x, n); // x -= p\n   }\n#else\n   SS_AddMod_lip_impl(x, a, b, p, n);\n#endif\n}\n\nstatic void\nSS_SubMod(ZZ& x, const ZZ& a, const ZZ& b, const ZZ& p, long n)\n// x = a - b mod p, where p = 2^n+1,  a, b in [0, p).\n// x may not alias b or p.\n{\n#ifndef NTL_PROVIDES_SS_LIP_IMPL\n   if (a < b) {\n      add(x, a, p);\n      SubPos(x, x, b);\n   }\n   else {\n      SubPos(x, a, b);\n   }\n#else\n   SS_SubMod_lip_impl(x, a, b, p, n);\n#endif\n}\n\n\n\n/* Compute a = b * 2^e mod p, where p = 2^n+1. 0<=e<n and 0<b<p are\n   assumed. */\n\nstatic void \nLeftRotate(ZZ& a, const ZZ& b, long e, const ZZ& p, long n, ZZ& scratch)\n{\n#ifndef NTL_PROVIDES_SS_LIP_IMPL\n  if (e == 0) {\n    if (&a != &b) {\n      a = b;\n    }\n    return;\n  }\n\n  /* scratch := upper e bits of b */\n  RightShift(scratch, b, n - e);\n  /* a := 2^e * lower n - e bits of b */\n  trunc(a, b, n - e);\n  LeftShift(a, a, e);\n  /* a -= scratch */\n  SS_SubMod(a, a, scratch, p, n);\n#else\n   LeftRotate_lip_impl(a, b, e, p, n, scratch);\n#endif\n}\n\n\n#define SS_FFT_THRESH (4)\n#define SS_NTEMPS (3)\n#define SS_FFT_RDUP (3)\n\nstatic long \nSS_FFTRoundUp(long xn, long k)\n// Assumes k >= 0.\n// Returns an integer m such that 1 <= m <= n = 2^k and \n// m divsisible my 2^SS_FFT_RDUP.\n// Also, if xn <= n, then m >= xn.\n{\n   long n = 1L << k;\n   if (xn <= 0) xn = 1;\n\n   xn = ((xn+((1L << SS_FFT_RDUP)-1)) >> SS_FFT_RDUP) << SS_FFT_RDUP; \n\n   if (xn > n - (n >> 4)) xn = n;\n\n   return xn;\n}\n\n\n\n// p = 2^n+1, where n = r*2^{l-1}, so 2^r is primitive 2^l-th root \n// of unity mod p.\n\n// j in [0, 2^{level-1})\n// a = b*2^{j*r*2^{l-level}}\nstatic void\nRotate(ZZ& a, const ZZ& b, long j, long level,\n       long r, long l, const ZZ& p, long n, ZZ* tmp)\n{\n   if (l-level >= 0) \n      LeftRotate(a, b, (j*r) << (l-level), p, n, tmp[0]);\n   else if (((j*r) & 1) == 0)\n      LeftRotate(a, b, (j*r) >> 1, p, n, tmp[0]);\n   else {\n      // use sqrt(2) = 2^{3n/4} - 2^{n/4}\n\n      long k = (j*r) >> 1; // j*r = 2*k + 1\n\n      // now compute a = b*2^{k+1/2} mod p\n\n      // a = b*{2^k} mod p\n      LeftRotate(a, b, k, p, n, tmp[0]);\n\n      // tmp[1] = a*2^{n/4} mod p\n      LeftRotate(tmp[1], a, n >> 2, p, n, tmp[0]);\n\n      // a = a*2^{3n/4} mod p\n      LeftRotate(a, a, 3*(n >> 2), p, n, tmp[0]);\n\n      // a -= tmp[1] mod p\n      SS_SubMod(a, a, tmp[1], p, n);\n   }\n}\n\n\nstatic void\nSS_butterfly(ZZ& x, ZZ& y, const ZZ& p, long n, ZZ* tmp)\n// (x, y) := (x+y, x-y)\n{\n  /* tmp[0] = x - y mod p */\n  SS_SubMod(tmp[0], x, y, p, n);\n\n  /* x += y mod p */\n  SS_AddMod(x, x, y, p, n);\n\n  y = tmp[0];\n}\n\nstatic void\nSS_fwd_butterfly(ZZ& x, ZZ& y, long j, long level, \n                long r, long l, const ZZ& p, long n, \n                ZZ* tmp)\n\n//         ( x, y ) *= ( 1  2^{j*r*2^{l-level}} )\n//                     ( 1 -2^{j*r*2^{l-level}} ) \n\n{\n  /* tmp[0] = x - y mod p */\n  SS_SubMod(tmp[0], x, y, p, n);\n\n  /* x += y mod p */\n  SS_AddMod(x, x, y, p, n);\n\n  /* y = tmp[0] * 2^{j*r*2^{l-level}} mod p */\n  Rotate(y, tmp[0], j, level, r, l, p, n, tmp+1);\n}\n\nstatic void\nSS_inv_butterfly(ZZ& x, ZZ& y, long j, long level, \n                long r, long l, const ZZ& p, long n, \n                ZZ* tmp)\n\n//         ( x, y ) *= ( 1                     1                    )\n//                     ( 2^{-j*r*2^{l-level}} -2^{-j*r*2^{l-level}} ) \n\n// *** should not be called with j == 0 \n//     call SS_butterfly instead\n\n{\n  /* tmp[0] = y * 2^{(2^{level-1}-j)*r*2^{l-level}} mod p */\n  Rotate(tmp[0], y, (1L<<(level-1))-j, level, r, l, p, n, tmp+1);\n\n  /* y = x + tmp[0] mod p */\n  SS_AddMod(y, x, tmp[0], p, n);  // NEGATED\n\n  /* x = x - tmp[0] mod p */\n  SS_SubMod(x, x, tmp[0], p, n);  // NEGATED\n}\n\n\n// Much of the following logic is taken from the code in FFT.cpp\n// for single-precision modular FFT's, which itself is adapted\n// from code originally written by David Harvey.\n// See copyright notice in FFT.cpp.\n\n// size == 2^level\nstatic void\nfft_layer(ZZ* xp, long blocks, long size, long level, long r, long l,\n          const ZZ& p, long n, ZZ* tmp)\n{\n   size /= 2;\n \n   do {\n      ZZ *xp0 = xp;\n      ZZ *xp1 = xp + size;\n\n      for (long j = 0; j < size; j++)\n         SS_fwd_butterfly(xp0[j], xp1[j], j, level, r, l, p, n, tmp);\n\n      xp += 2*size;\n   } while (--blocks != 0);\n}\n\nstatic void \nfft_base(ZZ* xp, long lgN, long r, long l, const ZZ& p, long n,\n         ZZ* tmp)\n{\n  long N = 1L << lgN;\n\n  for (long j = lgN, size = N, blocks = 1; \n       j >= 1; j--, blocks <<= 1, size >>= 1)\n    fft_layer(xp, blocks, size, j, r, l, p, n, tmp);\n}\n\n\nstatic void \nfft_rec(ZZ* xp, long lgN, long r, long l, const ZZ& p, long n,\n         ZZ* tmp)\n{\n   if (lgN <= SS_FFT_THRESH) {\n      fft_base(xp, lgN, r, l, p, n, tmp);\n      return;\n   }\n\n   long N = 1L << lgN;\n   long half = N >> 1;\n\n   ZZ *xp0 = xp;\n   ZZ *xp1 = xp + half;\n\n   for (long j = 0; j < half; j++) \n      SS_fwd_butterfly(xp0[j], xp1[j], j, lgN, r, l, p, n, tmp);\n\n   fft_rec(xp0, lgN-1, r, l, p, n, tmp);\n   fft_rec(xp1, lgN-1, r, l, p, n, tmp);\n}\n\n\nstatic void \nfft_short(ZZ* xp, long yn, long xn, long lgN, \n         long r, long l, const ZZ& p, long n,\n         ZZ* tmp, RecursiveThreadPool *pool)\n{\n  Vec<ZZ> alt_tmp;\n  if (!tmp) {\n    alt_tmp.SetLength(SS_NTEMPS);\n    tmp = &alt_tmp[0];\n  }\n\n  long N = 1L << lgN;\n\n  if (yn == N)\n    {\n      if (xn == N && lgN <= SS_FFT_THRESH)\n\t{\n\t  // no truncation\n\t  fft_base(xp, lgN, r, l, p, n, tmp);\n\t  return;\n\t}\n    }\n\n\n  // divide-and-conquer algorithm\n\n  long half = N >> 1;\n\n  if (yn <= half)\n    {\n      if (xn <= half)\n\t{\n\t  fft_short(xp, yn, xn, lgN-1, r, l, p, n, tmp, pool);\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++)\n\t    SS_AddMod(xp[j], xp[j], xp[j + half], p, n);\n\n\t  fft_short(xp, yn, half, lgN-1, r, l, p, n, tmp, pool);\n\t}\n    }\n  else\n    {\n      yn -= half;\n      \n      ZZ *xp0 = xp;\n      ZZ *xp1 = xp + half;\n\n      if (xn <= half)\n\t{\n\t  // X -> (X, w*X)\n\t  for (long j = 0; j < xn; j++)\n\t    Rotate(xp1[j], xp0[j], j, lgN, r, l, p, n, tmp);\n\n          \n          bool seq = SS_BelowThresh(half+yn, p.size());\n          NTL_EXEC_DIVIDE(seq, pool, helper, double(half)/double(half+yn),\n\t     fft_short(xp0, half, xn, lgN-1,  r, l, p, n, tmp, helper.subpool(0)),\n\t     fft_short(xp1, yn, xn, lgN-1, r, l, p, n, \n                       (helper.concurrent() ? 0 : tmp), helper.subpool(1)))\n\t}\n      else\n\t{\n\t  xn -= half;\n\n\t  // (X, Y) -> (X + Y, w*(X - Y))\n\t  for (long j = 0; j < xn; j++) \n            SS_fwd_butterfly(xp0[j], xp1[j], j, lgN, r, l, p, n, tmp);\n\n\t  // X -> (X, w*X)\n\t  for (long j = xn; j < half; j++)\n            Rotate(xp1[j], xp0[j], j, lgN, r, l, p, n, tmp);\n\n          bool seq = SS_BelowThresh(half+yn, p.size());\n          NTL_EXEC_DIVIDE(seq, pool, helper, double(half)/double(half+yn),\n\t     fft_short(xp0, half, half, lgN-1, r, l, p, n, tmp, helper.subpool(0)),\n\t     fft_short(xp1, yn, half, lgN-1, r, l, p, n, \n                       (helper.concurrent() ? 0 : tmp), helper.subpool(1)))\n\t}\n    }\n}\n\n\n\nstatic void \nfft(ZZVec& a, long r, long l, const ZZ& p, long n)\n{\n   ZZ tmp[SS_NTEMPS];\n   fft_rec(&a[0], l, r, l, p, n, &tmp[0]);\n}\n\nstatic void \nfft1(ZZVec& a, long r, long l, long l1, const ZZ& p, long n)\n{\n   ZZ tmp[SS_NTEMPS];\n   fft_rec(&a[0], l, r, l1, p, n, &tmp[0]);\n}\n\nstatic void \nfft_trunc(ZZVec& a, long yn, long xn, \n          long r, long l, long l1, const ZZ& p, long n)\n{\n   ZZ tmp[SS_NTEMPS];\n   fft_short(&a[0], yn, xn, l, r, l1, p, n, &tmp[0], NTL_INIT_DIVIDE);\n}\n\nstatic void \nfft_trunc_pair(ZZVec& a_0, ZZVec& a_1, long yn, long xn_0, long xn_1, \n          long r, long l, long l1, const ZZ& p, long n, \n          RecursiveThreadPool* pool)\n{\n   ZZ tmp_0[SS_NTEMPS];\n   ZZ tmp_1[SS_NTEMPS];\n   bool seq = SS_BelowThresh(yn, p.size());\n   NTL_EXEC_DIVIDE(seq, pool, helper, 0.5,\n     fft_short(&a_0[0], yn, xn_0, l, r, l1, p, n, &tmp_0[0], helper.subpool(0)),\n     fft_short(&a_1[0], yn, xn_1, l, r, l1, p, n, &tmp_1[0], helper.subpool(1)))\n}\n\nstatic void\nifft_layer(ZZ* xp, long blocks, long size, long level, long r, long l,\n          const ZZ& p, long n, ZZ* tmp)\n{\n   size /= 2;\n \n   do {\n      ZZ *xp0 = xp;\n      ZZ *xp1 = xp + size;\n\n      SS_butterfly(xp0[0], xp1[0], p, n, tmp);\n      for (long j = 1; j < size; j++)\n         SS_inv_butterfly(xp0[j], xp1[j], j, level, r, l, p, n, tmp);\n\n      xp += 2*size;\n   } while (--blocks != 0);\n}\n\nstatic void \nifft_base(ZZ* xp, long lgN, long r, long l, const ZZ& p, long n,\n         ZZ* tmp)\n{\n  long N = 1L << lgN;\n\n  for (long j = 1, size = 2, blocks = N/2; \n       j <= lgN; j++, blocks >>= 1, size <<= 1)\n    ifft_layer(xp, blocks, size, j, r, l, p, n, tmp);\n}\n\n\nstatic void \nifft_rec(ZZ* xp, long lgN, long r, long l, const ZZ& p, long n,\n         ZZ* tmp)\n{\n   if (lgN <= SS_FFT_THRESH) {\n      ifft_base(xp, lgN, r, l, p, n, tmp);\n      return;\n   }\n\n   long N = 1L << lgN;\n   long half = N >> 1;\n\n   ZZ *xp0 = xp;\n   ZZ *xp1 = xp + half;\n\n   ifft_rec(xp0, lgN-1, r, l, p, n, tmp);\n   ifft_rec(xp1, lgN-1, r, l, p, n, tmp);\n\n   SS_butterfly(xp0[0], xp1[0], p, n, tmp);\n   for (long j = 1; j < half; j++) \n      SS_inv_butterfly(xp0[j], xp1[j], j, lgN, r, l, p, n, tmp);\n}\n\nstatic void \nifft_short2(ZZ* xp, long yn, long lgN, \n           long r, long l, const ZZ& p, long n, ZZ* tmp, RecursiveThreadPool* pool);\n\nstatic void \nifft_short0(ZZ* xp, long lgN, \n           long r, long l, const ZZ& p, long n, ZZ* tmp, RecursiveThreadPool* pool)\n\n{\n  Vec<ZZ> alt_tmp;\n  if (!tmp) {\n    alt_tmp.SetLength(SS_NTEMPS);\n    tmp = &alt_tmp[0];\n  }\n\n\n  long N = 1L << lgN;\n\n  if (lgN <= SS_FFT_THRESH)\n    {\n      // no truncation\n      ifft_base(xp, lgN, r, l, p, n, tmp);\n      return;\n    }\n\n  // divide-and-conquer algorithm\n\n  long half = N >> 1;\n\n  ZZ *xp0 = xp;\n  ZZ *xp1 = xp + half;\n\n  bool seq = SS_BelowThresh(N, p.size());\n  NTL_EXEC_DIVIDE(seq, pool, helper, 0.5,\n     ifft_short0(xp0, lgN-1, r, l, p, n, tmp, helper.subpool(0)),\n     ifft_short0(xp1, lgN-1, r, l, p, n, \n                 (helper.concurrent() ? 0 : tmp), helper.subpool(1)))\n\n  // (X, Y) -> (X + Y/w, X - Y/w)\n  SS_butterfly(xp0[0], xp1[0], p, n, tmp);\n  for (long j = 1; j < half; j++) \n    SS_inv_butterfly(xp0[j], xp1[j], j, lgN, r, l, p, n, tmp);\n}\n\nstatic void \nifft_short1(ZZ* xp, long yn, long lgN, \n           long r, long l, const ZZ& p, long n, ZZ* tmp, RecursiveThreadPool* pool)\n\n{\n  long N = 1L << lgN;\n\n  if (yn == N) {\n    // no truncation\n    ifft_short0(xp, lgN, r, l, p, n, tmp, pool);\n    return;\n  }\n\n  // divide-and-conquer algorithm\n\n  long half = N >> 1;\n\n  if (yn <= half)\n    {\n      // X -> 2X\n      for (long j = 0; j < yn; j++)\n      \tSS_AddMod(xp[j], xp[j], xp[j], p, n);\n\n      ifft_short1(xp, yn, lgN-1, r, l, p, n, tmp, pool);\n    }\n  else\n    {\n      ZZ *xp0 = xp;\n      ZZ *xp1 = xp + half;\n\n      ifft_short0(xp0, lgN-1, r, l, p, n, tmp, pool);\n\n      yn -= half;\n\n      // X -> (2X, w*X)\n      for (long j = yn; j < half; j++)\n\t{\n\t  tmp[0] = xp0[j];\n          SS_AddMod(xp0[j], xp0[j], xp0[j], p, n);\n          Rotate(xp1[j], tmp[0], j, lgN, r, l, p, n, tmp+1);\n\t}\n\n      ifft_short2(xp1, yn, lgN-1, r, l, p, n, tmp, pool);\n\n      // (X, Y) -> (X + Y/w, X - Y/w)\n      SS_butterfly(xp0[0], xp1[0], p, n, tmp);\n      for (long j = 1; j < yn; j++) \n        SS_inv_butterfly(xp0[j], xp1[j], j, lgN, r, l, p, n, tmp);\n    }\n}\n\n\nstatic void \nifft_short2(ZZ* xp, long yn, long lgN, \n           long r, long l, const ZZ& p, long n, ZZ* tmp, RecursiveThreadPool* pool)\n\n{\n  long N = 1L << lgN;\n\n  if (yn == N) {\n    // no truncation\n    ifft_short0(xp, lgN, r, l, p, n, tmp, pool);\n    return;\n  }\n\n  // divide-and-conquer algorithm\n\n  long half = N >> 1;\n\n  if (yn <= half)\n    {\n      // X -> 2X\n      for (long j = 0; j < yn; j++)\n      \tSS_AddMod(xp[j], xp[j], xp[j], p, n);\n\n      // (X, Y) -> X + Y\n      for (long j = yn; j < half; j++)\n\tSS_AddMod(xp[j], xp[j], xp[j + half], p, n);\n\n      ifft_short2(xp, yn, lgN-1, r, l, p, n, tmp, pool);\n\n      // (X, Y) -> X - Y\n      for (long j = 0; j < yn; j++)\n\tSS_SubMod(xp[j], xp[j], xp[j + half], p, n);\n    }\n  else\n    {\n      ZZ *xp0 = xp;\n      ZZ *xp1 = xp + half;\n\n      ifft_short0(xp0, lgN-1, r, l, p, n, tmp, pool);\n\n      yn -= half;\n\n      // (X, Y) -> (2X - Y, w*(X - Y))\n      for (long j = yn; j < half; j++)\n\t{\n          SS_SubMod(tmp[0], xp0[j], xp1[j], p, n);\n          SS_AddMod(xp0[j], xp0[j], tmp[0], p, n);\n          Rotate(xp1[j], tmp[0], j, lgN, r, l, p, n, tmp+1);\n\t}\n\n\n      ifft_short2(xp1, yn, lgN-1, r, l, p, n, tmp, pool);\n\n      // (X, Y) -> (X + Y/w, X - Y/w)\n      SS_butterfly(xp0[0], xp1[0], p, n, tmp);\n      for (long j = 1; j < yn; j++) \n        SS_inv_butterfly(xp0[j], xp1[j], j, lgN, r, l, p, n, tmp);\n    }\n}\n\n\nstatic void \nifft(ZZVec& a, long r, long l, const ZZ& p, long n)\n{\n   ZZ tmp[SS_NTEMPS];\n   ifft_rec(&a[0], l, r, l, p, n, &tmp[0]);\n}\n\nstatic void \nifft1(ZZVec& a, long r, long l, long l1, const ZZ& p, long n)\n{\n   ZZ tmp[SS_NTEMPS];\n   ifft_rec(&a[0], l, r, l1, p, n, &tmp[0]);\n}\n\nstatic void \nifft_trunc(ZZVec& a, long yn, long r, long l, long l1, const ZZ& p, long n)\n{\n   ZZ tmp[SS_NTEMPS];\n   ifft_short1(&a[0], yn, l, r, l1, p, n, &tmp[0], NTL_INIT_DIVIDE);\n}\n\n\n\n\n\n/* Multiplication a la Schoenhage & Strassen, modulo a \"Fermat\" number\n   p = 2^{mr}+1, where m is a power of two and r is odd. Then w = 2^r\n   is a primitive 2mth root of unity, i.e., polynomials whose product\n   has degree less than 2m can be multiplied, provided that the\n   coefficients of the product polynomial are at most 2^{mr-1} in\n   absolute value. The algorithm is not called recursively;\n   coefficient arithmetic is done directly.*/\n\n// The original version of SSMUl was written by Juergen Gerhard.\n// However, it has been almost completely re-written so as\n// to provide the following improvements:\n//   * uses truncated FFT and Inverse FFT algorithms,\n//     for better performance between powers of 2\n//   * better cache locality because of divide and conquer structure\n//   * better performance because of sqrt(2) trick\n\nvoid SSMul(ZZX& c, const ZZX& a, const ZZX& b)\n{\n  if (&a == &b) {\n    SSSqr(c, a);\n    return;\n  }\n\n  long na = deg(a);\n  long nb = deg(b);\n\n  if (na <= 0 || nb <= 0) {\n    PlainMul(c, a, b);\n    return;\n  }\n\n  long n = na + nb; /* degree of the product */\n\n\n  /* Choose m and r suitably */\n  long l = NextPowerOfTwo(n + 1) - 1; /* 2^l <= n < 2^{l+1} */\n  long N = 1L << (l + 1); /* N = 2^{l+1} */\n  /* Bitlength of the product: if the coefficients of a are absolutely less\n     than 2^ka and the coefficients of b are absolutely less than 2^kb, then\n     the coefficients of ab are absolutely less than\n     (min(na,nb)+1)2^{ka+kb} <= 2^bound. */\n  long bound = 2 + NumBits(min(na, nb)) + MaxBits(a) + MaxBits(b);\n  /* Let r be minimal so that mr > bound */\n  long r = (bound >> l) + 1;\n  long mr = r << l;\n\n  // sqrt(2) trick\n  long l1 = l;\n  if (l1 >= 3) {\n    long alt_l1 = l-1;\n    long alt_r = (bound >> alt_l1) + 1;\n    long alt_mr = alt_r << alt_l1;\n\n    if (alt_mr < mr - mr/8) {\n      l1 = alt_l1;\n      r = alt_r;\n      mr = alt_mr;\n    }\n  }\n\n  /* p := 2^{mr}+1 */\n  ZZ p;\n  set(p);\n  LeftShift(p, p, mr);\n  add(p, p, 1);\n\n  /* Make coefficients of a and b positive */\n  ZZVec aa, bb;\n  aa.SetSize(N, p.size());\n  bb.SetSize(N, p.size());\n\n  for (long i = 0; i <= deg(a); i++) {\n    if (sign(a.rep[i]) >= 0) {\n      aa[i] = a.rep[i];\n    } else {\n      add(aa[i], a.rep[i], p);\n    }\n  }\n\n  for (long i = 0; i <= deg(b); i++) {\n    if (sign(b.rep[i]) >= 0) {\n      bb[i] = b.rep[i];\n    } else {\n      add(bb[i], b.rep[i], p);\n    }\n  }\n\n  long yn = SS_FFTRoundUp(n+1, l+1);\n\n  /* N-point FFT's mod p */\n  fft_trunc_pair(aa, bb, yn, SS_FFTRoundUp(na+1, l+1), SS_FFTRoundUp(nb+1, l+1),\n                 r, l+1, l1+1, p, mr, NTL_INIT_DIVIDE);\n  //fft_trunc(aa, yn, SS_FFTRoundUp(na+1, l+1), r, l+1, l1+1, p, mr);\n  //fft_trunc(bb, yn, SS_FFTRoundUp(nb+1, l+1), r, l+1, l1+1, p, mr);\n\n\n  /* Pointwise multiplication aa := aa * bb mod p */\n  bool seq = SS_BelowThresh(yn, p.size());\n  NTL_GEXEC_RANGE(seq, yn, first, last)\n  ZZ tmp, ai;\n  for (long i = first; i < last; i++) {\n    mul(ai, aa[i], bb[i]);\n    if (NumBits(ai) > mr) {\n      RightShift(tmp, ai, mr);\n      trunc(ai, ai, mr);\n      sub(ai, ai, tmp);\n      if (sign(ai) < 0) {\n        add(ai, ai, p);\n      }\n    }\n    aa[i] = ai;\n  }\n  NTL_GEXEC_RANGE_END\n\n  ifft_trunc(aa, yn, r, l+1, l1+1, p, mr);\n\n  /* Retrieve c, dividing by N, and subtracting p where necessary */\n\n  c.rep.SetLength(n + 1);\n  ZZ ai, tmp, scratch;\n  for (long i = 0; i <= n; i++) {\n    ai = aa[i];\n    ZZ& ci = c.rep[i];\n    if (!IsZero(ai)) {\n      /* ci = -ai * 2^{mr-l-1} = ai * 2^{-l-1} = ai / N mod p */\n      LeftRotate(ai, ai, mr - l - 1, p, mr, scratch);\n      sub(tmp, p, ai);\n      if (NumBits(tmp) >= mr) { /* ci >= (p-1)/2 */\n        negate(ci, ai); /* ci = -ai = ci - p */\n      }\n      else\n        ci = tmp;\n    } \n    else\n       clear(ci);\n  }\n}\n\nvoid SSMul(ZZ_pX& c, const ZZ_pX& a, const ZZ_pX& b)\n{\n  if (&a == &b) {\n    SSSqr(c, a);\n    return;\n  }\n\n  long na = deg(a);\n  long nb = deg(b);\n\n  if (na <= 0 || nb <= 0) {\n    PlainMul(c, a, b);\n    return;\n  }\n\n  long n = na + nb; /* degree of the product */\n\n\n  /* Choose m and r suitably */\n  long l = NextPowerOfTwo(n + 1) - 1; /* 2^l <= n < 2^{l+1} */\n  long N = 1L << (l + 1); /* N = 2^{l+1} */\n  /* Bitlength of the product: if the coefficients of a are absolutely less\n     than 2^ka and the coefficients of b are absolutely less than 2^kb, then\n     the coefficients of ab are absolutely less than\n     (min(na,nb)+1)2^{ka+kb} <= 2^bound. */\n  long bound = 2 + NumBits(min(na, nb)) + 2*NumBits(ZZ_p::modulus());\n  /* Let r be minimal so that mr > bound */\n  long r = (bound >> l) + 1;\n  long mr = r << l;\n\n  // sqrt(2) trick\n  long l1 = l;\n  if (l1 >= 3) {\n    long alt_l1 = l-1;\n    long alt_r = (bound >> alt_l1) + 1;\n    long alt_mr = alt_r << alt_l1;\n\n    if (alt_mr < mr - mr/8) {\n      l1 = alt_l1;\n      r = alt_r;\n      mr = alt_mr;\n    }\n  }\n\n  /* p := 2^{mr}+1 */\n  ZZ p;\n  set(p);\n  LeftShift(p, p, mr);\n  add(p, p, 1);\n\n  ZZVec aa, bb;\n  aa.SetSize(N, p.size());\n  bb.SetSize(N, p.size());\n\n  for (long i = 0; i <= deg(a); i++) {\n      aa[i] = rep(a.rep[i]);\n  }\n\n  for (long i = 0; i <= deg(b); i++) {\n    bb[i] = rep(b.rep[i]);\n  }\n\n  long yn = SS_FFTRoundUp(n+1, l+1);\n\n  /* N-point FFT's mod p */\n  fft_trunc_pair(aa, bb, yn, SS_FFTRoundUp(na+1, l+1), SS_FFTRoundUp(nb+1, l+1),\n                 r, l+1, l1+1, p, mr, NTL_INIT_DIVIDE);\n  //fft_trunc(aa, yn, SS_FFTRoundUp(na+1, l+1), r, l+1, l1+1, p, mr);\n  //fft_trunc(bb, yn, SS_FFTRoundUp(nb+1, l+1), r, l+1, l1+1, p, mr);\n\n\n  /* Pointwise multiplication aa := aa * bb mod p */\n  bool seq = SS_BelowThresh(yn, p.size());\n  NTL_GEXEC_RANGE(seq, yn, first, last)\n  ZZ tmp, ai;\n  for (long i = first; i < last; i++) {\n    mul(ai, aa[i], bb[i]);\n    if (NumBits(ai) > mr) {\n      RightShift(tmp, ai, mr);\n      trunc(ai, ai, mr);\n      sub(ai, ai, tmp);\n      if (sign(ai) < 0) {\n        add(ai, ai, p);\n      }\n    }\n    aa[i] = ai;\n  }\n  NTL_GEXEC_RANGE_END\n\n  ifft_trunc(aa, yn, r, l+1, l1+1, p, mr);\n\n  /* Retrieve c, dividing by N, and subtracting p where necessary */\n\n  c.rep.SetLength(n+1);\n  bool seq1 = SS_BelowThresh(n+1, p.size());\n  ZZ_pContext context;\n  context.save();\n  NTL_GEXEC_RANGE(seq1, n+1, first, last)\n  context.restore();\n  ZZ ai, tmp, scratch;\n  for (long i = first; i < last; i++) {\n    ai = aa[i];\n    ZZ_p& ci = c.rep[i];\n    if (!IsZero(ai)) {\n      /* ci = -ai * 2^{mr-l-1} = ai * 2^{-l-1} = ai / N mod p */\n      LeftRotate(ai, ai, mr - l - 1, p, mr, scratch);\n      sub(tmp, p, ai);\n      conv(ci, tmp);\n    } \n    else\n       clear(ci);\n  }\n  NTL_GEXEC_RANGE_END\n\n  c.normalize();\n}\n\n\n\n// SSRatio computes how much bigger the SS modulus must be\n// to accomodate the necessary roots of unity.\n// This is useful in determining algorithm crossover points.\n\ndouble SSRatio(long na, long maxa, long nb, long maxb)\n{\n  if (na <= 0 || nb <= 0) return 0;\n\n  long n = na + nb; /* degree of the product */\n\n\n  long l = NextPowerOfTwo(n + 1) - 1; /* 2^l <= n < 2^{l+1} */\n  long bound = 2 + NumBits(min(na, nb)) + maxa + maxb;\n  long r = (bound >> l) + 1;\n  long mr = r << l;\n\n  // sqrt(2) trick\n  long l1 = l;\n  if (l1 >= 3) {\n    long alt_l1 = l-1;\n    long alt_r = (bound >> alt_l1) + 1;\n    long alt_mr = alt_r << alt_l1;\n\n    if (alt_mr < mr - mr/8) {\n      l1 = alt_l1;\n      r = alt_r;\n      mr = alt_mr;\n    }\n  }\n\n  return double(mr + 1)/double(bound);\n}\n\n\n\nstatic\nvoid conv(vec_zz_p& x, const ZZVec& a)\n{\n   long i, n;\n\n   n = a.length();\n   x.SetLength(n);\n\n   VectorConv(n, x.elts(), a.elts());\n}\n\n\n\n// Decide to use SSMul.  \nstatic bool ChooseSS(long da, long maxbitsa, long db, long maxbitsb)\n{\n   long k = ((maxbitsa+maxbitsb+NTL_ZZ_NBITS-1)/NTL_ZZ_NBITS)/2;\n   double rat = SSRatio(da, maxbitsa, db, maxbitsb);\n\n#if 1\n   // I've made SSMul fully thread boosted, so I'm using\n   // just one set of crossovers...FIXME: may need to tune this.\n   return (k >= 13  && rat < 1.15) ||\n\t  (k >= 26  && rat < 1.30) ||\n\t  (k >= 53  && rat < 1.60) ||\n\t  (k >= 106 && rat < 1.80) ||\n\t  (k >= 212 && rat < 2.00);\n\n#else\n   // This old code was based on the fact that SSMul was not \n   // full thread boosted\n\n   long nt = AvailableThreads();\n\n   if (nt == 1) {\n\n      return (k >= 13  && rat < 1.15) ||\n             (k >= 26  && rat < 1.30) ||\n             (k >= 53  && rat < 1.60) ||\n             (k >= 106 && rat < 1.80) ||\n             (k >= 212 && rat < 2.00);\n\n   }\n   else if (nt == 2) {\n\n      return (k >= 53  && rat < 1.10) ||\n             (k >= 106 && rat < 1.10) ||\n             (k >= 212 && rat < 1.40);\n\n   }\n   else if (nt == 3) {\n\n      return (k >= 106 && rat < 1.05) ||\n             (k >= 212 && rat < 1.20);\n\n   }\n   else if (nt == 4) {\n\n      return (k >= 106 && rat < 1.04) ||\n             (k >= 212 && rat < 1.10);\n\n   }\n   else if (nt <= 8) {\n\n      return (k >= 212 && rat < 1.01);\n\n   }\n   else {\n\n      return false;\n\n   }\n#endif\n \n}\n\n\nvoid mul(ZZX& c, const ZZX& a, const ZZX& b)\n{\n   if (IsZero(a) || IsZero(b)) {\n      clear(c);\n      return;\n   }\n\n   if (&a == &b) {\n      sqr(c, a);\n      return;\n   }\n\n   long maxa = MaxSize(a);\n   long maxb = MaxSize(b);\n\n   long k = min(maxa, maxb);\n   long s = min(deg(a), deg(b)) + 1;\n\n   // FIXME: I should have a way of setting all these crossovers\n   // automatically\n\n   if (s == 1 || (k == 1 && s < 40) || (k == 2 && s < 20) || \n                 (k == 3 && s < 10)) {\n\n      PlainMul(c, a, b);\n      return;\n   }\n\n   if (s < 80 || (k < 30 && s < 150))  {\n      KarMul(c, a, b);\n      return;\n   }\n\n\n\n   if (ChooseSS(deg(a), MaxBits(a), deg(b), MaxBits(b))) {\n      SSMul(c, a, b);\n   }\n   else {\n      HomMul(c, a, b);\n   }\n}\n\nvoid SSSqr(ZZX& c, const ZZX& a)\n\n{\n  long na = deg(a);\n\n  if (na <= 0) {\n    PlainSqr(c, a);\n    return;\n  }\n\n  long n = na + na; /* degree of the product */\n\n\n  /* Choose m and r suitably */\n  long l = NextPowerOfTwo(n + 1) - 1; /* 2^l <= n < 2^{l+1} */\n  long N = 1L << (l + 1); /* N = 2^{l+1} */\n  long bound = 2 + NumBits(na) + 2*MaxBits(a);\n  /* Let r be minimal so that mr > bound */\n  long r = (bound >> l) + 1;\n  long mr = r << l;\n\n  // sqrt(2) trick\n  long l1 = l;\n  if (l1 >= 3) {\n    long alt_l1 = l-1;\n    long alt_r = (bound >> alt_l1) + 1;\n    long alt_mr = alt_r << alt_l1;\n\n    if (alt_mr < mr - mr/8) {\n      l1 = alt_l1;\n      r = alt_r;\n      mr = alt_mr;\n    }\n  }\n\n  /* p := 2^{mr}+1 */\n  ZZ p;\n  set(p);\n  LeftShift(p, p, mr);\n  add(p, p, 1);\n\n  /* Make coefficients of a and b positive */\n  ZZVec aa;\n  aa.SetSize(N, p.size());\n\n  for (long i = 0; i <= deg(a); i++) {\n    if (sign(a.rep[i]) >= 0) {\n      aa[i] = a.rep[i];\n    } else {\n      add(aa[i], a.rep[i], p);\n    }\n  }\n\n  long yn = SS_FFTRoundUp(n+1, l+1);\n\n  /* N-point FFT's mod p */\n  fft_trunc(aa, yn, SS_FFTRoundUp(na+1, l+1), r, l+1, l1+1, p, mr);\n\n\n  /* Pointwise multiplication aa := aa * bb mod p */\n  bool seq = SS_BelowThresh(yn, p.size());\n  NTL_GEXEC_RANGE(seq, yn, first, last)\n  ZZ tmp, ai;\n  for (long i = first; i < last; i++) {\n    sqr(ai, aa[i]);\n    if (NumBits(ai) > mr) {\n      RightShift(tmp, ai, mr);\n      trunc(ai, ai, mr);\n      sub(ai, ai, tmp);\n      if (sign(ai) < 0) {\n        add(ai, ai, p);\n      }\n    }\n    aa[i] = ai;\n  }\n  NTL_GEXEC_RANGE_END\n\n  ifft_trunc(aa, yn, r, l+1, l1+1, p, mr);\n\n  /* Retrieve c, dividing by N, and subtracting p where necessary */\n  c.rep.SetLength(n + 1);\n  ZZ ai, tmp, scratch;\n  for (long i = 0; i <= n; i++) {\n    ai = aa[i];\n    ZZ& ci = c.rep[i];\n    if (!IsZero(ai)) {\n      /* ci = -ai * 2^{mr-l-1} = ai * 2^{-l-1} = ai / N mod p */\n      LeftRotate(ai, ai, mr - l - 1, p, mr, scratch);\n      sub(tmp, p, ai);\n      if (NumBits(tmp) >= mr) { /* ci >= (p-1)/2 */\n        negate(ci, ai); /* ci = -ai = ci - p */\n      }\n      else\n        ci = tmp;\n    } \n    else\n       clear(ci);\n  }\n}\n\nvoid SSSqr(ZZ_pX& c, const ZZ_pX& a)\n\n{\n  long na = deg(a);\n\n  if (na <= 0) {\n    PlainSqr(c, a);\n    return;\n  }\n\n  long n = na + na; /* degree of the product */\n\n\n  /* Choose m and r suitably */\n  long l = NextPowerOfTwo(n + 1) - 1; /* 2^l <= n < 2^{l+1} */\n  long N = 1L << (l + 1); /* N = 2^{l+1} */\n  long bound = 2 + NumBits(na) + 2*NumBits(ZZ_p::modulus());\n  /* Let r be minimal so that mr > bound */\n  long r = (bound >> l) + 1;\n  long mr = r << l;\n\n  // sqrt(2) trick\n  long l1 = l;\n  if (l1 >= 3) {\n    long alt_l1 = l-1;\n    long alt_r = (bound >> alt_l1) + 1;\n    long alt_mr = alt_r << alt_l1;\n\n    if (alt_mr < mr - mr/8) {\n      l1 = alt_l1;\n      r = alt_r;\n      mr = alt_mr;\n    }\n  }\n\n  /* p := 2^{mr}+1 */\n  ZZ p;\n  set(p);\n  LeftShift(p, p, mr);\n  add(p, p, 1);\n\n  ZZVec aa;\n  aa.SetSize(N, p.size());\n\n  for (long i = 0; i <= deg(a); i++) {\n      aa[i] = rep(a.rep[i]);\n  }\n\n  long yn = SS_FFTRoundUp(n+1, l+1);\n\n  /* N-point FFT's mod p */\n  fft_trunc(aa, yn, SS_FFTRoundUp(na+1, l+1), r, l+1, l1+1, p, mr);\n\n\n  /* Pointwise multiplication aa := aa * bb mod p */\n  bool seq = SS_BelowThresh(yn, p.size());\n  NTL_GEXEC_RANGE(seq, yn, first, last)\n  ZZ tmp, ai;\n  for (long i = first; i < last; i++) {\n    sqr(ai, aa[i]);\n    if (NumBits(ai) > mr) {\n      RightShift(tmp, ai, mr);\n      trunc(ai, ai, mr);\n      sub(ai, ai, tmp);\n      if (sign(ai) < 0) {\n        add(ai, ai, p);\n      }\n    }\n    aa[i] = ai;\n  }\n  NTL_GEXEC_RANGE_END\n\n  ifft_trunc(aa, yn, r, l+1, l1+1, p, mr);\n\n  /* Retrieve c, dividing by N, and subtracting p where necessary */\n  c.rep.SetLength(n+1);\n  bool seq1 = SS_BelowThresh(n+1, p.size());\n  ZZ_pContext context;\n  context.save();\n  NTL_GEXEC_RANGE(seq1, n+1, first, last)\n  context.restore();\n  ZZ ai, tmp, scratch;\n  for (long i = first; i < last; i++) {\n    ai = aa[i];\n    ZZ_p& ci = c.rep[i];\n    if (!IsZero(ai)) {\n      /* ci = -ai * 2^{mr-l-1} = ai * 2^{-l-1} = ai / N mod p */\n      LeftRotate(ai, ai, mr - l - 1, p, mr, scratch);\n      sub(tmp, p, ai);\n      conv(ci, tmp);\n    } \n    else\n       clear(ci);\n  }\n  NTL_GEXEC_RANGE_END\n\n  c.normalize();\n}\n\n\n\nvoid sqr(ZZX& c, const ZZX& a)\n{\n   if (IsZero(a)) {\n      clear(c);\n      return;\n   }\n\n   long maxa = MaxSize(a);\n\n   long k = maxa;\n   long s = deg(a) + 1;\n\n   if (s == 1 || (k == 1 && s < 50) || (k == 2 && s < 25) || \n                 (k == 3 && s < 25) || (k == 4 && s < 10)) {\n\n      PlainSqr(c, a);\n      return;\n   }\n\n   if (s < 80 || (k < 30 && s < 150))  {\n      KarSqr(c, a);\n      return;\n   }\n\n   if (ChooseSS(deg(a), MaxBits(a), deg(a), MaxBits(a))) {\n      SSSqr(c, a);\n   }\n   else {\n      HomSqr(c, a);\n   }\n}\n\n\nvoid mul(ZZX& x, const ZZX& a, const ZZ& b)\n{\n   ZZ t;\n   long i, da;\n\n   const ZZ *ap;\n   ZZ* xp;\n\n   if (IsZero(b)) {\n      clear(x);\n      return;\n   }\n\n   t = b;\n   da = deg(a);\n   x.rep.SetLength(da+1);\n   ap = a.rep.elts();\n   xp = x.rep.elts();\n\n   for (i = 0; i <= da; i++) \n      mul(xp[i], ap[i], t);\n}\n\nvoid mul(ZZX& x, const ZZX& a, long b)\n{\n   long i, da;\n\n   const ZZ *ap;\n   ZZ* xp;\n\n   if (b == 0) {\n      clear(x);\n      return;\n   }\n\n   da = deg(a);\n   x.rep.SetLength(da+1);\n   ap = a.rep.elts();\n   xp = x.rep.elts();\n\n   for (i = 0; i <= da; i++) \n      mul(xp[i], ap[i], b);\n}\n\n\n\n\nvoid diff(ZZX& x, const ZZX& a)\n{\n   long n = deg(a);\n   long i;\n\n   if (n <= 0) {\n      clear(x);\n      return;\n   }\n\n   if (&x != &a)\n      x.rep.SetLength(n);\n\n   for (i = 0; i <= n-1; i++) {\n      mul(x.rep[i], a.rep[i+1], i+1);\n   }\n\n   if (&x == &a)\n      x.rep.SetLength(n);\n\n   x.normalize();\n}\n\nvoid HomPseudoDivRem(ZZX& q, ZZX& r, const ZZX& a, const ZZX& b)\n{\n   if (IsZero(b)) ArithmeticError(\"division by zero\");\n\n   long da = deg(a);\n   long db = deg(b);\n\n   if (da < db) {\n      r = a;\n      clear(q);\n      return;\n   }\n\n   ZZ LC;\n   LC = LeadCoeff(b);\n\n   ZZ LC1;\n\n   power(LC1, LC, da-db+1);\n\n   long a_bound = NumBits(LC1) + MaxBits(a);\n\n   LC1.kill();\n\n   long b_bound = MaxBits(b);\n\n   zz_pBak bak;\n   bak.save();\n\n   ZZX qq, rr;\n\n   ZZ prod, t;\n   set(prod);\n\n   clear(qq);\n   clear(rr);\n\n   long i;\n   long Qinstable, Rinstable;\n\n   Qinstable = 1;\n   Rinstable = 1;\n\n   for (i = 0; ; i++) {\n      zz_p::FFTInit(i);\n      long p = zz_p::modulus();\n\n\n      if (divide(LC, p)) continue;\n\n      zz_pX A, B, Q, R;\n\n      conv(A, a);\n      conv(B, b);\n      \n      if (!IsOne(LC)) {\n         zz_p y;\n         conv(y, LC);\n         power(y, y, da-db+1);\n         mul(A, A, y);\n      }\n\n      if (!Qinstable) {\n         conv(Q, qq);\n         mul(R, B, Q);\n         sub(R, A, R);\n\n         if (deg(R) >= db)\n            Qinstable = 1;\n         else\n            Rinstable = CRT(rr, prod, R);\n      }\n\n      if (Qinstable) {\n         DivRem(Q, R, A, B);\n         t = prod;\n         Qinstable = CRT(qq, t, Q);\n         Rinstable =  CRT(rr, prod, R);\n      }\n\n      if (!Qinstable && !Rinstable) {\n         // stabilized...check if prod is big enough\n\n         long bound1 = b_bound + MaxBits(qq) + NumBits(min(db, da-db)+1);\n         long bound2 = MaxBits(rr);\n         long bound = max(bound1, bound2);\n\n         if (a_bound > bound)\n            bound = a_bound;\n\n         bound += 4;\n\n         if (NumBits(prod) > bound)\n            break;\n      }\n   }\n\n   bak.restore();\n\n   q = qq;\n   r = rr;\n}\n\n\n\n\nvoid HomPseudoDiv(ZZX& q, const ZZX& a, const ZZX& b)\n{\n   ZZX r;\n   HomPseudoDivRem(q, r, a, b);\n}\n\nvoid HomPseudoRem(ZZX& r, const ZZX& a, const ZZX& b)\n{\n   ZZX q;\n   HomPseudoDivRem(q, r, a, b);\n}\n\nvoid PlainPseudoDivRem(ZZX& q, ZZX& r, const ZZX& a, const ZZX& b)\n{\n   long da, db, dq, i, j, LCIsOne;\n   const ZZ *bp;\n   ZZ *qp;\n   ZZ *xp;\n\n\n   ZZ  s, t;\n\n   da = deg(a);\n   db = deg(b);\n\n   if (db < 0) ArithmeticError(\"ZZX: division by zero\");\n\n   if (da < db) {\n      r = a;\n      clear(q);\n      return;\n   }\n\n   ZZX lb;\n\n   if (&q == &b) {\n      lb = b;\n      bp = lb.rep.elts();\n   }\n   else\n      bp = b.rep.elts();\n\n   ZZ LC = bp[db];\n   LCIsOne = IsOne(LC);\n\n\n   vec_ZZ x;\n\n   x = a.rep;\n   xp = x.elts();\n\n   dq = da - db;\n   q.rep.SetLength(dq+1);\n   qp = q.rep.elts();\n\n   if (!LCIsOne) {\n      t = LC;\n      for (i = dq-1; i >= 0; i--) {\n         mul(xp[i], xp[i], t);\n         if (i > 0) mul(t, t, LC);\n      }\n   }\n\n   for (i = dq; i >= 0; i--) {\n      t = xp[i+db];\n      qp[i] = t;\n\n      for (j = db-1; j >= 0; j--) {\n         mul(s, t, bp[j]);\n         if (!LCIsOne) mul(xp[i+j], xp[i+j], LC);\n         sub(xp[i+j], xp[i+j], s);\n      }\n   }\n\n   if (!LCIsOne) {\n      t = LC;\n      for (i = 1; i <= dq; i++) {\n         mul(qp[i], qp[i], t);\n         if (i < dq) mul(t, t, LC);\n      }\n   }\n      \n\n   r.rep.SetLength(db);\n   for (i = 0; i < db; i++)\n      r.rep[i] = xp[i];\n   r.normalize();\n}\n\n\nvoid PlainPseudoDiv(ZZX& q, const ZZX& a, const ZZX& b)\n{\n   ZZX r;\n   PlainPseudoDivRem(q, r, a, b);\n}\n\nvoid PlainPseudoRem(ZZX& r, const ZZX& a, const ZZX& b)\n{\n   ZZX q;\n   PlainPseudoDivRem(q, r, a, b);\n}\n\nvoid div(ZZX& q, const ZZX& a, long b)\n{\n   if (b == 0) ArithmeticError(\"div: division by zero\");\n\n   if (!divide(q, a, b)) ArithmeticError(\"DivRem: quotient undefined over ZZ\");\n}\n\nvoid div(ZZX& q, const ZZX& a, const ZZ& b)\n{\n   if (b == 0) ArithmeticError(\"div: division by zero\");\n\n   if (!divide(q, a, b)) ArithmeticError(\"DivRem: quotient undefined over ZZ\");\n}\n\nstatic\nvoid ConstDivRem(ZZX& q, ZZX& r, const ZZX& a, const ZZ& b)\n{\n   if (b == 0) ArithmeticError(\"DivRem: division by zero\");\n\n   if (!divide(q, a, b)) ArithmeticError(\"DivRem: quotient undefined over ZZ\");\n\n   r = 0;\n}\n\nstatic\nvoid ConstRem(ZZX& r, const ZZX& a, const ZZ& b)\n{\n   if (b == 0) ArithmeticError(\"rem: division by zero\");\n\n   r = 0;\n}\n\n\n\nvoid DivRem(ZZX& q, ZZX& r, const ZZX& a, const ZZX& b)\n{\n   long da = deg(a);\n   long db = deg(b);\n\n   if (db < 0) ArithmeticError(\"DivRem: division by zero\");\n\n   if (da < db) {\n      r = a;\n      q = 0;\n   }\n   else if (db == 0) {\n      ConstDivRem(q, r, a, ConstTerm(b));\n   }\n   else if (IsOne(LeadCoeff(b))) {\n      PseudoDivRem(q, r, a, b);\n   }\n   else if (LeadCoeff(b) == -1) {\n      ZZX b1;\n      negate(b1, b);\n      PseudoDivRem(q, r, a, b1);\n      negate(q, q);\n   }\n   else if (divide(q, a, b)) {\n      r = 0;\n   }\n   else {\n      ZZX q1, r1;\n      ZZ m;\n      PseudoDivRem(q1, r1, a, b);\n      power(m, LeadCoeff(b), da-db+1);\n      if (!divide(q, q1, m)) ArithmeticError(\"DivRem: quotient not defined over ZZ\");\n      if (!divide(r, r1, m)) ArithmeticError(\"DivRem: remainder not defined over ZZ\");\n   }\n}\n\nvoid div(ZZX& q, const ZZX& a, const ZZX& b)\n{\n   long da = deg(a);\n   long db = deg(b);\n\n   if (db < 0) ArithmeticError(\"div: division by zero\");\n\n   if (da < db) {\n      q = 0;\n   }\n   else if (db == 0) {\n      div(q, a, ConstTerm(b));\n   }\n   else if (IsOne(LeadCoeff(b))) {\n      PseudoDiv(q, a, b);\n   }\n   else if (LeadCoeff(b) == -1) {\n      ZZX b1;\n      negate(b1, b);\n      PseudoDiv(q, a, b1);\n      negate(q, q);\n   }\n   else if (divide(q, a, b)) {\n\n      // nothing to do\n      \n   }\n   else {\n      ZZX q1;\n      ZZ m;\n      PseudoDiv(q1, a, b);\n      power(m, LeadCoeff(b), da-db+1);\n      if (!divide(q, q1, m)) ArithmeticError(\"div: quotient not defined over ZZ\");\n   }\n}\n\nvoid rem(ZZX& r, const ZZX& a, const ZZX& b)\n{\n   long da = deg(a);\n   long db = deg(b);\n\n   if (db < 0) ArithmeticError(\"rem: division by zero\");\n\n   if (da < db) {\n      r = a;\n   }\n   else if (db == 0) {\n      ConstRem(r, a, ConstTerm(b));\n   }\n   else if (IsOne(LeadCoeff(b))) {\n      PseudoRem(r, a, b);\n   }\n   else if (LeadCoeff(b) == -1) {\n      ZZX b1;\n      negate(b1, b);\n      PseudoRem(r, a, b1);\n   }\n   else if (divide(a, b)) {\n      r = 0;\n   }\n   else {\n      ZZX r1;\n      ZZ m;\n      PseudoRem(r1, a, b);\n      power(m, LeadCoeff(b), da-db+1);\n      if (!divide(r, r1, m)) ArithmeticError(\"rem: remainder not defined over ZZ\");\n   }\n}\n\nlong HomDivide(ZZX& q, const ZZX& a, const ZZX& b)\n{\n   if (IsZero(b)) {\n      if (IsZero(a)) {\n         clear(q);\n         return 1;\n      }\n      else\n         return 0;\n   }\n\n   if (IsZero(a)) {\n      clear(q);\n      return 1;\n   }\n\n   if (deg(b) == 0) {\n      return divide(q, a, ConstTerm(b));\n   }\n\n   if (deg(a) < deg(b)) return 0;\n\n   ZZ ca, cb, cq;\n\n   content(ca, a);\n   content(cb, b);\n\n   if (!divide(cq, ca, cb)) return 0;\n\n   ZZX aa, bb;\n\n   divide(aa, a, ca);\n   divide(bb, b, cb);\n\n   if (!divide(LeadCoeff(aa), LeadCoeff(bb)))\n      return 0;\n\n   if (!divide(ConstTerm(aa), ConstTerm(bb)))\n      return 0;\n\n   zz_pBak bak;\n   bak.save();\n\n   ZZX qq;\n\n   ZZ prod;\n   set(prod);\n\n   clear(qq);\n   long res = 1;\n   long Qinstable = 1;\n\n\n   long a_bound = MaxBits(aa);\n   long b_bound = MaxBits(bb);\n\n\n   long i;\n   for (i = 0; ; i++) {\n      zz_p::FFTInit(i);\n      long p = zz_p::modulus();\n\n      if (divide(LeadCoeff(bb), p)) continue;\n\n      zz_pX A, B, Q, R;\n\n      conv(A, aa);\n      conv(B, bb);\n\n      if (!Qinstable) {\n         conv(Q, qq);\n         mul(R, B, Q);\n         sub(R, A, R);\n\n         if (deg(R) >= deg(B))\n            Qinstable = 1;\n         else if (!IsZero(R)) {\n            res = 0;\n            break;\n         }\n         else\n            mul(prod, prod, p);\n      }\n\n      if (Qinstable) {\n         if (!divide(Q, A, B)) {\n            res = 0;\n            break;\n         }\n\n         Qinstable = CRT(qq, prod, Q);\n      }\n\n      if (!Qinstable) {\n         // stabilized...check if prod is big enough\n\n         long bound = b_bound + MaxBits(qq) + \n                     NumBits(min(deg(bb), deg(qq)) + 1);\n\n         if (a_bound > bound)\n            bound = a_bound;\n\n         bound += 3;\n\n         if (NumBits(prod) > bound) \n            break;\n      }\n   }\n\n   bak.restore();\n\n   if (res) mul(q, qq, cq);\n   return res;\n\n}\n\n\nlong HomDivide(const ZZX& a, const ZZX& b)\n{\n   if (deg(b) == 0) {\n      return divide(a, ConstTerm(b));\n   }\n   else {\n      ZZX q;\n      return HomDivide(q, a, b);\n   }\n}\n\nlong PlainDivide(ZZX& qq, const ZZX& aa, const ZZX& bb)\n{\n   if (IsZero(bb)) {\n      if (IsZero(aa)) {\n         clear(qq);\n         return 1;\n      }\n      else\n         return 0;\n   }\n\n   if (deg(bb) == 0) {\n      return divide(qq, aa, ConstTerm(bb));\n   }\n\n   long da, db, dq, i, j, LCIsOne;\n   const ZZ *bp;\n   ZZ *qp;\n   ZZ *xp;\n\n\n   ZZ  s, t;\n\n   da = deg(aa);\n   db = deg(bb);\n\n   if (da < db) {\n      return 0;\n   }\n\n   ZZ ca, cb, cq;\n\n   content(ca, aa);\n   content(cb, bb);\n\n   if (!divide(cq, ca, cb)) {\n      return 0;\n   } \n\n\n   ZZX a, b, q;\n\n   divide(a, aa, ca);\n   divide(b, bb, cb);\n\n   if (!divide(LeadCoeff(a), LeadCoeff(b)))\n      return 0;\n\n   if (!divide(ConstTerm(a), ConstTerm(b)))\n      return 0;\n\n   long coeff_bnd = MaxBits(a) + (NumBits(da+1)+1)/2 + (da-db);\n\n   bp = b.rep.elts();\n\n   ZZ LC;\n   LC = bp[db];\n\n   LCIsOne = IsOne(LC);\n\n   xp = a.rep.elts();\n\n   dq = da - db;\n   q.rep.SetLength(dq+1);\n   qp = q.rep.elts();\n\n   for (i = dq; i >= 0; i--) {\n      if (!LCIsOne) {\n         if (!divide(t, xp[i+db], LC))\n            return 0;\n      }\n      else\n         t = xp[i+db];\n\n      if (NumBits(t) > coeff_bnd) return 0;\n\n      qp[i] = t;\n\n      for (j = db-1; j >= 0; j--) {\n         mul(s, t, bp[j]);\n         sub(xp[i+j], xp[i+j], s);\n      }\n   }\n\n   for (i = 0; i < db; i++)\n      if (!IsZero(xp[i]))\n         return 0;\n\n   mul(qq, q, cq);\n   return 1;\n}\n\nlong PlainDivide(const ZZX& a, const ZZX& b)\n{\n   if (deg(b) == 0) \n      return divide(a, ConstTerm(b));\n   else {\n      ZZX q;\n      return PlainDivide(q, a, b);\n   }\n}\n\n\nlong divide(ZZX& q, const ZZX& a, const ZZX& b)\n{\n   long da = deg(a);\n   long db = deg(b);\n\n   if (db <= 8 || da-db <= 8)\n      return PlainDivide(q, a, b);\n   else\n      return HomDivide(q, a, b);\n}\n\nlong divide(const ZZX& a, const ZZX& b)\n{\n   long da = deg(a);\n   long db = deg(b);\n\n   if (db <= 8 || da-db <= 8)\n      return PlainDivide(a, b);\n   else\n      return HomDivide(a, b);\n}\n\n\n\n\n\n\n\nlong divide(ZZX& q, const ZZX& a, const ZZ& b)\n{\n   if (IsZero(b)) {\n      if (IsZero(a)) {\n         clear(q);\n         return 1;\n      }\n      else\n         return 0;\n   }\n\n   if (IsOne(b)) {\n      q = a;\n      return 1;\n   }\n\n   if (b == -1) {\n      negate(q, a);\n      return 1;\n   }\n\n   long n = a.rep.length();\n   vec_ZZ res(INIT_SIZE, n);\n   long i;\n\n   for (i = 0; i < n; i++) {\n      if (!divide(res[i], a.rep[i], b))\n         return 0;\n   }\n\n   q.rep = res;\n   return 1;\n}\n\nlong divide(const ZZX& a, const ZZ& b)\n{\n   if (IsZero(b)) return IsZero(a);\n\n   if (IsOne(b) || b == -1) {\n      return 1;\n   }\n\n   long n = a.rep.length();\n   long i;\n\n   for (i = 0; i < n; i++) {\n      if (!divide(a.rep[i], b))\n         return 0;\n   }\n\n   return 1;\n}\n\nlong divide(ZZX& q, const ZZX& a, long b)\n{\n   if (b == 0) {\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   if (b == -1) {\n      negate(q, a);\n      return 1;\n   }\n\n   long n = a.rep.length();\n   vec_ZZ res(INIT_SIZE, n);\n   long i;\n\n   for (i = 0; i < n; i++) {\n      if (!divide(res[i], a.rep[i], b))\n         return 0;\n   }\n\n   q.rep = res;\n   return 1;\n}\n\nlong divide(const ZZX& a, long b)\n{\n   if (b == 0) return IsZero(a);\n   if (b == 1 || b == -1) {\n      return 1;\n   }\n\n   long n = a.rep.length();\n   long i;\n\n   for (i = 0; i < n; i++) {\n      if (!divide(a.rep[i], b))\n         return 0;\n   }\n\n   return 1;\n}\n\n   \n\nvoid content(ZZ& d, const ZZX& f)\n{\n   ZZ res;\n   long i;\n\n   clear(res);\n   for (i = 0; i <= deg(f); i++) {\n      GCD(res, res, f.rep[i]);\n      if (IsOne(res)) break;\n   }\n\n   if (sign(LeadCoeff(f)) < 0) negate(res, res);\n   d = res;\n}\n\nvoid PrimitivePart(ZZX& pp, const ZZX& f)\n{\n   if (IsZero(f)) {\n      clear(pp);\n      return;\n   }\n \n   ZZ d;\n\n   content(d, f);\n   divide(pp, f, d);\n}\n\n\nstatic\nvoid BalCopy(ZZX& g, const zz_pX& G)\n{\n   long p = zz_p::modulus();\n   long p2 = p >> 1;\n   long n = G.rep.length();\n   long i;\n   long t;\n\n   g.rep.SetLength(n);\n   for (i = 0; i < n; i++) {\n      t = rep(G.rep[i]);\n      if (t > p2) t = t - p;\n      conv(g.rep[i], t);\n   }\n}\n\n\n   \nvoid GCD(ZZX& d, const ZZX& a, const ZZX& b)\n{\n   if (IsZero(a)) {\n      d = b;\n      if (sign(LeadCoeff(d)) < 0) negate(d, d);\n      return;\n   }\n\n   if (IsZero(b)) {\n      d = a;\n      if (sign(LeadCoeff(d)) < 0) negate(d, d);\n      return;\n   }\n\n   ZZ c1, c2, c;\n   ZZX f1, f2;\n\n   content(c1, a);\n   divide(f1, a, c1);\n\n   content(c2, b);\n   divide(f2, b, c2);\n\n   GCD(c, c1, c2);\n\n   ZZ ld;\n   GCD(ld, LeadCoeff(f1), LeadCoeff(f2));\n\n   ZZX g, h, res;\n\n   ZZ prod;\n   set(prod);\n\n   zz_pBak bak;\n   bak.save();\n\n\n   long FirstTime = 1;\n\n   long i;\n   for (i = 0; ;i++) {\n      zz_p::FFTInit(i);\n      long p = zz_p::modulus();\n\n      if (divide(LeadCoeff(f1), p) || divide(LeadCoeff(f2), p)) continue;\n\n      zz_pX G, F1, F2;\n      zz_p  LD;\n\n      conv(F1, f1);\n      conv(F2, f2);\n      conv(LD, ld);\n\n      GCD(G, F1, F2);\n      mul(G, G, LD);\n\n\n      if (deg(G) == 0) { \n         set(res);\n         break;\n      }\n\n      if (FirstTime || deg(G) < deg(g)) {\n         FirstTime = 0;\n         conv(prod, p);\n         BalCopy(g, G);\n      }\n      else if (deg(G) > deg(g)) \n         continue;\n      else if (!CRT(g, prod, G)) {\n         PrimitivePart(res, g);\n         if (divide(f1, res) && divide(f2, res))\n            break;\n      }\n\n   }\n\n   bak.restore();\n\n   mul(d, res, c);\n   if (sign(LeadCoeff(d)) < 0) negate(d, d);\n}\n\nvoid trunc(ZZX& x, const ZZX& a, long m)\n\n// x = a % X^m, output may alias input\n\n{\n   if (m < 0) LogicError(\"trunc: bad args\");\n\n   if (&x == &a) {\n      if (x.rep.length() > m) {\n         x.rep.SetLength(m);\n         x.normalize();\n      }\n   }\n   else {\n      long n;\n      long i;\n      ZZ* xp;\n      const ZZ* ap;\n\n      n = min(a.rep.length(), m);\n      x.rep.SetLength(n);\n\n      xp = x.rep.elts();\n      ap = a.rep.elts();\n\n      for (i = 0; i < n; i++) xp[i] = ap[i];\n\n      x.normalize();\n   }\n}\n\n\n\nvoid LeftShift(ZZX& x, const ZZX& a, long n)\n{\n   if (IsZero(a)) {\n      clear(x);\n      return;\n   }\n\n   if (n < 0) {\n      if (n < -NTL_MAX_LONG)  \n         clear(x);\n      else\n         RightShift(x, a, -n);\n      return;\n   }\n\n   if (NTL_OVERFLOW(n, 1, 0))\n      ResourceError(\"overflow in LeftShift\");\n\n   long m = a.rep.length();\n\n   x.rep.SetLength(m+n);\n\n   long i;\n   for (i = m-1; i >= 0; i--)\n      x.rep[i+n] = a.rep[i];\n\n   for (i = 0; i < n; i++)\n      clear(x.rep[i]);\n}\n\n\nvoid RightShift(ZZX& x, const ZZX& a, long n)\n{\n   if (IsZero(a)) {\n      clear(x);\n      return;\n   }\n\n   if (n < 0) {\n      if (n < -NTL_MAX_LONG) ResourceError(\"overflow in RightShift\");\n      LeftShift(x, a, -n);\n      return;\n   }\n\n   long da = deg(a);\n   long i;\n\n   if (da < n) {\n      clear(x);\n      return;\n   }\n\n   if (&x != &a)\n      x.rep.SetLength(da-n+1);\n\n   for (i = 0; i <= da-n; i++)\n      x.rep[i] = a.rep[i+n];\n\n   if (&x == &a)\n      x.rep.SetLength(da-n+1);\n\n   x.normalize();\n}\n\n\nvoid TraceVec(vec_ZZ& S, const ZZX& ff)\n{\n   if (!IsOne(LeadCoeff(ff)))\n      LogicError(\"TraceVec: bad args\");\n\n   ZZX f;\n   f = ff;\n\n   long n = deg(f);\n\n   S.SetLength(n);\n\n   if (n == 0)\n      return;\n\n   long k, i;\n   ZZ acc, t;\n\n   S[0] = n;\n\n   for (k = 1; k < n; k++) {\n      mul(acc, f.rep[n-k], k);\n\n      for (i = 1; i < k; i++) {\n         mul(t, f.rep[n-i], S[k-i]);\n         add(acc, acc, t);\n      }\n\n      negate(S[k], acc);\n   }\n\n}\n\nstatic\nvoid EuclLength(ZZ& l, const ZZX& a)\n{\n   long n = a.rep.length();\n   long i;\n \n   ZZ sum, t;\n\n   clear(sum);\n   for (i = 0; i < n; i++) {\n      sqr(t, a.rep[i]);\n      add(sum, sum, t);\n   }\n\n   if (sum > 1) {\n      SqrRoot(l, sum);\n      add(l, l, 1);\n   }\n   else\n      l = sum;\n}\n\n\n\nstatic\nlong ResBound(const ZZX& a, const ZZX& b)\n{\n   if (IsZero(a) || IsZero(b)) \n      return 0;\n\n   ZZ t1, t2, t;\n   EuclLength(t1, a);\n   EuclLength(t2, b);\n   power(t1, t1, deg(b));\n   power(t2, t2, deg(a));\n   mul(t, t1, t2);\n   return NumBits(t);\n}\n\n\n\nvoid resultant(ZZ& rres, const ZZX& a, const ZZX& b, long deterministic)\n{\n   if (IsZero(a) || IsZero(b)) {\n      clear(rres);\n      return;\n   }\n\n   zz_pBak zbak;\n   zbak.save();\n\n   ZZ_pBak Zbak;\n   Zbak.save();\n\n   long instable = 1;\n\n   long bound = 2+ResBound(a, b);\n\n   long gp_cnt = 0;\n\n   ZZ res, prod;\n\n   clear(res);\n   set(prod);\n\n\n   long i;\n   for (i = 0; ; i++) {\n      if (NumBits(prod) > bound)\n         break;\n\n      if (!deterministic &&\n          !instable && bound > 1000 && NumBits(prod) < 0.25*bound) {\n\n         ZZ P;\n\n\n         long plen = 90 + NumBits(max(bound, NumBits(res)));\n\n         do {\n            GenPrime(P, plen, 90 + 2*NumBits(gp_cnt++));\n         }\n         while (divide(LeadCoeff(a), P) || divide(LeadCoeff(b), P));\n\n         ZZ_p::init(P);\n\n         ZZ_pX A, B;\n         conv(A, a);\n         conv(B, b);\n\n         ZZ_p t;\n         resultant(t, A, B);\n\n         if (CRT(res, prod, rep(t), P))\n            instable = 1;\n         else\n            break;\n      }\n\n\n      zz_p::FFTInit(i);\n      long p = zz_p::modulus();\n      if (divide(LeadCoeff(a), p) || divide(LeadCoeff(b), p))\n         continue;\n\n      zz_pX A, B;\n      conv(A, a);\n      conv(B, b);\n\n      zz_p t;\n      resultant(t, A, B);\n\n      instable = CRT(res, prod, rep(t), p);\n   }\n\n   rres = res;\n\n   zbak.restore();\n   Zbak.restore();\n}\n\n\n\n\nvoid MinPolyMod(ZZX& gg, const ZZX& a, const ZZX& f)\n\n{\n   if (!IsOne(LeadCoeff(f)) || deg(f) < 1 || deg(a) >= deg(f))\n      LogicError(\"MinPolyMod: bad args\");\n\n   if (IsZero(a)) {\n      SetX(gg);\n      return;\n   }\n\n   ZZ_pBak Zbak;\n   Zbak.save();\n   zz_pBak zbak;\n   zbak.save();\n\n   long n = deg(f);\n\n   long instable = 1;\n\n   long gp_cnt = 0;\n\n   ZZ prod;\n   ZZX g;\n\n   clear(g);\n   set(prod);\n\n   long bound = -1;\n\n   long i;\n   for (i = 0; ; i++) {\n      if (deg(g) == n) {\n         if (bound < 0)\n            bound = 2+CharPolyBound(a, f);\n\n         if (NumBits(prod) > bound)\n            break;\n      }\n\n      if (!instable && \n         (deg(g) < n || \n         (deg(g) == n && bound > 1000 && NumBits(prod) < 0.75*bound))) {\n\n         // guarantees 2^{-80} error probability\n         long plen = 90 + max( 2*NumBits(n) + NumBits(MaxBits(f)),\n                         max( NumBits(n) + NumBits(MaxBits(a)),\n                              NumBits(MaxBits(g)) ));\n\n         ZZ P;\n         GenPrime(P, plen, 90 + 2*NumBits(gp_cnt++));\n         ZZ_p::init(P);\n\n\n         ZZ_pX A, F, G;\n         conv(A, a);\n         conv(F, f);\n         conv(G, g);\n\n         ZZ_pXModulus FF;\n         build(FF, F);\n\n         ZZ_pX H;\n         CompMod(H, G, A, FF);\n         \n         if (IsZero(H))\n            break;\n\n         instable = 1;\n      } \n         \n      zz_p::FFTInit(i);\n\n      zz_pX A, F;\n      conv(A, a);\n      conv(F, f);\n\n      zz_pXModulus FF;\n      build(FF, F);\n\n      zz_pX G;\n      MinPolyMod(G, A, FF);\n\n      if (deg(G) < deg(g))\n         continue;\n\n      if (deg(G) > deg(g)) {\n         clear(g);\n         set(prod);\n      }\n\n      instable = CRT(g, prod, G);\n   }\n\n   gg = g;\n\n   Zbak.restore();\n   zbak.restore();\n}\n\n\nvoid XGCD(ZZ& rr, ZZX& ss, ZZX& tt, const ZZX& a, const ZZX& b, \n          long deterministic)\n{\n   ZZ r;\n\n   resultant(r, a, b, deterministic);\n\n   if (IsZero(r)) {\n      clear(rr);\n      return;\n   }\n\n   zz_pBak bak;\n   bak.save();\n\n   long i;\n   long instable = 1;\n\n   ZZ tmp;\n   ZZ prod;\n   ZZX s, t;\n\n   set(prod);\n   clear(s);\n   clear(t);\n\n   for (i = 0; ; i++) {\n      zz_p::FFTInit(i);\n      long p = zz_p::modulus();\n\n      if (divide(LeadCoeff(a), p) || divide(LeadCoeff(b), p) || divide(r, p))\n         continue;\n\n      zz_p R;\n      conv(R, r);\n\n      zz_pX D, S, T, A, B;\n      conv(A, a);\n      conv(B, b);\n\n      if (!instable) {\n         conv(S, s);\n         conv(T, t);\n         zz_pX t1, t2;\n         mul(t1, A, S); \n         mul(t2, B, T);\n         add(t1, t1, t2);\n\n         if (deg(t1) == 0 && ConstTerm(t1) == R)\n            mul(prod, prod, p);\n         else\n            instable = 1;\n      }\n\n      if (instable) {\n         XGCD(D, S, T, A, B);\n   \n         mul(S, S, R);\n         mul(T, T, R);\n   \n         tmp = prod;\n         long Sinstable = CRT(s, tmp, S);\n         long Tinstable = CRT(t, prod, T);\n   \n         instable = Sinstable || Tinstable;\n      }\n\n      if (!instable) {\n         long bound1 = NumBits(min(deg(a), deg(s)) + 1) \n                      + MaxBits(a) + MaxBits(s);\n         long bound2 = NumBits(min(deg(b), deg(t)) + 1) \n                      + MaxBits(b) + MaxBits(t);\n\n         long bound = 4 + max(NumBits(r), max(bound1, bound2));\n\n         if (NumBits(prod) > bound)\n            break;\n      }\n   }\n\n   rr = r;\n   ss = s;\n   tt = t;\n\n   bak.restore();\n}\n\nvoid NormMod(ZZ& x, const ZZX& a, const ZZX& f, long deterministic)\n{\n   if (!IsOne(LeadCoeff(f)) || deg(a) >= deg(f) || deg(f) <= 0)\n      LogicError(\"norm: bad args\");\n\n   if (IsZero(a)) {\n      clear(x);\n      return;\n   }\n\n   resultant(x, f, a, deterministic);\n}\n\nvoid TraceMod(ZZ& res, const ZZX& a, const ZZX& f)\n{\n   if (!IsOne(LeadCoeff(f)) || deg(a) >= deg(f) || deg(f) <= 0)\n      LogicError(\"trace: bad args\");\n\n   vec_ZZ S;\n\n   TraceVec(S, f);\n\n   InnerProduct(res, S, a.rep);\n}\n\n\nvoid discriminant(ZZ& d, const ZZX& a, long deterministic)\n{\n   long m = deg(a);\n\n   if (m < 0) {\n      clear(d);\n      return;\n   }\n\n   ZZX a1;\n   ZZ res;\n\n   diff(a1, a);\n   resultant(res, a, a1, deterministic);\n   if (!divide(res, res, LeadCoeff(a)))\n      LogicError(\"discriminant: inexact division\");\n\n   m = m & 3;\n   if (m >= 2)\n      negate(res, res);\n\n   d = res;\n}\n\n\nvoid MulMod(ZZX& x, const ZZX& a, const ZZX& b, const ZZX& f)\n{\n   if (deg(a) >= deg(f) || deg(b) >= deg(f) || deg(f) == 0 || \n       !IsOne(LeadCoeff(f)))\n      LogicError(\"MulMod: bad args\");\n\n   ZZX t;\n   mul(t, a, b);\n   rem(x, t, f);\n}\n\nvoid SqrMod(ZZX& x, const ZZX& a, const ZZX& f)\n{\n   if (deg(a) >= deg(f) || deg(f) == 0 || !IsOne(LeadCoeff(f)))\n      LogicError(\"MulMod: bad args\");\n\n   ZZX t;\n   sqr(t, a);\n   rem(x, t, f);\n}\n\n\n\nstatic\nvoid MulByXModAux(ZZX& h, const ZZX& a, const ZZX& f)\n{\n   long i, n, m;\n   ZZ* hh;\n   const ZZ *aa, *ff;\n\n   ZZ t, z;\n\n\n   n = deg(f);\n   m = deg(a);\n\n   if (m >= n || n == 0 || !IsOne(LeadCoeff(f)))\n      LogicError(\"MulByXMod: bad args\");\n\n   if (m < 0) {\n      clear(h);\n      return;\n   }\n\n   if (m < n-1) {\n      h.rep.SetLength(m+2);\n      hh = h.rep.elts();\n      aa = a.rep.elts();\n      for (i = m+1; i >= 1; i--)\n         hh[i] = aa[i-1];\n      clear(hh[0]);\n   }\n   else {\n      h.rep.SetLength(n);\n      hh = h.rep.elts();\n      aa = a.rep.elts();\n      ff = f.rep.elts();\n      negate(z, aa[n-1]);\n      for (i = n-1; i >= 1; i--) {\n         mul(t, z, ff[i]);\n         add(hh[i], aa[i-1], t);\n      }\n      mul(hh[0], z, ff[0]);\n      h.normalize();\n   }\n}\n\nvoid MulByXMod(ZZX& h, const ZZX& a, const ZZX& f)\n{\n   if (&h == &f) {\n      ZZX hh;\n      MulByXModAux(hh, a, f);\n      h = hh;\n   }\n   else\n      MulByXModAux(h, a, f);\n}\n\nstatic\nvoid EuclLength1(ZZ& l, const ZZX& a)\n{\n   long n = a.rep.length();\n   long i;\n \n   ZZ sum, t;\n\n   clear(sum);\n   for (i = 0; i < n; i++) {\n      sqr(t, a.rep[i]);\n      add(sum, sum, t);\n   }\n\n   abs(t, ConstTerm(a));\n   mul(t, t, 2);\n   add(t, t, 1);\n   add(sum, sum, t);\n\n   if (sum > 1) {\n      SqrRoot(l, sum);\n      add(l, l, 1);\n   }\n   else\n      l = sum;\n}\n\n\nlong CharPolyBound(const ZZX& a, const ZZX& f)\n// This computes a bound on the size of the\n// coefficients of the characterstic polynomial.\n// It uses the characterization of the char poly as\n// resultant_y(f(y), x-a(y)), and then interpolates this\n// through complex primimitive (deg(f)+1)-roots of unity.\n\n{\n   if (IsZero(a) || IsZero(f))\n      LogicError(\"CharPolyBound: bad args\");\n\n   ZZ t1, t2, t;\n   EuclLength1(t1, a);\n   EuclLength(t2, f);\n   power(t1, t1, deg(f));\n   power(t2, t2, deg(a));\n   mul(t, t1, t2);\n   return NumBits(t);\n}\n\n\nvoid SetCoeff(ZZX& x, long i, long a)\n{\n   if (a == 1) \n      SetCoeff(x, i);\n   else {\n      NTL_ZZRegister(aa);\n      conv(aa, a);\n      SetCoeff(x, i, aa);\n   }\n}\n\n\nvoid CopyReverse(ZZX& x, const ZZX& a, long hi)\n\n   // x[0..hi] = reverse(a[0..hi]), with zero fill\n   // input may not alias output\n\n{\n   long i, j, n, m;\n\n   n = hi+1;\n   m = a.rep.length();\n\n   x.rep.SetLength(n);\n\n   const ZZ* ap = a.rep.elts();\n   ZZ* xp = x.rep.elts();\n\n   for (i = 0; i < n; i++) {\n      j = hi-i;\n      if (j < 0 || j >= m)\n         clear(xp[i]);\n      else\n         xp[i] = ap[j];\n   }\n\n   x.normalize();\n}\n\nvoid reverse(ZZX& x, const ZZX& a, long hi)\n{\n   if (hi < 0) { clear(x); return; }\n   if (NTL_OVERFLOW(hi, 1, 0))\n      ResourceError(\"overflow in reverse\");\n\n   if (&x == &a) {\n      ZZX tmp;\n      CopyReverse(tmp, a, hi);\n      x = tmp;\n   }\n   else\n      CopyReverse(x, a, hi);\n}\n\nvoid MulTrunc(ZZX& x, const ZZX& a, const ZZX& b, long n)\n{\n   ZZX t;\n   mul(t, a, b);\n   trunc(x, t, n);\n}\n\nvoid SqrTrunc(ZZX& x, const ZZX& a, long n)\n{\n   ZZX t;\n   sqr(t, a);\n   trunc(x, t, n);\n}\n\n\nvoid NewtonInvTrunc(ZZX& c, const ZZX& a, long e)\n{\n   ZZ x;\n\n   if (ConstTerm(a) == 1)\n      x = 1;\n   else if (ConstTerm(a) == -1)\n      x = -1;\n   else\n      ArithmeticError(\"InvTrunc: non-invertible constant term\");\n\n   if (e == 1) {\n      conv(c, x);\n      return;\n   }\n\n   vec_long E;\n   E.SetLength(0);\n   append(E, e);\n   while (e > 1) {\n      e = (e+1)/2;\n      append(E, e);\n   }\n\n   long L = E.length();\n\n   ZZX g, g0, g1, g2;\n\n\n   g.rep.SetMaxLength(E[0]);\n   g0.rep.SetMaxLength(E[0]);\n   g1.rep.SetMaxLength((3*E[0]+1)/2);\n   g2.rep.SetMaxLength(E[0]);\n\n   conv(g, x);\n\n   long i;\n\n   for (i = L-1; i > 0; i--) {\n      // lift from E[i] to E[i-1]\n\n      long k = E[i];\n      long l = E[i-1]-E[i];\n\n      trunc(g0, a, k+l);\n\n      mul(g1, g0, g);\n      RightShift(g1, g1, k);\n      trunc(g1, g1, l);\n\n      mul(g2, g1, g);\n      trunc(g2, g2, l);\n      LeftShift(g2, g2, k);\n\n      sub(g, g, g2);\n   }\n\n   c = g;\n}\n\n\nvoid InvTrunc(ZZX& c, const ZZX& a, long e)\n{\n   if (e < 0) LogicError(\"InvTrunc: bad args\");\n\n   if (e == 0) {\n      clear(c);\n      return;\n   }\n\n   if (NTL_OVERFLOW(e, 1, 0))\n      ResourceError(\"overflow in InvTrunc\");\n\n   NewtonInvTrunc(c, a, e);\n}\n\nNTL_END_IMPL\n", "meta": {"hexsha": "f5c21721c73b9247a48de470282a14e1786b28f4", "size": 72983, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libNTL/unix.d/src/ZZX1.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/ZZX1.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/ZZX1.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": 19.7893167028, "max_line_length": 95, "alphanum_fraction": 0.4962251483, "num_tokens": 25926, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4861504095823268}}
{"text": "// Copyright 2020 Matthias Heinz\n#include <iostream>\n#include <vector>\n\n#include <boost/numeric/odeint.hpp>\n\n#include \"negele/matrix.h\"\n#include \"negele/potential.h\"\n#include \"negele/quad.h\"\n#include \"negele/srg.h\"\n\nint main(void) {\n  auto quadrature = negele::quad::get_gauss_legendre_quadrature(100, 0.0, 25.0);\n  auto pts = std::get<0>(quadrature);\n  auto weights = std::get<1>(quadrature);\n\n  int dim = pts.size();\n\n  double v1 = 12.0;\n  double sig1 = 0.2;\n  double v2 = -12.0;\n  double sig2 = 0.8;\n\n  negele::potential::NegelePotential pot(v1, v2, sig1, sig2);\n\n  std::vector<double> pot_mels(dim * dim, 0.0);\n  for (int i = 0; i < dim; i++) {\n    for (int j = 0; j < dim; j++) {\n      pot_mels[i * dim + j] =\n          pot.eval(pts[j], pts[i]) + pot.eval(pts[j], -1 * pts[i]);\n    }\n  }\n\n  // for (int i = 0; i < dim; i++) {\n  //   std::cout << pot_mels[i] << \", \";\n  // }\n  // std::cout << std::endl;\n\n  // negele::matrix::SquareMatrix pot_matrix(dim, pot_mels);\n\n  negele::matrix::MomentumSpaceMatrix pot_matrix(pts, weights, pot_mels);\n\n  auto ham_matrix =\n      pot_matrix.matrix_elements_with_weights() + pot_matrix.kinetic_energy();\n\n  auto evs = ham_matrix.eigenvalues();\n  for (int i = 0; i < 10; i++) {\n    std::cout << evs[i] << std::endl;\n  }\n\n  // typedef boost::numeric::odeint::runge_kutta4<\n  //     negele::matrix::MomentumSpaceMatrix, double,\n  //     negele::matrix::MomentumSpaceMatrix, double,\n  //     boost::numeric::odeint::vector_space_algebra>\n  //     stepper_type;\n  // stepper_type stepper;\n\n  // const double dlambda = -0.01;\n  // for (double lambda = 50.0; lambda >= 10.0; lambda += dlambda) {\n  //   stepper.do_step(negele::srg::rhs, pot_matrix, lambda, dlambda);\n  //   auto ham_matrix_new =\n  //       pot_matrix.matrix_elements_with_weights() +\n  //       pot_matrix.kinetic_energy();\n\n  //   auto evs_new = ham_matrix_new.eigenvalues();\n  //   std::cout << lambda << \", \" << evs_new[0] << \", \" << ham_matrix_new[30]\n  //             << std::endl;\n  // }\n\n  typedef boost::numeric::odeint::runge_kutta_dopri5<\n      negele::matrix::MomentumSpaceMatrix, double,\n      negele::matrix::MomentumSpaceMatrix, double,\n      boost::numeric::odeint::vector_space_algebra>\n      stepper;\n  int steps = boost::numeric::odeint::integrate_adaptive(\n      boost::numeric::odeint::make_controlled<stepper>(1E-6, 1E-6),\n      negele::srg::rhs, pot_matrix, 50.0, 2.0, -0.1);\n\n  return 0;\n}\n", "meta": {"hexsha": "969389447d21cbebb32b7ee70fc7dcf3c6222675", "size": 2414, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "exec/setup_hamiltonian.cpp", "max_stars_repo_name": "cheshyre/negele-srg-solver-cpp", "max_stars_repo_head_hexsha": "9510a40665480508c28de784f9af2eb4c7e6c0ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "exec/setup_hamiltonian.cpp", "max_issues_repo_name": "cheshyre/negele-srg-solver-cpp", "max_issues_repo_head_hexsha": "9510a40665480508c28de784f9af2eb4c7e6c0ae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "exec/setup_hamiltonian.cpp", "max_forks_repo_name": "cheshyre/negele-srg-solver-cpp", "max_forks_repo_head_hexsha": "9510a40665480508c28de784f9af2eb4c7e6c0ae", "max_forks_repo_licenses": ["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.8024691358, "max_line_length": 80, "alphanum_fraction": 0.6246893123, "num_tokens": 791, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256313782276, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.48615040041554614}}
{"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_FUNCTION_REM_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_REM_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-arithmetic\n    Function object implementing rem capabilities\n\n    Computes the remainder of division.\n    The return value is x-n*y, where n is the value x/y,\n    rounded toward zero.\n\n    @par semantic:\n    For any given value @c x, @c y of type @c T:\n\n    @code\n    T r = rem(x, y);\n    @endcode\n\n    For floating point values the code is similar to:\n\n    @code\n    T r = x-divfix(x, y)*y;\n    @endcode\n\n    For floating entries:\n       -  if x is +/-inf , Nan is returned\n       -  if x is +/-0 and y is not 0 x is returned\n       -  If y is +/-0, Nan is returned\n       -  If either argument is NaN, Nan is returned\n\n       If correct values for these limit cases do not matter for you, using the fast_ decorator\n    can gain some cycles.\n\n    The returned value has the same sign as x and is less than y in magnitude.\n\n    @par Decorators\n\n    std_,  fast_ for floating entries\n\n    @par Alias\n\n    @c fmod,  @c remfix\n\n    @see remainder, mod, modulo\n\n  **/\n  const boost::dispatch::functor<tag::rem_> rem = {};\n} }\n#endif\n\n#include <boost/simd/function/scalar/rem.hpp>\n#include <boost/simd/function/simd/rem.hpp>\n\n#endif\n", "meta": {"hexsha": "1035147a4a4b64ae9ce4c75e194edbdb9d1d3f01", "size": 1730, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/rem.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/function/rem.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/function/rem.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": 24.3661971831, "max_line_length": 100, "alphanum_fraction": 0.5907514451, "num_tokens": 414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6297746143530797, "lm_q1q2_score": 0.48608744119253533}}
{"text": "#ifndef PRECOMP_HPP\n#define PRECOMP_HPP\n\n// C++\n#include <iostream>\n#if defined(_WIN32) && !defined(_USE_MATH_DEFINES)\n#define _USE_MATH_DEFINES // for Windows\n#endif\n#include <cmath>\n#include <chrono>\n#include <vector>\n#include <memory>\n#include <cstdlib>\n#include <algorithm>\n#include <functional>\n#include <map>\n#include <exception>\n\n// OpenCV\n#include <opencv2/core.hpp>\n#include <opencv2/calib3d.hpp>\n\n// VSAC module\n#include \"../include/vsac_definitions.hpp\"\n\n#if defined(HAVE_EIGEN)\n#include <Eigen/Eigen>\n#include <unsupported/Eigen/MatrixFunctions>\n#else\n#define HAVE_EIGEN\n#include \"../lib/Eigen/Eigen\"\n#include \"../lib/Eigen/src/MatrixFunctions/MatrixSquareRoot.h\"\n#endif\n\n#if defined(HAVE_LAPACK)\n//#include <lapacke.h>\n#endif\n\n//#define DEBUG\n//#define DEBUG_DEGENSAC\n\n#endif // PRECOMP_HPP\n", "meta": {"hexsha": "8fe51925ba9dd50ea6dc899341a18230f31e8526", "size": 804, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/precomp.hpp", "max_stars_repo_name": "yuki-inaho/vsac", "max_stars_repo_head_hexsha": "4fb7b5e8c18fa05ef89ae092d7738da5522b8fd0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2021-10-22T04:45:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T13:08:13.000Z", "max_issues_repo_path": "src/precomp.hpp", "max_issues_repo_name": "yuki-inaho/vsac", "max_issues_repo_head_hexsha": "4fb7b5e8c18fa05ef89ae092d7738da5522b8fd0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2022-01-23T12:08:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-25T15:42:47.000Z", "max_forks_repo_path": "src/precomp.hpp", "max_forks_repo_name": "yuki-inaho/vsac", "max_forks_repo_head_hexsha": "4fb7b5e8c18fa05ef89ae092d7738da5522b8fd0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-11-15T06:36:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T11:17:35.000Z", "avg_line_length": 18.6976744186, "max_line_length": 62, "alphanum_fraction": 0.7475124378, "num_tokens": 207, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.4860874399454238}}
{"text": "#ifndef CALIBRATOR_PROCESSES_GENERALORNSTEINUHLENBECKPROCESS_HPP\n#define CALIBRATOR_PROCESSES_GENERALORNSTEINUHLENBECKPROCESS_HPP\n\n#include <boost/function.hpp>\n\n#include <ql/stochasticprocess.hpp>\n#include <ql/models/parameter.hpp>\n#include <ql/math/integrals/kronrodintegral.hpp>\n\n#include <calibrator/global.hpp>\n\nnamespace HJCALIBRATOR\n{\n\t//! Time-dependelt Ornstein-Uhlenbeck process class\n\t/*! This class describes the (constrained) time-dependent Ornstein-Uhlenbeck process\n\tdescribed by\n\t\\f[\n\tdx(t) = -a(t)x(t)dt + \\sigma(t)dW_t\n\t\\f]\n\n\t\\note The level(\\f$ \\mu \\f$) is constrained to be zero,\n\tand the speed term \\f$ \\alpha \\f$ must be given as a IntegrableParameter object.\n\t\n\t\\ingroup processes\n\t*/\n\tclass GeneralizedOrnsteinUhlenbeckProcess : public StochasticProcess1D\n\t{\n\tpublic :\n\t\tGeneralizedOrnsteinUhlenbeckProcess( const Parameter& a, // must be an IntegrableParameter\n\t\t\t\t\t\t\t\t\t\t\t const Parameter& sigma,\n\t\t\t\t\t\t\t\t\t\t\t const Real x0 = 0 )\n\t\t\t: a_(a), sigma_(sigma), x0_(x0)\n\t\t\t, integrator_(GaussKronrodAdaptive( GaussKronrodAdaptive( 1.e-8, 10000 ) ))\n\t\t{}\n\n\t\tvirtual ~GeneralizedOrnsteinUhlenbeckProcess() {}\n\n\t\t//! \\name StochasticProcess1D interface\n\t\t//@{\n\t\tReal x0() const override { return x0_; }\n\t\tReal drift( Time t, Real x ) const override;\n\t\tReal diffusion( Time t, Real x ) const override;\n\t\tReal variance( Time t0, Real x0, Time dt ) const override;\n\t\tReal expectation( Time t0, Real x0, Time dt ) const override;\n\t\tReal stdDeviation( Time t0, Real x0, Time dt ) const override;\n\t\t//@}\n\n\t\tParameter a() { return a_; }\n\t\tParameter sigma() { return sigma_; }\n\n\t\tReal a( Time t ) { return a_( t ); }\n\t\tReal sigma( Time t ) { return sigma_( t ); }\n\n\tprivate :\n\t\tReal E( Time t0, Time t1 ) const;\n\t\tReal VrIntegrand( Time t );\n\n\t\tReal x0_;\n\t\tParameter a_;\n\t\tParameter sigma_;\n\n\t\tGaussKronrodAdaptive integrator_;\n\t};\n\n\t// inline definitions\n\n\tinline Real GeneralizedOrnsteinUhlenbeckProcess::drift( Time t, Real x ) const\n\t{\n\t\treturn  - a_( t ) * x;\n\t}\n\n\tinline Real GeneralizedOrnsteinUhlenbeckProcess::diffusion( Time t, Real x ) const\n\t{\n\t\treturn sigma_( t );\n\t}\n\n\tinline Real GeneralizedOrnsteinUhlenbeckProcess::variance( Time t0, Real x0, Time dt ) const\n\t{\n\t\tTime t = t0 + dt;\n\n\t\tauto integrand = [&, t]( Time u )\n\t\t{\n\t\t\tReal sigma = sigma_( u );\n\t\t\tReal Etu = E( u, t );\n\n\t\t\treturn sigma * sigma / Etu / Etu;\n\t\t};\n\t\t\n\t\treturn integrator_( integrand, t0, t );\n\t}\n\n\tinline Real GeneralizedOrnsteinUhlenbeckProcess::stdDeviation( Time t0, Real x0, Time dt ) const\n\t{\n\t\treturn sqrt( variance( t0, x0, dt ) );\n\t}\n\n\tinline Real GeneralizedOrnsteinUhlenbeckProcess::expectation( Time t0, Real x0, Time dt ) const\n\t{\n\t\t/* A part of eq.35 */\n\t\tTime s = t0;\n\t\tTime t = t0 + dt;\n\n\t\tReal RE = 1 / E( s, t );\n\n\t\treturn RE * x0;\n\t}\n\n\tinline Real GeneralizedOrnsteinUhlenbeckProcess::E( Time t0, Time t1 ) const\n\t{\n\t\tconst Parameter& a = a_;\n\n\t\tauto integrand = [&a]( Time u )\n\t\t{\n\t\t\treturn a( u );\n\t\t};\n\n\t\treturn integrator_( integrand, t0, t1 );\n\t}\n\n\tinline Real GeneralizedOrnsteinUhlenbeckProcess::VrIntegrand( Time t )\n\t{\n\t\t/* Integrand of eq. 37\n\t\t\\f[\n\t\tI(t) =  E^2(t)\\sigam^2(t)\n\t\t\\f]\n\t\t*/\n\t\tReal Et = E( 0, t );\n\t\tReal sigmat = sigma_( t );\n\n\t\treturn Et * Et * sigmat * sigmat;\n\t}\n}\n#endif // !CALIBRATOR_PROCESSES_GENERALORNSTEINUHLENBECKPROCESS_HPP\n", "meta": {"hexsha": "37092dd879f8d04bd6efe7f3662510df8fb77bdf", "size": 3275, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "calibrator/calibrator/processes/generalornsteinuhlenbeckprocess.hpp", "max_stars_repo_name": "hanjin-kim/gaussian-n-factor", "max_stars_repo_head_hexsha": "0865fa115094e1f7f8e968eb8f7f123c2cc26c9f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-02-25T05:59:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-27T04:10:19.000Z", "max_issues_repo_path": "sources/calibrator/calibrator/processes/generalornsteinuhlenbeckprocess.hpp", "max_issues_repo_name": "hanjin-kim/gaussian-n-factor", "max_issues_repo_head_hexsha": "0865fa115094e1f7f8e968eb8f7f123c2cc26c9f", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/calibrator/calibrator/processes/generalornsteinuhlenbeckprocess.hpp", "max_forks_repo_name": "hanjin-kim/gaussian-n-factor", "max_forks_repo_head_hexsha": "0865fa115094e1f7f8e968eb8f7f123c2cc26c9f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-07-27T04:10:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-27T04:10:42.000Z", "avg_line_length": 24.4402985075, "max_line_length": 97, "alphanum_fraction": 0.6821374046, "num_tokens": 1060, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.48608743582925246}}
{"text": "/*\nCopyright 2014, 2015 Rogier van Dalen.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/** \\file\nDefine a magma that is a tuple of other magmas, where \"plus\" takes the best of\nthe two values according to a lexicographical ordering.\n*/\n\n#ifndef MATH_LEXICOGRAPHICAL_HPP_INCLUDED\n#define MATH_LEXICOGRAPHICAL_HPP_INCLUDED\n\n#include <type_traits>\n\n#include <boost/mpl/and.hpp>\n\n#include <boost/utility/enable_if.hpp>\n#include <boost/functional/hash_fwd.hpp>\n\n#include \"meta/vector.hpp\"\n#include \"meta/all_of_c.hpp\"\n\n#include \"utility/type_sequence_traits.hpp\"\n\n#include \"range/tuple.hpp\"\n#include \"range/call_unpack.hpp\"\n#include \"range/equal.hpp\"\n#include \"range/less_lexicographical.hpp\"\n#include \"range/transform.hpp\"\n#include \"range/all_of.hpp\"\n#include \"range/hash_range.hpp\"\n\n#include \"magma.hpp\"\n#include \"detail/tuple_helper.hpp\"\n\nnamespace math {\n\n/**\nThe lexicographical semiring.\nThis is a semiring that has multiple components.\nOperations \\ref plus and \\ref choose are defined as taking the best in a strict\nweak ordering.\nThe ordering is defined by lexicographical comparison: if the first components\nare the same, the second components are compared, et cetera.\n\nOften, the user will not care about the ordering of the later components, but it\nstill needs to be defined to make this a proper semiring.\nFor example, the first component could be of type \\ref cost or\n\\ref max_semiring, indicating a cost or probability.\nThe components following it could form the payload, for example, the word\nsequence.\nUsed on the correct automaton, the right algorithm might yield the lowest-cost\nor highest-probability word sequence.\n\nAll components must be monoids over \\ref times, and have \\ref choose defined.\nThe first component must be a semiring over \\ref times and \\ref choose.\nEach of the other elements must almost be a semiring, but does not have to have\na multiplicative annihilator.\n\nThe first component is used to indicate the additive identity (and, thus, the\nmultiplicative annihilator), \\ref zero(), of the whole semiring.\nWhen the first component is zero, the meaning of the whole semiring object is\nthe additive identity, whatever the value of the other components.\nAny two objects with the first component equal and the additive identity will\ntherefore compare equal.\nSuch objects can, however, have detectably different elements after the first\ncomponent.\n\nThis type is implicitly convertible from another lexicographical semiring if\nall components are.\nIt is explicitly convertible from if one or more of the components is explicitly\nconvertible (and the rest is implicitly convertible).\n\nThis semiring does not have \\ref divide.\nThis would require each component to be divided, which is impossible if any is\nan annihilator.\nThen, any element of a lexicographical semiring that has any component that is\nan annihilator would have to be an annihilator itself.\nThis is functionality that could be added, but should not be the default.\nIt is not currently implemented.\n\nlexicographical objects can be constructed explicitly with a list of argument,\neach of which is pairwise convertible to the component.\nThey can also be constructed from a compatible lexicographical: implicitly if\nall components are implicitly convertible; and explicitly if some are only\nexplicitly convertible.\n\nIt has a member function \\c components() which returns the range with the\ncomponents in order.\n\nThe lexicographical semiring supports Boost.Hash, if\n\\c boost/functional/hash.hpp is included.\nIf the hash values of the components of two lexicographical semirings are the\nsame, then the hash value of the two semirings will be the same.\n\n\\tparam Components\n    Type of the form \\ref over\\<...> with the magmas that should be contained.\n    All the magmas must have an ordered \\c choose.\n    The first of them must be a semiring over \\c times and \\c choose.\n    The rest must be semirings except for the annihilator.\n    That is, each must be a commutative monoid over \\c choose; a monoid over\n    \\c times; and \\c times must distribute over \\c choose.\n\n\\internal\nThere is some documentation of members in lexicographical <over <...>>, but\nSphinx refuses some of the syntax anyway.\n*/\ntemplate <class Components> class lexicographical;\n\ntemplate <class ComponentTags> struct lexicographical_tag;\n\ntemplate <class ... Components>\n    struct decayed_magma_tag <lexicographical <over <Components ...>>>\n{\n    typedef lexicographical_tag <\n        over <typename magma_tag <Components>::type ...>> type;\n};\n\ntemplate <class ... Components> class lexicographical <over <Components ...>> {\npublic:\n    typedef meta::vector <Components ...> component_types;\n    typedef range::tuple <Components ...> components_type;\n\nprivate:\n    typedef typename meta::first <component_types>::type first_component_type;\n    typedef typename meta::drop <component_types>::type rest_component_type;\n\n    static_assert (meta::all_of_c <std::is_same <Components,\n            typename std::decay <Components>::type>::value ...>::value,\n        \"The components may not be cv- or reference-qualified.\");\n\n    static_assert (meta::all_of_c <has <callable::order <callable::choose> (\n            Components, Components)>::value...>::value,\n        \"All components must have an ordered 'choose'.\");\n\n    static_assert (meta::all_of_c <\n            is::monoid <callable::times, Components>::value ...>::value,\n        \"All components must be monoids over 'times'.\");\n    static_assert (meta::all_of_c <\n            is::monoid <callable::choose, Components>::value ...>::value,\n        \"All components must be monoids over 'choose'.\");\n    static_assert (meta::all_of_c <\n            is::commutative <callable::choose, Components>::value ...>::value,\n        \"For all components, 'choose' must be commutative.\");\n\npublic:\n    /**\n    Evaluate to \\c true iff this is a semiring in \\a Direction.\n    For this to be true, the first component must be a semiring in \\a Direction,\n    and for the other components, \\c times is distributive over \\c choose in\n    \\a Direction.\n    */\n    template <class Direction> struct is_semiring\n    : boost::mpl::and_ <\n        is::semiring <Direction,\n            callable::times, callable::choose, first_component_type>,\n        meta::all_of_c <is::distributive <Direction,\n            callable::times, callable::choose, Components>::value ...>\n    > {};\n\n    static_assert (is_semiring <left>::value || is_semiring <right>::value,\n        \"The components must allow this to be a semiring in at least one \"\n        \"direction.\");\n\n    components_type components_;\npublic:\n    /**\n    Construct from arguments that are pairwise convertible to the components.\n    This constructor is implicit.\n    */\n    template <class ... Arguments, class Enable = typename boost::enable_if <\n        utility::are_constructible <\n            meta::vector <Components ...>, meta::vector <Arguments ...>>>::type>\n    explicit lexicographical (Arguments && ... arguments)\n    : components_ (std::forward <Arguments> (arguments) ...) {}\n\n    lexicographical (lexicographical const &) = default;\n    lexicographical (lexicographical &&) = default;\n\n    /**\n    Construct from a lexicographical with different component types, all of\n    which are implicitly convertible to the component types of this.\n    This constructor is implicit.\n    \\param other The lexicographical to copy.\n    */\n    template <class ... OtherComponents>\n    lexicographical (lexicographical <over <OtherComponents ...>> const & other,\n        typename boost::enable_if <utility::are_convertible <\n            meta::vector <OtherComponents const & ...>,\n            meta::vector <Components ...>>\n        >::type * = 0)\n    : components_ (other.components()) {}\n\n    /**\n    Construct from a lexicographical with different component types, at least\n    one of which is explicitly convertible and not implicitly convertible.\n    This constructor is explicit.\n    \\param other The lexicographical to copy.\n    */\n    template <class ... OtherComponents>\n    explicit lexicographical (\n        lexicographical <over <OtherComponents ...>> const & other, typename\n        boost::enable_if <\n            tuple_helper::components_constructible_only <\n                meta::vector <Components ...>,\n                meta::vector <OtherComponents const & ...>>\n            >::type * = 0)\n    : components_ (other.components()) {}\n\n    lexicographical & operator = (lexicographical const &) = default;\n    lexicographical & operator = (lexicographical &&) = default;\n\n    components_type & components() { return components_; }\n    components_type const & components() const { return components_; }\n};\n\nnamespace callable {\n\n    struct make_lexicographical {\n        template <class ... Components>\n            lexicographical <over <Components ...>> operator() (\n                Components const & ... components) const\n        { return lexicographical <over <Components ...>> (components ...); }\n    };\n\n    struct make_lexicographical_over {\n        template <class Components>\n            auto operator() (Components && components) const\n        RETURNS (range::call_unpack (\n            make_lexicographical(), std::forward <Components> (components)));\n    };\n\n} // namespace callable\n\nstatic auto constexpr make_lexicographical = callable::make_lexicographical();\nstatic auto constexpr make_lexicographical_over\n    = callable::make_lexicographical_over();\n\nnamespace detail {\n\n    template <class Type> struct is_lexicographical_tag : boost::mpl::false_ {};\n    template <class ... ComponentTags> struct is_lexicographical_tag <\n        lexicographical_tag <over <ComponentTags ...>>>\n    : boost::mpl::true_ {};\n\n} // namespace detail\n\nnamespace operation {\n\n    namespace tuple_helper {\n\n        template <class ... ComponentTags> struct get_components <\n            lexicographical_tag <over <ComponentTags ...>>>\n        {\n            template <class Lexicographical>\n                auto operator() (Lexicographical const & l) const\n            RETURNS (l.components());\n        };\n\n    } // namespace tuple_helper\n\n    /* Queries. */\n\n    template <class ... ComponentTags>\n        struct is_member <lexicographical_tag <over <ComponentTags ...>>>\n    {\n        template <class Lexicographical>\n            auto operator() (Lexicographical const & l) const\n        RETURNS (range::all_of (range::transform (\n            l.components(), ::math::is_member)));\n    };\n\n    // is_annihilator.\n    /*\n    If the operation has an inverse: any component being an annihilator makes\n    the whole product an annihilator.\n    If not, then the default implementation (compare component-per-component\n    with the result of annihilator()) works.\n    */\n    template <class ComponentTags> struct is_annihilator <\n        lexicographical_tag <ComponentTags>, callable::times>\n    {\n        template <class Lexicographical> auto operator() (\n            Lexicographical const & l) const\n        RETURNS (math::is_annihilator <callable::times> (\n            range::first (l.components())));\n    };\n\n    // Compare annihilators equal, otherwise compare components.\n    template <class ComponentTags>\n        struct equal <lexicographical_tag <ComponentTags>>\n    : tuple_helper::equal_if_annihilator <callable::times,\n        tuple_helper::equal_components <math::callable::equal>> {};\n\n    // Compare annihilators equal, otherwise compare components.\n    template <class ComponentTags>\n        struct approximately_equal <lexicographical_tag <ComponentTags>>\n    : tuple_helper::equal_if_annihilator <callable::times,\n        tuple_helper::equal_components <math::callable::approximately_equal>>\n    {};\n\n    // Compare annihilators equal, otherwise compare components.\n    template <class ComponentTags>\n        struct compare <lexicographical_tag <ComponentTags>>\n    : tuple_helper::compare_if_annihilator <callable::times,\n        tuple_helper::compare_components <math::callable::compare>> {};\n\n    /* Produce. */\n\n    template <class ... ComponentTags>\n        struct identity <lexicographical_tag <over <ComponentTags ...>>,\n            callable::times>\n    {\n        auto operator() () const\n        RETURNS (make_lexicographical (\n            identity <ComponentTags, callable::times>()() ...));\n    };\n\n    /**\n    Generalised 0.\n    This is (0, 1 ...) because apart from for the first component, the plus\n    operation is not guaranteed to be defined.\n    */\n    template <class FirstComponentTag, class ... ComponentTags>\n        struct identity <lexicographical_tag <over <\n            FirstComponentTag, ComponentTags ...>>, callable::choose>\n    {\n        auto operator() () const\n        RETURNS (make_lexicographical (\n            identity <FirstComponentTag, callable::choose>()(),\n            identity <ComponentTags, callable::times>()() ...));\n    };\n\n    // plus: forward to implementation for \"choose\".\n    template <class Tags>\n        struct identity <lexicographical_tag <Tags>, callable::plus>\n    : identity <lexicographical_tag <Tags>, callable::choose> {};\n\n    /**\n    Multiplicative annihilator: equal to the additive identity.\n    */\n    template <class FirstComponentTag, class ... ComponentTags>\n        struct annihilator <lexicographical_tag <over <\n            FirstComponentTag, ComponentTags ...>>, callable::times>\n    {\n        auto operator() () const\n        RETURNS (make_lexicographical (\n            annihilator <FirstComponentTag, callable::times>()(),\n            identity <ComponentTags, callable::times>()() ...));\n    };\n\n    /* Operations. */\n\n    template <class Tags>\n        struct order <lexicographical_tag <Tags>, callable::choose>\n    : tuple_helper::compare_components <\n        math::callable::order <callable::choose>> {};\n\n    // order <plus>: forward to order <choose>.\n    template <class Tags>\n        struct order <lexicographical_tag <Tags>, callable::plus>\n    : order <lexicographical_tag <Tags>, callable::choose> {};\n\n    /**\n    Apply the multiplication operation on the weights, and on the values.\n    */\n    template <class ... ComponentTags>\n        struct times <lexicographical_tag <over <ComponentTags ...>>>\n    : tuple_helper::binary_operation <callable::make_lexicographical,\n        meta::vector <times <ComponentTags> ...>> {};\n\n    // Semiring under times and choose/plus: depends on the direction.\n    template <class FirstComponentTag, class ... ComponentTags, class Direction>\n        struct is_semiring <\n            lexicographical_tag <over <FirstComponentTag, ComponentTags ...>>,\n                Direction, callable::times, callable::choose>\n    : meta::all_of_c <\n        is_semiring <FirstComponentTag,\n            Direction, callable::times, callable::choose>::value,\n        is_distributive <ComponentTags,\n            Direction, callable::times, callable::choose>::value ...> {};\n\n    template <class ComponentTags, class Direction> struct is_semiring <\n        lexicographical_tag <ComponentTags>,\n            Direction, callable::times, callable::plus>\n    : is_semiring <lexicographical_tag <ComponentTags>,\n        Direction, callable::times, callable::choose> {};\n\n    /*\n    divide is undefined.\n    It would have to call divide on all its components, and if one of them was\n    an annihilator, the whole lexicographical semiring would have to be an\n    annihilator.\n    This would probably require an interface similar to product's.\n    */\n\n    template <class ... Tags>\n        struct print <lexicographical_tag <over <Tags ...>>>\n    : tuple_helper::print_components <meta::vector <Tags ...>> {};\n\n    template <class ... ComponentTags,\n            class ... Components1, class ... Components2>\n        struct unify_type <lexicographical_tag <over <ComponentTags ...>>,\n            lexicographical <over <Components1 ...>>,\n            lexicographical <over <Components2 ...>>>\n    {\n        // Unify both underlying types in parallel.\n        typedef lexicographical <over <typename unify_type <\n            ComponentTags, Components1, Components2>::type ...>> type;\n    };\n\n} // namespace operation\n\nMATH_MAGMA_GENERATE_OPERATORS (detail::is_lexicographical_tag)\n\n// Boost.Hash support.\n\nnamespace lexicographical_detail {\n\n    // Annihilators are treated specially.\n    static std::size_t constexpr annihilator_hash =\n        std::size_t (0xa5e33b35c473015b  & std::size_t (-1));\n\n} // namespace lexicographical_detail\n\n// Without an inverse: just combine the hash values of the components.\ntemplate <class Components>\n    inline std::size_t hash_value (lexicographical <Components> const & l)\n{\n    if (is_annihilator <callable::times> (l))\n        return lexicographical_detail::annihilator_hash;\n    else\n        return range::hash_range (l.components());\n}\n\n} // namespace math\n\n#endif // MATH_LEXICOGRAPHICAL_HPP_INCLUDED\n", "meta": {"hexsha": "5f14e47c38e705a2bea326c76b3732f97d5da2ae", "size": 17255, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/math/lexicographical.hpp", "max_stars_repo_name": "rogiervd/math", "max_stars_repo_head_hexsha": "96174afac1a2933d71cb7ae3962437f860fc10ec", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/math/lexicographical.hpp", "max_issues_repo_name": "rogiervd/math", "max_issues_repo_head_hexsha": "96174afac1a2933d71cb7ae3962437f860fc10ec", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/math/lexicographical.hpp", "max_forks_repo_name": "rogiervd/math", "max_forks_repo_head_hexsha": "96174afac1a2933d71cb7ae3962437f860fc10ec", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.2594235033, "max_line_length": 80, "alphanum_fraction": 0.6960880904, "num_tokens": 3736, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390746, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.4860874358292524}}
{"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_RANDOM_STRATEGIES_CARTESIAN_UNIFORM_POINT_DISTRIBUTION_BOX_HPP\n#define BOOST_GEOMETRY_EXTENSIONS_RANDOM_STRATEGIES_CARTESIAN_UNIFORM_POINT_DISTRIBUTION_BOX_HPP\n\n#include <random>\n#include <iterator>\n\n#include <boost/geometry/algorithms/equals.hpp>\n#include <boost/geometry/util/for_each_coordinate.hpp>\n\n#include <boost/geometry/extensions/random/strategies/uniform_point_distribution.hpp>\n\nnamespace boost { namespace geometry\n{\n\nnamespace strategy { namespace uniform_point_distribution {\n\nnamespace detail\n{\n\ntemplate\n<\n    typename Point,\n    typename Box,\n    typename Generator,\n    bool isIntegral =\n        boost::is_integral<typename coordinate_type<Point>::type>::type::value\n>\nstruct interval_sample {};\n\ntemplate<typename Point, typename Box, typename Generator>\nstruct interval_sample<Point, Box, Generator, true>\n{\n    Box const& b;\n    Generator& gen;\n    inline interval_sample(Box const& b, Generator& gen):b(b),gen(gen) {}\n    template <typename PointDst, std::size_t Index>\n    inline void apply(PointDst& point_dst) const\n    {\n        std::uniform_int_distribution<typename coordinate_type<Point>::type>\n            dist(get<min_corner,Index>(b),get<max_corner,Index>(b));\n        set<Index>(point_dst,dist(gen));\n    }\n};\n\ntemplate<typename Point, typename Box, typename Generator>\nstruct interval_sample<Point, Box, Generator, false>\n{\n    Box const& b;\n    Generator& gen;\n    inline interval_sample(Box const& b, Generator& gen):b(b),gen(gen) {}\n\n    template <typename PointDst, std::size_t Index>\n    inline void apply(PointDst& point_dst) const\n    {\n        std::uniform_real_distribution<typename coordinate_type<Point>::type>\n            dist(get<min_corner,Index>(b),get<max_corner,Index>(b));\n        set<Index>(point_dst,dist(gen));\n    }\n};\n\n}\n\ntemplate\n<\n    typename Point,\n    typename DomainGeometry,\n    int Dim\n>\nstruct interval_product_distribution\n{\n    interval_product_distribution(DomainGeometry const& g) {}\n    bool equals(DomainGeometry const& l_domain,\n                DomainGeometry const& r_domain,\n                interval_product_distribution const& r_strategy) const\n    {\n        return boost::geometry::equals(l_domain.domain(), r_domain.domain());\n    }\n    template<typename Gen>\n    Point apply(Gen& g, DomainGeometry const& d)\n    {\n        Point r;\n        for_each_coordinate(r,\n        \tdetail::interval_sample<Point, DomainGeometry, Gen>(d, g));\n        return r;\n    }\n    void reset(DomainGeometry const&) {};\n};\n\nnamespace services {\n\ntemplate\n<\n    typename Point,\n    typename DomainGeometry,\n    int Dim\n>\nstruct default_strategy\n<\n    Point,\n    DomainGeometry,\n    box_tag,\n    single_tag, //There are no MultiBoxes right now\n    Dim,\n    cartesian_tag\n> : public interval_product_distribution<Point, DomainGeometry, Dim> {\n    typedef interval_product_distribution<Point, DomainGeometry, Dim> base;\n    using base::base;\n};\n\n} // namespace services\n\n}} // namespace strategy::uniform_point_distribution\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_EXTENSIONS_RANDOM_STRATEGIES_CARTESIAN_UNIFORM_POINT_DISTRIBUTION_BOX_HPP\n", "meta": {"hexsha": "6a37158ad7f04f77244e13915ad10eeb75cfee02", "size": 3442, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/geometry/extensions/random/strategies/cartesian/uniform_point_distribution_box.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/random/strategies/cartesian/uniform_point_distribution_box.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/random/strategies/cartesian/uniform_point_distribution_box.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": 27.536, "max_line_length": 98, "alphanum_fraction": 0.7254503196, "num_tokens": 761, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390746, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.4860874358292524}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\nCopyright (C) 2007 Marco Bianchetti\nCopyright (C) 2007 Giorgio Facchinetti\nCopyright (C) 2006 Chiara Fornarola\nCopyright (C) 2005 StatPro Italia srl\nCopyright (C) 2013 Peter Caspers\nCopyright (C) 2015 CompatibL\n\nThis file is part of QuantLib, a free-software/open-source library\nfor financial quantitative analysts and developers - http://quantlib.org/\n\nQuantLib is free software: you can redistribute it and/or modify it\nunder the terms of the QuantLib license.  You should have received a\ncopy of the license along with this program; if not, please email\n<quantlib-dev@lists.sf.net>. The license is also available online at\n<http://quantlib.org/license.shtml>.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT\nANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\nFOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n// Based on shortratemodels.cpp file from Quantlib/test-suite.\n\n#ifndef cl_adjoint_shortratemodels_impl_hpp\n#define cl_adjoint_shortratemodels_impl_hpp\n#pragma once\n\n#include <ql/quantlib.hpp>\n#include \"utilities.hpp\"\n#include \"adjointshortratemodelstest.hpp\"\n#include \"adjointtestutilities.hpp\"\n#include \"adjointtestbase.hpp\"\n#include <boost/shared_ptr.hpp>\n\nusing namespace QuantLib;\nusing namespace boost::unit_test_framework;\n\n#define OUTPUT_FOLDER_NAME \"AdjointShortRateModels\"\n\nnamespace\n{\n    struct CalibrationData\n    {\n        Integer start_;\n        Integer length_;\n        Real volatility_;\n    };\n\n    struct VolatilityDependence\n    {\n        static std::deque<std::string > get_columns()\n        {\n            static std::deque<std::string > columns =\n            {\n                \"Volatility\", \"ModelSigma\"\n            };\n\n            return columns;\n        }\n\n        template <typename stream_type>\n        friend inline stream_type&\n            operator << (stream_type& stm, VolatilityDependence& v)\n        {\n                stm << v.inputVolatility_\n                    << \";\" << v.modelSigma_ << std::endl;\n\n                return stm;\n            }\n\n        Real inputVolatility_;\n        Real modelSigma_;\n    };\n\n    struct ModelData\n    {\n        ModelData()\n        : today_(15, February, 2002)\n        , settlement_(19, February, 2002)\n        , termStructure_(flatRate(settlement_, 0.04875825, Actual365Fixed()))\n        , model_(new HullWhite(termStructure_))\n        , index_(new Euribor6M(termStructure_))\n        , engine_(new JamshidianSwaptionEngine(model_))\n        , swaptions_()\n        , data_()\n        {\n            Settings::instance().evaluationDate() = today_;\n        }\n\n        void calibrationData(std::vector<cl::tape_double>& vol, std::vector<CalibrationData>& data)\n        {\n            Integer pos = 0;\n            Integer size = vol.size();\n            data.clear();\n            for (std::vector<cl::tape_double>::iterator it = vol.begin(); it != vol.end(); it++, pos++)\n            {\n                data.push_back(CalibrationData { pos + 1, size - pos, *it });\n            }\n        }\n\n        std::string getPath(Size calibrationType)\n        {\n            if (calibrationType == 1)\n                return \"\\\\TestCachedHullWhite\";\n            else\n                return \"\\\\TestCachedHullWhiteFixedReversion\";\n        }\n\n        // Calibration type 1: Testing Hull-White calibration against cached values using swaptions with start delay\n        // type 2: Testing Hull-White calibration with fixed reversion against cached values.\n        Real calibrate(std::vector<Real>& volatility\n                       , Size calibrationType)\n        {\n            std::vector<CalibrationData> data;\n            calibrationData(volatility, data);\n            Size sizeof_indep = data.size();\n            swaptions_.clear();\n            for (Size i = 0; i < sizeof_indep; i++)\n            {\n                boost::shared_ptr<Quote> volatil(new SimpleQuote(data[i].volatility_));\n                boost::shared_ptr<CalibrationHelper> helper(\n                    new SwaptionHelper(Period(data[i].start_, Years),\n                    Period(data[i].length_, Years),\n                    Handle<Quote>(volatil),\n                    index_,\n                    Period(1, Years), Thirty360(),\n                    Actual360(), termStructure_));\n                helper->setPricingEngine(engine_);\n                swaptions_.push_back(helper);\n            }\n\n            // Set up the optimization problem\n            // Real simplexLambda = 0.1;\n            // Simplex optimizationMethod(simplexLambda);\n            LevenbergMarquardt optimizationMethod(1.0e-8, 1.0e-8, 1.0e-8);\n            EndCriteria endCriteria(1000, 100, 1e-6, 1e-8, 1e-8);\n\n            // Optimize.\n            switch (calibrationType)\n            {\n\n                case 1:\n                    model_->calibrate(swaptions_, optimizationMethod, endCriteria);\n                    break;\n                case 2:\n                    model_->calibrate(swaptions_, optimizationMethod, endCriteria, Constraint(), std::vector<Real>(),\n                                     HullWhite::FixedReversion());\n                    // The difference is in the choice of  HullWhite::FixedReversion() to calibrate the model below.\n            }\n\n            return  model_->sigma();\n        }\n\n        void finiteDiff(std::vector<Real>& vol\n                          , Size calibrationType\n                          , double h\n                          , std::vector<Real>& sfFinite)\n        {\n            std::vector<Real>::iterator it;\n            std::vector<Real>::iterator it_fin;\n            for (it = vol.begin(), it_fin = sfFinite.begin(); it != vol.end(); it++, it_fin++)\n            {\n                *it -= h;\n                calibrate(vol, calibrationType);\n                cl::tape_double stepbackward = model_->sigma();\n                *it += 2 * h;\n                calibrate(vol, calibrationType);\n                cl::tape_double stepforward = model_->sigma();\n                *it_fin = (stepforward - stepbackward) / (2 * h);\n                *it -= h;\n            }\n        }\n\n        // Common data.\n        Date today_;\n        Date settlement_;\n        Handle<YieldTermStructure> termStructure_;\n        boost::shared_ptr<HullWhite> model_;\n        boost::shared_ptr<IborIndex> index_;\n        boost::shared_ptr<PricingEngine> engine_;\n        std::vector<boost::shared_ptr<CalibrationHelper>> swaptions_;\n        std::vector<CalibrationData> data_;\n\n    };\n\n    struct CachedHullWhiteTestData\n        : public ModelData\n    {\n        struct Test\n        : public cl::AdjointTest<Test>\n        {\n            Test(Size size, CachedHullWhiteTestData* data)\n            : size_(size)\n            , data_(data)\n            , volatility_(size)\n            , iterNumFactor_(1)\n            {\n                setLogger(&data_->outPerform_);\n\n                for (Size i = 0; i < size; i++)\n                    volatility_[i] = 0.1148 - 0.004*i;\n            }\n\n            Size indepVarNumber() { return size_;}\n\n            Size depVarNumber() { return 1; }\n\n            Size minPerfIteration() { return iterNumFactor_; }\n\n            void recordTape()\n            {\n                cl::Independent(volatility_);\n                calculateModelSigma();\n                f_ = std::make_unique<cl::tape_function<double>>(volatility_, modelSigma_);\n            }\n\n            // Calculates total calibration error.\n            void  calculateModelSigma()\n            {\n                modelSigma_.push_back(data_->calibrate(volatility_, data_->calibrationType_));\n            }\n\n            // Calculates derivatives using finite difference method.\n            void calcAnalytical()\n            {\n                // Shift for finite diff. method.\n                double h = 1.0e-3;\n                analyticalResults_.resize(size_);\n                data_->finiteDiff(volatility_, data_->calibrationType_, h, analyticalResults_);\n            }\n\n            double relativeTol() const { return 1e-2; }\n\n            double absTol() const { return 1e-2; }\n\n            Size size_;\n            Size iterNumFactor_;\n            CachedHullWhiteTestData* data_;\n            std::vector<cl::tape_double> volatility_;\n            std::vector<cl::tape_double> modelSigma_;\n        };\n\n        CachedHullWhiteTestData(Size calibrationType)\n            : ModelData()\n            , calibrationType_(calibrationType)\n\n            , outPerform_(OUTPUT_FOLDER_NAME + getPath(calibrationType)\n            , { { \"filename\", \"AdjointPerformance\" }\n              , { \"not_clear\", \"Not\" }\n              , { \"line_box_width\", \"-5\" }\n              , { \"cleanlog\", \"true\" }\n              , { \"title\", \"Model sigma differentiation performance with respect to calibration implied swaption volatilities\" }\n              , { \"xlabel\", \"Size of  calibration  volatilities vector\" }\n              , { \"ylabel\", \"Time (s)\" }\n              , { \"smooth\", \"12\" } })\n\n            , outAdjoint_(OUTPUT_FOLDER_NAME + getPath(calibrationType)\n            , { { \"filename\", \"Adjoint\" }\n              , { \"not_clear\", \"Not\" }\n              , { \"cleanlog\", \"false\" }\n              , { \"title\", \"Adjoint differentiation performance with respect to calibration implied swaption volatilities\" }\n              , { \"xlabel\", \"Size of  calibration  volatilities vector\" }\n              , { \"ylabel\", \"Time (s)\" }\n              , { \"smooth\", \"12\" } })\n\n            , outSize_(OUTPUT_FOLDER_NAME + getPath(calibrationType)\n            , { { \"filename\", \"TapeSize\" }\n              , { \"not_clear\", \"Not\" }\n              , { \"cleanlog\", \"false\" }\n              , { \"title\", \"Tape size dependence on  size of  calibration  volatilities vector\" }\n              , { \"xlabel\", \"Size of  calibration  volatilities vector\" }\n              , { \"ylabel\", \"Memory (MB)\" }\n              , { \"smooth\", \"12\" } })\n\n            , out_(OUTPUT_FOLDER_NAME + getPath(calibrationType) + \"//output\"\n            , { { \"filename\", \"SigmaonVolatil\" }\n              , { \"not_clear\", \"Not\" }\n              , { \"title\", \"Model sigma on calibration swaption implied volatilty dependence\" }\n              , { \"xlabel\", \"Volatility\" }\n              , { \"ylabel\", \"Model Sigma\" }\n              , { \"cleanlog\", \"false\" } })\n\n#if defined CL_GRAPH_GEN\n            , pointNo_(20)\n            , iterNo_(20)\n            , step_(1)\n#else\n            , pointNo_(1)\n            , iterNo_(1)\n            , step_(1)\n#endif\n        {\n        }\n\n        bool makeOutput()\n        {\n            bool ok = true;\n            if (pointNo_ > 0)\n            {\n                ok &= recordDependencePlot();\n            }\n            ok &= cl::recordPerformance(*this, iterNo_, step_);\n            return ok;\n        }\n\n        std::shared_ptr<Test> getTest(size_t size)\n        {\n            return std::make_shared<Test>(size + 4, this);\n        }\n\n        // Makes plots for strike sensitivity dependence.\n        bool recordDependencePlot()\n        {\n            std::vector<VolatilityDependence> outData(pointNo_);\n            auto test = getTest(pointNo_);\n            for (Size i = 0; i < pointNo_; i++)\n            {\n                Real vol = 0.06 + 0.0003*i*5;\n                test->volatility_[0] = vol;\n                outData[i] = { vol, test->data_->calibrate(test->volatility_, test->data_->calibrationType_) };\n            }\n            out_ << outData;\n\n            // Reset volatility_[0] to initial value.\n            test->volatility_[0] = 0.1148;\n\n            return true;\n        }\n\n        Size pointNo_;\n        Size iterNo_;\n        Size step_;\n\n        Size calibrationType_;\n\n        cl::tape_empty_test_output outPerform_;\n        cl::tape_empty_test_output outAdjoint_;\n        cl::tape_empty_test_output outSize_;\n        cl::tape_empty_test_output out_;\n    };\n    typedef CachedHullWhiteTestData::Test CachedHullWhiteTest;\n\n    struct FuturesConvexityBiasTest\n        : public cl::AdjointTest<FuturesConvexityBiasTest>\n    {\n        FuturesConvexityBiasTest()\n        : iterNumFactor_(1)\n        , futureQuote_(94.0)\n        , a_(0.03)\n        , sigma_(0.015)\n        , t_(5.0)\n        , T_(5.25)\n        , parameters_(3)\n        , calculatedFunction_(1)\n        {\n            parameters_ = { a_, sigma_, futureQuote_ };\n        }\n\n        Size indepVarNumber() { return 3; }\n\n        Size depVarNumber() { return 1; }\n\n        Size minPerfIteration() { return iterNumFactor_; }\n\n        void recordTape()\n        {\n            cl::Independent(parameters_);\n            calculateFunction();\n            f_ = std::make_unique<cl::tape_function<double>>(parameters_, calculatedFunction_);\n        }\n\n        void calculateFunction()\n        {\n            calculatedFunction_[0] = (100.0 - parameters_[2]) / 100.0 -\n                HullWhite::convexityBias(parameters_[2], t_, T_, parameters_[1], parameters_[0]);\n        }\n\n        // Calculates derivatives using finite difference method.\n        void calcAnalytical()\n        {\n            double h = 1e-4;\n            Size size = indepVarNumber();\n            analyticalResults_.resize(size);\n            for (Size i = 0; i < size; i++)\n            {\n                parameters_[i] -= h;\n                Real stepbackward = (100.0 - parameters_[2]) / 100.0 -\n                    HullWhite::convexityBias(parameters_[2], t_, T_, parameters_[1], parameters_[0]);\n                parameters_[i] += 2 * h;\n                Real stepforward = (100.0 - parameters_[2]) / 100.0 -\n                    HullWhite::convexityBias(parameters_[2], t_, T_, parameters_[1], parameters_[0]);\n                analyticalResults_[i] = (stepforward - stepbackward) / (2 * h);\n                parameters_[i] -= h;\n            }\n\n        }\n\n        double relativeTol() const { return 1e-2; }\n\n        double absTol() const { return 1e-4; }\n\n        Size iterNumFactor_;\n\n        Real futureQuote_;\n        Real a_;\n        Real sigma_;\n        Time t_;\n        Time T_;\n\n        std::vector<cl::tape_double> parameters_;\n        std::vector<cl::tape_double> calculatedFunction_;\n    };\n}\n\n#endif", "meta": {"hexsha": "be616f30f4cb849ee2418ccf7f8c895133b75eb7", "size": 14116, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test-suite-adjoint/adjointshortratemodelsimpl.hpp", "max_stars_repo_name": "fduffy/QuantLibAdjoint", "max_stars_repo_head_hexsha": "d9d355db4f46824bb5e607e28381943aef994ed4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 41.0, "max_stars_repo_stars_event_min_datetime": "2016-03-19T02:31:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T13:23:20.000Z", "max_issues_repo_path": "test-suite-adjoint/adjointshortratemodelsimpl.hpp", "max_issues_repo_name": "fduffy/QuantLibAdjoint", "max_issues_repo_head_hexsha": "d9d355db4f46824bb5e607e28381943aef994ed4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test-suite-adjoint/adjointshortratemodelsimpl.hpp", "max_forks_repo_name": "fduffy/QuantLibAdjoint", "max_forks_repo_head_hexsha": "d9d355db4f46824bb5e607e28381943aef994ed4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2016-03-17T14:14:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T10:33:19.000Z", "avg_line_length": 33.7703349282, "max_line_length": 128, "alphanum_fraction": 0.5443468405, "num_tokens": 3211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.48600126282761097}}
{"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_FUNCTION_ABS_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_ABS_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n  @ingroup group-arithmetic\n    Function object implementing abs capabilities\n\n    Computes the absolute value of its parameter.\n\n    @par Semantic\n\n    For any value @c x of type @c T,\n\n    @code\n    T r = abs(x);\n    @endcode\n\n    is equivalent to:\n\n    @code\n    T r = x < T(0) ? -x : x;\n    @endcode\n\n    @par Note:\n\n    - Take care that for signed integers the absolute value of @ref Valmin is\n    @ref Valmin (thus negative!). This is a side effect of the 2-complement\n    representation of integers. To avoid this, you can use the abss\n    saturated functor or convert the input parameter to a larger type\n    before taking the absolute value.\n\n    - Also abs is a very current function name and sometimes a C macro version can be\n    an unwanted concurrent of simd::abs, you can just prefix abs or\n    use the alias modulus or fabs instead to circumvent this problem.\n\n    @par Alias\n\n    modulus, fabs\n\n    @par Decorators\n\n    std_ for floating entries\n\n    @see  abss, sqr_abs, sqrs\n\n  **/\n  const boost::dispatch::functor<tag::abs_> abs = {};\n} }\n#endif\n\n#include <boost/simd/function/scalar/abs.hpp>\n#include <boost/simd/function/simd/abs.hpp>\n\n#endif\n", "meta": {"hexsha": "c48078f506ef5edd3c6b7c5e7828264ea104da7e", "size": 1747, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/abs.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/function/abs.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/function/abs.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": 24.9571428571, "max_line_length": 100, "alphanum_fraction": 0.6199198626, "num_tokens": 400, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.4860012600819103}}
{"text": "// main.cpp\n// Used to write exploratory/behavioural tests for CSVParser\n\n#include \"CSVParser.hpp\"\n#include \"LeastSquaresFit.hpp\"\n#include <iostream>\n#include <memory> // shared pointers\n#include <unistd.h> // usleep\n#include <boost/program_options.hpp>\n#include <chrono>\n\nvoid usage() {\n\tstd::cout << \"Example usage:\\n\"\n\t\t<< \"CSVParser_tester --filename census_2000_all_places_sample_dimensions.csv --header SE_T001_001 --header_row_index 1 --first_data_row_index 2\\n\" << std::endl;\n}\n\nint main( int argc, char **argv ) {\n\t// program arg variables\n\tstd::string \tfilename;\n\tstd::string \theader;\n\tindex_type header_row_index;\n\tindex_type  first_data_row_index;\n\n\t// ********* start of boost::program_options code ****************\n\tnamespace po = boost::program_options;\n\tpo::options_description desc(\"Options\");\n\tdesc.add_options()\n\t\t(\"help\", \"Print help messages\")\n\t\t(\"filename\", po::value<std::string>(&filename)->required(), \n\t\t\t\"CSV filename including file extension\")\n\t\t(\"header\", po::value<std::string>(&header)->required(), \n\t\t\t\"unique header of column\")\n\t\t(\"header_row_index\", po::value<index_type>(&header_row_index)->required(), \n\t\t\t\"index of row header is located on\")\n\t\t(\"first_data_row_index\", po::value<index_type>(&first_data_row_index)->required(), \n\t\t\t\"index of first row of actual data\");\n\t\n\tpo::variables_map vm;\n\ttry{\n\t\tpo::store(po::parse_command_line(argc, argv, desc), vm);\n\t\tif(argc == 1) {\n\t\t\tusage();\n\t\t\tstd::cout << desc << std::endl;\n\t\t\treturn 0;\n\t\t}\n\n\t\tif (vm.count(\"help\") )\n\t\t{ \n\t\t\tstd::cout << \"Progressive Analytics Application\" << std::endl \n\t\t\t\t\t  << desc << std::endl; \n\t\t\treturn 0; \n\t\t} \n\t\n      po::notify(vm); // throws on error, so do after help in case \n                      // there are any problems \n    } \n    catch(po::error& e) \n    { \n      std::cerr << \"ERROR: \" << e.what() << std::endl << std::endl; \n      std::cerr << desc << std::endl; \n      return 1; \n    } \n\t// ********* end of boost::program_options code ****************\n\n\tconstexpr unsigned char DELIM {','};\n\tstd::shared_ptr<CSVParser> t1;\n\ttry {\n\t\t t1 = std::make_shared<CSVParser>(makeCSVParser(filename, DELIM));\n\t} catch(const std::runtime_error &e) {\n\t\tstd::cout << e.what() << std::endl;\n\t\treturn 2;\n\t}\n\tColumnData<int_data_type> results;\n\n\t// Set up values to perform a one-hit analysis\n\t{\n\t\tindex_type num_segments {1};\n\t\tstd::vector<ColumnData<int_data_type>> result_cds;\n\t\ttry{\n\t\t\tresult_cds = t1->makeSegments<int_data_type>(\n\t\t\t\theader, header_row_index, first_data_row_index, num_segments);\n\t\t}catch (std::runtime_error &e) {\n\t\t\tstd::cout << e.what() << std::endl;\n\t\t\treturn 3;\n\t\t}\n\t\tt1->runAnalysisSegment(result_cds.at(0));\n\n\t\tstd::cout << \"result of one-hit analysis: \" << result_cds.at(0).data_summary_actual << '\\n' << std::endl;\n\t}\n\n\t// Set up values to perform a progressive analysis\n\t// Note: This only creates ColumnData segments, it\n\t// does not perform any calculations\n\t{\n\t\tindex_type num_segments {5};\n\t\tstd::vector<ColumnData<int_data_type>> result_cds;\n\t\ttry{\n\t\t\tresult_cds = t1->makeSegments<int_data_type>(\n\t\t\t\theader, header_row_index, first_data_row_index, num_segments);\n\t\t}catch (std::runtime_error &e) {\n\t\t\tstd::cout << e.what() << std::endl;\n\t\t\treturn 3;\n\t\t}\n\n\t\tstd::cout << \"******************************************\" << std::endl;\n\t\tstd::cout << \"printing contents of progressive analysis:\" << std::endl;\n\t\tstd::cout << \"******************************************\" << std::endl;\n\n\t\tint_data_type sum{};\n\t\tfor(auto &cur_res : result_cds) {\n\t\t\tt1->runAnalysisSegment(cur_res);\n\t\t\tstd::cout << cur_res << '\\n' << std::endl;\n\t\t\tsum += cur_res.data_summary_actual;\n\t\t}\n\t\tstd::cout << \"Final sum: \" << sum << std::endl;\n\t}\n\n\n\t// Performing a progressive analysis using LeastSquaresFit class\n\tstd::string X_header {\"SE_T003_001\"};\n\tstd::string Y_header {\"SE_T013_001\"};\n\t\n\n\tauto Xs = t1->makeSegments<float_data_type>(X_header, header_row_index, first_data_row_index, 5);\n\tauto Ys = t1->makeSegments<float_data_type>(Y_header, header_row_index, first_data_row_index, 5);\n\tstd::cout << \"Xs size: \" << Xs.size() << std::endl;\n\tstd::cout << \"Ys size: \" << Ys.size() << std::endl;\n\tstd::cout << \"X_bar: \" << calcAvg(Xs) << std::endl;\n\tstd::cout << \"Y_bar: \" << calcAvg(Ys) << std::endl;\n\tstd::cout << \"\\n\" << std::endl;\n\n\tusing vec_cols_float = std::vector<ColumnData<float_data_type>>;\n\tLeastSquaresFit<vec_cols_float, vec_cols_float> lsf = \n\t\tmakeLeastSquaresFit<vec_cols_float, vec_cols_float>(Xs, Ys);\n\n\t// Display results/projections after each segment is processed\n\tstd::cout << lsf << \"\\n\\n\" << std::endl;\n\tconstexpr int_data_type usecs {2000000}; // microseconds\n\tstd::cout << \"Displaying projections during progressive analysis:\" << std::endl; \n\twhile(lsf.calcNextProjection()) {\n\t\tauto start = std::chrono::system_clock::now();\n\t\tstd::cout << '\\r' << \"a: \" << lsf.getProja() << \" b: \" << lsf.getProjb();\n\t\tauto end = std::chrono::system_clock::now();\n\t\tauto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start);\n\n\t\tstd::cout << \" elapsed: \" << elapsed.count() << \" ns\" << std::flush;\n\t\tusleep(usecs);\n\t}\n\tstd::cout << \"\\nProgram closing\" << std::endl;\n\treturn 0;\n}\n", "meta": {"hexsha": "5cb9ef509c2d5a6d2e4d624fc2233ef5920f4212", "size": 5137, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "app/main.cpp", "max_stars_repo_name": "Dusty-M/CSC_499_Integrated_Analytics", "max_stars_repo_head_hexsha": "2c7a4f279b6c5ff097d872a7ca15cc4f136439dc", "max_stars_repo_licenses": ["MIT"], "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/main.cpp", "max_issues_repo_name": "Dusty-M/CSC_499_Integrated_Analytics", "max_issues_repo_head_hexsha": "2c7a4f279b6c5ff097d872a7ca15cc4f136439dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-05-04T02:11:23.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-04T02:11:23.000Z", "max_forks_repo_path": "app/main.cpp", "max_forks_repo_name": "Dusty-M/CSC_499_Progressive_Analytics", "max_forks_repo_head_hexsha": "2c7a4f279b6c5ff097d872a7ca15cc4f136439dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-04-20T22:55:22.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-20T22:55:22.000Z", "avg_line_length": 33.7960526316, "max_line_length": 162, "alphanum_fraction": 0.6457076114, "num_tokens": 1444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548646660543, "lm_q2_score": 0.7461389817407016, "lm_q1q2_score": 0.48600125547378226}}
{"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_FEATURES_MATCHING_HARRIS_CORNER_DETECTOR_HPP\n#define PIC_FEATURES_MATCHING_HARRIS_CORNER_DETECTOR_HPP\n\n#include \"../util/vec.hpp\"\n#include \"../util/std_util.hpp\"\n#include \"../image.hpp\"\n#include \"../filtering/filter_luminance.hpp\"\n#include \"../filtering/filter_gaussian_2d.hpp\"\n#include \"../filtering/filter_gradient_harris_opt.hpp\"\n#include \"../filtering/filter_max.hpp\"\n#include \"../features_matching/general_corner_detector.hpp\"\n\n#ifndef PIC_DISABLE_EIGEN\n\n#ifndef PIC_EIGEN_NOT_BUNDLED\n    #include \"../externals/Eigen/Dense\"\n#else\n    #include <Eigen/Dense>\n#endif\n\n#endif\n\nnamespace pic {\n\n#ifndef PIC_DISABLE_EIGEN\n\n/**\n * @brief The HarrisCornerDetector class\n */\nclass HarrisCornerDetector: public GeneralCornerDetector\n{\nprotected:\n    Image *I_grad;\n    Image *I_grad_flt;\n    Image *ret;\n\n    //Harris Corners detector parameters\n    float sigma, threshold;\n    int radius;\n\n    //previous values\n    int width, height;\n\n    /**\n     * @brief release\n     */\n    void release()\n    {\n        lum = delete_s(lum);\n        I_grad = delete_s(I_grad);\n        I_grad_flt = delete_s(I_grad_flt);\n        ret = delete_s(ret);\n    }\n\n    /**\n     * @brief setNULL\n     */\n    void setNULL()\n    {\n        width = -1;\n        height = -1;\n        lum = NULL;\n        I_grad = NULL;\n        I_grad_flt = NULL;\n        ret = NULL;        \n    }\n\npublic:\n\n    /**\n     * @brief HarrisCornerDetector\n     * @param sigma\n     * @param radius\n     * @param threshold\n     */\n    HarrisCornerDetector(float sigma = 1.0f, int radius = 3, float threshold = 0.001f) : GeneralCornerDetector()\n    {\n        setNULL();\n        update(sigma, radius, threshold);\n    }\n\n    ~HarrisCornerDetector()\n    {\n        release();\n    }\n\n    /**\n     * @brief update\n     * @param sigma\n     * @param radius\n     * @param threshold\n     */\n    void update(float sigma = 1.0f, int radius = 3, float threshold = 0.001f)\n    {\n        this->sigma = sigma > 0.0f ? sigma : 1.0f;\n        this->radius = radius > 0 ? radius : 1;\n        this->threshold = threshold > 0.0f ? threshold : 0.001f;\n    }\n\n    /**\n     * @brief execute\n     * @param img\n     * @param corners\n     */\n    void execute(Image *img, std::vector< Eigen::Vector2f > *corners)\n    {\n        if(img == NULL || corners == NULL) {\n            return;\n        }\n\n        if((img->width != width) || (img->height != height)) {\n            width = img->width;\n            height = img->height;\n\n            release();\n        }\n\n        if(img->channels == 1) {\n            lum = img->clone();\n        } else {\n            lum = FilterLuminance::execute(img, lum, LT_CIE_LUMINANCE);\n        }\n\n        float minL, maxL;\n        lum->getMinVal(NULL, &minL);\n        lum->getMaxVal(NULL, &maxL);\n\n        float delta = maxL - minL;\n\n        *lum -= minL;\n        *lum *= delta;\n\n        corners->clear();\n\n        std::vector< Eigen::Vector3f > corners_w_quality;\n\n        //compute gradients\n        I_grad = FilterGradientHarrisOPT::execute(lum, I_grad, 0);\n\n        float eps = 2.2204e-16f;\n\n        //filter gradient values\n        FilterGaussian2D flt(sigma);\n        I_grad_flt = flt.Process(Single(I_grad), I_grad_flt);\n\n        if(ret == NULL) {\n            ret = lum->allocateSimilarOne();\n        }\n\n        //ret = (Ix2.*Iy2 - Ixy.^2)./(Ix2 + Iy2 + eps);\n        for(int i = 0; i < height; i++) {\n            for(int j = 0; j < width; j++) {\n                float *data_ret = (*ret)(j, i);\n\n                float *I_grad_val = (*I_grad_flt)(j, i);\n\n                float x2 = I_grad_val[0];\n                float y2 = I_grad_val[1];\n                float xy = I_grad_val[2];\n\n                data_ret[0] =  (x2 * y2 - xy * xy) / (x2 + y2 + eps);\n            }\n        }\n\n        //non-maximal supression\n        lum = FilterMax::execute(ret, lum, radius * 2 + 1);\n        Image* ret_flt = lum;\n\n        float w = 1.0f;\n\n        if(threshold < 0.0f) { //the best i-th points\n            int bestPoints = int(-threshold);\n\n            float *tmp = ret->sort();\n\n            int n = ret->size();\n            threshold = tmp[n - 1 - bestPoints];\n\n            delete_vec_s(tmp);\n        }\n\n        for(int i = 0; i < height; i++) {\n            float i_f = float(i);\n            float cx, cy, ax, ay, bx, by, x, y;\n\n            for(int j = 0; j < width; j++) {\n\n                float R = (*ret)(j, i)[0];\n                float R_flt = (*ret_flt)(j, i)[0];\n\n                if((R == R_flt) && (R > threshold)) {\n                    float Rr = (*ret)(j, i + 1)[0];\n                    float Rl = (*ret)(j, i - 1)[0];\n                    float Ru = (*ret)(j + 1, i)[0];\n                    float Rd = (*ret)(j - 1, i)[0];\n\n                    cx = R;\n                    ax = (Rl + Rr) / 2.0f - cx;\n                    bx = ax + cx - Rl;\n\n                    if(ax != 0.0f) {\n                        x = -w * bx / (2.0f * ax);\n                    } else {\n                        x = 0.0f;\n                    }\n\n                    cy = R;\n                    ay = (Rd + Ru) / 2.0f - cy;\n                    by = ay + cy - Rd;\n\n                    if(ay != 0.0f) {\n                        y = -w * by / (2.0f * ay);\n                    } else {\n                        y = 0.0f;\n                    }\n\n                    corners_w_quality.push_back(Eigen::Vector3f(float(j) + x, i_f + y, R));\n                }\n            }\n        }\n\n        sortCornersAndTransfer(&corners_w_quality, corners);\n    }\n};\n\n#endif\n\n} // end namespace pic\n\n#endif /* PIC_FEATURES_MATCHING_HARRIS_CORNER_DETECTOR_HPP */\n\n", "meta": {"hexsha": "6be196331c177cd801d2b7bf2d95fa612fc4b5b2", "size": 5950, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/features_matching/harris_corner_detector.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/features_matching/harris_corner_detector.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/features_matching/harris_corner_detector.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": 23.8955823293, "max_line_length": 112, "alphanum_fraction": 0.4981512605, "num_tokens": 1627, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389817407016, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.4860012453742535}}
{"text": "#ifndef NEURAL_NET_HPP_\n#define NEURAL_NET_HPP_\n\n#include <armadillo>\n#include <config.h>\n#include <string>\n#include \"util.hpp\"\n#include \"mnist.hpp\"\n\n#include <algorithm>\n#include <random>\n#include <vector>\n#include <numeric>\n\n// Apply sigmoid to all elements\ntemplate<typename T>\nvoid sigmoid(T&& out) {\n    out.transform([](typename T::elem_type val) {\n        return (1.0 / (1.0 + exp (-1.0 * val)));\n    });\n}\n\n/**\n * Simple two-layer neural network for the MNIST data set\n *\n * \\code\n * auto train_net = neural_net<float>(train_data, 0.1);\n * \\endcode\n */\ntemplate<typename T = float>\nstruct neural_net {\n    using elem_t = T;\n    using mat_t = arma::Mat<elem_t>;\n    using vec_t = arma::Col<elem_t>;\n    using subview_t = arma::subview<elem_t>;\n    using mnist = mnist<elem_t>;\n\n    const mnist input;    //< Input data\n    const elem_t lambda;  //< Regularization parameter\n    mat_t theta1;         //< Weights for layer 1\n    mat_t theta2;         //< Weights for layer 2\n    mat_t a1;             //< Input activations\n    mat_t a2;             //< Output activations from layer 1\n    mat_t a3;             //< Output activations from layer 2\n    mat_t yy;             //< One-hot vector for labels\n    mat_t d_theta1;       //< Gradient for layer 1 weights\n    mat_t d_theta2;       //< Gradient for layer 2 weights\n    mat_t delta3;         //< Gradient from output to labels\n    mat_t delta2;         //< Gradient from layer 2 to layer 1 activations\n\n    /**\n     * Constructor\n     *\n     * @param input_   MNIST inut data\n     * @param lambda_  lambda value for regularization. Set to 0 for no\n     *                 regularization\n     */\n    neural_net(const mnist& input_, elem_t lambda_ = 1)\n    : input(input_),\n      lambda(lambda_) {\n        using rowvec = arma::Row<elem_t>;\n        using arma::zeros;\n        using arma::ones;\n        using arma::randu;\n\n        elem_t epsilon = 0.12;\n        theta1 = (randu<mat_t>(64, input.images.n_cols + 1) * 2 - 1) * epsilon;\n        theta2 = (randu<mat_t>(10, theta1.n_rows + 1) * 2 - 1) * epsilon;\n\n        // Convert the column vector of y labels to a matrix where each\n        // row has a 1 in the column specified by the label.\n        yy = zeros<mat_t>(input.labels.n_rows, 11);\n        int row = 0;\n        input.labels.for_each([&](const elem_t& element) {\n            yy(row, element) = 1.0;\n            yy(row, 0) = 1.0;\n            row++;\n        });\n\n        // Allocate space for each layer of activations. Add an additional\n        // column for the bias neuron\n        a1 = ones<mat_t>(input.images.n_rows, input.images.n_cols + 1);\n        a2 = ones<mat_t>(input.images.n_rows, theta1.n_rows + 1);\n        a3 = ones<mat_t>(input.images.n_rows, theta2.n_rows + 1);\n\n        // Load the images onto first activation layer, but do not overwrite\n        // the bias neuron\n        no_bias(a1) = input.images;\n\n        //shuffle_a1_yy();\n    }\n\n\n    /**\n     * Use the neural network to predict outcomes\n     *\n     * @return The percentage of correct predictions\n\n     */\n    elem_t predict(void) const {\n        feed_forward();\n\n        // Find neuron with maximum confidence, this is our predicted label\n        arma::ucolvec predictions = index_max(no_bias(a3), 1);\n        predictions = predictions + 1;\n\n        // Display percentage of correct labels\n        return elem_t(sum(predictions == input.labels)) / input.labels.n_rows;\n    }\n\n    /**\n     * Cost function for the neural net\n     *\n     * @return the cost\n     */\n    elem_t cost() const {\n        // Cost, without regularization\n        elem_t cost = sum(sum(\n            -1 * no_bias(yy) % log(no_bias(a3)) -\n                (1 - no_bias(yy)) % log(1 - no_bias(a3)), 1))\n            / input.images.n_rows;\n\n        // Cost, with regularization\n        if (std::abs(lambda) > 0) {\n            // Square each element. This next operation makes a copy\n            mat_t theta1_sq = square(no_bias(theta1));\n            mat_t theta2_sq = square(no_bias(theta2));\n\n            // Sum up all elements in each layer\n            elem_t reg = (sum(sum(theta1_sq)) + sum(sum(theta2_sq)));\n\n            // Normalize\n            reg *= lambda / (2 * input.images.n_rows);\n\n            // Add in regularization term\n            cost += reg;\n        }\n\n        return cost;\n    }\n\n    /**\n     * Calculate the gradient for the weights\n     */\n    void gradient() {\n        elem_t m = a1.n_rows;\n\n        // Delta from labeled data to current set of predictions\n        delta3 = a3 - yy;\n        d_theta2 = (no_bias(delta3).t() * a2) / m;\n\n        // Delta from output layer to hidden layer\n        delta2 = no_bias(delta3) * theta2 % (a2 % (1 - a2));\n\n        // Delta from output layer to hidden layer without bias\n        d_theta1 = (no_bias(delta2).t() * a1) / m;\n\n        // Regularization\n        if (std::abs(lambda) > 0) {\n            no_bias(d_theta1) += (lambda / m) * no_bias(theta1);\n            no_bias(d_theta2) += (lambda / m) * no_bias(theta2);\n        }\n    }\n\n    /**\n     * A single Forward propogation step for the neural net\n     */\n    void feed_forward() const {\n        // Pass input thru weights to second layer, do not disturb the bias\n        // neuron\n        no_bias(a2) = a1 * theta1.t();\n        sigmoid(no_bias(a2));\n\n        // Pass hidden layer to output layer\n        no_bias(a3) = a2 * theta2.t();\n        sigmoid(no_bias(a3));\n    }\n\n    /**\n     * Train the neural network. Pass in a number of steps and a progress\n     * function.\n     *\n     * \\code\n     * net.train(1000, [&](size_t i, size_t max_itr) -> void {\n     *     if (i == 0 || i % 100 == 0 || i == max_itr - 1) {\n     *         std::cout << \"\\r \" << i << \" j = \" << train_net.cost()\n     *                   << std::flush;\n     *     }\n     * });\n     * \\endcode\n     *\n     * @param steps    The number of steps to train\n     * @param progress Function called after each step.\n     */\n    void train(size_t steps, std::function<void(size_t, size_t)> progress) {\n        for (size_t i = 0; i < steps; i++) {\n            feed_forward();\n            // Back prop\n            gradient();\n            theta1 -= d_theta1;\n            theta2 -= d_theta2;\n            progress(i, steps);\n        }\n    }\n\n    /**\n     * Save the weights to two files\n     */\n    void save() const {\n        std::string theta1_fn = data_dir + \"/theta1.bin\";\n        std::string theta2_fn = data_dir + \"/theta2.bin\";\n        theta1.save(theta1_fn);\n        theta2.save(theta2_fn);\n    }\n\n    /**\n     * Shuffle the rows of the input and label matrices\n     */\n    void shuffle_a1_yy() {\n        using std::iota;\n        using std::vector;\n        using std::shuffle;\n        using std::begin;\n        using std::end;\n\n        vector<size_t> indices(a1.n_rows);\n        iota(begin(indices), end(indices), 0);\n\n        auto rng = std::default_random_engine {};\n        shuffle(begin(indices), end(indices), rng);\n\n        mat_t a1_shfl(a1.n_rows, a1.n_cols);\n        mat_t yy_shfl(yy.n_rows, yy.n_cols);\n\n        for (size_t dst_idx = 0; dst_idx < indices.size(); ++dst_idx) {\n            size_t src_idx = indices[dst_idx];\n            a1_shfl.row(dst_idx) = a1.row(src_idx);\n            yy_shfl.row(dst_idx) = yy.row(src_idx);\n        }\n\n        a1 = a1_shfl;\n        yy = yy_shfl;\n    }\n};\n\n#endif /* end of include guard: NEURAL_NET_HPP_ */\n", "meta": {"hexsha": "62ff69045d7c33d322a3acdc695c55395aa00aa4", "size": 7347, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "neural_net.hpp", "max_stars_repo_name": "riskybacon/mnist_arma", "max_stars_repo_head_hexsha": "4921686adf2382d7fb87d41d25d5e7e6342e6ec3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-05-27T12:54:01.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-27T12:54:01.000Z", "max_issues_repo_path": "neural_net.hpp", "max_issues_repo_name": "riskybacon/mnist_arma", "max_issues_repo_head_hexsha": "4921686adf2382d7fb87d41d25d5e7e6342e6ec3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "neural_net.hpp", "max_forks_repo_name": "riskybacon/mnist_arma", "max_forks_repo_head_hexsha": "4921686adf2382d7fb87d41d25d5e7e6342e6ec3", "max_forks_repo_licenses": ["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.7449392713, "max_line_length": 79, "alphanum_fraction": 0.5558731455, "num_tokens": 1914, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.48593359052279467}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2015 NumScale SAS\n  @copyright 2015 J.T. Lapreste\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_REMAINDER_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_REMAINDER_HPP_INCLUDED\n\n#include <boost/simd/function/div.hpp>\n#include <boost/simd/function/idiv.hpp>\n#include <boost/simd/function/is_nez.hpp>\n#include <boost/simd/function/minus.hpp>\n#include <boost/simd/function/multiplies.hpp>\n#include <boost/simd/function/selsub.hpp>\n#include <boost/dispatch/function/overload.hpp>\n#include <boost/config.hpp>\n// As the result can be negative the functor is not defined for unsigned\n// The drem function is just an alias for the same thing.\n// The remainder() function computes the remainder of dividing x by y.  The\n// entries\n// integer.  If the boost::simd::absolute value of x-n*y is 0.5, n is chosen\n// return value is x-n*y, where n is the value x / y, rounded to the nearest\n// to be even.\n/////////////////////////////////////////////////////////////////////////////\n/////////////////////////////////////////////////////////////////////////////\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  BOOST_DISPATCH_OVERLOAD ( remainder_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::generic_< bd::signed_<A0> >\n                          , bd::generic_< bd::signed_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() ( A0 a0, A0 a1) const BOOST_NOEXCEPT\n    {\n      return selsub(is_nez(a1),a0,\n                    simd::multiplies(idiv(a0, a1, round2even), a1));\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( remainder_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::generic_< bd::floating_<A0> >\n                          , bd::generic_< bd::floating_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() ( A0 a0, A0 a1) const BOOST_NOEXCEPT\n    {\n      return a0-div(a0, a1, round2even)*a1;\n    }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "d75c263230bacf892fe821240f4af76906473a03", "size": 2408, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arch/common/scalar/function/remainder.hpp", "max_stars_repo_name": "yaeldarmon/boost.simd", "max_stars_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/simd/arch/common/scalar/function/remainder.hpp", "max_issues_repo_name": "yaeldarmon/boost.simd", "max_issues_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/arch/common/scalar/function/remainder.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": 36.4848484848, "max_line_length": 100, "alphanum_fraction": 0.528654485, "num_tokens": 525, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.6187804407739559, "lm_q1q2_score": 0.4859335898252967}}
{"text": "#include <fc/uint128.hpp>\n#include <fc/io/raw_fwd.hpp>\n#include <fc/variant.hpp>\n#include <fc/crypto/bigint.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n\n#include <stdexcept>\n#include \"byteswap.hpp\"\n\nnamespace fc \n{\n    typedef boost::multiprecision::uint128_t  m128;\n\n    template <typename T>\n    static void divide(const T &numerator, const T &denominator, T &quotient, T &remainder) \n    {\n      static const int bits = sizeof(T) * 8;//CHAR_BIT;\n\n      if(denominator == 0) {\n        throw std::domain_error(\"divide by zero\");\n      } else {\n        T n      = numerator;\n        T d      = denominator;\n        T x      = 1;\n        T answer = 0;\n\n\n        while((n >= d) && (((d >> (bits - 1)) & 1) == 0)) {\n          x <<= 1;\n          d <<= 1;\n        }\n\n        while(x != 0) {\n          if(n >= d) {\n            n -= d;\n            answer |= x;\n          }\n\n          x >>= 1;\n          d >>= 1;\n        }\n\n        quotient = answer;\n        remainder = n;\n      }\n    }\n\n    uint128::uint128(const std::string &sz) \n    :hi(0), lo(0) \n    {\n      // do we have at least one character?\n      if(!sz.empty()) {\n        // make some reasonable assumptions\n        int radix = 10;\n        bool minus = false;\n\n        std::string::const_iterator i = sz.begin();\n\n        // check for minus sign, i suppose technically this should only apply\n        // to base 10, but who says that -0x1 should be invalid?\n        if(*i == '-') {\n          ++i;\n          minus = true;\n        }\n\n        // check if there is radix changing prefix (0 or 0x)\n        if(i != sz.end()) {\n          if(*i == '0') {\n            radix = 8;\n            ++i;\n            if(i != sz.end()) {\n              if(*i == 'x') {\n                radix = 16;\n                ++i;\n              }\n            }\n          }\n\n          while(i != sz.end()) {\n            unsigned int n = 0;\n            const char ch = *i;\n\n            if(ch >= 'A' && ch <= 'Z') {\n              if(((ch - 'A') + 10) < radix) {\n                n = (ch - 'A') + 10;\n              } else {\n                break;\n              }\n            } else if(ch >= 'a' && ch <= 'z') {\n              if(((ch - 'a') + 10) < radix) {\n                n = (ch - 'a') + 10;\n              } else {\n                break;\n              }\n            } else if(ch >= '0' && ch <= '9') {\n              if((ch - '0') < radix) {\n                n = (ch - '0');\n              } else {\n                break;\n              }\n            } else {\n              /* completely invalid character */\n              break;\n            }\n\n            (*this) *= radix;\n            (*this) += n;\n\n            ++i;\n          }\n        }\n\n        // if this was a negative number, do that two's compliment madness :-P\n        if(minus) {\n          *this = -*this;\n        }\n      }\n    }\n\n\n    uint128::operator bigint()const\n    {\n       auto tmp  = uint128( bswap_64( hi ), bswap_64( lo ) );\n       bigint bi( (char*)&tmp, sizeof(tmp) );\n       return bi;\n    }\n    uint128::uint128( const fc::bigint& bi )\n    {\n       *this = uint128( std::string(bi) ); // TODO: optimize this...\n    }\n\n    uint128::operator std::string ()const\n    {\n      if(*this == 0) { return \"0\"; }\n\n      // at worst it will be size digits (base 2) so make our buffer\n      // that plus room for null terminator\n      static char sz [128 + 1];\n       sz[sizeof(sz) - 1] = '\\0';\n\n      uint128 ii(*this);\n      int i = 128 - 1;\n\n      while (ii != 0 && i) {\n\n      uint128 remainder;\n      divide(ii, uint128(10), ii, remainder);\n          sz [--i] = \"0123456789abcdefghijklmnopqrstuvwxyz\"[remainder.to_integer()];\n      }\n\n      return &sz[i];\n    }\n\n\n    uint128& uint128::operator<<=(const uint128& rhs) \n    {\n        if(rhs >= 128) \n        {\n          hi = 0;\n          lo = 0;\n        } \n        else \n        {\n          unsigned int n = rhs.to_integer();\n          const unsigned int halfsize = 128 / 2;\n        \n            if(n >= halfsize){\n                n -= halfsize;\n                hi = lo;\n                lo = 0;\n            }\n        \n            if(n != 0) {\n            // shift high half\n                hi <<= n;\n        \n            const uint64_t mask(~(uint64_t(-1) >> n));\n        \n            // and add them to high half\n                hi |= (lo & mask) >> (halfsize - n);\n        \n            // and finally shift also low half\n                lo <<= n;\n            }\n       }\n\n       return *this;\n    }\n\n    uint128 & uint128::operator>>=(const uint128& rhs) \n    {\n       if(rhs >= 128)\n       {\n         hi = 0;\n         lo = 0;\n       }\n       else\n       {\n         unsigned int n = rhs.to_integer();\n         const unsigned int halfsize = 128 / 2;\n       \n           if(n >= halfsize) {\n               n -= halfsize;\n               lo = hi;\n               hi = 0;\n           }\n       \n           if(n != 0) {\n           // shift low half\n               lo >>= n;\n       \n           // get lower N bits of high half\n           const uint64_t mask(~(uint64_t(-1) << n));\n       \n           // and add them to low qword\n               lo |= (hi & mask) << (halfsize - n);\n       \n           // and finally shift also high half\n               hi >>= n;\n           }\n      }\n      return *this;\n   }\n\n    uint128& uint128::operator/=(const uint128 &b) \n    {\n        auto self = (m128(hi) << 64) + m128(lo);\n        auto other = (m128(b.hi) << 64) + m128(b.lo);\n        self /= other;\n        hi = static_cast<uint64_t>(self >> 64);\n        lo = static_cast<uint64_t>((self << 64 ) >> 64);\n\n        /*\n        uint128 remainder;\n        divide(*this, b, *this, remainder ); //, *this);\n        if( tmp.hi != hi || tmp.lo != lo ) {\n           std::cerr << tmp.hi << \"  \" << hi <<\"\\n\";\n           std::cerr << tmp.lo << \"  \" << lo << \"\\n\";\n           exit(1);\n        }\n        */\n       \n        /*\n        const auto&  b128 = std::reinterpret_cast<const m128&>(b);\n        auto&     this128 = std::reinterpret_cast<m128&>(*this);\n        this128 /= b128;\n        */\n        return *this;\n    }\n\n    uint128& uint128::operator%=(const uint128 &b) \n    {\n        uint128 quotient;\n        divide(*this, b, quotient, *this);\n        return *this;\n    }\n\n    uint128& uint128::operator*=(const uint128 &b) \n    {\n        uint64_t a0 = (uint32_t) (this->lo        );\n        uint64_t a1 = (uint32_t) (this->lo >> 0x20);\n        uint64_t a2 = (uint32_t) (this->hi        );\n        uint64_t a3 = (uint32_t) (this->hi >> 0x20);\n\n        uint64_t b0 = (uint32_t) (b.lo        );\n        uint64_t b1 = (uint32_t) (b.lo >> 0x20);\n        uint64_t b2 = (uint32_t) (b.hi        );\n        uint64_t b3 = (uint32_t) (b.hi >> 0x20);\n\n        // (a0 + (a1 << 0x20) + (a2 << 0x40) + (a3 << 0x60)) *\n        // (b0 + (b1 << 0x20) + (b2 << 0x40) + (b3 << 0x60)) =\n        //  a0 * b0\n        //\n        // (a1 * b0 + a0 * b1) << 0x20\n        // (a2 * b0 + a1 * b1 + a0 * b2) << 0x40\n        // (a3 * b0 + a2 * b1 + a1 * b2 + a0 * b3) << 0x60\n        //\n        // all other cross terms are << 0x80 or higher, thus do not appear in result\n        \n        this->hi = 0;\n        this->lo = a3*b0;\n        (*this) += a2*b1;\n        (*this) += a1*b2;\n        (*this) += a0*b3;\n        (*this) <<= 0x20;\n        (*this) += a2*b0;\n        (*this) += a1*b1;\n        (*this) += a0*b2;\n        (*this) <<= 0x20;\n        (*this) += a1*b0;\n        (*this) += a0*b1;\n        (*this) <<= 0x20;\n        (*this) += a0*b0;\n\n        return *this;\n   }\n   \n   void uint128::full_product( const uint128& a, const uint128& b, uint128& result_hi, uint128& result_lo )\n   {\n       //   (ah * 2**64 + al) * (bh * 2**64 + bl)\n       // = (ah * bh * 2**128 + al * bh * 2**64 + ah * bl * 2**64 + al * bl\n       // =  P * 2**128 + (Q + R) * 2**64 + S\n       // = Ph * 2**192 + Pl * 2**128\n       // + Qh * 2**128 + Ql * 2**64\n       // + Rh * 2**128 + Rl * 2**64\n       // + Sh * 2**64  + Sl\n       //\n       \n       uint64_t ah = a.hi;\n       uint64_t al = a.lo;\n       uint64_t bh = b.hi;\n       uint64_t bl = b.lo;\n\n       uint128 s = al;\n       s *= bl;\n       uint128 r = ah;\n       r *= bl;\n       uint128 q = al;\n       q *= bh;\n       uint128 p = ah;\n       p *= bh;\n       \n       uint64_t sl = s.lo;\n       uint64_t sh = s.hi;\n       uint64_t rl = r.lo;\n       uint64_t rh = r.hi;\n       uint64_t ql = q.lo;\n       uint64_t qh = q.hi;\n       uint64_t pl = p.lo;\n       uint64_t ph = p.hi;\n\n       uint64_t y[4];    // final result\n       y[0] = sl;\n       \n       uint128_t acc = sh;\n       acc += ql;\n       acc += rl;\n       y[1] = acc.lo;\n       acc = acc.hi;\n       acc += qh;\n       acc += rh;\n       acc += pl;\n       y[2] = acc.lo;\n       y[3] = acc.hi + ph;\n       \n       result_hi = uint128( y[3], y[2] );\n       result_lo = uint128( y[1], y[0] );\n       \n       return;\n   }\n\n   static uint8_t _popcount_64( uint64_t x )\n   {\n      static const uint64_t m[] = {\n         0x5555555555555555ULL,\n         0x3333333333333333ULL,\n         0x0F0F0F0F0F0F0F0FULL,\n         0x00FF00FF00FF00FFULL,\n         0x0000FFFF0000FFFFULL,\n         0x00000000FFFFFFFFULL\n      };\n      // TODO future optimization:  replace slow, portable version\n      // with fast, non-portable __builtin_popcountll intrinsic\n      // (when available)\n\n      for( int i=0, w=1; i<6; i++, w+=w )\n      {\n         x = (x & m[i]) + ((x >> w) & m[i]);\n      }\n      return uint8_t(x);\n   }\n\n   uint8_t uint128::popcount()const\n   {\n      return _popcount_64( lo ) + _popcount_64( hi );\n   }\n\n   void to_variant( const uint128& var,  variant& vo )  { vo = std::string(var);         }\n   void from_variant( const variant& var,  uint128& vo ){ vo = uint128(var.as_string()); }\n\n} // namespace fc\n\n\n/*\n * Portions of the above code were adapted from the work of Evan Teran.\n *\n * Copyright (c) 2008\n * Evan Teran\n *\n * Permission to use, copy, modify, and distribute this software and its\n * documentation for any purpose and without fee is hereby granted, provided\n * that the above copyright notice appears in all copies and that both the\n * copyright notice and this permission notice appear in supporting\n * documentation, and that the same name not be used in advertising or\n * publicity pertaining to distribution of the software without specific,\n * written prior permission. We make no representations about the\n * suitability this software for any purpose. It is provided \"as is\"\n * without express or implied warranty.\n */\n\n", "meta": {"hexsha": "c836f31c556f0db6300b612ae18fb24d8e442dc7", "size": 10402, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libraries/fc/src/uint128.cpp", "max_stars_repo_name": "SophiaTX/SophiaTx-Blockchain", "max_stars_repo_head_hexsha": "c964691c020962ad1aba8263c0d8a78a9fa27e45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2018-07-25T20:42:43.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-11T03:14:09.000Z", "max_issues_repo_path": "libraries/fc/src/uint128.cpp", "max_issues_repo_name": "SophiaTX/SophiaTx-Blockchain", "max_issues_repo_head_hexsha": "c964691c020962ad1aba8263c0d8a78a9fa27e45", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2018-07-25T17:41:28.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-25T13:38:11.000Z", "max_forks_repo_path": "libraries/fc/src/uint128.cpp", "max_forks_repo_name": "SophiaTX/SophiaTx-Blockchain", "max_forks_repo_head_hexsha": "c964691c020962ad1aba8263c0d8a78a9fa27e45", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2018-07-25T14:34:13.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-03T13:29:37.000Z", "avg_line_length": 25.9401496259, "max_line_length": 107, "alphanum_fraction": 0.4406844838, "num_tokens": 3060, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.48593358430449435}}
{"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_FUNCTION_SINC_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_SINC_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n  @ingroup group-trigonometric\n    Function object implementing sinc capabilities\n\n    Computes the sinus cardinal  value of its parameter that is sin(x)/x.\n\n    @par Semantic:\n\n    For every parameter of floating type T\n\n    @code\n    T r = sinc(x);\n    @endcode\n\n    is similar to:\n\n    @code\n    T r = x ? sin(x)/x : One;\n    @endcode\n\n    @see sin, sincpi, sinhc\n\n  **/\n  const boost::dispatch::functor<tag::sinc_> sinc = {};\n} }\n#endif\n\n#include <boost/simd/function/scalar/sinc.hpp>\n#include <boost/simd/function/simd/sinc.hpp>\n\n#endif\n", "meta": {"hexsha": "2f52359e6da4e123f2254b646a4402470f4c1e26", "size": 1126, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/sinc.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/function/sinc.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/function/sinc.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": 22.52, "max_line_length": 100, "alphanum_fraction": 0.5737122558, "num_tokens": 251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.48593358430449435}}
{"text": "///////////////////////////////////////////////////////////////\n//  Copyright 2019 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#include \"../performance_test.hpp\"\n#if defined(TEST_CPP_INT)\n#include <boost/multiprecision/cpp_int.hpp>\n#endif\n\nvoid test10()\n{\n#ifdef TEST_CPP_INT\n   test<boost::multiprecision::number<boost::multiprecision::cpp_int_backend<256, 256, boost::multiprecision::signed_magnitude, boost::multiprecision::unchecked, void>, boost::multiprecision::et_off> >(\"cpp_int(fixed)\", 256);\n#endif\n}\n", "meta": {"hexsha": "3fbe6c66b3121ace11de91846f20b16cdf496c4b", "size": 637, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/boost_1.78.0/libs/multiprecision/performance/performance_test_files/test10.cpp", "max_stars_repo_name": "LaudateCorpus1/math", "max_stars_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 106.0, "max_stars_repo_stars_event_min_datetime": "2015-08-07T04:23:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-27T18:25:15.000Z", "max_issues_repo_path": "3rdparty/boost_1_73_0/libs/multiprecision/performance/performance_test_files/test10.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 130.0, "max_issues_repo_issues_event_min_datetime": "2016-06-22T22:11:25.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-29T20:24:09.000Z", "max_forks_repo_path": "3rdparty/boost_1_73_0/libs/multiprecision/performance/performance_test_files/test10.cpp", "max_forks_repo_name": "qingkouwei/mediaones", "max_forks_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2015-07-08T19:18:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-14T16:39:56.000Z", "avg_line_length": 37.4705882353, "max_line_length": 225, "alphanum_fraction": 0.6891679749, "num_tokens": 151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.48593358430449424}}
{"text": "/* \n   Intel Copyright (C) ....\n*/\n\n#include \"sparse_solver.h\"\n#include <Eigen/PardisoSupport>\n\ntemplate<typename T> void test_pardiso_T()\n{\n  PardisoLLT < SparseMatrix<T, RowMajor>, Lower> pardiso_llt_lower;\n  PardisoLLT < SparseMatrix<T, RowMajor>, Upper> pardiso_llt_upper;\n  PardisoLDLT < SparseMatrix<T, RowMajor>, Lower> pardiso_ldlt_lower;\n  PardisoLDLT < SparseMatrix<T, RowMajor>, Upper> pardiso_ldlt_upper;\n  PardisoLU  < SparseMatrix<T, RowMajor> > pardiso_lu;\n\n  check_sparse_spd_solving(pardiso_llt_lower);\n  check_sparse_spd_solving(pardiso_llt_upper);\n  check_sparse_spd_solving(pardiso_ldlt_lower);\n  check_sparse_spd_solving(pardiso_ldlt_upper);\n  check_sparse_square_solving(pardiso_lu);\n}\n\nEIGEN_DECLARE_TEST(pardiso_support)\n{\n  CALL_SUBTEST_1(test_pardiso_T<float>());\n  CALL_SUBTEST_2(test_pardiso_T<double>());\n  CALL_SUBTEST_3(test_pardiso_T< std::complex<float> >());\n  CALL_SUBTEST_4(test_pardiso_T< std::complex<double> >());\n}\n", "meta": {"hexsha": "9c16ded5bcfc6427c35158455d4a6f4bdf853b3a", "size": 955, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tools/eigen/test/pardiso_support.cpp", "max_stars_repo_name": "Krissmedt/imprunko", "max_stars_repo_head_hexsha": "94171d0d47171cc4b199cd52f5f29385cbff903e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2111.0, "max_stars_repo_stars_event_min_datetime": "2019-01-29T07:01:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T06:48:14.000Z", "max_issues_repo_path": "tools/eigen/test/pardiso_support.cpp", "max_issues_repo_name": "Krissmedt/imprunko", "max_issues_repo_head_hexsha": "94171d0d47171cc4b199cd52f5f29385cbff903e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 131.0, "max_issues_repo_issues_event_min_datetime": "2019-02-18T10:56:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-27T12:07:00.000Z", "max_forks_repo_path": "tools/eigen/test/pardiso_support.cpp", "max_forks_repo_name": "Krissmedt/imprunko", "max_forks_repo_head_hexsha": "94171d0d47171cc4b199cd52f5f29385cbff903e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 421.0, "max_forks_repo_forks_event_min_datetime": "2019-02-12T07:59:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T05:22:01.000Z", "avg_line_length": 31.8333333333, "max_line_length": 69, "alphanum_fraction": 0.7780104712, "num_tokens": 290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.48593358430449424}}
{"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_CONSTANT_MLOGEPS2_HPP_INCLUDED\n#define BOOST_SIMD_CONSTANT_MLOGEPS2_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n  /*!\n    @ingroup group-constant\n\n    Generate \\f$-\\log(eps^2)\\f$ value\n\n    @par Semantic:\n\n    @code\n    T r = Mlogeps2<T>();\n    @endcode\n\n    is similar to:\n\n    @code\n    T r = -log(sqr(Eps<T>()));\n    @endcode\n\n\n    @return The Mlogeps2 constant for the proper type\n  **/\n  template<typename T> T Mlogeps2();\n\n  namespace functional\n  {\n    /*!\n      @ingroup group-callable-constant\n      Generate the  constant mlogeps2.\n\n      @return The Mlogeps2 constant for the proper type\n    **/\n    const boost::dispatch::functor<tag::mlogeps2_> mlogeps2 = {};\n  }\n} }\n#endif\n\n#include <boost/simd/constant/definition/mlogeps2.hpp>\n#include <boost/simd/arch/common/scalar/constant/constant_value.hpp>\n#include <boost/simd/arch/common/simd/constant/constant_value.hpp>\n\n#endif\n", "meta": {"hexsha": "e1ccab31b7de8b7f2ed7061f9048e4bd076a2af8", "size": 1330, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/constant/mlogeps2.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/constant/mlogeps2.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/constant/mlogeps2.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": 23.3333333333, "max_line_length": 100, "alphanum_fraction": 0.5887218045, "num_tokens": 324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.48593358430449424}}
{"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_CSC_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_CSC_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 cosecante of the input in radian : \\f$1/\\sin(x)\\f$.\n\n\n    @par Header <boost/simd/function/csc.hpp>\n\n    @par Note\n\n      As most other trigonometric function csc can be called\n      with a second optional parameter  which is a tag on\n      speed and accuracy (see @ref cos for further details)\n\n    @see cscd, cscpi,\n\n\n    @par Example:\n\n      @snippet csc.cpp csc\n\n    @par Possible output:\n\n      @snippet csc.txt csc\n\n  **/\n  IEEEValue csc(IEEEValue const& x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/csc.hpp>\n#include <boost/simd/function/simd/csc.hpp>\n\n#endif\n", "meta": {"hexsha": "bf75e44e8cd25cdbf5b7575d819435bf0a81a85c", "size": 1198, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/csc.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/csc.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/csc.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 23.4901960784, "max_line_length": 100, "alphanum_fraction": 0.5868113523, "num_tokens": 271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.48593358430449424}}
{"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_REMROUND_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_REMROUND_HPP_INCLUDED\n#include <boost/simd/detail/overload.hpp>\n\n#include <boost/simd/meta/hierarchy/simd.hpp>\n#include <boost/simd/function/div.hpp>\n#include <boost/simd/function/round.hpp>\n#include <boost/simd/function/fnms.hpp>\n#include <boost/simd/function/is_nez.hpp>\n#include <boost/simd/function/multiplies.hpp>\n#include <boost/simd/function/if_minus.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n   namespace bd = boost::dispatch;\n   namespace bs = boost::simd;\n   BOOST_DISPATCH_OVERLOAD_IF(rem_\n                          , (typename A0, typename X)\n                          , (detail::is_native<X>)\n                          , bd::cpu_\n                          , bs::tag::round_\n                          , bs::pack_<bd::int_<A0>, X>\n                          , bs::pack_<bd::int_<A0>, X>\n                          )\n   {\n      BOOST_FORCEINLINE A0 operator()(bd::functor<bs::tag::round_> const&\n                                     , const A0& a0, const A0& a1) const BOOST_NOEXCEPT\n      {\n        return if_minus(is_nez(a1), a0, div(round,a0,a1)*a1);\n      }\n   };\n\n   BOOST_DISPATCH_OVERLOAD_IF(rem_\n                          , (typename A0, typename X)\n                          , (detail::is_native<X>)\n                          , bd::cpu_\n                          , bs::tag::round_\n                          , bs::pack_<bd::floating_<A0>, X>\n                          , bs::pack_<bd::floating_<A0>, X>\n                          )\n   {\n      BOOST_FORCEINLINE A0 operator()(bd::functor<bs::tag::round_> const&\n                                     , const A0& a0, const A0& a1) const BOOST_NOEXCEPT\n      {\n        auto z = is_nez(a1);\n        return if_else(logical_and(z, is_eqz(a0)),  a0,\n                       if_nan_else(logical_or(is_invalid(a1),is_invalid(a0)) ,\n                                   if_nan_else(is_eqz(a1),\n                                               if_minus(z, a0, div(round, a0,a1)*a1)\n                                              )\n                                  )\n                      );\n      }\n   };\n\n   BOOST_DISPATCH_OVERLOAD_IF(rem_\n                          , (typename A0, typename X)\n                          , (detail::is_native<X>)\n                          , bd::cpu_\n                          , bs::fast_tag\n                          , bs::tag::round_\n                          , bs::pack_<bd::floating_<A0>, X>\n                          , bs::pack_<bd::floating_<A0>, X>\n                          )\n   {\n      BOOST_FORCEINLINE A0 operator()(const fast_tag &\n                                     , bd::functor<bs::tag::round_> const&\n                                     , const A0& a0, const A0& a1) const BOOST_NOEXCEPT\n      {\n        return fnms(div(round, a0,a1), a1, a0);\n      }\n   };\n} } }\n\n#endif\n", "meta": {"hexsha": "9c432091a6609cb741b797ca039a378ccfb2b97e", "size": 3289, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/simd/function/remround.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/remround.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/remround.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": 38.2441860465, "max_line_length": 100, "alphanum_fraction": 0.4481605351, "num_tokens": 714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384736, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4859335780861937}}
{"text": "/*\n * File:   Grid.cpp\n * Author: Weiming Hu <weiming@psu.edu>\n *\n * Created on April 3, 2021, 11:15 AM\n */\n\n#include <cmath>\n#include <sstream>\n#include <boost/numeric/conversion/cast.hpp>\n\n#include \"Txt.h\"\n#include \"Grid.h\"\n\nusing namespace std;\n\n/********\n * Grid *\n*********/\n\nGrid::Grid() {\n    nan_count_ = 0;\n}\n\nGrid::Grid(const Grid & orig) {\n    *this = orig;\n}\n\nGrid::Grid(const string & file) {\n    setup(file);\n}\n\nGrid::~Grid() {\n}\n\nvoid\nGrid::setup(const string & file) {\n\n    // Read matrix from the file\n    Txt::readMatrix(file, grid_);\n\n    // Set up the mapping from station keys to the row/column numbers\n    row_cols_.clear();\n    nan_count_ = 0;\n\n    size_t num_rows = nrows();\n    size_t num_cols = ncols();\n\n    for (size_t r = 0; r < num_rows; ++r) {\n        for (size_t c = 0; c < num_cols; ++c) {\n            double key = grid_(r, c);\n\n            if (std::isnan(key)) {\n                nan_count_++;\n\n            } else {\n                double integral, fractional;\n                fractional = modf(key, &integral);\n\n                if (fractional != 0) {\n                    throw runtime_error(\"Station keys must be non-negative integer!\");\n                }\n\n                row_cols_[boost::numeric_cast<size_t>(key)] = {r, c};\n            }\n        }\n    }\n\n    if (row_cols_.size() + nan_count_ != num_rows * num_cols) {\n        stringstream ss;\n        ss << \"Duplicated station keys found. Expect \" << num_rows << \"x\" << num_cols\n            << \", but got \" << row_cols_.size() << \" and \" << nan_count_ << \" nan\";\n        throw runtime_error(ss.str());\n    }\n\n    return;\n}\n\nvoid\nGrid::getRectangle(size_t station_key, Matrix & mask,\n        size_t width, size_t height, bool same_padding) const {\n\n    if (width == 0 || height == 0) throw runtime_error(\"Invalid width or height\");\n    if (remainder(width - 1, 2) != 0) throw runtime_error(\"Width needs to be an odd number\");\n    if (remainder(height - 1, 2) != 0) throw runtime_error(\"Height needs to be an odd number\");\n\n    // Initialization\n    mask.resize(height, width);\n\n    // Get the location of the center grid\n    RowCol row_col = (*this)[station_key];\n    long center_row = boost::numeric_cast<long>(row_col.first);\n    long center_col = boost::numeric_cast<long>(row_col.second);\n\n    // Get the spatial extent of the mask\n    long left = center_col - (width - 1) / 2;\n    long top = center_row - (height - 1) / 2;\n\n    size_t num_rows = nrows();\n    size_t num_cols = ncols();\n\n    for (size_t r = 0; r < mask.size1(); ++r) {\n        long grid_r = top + r;\n\n        if (same_padding) {\n            if (grid_r < 0) grid_r = 0;\n            else if (grid_r >= num_rows) grid_r = num_rows - 1;\n        }\n\n        if (grid_r < 0 || grid_r >= num_rows) {\n            for (size_t c = 0; c < mask.size2(); ++c) {\n                mask(r, c) = NAN;\n            }\n\n        } else {\n            for (size_t c = 0; c < mask.size2(); ++c) {\n                long grid_c = left + c;\n\n                if (same_padding) {\n                    if (grid_c < 0) grid_c = 0;\n                    else if (grid_c >= num_cols) grid_c = num_cols - 1;\n                }\n\n                if (grid_c < 0 || grid_c >= num_cols) {\n                    mask(r, c) = NAN;\n                } else {\n                    double v = (*this)(grid_r, grid_c);\n\n                    if (same_padding && std::isnan(v)) {\n                        throw runtime_error(\"NAN is not allowed when using same padding\");\n                    } else {\n                        mask(r, c) = v;\n                    }\n                }\n            }\n        }\n    }\n\n    return;\n}\n\nsize_t\nGrid::nrows() const {\n    return grid_.size1();\n}\n\nsize_t\nGrid::ncols() const {\n    return grid_.size2();\n}\n\nsize_t\nGrid::nkeys() const {\n    return row_cols_.size();\n}\n\nstring\nGrid::summary() const {\n    stringstream ss;\n    ss << nrows() << \" rows, \" << ncols() << \" columns, \" << nkeys()\n        << \" station keys, and \" << nan_count_ << \" unassigned grids (nan)\";\n    return ss.str();\n}\n\nstring\nGrid::detail() const {\n    stringstream ss;\n    ss << grid_;\n    return ss.str();\n}\n\ndouble\nGrid::getMaxKey() const {\n    if (row_cols_.size() == 0) throw runtime_error(\"Grid empty! No max to find.\");\n\n    double max_val = 0;\n\n    for (auto & it:row_cols_) {\n        if (it.first > max_val) max_val = it.first;\n    }\n\n    return max_val;\n}\n\nostream &\noperator<<(ostream & os, const Grid & obj) {\n    return os << obj.grid_;\n}\n\nGrid &\nGrid::operator=(const Grid & rhs) {\n    if (this != &rhs) {\n        nan_count_ = rhs.nan_count_;\n        grid_ = rhs.grid_;\n        row_cols_ = rhs.row_cols_;\n    }\n    return *this;\n}\n\nRowCol\nGrid::operator[](size_t station_key) const {\n    return row_cols_.at(station_key);\n}\n\ndouble\nGrid::operator()(size_t row, size_t col) const {\n    return grid_(row, col);\n}\n\n", "meta": {"hexsha": "443c3a67e8224f65524af8dc40148197a34ba582", "size": 4829, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CGrid/src/Grid.cpp", "max_stars_repo_name": "Weiming-Hu/AnalogsEnsemble", "max_stars_repo_head_hexsha": "f1735ad0d025397066e9fe1018b8b4fc5bc68f2f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2018-12-14T10:45:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T05:57:43.000Z", "max_issues_repo_path": "CGrid/src/Grid.cpp", "max_issues_repo_name": "Weiming-Hu/AnalogsEnsemble", "max_issues_repo_head_hexsha": "f1735ad0d025397066e9fe1018b8b4fc5bc68f2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 100.0, "max_issues_repo_issues_event_min_datetime": "2018-09-27T21:48:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T00:32:40.000Z", "max_forks_repo_path": "CGrid/src/Grid.cpp", "max_forks_repo_name": "Weiming-Hu/AnalogsEnsemble", "max_forks_repo_head_hexsha": "f1735ad0d025397066e9fe1018b8b4fc5bc68f2f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-05-30T08:21:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-19T10:39:42.000Z", "avg_line_length": 22.9952380952, "max_line_length": 95, "alphanum_fraction": 0.5284738041, "num_tokens": 1280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.4859305133593912}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2013   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2013   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#include <nt2/ieee/include/functions/ulpdist.hpp>\n\n#include <boost/dispatch/functor/meta/call.hpp>\n\n#include <nt2/sdk/unit/tests/relation.hpp>\n#include <nt2/sdk/unit/tests/type_expr.hpp>\n#include <nt2/sdk/unit/module.hpp>\n\n#include <nt2/include/constants/mone.hpp>\n#include <nt2/include/constants/one.hpp>\n#include <nt2/include/constants/zero.hpp>\n#include <nt2/include/constants/inf.hpp>\n#include <nt2/include/constants/minf.hpp>\n#include <nt2/include/constants/nan.hpp>\n#include <nt2/include/constants/eps.hpp>\n#include <nt2/include/constants/valmin.hpp>\n#include <nt2/include/constants/valmax.hpp>\n\nNT2_TEST_CASE_TPL ( ulpdist_real,  BOOST_SIMD_REAL_TYPES)\n{\n  using nt2::ulpdist;\n  using nt2::tag::ulpdist_;\n\n  NT2_TEST_TYPE_IS( typename boost::dispatch::meta::call<ulpdist_(T,T)>::type\n                  , T\n                  );\n\n#ifndef BOOST_SIMD_NO_INVALIDS\n  NT2_TEST_EQUAL(ulpdist(nt2::Inf<T>(), nt2::Inf<T>()), nt2::Zero<T>());\n  NT2_TEST_EQUAL(ulpdist(nt2::Minf<T>(), nt2::Minf<T>()), nt2::Zero<T>());\n  NT2_TEST_EQUAL(ulpdist(nt2::Nan<T>(), nt2::Nan<T>()), nt2::Zero<T>());\n#endif\n\n  NT2_TEST_EQUAL(ulpdist(nt2::Mone<T>(), nt2::Mone<T>()), nt2::Zero<T>());\n  NT2_TEST_EQUAL(ulpdist(nt2::One<T>(), nt2::One<T>()), nt2::Zero<T>());\n  NT2_TEST_EQUAL(ulpdist(nt2::Zero<T>(), nt2::Zero<T>()), nt2::Zero<T>());\n\n  NT2_TEST_EQUAL( ulpdist(nt2::One<T>(), nt2::One<T>()+nt2::Eps<T>())\n                , T(0.5)\n                );\n\n  NT2_TEST_EQUAL( ulpdist(nt2::One<T>(), nt2::One<T>()-nt2::Eps<T>())\n                , T(0.5)\n                );\n\n  NT2_TEST_EQUAL( ulpdist(nt2::One<T>(), nt2::One<T>()-nt2::Eps<T>()/2)\n                , T(0.25)\n                );\n}\n\nNT2_TEST_CASE_TPL ( ulpdist_signed_integral,  BOOST_SIMD_INTEGRAL_SIGNED_TYPES)\n{\n  using nt2::ulpdist;\n  using nt2::tag::ulpdist_;\n\n  NT2_TEST_TYPE_IS( typename boost::dispatch::meta::call<ulpdist_(T,T)>::type\n                  , T\n                  );\n\n  NT2_TEST_EQUAL(ulpdist(nt2::Mone<T>(), nt2::Mone<T>()), nt2::Zero<T>());\n  NT2_TEST_EQUAL(ulpdist(nt2::One<T>(), nt2::One<T>()), nt2::Zero<T>());\n  NT2_TEST_EQUAL(ulpdist(nt2::Zero<T>(), nt2::Zero<T>()), nt2::Zero<T>());\n\n  NT2_TEST_EQUAL( ulpdist(nt2::Zero<T>(), nt2::Valmin<T>())\n                , nt2::Valmax<T>()\n                );\n\n  NT2_TEST_EQUAL( ulpdist(nt2::Valmin<T>(), nt2::Zero<T>())\n                , nt2::Valmax<T>()\n                );\n\n  NT2_TEST_EQUAL( ulpdist(nt2::Zero<T>(), nt2::Valmax<T>())\n                , nt2::Valmax<T>()\n                );\n\n  NT2_TEST_EQUAL( ulpdist(nt2::Valmax<T>(), nt2::Zero<T>())\n                , nt2::Valmax<T>()\n                );\n\n  NT2_TEST_EQUAL( ulpdist(nt2::Valmin<T>(), nt2::Valmax<T>())\n                , nt2::Valmax<T>()\n                );\n}\n\nNT2_TEST_CASE_TPL ( ulpdist_unsigned_integral,  BOOST_SIMD_UNSIGNED_TYPES)\n{\n  using nt2::ulpdist;\n  using nt2::tag::ulpdist_;\n\n  NT2_TEST_TYPE_IS( typename boost::dispatch::meta::call<ulpdist_(T,T)>::type\n                  , T\n                  );\n\n  NT2_TEST_EQUAL(ulpdist(nt2::Mone<T>(), nt2::Mone<T>()), nt2::Zero<T>());\n  NT2_TEST_EQUAL(ulpdist(nt2::One<T>(), nt2::One<T>()), nt2::Zero<T>());\n  NT2_TEST_EQUAL(ulpdist(nt2::Zero<T>(), nt2::Zero<T>()), nt2::Zero<T>());\n\n  NT2_TEST_EQUAL( ulpdist(nt2::Zero<T>(), nt2::Valmin<T>())\n                , nt2::Zero<T>()\n                );\n\n  NT2_TEST_EQUAL( ulpdist(nt2::Valmin<T>(), nt2::Zero<T>())\n                , nt2::Zero<T>()\n                );\n\n  NT2_TEST_EQUAL( ulpdist(nt2::Zero<T>(), nt2::Valmax<T>())\n                , nt2::Valmax<T>()\n                );\n\n  NT2_TEST_EQUAL( ulpdist(nt2::Valmax<T>(), nt2::Zero<T>())\n                , nt2::Valmax<T>()\n                );\n\n  NT2_TEST_EQUAL( ulpdist(nt2::Valmin<T>(), nt2::Valmax<T>())\n                , nt2::Valmax<T>()\n                );\n}\n", "meta": {"hexsha": "160143275ca88f775282679f1c07a07d199402cf", "size": 4283, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/core/base/unit/ieee/scalar/ulpdist.cpp", "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/base/unit/ieee/scalar/ulpdist.cpp", "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/base/unit/ieee/scalar/ulpdist.cpp", "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": 33.9920634921, "max_line_length": 80, "alphanum_fraction": 0.5454120943, "num_tokens": 1260, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195385342971, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.4859305112683077}}
{"text": "#include \"Scene.h\"\n#include \"Intersection.h\"\n#include \"Ray.h\"\n#include \"Surface.h\"\n#include \"SurfaceList.h\"\n\n#include <Eigen/Dense>\n\nstd::unique_ptr<Intersection> Scene::intersect(const Ray& ray) const {\n    return surfaces.intersect(ray);\n}\n\nColor Scene::shade(const Ray& ray, const Intersection& hit, int depth, bool shadows, bool kd) const {\n    auto p = ray.evaluate(hit.t); \n    auto n = hit.normal;\n\n    return (hit.hit)->shade(ray, p, n, light, *this, depth, shadows, kd);\n}\n", "meta": {"hexsha": "4422fd7b49d84d121734210c492e88ef1276e703", "size": 482, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Scene.cpp", "max_stars_repo_name": "fmenozzi/raytracer", "max_stars_repo_head_hexsha": "23a67c7a11bea5198b691ebb0ab7fd4bb3758097", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-12T20:31:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-12T20:31:51.000Z", "max_issues_repo_path": "src/Scene.cpp", "max_issues_repo_name": "fmenozzi/raytracer", "max_issues_repo_head_hexsha": "23a67c7a11bea5198b691ebb0ab7fd4bb3758097", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Scene.cpp", "max_forks_repo_name": "fmenozzi/raytracer", "max_forks_repo_head_hexsha": "23a67c7a11bea5198b691ebb0ab7fd4bb3758097", "max_forks_repo_licenses": ["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.3684210526, "max_line_length": 101, "alphanum_fraction": 0.6867219917, "num_tokens": 124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7341195152660688, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.4859305105544893}}
{"text": "/**\n * \\file se3_localization.cpp\n *\n *  Created on: Dec 12, 2018\n *     \\author: jsola\n *\n *  ---------------------------------------------------------\n *  This file is:\n *  (c) 2018 Joan Sola @ IRI-CSIC, Barcelona, Catalonia\n *\n *  This file is part of `manif`, a C++ template-only library\n *  for Lie theory targeted at estimation for robotics.\n *  Manif is:\n *  (c) 2018 Jeremie Deray @ IRI-UPC, Barcelona\n *  ---------------------------------------------------------\n *\n *  ---------------------------------------------------------\n *  Demonstration example:\n *\n *  3D Robot localization based on fixed beacons.\n *\n *  See se2_localization.cpp for the 2D equivalent.\n *  See se3_sam.cpp for a more advanced example performing smoothing and mapping.\n *  ---------------------------------------------------------\n *\n *  This demo corresponds to the 3D version of the application\n *  in chapter V, section A, in the paper Sola-18,\n *  [https://arxiv.org/abs/1812.01537].\n *\n *  The following is an abstract of the content of the paper.\n *  Please consult the paper for better reference.\n *\n *\n *  We consider a robot in 3D space surrounded by a small\n *  number of punctual landmarks or _beacons_.\n *  The robot receives control actions in the form of axial\n *  and angular velocities, and is able to measure the location\n *  of the beacons w.r.t its own reference frame.\n *\n *  The robot pose X is in SE(3) and the beacon positions b_k in R^3,\n *\n *      X = |  R   t |              // position and orientation\n *          |  0   1 |\n *\n *      b_k = (bx_k, by_k, bz_k)    // lmk coordinates in world frame\n *\n *  The control signal u is a twist in se(3) comprising longitudinal\n *  velocity vx and angular velocity wz, with no other velocity\n *  components, integrated over the sampling time dt.\n *\n *      u = (vx*dt, 0, 0, 0, 0, w*dt)\n *\n *  The control is corrupted by additive Gaussian noise u_noise,\n *  with covariance\n *\n *    Q = diagonal(sigma_x^2, sigma_y^2, sigma_z^2, sigma_roll^2, sigma_pitch^2, sigma_yaw^2).\n *\n *  This noise accounts for possible lateral and rotational slippage\n *  through a non-zero values of sigma_y, sigma_z, sigma_roll and sigma_pitch.\n *\n *  At the arrival of a control u, the robot pose is updated\n *  with X <-- X * Exp(u) = X + u.\n *\n *  Landmark measurements are of the range and bearing type,\n *  though they are put in Cartesian form for simplicity.\n *  Their noise n is zero mean Gaussian, and is specified\n *  with a covariances matrix R.\n *  We notice the rigid motion action y = h(X,b) = X^-1 * b\n *  (see appendix D),\n *\n *      y_k = (brx_k, bry_k, brz_k)    // lmk coordinates in robot frame\n *\n *  We consider the beacons b_k situated at known positions.\n *  We define the pose to estimate as X in SE(3).\n *  The estimation error dx and its covariance P are expressed\n *  in the tangent space at X.\n *\n *  All these variables are summarized again as follows\n *\n *    X   : robot pose, SE(3)\n *    u   : robot control, (v*dt; 0; 0; 0; 0; w*dt) in se(3)\n *    Q   : control perturbation covariance\n *    b_k : k-th landmark position, R^3\n *    y   : Cartesian landmark measurement in robot frame, R^3\n *    R   : covariance of the measurement noise\n *\n *  The motion and measurement models are\n *\n *    X_(t+1) = f(X_t, u) = X_t * Exp ( w )     // motion equation\n *    y_k     = h(X, b_k) = X^-1 * b_k          // measurement equation\n *\n *  The algorithm below comprises first a simulator to\n *  produce measurements, then uses these measurements\n *  to estimate the state, using a Lie-based error-state Kalman filter.\n *\n *  This file has plain code with only one main() function.\n *  There are no function calls other than those involving `manif`.\n *\n *  Printing simulated state and estimated state together\n *  with an unfiltered state (i.e. without Kalman corrections)\n *  allows for evaluating the quality of the estimates.\n */\n\n#include \"manif/SE3.h\"\n\n#include <Eigen/Dense>\n\n#include <vector>\n\n#include <iostream>\n#include <iomanip>\n\nusing std::cout;\nusing std::endl;\n\nusing namespace Eigen;\n\ntypedef Array<double, 3, 1> Array3d;\ntypedef Array<double, 6, 1> Array6d;\ntypedef Matrix<double, 6, 1> Vector6d;\ntypedef Matrix<double, 6, 6> Matrix6d;\n\nint main()\n{\n    // START CONFIGURATION\n    //\n    //\n    const int NUMBER_OF_LMKS_TO_MEASURE = 5;\n\n    // Define the robot pose element and its covariance\n    manif::SE3d X, X_simulation, X_unfiltered;\n    Matrix6d    P;\n\n    X_simulation.setIdentity();\n    X.setIdentity();\n    X_unfiltered.setIdentity();\n    P.setZero();\n\n    // Define a control vector and its noise and covariance\n    manif::SE3Tangentd  u_simu, u_est, u_unfilt;\n    Vector6d            u_nom, u_noisy, u_noise;\n    Array6d             u_sigmas;\n    Matrix6d            U;\n\n    u_nom    << 0.1, 0.0, 0.0, 0.0, 0.0, 0.05;\n    u_sigmas << 0.1, 0.1, 0.1, 0.1, 0.1, 0.1;\n    U        = (u_sigmas * u_sigmas).matrix().asDiagonal();\n\n    // Declare the Jacobians of the motion wrt robot and control\n    manif::SE3d::Jacobian J_x, J_u;\n\n    // Define five landmarks in R^3\n    Vector3d b0, b1, b2, b3, b4, b;\n    b0 << 2.0,  0.0,  0.0;\n    b1 << 3.0, -1.0, -1.0;\n    b2 << 2.0, -1.0,  1.0;\n    b3 << 2.0,  1.0,  1.0;\n    b4 << 2.0,  1.0, -1.0;\n    std::vector<Vector3d> landmarks;\n    landmarks.push_back(b0);\n    landmarks.push_back(b1);\n    landmarks.push_back(b2);\n    landmarks.push_back(b3);\n    landmarks.push_back(b4);\n\n    // Define the beacon's measurements\n    Vector3d                y, y_noise;\n    Array3d                 y_sigmas;\n    Matrix3d                R;\n    std::vector<Vector3d>   measurements(landmarks.size());\n\n    y_sigmas << 0.01, 0.01, 0.01;\n    R        = (y_sigmas * y_sigmas).matrix().asDiagonal();\n\n    // Declare the Jacobian of the measurements wrt the robot pose\n    Matrix<double, 3, 6>    H;      // H = J_e_x\n\n    // Declare some temporaries\n    Vector3d                e, z;   // expectation, innovation\n    Matrix3d                E, Z;   // covariances of the above\n    Matrix<double, 6, 3>    K;      // Kalman gain\n    manif::SE3Tangentd      dx;     // optimal update step, or error-state\n    manif::SE3d::Jacobian   J_xi_x; // Jacobian is typedef Matrix\n    Matrix<double, 3, 6>    J_e_xi; // Jacobian\n\n    //\n    //\n    // CONFIGURATION DONE\n\n\n\n    // DEBUG\n    cout << std::fixed   << std::setprecision(3) << std::showpos << endl;\n    cout << \"X STATE     :    X      Y      Z    TH_x   TH_y   TH_z \" << endl;\n    cout << \"-------------------------------------------------------\" << endl;\n    cout << \"X initial   : \" << X_simulation.log().coeffs().transpose() << endl;\n    cout << \"-------------------------------------------------------\" << endl;\n    // END DEBUG\n\n\n\n\n    // START TEMPORAL LOOP\n    //\n    //\n\n    // Make 10 steps. Measure up to three landmarks each time.\n    for (int t = 0; t < 10; t++)\n    {\n        //// I. Simulation ###############################################################################\n\n        /// simulate noise\n        u_noise = u_sigmas * Array6d::Random();             // control noise\n        u_noisy = u_nom + u_noise;                          // noisy control\n\n        u_simu   = u_nom;\n        u_est    = u_noisy;\n        u_unfilt = u_noisy;\n\n        /// first we move - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n        X_simulation = X_simulation + u_simu;               // overloaded X.rplus(u) = X * exp(u)\n\n        /// then we measure all landmarks - - - - - - - - - - - - - - - - - - - -\n        for (int i = 0; i < landmarks.size(); i++)\n        {\n            b = landmarks[i];                               // lmk coordinates in world frame\n\n            /// simulate noise\n            y_noise = y_sigmas * Array3d::Random();         // measurement noise\n\n            y = X_simulation.inverse().act(b);              // landmark measurement, before adding noise\n            y = y + y_noise;                                // landmark measurement, noisy\n            measurements[i] = y;                            // store for the estimator just below\n        }\n\n\n\n\n        //// II. Estimation ###############################################################################\n\n        /// First we move - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n\n        X = X.plus(u_est, J_x, J_u);                        // X * exp(u), with Jacobians\n\n        P = J_x * P * J_x.transpose() + J_u * U * J_u.transpose();\n\n\n        /// Then we correct using the measurements of each lmk - - - - - - - - -\n        for (int i = 0; i < NUMBER_OF_LMKS_TO_MEASURE; i++)\n        {\n            // landmark\n            b = landmarks[i];                               // lmk coordinates in world frame\n\n           // measurement\n            y = measurements[i];                            // lmk measurement, noisy\n\n            // expectation\n            e = X.inverse(J_xi_x).act(b, J_e_xi);           // note: e = R.tr * ( b - t ), for X = (R,t).\n            H = J_e_xi * J_xi_x;                            // note: H = J_e_x = J_e_xi * J_xi_x\n            E = H * P * H.transpose();\n\n            // innovation\n            z = y - e;\n            Z = E + R;\n\n            // Kalman gain\n            K = P * H.transpose() * Z.inverse();            // K = P * H.tr * ( H * P * H.tr + R).inv\n\n            // Correction step\n            dx = K * z;                                     // dx is in the tangent space at X\n\n            // Update\n            X = X + dx;                                     // overloaded X.rplus(dx) = X * exp(dx)\n            P = P - K * Z * K.transpose();\n        }\n\n\n\n\n        //// III. Unfiltered ##############################################################################\n\n        // move also an unfiltered version for comparison purposes\n        X_unfiltered = X_unfiltered + u_unfilt;\n\n\n\n\n        //// IV. Results ##############################################################################\n\n        // DEBUG\n        cout << \"X simulated : \" << X_simulation.log().coeffs().transpose() << endl;\n        cout << \"X estimated : \" << X.log().coeffs().transpose() << endl;\n        cout << \"X unfilterd : \" << X_unfiltered.log().coeffs().transpose() << endl;\n        cout << \"-------------------------------------------------------\" << endl;\n        // END DEBUG\n\n    }\n\n    //\n    //\n    // END OF TEMPORAL LOOP. DONE.\n\n    return 0;\n}\n", "meta": {"hexsha": "abf0528b756c133d28dc0ea0763192cf9cbec1c3", "size": 10337, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/se3_localization.cpp", "max_stars_repo_name": "mindbeast/manif", "max_stars_repo_head_hexsha": "8b4fdc3c18fe3f98cf60bb9a405f2bb393bd6a40", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T03:15:18.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-14T12:16:31.000Z", "max_issues_repo_path": "examples/se3_localization.cpp", "max_issues_repo_name": "mindbeast/manif", "max_issues_repo_head_hexsha": "8b4fdc3c18fe3f98cf60bb9a405f2bb393bd6a40", "max_issues_repo_licenses": ["MIT"], "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/se3_localization.cpp", "max_forks_repo_name": "mindbeast/manif", "max_forks_repo_head_hexsha": "8b4fdc3c18fe3f98cf60bb9a405f2bb393bd6a40", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-10T09:23:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-10T09:23:28.000Z", "avg_line_length": 33.8918032787, "max_line_length": 107, "alphanum_fraction": 0.5147528296, "num_tokens": 2775, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195152660687, "lm_q2_score": 0.6619228825191871, "lm_q1q2_score": 0.48593050565850454}}
{"text": "#ifndef FUN_HPP__\n#define FUN_HPP__\n\n#include <string>\n#include <deque>\n#include <functional>\n#include <boost/assert.hpp>\n\n//#include <stdlib.h>\nnamespace biggles {\n    /// \\brief x^2\n    template<class DTYPE> DTYPE square(const DTYPE& x) { return x*x; }\n    template<class DTYPE> DTYPE cubed(const DTYPE& x) { return x*x*x; }\n    template<class DTYPE> DTYPE abs_diff(const DTYPE& x, const DTYPE& y) {\n        return x>y ? x-y : y-x;\n    }\n\n    std::string local_time(const std::string& fmt = std::string(\"%y%m%d_%T\"));\n\n    std::string count2str(size_t cnt);\n    std::string float2str(float num);\n    std::string time2str(float seconds);\n\n    /// \\brief a class to hold a fixed number of values\n    ///\n    /// if a new value is inserted into the full container the last (and oldest) value is removed\n    template <class DATATYPE>\n    class fqueue {\n        typedef typename std::deque<DATATYPE> container_t;\n        container_t data_;\n        size_t max_size_;\n    public:\n        explicit fqueue(size_t max_size) : max_size_(max_size) { BOOST_ASSERT(max_size_ > 0); }\n        typedef typename container_t::const_iterator const_iterator;\n        const_iterator begin() const { return data_.begin(); }\n        const_iterator end() const { return data_.end(); }\n        void push(const DATATYPE& value) {\n            if (max_size_ == data_.size()) data_.pop_back();\n            data_.push_front(value);\n        }\n        bool is_full() const { return max_size_ <= data_.size(); }\n        size_t size() const { return data_.size(); }\n        DATATYPE last() const { return data_.front(); }\n        DATATYPE first() const { return data_.back(); }\n    };\n\n    /// \\brief this is copied form cplusplus.com and it not required in C++11\n    template <class ForwardIterator>\n    bool is_sorted (ForwardIterator first, ForwardIterator last) {\n      if (first==last) return true;\n      ForwardIterator next = first;\n      while (++next!=last) {\n        if (*next < *first)\n          return false;\n        ++first;\n      }\n      return true;\n    }\n\n    template<class ITERATOR>\n    bool any_weight(ITERATOR b, ITERATOR e) {\n        typedef typename ITERATOR::value_type value_type;\n        while (b != e) {\n            if (*b++ > value_type(0))\n                return true;\n        }\n        return false;\n    }\n\n    /// \\brief (sum(\\em fun(*\\em it)) for \\em it in [\\em b, \\em e)) + init\n    template<class ITERATOR, class FUN>\n    typename FUN::result_type fun_sum(ITERATOR b, ITERATOR e, const FUN& fun, typename FUN::result_type init) {\n        while (b != e) init += fun(*b++);\n        return init;\n    }\n\n    template<class INPUT_ITER, class OUTPUT_ITER, class FUN>\n    void fun_partial_sum(INPUT_ITER b, INPUT_ITER e, OUTPUT_ITER ob, const FUN& fun, typename FUN::result_type init) {\n        while (b != e) *ob++ = init += fun(*b++);\n    }\n\n    /// \\brief wrapper of unary function \\em FUN for std::partial_sum\n    template <class FUN> class fun_sum_operator :\n        public std::binary_function<typename FUN::result_type, typename FUN::argument_type, typename FUN::result_type>\n    {\n        typedef typename FUN::result_type result_type;\n        typedef typename FUN::argument_type argument_type;\n        const FUN& fun_;\n    public:\n        fun_sum_operator(const FUN& fun) : fun_(fun) {}\n        result_type operator()(const result_type& prev, const argument_type& arg) const { return prev + fun_(arg); }\n    }; // fun_sum_operator\n\ntemplate<class EIGEN_MATRIX> bool is_symmetric(const EIGEN_MATRIX &matrix) {\n    return matrix == matrix.transpose();\n}\n\ntemplate<class EIGEN_MATRIX> float measure_asymmetry(const EIGEN_MATRIX &matrix) {\n    return (matrix - matrix.transpose()).determinant();\n}\n\ntemplate<class EIGEN_MATRIX> EIGEN_MATRIX enforce_symmetry(const EIGEN_MATRIX &matrix) {\n    return (matrix + matrix.transpose())/2.0;\n}\n\n\n} // namespace biggles\n\n#endif\n", "meta": {"hexsha": "7cc82bb446193acd74dbc5afdac827c1850e52cb", "size": 3867, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/biggles/detail/fun.hpp", "max_stars_repo_name": "fbi-octopus/biggles", "max_stars_repo_head_hexsha": "2dac4f1748ab87242951239caf274f302be1143a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-15T14:01:59.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-15T14:01:59.000Z", "max_issues_repo_path": "include/biggles/detail/fun.hpp", "max_issues_repo_name": "fbi-octopus/biggles", "max_issues_repo_head_hexsha": "2dac4f1748ab87242951239caf274f302be1143a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/biggles/detail/fun.hpp", "max_forks_repo_name": "fbi-octopus/biggles", "max_forks_repo_head_hexsha": "2dac4f1748ab87242951239caf274f302be1143a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1545454545, "max_line_length": 118, "alphanum_fraction": 0.6431342126, "num_tokens": 952, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.734119526900183, "lm_q2_score": 0.6619228625116081, "lm_q1q2_score": 0.4859304986714367}}
{"text": "/* Copyright (C) 2010-2019, The Regents of The University of Michigan.\n All rights reserved.\n\n This software was developed as part of the The Vulcan project in the Intelligent Robotics Lab\n under the direction of Benjamin Kuipers, kuipers@umich.edu. Use of this code is governed by an\n MIT-style License that can be found at \"https://github.com/h2ssh/Vulcan\".\n*/\n\n\n/**\n * \\file     univariate_distribution_estimator_impl.cpp\n * \\author   Collin Johnson\n *\n * Definition of implementations of the UnivariateDistributionEstimator for the subclasses of UnivariateDistribution:\n *\n *   - UnivariateGaussianDistribution\n *   - GammaDistribution\n *   - BetaDistribution\n *   - ExponentialDistribution\n *   - TruncatedGaussianDistribution\n */\n\n#include \"math/univariate_distribution_estimator_impl.h\"\n#include \"math/beta_distribution.h\"\n#include \"math/discrete_gaussian.h\"\n#include \"math/exponential_distribution.h\"\n#include \"math/gamma_distribution.h\"\n#include \"math/statistics.h\"\n#include \"math/truncated_gaussian_distribution.h\"\n#include \"math/univariate_gaussian.h\"\n#include <boost/math/special_functions/digamma.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n#include <iostream>\n\nnamespace vulcan\n{\nnamespace math\n{\n\nusing DistPtr = std::unique_ptr<UnivariateDistribution>;\n\n\ndouble log_likelihood_gamma_func(double k, double sumXi, double sumLogXi, std::size_t n)\n{\n    return (k - 1) * sumXi - n * k - n * k * std::log(sumXi / (k * n)) - n * std::log(boost::math::tgamma(k));\n}\n\n\ndouble log_likelihood_gamma_deriv(double k, double sumXi, double sumLogXi, std::size_t n)\n{\n    return n * (std::log(k) - boost::math::digamma(k) - std::log(sumXi / n)) + sumLogXi;\n}\n\n\nDistPtr\n  UnivariateGaussianDistributionEstimator::estimateDistribution(const std::vector<double>::const_iterator dataBegin,\n                                                                const std::vector<double>::const_iterator dataEnd) const\n{\n    return DistPtr{new UnivariateGaussianDistribution(estimate(dataBegin, dataEnd))};\n}\n\n\nUnivariateGaussianDistribution\n  UnivariateGaussianDistributionEstimator::estimate(const std::vector<double>::const_iterator dataBegin,\n                                                    const std::vector<double>::const_iterator dataEnd) const\n{\n    double var = variance(dataBegin, dataEnd);\n\n    if (var == 0.0) {\n        std::cerr << \"WARNING: UnivariateGaussianDistributionEstimator: Variance in the data was 0. Setting variance \"\n                     \"to 1e-4.\\n\";\n        var = 1e-4;\n    }\n\n    return UnivariateGaussianDistribution(mean(dataBegin, dataEnd), var);\n}\n\n\nDistPtr\n  DiscreteGaussianDistributionEstimator::estimateDistribution(const std::vector<double>::const_iterator dataBegin,\n                                                              const std::vector<double>::const_iterator dataEnd) const\n{\n    return DistPtr{new DiscreteGaussianDistribution(estimate(dataBegin, dataEnd))};\n}\n\n\nDiscreteGaussianDistribution\n  DiscreteGaussianDistributionEstimator::estimate(const std::vector<double>::const_iterator dataBegin,\n                                                  const std::vector<double>::const_iterator dataEnd) const\n{\n    double var = variance(dataBegin, dataEnd);\n\n    if (var == 0.0) {\n        std::cerr\n          << \"WARNING: DiscreteGaussianDistributionEstimator: Variance in the data was 0. Setting variance to 1e-4.\\n\";\n        var = 1e-4;\n    }\n\n    return DiscreteGaussianDistribution(mean(dataBegin, dataEnd), var);\n}\n\n\nDistPtr GammaDistributionEstimator::estimateDistribution(const std::vector<double>::const_iterator dataBegin,\n                                                         const std::vector<double>::const_iterator dataEnd) const\n{\n    return DistPtr{new GammaDistribution(estimate(dataBegin, dataEnd))};\n}\n\n\nGammaDistribution GammaDistributionEstimator::estimate(const std::vector<double>::const_iterator dataBegin,\n                                                       const std::vector<double>::const_iterator dataEnd) const\n{\n    std::vector<double> filtered(dataBegin, dataEnd);\n    auto validDataEnd = std::remove_if(filtered.begin(), filtered.end(), [](double x) {\n        return x <= 0.0;\n    });\n\n    int numValidData = std::distance(filtered.begin(), validDataEnd);\n    assert(numValidData);\n\n    using namespace std::placeholders;\n\n    double sumXi = std::accumulate(filtered.begin(), validDataEnd, 0.0);\n    double sumLogXi = 0.0;\n    for (auto val : boost::make_iterator_range(filtered.begin(), validDataEnd)) {\n        sumLogXi += std::log(val);\n    }\n\n    double s = std::log(sumXi / numValidData) - sumLogXi / numValidData;\n    double k0 = (3.0 - s + std::sqrt(std::pow(s - 3.0, 2.0) + 24.0 * s)) / (12.0 * s);\n\n    //     NewtonRaphsonErrorFunc<double> newton(std::bind(log_likelihood_func,  _1, sumXi, sumLogXi, filtered.size()),\n    //                                           std::bind(log_likelihood_deriv, _1, sumXi, sumLogXi, filtered.size()));\n    //\n    //     double k     = find_single_root(newton, k0, 1e-5);\n    double k = k0;\n    double theta = sumXi / (numValidData * k);\n    return GammaDistribution(k, theta);\n}\n\n\nDistPtr BetaDistributionEstimator::estimateDistribution(const std::vector<double>::const_iterator dataBegin,\n                                                        const std::vector<double>::const_iterator dataEnd) const\n{\n    return DistPtr{new BetaDistribution(estimate(dataBegin, dataEnd))};\n}\n\n\nBetaDistribution BetaDistributionEstimator::estimate(const std::vector<double>::const_iterator dataBegin,\n                                                     const std::vector<double>::const_iterator dataEnd) const\n{\n    double mean = math::mean(dataBegin, dataEnd);\n    double variance = math::variance(dataBegin, dataEnd);\n\n    if (variance == 0.0) {\n        std::cerr << \"WARNING: BetaDistributionEstimator: Variance of data was 0. Setting to 1e-4.\\n\";\n        variance = 1e-4;\n    }\n\n    if (variance < mean * (1 - mean) && (variance > 0.0)) {\n        double alpha = mean * ((mean * (1.0 - mean) / variance) - 1.0);\n        double beta = (1.0 - mean) * ((mean * (1.0 - mean) / variance) - 1.0);\n        return BetaDistribution(alpha, beta);\n    } else {\n        std::cerr << \"ERROR: BetaDistributionEstimator: Could not use method-of-moments to find parameters. Mean:\"\n                  << mean << \" Variance:\" << variance << '\\n'\n                  << \" Variance should be less than \" << (mean * (1 - mean)) << '\\n';\n        return BetaDistribution();\n    }\n}\n\n\nExponentialDistributionEstimator::ExponentialDistributionEstimator(double maxValue) : max_(maxValue)\n{\n}\n\n\nDistPtr ExponentialDistributionEstimator::estimateDistribution(const std::vector<double>::const_iterator dataBegin,\n                                                               const std::vector<double>::const_iterator dataEnd) const\n{\n    return DistPtr{new ExponentialDistribution(estimate(dataBegin, dataEnd))};\n}\n\n\nExponentialDistribution\n  ExponentialDistributionEstimator::estimate(const std::vector<double>::const_iterator dataBegin,\n                                             const std::vector<double>::const_iterator dataEnd) const\n{\n    double mean = math::mean(dataBegin, dataEnd);\n    if (mean > 0.0) {\n        return ExponentialDistribution(1.0 / mean, max_);\n    } else {\n        std::cerr << \"ERROR: ExponentialDistributionEstimator: Invalid mean for the data:\" << mean\n                  << \" Must be greater than 0.\\n\";\n        return ExponentialDistribution(1.0, max_);\n    }\n}\n\n\nTruncatedGaussianDistributionEstimator::TruncatedGaussianDistributionEstimator(double lower, double upper)\n: lower_(lower)\n, upper_(upper)\n{\n}\n\n\nDistPtr\n  TruncatedGaussianDistributionEstimator::estimateDistribution(const std::vector<double>::const_iterator dataBegin,\n                                                               const std::vector<double>::const_iterator dataEnd) const\n{\n    return DistPtr{new TruncatedGaussianDistribution(estimate(dataBegin, dataEnd))};\n}\n\n\nTruncatedGaussianDistribution\n  TruncatedGaussianDistributionEstimator::estimate(const std::vector<double>::const_iterator dataBegin,\n                                                   const std::vector<double>::const_iterator dataEnd) const\n{\n    double var = variance(dataBegin, dataEnd);\n\n    if (var == 0.0) {\n        std::cerr\n          << \"WARNING: TruncatedGaussianDistributionEstimator: Variance in the data was 0. Setting variance to 1e-4.\\n\";\n        var = 1e-4;\n    }\n\n    return TruncatedGaussianDistribution(mean(dataBegin, dataEnd), var, lower_, upper_);\n}\n\n}   // namespace math\n}   // namespace vulcan\n", "meta": {"hexsha": "6b4767771842e9ad011979185adbad0d289e4d4e", "size": 8587, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/math/univariate_distribution_estimator_impl.cpp", "max_stars_repo_name": "anuranbaka/Vulcan", "max_stars_repo_head_hexsha": "56339f77f6cf64b5fda876445a33e72cd15ce028", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-03-05T23:56:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-17T19:06:50.000Z", "max_issues_repo_path": "src/math/univariate_distribution_estimator_impl.cpp", "max_issues_repo_name": "anuranbaka/Vulcan", "max_issues_repo_head_hexsha": "56339f77f6cf64b5fda876445a33e72cd15ce028", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-03-07T01:23:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-07T01:23:47.000Z", "max_forks_repo_path": "src/math/univariate_distribution_estimator_impl.cpp", "max_forks_repo_name": "anuranbaka/Vulcan", "max_forks_repo_head_hexsha": "56339f77f6cf64b5fda876445a33e72cd15ce028", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-03T07:54:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-03T07:54:16.000Z", "avg_line_length": 37.0129310345, "max_line_length": 120, "alphanum_fraction": 0.6577384418, "num_tokens": 1978, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152497, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4859234009373571}}
{"text": "/*\n * Copyright (c) 2021 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 <random>\n#include <vector>\n#include <cstdlib>\n#include <Eigen/Core>\n#if defined(_WIN32) // windows\n#  define NOMINMAX   // to remove min,max macro\n#  include <windows.h>  // should put before glfw3.h\n#endif\n#define GL_SILENCE_DEPRECATION\n#include <GLFW/glfw3.h>\n\n#include \"delfem2/mshprimitive.h\"\n#include \"delfem2/eigen/ls_dense.h\"\n#include \"delfem2/eigen/ls_sparse.h\"\n#include \"delfem2/femsolidlinear.h\"\n#include \"delfem2/lsitrsol.h\"\n#include \"delfem2/mshuni.h\"\n#include \"delfem2/femutil.h\"\n#include \"delfem2/glfw/viewer3.h\"\n#include \"delfem2/glfw/util.h\"\n#include \"delfem2/opengl/old/funcs.h\"\n#include \"delfem2/opengl/old/mshuni.h\"\n\nnamespace dfm2 = delfem2;\n\n// --------------------------------------------------------------\n\nvoid Simulation_Mat3(\n    std::vector<double> &aDisp,\n    delfem2::CMatrixSparseBlock<Eigen::Matrix3d, Eigen::aligned_allocator<Eigen::Matrix3d>> &mA,\n    //\n    const std::vector<double> &aXYZ0,\n    const std::vector<unsigned int> &aHex,\n    const std::vector<int> &aBCFlag,\n    //\n    double mass,\n    double myu,\n    double lambda,\n    const double gravity[3]) {\n  const unsigned int np = aXYZ0.size() / 3;\n  const unsigned int nDoF = np * 3;\n  mA.setZero();\n  {\n    double ddW[8][8][3][3];\n    {\n      const double gravity_zero[3] = {0, 0, 0};\n      double aP0[8][3], aU[8][3];\n      delfem2::FetchData<8, 3>(aP0, aHex.data(), aXYZ0.data());\n      delfem2::FetchData<8, 3>(aU, aHex.data(), aDisp.data());\n      double dW[8][3];\n      std::fill_n(&dW[0][0], 8 * 3, 0.0);\n      std::fill_n(&ddW[0][0][0][0], 8 * 8 * 3 * 3, 0.0);\n      delfem2::elemMatRes_LinearSolidGravity3_Static_Q1(\n          myu, lambda,\n          0, gravity_zero,\n          aP0, aU, ddW, dW);\n    }\n    std::vector<unsigned int> tmp_buffer;\n    for (unsigned int ih = 0; ih < aHex.size() / 8; ++ih) {\n      const unsigned int *aIP = aHex.data() + ih * 8;\n      delfem2::Merge<8, 8, 3, 3, double>(mA, aIP, aIP, ddW, tmp_buffer);\n    }\n  }\n  Eigen::VectorXd vec_b(nDoF);\n  vec_b.setZero();\n  for (unsigned int ip = 0; ip < np; ++ip) {\n    vec_b[ip * 3 + 0] += mass * gravity[0];\n    vec_b[ip * 3 + 1] += mass * gravity[1];\n    vec_b[ip * 3 + 2] += mass * gravity[2];\n  }\n  { // comput rhs vectors\n    const Eigen::VectorXd &vd = Eigen::Map<const Eigen::VectorXd>(aDisp.data(), nDoF);\n    AddMatVec(vec_b, 1.0, -1.0, mA, vd);\n    std::cout << \"energy\" << vec_b.dot(vd) << std::endl;\n  }\n  SetFixedBC_Dia(mA, aBCFlag.data(), 1.f);\n  SetFixedBC_Col(mA, aBCFlag.data());\n  SetFixedBC_Row(mA, aBCFlag.data());\n  delfem2::setZero_Flag(vec_b, aBCFlag, 0);\n  // --------------------------------\n  Eigen::VectorXd vec_x(vec_b.size());\n  {\n    double conv_ratio = 1.0e-6;\n    int iteration = 1000;\n    const std::size_t n = vec_b.size();\n    Eigen::VectorXd tmp0(n), tmp1(n);\n    std::vector<double> aConv = delfem2::Solve_CG(\n        vec_b, vec_x, tmp0, tmp1,\n        conv_ratio, iteration, mA);\n    std::cout << aConv.size() << std::endl;\n  }\n  // ------------------------------\n  dfm2::XPlusAY(\n      aDisp,\n      aBCFlag, 1.0, vec_x);\n}\n\nvoid Simulation_Mat4(\n    std::vector<double> &aDisp,\n    delfem2::CMatrixSparseBlock<Eigen::Matrix4d, Eigen::aligned_allocator<Eigen::Matrix4d>, 3> &mA,\n    //\n    const std::vector<double> &aXYZ0,\n    const std::vector<unsigned int> &aHex,\n    const std::vector<int> &aBCFlag,\n    //\n    double mass,\n    double myu,\n    double lambda,\n    const double gravity[3]) {\n  const unsigned int np = aXYZ0.size() / 3;\n  mA.setZero();\n  {\n    double ddW[8][8][3][3];\n    {\n      const double gravity_zero[3] = {0, 0, 0};\n      double aP0[8][3], aU[8][3];\n      delfem2::FetchData<8, 3>(aP0, aHex.data(), aXYZ0.data());\n      delfem2::FetchData<8, 3>(aU, aHex.data(), aDisp.data());\n      double dW[8][3];\n      std::fill_n(&dW[0][0], 8 * 3, 0.0);\n      std::fill_n(&ddW[0][0][0][0], 8 * 8 * 3 * 3, 0.0);\n      delfem2::elemMatRes_LinearSolidGravity3_Static_Q1(\n          myu, lambda,\n          0, gravity_zero,\n          aP0, aU, ddW, dW);\n    }\n    std::vector<unsigned int> tmp_buffer;\n    for (unsigned int ih = 0; ih < aHex.size() / 8; ++ih) {\n      const unsigned int *aIP = aHex.data() + ih * 8;\n      delfem2::Merge<8, 8, 3, 3, double>(mA, aIP, aIP, ddW, tmp_buffer);\n    }\n  }\n  Eigen::Matrix<double, -1, 4, Eigen::RowMajor> vec_b(np, 4);\n  vec_b.setZero();\n  for (unsigned int ip = 0; ip < np; ++ip) {\n    vec_b(ip, 0) += mass * gravity[0];\n    vec_b(ip, 1) += mass * gravity[1];\n    vec_b(ip, 2) += mass * gravity[2];\n  }\n  { // comput rhs vectors\n    Eigen::Matrix<double, -1, 4, Eigen::RowMajor> vd(np, 4);\n    for (unsigned int ip = 0; ip < np; ++ip) {\n      vd(ip, 0) = aDisp[ip * 3 + 0];\n      vd(ip, 1) = aDisp[ip * 3 + 1];\n      vd(ip, 2) = aDisp[ip * 3 + 2];\n      vd(ip, 3) = 0.0;\n    }\n    AddMatVec(vec_b, 1.0, -1.0, mA, vd);\n    std::cout << \"energy\" << delfem2::Dot(vec_b, vd) << std::endl;\n  }\n  SetFixedBC_Dia(mA, aBCFlag.data(), 1.f);\n  SetFixedBC_Col(mA, aBCFlag.data());\n  SetFixedBC_Row(mA, aBCFlag.data());\n  delfem2::setZero_Flag(vec_b, np, aBCFlag, 0);\n  // --------------------------------\n  Eigen::Matrix<double, -1, 4, Eigen::RowMajor> vec_x(np, 4);\n  {\n    double conv_ratio = 1.0e-6;\n    int iteration = 1000;\n    Eigen::Matrix<double, -1, 4, Eigen::RowMajor> tmp0(np, 4), tmp1(np, 4);\n    std::vector<double> aConv = delfem2::Solve_CG(\n        vec_b, vec_x, tmp0, tmp1,\n        conv_ratio, iteration, mA);\n    std::cout << aConv.size() << std::endl;\n  }\n  // ------------------------------\n  dfm2::XPlusAY(\n      aDisp,\n      np, aBCFlag, 1.0, vec_x);\n}\n\nint main() {\n  std::vector<double> aXYZ0;\n  std::vector<unsigned int> aHex;\n  dfm2::MeshHex3_Grid(\n      aXYZ0, aHex,\n      20, 10, 10, 0.1);\n  std::vector<double> aMass(aXYZ0.size() / 3);\n\n  delfem2::CMatrixSparseBlock<Eigen::Matrix3d, Eigen::aligned_allocator<Eigen::Matrix3d>> A3;\n  delfem2::CMatrixSparseBlock<Eigen::Matrix4d, Eigen::aligned_allocator<Eigen::Matrix4d>, 3> A4;\n  {\n    const unsigned int np = aXYZ0.size() / 3;\n    std::vector<unsigned int> psup_ind, psup;\n    dfm2::JArray_PSuP_MeshElem(\n        psup_ind, psup,\n        aHex.data(), aHex.size() / 8, 8,\n        aXYZ0.size() / 3);\n    A3.Initialize(np);\n    A3.SetPattern(psup_ind.data(), psup_ind.size(), psup.data(), psup.size());\n    A4.Initialize(np);\n    A4.SetPattern(psup_ind.data(), psup_ind.size(), psup.data(), psup.size());\n  }\n\n  std::vector<double> aDisp(aXYZ0.size(), 0.0);\n  std::vector<int> aBCFlag(aXYZ0.size(), 0.0); // 0: free, 1: fix BC\n  {\n    for (unsigned int ip = 0; ip < aXYZ0.size() / 3; ++ip) {\n      double x0 = aXYZ0[ip * 3 + 0];\n      if (x0 > 1.0e-10) { continue; }\n      aBCFlag[ip * 3 + 0] = 1;\n      aBCFlag[ip * 3 + 1] = 1;\n      aBCFlag[ip * 3 + 2] = 1;\n    }\n  }\n  const double mass = 0.5;\n  const double gravity[3] = {0, 0, -10};\n  aDisp.assign(aXYZ0.size(), 0.0);\n  for (unsigned int i = 0; i < aDisp.size(); ++i) {\n    if (aBCFlag[i] != 0) { continue; }\n    aDisp[i] = (i % 10) * 1.0e-4;\n  }\n  Simulation_Mat3(\n      aDisp, A3,\n      aXYZ0, aHex, aBCFlag,\n      mass, 1.0e+5, 1.e+5, gravity);\n\n  aDisp.assign(aXYZ0.size(), 0.0);\n  for (unsigned int i = 0; i < aDisp.size(); ++i) {\n    if (aBCFlag[i] != 0) { continue; }\n    aDisp[i] = (i % 10) * 1.0e-4;\n  }\n  Simulation_Mat4(\n      aDisp, A4,\n      aXYZ0, aHex, aBCFlag,\n      mass, 1.0e+5, 1.e+5, gravity);\n\n  // ----------------------\n  delfem2::glfw::CViewer3 viewer(1.5);\n//  viewer.camera.camera_rot_mode = delfem2::CCam3_OnAxisZplusLookOrigin<double>::CAMERA_ROT_MODE::ZTOP;\n//  viewer.camera.theta = 0.1;\n//  viewer.camera.psi = 0.1;\n  delfem2::glfw::InitGLOld();\n  viewer.InitGL();\n\n  delfem2::opengl::setSomeLighting();\n  while (!glfwWindowShouldClose(viewer.window)) {\n    // -----\n    viewer.DrawBegin_oldGL();\n    ::glDisable(GL_LIGHTING);\n    ::glColor3d(0, 0, 0);\n    delfem2::opengl::DrawMeshHex3D_EdgeDisp(\n        aXYZ0.data(), aXYZ0.size() / 3,\n        aHex.data(), aHex.size() / 8,\n        aDisp.data());\n    //\n    ::glEnable(GL_LIGHTING);\n//    dfm2::opengl::DrawMeshHex3D_FaceNorm(aXYZ0.data(), aHex.data(), aHex.size() / 8);\n    delfem2::opengl::DrawHex3D_FaceNormDisp(aXYZ0, aHex, aDisp);\n    viewer.SwapBuffers();\n    glfwPollEvents();\n  }\n  glfwDestroyWindow(viewer.window);\n  glfwTerminate();\n  exit(EXIT_SUCCESS);\n}\n", "meta": {"hexsha": "f0e4f90364c735535b23905b774631e4fb91bc90", "size": 8411, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples_oldgl_glfw_eigen/03_FemSolidLinear3/main.cpp", "max_stars_repo_name": "nobuyuki83/delfem2", "max_stars_repo_head_hexsha": "118768431ccc5b77ed10b8f76f625d38e0b552f0", "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": "examples_oldgl_glfw_eigen/03_FemSolidLinear3/main.cpp", "max_issues_repo_name": "nobuyuki83/delfem2", "max_issues_repo_head_hexsha": "118768431ccc5b77ed10b8f76f625d38e0b552f0", "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": "examples_oldgl_glfw_eigen/03_FemSolidLinear3/main.cpp", "max_forks_repo_name": "nobuyuki83/delfem2", "max_forks_repo_head_hexsha": "118768431ccc5b77ed10b8f76f625d38e0b552f0", "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": 31.8598484848, "max_line_length": 104, "alphanum_fraction": 0.5806681726, "num_tokens": 3040, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118221, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.48592339050439354}}
{"text": "/*\n * Copyright 2018, LAAS-CNRS\n * Author: Steve Tonneau\n */\n\n#ifndef BEZIER_COM_TRAJ_LIB_COMMON_SOLVE_H\n#define BEZIER_COM_TRAJ_LIB_COMMON_SOLVE_H\n\n#include <hpp/bezier-com-traj/local_config.hh>\n#include <hpp/bezier-com-traj/data.hh>\n#include <hpp/bezier-com-traj/waypoints/waypoints_definition.hh>\n#include <hpp/bezier-com-traj/solver/solver-abstract.hpp>\n\n#include <Eigen/Dense>\n\nnamespace bezier_com_traj {\n\n/**\n * @brief ComputeDiscretizedWaypoints Given the waypoints defining a bezier curve,\n * computes a discretization of the curve\n * @param wps original waypoints\n * @param bernstein berstein polynoms for\n * @param numSteps desired number of wayoints\n * @return a vector of waypoint representing the discretization of the curve\n */\nBEZIER_COM_TRAJ_DLLAPI std::vector<waypoint6_t> ComputeDiscretizedWaypoints(\n    const std::vector<waypoint6_t>& wps, const std::vector<ndcurves::Bern<double> >& bernstein, int numSteps);\n\n/**\n * @brief compute6dControlPointInequalities Given linear and angular control waypoints,\n * compute the inequality matrices A and b, A x <= b that constrain the desired control point x.\n * @param cData data for the current contact phase\n * @param wps waypoints or the linear part of the trajectory\n * @param wpL waypoints or the angular part of the trajectory\n * @param useAngMomentum whether the angular momentum is consider or equal to 0\n * @param fail set to true if problem is found infeasible\n * @return\n */\nBEZIER_COM_TRAJ_DLLAPI std::pair<MatrixXX, VectorX> compute6dControlPointInequalities(\n    const ContactData& cData, const std::vector<waypoint6_t>& wps, const std::vector<waypoint6_t>& wpL,\n    const bool useAngMomentum, bool& fail);\n\n/**\n * @brief compute6dControlPointEqualities Given linear and angular control waypoints,\n * compute the equality matrices D and d, D [x; Beta]' = d that constrain the desired control point x and contact\n * forces Beta.\n * @param cData data for the current contact phase\n * @param wps waypoints or the linear part of the trajectory\n * @param wpL waypoints or the angular part of the trajectory\n * @param useAngMomentum whether the angular momentum is consider or equal to 0\n * @param fail set to true if problem is found infeasible\n * @return\n */\nBEZIER_COM_TRAJ_DLLAPI std::pair<MatrixXX, VectorX> compute6dControlPointEqualities(\n    const ContactData& cData, const std::vector<waypoint6_t>& wps, const std::vector<waypoint6_t>& wpL,\n    const bool useAngMomentum, bool& fail);\n\n/**\n * @brief solve x' h x + 2 g' x, subject to A*x <= b using quadprog\n * @param A Inequality matrix\n * @param b Inequality vector\n * @param H Cost matrix\n * @param g cost Vector\n * @param x initGuess initial guess\n * @param minBounds lower bounds on x values. Can be of size 0 if all elements of x are unbounded in that direction, or\n * a size equal to x. Unbounded elements should be lesser or equal to solvers::UNBOUNDED_UP;\n * @param maxBounds upper bounds on x values. Can be of size 0 if all elements of x are unbounded in that direction, or\n * a size equal to x Unbounded elements should be higher or lower than solvers::UNBOUNDED_DOWN;\n * @param solver solver used to solve QP or LP. If LGPK is used, Hessian is not considered as an lp is solved\n * @return\n */\nBEZIER_COM_TRAJ_DLLAPI ResultData solve(Cref_matrixXX A, Cref_vectorX b, Cref_matrixXX H, Cref_vectorX g,\n                                        Cref_vectorX initGuess, Cref_vectorX minBounds, Cref_vectorX maxBounds,\n                                        const solvers::SolverType solver = solvers::SOLVER_QUADPROG);\n/**\n * @brief solve x' h x + 2 g' x, subject to A*x <= b and D*x = c using quadprog\n * @param A Inequality matrix\n * @param b Inequality vector\n * @param D Equality matrix\n * @param d Equality vector\n * @param H Cost matrix\n * @param g cost Vector\n * @return\n */\nBEZIER_COM_TRAJ_DLLAPI ResultData solve(Cref_matrixXX A, Cref_vectorX b, Cref_matrixXX D, Cref_vectorX d,\n                                        Cref_matrixXX H, Cref_vectorX g, Cref_vectorX initGuess,\n                                        const solvers::SolverType solver = solvers::SOLVER_QUADPROG);\n\n/**\n * @brief solve x' h x + 2 g' x, subject to A*x <= b using quadprog, with x of fixed dimension 3\n * @param Ab Inequality matrix and vector\n * @param Hg Cost matrix and vector\n * @return\n */\nBEZIER_COM_TRAJ_DLLAPI ResultData solve(const std::pair<MatrixXX, VectorX>& Ab, const std::pair<MatrixXX, VectorX>& Hg,\n                                        const VectorX& init,\n                                        const solvers::SolverType solver = solvers::SOLVER_QUADPROG);\n\n/**\n * @brief solve x' h x + 2 g' x, subject to A*x <= b  and D*x = c using quadprog, with x of fixed dimension 3\n * @param Ab Inequality matrix and vector\n * @param Dd Equality matrix and vector\n * @param Hg Cost matrix and vector\n * @param minBounds lower bounds on x values. Can be of size 0 if all elements of x are unbounded in that direction, or\n * a size equal to x. Unbounded elements should be equal to -std::numeric_limits<double>::infinity();\n * @param maxBounds upper bounds on x values. Can be of size 0 if all elements of x are unbounded in that direction, or\n * a size equal to x Unbounded elements should be equal to  std::numeric_limits<double>::infinity();\n * @param solver solver used to solve QP or LP. If LGPK is used, Hessian is not considered as an lp is solved\n * @return\n */\nBEZIER_COM_TRAJ_DLLAPI ResultData solve(const std::pair<MatrixXX, VectorX>& Ab, const std::pair<MatrixXX, VectorX>& Dd,\n                                        const std::pair<MatrixXX, VectorX>& Hg, Cref_vectorX minBounds,\n                                        Cref_vectorX maxBounds, const VectorX& init,\n                                        const solvers::SolverType solver = solvers::SOLVER_QUADPROG);\n\ntemplate <typename Point>\nBEZIER_COM_TRAJ_DLLAPI std::vector<std::pair<double, Point> > computeDiscretizedWaypoints(const ProblemData& pData,\n                                                                                          double T,\n                                                                                          const T_time& timeArray);\n\ntemplate <typename Point>\nBEZIER_COM_TRAJ_DLLAPI std::vector<std::pair<double, Point> > computeDiscretizedAccelerationWaypoints(\n    const ProblemData& pData, double T, const T_time& timeArray);\n\n}  // end namespace bezier_com_traj\n\n#include \"common_solve_methods.inl\"\n\n#endif\n", "meta": {"hexsha": "4719bae06f374c0e8abff0e97481f701028cb79a", "size": 6450, "ext": "hh", "lang": "C++", "max_stars_repo_path": "include/hpp/bezier-com-traj/common_solve_methods.hh", "max_stars_repo_name": "nim65s/hpp-bezier-com-traj", "max_stars_repo_head_hexsha": "7cb25463a353cd917468af12e5b325c8366af66e", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2019-09-17T13:06:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-09T22:52:40.000Z", "max_issues_repo_path": "include/hpp/bezier-com-traj/common_solve_methods.hh", "max_issues_repo_name": "nim65s/hpp-bezier-com-traj", "max_issues_repo_head_hexsha": "7cb25463a353cd917468af12e5b325c8366af66e", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-01-16T10:02:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-16T17:14:00.000Z", "max_forks_repo_path": "include/hpp/bezier-com-traj/common_solve_methods.hh", "max_forks_repo_name": "nim65s/hpp-bezier-com-traj", "max_forks_repo_head_hexsha": "7cb25463a353cd917468af12e5b325c8366af66e", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2019-02-04T14:36:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-20T15:42:17.000Z", "avg_line_length": 49.6153846154, "max_line_length": 119, "alphanum_fraction": 0.6973643411, "num_tokens": 1629, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118221, "lm_q2_score": 0.5926665999540697, "lm_q1q2_score": 0.4859233905043934}}
{"text": "#include <iostream>\n#include <Eigen/IterativeLinearSolvers>\n\n#include <libv/lma/lm/solver/solver.hpp>\n#include <libv/lma/lm/solver/verbose.hpp>\n\nusing namespace Eigen;\n\nvoid eigen_pcg(const Eigen::MatrixXd& m, const Eigen::VectorXd& jte)\n{\n  \n  std::cout << \"\\n\\n EIGEN PCG \" << std::endl;\n  size_t n = jte.size();\n  VectorXd x(n), b(jte);\n//   typedef SparseMatrix<double> Mat;\n  typedef Eigen::MatrixXd Mat;\n//   Mat A(n,n);\n  Mat A = m;\n//   for(size_t i = 0 ; i < m.cols() ; ++i)\n//     for(size_t j = 0 ; j < m.rows() ; ++j)\n//       A.coeff(j,i) = m(j,i);\n      \n//   for(size_t i = 0 ; i < n ; ++i)\n//     A.coeffRef(i,i) = 1.0;\n//   A.setIdentity();\n  std::cout << A << std::endl;\n  x.setZero();\n  std::cout <<\"\\n X = \" <<  x.transpose() << std::endl;\n  std::cout <<\"\\n B = \" <<  b.transpose() << std::endl;\n  // fill A and b\n  ConjugateGradient<Mat> cg;\n  cg.compute(A);\n  x = cg.solve(b);\n  std::cout << \"#iterations:     \" << cg.iterations() << std::endl;\n  std::cout << \"estimated error: \" << cg.error()      << std::endl;\n  // update b, and solve again\n//   x = cg.solve(b);\n  std::cout << \"\\n X = \" << x.transpose() << std::endl;\n}\n\n// typedef Eigen::Matrix<double,2,1> Type0;\n// typedef Eigen::Matrix<double,3,1> Type1;\n// typedef Eigen::Matrix<double,1,1> Type2;\n// \n// struct F\n// {\n//   bool operator()(const Type0& , const Type1& , const Type2&, Eigen::Matrix<double,2,1>&) const\n//   {\n//     return true;\n//   }\n// };\n\nint main()\n{\n  /*\n  Type0 t0;\n  Type1 t1;\n  Type2 t2;\n  std::cout << \" Test pcg \" << std::endl;\n  lma::Solver<F> solver(1,1);\n  \n//   solver.algo.norm_eq.seuil=0.9999;\n//   solver.algo.norm_eq.max_iteration=100000typedef typename SelectAlgo<Container,Container::NbClass,AlgoTag>::type Algorithm;\n//       Algorithm algo(config);;\n  \n  auto i0 = ttt::Indice<Type0*>(0);\n  auto i1 = ttt::Indice<Type1*>(0);\n  auto i2 = ttt::Indice<Type2*>(0);\n  solver.add(F(),&t0,&t1,&t2);//lma::bf::make_vector(i0,i1,i2),F());\n//   solver.solve(lma::enable_verbose_output());\n//   solver.algo.compute_b(solver.algo.ba_);\n//   solver.algo.compute_delta_a(solver.algo.ba_);\n  using namespace lma;\n  typedef typename SelectAlgo<lma::Solver<F>::Container,lma::Solver<F>::Container::NbClass,ImplicitSchurTag<1>>::type Algorithm;\n  Algorithm algo(ImplicitSchurTag<1>(0.9999,100000));\n  algo.init(solver.bundle);\n  \n  lma::bf::at_key<lma::bf::pair<Type0*,Type0*>>(algo.ba_.h())(i0,0) << \n    1,0,\n    0,2;\n    \n  lma::bf::at_key<lma::bf::pair<Type2*,Type2*>>(algo.ba_.h())(i2,0) << \n    1;\n  \n  lma::bf::at_key<lma::bf::pair<Type0*,Type1*>>(algo.ba_.h())(i0,0) << \n    3.2,0.5,2,\n    0,-2.5,-1.5;\n    \n  lma::bf::at_key<lma::bf::pair<Type1*,Type1*>>(algo.ba_.h())(i1,0) << \n    3,0,0,\n    0,4,0,\n    0,0,5;\n    \n  lma::bf::at_key<Type0*>(algo.ba_.jte())(i0) << 1,2;\n  lma::bf::at_key<Type1*>(algo.ba_.jte())(i1) << 3,4,5;\n  lma::bf::at_key<Type2*>(algo.ba_.jte())(i2) << 1;\n  \n  \n  \n  std::cout << std::endl;\n  std::cout << \" A = \\n\" << lma::to_mat(algo.ba_.h()) << std::endl;\n//   std::cout << \" B = \" << lma::to_vect(solver.algo.schur_.bs_).transpose() << std::endl;\n  std::cout << \" B = \" << lma::to_vect(algo.ba_.jte()).transpose() << std::endl;\n  \n  algo.compute_y(algo.ba_);\n  algo.compute_b(algo.ba_);\n  algo.compute_delta_a(algo.ba_);\n  \n  std::cout << \" X = \" << lma::to_vect(algo.ba_.delta()).transpose() << std::endl;\n  \n  eigen_pcg(lma::to_mat(algo.ba_.h()),lma::to_vect(algo.ba_.jte()));*/\n}\n\n", "meta": {"hexsha": "41c0336090f3f0d8a0ca993471720ec50fbf335d", "size": 3422, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/pcg.cpp", "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": "tests/pcg.cpp", "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": "tests/pcg.cpp", "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": 30.0175438596, "max_line_length": 128, "alphanum_fraction": 0.5829924021, "num_tokens": 1239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933183101078, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.48592338528791146}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2020-2021 Mikhail Komarov <nemo@nil.foundation>\n// Copyright (c) 2020-2021 Nikita Kaskov <nbering@nil.foundation>\n//\n// MIT License\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n//---------------------------------------------------------------------------//\n\n#define BOOST_TEST_MODULE multiexpr_test\n\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 <cstdio>\n#include <vector>\n#include <chrono>\n#include <ctime>\n\n#include <nil/crypto3/algebra/multiexp/multiexp.hpp>\n#include <nil/crypto3/algebra/multiexp/policies.hpp>\n\n#include <nil/crypto3/algebra/curves/alt_bn128.hpp>\n#include <nil/crypto3/algebra/curves/bls12.hpp>\n//#include <nil/crypto3/algebra/curves/bn128.hpp>\n// #include <nil/crypto3/algebra/curves/brainpool_r1.hpp>\n#include <nil/crypto3/algebra/curves/edwards.hpp>\n// #include <nil/crypto3/algebra/curves/frp_v1.hpp>\n// #include <nil/crypto3/algebra/curves/gost_A.hpp>\n#include <nil/crypto3/algebra/curves/mnt4.hpp>\n#include <nil/crypto3/algebra/curves/mnt6.hpp>\n// #include <nil/crypto3/algebra/curves/p192.hpp>\n// #include <nil/crypto3/algebra/curves/p224.hpp>\n// #include <nil/crypto3/algebra/curves/p256.hpp>\n// #include <nil/crypto3/algebra/curves/p384.hpp>\n// #include <nil/crypto3/algebra/curves/p521.hpp>\n// #include <nil/crypto3/algebra/curves/secp.hpp>\n// #include <nil/crypto3/algebra/curves/sm2p_v1.hpp>\n// #include <nil/crypto3/algebra/curves/x962_p.hpp>\n\n#include <nil/crypto3/algebra/curves/params/multiexp/alt_bn128.hpp>\n#include <nil/crypto3/algebra/curves/params/multiexp/bls12.hpp>\n//#include <nil/crypto3/algebra/curves/params/multiexp/bn128.hpp>\n// #include <nil/crypto3/algebra/curves/params/multiexp/brainpool_r1.hpp>\n#include <nil/crypto3/algebra/curves/params/multiexp/edwards.hpp>\n// #include <nil/crypto3/algebra/curves/params/multiexp/frp_v1.hpp>\n// #include <nil/crypto3/algebra/curves/params/multiexp/gost_A.hpp>\n#include <nil/crypto3/algebra/curves/params/multiexp/mnt4.hpp>\n#include <nil/crypto3/algebra/curves/params/multiexp/mnt6.hpp>\n// #include <nil/crypto3/algebra/curves/params/multiexp/p192.hpp>\n// #include <nil/crypto3/algebra/curves/params/multiexp/p224.hpp>\n// #include <nil/crypto3/algebra/curves/params/multiexp/p256.hpp>\n// #include <nil/crypto3/algebra/curves/params/multiexp/p384.hpp>\n// #include <nil/crypto3/algebra/curves/params/multiexp/p521.hpp>\n// #include <nil/crypto3/algebra/curves/params/multiexp/secp.hpp>\n// #include <nil/crypto3/algebra/curves/params/multiexp/sm2p_v1.hpp>\n// #include <nil/crypto3/algebra/curves/params/multiexp/x962_p.hpp>\n\n#include <nil/crypto3/algebra/random_element.hpp>\n\nusing namespace nil::crypto3::algebra;\n\ntemplate<typename GroupType>\nusing run_result_t = std::pair<long long, std::vector<typename GroupType::value_type>>;\n\ntemplate<typename T>\nusing test_instances_t = std::vector<std::vector<T>>;\n\ntemplate<typename GroupType>\ntest_instances_t<GroupType> generate_group_elements(std::size_t count, std::size_t size) {\n    // generating a random group element is expensive,\n    // so for now we only generate a single one and repeat it\n    test_instances_t<GroupType> result(count);\n\n    for (size_t i = 0; i < count; i++) {\n\n        typename GroupType::value_type x =\n            random_element<GroupType>().to_projective();    // djb requires input to be in special form\n\n        for (size_t j = 0; j < size; j++) {\n            result[i].push_back(x);\n            // result[i].push_back(curve_random_element<GroupType>());\n        }\n    }\n\n    return result;\n}\n\ntemplate<typename FieldType>\ntest_instances_t<FieldType> generate_scalars(std::size_t count, std::size_t size) {\n    // we use SHA512_rng because it is much faster than\n    // FieldType::random_element()\n    test_instances_t<FieldType> result(count);\n\n    for (size_t i = 0; i < count; i++) {\n        for (size_t j = 0; j < size; j++) {\n            result[i].push_back(random_element<FieldType>(i * size + j));\n        }\n    }\n\n    return result;\n}\n\nlong long get_nsec_time() {\n    auto timepoint = std::chrono::high_resolution_clock::now();\n    return std::chrono::duration_cast<std::chrono::nanoseconds>(timepoint.time_since_epoch()).count();\n}\n\ntemplate<typename GroupType, typename FieldType, typename MultiexpMethod>\nrun_result_t<GroupType>\n    profile_multiexp(test_instances_t<GroupType> group_elements, test_instances_t<FieldType> scalars) {\n    long long start_time = get_nsec_time();\n\n    std::vector<typename GroupType::value_type> answers;\n    for (size_t i = 0; i < group_elements.size(); i++) {\n        answers.push_back(multiexp<MultiexpMethod>(group_elements[i].cbegin(), group_elements[i].cend(),\n                                                   scalars[i].cbegin(), scalars[i].cend(), 1));\n    }\n\n    long long time_delta = get_nsec_time() - start_time;\n\n    return run_result_t<GroupType>(time_delta, answers);\n}\n\ntemplate<typename GroupType, typename FieldType>\nvoid print_performance_csv(size_t expn_start, std::size_t expn_end_fast, std::size_t expn_end_naive,\n                           bool compare_answers) {\n    for (size_t expn = expn_start; expn <= expn_end_fast; expn++) {\n        printf(\"%ld\", expn);\n        fflush(stdout);\n\n        test_instances_t<GroupType> group_elements = generate_group_elements<GroupType>(10, 1 << expn);\n        test_instances_t<FieldType> scalars = generate_scalars<FieldType>(10, 1 << expn);\n\n        run_result_t<GroupType> result_bos_coster =\n            profile_multiexp<GroupType, FieldType, policies::multiexp_method_bos_coster>(group_elements, scalars);\n        printf(\"\\t%lld\", result_bos_coster.first);\n        fflush(stdout);\n\n        run_result_t<GroupType> result_djb =\n            profile_multiexp<GroupType, FieldType, policies::multiexp_method_BDLO12>(group_elements, scalars);\n        printf(\"\\t%lld\", result_djb.first);\n        fflush(stdout);\n\n        if (compare_answers && (result_bos_coster.second != result_djb.second)) {\n            fprintf(stderr, \"Answers NOT MATCHING (bos coster != djb)\\n\");\n        }\n\n        if (expn <= expn_end_naive) {\n            run_result_t<GroupType> result_naive =\n                profile_multiexp<GroupType, FieldType, policies::multiexp_method_naive_plain>(group_elements, scalars);\n            printf(\"\\t%lld\", result_naive.first);\n            fflush(stdout);\n\n            if (compare_answers && (result_bos_coster.second != result_naive.second)) {\n                fprintf(stderr, \"Answers NOT MATCHING (bos coster != naive)\\n\");\n            }\n        }\n\n        printf(\"\\n\");\n    }\n}\n\nBOOST_AUTO_TEST_SUITE(multiexp_test_suite)\n\nBOOST_AUTO_TEST_CASE(multiexp_test_case) {\n\n    std::cout << \"Testing BLS12-381 G1\" << std::endl;\n    print_performance_csv<curves::bls12<381>::g1_type<>, curves::bls12<381>::scalar_field_type>(2, 20, 14, true);\n\n    std::cout << \"Testing BLS12-381 G2\" << std::endl;\n    print_performance_csv<curves::bls12<381>::g2_type<>, curves::bls12<381>::scalar_field_type>(2, 20, 14, true);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "523ed810e9afdbf6be0475c66aac80331663622f", "size": 8131, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/multiexp.cpp", "max_stars_repo_name": "JasonCoombs/crypto3-algebra", "max_stars_repo_head_hexsha": "3ddb4eb0ed65dc046660cc49811d17a140a4c72f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-09-20T18:56:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T06:58:28.000Z", "max_issues_repo_path": "test/multiexp.cpp", "max_issues_repo_name": "JasonCoombs/crypto3-algebra", "max_issues_repo_head_hexsha": "3ddb4eb0ed65dc046660cc49811d17a140a4c72f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41.0, "max_issues_repo_issues_event_min_datetime": "2020-08-27T18:11:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-20T21:01:55.000Z", "max_forks_repo_path": "test/multiexp.cpp", "max_forks_repo_name": "NilFoundation/algebra", "max_forks_repo_head_hexsha": "f211b0ffb2c7d817d44d2a6d1cc586a6db62dc03", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-07-05T13:50:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T03:09:12.000Z", "avg_line_length": 42.1295336788, "max_line_length": 119, "alphanum_fraction": 0.7008977985, "num_tokens": 2082, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933183101077, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4859233852879114}}
{"text": "// Copyright (C) 2010-2021 Internet Systems Consortium, Inc. (\"ISC\")\n//\n// This Source Code Form is subject to the terms of the Mozilla Public\n// License, v. 2.0. If a copy of the MPL was not distributed with this\n// file, You can obtain one at http://mozilla.org/MPL/2.0/.\n\n#include <config.h>\n\n#include <perfdhcp/random_number_generator.h>\n\n#include <gtest/gtest.h>\n#include <boost/shared_ptr.hpp>\n\n#include <iostream>\n\nusing namespace isc;\nusing namespace isc::perfdhcp;\nusing namespace std;\n\n/// \\brief Test Fixture Class for uniform random number generator\n///\n/// The hard part for this test is how to test that the number is random?\n/// and how to test that the number is uniformly distributed?\n/// Or maybe we can trust the boost implementation\nclass UniformRandomIntegerGeneratorTest : public ::testing::Test {\npublic:\n    UniformRandomIntegerGeneratorTest():\n        gen_(min_, max_)\n    {\n    }\n    virtual ~UniformRandomIntegerGeneratorTest(){}\n\n    int gen() { return (gen_()); }\n    int max() const { return (max_); }\n    int min() const { return (min_); }\n\nprivate:\n    UniformRandomIntegerGenerator gen_;\n\n    const static int min_ = 1;\n    const static int max_ = 10;\n};\n\n// Some validation tests will incur performance penalty, so the tests are\n// made only in \"debug\" version with assert(). But if NDEBUG is defined\n// the tests will be failed since assert() is non-op in non-debug version.\n// The \"#ifndef NDEBUG\" is added to make the tests be performed only in\n// non-debug environment.\n// Note: the death test is not supported by all platforms.  We need to\n// compile tests using it selectively.\n#if !defined(NDEBUG)\n// Test of the constructor\nTEST_F(UniformRandomIntegerGeneratorTest, Constructor) {\n    // The range must be min<=max\n    ASSERT_THROW(UniformRandomIntegerGenerator(3, 2), InvalidLimits);\n}\n#endif\n\n// Test of the generated integers are in the range [min, max]\nTEST_F(UniformRandomIntegerGeneratorTest, IntegerRange) {\n    vector<int> numbers;\n\n    // Generate a lot of random integers\n    for (int i = 0; i < max()*10; ++i) {\n        numbers.push_back(gen());\n    }\n\n    // Remove the duplicated values\n    sort(numbers.begin(), numbers.end());\n    vector<int>::iterator it = unique(numbers.begin(), numbers.end());\n\n    // make sure the numbers are in range [min, max]\n    ASSERT_EQ(it - numbers.begin(), max() - min() + 1);\n}\n\n/// \\brief Test Fixture Class for weighted random number generator\nclass WeightedRandomIntegerGeneratorTest : public ::testing::Test {\npublic:\n    WeightedRandomIntegerGeneratorTest()\n    { }\n\n    virtual ~WeightedRandomIntegerGeneratorTest()\n    { }\n};\n\n// Test of the weighted random number generator constructor\nTEST_F(WeightedRandomIntegerGeneratorTest, Constructor) {\n    vector<double> probabilities;\n\n    // If no probabilities is provided, the smallest integer will always\n    // be generated\n    WeightedRandomIntegerGenerator gen(probabilities, 123);\n    for (int i = 0; i < 100; ++i) {\n        ASSERT_EQ(gen(), 123);\n    }\n\n/// Some validation tests will incur performance penalty, so the tests are\n/// made only in \"debug\" version with assert(). But if NDEBUG is defined\n/// the tests will be failed since assert() is non-op in non-debug version.\n/// The \"#ifndef NDEBUG\" is added to make the tests be performed only in\n/// non-debug environment.\n#if !defined(NDEBUG)\n    //The probability must be >= 0\n    probabilities.push_back(-0.1);\n    probabilities.push_back(1.1);\n    ASSERT_THROW(WeightedRandomIntegerGenerator gen2(probabilities),\n                 InvalidProbValue);\n\n    //The probability must be <= 1.0\n    probabilities.clear();\n    probabilities.push_back(0.1);\n    probabilities.push_back(1.1);\n    ASSERT_THROW(WeightedRandomIntegerGenerator gen3(probabilities),\n                 InvalidProbValue);\n\n    //The sum must be equal to 1.0\n    probabilities.clear();\n    probabilities.push_back(0.2);\n    probabilities.push_back(0.9);\n    ASSERT_THROW(WeightedRandomIntegerGenerator gen4(probabilities), SumNotOne);\n\n    //The sum must be equal to 1.0\n    probabilities.clear();\n    probabilities.push_back(0.3);\n    probabilities.push_back(0.2);\n    probabilities.push_back(0.1);\n    ASSERT_THROW(WeightedRandomIntegerGenerator gen5(probabilities), SumNotOne);\n#endif\n}\n\n// Test the randomization of the generator\nTEST_F(WeightedRandomIntegerGeneratorTest, WeightedRandomization) {\n    const int repeats = 100000;\n    // We repeat the simulation for N=repeats times\n    // for each probability p, its average is mu = N*p\n    // variance sigma^2 = N * p * (1-p)\n    // sigma = sqrt(N*2/9)\n    // we should make sure that mu - 4sigma < count < mu + 4sigma\n    // which means for 99.99366% of the time this should be true\n    {\n        double p = 0.5;\n        vector<double> probabilities;\n        probabilities.push_back(p);\n        probabilities.push_back(p);\n\n        // Uniformly generated integers\n        WeightedRandomIntegerGenerator gen(probabilities);\n        int c1 = 0;\n        int c2 = 0;\n        for (int i = 0; i < repeats; ++i){\n            int n = gen();\n            if (n == 0) {\n                ++c1;\n            } else if (n == 1) {\n                ++c2;\n            }\n        }\n        double mu = repeats * p;\n        double sigma = sqrt(repeats * p * (1 - p));\n        ASSERT_TRUE(fabs(c1 - mu) < 4*sigma);\n        ASSERT_TRUE(fabs(c2 - mu) < 4*sigma);\n    }\n\n    {\n        vector<double> probabilities;\n        int c1 = 0;\n        int c2 = 0;\n        double p1 = 0.2;\n        double p2 = 0.8;\n        probabilities.push_back(p1);\n        probabilities.push_back(p2);\n        WeightedRandomIntegerGenerator gen(probabilities);\n        for (int i = 0; i < repeats; ++i) {\n            int n = gen();\n            if (n == 0) {\n                ++c1;\n            } else if (n == 1) {\n                ++c2;\n            }\n        }\n        double mu1 = repeats * p1;\n        double mu2 = repeats * p2;\n        double sigma1 = sqrt(repeats * p1 * (1 - p1));\n        double sigma2 = sqrt(repeats * p2 * (1 - p2));\n        ASSERT_TRUE(fabs(c1 - mu1) < 4*sigma1);\n        ASSERT_TRUE(fabs(c2 - mu2) < 4*sigma2);\n    }\n\n    {\n        vector<double> probabilities;\n        int c1 = 0;\n        int c2 = 0;\n        double p1 = 0.8;\n        double p2 = 0.2;\n        probabilities.push_back(p1);\n        probabilities.push_back(p2);\n        WeightedRandomIntegerGenerator gen(probabilities);\n        for (int i = 0; i < repeats; ++i) {\n            int n = gen();\n            if (n == 0) {\n                ++c1;\n            } else if (n == 1) {\n                ++c2;\n            }\n        }\n        double mu1 = repeats * p1;\n        double mu2 = repeats * p2;\n        double sigma1 = sqrt(repeats * p1 * (1 - p1));\n        double sigma2 = sqrt(repeats * p2 * (1 - p2));\n        ASSERT_TRUE(fabs(c1 - mu1) < 4*sigma1);\n        ASSERT_TRUE(fabs(c2 - mu2) < 4*sigma2);\n    }\n\n    {\n        vector<double> probabilities;\n        int c1 = 0;\n        int c2 = 0;\n        int c3 = 0;\n        double p1 = 0.5;\n        double p2 = 0.25;\n        double p3 = 0.25;\n        probabilities.push_back(p1);\n        probabilities.push_back(p2);\n        probabilities.push_back(p3);\n        WeightedRandomIntegerGenerator gen(probabilities);\n        for (int i = 0; i < repeats; ++i){\n            int n = gen();\n            if (n == 0) {\n                ++c1;\n            } else if (n == 1) {\n                ++c2;\n            } else if (n == 2) {\n                ++c3;\n            }\n        }\n        double mu1 = repeats * p1;\n        double mu2 = repeats * p2;\n        double mu3 = repeats * p3;\n        double sigma1 = sqrt(repeats * p1 * (1 - p1));\n        double sigma2 = sqrt(repeats * p2 * (1 - p2));\n        double sigma3 = sqrt(repeats * p3 * (1 - p3));\n        ASSERT_TRUE(fabs(c1 - mu1) < 4*sigma1);\n        ASSERT_TRUE(fabs(c2 - mu2) < 4*sigma2);\n        ASSERT_TRUE(fabs(c3 - mu3) < 4*sigma3);\n    }\n}\n\n// Test the reset function of generator\nTEST_F(WeightedRandomIntegerGeneratorTest, ResetProbabilities) {\n    const int repeats = 100000;\n    vector<double> probabilities;\n    int c1 = 0;\n    int c2 = 0;\n    double p1 = 0.8;\n    double p2 = 0.2;\n    probabilities.push_back(p1);\n    probabilities.push_back(p2);\n    WeightedRandomIntegerGenerator gen(probabilities);\n    for (int i = 0; i < repeats; ++i) {\n        int n = gen();\n        if (n == 0) {\n            ++c1;\n        } else if (n == 1) {\n            ++c2;\n        }\n    }\n    double mu1 = repeats * p1;\n    double mu2 = repeats * p2;\n    double sigma1 = sqrt(repeats * p1 * (1 - p1));\n    double sigma2 = sqrt(repeats * p2 * (1 - p2));\n    ASSERT_TRUE(fabs(c1 - mu1) < 4*sigma1);\n    ASSERT_TRUE(fabs(c2 - mu2) < 4*sigma2);\n\n    // Reset the probabilities\n    probabilities.clear();\n    c1 = c2 = 0;\n    p1 = 0.2;\n    p2 = 0.8;\n    probabilities.push_back(p1);\n    probabilities.push_back(p2);\n    gen.reset(probabilities);\n    for (int i = 0; i < repeats; ++i) {\n        int n = gen();\n        if (n == 0) {\n            ++c1;\n        } else if (n == 1) {\n            ++c2;\n        }\n    }\n    mu1 = repeats * p1;\n    mu2 = repeats * p2;\n    sigma1 = sqrt(repeats * p1 * (1 - p1));\n    sigma2 = sqrt(repeats * p2 * (1 - p2));\n    ASSERT_TRUE(fabs(c1 - mu1) < 4*sigma1);\n    ASSERT_TRUE(fabs(c2 - mu2) < 4*sigma2);\n}\n", "meta": {"hexsha": "58da95586b8efc710e4a2a40c2443585d0e58256", "size": 9270, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/bin/perfdhcp/tests/random_number_generator_unittest.cc", "max_stars_repo_name": "oss-mirror/isc-kea", "max_stars_repo_head_hexsha": "e7bfb8886b0312a293e73846499095e7ec9686b9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 273.0, "max_stars_repo_stars_event_min_datetime": "2015-01-22T14:14:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T10:27:44.000Z", "max_issues_repo_path": "src/bin/perfdhcp/tests/random_number_generator_unittest.cc", "max_issues_repo_name": "oss-mirror/isc-kea", "max_issues_repo_head_hexsha": "e7bfb8886b0312a293e73846499095e7ec9686b9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 104.0, "max_issues_repo_issues_event_min_datetime": "2015-01-16T16:37:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-08T19:38:45.000Z", "max_forks_repo_path": "src/bin/perfdhcp/tests/random_number_generator_unittest.cc", "max_forks_repo_name": "oss-mirror/isc-kea", "max_forks_repo_head_hexsha": "e7bfb8886b0312a293e73846499095e7ec9686b9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 133.0, "max_forks_repo_forks_event_min_datetime": "2015-02-21T14:06:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-27T08:56:40.000Z", "avg_line_length": 31.2121212121, "max_line_length": 80, "alphanum_fraction": 0.5914778857, "num_tokens": 2483, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6791787121629466, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.4859007439857519}}
{"text": "#include \"potts.h\"\n#include \"ising.h\"\n#include \"util/observable.hpp\"\n#include \"util/squarelattice.hpp\"\n#include <iostream>\n#include <boost/random.hpp>\n#include <ctime>\n#include <mpi.h>\n#include <boost/program_options.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/timer/timer.hpp>\n#include <boost/foreach.hpp>\n#define foreach BOOST_FOREACH\n\nint main(int argc, char **argv)\n{\n  typedef util::SquareLattice Lattice;\n  typedef boost::variate_generator<boost::mt19937, boost::uniform_real<> > RNG01;\n\n  RNG01 rnd(boost::mt19937(static_cast<uint32_t>(std::time(0))), boost::uniform_real<>(0.0, 1.0));\n\n  using namespace boost;\n  using namespace boost::program_options;\n  options_description opt(\"options\");\n  opt.add_options()\n    (\"help\", \"show this message\")\n    (\"q,q\", value<int>()->default_value(2), \"number of state of a spin\")\n    (\"L,L\", value<int>()->default_value(10), \"length of lattice\")\n    (\"beta-min\", value<double>()->default_value(0.1), \"minimum beta\")\n    (\"beta-max\", value<double>()->default_value(1.0), \"maximum beta\")\n    (\"beta-num\", value<int>()->default_value(10), \"number of beta\")\n    (\"thermalization\", value<int>()->default_value(8), \"number of exchange to thermalize\")\n    (\"mcs\", value<int>()->default_value(64), \"number of exchange to measure\")\n    ;\n\n  variables_map vm;\n  store(parse_command_line(argc, argv, opt), vm);\n  notify(vm);\n\n  if( vm.count(\"help\") ){\n    std::cout << opt << std::endl;\n    return 0;\n  }\n\n  const int q = vm[\"q\"].as<int>();\n  const int L = vm[\"L\"].as<int>();\n  const double bmin = vm[\"beta-min\"].as<double>();\n  const double bmax = vm[\"beta-max\"].as<double>();\n  const int nbeta = vm[\"beta-num\"].as<int>();\n  const int therm = vm[\"thermalization\"].as<int>();\n  const int MCS = vm[\"mcs\"].as<int>();\n\n  const double dbeta = (bmax-bmin)/(nbeta-1);\n\n  potts::Potts<Lattice, RNG01> model(q, L);\n\n  for(int ibeta=0; ibeta<nbeta; ++ibeta){\n    const double beta = bmin + dbeta*ibeta;\n    util::Observable obs_time;\n    util::Observable obs_speed;\n    \n    for(int mcs=0; mcs < therm+MCS; ++mcs){\n      boost::timer::cpu_timer tm;\n      model.SW_update(beta, rnd);\n      const double sec = tm.elapsed().wall * 1.0e-9;\n      const double speed = 1.0/sec;\n      obs_time << sec;\n      obs_speed << speed;\n    }\n    std::cout << beta\n       << \" \" << obs_time.mean() << \" \" << obs_time.error()\n       << \" \" << obs_speed.mean() << \" \" << obs_speed.error()\n       << std::endl;\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "d34d7087d05ae8908fb743690f0271b28989b8e3", "size": 2448, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/potts_main.cpp", "max_stars_repo_name": "yomichi/SpinMonteCarlo.cpp", "max_stars_repo_head_hexsha": "2ce7f589a52b30da9f698c1a202b8348c2e578dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/potts_main.cpp", "max_issues_repo_name": "yomichi/SpinMonteCarlo.cpp", "max_issues_repo_head_hexsha": "2ce7f589a52b30da9f698c1a202b8348c2e578dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/potts_main.cpp", "max_forks_repo_name": "yomichi/SpinMonteCarlo.cpp", "max_forks_repo_head_hexsha": "2ce7f589a52b30da9f698c1a202b8348c2e578dc", "max_forks_repo_licenses": ["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.3846153846, "max_line_length": 98, "alphanum_fraction": 0.6331699346, "num_tokens": 689, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.48590074346088497}}
{"text": "/* +------------------------------------------------------------------------+\n   |                     Mobile Robot Programming Toolkit (MRPT)            |\n   |                          https://www.mrpt.org/                         |\n   |                                                                        |\n   | Copyright (c) 2005-2022, Individual contributors, see AUTHORS file     |\n   | See: https://www.mrpt.org/Authors - All rights reserved.               |\n   | Released under BSD License. See: https://www.mrpt.org/License          |\n   +------------------------------------------------------------------------+ */\n\n#include <CTraitsTest.h>\n#include <gtest/gtest.h>\n#include <mrpt/poses/CPose3D.h>\n#include <mrpt/poses/CPose3DInterpolator.h>\n#include <mrpt/system/datetime.h>\n\n#include <Eigen/Dense>\n\ntemplate class mrpt::CTraitsTest<mrpt::poses::CPose3DInterpolator>;\n\nTEST(CPose3DInterpolator, interp)\n{\n\tusing namespace mrpt::poses;\n\tusing namespace mrpt;  // for 0.0_deg\n\tusing mrpt::DEG2RAD;\n\tusing mrpt::math::CMatrixDouble44;\n\tusing mrpt::math::TPose3D;\n\n\tauto t0 = mrpt::Clock::now();\n\tmrpt::Clock::duration dt(std::chrono::milliseconds(100));\n\n\tCPose3DInterpolator pose_path;\n\n\tpose_path.insert(t0, TPose3D(1., 2., 3., 30.0_deg, .0_deg, .0_deg));\n\tpose_path.insert(\n\t\tt0 + 2 * dt,\n\t\tTPose3D(\n\t\t\t1. + 3., 2. + 4., 3. + 5., DEG2RAD(30.0 + 20.0), .0_deg, .0_deg));\n\n\tTPose3D interp;\n\tbool valid;\n\tpose_path.interpolate(t0 + dt, interp, valid);\n\n\tEXPECT_TRUE(valid);\n\tconst TPose3D interp_good(\n\t\t1. + 1.5, 2. + 2.0, 3. + 2.5, DEG2RAD(30.0 + 10.0), .0_deg, .0_deg);\n\tEXPECT_NEAR(\n\t\t.0,\n\t\t(CPose3D(interp_good).getHomogeneousMatrixVal<CMatrixDouble44>() -\n\t\t CPose3D(interp).getHomogeneousMatrixVal<CMatrixDouble44>())\n\t\t\t.array()\n\t\t\t.abs()\n\t\t\t.sum(),\n\t\t2e-4);\n}\n", "meta": {"hexsha": "c9f81154144f70ec6f3c74a45ff247392b609b20", "size": 1779, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/poses/src/CPose3DInterpolator_unittest.cpp", "max_stars_repo_name": "wstnturner/mrpt", "max_stars_repo_head_hexsha": "b0be3557a4cded6bafff03feb28f7fa1f75762a3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 38.0, "max_stars_repo_stars_event_min_datetime": "2015-01-04T05:24:26.000Z", "max_stars_repo_stars_event_max_datetime": "2015-07-17T00:30:02.000Z", "max_issues_repo_path": "libs/poses/src/CPose3DInterpolator_unittest.cpp", "max_issues_repo_name": "wstnturner/mrpt", "max_issues_repo_head_hexsha": "b0be3557a4cded6bafff03feb28f7fa1f75762a3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 40.0, "max_issues_repo_issues_event_min_datetime": "2015-01-03T22:43:00.000Z", "max_issues_repo_issues_event_max_datetime": "2015-07-17T18:52:59.000Z", "max_forks_repo_path": "libs/poses/src/CPose3DInterpolator_unittest.cpp", "max_forks_repo_name": "wstnturner/mrpt", "max_forks_repo_head_hexsha": "b0be3557a4cded6bafff03feb28f7fa1f75762a3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2015-01-06T12:32:19.000Z", "max_forks_repo_forks_event_max_datetime": "2017-05-30T15:50:13.000Z", "avg_line_length": 32.3454545455, "max_line_length": 80, "alphanum_fraction": 0.5514333895, "num_tokens": 523, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239836484143, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.48590073521901134}}
{"text": "static bool eigen_did_assert = false;\n#define eigen_assert(X) if(!eigen_did_assert && !(X)){ std::cout << \"### Assertion raised in \" << __FILE__ << \":\" << __LINE__ << \":\\n\" #X << \"\\n### The following would happen without assertions:\\n\"; eigen_did_assert = true;}\n\n#include <iostream>\n#include <Eigen/Eigen>\n\n#ifndef M_PI\n#define M_PI 3.1415926535897932384626433832795\n#endif\n\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n  int array[12];\nfor(int i = 0; i < 12; ++i) array[i] = i;\ncout << Map<MatrixXi, 0, OuterStride<> >(array, 3, 3, OuterStride<>(4)) << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "510da9167fea26509678beadc7838675a0a88a3e", "size": 622, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/snippets/compile_Map_outer_stride.cpp", "max_stars_repo_name": "mousepawmedia/libdeps", "max_stars_repo_head_hexsha": "b004d58d5b395ceaf9fdc993cfb00e91334a5d36", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2021-02-27T11:00:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T10:31:46.000Z", "max_issues_repo_path": "doc/snippets/compile_Map_outer_stride.cpp", "max_issues_repo_name": "mousepawmedia/libdeps", "max_issues_repo_head_hexsha": "b004d58d5b395ceaf9fdc993cfb00e91334a5d36", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-11-14T23:14:58.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-14T23:14:58.000Z", "max_forks_repo_path": "doc/snippets/compile_Map_outer_stride.cpp", "max_forks_repo_name": "mousepawmedia/libdeps", "max_forks_repo_head_hexsha": "b004d58d5b395ceaf9fdc993cfb00e91334a5d36", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-03-13T13:28:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-05T02:26:02.000Z", "avg_line_length": 25.9166666667, "max_line_length": 224, "alphanum_fraction": 0.6623794212, "num_tokens": 191, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6791786861878392, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.48590073364441017}}
{"text": "#include <iostream>\r\n#include <cassert>\r\n#include <time.h>\r\n#include \"timer.h\"\r\n#include \"Encoding.h\"\r\n#include \"PolyTree.h\"\r\n#include \"EncodingEnigmaBN.h\"\r\n\r\n#include <boost/program_options.hpp>\r\nusing namespace std;\r\nusing namespace boost::program_options;\r\n\r\nvoid microbenchmarks(variables_map& config) {\r\n\r\n#ifdef _DEBUG\r\n\tprintf(\"\\nRunning in DEBUG mode -- performance measurements should not be trusted!\\n\\n\");\r\n#endif\r\n\r\n\tstring option = config[\"micro\"].as<string>();\r\n\tint num_trials = config[\"trials\"].as<int>();\r\n\tprintf(\"About to run %d tests...\\n\", num_trials);\r\n\r\n\tEncoding* encoding = NewEncoding(config[\"encoding\"].as<string>());\r\n\tif (encoding == NULL) { return; }\r\n\tField* field = encoding->getSrcField();\r\n  if (option.compare(\"mont-test\") == 0) {\r\n    assert(config[\"encoding\"].as<string>().compare(\"enigma-bn\") == 0);\r\n    field = ((EncodingEnigmaBN*)encoding)->getMontField();\r\n\r\n    ((EncodingEnigmaBN*)encoding)->testToFromMont(field, num_trials);\r\n  }\r\n\r\n\tFieldEltArray* field1 = field->newEltArray(num_trials, true);\r\n\tFieldEltArray* field2 = field->newEltArray(num_trials, true);\r\n\tFieldEltArray* field32 = field->newEltArray(num_trials, true);\r\n\r\n\tEncodedEltArray* lencodings = encoding->new_elt_array(L, num_trials, true);\r\n\tEncodedEltArray* rencodings = encoding->new_elt_array(R, num_trials, true);\r\n\tEncodedEltArray* lencodings2 = encoding->new_elt_array(L, num_trials, true);\r\n\tEncodedEltArray* rencodings2 = encoding->new_elt_array(R, num_trials, true);\r\n\tEncodedProduct** prods = new EncodedProduct*[num_trials];\r\n\r\n\tFieldElt *fieldg1 = field->newElt(), *fieldg0 = field->newElt();\r\n\t// I'll assume 5^i are unique values, for i in [0,num_trials)\r\n\tfield->set(fieldg1, 5);\r\n\tfield->set(fieldg0, 1);\r\n\tfor (int i = 0; i < num_trials; i++) {\r\n\t\tfield->assignRandomElt(field1->elt(i));\r\n\t\tfield->assignRandomElt(field2->elt(i));\r\n\t\tfield->assignRandomElt(field32->elt(i));\r\n\r\n    field->truncate(field1->elt(i), 254);\r\n    field->truncate(field2->elt(i), 254);\r\n\t\tfield->truncate(field32->elt(i), 32);   \r\n\r\n\t\tprods[i] = encoding->new_prod();\r\n\t}\r\n\r\n\tTimer* total = timers.newTimer(\"Total\", NULL);\r\n\ttotal->start();\r\n\r\n\t/////////////// Field ops ///////////////////////////\r\n  if (option.compare(\"all\") == 0 || option.compare(\"field\") == 0 || option.compare(\"mont-test\") == 0) {\r\n\t\tTIMEREP(field->add(field1->elt(i), field2->elt(i), field1->elt(i)), num_trials, \"FieldAdd\", \"Total\");\r\n\t\tTIMEREP(field->sub(field1->elt(i), field2->elt(i), field1->elt(i)), num_trials, \"FieldSub\", \"Total\");\r\n\t\tTIMEREP(field->mul(field1->elt(i), field2->elt(i), field1->elt(i)), num_trials, \"FieldMul\", \"Total\");\r\n\t\tTIMEREP(field->mul(field1->elt(i), field2->elt(i), field1->elt(i)), num_trials, \"FieldDiv\", \"Total\");\t\r\n\r\n\t\tprintf(\"Finished field ops\\n\");  fflush(stdout);\r\n\t}\r\n\r\n\t/////////////// Encoding ops ///////////////////////////\r\n\tif (option.compare(\"all\") == 0 || option.compare(\"encoding\") == 0) {\r\n\t\tTIMEREP(encoding->encode(L, field1->elt(i), lencodings->elt(i)), num_trials, \"EncodeSlowL\", \"Total\");\r\n\t\tTIMEREP(encoding->encode(R, field1->elt(i), rencodings->elt(i)), num_trials, \"EncodeSlowR\", \"Total\");\r\n\r\n\t\tTIME(encoding->prepareForManyEncodings(num_trials, config[\"mem\"].as<int>(), false), \"PrepForEnc\", \"Total\");\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 \r\n\t\tTIMEREP(encoding->encode(L, field1->elt(i), lencodings->elt(i)), num_trials, \"EncodeFastL\", \"Total\");\r\n\t\tTIMEREP(encoding->encode(R, field1->elt(i), rencodings->elt(i)), num_trials, \"EncodeFastR\", \"Total\");\r\n\t\tTIMEREP(encoding->encode(L, field2->elt(i), lencodings2->elt(i)), num_trials, \"ignoreL\", \"Total\");\r\n\t\tTIMEREP(encoding->encode(R, field2->elt(i), rencodings2->elt(i)), num_trials, \"ignoreR\", \"Total\");\r\n\t\tencoding->doneWithManyEncodings();\r\n\r\n\t\tprintf(\"Finished encoding test values\\n\");  fflush(stdout);\r\n\r\n\t\tTIMEREP(encoding->add(L, lencodings->elt(i), lencodings2->elt(i), lencodings2->elt(i)), num_trials, \"EncAddL\", \"Total\");\r\n\t\tTIMEREP(encoding->add(R, rencodings->elt(i), rencodings2->elt(i), rencodings2->elt(i)), num_trials, \"EncAddR\", \"Total\");\r\n\r\n\t\tip_handle_t hL, hR;\r\n    int field_elt_max_bitsize = field->eltSize()*sizeof(digit_t) * 8;\r\n    TIME(hL = encoding->prepareForInnerProduct(lencodings, num_trials, 1, field_elt_max_bitsize, config[\"mem\"].as<int>(), false), \"PrepInnerL\", \"Total\");\r\n\t\tTIME(encoding->innerProduct(hL, field1, num_trials, lencodings2->elt(0)), \"InnerProdL\", \"Total\");\r\n\t\tencoding->doneWithInnerProduct(hL);\r\n\r\n    TIME(hR = encoding->prepareForInnerProduct(rencodings, num_trials, 1, field_elt_max_bitsize, config[\"mem\"].as<int>(), false), \"PrepInnerR\", \"Total\");\r\n\t\tTIME(encoding->innerProduct(hR, field1, num_trials, rencodings2->elt(0)), \"InnerProdR\", \"Total\");\r\n\t\tencoding->doneWithInnerProduct(hR);\r\n\r\n\t\tTIMEREP(encoding->mul(lencodings->elt(i), rencodings->elt(i), prods[i]), num_trials, \"Pairing\", \"Total\");\r\n\r\n\t\tprintf(\"Finished large encoding tests\\n\");  fflush(stdout);\r\n\r\n\t\t// Measure the time for smaller field elements\r\n\t\tTIME(encoding->prepareForManyEncodings(num_trials, config[\"mem\"].as<int>(), false), \"PrepForEnc\", \"Total\");\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 \r\n\t\tTIMEREP(encoding->encode(L, field32->elt(i), lencodings2->elt(i)), num_trials, \"EncodeFast32L\", \"Total\");\r\n\t\tTIMEREP(encoding->encode(R, field32->elt(i), rencodings2->elt(i)), num_trials, \"EncodeFast32R\", \"Total\");\t\r\n\t\tencoding->doneWithManyEncodings();\r\n\r\n\t\tTIME(hL = encoding->prepareForInnerProduct(lencodings, num_trials, 1, 32, config[\"mem\"].as<int>(), false), \"PrepInnerL\", \"Total\");\r\n\t\tTIME(encoding->innerProduct(hL, field32, num_trials, lencodings2->elt(0)), \"InnerProd32L\", \"Total\");\r\n\t\tencoding->doneWithInnerProduct(hL);\r\n\r\n\t\tTIME(hR = encoding->prepareForInnerProduct(rencodings, num_trials, 1, 32, config[\"mem\"].as<int>(), false), \"PrepInnerR\", \"Total\");\r\n\t\tTIME(encoding->innerProduct(hR, field32, num_trials, rencodings2->elt(0)), \"InnerProd32R\", \"Total\");\r\n\t\tencoding->doneWithInnerProduct(hR);\r\n\r\n\t\tprintf(\"Finished 32-bit encoding tests\\n\");  fflush(stdout);\r\n\t}\r\n\t\r\n\t/////////////// Poly Ops ///////////////////////////\r\n  if (option.compare(\"all\") == 0 || option.compare(\"poly-all\") == 0 || option.compare(\"poly-fast\") == 0 || option.compare(\"poly-slow\") == 0 || option.compare(\"mont-test\") == 0) {\r\n\t\tTimer* polyPreComp = timers.newTimer(\"PolyPreComp\", \"Total\");\r\n\t\tpolyPreComp->start();\r\n\t\tPolyTree* tree = new PolyTree(field, field1, num_trials);\r\n\t\tFieldEltArray* denominators = Poly::genLagrangeDenominators(field, *tree->polys[tree->height-1][0], tree, field1, num_trials);\r\n\t\tpolyPreComp->stop();\r\n\r\n\t\tTIME(Poly::interpolate(field, field2, num_trials, tree, denominators), \"PolyInterp\", \"Total\");\r\n\t\tTIME(Poly::interpolateGeometric(field, fieldg0, fieldg1, field2, num_trials), \"PolyInterpGeom\", \"Total\");\r\n\t\t\r\n\t\t// Compare slow vs. optimized polynomial multiplication\r\n\t\tPoly p1(field), p2(field), r(field);\r\n\t\tPoly::polyRand(field, p1, num_trials);\r\n\t\tPoly::polyRand(field, p2, num_trials);\r\n\t\tif (option.compare(\"poly-all\") == 0 || option.compare(\"poly-fast\") == 0) {\r\n\t\t\tTIME(Poly::mul(p1, p2, p1), \"PolyMul\", \"Total\");\r\n\t\t}\r\n\t\tif (option.compare(\"poly-all\") == 0 || option.compare(\"poly-slow\") == 0) {\t\t\t\t \r\n\t\t\tTIME(Poly::mulSlow(p1, p2, p1), \"PolyMulSlow\", \"Total\");\r\n\t\t}\r\n\t}\r\n\r\n\ttotal->stop();\r\n\r\n\tif (config.count(\"raw\")) {\r\n\t\ttimers.printRaw();\r\n\t} else {\r\n\t\ttimers.printStats();\r\n\t}\r\n\tprintf(\"\\n\");\r\n\r\n\tdelete field1, field2, field32;\r\n\tdelete lencodings,  rencodings;\r\n\tdelete lencodings2, rencodings2;\r\n\tdelete [] prods;\r\n\r\n\tdelete encoding;\r\n}", "meta": {"hexsha": "cf0a2a7e147cee852cbee00ac7d81fe1e10448be", "size": 7480, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "geppetto/code/compiler/src/cpp/tests-perf.cpp", "max_stars_repo_name": "anthonydelgado/pinocchio", "max_stars_repo_head_hexsha": "a1f1836679b8a135d85f2094bfaafc972101557a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "geppetto/code/compiler/src/cpp/tests-perf.cpp", "max_issues_repo_name": "anthonydelgado/pinocchio", "max_issues_repo_head_hexsha": "a1f1836679b8a135d85f2094bfaafc972101557a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "geppetto/code/compiler/src/cpp/tests-perf.cpp", "max_forks_repo_name": "anthonydelgado/pinocchio", "max_forks_repo_head_hexsha": "a1f1836679b8a135d85f2094bfaafc972101557a", "max_forks_repo_licenses": ["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.3417721519, "max_line_length": 179, "alphanum_fraction": 0.6610962567, "num_tokens": 2183, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708562, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.48560066237485644}}
{"text": "/* +------------------------------------------------------------------------+\n   |                     Mobile Robot Programming Toolkit (MRPT)            |\n   |                          https://www.mrpt.org/                         |\n   |                                                                        |\n   | Copyright (c) 2005-2022, Individual contributors, see AUTHORS file     |\n   | See: https://www.mrpt.org/Authors - All rights reserved.               |\n   | Released under BSD License. See: https://www.mrpt.org/License          |\n   +------------------------------------------------------------------------+ */\n\n#include <gtest/gtest.h>\n#include <mrpt/math/CMatrixFixed.h>\n\n#include <Eigen/Dense>\n\nTEST(CMatrixFixed, CtorUninit)\n{\n\tmrpt::math::CMatrixFixed<double, 2, 2> M(mrpt::math::UNINITIALIZED_MATRIX);\n\t// do nothing, just test that the ctor above compiles\n\t(void)M(0, 0);\n}\n\nTEST(CMatrixFixed, CtorAllZeros)\n{\n\tmrpt::math::CMatrixFixed<double, 2, 2> M;\n\tfor (int i = 0; i < 2; i++)\n\t\tfor (int j = 0; j < 2; j++)\n\t\t\tEXPECT_EQ(M(i, j), .0);\n}\n\nTEST(CMatrixFixed, Identity)\n{\n\tmrpt::math::CMatrixFixed<double, 3, 3> M;\n\tM.setIdentity();\n\tfor (int i = 0; i < 3; i++)\n\t{\n\t\tEXPECT_EQ(M(i, i), 1.0);\n\t\t// Also test access via data():\n\t\tEXPECT_EQ(M(i, i), M.data()[i + i * 3]);\n\t}\n\n\t// Check that access via data() is what we expect:\n\tfor (int r = 0; r < 3; r++)\n\t\tfor (int c = 0; c < 3; c++)\n\t\t\tEXPECT_EQ(&M(r, c), &M.data()[c + r * 3]);\n}\n\nTEST(CMatrixFixed, asString)\n{\n\tmrpt::math::CMatrixFixed<double, 2, 2> M;\n\tM.setIdentity();\n\tEXPECT_EQ(std::string(\"1 0\\n0 1\"), M.asString());\n}\n\nTEST(CMatrixFixed, GetSetEigen)\n{\n\t{\n\t\tmrpt::math::CMatrixFixed<double, 3, 3> M;\n\t\tauto em = M.asEigen();\n\t\tem.setIdentity();\n\t\tfor (int i = 0; i < 3; i++)\n\t\t\tEXPECT_EQ(M(i, i), 1.0);\n\t}\n\t{\n\t\tmrpt::math::CMatrixFixed<double, 3, 3> M;\n\t\tauto em = M.asEigen();\n\t\tfor (int i = 0; i < 3; i++)\n\t\t\tfor (int j = 0; j < 3; j++)\n\t\t\t{\n\t\t\t\tconst auto n = ((i + 1) * 3) + (j * 1001);\n\t\t\t\tem(i, j) = n;\n\t\t\t\tEXPECT_NEAR(M(i, j), em(i, j), 1e-9)\n\t\t\t\t\t<< \"(i,j)=(\" << i << \",\" << j << \")\\n\";\n\t\t\t}\n\t}\n}\n", "meta": {"hexsha": "a10be482c88ab2f4bd95d5ac04c463681ca961e7", "size": 2089, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/src/CMatrixFixed_unittest.cpp", "max_stars_repo_name": "wstnturner/mrpt", "max_stars_repo_head_hexsha": "b0be3557a4cded6bafff03feb28f7fa1f75762a3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 38.0, "max_stars_repo_stars_event_min_datetime": "2015-01-04T05:24:26.000Z", "max_stars_repo_stars_event_max_datetime": "2015-07-17T00:30:02.000Z", "max_issues_repo_path": "libs/math/src/CMatrixFixed_unittest.cpp", "max_issues_repo_name": "wstnturner/mrpt", "max_issues_repo_head_hexsha": "b0be3557a4cded6bafff03feb28f7fa1f75762a3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 40.0, "max_issues_repo_issues_event_min_datetime": "2015-01-03T22:43:00.000Z", "max_issues_repo_issues_event_max_datetime": "2015-07-17T18:52:59.000Z", "max_forks_repo_path": "libs/math/src/CMatrixFixed_unittest.cpp", "max_forks_repo_name": "wstnturner/mrpt", "max_forks_repo_head_hexsha": "b0be3557a4cded6bafff03feb28f7fa1f75762a3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2015-01-06T12:32:19.000Z", "max_forks_repo_forks_event_max_datetime": "2017-05-30T15:50:13.000Z", "avg_line_length": 27.4868421053, "max_line_length": 80, "alphanum_fraction": 0.4815701292, "num_tokens": 686, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757645879592641, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.48560064767799177}}
{"text": "/*\n * This file is part of the Interpolated Polyline (https://github.com/fzi-forschungszentrum-informatik/P3IV),\n * copyright by FZI Forschungszentrum Informatik, licensed under the BSD-3 license (see LICENSE file in main directory)\n */\n\n#pragma once\n#include <iostream>\n#include <Eigen/Core>\n#include <glog/logging.h>\n\nnamespace util_probability {\n\ntemplate <typename T, int Dim>\nstruct NormalDistribution {\n\n    using Mean = Eigen::Matrix<T, Dim, 1>;\n    using Covariance = Eigen::Matrix<T, Dim, Dim>;\n\n\n    NormalDistribution() : _mean{Mean::Zero()}, _covariance{Covariance::Zero()} {\n    }\n\n    NormalDistribution(const Eigen::Ref<const Mean>& mean_) : _mean{mean_}, _covariance{Covariance::Zero()} {\n    }\n\n    NormalDistribution(const Eigen::Ref<const Mean>& mean_, const Eigen::Ref<const Covariance>& covariance_)\n            : _mean{mean_}, _covariance{covariance_} {\n        LOG_ASSERT(_covariance.rows() == _covariance.cols());\n        LOG_ASSERT(_mean.size() == _covariance.rows());\n    }\n\n    NormalDistribution(const Eigen::Ref<const Mean>& mean_, Eigen::Matrix<T, Dim, 1>& variance_)\n            : _mean{mean_}, _covariance{Covariance::Zero()} {\n\n        for (size_t i = 0; i < variance_.size(); i++) {\n            _covariance(i, i) = variance_(i);\n        }\n    }\n\n    size_t dimension() const {\n        return static_cast<size_t>(_mean.size());\n    }\n\n    Mean mean() const {\n        return _mean;\n    }\n\n    T mean(size_t r, size_t c) const {\n        return _mean(r, c);\n    }\n\n    Covariance covariance() const {\n        return _covariance;\n    }\n\n    T covariance(size_t r, size_t c) const {\n        return _covariance(r, c);\n    }\n\n    virtual Eigen::Matrix<T, Dim, 1> variance() const {\n        Eigen::Matrix<T, Dim, 1> variance;\n        for (size_t i = 0; i < _covariance.rows(); i++) {\n            variance(i) = _covariance(i, i);\n        }\n        return variance;\n    }\n\nprotected:\n    Mean _mean;\n    Covariance _covariance;\n};\n\n} // namespace util_probability\n", "meta": {"hexsha": "6cf8240a2693dfbb158d9df1ca132364f9e0a972", "size": 1987, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "p3iv_utils_probability/include/p3iv_utils_probability/internal/normal.hpp", "max_stars_repo_name": "fzi-forschungszentrum-informatik/P3IV", "max_stars_repo_head_hexsha": "51784e6dc03dcaa0ad58a5078475fa4daec774bd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-07-27T06:56:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T11:21:30.000Z", "max_issues_repo_path": "p3iv_utils_probability/include/p3iv_utils_probability/internal/normal.hpp", "max_issues_repo_name": "fzi-forschungszentrum-informatik/P3IV", "max_issues_repo_head_hexsha": "51784e6dc03dcaa0ad58a5078475fa4daec774bd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "p3iv_utils_probability/include/p3iv_utils_probability/internal/normal.hpp", "max_forks_repo_name": "fzi-forschungszentrum-informatik/P3IV", "max_forks_repo_head_hexsha": "51784e6dc03dcaa0ad58a5078475fa4daec774bd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-10-10T01:56:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-10T01:56:44.000Z", "avg_line_length": 26.8513513514, "max_line_length": 119, "alphanum_fraction": 0.627075994, "num_tokens": 517, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.6757645879592642, "lm_q1q2_score": 0.48560064360548233}}
{"text": "// Servo command generator\n// Author: Max Schwarz <max.schwarz@uni-bonn.de>\n\n#include <ros/node_handle.h>\n\n#include <servomodel/servocommandgenerator.h>\n\n#include <math.h>\n#include <Eigen/Core>\n\nusing namespace Eigen;\n\nconst int ServoCommandGenerator::DefaultTicksPerRev = 4096;\n\nServoCommandGenerator::ServoCommandGenerator()\n : m_coeff(4)\n , m_ticksPerRev(DefaultTicksPerRev)\n , m_pValue(2)\n , m_latency(0)\n , m_voltage(15.0)\n{\n\tm_coeff << 0.17, 0.553952330165401, -0.0023, 0.0250731405677264;\n}\n\ninline double sgn(double x)\n{\n\tif(x > 0.0) return 1.0;\n\telse if(x < 0.0) return -1.0;\n\telse return 0.0;\n}\n\nVectorXd ServoCommandGenerator::commandPartsFor(double pos, double vel, double acc, double outsideTorque) const\n{\n\tVectorXd ret(4);\n\t// Motor model\n\tdouble stribeckFactor = exp(-fabs(vel / 0.1));\n\tret <<\n\t\toutsideTorque,\n\t\tvel,                           // viscous friction / back-EMF\n\t\tsgn(vel) * (1-stribeckFactor), // stribeck I\n\t\tsgn(vel) * stribeckFactor      // stribeck II\n\t;\n\n\treturn ret;\n}\n\ndouble ServoCommandGenerator::currentFactor() const\n{\n\treturn (15.0 / m_voltage) / m_pValue * 2.0;\n}\n\ndouble ServoCommandGenerator::servoCommandFor(double pos, double vel, double acc, double outside) const\n{\n\treturn pos + currentFactor() * (\n\t\tm_coeff.dot(commandPartsFor(pos, vel, acc, outside))\n\t);\n}\n\ndouble ServoCommandGenerator::servoTorqueFromCommand(double pos_cmd, double pos_cur, double vel) const\n{\n\tEigen::VectorXd frictionParts = commandPartsFor(0.0, vel, 0.0, 0.0);\n\n\tdouble d = (pos_cmd - pos_cur) / currentFactor();\n\n\tdouble torquePart = d - m_coeff.dot(frictionParts);\n\n\treturn torquePart / m_coeff(0);\n}\n\nvoid ServoCommandGenerator::setCoefficients(const VectorXd& coeff)\n{\n\tm_coeff = coeff;\n\tupdate();\n}\n\nvoid ServoCommandGenerator::setKM(double val)\n{\n\tm_coeff(0) = val;\n\tupdate();\n}\n\nvoid ServoCommandGenerator::setViscousFriction(double val)\n{\n\tm_coeff(1) = val;\n\tupdate();\n}\n\nvoid ServoCommandGenerator::setStribeckOne(double val)\n{\n\tm_coeff(2) = val;\n\tupdate();\n}\n\nvoid ServoCommandGenerator::setStribeckTwo(double val)\n{\n\tm_coeff(3) = val;\n\tupdate();\n}\n\nvoid ServoCommandGenerator::setTicksPerRev(double val)\n{\n\tm_ticksPerRev = val;\n\tupdate();\n}\n\nvoid ServoCommandGenerator::setMinTickValue(int val)\n{\n\tm_minTickValue = val;\n\tupdate();\n}\n\nvoid ServoCommandGenerator::setMaxTickValue(int val)\n{\n\tm_maxTickValue = val;\n\tupdate();\n}\n\nvoid ServoCommandGenerator::setPValue(int p)\n{\n\tm_pValue = p;\n\tupdate();\n}\n\nvoid ServoCommandGenerator::setLatency(double val)\n{\n\tm_latency = val;\n\tupdate();\n}\n\nvoid ServoCommandGenerator::setVoltage(double volt)\n{\n\tm_voltage = volt;\n\tupdate();\n}\n\nvoid ServoCommandGenerator::update()\n{\n}\n\nstd::string ServoCommandGenerator::serializeCoefficients()\n{\n\tstd::stringstream ss;\n\n\tfor(int i = 0; i < m_coeff.rows(); ++i)\n\t\tss << m_coeff(i) << \" \";\n\n\treturn ss.str();\n}\n\nbool ServoCommandGenerator::deserializeCoefficients(const std::string& coeff)\n{\n\tstd::stringstream ss;\n\tss.str(coeff);\n\n\tEigen::VectorXd newCoeff(m_coeff.rows());\n\n\tfor(int i = 0; i < m_coeff.rows(); ++i)\n\t{\n\t\tss >> newCoeff(i);\n\n\t\tif(ss.fail())\n\t\t\treturn false;\n\t}\n\n\tsetCoefficients(newCoeff);\n\treturn true;\n}\n\n", "meta": {"hexsha": "68142a354303118b2f4b30de61b50491284570c1", "size": 3138, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/nimbro_robotcontrol/hardware/servomodel/src/servocommandgenerator.cpp", "max_stars_repo_name": "hfarazi/humanoid_op_ros_kinetic", "max_stars_repo_head_hexsha": "84712bd541d0130b840ad1935d5bfe301814dbe6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 45.0, "max_stars_repo_stars_event_min_datetime": "2015-11-04T01:29:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T05:37:42.000Z", "max_issues_repo_path": "src/nimbro_robotcontrol/hardware/servomodel/src/servocommandgenerator.cpp", "max_issues_repo_name": "hfarazi/humanoid_op_ros_kinetic", "max_issues_repo_head_hexsha": "84712bd541d0130b840ad1935d5bfe301814dbe6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-08-10T04:00:32.000Z", "max_issues_repo_issues_event_max_datetime": "2016-08-10T12:59:36.000Z", "max_forks_repo_path": "src/nimbro_robotcontrol/hardware/servomodel/src/servocommandgenerator.cpp", "max_forks_repo_name": "hfarazi/humanoid_op_ros_kinetic", "max_forks_repo_head_hexsha": "84712bd541d0130b840ad1935d5bfe301814dbe6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 20.0, "max_forks_repo_forks_event_min_datetime": "2016-03-05T14:28:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-30T00:50:47.000Z", "avg_line_length": 18.5680473373, "max_line_length": 111, "alphanum_fraction": 0.7096876992, "num_tokens": 891, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757870046160258, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.48559802765574767}}
{"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_ALGORITHMS_POISSON_SOLVER_HPP\n#define PIC_ALGORITHMS_POISSON_SOLVER_HPP\n\n#include \"../base.hpp\"\n\n#include \"../image.hpp\"\n\n#ifndef PIC_DISABLE_EIGEN\n\n#ifndef PIC_EIGEN_NOT_BUNDLED\n    #include \"../externals/Eigen/Sparse\"\n    #include \"../externals/Eigen/src/SparseCore/SparseMatrix.h\"\n#else\n    #include <Eigen/Sparse>\n    #include <Eigen/src/SparseCore/SparseMatrix.h>\n#endif\n\n#endif\n\nnamespace pic {\n\n#ifndef PIC_DISABLE_EIGEN\n\n/**\n * @brief computePoissonSolver\n * @param f\n * @param ret\n * @return\n */\nPIC_INLINE Image *computePoissonSolver(Image *f, Image *ret = NULL)\n{\n    if(f == NULL) {\n        return NULL;\n    }\n\n    //allocate the output\n    if(ret == NULL) {\n        ret = f->allocateSimilarOne();\n    }\n\n    int width = f->width;\n    int height = f->height;\n    int tot = height * width;\n\n    #ifdef PIC_DEBUG\n        printf(\"Init matrix...\");\n    #endif\n\n    std::vector< Eigen::Triplet< double > > tL;\n\n    for(int i = 0; i < height; i++) {\n        int tmpI = i * width;\n\n        for(int j = 0; j < width; j++) {\n            int indI = tmpI + j;\n\n            tL.push_back(Eigen::Triplet< double > (indI, indI, 4.0f));\n\n            if(((indI + 1) < tot) &&\n               ((indI % width) != (width - 1))) {\n\n                tL.push_back(Eigen::Triplet< double > (indI, indI + 1, -1.0f));\n                tL.push_back(Eigen::Triplet< double > (indI + 1, indI, -1.0f));\n            }\n        }\n    }\n\n    for(int i = 0; i < (tot - width); i++) {\n        tL.push_back(Eigen::Triplet< double > (i + width, i         , -1.0f));\n        tL.push_back(Eigen::Triplet< double > (i        , i +  width, -1.0f));\n    }\n\n    #ifdef PIC_DEBUG\n        printf(\"Ok\\n\");\n    #endif\n\n    //solve the linear system for each color channel\n    Eigen::SparseMatrix<double> A = Eigen::SparseMatrix<double>(tot, tot);\n    A.setFromTriplets(tL.begin(), tL.end());\n    Eigen::SimplicialCholesky<Eigen::SparseMatrix<double> > solver(A);\n\n    for(int k = 0; k < f->channels; k++) {\n\n        Eigen::VectorXd b, x;\n        b = Eigen::VectorXd::Zero(tot);\n\n        //copy values from f to b\n        for(int i = 0; i < height; i++) {\n            int tmpI = i * width;\n            for(int j = 0; j < width; j++) {\n                int indI = (tmpI + j);\n                b[indI] = - f->data[indI * f->channels + k];\n            }\n        }\n\n        x = solver.solve(b);\n\n        if(solver.info() != Eigen::Success) {\n            #ifdef PIC_DEBUG\n                printf(\"SOLVER FAILED!\\n\");\n            #endif\n\n            return ret;\n        }\n\n        #ifdef PIC_DEBUG\n            printf(\"SOLVER SUCCESS!\\n\");\n        #endif\n\n        for(int i = 0; i < height; i++) {\n            int tmpI = i * width;\n\n            for(int j = 0; j < width; j++) {\n                (*ret)(j, i)[k] = float(x(tmpI + j));\n            }\n        }\n    }\n\n    return ret;\n}\n\n#endif\n\n/**\n * @brief computePoissonSolverIterative\n * @param img\n * @param laplacian\n * @param coords\n * @param maxSteps\n * @return\n */\nPIC_INLINE Image *computePoissonSolverIterative(Image *img, Image *laplacian,\n                              std::vector<int> coords,\n                              int maxSteps = 100)\n{\n    #ifdef PIC_DEBUG\n        printf(\"Iterative Poisson solver... \");\n    #endif\n\n    if(maxSteps < 1) {\n        maxSteps = 100;\n    }\n\n    Image *tmpImg = img->clone();\n    Image *tmpSwap = NULL;\n\n    int c, x, y;\n\n    for(int i = 0; i < maxSteps; i++) {\n        for(unsigned int j = 0; j < coords.size(); j++) {\n            int coord = coords[j];\n            img->reverseAddress(coord, x, y);\n\n            float workValue = -laplacian->data[coord];\n\n            c = img->getAddress(x + 1, y);\n            workValue += img->data[c];\n\n            c = img->getAddress(x - 1, y);\n            workValue += img->data[c];\n\n            c = img->getAddress(x, y + 1);\n            workValue += img->data[c];\n\n            c = img->getAddress(x, y - 1);\n            workValue += img->data[c];\n\n            tmpImg->data[coord] = workValue / 4.0f;\n        }\n\n        tmpSwap = img;\n        img     = tmpImg;\n        tmpImg  = tmpSwap;\n    }\n\n    #ifdef PIC_DEBUG\n        printf(\"done.\\n\");\n    #endif\n\n    return img;\n}\n\n} // end namespace pic\n\n\n#endif /* PIC_ALGORITHMS_POISSON_SOLVER_HPP */\n\n", "meta": {"hexsha": "45009e2b06b0f7fc32b6c80b17829408653c7b40", "size": 4639, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/poisson_solver.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/algorithms/poisson_solver.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/algorithms/poisson_solver.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": 22.6292682927, "max_line_length": 79, "alphanum_fraction": 0.5287777538, "num_tokens": 1326, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319862, "lm_q2_score": 0.5544704649604274, "lm_q1q2_score": 0.48559802406053937}}
{"text": "//\n// Created by tim on 22.02.21.\n//\n#include <Eigen/StdVector>\n#include <Eigen/Geometry>\n#include <iostream>\n#include \"graphSlamSaveStructure.h\"\n\n\nvoid createExampleVertex(graphSlamSaveStructure &graphSaved) {\n    Eigen::Vector3f positionVertex0(0, 0, 0);\n    Eigen::AngleAxisf rotation_vector0(0.0f, Eigen::Vector3f(0, 0, 1));\n    Eigen::Quaternionf rotationVertex0(rotation_vector0);\n    float covariance0 = 0.0;\n    Eigen::Vector3f covarianceVector(1, 1, 0);\n    graphSaved.addVertex(0, positionVertex0, rotationVertex0, covarianceVector * covariance0, covariance0);\n\n    Eigen::Vector3f positionVertex1(1, 1, 0);\n    Eigen::AngleAxisf rotation_vector1(-0.0f / 180.0f * 3.14159f, Eigen::Vector3f(0, 0, 1));\n    Eigen::Quaternionf rotationVertex1(rotation_vector1.toRotationMatrix());\n    graphSaved.addVertex(1, positionVertex1, rotationVertex1, covarianceVector * covariance0, covariance0);\n\n    Eigen::Vector3f positionVertex2(1, 1, 0);\n    Eigen::AngleAxisf rotation_vector2(-0.0f / 180.0f * 3.14159f, Eigen::Vector3f(0, 0, 1));\n    Eigen::Quaternionf rotationVertex2(rotation_vector2.toRotationMatrix());\n    graphSaved.addVertex(2, positionVertex2, rotationVertex2, covarianceVector * covariance0, covariance0);\n\n    Eigen::Vector3f positionVertex3(1, 1, 0);\n    Eigen::AngleAxisf rotation_vector3(0.0f / 180.0f * 3.14159f, Eigen::Vector3f(0, 0, 1));\n    Eigen::Quaternionf rotationVertex3(rotation_vector3.toRotationMatrix());\n    graphSaved.addVertex(3, positionVertex3, rotationVertex3, covarianceVector * covariance0, covariance0);\n\n    Eigen::Vector3f positionVertex4(2, 2, 0);\n    graphSaved.addVertex(4, positionVertex4, rotationVertex0, covarianceVector * covariance0, covariance0);\n\n}\n\nvoid createExampleEdge(graphSlamSaveStructure &graphSaved) {\n\n    Eigen::Vector3f eyeVector(1, 1, 0);\n    Eigen::Vector3f positionDifference0(8, 10, 0);\n    Eigen::AngleAxisf rotation_vector0(-0.0f / 180.0f * 3.14159f, Eigen::Vector3f(0, 0, 1));\n    Eigen::Quaternionf rotationDifference0(rotation_vector0.toRotationMatrix());\n    float covariancePosition0 = 0.1;\n    float covarianceQuaternion0 = 0.1;\n    graphSaved.addEdge(0, 1, positionDifference0, rotationDifference0, eyeVector * covariancePosition0,\n                       covarianceQuaternion0);\n\n    Eigen::Vector3f positionDifference1(4, 9, 0);\n    Eigen::AngleAxisf rotation_vector1(30.0f / 180.0f * 3.14159f, Eigen::Vector3f(0, 0, 1));\n    Eigen::Quaternionf rotationDifference1(rotation_vector1.toRotationMatrix());\n    float covariancePosition1 = 3;\n    float covarianceQuaternion1 = 3;\n    graphSaved.addEdge(1, 2, positionDifference1, rotationDifference1, eyeVector * covariancePosition1,\n                       covarianceQuaternion1);\n\n    Eigen::Vector3f positionDifference2(0, 12.4, 0);\n    Eigen::AngleAxisf rotation_vector2(0.0f / 180.0f * 3.14159f, Eigen::Vector3f(0, 0, 1));\n    Eigen::Quaternionf rotationDifference2(rotation_vector2.toRotationMatrix());\n    float covariancePosition2 = 0.1;\n    float covarianceQuaternion2 = 0.1;\n    graphSaved.addEdge(2, 3, positionDifference2, rotationDifference2, eyeVector * covariancePosition2,\n                       covarianceQuaternion2);\n\n    Eigen::Vector3f positionDifference3(2, -9, 0);\n    Eigen::AngleAxisf rotation_vector3(0.0f / 180.0f * 3.14159f, Eigen::Vector3f(0, 0, 1));\n    Eigen::Quaternionf rotationDifference3(rotation_vector3.toRotationMatrix());\n    float covariancePosition3 = 0.1;\n    float covarianceQuaternion3 = 0.1;\n    graphSaved.addEdge(3, 4, positionDifference3, rotationDifference3, eyeVector * covariancePosition3,\n                       covarianceQuaternion3);\n\n\n    Eigen::Vector3f positionDifference4(2, 12.4 - 9, 0);\n    Eigen::AngleAxisf rotation_vector4(0.0f / 180.0f * 3.14159f, Eigen::Vector3f(0, 0, 1));\n    Eigen::Quaternionf rotationDifference4(rotation_vector4.toRotationMatrix());\n    float covariancePosition4 = 0.1;\n    float covarianceQuaternion4 = 0.1;\n    graphSaved.addEdge(2, 4, positionDifference4, rotationDifference4, eyeVector * covariancePosition4,\n                       covarianceQuaternion4);\n\n}\n\n\nint\nmain(int argc, char **argv) {\n    const int dimension = 3;\n    graphSlamSaveStructure graphSaved(dimension);\n\n\n    createExampleVertex(graphSaved);\n\n    createExampleEdge(graphSaved);\n\n    //graphSaved.optimizeGraphWithSlam();\n    graphSaved.printCurrentStateGeneralInformation();\n    //graphSaved.printCurrentState();\n    //graphSaved.getEdgeBetweenNodes(2,4);\n    //std::cout << \"now hierachical graph design\" << std::endl;\n    graphSaved.createHierachicalGraph(1);//this is 1 m\n    graphSaved.optimizeGraphWithSlamTopDown(false);\n    graphSlamSaveStructure differentGraph = graphSaved;\n\n    differentGraph.optimizeGraphWithSlam(false);\n\n    graphSaved.printCurrentStateGeneralInformation();\n    //hierachicalGraph.printCurrentStateGeneralInformation();\n    graphSaved.printCurrentStateGeneralInformation();\n\n    return (0);\n}\n\n", "meta": {"hexsha": "13ea4cf7656d83a0fb869c7110b7a3e14fc31f39", "size": 4910, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/graphOptimizationTest.cpp", "max_stars_repo_name": "Zarbokk/simulation_bluerov", "max_stars_repo_head_hexsha": "578af3feaf2d7d875d1fe297ecf6f8f61d112d9c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/graphOptimizationTest.cpp", "max_issues_repo_name": "Zarbokk/simulation_bluerov", "max_issues_repo_head_hexsha": "578af3feaf2d7d875d1fe297ecf6f8f61d112d9c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/graphOptimizationTest.cpp", "max_forks_repo_name": "Zarbokk/simulation_bluerov", "max_forks_repo_head_hexsha": "578af3feaf2d7d875d1fe297ecf6f8f61d112d9c", "max_forks_repo_licenses": ["Apache-2.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.4513274336, "max_line_length": 107, "alphanum_fraction": 0.7350305499, "num_tokens": 1370, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869786798664, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.48559801327491336}}
{"text": "#include <boost/graph/dijkstra_shortest_paths.hpp>\n", "meta": {"hexsha": "b41108048c6290ebe0de33a86a9bdb55051e9a39", "size": 51, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_graph_dijkstra_shortest_paths.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_graph_dijkstra_shortest_paths.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_graph_dijkstra_shortest_paths.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 25.5, "max_line_length": 50, "alphanum_fraction": 0.8431372549, "num_tokens": 11, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028205, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.48551667225497575}}
{"text": "#include \"kiteNMPF.h\"\n#include \"integrator.h\"\n\n#define  BOOST_TEST_TOOLS_UNDER_DEBUGGER\n#define BOOST_TEST_MODULE kite_identification_test\n#include <boost/test/included/unit_test.hpp>\n#include <fstream>\n#include \"pseudospectral/chebyshev.hpp\"\n\nusing namespace casadi;\n\nBOOST_AUTO_TEST_SUITE( kite_identification_test )\n\nBOOST_AUTO_TEST_CASE( first_id_test )\n{\n    /** Load identification data */\n    std::ifstream id_data_file(\"id_data_state.txt\", std::ios::in);\n    std::ifstream id_control_file(\"id_data_control.txt\", std::ios::in);\n    const int DATA_POINTS = 201;\n    const int state_size   = 13;\n    const int control_size = 3;\n\n    DM id_data    = DM::zeros(state_size, DATA_POINTS);\n    DM id_control = DM::zeros(control_size, DATA_POINTS);\n\n    /** load state trajectory */\n    if(!id_data_file.fail())\n    {\n    for(uint i = 0; i < DATA_POINTS; ++i) {\n        for(uint j = 0; j < state_size; ++j){\n            double entry;\n            id_data_file >> entry;\n            id_data(j,i) = entry;\n        }\n    }\n    }\n    else\n    {\n        std::cout << \"Could not open : id state data file \\n\";\n        id_data_file.clear();\n    }\n\n    /** load control data */\n    if(!id_control_file.fail())\n    {\n    for(uint i = 0; i < DATA_POINTS; ++i){\n        for(uint j = 0; j < control_size; ++j){\n            double entry;\n            id_control_file >> entry;\n            /** put in reverse order to comply with Chebyshev method */\n            id_control(j,DATA_POINTS - 1 - i) = entry;\n        }\n    }\n    }\n    else\n    {\n        std::cout << \"Could not open : id control data file \\n\";\n        id_control_file.clear();\n    }\n\n    /** define kite dynamics */\n    std::string kite_params_file = \"umx_radian.yaml\";\n    KiteProperties kite_props = kite_utils::LoadProperties(kite_params_file);\n\n    AlgorithmProperties algo_props;\n    algo_props.Integrator = CVODES;\n    algo_props.sampling_time = 0.02;\n    KiteDynamics kite(kite_props, algo_props, true);\n    KiteDynamics kite_int(kite_props, algo_props); //integration model\n    Function ode = kite_int.getNumericDynamics();\n\n    /** get dynamics function and state Jacobian */\n    Function DynamicsFunc = kite.getNumericDynamics();\n    SX X = kite.getSymbolicState();\n    SX U = kite.getSymbolicControl();\n    SX P = kite.getSymbolicParameters();\n\n    /** state bounds */\n    DM LBX = DM::vertcat({2.0, -DM::inf(1), -DM::inf(1), -4 * M_PI, -4 * M_PI, -4 * M_PI, -DM::inf(1), -DM::inf(1), -DM::inf(1),\n                          -1.05, -1.05, -1.05, -1.05});\n    DM UBX = DM::vertcat({DM::inf(1), DM::inf(1), DM::inf(1), 4 * M_PI, 4 * M_PI, 4 * M_PI, DM::inf(1), DM::inf(1), DM::inf(1),\n                          1.05, 1.05, 1.05, 1.05});\n    /** control bounds */\n    DM LBU = DM::vec(id_control);\n    DM UBU = DM::vec(id_control);\n\n    /** parameter bounds */\n    YAML::Node config = YAML::LoadFile(\"umx_radian.yaml\");\n    double CL0 = config[\"aerodynamic\"][\"CL0\"].as<double>();\n    double CLa_tot = config[\"aerodynamic\"][\"CLa_total\"].as<double>();\n\n    double CD0_tot = config[\"aerodynamic\"][\"CD0_total\"].as<double>();\n    double CYb = config[\"aerodynamic\"][\"CYb\"].as<double>();\n    double Cm0 = config[\"aerodynamic\"][\"Cm0\"].as<double>();\n    double Cma = config[\"aerodynamic\"][\"Cma\"].as<double>();\n    double Cnb = config[\"aerodynamic\"][\"Cnb\"].as<double>();\n    double Clb = config[\"aerodynamic\"][\"Clb\"].as<double>();\n\n    double CLq = config[\"aerodynamic\"][\"CLq\"].as<double>();\n    double Cmq = config[\"aerodynamic\"][\"Cmq\"].as<double>();\n    double CYr = config[\"aerodynamic\"][\"CYr\"].as<double>();\n    double Cnr = config[\"aerodynamic\"][\"Cnr\"].as<double>();\n    double Clr = config[\"aerodynamic\"][\"Clr\"].as<double>();\n    double CYp = config[\"aerodynamic\"][\"CYp\"].as<double>();\n    double Clp = config[\"aerodynamic\"][\"Clp\"].as<double>();\n    double Cnp = config[\"aerodynamic\"][\"Cnp\"].as<double>();\n\n    double CLde = config[\"aerodynamic\"][\"CLde\"].as<double>();\n    double CYdr = config[\"aerodynamic\"][\"CYdr\"].as<double>();\n    double Cmde = config[\"aerodynamic\"][\"Cmde\"].as<double>();\n    double Cndr = config[\"aerodynamic\"][\"Cndr\"].as<double>();\n    double Cldr = config[\"aerodynamic\"][\"Cldr\"].as<double>();\n\n    double Lt = config[\"tether\"][\"length\"].as<double>();\n    double Ks = config[\"tether\"][\"Ks\"].as<double>();\n    double Kd = config[\"tether\"][\"Kd\"].as<double>();\n    double rx = config[\"tether\"][\"rx\"].as<double>();\n    double rz = config[\"tether\"][\"rz\"].as<double>();\n\n    DM REF_P = DM::vertcat({CL0, CLa_tot, CD0_tot, CYb, Cm0, Cma, Cnb, Clb, CLq, Cmq,\n                            CYr, Cnr, Clr, CYp, Clp, Cnp, CLde, CYdr, Cmde, Cndr, Cldr});\n    DM LBP = REF_P; DM UBP = REF_P;\n    LBP = -DM::inf(21);\n    UBP = DM::inf(21);\n\n\n    LBP[0] = REF_P[0] -  0.1 * fabs(REF_P[0]); UBP[0] = REF_P[0] +  0.1 * fabs(REF_P[0]); // CL0\n    LBP[1] = REF_P[1] - 0.05 * fabs(REF_P[1]); UBP[1] = REF_P[1] +  0.1 * fabs(REF_P[1]); // CLa\n    LBP[2] = REF_P[2] -  0.1 * fabs(REF_P[2]); UBP[2] = REF_P[2] + 0.25 * fabs(REF_P[2]); // CD0\n    LBP[3] = REF_P[3] -  0.5 * fabs(REF_P[3]); UBP[3] = REF_P[3] +  0.5 * fabs(REF_P[3]); // CYb\n    LBP[4] = REF_P[4] -  0.5 * fabs(REF_P[4]); UBP[4] = REF_P[4] +  0.5 * fabs(REF_P[4]); // Cm0\n    LBP[5] = REF_P[5] -  0.1 * fabs(REF_P[5]); UBP[5] = REF_P[5] + 0.30 * fabs(REF_P[5]); // Cma\n    LBP[6] = REF_P[6] -  0.5 * fabs(REF_P[6]); UBP[6] = REF_P[6] +  0.5 * fabs(REF_P[6]); // Cnb\n    LBP[7] = REF_P[7] -  0.5 * fabs(REF_P[7]); UBP[7] = REF_P[7] +  0.5 * fabs(REF_P[7]); // Clb\n    LBP[8] = REF_P[8] -  0.2 * fabs(REF_P[8]); UBP[8] = REF_P[8] +  0.2 * fabs(REF_P[8]); // CLq\n    LBP[9] = REF_P[9] -  0.3 * fabs(REF_P[9]); UBP[9] = REF_P[9] +  0.3 * fabs(REF_P[9]); // Cmq\n\n    LBP[10] = REF_P[10] -  0.3 * fabs(REF_P[10]); UBP[10] = REF_P[10] +  0.3 * fabs(REF_P[10]); // CYr\n    LBP[11] = REF_P[11] -  0.5 * fabs(REF_P[11]); UBP[11] = REF_P[11] +  0.5 * fabs(REF_P[11]); // Cnr\n    LBP[12] = REF_P[12] -  0.5 * fabs(REF_P[12]); UBP[12] = REF_P[12] +  0.5 * fabs(REF_P[12]); // Clr\n    LBP[13] = REF_P[13] -  0.5 * fabs(REF_P[13]); UBP[13] = REF_P[13] +  0.5 * fabs(REF_P[13]); // CYp\n    LBP[14] = REF_P[14] -  0.5 * fabs(REF_P[14]); UBP[14] = REF_P[14] +  0.5 * fabs(REF_P[14]); // Clp\n    LBP[15] = REF_P[15] -  0.3 * fabs(REF_P[15]); UBP[15] = REF_P[15] +  1.0 * fabs(REF_P[15]); // Cnp\n    LBP[16] = REF_P[16] -  0.5 * fabs(REF_P[16]); UBP[16] = REF_P[16] +  0.5 * fabs(REF_P[16]); // CLde\n    LBP[17] = REF_P[17] -  0.5 * fabs(REF_P[17]); UBP[17] = REF_P[17] +  0.5 * fabs(REF_P[17]); // CYdr\n    LBP[18] = REF_P[18] -  0.5 * fabs(REF_P[18]); UBP[18] = REF_P[18] +  0.5 * fabs(REF_P[18]); // Cmde\n    LBP[19] = REF_P[19] -  0.5 * fabs(REF_P[19]); UBP[19] = REF_P[19] +  0.5 * fabs(REF_P[19]); // Cndr\n    LBP[20] = REF_P[20] -  0.5 * fabs(REF_P[20]); UBP[20] = REF_P[20] +  0.5 * fabs(REF_P[20]); // Cldr\n\n    // LBP[21] = 2.65;    UBP[21] = 2.75;   // tether length\n    // LBP[22] = 150.0;  UBP[22] = 150.0;  // Ks\n    // LBP[23] = 0.0;    UBP[23] = 10;   // Kd\n    // LBP[24] = 0.0;    UBP[24] = 0.0;   // rx\n    // LBP[25] = 0.0;    UBP[25] = 0.0;  // rz\n\n    std::cout << \"OK so far \\n\";\n\n    /** ----------------------------------------------------------------------------------*/\n    const int num_segments = 10;\n    const int poly_order   = 20;\n    const int dimx         = 13;\n    const int dimu         = 3;\n    const int dimp         = 21;\n    const double tf        = 5.0;\n\n    Chebyshev<SX, poly_order, num_segments, dimx, dimu, dimp> spectral;\n    SX diff_constr = spectral.CollocateDynamics(DynamicsFunc, 0, tf);\n    diff_constr = diff_constr(casadi::Slice(0, num_segments * poly_order * dimx));\n\n    SX varx = spectral.VarX();\n    SX varu = spectral.VarU();\n    SX varp = spectral.VarP();\n\n    SX opt_var = SX::vertcat(SXVector{varx, varu, varp});\n\n    SX lbg = SX::zeros(diff_constr.size());\n    SX ubg = SX::zeros(diff_constr.size());\n\n    /** set inequality (box) constraints */\n    /** state */\n    SX lbx = SX::repmat(LBX, num_segments * poly_order + 1, 1);\n    SX ubx = SX::repmat(UBX, num_segments * poly_order + 1, 1);\n\n    /** control */\n    lbx = SX::vertcat({lbx, LBU});\n    ubx = SX::vertcat({ubx, UBU});\n\n    /** parameters */\n    lbx = SX::vertcat({lbx, LBP});\n    ubx = SX::vertcat({ubx, UBP});\n\n\n    DM Q  = SX::diag(SX({1e3, 1e2, 1e2,  1e2, 1e2, 1e2,  1e1, 1e1, 1e2,  1e2, 1e2, 1e2, 1e2})); //good one as well\n    //DM Q = 1e1 * DM::eye(13);\n    double alpha = 100.0;\n\n\n    SX fitting_error = 0;\n    SX varx_ = SX::reshape(varx, state_size, DATA_POINTS);\n    for (uint j = 0; j < DATA_POINTS; ++j)\n    {\n        SX measurement = id_data(Slice(0, id_data.size1()), j);\n        SX error = measurement - varx_(Slice(0, varx_.size1()), varx_.size2() - j - 1);\n        fitting_error += static_cast<double>(1.0 / DATA_POINTS) * SX::sumRows( SX::mtimes(Q, pow(error, 2)) );\n    }\n\n    /** add regularisation */\n    // fitting_error = fitting_error + alpha * SX::dot(varp - SX({REF_P}), varp - SX({REF_P}));\n\n    /** alternative approximation */\n    SX x = SX::sym(\"x\", state_size);\n    SX y = SX::sym(\"y\", state_size);\n    SX cost_function = SX::sumRows( SX::mtimes(Q, pow(x - y, 2)) );\n    Function IdCost = Function(\"IdCost\",{x,y}, {cost_function});\n    SX fitting_error2 = spectral.CollocateIdCost(IdCost, id_data, 0, tf);\n    fitting_error2 = fitting_error2 + alpha * SX::dot(varp - SX({REF_P}), varp - SX({REF_P}));\n\n    /** formulate NLP */\n    SXDict NLP;\n    Dict OPTS;\n    DMDict ARG;\n    NLP[\"x\"] = opt_var;\n    NLP[\"f\"] = fitting_error;\n    NLP[\"g\"] = diff_constr;\n\n    OPTS[\"ipopt.linear_solver\"]  = \"ma97\";\n    OPTS[\"ipopt.print_level\"]    = 5;\n    OPTS[\"ipopt.tol\"]            = 1e-4;\n    OPTS[\"ipopt.acceptable_tol\"] = 1e-4;\n    OPTS[\"ipopt.warm_start_init_point\"] = \"yes\";\n    //OPTS[\"ipopt.max_iter\"]       = 20;\n\n    Function NLP_Solver = nlpsol(\"solver\", \"ipopt\", NLP, OPTS);\n\n    std::cout << \"Ok here as well \\n\";\n\n    /** set default args */\n    ARG[\"lbx\"] = lbx;\n    ARG[\"ubx\"] = ubx;\n    ARG[\"lbg\"] = lbg;\n    ARG[\"ubg\"] = ubg;\n\n    /** provide initial guess from integrator */\n    casadi::DMDict props;\n    props[\"scale\"] = 0;\n    props[\"P\"] = casadi::DM::diag(casadi::DM({0.1, 1/3.0, 1/3.0, 1/2.0, 1/5.0, 1/2.0, 1/3.0, 1/3.0, 1/3.0, 1.0, 1.0, 1.0, 1.0}));\n    props[\"R\"] = casadi::DM::diag(casadi::DM({1/0.15, 1/0.2618, 1/0.2618}));\n    PSODESolver<poly_order,num_segments,dimx,dimu>ps_solver(ode, tf, props);\n\n\n    //here put actual numbers every time?\n    //DM x0 = id_data(Slice(0, id_data.size1()), 0);\n    DM init_state = id_data(Slice(0, id_data.size1()), 0);\n    DM init_control = DM({0.1, 0.0, 0.0});\n    init_control = casadi::DM::repmat(init_control, (num_segments * poly_order + 1), 1);\n\n    DMDict solution = ps_solver.solve_trajectory(init_state, init_control, true);\n    DM feasible_state = solution.at(\"x\");\n    //DM feasible_state = DM::reshape(id_data, 13 * (num_segments * poly_order + 1), 1);\n    //DM feasible_state = DM::repmat(id_data(Slice(0, id_data.size1()), 0), (num_segments * poly_order + 1), 1);\n\n    std::ofstream trajectory_file(\"integrated_trajectory.txt\", std::ios::out);\n\n    if(!trajectory_file.fail())\n    {\n        for (int i = 0; i < varx.size1(); i = i + 13)\n        {\n            std::vector<double> tmp = feasible_state(Slice(i, i + 13),0).nonzeros();\n            for (uint j = 0; j < tmp.size(); j++)\n            {\n                trajectory_file << tmp[j] << \" \";\n            }\n            trajectory_file << \"\\n\";\n        }\n    }\n    trajectory_file.close();\n\n    std::cout << \"Initial guess computed. \\n\";\n\n    DM feasible_control = (UBU + LBU) / 2;\n\n    //ARG[\"x0\"] = DM::vertcat(DMVector{feasible_state, feasible_control, REF_P});\n    ARG[\"x0\"] = DM::vertcat(DMVector{feasible_state, REF_P});\n    ARG[\"lam_g0\"] = solution.at(\"lam_g\");\n    ARG[\"lam_x0\"] = DM::vertcat({solution.at(\"lam_x\"), DM::zeros(REF_P.size1())});\n\n    int idx_in = num_segments * poly_order * dimx;\n    int idx_out = idx_in + dimx;\n    ARG[\"lbx\"](Slice(idx_in, idx_out), 0) = init_state;\n    ARG[\"ubx\"](Slice(idx_in, idx_out), 0) = init_state;\n\n    DMDict res = NLP_Solver(ARG);\n    DM result = res.at(\"x\");\n\n    DM new_params = result(Slice(result.size1() - varp.size1(), result.size1()));\n    std::vector<double> new_params_vec = new_params.nonzeros();\n\n    DM trajectory = result(Slice(0, varx.size1()));\n    //DM trajectory = DM::reshape(traj, DATA_POINTS, dimx );\n    std::ofstream est_trajectory_file(\"estimated_trajectory.txt\", std::ios::out);\n\n    if(!est_trajectory_file.fail())\n    {\n        for (int i = 0; i < trajectory.size1(); i = i + dimx)\n        {\n            std::vector<double> tmp = trajectory(Slice(i, i + dimx),0).nonzeros();\n            for (uint j = 0; j < tmp.size(); j++)\n            {\n                est_trajectory_file << tmp[j] << \" \";\n            }\n            est_trajectory_file << \"\\n\";\n        }\n    }\n    est_trajectory_file.close();\n\n    /** update parameter file */\n    config[\"aerodynamic\"][\"CL0\"] = new_params_vec[0];\n    config[\"aerodynamic\"][\"CLa_total\"] = new_params_vec[1];\n    config[\"aerodynamic\"][\"CD0_total\"] = new_params_vec[2];\n    config[\"aerodynamic\"][\"CYb\"] = new_params_vec[3];\n    config[\"aerodynamic\"][\"Cm0\"] = new_params_vec[4];\n    config[\"aerodynamic\"][\"Cma\"] = new_params_vec[5];\n    config[\"aerodynamic\"][\"Cnb\"] = new_params_vec[6];\n    config[\"aerodynamic\"][\"Clb\"] = new_params_vec[7];\n\n    config[\"aerodynamic\"][\"CLq\"] = new_params_vec[8];\n    config[\"aerodynamic\"][\"Cmq\"] = new_params_vec[9];\n    config[\"aerodynamic\"][\"CYr\"] = new_params_vec[10];\n    config[\"aerodynamic\"][\"Cnr\"] = new_params_vec[11];\n    config[\"aerodynamic\"][\"Clr\"] = new_params_vec[12];\n    config[\"aerodynamic\"][\"CYp\"] = new_params_vec[13];\n    config[\"aerodynamic\"][\"Clp\"] = new_params_vec[14];\n    config[\"aerodynamic\"][\"Cnp\"] = new_params_vec[15];\n\n    config[\"aerodynamic\"][\"CLde\"] = new_params_vec[16];\n    config[\"aerodynamic\"][\"CYdr\"] = new_params_vec[17];\n    config[\"aerodynamic\"][\"Cmde\"] = new_params_vec[18];\n    config[\"aerodynamic\"][\"Cndr\"] = new_params_vec[19];\n    config[\"aerodynamic\"][\"Cldr\"] = new_params_vec[20];\n\n    // config[\"tether\"][\"length\"] = new_params_vec[21];\n    // config[\"tether\"][\"Ks\"] = new_params_vec[22];\n    // config[\"tether\"][\"Kd\"] = new_params_vec[23];\n    // config[\"tether\"][\"rx\"] = new_params_vec[24];\n    // config[\"tether\"][\"rz\"] = new_params_vec[25];\n\n    std::ofstream fout(\"umx_radian_id.yaml\");\n    fout << config;\n\n    BOOST_CHECK(true);\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "1780167c5e85e7b6c6c5505fa0f8cabf9518cc6f", "size": 14428, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/kite_control/kite_identification_test.cpp", "max_stars_repo_name": "jowaibel/openkite", "max_stars_repo_head_hexsha": "165e4fc8e3e01934a36543be03e34a8cfa5b9926", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-05-21T20:40:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-19T19:28:17.000Z", "max_issues_repo_path": "src/kite_control/kite_identification_test.cpp", "max_issues_repo_name": "jowaibel/openkite", "max_issues_repo_head_hexsha": "165e4fc8e3e01934a36543be03e34a8cfa5b9926", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-12-04T14:00:12.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-04T14:00:12.000Z", "max_forks_repo_path": "src/kite_control/kite_identification_test.cpp", "max_forks_repo_name": "jowaibel/openkite", "max_forks_repo_head_hexsha": "165e4fc8e3e01934a36543be03e34a8cfa5b9926", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-07-11T09:53:26.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-06T13:01:12.000Z", "avg_line_length": 40.6422535211, "max_line_length": 129, "alphanum_fraction": 0.5750623787, "num_tokens": 5024, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619220634456, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.48551666463511856}}
{"text": "#include \"control/system/ss.h\"\n#include \"gtest/gtest.h\"\n#include \"gmock/gmock.h\"\n#include <Eigen/Dense>\n#include <iostream>\n\n/**\n * Discrete time state-space tests\n * @todo write tests for MIMO\n */\nnamespace {\n\nclass SSTest : public ::testing::Test {\npublic:\n    using ss = control::system::ss<float,2>;\nprotected:\n  ss *P; \n  SSTest() {\n    ss::TA A;\n    ss::TB B;\n    ss::TC C;\n    ss::TD D;\n    A << 1, 1, 0, 1;\n    B << 0.5, 1;\n    C << 1, 0;\n    D << 0;\n    P = new ss(A,B,C,D);      \n  }\n};\n\nTEST_F(SSTest, SimpleSSTest) {\n  std::vector<float> r(10);\n  std::vector<float> v = {0.5, 2, 4.5, 8, 12.5, 18, 24.5, 32, 40.5};\n  std::generate(r.begin(), r.end(), [this]{ \n                ss::Tu u;\n                u << 1;\n                auto y = P->step(u); \n                return y(0);\n                });\n\n\tfor( size_t i = 0; i < v.size(); i++ ) \n\t\tASSERT_FLOAT_EQ(r[i], v[i]);\n\n}\n\n}  // namespace\n", "meta": {"hexsha": "bc5ed8122277b8d28e4f723c6be5f45145ebdc96", "size": 901, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/ss-test.cpp", "max_stars_repo_name": "tomlankhorst/control", "max_stars_repo_head_hexsha": "8037e8a0267e2c1a4e7d9db0f0dbc8db634d3e1e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2018-04-12T07:09:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-17T19:45:18.000Z", "max_issues_repo_path": "tests/ss-test.cpp", "max_issues_repo_name": "tomlankhorst/control", "max_issues_repo_head_hexsha": "8037e8a0267e2c1a4e7d9db0f0dbc8db634d3e1e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-10-29T21:10:30.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-29T21:10:30.000Z", "max_forks_repo_path": "tests/ss-test.cpp", "max_forks_repo_name": "tomlankhorst/control", "max_forks_repo_head_hexsha": "8037e8a0267e2c1a4e7d9db0f0dbc8db634d3e1e", "max_forks_repo_licenses": ["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.170212766, "max_line_length": 68, "alphanum_fraction": 0.4927857936, "num_tokens": 314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503206, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.48551666209516614}}
{"text": "#include <geometry.h>\n#include <tiny.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n\n\n#include <vector>\n\ntypedef tiny::MathTypes<float> MT;\ntypedef MT::vector3_type       V;\ntypedef MT::real_type          T;\n\nclass ContactInfo\n{\npublic:\n\n  V m_point;\n  V m_normal;\n  T m_distance;\n\n};\n\n\nclass MyCallback\n  : public geometry::ContactsCallback<V>\n{\npublic:\n\n  std::vector<ContactInfo> m_contacts;\n\npublic:\n\n  void operator()(\n                  V const & point\n                  , V const & normal\n                  , typename V::real_type const & distance\n                  )\n  {\n    ContactInfo info;\n\n    info.m_point = point;\n    info.m_normal = normal;\n    info.m_distance = distance;\n\n    m_contacts.push_back(info);\n  }\n\n};\n\n\n\nBOOST_AUTO_TEST_SUITE(geometry);\n\nBOOST_AUTO_TEST_CASE(contacts_sphere_sphere_test)\n{\n\n  // Penetration\n  {\n    V const centerA = V::make(0.0, 0.0, 0.0);\n    T const radiusA = 2.0;\n    V const centerB = V::make(5.0, 0.0, 0.0);\n    T const radiusB = 4.0;\n\n    geometry::Sphere<V> const A = geometry::make_sphere(centerA, radiusA);\n    geometry::Sphere<V> const B = geometry::make_sphere(centerB, radiusB);\n\n    MyCallback callback;\n\n    geometry::contacts_sphere_sphere(A, B, 0.0, callback);\n\n    BOOST_CHECK(callback.m_contacts.size() == 1u);\n\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_point[0], 1.6666, 0.01);\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_point[1], 0.0, 0.01);\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_point[2], 0.0, 0.01);\n\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_normal[0], 1.0, 0.01);\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_normal[1], 0.0, 0.01);\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_normal[2], 0.0, 0.01);\n\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_distance, -1.0, 0.01);\n\n  }\n\n  // Touching\n  {\n    V const centerA = V::make(0.0, 0.0, 0.0);\n    T const radiusA = 2.0;\n    V const centerB = V::make(6.0, 0.0, 0.0);\n    T const radiusB = 4.0;\n\n    geometry::Sphere<V> const A = geometry::make_sphere(centerA, radiusA);\n    geometry::Sphere<V> const B = geometry::make_sphere(centerB, radiusB);\n\n    MyCallback callback;\n\n    geometry::contacts_sphere_sphere(A, B, 0.0, callback);\n\n    BOOST_CHECK(callback.m_contacts.size() == 1u);\n\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_point[0], 2.0, 0.01);\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_point[1], 0.0, 0.01);\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_point[2], 0.0, 0.01);\n\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_normal[0], 1.0, 0.01);\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_normal[1], 0.0, 0.01);\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_normal[2], 0.0, 0.01);\n\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_distance,  0.0, 0.01);\n    \n    \n  }\n\n  // Separation\n  {\n    V const centerA = V::make(0.0, 0.0, 0.0);\n    T const radiusA = 2.0;\n    V const centerB = V::make(7.0, 0.0, 0.0);\n    T const radiusB = 4.0;\n\n    geometry::Sphere<V> const A = geometry::make_sphere(centerA, radiusA);\n    geometry::Sphere<V> const B = geometry::make_sphere(centerB, radiusB);\n\n    MyCallback callback;\n\n    geometry::contacts_sphere_sphere(A, B, 0.0, callback);\n\n    BOOST_CHECK(callback.m_contacts.size() == 0u);\n  }\n\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "b452374ce1445e469932ae383dd97307d0543494", "size": 3381, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/FOUNDATION/GEOMETRY/unit_tests/geometry_contacts_sphere_sphere/geometry_contacts_sphere_sphere.cpp", "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/FOUNDATION/GEOMETRY/unit_tests/geometry_contacts_sphere_sphere/geometry_contacts_sphere_sphere.cpp", "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/FOUNDATION/GEOMETRY/unit_tests/geometry_contacts_sphere_sphere/geometry_contacts_sphere_sphere.cpp", "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": 24.5, "max_line_length": 74, "alphanum_fraction": 0.6640047323, "num_tokens": 1031, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619091240701, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.485516657015261}}
{"text": "/*\nA \"C\" interface to libigl's bbw.\n*/\n\n#include <cassert>\n\n#define IGL_HEADER_ONLY\n#define IGL_NO_MOSEK\n#include <igl/boundary_conditions.h>\n#include <igl/normalize_row_sums.h>\n#include <igl/bbw/bbw.h>\n\n#include <Eigen/Dense>\n\n#include <iostream>\n\n#define kVertexDimension 3\n\nextern \"C\"\n{\n\ntypedef double real_t;\ntypedef int index_t;\n\n// Returns 0 for success, anything else is an error.\nint bbw(\n    /// Input Parameters\n    // 'vertices' is a pointer to num_vertices*kVertexDimension floating point values,\n    // packed: x0, y0, z0, x1, y1, z1, ...\n    // In other words, a num_vertices-by-kVertexDimension matrix packed row-major.\n    int num_vertices, real_t* vertices,\n    // 'faces' is a pointer to num_faces*3 integers,\n    // where each face is three vertex indices: f0.v0, f0.v1, f0.v2, f1.v0, f1.v1, f1.v2, ...\n    // Face i's vertices are: vertices[ faces[3*i]*2 ], vertices[ faces[3*i+1]*2 ], vertices[ faces[3*i+2]*2 ]\n    // In other words, a num_faces-by-3 matrix packed row-major.\n    int num_faces, index_t* faces,\n    // 'skeleton_vertices' is a pointer to num_skeleton_vertices*kVertexDimension floating point values,\n    // packed the same way as 'vertices' (NOTE: And whose positions must also exist inside 'vertices'.)\n    int num_skeleton_vertices, real_t* skeleton_vertices,\n    // 'skeleton_point_handles' is a pointer to num_skeleton_point_handles integers,\n    // where each element \"i\" in skeleton_point_handles references the vertex whose data\n    // is located at skeleton_vertices[ skeleton_point_handles[i]*kVertexDimension ].\n    int num_skeleton_point_handles, index_t* skeleton_point_handles,\n    // TODO: Take skeleton bone edges and cage edges\n    \n    /// Output Parameters\n    // 'Wout' is a pointer to num_vertices*num_skeleton_vertices values.\n    // Upon return, W will be filled with each vertex in 'num_vertices' weight for\n    // each skeleton vertex in 'num_skeleton_vertices'.\n    // The data layout is that all 'num_skeleton_vertices' weights for vertex 0\n    // appear before all 'num_skeleton_vertices' weights for vertex 1, and so on.\n    // In other words, a num_vertices-by-num_skeleton_vertices matrix packed row-major.\n    real_t* Wout\n    )\n{\n    using namespace std;\n    using namespace igl;\n    using namespace Eigen;\n    \n    assert( num_vertices > 0 );\n    assert( vertices );\n    assert( num_faces > 0 );\n    assert( faces );\n    assert( num_skeleton_vertices > 0 );\n    assert( skeleton_vertices );\n    \n    // TODO: These next two asserts need not be true once we add support for the other\n    //       kinds of handles.\n    assert( num_skeleton_point_handles > 0 );\n    assert( skeleton_point_handles );\n    \n    assert( Wout );\n    \n    // #V by 2 list of mesh vertex positions\n    // Make this an Eigen::map from 'vertices'\n    MatrixXd V = Eigen::Map< Eigen::Matrix< real_t, Eigen::Dynamic, kVertexDimension, Eigen::RowMajor > >( vertices, num_vertices, kVertexDimension );\n    // #F by 3 list of triangle indices\n    // Make this an Eigen::map from 'faces'\n    MatrixXi F = Eigen::Map< Eigen::Matrix< index_t, Eigen::Dynamic, 3, Eigen::RowMajor > >( faces, num_faces, 3 );\n    \n    // \"Skeleton\" (handles) descriptors:\n    // List of control and joint (bone endpoint) positions\n    // Make this an Eigen::map from skeleton_vertices.\n    MatrixXd C = Eigen::Map< Eigen::Matrix< real_t, Eigen::Dynamic, kVertexDimension, Eigen::RowMajor > >( skeleton_vertices, num_skeleton_vertices, kVertexDimension );\n    // List of point handles indexing C\n    // Make this an Eigen::map from skeleton_point_handles.\n    VectorXi P = Eigen::Map< Eigen::Matrix< index_t, Eigen::Dynamic, 1 > >( skeleton_point_handles, num_skeleton_point_handles, 1 );\n    // List of bone edges indexing C\n    // TODO: ...\n    MatrixXi BE;\n    // List of cage edges indexing *P*\n    // TODO: ...\n    MatrixXi CE;\n    \n    // Compute boundary conditions (aka fixed value constraints)\n    // List of boundary indices (aka fixed value indices into VV)\n    VectorXi b;\n    // List of boundary conditions of each weight function\n    MatrixXd bc;\n    if(!boundary_conditions(V,F,C,P,BE,CE,b,bc))\n    {\n        return 1;\n    }\n    \n    // compute BBW \n    // Default bbw data and flags\n    BBWData bbw_data;\n    // Weights matrix\n    MatrixXd W;\n    if(!bbw(V,F,b,bc,bbw_data,W))\n    {\n        return 2;\n    }\n    \n    // Normalize weights.\n    normalize_row_sums(W,W);\n    \n    // Save output\n    // Copy W to Wout.\n    Eigen::Map< Eigen::Matrix< real_t, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor > >( Wout, num_vertices, num_skeleton_vertices ) = W;\n    \n    return 0;\n}\n\n}\n", "meta": {"hexsha": "e84697febb716860c0267ff5384012f96a524d78", "size": 4611, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/bbw_wrapper/bbw.cpp", "max_stars_repo_name": "songrun/VectorSkinning", "max_stars_repo_head_hexsha": "a19dff78215b51d824adcd39c7dcdf8dc78ec617", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2015-04-29T20:54:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-13T17:48:05.000Z", "max_issues_repo_path": "src/bbw_wrapper/bbw.cpp", "max_issues_repo_name": "songrun/VectorSkinning", "max_issues_repo_head_hexsha": "a19dff78215b51d824adcd39c7dcdf8dc78ec617", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/bbw_wrapper/bbw.cpp", "max_forks_repo_name": "songrun/VectorSkinning", "max_forks_repo_head_hexsha": "a19dff78215b51d824adcd39c7dcdf8dc78ec617", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-04-23T17:52:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T11:01:56.000Z", "avg_line_length": 36.5952380952, "max_line_length": 168, "alphanum_fraction": 0.6803296465, "num_tokens": 1198, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619091240701, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.485516657015261}}
{"text": "#include \"lwtnn/LightweightNeuralNetwork.hh\"\n#include \"lwtnn/Stack.hh\"\n#include \"lwtnn/parse_json.hh\"\n\n#include <Eigen/Dense>\n\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <fstream>\n\nvoid usage(const std::string& name) {\n  std::cout << \"usage: \" << name << \" <nn config> [<disable>]\\n\"\n            << \"\\n\"\n            << \"Read in an RNN, feed it data.\\n\"\n            << \"With anything for <disable>, just run the random number gen\";\n}\n\nstd::vector<lwt::ValueMap> get_values(\n  const std::vector<lwt::Input>& inputs) {\n  Eigen::MatrixXd test_pattern = Eigen::MatrixXd::Random(inputs.size(), 40);\n  std::vector<lwt::ValueMap> out;\n  const auto n_cols = static_cast<std::size_t>(test_pattern.cols());\n  for (std::size_t iii = 0; iii < n_cols; iii++) {\n    lwt::ValueMap vals;\n    for (std::size_t jjj = 0; jjj < inputs.size(); jjj++) {\n      vals[inputs.at(jjj).name] = test_pattern(jjj, iii);\n    }\n    out.push_back(vals);\n  }\n  return out;\n}\n\nlwt::VectorMap get_values_vec(const std::vector<lwt::Input>& inputs) {\n  Eigen::MatrixXd test_pattern = Eigen::MatrixXd::Random(inputs.size(), 40);\n  lwt::VectorMap out;\n  for (std::size_t in_num = 0; in_num < inputs.size(); in_num++) {\n    std::vector<double> ins;\n    const auto n_cols = static_cast<std::size_t>(test_pattern.cols());\n    for (std::size_t iii = 0; iii < n_cols; iii++) {\n      ins.push_back(test_pattern(in_num, iii));\n    }\n    out[inputs.at(in_num).name] = std::move(ins);\n  }\n  return out;\n}\n\nint main(int argc, char* argv[]) {\n  if (argc < 2 || argc > 3) {\n    usage(argv[0]);\n    exit(1);\n  }\n  bool run_stack = true;\n  if (argc == 3) {\n    run_stack = false;\n  }\n  // Read in the configuration.\n  std::string in_file_name(argv[1]);\n  std::ifstream in_file(in_file_name);\n  auto config = lwt::parse_json(in_file);\n\n  if (!config.miscellaneous.count(\"sort_order\")) {\n    std::cout << \"no sort order given!\" << std::endl;\n  } else {\n    std::cout << \"sort order: \" << config.miscellaneous.at(\"sort_order\")\n              << std::endl;\n  }\n\n  std::size_t n_inputs = config.inputs.size();\n  lwt::ReductionStack stack(n_inputs, config.layers);\n  lwt::LightweightRNN rnn(config.inputs, config.layers, config.outputs);\n  Eigen::VectorXd sum_outputs = Eigen::VectorXd::Zero(stack.n_outputs());\n  std::size_t n_loops = 1;\n  std::cout << \"running over \" << n_loops << \" loops\" << std::endl;\n  std::cout << \"running \" << (run_stack ? \"fast\": \"slow\") << std::endl;\n  for (std::size_t nnn = 0; nnn < n_loops; nnn++) {\n    if (run_stack) {\n      Eigen::MatrixXd test_pattern = Eigen::MatrixXd::Random(n_inputs, 2);\n      std::cout << test_pattern << std::endl;\n      sum_outputs += stack.reduce(test_pattern);\n    } else {\n      const auto inputs = get_values_vec(config.inputs);\n      auto out = rnn.reduce(inputs);\n      for (std::size_t iii = 0; iii < config.outputs.size(); iii++) {\n        sum_outputs(iii) += out.at(config.outputs.at(iii));\n      }\n    }\n  }\n  std::cout << \"output sum:\\n\" << sum_outputs << std::endl;\n  return 0;\n}\n", "meta": {"hexsha": "489db2ec9e186331cb814bf3646bd535f849c390", "size": 3012, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/lwtnn-benchmark-rnn.cxx", "max_stars_repo_name": "ishine/lwtnn", "max_stars_repo_head_hexsha": "e12098bf0a012b4975804e3db4455a9a2ab3a719", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 98.0, "max_stars_repo_stars_event_min_datetime": "2016-11-27T04:05:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T17:14:19.000Z", "max_issues_repo_path": "src/lwtnn-benchmark-rnn.cxx", "max_issues_repo_name": "ishine/lwtnn", "max_issues_repo_head_hexsha": "e12098bf0a012b4975804e3db4455a9a2ab3a719", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 90.0, "max_issues_repo_issues_event_min_datetime": "2016-11-24T15:13:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-29T14:09:34.000Z", "max_forks_repo_path": "src/lwtnn-benchmark-rnn.cxx", "max_forks_repo_name": "ishine/lwtnn", "max_forks_repo_head_hexsha": "e12098bf0a012b4975804e3db4455a9a2ab3a719", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 46.0, "max_forks_repo_forks_event_min_datetime": "2016-12-15T17:21:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-27T22:45:42.000Z", "avg_line_length": 32.7391304348, "max_line_length": 77, "alphanum_fraction": 0.6241699867, "num_tokens": 868, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.82446190912407, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4855166570152609}}
{"text": "/*\n * get_dimension_count.hpp\n *\n *  Created on: Apr 11, 2019\n *      Author: Gregory Kramida\n *   Copyright: 2019 Gregory Kramida\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n */\n\n#pragma once\n\n// libraries\n#include <Eigen/Eigen>\n#include <unsupported/Eigen/CXX11/Tensor>\n\n//local\n#include \"typedefs.hpp\"\n\nnamespace math {\n\ntemplate<typename Container>\nclass ContainerWrapper {};\n\ntemplate<typename Scalar>\nclass ContainerWrapper<Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic,Eigen::ColMajor> >{\npublic:\n\tstatic const int DimensionCount = 2;\n\ttypedef math::Vector2i Coordinates;\n\ttypedef Eigen::Matrix<math::Vector2<Scalar>,Eigen::Dynamic,Eigen::Dynamic,Eigen::ColMajor> VectorContainer;\n\ttypedef Eigen::Matrix<math::Matrix2<Scalar>,Eigen::Dynamic,Eigen::Dynamic,Eigen::ColMajor> MatrixContainer;\n};\n\ntemplate<typename Scalar, int DimensionCountIn>\nclass ContainerWrapper<Eigen::Tensor<Scalar, DimensionCountIn, Eigen::ColMajor>>{\npublic:\n\tstatic const int DimensionCount = DimensionCountIn;\n\ttypedef math::Vector3i Coordinates;\n};\n\ntemplate<typename Scalar>\nclass ContainerWrapper<Eigen::Tensor<Scalar, 3, Eigen::ColMajor>>{\npublic:\n\tstatic const int DimensionCount = 3;\n\ttypedef math::Vector3i Coordinates;\n\ttypedef Eigen::Tensor<math::Vector3<Scalar>,3,Eigen::ColMajor> VectorContainer;\n\ttypedef Eigen::Tensor<math::Matrix3<Scalar>,3,Eigen::ColMajor> MatrixContainer;\n};\n\n} // namespace math\n", "meta": {"hexsha": "80011cdfad3dff235a66b24530f5520018cafc16", "size": 1928, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/math/container_traits.hpp", "max_stars_repo_name": "Algomorph/LevelSetFusionExperimentsCPP", "max_stars_repo_head_hexsha": "f56962f0ad5c62e6706f818062782a2e1660afda", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2019-01-07T14:12:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T01:48:03.000Z", "max_issues_repo_path": "src/math/container_traits.hpp", "max_issues_repo_name": "Algomorph/LevelSetFusionExperimentsCPP", "max_issues_repo_head_hexsha": "f56962f0ad5c62e6706f818062782a2e1660afda", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2018-12-19T16:43:33.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-06T19:50:22.000Z", "max_forks_repo_path": "src/math/container_traits.hpp", "max_forks_repo_name": "Algomorph/LevelSetFusionExperimentsCPP", "max_forks_repo_head_hexsha": "f56962f0ad5c62e6706f818062782a2e1660afda", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-01-07T14:12:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-06T06:30:24.000Z", "avg_line_length": 31.606557377, "max_line_length": 108, "alphanum_fraction": 0.7567427386, "num_tokens": 454, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825006, "lm_q2_score": 0.6224593452091672, "lm_q1q2_score": 0.48551387632672993}}
{"text": "#include <Eigen/Dense>\n#include <mutex>\n#include <chrono> \n#include <atomic>\n#include <iostream>\n\n#ifndef UTILS_KALMAN_H\n#define UTILS_KALMAN_H\n\nnamespace utils {\n\n    //https://stackoverflow.com/a/28876046\n    template <typename T>\n    struct is_chrono_duration\n    {\n        static constexpr bool value = false;\n    };\n\n    template <typename Rep, typename Period>\n    struct is_chrono_duration<std::chrono::duration<Rep, Period>>\n    {\n        static constexpr bool value = true;\n    };\n\n    static void PRINT_MATRIX_SIZES(const Eigen::MatrixXd& P_0, const Eigen::VectorXd& z, const Eigen::VectorXd& u) {\n        int m = z.size(), l = u.size(), n = P_0.rows();\n        std::cout << \"\\n\\n\\n--------------------------\" << std::endl;\n        std::cout << \"m = z.size() = \" << m << std::endl;\n        std::cout << \"l = u.size() = \" << l << std::endl;\n        std::cout << \"n = P.rows() = \" << n << std::endl;\n        std::cout << \"A(nxn) = \" << n << \"x\" << n << std::endl; \n        std::cout << \"B(nxl) = \" << n << \"x\" << l << std::endl; \n        std::cout << \"C(mxn) = \" << m << \"x\" << n << std::endl; \n        std::cout << \"Q(nxn) = \" << n << \"x\" << n << std::endl; \n        std::cout << \"R(mxm) = \" << m << \"x\" << m << std::endl; \n        std::cout << \"K(nxm) = \" << n << \"x\" << m << std::endl; \n        std::cout << \"x(n) = \" << n << std::endl; \n        std::cout << \"--------------------------\\n\\n\\n\" << std::endl;\n    }\n\n    static void PRINT_MATRIX_SIZES(const Eigen::MatrixXd& P_0, const Eigen::VectorXd& z) {\n        int m = z.size(), n = P_0.rows();\n        std::cout << \"\\n\\n\\n--------------------------\" << std::endl;\n        std::cout << \"m = z.size() = \" << m << std::endl;\n        std::cout << \"n = P.rows() = \" << n << std::endl;\n        std::cout << \"A(nxn) = \" << n << \"x\" << n << std::endl; \n        std::cout << \"C(mxn) = \" << m << \"x\" << n << std::endl; \n        std::cout << \"Q(nxn) = \" << n << \"x\" << n << std::endl; \n        std::cout << \"R(mxm) = \" << m << \"x\" << m << std::endl; \n        std::cout << \"K(nxm) = \" << n << \"x\" << m << std::endl; \n        std::cout << \"x(n) = \" << n << std::endl; \n        std::cout << \"--------------------------\\n\\n\\n\" << std::endl;\n    }\n    template <typename T = std::chrono::milliseconds>\n    class Kalman {\n        static_assert(is_chrono_duration<T>::value, \"T not derived from std::chrono::duration\");\n    private:\n        Eigen::VectorXd x_;\n        std::mutex mtx_;\n        std::chrono::steady_clock::time_point last_call_;\n        Eigen::MatrixXd P_, K_, I_;\n        std::atomic<long> dt_{ 0 };\n        std::atomic_bool first_call_ {true};\n\n        /*\n        Method to set dt_ for the integral / derivate term\n        */\n        void setDt();\n\n        /**\n         * Initialize the component\n         */\n        void init();\n        \n        /**\n         * Update all matrices and dt\n         */\n        void preupdate();\n\n\n        /**\n         * Update the matrixes and calculate the values based on new x\n         * @param z The measured / calculated system state\n         */\n        void updateStep(const Eigen::VectorXd& z);\n\n    protected:\n        Eigen::MatrixXd A_, Q_, B_, R_, C_;\n        \n\n        /**\n         * Method to update the A matrix (state transition model) of the Kalman Filter\n         */\n        virtual void updateA();\n\n        /**\n         * Method to update the B matrix (control-input) of the Kalman Filter\n         */\n        virtual void updateB();\n\n        /**\n         * Method to update the C matrix (uutput matrix) of the Kalman Filter\n         */\n        virtual void updateC();\n\n        /**\n         * Method to update the Q matrix (process noise covariance) of the Kalman Filter\n         */\n        virtual void updateQ();\n\n        /**\n         * Method to update the R matrix (measurement noise covariance) of the Kalman Filter\n         */\n        virtual void updateR();\n\n    public:\n        /**\n         * Constructor\n         * @param A State transition model\n         * @param B Control input matrix\n         * @param C Output matrix\n         * @param P_0 Initial error covariance estiamtion\n         * @param Q Process noise covariance\n         * @param R Measurement noise covariance\n         * @param x0 Inital state guess\n         */\n        Kalman(\n            const Eigen::MatrixXd& A,\n            const Eigen::MatrixXd& B,\n            const Eigen::MatrixXd& C,\n            const Eigen::MatrixXd& P_0,\n            const Eigen::MatrixXd& Q,\n            const Eigen::MatrixXd& R,\n            const Eigen::VectorXd& x0\n        );\n\n        /**\n         * Constructor\n         * @param A State transition model\n         * @param B Control input matrix\n         * @param C Output matrix\n         * @param P_0 Initial error covariance estiamtion\n         * @param Q Process noise covariance\n         * @param R Measurement noise covariance\n         */\n        Kalman(\n            const Eigen::MatrixXd& A,\n            const Eigen::MatrixXd& B,\n            const Eigen::MatrixXd& C,\n            const Eigen::MatrixXd& P_0,\n            const Eigen::MatrixXd& Q,\n            const Eigen::MatrixXd& R\n        );\n\n\n        /**\n         * Constructor\n         *\n         * @param C Output matrix\n         * @param P_0 Initial error covariance estiamtion\n         * @param R Measurement noise covariance\n         * @param x0 Inital state guess\n         */\n        Kalman(\n            const Eigen::MatrixXd& C,\n            const Eigen::MatrixXd& P_0,\n            const Eigen::MatrixXd& R,\n            const Eigen::VectorXd& x0\n        );\n\n        /**\n         * Constructor\n         *\n         * @param C Output matrix\n         * @param P_0 Initial error covariance estiamtion\n         * @param R Measurement noise covariance\n         */\n        Kalman(\n            const Eigen::MatrixXd& C,\n            const Eigen::MatrixXd& P_0,\n            const Eigen::MatrixXd& R\n        );\n\n        /**\n         * Predict the state of the system based on observed state\n         * @param out Vector to store prediction\n         * @param z The observed state\n         *\n         */\n        void predict(Eigen::VectorXd& out, const Eigen::VectorXd& z);\n\n        /**\n         * Predict the state of the system based on control input\n         * @param out Vector to store prediction\n         * @param z The observed state\n         * @param u control input\n         */\n        void predict(Eigen::VectorXd& out, const Eigen::VectorXd& z, const Eigen::VectorXd& u);\n        \n        /**\n         * Method to get dt value\n         * @returns delta t between last steps\n         */\n        double getDt();\n    };\n}\n\n#endif", "meta": {"hexsha": "92e0bf16fdcb72aa13a88045082cb6fc960be198", "size": 6604, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "utils/src/kalman.hpp", "max_stars_repo_name": "Krenol/CppUtils", "max_stars_repo_head_hexsha": "c2edd9ca845fc6975d4179733b39c4d34a4b0ea0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "utils/src/kalman.hpp", "max_issues_repo_name": "Krenol/CppUtils", "max_issues_repo_head_hexsha": "c2edd9ca845fc6975d4179733b39c4d34a4b0ea0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "utils/src/kalman.hpp", "max_forks_repo_name": "Krenol/CppUtils", "max_forks_repo_head_hexsha": "c2edd9ca845fc6975d4179733b39c4d34a4b0ea0", "max_forks_repo_licenses": ["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.75, "max_line_length": 116, "alphanum_fraction": 0.498788613, "num_tokens": 1652, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.779992900254107, "lm_q2_score": 0.6224593452091672, "lm_q1q2_score": 0.4855138699599707}}
{"text": "// This file is part of libigl, a simple c++ geometry processing library.\n// \n// Copyright (C) 2016 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 \"point_solid_signed_squared_distance.h\"\n#include \"points_inside_component.h\"\n#include \"point_mesh_squared_distance.h\"\n#include \"../../list_to_matrix.h\"\n#include \"../../slice_mask.h\"\n#include <vector>\n#include <Eigen/Core>\n\ntemplate <\n  typename DerivedQ,\n  typename DerivedVB,\n  typename DerivedFB,\n  typename DerivedD>\nIGL_INLINE void igl::copyleft::cgal::point_solid_signed_squared_distance(\n  const Eigen::PlainObjectBase<DerivedQ> & Q,\n  const Eigen::PlainObjectBase<DerivedVB> & VB,\n  const Eigen::PlainObjectBase<DerivedFB> & FB,\n  Eigen::PlainObjectBase<DerivedD> & D)\n{\n  // compute unsigned distances\n  Eigen::VectorXi I;\n  DerivedVB C;\n  point_mesh_squared_distance<CGAL::Epeck>(Q,VB,FB,D,I,C);\n  // Collect queries that have non-zero distance\n  Eigen::Array<bool,Eigen::Dynamic,1> NZ = D.array()!=0;\n  // Compute sign for non-zero distance queries\n  DerivedQ QNZ;\n  slice_mask(Q,NZ,1,QNZ);\n  Eigen::Array<bool,Eigen::Dynamic,1> DNZ;\n  igl::copyleft::cgal::points_inside_component(VB,FB,QNZ,DNZ);\n  // Apply sign to distances\n  DerivedD S = DerivedD::Zero(Q.rows(),1);\n  {\n    int k = 0;\n    for(int q = 0;q<Q.rows();q++)\n    {\n      if(NZ(q))\n      {\n        D(q) *= DNZ(k++) ? -1. : 1.;\n      }\n    }\n  }\n}\n\n#ifdef IGL_STATIC_LIBRARY\n// Explicit template instantiation\ntemplate void igl::copyleft::cgal::point_solid_signed_squared_distance<Eigen::Matrix<CGAL::Epeck::FT, -1, 3, 0, -1, 3>, Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<CGAL::Epeck::FT, -1, 1, 0, -1, 1> >(Eigen::PlainObjectBase<Eigen::Matrix<CGAL::Epeck::FT, -1, 3, 0, -1, 3> > const&, 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<CGAL::Epeck::FT, -1, 1, 0, -1, 1> >&);\n#endif\n", "meta": {"hexsha": "d975b45809f675a5d05cf6dac5eb31e4fae0cf1b", "size": 2196, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/depends/igl/headers/igl/copyleft/cgal/point_solid_signed_squared_distance.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/point_solid_signed_squared_distance.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/point_solid_signed_squared_distance.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": 39.2142857143, "max_line_length": 552, "alphanum_fraction": 0.6775956284, "num_tokens": 709, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6224593452091672, "lm_q1q2_score": 0.48551386995997065}}
{"text": "//=======================================================================\n// Copyright (c) 2014 Piotr Smulewicz\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n/**\n * @file multiway_cut_test_long.cpp\n * @brief\n * @author Piotr Smulewicz\n * @version 1.0\n * @date 2014-01-17\n */\n\n#include <boost/test/unit_test.hpp>\n\n#include \"test_utils/logger.hpp\"\n#include \"test_utils/test_result_check.hpp\"\n\n#include \"paal/multiway_cut/multiway_cut.hpp\"\n#include \"paal/utils/irange.hpp\"\n\n#include <boost/graph/adjacency_list.hpp>\n\n#include <vector>\n\nnamespace{\ntemplate <typename Graph>\ndouble test(Graph graph){\n    auto weight= boost::get(boost::edge_weight, graph);\n    std::vector<std::pair<int,int> > vertices_parts;\n    LOGLN(\"multiway_cut: \");\n    auto cost_cut=paal::multiway_cut(graph,back_inserter(vertices_parts));\n    std::vector<int> vertices_to_parts;\n    vertices_to_parts.resize(vertices_parts.size());\n    for(auto i:vertices_parts){\n        LOG(i.first<<\"(\"<<i.second<<\"), \");\n        vertices_to_parts[i.first]=i.second;\n    }\n    LOGLN(\"\");\n    int cost_cut_verification=0;\n    auto all_edges=edges(graph);\n    for(auto i=all_edges.first;i!=all_edges.second;i++){\n        if(vertices_to_parts[source(*i,graph)]!=vertices_to_parts[target(*i,graph)])\n            cost_cut_verification+=weight(*i);\n    }\n\n    LOGLN(\"Cost Cut:              \"<<cost_cut);\n    LOGLN(\"Cost Cut Verification: \"<<cost_cut_verification );\n    LOGLN(\"\");\n    BOOST_CHECK_EQUAL(cost_cut,cost_cut_verification);\n    return cost_cut;\n}\nauto env_to_add_edge =[](std::vector<std::pair<int,int> >& edges,std::vector<long long>& cost_edges){\n    return [&](int source,int target,int edge_cost){\n        edges.push_back(std::make_pair(source,target));\n        cost_edges.push_back(edge_cost);\n        LOGLN(source<<\" \"<<target<<\" \"<<edge_cost);\n    };\n};\n\n}\nBOOST_AUTO_TEST_SUITE(multiway_cut)\n\n\nBOOST_AUTO_TEST_CASE(multiway_cut_random) {\n    static const int NU_VERTICES=1000;\n    static const int NU_RANDOM_EDGES=1000;\n    static const int NU_TERMINAL_EDGES=1000;\n    static const int NU_COMPONENTS_EDGES=1000;\n    static const int SEED=211;\n    static const int CONECT_TO_TERMINAL_COST=1000*1000;\n    static const int CONECT_IN_COMPONENT_COST=1000;\n    static const int CONECT_BETWEEN_COMPONENTS_COST=1;\n    static const int NU_COMPONENTS=3;\n    std::vector<std::pair<int,int> > edges_p;\n    std::vector<long long> cost_edges;\n    std::srand(SEED);\n    auto add_edge_to_graph=env_to_add_edge(edges_p,cost_edges);\n    auto rand_vertex_id=[&](){\n        return rand()%NU_VERTICES;\n    };\n    auto rand_vertex_id_in_component=[&](int component){\n        return (((rand_vertex_id())/NU_COMPONENTS)*NU_COMPONENTS+component)%NU_VERTICES;\n    };\n\n    {\n        //add edges to terminals\n        int source,target,nu_edges_copy=NU_TERMINAL_EDGES;\n        while(--nu_edges_copy){\n            do{\n                source=rand_vertex_id();\n                target=source%NU_COMPONENTS;\n            }while(source==target);\n            add_edge_to_graph(source,target,CONECT_TO_TERMINAL_COST);\n        }\n\n        //add edges in components\n        nu_edges_copy=NU_COMPONENTS_EDGES;\n        while(--nu_edges_copy){\n            do{\n                source=rand_vertex_id();\n                target=rand_vertex_id_in_component(source);\n            }while(source==target);\n            add_edge_to_graph(source,target,CONECT_IN_COMPONENT_COST);\n        }\n\n        //add random edges\n        nu_edges_copy=NU_RANDOM_EDGES;\n        while(--nu_edges_copy){\n            do{\n                source=rand_vertex_id();\n                target=rand_vertex_id();\n            }while(source==target);\n            add_edge_to_graph(source,target,CONECT_BETWEEN_COMPONENTS_COST);\n        }\n    }\n    std::vector<int> terminals={0,1,2};\n    boost::adjacency_list<boost::vecS,boost::vecS,boost::undirectedS,\n                    boost::property < boost::vertex_color_t, int>,\n                    boost::property < boost::edge_weight_t, int>\n                    > graph(edges_p.begin(),edges_p.end(),cost_edges.begin(),NU_VERTICES);\n\n    for(std::size_t i=1;i<=terminals.size();i++)\n        put (boost::vertex_color,graph,terminals[i-1],i);\n    ::test(graph);\n}\n\nBOOST_AUTO_TEST_CASE(multiway_cut_triangle) {\n    //We place 33*33 points on the grid\n    //each point above diagonal have edge to right, down and left-down neighbor\n    //each point on diagonal have edge to left-down neighbor\n    //\n    //  *-*-*-*-*\n    //  |/|/|/|/\n    //  *-*-*-* *\n    //  |/|/|/\n    //  *-*-* * *\n    //  |/|/\n    //  *-* * * *\n    //  |/\n    //  * * * * *\n    //\n    // in the oder words we have triangle\n    // and we several times get all triangle add point on each edge and connect\n    // them dividing triangle on 4 triangle\n    // edges added in each step have ten times smaller cost\n\n    static const int SIZ=33;\n    static const int OPTIMAL=324992;\n    static const int NU_VERTICES=SIZ*SIZ;\n    static const int SEED=211;\n    std::vector<std::pair<int,int> > edges_p;\n    std::vector<long long> cost_edges;\n    std::srand(SEED);\n    auto coordinates= [&](int x,int y){return x*SIZ+y;};\n    auto size_range = paal::irange(SIZ);\n    auto add_edge_to_graph=env_to_add_edge(edges_p,cost_edges);\n    auto gen_cost=[](int position){\n        long long cost=1;\n        while(position%2==0){\n            position/=2;\n            cost*=10;\n        }\n        return cost;\n    };\n\n    {\n        for(auto i:size_range)\n        for(auto j:size_range){\n            if(i+j<SIZ-1){\n                //add horizontal edges\n                add_edge_to_graph(coordinates(i,j),coordinates(i,j+1),gen_cost(i+SIZ-1));\n                //add vertical edges\n                add_edge_to_graph(coordinates(i,j),coordinates(i+1,j),gen_cost(j+SIZ-1));\n            }\n            if(i+j<SIZ&&i>0){\n                //add diagonal edges\n                add_edge_to_graph(coordinates(i,j),coordinates(i-1,j+1),gen_cost(i+j));\n            }\n        }\n    }\n    std::vector<int> terminals={0,SIZ-1,(SIZ-1)*SIZ};\n    boost::adjacency_list<boost::vecS,boost::vecS,boost::undirectedS,\n                    boost::property < boost::vertex_color_t, int>,\n                    boost::property < boost::edge_weight_t, int>\n                    > graph(edges_p.begin(),edges_p.end(),cost_edges.begin(),NU_VERTICES);\n\n    for (std::size_t i = 1; i <= terminals.size(); i++)\n        put(boost::vertex_color, graph, terminals[i - 1], i);\n\n    int cost_cut=::test(graph);\n    check_result(cost_cut,OPTIMAL,2);\n}\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "c48bf7671dad8a4b3e696655d516a5aa8f08775c", "size": 6699, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/linear_programming/multiway_cut/multiway_cut_test_long.cpp", "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": "test/linear_programming/multiway_cut/multiway_cut_test_long.cpp", "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": "test/linear_programming/multiway_cut/multiway_cut_test_long.cpp", "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": 34.0050761421, "max_line_length": 101, "alphanum_fraction": 0.6102403344, "num_tokens": 1671, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825006, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4855138654011254}}
{"text": "#ifndef WALKING_PATTERN_GENERATOR_H\n#define WALKING_PATTERN_GENERATOR_H\n\n#include <Eigen/Dense>\n#include <cmath>\n#include <string>\n#include <avatar_locomanipulation/data_types/footstep.hpp>\n#include <avatar_locomanipulation/data_types/trajectory_SE3.hpp>\n\n#include <avatar_locomanipulation/helpers/hermite_curve_vec.hpp>\n#include <avatar_locomanipulation/helpers/hermite_quaternion_curve.hpp>\n#include <iostream>\n\n\nclass WalkingPatternGenerator{\npublic:\n  WalkingPatternGenerator();\n  ~WalkingPatternGenerator(); \n\n  static int const SWING_VRP_TYPE;\n  static int const DOUBLE_SUPPORT_TRANSFER_VRP_TYPE;\n\n  static int const STATE_INITIAL_TRANSFER;\n  static int const STATE_SWING;\n  static int const STATE_DOUBLE_SUPPORT;\n  static int const STATE_FINAL_TRANSFER;\n\n  std::vector<Footstep> footstep_list;\n\n  std::vector<Eigen::Vector3d> rvrp_list; // List of virtual repelant points.\n  std::vector<Eigen::Vector3d> dcm_ini_list; // List of initial DCM states \n  std::vector<Eigen::Vector3d> dcm_eos_list; // List of end-of-step DCM states\n\n  std::vector<int> rvrp_type_list; // List of type of virtual repelant point\n\n\n  Eigen::Vector3d start_stance_rvrp;\n  Eigen::Vector3d start_stance_dcm_ini;  \n  Eigen::Vector3d start_stance_dcm_eos;  \n\n  // DCM parameters:\n  double gravity = 9.81;\n  double z_vrp = 0.95; //1.0; // desired VRP height / CoM height\n  double b = std::sqrt(z_vrp/gravity); // time constant of DCM dynamics  \n\n  double t_ds = 0.45; //0.9; // time in double support\n  double t_ss = 1.0;//1.2; // time in single support\n  double t_settle = -b*log(0.001); // settling time at the end of the full walking trajectory \n  double t_transfer = -b*log(1.0 - 0.01); // settling time at the end of the full walking trajectory \n\n  double swing_height = 0.1; //0.05; // swing height in meters.\n\n  void setCoMHeight(double z_vrp_in); // Sets the desired CoM Height\n  void setDoubleSupportTime(double t_ds_in); // Sets the desired double support time\n  void setSingleSupportSwingTime(double t_ss_in); // Sets the desired single support swing time\n  void setSettlingPercentage(double percentage_convergence); // Percentage to settle. Default 0.999\n  void setSwingHeight(double swing_height_in); // Sets the swing height of the robot. Default 0.1m\n\n  // DCM trajectory calculation\n  // input: input_footstep_list - a list of footsteps to take not including the current stance configuration.\n  //        initial_footstance  - a footstep object describing the stance leg. \n  // populates this object's footstep_list, rvrp_list, dcm_ini_list, dcm_eos_list\n  void initialize_footsteps_rvrp(const std::vector<Footstep> & input_footstep_list, const Footstep & initial_footstance, bool clear_list=false);\n\n  // input: input_footstep_list - a list of footsteps to take not including the current stance configuration.\n  //        initial_footstance  - a footstep object describing the stance leg. \n  //        initial_rvrp        - an initial virtual repelant point (eg: average of the stance feet's rvrp). \n  // populates this object's footstep_list, rvrp_list, dcm_ini_list, dcm_eos_list\n  void initialize_footsteps_rvrp(const std::vector<Footstep> & input_footstep_list, const Footstep & initial_footstance, const Eigen::Vector3d & initial_rvrp);\n\n  // input: input_footstep_list - a list of footsteps to take not including the current stance configuration.\n  //        left_footstance        - a footstep object describing the left stance feet\n  //        right_footstance       - a footstep object describing the right stance feet\n  // populates this object's footstep_list, rvrp_list, dcm_ini_list, dcm_eos_list. \n  void initialize_footsteps_rvrp(const std::vector<Footstep> & input_footstep_list, const Footstep & left_footstance, const Footstep & right_footstance);\n\n  // input: input_footstep_list - a list of footsteps to take not including the current stance configuration.\n  //        left_footstance        - a footstep object describing the left stance feet\n  //        right_footstance       - a footstep object describing the right stance feet\n  //        initial_com            - the initial location of the com \n  // populates this object's footstep_list, rvrp_list, dcm_ini_list, dcm_eos_list. \n  void initialize_footsteps_rvrp(const std::vector<Footstep> & input_footstep_list, const Footstep & left_footstance, const Footstep & right_footstance, const Eigen::Vector3d & initial_com);\n\n\n   // Outputs the average r_vrp location given two footstances\n  void get_average_rvrp(const Footstep & footstance_1, const Footstep & footstance_2, Eigen::Vector3d & average_rvrp);\n\n    // computes all the dcm states. Computation properly populates the dcm_ini_list and dcm_eos_list\n  void computeDCM_states();\n\n  // Initialize trajectory clock\n  void initialize_internal_clocks();\n\n  // Given a delta_t compute the next desired DCM\n  Eigen::Vector3d get_next_desired_DCM(const double & dt);\n\n  // Given the current \n  Eigen::Vector3d get_desired_DCM(const int & step_index, const double & t);\n  Eigen::Vector3d get_com_vel(const Eigen::Vector3d & current_com, const int & step_index, const double & t);\n\n\n  double get_total_trajectory_time();\n  void initialize_trajectory_discretization(const int & N_samples);\n\n  void construct_trajectories(const std::vector<Footstep> & input_footstep_list, \n                              const Footstep & initial_left_footstance,\n                              const Footstep & initial_right_footstance, \n                              const Eigen::Vector3d & initial_com,\n                              const Eigen::Quaterniond initial_pelvis_ori);\n\n\n  // trajectory objects\n  Footstep mid_foot_;\n  TrajSE3         traj_SE3_tmp;;\n  TrajSE3         traj_SE3_left_foot;\n  TrajSE3         traj_SE3_right_foot;\n  TrajOrientation traj_ori_pelvis;\n  TrajEuclidean   traj_pos_com;\n  TrajEuclidean   traj_dcm_pos;\n\n  std::vector<int> state_list;\n  std::vector<int> bin_size_list;\n  std::vector<int> stance_list;\n  std::vector<Footstep> stance_location_list;\n  std::vector<Footstep> swing_landing_location_list;\n\n  void compute_trajectory_lists();\n  void compute_pelvis_orientation_trajectory(const Eigen::Quaterniond & init_pelvis_ori,\n                                             const Footstep & initial_left_footstance,\n                                             const Footstep & initial_right_footstance);\n\n  void compute_foot_trajectories(const Footstep & initial_left_footstance,\n                                 const Footstep & initial_right_footstance);\n  void compute_com_dcm_trajectory(const Eigen::Vector3d & initial_com);\n\n  void setOrientationTrajectory(const int & starting_index, const int & N_bins, HermiteQuaternionCurve & curve, TrajOrientation & traj_ori);\n  void setSwingFootTrajectory(const Footstep & init_location, const Footstep & landing_location, const int & starting_index, const int & N_bins, TrajSE3 & swing_foot);\n  void setConstantSE3(const int & starting_index, const int & N_bins, TrajSE3 & traj, const Eigen::Vector3d & pos, const Eigen::Quaterniond & quat);  \n\nprivate:\n  // input: r_vrp_d_i - the desired virtual repelant point for the i-th step.\n  //        t_step    - the time interval to use for backwards integration\n  //        dcm_eos_i - the DCM state at the end of the i-th step. \n  // computes the step i's initial DCM state and the end-of-step i-1's dcm state. \n  // The computation is stored in the dcm_ini_list and dcm_eos_list. \n  Eigen::Vector3d computeDCM_ini_i(const Eigen::Vector3d & r_vrp_d_i, const double & t_step, const Eigen::Vector3d & dcm_eos_i);\n\n  // Get the t_step for step i.\n  double get_t_step(const int & step_i);\n\n  double internal_timer;\n  double internal_t_step;\n  double internal_step_timer;\n  int internal_step_i;\n\n  int N_size;\n  double internal_dt;\n\n\n\n\n};\n\n#endif", "meta": {"hexsha": "30e4a8a533e3f9d86795de4c9cc09d6db65f8cc3", "size": 7762, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/avatar_locomanipulation/walking/walking_pattern_generator.hpp", "max_stars_repo_name": "stevenjj/icra2020locomanipulation", "max_stars_repo_head_hexsha": "414085b68cc1b3b24f7b920b543bba9d95350c16", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-01-06T11:43:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-14T22:59:09.000Z", "max_issues_repo_path": "include/avatar_locomanipulation/walking/walking_pattern_generator.hpp", "max_issues_repo_name": "stevenjj/icra2020locomanipulation", "max_issues_repo_head_hexsha": "414085b68cc1b3b24f7b920b543bba9d95350c16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/avatar_locomanipulation/walking/walking_pattern_generator.hpp", "max_forks_repo_name": "stevenjj/icra2020locomanipulation", "max_forks_repo_head_hexsha": "414085b68cc1b3b24f7b920b543bba9d95350c16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-09-03T16:08:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T11:13:49.000Z", "avg_line_length": 47.3292682927, "max_line_length": 190, "alphanum_fraction": 0.7389847977, "num_tokens": 1935, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825006, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4855138654011254}}
{"text": "//\n// Copyright (c) 2016-2019 CNRS INRIA\n//\n\n#ifndef __pinocchio_math_fwd_hpp__\n#define __pinocchio_math_fwd_hpp__\n\n#include \"pinocchio/fwd.hpp\"\n#include <math.h>\n#include <boost/math/constants/constants.hpp>\n\nnamespace pinocchio\n{\n\n  template <typename T>\n  struct is_floating_point : boost::is_floating_point<T>\n  {\n  };\n\n  ///\n  /// \\brief Returns the value of PI according to the template parameters Scalar\n  ///\n  /// \\tparam Scalar The scalar type of the return pi value\n  ///\n  template<typename Scalar>\n  const Scalar PI()\n  { return boost::math::constants::pi<Scalar>(); }\n  \n  ///\u00a0\\brief Foward declaration of TaylorSeriesExpansion.\n  template<typename Scalar> struct TaylorSeriesExpansion;\n  \n  namespace math\n  {\n    \n#define PINOCCHIO_OVERLOAD_MATH_UNARY_OPERATOR(name) \\\n    template<typename Scalar> \\\n    Scalar name(const Scalar & value) \\\n    { using std::name; return name(value); }\n    \n#define PINOCCHIO_OVERLOAD_MATH_BINARY_OPERATOR(name) \\\n    namespace internal \\\n    { \\\n      template<typename T1, typename T2> \\\n      struct return_type_##name \\\n      { \\\n        typedef T1 type; \\\n      }; \\\n      template<typename T1, typename T2> \\\n      struct call_##name \\\n      { \\\n        static inline typename return_type_##name<T1,T2>::type \\\n        run(const T1 & a, const T2 & b) \\\n        { using std::name; return name(a,b); } \\\n      }; \\\n    } \\\n    template<typename T1, typename T2> \\\n    inline typename internal::return_type_##name<T1,T2>::type name(const T1 & a, const T2 & b) \\\n    { return internal::call_##name<T1,T2>::run(a,b); }\n    \n    PINOCCHIO_OVERLOAD_MATH_UNARY_OPERATOR(fabs)\n    PINOCCHIO_OVERLOAD_MATH_UNARY_OPERATOR(sqrt)\n    PINOCCHIO_OVERLOAD_MATH_UNARY_OPERATOR(atan)\n    PINOCCHIO_OVERLOAD_MATH_UNARY_OPERATOR(acos)\n    PINOCCHIO_OVERLOAD_MATH_UNARY_OPERATOR(asin)\n    PINOCCHIO_OVERLOAD_MATH_UNARY_OPERATOR(cos)\n    PINOCCHIO_OVERLOAD_MATH_UNARY_OPERATOR(sin)\n    \n    PINOCCHIO_OVERLOAD_MATH_BINARY_OPERATOR(pow)\n    PINOCCHIO_OVERLOAD_MATH_BINARY_OPERATOR(min)\n    PINOCCHIO_OVERLOAD_MATH_BINARY_OPERATOR(max)\n    PINOCCHIO_OVERLOAD_MATH_BINARY_OPERATOR(atan2)\n  }\n}\n\n#endif //#ifndef __pinocchio_math_fwd_hpp__\n", "meta": {"hexsha": "d10fe48c8c0eb9022a4087d2d6abc3ccc8e6104d", "size": 2169, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/math/fwd.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/math/fwd.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/math/fwd.hpp", "max_forks_repo_name": "thanhndv212/pinocchio", "max_forks_repo_head_hexsha": "3b4d272bf4e8a231954b71201ee7e0963c944aef", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 239.0, "max_forks_repo_forks_event_min_datetime": "2015-02-05T14:15:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T23:51:47.000Z", "avg_line_length": 28.5394736842, "max_line_length": 96, "alphanum_fraction": 0.7049331489, "num_tokens": 560, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6224593382055109, "lm_q1q2_score": 0.48551386449716843}}
{"text": "/* test_student_t_distribution.cpp\n *\n * Copyright Steven Watanabe 2011\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#include <boost/random/student_t_distribution.hpp>\n#include <limits>\n\n#define BOOST_RANDOM_DISTRIBUTION boost::random::student_t_distribution<>\n#define BOOST_RANDOM_ARG1 n\n#define BOOST_RANDOM_ARG1_DEFAULT 1.0\n#define BOOST_RANDOM_ARG1_VALUE 7.5\n\n#define BOOST_RANDOM_DIST0_MIN -(std::numeric_limits<double>::infinity)()\n#define BOOST_RANDOM_DIST0_MAX (std::numeric_limits<double>::infinity)()\n#define BOOST_RANDOM_DIST1_MIN -(std::numeric_limits<double>::infinity)()\n#define BOOST_RANDOM_DIST1_MAX (std::numeric_limits<double>::infinity)()\n\n#define BOOST_RANDOM_TEST1_PARAMS\n\n#define BOOST_RANDOM_TEST2_PARAMS (100.0)\n\n#include \"test_distribution.ipp\"\n", "meta": {"hexsha": "3602f6750abb7a7583261750aeac7f47d89ff1f2", "size": 900, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/random/test/test_student_t_distribution.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "boost/libs/random/test/test_student_t_distribution.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "boost/libs/random/test/test_student_t_distribution.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "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.0, "max_line_length": 73, "alphanum_fraction": 0.7933333333, "num_tokens": 213, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4855138590343662}}
{"text": "///////////////////////////////////////////////////////////////////////////////\r\n// weighted_sum_kahan.hpp\r\n//\r\n//  Copyright 2011 Simon West. 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_SUM_KAHAN_HPP_EAN_11_05_2011\r\n#define BOOST_ACCUMULATORS_STATISTICS_WEIGHTED_SUM_KAHAN_HPP_EAN_11_05_2011\r\n\r\n#include <boost/mpl/placeholders.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/parameters/weight.hpp>\r\n#include <boost/accumulators/framework/accumulators/external_accumulator.hpp>\r\n#include <boost/accumulators/framework/depends_on.hpp>\r\n#include <boost/accumulators/statistics_fwd.hpp>\r\n#include <boost/accumulators/statistics/weighted_sum.hpp>\r\n#include <boost/numeric/conversion/cast.hpp>\r\n\r\nnamespace boost { namespace accumulators\r\n{\r\n\r\nnamespace impl\r\n{\r\n#if _MSC_VER > 1400\r\n# pragma float_control(push)\r\n# pragma float_control(precise, on)\r\n#endif\r\n\r\n    ///////////////////////////////////////////////////////////////////////////////\r\n    // weighted_sum_kahan_impl\r\n    template<typename Sample, typename Weight, typename Tag>\r\n    struct weighted_sum_kahan_impl\r\n      : accumulator_base\r\n    {\r\n        typedef typename numeric::functional::multiplies<Sample, Weight>::result_type weighted_sample;\r\n\r\n        // for boost::result_of\r\n        typedef weighted_sample result_type;\r\n\r\n        template<typename Args>\r\n        weighted_sum_kahan_impl(Args const &args)\r\n          : weighted_sum_(\r\n                args[parameter::keyword<Tag>::get() | Sample()] * numeric::one<Weight>::value),\r\n                compensation(boost::numeric_cast<weighted_sample>(0.0))\r\n        {\r\n        }\r\n\r\n        template<typename Args>\r\n        void \r\n#if BOOST_ACCUMULATORS_GCC_VERSION > 40305\r\n        __attribute__((optimize(\"no-associative-math\")))\r\n#endif\r\n        operator ()(Args const &args)\r\n        {\r\n            const weighted_sample myTmp1 = args[parameter::keyword<Tag>::get()] * args[weight] - this->compensation;\r\n            const weighted_sample myTmp2 = this->weighted_sum_ + myTmp1;\r\n            this->compensation = (myTmp2 - this->weighted_sum_) - myTmp1;\r\n            this->weighted_sum_ = myTmp2;\r\n\r\n        }\r\n\r\n        result_type result(dont_care) const\r\n        {\r\n            return this->weighted_sum_;\r\n        }\r\n\r\n    private:\r\n        weighted_sample weighted_sum_;\r\n        weighted_sample compensation;\r\n    };\r\n\r\n#if _MSC_VER > 1400\r\n# pragma float_control(pop)\r\n#endif\r\n\r\n} // namespace impl\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// tag::weighted_sum_kahan\r\n// tag::weighted_sum_of_variates_kahan\r\n//\r\nnamespace tag\r\n{\r\n    struct weighted_sum_kahan\r\n      : depends_on<>\r\n    {\r\n        /// INTERNAL ONLY\r\n        ///\r\n        typedef accumulators::impl::weighted_sum_kahan_impl<mpl::_1, mpl::_2, tag::sample> impl;\r\n    };\r\n\r\n    template<typename VariateType, typename VariateTag>\r\n    struct weighted_sum_of_variates_kahan\r\n      : depends_on<>\r\n    {\r\n        /// INTERNAL ONLY\r\n        ///\r\n        typedef accumulators::impl::weighted_sum_kahan_impl<VariateType, mpl::_2, VariateTag> impl;\r\n    };\r\n\r\n}\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// extract::weighted_sum_kahan\r\n// extract::weighted_sum_of_variates_kahan\r\n//\r\nnamespace extract\r\n{\r\n    extractor<tag::weighted_sum_kahan> const weighted_sum_kahan = {};\r\n    extractor<tag::abstract_weighted_sum_of_variates> const weighted_sum_of_variates_kahan = {};\r\n\r\n    BOOST_ACCUMULATORS_IGNORE_GLOBAL(weighted_sum_kahan)\r\n    BOOST_ACCUMULATORS_IGNORE_GLOBAL(weighted_sum_of_variates_kahan)\r\n}\r\n\r\nusing extract::weighted_sum_kahan;\r\nusing extract::weighted_sum_of_variates_kahan;\r\n\r\n// weighted_sum(kahan) -> weighted_sum_kahan\r\ntemplate<>\r\nstruct as_feature<tag::weighted_sum(kahan)>\r\n{\r\n    typedef tag::weighted_sum_kahan type;\r\n};\r\n\r\ntemplate<typename VariateType, typename VariateTag>\r\nstruct feature_of<tag::weighted_sum_of_variates_kahan<VariateType, VariateTag> >\r\n  : feature_of<tag::abstract_weighted_sum_of_variates>\r\n{\r\n};\r\n\r\n}} // namespace boost::accumulators\r\n\r\n#endif\r\n", "meta": {"hexsha": "ca716cf4352e5a550f0adab9404a5edb7fc592be", "size": 4460, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "trunk/win/Source/Includes/Boost/accumulators/statistics/weighted_sum_kahan.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/accumulators/statistics/weighted_sum_kahan.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/accumulators/statistics/weighted_sum_kahan.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": 32.0863309353, "max_line_length": 117, "alphanum_fraction": 0.6504484305, "num_tokens": 966, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4855138590343662}}
{"text": "\n#include \"cloud_math.h\"\n#include <algorithm>\n\n#define EIGEN_YES_I_KNOW_SPARSE_MODULE_IS_NOT_STABLE_YET\n#include <Eigen/Eigen>\n#include <Eigen/Sparse>\n\n#define LOG1(message)\n\nnamespace Cloud\n{\n\n//----( random numbers )------------------------------------------------------\n\nvoid randomize (Vector<float> x, float sigma)\n{\n  const size_t x_size = x.size;\n  float * restrict x_data = x.data;\n\n  for (size_t i = 0; i < x_size; ++i) {\n    x_data[i] = sigma * random_std();\n  }\n}\n\nsize_t random_index (const Vector<float> & likes)\n{\n  float total = sum(likes);\n  ASSERT_LT(0, total);\n\n  while (true) {\n    float t = random_unif(0, total);\n\n    for (int i = 0, I = likes.size; i < I; ++i) {\n\n      t -= likes[i];\n      if (t < 0) return i;\n    }\n  }\n}\n\nsize_t random_index (const VectorXf & likes)\n{\n  float total = likes.sum();\n  ASSERT_LT(0, total);\n\n  while (true) {\n    float t = random_unif(0, total);\n\n    for (int i = 0, I = likes.size(); i < I; ++i) {\n\n      t -= likes(i);\n      if (t < 0) return i;\n    }\n  }\n}\n\nint random_index (const VectorSf & likes)\n{\n  float total = likes.sum();\n  ASSERT_LT(0, total);\n\n  while (true) {\n    float t = random_unif(0, total);\n\n    for (VectorSf::InnerIterator iter(likes); iter; ++iter) {\n\n      t -= iter.value();\n      if (t < 0) return iter.index();\n    }\n  }\n}\n\nvoid generate_noise (Vector<int8_t> & noise, float sigma)\n{\n  const float quantization_correction = 1 / 6.0f;\n  sigma = sqrtf(sqr(sigma) + quantization_correction);\n\n  for (size_t i = 0, I = noise.size; i < I; ++i) {\n    noise[i] = roundi(sigma * random_std());\n  }\n}\n\n//----( normalization )-------------------------------------------------------\n\nvoid normalize_l1 (VectorXf & x, float tot) { x *= tot / x.sum(); }\nvoid normalize_l1 (VectorSf & x, float tot) { x *= tot / x.sum(); }\nvoid normalize_l1 (MatrixXf & x, float tot) { x *= tot / x.sum(); }\nvoid normalize_l1 (MatrixSf & x, float tot) { x *= tot / x.sum(); }\n\nvoid normalize_rows_l1 (size_t I, size_t J, Vector<float> & A)\n{\n  for (size_t i = 0; i < I; ++i) {\n\n    Vector<float> row = A.block(J, i);\n\n    row /= sum(row);\n  }\n}\n\nvoid normalize_columns_l1 (MatrixXf & A)\n{\n  const int I = A.rows();\n  const int J = A.cols();\n\n  for (int j = 0; j < J; ++j) {\n\n    Vector<float> col(I, & A.coeffRef(0,j));\n\n    col /= sum(col);\n  }\n}\n\nvoid normalize_columns_l1 (MatrixXd & A)\n{\n  const int I = A.rows();\n  const int J = A.cols();\n\n  for (int j = 0; j < J; ++j) {\n\n    Vector<double> col(I, & A.coeffRef(0,j));\n\n    col /= sum(col);\n  }\n}\n\nvoid normalize_columns_l1 (MatrixSf & A)\n{\n  // WARNING this assumes column-major ordering\n\n  for (int i = 0; i < A.outerSize(); ++i) {\n    A.col(i) *= 1.0f / A.col(i).sum();\n  }\n}\n\n//----( sparse tools )--------------------------------------------------------\n\ndouble density (const VectorXf & x)\n{\n  const size_t I = x.size();\n\n  double sum_x1 = 0;\n  double sum_x2 = 0;\n\n  const float * restrict x_ = x.data();\n\n  for (size_t i = 0; i < I; ++i) {\n    double xi = x_[i];\n\n    sum_x1 += max(-xi,xi);\n    sum_x2 += xi * xi;\n  }\n\n  return sqr(sum_x1) / sum_x2 / I;\n}\n\nfloat density (const VectorSf & x)\n{\n  float sum_x1 = 0;\n  float sum_x2 = 0;\n\n  for (VectorSf::InnerIterator iter(x); iter; ++iter) {\n    float xi = iter.value();\n\n    sum_x1 += max(-xi,xi);\n    sum_x2 += xi * xi;\n  }\n\n  return sqr(sum_x1) / sum_x2 / x.size();\n}\n\ndouble density (const MatrixXf & x)\n{\n  const size_t I = x.rows() * x.cols();\n\n  double sum_x1 = 0;\n  double sum_x2 = 0;\n\n  const float * restrict x_ = x.data();\n\n  for (size_t i = 0; i < I; ++i) {\n    double xi = x_[i];\n\n    sum_x1 += max(-xi,xi);\n    sum_x2 += xi * xi;\n  }\n\n  return sqr(sum_x1) / sum_x2 / I;\n}\n\ndouble density (const MatrixSf & x)\n{\n  double sum_x1 = 0;\n  double sum_x2 = 0;\n\n  for (int i = 0; i < x.outerSize(); ++i) {\n    for (MatrixSf::InnerIterator iter(x,i); iter; ++iter) {\n      double xi = iter.value();\n\n      sum_x1 += max(-xi,xi);\n      sum_x2 += xi * xi;\n    }\n  }\n\n  return sqr(sum_x1) / sum_x2 / x.size();\n}\n\nnamespace {\nstruct SparseVectorEntry\n{\n  float value;\n  int index;\n\n  SparseVectorEntry () {}\n  SparseVectorEntry (float v, int i) : value(v), index(i) {}\n\n  bool operator< (const SparseVectorEntry & other) const\n  {\n    return value > other.value;\n  }\n};\nstruct SparseMatrixEntry\n{\n  float value;\n  int row;\n  int col;\n\n  SparseMatrixEntry () {}\n  SparseMatrixEntry (float v, int i, int j) : value(v), row(i), col(j) {}\n\n  bool operator< (const SparseMatrixEntry & other) const\n  {\n    return value > other.value;\n  }\n};\n} // anonymous namespace\n\nfloat sparsify_size (VectorSf & sparse, int size)\n{\n  ASSERT_LT(0, size);\n  ASSERT_LT(size, sparse.nonZeros());\n\n  static std::vector<SparseVectorEntry> entries;\n\n  for (VectorSf::InnerIterator iter(sparse); iter; ++iter) {\n    entries.push_back(SparseVectorEntry(iter.value(), iter.index()));\n  }\n\n  std::nth_element(entries.begin(), entries.begin() + size, entries.end());\n\n  VectorSf sparser(sparse.size());\n  sparser.reserve(size);\n\n  for (int e = 0; e < size; ++e) {\n    const SparseVectorEntry & entry = entries[e];\n    sparser.insert(entry.index) = entry.value;\n  }\n\n  sparser.finalize();\n  entries.clear();\n\n  std::swap(sparse, sparser);\n\n  return sparser.sum() - sparse.sum();\n}\n\nfloat sparsify_size (MatrixSf & sparse, int size)\n{\n  ASSERT_LT(0, size);\n  ASSERT_LT(size, sparse.nonZeros());\n\n  LOG(\"sparsifying \" << sparse.rows() << \" x \" << sparse.cols()\n      << \" matrix from \" << sparse.nonZeros() << \" to \" << size << \" entries\");\n\n  static std::vector<SparseMatrixEntry> entries;\n\n  for (int i = 0; i < sparse.outerSize(); ++i) {\n    for (MatrixSf::InnerIterator iter(sparse,i); iter; ++iter) {\n      entries.push_back(\n          SparseMatrixEntry(iter.value(), iter.row(), iter.col()));\n    }\n  }\n\n  std::nth_element(entries.begin(), entries.begin() + size, entries.end());\n\n  MatrixSf sparser(sparse.rows(), sparse.cols());\n  sparser.reserve(size);\n\n  for (int e = 0; e < size; ++e) {\n    const SparseMatrixEntry & entry = entries[e];\n    sparser.insert(entry.row, entry.col) = entry.value;\n  }\n\n  sparser.finalize();\n  entries.clear();\n\n  std::swap(sparse, sparser);\n\n  float old_sum = sparser.sum();\n  float new_sum = sparse.sum();\n  float loss = (old_sum - new_sum) / old_sum;\n  float density = float(size) / sparser.nonZeros();\n  LOG(\"sparsifying to density \" << density\n      << \" loses \" << (loss*100) << \"% of mass\");\n\n  return old_sum - new_sum;\n}\n\nfloat sparsify_absolute (\n    const VectorXf & dense,\n    VectorSf & sparse,\n    float thresh)\n{\n  ASSERT_LE(0, thresh);\n\n  const int I = dense.size();\n\n  sparse.resize(I);\n\n  float loss = 0;\n\n  for (int i = 0; i < I; ++i) {\n\n    const float dense_i = dense(i);\n    const float abs_i = fabsf(dense_i);\n\n    if (abs_i > thresh) sparse.insert(i) = dense_i;\n    else loss += abs_i;\n  }\n\n  sparse.finalize();\n\n  return loss;\n}\n\nfloat sparsify_absolute (\n    const VectorSf & sparse,\n    VectorSf & sparser,\n    float thresh)\n{\n  ASSERT_LE(0, thresh);\n\n  sparser.resize(sparse.size());\n\n  float loss = 0;\n\n  for (VectorSf::InnerIterator iter(sparse); iter; ++iter) {\n\n    const float value_i = iter.value();\n    const float abs_i = fabsf(value_i);\n\n    if (abs_i > thresh) sparser.insert(iter.index()) = value_i;\n    else loss += abs_i;\n  }\n\n  sparser.finalize();\n\n  return loss;\n}\n\nfloat sparsify_absolute (\n    const VectorXf & dense,\n    VectorSf & sparse,\n    const Vector<float> & thresh)\n{\n  ASSERT1_LE(0, min(thresh));\n\n  const int I = dense.size();\n\n  sparse.resize(I);\n\n  float loss = 0;\n\n  for (int i = 0; i < I; ++i) {\n\n    const float dense_i = dense(i);\n    const float abs_i = fabsf(dense_i);\n\n    if (abs_i > thresh[i]) sparse.insert(i) = dense_i;\n    else loss += abs_i;\n  }\n\n  sparse.finalize();\n\n  return loss;\n}\n\nvoid sparsify_absolute (const MatrixXf & dense, MatrixSf & sparse, float thresh)\n{\n  ASSERT_LE(0, thresh);\n\n  LOG(\"sparsifying \" << dense.rows() << \" x \" << dense.cols()\n      << \" matrix to threshold \" << thresh);\n\n  const int I = dense.rows();\n  const int J = dense.cols();\n\n  sparse.resize(I,J);\n\n  double sum_dense = 0;\n  double sum_sparse = 0;\n\n  for (int j = 0; j < J; ++j) {\n    for (int i = 0; i < I; ++i) {\n\n      const float dense_ij = dense(i,j);\n      const float abs_ij = fabsf(dense_ij);\n      sum_dense += abs_ij;\n\n      if (abs_ij > thresh) {\n\n        sparse.insert(i,j) = dense_ij;\n        sum_sparse += abs_ij;\n      }\n    }\n  }\n\n  sparse.finalize();\n\n  float density = sparse.nonZeros() / float(I * J);\n  float loss = (sum_dense - sum_sparse) / sum_dense;\n  LOG(\"sparsifying to density \" << density\n      << \" loses \" << (100 * loss) << \"% of mass\");\n}\n\nvoid sparsify_soft_relative_to_row_col_max (\n    const MatrixXf & dense,\n    MatrixSf & sparse,\n    float relthresh,\n    bool ignore_diagonal)\n{\n  ASSERT_LT(0, relthresh);\n\n  LOG(\"sparsifying \" << dense.rows() << \" x \" << dense.cols()\n      << \" positive matrix to relative threshold \" << relthresh);\n\n  VectorXf row_max;\n  VectorXf col_max;\n\n  if (ignore_diagonal) {\n\n    VectorXf diag = dense.diagonal();\n    const_cast<MatrixXf &>(dense).diagonal().setZero();\n\n    row_max = dense.rowwise().maxCoeff();\n    col_max = dense.colwise().maxCoeff();\n\n    const_cast<MatrixXf &>(dense).diagonal() = diag;\n\n  } else {\n\n    row_max = dense.rowwise().maxCoeff();\n    col_max = dense.colwise().maxCoeff();\n\n  }\n\n  const int I = dense.rows();\n  const int J = dense.cols();\n\n  sparse.resize(I,J);\n\n  double sum_dense = 0;\n  double sum_sparse = 0;\n\n  for (int j = 0; j < J; ++j) {\n    for (int i = 0; i < I; ++i) {\n\n      const float dense_ij = dense(i,j);\n      sum_dense += dense_ij;\n\n      const float thresh = relthresh * min(row_max(i), col_max(j));\n      if (dense_ij > thresh) {\n\n        sparse.insert(i,j) = dense_ij;\n        sum_sparse += dense_ij;\n      }\n    }\n  }\n\n  sparse.finalize();\n\n  float density = sparse.nonZeros() / float(I * J);\n  float loss = (sum_dense - sum_sparse) / sum_dense;\n  LOG(\"sparsifying to density \" << density\n      << \" loses \" << (100 * loss) << \"% of mass\");\n}\n\nfloat max_entries_heuristic (MatrixXf & dense)\n{\n  int N = dense.rows() + dense.cols();\n  return N * log2f(N);\n}\n\nvoid sparsify_hard_relative_to_row_col_max (\n    const MatrixXf & dense,\n    MatrixSf & sparse,\n    float relthresh,\n    int max_entries,\n    bool ignore_diagonal)\n{\n  do {\n    sparsify_soft_relative_to_row_col_max(\n        dense,\n        sparse,\n        relthresh,\n        ignore_diagonal);\n    relthresh *= 1.5f;\n  } while (sparse.nonZeros() > max_entries);\n}\n\n//----( joint probabilities )-------------------------------------------------\n\ndouble likelihood_entropy (const VectorXf & likes)\n{\n  double sum_l = 0;\n  double sum_l_log_l = 0;\n\n  for (size_t i = 0, I = likes.size(); i < I; ++i) {\n\n    float li = likes[i];\n    if (li > 0) {\n\n      sum_l += li;\n      sum_l_log_l += li * log(li);\n    }\n  }\n\n  return log(sum_l) - sum_l_log_l / sum_l;\n}\n\ndouble likelihood_entropy (const VectorSf & likes)\n{\n  double sum_l = 0;\n  double sum_l_log_l = 0;\n\n  for (VectorSf::InnerIterator iter(likes); iter; ++iter) {\n\n    float li = iter.value();\n    if (li > 0) {\n\n      sum_l += li;\n      sum_l_log_l += li * log(li);\n    }\n  }\n\n  return log(sum_l) - sum_l_log_l / sum_l;\n}\n\ndouble likelihood_entropy_rate (const MatrixSf & joint_likes)\n{\n  double sum_L = 0;\n  double sum_L_H = 0;\n\n  for (int i = 0; i < joint_likes.outerSize(); ++i) {\n\n    double sum_l = 0;\n    double sum_l_log_l = 0;\n\n    for (MatrixSf::InnerIterator iter(joint_likes,i); iter; ++iter) {\n\n      float li = iter.value();\n      if (li > 0) {\n\n        sum_l += li;\n        sum_l_log_l += li * log(li);\n      }\n    }\n\n    sum_L += sum_l;\n    sum_L_H += sum_l * log(sum_l) - sum_l_log_l;\n  }\n\n  return sum_L_H / sum_L;\n}\n\ndouble likelihood_mutual_info (const MatrixSf & joint_likes)\n{\n  double sum_lij = 0;\n  double sum_lij_log_lij = 0;\n\n  double sum_li = 0;\n  double sum_li_log_li = 0;\n\n  Vector<double> likes_j(joint_likes.innerSize());\n  likes_j.set(0);\n\n  for (int i = 0; i < joint_likes.outerSize(); ++i) {\n\n    double li = 0;\n\n    for (MatrixSf::InnerIterator iter(joint_likes,i); iter; ++iter) {\n\n      float lij = iter.value();\n      if (lij > 0) {\n\n        sum_lij += lij;\n        sum_lij_log_lij += lij * log(lij);\n\n        li += lij;\n        likes_j[iter.index()] += lij;\n      }\n    }\n\n    if (li > 0) {\n      sum_li += li;\n      sum_li_log_li += li * log(li);\n    }\n  }\n\n  double sum_lj = 0;\n  double sum_lj_log_lj = 0;\n\n  for (size_t j = 0, J = likes_j.size; j < J; ++j) {\n\n    double lj = likes_j[j];\n    if (lj > 0) {\n\n      sum_lj += lj;\n      sum_lj_log_lj += lj * log(lj);\n    }\n  }\n\n  double hij = log(sum_lij) - sum_lij_log_lij / sum_lij;\n  double hi = log(sum_li) - sum_li_log_li / sum_li;\n  double hj = log(sum_lj) - sum_lj_log_lj / sum_lj;\n\n  return hi + hj - hij;\n}\n\nvoid constrain_marginals_bp (\n    MatrixXf & joint,\n    const VectorXf & prior_dom,\n    const VectorXf & prior_cod,\n    VectorXf & temp_dom,\n    VectorXf & temp_cod,\n    float tol,\n    size_t max_steps,\n    bool logging)\n{\n  // Enforce simultaineous constraints on a joint PMF\n  //\n  //   /\\x. sum y. J(y,x) = p(x)\n  //   /\\y. sum x. J(y,x) = q(y)\n\n  ASSERT_EQ(prior_dom.size(), joint.cols());\n  ASSERT_EQ(prior_cod.size(), joint.rows());\n  ASSERT_LT(0, prior_dom.minCoeff());\n  ASSERT_LT(0, prior_cod.minCoeff());\n\n  if (logging) LOG(\"  constraining marginals via full BP\");\n\n  const size_t X = joint.cols();\n  const size_t Y = joint.rows();\n\n  const Vector<float> p = as_vector(prior_dom);\n  const Vector<float> q = as_vector(prior_cod);\n\n  Vector<float> J = as_vector(joint);\n  Vector<float> sum_y_J = as_vector(temp_dom);\n  Vector<float> sum_x_J = as_vector(temp_cod);\n\n  float stepsize = 0;\n  size_t steps = 0;\n  while (steps < max_steps) {\n    ++steps;\n    if (logging) cout << \"   step \" << steps << \"/\" << max_steps << flush;\n\n    stepsize = 0;\n\n    // constrain sum y. J(y,x) = 1 first,\n    // in case joint is initalized with conditional\n\n    for (size_t x = 0; x < X; ++x) {\n      Vector<float> J_x = J.block(Y, x);\n      sum_y_J[x] = sum(J_x);\n    }\n    ASSERT_LT(0, min(sum_y_J)); // XXX error here\n    imax(stepsize, sqrtf(max_dist_squared(sum_y_J, p)));\n    idiv_store_rhs(p, sum_y_J);\n    for (size_t x = 0; x < X; ++x) {\n      Vector<float> J_x = J.block(Y, x);\n      J_x *= sum_y_J[x];\n    }\n\n    sum_x_J.zero();\n    for (size_t x = 0; x < X; ++x) {\n      Vector<float> J_x = J.block(Y, x);\n      sum_x_J += J_x;\n    }\n    ASSERT_LT(0, min(sum_x_J));\n    imax(stepsize, sqrtf(max_dist_squared(sum_x_J, q)));\n    idiv_store_rhs(q, sum_x_J);\n    for (size_t x = 0; x < X; ++x) {\n      Vector<float> J_x = J.block(Y, x);\n      J_x *= sum_x_J;\n    }\n\n    if (logging) LOG(\", stepsize = \" << stepsize);\n    if (stepsize < tol) break;\n  }\n}\n\n//----( distances )-----------------------------------------------------------\n\nfloat squared_distance (const Point & x, const Point & y)\n{\n  ASSERT_EQ(x.size, y.size);\n\n  typedef int Accum;\n\n  const uint8_t * restrict x_data = x.data;\n  const uint8_t * restrict y_data = y.data;\n\n  Accum result = 0;\n  for (size_t i = 0, I = x.size; i < I; ++i) {\n    result += sqr(Accum(x_data[i]) - Accum(y_data[i]));\n  }\n\n  return result;\n}\n\n} // namespace Cloud\n\n", "meta": {"hexsha": "f779ae2ecd7f6ac714a8b640190b063d96ea60c2", "size": 15166, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cloud_math.cpp", "max_stars_repo_name": "fritzo/kazoo", "max_stars_repo_head_hexsha": "7281fe382b98ec81a0e223bfc76c49749543afdb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-04-29T11:38:29.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-31T01:32:13.000Z", "max_issues_repo_path": "src/cloud_math.cpp", "max_issues_repo_name": "fritzo/kazoo", "max_issues_repo_head_hexsha": "7281fe382b98ec81a0e223bfc76c49749543afdb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cloud_math.cpp", "max_forks_repo_name": "fritzo/kazoo", "max_forks_repo_head_hexsha": "7281fe382b98ec81a0e223bfc76c49749543afdb", "max_forks_repo_licenses": ["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.9475138122, "max_line_length": 80, "alphanum_fraction": 0.5838718185, "num_tokens": 4600, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257127, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4855138526676068}}
{"text": "\n#ifndef HEADER_SHAPEMODELTRI\n#define HEADER_SHAPEMODELTRI\n\n#include <string>\n#include <string>\n#include <iostream>\n#include <armadillo>\n#include <set>\n#include <map>\n#include <limits>\n#include <cassert>\n\n\n#include <ShapeUQLib/ShapeModel.hpp>\n#include <ShapeUQLib/Facet.hpp>\n\n\n\n\n/**\nDeclaration of the ShapeModelTri class. Specialized\nimplementation storing an explicit facet/vertex shape model\n*/\ntemplate <class PointType>\nclass ShapeModelTri : public ShapeModel<PointType> {\n\npublic:\n\n\t\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\tShapeModelTri(std::string ref_frame_name,\n\t\tFrameGraph * frame_graph) : ShapeModel<PointType>(ref_frame_name,frame_graph){};\n\n\n\tShapeModelTri(){};\n\n\tShapeModelTri(const std::vector<std::vector<int> > & vertices,\n\t\tconst std::vector<int> & super_elements,\n\t\tconst std::vector<PointType> & control_points);\n\n\n\t/**\n\tDetermines whether the provided point lies inside or outside the shape model.\n\tThe shape model must have a closed surface for this method to be trusted\n\t@param point coordinates of the point to be tested expressed in the shape model frame\n\t@param tol numerical tolerance ,i.e value under which the lagrangian of the \"surface field\"\n\t\tbelow which the point is considered outside\n\t@return true if point is contained inside the shape, false otherwise\n\t*/\n\tbool contains(double * point, double tol = 1e-6) ;\n\n\n\t/**\n\tChecks that the normals were consistently oriented. If not,\n\tthe ordering of the vertices in the provided shape model file is incorrect\n\t@param tol numerical tolerance (if consistent: norm(Sum(oriented_surface_area)) / average_facet_surface_area << tol)\n\t*/\n\tvoid check_normals_consistency(double tol = 1e-3) const;\n\n\n\n\t/**\n\tSaves the shape model in the form of an .obj file\n\t@param path Location of the saved file\n\t@param X translation component to apply\n\t@param M rotational component to apply\n\t*/\n\tvoid save(std::string path,\n\t\tconst arma::vec & X = arma::zeros<arma::vec>(3),\n\t\tconst arma::mat & M = arma::eye<arma::mat>(3,3)) const;\n\n\t/**\n\tSamples N points over each facet of the shape model\n\t@param N number of samples per facet\n\t@param points reference to matrix holding points coordinates\n\t@param normals reference to matrix holding normals coordinates\n\t*/\n\tvoid random_sampling(unsigned int N,arma::mat & points, arma::mat & normals) const;\n\n\tvirtual unsigned int get_NElements() const;\n\n\t/**\n\tUpdates the values of the center of mass, volume, surface area\n\t*/\n\tvirtual void update_mass_properties();\n\n\t/**\n\tUpdate all the facets of the shape model\n\t*/\n\tvoid update_facets() ;\n\n\tvoid add_element(Facet & el);\n\tvoid set_elements(std::vector<Facet> elements);\n\n\n\tvirtual void clear();\n\n\n\n\n\t/**\n\tUpdates the specified facets of the shape model. Ensures consistency between the vertex coordinates\n\tand the facet surface area, normals and centers.\n\t@param facets Facets to be updated\n\t@param compute_dyad true if the facet dyad needs to be computed/updated\n\t*/\n\tvoid update_facets(std::set<Facet *> & facets);\n\n\n\t\n\n\t/**\n\tComputes the surface area of the shape model\n\t*/\n\tvirtual void compute_surface_area();\n\t/**\n\tComputes the volume of the shape model\n\t*/\n\tvirtual void compute_volume();\n\t/**\n\tComputes the center of mass of the shape model\n\t*/\n\tvirtual void compute_center_of_mass();\n\t/**\n\tComputes the inertia tensor of the shape model\n\t*/\n\tvirtual void compute_inertia();\n\n\n\tFacet & get_element(int e);\n\n\n\tvirtual const std::vector<int> & get_element_control_points(int e) const;\n\tvirtual arma::vec::fixed<3> get_point_normal_coordinates(unsigned int i) const;\n\n\n\n\nprotected:\n\t\n\tstd::vector<Facet> elements;\n\n\n\n};\n\n#endif", "meta": {"hexsha": "163f37831677f4d6ad5468197855f497634c0595", "size": 3704, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ShapeUQLib/ShapeModelTri.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/ShapeModelTri.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/ShapeModelTri.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": 24.2091503268, "max_line_length": 117, "alphanum_fraction": 0.7478401728, "num_tokens": 860, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6224593171945416, "lm_q1q2_score": 0.4855138481087615}}
{"text": "#include \"LITD_VirtualCar.h\"\n#include \"LITD_VirtualPoint.h\"\n#include \"math_utilities.h\"\n#include <Eigen/Dense>\n\n#include <stdio.h>\n#include <unistd.h>\n#include <iostream>\n\nLITD_VirtualCar::LITD_VirtualCar()\n{\n    carPosition.x = 0.0;\n    carPosition.y = -0.2;\n    carPosition.h = 0.0;\n    carSpeed = 0.0;\n\n    stanleyGain = 1.5;\n    vKp = 0.1;\n    vKi =0.5;\n\n    vpOld.x = carPosition.x;\n    vpOld.y = carPosition.y;\n    vIntegrate = 0.0;\n}\n\ndouble LITD_VirtualCar::getActSpeed(LITD_VirtualPoint vp, double dtime){\n    double distance = (carPosition.getVector2d() - vpOld.getVector2d()).norm();\n    std::cout << \"Distance : \" << distance << std::endl;\n    vpOld = carPosition;\n    double actSpeed = distance / dtime;\n    return actSpeed;\n}\n\nvoid LITD_VirtualCar::speedRegulator(LITD_VirtualPoint vp, double dtime){\n    double actSpeed = getActSpeed(vp, dtime);\n    double diff = vp.speed - actSpeed;\n    vIntegrate += diff;\n\n    carSpeed = vKp * diff + vKi * dtime * vIntegrate;\n\n    std::cout << \"-----------------------\" << std::endl;\n    std::cout << \"Vp speed : \" << vp.speed << std::endl;\n    std::cout << \"Act Speed : \" << actSpeed << std::endl;\n    std::cout << \"Speed_diff : \" << diff << std::endl;\n    std::cout << \"Integrate val: \" << vIntegrate << std::endl;\n    std::cout << \"carspeed: \" << carSpeed  << std::endl;\n    std::cout << \"-----------------------\" << std::endl;\n}\n\n//Params: position of otpimum point, delta time step\n//returns the new position of the car after dtime\nLITD_VirtualPoint LITD_VirtualCar::updateStep(LITD_VirtualPoint vp, double dtime)\n{\n\n    \n\n    double rad2degree = 180.0 / M_PI; \n    //vector between car and virtualpoint\n    Vector2d diff = vp.getVector2d() - carPosition.getVector2d();\n\n    //calc sign to steer in direction of road\n    int sign = 1;\n    double diff_heading_abs = wrapTo2Pi(atan2(diff(1), diff(0)));\n    if(wrapTo2Pi(diff_heading_abs - wrapTo2Pi(vp.h))> 4.712 ){\n        sign = -1;\n    }\n    //calc new direction\n\n    //calc normal distance of tangent to car (e)\n    e = (vp.getVector2d() - carPosition.getVector2d()).norm() * sign;\n\n    //calc angle between car heading and point tangent\n    theta_c =  wrapTo2Pi(vp.h) - wrapTo2Pi(carPosition.h);\n\n    //calc steering-angle with stanley-approach\n    carSteeringAngle = theta_c + atan2(stanleyGain*e, carSpeed);\n\n    //Debug Messages\n    std::cout << \"-----------------------\" << std::endl;\n    std::cout << \"point heading : \" << vp.h << \"(\" << rad2degree * vp.h << \"\u00b0)\" << std::endl;\n    std::cout << \"car heading: \" << carPosition.h << \"(\" << rad2degree * carPosition.h << \"\u00b0)\" << std::endl;\n    std::cout << \"diff heading: \" << diff_heading_abs << \"(\" << rad2degree * diff_heading_abs << \"\u00b0)\" << std::endl;\n    std::cout << \"e: \" << e << std::endl;\n    std::cout << \"Theta_C: \" << theta_c << \"(\" << rad2degree * theta_c << \"\u00b0)\" << std::endl;\n    \n    \n\n    for (int i=0; i<SIM_STEPS; i++){\n    \n        std::cout << \"h: \" << carPosition.h << std::endl;\n        carPosition.h += tan(carSteeringAngle)/CAR_AXIS_DIST * carSpeed * dtime/SIM_STEPS;\n        carPosition.x += cos(carPosition.h) * carSpeed * dtime/SIM_STEPS;\n        carPosition.y += sin(carPosition.h) * carSpeed * dtime/SIM_STEPS;\n    }\n\n    std::cout << \"new car pos x: \" << carPosition.x << std::endl;\n    std::cout << \"new car pos y: \" << carPosition.y << std::endl;\n    std::cout << \"-----------------------\" << std::endl;\n \n speedRegulator(vp, dtime);\n    //calc next point of front axis\n    LITD_VirtualPoint newFrontAxisPoint;\n    //newFrontAxisPoint.x = carPosition.x+ cos(theta_c) * carSpeed  * dtime;\n    //newFrontAxisPoint.y = carPosition.y + sin(theta_c) * carSpeed * dtime;\n    //newFrontAxisPoint.h = tan(carSteeringAngle) / (CAR_AXIS_DIST);\n\n    //carPosition = newFrontAxisPoint;\n\n\n\n}\n", "meta": {"hexsha": "ca71ef3b665d9cfde8452b04b806fe11d908e5b8", "size": 3775, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/aadcUser/controlTest/LITD_VirtualCar.cpp", "max_stars_repo_name": "LITdrive/aadc2018", "max_stars_repo_head_hexsha": "93ce64286eef7eedd9e886da8c685f12827e396f", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-11-13T01:40:20.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-22T12:25:38.000Z", "max_issues_repo_path": "src/aadcUser/controlTest/LITD_VirtualCar.cpp", "max_issues_repo_name": "LITdrive/aadc2018", "max_issues_repo_head_hexsha": "93ce64286eef7eedd9e886da8c685f12827e396f", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/aadcUser/controlTest/LITD_VirtualCar.cpp", "max_forks_repo_name": "LITdrive/aadc2018", "max_forks_repo_head_hexsha": "93ce64286eef7eedd9e886da8c685f12827e396f", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-12-28T02:19:44.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-28T02:19:44.000Z", "avg_line_length": 33.7053571429, "max_line_length": 115, "alphanum_fraction": 0.6076821192, "num_tokens": 1143, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683105, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.48548756308136204}}
{"text": "#include \"system/CameraModel.h\"\n#include \"system/DsoSystem.h\"\n#include \"util/types.h\"\n#include <Eigen/Core>\n#include <gtest/gtest.h>\n\nusing namespace fishdso;\n\nTEST(CameraModelTest, CoreanCameraReprojection) {\n  // some real-world data\n  double scale = 604.0;\n  Vec2 center(1.58492, 1.07424);\n  int unmapPolyDeg = 5;\n  VecX unmapPolyCoeffs(unmapPolyDeg, 1);\n  unmapPolyCoeffs << 1.14169, -0.203229, -0.362134, 0.351011, -0.147191;\n  int width = 1920, height = 1208;\n  CameraModel cam(width, height, scale, center, unmapPolyCoeffs);\n\n  std::srand(42);\n  const int testnum = 2000;\n  double sqErr = 0.0;\n\n  for (int i = 0; i < testnum; ++i) {\n    Vec2 pnt(double(rand() % width), double(rand() % height));\n    Vec3 ray = cam.unmap(pnt.data());\n    ray *= 10.5;\n\n    Vec2 pntBack = cam.map(ray.data());\n    sqErr += (pnt - pntBack).squaredNorm();\n  }\n\n  double rmse = std::sqrt(sqErr / testnum); // rmse in pixels\n  std::cout << \"reprojection rmse = \" << rmse << std::endl;\n  EXPECT_LT(rmse, 0.1);\n}\n\nTEST(CameraModelTest, SolelyPolynomial) {\n  // here camera is initialised so that its mapping only inverses the given\n  // polynomial\n  double scale = 1;\n  Vec2 center(0.0, 0.0);\n  int unmapPolyDeg = 2;\n  VecX unmapPolyCoefs(unmapPolyDeg, 1);\n  unmapPolyCoefs << 1.0, -1.0;\n  int width = 2, height = 0;\n  CameraModel cam(width, height, scale, center, unmapPolyCoefs);\n\n  std::srand(43);\n  const int testnum = 2000;\n  double sqErr = 0.0;\n  for (int i = 0; i < testnum; ++i) {\n    double x = double(std::rand()) / RAND_MAX;\n    Vec3 pnt(x, 0, 1 - x * x);\n    Vec2 projected = cam.map(pnt.data());\n    sqErr += (projected - Vec2(x, 0)).squaredNorm();\n  }\n  double rmse = std::sqrt(sqErr / testnum);\n  std::cout << \"rmse = \" << rmse << std::endl;\n  EXPECT_LT(rmse, 0.0005);\n}\n\nTEST(CameraModelTest, CamerasPyramid) {\n  double scale = 604.0;\n  Vec2 center(1.58447, 1.07353);\n  int unmapPolyDeg = 7;\n  int pyrLevels = 6;\n  VecX unmapPolyCoeffs(unmapPolyDeg, 1);\n  unmapPolyCoeffs << 1.14544, -0.146714, -0.967996, 2.13329, -2.42001, 1.33018,\n      -0.292722;\n  int width = 1920, height = 1208;\n  CameraModel cam(width, height, scale, center, unmapPolyCoeffs);\n  StdVector<CameraModel> camPyr = cam.camPyr(pyrLevels);\n\n  std::mt19937 mt;\n  std::uniform_real_distribution<> xs(0, width - 1);\n  std::uniform_real_distribution<> ys(0, height - 1);\n\n  const int testCount = 1000;\n  for (int lvl = 0; lvl < pyrLevels; ++lvl)\n    for (int it = 0; it < testCount; ++it) {\n      double x = xs(mt), y = ys(mt);\n      Vec2 pnt(x, y);\n      Vec2 pntScaled(x / (1 << lvl), y / (1 << lvl));\n      Vec3 unmapOrig = cam.unmap(pnt).normalized();\n      Vec3 unmapPyr = camPyr[lvl].unmap(pntScaled).normalized();\n      double cos = unmapOrig.dot(unmapPyr);\n      if (cos < -1)\n        cos = -1;\n      if (cos > 1)\n        cos = 1;\n      double angle = (180.0 / M_PI) * std::acos(cos);\n      EXPECT_LT(angle, 0.01);\n    }\n}\n\nint main(int argc, char **argv) {\n  ::testing::InitGoogleTest(&argc, argv);\n  return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "c9f29fd66aa8ab6c8294df74534bc81373b73866", "size": 3000, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_cameramodel.cpp", "max_stars_repo_name": "MikhailTerekhov/mdso", "max_stars_repo_head_hexsha": "e032083bc6da6548718a5d222ec4016189ec2dc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2020-09-11T11:27:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T02:12:07.000Z", "max_issues_repo_path": "test/test_cameramodel.cpp", "max_issues_repo_name": "MikhailTerekhov/mdso", "max_issues_repo_head_hexsha": "e032083bc6da6548718a5d222ec4016189ec2dc8", "max_issues_repo_licenses": ["MIT"], "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_cameramodel.cpp", "max_forks_repo_name": "MikhailTerekhov/mdso", "max_forks_repo_head_hexsha": "e032083bc6da6548718a5d222ec4016189ec2dc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-09-11T19:52:59.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-11T19:52:59.000Z", "avg_line_length": 30.0, "max_line_length": 79, "alphanum_fraction": 0.631, "num_tokens": 1057, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.4854702552330544}}
{"text": "extern \"C\" {\n    #include <vlfeat/fisher.h>\n    #include <vlfeat/gmm.h>\n}\n\n#include <Eigen/Core>\n#include <glog/logging.h>\n#include <memory>\n#include <vector>\n\n#include \"fisher_vector_extractor.h\"\n\nnamespace GraphSfM {\nnamespace feature {\nEigen::MatrixXf ConvertVectorOfFeaturesToMatrix(const std::vector<Eigen::VectorXf>& features) \n{\n    Eigen::MatrixXf feature_table(features[0].size(), features.size());\n    for (int i = 0; i < feature_table.cols(); i++) {\n        feature_table.col(i) = features[i];\n    }\n    return feature_table;\n}\n\nFisherVectorExtractor::FisherVectorExtractor(const Options& options)\n    : gmm_(new GaussianMixtureModel(options.num_gmm_clusters)),\n      training_feature_sampler_(options.max_num_features_for_training) \n{\n\n}\n\nFisherVectorExtractor::~FisherVectorExtractor() \n{\n\n}\n\nvoid FisherVectorExtractor::AddFeaturesForTraining(const std::vector<Eigen::VectorXf>& features) \n{\n    for (const Eigen::VectorXf& feature : features) {\n      CHECK(!feature.hasNaN()) << \"Feature: \" << feature.transpose();\n      training_feature_sampler_.AddElementToSampler(feature);\n    }\n}\n\nbool FisherVectorExtractor::Train() \n{\n    // Get the features randomly sampled for training.\n    const auto& sampled_features = training_feature_sampler_.GetAllSamples();\n    CHECK_GT(sampled_features.size(), 0);\n    LOG(INFO) << \"Training GMM for Fisher Vector extractin with \"\n              << sampled_features.size() << \" features sampled from \"\n              << training_feature_sampler_.NumElementsAdded()\n              << \" total features.\";    \n    // Train the GMM using the training feaures.\n    const Eigen::MatrixXf feature_table = ConvertVectorOfFeaturesToMatrix(sampled_features);\n    return gmm_->Compute(feature_table);\n}\n\nEigen::VectorXf \nFisherVectorExtractor::ExtractGlobalDescriptor(const std::vector<Eigen::VectorXf>& features) \n{\n    // Ensure there are input features and they are not zero dimensions.\n    CHECK_GT(features.size(), 0);\n    CHECK_GT(features[0].size(), 0);    \n    // Convert the features into a continuous memory block. The matrix is of size\n    // D x N where D is the number of descrip\n    const Eigen::MatrixXf feature_table = ConvertVectorOfFeaturesToMatrix(features);\n    // Compute the fisher vector encoding.\n    Eigen::VectorXf fisher_vector(2 * feature_table.rows() * gmm_->num_clusters());\n    vl_fisher_encode(fisher_vector.data(),\n                     VL_TYPE_FLOAT,\n                     gmm_->GetMeans(),\n                     feature_table.rows(),\n                     gmm_->num_clusters(),\n                     gmm_->GetCovariances(),\n                     gmm_->GetPriors(),\n                     feature_table.data(),\n                     feature_table.cols(),\n                     VL_FISHER_FLAG_IMPROVED);\n    DCHECK(std::isfinite(fisher_vector.sum()));\n    return fisher_vector;\n}\n\nvoid FisherVectorExtractor::ExportGaussianMixtureModel(std::string filename)\n{\n    size_t dimension = gmm_->GetDimension();\n    size_t num_clusters = gmm_->GetNumClusters();\n    float const *means = (float const *)gmm_->GetMeans();\n    float const *covariances = (float const *)gmm_->GetCovariances();\n    float const *priors = (float const *)gmm_->GetPriors();\n\n    std::ofstream out(filename);\n    if (!out.is_open()) {\n        LOG(ERROR) << filename << \" cannot be created!\";\n        return;\n    }\n    out << dimension << \" \" << num_clusters << std::endl;\n\n    for (int i = 0; i < dimension * num_clusters; i++) {\n        out << means[i] << \" \";\n    }\n    out << std::endl;\n\n    for (int i = 0; i < dimension * num_clusters; i++) {\n        out << covariances[i] << \" \";\n    }\n    out << std::endl;\n\n    for (int i = 0;  i < num_clusters; i++) {\n        out << priors[i] << \" \";\n    }\n    out << std::endl;\n    out.close();\n}\n\nvoid FisherVectorExtractor::ImportGaussianMixtureModel(std::string filename)\n{\n    std::ifstream in(filename);\n    if (!in.is_open()) {\n        LOG(ERROR) << filename << \" cannot be created!\";\n    }\n    \n    size_t dimension, num_clusters;\n    float *means = new float [dimension * num_clusters];\n    float *covariances = new float [dimension * num_clusters];\n    float *priors = new float [num_clusters];\n\n    in >> dimension >> num_clusters;\n\n    for (int i = 0; i < dimension * num_clusters; i++) {\n        in >> means[i];\n    }\n    for (int i = 0; i < dimension * num_clusters; i++) {\n        in >> covariances[i];\n    }\n    for (int i = 0; i < num_clusters; i++) {\n        in >> priors[i];\n    }\n    in.close();\n\n    // gmm_.reset(vl_gmm_new(VL_TYPE_FLOAT, dimension, num_clusters));\n    if (!gmm_->Init(dimension, num_clusters)) {\n        delete [] means;\n        delete [] covariances;\n        delete [] priors;\n        LOG(ERROR) << \"Gaussian Mixture Model import failed!\";\n        return;\n    }\n    gmm_->SetMeans(means);\n    gmm_->SetCovariances(covariances);\n    gmm_->SetPriors(priors);\n\n    delete [] means;\n    delete [] covariances;\n    delete [] priors;\n}\n\n}  // namespace feature\n}  // namespace GraphSfM\n", "meta": {"hexsha": "e0d801904d27f9a724516b06dc80bab13f26d080", "size": 4991, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/feature/fisher_vector_extractor.cpp", "max_stars_repo_name": "bitlw/EGSfM", "max_stars_repo_head_hexsha": "d5b4260d38237c6bd814648cadcf1fcf2f8f5d31", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 90.0, "max_stars_repo_stars_event_min_datetime": "2019-05-19T03:48:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-02T15:20:49.000Z", "max_issues_repo_path": "src/feature/fisher_vector_extractor.cpp", "max_issues_repo_name": "bitlw/EGSfM", "max_issues_repo_head_hexsha": "d5b4260d38237c6bd814648cadcf1fcf2f8f5d31", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2019-05-22T07:45:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T01:48:26.000Z", "max_forks_repo_path": "src/feature/fisher_vector_extractor.cpp", "max_forks_repo_name": "bitlw/EGSfM", "max_forks_repo_head_hexsha": "d5b4260d38237c6bd814648cadcf1fcf2f8f5d31", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2019-05-19T03:48:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-29T18:19:16.000Z", "avg_line_length": 31.3899371069, "max_line_length": 97, "alphanum_fraction": 0.6315367662, "num_tokens": 1227, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6406358617010351, "lm_q1q2_score": 0.4854702500337235}}
{"text": "/**\n * @author Mike Bogochow\n * @version 2.5.0, Dec 8, 2015\n *\n * @file main.cpp\n *\n * pBidder main\n */\n\n#include \"defs.h\"\n#include \"Path.h\"\n#include \"SpanningTree.h\"\n#include \"Graph.h\"\n\n// boost\n#include <boost/config.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/prim_minimum_spanning_tree.hpp>\n//#include <boost/lexical_cast.hpp>\n#include <boost/graph/graph_utility.hpp>\n\n#include <iostream>\n#include <algorithm> // std::remove\n#include <limits>\n\n//#define _a 0\n//#define _b 1\n//#define _c 2\n//#define _d 3\n//#define _e 4\n//#define _f 5\n//#define _g 6\n//#define _h 7\n//#define _i 8\n\nconst size_t __num_nodes = 9;\nconst size_t __num_edges = 36;\nEdge __edges[__num_edges] = {\n    Edge(_a, _b), Edge(_a, _c), Edge(_a, _d), Edge(_a, _e), Edge(_a, _f), Edge(_a, _g), Edge(_a, _h), Edge(_a, _i),\n    Edge(_b, _c), Edge(_b, _d), Edge(_b, _e), Edge(_b, _f), Edge(_b, _g), Edge(_b, _h), Edge(_b, _i),\n    Edge(_c, _d), Edge(_c, _e), Edge(_c, _f), Edge(_c, _g), Edge(_c, _h), Edge(_c, _i),\n    Edge(_d, _e), Edge(_d, _f), Edge(_d, _g), Edge(_d, _h), Edge(_d, _i),\n    Edge(_e, _f), Edge(_e, _g), Edge(_e, _h), Edge(_e, _i),\n    Edge(_f, _g), Edge(_f, _h), Edge(_f, _i),\n    Edge(_g, _h), Edge(_g, _i),\n    Edge(_h, _i)\n};\nint __weights[__num_edges] = {\n    4,       8,       11,      8,      7,        4,       2,      9,\n    14,      10,      2,       1,      6,        7,       4,\n    8,       11,      8,       7,      4,        2,\n    9,       14,      10,      2,      1,\n    6,       7,       4,       8,\n    11,      8,       7,\n    4,       2,\n    9 };\n\n/**\n * Main\n */\nint main(int argc, char **argv)\n{\n  Graph *g = new Graph(__edges, __num_edges, __weights, __num_nodes);\n//g->print();\n  // TODO add my location to graph\n\n  Graph *sub;\n  std::vector<Vertex> allocated;\n  std::vector<Vertex> unallocated;\n  unallocated.reserve(__num_nodes);\n\n  int rtc = 0; // my cost\n  for (Vertex i = 0; i < __num_nodes; i++)\n    unallocated.push_back(i);\n\n  // each round of bidding\n  for (Vertex i = 0; i < __num_nodes; i++)\n  {\n    std::pair<Vertex, mbogo_weight_t> currentBid = std::make_pair(\n        std::numeric_limits<Vertex>::max(),\n        std::numeric_limits<mbogo_weight_t>::max());\n\n//std::cerr << \"~~~ Round \" << i+1 << std::endl;\n    // each unallocated target\n    for (std::vector<Vertex>::iterator t = unallocated.begin();\n        t != unallocated.end(); t++)\n    {\n      Path *path;\n      SpanningTree *tree;\n      mbogo_weight_t cost;\n      mbogo_weight_t bid;\n      std::vector<Vertex> possibleAllocation;\n\n      possibleAllocation = allocated;\n//std::cerr << \"Adding \" << *t << \" for possible allocation\" << std::endl;\n      possibleAllocation.push_back(*t);\n\n      // Catch simple cases for efficiency\n      if (possibleAllocation.size() == 1)\n      {\n        cost = bid = 0;\n      }\n      else if (possibleAllocation.size() == 2)\n      {\n        path = Path::fromPair(\n            std::make_pair(possibleAllocation.front(),\n                possibleAllocation.back()));\n        cost = path->getTotalCost(g->getGraph());\n        bid = cost - rtc;\n\n        delete path;\n      }\n      else\n      {\n        sub = g->getSubgraph(possibleAllocation);\n//sub->print();\n\n        tree = SpanningTree::fromGraph(sub->getGraph());\n//std::cout << \"Spanning Tree:\" << std::endl;\n//tree->print();\n\n        path = Path::fromTree(tree);\n\n        cost = path->getTotalCost(g->getGraph());//= get_path_cost(g, path); // TODO\n        bid = cost - rtc;\n\n        delete path;\n        delete tree;\n        delete sub;\n      }\n\n//std::cerr << \"bid[\" << i << \"_\" << *t << \"]=\" << bid << \" (cost-rtc)=(\" << cost << \"-\" << rtc << \")\" << std::endl;\n\n      if (currentBid.second > bid && bid >= 0)\n        currentBid = std::make_pair(*t, bid);\n\n//std::cerr << \"cur_bid=\" << currentBid.first << \":\" << currentBid.second << std::endl;\n    }\n\n    // submit current bid\n    // get results\n\n    // if win\n    //   allocated.push_back(winning target);\n    //   unallocated.erase(std::remove(vec.begin(), vec.end(), winning target), vec.end());\n    //   update rtc\n\n    // TODO change\n    int winner = unallocated.front();\n    allocated.push_back(winner);\n    unallocated.erase(std::remove(unallocated.begin(), unallocated.end(), winner), unallocated.end());\n    rtc += currentBid.second;\n  }\n\n  // Do final calculation with allocated nodes\n  sub = g->getSubgraph(allocated);\n  SpanningTree *tree = SpanningTree::fromGraph(sub->getGraph());\n\n  // Output spanning tree\n  std::cout << \"Spanning Tree:\" << std::endl;\n  tree->print();\n\n  // Get the path from the tree\n  Path *path = Path::fromTree(tree);\n  mbogo_weight_t pathCost = path->getTotalCost(g->getGraph());//get_path_cost(g, path);\n\n  // Output the path\n  std::cout << \"Path:\" << std::endl;\n  path->print();\n  std::cerr << \"cost: \" << pathCost << std::endl;\n\n  delete path;\n  delete tree;\n  delete g;\n  delete sub;\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "b31fb8ede7925d877fc7760533c36b14bb28bf57", "size": 4894, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/lib_graphs/prim-example.cpp", "max_stars_repo_name": "mbogochow/proj", "max_stars_repo_head_hexsha": "83e21d11b30da02bd400e65440ddc99d05d04a4a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-04-14T23:17:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-05T16:16:11.000Z", "max_issues_repo_path": "src/lib_graphs/prim-example.cpp", "max_issues_repo_name": "mbogochow/proj", "max_issues_repo_head_hexsha": "83e21d11b30da02bd400e65440ddc99d05d04a4a", "max_issues_repo_licenses": ["MIT"], "max_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_graphs/prim-example.cpp", "max_forks_repo_name": "mbogochow/proj", "max_forks_repo_head_hexsha": "83e21d11b30da02bd400e65440ddc99d05d04a4a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-11-06T03:47:36.000Z", "max_forks_repo_forks_event_max_datetime": "2017-11-06T03:47:36.000Z", "avg_line_length": 27.3407821229, "max_line_length": 116, "alphanum_fraction": 0.5688598284, "num_tokens": 1514, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6406358548398982, "lm_q1q2_score": 0.4854702448343925}}
{"text": "/**\n * Sample host program to generate a sequence\n * using jump and parallel generation.\n *\n * 1. make initial state from a seed\n * 2. calculate initial position for each work group.\n *    (This step is time comsuming)\n * 3. Loop:\n *   3.1 generate sub-sequences parallel\n *   3.2 jump for next loop\n */\n\n#include \"opencl_tools.hpp\"\n#include <cstddef>\n#include <cfloat>\n#include <ctime>\n#include <NTL/GF2X.h>\n#include <NTL/ZZ.h>\n\ntypedef uint32_t uint;\n#include \"mtgp32-calc-poly.hpp\"\n#include \"mtgp-calc-jump.hpp\"\n#include \"mtgp32-fast-jump.h\"\n#include \"mtgp32-sample-common.h\"\n#include \"parse_opt.h\"\n\nusing namespace std;\nusing namespace cl;\nusing namespace NTL;\n\n/* ================== */\n/* OpenCL information */\n/* ================== */\nstd::vector<cl::Platform> platforms;\nstd::vector<cl::Device> devices;\ncl::Context context;\nstd::string programBuffer;\ncl::Program program;\ncl::Program::Sources source;\ncl::CommandQueue queue;\nstd::string errorMessage;\n\n/* ========================= */\n/* Sample global variables\n/* ========================= */\n/**\n * max size of jump table\n * 2^(2*MAX_JUMP_TABLE-1) work groups will be supported\n * currently max 2048 work groups are supported\n */\n#define MAX_JUMP_TABLE 6\nstatic mtgp32_fast_t mtgp32;\nstatic bool thread_max = false;\n/* small size for check */\nstatic const int jump_step = MTGP32_LS * 10;\nstatic ZZ jump;\nstatic uint32_t jump_poly[MTGP32_N];\nstatic uint32_t jump_initial[MTGP32_N * MAX_JUMP_TABLE];\n\n\n/* =========================\n   declaration\n   ========================= */\nstatic int test(int argc, char * argv[]);\nstatic void make_jump_table(int group_num);\nstatic void initialize_by_seed(options& opt,\n\t\t\t       Buffer& status_buffer,\n\t\t\t       int group,\n\t\t\t       uint32_t seed);\nstatic void initialize_by_array(options& opt,\n\t\t\t\tBuffer& status_buffer,\n\t\t\t\tint group,\n\t\t\t\tuint32_t seed_array[],\n\t\t\t\tint seed_size);\nstatic void status_jump(Buffer& status_buffer, int group);\nstatic void generate_uint32(int group_num,\n\t\t\t    Buffer& status_buffer,\n\t\t\t    int data_size);\nstatic void generate_single12(int group_num,\n\t\t\t      Buffer& status_buffer,\n\t\t\t      int data_size);\nstatic void generate_single01(int group_num,\n\t\t\t      Buffer& status_buffer,\n\t\t\t      int data_size);\nstatic int init_check_data(mtgp32_fast_t * mtgp32,\n\t\t\t   uint32_t seed);\nstatic int init_check_data_array(mtgp32_fast_t * mtgp32,\n\t\t\t\t uint32_t seed_array[],\n\t\t\t\t int size);\nstatic void free_check_data(mtgp32_fast_t * mtgp32);\nstatic void check_data(uint32_t * h_data, int num_data);\nstatic void check_single12(float * h_data, int num_data);\nstatic void check_single01(float * h_data, int num_data);\n\n/* =========================\n   mtgp32 sample code\n   ========================= */\n/**\n * main\n * catch errors\n *@param argc number of arguments\n *@param argv array of arguments\n *@return 0 normal, -1 error\n */\nint main(int argc, char * argv[]) {\n    try {\n\treturn test(argc, argv);\n    } catch (cl::Error e) {\n\tcerr << \"Error Code:\" << e.err() << endl;\n\tcerr << errorMessage << endl;\n\tcerr << e.what() << endl;\n    }\n}\n\n/**\n * sample main\n *@param argc number of arguments\n *@param argv array of arguments\n *@return 0 normal, -1 error\n */\nstatic int test(int argc, char * argv[]) {\n#if defined(DEBUG)\n    cout << \"test start\" << endl;\n#endif\n    options opt;\n    if (!parse_opt(opt, argc, argv)) {\n\treturn -1;\n    }\n    // OpenCL setup\n#if defined(DEBUG)\n    cout << \"openCL setup start\" << endl;\n#endif\n    platforms = getPlatforms();\n    devices = getDevices();\n    context = getContext();\n#if defined(APPLE) || defined(__MACOSX) || defined(__APPLE__)\n    source = getSource(\"mtgp32-jump.cli\");\n#else\n    source = getSource(\"mtgp32-jump.cl\");\n#endif\n    program = getProgram();\n    queue = getCommandQueue();\n#if defined(DEBUG)\n    cout << \"openCL setup end\" << endl;\n#endif\n\n    int max_group_size = getMaxGroupSize();\n    if (opt.group_num > max_group_size) {\n\tcout << \"group_num greater than max value(\"\n\t     << max_group_size << \")\"\n\t     << endl;\n\treturn -1;\n    }\n    int max_size = getMaxWorkItemSize(0);\n    if (MTGP32_TN > max_size) {\n\tcout << \"workitem size is greater than max value(\"\n\t     << dec << max_size << \")\"\n\t     << \"current:\" << dec << MTGP32_N << endl;\n\treturn -1;\n    }\n    if (MTGP32_N > max_size) {\n\tthread_max = true;\n    }\n    int local_mem_size = getLocalMemSize();\n    if (local_mem_size < sizeof(uint32_t) * MTGP32_N * 2) {\n\tcout << \"local memory size is smaller than min value(\"\n\t     << dec << sizeof(uint32_t) * MTGP32_N * 2\n\t     << \") current:\"\n\t     << dec << local_mem_size << endl;\n\treturn -1;\n    }\n    Buffer status_buffer(context,\n\t\t\t CL_MEM_READ_WRITE,\n\t\t\t sizeof(uint32_t) * MTGP32_N * opt.group_num);\n\n    make_jump_table(opt.group_num);\n    int data_count = opt.data_count;\n    int data_unit = jump_step * opt.group_num;\n\n    // initialize by seed\n    // generate uint32_t\n    init_check_data(&mtgp32, 1234);\n    initialize_by_seed(opt, status_buffer, opt.group_num, 1234);\n    while (data_count > 0) {\n\tgenerate_uint32(opt.group_num, status_buffer, data_unit);\n\tstatus_jump(status_buffer, opt.group_num);\n\tdata_count -= data_unit;\n    }\n    free_check_data(&mtgp32);\n\n    // initialize by array\n    // generate single float\n    uint32_t seed_array[5] = {1, 2, 3, 4, 5};\n    init_check_data_array(&mtgp32, seed_array, 5);\n    initialize_by_array(opt, status_buffer, opt.group_num,\n\t\t\tseed_array, 5);\n    data_count = opt.data_count;\n    while (data_count > 0) {\n\tgenerate_single12(opt.group_num, status_buffer, data_unit);\n\tstatus_jump(status_buffer, opt.group_num);\n\tdata_count -= data_unit;\n\tif (data_count > 0) {\n\t    generate_single01(opt.group_num, status_buffer, data_unit);\n\t    status_jump(status_buffer, opt.group_num);\n\t    data_count -= data_unit;\n\t}\n    }\n    free_check_data(&mtgp32);\n    return 0;\n}\n\n/**\n * prepare jump polynomial.\n * this step may be pre-computed in practical use.\n * @param group_num number of work groups\n */\nstatic void make_jump_table(int group_num)\n{\n#if defined(DEBUG)\n    cout << \"make_jump_table start\" << endl;\n#endif\n    mtgp32_fast_t dummy;\n    int rc = mtgp32_init(&dummy, &mtgp32_params_fast_11213[0], 1);\n    if (rc) {\n\tcerr << \"init error\" << endl;\n\tthrow cl::Error(rc, \"mtgp32 init error\");\n    }\n    GF2X poly;\n    clock_t start = clock();\n    calc_characteristic(poly, &dummy);\n    clock_t end = clock();\n    double time = (double)(end - start) / CLOCKS_PER_SEC * 1000.0;\n    cout << \"calc_characteristic: \" << dec << time << \"ms\" << endl;\n    ZZ step;\n    step = jump_step;\n    start = clock();\n    for (int i = 0; i < MAX_JUMP_TABLE; i++) {\n\tcalc_jump(&jump_initial[i * MTGP32_N],\n\t\t  MTGP32_N,\n\t\t  step,\n\t\t  poly);\n\tstep *= 4;\n    }\n    step = jump_step;\n    step *= group_num - 1;\n    calc_jump(jump_poly, MTGP32_N, step, poly);\n    end = clock();\n    time = (double)(end - start) / CLOCKS_PER_SEC * 1000.0;\n    cout << \"make jump table: \" << dec << time << \"ms\" << endl;\n#if defined(DEBUG)\n    cout << \"step:\" << dec << step << endl;\n    cout << \"jump_poly[0]:\" << hex << jump_poly[0] << endl;\n    cout << \"jump_poly[1]:\" << hex << jump_poly[1] << endl;\n    cout << \"jump_initial[0]:\" << hex << jump_initial[0 * MTGP32_N] << endl;\n    cout << \"jump_initial[1]:\" << hex << jump_initial[1 * MTGP32_N] << endl;\n    cout << \"jump_initial[2]:\" << hex << jump_initial[2 * MTGP32_N] << endl;\n#endif\n#if defined(DEBUG)\n    cout << \"make_jump_table end\" << endl;\n#endif\n}\n\n/**\n * initialize mtgp status in device global memory\n * using seed and fixed jump.\n * jump step is fixed to 3^162.\n *@param opt command line option\n *@param status_buffer mtgp status in device global memory\n *@param group number of group\n *@param seed seed for initialization\n */\nstatic void initialize_by_seed(options& opt,\n\t\t\t       Buffer& status_buffer,\n\t\t\t       int group,\n\t\t\t       uint32_t seed)\n{\n#if defined(DEBUG)\n    cout << \"initialize_by_seed start\" << endl;\n#endif\n    // jump table\n    Buffer jump_table_buffer(context,\n\t\t\t     CL_MEM_READ_WRITE,\n\t\t\t     MTGP32_N * MAX_JUMP_TABLE * sizeof(uint32_t));\n    queue.enqueueWriteBuffer(jump_table_buffer,\n\t\t\t     CL_TRUE,\n\t\t\t     0,\n\t\t\t     MTGP32_N * MAX_JUMP_TABLE * sizeof(uint32_t),\n\t\t\t     jump_initial);\n\n    Kernel init_kernel(program, \"mtgp32_jump_seed_kernel\");\n#if defined(DEBUG)\n    cout << \"arg0 start\" << endl;\n#endif\n    init_kernel.setArg(0, status_buffer);\n    init_kernel.setArg(1, seed);\n    init_kernel.setArg(2, jump_table_buffer);\n#if defined(DEBUG)\n    cout << \"arg2 end\" << endl;\n#endif\n    int local_item = MTGP32_N;\n    if (thread_max) {\n\tlocal_item = MTGP32_TN;\n    }\n    NDRange global(group * local_item);\n    NDRange local(local_item);\n    Event event;\n#if defined(DEBUG)\n    cout << \"global:\" << dec << group * local_item << endl;\n    cout << \"group:\" << dec << group << endl;\n    cout << \"local:\" << dec << local_item << endl;\n#endif\n    queue.enqueueNDRangeKernel(init_kernel,\n\t\t\t       NullRange,\n\t\t\t       global,\n\t\t\t       local,\n\t\t\t       NULL,\n\t\t\t       &event);\n    double time = get_time(event);\n    cout << \"initializing time = \" << time * 1000 << \"ms\" << endl;\n#if 0\n    uint status[group * MTGP32_N];\n    queue.enqueueReadBuffer(status_buffer,\n\t\t\t    CL_TRUE,\n\t\t\t    0,\n\t\t\t    sizeof(uint32_t) * MTGP32_N * group,\n\t\t\t    status);\n#if defined(DEBUG)\n    cout << \"status[0]:\" << hex << status[0] << endl;\n    cout << \"status[MTGP32_N - 1]:\" << hex << status[MTGP32_N - 1] << endl;\n    cout << \"status[MTGP32_N]:\" << hex << status[MTGP32_N] << endl;\n    cout << \"status[MTGP32_N + 1]:\" << hex << status[MTGP32_N + 1] << endl;\n#endif\n    check_status(status, group);\n#endif\n#if defined(DEBUG)\n    cout << \"initialize_by_seed end\" << endl;\n#endif\n}\n\n/**\n * initialize mtgp status in device global memory\n * using an array of seeds and jump.\n *@param opt command line option\n *@param status_buffer mtgp status in device global memory\n *@param group number of group\n *@param seed_array seeds for initialization\n *@param seed_size size of seed_array\n */\nstatic void initialize_by_array(options& opt,\n\t\t\t\tBuffer& status_buffer,\n\t\t\t\tint group,\n\t\t\t\tuint32_t seed_array[],\n\t\t\t\tint seed_size)\n{\n#if defined(DEBUG)\n    cout << \"initialize_by_array start\" << endl;\n#endif\n    // jump table\n    Buffer jump_table_buffer(context,\n\t\t\t     CL_MEM_READ_WRITE,\n\t\t\t     MTGP32_N * MAX_JUMP_TABLE * sizeof(uint32_t));\n    queue.enqueueWriteBuffer(jump_table_buffer,\n\t\t\t     CL_TRUE,\n\t\t\t     0,\n\t\t\t     MTGP32_N * MAX_JUMP_TABLE * sizeof(uint32_t),\n\t\t\t     jump_initial);\n\n    Buffer seed_array_buffer(context,\n\t\t\t     CL_MEM_READ_WRITE,\n\t\t\t     seed_size * sizeof(uint32_t));\n    queue.enqueueWriteBuffer(seed_array_buffer,\n\t\t\t     CL_TRUE,\n\t\t\t     0,\n\t\t\t     seed_size * sizeof(uint32_t),\n\t\t\t     seed_array);\n    Kernel init_kernel(program, \"mtgp32_jump_array_kernel\");\n    init_kernel.setArg(0, status_buffer);\n    init_kernel.setArg(1, seed_array_buffer);\n    init_kernel.setArg(2, seed_size);\n    init_kernel.setArg(3, jump_table_buffer);\n    int local_item = MTGP32_N;\n    if (thread_max) {\n\tlocal_item = MTGP32_TN;\n    }\n    NDRange global(group * local_item);\n    NDRange local(local_item);\n    Event event;\n    queue.enqueueNDRangeKernel(init_kernel,\n\t\t\t       NullRange,\n\t\t\t       global,\n\t\t\t       local,\n\t\t\t       NULL,\n\t\t\t       &event);\n    double time = get_time(event);\n#if 0\n    uint status[group * MTGP32_N];\n    queue.enqueueReadBuffer(status_buffer,\n\t\t\t    CL_TRUE,\n\t\t\t    0,\n\t\t\t    sizeof(uint32_t) * MTGP32_N * group,\n\t\t\t    status);\n    check_status(status, group);\n#endif\n    cout << \"initializing time = \" << time * 1000 << \"ms\" << endl;\n#if defined(DEBUG)\n    cout << \"initialize_by_array end\" << endl;\n#endif\n}\n\n/**\n * jump mtgp status in device global memory\n *@param status_buffer mtgp status in device global memory\n *@param group number of group\n */\nstatic void status_jump(Buffer& status_buffer, int group)\n{\n#if defined(DEBUG)\n    cout << \"jump start\" << endl;\n#endif\n    // jump table\n    Buffer jump_table_buffer(context,\n\t\t\t     CL_MEM_READ_WRITE,\n\t\t\t     MTGP32_N * sizeof(uint32_t));\n    queue.enqueueWriteBuffer(jump_table_buffer,\n\t\t\t     CL_TRUE,\n\t\t\t     0,\n\t\t\t     MTGP32_N * sizeof(uint32_t),\n\t\t\t     jump_poly);\n\n    Kernel init_kernel(program, \"mtgp32_jump_kernel\");\n    init_kernel.setArg(0, status_buffer);\n    init_kernel.setArg(1, jump_table_buffer);\n    int local_item = MTGP32_N;\n    if (thread_max) {\n\tlocal_item = MTGP32_TN;\n    }\n    NDRange global(group * local_item);\n    NDRange local(local_item);\n    Event event;\n#if defined(DEBUG)\n    cout << \"global:\" << dec << group * local_item << endl;\n    cout << \"group:\" << dec << group << endl;\n    cout << \"local:\" << dec << local_item << endl;\n#endif\n    queue.enqueueNDRangeKernel(init_kernel,\n\t\t\t       NullRange,\n\t\t\t       global,\n\t\t\t       local,\n\t\t\t       NULL,\n\t\t\t       &event);\n    double time = get_time(event);\n    cout << \"jump time = \" << time * 1000 << \"ms\" << endl;\n#if defined(DEBUG)\n    cout << \"jump end\" << endl;\n#endif\n}\n\n/**\n * generate 32 bit unsigned random numbers in device global memory\n *@param group_num number of groups for execution\n *@param status_buffer mtgp status in device global memory\n *@param data_size number of data to generate\n */\nstatic void generate_uint32(int group_num,\n\t\t\t    Buffer& status_buffer,\n\t\t\t    int data_size)\n{\n#if defined(DEBUG)\n    cout << \"generate_uint32 start\" << endl;\n#endif\n    int item_num = MTGP32_TN * group_num;\n    int min_size = MTGP32_LS * group_num;\n    if (data_size % min_size != 0) {\n\tdata_size = (data_size / min_size + 1) * min_size;\n    }\n    Kernel uint_kernel(program, \"mtgp32_uint32_kernel\");\n    Buffer output_buffer(context,\n\t\t\t CL_MEM_READ_WRITE,\n\t\t\t data_size * sizeof(uint32_t));\n    uint_kernel.setArg(0, status_buffer);\n    uint_kernel.setArg(1, output_buffer);\n    uint_kernel.setArg(2, data_size / group_num);\n    NDRange global(item_num);\n    NDRange local(MTGP32_TN);\n    Event generate_event;\n#if defined(DEBUG)\n    cout << \"generate_uint32 enque kernel start\" << endl;\n#endif\n    queue.enqueueNDRangeKernel(uint_kernel,\n\t\t\t       NullRange,\n\t\t\t       global,\n\t\t\t       local,\n\t\t\t       NULL,\n\t\t\t       &generate_event);\n#if defined(DEBUG)\n    cout << \"generate_uint32 enque kernel end\" << endl;\n#endif\n    uint32_t * output = new uint32_t[data_size];\n#if defined(DEBUG)\n    cout << \"generate_uint32 event wait start\" << endl;\n#endif\n    generate_event.wait();\n#if defined(DEBUG)\n    cout << \"generate_uint32 event wait end\" << endl;\n#endif\n#if defined(DEBUG)\n    cout << \"generate_uint32 readbuffer start\" << endl;\n#endif\n    queue.enqueueReadBuffer(output_buffer,\n\t\t\t    CL_TRUE,\n\t\t\t    0,\n\t\t\t    data_size * sizeof(uint32_t),\n\t\t\t    &output[0]);\n#if defined(DEBUG)\n    cout << \"generate_uint32 readbuffer end\" << endl;\n#endif\n    check_data(output, data_size);\n    print_uint32(&output[0], data_size, item_num);\n    double time = get_time(generate_event);\n    cout << \"generate time:\" << time * 1000 << \"ms\" << endl;\n    delete[] output;\n#if defined(DEBUG)\n    cout << \"generate_uint32 end\" << endl;\n#endif\n}\n\n/**\n * generate single precision floating point numbers in the range [1, 2)\n * in device global memory\n *@param group_num number of groups for execution\n *@param status_buffer mtgp status in device global memory\n *@param data_size number of data to generate\n */\nstatic void generate_single12(int group_num,\n\t\t\t      Buffer& status_buffer,\n\t\t\t      int data_size)\n{\n    int item_num = MTGP32_TN * group_num;\n    int min_size = MTGP32_LS * group_num;\n    if (data_size % min_size != 0) {\n\tdata_size = (data_size / min_size + 1) * min_size;\n    }\n    Kernel single_kernel(program, \"mtgp32_single12_kernel\");\n    Buffer output_buffer(context,\n\t\t\t CL_MEM_READ_WRITE,\n\t\t\t data_size * sizeof(float));\n    single_kernel.setArg(0, status_buffer);\n    single_kernel.setArg(1, output_buffer);\n    single_kernel.setArg(2, data_size / group_num);\n    NDRange global(item_num);\n    NDRange local(MTGP32_TN);\n    Event generate_event;\n    queue.enqueueNDRangeKernel(single_kernel,\n\t\t\t       NullRange,\n\t\t\t       global,\n\t\t\t       local,\n\t\t\t       NULL,\n\t\t\t       &generate_event);\n    float * output = new float[data_size];\n    generate_event.wait();\n    queue.enqueueReadBuffer(output_buffer,\n\t\t\t    CL_TRUE,\n\t\t\t    0,\n\t\t\t    data_size * sizeof(float),\n\t\t\t    &output[0]);\n    check_single12(output, data_size);\n    print_float(output, data_size, item_num);\n    double time = get_time(generate_event);\n    delete[] output;\n    cout << \"generate time:\" << time * 1000 << \"ms\" << endl;\n}\n\n/**\n * generate single precision floating point numbers in the range [0, 1)\n * in device global memory\n *@param group_num number of groups for execution\n *@param status_buffer mtgp status in device global memory\n *@param data_size number of data to generate\n */\nstatic void generate_single01(int group_num,\n\t\t\t      Buffer& status_buffer,\n\t\t\t      int data_size)\n{\n    int item_num = MTGP32_TN * group_num;\n    int min_size = MTGP32_LS * group_num;\n    if (data_size % min_size != 0) {\n\tdata_size = (data_size / min_size + 1) * min_size;\n    }\n    Kernel single_kernel(program, \"mtgp32_single01_kernel\");\n    Buffer output_buffer(context,\n\t\t\t CL_MEM_READ_WRITE,\n\t\t\t data_size * sizeof(float));\n    single_kernel.setArg(0, status_buffer);\n    single_kernel.setArg(1, output_buffer);\n    single_kernel.setArg(2, data_size / group_num);\n    NDRange global(item_num);\n    NDRange local(MTGP32_TN);\n    Event generate_event;\n    queue.enqueueNDRangeKernel(single_kernel,\n\t\t\t       NullRange,\n\t\t\t       global,\n\t\t\t       local,\n\t\t\t       NULL,\n\t\t\t       &generate_event);\n    float * output = new float[data_size];\n    generate_event.wait();\n    queue.enqueueReadBuffer(output_buffer,\n\t\t\t    CL_TRUE,\n\t\t\t    0,\n\t\t\t    data_size * sizeof(float),\n\t\t\t    &output[0]);\n    check_single01(output, data_size);\n    print_float(output, data_size, item_num);\n    double time = get_time(generate_event);\n    delete[] output;\n    cout << \"generate time:\" << time * 1000 << \"ms\" << endl;\n}\n\n/* ==============\n * check programs\n * ==============*/\nstatic int init_check_data(mtgp32_fast_t * mtgp32,\n\t\t\t   uint32_t seed)\n{\n#if defined(DEBUG)\n    cout << \"init_check_data start\" << endl;\n#endif\n    int rc = mtgp32_init(mtgp32,\n\t\t\t &mtgp32_params_fast_11213[0],\n\t\t\t seed);\n    if (rc) {\n\treturn rc;\n    }\n#if defined(DEBUG)\n    cout << \"init_check_data end\" << endl;\n#endif\n    return 0;\n}\n\nstatic int init_check_data_array(mtgp32_fast_t * mtgp32,\n\t\t\t\t uint32_t seed_array[],\n\t\t\t\t int size)\n{\n#if defined(DEBUG)\n    cout << \"init_check_data_array start\" << endl;\n#endif\n    int rc = mtgp32_init_by_array(mtgp32,\n\t\t\t\t  &mtgp32_params_fast_11213[0],\n\t\t\t\t  seed_array,\n\t\t\t\t  size);\n    if (rc) {\n\treturn rc;\n    }\n#if defined(DEBUG)\n    cout << \"init_check_data_array end\" << endl;\n#endif\n    return 0;\n}\n\nstatic void free_check_data(mtgp32_fast_t * mtgp32)\n{\n#if defined(DEBUG)\n    cout << \"free_check_data start\" << endl;\n#endif\n    mtgp32_free(mtgp32);\n#if defined(DEBUG)\n    cout << \"free_check_data end\" << endl;\n#endif\n}\n\nstatic void check_data(uint32_t * h_data, int num_data)\n{\n#if defined(DEBUG)\n    cout << \"check_data start\" << endl;\n#endif\n    bool error = false;\n    bool disp_flg = true;\n    int count = 0;\n    for (int j = 0; j < num_data; j++) {\n\tuint32_t r = mtgp32_genrand_uint32(&mtgp32);\n\tif ((h_data[j] != r) && disp_flg) {\n\t    cout << \"mismatch\"\n\t\t << \" j = \" << dec << j\n\t\t << \" data = \" << hex << h_data[j]\n\t\t << \" r = \" << hex << r << endl;\n\t    cout << \"check_data check N.G!\" << endl;\n\t    count++;\n\t    error = true;\n\t}\n\tif (count > 10) {\n\t    disp_flg = false;\n\t}\n    }\n    if (!error) {\n\tcout << \"check_data check O.K!\" << endl;\n    } else {\n\tthrow cl::Error(-1, \"mtgp32 check_data error!\");\n    }\n#if defined(DEBUG)\n    cout << \"check_data end\" << endl;\n#endif\n}\n\nstatic void check_single12(float * h_data, int num_data)\n{\n#if defined(DEBUG)\n    cout << \"check_single start\" << endl;\n#endif\n    bool error = false;\n    bool disp_flg = true;\n    int count = 0;\n    for (int j = 0; j < num_data; j++) {\n\tfloat r =  mtgp32_genrand_close1_open2(&mtgp32);\n\tif (!(-FLT_EPSILON <= h_data[j] - r &&\n\t     h_data[j] - r <= FLT_EPSILON)\n\t    && disp_flg) {\n\t    cout << \"mismatch\"\n\t\t << \" j = \" << dec << j\n\t\t << \" data = \" << dec << h_data[j]\n\t\t << \" r = \" << dec << r << endl;\n\t    cout << \"check_data check N.G!\" << endl;\n\t    count++;\n\t    error = true;\n\t}\n\tif (count > 10) {\n\t    disp_flg = false;\n\t}\n    }\n    if (!error) {\n\tcout << \"check_single check O.K!\" << endl;\n    } else {\n\tthrow cl::Error(-1, \"mtgp32 check_data error!\");\n    }\n#if defined(DEBUG)\n    cout << \"check_single end\" << endl;\n#endif\n}\n\nstatic void check_single01(float * h_data, int num_data)\n{\n#if defined(DEBUG)\n    cout << \"check_single start\" << endl;\n#endif\n    bool error = false;\n    bool disp_flg = true;\n    int count = 0;\n    for (int j = 0; j < num_data; j++) {\n\tfloat r =  mtgp32_genrand_close_open(&mtgp32);\n\tif (!(-FLT_EPSILON <= h_data[j] - r &&\n\t     h_data[j] - r <= FLT_EPSILON)\n\t    && disp_flg) {\n\t    cout << \"mismatch\"\n\t\t << \" j = \" << dec << j\n\t\t << \" data = \" << dec << h_data[j]\n\t\t << \" r = \" << dec << r << endl;\n\t    cout << \"check_data check N.G!\" << endl;\n\t    count++;\n\t    error = true;\n\t}\n\tif (count > 10) {\n\t    disp_flg = false;\n\t}\n    }\n    if (!error) {\n\tcout << \"check_single check O.K!\" << endl;\n    } else {\n\tthrow cl::Error(-1, \"mtgp32 check_data error!\");\n    }\n#if defined(DEBUG)\n    cout << \"check_single end\" << endl;\n#endif\n}\n\n\n", "meta": {"hexsha": "831474d103fed69ad394d5bd2ccbc7ad66337c33", "size": 21422, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "openCL-sample/mtgp32-sample-jump2.cpp", "max_stars_repo_name": "mkt-matsumoto-lab/MTGP", "max_stars_repo_head_hexsha": "9cea3283dc67d9fc6cfc044b7ae38fe9ef32afb3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2015-04-24T06:39:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-10T09:48:37.000Z", "max_issues_repo_path": "openCL-sample/mtgp32-sample-jump2.cpp", "max_issues_repo_name": "mkt-matsumoto-lab/MTGP", "max_issues_repo_head_hexsha": "9cea3283dc67d9fc6cfc044b7ae38fe9ef32afb3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-01-10T07:15:53.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-10T07:15:53.000Z", "max_forks_repo_path": "openCL-sample/mtgp32-sample-jump2.cpp", "max_forks_repo_name": "mkt-matsumoto-lab/MTGP", "max_forks_repo_head_hexsha": "9cea3283dc67d9fc6cfc044b7ae38fe9ef32afb3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-07-27T21:05:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-10T09:47:58.000Z", "avg_line_length": 27.6412903226, "max_line_length": 76, "alphanum_fraction": 0.6348613575, "num_tokens": 5667, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.48547024483439244}}
{"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 \"teaser/matcher.h\"\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <flann/flann.hpp>\n\n#include \"teaser/geometry.h\"\n\nnamespace teaser {\n\nstd::vector<std::pair<int, int>> Matcher::calculateCorrespondences(\n    teaser::PointCloud& source_points, teaser::PointCloud& target_points,\n    teaser::FPFHCloud& source_features, teaser::FPFHCloud& target_features, bool use_absolute_scale,\n    bool use_crosscheck, bool use_tuple_test, float tuple_scale) {\n\n  Feature cloud_features;\n  pointcloud_.push_back(source_points);\n  pointcloud_.push_back(target_points);\n\n  // It compute the global_scale_ required to set correctly the search radius\n  normalizePoints(use_absolute_scale);\n\n  for (auto& f : source_features) {\n    Eigen::VectorXf fpfh(33);\n    for (int i = 0; i < 33; i++)\n      fpfh(i) = f.histogram[i];\n    cloud_features.push_back(fpfh);\n  }\n  features_.push_back(cloud_features);\n\n  cloud_features.clear();\n  for (auto& f : target_features) {\n    Eigen::VectorXf fpfh(33);\n    for (int i = 0; i < 33; i++)\n      fpfh(i) = f.histogram[i];\n    cloud_features.push_back(fpfh);\n  }\n  features_.push_back(cloud_features);\n\n  advancedMatching(use_crosscheck, use_tuple_test, tuple_scale);\n\n  return corres_;\n}\n\nvoid Matcher::normalizePoints(bool use_absolute_scale) {\n  int num = 2;\n  float scale = 0;\n\n  means_.clear();\n\n  for (int i = 0; i < num; ++i) {\n    float max_scale = 0;\n\n    // compute mean\n    Eigen::Vector3f mean;\n    mean.setZero();\n\n    int npti = pointcloud_[i].size();\n    for (int ii = 0; ii < npti; ++ii) {\n      Eigen::Vector3f p(pointcloud_[i][ii].x, pointcloud_[i][ii].y, pointcloud_[i][ii].z);\n      mean = mean + p;\n    }\n    mean = mean / npti;\n    means_.push_back(mean);\n\n    for (int ii = 0; ii < npti; ++ii) {\n      pointcloud_[i][ii].x -= mean(0);\n      pointcloud_[i][ii].y -= mean(1);\n      pointcloud_[i][ii].z -= mean(2);\n    }\n\n    // compute scale\n    for (int ii = 0; ii < npti; ++ii) {\n      Eigen::Vector3f p(pointcloud_[i][ii].x, pointcloud_[i][ii].y, pointcloud_[i][ii].z);\n      float temp = p.norm(); // because we extract mean in the previous stage.\n      if (temp > max_scale) {\n        max_scale = temp;\n      }\n    }\n\n    if (max_scale > scale) {\n      scale = max_scale;\n    }\n  }\n\n  // mean of the scale variation\n  if (use_absolute_scale) {\n    global_scale_ = 1.0f;\n  } else {\n    global_scale_ = scale; // second choice: we keep the maximum scale.\n  }\n\n  if (global_scale_ != 1.0f) {\n    for (int i = 0; i < num; ++i) {\n      int npti = pointcloud_[i].size();\n      for (int ii = 0; ii < npti; ++ii) {\n        pointcloud_[i][ii].x /= global_scale_;\n        pointcloud_[i][ii].y /= global_scale_;\n        pointcloud_[i][ii].z /= global_scale_;\n      }\n    }\n  }\n}\nvoid Matcher::advancedMatching(bool use_crosscheck, bool use_tuple_test, float tuple_scale) {\n\n  int fi = 0; // source idx\n  int fj = 1; // destination idx\n\n  bool swapped = false;\n\n  if (pointcloud_[fj].size() > pointcloud_[fi].size()) {\n    int temp = fi;\n    fi = fj;\n    fj = temp;\n    swapped = true;\n  }\n\n  int nPti = pointcloud_[fi].size();\n  int nPtj = pointcloud_[fj].size();\n\n  ///////////////////////////\n  /// Build FLANNTREE\n  ///////////////////////////\n  KDTree feature_tree_i(flann::KDTreeSingleIndexParams(15));\n  buildKDTree(features_[fi], &feature_tree_i);\n\n  KDTree feature_tree_j(flann::KDTreeSingleIndexParams(15));\n  buildKDTree(features_[fj], &feature_tree_j);\n\n  std::vector<int> corres_K, corres_K2;\n  std::vector<float> dis;\n  std::vector<int> ind;\n\n  std::vector<std::pair<int, int>> corres;\n  std::vector<std::pair<int, int>> corres_cross;\n  std::vector<std::pair<int, int>> corres_ij;\n  std::vector<std::pair<int, int>> corres_ji;\n\n  ///////////////////////////\n  /// INITIAL MATCHING\n  ///////////////////////////\n  std::vector<int> i_to_j(nPti, -1);\n  for (int j = 0; j < nPtj; j++) {\n    searchKDTree(&feature_tree_i, features_[fj][j], corres_K, dis, 1);\n    int i = corres_K[0];\n    if (i_to_j[i] == -1) {\n      searchKDTree(&feature_tree_j, features_[fi][i], corres_K, dis, 1);\n      int ij = corres_K[0];\n      i_to_j[i] = ij;\n    }\n    corres_ji.push_back(std::pair<int, int>(i, j));\n  }\n\n  for (int i = 0; i < nPti; i++) {\n    if (i_to_j[i] != -1)\n      corres_ij.push_back(std::pair<int, int>(i, i_to_j[i]));\n  }\n\n  int ncorres_ij = corres_ij.size();\n  int ncorres_ji = corres_ji.size();\n\n  // corres = corres_ij + corres_ji;\n  for (int i = 0; i < ncorres_ij; ++i)\n    corres.push_back(std::pair<int, int>(corres_ij[i].first, corres_ij[i].second));\n  for (int j = 0; j < ncorres_ji; ++j)\n    corres.push_back(std::pair<int, int>(corres_ji[j].first, corres_ji[j].second));\n\n  ///////////////////////////\n  /// CROSS CHECK\n  /// input : corres_ij, corres_ji\n  /// output : corres\n  ///////////////////////////\n  if (use_crosscheck) {\n    std::cout << \"CROSS CHECK\" << std::endl;\n    // build data structure for cross check\n    corres.clear();\n    corres_cross.clear();\n    std::vector<std::vector<int>> Mi(nPti);\n    std::vector<std::vector<int>> Mj(nPtj);\n\n    int ci, cj;\n    for (int i = 0; i < ncorres_ij; ++i) {\n      ci = corres_ij[i].first;\n      cj = corres_ij[i].second;\n      Mi[ci].push_back(cj);\n    }\n    for (int j = 0; j < ncorres_ji; ++j) {\n      ci = corres_ji[j].first;\n      cj = corres_ji[j].second;\n      Mj[cj].push_back(ci);\n    }\n\n    // cross check\n    for (int i = 0; i < nPti; ++i) {\n      for (int ii = 0; ii < Mi[i].size(); ++ii) {\n        int j = Mi[i][ii];\n        for (int jj = 0; jj < Mj[j].size(); ++jj) {\n          if (Mj[j][jj] == i) {\n            corres.push_back(std::pair<int, int>(i, j));\n            corres_cross.push_back(std::pair<int, int>(i, j));\n          }\n        }\n      }\n    }\n  } else {\n    std::cout << \"Skipping Cross Check.\" << std::endl;\n  }\n\n  ///////////////////////////\n  /// TUPLE CONSTRAINT\n  /// input : corres\n  /// output : corres\n  ///////////////////////////\n  if (use_tuple_test && tuple_scale != 0) {\n    std::cout << \"TUPLE CONSTRAINT\" << std::endl;\n    srand(time(NULL));\n    int rand0, rand1, rand2;\n    int idi0, idi1, idi2;\n    int idj0, idj1, idj2;\n    float scale = tuple_scale;\n    int ncorr = corres.size();\n    int number_of_trial = ncorr * 100;\n    std::vector<std::pair<int, int>> corres_tuple;\n\n    for (int i = 0; i < number_of_trial; i++) {\n      rand0 = rand() % ncorr;\n      rand1 = rand() % ncorr;\n      rand2 = rand() % ncorr;\n\n      idi0 = corres[rand0].first;\n      idj0 = corres[rand0].second;\n      idi1 = corres[rand1].first;\n      idj1 = corres[rand1].second;\n      idi2 = corres[rand2].first;\n      idj2 = corres[rand2].second;\n\n      // collect 3 points from i-th fragment\n      Eigen::Vector3f pti0 = {pointcloud_[fi][idi0].x, pointcloud_[fi][idi0].y,\n                              pointcloud_[fi][idi0].z};\n      Eigen::Vector3f pti1 = {pointcloud_[fi][idi1].x, pointcloud_[fi][idi1].y,\n                              pointcloud_[fi][idi1].z};\n      Eigen::Vector3f pti2 = {pointcloud_[fi][idi2].x, pointcloud_[fi][idi2].y,\n                              pointcloud_[fi][idi2].z};\n\n      float li0 = (pti0 - pti1).norm();\n      float li1 = (pti1 - pti2).norm();\n      float li2 = (pti2 - pti0).norm();\n\n      // collect 3 points from j-th fragment\n      Eigen::Vector3f ptj0 = {pointcloud_[fj][idj0].x, pointcloud_[fj][idj0].y,\n                              pointcloud_[fj][idj0].z};\n      Eigen::Vector3f ptj1 = {pointcloud_[fj][idj1].x, pointcloud_[fj][idj1].y,\n                              pointcloud_[fj][idj1].z};\n      Eigen::Vector3f ptj2 = {pointcloud_[fj][idj2].x, pointcloud_[fj][idj2].y,\n                              pointcloud_[fj][idj2].z};\n\n      float lj0 = (ptj0 - ptj1).norm();\n      float lj1 = (ptj1 - ptj2).norm();\n      float lj2 = (ptj2 - ptj0).norm();\n\n      if ((li0 * scale < lj0) && (lj0 < li0 / scale) && (li1 * scale < lj1) &&\n          (lj1 < li1 / scale) && (li2 * scale < lj2) && (lj2 < li2 / scale)) {\n        corres_tuple.push_back(std::pair<int, int>(idi0, idj0));\n        corres_tuple.push_back(std::pair<int, int>(idi1, idj1));\n        corres_tuple.push_back(std::pair<int, int>(idi2, idj2));\n      }\n    }\n    corres.clear();\n\n    for (size_t i = 0; i < corres_tuple.size(); ++i)\n      corres.push_back(std::pair<int, int>(corres_tuple[i].first, corres_tuple[i].second));\n  } else {\n    std::cout << \"Skipping Tuple Constraint.\" << std::endl;\n  }\n\n  if (swapped) {\n    std::vector<std::pair<int, int>> temp;\n    for (size_t i = 0; i < corres.size(); i++)\n      temp.push_back(std::pair<int, int>(corres[i].second, corres[i].first));\n    corres.clear();\n    corres = temp;\n  }\n  corres_ = corres;\n\n  ///////////////////////////\n  /// ERASE DUPLICATES\n  /// input : corres_\n  /// output : corres_\n  ///////////////////////////\n  std::sort(corres_.begin(), corres_.end());\n  corres_.erase(std::unique(corres_.begin(), corres_.end()), corres_.end());\n}\n\ntemplate <typename T> void Matcher::buildKDTree(const std::vector<T>& data, Matcher::KDTree* tree) {\n  int rows, dim;\n  rows = (int)data.size();\n  dim = (int)data[0].size();\n  std::vector<float> dataset(rows * dim);\n  flann::Matrix<float> dataset_mat(&dataset[0], rows, dim);\n  for (int i = 0; i < rows; i++)\n    for (int j = 0; j < dim; j++)\n      dataset[i * dim + j] = data[i][j];\n  KDTree temp_tree(dataset_mat, flann::KDTreeSingleIndexParams(15));\n  temp_tree.buildIndex();\n  *tree = temp_tree;\n}\n\ntemplate <typename T>\nvoid Matcher::searchKDTree(Matcher::KDTree* tree, const T& input, std::vector<int>& indices,\n                           std::vector<float>& dists, int nn) {\n  int rows_t = 1;\n  int dim = input.size();\n\n  std::vector<float> query;\n  query.resize(rows_t * dim);\n  for (int i = 0; i < dim; i++)\n    query[i] = input(i);\n  flann::Matrix<float> query_mat(&query[0], rows_t, dim);\n\n  indices.resize(rows_t * nn);\n  dists.resize(rows_t * nn);\n  flann::Matrix<int> indices_mat(&indices[0], rows_t, nn);\n  flann::Matrix<float> dists_mat(&dists[0], rows_t, nn);\n\n  tree->knnSearch(query_mat, indices_mat, dists_mat, nn, flann::SearchParams(128));\n}\n\n} // namespace teaser\n", "meta": {"hexsha": "c8e2991917a515fc2e54fc68ec3456adb7e8ef3e", "size": 10265, "ext": "cc", "lang": "C++", "max_stars_repo_path": "teaser/src/matcher.cc", "max_stars_repo_name": "plusk01/TEASER-plusplus", "max_stars_repo_head_hexsha": "0d497521d261b3fa35c4ca29eb86ba7cf9558f9f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 962.0, "max_stars_repo_stars_event_min_datetime": "2020-01-21T19:08:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T17:28:49.000Z", "max_issues_repo_path": "teaser/src/matcher.cc", "max_issues_repo_name": "plusk01/TEASER-plusplus", "max_issues_repo_head_hexsha": "0d497521d261b3fa35c4ca29eb86ba7cf9558f9f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 105.0, "max_issues_repo_issues_event_min_datetime": "2020-01-24T15:11:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T02:28:52.000Z", "max_forks_repo_path": "teaser/src/matcher.cc", "max_forks_repo_name": "plusk01/TEASER-plusplus", "max_forks_repo_head_hexsha": "0d497521d261b3fa35c4ca29eb86ba7cf9558f9f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 234.0, "max_forks_repo_forks_event_min_datetime": "2020-01-21T12:28:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T08:41:31.000Z", "avg_line_length": 30.4599406528, "max_line_length": 100, "alphanum_fraction": 0.5805163176, "num_tokens": 3165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.757794360334681, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.48547022742720003}}
{"text": "#include <chrono>\n#include <fstream>\n#include <iostream>\n#include <random>\n#include <utility>\n#include <vector>\n\n#include <Eigen/Geometry>\n#include <common_robotics_utilities/math.hpp>\n#include <common_robotics_utilities/simple_hierarchical_clustering.hpp>\n#include <common_robotics_utilities/simple_kmeans_clustering.hpp>\n\nusing PointVector = common_robotics_utilities::math::VectorVector4d;\nusing IndexClusteringResult\n    = common_robotics_utilities::simple_hierarchical_clustering\n        ::IndexClusteringResult;\nusing PointClusteringResult\n    = common_robotics_utilities::simple_hierarchical_clustering\n        ::ClusteringResult<Eigen::Vector4d, PointVector>;\n\nvoid SaveClustering(\n    const PointClusteringResult& clusters,\n    const std::string& filename)\n{\n  // Use the cluster index to set z-coordinates for easy visualization\n  std::ofstream clustering_output_file(filename, std::ios_base::out);\n  if (!clustering_output_file.is_open())\n  {\n    throw std::invalid_argument(\n        \"Log file \" + filename + \" must be write-openable\");\n  }\n  std::cout << \"Saving clustering to \" << filename << std::endl;\n  for (size_t idx = 0; idx < clusters.Clusters().size(); idx++)\n  {\n    const PointVector& cluster = clusters.Clusters().at(idx);\n    const double cluster_num = 1.0 + static_cast<double>(idx);\n    for (const Eigen::Vector4d& point : cluster)\n    {\n      clustering_output_file << point(0) << \",\" << point(1) << \",\"\n                             << cluster_num << std::endl;\n    }\n  }\n  clustering_output_file.close();\n}\n\nvoid SaveIndexClustering(\n    const PointVector& raw_points,\n    const IndexClusteringResult& index_clusters,\n    const std::string& filename)\n{\n  SaveClustering(\n      common_robotics_utilities::simple_hierarchical_clustering\n          ::MakeElementClusteringFromIndexClustering<\n              Eigen::Vector4d, PointVector>(raw_points, index_clusters),\n      filename);\n}\n\nint main(int argc, char** argv)\n{\n  const size_t num_points\n      = (argc >= 2) ? static_cast<size_t>(atoi(argv[1])) : 1000;\n  const double cluster_threshold\n      = (argc >= 3) ? atof(argv[2]) : 0.1;\n  if (cluster_threshold < 0.0)\n  {\n    throw std::invalid_argument(\"cluster_threshold < 0.0\");\n  }\n  std::cout << \"Generating \" << num_points << \" points...\" << std::endl;\n  const int64_t seed = 42;\n  std::mt19937_64 prng(seed);\n  std::uniform_real_distribution<double> dist(0.0, 10.0);\n  PointVector random_points(num_points);\n  for (size_t idx = 0; idx < num_points; idx++)\n  {\n    const double x = dist(prng);\n    const double y = dist(prng);\n    random_points.at(idx) = Eigen::Vector4d(x, y, 0.0, 0.0);\n  }\n  std::function<double(const Eigen::Vector4d&, const Eigen::Vector4d&)>\n      distance_fn = [] (const Eigen::Vector4d& v1, const Eigen::Vector4d& v2)\n  {\n    return (v1 - v2).norm();\n  };\n  const std::vector<bool> use_parallel_options = {false, true};\n  for (const bool use_parallel : use_parallel_options)\n  {\n    // Cluster using index-cluster methods\n    // Single-link clustering\n    std::cout << \"Single-link hierarchical index clustering \" << num_points\n              << \" points...\" << std::endl;\n    const auto slhic_start = std::chrono::steady_clock::now();\n    const auto single_link_index_clusters\n        = common_robotics_utilities::simple_hierarchical_clustering\n            ::IndexCluster(\n                random_points, distance_fn, 1.0,\n                common_robotics_utilities::simple_hierarchical_clustering\n                    ::ClusterStrategy::SINGLE_LINK, use_parallel);\n    const auto slhic_end = std::chrono::steady_clock::now();\n    const double slhic_elapsed =\n        std::chrono::duration<double>(slhic_end - slhic_start).count();\n    std::cout << \"...took \" << slhic_elapsed << \" seconds\" << std::endl;\n    // Save\n    SaveIndexClustering(\n        random_points, single_link_index_clusters, (use_parallel)\n            ? \"/tmp/test_parallel_single_link_index_clustering.csv\"\n            : \"/tmp/test_serial_single_link_index_clustering.csv\");\n    // Complete-link clustering\n    std::cout << \"Complete-link hierarchical index clustering \" << num_points\n              << \" points...\" << std::endl;\n    const auto clhic_start = std::chrono::steady_clock::now();\n    const auto complete_link_index_clusters\n        = common_robotics_utilities::simple_hierarchical_clustering\n            ::IndexCluster(\n                random_points, distance_fn, 1.0,\n                common_robotics_utilities::simple_hierarchical_clustering\n                    ::ClusterStrategy::COMPLETE_LINK, use_parallel);\n    const auto clhic_end = std::chrono::steady_clock::now();\n    const double clhic_elapsed =\n        std::chrono::duration<double>(clhic_end - clhic_start).count();\n    std::cout << \"...took \" << clhic_elapsed << \" seconds\" << std::endl;\n    // Save\n    SaveIndexClustering(\n        random_points, complete_link_index_clusters, (use_parallel)\n            ? \"/tmp/test_parallel_complete_link_index_clustering.csv\"\n            : \"/tmp/test_serial_complete_link_index_clustering.csv\");\n    // Cluster using value-cluster methods\n    // Single-link clustering\n    std::cout << \"Single-link hierarchical clustering \" << num_points\n              << \" points...\" << std::endl;\n    const auto slhc_start = std::chrono::steady_clock::now();\n    const auto single_link_clusters\n        = common_robotics_utilities::simple_hierarchical_clustering::Cluster(\n            random_points, distance_fn, 1.0,\n            common_robotics_utilities::simple_hierarchical_clustering\n                ::ClusterStrategy::SINGLE_LINK, use_parallel);\n    const auto slhc_end = std::chrono::steady_clock::now();\n    const double slhc_elapsed =\n        std::chrono::duration<double>(slhc_end - slhc_start).count();\n    std::cout << \"...took \" << slhc_elapsed << \" seconds\" << std::endl;\n    // Save\n    SaveClustering(single_link_clusters, (use_parallel)\n        ? \"/tmp/test_parallel_single_link_clustering.csv\"\n        : \"/tmp/test_serial_single_link_clustering.csv\");\n    // Complete-link clustering\n    std::cout << \"Complete-link hierarchical clustering \" << num_points\n              << \" points...\" << std::endl;\n    const auto clhc_start = std::chrono::steady_clock::now();\n    const auto complete_link_clusters\n        = common_robotics_utilities::simple_hierarchical_clustering::Cluster(\n            random_points, distance_fn, 1.0,\n            common_robotics_utilities::simple_hierarchical_clustering\n                ::ClusterStrategy::COMPLETE_LINK, use_parallel);\n    const auto clhc_end = std::chrono::steady_clock::now();\n    const double clhc_elapsed =\n        std::chrono::duration<double>(clhc_end - clhc_start).count();\n    std::cout << \"...took \" << clhc_elapsed << \" seconds\" << std::endl;\n    // Save\n    SaveClustering(complete_link_clusters, (use_parallel)\n        ? \"/tmp/test_parallel_complete_link_clustering.csv\"\n        : \"/tmp/test_serial_complete_link_clustering.csv\");\n    // Cluster using K-means\n    const int32_t num_clusters = 50;\n    std::cout << \"K-means clustering \" << num_points << \" points into \"\n              << num_clusters << \" clusters...\" << std::endl;\n    std::function<Eigen::Vector4d(const PointVector&)>\n        average_fn = [] (const PointVector& cluster)\n    {\n      return common_robotics_utilities::math::AverageEigenVector4d(cluster);\n    };\n    const auto kmeans_start = std::chrono::steady_clock::now();\n    const std::vector<int32_t> kmeans_labels\n        = common_robotics_utilities::simple_kmeans_clustering::Cluster(\n            random_points, distance_fn, average_fn, num_clusters, 42, true,\n            use_parallel);\n    const auto kmeans_end = std::chrono::steady_clock::now();\n    const double kmeans_elapsed =\n        std::chrono::duration<double>(kmeans_end - kmeans_start).count();\n    std::cout << \"...took \" << kmeans_elapsed << \" seconds\" << std::endl;\n    // Get value clusters from the K-means labels\n    std::vector<PointVector> kmeans_clusters(num_clusters);\n    for (size_t idx = 0; idx < kmeans_labels.size(); idx++)\n    {\n      const size_t cluster_num = static_cast<size_t>(kmeans_labels.at(idx));\n      kmeans_clusters.at(cluster_num).push_back(random_points.at(idx));\n    }\n    // Save\n    SaveClustering(complete_link_clusters, (use_parallel)\n        ? \"/tmp/test_parallel_kmeans_clustering.csv\"\n        : \"/tmp/test_serial_kmeans_clustering.csv\");\n  }\n  std::cout << \"Done saving, you can plot as a 3d scatterplot to see clustering\"\n            << std::endl;\n  return 0;\n}\n", "meta": {"hexsha": "cfbee0d86cd363a7235b06bc46b2067436d96e22", "size": 8476, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/clustering_example.cpp", "max_stars_repo_name": "hidmic/common_robotics_utilities", "max_stars_repo_head_hexsha": "b3e10e0e0bfa9a968efdaa57e0a4422d9327bb9c", "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": "example/clustering_example.cpp", "max_issues_repo_name": "hidmic/common_robotics_utilities", "max_issues_repo_head_hexsha": "b3e10e0e0bfa9a968efdaa57e0a4422d9327bb9c", "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": "example/clustering_example.cpp", "max_forks_repo_name": "hidmic/common_robotics_utilities", "max_forks_repo_head_hexsha": "b3e10e0e0bfa9a968efdaa57e0a4422d9327bb9c", "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": 43.4666666667, "max_line_length": 80, "alphanum_fraction": 0.6754365267, "num_tokens": 2014, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859598, "lm_q2_score": 0.6334102775181399, "lm_q1q2_score": 0.4853782691274643}}
{"text": "/*! \\file perlinNoise.hxx\n *  \\brief breastPhantom Perlin Noise header file\n *  \\author Christian G. Graff\n *  \\version 1.0\n *  \\date 2018\n *  \n *  \\copyright To the extent possible under law, the author(s) have\n *  dedicated all copyright and related and neighboring rights to this\n *  software to the public domain worldwide. This software is\n *  distributed without any warranty.  You should have received a copy\n *  of the CC0 Public Domain Dedication along with this software.\n *  If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.\n * \n */\n\n#ifndef PERLINNOISE_HXX_\n#define PERLINNOISE_HXX_\n\n#ifndef __BOOST__\n#define __BOOST__\n#include <boost/random.hpp>\n#include <boost/math/distributions/beta.hpp>\n#include <boost/program_options.hpp>\n#endif\n\nclass perlinNoise{\n\t \nprivate:\n  double frequency;\n  double lacunarity;\n  double persistence;\n  int numOctaves;\n  int32_t seed;\n  int32_t xNoiseGen,yNoiseGen,zNoiseGen,seedNoiseGen,shiftNoiseGen;\n  double makeInt32Range(double x);\n  double pInterp(double x);\n  double linInterp(double lbound, double rbound, double x);\n  double coherentNoise(double x, double y, double z, int32_t mySeed);\n  double gradientNoise(double x, double y, double z, \n\t\t       int32_t ia, int32_t ib, int32_t ic, int32_t mySeed);\n\t\npublic:\n  double getNoise(double* r);\n  void setSeed(int32_t inSeed);\n  perlinNoise(boost::program_options::variables_map vm, int32_t inSeed, const char* type);\n  perlinNoise(boost::program_options::variables_map vm, int32_t inSeed, double freq, double lac, double pers, int oct);\n  perlinNoise(boost::program_options::variables_map vm, const char* type);\t\t\n};\n\n#endif /* PERLINNOISE_HXX_ */\n\n\t\n\t\t\n", "meta": {"hexsha": "4d526b5b79caf28d4833404156dcb7950f0cfaa7", "size": 1670, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "perlinNoise.hxx", "max_stars_repo_name": "rtmass/breastPhantom", "max_stars_repo_head_hexsha": "a852077b3cb0ca9ba2e2c16d12fe34d00808d641", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-12-27T20:34:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-14T09:52:49.000Z", "max_issues_repo_path": "perlinNoise.hxx", "max_issues_repo_name": "rtmass/breastPhantom", "max_issues_repo_head_hexsha": "a852077b3cb0ca9ba2e2c16d12fe34d00808d641", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-10-14T14:39:21.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-16T16:45:38.000Z", "max_forks_repo_path": "perlinNoise.hxx", "max_forks_repo_name": "rtmass/breastPhantom", "max_forks_repo_head_hexsha": "a852077b3cb0ca9ba2e2c16d12fe34d00808d641", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2018-12-08T00:15:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T17:55:33.000Z", "avg_line_length": 30.9259259259, "max_line_length": 119, "alphanum_fraction": 0.7467065868, "num_tokens": 447, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6334102775181399, "lm_q1q2_score": 0.48537826912746423}}
{"text": "#include <iostream>\n#include <fstream>\n#include <vector>\n#include <string>\n\n#include <vigra/impex.hxx>\n#include <vigra/multi_array.hxx>\n\n#include <opencv/cv.hpp>\n\n#include <boost/program_options.hpp>\n\n#include \"sift.hpp\"\n#include \"interestpoint.hpp\"\n\nnamespace po = boost::program_options;\n\n/*\n * Main Function takes a greyvalue image as input\n */\nint main(int argc, char** argv) {\n    std::string img_file;\n    f32_t sigma, k; \n    u16_t octaves, dogsPerEpoch; \n    bool subpixel;\n    bool result;\n\n    po::options_description desc(\"Options\");\n\n    desc.add_options() \n        (\"help\", \"Print help messages\") \n        (\"img,i\", po::value<std::string>(&img_file), \"The image on which sift will be executed\")\n        (\"sigma,s\", po::value<f32_t>(&sigma)->default_value(1.6), \"The sigma value of the Gaussian calculations\")\n        (\"k,k\", po::value<f32_t>(&k)->default_value(std::sqrt(2)), \"The constant which is calculated on sigma for the DoGs\")\n        (\"octaves,o\", po::value<u16_t>(&octaves)->default_value(4), \"How many octaves should be calculated\")\n        (\"dogsPerEpoch,d\", po::value<u16_t>(&dogsPerEpoch)->default_value(3), \"How many DoGs should be created per epoch\")\n        (\"subpixel,p\", po::value<bool>(&subpixel)->default_value(false), \"Starts with the doubled size of initial image\")\n        (\"result,r\", po::value<bool>(&result)->default_value(false), \"Print the resulting InterestPoints in a file\")\n        ;  \n    po::positional_options_description p; \n    p.add(\"img\", 1);\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\n        if (vm.count(\"help\")) {\n            std::cout << desc << \"\\n\";\n            return 1;\n        }\n\n        vigra::ImageImportInfo info(img_file.c_str());\n        vigra::MultiArray<2, f32_t> img(vigra::Shape2(info.shape()));\n        vigra::importImage(info, img);\n\n        sift::Sift sift(dogsPerEpoch, octaves, sigma, k, subpixel);\n        std::vector<sift::InterestPoint> interestPoints = sift.calculate(img);\n\n        auto image = cv::imread(img_file.c_str(), CV_LOAD_IMAGE_COLOR);\n        u16_t subpixel_divisor = sift.subpixel ? 2 : 1;\n        for (const sift::InterestPoint& p : interestPoints) {\n            u16_t x = (p.loc.x * std::pow(2, p.octave)) / subpixel_divisor;\n            u16_t y = (p.loc.y * std::pow(2, p.octave)) / subpixel_divisor;\n            cv::RotatedRect r(cv::Point2f(x, y), \n                    cv::Size(p.scale * 10, p.scale * 10),\n                    p.orientation);\n\n            cv::Point2f points[4]; \n            r.points( points );\n            cv::line(image, points[0], points[1], cv::Scalar(255, 0, 0));\n            cv::line(image, points[0], points[3], cv::Scalar(255, 0, 0));\n            cv::line(image, points[2], points[3], cv::Scalar(255, 0, 0));\n            cv::line(image, points[1], points[2], cv::Scalar(255, 0, 0));\n        }\n\n        cv::imwrite(img_file + \"_orientation.png\", image);\n\n        if (result) {\n            std::ofstream out(\"interstpoints.txt\");\n            out << \"Location\\tscale\\torientation\\tdescriptors\\n\";\n            for (const sift::InterestPoint& p : interestPoints) {\n               out << \"[\" << p.loc.x << \", \" << p.loc.y <<  \"]\\t\" << p.scale << \"\\t\" << p.orientation << \"\\t\" << \"[\";\n               for (f32_t d : p.descriptors) {\n                   out << d << \", \";\n               }\n               out << \"]\\n\";\n            }\n            out.close();\n        }\n    } catch (std::exception& ex) {\n        std::cerr << ex.what() << std::endl;\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "3f25c806ec7127c6ed5a9869039e9caa2f36a2c7", "size": 3596, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "snowiow/SIFT", "max_stars_repo_head_hexsha": "83364b87f60cd8c859a058fb67f4cf321e016a07", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 41.0, "max_stars_repo_stars_event_min_datetime": "2016-04-21T21:15:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-12T02:46:54.000Z", "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "snowiow/SIFT", "max_issues_repo_head_hexsha": "83364b87f60cd8c859a058fb67f4cf321e016a07", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2015-06-09T07:10:18.000Z", "max_issues_repo_issues_event_max_datetime": "2017-07-17T08:09:11.000Z", "max_forks_repo_path": "main.cpp", "max_forks_repo_name": "snowiow/SIFT", "max_forks_repo_head_hexsha": "83364b87f60cd8c859a058fb67f4cf321e016a07", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2017-02-28T06:11:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-21T04:46:53.000Z", "avg_line_length": 37.4583333333, "max_line_length": 124, "alphanum_fraction": 0.5703559511, "num_tokens": 974, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936537604181, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.485378265283042}}
{"text": "#include <sparse.h>\n\n#include <sparse_fill.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n\nBOOST_AUTO_TEST_SUITE(SPARSE);\n\nBOOST_AUTO_TEST_CASE(product_block_test)\n{  \n  // scalar case\n  typedef sparse::Block<1,1,float> block_type1;\n  \n  block_type1 s1(5), s2(2), s3(0);\n  \n  sparse::prod(s1,s2,s3);\n  BOOST_CHECK(s3[0] == 5*2);\n  \n  // block case\n  sparse::Block<4,3,float> a;\n  sparse::Block<3,3,float> b;\n  sparse::Block<4,3,float> c(sparse::zero_block< sparse::Block<4,3,float> >() );\n  sparse::fill(a, 1);\n  sparse::fill(b, 1);\n  sparse::prod(a,b,c);\n  \n  BOOST_CHECK( c[0] ==  30 );\n  BOOST_CHECK( c[1] ==  36 );\n  BOOST_CHECK( c[2] ==  42 );\n  BOOST_CHECK( c[3] ==  66 );\n  BOOST_CHECK( c[4] ==  81 );\n  BOOST_CHECK( c[5] ==  96 );\n  BOOST_CHECK( c[6] == 102 );\n  BOOST_CHECK( c[7] == 126 );\n  BOOST_CHECK( c[8] == 150 );\n  BOOST_CHECK( c[9] == 138 );\n  BOOST_CHECK( c[10] == 171 );\n  BOOST_CHECK( c[11] == 204 );\n  \n}\n\nBOOST_AUTO_TEST_SUITE_END();\n\n", "meta": {"hexsha": "7628a7d4eec6f90f8beff73d04c3dee09e00a462", "size": 1115, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/FOUNDATION/SPARSE/unit_tests/sparse_product_block/sparse_product_block.cpp", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-11-27T09:44:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-13T00:24:21.000Z", "max_issues_repo_path": "PROX/FOUNDATION/SPARSE/unit_tests/sparse_product_block/sparse_product_block.cpp", "max_issues_repo_name": "erleben/matchstick", "max_issues_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_issues_repo_licenses": ["MIT"], "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/FOUNDATION/SPARSE/unit_tests/sparse_product_block/sparse_product_block.cpp", "max_forks_repo_name": "erleben/matchstick", "max_forks_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_forks_repo_licenses": ["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.2291666667, "max_line_length": 80, "alphanum_fraction": 0.6385650224, "num_tokens": 380, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.63341027059799, "lm_q1q2_score": 0.4853782570632856}}
{"text": "//! \\file examples/Arrangement_on_surface_2/bgl_dual_adapter.cpp\n// Adapting the dual of an arrangement to a BGL graph.\n\n#include <CGAL/config.h>\n\n#include <boost/graph/breadth_first_search.hpp>\n#include <boost/graph/visitors.hpp>\n\n#include <CGAL/Arr_extended_dcel.h>\n#include <CGAL/graph_traits_dual_arrangement_2.h>\n#include <CGAL/Arr_face_index_map.h>\n\n#include \"Extended_face_property_map.h\"\n#include \"arr_exact_construction_segments.h\"\n#include \"arr_print.h\"\n\ntypedef CGAL::Arr_face_extended_dcel<Traits, unsigned int> Dcel;\ntypedef CGAL::Arrangement_2<Traits, Dcel>                  Ex_arrangement;\ntypedef CGAL::Dual<Ex_arrangement>                         Dual_arrangement;\ntypedef CGAL::Arr_face_index_map<Ex_arrangement>           Face_index_map;\ntypedef Extended_face_property_map<Ex_arrangement,unsigned int>\n                                                           Face_property_map;\n\nint main() {\n  // Construct an arrangement of seven intersecting line segments.\n  Point p1(1, 1), p2(1, 4), p3(2, 2), p4(3, 7), p5(4, 4), p6(7, 1), p7(9, 3);\n  Ex_arrangement  arr;\n  insert(arr, Segment(p1, p6));\n  insert(arr, Segment(p1, p4));  insert(arr, Segment(p2, p6));\n  insert(arr, Segment(p3, p7));  insert(arr, Segment(p3, p5));\n  insert(arr, Segment(p6, p7));  insert(arr, Segment(p4, p7));\n\n  // Create a mapping of the arrangement faces to indices.\n  Face_index_map index_map(arr);\n\n  // Perform breadth-first search from the unbounded face, using the event\n  // visitor to associate each arrangement face with its discover time.\n  int time = -1;\n  boost::breadth_first_search(Dual_arrangement(arr), arr.unbounded_face(),\n                              boost::vertex_index_map(index_map).visitor\n                              (boost::make_bfs_visitor\n                               (stamp_times(Face_property_map(), time,\n                                            boost::on_discover_vertex()))));\n\n  // Print the discover time of each arrangement face.\n  for (auto fit = arr.faces_begin(); fit != arr.faces_end(); ++fit) {\n    std::cout << \"Discover time \" << fit->data() << \" for \";\n    if (fit != arr.unbounded_face()) {\n      std::cout << \"face \";\n      print_ccb<Ex_arrangement>(fit->outer_ccb());\n    }\n    else std::cout << \"the unbounded face.\\n\";\n  }\n  return 0;\n}\n", "meta": {"hexsha": "14b2dffee916188258bf0219df28900434f394f9", "size": 2287, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Arrangement_on_surface_2/examples/Arrangement_on_surface_2/bgl_dual_adapter.cpp", "max_stars_repo_name": "ffteja/cgal", "max_stars_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 3227.0, "max_stars_repo_stars_event_min_datetime": "2015-03-05T00:19:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:20:35.000Z", "max_issues_repo_path": "Arrangement_on_surface_2/examples/Arrangement_on_surface_2/bgl_dual_adapter.cpp", "max_issues_repo_name": "ffteja/cgal", "max_issues_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 5574.0, "max_issues_repo_issues_event_min_datetime": "2015-03-05T00:01:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:08:11.000Z", "max_forks_repo_path": "Arrangement_on_surface_2/examples/Arrangement_on_surface_2/bgl_dual_adapter.cpp", "max_forks_repo_name": "ffteja/cgal", "max_forks_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1274.0, "max_forks_repo_forks_event_min_datetime": "2015-03-05T00:01:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:47:56.000Z", "avg_line_length": 40.8392857143, "max_line_length": 77, "alphanum_fraction": 0.6488850022, "num_tokens": 583, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.766293653760418, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.48537825467730783}}
{"text": "//\n// Created by Liuyu Jin on Jun 9, 2016.\n//\n\n#include \"ICLasso.hpp\"\n#include <Eigen/Dense>\n#include <boost/math/distributions.hpp>\n#include <math.h>\n#include <unordered_map>\n#include <iostream>\n\n#ifdef BAZEL\n#include \"model/ModelOptions.hpp\"\n#else\n#include \"ModelOptions.hpp\"\n#endif\n\nusing namespace Eigen;\nusing namespace std;\n\n\nICLasso::ICLasso() {\n    lambda1 = 1;\n    lambda2 = 1;\n    gamma = 1;\n};\n\nvoid ICLasso::set_X(MatrixXf new_X){\n    X = new_X;\n};\n\nvoid ICLasso::set_Y(MatrixXf new_Y){\n    Y = new_Y;\n};\n\nvoid ICLasso::set_XY(MatrixXf new_X, MatrixXf new_Y){\n    X = new_X;\n    Y = new_Y;\n    //initialize Beta here\n    Beta = MatrixXf::Random(X.cols(),Y.rows());\n};\n\nvoid ICLasso::set_lambda1(float new_l){\n    lambda1 = new_l;\n};\n\nvoid ICLasso::set_lambda2(float new_l){\n    lambda2 = new_l;\n};\n\nvoid ICLasso::set_gamma(float new_g){\n    gamma = new_g;\n};\n\nvoid ICLasso::set_theta(MatrixXf new_t){\n    Theta = new_t;\n};\n\n/* helpers for cost */\nfloat square(float a){\n    return a*a;\n};\n\nMatrixXf cov(MatrixXf X){\n  MatrixXf centered = X.rowwise() - X.colwise().mean();\n  MatrixXf result = (centered.adjoint() * centered) / float(X.rows() - 1);\n  return result;\n};\n\nfloat sign(float x){\n    if (x > 0) return 1;\n    if (x < 0) return -1;\n    return 0;\n};\n\n/* end helpers for cost */\n\nfloat ICLasso::cost() {\n    int n = X.cols();\n    MatrixXf YXBeta = Y-X*Beta;\n    MatrixXf squared = YXBeta.unaryExpr(std::ptr_fun(square));\n    float loss1 = squared.sum()/n;\n    float loss2 = (cov(Y)*Theta).trace() - log(Theta.determinant());\n    float pen1 = Beta.cwiseAbs().sum();\n    float pen2 = Theta.cwiseAbs().sum();\n    float pen3 = 0;\n    float incr;\n    int size_T = Theta.rows();\n    for (int i = 0; i < size_T; i++){\n        for (int j = i+1; j < size_T; j++){\n            incr = ((Beta.col(i) + sign(Theta(i,j))*Beta.col(j)).cwiseAbs().sum());\n            pen3 = pen3 + abs(Theta(i, j))*incr;\n        }\n    }\n    return loss1 + loss2 + lambda1 * pen1 + lambda2 * pen2 + gamma * pen3;\n};\n\n/* Helpers for optimize_theta */\nfloat cost_theta(MatrixXf S, MatrixXf Beta, MatrixXf Theta, float lambda, float gamma) {\n    float loss = (S*Theta).trace()-log(Theta.determinant());\n    float pen2 = Theta.cwiseAbs().sum();\n    float pen3 = 0;\n    int size_T = Theta.rows();\n    float incr;\n    for (int i = 0; i < size_T; i++){\n        for (int j = i+1; j < size_T; j++){\n            incr = ((Beta.col(i) + sign(Theta(i,j))*Beta.col(j)).cwiseAbs().sum());\n            pen3 = pen3 + abs(Theta(i, j))*incr;\n        }\n    }\n    return loss + lambda * pen2 + gamma * pen3;\n};\n\n\nMatrixXf remove_row(MatrixXf X, int j){\n    int numRows = X.rows()-1;\n    int numCols = X.cols();\n    MatrixXf result = MatrixXf::Zero(numRows, numCols);\n    result.block(0, 0, j, numCols) = X.block(0, 0, j, numCols);\n    result.block(j, 0, numRows-j, numCols) = X.block(j+1, 0, numRows-j, numCols);\n    return result;\n};\n\nMatrixXf remove_col(MatrixXf X, int j){\n    int numRows = X.rows();\n    int numCols = X.cols() - 1;\n    MatrixXf result = MatrixXf::Zero(numRows, numCols);\n    result.block(0, 0, numRows, j) = X.block(0, 0, numRows, j);\n    result.block(0, j, numRows, numCols - j) = X.block(0, j+1, numRows, numCols-j);\n    return result;\n};\n\nvoid change_theta(MatrixXf C, MatrixXf Theta, int j){\n    for (int i = 0; i < Theta.cols(); i++){\n        if (i != j){\n            Theta(i, j) = Theta(j, j) * C(i, j);\n        }\n    }\n};\n\nvoid symmetrize(MatrixXf Theta, int j){\n    for (int i = 0; i < Theta.cols(); i++){\n        if (i != j){\n            Theta(j, i) = Theta(i, j);\n        }\n    }\n};\n\nMatrixXf bound_below(MatrixXf X){\n    for (int i = 0; i < X.rows(); i++){\n        for (int j = 0; j < X.cols(); j++){\n            if (X(i, j) < 0){\n                X(i, j) = 0;\n            }\n        }\n    }\n    return X;\n}\n\nMatrixXf update_beta_mex(MatrixXf X, MatrixXf S, MatrixXf a,\n                     MatrixXf b, float lambda, float gamma, MatrixXf Beta){\n    int p = X.cols();\n    MatrixXf beta_new = MatrixXf::Zero(p, 1);\n    int k, j;\n    for (k = 0; k < p; k++) {\n        beta_new(k,0) = Beta(k, 0);\n    }\n    float beta_k, upper_k, lower_k;\n    for (k = 0; k < p; k++) {\n        beta_k = S(k, 0);\n        for (j = 0; j < p; j++) {\n            if (j != k)\n                beta_k += X(k,j)*beta_new(j, 0);\n        }\n        beta_k = -1*beta_k/X(k, k);\n        upper_k = (gamma*a(k,0) + lambda)/X(k, k);\n        lower_k = -1*(gamma*b(k,0) + lambda)/X(k, k);\n        if (beta_k > upper_k) {\n            beta_new(k,0) = beta_k - upper_k;\n        } else if (beta_k < lower_k) {\n            beta_new(k,0) = beta_k - lower_k;\n        } else {\n            beta_new(k,0) = 0;\n        }\n    }\n    return beta_new;\n}\n\nMatrixXf optimize_block_coord_sigma(MatrixXf X,\n       MatrixXf S, int maxiter, MatrixXf a, MatrixXf b, float lambda,\n       float gamma){\n    int p = X.cols();\n    MatrixXf Beta = MatrixXf::Zero(p, 1);\n    MatrixXf oldBeta;\n    for (int i = 0; i < maxiter; i++){\n        oldBeta = Beta;\n        Beta = update_beta_mex(X,S,a,b,lambda,gamma,Beta);\n        if ((Beta-oldBeta).norm() < 1e-3) break;\n    }\n    return -X*(bound_below(Beta)-bound_below(-Beta));\n}\n\nMatrixXf optimize_block_coord_beta(MatrixXf X,\n    MatrixXf S, int maxiter, MatrixXf a, MatrixXf b, float lambda, float gamma){\n    int p = X.cols();\n    MatrixXf Beta = MatrixXf::Zero(p, 1);\n    MatrixXf oldBeta;\n    for (int i = 0; i < maxiter; i++){\n        oldBeta = Beta;\n        Beta = update_beta_mex(X,S,a,b,lambda,gamma,Beta);\n        if ((Beta-oldBeta).norm() < 1e-3) break;\n    }\n    return Beta;\n}\n\nMatrixXf fused_prox_vector(MatrixXf beta, MatrixXf u, MatrixXf l){\n    int len = beta.rows();\n    MatrixXf w = MatrixXf::Zero(len, 1);\n    for (int i = 0; i < len; i++){\n        float beta_c = beta(i, 0);\n        if (beta_c > u(i, 0)){\n            beta(i, 0) = beta_c - u(i, 0);\n        } else if (beta_c < l(i, 0)){\n            beta(i, 0) = beta_c - l(i, 0);\n        }\n    }\n    return w;\n\n}\n\n\nfloat fused_prox_scalar(float beta, float u, float l){\n    if (beta > u){\n        return beta - u;\n    } else if (beta < l){\n        return beta - l;\n    } else {\n        return 0;\n    }\n}\n\n\nMatrixXf cwiseAdd(MatrixXf X, float p){\n    for (int i = 0; i < X.rows(); i++){\n        for (int j = 0; j < X.cols(); j++){\n            X(i, j) = X(i, j) + p;\n        }\n    }\n    return X;\n}\n\n/* type issues with Q and h_beta */\n\nMatrixXf optimize_block_prox(MatrixXf X,\n     MatrixXf s, int maxiter, MatrixXf a, MatrixXf b, float lambda, float gamma){\n\n    //get dimension\n    int n = X.rows();\n\n    //initialize variables\n    MatrixXf Beta = MatrixXf::Zero(n, 1);\n    MatrixXf w = Beta;\n    float theta = 1;\n    float L = 10;\n    MatrixXf objVals = MatrixXf::Zero(maxiter, 1);\n\n    MatrixXf h_w, grad, z, beta_new, upper, lower;\n    float h_beta, Q;\n    float theta_new;\n\n    //optimize Beta\n    for (int iter = 0; iter < maxiter; iter++){\n        //computer gradient\n        grad = (X*w) + s;\n\n        //compute new estimate of beta using line search\n        h_w = w.transpose()*X*w/2 + s.transpose()*w;\n        while (true){\n            z = w - (1/L)*grad;\n            upper = cwiseAdd(gamma*a, lambda)/L;\n            lower = -cwiseAdd(gamma*b, lambda)/L;\n            beta_new = fused_prox_vector(z,upper,lower);\n            h_beta = ((beta_new.transpose()*X*beta_new)/2 + (s.transpose()*beta_new))(0, 0);\n            Q = (h_w + (beta_new-w).transpose()*grad)(0,0)+\n                L*((beta_new-w).cwiseProduct(beta_new-w)).sum()/2;\n            if (h_beta <= Q) break;\n            else L = 2*L;\n\n            //update w and theta\n            theta_new = (1 + sqrt(1 + 4*theta*theta))/2;\n            w = beta_new + (theta-1)/(theta_new)*(beta_new-Beta);\n\n            //store current objective value\n            objVals(iter, 0) = h_beta + (cwiseAdd(gamma*a, lambda).transpose()*bound_below(beta_new))(0,0) + \n                               (cwiseAdd(gamma*b, lambda).transpose()*bound_below(-beta_new))(0, 0);\n\n            //store new variables\n            Beta = beta_new;\n            theta = theta_new;\n            if (iter >= 5 && abs(objVals(iter, 0)-objVals(iter-1, 0))/abs(objVals(iter-1, 0)) < 1e-8)\n            break;\n\n\n        }\n    }\n\n    //calculate sigma\n    MatrixXf sigma = -X*(bound_below(beta_new)-bound_below(-beta_new));\n    return sigma;\n\n\n}\n\n\n\n/* end helpers for optimize_theta */\n\nvoid ICLasso::optimize_theta(){\n\n    int q = Y.rows();\n\n    //precompute sample covariance & penalty matrices\n    MatrixXf S = cov(Y);\n    MatrixXf A = MatrixXf::Zero(q, q);\n    MatrixXf B = MatrixXf::Zero(q, q);\n    for (int j = 0; j < q; j++){\n        for (int k = 0; k < q; k++){\n            A(j, k) = (Beta.col(j) + Beta.col(k)).cwiseAbs().sum()/2;\n            B(j, k) = (Beta.col(j) - Beta.col(k)).cwiseAbs().sum()/2;\n        }\n        A(j, j) = 0;\n        B(j, j) = 0;\n    }\n    int maxiter = 10000;\n    float tol = 1e-4;\n    MatrixXf C, s, a, b;\n\n    //store objective values and run times\n    MatrixXf objVals = MatrixXf::Zero(maxiter, 1);\n\n    //initialize values;\n    MatrixXf Sigma = S + lambda * MatrixXf::Identity(q, q);\n\n    int i = 0;\n    //run optimization to obtain estimate of covariance\n    for (int iter = 0; iter < maxiter; iter++){\n        //iterate through each block\n        C = MatrixXf::Zero(q, q);\n        for (int j = 0; j < q; j++){\n            X = remove_col(remove_row(Sigma, j), j);\n            s = remove_row(S, j);\n            a = remove_row(A, j);\n            b = remove_row(B, j);\n\n            MatrixXf sigma_j, beta;\n            sigma_j = optimize_block_coord_sigma(X, s, maxiter, a, b, lambda, gamma);\n            beta = optimize_block_coord_beta(X, s, maxiter, a, b, lambda, gamma);\n            for (i = 0; i < S.rows(); i++){\n                if (i != j) {\n                    Sigma(i, j) = sigma_j(i, 0);\n                    Sigma(j, i) = sigma_j(i, 0);\n                }\n            }\n            //store beta\n            for (i = 0; i < C.rows(); i++){\n                if (i != j){\n                    C(i, j) = beta(i, 0);\n                }\n            }\n        }\n        objVals(iter) = cost_theta(S, Beta, Sigma.inverse(), lambda, gamma);\n        //check for convergence \n        if (iter >= 10 && abs(objVals(iter)-objVals(iter-1))/abs(objVals(iter-1)) < tol)\n        {break;}\n\n    }\n\n\n\n\n    //calculate inverse covariance\n    Theta = MatrixXf::Zero(q, q);\n    for (int j = 0; j < q; j++){\n        MatrixXf removed_Sigma = remove_row(Sigma, j);\n        MatrixXf removed_C = remove_row(C, j);\n        Theta(j, j) = 1/(Sigma(j, j) + \n               (removed_Sigma.col(j).transpose() * removed_C.col(j))(0, 0));\n        change_theta(C, Theta, j);\n        symmetrize(Theta, j);\n    }\n\n};\n", "meta": {"hexsha": "9ad3d782aa4ab0482854dac0f605eb139fe2d81b", "size": 10684, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Models/ICLasso.cpp", "max_stars_repo_name": "blengerich/jenkins_test", "max_stars_repo_head_hexsha": "512aec681577063e3d68f699d19f53374e59585a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2016-10-20T00:36:31.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-06T16:40:52.000Z", "max_issues_repo_path": "src/Models/ICLasso.cpp", "max_issues_repo_name": "blengerich/jenkins_test", "max_issues_repo_head_hexsha": "512aec681577063e3d68f699d19f53374e59585a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 44.0, "max_issues_repo_issues_event_min_datetime": "2016-11-11T22:41:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-04T21:55:57.000Z", "max_forks_repo_path": "src/Models/ICLasso.cpp", "max_forks_repo_name": "blengerich/jenkins_test", "max_forks_repo_head_hexsha": "512aec681577063e3d68f699d19f53374e59585a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-02-01T09:19:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-28T14:40:43.000Z", "avg_line_length": 27.1857506361, "max_line_length": 109, "alphanum_fraction": 0.5330400599, "num_tokens": 3317, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6334102567576901, "lm_q1q2_score": 0.4853782532188635}}
{"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_REM_HPP_INCLUDED\n#define BOOST_SIMD_TOOLBOX_ARITHMETIC_FUNCTIONS_SCALAR_REM_HPP_INCLUDED\n#include <boost/simd/toolbox/arithmetic/functions/rem.hpp>\n#include <boost/simd/include/functions/scalar/idivfix.hpp>\n/////////////////////////////////////////////////////////////////////////////\n//  The rem function computes the floating-point remainder of dividing x by y.\n//  The return value is x - n * y, where n is the quotient of x / y, rounded\n//  toward zero to an integer.\n//  The fmod function is just an alias for the same thing.\n/////////////////////////////////////////////////////////////////////////////\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::rem_, tag::cpu_\n                            , (A0)\n                            , (scalar_< arithmetic_<A0> >)(scalar_< arithmetic_<A0> >)\n                            )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    {\n      if (a1) return a0%a1; else return a0;\n    }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::rem_, tag::cpu_\n                            , (A0)\n                            , (scalar_< floating_<A0> >)(scalar_< floating_<A0> >)\n                            )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    {\n      if (a1) return a0-a1*idivfix(a0,a1);  else return a0;\n    }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "0a33a33b82aa915647108b431584d41727427ea3", "size": 1956, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/arithmetic/include/boost/simd/toolbox/arithmetic/functions/scalar/rem.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/rem.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/rem.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.9183673469, "max_line_length": 86, "alphanum_fraction": 0.5194274029, "num_tokens": 439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6334102567576901, "lm_q1q2_score": 0.4853782532188635}}
{"text": "//eigen shits up the compiler outside of optimized builds\n//all this stuff is compatible with eigen's shit\n\n#define EIGEN_VECTORIZE_SSE4_2\n\n#include <complex>\n#include <iostream>\n#include <cstdlib>\n#include <vector>\n#include <memory>\n#include <utility>\n#include <tuple>\n#include <array>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/LU>\n#include <Eigen/Geometry>\n#include <Eigen/SVD>\n#include <Eigen/SparseCore>\n#include <Eigen/SparseLU>\n\nusing namespace std;\nusing namespace Eigen;\n\n#define todo\n#include \"linear_algebra_header.h\"\n\nusing namespace std;\nusing namespace Eigen;\n\ntemplate<int num, class type> Matrix<type, num, num> eigen_read_matrix(const type* d) {\n    Matrix<type, num, num> res;\n    for (int y=0;y<num;++y) {\n        for (int x=0;x<num;++x) {\n            res(y, x)=d[y*num+x];\n        }\n    }\n    return res;\n}\n\ntemplate<int num, class type, class matrix> void eigen_assign_matrix(type* out, const matrix& d) {\n    for (int y=0;y<num;++y) {\n        for (int x=0;x<num;++x) {\n            out[y*num+x]=d(y, x);\n        }\n    }\n}\n\ntemplate<class type> Quaternion<type> eigen_read_quaternion(const type* d) {\n    return Quaternion<type>(d[0], d[1], d[2], d[3]);\n}\n\ntemplate<class type, class quaternion> void eigen_assign_quaternion(type* out, const quaternion& d) {\n    out[0]=d.w();\n    out[1]=d.x();\n    out[2]=d.y();\n    out[3]=d.z();\n}\n\ntemplate<class type1, class type2, unsigned long size> array<type2, size> solve_least_squares_impl(\n    const vector<array<type1, size>>& A,\n    const vector<type2>& b\n) {\n    assert(A.size()==b.size());\n\n    //Matrix<type2, Dynamic, Dynamic> A_matrix(b.size(), size); todo //slow\n    Matrix<type1, Dynamic, size> A_matrix(b.size(), size);\n    Matrix<type2, Dynamic, 1> b_matrix(b.size());\n\n    for (int i=0;i<b.size();++i) {\n        for (int j=0;j<size;++j) {\n            A_matrix(i, j)=A[i][j];\n        }\n        b_matrix[i]=b[i];\n    }\n\n    Matrix<type2, size, 1> x_matrix=\n        (A_matrix.transpose() * A_matrix).ldlt().solve(A_matrix.transpose() * b_matrix)\n    ;\n\n    /*todo //slow\n    Matrix<type2, size, 1> x_matrix=\n        A_matrix.bdcSvd(ComputeThinU | ComputeThinV).solve(b_matrix)\n    ;*/\n\n    /*Matrix<type2, Dynamic, 1> error=A_matrix*x_matrix-b_matrix;\n    cerr << \"Error: \";\n    for (int i=0;i<size;++i) {\n        cerr << error[i] << \", \";\n    }\n    cerr << \"\\n\";*/\n\n    array<type2, size> res;\n    for (int i=0;i<size;++i) {\n        res[i]=x_matrix[i];\n    }\n    return res;\n}\n\ntemplate<class type> void solve_equations_impl(\n    const vector<tuple<int, int, type>>& A,\n    const vector<type>& b,\n    vector<type>& x\n) {\n    const type error_scale=1e-5f;\n\n    vector<Triplet<type>> triplets;\n    for (tuple<int, int, type> c : A) {\n        triplets.emplace_back(get<0>(c), get<1>(c), get<2>(c));\n    }\n\n    SparseMatrix<type> A_matrix(b.size(), b.size());\n    Matrix<type, Dynamic, 1> b_matrix(b.size());\n    Matrix<type, Dynamic, 1> x_matrix(b.size());\n\n    for (int i=0;i<b.size();++i) {\n        b_matrix[i]=b[i];\n    }\n\n    A_matrix.setFromTriplets(triplets.begin(), triplets.end());\n\n    SparseLU<SparseMatrix<type>> solver;\n\n    auto check_error=[&](int n) {\n        if (solver.info()!=0) {\n            cerr << \"solve_equations_impl error: \" <<  n << \", \" << solver.info() << \", \" << solver.lastErrorMessage() << \"\\n\";\n        }\n    };\n\n    solver.analyzePattern(A_matrix);\n    solver.factorize(A_matrix); check_error(0);\n    x_matrix=solver.solve(b_matrix);\n\n    x.clear();\n    for (int i=0;i<b.size();++i) {\n        x.push_back(x_matrix[i]);\n    }\n\n    //\n    //\n\n    auto rand_11=[&]() -> type {\n        return type(std::rand())*type(2.0/RAND_MAX)-type(1);\n    };\n\n    Matrix<type, Dynamic, 1> x_matrix_new=x_matrix;\n    type error_amount=error_scale*x_matrix.norm()/sqrt(b.size());\n    for (int i=0;i<b.size();++i) {\n        x_matrix_new[i]+=rand_11()*error_amount;\n    }\n    type x_error=(x_matrix_new-x_matrix).norm()/x_matrix.norm();\n\n    Matrix<type, Dynamic, 1> b_matrix_new=A_matrix*x_matrix_new;\n    type b_error=(b_matrix_new-b_matrix).norm()/b_matrix.norm();\n\n    cerr << \"solve_equations \" <<\n        \"x_error: \" << x_error << \", b_error: \" << b_error << \" \" <<\n        \"x/b: \" << x_error/b_error << \" \" <<\n    \"\\n\";\n}\n\nnamespace linear_algebra {\n    void solve_equations(\n        const vector<tuple<int, int, complex<double>>>& A,\n        const vector<complex<double>>& b,\n        vector<complex<double>>& x\n    ) {\n        solve_equations_impl(A, b, x);\n    }\n\n    array<complex<double>, 3> solve_least_squares(\n        const vector<array<double, 3>>& A,\n        const vector<complex<double>>& b\n    ) {\n        return solve_least_squares_impl(A, b);\n    }\n\n    array<complex<double>, 10> solve_least_squares(\n        const vector<array<double, 10>>& A,\n        const vector<complex<double>>& b\n    ) {\n        return solve_least_squares_impl(A, b);\n    }\n\n    void eigen_to_rotation_matrix(float* out, const float* q) {\n        eigen_assign_matrix<3>(out, eigen_read_quaternion(q).toRotationMatrix());\n    }\n\n    void eigen_to_rotation_matrix(double* out, const double* q) {\n        eigen_assign_matrix<3>(out, eigen_read_quaternion(q).toRotationMatrix());\n    }\n\n    void eigen_from_rotation_matrix(float* out, const float* m) {\n        eigen_assign_quaternion(out, Quaternion<float>(eigen_read_matrix<3>(m)));\n    }\n\n    void eigen_from_rotation_matrix(double* out, const double* m) {\n        eigen_assign_quaternion(out, Quaternion<double>(eigen_read_matrix<3>(m)));\n    }\n\n    void eigen_inverse_2(float* out, const float* m) {\n        eigen_assign_matrix<2>(out, eigen_read_matrix<2>(m).inverse());\n    }\n\n    void eigen_inverse_2(double* out, const double* m) {\n        eigen_assign_matrix<2>(out, eigen_read_matrix<2>(m).inverse());\n    }\n\n    void eigen_inverse_3(float* out, const float* m) {\n        eigen_assign_matrix<3>(out, eigen_read_matrix<3>(m).inverse());\n    }\n\n    void eigen_inverse_3(double* out, const double* m) {\n        eigen_assign_matrix<3>(out, eigen_read_matrix<3>(m).inverse());\n    }\n\n    void eigen_inverse_2(complex<float>* out, const complex<float>* m) {\n        eigen_assign_matrix<2>(out, eigen_read_matrix<2>(m).inverse());\n    }\n\n    void eigen_inverse_2(complex<double>* out, const complex<double>* m) {\n        eigen_assign_matrix<2>(out, eigen_read_matrix<2>(m).inverse());\n    }\n\n    void eigen_inverse_3(complex<float>* out, const complex<float>* m) {\n        eigen_assign_matrix<3>(out, eigen_read_matrix<3>(m).inverse());\n    }\n\n    void eigen_inverse_3(complex<double>* out, const complex<double>* m) {\n        eigen_assign_matrix<3>(out, eigen_read_matrix<3>(m).inverse());\n    }\n}\n", "meta": {"hexsha": "91d0bf73e8d6733d442b8f233638819e4953ca63", "size": 6645, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "geometry/linear_algebra.cpp", "max_stars_repo_name": "sundersoft2/utility", "max_stars_repo_head_hexsha": "9dadd9bc8680cf6ef2d7115bda56ab5f475c0543", "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": "geometry/linear_algebra.cpp", "max_issues_repo_name": "sundersoft2/utility", "max_issues_repo_head_hexsha": "9dadd9bc8680cf6ef2d7115bda56ab5f475c0543", "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": "geometry/linear_algebra.cpp", "max_forks_repo_name": "sundersoft2/utility", "max_forks_repo_head_hexsha": "9dadd9bc8680cf6ef2d7115bda56ab5f475c0543", "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.3974358974, "max_line_length": 127, "alphanum_fraction": 0.6192626035, "num_tokens": 1854, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.4853782517604188}}
{"text": "#include <gtest/gtest.h>\n#include <gmock/gmock.h>\n\n#include <waypoint_control/waypoint_controller.h>\n#include <boost/math/constants/constants.hpp>\n\nusing boost::math::double_constants::pi;\nusing std::abs;\nusing std::sqrt;\nusing std::pow;\n\nusing namespace waypoint_control;\n\nTEST(FeedbackTests, invalidOrientation)\n{\n  tf2::Transform robot;\n  Waypoint goal;\n\n  // Throw error if robot quaternion is invalid\n  ASSERT_THROW(Feedback(robot, goal), std::runtime_error);\n\n  // Set default orientation if waypoint quaternion is invalid\n  robot.setRotation(tf2::Quaternion(0.0, 0.0, 0.0, 1.0));\n  Feedback feedback(robot, goal);\n  EXPECT_NEAR(feedback.theta(), 0.0, 1.0e-6);\n}\n\nTEST(FeedbackTests, goalPoses)\n{\n  tf2::Transform robot;\n  robot.setRotation(tf2::Quaternion(0.0, 0.0, 0.0, 1.0));\n  Waypoint goal;\n  goal.pose.orientation.w = 1.0;\n  Feedback feedback;\n\n  goal.pose.position.x =  1.0;\n  goal.pose.position.y =  0.0;\n  feedback = Feedback(robot, goal);\n  EXPECT_NEAR(feedback.x(),     1.0, 1e-6);\n  EXPECT_NEAR(feedback.y(),     0.0, 1e-6);\n  EXPECT_NEAR(feedback.r(),     1.0, 1e-6);\n  EXPECT_NEAR(feedback.theta(), 0.0, 1e-6);\n\n  goal.pose.position.x =  1.0;\n  goal.pose.position.y =  1.0;\n  feedback = Feedback(robot, goal);\n  EXPECT_NEAR(feedback.x(),           1.0, 1e-6);\n  EXPECT_NEAR(feedback.y(),           1.0, 1e-6);\n  EXPECT_NEAR(feedback.r(),     sqrt(2.0), 1e-6);\n  EXPECT_NEAR(feedback.theta(),      pi/4, 1e-6);\n\n  goal.pose.position.x =  0.0;\n  goal.pose.position.y =  1.0;\n  feedback = Feedback(robot, goal);\n  EXPECT_NEAR(feedback.x(),           0.0, 1e-6);\n  EXPECT_NEAR(feedback.y(),           1.0, 1e-6);\n  EXPECT_NEAR(feedback.r(),     sqrt(1.0), 1e-6);\n  EXPECT_NEAR(feedback.theta(),      pi/2, 1e-6);\n\n  goal.pose.position.x = -1.0;\n  goal.pose.position.y =  1.0;\n  feedback = Feedback(robot, goal);\n  EXPECT_NEAR(feedback.x(),          -1.0, 1e-6);\n  EXPECT_NEAR(feedback.y(),           1.0, 1e-6);\n  EXPECT_NEAR(feedback.r(),     sqrt(2.0), 1e-6);\n  EXPECT_NEAR(feedback.theta(),    3*pi/4, 1e-6);\n\n  goal.pose.position.x = -1.0;\n  goal.pose.position.y =  0.0;\n  feedback = Feedback(robot, goal);\n  EXPECT_NEAR(feedback.x(),          -1.0, 1e-6);\n  EXPECT_NEAR(feedback.y(),           0.0, 1e-6);\n  EXPECT_NEAR(feedback.r(),     sqrt(1.0), 1e-6);\n  EXPECT_NEAR(feedback.theta(),        pi, 1e-6);\n\n  goal.pose.position.x = -1.0;\n  goal.pose.position.y = -1.0;\n  feedback = Feedback(robot, goal);\n  EXPECT_NEAR(feedback.x(),          -1.0, 1e-6);\n  EXPECT_NEAR(feedback.y(),          -1.0, 1e-6);\n  EXPECT_NEAR(feedback.r(),     sqrt(2.0), 1e-6);\n  EXPECT_NEAR(feedback.theta(),   -3*pi/4, 1e-6);\n\n  goal.pose.position.x =  0.0;\n  goal.pose.position.y = -1.0;\n  feedback = Feedback(robot, goal);\n  EXPECT_NEAR(feedback.x(),           0.0, 1e-6);\n  EXPECT_NEAR(feedback.y(),          -1.0, 1e-6);\n  EXPECT_NEAR(feedback.r(),     sqrt(1.0), 1e-6);\n  EXPECT_NEAR(feedback.theta(),     -pi/2, 1e-6);\n\n  goal.pose.position.x =  1.0;\n  goal.pose.position.y = -1.0;\n  feedback = Feedback(robot, goal);\n  EXPECT_NEAR(feedback.x(),           1.0, 1e-6);\n  EXPECT_NEAR(feedback.y(),          -1.0, 1e-6);\n  EXPECT_NEAR(feedback.r(),     sqrt(2.0), 1e-6);\n  EXPECT_NEAR(feedback.theta(),     -pi/4, 1e-6);\n}\n\nTEST(Feedback, robotPoses)\n{\n  tf2::Transform robot;\n  robot.setRotation(tf2::Quaternion(0.0, 0.0, 0.0, 1.0));\n  Waypoint goal;\n  goal.pose.position.x =  1.0;\n  goal.pose.position.y =  0.0;\n  goal.pose.orientation.w = 1.0;\n  Feedback feedback;\n\n  robot.setRotation(tf2::Quaternion(tf2::Vector3(0, 0, 1), pi/2));\n  feedback = Feedback(robot, goal);\n  EXPECT_NEAR(feedback.x(),         0.0, 1e-6);\n  EXPECT_NEAR(feedback.y(),        -1.0, 1e-6);\n  EXPECT_NEAR(feedback.r(),         1.0, 1e-6);\n  EXPECT_NEAR(feedback.theta(),   -pi/2, 1e-6);\n\n  robot.setRotation(tf2::Quaternion(tf2::Vector3(0, 0, 1), -pi/2));\n  feedback = Feedback(robot, goal);\n  EXPECT_NEAR(feedback.x(),         0.0, 1e-6);\n  EXPECT_NEAR(feedback.y(),         1.0, 1e-6);\n  EXPECT_NEAR(feedback.r(),         1.0, 1e-6);\n  EXPECT_NEAR(feedback.theta(),    pi/2, 1e-6);\n\n  robot.setRotation(tf2::Quaternion(tf2::Vector3(0, 0, 1), 3*pi/4));\n  feedback = Feedback(robot, goal);\n  EXPECT_NEAR(feedback.x(), cos(-3*pi/4), 1e-6);\n  EXPECT_NEAR(feedback.y(), sin(-3*pi/4), 1e-6);\n  EXPECT_NEAR(feedback.r(),          1.0, 1e-6);\n  EXPECT_NEAR(feedback.theta(),  -3*pi/4, 1e-6);\n\n  robot.setRotation(tf2::Quaternion(tf2::Vector3(0, 0, 1), -3*pi/4));\n  feedback = Feedback(robot, goal);\n  EXPECT_NEAR(feedback.x(),  cos(3*pi/4), 1e-6);\n  EXPECT_NEAR(feedback.y(),  sin(3*pi/4), 1e-6);\n  EXPECT_NEAR(feedback.r(),         1.0, 1e-6);\n  EXPECT_NEAR(feedback.theta(),  3*pi/4, 1e-6);\n\n  robot.setRotation(tf2::Quaternion(tf2::Vector3(0, 0, 1), pi));\n  feedback = Feedback(robot, goal);\n  EXPECT_NEAR(feedback.x(),    -1.0, 1e-6);\n  EXPECT_NEAR(feedback.y(),     0.0, 1e-6);\n  EXPECT_NEAR(feedback.r(),     1.0, 1e-6);\n  EXPECT_NEAR(feedback.theta(), -pi, 1e-6);\n}\n\nTEST(Feedback, robotAndGoalPoses)\n{\n  tf2::Transform robot;\n  robot.setRotation(tf2::Quaternion(0.0, 0.0, 0.0, 1.0));\n  Waypoint goal;\n  goal.pose.orientation.w = 1.0;\n  Feedback feedback;\n\n  robot.setRotation(tf2::Quaternion(tf2::Vector3(0, 0, 1), pi/4));\n  goal.pose.position.x =  1.0;\n  goal.pose.position.y =  1.0;\n  feedback = Feedback(robot, goal);\n  EXPECT_NEAR(feedback.x(),     sqrt(2.0), 1e-6);\n  EXPECT_NEAR(feedback.y(),     sqrt(2.0), 1e-6);\n  EXPECT_NEAR(feedback.r(),     sqrt(2.0), 1e-6);\n  EXPECT_NEAR(feedback.theta(),       0.0, 1e-6);\n\n  robot.setRotation(tf2::Quaternion(tf2::Vector3(0, 0, 1), pi/2));\n  goal.pose.position.x =  0.0;\n  goal.pose.position.y =  1.0;\n  feedback = Feedback(robot, goal);\n  EXPECT_NEAR(feedback.x(),     sqrt(1.0), 1e-6);\n  EXPECT_NEAR(feedback.y(),     sqrt(0.0), 1e-6);\n  EXPECT_NEAR(feedback.r(),     sqrt(1.0), 1e-6);\n  EXPECT_NEAR(feedback.theta(),       0.0, 1e-6);\n\n  robot.setRotation(tf2::Quaternion(tf2::Vector3(0, 0, 1), -pi/2));\n  goal.pose.position.x =   0.0;\n  goal.pose.position.y =  -1.0;\n  feedback = Feedback(robot, goal);\n  EXPECT_NEAR(feedback.x(),           1.0, 1e-6);\n  EXPECT_NEAR(feedback.y(),           0.0, 1e-6);\n  EXPECT_NEAR(feedback.r(),     sqrt(1.0), 1e-6);\n  EXPECT_NEAR(feedback.theta(),       0.0, 1e-6);\n\n  robot.setRotation(tf2::Quaternion(tf2::Vector3(0, 0, 1), pi));\n  goal.pose.position.x =  -1.0;\n  goal.pose.position.y =   0.0;\n  feedback = Feedback(robot, goal);\n  EXPECT_NEAR(feedback.x(),     sqrt(1.0), 1e-6);\n  EXPECT_NEAR(feedback.y(),     sqrt(0.0), 1e-6);\n  EXPECT_NEAR(feedback.r(),     sqrt(1.0), 1e-6);\n  EXPECT_NEAR(feedback.theta(),       0.0, 1e-6);\n\n  robot.setRotation(tf2::Quaternion(tf2::Vector3(0, 0, 1), pi));\n  goal.pose.position.x =  -1.0;\n  goal.pose.position.y =  -1.0;\n  feedback = Feedback(robot, goal);\n  EXPECT_NEAR(feedback.x(),     sqrt(1.0), 1e-6);\n  EXPECT_NEAR(feedback.y(),     sqrt(1.0), 1e-6);\n  EXPECT_NEAR(feedback.r(),     sqrt(2.0), 1e-6);\n  EXPECT_NEAR(feedback.theta(),      pi/4, 1e-6);\n\n  robot.setRotation(tf2::Quaternion(tf2::Vector3(0, 0, 1), pi));\n  goal.pose.position.x =  -1.0;\n  goal.pose.position.y =   1.0;\n  feedback = Feedback(robot, goal);\n  EXPECT_NEAR(feedback.x(),           1.0, 1e-6);\n  EXPECT_NEAR(feedback.y(),          -1.0, 1e-6);\n  EXPECT_NEAR(feedback.r(),     sqrt(2.0), 1e-6);\n  EXPECT_NEAR(feedback.theta(),     -pi/4, 1e-6);\n\n  robot.setOrigin(tf2::Vector3(2.0, 3.0, 0.0));\n  robot.setRotation(tf2::Quaternion(tf2::Vector3(0, 0, 1), pi));\n  goal.pose.position.x =  1.0;\n  goal.pose.position.y =  2.0;\n  feedback = Feedback(robot, goal);\n  EXPECT_NEAR(feedback.x(),         -1.0, 1e-6);\n  EXPECT_NEAR(feedback.y(),         -1.0, 1e-6);\n  EXPECT_NEAR(feedback.r(),     sqrt(2.0), 1e-6);\n  EXPECT_NEAR(feedback.theta(),      pi/4, 1e-6);\n}\n\n// Run all the tests that were declared with TEST()\nint main(int argc, char **argv)\n{\n  testing::InitGoogleTest(&argc, argv);\n  return RUN_ALL_TESTS();\n}\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "7eaef0bd05005b696be4ced728b0a74f6101df9b", "size": 7915, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/controls/waypoint_control/src/waypoint_control/tests/waypoint_control_tests.cpp", "max_stars_repo_name": "robotic-mining-competition/NDSU2019", "max_stars_repo_head_hexsha": "2f9a324d110fece78da3f42e2ae89a7fe198e6e3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-05-10T22:52:09.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-10T22:52:09.000Z", "max_issues_repo_path": "src/controls/waypoint_control/src/waypoint_control/tests/waypoint_control_tests.cpp", "max_issues_repo_name": "robotic-mining-competition/NDSU2019", "max_issues_repo_head_hexsha": "2f9a324d110fece78da3f42e2ae89a7fe198e6e3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/controls/waypoint_control/src/waypoint_control/tests/waypoint_control_tests.cpp", "max_forks_repo_name": "robotic-mining-competition/NDSU2019", "max_forks_repo_head_hexsha": "2f9a324d110fece78da3f42e2ae89a7fe198e6e3", "max_forks_repo_licenses": ["BSD-3-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.256302521, "max_line_length": 69, "alphanum_fraction": 0.6160454833, "num_tokens": 2807, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581741774411, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.4853578524423633}}
{"text": "// Filename: matrix_indirect.cpp (part of MTL4)\n#include <iostream>\n#include <boost/numeric/mtl/mtl.hpp>\n\nusing namespace std;  \n\nint main(int, char**)\n{\n    typedef mtl::dense2D<double> matrix;\n    matrix A(5, 3);\n    hessian_setup(A, 1.0);\n\n    mtl::iset rows, cols;\n    rows= 2, 0, 3; cols= 2, 1;\n\n    cout << \"rows = \" << rows << \", cols = \" << cols << \"\\n\"   \n\t << \"The sub-matrix A[{2, 0, 3}][{2, 1}] is\\n\" << A[rows][cols];\n\n    mtl::mat::indirect<matrix> B(A[rows][cols]);\n    cout << \"B is\\n\" << B;\n\n    return 0;\n}\n", "meta": {"hexsha": "a2e84feb070383835e27a5e29f5f9636716e30be", "size": 525, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/examples/matrix_indirect.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/matrix_indirect.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/matrix_indirect.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": 21.875, "max_line_length": 65, "alphanum_fraction": 0.5504761905, "num_tokens": 195, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.48535783989753967}}
{"text": "/***************************************************************************\n *  @file       lcs_with_one_table.hpp\n *  @author     alan.w\n *  @date       09  August 2014\n *  @remark     CLRS Algorithms implementation, using C++ templates.\n ***************************************************************************/\n\n#ifndef LCS_WITH_ONE_TABLE_HPP\n#define LCS_WITH_ONE_TABLE_HPP\n//!\n//! ex15.4-2\n//! Give pseudocode to reconstruct an LCS from the completed c table and the original\n//! sequences X and Y in O(m + n) time, without using the b table.\n//!\n#include <functional>\n#include <memory>\n#include \"matrix.hpp\"\n#include \"color.hpp\"\n\nnamespace ch15 {\n\n/**\n * @brief The LcsWithOneTable class\n *\n * for ex15.4-2\n */\ntemplate<typename Range>\nclass LcsWithOneTable\n{\npublic:\n    using SizeType  =   typename Range::size_type;\n    using Pointer   =   const Range*;\n    using sPointer  =   std::shared_ptr<Range>;\n    using MatrixType=   ch15::Matrix<SizeType>;\n\n    //! Ctor\n    LcsWithOneTable(const Range& l, const Range& r):\n        lhs(&l),\n        rhs(&r),\n        maze(l.size() + 1, r.size() + 1, 0)\n    {\n        build_maze();\n    }\n\n    /**\n     * @brief print_maze\n     */\n    void print_maze()const\n    {\n        ch15::print(maze);\n    }\n\n    /**\n     * @brief generate\n     */\n    sPointer generate() const\n    {\n        assert(lhs && rhs);\n        sPointer lcs = std::make_shared<Range>();\n\n        //! lambda to do the real work\n        using Lambda = std::function<void(SizeType, SizeType)>;\n        Lambda build_lcs = [&lcs, &build_lcs, this](SizeType l, SizeType r)\n        {\n            //! stop condition\n            if(l == 0 || r == 0)    return;\n\n            //! recur\n            if((*lhs)[l - 1]    ==  (*rhs)[r - 1])\n            {\n                build_lcs(l - 1, r - 1);\n                lcs->push_back((*lhs)[l - 1]);\n            }\n            else if (maze(l - 1, r) >= maze(l, r - 1))\n                build_lcs(l - 1, r);\n            else\n                build_lcs(l, r - 1);\n        };\n\n        //! call the lambda\n        build_lcs(lhs->size(),rhs->size());\n        return lcs;\n    }\n\nprivate:\n    Pointer lhs;\n    Pointer rhs;\n    MatrixType maze;\n\n    /**\n     * @brief build_maze\n     *\n     * @complx  O(m + n)\n     * for ex15.4-2\n     */\n    void build_maze()\n    {\n        for(SizeType l = 1; l != maze.size1(); ++l)\n            for(SizeType r = 1; r != maze.size2(); ++r)\n            {\n                if((*lhs)[l - 1]    ==  (*rhs)[r - 1])\n                    maze(l,r)   =   maze(l - 1, r - 1) + 1;\n                else if(maze(l - 1, r) >= maze(l, r - 1))\n                    maze(l,r)   =   maze(l - 1, r);\n                else\n                    maze(l,r)   =   maze(l, r - 1);\n            }\n    }\n};\n\n}//namespace\n#endif // LCS_WITH_ONE_TABLE_HPP\n\n//! @test   for ex15.4-2\n//!\n//#include <iostream>\n//#include <boost/numeric/ublas/io.hpp>\n//#include \"lcs_with_one_table.hpp\"\n//#include \"color.hpp\"\n\n//int main()\n//{\n//    std::string lhs = \"ABCBDAB\";\n//    std::string rhs = \"BDCABA\";\n\n//    using LCS   =   ch15::LcsWithOneTable<std::string>;\n//    LCS lcs(lhs, rhs);\n//    lcs.print_maze();\n\n//    auto sequence = lcs.generate();\n//    std::cout << \"The longest common sequence = \";\n//    std::cout << color::yellow(*sequence) << std::endl;\n\n//    std::cout << color::red(\"\\nend\\n\");\n//    return 0;\n//}\n\n//! @output:\n//!\n//0 0 0 0 0 0 0\n\n//0 0 0 0 1 1 1\n\n//0 1 1 1 1 2 2\n\n//0 1 1 2 2 2 2\n\n//0 1 1 2 2 3 3\n\n//0 1 2 2 2 3 3\n\n//0 1 2 2 3 3 4\n\n//0 1 2 2 3 4 4\n\n//The longest common sequence = BCBA\n\n", "meta": {"hexsha": "0eae6fd27a5198576c46dc5213b635cc497952f3", "size": 3542, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ch15/lcs_with_one_table.hpp", "max_stars_repo_name": "klong13579/cppL", "max_stars_repo_head_hexsha": "7aa8afaf2d2e17578c7fd91654bedcccf0a6baab", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 261.0, "max_stars_repo_stars_event_min_datetime": "2015-01-11T20:42:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T01:33:39.000Z", "max_issues_repo_path": "ch15/lcs_with_one_table.hpp", "max_issues_repo_name": "LeungGeorge/CLRS", "max_issues_repo_head_hexsha": "7aa8afaf2d2e17578c7fd91654bedcccf0a6baab", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-04-05T11:49:45.000Z", "max_issues_repo_issues_event_max_datetime": "2017-02-19T08:29:52.000Z", "max_forks_repo_path": "ch15/lcs_with_one_table.hpp", "max_forks_repo_name": "LeungGeorge/CLRS", "max_forks_repo_head_hexsha": "7aa8afaf2d2e17578c7fd91654bedcccf0a6baab", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 98.0, "max_forks_repo_forks_event_min_datetime": "2015-01-03T12:58:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-16T07:29:31.000Z", "avg_line_length": 22.417721519, "max_line_length": 85, "alphanum_fraction": 0.4765669113, "num_tokens": 1068, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.48535783875857247}}
{"text": "/********************************************************************************\n*  This file is part of CinoLib                                                 *\n*  Copyright(C) 2021: Marco Livesu                                              *\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*                                                                               *\n*     Marco Livesu (marco.livesu@gmail.com)                                     *\n*     http://pers.ge.imati.cnr.it/livesu/                                       *\n*                                                                               *\n*     Italian National Research Council (CNR)                                   *\n*     Institute for Applied Mathematics and Information Technologies (IMATI)    *\n*     Via de Marini, 6                                                          *\n*     16149 Genoa,                                                              *\n*     Italy                                                                     *\n*********************************************************************************/\n#include <cinolib/geometry/vec_mat_utils.h>\n#include <cinolib/clamp.h>\n#include <cinolib/deg_rad.h>\n#include <iostream>\n#include <cmath>\n#include <cassert>\n#include <Eigen/Dense>\n\nnamespace cinolib\n{\n\ntemplate<unsigned int d, typename T>\nCINO_INLINE\nvoid vec_set(T * v, const std::initializer_list<T> & il)\n{\n    assert(il.size()==d);\n    auto it = il.begin();\n    for(unsigned int i=0; i<d; ++i,++it) v[i] = *it;\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\ntemplate<unsigned int d, typename T>\nCINO_INLINE\nvoid vec_set_dense(T * vec, const T val)\n{\n    for(unsigned int i=0; i<d; ++i)\n    {\n        vec[i] = val;\n    }\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\n// v2 = v0 + v1\ntemplate<unsigned int d, typename T>\nCINO_INLINE\nvoid vec_plus(const T * v0, const T * v1, T * v2)\n{\n    for(unsigned int i=0; i<d; ++i)\n    {\n        v2[i] = v0[i] + v1[i];\n    }\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\n// v2 = v0 - v1\ntemplate<unsigned int d, typename T>\nCINO_INLINE\nvoid vec_minus(const T * v0, const T * v1, T * v2)\n{\n    for(unsigned int i=0; i<d; ++i)\n    {\n        v2[i] = v0[i] - v1[i];\n    }\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\n// v = -v\ntemplate<unsigned int d, typename T>\nCINO_INLINE\nvoid vec_minus(const T * v0, T * v1)\n{\n    for(unsigned int i=0; i<d; ++i)\n    {\n        v1[i] = -v0[i];\n    }\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\n// v1 = v0 * val (element-wise)\ntemplate<unsigned int d, typename T>\nCINO_INLINE\nvoid vec_times(const T * v0, const T val, T * v1)\n{\n    for(unsigned int i=0; i<d; ++i)\n    {\n        v1[i] = v0[i] * val;\n    }\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\n// v1 = v0 / val (element-wise)\ntemplate<unsigned int d, typename T>\nCINO_INLINE\nvoid vec_divide(const T * v0, const T val, T * v1)\n{\n    for(unsigned int i=0; i<d; ++i)\n    {\n        v1[i] = v0[i] / val;\n    }\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\n// true if v0 == v1 (element-wise)\ntemplate<unsigned int d, typename T>\nCINO_INLINE\nbool vec_equals(const T * v0, const T * v1)\n{\n    for(unsigned int i=0; i<d; ++i)\n    {\n        if(v0[i] != v1[i]) return false;\n    }\n    return true;\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\n// true if v0 < v1 (element-wise)\ntemplate<unsigned int d, typename T>\nCINO_INLINE\nbool vec_less(const T * v0, const T * v1)\n{\n    for(unsigned int i=0; i<d; ++i)\n    {\n        if(v0[i] < v1[i]) return true;\n        if(v0[i] > v1[i]) return false;\n    }\n    return false;\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\ntemplate<unsigned int d, typename T>\nCINO_INLINE\nT vec_dot(const T * v0, const T * v1)\n{\n    T res = 0;\n    for(unsigned int i=0; i<d; ++i)\n    {\n        res += v0[i]*v1[i];\n    }\n    return res;\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\ntemplate<typename T>\nCINO_INLINE\nvoid vec_cross(const T * v0, const T * v1, T * v2)\n{\n    v2[0] = v0[1] * v1[2] - v0[2] * v1[1];\n    v2[1] = v0[2] * v1[0] - v0[0] * v1[2];\n    v2[2] = v0[0] * v1[1] - v0[1] * v1[0];\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\ntemplate<unsigned int d, typename T>\nCINO_INLINE\nT vec_angle_deg(const T * v0, const T * v1, const bool normalize)\n{\n    return (T)to_deg((double)vec_angle_rad<d,T>(v0,v1,normalize));\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\ntemplate<unsigned int d, typename T>\nCINO_INLINE\nT vec_angle_rad(const T * v0, const T * v1, const bool normalize)\n{\n    T dot;\n    if(normalize)\n    {\n        // normalize input vecs if they are not known to be BOTH already normal\n        T tmp0[d], tmp1[d];\n        vec_copy<d,T>(v0, tmp0);\n        vec_copy<d,T>(v1, tmp1);\n        vec_normalize<d,T>(tmp0);\n        vec_normalize<d,T>(tmp1);\n        if(vec_is_deg<d,T>(tmp0) || vec_is_deg<d,T>(tmp1))\n        {\n            return std::numeric_limits<T>::infinity();\n        }\n        dot = vec_dot<d,T>(tmp0,tmp1);\n    }\n    else\n    {\n        dot = vec_dot<d,T>(v0,v1);\n    }\n    return acos(clamp(dot,T(-1),T(1)));\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\n// vector distance (in the L2 sense)\ntemplate<unsigned int d, typename T>\nCINO_INLINE\ndouble vec_dist_sqrd(const T * v_0, const T * v_1)\n{\n    double res = 0.0;\n    for(unsigned int i=0; i<d; ++i)\n    {\n        T tmp = v_0[i] - v_1[i];\n        res += tmp*tmp;\n    }\n    return res;\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\n// L2 vector norm\ntemplate<unsigned int d, typename T>\nCINO_INLINE\ndouble vec_norm_sqrd(const T * v)\n{\n    double res = 0.0;\n    for(unsigned int i=0; i<d; ++i)\n    {\n        res += v[i]*v[i];\n    }\n    return res;\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\n// vector distance (in the L2 sense)\ntemplate<unsigned int d, typename T>\nCINO_INLINE\ndouble vec_dist(const T * v_0, const T * v_1)\n{\n    return sqrt(vec_dist_sqrd<d,T>(v_0,v_1));\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\n// L2 vector norm\ntemplate<unsigned int d, typename T>\nCINO_INLINE\ndouble vec_norm(const T * v)\n{\n    return sqrt(vec_norm_sqrd<d,T>(v));\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\n// Lp vector norm\ntemplate<unsigned int d, typename T>\nCINO_INLINE\ndouble vec_norm_p(const T * v, const float p)\n{\n    double res = 0.0;\n    for(unsigned int i=0; i<d; ++i)\n    {\n        res += std::pow(std::fabs(v[i]),p);\n    }\n    res = std::pow(res,1.0/p);\n    return res;\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\ntemplate<unsigned int d, typename T>\nCINO_INLINE\ndouble vec_normalize(T * v)\n{\n    double n = vec_norm<d,T>(v);\n    if(vec_is_deg<d,T>(v)) return -1;\n    vec_divide<d,T>(v,n,v);\n    return n;\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\n// element-wise min\ntemplate<unsigned int d, typename T>\nCINO_INLINE\nvoid vec_min(const T * v0, const T * v1, T * v2)\n{\n    for(unsigned int i=0; i<d; ++i)\n    {\n        v2[i] = std::min(v0[i], v1[i]);\n    }\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\n// element-wise max\ntemplate<unsigned int d, typename T>\nCINO_INLINE\nvoid vec_max(const T * v0, const T * v1, T * v2)\n{\n    for(unsigned int i=0; i<d; ++i)\n    {\n        v2[i] = std::max(v0[i], v1[i]);\n    }\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\ntemplate<unsigned int d, typename T>\nCINO_INLINE\nT vec_min_entry(const T * v)\n{\n    return *std::min_element(v,v+d);\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\ntemplate<unsigned int d, typename T>\nCINO_INLINE\nT vec_max_entry(const T * v)\n{\n    return *std::max_element(v,v+d);\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\n// element-wise clamp\ntemplate<unsigned int d, typename T>\nCINO_INLINE\nvoid vec_clamp(T * v, const T min, const T max)\n{\n    for(unsigned int i=0; i<d; ++i)\n    {\n        v[i] = clamp(v[i], min, max);\n    }\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\ntemplate<unsigned int d, typename T>\nCINO_INLINE\nvoid vec_swap(T * v, const unsigned int i, const unsigned int j)\n{\n    assert(i<d && j<d);\n    std::swap(v[i],v[j]);\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\n// true if all entries are zero\ntemplate<unsigned int d, typename T>\nCINO_INLINE\nbool vec_is_null(const T * v)\n{\n    for(unsigned int i=0; i<d; ++i)\n    {\n        if(v[i] !=0) return false;\n    }\n    return true;\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\n// true if at least one entry is NaN\ntemplate<unsigned int d, typename T>\nCINO_INLINE\nbool vec_is_nan(const T * v)\n{\n    for(unsigned int i=0; i<d; ++i)\n    {\n        if(std::isnan(v[i])) return true;\n    }\n    return false;\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\n// true if at least one entry is inf\ntemplate<unsigned int d, typename T>\nCINO_INLINE\nbool vec_is_inf(const T * v)\n{\n    for(unsigned int i=0; i<d; ++i)\n    {\n        if(std::isinf(v[i])) return true;\n    }\n    return false;\n}\n\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\n// true if at least one entry is NaN or Inf, or all entries are zero\ntemplate<unsigned int d, typename T>\nCINO_INLINE\nbool vec_is_deg(const T * v)\n{\n    for(unsigned int i=0; i<d; ++i)\n    {\n        if(std::isinf(v[i]) || std::isnan(v[i])) return true;\n    }\n    return vec_is_null<d,T>(v);\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\n// true if all entries are null, normal or subnormal\ntemplate<unsigned int d, typename T>\nCINO_INLINE\nbool vec_is_finite(const T* v)\n{\n    for (std::size_t i = 0; i < d; ++i)\n    {\n        if (!std::isfinite(v[i])) return false;\n    }\n    return true;\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\ntemplate<unsigned int d, typename T>\nCINO_INLINE\nvoid vec_copy(const T * v0, T * v1)\n{\n    std::copy(v0, v0+d, v1);\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\ntemplate<unsigned int d, typename T>\nCINO_INLINE\nvoid vec_print(const T * v)\n{\n    for(unsigned int i=0; i<d; ++i)\n    {\n        std::cout << v[i] << \" \";\n    }\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\ntemplate<unsigned int r, unsigned int c, typename T>\nCINO_INLINE\nvoid mat_set(T m[][c], const std::initializer_list<T> & il)\n{\n    assert(il.size()==r*c);\n    auto it = il.begin();\n    for(unsigned int i=0; i<r; ++i)\n    for(unsigned int j=0; j<c; ++j)\n    {\n        m[i][j] = *it;\n        ++it;\n    }\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\n// initialize diagonal matrix\ntemplate<unsigned int d, typename T>\nCINO_INLINE\nvoid mat_set_diag(T m[][d], const T val)\n{\n    for(unsigned int i=0; i<d; ++i)\n    for(unsigned int j=0; j<d; ++j)\n    {\n        m[i][j] = (i==j) ? val : 0;\n    }\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\n// initialize diagonal matrix\ntemplate<unsigned int d, typename T>\nCINO_INLINE\nvoid mat_set_diag(T m[][d], const T diag[])\n{\n    for(unsigned int i=0; i<d; ++i)\n    for(unsigned int j=0; j<d; ++j)\n    {\n        m[i][j] = (i==j) ? diag[i] : 0;\n    }\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\ntemplate<unsigned int r, unsigned int c, typename T>\nCINO_INLINE\nvoid mat_set_row(T m[][c], const unsigned int i, const T row[])\n{\n    assert(i<r);\n    for(unsigned int j=0; j<c; ++j)\n    {\n        m[i][j] = row[j];\n    }\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\ntemplate<unsigned int r, unsigned int c, typename T>\nCINO_INLINE\nvoid mat_set_col(T m[][c], const unsigned int i, const T col[])\n{\n    assert(i<c);\n    for(unsigned int j=0; j<r; ++j)\n    {\n        m[j][i] = col[j];\n    }\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\n// initialize 2D rotation matrix\ntemplate<unsigned int d,typename T>\nCINO_INLINE\nvoid mat_set_rot_2d(T m[][d], const T ang_rad)\n{\n    assert(d==2 || d==3);\n    if(d==3) mat_set_diag<d,T>(m,1); // for transformations in homogeneous coordinates\n\n    T rcos  = (T)cos(ang_rad);\n    T rsin  = (T)sin(ang_rad);\n    m[0][0] =  rcos;\n    m[1][0] =  rsin;\n    m[0][1] = -rsin;\n    m[1][1] =  rcos;\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\n// initialize 3D rotation matrix\ntemplate<unsigned int d,typename T>\nCINO_INLINE\nvoid mat_set_rot_3d(T m[][d], const T ang_rad, const T axis[])\n{\n    assert(d==3 || d==4);\n    if(d==4) mat_set_diag<d,T>(m, 1); // for transformations in homogeneous coordinates\n\n    T u     = axis[0];\n    T v     = axis[1];\n    T w     = axis[2];\n    T rcos  = (T)cos(ang_rad);\n    T rsin  = (T)sin(ang_rad);\n    m[0][0] =      rcos + u*u*(1-rcos);\n    m[1][0] =  w * rsin + v*u*(1-rcos);\n    m[2][0] = -v * rsin + w*u*(1-rcos);\n    m[0][1] = -w * rsin + u*v*(1-rcos);\n    m[1][1] =      rcos + v*v*(1-rcos);\n    m[2][1] =  u * rsin + w*v*(1-rcos);\n    m[0][2] =  v * rsin + u*w*(1-rcos);\n    m[1][2] = -u * rsin + v*w*(1-rcos);\n    m[2][2] =      rcos + w*w*(1-rcos);\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\n// initialize translation matrix\n// NOTE: translation is a non linear operation.\n// Homogeneous coordinates are assumed here, hence tx is supposed to be a (d-1) vector\ntemplate<unsigned int d, typename T>\nCINO_INLINE\nvoid mat_set_trans(T m[][d], const T tx[])\n{\n    mat_set_diag<d,T>(m,1);\n    for(unsigned int i=0; i<d-1; ++i)\n    {\n        m[i][d-1] = tx[i];\n    }\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\ntemplate<unsigned int r, unsigned int c, typename T>\nCINO_INLINE\nvoid mat_swap(T m[][c], const unsigned int i, const unsigned int j, const unsigned int k, const unsigned int l)\n{\n    assert(i<r && j<c && k<r && l<c);\n    std::swap(m[i][j], m[k][l]);\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\n// copy ith column\ntemplate<unsigned int r, unsigned int c, typename T>\nCINO_INLINE\nvoid mat_col(const T m[][c], const unsigned int i, T col[])\n{\n    assert(i<c);\n    for(unsigned int j=0; j<r; ++j)\n    {\n        col[j] = m[j][i];\n    }\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\n// copy ith row\ntemplate<unsigned int r, unsigned int c, typename T>\nCINO_INLINE\nvoid mat_row(const T m[][c], const unsigned int i, T row[])\n{\n    assert(i<r);\n    std::copy(m[i], m[i]+c, row);\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\n// copy diagonal\ntemplate<unsigned int d, typename T>\nCINO_INLINE\nvoid mat_diag(const T m[][d], T diag[])\n{\n    for(unsigned int i=0; i<d; ++i)\n    {\n        diag[i] = m[i][i];\n    }\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\n// vector of pointers to elements in the ith column\ntemplate<unsigned int r, unsigned int c, typename T>\nCINO_INLINE\nvoid mat_col_ptr(const T m[][c], const unsigned int i, T * col[])\n{\n    assert(i<c);\n    for(unsigned int j=0; j<r; ++j)\n    {\n        col[j] = & m[j][i];\n    }\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\n// vector of pointers to elements in the ith row\ntemplate<unsigned int r, unsigned int c, typename T>\nCINO_INLINE\nvoid mat_row_ptr(const T m[][c], const unsigned int i, T * row[])\n{\n    assert(i<r);\n    for(unsigned int j=0; j<c; ++j)\n    {\n        row[j] = & m[i][j];\n    }\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\n// vector of pointers to elements in the diagonal\ntemplate<unsigned int d, typename T>\nCINO_INLINE\nvoid mat_diag_ptr(const T m[][d], T * diag[])\n{\n    for(unsigned int i=0; i<d; ++i)\n    for(unsigned int j=0; j<d; ++j)\n    {\n        diag[i] = & m[i][j];\n    }\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\ntemplate<unsigned int d, typename T>\nCINO_INLINE\nbool mat_is_symmetric(const T m[][d])\n{\n    for(unsigned int i=0;   i<d-1; ++i)\n    for(unsigned int j=i+1; j<d;   ++j)\n    {\n        if(m[i][j]!=m[j][i]) return false;\n    }\n    return true;\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\ntemplate<unsigned int d, typename T>\nCINO_INLINE\nT mat_trace(const T m[][d])\n{\n    T res = 0;\n    for(unsigned int i=0; i<d; ++i)\n    {\n        res += m[i][i];\n    }\n    return res;\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\ntemplate<unsigned int d, typename T>\nCINO_INLINE\nT mat_det(const T m[][d])\n{\n    switch(d)\n    {\n        case 2: return mat_det22<T>(m[0][0], m[0][1],\n                                    m[1][0], m[1][1]);\n\n        case 3: return mat_det33<T>(m[0][0], m[0][1], m[0][2],\n                                    m[1][0], m[1][1], m[1][2],\n                                    m[2][0], m[2][1], m[2][2]);\n\n        default:\n        {\n            typedef Eigen::Matrix<T,d,d,Eigen::RowMajor> M;\n            Eigen::Map<const M> tmp(m[0]);\n            return tmp.determinant();\n        }\n    }\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\ntemplate<typename T>\nCINO_INLINE\nT mat_det22(const T m00, const T m01,\n            const T m10, const T m11)\n{\n    return m00*m11 - m10*m01;\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\ntemplate<typename T>\nCINO_INLINE\nT mat_det33(const T m00, const T m01, const T m02,\n            const T m10, const T m11, const T m12,\n            const T m20, const T m21, const T m22)\n{\n    return m00 * mat_det22(m11, m12, m21, m22) -\n           m01 * mat_det22(m10, m12, m20, m22) +\n           m02 * mat_det22(m10, m11, m20, m21);\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\ntemplate<unsigned int r, unsigned int c, typename T>\nCINO_INLINE\nvoid mat_transpose(const T m[][c], T tr[][r])\n{\n    for(unsigned int i=0; i<r; ++i)\n    for(unsigned int j=0; j<c; ++j)\n    {\n        tr[j][i] = m[i][j];\n    }\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\ntemplate<unsigned int d, typename T>\nCINO_INLINE\nvoid mat_inverse(const T m[][d], T in[][d])\n{\n    switch(d)\n    {\n        case 2:\n        {\n            // https://mathworld.wolfram.com/MatrixInverse.html\n            // https://www.mathsisfun.com/algebra/matrix-inverse.html\n            double one_over_det = 1.0 / mat_det(m);\n            in[0][0] =  m[1][1] * one_over_det;\n            in[0][1] = -m[0][1] * one_over_det;\n            in[1][0] = -m[1][0] * one_over_det;\n            in[1][1] =  m[0][0] * one_over_det;\n        }\n\n        default: // up to 4x4 matrices with Eigen\n        {\n            typedef Eigen::Matrix<T,d,d,Eigen::RowMajor> M;\n            Eigen::Map<const M> tmp_m(m[0]);\n            Eigen::Map<M> tmp_in(in[0]);\n            tmp_in = tmp_m.inverse();\n        }\n    }\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\n// matrix eigen values and eigenvectors (from lowest to highest)\ntemplate<unsigned int r, unsigned int c, typename T>\nCINO_INLINE\nvoid mat_eigendec(const T m[][c], T eval[], T evec[][c])\n{\n    assert(r==c);\n\n    if(r==2)\n    {\n        // http://legacy-www.math.harvard.edu/archive/21b_fall_04/exhibits/2dmatrices/index.html\n        T trace = mat_trace<r,T>(m);\n        T det   = mat_det<r,T>(m);\n        eval[0] = trace*0.5 - sqrt((trace*trace)*0.25 - det);\n        eval[1] = trace*0.5 + sqrt((trace*trace)*0.25 - det);\n\n        T e0[c];\n        T e1[c];\n        if(m[1][0]!=0)\n        {\n            vec_set<r,T>(e0, { eval[0]-m[1][1], m[1][0] });\n            vec_set<r,T>(e1, { eval[1]-m[1][1], m[1][0] });\n        }\n        else if(m[0][1]!=0)\n        {\n            vec_set<r,T>(e0, { m[0][1], eval[0]-m[0][0] });\n            vec_set<r,T>(e1, { m[0][1], eval[1]-m[0][0] });\n        }\n        else\n        {\n            vec_set<r,T>(e0, { 0, 1 });\n            vec_set<r,T>(e1, { 1, 0 });\n        }\n        vec_normalize<r,T>(e0);\n        vec_normalize<r,T>(e1);\n        mat_set_col<r,c,T>(evec, 0, e0);\n        mat_set_col<r,c,T>(evec, 1, e1);\n    }\n    else\n    {\n        if(mat_is_symmetric(m))\n        {\n            // eigen decomposition for self-adjoint (i.e. real valued symmetric) matrices\n            //  - guaranteed real valued eigen values and vectors\n            //  - faster and more precise than Eigen::EigenSolver\n            typedef Eigen::Matrix<T,r,c,Eigen::RowMajor> M;\n            Eigen::Map<const M> tmp(m[0]);\n            Eigen::SelfAdjointEigenSolver<Eigen::Matrix<T,r,c>> eig(tmp);\n            assert(eig.info() == Eigen::Success);\n            vec_copy<r*c,T>(eig.eigenvectors().data(), evec[0]);\n            vec_copy<r,T>(eig.eigenvalues().data(),  eval);\n            std::cout << eig.eigenvectors() << std::endl;\n            std::cout << eig.eigenvalues() << std::endl;\n        }\n        else\n        {\n            // eigen decomposition for general matrices\n            typedef Eigen::Matrix<T,r,c,Eigen::RowMajor> M;\n            Eigen::Map<const M> tmp(m[0]);\n            Eigen::EigenSolver<Eigen::Matrix<T,r,c>> eig(tmp);\n            assert(eig.info() == Eigen::Success);\n            for(unsigned int i=0; i<r; ++i)\n            {\n                for(unsigned int j=0; j<r; ++j)\n                {\n                    // WARNING: I am taking only the real part!\n                    evec[j][i] = eig.eigenvectors()(j,i).real();\n                }\n                eval[i] = eig.eigenvalues()[i].real();\n            }\n        }\n    }\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\n// matrix eigen values (from highest to lowest)\ntemplate<unsigned int r, unsigned int c, typename T>\nCINO_INLINE\nvoid mat_eigenval(const T m[][c], T eval[])\n{\n    T evec[r][c];\n    mat_eigendec<r,c,T>(m, eval, evec);\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\ntemplate<unsigned int r, unsigned int c, typename T>\nCINO_INLINE\nvoid mat_eigenvec(const T m[][c], T evec[][c])\n{\n    T eval[2];\n    mat_eigendec<r,c,T>(m, eval, evec);\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\ntemplate<unsigned int r, unsigned int c, typename T>\nCINO_INLINE\nvoid mat_svd(const T m[][c], T U[][r], T S[], T V[][c])\n{\n//    // https://lucidar.me/en/mathematics/singular-value-decomposition-of-a-2x2-matrix/\n//    if(r==2 && c==2)\n//    {\n//        // singular values (S)\n//        {\n//            T m00_2 = m[0][0]*m[0][0];\n//            T m01_2 = m[0][1]*m[0][1];\n//            T m10_2 = m[1][0]*m[1][0];\n//            T m11_2 = m[1][1]*m[1][1];\n//            T s1    = m00_2 + m01_2 + m10_2 + m11_2;\n//            T s2    = sqrt(std::pow(m00_2 + m01_2 - m10_2 - m11_2,2) + 4*std::pow(m[0][0]*m[1][0] + m[0][1]*m[1][1],2));\n//            S[0]    = sqrt((s1+s2)*0.5);\n//            S[1]    = sqrt((s1-s2)*0.5);\n//        }\n//        // orthogonal matrices (U,V)\n//        {\n//            double theta     = 0.5 * atan2(2.0*m[0][0]*m[1][0]+2.0*m[0][1]*m[1][1], m[0][0]*m[0][0] + m[0][1]*m[0][1] - m[1][0]*m[1][0] - m[1][1]*m[1][1]);\n//            double phi       = 0.5 * atan2(2.0*m[0][0]*m[0][1]+2.0*m[1][0]*m[1][1], m[0][0]*m[0][0] - m[0][1]*m[0][1] + m[1][0]*m[1][0] - m[1][1]*m[1][1]);\n//            double cos_theta = cos(theta);\n//            double sin_theta = cos(theta);\n//            double cos_phi   = cos(phi);\n//            double sin_phi   = cos(phi);\n//            int sign1        = ((m[0][0]*cos_theta + m[1][0]*sin_theta)*cos_phi + ( m[0][1]*cos_theta + m[1][1]*sin_theta)*sin_phi > 0) ? +1 : -1;\n//            int sign2        = ((m[0][0]*sin_theta - m[1][0]*cos_theta)*sin_phi + (-m[0][1]*sin_theta + m[1][1]*cos_theta)*cos_phi > 0) ? +1 : -1;\n//            mat_set_rot_2d<r,T>(U, theta);\n//            mat_set_rot_2d<r,T>(V, phi);\n//            V[0][0] *= sign1;\n//            V[1][0] *= sign1;\n//            V[0][1] *= sign2;\n//            V[1][1] *= sign2;\n//        }\n//    }\n//    else\n    {\n        typedef Eigen::Matrix<T,r,c,Eigen::RowMajor> M;\n        Eigen::Map<const M> tmp(m[0]);\n        Eigen::JacobiSVD<M> svd(tmp, Eigen::ComputeFullU | Eigen::ComputeFullV);\n        vec_copy<r*r,T>(svd.matrixU().data(), U[0]);\n        vec_copy<c*c,T>(svd.matrixV().data(), V[0]);\n        if(r<c) vec_copy<r>(svd.singularValues().data(), S);\n        else    vec_copy<c>(svd.singularValues().data(), S);\n    }\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\ntemplate<unsigned int r, unsigned int c, typename T>\nCINO_INLINE\nvoid mat_ssvd(const T m[][c], T U[][r], T S[], T V[][c])\n{\n    mat_svd<r,c,T>(m,U,S,V);\n\n    if(r==2 && c==2)\n    {\n        if(mat_det<c,T>(V)<0)\n        {\n            V[0][1] = -V[0][1];\n            V[1][1] = -V[1][1];\n            U[0][1] = -U[0][1];\n            U[1][1] = -U[1][1];\n            assert((mat_det<c,T>(V)>0));\n        }\n\n        if(mat_det<r,T>(U)<0)\n        {\n            U[0][1] = -U[0][1];\n            U[1][1] = -U[1][1];\n            S[1]    = -S[1];\n            assert((mat_det<r,T>(U)>0));\n        }\n    }\n    else if(r==3 && c==3)\n    {\n        if(mat_det<c,T>(V)<0)\n        {\n            V[0][2] = -V[0][2];\n            V[1][2] = -V[1][2];\n            V[2][2] = -V[2][2];\n            U[0][2] = -U[0][2];\n            U[1][2] = -U[1][2];\n            U[2][2] = -U[2][2];\n            assert((mat_det<c,T>(V)>0));\n        }\n\n        if(mat_det<r,T>(U)<0)\n        {\n            U[0][2] = -U[0][2];\n            U[1][2] = -U[1][2];\n            U[2][2] = -U[2][2];\n            S[2]    = -S[2];\n            assert((mat_det<c,T>(U)>0));\n        }\n    }\n    else assert(false && \"mat_ssvd: unsupported matrix size\");\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\ntemplate<unsigned int d, typename T>\nCINO_INLINE\nvoid mat_solve_Cramer(const T m[][d], const T b[], T x[])\n{\n    T det = mat_det<d,T>(m);\n    if(det==0)\n    {\n        vec_set_dense<d,T>(x,0);\n        return;\n    }\n    for(unsigned int i=0; i<d; ++i)\n    {\n        T m_i[d][d];\n        mat_copy<d,d,T>(m, m_i);\n        mat_set_col<d,d,T>(m_i, i, b);\n        x[i] = mat_det<d,T>(m_i) / det;\n    }\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\ntemplate<unsigned int r, unsigned int c, typename T>\nCINO_INLINE\nvoid mat_copy(const T m1[][c], T m2[][c])\n{\n    std::copy(m1[0], m1[0]+(r*c), m2[0]);\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\ntemplate<unsigned int r, unsigned int c, typename T>\nCINO_INLINE\nvoid mat_print(const T m[][c])\n{\n    for(unsigned int i=0; i<r; ++i)\n    for(unsigned int j=0; j<c; ++j)\n    {\n        if(i>0 && j%c==0) std::cout << \"\\n\";\n        std::cout << m[i][j] << \" \";\n    }\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\ntemplate<typename T>\nCINO_INLINE\nvec3<T> operator*(const mat4<T>& mat, const vec3<T>& vec)\n{\n    vec4<T> prod(mat * vec.add_coord(1));\n    prod /= prod[3];\n    return prod.rem_coord();\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\ntemplate<unsigned int r0, unsigned int c0, unsigned int c1, typename T>\nCINO_INLINE\nvoid mat_times(const T m0[][c0], const T m1[][c1], T m2[][c1])\n{\n    for(unsigned int i=0; i<r0; ++i)\n    for(unsigned int j=0; j<c1; ++j)\n    {\n        m2[i][j] = 0;\n        for(unsigned int k=0; k<c0; ++k)\n        {\n            m2[i][j] += m0[i][k] * m1[k][j];\n        }\n    }\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\n}\n", "meta": {"hexsha": "d5a31670101ddf8e9bb6f336a34103f98e58a110", "size": 29695, "ext": "tpp", "lang": "C++", "max_stars_repo_path": "include/cinolib/geometry/vec_mat_utils.tpp", "max_stars_repo_name": "francescozoccheddu/cinolib", "max_stars_repo_head_hexsha": "6d6f7d359db673aca1c203a208f50e0a7a362b76", "max_stars_repo_licenses": ["MIT"], "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/cinolib/geometry/vec_mat_utils.tpp", "max_issues_repo_name": "francescozoccheddu/cinolib", "max_issues_repo_head_hexsha": "6d6f7d359db673aca1c203a208f50e0a7a362b76", "max_issues_repo_licenses": ["MIT"], "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/cinolib/geometry/vec_mat_utils.tpp", "max_forks_repo_name": "francescozoccheddu/cinolib", "max_forks_repo_head_hexsha": "6d6f7d359db673aca1c203a208f50e0a7a362b76", "max_forks_repo_licenses": ["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.7005597015, "max_line_length": 157, "alphanum_fraction": 0.4294662401, "num_tokens": 8442, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.4853578349566204}}
{"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#include <NTL/ZZ.h>\n\n#include <helib/helib.h>\n#include <helib/permutations.h>\n#include <helib/debugging.h>\n\n#include \"gtest/gtest.h\"\n#include \"test_common.h\"\n\nnamespace {\n\nstruct Parameters\n{\n\n  long test;\n  long m;\n  long p;\n  long r;\n  long depth;\n  long L;\n  long ord1;\n  long ord2;\n  long ord3;\n  long ord4;\n  long good1;\n  long good2;\n  long good3;\n  long good4;\n\n  Parameters(long test,\n             long m,\n             long p,\n             long r,\n             long depth,\n             long L,\n             long ord1,\n             long ord2,\n             long ord3,\n             long ord4,\n             long good1,\n             long good2,\n             long good3,\n             long good4) :\n      test(test),\n      m(m),\n      p(p),\n      r(r),\n      depth(depth),\n      L(L),\n      ord1(ord1),\n      ord2(ord2),\n      ord3(ord3),\n      ord4(ord4),\n      good1(good1),\n      good2(good2),\n      good3(good3),\n      good4(good4){};\n\n  // Let googletest know how to print the Parameters\n  friend std::ostream& operator<<(std::ostream& os, const Parameters& params)\n  {\n    return os << \"{\"\n              << \"test=\" << params.test << \",\"\n              << \"p=\" << params.p << \",\"\n              << \"r=\" << params.r << \",\"\n              << \"m=\" << params.m << \",\"\n              << \"depth=\" << params.depth << \",\"\n              << \"L=\" << params.L << \",\"\n              << \"ord1=\" << params.ord1 << \",\"\n              << \"ord2=\" << params.ord2 << \",\"\n              << \"ord3=\" << params.ord3 << \",\"\n              << \"ord4=\" << params.ord4 << \",\"\n              << \"good1=\" << params.good1 << \",\"\n              << \"good2=\" << params.good2 << \",\"\n              << \"good3=\" << params.good3 << \",\"\n              << \"good4=\" << params.good4 << \"}\";\n  };\n};\n\nclass GTestPermutations : public ::testing::TestWithParam<Parameters>\n{\nprotected:\n  GTestPermutations() :\n      test(GetParam().test),\n      m(GetParam().m),\n      p(GetParam().p),\n      r(GetParam().r),\n      depth(GetParam().depth),\n      L(GetParam().L),\n      ord1(GetParam().ord1),\n      ord2(GetParam().ord2),\n      ord3(GetParam().ord3),\n      ord4(GetParam().ord4),\n      good1(GetParam().good1),\n      good2(GetParam().good2),\n      good3(GetParam().good3),\n      good4(GetParam().good4){};\n\n  long test;\n  long m;\n  long p;\n  long r;\n  long depth;\n  long L;\n  long ord1;\n  long ord2;\n  long ord3;\n  long ord4;\n  long good1;\n  long good2;\n  long good3;\n  long good4;\n\n  virtual void SetUp() override { helib::setDryRun(helib_test::dry); };\n\n  virtual void TearDown() override { helib::cleanupGlobals(); }\n};\n\nvoid testCube(NTL::Vec<helib::GenDescriptor>& vec, long widthBound)\n{\n  helib::GeneratorTrees trees;\n  long cost = trees.buildOptimalTrees(vec, widthBound);\n  if (!helib_test::noPrint) {\n    std::cout << \"@TestCube: trees=\" << trees << std::endl;\n    std::cout << \" cost =\" << cost << std::endl;\n  }\n  NTL::Vec<long> dims;\n  trees.getCubeDims(dims);\n  helib::CubeSignature sig(dims);\n\n  for (long cnt = 0; cnt < 3; cnt++) {\n    helib::Permut pi;\n    helib::randomPerm(pi, trees.getSize());\n\n    helib::PermNetwork net;\n    net.buildNetwork(pi, trees);\n\n    helib::HyperCube<long> cube1(sig), cube2(sig);\n    for (long i = 0; i < cube1.getSize(); i++)\n      cube1[i] = i;\n    helib::HyperCube<long> cube3 = cube1;\n    helib::applyPermToVec(\n        cube2.getData(), cube1.getData(), pi); // direct application\n    net.applyToCube(cube3);                    // applying permutation netwrok\n\n    const auto getErrorMessage = [&cube1, &cube2, &cube3]() {\n      std::ostringstream os;\n      if (cube1.getSize() < 100 && !helib_test::noPrint)\n        os << \"in=\" << cube1.getData() << std::endl\n           << \"out1=\" << cube2.getData() << \", out2=\" << cube3.getData()\n           << std::endl\n           << std::endl;\n      return os;\n    };\n\n    ASSERT_EQ(cube2, cube3) << getErrorMessage().str();\n  }\n}\n\nvoid testCtxt(long m, long p, long widthBound = 0, long L = 0, long r = 1);\n\nvoid testCtxt(long m, long p, long widthBound, long L, long r)\n{\n  if (!helib_test::noPrint)\n    std::cout << \"@testCtxt(m=\" << m << \",p=\" << p << \",depth=\" << widthBound\n              << \",r=\" << r << \")\";\n\n  helib::Context context(m, p, r);\n  helib::EncryptedArray ea(context); // Use G(X)=X for this ea object\n\n  // Some arbitrary initial plaintext array\n  std::vector<long> in(ea.size());\n  for (long i = 0; i < ea.size(); i++)\n    in[i] = i % p;\n\n  // Setup generator-descriptors for the PAlgebra generators\n  NTL::Vec<helib::GenDescriptor> vec(NTL::INIT_SIZE, ea.dimension());\n  for (long i = 0; i < ea.dimension(); i++)\n    vec[i] = helib::GenDescriptor(/*order=*/ea.sizeOfDimension(i),\n                                  /*good=*/ea.nativeDimension(i),\n                                  /*genIdx=*/i);\n\n  // Some default for the width-bound, if not provided\n  if (widthBound <= 0)\n    widthBound = 1 + log2((double)ea.size());\n\n  // Get the generator-tree structures and the corresponding hypercube\n  helib::GeneratorTrees trees;\n  long cost = trees.buildOptimalTrees(vec, widthBound);\n  if (!helib_test::noPrint) {\n    context.zMStar.printout();\n    std::cout << \": trees=\" << trees << std::endl;\n    std::cout << \" cost =\" << cost << std::endl;\n  }\n  //  NTL::Vec<long> dims;\n  //  trees.getCubeDims(dims);\n  //  helib::CubeSignature sig(dims);\n\n  // 1/2 prime per level should be more or less enough, here we use 1 per layer\n  if (L <= 0)\n    L = (1 + trees.numLayers()) * context.BPL();\n  helib::buildModChain(context, /*nLevels=*/L, /*nDigits=*/3);\n  if (!helib_test::noPrint)\n    std::cout << \"**Using \" << L << \" and \" << context.ctxtPrimes.card()\n              << \" Ctxt-primes)\\n\";\n\n  // Generate a sk/pk pair\n  helib::SecKey secretKey(context);\n  const helib::PubKey& publicKey = secretKey;\n  secretKey.GenSecKey(); // A +-1/0 secret key\n  helib::Ctxt ctxt(publicKey);\n\n  for (long cnt = 0; cnt < 3; cnt++) {\n    helib::resetAllTimers();\n    // Choose a random permutation\n    helib::Permut pi;\n    helib::randomPerm(pi, trees.getSize());\n\n    // Build a permutation network for pi\n    helib::PermNetwork net;\n    net.buildNetwork(pi, trees);\n\n    // make sure we have the key-switching matrices needed for this network\n    helib::addMatrices4Network(secretKey, net);\n\n    // Apply the permutation pi to the plaintext\n    std::vector<long> out1(ea.size());\n    std::vector<long> out2(ea.size());\n    helib::applyPermToVec(out1, in, pi); // direct application\n\n    // Encrypt plaintext array, then apply permutation network to ciphertext\n    ea.encrypt(ctxt, publicKey, in);\n    if (!helib_test::noPrint)\n      std::cout << \"  ** applying permutation network to ciphertext... \"\n                << std::flush;\n    double t = NTL::GetTime();\n    net.applyToCtxt(ctxt, ea); // applying permutation netwrok\n    t = NTL::GetTime() - t;\n    if (!helib_test::noPrint)\n      std::cout << \"done in \" << t << \" seconds\" << std::endl;\n    ea.decrypt(ctxt, secretKey, out2);\n\n    ASSERT_EQ(out1, out2);\n    // printAllTimers();\n  }\n}\n\n/* m = 31, p = 2, phi(m) = 30\n  ord(p)=5\n  generator 6 has order (== Z_m^*) of 6\n  T = [1 6 5 30 25 26 ]\n\n  m = 61, p = 3, phi(m) = 60\n  ord(p)=10\n  generator 13 has order (== Z_m^*) of 3\n  generator 2 has order (!= Z_m^*) of 2\n  T = [1 2 13 26 47 33 ]\n\n  m = 683, p = 2, phi(m) = 682\n  ord(p)=22\n  generator 3 has order (== Z_m^*) of 31\n\n  m = 47127, p = 2, phi(m) = 30008\n  ord(p)=22\n  generator 5 has order (== Z_m^*) of 682\n  generator 13661 has order (== Z_m^*) of 2\n*/\n\nTEST_P(GTestPermutations, ciphertextPermutations)\n{\n  if (test == 0 || helib_test::dry != 0) {\n    NTL::Vec<helib::GenDescriptor> vec;\n    long nGens;\n    if (ord2 <= 1)\n      nGens = 1;\n    else if (ord3 <= 1)\n      nGens = 2;\n    else if (ord4 <= 1)\n      nGens = 3;\n    else\n      nGens = 4;\n    vec.SetLength(nGens);\n\n    switch (nGens) {\n    case 4:\n      vec[3] = helib::GenDescriptor(ord4, good4, /*genIdx=*/3);\n    case 3:\n      vec[2] = helib::GenDescriptor(ord3, good3, /*genIdx=*/2);\n    case 2:\n      vec[1] = helib::GenDescriptor(ord2, good2, /*genIdx=*/1);\n    default:\n      vec[0] = helib::GenDescriptor(ord1, good1, /*genIdx=*/0);\n    }\n    if (!helib_test::noPrint) {\n      std::cout << \"***Testing \";\n      if (helib::isDryRun())\n        std::cout << \"(dry run) \";\n      for (long i = 0; i < vec.length(); i++)\n        std::cout << \"(\" << vec[i].order << \",\" << vec[i].good << \")\";\n      std::cout << \", depth=\" << depth << \"\\n\";\n    }\n    ASSERT_NO_FATAL_FAILURE(testCube(vec, depth));\n  } else {\n    helib::setTimersOn();\n    if (!helib_test::noPrint) {\n      std::cout << \"***Testing m=\" << m << \", p=\" << p << \", depth=\" << depth\n                << std::endl;\n    }\n    ASSERT_NO_FATAL_FAILURE(testCtxt(m, p, depth, L, r));\n  }\n};\n\nINSTANTIATE_TEST_SUITE_P(\n    defaultParameters,\n    GTestPermutations,\n    ::testing::Values(\n        // FAST\n        // Parameters(1, 91, 2, 1, 5, 0, 30, 0, 0, 0, 1, 1, 1, 1)\n        // SLOW\n        Parameters(1, 4369, 2, 1, 5, 0, 30, 0, 0, 0, 1, 1, 1, 1)));\n\n} // namespace\n\n#if 0\n  std::cout << \"***Testing m=31, p=2, width=3\\n\"; // (6 good)\n  testCtxt(/*m=*/31, /*p=*/2, /*width=*/3);\n\n  std::cout << \"\\n***Testing m=61, p=3, width=3\\n\"; // (3 good), (2, bad)\n  testCtxt(/*m=*/61, /*p=*/3, /*width=*/3);\n\n  std::cout << \"\\n***Testing m=683, p=2, width=5\\n\"; // (31, good)\n  testCtxt(/*m=*/683, /*p=*/2, /*width=*/5);\n\n  //  std::cout << \"\\n***Testing m=47127, p=2, width=11\\n\"; // (682,good),(2,good)\n  //  testCtxt(/*m=*/47127, /*p=*/2, /*width=*/11);\n\n  // Test 1: a single good small prime-order generator (3)\n  {\n  NTL::Vec<helib::GenDescriptor> vec(INIT_SIZE, 1);\n  vec[0] = helib::GenDescriptor(/*order=*/3, /*good=*/true, /*genIdx=*/0);\n  std::cout << \"***Testing (3,good), width=1\\n\";\n  testCube(vec, /*width=*/1);\n  }\n\n  // Test 2: a single bad larger prime-order generator (31)\n  {\n  NTL::Vec<helib::GenDescriptor> vec(INIT_SIZE, 1);\n  vec[0] = helib::GenDescriptor(/*order=*/31, /*good=*/false, /*genIdx=*/0);\n  std::cout << \"\\n***Testing (31,bad), width=5\\n\";\n  testCube(vec, /*width=*/5);\n  }\n\n  // Test 3: two generators with small prime orders (2,3), both bad\n  {\n  NTL::Vec<helib::GenDescriptor> vec(INIT_SIZE, 2);\n  vec[0] = helib::GenDescriptor(/*order=*/2, /*good=*/false, /*genIdx=*/0);\n  vec[1] = helib::GenDescriptor(/*order=*/3, /*good=*/false, /*genIdx=*/1);\n  std::cout << \"\\n***Testing [(2,bad),(3,bad)], width=3\\n\";\n  testCube(vec, /*width=*/3);\n  }\n\n  // Test 4: two generators with small prime orders (2,3), one good\n  {\n  NTL::Vec<helib::GenDescriptor> vec(INIT_SIZE, 2);\n  vec[0] = helib::GenDescriptor(/*order=*/3, /*good=*/true, /*genIdx=*/0);\n  vec[1] = helib::GenDescriptor(/*order=*/2, /*good=*/false, /*genIdx=*/1);\n  std::cout << \"\\n***Testing [(3,good),(2,bad)], width=3\\n\";\n  testCube(vec, /*width=*/3);\n  }\n\n  // Test 5: a single good composite-order generator (6)\n  {\n  NTL::Vec<helib::GenDescriptor> vec(INIT_SIZE, 1);\n  vec[0] = helib::GenDescriptor(/*order=*/6, /*good=*/true, /*genIdx=*/0);\n  std::cout << \"\\n***Testing (6,good), width=3\\n\";\n  testCube(vec, /*width=*/3);\n  }\n\n  // Test 6: (6,good),(2,bad)\n  {\n  NTL::Vec<helib::GenDescriptor> vec(INIT_SIZE, 2);\n  vec[0] = helib::GenDescriptor(/*order=*/6,/*good=*/true, /*genIdx=*/0);\n  vec[1] = helib::GenDescriptor(/*order=*/ 2, /*good=*/false,/*genIdx=*/1);\n  std::cout << \"\\n**Testing [(6,good),(2,bad)], width=5\\n\";\n  testCube(vec, /*width=*/5);\n  }\n\n  // Test 7: the \"general case\", (682,good),(2,bad)\n  {\n  NTL::Vec<helib::GenDescriptor> vec(INIT_SIZE, 2);\n  vec[0] = helib::GenDescriptor(/*order=*/682,/*good=*/true, /*genIdx=*/0);\n  vec[1] = helib::GenDescriptor(/*order=*/ 2, /*good=*/false,/*genIdx=*/1);\n  std::cout << \"\\n**Testing [(682,good),(2,bad)], width=11\\n\";\n  testCube(vec, /*width=*/11);\n  }\n#endif\n", "meta": {"hexsha": "b848781162c3365e455a3d920e598b96ee61d964", "size": 12376, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/GTestPermutations.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": "tests/GTestPermutations.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": "tests/GTestPermutations.cpp", "max_forks_repo_name": "Souhail-MEFTAH/HElib", "max_forks_repo_head_hexsha": "5f97813b99407d6f9a6251cee920b4e419edc028", "max_forks_repo_licenses": ["Apache-2.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.2591687042, "max_line_length": 82, "alphanum_fraction": 0.5622979961, "num_tokens": 3900, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286833, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.48535783495662027}}
{"text": "/*******************************************************************************\nCopyright (c) 2011, Dr. D. Studios\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 other\nmaterials provided with the distribution.\nNeither the name of the Dr. D. Studios nor the names of its contributors may be\nused to endorse or promote products derived from this software without specific\nprior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\nIN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\nINDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\nBUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\nOR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\nOF THE POSSIBILITY OF SUCH DAMAGE.\n*******************************************************************************/\n\n#ifndef _PIMATH_FRAME__H_\n#define _PIMATH_FRAME__H_\n\n#include <boost/python.hpp>\n#include <ImathFrame.h>\n#include \"util.h\"\n\nnamespace pimath\n{\n\tnamespace bp = boost::python;\n\n\ttemplate<typename T>\n\tstruct FrameBind\n\t{\n\t\ttypedef Imath::Vec3<T> \t\tvec3_type;\n\t\ttypedef Imath::Matrix44<T> \tmat44_type;\n\n\t\tFrameBind()\n\t\t{\n\t\t\tbp::def(\"firstFrame\", &Imath::firstFrame<T>);\n\t\t\tbp::def(\"nextFrame\", &Imath::nextFrame<T>);\n\t\t\tbp::def(\"lastFrame\", &Imath::lastFrame<T>);\n\t\t}\n\t};\n}\n\n#endif\n\n", "meta": {"hexsha": "ab57e1577284beede62ae5fc26158b624c5fc769", "size": 2114, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Frame.hpp", "max_stars_repo_name": "madpianist/pimath", "max_stars_repo_head_hexsha": "d79c56d492887d52e1e6f7ec0ffa1966a4717b0a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-07-22T21:32:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-22T21:32:34.000Z", "max_issues_repo_path": "src/Frame.hpp", "max_issues_repo_name": "madpianist/pimath", "max_issues_repo_head_hexsha": "d79c56d492887d52e1e6f7ec0ffa1966a4717b0a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Frame.hpp", "max_forks_repo_name": "madpianist/pimath", "max_forks_repo_head_hexsha": "d79c56d492887d52e1e6f7ec0ffa1966a4717b0a", "max_forks_repo_licenses": ["BSD-3-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.0877192982, "max_line_length": 82, "alphanum_fraction": 0.7232734153, "num_tokens": 444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286833, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.48535783495662027}}
{"text": "#ifndef STAN_MATH_PRIM_FUN_RISING_FACTORIAL_HPP\n#define STAN_MATH_PRIM_FUN_RISING_FACTORIAL_HPP\n\n#include <stan/math/prim/meta.hpp>\n#include <stan/math/prim/err.hpp>\n#include <stan/math/prim/fun/boost_policy.hpp>\n#include <boost/math/special_functions/factorials.hpp>\n\nnamespace stan {\nnamespace math {\n\n/**\n * Return the rising factorial function evaluated\n * at the inputs.\n *\n * @tparam T type of the first argument\n * @param x first argument\n * @param n second argument\n * @return Result of rising factorial function.\n * @throw std::domain_error if x is NaN\n * @throw std::domain_error if n is negative\n *\n \\f[\n \\mbox{rising\\_factorial}(x, n) =\n \\begin{cases}\n \\textrm{error} & \\mbox{if } x \\leq 0\\\\\n x^{(n)} & \\mbox{if } x > 0 \\textrm{ and } -\\infty \\leq n \\leq \\infty \\\\[6pt]\n \\textrm{NaN} & \\mbox{if } x = \\textrm{NaN or } n = \\textrm{NaN}\n \\end{cases}\n \\f]\n\n \\f[\n \\frac{\\partial\\, \\mbox{rising\\_factorial}(x, n)}{\\partial x} =\n \\begin{cases}\n \\textrm{error} & \\mbox{if } x \\leq 0\\\\\n \\frac{\\partial\\, x^{(n)}}{\\partial x} & \\mbox{if } x > 0 \\textrm{ and } -\\infty\n \\leq n \\leq \\infty \\\\[6pt] \\textrm{NaN} & \\mbox{if } x = \\textrm{NaN or } n =\n \\textrm{NaN} \\end{cases} \\f]\n\n \\f[\n \\frac{\\partial\\, \\mbox{rising\\_factorial}(x, n)}{\\partial n} =\n \\begin{cases}\n \\textrm{error} & \\mbox{if } x \\leq 0\\\\\n \\frac{\\partial\\, x^{(n)}}{\\partial n} & \\mbox{if } x > 0 \\textrm{ and } -\\infty\n \\leq n \\leq \\infty \\\\[6pt] \\textrm{NaN} & \\mbox{if } x = \\textrm{NaN or } n =\n \\textrm{NaN} \\end{cases} \\f]\n\n \\f[\n x^{(n)}=\\frac{\\Gamma(x+n)}{\\Gamma(x)}\n \\f]\n\n \\f[\n \\frac{\\partial \\, x^{(n)}}{\\partial x} = x^{(n)}(\\Psi(x+n)-\\Psi(x))\n \\f]\n\n \\f[\n \\frac{\\partial \\, x^{(n)}}{\\partial n} = (x)_n\\Psi(x+n)\n \\f]\n *\n */\ntemplate <typename T>\ninline return_type_t<T> rising_factorial(const T& x, int n) {\n  static const char* function = \"rising_factorial\";\n  check_not_nan(function, \"first argument\", x);\n  check_nonnegative(function, \"second argument\", n);\n  return boost::math::rising_factorial(x, n, boost_policy_t());\n}\n\n}  // namespace math\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "ce262562b068ac174bec9c6abd6f1770aef404b8", "size": 2053, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/prim/fun/rising_factorial.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/fun/rising_factorial.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/fun/rising_factorial.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": 28.5138888889, "max_line_length": 80, "alphanum_fraction": 0.6361422309, "num_tokens": 754, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799252, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.4853578273527159}}
{"text": "#include <iostream>\n#include <vector>\n#include <set>\n#include <map>\n#include <algorithm>\n\nusing namespace std;\n\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/cycle_canceling.hpp>\n#include <boost/graph/push_relabel_max_flow.hpp>\n#include <boost/graph/successive_shortest_path_nonnegative_weights.hpp>\n#include <boost/graph/find_flow_cost.hpp>\n\ntypedef boost::adjacency_list_traits<boost::vecS, boost::vecS, boost::directedS> traits;\ntypedef boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS, boost::no_property,\n    boost::property<boost::edge_capacity_t, long,\n        boost::property<boost::edge_residual_capacity_t, long,\n            boost::property<boost::edge_reverse_t, traits::edge_descriptor,\n                boost::property <boost::edge_weight_t, long>>>>> graph;\n\ntypedef boost::graph_traits<graph>::edge_descriptor             edge_desc;\ntypedef boost::graph_traits<graph>::out_edge_iterator           out_edge_it;\n\n\nclass edge_adder {\n graph &G;\n\n public:\n  explicit edge_adder(graph &G) : G(G) {}\n  void add_edge(int from, int to, long capacity, long cost) {\n    auto c_map = boost::get(boost::edge_capacity, G);\n    auto r_map = boost::get(boost::edge_reverse, G);\n    auto w_map = boost::get(boost::edge_weight, G); // new!\n    const edge_desc e = boost::add_edge(from, to, G).first;\n    const edge_desc rev_e = boost::add_edge(to, from, G).first;\n    c_map[e] = capacity;\n    c_map[rev_e] = 0; // reverse edge has no capacity!\n    r_map[e] = rev_e;\n    r_map[rev_e] = e;\n    w_map[e] = cost;   // new assign cost\n    w_map[rev_e] = -cost;   // new negative cost\n  }\n};\n\n// Strategy:\n// - Build a space-time graph, i.e. a vertex is described by a tuple (i, t) where i is the rental station and t is the time\n//   - We add edges for every booking and for parking (stay at the same station until the next time step)\n//   - Use Maxflow-Mincost to solve the problem\nvoid solve() {\n  \n  // Read input\n  int n, m;\n  cin >> n >> m;\n  \n  vector<int> l(m); // initially available cars\n  int sumCars = 0; // How many cars are there in total?\n  for (int j = 0; j < m; ++j) {\n    cin >> l[j];\n    sumCars += l[j];\n  }\n  \n  // Save the relevant timesteps for each station (a timestep is only relevant if a booking starts or ends at the given station)\n  vector<set<int>> timePoints(m); \n  \n  vector<int> s(n); // source\n  vector<int> t(n); // target\n  vector<int> d(n); // departure time\n  vector<int> a(n); // arrival time\n  vector<int> p(n); // profit\n  int tMax = 0;\n  for (int i = 0; i < n; ++i) {\n    \n    // Read input\n    cin >> s[i] >> t[i] >> d[i] >> a[i] >> p[i];\n    --s[i]; --t[i]; // convert 1-based to 0-based indices\n    \n    // Save relevant time points\n    timePoints[s[i]].insert(d[i]);\n    timePoints[t[i]].insert(a[i]);\n    tMax = max(tMax, a[i]);\n  }\n  \n  // Time 0 and tMax are relevant for connecting to source and target\n  for (int j = 0; j < m; ++j) {\n    timePoints[j].insert(0);\n    timePoints[j].insert(tMax);\n  }\n  \n  // For every station:\n  // - Assign a vertex id to every time point \n  // - Sort relevant time points\n  vector<map<int, int>> timeToVertex(m);\n  vector<vector<int>> sortedTimePoints(m);\n  int id = 0;\n  for (int j = 0; j < m; ++j) {\n    for (int t : timePoints[j]) {\n      timeToVertex[j][t] = id++;\n      sortedTimePoints[j].push_back(t);\n    }\n    sort(sortedTimePoints[j].begin(), sortedTimePoints[j].end());\n  }\n  \n  // Create graph\n  int N = id;\n  graph G(N);\n  edge_adder adder(G);  \n  \n  // Connect consecutive time points\n  for (int j = 0; j < m; ++j) {\n    for (int i = 0; i < sortedTimePoints[j].size() - 1; ++i) {\n      int t0 = sortedTimePoints[j][i];\n      int t1 = sortedTimePoints[j][i + 1];\n      adder.add_edge(timeToVertex[j][t0], timeToVertex[j][t1], sumCars, 100 * (t1 - t0));\n    }\n  }\n  \n  // Add edges for booking requests\n  for (int i = 0; i < n; ++i) {\n    adder.add_edge(timeToVertex[s[i]][d[i]], timeToVertex[t[i]][a[i]], 1, 100 * (a[i] - d[i]) - p[i]);\n  }\n\n  // Connect source and sink\n  int source = boost::add_vertex(G);\n  int target = boost::add_vertex(G);\n  for (int j = 0; j < m; ++j) {\n    adder.add_edge(source, timeToVertex[j][0], l[j], 0);\n    adder.add_edge(timeToVertex[j][tMax], target, sumCars, 0);\n  }\n\n  boost::successive_shortest_path_nonnegative_weights(G, source, target);\n  int cost = boost::find_flow_cost(G);\n  cost = 100 * sumCars * tMax - cost;\n\n  cout << cost << endl;\n}\n\nint main() {\n  ios_base::sync_with_stdio(false);\n  int t; \n  cin >> t;\n  while (t--) {\n    solve();\n  }\n  return 0;\n}", "meta": {"hexsha": "dd459ca22070f5750a7a00b56bb98bbca4961b52", "size": 4521, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/carsharing.cpp", "max_stars_repo_name": "dsparber/algolab", "max_stars_repo_head_hexsha": "9781eb5c7444236f796f167f1f39fc9d913e5c53", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2021-01-01T17:19:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T12:27:57.000Z", "max_issues_repo_path": "src/carsharing.cpp", "max_issues_repo_name": "dsparber/algolab", "max_issues_repo_head_hexsha": "9781eb5c7444236f796f167f1f39fc9d913e5c53", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/carsharing.cpp", "max_forks_repo_name": "dsparber/algolab", "max_forks_repo_head_hexsha": "9781eb5c7444236f796f167f1f39fc9d913e5c53", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-28T10:55:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-28T10:55:25.000Z", "avg_line_length": 30.9657534247, "max_line_length": 128, "alphanum_fraction": 0.6275160363, "num_tokens": 1357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.48529890577536344}}
{"text": "// Copyright 2022 Haruki Uchiito\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\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 DEALINGS\n// IN THE SOFTWARE.\n\n#ifndef NDT_2D_SLAM__DATA_TYPES_HPP_\n#define NDT_2D_SLAM__DATA_TYPES_HPP_\n\n#include <Eigen/Core>\n#include <algorithm>\n#include <iostream>\n#include <utility>\n#include <vector>\n\nnamespace NDT2DSLAM {\n\n/**\n * @brief Transform2D represensts homogeneous transformation in 2D space\n */\nstruct Transform2D {\n    // parameters\n    double tx, ty;  // translation [m]\n    double theta;   // rotation [rad]\n\n    // homogeneous transformation matrix type\n    typedef Eigen::Matrix<double, 3, 3> TransformMat;\n    TransformMat matrix;\n\n    void setMatrix() {\n        double ct = cos(theta);\n        double st = sin(theta);\n        matrix << ct, -st, tx, st, ct, ty, 0, 0, 1;\n    }\n\n    Transform2D()\n        : tx(0.0), ty(0.0), theta(0.0), matrix(TransformMat::Identity()) {}\n    Transform2D(double tx_, double ty_, double theta_)\n        : tx(tx_), ty(ty_), theta(theta_) {\n        setMatrix();\n    }\n    Transform2D(const Transform2D& another)\n        : tx(another.tx),\n          ty(another.ty),\n          theta(another.theta),\n          matrix(another.matrix) {}\n\n    Transform2D& operator+=(const Transform2D& another) {\n        tx += another.tx;\n        ty += another.ty;\n        theta += another.theta;\n        setMatrix();\n        return *this;\n    }\n    Transform2D& operator=(const Transform2D& another) {\n        tx = another.tx;\n        ty = another.ty;\n        theta = another.theta;\n        setMatrix();\n        return *this;\n    }\n    friend std::ostream& operator<<(std::ostream& os,\n                                    const Transform2D& transform) {\n        os << \"Transform2D tx: \" << transform.tx << \", ty: \" << transform.ty\n           << \", theta: \" << transform.theta;\n        return os;\n    }\n};\n\n/**\n * @brief Scan2D represensts pointcloud in 2D space\n */\nstruct Scan2D {\n    // scan points container\n    // each row contains positions of each points\n    // < x1 x2 ...\n    //   y1 y2 ...\n    //    1  1 ... >\n    // last lines is required for homogeneous transformation of points.\n    // data is stored in row-major order for ease of entire row access.\n    typedef Eigen::Matrix<double, 3, Eigen::Dynamic, Eigen::RowMajor> ScanMat;\n\n    ScanMat points;\n\n    Scan2D() {}\n    explicit Scan2D(size_t n) : points(ScanMat::Constant(3, n, 1.0)) {}\n    Scan2D(const Scan2D& scan) : points(scan.points) {}\n    /**\n     * @brief Construct a new Scan2D object from std::vector containing\n     * positions\n     * @param[in] x, y position of scan points\n     */\n    Scan2D(const std::vector<double>& x, const std::vector<double>& y) {\n        int pNum = static_cast<int>(x.size());\n        if (pNum == 0)\n            throw std::invalid_argument(\"input size must be over zero\");\n        if (pNum != static_cast<int>(y.size()))\n            throw std::invalid_argument(\"size of vector x and y must be same\");\n\n        points = ScanMat::Constant(3, pNum, 1.0);\n        for (int i = 0; i < pNum; ++i) {\n            points(0, i) = x[i];\n            points(1, i) = y[i];\n        }\n    }\n\n    Scan2D transformBy(const Transform2D& transform) const {\n        Scan2D ret(*this);\n        ret.points = transform.matrix * points;\n        return ret;\n    }\n\n    Scan2D& operator+=(const Scan2D& another) {\n        size_t pcol = points.cols(), acol = another.points.cols();\n        size_t ncol = pcol + acol;\n        ScanMat npoints = ScanMat::Constant(3, ncol, 1.0);\n        std::copy(points.data(), points.data() + pcol, npoints.data());\n        std::copy(points.data() + pcol, points.data() + pcol + pcol,\n                  npoints.data() + ncol);\n        // copy another\n        std::copy(another.points.data(), another.points.data() + acol,\n                  npoints.data() + pcol);  // x\n        std::copy(another.points.data() + acol,\n                  another.points.data() + acol + acol,\n                  npoints.data() + ncol + pcol);  // y\n\n        // npoints << points, another.points;\n        points = npoints;\n        return *this;\n    }\n\n    Scan2D& operator=(const Scan2D& another) {\n        points = another.points;\n        return *this;\n    }\n\n    std::vector<double> getRow(int i) const {\n        auto start = points.data() + points.cols() * i;\n        std::vector<double> ret(start, start + points.cols());\n        return ret;\n    }\n    std::vector<double> getXVec() const { return getRow(0); }\n    std::vector<double> getYVec() const { return getRow(1); }\n    double getX(int index) const { return points(0, index); }\n    double getY(int index) const { return points(1, index); }\n    size_t size() const { return points.cols(); }\n};\n\n}  // namespace NDT2DSLAM\n\n#endif  // NDT_2D_SLAM__DATA_TYPES_HPP_\n", "meta": {"hexsha": "f9998e8699cdab6f044b549983b4d316cbbee95a", "size": 5716, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ndt_2d_slam/data_types.hpp", "max_stars_repo_name": "HarukiUchito/ndt_2d_slam", "max_stars_repo_head_hexsha": "7063044fc11a3ba1e0d708741615334afcbb102a", "max_stars_repo_licenses": ["MIT"], "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/ndt_2d_slam/data_types.hpp", "max_issues_repo_name": "HarukiUchito/ndt_2d_slam", "max_issues_repo_head_hexsha": "7063044fc11a3ba1e0d708741615334afcbb102a", "max_issues_repo_licenses": ["MIT"], "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/ndt_2d_slam/data_types.hpp", "max_forks_repo_name": "HarukiUchito/ndt_2d_slam", "max_forks_repo_head_hexsha": "7063044fc11a3ba1e0d708741615334afcbb102a", "max_forks_repo_licenses": ["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": 79, "alphanum_fraction": 0.6142407278, "num_tokens": 1456, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872243177518, "lm_q2_score": 0.6477982315512488, "lm_q1q2_score": 0.48525737919067324}}
{"text": "#include <string>\n#include <iostream>\n#include <fstream>\n#include <stdexcept>\n#include <stdio.h>\n#include <vector>\n#include <utility>                          \n#include <algorithm>                      \n#include <sys/times.h>\n\n//includes from boost librabry\n#include <boost/config.hpp>\n#include <boost/utility.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 std;\nusing namespace boost;\n\n/** ex5 with timing.  \n *   \n *  @author Michael Brand  \n *  @date 20.06.2017 \n * \n *  @version 2.0 \n *  Merged ex5_old and ex5_boost \n */\n\n\nint maxEdgeWeight = 2e9; //*SETUP VARIABLES\n\n/**\n*   TIME MEASUREMENT FUNCTIONS\n*/\nclock_t times(struct tms *buffer);\n\nvoid start_clock(void);\nvoid end_clock(void);\n\nstatic clock_t st_time;\nstatic clock_t en_time;\nstatic struct tms st_cpu;\nstatic struct tms en_cpu;\n\n/** Function for time measurement\n*   Measuring the time\n*/\nvoid\nstart_clock()\n{\n    st_time = times(&st_cpu);\n}\n\nvoid\nend_clock()\n{\n    en_time = times(&en_cpu);\n\n    printf(\"\\nREAL TIME: %jd ms,\\nUSER TIME %jd ms,\\nSYSTEM TIME %jd ms.\\n\",\n        (intmax_t)(en_time - st_time)*10,\n        (intmax_t)(en_cpu.tms_utime - st_cpu.tms_utime)*10,\n        (intmax_t)(en_cpu.tms_stime - st_cpu.tms_stime))*10;\n}\n\n/**\n* STRUCTURE FOR OWN IMPLEMENTATION\n*/\n\n\n\n//* a structure to represent a weighted edge in graph\nstruct Edge\n{\n    int src, dest, weight;\n};\n//* a structure to represent a connected, directed and weighted graph\nstruct Graph\n{\n    // V-> Number of vertices, E-> Number of edges\n    int V, E;\n    // graph is represented as an array of edges.\n    struct Edge* edge;\n};\n \n//* Creates a graph with V vertices and E edges\nstruct Graph* createGraph(int V, int E)\n{\n    struct Graph* graph = (struct Graph*) malloc( sizeof(struct Graph) );\n    graph->V = V;\n    graph->E = E;\n \n    graph->edge = \n       (struct Edge*) malloc( graph->E * sizeof( struct Edge ) );\n \n    return graph;\n}\n\n//ALGOS\n\n/** gets longest path value.  \n   *  @param[in] dist[] int array of edges. \n   *  @param[in] n no. vertices.  \n   *  @return weight of longest path    \n   */\nint getLongestPathValue(int dist[], int n){\n  \n  int high = 0;\n\n  for(int i=0; i<n; i++){\n    if(dist[i]>high && dist[i]<=maxEdgeWeight) high = dist[i];\n  }\n\n  return high;\n}\n\n/** gets vertices with longest distance to source.  \n   *  @param[in] dist[] int array of edges. \n   *  @param[in] n no. vertices.\n   *  @param[in] val longest path value in graph\n   *  @return vector of vertices which have given path value in common    \n   */\nstd::vector<int> getLongestPathVertices(int dist[], int n, int val){\n  std::vector<int> v;\n  for(int i=0; i<n; i++){\n    if(dist[i] == val)\n      v.push_back(i);\n  }\n  return v;\n}\n\n/** gets vertex of longest way.  \n   *  @param[in] vertices possible vertices \n   *  @param[in] ecounter no. of edges to source\n   *  @return vertice with more edges or smaller index if even    \n   */\nint chooseWinner(std::vector<int> vertices,int ecounter[]){\n\n  int winner = vertices[0];\n\n  for(int i=1; i<vertices.size(); i++){\n    if(ecounter[vertices[i]] > ecounter[winner]){\n      winner = vertices[i];\n    } \n  }\n  return winner;\n}\n\n\n/** BellmanFord main algo  \n   *  @param[in] graph graph on which BF is executed \n   *  @param[in] src source node\n   */\nvoid BellmanFord(struct Graph* graph, int src)\n{\n    int V = graph->V;\n    int E = graph->E;\n    int dist[V];\n    int ecount[V];\n \n    // Initialize distances from src to all other vertices as INFINITE\n    for(int i = 0; i < V; i++){\n        dist[i]   = INT_MAX;\n        ecount[i] = 0;\n    }\n\n    dist[src] = 0;\n \n    // Relax all edges |V| - 1 times. A simple shortest \n    // path from src to any other vertex can have at-most |V| - 1 \n    // edges\n    for(int i = 1; i <= V-1; i++)\n    {\n        for (int j = 0; j < E; j++)\n        {\n            int u = graph->edge[j].src;\n            int v = graph->edge[j].dest;\n            int weight = graph->edge[j].weight;\n            if (dist[u] != INT_MAX && dist[u] + weight < dist[v]){\n                dist[v] = dist[u] + weight;\n                ecount[v] = ecount[u]+1;\n            }\n\n        }\n    }\n \n    // check for negative-weight cycles.  The above step \n    // guarantees shortest distances if graph doesn't contain \n    // negative weight cycle.  If we get a shorter path, then there\n    // is a cycle.\n    for (int i = 0; i < E; i++)\n    {\n        int u = graph->edge[i].src;\n        int v = graph->edge[i].dest;\n        int weight = graph->edge[i].weight;\n        if (dist[u] != INT_MAX && dist[u] + weight < dist[v])\n            fprintf(stderr, \"%s\", \"Graph contains negative weight cycle\");\n    }\n \n  int lPathVal = getLongestPathValue(dist,V);\n\n  std::vector<int> vert = getLongestPathVertices(dist, V, lPathVal);\n\n  int win = chooseWinner(vert, ecount);\n\n  fprintf(stdout, \"NON-BOOST mode\\nRESULT VERTEX %i \\nRESULT DIST %i \\n\", win+1, dist[win]);\n \n    return;\n}\n\n\n/** Main Method\n*   runrunrunrunrun\n*\n*/\nint main (int argc, char* argv[]) {\n    \n  start_clock(); //*start timer\n\n  //check for right number of arguments\n  if( argc != 3){\n      fprintf(stderr, \"%s\", \"Call programm as ex5 mode filename.gph, where mode is integer 1(boost) or 2(non-boost)\\n\");\n      exit(EXIT_FAILURE);\n  }\n  \n  int mode = stoi(argv[1]);\n\n  if(mode!=1 && mode!=2){\n    fprintf(stderr, \"%s\", \"mode argument needs to be 1(for boost) or 2(non-boost)\\n\");\n    exit(EXIT_FAILURE);\n  }\n\n  if(mode==1){\n  //Boost\n  ifstream    file(argv[2]);\n  string      line;\n\n  if(!file){\n    fprintf(stderr, \"%s\", \"Could not open file.\\n\");\n    exit(EXIT_FAILURE);\n\n  }\n\n\n  //property weighted graph\n  typedef property <edge_weight_t, int> EdgeWeightProperty;\n  //typedef for graph type: undirected, weighted graph\n  typedef adjacency_list <listS, vecS, undirectedS, no_property, EdgeWeightProperty> Graph;\n  //typedef to describe vertecies in boost library\n  typedef graph_traits <Graph>::vertex_descriptor vertex_descriptor;\n  //typedef for edges in the graph\n  typedef pair<int, int> Edge;\n  \n  \n  //read number of vertices and edges\n  getline(file, line, ' ');       \n  const int numV = stoi(line);\n  getline(file, line, '\\n');\n  const int numE = stoi(line);\n  \n  Edge* edges;\n  int* weights;\n\n\n//  Edge edges[numE];     //array containig edge-pairs\n//  int  weights[numE];   //array containing corresponding weights\n  int  edgecount = 0;\n  \n  edges = new Edge[numE];\n  weights = new int[numE];\n\n    //loop over all lines in the file\n  while( getline(file, line) ){\n\n    stringstream linestream(line);\n    string       vertex1, vertex2, weight;\n\n    try{\n      getline(linestream, vertex1, ' ');\n      getline(linestream, vertex2, ' ');\n      edges[edgecount] = Edge(stoi(vertex1), stoi(vertex2));     //store edges as pairs of vertices\n      \n\n      \n      getline(linestream, weight, '\\n');\n      weights[edgecount] = stoi(weight); //store corresponding weights\n\n      \n    } catch (std::invalid_argument& ia){\n      //when data is not a digit,\n      //std::stoi throws an invalid argument exception\n    } catch ( ... ){}\n    \n    edgecount++;\n    \n  }//while\n  file.close();\n  \n  //*create graph containig edges and weights\n  Graph g (edges, edges + numE, weights, numV);\n  //*setup for shortest path solver\n  property_map<Graph, edge_weight_t>::type weightmap = get(edge_weight, g);\n  std::vector<vertex_descriptor> pre(num_vertices(g));\n  //*vector to store distances to source vertex\n  std::vector<int> dist(num_vertices(g));\n  //*define source vertex to which shortest path shall be\n  //*computed from all other vertecies in graph g\n  vertex_descriptor source = vertex(edges[0].first, g);\n  \n  //*use dijkstra algorithm, since all edges are positive\n  dijkstra_shortest_paths(g, source,\n                          predecessor_map(make_iterator_property_map(pre.begin(), get(vertex_index, g))).\n                          distance_map(make_iterator_property_map(dist.begin(), get(vertex_index, g))));\n  int maxdist = 0;\n  int vertex  = 0;\n  \n  //*iterate over all vertecies and update\n  //*maximum disntance, if needed\n  graph_traits < Graph >::vertex_iterator vi, vend;\n  tie(vi, vend) = vertices(g);\n  vi++;\n  for (; vi != vend; ++vi) { \n    \n    if(dist[*vi] > maxdist){\n      maxdist = dist[*vi];\n      vertex  = *vi;\n    }\n  }\n  \n  fprintf(stdout, \"BOOST mode\\nRESULT VERTEX %i \\nRESULT DIST %i \\n\", vertex, maxdist);\n\n  end_clock();\n  return 0;\n\n  }\n\n\n  //OWN BELLMANFORD FROM COMA\n  else if(mode==2){\n    //nonboost\n\n  //Find shortest path to vertex of index...\n  int src=1;\n\n  string line;\n  \n  int err=0;\n  \n  int lcout = 0;\n  int ecount = 0;\n  int edgesTot;\n  int vertTot;\n\n  struct Graph* graph;\n\n    ifstream f (argv[2]);\n  \n    //* Read input file and create graph\n\n  while(getline(f, line)) {\n\n    lcout++;\n\n    stringstream buffer(line);\n    \n    int start = 0;\n    int end = 0;\n    int weight = 0;\n    \n    \n    buffer >> start >> end >> weight;\n    \n    //FROM EX1\n    if(lcout==1){\n      //std::cout << \"Graph setup\" << std::endl;\n        graph = createGraph(start, 2*end);\n        //fprintf(stdout, \"%s %d %s %d %s\\n\", \"Creating undirected Graph with \",start,\" nodes, \",end,\" edges.\");\n        edgesTot = end;\n        vertTot = start;\n    }\n    else{\n\n      if(start < 1 || start>vertTot || end < 1 || end > vertTot){\n        fprintf(stderr, \"%s \\t %d\\n\", \"errorline: \" , lcout);\n        err++;\n        continue;\n      }\n\n      if((weight <= 0 || weight>=2000000000 ) && lcout>1 ){\n        fprintf(stderr, \"%s \\t %d\\n\", \"errorline: \" , lcout);\n        err++;\n        continue;\n    }\n\n      if(ecount>=2*edgesTot){\n        cout << \"too many edges \" << buffer.str() << endl;\n        err++;\n        continue;\n      } \n    // INDEX SWITCH 1->0,...   \n      graph->edge[ecount].src = int(start-1);\n      graph->edge[ecount].dest = int(end-1);\n      graph->edge[ecount].weight = weight;\n\n      ecount++;\n\n      graph->edge[ecount].src = int(end-1);\n      graph->edge[ecount].dest = int(start-1);\n      graph->edge[ecount].weight = weight;\n\n      ecount++;\n    }\n    \n  }\n\n  f.close();\n\n  if(err>0) fprintf(stderr, \"%s \\t\\t %d\\n\", \"ERRORS\" , err);\n\n  if(ecount < 2*edgesTot){\n     fprintf(stderr, \"%s \\t\\t %s\\n\", \"INFO\", \"NOT ENOUGH EDGES DEFINED\");\n     return -1;\n  }\n\n// BELLMAN FORD FROM COMA\n\n  BellmanFord(graph, src-1);\n  \n  end_clock(); //* end timing and print stats\n\n  return 0;\n  }\n\n}\n", "meta": {"hexsha": "5560633ca682420a767438c98063b4393c8d4cf8", "size": 10402, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Brand/ex5/ex5.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": "Brand/ex5/ex5.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": "Brand/ex5/ex5.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": 23.9126436782, "max_line_length": 120, "alphanum_fraction": 0.5993078254, "num_tokens": 2905, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.6477982247516796, "lm_q1q2_score": 0.48525736683990356}}
{"text": "#include <CGAL/Simple_cartesian.h>\n#include <CGAL/Surface_mesh.h>\n\n#include <iostream>\n#include <fstream>\n\n#include <boost/graph/connected_components.hpp>\n\ntypedef CGAL::Simple_cartesian<double>                       Kernel;\ntypedef Kernel::Point_3                                      Point;\ntypedef CGAL::Surface_mesh<Point>                            Mesh;\n\ntypedef boost::graph_traits<Mesh>::vertex_descriptor vertex_descriptor;\n\nint main(int argc, char* argv[])\n{\n  const std::string filename = (argc > 1) ? argv[1] : CGAL::data_file_path(\"meshes/prim.off\");\n\n  Mesh sm;\n  if(!CGAL::IO::read_polygon_mesh(filename, sm))\n  {\n    std::cerr << \"Invalid input.\" << std::endl;\n    return 1;\n  }\n\n  Mesh::Property_map<vertex_descriptor,int> ccmap;\n  ccmap = sm.add_property_map<vertex_descriptor,int>(\"v:CC\").first;\n\n  int num = connected_components(sm, ccmap);\n  std::cout  << num << \" connected components\" << std::endl;\n  for(vertex_descriptor v : vertices(sm)){\n    std::cout  << v << \" is in component \" << ccmap[v] << std::endl;\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "33686a72428cfa02e5257ba6b56f9b4ed93812c2", "size": 1053, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "BGL/examples/BGL_surface_mesh/connected_components.cpp", "max_stars_repo_name": "ffteja/cgal", "max_stars_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 3227.0, "max_stars_repo_stars_event_min_datetime": "2015-03-05T00:19:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:20:35.000Z", "max_issues_repo_path": "BGL/examples/BGL_surface_mesh/connected_components.cpp", "max_issues_repo_name": "ffteja/cgal", "max_issues_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 5574.0, "max_issues_repo_issues_event_min_datetime": "2015-03-05T00:01:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:08:11.000Z", "max_forks_repo_path": "BGL/examples/BGL_surface_mesh/connected_components.cpp", "max_forks_repo_name": "ffteja/cgal", "max_forks_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1274.0, "max_forks_repo_forks_event_min_datetime": "2015-03-05T00:01:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:47:56.000Z", "avg_line_length": 28.4594594595, "max_line_length": 94, "alphanum_fraction": 0.6372269706, "num_tokens": 264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.749087201911703, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.48525736467607455}}
{"text": "//  (C) Copyright John Maddock 2006.\r\n//  Use, modification and distribution are subject to the\r\n//  Boost Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef BOOST_MATH_SF_CBRT_HPP\r\n#define BOOST_MATH_SF_CBRT_HPP\r\n\r\n#ifdef _MSC_VER\r\n#pragma once\r\n#endif\r\n\r\n#include <boost/math/tools/rational.hpp>\r\n#include <boost/math/policies/error_handling.hpp>\r\n#include <boost/math/special_functions/math_fwd.hpp>\r\n#include <boost/math/special_functions/fpclassify.hpp>\r\n#include <boost/mpl/divides.hpp>\r\n#include <boost/mpl/plus.hpp>\r\n#include <boost/mpl/if.hpp>\r\n#include <boost/type_traits/is_convertible.hpp>\r\n\r\nnamespace boost{ namespace math{\r\n\r\nnamespace detail\r\n{\r\n\r\nstruct big_int_type\r\n{\r\n   operator boost::uintmax_t()const;\r\n};\r\n\r\ntemplate <class T>\r\nstruct largest_cbrt_int_type\r\n{\r\n   typedef typename mpl::if_<\r\n      boost::is_convertible<big_int_type, T>,\r\n      boost::uintmax_t,\r\n      unsigned int\r\n   >::type type;\r\n};\r\n\r\ntemplate <class T, class Policy>\r\nT cbrt_imp(T z, const Policy& pol)\r\n{\r\n   BOOST_MATH_STD_USING\r\n   //\r\n   // cbrt approximation for z in the range [0.5,1]\r\n   // It's hard to say what number of terms gives the optimum\r\n   // trade off between precision and performance, this seems\r\n   // to be about the best for double precision.\r\n   //\r\n   // Maximum Deviation Found:                     1.231e-006\r\n   // Expected Error Term:                         -1.231e-006\r\n   // Maximum Relative Change in Control Points:   5.982e-004\r\n   //\r\n   static const T P[] = { \r\n      static_cast<T>(0.37568269008611818),\r\n      static_cast<T>(1.3304968705558024),\r\n      static_cast<T>(-1.4897101632445036),\r\n      static_cast<T>(1.2875573098219835),\r\n      static_cast<T>(-0.6398703759826468),\r\n      static_cast<T>(0.13584489959258635),\r\n   };\r\n   static const T correction[] = {\r\n      static_cast<T>(0.62996052494743658238360530363911),  // 2^-2/3\r\n      static_cast<T>(0.79370052598409973737585281963615),  // 2^-1/3\r\n      static_cast<T>(1),\r\n      static_cast<T>(1.2599210498948731647672106072782),   // 2^1/3\r\n      static_cast<T>(1.5874010519681994747517056392723),   // 2^2/3\r\n   };\r\n\r\n   if(!boost::math::isfinite(z))\r\n   {\r\n      return policies::raise_domain_error(\"boost::math::cbrt<%1%>(%1%)\", \"Argument to function must be finite but got %1%.\", z, pol);\r\n   }\r\n\r\n   int i_exp, sign(1);\r\n   if(z < 0)\r\n   {\r\n      z = -z;\r\n      sign = -sign;\r\n   }\r\n   if(z == 0)\r\n      return 0;\r\n\r\n   T guess = frexp(z, &i_exp);\r\n   int original_i_exp = i_exp; // save for later\r\n   guess = tools::evaluate_polynomial(P, guess);\r\n   int i_exp3 = i_exp / 3;\r\n\r\n   typedef typename largest_cbrt_int_type<T>::type shift_type;\r\n\r\n   if(abs(i_exp3) < std::numeric_limits<shift_type>::digits)\r\n   {\r\n      if(i_exp3 > 0)\r\n         guess *= shift_type(1u) << i_exp3;\r\n      else\r\n         guess /= shift_type(1u) << -i_exp3;\r\n   }\r\n   else\r\n   {\r\n      guess = ldexp(guess, i_exp3);\r\n   }\r\n   i_exp %= 3;\r\n   guess *= correction[i_exp + 2];\r\n   //\r\n   // Now inline Halley iteration.\r\n   // We do this here rather than calling tools::halley_iterate since we can\r\n   // simplify the expressions algebraically, and don't need most of the error\r\n   // checking of the boilerplate version as we know in advance that the function\r\n   // is well behaved...\r\n   //\r\n   typedef typename policies::precision<T, Policy>::type prec;\r\n   typedef typename mpl::divides<prec, mpl::int_<3> >::type prec3;\r\n   typedef typename mpl::plus<prec3, mpl::int_<3> >::type new_prec;\r\n   typedef typename policies::normalise<Policy, policies::digits2<new_prec::value> >::type new_policy;\r\n   //\r\n   // Epsilon calculation uses compile time arithmetic when it's available for type T,\r\n   // otherwise uses ldexp to calculate at runtime:\r\n   //\r\n   T eps = (new_prec::value > 3) ? policies::get_epsilon<T, new_policy>() : ldexp(T(1), -2 - tools::digits<T>() / 3);\r\n   T diff;\r\n\r\n   if(original_i_exp < std::numeric_limits<T>::max_exponent - 3)\r\n   {\r\n      //\r\n      // Safe from overflow, use the fast method:\r\n      //\r\n      do\r\n      {\r\n         T g3 = guess * guess * guess;\r\n         diff = (g3 + z + z) / (g3 + g3 + z);\r\n         guess *= diff;\r\n      }\r\n      while(fabs(1 - diff) > eps);\r\n   }\r\n   else\r\n   {\r\n      //\r\n      // Either we're ready to overflow, or we can't tell because numeric_limits isn't\r\n      // available for type T:\r\n      //\r\n      do\r\n      {\r\n         T g2 = guess * guess;\r\n         diff = (g2 - z / guess) / (2 * guess + z / g2);\r\n         guess -= diff;\r\n      }\r\n      while((guess * eps) < fabs(diff));\r\n   }\r\n\r\n   return sign * guess;\r\n}\r\n\r\n} // namespace detail\r\n\r\ntemplate <class T, class Policy>\r\ninline typename tools::promote_args<T>::type cbrt(T z, const Policy& pol)\r\n{\r\n   typedef typename tools::promote_args<T>::type result_type;\r\n   typedef typename policies::evaluation<result_type, Policy>::type value_type;\r\n   return static_cast<result_type>(detail::cbrt_imp(value_type(z), pol));\r\n}\r\n\r\ntemplate <class T>\r\ninline typename tools::promote_args<T>::type cbrt(T z)\r\n{\r\n   return cbrt(z, policies::policy<>());\r\n}\r\n\r\n} // namespace math\r\n} // namespace boost\r\n\r\n#endif // BOOST_MATH_SF_CBRT_HPP\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "4fe9bb1a077807d1f98032c6f100bc152e80efb1", "size": 5227, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Compiler/boost/boost/math/special_functions/cbrt.hpp", "max_stars_repo_name": "davidov541/MiniC", "max_stars_repo_head_hexsha": "d3b16a1568b97a4d801880b110a8be04fe848adb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-04-16T01:05:53.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-26T07:38:43.000Z", "max_issues_repo_path": "LibsExternes/Includes/boost/math/special_functions/cbrt.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/special_functions/cbrt.hpp", "max_forks_repo_name": "benkaraban/anima-games-engine", "max_forks_repo_head_hexsha": "8aa7a5368933f1b82c90f24814f1447119346c3b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.2011173184, "max_line_length": 134, "alphanum_fraction": 0.6215802564, "num_tokens": 1440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.48525736174643325}}
{"text": "#include \"shortest_path.h\"\n\n#include <iostream>\n#include <memory>\n#include <vector>\n#include <queue>\n#include <set>\n\n#include <Eigen/Dense>\n\n#include <geometry/patch.h>\n\nnamespace shortest_path {\n\tstd::map<Eigen::DenseIndex, std::shared_ptr<DjikstraVertexNode>> djikstras_algorithm(std::shared_ptr<Patch> patch, Eigen::DenseIndex source, std::set<Eigen::DenseIndex> exclude) {\n\t\tstd::priority_queue<std::shared_ptr<DjikstraVertexNode>, std::vector<std::shared_ptr<DjikstraVertexNode>>, DjikstraDist> q;\n\t\tstd::map<Eigen::DenseIndex, std::shared_ptr<DjikstraVertexNode>> nodes;\n\n\t\tconst Eigen::MatrixXd& V = patch->origin_mesh()->vertices();\n\n\t\tif (exclude.count(source) > 0) {\n\t\t\t// Why would you do that??\n\t\t\treturn nodes;\n\t\t}\n\n\t\tconst Eigen::SparseMatrix<int>& adj = patch->origin_mesh()->adjacency_matrix();\n\t\tauto source_node = std::make_shared<DjikstraVertexNode>(nullptr, 0.0, source);\n\n\t\tq.push(source_node);\n\t\tnodes.insert(std::pair<Eigen::DenseIndex, std::shared_ptr<DjikstraVertexNode>>(source, source_node));\n\n\t\twhile (!q.empty()) {\n\t\t\tstd::vector<std::shared_ptr<DjikstraVertexNode>> stored;\n\n\t\t\tauto u = q.top();\n\t\t\tq.pop();\n\n\t\t\twhile (!q.empty()) {\n\t\t\t\tstored.push_back(q.top());\n\t\t\t\tq.pop();\n\t\t\t}\n\n\t\t\tfor (Eigen::SparseMatrix<int>::InnerIterator it(adj, static_cast<int>(u->_vid)); it; ++it) {\n\t\t\t\tEigen::DenseIndex neighbor = it.row();   // neighbor vid\n\n\t\t\t\tif (patch->vids().count(neighbor) == 0) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tdouble dist = (V.row(neighbor).block<1, 3>(0, 0) - V.row(u->_vid).block<1, 3>(0, 0)).norm() + u->_dist;\n\t\t\t\tauto node = nodes.find(neighbor);\n\n\t\t\t\tif (node == nodes.cend()) {\n\t\t\t\t\tauto neighbor_node = std::make_shared<DjikstraVertexNode>(u, dist, neighbor);\n\n\t\t\t\t\tif (exclude.count(neighbor) <= 0) {\n\t\t\t\t\t\tq.push(neighbor_node);\n\t\t\t\t\t\tnodes.insert(std::pair<Eigen::DenseIndex, std::shared_ptr<DjikstraVertexNode>>(neighbor, neighbor_node));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tif (dist < node->second->_dist) {\n\t\t\t\t\t\tnode->second->_dist = dist;\n\t\t\t\t\t\tnode->second->_prev = u;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Changing values in a priority_queue invalidates the queue, so update it\n\t\t\tstd::priority_queue<std::shared_ptr<DjikstraVertexNode>, std::vector<std::shared_ptr<DjikstraVertexNode>>, DjikstraDist> new_q;\n\t\t\tfor (unsigned int i = 0; i < stored.size(); ++i) {\n\t\t\t\tq.push(stored[i]);\n\t\t\t}\n\t\t}\n\n\t\t// q is now empty, and nodes contains all _vid vertices and their shortest paths from source\n\t\treturn nodes;\n\t}\n\n\t// Nothing fancy, just a straight implementation of the most basic Floyd-Warshall algorithm for shortest path distance values\n\tEigen::MatrixXd floyd_warshall(const Eigen::SparseMatrix<double> edge_weights) {\n\t\tif (edge_weights.rows() != edge_weights.cols()) {\n\t\t\tthrow std::logic_error(\"Edge weights is not symmetric!\");\n\t\t}\n\n\t\tEigen::DenseIndex V = edge_weights.rows();\n\n\t\tEigen::MatrixXd dist = Eigen::MatrixXd::Constant(V, V, std::numeric_limits<double>::infinity());\n\n\t\tfor (Eigen::DenseIndex i = 0; i < V; ++i) {\n\t\t\tdist(i, i) = 0;\n\t\t}\n\n\t\tfor (int k = 0; k < edge_weights.outerSize(); ++k) {\n\t\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(edge_weights, k); it; ++it) {\n\t\t\t\tdist(it.row(), it.col()) = it.value();\n\t\t\t}\n\t\t}\n\n\t\tfor (Eigen::DenseIndex k = 0; k < V; ++k) {\n\t\t\tfor (Eigen::DenseIndex i = 0; i < V; ++i) {\n\t\t\t\tfor (Eigen::DenseIndex j = 0; j < V; ++j) {\n\t\t\t\t\tif (dist(i, j) > dist(i, k) + dist(k, j)) {\n\t\t\t\t\t\tdist(i, j) = dist(i, k) + dist(k, j);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn dist;\n\t}\n\n\tstruct EdgeComparator {\n\t\tbool operator()(const std::pair<Eigen::DenseIndex, Eigen::DenseIndex>& a, const std::pair<Eigen::DenseIndex, Eigen::DenseIndex>& b) const {\n\t\t\t// order of the face identifiers of the edge doesn't matter, only that the combination is the same\n\t\t\tbool res = (a.first == b.first && a.second == b.second) || (a.first == b.second && a.second == b.first);\n\n\t\t\tif (res) {\n\t\t\t\t// They're equal\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\t// Otherwise, order by vid (arbitrary)\n\t\t\tif (a.first == b.first) {\n\t\t\t\treturn a.second < b.second;\n\t\t\t} \n\n\t\t\treturn a.first < b.first;\n\t\t}\n\t};\n\n\t// This will assert if the two faces are not neighbors\n\tEigen::VectorXd shared_edge_midpoint(Eigen::DenseIndex fid1, Eigen::DenseIndex fid2, std::shared_ptr<Mesh> mesh) {\n\t\tconst Eigen::MatrixXd& V = mesh->vertices();\n\t\tconst Eigen::MatrixXi& F = mesh->faces();\n\n\t\tstd::vector<Eigen::DenseIndex> endpoints;\n\t\tfor (Eigen::DenseIndex j = 0; j < F.cols(); ++j) {\n\t\t\tEigen::DenseIndex adj_vid = F(fid2, j);\n\n\t\t\tif ((F.row(fid1).array() == adj_vid).any()) {\n\t\t\t\tendpoints.push_back(adj_vid);\n\t\t\t}\n\t\t}\n\n\t\tassert(endpoints.size() == 2);\n\n\t\tEigen::VectorXd midpoint = (V.row(endpoints[0]) + V.row(endpoints[1])).transpose() / 2.0;\n\n\t\treturn midpoint;\n\t}\n\n\tstd::vector<Eigen::DenseIndex> face_to_face(Eigen::DenseIndex source, Eigen::DenseIndex sink, std::shared_ptr<Mesh> mesh) {\n\t\tstd::vector<Eigen::DenseIndex> path;\n\n\t\tif (mesh == nullptr) {\n\t\t\treturn path;\n\t\t}\n\n\t\tstd::priority_queue<std::shared_ptr<DjikstraFaceNode>, std::vector<std::shared_ptr<DjikstraFaceNode>>, DjikstraDist> q;\n\t\tstd::map<std::pair<Eigen::DenseIndex, Eigen::DenseIndex>, std::shared_ptr<DjikstraFaceNode>, EdgeComparator> nodes;\n\n\t\tconst Eigen::MatrixXd& V = mesh->vertices();\n\t\tconst Eigen::MatrixXi& F = mesh->faces();\n\t\tconst Eigen::MatrixXi& tri_adj = mesh->tri_adjacency_matrix();\n\n\t\t{ // Bootstrap source (the source is actually made up of a number of sources equal to the number of edges of the source face\n\t\t\tfor (Eigen::DenseIndex i = 0; i < tri_adj.cols(); ++i) {\n\t\t\t\tEigen::DenseIndex adj_fid = tri_adj(source, i);\n\n\t\t\t\tif (adj_fid < 0 || adj_fid >= F.rows()) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tEigen::VectorXd midpoint = shared_edge_midpoint(source, adj_fid, mesh);\n\n\t\t\t\t// Note: order here is *important* -- (from_fid, to_fid)\n\t\t\t\tauto edge = std::make_pair(source, adj_fid);\n\t\t\t\t\n\t\t\t\tauto source_node = std::make_shared<DjikstraFaceNode>(nullptr, 0.0, edge, midpoint);\n\n\t\t\t\tq.push(source_node);\n\t\t\t\t\n\t\t\t\tnodes.insert(std::make_pair(edge, source_node));\n\t\t\t\tnodes.insert(std::make_pair(std::make_pair(adj_fid, source), source_node));\n\n\t\t\t\tauto check = nodes.find(edge);\n\n\t\t\t\tif (check == nodes.end()) {\n\t\t\t\t\tthrow std::logic_error(\"This is dead wrong!\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Search\n\t\tstd::shared_ptr<DjikstraFaceNode> sink_node = nullptr;\n\n\t\twhile (!q.empty()) {\n\t\t\tstd::vector<std::shared_ptr<DjikstraFaceNode>> stored;\n\n\t\t\tauto u = q.top();\n\t\t\tq.pop();\n\n\t\t\twhile (!q.empty()) {\n\t\t\t\tstored.push_back(q.top());\n\t\t\t\tq.pop();\n\t\t\t}\n\n\t\t\tEigen::DenseIndex cur_face = u->_edge.second;\n\t\t\tEigen::DenseIndex prev_face = u->_edge.first;\n\n\t\t\tif (cur_face == sink) {\n\t\t\t\tsink_node = u;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tfor (Eigen::DenseIndex i = 0; i < tri_adj.cols(); ++i) {\n\t\t\t\tEigen::DenseIndex neighbor = tri_adj(cur_face, i);   // neighbor fid\n\n\t\t\t\tif (neighbor == prev_face || neighbor < 0 || neighbor >= F.rows()) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tEigen::VectorXd midpoint = shared_edge_midpoint(cur_face, neighbor, mesh);\n\n\t\t\t\tauto neighbor_edge = std::make_pair(cur_face, neighbor);\n\n\t\t\t\tdouble dist = u->_dist + (u->_midpoint - midpoint).norm();\n\n\t\t\t\tauto node = nodes.find(neighbor_edge);\n\n\t\t\t\tif (node == nodes.cend()) {\n\t\t\t\t\tauto neighbor_node = std::make_shared<DjikstraFaceNode>(u, dist, neighbor_edge, midpoint);\n\t\n\t\t\t\t\tq.push(neighbor_node);\n\n\t\t\t\t\tnodes.insert(std::make_pair(neighbor_edge, neighbor_node));\n\t\t\t\t} else {\n\t\t\t\t\tif (dist < node->second->_dist) {\n\t\t\t\t\t\tnode->second->_dist = dist;\n\n\t\t\t\t\t\tif (node->second->_prev == nullptr || node->second->_dist <= 0.0) {\n\t\t\t\t\t\t\tthrow std::logic_error(\"How are we replacing the prev of a root note??\");\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tnode->second->_prev = u;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Changing values in a priority_queue invalidates the queue, so update it\n\t\t\t//std::priority_queue<std::shared_ptr<DjikstraFaceNode>, std::vector<std::shared_ptr<DjikstraFaceNode>>, DjikstraDist> new_q;\n\t\t\tfor (unsigned int i = 0; i < stored.size(); ++i) {\n\t\t\t\tq.push(stored[i]);\n\t\t\t}\n\t\t}\n\n\t\t// Populate shortest path from source to sink\n\t\tif (sink_node == nullptr) {\n\t\t\treturn path;\n\t\t}\n\n\t\twhile (true) {\n\t\t\tpath.push_back(sink_node->_edge.second);\n\n\t\t\tif (sink_node->_prev == nullptr) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tsink_node = sink_node->_prev;\n\t\t}\n\n\t\tassert(sink_node->_edge.first == source);\n\n\t\tpath.push_back(source);\n\n\t\tstd::reverse(path.begin(), path.end());\n\n\t\treturn path;\n\t}\n}", "meta": {"hexsha": "47da12cd73417471f122ba06d6569ff85bfe7419", "size": 8293, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/algorithms/shortest_path.cpp", "max_stars_repo_name": "josefgraus/self_similiarity", "max_stars_repo_head_hexsha": "c032daa3009f60fdc8a52c437a07c6e3ba2efe4b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-25T09:35:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-25T09:35:14.000Z", "max_issues_repo_path": "src/algorithms/shortest_path.cpp", "max_issues_repo_name": "josefgraus/self_similiarity", "max_issues_repo_head_hexsha": "c032daa3009f60fdc8a52c437a07c6e3ba2efe4b", "max_issues_repo_licenses": ["MIT"], "max_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/shortest_path.cpp", "max_forks_repo_name": "josefgraus/self_similiarity", "max_forks_repo_head_hexsha": "c032daa3009f60fdc8a52c437a07c6e3ba2efe4b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-09-22T13:02:45.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-08T00:21:36.000Z", "avg_line_length": 29.6178571429, "max_line_length": 180, "alphanum_fraction": 0.6465693959, "num_tokens": 2431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.6477982043529716, "lm_q1q2_score": 0.48525735155949223}}
{"text": "#ifndef TRAJCOMP_SYMMAT_INC\n#define TRAJCOMP_SYMMAT_INC\n\n\n#include<vector>\n/*a nice trick to make rvalues to lvalues*/\n\ntemplate <typename T>\nT& as_lvalue(T&& x)\n{\n    return x;\n}\n\n/*Symmetric Square Matrix storing only Upper Triangular, diagonal is fixed zero\n * \n * Especially useful for distance matrices. * \n * */\n\ntemplate<class tvalue> \nclass UTSquareMatrix\n{\n\tpublic:\n\tsize_t _size;\n\tstd::vector<tvalue> data;\n\t\n\tsize_t size(void)\n\t{\n\t\t\n\t\treturn _size;\n\t}\n\t\n\tvoid resize(size_t m)\n\t{\n\t\t_size = m;\n\t\tsize_t size = m*(m-1)/2;\n\t\tdata.resize(size);\n\t}\n\n\tstruct tsymmetricgetter{\n\t\ttvalue temp; // for making a zero reference-accessible\n\t\tstd::vector<tvalue> &base;\n\t\tsize_t i;\n\t\ttsymmetricgetter (std::vector<tvalue> &_base, size_t _i): base(_base),i(_i)\n\t\t{};\n\t\ttvalue &operator[] (size_t j)\n\t\t{\n\t\t\tif (i==j)\n\t\t\t{\n\t\t\t\ttemp =0;\n\t\t\t   return  temp;\n\t\t    }\n\t\t    if (i < j )\n\t\t      swap(i,j);\n\t\t    \t\t    \n\t\t\treturn as_lvalue (base[((i*(i-1))/2) + (j)]);\n\t\t}\n\t};\n\n\ttsymmetricgetter operator[](size_t i)\n\t{\n\t\treturn tsymmetricgetter(data, i);\n\t}\n\t\n\ttemplate<class Archive>\n    void serialize(Archive & ar, const unsigned int version)\n    {\n\t\tar & _size;\n\t\tar & data;\n    }\n\t\n\t\n};\n\n\n/* Test Main <=> Documentation ;-)\n * \n * // #include<iostream>\n#include <fstream>\n//include headers that implement a archive in simple text format\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/archive/text_iarchive.hpp>\n#include <boost/serialization/vector.hpp>\nusing namespace std;\nint main(void)\n{\n\tUTSquareMatrix<int> m;\n\tconst int s = 6;\n\tm.resize(s);\n\t// Fill in matrix\n\t\n\tfor (size_t i=0; i < s; i++)\n\t{\n\t\tfor (size_t j=0; j < s; j++)\n\t\t{\n\t\t\tm[i][j] = i+j;\n\t\t\t\n    \t}\n\t}\n\t// Dump before save\n\tfor (size_t i=0; i < s; i++)\n\t{\n\t\tfor (size_t j=0; j < s; j++)\n\t\t{\n\t\t\tcout << m[i][j]<< \"\\t\";\n\t\t}\n\t\tcout << endl;\n\t}\n\t// Serialize\n\t std::ofstream ofs(\"serial.dat\");\n\n    // save data to archive\n    {\n        boost::archive::text_oarchive oa(ofs);\n        // write class instance to archive\n        oa << m;\n    \t// archive and stream closed when destructors are called\n    }\n\tfor (size_t i=0; i < s; i++)\n\t{\n\t\tfor (size_t j=0; j < s; j++)\n\t\t{\n\t\t\tm[i][j] = 4;\n\t\t\t\n    \t}\n\t}\n\nfor (size_t i=0; i < s; i++)\n\t{\n\t\tfor (size_t j=0; j < s; j++)\n\t\t{\n\t\t\tcout << m[i][j]<< \"\\t\";\n\t\t}\n\t\tcout << endl;\n\t}\n\t\n\n    UTSquareMatrix<int> n;\n    \n    {\n        // create and open an archive for input\n        std::ifstream ifs(\"serial.dat\");\n        boost::archive::text_iarchive ia(ifs);\n        // read class state from archive\n        ia >> n;\n        // archive and stream closed when destructors are called\n    }\n    cout << \"--\" << endl;\n\tfor (size_t i=0; i < s; i++)\n\t{\n\t\tfor (size_t j=0; j < s; j++)\n\t\t{\n\t\t\tcout << n[i][j]<< \"\\t\";\n\t\t}\n\t\tcout << endl;\n\t}\n\t\n\n\n\n\t\n}\n\n*/ \n#endif\n", "meta": {"hexsha": "d4a4d820fa8b432ca3602994fe0ed4ffdf241ee8", "size": 2760, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/trajcomp/trajcomp_symmat.hpp", "max_stars_repo_name": "mlaass/persistence-open", "max_stars_repo_head_hexsha": "4a5528141ab8269cf7f5baa0862af02a40835167", "max_stars_repo_licenses": ["MIT"], "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/trajcomp/trajcomp_symmat.hpp", "max_issues_repo_name": "mlaass/persistence-open", "max_issues_repo_head_hexsha": "4a5528141ab8269cf7f5baa0862af02a40835167", "max_issues_repo_licenses": ["MIT"], "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/trajcomp/trajcomp_symmat.hpp", "max_forks_repo_name": "mlaass/persistence-open", "max_forks_repo_head_hexsha": "4a5528141ab8269cf7f5baa0862af02a40835167", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.7272727273, "max_line_length": 79, "alphanum_fraction": 0.5710144928, "num_tokens": 868, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723317123102956, "lm_q2_score": 0.721743200312399, "lm_q1q2_score": 0.48525084171434796}}
{"text": "// Copyright Abel Sinkovics (abel@sinkovics.hu) 2013.\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 <mpllibs/metamonad/apply.hpp>\n#include <mpllibs/metamonad/tmp_value.hpp>\n#include <mpllibs/metamonad/returns.hpp>\n\n#include <boost/test/unit_test.hpp>\n\n#include <boost/mpl/plus.hpp>\n#include <boost/mpl/equal_to.hpp>\n\n#include \"common.hpp\"\n\nusing mpllibs::metamonad::tmp_value;\n\nusing boost::mpl::plus;\n\nnamespace\n{\n  struct add : tmp_value<add>\n  {\n    template <class A, class B>\n    struct apply : plus<A, B> {};\n  };\n\n  struct id : tmp_value<id>\n  {\n    template <class A>\n    struct apply : A {};\n  };\n}\n\nBOOST_AUTO_TEST_CASE(test_apply)\n{\n  using mpllibs::metamonad::apply;\n  using mpllibs::metamonad::returns;\n\n  using boost::mpl::equal_to;\n\n  BOOST_MPL_ASSERT((equal_to<int13, apply<add, int11, int2> >));\n\n  BOOST_MPL_ASSERT((\n    equal_to<int13, apply<returns<add>, returns<int11>, returns<int2> > >\n  ));\n}\n\n\n", "meta": {"hexsha": "f287e5bbf4acb5185cd2c73f69da103ff1fb4a91", "size": 1051, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/metamonad/test/apply.cpp", "max_stars_repo_name": "sabel83/mpllibs", "max_stars_repo_head_hexsha": "8e245aedcf658fe77bb29537aeba1d4e1a619a19", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 70.0, "max_stars_repo_stars_event_min_datetime": "2015-01-15T09:05:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-08T15:49:31.000Z", "max_issues_repo_path": "libs/metamonad/test/apply.cpp", "max_issues_repo_name": "sabel83/mpllibs", "max_issues_repo_head_hexsha": "8e245aedcf658fe77bb29537aeba1d4e1a619a19", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-06-18T19:25:34.000Z", "max_issues_repo_issues_event_max_datetime": "2016-05-13T19:49:51.000Z", "max_forks_repo_path": "libs/metamonad/test/apply.cpp", "max_forks_repo_name": "sabel83/mpllibs", "max_forks_repo_head_hexsha": "8e245aedcf658fe77bb29537aeba1d4e1a619a19", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2015-07-10T08:18:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-01T07:17:57.000Z", "avg_line_length": 20.6078431373, "max_line_length": 73, "alphanum_fraction": 0.6917221694, "num_tokens": 299, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.4852508315225615}}
{"text": "//=======================================================================\r\n// Copyright 1997, 1998, 1999, 2000 University of Notre Dame.\r\n// Authors: Andrew Lumsdaine, Lie-Quan Lee, Jeremy G. Siek\r\n//\r\n// Distributed under the Boost Software License, Version 1.0. (See\r\n// accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n//=======================================================================\r\n\r\n// Revision History:\r\n//   17 March 2006: Fixed a bug: when updating the degree a vertex \r\n//                  could be moved to a wrong bucket. (Roman Dementiev) \r\n//\r\n\r\n\r\n\r\n#ifndef BOOST_SMALLEST_LAST_VERTEX_ORDERING_HPP\r\n#define BOOST_SMALLEST_LAST_VERTEX_ORDERING_HPP\r\n/*\r\n   The smallest-last ordering is defined for the loopless graph G with\r\n   vertices a(j), j = 1,2,...,n where a(j) is the j-th column of A and\r\n   with edge (a(i),a(j)) if and only if columns i and j have a\r\n   non-zero in the same row position.  The smallest-last ordering is\r\n   determined recursively by letting list(k), k = n,...,1 be a column\r\n   with least degree in the subgraph spanned by the un-ordered\r\n   columns.\r\n */\r\n#include <vector>\r\n#include <algorithm>\r\n#include <boost/config.hpp>\r\n#include <boost/graph/graph_traits.hpp>\r\n#include <boost/graph/properties.hpp>\r\n#include <boost/pending/bucket_sorter.hpp>\r\n\r\nnamespace boost {\r\n\r\n  template <class VertexListGraph, class Order, class Degree, class Marker>\r\n  void \r\n  smallest_last_vertex_ordering(const VertexListGraph& G, Order order, \r\n                                Degree degree, Marker marker) {\r\n    typedef typename boost::graph_traits<VertexListGraph> GraphTraits;\r\n    typedef typename GraphTraits::vertex_descriptor Vertex;\r\n    //typedef typename GraphTraits::size_type size_type;\r\n    typedef std::size_t size_type;\r\n    \r\n    const size_type num = num_vertices(G);\r\n    \r\n    typedef typename boost::property_map<VertexListGraph, vertex_index_t>::type ID;\r\n    typedef bucket_sorter<size_type, Vertex, Degree, ID> BucketSorter;\r\n    \r\n    BucketSorter degree_bucket_sorter(num, num, degree,  \r\n                                      get(vertex_index,G));\r\n\r\n    smallest_last_vertex_ordering(G, order, degree, marker, degree_bucket_sorter);\r\n  }\r\n\r\n  template <class VertexListGraph, class Order, class Degree, \r\n            class Marker, class BucketSorter>\r\n  void \r\n  smallest_last_vertex_ordering(const VertexListGraph& G, Order order, \r\n                                Degree degree, Marker marker,\r\n                                BucketSorter& degree_buckets) {\r\n    typedef typename boost::graph_traits<VertexListGraph> GraphTraits;\r\n    typedef typename GraphTraits::vertex_descriptor Vertex;\r\n    //typedef typename GraphTraits::size_type size_type;\r\n    typedef std::size_t size_type;\r\n\r\n    const size_type num = num_vertices(G);\r\n    \r\n    typename GraphTraits::vertex_iterator v, vend;\r\n    for (boost::tie(v, vend) = vertices(G); v != vend; ++v) {\r\n      put(marker, *v, num);\r\n      put(degree, *v, out_degree(*v, G));\r\n      degree_buckets.push(*v);\r\n    }\r\n \r\n    size_type minimum_degree = 0;\r\n    size_type current_order = num - 1;\r\n    \r\n    while ( 1 ) {\r\n      typedef typename BucketSorter::stack MDStack;\r\n      MDStack minimum_degree_stack = degree_buckets[minimum_degree];\r\n      while (minimum_degree_stack.empty())\r\n        minimum_degree_stack = degree_buckets[++minimum_degree];\r\n      \r\n      Vertex node = minimum_degree_stack.top();\r\n      put(order, current_order, node);\r\n      \r\n      if ( current_order == 0 ) //find all vertices\r\n        break;\r\n      \r\n      minimum_degree_stack.pop();\r\n      put(marker, node, 0); //node has been ordered.\r\n      \r\n      typename GraphTraits::adjacency_iterator v, vend;\r\n      for (boost::tie(v,vend) = adjacent_vertices(node, G); v != vend; ++v)\r\n        \r\n        if ( get(marker,*v) > current_order ) { //*v is unordered vertex\r\n          put(marker, *v, current_order);  //mark the columns adjacent to node\r\n\r\n          //delete *v from the bucket sorter         \r\n          degree_buckets.remove(*v);\r\n \r\n          //It is possible minimum degree goes down\r\n          //Here we keep tracking it.\r\n          put(degree, *v, get(degree, *v) - 1); \r\n          BOOST_USING_STD_MIN();\r\n          minimum_degree = min BOOST_PREVENT_MACRO_SUBSTITUTION(minimum_degree, get(degree, *v)); \r\n          \r\n          //reinsert *v in the bucket sorter with the new degree\r\n          degree_buckets.push(*v);\r\n        }\r\n\r\n      current_order--;\r\n    }\r\n    \r\n    //at this point, order[i] = v_i;\r\n  }\r\n  \r\n  template <class VertexListGraph, class Order>\r\n  void \r\n  smallest_last_vertex_ordering(const VertexListGraph& G, Order order) {\r\n    typedef typename graph_traits<VertexListGraph>::vertex_descriptor vertex_descriptor;\r\n    typedef typename graph_traits<VertexListGraph>::degree_size_type degree_size_type;\r\n    smallest_last_vertex_ordering(G, order,\r\n                                  make_shared_array_property_map(num_vertices(G), degree_size_type(0), get(vertex_index, G)),\r\n                                  make_shared_array_property_map(num_vertices(G), (std::size_t)(0), get(vertex_index, G)));\r\n  }\r\n\r\n  template <class VertexListGraph>\r\n  std::vector<typename graph_traits<VertexListGraph>::vertex_descriptor>\r\n  smallest_last_vertex_ordering(const VertexListGraph& G) {\r\n    std::vector<typename graph_traits<VertexListGraph>::vertex_descriptor> o(num_vertices(G));\r\n    smallest_last_vertex_ordering(G, make_iterator_property_map(o.begin(), typed_identity_property_map<std::size_t>()));\r\n    return o;\r\n  }\r\n}\r\n\r\n#endif\r\n\r\n", "meta": {"hexsha": "bad0da7687c7e2b7b89cbfdaaaa4c136b3e0315a", "size": 5608, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ios/Pods/boost-for-react-native/boost/graph/smallest_last_ordering.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/smallest_last_ordering.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/smallest_last_ordering.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.7730496454, "max_line_length": 126, "alphanum_fraction": 0.6414051355, "num_tokens": 1233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217431943271999, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.48525082821309196}}
{"text": "/* A simple program that demonstrates a simple homomorphic program on 4 input values.\n * */\n\n#include <iostream>\n#include <NTL/ZZ.h>\n#include <NTL/BasicThreadPool.h>\n#include \"FHE.h\"\n#include \"timing.h\"\n#include \"EncryptedArray.h\"\n#include <NTL/lzz_pXFactoring.h>\n\n#include <cassert>\n#include <cstdio>\n\nnamespace std {} using namespace std;\n\nint main(int argc, char *argv[])\n{\n  ArgMapping amap;\n\n  // Technical parameter. Use if you want to explicitly\n  // set generator elements for the plaintext arrays.\n  // These are generators in the group theoretic sense of\n  // generating a particular group.\n  Vec<long> generators;\n  amap.arg(\"generators\", generators, \"use specified vector of generators\", NULL);\n  amap.note(\"e.g., generators='[562 1871 751]'\");\n\n  // Technical parameter. The order of each generator\n  // specified in orders. Recall the order e of a group\n  // element g is the number e such g**e == 1\n  Vec<long> orders;\n  amap.arg(\"orders\", orders, \"use specified vector of orders\", NULL);\n  amap.note(\"e.g., orders='[4 2 -4]', negative means 'bad'\");\n\n  // Random seed used in scheme.\n  long seed=0;\n  amap.arg(\"seed\", seed, \"PRG seed\");\n\n  // The number of rounds of encrypted computation. If\n  // num_rounds > 1, then we need to \"bootstrap\" between\n  // rounds which adds a heavy computational overhead.\n  long num_rounds = 1;\n  amap.arg(\"num_rounds\", num_rounds, \"number of rounds\");\n\n  // If plaintext_base_prime=2, then plaintext entries are\n  // bits.\n  long plaintext_base_prime = 2;\n  amap.arg(\"plaintext_base_prime\", plaintext_base_prime,\n      \"plaintext base prime\");\n\n  // Technical parameter. In case finite_field_degree=1,\n  // then plaintext entries are just bits.\n  long finite_field_degree=1;\n  amap.arg(\"finite_field_degree\", finite_field_degree,\n      \"finite_field_degree\");\n\n  long d=1;\n  amap.arg(\"d\", d, \"degree of the field extension\");\n\n  // Key-switching is an operation which swaps out the key\n  // under which a particular ciphertext is encoded.\n  // Key-switching is used in a variety of places in\n  // homomorphic encryption, notably during\n  // \"relinearization\" which happens after homomorphic\n  // multiplication of ciphertexts. The key-switching\n  // matrix is a 2xn matrix, where n is some number <\n  // num_levels (see description of num_levels below).\n  long num_key_columns = 2;\n  amap.arg(\"num_key_columns\", num_key_columns, \"number of columns in the key-switching matrices\");\n\n  // The number of \"bits\" of security the scheme provides\n  // (see https://en.wikipedia.org/wiki/Security_level).\n  // Basic idea is that for a security level of 80, the\n  // attacker needs to perform ~2^80 operations to break\n  // the scheme.\n  long security_parameter=80;\n  amap.arg(\"security_parameter\", security_parameter,\n      \"security parameter\");\n\n  // The number of levels in the modulus chain. See\n  // detailed comment below.\n  long num_levels = 0;\n  amap.arg(\"num_levels\", num_levels, \"# of levels in the modulus chain\",  \"heuristic\");\n\n  long num_slots=0;\n  amap.arg(\"num_slots\", num_slots, \"minimum number of slots\");\n\n  // See comment about cyclotomic polynomials below. If\n  // chosen_cyclotomic_degree is set, this value is passed\n  // to helper findM that checks if it is secure.\n  long chosen_cyclotomic_degree=0;\n  amap.arg(\"cyclotomic_degree\", chosen_cyclotomic_degree, \"use specified value for cyclotomic polynomial.\", NULL);\n\n  amap.parse(argc, argv);\n\n  SetSeed(ZZ(seed));\n\n  // num_levels is the number of \"levels\" to the FHE\n  // scheme. The number of levels governs how many compute\n  // operations can be performed on encrypted data before\n  // the encryption needs to be refreshed (this refreshing\n  // process is called \"bootstrapping\").  See comment\n  // below about the modulus chain. \n  if (num_levels==0) { \n    // determine num_levels based on num_rounds,r\n    num_levels = 3*num_rounds+3;\n    if (plaintext_base_prime>2 || finite_field_degree>1) { // add some more primes for each round\n      long addPerRound = 2*ceil(log((double)plaintext_base_prime)*finite_field_degree*3)/(log(2.0)*FHE_p2Size) +1;\n      num_levels += num_rounds * addPerRound;\n    }\n  }\n\n  // Hamming weight of secret key\n  long sec_key_weight = 64; \n\n  // The FHE scheme uses a technical parameter called a\n  // cyclotomic polynomial.  These polynomials are indexed\n  // by whole numbers m. The helper findM helps select a\n  // value of m that meets our security requirements.\n  long cyclotomic_degree = FindM(security_parameter,\n      num_levels, num_key_columns, plaintext_base_prime,\n      d, num_slots, chosen_cyclotomic_degree, false);\n\n  // Converting generators and orders into vector<long> types.\n  vector<long> generators1, orders1;\n  convert(generators1, generators);\n  convert(orders1, orders);\n\n  // FHEcontext is a convenient book-keeping class that\n  // stores a variety of parameters tied to the fully\n  // homomorphic encryption scheme.\n  FHEcontext context(cyclotomic_degree,\n      plaintext_base_prime, finite_field_degree,\n      generators1, orders1);\n  // FHE schemes use a sequence of parameters called the\n  // modulus chain. These \"moduli\" are ordered in size,\n  // q_0 < q_1 < --- < q_L. At the start of encryption,\n  // the largest modulus q_L is used. For technical\n  // reasons, as encryption proceeds, have to swap down to\n  // smaller and smaller moduli. When q_0 is reached, the\n  // FHE scheme can no longer compute on the encrypted\n  // data. At this point, a \"bootstrapping\" step is needed\n  // (not used in this file) to refresh.\n  buildModChain(context, num_levels, num_key_columns);\n\n  // irred_poly is a technical parameter used to define\n  // the plaintexts. Formally, an irreducible polynomial.\n  ZZX irred_poly;\n  irred_poly = makeIrredPoly(plaintext_base_prime, d); \n\n  // Print some information about the security level of\n  // the current scheme.\n  std::cout << \"security=\" << context.securityLevel()<<endl;\n\n  // Stores the secret key. Almost like the FHEPubKey\n  // object, \n  FHESecKey secretKey(context);\n\n  // The public key contains the encryption of the\n  // constant 0 (that is, Enc(0)) along with key-switching\n  // matrices and some bookkeeping information.\n  const FHEPubKey& publicKey = secretKey;\n  // A secret key with specified Hamming weight. The\n  // hamming weight is the number of nonzero entries in\n  // the secret key.\n  secretKey.GenSecKey(sec_key_weight); \n  // compute key-switching matrices that we need\n  addSome1DMatrices(secretKey); \n\n  // A convenience class that allows for operations on an array of plaintexts.\n  // The size of this array is set automatically by the choice of parameters\n  // listed above.\n  EncryptedArray ea(context, irred_poly);\n  long nslots = ea.size();\n  std::cout << \"nslot = \" << nslots << endl;\n\n  // A PlaintextArray must be paired with an EncryptedArray.\n  NewPlaintextArray p0(ea);\n  NewPlaintextArray p1(ea);\n  NewPlaintextArray p2(ea);\n  NewPlaintextArray p3(ea);\n\n  // Populate our plaintext arrays with random values.\n  random(ea, p0);\n  random(ea, p1);\n  random(ea, p2);\n  random(ea, p3);\n\n  // Construct our ciphertext objects\n  Ctxt c0(publicKey), c1(publicKey), c2(publicKey), c3(publicKey);\n\n  // Encrypt our plaintexts into the ciphertext\n  ea.encrypt(c0, publicKey, p0);\n  ea.encrypt(c1, publicKey, p1);\n  ea.encrypt(c2, publicKey, p2);\n  ea.encrypt(c3, publicKey, p3);\n\n\n  // random number in [-nslots/2..nslots/2]\n  long shamt = RandomBnd(2*(nslots/2) + 1) - (nslots/2);\n  // random number in [-(nslots-1)..nslots-1]\n  long rotamt = RandomBnd(2*nslots - 1) - (nslots - 1);\n\n  // two random constants\n  NewPlaintextArray const1(ea);\n  NewPlaintextArray const2(ea);\n  random(ea, const1);\n  random(ea, const2);\n\n  ZZX const1_poly, const2_poly;\n  ea.encode(const1_poly, const1);\n  ea.encode(const2_poly, const2);\n\n  // Perform computation upon encrypted ciphertexts\n  c1.multiplyBy(c0);\n  c0.addConstant(const1_poly);\n  c2.multByConstant(const2_poly);\n  Ctxt tmp(c1);\n  ea.shift(tmp, shamt);\n  c2 += tmp;\n  ea.rotate(c2, rotamt);\n  c1.negate();\n  c3.multiplyBy(c2);\n  c0 -= c3;\n\n  // Perform computations upon plaintext data. Will check\n  // that decryption of the encrypted data equals the\n  // output of the plaintext computation.\n  mul(ea, p1, p0);     // c1.multiplyBy(c0)\n  add(ea, p0, const1); // c0 += random constant\n  mul(ea, p2, const2); // c2 *= random constant\n  NewPlaintextArray tmp_p(p1); // tmp = c1\n  shift(ea, tmp_p, shamt); // ea.shift(tmp, random amount in [-nSlots/2,nSlots/2])\n  add(ea, p2, tmp_p);  // c2 += tmp\n  rotate(ea, p2, rotamt); // ea.rotate(c2, random amount in [1-nSlots, nSlots-1])\n  ::negate(ea, p1); // c1.negate()\n  mul(ea, p3, p2); // c3.multiplyBy(c2) \n  sub(ea, p0, p3); // c0 -= c3\n\n  c0.cleanUp();\n  c1.cleanUp();\n  c2.cleanUp();\n  c3.cleanUp();\n\n  // Create new plaintexts we use to store decryption of\n  // homomorphic outputs.\n  NewPlaintextArray pp0(ea);\n  NewPlaintextArray pp1(ea);\n  NewPlaintextArray pp2(ea);\n  NewPlaintextArray pp3(ea);\n   \n  // Decrypt the ciphertexts\n  ea.decrypt(c0, secretKey, pp0);\n  ea.decrypt(c1, secretKey, pp1);\n  ea.decrypt(c2, secretKey, pp2);\n  ea.decrypt(c3, secretKey, pp3);\n   \n  // Check that the decrypted ciphertexts have the right\n  // values.\n  if (equals(ea, pp0, p0) && equals(ea, pp1, p1)\n      && equals(ea, pp2, p2) && equals(ea, pp3, p3))\n       std::cout << \"Homomorphic Computation performed correctly.\\n\";\n  else std::cout << \"ERROR\\n\";\n\n}\n", "meta": {"hexsha": "13cbde20393c5a3a572d3f308967e64bf735f445", "size": 9392, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/PrintEncrypted.cpp", "max_stars_repo_name": "computablelabs/HElib", "max_stars_repo_head_hexsha": "4a21dd6ce42a4335564792de55e17d60361fc2bb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-05-22T00:27:17.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-22T21:22:58.000Z", "max_issues_repo_path": "src/PrintEncrypted.cpp", "max_issues_repo_name": "computablelabs/HElib", "max_issues_repo_head_hexsha": "4a21dd6ce42a4335564792de55e17d60361fc2bb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2018-05-17T21:41:34.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-18T21:37:26.000Z", "max_forks_repo_path": "src/PrintEncrypted.cpp", "max_forks_repo_name": "computablelabs/HElib", "max_forks_repo_head_hexsha": "4a21dd6ce42a4335564792de55e17d60361fc2bb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-06-03T15:41:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-03T15:41:14.000Z", "avg_line_length": 35.1760299625, "max_line_length": 114, "alphanum_fraction": 0.7056005111, "num_tokens": 2628, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738010682209, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.48506222647977865}}
{"text": "// SPDX-License-Identifier: MIT\n// Copyright (c) 2019-2021 Thomas Vanderbruggen <th.vanderbruggen@gmail.com>\n\n#ifndef SCICPP_LINALG_SOLVE\n#define SCICPP_LINALG_SOLVE\n\n#include \"scicpp/linalg/utils.hpp\"\n\n#include <Eigen/Dense>\n#include <type_traits>\n\nnamespace scicpp::linalg {\n\ntemplate <class EigenMatrix, class StdContainer>\nauto lstsq(const EigenMatrix &A, const StdContainer &b) {\n    static_assert(std::is_same_v<typename EigenMatrix::value_type,\n                                 typename StdContainer::value_type>);\n\n    return to_std_container(\n        A.fullPivHouseholderQr().solve(to_eigen_matrix(b)).eval());\n}\n\n} // namespace scicpp::linalg\n\n#endif // SCICPP_LINALG_SOLVE\n", "meta": {"hexsha": "7007d7fac64b46943fd9458751c69cc892af43d5", "size": 684, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "scicpp/linalg/solve.hpp", "max_stars_repo_name": "tvanderbruggen/SciCpp", "max_stars_repo_head_hexsha": "09408506c8d0b49ca5dadb8cd1f3cb4db41c8c46", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-08-02T09:03:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T11:58:05.000Z", "max_issues_repo_path": "scicpp/linalg/solve.hpp", "max_issues_repo_name": "tvanderbruggen/SciCpp", "max_issues_repo_head_hexsha": "09408506c8d0b49ca5dadb8cd1f3cb4db41c8c46", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scicpp/linalg/solve.hpp", "max_forks_repo_name": "tvanderbruggen/SciCpp", "max_forks_repo_head_hexsha": "09408506c8d0b49ca5dadb8cd1f3cb4db41c8c46", "max_forks_repo_licenses": ["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.3076923077, "max_line_length": 76, "alphanum_fraction": 0.7295321637, "num_tokens": 179, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.48506222363446305}}
{"text": "// Copyright (c) 2022 CNES\n//\n// All rights reserved. Use of this source code is governed by a\n// BSD-style license that can be found in the LICENSE file.\n#pragma once\n#include <gsl/gsl_spline.h>\n\n#include <Eigen/Core>\n#include <functional>\n#include <memory>\n\n#include \"pyinterp/detail/gsl/accelerator.hpp\"\n\nnamespace pyinterp::detail::gsl {\n\n/// Interpolate a 1-D function\nclass Interpolate1D {\n public:\n  /// Interpolate a 1-D function\n  ///\n  /// @param size Size of workspace\n  /// @param type fitting model\n  /// @param acc Accelerator\n  Interpolate1D(const size_t size, const gsl_interp_type* type, Accelerator acc)\n      : workspace_(\n            std::unique_ptr<gsl_spline, std::function<void(gsl_spline*)>>(\n                gsl_spline_alloc(type, size),\n                [](gsl_spline* ptr) { gsl_spline_free(ptr); })),\n        acc_(std::move(acc)) {}\n\n  /// Returns the name of the interpolation type used\n  [[nodiscard]] inline auto name() const noexcept -> std::string {\n    return gsl_spline_name(workspace_.get());\n  }\n\n  /// Return the minimum number of points required by the interpolation\n  [[nodiscard]] inline auto min_size() const noexcept -> size_t {\n    return gsl_spline_min_size(workspace_.get());\n  }\n\n  /// Return the interpolated value of y for a given point x\n  [[nodiscard]] inline auto interpolate(const Eigen::VectorXd& xa,\n                                        const Eigen::VectorXd& ya,\n                                        const double x) -> double {\n    init(xa, ya);\n    return gsl_spline_eval(workspace_.get(), x, acc_);\n  }\n\n  /// Return the derivative d of an interpolated function for a given point x\n  [[nodiscard]] inline auto derivative(const Eigen::VectorXd& xa,\n                                       const Eigen::VectorXd& ya,\n                                       const double x) -> double {\n    init(xa, ya);\n    return gsl_spline_eval_deriv(workspace_.get(), x, acc_);\n  }\n\n  /// Return the second derivative d of an interpolated function for a given\n  /// point x\n  [[nodiscard]] inline auto second_derivative(const Eigen::VectorXd& xa,\n                                              const Eigen::VectorXd& ya,\n                                              const double x) -> double {\n    init(xa, ya);\n    return gsl_spline_eval_deriv2(workspace_.get(), x, acc_);\n  }\n\n  /// Return the numerical integral result of an interpolated function over the\n  /// range [a, b],\n  [[nodiscard]] inline auto integral(const Eigen::VectorXd& xa,\n                                     const Eigen::VectorXd& ya, const double a,\n                                     const double b) -> double {\n    init(xa, ya);\n    return gsl_spline_eval_integ(workspace_.get(), a, b, acc_);\n  }\n\n private:\n  std::unique_ptr<gsl_spline, std::function<void(gsl_spline*)>> workspace_;\n  Accelerator acc_;\n\n  /// Initializes the interpolation object\n  inline auto init(const Eigen::VectorXd& xa,\n                   const Eigen::VectorXd& ya) noexcept -> void {\n    acc_.reset();\n    gsl_spline_init(workspace_.get(), xa.data(), ya.data(), xa.size());\n  }\n};\n\n}  // namespace pyinterp::detail::gsl\n", "meta": {"hexsha": "a599f05516ecf7d564c72fe963508d65311ebfb2", "size": 3117, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/pyinterp/core/include/pyinterp/detail/gsl/interpolate1d.hpp", "max_stars_repo_name": "readthedocs-assistant/pangeo-pyinterp", "max_stars_repo_head_hexsha": "e9dc18445dce36638d5a90f64c8e2f1b53164f90", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/pyinterp/core/include/pyinterp/detail/gsl/interpolate1d.hpp", "max_issues_repo_name": "readthedocs-assistant/pangeo-pyinterp", "max_issues_repo_head_hexsha": "e9dc18445dce36638d5a90f64c8e2f1b53164f90", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pyinterp/core/include/pyinterp/detail/gsl/interpolate1d.hpp", "max_forks_repo_name": "readthedocs-assistant/pangeo-pyinterp", "max_forks_repo_head_hexsha": "e9dc18445dce36638d5a90f64c8e2f1b53164f90", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.4204545455, "max_line_length": 80, "alphanum_fraction": 0.6124478665, "num_tokens": 694, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.48506222363446294}}
{"text": "#include <cmath>\n\n#include <gtest/gtest.h>\n#include <Eigen/Dense>\n\n#include <BingoCpp/implicit_regression.h>\n\n#include \"test_fixtures.h\"\n\nusing namespace bingo;\n\nnamespace {\n\nclass ImplicitRegressionFixture {\n public:\n  ImplicitTrainingData *training_data_;\n  testutils::SumEquation sum_equation_;\n\n protected:\n  ImplicitTrainingData* init_sample_training_data() {\n    const int num_points = 50;\n    const int num_data_per_feature = 10;\n    const int num_feature = 50 / num_data_per_feature;\n    const int index_block_mod = 3;\n\n    Eigen::ArrayXXd x = Eigen::ArrayXd::LinSpaced(num_points, 0, 0.98);\n    x = x.reshaped(num_feature, num_data_per_feature);\n    x.transposeInPlace();\n\n    Eigen::ArrayXXd dx_dt = Eigen::ArrayXXd::Constant(x.rows(), x.cols(), 1);\n    dx_dt.block(\n        0, index_block_mod, dx_dt.rows(), dx_dt.cols() - index_block_mod)\n        = Eigen::ArrayXXd::Constant(x.rows(), 2, -1);\n    dx_dt.col(dx_dt.cols()/2) = Eigen::ArrayXd::Constant(dx_dt.rows(), 0);\n    return new ImplicitTrainingData(x, dx_dt);\n  }\n};\n\nclass ImplicitRegressionTestNormalize : public ImplicitRegressionFixture,\n                                        public testing::TestWithParam<bool> {\n public:\n  virtual void SetUp() {\n    training_data_ = init_sample_training_data();\n    sum_equation_ = testutils::init_sum_equation();\n  }\n\n  virtual void TearDown() {\n    delete training_data_;\n  }\n};\n\nTEST_P(ImplicitRegressionTestNormalize, EvaluateIndividualFitness) {\n  bool normalize_dot_product = GetParam();\n  auto regressor\n      = new ImplicitRegression(training_data_, -1, normalize_dot_product);\n  double fitness = regressor->EvaluateIndividualFitness(sum_equation_);\n  ASSERT_TRUE(0.14563031020 - fitness < 1e-10);\n  delete regressor;\n}\nINSTANTIATE_TEST_CASE_P(,ImplicitRegressionTestNormalize, testing::Bool());\n\nclass ImplicitRegressionTestNonNormalized : \n    public ImplicitRegressionFixture,\n    public testing::TestWithParam<std::tuple<int, bool>> {\n public:\n  virtual void SetUp() {\n    training_data_ = init_sample_training_data();\n    sum_equation_ = testutils::init_sum_equation();\n  }\n\n  virtual void TearDown() {\n    delete training_data_;\n  }\n};\n\nTEST_P(ImplicitRegressionTestNonNormalized, EvaluateIndividualFitness) {\n  auto const &param = GetParam();\n  auto required_params = std::get<0>(param);\n  auto infinite_fitness = std::get<1>(param);\n  auto regressor = new ImplicitRegression(training_data_,\n                                          required_params,\n                                          infinite_fitness);\n  double fitness = regressor->EvaluateIndividualFitness(sum_equation_);\n  ASSERT_TRUE(!std::isfinite(fitness) == infinite_fitness);\n  delete regressor;\n}\nINSTANTIATE_TEST_CASE_P(instance_one, ImplicitRegressionTestNonNormalized,\n  ::testing::Values(std::make_tuple(4, false), std::make_tuple(5, true))\n);\n\nclass ImplicitRegressionTest : public ImplicitRegressionFixture,\n                               public testing::Test {\n public:\n  virtual void SetUp() {\n    training_data_ = init_sample_training_data();\n    sum_equation_ = testutils::init_sum_equation();\n  }\n\n  virtual void TearDown() {\n    delete training_data_;\n  }\n};\n\nTEST_F(ImplicitRegressionTest, GetSubsetOfData) {\n  auto data_input = Eigen::ArrayXd::LinSpaced(5, 0, 4);\n  auto training_data = new ImplicitTrainingData(data_input, data_input);\n  auto subset_training_data = training_data->GetItem(std::vector<int>{0, 2, 3});\n  Eigen::ArrayXXd expected_subset(3, 1);\n  expected_subset << 0, 2, 3;\n  ASSERT_TRUE(subset_training_data->x.isApprox(expected_subset));\n  ASSERT_TRUE(subset_training_data->dx_dt.isApprox(expected_subset));\n  delete training_data;\n  delete subset_training_data;\n}\n\nTEST_F(ImplicitRegressionTest, CorrectTrainingDataSize) {\n  for (int size : std::vector<int> {2, 5, 50}) {\n    Eigen::ArrayXXd data_input = Eigen::ArrayXd::LinSpaced(size, 0, 10);\n    auto training_data = new ImplicitTrainingData(data_input, data_input);\n    ASSERT_EQ(training_data->Size(), size);\n    delete training_data;\n  }\n}\n\nTEST(ImplicitRegressionPartials, PartialCalculationInTrainingData) {\n  auto data_input = Eigen::ArrayXd::LinSpaced(20, 0., 19.);\n  Eigen::ArrayXXd data_array(data_input.rows(), 3);\n  data_array << data_input * 0, data_input * 1, data_input * 2;\n  auto training_data = new ImplicitTrainingData(data_array);\n  Eigen::ArrayXXd expected_derivatives(13, 3);\n  expected_derivatives << Eigen::ArrayXd::Ones(13) * 0,\n                          Eigen::ArrayXd::Ones(13) * 1,\n                          Eigen::ArrayXd::Ones(13) * 2;\n  ASSERT_TRUE(training_data->dx_dt.isApprox(expected_derivatives));\n  delete training_data;\n}\n\nTEST(ImplicitRegressionPartials, PartialCalculationInTrainingDataNaN) {\n  auto data_input = Eigen::ArrayXd::LinSpaced(20, 0., 19.) * 2;\n  Eigen::ArrayXXd data_array(data_input.rows() * 2 + 1, 1);\n  data_array << data_input,\n                std::numeric_limits<double>::quiet_NaN(),\n                data_input;\n  auto training_data = new ImplicitTrainingData(data_array);\n  Eigen::ArrayXd expected_derivative = Eigen::ArrayXd::Constant(26, 2.0);\n  ASSERT_TRUE(training_data->dx_dt.isApprox(expected_derivative));\n  delete training_data;\n}\n} // namespace (anonymous)", "meta": {"hexsha": "a89aa78bdcb7b403875bc49f06586aea2161aadc", "size": 5202, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/implicit_regression_tests.cpp", "max_stars_repo_name": "imikejackson/bingocpp", "max_stars_repo_head_hexsha": "6ba00a490c8cb46edebfd78f56b1604a76d668e9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/implicit_regression_tests.cpp", "max_issues_repo_name": "imikejackson/bingocpp", "max_issues_repo_head_hexsha": "6ba00a490c8cb46edebfd78f56b1604a76d668e9", "max_issues_repo_licenses": ["Apache-2.0"], "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/implicit_regression_tests.cpp", "max_forks_repo_name": "imikejackson/bingocpp", "max_forks_repo_head_hexsha": "6ba00a490c8cb46edebfd78f56b1604a76d668e9", "max_forks_repo_licenses": ["Apache-2.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.9127516779, "max_line_length": 80, "alphanum_fraction": 0.7135717032, "num_tokens": 1285, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.48506222363446294}}
{"text": "/**************************************************************************\n** This file is a part of our work (Siggraph'16 paper, binary, code and dataset):\n**\n** Roto++: Accelerating Professional Rotoscoping using Shape Manifolds\n** Wenbin Li, Fabio Viola, Jonathan Starck, Gabriel J. Brostow and Neill D.F. Campbell\n**\n** w.li AT cs.ucl.ac.uk\n** http://visual.cs.ucl.ac.uk/pubs/rotopp\n**\n** Copyright (c) 2016, Wenbin Li\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 and data must retain the above\n**    copyright notice, this list of conditions and the following disclaimer.\n** -- Redistributions in binary form must reproduce the above copyright\n**    notice, this list of conditions and the following disclaimer in the\n**    documentation and/or other materials provided with the distribution.\n**\n** THIS WORK AND THE RELATED SOFTWARE, SOURCE CODE AND DATA IS PROVIDED BY\n** THE COPYRIGHT 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 DISCLAIMED. IN\n** NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n** INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n** BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n** USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n** 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,\n** EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***************************************************************************/\n\n#ifndef PLANARTRACKERSOLVER_HPP\n#define PLANARTRACKERSOLVER_HPP\n\n#include \"ceres/ceres.h\"\n#include \"glog/logging.h\"\n#include \"ceres/solver.h\"\n#include \"gflags/gflags.h\"\n#include <glog/logging.h>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/SparseCore>\n#include <Eigen/Eigenvalues>\n\n#include <array>\n#include <random>\n#include <cmath>\n#include <fstream>\n\n#include \"include/rotoSolver/gplvm.hpp\"\n#include \"include/rotoSolver/fileUtils.hpp\"\n#include \"include/rotoSolver/baseDefs.hpp\"\n#include \"include/rotoSolver/eigenUtils.hpp\"\n#include \"include/rotoSolver/transformations.hpp\"\n\nDECLARE_double(s);\nDECLARE_double(a);\nDECLARE_double(r);\nDECLARE_double(trans_weight);\nDECLARE_double(rot_weight);\nDECLARE_double(scale_weight);\nDECLARE_bool(skip_initial_optimisation);\n\nstruct PlanarTrackSolve\n{\n    typedef Eigen::MatrixXd Matrix;\n    typedef Eigen::VectorXd Vector;\n\n    typedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> RowMatrix;\n    typedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor> ColMatrix;\n\nprivate:\n\n    shared_ptr<GPLVM> _gplvm;\n\n    // Very important that it's RowMajor here..\n    RowMatrix _U;\n\n    const int _N, _Q;\n    const int _startIdx, _endIdx;\n\n    PlanarTrackingData _keyFrames;\n\n    std::vector<int> _keyFramesIndex;\n\n    std::vector<PlanarTrackingData> _targetTracks;\n\n    Vector _normalisationWeight;\n\n    shared_ptr<RigidMotionEstimator> _motionEstimator;\n\n    RowMatrix _translations;\n    Vector _rotations;\n    Vector _scales;\n\n    ceres::LossFunctionWrapper* _residualLossFunctionPtr;\n\npublic:\n\n    PlanarTrackSolve(shared_ptr<GPLVM> gplvm,\n                     const Matrix& U,\n                     const std::vector<PlanarTrackingData>& targetTracks,\n                     const int startIdx, const int endIdx,\n                     const PlanarTrackingData& keyFrames,\n                     const std::vector<int>& keyFramesIndex,\n                     shared_ptr<RigidMotionEstimator> motionEstimator = shared_ptr<RigidMotionEstimator>());\n\n    void SpecialTest();\n\n    bool RunSolve();\n\n    Matrix GetOutput(Vector* gplvmVariance = NULL) const;\n    Matrix GetOutputLinearInterp(Vector* gplvmVariance = NULL) const;\n\n    void SaveToFile(std::string textFilename, std::string confidenceOutputFile = \"\") const;\n    void SaveToFileLinearInterp(std::string textFilename, std::string confidenceOutputFile = \"\") const;\n\n    bool UsingRotationAndTranslation() const\n    {\n        return (_motionEstimator.get() != 0);\n    }\n\n    const RowMatrix& GetU() const\n    {\n        return _U;\n    }\n\nprivate:\n\n    Vector CalcConfidence(const Vector& gplvmVariance) const;\n\n    void CropTargetTracks(int width = 1920, int height = 1080);\n\n    void InitRotationAndTranslation();\n\n    template <typename Mat>\n    double* getFrameParameterPointer(Mat& M, const int frameIdx)\n    {\n        nassert (frameIdx >= 0);\n        nassert (frameIdx < _N);\n        double* ptr = M.data();\n        ptr += (frameIdx * M.cols());\n        return ptr;\n    }\n\n};\n\n#endif // PLANARTRACKERSOLVER_HPP\n", "meta": {"hexsha": "a603ead09abecf935492e2e1830771ed186b99fc", "size": 4941, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/rotoSolver/planarTrackerSolver.hpp", "max_stars_repo_name": "vinben/Rotopp", "max_stars_repo_head_hexsha": "f0c25db5bd25074c55ff0f67539a2452d92aaf72", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 47.0, "max_stars_repo_stars_event_min_datetime": "2016-07-27T07:22:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-17T13:08:19.000Z", "max_issues_repo_path": "include/rotoSolver/planarTrackerSolver.hpp", "max_issues_repo_name": "vinben/Rotopp", "max_issues_repo_head_hexsha": "f0c25db5bd25074c55ff0f67539a2452d92aaf72", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-09-24T06:04:39.000Z", "max_issues_repo_issues_event_max_datetime": "2016-09-25T10:34:19.000Z", "max_forks_repo_path": "include/rotoSolver/planarTrackerSolver.hpp", "max_forks_repo_name": "vinben/Rotopp", "max_forks_repo_head_hexsha": "f0c25db5bd25074c55ff0f67539a2452d92aaf72", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2016-07-27T10:44:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-01T21:08:33.000Z", "avg_line_length": 32.2941176471, "max_line_length": 108, "alphanum_fraction": 0.6996559401, "num_tokens": 1127, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.48506222363446294}}
{"text": "//\n//  rntn.h\n//  NeuralNetwork\n//\n//  Created by Nikhil Joshi on 12/14/14.\n//  Copyright (c) 2014 Nikhil Joshi. All rights reserved.\n//\n\n#ifndef __NeuralNetwork__rntn__\n#define __NeuralNetwork__rntn__\n\n#include <unordered_map>\n#include <string>\n#include <ctime>\n\n#include <Eigen/Dense>\n\n#include \"utility-rntn.hpp\"\n#include \"functionalitysuite.hpp\"\n\nnamespace NNetwork {\n    \n    typedef std::unordered_map<std::string, unsigned long> Vocabulary;\n    \n    class RNTN {\n    public:\n        \n        // constructor\n        RNTN(const size_t dimWordRep,\n             const size_t numClasses,\n             const size_t lowerClassIndex,\n             const bool useTensor = true)\n        : _dimWordRep(dimWordRep),\n        _numClasses(numClasses),\n        _lowerClassIndex(lowerClassIndex),\n        _useTensor(useTensor) {\n            init();\n        }\n        \n        // Set vocabulary\n        void setVocabulary(Vocabulary& vocab)                     { _vocabMap = vocab; }\n        // Get vocabulary\n        Vocabulary getVocabulary(void) const                      { return _vocabMap; }\n        // Set non-linearity\n        void setNonlinearlity(const FunctionalitySuite& nonlinearity);\n        \n        // Train the network\n        double train(const char* trainingFile, const double regularizer = 0,\n                     const bool verbos = true);\n        // Predict sentiment\n        size_t predict(PTree& p);\n        size_t predict(PTree_uptr& p);\n\n        \n        // A unit_test method\n        friend bool isValidRntnImplementation(RNTN& testNet, const char* testFile,\n                                              const size_t numExamples, const bool resetNet);\n        \n        \n    private:\n        \n        size_t _dimWordRep, _lowerClassIndex, _numClasses;\n        Eigen::MatrixXd _sentimentMatrix, _wordRepMatrix, _weightMatrix;\n        std::vector<Eigen::MatrixXd> _interactionTensor;\n        Vocabulary _vocabMap;\n        FunctionalitySuite* _nonlinearity;\n        bool _useTensor;\n        \n        // No copying of RNTN network\n        RNTN& operator=(const RNTN& o) {\n            return *this;\n        }\n        // No assignments\n        RNTN(const RNTN& o)\n        : _vocabMap(o._vocabMap) {\n            \n        }\n        \n        // Initialize network to random state\n        void init(void);\n        // Is the given node a leaf\n        bool isLeaf(const PTree& p) const;\n        bool isLeaf(const PTree_uptr& p) const;\n        // Is a given node a root\n        bool isRoot(const PTree& p) const;\n        bool isRoot(const PTree_uptr& p) const;\n        // Get current representation of a word at the (leaf) node\n        Eigen::VectorXd getRepresentation(const PTree& p);\n        Eigen::VectorXd getRepresentation(const PTree_uptr& p);\n        // Evaluate the sentiment for the given phrase at a given node.\n        Eigen::VectorXd evaluateSentiment(PTree& p);\n        Eigen::VectorXd evaluateSentiment(PTree_uptr& p);\n        // Evaluate representation for the tree rooted at given node\n        Eigen::VectorXd evaluateRepresentation(PTree& p);\n        Eigen::VectorXd evaluateRepresentation(PTree_uptr& p);\n        // Loss function (softmax)\n        double loss(const Eigen::Ref<const Eigen::VectorXd>& output,\n                    const Eigen::Ref<const Eigen::VectorXd>& label, const double regularizer = 0);\n        double loss(PTree& p, const double regularizer = 0);\n        double loss(PTree_uptr& p, const double regularizer = 0);\n        double loss(std::vector<PTree_uptr>& trees, const double regularizer = 0);\n        // Corrections to Ws, W, V\n        void correctionsToParamMatrices(PTree& p,\n                                        Eigen::MatrixXd& correctionWsent,\n                                        Eigen::MatrixXd& correctionW,\n                                        std::vector<Eigen::MatrixXd>& correctionV,\n                                        Eigen::VectorXd carryDown);\n        void correctionsToParamMatrices(PTree_uptr& p,\n                                        Eigen::MatrixXd& correctionWsent,\n                                        Eigen::MatrixXd& correctionW,\n                                        std::vector<Eigen::MatrixXd>& correctionV,\n                                        Eigen::VectorXd carryDown);\n        void correctionsToParamMatrices(std::vector<PTree_uptr>& trees,\n                                        Eigen::MatrixXd& correctionWsent,\n                                        Eigen::MatrixXd& correctionW,\n                                        std::vector<Eigen::MatrixXd>& correctionV,\n                                        Eigen::VectorXd carryDown);\n        \n    };\n    \n    \n    // Implementation test method\n    bool isValidRntnImplementation(RNTN& testNet, const char* testFile,\n                                   const size_t numExamples, const bool resetNet = true);\n    \n}\n\n#endif /* defined(__NeuralNetwork__rntn__) */\n", "meta": {"hexsha": "b30228d3fc63aeb480b1e3b5c334838800b9610a", "size": 4912, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "NeuralNetwork/rntn.hpp", "max_stars_repo_name": "nikhiljjoshi/neuralNetwork", "max_stars_repo_head_hexsha": "6c5df9e2fb1edac8c28d8bd191972d5f574fba83", "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": "NeuralNetwork/rntn.hpp", "max_issues_repo_name": "nikhiljjoshi/neuralNetwork", "max_issues_repo_head_hexsha": "6c5df9e2fb1edac8c28d8bd191972d5f574fba83", "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": "NeuralNetwork/rntn.hpp", "max_forks_repo_name": "nikhiljjoshi/neuralNetwork", "max_forks_repo_head_hexsha": "6c5df9e2fb1edac8c28d8bd191972d5f574fba83", "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.0775193798, "max_line_length": 98, "alphanum_fraction": 0.5675895765, "num_tokens": 1046, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4850622236344629}}
{"text": "//==================================================================================================\n/*\n  Copyright 2017 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//! [saturated_abs]\n#include <boost/simd/arithmetic.hpp>\n#include <boost/simd/pack.hpp>\n#include <boost/simd/constant/minf.hpp>\n#include <iostream>\n\nnamespace bs =  boost::simd;\nusing pack_ft =  bs::pack <float, 4>;\nusing pack_it =  bs::pack <std::int16_t,4>;\n\nint main()\n{\n  pack_ft pf = {-1.0f, 2.0f, -3.0f, bs::Minf<float>()       };\n  pack_it pi = {-1,    2,    -3,    bs::Minf<std::int16_t>()};\n  std::cout << \" pf =  \" << pf  << \" -> bs::abs(pf) =                  \" << bs::abs(pf)                 << std::endl;\n  std::cout << \" pi =  \" << pi  << \" -> bs::abs(pi) =                  \" << bs::abs(pi)                 << std::endl;\n  std::cout << \" pi =  \" << pi  << \" -> bs::saturated_(bs::abs(pi)) =  \" << bs::saturated_(bs::abs)(pi) << std::endl;\n  return 0;\n}\n//! [saturated_abs]\n", "meta": {"hexsha": "c396e17867a432a71abab717c759147e0bf68c44", "size": 1169, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/doc/arithmetic/saturated_abs.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": "test/doc/arithmetic/saturated_abs.cpp", "max_issues_repo_name": "remymuller/boost.simd", "max_issues_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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/doc/arithmetic/saturated_abs.cpp", "max_forks_repo_name": "remymuller/boost.simd", "max_forks_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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": 40.3103448276, "max_line_length": 117, "alphanum_fraction": 0.4465355004, "num_tokens": 323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4850622236344629}}
{"text": "#pragma once\n\n#ifndef _VECTOR_H_\n#define _VECTOR_H_\n\n// Includes\n#include <Eigen/Dense>\n#include <viennacl/vector.hpp>\n#include \"AbstractLinearAlgebraObject.hpp\"\n\nnamespace LightBulb\n{\n\t/**\n\t * \\brief Describes a one dimensional linear algebra data structure, also called vector.\n\t * \\tparam DataType The data type which should be stored in the data structure.\n\t */\n\ttemplate<typename DataType = float>\n\tclass Vector : public AbstractLinearAlgebraObject<Eigen::Matrix<DataType, -1, 1>, viennacl::vector<DataType>>\n\t{\n\tprotected:\n\t\tvoid copyToEigen() const override\n\t\t{\n\t\t\tif (this->eigenValue.size() != this->viennaclValue.size())\n\t\t\t\tthis->eigenValue.resize(this->viennaclValue.size());\n\n\t\t\tviennacl::copy(this->viennaclValue, this->eigenValue);\n\t\t}\n\t\tvoid copyToViennaCl() const override\n\t\t{\n\t\t\tif (this->eigenValue.size() != this->viennaclValue.size())\n\t\t\t\tthis->viennaclValue.resize(this->eigenValue.size());\n\n\t\t\tif (this->eigenValue.size() != 0)\n\t\t\t\tviennacl::copy(this->eigenValue, this->viennaclValue);\n\t\t}\n\tpublic:\n\t\t/**\n\t\t* \\brief Creates a new matrix with a specific size.\n\t\t* \\param rows The amount of rows.\n\t\t*/\n\t\tVector(int rows = 0)\n\t\t{\n\t\t\tif (rows > 0) {\n\t\t\t\tthis->eigenValue = Eigen::Matrix<DataType, -1, 1>(rows);\n\t\t\t\tthis->eigenValueIsDirty = true;\n\t\t\t}\n\t\t}\n\t\tVector(const Vector& other)\n\t\t\t: AbstractLinearAlgebraObject<Eigen::Matrix<DataType, -1, 1>, viennacl::vector<DataType>>()\n\t\t{\n\t\t\tif (!((other.eigenValueIsDirty && other.eigenValue.size() == 0) || (other.viennaclValueIsDirty && other.viennaclValue.empty()) || (other.eigenValue.size() == 0 && other.viennaclValue.empty())))\n\t\t\t\tthis->copyAllFrom(other);\n\t\t}\n\t\tVector(const Eigen::Matrix<DataType, -1, 1>& eigenVector)\n\t\t{\n\t\t\tthis->eigenValue = eigenVector;\n\t\t\tthis->eigenValueIsDirty = true;\n\t\t}\n\t};\n}\n\n#include \"LightBulb/IO/VectorIO.hpp\"\n\n#endif", "meta": {"hexsha": "2361f0e612288686a37828d042a0f28eb4849982", "size": 1825, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/LightBulb/LinearAlgebra/Vector.hpp", "max_stars_repo_name": "domin1101/ANNHelper", "max_stars_repo_head_hexsha": "50acb5746d6dad6777532e4c7da4983a7683efe0", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2016-02-04T06:14:42.000Z", "max_stars_repo_stars_event_max_datetime": "2017-02-06T02:21:43.000Z", "max_issues_repo_path": "include/LightBulb/LinearAlgebra/Vector.hpp", "max_issues_repo_name": "domin1101/ANNHelper", "max_issues_repo_head_hexsha": "50acb5746d6dad6777532e4c7da4983a7683efe0", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 41.0, "max_issues_repo_issues_event_min_datetime": "2015-04-15T21:05:45.000Z", "max_issues_repo_issues_event_max_datetime": "2015-07-09T12:59:02.000Z", "max_forks_repo_path": "include/LightBulb/LinearAlgebra/Vector.hpp", "max_forks_repo_name": "domin1101/LightBulb", "max_forks_repo_head_hexsha": "50acb5746d6dad6777532e4c7da4983a7683efe0", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.515625, "max_line_length": 196, "alphanum_fraction": 0.6915068493, "num_tokens": 542, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737775116229, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.48506221225319923}}
{"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_FUNCTION_ACSC_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_ACSC_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-trigonometric\n    Function object implementing acsc capabilities\n\n    inverse cosecant in radian.\n\n    @par Semantic:\n\n    For every parameter of floating type T\n\n    @code\n    T r = acsc(x);\n    @endcode\n\n    is similar to:\n\n    @code\n    T r = asin(rec(x));\n    @endcode\n\n    @see acscd\n\n  **/\n  const boost::dispatch::functor<tag::acsc_> acsc = {};\n} }\n#endif\n\n#include <boost/simd/function/scalar/acsc.hpp>\n#include <boost/simd/function/simd/acsc.hpp>\n\n#endif\n", "meta": {"hexsha": "47bbb4c0b1dc215c24bc7c3be2e3fe1fd121bf9a", "size": 1068, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/acsc.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/function/acsc.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/function/acsc.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": 20.9411764706, "max_line_length": 100, "alphanum_fraction": 0.5664794007, "num_tokens": 238, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.48502871331437286}}
{"text": "#include <iostream>\n#include <armadillo>\n\nusing namespace std;\nusing namespace arma;\n\nint main()\n{\n  ///////////////////////////ANN LAYER TEST (USER INPUT)////////////////////////\n  arma::mat input;\n  input << 1  << 19  << arma::endr\n        << 2  << 20  << arma::endr\n        << 3  << 21  << arma::endr\n        << 4  << 22  << arma::endr\n        << 5  << 23  << arma::endr\n        << 6  << 24  << arma::endr\n        << 7  << 25  << arma::endr\n        << 8  << 26  << arma::endr\n        << 9  << 27  << arma::endr\n        << 10 << 28  << arma::endr\n        << 11 << 29  << arma::endr\n        << 12 << 30  << arma::endr\n        << 13 << 31  << arma::endr\n        << 14 << 32  << arma::endr\n        << 15 << 33  << arma::endr\n        << 16 << 34  << arma::endr\n        << 17 << 35  << arma::endr\n        << 18 << 36  << arma::endr;\n\n  size_t size = 3; // number of channels\n  const double eps = 1e-5;\n  const double momentum = 0.1;\n  //////////////////////////////////////////////////////////////////////////////\n\n  ///////////////////////////INSTANCE NORM FORWARD//////////////////////////////\n  const size_t shapeA = input.n_rows;\n  const size_t shapeB = input.n_cols;\n  const size_t shapeC = size;\n  arma::mat runningTemp = arma::zeros(shapeC, 1);\n  size *= input.n_cols;\n  input = arma::vectorise(input);\n\n    /////////////////////////BATCH NORM RESET + FORWARD/////////////////////////\n    arma::mat weights, runningMean, runningVariance;\n    weights.set_size(size + size, 1);\n    runningMean.zeros(size, 1);\n    runningVariance.ones(size, 1);\n    arma::mat gamma, beta;\n    gamma = arma::mat(weights.memptr(), size, 1, false, false);\n    beta = arma::mat(weights.memptr() + gamma.n_elem, size, 1, false, false);\n    gamma.fill(1.0);\n    beta.fill(0.0);\n    const size_t batchSize = input.n_cols;\n    const size_t inputSize = input.n_rows / size;\n    arma::mat output;\n    output.set_size(arma::size(input));\n    arma::cube inputTemp(const_cast<arma::mat&>(input).memptr(), inputSize, size, batchSize, false, false);\n    arma::cube outputTemp(const_cast<arma::mat&>(output).memptr(), inputSize, size, input.n_cols, false, false);\n    outputTemp = inputTemp;\n    arma::mat mean = arma::mean(arma::mean(inputTemp, 2), 0);\n    arma::mat variance = arma::mean(arma::mean(arma::pow(inputTemp.each_slice() - arma::repmat(mean,inputSize, 1), 2), 2), 0);\n    outputTemp.each_slice() -= arma::repmat(mean, inputSize, 1);\n    arma::cube inputMean;\n    inputMean.set_size(arma::size(inputTemp));\n    inputMean = outputTemp;\n    outputTemp.each_slice() /= arma::sqrt(arma::repmat(variance, inputSize, 1) + eps);\n    arma::cube normalized;\n    normalized.set_size(arma::size(inputTemp));\n    normalized = outputTemp;\n    outputTemp.each_slice() %= arma::repmat(gamma.t(),inputSize, 1);\n    outputTemp.each_slice() += arma::repmat(beta.t(), inputSize, 1);\n    double nElements = 1.0 / (input.n_elem - size + eps);\n    runningMean = (1 - momentum) * runningMean + momentum * mean.t();\n    runningVariance = (1 - momentum) * runningVariance + input.n_elem * nElements * momentum * variance.t();\n    //////////////////////////////////////////////////////////////////////////////\n\n  input.reshape(shapeA, shapeB);\n  output.reshape(shapeA, shapeB);\n  runningMean.reshape(shapeC, shapeB);\n  runningVariance.reshape(shapeC, shapeB);\n  runningTemp = arma::mean(runningMean, 1);\n  runningMean.set_size(shapeC, 1);\n  runningMean = runningTemp;\n  runningTemp = arma::mean(runningVariance, 1);\n  runningVariance.set_size(shapeC, 1);\n  runningVariance = runningTemp;\n  mean.reshape(shapeC, shapeB);\n  //////////////////////////////////////////////////////////////////////////////\n\n  ///////////////////////////ANN LAYER TEST (USER INPUT)////////////////////////\n  arma::mat gy = output;\n  //////////////////////////////////////////////////////////////////////////////\n\n  ///////////////////////////INSTANCE NORM BACKWARD/////////////////////////////\n  gy = arma::vectorise(gy);\n  input = arma::vectorise(input);\n\n    ///////////////////////////BATCH NORM BACKWARD////////////////////////////////\n    arma::mat g;\n    const arma::mat stdInv = 1.0 / arma::sqrt(variance + eps);\n    g.set_size(arma::size(input));\n    arma::cube gyTemp(const_cast<arma::mat&>(gy).memptr(), input.n_rows / size, size, input.n_cols, false, false);\n    arma::cube gTemp(const_cast<arma::mat&>(g).memptr(), input.n_rows / size, size, input.n_cols, false, false);\n    arma::cube norm = gyTemp.each_slice() % arma::repmat(gamma.t(), input.n_rows / size, 1);\n    arma::mat temp = arma::sum(norm % inputMean, 2);\n    arma::mat vars = temp % arma::repmat(arma::pow(stdInv, 3), input.n_rows / size, 1) * -0.5;\n    gTemp = (norm.each_slice() % arma::repmat(stdInv, input.n_rows / size, 1) + (inputMean.each_slice() % vars * 2)) / input.n_cols;\n    arma::mat normTemp = arma::sum(norm.each_slice() %arma::repmat(-stdInv, input.n_rows / size, 1) , 2) / input.n_cols;\n    gTemp.each_slice() += normTemp;\n    //////////////////////////////////////////////////////////////////////////////\n\n  input.reshape(shapeA, shapeB);\n  output.reshape(shapeA, shapeB);\n  g.reshape(shapeA, shapeB);\n  gy.reshape(shapeA, shapeB);\n  //////////////////////////////////////////////////////////////////////////////\n\n  cout << \"-----------------------------------\" << endl;\n  mean.print(\"Input mean: \");\n  cout << \"-----------------------------------\" << endl;\n  variance.print(\"Input variance: \");\n  cout << \"-----------------------------------\" << endl;\n  output.print(\"Output: \");\n  cout << \"-----------------------------------\" << endl;\n  runningMean.print(\"Running Mean: \");\n  cout << \"-----------------------------------\" << endl;\n  runningVariance.print(\"Running Variance: \");\n  cout << \"-----------------------------------\" << endl;\n  g.print(\"g: \");\n  cout << \"-----------------------------------\" << endl;\n  gy.print(\"gy: \");\n  cout << \"-----------------------------------\" << endl;\n  cout << \"Sum of values in g matrix : \" << arma::accu(g) << endl;\n  cout << \"-----------------------------------\" << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "7faaaa1eff3ec0cc4c4f9b92d065605e3d045ac2", "size": 6053, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "instance_norm/bn.cpp", "max_stars_repo_name": "iamshnoo/mlpack-testing", "max_stars_repo_head_hexsha": "43f9fde18afc7f1e6d54c0a2bd59709c103eed55", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "instance_norm/bn.cpp", "max_issues_repo_name": "iamshnoo/mlpack-testing", "max_issues_repo_head_hexsha": "43f9fde18afc7f1e6d54c0a2bd59709c103eed55", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "instance_norm/bn.cpp", "max_forks_repo_name": "iamshnoo/mlpack-testing", "max_forks_repo_head_hexsha": "43f9fde18afc7f1e6d54c0a2bd59709c103eed55", "max_forks_repo_licenses": ["BSD-3-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.8623188406, "max_line_length": 132, "alphanum_fraction": 0.5009086403, "num_tokens": 1617, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4850287133143728}}
{"text": "#include <gtest/gtest.h>\n\n#include <Eigen/Eigenvalues>\n#include <cppsim/circuit.hpp>\n#include <cppsim/gate_factory.hpp>\n#include <cppsim/gate_named_pauli.hpp>\n#include <cppsim/observable.hpp>\n#include <cppsim/pauli_operator.hpp>\n#include <cppsim/state.hpp>\n#include <cppsim/type.hpp>\n#include <cppsim/utility.hpp>\n#include <csim/constant.hpp>\n#include <fstream>\n\n#include \"../util/util.hpp\"\n\nTEST(ObservableTest, CheckExpectationValue) {\n    const UINT n = 4;\n    const UINT dim = 1ULL << n;\n    const double eps = 1e-14;\n    double coef;\n    CPPCTYPE res;\n    CPPCTYPE test_res;\n    Random random;\n\n    Eigen::MatrixXcd X(2, 2);\n    X << 0, 1, 1, 0;\n\n    QuantumState state(n);\n    state.set_computational_basis(0);\n    Eigen::VectorXcd test_state = Eigen::VectorXcd::Zero(dim);\n    test_state(0) = 1.;\n\n    coef = random.uniform();\n    Observable observable(n);\n    observable.add_operator(coef, \"X 0\");\n    Eigen::MatrixXcd test_observable = Eigen::MatrixXcd::Zero(dim, dim);\n    test_observable += coef * get_expanded_eigen_matrix_with_identity(0, X, n);\n\n    res = observable.get_expectation_value(&state);\n    test_res = (test_state.adjoint() * test_observable * test_state);\n    ASSERT_NEAR(test_res.real(), res.real(), eps);\n    ASSERT_NEAR(res.imag(), 0, eps);\n    ASSERT_NEAR(test_res.imag(), 0, eps);\n\n    state.set_Haar_random_state();\n    for (ITYPE i = 0; i < dim; ++i) test_state[i] = state.data_cpp()[i];\n    res = observable.get_expectation_value(&state);\n    test_res = (test_state.adjoint() * test_observable * test_state);\n    ASSERT_NEAR(test_res.real(), res.real(), eps);\n    ASSERT_NEAR(res.imag(), 0, eps);\n    ASSERT_NEAR(test_res.imag(), 0, eps);\n\n    for (UINT repeat = 0; repeat < 10; ++repeat) {\n        Observable rand_observable(n);\n        Eigen::MatrixXcd test_rand_observable =\n            Eigen::MatrixXcd::Zero(dim, dim);\n\n        UINT term_count = random.int32() % 10 + 1;\n        for (UINT term = 0; term < term_count; ++term) {\n            std::vector<UINT> paulis(n, 0);\n            Eigen::MatrixXcd test_rand_observable_term =\n                Eigen::MatrixXcd::Identity(dim, dim);\n            coef = random.uniform();\n            for (UINT i = 0; i < paulis.size(); ++i) {\n                paulis[i] = random.int32() % 4;\n\n                test_rand_observable_term *=\n                    get_expanded_eigen_matrix_with_identity(\n                        i, get_eigen_matrix_single_Pauli(paulis[i]), n);\n            }\n            test_rand_observable += coef * test_rand_observable_term;\n\n            std::string str = \"\";\n            for (UINT ind = 0; ind < paulis.size(); ind++) {\n                UINT val = paulis[ind];\n                if (val != 0) {\n                    if (val == 1)\n                        str += \" X\";\n                    else if (val == 2)\n                        str += \" Y\";\n                    else if (val == 3)\n                        str += \" Z\";\n                    str += \" \" + std::to_string(ind);\n                }\n            }\n            rand_observable.add_operator(coef, str.c_str());\n        }\n\n        state.set_Haar_random_state();\n        for (ITYPE i = 0; i < dim; ++i) test_state[i] = state.data_cpp()[i];\n\n        res = rand_observable.get_expectation_value(&state);\n        test_res = test_state.adjoint() * test_rand_observable * test_state;\n        ASSERT_NEAR(test_res.real(), res.real(), eps);\n        ASSERT_NEAR(res.imag(), 0, eps);\n        ASSERT_NEAR(test_res.imag(), 0, eps);\n    }\n}\n\nTEST(ObservableTest, CheckParsedObservableFromOpenFermionText) {\n    auto func = [](const std::string str,\n                    const QuantumStateBase* state) -> CPPCTYPE {\n        CPPCTYPE energy = 0;\n\n        std::vector<std::string> lines = split(str, \"\\n\");\n\n        for (std::string line : lines) {\n            // std::cout << state->get_norm() << std::endl;\n\n            std::vector<std::string> elems;\n            elems = split(line, \"()j[]+\");\n\n            chfmt(elems[3]);\n\n            CPPCTYPE coef(std::stod(elems[0]), std::stod(elems[1]));\n            // std::cout << elems[3].c_str() << std::endl;\n\n            PauliOperator mpt(elems[3].c_str(), coef.real());\n\n            // std::cout << mpt.get_coef() << \" \";\n            // std::cout << elems[3].c_str() << std::endl;\n            energy += mpt.get_expectation_value(state);\n            // mpt.get_expectation_value(state);\n        }\n        return energy;\n    };\n\n    const double eps = 1e-14;\n    const std::string text =\n        \"(-0.8126100000000005+0j) [] +\\n\"\n        \"(0.04532175+0j) [X0 Z1 X2] +\\n\"\n        \"(0.04532175+0j) [X0 Z1 X2 Z3] +\\n\"\n        \"(0.04532175+0j) [Y0 Z1 Y2] +\\n\"\n        \"(0.04532175+0j) [Y0 Z1 Y2 Z3] +\\n\"\n        \"(0.17120100000000002+0j) [Z0] +\\n\"\n        \"(0.17120100000000002+0j) [Z0 Z1] +\\n\"\n        \"(0.165868+0j) [Z0 Z1 Z2] +\\n\"\n        \"(0.165868+0j) [Z0 Z1 Z2 Z3] +\\n\"\n        \"(0.12054625+0j) [Z0 Z2] +\\n\"\n        \"(0.12054625+0j) [Z0 Z2 Z3] +\\n\"\n        \"(0.16862325+0j) [Z1] +\\n\"\n        \"(-0.22279649999999998+0j) [Z1 Z2 Z3] +\\n\"\n        \"(0.17434925+0j) [Z1 Z3] +\\n\"\n        \"(-0.22279649999999998+0j) [Z2]\";\n\n    CPPCTYPE res, test_res;\n\n    Observable* observable;\n    observable = observable::create_observable_from_openfermion_text(text);\n    ASSERT_NE(observable, (Observable*)NULL);\n    UINT qubit_count = observable->get_qubit_count();\n\n    QuantumState state(qubit_count);\n    state.set_computational_basis(0);\n\n    res = observable->get_expectation_value(&state);\n    test_res = func(text, &state);\n\n    ASSERT_NEAR(test_res.real(), res.real(), eps);\n    ASSERT_NEAR(test_res.imag(), res.imag(), eps);\n\n    state.set_Haar_random_state();\n\n    res = observable->get_expectation_value(&state);\n    test_res = func(text, &state);\n\n    ASSERT_NEAR(test_res.real(), res.real(), eps);\n    ASSERT_NEAR(test_res.imag(), 0, eps);\n    ASSERT_NEAR(res.imag(), 0, eps);\n}\n\n/*\n\nTEST(ObservableTest, CheckParsedObservableFromOpenFermionFile) {\n    auto func = [](const std::string path,\n        const QuantumStateBase* state) -> CPPCTYPE {\n        std::ifstream ifs;\n        ifs.open(path);\n        if (!ifs) {\n            std::cerr << \"ERROR: Cannot open file\" << std::endl;\n            return -1.;\n        }\n\n        CPPCTYPE energy = 0;\n\n        std::string str;\n        while (getline(ifs, str)) {\n            // std::cout << state->get_norm() << std::endl;\n\n            std::vector<std::string> elems;\n            elems = split(str, \"()j[]+\");\n\n            chfmt(elems[3]);\n\n            CPPCTYPE coef(std::stod(elems[0]), std::stod(elems[1]));\n            // std::cout << elems[3].c_str() << std::endl;\n\n            PauliOperator mpt(elems[3].c_str(), coef.real());\n\n            // std::cout << mpt.get_coef() << \" \";\n            // std::cout << elems[3].c_str() << std::endl;\n            energy += mpt.get_expectation_value(state);\n            // mpt.get_expectation_value(state);\n        }\n        if (!ifs.eof()) {\n            std::cerr << \"ERROR: Invalid format\" << std::endl;\n            return -1.;\n        }\n        ifs.close();\n        return energy;\n    };\n\n    const double eps = 1e-14;\n    const char* filename = \"../test/cppsim/H2.txt\";\n\n    CPPCTYPE res, test_res;\n\n    Observable* observable;\n    observable = observable::create_observable_from_openfermion_file(filename);\n    ASSERT_NE(observable, (Observable*)NULL);\n    UINT qubit_count = observable->get_qubit_count();\n\n    QuantumState state(qubit_count);\n    state.set_computational_basis(0);\n\n    res = observable->get_expectation_value(&state);\n    test_res = func(filename, &state);\n\n    ASSERT_EQ(test_res, res);\n\n    state.set_Haar_random_state();\n\n    res = observable->get_expectation_value(&state);\n    test_res = func(filename, &state);\n\n    ASSERT_NEAR(test_res.real(), res.real(), eps);\n    ASSERT_NEAR(test_res.imag(), 0, eps);\n    ASSERT_NEAR(res.imag(), 0, eps);\n}\n\nTEST(ObservableTest, CheckSplitObservable) {\n    auto func = [](const std::string path,\n                    const QuantumStateBase* state) -> CPPCTYPE {\n        std::ifstream ifs;\n        CPPCTYPE coef;\n        ifs.open(path);\n        if (!ifs) {\n            std::cerr << \"ERROR: Cannot open file\" << std::endl;\n            return -1.;\n        }\n\n        CPPCTYPE energy = 0;\n\n        std::string str;\n        while (getline(ifs, str)) {\n            // std::cout << state->get_norm() << std::endl;\n\n            std::vector<std::string> elems;\n            elems = split(str, \"()j[]+\");\n\n            chfmt(elems[3]);\n\n            CPPCTYPE coef(std::stod(elems[0]), std::stod(elems[1]));\n            // std::cout << elems[3].c_str() << std::endl;\n\n            PauliOperator mpt(elems[3].c_str(), coef.real());\n\n            // std::cout << mpt.get_coef() << \" \";\n            // std::cout << elems[3].c_str() << std::endl;\n            energy += mpt.get_expectation_value(state);\n            // mpt.get_expectation_value(state);\n        }\n        if (!ifs.eof()) {\n            std::cerr << \"ERROR: Invalid format\" << std::endl;\n            return -1.;\n        }\n        ifs.close();\n        return energy;\n    };\n\n    const double eps = 1e-14;\n    const char* filename = \"../test/cppsim/H2.txt\";\n\n    CPPCTYPE diag_res, test_res, non_diag_res;\n\n    std::pair<Observable*, Observable*> observables;\n    observables = observable::create_split_observable(filename);\n    ASSERT_NE(observables.first, (Observable*)NULL);\n    ASSERT_NE(observables.second, (Observable*)NULL);\n\n    UINT qubit_count = observables.first->get_qubit_count();\n    QuantumState state(qubit_count);\n    state.set_computational_basis(0);\n\n    diag_res = observables.first->get_expectation_value(&state);\n    non_diag_res = observables.second->get_expectation_value(&state);\n    test_res = func(filename, &state);\n\n    ASSERT_NEAR(test_res.real(), (diag_res + non_diag_res).real(), eps);\n    ASSERT_NEAR(test_res.imag(), 0, eps);\n    ASSERT_NEAR(diag_res.imag(), 0, eps);\n    ASSERT_NEAR(non_diag_res.imag(), 0, eps);\n\n    state.set_Haar_random_state();\n\n    diag_res = observables.first->get_expectation_value(&state);\n    non_diag_res = observables.second->get_expectation_value(&state);\n    test_res = func(filename, &state);\n\n    ASSERT_NEAR(test_res.real(), (diag_res + non_diag_res).real(), eps);\n    ASSERT_NEAR(test_res.imag(), 0, eps);\n    ASSERT_NEAR(diag_res.imag(), 0, eps);\n    ASSERT_NEAR(non_diag_res.imag(), 0, eps);\n}\n\n*/\n\n// Kind of eigenvalue calculation method.\n// Only used to specify method in `test_eigenvalue()`.\nenum class CalculationMethod {\n    PowerMethod,\n    ArnoldiMethod,\n    LanczosMethod,\n};\n\n// Test calculating eigenvalue.\n// Actual test code calls this function with prepared observable.\n// Return an error message if failed, an empty string if passed.\nstd::string test_eigenvalue(Observable& observable, const UINT iter_count,\n    const double eps, const CalculationMethod method) {\n    auto observable_matrix = convert_observable_to_matrix(observable);\n    const auto eigenvalues = observable_matrix.eigenvalues();\n    CPPCTYPE test_ground_state_eigenvalue = eigenvalues[0];\n    for (UINT i = 0; i < eigenvalues.size(); i++) {\n        if (eigenvalues[i].real() < test_ground_state_eigenvalue.real()) {\n            test_ground_state_eigenvalue = eigenvalues[i];\n        }\n    }\n\n    const auto qubit_count = observable.get_qubit_count();\n    QuantumState state(qubit_count);\n    state.set_Haar_random_state();\n    CPPCTYPE ground_state_eigenvalue;\n    if (method == CalculationMethod::PowerMethod) {\n        ground_state_eigenvalue =\n            observable.solve_ground_state_eigenvalue_by_power_method(\n                &state, iter_count);\n    } else if (method == CalculationMethod::ArnoldiMethod) {\n        ground_state_eigenvalue =\n            observable.solve_ground_state_eigenvalue_by_arnoldi_method(\n                &state, iter_count);\n    } else if (method == CalculationMethod::LanczosMethod) {\n        ground_state_eigenvalue =\n            observable.solve_ground_state_eigenvalue_by_lanczos_method(\n                &state, iter_count);\n    }\n    std::string err_message;\n    err_message = _CHECK_NEAR(ground_state_eigenvalue.real(),\n        test_ground_state_eigenvalue.real(), eps);\n    if (err_message != \"\") return err_message;\n\n    QuantumState multiplied_state(qubit_count);\n    QuantumState work_state(qubit_count);\n    // multiplied_state = A|q>\n    observable.apply_to_state(&work_state, state, &multiplied_state);\n    // state = \u03bb|q>\n    state.multiply_coef(ground_state_eigenvalue);\n    multiplied_state.normalize(multiplied_state.get_squared_norm());\n    state.normalize(state.get_squared_norm());\n\n    for (UINT i = 0; i < state.dim; i++) {\n        err_message = _CHECK_NEAR(multiplied_state.data_cpp()[i].real(),\n            state.data_cpp()[i].real(), eps);\n        if (err_message != \"\") return err_message;\n        err_message = _CHECK_NEAR(multiplied_state.data_cpp()[i].imag(),\n            state.data_cpp()[i].imag(), eps);\n        if (err_message != \"\") return err_message;\n    }\n    return \"\";\n}\n\nTEST(ObservableTest, MinimumEigenvalueByPowerMethod) {\n    constexpr double eps = 1e-2;\n    constexpr UINT qubit_count = 4;\n    constexpr UINT test_count = 10;\n    UINT pass_count = 0;\n    Random random;\n\n    for (UINT i = 0; i < test_count; i++) {\n        const UINT operator_count =\n            random.int32() % 10 + 2;  // 2 <= operator_count <= 11\n        auto observable = Observable(qubit_count);\n        observable.add_random_operator(operator_count);\n        std::string err_message = test_eigenvalue(\n            observable, 500, eps, CalculationMethod::PowerMethod);\n        if (err_message == \"\")\n            pass_count++;\n        else\n            std::cerr << err_message;\n    }\n    ASSERT_GE(pass_count, test_count - 1);\n}\n\nTEST(ObservableTest, MinimumEigenvalueByArnoldiMethod) {\n    constexpr double eps = 1e-6;\n    constexpr UINT test_count = 10;\n    UINT pass_count = 0;\n    Random random;\n\n    for (UINT i = 0; i < test_count; i++) {\n        // 3 <= qubit_count <= 5\n        const auto qubit_count = random.int32() % 4 + 3;\n        // 2 <= operator_count <= 11\n        const auto operator_count = random.int32() % 10 + 2;\n        auto observable = Observable(qubit_count);\n        observable.add_random_operator(operator_count);\n        std::string err_message = test_eigenvalue(\n            observable, 60, eps, CalculationMethod::ArnoldiMethod);\n        if (err_message == \"\")\n            pass_count++;\n        else\n            std::cerr << err_message;\n    }\n    ASSERT_GE(pass_count, test_count - 1);\n}\n\nvoid add_identity(Observable* observable, Random random) {\n    std::vector<UINT> qil;\n    std::vector<UINT> qpl;\n    for (UINT i = 0; i < observable->get_qubit_count(); i++) {\n        qil.push_back(i);\n        qpl.push_back(0);\n    }\n    auto op = PauliOperator(qil, qpl, random.uniform());\n    observable->add_operator(&op);\n}\n\n// Test observable with identity pauli operator because calculation was unstable\n// in this situation.\nTEST(ObservableTest, MinimumEigenvalueByArnoldiMethodWithIdentity) {\n    constexpr double eps = 1e-6;\n    constexpr UINT test_count = 10;\n    UINT pass_count = 0;\n    Random random;\n\n    for (UINT i = 0; i < test_count; i++) {\n        // 3 <= qubit_count <= 5\n        const auto qubit_count = random.int32() % 4 + 3;\n        // 2 <= operator_count <= 11\n        const auto operator_count = random.int32() % 10 + 2;\n        auto observable = Observable(qubit_count);\n        observable.add_random_operator(operator_count);\n        add_identity(&observable, random);\n        std::string err_message = test_eigenvalue(\n            observable, 70, eps, CalculationMethod::ArnoldiMethod);\n        if (err_message == \"\")\n            pass_count++;\n        else\n            std::cerr << err_message;\n    }\n    ASSERT_GE(pass_count, test_count - 1);\n}\n\nTEST(ObservableTest, MinimumEigenvalueByLanczosMethod) {\n    constexpr double eps = 1e-6;\n    constexpr UINT test_count = 10;\n    UINT pass_count = 0;\n    Random random;\n\n    for (UINT i = 0; i < test_count; i++) {\n        // 3 <= qubit_count <= 6\n        const auto qubit_count = random.int32() % 4 + 3;\n        // 2 <= operator_count <= 11\n        const auto operator_count = random.int32() % 10 + 2;\n        auto observable = Observable(qubit_count);\n        observable.add_random_operator(operator_count);\n        std::string err_message = test_eigenvalue(\n            observable, 70, eps, CalculationMethod::LanczosMethod);\n        if (err_message == \"\")\n            pass_count++;\n        else\n            std::cerr << err_message;\n    }\n    ASSERT_GE(pass_count, test_count - 1);\n}\n\nTEST(ObservableTest, GetDaggerTest) {\n    constexpr double eps = 1e-2;\n    constexpr UINT qubit_count = 4;\n\n    auto observable = Observable(qubit_count);\n    observable.add_operator(1.0, \"X 0\");\n    auto dagger_observable = observable.get_dagger();\n    std::string s = dagger_observable->to_string();\n    ASSERT_TRUE(s == \"(1,-0) X 0\" || s == \"(1,0) X 0\");\n}\n\nTEST(ObservableTest, ObservableAndStateHaveDifferentQubitCountTest) {\n    auto func = [](const std::string str,\n                    const QuantumStateBase* state) -> CPPCTYPE {\n        CPPCTYPE energy = 0;\n\n        std::vector<std::string> lines = split(str, \"\\n\");\n\n        for (std::string line : lines) {\n            std::vector<std::string> elems;\n            elems = split(line, \"()j[]+\");\n            chfmt(elems[3]);\n            CPPCTYPE coef(std::stod(elems[0]), std::stod(elems[1]));\n            PauliOperator mpt(elems[3].c_str(), coef.real());\n            energy += mpt.get_expectation_value(state);\n        }\n        return energy;\n    };\n\n    const double eps = 1e-14;\n    const std::string text =\n        \"(-0.8126100000000005+0j) [] +\\n\"\n        \"(0.04532175+0j) [X0 Z1 X2] +\\n\"\n        \"(0.04532175+0j) [X0 Z1 X2 Z3] +\\n\"\n        \"(0.04532175+0j) [Y0 Z1 Y2] +\\n\"\n        \"(0.04532175+0j) [Y0 Z1 Y2 Z3] +\\n\"\n        \"(0.17120100000000002+0j) [Z0] +\\n\"\n        \"(0.17120100000000002+0j) [Z0 Z1] +\\n\"\n        \"(0.165868+0j) [Z0 Z1 Z2] +\\n\"\n        \"(0.165868+0j) [Z0 Z1 Z2 Z3] +\\n\"\n        \"(0.12054625+0j) [Z0 Z2] +\\n\"\n        \"(0.12054625+0j) [Z0 Z2 Z3] +\\n\"\n        \"(0.16862325+0j) [Z1] +\\n\"\n        \"(-0.22279649999999998+0j) [Z1 Z2 Z3] +\\n\"\n        \"(0.17434925+0j) [Z1 Z3] +\\n\"\n        \"(-0.22279649999999998+0j) [Z2]\";\n\n    CPPCTYPE res, test_res;\n\n    Observable* observable;\n    observable = observable::create_observable_from_openfermion_text(text);\n    ASSERT_NE(observable, (Observable*)NULL);\n    UINT qubit_count = observable->get_qubit_count();\n\n    QuantumState state(qubit_count + 2);  // +2 is point. diff test\n    state.set_computational_basis(0);\n\n    res = observable->get_expectation_value(&state);\n    test_res = func(text, &state);\n\n    ASSERT_NEAR(res.real(), test_res.real(), eps);\n    ASSERT_NEAR(res.imag(), test_res.imag(), eps);\n\n    state.set_Haar_random_state();\n\n    res = observable->get_expectation_value(&state);\n    test_res = func(text, &state);\n\n    ASSERT_NEAR(res.real(), test_res.real(), eps);\n    ASSERT_NEAR(0, test_res.imag(), eps);\n    ASSERT_NEAR(0, res.imag(), eps);\n}\n\nTEST(ObservableTest, ApplyIdentityToState) {\n    const double eps = 1e-14;\n\n    double coef = .5;\n    int n_qubits = 3;\n    Observable obs(n_qubits);\n    obs.add_operator(coef, \"I\");\n    QuantumState state(n_qubits);\n    QuantumState dst_state(n_qubits);\n    obs.apply_to_state(&state, &dst_state);\n    state.add_state_with_coef(-1 / coef, &dst_state);\n    ASSERT_NEAR(0., state.get_squared_norm(), eps);\n}\n", "meta": {"hexsha": "14e1e38cbea8e902ff04d5281104a9d79128b4bb", "size": 19461, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/cppsim/test_hamiltonian.cpp", "max_stars_repo_name": "forest1040/qulacs-osaka", "max_stars_repo_head_hexsha": "6630dffe40717963b9ef1caf73cad702978b51a4", "max_stars_repo_licenses": ["MIT"], "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/cppsim/test_hamiltonian.cpp", "max_issues_repo_name": "forest1040/qulacs-osaka", "max_issues_repo_head_hexsha": "6630dffe40717963b9ef1caf73cad702978b51a4", "max_issues_repo_licenses": ["MIT"], "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/cppsim/test_hamiltonian.cpp", "max_forks_repo_name": "forest1040/qulacs-osaka", "max_forks_repo_head_hexsha": "6630dffe40717963b9ef1caf73cad702978b51a4", "max_forks_repo_licenses": ["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.9041811847, "max_line_length": 80, "alphanum_fraction": 0.6026925646, "num_tokens": 5232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867825403177, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4850287103971664}}
{"text": "//==================================================================================================\n/*!\n  @file\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_ERFC_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_ERFC_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n    @ingroup group-euler\n   This fFunction object computes the complementary error function\n   \\f$\\displaystyle \\frac{2}{\\sqrt\\pi}\\int_{x}^{\\infty} e^{-t^2}\\mbox{d}t\\f$\n\n\n\n    @par Header <boost/simd/function/erfc.hpp>\n\n    @par Decorators\n\n   - std_ calls @c std::erfc\n\n    @see erf, erfcx\n\n\n    @par Example:\n\n      @snippet erfc.cpp erfc\n\n    @par Possible output:\n\n      @snippet erfc.txt erfc\n  **/\n  IEEEValue erfc(IEEEValue const& x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/erfc.hpp>\n#include <boost/simd/function/simd/erfc.hpp>\n\n#endif\n", "meta": {"hexsha": "8c3e19ddd45bf767d95b48cd0aebc61b47fe9640", "size": 1108, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/erfc.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/erfc.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/erfc.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.612244898, "max_line_length": 100, "alphanum_fraction": 0.5740072202, "num_tokens": 268, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.48502870747996}}
{"text": "#include <iostream>\n#include <array>\n#include <boost/histogram.hpp>\n#include <boost/format.hpp>\n#include <boost/progress.hpp>\n\nconstexpr long int addresses = (2 << 21);\n\nstd::array<int, addresses> visits = {0};\n\nconstexpr inline long int LCG(long int previous) {\n    constexpr long int a = 1025;\n    constexpr long int c = 3;\n    constexpr long int m = addresses;\n\n    return (a * previous + c) % m;\n}\n\nint main() {\n    long int x = 1;\n\n    boost::progress_display show_progress(2 * addresses);\n    for (int i = 0; i < addresses; i++) {\n        x = LCG(x);\n        visits.at(x)++;\n        ++show_progress;\n//        std::cout << std::hex << x << std::endl;\n    }\n\n    // Histogram\n    auto h = boost::histogram::make_histogram(\n            boost::histogram::axis::variable<>({0, 1, 2, 3, 4, 9999999})\n    );\n\n    for (auto&& addressVisits : visits) {\n        h(addressVisits);\n        ++show_progress;\n    }\n\n    // iterate over bins\n    for (auto&& bin : indexed(h)) {\n        std::cout << boost::format(\"bin %i [ %.1f, %.1f ): %i\\n\")\n                     % bin.index() % bin.bin().lower() % bin.bin().upper() % *bin;\n    }\n}", "meta": {"hexsha": "1de62f850fb1b46fe3e12585c1d86b270c46aac8", "size": 1126, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Interface/tests/LCG.cpp", "max_stars_repo_name": "AcubeSAT/rtb-software", "max_stars_repo_head_hexsha": "906425dea139d454bdee731a62a47d9d8602f744", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Interface/tests/LCG.cpp", "max_issues_repo_name": "AcubeSAT/rtb-software", "max_issues_repo_head_hexsha": "906425dea139d454bdee731a62a47d9d8602f744", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Interface/tests/LCG.cpp", "max_forks_repo_name": "AcubeSAT/rtb-software", "max_forks_repo_head_hexsha": "906425dea139d454bdee731a62a47d9d8602f744", "max_forks_repo_licenses": ["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.0222222222, "max_line_length": 82, "alphanum_fraction": 0.5559502664, "num_tokens": 316, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.48502870747995985}}
{"text": "#include \"mwtrans.hpp\"\n\n#include <Eigen/Dense>\n#include <algorithm>\n#include <boost/math/quadrature/gauss_kronrod.hpp>\n#include <boost/math/special_functions/bessel.hpp>\n#include <cmath>\n#include <fmt/format.h>\n#include <iostream>\n#include <limits>\n\nusing namespace Eigen;\nusing namespace boost::math::quadrature;\nusing boost::math::cyl_bessel_j_zero;\nusing std::abs;\n\nMWtransInt::MWtransInt(double lb, double v, double abserr, double referr,\n                       int max_depth)\n    : max_depth_(max_depth), zeros_(nzero_), lb_(lb), v_(v), abserr_(abserr),\n      referr_(referr) {\n  int nz = 0;\n  int i = 0;\n  while (nz < nzero_) {\n    double r = cyl_bessel_j_zero(v_, ++i);\n    if (r > lb_) {\n      zeros_(nz) = r;\n      ++nz;\n    }\n  }\n  ub_ = zeros_(0) - lb_;\n}\n\ndouble MWtransInt::MWtransInt::perform(std::function<double(double)> functor) {\n  // int_lb^z0 functor\n  double error;\n  double int1 = gauss_kronrod<double, 15>::integrate(\n      functor, lb_, zeros_(0), max_depth_, referr_, &error);\n\n  // int_z0^\\infty functor\n  ArrayXXd aM = ArrayXXd::Zero(niter_, niter_);\n  ArrayXXd aN = ArrayXXd::Zero(niter_, niter_);\n  ArrayXd aW = ArrayXd::Zero(niter_);\n  ArrayXd x = ArrayXd::Zero(niter_);\n\n  aW(0) = 1.0;\n  aW(1) = 1.0;\n\n  int i0 = 0;\n  double left = zeros_(i0++);\n  double right = zeros_(i0++);\n\n  double fxs = gauss_kronrod<double, 15>::integrate(\n      functor, left, right, max_depth_, referr_, &error);\n  left = right;\n  right = zeros_(i0++);\n  x(0) = right;\n\n  int neval = 1;\n  int count = 0;\n  double diff = std::numeric_limits<double>::max();\n  double errorbound = 0.0;\n\n  while (count < niter_ - 3 && diff > errorbound) {\n    double phixs = gauss_kronrod<double, 15>::integrate(\n        functor, left, right, max_depth_, referr_, &error);\n    if (phixs == 0 || abs(phixs) < 1.0e-100) {\n      diff = 0.0;\n      break;\n    }\n    left = right;\n    right = zeros_(i0++);\n    x(count + 1) = right;\n    ++neval;\n\n    aM(count, 0) = fxs / phixs;\n    aN(count, 0) = 1.0 / phixs;\n    fxs += phixs;\n\n    if (count == 1) {\n      double denom = 1.0 / (1.0 / x(0) - 1.0 / x(1));\n      aM(0, 0) = (aM(0, 0) - aM(1, 0)) * denom;\n      aN(0, 0) = (aN(0, 0) - aN(1, 0)) * denom;\n      denom = 1.0 / (1.0 / x(0) - 1.0 / x(2));\n      aM(0, 1) = (aM(0, 0) - aM(1, 0)) * denom;\n      aN(0, 1) = (aN(0, 0) - aN(1, 0)) * denom;\n    } else if (count > 1) {\n      for (int i = 1; i <= count; ++i) {\n        double denom = 1.0 / (1.0 / x(count - i) - 1.0 / x(count + 1));\n        aM(count - i, i) =\n            (aM(count - i, i - 1) - aM(count + 1 - i, i - 1)) * denom;\n        aN(count - i, i) =\n            (aN(count - i, i - 1) - aN(count + 1 - i, i - 1)) * denom;\n      }\n    }\n    aW(count) = aM(0, count) / aN(0, count);\n    errorbound = std::max(abserr_, referr_ * abs(aW(count)));\n\n    if (count > 1) {\n      diff = std::max(abs(aW(count) - aW(count - 1)),\n                      abs(aW(count) - aW(count - 2)));\n    }\n    if (std::isnan(diff)) {\n      throw \"Warning: Divergent partial sums for mW tranformation.\";\n    }\n    count++;\n  }\n  if ((count == niter_ - 3) && (diff > errorbound)) {\n    throw \"Warning: Possible non-convergence of mW transformation\";\n  }\n\n  double result;\n  if (count > 0) {\n    result = aW(count - 1);\n  } else {\n    result = aW(count);\n    if (count == 0)\n      result = 0;\n  }\n\n  return result + int1;\n}", "meta": {"hexsha": "1b482538a544628e500c165f68b60164ec57a017", "size": 3335, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/mwtrans.cc", "max_stars_repo_name": "pan3rock/mWOI", "max_stars_repo_head_hexsha": "47f544cd29020616d2dfb4ce01e09da27ccf84c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/mwtrans.cc", "max_issues_repo_name": "pan3rock/mWOI", "max_issues_repo_head_hexsha": "47f544cd29020616d2dfb4ce01e09da27ccf84c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mwtrans.cc", "max_forks_repo_name": "pan3rock/mWOI", "max_forks_repo_head_hexsha": "47f544cd29020616d2dfb4ce01e09da27ccf84c0", "max_forks_repo_licenses": ["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.5619834711, "max_line_length": 79, "alphanum_fraction": 0.5538230885, "num_tokens": 1204, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867681382279, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.4850287016455469}}
{"text": "#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <sys/time.h>\n#include <stdlib.h>\n#include <math.h>\n#include <inttypes.h>\n#include <string.h>\n#include <adept_source.h>\n#include <adept.h>\n#include <adept_arrays.h>\nusing adept::adouble;\nusing adept::aVector;\n\ntemplate<typename Return, typename... T>\nReturn __enzyme_autodiff(T...);\nextern \"C\" {\n  extern int enzyme_dup;\n  extern int enzyme_const;\n  extern int enzyme_dupnoneed;\n}\n\nfloat tdiff(struct timeval *start, struct timeval *end) {\n  return (end->tv_sec-start->tv_sec) + 1e-6*(end->tv_usec-start->tv_usec);\n}\n\n#define BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n#define BOOST_NO_EXCEPTIONS\n#include <iostream>\n#include <boost/array.hpp>\n\n#include <boost/numeric/odeint.hpp>\n\n#include <boost/throw_exception.hpp>\nvoid boost::throw_exception(std::exception const & e){\n    //do nothing\n}\n\nusing namespace std;\nusing namespace boost::numeric::odeint;\n\n#define N 32\n#define xmin 0.\n#define xmax 1.\n#define ymin 0.\n#define ymax 1.\n\n#include <assert.h>\n#define RANGE(min, max, i, N) ((max-min)/(N-1)*i + min)\n#define GETnb(x, i, j) (x)[N*i+j]\n#define GET(x, i, j) GETnb(x, i, j)\n//#define GET(x, i, j) ({ assert(i >=0); assert( j>=0); assert(j<N); assert(j<N); GETnb(x, i, j); })\n\ntemplate <typename T>\nT brusselator_f(T x, T y, T t) {\n  bool eq1 = ((x-0.3)*(x-0.3) + (y-0.6)*(y-0.6)) <= 0.1*0.1;\n  bool eq2 = t >= 1.1;\n  if (eq1 && eq2) {\n    return T(5);\n  } else {\n    return T(0);\n  }\n}\n\nvoid init_brusselator(double* __restrict u, double* __restrict v) {\n  for(int i=0; i<N; i++) {\n    for(int j=0; j<N; j++) {\n\n      double x = RANGE(xmin, xmax, i, N);\n      double y = RANGE(ymin, ymax, j, N);\n\n      GETnb(u, i, j) = 22*(y*(1-y))*sqrt(y*(1-y));\n      GETnb(v, i, j) = 27*(x*(1-x))*sqrt(x*(1-x));\n    }\n  }\n}\n\n__attribute__((noinline))\nvoid brusselator_2d_loop(double* __restrict du, double* __restrict dv, const double* __restrict u, const double* __restrict v, const double* __restrict p, double t) {\n  double A = p[0];\n  double B = p[1];\n  double alpha = p[2];\n  double dx = (double)1/(N-1);\n\n  alpha = alpha/(dx*dx);\n\n  for(int i=0; i<N; i++) {\n    for(int j=0; j<N; j++) {\n\n      double x = RANGE(xmin, xmax, i, N);\n      double y = RANGE(ymin, ymax, j, N);\n\n      unsigned ip1 = (i == N-1) ? i : (i+1);\n      unsigned im1 = (i == 0) ? i : (i-1);\n\n      unsigned jp1 = (j == N-1) ? j : (j+1);\n      unsigned jm1 = (j == 0) ? j : (j-1);\n\n      double u2v = GET(u, i, j) * GET(u, i, j) * GET(v, i, j);\n\n      GETnb(du, i, j) = alpha*( GET(u, im1, j) + GET(u, ip1, j) + GET(u, i, jp1) + GET(u, i, jm1) - 4 * GET(u, i, j))\n                      + B + u2v - (A + 1)*GET(u, i, j) + brusselator_f(x, y, t);\n\n      GETnb(dv, i, j) = alpha*( GET(v, im1, j) + GET(v, ip1, j) + GET(v, i, jp1) + GET(v, i, jm1) - 4 * GET(v, i, j))\n                      + A * GET(u, i, j) - u2v;\n    }\n  }\n}\n\ntypedef boost::array< double , 2 * N * N > state_type;\n\nvoid lorenz( const state_type &x , state_type &dxdt , double t )\n{\n    // Extract the parameters\n  double p[3] = { /*A*/ 3.4, /*B*/ 1, /*alpha*/10. };\n  brusselator_2d_loop(dxdt.c_array(), dxdt.c_array() + N * N, x.data(), x.data() + N * N, p, t);\n}\n\n// init_brusselator(x.c_array(), x.c_array() + N*N)\n\ndouble foobar(const double* p, const state_type x, const state_type adjoint, double t) {\n    double dp[3] = { 0. };\n\n    state_type dx = { 0. };\n\n    state_type dadjoint_inp = adjoint;\n\n    state_type dxdu;\n\n    __enzyme_autodiff<void>(brusselator_2d_loop,\n//                            enzyme_dup, dxdu.c_array(), dadjoint_inp.c_array(),\n//                            enzyme_dup, dxdu.c_array() + N * N, dadjoint_inp.c_array() + N * N,\n                            enzyme_dupnoneed, nullptr, dadjoint_inp.data(),\n                            enzyme_dupnoneed, nullptr, dadjoint_inp.data() + N * N,\n                            enzyme_dup, x.data(), dx.data(),\n                            enzyme_dup, x.data() + N * N, dx.data() + N * N,\n                            enzyme_dup, p, dp,\n                            enzyme_const, t);\n\n    return dx[0];\n}\n\n#undef GETnb\n#define GETnb(x, i, j) (x)(N*i+j)\n\nvoid abrusselator_2d_loop(aVector& du, aVector& dv, aVector& u, aVector& v, aVector& p, double t) {\n  adouble A = p(0);\n  adouble B = p(1);\n  adouble alpha = p(2);\n  adouble dx = (double)1/(N-1);\n\n  alpha = alpha/(dx*dx);\n\n  for(int i=0; i<N; i++) {\n    for(int j=0; j<N; j++) {\n\n      adouble x = RANGE(xmin, xmax, i, N);\n      adouble y = RANGE(ymin, ymax, j, N);\n\n      unsigned ip1 = (i == N-1) ? i : (i+1);\n      unsigned im1 = (i == 0) ? i : (i-1);\n\n      unsigned jp1 = (j == N-1) ? j : (j+1);\n      unsigned jm1 = (j == 0) ? j : (j-1);\n\n      adouble u2v = GET(u, i, j) * GET(u, i, j) * GET(v, i, j);\n\n      GETnb(du, i, j) = alpha*( GET(u, im1, j) + GET(u, ip1, j) + GET(u, i, jp1) + GET(u, i, jm1) - 4 * GET(u, i, j))\n                      + B + u2v - (A + 1)*GET(u, i, j) + brusselator_f<adouble>(x, y, t);\n\n      GETnb(dv, i, j) = alpha*( GET(v, im1, j) + GET(v, ip1, j) + GET(v, i, jp1) + GET(v, i, jm1) - 4 * GET(v, i, j))\n                      + A * GET(u, i, j) - u2v;\n    }\n  }\n}\n\ndouble afoobar(const double* p_in, const state_type x, const state_type adjoint, double t) {\n    adept::Stack stack;\n\n    aVector p(3);\n    for(unsigned i=0; i<3; i++) p(i) = p_in[i];\n    aVector ax(N*N);\n    aVector ay(N*N);\n    for(unsigned i=0; i<N*N; i++) {\n      ax(i) = x[i];\n      ay(i) = x[i+N*N];\n    }\n\n    aVector dxdu(N*N);\n    aVector dydu(N*N);\n\n    stack.new_recording();\n\n    abrusselator_2d_loop(dxdu, dydu, ax, ay, p, t);\n\n    for(unsigned i=0; i<N*N; i++) {\n      dxdu(i).set_gradient(adjoint[i]);\n      dydu(i).set_gradient(adjoint[i+N*N]);\n    }\n    stack.compute_adjoint();\n\n    return ax(0).get_gradient();\n}\n\n\n//! Tapenade\nextern \"C\" {\n  /*        Generated by TAPENADE     (INRIA, Ecuador team)\n    Tapenade 3.15 (master) -  8 Jan 2020 10:48\n*/\n#include <adBuffer.h>\n\n/*\n  Differentiation of get in reverse (adjoint) mode (with options i4 dr8 r4):\n   gradient     of useful results: *x get\n   with respect to varying inputs: *x\n   Plus diff mem management of: x:in\n*/\nvoid get_b(const double *x, double *xb, unsigned int i, unsigned int j, double getb)\n{\n    double get;\n    xb[N*i + j] = xb[N*i + j] + getb;\n}\n\ndouble get_nodiff(const double *x, unsigned int i, unsigned int j) {\n    return x[N*i + j];\n}\n\ndouble brusselator_f_nodiff(double x, double y, double t) {\n    if ((x-0.3)*(x-0.3) + (y-0.6)*(y-0.6) <= 0.1*0.1 && t >= 1.1)\n        return 5.0;\n    else\n        return 0.0;\n}\n\n#if 1\nvoid brusselator_2d_loop_b(double *du, double *dub, double *dv, double *dvb,\n        const double *u, double *ub, const double *v, double *vb, const double *p, double *pb,\n        double t) {\n    double A = p[0];\n    double Ab = 0.0;\n    double B = p[1];\n    double Bb = 0.0;\n    double alpha = p[2];\n    double alphab = 0.0;\n    double dx = (double)1/(N-1);\n    alpha = alpha/(dx*dx);\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j) {\n            double x = (xmax-xmin)/(N-1)*i + xmin;\n            double y = (ymax-ymin)/(N-1)*j + ymin;\n            unsigned int ip1 = (i == N - 1 ? i : i + 1);\n            unsigned int im1 = (i == 0 ? i : i - 1);\n            unsigned int jp1 = (j == N - 1 ? j : j + 1);\n            unsigned int jm1 = (j == 0 ? j : j - 1);\n            double u2v = u[N*i+j]*u[N*i+j]*v[N*i+j];\n            double result1;\n            pushInteger4(jm1);\n            pushInteger4(jp1);\n            pushInteger4(im1);\n            pushInteger4(ip1);\n        }\n    *ub = 0.0;\n    *vb = 0.0;\n    alphab = 0.0;\n    Ab = 0.0;\n    Bb = 0.0;\n    for (int i = N-1; i > -1; --i)\n        for (int j = N-1; j > -1; --j) {\n            double x;\n            double y;\n            unsigned int ip1;\n            unsigned int im1;\n            unsigned int jp1;\n            unsigned int jm1;\n            double u2v;\n            double u2vb = 0.0;\n            double result1;\n            double temp;\n            double tempb;\n            popInteger4((int*)&ip1);\n            popInteger4((int*)&im1);\n            popInteger4((int*)&jp1);\n            popInteger4((int*)&jm1);\n            temp = u[N*i + j];\n            alphab = alphab + (v[N*im1+j]+v[N*ip1+j]+v[N*i+jp1]+v[N*i+jm1]\n                -4*v[N*i+j])*dvb[N*i+j] + (u[N*im1+j]+u[N*ip1+j]+u[N*i+\n                jp1]+u[N*i+jm1]-4*u[N*i+j])*dub[N*i+j];\n            tempb = alpha*dvb[N*i+j];\n            Ab = Ab + u[N*i+j]*dvb[N*i+j] - u[N*i+j]*dub[N*i+j];\n            ub[N*i + j] = ub[N*i + j] + A*dvb[N*i+j] - (A+1)*dub[N*i+j];\n            u2vb = dub[N*i + j] - dvb[N*i + j];\n            dvb[N*i + j] = 0.0;\n            vb[N*im1 + j] = vb[N*im1 + j] + tempb;\n            vb[N*ip1 + j] = vb[N*ip1 + j] + tempb;\n            vb[N*i + jp1] = vb[N*i + jp1] + tempb;\n            vb[N*i + jm1] = vb[N*i + jm1] + tempb;\n            vb[N*i + j] = vb[N*i + j] + temp*temp*u2vb - 4*tempb;\n            tempb = alpha*dub[N*i+j];\n            Bb = Bb + dub[N*i + j];\n            dub[N*i + j] = 0.0;\n            ub[N*im1 + j] = ub[N*im1 + j] + tempb;\n            ub[N*ip1 + j] = ub[N*ip1 + j] + tempb;\n            ub[N*i + jp1] = ub[N*i + jp1] + tempb;\n            ub[N*i + jm1] = ub[N*i + jm1] + tempb;\n            ub[N*i + j] = ub[N*i + j] + 2*temp*v[N*i+j]*u2vb - 4*tempb;\n        }\n    alphab = alphab/(dx*dx);\n    pb[2] = pb[2] + alphab;\n    pb[1] = pb[1] + Bb;\n    pb[0] = pb[0] + Ab;\n\n}\n#else\n/*\n  Differentiation of brusselator_2d_loop in reverse (adjoint) mode (with options i4 dr8 r4):\n   gradient     of useful results: *du *dv\n   with respect to varying inputs: *p *u *du *v *dv\n   RW status of diff variables: *p:out *u:out *du:in-out *v:out\n                *dv:in-out\n   Plus diff mem management of: p:in u:in du:in v:in dv:in\n*/\nvoid brusselator_2d_loop_b(double *du, double *dub, double *dv, double *dvb,\n        const double *u, double *ub, const double *v, double *vb, const double *p, double *pb,\n        double t) {\n    double A = p[0];\n    double Ab = 0.0;\n    double B = p[1];\n    double Bb = 0.0;\n    double alpha = p[2];\n    double alphab = 0.0;\n    double dx = (double)1/(N-1);\n    alpha = alpha/(dx*dx);\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j) {\n            double x = (xmax-xmin)/(N-1)*i + xmin;\n            double y = (ymax-ymin)/(N-1)*j + ymin;\n            unsigned int ip1 = (i == N - 1 ? i : i + 1);\n            unsigned int im1 = (i == 0 ? i : i - 1);\n            unsigned int jp1 = (j == N - 1 ? j : j + 1);\n            unsigned int jm1 = (j == 0 ? j : j - 1);\n            double u2v;\n            double result1;\n            double result2;\n            double result3;\n            double result4;\n            double result5;\n            double result6;\n            double result7;\n            result1 = get_nodiff(u, i, j);\n            result2 = get_nodiff(u, i, j);\n            result3 = get_nodiff(v, i, j);\n            pushReal8(result1);\n            result1 = get_nodiff(u, im1, j);\n            pushReal8(result2);\n            result2 = get_nodiff(u, ip1, j);\n            pushReal8(result3);\n            result3 = get_nodiff(u, i, jp1);\n            result4 = get_nodiff(u, i, jm1);\n            result5 = get_nodiff(u, i, j);\n            result6 = get_nodiff(u, i, j);\n            pushReal8(result1);\n            result1 = get_nodiff(v, im1, j);\n            pushReal8(result2);\n            result2 = get_nodiff(v, ip1, j);\n            pushReal8(result3);\n            result3 = get_nodiff(v, i, jp1);\n            pushReal8(result4);\n            result4 = get_nodiff(v, i, jm1);\n            pushReal8(result5);\n            result5 = get_nodiff(v, i, j);\n            pushReal8(result6);\n            result6 = get_nodiff(u, i, j);\n            pushInteger4(jm1);\n            pushInteger4(jp1);\n            pushReal8(result6);\n            pushReal8(result5);\n            pushReal8(result4);\n            pushReal8(result3);\n            pushReal8(result2);\n            pushReal8(result1);\n            pushInteger4(im1);\n            pushInteger4(ip1);\n        }\n    *ub = 0.0;\n    *vb = 0.0;\n    alphab = 0.0;\n    Ab = 0.0;\n    Bb = 0.0;\n    for (int i = N-1; i > -1; --i)\n        for (int j = N-1; j > -1; --j) {\n            double x;\n            double y;\n            unsigned int ip1;\n            unsigned int im1;\n            unsigned int jp1;\n            unsigned int jm1;\n            double u2v;\n            double u2vb;\n            double result1;\n            double result1b;\n            double result2;\n            double result2b;\n            double result3;\n            double result3b;\n            double result4;\n            double result4b;\n            double result5;\n            double result5b;\n            double result6;\n            double result6b;\n            double result7;\n            double tempb;\n            popInteger4((int*)&ip1);\n            popInteger4((int*)&im1);\n            popReal8(&result1);\n            popReal8(&result2);\n            popReal8(&result3);\n            popReal8(&result4);\n            popReal8(&result5);\n            popReal8(&result6);\n            popInteger4((int*)&jp1);\n            popInteger4((int*)&jm1);\n            alphab = alphab + (result1+result2+result3+result4-4*result5)*dvb[\n                N*i+j];\n            tempb = alpha*dvb[N*i+j];\n            Ab = Ab + result6*dvb[N*i+j];\n            result6b = A*dvb[N*i+j];\n            u2vb = dub[N*i + j] - dvb[N*i + j];\n            dvb[N*i + j] = 0.0;\n            result1b = tempb;\n            result2b = tempb;\n            result3b = tempb;\n            result4b = tempb;\n            result5b = -(4*tempb);\n            popReal8(&result6);\n            get_b(u, ub, i, j, result6b);\n            popReal8(&result5);\n            get_b(v, vb, i, j, result5b);\n            popReal8(&result4);\n            get_b(v, vb, i, jm1, result4b);\n            popReal8(&result3);\n            get_b(v, vb, i, jp1, result3b);\n            popReal8(&result2);\n            get_b(v, vb, ip1, j, result2b);\n            popReal8(&result1);\n            get_b(v, vb, im1, j, result1b);\n            alphab = alphab + (result1+result2+result3+result4-4*result5)*dub[\n                N*i+j];\n            tempb = alpha*dub[N*i+j];\n            Bb = Bb + dub[N*i + j];\n            Ab = Ab - result6*dub[N*i+j];\n            result6b = -((A+1)*dub[N*i+j]);\n            dub[N*i + j] = 0.0;\n            result1b = tempb;\n            result2b = tempb;\n            result3b = tempb;\n            result4b = tempb;\n            result5b = -(4*tempb);\n            get_b(u, ub, i, j, result6b);\n            get_b(u, ub, i, j, result5b);\n            get_b(u, ub, i, jm1, result4b);\n            popReal8(&result3);\n            get_b(u, ub, i, jp1, result3b);\n            popReal8(&result2);\n            get_b(u, ub, ip1, j, result2b);\n            popReal8(&result1);\n            get_b(u, ub, im1, j, result1b);\n            result1b = result2*result3*u2vb;\n            result2b = result1*result3*u2vb;\n            result3b = result1*result2*u2vb;\n            get_b(v, vb, i, j, result3b);\n            get_b(u, ub, i, j, result2b);\n            get_b(u, ub, i, j, result1b);\n        }\n    alphab = alphab/(dx*dx);\n    pb[2] = pb[2] + alphab;\n    pb[1] = pb[1] + Bb;\n    pb[0] = pb[0] + Ab;\n}\n#endif\n}\n\ndouble tfoobar(const double* p, const state_type x, const state_type adjoint, double t) {\n    double dp[3] = { 0. };\n\n    state_type dx = { 0. };\n\n    state_type dadjoint_inp = adjoint;\n\n    state_type dxdu;\n\n    brusselator_2d_loop_b(nullptr, dadjoint_inp.data(),\n                          nullptr, dadjoint_inp.data() + N * N,\n                          x.data(), dx.data(),\n                          x.data() + N * N, dx.data() + N * N,\n                          p, dp,\n                          t);\n\n    return dx[0];\n}\n\n//! Main\nint main(int argc, char** argv) {\n  const double p[3] = { /*A*/ 3.4, /*B*/ 1, /*alpha*/10. };\n\n  state_type x;\n  init_brusselator(x.data(), x.data() + N * N);\n\n  state_type adjoint;\n  init_brusselator(adjoint.data(), adjoint.data() + N * N);\n\n  double t = 2.1;\n\n  {\n  struct timeval start, end;\n  gettimeofday(&start, NULL);\n\n  double res;\n  for(int i=0; i<10000; i++)\n  res = afoobar(p, x, adjoint, t);\n\n  gettimeofday(&end, NULL);\n  printf(\"Adept combined %0.6f res=%f\\n\", tdiff(&start, &end), res);\n  }\n\n  {\n  struct timeval start, end;\n  gettimeofday(&start, NULL);\n\n  double res;\n  for(int i=0; i<10000; i++)\n  res = tfoobar(p, x, adjoint, t);\n\n  gettimeofday(&end, NULL);\n  printf(\"Tapenade combined %0.6f res=%f\\n\", tdiff(&start, &end), res);\n  }\n\n  {\n  struct timeval start, end;\n  gettimeofday(&start, NULL);\n\n  double res;\n  for(int i=0; i<10000; i++)\n  res = foobar(p, x, adjoint, t);\n\n  gettimeofday(&end, NULL);\n  printf(\"Enzyme combined %0.6f res=%f\\n\", tdiff(&start, &end), res);\n  }\n  //printf(\"res=%f\\n\", foobar(1000));\n}\n\n\n#if 0\n\ntypedef boost::array< double , 6 > state_type;\n\nvoid lorenz( const state_type &x , state_type &dxdt , double t )\n{\n    // Extract the parameters\n    double k1 = x[3];\n    double k2 = x[4];\n    double k3 = x[5];\n\n    dxdt[0] = -k1 * x[0] + k3 * x[1] * x[2];\n    dxdt[1] = k1 * x[0] - k2 * x[1] * x[1] - k3 * x[1] * x[2];\n    dxdt[2] = k2 * x[1] * x[1];\n\n    // Don't change the parameters p\n    dxdt[3] = 0;\n    dxdt[4] = 0;\n    dxdt[5] = 0;\n}\n\ndouble foobar(double* p, uint64_t iters) {\n    state_type x = { 1.0, 0, 0, p[0], p[1], p[2] }; // initial conditions\n    double t = 1e5;\n    typedef controlled_runge_kutta< runge_kutta_dopri5< state_type , typename state_type::value_type , state_type , double > > stepper_type;\n    //typedef euler< state_type , typename state_type::value_type , state_type , double > stepper_type;\n    integrate_const( stepper_type(), lorenz , x , 0.0 , t, t/iters );\n\n    return x[0];\n}\n\ntypedef boost::array< adouble , 6 > astate_type;\n\nvoid alorenz( const astate_type &x , astate_type &dxdt , adouble t )\n{\n    // Extract the parameters\n    adouble k1 = x[3];\n    adouble k2 = x[4];\n    adouble k3 = x[5];\n\n    dxdt[0] = -k1 * x[0] + k3 * x[1] * x[2];\n    dxdt[1] = k1 * x[0] - k2 * x[1] * x[1] - k3 * x[1] * x[2];\n    dxdt[2] = k2 * x[1] * x[1];\n\n    // Don't change the parameters p\n    dxdt[3] = 0;\n    dxdt[4] = 0;\n    dxdt[5] = 0;\n}\n\nadouble afoobar(adouble* p, uint64_t iters) {\n    astate_type x = { 1.0, 0, 0, p[0], p[1], p[2] }; // initial conditions\n    double t = 1e5;\n    typedef controlled_runge_kutta< runge_kutta_dopri5< astate_type , typename astate_type::value_type , astate_type , adouble > > stepper_type;\n    //typedef euler< astate_type , typename astate_type::value_type , astate_type , adouble > stepper_type;\n    integrate_const( stepper_type(), alorenz , x , 0.0 , t, t/iters );\n\n    return x[0];\n}\n\nstatic\ndouble afoobar_and_gradient(double* p_in, double* dp_out, uint64_t iters) {\n    adept::Stack stack;\n    adouble x[3] = { p_in[0], p_in[1], p_in[2] };\n    stack.new_recording();\n    adouble y = afoobar(x, iters);\n    y.set_gradient(1.0);\n    stack.compute_adjoint();\n    for(int i=0; i<3; i++)\n      dp_out[i] = x[i].get_gradient();\n    return y.value();\n}\n\nstatic void adept_sincos(uint64_t iters) {\n  {\n  struct timeval start, end;\n  gettimeofday(&start, NULL);\n\n  double p[3] = { 0.04,3e7,1e4 };\n  double res = foobar(p, iters);\n\n  gettimeofday(&end, NULL);\n  printf(\"Adept real %0.6f res=%f\\n\", tdiff(&start, &end), res);\n  }\n\n  {\n  struct timeval start, end;\n  gettimeofday(&start, NULL);\n\n  adept::Stack stack;\n  adouble p[3] = { 0.04,3e7,1e4 };\n // stack.new_recording();\n  adouble resa = afoobar(p, iters);\n  double res = resa.value();\n\n  gettimeofday(&end, NULL);\n  printf(\"Adept forward %0.6f res=%f\\n\", tdiff(&start, &end), res);\n  }\n\n  {\n  struct timeval start, end;\n  gettimeofday(&start, NULL);\n\n  double p[3] = { 0.04,3e7,1e4 };\n  double dp[3] = { 0 };\n  afoobar_and_gradient(p, dp, iters);\n\n  gettimeofday(&end, NULL);\n  printf(\"Adept combined %0.6f res'=%f\\n\", tdiff(&start, &end), dp[0]);\n  }\n}\n\nstatic void enzyme_sincos(double inp, uint64_t iters) {\n\n  {\n  struct timeval start, end;\n  gettimeofday(&start, NULL);\n\n  double p[3] = { 0.04,3e7,1e4 };\n  double res = foobar(p, iters);\n\n  gettimeofday(&end, NULL);\n  printf(\"Enzyme real %0.6f res=%f\\n\", tdiff(&start, &end), res);\n  }\n\n  {\n  struct timeval start, end;\n  gettimeofday(&start, NULL);\n\n  double p[3] = { 0.04,3e7,1e4 };\n  double res = foobar(p, iters);\n\n  gettimeofday(&end, NULL);\n  printf(\"Enzyme forward %0.6f res=%f\\n\", tdiff(&start, &end), res);\n  }\n\n  {\n  struct timeval start, end;\n  gettimeofday(&start, NULL);\n\n  double p[3] = { 0.04,3e7,1e4 };\n  double dp[3] = { 0 };\n  __enzyme_autodiff<void>(foobar, p, dp, iters);\n\n  gettimeofday(&end, NULL);\n  printf(\"Enzyme combined %0.6f res'=%f\\n\", tdiff(&start, &end), dp[0]);\n  }\n}\n\nint main(int argc, char** argv) {\n\n  int max_iters = atoi(argv[1]) ;\n  double inp = 2.1;\n\n  //for(int iters=max_iters/20; iters<=max_iters; iters+=max_iters/20) {\n  auto iters = max_iters;\n    printf(\"iters=%d\\n\", iters);\n    adept_sincos(inp, iters);\n    enzyme_sincos(inp, iters);\n  //}\n}\n#endif\n", "meta": {"hexsha": "7c7113df964157f90dd8c0ed7910557fad95593d", "size": 20961, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "enzyme/benchmarks/ode-real/ode.cpp", "max_stars_repo_name": "anandijain/Enzyme", "max_stars_repo_head_hexsha": "fcaeb498a7fcb941be02ca407444fbb81e31c02e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 674.0, "max_stars_repo_stars_event_min_datetime": "2020-10-05T17:55:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T11:18:11.000Z", "max_issues_repo_path": "enzyme/benchmarks/ode-real/ode.cpp", "max_issues_repo_name": "anandijain/Enzyme", "max_issues_repo_head_hexsha": "fcaeb498a7fcb941be02ca407444fbb81e31c02e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 119.0, "max_issues_repo_issues_event_min_datetime": "2020-10-07T00:47:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-06T16:46:58.000Z", "max_forks_repo_path": "enzyme/benchmarks/ode-real/ode.cpp", "max_forks_repo_name": "anandijain/Enzyme", "max_forks_repo_head_hexsha": "fcaeb498a7fcb941be02ca407444fbb81e31c02e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 55.0, "max_forks_repo_forks_event_min_datetime": "2020-10-10T14:45:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-30T05:51:07.000Z", "avg_line_length": 29.2751396648, "max_line_length": 166, "alphanum_fraction": 0.5193454511, "num_tokens": 7121, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.82893881677331, "lm_q2_score": 0.5851011542032313, "lm_q1q2_score": 0.4850130584579246}}
{"text": "#pragma once\n#include \"world.hpp\"\n#include <Eigen/Core>\n#include <cstdint>\n\nusing RenderBuffer = Eigen::Matrix<uint8_t, world_size, world_size>;\n\nRenderBuffer render_world(const World &world, int channel) {\n  RenderBuffer result;\n  for (int y=0; y<world_size; y++) {\n    for (int x=0; x<world_size; x++) {\n      result(y, x) = 0;\n      auto blend = [&](Eigen::Vector3i rgb, float alpha=1.0) {\n        float value = alpha * rgb[channel] + (1.0 - alpha) * result(y, x);\n        result(y, x) = std::round(value);\n      };\n      switch (world.pixels_[y*world_size+x].block) {\n        case Food: blend({200, 80, 80}); break;\n        case Wall: blend({255, 255, 255}); break;\n      }\n      if (world.pixels_[y*world_size+x].pheromone_1) {\n        blend({0, 128, 0}, 0.4);\n      }\n    }\n  }\n  for (auto &a: world.agents_) {\n    result(a.y, a.x) = 0;\n    if (channel == 1) result(a.y, a.x) = 255;\n  }\n  return result;\n}\n", "meta": {"hexsha": "f27f0028261d44f7d9331f24fa3550af1b5f9623", "size": 912, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "world/render.hpp", "max_stars_repo_name": "martinxyz/pixelcrawl", "max_stars_repo_head_hexsha": "e1218be20ec2fb65ab577b366f54546b59db5854", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-05-24T13:31:43.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-26T08:50:21.000Z", "max_issues_repo_path": "world/render.hpp", "max_issues_repo_name": "martinxyz/pixelcrawl", "max_issues_repo_head_hexsha": "e1218be20ec2fb65ab577b366f54546b59db5854", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-10-31T02:21:45.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-31T02:21:46.000Z", "max_forks_repo_path": "world/render.hpp", "max_forks_repo_name": "martinxyz/pixelcrawl", "max_forks_repo_head_hexsha": "e1218be20ec2fb65ab577b366f54546b59db5854", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-05-24T13:32:10.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-24T13:32:10.000Z", "avg_line_length": 28.5, "max_line_length": 74, "alphanum_fraction": 0.576754386, "num_tokens": 293, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.48501304856749794}}
{"text": "/**\n * @file ann_dist_test.cpp\n * @author Atharva Khandait\n *\n * Tests the ann distributions.\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#include <mlpack/core.hpp>\n\n#include <mlpack/methods/ann/dists/bernoulli_distribution.hpp>\n#include <mlpack/methods/ann/init_rules/random_init.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n\n#include <mlpack/methods/ann/activation_functions/logistic_function.hpp>\n\nusing namespace mlpack;\nusing namespace mlpack::ann;\n\nBOOST_AUTO_TEST_SUITE(ANNDistTest);\n\n/**\n * Simple bernoulli distribution module test.\n */\nBOOST_AUTO_TEST_CASE(SimpleBernoulliDistributionTest)\n{\n  arma::mat param = arma::mat(\"1 1 0\");\n  BernoulliDistribution<> module(std::move(param), false);\n\n  arma::mat sample = module.Sample();\n  // As the probabilities are [1, 1, 0], the bernoulli samples should be\n  // [1, 1, 0] as well.\n  CheckMatrices(param, sample);\n}\n\n/**\n * Jacobian bernoulli distribution module test when we don't apply logistic.\n */\nBOOST_AUTO_TEST_CASE(JacobianBernoulliDistributionTest)\n{\n  for (size_t i = 0; i < 5; i++)\n  {\n    const size_t targetElements = math::RandInt(2, 1000);\n\n    arma::mat param;\n    param.randn(targetElements, 1);\n\n    arma::mat target;\n    target.randn(targetElements, 1);\n\n    BernoulliDistribution<> module(std::move(param), false);\n\n    const double perturbation = 1e-6;\n    double outputA, outputB, original;\n    arma::mat jacobianA, jacobianB;\n\n    // Initialize the jacobian matrix.\n    jacobianA = arma::zeros(targetElements, 1);\n\n    for (size_t j = 0; j < targetElements; ++j)\n    {\n      original = module.Probability()(j);\n      module.Probability()(j) = original - perturbation;\n      outputA = module.LogProbability(std::move(target));\n      module.Probability()(j) = original + perturbation;\n      outputB = module.LogProbability(std::move(target));\n      module.Probability()(j) = original;\n      outputB -= outputA;\n      outputB /= 2 * perturbation;\n      jacobianA(j) = outputB;\n    }\n\n    module.LogProbBackward(std::move(target), std::move(jacobianB));\n    BOOST_REQUIRE_LE(arma::max(arma::max(arma::abs(jacobianA - jacobianB))),\n        1e-5);\n  }\n}\n\n/**\n * Jacobian bernoulli distribution module test when we apply logistic.\n */\nBOOST_AUTO_TEST_CASE(JacobianBernoulliDistributionLogisticTest)\n{\n  for (size_t i = 0; i < 5; i++)\n  {\n    const size_t targetElements = math::RandInt(2, 1000);\n\n    arma::mat param;\n    param.randn(targetElements, 1);\n\n    arma::mat target;\n    target.randn(targetElements, 1);\n\n    BernoulliDistribution<> module(std::move(param));\n\n    const double perturbation = 1e-6;\n    double outputA, outputB, original;\n    arma::mat jacobianA, jacobianB;\n\n    // Initialize the jacobian matrix.\n    jacobianA = arma::zeros(targetElements, 1);\n\n    for (size_t j = 0; j < targetElements; ++j)\n    {\n      original = module.Logits()(j);\n      module.Logits()(j) = original - perturbation;\n      LogisticFunction::Fn(module.Logits(), module.Probability());\n      outputA = module.LogProbability(std::move(target));\n      module.Logits()(j) = original + perturbation;\n      LogisticFunction::Fn(module.Logits(), module.Probability());\n      outputB = module.LogProbability(std::move(target));\n      module.Logits()(j) = original;\n      LogisticFunction::Fn(module.Logits(), module.Probability());\n      outputB -= outputA;\n      outputB /= 2 * perturbation;\n      jacobianA(j) = outputB;\n    }\n\n    module.LogProbBackward(std::move(target), std::move(jacobianB));\n    BOOST_REQUIRE_LE(arma::max(arma::max(arma::abs(jacobianA - jacobianB))),\n        3e-5);\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "cf9baca90d11f3ea8e07ade2c6ed7087a577d3fe", "size": 3859, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/ann_dist_test.cpp", "max_stars_repo_name": "RMaron/mlpack", "max_stars_repo_head_hexsha": "a179a2708d9555ab7ee4b1e90e0c290092edad2e", "max_stars_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-01-04T04:20:29.000Z", "max_stars_repo_stars_event_max_datetime": "2016-07-21T23:30:34.000Z", "max_issues_repo_path": "src/mlpack/tests/ann_dist_test.cpp", "max_issues_repo_name": "RMaron/mlpack", "max_issues_repo_head_hexsha": "a179a2708d9555ab7ee4b1e90e0c290092edad2e", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2017-01-23T18:39:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-15T13:58:34.000Z", "max_forks_repo_path": "src/mlpack/tests/ann_dist_test.cpp", "max_forks_repo_name": "RMaron/mlpack", "max_forks_repo_head_hexsha": "a179a2708d9555ab7ee4b1e90e0c290092edad2e", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-01-20T00:54:34.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-16T05:34:32.000Z", "avg_line_length": 29.4580152672, "max_line_length": 78, "alphanum_fraction": 0.6841150557, "num_tokens": 1026, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4849925406225546}}
{"text": "#include <Eigen/Core>\n#include <Eigen/Sparse>\n#include <vector>\n\nnamespace ials11 {\nusing Real = float;\nusing IndexType = std::size_t;\nusing SparseMatrix = Eigen::SparseMatrix<Real, Eigen::RowMajor>;\nusing DenseMatrix =\n    Eigen::Matrix<Real, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;\nusing DenseVector = Eigen::Matrix<Real, Eigen::Dynamic, 1>;\n} // namespace ials11\n", "meta": {"hexsha": "135d33dc09995e78230b9cbecfe8a37c537bcae3", "size": 376, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cpp_source/als/definitions.hpp", "max_stars_repo_name": "wararaki/irspack", "max_stars_repo_head_hexsha": "650cc012924d46b3ecb87f1a6f806aee735a9559", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 30.0, "max_stars_repo_stars_event_min_datetime": "2020-12-23T08:08:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T13:48:55.000Z", "max_issues_repo_path": "cpp_source/als/definitions.hpp", "max_issues_repo_name": "kiminh/irspack", "max_issues_repo_head_hexsha": "45e448bb741b5f08b1b93d47ca293b981dd5f8af", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 38.0, "max_issues_repo_issues_event_min_datetime": "2021-01-03T12:29:40.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-11T12:58:05.000Z", "max_forks_repo_path": "cpp_source/als/definitions.hpp", "max_forks_repo_name": "kiminh/irspack", "max_forks_repo_head_hexsha": "45e448bb741b5f08b1b93d47ca293b981dd5f8af", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2020-12-24T10:23:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-04T12:53:20.000Z", "avg_line_length": 28.9230769231, "max_line_length": 73, "alphanum_fraction": 0.7367021277, "num_tokens": 95, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.48499253507419865}}
{"text": "#include <iostream>\n#include <fstream>\n#include <string>\n#include <Eigen/Cholesky>\n#include <adept_arrays.h>\n#include <chrono>\n\nusing namespace adept;\nusing namespace std;\nusing namespace std::chrono;\nint main(int argc, char **argv)\n{\n   string output_filename = argv[1];\n   cout << output_filename << endl;\n\n   int num_params = 4010;\n   int num_vars = 1;\n\n   Stack stack;\n   aVector  k(num_params);\n\n   Eigen::VectorXd args(num_params * num_vars);\n   Eigen::VectorXd ders(num_params * num_vars);\n\n   std::ifstream file(\"./tests/utils/params.txt\");\n   int i = 0;\n   for (std::string line; std::getline(file, line);)\n   {\n       args(i) = stod(line.c_str());\n       i++;\n   }\n   file.close();\n\n\n   for (int index = 0; index < num_params; index++) {\n\t\t\tk(index) = args[index * num_vars + 0];\n    }\n\n\n   ofstream outfile;\n   outfile.open(output_filename);\n\n   auto start = high_resolution_clock::now();\n   stack.new_recording();                 // Clear any existing differential statements\n   aReal J = sum(((k*k+3*k)-k/4)/k+k*k*k*k+k*k*(22/7*k)+k*k*k*k*k*k*k*k*k);\n   J.set_gradient(1.0);                   // Seed the dependent variable\n   stack.reverse();                       // Reverse-mode differentiation\n\n   auto stop = high_resolution_clock::now();\n   auto duration = duration_cast<microseconds>(stop - start);\n   outfile << (double)duration.count() / 1000000.0 << \" \";\n   for (int index = 0; index < num_params; index++) {\n\t\t\tders[index * num_vars + 0] = k.get_gradient()[index];\n    }\n   for (int i = 0; i < num_params * num_vars; i++)\n   {\n        ostringstream ss;\n        ss.precision(3);\n       ss << fixed << ders[i];\n       outfile << ss.str() << \" \";\n   }\n\n   outfile.close();\n\n   return 0;\n}", "meta": {"hexsha": "d620393803c5c1a190112014de98cec325e943cd", "size": 1709, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/utils/adept_jacobian.cpp", "max_stars_repo_name": "jiangzhongshi/acorns-benchmark", "max_stars_repo_head_hexsha": "df5f43af90a32f4c1578cdea1f4f412237e18c75", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-24T21:24:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-24T21:24:02.000Z", "max_issues_repo_path": "tests/utils/adept_jacobian.cpp", "max_issues_repo_name": "jiangzhongshi/acorns-benchmark", "max_issues_repo_head_hexsha": "df5f43af90a32f4c1578cdea1f4f412237e18c75", "max_issues_repo_licenses": ["MIT"], "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/utils/adept_jacobian.cpp", "max_forks_repo_name": "jiangzhongshi/acorns-benchmark", "max_forks_repo_head_hexsha": "df5f43af90a32f4c1578cdea1f4f412237e18c75", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-24T21:22:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-24T21:22:54.000Z", "avg_line_length": 25.8939393939, "max_line_length": 87, "alphanum_fraction": 0.602106495, "num_tokens": 456, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.48499253507419865}}
{"text": "#ifndef CVUTILS_HPP\n#define CVUTILS_HPP\n\n#include <vector>\n#include <opencv2/opencv.hpp>\n#include <boost/circular_buffer.hpp>\n\nnamespace cvk {\n\ninline boost::circular_buffer<cv::Scalar> create_color_palette(int n, double scale = 255.0) {\n  std::vector<cv::Vec3b> palette;\n  palette.reserve(n);\n\n  for(int i=0; i<n; i++) {\n    palette.push_back(cv::Vec3b((180.0 / (n+1)) * i, 220, 220));\n  }\n  cv::cvtColor(palette, palette, CV_HSV2BGR);\n\n  boost::circular_buffer<cv::Scalar> hsv(n);\n  double s = scale / 255.0;\n  for(const auto& col: palette) {\n    hsv.push_back(cv::Scalar(col[0] * s, col[1] * s, col[2] * s));\n  }\n  return hsv;\n}\n\ninline cv::Rect clip_roi(const cv::Rect& rect, const cv::Size& size) {\n  int top = std::max(0, rect.y);\n  int left = std::max(0, rect.x);\n  int bottom = std::min(size.height, rect.y + rect.height);\n  int right = std::min(size.width, rect.x + rect.width);\n  return cv::Rect(left, top, right - left, bottom - top);\n}\n\ninline cv::Rect enlarge_rect(const cv::Rect& rect, double scale) {\n  double dsize = (scale - 1.0) / 2.0;\n  return cv::Rect(rect.x - rect.width * dsize, rect.y - rect.height * dsize, rect.width * scale, rect.height * scale);\n}\n\ninline cv::Rect shift_rect(const cv::Rect& rect, const cv::Point& pt) {\n  return cv::Rect(rect.tl() + pt, rect.size());\n}\n\n}\n\n#endif // CVUTILS_HPP\n", "meta": {"hexsha": "3bf34268ebb58af90d988a7f0f383312593cc97c", "size": 1324, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/kkl/cvk/cvutils.hpp", "max_stars_repo_name": "shangzhouye/hdl_people_tracking", "max_stars_repo_head_hexsha": "ba1dd664439bedd8b5f99113326ffca4703d4aeb", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 207.0, "max_stars_repo_stars_event_min_datetime": "2018-03-10T14:56:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T07:32:53.000Z", "max_issues_repo_path": "include/kkl/cvk/cvutils.hpp", "max_issues_repo_name": "fwarmuth/hdl_people_tracking", "max_issues_repo_head_hexsha": "8153c2524e83a50abfe1f650fe44175c2d97ab5b", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 24.0, "max_issues_repo_issues_event_min_datetime": "2018-02-19T10:50:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T19:44:55.000Z", "max_forks_repo_path": "include/kkl/cvk/cvutils.hpp", "max_forks_repo_name": "fwarmuth/hdl_people_tracking", "max_forks_repo_head_hexsha": "8153c2524e83a50abfe1f650fe44175c2d97ab5b", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 91.0, "max_forks_repo_forks_event_min_datetime": "2018-02-23T09:44:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-03T01:38:14.000Z", "avg_line_length": 28.170212766, "max_line_length": 118, "alphanum_fraction": 0.6525679758, "num_tokens": 419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.48498539491274845}}
{"text": "\n//  (C) Copyright Nick Thompson 2020.\n//  (C) Copyright John Maddock 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#include <iostream>\n#include <boost/math/tools/ulps_plot.hpp>\n#include <boost/core/demangle.hpp>\n#include <nil/crypto3/multiprecision/mpfr.hpp>\n#include <nil/crypto3/multiprecision/cpp_bin_float.hpp>\n\nusing boost::math::tools::ulps_plot;\n\nint main() {\n   using PreciseReal = nil::crypto3::multiprecision::mpfr_float_100;\n   using CoarseReal = nil::crypto3::multiprecision::cpp_bin_float_50;\n\n   typedef boost::math::policies::policy<\n      boost::math::policies::promote_float<false>,\n      boost::math::policies::promote_double<false> >\n      no_promote_policy;\n\n   auto ai_coarse = [](CoarseReal const& x)->CoarseReal {\n      return log(x);\n   };\n   auto ai_precise = [](PreciseReal const& x)->PreciseReal {\n      return log(x);\n   };\n\n   std::string filename = \"cpp_bin_float_log.svg\";\n   int samples = 100000;\n   // How many pixels wide do you want your .svg?\n   int width = 700;\n   // Near a root, we have unbounded relative error. So for functions with roots, we define an ULP clip:\n   PreciseReal clip = 20;\n   // Should we perturb the abscissas?\n   bool perturb_abscissas = false;\n   auto plot = ulps_plot<decltype(ai_precise), PreciseReal, CoarseReal>(ai_precise, CoarseReal(0), CoarseReal(200), samples, perturb_abscissas);\n   // Note the argument chaining:\n   plot.clip(clip).width(width);\n   plot.background_color(\"white\").font_color(\"black\");\n   // Sometimes it's useful to set a title, but in many cases it's more useful to just use a caption.\n   //std::string title = \"Airy Ai ULP plot at \" + boost::core::demangle(typeid(CoarseReal).name()) + \" precision\";\n   //plot.title(title);\n   plot.vertical_lines(6);\n   plot.add_fn(ai_coarse);\n   // You can write the plot to a stream:\n   //std::cout << plot;\n   // Or to a file:\n   plot.write(filename);\n}\n", "meta": {"hexsha": "7421bb52a6f84b515d3f39381998e2ba0bb86356", "size": 2031, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "snark-logic/libs-source/multiprecision/plots/cpp_bin_float_log_errors.cpp", "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/plots/cpp_bin_float_log_errors.cpp", "max_issues_repo_name": "podlodkin/podlodkin-freeton-year-control", "max_issues_repo_head_hexsha": "e394c11f2414804d2fbde93a092ae589d4359739", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "snark-logic/libs-source/multiprecision/plots/cpp_bin_float_log_errors.cpp", "max_forks_repo_name": "podlodkin/podlodkin-freeton-year-control", "max_forks_repo_head_hexsha": "e394c11f2414804d2fbde93a092ae589d4359739", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-31T06:27:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-31T06:27:19.000Z", "avg_line_length": 38.320754717, "max_line_length": 144, "alphanum_fraction": 0.7016248154, "num_tokens": 564, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.6261241842048092, "lm_q1q2_score": 0.4849853895088629}}
{"text": "#include <fstream>\n#include <iostream>\n#include <unordered_set>\n\n#include <boost/functional/hash.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/exterior_property.hpp>\n#include <boost/graph/floyd_warshall_shortest.hpp>\n#include <boost/program_options.hpp>\n\n#include <yaml-cpp/yaml.h>\n\n#include \"timer.hpp\"\n\nstruct Location {\n  Location(int x, int y) : x(x), y(y) {}\n  int x;\n  int y;\n\n  bool operator<(const Location& other) const {\n    return std::tie(x, y) < std::tie(other.x, other.y);\n  }\n\n  bool operator==(const Location& other) const {\n    return std::tie(x, y) == std::tie(other.x, other.y);\n  }\n\n  friend std::ostream& operator<<(std::ostream& os, const Location& c) {\n    return os << \"(\" << c.x << \",\" << c.y << \")\";\n  }\n};\n\nnamespace std {\ntemplate <>\nstruct hash<Location> {\n  size_t operator()(const Location& s) const {\n    size_t seed = 0;\n    boost::hash_combine(seed, s.x);\n    boost::hash_combine(seed, s.y);\n    return seed;\n  }\n};\n}\n\n#include \"shortest_path_heuristic.hpp\"\n\nint main(int argc, char* argv[]) {\n  namespace po = boost::program_options;\n  // Declare the supported options.\n  po::options_description desc(\"Allowed options\");\n  std::string inputFile;\n  std::string outputFile;\n  desc.add_options()(\"help\", \"produce help message\")(\n      \"input,i\", po::value<std::string>(&inputFile)->required(),\n      \"input file (YAML)\")(\"output,o\",\n                           po::value<std::string>(&outputFile)->required(),\n                           \"output file (CSV)\");\n\n  try {\n    po::variables_map vm;\n    po::store(po::parse_command_line(argc, argv, desc), vm);\n    po::notify(vm);\n\n    if (vm.count(\"help\")) {\n      std::cout << desc << \"\\n\";\n      return 0;\n    }\n  } catch (po::error& e) {\n    std::cerr << e.what() << std::endl << std::endl;\n    std::cerr << desc << std::endl;\n    return 1;\n  }\n\n  YAML::Node config = YAML::LoadFile(inputFile);\n\n  std::unordered_set<Location> obstacles;\n#if 0\n  typedef boost::adjacency_list_traits<boost::vecS, boost::vecS, boost::undirectedS > searchGraphTraits_t;\n  typedef searchGraphTraits_t::vertex_descriptor vertex_t;\n  typedef searchGraphTraits_t::edge_descriptor edge_t;\n\n  struct Vertex\n  {\n  };\n\n  struct Edge\n  {\n    float weight;\n  };\n\n  typedef boost::adjacency_list<\n          boost::vecS, boost::vecS, boost::undirectedS,\n          Vertex, Edge>\n          searchGraph_t;\n  typedef boost::exterior_vertex_property<searchGraph_t, float> distanceProperty_t;\n  typedef distanceProperty_t::matrix_type distanceMatrix_t;\n  typedef distanceProperty_t::matrix_map_type distanceMatrixMap_t;\n\n  searchGraph_t searchGraph;\n  std::map<Location, vertex_t> mapLocToVertex;\n#endif\n  const auto& dim = config[\"map\"][\"dimensions\"];\n  int dimx = dim[0].as<int>();\n  int dimy = dim[1].as<int>();\n\n  for (const auto& node : config[\"map\"][\"obstacles\"]) {\n    obstacles.insert(Location(node[0].as<int>(), node[1].as<int>()));\n  }\n#if 0\n  // add vertices\n  for (int x = 0; x < dimx; ++x) {\n    for (int y = 0; y < dimy; ++y) {\n      Location l(x, y);\n      auto v = boost::add_vertex(searchGraph);\n      mapLocToVertex[l] = v;\n    }\n  }\n\n  // add edges\n  for (int x = 0; x < dimx; ++x) {\n    for (int y = 0; y < dimy; ++y) {\n      Location l(x, y);\n      if (obstacles.find(l) == obstacles.end()) {\n        Location right(x+1, y);\n        if (x < dimx - 1 && obstacles.find(right) == obstacles.end()) {\n          auto e = boost::add_edge(mapLocToVertex[l], mapLocToVertex[right], searchGraph);\n          searchGraph[e.first].weight = 1;\n        }\n        Location below(x, y+1);\n        if (y < dimy - 1 && obstacles.find(below) == obstacles.end()) {\n          auto e = boost::add_edge(mapLocToVertex[l], mapLocToVertex[below], searchGraph);\n          searchGraph[e.first].weight = 1;\n        }\n      }\n    }\n  }\n\n  distanceMatrix_t m_shortestDistance(boost::num_vertices(searchGraph));\n  distanceMatrixMap_t distanceMap(m_shortestDistance, searchGraph);\n  boost::floyd_warshall_all_pairs_shortest_paths(searchGraph, distanceMap, boost::weight_map(boost::get(&Edge::weight, searchGraph)));\n\n  std::ofstream fileStream(outputFile.c_str());\n  fileStream << dimx << \",\" << dimy << std::endl;\n  for (size_t row = 0; row < dimx * dimy; ++row) {\n    for (size_t column = 0; column < m_shortestDistance[row].size(); ++column) {\n      fileStream << m_shortestDistance[row][column] << \",\";\n    }\n    fileStream << std::endl;\n  }\n#endif\n\n  ShortestPathHeuristic h(dimx, dimy, obstacles);\n  std::cout << h.getValue(Location(0, 0), Location(3, 0)) << std::endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "3be05926e520810d13d03e15570036ba2ae54ded", "size": 4545, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/shortest_path_heuristic.cpp", "max_stars_repo_name": "VSumanth99/libMultiRobotPlanning", "max_stars_repo_head_hexsha": "0720ac87711c5bace889be160087b86a2042cd14", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 350.0, "max_stars_repo_stars_event_min_datetime": "2018-07-23T12:33:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:28:36.000Z", "max_issues_repo_path": "example/shortest_path_heuristic.cpp", "max_issues_repo_name": "VSumanth99/libMultiRobotPlanning", "max_issues_repo_head_hexsha": "0720ac87711c5bace889be160087b86a2042cd14", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 33.0, "max_issues_repo_issues_event_min_datetime": "2018-08-08T19:57:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-19T18:16:41.000Z", "max_forks_repo_path": "example/shortest_path_heuristic.cpp", "max_forks_repo_name": "VSumanth99/libMultiRobotPlanning", "max_forks_repo_head_hexsha": "0720ac87711c5bace889be160087b86a2042cd14", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 147.0, "max_forks_repo_forks_event_min_datetime": "2018-07-23T12:53:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T12:21:03.000Z", "avg_line_length": 28.949044586, "max_line_length": 134, "alphanum_fraction": 0.6305830583, "num_tokens": 1248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577159, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.4849853883965441}}
{"text": "#include <Eigen/Core>\n#include <iostream>\n#include <LBFGS.h>\n\nusing Eigen::VectorXd;\nusing namespace LBFGSpp;\n\ntypedef struct VectorRep {\n  double *vdata;\n  Eigen::Index vsize;\n} VectorRep;\n\n// A function that can be optimized\ntypedef double (*optfun) (const double *x, double *grad);\n\n// C++ wrapper around a C function pointer, for use with LBFGS++\nclass WrappedFun {\nprivate:\n  optfun f;\npublic:\n  WrappedFun (optfun f_in) { f = f_in; }\n  double operator()(const VectorXd& x, VectorXd& grad) {\n    return f (((VectorRep*)&x)->vdata, ((VectorRep*)&grad)->vdata);\n  }\n};\n\n// External entrypoint to call LBFGS++\nextern \"C\" double optimize_lbfgs (uint32_t size, optfun f, double *init_xs) {\n  // Set up parameters\n  LBFGSParam<double> param;\n  param.epsilon = 1e-6;\n  param.max_iterations = 100;\n\n  // Create solver and function objects, and return value slot\n  VectorRep init_rep = { init_xs, size };\n  VectorXd *vect = (VectorXd*)&init_rep;\n  LBFGSSolver<double> solver(param);\n  WrappedFun fun (f);\n  double val;\n\n  // Call solver\n  solver.minimize (fun, *vect, val);\n  return val;\n}\n", "meta": {"hexsha": "e7c27b8eac7550ecbfb9873f28c4703e19c14d7e", "size": 1086, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cbits/optimize_lbfgs.cpp", "max_stars_repo_name": "kquick/grappa", "max_stars_repo_head_hexsha": "44f22522a4cc64ed3c947466f0d06ce97403387c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-27T06:40:58.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-27T06:40:58.000Z", "max_issues_repo_path": "cbits/optimize_lbfgs.cpp", "max_issues_repo_name": "kquick/grappa", "max_issues_repo_head_hexsha": "44f22522a4cc64ed3c947466f0d06ce97403387c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-09-05T16:06:47.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-26T01:24:32.000Z", "max_forks_repo_path": "cbits/optimize_lbfgs.cpp", "max_forks_repo_name": "kquick/grappa", "max_forks_repo_head_hexsha": "44f22522a4cc64ed3c947466f0d06ce97403387c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-11-19T17:29:10.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-19T17:29:10.000Z", "avg_line_length": 24.1333333333, "max_line_length": 77, "alphanum_fraction": 0.6933701657, "num_tokens": 308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721303, "lm_q2_score": 0.6261241702517975, "lm_q1q2_score": 0.48498538521729573}}
{"text": "#include <iostream>\n#include <map>\nusing std::map;\n#include <string>\nusing std::string;\n#include <boost/shared_ptr.hpp>\nusing boost::shared_ptr;\n\n#include \"Resources.h\"\n\n#include \"flint/app/App.h\"\n#include \"flint/cairo/Cairo.h\"\n#include \"flint/Fill.h\"\t\n\n#define TEST_SVG\n#define TEST_PDF\n#define TEST_PNG\n\nusing namespace fli;\n\nstruct TestBase {\n virtual void run( fli::cairo::Context &ctx ) = 0;\n};\n\n// Arc\nstruct TestArc : public TestBase {\n\tvirtual void run( fli::cairo::Context &ctx ) {\n\t\tdouble xc = 128.0;\n\t\tdouble yc = 128.0;\n\t\tdouble radius = 100.0;\n\t\tdouble angle1 = 45.0  * ( M_PI / 180.0 );  /* angles are specified */\n\t\tdouble angle2 = 180.0 * ( M_PI / 180.0 );  /* in radians           */\n\n\t\tctx.setLineWidth( 10.0 );\n\t\tctx.arc( xc, yc, radius, angle1, angle2 );\n\t\tctx.stroke();\n\n\t\t/* draw helping lines */\n\t\tctx.setSourceRgba( 1, 0.2, 0.2, 0.6 );\n\t\tctx.setLineWidth( 6.0 );\n\n\t\tctx.arc( xc, yc, 10.0, 0, 2*M_PI );\n\t\tctx.fill();\n\n\t\tctx.arc( xc, yc, radius, angle1, angle1 );\n\t\tctx.lineTo( xc, yc);\n\t\tctx.arc( xc, yc, radius, angle2, angle2 );\n\t\tctx.lineTo( xc, yc );\n\t\tctx.stroke();\n\t}\n};\n\n// Arc Negative\nstruct TestArcNegative : public TestBase {\n\tvirtual void run( fli::cairo::Context &ctx ) {\n\t\tdouble xc = 128.0;\n\t\tdouble yc = 128.0;\n\t\tdouble radius = 100.0;\n\t\tdouble angle1 = 45.0  * ( M_PI / 180.0 );  /* angles are specified */\n\t\tdouble angle2 = 180.0 * ( M_PI / 180.0 );  /* in radians           */\n\n\t\tctx.setSourceRgb( 0.0, 0.0, 0.0 );\n\t\tctx.setLineWidth( 10.0 );\n\t\tctx.arcNegative( xc, yc, radius, angle1, angle2 );\n\t\tctx.stroke();\n\n\t\t/* draw helping lines */\n\t\tctx.setSourceRgba( 1, 0.2, 0.2, 0.6 );\n\t\tctx.setLineWidth( 6.0 );\n\n\t\tctx.arc( xc, yc, 10.0, 0, 2*M_PI );\n\t\tctx.fill();\n\n\t\tctx.arc( xc, yc, radius, angle1, angle1 );\n\t\tctx.lineTo( xc, yc);\n\t\tctx.arc( xc, yc, radius, angle2, angle2 );\n\t\tctx.lineTo( xc, yc );\n\t\tctx.stroke();\n\t}\n};\n\n// clip\nstruct TestClip : public TestBase {\n\tvirtual void run( fli::cairo::Context &ctx ) {\n\t\tctx.setSourceRgb( 0, 0, 0 );\n\t\tctx.arc( 128.0, 128.0, 76.8, 0, 2 * M_PI );\n\t\tctx.clip();\n\n\t\tctx.newPath();  // current path is not consumed by ctx.clip()\n\t\tctx.rectangle( 0, 0, 256, 256 );\n\t\tctx.fill();\n\t\tctx.setSourceRgb( 0, 1, 0 );\n\t\tctx.moveTo( 0, 0 );\n\t\tctx.lineTo( 256, 256 );\n\t\tctx.moveTo( 256, 0 );\n\t\tctx.lineTo( 0, 256 );\n\t\tctx.setLineWidth( 10.0 );\n\t\tctx.stroke();\n\t}\n};\n\n// clip image\nstruct TestClipImage : public TestBase {\n\tvirtual void run( fli::cairo::Context &ctx ) {\n\t\tint w, h;\n\n\t\tctx.arc( 128.0, 128.0, 76.8, 0, 2 * M_PI );\n\t\tctx.clip();\n\t\tctx.newPath(); // path not consumed by clip()\n\n//\t\tfli::shared_ptr<fli::cairo::SurfaceImage> image( fli::cairo::SurfaceImage::createFromPng( \"/Users/andrewfb/Code/dt/libdt_2.0/test/fullCairoTest/data/romedalen.png\" ) );\n\t\tSurface beyonceSurface( loadImage( app::App::loadResource( \"romedalen.png\", RES_ROMEDALEN_PNG, \"PNG\" ) ), SurfaceConstraintsCairo() );\n\t\tfli::shared_ptr<fli::cairo::SurfaceImage> image( new cairo::SurfaceImage( beyonceSurface ) );\n\t\tw = image->getWidth();\n\t\th = image->getHeight();\n\n\t\tctx.scale( 256.0 / w, 256.0 / h );\n\n\t\tctx.setSourceSurface( *image, 0, 0 );\n\t\tctx.paint();\n\t}\n};\n\n// curve rectangle\nstruct TestCurveRectangle : public TestBase {\n\tvirtual void run( fli::cairo::Context &ctx ) {\n\t\tdouble x0 = 25.6, y0 = 25.6, rect_width = 204.8, rect_height = 204.8, radius = 102.4;\n\t\t\n\t\tdouble x1,y1;\n\t\tx1 = x0 + rect_width;\n\t\ty1 = y0 + rect_height;\n\t\tif( ( ! rect_width ) || ( ! rect_height ) )\n\t\t\treturn;\n\t\t\n\t\tctx.moveTo( x0, y0 + radius );\n        ctx.curveTo( x0 , y0, x0 , y0, x0 + radius, y0 );\n        ctx.lineTo( x1 - radius, y0 );\n        ctx.curveTo( x1, y0, x1, y0, x1, y0 + radius );\n        ctx.lineTo( x1 , y1 - radius );\n        ctx.curveTo( x1, y1, x1, y1, x1 - radius, y1 );\n        ctx.lineTo( x0 + radius, y1 );\n        ctx.curveTo( x0, y1, x0, y1, x0, y1- radius );\n        \n        ctx.closePath();\n\n\t\tctx.setSourceRgb( 0.5, 0.5, 1 );\n\t\tctx.fillPreserve();\n\t\tctx.setSourceRgba( 0.5, 0, 0, 0.5 );\n\t\tctx.setLineWidth( 10.0 );\n\t\tctx.stroke();\n\t}\n};\n\n// curve to\nstruct TestCurveTo : public TestBase {\n\tvirtual void run( fli::cairo::Context &ctx ) {\n\t\tdouble x=25.6, y=128.0;\n\t\tdouble x1=102.4, y1=230.4, x2=153.6, y2=25.6, x3=230.4, y3=128.0;\n\n\t\tctx.moveTo( x, y );\n\t\tctx.curveTo( x1, y1, x2, y2, x3, y3 );\n\n\t\tctx.setLineWidth( 10.0 );\n\t\tctx.stroke();\n\n\t\tctx.setSourceRgba( 1, 0.2, 0.2, 0.6 );\n\t\tctx.setLineWidth( 6.0 );\n\t\tctx.moveTo( x, y );\n\t\tctx.lineTo( x1, y1 );\n\t\tctx.moveTo( x2, y2 );\n\t\tctx.lineTo( x3, y3 );\n\t\tctx.stroke();\n\t}\n};\n\n// dash\nstruct TestDash : public TestBase {\n\tvirtual void run( fli::cairo::Context &ctx ) {\n\t\tdouble dashes[] = {50.0,  /* ink */ 10.0,  /* skip */ 10.0,  /* ink */ 10.0   /* skip*/ };\n\t\tint ndash  = sizeof( dashes ) / sizeof( dashes[0] );\n\t\tdouble offset = -50.0;\n\n\t\tctx.setDash( dashes, ndash, offset );\n\t\tctx.setLineWidth( 10.0 );\n\n\t\tctx.moveTo( 128.0, 25.6 );\n\t\tctx.lineTo( 230.4, 230.4 );\n\t\tctx.relLineTo( -102.4, 0.0 );\n\t\tctx.curveTo( 51.2, 230.4, 51.2, 128.0, 128.0, 128.0 );\n\n\t\tctx.stroke();\n\t}\n};\n\n// fill and stroke\nstruct TestFillAndStroke : public TestBase {\n\tvirtual void run( fli::cairo::Context &ctx ) {\n\t\tctx.moveTo( 128.0, 25.6 );\n\t\tctx.lineTo( 230.4, 230.4 );\n\t\tctx.relLineTo( -102.4, 0.0 );\n\t\tctx.curveTo( 51.2, 230.4, 51.2, 128.0, 128.0, 128.0 );\n\t\tctx.closePath();\n\n\t\tctx.moveTo( 64.0, 25.6 );\n\t\tctx.relLineTo( 51.2, 51.2 );\n\t\tctx.relLineTo( -51.2, 51.2 );\n\t\tctx.relLineTo( -51.2, -51.2 );\n\t\tctx.closePath();\n\n\t\tctx.setLineWidth( 10.0 );\n\t\tctx.setSourceRgb( 0, 0, 1 );\n\t\tctx.fillPreserve();\n\t\tctx.setSourceRgb( 0, 0, 0 );\n\t\tctx.stroke();\n\t}\n};\n\n// fill style\nstruct TestFillStyle : public TestBase {\n\tvirtual void run( fli::cairo::Context &ctx ) {\n\t\tctx.setLineWidth( 6 );\n\n\t\tctx.rectangle( 12, 12, 232, 70 );\n\t\tctx.newSubPath();\n\t\tctx.arc( 64, 64, 40, 0, 2 * M_PI );\n\t\tctx.newSubPath();\n\t\tctx.arcNegative( 192, 64, 40, 0, -2 * M_PI );\n\n\t\tctx.setFillRule( fli::cairo::FILL_RULE_EVEN_ODD );\n\t\tctx.setSourceRgb( 0, 0.7, 0 );\n\t\tctx.fillPreserve();\n\t\tctx.setSourceRgb( 0, 0, 0 );\n\t\tctx.stroke();\n\n\t\tctx.translate( 0, 128 );\n\t\tctx.rectangle( 12, 12, 232, 70 );\n\t\tctx.newSubPath();\n\t\tctx.arc( 64, 64, 40, 0, 2 * M_PI );\n\t\tctx.newSubPath();\n\t\tctx.arcNegative( 192, 64, 40, 0, -2 * M_PI );\n\n\t\tctx.setFillRule( fli::cairo::FILL_RULE_WINDING );\n\t\tctx.setSourceRgb( 0, 0, 0.9);\n\t\tctx.fillPreserve();\n\t\tctx.setSourceRgb( 0, 0, 0);\n\t\tctx.stroke();\n\t}\n};\n\n// gradient\nstruct TestGradient : public TestBase {\n\tvirtual void run( fli::cairo::Context &ctx ) {\n\t\tshared_ptr<fli::cairo::Pattern> pat;\n\n\t\tpat = shared_ptr<fli::cairo::Pattern>( fli::cairo::Pattern::createLinear( 0.0, 0.0, 0.0, 256.0 ) );\n\t\tpat->addColorStopRgba( 1, 0, 0, 0, 1 );\n\t\tpat->addColorStopRgba( 0, 1, 1, 1, 1);\n\t\tctx.rectangle( 0, 0, 256, 256 );\n\t\tctx.setSource( pat.get() );\n\t\tctx.fill();\n\n\t\tpat = shared_ptr<fli::cairo::Pattern>( fli::cairo::Pattern::createRadial( 115.2, 102.4, 25.6, 102.4, 102.4, 128.0 ) );\n\t\tpat->addColorStopRgba( 0, 1, 1, 1, 1 );\n\t\tpat->addColorStopRgba( 1, 0, 0, 0, 1 );\n\t\tctx.setSource( pat.get() );\n\t\tctx.arc( 128.0, 128.0, 76.8, 0, 2 * M_PI );\n\t\tctx.fill();\n\t}\n};\n\n// image\nstruct TestImage : public TestBase {\n\tvirtual void run( fli::cairo::Context &ctx ) {\n\t\tSurface beyonceSurface( loadImage( app::App::loadResource( \"Beyonce.jpg\", RES_BEYONCE_JPG, \"JPG\" ) ), SurfaceConstraintsCairo() );\n\t\tfli::shared_ptr<fli::cairo::SurfaceImage> image( new cairo::SurfaceImage( beyonceSurface ) );\n\n\n\t\tctx.translate( 128.0, 128.0 );\n\t\tctx.rotate( 45 * M_PI / 180 );\n\t\tctx.scale( 256.0 / image->getWidth(), 256.0 / image->getHeight() );\n\t\tctx.translate( -0.5 * image->getWidth(), -0.5 * image->getHeight() );\n\n\t\tctx.setSourceSurface( *image, 0, 0 );\n\t\tctx.paint();\n\t}\n};\n\n// image pattern\nstruct TestImagePattern : public TestBase {\n\tvirtual void run( fli::cairo::Context &ctx ) {\n\t\tSurface beyonceSurface( loadImage( app::App::loadResource( \"Beyonce.jpg\", RES_BEYONCE_JPG, \"JPG\" ) ), SurfaceConstraintsCairo() );\n\t\tfli::shared_ptr<fli::cairo::SurfaceImage> image( new cairo::SurfaceImage( beyonceSurface ) );\n\t\tfli::shared_ptr<fli::cairo::Pattern> pattern( fli::cairo::Pattern::createForSurface( image.get() ) );\t\t\n\t\tpattern->setExtend( fli::cairo::EXTEND_REPEAT );\n\n\t\tctx.translate( 128.0, 128.0 );\n\t\tctx.rotate( M_PI / 4 );\n\t\tctx.scale( 1 / sqrt( 2.0 ), 1 / sqrt( 2.0 ) );\n\t\tctx.translate( -128.0, -128.0 );\n\n\t\tfli::cairo::Matrix mtx;\n\t\tmtx.initScale( image->getWidth() / 256.0 * 5.0, image->getHeight() / 256.0 * 5.0 );\n\t\tpattern->setMatrix( &mtx );\n\t\t\n\t\tctx.setSource( pattern.get() );\n\t\tctx.rectangle( 0, 0, 256.0, 256.0 );\n\t\tctx.fill();\n\t}\n};\n\n// multi segment caps\nstruct TestMultiSegmentCaps : public TestBase {\n\tvirtual void run( fli::cairo::Context &ctx ) {\n\t\tctx.moveTo( 50.0, 75.0 );\n\t\tctx.lineTo( 200.0, 75.0 );\n\n\t\tctx.moveTo( 50.0, 125.0 );\n\t\tctx.lineTo( 200.0, 125.0 );\n\n\t\tctx.moveTo( 50.0, 175.0 );\n\t\tctx.lineTo( 200.0, 175.0 );\n\n\t\tctx.setLineWidth( 30.0 );\n\t\tctx.setLineCap( fli::cairo::LINE_CAP_ROUND );\n\t\tctx.stroke();\n\t}\n};\n\n// set line cap\nstruct TestSetLineCap : public TestBase {\n\tvirtual void run( fli::cairo::Context &ctx ) {\n\t\tctx.setLineWidth( 30.0 );\n\t\tctx.setLineCap( fli::cairo::LINE_CAP_BUTT ); /* default */\n\t\tctx.moveTo( 64.0, 50.0 );\n\t\tctx.lineTo( 64.0, 200.0 );\n\t\tctx.stroke();\n\t\tctx.setLineCap( fli::cairo::LINE_CAP_ROUND );\n\t\tctx.moveTo( 128.0, 50.0 );\n\t\tctx.lineTo( 128.0, 200.0 );\n\t\tctx.stroke();\n\t\tctx.setLineCap( fli::cairo::LINE_CAP_SQUARE );\n\t\tctx.moveTo( 192.0, 50.0 );\n\t\tctx.lineTo( 192.0, 200.0 );\n\t\tctx.stroke();\n\n\t\t/* draw helping lines */\n\t\tctx.setSourceRgb( 1, 0.2, 0.2 );\n\t\tctx.setLineWidth( 2.56 );\n\t\tctx.moveTo( 64.0, 50.0 );\n\t\tctx.lineTo( 64.0, 200.0 );\n\t\tctx.moveTo( 128.0, 50.0 );\n\t\tctx.lineTo( 128.0, 200.0 );\n\t\tctx.moveTo( 192.0, 50.0 );\n\t\tctx.lineTo( 192.0, 200.0 );\n\t\tctx.stroke();\n\t}\n};\n\n// set line join\nstruct TestSetLineJoin : public TestBase {\n\tvirtual void run( fli::cairo::Context &ctx ) {\n\t\tctx.setLineWidth( 40.96 );\n\t\tctx.moveTo( 76.8, 84.48 );\n\t\tctx.relLineTo( 51.2, -51.2 );\n\t\tctx.relLineTo( 51.2, 51.2 );\n\t\tctx.setLineJoin( fli::cairo::LINE_JOIN_MITER );\n\t\tctx.stroke();\n\n\t\tctx.moveTo( 76.8, 161.28 );\n\t\tctx.relLineTo( 51.2, -51.2 );\n\t\tctx.relLineTo( 51.2, 51.2 );\n\t\tctx.setLineJoin( fli::cairo::LINE_JOIN_BEVEL );\n\t\tctx.stroke();\n\n\t\tctx.moveTo( 76.8, 238.08 );\n\t\tctx.relLineTo( 51.2, -51.2 );\n\t\tctx.relLineTo( 51.2, 51.2 );\n\t\tctx.setLineJoin( fli::cairo::LINE_JOIN_ROUND );\n\t\tctx.stroke();\n\t}\n};\n\n// text\nstruct TestText : public TestBase {\n\tvirtual void run( fli::cairo::Context &ctx ) {\n\t\tctx.selectFontFace( \"Batang\", fli::cairo::FONT_SLANT_NORMAL, fli::cairo::FONT_WEIGHT_BOLD );\n\t\tctx.setFontSize( 90.0 );\n\n\t\tctx.moveTo( 10.0, 135.0 );\n\t\tctx.showText( \"Hello\" );\n\n\t\tctx.moveTo( 70.0, 165.0 );\n\n// This code crashes PDF on the Mac\n//\tfli::cairo::FontFace *otherFont = new fli::cairo::FontFace( \"Baskerville\" );\n//\t\tcairo_set_font_face( ctx.getCairo(), cf );\n\n\t\tctx.textPath( \"World\" );\n\t\tctx.setSourceRgb( 0.5, 0.5, 1 );\n\t\tctx.fillPreserve();\n\t\tctx.setSourceRgb( 0, 0, 0 );\n\t\tctx.setLineWidth( 2.56 );\n\t\tctx.stroke();\n\n\t\t// draw helping lines\n\t\tctx.setSourceRgba( 1, 0.2, 0.2, 0.6 );\n\t\tctx.arc( 10.0, 135.0, 5.12, 0, 2 * M_PI );\n\t\tctx.closePath();\n\t\tctx.arc( 70.0, 165.0, 5.12, 0, 2 * M_PI );\n\t\tctx.fill();\n\t}\n};\n\n// text align center\nstruct TestTextAlignCenter : public TestBase {\n\tvirtual void run( fli::cairo::Context &ctx ) {\n\t\tconst std::string text = \"cairo\";\n\t\tdouble x,y;\n\n\t\tctx.selectFontFace( \"Sans\", fli::cairo::FONT_SLANT_NORMAL, fli::cairo::FONT_WEIGHT_NORMAL );\n\n\t\tctx.setFontSize( 52.0 );\n\t\tfli::cairo::TextExtents extents = ctx.textExtents( text );\n\t\tx = 128.0 - ( extents.width() / 2 + extents.xBearing() );\n\t\ty = 128.0 - ( extents.height() / 2 + extents.yBearing() );\n\n\t\tctx.moveTo( x, y );\n\t\tctx.showText( text );\n\n\t\t// draw helping lines\n\t\tctx.setSourceRgba( 1, 0.2, 0.2, 0.6 );\n\t\tctx.setLineWidth( 6.0 );\n\t\tctx.arc( x, y, 10.0, 0, 2 * M_PI );\n\t\tctx.fill();\n\t\tctx.moveTo( 128.0, 0 );\n\t\tctx.relLineTo( 0, 256 );\n\t\tctx.moveTo( 0, 128.0 );\n\t\tctx.relLineTo( 256, 0 );\n\t\tctx.stroke();\n\t}\n};\n\n// text extents\nstruct TestTextExtents : public TestBase {\n\tvirtual void run( fli::cairo::Context &ctx ) {\n\t\tconst std::string text = \"cairo\";\n\t\tdouble x,y;\n\n\t\tctx.selectFontFace( \"Sans\", fli::cairo::FONT_SLANT_NORMAL, fli::cairo::FONT_WEIGHT_NORMAL );\n\n\t\tctx.setFontSize( 100.0 );\n\t\tfli::cairo::TextExtents extents = ctx.textExtents( text );\n\t\tx = 25.0;\n\t\ty = 150.0;\n\n\t\tctx.moveTo( x, y );\n\t\tctx.showText( text );\n\n\t\t// draw helping lines\n\t\tctx.setSourceRgba( 1, 0.2, 0.2, 0.6 );\n\t\tctx.setLineWidth( 6.0 );\n\t\tctx.arc( x, y, 10.0, 0, 2 * M_PI );\n\t\tctx.fill();\n\t\tctx.moveTo( x, y );\n\t\tctx.relLineTo( 0, -extents.height() );\n\t\tctx.relLineTo( extents.width(), 0 );\n\t\tctx.relLineTo( extents.xBearing(), -extents.yBearing() );\n\t\tctx.stroke();\n\t}\n};\n\nint main( int argc, char **argv ) \n{\n\tmap<string,TestBase*> tests;\n\t\n\ttests[\"arc\"] = new TestArc();\n\ttests[\"arc_negative\"] = new TestArcNegative();\n\ttests[\"clip\"] = new TestClip();\n\ttests[\"clip_image\"] = new TestClipImage();\n\ttests[\"curve_rectangle\"] = new TestCurveRectangle();\n\ttests[\"curve_to\"] = new TestCurveTo();\n\ttests[\"dash\"] = new TestDash();\n\ttests[\"fill_and_stroke\"] = new TestFillAndStroke();\n\ttests[\"fill_style\"] = new TestFillStyle();\n\ttests[\"gradient\"] = new TestGradient();\n\ttests[\"image\"] = new TestImage();\n\ttests[\"image_pattern\"] = new TestImagePattern();\n\ttests[\"multi_segment_caps\"] = new TestMultiSegmentCaps();\n\ttests[\"set_line_cap\"] = new TestSetLineCap();\n\ttests[\"set_line_join\"] = new TestSetLineJoin();\n\ttests[\"text\"] = new TestText();\n\ttests[\"text_align_center\"] = new TestTextAlignCenter();\n\ttests[\"text_extents\"] = new TestTextExtents();\n#if defined( TEST_PNG )\n\t{\n\t\tstd::cout << \"-= Testing PNG =-\" << std::endl;\n\t\tfli::cairo::SurfaceImage surface( 512, 512 );\n\t\tfor( map<string,TestBase*>::const_iterator it = tests.begin(); it != tests.end(); ++it ) {\n\t\t\tfli::cairo::Context ctx( &surface );\n\t\t\tstd::cout << \"Running test: \" << it->first << std::endl;\n\t\t\tfli::fill( &surface.getSurface(), fli::Color8u( 255, 255, 255 ) );\n\t\t\tit->second->run( ctx );\n\t\t\tsurface.writeToPng( it->first + \".png\" );\n\t\t}\n\t}\n#endif\n\n#if defined( TEST_PDF )\n\t{\n\t\tstd::cout << \"-= Testing PDF =-\" << std::endl;\n\t\tfli::cairo::SurfacePDF surface( \"tests.pdf\", 512, 512 );\n\t\tfli::cairo::Context ctx( &surface );\n\t\tctx.save();\n\t\tfor( map<string,TestBase*>::const_iterator it = tests.begin(); it != tests.end(); ++it ) {\n\t\t\tstd::cout << \"Running test: \" << it->first << std::endl;\n\t\t\tit->second->run( ctx );\n\t\t\tctx.showPage();\n\t\t\tctx.restore();\n\t\t\tctx.save();\n\t\t}\n\t}\n#endif\n\n#if defined( TEST_SVG )\n\t{\n\t\tstd::cout << \"-= Testing SVG =-\" << std::endl;\n\t\tfor( map<string,TestBase*>::const_iterator it = tests.begin(); it != tests.end(); ++it ) {\n\t\t\tfli::cairo::SurfaceSVG surface( ( it->first + \".svg\" ).c_str(), 512, 512 );\n\t\t\tfli::cairo::Context ctx( &surface );\n\t\t\tstd::cout << \"Running test: \" << it->first << std::endl;\n\t\t\tit->second->run( ctx );\n\t\t\tctx.showPage();\n\t\t}\n\t}\n#endif\n\n\treturn 0;\n}\n", "meta": {"hexsha": "7b4de0597d4adcfb94e4bb5998cb0dcf92a4bef9", "size": 14922, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/cairoTest/cairoTest.cpp", "max_stars_repo_name": "rsh/Cinder-Emscripten", "max_stars_repo_head_hexsha": "4a08250c56656865c7c3a52fb9380980908b1439", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3494.0, "max_stars_repo_stars_event_min_datetime": "2015-01-02T08:42:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:16:23.000Z", "max_issues_repo_path": "test/cairoTest/cairoTest.cpp", "max_issues_repo_name": "rsh/Cinder-Emscripten", "max_issues_repo_head_hexsha": "4a08250c56656865c7c3a52fb9380980908b1439", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1284.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T07:31:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T02:06:43.000Z", "max_forks_repo_path": "test/cairoTest/cairoTest.cpp", "max_forks_repo_name": "rsh/Cinder-Emscripten", "max_forks_repo_head_hexsha": "4a08250c56656865c7c3a52fb9380980908b1439", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 780.0, "max_forks_repo_forks_event_min_datetime": "2015-01-02T22:14:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T00:16:56.000Z", "avg_line_length": 27.6846011132, "max_line_length": 172, "alphanum_fraction": 0.6180136711, "num_tokens": 5364, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.6261241772283035, "lm_q1q2_score": 0.48498538410497755}}
{"text": "//\n//  MonteCarloTools.cpp\n//  AmericanGeometric\n//\n//  Created by Jose Alcala Burgos on 6/28/13.\n//  Copyright (c) 2013 Jose V. Alcala. All rights reserved.\n//\n\n//include C++11 random\n#include <random>\n#include <math.h>\n#include \"MonteCarloTools.h\"\n#include <armadillo>\n\nusing namespace arma;\n\n/*\nvoid coefficientsGBM( mat *drift , mat *volatility , mat x , double t)\n{   //Check that dimensions are correct\n    int BM_dim ;\n    BM_dim = mu.n_rows ;\n    \n    if ( sigma.n_rows != BM_dim || sigma.n_cols != BM_dim ){\n        throw invalid_argument(\"The dimensions of sigma and mu do not agree.\");\n    }\n    \n\t//Check if the sigma matrix is invertible\n    if ( fabs(det(sigma)) < 0.000000000000001){\n        cout << \"sigma is not invertible, det_sigma = \" << fabs(det(sigma))<< endl;\n    }\n    \n    //Calculate the volatility\n    for (int i = 0 ; i < BM_dim; i++) {\n\t\tfor (int j=0; j < BM_dim; j++) {\n\t\t\t(*volatility)(i,j) = x(i,0)*sigma(i,j) ;\n\t\t}\n\t}\n    \n    //Calculate the drift\n    for (int i = 0 ; i < BM_dim; i++) {\n\t\t(*drift)(i,0) = mu(i,0) ;\n\t\tfor (int l=0; l < BM_dim; l++) {\n\t\t\t(*drift)(i,0) = (*drift)(i,0) + (0.5)*sigma(i,l)*sigma(i,l) ;\n\t\t}\n\t\t(*drift)(i,0) = x(i,0)*((*drift)(i,0));\n\t}\n    \n    \n}*/\n\n\n\n\n", "meta": {"hexsha": "b46dde6e77936c723c471c6288a3bbc74f16b345", "size": 1217, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "spike/MonteCarloTools.cpp", "max_stars_repo_name": "vidalalcala/sopt-ols", "max_stars_repo_head_hexsha": "ffc41ccdd0c523c39eebbada894c83533f92338d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "spike/MonteCarloTools.cpp", "max_issues_repo_name": "vidalalcala/sopt-ols", "max_issues_repo_head_hexsha": "ffc41ccdd0c523c39eebbada894c83533f92338d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "spike/MonteCarloTools.cpp", "max_forks_repo_name": "vidalalcala/sopt-ols", "max_forks_repo_head_hexsha": "ffc41ccdd0c523c39eebbada894c83533f92338d", "max_forks_repo_licenses": ["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.537037037, "max_line_length": 83, "alphanum_fraction": 0.5727198028, "num_tokens": 409, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.48498538410497744}}
{"text": "/**\n *          Copyright Matthias Walter 2010.\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 GEN_NETWORK_HPP_\n#define GEN_NETWORK_HPP_\n\n#include \"gen_generic.hpp\"\n#include \"matrix.hpp\"\n\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/depth_first_search.hpp>\n#include <boost/graph/two_bit_color_map.hpp>\n\ntemplate <typename OutputIterator, typename Graph, typename IndexMap, typename Vertex>\nOutputIterator find_path(Graph graph, IndexMap index_map, Vertex s, Vertex t, OutputIterator result)\n{\n  if (s == t)\n  {\n    *result++ = s;\n    return result;\n  }\n\n  typedef boost::graph_traits <Graph> graph_traits_t;\n  typedef typename graph_traits_t::vertex_descriptor vertex_t;\n\n  /// Define a color map for DFS\n  typedef boost::two_bit_color_map <> color_map_t;\n  color_map_t color_map(boost::num_vertices(graph));\n\n  /// Declare predecessor map\n  typedef std::vector <vertex_t> predecessors_t;\n  typedef boost::iterator_property_map <typename predecessors_t::iterator, IndexMap> predecessor_map_t;\n\n  predecessors_t predecessors(boost::num_vertices(graph), graph_traits_t::null_vertex());\n  predecessor_map_t predecessor_map(predecessors.begin(), index_map);\n\n  boost::depth_first_visit(graph, s, boost::make_dfs_visitor(record_predecessors(predecessor_map, boost::on_tree_edge())), color_map);\n\n  vertex_t current_vertex = t;\n  while (current_vertex != s)\n  {\n    vertex_t next_vertex = boost::get(predecessor_map, current_vertex);\n    if (next_vertex == graph_traits_t::null_vertex())\n      return result;\n\n    *result++ = current_vertex;\n\n    current_vertex = next_vertex;\n  }\n\n  *result++ = s;\n  return result;\n}\n\nclass network_matrix_generator: public matrix_generator\n{\npublic:\n  network_matrix_generator(size_t height, size_t width, unimod::log_level level) :\n    matrix_generator(\"network\", height, width, level)\n  {\n\n  }\n\n  virtual ~network_matrix_generator()\n  {\n\n  }\n\n  template <typename MatrixType>\n  void generate(MatrixType& matrix)\n  {\n    size_t nodes = matrix.size1() + 1;\n\n    if (_level != unimod::LOG_QUIET)\n      std::cerr << \"Creating a spanning tree with \" << nodes << \" nodes...\" << std::flush;\n\n    /// Create a spanning tree\n    typedef boost::adjacency_list <boost::vecS, boost::vecS, boost::undirectedS> tree_graph_t;\n    typedef boost::graph_traits <tree_graph_t> tree_traits_t;\n\n    tree_graph_t tree_graph(nodes);\n    std::vector <tree_traits_t::vertex_descriptor> used_vertices;\n\n    tree_traits_t::vertex_iterator vertex_iter, vertex_beyond;\n    for (boost::tie(vertex_iter, vertex_beyond) = boost::vertices(tree_graph); vertex_iter != vertex_beyond; ++vertex_iter)\n    {\n      if (!used_vertices.empty())\n      {\n        boost::uniform_int <int> dist(0, used_vertices.size() - 1);\n        tree_traits_t::vertex_descriptor other = used_vertices[dist(_rng)];\n\n        boost::add_edge(*vertex_iter, other, tree_graph);\n      }\n      used_vertices.push_back(*vertex_iter);\n    }\n\n    if (_level != unimod::LOG_QUIET)\n      std::cerr << \" done.\\nAdding edges and filling matrix...\" << std::flush;\n\n    for (size_t column = 0; column < _matrix.size2(); ++column)\n    {\n      /// Choose an edge not in the tree\n      boost::uniform_int <int> dist(0, nodes - 1);\n      tree_traits_t::vertex_descriptor u, v;\n      do\n      {\n        u = boost::vertex(dist(_rng), tree_graph);\n        v = boost::vertex(dist(_rng), tree_graph);\n      }\n      while (u == v || boost::edge(u, v, tree_graph).second);\n\n      std::set <tree_traits_t::vertex_descriptor> path_vertices;\n      find_path(tree_graph, boost::get(boost::vertex_index, tree_graph), u, v, std::inserter(path_vertices, path_vertices.end()));\n\n      size_t row = 0;\n      tree_traits_t::edge_iterator edge_iter, edge_beyond;\n      for (boost::tie(edge_iter, edge_beyond) = boost::edges(tree_graph); edge_iter != edge_beyond; ++edge_iter)\n      {\n        u = boost::source(*edge_iter, tree_graph);\n        v = boost::target(*edge_iter, tree_graph);\n\n        _matrix(row, column) = (path_vertices.find(u) != path_vertices.end() && path_vertices.find(v) != path_vertices.end()) ? 1 : 0;\n\n        ++row;\n      }\n    }\n\n    if (_level != unimod::LOG_QUIET)\n      std::cerr << \" done.\\nCorrecting the signs...\" << std::flush;\n    sign();\n    if (_level != unimod::LOG_QUIET)\n      std::cerr << \" done.\" << std::endl;\n  }\n\n  virtual void generate()\n  {\n    if (_height <= _width)\n    {\n      generate(_matrix);\n    }\n    else\n    {\n      unimod::matrix_transposed <unimod::integer_matrix> transposed(_matrix);\n      generate(transposed);\n    }\n  }\n\n};\n#endif\n", "meta": {"hexsha": "d500273c56f928be0f6cb11a1bac8c79512bdfc9", "size": 4679, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "unimodularity-library-1.2c/src/gen_network.hpp", "max_stars_repo_name": "vios-fish/CompetitiveProgramming", "max_stars_repo_head_hexsha": "6953f024e4769791225c57ed852cb5efc03eb94b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-07-05T21:14:40.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-08T01:33:12.000Z", "max_issues_repo_path": "src/gen_network.hpp", "max_issues_repo_name": "vbraun/unimodularity-library", "max_issues_repo_head_hexsha": "d329571908a84ed98713721a2fe873ad534901c8", "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/gen_network.hpp", "max_forks_repo_name": "vbraun/unimodularity-library", "max_forks_repo_head_hexsha": "d329571908a84ed98713721a2fe873ad534901c8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3831168831, "max_line_length": 134, "alphanum_fraction": 0.6794186792, "num_tokens": 1177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.48498538410497744}}
{"text": "#include <sparse.h>\n#include <sparse_fill.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n\nBOOST_AUTO_TEST_SUITE(SPARSE);\n\nBOOST_AUTO_TEST_CASE(product_2cm_vector_test)\n{    \n  \n  typedef sparse::Block<4,1,float> block4_type; \n  typedef sparse::Block<6,1,float> block6_type;\n  typedef sparse::Block<4,6,float> block4x6_type;\n    \n  typedef sparse::TwoColumnMatrix<block4x6_type> matrix_type;\n\ttypedef sparse::Vector<block6_type> vector6_type;\n\ttypedef sparse::Vector<block4_type> vector4_type;\n  \n\tmatrix_type J(1,2,2);\n  sparse::fill(J(0,0), 1.0f);\n\tsparse::fill(J(0,1), 2.0f);\n  \n\tvector6_type u(2);\n\tsparse::fill(u(0), 0.5f);\n\tsparse::fill(u(1), 6.5f);\n\t\n  vector4_type r(1);\n\tsparse::prod(J, u, r);\n\tBOOST_CHECK( r(0)(0) == 341  );\n  BOOST_CHECK( r(0)(1) == 773  );\n  BOOST_CHECK( r(0)(2) == 1205 );\n  BOOST_CHECK( r(0)(3) == 1637 );\n  \n\tJ.resize(2,4,4);\n  sparse::fill(J(1,1), 3.0f);\n\tsparse::fill(J(1,2), 4.0f);\n\tu.resize(4);\n\tsparse::fill(u(2), 12.5f);\n\tsparse::fill(u(3), 18.5f);\n\tr.clear();\n\tr.resize(2);\n\tsparse::prod(J, u, r);\n\tBOOST_CHECK( r(0)(0) == 341  );\n  BOOST_CHECK( r(0)(1) == 773  );\n  BOOST_CHECK( r(0)(2) == 1205 );\n  BOOST_CHECK( r(0)(3) == 1637 );\n\tBOOST_CHECK( r(1)(0) == 917  );\n  BOOST_CHECK( r(1)(1) == 1781 );\n  BOOST_CHECK( r(1)(2) == 2645 );\n  BOOST_CHECK( r(1)(3) == 3509 );\n\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "2ed9e64ee24f7a7522ee774532eae6babb0e34a5", "size": 1498, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/FOUNDATION/SPARSE/unit_tests/sparse_prod_2cm_vec/sparse_prod_2cm_vec.cpp", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-11-27T09:44:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-13T00:24:21.000Z", "max_issues_repo_path": "PROX/FOUNDATION/SPARSE/unit_tests/sparse_prod_2cm_vec/sparse_prod_2cm_vec.cpp", "max_issues_repo_name": "erleben/matchstick", "max_issues_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_issues_repo_licenses": ["MIT"], "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/FOUNDATION/SPARSE/unit_tests/sparse_prod_2cm_vec/sparse_prod_2cm_vec.cpp", "max_forks_repo_name": "erleben/matchstick", "max_forks_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_forks_repo_licenses": ["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.3898305085, "max_line_length": 61, "alphanum_fraction": 0.652870494, "num_tokens": 541, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.6261241702517975, "lm_q1q2_score": 0.4849853787010919}}
{"text": "#include \"postprocess.h\"\n\n#include <fstream>\n#include <map>\n\n#include <Eigen/Dense>\n\n#include \"simple_svg.h\"\n\nusing namespace svg;\n\nint EvaluateEdgeType(Arrangement_2::Halfedge_const_handle he, const Mesh& mesh, const Arrangement_2& overlay, double angle_thres) {\n\tint fid = he->face()->data() - 1;\n\tauto& params = mesh.GetPlanes();\n\tif (he->twin()->face() == overlay.unbounded_face()) {\n\t\treturn 2;\n\t}\n\telse {\n\t\tint fid1 = he->twin()->face()->data() - 1;\n\t\tif (fid1 == -1)\n\t\t\treturn 2;\n\t\tif (fid1 != fid) {\n\t\t\tK z = params[fid].ComputeDepth(he->source()->point());\n\t\t\tK n_z = params[fid1].ComputeDepth(he->source()->point());\n\t\t\tif (std::abs((z-n_z).convert_to<double>()) > 1e-6) {\n\t\t\t\treturn 2;\n\t\t\t} else {\n\t\t\t\tK z = params[fid].ComputeDepth(he->target()->point());\n\t\t\t\tK n_z = params[fid1].ComputeDepth(he->target()->point());\n\t\t\t\tif (std::abs((z-n_z).convert_to<double>()) > 1e-6)\n\t\t\t\t\treturn 2;\n\n\t\t\t\tauto& p1 = mesh.GetPlanes()[fid];\n\t\t\t\tauto& p2 = mesh.GetPlanes()[fid1];\n\t\t\t\tK dot = p1.n1_ * p2.n1_ + p1.n2_ * p2.n2_ + p1.n3_ * p2.n3_;\n\t\t\t\tdouble t1 = dot.convert_to<double>();\n\t\t\t\tdouble t2 = cos(angle_thres * 3.141592654 / 180.0);\n\n\t\t\t\tif (std::abs(t1) < t2) {\n\t\t\t\t\treturn 1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn 0;\n}\n\nvoid PostProcess::CollectFaceAndVertices(const Mesh& mesh, const Arrangement_2& overlay, double angle_thres) {\n\tauto& points = points_;\n\tauto& facets_id = facets_id_;\n\tauto& facets = facets_;\n\tauto& params = mesh.GetPlanes();\n\tauto& depths = depths_;\n\tstd::map<std::pair<Arrangement_2::Vertex_const_handle,int>, int> vertexID;\n\n\tfor (auto fit = overlay.faces_begin(); fit != overlay.faces_end(); ++fit) {\n\t\tint fid = fit->data() - 1;\n\t\tif (fit == overlay.unbounded_face() || fid < 0)\n\t\t\tcontinue;\n\n\t\tEdgeList e;\n\t\tauto e_handle = fit->outer_ccb();\n\t\tArrangement_2::Ccb_halfedge_const_circulator curr = e_handle;\n\t\tdo {\n\t\t\tArrangement_2::Halfedge_const_handle he = curr;\n\t\t\tauto key = std::make_pair(he->source(), fid);\n\t\t\tauto it = vertexID.find(key);\n\t\t\tif (it == vertexID.end()) {\n\t\t\t\tvertexID[key] = points.size();\n\t\t\t\te.outer_indices.push_back(points.size());\n\t\t\t\tK z = params[fid].ComputeDepth(he->source()->point());\n\t\t\t\tpoints.push_back(key);\n\t\t\t\tdepths.push_back(z);\n\t\t\t} else {\n\t\t\t\te.outer_indices.push_back(it->second);\n\t\t\t}\n\t\t\te.outer_type.push_back(EvaluateEdgeType(he, mesh, overlay, angle_thres));\n\t\t} while (++curr != e_handle);\n\n\t\tfor (auto hi = fit->holes_begin(); hi != fit->holes_end(); ++hi) {\n\t\t\tauto circ = *hi;\n\t\t\tArrangement_2::Ccb_halfedge_const_circulator curr = circ;\n\t\t\te.inner_indices.push_back(std::vector<int>());\n\t\t\te.inner_type.push_back(std::vector<int>());\n\t\t\tdo {\n\t\t\t\tArrangement_2::Halfedge_const_handle he = curr;\n\t\t\t\tauto key = std::make_pair(he->source(), fid);\n\t\t\t\tauto it = vertexID.find(key);\n\t\t\t\tif (it == vertexID.end()) {\n\t\t\t\t\tvertexID[key] = points.size();\n\t\t\t\t\te.inner_indices.back().push_back(points.size());\n\t\t\t\t\tK z = params[fid].ComputeDepth(he->source()->point());\n\t\t\t\t\tpoints.push_back(key);\n\t\t\t\t\tdepths.push_back(z);\n\t\n\t\t\t\t} else {\n\t\t\t\t\te.inner_indices.back().push_back(it->second);\n\t\t\t\t}\n\t\t\t\te.inner_type.back().push_back(EvaluateEdgeType(he, mesh, overlay, angle_thres));\n\t\t\t} while (++curr != circ);\n\t\t}\n\t\tfacets.push_back(e);\n\t\tfacets_id.push_back(fid);\n\t}\t\n}\n\nvoid PostProcess::RemoveRedundantVertices()\n{\n\tauto& facets = facets_;\n\tauto& points = points_;\n\tauto& depths = depths_;\n\tauto& degrees = degrees_;\n\n\tComputeDegree();\n\n\tfor (auto& f : facets) {\n\t\tRemoveRedundantVerticesFromLoop(f.outer_indices, f.outer_type);\n\t\tfor (int i = 0; i < f.inner_indices.size(); ++i) {\n\t\t\tRemoveRedundantVerticesFromLoop(f.inner_indices[i], f.inner_type[i]);\n\t\t}\n\t}\n\n\tComputeDegree();\n\tstd::vector<int> compressed_vertexID(degrees.size());\n\tcompressed_vertexID[0] = 0;\n\tfor (int i = 1; i < compressed_vertexID.size(); ++i) {\n\t\tcompressed_vertexID[i] = compressed_vertexID[i - 1] + (degrees[i - 1] > 0 ? 1 : 0);\n\t}\n\n\tint top = 0;\n\tfor (int i = 0; i < points.size(); ++i) {\n\t\tif (degrees[i]) {\n\t\t\tpoints[top] = points[i];\n\t\t\tdepths[top] = depths[i];\n\t\t\ttop += 1;\n\t\t}\n\t}\n\n\tpoints.resize(top);\n\tdepths.resize(top);\n\tfor (auto& i : facets) {\n\t\tfor (auto& e : i.outer_indices) {\n\t\t\te = compressed_vertexID[e];\n\t\t}\n\t\tfor (auto& es : i.inner_indices) {\n\t\t\tfor (auto& e : es)\n\t\t\t\te = compressed_vertexID[e];\n\t\t}\n\t}\n}\n\nvoid PostProcess::MergeDuplex(const Mesh& mesh)\n{\n\tauto & vertices = mesh.GetVertices();\n\tauto & faces = mesh.GetFaces();\n\n\tauto& facets = facets_;\n\tauto& points = points_;\n\tauto& depths = depths_;\n\t// merge duplex\n\tstd::map<std::pair<int,std::pair<int,int> >, int> vID;\n\tstd::vector<int> compressed_vertexID;\n\n\tint top = 0;\n\tcompressed_vertexID.resize(points.size());\n\tstd::vector<VertexSignature> points_buf;\n\tstd::vector<K> depths_buf;\n\tfor (int i = 0; i < points.size(); ++i) {\n\t\tdouble x = points[i].first->point().x().convert_to<double>();\n\t\tdouble y = points[i].first->point().y().convert_to<double>();\n\t\tdouble z = depths[i].convert_to<double>();\n\n\t\tauto key = std::make_pair(int(x * 1e5), std::make_pair(int(y * 1e5), int(z * 1e5)));\n\t\tauto it = vID.find(key);\n\t\tif (it == vID.end()) {\n\t\t\tcompressed_vertexID[i] = top;\n\t\t\tpoints_buf.push_back(points[i]);\n\t\t\tdepths_buf.push_back(depths[i]);\n\t\t\tvID[key] = top++;\n\t\t} else {\n\t\t\tcompressed_vertexID[i] = it->second;\n\t\t}\n\t}\n\tpoints = points_buf;\n\tdepths = depths_buf;\n\n\tauto shrink = [&](std::vector<int>& v) {\n\t\tstd::vector<int> m(v.size(), 1);\n\t\tfor (int i = 0; i < v.size(); ++i) {\n\t\t\tint curr = v[i];\n\t\t\tint next = v[(i + 1) % v.size()];\n\t\t\tif (curr == next) {\n\t\t\t\tm[i] = 0;\n\t\t\t}\n\t\t}\n\t\tint top = 0;\n\t\tfor (int i = 0; i < v.size(); ++i) {\n\t\t\tif (m[i] == 1)\n\t\t\t\tv[top++] = v[i];\n\t\t}\n\t\tv.resize(top);\n\t};\n\n\tfor (auto& i : facets) {\n\t\tfor (auto& e : i.outer_indices) {\n\t\t\te = compressed_vertexID[e];\n\t\t}\n\t\tshrink(i.outer_indices);\n\t\tfor (auto& es : i.inner_indices) {\n\t\t\tfor (auto& e : es) {\n\t\t\t\te = compressed_vertexID[e];\n\t\t\t}\n\t\t\tshrink(es);\n\t\t}\n\t}\n}\n\n\nvoid PostProcess::CollectEdges(const Mesh& mesh) {\n\tauto & vertices = mesh.GetVertices();\n\tauto & faces = mesh.GetFaces();\n\tauto & face_normals = mesh.GetFaceNormals();\n\tauto & facets_id = facets_id_;\n\tauto & edge2face = edge2face_;\n\n\tauto& facets = facets_;\n\tauto& points = points_;\n\n\tfor (int i = 0; i < facets.size(); ++i) {\n\t\tfor (int j = 0; j < facets[i].outer_indices.size(); ++j) {\n\t\t\tint v0 = facets[i].outer_indices[j];\n\t\t\tint v1 = facets[i].outer_indices[(j + 1) % facets[i].outer_indices.size()];\n\t\t\tauto key = (v0 < v1) ? std::make_pair(v0, v1) : std::make_pair(v1, v0);\n\t\t\tedge2face[key].insert(facets_id[i]);\n\t\t}\n\t\tfor (auto& es : facets[i].inner_indices) {\n\t\t\tfor (int j = 0; j < es.size(); ++j) {\n\t\t\t\tint v0 = es[j];\n\t\t\t\tint v1 = es[(j + 1) % es.size()];\n\t\t\t\tauto key = (v0 < v1) ? std::make_pair(v0, v1) : std::make_pair(v1, v0);\n\t\t\t\tedge2face[key].insert(facets_id[i]);\n\t\t\t}\t\t\t\n\t\t}\n\t}\n}\n\nvoid PostProcess::SaveToFile(const Mesh& mesh, const char* filename) {\n\tauto & vertices = mesh.GetVertices();\n\tauto & faces = mesh.GetFaces();\n\tauto & facets = facets_;\n\tauto & face_normals = mesh.GetFaceNormals();\n\tauto & facets_id = facets_id_;\n\tauto & edge2face = edge2face_;\n\tauto & points = points_;\n\tauto & depths = depths_;\n\n\tstd::ofstream os;\n\n\tos.open(filename);\n\n\tfor (int i = 0; i < points.size(); ++i) {\n\t\tdouble x = points[i].first->point().x().convert_to<double>();\n\t\tdouble y = points[i].first->point().y().convert_to<double>();\n\t\tdouble z = depths[i].convert_to<double>();\n\n\t\tEigen::Vector3d v(x * z, y * z, z);\n\t\t//Eigen::Vector3d v(x, y, z);\n\t\tos << \"v \" << v[0] << \" \" << v[1] << \" \" << v[2] << \"\\n\";\n\t}\n\n\tfor (auto& i : facets) {\n\t\tif (i.outer_indices.size() < 3)\n\t\t\tcontinue;\n\t\tos << \"f\";\n\t\tfor (auto& e : i.outer_indices) {\n\t\t\tos << \" \" << e + 1;\n\t\t}\n\t\tos << \"\\n\";\n\t\tfor (auto& es : i.inner_indices) {\n\t\t\tif (es.size() < 3)\n\t\t\t\tcontinue;\n\t\t\tos << \"###holes### f\";\n\t\t\tfor (auto& e : es) {\n\t\t\t\tos << \" \" << e + 1;\n\t\t\t}\n\t\t\tos << \"\\n\";\n\t\t}\n\t}\n\n\tfor (int i = 0; i < points.size(); ++i) {\n\t\tdouble x = points[i].first->point().x().convert_to<double>();\n\t\tdouble y = points[i].first->point().y().convert_to<double>();\n\t\tdouble z = depths[i].convert_to<double>();\n\n\t\tEigen::Vector3d v(x * z, y * z, z);\n\t\t//Eigen::Vector3d v(x, y, z);\n\t\tos << \"v \" << v[0] << \" \" << v[1] << \" \" << v[2] << \"\\n\";\n\t}\n\tos << \"### occlude boundaries\\n\";\n\tfor (auto& i : facets) {\n\t\tif (i.outer_indices.size() < 3)\n\t\t\tcontinue;\n\t\tfor (int j = 0; j < i.outer_indices.size(); ++j) {\n\t\t\tif (i.outer_type[j] == 2) {\n\t\t\t\tint next_j = (j + 1) % i.outer_indices.size();\n\t\t\t\tos << \"l \" << i.outer_indices[j] + 1\n\t\t\t\t   << \" \" << i.outer_indices[next_j] + 1 << \"\\n\";\n\t\t\t}\n\t\t}\n\t}\n\n\tfor (int i = 0; i < points.size(); ++i) {\n\t\tdouble x = points[i].first->point().x().convert_to<double>();\n\t\tdouble y = points[i].first->point().y().convert_to<double>();\n\t\tdouble z = depths[i].convert_to<double>();\n\n\t\tEigen::Vector3d v(x * z, y * z, z);\n\t\t//Eigen::Vector3d v(x, y, z);\n\t\tos << \"v \" << v[0] << \" \" << v[1] << \" \" << v[2] << \"\\n\";\n\t}\n\tos << \"### sharp edges\\n\";\n\tfor (auto& i : facets) {\n\t\tif (i.outer_indices.size() < 3)\n\t\t\tcontinue;\n\t\tfor (int j = 0; j < i.outer_indices.size(); ++j) {\n\t\t\tif (i.outer_type[j] == 1) {\n\t\t\t\tint next_j = (j + 1) % i.outer_indices.size();\n\t\t\t\tos << \"l \" << i.outer_indices[j] + 1\n\t\t\t\t   << \" \" << i.outer_indices[next_j] + 1 << \"\\n\";\n\t\t\t}\n\t\t}\n\t}\n\tos.close();\t\n}\n\nvoid PostProcess::SaveToSVG(const Mesh& mesh, const char* filename) {\n    auto & facets = facets_;\n    auto & points = points_;\n    auto & face_normals = mesh.GetFaceNormals();\n    auto & edge2face = edge2face_;\n   \t\n   \tDimensions dimensions(1000, 1000);\n    Document doc(filename, Layout(dimensions, Layout::BottomLeft));\n\n    // Red image border.\n    Polygon border(Stroke(1, Color::Red));\n    border << Point(0, 0) << Point(dimensions.width, 0)\n        << Point(dimensions.width, dimensions.height) << Point(0, dimensions.height);\n    doc << border;\n    // Render polygon\n\n\tfor (auto& i : facets) {\n\t\tif (i.outer_indices.size() < 3)\n\t\t\tcontinue;\n\n\t    Polygon poly(Color(128,128,128), Stroke(.0, Color(150, 160, 200)));\n\n\t    for (auto& e : i.outer_indices) {\n\t    \tauto& p = points[e].first->point();\n\t    \tint x = (p.x().convert_to<double>()+0.5) * 1000;\n\t    \tint y = (p.y().convert_to<double>()+0.5) * 1000;\n\t    \tpoly << Point(x, 1000-y);\n\t    }\n\t    doc << poly;\n\t}\n\n\tfor (int seq = 1; seq <= 2; ++seq) {\n\t\tfor (auto& i : facets) {\n\t\t\tif (i.outer_indices.size() < 3)\n\t\t\t\tcontinue;\n\t\t\tfor (int j = 0; j < i.outer_indices.size(); ++j) {\n\t\t\t\tif (i.outer_type[j] > 0 && i.outer_type[j] == seq) {\n\t\t\t    \tPolyline poly(Stroke(2, Color::Blue));\n\t\t\t    \tif (i.outer_type[j] == 2)\n\t\t\t    \t\tpoly = Polyline(Stroke(2, Color::Red));\n\t\t\t\t    {\n\t\t\t\t\t    auto& p1 = points[i.outer_indices[j]].first->point();\n\t\t\t\t    \tint x = (p1.x().convert_to<double>()+0.5) * 1000;\n\t\t\t\t    \tint y = (p1.y().convert_to<double>()+0.5) * 1000;\n\t\t\t\t    \tpoly << Point(x, 1000-y);\n\t\t\t\t    }\n\t\t\t\t    {\n\t\t\t\t    \tint next_j = (j + 1) % i.outer_indices.size();\n\t\t\t\t\t    auto& p1 = points[i.outer_indices[next_j]].first->point();\n\t\t\t\t    \tint x = (p1.x().convert_to<double>()+0.5) * 1000;\n\t\t\t\t    \tint y = (p1.y().convert_to<double>()+0.5) * 1000;\n\t\t\t\t    \tpoly << Point(x, 1000-y);\n\t\t\t\t    }\n\t\t\t\t    doc << poly;\n\t\t\t    }\n\t\t\t}\n\t\t}\n\t}\n\n    doc.save();\n}\n\nvoid PostProcess::ComputeDegree()\n{\n\tdegrees_.resize(points_.size());\n\n\tfor (auto& d :degrees_)\n\t\td = 0;\n\tfor (auto& f : facets_) {\n\t\tfor (auto& e : f.outer_indices) {\n\t\t\tdegrees_[e] += 2;\n\t\t}\n\t\tfor (auto& es : f.inner_indices) {\n\t\t\tfor (auto& e : es) {\n\t\t\t\tdegrees_[e] += 2;\n\t\t\t} \n\t\t}\n\t}\n}\n\nvoid PostProcess::RemoveRedundantVerticesFromLoop(std::vector<int>& indices, std::vector<int>& types) {\n\tauto& points = points_;\n\tauto& degrees = degrees_;\n\n\tstd::vector<int> mask(indices.size(), 0);\n\tfor (int i = 0; i < indices.size(); ++i) {\n\t\tif (degrees[indices[i]] > 2) {\n\t\t\tmask[i] = 1;\n\t\t\tcontinue;\n\t\t}\n\t\tif (types[i] != types[(i + indices.size() - 1) % indices.size()]) {\n\t\t\tmask[i] = 1;\n\t\t\tcontinue;\n\t\t}\n\t\tint prev_id = indices[(i + indices.size() - 1) % indices.size()];\n\t\tint next_id = indices[(i + 1) % indices.size()];\n\n\t\tauto& p1 = points[prev_id];\n\t\tauto& p2 = points[indices[i]];\n\t\tauto& p3 = points[next_id];\n\n\t\tauto diff1 = p2.first->point() - p1.first->point();\n\t\tauto diff2 = p3.first->point() - p2.first->point();\n\n\t\tK a = diff1.x() * diff2.y() - diff1.y() * diff2.x();\n\t\tif (a != K(0)) {\n\t\t\tmask[i] = 1;\n\t\t}\n\t}\n\tint top = 0;\n\tfor (int i = 0; i < indices.size(); ++i) {\n\t\tif (mask[i] == 1) {\n\t\t\tindices[top] = indices[i];\n\t\t\ttypes[top] = types[i];\n\t\t\ttop += 1;\n\t\t}\n\t}\n\tindices.resize(top);\n\ttypes.resize(top);\n\n}", "meta": {"hexsha": "caf3e1acffb093e9b063a8284cb3f03c36bdf180", "size": 12516, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/postprocess.cc", "max_stars_repo_name": "hjwdzh/VectorGraphRenderer", "max_stars_repo_head_hexsha": "4af5a683fb1414f32101be22924a809db08d7cb5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2020-02-15T23:00:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-25T05:01:17.000Z", "max_issues_repo_path": "src/postprocess.cc", "max_issues_repo_name": "hjwdzh/VectorGraphRenderer", "max_issues_repo_head_hexsha": "4af5a683fb1414f32101be22924a809db08d7cb5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/postprocess.cc", "max_forks_repo_name": "hjwdzh/VectorGraphRenderer", "max_forks_repo_head_hexsha": "4af5a683fb1414f32101be22924a809db08d7cb5", "max_forks_repo_licenses": ["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.3873085339, "max_line_length": 131, "alphanum_fraction": 0.5822946628, "num_tokens": 4066, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.839733983715524, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4849424835847331}}
{"text": "#include <boost/math/special_functions/expint.hpp>\n", "meta": {"hexsha": "8cadb1494bcf49f359039170a6e1f6554f13474b", "size": 51, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_special_functions_expint.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_special_functions_expint.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_special_functions_expint.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 25.5, "max_line_length": 50, "alphanum_fraction": 0.8235294118, "num_tokens": 11, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.839733983715524, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4849424835847331}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n\r\n// Copyright (c) 2007-2015 Barend Gehrels, Amsterdam, the Netherlands.\r\n// Copyright (c) 2008-2015 Bruno Lalande, Paris, France.\r\n// Copyright (c) 2009-2015 Mateusz Loskot, London, UK.\r\n\r\n// This file was modified by Oracle on 2014, 2015, 2018.\r\n// Modifications copyright (c) 2014-2018, Oracle and/or its affiliates.\r\n\r\n// Contributed and/or modified by Menelaos Karavelas, on behalf of Oracle\r\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\r\n\r\n// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library\r\n// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef BOOST_GEOMETRY_UTIL_MATH_HPP\r\n#define BOOST_GEOMETRY_UTIL_MATH_HPP\r\n\r\n#include <cmath>\r\n#include <limits>\r\n\r\n#include <boost/core/ignore_unused.hpp>\r\n\r\n#include <boost/math/constants/constants.hpp>\r\n#include <boost/math/special_functions/fpclassify.hpp>\r\n//#include <boost/math/special_functions/round.hpp>\r\n#include <boost/numeric/conversion/cast.hpp>\r\n#include <boost/type_traits/is_fundamental.hpp>\r\n#include <boost/type_traits/is_integral.hpp>\r\n\r\n#include <boost/geometry/core/cs.hpp>\r\n\r\n#include <boost/geometry/util/select_most_precise.hpp>\r\n\r\nnamespace boost { namespace geometry\r\n{\r\n\r\nnamespace math\r\n{\r\n\r\n#ifndef DOXYGEN_NO_DETAIL\r\nnamespace detail\r\n{\r\n\r\ntemplate <typename T>\r\ninline T const& greatest(T const& v1, T const& v2)\r\n{\r\n    return (std::max)(v1, v2);\r\n}\r\n\r\ntemplate <typename T>\r\ninline T const& greatest(T const& v1, T const& v2, T const& v3)\r\n{\r\n    return (std::max)(greatest(v1, v2), v3);\r\n}\r\n\r\ntemplate <typename T>\r\ninline T const& greatest(T const& v1, T const& v2, T const& v3, T const& v4)\r\n{\r\n    return (std::max)(greatest(v1, v2, v3), v4);\r\n}\r\n\r\ntemplate <typename T>\r\ninline T const& greatest(T const& v1, T const& v2, T const& v3, T const& v4, T const& v5)\r\n{\r\n    return (std::max)(greatest(v1, v2, v3, v4), v5);\r\n}\r\n\r\n\r\ntemplate <typename T>\r\ninline T bounded(T const& v, T const& lower, T const& upper)\r\n{\r\n    return (std::min)((std::max)(v, lower), upper);\r\n}\r\n\r\ntemplate <typename T>\r\ninline T bounded(T const& v, T const& lower)\r\n{\r\n    return (std::max)(v, lower);\r\n}\r\n\r\n\r\ntemplate <typename T,\r\n          bool IsFloatingPoint = boost::is_floating_point<T>::value>\r\nstruct abs\r\n{\r\n    static inline T apply(T const& value)\r\n    {\r\n        T const zero = T();\r\n        return value < zero ? -value : value;\r\n    }\r\n};\r\n\r\ntemplate <typename T>\r\nstruct abs<T, true>\r\n{\r\n    static inline T apply(T const& value)\r\n    {\r\n        using ::fabs;\r\n        using std::fabs; // for long double\r\n\r\n        return fabs(value);\r\n    }\r\n};\r\n\r\n\r\nstruct equals_default_policy\r\n{\r\n    template <typename T>\r\n    static inline T apply(T const& a, T const& b)\r\n    {\r\n        // See http://www.parashift.com/c++-faq-lite/newbie.html#faq-29.17\r\n        return greatest(abs<T>::apply(a), abs<T>::apply(b), T(1));\r\n    }\r\n};\r\n\r\ntemplate <typename T,\r\n          bool IsFloatingPoint = boost::is_floating_point<T>::value>\r\nstruct equals_factor_policy\r\n{\r\n    equals_factor_policy()\r\n        : factor(1) {}\r\n    explicit equals_factor_policy(T const& v)\r\n        : factor(greatest(abs<T>::apply(v), T(1)))\r\n    {}\r\n    equals_factor_policy(T const& v0, T const& v1, T const& v2, T const& v3)\r\n        : factor(greatest(abs<T>::apply(v0), abs<T>::apply(v1),\r\n                          abs<T>::apply(v2), abs<T>::apply(v3),\r\n                          T(1)))\r\n    {}\r\n\r\n    T const& apply(T const&, T const&) const\r\n    {\r\n        return factor;\r\n    }\r\n\r\n    T factor;\r\n};\r\n\r\ntemplate <typename T>\r\nstruct equals_factor_policy<T, false>\r\n{\r\n    equals_factor_policy() {}\r\n    explicit equals_factor_policy(T const&) {}\r\n    equals_factor_policy(T const& , T const& , T const& , T const& ) {}\r\n\r\n    static inline T apply(T const&, T const&)\r\n    {\r\n        return T(1);\r\n    }\r\n};\r\n\r\ntemplate <typename Type,\r\n          bool IsFloatingPoint = boost::is_floating_point<Type>::value>\r\nstruct equals\r\n{\r\n    template <typename Policy>\r\n    static inline bool apply(Type const& a, Type const& b, Policy const&)\r\n    {\r\n        return a == b;\r\n    }\r\n};\r\n\r\ntemplate <typename Type>\r\nstruct equals<Type, true>\r\n{\r\n    template <typename Policy>\r\n    static inline bool apply(Type const& a, Type const& b, Policy const& policy)\r\n    {\r\n        boost::ignore_unused(policy);\r\n\r\n        if (a == b)\r\n        {\r\n            return true;\r\n        }\r\n\r\n        if (boost::math::isfinite(a) && boost::math::isfinite(b))\r\n        {\r\n            // If a is INF and b is e.g. 0, the expression below returns true\r\n            // but the values are obviously not equal, hence the condition\r\n            return abs<Type>::apply(a - b)\r\n                <= std::numeric_limits<Type>::epsilon() * policy.apply(a, b);\r\n        }\r\n        else\r\n        {\r\n            return a == b;\r\n        }\r\n    }\r\n};\r\n\r\ntemplate <typename T1, typename T2, typename Policy>\r\ninline bool equals_by_policy(T1 const& a, T2 const& b, Policy const& policy)\r\n{\r\n    return detail::equals\r\n        <\r\n            typename select_most_precise<T1, T2>::type\r\n        >::apply(a, b, policy);\r\n}\r\n\r\ntemplate <typename Type,\r\n          bool IsFloatingPoint = boost::is_floating_point<Type>::value>\r\nstruct smaller\r\n{\r\n    static inline bool apply(Type const& a, Type const& b)\r\n    {\r\n        return a < b;\r\n    }\r\n};\r\n\r\ntemplate <typename Type>\r\nstruct smaller<Type, true>\r\n{\r\n    static inline bool apply(Type const& a, Type const& b)\r\n    {\r\n        if (!(a < b)) // a >= b\r\n        {\r\n            return false;\r\n        }\r\n        \r\n        return ! equals<Type, true>::apply(b, a, equals_default_policy());\r\n    }\r\n};\r\n\r\ntemplate <typename Type,\r\n          bool IsFloatingPoint = boost::is_floating_point<Type>::value>\r\nstruct smaller_or_equals\r\n{\r\n    static inline bool apply(Type const& a, Type const& b)\r\n    {\r\n        return a <= b;\r\n    }\r\n};\r\n\r\ntemplate <typename Type>\r\nstruct smaller_or_equals<Type, true>\r\n{\r\n    static inline bool apply(Type const& a, Type const& b)\r\n    {\r\n        if (a <= b)\r\n        {\r\n            return true;\r\n        }\r\n\r\n        return equals<Type, true>::apply(a, b, equals_default_policy());\r\n    }\r\n};\r\n\r\n\r\ntemplate <typename Type,\r\n          bool IsFloatingPoint = boost::is_floating_point<Type>::value>\r\nstruct equals_with_epsilon\r\n    : public equals<Type, IsFloatingPoint>\r\n{};\r\n\r\ntemplate\r\n<\r\n    typename T,\r\n    bool IsFundemantal = boost::is_fundamental<T>::value /* false */\r\n>\r\nstruct square_root\r\n{\r\n    typedef T return_type;\r\n\r\n    static inline T apply(T const& value)\r\n    {\r\n        // for non-fundamental number types assume that sqrt is\r\n        // defined either:\r\n        // 1) at T's scope, or\r\n        // 2) at global scope, or\r\n        // 3) in namespace std\r\n        using ::sqrt;\r\n        using std::sqrt;\r\n\r\n        return sqrt(value);\r\n    }\r\n};\r\n\r\ntemplate <typename FundamentalFP>\r\nstruct square_root_for_fundamental_fp\r\n{\r\n    typedef FundamentalFP return_type;\r\n\r\n    static inline FundamentalFP apply(FundamentalFP const& value)\r\n    {\r\n#ifdef BOOST_GEOMETRY_SQRT_CHECK_FINITENESS\r\n        // This is a workaround for some 32-bit platforms.\r\n        // For some of those platforms it has been reported that\r\n        // std::sqrt(nan) and/or std::sqrt(-nan) returns a finite value.\r\n        // For those platforms we need to define the macro\r\n        // BOOST_GEOMETRY_SQRT_CHECK_FINITENESS so that the argument\r\n        // to std::sqrt is checked appropriately before passed to std::sqrt\r\n        if (boost::math::isfinite(value))\r\n        {\r\n            return std::sqrt(value);\r\n        }\r\n        else if (boost::math::isinf(value) && value < 0)\r\n        {\r\n            return -std::numeric_limits<FundamentalFP>::quiet_NaN();\r\n        }\r\n        return value;\r\n#else\r\n        // for fundamental floating point numbers use std::sqrt\r\n        return std::sqrt(value);\r\n#endif // BOOST_GEOMETRY_SQRT_CHECK_FINITENESS\r\n    }\r\n};\r\n\r\ntemplate <>\r\nstruct square_root<float, true>\r\n    : square_root_for_fundamental_fp<float>\r\n{\r\n};\r\n\r\ntemplate <>\r\nstruct square_root<double, true>\r\n    : square_root_for_fundamental_fp<double>\r\n{\r\n};\r\n\r\ntemplate <>\r\nstruct square_root<long double, true>\r\n    : square_root_for_fundamental_fp<long double>\r\n{\r\n};\r\n\r\ntemplate <typename T>\r\nstruct square_root<T, true>\r\n{\r\n    typedef double return_type;\r\n\r\n    static inline double apply(T const& value)\r\n    {\r\n        // for all other fundamental number types use also std::sqrt\r\n        //\r\n        // Note: in C++98 the only other possibility is double;\r\n        //       in C++11 there are also overloads for integral types;\r\n        //       this specialization works for those as well.\r\n        return square_root_for_fundamental_fp\r\n            <\r\n                double\r\n            >::apply(boost::numeric_cast<double>(value));\r\n    }\r\n};\r\n\r\n\r\n\r\ntemplate\r\n<\r\n    typename T,\r\n    bool IsFundemantal = boost::is_fundamental<T>::value /* false */\r\n>\r\nstruct modulo\r\n{\r\n    typedef T return_type;\r\n\r\n    static inline T apply(T const& value1, T const& value2)\r\n    {\r\n        // for non-fundamental number types assume that a free\r\n        // function mod() is defined either:\r\n        // 1) at T's scope, or\r\n        // 2) at global scope\r\n        return mod(value1, value2);\r\n    }\r\n};\r\n\r\ntemplate\r\n<\r\n    typename Fundamental,\r\n    bool IsIntegral = boost::is_integral<Fundamental>::value\r\n>\r\nstruct modulo_for_fundamental\r\n{\r\n    typedef Fundamental return_type;\r\n\r\n    static inline Fundamental apply(Fundamental const& value1,\r\n                                    Fundamental const& value2)\r\n    {\r\n        return value1 % value2;\r\n    }\r\n};\r\n\r\n// specialization for floating-point numbers\r\ntemplate <typename Fundamental>\r\nstruct modulo_for_fundamental<Fundamental, false>\r\n{\r\n    typedef Fundamental return_type;\r\n\r\n    static inline Fundamental apply(Fundamental const& value1,\r\n                                    Fundamental const& value2)\r\n    {\r\n        return std::fmod(value1, value2);\r\n    }\r\n};\r\n\r\n// specialization for fundamental number type\r\ntemplate <typename Fundamental>\r\nstruct modulo<Fundamental, true>\r\n    : modulo_for_fundamental<Fundamental>\r\n{};\r\n\r\n\r\n\r\n/*!\r\n\\brief Short constructs to enable partial specialization for PI, 2*PI\r\n       and PI/2, currently not possible in Math.\r\n*/\r\ntemplate <typename T>\r\nstruct define_pi\r\n{\r\n    static inline T apply()\r\n    {\r\n        // Default calls Boost.Math\r\n        return boost::math::constants::pi<T>();\r\n    }\r\n};\r\n\r\ntemplate <typename T>\r\nstruct define_two_pi\r\n{\r\n    static inline T apply()\r\n    {\r\n        // Default calls Boost.Math\r\n        return boost::math::constants::two_pi<T>();\r\n    }\r\n};\r\n\r\ntemplate <typename T>\r\nstruct define_half_pi\r\n{\r\n    static inline T apply()\r\n    {\r\n        // Default calls Boost.Math\r\n        return boost::math::constants::half_pi<T>();\r\n    }\r\n};\r\n\r\ntemplate <typename T>\r\nstruct relaxed_epsilon\r\n{\r\n    static inline T apply(const T& factor)\r\n    {\r\n        return factor * std::numeric_limits<T>::epsilon();\r\n    }\r\n};\r\n\r\n// This must be consistent with math::equals.\r\n// By default math::equals() scales the error by epsilon using the greater of\r\n// compared values but here is only one value, though it should work the same way.\r\n// (a-a) <= max(a, a) * EPS       -> 0 <= a*EPS\r\n// (a+da-a) <= max(a+da, a) * EPS -> da <= (a+da)*EPS\r\ntemplate <typename T, bool IsFloat = boost::is_floating_point<T>::value>\r\nstruct scaled_epsilon\r\n{\r\n    static inline T apply(T const& val)\r\n    {\r\n        return (std::max)(abs<T>::apply(val), T(1))\r\n                    * std::numeric_limits<T>::epsilon();\r\n    }\r\n};\r\n\r\ntemplate <typename T>\r\nstruct scaled_epsilon<T, false>\r\n{\r\n    static inline T apply(T const&)\r\n    {\r\n        return T(0);\r\n    }\r\n};\r\n\r\n// ItoF ItoI FtoF\r\ntemplate <typename Result, typename Source,\r\n          bool ResultIsInteger = std::numeric_limits<Result>::is_integer,\r\n          bool SourceIsInteger = std::numeric_limits<Source>::is_integer>\r\nstruct rounding_cast\r\n{\r\n    static inline Result apply(Source const& v)\r\n    {\r\n        return boost::numeric_cast<Result>(v);\r\n    }\r\n};\r\n\r\n// TtoT\r\ntemplate <typename Source, bool ResultIsInteger, bool SourceIsInteger>\r\nstruct rounding_cast<Source, Source, ResultIsInteger, SourceIsInteger>\r\n{\r\n    static inline Source apply(Source const& v)\r\n    {\r\n        return v;\r\n    }\r\n};\r\n\r\n// FtoI\r\ntemplate <typename Result, typename Source>\r\nstruct rounding_cast<Result, Source, true, false>\r\n{\r\n    static inline Result apply(Source const& v)\r\n    {\r\n        return boost::numeric_cast<Result>(v < Source(0) ?\r\n                                            v - Source(0.5) :\r\n                                            v + Source(0.5));\r\n    }\r\n};\r\n\r\n} // namespace detail\r\n#endif\r\n\r\n\r\ntemplate <typename T>\r\ninline T pi() { return detail::define_pi<T>::apply(); }\r\n\r\ntemplate <typename T>\r\ninline T two_pi() { return detail::define_two_pi<T>::apply(); }\r\n\r\ntemplate <typename T>\r\ninline T half_pi() { return detail::define_half_pi<T>::apply(); }\r\n\r\ntemplate <typename T>\r\ninline T relaxed_epsilon(T const& factor)\r\n{\r\n    return detail::relaxed_epsilon<T>::apply(factor);\r\n}\r\n\r\ntemplate <typename T>\r\ninline T scaled_epsilon(T const& value)\r\n{\r\n    return detail::scaled_epsilon<T>::apply(value);\r\n}\r\n\r\n\r\n// Maybe replace this by boost equals or so\r\n\r\n/*!\r\n    \\brief returns true if both arguments are equal.\r\n    \\ingroup utility\r\n    \\param a first argument\r\n    \\param b second argument\r\n    \\return true if a == b\r\n    \\note If both a and b are of an integral type, comparison is done by ==.\r\n    If one of the types is floating point, comparison is done by abs and\r\n    comparing with epsilon. If one of the types is non-fundamental, it might\r\n    be a high-precision number and comparison is done using the == operator\r\n    of that class.\r\n*/\r\n\r\ntemplate <typename T1, typename T2>\r\ninline bool equals(T1 const& a, T2 const& b)\r\n{\r\n    return detail::equals\r\n        <\r\n            typename select_most_precise<T1, T2>::type\r\n        >::apply(a, b, detail::equals_default_policy());\r\n}\r\n\r\ntemplate <typename T1, typename T2>\r\ninline bool equals_with_epsilon(T1 const& a, T2 const& b)\r\n{\r\n    return detail::equals_with_epsilon\r\n        <\r\n            typename select_most_precise<T1, T2>::type\r\n        >::apply(a, b, detail::equals_default_policy());\r\n}\r\n\r\ntemplate <typename T1, typename T2>\r\ninline bool smaller(T1 const& a, T2 const& b)\r\n{\r\n    return detail::smaller\r\n        <\r\n            typename select_most_precise<T1, T2>::type\r\n        >::apply(a, b);\r\n}\r\n\r\ntemplate <typename T1, typename T2>\r\ninline bool larger(T1 const& a, T2 const& b)\r\n{\r\n    return detail::smaller\r\n        <\r\n            typename select_most_precise<T1, T2>::type\r\n        >::apply(b, a);\r\n}\r\n\r\ntemplate <typename T1, typename T2>\r\ninline bool smaller_or_equals(T1 const& a, T2 const& b)\r\n{\r\n    return detail::smaller_or_equals\r\n        <\r\n            typename select_most_precise<T1, T2>::type\r\n        >::apply(a, b);\r\n}\r\n\r\ntemplate <typename T1, typename T2>\r\ninline bool larger_or_equals(T1 const& a, T2 const& b)\r\n{\r\n    return detail::smaller_or_equals\r\n        <\r\n            typename select_most_precise<T1, T2>::type\r\n        >::apply(b, a);\r\n}\r\n\r\n\r\ntemplate <typename T>\r\ninline T d2r()\r\n{\r\n    static T const conversion_coefficient = geometry::math::pi<T>() / T(180.0);\r\n    return conversion_coefficient;\r\n}\r\n\r\ntemplate <typename T>\r\ninline T r2d()\r\n{\r\n    static T const conversion_coefficient = T(180.0) / geometry::math::pi<T>();\r\n    return conversion_coefficient;\r\n}\r\n\r\n\r\n#ifndef DOXYGEN_NO_DETAIL\r\nnamespace detail {\r\n\r\ntemplate <typename DegreeOrRadian>\r\nstruct as_radian\r\n{\r\n    template <typename T>\r\n    static inline T apply(T const& value)\r\n    {\r\n        return value;\r\n    }\r\n};\r\n\r\ntemplate <>\r\nstruct as_radian<degree>\r\n{\r\n    template <typename T>\r\n    static inline T apply(T const& value)\r\n    {\r\n        return value * d2r<T>();\r\n    }\r\n};\r\n\r\ntemplate <typename DegreeOrRadian>\r\nstruct from_radian\r\n{\r\n    template <typename T>\r\n    static inline T apply(T const& value)\r\n    {\r\n        return value;\r\n    }\r\n};\r\n\r\ntemplate <>\r\nstruct from_radian<degree>\r\n{\r\n    template <typename T>\r\n    static inline T apply(T const& value)\r\n    {\r\n        return value * r2d<T>();\r\n    }\r\n};\r\n\r\n} // namespace detail\r\n#endif\r\n\r\ntemplate <typename DegreeOrRadian, typename T>\r\ninline T as_radian(T const& value)\r\n{\r\n    return detail::as_radian<DegreeOrRadian>::apply(value);\r\n}\r\n\r\ntemplate <typename DegreeOrRadian, typename T>\r\ninline T from_radian(T const& value)\r\n{\r\n    return detail::from_radian<DegreeOrRadian>::apply(value);\r\n}\r\n\r\n\r\n/*!\r\n    \\brief Calculates the haversine of an angle\r\n    \\ingroup utility\r\n    \\note See http://en.wikipedia.org/wiki/Haversine_formula\r\n    haversin(alpha) = sin2(alpha/2)\r\n*/\r\ntemplate <typename T>\r\ninline T hav(T const& theta)\r\n{\r\n    T const half = T(0.5);\r\n    T const sn = sin(half * theta);\r\n    return sn * sn;\r\n}\r\n\r\n/*!\r\n\\brief Short utility to return the square\r\n\\ingroup utility\r\n\\param value Value to calculate the square from\r\n\\return The squared value\r\n*/\r\ntemplate <typename T>\r\ninline T sqr(T const& value)\r\n{\r\n    return value * value;\r\n}\r\n\r\n/*!\r\n\\brief Short utility to return the square root\r\n\\ingroup utility\r\n\\param value Value to calculate the square root from\r\n\\return The square root value\r\n*/\r\ntemplate <typename T>\r\ninline typename detail::square_root<T>::return_type\r\nsqrt(T const& value)\r\n{\r\n    return detail::square_root\r\n        <\r\n            T, boost::is_fundamental<T>::value\r\n        >::apply(value);\r\n}\r\n\r\n/*!\r\n\\brief Short utility to return the modulo of two values\r\n\\ingroup utility\r\n\\param value1 First value\r\n\\param value2 Second value\r\n\\return The result of the modulo operation on the (ordered) pair\r\n(value1, value2)\r\n*/\r\ntemplate <typename T>\r\ninline typename detail::modulo<T>::return_type\r\nmod(T const& value1, T const& value2)\r\n{\r\n    return detail::modulo\r\n        <\r\n            T, boost::is_fundamental<T>::value\r\n        >::apply(value1, value2);\r\n}\r\n\r\n/*!\r\n\\brief Short utility to workaround gcc/clang problem that abs is converting to integer\r\n       and that older versions of MSVC does not support abs of long long...\r\n\\ingroup utility\r\n*/\r\ntemplate<typename T>\r\ninline T abs(T const& value)\r\n{\r\n    return detail::abs<T>::apply(value);\r\n}\r\n\r\n/*!\r\n\\brief Short utility to calculate the sign of a number: -1 (negative), 0 (zero), 1 (positive)\r\n\\ingroup utility\r\n*/\r\ntemplate <typename T>\r\ninline int sign(T const& value)\r\n{\r\n    T const zero = T();\r\n    return value > zero ? 1 : value < zero ? -1 : 0;\r\n}\r\n\r\n/*!\r\n\\brief Short utility to cast a value possibly rounding it to the nearest\r\n       integral value.\r\n\\ingroup utility\r\n\\note If the source T is NOT an integral type and Result is an integral type\r\n      the value is rounded towards the closest integral value. Otherwise it's\r\n      casted without rounding.\r\n*/\r\ntemplate <typename Result, typename T>\r\ninline Result rounding_cast(T const& v)\r\n{\r\n    return detail::rounding_cast<Result, T>::apply(v);\r\n}\r\n\r\n/*!\r\n\\brief Short utility to calculate the power\r\n\\ingroup utility\r\n*/\r\ntemplate <typename T1, typename T2>\r\ninline T1 pow(T1 const& a, T2 const& b)\r\n{\r\n    using std::pow;\r\n    return pow(a, b);\r\n}\r\n\r\n} // namespace math\r\n\r\n\r\n}} // namespace boost::geometry\r\n\r\n#endif // BOOST_GEOMETRY_UTIL_MATH_HPP\r\n", "meta": {"hexsha": "294ea439c8aa8d8295c3c36e631a18e6aa9390aa", "size": 19572, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/geometry/util/math.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/util/math.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/util/math.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": 24.7433628319, "max_line_length": 94, "alphanum_fraction": 0.6204782342, "num_tokens": 4694, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.48489068744587416}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2007-2016 Barend Gehrels, Amsterdam, the Netherlands.\n\n// This file was modified by Oracle on 2014, 2016.\n// Modifications copyright (c) 2014-2016 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_GEOGRAPHIC_ANDOYER_HPP\n#define BOOST_GEOMETRY_STRATEGIES_GEOGRAPHIC_ANDOYER_HPP\n\n\n#include <boost/geometry/core/coordinate_type.hpp>\n#include <boost/geometry/core/radian_access.hpp>\n#include <boost/geometry/core/radius.hpp>\n#include <boost/geometry/core/srs.hpp>\n\n#include <boost/geometry/algorithms/detail/andoyer_inverse.hpp>\n#include <boost/geometry/algorithms/detail/flattening.hpp>\n\n#include <boost/geometry/strategies/distance.hpp>\n\n#include <boost/geometry/util/math.hpp>\n#include <boost/geometry/util/promote_floating_point.hpp>\n#include <boost/geometry/util/select_calculation_type.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\nnamespace strategy { namespace distance\n{\n\n\n/*!\n\\brief Point-point distance approximation taking flattening into account\n\\ingroup distance\n\\tparam Spheroid The reference spheroid model\n\\tparam CalculationType \\tparam_calculation\n\\author After Andoyer, 19xx, republished 1950, republished by Meeus, 1999\n\\note Although not so well-known, the approximation is very good: in all cases the results\nare about the same as Vincenty. In my (Barend's) testcases the results didn't differ more than 6 m\n\\see http://nacc.upc.es/tierra/node16.html\n\\see http://sci.tech-archive.net/Archive/sci.geo.satellite-nav/2004-12/2724.html\n\\see http://home.att.net/~srschmitt/great_circle_route.html (implementation)\n\\see http://www.codeguru.com/Cpp/Cpp/algorithms/article.php/c5115 (implementation)\n\\see http://futureboy.homeip.net/frinksamp/navigation.frink (implementation)\n\\see http://www.voidware.com/earthdist.htm (implementation)\n\\see http://www.dtic.mil/docs/citations/AD0627893\n\\see http://www.dtic.mil/docs/citations/AD703541\n*/\ntemplate\n<\n    typename Spheroid,\n    typename CalculationType = void\n>\nclass andoyer\n{\npublic :\n    template <typename Point1, typename Point2>\n    struct calculation_type\n        : promote_floating_point\n          <\n              typename select_calculation_type\n                  <\n                      Point1,\n                      Point2,\n                      CalculationType\n                  >::type\n          >\n    {};\n\n    typedef Spheroid model_type;\n\n    inline andoyer()\n        : m_spheroid()\n    {}\n\n    explicit inline andoyer(Spheroid const& spheroid)\n        : m_spheroid(spheroid)\n    {}\n\n    template <typename Point1, typename Point2>\n    inline typename calculation_type<Point1, Point2>::type\n    apply(Point1 const& point1, Point2 const& point2) const\n    {\n        return geometry::detail::andoyer_inverse\n            <\n                typename calculation_type<Point1, Point2>::type,\n                true, false\n            >::apply(get_as_radian<0>(point1), get_as_radian<1>(point1),\n                     get_as_radian<0>(point2), get_as_radian<1>(point2),\n                     m_spheroid).distance;\n    }\n\n    inline Spheroid const& model() const\n    {\n        return m_spheroid;\n    }\n\nprivate :\n    Spheroid m_spheroid;\n};\n\n\n#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\nnamespace services\n{\n\ntemplate <typename Spheroid, typename CalculationType>\nstruct tag<andoyer<Spheroid, CalculationType> >\n{\n    typedef strategy_tag_distance_point_point type;\n};\n\n\ntemplate <typename Spheroid, typename CalculationType, typename P1, typename P2>\nstruct return_type<andoyer<Spheroid, CalculationType>, P1, P2>\n    : andoyer<Spheroid, CalculationType>::template calculation_type<P1, P2>\n{};\n\n\ntemplate <typename Spheroid, typename CalculationType>\nstruct comparable_type<andoyer<Spheroid, CalculationType> >\n{\n    typedef andoyer<Spheroid, CalculationType> type;\n};\n\n\ntemplate <typename Spheroid, typename CalculationType>\nstruct get_comparable<andoyer<Spheroid, CalculationType> >\n{\n    static inline andoyer<Spheroid, CalculationType> apply(andoyer<Spheroid, CalculationType> const& input)\n    {\n        return input;\n    }\n};\n\ntemplate <typename Spheroid, typename CalculationType, typename P1, typename P2>\nstruct result_from_distance<andoyer<Spheroid, CalculationType>, P1, P2>\n{\n    template <typename T>\n    static inline typename return_type<andoyer<Spheroid, CalculationType>, P1, P2>::type\n        apply(andoyer<Spheroid, CalculationType> const& , T const& value)\n    {\n        return value;\n    }\n};\n\n\ntemplate <typename Point1, typename Point2>\nstruct default_strategy<point_tag, point_tag, Point1, Point2, geographic_tag, geographic_tag>\n{\n    typedef strategy::distance::andoyer\n                <\n                    srs::spheroid\n                        <\n                            typename select_coordinate_type<Point1, Point2>::type\n                        >\n                > type;\n};\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\n#endif // BOOST_GEOMETRY_STRATEGIES_GEOGRAPHIC_ANDOYER_HPP\n", "meta": {"hexsha": "1646727d091968b2bc06430dd58851dd15b4c951", "size": 5324, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "nheqminer/3rdparty/boost/geometry/strategies/geographic/distance_andoyer.hpp", "max_stars_repo_name": "EuroLine/nheqminer", "max_stars_repo_head_hexsha": "81c7ef889bb502d16f7d1e7ef020d0592f8af945", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 886.0, "max_stars_repo_stars_event_min_datetime": "2016-10-20T20:59:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T07:47:52.000Z", "max_issues_repo_path": "nheqminer/3rdparty/boost/geometry/strategies/geographic/distance_andoyer.hpp", "max_issues_repo_name": "EuroLine/nheqminer", "max_issues_repo_head_hexsha": "81c7ef889bb502d16f7d1e7ef020d0592f8af945", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 369.0, "max_issues_repo_issues_event_min_datetime": "2016-10-21T07:42:54.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-19T10:49:29.000Z", "max_forks_repo_path": "nheqminer/3rdparty/boost/geometry/strategies/geographic/distance_andoyer.hpp", "max_forks_repo_name": "EuroLine/nheqminer", "max_forks_repo_head_hexsha": "81c7ef889bb502d16f7d1e7ef020d0592f8af945", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 534.0, "max_forks_repo_forks_event_min_datetime": "2016-10-20T21:00:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T10:02:27.000Z", "avg_line_length": 29.5777777778, "max_line_length": 107, "alphanum_fraction": 0.7118707739, "num_tokens": 1283, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.48489068146627706}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2007-2015 Barend Gehrels, Amsterdam, the Netherlands.\n// Copyright (c) 2008-2015 Bruno Lalande, Paris, France.\n// Copyright (c) 2009-2015 Mateusz Loskot, London, UK.\n// Copyright (c) 2013-2015 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_NSPHERE_ALGORITHMS_DISJOINT_HPP\n#define BOOST_GEOMETRY_EXTENSIONS_NSPHERE_ALGORITHMS_DISJOINT_HPP\n\n#include <boost/geometry/algorithms/disjoint.hpp>\n#include <boost/geometry/algorithms/comparable_distance.hpp>\n\n#include <boost/mpl/if.hpp>\n#include <boost/type_traits/is_same.hpp>\n\n#include <boost/geometry/extensions/nsphere/views/center_view.hpp>\n\nnamespace boost { namespace geometry\n{\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail { namespace disjoint\n{\n\n// Arvo's algorithm implemented\n// TODO - implement the method mentioned in the article below and compare performance\n// \"On Faster Sphere-Box Overlap Testing\" - Larsson, T.; Akeine-Moller, T.; Lengyel, E.\ntemplate\n<\n    typename Box, typename NSphere,\n    std::size_t Dimension, std::size_t DimensionCount\n>\nstruct box_nsphere_comparable_distance_cartesian\n{\n    typedef typename geometry::select_most_precise\n        <\n            typename coordinate_type<Box>::type,\n            typename coordinate_type<NSphere>::type\n        >::type coordinate_type;\n\n    typedef typename geometry::default_distance_result\n        <\n            Box,\n            typename point_type<NSphere>::type\n        >::type result_type;\n\n    static inline result_type apply(Box const& box, NSphere const& nsphere)\n    {\n        result_type r = 0;\n\n        if( get<Dimension>(nsphere) < get<min_corner, Dimension>(box) )\n        {\n            coordinate_type tmp = get<min_corner, Dimension>(box) - get<Dimension>(nsphere);\n            r = tmp*tmp;\n        }\n        else if( get<max_corner, Dimension>(box) < get<Dimension>(nsphere) )\n        {\n            coordinate_type tmp = get<Dimension>(nsphere) - get<max_corner, Dimension>(box);\n            r = tmp*tmp;\n        }\n\n        return r + box_nsphere_comparable_distance_cartesian<\n                        Box, NSphere, Dimension + 1, DimensionCount\n                    >::apply(box, nsphere);\n    }\n};\n\ntemplate <typename Box, typename NSphere, std::size_t DimensionCount>\nstruct box_nsphere_comparable_distance_cartesian<Box, NSphere, DimensionCount, DimensionCount>\n{\n    static inline int apply(Box const& , NSphere const& )\n    {\n        return 0;\n    }\n};\n\n}} // namespace detail::disjoint\n#endif // DOXYGEN_NO_DETAIL\n\n#ifndef DOXYGEN_NO_DISPATCH\nnamespace dispatch\n{\n\ntemplate <typename Point, typename NSphere, std::size_t DimensionCount, bool Reverse>\nstruct disjoint<Point, NSphere, DimensionCount, point_tag, nsphere_tag, Reverse>\n{\n    static inline bool apply(Point const& p, NSphere const& s)\n    {\n        typedef typename coordinate_system<Point>::type p_cs;\n        typedef typename coordinate_system<NSphere>::type s_cs;\n        static const bool check_cs = ::boost::is_same<p_cs, cs::cartesian>::value\n                                  && ::boost::is_same<s_cs, cs::cartesian>::value;\n        BOOST_MPL_ASSERT_MSG(check_cs,\n                             NOT_IMPLEMENTED_FOR_THOSE_COORDINATE_SYSTEMS,\n                             (p_cs, s_cs));\n\n        typename radius_type<NSphere>::type const r = get_radius<0>(s);\n        center_view<const NSphere> const c(s);\n\n        return r * r < geometry::comparable_distance(p, c);\n    }\n};\n\ntemplate <typename NSphere, typename Box, std::size_t DimensionCount, bool Reverse>\nstruct disjoint<NSphere, Box, DimensionCount, nsphere_tag, box_tag, Reverse>\n{\n    static inline bool apply(NSphere const& s, Box const& b)\n    {\n        typedef typename coordinate_system<Box>::type b_cs;\n        typedef typename coordinate_system<NSphere>::type s_cs;\n        static const bool check_cs = ::boost::is_same<b_cs, cs::cartesian>::value\n                                  && ::boost::is_same<s_cs, cs::cartesian>::value;\n        BOOST_MPL_ASSERT_MSG(check_cs,\n                             NOT_IMPLEMENTED_FOR_THOSE_COORDINATE_SYSTEMS,\n                             (b_cs, s_cs));\n\n        typename radius_type<NSphere>::type const r = get_radius<0>(s);\n\n        return r * r < geometry::detail::disjoint::box_nsphere_comparable_distance_cartesian\n                           <\n                               Box, NSphere, 0, DimensionCount\n                           >::apply(b, s);\n    }\n};\n\ntemplate <typename NSphere1, typename NSphere2, std::size_t DimensionCount, bool Reverse>\nstruct disjoint<NSphere1, NSphere2, DimensionCount, nsphere_tag, nsphere_tag, Reverse>\n{\n    static inline bool apply(NSphere1 const& s1, NSphere2 const& s2)\n    {\n        typedef typename coordinate_system<NSphere1>::type s1_cs;\n        typedef typename coordinate_system<NSphere2>::type s2_cs;\n        static const bool check_cs = ::boost::is_same<s1_cs, cs::cartesian>::value\n                                  && ::boost::is_same<s2_cs, cs::cartesian>::value;\n        BOOST_MPL_ASSERT_MSG(check_cs,\n                             NOT_IMPLEMENTED_FOR_THOSE_COORDINATE_SYSTEMS,\n                             (s1_cs, s2_cs));\n\n        /*return get_radius<0>(s1) + get_radius<0>(s2)\n               <   ::sqrt(geometry::comparable_distance(center_view<NSphere>(s1), center_view<NSphere>(s2)));*/\n\n        typename radius_type<NSphere1>::type const r1 = get_radius<0>(s1);\n        typename radius_type<NSphere2>::type const r2 = get_radius<0>(s2);\n        center_view<NSphere1 const> const c1(s1);\n        center_view<NSphere2 const> const c2(s2);\n\n        return r1 * r1 + 2 * r1 * r2 + r2 * r2\n                < geometry::comparable_distance(c1, c2);\n    }\n};\n\n\n} // namespace dispatch\n#endif // DOXYGEN_NO_DISPATCH\n\n}} // namespace boost::geometry\n\n\n#endif // BOOST_GEOMETRY_EXTENSIONS_NSPHERE_ALGORITHMS_DISJOINT_HPP\n", "meta": {"hexsha": "6b073fa1219a5a279880ed3e57fe85887a4fe408", "size": 6206, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/geometry/extensions/nsphere/algorithms/disjoint.hpp", "max_stars_repo_name": "jonasdmentia/geometry", "max_stars_repo_head_hexsha": "097f6fdbe98118be82cd1917cc72c3c6a37bdf30", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-07T17:40:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-07T17:40:19.000Z", "max_issues_repo_path": "include/boost/geometry/extensions/nsphere/algorithms/disjoint.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/extensions/nsphere/algorithms/disjoint.hpp", "max_forks_repo_name": "jonasdmentia/geometry", "max_forks_repo_head_hexsha": "097f6fdbe98118be82cd1917cc72c3c6a37bdf30", "max_forks_repo_licenses": ["BSL-1.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": 36.9404761905, "max_line_length": 111, "alphanum_fraction": 0.6629068643, "num_tokens": 1498, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.48489068146627706}}
{"text": "/*\n [auto_generated]\n libs/numeric/odeint/examples/molecular_dynamics_cells.cpp\n\n [begin_description]\n Molecular dynamics example with cells.\n [end_description]\n\n Copyright 2009-2012 Karsten Ahnert\n Copyright 2009-2012 Mario Mulansky\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 <boost/numeric/odeint.hpp>\n\n#include <cstddef>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <tuple>\n#include <iostream>\n#include <random>\n\n#include <boost/range/algorithm/for_each.hpp>\n#include <boost/range/algorithm/sort.hpp>\n#include <boost/range/algorithm/unique_copy.hpp>\n#include <boost/range/algorithm_ext/iota.hpp>\n#include <boost/iterator/zip_iterator.hpp>\n#include <boost/iterator/transform_iterator.hpp>\n#include <boost/iterator/permutation_iterator.hpp>\n#include <boost/iterator/counting_iterator.hpp>\n\n#include \"point_type.hpp\"\n\n\n\n\n\n\n\n\nstruct local_force\n{\n    double m_gamma;        // friction\n    local_force( double gamma = 0.0 ) : m_gamma( gamma ) { }\n    template< typename Point >\n    Point operator()( Point& x , Point& v ) const\n    {\n        return - m_gamma * v;\n    }\n};\n\n\nstruct lennard_jones\n{\n    double m_sigma;\n    double m_eps;\n    lennard_jones( double sigma = 1.0 , double eps = 0.1 ) : m_sigma( sigma ) , m_eps( eps ) { }\n    double operator()( double r ) const\n    {\n        double c = m_sigma / r;\n        double c3 = c * c * c;\n        double c6 = c3 * c3;\n        return 4.0 * m_eps * ( -12.0 * c6 * c6 / r + 6.0 * c6 / r );\n    }\n};\n\ntemplate< typename F >\nstruct conservative_interaction\n{\n    F m_f;\n    conservative_interaction( F const &f = F() ) : m_f( f ) { }\n    template< typename Point >\n    Point operator()( Point const& x1 , Point const& x2 ) const\n    {\n        Point diff = x1 - x2;\n        double r = abs( diff );\n        double f = m_f( r );\n        return - diff / r * f; \n    }\n};\n\ntemplate< typename F >\nconservative_interaction< F > make_conservative_interaction( F const &f )\n{\n    return conservative_interaction< F >( f );\n}\n\n\n\n\n\n\n\n// force = interaction( x1 , x2 )\n// force = local_force( x , v )\ntemplate< typename LocalForce , typename Interaction >\nclass md_system_bs\n{\npublic:\n    \n    typedef std::vector< double > vector_type;\n    typedef point< double , 2 > point_type;\n    typedef point< int , 2 > index_type;\n    typedef std::vector< point_type > point_vector;\n    typedef std::vector< index_type > index_vector;\n    typedef std::vector< size_t > hash_vector;\n    typedef LocalForce local_force_type;\n    typedef Interaction interaction_type;\n\n\n    struct params\n    {\n        size_t n;\n        size_t n_cell_x , n_cell_y , n_cells;\n        double x_max , y_max , cell_size;\n        double eps , sigma;    // interaction strength, interaction radius\n        interaction_type interaction;\n        local_force_type local_force;\n    };\n\n\n    struct cell_functor\n    {\n        params const &m_p;\n\n        cell_functor( params const& p ) : m_p( p ) { }\n        \n        template< typename Tuple >\n        void operator()( Tuple const& t ) const\n        {\n            auto point = boost::get< 0 >( t );\n            size_t i1 = size_t( point[0] / m_p.cell_size ) , i2 = size_t( point[1] / m_p.cell_size );\n            boost::get< 1 >( t ) = index_type( i1 , i2 );\n            boost::get< 2 >( t ) = hash_func( boost::get< 1 >( t ) , m_p );\n        }\n    };\n\n\n\n    struct transform_functor\n    {\n        typedef size_t argument_type;\n        typedef size_t result_type;\n        hash_vector const* m_index;\n        transform_functor( hash_vector const& index ) : m_index( &index ) { }\n        size_t operator()( size_t i ) const { return (*m_index)[i]; }\n    };\n\n\n\n    struct interaction_functor\n    {\n        hash_vector const &m_cells_begin;\n        hash_vector const &m_cells_end;\n        hash_vector const &m_order;\n        point_vector const &m_x;\n        point_vector const &m_v;\n        params const &m_p;\n        size_t m_ncellx , m_ncelly;\n        \n        interaction_functor( hash_vector const& cells_begin , hash_vector const& cells_end , hash_vector pos_order ,\n                            point_vector const&x , point_vector const& v , params const &p )\n        : m_cells_begin( cells_begin ) , m_cells_end( cells_end ) , m_order( pos_order ) , m_x( x ) , m_v( v ) ,\n        m_p( p ) { }\n        \n        template< typename Tuple >\n        void operator()( Tuple const &t ) const\n        {\n            point_type x = periodic_bc( boost::get< 0 >( t ) , m_p ) , v = boost::get< 1 >( t );\n            index_type index = boost::get< 3 >( t );\n            size_t pos_hash = boost::get< 4 >( t );\n\n            point_type a = m_p.local_force( x , v );\n\n            for( int i=-1 ; i<=1 ; ++i )\n            {\n                for( int j=-1 ; j<=1 ; ++j )\n                {\n                    index_type cell_index = index + index_type( i , j );\n                    size_t cell_hash = hash_func( cell_index , m_p );\n                    for( size_t ii = m_cells_begin[ cell_hash ] ; ii < m_cells_end[ cell_hash ] ; ++ii )\n                    {\n                        if( m_order[ ii ] == pos_hash ) continue;\n                        point_type x2 = periodic_bc( m_x[ m_order[ ii ] ] , m_p );\n\n                        if( cell_index[0] >= m_p.n_cell_x ) x2[0] += m_p.x_max;\n                        if( cell_index[0] < 0 ) x2[0] -= m_p.x_max;\n                        if( cell_index[1] >= m_p.n_cell_y ) x2[1] += m_p.y_max;\n                        if( cell_index[1] < 0 ) x2[1] -= m_p.y_max;\n\n                        a += m_p.interaction( x , x2 );\n                    }\n                }\n            }\n            boost::get< 2 >( t ) = a;\n        }\n    };\n\n\n\n\n    md_system_bs( size_t n ,\n                  local_force_type const& local_force = local_force_type() ,                  \n                  interaction_type const& interaction = interaction_type() ,\n                  double xmax = 100.0 , double ymax = 100.0 , double cell_size = 2.0 )\n    : m_p() \n    {\n        m_p.n = n;\n        m_p.x_max = xmax;\n        m_p.y_max = ymax;\n        m_p.interaction = interaction;\n        m_p.local_force = local_force;\n        m_p.n_cell_x = size_t( xmax / cell_size );\n        m_p.n_cell_y = size_t( ymax / cell_size );\n        m_p.n_cells = m_p.n_cell_x * m_p.n_cell_y;\n        m_p.cell_size = cell_size;\n    }\n    \n    void init_point_vector( point_vector &x ) const { x.resize( m_p.n ); }\n    \n    void operator()( point_vector const& x , point_vector const& v , point_vector &a , double t ) const\n    {\n        // init\n        hash_vector pos_hash( m_p.n , 0 );\n        index_vector pos_index( m_p.n );\n        hash_vector pos_order( m_p.n , 0 );\n        hash_vector cells_begin( m_p.n_cells ) , cells_end( m_p.n_cells ) , cell_order( m_p.n_cells );\n\n        boost::iota( pos_order , 0 );\n        boost::iota( cell_order , 0 );\n\n        // calculate grid hash\n        // calcHash( m_dGridParticleHash, m_dGridParticleIndex, dPos, m_numParticles);\n        std::for_each(\n            boost::make_zip_iterator( boost::make_tuple( x.begin() , pos_index.begin() , pos_hash.begin() ) ) ,\n            boost::make_zip_iterator( boost::make_tuple( x.end() , pos_index.end() , pos_hash.end() ) ) ,\n            cell_functor( m_p ) );\n\n//         // sort particles based on hash\n//         // sortParticles(m_dGridParticleHash, m_dGridParticleIndex, m_numParticles);        \n        boost::sort( pos_order , [&]( size_t i1 , size_t i2 ) -> bool {\n            return pos_hash[i1] < pos_hash[i2]; } );\n\n\n        \n        // reorder particle arrays into sorted order and find start and end of each cell\n        std::for_each( cell_order.begin() , cell_order.end() , [&]( size_t i ) {\n            auto pos_begin = boost::make_transform_iterator( pos_order.begin() , transform_functor( pos_hash ) );\n            auto pos_end = boost::make_transform_iterator( pos_order.end() , transform_functor( pos_hash ) );\n            cells_begin[ i ] = std::distance( pos_begin , std::lower_bound( pos_begin , pos_end , i ) );\n            cells_end[ i ] = std::distance( pos_begin , std::upper_bound( pos_begin , pos_end , i ) );\n        } );\n        \n        std::for_each(\n            boost::make_zip_iterator( boost::make_tuple(\n                x.begin() ,\n                v.begin() ,\n                a.begin() ,\n                pos_index.begin() ,\n                boost::counting_iterator< size_t >( 0 )\n            ) ) ,\n            boost::make_zip_iterator( boost::make_tuple(\n                x.end() ,\n                v.end() ,\n                a.end() ,\n                pos_index.end() ,\n                boost::counting_iterator< size_t >( m_p.n )\n            ) ) ,\n            interaction_functor( cells_begin , cells_end , pos_order , x , v , m_p ) );\n    }\n\n    void bc( point_vector &x )\n    {\n        for( size_t i=0 ; i<m_p.n ; ++i )\n        {\n            x[i][0] = periodic_bc( x[ i ][0] , m_p.x_max );\n            x[i][1] = periodic_bc( x[ i ][1] , m_p.y_max );\n        }\n    }\n    \n    static inline double periodic_bc( double x , double xmax )\n    {\n        double tmp = x - xmax * int( x / xmax );\n        return tmp >= 0.0 ? tmp : tmp + xmax;\n    }\n\n\n    static inline point_type periodic_bc( point_type const& x , params const& p ) \n    {\n        return point_type( periodic_bc( x[0] , p.x_max ) , periodic_bc( x[1] , p.y_max ) );\n    }\n\n\n    static inline int check_interval( int i , int max )\n    {\n        int tmp = i % max;\n        return tmp >= 0 ? tmp : tmp + max;\n    }\n\n\n    static inline size_t hash_func( index_type index , params const & p )\n    {\n        size_t i1 = check_interval( index[0] , p.n_cell_x );\n        size_t i2 = check_interval( index[1] , p.n_cell_y );\n        return i1 * p.n_cell_y + i2;\n    }\n    \n    params m_p;\n};\n\n\ntemplate< typename LocalForce , typename Interaction >\nmd_system_bs< LocalForce , Interaction > make_md_system_bs( size_t n , LocalForce const &f1 , Interaction const &f2 ,\n    double xmax = 100.0 , double ymax = 100.0 , double cell_size = 2.0 )\n{\n    return md_system_bs< LocalForce , Interaction >( n , f1 , f2 , xmax , ymax , cell_size );\n}\n\n\n\n\n\n\nusing namespace boost::numeric::odeint;\n\n\n\nint main( int argc , char *argv[] )\n{\n    const size_t n1 = 32;\n    const size_t n2 = 32;\n    const size_t n = n1 * n2;\n    auto sys = make_md_system_bs( n , local_force() , make_conservative_interaction( lennard_jones() ) , 100.0 , 100.0 , 2.0 );\n    typedef decltype( sys ) system_type;\n    typedef system_type::point_vector point_vector;\n    \n    std::mt19937 rng;\n    std::normal_distribution<> dist( 0.0 , 1.0 );\n    \n    point_vector x , v;\n    sys.init_point_vector( x );\n    sys.init_point_vector( v );\n    \n    for( size_t i=0 ; i<n1 ; ++i )\n    {\n        for( size_t j=0 ; j<n2 ; ++j )\n        {\n            size_t index = i * n2 + j; \n            x[index][0] = 10.0 + i * 2.0 ;\n            x[index][1] = 10.0 + j * 2.0 ;\n            v[index][0] = dist( rng ) ;\n            v[index][1] = dist( rng ) ;\n        }\n    }\n    \n    velocity_verlet< point_vector > stepper;\n    const double dt = 0.025;\n    double t = 0.0;\n    // std::cout << \"set term x11\" << endl;\n    for( size_t oi=0 ; oi<10000 ; ++oi )\n    {\n        for( size_t ii=0 ; ii<50 ; ++ii,t+=dt )\n            stepper.do_step( sys , std::make_pair( std::ref( x ) , std::ref( v ) ) , t , dt );\n        sys.bc( x );\n        \n        std::cout << \"set size square\" << \"\\n\";\n        std::cout << \"unset key\" << \"\\n\";\n        std::cout << \"p [0:\" << sys.m_p.x_max << \"][0:\" << sys.m_p.y_max << \"] '-' pt 7 ps 0.5\" << \"\\n\";\n        for( size_t i=0 ; i<n ; ++i )\n            std::cout << x[i][0] << \" \" << x[i][1] << \" \" << v[i][0] << \" \" << v[i][1] << \"\\n\";\n        std::cout << \"e\" << std::endl;\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "dcb7c5fda99cc9c97c0e5555adbefa19badadef7", "size": 11804, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/odeint/examples/molecular_dynamics_cells.cpp", "max_stars_repo_name": "cpp-pm/boost", "max_stars_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "libs/numeric/odeint/examples/molecular_dynamics_cells.cpp", "max_issues_repo_name": "cpp-pm/boost", "max_issues_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "libs/numeric/odeint/examples/molecular_dynamics_cells.cpp", "max_forks_repo_name": "cpp-pm/boost", "max_forks_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 31.0631578947, "max_line_length": 127, "alphanum_fraction": 0.5532023043, "num_tokens": 3199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059414036511, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4848906754866796}}
{"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_filter_linear_vs_x_test_suite.hpp\n * \\date July 2015\n * \\author Jan Issac (jan.issac@gmail.com)\n */\n\n#include <gtest/gtest.h>\n#include \"../typecast.hpp\"\n\n#include <Eigen/Dense>\n\n#include <cmath>\n#include <iostream>\n\n#include <fl/util/math/linear_algebra.hpp>\n#include <fl/filter/filter_interface.hpp>\n\n#include <fl/filter/gaussian/gaussian_filter_linear.hpp>\n#include <fl/model/transition/linear_transition.hpp>\n#include <fl/model/sensor/linear_gaussian_sensor.hpp>\n#include <fl/model/sensor/linear_decorrelated_gaussian_sensor.hpp>\n\nenum : signed int\n{\n    DecorrelatedGaussianModel,\n    GaussianModel\n};\n\nstatic constexpr double epsilon = 0.1;\n\ntemplate <typename TestType>\nclass GaussianFilterLinearVsXTest\n    : public ::testing::Test\n{\nprotected:\n    typedef typename TestType::Parameter Configuration;\n\n    enum: signed int\n    {\n        StateDim = Configuration::StateDim,\n        InputDim = Configuration::InputDim,\n        ObsrvDim = Configuration::ObsrvDim,\n\n        StateSize = fl::TestSize<StateDim, TestType>::Value,\n        InputSize = fl::TestSize<InputDim, TestType>::Value,\n        ObsrvSize = fl::TestSize<ObsrvDim, TestType>::Value\n    };\n\n    enum ModelSetup\n    {\n        Random,\n        Identity\n    };\n\n    typedef Eigen::Matrix<fl::Real, StateSize, 1> State;\n    typedef Eigen::Matrix<fl::Real, InputSize, 1> Input;\n    typedef Eigen::Matrix<fl::Real, ObsrvSize, 1> Obsrv;\n\n    typedef fl::IntegerTypeMap<\n                fl::IntegerTypePair<\n                    DecorrelatedGaussianModel,\n                    fl::LinearDecorrelatedGaussianSensor<Obsrv, State>\n                >,\n                fl::IntegerTypePair<\n                    GaussianModel,\n                    fl::LinearGaussianSensor<Obsrv, State>\n                >\n            > SensorMap;\n\n\n    typedef fl::LinearTransition<State, State, Input> LinearTransition;\n\n    typedef typename SensorMap::template Select<\n                Configuration::SelectedModel\n            >::Type LinearSensor;\n\n    typedef fl::GaussianFilter<\n                LinearTransition, LinearSensor\n            > KalmanFilter;\n\n    typedef typename Configuration::template FilterDefinition<\n                LinearTransition,\n                LinearSensor\n            > FilterDefinition;\n\n    typedef typename FilterDefinition::Type Filter;\n\n    GaussianFilterLinearVsXTest()\n        : predict_steps_(200),\n          predict_update_steps_(30)\n    { }\n\n    KalmanFilter create_kalman_filter() const\n    {\n        return KalmanFilter(\n                LinearTransition(StateDim, InputDim),\n                LinearSensor(ObsrvDim, StateDim));\n    }\n\n    Filter create_filter() const\n    {\n        return Configuration::create_filter(\n                LinearTransition(StateDim, InputDim),\n                LinearSensor(ObsrvDim, StateDim));\n    }\n\n    void setup_models(\n        KalmanFilter& kalman_filter, Filter& other_filter, ModelSetup setup)\n    {\n        auto A = kalman_filter.transition().create_dynamics_matrix();\n        auto B = kalman_filter.transition().create_input_matrix();\n        auto Q = kalman_filter.transition().create_noise_matrix();\n\n        auto H = kalman_filter.sensor().create_sensor_matrix();\n        auto R = kalman_filter.sensor().create_noise_matrix();\n\n        Q.setZero();\n        R.setZero();\n        B.setZero();\n\n        switch (setup)\n        {\n        case Random:\n            A.diagonal().setRandom();\n            H.diagonal().setRandom();\n            Q.diagonal().setRandom(); Q *= Q.transpose().eval();\n            R.diagonal().setRandom(); R *= R.transpose().eval();\n            break;\n\n        case Identity:\n            A.setIdentity();\n            H.setIdentity();\n            Q.setIdentity();\n            R.setIdentity();\n            break;\n        }\n\n        kalman_filter.transition().dynamics_matrix(A);\n        kalman_filter.transition().input_matrix(B);\n        kalman_filter.transition().noise_matrix(Q);\n        kalman_filter.sensor().sensor_matrix(H);\n        kalman_filter.sensor().noise_matrix(R);\n\n        other_filter.transition().dynamics_matrix(A);\n        other_filter.transition().input_matrix(B);\n        other_filter.transition().noise_matrix(Q);\n        other_filter.sensor().sensor_matrix(H);\n        other_filter.sensor().noise_matrix(R);\n    }\n\n    State zero_state() { return State::Zero(StateDim); }\n    Input zero_input() { return Input::Zero(InputDim); }\n    Obsrv zero_obsrv() { return Obsrv::Zero(ObsrvDim); }\n\n    State rand_state() { return State::Random(StateDim); }\n    Input rand_input() { return Input::Random(InputDim); }\n    Obsrv rand_obsrv() { return Obsrv::Random(ObsrvDim); }\n\nprotected:\n    int predict_steps_;\n    int predict_update_steps_;\n};\n\nTYPED_TEST_CASE_P(GaussianFilterLinearVsXTest);\n\n//TYPED_TEST_P(GaussianFilterLinearVsXTest, predict)\n//{\n//    typedef TestFixture This;\n\n//    auto other_filter = This::create_filter();\n//    auto kalman_filter = This::create_kalman_filter();\n\n//    This::setup_models(kalman_filter, other_filter, This::Random);\n\n//    auto belief_other = other_filter.create_belief();\n//    auto belief_kf = kalman_filter.create_belief();\n\n//    for (int i = 0; i < This::predict_steps_; ++i)\n//    {\n//        other_filter.predict(belief_other, This::zero_input(), belief_other);\n//        kalman_filter.predict(belief_kf, This::zero_input(), belief_kf);\n\n//        if (!fl::are_similar(belief_other.mean(), belief_kf.mean(), epsilon))\n//        {\n//            std::cout << \"i = \" << i << std::endl;\n//            PV(belief_kf.mean());\n//            PV(belief_other.mean());\n//        }\n\n//        if (!fl::are_similar(belief_other.covariance(), belief_kf.covariance(), epsilon))\n//        {\n//            std::cout << \"i = \" << i << std::endl;\n//            PV(belief_kf.covariance());\n//            PV(belief_other.covariance());\n//        }\n\n//        ASSERT_TRUE(\n//            fl::are_similar(belief_other.mean(), belief_kf.mean(), epsilon));\n\n//        ASSERT_TRUE(\n//            fl::are_similar(belief_other.covariance(), belief_kf.covariance(), epsilon));\n//    }\n\n//    PV(belief_kf.mean());\n//    PV(belief_other.mean());\n//    PV(belief_kf.covariance());\n//    PV(belief_other.covariance());\n//}\n\nTYPED_TEST_P(GaussianFilterLinearVsXTest, predict_and_update)\n{\n    typedef TestFixture This;\n\n    auto other_filter = This::create_filter();\n    auto kalman_filter = This::create_kalman_filter();\n\n    This::setup_models(kalman_filter, other_filter, This::Random);\n\n    auto belief_other = other_filter.create_belief();\n    auto belief_kf = kalman_filter.create_belief();\n\n    for (int i = 0; i < This::predict_update_steps_; ++i)\n    {\n        auto y = This::rand_obsrv();\n\n        kalman_filter.predict(belief_kf, This::zero_input(), belief_kf);\n        other_filter.predict(belief_other, This::zero_input(), belief_other);\n\n//        if (!fl::are_similar(belief_other.mean(), belief_kf.mean(), epsilon))\n//        {\n//            std::cout << \"predict i = \" << i << std::endl;\n//            PV(belief_kf.mean());\n//            PV(belief_other.mean());\n//        }\n\n//        if (!fl::are_similar(belief_other.covariance(), belief_kf.covariance(), epsilon))\n//        {\n//            std::cout << \"predict i = \" << i << std::endl;\n//            PV(belief_kf.covariance());\n//            PV(belief_other.covariance());\n//        }\n\n        kalman_filter.update(belief_kf, y, belief_kf);\n        other_filter.update(belief_other, y, belief_other);\n\n//        if (!fl::are_similar(belief_other.mean(), belief_kf.mean(), epsilon))\n//        {\n//            std::cout << \"update i = \" << i << std::endl;\n//            PV(belief_kf.mean());\n//            PV(belief_other.mean());\n//        }\n\n//        if (!fl::are_similar(belief_other.covariance(), belief_kf.covariance(), epsilon))\n//        {\n//            std::cout << \"update i = \" << i << std::endl;\n//            PV(belief_kf.covariance());\n//            PV(belief_other.covariance());\n//        }\n\n        ASSERT_TRUE(\n            fl::are_similar(belief_other.mean(), belief_kf.mean(), epsilon));\n\n        ASSERT_TRUE(\n            fl::are_similar(belief_other.covariance(), belief_kf.covariance(), epsilon));\n    }\n\n//    PV(belief_kf.mean());\n//    PV(belief_other.mean());\n\n//    PV(belief_kf.covariance());\n//    PV(belief_other.covariance());\n\n//    std::cout << other_filter.name() << std::endl;\n}\n\n\nREGISTER_TYPED_TEST_CASE_P(GaussianFilterLinearVsXTest,\n                           predict_and_update);\n", "meta": {"hexsha": "f946696a7d0623b6cb4cc3138e4b97679ef3ab6d", "size": 8891, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/gaussian_filter/gaussian_filter_linear_vs_x_test_suite.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": "test/gaussian_filter/gaussian_filter_linear_vs_x_test_suite.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": "test/gaussian_filter/gaussian_filter_linear_vs_x_test_suite.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": 30.448630137, "max_line_length": 91, "alphanum_fraction": 0.6145540434, "num_tokens": 2115, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768249, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.4848514238489398}}
{"text": "#include <iostream>\n#include <vector>\n#include <bitset>\n#include <random>\n#include <Eigen/Dense>\n#include \"utils.h\"\n#include \"SC.h\"\n \n//using Eigen::MatrixXd;\n\nstd::vector< std::vector<double> > SC_true_abs_err;\nstd::vector< std::vector<double> > SC_LFSR_abs_err;\nstd::vector< std::vector<double> > SC_LD_abs_err;\n\nstd::vector<double> SC_true_RMSE;\nstd::vector<double> SC_LFSR_RMSE;\nstd::vector<double> SC_LD_RMSE;\n\nvoid init()\n{\n    //fill the vector till position x\n\n    int size = 32;\n\n    SC_true_abs_err.reserve(size);\n    SC_LFSR_abs_err.reserve(size);\n    SC_LD_abs_err.reserve(size);\n\n    SC_true_RMSE.reserve(size);\n    SC_LFSR_RMSE.reserve(size);\n    SC_LD_RMSE.reserve(size);\n\n    std::vector<double> tmp(1);\n\n    for(int i = 0; i < size; i++)\n    {\n        SC_true_abs_err.push_back(tmp);\n        SC_LFSR_abs_err.push_back(tmp);\n        SC_LD_abs_err.push_back(tmp);\n\n        SC_true_RMSE.push_back(0);\n        SC_LFSR_RMSE.push_back(0);\n        SC_LD_RMSE.push_back(0);\n    }\n}\n\nvoid Test_utils_compare()\n{    \n    std::random_device rd;\n    std::mt19937 gen(rd());\n    std::uniform_real_distribution<> dis(-1.0, 1.0);\n\n    for(int i = 0; i < 1000; i++)\n    {\n        double tmp1 = dis(gen);\n        double tmp2 = dis(gen);\n\n        Complement a(16, tmp1);\n        Complement b(16, tmp2);\n\n        bool flag_true = tmp1 > tmp2 ? 1 : 0;\n        bool flag_compare = compare(a, b);\n\n        if(flag_true != flag_compare)\n        {\n            std::cout << flag_true << ' ' << flag_compare << std::endl;\n            std::cout << tmp1 << ' ' << tmp2 << std::endl;\n            compare(a, b, true);\n            return;\n        }\n    }\n\n    printf(\"unit test utils compare() done, all green\\n\");\n\n}\n\nvoid Test_SC_err(std::string RNG_type, int data_bits, int scaling_factor, int num)\n{\n    //return abs error and RMSE(Root Mean Squared Error) of different type of SN\n\n    std::random_device rd;\n    std::mt19937 gen(rd());\n    std::uniform_real_distribution<> dis(-8.0, 8.0);\n\n    SC sc(\"bipolar\", RNG_type, data_bits, scaling_factor);\n\n    //printf(\"%d start\\n\", data_bits);\n\n    std::vector<double> tmp_abs;\n    std::vector<double> tmp_RMSE;\n\n    tmp_abs.reserve(num);\n    tmp_RMSE.reserve(num);\n\n    for(int i = 0; i < num; i++)\n    {\n        double a = dis(gen);\n        double b = dis(gen);\n\n        double ans = sc.SC_Mul(a, b);\n\n        double abs_err = abs(ans - a * b);\n        tmp_abs.push_back(abs_err);\n        tmp_RMSE.push_back(abs_err * abs_err);\n    }\n\n    //printf(\"%d one done\\n\", data_bits);\n\n    if(RNG_type == \"true\")\n    {\n        SC_true_abs_err[data_bits] = tmp_abs;\n        SC_true_RMSE[data_bits] = Std_Dev(tmp_RMSE);\n    }\n\n    if(RNG_type == \"LFSR\")\n    {\n        SC_LFSR_abs_err[data_bits] = tmp_abs;\n        SC_LFSR_RMSE[data_bits] = Std_Dev(tmp_RMSE);\n    }\n\n    if(RNG_type == \"LD\")\n    {\n        SC_LD_abs_err[data_bits] = tmp_abs;\n        SC_LD_RMSE[data_bits] = Std_Dev(tmp_RMSE);\n    }\n}\n\nvoid Test_LFSR()\n{\n    LFSR lfsr(8);\n\n    for(int i = 0; i < 10; i++)\n        std::cout << lfsr.next() << std::endl;\n\n}\n\nvoid Test_SC_LFSR()\n{\n    SC sc(\"bipolar\", \"LFSR\", 16, 3);\n}\n\nvoid Test()\n{\n    SC sc(\"bipolar\", \"LFSR\", 3, 3);\n\n    double a = -4;\n    double b = 4;\n\n    double ans = sc.SC_Mul(a, b);\n\n    //printf(\"%lf\\n\", ans);\n}\n\nvoid write(int x, int y)\n{\n    //write results of data_bits x to data_bits y to file for storing\n\n    //true random\n    for(int i = 2; i <= 16; i++)\n        printf(\"%lf \", SC_true_RMSE[i]);\n\n    printf(\"\\n\");\n\n    //LFSR\n    for(int i = 2; i <= 16; i++)\n        printf(\"%lf \", SC_LFSR_RMSE[i]);\n\n    printf(\"\\n\");\n\n    //LD\n    for(int i = 2; i <= 16; i++)\n        printf(\"%lf \", SC_LD_RMSE[i]);\n\n    printf(\"\\n\");\n}\n\nint main()\n{\n    init();\n    \n    int trials = 10000;\n    \n    for(int i = 2; i <= 16; i++)\n    {\n        Test_SC_err(\"true\", i, 3, trials);\n        Test_SC_err(\"LFSR\", i, 3, trials);\n        Test_SC_err(\"LD\", i, 3, trials);\n    }\n    \n    write(2, 16);\n\n    //fwrite abs err\n    fwrite_vec(\"../data/results/true_abs_err_10k.out\", SC_true_abs_err);\n\n    fwrite_vec(\"../data/results/LFSR_abs_err_10k.out\", SC_LFSR_abs_err);\n\n    fwrite_vec(\"../data/results/Halton_abs_err_10k.out\", SC_LD_abs_err);\n\n    //fwrite RMSE\n    fwrite_vec(\"../data/results/true_RMSE_10k.out\", SC_true_RMSE);\n\n    fwrite_vec(\"../data/results/LFSR_RMSE_10k.out\", SC_LFSR_RMSE);\n\n    fwrite_vec(\"../data/results/Halton_RMSE_10k.out\", SC_LD_RMSE);\n\n    //Test();\n\n    //Test_SC_LFSR();\n\n    //Test_LFSR();\n\n    /*LD ld(3, 5); //ld(base, sequence_length)\n\n    for(int i = 0; i < 30; i++)\n    {\n        //ld.show_status();\n        //ld.update_status();\n        //ld.next();\n        std::cout << ld.next() << std::endl;\n    }\n    */\n\n    return 0;\n\n}", "meta": {"hexsha": "025a3fa0b4b8978a800900cfb0c0ce85bf33fa27", "size": 4703, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "codes/test.cpp", "max_stars_repo_name": "YAMWD/SC_CNN", "max_stars_repo_head_hexsha": "182e9e7daae27db2980d0df992914c18ee33a40a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-09T12:49:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-09T12:49:10.000Z", "max_issues_repo_path": "codes/test.cpp", "max_issues_repo_name": "YAMWD/SC_CNN", "max_issues_repo_head_hexsha": "182e9e7daae27db2980d0df992914c18ee33a40a", "max_issues_repo_licenses": ["MIT"], "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/test.cpp", "max_forks_repo_name": "YAMWD/SC_CNN", "max_forks_repo_head_hexsha": "182e9e7daae27db2980d0df992914c18ee33a40a", "max_forks_repo_licenses": ["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.9022222222, "max_line_length": 82, "alphanum_fraction": 0.5726132256, "num_tokens": 1427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.48485142384893976}}
{"text": "#include <iostream>\n#include <fstream>\n#include <vector>\n#include <Eigen/Dense>\n\nusing namespace std;\nusing namespace Eigen;\n\nvoid print_image(VectorXd image, int num_rows, int num_cols);\nvoid print_image_values(VectorXd image, int num_rows, int num_cols);\nvector<int> get_labels(string path);\nvector<VectorXd> get_images(string path);\nvector<VectorXd> get_output_vectors(vector<int> labels);\n", "meta": {"hexsha": "fc4ac48ebd1be868e6fdd6132cce7225e5c509b2", "size": 393, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/read_mnist.hpp", "max_stars_repo_name": "oojiang/Neural-Net-From-Scratch", "max_stars_repo_head_hexsha": "555847dee624c8f16ca6dd46b84e1114bdc0b4e3", "max_stars_repo_licenses": ["MIT"], "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/read_mnist.hpp", "max_issues_repo_name": "oojiang/Neural-Net-From-Scratch", "max_issues_repo_head_hexsha": "555847dee624c8f16ca6dd46b84e1114bdc0b4e3", "max_issues_repo_licenses": ["MIT"], "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/read_mnist.hpp", "max_forks_repo_name": "oojiang/Neural-Net-From-Scratch", "max_forks_repo_head_hexsha": "555847dee624c8f16ca6dd46b84e1114bdc0b4e3", "max_forks_repo_licenses": ["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.0714285714, "max_line_length": 68, "alphanum_fraction": 0.7938931298, "num_tokens": 86, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7248702880639792, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.4848514222308619}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   tstGaussKronrodIntegrator.cpp\n//! \\author Luke Kersting\n//! \\brief  Gauss-Kronrod quadrature integrator unit tests.\n//!\n//---------------------------------------------------------------------------//\n\n// Std Lib Includes\n#include <iostream>\n\n// Boost Includes\n#include <boost/function.hpp>\n#include <boost/bind.hpp>\n\n// Trilinos Includes\n#include <Teuchos_UnitTestHarness.hpp>\n#include <Teuchos_Array.hpp>\n\n// FRENSIE Includes\n#include \"Utility_GaussKronrodIntegrator.hpp\"\n\n//---------------------------------------------------------------------------//\n// Testing Functors\n//---------------------------------------------------------------------------//\nstruct X2Functor\n{\n  double operator()( const double x ) const\n  {\n    if( x >= 0.0 && x <= 1.0 )\n      return x*x;\n    else\n      return 0.0;\n  }\n  \n  static double getIntegratedValue()\n  {\n    return 1.0/3.0;\n  }\n\n  static double getLowerIntegratedValue()\n  {\n    return 1.0/24.0;\n  }\n\n  static double getUpperIntegratedValue()\n  {\n    return 7.0/24.0;\n  }\n};\n\nstruct X3Functor\n{\n  double operator()( const double x ) const\n  {\n    if( x >= 0.0 && x <= 1.0 )\n      return x*x*x;\n    else\n      return 0.0;\n  }\n\n  static double getIntegratedValue()\n  {\n    return 0.25;\n  }\n\n  static double getLowerIntegratedValue()\n  {\n    return 1.0/64.0;\n  }\n\n  static double getUpperIntegratedValue()\n  {\n    return 15.0/64.0;\n  }\n};\n\ndouble exp_neg_x( const double x )\n{\n  return exp( -x );\n}\n\ndouble exp_neg_abs_x( const double x, const double a )\n{\n  return exp( -a*fabs(x) );\n}\n\ndouble inv_sqrt_abs_x( const double x )\n{\n  return 1/sqrt(fabs(x));\n}\n\n//---------------------------------------------------------------------------//\n// Testing Structs.\n//---------------------------------------------------------------------------//\nclass TestGaussKronrodIntegrator : public Utility::GaussKronrodIntegrator\n{\npublic:\n  TestGaussKronrodIntegrator( const double relative_error_tol )\n    : Utility::GaussKronrodIntegrator( relative_error_tol )\n  { /* ... */ }\n\n  ~TestGaussKronrodIntegrator()\n  { /* ... */ }\n\n  // Allow public access to the GaussKronrodIntegrator protected member functions\n  using Utility::GaussKronrodIntegrator::calculateQuadratureIntegrandValuesAtAbscissa;\n  using Utility::GaussKronrodIntegrator::bisectAndIntegrateBinInterval;\n  using Utility::GaussKronrodIntegrator::rescaleAbsoluteError;\n  using Utility::GaussKronrodIntegrator::subintervalTooSmall;\n  using Utility::GaussKronrodIntegrator::checkRoundoffError;\n  using Utility::GaussKronrodIntegrator::sortBins;\n  using Utility::GaussKronrodIntegrator::getWynnEpsilonAlgorithmExtrapolation;\n};\n\n//---------------------------------------------------------------------------//\n// Instantiation macros.\n//---------------------------------------------------------------------------//\n#define UNIT_TEST_INSTANTIATION( type, name ) \\\n  TEUCHOS_UNIT_TEST_TEMPLATE_1_INSTANT( type, name, X2Functor ) \\\n  TEUCHOS_UNIT_TEST_TEMPLATE_1_INSTANT( type, name, X3Functor )\n\n//---------------------------------------------------------------------------//\n// Tests\n//---------------------------------------------------------------------------//\n// Check that functions can be integrated over [0,1]\nTEUCHOS_UNIT_TEST_TEMPLATE_1_DECL( GaussKronrodIntegrator,\n\t\t\t\t                   integrateWithPointRule,\n                                   Functor )\n{\n  Utility::GaussKronrodIntegrator gk_integrator( 1e-12 );\n  \n  double absolute_error, result_abs, result_asc, test_result, tol;\n  long double result;\n\n  Functor functor_instance;\n\n  gk_integrator.integrateWithPointRule<15>( functor_instance, \n                                        0.0,  \n                                        1.0,  \n                                        result,  \n                                        absolute_error,  \n                                        result_abs, \n                                        result_asc );\n\n  tol = absolute_error/result;\n  test_result = result;\n\n  TEST_FLOATING_EQUALITY( Functor::getIntegratedValue(), test_result, tol );\n\n  gk_integrator.integrateWithPointRule<21>( functor_instance, \n                                        0.0,  \n                                        1.0,  \n                                        result,  \n                                        absolute_error,  \n                                        result_abs, \n                                        result_asc );\n\n  tol = absolute_error/result;\n  test_result = result;\n\n  TEST_FLOATING_EQUALITY( Functor::getIntegratedValue(), test_result, tol );\n\n  gk_integrator.integrateWithPointRule<31>( functor_instance, \n                                        0.0,  \n                                        1.0,  \n                                        result,  \n                                        absolute_error,  \n                                        result_abs, \n                                        result_asc );\n\n  tol = absolute_error/result;\n  test_result = result;\n\n  TEST_FLOATING_EQUALITY( Functor::getIntegratedValue(), test_result, tol );\n\n  gk_integrator.integrateWithPointRule<41>( functor_instance, \n                                        0.0,  \n                                        1.0,  \n                                        result,  \n                                        absolute_error,  \n                                        result_abs, \n                                        result_asc );\n\n  tol = absolute_error/result;\n  test_result = result;\n\n  TEST_FLOATING_EQUALITY( Functor::getIntegratedValue(), test_result, tol );\n\n  gk_integrator.integrateWithPointRule<51>( functor_instance, \n                                        0.0,  \n                                        1.0,  \n                                        result,  \n                                        absolute_error,  \n                                        result_abs, \n                                        result_asc );\n\n  tol = absolute_error/result;\n  test_result = result;\n\n  TEST_FLOATING_EQUALITY( Functor::getIntegratedValue(), test_result, tol );\n\n  gk_integrator.integrateWithPointRule<61>( functor_instance, \n                                        0.0,  \n                                        1.0,  \n                                        result,  \n                                        absolute_error,  \n                                        result_abs, \n                                        result_asc );\n\n  tol = absolute_error/result;\n  test_result = result;\n\n  TEST_FLOATING_EQUALITY( Functor::getIntegratedValue(), test_result, tol );\n}\n\nUNIT_TEST_INSTANTIATION( GaussKronrodIntegrator, integrateWithPointRule );\n\n//---------------------------------------------------------------------------//\n// Check that quadrature integrand values can be evaulated at abscissa\nTEUCHOS_UNIT_TEST_TEMPLATE_1_DECL( GaussKronrodIntegrator,\n\t\t\t\t                   calculateQuadratureIntegrandValuesAtAbscissa,\n                                   Functor )\n{\n  TestGaussKronrodIntegrator test_integrator( 1e-12 );\n  \n  double half_length = 0.5;\n  double midpoint = 0.5;\n  double abscissa = 0.5;\n\n  double integrand_value_lower, integrand_value_upper ;\n\n  Functor functor_instance;\n\n  test_integrator.calculateQuadratureIntegrandValuesAtAbscissa( \n                functor_instance, \n                abscissa,\n                half_length,\n                midpoint,\n                integrand_value_lower,\n                integrand_value_upper );  \n\n\n  double tol = 1e-12;\n\n  TEST_FLOATING_EQUALITY( functor_instance( 0.25 ), integrand_value_lower, tol );\n  TEST_FLOATING_EQUALITY( functor_instance( 0.75 ), integrand_value_upper, tol );\n}\n\nUNIT_TEST_INSTANTIATION( GaussKronrodIntegrator, calculateQuadratureIntegrandValuesAtAbscissa );\n\n//---------------------------------------------------------------------------//\n// Check that quadrature integrand can be bisected and integrated\nTEUCHOS_UNIT_TEST_TEMPLATE_1_DECL( GaussKronrodIntegrator,\n\t\t\t\t                   bisectAndIntegrateBinInterval,\n                                   Functor )\n{\n  TestGaussKronrodIntegrator test_integrator( 1e-12 );\n  \n  Utility::BinTraits bin, bin_1, bin_2;\n\n  double bin_1_asc, bin_2_asc, tol_1, tol_2;\n\n  bin.lower_limit = 0.0;\n  bin.upper_limit = 1.0;\n  \n\n  Functor functor_instance;\n\n  test_integrator.bisectAndIntegrateBinInterval<15>( \n                functor_instance, \n                bin,\n                bin_1,\n                bin_2,\n                bin_1_asc,\n                bin_2_asc );  \n\n  tol_1 = bin_1.error/bin_1.result;\n  tol_2 = bin_2.error/bin_2.result;\n\n  TEST_FLOATING_EQUALITY( Functor::getLowerIntegratedValue(), \n                          static_cast<double>( bin_1.result ), \n                          tol_1 );\n  TEST_FLOATING_EQUALITY( Functor::getUpperIntegratedValue(),\n                          static_cast<double>( bin_2.result ), \n                          tol_2 );\n\n  TEST_EQUALITY( bin_1.lower_limit, bin.lower_limit );\n  TEST_FLOATING_EQUALITY( bin_1.upper_limit, 0.5, 1e-15);\n  TEST_FLOATING_EQUALITY( bin_2.lower_limit, 0.5, 1e-15 );\n  TEST_EQUALITY( bin_2.upper_limit, bin.upper_limit );\n\n\n  test_integrator.bisectAndIntegrateBinInterval<21>( \n                functor_instance, \n                bin,\n                bin_1,\n                bin_2,\n                bin_1_asc,\n                bin_2_asc );  \n\n  tol_1 = bin_1.error/bin_1.result;\n  tol_2 = bin_2.error/bin_2.result;\n\n  TEST_FLOATING_EQUALITY( Functor::getLowerIntegratedValue(), \n                          static_cast<double>( bin_1.result ), \n                          tol_1 );\n  TEST_FLOATING_EQUALITY( Functor::getUpperIntegratedValue(),\n                          static_cast<double>( bin_2.result ), \n                          tol_2 );\n\n\n  test_integrator.bisectAndIntegrateBinInterval<31>( \n                functor_instance, \n                bin,\n                bin_1,\n                bin_2,\n                bin_1_asc,\n                bin_2_asc );  \n\n  tol_1 = bin_1.error/bin_1.result;\n  tol_2 = bin_2.error/bin_2.result;\n\n  TEST_FLOATING_EQUALITY( Functor::getLowerIntegratedValue(), \n                          static_cast<double>( bin_1.result ), \n                          tol_1 );\n  TEST_FLOATING_EQUALITY( Functor::getUpperIntegratedValue(),\n                          static_cast<double>( bin_2.result ), \n                          tol_2 );\n\n\n  test_integrator.bisectAndIntegrateBinInterval<41>( \n                functor_instance, \n                bin,\n                bin_1,\n                bin_2,\n                bin_1_asc,\n                bin_2_asc );  \n\n  tol_1 = bin_1.error/bin_1.result;\n  tol_2 = bin_2.error/bin_2.result;\n\n  TEST_FLOATING_EQUALITY( Functor::getLowerIntegratedValue(), \n                          static_cast<double>( bin_1.result ), \n                          tol_1 );\n  TEST_FLOATING_EQUALITY( Functor::getUpperIntegratedValue(),\n                          static_cast<double>( bin_2.result ), \n                          tol_2 );\n\n\n  test_integrator.bisectAndIntegrateBinInterval<51>( \n                functor_instance, \n                bin,\n                bin_1,\n                bin_2,\n                bin_1_asc,\n                bin_2_asc );  \n\n  tol_1 = bin_1.error/bin_1.result;\n  tol_2 = bin_2.error/bin_2.result;\n\n  TEST_FLOATING_EQUALITY( Functor::getLowerIntegratedValue(), \n                          static_cast<double>( bin_1.result ), \n                          tol_1 );\n  TEST_FLOATING_EQUALITY( Functor::getUpperIntegratedValue(),\n                          static_cast<double>( bin_2.result ), \n                          tol_2 );\n\n\n  test_integrator.bisectAndIntegrateBinInterval<61>( \n                functor_instance, \n                bin,\n                bin_1,\n                bin_2,\n                bin_1_asc,\n                bin_2_asc );  \n\n  tol_1 = bin_1.error/bin_1.result;\n  tol_2 = bin_2.error/bin_2.result;\n\n  TEST_FLOATING_EQUALITY( Functor::getLowerIntegratedValue(), \n                          static_cast<double>( bin_1.result ), \n                          tol_1 );\n  TEST_FLOATING_EQUALITY( Functor::getUpperIntegratedValue(),\n                          static_cast<double>( bin_2.result ), \n                          tol_2 );\n}\n\nUNIT_TEST_INSTANTIATION( GaussKronrodIntegrator, bisectAndIntegrateBinInterval );\n\n//---------------------------------------------------------------------------//\n// Check that the error can be rescaled\nTEUCHOS_UNIT_TEST( GaussKronrodIntegrator, \n                   rescaleAbsoluteError )\n{\n  TestGaussKronrodIntegrator test_integrator( 1e-12 );\n  \n  double absolute_error = 0.0;\n  double result_abs = 0.0;\n  double result_asc = 0.0;\n  double tol = 1e-12;\n  double limit = std::numeric_limits<double>::min() / ( 50.0 *\n                   std::numeric_limits<double>::epsilon() );\n\n  absolute_error = limit/2.0;\n\n  test_integrator.rescaleAbsoluteError( \n                absolute_error, \n                result_abs,\n                result_asc );  \n\n  TEST_FLOATING_EQUALITY( limit/2.0, absolute_error, tol );\n\n\n  absolute_error = 1.0;\n  result_asc = 2.0;\n\n  test_integrator.rescaleAbsoluteError( \n                absolute_error, \n                result_abs,\n                result_asc );  \n\n  TEST_FLOATING_EQUALITY( 2.0, absolute_error, tol );\n\n\n  absolute_error = 1.0;\n  result_asc = 800.0;\n\n  test_integrator.rescaleAbsoluteError( \n                absolute_error, \n                result_abs,\n                result_asc );  \n\n  TEST_FLOATING_EQUALITY( 100.0, absolute_error, tol );\n\n\n  absolute_error = 50.0*std::numeric_limits<double>::epsilon();\n  result_asc = 0.0;\n  result_abs = 2.0;\n  double min_error = 50.0*std::numeric_limits<double>::epsilon() * result_abs;\n\n  test_integrator.rescaleAbsoluteError( \n                absolute_error, \n                result_abs,\n                result_asc );  \n\n  TEST_FLOATING_EQUALITY( min_error, absolute_error, tol );\n}\n\n//---------------------------------------------------------------------------//\n// Check the roundoff error\nTEUCHOS_UNIT_TEST( GaussKronrodIntegrator, \n                   checkRoundoffError )\n{\n  TestGaussKronrodIntegrator test_integrator( 1e-12 );\n  \n  Utility::BinTraits bin, bin_1, bin_2;\n  int round_off_1 = 0;\n  int round_off_2 = 0;\n  int number_of_interactions = 0;\n  double error_12 = 0.0, bin_1_asc = 0.0, bin_2_asc = 0.0;\n  double tol = 1e-12;\n\n  bin.result = 9.9999;\n  bin_1.result = 5.0;\n  bin_2.result = 5.0;\n\n  bin.error = 1.0;\n  bin_1.error = 0.5;\n  bin_2.error = 0.49;\n\n  bin_1_asc = bin_1.error;\n  bin_2_asc = bin_2.error;\n\n\n  test_integrator.checkRoundoffError( \n                bin, \n                bin_1,\n                bin_2,\n                bin_1_asc,\n                bin_2_asc,\n                round_off_1,\n                round_off_2,\n                number_of_interactions );  \n\n  TEST_EQUALITY_CONST( 0, round_off_1 );\n  TEST_EQUALITY_CONST( 0, round_off_2 );\n\n  bin_1_asc = 0.0;\n  bin_2_asc = 0.0;\n\n\n  test_integrator.checkRoundoffError( \n                bin, \n                bin_1,\n                bin_2,\n                bin_1_asc,\n                bin_2_asc,\n                round_off_1,\n                round_off_2,\n                number_of_interactions );  \n\n  TEST_EQUALITY_CONST( 1, round_off_1 );\n  TEST_EQUALITY_CONST( 0, round_off_2 );\n\n\n  bin_2.error = 0.501;\n  number_of_interactions = 10;\n\n  test_integrator.checkRoundoffError( \n                bin, \n                bin_1,\n                bin_2,\n                bin_1_asc,\n                bin_2_asc,\n                round_off_1,\n                round_off_2,\n                number_of_interactions );  \n\n  TEST_EQUALITY_CONST( 2, round_off_1 );\n  TEST_EQUALITY_CONST( 1, round_off_2 );\n\n\n  bin.result = 9.9;\n\n  test_integrator.checkRoundoffError( \n                bin, \n                bin_1,\n                bin_2,\n                bin_1_asc,\n                bin_2_asc,\n                round_off_1,\n                round_off_2,\n                number_of_interactions );  \n\n  TEST_EQUALITY_CONST( 2, round_off_1 );\n  TEST_EQUALITY_CONST( 2, round_off_2 );\n}\n\n//---------------------------------------------------------------------------//\n// Check the roundoff error\nTEUCHOS_UNIT_TEST( GaussKronrodIntegrator, \n                   checkRoundoffError2 )\n{\n  TestGaussKronrodIntegrator test_integrator( 1e-12 );\n  \n  Utility::ExtrpolatedBinTraits bin, bin_1, bin_2;\n  int round_off_1 = 0;\n  int round_off_2 = 0;\n  int round_off_3 = 0;\n  int number_of_interactions = 0;\n  bool extrapolate = false;\n  double error_12 = 0.0, bin_1_asc = 0.0, bin_2_asc = 0.0;\n  double tol = 1e-12;\n\n  bin.result = 9.9999;\n  bin_1.result = 5.0;\n  bin_2.result = 5.0;\n\n  bin.error = 1.0;\n  bin_1.error = 0.5;\n  bin_2.error = 0.49;\n\n  bin_1_asc = bin_1.error;\n  bin_2_asc = bin_2.error;\n\n\n  test_integrator.checkRoundoffError( \n                bin, \n                bin_1,\n                bin_2,\n                bin_1_asc,\n                bin_2_asc,\n                round_off_1,\n                round_off_2,\n                round_off_3,\n                extrapolate,\n                number_of_interactions );  \n\n  TEST_EQUALITY_CONST( 0, round_off_1 );\n  TEST_EQUALITY_CONST( 0, round_off_2 );\n  TEST_EQUALITY_CONST( 0, round_off_3 );\n\n  bin_1_asc = 0.0;\n  bin_2_asc = 0.0;\n\n\n  test_integrator.checkRoundoffError( \n                bin, \n                bin_1,\n                bin_2,\n                bin_1_asc,\n                bin_2_asc,\n                round_off_1,\n                round_off_2,\n                round_off_3,\n                extrapolate,\n                number_of_interactions );  \n\n  TEST_EQUALITY_CONST( 1, round_off_1 );\n  TEST_EQUALITY_CONST( 0, round_off_2 );\n  TEST_EQUALITY_CONST( 0, round_off_3 );\n\n  extrapolate = true;\n\n  test_integrator.checkRoundoffError( \n                bin, \n                bin_1,\n                bin_2,\n                bin_1_asc,\n                bin_2_asc,\n                round_off_1,\n                round_off_2,\n                round_off_3,\n                extrapolate,\n                number_of_interactions );  \n\n  TEST_EQUALITY_CONST( 1, round_off_1 );\n  TEST_EQUALITY_CONST( 1, round_off_2 );\n  TEST_EQUALITY_CONST( 0, round_off_3 );\n\n  bin_2.error = 0.501;\n  number_of_interactions = 10;\n\n  test_integrator.checkRoundoffError( \n                bin, \n                bin_1,\n                bin_2,\n                bin_1_asc,\n                bin_2_asc,\n                round_off_1,\n                round_off_2,\n                round_off_3,\n                extrapolate,\n                number_of_interactions );   \n\n  TEST_EQUALITY_CONST( 1, round_off_1 );\n  TEST_EQUALITY_CONST( 2, round_off_2 );\n  TEST_EQUALITY_CONST( 1, round_off_3 );\n\n\n  bin.result = 9.9;\n\n  test_integrator.checkRoundoffError( \n                bin, \n                bin_1,\n                bin_2,\n                bin_1_asc,\n                bin_2_asc,\n                round_off_1,\n                round_off_2,\n                round_off_3,\n                extrapolate,\n                number_of_interactions );   \n\n  TEST_EQUALITY_CONST( 1, round_off_1 );\n  TEST_EQUALITY_CONST( 2, round_off_2 );\n  TEST_EQUALITY_CONST( 2, round_off_3 );\n}\n\n//---------------------------------------------------------------------------//\n// Check that the error list can be sorted\nTEUCHOS_UNIT_TEST( GaussKronrodIntegrator, \n                   sortBins )\n{\n  TestGaussKronrodIntegrator test_integrator( 1e-12 );\n  \n  Utility::ExtrpolatedBinTraits bin, bin_1, bin_2;\n  \n  int nr_max = 0;\n  int number_of_intervals = 3;\n\n  // Set up bin order array\n  Teuchos::Array<int> bin_order(3);\n  bin_order[0] = 0;\n  bin_order[1] = 1;\n  bin_order[2] = 2;\n\n  // Set bin array\n  Utility::BinArray bin_array(1000);\n  bin.error = 10.0;\n  bin_array[0] = bin;\n  bin.error = 8.0;\n  bin_array[1] = bin;\n  bin.error = 1.0;\n  bin_array[2] = bin;\n\n  // Set bin_1 and bin_2\n  bin_1.error = 5.0;\n  bin_2.error = 2.0;\n \n  test_integrator.sortBins( \n                bin_order, \n                bin_array,\n                bin_1,\n                bin_2,\n                number_of_intervals,\n                nr_max );  \n\n  TEST_EQUALITY_CONST( 1, bin_order[0] );\n  TEST_EQUALITY_CONST( 0, bin_order[1] );\n  TEST_EQUALITY_CONST( 3, bin_order[2] );\n  TEST_EQUALITY_CONST( 2, bin_order[3] );\n  TEST_EQUALITY_CONST( 0, nr_max );\n\n  // Test with nr_max != 0\n  nr_max = 1;\n  number_of_intervals = 3;\n\n  // Set up bin order array\n  bin_order.resize(3);\n  bin_order[0] = 0;\n  bin_order[1] = 1;\n  bin_order[2] = 2;\n\n  // Set bin array\n  bin.error = 10.0;\n  bin_array[0] = bin;\n  bin.error = 8.0;\n  bin_array[1] = bin;\n  bin.error = 1.0;\n  bin_array[2] = bin;\n\n  // Set bin_1 and bin_2\n  bin_1.error = 11.0;\n  bin_2.error = 2.0;\n \n  test_integrator.sortBins( \n                bin_order, \n                bin_array,\n                bin_1,\n                bin_2,\n                number_of_intervals,\n                nr_max ); \n\n  TEST_EQUALITY_CONST( 1, bin_order[0] );\n  TEST_EQUALITY_CONST( 0, bin_order[1] );\n  TEST_EQUALITY_CONST( 3, bin_order[2] );\n  TEST_EQUALITY_CONST( 2, bin_order[3] );\n  TEST_EQUALITY_CONST( 0, nr_max );\n\n\n  // Test 3\n  nr_max = 0;\n  number_of_intervals = 3;\n\n  // Set up bin order array\n  bin_order.resize(3);\n  bin_order[0] = 1;\n  bin_order[1] = 0;\n  bin_order[2] = 2;\n\n  bin_array.clear();\n\n  // Set bin array\n  bin.error = 0.673651;\n  bin_array[0] = bin;\n  bin.error = 1.90537;\n  bin_array[1] = bin;\n  bin.error = 6.50354e-15;\n  bin_array[2] = bin;\n\n  // Set bin_1 and bin_2\n  bin_1.error = 0.673652;\n  bin_2.error = 6.50353e-15;\n\n  test_integrator.sortBins( \n                bin_order, \n                bin_array,\n                bin_1,\n                bin_2,\n                number_of_intervals,\n                nr_max ); \n\n  TEST_EQUALITY_CONST( 1, bin_order[0] );\n  TEST_EQUALITY_CONST( 0, bin_order[1] );\n  TEST_EQUALITY_CONST( 2, bin_order[2] );\n  TEST_EQUALITY_CONST( 3, bin_order[3] );\n  TEST_EQUALITY_CONST( 0, nr_max );\n\n  // Test 4\n  nr_max = 3;\n  number_of_intervals = 6;\n\n  // Set up bin order array\n  bin_order.resize(6);\n  bin_order[0] = 3;\n  bin_order[1] = 4;\n  bin_order[2] = 0;\n  bin_order[3] = 2;\n  bin_order[4] = 1;\n  bin_order[5] = 5;\n\n  bin_array.clear();\n\n  // Set bin array\n  bin.error = 4.0;\n  bin_array[0] = bin;\n  bin.error = 2.0;\n  bin_array[1] = bin;\n  bin.error = 3.0;\n  bin_array[2] = bin;\n  bin.error = 6.0;\n  bin_array[3] = bin;\n  bin.error = 5.0;\n  bin_array[4] = bin;\n  bin.error = 1.0;\n  bin_array[5] = bin;\n\n  // Set bin_1 and bin_2\n  bin_1.error = 2.5;\n  bin_2.error = 0.5;\n\n  test_integrator.sortBins( \n                bin_order, \n                bin_array,\n                bin_1,\n                bin_2,\n                number_of_intervals,\n                nr_max ); \n\n  TEST_EQUALITY_CONST( 3, bin_order[0] );\n  TEST_EQUALITY_CONST( 4, bin_order[1] );\n  TEST_EQUALITY_CONST( 0, bin_order[2] );\n  TEST_EQUALITY_CONST( 2, bin_order[3] );\n  TEST_EQUALITY_CONST( 1, bin_order[4] );\n  TEST_EQUALITY_CONST( 5, bin_order[5] );\n  TEST_EQUALITY_CONST( 6, bin_order[6] );\n  TEST_EQUALITY_CONST( 3, nr_max );\n\n  // Test 5\n  nr_max = 3;\n  number_of_intervals = 6;\n\n  // Set up bin order array\n  bin_order.resize(6);\n  bin_order[0] = 3;\n  bin_order[1] = 4;\n  bin_order[2] = 0;\n  bin_order[3] = 2;\n  bin_order[4] = 1;\n  bin_order[5] = 5;\n\n  bin_array.clear();\n\n  // Set bin array\n  bin.error = 4.0;\n  bin_array[0] = bin;\n  bin.error = 2.0;\n  bin_array[1] = bin;\n  bin.error = 3.0;\n  bin_array[2] = bin;\n  bin.error = 6.0;\n  bin_array[3] = bin;\n  bin.error = 5.0;\n  bin_array[4] = bin;\n  bin.error = 1.0;\n  bin_array[5] = bin;\n\n  // Set bin_1 and bin_2\n  bin_1.error = 4.5;\n  bin_2.error = 0.5;\n\n  test_integrator.sortBins( \n                bin_order, \n                bin_array,\n                bin_1,\n                bin_2,\n                number_of_intervals,\n                nr_max ); \n\n  TEST_EQUALITY_CONST( 3, bin_order[0] );\n  TEST_EQUALITY_CONST( 4, bin_order[1] );\n  TEST_EQUALITY_CONST( 2, bin_order[2] );\n  TEST_EQUALITY_CONST( 0, bin_order[3] );\n  TEST_EQUALITY_CONST( 1, bin_order[4] );\n  TEST_EQUALITY_CONST( 5, bin_order[5] );\n  TEST_EQUALITY_CONST( 6, bin_order[6] );\n  TEST_EQUALITY_CONST( 2, nr_max );\n}\n\n//---------------------------------------------------------------------------//\n// Check that the Wynn Epsilon-Algorithm extrapolated value can be calculated\nTEUCHOS_UNIT_TEST( GaussKronrodIntegrator, \n                   getWynnEpsilonAlgorithmExtrapolation )\n{\n  TestGaussKronrodIntegrator test_integrator( 1e-12 );\n  \n  Teuchos::Array<double> bin_extrapolated_result(52);\n  Teuchos::Array<double> last_three_results(3);\n  double extrapolated_result, extrapolated_error;\n  int number_of_extrapolated_intervals, number_of_extrapolated_calls;\n  double tol = 1e-16;\n  number_of_extrapolated_calls = 0;\n\n  // test 1\n  number_of_extrapolated_intervals = 2;\n  bin_extrapolated_result[0] = 3.93505142975913369L;\n  bin_extrapolated_result[1] = 3.95407442555431254L;\n  bin_extrapolated_result[2] = 3.96752571487956640L;\n \n  test_integrator.getWynnEpsilonAlgorithmExtrapolation( \n                bin_extrapolated_result, \n                last_three_results,\n                extrapolated_result,\n                extrapolated_error,\n                number_of_extrapolated_intervals,\n                number_of_extrapolated_calls ); \n\n  TEST_EQUALITY_CONST( number_of_extrapolated_intervals, 2 );\n  TEST_EQUALITY_CONST( number_of_extrapolated_calls, 1 ); \n  TEST_FLOATING_EQUALITY( extrapolated_error, \n                          std::numeric_limits<double>::max(), \n                          tol );\n  TEST_FLOATING_EQUALITY( extrapolated_result, \n                          3.99999999999999645, \n                          tol );\n  TEST_FLOATING_EQUALITY( last_three_results[0], \n                          3.99999999999999645, \n                          tol );\n  TEST_FLOATING_EQUALITY( last_three_results[1], \n                          0.0, \n                          tol );\n  TEST_FLOATING_EQUALITY( last_three_results[2], \n                          0.0, \n                          tol );\n\n  // test 2\n  number_of_extrapolated_intervals = 3;\n  bin_extrapolated_result[0] = 3.99999999999999645L;\n  bin_extrapolated_result[1] = 3.95407442555431254L;\n  bin_extrapolated_result[2] = 3.96752571487956640L;\n  bin_extrapolated_result[3] = 3.97703721277715605L;\n  bin_extrapolated_result[4] = 3.96752571487956640L;\n \n  test_integrator.getWynnEpsilonAlgorithmExtrapolation( \n                bin_extrapolated_result, \n                last_three_results,\n                extrapolated_result,\n                extrapolated_error,\n                number_of_extrapolated_intervals,\n                number_of_extrapolated_calls ); \n\n  TEST_EQUALITY_CONST( number_of_extrapolated_intervals, 3 );\n  TEST_EQUALITY_CONST( number_of_extrapolated_calls, 2 ); \n  TEST_FLOATING_EQUALITY( extrapolated_error, \n                          std::numeric_limits<double>::max(), \n                          tol );\n  TEST_FLOATING_EQUALITY( extrapolated_result, \n                          4.00000000000000355, \n                          tol );\n  TEST_FLOATING_EQUALITY( last_three_results[0], \n                          3.99999999999999645, \n                          tol );\n  TEST_FLOATING_EQUALITY( last_three_results[1], \n                          4.00000000000000355, \n                          tol );\n  TEST_FLOATING_EQUALITY( last_three_results[2], \n                          0.0, \n                          tol );\n\n\n  // test 3\n  number_of_extrapolated_intervals = 4;\n  bin_extrapolated_result[0] = 3.99999999999999645L;\n  bin_extrapolated_result[1] = 4.00000000000000355L;\n  bin_extrapolated_result[2] = 3.96752571487956640L;\n  bin_extrapolated_result[3] = 3.97703721277715605L;\n  bin_extrapolated_result[4] = 3.98376285743978320L;\n  bin_extrapolated_result[5] = 3.97703721277715605L;\n \n  test_integrator.getWynnEpsilonAlgorithmExtrapolation( \n                bin_extrapolated_result, \n                last_three_results,\n                extrapolated_result,\n                extrapolated_error,\n                number_of_extrapolated_intervals,\n                number_of_extrapolated_calls ); \n\n  TEST_EQUALITY_CONST( number_of_extrapolated_intervals, 4 );\n  TEST_EQUALITY_CONST( number_of_extrapolated_calls, 3 ); \n  TEST_FLOATING_EQUALITY( extrapolated_error, \n                          std::numeric_limits<double>::max(), \n                          tol );\n  TEST_FLOATING_EQUALITY( extrapolated_result, \n                          4.00000000000000089, \n                          tol );\n  TEST_FLOATING_EQUALITY( last_three_results[0], \n                          3.99999999999999645, \n                          tol );\n  TEST_FLOATING_EQUALITY( last_three_results[1], \n                          4.00000000000000355, \n                          tol );\n  TEST_FLOATING_EQUALITY( last_three_results[2], \n                          4.00000000000000089, \n                          tol );\n\n\n  // test 4\n  number_of_extrapolated_intervals = 5;\n  bin_extrapolated_result[0] = 4.00000000000000089L;\n  bin_extrapolated_result[1] = 4.00000000000000355L;\n  bin_extrapolated_result[2] = 3.99999999999999911L;\n  bin_extrapolated_result[3] = 3.97703721277715605L;\n  bin_extrapolated_result[4] = 3.98376285743978320L;\n  bin_extrapolated_result[5] = 3.98851860638857758L;\n  bin_extrapolated_result[6] = 3.98376285743978320L;\n\n \n  test_integrator.getWynnEpsilonAlgorithmExtrapolation( \n                bin_extrapolated_result, \n                last_three_results,\n                extrapolated_result,\n                extrapolated_error,\n                number_of_extrapolated_intervals,\n                number_of_extrapolated_calls ); \n\n  TEST_EQUALITY_CONST( number_of_extrapolated_intervals, 5 );\n  TEST_EQUALITY_CONST( number_of_extrapolated_calls, 4 ); \n  TEST_FLOATING_EQUALITY( extrapolated_error, \n                          5.68434188608080149e-14, \n                          tol );\n  TEST_FLOATING_EQUALITY( extrapolated_result, \n                          3.99999999999998135, \n                          tol );\n  TEST_FLOATING_EQUALITY( last_three_results[0], \n                          4.00000000000000355, \n                          tol );\n  TEST_FLOATING_EQUALITY( last_three_results[1], \n                          4.00000000000000089, \n                          tol );\n  TEST_FLOATING_EQUALITY( last_three_results[2], \n                          3.99999999999998135, \n                          tol );\n\n}\n\n//---------------------------------------------------------------------------//\n// Check that functions can be integrated over [0,1] adaptively\nTEUCHOS_UNIT_TEST_TEMPLATE_1_DECL( GaussKronrodIntegrator,\n\t\t\t\t   integrateAdaptively,\n\t\t\t\t   Functor )\n{\n  Utility::GaussKronrodIntegrator gk_integrator( 1e-12 );\n\n  double result, absolute_error, tol;\n\n  Functor functor_instance;\n\n  // Test the 15-point rule\n  gk_integrator.integrateAdaptively<15>( functor_instance, \n\t\t\t\t  0.0, \n\t\t\t\t  1.0, \n\t\t\t\t  result, \n\t\t\t\t  absolute_error );\n\n  tol = absolute_error/result;\n\n  TEST_FLOATING_EQUALITY( Functor::getIntegratedValue(), result, tol );\n\n\n  // Test the 21-point rule\n  gk_integrator.integrateAdaptively<21>( functor_instance, \n\t\t\t\t  0.0, \n\t\t\t\t  1.0, \n\t\t\t\t  result, \n\t\t\t\t  absolute_error );\n\n  tol = absolute_error/result;\n\n  TEST_FLOATING_EQUALITY( Functor::getIntegratedValue(), result, tol );\n\n\n  // Test the 31-point rule\n  gk_integrator.integrateAdaptively<31>( functor_instance, \n\t\t\t\t  0.0, \n\t\t\t\t  1.0, \n\t\t\t\t  result, \n\t\t\t\t  absolute_error );\n\n  tol = absolute_error/result;\n\n  TEST_FLOATING_EQUALITY( Functor::getIntegratedValue(), result, tol );\n\n\n  // Test the 41-point rule\n  gk_integrator.integrateAdaptively<41>( functor_instance, \n\t\t\t\t  0.0, \n\t\t\t\t  1.0, \n\t\t\t\t  result, \n\t\t\t\t  absolute_error );\n\n  tol = absolute_error/result;\n\n  TEST_FLOATING_EQUALITY( Functor::getIntegratedValue(), result, tol );\n\n\n  // Test the 51-point rule\n  gk_integrator.integrateAdaptively<51>( functor_instance, \n\t\t\t\t  0.0, \n\t\t\t\t  1.0, \n\t\t\t\t  result, \n\t\t\t\t  absolute_error );\n\n  tol = absolute_error/result;\n\n  TEST_FLOATING_EQUALITY( Functor::getIntegratedValue(), result, tol );\n\n\n  // Test the 61-point rule\n  gk_integrator.integrateAdaptively<61>( functor_instance, \n\t\t\t\t  0.0, \n\t\t\t\t  1.0, \n\t\t\t\t  result, \n\t\t\t\t  absolute_error );\n\n  tol = absolute_error/result;\n\n  TEST_FLOATING_EQUALITY( Functor::getIntegratedValue(), result, tol );\n}\n\nUNIT_TEST_INSTANTIATION( GaussKronrodIntegrator, integrateAdaptively );\n\n//---------------------------------------------------------------------------//\n// Check that a function with integrable singularities can be integrated\nTEUCHOS_UNIT_TEST( GaussKronrodIntegrator,\n\t\t   integrateAdaptivelyWynnEpsilon )\n{\n  boost::function<double (double x)> function_wrapper = inv_sqrt_abs_x;\n\n  Teuchos::Array<double> points_of_interest( 3 );\n  points_of_interest[0] = -1.0;\n  points_of_interest[1] = 0.0; // integrable singularity\n  points_of_interest[2] = 1.0;\n\n  Utility::GaussKronrodIntegrator gk_int( 1e-12, 0.0, 100000 );\n\n  double result, absolute_error;\n\n  gk_int.integrateAdaptivelyWynnEpsilon( function_wrapper,\n\t\t\t\t\t points_of_interest(),\n\t\t\t\t\t result,\n\t\t\t\t\t absolute_error );\n\n  \n  double tol = absolute_error/result;\n\n  TEST_FLOATING_EQUALITY( result, 4.0, tol );\n}\n\n//---------------------------------------------------------------------------//\n// Check that a function with no singularities can be integrated using Wynn Epsilon\nTEUCHOS_UNIT_TEST_TEMPLATE_1_DECL( GaussKronrodIntegrator,\n                                   integrateAdaptivelyWynnEpsilon_no_singularities,\n                                   Functor )\n{\n  Functor functor_instance;\n\n  Teuchos::Array<double> points_of_interest( 3 );\n  points_of_interest[0] = 0.0;\n  points_of_interest[1] = 0.5;\n  points_of_interest[2] = 1.0;\n\n  Utility::GaussKronrodIntegrator gkq_set( 1e-12, 0.0, 100000 );\n\n  double result, absolute_error;\n\n  gkq_set.integrateAdaptivelyWynnEpsilon( \n            functor_instance,\n    \t\tpoints_of_interest(),\n\t\t\tresult,\n\t\t\tabsolute_error );\n  \n  double tol = absolute_error/result;\n\n  TEST_FLOATING_EQUALITY( Functor::getIntegratedValue(), result, tol );\n}\n\nUNIT_TEST_INSTANTIATION( GaussKronrodIntegrator, integrateAdaptivelyWynnEpsilon_no_singularities );\n\n//---------------------------------------------------------------------------//\n// end tstGaussKronrodIntegrator.cpp\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "51e7183165eb227aa88e4d764ef777180433d736", "size": 34391, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "packages/utility/integrator/test/tstGaussKronrodIntegrator.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/utility/integrator/test/tstGaussKronrodIntegrator.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/utility/integrator/test/tstGaussKronrodIntegrator.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": 29.0464527027, "max_line_length": 99, "alphanum_fraction": 0.5618621151, "num_tokens": 8775, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.4848514190643594}}
{"text": "#include <iostream>\n#include <vector>\n#include <alglib/graph/undirected_graph.h>\n\nusing namespace std;\nusing namespace alglib::graph;\n\nint main() {\n\n    undirected_graph<string, int> G;\n\n    string c1 = \"Bikaner\";\n    string c2 = \"Bangalore\";\n    string c3 = \"Jaipur\";\n    string c4 = \"Hanumangarh\";\n    string c5 = \"Jodhpur\";\n\n\n    G.add_vertex(c2);\n    G.add_vertex(c1);\n    G.add_vertex(c3);\n    G.add_vertex(c4);\n    G.add_vertex(c5);\n\n    G.add_edge(c1, c2, 100);\n    G.add_edge(c5, c1, 250);\n\n    cout << \"No. of edges: \" << G.num_edges() << endl;\n    \n    cout << \"Cities adjacent to Bikaner: \";\n    for(auto it = G.avbegin(c1); it != G.avend(c1); it++)\n        cout << *it << \"\\t\";\n    cout << endl;\n\n\n    undirected_graph<int> G1;\n\n    G1.add_vertex(2);\n    G1.add_vertex(10);\n    G1.add_vertex(11);\n    G1.add_vertex(6);\n\n    G1.add_edge(3, 10);\n    G1.add_edge(10, 11);\n    G1.add_edge(6, 10);\n\n    cout << \"Numbers adjacent to 10: \";\n    for(auto it = G1.avbegin(10); it != G1.avend(10); it++) \n        cout << *it << \"\\t\";\n    cout << endl;\n}\n", "meta": {"hexsha": "5db6aecaf00b9e7bc2b54c5ee4274ad56107f4fc", "size": 1056, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/graph/undirected_graph.cpp", "max_stars_repo_name": "divkakwani/alglib", "max_stars_repo_head_hexsha": "464441c26ff802e0c7eb58106201c840dc37047b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-01-26T13:37:52.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-02T12:30:03.000Z", "max_issues_repo_path": "test/graph/undirected_graph.cpp", "max_issues_repo_name": "divkakwani/alglib", "max_issues_repo_head_hexsha": "464441c26ff802e0c7eb58106201c840dc37047b", "max_issues_repo_licenses": ["MIT"], "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/graph/undirected_graph.cpp", "max_forks_repo_name": "divkakwani/alglib", "max_forks_repo_head_hexsha": "464441c26ff802e0c7eb58106201c840dc37047b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-04-21T14:07:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T10:30:28.000Z", "avg_line_length": 20.3076923077, "max_line_length": 60, "alphanum_fraction": 0.5691287879, "num_tokens": 346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.6688802603710085, "lm_q1q2_score": 0.48485141906435936}}
{"text": "#include <hpx/hpx_init.hpp>\n#include <hpx/util/high_resolution_timer.hpp>\n#include <hpx/include/compute.hpp>\n#include <hpx/include/parallel_transform.hpp>\n\n#include <boost/program_options.hpp>\n\n#include <algorithm>\n#include <vector>\n#include <iostream>\n\n#define CALC_TYPE double\n\nvoid print_tile(std::vector<CALC_TYPE> A, std::string id, std::size_t row, std::size_t col, std::size_t N)\n{\n   for(int i = 0; i < N; ++i) {\n      for(int j = 0; j < N; ++j) {\n         std::ostringstream os;\n         os << id << \" \" << row * N + i << \" \" << col * N + j << \" \" << A[i * N + j] << std::endl;\n         std::cout << os.str();\n      }\n   }\n}\n\nstd::vector<CALC_TYPE> gen_tile(std::size_t row, std::size_t col, std::size_t N, std::size_t T)\n{\n   std::vector<CALC_TYPE> v;\n   v.resize(N * N);\n   std::srand(row * T + col);\n   for(int i = 0; i < N; ++i) {\n      for(int j = 0; j < N; ++j) {\n         v[i * N + j] = (double) (std::rand() % 10000 - 5000) / 1000;\n      }\n   }\n   return v;\n}\n\n//return inv\nstd::vector<CALC_TYPE> inversion(hpx::shared_future<std::vector<CALC_TYPE>> ft_A,\n                                 std::size_t N)\n{\n   auto A = ft_A.get();\n   double tmp;\n   std::vector<CALC_TYPE> v;\n   v.resize(N * N);\n\n   for(int i = 0; i < N; ++i) {\n      for(int j = 0; j < N; ++j) {\n         v[i * N + j] = 0;\n      }\n      v[i * N + i] = 1;\n   }\n   for(int k = 0; k < N; ++k) {\n      tmp = A[k * N + k];\n      for(int j = 0; j < N; ++j) {\n         v[k * N + j] /= tmp;\n         A[k * N + j] /= tmp;\n      }\n\n      // can be parallalized\n      for(int i = 0; i < k; ++i) {\n         tmp = A[i * N + k];\n         for(int j = 0; j < N; ++j) {\n            v[i * N + j] -= tmp * v[k * N + j];\n            A[i * N + j] -= tmp * A[k * N + j];\n         }\n      }\n      for(int i = k + 1; i < N; ++i) {\n         tmp = A[i * N + k];\n         for(int j = 0; j < N; ++j) {\n            v[i * N + j] -= tmp * v[k * N + j];\n            A[i * N + j] -= tmp * A[k * N + j];\n         }\n      }\n   }\n   return v;\n}\n\n//A = A * B\nstd::vector<CALC_TYPE> pmm(hpx::shared_future<std::vector<CALC_TYPE>> ft_A,\n                           hpx::shared_future<std::vector<CALC_TYPE>> ft_B,\n                           std::size_t N)\n{\n   std::vector<CALC_TYPE> v;\n   v.resize(N * N);\n   auto A = ft_A.get();\n   auto B = ft_B.get();\n\n   // i and j can be parallalized\n   for(int i = 0; i < N; ++i) {\n      for(int j = 0; j < N; ++j) {\n         v[i * N + j] = 0;\n         for(int k = 0; k < N; ++k) {\n            v[i * N + j] += A[i * N + k] * B[k * N + j];\n         }\n      }\n   }\n   return v;\n}\n\n//C = C - A * B\nstd::vector<CALC_TYPE> pmm_d(hpx::shared_future<std::vector<CALC_TYPE>> ft_A,\n                             hpx::shared_future<std::vector<CALC_TYPE>> ft_B,\n                             hpx::shared_future<std::vector<CALC_TYPE>> ft_C,\n                             std::size_t N)\n{\n   auto A = ft_A.get();\n   auto B = ft_B.get();\n   auto C = ft_C.get();\n\n   // i and j can be parallalized\n   for(int i = 0; i < N; ++i) {\n      for(int j = 0; j < N; ++j) {\n         for(int k = 0; k < N; ++k) {\n            C[i * N + j] -= A[i * N + k] * B[k * N + j];\n         }\n      }\n   }\n   return C;\n}\n\n\nvoid lu_tiled(std::vector<hpx::shared_future<std::vector<CALC_TYPE>>> &ft_tiles, std::size_t N, std::size_t T)\n{\n    std::vector<hpx::shared_future<std::vector<CALC_TYPE>>> ft_inv;\n    ft_inv.resize(T);\n\n    for (std::size_t k = 0; k < T - 1; ++k)\n    {\n       ft_inv[k] = hpx::dataflow(&inversion, ft_tiles[k * T + k], N);\n       for (std::size_t i = k + 1; i < T; ++i)\n       {\n          ft_tiles[i * T + k] = hpx::dataflow(&pmm, ft_tiles[i * T + k], ft_inv[k], N);\n          for (std::size_t j = k + 1; j < T; ++j)\n          {\n             ft_tiles[i * T + j] = hpx::dataflow(&pmm_d, ft_tiles[i * T + k], ft_tiles[k * T + j], ft_tiles[i * T + j], N);\n          }\n       }\n    }\n\n}\n\nint hpx_main(boost::program_options::variables_map& vm)\n{\n    std::size_t N = vm[\"N\"].as<std::size_t>();\n    std::size_t T = vm[\"T\"].as<std::size_t>();\n    std::string out = vm[\"out\"].as<std::string>();\n\n    hpx::util::high_resolution_timer t;\n\n    std::vector<hpx::shared_future<std::vector<CALC_TYPE>>> A_tiles;\n    A_tiles.resize(T * T);\n\n    for (std::size_t i = 0; i < T; ++i)\n    {\n       for (std::size_t j = 0; j < T; ++j)\n       {\n          A_tiles[i * T + j] = hpx::dataflow(&gen_tile, i, j, N, T);\n       }\n    }\n\n    if (out == \"debug\")\n    {\n       for (std::size_t i = 0; i < T; ++i)\n       {\n          for (std::size_t j = 0; j < T; ++j)\n          {\n             print_tile(A_tiles[i * T + j].get(), \"a\", i, j, N);\n          }\n       }\n    }\n\n    lu_tiled(A_tiles, N, T);\n\n    if (out == \"debug\")\n    {\n       for (std::size_t i = 0; i < T; ++i)\n       {\n          for (std::size_t j = 0; j < T; ++j)\n          {\n             print_tile(A_tiles[i * T + j].get(), \"lu\", i, j, N);\n          }\n       }\n    }\n\n    double elapsed = t.elapsed();\n    std::cout << \"Elapsed \" << elapsed << \" s\\n\";\n    return hpx::finalize();\n}\n\nint main(int argc, char* argv[])\n{\n    using namespace boost::program_options;\n\n    options_description desc_commandline;\n    desc_commandline.add_options()\n        (\"N\", value<std::size_t>()->default_value(10),\n         \"Dimension of each Tile (N*N elements per tile)\")\n        (\"T\", value<std::size_t>()->default_value(10),\n         \"Number of Tiles in each dimension (T*T tiles)\")\n        (\"out\", value<std::string>()->default_value(\"no\"),\n         \"(debug) => print matrices in coo format\")\n    ;\n\n    return hpx::init(desc_commandline, argc, argv);\n}\n", "meta": {"hexsha": "4f62abc2ea1771b8062ac9a78ff741cb56948d75", "size": 5546, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lu_tiled.cpp", "max_stars_repo_name": "jgurhem/HPX_LA", "max_stars_repo_head_hexsha": "22effbd77134b488104c0baa0d02feb282c5e251", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-07-26T12:42:13.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-26T12:42:13.000Z", "max_issues_repo_path": "lu_tiled.cpp", "max_issues_repo_name": "jgurhem/HPX_LA", "max_issues_repo_head_hexsha": "22effbd77134b488104c0baa0d02feb282c5e251", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lu_tiled.cpp", "max_forks_repo_name": "jgurhem/HPX_LA", "max_forks_repo_head_hexsha": "22effbd77134b488104c0baa0d02feb282c5e251", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.7922705314, "max_line_length": 123, "alphanum_fraction": 0.4646592138, "num_tokens": 1848, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702880639791, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.48485141744628135}}
{"text": "#ifndef TEST_UNIT_MATH_FWD_MAT_VECTORIZE_EXPECT_FWD_MATRIX_VALUE_HPP\n#define TEST_UNIT_MATH_FWD_MAT_VECTORIZE_EXPECT_FWD_MATRIX_VALUE_HPP\n\n#include <stan/math/fwd/mat.hpp>\n#include <math/fwd/mat/vectorize/build_fwd_matrix.hpp>\n#include <math/fwd/mat/vectorize/expect_val_deriv_eq.hpp>\n#include <Eigen/Dense>\n#include <vector>\n\ntemplate <typename F, typename T>\nvoid expect_fwd_matrix_value() {\n  using stan::math::fvar;\n  using std::vector;\n  typedef Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> matrix_t;\n\n  int num_inputs = F::valid_inputs().size();\n  int num_cols = 3;\n  matrix_t template_m(num_inputs, num_cols);\n\n  for (int i = 0; i < template_m.size(); ++i) {\n    matrix_t a = build_fwd_matrix<F>(template_m, i);\n    matrix_t fa = F::template apply<matrix_t>(a);\n    EXPECT_EQ(a.size(), fa.size());\n    expect_val_deriv_eq(F::apply_base(a(i)), fa(i));\n  }\n\n  size_t vector_matrix_size = 2;\n  for (size_t i = 0; i < vector_matrix_size; ++i) {\n    for (int j = 0; j < template_m.size(); ++j) {\n      vector<matrix_t> b;\n      for (size_t k = 0; k < vector_matrix_size; ++k)\n        if (k == i)\n          b.push_back(build_fwd_matrix<F>(template_m, j));\n        else\n          b.push_back(build_fwd_matrix<F>(template_m));\n      vector<matrix_t> fb = F::template apply<vector<matrix_t> >(b);\n      EXPECT_EQ(b.size(), fb.size());\n      EXPECT_EQ(b[i].size(), fb[i].size());\n      expect_val_deriv_eq(F::apply_base(b[i](j)), fb[i](j));\n    }\n  }\n\n  int seed_i = num_inputs + 1;\n  matrix_t a = build_fwd_matrix<F>(template_m, seed_i);\n  matrix_t fab = F::template apply<matrix_t>(a.block(1, 1, 1, 1));\n  expect_val_deriv_eq(F::apply_base(a(1, 1)), fab(0, 0));\n}\n\n#endif\n", "meta": {"hexsha": "6d1472bffdcc5ed31e2df53de48c3bebb4cb0ca5", "size": 1675, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "tests/math_unit/math/fwd/mat/vectorize/expect_fwd_matrix_value.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": "tests/math_unit/math/fwd/mat/vectorize/expect_fwd_matrix_value.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": "tests/math_unit/math/fwd/mat/vectorize/expect_fwd_matrix_value.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": 33.5, "max_line_length": 68, "alphanum_fraction": 0.6698507463, "num_tokens": 486, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.484851414279779}}
{"text": "/*\n * test_bresenham.cpp\n *\n * Test the Graph Library for Autonomous and Dynamic Systems\n *\n * author:  Cyril Robin <cyril.robin@laas.fr>\n * created: 2013-09-13\n * license: BSD\n */\n#define BOOST_TEST_MODULE const_string test\n#include <boost/test/included/unit_test.hpp>\n\n#include \"gladys/bresenham.hpp\"\n\nusing namespace gladys;\n\nBOOST_AUTO_TEST_SUITE( bresenham )\n\nBOOST_AUTO_TEST_CASE( test_bresenham )\n{\n    // two arbitrary points\n    gladys::point_xy_t s {  1, 1 } ;\n    gladys::point_xy_t t { 11, 5 } ;\n\n    // ascending line\n    gladys::points_t l = gladys::bresenham( s, t );\n\n    BOOST_TEST_MESSAGE( \"line 1 size = \" << l.size() );\n    BOOST_CHECK_EQUAL( l.size() , 11 );\n\n    // descending line\n    gladys::points_t m = gladys::bresenham( t, s );\n    BOOST_TEST_MESSAGE( \"line 2 size = \" << m.size() );\n    BOOST_CHECK_EQUAL( m.size() , 11 );\n\n    // m is the reverse of l\n    bool b = true;\n    for ( unsigned int i = 0 ; ( b && ( i < 11 )) ; i++ )\n        b = ( l[i][0] == m[10-i][0] && l[i][1] == m[10-i][1] ) ;\n    BOOST_TEST_MESSAGE( \"Check order \" );\n    BOOST_CHECK_EQUAL( b , true );\n\n    // Check one specific point\n    b =  ( l[4][0] == 5 && l[4][1] == 3 ) ;\n    BOOST_TEST_MESSAGE( \"Check the coordinate of some specific point\" );\n    BOOST_CHECK_EQUAL( b , true );\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "5e36c94351c2d6afa684e5892d534b0465c7a673", "size": 1318, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_bresenham.cpp", "max_stars_repo_name": "PBechon/gladys", "max_stars_repo_head_hexsha": "6a8313c33bd8cf0d73fae3d2845271039d234c91", "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": "test/test_bresenham.cpp", "max_issues_repo_name": "PBechon/gladys", "max_issues_repo_head_hexsha": "6a8313c33bd8cf0d73fae3d2845271039d234c91", "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": "test/test_bresenham.cpp", "max_forks_repo_name": "PBechon/gladys", "max_forks_repo_head_hexsha": "6a8313c33bd8cf0d73fae3d2845271039d234c91", "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.36, "max_line_length": 72, "alphanum_fraction": 0.6160849772, "num_tokens": 413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.72487026428967, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.48485140154411566}}
{"text": "#ifndef STAN_MATH_PRIM_MAT_PROB_MATRIX_NORMAL_PREC_RNG_HPP\n#define STAN_MATH_PRIM_MAT_PROB_MATRIX_NORMAL_PREC_RNG_HPP\n\n#include <stan/math/prim/meta.hpp>\n#include <stan/math/prim/mat/err/check_pos_semidefinite.hpp>\n#include <stan/math/prim/mat/err/check_symmetric.hpp>\n#include <stan/math/prim/mat/fun/Eigen.hpp>\n#include <stan/math/prim/scal/err/check_finite.hpp>\n#include <stan/math/prim/scal/err/check_positive.hpp>\n#include <stan/math/prim/scal/err/check_size_match.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n\nnamespace stan {\nnamespace math {\n\n/** \\ingroup multivar_dists\n * Sample from the the matrix normal distribution for the given Mu,\n * Sigma and D where Sigma and D are given as precision matrices, not\n * covariance matrices.\n *\n * @param Mu The mean matrix.\n * @param Sigma The mxm inverse covariance matrix (i.e., the precision\n * matrix) of the rows of y.\n * @param D The nxn inverse covariance matrix (i.e., the precision\n * matrix) of the columns of y.\n * @param rng Pseudo-random number generator.\n * @return A sample from the distribution, of type Matrix<double,\n * Dynamic, Dynamic>.\n * @throw std::invalid_argument if Sigma or D are not square.\n * @throw std::domain_error if Sigma or D are not symmetric, not\n * semi-positive definite, or if they contain infinities or NaNs.\n * @tparam RNG Type of pseudo-random number generator.\n */\ntemplate <class RNG>\ninline Eigen::MatrixXd matrix_normal_prec_rng(const Eigen::MatrixXd &Mu,\n                                              const Eigen::MatrixXd &Sigma,\n                                              const Eigen::MatrixXd &D,\n                                              RNG &rng) {\n  using boost::normal_distribution;\n  using boost::variate_generator;\n\n  static const char *function = \"matrix_normal_prec_rng\";\n\n  check_positive(function, \"Sigma rows\", Sigma.rows());\n  check_finite(function, \"Sigma\", Sigma);\n  check_symmetric(function, \"Sigma\", Sigma);\n\n  check_positive(function, \"D rows\", D.rows());\n  check_finite(function, \"D\", D);\n  check_symmetric(function, \"D\", D);\n\n  check_size_match(function, \"Rows of location parameter\", Mu.rows(),\n                   \"Rows of Sigma\", Sigma.rows());\n  check_size_match(function, \"Columns of location parameter\", Mu.cols(),\n                   \"Rows of D\", D.rows());\n\n  check_finite(function, \"Location parameter\", Mu);\n\n  Eigen::LDLT<Eigen::MatrixXd> Sigma_ldlt(Sigma);\n  // Sigma = PS^T LS DS LS^T PS\n  // PS a permutation matrix.\n  // LS lower triangular with unit diagonal.\n  // DS diagonal.\n  Eigen::LDLT<Eigen::MatrixXd> D_ldlt(D);\n  // D = PD^T LD DD LD^T PD\n\n  check_pos_semidefinite(function, \"Sigma\", Sigma_ldlt);\n  check_pos_semidefinite(function, \"D\", D_ldlt);\n\n  // If\n  // C ~ N[0, I, I]\n  // Then\n  // A C B ~ N[0, A A^T, B^T B]\n  // So to get\n  // Y - Mu ~ N[0, Sigma^(-1), D^(-1)]\n  // We need to do\n  // Y - Mu = Q^T^(-1) C R^(-1)\n  // Where Q^T^(-1) and R^(-1) are such that\n  // Q^(-1) Q^(-1)^T = Sigma^(-1)\n  // R^(-1)^T R^(-1) = D^(-1)\n  // We choose:\n  // Q^(-1)^T = PS^T LS^T^(-1) sqrt[DS]^(-1)\n  // R^(-1) = sqrt[DD]^(-1) LD^(-1) PD\n  // And therefore\n  // Y - Mu = (PS^T LS^T^(-1) sqrt[DS]^(-1)) C (sqrt[DD]^(-1) LD^(-1) PD)\n\n  int m = Sigma.rows();\n  int n = D.rows();\n\n  variate_generator<RNG &, normal_distribution<>> std_normal_rng(\n      rng, normal_distribution<>(0, 1));\n\n  // X = sqrt[DS]^(-1) C sqrt[DD]^(-1)\n  // X ~ N[0, DS, DD]\n  Eigen::MatrixXd X(m, n);\n  Eigen::VectorXd row_stddev\n      = Sigma_ldlt.vectorD().array().inverse().sqrt().matrix();\n  Eigen::VectorXd col_stddev\n      = D_ldlt.vectorD().array().inverse().sqrt().matrix();\n  for (int row = 0; row < m; ++row) {\n    for (int col = 0; col < n; ++col) {\n      double stddev = row_stddev(row) * col_stddev(col);\n      // C(row, col) = std_normal_rng();\n      X(row, col) = stddev * std_normal_rng();\n    }\n  }\n\n  // Y - Mu = PS^T (LS^T^(-1) X LD^(-1)) PD\n  // Y' = LS^T^(-1) X LD^(-1)\n  // Y' = LS^T.solve(X) LD^(-1)\n  // Y' = (LD^(-1)^T (LS^T.solve(X))^T)^T\n  // Y' = (LD^T.solve((LS^T.solve(X))^T))^T\n  // Y = Mu + PS^T Y' PD\n  Eigen::MatrixXd Y = Mu\n                      + (Sigma_ldlt.transpositionsP().transpose()\n                         * (D_ldlt.matrixU().solve(\n                                (Sigma_ldlt.matrixU().solve(X)).transpose()))\n                               .transpose()\n                         * D_ldlt.transpositionsP());\n\n  return Y;\n}\n}  // namespace math\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "6d08c20e4e604cd2ecabd67c45ab7b2a62d5e4d9", "size": 4486, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/prim/mat/prob/matrix_normal_prec_rng.hpp", "max_stars_repo_name": "StrayDoki/math", "max_stars_repo_head_hexsha": "2f2f99759b822e3c8467d3efc56e781125067eb6", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/matrix_normal_prec_rng.hpp", "max_issues_repo_name": "StrayDoki/math", "max_issues_repo_head_hexsha": "2f2f99759b822e3c8467d3efc56e781125067eb6", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/matrix_normal_prec_rng.hpp", "max_forks_repo_name": "StrayDoki/math", "max_forks_repo_head_hexsha": "2f2f99759b822e3c8467d3efc56e781125067eb6", "max_forks_repo_licenses": ["BSD-3-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.3228346457, "max_line_length": 77, "alphanum_fraction": 0.6087828801, "num_tokens": 1299, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042768, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.48482101728123356}}
{"text": "// Boost.Geometry\n\n// 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\n#include <geometry_test_common.hpp>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/geometries.hpp>\n#include <boost/geometry/srs/epsg.hpp>\n#include <boost/geometry/srs/transformation.hpp>\n\n#include \"check_geometry.hpp\"\n\ntemplate <typename T>\nvoid test_issue_657()\n{\n    using namespace boost::geometry;\n    using namespace boost::geometry::model;\n    using namespace boost::geometry::srs;\n\n    typedef model::point<T, 2, bg::cs::cartesian> point_car;\n    typedef model::point<T, 2, cs::geographic<bg::degree> > point_geo;\n    \n    transformation<> tr1((bg::srs::epsg(4326)),\n                         (bg::srs::proj4(\n                             \"+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 \"\n                             \"+y_0=0 +k=1.0 +units=m +nadgrids=@null +wktext  +no_defs\")));\n    transformation<> tr2((bg::srs::epsg(4326)),\n                         (bg::srs::epsg(3785)));\n    transformation<bg::srs::static_epsg<4326>,\n                   bg::srs::static_epsg<3785> > tr3;\n\n    point_geo pt(-114.7399212, 36.0160698);\n    point_car pt_out(-12772789.6016, 4302832.77709);\n    point_car pt_out1, pt_out2, pt_out3;\n\n    tr1.forward(pt, pt_out1);\n    tr2.forward(pt, pt_out2);\n    tr3.forward(pt, pt_out3);\n\n    test::check_geometry(pt_out1, pt_out, 0.001);\n    test::check_geometry(pt_out2, pt_out, 0.001);\n    test::check_geometry(pt_out3, pt_out, 0.001);\n}\n\nint test_main(int, char*[])\n{\n    test_issue_657<double>();\n    \n    return 0;\n}\n", "meta": {"hexsha": "c57726d0339c3d76df83ba36db1df6703ccf7984", "size": 1820, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/srs/transformation_epsg.cpp", "max_stars_repo_name": "jkerkela/geometry", "max_stars_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 326.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T13:47:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T02:13:59.000Z", "max_issues_repo_path": "test/srs/transformation_epsg.cpp", "max_issues_repo_name": "jkerkela/geometry", "max_issues_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 623.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T23:45:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T11:15:23.000Z", "max_forks_repo_path": "Libs/boost_1_76_0/libs/geometry/test/srs/transformation_epsg.cpp", "max_forks_repo_name": "Antd23rus/S2DE", "max_forks_repo_head_hexsha": "47cc7151c2934cd8f0399a9856c1e54894571553", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-01-14T15:50:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T03:58:36.000Z", "avg_line_length": 31.3793103448, "max_line_length": 96, "alphanum_fraction": 0.6494505495, "num_tokens": 542, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4848210172812335}}
{"text": "#include <iostream>\n#include \"Sensor.h\"\n#include \"Thruster.h\"\n#include \"Body.h\"\n\n#include <Eigen/Eigen/Dense>\n\nusing namespace Eigen;\n\nint main(){\n\tBody bod(Vector3d(0,0,0),Vector3d(0,0.5,0.1),2,1);\n\tfor(int i = 0; i < 100; i++){\n\t\tbod.Update(0.01);\n\t\tstd::cout<<bod.getPos()<<std::endl;\n\t}\n}\n\n", "meta": {"hexsha": "13404c78e2fe40d8859e5169465c028fa4b23532", "size": 294, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "Achierius/SysSim", "max_stars_repo_head_hexsha": "067c32a3a03418819d11284db4050fdb43505abc", "max_stars_repo_licenses": ["MIT"], "max_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": "Achierius/SysSim", "max_issues_repo_head_hexsha": "067c32a3a03418819d11284db4050fdb43505abc", "max_issues_repo_licenses": ["MIT"], "max_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": "Achierius/SysSim", "max_forks_repo_head_hexsha": "067c32a3a03418819d11284db4050fdb43505abc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.3333333333, "max_line_length": 51, "alphanum_fraction": 0.6326530612, "num_tokens": 106, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4848210172812335}}
{"text": "#pragma once\n\n#include <CCD/Rational.hpp>\n#include <Eigen/Core>\n#include <array>\n#include <vector>\n\n#include <cfenv>\n\nnamespace ccd {\n\ntypedef Eigen::Matrix<Rational, 3, 1, Eigen::ColMajor | Eigen::DontAlign>\n    Vector3r;\ntypedef Eigen::Matrix<double, 3, 1> Vector3d;\nstatic const int COPLANAR = -1;\nstatic const int INTERSECTED = 1;\nstatic const int NOT_INTERSECTED1 = 2;\nstatic const int NOT_INTERSECTED2 = 3;\nstatic const Vector3r ORIGIN = Vector3r(0, 0, 0);\n\nstatic const int BI_DEGE_PLANE = 1;\nstatic const int BI_DEGE_XOR_02 = 2;\nstatic const int BI_DEGE_XOR_13 = 3;\n\nclass bilinear {\npublic:\n    // v0, v1 are vertices of one triangle, v2, v3 are the vertices of another\n    // one.\n    bilinear(\n        const Vector3r& v0,\n        const Vector3r& v1,\n        const Vector3r& v2,\n        const Vector3r& v3);\n    bool is_degenerated;\n    std::vector<std::array<int, 3>> facets;\n    std::array<int, 2> phi_f = { { 2, 2 } };\n    std::array<Vector3r, 4> v;\n};\ntemplate <typename V1, typename V2> Vector3r cross(const V1& v1, const V2& v2)\n{\n    Vector3r res;\n    res[0] = v1[1] * v2[2] - v1[2] * v2[1];\n    res[1] = v1[2] * v2[0] - v1[0] * v2[2];\n    res[2] = v1[0] * v2[1] - v1[1] * v2[0];\n\n    return res;\n}\n\nVector3r sum(const Vector3r& a, const Vector3r& b);\nRational func_g(\n    const Vector3r& x,\n    const std::array<Vector3r, 4>& corners,\n    const std::array<int, 3>& indices);\n\nRational phi(const Vector3r x, const std::array<Vector3r, 4>& corners);\n\nvoid get_tet_phi(bilinear& bl);\n// bool XOR(const bool a, const bool b)\n//{\n//    if (a && b)\n//        return false;\n//    if (!a && !b)\n//        return false;\n//    return true;\n//}\n\n// accept 0,1,2,3 as inputs\nbool int_seg_XOR(const int a, const int b);\n\n// accept -1,0,1,2,3 as inputs\nint int_ray_XOR(const int a, const int b);\ntemplate <typename V> void print(const V& v)\n{\n    std::cout << v[0] << \" \" << v[1] << \" \" << v[2] << std::endl;\n}\n\nvoid write(const Vector3d& v, std::ostream& out);\nVector3d read(std::istream& in);\n\nint orient3d(\n    const Vector3r& a, const Vector3r& b, const Vector3r& c, const Vector3r& d);\nint orient2d(\n    const Vector3r& a, const Vector3r& b, const Vector3r& c, const int axis);\n\nbool segment_segment_intersection(\n    const Vector3r& s0,\n    const Vector3r& e0,\n    const Vector3r& s1,\n    const Vector3r& e1);\n// 0 not intersected, 1 intersected, 2 s0 on segment\n// can deal with degenerated cases\nint ray_segment_intersection(\n    const Vector3r& s0,\n    const Vector3r& dir0,\n    const Vector3r& s1,\n    const Vector3r& e1);\n\n// this function can also tell us if they are parallel and overlapped\n// and also tell us if the parallel case has seg-seg overlapping:\n\nbool same_point(const Vector3r& p1, const Vector3r& p2);\nVector3r tri_norm(const Vector3r& t0, const Vector3r& t1, const Vector3r& t2);\n\ntemplate <typename T>\nstatic bool orient3D_LPI_prefilter_multiprecision(\n    const T& px,\n    const T& py,\n    const T& pz,\n    const T& qx,\n    const T& qy,\n    const T& qz,\n    const T& rx,\n    const T& ry,\n    const T& rz,\n    const T& sx,\n    const T& sy,\n    const T& sz,\n    const T& tx,\n    const T& ty,\n    const T& tz,\n    T& a11,\n    T& a12,\n    T& a13,\n    T& d,\n    const std::function<int(T)>& checker)\n{\n\n    a11 = (px - qx);\n    a12 = (py - qy);\n    a13 = (pz - qz);\n    T a21(sx - rx);\n    T a22(sy - ry);\n    T a23(sz - rz);\n    T a31(tx - rx);\n    T a32(ty - ry);\n    T a33(tz - rz);\n    T a2233((a22 * a33) - (a23 * a32));\n    T a2133((a21 * a33) - (a23 * a31));\n    T a2132((a21 * a32) - (a22 * a31));\n    d = (((a11 * a2233) - (a12 * a2133)) + (a13 * a2132));\n    int flag1 = checker(d);\n    if (flag1 == -2 || flag1 == 0) {\n        return false; // not enough precision\n    }\n    T px_rx(px - rx);\n    T py_ry(py - ry);\n    T pz_rz(pz - rz);\n\n    T n((((py_ry)*a2133) - ((px_rx)*a2233)) - ((pz_rz)*a2132));\n\n    a11 = a11 * n;\n    a12 = a12 * n;\n    a13 = a13 * n;\n    return true;\n}\n\ntemplate <typename T>\nstatic bool orient3D_TPI_prefilter_multiprecision(\n    const T& ov1x,\n    const T& ov1y,\n    const T& ov1z,\n    const T& ov2x,\n    const T& ov2y,\n    const T& ov2z,\n    const T& ov3x,\n    const T& ov3y,\n    const T& ov3z,\n    const T& ow1x,\n    const T& ow1y,\n    const T& ow1z,\n    const T& ow2x,\n    const T& ow2y,\n    const T& ow2z,\n    const T& ow3x,\n    const T& ow3y,\n    const T& ow3z,\n    const T& ou1x,\n    const T& ou1y,\n    const T& ou1z,\n    const T& ou2x,\n    const T& ou2y,\n    const T& ou2z,\n    const T& ou3x,\n    const T& ou3y,\n    const T& ou3z,\n    T& d,\n    T& n1,\n    T& n2,\n    T& n3,\n    const std::function<int(T)>& checker)\n{\n    ::feclearexcept(FE_UNDERFLOW | FE_OVERFLOW | FE_INVALID);\n\n    T v3x(ov3x - ov2x);\n    T v3y(ov3y - ov2y);\n    T v3z(ov3z - ov2z);\n    T v2x(ov2x - ov1x);\n    T v2y(ov2y - ov1y);\n    T v2z(ov2z - ov1z);\n    T w3x(ow3x - ow2x);\n    T w3y(ow3y - ow2y);\n    T w3z(ow3z - ow2z);\n    T w2x(ow2x - ow1x);\n    T w2y(ow2y - ow1y);\n    T w2z(ow2z - ow1z);\n    T u3x(ou3x - ou2x);\n    T u3y(ou3y - ou2y);\n    T u3z(ou3z - ou2z);\n    T u2x(ou2x - ou1x);\n    T u2y(ou2y - ou1y);\n    T u2z(ou2z - ou1z);\n\n    T nvx(v2y * v3z - v2z * v3y);\n    T nvy(v3x * v2z - v3z * v2x);\n    T nvz(v2x * v3y - v2y * v3x);\n\n    T nwx(w2y * w3z - w2z * w3y);\n    T nwy(w3x * w2z - w3z * w2x);\n    T nwz(w2x * w3y - w2y * w3x);\n\n    T nux(u2y * u3z - u2z * u3y);\n    T nuy(u3x * u2z - u3z * u2x);\n    T nuz(u2x * u3y - u2y * u3x);\n\n    T nwyuz(nwy * nuz - nwz * nuy);\n    T nwxuz(nwx * nuz - nwz * nux);\n    T nwxuy(nwx * nuy - nwy * nux);\n\n    T nvyuz(nvy * nuz - nvz * nuy);\n    T nvxuz(nvx * nuz - nvz * nux);\n    T nvxuy(nvx * nuy - nvy * nux);\n\n    T nvywz(nvy * nwz - nvz * nwy);\n    T nvxwz(nvx * nwz - nvz * nwx);\n    T nvxwy(nvx * nwy - nvy * nwx);\n\n    d = (nvx * nwyuz - nvy * nwxuz + nvz * nwxuy);\n\n    int flag1 = checker(d);\n    if (flag1 == -2 || flag1 == 0) {\n        return false; // not enough precision\n    }\n\n    T p1(nvx * ov1x + nvy * ov1y + nvz * ov1z);\n    T p2(nwx * ow1x + nwy * ow1y + nwz * ow1z);\n    T p3(nux * ou1x + nuy * ou1y + nuz * ou1z);\n\n    n1 = p1 * nwyuz - p2 * nvyuz + p3 * nvywz;\n    n2 = p2 * nvxuz - p3 * nvxwz - p1 * nwxuz;\n    n3 = p3 * nvxwy - p2 * nvxuy + p1 * nwxuy;\n    return true;\n}\n\ntemplate <typename T>\nstatic int orient3D_LPI_postfilter_multiprecision(\n    const T& a11,\n    const T& a12,\n    const T& a13,\n    const T& d,\n    const T& px,\n    const T& py,\n    const T& pz,\n    const T& ax,\n    const T& ay,\n    const T& az,\n    const T& bx,\n    const T& by,\n    const T& bz,\n    const T& cx,\n    const T& cy,\n    const T& cz,\n    const std::function<int(T)>& checker)\n{\n\n    T px_cx(px - cx);\n    T py_cy(py - cy);\n    T pz_cz(pz - cz);\n\n    T d11((d * px_cx) + (a11));\n    T d21(ax - cx);\n    T d31(bx - cx);\n    T d12((d * py_cy) + (a12));\n    T d22(ay - cy);\n    T d32(by - cy);\n    T d13((d * pz_cz) + (a13));\n    T d23(az - cz);\n    T d33(bz - cz);\n\n    T d2233(d22 * d33);\n    T d2332(d23 * d32);\n    T d2133(d21 * d33);\n    T d2331(d23 * d31);\n    T d2132(d21 * d32);\n    T d2231(d22 * d31);\n\n    T det(\n        d11 * (d2233 - d2332) - d12 * (d2133 - d2331) + d13 * (d2132 - d2231));\n\n    int flag2 = checker(det);\n    if (flag2 == -2) {\n        return 100; // not enough precision, only happens when using floating\n                    // points\n    }\n    if (flag2 == 1) {\n        if (d > 0) {\n            return 1;\n        }\n        if (d < 0) {\n            return -1;\n        }\n    }\n    if (flag2 == -1) {\n        if (d > 0) {\n            return -1;\n        }\n        if (d < 0) {\n            return 1;\n        }\n    }\n    return 0;\n}\n\ntemplate <typename T>\nstatic int orient3D_TPI_postfilter_multiprecision(\n    const T& d,\n    const T& n1,\n    const T& n2,\n    const T& n3,\n    const T& q1x,\n    const T& q1y,\n    const T& q1z,\n    const T& q2x,\n    const T& q2y,\n    const T& q2z,\n    const T& q3x,\n    const T& q3y,\n    const T& q3z,\n    const std::function<int(T)>& checker)\n{\n    ::feclearexcept(FE_UNDERFLOW | FE_OVERFLOW | FE_INVALID);\n\n    T dq3x(d * q3x);\n    T dq3y(d * q3y);\n    T dq3z(d * q3z);\n\n    T a11(n1 - dq3x);\n    T a12(n2 - dq3y);\n    T a13(n3 - dq3z);\n    T a21(q1x - q3x);\n    T a22(q1y - q3y);\n    T a23(q1z - q3z);\n    T a31(q2x - q3x);\n    T a32(q2y - q3y);\n    T a33(q2z - q3z);\n\n    T det(\n        a11 * (a22 * a33 - a23 * a32) - a12 * (a21 * a33 - a23 * a31)\n        + a13 * (a21 * a32 - a22 * a31));\n\n    int flag2 = checker(det);\n    if (flag2 == -2) {\n        return 100; // not enough precision\n    }\n    if (flag2 == 1) {\n        if (d > 0) {\n            return 1;\n        }\n        if (d < 0) {\n            return -1;\n        }\n    }\n    if (flag2 == -1) {\n        if (d > 0) {\n            return -1;\n        }\n        if (d < 0) {\n            return 1;\n        }\n    }\n    return 0;\n}\nstatic const std::function<int(Rational)> check_rational = [](Rational v) {\n    if (v.get_sign() > 0)\n        return 1;\n    if (v.get_sign() < 0)\n        return -1;\n    return 0;\n};\n\n// already know lpi exist;\n// 0 not intersected, 1 intersect open triangle, 2 shoot on edge, 3 shoot on\n// edge t2-t3\nint is_line_cut_triangle(\n    const Vector3r& e0,\n    const Vector3r& e1,\n    const Vector3r& t1,\n    const Vector3r& t2,\n    const Vector3r& t3,\n    const bool halfopen,\n    const Vector3r& norm);\nint line_triangle_inter_return_t(\n    const Vector3r& e0,\n    const Vector3r& e1,\n    const Vector3r& t1,\n    const Vector3r& t2,\n    const Vector3r& t3,\n    Rational& t);\n// if a line (going across pt, pt+dir) intersects triangle\n// triangle is not degenerated\n// 0 not intersected, 1 intersected, 3 intersected t2-t3 edge\nint line_triangle_intersection(\n    const Vector3r& pt,\n    const Vector3r& dir,\n    const Vector3r& t1,\n    const Vector3r& t2,\n    const Vector3r& t3,\n    const bool halfopen);\n// we check if triangle intersect segment,\n// this function is used in cube edge--prism tri and cube edge--bilinear tri\n// if halfopen= true, can tell us if intersect the edge t2-t3\n// 0 not intersected, 1 intersected, 2 intersect edge, 3 intersect t2-t3 edge\nint segment_triangle_intersection(\n    const Vector3r& e0,\n    const Vector3r& e1,\n    const Vector3r& t1,\n    const Vector3r& t2,\n    const Vector3r& t3,\n    const bool halfopen);\n// 0 no intersection, 1 intersect, 2 point on triangle, 3 point or ray go to on\n// t2-t3 edge, -1 shoot on border\nint ray_triangle_intersection(\n    const Vector3r& pt,\n    const Vector3r& dir,\n    const Vector3r& t1,\n    const Vector3r& t2,\n    const Vector3r& t3,\n    const bool halfopen);\n} // namespace ccd\n", "meta": {"hexsha": "5a32475f16deaad32462f8f4c52d2c253eaf6bd2", "size": 10508, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Utils.hpp", "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": "src/Utils.hpp", "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": "src/Utils.hpp", "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": 23.9362186788, "max_line_length": 80, "alphanum_fraction": 0.5607156452, "num_tokens": 3985, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673223709251, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.48482101457739246}}
{"text": "#include \"perlin_noise.h\"\r\n\r\n#include <array>\r\n#include <boost/random.hpp>\r\n#include <vector>\r\n\r\n#include \"composite_data_buffer.h\"\r\n\r\nnamespace noises {\r\nnamespace nodes\r\n{\r\n    struct PerlinNoiseData\r\n    {\r\n        PerlinNoiseData() { }\r\n\r\n        std::unique_ptr<boost::random::mt19937> rng;\r\n\r\n        std::vector<signed char> vectors;\r\n\r\n        int dimensions;\r\n    };\r\n\r\n    PerlinNoise::PerlinNoise()\r\n    {\r\n        seed_socket_ = &inputs().add(\"Seed\", SocketType::uniform);\r\n        seed_socket_->set_accepts(ConnectionDataType::value<long, 1>());\r\n\r\n        // Just a vector2 to start out with\r\n        points_socket_ = &inputs().add(\"Points\", SocketType::attribute);\r\n        points_socket_->set_accepts(ConnectionDataType::value<float, 2>());\r\n        points_socket_->set_accepts(ConnectionDataType::value<float, 3>());\r\n        points_socket_->set_accepts(ConnectionDataType::value<float, 4>());\r\n        points_socket_->set_accepts(ConnectionDataType::value<float, 5>());\r\n        points_socket_->set_accepts(ConnectionDataType::value<float, 6>());\r\n\r\n        output_socket_ = &outputs().add(\"Output\", ConnectionDataType::value<float, 1>(), SocketType::attribute);\r\n    }\r\n\r\n    std::string PerlinNoise::node_name() const\r\n    {\r\n        return \"Perlin Noise\";\r\n    }\r\n\r\n    void PerlinNoise::execute_uniforms(const CompositeDataBuffer &input, DataBuffer &output) const\r\n    {\r\n        long seed = input.get_uniform<long, 1>(*seed_socket_);\r\n\r\n        std::shared_ptr<PerlinNoiseData> data(new PerlinNoiseData);\r\n\r\n        data->rng.reset(new boost::random::mt19937);\r\n        data->rng->seed(seed);\r\n\r\n        int dimensions = points_socket_->connection()->get().data_type().dimensions();\r\n        load_hypercube_edge_vectors(*data, dimensions);\r\n\r\n        utils::shuffle_group(data->vectors, *data->rng, dimensions);\r\n\r\n        output.set_scratch(0, std::move(data));\r\n    }\r\n\r\n    void PerlinNoise::load_hypercube_edge_vectors(PerlinNoiseData &data, int dimensions) const\r\n    {\r\n        switch(dimensions)\r\n        {\r\n            case 0:\r\n                throw std::logic_error(\"Cannot have 0 dimension noise.\");\r\n            case 1:\r\n                throw std::logic_error(\"Cannot have 1 dimension perlin noise.\");\r\n            case 2:\r\n                data.vectors = HypercubeEdges<2>::edge_vectors_flattened();\r\n                break;\r\n            case 3:\r\n                data.vectors = HypercubeEdges<3>::edge_vectors_flattened();\r\n                break;\r\n            case 4:\r\n                data.vectors = HypercubeEdges<4>::edge_vectors_flattened();\r\n                break;\r\n            case 5:\r\n                data.vectors = HypercubeEdges<5>::edge_vectors_flattened();\r\n                break;\r\n            case 6:\r\n                data.vectors = HypercubeEdges<6>::edge_vectors_flattened();\r\n        }\r\n\r\n        data.dimensions = dimensions;\r\n    }\r\n\r\n    void PerlinNoise::execute_attributes(const CompositeDataBuffer &input, DataBuffer &output, DataBuffer::size_type index) const\r\n    {\r\n        PerlinNoiseData& data = *output.get_scratch_ref<std::shared_ptr<PerlinNoiseData>>(0);\r\n        int dimensions = data.dimensions;\r\n\r\n        const float* attribute_point = get_input_point_attribute(index, input, dimensions);\r\n\r\n        std::vector<int> dimension_starts(dimensions);\r\n        std::vector<std::vector<int>> points;\r\n        std::vector<int> gradient_indexes;\r\n\r\n        int num_gradients = data.vectors.size() / dimensions;\r\n\r\n        // Get floor(x), floor(y), floor(z) etc\r\n        for(int i = 0; i < dimensions; i++)\r\n        {\r\n            dimension_starts[i] = std::floor(attribute_point[i]);\r\n        }\r\n\r\n        // Get all points in the hypercube surrounding the input point\r\n        get_point_permutations(dimension_starts, dimensions, std::vector<int>(), points);\r\n\r\n        // Get all rng gradients for each point. Hash x/y/z to get index into gradients array\r\n        for(unsigned int i = 0; i < points.size(); i++)\r\n        {\r\n            std::vector<int>& point = points[i];\r\n            unsigned int sum = 0;\r\n            for(int j = 0; j < dimensions; j++)\r\n            {\r\n                static const unsigned int primes[] { 1699, 2237, 2671, 3571, 1949, 2221, 3469, 3083 };\r\n                sum += point[j] * point[j] * primes[j]; //Hopefully this has enough entropy and random enough results\r\n            }\r\n\r\n            gradient_indexes.push_back(sum % num_gradients);\r\n        }\r\n\r\n        // Because of how the get_point_permutations algorithm works, adjacent verticies are in pairs recursively\r\n        // There will always be an even number of points (2^n)\r\n        std::vector<float> out(points.size());\r\n\r\n        // vector from the first hypercube vertex to the input point (main diagonal) i.e. uv\r\n        std::vector<float> uvs(dimensions);\r\n\r\n        for(int i = 0; i < dimensions; i++)\r\n        {\r\n            uvs[i] = attribute_point[i] - points[0][i];\r\n        }\r\n\r\n        // Number of vertexes for an n-dimensional hypercube is 2^n\r\n        int num_points = std::pow(2, dimensions);\r\n\r\n        // Find dot product for every vertex.\r\n        // Multiply the vector from the hypercube vertex to the input point, and the gradient at the hypercube vertex\r\n        for(int i = 0; i < num_points; i++)\r\n        {\r\n            std::vector<int>& point = points[i];\r\n            int gradient_index = gradient_indexes[i] * dimensions;\r\n\r\n            // In theory, the dot products will be -1 to 1\r\n            float dot = 0;\r\n\r\n            for(int j = 0; j < dimensions; j++)\r\n            {\r\n                // gradient value (for this dimension) at hypercube vertex\r\n                signed char gradient_u = data.vectors[gradient_index + j];\r\n\r\n                // input point (in this dimension)\r\n                float attr_p = attribute_point[j];\r\n\r\n                // vector (for this dimension) from hypercube vertex to input point\r\n                float u = attr_p - point[j];\r\n\r\n                dot += u * gradient_u;\r\n            }\r\n\r\n            out[i] = dot;\r\n        }\r\n\r\n        // Collapse the dimensions down\r\n        int current_dimension = dimensions;\r\n        for(; num_points > 1; num_points /= 2)\r\n        {\r\n            // Take the dot products two at a time and interpolate between then\r\n            int half_num = num_points / 2;\r\n            for(int i = 0; i < half_num; i++)\r\n            {\r\n                int index = i * 2;\r\n\r\n                float x_1 = out[index];\r\n                float x_2 = out[index + 1];\r\n\r\n                float u = uvs[current_dimension - 1];\r\n                float interpolated = 6 * std::pow(u, 5) - (15 * std::pow(u, 4)) + (10 * std::pow(u, 3));\r\n\r\n                out[i] = (x_1 * (1.0f - interpolated)) + (x_2 * interpolated);\r\n            }\r\n\r\n            current_dimension--;\r\n        }\r\n\r\n        output.set_attribute<float, 1>(*output_socket_, index, &out[0]);\r\n    }\r\n\r\n    const float* PerlinNoise::get_input_point_attribute(DataBuffer::size_type index, const CompositeDataBuffer& input, int dimensions) const\r\n    {\r\n        switch(dimensions)\r\n        {\r\n            case 2:\r\n                return &input.get_attribute<float, 2>(*points_socket_, index);\r\n            case 3:\r\n                return &input.get_attribute<float, 3>(*points_socket_, index);\r\n            case 4:\r\n                return &input.get_attribute<float, 4>(*points_socket_, index);\r\n            case 5:\r\n                return &input.get_attribute<float, 5>(*points_socket_, index);\r\n            case 6:\r\n                return &input.get_attribute<float, 7>(*points_socket_, index);\r\n        }\r\n        throw std::logic_error(\"Not supported\");\r\n    }\r\n\r\n    void PerlinNoise::get_point_permutations(std::vector<int>& dimension_starts, int dimensions, std::vector<int> point, std::vector<std::vector<int>>& points)\r\n    {\r\n        int dimension = point.size();\r\n        if(dimension == dimensions)\r\n        {\r\n            points.push_back(point);\r\n        }\r\n        else\r\n        {\r\n            int start = dimension_starts[dimension];\r\n\r\n            point.push_back(start);\r\n            get_point_permutations(dimension_starts, dimensions, point, points);\r\n\r\n            point[dimension] = start + 1;\r\n            get_point_permutations(dimension_starts, dimensions, point, points);\r\n        }\r\n    }\r\n} }\r\n", "meta": {"hexsha": "e648aa3e07ae227e136279076bfaa56ab8d6ced8", "size": 8317, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "NoiseStudioLib/NoiseStudioLib/nodes/perlin_noise.cpp", "max_stars_repo_name": "SneakyMax/NoiseStudio", "max_stars_repo_head_hexsha": "b0c3c72e787d61b798acbcd2147f36e1e78f5bad", "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": "NoiseStudioLib/NoiseStudioLib/nodes/perlin_noise.cpp", "max_issues_repo_name": "SneakyMax/NoiseStudio", "max_issues_repo_head_hexsha": "b0c3c72e787d61b798acbcd2147f36e1e78f5bad", "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": "NoiseStudioLib/NoiseStudioLib/nodes/perlin_noise.cpp", "max_forks_repo_name": "SneakyMax/NoiseStudio", "max_forks_repo_head_hexsha": "b0c3c72e787d61b798acbcd2147f36e1e78f5bad", "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.4780701754, "max_line_length": 160, "alphanum_fraction": 0.5689551521, "num_tokens": 1841, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.48482101187355126}}
{"text": "#include <iostream>\n#include <boost/numeric/mtl/mtl.hpp>\n\nint main(int, char**)\n{\n    using namespace mtl;\n    \n    typedef std::complex<double>      cdouble;\n    const unsigned                    xd= 2, yd= 5, n= xd * yd;\n    compressed2D<cdouble>             A(n, n);\n    mat::laplacian_setup(A, xd, yd); \n\n    // Fill imaginary part of the matrix\n    A*= cdouble(1, -1);\n    std::cout << \"A is\\n\" << with_format(A, 7, 1) << \"\\n\";\n\n    std::cout << \"trace(A) is \" << trace(A) << \"\\n\\n\";\n    std::cout << \"conj(A) is\\n\" << with_format(mtl::mat::conj(A), 7, 1) << \"\\n\"; // ADL issue on g++ 4.4\n    std::cout << \"trans(A) is\\n\" << with_format(trans(A), 7, 1) << \"\\n\";\n    std::cout << \"hermitian(A) is\\n\" << with_format(hermitian(A), 7, 1) << \"\\n\";\n\n    return 0;\n}\n", "meta": {"hexsha": "691664a4c3ac9723bb8bcaffd75f8b83da145e00", "size": 765, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/examples/matrix_functions2.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/matrix_functions2.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/matrix_functions2.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": 31.875, "max_line_length": 104, "alphanum_fraction": 0.522875817, "num_tokens": 270, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.48482101187355126}}
{"text": "#include \"potts.h\"\n#include \"ising.h\"\n#include \"../util/observable.hpp\"\n#include \"../util/squarelattice.hpp\"\n#include <iostream>\n#include <boost/random.hpp>\n#include <ctime>\n#include <mpi.h>\n#include <boost/shared_ptr.hpp>\n#include <boost/program_options.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/foreach.hpp>\n#define foreach BOOST_FOREACH\n\nint main(int argc, char **argv)\n{\n  typedef util::SquareLattice Lattice;\n  typedef boost::variate_generator<boost::mt19937, boost::uniform_real<> > RNG01;\n  typedef boost::shared_ptr<potts::Model<Lattice, RNG01> > ModelPtr;\n\n  MPI_Init(&argc, &argv);\n\n  int nprocs, rank;\n  MPI_Comm_size(MPI_COMM_WORLD, &nprocs);\n  MPI_Comm_rank(MPI_COMM_WORLD, &rank);\n\n  RNG01 rnd(boost::mt19937(static_cast<uint32_t>(std::time(0)+rank*137)), boost::uniform_real<>(0.0, 1.0));\n\n  using namespace boost;\n  using namespace boost::program_options;\n  options_description opt(\"options\");\n  opt.add_options()\n    (\"help\", \"show this message\")\n    (\"Ising\", \"simulate Ising model\")\n    (\"q,q\", value<int>()->default_value(2), \"number of state of a spin\")\n    (\"h,h\", value<double>()->default_value(0.0), \"magnetic field\")\n    (\"L,L\", value<int>()->default_value(10), \"length of lattice\")\n    (\"beta-min\", value<double>()->default_value(0.1), \"minimum beta\")\n    (\"beta-max\", value<double>()->default_value(1.0), \"maximum beta\")\n    (\"beta-num\", value<int>()->default_value(10), \"number of beta\")\n    (\"thermalization\", value<int>()->default_value(8), \"number of exchange to thermalize\")\n    (\"mcs\", value<int>()->default_value(64), \"number of exchange to measure\")\n    (\"interval,i\", value<int>()->default_value(1024), \"temperature exchange interval\")\n    (\"no-exchange\", \"switch off temperature exchange\")\n    ;\n\n  variables_map vm;\n  store(parse_command_line(argc, argv, opt), vm);\n  notify(vm);\n\n  if( vm.count(\"help\") ){\n    std::cout << opt << std::endl;\n    MPI_Barrier(MPI_COMM_WORLD);\n    MPI_Finalize();\n    return 0;\n  }\n\n  const bool bIsing = vm.count(\"Ising\");\n  const bool noEx = vm.count(\"no-exchange\");\n\n  const int q = vm[\"q\"].as<int>();\n  const int L = vm[\"L\"].as<int>();\n  const double h = vm[\"h\"].as<double>();\n  const double bmin = vm[\"beta-min\"].as<double>();\n  const double bmax = vm[\"beta-max\"].as<double>();\n  const int nbeta = vm[\"beta-num\"].as<int>();\n  const int therm = vm[\"thermalization\"].as<int>();\n  const int MCS = vm[\"mcs\"].as<int>();\n  const int interval = vm[\"interval\"].as<int>();\n\n  const double dbeta = (bmax-bmin)/(nbeta-1);\n\n  // the i-th worker runs under beta = betas[i]\n  // the beta_index[i]-th worker runs under the i-th lowest beta (bmin + i*dbeta)\n  // in other words, the value of the i-th lowest beta is betas[beta_index[i]]\n  std::vector<double> betas(nbeta);\n  std::vector<int> beta_index(nbeta);\n  // inv_beta_index is the inverse of beta_index\n  std::vector<int> inv_beta_index(nbeta);\n  for(int i=0; i<nbeta; ++i){\n    betas[i] = bmin + i*dbeta;\n    beta_index[i] = i;\n    inv_beta_index[i] = i;\n  }\n\n  std::vector<int> offsets(nprocs+1,0);\n  for(int i=0; i<nbeta%nprocs; ++i){\n    offsets[i+1] = offsets[i] + nbeta/nprocs+1;\n  }\n  for(int i = nbeta%nprocs; i<nprocs; ++i){\n    offsets[i+1] = offsets[i] + nbeta/nprocs;\n  }\n  assert(offsets[nprocs] == nbeta);\n  const int offset = offsets[rank];\n\n  const int nbeta_local = offsets[rank+1]-offsets[rank];\n\n  std::vector<ModelPtr> models;\n  if(bIsing){\n    for(int i=0; i<nbeta_local; ++i){\n      models.push_back(ModelPtr(new potts::Ising<Lattice,RNG01>(h,L)));\n    }\n  }else{\n    for(int i=0; i<nbeta_local; ++i){\n      models.push_back(ModelPtr(new potts::Potts<Lattice,RNG01>(q,h,L)));\n    }\n  }\n\n  std::vector<util::Observable> obs_ene(nbeta);\n  std::vector<util::Observable> obs_mag(nbeta);\n\n  for(int mcs = 0; mcs < therm+MCS; ++mcs){\n    for(int lm=0; lm < interval; ++lm){\n      for(int i=0; i<nbeta_local; ++i){\n        models[i]->update(betas[offset+i], rnd);\n      }\n    }\n    std::vector<double> enes_local(nbeta);\n    std::vector<double> mags_local(nbeta);\n    for(int i=0; i<nbeta_local; ++i){\n      enes_local[offset+i] = models[i]->ene();\n      mags_local[offset+i] = models[i]->mag();\n    }\n    std::vector<double> enes(rank==0?nbeta:0);\n    std::vector<double> mags(rank==0?nbeta:0);\n    MPI_Reduce(&enes_local[0], &enes[0], nbeta, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);\n    MPI_Reduce(&mags_local[0], &mags[0], nbeta, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);\n\n    if(noEx){\n      if(rank == 0){\n        for(int i=0; i<nbeta; ++i){\n          obs_ene[i] << enes[beta_index[i]];\n          obs_mag[i] << mags[beta_index[i]];\n        }\n        std::clog << \"mcs : \" << mcs+1 << \"/\" << MCS+therm << \" done.\" << std::endl;\n      }\n    }else{\n      if(rank == 0){\n        for(int i=0; i<nbeta; ++i){\n          obs_ene[i] << enes[beta_index[i]];\n          obs_mag[i] << mags[beta_index[i]];\n        }\n\n        for(int i=nbeta-1; i>0; --i){ // from low-temperature to high-T\n          const int ihigh = beta_index[i];\n          const int ilow = beta_index[i-1];\n          const double p = std::exp( (betas[ihigh] - betas[ilow])*(enes[ihigh]-enes[ilow]));\n          if(rnd() < p){\n            std::swap(betas[ihigh], betas[ilow]);\n            std::swap(beta_index[i], beta_index[i-1]);\n            std::swap(inv_beta_index[beta_index[i]], inv_beta_index[beta_index[i-1]]);\n          }\n        }\n      }\n      MPI_Bcast(&betas[0], nbeta, MPI_DOUBLE, 0, MPI_COMM_WORLD);\n      if(rank==0){\n        if(mcs == therm){\n          for(int i=0; i<nbeta; ++i){\n            obs_ene[i].reset();\n            obs_mag[i].reset();\n          }\n        }\n        std::clog << \"mcs : \" << mcs+1 << \"/\" << MCS+therm << \" done.\" << std::endl;\n      }\n    }\n  }\n\n  if(rank==0){\n    for(int i=0; i<nbeta; ++i){\n      std::cout << betas[beta_index[i]]\n         << \" \" << obs_ene[i].mean() << \" \" << obs_ene[i].error()\n         << \" \" << obs_mag[i].mean() << \" \" << obs_mag[i].error()\n         << std::endl;\n    }\n  }\n\n  MPI_Barrier(MPI_COMM_WORLD);\n  MPI_Finalize();\n\n  return 0;\n}\n", "meta": {"hexsha": "8a3deb8adb2879f57d0ea5f8f0c29705169c654a", "size": 6006, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/potts_exchange_main.cpp", "max_stars_repo_name": "yomichi/SpinMonteCarlo.cpp", "max_stars_repo_head_hexsha": "2ce7f589a52b30da9f698c1a202b8348c2e578dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/potts_exchange_main.cpp", "max_issues_repo_name": "yomichi/SpinMonteCarlo.cpp", "max_issues_repo_head_hexsha": "2ce7f589a52b30da9f698c1a202b8348c2e578dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/potts_exchange_main.cpp", "max_forks_repo_name": "yomichi/SpinMonteCarlo.cpp", "max_forks_repo_head_hexsha": "2ce7f589a52b30da9f698c1a202b8348c2e578dc", "max_forks_repo_licenses": ["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.0, "max_line_length": 107, "alphanum_fraction": 0.5987345987, "num_tokens": 1811, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.48482101187355114}}
{"text": "////////////////////////////////////////////////////////////////////////\n// Manuel Martinez (manuel.martinez@kit.edu)\n//\n// license: LGPLv3\n// FLAGS: -g -std=c++11 `pkg-config opencv --cflags --libs` -lboost_system -pthread -lturbojpeg  -lboost_system -lboost_program_options -O2 -Wno-inline\n\n#include <opencv2/opencv.hpp>\n#include <boost/program_options.hpp>\n#include <uSnippets/log.hpp>\n#include <dirent.h>\n\n\nusing namespace uSnippets;\n\n\nstruct HeatMap {\n\t\n\tcv::Mat1f H;\n\t\n\tHeatMap() {}\n\t\n\tHeatMap(cv::Size size) : H(size,0.f) {}\n\t\n\tHeatMap &filter(double cooling=0.90, double sigma=3) {\n\t\t\n\t\tH *= cooling;\n\t\tcv::GaussianBlur(H,H,cv::Size(),sigma,sigma);\n\t\treturn *this;\n\t}\n\t\n\t\n\t\n\tHeatMap &heat(cv::Point2f pt, double temperature) {\n/*\n\t\tcv::Mat1f row(1,H.cols,0.f);\n\t\tfor (int j=0; j<H.cols; j++)\n\t\t\trow(j) = std::exp(- std::pow((j-pt.x)/2,2)/(2*sigma*sigma) );\n\n\t\tcv::Mat1f col(H.rows,1,0.f);\n\t\tfor (int i=0; i<H.rows; i++)\n\t\t\tcol(i) = temperature*std::exp(- std::pow((i-pt.y)/2,2)/(2*sigma*sigma) );\n\t\t\n\t\tfor (int i=0; i<H.rows; i++)\n\t\t\tfor (int j=0; j<H.cols; j++)\n\t\t\t\tH(i,j) += col(i)*row(j);*/\n\t\tif (pt.x>=H.cols or pt.y>=H.rows) return *this;\n\t\tH(pt)+=temperature;\n\t\treturn *this;\n\t}\n\t\n\tcv::Mat3b draw(cv::Mat3b img, cv::Vec3b color, float scale=0) const {\n\t\t\t\n\t\tcv::Mat3b out = img.clone();\n\t\tAssert(img.size==H.size) << \"Heat map not the same size as the image\";\n\n\t\tif (scale==0) {\n\t\t\tfor (int i=0; i<H.rows; i++)\n\t\t\t\tfor (int j=0; j<H.cols; j++)\n\t\t\t\t\tscale = std::max(scale,H(i,j));\n\t\t\tscale = 1./(scale+1e-10);\n\t\t}\n\n\t\tfor (int i=0; i<H.rows; i++) {\n\t\t\tfor (int j=0; j<H.cols; j++) {\n\t\t\t\tdouble h = std::min(std::max(H(i,j)*scale,0.f),1.f);\n\t\t\t\tout(i,j)/= 1+h;\n\t\t\t\tout(i,j) += h*color;\n\t\t\t}\n\t\t}\t\t\t\t\n\t\treturn out;\n\t}\n\t\n\toperator bool() const { return not H.empty(); }\n};\n\nnamespace Geometry {\n\t\n\ttypedef cv::Vec4f Vec4; // third component should always be 1\n\ttypedef cv::Matx44f Mat44;\n\n/*\tstruct PinHole { double fx, fy, cx, cy; };\n\t\n\tclass Pose {\n\t\tmutable Mat44 transformMatrix, iTransformMatrix;\n\tpublic:\n\n\t\tconst Vec4   translation;\n\t\tconst Vec4   quaternion;\n\t\t\n\t\tPose( const Vec4 &translation, const Vec4 &rotation ): translation(translation), rotation(rotation), transformMatrix(Mat44::zeros()), iTransformMatrix(Mat44::zeros()) {};\n\n\t\tconst Mat44 &getTransformMatrix() const {\n\t\t\t\n\t\t\tconst auto &q = quaternion;\n\t\t\tif (transformMatrix(4,4)==0) transformMatrix = Mat44(\n\t\t\t\tq[3]*q[3]+q[0]*q[0]-q[1]*q[1]-q[2]*q[2],\t\t\t\t\t2*q[0]*q[1]+2*q[3]*q[2],\t\t\t\t\t2*q[0]*q[2]-2*q[3]*q[1], \ttranslation[0],\n\t\t\t\t\t\t\t\t2*q[0]*q[1]-2*q[3]*q[2], \tq[3]*q[3]-q[0]*q[0]+q[1]*q[1]-q[2]*q[2],\t\t\t\t \t2*q[1]*q[2]+2*q[3]*q[0], \ttranslation[1],\n\t\t\t\t\t\t\t\t2*q[0]*q[2]+2*q[3]*q[1], \t\t\t\t\t2*q[1]*q[2]-2*q[3]*q[0], \tq[3]*q[3]-q[0]*q[0]-q[1]*q[1]+q[2]*q[2], \ttranslation[2],\n\t\t\t\t\t\t\t\t\t\t\t\t\t0.f, \t\t\t\t\t\t\t\t\t\t0.f,\t\t\t\t\t\t\t\t\t\t0.f, \t  \t\t\t1.);\n\t\t\treturn transformMatrix;\n\t\t}\n\n\t\tconst Mat44 &getInvTransformMatrix(const Vec4 &t, const Vec4 &q) const {\n\t\t\t\n\t\t\tgetTransformMatrix();\n\t\t\tconst auto &tm = transformMatrix;\n\t\t\tif (iTransformMatrix(4,4)==0) iTransformMatrix = Mat44(\n\t\t\t\ttm(0,0), tm(1,0), tm(2,0), -(tm(0,0)*tm(0,3) + tm(1,0)*tm(1,3) + tm(2,0)*tm(2,3)),\n\t\t\t\ttm(0,1), tm(1,1), tm(2,1), -(tm(0,1)*tm(0,3) + tm(1,1)*tm(1,3) + tm(2,1)*tm(2,3)),\n\t\t\t\ttm(0,2), tm(1,2), tm(2,2), -(tm(0,2)*tm(0,3) + tm(1,2)*tm(1,3) + tm(2,2)*tm(2,3)),\n\t\t\t\t\t  0,\t   0, \t    0,\t\t\t\t\t\t\t\t\t\t\t\t\t \t1);\n\t\t\treturn iTransformMatrix;\n\t\t}\n\n\t\tbool operator< (const Pose &p) const { return translation=p.translation?rotation<p.rotation:translation<p.translation; }\n\n\t\tfriend std::ostream& operator<< (std::ostream &out, const Pose &p) { out << pt.translation << \" \" << pt.rotation; return out; }\n\t};\n\n\t// Transform a point in Object Coordinates to World Coordinates\n\tinline Vec4 tObjectToWorld( const Vec4 &p3D, const Pose &objectPose ) { return objectPose.getTransformMatrix()*p3D; }\n\n\t// Transform a point in World Coordinates to Camera Coordinates\n\tinline Vec4 tWorldToCamera( const Vec4 &p3D, const Pose &camPose    ) { return camPose.getInvTransformMatrix()*p3D; }\n\n\t// Transform a point in Object Coordinates to Camera Coordinates\n\t//static inline Vec4 tWorldToCamera( const Vec4 &p3D, const Pose &objectPose, const Pose &camPose ) { return camPose.iTransformMatrix*p3D; }\n\t\n\tinline cv::Vec2f projectToFrame( const Vec4 &p3D, const PinHole &pinhole) { \n\t\treturn { proj3D[0]/(proj3D[2]+std::numeric_limits<float>::min()) * pinhole.fx + pinhole.cx, \n\t\t\t\t proj3D[1]/(proj3D[2]+std::numeric_limits<float>::min()) * pinhole.fy + pinhole.cy };\n\t}*/\n}\n\nstruct ORBFeatureEngine {\n\t\n\tcv::ORB orb = cv::ORB(2000,1.15f,12);\n\n\tstruct Descriptor {\n\t\t\n\t\tconst cv::Mat1b d;\n\t\t\n\t\tDescriptor(const cv::Mat1b &d) : d(d.clone()) {}\n\t\t\n\t\tuint dist(const Descriptor &desc) const {\n\t\t\tconst uint64_t *v0 = reinterpret_cast<const uint64_t*>(d.data);\n\t\t\tconst uint64_t *v1 = reinterpret_cast<const uint64_t*>(desc.d.data);\n\t\t\treturn _popcnt64(v0[0]^v1[0])+_popcnt64(v0[1]^v1[1])+_popcnt64(v0[2]^v1[2])+_popcnt64(v0[2]^v1[2]);\n\t\t}\n\t};\n\t\n\tstd::vector<std::pair<cv::KeyPoint,Descriptor>> extract(cv::Mat3b img) {\n\t\t\n\t\tstd::vector<std::pair<cv::KeyPoint,Descriptor>> desc;\n\t\t\n\t\tstd::vector<cv::KeyPoint> keyPoints;\n\t\tcv::Mat1b descriptors;\n\t\torb(img, cv::Mat(), keyPoints, descriptors);\n\t\tfor (size_t i=0; i<keyPoints.size(); i++)\n\t\t\tdesc.emplace_back(keyPoints[i], descriptors.row(i));\n\n\t\treturn desc;\n\t}\t\t\n\t\n};\n\n/*\nstruct SURFFeatureEngine {\n\t\n\tcv::SURF surf(500);\n\n\tstruct Descriptor {\n\t\t\n\t\tconst cv::Mat1f d;\n\t\t\n\t\tDescriptor(const cv::Mat1f &d) : d(d.clone()) {}\n\t\t\n\t\tfloat dist(const Descriptor &desc) const {\n\t\t\treturn cv::norm(d-desc.d);\n\t\t}\n\t};\n\t\n\tstd::vector<std::pair<cv::KeyPoint,Descriptor>> extract(cv::Mat3b img) {\n\t\t\n\t\tstd::vector<std::pair<cv::KeyPoint,Descriptor>> desc;\n\t\t\n\t\tstd::vector<cv::KeyPoint> keyPoints;\n\t\tcv::Mat1f descriptors;\n\t\tsurf(img, cv::Mat(), keyPoints, descriptors);\n\t\tfor (size_t i=0; i<keyPoints.size(); i++)\n\t\t\tdesc.emplace_back(keyPoints[i], descriptors.row(i));\n\n\t\treturn desc;\n\t}\t\t\n\t\n};*/\n\ntemplate<typename FeatureEngine>\nstruct MopedLt {\n\n\tstatic inline std::vector<std::string> getAllFilenames(std::string path, std::string type=\"\") {\n\t\t\n\t\tstd::vector<std::string> r;\n\t\tDIR *dir;\n\t\tstruct dirent *ent;\n\t\tif ((dir = opendir (path.c_str())) == NULL)\n\t\t\treturn r;\n\t\t\n\t\twhile ((ent = readdir (dir)) != NULL)\n\t\t\tif (std::string(ent->d_name).size()>=type.size() and std::string(&ent->d_name[std::string(ent->d_name).size()-type.size()])==type)\n\t\t\t\tr.push_back(path+\"/\"+ent->d_name);\n\n\t\tclosedir (dir);\n\t\tstd::sort(r.begin(), r.end());\n\t\treturn r;\n\t}\n\n\tFeatureEngine FE;\n\ttypedef typename FeatureEngine::Descriptor Descriptor;\n\t\n\tstruct ImageKeyPoint {\n\t\t\n\t\tcv::KeyPoint kp;\n\t\tDescriptor desc;\n\t\tcv::Mat3b img;\n\t\tImageKeyPoint(const cv::KeyPoint &kp, const Descriptor &desc, const cv::Mat3b &img) : kp(kp), desc(desc), img(img) {}\n\t};\n\n\tstruct ModelKeyPoint {\n\t\t\n\t\tGeometry::Vec4 pt;\n\t\tstd::vector<ImageKeyPoint> ikps;\n\t\tModelKeyPoint(const cv::KeyPoint &kp, const Descriptor &desc, const cv::Mat3b &img) { ikps.emplace_back(kp,desc,img); }\n\t};\n\t\n\ttypedef std::vector<ModelKeyPoint> Model;\n\n\tstd::vector<std::pair<std::string, Model>> models;\n\n\tMopedLt &add(std::string path) {\n\t\t\n\t\tfor (auto &model : getAllFilenames(path)) {\n\t\t\t\n\t\t\tstd::vector<cv::Mat3b> images;\n\t\t\tfor (auto &imageName : getAllFilenames(model)) {\n\t\t\t\tcv::Mat3b image = cv::imread(imageName);\n\t\t\t\twhile (image.cols>1024) cv::resize(image,image,cv::Size(),.5,.5);\n\t\t\t\tif (not image.empty())\n\t\t\t\t\timages.emplace_back(image);\n\t\t\t}\n\t\t\tif (images.empty()) continue;\n\t\t\t\n\t\t\tstd::string name = model.substr(model.find_last_of(\"/\\\\\")+1);\n\t\t\tLog(0) << name << \": \" << images.size();\n\t\t\t\n\t\t\tadd(name, images);\n\t\t}\n\t\treturn *this;\n\t}\n\n\tMopedLt &add(std::string name, std::vector<cv::Mat3b> images) {\n\t\t\n\t\tmodels.emplace_back(name, Model());\n\n\t\tModel &model = models.back().second;\n\t\t\n\t\tAssert(images.size()>2) << \"Not enough images for SFM\";\n\t\t\n\t\t// We assume images are correlated, therefore an almost-planar transformation must exist between consecutive images\n\t\tLog(0) << \"KeyPoint Extraction\";\n\t\t{\n\t\t\tfor (auto &p : FE.extract(images[0]))\n\t\t\t\tmodel.emplace_back(p.first, p.second, images[0]);\n\t\t\t\n\t\t\tfor (size_t ii = 1; ii<images.size(); ii++) {\n\t\t\t\tLog(0) << \"Image \" << ii << \" of \" << images.size();\n\n\t\t\t\tauto feats = FE.extract(images[ii]);\n\t\t\t\tAssert(feats.size()>4) << \"Not enough features in image\" << ii;\n\t\t\t\t\n\t\t\t\tstd::vector<size_t> bestMatchA(model.size()), bestMatchB(feats.size());\n\t\t\t\tfor (size_t i=0; i<model.size(); i++) {\n\t\t\t\t\tfor (size_t j=0; j<feats.size(); j++) {\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (model[i].ikps.back().desc.dist(feats[j].second) < model[i].ikps.back().desc.dist(feats[bestMatchA[i]].second))\n\t\t\t\t\t\t\tbestMatchA[i] = j;\n\n\t\t\t\t\t\tif (model[i].ikps.back().desc.dist(feats[j].second) < model[bestMatchB[j]].ikps.back().desc.dist(feats[j].second))\n\t\t\t\t\t\t\tbestMatchB[j] = i;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tstd::vector<cv::Point2f> pointsA, pointsB;\n\t\t\t\tfor (size_t j=0; j<feats.size(); j++) {\n\t\t\t\t\tif (bestMatchA[bestMatchB[j]]==j) {\n\t\t\t\t\t\tpointsA.push_back(model[bestMatchB[j]].ikps.back().kp.pt);\n\t\t\t\t\t\tpointsB.push_back(feats[j].first.pt);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tcv::Mat maskG;\n\t\t\t\tcv::Mat H = findHomography( pointsA, pointsB, cv::RANSAC, 5, maskG );\n\t\t\t\tcv::Mat1b mask = maskG;\n\t\t\t\tif (H.empty()) Log(0) << \"Homography found: \" << H.empty();\n\t\t\t\t\n\t\t\t\t{\n\n\t\t\t\t\tstd::vector<cv::KeyPoint> kp;\n\t\t\t\t\tfor (size_t j=0,k=0; j<feats.size(); j++) {\n\t\t\t\t\t\tif (bestMatchA[bestMatchB[j]]!=j) continue;\n\t\t\t\t\t\tif (mask(k)) \n\t\t\t\t\t\t\tkp.push_back(feats[j].first);\n\t\t\t\t\t\tk++;\n\t\t\t\t\t}\n\n\t\t\t\t\tcv::Mat3b displayImg = images[ii].clone();\n\t\t\t\t\tcv::drawKeypoints(displayImg, kp, displayImg);\n\t\t\t\t\tcv::imshow(\"kk\",displayImg);\n\t\t\t\t\tcv::waitKey(10);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tfor (size_t j=0,k=0; j<feats.size(); j++) {\n\t\t\t\t\tif (bestMatchA[bestMatchB[j]]!=j) continue;\n\t\t\t\t\tif (mask(k)) {\n\t\t\t\t\t\tmodel[bestMatchB[j]].ikps.push_back({feats[j].first, feats[j].second, images[ii]});\n\t\t\t\t\t} else {\n\t\t\t\t\t\tmodel.emplace_back(feats[j].first, feats[j].second, images[ii]);\n\t\t\t\t\t}\n\t\t\t\t\tk++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tLog(0) << \"KeyPoint Extraction Done: \" <<model.size() << \" current points\";\n\t\t\n\t\tLog(0) << \"Removing low cardinality points\";\n\t\t{\n\t\t\tstd::vector<ModelKeyPoint> modelTmp;\n\t\t\tstd::swap(model, modelTmp);\n\t\t\tfor (auto &m : modelTmp)\n\t\t\t\tif (m.ikps.size()>2)\n\t\t\t\t\tmodel.push_back(m);\n\t\t}\n\t\tLog(0) << \"Removing low cardinality points: Done, \" <<model.size() << \" current points\";\n\t\treturn *this;\n\t}\n\t\n//\tPoint *query(const Descriptor &) {}\n\n//\tstd::vector<std::pair<cv::Point2f,Point *>> queryN(cv::Mat3b img) {\n//\t}\n\n\tstd::string queryLargestObject(cv::Mat3b image, HeatMap &heatMap) {\n\t\t\n\t\tstd::vector<cv::KeyPoint> kps;\n\t\tstd::map<std::pair<std::string,Model>*,double> mp;\n\t\t\n\t\tfor (auto &f : FE.extract(image)) {\n\t\t\t\n\t\t\tstruct MatchInfo { double distance; std::pair<std::string,Model> *m; ModelKeyPoint *k; };\n\t\t\tMatchInfo M[2]; M[0].distance = M[1].distance = 1e10;\n\t\t\tfor (auto &m : models) {\n\t\t\t\tfor (auto &k : m.second) {\n\t\t\t\t\tfor (auto &ikp : k.ikps) {\n\t\t\t\t\t\tdouble d = ikp.desc.dist(f.second);\n\t\t\t\t\t\tif (d>=M[1].distance) continue;\n\t\t\t\t\t\tM[1].distance = d;\n\t\t\t\t\t\tM[1].m = &m;\n\t\t\t\t\t\tM[1].k = &k;\n\t\t\t\t\t\tif (M[0].distance > M[1].distance) std::swap(M[0],M[1]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tLog(-2) << M[0].distance << \" \" << M[1].distance;\n\t\t\tif (M[0].k != M[1].k) continue;\n\t\t\t//if (M[0].distance > 40) continue; //Magic number!\t\t\t\n\t\t\tkps.push_back(f.first);\n\t\t\tmp[M[0].m] += std::pow(1/M[0].distance,2);\n\n\t\t\tif (heatMap)\n\t\t\t\theatMap.heat(f.first.pt,.2);\n\t\t}\n\t\theatMap.filter();\n\t\t\n\t\tLog(0) << kps.size();\n\t\tif (0) {\n\t\t\tcv::Mat3b displayImg = image.clone();\n\t\t\tcv::drawKeypoints(displayImg, kps, displayImg);\n\t\t\tcv::imshow(\"kk\",displayImg);\n\t\t\tcv::waitKey(10);\n\t\t}\n\t\t\n\t\tstd::pair<std::string,Model> *best=&models.front();\n\t\tfor (auto &m : mp)\n\t\t\tif (m.second>mp[best])\n\t\t\t\tbest = m.first;\n\t\t\n\t\tfor (auto &m : mp)\n\t\t\tLog(0) << m.first->first << \": \" << m.second; \n\t\t\n\t\treturn \"\";\n\t}\n};\n\n/*\nclass MonoSFM {\n\n\n\n\npublic:\n\t\n\tstd::map<std::string, std::vector<cv::KeyPoint>> imageKeypoints;\n\tstd::map<std::string, cv::Mat1b> imageDescriptors;\n\tstd::map<std::string, cv::Mat1f> imageFundamentals;\n\t\n\tcv::Mat3b panorama;\n\tstd::vector<cv::KeyPoint> panoramaKeypoints;\n\tcv::Mat1b panoramaDescriptors;\n\t\n\tMonoSFM(const std::Mat3b &pattern, double ppm, const std::vector<std::string> &imageFiles) {\n\t\t\n\t\t\n\t\tstd::vector<cv::KeyPoint> lastKeypoints;\n\t\tcv::Mat1b lastDescriptors;\n\t\n\t\torb(pattern, cv::Mat(), lastKeypoints, lastDescriptors);\n\t\t\n\t\tLog(0) << \"Extracting all descriptors\";\n\t\tfor (auto &imageFile : imageFiles) {\n\t\t\t\n\t\t\tcv::Mat3b image = cv::imread(imageFile);\n\n\t\t\tstd::vector<cv::KeyPoint> keypoints;\n\t\t\tcv::Mat1b descriptors;\n\t\t\torb(image, cv::Mat(), keypoints, descriptors);\n\t\t\t\n\t\t\tif (descriptors.rows<8) throw(std::string(\"Not enough keypoints\"));\n\t\t\t\n\t\t\tfor (int i=0; i<descriptors.rows; i++) {\n\t\t\t\tstd::vector<std::pair<int, uint>> dists;\n\t\t\t\tfor (int j=0; j<lastDescriptors.rows; j++)\n\t\t\t\t\tdists.emplace_back(j,dist(descriptors.row(i), lastDescriptors.row(j)));\n\t\t\t\t\n\t\t\t\tstd::partial_sort(dists.begin(), dists.begin()+3, dists.end());\n\t\t\t\t\n\t\t\t\tLog(0) << dists[0].second << \" \" << dists[1].second; \n\t\t\t}\n\t\t\t\n\t\t\tlastKeypoints = keypoints;\n\t\t\tlastDescriptors = descriptors;\n\t\t}\t\t\n\t}\n};*/\n\n\nint main(int argc, char *argv[]) {\n\t\t\n\t// PARSING PROGRAM OPTIONS\n\tnamespace po = boost::program_options;\n\tpo::options_description pod(\"BlindSLAM Tool\");\n\n\tpo::positional_options_description p;\n\tp.add(\"path\", 1);\n\n\tpod.add_options() \n\t\t(\"help,h\", \"produce this help message\")\n\t\t(\"log,l\", po::value<int>()->default_value(0), \"set log level\")\n\t\t(\"path\", po::value<std::string>()->default_value(\"data/objects\"), \"path to SFM files\");\n\t\n\tpo::variables_map pom;\n\tpo::store( po::command_line_parser( argc, argv).options(pod).positional(p).run(), pom);\n\tpo::notify(pom);\n\n\tif (pom.count(\"help\")) {\n\t\tstd::cout << \"Usage:\" << std::endl <<  pod << \"\\n\";\n\t\treturn 0;\n\t}\n\t\n\tLog::reportLevel(pom[\"log\"].as<int>());\n\n\tMopedLt<ORBFeatureEngine> moped;\n\tmoped.add(pom[\"path\"].as<std::string>());\n\t\n\tcv::VideoCapture cap(0);\n    if (cap.isOpened()) {\n\t\twhile (cv::waitKey(10)!='q') {\n\t\t\tcv::Mat3b image;\n\t\t\tcap >> image;\n\t\t\tHeatMap heatMap(image.size());\n\t\t\tmoped.queryLargestObject(image,heatMap);\n\t\t\tcv::imshow(\"kk\",heatMap.draw(image,{0,0,255}));\n\t\t}\t\t\n\t} else {\n\t\tfor (auto &model : moped.getAllFilenames(pom[\"path\"].as<std::string>())) {\n\t\t\t\t\n\t\t\tfor (auto &imageName : moped.getAllFilenames(model)) {\n\t\t\t\tcv::Mat3b image = cv::imread(imageName);\n\t\t\t\twhile (image.cols>1024) cv::resize(image,image,cv::Size(),.5,.5);\n\t\t\t\tif (image.empty()) continue;\n\t\t\t\tHeatMap heatMap(image.size());\n\t\t\t\tmoped.queryLargestObject(image,heatMap);\n\t\t\t\tcv::imshow(\"kk\",heatMap.draw(image,{0,0,255}));\n\t\t\t\tcv::waitKey(10);\t\t\t\n\t\t\t}\n\t\t}\n\t}\n}\n", "meta": {"hexsha": "c9c0e874432fc99676b3df2bad7146ef5daccf54", "size": 14671, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/mopedLt.cc", "max_stars_repo_name": "MartinezTorres/uSnippets-dev", "max_stars_repo_head_hexsha": "049006786cff23eaab532da6401ca84972a45037", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/mopedLt.cc", "max_issues_repo_name": "MartinezTorres/uSnippets-dev", "max_issues_repo_head_hexsha": "049006786cff23eaab532da6401ca84972a45037", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mopedLt.cc", "max_forks_repo_name": "MartinezTorres/uSnippets-dev", "max_forks_repo_head_hexsha": "049006786cff23eaab532da6401ca84972a45037", "max_forks_repo_licenses": ["Apache-2.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.8799212598, "max_line_length": 172, "alphanum_fraction": 0.6097743848, "num_tokens": 4844, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.48482101187355114}}
{"text": "#include \"batoid.h\"\n#include \"ray.h\"\n#include \"surface.h\"\n#include \"medium.h\"\n#include \"utils.h\"\n#include <cmath>\n#include <numeric>\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n\nusing Eigen::Vector3d;\nusing Eigen::Matrix3d;\nusing Eigen::AngleAxisd;\n\nnamespace batoid{\n    RayVector rayGrid(double dist, double length,\n                      double xcos, double ycos, double zcos,\n                      int nside, double wavelength, double flux,\n                      const Medium& m, bool lattice=false) {\n        double n = m.getN(wavelength);\n    // `dist` is the distance from the center of the pupil to the center of the rayGrid.\n    // `length` is the length of one side of the rayGrid square.\n    // `xcos`, `ycos`, `zcos` are the direction cosines of the ray velocities\n    // `nside` is the number of rays on a side of the rayGrid.\n    // `wavelength` is the wavelength assigned to the rays\n    // `m` is the medium (from which we get the refractive index) at the position of the rays.\n    // (Needed to properly normalize the ray magnitudes).\n        std::vector<Ray> result;\n        result.reserve(nside*nside);\n\n        // The \"velocities\" of all the rays in the grid are the same.\n        Vector3d v(xcos, ycos, zcos);\n        v.normalize();\n        v /= n;\n\n        double dy;\n        if (lattice)\n            dy = length/nside;\n        else\n            dy = length/(nside-1);\n        double y0 = -length/2;\n        double y = y0;\n        for(int iy=0; iy<nside; iy++) {\n            double x = y0;\n            for(int ix=0; ix<nside; ix++) {\n                // Start with the position of the ray when it intersects the pupil\n                Vector3d r(x,y,0);\n                // We know that the position of the ray that goes through the origin\n                // (which is also the center of the pupil), is given by\n                //   a = -dist * vhat = -dist * v * n\n                // We want to find the position r0 that satisfies\n                // 1) r0 - a is perpendicular to v\n                // 2) r = r0 + v t\n                // The first equation can be rewritten as\n                // (r0 - a) . v = 0\n                // some algebra reveals\n                // (r + v n d) . v - t v . v = 0\n                // => t = (r + v n d) . v / v . v\n                //      = (r + v n d) . v n^2\n                // => r0 = r - v t\n                double t = (r + v*n*dist).dot(v) * n * n;\n                result.emplace_back(r-v*t, v, 0, wavelength, flux, false);\n                x += dy;\n            }\n            y += dy;\n        }\n        return RayVector(std::move(result), wavelength);\n    }\n\n    RayVector circularGrid(double dist, double outer, double inner,\n                           double xcos, double ycos, double zcos,\n                           int nradii, int naz, double wavelength, double flux, const Medium& m) {\n        double n = m.getN(wavelength);\n\n        // Determine number of rays at each radius\n        std::vector<int> nphis(nradii);\n        double drfrac = (outer-inner)/(nradii-1)/outer;\n        double rfrac = 1.0;\n        for (int i=0; i<nradii; i++) {\n            nphis[i] = int(std::ceil(naz*rfrac/6.))*6;\n            rfrac -= drfrac;\n        }\n        // Point in the center is a special case\n        if (inner == 0.0)\n            nphis[nradii-1] = 1;\n        int nray = std::accumulate(nphis.begin(), nphis.end(), 0);\n\n        std::vector<Ray> result;\n        result.reserve(nray);\n\n        // The \"velocities\" of all the rays in the grid are the same.\n        Vector3d v(xcos, ycos, zcos);\n        v.normalize();\n        v /= n;\n\n        rfrac = 1.0;\n        for (int i=0; i<nradii; i++) {\n            double az = 0.0;\n            double daz = 2*M_PI/nphis[i];\n            double radius = rfrac*outer;\n            for (int j=0; j<nphis[i]; j++) {\n                Vector3d r(radius*std::cos(az), radius*std::sin(az), 0);\n                double t = (r + v*n*dist).dot(v) * n * n;\n                result.emplace_back(r-v*t, v, 0, wavelength, flux, false);\n                az += daz;\n            }\n            rfrac -= drfrac;\n        }\n        return RayVector(std::move(result), wavelength);\n    }\n\n    RayVector pointSourceCircularGrid(const Vector3d& source, double outer, double inner,\n                                      int nradii, int naz, double wavelength, double flux,\n                                      const Medium& m) {\n        double n = m.getN(wavelength);\n\n        // Determine largest and smallest axial angle.\n        double dist = source.norm();\n        double thetaMax = std::atan(outer/dist);\n        double thetaMin = std::atan(inner/dist);\n\n        // Determine number of rays at each angle\n        std::vector<int> nphis(nradii);\n        double dthetaFrac = (thetaMax-thetaMin)/(nradii-1)/thetaMax;\n        double thetaFrac = 1.0;\n        for (int i=0; i<nradii; i++) {\n            nphis[i] = int(std::ceil(naz*thetaFrac/6.))*6;\n            thetaFrac -= dthetaFrac;\n        }\n        // Point in the center is a special case\n        if (inner == 0.0)\n            nphis[nradii-1] = 1;\n        int nray = std::accumulate(nphis.begin(), nphis.end(), 0);\n\n        std::vector<Ray> result;\n        result.reserve(nray);\n\n        // Rotation matrix from z-axis aligned to actual source axis.\n        Vector3d axis = -source.cross(Vector3d::UnitZ()).normalized();\n        double angle = std::acos(source.normalized().dot(Vector3d::UnitZ()));\n        Matrix3d rot2 = AngleAxisd(angle, axis).toRotationMatrix();\n\n        thetaFrac = 1.0;\n        for (int i=0; i<nradii; i++) {\n            double az = 0.0;\n            double daz = 2*M_PI/nphis[i];\n            double theta = thetaFrac*thetaMax;\n            Vector3d vref(std::sin(theta), 0, -std::cos(theta));\n            vref /= n;\n            for (int j=0; j<nphis[i]; j++) {\n                // Rotate vref around the z axis.\n                Matrix3d rot1 = AngleAxisd(az, Vector3d::UnitZ()).toRotationMatrix();\n                Vector3d v = rot2*rot1*vref;\n                result.emplace_back(source, v, 0, wavelength, flux, false);\n                az += daz;\n            }\n            thetaFrac -= dthetaFrac;\n        }\n        return RayVector(std::move(result), wavelength);\n    }\n}\n", "meta": {"hexsha": "0e48531e1371d4089751ea51c329f36053145198", "size": 6215, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/batoid.cpp", "max_stars_repo_name": "dkirkby/batoid", "max_stars_repo_head_hexsha": "734dccc289eb7abab77a62cdc14563ed5981753b", "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/batoid.cpp", "max_issues_repo_name": "dkirkby/batoid", "max_issues_repo_head_hexsha": "734dccc289eb7abab77a62cdc14563ed5981753b", "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/batoid.cpp", "max_forks_repo_name": "dkirkby/batoid", "max_forks_repo_head_hexsha": "734dccc289eb7abab77a62cdc14563ed5981753b", "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.3641975309, "max_line_length": 98, "alphanum_fraction": 0.5209975865, "num_tokens": 1636, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4848210064658687}}
{"text": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\n#include <Eigen/Dense>\n\n// Uncomment if you want to use this structure for TripletMatrix\ntemplate <class scalar>\nstruct Triplet {\n    \n};\n\ntemplate <class scalar>\nstruct TripletMatrix {\n    // TODO: insert here members and methods to TripletMatrix\n    \n    // densify() prototype\n    Eigen::Matrix<scalar, -1, -1> densify() const;\n};\n\n// Uncomment if you want to use this structure for CRSMatrix\n// template <class scalar>\n// struct ColValPair {\n//     \n// };\n\ntemplate <class scalar>\nstruct CRSMatrix {\n    // TODO: insert here members and methods to CRSMatrix\n    \n    // densify() prototype\n    Eigen::Matrix<scalar, -1, -1> densify() const;\n};\n\ntemplate <class scalar>\nvoid tripletToCRS(const TripletMatrix<scalar> & T, CRSMatrix<scalar> & C) {\n    // TODO: conversion function\n}\n\n//! \\brief overload of operator << for output of Triplet Matrix (debug).\n//! WARNING: uses densify() so there may be a lot of fill-in\n//! this allows something like std::cout << S\n//! \\param o standard output stream\n//! \\param S matrix in Triplet matrix format\n//! \\return a ostream o, s.t. you can write o << A << B;\nstd::ostream & operator<<(std::ostream & o, const TripletMatrix<double> & S) {\n    return o << S.densify();\n}\n\n//! \\brief overload of operator << for output of CRS Matrix (debug).\n//! WARNING: uses densify() so there may be a lot of fill-in\n//! this allows something like std::cout << S\n//! \\param o standard output stream\n//! \\param S matrix in CRS matrix format\n//! \\return a ostream o, s.t. you can write o << A << B;\nstd::ostream & operator<<(std::ostream & o, const CRSMatrix<double> & S) {\n    return o << S.densify();\n}\n\nint main() {\n    //// Correctness test\n    std::size_t nrows = 7, ncols = 5, ntriplets = 9;\n    \n    TripletMatrix<double> T;\n    CRSMatrix<double> C;\n    \n    // TODO: contrtuct T here\n    // TODO: Use this loop to push back triplets in your matrix\n    for(auto i = 0u; i < ntriplets; ++i) {\n        // TODO: Insert triplet (rand() % nrows, rand() % ncols, rand() % 1000))\n    }\n    \n    std::cout << \"***Test conversion with random matrices***\" << std::endl;\n    tripletToCRS(T, C);\n    // TODO: Uncomment if you implemented densify()\n//     std::cout << \"--> Frobenius norm of T - C: \" << (T.densify()-C.densify()).norm() << std::endl;\n    std::cout << \"T = \" << std::endl << T << std::endl;\n    std::cout << \"C = \" << std::endl << C << std::endl;\n}\n", "meta": {"hexsha": "d098c0f7ddf13e9d3c2447d029090c0d581b38cb", "size": 2444, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/solutions/solution_3/tripletToCRS.cpp", "max_stars_repo_name": "valentinjacot/backupETHZ", "max_stars_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T10:21:30.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-25T10:21:30.000Z", "max_issues_repo_path": "Nummerical Methods for CSE/solutions/solution_3/tripletToCRS.cpp", "max_issues_repo_name": "valentinjacot/backupETHZ", "max_issues_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Nummerical Methods for CSE/solutions/solution_3/tripletToCRS.cpp", "max_forks_repo_name": "valentinjacot/backupETHZ", "max_forks_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_forks_repo_licenses": ["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.55, "max_line_length": 101, "alphanum_fraction": 0.6321603928, "num_tokens": 669, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.8128673201042492, "lm_q1q2_score": 0.48482100156336455}}
{"text": "#include \"smmap/gurobi_solvers.h\"\n#include <gurobi_c++.h>\n#include <iostream>\n#include <mutex>\n#include <Eigen/Eigenvalues>\n\nusing namespace Eigen;\n\nstatic std::mutex gurobi_env_construct_mtx;\n\nGRBQuadExpr normSquared(const std::vector<GRBLinExpr>& exprs)\n{\n    GRBQuadExpr vector_norm_squared = 0;\n\n    // TODO: replace with a single call to addTerms?\n    for (size_t expr_ind = 0; expr_ind < exprs.size(); expr_ind++)\n    {\n        vector_norm_squared += exprs[expr_ind] * exprs[expr_ind];\n    }\n\n    return vector_norm_squared;\n}\n\nGRBQuadExpr normSquared(const std::vector<GRBLinExpr>& exprs, const VectorXd& weights)\n{\n    assert(exprs.size() == (size_t)weights.rows());\n    GRBQuadExpr vector_norm_squared = 0;\n\n    // TODO: replace with a single call to addTerms?\n    for (size_t expr_ind = 0; expr_ind < exprs.size(); expr_ind++)\n    {\n        vector_norm_squared += weights((ssize_t)expr_ind) * exprs[expr_ind] * exprs[expr_ind];\n    }\n\n    return vector_norm_squared;\n}\n\nGRBQuadExpr normSquared(GRBVar* vars, const ssize_t num_vars)\n{\n    GRBQuadExpr vector_norm_squared = 0;\n\n    // TODO: replace with a single call to addTerms?\n    for (ssize_t var_ind = 0; var_ind < num_vars; var_ind++)\n    {\n        vector_norm_squared += vars[var_ind] * vars[var_ind];\n    }\n\n    return vector_norm_squared;\n}\n\nstd::vector<GRBLinExpr> buildVectorOfExperssions(const MatrixXd& A, GRBVar* vars, const VectorXd& b)\n{\n    const ssize_t num_expr = A.rows();\n    const ssize_t num_vars = A.cols();\n    std::vector<GRBLinExpr> exprs(num_expr, 0);\n\n    for (ssize_t expr_ind = 0; expr_ind < num_expr; expr_ind++)\n    {\n        for (ssize_t var_ind = 0; var_ind < num_vars; var_ind++)\n        {\n            exprs[expr_ind] += A(expr_ind, var_ind) * vars[var_ind];\n        }\n        exprs[expr_ind] -= b(expr_ind);\n    }\n\n    return exprs;\n}\n\nVectorXd smmap::minSquaredNorm(const MatrixXd& A, const VectorXd& b, const double max_x_norm)\n{\n    VectorXd x;\n    GRBVar* vars = nullptr;\n    try\n    {\n        const ssize_t num_vars = A.cols();\n        const std::vector<double> lb(num_vars, -max_x_norm);\n        const std::vector<double> ub(num_vars, max_x_norm);\n\n        // TODO: Find a way to put a scoped lock here\n        gurobi_env_construct_mtx.lock();\n        GRBEnv env;\n        gurobi_env_construct_mtx.unlock();\n\n        env.set(GRB_IntParam_OutputFlag, 0);\n        GRBModel model(env);\n        vars = model.addVars(lb.data(), ub.data(), nullptr, nullptr, nullptr, (int)num_vars);\n        model.update();\n\n        model.addQConstr(normSquared(vars, num_vars), GRB_LESS_EQUAL, max_x_norm * max_x_norm);\n        model.setObjective(normSquared(buildVectorOfExperssions(A, vars, b)), GRB_MINIMIZE);\n        model.update();\n        model.optimize();\n\n        if (model.get(GRB_IntAttr_Status) == GRB_OPTIMAL)\n        {\n            x.resize(num_vars);\n            for (ssize_t var_ind = 0; var_ind < num_vars; var_ind++)\n            {\n                x(var_ind) = vars[var_ind].get(GRB_DoubleAttr_X);\n            }\n        }\n        else\n        {\n            std::cout << \"Status: \" << model.get(GRB_IntAttr_Status) << std::endl;\n            exit(-1);\n        }\n    }\n    catch(GRBException e)\n    {\n        std::cout << \"Error code = \" << e.getErrorCode() << std::endl;\n        std::cout << e.getMessage() << std::endl;\n    }\n    catch(...)\n    {\n        std::cout << \"Exception during optimization\" << std::endl;\n    }\n\n    delete[] vars;\n    return x;\n}\n\nVectorXd smmap::minSquaredNorm(const MatrixXd& A, const VectorXd& b, const double max_x_norm, const VectorXd& weights)\n{\n    VectorXd x;\n    GRBVar* vars = nullptr;\n    try\n    {\n        const ssize_t num_vars = A.cols();\n        const std::vector<double> lb(num_vars, -max_x_norm);\n        const std::vector<double> ub(num_vars, max_x_norm);\n\n        // TODO: Find a way to put a scoped lock here\n        gurobi_env_construct_mtx.lock();\n        GRBEnv env;\n        gurobi_env_construct_mtx.unlock();\n\n        env.set(GRB_IntParam_OutputFlag, 0);\n        GRBModel model(env);\n        vars = model.addVars(lb.data(), ub.data(), nullptr, nullptr, nullptr, (int)num_vars);\n        model.update();\n\n        model.addQConstr(normSquared(vars, num_vars), GRB_LESS_EQUAL, max_x_norm * max_x_norm);\n\n        GRBQuadExpr objective_fn = normSquared(buildVectorOfExperssions(A, vars, b), weights);\n        // Check if we need to add anything extra to the main diagonal.\n        const VectorXd eigenvalues = (A.transpose() * weights.asDiagonal() * A).selfadjointView<Upper>().eigenvalues();\n        if ((eigenvalues.array() < 1.1e-4).any())\n        {\n            const std::vector<double> diagonal(num_vars, 1.1e-4 - eigenvalues.minCoeff());\n            objective_fn.addTerms(diagonal.data(), vars, vars, (int)num_vars);\n        }\n        model.setObjective(objective_fn, GRB_MINIMIZE);\n\n        model.update();\n        model.optimize();\n\n        if (model.get(GRB_IntAttr_Status) == GRB_OPTIMAL)\n        {\n            x.resize(num_vars);\n            for (ssize_t var_ind = 0; var_ind < num_vars; var_ind++)\n            {\n                x(var_ind) = vars[var_ind].get(GRB_DoubleAttr_X);\n            }\n        }\n        else\n        {\n            std::cout << \"Status: \" << model.get(GRB_IntAttr_Status) << std::endl;\n            exit(-1);\n        }\n    }\n    catch(GRBException e)\n    {\n        std::cout << \"Error code = \" << e.getErrorCode() << std::endl;\n        std::cout << e.getMessage() << std::endl;\n    }\n    catch(...)\n    {\n        std::cout << \"Exception during optimization\" << std::endl;\n    }\n\n    delete[] vars;\n    return x;\n}\n\nEigen::VectorXd smmap::minSquaredNormSE3VelocityConstraints(const Eigen::MatrixXd& A, const Eigen::VectorXd& b, const double max_se3_velocity, const Eigen::VectorXd& weights)\n{\n    VectorXd x;\n    GRBVar* vars = nullptr;\n    try\n    {\n        const ssize_t num_vars = A.cols();\n        assert(num_vars % 6 == 0);\n\n        const std::vector<double> lb(num_vars, -max_se3_velocity);\n        const std::vector<double> ub(num_vars, max_se3_velocity);\n\n        // TODO: Find a way to put a scoped lock here\n        gurobi_env_construct_mtx.lock();\n        GRBEnv env;\n        gurobi_env_construct_mtx.unlock();\n\n        env.set(GRB_IntParam_OutputFlag, 0);\n        GRBModel model(env);\n        vars = model.addVars(lb.data(), ub.data(), nullptr, nullptr, nullptr, (int)num_vars);\n        model.update();\n\n        // Add the SE3 velocity constraints\n        for (int i = 0; i < num_vars / 6; i++)\n        {\n            model.addQConstr(normSquared(&vars[i * 6], 6), GRB_LESS_EQUAL, max_se3_velocity * max_se3_velocity);\n        }\n\n        GRBQuadExpr objective_fn = normSquared(buildVectorOfExperssions(A, vars, b), weights);\n        // Check if we need to add anything extra to the main diagonal.\n        const VectorXd eigenvalues = (A.transpose() * weights.asDiagonal() * A).selfadjointView<Upper>().eigenvalues();\n        if ((eigenvalues.array() < 1.1e-4).any())\n        {\n            std::vector<double> diagonal(num_vars, 1.1e-4 - eigenvalues.minCoeff());\n            objective_fn.addTerms(diagonal.data(), vars, vars, (int)num_vars);\n        }\n        model.setObjective(objective_fn, GRB_MINIMIZE);\n\n        model.update();\n        model.optimize();\n\n        if (model.get(GRB_IntAttr_Status) == GRB_OPTIMAL)\n        {\n            x.resize(num_vars);\n            for (ssize_t var_ind = 0; var_ind < num_vars; var_ind++)\n            {\n                x(var_ind) = vars[var_ind].get(GRB_DoubleAttr_X);\n            }\n        }\n        else\n        {\n            std::cout << \"Status: \" << model.get(GRB_IntAttr_Status) << std::endl;\n            exit(-1);\n        }\n    }\n    catch(GRBException e)\n    {\n        std::cout << \"Error code = \" << e.getErrorCode() << std::endl;\n        std::cout << e.getMessage() << std::endl;\n    }\n    catch(...)\n    {\n        std::cout << \"Exception during optimization\" << std::endl;\n    }\n\n    delete[] vars;\n    return x;\n}\n", "meta": {"hexsha": "aa19dc5c9fca660afbe1c21c7e1caec19d3d0f36", "size": 7945, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "smmap/src/gurobi_solvers.cpp", "max_stars_repo_name": "UM-ARM-Lab/mab_ms", "max_stars_repo_head_hexsha": "f199f05b88060182cfbb47706bd1ff3479032c43", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-08-20T12:12:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-06T09:43:27.000Z", "max_issues_repo_path": "smmap/src/gurobi_solvers.cpp", "max_issues_repo_name": "UM-ARM-Lab/mab_ms", "max_issues_repo_head_hexsha": "f199f05b88060182cfbb47706bd1ff3479032c43", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "smmap/src/gurobi_solvers.cpp", "max_forks_repo_name": "UM-ARM-Lab/mab_ms", "max_forks_repo_head_hexsha": "f199f05b88060182cfbb47706bd1ff3479032c43", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-31T03:12:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T03:12:23.000Z", "avg_line_length": 31.4031620553, "max_line_length": 174, "alphanum_fraction": 0.6010069226, "num_tokens": 2078, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128672997041659, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4848210010581859}}
{"text": "#include <boost/math/distributions/laplace.hpp>\n", "meta": {"hexsha": "e434f1e03ed4f9fe02f552d934034350620002a7", "size": 48, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_distributions_laplace.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_distributions_laplace.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_distributions_laplace.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 24.0, "max_line_length": 47, "alphanum_fraction": 0.8125, "num_tokens": 11, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128672997041659, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4848210010581859}}
{"text": "#include <boost/numeric/odeint/stepper/symplectic_rkn_sb3a_m4_mclachlan.hpp>\n", "meta": {"hexsha": "4e1788f95e740708c56489ebfd27370f6459576b", "size": 77, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_numeric_odeint_stepper_symplectic_rkn_sb3a_m4_mclachlan.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_numeric_odeint_stepper_symplectic_rkn_sb3a_m4_mclachlan.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_numeric_odeint_stepper_symplectic_rkn_sb3a_m4_mclachlan.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 38.5, "max_line_length": 76, "alphanum_fraction": 0.8701298701, "num_tokens": 28, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128672997041659, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4848210010581859}}
{"text": "#include <gtest/gtest.h>\n#include <Eigen/Dense>\n\n#include \"refill/distributions/gaussian_distribution.h\"\n\nnamespace refill {\n\nTEST(GaussianDistributionTest, ConstructorTests) {\n  GaussianDistribution* dist = new GaussianDistribution();\n\n  ASSERT_EQ(1, dist->dimension())<< \"Dimension not correct.\";\n  ASSERT_EQ(Eigen::VectorXd::Zero(1), dist->mean())<< \"Mean not correct\";\n  ASSERT_EQ(Eigen::MatrixXd::Identity(1, 1), dist->cov())\n      << \"Covariance not correct\";\n\n  delete dist;\n  dist = new GaussianDistribution(2);\n\n  ASSERT_EQ(2, dist->dimension())<< \"Dimension not correct\";\n  ASSERT_EQ(Eigen::Vector2d::Zero(), dist->mean())<< \"Mean not correct\";\n  ASSERT_EQ(Eigen::Matrix2d::Identity(), dist->cov())\n      << \"Covariance not correct\";\n\n  delete dist;\n  dist = new GaussianDistribution(Eigen::Vector2d::Zero(),\n                                  Eigen::Matrix2d::Identity());\n\n  ASSERT_EQ(2, dist->dimension())<< \"Dimension not correct\";\n  ASSERT_EQ(Eigen::Vector2d::Zero(), dist->mean())<< \"Mean not correct\";\n  ASSERT_EQ(Eigen::Matrix2d::Identity(), dist->cov())\n      << \"Covariance not correct\";\n\n  GaussianDistribution dist_4(*dist);\n\n  ASSERT_EQ(2, dist_4.dimension())<< \"Dimension not correct\";\n  ASSERT_EQ(Eigen::Vector2d::Zero(), dist_4.mean())<< \"Mean not correct\";\n  ASSERT_EQ(Eigen::Matrix2d::Identity(), dist_4.cov())\n      << \"Covariance not correct\";\n}\n\nTEST(GaussianDistributionTest, SetterTests) {\n  GaussianDistribution dist(2);\n\n  dist.setDistributionParameters(Eigen::Vector2d::Ones(),\n                                 Eigen::Matrix2d::Identity() * 2.0);\n\n  ASSERT_EQ(2, dist.dimension())<< \"Dimension not correct\";\n  ASSERT_EQ(Eigen::Vector2d::Ones(), dist.mean())<< \"Mean not correct\";\n  ASSERT_EQ(Eigen::Matrix2d::Identity() * 2.0, dist.cov())\n      << \"Covariance not correct\";\n\n  dist.setMean(Eigen::Vector2d::Constant(2.0));\n\n  ASSERT_EQ(2, dist.dimension())<< \"Dimension not correct\";\n  ASSERT_EQ(Eigen::Vector2d::Constant(2.0), dist.mean())<< \"Mean not correct\";\n  ASSERT_EQ(Eigen::Matrix2d::Identity() * 2.0, dist.cov())\n      << \"Covariance not correct\";\n\n  dist.setCov(Eigen::Matrix2d::Identity() * 3.0);\n\n  ASSERT_EQ(2, dist.dimension())<< \"Dimension not correct\";\n  ASSERT_EQ(Eigen::Vector2d::Constant(2.0), dist.mean())<< \"Mean not correct\";\n  ASSERT_EQ(Eigen::Matrix2d::Identity() * 3.0, dist.cov())\n      << \"Covariance not correct\";\n}\n\nTEST(GaussianDistributionTest, OperatorTests) {\n  GaussianDistribution dist_1(Eigen::Vector2d::Zero(),\n                              Eigen::Matrix2d::Identity());\n  GaussianDistribution dist_2(Eigen::Vector2d::Ones(),\n                              Eigen::Matrix2d::Identity() * 2.0);\n\n  dist_1 += dist_2;\n\n  ASSERT_EQ(2, dist_1.dimension())<< \"Dimension not correct\";\n  ASSERT_EQ(Eigen::Vector2d::Ones(), dist_1.mean())<< \"Mean not correct\";\n  ASSERT_EQ(Eigen::Matrix2d::Identity() * 3.0, dist_1.cov())\n      << \"Covariance not correct\";\n\n  dist_1 -= dist_2;\n\n  ASSERT_EQ(2, dist_1.dimension())<< \"Dimension not correct\";\n  ASSERT_EQ(Eigen::Vector2d::Zero(), dist_1.mean())<< \"Mean not correct\";\n  ASSERT_EQ(Eigen::Matrix2d::Identity() * 5.0, dist_1.cov())\n      << \"Covariance not correct\";\n\n  GaussianDistribution dist_3 = dist_1 + dist_2;\n\n  ASSERT_EQ(2, dist_3.dimension())<< \"Dimension not correct\";\n  ASSERT_EQ(Eigen::Vector2d::Ones(), dist_3.mean())<< \"Mean not correct\";\n  ASSERT_EQ(Eigen::Matrix2d::Identity() * 7.0, dist_3.cov())\n      << \"Covariance not correct\";\n\n  GaussianDistribution dist_4 = dist_1 - dist_2;\n\n  ASSERT_EQ(2, dist_4.dimension())<< \"Dimension not correct\";\n  ASSERT_EQ(Eigen::Vector2d::Constant(-1.0), dist_4.mean())\n      << \"Mean not correct\";\n  ASSERT_EQ(Eigen::Matrix2d::Identity() * 7.0, dist_4.cov())\n      << \"Covariance not correct\";\n\n  dist_4.setDistributionParameters(Eigen::Vector2d::Ones(),\n                                   Eigen::Matrix2d::Identity());\n\n  GaussianDistribution dist_5 = Eigen::Matrix2d::Ones() * dist_4;\n\n  ASSERT_EQ(2, dist_5.dimension())<< \"Dimension not correct\";\n  ASSERT_EQ(Eigen::Vector2d::Constant(2.0), dist_5.mean())<< \"Mean not correct\";\n  ASSERT_EQ(Eigen::Matrix2d::Constant(2.0), dist_5.cov())\n      << \"Covariance not correct\";\n\n  GaussianDistribution dist_6 = 2.0 * dist_4;\n\n  ASSERT_EQ(2, dist_6.dimension())<< \"Dimension not correct\";\n  ASSERT_EQ(Eigen::Vector2d::Constant(2.0), dist_6.mean())<< \"Mean not correct\";\n  ASSERT_EQ(Eigen::Matrix2d::Identity() * 4.0, dist_6.cov())\n      <<\"Covariance not correct\";\n}\n\nTEST(GaussianDistributionTest, PdfEvaluationTest) {\n    GaussianDistribution distribution(2);\n\n    double evaluation = distribution.evaluatePdf(Eigen::VectorXd::Zero(2));\n\n    double expected_evaluation = 1 / (2 * M_PI);\n\n    EXPECT_EQ(expected_evaluation, evaluation);\n}\n\nTEST(GaussianDistributionTest, VectorizedEvaluationTest) {\n    GaussianDistribution distribution(2);\n\n    Eigen::Vector2d evaluation =\n        distribution.evaluatePdfVectorized(Eigen::MatrixXd::Zero(2, 2));\n\n    Eigen::Vector2d expected_evaluation =\n        Eigen::Vector2d::Constant(1 / (2 * M_PI));\n\n    EXPECT_EQ(expected_evaluation, evaluation);\n}\n\n}  // namespace refill\n", "meta": {"hexsha": "41ee832205cf88a01ed0fd3ee5ce887d8bb0bf64", "size": 5122, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/tests/gaussian_distribution_test.cc", "max_stars_repo_name": "jwidauer/refill", "max_stars_repo_head_hexsha": "64947e0a8e15855f4a5ad048f09f8d38715bbe91", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-06-13T07:28:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-08T11:26:34.000Z", "max_issues_repo_path": "src/tests/gaussian_distribution_test.cc", "max_issues_repo_name": "jwidauer/refill", "max_issues_repo_head_hexsha": "64947e0a8e15855f4a5ad048f09f8d38715bbe91", "max_issues_repo_licenses": ["MIT"], "max_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/gaussian_distribution_test.cc", "max_forks_repo_name": "jwidauer/refill", "max_forks_repo_head_hexsha": "64947e0a8e15855f4a5ad048f09f8d38715bbe91", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-06-01T13:21:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-01T20:33:20.000Z", "avg_line_length": 35.8181818182, "max_line_length": 80, "alphanum_fraction": 0.6706364701, "num_tokens": 1421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743735019595, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.4847363057494582}}
{"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#ifndef NORMAL_FITNESS_METRIC_HPP_\n#define NORMAL_FITNESS_METRIC_HPP_\n\n#include <boost/math/constants/constants.hpp>\n#include <vector>\n#include <cmath>\n\n#include \"clotho/fitness/ifitness.hpp\"\n\nextern const std::string NORM_NAME;\n\n/**\n * univariate normal distribution function\n *\n * Note: for k-dimensional trait vector the fitness is based on the phenotype of\n * only the first trait\n */\nclass normal_fitness_metric : public ifitness {\npublic:\n    typedef double      real_type;\n    typedef real_type   result_type;\n\n    normal_fitness_metric( real_type mu = 0., real_type sigma = 1. );\n\n    result_type operator()( double x );\n    result_type operator()( float x ) { return operator()( (double) x ); }\n\n    result_type operator()( double x, real_type mu, real_type sigma );\n    result_type operator()( float x, real_type mu, real_type sigma ) { return operator()( (double) x, mu, sigma); }\n\n    inline result_type operator()( const std::vector< double > & multi_variate ) {\n        return ((multi_variate.empty()) ? operator()( 0. ) : operator()( multi_variate.front() ));\n    }\n\n    inline result_type operator()( const std::vector< float > & multi_variate ) {\n        return ((multi_variate.empty()) ? operator()( 0. ) : operator()( multi_variate.front() ));\n    }\n\n    inline result_type operator()( const std::vector< double > & multi_variate, real_type mu, real_type sigma ) {\n        return ((multi_variate.empty()) ? operator()( 0., mu, sigma ) : operator()( multi_variate.front(), mu, sigma ));\n    }\n\n    inline result_type operator()( const std::vector< float > & multi_variate, real_type mu, real_type sigma ) {\n        return ((multi_variate.empty()) ? operator()( 0., mu, sigma ) : operator()( multi_variate.front(), mu, sigma ));\n    }\n\n    inline result_type operator()( double * first, double * last ) {\n        return (first == last) ? operator()( 0. ) : operator()( *first );\n    }\n\n    inline result_type operator()( float * first, float * last ) {\n        return (first == last) ? operator()( 0. ) : operator()( *first );\n    }\n\n    const std::string name() const;\n\n    void log( std::ostream & out ) const;\n\n    virtual ~normal_fitness_metric();\n\nprotected:\n    real_type m_mean;\n    real_type m_sigma;\n\n    real_type _coeff, _denom;\n};\n\n#endif  // NORMAL_FITNESS_METRIC_HPP_\n", "meta": {"hexsha": "dd709a13d926793c7d5d0c22650d5c0845f99cdb", "size": 2910, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/clotho/fitness/normal_fitness_metric.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/fitness/normal_fitness_metric.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/fitness/normal_fitness_metric.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": 35.487804878, "max_line_length": 120, "alphanum_fraction": 0.6749140893, "num_tokens": 688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.4847362882714712}}
{"text": "#include <stdio.h>\n#include <omp.h>\n\n#include <iostream>\n\n#include <Eigen/Dense>\n#include <Parareal/core.h>\n#include <Parareal/backward_euler.h>\n\n#include \"rhs_linear1d.h\"\n\ntypedef Eigen::VectorXd Evec;\ntypedef Eigen::MatrixXd Emat;\n\nint main(int argc, char **argv)\n{\n  ode_system ode;\n  ode.dimension = 1; ode.t_init = 0; ode.t_final = 1;\n  ode.y0 = Evec(1); ode.y0(0) = 1;\n  ode.f = std::function<int(double, Evec&, Evec&)>(&linear1d);\n  ode.J = std::function<int(double, Evec&, Emat&)>(&linear1d_jac);\n\n  time_stepper solver; \n\n  // Backward Euler \n  solver.dt = 0.1;\n  solver.F = std::function<int(ode_system&, double, Evec &)>(&backward_euler);\n  solver.F_allt = std::function<int(ode_system&, double, Emat &)>(&backward_euler_allt);\n\n  int steps = ode.num_steps(solver.dt);\n  double tt = 0.0;\n\n  // Parareal Solver\n  Emat yf(steps, ode.dimension);\n  tt = omp_get_wtime();\n  solver.integrate_allt(ode, yf);\n  tt = omp_get_wtime() - tt;\n\n  std::cout << yf << std::endl;\n  printf(\"Time taken %f\\n\", tt);\n\n  return 0;\n}\n", "meta": {"hexsha": "433f55cde239a9ef8285031a25b88e21b0fdd063", "size": 1022, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tests/linear1d_be/test_be.cpp", "max_stars_repo_name": "abhijit-c/Parareal", "max_stars_repo_head_hexsha": "e64c8ae44577da7e92720aa12b12f28acb3fc473", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-08-01T19:31:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-08T13:54:15.000Z", "max_issues_repo_path": "Tests/linear1d_be/test_be.cpp", "max_issues_repo_name": "abhijit-c/Parareal", "max_issues_repo_head_hexsha": "e64c8ae44577da7e92720aa12b12f28acb3fc473", "max_issues_repo_licenses": ["MIT"], "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/linear1d_be/test_be.cpp", "max_forks_repo_name": "abhijit-c/Parareal", "max_forks_repo_head_hexsha": "e64c8ae44577da7e92720aa12b12f28acb3fc473", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-09-25T00:02:33.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-25T00:02:33.000Z", "avg_line_length": 23.2272727273, "max_line_length": 88, "alphanum_fraction": 0.6643835616, "num_tokens": 332, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.4847362832859883}}
{"text": "#include <iostream>\n#include <vector>\n#include <unordered_map>\n#include <fstream>\n#include <boost/functional/hash.hpp>\n#include <algorithm>\n#include <utility>\n#include <cassert>\n#include <chrono>\n#include <iomanip>\n\nusing namespace std;\nusing namespace std::chrono;\n\n#define point pair<double, double>\n#define inter pair<bool, point>\nconst double doublePrecision = 1e-6;\nconst double delta = 1.0;\nconst double upperDelta = 1.0;\n\nstatic void print(point u) {\n\tcerr << setprecision(15) << u.first << \" \" << u.second << endl;\n}\n\n// Read pair of doubles.\nstatic vector<point> readBinary(char* fileName, int limitSize) {\n\tifstream input(fileName, ios::binary);\n    auto pos = input.tellg();\n    input.seekg( 0, ios::end );\n    auto size=input.tellg()-pos;\n    input.seekg(0,ios::beg);\n/*\n\tsize >>= 1;\n\tcerr <<\"size = \" << size << endl;\n\tint sizeToRead = limitSize == -1 ? size : (limitSize < size ? limitSize : size);\n\tvector<point> coord(sizeToRead);\n\tcerr << \"sizeToRead = \" << sizeToRead << endl; \n\tfor (unsigned index = 0; index < sizeToRead; ++index) {\n\t\tdouble x, y;\n\t\tinput.read(reinterpret_cast<char*>(&x), sizeof(double));\n\t\tinput.read(reinterpret_cast<char*>(&y), sizeof(double));\n\t\tlong double x0 = static_cast<long double>(x);\n\t\tlong double y0 = static_cast<long double>(y);\n\t\tcoord[index] = make_pair(x0, y0 + delta);\n\t\tif (index < 10)\n\t\t\tprint(coord[index]);\n\t}\n\treturn coord;\n*/\n    unsigned elements = size / sizeof(point);\n    if (limitSize != -1)\n    \telements = limitSize < elements ? limitSize : elements;\n    vector<point> cdf;\n    cdf.resize(elements);\n    input.read(reinterpret_cast<char*>(cdf.data()), elements * sizeof(point));\n    return cdf;\n}\n\n// Write the sample points in a binary file.\nstatic void writeBinary(char* fileName, vector<point>& samplePoints) {\n\tofstream output(fileName, ios::binary);\n\tfor (point p: samplePoints) {\n\t\tdouble x = static_cast<double>(p.first);\n\t\tdouble y = static_cast<double>(p.second - delta);\n\t\toutput.write(reinterpret_cast<char*>(&x), sizeof(double));\n\t\toutput.write(reinterpret_cast<char*>(&y), sizeof(double));\n\t}\n}\n\n// Read from a .txt file.\nstatic vector<point> readTxt(char* fileName) {\n\tifstream input(fileName);\n\tvector<point> coord;\n\tdouble x, y;\n\twhile (input >> x >> y) {\n\t\tlong double x0 = static_cast<long double>(x);\n\t\tlong double y0 = static_cast<long double>(y);\n\t\tcoord.push_back(make_pair(x0, y0 + delta));\n\t}\n\treturn coord;\n}\n\n// Write into a .txt file\nstatic void writeTxt(char* fileName, vector<point>& samplePoints) {\n\tofstream output(fileName);\n\tfor (point p: samplePoints)\n\t\toutput << p.first << \" \" << (p.second - delta) << \"\\n\";\n}\n\n// Computes the position of the triple (u, v, w) in respect to pi.\nstatic int angle(bool counterclockwise, point u, point v, point w) {\n\tdouble ret = ((v.first - u.first) * (w.second - u.second) - (v.second - u.second) * (w.first - u.first));\n\treturn counterclockwise ? ret : -ret;\n}\n\nstatic double myabs(long double x) {\n\treturn (x < -doublePrecision) ? -x : x;\n}\n\n// Intersection of the lines (u1, u2) and (v1, v2).\nstatic inter intersection(point u1, point u2, point v1, point v2) {\n\tdouble a1 = u2.second - u1.second, b1 = u1.first - u2.first, c1 = a1 * u1.first + b1 * u1.second;\n\tdouble a2 = v2.second - v1.second, b2 = v1.first - v2.first, c2 = a2 * v1.first + b2 * v1.second;\n\tdouble det = a1 * b2 - a2 * b1;\n\n\t// compute with long double precision.\n\tif (abs(det) < doublePrecision) {\n\t\tcerr << \"ba e determinantul zero!!! Ia sa vedem, totusi\" << endl;\n\t\tprint(u1);\n\t\tprint(u2);\n\t\tprint(v1);\n\t\tprint(v2);\n\t\treturn make_pair(false, u1);\n\t}\n\treturn make_pair(true, make_pair((c1 * b2 - c2 * b1) / det, (a1 * c2 - a2 * c1) / det));\n\t/*if ((min(v1.first, v2.first) <= ret.first) && (ret.first <= max(v1.first, v2.first)) && (min(v1.second, v2.second) <= ret.second) && (ret.second <= max(v1.second, v2.second))) {\n\t\treturn ret;\n\t} else {\n\t\tprint(ret);\n\t\tprint(u1);\n\t\tprint(u2);\n\t\tprint(v1);\n\t\tprint(v2);\n\t\t//cerr << u1.firs << \" \"  << u2 << \" \" << v1 << \" \" << v2 << endl;\n\t\tassert(0);\n\t}*/\n}\n\ndouble globalEpsForChange;\ndouble minusEpsForChange;\n\npoint change(bool sign, vector<point>& coord, unsigned index) {\n    return sign ? make_pair(coord[index - 1].first, coord[index - 1].second * (1 + globalEpsForChange) + delta + upperDelta) \n                : make_pair(coord[index - 1].first, coord[index - 1].second + delta);\n}\n\n// Computes the samples points.\nvector<point> samplePointsOfApproximateFunction(vector<point>& coord, double eps) { \n\tunsigned n = coord.size();\n\n    globalEpsForChange = eps;\n    minusEpsForChange = 1e-2;\n    \n\tcerr << \"size of coord in funciton = \" << n << endl;\n\n\tpoint *windowBound = new point[2], *leftBound = new point[2], *rightBound = new point[2];\n\n\t// lists of neighbours.\n\tunordered_map<point, point, boost::hash<point>> *rightList = new unordered_map<point, point, boost::hash<point>>[2];\n\tunordered_map<point, point, boost::hash<point>> *leftList = new unordered_map<point, point, boost::hash<point>>[2];\n\t\n\t//map<point, point> *rightList = new map<point, point>[2];\n\t//map<point, point> *leftList = new map<point, point>[2]; \n\n\tcerr << \"before alloc\" << endl;\n\n\tvector<point> samplePoints;\n\t\n\tcerr << \"wwas???\" << endl;\n\n\t// Maybe we should reverse the order in points.\n\t/*for (unsigned index = 1; index <= n; ++index) {\n\t\tpoints[index][0] = make_pair(coord[index - 1].first, coord[index - 1].seconc * (1 - eps) + delta);\n\t\tpoints[index][1] = make_pair(coord[index - 1].first, coord[index - 1].second * (1 + eps) + delta + upperDelta);\n\t}*/\n\n\tcerr << \"Umwandeln\" << endl;\n\n\tfor (int sign = 1; sign >= 0; --sign) {\n        point p1 = change(sign, coord, 1), p2 = change(sign, coord, 2);\n        \n\t\twindowBound[sign] = p1;//points[1][sign];\n\t\tleftBound[sign] = p1;//points[1][sign];\n\t\trightBound[sign] = p1;//points[1][sign];\n\n\t\trightList[sign][p1] = p2;//points[2][sign];\n\t\tleftList[sign][p2] = p1;//points[1][sign];\n\t}\n\n\tfor (unsigned index = 3; index < n; ++index) {\n\t\t//cerr << \"now at index = \" << index << endl;\n\t\tbool nextWindow = false;\n\t\t// Updating convex hulls\n\t\tfor (int sign = 1; sign >= 0; --sign) {\n            point indexPoint = change(sign, coord, index);\n\t\t\tpoint currPoint = change(sign, coord, index - 1);\n            \n\t\t\twhile ((currPoint != windowBound[sign]) && (angle(sign, indexPoint, currPoint, leftList[sign][currPoint]) > doublePrecision))\n\t\t\t\tcurrPoint = leftList[sign][currPoint];\n\t\t\trightList[sign][currPoint] = indexPoint; //[index][sign];\n\t\t\tleftList[sign][indexPoint] = currPoint;\n\t\t}\n\n\t\tfor (int sign = 1; sign >= 0; --sign) {\n\t\t\tint star = sign, diamond = !sign;\n            point indexPointStar = change(star, coord, index);\n            point indexPointDiamond = change(diamond, coord, index);\n            point lastIndexPoint = change(star, coord, index - 1);\n            \n\t\t\tif ((!nextWindow) && (angle(star, indexPointStar, leftBound[star], rightBound[diamond]) < -doublePrecision)) {\n\t\t\t\t// Get new sample point.\n\t\t\t\t//cerr << \"found sth!\" << endl;\n\t\t\t\tinter value = intersection(leftBound[star], rightBound[diamond], windowBound[star], windowBound[diamond]);\n\t\t\t\tif (value.first == true) {\n\t\t\t\t\tsamplePoints.push_back(value.second);\n\t\t\t\t} else {\n\t\t\t\t\tcerr << \"For one sample point the determinant is 0!\" << endl;\n\t\t\t\t}\n\t\t\t\t//cerr << \"it's not him\" << endl;\n\n\t\t\t\t// Update the window.\n\t\t\t\twindowBound[diamond] = rightBound[diamond];\n\t\t\t\tvalue = intersection(leftBound[star], rightBound[diamond], lastIndexPoint, indexPointStar);\n\t\t\t\tif (value.first == true)\n\t\t\t\t\twindowBound[star] = value.second;\n\t\t\t\telse \n\t\t\t\t\tassert(0);\n\n\t\t\t\t// Update the lists.\n\t\t\t\trightList[star][windowBound[star]] = indexPointStar;\n\t\t\t\tleftList[star][indexPointStar] = windowBound[star];\n\n\t\t\t\t// Update rightBound\n\t\t\t\trightBound[star] = indexPointStar;\n\t\t\t\trightBound[diamond] = indexPointDiamond;\n\n\t\t\t\t// Update leftBound\n\t\t\t\tleftBound[star] = windowBound[star];\n\t\t\t\tleftBound[diamond] = windowBound[diamond];\n\t\t\t\n\t\t\t\twhile (angle(diamond, leftBound[diamond], rightBound[star], rightList[diamond][leftBound[diamond]]) < -doublePrecision)\n\t\t\t\t\tleftBound[diamond] = rightList[diamond][leftBound[diamond]];\n\t\t\t\tnextWindow = true;\n\t\t\t}\n\t\t}\n\n\t\t// Updating the supports and separating lines.\n\t\tif (!nextWindow) {\n\t\t\tfor (int sign = 1; sign >= 0; --sign) {\n\t\t\t\tint star = sign, diamond = !sign;\n                point indexPoint = change(star, coord, index);\n                \n\t\t\t\tif (angle(star, indexPoint, leftBound[diamond], rightBound[star]) < -doublePrecision) {\n\t\t\t\t\trightBound[star] = indexPoint;\n\t\t\t\t\twhile (angle(star, indexPoint, leftBound[diamond], rightList[diamond][leftBound[diamond]]) < -doublePrecision) \n\t\t\t\t\t\tleftBound[diamond] = rightList[diamond][leftBound[diamond]];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Compute the two last approximated points.\n\t// Quite weird here!\n\tcerr << \"by now\" << samplePoints.size() << endl;\n\t// I'm still confused if there is need for a condition here. \n\tcerr << \"n-ter Eintrag = \" << endl;\n\t//print(points[n][1]);\n\t//print(points[n][0]);\n\tcerr << \"leftBound + rightBound + windowBound\" << endl;\n\tfor (int sign = 1; sign >= 0; --sign) {\n\t\tprint(leftBound[sign]);\n\t\tprint(rightBound[sign]);\n\t\tprint(windowBound[sign]);\n\t}\n\n\tinter value = intersection(leftBound[0], rightBound[1], windowBound[1], windowBound[0]);\n\tif (value.first == true)\n\t\tsamplePoints.push_back(value.second);\n\telse\n\t\tcerr << \"Penultimul punct nu exista!\" << endl;\n\n\tvalue = intersection(leftBound[0], rightBound[1], change(1, coord, n), change(0, coord, n));\n\tif (value.first == true)\n\t\tsamplePoints.push_back(value.second);\n\telse\n\t\tcerr << \"Ultimul punct nu exista!\" << endl;\n\treturn samplePoints;\n}\n\nstatic double interpolate(vector<point>& spline, double pos, bool dump) {\n   if (pos <= spline.front().first)\n      return spline.front().second;\n   if (pos >= spline.back().first)\n      return spline.back().second;\n  \n\tauto iter=lower_bound(spline.begin(),spline.end(),pos,[](const point& a,double b) { return a.first<b; });\n\n   if (dump) cerr << \"(\" << (iter-1)->first << \",\" << (iter-1)->second << \") - \" << pos << \" - (\" << (iter+0)->first << \",\" << (iter+0)->second << \")\" << endl;\n   \n   if (iter->first == pos)\n      return iter->second;\n\n   double dx = iter->first - (iter - 1)->first;\n   double dy = iter->second - (iter - 1)->second;\n\n   double ofs = pos - (iter - 1)->first;\n   return (iter - 1)->second + ofs * (dy / dx);\n}\n\n/*\nstatic void convertBack(vector<point>& func) {\n\tfor (auto& e: func)\n\t\te.second -= delta;\n}\n*/\n\nstatic vector<point> compressFunc(vector<point>& func, unsigned desiredSize)\n// Compress to the desired size\n{\n\t// Relax a bit to speed up compression\n\tunsigned maxSize = desiredSize + (desiredSize / 100), minSize = desiredSize - (desiredSize / 100);\n\n\tcerr << maxSize << \" and min = \" << minSize << endl;\n\n\t// Fits?\n\tif (func.size()<=maxSize)\n\t\treturn func;\n\n\t// No, binary search\n\tlong long capacity = 1e9, left = 1, right = capacity;\n\tdouble mul = 1.0 / capacity;\n\t//long double last = 0;\n\twhile (left < right) {\n\t\tlong long middle=(left+right)/2;\n\t\n\n\t\tdouble epsilon = mul * middle;\n\t\t\t\tcerr << \"------------- Binary search for \" << epsilon << endl;\n\n\t\t//if (abs(epsilon - last) < doublePrecision)return \n\n\t\tif (myabs(epsilon - 1) < doublePrecision) {\n\t\t\treturn samplePointsOfApproximateFunction(func, epsilon);\n\t\t}\n\t\tif (myabs(epsilon - capacity) < doublePrecision) {\n\t\t\treturn samplePointsOfApproximateFunction(func, epsilon);\n\t\t}\n\n\t\tvector<point> candidate = samplePointsOfApproximateFunction(func, epsilon);\n\t\t\n\t\tcerr << \"done sample\" << endl;\n\t\tcerr << \"------------- Binary search for \" << epsilon << \" has \" << candidate.size() << endl;\n\n\t\tcerr << candidate.size() << \" \" << minSize << \" \" << maxSize << endl;\n\n\t\tif (candidate.size() < minSize) {\n\t \t\tright = middle;\n\t\t} else if (candidate.size()>maxSize) {\n\t \t\tleft = middle;\n\t\t} else {\n\t\t\tcerr << \"Found already in binary search = \" << middle << \" and epsilon \" << mul * middle << endl; \n\t\t\t//convertBack(candidate);\n\t \t\treturn candidate;\n\t\t}\n\t}\n\n\tcerr << \"At the end is left = \" << left << \" and so epsilon \" << (mul * left) << endl;\n\n   // Final call, this is the best we could get\n   vector<point> candidate = samplePointsOfApproximateFunction(func, mul * left);\n   //convertBack(candidate);\n   return candidate;\n}\n\nint mainn(int argc, char** argv) {\n\tif (argc != 7) {\n\t\tcout << \"Usage: ./a.out inputVariant(1 -> binary, 0 -> txt) inputFileName outputVariant(1 -> binary, 0 -> txt) outputFileName howManySupportingPoints howManyToRead\\n\";\n\t\treturn 1;\n\t}\n\tint inputVariant = atoi(argv[1]);\n\tchar* inputFileName = argv[2];\n\tint outputVariant = atoi(argv[3]);\n\tchar* outputFileName = argv[4];\n\tint countSupportingPoints = atoi(argv[5]);\n\tint countToRead = atoi(argv[6]);\n\n\tcerr << \"Begin of reading\" << endl;\n\tauto readingStart = high_resolution_clock::now();\n\n\tvector<point> coord;\n\tif (inputVariant == 1)\n\t\tcoord = readBinary(inputFileName, countToRead);\n\telse \n\t\tcoord = readTxt(inputFileName);\n\n\tauto readingStop = high_resolution_clock::now();\n\tcerr << \"Reading done!\" << endl;\n\t/*\n\tif (useSort) {\n\t\tcerr << \"Begin of sort\" << endl;\n\t\tcerr << \"wieder\" << coord.size() << endl;\n\t\tauto startSort = high_resolution_clock::now();\n\n\t\tsort(coord.begin(), coord.end());\n\n\t\tauto sortStop = high_resolution_clock::now();\n\t\tcerr << \"Sort done!\" << endl;\n\n\t\tcerr << \"wieder\" << coord.size() << endl;\n\n\t\t//writeBinary(outputFileName, coord);\n\t\t//return 0;\n\t}\n\t*/\n\tcerr << \"test\" << coord[0].first << \" \" << coord[0].second << endl;\n\tcerr << \"test\" << coord[1].first << \" \" << coord[1].second << endl;\n\n\tcerr << \"Begin of the algorithm\" << endl;\n\tauto startAlg = high_resolution_clock::now();\n\n\tcerr << \"count = \" << countSupportingPoints << endl;\n/*\n\tunsigned n = coord.size();\n\tpoints = new point*[n + 1];\n\tfor (unsigned index = 1; index <= n; ++index) {\n\t\tpoints[index] = new point[2];\n\t}\t\n*/\n\t//vector<point> samplePoints = compressFunc(coord, countSupportingPoints);\n\tvector<point> samplePoints = samplePointsOfApproximateFunction(coord, 1e-15);\n\n\tcerr << \"End of the algorithm\" << endl;\n\tauto algStop = high_resolution_clock::now();\n\n\tcerr << \"Begin of writing\" << endl;\n\tauto startWriting = high_resolution_clock::now();\n/*\n\tif (outputVariant == 1)\n\t\twriteBinary(outputFileName, samplePoints);\n\telse\n\t\twriteTxt(outputFileName, samplePoints);\n\t\n\tauto writingDone = high_resolution_clock::now();\n*/\n\tif (samplePoints.size() == 0) {\n\t\tcerr << \"alles falsch\" << endl;\n\t\treturn 0;\n\t}\n\t  double sumError = 0, maxError = 0;\n\t  for (auto e: coord) {\n          // TODO: I have put here a + delta! Don't forget that!\n\t     double estimate = interpolate(samplePoints, e.first, false);\n\t     double real = e.second + delta;\n\t     double diff = estimate-real;\n\t     if (diff<0) \n\t     \tdiff=-diff;\n\t     if (diff>maxError)\n\t        maxError=diff;\n\t     sumError+=diff;\n\t  }\n\t  cerr << samplePoints.size() << \" \" << maxError << \" \" << (sumError / coord.size()) << endl;\n\t\n\t//auto duration = duration_cast<milliseconds>(writingDone - readingStart);\n\t//cerr << \"Total time is = \" << duration.count() << endl;\n\treturn 0;\n}\n", "meta": {"hexsha": "c9fc05126c6fd2291634e889c2622e4f504d04f2", "size": 14976, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "planet.cpp", "max_stars_repo_name": "stoianmihail/Planet", "max_stars_repo_head_hexsha": "c1869fbab7a57ca635830ea478d85070763aba9a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-09-13T11:39:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-11T19:45:00.000Z", "max_issues_repo_path": "planet.cpp", "max_issues_repo_name": "Alexie81/Planet", "max_issues_repo_head_hexsha": "c1869fbab7a57ca635830ea478d85070763aba9a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "planet.cpp", "max_forks_repo_name": "Alexie81/Planet", "max_forks_repo_head_hexsha": "c1869fbab7a57ca635830ea478d85070763aba9a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-09-13T11:39:46.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-13T11:39:46.000Z", "avg_line_length": 32.7702407002, "max_line_length": 180, "alphanum_fraction": 0.6402911325, "num_tokens": 4250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.6548947155710234, "lm_q1q2_score": 0.4847362783005053}}
{"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/estimators/estimate_triangulation.h\"\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <limits>\n\n#include \"theia/solvers/estimator.h\"\n#include \"theia/solvers/ransac.h\"\n#include \"theia/solvers/sample_consensus_estimator.h\"\n#include \"theia/util/util.h\"\n#include \"theia/sfm/triangulation/triangulation.h\"\n#include \"theia/sfm/types.h\"\n\nnamespace theia {\n\nnamespace {\n// The pixel observation and projection matrix needed in order to triangulate a\n// 3D point.\nstruct PointObservation {\n  Matrix3x4d projection_matrix;\n  Eigen::Vector2d feature;\n};\n\n// Returns true if the point is in front of the camera and false if the point is\n// behind the camera.\nbool IsPointInFrontOfCamera(const Matrix3x4d& projection_matrix,\n                            const Eigen::Vector4d& point) {\n  return point.dot(projection_matrix.row(2)) > 0;\n}\n\nclass TriangulationEstimator\n    : public Estimator<PointObservation, Eigen::Vector4d> {\n public:\n  TriangulationEstimator() {}\n\n  double SampleSize() const { return 2; }\n\n  // Triangulates the 3D point from 2 observations.\n  bool EstimateModel(const std::vector<PointObservation>& observations,\n                     std::vector<Eigen::Vector4d>* triangulated_points) const {\n    // TODO(cmsweeney): We do not check the angle between the two views at the\n    // moment. This requires the ray direction of each feature meaning we would\n    // have to either decompose the projection matrix or pass in the ray\n    // direction as part of the Point Observation. RANSAC should be good enough\n    // at filtering out these bad solutions so we ignore this for now.\n    triangulated_points->resize(1);\n    if (!Triangulate(observations[0].projection_matrix,\n                     observations[1].projection_matrix,\n                     observations[0].feature,\n                     observations[1].feature,\n                     &triangulated_points->at(0))) {\n      return false;\n    }\n    // Only return true if the point is in front of both cameras and the\n    // triangulation was a success.\n    return IsPointInFrontOfCamera(observations[0].projection_matrix,\n                                  triangulated_points->at(0)) &&\n        IsPointInFrontOfCamera(observations[1].projection_matrix,\n                               triangulated_points->at(0));\n  }\n\n  double Error(const PointObservation& observation,\n               const Eigen::Vector4d& triangulated_point) const {\n    if (!IsPointInFrontOfCamera(observation.projection_matrix,\n                                triangulated_point)) {\n      return std::numeric_limits<double>::max();\n    }\n\n    const Eigen::Vector2d reprojection =\n        (observation.projection_matrix * triangulated_point).hnormalized();\n    return (observation.feature - reprojection).squaredNorm();\n  }\n\n private:\n  DISALLOW_COPY_AND_ASSIGN(TriangulationEstimator);\n};\n\n}  // namespace\n\nbool EstimateTriangulation(const RansacParameters& ransac_params,\n                           const std::vector<Matrix3x4d>& projection_matrices,\n                           const std::vector<Eigen::Vector2d>& features,\n                           Eigen::Vector4d* triangulated_point,\n                           RansacSummary* summary) {\n  if (projection_matrices.size() < 2) {\n    return false;\n  }\n\n  // Create point correspondences.\n  std::vector<PointObservation> point_observations(\n      projection_matrices.size());\n  for (int i = 0; i < point_observations.size(); i++) {\n    point_observations[i].projection_matrix = projection_matrices[i];\n    point_observations[i].feature = features[i];\n  }\n\n  // RANSAC triangulation.\n  TriangulationEstimator triangulation_estimator;\n  Ransac<TriangulationEstimator> ransac(ransac_params,\n                                        triangulation_estimator);\n  CHECK(ransac.Initialize());\n  if (!ransac.Estimate(point_observations, triangulated_point, summary)) {\n    return false;\n  }\n\n  return true;\n}\n\n}  // namespace theia\n", "meta": {"hexsha": "9ae6c00542da6e7c5fe58cdc3a63df183ef2145d", "size": 5731, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/sfm/estimators/estimate_triangulation.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/estimators/estimate_triangulation.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/estimators/estimate_triangulation.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-07-16T08:45:55.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-11T05:32:16.000Z", "avg_line_length": 39.7986111111, "max_line_length": 80, "alphanum_fraction": 0.7005758157, "num_tokens": 1245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.4847362757789671}}
{"text": "\n/*===================================================================\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<mitkConnectomicsShortestPathHistogram.h>\n\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n\n#include \"mitkConnectomicsConstantsManager.h\"\n\nmitk::ConnectomicsShortestPathHistogram::ConnectomicsShortestPathHistogram()\n: m_Mode( UnweightedUndirectedMode )\n, m_EverythingConnected( true )\n{\n  m_Subject = \"Shortest path\";\n}\n\nmitk::ConnectomicsShortestPathHistogram::~ConnectomicsShortestPathHistogram()\n{\n}\n\nvoid mitk::ConnectomicsShortestPathHistogram::SetShortestPathCalculationMode( const mitk::ConnectomicsShortestPathHistogram::ShortestPathCalculationMode & mode)\n{\n  m_Mode = mode;\n}\n\nmitk::ConnectomicsShortestPathHistogram::ShortestPathCalculationMode mitk::ConnectomicsShortestPathHistogram::GetShortestPathCalculationMode()\n{\n  return m_Mode;\n}\n\nvoid mitk::ConnectomicsShortestPathHistogram::ComputeFromConnectomicsNetwork( ConnectomicsNetwork* source )\n{\n\n  NetworkType* boostGraph = source->GetBoostGraph();\n\n  switch( m_Mode )\n  {\n  case UnweightedUndirectedMode:\n    {\n      CalculateUnweightedUndirectedShortestPaths( boostGraph );\n      break;\n    }\n  case WeightedUndirectedMode:\n    {\n      CalculateWeightedUndirectedShortestPaths( boostGraph );\n      break;\n    }\n  }\n\n    ConvertDistanceMapToHistogram();\n}\n\nvoid mitk::ConnectomicsShortestPathHistogram::CalculateUnweightedUndirectedShortestPaths( NetworkType* boostGraph )\n{\n  std::vector< DescriptorType > predecessorMap( boost::num_vertices( *boostGraph ) );\n  int numberOfNodes( boost::num_vertices( *boostGraph ) );\n\n  m_DistanceMatrix.resize( numberOfNodes );\n  for( int index(0); index < m_DistanceMatrix.size(); index++ )\n  {\n    m_DistanceMatrix[ index ].resize( numberOfNodes );\n  }\n\n  IteratorType iterator, end;\n  boost::tie(iterator, end) = boost::vertices( *boostGraph );\n\n  for ( int index(0) ; iterator != end; ++iterator, index++)\n  {\n          boost::dijkstra_shortest_paths(*boostGraph, *iterator, boost::predecessor_map(&predecessorMap[ 0 ]).distance_map(&m_DistanceMatrix[ index ][ 0 ]).weight_map( boost::get( &mitk::ConnectomicsNetwork::NetworkEdge::edge_weight ,*boostGraph ) ) ) ;\n  }\n}\n\nvoid mitk::ConnectomicsShortestPathHistogram::CalculateWeightedUndirectedShortestPaths( NetworkType* boostGraph )\n{\n  MBI_WARN << mitk::ConnectomicsConstantsManager::CONNECTOMICS_WARNING_UNIMPLEMENTED_FEATURE;\n}\n\nvoid mitk::ConnectomicsShortestPathHistogram::ConvertDistanceMapToHistogram()\n{\n  // get the longest path between any two nodes in the network\n  // we assume that no nodes are farther apart than there are nodes,\n  // this is to filter unconnected nodes\n  int longestPath( 0 );\n  int numberOfNodes( m_DistanceMatrix.size() );\n  m_EverythingConnected = true;\n\n  for( int index(0); index < m_DistanceMatrix.size(); index++ )\n  {\n    for( int innerIndex(0); innerIndex < m_DistanceMatrix[ index ].size(); innerIndex++ )\n    {\n      if( m_DistanceMatrix[ index ][ innerIndex ] > longestPath )\n      {\n        if( m_DistanceMatrix[ index ][ innerIndex ] < numberOfNodes )\n        {\n          longestPath = m_DistanceMatrix[ index ][ innerIndex ];\n        }\n        else\n        {\n          // these nodes are not connected\n          m_EverythingConnected = false;\n        }\n      }\n    }\n  }\n\n  m_HistogramVector.resize( longestPath + 1 );\n\n  for( int index(0); index < m_DistanceMatrix.size(); index++ )\n  {\n    for( int innerIndex(0); innerIndex < m_DistanceMatrix[ index ].size(); innerIndex++ )\n    {\n      if( m_DistanceMatrix[ index ][ innerIndex ] < numberOfNodes )\n      {\n        m_HistogramVector[ m_DistanceMatrix[ index ][ innerIndex ] ]++;\n      }\n    }\n  }\n\n  // correct for every path being counted twice\n\n  for( int index(1); index < m_HistogramVector.size(); index++ )\n  {\n    m_HistogramVector[ index ] = m_HistogramVector[ index ] / 2;\n  }\n\n    // correct for every node being distance zero to itself\n  if( m_HistogramVector[ 0 ] >= numberOfNodes )\n  {\n    m_HistogramVector[ 0 ] = m_HistogramVector[ 0 ] - numberOfNodes;\n  }\n  else\n  {\n    MBI_WARN << mitk::ConnectomicsConstantsManager::CONNECTOMICS_WARNING_ZERO_DISTANCE_NODES;\n  }\n\n  UpdateYMax();\n\n  this->m_Valid = true;\n}\n\ndouble mitk::ConnectomicsShortestPathHistogram::GetEfficiency()\n{\n  if( !this->m_Valid )\n  {\n    MBI_INFO << mitk::ConnectomicsConstantsManager::CONNECTOMICS_WARNING_CAN_NOT_COMPUTE_EFFICIENCY << mitk::ConnectomicsConstantsManager::CONNECTOMICS_WARNING_NETWORK_NOT_VALID;\n    return 0.0;\n  }\n\n  if( !m_EverythingConnected )\n  { // efficiency of disconnected graphs is 0\n        MBI_INFO << mitk::ConnectomicsConstantsManager::CONNECTOMICS_WARNING_NETWORK_DISCONNECTED;\n    return 0.0;\n  }\n\n  double efficiency( 0.0 );\n\n  double overallDistance( 0.0 );\n  double numberOfPairs( 0.0 );\n  // add up all distances\n  for( int index(0); index < m_HistogramVector.size(); index++ )\n  {\n    overallDistance = overallDistance + m_HistogramVector[ index ] * index;\n    numberOfPairs = numberOfPairs + m_HistogramVector[ index ];\n  }\n\n  // efficiency = 1 / averageDistance = 1 / ( overallDistance / numberofPairs )\n  efficiency = numberOfPairs / overallDistance;\n\n  return efficiency;\n}\n", "meta": {"hexsha": "0e4e3d0d140f810d9a235afb8ef15b7a3e1ea2c5", "size": 5573, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Modules/DiffusionImaging/Connectomics/Algorithms/mitkConnectomicsShortestPathHistogram.cpp", "max_stars_repo_name": "rfloca/MITK", "max_stars_repo_head_hexsha": "b7dcb830dc36a5d3011b9828c3d71e496d3936ad", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/Connectomics/Algorithms/mitkConnectomicsShortestPathHistogram.cpp", "max_issues_repo_name": "rfloca/MITK", "max_issues_repo_head_hexsha": "b7dcb830dc36a5d3011b9828c3d71e496d3936ad", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/Connectomics/Algorithms/mitkConnectomicsShortestPathHistogram.cpp", "max_forks_repo_name": "rfloca/MITK", "max_forks_repo_head_hexsha": "b7dcb830dc36a5d3011b9828c3d71e496d3936ad", "max_forks_repo_licenses": ["BSD-3-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.1243243243, "max_line_length": 253, "alphanum_fraction": 0.7084155751, "num_tokens": 1374, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.78793120560257, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.48464691554827366}}
{"text": "/*\n * Copyright 2017-2020 CNRS-UM LIRMM, CNRS-AIST JRL\n */\n\n#define BOOST_TEST_MODULE TestSpatialFilters\n#include <boost/test/unit_test.hpp>\n#include <gram_savitzky_golay/spatial_filters.h>\n\n#ifndef M_PI\n#  include <boost/math/constants/constants.hpp>\n#  define M_PI boost::math::constants::pi<double>()\n#endif\n\nusing namespace gram_sg;\n\nBOOST_AUTO_TEST_CASE(test_transform_filter)\n{\n  /** Filtering **/\n  {\n    gram_sg::SavitzkyGolayFilterConfig sg_conf(50, 50, 2, 0);\n    TransformFilter filter(sg_conf);\n\n    Eigen::Matrix3d rot_sg;\n    rot_sg = Eigen::AngleAxisd(1.2, Eigen::Vector3d::UnitX()) * Eigen::AngleAxisd(1.9, Eigen::Vector3d::UnitY())\n             * Eigen::AngleAxisd(2.3, Eigen::Vector3d::UnitZ());\n    Eigen::Affine3d X_init = Eigen::Affine3d::Identity();\n    X_init.matrix().block<3, 3>(0, 0) = rot_sg;\n    X_init.matrix().block<3, 1>(0, 3) = Eigen::Vector3d{0.1, 5, 0.3};\n    filter.reset(X_init);\n    const auto & res_init = filter.filter();\n    BOOST_CHECK_MESSAGE(X_init.matrix().isApprox(res_init.matrix()), \"\\n\" << X_init.matrix() << \"\\n-----\\n\"\n                                                                          << res_init.matrix());\n  }\n\n  {\n    gram_sg::SavitzkyGolayFilterConfig sg_conf(50, 50, 2, 0);\n    TransformFilter filter(sg_conf);\n    Eigen::Matrix3d rot_sg;\n    rot_sg = Eigen::AngleAxisd(M_PI, Eigen::Vector3d::UnitX()) * Eigen::AngleAxisd(-M_PI / 2, Eigen::Vector3d::UnitY())\n             * Eigen::AngleAxisd(M_PI, Eigen::Vector3d::UnitZ());\n    Eigen::Affine3d X_init = Eigen::Affine3d::Identity();\n    X_init.matrix().block<3, 3>(0, 0) = rot_sg;\n    X_init.matrix().block<3, 1>(0, 3) = Eigen::Vector3d{0.1, 5, 0.3};\n    filter.reset(X_init);\n\n    const auto & res_init = filter.filter();\n    BOOST_CHECK_MESSAGE(X_init.matrix().isApprox(res_init.matrix()), \"\\n\" << X_init.matrix() << \"\\n-----\\n\"\n                                                                          << res_init.matrix());\n  }\n}\n\nBOOST_AUTO_TEST_CASE(test_rotation_filter)\n{\n  Eigen::Matrix3d rot;\n  rot = Eigen::AngleAxisd(1.2, Eigen::Vector3d::UnitX()) * Eigen::AngleAxisd(M_PI / 2, Eigen::Vector3d::UnitY())\n        * Eigen::AngleAxisd(0.3, Eigen::Vector3d::UnitZ());\n\n  gram_sg::SavitzkyGolayFilterConfig sg_conf(50, 50, 2, 0);\n  RotationFilter filter(sg_conf);\n\n  filter.reset(rot);\n\n  const Eigen::Matrix3d res = filter.filter();\n  BOOST_CHECK(rot.isApprox(res));\n}\n", "meta": {"hexsha": "bce8a01a17c6d95b8440d37590a5222619e60f8a", "size": 2390, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_spatial_filters.cpp", "max_stars_repo_name": "hedgepigdaniel/gram_savitzky_golay", "max_stars_repo_head_hexsha": "ad18bf4ee1648dc80144681565a324f9f4ad7914", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 51.0, "max_stars_repo_stars_event_min_datetime": "2018-02-16T16:12:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T03:09:04.000Z", "max_issues_repo_path": "tests/test_spatial_filters.cpp", "max_issues_repo_name": "hedgepigdaniel/gram_savitzky_golay", "max_issues_repo_head_hexsha": "ad18bf4ee1648dc80144681565a324f9f4ad7914", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2018-03-22T13:08:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-07T15:23:42.000Z", "max_forks_repo_path": "tests/test_spatial_filters.cpp", "max_forks_repo_name": "hedgepigdaniel/gram_savitzky_golay", "max_forks_repo_head_hexsha": "ad18bf4ee1648dc80144681565a324f9f4ad7914", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2018-07-18T08:51:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-12T02:57:25.000Z", "avg_line_length": 36.2121212121, "max_line_length": 119, "alphanum_fraction": 0.6280334728, "num_tokens": 723, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.78793120560257, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.48464691554827366}}
{"text": "#define CATCH_CONFIG_MAIN\n#include <Eigen/Dense>\n#include <catch.hpp>\n#include <memory>\n#include <random>\n\n#include \"EDP/ConstructSparseMat.hpp\"\n#include \"EDP/LocalHamiltonian.hpp\"\n\n#include \"yavque/Operators/DiagonalHamEvol.hpp\"\n#include \"yavque/utils.hpp\"\n\n#include \"common.hpp\"\n\nTEST_CASE(\"test random diagonal\", \"[random-diagonal]\")\n{\n\tconstexpr uint32_t N = 8;\n\tconstexpr yavque::cx_double I(0., 1.);\n\tstd::random_device rd;\n\tstd::default_random_engine re{rd()};\n\n\tstd::normal_distribution<> nd;\n\n\tEigen::VectorXd ham = Eigen::VectorXd::Random(1 << N);\n\tyavque::DiagonalOperator diag_op(ham);\n\tyavque::DiagonalHamEvol diag_ham_evol(diag_op);\n\n\tfor(uint32_t k = 0; k < 100; ++k) // instance\n\t{\n\t\tEigen::VectorXcd vec = Eigen::VectorXcd::Random(1 << N);\n\t\tvec.normalize();\n\n\t\tdouble t = nd(re);\n\t\tdiag_ham_evol.set_variable_value(t);\n\n\t\tEigen::VectorXcd out1 = diag_ham_evol.apply_right(vec);\n\t\tEigen::VectorXcd out2 = exp(-I * ham.array() * t) * vec.array();\n\n\t\tREQUIRE((out1 - out2).norm() < 1e-6);\n\n\t\tEigen::VectorXcd grad1 = diag_ham_evol.log_deriv()->apply_right(out1);\n\t\tEigen::VectorXcd grad2 = -I * ham.cwiseProduct(out1);\n\t\tREQUIRE((grad1 - grad2).norm() < 1e-6);\n\t}\n\n\tdiag_ham_evol.dagger_in_place();\n\tfor(uint32_t k = 0; k < 100; ++k) // instance\n\t{\n\t\tEigen::VectorXcd vec = Eigen::VectorXcd::Random(1 << N);\n\t\tvec.normalize();\n\n\t\tdouble t = nd(re);\n\t\tdiag_ham_evol.set_variable_value(t);\n\n\t\tEigen::VectorXcd out1 = diag_ham_evol.apply_right(vec);\n\t\tEigen::VectorXcd out2 = exp(I * ham.array() * t) * vec.array();\n\n\t\tREQUIRE((out1 - out2).norm() < 1e-6);\n\t\tEigen::VectorXcd grad1 = diag_ham_evol.log_deriv()->apply_right(out1);\n\t\tEigen::VectorXcd grad2 = I * ham.cwiseProduct(out1);\n\t\tREQUIRE((grad1 - grad2).norm() < 1e-6);\n\t}\n}\n\nTEST_CASE(\"test basic operations\", \"[basic-operation]\")\n{\n\tconstexpr uint32_t N = 8;\n\tstd::random_device rd;\n\tstd::default_random_engine re{rd()};\n\n\tstd::normal_distribution<> nd;\n\n\tEigen::VectorXd ham = Eigen::VectorXd::Random(1 << N);\n\tyavque::DiagonalOperator diag_op(ham);\n\tyavque::DiagonalHamEvol diag_ham_evol(diag_op);\n\n\tdiag_ham_evol.set_variable_value(1.0);\n\n\tauto clonned = diag_ham_evol.clone();\n\n\tstd::cout << clonned->desc() << std::endl;\n\tauto* p = dynamic_cast<yavque::Univariate*>(clonned.get());\n\tp->set_variable_value(-1.0);\n\n\tREQUIRE(diag_ham_evol.get_variable_value() == 1.0);\n}\n", "meta": {"hexsha": "ed089aabfb5c62c491f1b91b34bd257095890803", "size": 2344, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tests/TestDiagonalHamEvol.cpp", "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": "Tests/TestDiagonalHamEvol.cpp", "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": "Tests/TestDiagonalHamEvol.cpp", "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": 26.9425287356, "max_line_length": 72, "alphanum_fraction": 0.6975255973, "num_tokens": 749, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.78793120560257, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.48464691554827366}}
{"text": "///////////////////////////////////////////////////////////////\n//  Copyright 2019 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#include \"../performance_test.hpp\"\n#if defined(TEST_CPP_INT)\n#include <boost/multiprecision/cpp_int.hpp>\n#endif\n\nvoid test11()\n{\n#ifdef TEST_CPP_INT\n   test<boost::multiprecision::number<boost::multiprecision::cpp_int_backend<512, 512, boost::multiprecision::signed_magnitude, boost::multiprecision::unchecked, void>, boost::multiprecision::et_off> >(\"cpp_int(fixed)\", 512);\n#endif\n}\n", "meta": {"hexsha": "205ce51797e8ff76631c121a5a16aa817d900cea", "size": 637, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/boost_1.78.0/libs/multiprecision/performance/performance_test_files/test11.cpp", "max_stars_repo_name": "LaudateCorpus1/math", "max_stars_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 106.0, "max_stars_repo_stars_event_min_datetime": "2015-08-07T04:23:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-27T18:25:15.000Z", "max_issues_repo_path": "3rdparty/boost_1_73_0/libs/multiprecision/performance/performance_test_files/test11.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 130.0, "max_issues_repo_issues_event_min_datetime": "2016-06-22T22:11:25.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-29T20:24:09.000Z", "max_forks_repo_path": "3rdparty/boost_1_73_0/libs/multiprecision/performance/performance_test_files/test11.cpp", "max_forks_repo_name": "qingkouwei/mediaones", "max_forks_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2015-07-08T19:18:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-14T16:39:56.000Z", "avg_line_length": 37.4705882353, "max_line_length": 225, "alphanum_fraction": 0.6891679749, "num_tokens": 151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.78793120560257, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.48464691554827366}}
{"text": "/**\n * @file random.cpp\n *\n * Declarations of global Boost random number generators.\n *\n * This file is part of mlpack 1.0.12.\n *\n * mlpack is free software; you may redstribute 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#include <boost/random.hpp>\n#include <boost/version.hpp>\n\nnamespace mips {\nnamespace math {\n\n#if BOOST_VERSION >= 104700\n  // Global random object.\n  boost::random::mt19937 randGen;\n  // Global uniform distribution.\n  boost::random::uniform_01<> randUniformDist;\n  // Global normal distribution.\n  boost::random::normal_distribution<> randNormalDist;\n#else\n  // Global random object.\n  boost::mt19937 randGen;\n\n  #if BOOST_VERSION >= 103900\n    // Global uniform distribution.\n    boost::uniform_01<> randUniformDist;\n  #else\n    // Pre-1.39 Boost.Random did not give default template parameter values.\n    boost::uniform_01<boost::mt19937, double> randUniformDist(randGen);\n  #endif\n\n  // Global normal distribution.\n  boost::normal_distribution<> randNormalDist;\n#endif\n\n}; // namespace math\n}; // namespace mlpack\n", "meta": {"hexsha": "6787bdfaeb1ad19953038bdd5418029cde9b3a97", "size": 1236, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mips/my_mlpack/core/math/random.cpp", "max_stars_repo_name": "uma-pi1/LEMP", "max_stars_repo_head_hexsha": "e24ce821692aba8403ca8733382f53641f7f96d5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2018-07-28T07:05:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-16T17:34:42.000Z", "max_issues_repo_path": "mips/my_mlpack/core/math/random.cpp", "max_issues_repo_name": "d3v3l0/LEMP-benchmarking", "max_issues_repo_head_hexsha": "0279528b427aa4fae59e4d3598b1f098fcb4cf4b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-16T03:30:55.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-16T03:30:55.000Z", "max_forks_repo_path": "mips/my_mlpack/core/math/random.cpp", "max_forks_repo_name": "d3v3l0/LEMP-benchmarking", "max_forks_repo_head_hexsha": "0279528b427aa4fae59e4d3598b1f098fcb4cf4b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-09-16T08:21:24.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-04T06:37:41.000Z", "avg_line_length": 28.0909090909, "max_line_length": 77, "alphanum_fraction": 0.7241100324, "num_tokens": 310, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4846469094221983}}
{"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#include <boost/intrusive_ptr.hpp>\n\n#include \"formula.hpp\"\n#include \"formula_callable.hpp\"\n#include \"unit_test.hpp\"\n\nnamespace {\nusing namespace game_logic;\nclass mock_char : public formula_callable {\n\tvariant get_value(const std::string& key) const {\n\t\tif(key == \"strength\") {\n\t\t\treturn variant(15);\n\t\t} else if(key == \"agility\") {\n\t\t\treturn variant(12);\n\t\t}\n\n\t\treturn variant(10);\n\t}\n};\nclass mock_party : public formula_callable {\n\tvariant get_value(const std::string& key) const {\n\t\tc_.add_ref();\n\t\ti_[0].add_ref();\n\t\ti_[1].add_ref();\n\t\ti_[2].add_ref();\n\t\tif(key == \"members\") {\n\t\t\ti_[0].add(\"strength\",variant(12));\n\t\t\ti_[1].add(\"strength\",variant(16));\n\t\t\ti_[2].add(\"strength\",variant(14));\n\t\t\tstd::vector<variant> members;\n\t\t\tfor(int n = 0; n != 3; ++n) {\n\t\t\t\tmembers.push_back(variant(&i_[n]));\n\t\t\t}\n\n\t\t\treturn variant(&members);\n\t\t} else if(key == \"char\") {\n\t\t\treturn variant(&c_);\n\t\t} else {\n\t\t\treturn variant(0);\n\t\t}\n\t}\n\n\tmock_char c_;\n\tmutable map_formula_callable i_[3];\n\n};\n\n}\n\nUNIT_TEST(formula)\n{\n\tboost::intrusive_ptr<mock_char> cp(new mock_char);\n\tboost::intrusive_ptr<mock_party> pp(new mock_party);\n#define FML(a) formula(variant(a))\n\tmock_char& c = *cp;\n\tmock_party& p = *pp;\n\tCHECK_EQ(FML(\"strength\").execute(c).as_int(), 15);\n\tCHECK_EQ(FML(\"17\").execute(c).as_int(), 17);\n\tCHECK_EQ(FML(\"strength/2 + agility\").execute(c).as_int(), 19);\n\tCHECK_EQ(FML(\"(strength+agility)/2\").execute(c).as_int(), 13);\n\tCHECK_EQ(FML(\"strength > 12\").execute(c).as_int(), 1);\n\tCHECK_EQ(FML(\"strength > 18\").execute(c).as_int(), 0);\n\tCHECK_EQ(FML(\"if(strength > 12, 7, 2)\").execute(c).as_int(), 7);\n\tCHECK_EQ(FML(\"if(strength > 18, 7, 2)\").execute(c).as_int(), 2);\n\tCHECK_EQ(FML(\"2 and 1\").execute(c).as_int(), 1);\n\tCHECK_EQ(FML(\"2 and 0\").execute(c).as_int(), 0);\n\tCHECK_EQ(FML(\"2 or 0\").execute(c).as_int(), 2);\n\tCHECK_EQ(FML(\"-5\").execute(c).as_int(),-5);\n\tCHECK_EQ(FML(\"not 5\").execute(c).as_int(), 0);\n\tCHECK_EQ(FML(\"not 0\").execute(c).as_int(), 1);\n\tCHECK_EQ(FML(\"abs(5)\").execute(c).as_int(), 5);\n\tCHECK_EQ(FML(\"abs(-5)\").execute(c).as_int(), 5);\n\tCHECK_EQ(FML(\"sign(5)\").execute(c).as_int(), 1);\n\tCHECK_EQ(FML(\"sign(0)\").execute(c).as_int(), 0);\n\tCHECK_EQ(FML(\"sign(-5)\").execute(c).as_int(), -1);\n\tCHECK_EQ(FML(\"min(3,5)\").execute(c).as_int(), 3);\n\tCHECK_EQ(FML(\"min(5,2)\").execute(c).as_int(), 2);\n\tCHECK_EQ(FML(\"max(3,5)\").execute(c).as_int(), 5);\n\tCHECK_EQ(FML(\"max(5,2)\").execute(c).as_int(), 5);\n\tCHECK_EQ(FML(\"char.strength\").execute(p).as_int(), 15);\n\tCHECK_EQ(FML(\"choose(members,value.strength).strength\").execute(p).as_int(), 16);\n\tCHECK_EQ(FML(\"4^2\").execute().as_int(), 16);\n\tCHECK_EQ(FML(\"2+3^3\").execute().as_int(), 29);\n\tCHECK_EQ(FML(\"2*3^3+2\").execute().as_int(), 56);\n\tCHECK_EQ(FML(\"9^3\").execute().as_int(), 729);\n\tCHECK_EQ(FML(\"x*5 where x=1\").execute().as_int(), 5);\n\tCHECK_EQ(FML(\"x*(a*b where a=2,b=1) where x=5\").execute().as_int(), 10);\n\tCHECK_EQ(FML(\"char.strength * ability where ability=3\").execute(p).as_int(), 45);\n\tCHECK_EQ(FML(\"'abcd' = 'abcd'\").execute(p).as_bool(), true);\n\tCHECK_EQ(FML(\"'abcd' = 'acd'\").execute(p).as_bool(), false);\n\tCHECK_EQ(FML(\"~strength, agility: ${strength}, ${agility}~\").execute(c).as_string(),\n\t               \"strength, agility: 15, 12\");\n\tfor(int n = 0; n != 128; ++n) {\n\t\tconst int dice_roll = FML(\"3d6\").execute().as_int();\n\t\tCHECK_GE(dice_roll, 3);\n   \t\tCHECK_LE(dice_roll, 18);\n\t}\n\n\tvariant myarray = FML(\"[1,2,3]\").execute();\n\tCHECK_EQ(myarray.num_elements(), 3);\n\tCHECK_EQ(myarray[0].as_int(), 1);\n\tCHECK_EQ(myarray[1].as_int(), 2);\n\tCHECK_EQ(myarray[2].as_int(), 3);\n\n}\n\nBENCHMARK(construct_int_variant)\n{\n\tBENCHMARK_LOOP {\n\t\tvariant v(0);\n\t}\n}\n\nBENCHMARK_ARG(formula, const std::string& fm)\n{\n\tstatic mock_party p;\n\tformula f = formula(variant(fm));\n\tBENCHMARK_LOOP {\n\t\tf.execute(p);\n\t}\n}\n\nBENCHMARK_ARG_CALL(formula, integer, \"0\");\nBENCHMARK_ARG_CALL(formula, where, \"x where x = 5\");\nBENCHMARK_ARG_CALL(formula, add, \"5 + 4\");\nBENCHMARK_ARG_CALL(formula, arithmetic, \"(5 + 4)*17 + 12*9 - 5/2\");\nBENCHMARK_ARG_CALL(formula, read_input, \"char\");\nBENCHMARK_ARG_CALL(formula, read_input_sub, \"char.strength\");\nBENCHMARK_ARG_CALL(formula, array, \"[4, 5, 8, 12, 17, 0, 19]\");\nBENCHMARK_ARG_CALL(formula, array_str, \"['stand', 'walk', 'run', 'jump']\");\nBENCHMARK_ARG_CALL(formula, string, \"'blah'\");\nBENCHMARK_ARG_CALL(formula, null_function, \"null()\");\nBENCHMARK_ARG_CALL(formula, if_function, \"if(4 > 5, 7, 8)\");\n", "meta": {"hexsha": "f5acb1510a34129c12abddb78afa20d5b9b64217", "size": 5111, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/formula_test.cpp", "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/formula_test.cpp", "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/formula_test.cpp", "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": 34.0733333333, "max_line_length": 85, "alphanum_fraction": 0.6624926629, "num_tokens": 1607, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4846469094221983}}
{"text": "///////////////////////////////////////////////////////////////\n//  Copyright 2012-2021 John Maddock.\n//  Copyright 2021 Matt Borland. 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#include <boost/multiprecision/gmp.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/math/special_functions/prime.hpp>\n#include <boost/random.hpp>\n#include <random>\n#include <iostream>\n#include <iomanip>\n#include \"test.hpp\"\n\n#define BOOST_MP_STANDALONE\n#include <boost/multiprecision/miller_rabin.hpp>\n\ntemplate <class I>\nvoid test()\n{\n   //\n   // Very simple test program to verify that the GMP's Miller-Rabin\n   // implementation and this one agree on whether some random numbers\n   // are prime or not.  Of course these are probabilistic tests so there's\n   // no reason why they should actually agree - except the probability of\n   // disagreement for 25 trials is almost infinitely small.\n   //\n   using namespace boost::random;\n   using namespace boost::multiprecision;\n\n   typedef I test_type;\n\n   static const unsigned test_bits =\n      std::numeric_limits<test_type>::digits && (std::numeric_limits<test_type>::digits <= 256)\n         ? std::numeric_limits<test_type>::digits\n         : 128;\n\n   independent_bits_engine<mt11213b, test_bits, test_type> gen;\n   //\n   // We must use a different generator for the tests and number generation, otherwise\n   // we get false positives.  Further we use the same random number engine for the\n   // Miller Rabin test as GMP uses internally:\n   //\n   mt19937 gen2;\n\n   //\n   // Begin by testing the primes in our table as all these should return true:\n   //\n   for (unsigned i = 1; i < boost::math::max_prime; ++i)\n   {\n      BOOST_TEST(miller_rabin_test(test_type(boost::math::prime(i)), 25, gen));\n      BOOST_TEST(mpz_probab_prime_p(mpz_int(boost::math::prime(i)).backend().data(), 25));\n   }\n   //\n   // Now test some random values and compare GMP's native routine with ours.\n   //\n   for (unsigned i = 0; i < 10000; ++i)\n   {\n      test_type n              = gen();\n      bool      is_prime_boost = miller_rabin_test(n, 25, gen2);\n      bool      is_gmp_prime   = mpz_probab_prime_p(mpz_int(n).backend().data(), 25) ? true : false;\n      if (is_prime_boost && is_gmp_prime)\n      {\n         std::cout << \"We have a prime: \" << std::hex << std::showbase << n << std::endl;\n      }\n      if (is_prime_boost != is_gmp_prime)\n         std::cout << std::hex << std::showbase << \"n = \" << n << std::endl;\n      BOOST_CHECK_EQUAL(is_prime_boost, is_gmp_prime);\n   }\n}\n\nint main()\n{\n   using namespace boost::multiprecision;\n\n   test<mpz_int>();\n   test<number<gmp_int, et_off> >();\n   test<std::uint64_t>();\n   test<std::uint32_t>();\n\n   test<cpp_int>();\n   test<number<cpp_int_backend<64, 64, unsigned_magnitude, checked, void>, et_off> >();\n   test<checked_uint128_t>();\n   test<checked_uint1024_t>();\n\n   return boost::report_errors();\n}\n", "meta": {"hexsha": "88396cac572672c22f9898bfe8f78fce9c310cd8", "size": 2994, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/standalone_test_miller_rabin.cpp", "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": "test/standalone_test_miller_rabin.cpp", "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": "test/standalone_test_miller_rabin.cpp", "max_forks_repo_name": "mariospr/multiprecision", "max_forks_repo_head_hexsha": "4720edda9e3058ba68be8ae6c29342536b9ce142", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.6404494382, "max_line_length": 100, "alphanum_fraction": 0.6576486306, "num_tokens": 773, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311856832191, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4846469032961228}}
{"text": "#pragma once\n\n#include <Eigen/Core>\n\n#include <ipc/broad_phase/collision_candidate.hpp>\n#include <ipc/utils/eigen_ext.hpp>\n\nnamespace ipc {\n\nstruct CollisionConstraint {\npublic:\n    virtual ~CollisionConstraint() {}\n\n    virtual std::vector<long> vertex_indices(\n        const Eigen::MatrixXi& E, const Eigen::MatrixXi& F) const = 0;\n\n    virtual double compute_distance(\n        const Eigen::MatrixXd& V,\n        const Eigen::MatrixXi& E,\n        const Eigen::MatrixXi& F) const = 0;\n\n    virtual VectorMax12d compute_distance_gradient(\n        const Eigen::MatrixXd& V,\n        const Eigen::MatrixXi& E,\n        const Eigen::MatrixXi& F) const = 0;\n\n    virtual MatrixMax12d compute_distance_hessian(\n        const Eigen::MatrixXd& V,\n        const Eigen::MatrixXi& E,\n        const Eigen::MatrixXi& F) const = 0;\n\n    virtual double compute_potential(\n        const Eigen::MatrixXd& V,\n        const Eigen::MatrixXi& E,\n        const Eigen::MatrixXi& F,\n        const double dhat) const;\n\n    virtual VectorMax12d compute_potential_gradient(\n        const Eigen::MatrixXd& V,\n        const Eigen::MatrixXi& E,\n        const Eigen::MatrixXi& F,\n        const double dhat) const;\n\n    virtual MatrixMax12d compute_potential_hessian(\n        const Eigen::MatrixXd& V,\n        const Eigen::MatrixXi& E,\n        const Eigen::MatrixXi& F,\n        const double dhat,\n        const bool project_hessian_to_psd) const;\n\n    double minimum_distance = 0;\n};\n\n///////////////////////////////////////////////////////////////////////////////\n\nstruct VertexVertexConstraint : VertexVertexCandidate, CollisionConstraint {\n    VertexVertexConstraint(long vertex0_index, long vertex1_index);\n    VertexVertexConstraint(const VertexVertexCandidate& candidate);\n\n    std::vector<long> vertex_indices(\n        const Eigen::MatrixXi& E, const Eigen::MatrixXi& F) const override\n    {\n        return { { vertex0_index, vertex1_index } };\n    }\n\n    double compute_distance(\n        const Eigen::MatrixXd& V,\n        const Eigen::MatrixXi& E,\n        const Eigen::MatrixXi& F) const override;\n\n    VectorMax12d compute_distance_gradient(\n        const Eigen::MatrixXd& V,\n        const Eigen::MatrixXi& E,\n        const Eigen::MatrixXi& F) const override;\n\n    MatrixMax12d compute_distance_hessian(\n        const Eigen::MatrixXd& V,\n        const Eigen::MatrixXi& E,\n        const Eigen::MatrixXi& F) const override;\n\n    double compute_potential(\n        const Eigen::MatrixXd& V,\n        const Eigen::MatrixXi& E,\n        const Eigen::MatrixXi& F,\n        const double dhat) const override;\n\n    VectorMax12d compute_potential_gradient(\n        const Eigen::MatrixXd& V,\n        const Eigen::MatrixXi& E,\n        const Eigen::MatrixXi& F,\n        const double dhat) const override;\n\n    MatrixMax12d compute_potential_hessian(\n        const Eigen::MatrixXd& V,\n        const Eigen::MatrixXi& E,\n        const Eigen::MatrixXi& F,\n        const double dhat,\n        const bool project_hessian_to_psd) const override;\n\n    unsigned int multiplicity = 1;\n};\n\n///////////////////////////////////////////////////////////////////////////////\n\nstruct EdgeVertexConstraint : EdgeVertexCandidate, CollisionConstraint {\n    EdgeVertexConstraint(long edge_index, long vertex_index);\n    EdgeVertexConstraint(const EdgeVertexCandidate& candidate);\n\n    std::vector<long> vertex_indices(\n        const Eigen::MatrixXi& E, const Eigen::MatrixXi& F) const override\n    {\n        return { { vertex_index, E(edge_index, 0), E(edge_index, 1) } };\n    }\n\n    double compute_distance(\n        const Eigen::MatrixXd& V,\n        const Eigen::MatrixXi& E,\n        const Eigen::MatrixXi& F) const override;\n\n    VectorMax12d compute_distance_gradient(\n        const Eigen::MatrixXd& V,\n        const Eigen::MatrixXi& E,\n        const Eigen::MatrixXi& F) const override;\n\n    MatrixMax12d compute_distance_hessian(\n        const Eigen::MatrixXd& V,\n        const Eigen::MatrixXi& E,\n        const Eigen::MatrixXi& F) const override;\n\n    double compute_potential(\n        const Eigen::MatrixXd& V,\n        const Eigen::MatrixXi& E,\n        const Eigen::MatrixXi& F,\n        const double dhat) const override;\n\n    VectorMax12d compute_potential_gradient(\n        const Eigen::MatrixXd& V,\n        const Eigen::MatrixXi& E,\n        const Eigen::MatrixXi& F,\n        const double dhat) const override;\n\n    MatrixMax12d compute_potential_hessian(\n        const Eigen::MatrixXd& V,\n        const Eigen::MatrixXi& E,\n        const Eigen::MatrixXi& F,\n        const double dhat,\n        const bool project_hessian_to_psd) const override;\n\n    unsigned int multiplicity = 1;\n};\n\n///////////////////////////////////////////////////////////////////////////////\n\nstruct EdgeEdgeConstraint : EdgeEdgeCandidate, CollisionConstraint {\n    EdgeEdgeConstraint(long edge0_index, long edge1_index, double eps_x);\n    EdgeEdgeConstraint(const EdgeEdgeCandidate& candidate, double eps_x);\n\n    std::vector<long> vertex_indices(\n        const Eigen::MatrixXi& E, const Eigen::MatrixXi& F) const override\n    {\n        return { { E(edge0_index, 0), E(edge0_index, 1), //\n                   E(edge1_index, 0), E(edge1_index, 1) } };\n    }\n\n    double compute_distance(\n        const Eigen::MatrixXd& V,\n        const Eigen::MatrixXi& E,\n        const Eigen::MatrixXi& F) const override;\n\n    VectorMax12d compute_distance_gradient(\n        const Eigen::MatrixXd& V,\n        const Eigen::MatrixXi& E,\n        const Eigen::MatrixXi& F) const override;\n\n    MatrixMax12d compute_distance_hessian(\n        const Eigen::MatrixXd& V,\n        const Eigen::MatrixXi& E,\n        const Eigen::MatrixXi& F) const override;\n\n    double compute_potential(\n        const Eigen::MatrixXd& V,\n        const Eigen::MatrixXi& E,\n        const Eigen::MatrixXi& F,\n        const double dhat) const override;\n\n    VectorMax12d compute_potential_gradient(\n        const Eigen::MatrixXd& V,\n        const Eigen::MatrixXi& E,\n        const Eigen::MatrixXi& F,\n        const double dhat) const override;\n\n    MatrixMax12d compute_potential_hessian(\n        const Eigen::MatrixXd& V,\n        const Eigen::MatrixXi& E,\n        const Eigen::MatrixXi& F,\n        const double dhat,\n        const bool project_hessian_to_psd) const override;\n\n    double eps_x;\n};\n\n///////////////////////////////////////////////////////////////////////////////\n\nstruct FaceVertexConstraint : FaceVertexCandidate, CollisionConstraint {\n    FaceVertexConstraint(long face_index, long vertex_index);\n    FaceVertexConstraint(const FaceVertexCandidate& candidate);\n\n    std::vector<long> vertex_indices(\n        const Eigen::MatrixXi& E, const Eigen::MatrixXi& F) const override\n    {\n        return { { vertex_index, //\n                   F(face_index, 0), F(face_index, 1), F(face_index, 2) } };\n    }\n\n    double compute_distance(\n        const Eigen::MatrixXd& V,\n        const Eigen::MatrixXi& E,\n        const Eigen::MatrixXi& F) const override;\n\n    VectorMax12d compute_distance_gradient(\n        const Eigen::MatrixXd& V,\n        const Eigen::MatrixXi& E,\n        const Eigen::MatrixXi& F) const override;\n\n    MatrixMax12d compute_distance_hessian(\n        const Eigen::MatrixXd& V,\n        const Eigen::MatrixXi& E,\n        const Eigen::MatrixXi& F) const override;\n};\n\n///////////////////////////////////////////////////////////////////////////////\n\nstruct PlaneVertexConstraint : CollisionConstraint {\n    PlaneVertexConstraint(\n        const VectorMax3d& plane_origin,\n        const VectorMax3d& plane_normal,\n        const long vertex_index);\n\n    std::vector<long> vertex_indices(\n        const Eigen::MatrixXi& E, const Eigen::MatrixXi& F) const override\n    {\n        return { vertex_index };\n    }\n\n    double compute_distance(\n        const Eigen::MatrixXd& V,\n        const Eigen::MatrixXi& E,\n        const Eigen::MatrixXi& F) const override;\n\n    VectorMax12d compute_distance_gradient(\n        const Eigen::MatrixXd& V,\n        const Eigen::MatrixXi& E,\n        const Eigen::MatrixXi& F) const override;\n\n    MatrixMax12d compute_distance_hessian(\n        const Eigen::MatrixXd& V,\n        const Eigen::MatrixXi& E,\n        const Eigen::MatrixXi& F) const override;\n\n    VectorMax3d plane_origin;\n    VectorMax3d plane_normal;\n    long vertex_index;\n};\n\n///////////////////////////////////////////////////////////////////////////////\n\nstruct Constraints {\n    std::vector<VertexVertexConstraint> vv_constraints;\n    std::vector<EdgeVertexConstraint> ev_constraints;\n    std::vector<EdgeEdgeConstraint> ee_constraints;\n    std::vector<FaceVertexConstraint> fv_constraints;\n    std::vector<PlaneVertexConstraint> pv_constraints;\n\n    size_t size() const;\n\n    size_t num_constraints() const;\n\n    bool empty() const;\n\n    void clear();\n\n    CollisionConstraint& operator[](size_t idx);\n    const CollisionConstraint& operator[](size_t idx) const;\n};\n\n} // namespace ipc\n", "meta": {"hexsha": "0bb6795fc453d0a9131fc3ab71c3c8b451fddbfc", "size": 8877, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/collision_constraint.hpp", "max_stars_repo_name": "ipc-sim/ipc-toolk", "max_stars_repo_head_hexsha": "81873d0288810e30166d871419da4104329860e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 61.0, "max_stars_repo_stars_event_min_datetime": "2020-08-04T21:08:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T02:24:31.000Z", "max_issues_repo_path": "src/collision_constraint.hpp", "max_issues_repo_name": "dbelgrod/ipc-toolkit", "max_issues_repo_head_hexsha": "0b7ca9b5f867db63bd68dd02ce54a9d00b0fc337", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-10-12T05:54:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-10T18:39:30.000Z", "max_forks_repo_path": "src/collision_constraint.hpp", "max_forks_repo_name": "dbelgrod/ipc-toolkit", "max_forks_repo_head_hexsha": "0b7ca9b5f867db63bd68dd02ce54a9d00b0fc337", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2020-11-26T12:47:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T04:55:49.000Z", "avg_line_length": 30.9303135889, "max_line_length": 79, "alphanum_fraction": 0.6278021854, "num_tokens": 1973, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311856832191, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4846469032961228}}
{"text": "///////////////////////////////////////////////////////////////\n//  Copyright 2020 John Maddock. Distributed under the Boost\n//  Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt\n\n#ifdef _MSC_VER\n#define _SCL_SECURE_NO_WARNINGS\n#endif\n\n#define BOOST_MP_GCD_DEBUG\n\n#include \"test.hpp\"\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/random.hpp>\n#include <map>\n#include <tuple>\n//\n// clang in c++14 mode only has a problem with this file: it's an order of instantiation\n// issue caused by us using cpp_int within the gcd algorithm as an error check.\n// Just exclude that combination from testing for now as it's purely a testing issue\n// and we have other compilers that cover this sanity check...\n//\n#if !(defined(__clang__) && (__cplusplus > 201300))\n\nusing boost::multiprecision::cpp_int;\n\nstd::tuple<std::vector<cpp_int>, std::vector<cpp_int>, std::vector<cpp_int> >& get_test_vector(std::size_t bits)\n{\n   static std::map<std::size_t, std::tuple<std::vector<cpp_int>, std::vector<cpp_int>, std::vector<cpp_int> > > data;\n\n   std::tuple<std::vector<cpp_int>, std::vector<cpp_int>, std::vector<cpp_int> >& result = data[bits];\n\n   if (std::get<0>(result).size() == 0)\n   {\n      boost::random::mt19937                     mt;\n      boost::random::uniform_int_distribution<cpp_int> ui(cpp_int(1) << (bits - 1), cpp_int(1) << bits);\n\n      std::vector<cpp_int>& a = std::get<0>(result);\n      std::vector<cpp_int>& b = std::get<1>(result);\n      std::vector<cpp_int>& c = std::get<2>(result);\n\n      for (unsigned i = 0; i < 1000; ++i)\n      {\n         a.push_back(ui(mt));\n         b.push_back(ui(mt));\n         if (b.back() > a.back())\n            b.back().swap(a.back());\n         c.push_back(0);\n      }\n   }\n   return result;\n}\n\nstd::vector<cpp_int>& get_test_vector_a(std::size_t bits)\n{\n   return std::get<0>(get_test_vector(bits));\n}\nstd::vector<cpp_int>& get_test_vector_b(std::size_t bits)\n{\n   return std::get<1>(get_test_vector(bits));\n}\nstd::vector<cpp_int>& get_test_vector_c(std::size_t bits)\n{\n   return std::get<2>(get_test_vector(bits));\n}\n\ncpp_int gcd_euler(cpp_int u, cpp_int v)\n{\n   while (v)\n   {\n      cpp_int t(v);\n      v = u % v;\n      u = t;\n   }\n   return u;\n}\n\nnamespace boost {\nnamespace multiprecision {\nnamespace backends {\n\nstd::size_t total_lehmer_gcd_calls      = 0;\nstd::size_t total_lehmer_gcd_bits_saved = 0;\nstd::size_t total_lehmer_gcd_cycles     = 0;\n\n}}}\n\n\nint main()\n{\n   using boost::multiprecision::backends::total_lehmer_gcd_calls;\n   using boost::multiprecision::backends::total_lehmer_gcd_bits_saved;\n   using boost::multiprecision::backends::total_lehmer_gcd_cycles;\n\n   unsigned bits = 2048;\n\n   std::vector<cpp_int>& a = get_test_vector_a(bits);\n   std::vector<cpp_int>& b = get_test_vector_b(bits);\n   std::vector<cpp_int>& c = get_test_vector_c(bits);\n\n   for (unsigned i = 0; i < a.size(); ++i)\n   {\n      c[i] = gcd(a[i], b[i]);\n      cpp_int t = gcd_euler(a[i], b[i]);\n      BOOST_CHECK_EQUAL(t, c[i]);\n   }\n\n   float average_bits_saved_per_lehmer_call = static_cast<float>(total_lehmer_gcd_bits_saved) / total_lehmer_gcd_calls;\n   float average_number_of_euler_cycles_saved = static_cast<float>(total_lehmer_gcd_cycles) / total_lehmer_gcd_calls;\n\n   std::cout << \"Average number of bits saved per Lehmer call:           \" << average_bits_saved_per_lehmer_call << std::endl;\n   std::cout << \"Average number of Euclid cycles saved per Lehmer call:  \" << average_number_of_euler_cycles_saved << std::endl;\n\n#ifndef BOOST_HAS_INT128\n   BOOST_CHECK_GT(average_bits_saved_per_lehmer_call, 30);\n#else\n   BOOST_CHECK_GT(average_bits_saved_per_lehmer_call, 62);\n#endif\n\n   return boost::report_errors();\n}\n\n#else\n\nint main() { return 0; }\n\n#endif\n", "meta": {"hexsha": "f38b27031a91f4d5b9c089e30f2dc0fc3b7b747d", "size": 3779, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_gcd.cpp", "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": "test/test_gcd.cpp", "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": "test/test_gcd.cpp", "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": 29.5234375, "max_line_length": 128, "alphanum_fraction": 0.6702831437, "num_tokens": 1060, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255928, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.48455789316741116}}
{"text": "/*\n * Filename: similarity.cpp\n *\n * Copyright 2020 Tecnalia\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 \"similarity.h\"\n\n#include <Eigen/LU>\n\n#include <numeric>\n\nnamespace manipulability_metrics\n{\ndouble volumeIntersection(const Ellipsoid& desired_ellipsoid, const Eigen::Matrix<double, 6, Eigen::Dynamic>& jacobian)\n{\n  // Force evaluation by casting to avoid multiple (lazy) computations when iterating\n  auto jjti = static_cast<Eigen::Matrix<double, 6, 6>>((jacobian * jacobian.transpose()).inverse());\n\n  return std::accumulate(cbegin(desired_ellipsoid), cend(desired_ellipsoid), 1.0, [&](auto volume, const auto& ax) {\n    double nu = 1.0 / sqrt(ax.unit.transpose() * jjti * ax.unit);\n    return volume * std::min(nu, ax.len);\n  });\n}\n\ndouble inverseShapeDiscrepancy(const Ellipsoid& desired_ellipsoid,\n                               const Eigen::Matrix<double, 6, Eigen::Dynamic>& jacobian)\n{\n  // Force evaluation by casting to avoid multiple (lazy) computations when iterating\n  auto jjti = static_cast<Eigen::Matrix<double, 6, 6>>((jacobian * jacobian.transpose()).inverse());\n\n  return 1.0 / std::accumulate(cbegin(desired_ellipsoid), cend(desired_ellipsoid),\n                               std::numeric_limits<double>::epsilon(), [&](auto sq_diff, const auto& ax) {\n                                 double nu = 1.0 / sqrt(ax.unit.transpose() * jjti * ax.unit);\n                                 return sq_diff + pow(nu - ax.len, 2.0);\n                               });\n}\n\ndouble dualVolumeIntersection(const Ellipsoid& desired_ellipsoid,\n                              const Eigen::Matrix<double, 6, Eigen::Dynamic>& left_jacobian,\n                              const Eigen::Matrix<double, 6, Eigen::Dynamic>& right_jacobian)\n{\n  const auto left_jjti =\n      static_cast<Eigen::Matrix<double, 6, 6>>((left_jacobian * left_jacobian.transpose()).inverse());\n  const auto right_jjti =\n      static_cast<Eigen::Matrix<double, 6, 6>>((right_jacobian * right_jacobian.transpose()).inverse());\n\n  double volume = 1.0;\n  for (auto i = 0; i < 6; ++i)\n  {\n    double left_nu = 1.0 / sqrt(desired_ellipsoid[i].unit.transpose() * left_jjti * desired_ellipsoid[i].unit);\n    double right_nu = 1.0 / sqrt(desired_ellipsoid[i].unit.transpose() * right_jjti * desired_ellipsoid[i].unit);\n    volume *= std::min({ desired_ellipsoid[i].len, left_nu, right_nu });\n  }\n\n  return volume;\n}\n\ndouble dualInverseShapeDiscrepancy(const Ellipsoid& desired_ellipsoid,\n                                   const Eigen::Matrix<double, 6, Eigen::Dynamic>& left_jacobian,\n                                   const Eigen::Matrix<double, 6, Eigen::Dynamic>& right_jacobian)\n{\n  const auto left_jjti =\n      static_cast<Eigen::Matrix<double, 6, 6>>((left_jacobian * left_jacobian.transpose()).inverse());\n  const auto right_jjti =\n      static_cast<Eigen::Matrix<double, 6, 6>>((right_jacobian * right_jacobian.transpose()).inverse());\n\n  double sq_diff = 0.0;\n  for (auto i = 0; i < 6; ++i)\n  {\n    double left_nu = 1.0 / sqrt(desired_ellipsoid[i].unit.transpose() * left_jjti * desired_ellipsoid[i].unit);\n    double right_nu = 1.0 / sqrt(desired_ellipsoid[i].unit.transpose() * right_jjti * desired_ellipsoid[i].unit);\n    sq_diff += pow(desired_ellipsoid[i].len - std::min(left_nu, right_nu), 2.0);\n  }\n\n  return 1.0 / (sq_diff + std::numeric_limits<double>::epsilon());\n}\n}  // namespace manipulability_metrics\n", "meta": {"hexsha": "84bd857463ad86a78cfc649add9656b60cc309dd", "size": 3917, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "KDLUtils/similarity.cpp", "max_stars_repo_name": "hyu-ryeol/RTControlDualArm", "max_stars_repo_head_hexsha": "30467a95863c5e33c355ec494d9a705ce84f98cd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-02-06T09:55:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-05T12:29:16.000Z", "max_issues_repo_path": "KDLUtils/similarity.cpp", "max_issues_repo_name": "hyu-ryeol/RTControlDualArm", "max_issues_repo_head_hexsha": "30467a95863c5e33c355ec494d9a705ce84f98cd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "KDLUtils/similarity.cpp", "max_forks_repo_name": "hyu-ryeol/RTControlDualArm", "max_forks_repo_head_hexsha": "30467a95863c5e33c355ec494d9a705ce84f98cd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-07-27T06:12:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-24T13:54:46.000Z", "avg_line_length": 43.043956044, "max_line_length": 119, "alphanum_fraction": 0.6630074036, "num_tokens": 1009, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.48455788959703505}}
{"text": "/*\n * Copyright 2012-2019 CNRS-UM LIRMM, CNRS-AIST JRL\n */\n\n// includes\n// std\n#include <fstream>\n#include <iostream>\n#include <tuple>\n\n// boost\n#define BOOST_TEST_MODULE QPMultiRobotTest\n#include <boost/math/constants/constants.hpp>\n#include <boost/test/unit_test.hpp>\n\n// RBDyn\n#include <RBDyn/EulerIntegration.h>\n#include <RBDyn/FK.h>\n#include <RBDyn/FV.h>\n#include <RBDyn/ID.h>\n#include <RBDyn/MultiBody.h>\n#include <RBDyn/MultiBodyConfig.h>\n#include <RBDyn/MultiBodyGraph.h>\n\n// Tasks\n#include \"Tasks/Bounds.h\"\n#include \"Tasks/QPConstr.h\"\n#include \"Tasks/QPContactConstr.h\"\n#include \"Tasks/QPMotionConstr.h\"\n#include \"Tasks/QPSolver.h\"\n#include \"Tasks/QPTasks.h\"\n\n// Arms\n#include \"arms.h\"\n\n// Test contact between two robot.\n// We set two identical robot at the same positio\n// then we link the end effector and add a task\n// to make it move on the second robot.\n// The first robot must have the same motion.\nBOOST_AUTO_TEST_CASE(TwoArmContactTest)\n{\n  using namespace Eigen;\n  using namespace sva;\n  using namespace rbd;\n  using namespace tasks;\n  namespace cst = boost::math::constants;\n\n  MultiBody mb1, mb2;\n  MultiBodyConfig mbc1Init, mbc2Init;\n\n  std::tie(mb1, mbc1Init) = makeZXZArm();\n  std::tie(mb2, mbc2Init) = makeZXZArm();\n\n  forwardKinematics(mb1, mbc1Init);\n  forwardVelocity(mb1, mbc1Init);\n  forwardKinematics(mb2, mbc2Init);\n  forwardVelocity(mb2, mbc2Init);\n\n  sva::PTransformd X_0_b1(mbc1Init.bodyPosW.back());\n  sva::PTransformd X_0_b2(mbc2Init.bodyPosW.back());\n  sva::PTransformd X_b1_b2(X_0_b2 * X_0_b1.inv());\n\n  std::vector<MultiBody> mbs = {mb1, mb2};\n  std::vector<MultiBodyConfig> mbcs = {mbc1Init, mbc2Init};\n\n  // Test ContactAccConstr constraint\n  // Also test PositionTask on the second robot\n\n  qp::QPSolver solver;\n\n  std::vector<qp::UnilateralContact> contVec = {qp::UnilateralContact(0, 1, \"b3\", \"b3\", {Vector3d::Zero()},\n                                                                      RotX(cst::pi<double>() / 2.), X_b1_b2, 3,\n                                                                      std::tan(cst::pi<double>() / 4.))};\n\n#if defined __i386__ || defined __aarch64__\n  Matrix3d oriD = RotZ(cst::pi<double>() / 4.);\n  if(solver.solver() == \"QLD\")\n  {\n    oriD = RotZ(0.0);\n  }\n#else\n  Matrix3d oriD = RotZ(cst::pi<double>() / 4.);\n#endif\n  Vector3d posD(oriD * mbc2Init.bodyPosW.back().translation());\n  qp::PositionTask posTask(mbs, 1, \"b3\", posD);\n  qp::SetPointTask posTaskSp(mbs, 1, &posTask, 1000., 1.);\n\n  qp::ContactAccConstr contCstrAcc;\n\n  contCstrAcc.addToSolver(solver);\n  solver.addTask(&posTaskSp);\n\n  solver.nrVars(mbs, contVec, {});\n  solver.updateConstrSize();\n\n  // 3 dof + 3 dof + 3 lambda\n  BOOST_CHECK_EQUAL(solver.nrVars(), 3 + 3 + 3);\n\n  for(int i = 0; i < 1000; ++i)\n  {\n    BOOST_REQUIRE(solver.solve(mbs, mbcs));\n    for(std::size_t r = 0; r < mbs.size(); ++r)\n    {\n      eulerIntegration(mbs[r], mbcs[r], 0.001);\n\n      forwardKinematics(mbs[r], mbcs[r]);\n      forwardVelocity(mbs[r], mbcs[r]);\n    }\n    // check that the link hold\n    sva::PTransformd X_0_b1_post(mbcs[0].bodyPosW.back());\n    sva::PTransformd X_0_b2_post(mbcs[1].bodyPosW.back());\n    sva::PTransformd X_b1_b2_post(X_0_b2 * X_0_b1.inv());\n    BOOST_CHECK_SMALL((X_b1_b2.matrix() - X_b1_b2_post.matrix()).norm(), 1e-5);\n  }\n  // check that the task is well minimized\n  BOOST_CHECK_SMALL(posTask.eval().norm(), 1e-5);\n\n  contCstrAcc.removeFromSolver(solver);\n  solver.removeTask(&posTaskSp);\n\n  // Test ContactSpeedConstr constraint\n  // Also test OrientationTask on the second robot\n\n  mbcs = {mbc1Init, mbc2Init};\n  qp::OrientationTask oriTask(mbs, 1, \"b3\", oriD);\n  qp::SetPointTask oriTaskSp(mbs, 1, &oriTask, 1000., 1.);\n\n  qp::ContactSpeedConstr contCstrSpeed(0.001);\n\n  contCstrSpeed.addToSolver(solver);\n  solver.addTask(&oriTaskSp);\n\n  solver.nrVars(mbs, contVec, {});\n  solver.updateConstrSize();\n\n  for(int i = 0; i < 1000; ++i)\n  {\n    BOOST_REQUIRE(solver.solve(mbs, mbcs));\n    for(std::size_t r = 0; r < mbs.size(); ++r)\n    {\n      eulerIntegration(mbs[r], mbcs[r], 0.001);\n\n      forwardKinematics(mbs[r], mbcs[r]);\n      forwardVelocity(mbs[r], mbcs[r]);\n    }\n    // check that the link hold\n    sva::PTransformd X_0_b1_post(mbcs[0].bodyPosW.back());\n    sva::PTransformd X_0_b2_post(mbcs[1].bodyPosW.back());\n    sva::PTransformd X_b1_b2_post(X_0_b2 * X_0_b1.inv());\n    BOOST_CHECK_SMALL((X_b1_b2.matrix() - X_b1_b2_post.matrix()).norm(), 1e-5);\n  }\n  // check that the task is well minimized\n  BOOST_CHECK_SMALL(oriTask.eval().norm(), 1e-5);\n}\n\n// Test Motion constraint\n// We setup two arm, one with a fixed base and the second\n// with a freebase put on the body b3 of the first robot.\n// First we launch an impossible motion to check the dynamics\n// After we try with an unilateral contact\n// Then we try with a bilateral contact.\nBOOST_AUTO_TEST_CASE(TwoArmDDynamicContactTest)\n{\n  using namespace Eigen;\n  using namespace sva;\n  using namespace rbd;\n  using namespace tasks;\n  namespace cst = boost::math::constants;\n\n  MultiBody mb1, mb2;\n  MultiBodyConfig mbc1Init, mbc2Init;\n\n  std::tie(mb1, mbc1Init) = makeZXZArm();\n\n  forwardKinematics(mb1, mbc1Init);\n  forwardVelocity(mb1, mbc1Init);\n\n  std::tie(mb2, mbc2Init) = makeZXZArm(false);\n  Vector3d mb2InitPos = mbc1Init.bodyPosW.back().translation();\n  Quaterniond mb2InitOri(RotY(cst::pi<double>() / 2.));\n  mbc2Init.q[0] = {mb2InitOri.w(), mb2InitOri.x(),     mb2InitOri.y(), mb2InitOri.z(),\n                   mb2InitPos.x(), mb2InitPos.y() + 1, mb2InitPos.z()};\n  forwardKinematics(mb2, mbc2Init);\n  forwardVelocity(mb2, mbc2Init);\n\n  sva::PTransformd X_0_b1(mbc1Init.bodyPosW.back());\n  sva::PTransformd X_0_b2(mbc2Init.bodyPosW.front());\n  sva::PTransformd X_b1_b2(X_0_b2 * X_0_b1.inv());\n\n  std::vector<MultiBody> mbs = {mb1, mb2};\n  std::vector<MultiBodyConfig> mbcs = {mbc1Init, mbc2Init};\n\n  // Test ContactAccConstr constraint\n  // Also test PositionTask on the second robot\n\n  qp::QPSolver solver;\n\n  std::vector<Eigen::Vector3d> points = {\n      Vector3d(0.1, 0., 0.1),\n      Vector3d(0.1, 0., -0.1),\n      Vector3d(-0.1, 0., -0.1),\n      Vector3d(-0.1, 0., 0.1),\n  };\n\n  std::vector<Eigen::Vector3d> biPoints = {\n      Vector3d(0., 0., 0.),\n      Vector3d(0., 0., 0.),\n      Vector3d(0., 0., 0.),\n      Vector3d(0., 0., 0.),\n  };\n\n  const int nrGen = 4;\n  std::vector<Eigen::Matrix3d> biFrames = {\n      RotX((1. * cst::pi<double>()) / 4.),\n      RotX((3. * cst::pi<double>()) / 4.),\n      Matrix3d(RotX((1. * cst::pi<double>()) / 4.) * RotY(cst::pi<double>() / 2.)),\n      Matrix3d(RotX((3. * cst::pi<double>()) / 4.) * RotY(cst::pi<double>() / 2.)),\n  };\n\n  // The fixed robot can pull the other\n  std::vector<qp::UnilateralContact> contVecFail = {\n      qp::UnilateralContact(0, 1, \"b3\", \"b0\", points, RotX(-cst::pi<double>() / 2.), X_b1_b2, nrGen, 0.7)};\n\n  // The fixed robot can push the other\n  std::vector<qp::UnilateralContact> contVec = {\n      qp::UnilateralContact({0, 1, \"b3\", \"b0\"}, points, RotX(cst::pi<double>() / 2.), X_b1_b2, nrGen, 0.7)};\n\n  // The fixed robot has non coplanar force apply on the other\n  std::vector<qp::BilateralContact> contVecBi = {\n      qp::BilateralContact({0, 1, \"b3\", \"b0\"}, biPoints, biFrames, X_b1_b2, nrGen, 1.)};\n\n  qp::PostureTask posture1Task(mbs, 0, mbc1Init.q, 2., 1.);\n  qp::PostureTask posture2Task(mbs, 1, mbc2Init.q, 2., 1.);\n\n  qp::ContactSpeedConstr contCstrSpeed(0.001);\n\n  const double Inf = std::numeric_limits<double>::infinity();\n  std::vector<std::vector<double>> torqueMin1 = {{}, {-Inf}, {-Inf}, {-Inf}};\n  std::vector<std::vector<double>> torqueMax1 = {{}, {Inf}, {Inf}, {Inf}};\n  std::vector<std::vector<double>> torqueMin2 = {{0., 0., 0., 0., 0., 0.}, {-Inf}, {-Inf}, {-Inf}};\n  std::vector<std::vector<double>> torqueMax2 = {{0., 0., 0., 0., 0., 0.}, {Inf}, {Inf}, {Inf}};\n  std::vector<std::vector<double>> torqueDtMin1 = {{}, {-Inf}, {-Inf}, {-Inf}};\n  std::vector<std::vector<double>> torqueDtMax1 = {{}, {Inf}, {Inf}, {Inf}};\n  std::vector<std::vector<double>> torqueDtMin2 = {{0., 0., 0., 0., 0., 0.}, {-Inf}, {-Inf}, {-Inf}};\n  std::vector<std::vector<double>> torqueDtMax2 = {{0., 0., 0., 0., 0., 0.}, {Inf}, {Inf}, {Inf}};\n  qp::MotionConstr motion1(mbs, 0, {torqueMin1, torqueMax1}, {torqueDtMin1, torqueDtMax1}, 0.005);\n  qp::MotionConstr motion2(mbs, 1, {torqueMin2, torqueMax2}, {torqueDtMin2, torqueDtMax2}, 0.005);\n  qp::PositiveLambda plCstr;\n\n  motion1.addToSolver(solver);\n  motion2.addToSolver(solver);\n  plCstr.addToSolver(solver);\n\n  contCstrSpeed.addToSolver(solver);\n  solver.addTask(&posture1Task);\n  solver.addTask(&posture2Task);\n\n  // check the impossible motion\n  solver.nrVars(mbs, contVecFail, {});\n  solver.updateConstrSize();\n\n  // 3 dof + 9 dof + 4*nrGen lambda\n  BOOST_CHECK_EQUAL(solver.nrVars(), 3 + 9 + 4 * nrGen);\n  BOOST_REQUIRE(!solver.solve(mbs, mbcs));\n\n  // check the unilateral motion\n  mbcs = {mbc1Init, mbc2Init};\n  solver.nrVars(mbs, contVec, {});\n  solver.updateConstrSize();\n\n  for(int i = 0; i < 1000; ++i)\n  {\n    BOOST_REQUIRE(solver.solve(mbs, mbcs));\n    for(std::size_t r = 0; r < mbs.size(); ++r)\n    {\n      eulerIntegration(mbs[r], mbcs[r], 0.001);\n\n      forwardKinematics(mbs[r], mbcs[r]);\n      forwardVelocity(mbs[r], mbcs[r]);\n    }\n    // check that the link hold\n    sva::PTransformd X_0_b1_post(mbcs[0].bodyPosW.back());\n    sva::PTransformd X_0_b2_post(mbcs[1].bodyPosW.front());\n    sva::PTransformd X_b1_b2_post(X_0_b2 * X_0_b1.inv());\n    BOOST_CHECK_SMALL((X_b1_b2.matrix() - X_b1_b2_post.matrix()).norm(), 1e-5);\n\n    // force in world frame must be the same\n    auto f1 = contVec[0].force(solver.lambdaVec(0), contVec[0].r1Cone);\n    auto f2 = contVec[0].force(solver.lambdaVec(0), contVec[0].r2Cone);\n    BOOST_CHECK_SMALL((f1 + f2).norm(), 1e-5);\n  }\n\n  // check the bilateral motion\n  mbcs = {mbc1Init, mbc2Init};\n  solver.nrVars(mbs, {}, contVecBi);\n  solver.updateConstrSize();\n  // 3 dof + 9 dof + 4*nrGen lambda\n  BOOST_CHECK_EQUAL(solver.nrVars(), 3 + 9 + 4 * nrGen);\n\n  for(int i = 0; i < 1000; ++i)\n  {\n    // std::cout << i << std::endl;\n    BOOST_REQUIRE(solver.solve(mbs, mbcs));\n    for(std::size_t r = 0; r < mbs.size(); ++r)\n    {\n      eulerIntegration(mbs[r], mbcs[r], 0.001);\n\n      forwardKinematics(mbs[r], mbcs[r]);\n      forwardVelocity(mbs[r], mbcs[r]);\n    }\n    // check that the link hold\n    sva::PTransformd X_0_b1_post(mbcs[0].bodyPosW.back());\n    sva::PTransformd X_0_b2_post(mbcs[1].bodyPosW.front());\n    sva::PTransformd X_b1_b2_post(X_0_b2 * X_0_b1.inv());\n    BOOST_CHECK_SMALL((X_b1_b2.matrix() - X_b1_b2_post.matrix()).norm(), 1e-5);\n\n    // force in world frame must be the same\n    auto f1 = contVec[0].force(solver.lambdaVec(0), contVec[0].r1Cone);\n    auto f2 = contVec[0].force(solver.lambdaVec(0), contVec[0].r2Cone);\n    BOOST_CHECK_SMALL((f1 + f2).norm(), 1e-5);\n  }\n\n  plCstr.removeFromSolver(solver);\n  motion2.removeFromSolver(solver);\n  motion1.removeFromSolver(solver);\n  contCstrSpeed.removeFromSolver(solver);\n\n  solver.removeTask(&posture1Task);\n  solver.removeTask(&posture2Task);\n}\n\n// Test the MultiCoMTask.\n// We try to move the CoM of two arm at a specific position.\nBOOST_AUTO_TEST_CASE(TwoArmMultiCoMTest)\n{\n  using namespace Eigen;\n  using namespace sva;\n  using namespace rbd;\n  using namespace tasks;\n  namespace cst = boost::math::constants;\n\n  MultiBody mb1, mb2;\n  MultiBodyConfig mbc1Init, mbc2Init;\n\n  std::tie(mb1, mbc1Init) = makeZXZArm(true, sva::PTransformd(Vector3d(-0.5, 0., 0.)));\n  forwardKinematics(mb1, mbc1Init);\n  forwardVelocity(mb1, mbc1Init);\n\n  std::tie(mb2, mbc2Init) = makeZXZArm(true, sva::PTransformd(Vector3d(0.5, 0., 0.)));\n  forwardKinematics(mb2, mbc2Init);\n  forwardVelocity(mb2, mbc2Init);\n\n  sva::PTransformd X_0_b1(mbc1Init.bodyPosW.back());\n  sva::PTransformd X_0_b2(mbc2Init.bodyPosW.back());\n  sva::PTransformd X_b1_b2(X_0_b2 * X_0_b1.inv());\n\n  std::vector<MultiBody> mbs = {mb1, mb2};\n  std::vector<MultiBodyConfig> mbcs = {mbc1Init, mbc2Init};\n\n  // Test ContactAccConstr constraint\n  // Also test PositionTask on the second robot\n\n  qp::QPSolver solver;\n\n  const int nrGen = 3;\n  // The fixed robot can push the other\n  std::vector<qp::UnilateralContact> contVec = {qp::UnilateralContact(\n      {0, 1, \"b3\", \"b3\"}, {Vector3d(0., 0., 0.)}, RotX(cst::pi<double>() / 2.), X_b1_b2, nrGen, 0.7)};\n\n  qp::PostureTask posture1Task(mbs, 0, mbc1Init.q, 2., 1.);\n  qp::PostureTask posture2Task(mbs, 1, mbc2Init.q, 2., 1.);\n  Vector3d comD((rbd::computeCoM(mb1, mbc1Init) + rbd::computeCoM(mb2, mbc2Init)) / 2. + Vector3d(0., 0., 0.5));\n  qp::MultiCoMTask multiCoM(mbs, {0, 1}, comD, 10., 500.);\n  // call this method just for test coverage\n  multiCoM.updateInertialParameters(mbs);\n\n  qp::ContactSpeedConstr contCstrSpeed(0.001);\n\n  solver.addTask(&posture1Task);\n  solver.addTask(&posture2Task);\n\n  solver.nrVars(mbs, contVec, {});\n\n  // Add MultiCoMTask and ContactSpeedConstr after the nrVars call to test\n  // addTask and addToSolver with nrVars init\n  solver.addTask(mbs, &multiCoM);\n  contCstrSpeed.addToSolver(mbs, solver);\n\n  solver.updateConstrSize();\n\n  // 3 dof + 3 dof + 1*nrGen lambda\n  BOOST_CHECK_EQUAL(solver.nrVars(), 3 + 3 + 1 * nrGen);\n\n  for(int i = 0; i < 2000; ++i)\n  {\n    BOOST_REQUIRE(solver.solve(mbs, mbcs));\n    for(std::size_t r = 0; r < mbs.size(); ++r)\n    {\n      eulerIntegration(mbs[r], mbcs[r], 0.001);\n\n      forwardKinematics(mbs[r], mbcs[r]);\n      forwardVelocity(mbs[r], mbcs[r]);\n    }\n    // check that the link hold\n    sva::PTransformd X_0_b1_post(mbcs[0].bodyPosW.back());\n    sva::PTransformd X_0_b2_post(mbcs[1].bodyPosW.back());\n    sva::PTransformd X_b1_b2_post(X_0_b2 * X_0_b1.inv());\n    BOOST_CHECK_SMALL((X_b1_b2.matrix() - X_b1_b2_post.matrix()).norm(), 1e-5);\n  }\n  BOOST_CHECK_SMALL(multiCoM.speed().norm(), 1e-3);\n\n  contCstrSpeed.removeFromSolver(solver);\n\n  solver.removeTask(&posture1Task);\n  solver.removeTask(&posture2Task);\n  solver.removeTask(&multiCoM);\n}\n\n// Test the MultiRobotTransformTask\n// We try to set he two end effector at the same frame.\nBOOST_AUTO_TEST_CASE(MultiRobotTransformTest)\n{\n  using namespace Eigen;\n  using namespace sva;\n  using namespace rbd;\n  using namespace tasks;\n  namespace cst = boost::math::constants;\n\n  MultiBody mb1, mb2;\n  MultiBodyConfig mbc1Init, mbc2Init;\n\n  std::tie(mb1, mbc1Init) =\n      makeZXZArm(true, sva::PTransformd(sva::RotZ(-cst::pi<double>() / 4.), Vector3d(-0.5, 0., 0.)));\n  forwardKinematics(mb1, mbc1Init);\n  forwardVelocity(mb1, mbc1Init);\n\n  std::tie(mb2, mbc2Init) =\n      makeZXZArm(false, sva::PTransformd(sva::RotZ(cst::pi<double>() / 2.), Vector3d(0.5, 0., 0.)));\n  forwardKinematics(mb2, mbc2Init);\n  forwardVelocity(mb2, mbc2Init);\n\n  std::vector<MultiBody> mbs = {mb1, mb2};\n  std::vector<MultiBodyConfig> mbcs = {mbc1Init, mbc2Init};\n\n  // Test ContactAccConstr constraint\n  // Also test PositionTask on the second robot\n\n  qp::QPSolver solver;\n\n  qp::PostureTask posture1Task(mbs, 0, mbc1Init.q, 0.1, 10.);\n  qp::PostureTask posture2Task(mbs, 1, mbc2Init.q, 0.1, 10.);\n  qp::MultiRobotTransformTask mrtt(mbs, 0, 1, \"b3\", \"b3\", sva::PTransformd(sva::RotZ(-cst::pi<double>() / 8.)),\n                                   sva::PTransformd::Identity(), 100., 1000.);\n  mrtt.dimWeight((Vector6d() << 0., 0., 1., 1., 1., 0.).finished());\n\n  solver.addTask(&posture1Task);\n  solver.addTask(&posture2Task);\n  solver.addTask(&mrtt);\n\n  solver.nrVars(mbs, {}, {});\n  solver.updateConstrSize();\n  // 3 dof + 9 dof\n  BOOST_CHECK_EQUAL(solver.nrVars(), 3 + 9);\n\n  for(int i = 0; i < 2000; ++i)\n  {\n    BOOST_REQUIRE(solver.solve(mbs, mbcs));\n    for(std::size_t r = 0; r < mbs.size(); ++r)\n    {\n      eulerIntegration(mbs[r], mbcs[r], 0.005);\n\n      forwardKinematics(mbs[r], mbcs[r]);\n      forwardVelocity(mbs[r], mbcs[r]);\n    }\n  }\n  BOOST_CHECK_SMALL(mrtt.eval().norm(), 1e-3);\n\n  solver.removeTask(&posture1Task);\n  solver.removeTask(&posture2Task);\n  solver.removeTask(&mrtt);\n}\n\n// Test the TorqueTask\nBOOST_AUTO_TEST_CASE(TorqueTaskTest)\n{\n  using namespace Eigen;\n  using namespace sva;\n  using namespace rbd;\n  using namespace tasks;\n  namespace cst = boost::math::constants;\n\n  MultiBody mb1, mb2;\n  MultiBodyConfig mbc1Init, mbc2Init;\n\n  std::tie(mb1, mbc1Init) =\n      makeZXZArm(true, sva::PTransformd(sva::RotZ(-cst::pi<double>() / 4.), Vector3d(-0.5, 0., 0.)));\n  forwardKinematics(mb1, mbc1Init);\n  forwardVelocity(mb1, mbc1Init);\n\n  std::tie(mb2, mbc2Init) =\n      makeZXZArm(false, sva::PTransformd(sva::RotZ(cst::pi<double>() / 2.), Vector3d(0.5, 0., 0.)));\n  forwardKinematics(mb2, mbc2Init);\n  forwardVelocity(mb2, mbc2Init);\n\n  std::vector<MultiBody> mbs = {mb1, mb2};\n  std::vector<MultiBodyConfig> mbcs = {mbc1Init, mbc2Init};\n\n  // Test ContactAccConstr constraint\n  // Also test PositionTask on the second robot\n\n  qp::QPSolver solver;\n\n  std::vector<std::vector<double>> lsup;\n  std::vector<std::vector<double>> linf;\n  std::vector<double> sup;\n  std::vector<double> inf;\n  std::vector<std::vector<double>> lsupDt;\n  std::vector<std::vector<double>> linfDt;\n  std::vector<double> supDt;\n  std::vector<double> infDt;\n\n  for(const auto j : mb1.joints())\n  {\n    sup.resize(j.dof());\n    inf.resize(j.dof());\n    std::fill(sup.begin(), sup.end(), 1e4);\n    std::fill(inf.begin(), inf.end(), -1e4);\n    lsup.push_back(sup);\n    linf.push_back(inf);\n\n    supDt.resize(j.dof());\n    infDt.resize(j.dof());\n    std::fill(supDt.begin(), supDt.end(), 1e8);\n    std::fill(infDt.begin(), infDt.end(), -1e8);\n    lsupDt.push_back(supDt);\n    linfDt.push_back(infDt);\n  }\n\n  TorqueBound tb(lsup, linf);\n  TorqueDBound tdb(lsup, linf);\n\n  qp::PostureTask posture1Task(mbs, 0, mbc1Init.q, 0.1, 10.);\n  qp::PostureTask posture2Task(mbs, 1, mbc2Init.q, 0.1, 10.);\n  qp::TorqueTask tt(mbs, 0, tb, tdb, 0.005, 1);\n\n  solver.addTask(&posture1Task);\n  solver.addTask(&posture2Task);\n  solver.addTask(&tt);\n\n  solver.nrVars(mbs, {}, {});\n  solver.updateConstrSize();\n  // 3 dof + 9 dof\n  BOOST_CHECK_EQUAL(solver.nrVars(), 3 + 9);\n\n  for(int i = 0; i < 2000; ++i)\n  {\n    BOOST_REQUIRE(solver.solve(mbs, mbcs));\n    for(std::size_t r = 0; r < mbs.size(); ++r)\n    {\n      eulerIntegration(mbs[r], mbcs[r], 0.005);\n\n      forwardKinematics(mbs[r], mbcs[r]);\n      forwardVelocity(mbs[r], mbcs[r]);\n    }\n  }\n  solver.removeTask(&posture1Task);\n  solver.removeTask(&posture2Task);\n  solver.removeTask(&tt);\n}\n", "meta": {"hexsha": "6bad9c9b3e15e0bb2a830d9470cb169e7ac5c82b", "size": 18317, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/QPMultiRobotTest.cpp", "max_stars_repo_name": "jrl-umi3218/Tasks", "max_stars_repo_head_hexsha": "a2fa7d118c18533fa1a841c7bebeea0a5688850b", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 60.0, "max_stars_repo_stars_event_min_datetime": "2016-04-08T05:48:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T16:54:31.000Z", "max_issues_repo_path": "tests/QPMultiRobotTest.cpp", "max_issues_repo_name": "jrl-umi3218/Tasks", "max_issues_repo_head_hexsha": "a2fa7d118c18533fa1a841c7bebeea0a5688850b", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 48.0, "max_issues_repo_issues_event_min_datetime": "2016-04-01T09:50:12.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-05T02:12:27.000Z", "max_forks_repo_path": "tests/QPMultiRobotTest.cpp", "max_forks_repo_name": "jrl-umi3218/Tasks", "max_forks_repo_head_hexsha": "a2fa7d118c18533fa1a841c7bebeea0a5688850b", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 21.0, "max_forks_repo_forks_event_min_datetime": "2017-01-10T16:23:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-18T08:40:20.000Z", "avg_line_length": 32.0788091068, "max_line_length": 112, "alphanum_fraction": 0.6562209969, "num_tokens": 6316, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.484557889597035}}
{"text": "#include \"misc.h\"\n\n#include <stdlib.h>\n#include <cmath>\n#include <random> \n\n#include \"../molecules/bead.h\"\n#include <Eigen/Dense>\n\nusing namespace std;\nusing namespace Eigen;\n\ndouble getDist(Bead* b1, Bead* b2, double box_l[], int npbc) {\n  double dist = 0;\n  for (int i = 0; i < 3; i++) {\n    double di = b1->GetCrd(1, i) - b2->GetCrd(1,i);\n    if (i < npbc) {\n      // Periodic boundary conditions\n      di -= box_l[i] * round(di / box_l[i]);\n    }\n    dist += (di * di);\n  }\n\n  return sqrt(dist);\n\n}\n\ndouble getDist(Bead& b1, Bead& b2, double box_l[], int npbc) {\n  double dist = 0;\n  for (int i = 0; i < 3; i++) {\n    double di = b1.GetCrd(1, i) - b2.GetCrd(1,i);\n    if (i < npbc) {\n      // Periodic boundary conditions\n      di -= box_l[i] * round(di / box_l[i]);\n    }\n    dist += (di * di);\n  }\n\n  return sqrt(dist);\n\n}\n\nvoid GetDistVector(Bead& b1, Bead& b2, double box_l[], int npbc,\n                   double (&dist)[3]) {\n  // Vector pointing from Bead1 to Bead2.\n  for (int i = 0; i < 3; i++) {\n    double di = b2.GetCrd(1, i) - b1.GetCrd(1, i);\n\n    // Periodic boundary conditions.\n    if (i < npbc) {\n      di -= box_l[i] * round(di / box_l[i]);\n    }\n    dist[i] = di;\n  }\n\n}\n\nvoid GetDistVectorConsistent(Bead& b1, Bead& b2, double box_l[], int npbc,\n                             double (&dist)[3]) {\n\n  double xyz1[3] = {b1.GetCrd(1, 0), b1.GetCrd(1, 1), b1.GetCrd(1, 2)};\n  double xyz2[3] = {b2.GetCrd(1, 0), b2.GetCrd(1, 1), b2.GetCrd(1, 2)};\n  for (int i = 0; i < 3; i++) {\n    xyz1[i] -= box_l[i] * floor(xyz1[i] / box_l[i]);\n    xyz2[i] -= box_l[i] * floor(xyz2[i] / box_l[i]);\n    dist[i] = xyz2[i] - xyz1[i];\n  }\n\n}\n\nvoid GetDistVectorC(Bead& b1, Bead& b2, double box_l[], int npbc,\n                    double (&dist)[3]) {\n  // Vector pointing from Bead1 to Bead2.\n  for (int i = 0; i < 3; i++) {\n    double di = b2.GetCrd(0, i) - b1.GetCrd(0, i);\n\n    // Periodic boundary conditions.\n    if (i < npbc) {\n      di -= box_l[i] * round(di / box_l[i]);\n    }\n    // Finding the shortest distance between periodic images.\n    if (abs(di) > box_l[i]/2.0) {\n      if (di < 0) {\n        di += box_l[i];\n      }\n      else {\n        di -= box_l[i];\n      }\n    }\n    dist[i] = di;\n  }\n\n}\n\nvoid randSphere(double vec[], mt19937& rand_gen) {\n  double rand_square = 2;\n  double r1, r2;\n  while (rand_square > 1) {\n    // Random numbers between -1 and 1.\n    r1 = 1 - 2 * ((double)rand_gen() / rand_gen.max()); \n    r2 = 1 - 2 * ((double)rand_gen() / rand_gen.max());\n    rand_square = r1 * r1 + r2 * r2;\n  }\n  double ranh = 2 * sqrt(1 - rand_square);\n  vec[0] = r1 * ranh; \n  vec[1] = r2 * ranh; \n  vec[2] = (1 - 2*rand_square); \n\n}\n\ndouble gasdev(double mean, double stdev, mt19937& ranGen) {\n  static int iset = 0;\n  static double gset;\n  double fac, rsq, v1, v2;\n  if (iset == 0) {\n    do {\n      v1=2.0*((double)ranGen() / ranGen.max()) - 1.0;\n      v2=2.0*((double)ranGen() / ranGen.max()) - 1.0;\n      rsq = v1*v1 + v2*v2;\n    } while (rsq >= 1.0 || rsq == 0.0 );\n      fac = sqrt(-2.0 * log(rsq)/rsq);\n\n      gset = v1*fac;\n      iset = 1;\n      return v2*fac * stdev + mean;\n  }\n  else {\n    iset = 0;\n    return gset * stdev + mean;\n  }\n\n  return 0; \n\n}\n\nstring YesOrNo(bool input) {\n  if (input) {\n    return \"yes\";\n  }\n  else {\n    return \"no\";\n  }\n\n}\n\nint factorial(int n) {\n  if (n != 1) {\n     return n*factorial(n-1);\n  }\n  else {\n    return 1;\n  }\n\n}\n\n/** This is a simple least square fit procedure. */\ndouble Interpolate(double * bin_pos, double * f, int len, double sigma) {\n  /*                     INDEX 2\n     X = | bin1_pos 1 |  B = | b1 |  Y = | g(bin1_pos) | d\n         | bin2_pos 1 |      | b2 |      | g(bin2_pos) | i     INDEX 1\n         |    ...     |                  |     ...     | m e\n   */\n  MatrixXf X(len, 2);\n  VectorXf Y(len);\n  for (int i = 0; i < len; i++) {\n    X(i, 0) = bin_pos[i];\n    X(i, 1) = 1.0;\n    Y(i) = f[i];\n  }\n  VectorXf B = (X.transpose() * X).ldlt().solve(X.transpose() * Y);\n\n  /*\n  cout << sigma << '\\t' << sigma * B(0) + B(1) << endl;\n  for (int i = 0; i < len; i++)\n  cout << bin_pos[i] << '\\t' << f[i] << endl;\n  cout << endl;\n  */\n\n  return sigma * B(0) + B(1);\n\n}\n\ndouble Interpolate2(double * bin_pos, double * f, int len, double sigma) {\n  MatrixXf X(len, 2);\n  VectorXf Y(len);\n  for (int i = 0; i < len; i++) {\n    X(i, 0) = bin_pos[i];\n    X(i, 1) = 1.0;\n    Y(i) = f[i];\n  }\n  VectorXf B = (X.transpose() * X).ldlt().solve(X.transpose() * Y);\n  return bin_pos[len-1] * B(0) + B(1);\n\n}\n\n\n", "meta": {"hexsha": "5a494ee1e2c5330091798456643dce020175dc4a", "size": 4475, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/utilities/misc.cc", "max_stars_repo_name": "nuwapi/Plum", "max_stars_repo_head_hexsha": "9359ea634d90dbe0717cd0cc33139b98224817da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-05-11T01:41:00.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-13T14:08:06.000Z", "max_issues_repo_path": "src/utilities/misc.cc", "max_issues_repo_name": "nuowang/Plum", "max_issues_repo_head_hexsha": "9359ea634d90dbe0717cd0cc33139b98224817da", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utilities/misc.cc", "max_forks_repo_name": "nuowang/Plum", "max_forks_repo_head_hexsha": "9359ea634d90dbe0717cd0cc33139b98224817da", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-14T23:20:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-14T23:20:47.000Z", "avg_line_length": 22.7157360406, "max_line_length": 74, "alphanum_fraction": 0.5077094972, "num_tokens": 1665, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.484557889597035}}
{"text": "// smooth_feedback: Control theory on Lie groups\n// https://github.com/pettni/smooth_feedback\n//\n// Licensed under the MIT License <http://opensource.org/licenses/MIT>.\n//\n// Copyright (c) 2021 Petter Nilsson, John B. Mains\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n#ifndef SMOOTH__FEEDBACK__OCP_HPP_\n#define SMOOTH__FEEDBACK__OCP_HPP_\n\n/**\n * @file\n * @brief Optimal control problem definition and conversion to QP.\n */\n\n#include <Eigen/Core>\n#include <smooth/lie_group.hpp>\n\n#include \"collocation.hpp\"\n#include \"nlp.hpp\"\n#include \"traits.hpp\"\n\nnamespace smooth::feedback {\n\n/**\n * @brief Optimal control problem definition\n * @tparam _X state space\n * @tparam _U input space\n *\n * Problem is defined on the interval \\f$ t \\in [0, t_f] \\f$.\n * \\f[\n * \\begin{cases}\n *  \\min              & \\theta(t_f, x_0, x_f, q)                                         \\\\\n *  \\text{s.t.}       & x(0) = x_0                                                       \\\\\n *                    & x(t_f) = x_f                                                     \\\\\n *                    & \\dot x(t) = f(t, x(t), u(t))                                     \\\\\n *                    & q = \\int_{0}^{t_f} g(t, x(t), u(t)) \\mathrm{d}t                  \\\\\n *                    & c_{rl} \\leq c_r(t, x(t), u(t)) \\leq c_{ru} \\quad t \\in [0, t_f]  \\\\\n *                    & c_{el} \\leq c_e(t_f, x_0, x_f, q) \\leq c_{eu}\n * \\end{cases}\n * \\f]\n *\n * The optimal control problem depends on arbitrary functions \\f$ \\theta, f, g, c_r, c_e \\f$.\n * The type of those functions are template pararamters in this structure.\n *\n * @note To enable automatic differentiation \\f$ \\theta, f, g, c_r, c_e \\f$ must be templated over the\n * scalar type.\n */\ntemplate<LieGroup _X, Manifold _U, typename Theta, typename F, typename G, typename CR, typename CE>\nstruct OCP\n{\n  using X = _X;\n  using U = _U;\n\n  /// @brief State dimension \\f$ n_{x} \\f$\n  std::size_t nx;\n  /// @brief Input dimension \\f$ n_{u} \\f$\n  std::size_t nu;\n  /// @brief Number of integrals \\f$ n_{q} \\f$\n  std::size_t nq;\n  /// @brief Number of running constraints \\f$ n_{cr} \\f$\n  std::size_t ncr;\n  /// @brief Number of end constraints \\f$ n_{ce} \\f$\n  std::size_t nce;\n\n  /// @brief Objective function \\f$ \\theta : R \\times X \\times X \\times R^{n_q} \\rightarrow R \\f$\n  Theta theta;\n\n  /// @brief System dynamics \\f$ f : R \\times X \\times U \\rightarrow Tangent<X> \\f$\n  F f;\n  /// @brief Integrals \\f$ g : R \\times X \\times U \\rightarrow R^{n_q} \\f$\n  G g;\n\n  /// @brief Running constraint \\f$ c_r : R \\times X \\times U \\rightarrow R^{n_{cr}} \\f$\n  CR cr;\n  /// @brief Running constraint lower bound \\f$ c_{rl} \\in R^{n_{cr}} \\f$\n  Eigen::VectorXd crl;\n  /// @brief Running constraint upper bound \\f$ c_{ru} \\in R^{n_{cr}} \\f$\n  Eigen::VectorXd cru;\n\n  /// @brief End constraint \\f$ c_e : R \\times X \\times X \\times R^{n_q} \\rightarrow R^{n_{ce}} \\f$\n  CE ce;\n  /// @brief End constraint lower bound \\f$ c_{el} \\in R^{n_{ce}} \\f$\n  Eigen::VectorXd cel;\n  /// @brief End constraint upper bound \\f$ c_{eu} \\in R^{n_{ce}} \\f$\n  Eigen::VectorXd ceu;\n};\n\n/// @brief Concept that is true for OCP specializations\ntemplate<typename T>\nconcept OCPType = traits::is_specialization_of_v<T, OCP>;\n\n/// @brief OCP defined on flat spaces\ntemplate<typename Theta, typename F, typename G, typename CR, typename CE>\nusing FlatOCP = OCP<Eigen::VectorXd, Eigen::VectorXd, Theta, F, G, CR, CE>;\n\n/// @brief Concept that is true for FlatOCP specializations\ntemplate<typename T>\nconcept FlatOCPType = OCPType<T> &&(\n  std::is_same_v<typename T::X, Eigen::VectorXd> && std::is_same_v<typename T::U, Eigen::VectorXd>);\n\n/**\n * @brief Check if an OCP is properly defined.\n */\ninline bool check_ocp(const OCPType auto & ocp)\n{\n  using X = typename std::decay_t<decltype(ocp)>::X;\n  using U = typename std::decay_t<decltype(ocp)>::U;\n\n  const double t = 0;\n  const X x      = Default<X>(ocp.nx);\n  const U u      = Default<U>(ocp.nu);\n\n  if (!(static_cast<std::size_t>(dof(x)) == ocp.nx)) { return false; }\n  if (!(static_cast<std::size_t>(dof(u)) == ocp.nu)) { return false; }\n\n  const auto dx = ocp.f.template operator()<double>(t, x, u);\n  if (!(static_cast<std::size_t>(dx.size()) == ocp.nx)) { return false; }\n\n  const auto g = ocp.g.template operator()<double>(t, x, u);\n  if (!(static_cast<std::size_t>(g.size()) == ocp.nq)) { return false; }\n\n  [[maybe_unused]] const double obj = ocp.theta.template operator()<double>(t, x, x, g);\n\n  const auto cr = ocp.cr.template operator()<double>(t, x, u);\n  if (!(static_cast<std::size_t>(cr.size()) == ocp.ncr)) { return false; }\n  if (!(static_cast<std::size_t>(ocp.crl.size()) == ocp.ncr)) { return false; }\n  if (!(static_cast<std::size_t>(ocp.cru.size()) == ocp.ncr)) { return false; }\n\n  const auto ce = ocp.ce.template operator()<double>(t, x, x, g);\n  if (!(static_cast<std::size_t>(ce.size()) == ocp.nce)) { return false; }\n  if (!(static_cast<std::size_t>(ocp.cel.size()) == ocp.nce)) { return false; }\n  if (!(static_cast<std::size_t>(ocp.ceu.size()) == ocp.nce)) { return false; }\n\n  return true;\n}\n\n/**\n * @brief Flatten a LieGroup OCP by defining it in the tangent space around a trajectory.\n *\n * @param ocp OCPType defined on a LieGroup\n * @param xl nominal state trajectory\n * @param ul nominal state trajectory\n *\n * @return FlatOCPType in variables (xe, ue) obtained via variables change x = xl \u2295 xe, u = ul \u2295 ue,\n */\ninline auto flatten_ocp(const OCPType auto & ocp, auto && xl_fun, auto && ul_fun)\n{\n  using Eigen::VectorX;\n  using X = typename std::decay_t<decltype(ocp)>::X;\n  using U = typename std::decay_t<decltype(ocp)>::U;\n\n  assert(Dof<X> == -1 || ocp.nx == Dof<X>);\n  assert(Dof<U> == -1 || ocp.nu == Dof<U>);\n\n  auto f_new = [f = ocp.f, xl_fun = xl_fun, ul_fun = ul_fun]<typename T>(\n                 const T & t, const VectorX<T> & xe, const VectorX<T> & ue) -> VectorX<T> {\n    using X_T = smooth::CastT<T, X>;\n    using U_T = smooth::CastT<T, U>;\n\n    // can not double-differentiate, so we neglect derivative of linearization w.r.t. t\n    const double tdbl    = static_cast<double>(t);\n    const auto [xl, dxl] = diff::dr(xl_fun, wrt(tdbl));\n    const auto ul        = ul_fun(tdbl);\n\n    const X_T x = rplus(xl.template cast<T>(), xe);\n    const U_T u = rplus(ul.template cast<T>(), ue);\n\n    return dr_expinv<X_T>(xe) * f.template operator()<T>(t, x, u)\n         - dl_expinv<X_T>(xe) * dxl.template cast<T>();\n  };\n\n  auto g_new = [g = ocp.g, xl_fun = xl_fun, ul_fun = ul_fun]<typename T>(\n                 const T & t, const VectorX<T> & xe, const VectorX<T> & ue) -> VectorX<T> {\n    return g.template operator()<T>(t, rplus(xl_fun(t), xe), rplus(ul_fun(t), ue));\n  };\n\n  auto cr_new = [cr = ocp.cr, xl_fun = xl_fun, ul_fun = ul_fun]<typename T>(\n                  const T & t, const VectorX<T> & xe, const VectorX<T> & ue) -> VectorX<T> {\n    return cr.template operator()<T>(t, rplus(xl_fun(t), xe), rplus(ul_fun(t), ue));\n  };\n\n  auto theta_new =\n    [theta = ocp.theta, xl_fun = xl_fun]<typename T>(\n      const T & tf, const VectorX<T> & xe0, const VectorX<T> & xef, const VectorX<T> & q) -> T {\n    return theta.template operator()<T>(tf, rplus(xl_fun(T(0.)), xe0), rplus(xl_fun(tf), xef), q);\n  };\n\n  auto ce_new = [ce = ocp.ce, xl_fun = xl_fun]<typename T>(\n                  const T & tf,\n                  const VectorX<T> & xe0,\n                  const VectorX<T> & xef,\n                  const VectorX<T> & q) -> VectorX<T> {\n    return ce.template operator()<T>(tf, rplus(xl_fun(T(0.)), xe0), rplus(xl_fun(tf), xef), q);\n  };\n\n  return FlatOCP<\n    decltype(theta_new),\n    decltype(f_new),\n    decltype(g_new),\n    decltype(cr_new),\n    decltype(ce_new)>{\n    .nx    = ocp.nx,\n    .nu    = ocp.nu,\n    .nq    = ocp.nq,\n    .ncr   = ocp.ncr,\n    .nce   = ocp.nce,\n    .theta = std::move(theta_new),\n    .f     = std::move(f_new),\n    .g     = std::move(g_new),\n    .cr    = std::move(cr_new),\n    .crl   = ocp.crl,\n    .cru   = ocp.cru,\n    .ce    = std::move(ce_new),\n    .cel   = ocp.cel,\n    .ceu   = ocp.ceu,\n  };\n}\n\n/**\n * @brief Solution to OCP problem.\n */\ntemplate<LieGroup X, Manifold U>\nstruct OCPSolution\n{\n  double t0;\n  double tf;\n\n  /// @brief Integral values\n  Eigen::VectorXd Q;\n\n  /// @brief Callable functions for state and input\n  std::function<U(double)> u;\n  std::function<X(double)> x;\n\n  /// @brief Multipliers for integral constraints\n  Eigen::VectorXd lambda_q;\n\n  /// @brief Multipliers for endpoint constraints\n  Eigen::VectorXd lambda_ce;\n\n  /// @brief Multipliers for dynamics equality constraint\n  std::function<Eigen::VectorXd(double)> lambda_dyn;\n\n  /// @brief Multipliers for active running constraints\n  std::function<Eigen::VectorXd(double)> lambda_cr;\n};\n\n/// @brief Solution to OCP problem defined on flat spaces\nusing FlatOCPSolution = OCPSolution<Eigen::VectorXd, Eigen::VectorXd>;\n\n/**\n * @brief Unflatten a FlatOCPSolution\n *\n * If flat_sol is a solution to flat_ocp = flatten_ocp(ocp, xl_fun, ul_fun),\n * then unflatten_ocpsol(flat_sol, xl_fun, ul_fun) is a solution to ocp.\n */\ntemplate<LieGroup X, Manifold U>\nOCPSolution<X, U> unflatten_ocpsol(const FlatOCPSolution & flatsol, auto && xl_fun, auto && ul_fun)\n{\n  auto u_unflat = [ul_fun = std::forward<decltype(ul_fun)>(ul_fun),\n                   usol   = flatsol.u](double t) -> U { return rplus(ul_fun(t), usol(t)); };\n\n  auto x_unflat = [xl_fun = std::forward<decltype(xl_fun)>(xl_fun),\n                   xsol   = flatsol.x](double t) -> X { return rplus(xl_fun(t), xsol(t)); };\n\n  return {\n    .t0         = flatsol.t0,\n    .tf         = flatsol.tf,\n    .Q          = flatsol.Q,\n    .u          = std::move(u_unflat),\n    .x          = std::move(x_unflat),\n    .lambda_q   = flatsol.lambda_q,\n    .lambda_ce  = flatsol.lambda_ce,\n    .lambda_dyn = flatsol.lambda_dyn,\n    .lambda_cr  = flatsol.lambda_cr,\n  };\n}\n\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}  // namespace detail\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 */\nNLP ocp_to_nlp(const FlatOCPType auto & ocp, const MeshType auto & mesh)\n{\n  const auto [var_beg, var_len, con_beg, con_len] = detail::ocp_nlp_structure(ocp, mesh);\n\n  // OBJECTIVE FUNCTION\n\n  auto f = [var_beg = var_beg, var_len = var_len, ocp = ocp](const Eigen::VectorXd & x) -> double {\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    assert(std::size_t(x.size()) == n);\n\n    const double t0         = 0;\n    const double tf         = x(tfvar_B);\n    const Eigen::VectorXd Q = x.segment(qvar_B, qvar_L);\n    const Eigen::MatrixXd X = x.segment(xvar_B, xvar_L).reshaped(ocp.nx, xvar_L / ocp.nx);\n\n    return colloc_eval_endpt<false>(1, ocp.nx, ocp.theta, t0, tf, X, Q);\n  };\n\n  // OBJECTIVE JACOBIAN\n\n  auto df_dx = [var_beg = var_beg, var_len = var_len, ocp = ocp](\n                 const Eigen::VectorXd & x) -> Eigen::SparseMatrix<double> {\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 double t0         = 0;\n    const double tf         = x(tfvar_B);\n    const Eigen::VectorXd Q = x.segment(qvar_B, qvar_L);\n    const Eigen::MatrixXd X = x.segment(xvar_B, xvar_L).reshaped(ocp.nx, xvar_L / ocp.nx);\n\n    const auto [fval, df_dt0, df_dtf, df_dvecX, df_dQ] =\n      colloc_eval_endpt<true>(1, ocp.nx, ocp.theta, t0, tf, X, Q);\n\n    return sparse_block_matrix({\n      {df_dtf, df_dQ, df_dvecX, Eigen::SparseMatrix<double>(1, uvar_L)},\n    });\n  };\n\n  // CONSTRAINT FUNCTION\n\n  auto g = [var_beg = var_beg,\n            var_len = var_len,\n            con_beg = con_beg,\n            con_len = con_len,\n            mesh    = mesh,\n            ocp     = ocp](const Eigen::VectorXd & x) -> Eigen::VectorXd {\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    assert(std::size_t(x.size()) == n);\n\n    const double t0         = 0;\n    const double tf         = x(tfvar_B);\n    const Eigen::VectorXd Q = x.segment(qvar_B, qvar_L);\n    const Eigen::MatrixXd X = x.segment(xvar_B, xvar_L).reshaped(ocp.nx, xvar_L / ocp.nx);\n    const Eigen::MatrixXd U = x.segment(uvar_B, uvar_L).reshaped(ocp.nu, uvar_L / ocp.nu);\n\n    Eigen::VectorXd ret(m);\n    // clang-format off\n    ret.segment(dcon_B, dcon_L)   = colloc_dyn<false>(ocp.nx, ocp.f, mesh, t0, tf, X, U);\n    ret.segment(qcon_B, qcon_L)   = colloc_int<false>(ocp.nq, ocp.g, mesh, t0, tf, Q, X, U).reshaped();\n    ret.segment(crcon_B, crcon_L) = colloc_eval<false>(ocp.ncr, ocp.cr, mesh, t0, tf, X, U).reshaped();\n    ret.segment(cecon_B, cecon_L) = colloc_eval_endpt<false>(ocp.nce, ocp.nx, ocp.ce, t0, tf, X, Q).reshaped();\n    // clang-format on\n    return ret;\n  };\n\n  // CONSTRAINT JACOBIAN\n  auto dg_dx =\n    [var_beg = var_beg, var_len = var_len, mesh = mesh, ocp = ocp](const Eigen::VectorXd & x) {\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      assert(std::size_t(x.size()) == n);\n\n      const double t0          = 0;\n      const double tf          = x(tfvar_B);\n      const Eigen::VectorXd Qm = x.segment(qvar_B, qvar_L);\n      const Eigen::MatrixXd Xm = x.segment(xvar_B, xvar_L).reshaped(ocp.nx, xvar_L / ocp.nx);\n      const Eigen::MatrixXd Um = x.segment(uvar_B, uvar_L).reshaped(ocp.nu, uvar_L / ocp.nu);\n\n      // clang-format off\n      const auto [Fval, dF_dt0, dF_dtf, dF_dX, dF_dU]        = colloc_dyn<true>(ocp.nx, ocp.f, mesh, t0, tf, Xm, Um);\n      const auto [Gval, dG_dt0, dG_dtf, dG_dQ, dG_dX, dG_dU] = colloc_int<true>(ocp.nq, ocp.g, mesh, t0, tf, Qm, Xm, Um);\n      const auto [CRval, dCR_dt0, dCR_dtf, dCR_dX, dCR_dU]   = colloc_eval<true>(ocp.ncr, ocp.cr, mesh, t0, tf, Xm, Um);\n      const auto [CEval, dCE_dt0, dCE_dtf, dCE_dX, dCE_dQ]   = colloc_eval_endpt<true>(ocp.nce, ocp.nx, ocp.ce, t0, tf, Xm, Qm);\n      // clang-format on\n\n      return sparse_block_matrix({\n        // clang-format off\n        { dF_dtf,     {},  dF_dX,  dF_dU},\n        { dG_dtf,  dG_dQ,  dG_dX,  dG_dU},\n        {dCR_dtf,     {}, dCR_dX, dCR_dU},\n        {dCE_dtf, dCE_dQ, dCE_dX,     {}},\n        // clang-format on\n      });\n    };\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  // VARIABLE BOUNDS\n\n  Eigen::VectorXd xl = Eigen::VectorXd::Constant(n, -std::numeric_limits<double>::infinity());\n  Eigen::VectorXd xu = Eigen::VectorXd::Constant(n, std::numeric_limits<double>::infinity());\n\n  xl.segment(tfvar_B, tfvar_L).setZero();  // tf lower bounded by zero\n\n  // CONSTRAINT BOUNDS\n\n  Eigen::VectorXd gl(m);\n  Eigen::VectorXd gu(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\n  gl.segment(crcon_B, crcon_L) = ocp.crl.replicate(mesh.N_colloc(), 1);\n  gu.segment(crcon_B, crcon_L) = ocp.cru.replicate(mesh.N_colloc(), 1);\n\n  // end constraints\n  gl.segment(cecon_B, cecon_L) = ocp.cel;\n  gu.segment(cecon_B, cecon_L) = ocp.ceu;\n\n  return {\n    .n       = n,\n    .m       = m,\n    .f       = std::move(f),\n    .xl      = std::move(xl),\n    .xu      = std::move(xu),\n    .g       = std::move(g),\n    .gl      = std::move(gl),\n    .gu      = std::move(gu),\n    .df_dx   = std::move(df_dx),\n    .dg_dx   = std::move(dg_dx),\n    .d2f_dx2 = {},\n    .d2g_dx2 = {},\n  };\n}\n\n/**\n * @brief Convert nonlinear program solution to ocp solution\n */\nFlatOCPSolution nlpsol_to_ocpsol(\n  const FlatOCPType auto & ocp, const MeshType auto & mesh, const NLPSolution & nlp_sol)\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::VectorXd 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 = [t0 = t0, tf = tf, mesh = mesh, X = std::move(X)](double t) -> Eigen::VectorXd {\n    return mesh.template eval<Eigen::VectorXd>((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 = [t0 = t0, tf = tf, mesh = mesh, U = std::move(U)](double t) -> Eigen::VectorXd {\n    return mesh.template eval<Eigen::VectorXd>((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::VectorXd {\n    return mesh.template eval<Eigen::VectorXd>((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 = [t0 = t0, tf = tf, mesh = mesh, Lcr = std::move(Lcr)](double t) -> Eigen::VectorXd {\n    return mesh.template eval<Eigen::VectorXd>((t - t0) / (tf - t0), Lcr.colwise(), 0, false);\n  };\n\n  return {\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\n */\nNLPSolution ocpsol_to_nlpsol(\n  const FlatOCPType auto & ocp, const MeshType auto & mesh, const FlatOCPSolution & ocpsol)\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 auto [nodes, weights] = mesh.all_nodes_and_weights();\n\n  const double t0 = 0;\n  const double tf = ocpsol.tf;\n\n  Eigen::VectorXd x(n);\n  Eigen::VectorXd zl(n), zu(n);\n  Eigen::VectorXd lambda(m);\n\n  zl.setZero();\n  zu.setZero();\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 (auto i = 0u; const auto tau : 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    ++i;\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_HPP_\n", "meta": {"hexsha": "4f8d245ff5402ebae17e9325e861203e6cd0c7dd", "size": 22069, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/smooth/feedback/ocp.hpp", "max_stars_repo_name": "pettni/smooth_feedback", "max_stars_repo_head_hexsha": "5f967a6b513a7eeea7c70406416440e7c9a5d2e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-09-08T16:18:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-28T06:13:55.000Z", "max_issues_repo_path": "include/smooth/feedback/ocp.hpp", "max_issues_repo_name": "pettni/smooth_feedback", "max_issues_repo_head_hexsha": "5f967a6b513a7eeea7c70406416440e7c9a5d2e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2021-09-08T16:39:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-10T03:51:41.000Z", "max_forks_repo_path": "include/smooth/feedback/ocp.hpp", "max_forks_repo_name": "pettni/smooth_feedback", "max_forks_repo_head_hexsha": "5f967a6b513a7eeea7c70406416440e7c9a5d2e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2022-02-07T15:56:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T07:23:18.000Z", "avg_line_length": 35.8845528455, "max_line_length": 128, "alphanum_fraction": 0.6164302868, "num_tokens": 7122, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.6370307875894139, "lm_q1q2_score": 0.48455788435541475}}
{"text": "#include \"generation-gui.h\"\n\n#include <imgui/imgui.h>\n#include <Eigen/Dense>\n#include <glm/gtc/type_ptr.hpp>\n#include <string>\n\n#include \"gui/icons-awesome.h\"\n#include \"maths/rbf.h\"\n#include \"components/graphics/material.h\"\n#include \"components/physics/transform.h\"\n\nGenerationGui::GenerationGui(Context& ctx, SingletonComponents& scomps) \n    : m_ctx(ctx), m_scomps(scomps)\n{\n    m_controlPointsXYZ.push_back(glm::ivec3(10, 10, 10));\n    m_controlPointsWeights.push_back(5);\n    m_controlPointsXYZ.push_back(glm::ivec3(0, 0, 0));\n    m_controlPointsWeights.push_back(5);\n}\n\nGenerationGui::~GenerationGui() {}\n\nvoid GenerationGui::update() {\n    ImGui::Begin(ICON_FA_SEEDLING \"  Generation\", 0);\n        if (ImGui::Button(\"Add control point\")) {\n            m_controlPointsXYZ.push_back(glm::ivec3(0, 0, 0));\n            m_controlPointsWeights.push_back(1);\n        }\n\n        if (m_controlPointsXYZ.size() > 2)\n            if (ImGui::Button(\"Remove control point\")) {\n                m_controlPointsXYZ.pop_back();\n                m_controlPointsWeights.push_back(1);\n            }\n\n        ImGui::Spacing();\n        ImGui::Separator();\n        ImGui::Spacing();\n\n        for (unsigned int i = 0; i < m_controlPointsXYZ.size(); i++) {\n            ImGui::SliderFloat(std::to_string(i).c_str(), &m_controlPointsWeights.at(i), 1, 30);\n            ImGui::SliderInt3(std::to_string(i).c_str(), (int*) glm::value_ptr(m_controlPointsXYZ.at(i)), 0, 20);\n            ImGui::Separator();\n        }\n\n        ImGui::Separator();\n        ImGui::Spacing();\n\n        if (ImGui::Button(\"Generate\")) {\n            Eigen::VectorXd controlPointWeights(m_controlPointsXYZ.size());\n            for (unsigned int i = 0; i < m_controlPointsWeights.size(); i++) {\n                controlPointWeights[i] = m_controlPointsWeights.at(i);\n            }\n\n            std::vector<glm::ivec3> coordWithYtoFind;\n            std::vector<met::entity> entityToChange;\n            m_ctx.registry.view<comp::Transform>().each([&](met::entity id, comp::Transform& transform){\n                coordWithYtoFind.push_back(transform.position);\n                entityToChange.push_back(id);\n            });\n            voxmt::rbfInterpolate(coordWithYtoFind, m_controlPointsXYZ, controlPointWeights, voxmt::RBFType::LINEAR, 0.5f, voxmt::RBFTransformAxis::Y);\n\n            for (size_t i = 0; i < coordWithYtoFind.size(); i++) {\n                comp::Transform& trans =  m_ctx.registry.get<comp::Transform>(entityToChange.at(i));\n                trans.position = coordWithYtoFind.at(i);\n            }\n            \n        }\n    ImGui::End();\n}\n\nvoid GenerationGui::onEvent(GuiEvent e) {\n\n}\n", "meta": {"hexsha": "338867e809d736107c8e1a513f02112d5d3a3ba3", "size": 2646, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/gui/generation-gui.cpp", "max_stars_repo_name": "guillaume-haerinck/voxel-editor", "max_stars_repo_head_hexsha": "78c2db3e7f33a1944ef6202c8ae33f4008695153", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-12-30T21:01:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T07:41:52.000Z", "max_issues_repo_path": "src/gui/generation-gui.cpp", "max_issues_repo_name": "guillaume-haerinck/voxel-editor", "max_issues_repo_head_hexsha": "78c2db3e7f33a1944ef6202c8ae33f4008695153", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gui/generation-gui.cpp", "max_forks_repo_name": "guillaume-haerinck/voxel-editor", "max_forks_repo_head_hexsha": "78c2db3e7f33a1944ef6202c8ae33f4008695153", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-04-26T22:02:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-26T22:02:29.000Z", "avg_line_length": 34.8157894737, "max_line_length": 151, "alphanum_fraction": 0.6137566138, "num_tokens": 659, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255927, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.48455788268417077}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2014 Roshan <thisisroshansmail@gmail.com>\n//\n// Distributed under the Boost Software License, Version 1.0\n// See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt\n//\n// See http://kylelutz.github.com/compute for more information.\n//---------------------------------------------------------------------------//\n\n#define BOOST_TEST_MODULE TestDiscreteDistribution\n#include <boost/test/unit_test.hpp>\n\n#include <boost/compute/system.hpp>\n#include <boost/compute/command_queue.hpp>\n#include <boost/compute/algorithm/count_if.hpp>\n#include <boost/compute/container/vector.hpp>\n#include <boost/compute/random/default_random_engine.hpp>\n#include <boost/compute/random/discrete_distribution.hpp>\n#include <boost/compute/lambda.hpp>\n\n#include \"context_setup.hpp\"\n\nBOOST_AUTO_TEST_CASE(discrete_distribution_doctest)\n{\n    using boost::compute::uint_;\n    using boost::compute::lambda::_1;\n\n    boost::compute::vector<uint_> vec(100, context);\n\n//! [generate]\n// initialize the default random engine\nboost::compute::default_random_engine engine(queue);\n\n// initialize weights\nint weights[] = {2, 2};\n\n// setup the discrete distribution to produce integers 0 and 1\n// with equal weights\nboost::compute::discrete_distribution<uint_> distribution(weights, weights+2);\n\n// generate the random values and store them to 'vec'\ndistribution.generate(vec.begin(), vec.end(), engine, queue);\n// ! [generate]\n\n    BOOST_CHECK_EQUAL(\n        boost::compute::count_if(\n            vec.begin(), vec.end(), _1 > 1, queue\n        ),\n        size_t(0)\n    );\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "c572f41d0c72c5e40a4e619973de2415560fa56e", "size": 1695, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_discrete_distribution.cpp", "max_stars_repo_name": "bastiankoe/compute", "max_stars_repo_head_hexsha": "57eec36d20e122a496d3fbfddf8bf4ad8d6f4a4f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-03-18T01:14:13.000Z", "max_stars_repo_stars_event_max_datetime": "2015-03-18T01:14:13.000Z", "max_issues_repo_path": "test/test_discrete_distribution.cpp", "max_issues_repo_name": "bastiankoe/compute", "max_issues_repo_head_hexsha": "57eec36d20e122a496d3fbfddf8bf4ad8d6f4a4f", "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/test_discrete_distribution.cpp", "max_forks_repo_name": "bastiankoe/compute", "max_forks_repo_head_hexsha": "57eec36d20e122a496d3fbfddf8bf4ad8d6f4a4f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8181818182, "max_line_length": 79, "alphanum_fraction": 0.6696165192, "num_tokens": 364, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.48455787911379433}}
{"text": "#include <cassert>\n#include <cmath>\n#include <boost/multiprecision/gmp.hpp>\n\n#include <array>\n#include <algorithm>\n#include <bitset>\n#include <numeric>\n#include <sstream>\n#include <utility>\n#include <vector>\n\n#include <functional>\n\n#include <QtDebug>\n#include <QTime>\n\n#include \"lrucache.hpp\"\n\nusing namespace std;\nusing boost::multiprecision::mpq_rational;\n\nQDebug operator<<(QDebug d, const mpq_rational& r) {\n    d.nospace();\n    d.noquote();\n    stringstream s;\n    s << r;\n    d << QString::fromStdString(s.str());\n    return d.resetFormat();\n}\n\ntemplate<class T, std::size_t N>\nQDebug operator<<(QDebug d, const array<T, N>& a) {\n    d.nospace();\n    d.noquote();\n\n    d << \"std::array(\";\n    for(auto i = begin(a); i != end(a); ++i) {\n        d << *i;\n        if (distance(i, end(a)) > 1) {\n            d << \", \";\n        }\n    }\n    d << \")\";\n    return d.resetFormat();\n}\n\ntemplate<class T>\nQDebug operator<<(QDebug d, const vector<T>& v) {\n    d.nospace();\n    d.noquote();\n    d << \"std::vector(\";\n    for(auto i = begin(v); i != end(v); ++i) {\n        d << *i;\n        if (distance(i, end(v)) > 1) {\n            d << \", \";\n        }\n    }\n    d << \")\";\n    return d.resetFormat();\n}\n\ntemplate<class S, class T>\nQDebug operator<<(QDebug d, const pair<S, T>& p) {\n    d.nospace();\n    d.noquote();\n    d << \"std::pair(\" << p.first << \", \" << p.second << \")\";\n    return d.resetFormat();\n}\n\n// warning: this is only supposed to work for our narrow task of 10 balls for 7 colors. this could go wrong in other cases.\nnamespace std {\ntemplate<size_t L>\nstruct hash<array<int8_t, L>>\n{\n    size_t operator()(const array<int8_t, L>& a) const {\n        int shift = 0;\n        size_t ret = 0;\n\n        foreach (int8_t i, a) {\n            ret += i << shift;\n            shift += 4;\n        }\n\n        return ret;\n    }\n};\n}\n\ntemplate<int NumberOfColors, int NumberOfBallsPerColor>\nclass Urn {\npublic:\n    Urn() {\n        _urn[NumberOfBallsPerColor] = NumberOfColors;\n        for (auto i = 0; i < NumberOfBallsPerColor; i += 1) {\n            _urn[i] = 0;\n        }\n    }\n\n    //bool operator==(const Urn<NumberOfColors, NumberOfBallsPerColor>& u) const {\n    //    return _urn == u._urn;\n    //}\n\n    //bool operator<(const Urn<NumberOfColors, NumberOfBallsPerColor>& u) const {\n    //    for (auto i = begin(_urn), j = begin(u._urn); i != end(_urn); ++i, ++j) {\n    //        if (*i < *j) return true;\n    //    }\n    //    return false;\n    //}\n\n    bool sumOfElementsIsCorrect() const {\n        int8_t sum = 0;\n        for (auto i = begin(_urn); i != end(_urn); ++i) {\n            sum += *i;\n        }\n        return sum == NumberOfColors;\n    }\n\n    int distinctDrawnColors() const {\n        return NumberOfColors - _urn[NumberOfBallsPerColor];\n    }\n\n    vector<pair<int /*index*/, mpq_rational /*prob*/>> pickOptions(int remainingBalls) const {\n        vector<pair<int, mpq_rational>> options;\n\n        int balls = remainingBalls;\n\n        for (int i = 1; i <= NumberOfBallsPerColor; i += 1) {\n            if (_urn[i] > 0) {\n                options.emplace_back(make_pair(i, mpq_rational((int)_urn[i]*i, balls)));\n            }\n        }\n        return options;\n    }\n\n    void pick(int i) {\n        assert(i > 0 && i < (int) _urn.size()); // remove for more speed\n        assert(_urn[i] > 0);                    // remove for more speed\n        _urn[i] -= 1;\n        _urn[i-1] += 1;\n    }\n\n    mpq_rational expectedNumberOfDistinctColors(int picks_) const {\n\n        assert(picks_ <= NumberOfColors*NumberOfBallsPerColor);\n\n        function<mpq_rational(Urn<NumberOfColors, NumberOfBallsPerColor>, mpq_rational, int, lru_cache<array<int8_t, NumberOfBallsPerColor + 1>, mpq_rational>*)> recurse = [&recurse, &picks_](Urn<NumberOfColors, NumberOfBallsPerColor> u, mpq_rational p, int picks, lru_cache<array<int8_t, NumberOfBallsPerColor + 1>, mpq_rational>* cache) -> mpq_rational {\n\n            if (picks == 0) {\n                return u.distinctDrawnColors();\n            }\n\n            if (cache->exists(u._urn)) {\n                return cache->get(u._urn);\n            }\n\n            mpq_rational e = 0;\n\n            for (const auto& pick : u.pickOptions(NumberOfBallsPerColor*NumberOfColors - (picks_ - picks))) {\n                auto uCopy = u;\n                uCopy.pick(pick.first);\n\n                e += recurse(uCopy, p*pick.second, picks-1, cache)*pick.second;\n            }\n\n            cache->put(u._urn, e);\n\n            return e;\n        };\n\n        lru_cache<array<int8_t, NumberOfBallsPerColor + 1>, mpq_rational> cache(100000);\n\n\n        auto ret = recurse(*this, 1, picks_, &cache);\n\n        return ret;\n    }\n\n//private:\npublic: // for testing\n    array<int8_t, NumberOfBallsPerColor + 1> _urn; // _urn[numberofballs] = numberofcolors that have as many balls\n};\n\n\nvoid test() {\n    Urn<7, 10> u710; assert(u710._urn.size() == 11);\n    assert(u710._urn[10] == 7);\n    for(auto i = 0; i < 10; i += 1) assert(u710._urn[i] == 0);\n    assert(u710.sumOfElementsIsCorrect());\n\n    Urn<1, 1> u11;\n    assert(u11.expectedNumberOfDistinctColors(1) == 1);\n\n    Urn<1, 2> u12;\n    assert(u12.expectedNumberOfDistinctColors(1) == 1);\n    assert(u12.expectedNumberOfDistinctColors(2) == 1);\n\n    Urn<2, 3> u22;\n    assert(u22.expectedNumberOfDistinctColors(2) == 1*mpq_rational(4, 10) + 2*mpq_rational( 6, 10));\n    assert(u22.expectedNumberOfDistinctColors(3) == 1*mpq_rational(4, 40) + 2*mpq_rational(36, 40));\n    assert(u22.expectedNumberOfDistinctColors(4) == 2);\n    assert(u22.expectedNumberOfDistinctColors(5) == 2);\n    assert(u22.expectedNumberOfDistinctColors(6) == 2);\n\n    Urn<3, 2> u32_;\n    assert(u32_.expectedNumberOfDistinctColors(2) == 1*mpq_rational( 3, 15) + 2*mpq_rational(12, 15));\n    assert(u32_.expectedNumberOfDistinctColors(3) == 2*mpq_rational(18, 30) + 3*mpq_rational(12, 30));\n    //assert(u32_.expectedNumberOfDistinctColors(4) == );\n    //assert(u32_.expectedNumberOfDistinctColors(5) == );\n    assert(u32_.expectedNumberOfDistinctColors(6) == 3);\n}\n\nvoid doit() {\n    Urn<7, 10> u;\n    qDebug() << u.expectedNumberOfDistinctColors(20);\n}\n\nint main() {\n\n    test();\n\n    doit();\n\n    return 0;\n}\n", "meta": {"hexsha": "3814adf2c2d7360151e8820941a8fc7257571d0a", "size": 6140, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "project-euler/493/main.cpp", "max_stars_repo_name": "hydroo/coding-and-math-exercises", "max_stars_repo_head_hexsha": "c0c9b8ae48e043b0809e4c592444f3e4bc3222d8", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-05-29T21:03:26.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-11T02:10:53.000Z", "max_issues_repo_path": "project-euler/493/main.cpp", "max_issues_repo_name": "hydroo/coding-and-math-exercises", "max_issues_repo_head_hexsha": "c0c9b8ae48e043b0809e4c592444f3e4bc3222d8", "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": "project-euler/493/main.cpp", "max_forks_repo_name": "hydroo/coding-and-math-exercises", "max_forks_repo_head_hexsha": "c0c9b8ae48e043b0809e4c592444f3e4bc3222d8", "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": 27.1681415929, "max_line_length": 356, "alphanum_fraction": 0.5814332248, "num_tokens": 1791, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936438, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4845490850149164}}
{"text": "//Author: Dr. Shantanu Shahane\n#include <stdio.h>\n#include <math.h>\n#include <stdlib.h>\n#include <time.h>\n#include <float.h>\n#include <string.h>\n#include <iostream>\n#include <vector>\n#include <algorithm>\n#include \"class.hpp\"\n#include <unistd.h>\n#include <limits.h>\n#include <Eigen/Dense>\n#include <unsupported/Eigen/SparseExtra>\n#include <Eigen/SparseLU>\n#include <Eigen/OrderingMethods>\n#include <Eigen/Eigenvalues>\n#include <Eigen/Core>\n#include <Eigen/SparseCore>\n#include <Spectra/GenEigsSolver.h>\n#include <Spectra/MatOp/SparseGenMatProd.h>\n#include <Spectra/GenEigsRealShiftSolver.h>\n#include <Spectra/MatOp/SparseGenRealShiftSolve.h>\nusing namespace std;\n\nPOINTS::POINTS(PARAMETERS &parameters)\n{\n    cout << \"\\n\";\n    clock_t clock_t1 = clock();\n    read_points_xyz_msh(parameters);\n    read_points_flag_msh(parameters);\n    calc_vert_normal(parameters);\n    calc_boundary_face_area(parameters);\n    delete_corner_edge_vertices(parameters);\n    cout << \"POINTS::read_points_xyz_msh original mesh nv: \" << nv_original << \", nelem: \" << nelem_original << endl;\n    cout << \"POINTS::POINTS after deleting corners nv: \" << nv << endl;\n    cout << \"\\n\";\n    for (int iv = 0; iv < nv; iv++)\n        bc_tag.push_back(INTERIOR_TAG); //initialize to interior; should be set to correct value in main file if required\n    for (int icv = 0; icv < nelem_original; icv++)\n        elem_bc_tag_original.push_back(INTERIOR_TAG); //initialize to interior; should be set to correct value by calling points.calc_elem_bc_tag(parameters) in main file if required\n    parameters.points_timer = ((double)(clock() - clock_t1)) / CLOCKS_PER_SEC;\n}\n\nvoid POINTS::set_periodic_bc(PARAMETERS &parameters, vector<string> periodic_axis)\n{\n    int dim = parameters.dimension;\n    if (periodic_axis.size() > dim)\n    {\n        cout << \"\\n\\nPOINTS::set_periodic_bc number of periodic axes: \" << periodic_axis.size() << \" should not be greater than problem dimension: \" << dim << \"\\n\\n\";\n        throw bad_exception();\n    }\n\n    for (int ip = 0; ip < periodic_axis.size(); ip++)\n        if (periodic_axis[ip] == \"x\" || periodic_axis[ip] == \"X\")\n            parameters.periodic_bc_index.push_back(0);\n        else if (periodic_axis[ip] == \"y\" || periodic_axis[ip] == \"Y\")\n            parameters.periodic_bc_index.push_back(1);\n        else if ((periodic_axis[ip] == \"z\" || periodic_axis[ip] == \"Z\") && dim == 3)\n            parameters.periodic_bc_index.push_back(2);\n        else\n        {\n            cout << \"\\n\\nPOINTS::set_periodic_bc undefined periodic_axis: \" << periodic_axis[ip] << \"\\n\\n\";\n            throw bad_exception();\n        }\n    cout << \"POINTS::set_periodic_bc periodic axes:\";\n    for (int ip = 0; ip < periodic_axis.size(); ip++)\n        cout << \" \" << periodic_axis[ip];\n    cout << \"\\n\\n\";\n    vector<int> ind_p = parameters.periodic_bc_index;\n    double x_min = xyz[0], x_max = xyz[0], y_min = xyz[1], y_max = xyz[1], z_min = xyz[2], z_max = xyz[2];\n    for (int iv = 0; iv < nv; iv++)\n    {\n        if (x_min > xyz[dim * iv])\n            x_min = xyz[dim * iv];\n        if (x_max < xyz[dim * iv])\n            x_max = xyz[dim * iv];\n        if (y_min > xyz[dim * iv + 1])\n            y_min = xyz[dim * iv + 1];\n        if (y_max < xyz[dim * iv + 1])\n            y_max = xyz[dim * iv + 1];\n        if (dim == 3)\n        {\n            if (z_min > xyz[dim * iv + 2])\n                z_min = xyz[dim * iv + 2];\n            if (z_max < xyz[dim * iv + 2])\n                z_max = xyz[dim * iv + 2];\n        }\n    }\n    xyz_min.push_back(x_min), xyz_min.push_back(y_min);\n    xyz_max.push_back(x_max), xyz_max.push_back(y_max);\n    if (dim == 3)\n        xyz_min.push_back(z_min), xyz_max.push_back(z_max);\n    for (int i1 = 0; i1 < xyz_min.size(); i1++)\n        xyz_length.push_back(xyz_max[i1] - xyz_min[i1]);\n\n    delete_periodic_bc_vertices(parameters);\n\n    vector<bool> empty_bool;\n    for (int iv = 0; iv < nv; iv++)\n    {\n        periodic_bc_flag.push_back(empty_bool);\n        for (int ip = 0; ip < ind_p.size(); ip++)\n            periodic_bc_flag[iv].push_back(false);\n    }\n    for (int iv = 0; iv < nv; iv++)\n        if (boundary_flag[iv])\n            for (int ip = 0; ip < ind_p.size(); ip++)\n                if ((fabs(xyz[dim * iv + ind_p[ip]] - xyz_min[ind_p[ip]]) < 1E-5) || (fabs(xyz[dim * iv + ind_p[ip]] - xyz_max[ind_p[ip]]) < 1E-5)) //periodic point is not a real boundary\n                    boundary_flag[iv] = false, periodic_bc_flag[iv][ip] = true;\n\n    vector<int> empty_int;\n    for (int iv = 0; iv < nv; iv++)\n    {\n        periodic_bc_section.push_back(empty_int);\n        for (int ip = 0; ip < ind_p.size(); ip++)\n            periodic_bc_section[iv].push_back(100);\n    }\n    double xyz_1, xyz_2;\n    for (int iv = 0; iv < nv; iv++) //takes values [-1,0,1] for [near_min,middle,near_max] sections respectively\n        for (int ip = 0; ip < ind_p.size(); ip++)\n        {\n            xyz_1 = xyz_min[ind_p[ip]] + (xyz_length[ind_p[ip]] / 3.0);\n            xyz_2 = xyz_min[ind_p[ip]] + (2.0 * xyz_length[ind_p[ip]] / 3.0);\n            if (xyz[dim * iv + ind_p[ip]] < xyz_1)\n                periodic_bc_section[iv][ip] = -1; //section in range [min, xyz_1)\n            else if ((xyz_1 <= xyz[dim * iv + ind_p[ip]]) && (xyz[dim * iv + ind_p[ip]] <= xyz_2))\n                periodic_bc_section[iv][ip] = 0; //section in range [xyz_1 -> xyz_2]\n            else\n                periodic_bc_section[iv][ip] = 1; //section in range (xyz_2, max]}\n        }\n}\n\nvoid POINTS::delete_periodic_bc_vertices(PARAMETERS &parameters)\n{ //delete corner vertices for 2D problems and both corner and edge vertices for 3D problems\n    int iv_offset = 0, iv1, dim = parameters.dimension, nv1 = boundary_flag.size();\n    vector<int> ind_p = parameters.periodic_bc_index;\n    vector<bool> delete_vertices_temp;\n    for (int iv0 = 0; iv0 < nv_original; iv0++)\n    {\n        if (corner_edge_vertices[iv0]) //already deleted vertex\n            iv_offset++;\n        else\n        {\n            iv1 = iv0 - iv_offset;\n            delete_vertices_temp.push_back(false);\n            if (boundary_flag[iv1])\n                for (int ip = 0; ip < ind_p.size(); ip++)\n                    if (fabs(xyz[dim * iv1 + ind_p[ip]] - xyz_max[ind_p[ip]]) < 1E-5)\n                    { //delete higher end of periodic bc\n                        delete_vertices_temp[iv1] = true;\n                        corner_edge_vertices[iv0] = true; //this vertex is deleted (used in CLOUD::calc_iv_original_nearest_vert)\n                    }\n        }\n    }\n\n    vector<double> xyz_temp, normal_temp;\n    vector<bool> b_temp;\n    vector<int> bc_tag_temp;\n    for (iv1 = 0; iv1 < nv1; iv1++)\n    {\n        if (delete_vertices_temp[iv1] == false)\n        { //iv is a required vertex: thus copy in temporary vectors\n            b_temp.push_back(boundary_flag[iv1]);\n            bc_tag_temp.push_back(bc_tag[iv1]);\n            for (int i = 0; i < dim; i++)\n            {\n                xyz_temp.push_back(xyz[dim * iv1 + i]);\n                normal_temp.push_back(normal[dim * iv1 + i]);\n            }\n        }\n    }\n    bc_tag.clear();\n    boundary_flag.clear();\n    xyz.clear();\n    normal.clear();\n    boundary_flag.insert(boundary_flag.end(), b_temp.begin(), b_temp.end());\n    bc_tag.insert(bc_tag.end(), bc_tag_temp.begin(), bc_tag_temp.end());\n    xyz.insert(xyz.end(), xyz_temp.begin(), xyz_temp.end());\n    normal.insert(normal.end(), normal_temp.begin(), normal_temp.end());\n    b_temp.clear();\n    xyz_temp.clear();\n    normal_temp.clear();\n    delete_vertices_temp.clear();\n    bc_tag_temp.clear();\n    nv = boundary_flag.size();\n    cout << \"POINTS::delete_periodic_bc_vertices after deleting periodic_bc vertices nv: \" << nv << endl;\n}\n\nvoid POINTS::calc_elem_bc_tag(PARAMETERS &parameters)\n{\n    int iv_orig, iv_new, dim = parameters.dimension;\n    double dist = 0.0;\n    vector<int> iv_tag_temp;\n    vector<int>::iterator it;\n    for (int icv = 0; icv < nelem_original; icv++)\n    {\n        if (elem_boundary_flag_original[icv])\n        {\n            for (int i1 = 0; i1 < elem_vert_original[icv].size(); i1++)\n            {\n                iv_orig = elem_vert_original[icv][i1];\n                iv_new = iv_original_nearest_vert[iv_orig];\n                dist = 0.0;\n                for (int i2 = 0; i2 < dim; i2++)\n                    dist = dist + ((xyz[dim * iv_new + i2] - xyz_original[dim * iv_orig + i2]) * (xyz[dim * iv_new + i2] - xyz_original[dim * iv_orig + i2]));\n                if (sqrt(dist) < 1E-5) //keep vertices which are not removed (thus, dist should be zero)\n                    iv_tag_temp.push_back(bc_tag[iv_new]);\n            }\n            if (iv_tag_temp.size() == 0)\n            {\n                printf(\"\\n\\nERROR from POINTS::calc_elem_bc_tag icv: %i does not have any vertices which are not deleted; elem_vert_original[icv].size(): %lu\\n\\n\", icv, elem_vert_original[icv].size());\n                throw bad_exception();\n            }\n            sort(iv_tag_temp.begin(), iv_tag_temp.end());          //sort vector\n            it = unique(iv_tag_temp.begin(), iv_tag_temp.end());   //get indices of duplicate entries\n            iv_tag_temp.erase(it, iv_tag_temp.end());              //delete duplicate entries\n            iv_tag_temp.resize(distance(iv_tag_temp.begin(), it)); //resize vector to remove empty entry locations\n            if (iv_tag_temp.size() > 1)\n            {\n                printf(\"\\n\\nERROR from POINTS::calc_elem_bc_tag icv: %i has vertices belonging to %lu bc_tag; elem_vert_original[icv].size(): %lu\\n\\n\", icv, iv_tag_temp.size(), elem_vert_original[icv].size());\n                throw bad_exception();\n            }\n            elem_bc_tag_original[icv] = iv_tag_temp[0];\n\n            iv_tag_temp.clear();\n        }\n    }\n}\n\nvoid POINTS::calc_boundary_face_area(PARAMETERS &parameters)\n{ //area or length of boundary elements for 3D or 2D (used to compute fluxes at boundaries)\n    //algorithm references: http://geomalgorithms.com/a01-_area.html#3D%20Polygons, https://stackoverflow.com/questions/12642256/python-find-area-of-polygon-from-xyz-coordinates\n    double crossprod_sum[3], crossprod[3], v1[3], v2[3], normal[3];\n    int iv1, iv2, dim = parameters.dimension;\n    vector<vector<int>> vert_nb_cv;\n    vector<double> elem_normal;\n    if (dim == 3)\n    {\n        calc_vert_nb_cv(parameters, vert_nb_cv, elem_vert_original);\n        calc_elem_normal_3D(elem_normal, vert_nb_cv, elem_vert_original, elem_boundary_flag_original);\n    }\n    for (int icv = 0; icv < elem_vert_original.size(); icv++)\n    {\n        boundary_face_area_original.push_back(0.0);\n        if (elem_boundary_flag_original[icv])\n        {\n            if (dim == 3)\n            { //3D: area of face\n                crossprod_sum[0] = 0.0, crossprod_sum[1] = 0.0, crossprod_sum[2] = 0.0;\n                for (int i = 0; i < elem_vert_original[icv].size(); i++)\n                {\n                    iv1 = elem_vert_original[icv][i];\n                    if (i < elem_vert_original[icv].size() - 1)\n                        iv2 = elem_vert_original[icv][i + 1];\n                    else\n                        iv2 = elem_vert_original[icv][0]; //last vertex gets connected to vertex no \"0\"\n                    for (int j = 0; j < 3; j++)\n                    {\n                        v1[j] = xyz_original[3 * iv1 + j];\n                        v2[j] = xyz_original[3 * iv2 + j];\n                    }\n                    cross_product(crossprod, v1, v2);\n                    for (int j = 0; j < 3; j++)\n                        crossprod_sum[j] += crossprod[j];\n                }\n                for (int i = 0; i < 3; i++)\n                    normal[i] = elem_normal[3 * icv + i];\n                boundary_face_area_original[icv] = 0.5 * fabs(crossprod_sum[0] * normal[0] + crossprod_sum[1] * normal[1] + crossprod_sum[2] * normal[2]);\n            }\n            else\n            { //2D: length of edge\n                iv1 = elem_vert_original[icv][0];\n                iv2 = elem_vert_original[icv][1];\n                for (int j = 0; j < dim; j++)\n                {\n                    v1[j] = xyz_original[dim * iv1 + j];\n                    v2[j] = xyz_original[dim * iv2 + j];\n                    boundary_face_area_original[icv] = boundary_face_area_original[icv] + (v1[j] - v2[j]) * (v1[j] - v2[j]);\n                }\n                boundary_face_area_original[icv] = sqrt(boundary_face_area_original[icv]);\n            }\n        }\n    }\n    if (dim == 3)\n    {\n        for (int iv = 0; iv < vert_nb_cv.size(); iv++)\n            vert_nb_cv[iv].clear();\n        vert_nb_cv.clear();\n        elem_normal.clear();\n    }\n}\n\nvoid POINTS::delete_corner_edge_vertices(PARAMETERS &parameters)\n{ //delete corner vertices for 2D problems and both corner and edge vertices for 3D problems\n    clock_t start = clock();\n    vector<double> xyz_temp, normal_temp;\n    vector<bool> b_temp;\n    int dim = parameters.dimension, nv1 = boundary_flag.size();\n    for (int iv = 0; iv < nv1; iv++)\n    {\n        if (corner_edge_vertices[iv] == false)\n        { //iv is a required vertex: thus copy in temporary vectors\n            b_temp.push_back(boundary_flag[iv]);\n            for (int i = 0; i < dim; i++)\n            {\n                xyz_temp.push_back(xyz[dim * iv + i]);\n                normal_temp.push_back(normal[dim * iv + i]);\n            }\n        }\n    }\n    boundary_flag.clear();\n    xyz.clear();\n    normal.clear();\n    boundary_flag.insert(boundary_flag.end(), b_temp.begin(), b_temp.end());\n    xyz.insert(xyz.end(), xyz_temp.begin(), xyz_temp.end());\n    normal.insert(normal.end(), normal_temp.begin(), normal_temp.end());\n    b_temp.clear();\n    xyz_temp.clear();\n    normal_temp.clear();\n    // corner_edge_vertices.clear();\n    nv = boundary_flag.size();\n}\n\nvoid POINTS::calc_vert_normal(PARAMETERS &parameters)\n{\n    vector<vector<int>> elem_vert, vert_nb_cv;\n    vector<bool> elem_boundary_flag; //, vert_boundary_flag;\n    vector<double> elem_normal;\n    read_elem_vert_complete_msh(parameters, elem_vert, elem_boundary_flag);\n    calc_vert_nb_cv(parameters, vert_nb_cv, elem_vert);\n    if (parameters.dimension == 2)\n        calc_elem_normal_2D(elem_normal, vert_nb_cv, elem_vert, elem_boundary_flag);\n    else\n        calc_elem_normal_3D(elem_normal, vert_nb_cv, elem_vert, elem_boundary_flag);\n    elem_boundary_flag_original = elem_boundary_flag;\n\n    for (int iv = 0; iv < parameters.dimension * nv; iv++)\n        normal.push_back(0.0);\n    int nbcv, count;\n    double magnitude;\n    for (int iv = 0; iv < nv; iv++)\n    {\n        if (boundary_flag[iv])\n        {\n            count = 0;\n            for (int i1 = 0; i1 < vert_nb_cv[iv].size(); i1++)\n            {\n                nbcv = vert_nb_cv[iv][i1];\n                if (elem_boundary_flag[nbcv])\n                {\n                    for (int i2 = 0; i2 < parameters.dimension; i2++)\n                        normal[parameters.dimension * iv + i2] += elem_normal[parameters.dimension * nbcv + i2];\n                    count++;\n                }\n            }\n            for (int i2 = 0; i2 < parameters.dimension; i2++)\n                normal[parameters.dimension * iv + i2] /= ((double)count);\n            magnitude = 0.0;\n            for (int i2 = 0; i2 < parameters.dimension; i2++)\n                magnitude += normal[parameters.dimension * iv + i2] * normal[parameters.dimension * iv + i2];\n            magnitude = sqrt(magnitude);\n            for (int i2 = 0; i2 < parameters.dimension; i2++)\n                normal[parameters.dimension * iv + i2] /= magnitude;\n        }\n    }\n\n    elem_boundary_flag.clear();\n    elem_normal.clear();\n    int ncv = elem_vert.size(), nv1 = vert_nb_cv.size();\n    for (int icv = 0; icv < ncv; icv++)\n        elem_vert[icv].clear();\n    elem_vert.clear();\n    for (int iv = 0; iv < nv1; iv++)\n        vert_nb_cv[iv].clear();\n    vert_nb_cv.clear();\n}\n\nvoid POINTS::calc_elem_normal_3D(vector<double> &elem_normal, vector<vector<int>> &vert_nb_cv, vector<vector<int>> &elem_vert, vector<bool> &elem_boundary_flag)\n{\n    int dim = 3;\n    int nv = (int)(xyz.size() / dim), ncv = elem_vert.size();\n    int iv_nb_cv_internal, iv0, iv1, iv2;\n    double normal[3], direction[3], magnitude, d_temp, vec0[3], vec1[3], centroid[3];\n    for (int icv = 0; icv < dim * ncv; icv++)\n    {\n        elem_normal.push_back(0.0);\n    }\n    for (int icv = 0; icv < ncv; icv++)\n    {\n        if (elem_boundary_flag[icv])\n        {\n            if (elem_vert[icv].size() < 3)\n            {\n                cout << \"\\n\\nERROR from calc_elem_normal_3D boundary element icv: \" << icv << \" has only \" << elem_vert[icv].size() << \" vertices\\n\\n\";\n                throw bad_exception();\n            }\n            iv0 = elem_vert[icv][0];\n            iv1 = elem_vert[icv][1];\n            iv2 = elem_vert[icv][2];\n            for (int i1 = 0; i1 < dim; i1++)\n            {\n                vec0[i1] = xyz[dim * iv1 + i1] - xyz[dim * iv0 + i1];\n                vec1[i1] = xyz[dim * iv2 + i1] - xyz[dim * iv1 + i1];\n            }\n            cross_product(normal, vec0, vec1);\n            iv_nb_cv_internal = -1;\n            for (int i1 = 0; i1 < vert_nb_cv[iv0].size(); i1++)\n            {\n                if (!elem_boundary_flag[vert_nb_cv[iv0][i1]])\n                { //is internal CV\n                    iv_nb_cv_internal = vert_nb_cv[iv0][i1];\n                    break;\n                }\n            }\n            if (iv_nb_cv_internal == -1)\n            {\n                cout << \"\\n\\nERROR from calc_elem_normal_3D boundary vertex iv0: \" << iv0 << \" does not have a neighboring internal element\\n\\n\";\n                cout << \"\\n\\nERROR from calc_elem_normal_3D boundary element icv: \" << icv << \" does not have a neighboring internal element\\n\\n\";\n                throw bad_exception();\n            }\n            // iv_nb_vert_internal = -1;\n            centroid[0] = 0.0;\n            centroid[1] = 0.0;\n            centroid[2] = 0.0;\n            for (int i1 = 0; i1 < elem_vert[iv_nb_cv_internal].size(); i1++)\n            {\n                // if (elem_vert[iv_nb_cv_internal][i1] != iv0 && elem_vert[iv_nb_cv_internal][i1] != iv1)\n                // if (!vert_boundary_flag[elem_vert[iv_nb_cv_internal][i1]])\n                // { //internal vertex found\n                //     iv_nb_vert_internal = elem_vert[iv_nb_cv_internal][i1];\n                //     break;\n                // }\n                centroid[0] += xyz[dim * elem_vert[iv_nb_cv_internal][i1]];\n                centroid[1] += xyz[dim * elem_vert[iv_nb_cv_internal][i1] + 1];\n                centroid[2] += xyz[dim * elem_vert[iv_nb_cv_internal][i1] + 2];\n            }\n            // if (iv_nb_vert_internal == -1)\n            // {\n            //     cout << \"\\ncalc_elem_normal_3D internal element iv_nb_cv_internal: \" << iv_nb_cv_internal << \" does not have a internal vertex\\n\\n\";\n            //     throw bad_exception();\n            // }\n            centroid[0] = centroid[0] / ((double)(elem_vert[iv_nb_cv_internal].size()));\n            centroid[1] = centroid[1] / ((double)(elem_vert[iv_nb_cv_internal].size()));\n            centroid[2] = centroid[2] / ((double)(elem_vert[iv_nb_cv_internal].size()));\n            // direction[0] = xyz[dim * iv1] - xyz[dim * iv_nb_vert_internal];\n            // direction[1] = xyz[dim * iv1 + 1] - xyz[dim * iv_nb_vert_internal + 1];\n            // direction[2] = xyz[dim * iv1 + 2] - xyz[dim * iv_nb_vert_internal + 2];\n            direction[0] = xyz[dim * iv1] - centroid[0];\n            direction[1] = xyz[dim * iv1 + 1] - centroid[1];\n            direction[2] = xyz[dim * iv1 + 2] - centroid[2];\n            if ((direction[0] * normal[0] + direction[1] * normal[1] + direction[2] * normal[2]) < 0)\n            { //make outward facing\n                normal[0] = -normal[0];\n                normal[1] = -normal[1];\n                normal[2] = -normal[2];\n            }\n            magnitude = sqrt(normal[0] * normal[0] + normal[1] * normal[1] + normal[2] * normal[2]);\n            normal[0] = normal[0] / magnitude;\n            normal[1] = normal[1] / magnitude;\n            normal[2] = normal[2] / magnitude;\n            elem_normal[dim * icv] = normal[0];\n            elem_normal[dim * icv + 1] = normal[1];\n            elem_normal[dim * icv + 2] = normal[2];\n        }\n    }\n}\n\nvoid POINTS::calc_elem_normal_2D(vector<double> &elem_normal, vector<vector<int>> &vert_nb_cv, vector<vector<int>> &elem_vert, vector<bool> &elem_boundary_flag)\n{\n    int dim = 2;\n    int nv = (int)(xyz.size() / dim), ncv = elem_vert.size();\n    int iv_nb_cv_internal, iv0, iv1;\n    double normal[2], direction[2], magnitude, d_temp, centroid[2];\n    for (int icv = 0; icv < dim * ncv; icv++)\n    {\n        elem_normal.push_back(0.0);\n    }\n    for (int icv = 0; icv < ncv; icv++)\n    {\n        if (elem_boundary_flag[icv])\n        {\n            iv0 = elem_vert[icv][0];\n            iv1 = elem_vert[icv][1];\n            normal[0] = xyz[dim * iv1 + 1] - xyz[dim * iv0 + 1];\n            normal[1] = -(xyz[dim * iv1] - xyz[dim * iv0]);\n            iv_nb_cv_internal = -1;\n            for (int i1 = 0; i1 < vert_nb_cv[iv0].size(); i1++)\n            {\n                if (!elem_boundary_flag[vert_nb_cv[iv0][i1]])\n                { //is internal CV\n                    iv_nb_cv_internal = vert_nb_cv[iv0][i1];\n                    break;\n                }\n            }\n            if (iv_nb_cv_internal == -1)\n            {\n                cout << \"\\n\\nERROR from calc_elem_normal_2D boundary vertex iv0: \" << iv0 << \" does not have a neighboring internal element\\n\\n\";\n                cout << \"\\n\\nERROR from calc_elem_normal_2D boundary element icv: \" << icv << \" does not have a neighboring internal element\\n\\n\";\n                throw bad_exception();\n            }\n            // iv_nb_vert_internal = -1;\n            centroid[0] = 0.0;\n            centroid[1] = 0.0;\n            for (int i1 = 0; i1 < elem_vert[iv_nb_cv_internal].size(); i1++)\n            {\n                // if (!vert_boundary_flag[elem_vert[iv_nb_cv_internal][i1]])\n                // { //internal vertex found\n                //     iv_nb_vert_internal = elem_vert[iv_nb_cv_internal][i1];\n                //     break;\n                // }\n                centroid[0] += xyz[dim * elem_vert[iv_nb_cv_internal][i1]];\n                centroid[1] += xyz[dim * elem_vert[iv_nb_cv_internal][i1] + 1];\n            }\n            centroid[0] = centroid[0] / ((double)(elem_vert[iv_nb_cv_internal].size()));\n            centroid[1] = centroid[1] / ((double)(elem_vert[iv_nb_cv_internal].size()));\n            // if (iv_nb_vert_internal == -1)\n            // {\n            //     cout << \"\\ncalc_elem_normal_2D internal element iv_nb_cv_internal: \" << iv_nb_cv_internal << \" does not have a internal vertex\\n\\n\";\n            //     throw bad_exception();\n            // }\n            // direction[0] = xyz[dim * iv1] - xyz[dim * iv_nb_vert_internal];\n            // direction[1] = xyz[dim * iv1 + 1] - xyz[dim * iv_nb_vert_internal + 1];\n            direction[0] = xyz[dim * iv1] - centroid[0];\n            direction[1] = xyz[dim * iv1 + 1] - centroid[1];\n            if ((direction[0] * normal[0] + direction[1] * normal[1]) < 0)\n            { //make outward facing\n                normal[0] = -normal[0];\n                normal[1] = -normal[1];\n            }\n            magnitude = sqrt(normal[0] * normal[0] + normal[1] * normal[1]);\n            normal[0] = normal[0] / magnitude;\n            normal[1] = normal[1] / magnitude;\n            elem_normal[dim * icv] = normal[0];\n            elem_normal[dim * icv + 1] = normal[1];\n        }\n    }\n}\n\nvoid POINTS::read_elem_vert_complete_msh(PARAMETERS &parameters, vector<vector<int>> &elem_vert, vector<bool> &elem_boundary_flag)\n{                                   //read all non-trivial elements (do not read point, do not read line for 3D)\n    int dim = parameters.dimension; //problem dimension (2 or 3)\n    int itemp, cv_type, ncv_full, tag, count = 0;\n    double dtemp;\n    char temp[50];\n    vector<int> vec_temp;\n    FILE *file;\n    file = fopen(parameters.meshfile.c_str(), \"r\");\n    while (true)\n    {\n        fscanf(file, \"%s \", temp);\n        if (strcmp(temp, \"$Elements\") == 0)\n            break;\n    }\n    fscanf(file, \"%i \", &ncv_full);\n    for (int icv = 0; icv < ncv_full; icv++)\n    {\n        fscanf(file, \"%i \", &itemp);   //cv number\n        fscanf(file, \"%i \", &cv_type); //cv type\n        fscanf(file, \"%i \", &itemp);\n        fscanf(file, \"%i \", &itemp);\n        fscanf(file, \"%i \", &tag);     //element tag\n        if (cv_type == 15)             //corner vertex CV: do not read\n            fscanf(file, \"%*[^\\n]\\n\"); //skip reading remaining row\n        else if (cv_type == 1)\n        { //2 node line CV\n            if (dim == 2)\n            {\n                elem_boundary_flag.push_back(true);\n                elem_vert.push_back(vec_temp);\n                for (int i1 = 0; i1 < 2; i1++)\n                {\n                    fscanf(file, \"%i \", &itemp); //vertex number\n                    elem_vert[count].push_back(itemp - 1);\n                }\n                count++;\n            }\n            else\n            {\n                fscanf(file, \"%*[^\\n]\\n\"); //skip reading remaining row\n            }\n        }\n        else if (cv_type == 2)\n        { //3 node triangular CV\n            elem_vert.push_back(vec_temp);\n            for (int i1 = 0; i1 < 3; i1++)\n            {\n                fscanf(file, \"%i \", &itemp); //vertex number\n                elem_vert[count].push_back(itemp - 1);\n            }\n            if (dim == 2)\n                elem_boundary_flag.push_back(false);\n            else\n                elem_boundary_flag.push_back(true);\n            count++;\n        }\n        else if (cv_type == 4)\n        { //4 node tetrahedral CV\n            elem_vert.push_back(vec_temp);\n            for (int i1 = 0; i1 < 4; i1++)\n            {\n                fscanf(file, \"%i \", &itemp); //vertex number\n                elem_vert[count].push_back(itemp - 1);\n            }\n            elem_boundary_flag.push_back(false);\n            count++;\n        }\n        else\n        {\n            cout << \"\\n\\nERROR from read_elem_vert_complete_msh: Unable to identify CV type: \" << cv_type << \"\\n\\n\";\n            throw bad_exception();\n        }\n    }\n    fclose(file);\n    elem_vert_original = elem_vert;\n    nelem_original = elem_vert_original.size();\n}\n\nvoid POINTS::calc_vert_nb_cv(PARAMETERS &parameters, vector<vector<int>> &vert_nb_cv, vector<vector<int>> &elem_vert)\n{\n    clock_t start = clock();\n    vector<int> vec_temp;\n    int iv1, ncv = elem_vert.size();\n    for (int iv = 0; iv < nv; iv++)\n        vert_nb_cv.push_back(vec_temp);\n    for (int icv = 0; icv < ncv; icv++)\n    {\n        for (int i1 = 0; i1 < elem_vert[icv].size(); i1++)\n        {\n            iv1 = elem_vert[icv][i1];\n            vert_nb_cv[iv1].push_back(icv);\n        }\n    }\n    for (int iv = 0; iv < nv; iv++)\n        if (vert_nb_cv[iv].size() == 0)      //no nbcv\n            corner_edge_vertices[iv] = true; //hanging vertex: remove it later\n}\n\nvoid POINTS::read_points_xyz_msh(PARAMETERS &parameters)\n{\n    int dim = parameters.dimension; //problem dimension (2 or 3)\n    FILE *file;\n    int itemp;\n    double dtemp;\n    char temp[50];\n    file = fopen(parameters.meshfile.c_str(), \"r\");\n    while (true)\n    {\n        fscanf(file, \"%s \", temp);\n        if (strcmp(temp, \"$Nodes\") == 0)\n            break;\n    }\n    fscanf(file, \"%i \", &nv);\n    for (int iv = 0; iv < nv; iv++)\n    {\n        fscanf(file, \"%i \", &itemp);  //vertex number\n        fscanf(file, \"%lf \", &dtemp); //x co-ordinate\n        xyz.push_back(dtemp);\n        fscanf(file, \"%lf \", &dtemp); //y co-ordinate\n        xyz.push_back(dtemp);\n        fscanf(file, \"%lf \", &dtemp); //z co-ordinate\n        if (dim == 3)\n            xyz.push_back(dtemp); //for 2D problems, Z co-ordinate should be zero and should not be stored\n    }\n    xyz_original = xyz;\n    nv_original = nv;\n}\n\nvoid POINTS::read_points_flag_msh(PARAMETERS &parameters)\n{\n    vector<int>::iterator it;\n    for (int iv = 0; iv < nv; iv++)\n    { //initialize\n        boundary_flag.push_back(false);\n        corner_edge_vertices.push_back(false);\n    }\n    FILE *file;\n    int itemp, ncv, cv_type, tag_int, dim = parameters.dimension;\n    double dtemp;\n    char temp[50];\n    file = fopen(parameters.meshfile.c_str(), \"r\");\n    while (true)\n    {\n        fscanf(file, \"%s \", temp);\n        if (strcmp(temp, \"$Elements\") == 0)\n            break;\n    }\n    fscanf(file, \"%i \", &ncv);\n    if (dim == 2)\n    { //2D problem\n        for (int icv = 0; icv < ncv; icv++)\n        {\n            fscanf(file, \"%i \", &itemp);   //cv number\n            fscanf(file, \"%i \", &cv_type); //cv type\n            if (cv_type == 1)\n            { //important 2 node line CV on the boundary\n                fscanf(file, \"%i \", &itemp);\n                fscanf(file, \"%i \", &itemp);\n                fscanf(file, \"%i \", &tag_int); //element tag\n                for (int i = 0; i < 2; i++)\n                {                                    //has 2 vertices\n                    fscanf(file, \"%i \", &itemp);     //vertex number\n                    boundary_flag[itemp - 1] = true; //boundary vertex identified\n                }\n            }\n            else if (cv_type == 15)\n            { //corner vertex CV: log this vertex number to delete it later\n                fscanf(file, \"%i \", &itemp);\n                fscanf(file, \"%i \", &itemp);\n                fscanf(file, \"%i \", &tag_int); //element tag\n                fscanf(file, \"%i \", &itemp);   //vertex number\n                corner_edge_vertices[itemp - 1] = true;\n            }\n            else\n            {                              //not reading any other kind of CV\n                fscanf(file, \"%*[^\\n]\\n\"); //skip reading remaining row\n            }\n        }\n    }\n    else\n    { //3D problem\n        int cv_vert_num;\n        for (int icv = 0; icv < ncv; icv++)\n        {\n            fscanf(file, \"%i \", &itemp);   //cv number\n            fscanf(file, \"%i \", &cv_type); //cv type\n            if (cv_type == 2)\n            { //important 3 node triangle CV on the boundary\n                fscanf(file, \"%i \", &itemp);\n                fscanf(file, \"%i \", &itemp);\n                fscanf(file, \"%i \", &tag_int); //element tag\n                for (int i = 0; i < 3; i++)\n                {                                    //has 3 vertices\n                    fscanf(file, \"%i \", &itemp);     //vertex number\n                    boundary_flag[itemp - 1] = true; //boundary vertex identified\n                }\n            }\n            else if (cv_type == 3)\n            { //important 4 node quad CV on the boundary\n                fscanf(file, \"%i \", &itemp);\n                fscanf(file, \"%i \", &itemp);\n                fscanf(file, \"%i \", &tag_int); //element tag\n                for (int i = 0; i < 4; i++)\n                {                                    //has 4 vertices\n                    fscanf(file, \"%i \", &itemp);     //vertex number\n                    boundary_flag[itemp - 1] = true; //boundary vertex identified\n                }\n            }\n            else if (cv_type == 1)\n            { //2 node line CV: log these 2 vertex numbers to delete them later\n                fscanf(file, \"%i \", &itemp);\n                fscanf(file, \"%i \", &itemp);\n                fscanf(file, \"%i \", &tag_int); //element tag\n                fscanf(file, \"%i \", &itemp);   //first vertex number\n                corner_edge_vertices[itemp - 1] = true;\n                fscanf(file, \"%i \", &itemp); //second vertex number\n                corner_edge_vertices[itemp - 1] = true;\n            }\n            else\n            {                              //not reading any other kind of CV\n                fscanf(file, \"%*[^\\n]\\n\"); //skip reading remaining row\n            }\n        }\n    }\n}", "meta": {"hexsha": "a662b20ec8a19408033152afaa700048e362d80b", "size": 31864, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "header_files/points.cpp", "max_stars_repo_name": "shahaneshantanu/memphys", "max_stars_repo_head_hexsha": "1b95afa505808f302d2dd4689faa45bb6480e8d8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "header_files/points.cpp", "max_issues_repo_name": "shahaneshantanu/memphys", "max_issues_repo_head_hexsha": "1b95afa505808f302d2dd4689faa45bb6480e8d8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "header_files/points.cpp", "max_forks_repo_name": "shahaneshantanu/memphys", "max_forks_repo_head_hexsha": "1b95afa505808f302d2dd4689faa45bb6480e8d8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-07T00:32:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T00:32:37.000Z", "avg_line_length": 41.5979112272, "max_line_length": 209, "alphanum_fraction": 0.5291865428, "num_tokens": 8448, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.5926665999540697, "lm_q1q2_score": 0.4845490850149163}}
{"text": "#include <boost/test/unit_test.hpp>\n\n#include <iostream>\n\n#include <smtrat-cad/CAD.h>\n#include <smtrat-cad/projection/Projection.h>\n#include <smtrat-cad/projection/Projection_Debug.h>\n#include <smtrat-cad/lifting/Sample.h>\n#include <smtrat-modules/NewCADModule/NewCADSettings.h>\n\n\nusing namespace smtrat;\n\nBOOST_AUTO_TEST_SUITE(Test_Projection);\n\nBOOST_AUTO_TEST_CASE(Projection)\n{\n\tcarl::Variable a = carl::freshRealVariable(\"a\");\n\tcarl::Variable b = carl::freshRealVariable(\"b\");\n\tcarl::Variable c = carl::freshRealVariable(\"c\");\n\tcarl::Variable d = carl::freshRealVariable(\"d\");\n\tcarl::Variable e = carl::freshRealVariable(\"e\");\n\tcarl::Variable f = carl::freshRealVariable(\"f\");\n\tcarl::Variable g = carl::freshRealVariable(\"g\");\n\n\tPoly p1 = Poly(b)*b - Poly(10)*c - Poly(1);\n\tPoly p2 = Poly(b);\n\tPoly p3 = Poly(d) - Poly(c);\n\tPoly p4 = Poly(b);\n\tPoly p5 = Poly(f);\n\t//Poly p6 = Poly(b);\n\n\tcad::projection::Projection_Debug<cad::ProjectionType::McCallum> projection(\"projection.dot\", {e, g, c, d, f, b});\n\tprojection.doProjection({p1, p2, p3, p4, p5});\n}\n// \n// BOOST_AUTO_TEST_CASE(Test_CAD)\n// {\n// \tcarl::Variable x = carl::freshRealVariable(\"x\");\n// \tcarl::Variable y = carl::freshRealVariable(\"y\");\n// \tPoly p = Poly(x*y)+Poly(y)+Rational(1);\n// \tPoly q = Poly(y*y*y)+Poly(x*x*y)+Rational(2);\n// \t\n// \tCAD<NewCADSettingsSO> cad;\n// \tcad.reset({x,y});\n// \tcad.addConstraint(ConstraintT(p, carl::Relation::GEQ));\n// \tcad.addConstraint(ConstraintT(q, carl::Relation::LEQ));\n// \t\n// \tAssignment a;\n// \tstd::vector<FormulaSetT> mis;\n// \tcad.check(a, mis);\n// }\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "5f60bbda0917dcb0f4e3f72feed9045ead5a5383", "size": 1593, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tests/cad/Test_Projection.cpp", "max_stars_repo_name": "minemebarsha/smtrat", "max_stars_repo_head_hexsha": "eaada50cdf9bbfe4dd4f6a54776387484c37b0f2", "max_stars_repo_licenses": ["MIT"], "max_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/cad/Test_Projection.cpp", "max_issues_repo_name": "minemebarsha/smtrat", "max_issues_repo_head_hexsha": "eaada50cdf9bbfe4dd4f6a54776387484c37b0f2", "max_issues_repo_licenses": ["MIT"], "max_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/cad/Test_Projection.cpp", "max_forks_repo_name": "minemebarsha/smtrat", "max_forks_repo_head_hexsha": "eaada50cdf9bbfe4dd4f6a54776387484c37b0f2", "max_forks_repo_licenses": ["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.9636363636, "max_line_length": 115, "alphanum_fraction": 0.6842435656, "num_tokens": 509, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.817574471748733, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.48454908238056627}}
{"text": "/*!\r\n * \\file fitness_metric.cc\r\n *\r\n * \\author Ethan Adams\r\n * \\date\r\n *\r\n * This file contains the cpp version of FitnessMetric.py\r\n */\r\n\r\n#include \"BingoCpp/fitness_metric.h\"\r\n#include <iostream>\r\n#include <stdlib.h>\r\n#include <Eigen/Dense>\r\n#include <Eigen/Core>\r\n#include <unsupported/Eigen/NonLinearOptimization>\r\n\r\nnamespace bingo {\r\n  \r\nint LMFunctor::operator()(const Eigen::VectorXd &x, Eigen::VectorXd &fvec) {\r\n  agraphIndv.set_constants(x);\r\n  fvec = fit->evaluate_fitness_vector(agraphIndv, *train);\r\n  return 0;\r\n}\r\n\r\nint LMFunctor::df(const Eigen::VectorXd &x, Eigen::MatrixXd &fjac) {\r\n  double epsilon;\r\n  epsilon = 1e-5f;\r\n\r\n  for (int i = 0; i < x.size(); i++) {\r\n    Eigen::VectorXd xPlus(x);\r\n    xPlus(i) += epsilon;\r\n    Eigen::VectorXd xMinus(x);\r\n    xMinus(i) -= epsilon;\r\n    Eigen::VectorXd fvecPlus(values());\r\n    operator()(xPlus, fvecPlus);\r\n    Eigen::VectorXd fvecMinus(values());\r\n    operator()(xMinus, fvecMinus);\r\n    Eigen::VectorXd fvecDiff(values());\r\n    fvecDiff = (fvecPlus - fvecMinus) / (2.0 * epsilon);\r\n    fjac.block(0, i, values(), 1) = fvecDiff;\r\n  }\r\n\r\n  return 0;\r\n}\r\n\r\ndouble FitnessMetric::evaluate_fitness(AcyclicGraph &indv,\r\n                                       TrainingData &train) {\r\n  if (indv.needs_optimization()) {\r\n    optimize_constants(indv, train);\r\n  }\r\n\r\n  return ((evaluate_fitness_vector(indv, train)).abs()).mean();\r\n}\r\n\r\nvoid FitnessMetric::optimize_constants(AcyclicGraph &indv,\r\n                                       TrainingData &train) {\r\n  LMFunctor functor;\r\n  functor.train = &train;\r\n  functor.fit = this;\r\n  functor.m = functor.train->size();\r\n  // indv.input_constants();\r\n  functor.n = indv.count_constants();\r\n  functor.agraphIndv = indv;\r\n  Eigen::VectorXd vec = Eigen::VectorXd::Random(functor.n);\r\n  Eigen::LevenbergMarquardt<LMFunctor, double> lm(functor);\r\n  lm.minimize(vec);\r\n  indv.set_constants(vec);\r\n  indv.needs_opt = false;\r\n}\r\n\r\nEigen::ArrayXXd StandardRegression::evaluate_fitness_vector(AcyclicGraph &indv,\r\n    TrainingData &train) {\r\n  ExplicitTrainingData* temp = dynamic_cast<ExplicitTrainingData*>(&train);\r\n  return (indv.evaluate(temp->x)) - temp->y;\r\n}\r\n\r\nImplicitRegression::ImplicitRegression(int required_params, bool normalize_dot,\r\n                                       double acceptable_nans) {\r\n  this->required_params = required_params;\r\n  this->normalize_dot = normalize_dot;\r\n  acceptable_finite_fracion = 1.0 - acceptable_nans;\r\n}\r\n\r\nEigen::ArrayXXd ImplicitRegression::evaluate_fitness_vector(AcyclicGraph &indv,\r\n    TrainingData &train) {\r\n  ImplicitTrainingData* temp = dynamic_cast<ImplicitTrainingData*>(&train);\r\n  std::pair<Eigen::ArrayXXd, Eigen::ArrayXXd> deriv = indv.evaluate_deriv(\r\n        temp->x);\r\n  Eigen::ArrayXXd dot(deriv.second.rows(), deriv.second.cols());\r\n  double infinity = std::numeric_limits<double>::infinity();\r\n\r\n  if (normalize_dot) {\r\n    dot = (deriv.second / (deriv.second.square().rowwise().sum().sqrt())) *\r\n          (temp->dx_dt / (temp->dx_dt.square().rowwise().sum().sqrt()));\r\n\r\n  } else {\r\n    dot = deriv.second * temp->dx_dt;\r\n  }\r\n\r\n  if (required_params != 0) {\r\n    int n_params_used;\r\n\r\n    for (int i = 0; i < dot.rows(); ++i) {\r\n      n_params_used = 0;\r\n\r\n      for (int j = 0; j < dot.cols(); ++j) {\r\n        if (dot(i, j) > 0) {\r\n          ++n_params_used;\r\n        }\r\n      }\r\n\r\n      if (n_params_used >= required_params) {\r\n        return Eigen::ArrayXXd::Constant(deriv.second.rows(), 1, infinity);\r\n      }\r\n    }\r\n  }\r\n\r\n  Eigen::ArrayXXd fit(deriv.second.rows(), 1);\r\n  fit = dot.rowwise().sum() / dot.abs().rowwise().sum();\r\n  return fit;\r\n}\r\n} // namespace bingo ", "meta": {"hexsha": "f1359b7929becbe8a9e00eb6efec2c80db22645c", "size": 3653, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/fitness_metric.cpp", "max_stars_repo_name": "tylertownsend/bingocpp", "max_stars_repo_head_hexsha": "c8133fca89edaea30205b70eb5d2a8c91271cb80", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/fitness_metric.cpp", "max_issues_repo_name": "tylertownsend/bingocpp", "max_issues_repo_head_hexsha": "c8133fca89edaea30205b70eb5d2a8c91271cb80", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/fitness_metric.cpp", "max_forks_repo_name": "tylertownsend/bingocpp", "max_forks_repo_head_hexsha": "c8133fca89edaea30205b70eb5d2a8c91271cb80", "max_forks_repo_licenses": ["Apache-2.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.9426229508, "max_line_length": 80, "alphanum_fraction": 0.628798248, "num_tokens": 945, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744584140004, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.48454907447751566}}
{"text": "/* +------------------------------------------------------------------------+\n   |                     Mobile Robot Programming Toolkit (MRPT)            |\n   |                          http://www.mrpt.org/                          |\n   |                                                                        |\n   | Copyright (c) 2005-2018, Individual contributors, see AUTHORS file     |\n   | See: http://www.mrpt.org/Authors - All rights reserved.                |\n   | Released under BSD License. See details in http://www.mrpt.org/License |\n   +------------------------------------------------------------------------+ */\n\n#include \"vision-precomp.h\"  // Precompiled headers\n\n#include <mrpt/config.h>\n#include <mrpt/vision/utils.h>\n#include <mrpt/vision/pnp_algos.h>\n\n#include <iostream>\n\n#include <mrpt/math/types_math.h>  // Eigen must be included first via MRPT to enable the plugin system\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n#include <mrpt/otherlibs/do_opencv_includes.h>\n#if MRPT_HAS_OPENCV\n#include <opencv2/core/eigen.hpp>\n#endif\n\n#include \"dls.h\"\n#include \"epnp.h\"\n#include \"upnp.h\"\n#include \"p3p.h\"\n#include \"ppnp.h\"\n#include \"posit.h\"\n#include \"lhm.h\"\n#include \"rpnp.h\"\n\nbool mrpt::vision::pnp::CPnP::dls(\n\tconst Eigen::Ref<Eigen::MatrixXd> obj_pts,\n\tconst Eigen::Ref<Eigen::MatrixXd> img_pts, int n,\n\tconst Eigen::Ref<Eigen::MatrixXd> cam_intrinsic,\n\tEigen::Ref<Eigen::MatrixXd> pose_mat)\n{\n\ttry\n\t{\n#if MRPT_HAS_OPENCV == 1\n\n\t\t// Input 2d/3d correspondences and camera intrinsic matrix\n\t\tEigen::MatrixXd cam_in_eig, img_pts_eig, obj_pts_eig;\n\n\t\t// Check for consistency of input matrix dimensions\n\t\tif (img_pts.rows() != obj_pts.rows() ||\n\t\t\timg_pts.cols() != obj_pts.cols())\n\t\t\tthrow(2);\n\t\telse if (cam_intrinsic.rows() != 3 || cam_intrinsic.cols() != 3)\n\t\t\tthrow(3);\n\n\t\tif (obj_pts.rows() < obj_pts.cols())\n\t\t{\n\t\t\tcam_in_eig = cam_intrinsic.transpose();\n\t\t\timg_pts_eig = img_pts.transpose().block(0, 0, n, 2);\n\t\t\tobj_pts_eig = obj_pts.transpose();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcam_in_eig = cam_intrinsic;\n\t\t\timg_pts_eig = img_pts.block(0, 0, n, 2);\n\t\t\tobj_pts_eig = obj_pts;\n\t\t}\n\n\t\t// Output pose\n\t\tEigen::Matrix3d R_eig;\n\t\tEigen::MatrixXd t_eig;\n\n\t\t// Compute pose\n\t\tcv::Mat cam_in_cv(3, 3, CV_32F), img_pts_cv(2, n, CV_32F),\n\t\t\tobj_pts_cv(3, n, CV_32F), R_cv(3, 3, CV_32F), t_cv(3, 1, CV_32F);\n\n\t\tcv::eigen2cv(cam_in_eig, cam_in_cv);\n\t\tcv::eigen2cv(img_pts_eig, img_pts_cv);\n\t\tcv::eigen2cv(obj_pts_eig, obj_pts_cv);\n\n\t\tmrpt::vision::pnp::dls d(obj_pts_cv, img_pts_cv);\n\t\tbool ret = d.compute_pose(R_cv, t_cv);\n\n\t\tcv::cv2eigen(R_cv, R_eig);\n\t\tcv::cv2eigen(t_cv, t_eig);\n\n\t\tEigen::Quaterniond q(R_eig);\n\n\t\tpose_mat << t_eig, q.vec();\n\n\t\treturn ret;\n\n#else\n\t\tthrow(-1);\n#endif\n\t}\n\tcatch (int e)\n\t{\n\t\tswitch (e)\n\t\t{\n\t\t\tcase -1:\n\t\t\t\tstd::cout << \"Please install OpenCV for DLS-PnP\" << std::endl;\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tstd::cout << \"2d/3d correspondences mismatch\\n Check dimension \"\n\t\t\t\t\t\t\t \"of obj_pts and img_pts\"\n\t\t\t\t\t\t  << std::endl;\n\t\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\tstd::cout\n\t\t\t\t\t<< \"Camera intrinsic matrix does not have 3x3 dimensions \"\n\t\t\t\t\t<< std::endl;\n\t\t\t\tbreak;\n\t\t}\n\t\treturn false;\n\t}\n}\n\nbool mrpt::vision::pnp::CPnP::epnp(\n\tconst Eigen::Ref<Eigen::MatrixXd> obj_pts,\n\tconst Eigen::Ref<Eigen::MatrixXd> img_pts, int n,\n\tconst Eigen::Ref<Eigen::MatrixXd> cam_intrinsic,\n\tEigen::Ref<Eigen::MatrixXd> pose_mat)\n{\n\ttry\n\t{\n#if MRPT_HAS_OPENCV == 1\n\n\t\t// Input 2d/3d correspondences and camera intrinsic matrix\n\t\tEigen::MatrixXd cam_in_eig, img_pts_eig, obj_pts_eig;\n\n\t\t// Check for consistency of input matrix dimensions\n\t\tif (img_pts.rows() != obj_pts.rows() ||\n\t\t\timg_pts.cols() != obj_pts.cols())\n\t\t\tthrow(2);\n\t\telse if (cam_intrinsic.rows() != 3 || cam_intrinsic.cols() != 3)\n\t\t\tthrow(3);\n\n\t\tif (obj_pts.rows() < obj_pts.cols())\n\t\t{\n\t\t\tcam_in_eig = cam_intrinsic.transpose();\n\t\t\timg_pts_eig = img_pts.transpose().block(0, 0, n, 2);\n\t\t\tobj_pts_eig = obj_pts.transpose();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcam_in_eig = cam_intrinsic;\n\t\t\timg_pts_eig = img_pts.block(0, 0, n, 2);\n\t\t\tobj_pts_eig = obj_pts;\n\t\t}\n\n\t\t// Output pose\n\t\tEigen::Matrix3d R_eig;\n\t\tEigen::MatrixXd t_eig;\n\n\t\t// Compute pose\n\t\tcv::Mat cam_in_cv(3, 3, CV_32F), img_pts_cv(2, n, CV_32F),\n\t\t\tobj_pts_cv(3, n, CV_32F), R_cv, t_cv;\n\n\t\tcv::eigen2cv(cam_in_eig, cam_in_cv);\n\t\tcv::eigen2cv(img_pts_eig, img_pts_cv);\n\t\tcv::eigen2cv(obj_pts_eig, obj_pts_cv);\n\n\t\tmrpt::vision::pnp::epnp e(cam_in_cv, obj_pts_cv, img_pts_cv);\n\t\te.compute_pose(R_cv, t_cv);\n\n\t\tcv::cv2eigen(R_cv, R_eig);\n\t\tcv::cv2eigen(t_cv, t_eig);\n\n\t\tEigen::Quaterniond q(R_eig);\n\n\t\tpose_mat << t_eig, q.vec();\n\n\t\treturn true;\n\n#else\n\t\tthrow(-1);\n#endif\n\t}\n\tcatch (int e)\n\t{\n\t\tswitch (e)\n\t\t{\n\t\t\tcase -1:\n\t\t\t\tstd::cout << \"Please install OpenCV for DLS-PnP\" << std::endl;\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tstd::cout << \"2d/3d correspondences mismatch\\n Check dimension \"\n\t\t\t\t\t\t\t \"of obj_pts and img_pts\"\n\t\t\t\t\t\t  << std::endl;\n\t\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\tstd::cout\n\t\t\t\t\t<< \"Camera intrinsic matrix does not have 3x3 dimensions \"\n\t\t\t\t\t<< std::endl;\n\t\t\t\tbreak;\n\t\t}\n\t\treturn false;\n\t}\n}\n\nbool mrpt::vision::pnp::CPnP::upnp(\n\tconst Eigen::Ref<Eigen::MatrixXd> obj_pts,\n\tconst Eigen::Ref<Eigen::MatrixXd> img_pts, int n,\n\tconst Eigen::Ref<Eigen::MatrixXd> cam_intrinsic,\n\tEigen::Ref<Eigen::MatrixXd> pose_mat)\n{\n\ttry\n\t{\n#if MRPT_HAS_OPENCV == 1\n\n\t\t// Input 2d/3d correspondences and camera intrinsic matrix\n\t\tEigen::MatrixXd cam_in_eig, img_pts_eig, obj_pts_eig;\n\n\t\t// Check for consistency of input matrix dimensions\n\t\tif (img_pts.rows() != obj_pts.rows() ||\n\t\t\timg_pts.cols() != obj_pts.cols())\n\t\t\tthrow(2);\n\t\telse if (cam_intrinsic.rows() != 3 || cam_intrinsic.cols() != 3)\n\t\t\tthrow(3);\n\n\t\tif (obj_pts.rows() < obj_pts.cols())\n\t\t{\n\t\t\tcam_in_eig = cam_intrinsic.transpose();\n\t\t\timg_pts_eig = img_pts.transpose().block(0, 0, n, 2);\n\t\t\tobj_pts_eig = obj_pts.transpose();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcam_in_eig = cam_intrinsic;\n\t\t\timg_pts_eig = img_pts.block(0, 0, n, 2);\n\t\t\tobj_pts_eig = obj_pts;\n\t\t}\n\n\t\t// Output pose\n\t\tEigen::Matrix3d R_eig;\n\t\tEigen::MatrixXd t_eig;\n\n\t\t// Compute pose\n\t\tcv::Mat cam_in_cv(3, 3, CV_32F), img_pts_cv(2, n, CV_32F),\n\t\t\tobj_pts_cv(3, n, CV_32F), R_cv, t_cv;\n\n\t\tcv::eigen2cv(cam_in_eig, cam_in_cv);\n\t\tcv::eigen2cv(img_pts_eig, img_pts_cv);\n\t\tcv::eigen2cv(obj_pts_eig, obj_pts_cv);\n\n\t\tmrpt::vision::pnp::upnp u(cam_in_cv, obj_pts_cv, img_pts_cv);\n\t\tu.compute_pose(R_cv, t_cv);\n\n\t\tcv::cv2eigen(R_cv, R_eig);\n\t\tcv::cv2eigen(t_cv, t_eig);\n\n\t\tEigen::Quaterniond q(R_eig);\n\n\t\tpose_mat << t_eig, q.vec();\n\n\t\treturn true;\n#else\n\t\tthrow(-1);\n#endif\n\t}\n\tcatch (int e)\n\t{\n\t\tswitch (e)\n\t\t{\n\t\t\tcase -1:\n\t\t\t\tstd::cout << \"Please install OpenCV for DLS-PnP\" << std::endl;\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tstd::cout << \"2d/3d correspondences mismatch\\n Check dimension \"\n\t\t\t\t\t\t\t \"of obj_pts and img_pts\"\n\t\t\t\t\t\t  << std::endl;\n\t\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\tstd::cout\n\t\t\t\t\t<< \"Camera intrinsic matrix does not have 3x3 dimensions \"\n\t\t\t\t\t<< std::endl;\n\t\t\t\tbreak;\n\t\t}\n\t\treturn false;\n\t}\n}\n\nbool mrpt::vision::pnp::CPnP::p3p(\n\tconst Eigen::Ref<Eigen::MatrixXd> obj_pts,\n\tconst Eigen::Ref<Eigen::MatrixXd> img_pts, int n,\n\tconst Eigen::Ref<Eigen::MatrixXd> cam_intrinsic,\n\tEigen::Ref<Eigen::MatrixXd> pose_mat)\n{\n\ttry\n\t{\n\t\t// Input 2d/3d correspondences and camera intrinsic matrix\n\t\tEigen::MatrixXd cam_in_eig, img_pts_eig, obj_pts_eig;\n\n\t\t// Check for consistency of input matrix dimensions\n\t\tif (img_pts.rows() != obj_pts.rows() ||\n\t\t\timg_pts.cols() != obj_pts.cols())\n\t\t\tthrow(2);\n\t\telse if (cam_intrinsic.rows() != 3 || cam_intrinsic.cols() != 3)\n\t\t\tthrow(3);\n\n\t\tif (obj_pts.rows() < obj_pts.cols())\n\t\t{\n\t\t\tcam_in_eig = cam_intrinsic.transpose();\n\t\t\timg_pts_eig = img_pts.transpose().block(0, 0, n, 2);\n\t\t\tobj_pts_eig = obj_pts.transpose();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcam_in_eig = cam_intrinsic;\n\t\t\timg_pts_eig = img_pts.block(0, 0, n, 2);\n\t\t\tobj_pts_eig = obj_pts;\n\t\t}\n\n\t\t// Output pose\n\t\tEigen::Matrix3d R;\n\t\tEigen::Vector3d t;\n\n\t\t// Compute pose\n\t\tmrpt::vision::pnp::p3p p(cam_in_eig);\n\t\tbool ret = p.solve(R, t, obj_pts_eig, img_pts_eig);\n\n\t\tEigen::Quaterniond q(R);\n\n\t\tpose_mat << t, q.vec();\n\n\t\treturn ret;\n\t}\n\tcatch (int e)\n\t{\n\t\tswitch (e)\n\t\t{\n\t\t\tcase 2:\n\t\t\t\tstd::cout << \"2d/3d correspondences mismatch\\n Check dimension \"\n\t\t\t\t\t\t\t \"of obj_pts and img_pts\"\n\t\t\t\t\t\t  << std::endl;\n\t\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\tstd::cout\n\t\t\t\t\t<< \"Camera intrinsic matrix does not have 3x3 dimensions \"\n\t\t\t\t\t<< std::endl;\n\t\t\t\tbreak;\n\t\t}\n\t\treturn false;\n\t}\n}\n\nbool mrpt::vision::pnp::CPnP::rpnp(\n\tconst Eigen::Ref<Eigen::MatrixXd> obj_pts,\n\tconst Eigen::Ref<Eigen::MatrixXd> img_pts, int n,\n\tconst Eigen::Ref<Eigen::MatrixXd> cam_intrinsic,\n\tEigen::Ref<Eigen::MatrixXd> pose_mat)\n{\n\ttry\n\t{\n\t\t// Input 2d/3d correspondences and camera intrinsic matrix\n\t\tEigen::MatrixXd cam_in_eig, img_pts_eig, obj_pts_eig;\n\n\t\t// Check for consistency of input matrix dimensions\n\t\tif (img_pts.rows() != obj_pts.rows() ||\n\t\t\timg_pts.cols() != obj_pts.cols())\n\t\t\tthrow(2);\n\t\telse if (cam_intrinsic.rows() != 3 || cam_intrinsic.cols() != 3)\n\t\t\tthrow(3);\n\n\t\tif (obj_pts.rows() < obj_pts.cols())\n\t\t{\n\t\t\tcam_in_eig = cam_intrinsic.transpose();\n\t\t\timg_pts_eig = img_pts.transpose();\n\t\t\tobj_pts_eig = obj_pts.transpose();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcam_in_eig = cam_intrinsic;\n\t\t\timg_pts_eig = img_pts;\n\t\t\tobj_pts_eig = obj_pts;\n\t\t}\n\n\t\t// Output pose\n\t\tEigen::Matrix3d R;\n\t\tEigen::Vector3d t;\n\n\t\t// Compute pose\n\t\tmrpt::vision::pnp::rpnp r(obj_pts_eig, img_pts_eig, cam_in_eig, n);\n\t\tbool ret = r.compute_pose(R, t);\n\n\t\tEigen::Quaterniond q(R);\n\n\t\tpose_mat << t, q.vec();\n\n\t\treturn ret;\n\t}\n\tcatch (int e)\n\t{\n\t\tswitch (e)\n\t\t{\n\t\t\tcase 2:\n\t\t\t\tstd::cout << \"2d/3d correspondences mismatch\\n Check dimension \"\n\t\t\t\t\t\t\t \"of obj_pts and img_pts\"\n\t\t\t\t\t\t  << std::endl;\n\t\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\tstd::cout\n\t\t\t\t\t<< \"Camera intrinsic matrix does not have 3x3 dimensions \"\n\t\t\t\t\t<< std::endl;\n\t\t\t\tbreak;\n\t\t}\n\t\treturn false;\n\t}\n}\n\nbool mrpt::vision::pnp::CPnP::ppnp(\n\tconst Eigen::Ref<Eigen::MatrixXd> obj_pts,\n\tconst Eigen::Ref<Eigen::MatrixXd> img_pts, int n,\n\tconst Eigen::Ref<Eigen::MatrixXd> cam_intrinsic,\n\tEigen::Ref<Eigen::MatrixXd> pose_mat)\n{\n\ttry\n\t{\n\t\t// Input 2d/3d correspondences and camera intrinsic matrix\n\t\tEigen::MatrixXd cam_in_eig, img_pts_eig, obj_pts_eig;\n\n\t\t// Check for consistency of input matrix dimensions\n\t\tif (img_pts.rows() != obj_pts.rows() ||\n\t\t\timg_pts.cols() != obj_pts.cols())\n\t\t\tthrow(2);\n\t\telse if (cam_intrinsic.rows() != 3 || cam_intrinsic.cols() != 3)\n\t\t\tthrow(3);\n\n\t\tif (obj_pts.rows() < obj_pts.cols())\n\t\t{\n\t\t\tcam_in_eig = cam_intrinsic.transpose();\n\t\t\timg_pts_eig = img_pts.transpose();\n\t\t\tobj_pts_eig = obj_pts.transpose();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcam_in_eig = cam_intrinsic;\n\t\t\timg_pts_eig = img_pts;\n\t\t\tobj_pts_eig = obj_pts;\n\t\t}\n\n\t\t// Output pose\n\t\tEigen::Matrix3d R;\n\t\tEigen::Vector3d t;\n\n\t\t// Compute pose\n\t\tmrpt::vision::pnp::ppnp p(obj_pts_eig, img_pts_eig, cam_in_eig);\n\n\t\tbool ret = p.compute_pose(R, t, n);\n\n\t\tEigen::Quaterniond q(R);\n\n\t\tpose_mat << t, q.vec();\n\n\t\treturn ret;\n\t}\n\tcatch (int e)\n\t{\n\t\tswitch (e)\n\t\t{\n\t\t\tcase 2:\n\t\t\t\tstd::cout << \"2d/3d correspondences mismatch\\n Check dimension \"\n\t\t\t\t\t\t\t \"of obj_pts and img_pts\"\n\t\t\t\t\t\t  << std::endl;\n\t\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\tstd::cout\n\t\t\t\t\t<< \"Camera intrinsic matrix does not have 3x3 dimensions \"\n\t\t\t\t\t<< std::endl;\n\t\t\t\tbreak;\n\t\t}\n\t\treturn false;\n\t}\n}\n\nbool mrpt::vision::pnp::CPnP::posit(\n\tconst Eigen::Ref<Eigen::MatrixXd> obj_pts,\n\tconst Eigen::Ref<Eigen::MatrixXd> img_pts, int n,\n\tconst Eigen::Ref<Eigen::MatrixXd> cam_intrinsic,\n\tEigen::Ref<Eigen::MatrixXd> pose_mat)\n{\n\ttry\n\t{\n\t\t// Input 2d/3d correspondences and camera intrinsic matrix\n\t\tEigen::MatrixXd cam_in_eig, img_pts_eig, obj_pts_eig;\n\n\t\t// Check for consistency of input matrix dimensions\n\t\tif (img_pts.rows() != obj_pts.rows() ||\n\t\t\timg_pts.cols() != obj_pts.cols())\n\t\t\tthrow(2);\n\t\telse if (cam_intrinsic.rows() != 3 || cam_intrinsic.cols() != 3)\n\t\t\tthrow(3);\n\n\t\tif (obj_pts.rows() < obj_pts.cols())\n\t\t{\n\t\t\tcam_in_eig = cam_intrinsic.transpose();\n\t\t\timg_pts_eig = img_pts.transpose().block(0, 0, n, 2);\n\t\t\tobj_pts_eig = obj_pts.transpose();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcam_in_eig = cam_intrinsic;\n\t\t\timg_pts_eig = img_pts.block(0, 0, n, 2);\n\t\t\tobj_pts_eig = obj_pts;\n\t\t}\n\n\t\t// Output pose\n\t\tEigen::Matrix3d R;\n\t\tEigen::Vector3d t;\n\n\t\t// Compute pose\n\t\tmrpt::vision::pnp::posit p(obj_pts_eig, img_pts_eig, cam_in_eig, n);\n\n\t\tbool ret = p.compute_pose(R, t);\n\n\t\tEigen::Quaterniond q(R);\n\n\t\tpose_mat << t, q.vec();\n\n\t\treturn ret;\n\t}\n\tcatch (int e)\n\t{\n\t\tswitch (e)\n\t\t{\n\t\t\tcase 2:\n\t\t\t\tstd::cout << \"2d/3d correspondences mismatch\\n Check dimension \"\n\t\t\t\t\t\t\t \"of obj_pts and img_pts\"\n\t\t\t\t\t\t  << std::endl;\n\t\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\tstd::cout\n\t\t\t\t\t<< \"Camera intrinsic matrix does not have 3x3 dimensions \"\n\t\t\t\t\t<< std::endl;\n\t\t\t\tbreak;\n\t\t}\n\t\treturn false;\n\t}\n}\n\nbool mrpt::vision::pnp::CPnP::lhm(\n\tconst Eigen::Ref<Eigen::MatrixXd> obj_pts,\n\tconst Eigen::Ref<Eigen::MatrixXd> img_pts, int n,\n\tconst Eigen::Ref<Eigen::MatrixXd> cam_intrinsic,\n\tEigen::Ref<Eigen::MatrixXd> pose_mat)\n{\n\ttry\n\t{\n\t\t// Input 2d/3d correspondences and camera intrinsic matrix\n\t\tEigen::MatrixXd cam_in_eig, img_pts_eig, obj_pts_eig;\n\n\t\t// Check for consistency of input matrix dimensions\n\t\tif (img_pts.rows() != obj_pts.rows() ||\n\t\t\timg_pts.cols() != obj_pts.cols())\n\t\t\tthrow(2);\n\t\telse if (cam_intrinsic.rows() != 3 || cam_intrinsic.cols() != 3)\n\t\t\tthrow(3);\n\n\t\tif (obj_pts.rows() < obj_pts.cols())\n\t\t{\n\t\t\tcam_in_eig = cam_intrinsic.transpose();\n\t\t\timg_pts_eig = img_pts.transpose();\n\t\t\tobj_pts_eig = obj_pts.transpose();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcam_in_eig = cam_intrinsic;\n\t\t\timg_pts_eig = img_pts;\n\t\t\tobj_pts_eig = obj_pts;\n\t\t}\n\n\t\t// Output pose\n\t\tEigen::Matrix3d R;\n\t\tEigen::Vector3d t;\n\n\t\t// Compute pose\n\t\tmrpt::vision::pnp::lhm l(obj_pts_eig, img_pts_eig, cam_intrinsic, n);\n\n\t\tbool ret = l.compute_pose(R, t);\n\n\t\tEigen::Quaterniond q(R);\n\n\t\tpose_mat << t, q.vec();\n\n\t\treturn ret;\n\t}\n\tcatch (int e)\n\t{\n\t\tswitch (e)\n\t\t{\n\t\t\tcase 2:\n\t\t\t\tstd::cout << \"2d/3d correspondences mismatch\\n Check dimension \"\n\t\t\t\t\t\t\t \"of obj_pts and img_pts\"\n\t\t\t\t\t\t  << std::endl;\n\t\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\tstd::cout\n\t\t\t\t\t<< \"Camera intrinsic matrix does not have 3x3 dimensions \"\n\t\t\t\t\t<< std::endl;\n\t\t\t\tbreak;\n\t\t}\n\t\treturn false;\n\t}\n}\n", "meta": {"hexsha": "a982b453ad9666bda6528d9f642d03dc2df9e388", "size": 14068, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/vision/src/pnp/pnp_algos.cpp", "max_stars_repo_name": "mrliujie/mrpt-learning-code", "max_stars_repo_head_hexsha": "7b41a9501fc35c36580c93bc1499f5a36d26c216", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-04-21T08:51:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T10:47:52.000Z", "max_issues_repo_path": "libs/vision/src/pnp/pnp_algos.cpp", "max_issues_repo_name": "qifengl/mrpt", "max_issues_repo_head_hexsha": "979a458792273a86ec5ab105e0cd6c963c65ea73", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/vision/src/pnp/pnp_algos.cpp", "max_forks_repo_name": "qifengl/mrpt", "max_forks_repo_head_hexsha": "979a458792273a86ec5ab105e0cd6c963c65ea73", "max_forks_repo_licenses": ["BSD-3-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.2145214521, "max_line_length": 103, "alphanum_fraction": 0.634063122, "num_tokens": 4610, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744584140003, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4845490744775156}}
{"text": "#include <cstdlib>\n#include <cassert>\n#include <iostream>\n#include <fstream>\n#include <chrono>\n#include <functional>\n#include <vector>\n#include <string>\n#include <random>\n#include <boost/algorithm/string.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/cuthill_mckee_ordering.hpp>\n#include <boost/graph/properties.hpp>\n#include <boost/graph/bandwidth.hpp>\n#include <cxxopts.hpp>\n#include <xerus/algorithms/randomSVD.h>\n#include \"sptensor2tt.h\"\n\nusing namespace std;\nusing namespace xerus;\n\nvoid error(string message = \"Error!\") {\n    cerr << message << endl;\n    exit(1);\n}\n\nvoid run_test(const std::function<TTTensor(const Tensor&)> &f, const Tensor &x, ostream &sout, ostream &vout) {\n    auto c_begin = clock();\n    auto begin = chrono::high_resolution_clock::now();\n    auto tt = f(x);\n    auto c_end = clock();\n    auto end = chrono::high_resolution_clock::now();\n    auto xx = Tensor(tt);\n    auto eps = (x - xx).frob_norm() / x.frob_norm();\n    auto mse = pow((x - xx).frob_norm(), 2) / x.size;\n    auto walltime = chrono::duration_cast<chrono::milliseconds>(end - begin).count();\n    auto cputime = 1000.0 * (c_end-c_begin) / CLOCKS_PER_SEC;\n    \n    vout << \"walltime: \" <<  walltime << \"ms\"  << endl;\n    vout << \"cputime: \" << setprecision(6) << cputime << \"ms\" << endl;\n    sout << setprecision(6) << cputime << endl;\n    vout << \"eps: \" << setprecision(10) << eps << endl;\n    vout << \"mse: \" << setprecision(6) << mse << endl;\n    vout << \"ranks: \";\n    for (auto r : tt.ranks()) {\n        vout << r << \" \";\n    }\n    vout << endl;\n}\n\nint main(int argc, char *argv[]) {\n    cxxopts::Options options(\"test\", \"Test fast T2TT.\");\n    options.add_options()\n        (\"f,file\", \"Input file name\", cxxopts::value<string>())\n        (\"t,type\", \"Input file type: graph / image / tensor\", cxxopts::value<string>()->default_value(\"unspecific\"))\n        (\"U,undirected\", \"If input graph is undirected\")\n        (\"O,obeserved\", \"The obeservation ratio of the image\", cxxopts::value<double>()->default_value(\"0.01\"))\n        (\"R,random\", \"Use random generated n^d tesors as input instead\")\n        (\"n\", \"Parameter n of the tensor\", cxxopts::value<int>()->default_value(\"4\"))\n        (\"d\", \"Parameter d of the tensor\", cxxopts::value<int>()->default_value(\"10\"))\n        (\"l,n_list\", \"Use a list of n instead of n^d\", cxxopts::value<string>())\n        (\"N,nnz\", \"The number of nonzero elements of the random generated tensor\", cxxopts::value<int>()->default_value(\"500\"))\n        (\"F,fixed_rank\", \"Generate fixed-rank tesors\", cxxopts::value<int>()->default_value(\"0\"))\n        (\"s,sparsity\", \"The sparsity of generated cores\", cxxopts::value<double>()->default_value(\"0.02\"))\n        (\"p\", \"Parameter p of FastTT\", cxxopts::value<int>()->default_value(\"-1\"))\n        (\"r,max_rank\", \"Max ranks of the target tensor train\", cxxopts::value<int>()->default_value(\"0\"))\n        (\"e,epsilon\", \"Desired tolerated relative error\", cxxopts::value<double>()->default_value(\"1e-14\"))\n        (\"ttsvd\", \"Test TT-SVD\")\n        (\"rttsvd\", \"Test Randomized TT-SVD for given target rank\", cxxopts::value<int>()->default_value(\"10\"))\n        (\"nofasttt\", \"Do not test FastTT\")\n        (\"S,simple\", \"Output simple result\")\n        (\"save\", \"Save the tensor as a tsv file\", cxxopts::value<string>()->default_value(\"backup.tsv\"))\n        ;\n    const auto args = [&options, &argc, &argv]() {\n        try {\n            return options.parse(argc, argv);\n        }\n        catch (cxxopts::OptionParseException &) {\n            cout << options.help() << endl;\n            exit(1);\n        }\n    } ();\n    vector<size_t> n_list;\n    if (args.count(\"n_list\")) {\n        string n_list_str = args[\"n_list\"].as<string>();\n        vector<string> n_str_list;\n        boost::split(n_str_list, n_list_str, [](char c) { return c < '0' || c > '9'; });\n        for (string n_str: n_str_list) {\n            if (!n_str.empty()) {\n                n_list.push_back(stoi(n_str));\n            }\n        }\n    }\n    else {\n        int n = args[\"n\"].as<int>();\n        int d = args[\"d\"].as<int>();\n        if (!(d > 0 && n > 0)) {\n            error(\"n and d must be positive integers!\");\n        }\n        n_list = vector<size_t>(d, n);\n    }\n    int d = n_list.size();\n    int m = 1;\n    for (int n : n_list) {\n        m *= n;\n    }\n    Tensor x;\n    int N = 0;\n    string type = args[\"type\"].as<string>();\n    if (args.count(\"random\")) {\n        N = args[\"N\"].as<int>();\n        double sp = args[\"s\"].as<double>();\n        int r = args[\"fixed_rank\"].as<int>();\n        if (!(N >= 0)) {\n            error(\"N must be a positive integer!\");\n        }\n        if (!(sp > 0 && sp < 1)) {\n            error(\"sp must be a real number between 0 and 1!\");\n        }\n        if (!(r > 0)) {\n            x = Tensor::random(vector<size_t>(n_list), static_cast<size_t>(N));\n        }\n        else {\n            x = Tensor::random({n_list.front(), static_cast<size_t>(r)}, static_cast<size_t>(n_list.front() * r * sp));\n            for (int i = 1; i < d - 1; ++i) {\n                auto n = n_list.at(i);\n                auto y = Tensor::random({static_cast<size_t>(r), n, static_cast<size_t>(r)},\n                                        static_cast<size_t>(r * n * r * sp));\n                contract(x, x, y, 1);\n            }\n            auto y = Tensor::random({static_cast<size_t>(r), n_list.back()}, static_cast<size_t>(r * n_list.back() * sp));\n            contract(x, x, y, 1);\n        }\n        x.use_sparse_representation();\n        N = x.get_sparse_data().size();\n    }\n    else if (type == \"graph\") {\n        ifstream fin(args[\"file\"].as<string>());\n        if (!fin.is_open()) {\n            cerr << \"Cannot open file \" << args[\"file\"].as<string>() << endl;\n            exit(-1);\n        }\n        auto nn_list = n_list;\n        nn_list.insert(nn_list.end(), n_list.begin(), n_list.end());\n        x = Tensor(nn_list);\n        \n        vector<pair<size_t, size_t>> edges;\n        auto index = [n_list, d](int a, int b) {\n            vector<size_t> ret;\n            for (int i = 0; i < d; ++i) {\n                auto n = n_list[i];\n                ret.push_back(b % n);\n                ret.push_back(a % n);\n                b /= n;\n                a /= n;\n                reverse(ret.begin(), ret.end());\n            }\n            return ret;\n        };\n        for (string line; getline(fin, line); ) {\n            line.erase(line.begin(), std::find_if(line.begin(), line.end(), [](int ch) {\n                return !std::isspace(ch);\n            }));\n            line.erase(std::find_if(line.rbegin(), line.rend(), [](int ch) {\n                return !std::isspace(ch);\n            }).base(), line.end());\n            if (line.length() < 3 || line.front() == '#') {\n                continue;\n            }\n            istringstream line_in(line);\n            int a, b;\n            line_in >> a >> b;\n            if (a >= m || b >= m) {\n                continue;\n            }\n            edges.emplace_back(a, b);\n        }\n        if (!args.count(\"undirected\")) {\n            for (const auto e : edges) {\n                x[index(e.first, e.second)] = 1;\n            }\n        }\n        else {\n            using namespace boost;\n            typedef adjacency_list<vecS, vecS, undirectedS,\n                property<vertex_color_t, default_color_type,\n                property<vertex_degree_t, int> > > Graph;\n            typedef graph_traits<Graph>::vertex_descriptor Vertex;\n            typedef graph_traits<Graph>::vertices_size_type size_type;\n            Graph G(m);\n            for (size_t i = 0; i < edges.size(); ++i) {\n                add_edge(edges[i].first, edges[i].second, G);\n            }\n            std::vector<Vertex> inv_perm(num_vertices(G));\n            std::vector<size_type> perm(num_vertices(G));\n            cuthill_mckee_ordering(G, inv_perm.rbegin(), get(vertex_color, G), make_degree_map(G));\n            property_map<Graph, vertex_index_t>::type index_map = get(vertex_index, G);\n            for (size_type c = 0; c != inv_perm.size(); ++c) {\n                perm[index_map[inv_perm[c]]] = c;\n            }\n            for (const auto &e : edges) {\n                int a = perm[e.first];\n                int b = perm[e.second];\n                x[index(a, b)] = 1;\n                x[index(b, a)] = 1;\n            }\n        }\n        for (auto &n : n_list) {\n            n *= n;\n        }\n        m *= m;\n        x.reinterpret_dimensions(n_list);\n        x.use_sparse_representation();\n        N = x.get_sparse_data().size();\n    }\n    else if (type == \"image\") {\n        ifstream fin(args[\"file\"].as<string>());\n        if (!fin.is_open()) {\n            cerr << \"Cannot open file \" << args[\"file\"].as<string>() << endl;\n            exit(-1);\n        }\n        double obeserved = args[\"obeserved\"].as<double>();\n        int channels = 3;\n        int sz = m / channels;\n        if (!(obeserved > 0 && obeserved < 1)) {\n            error(\"The obeservation ratio must be a real number between 0 and 1!\");\n        }\n        vector<bool> mask(sz, false);\n        N = static_cast<int>(floor(static_cast<double>(sz) * obeserved));\n        fill_n(mask.begin(), N, true);\n        N *= channels;\n        random_device rd;\n        mt19937 gen(rd());\n        shuffle(mask.begin(), mask.end(), gen);\n        map<size_t, value_t> x_data;\n        for (int i = 0; i < m; ++i) {\n            int pixel;\n            fin >> pixel;\n            if (mask[i/channels]) {\n                x_data.try_emplace(i, pixel);\n            }\n        }\n        x = Tensor(n_list, Tensor::Representation::Sparse, Tensor::Initialisation::None);\n        x.get_unsanitized_sparse_data() = move(x_data);\n    }\n    else if (type == \"tensor\") {\n        ifstream fin(args[\"file\"].as<string>());\n        if (!fin.is_open()) {\n            cerr << \"Cannot open file \" << args[\"file\"].as<string>() << endl;\n            exit(-1);\n        }\n        map<size_t, value_t> x_data;\n        for (string line; getline(fin, line); ) {\n            istringstream line_in(line);\n            size_t position;\n            value_t value;\n            line_in >> position >> value;\n            x_data.try_emplace(position, value);\n        }\n        N = x_data.size();\n        x = Tensor(n_list, Tensor::Representation::Sparse, Tensor::Initialisation::None);\n        x.get_unsanitized_sparse_data() = move(x_data);\n    }\n    else {\n        error(\"You must specific a valid file type\");\n    }\n\n    if (args.count(\"save\")) {\n        ofstream fout(args[\"save\"].as<string>());\n        fout.precision(std::numeric_limits<value_t>::digits10 + 3);\n        for (auto [poistion, value] : x.get_sparse_data()) {\n            fout << poistion << \"\\t\" << value << endl;\n        }\n    }\n\n    int r = args[\"r\"].as<int>();\n    if (r < 0) {\n        error(\"Max ranks must be positive!\");\n    }\n    double eps = args[\"e\"].as<double>();\n    if (eps <= 0) {\n        error(\"Epsilon must be positive!\");\n    }\n\n    const bool simple = args.count(\"simple\");\n    ofstream nout(\"/dev/null\");\n    ostream &sout = simple ? cout : nout;\n    ostream &vout = !simple ? cout : nout;\n    \n    int vpos = args[\"p\"].as<int>();\n    string n_list_str = \"[\";\n    for (int n : n_list) {\n        n_list_str.append(to_string(n));\n        n_list_str.append(\", \");\n    }\n    n_list_str.erase(n_list_str.size() - 2);\n    n_list_str.push_back(']');\n    vout << \"n = \" << n_list_str << \", d = \" << d << \", N = \" << N << endl;\n    vout << \"sparse: \" << static_cast<double>(N) / m << endl;\n    \n    if (!args.count(\"nofasttt\")) {\n        vout << \"--------------------FastTT-------------------\" << endl;\n        run_test([vpos, r, eps](auto &&x) { return sptensor2tt(x, vpos, r, eps); }, x, sout, vout);\n    }\n\n    if (args.count(\"ttsvd\")) {\n        vout << \"--------------------TTSVD--------------------\" << endl;\n        auto y(x);\n        y.use_dense_representation();\n        auto rr = r == 0 ? numeric_limits<int>::max() : r;\n        run_test([rr, eps](auto &&x) { return TTTensor(x, eps, rr); }, y, sout, vout);\n    }\n    else {\n        sout << 0 << endl;\n    }\n    \n    if (args.count(\"rttsvd\")) {\n        vout << \"----------------Random TTSVD-----------------\" << endl;\n        auto y(x);\n        y.use_dense_representation();\n        int r = args[\"rttsvd\"].as<int>();\n        if (r < 0) {\n            error(\"Target ranks must be positive!\");\n        }\n        run_test([d, r](auto &&x) { return randomTTSVD(x, vector<size_t>(d-1, r), vector<size_t>(d-1, 10)); }, y, sout, vout);\n    }\n    else {\n        sout << 0 << endl;\n    }\n    \n    return 0;\n}\n\n", "meta": {"hexsha": "27342cf7cf0dd0d945ee2a40fb59f0f9bc972f55", "size": 12545, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test.cc", "max_stars_repo_name": "lljbash/FastTT", "max_stars_repo_head_hexsha": "943ed6756f630bbf2a7d18f297b65b98c2d891b8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2021-02-27T10:07:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-12T22:49:26.000Z", "max_issues_repo_path": "test.cc", "max_issues_repo_name": "lljbash/FastTT", "max_issues_repo_head_hexsha": "943ed6756f630bbf2a7d18f297b65b98c2d891b8", "max_issues_repo_licenses": ["MIT"], "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.cc", "max_forks_repo_name": "lljbash/FastTT", "max_forks_repo_head_hexsha": "943ed6756f630bbf2a7d18f297b65b98c2d891b8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-14T09:22:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-14T09:22:55.000Z", "avg_line_length": 37.5598802395, "max_line_length": 127, "alphanum_fraction": 0.5107214029, "num_tokens": 3275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744584140003, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4845490744775156}}
{"text": "/*\r\n [auto_generated]\r\n libs/numeric/odeint/test/euler_stepper.cpp\r\n\r\n [begin_description]\r\n This file tests explicit Euler stepper.\r\n [end_description]\r\n\r\n Copyright 2011 Mario Mulansky\r\n Copyright 2012 Karsten Ahnert\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#define BOOST_TEST_MODULE odeint_explicit_euler\r\n\r\n#include <boost/test/unit_test.hpp>\r\n\r\n#include <utility>\r\n#include <iostream>\r\n#include <vector>\r\n\r\n#include <boost/numeric/odeint/stepper/euler.hpp>\r\n#include <boost/numeric/odeint/algebra/range_algebra.hpp>\r\n\r\nusing namespace boost::unit_test;\r\nusing namespace boost::numeric::odeint;\r\n\r\n// test with own vector implementation\r\n\r\nclass my_vec : public std::vector< double > {\r\n\r\npublic:\r\n\r\n    my_vec() : std::vector< double >()\r\n        { }\r\n\r\n    my_vec( const my_vec &x ) : std::vector< double >( x )\r\n        { }\r\n\r\n\r\n    my_vec( size_t dim )\r\n        : std::vector< double >( dim )\r\n    { }\r\n\r\n};\r\n\r\nnamespace boost {\r\nnamespace numeric {\r\nnamespace odeint {\r\n\r\ntemplate<>\r\nstruct is_resizeable< my_vec >\r\n{\r\n    //struct type : public boost::true_type { };\r\n    typedef boost::true_type type;\r\n    const static bool value = type::value;\r\n};\r\n} } }\r\n\r\ntypedef double value_type;\r\n//typedef std::vector< value_type > state_type;\r\ntypedef my_vec state_type;\r\n\r\n/* use functors, because functions don't work with msvc 10, I guess this is a bug */\r\nstruct sys\r\n{\r\n    void operator()( const state_type &x , state_type &dxdt , const value_type t ) const\r\n    {\r\n        std::cout << \"sys start \" << dxdt.size() << std::endl;\r\n        dxdt[0] = x[0] + 2 * x[1];\r\n        dxdt[1] = x[1];\r\n        std::cout << \"sys done\" << std::endl;\r\n    }\r\n};\r\n\r\n\r\nBOOST_AUTO_TEST_SUITE( explicit_euler_test )\r\n\r\nBOOST_AUTO_TEST_CASE( test_euler )\r\n{\r\n    range_algebra algebra;\r\n    euler< state_type > stepper( algebra );\r\n    state_type x( 2 );\r\n    x[0] = 0.0; x[1] = 1.0;\r\n\r\n    std::cout << \"initialized\" << std::endl;\r\n\r\n    const value_type eps = 1E-12;\r\n    const value_type dt = 0.1;\r\n\r\n    stepper.do_step( sys() , x , 0.0 , dt );\r\n\r\n    using std::abs;\r\n\r\n    // compare with analytic solution of above system\r\n    BOOST_CHECK_MESSAGE( abs( x[0] - 2.0*1.0*dt ) < eps , x[0] - 2.0*1.0*dt );\r\n    BOOST_CHECK_MESSAGE( abs( x[1] - (1.0 + dt) ) < eps , x[1] - (1.0+dt) );\r\n\r\n}\r\n\r\nBOOST_AUTO_TEST_SUITE_END()\r\n", "meta": {"hexsha": "57436ed8d3a4d0aabf9a8a54f25f48acd39e8418", "size": 2439, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/numeric/odeint/test/euler_stepper.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": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/numeric/odeint/test/euler_stepper.cpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-04T18:00:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-04T18:00:00.000Z", "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/numeric/odeint/test/euler_stepper.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 23.0094339623, "max_line_length": 89, "alphanum_fraction": 0.6277162772, "num_tokens": 664, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.4844653804094943}}
{"text": "// Copyright Oleg Maximenko 2014.\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//\n// See http://github.com/svgpp/svgpp for library home page.\n\n#pragma once\n\n#include <boost/spirit/include/qi.hpp>\n#include <boost/spirit/include/phoenix.hpp>\n#include <svgpp/parser/detail/common.hpp>\n\nnamespace svgpp\n{ \n  \nnamespace qi = boost::spirit::qi;\n\ntemplate <class Iterator, class Coordinate = double>\nclass coordinate_pair_grammar: \n  public qi::grammar<Iterator, std::pair<Coordinate, Coordinate>(), qi::locals<Coordinate> >\n{\npublic:\n  coordinate_pair_grammar()\n    : coordinate_pair_grammar::base_type(rule_)\n  {\n    rule_ = \n         number [qi::_a = qi::_1]\n      >> (   comma_wsp\n           | &qi::lit('-')\n         )\n      >> number\n        [qi::_val = boost::phoenix::bind(&coordinate_pair_grammar::make_pair, qi::_a, qi::_1)];\n  }\n\nprivate:\n  typename coordinate_pair_grammar::start_type rule_;\n  detail::comma_wsp_rule_no_skip<Iterator> comma_wsp;\n  qi::real_parser<Coordinate, detail::real_policies_without_inf_nan<Coordinate> > number; // trailing dot is allowed, 'inf' and 'nan' - no\n\n  static std::pair<Coordinate, Coordinate> make_pair(Coordinate val1, Coordinate val2)\n  {\n    return std::pair<Coordinate, Coordinate>(val1, val2);\n  }\n};\n\n}", "meta": {"hexsha": "63594283057225f08001699ee2f213a4dade4799", "size": 1359, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/svgpp/parser/grammar/coordinate_pair.hpp", "max_stars_repo_name": "RichardCory/svgpp", "max_stars_repo_head_hexsha": "801e0142c61c88cf2898da157fb96dc04af1b8b0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 428.0, "max_stars_repo_stars_event_min_datetime": "2015-01-05T17:13:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:25:47.000Z", "max_issues_repo_path": "include/svgpp/parser/grammar/coordinate_pair.hpp", "max_issues_repo_name": "andrew2015/svgpp", "max_issues_repo_head_hexsha": "1d2f15ab5e1ae89e74604da08f65723f06c28b3b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 61.0, "max_issues_repo_issues_event_min_datetime": "2015-01-08T14:32:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-06T16:55:11.000Z", "max_forks_repo_path": "include/svgpp/parser/grammar/coordinate_pair.hpp", "max_forks_repo_name": "andrew2015/svgpp", "max_forks_repo_head_hexsha": "1d2f15ab5e1ae89e74604da08f65723f06c28b3b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 90.0, "max_forks_repo_forks_event_min_datetime": "2015-05-19T04:56:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:42:50.000Z", "avg_line_length": 28.914893617, "max_line_length": 138, "alphanum_fraction": 0.7012509198, "num_tokens": 358, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.6442250996557036, "lm_q1q2_score": 0.4844653752727476}}
{"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#include <boost/simd/pack.hpp>\n#include <boost/simd/function/pow2.hpp>\n#include <boost/simd/meta/cardinal_of.hpp>\n#include <boost/simd/logical.hpp>\n#include <simd_test.hpp>\n#include <boost/simd/detail/dispatch/meta/as_integer.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/minf.hpp>\n#include <boost/simd/constant/nan.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/mone.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/constant/mzero.hpp>\n#include <boost/simd/constant/four.hpp>\n\ntemplate <typename T, std::size_t N, typename Env>\nvoid test(Env& $)\n{\n  namespace bs = boost::simd;\n  using p_t = bs::pack<T, N>;\n\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n\n  T a1[N],  b[N];\n  bd::as_integer_t<T> a2 =  2;\n  for(std::size_t i = 0; i < N; ++i)\n  {\n     a1[i] = (i%2) ? T(i) : T(-i);\n     b[i] = bs::pow2(a1[i], a2);\n   }\n  p_t aa1(&a1[0], &a1[0]+N);\n  p_t bb(&b[0], &b[0]+N);//logical\n  STF_IEEE_EQUAL(bs::pow2(aa1, a2), bb);\n}\n\nSTF_CASE_TPL(\"Check pow2 on pack\" , (float))//STF_NUMERIC_TYPES)\n{\n  namespace bs = boost::simd;\n  using p_t = bs::pack<T>;\n  static const std::size_t N = bs::cardinal_of<p_t>::value;\n  test<T, N>($);\n  test<T, N/2>($);\n  test<T, N*2>($);\n}\n\n\n\n\nSTF_CASE_TPL (\" pow2\",  STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::pow2;\n  using p_t = bs::pack<T>;\n  using ip_t = bd::as_integer_t<p_t>;\n  using r_t = decltype(pow2(p_t(), ip_t()));\n\n  // return type conformity test\n  STF_TYPE_IS(r_t, p_t);\n\n  // specific values tests\n  STF_EQUAL(pow2(bs::Inf<p_t>(),  2), bs::Inf<r_t>());\n  STF_EQUAL(pow2(bs::Minf<p_t>(), 2), bs::Minf<r_t>());\n  STF_IEEE_EQUAL(pow2(bs::Nan<p_t>(),  2), bs::Nan<r_t>());\n  STF_EQUAL(pow2(bs::Inf<p_t>(),  p_t(2.5)), bs::Inf<r_t>());\n  STF_EQUAL(pow2(bs::Minf<p_t>(), p_t(2.5)), bs::Minf<r_t>());\n  STF_IEEE_EQUAL(pow2(bs::Nan<p_t>(),  p_t(2.5)), bs::Nan<r_t>());\n  STF_EQUAL(pow2(bs::Mone<p_t>(), 2), -bs::Four<r_t>());\n  STF_EQUAL(pow2(bs::One<p_t>(),  2), bs::Four<r_t>());\n  STF_EQUAL(pow2(bs::Zero<p_t>(), 2), bs::Zero<r_t>());\n  STF_EQUAL(pow2(bs::Mone<p_t>(), p_t(2.5)), -bs::Four<r_t>());\n  STF_EQUAL(pow2(bs::One<p_t>(),  p_t(2.5)), bs::Four<r_t>());\n  STF_EQUAL(pow2(bs::Zero<p_t>(), p_t(2.5)), bs::Zero<r_t>());\n}\n", "meta": {"hexsha": "40366c4aa5bc023679ee7617fecb5ee3646a58e4", "size": 2699, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/simd/pow2.cpp", "max_stars_repo_name": "nickporubsky/boost-simd-clone", "max_stars_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_stars_repo_licenses": ["BSL-1.0"], "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": "test/function/simd/pow2.cpp", "max_issues_repo_name": "nickporubsky/boost-simd-clone", "max_issues_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "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/function/simd/pow2.cpp", "max_forks_repo_name": "nickporubsky/boost-simd-clone", "max_forks_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_forks_repo_licenses": ["BSL-1.0"], "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": 31.3837209302, "max_line_length": 100, "alphanum_fraction": 0.5854020007, "num_tokens": 889, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597974, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.4844653701360008}}
{"text": "//  (C) Copyright John Maddock 2006.\r\n//  Use, modification and distribution are subject to the\r\n//  Boost Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n\r\n#ifndef BOOST_MATH_TOOLS_MINIMA_HPP\r\n#define BOOST_MATH_TOOLS_MINIMA_HPP\r\n\r\n#include <utility>\r\n#include <cmath>\r\n#include <boost/math/tools/precision.hpp>\r\n#include <boost/math/policies/policy.hpp>\r\n#include <boost/cstdint.hpp>\r\n\r\nnamespace boost{ namespace math{ namespace tools{\r\n\r\ntemplate <class F, class T>\r\nstd::pair<T, T> brent_find_minima(F f, T min, T max, int bits, boost::uintmax_t& max_iter)\r\n{\r\n   BOOST_MATH_STD_USING\r\n   bits = (std::min)(policies::digits<T, policies::policy<> >() / 2, bits);\r\n   T tolerance = static_cast<T>(ldexp(1.0, 1-bits));\r\n   T x;  // minima so far\r\n   T w;  // second best point\r\n   T v;  // previous value of w\r\n   T u;  // most recent evaluation point\r\n   T delta;  // The distance moved in the last step\r\n   T delta2; // The distance moved in the step before last\r\n   T fu, fv, fw, fx;  // function evaluations at u, v, w, x\r\n   T mid; // midpoint of min and max\r\n   T fract1, fract2;  // minimal relative movement in x\r\n\r\n   static const T golden = 0.3819660f;  // golden ratio, don't need too much precision here!\r\n\r\n   x = w = v = max;\r\n   fw = fv = fx = f(x);\r\n   delta2 = delta = 0;\r\n\r\n   uintmax_t count = max_iter;\r\n\r\n   do{\r\n      // get midpoint\r\n      mid = (min + max) / 2;\r\n      // work out if we're done already:\r\n      fract1 = tolerance * fabs(x) + tolerance / 4;\r\n      fract2 = 2 * fract1;\r\n      if(fabs(x - mid) <= (fract2 - (max - min) / 2))\r\n         break;\r\n\r\n      if(fabs(delta2) > fract1)\r\n      {\r\n         // try and construct a parabolic fit:\r\n         T r = (x - w) * (fx - fv);\r\n         T q = (x - v) * (fx - fw);\r\n         T p = (x - v) * q - (x - w) * r;\r\n         q = 2 * (q - r);\r\n         if(q > 0)\r\n            p = -p;\r\n         q = fabs(q);\r\n         T td = delta2;\r\n         delta2 = delta;\r\n         // determine whether a parabolic step is acceptible or not:\r\n         if((fabs(p) >= fabs(q * td / 2)) || (p <= q * (min - x)) || (p >= q * (max - x)))\r\n         {\r\n            // nope, try golden section instead\r\n            delta2 = (x >= mid) ? min - x : max - x;\r\n            delta = golden * delta2;\r\n         }\r\n         else\r\n         {\r\n            // whew, parabolic fit:\r\n            delta = p / q;\r\n            u = x + delta;\r\n            if(((u - min) < fract2) || ((max- u) < fract2))\r\n               delta = (mid - x) < 0 ? -fabs(fract1) : fabs(fract1);\r\n         }\r\n      }\r\n      else\r\n      {\r\n         // golden section:\r\n         delta2 = (x >= mid) ? min - x : max - x;\r\n         delta = golden * delta2;\r\n      }\r\n      // update current position:\r\n      u = (fabs(delta) >= fract1) ? x + delta : (delta > 0 ? x + fabs(fract1) : x - fabs(fract1));\r\n      fu = f(u);\r\n      if(fu <= fx)\r\n      {\r\n         // good new point is an improvement!\r\n         // update brackets:\r\n         if(u >= x)\r\n            min = x;\r\n         else\r\n            max = x;\r\n         // update control points:\r\n         v = w;\r\n         w = x;\r\n         x = u;\r\n         fv = fw;\r\n         fw = fx;\r\n         fx = fu;\r\n      }\r\n      else\r\n      {\r\n         // Oh dear, point u is worse than what we have already,\r\n         // even so it *must* be better than one of our endpoints:\r\n         if(u < x)\r\n            min = u;\r\n         else\r\n            max = u;\r\n         if((fu <= fw) || (w == x))\r\n         {\r\n            // however it is at least second best:\r\n            v = w;\r\n            w = u;\r\n            fv = fw;\r\n            fw = fu;\r\n         }\r\n         else if((fu <= fv) || (v == x) || (v == w))\r\n         {\r\n            // third best:\r\n            v = u;\r\n            fv = fu;\r\n         }\r\n      }\r\n\r\n   }while(--count);\r\n\r\n   max_iter -= count;\r\n\r\n   return std::make_pair(x, fx);\r\n}\r\n\r\ntemplate <class F, class T>\r\ninline std::pair<T, T> brent_find_minima(F f, T min, T max, int digits)\r\n{\r\n   boost::uintmax_t m = (std::numeric_limits<boost::uintmax_t>::max)();\r\n   return brent_find_minima(f, min, max, digits, m);\r\n}\r\n\r\n}}} // namespaces\r\n\r\n#endif\r\n\r\n\r\n\r\n", "meta": {"hexsha": "29b6a390eca799022a23b6968cb3477c873bfa1f", "size": 4199, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "external/windows/boost/include/boost/math/tools/minima.hpp", "max_stars_repo_name": "foxostro/CheeseTesseract", "max_stars_repo_head_hexsha": "737ebbd19cee8f5a196bf39a11ca793c561e56cb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-05-17T03:36:52.000Z", "max_stars_repo_stars_event_max_datetime": "2016-05-17T03:36:52.000Z", "max_issues_repo_path": "external/windows/boost/include/boost/math/tools/minima.hpp", "max_issues_repo_name": "foxostro/CheeseTesseract", "max_issues_repo_head_hexsha": "737ebbd19cee8f5a196bf39a11ca793c561e56cb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "external/windows/boost/include/boost/math/tools/minima.hpp", "max_forks_repo_name": "foxostro/CheeseTesseract", "max_forks_repo_head_hexsha": "737ebbd19cee8f5a196bf39a11ca793c561e56cb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.3716216216, "max_line_length": 99, "alphanum_fraction": 0.4767801858, "num_tokens": 1184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.4844653701360007}}
{"text": "#include <cmath>\r\n#include <complex>\r\n#include <cstring>\r\n#include <algorithm>\r\n#include <gsl/gsl_errno.h>\r\n#include <gsl/gsl_math.h>\r\n#include <gsl/gsl_odeiv.h>\r\n#include <Eigen/Core>\r\n\r\n#include \"Const.h\"\r\n#include \"SpeechSynthesizer.h\"\r\n\r\nusing namespace std;\r\nusing namespace Eigen;\r\n\r\n\r\nstatic const double NasalCavityArea[] = { 1, 2, 3, 4, 6, 8, 8, 7, 4, 2, 2 };\r\n\r\nSpeechSynthesizer::SpeechSynthesizer(int sampling, int freqResolution, vector<double> &tractArea, double dl) :\r\n\tm1\t(0.125),\r\n\tm2\t(0.025),\r\n\td1\t(0.25),\r\n\td2\t(0.05),\r\n\tlg\t(1.4),\r\n\tes\t(100),\r\n\teh\t(500),\r\n\tks1\t(8.0E+4),\r\n\tks2\t(8.0E+3),\r\n\tkh1\t(3 * ks1),\r\n\tkh2\t(3 * ks2),\r\n\tkc\t(2.5E+4),\r\n\tom1\t(sqrt(ks1 / m1)),\r\n\tAg0\t(0.05),\r\n\tp_s\t(7.85E+3),\r\n\tx1\t(0),\r\n\tx2\t(0),\r\n\tv1\t(0),\r\n\tv2\t(0),\r\n\tug_buf\t(freqResolution),\r\n\ttoVelum\t\t(8.0),\r\n    toSinus\t\t(7.0),\r\n    toConstr\t(3.0),\r\n    R_sin\t\t(1.0),\r\n    L_sin\t\t(5.94E-3),\r\n    C_sin\t\t(15.8E-6),\r\n\toral\t\t(4.0, dl, tractArea),\r\n\tnasal\t\t(72.0, 1.0, NasalCavityArea, 11),\r\n\tr_N(0.2),\r\n\tr_vib(3.0),\r\n\tdt\t(1.0 / sampling),\r\n\tdf\t(1.0 / (freqResolution * dt)),\r\n\tN\t(freqResolution),\r\n\tcalcSpan(0.020),\r\n\tt(0)\r\n{\r\n\tz_in_curr = new double[N];\r\n\th_out_curr = new double[N];\r\n\tz_in_prev = new double[N];\r\n\th_out_prev = new double[N];\r\n\r\n\tfor (int i = 0; i < N; i++)\r\n\t\tug_buf.push_front(0);\r\n\r\n\tlastCalcTime = -2 * calcSpan;\r\n\tCalcTract();\r\n\tmemcpy(z_in_prev, z_in_curr, N);\r\n\tmemcpy(h_out_prev, h_out_curr, N);\r\n\tlastCalcSpan = calcSpan;\r\n\r\n\tsystem.function = Differentiate;\r\n\tsystem.jacobian = nullptr;\r\n\tsystem.dimension = 5;\r\n\tsystem.params = this;\r\n\tstep = gsl_odeiv_step_alloc(gsl_odeiv_step_rk4, system.dimension);\r\n}\r\n\r\nSpeechSynthesizer::~SpeechSynthesizer(void)\r\n{\r\n\tdelete [] z_in_curr;\r\n\tdelete [] h_out_curr;\r\n\tdelete [] z_in_prev;\r\n\tdelete [] h_out_prev;\r\n}\r\n\r\nint SpeechSynthesizer::Differentiate(double t, const double y[], double dydt[], void *params)\r\n{\r\n\tSpeechSynthesizer *s = (SpeechSynthesizer*) params;\r\n\tconst double h_min = s->h_min;\r\n\tconst double x1 = y[0];\r\n\tconst double v1 = y[1];\r\n\tconst double x2 = y[2];\r\n\tconst double v2 = y[3];\r\n\tconst double ug = y[4];\r\n\tdouble *dx1 = &dydt[0];\r\n\tdouble *dv1 = &dydt[1];\r\n\tdouble *dx2 = &dydt[2];\r\n\tdouble *dv2 = &dydt[3];\r\n\tdouble *dug = &dydt[4];\r\n\r\n\tconst int n = s->N;\r\n\tdouble *z_in = new double[n];\r\n\tdouble V = 0;\r\n\r\n\ts->GetTractImpedance(z_in, t);\r\n\tfor (int i = 0; i < n; i++)\r\n\t{\r\n\t\tV += z_in[i] * s->ug_buf[i];\r\n\t}\r\n\r\n\tdouble xc = -s->Ag0 / (2 * s->lg);\r\n\tdouble h1 = x1 - xc;\r\n\tdouble h2 = x2 - xc;\r\n\tif (h1 > 0 && h1 < h_min) h1 = h_min;\r\n\tif (h2 > 0 && h2 < h_min) h2 = h_min;\r\n\tdouble Rv = 1.5 * Const::mu / s->lg;\r\n\tdouble Rv1 = Rv * s->d1 / gsl_pow_3(h1);\r\n\tdouble Rv2 = Rv * s->d2 / gsl_pow_3(h2);\r\n\tdouble Rbb = Const::rho / (8 * gsl_pow_2(s->lg));\r\n\tdouble Rc = Rbb * 1.37 / gsl_pow_2(h1) * (ug);\r\n\tdouble R12 = Rbb * (1 / gsl_pow_2(h2) - 1 / gsl_pow_2(h1)) * (ug);\r\n\tdouble Re = -Rbb * 0.5 / gsl_pow_2(h2) * (ug);\r\n\tdouble Lg = Const::rho / (2 * s->lg);\r\n\tdouble Lg1 = Lg * s->d1 / h1;\r\n\tdouble Lg2 = Lg * s->d2 / h2;\r\n\r\n\t*dug = (h1 <= 0 || h2 <= 0\r\n\t\t\t? -ug / (t - s->t)\r\n\t\t\t: (s->p_s - V - (Rc + Rv1 + R12 + Rv2 + Re) * ug) / (Lg1 + Lg2));\r\n\r\n\tdouble P1, P2;\r\n\tif (h1 <= 0)\r\n\t{\r\n\t\tP1 = s->p_s;\r\n\t\tP2 = 0;\r\n\t}\r\n\telse if (h2 <= 0)\r\n\t{\r\n\t\tP1 = s->p_s;\r\n\t\tP2 = P1;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tP1 = s->p_s - (Rc + Rv1 / 2) * ug - Lg1 / 2 * *dug;\r\n\t\tP2 = P1 - (R12 + (Rv1 + Rv2) / 2) * ug - (Lg1 + Lg2) / 2 * *dug;\r\n\t}\r\n\r\n\tdouble s1 = s->ks1 * x1 * (1 + s->es * gsl_pow_2(x1));\r\n\tif (h1 <= 0) s1 += s->kh1 * h1 * (1 + s->eh * gsl_pow_2(h1));\r\n\tdouble s2 = s->ks2 * x2 * (1 + s->es * gsl_pow_2(x2));\r\n\tif (h2 <= 0) s2 += s->kh2 * h2 * (1 + s->eh * gsl_pow_2(h2));\r\n\tdouble r1 = 2 * (h1 > 0 ? 0.2 : 1.1) * sqrt(s->ks1 * s->m1);\r\n\tdouble r2 = 2 * (h2 > 0 ? 0.6 : 1.9) * sqrt(s->ks2 * s->m2);\r\n\t\r\n\t*dv1 = (-r1 * v1 - s1 - s->kc * (x1 - x2) + P1 * s->lg * s->d1) / s->m1;\r\n\t*dv2 = (-r2 * v2 - s2 - s->kc * (x2 - x1) + P2 * s->lg * s->d2) / s->m2;\r\n\r\n\t*dx1 = v1;\r\n\t*dx2 = v2;\r\n\r\n\tdelete [] z_in;\r\n\r\n\treturn GSL_SUCCESS;\r\n}\r\n\r\ndouble SpeechSynthesizer::Step(void)\r\n{\r\n\tCalcTract();\r\n\r\n\tdouble y[5] = { x1, v1, x2, v2, ug_buf.front() };\r\n\tdouble yerr[5];\r\n\r\n\tgsl_odeiv_step_apply(step, t, dt, y, yerr, t == 0 ? nullptr : dydt, dydt, &system);\r\n\tt += dt;\r\n\r\n\tif (yerr[0] > 1E-3)\r\n\t\tstd::cerr << \"large error\" << std::endl;\r\n\r\n\tx1 = y[0];\r\n\tv1 = y[1];\r\n\tx2 = y[2];\r\n\tv2 = y[3];\r\n\tug_buf.pop_back();\r\n\tug_buf.push_front(y[4]);\r\n\r\n\tdouble *h_out = new double[N];\r\n\tdouble p = 0;\r\n\r\n\tGetOutputImpedance(h_out, t);\r\n\tfor (int i = 0; i < N; i++)\r\n\t\tp += h_out[i] * ug_buf[i];\r\n\r\n\tdelete [] h_out;\r\n\r\n\tstd::printf(\"%f %.3e %.3e %.3e %.3e %.3e %.3e\\n\", t, x1 * 2 * lg + Ag0, v1, x2 * 2 * lg + Ag0, v2, ug_buf.front(), p);\r\n\r\n\treturn p;\r\n}\r\n\r\ndouble SpeechSynthesizer::GetTime(void)\r\n{\r\n\treturn t;\r\n}\r\n\r\nvoid SpeechSynthesizer::CalcTract(void)\r\n{\r\n\tdouble dur = t - lastCalcTime;\r\n\r\n\tif (dur < calcSpan)\r\n\t\treturn;\r\n\r\n\tlastCalcSpan = dur;\r\n\tlastCalcTime = t;\r\n\r\n#ifdef _MSC_VER\r\n\tcomplex<double> *Z_in = new complex<double>[N - 1];\r\n\tcomplex<double> *H_out = new complex<double>[N - 1];\r\n#else\r\n\tcomplex<double> Z_in[N - 1];\r\n\tcomplex<double> H_out[N - 1];\r\n#endif\r\n\r\n\tint i_v = (int) (toVelum / oral.GetElemLength());\r\n\tint i_c = i_v + (int) (toConstr / oral.GetElemLength());\r\n\tint i_s = (int) (toSinus / nasal.GetElemLength());\r\n\r\n    for (int i = 1; i < N; i++)\r\n    {\r\n\t\tdouble f = i * df;\r\n        double omg = 2 * Const::pi * f;\r\n        complex<double> s(0, omg);\r\n\t\t\r\n\t\tMatrix2cd K_G = oral.ChainMatrix(f, 0, i_v);\r\n        Matrix2cd K_C = oral.ChainMatrix(f, i_v, i_c);\r\n        Matrix2cd K_L = oral.ChainMatrix(f, i_c);\r\n\t\tdouble r_L = sqrt(oral.GetEndArea() / Const::pi);\r\n\t\tdouble ka = omg / Const::c * r_L;\r\n\t\tcomplex<double> Z_L = Const::rho * Const::c / oral.GetEndArea() * complex<double>(ka * ka / 2, 8.0 * ka / (3.0 * Const::pi));\r\n\r\n        complex<double> Z_sin = R_sin + L_sin * s + 1.0 / (C_sin * s);\r\n        Matrix2cd K_N1 = nasal.ChainMatrix(f, 0, i_s);\r\n        Matrix2cd K_N2 = nasal.ChainMatrix(f, i_s);\r\n        Matrix2cd K_sin;\r\n\t\tK_sin << 1, 0, -1.0 / Z_sin, 1;\r\n        Matrix2cd K_N = K_N2 * K_sin * K_N1;\r\n        complex<double> Z_N = 4 * Const::pi * gsl_pow_2(r_N) * Const::rho * Const::c / (gsl_pow_2(Const::c) + gsl_pow_2(r_N * omg)) * (gsl_pow_2(r_N * omg) + Const::c * r_N * s);\r\n\r\n        Matrix2cd K_oral = K_L * K_C;\r\n\t\tcomplex<double> Z_VN = (K_N(1, 1) * Z_N - K_N(0, 1)) / (K_N(0, 0) - K_N(1, 0) * Z_N);\r\n\r\n\t\tcomplex<double> Z_VT = (K_oral(1, 1) * Z_L - K_oral(0, 1)) / (K_oral(0, 0) - K_oral(1, 0) * Z_L);\r\n        Matrix2cd K_cN, K_cT;\r\n\t\tK_cN << 1, 0, -1.0 / Z_VN, 1;\r\n        K_cT << 1, 0, -1.0 / Z_VT, 1;\r\n\r\n        Matrix2cd K_fric = K_C * K_cN * K_G;\r\n        Matrix2cd K_tract = K_L * K_fric;\r\n        Matrix2cd K_nasal = K_N * K_cT * K_G;\r\n\r\n\t\t//double Z_0 = Const::rho * Const::c / oral.GetEndArea();\r\n        Z_in[i - 1] = (K_tract(1, 1) * Z_L - K_tract(0, 1)) / (K_tract(0, 0) - K_tract(1, 0) * Z_L);\r\n\r\n\t\tcomplex<double> H_vib = oral.GetStartArea() / Const::c * s * r_vib / (Const::c + s * r_vib) * Z_in[i - 1] * oral.GetBeta(f);\r\n\r\n        H_out[i - 1] = Z_L / (K_tract(0, 0) - K_tract(1, 0) * Z_L)\r\n            + Z_N / (K_nasal(0, 0) - K_nasal(1, 0) * Z_N)\r\n            + H_vib;\r\n    }\r\n\r\n\tswap(z_in_curr, z_in_prev);\r\n\tswap(h_out_curr, h_out_prev);\r\n\tCalcResponse(z_in_curr, Z_in);\r\n\tCalcResponse(h_out_curr, H_out);\r\n\r\n#ifdef _MSC_VER\r\n\tdelete [] Z_in;\r\n\tdelete [] H_out;\r\n#endif\r\n}\r\n\r\ninline static complex<double> Exp(const complex<double> z)\r\n{\r\n    double re = real(z);\r\n    double im = imag(z);\r\n    return exp(re) * complex<double>(cos(im), sin(im));\r\n}\r\n\r\nvoid SpeechSynthesizer::CalcResponse(double res[], const complex<double> spec[])\r\n{\r\n    for (int i = 0; i < N; i++)\r\n    {\r\n\t\tdouble t = i * dt;\r\n\t\tdouble c_t = 0.54 - 0.46 * cos(Const::pi * (1 + (double)i / N));\r\n\t\tcomplex<double> r(0, 0);\r\n\r\n\t\tfor (int j = 1; j < N; j++)\r\n\t\t{\r\n\t        double omg = 2 * Const::pi * j * df;\r\n\t\t\tcomplex<double> s(0, omg);\r\n\t\t\tdouble c_f = 1 / (1 + exp(4 * (8.0 * j / N - 5)));\t// designed to decrease around 5/8\r\n\r\n\t\t\tr += c_t * c_f / (2 * Const::pi * N) * spec[j - 1] * Exp(s * t);\r\n\t\t}\r\n\r\n\t\tres[i] = real(r);\r\n\t}\r\n}\r\n\r\nvoid SpeechSynthesizer::GetTractImpedance(double res[], double t)\r\n{\r\n\tdouble dur = t - lastCalcTime;\r\n\r\n\tfor (int i = 0; i < N; i++)\r\n\t{\r\n\t\tres[i] = z_in_curr[i] + (z_in_curr[i] - z_in_prev[i]) / calcSpan * dur;\r\n\t}\r\n}\r\nvoid SpeechSynthesizer::GetOutputImpedance(double res[], double t)\r\n{\r\n\tdouble dur = t - lastCalcTime;\r\n\r\n\tfor (int i = 0; i < N; i++)\r\n\t{\r\n\t\tres[i] = h_out_curr[i] + (h_out_curr[i] - h_out_prev[i]) / calcSpan * dur;\r\n\t}\r\n}\r\n", "meta": {"hexsha": "ad726dd15004a2db738de11ae84f5071344cf885", "size": 8582, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "SpeechSynthesizer.cxx", "max_stars_repo_name": "kinoh/VoiceSynthesis", "max_stars_repo_head_hexsha": "4f9ce82c59419b0a54c38607521fa30fe3ad22af", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2015-01-01T16:36:25.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-27T04:58:04.000Z", "max_issues_repo_path": "SpeechSynthesizer.cxx", "max_issues_repo_name": "kinoh/VoiceSynthesis", "max_issues_repo_head_hexsha": "4f9ce82c59419b0a54c38607521fa30fe3ad22af", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SpeechSynthesizer.cxx", "max_forks_repo_name": "kinoh/VoiceSynthesis", "max_forks_repo_head_hexsha": "4f9ce82c59419b0a54c38607521fa30fe3ad22af", "max_forks_repo_licenses": ["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.3251533742, "max_line_length": 179, "alphanum_fraction": 0.5474248427, "num_tokens": 3381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851154320682, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.48442761671448503}}
{"text": "#include \"MyModel_Pixels.h\"\n#include \"DNest4/code/DNest4.h\"\n#include <stdexcept>\n#include <armadillo>\n\nnamespace Obscurity\n{\n\n// CONSTRUCTOR AND MEMBER FUNCTIONS\nMyModel_Pixels::MyModel_Pixels()\n:n(ni, nj)\n,obscurer_map(ni, nj)\n,convolved(ni, nj)\n{\n\n}\n\nvoid MyModel_Pixels::from_prior(DNest4::RNG& rng)\n{\n    for(size_t j=0; j<nj; ++j)\n        for(size_t i=0; i<ni; ++i)\n            n(i, j) = rng.randn();\n\n    sd = rng.rand();\n\n    DNest4::Cauchy c1(0.0, 1.0);\n    x0 = -std::abs(c1.generate(rng));\n\n    DNest4::Cauchy c2(0.0, 0.1*data.get_t_range());\n    timescale = std::abs(c2.generate(rng));\n\n    calculate_obscurer_map();\n}\n\ndouble MyModel_Pixels::calculate_total_flux(double time) const\n{\n    double speed = 1.0/timescale;\n    double offset = x0 + speed*time;\n\n    int j = (int)floor((offset - (x_min + 0.5*dx))/dx);\n    return convolved(ni/2, j%nj);\n}\n\ndouble MyModel_Pixels::perturb(DNest4::RNG& rng)\n{\n    double logH = 0.0;\n\n    if(rng.rand() <= 0.7)\n    {\n        // Perturb the ns\n        int which_i, which_j;\n        int reps = 1;\n        if(rng.rand() <= 0.5)\n            reps = (int)pow(10.0, 3*rng.rand());\n\n        if(reps == 1)\n        {\n            which_i = rng.rand_int(ni);\n            which_j = rng.rand_int(nj);\n\n            logH -= -0.5*pow(n(which_i, which_j), 2);\n            n(which_i, which_j) += rng.randh();\n            logH += -0.5*pow(n(which_i, which_j), 2);\n        }\n        else\n        {\n            for(int i=0; i<reps; ++i)\n            {\n                which_i = rng.rand_int(ni);\n                which_j = rng.rand_int(nj);\n                n(which_i, which_j) = rng.randn();\n            }\n        }\n    }\n    else\n    {\n        int which = rng.rand_int(3);\n\n        if(which == 0)\n        {\n            sd += rng.randh();\n            DNest4::wrap(sd, 0.0, 1.0);\n            calculate_obscurer_map();\n        }\n        else if(which == 1)\n        {\n            DNest4::Cauchy c(0.0, 1.0);\n            logH += c.perturb(x0, rng);\n            x0 = -std::abs(x0);\n        }\n        else\n        {\n            DNest4::Cauchy c(0.0, 0.1*data.get_t_range());\n            logH += c.perturb(timescale, rng);\n            timescale = std::abs(timescale);\n        }\n    }\n\n\n    return logH;\n}\n\ndouble MyModel_Pixels::log_likelihood() const\n{\n    double logL = 0.0;\n\n    const auto& t = data.get_t();\n    const auto& y = data.get_y();\n    const auto& sig = data.get_sig();\n\n    double model_prediction;\n    for(size_t i=0; i<t.size(); ++i)\n    {\n        model_prediction = calculate_total_flux(t[i]);\n        logL += -0.5*log(2*M_PI) - log(sig[i])\n                    - 0.5*pow((y[i] - model_prediction)/sig[i], 2);\n    }\n\n    return logL;\n}\n\nvoid MyModel_Pixels::calculate_obscurer_map()\n{\n    // Obscurer image\n    for(size_t j=0; j<nj; ++j)\n        for(size_t i=0; i<ni; ++i)\n            obscurer_map(i, j) = exp(-sd*n(i, j));\n\n    // FFT of obscurer_map\n    arma::cx_mat A = arma::fft2(obscurer_map);\n\n    // (FFT of obscurer map)*(FFT of star map)\n    for(size_t j=0; j<nj; ++j)\n        for(size_t i=0; i<ni; ++i)\n            A(i, j) *= fft_of_star(i, j);\n\n    // obscurer map convolved with star map\n    A = arma::ifft2(A);\n    for(size_t i=0; i<ni; ++i)\n        for(size_t j=0; j<nj; ++j)\n            convolved(i, j) = A(i, j).real();\n}\n\nvoid MyModel_Pixels::print(std::ostream& out) const\n{\n    const auto& t = data.get_t();\n    for(size_t i=0; i<t.size(); ++i)\n        out<<calculate_total_flux(t[i])<<' ';\n\n    for(size_t i=0; i<ni; ++i)\n        for(size_t j=0; j<nj; ++j)\n            out<<star(i, j)<<' ';\n\n    for(size_t i=0; i<ni; ++i)\n        for(size_t j=0; j<nj; ++j)\n            out<<obscurer_map(i, j)<<' ';\n}\n\nstd::string MyModel_Pixels::description() const\n{\n    return std::string(\"\");\n}\n\n/* STATIC STUFF */\n\nData                  MyModel_Pixels::data;\narma::mat             MyModel_Pixels::star(MyModel_Pixels::ni, MyModel_Pixels::nj);\narma::cx_mat          MyModel_Pixels::fft_of_star(MyModel_Pixels::ni, MyModel_Pixels::nj);\nstd::vector<double>   MyModel_Pixels::x(MyModel_Pixels::nj);\nstd::vector<double>   MyModel_Pixels::y(MyModel_Pixels::ni);\n\nvoid MyModel_Pixels::initialise()\n{\n    for(size_t i=0; i<ni; ++i)\n        y[i] = y_max - (i + 0.5)*dy;\n\n    for(size_t j=0; j<nj; ++j)\n        x[j] = x_min + (j + 0.5)*dx;\n\n    double rsq;\n\n    double limb_darkening_coefficient = 1.0;\n\n    // Argh column-major order\n    // Star image\n    double tot = 0.0;\n    for(size_t j=0; j<nj; ++j)\n    {\n        for(size_t i=0; i<ni; ++i)\n        {\n            rsq = x[j]*x[j] + y[i]*y[i];\n            if(rsq < 1.0)\n            {\n                star(i, j) = 1.0 -\n                    limb_darkening_coefficient*(1.0 - sqrt(1.0 - rsq));\n            }\n            else\n                star(i, j) = 0.0;\n            tot += star(i, j);\n        }\n    }\n    for(size_t j=0; j<nj; ++j)\n        for(size_t i=0; i<ni; ++i)\n            star(i, j) /= tot;\n\n    arma::mat star2 = star;\n    int m, n;\n    for(int i=0; i<(int)ni; i++)\n    {\n        m = DNest4::mod(i - (int)ni/2, (int)ni);\n        for(int j=0; j<(int)nj; j++)\n        {\n            n = DNest4::mod(j - (int)nj/2, (int)nj);\n            star2(m, n) = star(i, j);\n        }\n    }\n\n    fft_of_star = arma::fft2(star2);\n}\n\nvoid MyModel_Pixels::load_data(const char* filename)\n{\n    data.load(filename);\n}\n\n} // namespace Obscurity\n\n", "meta": {"hexsha": "973077cb33d6b5fb174a2a1fc771b2b9e2d8df50", "size": 5325, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/MyModel_Pixels.cpp", "max_stars_repo_name": "eggplantbren/Obscurity", "max_stars_repo_head_hexsha": "29cba90a1a050807db0fbbb52d0137ef40ae8f1a", "max_stars_repo_licenses": ["MIT"], "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/MyModel_Pixels.cpp", "max_issues_repo_name": "eggplantbren/Obscurity", "max_issues_repo_head_hexsha": "29cba90a1a050807db0fbbb52d0137ef40ae8f1a", "max_issues_repo_licenses": ["MIT"], "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/MyModel_Pixels.cpp", "max_forks_repo_name": "eggplantbren/Obscurity", "max_forks_repo_head_hexsha": "29cba90a1a050807db0fbbb52d0137ef40ae8f1a", "max_forks_repo_licenses": ["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.3552631579, "max_line_length": 90, "alphanum_fraction": 0.5064788732, "num_tokens": 1747, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.48441415795232606}}
{"text": "#ifndef TENSOR_OPS_H\n#define TENSOR_OPS_H\n\n#include <stdexcept>\n\n#include <boost/optional.hpp>\n\n#include <fmt/format.h>\n\n#include <tensor.hpp>\n#include <types.hpp>\n\nconstexpr index_t expand = std::numeric_limits<index_t>::max();\n\nstruct TensorError: public std::runtime_error {\n    TensorError(std::string const &msg): std::runtime_error(msg) {}\n};\n\nstruct MismatchedNumberOfElements: public TensorError {\n    MismatchedNumberOfElements(std::size_t lhs, std::size_t rhs):\n        TensorError(fmt::format(\"Number of elements are not the same: {} and {}\", lhs, rhs)) {}\n};\n\nstruct MismatchedDimensions: public TensorError {\n    MismatchedDimensions(extent const &shape1, extent const &shape2):\n        TensorError(fmt::format(\"Mismatched dimensions: {} and {}\", shape1, shape2)) {}\n};\n\nstruct CannotBroadcast: public TensorError {\n    CannotBroadcast(extent const &shape1, extent const &shape2):\n        TensorError(fmt::format(\"Cannot broadcast: {} and {}\", shape1, shape2)) {}\n};\n\nstruct NotEnoughDimensions: public TensorError {\n    NotEnoughDimensions(extent const &shape):\n        TensorError(fmt::format(\"Not enough dimensions: {}\", shape)) {}\n};\n\n/**\n * @brief Returns a tensor fill with `0`s\n *\n * @tparam T The tensor type\n * @tparam Device=CPU The device tensor is stored on\n * @param shape The shape of the tensor\n * @return Tensor<T, Device>\n */\ntemplate <typename T, typename Device=CPU>\nTensor<T, Device> zeros(extent const &shape) {\n    Tensor<T, Device> result(shape);\n    fill(result, 0);\n    return result;\n}\n\n/**\n * @brief Returns a tensor fill with `1`s\n *\n * @tparam T The tensor type\n * @tparam Device=CPU The device tensor is stored on\n * @param shape The shape of the tensor\n * @return Tensor<T, Device>\n */\ntemplate <typename T, typename Device=CPU>\nTensor<T, Device> ones(extent const &shape) {\n    Tensor<T, Device> result(shape);\n    fill(result, 0);\n    return result;\n}\n\ntemplate <typename T, typename Device>\nvoid iota(Tensor<T, Device> &t, T start=0, T stride=1) {\n    T value = start;\n    fill(t, [&value, stride]() {\n        T tmp = value;\n        value += stride;\n        return tmp;\n    });\n}\n\ntemplate <typename T, typename Device=CPU>\nTensor<T, Device> range(T start, T end, T stride=1) {\n    std::size_t size = std::floor((end - start) / stride);\n    Tensor<T, Device> result({size});\n\n    iota(result, start, end, stride);\n    return result;\n}\n\n/**\n * @brief Re-orders dimensions of Tensor\n *\n * @tparam T The tensor type\n * @tparam Device The device tensor is stored on\n * @param tensor The tensor to re-order\n * @param order The new order of dimensions\n * @return Tensor<T, Device>\n */\ntemplate <typename T, typename Device>\nTensor<T, Device> transpose(\n    Tensor<T, Device> const &tensor,\n    indices const &order)\n{\n    extent shape(tensor.shape().size());\n    indices offset(tensor.shape().size());\n    indices strides(tensor.shape().size());\n\n    for (index_t i = 0; i < tensor.shape().size(); i++) {\n        shape[i] = tensor.view().shape[order[i]];\n        offset[i] = tensor.view().offset[order[i]];\n        strides[i] = tensor.view().strides[order[i]];\n    }\n\n    return tensor.view({shape, offset, order, strides});\n}\n\n// TODO: move to source\ninline boost::optional<index_t> get_inferred_dimension(extent const &shape) {\n    boost::optional<index_t> result;\n\n    for (index_t i = 0; i < shape.size(); i++) {\n        if (shape[i] == expand) {\n            if (!result) {\n                result = i;\n            } else {\n                throw TensorError(\"Cannot infer more than one dimension.\");\n            }\n        }\n    }\n\n    return result;\n}\n\n// TODO: move to source\ninline void calculate_reshape(extent const &from_shape, extent &to_shape) {\n    auto inferred_dimension = get_inferred_dimension(to_shape);\n\n    if (inferred_dimension) {\n        // number of elements for the new shape\n        to_shape[*inferred_dimension] = 1;\n        std::size_t new_size = num_elements(to_shape);\n\n        // number of elements for the old shape\n        std::size_t total_size = num_elements(from_shape);\n\n        // calculate the size of the inferred dimension\n        std::size_t inferred_size = total_size / new_size;\n        to_shape[*inferred_dimension] = inferred_size;\n    }\n}\n\n// TODO: make this either respect order, or take order f strides\ntemplate <typename T, typename Device>\nTensor<T, Device> reshape(Tensor<T, Device> const &tensor, extent const &shape) {\n    extent new_shape = shape;\n    calculate_reshape(tensor.shape(), new_shape);\n\n    // we can only reshape if the number of elements is conserved\n    if (num_elements(new_shape) != num_elements(tensor.shape())) {\n        throw MismatchedNumberOfElements(num_elements(new_shape),\n                                         num_elements(tensor.shape()));\n    }\n\n    auto order = make_row_major_order(new_shape.size());\n    auto strides = make_strides(new_shape, order);\n    auto offset = make_offset(new_shape.size());\n\n    if (tensor.contiguous()) {\n        return tensor.view({new_shape, offset, order, strides});\n    }\n\n    return copy(tensor.view({new_shape, offset, order, strides}));\n}\n\ntemplate <typename T, typename Device>\nbool is_broadcastable_to(Tensor<T, Device> const &tensor, extent const &shape) {\n    if (shape.size() < tensor.shape().size()) return false;\n\n    auto shape_it = shape.rbegin();\n    auto tensor_shape_it = tensor.shape().rbegin();\n    for (; tensor_shape_it != tensor.shape().rend(); ++shape_it, ++tensor_shape_it) {\n        if (*shape_it != *tensor_shape_it && *tensor_shape_it != 1) return false;\n    }\n\n    return true;\n}\n\nnamespace detail {\n\ntemplate <typename T, typename Device>\nTensor<T, Device> broadcast_to(Tensor<T, Device> const &tensor, extent const &shape) {\n    extent strides(shape.size(), 0);\n    auto offset = make_offset(shape.size());\n    auto order = make_row_major_order(shape.size());\n\n    std::size_t diff = shape.size() - tensor.shape().size();\n    for (index_t i = 0; i < tensor.shape().size(); i++) {\n        if (tensor.shape()[i] > 1) {\n            strides[diff+i] = tensor.view().strides[i];\n        } else {\n            strides[diff+i] = 0;\n        }\n    }\n\n    return tensor.view({shape, offset, order, strides});\n}\n\n} // namespace detail\n\ntemplate <typename T, typename Device>\nTensor<T, Device> broadcast_to(Tensor<T, Device> const &tensor, extent const &shape) {\n    if (tensor.shape() == shape) return tensor;\n\n    if (!is_broadcastable_to(tensor, shape)) {\n        throw CannotBroadcast(tensor.shape(), shape);\n    }\n\n    return detail::broadcast_to(tensor, shape);\n}\n\ntemplate <typename T, typename Device>\nstd::pair<Tensor<T, Device>, Tensor<T, Device>>\nbroadcast(Tensor<T, Device> const &t1, Tensor<T, Device> const &t2) {\n    if (t1.shape() == t2.shape()) return std::make_pair(t1, t2);\n\n    bool t1_to_t2 = is_broadcastable_to(t1, t2.shape());\n    bool t2_to_t1 = is_broadcastable_to(t2, t1.shape());\n\n    if (!t1_to_t2 && !t2_to_t1) {\n        throw CannotBroadcast(t1.shape(), t2.shape());\n    }\n\n    auto result1 = t1_to_t2 ? detail::broadcast_to(t1, t2.shape()) : t1;\n    auto result2 = t2_to_t1 ? detail::broadcast_to(t2, t1.shape()) : t2;\n    return std::make_pair(result1, result2);\n}\n\ntemplate <typename RT, typename T, typename Device, typename F>\nTensor<RT, Device> apply(Tensor<T, Device> const &lhs,\n                         Tensor<T, Device> const &rhs,\n                         F fn)\n{\n    if (lhs.shape() != rhs.shape()) {\n        // if the dimensions don't match, try to broadcast\n        auto [lhs_broadcast, rhs_broadcast] = broadcast(lhs, rhs);\n        return apply<RT>(lhs_broadcast, rhs_broadcast, fn);\n    }\n\n    Tensor<RT, Device> result(lhs.shape());\n\n    // can optimize if both lhs and rhs are contiguous\n    for (auto const &index : lhs.indices()) {\n        result(index) = fn(lhs(index), rhs(index));\n    }\n\n    return result;\n}\n\ntemplate <typename T, typename Device, typename F>\nvoid iapply(Tensor<T, Device> &lhs, Tensor<T, Device> const &rhs, F fn) {\n    if (lhs.shape() != rhs.shape()) {\n        throw MismatchedDimensions(lhs.shape(), rhs.shape());\n    }\n\n    // can optimize if both lhs and rhs are contiguous\n    for (auto const &index : lhs.indices()) {\n        lhs(index) = fn(lhs(index), rhs(index));\n    }\n}\n\ntemplate <typename RT, typename T, typename Device, typename F>\nTensor<RT, Device> apply(Tensor<T, Device> const &t, F fn) {\n    Tensor<RT, Device> result(t.shape());\n    for (auto const &index : t.indices()) {\n        result(index) = fn(t(index));\n    }\n\n    return result;\n}\n\ntemplate <typename T, typename Device, typename F>\nvoid iapply(Tensor<T, Device> &t, F fn) {\n    for (auto const &index : t.indices()) {\n        t(index) = fn(t(index));\n    }\n}\n\n/**\n * @brief Sets all the elements of a tensor to the given value\n *\n * @tparam T The tensor type\n * @tparam Device The device tensor is stored on\n * @param t The tensor to fill\n * @param value The value use\n */\ntemplate <typename T, typename Device>\nvoid fill(Tensor<T, Device> &t, T const &value) {\n    iapply(t, [value](T const &) { return value; });\n}\n\n/**\n * @brief Fills tensor using a successive calls to passed in function\n *\n * @tparam T The tensor type\n * @tparam Device The device tensor is stored on\n * @tparam F Function type\n * @param t The tensor to fill\n * @param fn The function used to fill tensor\n */\ntemplate <typename T, typename Device, typename F>\nvoid fill(Tensor<T, Device> &t, F fn) {\n    iapply(t, [fn](T const &) { return fn(); });\n}\n\ntemplate <typename T, typename Device>\nTensor<T, Device> operator +(Tensor<T, Device> const &lhs, Tensor<T, Device> const &rhs) {\n    return apply<T>(lhs, rhs, [](T const &lop, T const &rop) { return lop + rop; });\n}\n\ntemplate <typename T, typename Device>\nTensor<T, Device> &operator +=(Tensor<T, Device> &lhs, Tensor<T, Device> const &rhs) {\n    iapply(lhs, rhs, [](T const &lop, T const &rop) { return lop + rop; });\n    return lhs;\n}\n\ntemplate <typename T, typename Device>\nTensor<T, Device> operator -(Tensor<T, Device> const &lhs, Tensor<T, Device> const &rhs) {\n    return apply<T>(lhs, rhs, [](T const &lop, T const &rop) { return lop - rop; });\n}\n\ntemplate <typename T, typename Device>\nTensor<T, Device> &operator -=(Tensor<T, Device> &lhs, Tensor<T, Device> const &rhs) {\n    iapply(lhs, rhs, [](T const &lop, T const &rop) { return lop - rop; });\n    return lhs;\n}\n\ntemplate <typename T, typename Device>\nTensor<T, Device> operator *(ElementTensor<T, Device> lhs, ElementTensor<T, Device> rhs) {\n    return apply<T>(lhs.tensor, rhs.tensor, [](T const &lop, T const &rop) {\n        return lop * rop;\n    });\n}\n\ntemplate <typename T, typename Device>\nTensor<T, Device> &operator *=(ElementTensor<T, Device> lhs, ElementTensor<T, Device> rhs) {\n    iapply(lhs.tensor, rhs.tensor, [](T const &lop, T const &rop) { return lop * rop; });\n    return lhs.tensor;\n}\n\ntemplate <typename T, typename Device>\nTensor<T, Device> operator /(Tensor<T, Device> const &lhs, Tensor<T, Device> const &rhs) {\n    return apply<T>(lhs, rhs, [](T const &lop, T const &rop) { return lop / rop; });\n}\n\ntemplate <typename T, typename Device>\nTensor<T, Device> &operator /=(Tensor<T, Device> &lhs, Tensor<T, Device> const &rhs) {\n    iapply(lhs, rhs, [](T const &lop, T const &rop) { return lop / rop; });\n    return lhs;\n}\n\ntemplate <typename T, typename Device>\nTensor<T, Device> sin(Tensor<T, Device> &t) {\n    return apply<T>(t, [](T const &v) { return std::sin(v); });\n}\n\ntemplate <typename T, typename Device>\nvoid isin(Tensor<T, Device> &t) {\n    iapply(t, [](T const &v) { return std::sin(v); });\n}\n\n// move to detail\ntemplate <typename T, typename Device>\nTensor<T, Device> vector_vector_product(Tensor<T, Device> const &lhs,\n                                        Tensor<T, Device> const &rhs)\n{\n    if (num_elements(lhs) != num_elements(rhs)) {\n        throw MismatchedNumberOfElements(num_elements(lhs), num_elements(rhs));\n    }\n\n    T result(0);\n    for (index_t i = 0; i < num_elements(lhs); i++) {\n        result += lhs(i)*rhs(i);\n    }\n\n    return tensor({result});\n}\n\ntemplate <typename T, typename Device>\nTensor<T, Device> matrix_vector_product(Tensor<T, Device> const &lhs,\n                                        Tensor<T, Device> const &rhs)\n{\n    // verify inner dimensions match: (Nx1, 1)\n    Tensor<T, Device> result({lhs.shape()[0]});\n    fill(result, 0);\n\n    for (index_t i = 0; i < lhs.shape()[0]; i++) {\n        for (index_t j = 0; j < lhs.shape()[1]; j++) {\n            result(i) += lhs(i, j)*rhs(j);\n        }\n    }\n\n    return result;\n}\n\n// need batch_matrix_vector\n\ntemplate <typename T, typename Device>\nTensor<T, Device> matrix_matrix_product(Tensor<T, Device> const &lhs,\n                                        Tensor<T, Device> const &rhs)\n{\n    Tensor<T, Device> result({lhs.shape()[0], rhs.shape()[1]});\n    fill(result, 0);\n\n    for (index_t i = 0; i < lhs.shape()[0]; i++) {\n        for (index_t j = 0; j < lhs.shape()[1]; j++) {\n            for (index_t k = 0; k < rhs.shape()[1]; k++) {\n                result(i, k) += lhs(i, j)*rhs(j, k);\n            }\n        }\n    }\n\n    return result;\n}\n\ntemplate <typename T, typename Device>\nTensor<T, Device> batch_matrix_matrix_product(Tensor<T, Device> const &lhs,\n                                              Tensor<T, Device> const &rhs)\n{\n    // BxMxN * BxNxP\n    Tensor<T, Device> result({lhs.shape()[0], lhs.shape()[1], rhs.shape()[2]});\n    fill(result, 0);\n\n    for (index_t b = 0; b < lhs.shape()[0]; b++) {\n        for (index_t i = 0; i < lhs.shape()[1]; i++) {\n            for (index_t j = 0; j < lhs.shape()[2]; j++) {\n                for (index_t k = 0; k < rhs.shape()[2]; k++) {\n                    result(b, i, k) += lhs(b, i, j)*rhs(b, j, k);\n                }\n            }\n        }\n    }\n\n    return result;\n}\n\n\ninline extent get_batch_shape(extent const &shape) {\n    if (shape.size() < 3) throw NotEnoughDimensions(shape);\n    std::size_t count = shape.size() - 2;\n\n    extent batch_shape(count);\n    std::copy_n(std::begin(shape), count, std::begin(batch_shape));\n    return batch_shape;\n}\n\ninline extent calculate_batch_shape(extent const &shape, index_t d0, index_t d1) {\n    auto new_shape = get_batch_shape(shape);\n    new_shape.push_back(d0);\n    new_shape.push_back(d1);\n    return new_shape;\n}\n\ntemplate <typename T, typename Device>\nTensor<T, Device> product(Tensor<T, Device> const &lhs,\n                          Tensor<T, Device> const &rhs)\n{\n    auto lhs_dims = num_dims(lhs);\n    auto rhs_dims = num_dims(rhs);\n\n    // 5x3x6 * 5x\n    if (lhs_dims > 2 || rhs_dims > 2) {\n        auto lhs_copy = lhs;\n        auto rhs_copy = rhs;\n\n        // flatten batch dimension if either tensor is > 3 dims\n        if (lhs_dims > 3) {\n            lhs_copy = reshape(lhs_copy, {expand, lhs.shape()[lhs_dims-2], lhs.shape()[lhs_dims-1]});\n        }\n\n        if (rhs_dims > 3) {\n            rhs_copy = reshape(rhs_copy, {expand, rhs.shape()[rhs_dims-2], rhs.shape()[rhs_dims-1]});\n        }\n\n        // if (lhs_dims == 2) {\n        //     // add batch dimension\n        // } else if (lhs_dims == 1) {\n        //     // treat as batch matrix-vector multiplication\n        // }\n\n        // 2. either lhs or rhs > 3, in which case need to flatten\n        auto result = batch_matrix_matrix_product(lhs_copy, rhs_copy);\n\n        // for now, assume both lhs and rhs start off as the same shape\n        // auto new_shape = get_batch_size(orig_lhs_shape);\n        auto new_shape = calculate_batch_shape(lhs.shape(), result.shape()[1], result.shape()[2]);\n\n        // reshape into original batch dims\n        return reshape(result, new_shape);\n    }\n\n    if (lhs_dims == 1 && rhs_dims == 1) {\n        return vector_vector_product(lhs, rhs);\n    }\n\n    if (rhs_dims == 1) {\n        return matrix_vector_product(lhs, rhs);\n    }\n\n    if (lhs_dims == 1) {\n        // TODO: follow pytorch convention and add a dimension\n        // to lhs and make matrix_matrix?\n        return matrix_vector_product(rhs, lhs);\n    }\n\n    // matrix output\n    return matrix_matrix_product(lhs, rhs);\n}\n\ntemplate <typename T, typename Device>\nTensor<T, Device> operator *(Tensor<T, Device> const &lhs, Tensor<T, Device> const &rhs) {\n    return product(lhs, rhs);\n}\n\n\ntemplate <typename T, typename Device>\nTensor<std::uint8_t, Device> operator ==(Tensor<T, Device> const &lhs,\n                                         Tensor<T, Device> const &rhs)\n{\n    return apply<std::uint8_t>(lhs, rhs, [](T const &lop, T const &rop) {\n        return lop == rop;\n    });\n}\n\ntemplate <typename T, typename Device>\nTensor<std::uint8_t, Device> operator !=(Tensor<T, Device> const &lhs,\n                                         Tensor<T, Device> const &rhs)\n{\n    return !(lhs == rhs);\n}\n\ntemplate <typename T, typename Device, typename F>\nbool all(Tensor<T, Device> const &op, F fn) {\n    for (auto const &index : op.indices()) {\n        if (!fn(op(index))) return false;\n    }\n\n    return true;\n}\n\ntemplate <typename T, typename Device, typename F>\nbool any(Tensor<T, Device> const &op, F fn) {\n    for (auto const &index : op.indices()) {\n        if (fn(op(index))) return true;\n    }\n\n    return false;\n}\n\ntemplate <typename T, typename Device>\nbool equals(Tensor<T, Device> const &lhs, Tensor<T, Device> const &rhs) {\n    return all(lhs == rhs, [](std::uint8_t v) { return v == true; });\n}\n\n#endif", "meta": {"hexsha": "a2923120d2a64da978916ffd3ce8ff3378bf5de2", "size": 17299, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/tensor_ops.hpp", "max_stars_repo_name": "abeschneider/tensor", "max_stars_repo_head_hexsha": "cd9e26ce756dc3095f8ca4ebc4e67b7fa75cdc6d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-08-20T10:09:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-25T07:02:22.000Z", "max_issues_repo_path": "include/tensor_ops.hpp", "max_issues_repo_name": "abeschneider/tensor", "max_issues_repo_head_hexsha": "cd9e26ce756dc3095f8ca4ebc4e67b7fa75cdc6d", "max_issues_repo_licenses": ["MIT"], "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/tensor_ops.hpp", "max_forks_repo_name": "abeschneider/tensor", "max_forks_repo_head_hexsha": "cd9e26ce756dc3095f8ca4ebc4e67b7fa75cdc6d", "max_forks_repo_licenses": ["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.78113879, "max_line_length": 101, "alphanum_fraction": 0.6192265449, "num_tokens": 4467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6654105720171531, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.4844025598709703}}
{"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_ATANH_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_ATANH_HPP_INCLUDED\n\n#include <boost/simd/detail/overload.hpp>\n#include <boost/simd/meta/as_logical.hpp>\n#include <boost/simd/constant/half.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/divides.hpp>\n#include <boost/simd/function/fma.hpp>\n#include <boost/simd/function/if_else.hpp>\n#include <boost/simd/function/is_less.hpp>\n#include <boost/simd/function/log.hpp>\n#include <boost/simd/function/log1p.hpp>\n#include <boost/simd/function/oneminus.hpp>\n#include <boost/simd/function/raw.hpp>\n#include <boost/simd/function/inc.hpp>\n#include <boost/simd/function/oneminus.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n   namespace bd = boost::dispatch;\n   namespace bs = boost::simd;\n   BOOST_DISPATCH_OVERLOAD_IF( atanh_\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 absa0 = bs::abs(a0);\n        A0 t =  absa0+absa0;\n        A0 z1 = oneminus(absa0);\n        auto test =  is_less(absa0, Half<A0>());\n        A0 tmp = if_else(test, absa0, t)/z1;\n        return bitwise_xor(bitofsign(a0), Half<A0>()*log1p(if_else(test, fma(t,tmp,t), tmp)));\n      }\n   };\n\n   BOOST_DISPATCH_OVERLOAD_IF( atanh_\n                          , (typename A0, typename X)\n                          , (detail::is_native<X>)\n                          , bd::cpu_\n                          , boost::simd::raw_tag\n                          , bs::pack_<bd::floating_<A0>, X>\n                          )\n   {\n      BOOST_FORCEINLINE A0 operator()(const raw_tag &,\n                                      const A0& a0) const BOOST_NOEXCEPT\n      {\n        return  Half<A0>()*log(inc(a0)/oneminus(a0));\n      }\n   };\n\n} } }\n\n#endif\n", "meta": {"hexsha": "db9ca8b1bc1c2b62687dc507871404ec3006269e", "size": 2502, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/simd/function/atanh.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/atanh.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/atanh.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.2394366197, "max_line_length": 100, "alphanum_fraction": 0.553157474, "num_tokens": 582, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583696, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4843583324054103}}
{"text": "static bool eigen_did_assert = false;\n#define eigen_assert(X) if(!eigen_did_assert && !(X)){ std::cout << \"### Assertion raised in \" << __FILE__ << \":\" << __LINE__ << \":\\n\" #X << \"\\n### The following would happen without assertions:\\n\"; eigen_did_assert = true;}\n\n#include <iostream>\n#include <Eigen/Eigen>\n\n#ifndef M_PI\n#define M_PI 3.1415926535897932384626433832795\n#endif\n\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n  Vector3d v(1,0,0);\nVector3d w(1e-4,0,1);\ncout << \"Here's the vector v:\" << endl << v << endl;\ncout << \"Here's the vector w:\" << endl << w << endl;\ncout << \"v.isOrthogonal(w) returns: \" << v.isOrthogonal(w) << endl;\ncout << \"v.isOrthogonal(w,1e-3) returns: \" << v.isOrthogonal(w,1e-3) << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "153db7542e175fa5c61b28d7b56cec4f5a6b2353", "size": 777, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/snippets/compile_MatrixBase_isOrthogonal.cpp", "max_stars_repo_name": "mousepawmedia/libdeps", "max_stars_repo_head_hexsha": "b004d58d5b395ceaf9fdc993cfb00e91334a5d36", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2021-02-27T11:00:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T10:31:46.000Z", "max_issues_repo_path": "doc/snippets/compile_MatrixBase_isOrthogonal.cpp", "max_issues_repo_name": "mousepawmedia/libdeps", "max_issues_repo_head_hexsha": "b004d58d5b395ceaf9fdc993cfb00e91334a5d36", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-11-14T23:14:58.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-14T23:14:58.000Z", "max_forks_repo_path": "doc/snippets/compile_MatrixBase_isOrthogonal.cpp", "max_forks_repo_name": "mousepawmedia/libdeps", "max_forks_repo_head_hexsha": "b004d58d5b395ceaf9fdc993cfb00e91334a5d36", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-03-13T13:28:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-05T02:26:02.000Z", "avg_line_length": 28.7777777778, "max_line_length": 224, "alphanum_fraction": 0.6525096525, "num_tokens": 246, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.4843579857945293}}
{"text": "// Filthy awful hack to test.\n#include \"gtest/gtest.h\"\n#include <Eigen/Dense>\n#define private public\n#include \"bond.h\"\n\n\nTEST(ProjectionTest, OnRailUnchanged)\n{\n    // Test if projecting a vector onto itself leaves the vector unchanged.\n    Eigen::VectorXd rail(2);\n    rail << 1.0, 0.0;\n    const HarmonicBond bond {1.0, 1.0, 0, 1, rail};\n    \n    Eigen::VectorXd new_vec(2);\n    new_vec << 1.0, 0.0;\n\n    auto projected_vec = bond.project_onto_rail(new_vec);\n    \n    for (int i = 0; i < new_vec.rows(); ++i) {\n        ASSERT_FLOAT_EQ(projected_vec(i), new_vec(i));\n    }\n}\n\nTEST(ProjectionTest, UnnormalisedRail)\n{\n    // Test if projecting a vector onto itself leaves the vector unchanged.\n    Eigen::VectorXd rail(2);\n    rail << 10.0, 0.0;\n    const HarmonicBond bond {1.0, 1.0, 0, 1, rail};\n    \n    Eigen::VectorXd new_vec(2);\n    new_vec << 1.0, 0.0;\n\n    auto projected_vec = bond.project_onto_rail(new_vec);\n    \n    for (int i = 0; i < new_vec.rows(); ++i) {\n        ASSERT_FLOAT_EQ(projected_vec(i), new_vec(i));\n    }\n}\n\nTEST(ProjectionTest, OnRailOpposite)\n{\n    // Test if projecting negative vector onto itself leaves the vector unchanged.\n    Eigen::VectorXd rail(2);\n    rail << 1.0, 0.0;\n    const HarmonicBond bond {1.0, 1.0, 0, 1, rail};\n    \n    Eigen::VectorXd new_vec(2);\n    new_vec << -1.0, 0.0;\n\n    auto projected_vec = bond.project_onto_rail(new_vec);\n    \n    for (int i = 0; i < new_vec.rows(); ++i) {\n        ASSERT_FLOAT_EQ(projected_vec(i), new_vec(i));\n    }\n}\n\nTEST(ProjectionTest, OnRailLarger)\n{\n    // Test if projecting a larger vector onto itself leaves the vector unchanged.\n    Eigen::VectorXd rail(2);\n    rail << 1.0, 0.0;\n    const HarmonicBond bond {1.0, 1.0, 0, 1, rail};\n    \n    Eigen::VectorXd new_vec(2);\n    new_vec << 2.0, 0.0;\n\n    auto projected_vec = bond.project_onto_rail(new_vec);\n    \n    for (int i = 0; i < new_vec.rows(); ++i) {\n        ASSERT_FLOAT_EQ(projected_vec(i), new_vec(i));\n    }\n}\n\nTEST(ProjectionTest, OnRailOppositeLarger)\n{\n    // Test if projecting a larger negative vector onto itself leaves the vector unchanged.\n    Eigen::VectorXd rail(2);\n    rail << 1.0, 0.0;\n    const HarmonicBond bond {1.0, 1.0, 0, 1, rail};\n    \n    Eigen::VectorXd new_vec(2);\n    new_vec << -2.0, 0.0;\n\n    auto projected_vec = bond.project_onto_rail(new_vec);\n    \n    for (int i = 0; i < new_vec.rows(); ++i) {\n        ASSERT_FLOAT_EQ(projected_vec(i), new_vec(i));\n    }\n}\n\nTEST(ProjectionTest, OffRail)\n{\n    // Test if projecting a vector that's off a rail back onto the rail\n    // changes it.\n    Eigen::VectorXd rail(2);\n    rail << 1.0, 0.0;\n    const HarmonicBond bond {1.0, 1.0, 0, 1, rail};\n    \n    Eigen::VectorXd new_vec(2);\n    new_vec << 1.0, 1.0;\n\n    Eigen::VectorXd expected_vec(2);\n    expected_vec << 1.0, 0.0;\n    auto projected_vec = bond.project_onto_rail(new_vec);\n\n    for (int i = 0; i < new_vec.rows(); ++i) {\n        ASSERT_FLOAT_EQ(projected_vec(i), expected_vec(i));\n    }\n}\n\nTEST(ProjectionTest, OffRailNegative)\n{\n    // Test if projecting a vector onto itself leaves the vector unchanged.\n    Eigen::VectorXd rail(2);\n    rail << 1.0, 0.0;\n    const HarmonicBond bond {1.0, 1.0, 0, 1, rail};\n    \n    Eigen::VectorXd new_vec(2);\n    new_vec << -1.0, -1.0;\n\n    Eigen::VectorXd expected_vec(2);\n    expected_vec << -1.0, 0.0;\n    \n    auto projected_vec = bond.project_onto_rail(new_vec);\n    for (int i = 0; i < new_vec.rows(); ++i) {\n        ASSERT_FLOAT_EQ(projected_vec(i), expected_vec(i));\n    }\n}\n\nTEST(ProjectionTest, NegativeRail)\n{\n    // Test if projecting negative vector onto itself leaves the vector unchanged.\n    Eigen::VectorXd rail(2);\n    rail << -1.0, 0.0;\n    const HarmonicBond bond {1.0, 1.0, 0, 1, rail};\n    \n    Eigen::VectorXd new_vec(2);\n    new_vec << -1.0, 0.0;\n\n    auto projected_vec = bond.project_onto_rail(new_vec);\n    \n    for (int i = 0; i < new_vec.rows(); ++i) {\n        ASSERT_FLOAT_EQ(projected_vec(i), new_vec(i));\n    }\n}\n\nTEST(ProjectionTest, NegativeRailOppositeVec)\n{\n    // Test if projecting negative vector onto itself leaves the vector unchanged.\n    Eigen::VectorXd rail(2);\n    rail << -1.0, 0.0;\n    const HarmonicBond bond {1.0, 1.0, 0, 1, rail};\n    \n    Eigen::VectorXd new_vec(2);\n    new_vec << 1.0, 0.0;\n\n    auto projected_vec = bond.project_onto_rail(new_vec);\n    \n    for (int i = 0; i < new_vec.rows(); ++i) {\n        ASSERT_FLOAT_EQ(projected_vec(i), new_vec(i));\n    }\n}\n", "meta": {"hexsha": "ddc1cc0c61b051fe5ec4e2ca35a48385c74f8dd9", "size": 4431, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_projection.cpp", "max_stars_repo_name": "Matt-HJ-Bailey/Constrained-MD", "max_stars_repo_head_hexsha": "3897a5f97272772ea03f953414df779aed844216", "max_stars_repo_licenses": ["MIT"], "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_projection.cpp", "max_issues_repo_name": "Matt-HJ-Bailey/Constrained-MD", "max_issues_repo_head_hexsha": "3897a5f97272772ea03f953414df779aed844216", "max_issues_repo_licenses": ["MIT"], "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_projection.cpp", "max_forks_repo_name": "Matt-HJ-Bailey/Constrained-MD", "max_forks_repo_head_hexsha": "3897a5f97272772ea03f953414df779aed844216", "max_forks_repo_licenses": ["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.8545454545, "max_line_length": 91, "alphanum_fraction": 0.6235612729, "num_tokens": 1379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.6959583124210896, "lm_q1q2_score": 0.4843579814056898}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2014 Jose Aparicio\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n#include <boost/make_shared.hpp>\n#include <qlo/latentmodels.hpp>\n\n#include <ql/experimental/credit/defaultprobabilitylatentmodel.hpp>\n\nnamespace QuantLibAddin {\n\n    GaussianDefProbLM::GaussianDefProbLM(\n        const boost::shared_ptr<ObjectHandler::ValueObject>& properties,\n        const boost::shared_ptr<QuantLib::Basket>& basket,\n        const std::vector<std::vector<QuantLib::Real> >& factorWeights,\n        bool permanent)\n    : ObjectHandler::LibraryObject<QuantLib::GaussianDefProbLM>(properties, \n      permanent) {\n        libraryObject_ = boost::make_shared<QuantLib::GaussianDefProbLM>(\n            //basket,\n            factorWeights,\n            QuantLib::LatentModelIntegrationType::GaussianQuadrature);\n        libraryObject_->resetBasket(basket);\n    }\n\n    TDefProbLM::TDefProbLM(\n        const boost::shared_ptr<ObjectHandler::ValueObject>& properties,\n        const std::vector<QuantLib::Integer>& tOrders,\n        const boost::shared_ptr<QuantLib::Basket>& basket,\n        const std::vector<std::vector<QuantLib::Real> >& factorWeights,\n        bool permanent)\n    : ObjectHandler::LibraryObject<QuantLib::TDefProbLM>(properties, \n      permanent) {\n        QuantLib::TCopulaPolicy::initTraits initsT;\n        initsT.tOrders = tOrders;\n        libraryObject_ = boost::make_shared<QuantLib::TDefProbLM>(\n            //basket,\n            factorWeights,\n            QuantLib::LatentModelIntegrationType::GaussianQuadrature,\n            initsT);\n        libraryObject_->resetBasket(basket);\n    }\n\n}\n", "meta": {"hexsha": "5a7c55ecffd560f41cc4cbfff148b7efc2d29da5", "size": 2321, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QuantLibAddin/qlo/latentmodels.cpp", "max_stars_repo_name": "txu2014/quantlib", "max_stars_repo_head_hexsha": "95c7d94906c30d0c3c4e0758a2ebfe2a62b075ec", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "QuantLibAddin/qlo/latentmodels.cpp", "max_issues_repo_name": "txu2014/quantlib", "max_issues_repo_head_hexsha": "95c7d94906c30d0c3c4e0758a2ebfe2a62b075ec", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "QuantLibAddin/qlo/latentmodels.cpp", "max_forks_repo_name": "txu2014/quantlib", "max_forks_repo_head_hexsha": "95c7d94906c30d0c3c4e0758a2ebfe2a62b075ec", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.6833333333, "max_line_length": 79, "alphanum_fraction": 0.7052994399, "num_tokens": 541, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.769080247656264, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.4843472110302127}}
{"text": "/**\n * @file NlpDescription.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-06\n */\n\n#pragma once\n\n#include <iostream>\n#include <Eigen/Dense>\n\nnamespace solver\n{\n\n  // Nonlinear problem description\n  class NlpDescription\n  {\n    public:\n\t  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n    public:\n\t  NlpDescription(){};\n      virtual ~NlpDescription(){};\n\n      // definition of problem size\n      virtual void getNlpParameters(int& n_vars, int& n_cons) = 0;\n\n      // definition of problem box constraints\n      virtual void getNlpBounds(int n_vars, int n_cons, double* x_l, double* x_u, double* g_l, double* g_u) = 0;\n\n      // definition of starting point\n      virtual void getStartingPoint(int n_vars, double* x) = 0;\n\n      // definition of objective function\n      virtual double evaluateObjective(int n_vars, const double* x) = 0;\n\n      // definition of constraints function\n      virtual void evaluateConstraintsVector(int n_vars, int n_cons, const double* x, double* constraints) = 0;\n\n      // definition of how to process solution\n      virtual void processSolution(int n_vars, double objective_value, const double* x)\n      {\n        Eigen::Map<const Eigen::VectorXd> eig_x_const(&x[0], n_vars);\n        this->optimalVector() = eig_x_const;\n        this->optimalValue()  = objective_value;\n      }\n\n      double& optimalValue() { return eig_obj_; }\n      const double& optimalValue() const { return eig_obj_; }\n      Eigen::VectorXd& optimalVector() { return eig_opt_x_; }\n      const Eigen::VectorXd& optimalVector() const { return eig_opt_x_; }\n\n    private:\n      double eig_obj_;\n      Eigen::VectorXd eig_opt_x_;\n  };\n}\n", "meta": {"hexsha": "8aca7b43b763812802c419e7af9306b1d70628d4", "size": 1777, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "solver/include/solver/interface/NlpDescription.hpp", "max_stars_repo_name": "ferdinand-wood/kino_dynamic_opt", "max_stars_repo_head_hexsha": "ba6bef170819c55d1d26e40af835a744d1ae663f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 26.0, "max_stars_repo_stars_event_min_datetime": "2019-11-18T17:39:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-18T00:38:22.000Z", "max_issues_repo_path": "solver/include/solver/interface/NlpDescription.hpp", "max_issues_repo_name": "ferdinand-wood/kino_dynamic_opt", "max_issues_repo_head_hexsha": "ba6bef170819c55d1d26e40af835a744d1ae663f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 25.0, "max_issues_repo_issues_event_min_datetime": "2019-11-11T19:54:51.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-07T13:41:47.000Z", "max_forks_repo_path": "solver/include/solver/interface/NlpDescription.hpp", "max_forks_repo_name": "ferdinand-wood/kino_dynamic_opt", "max_forks_repo_head_hexsha": "ba6bef170819c55d1d26e40af835a744d1ae663f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-15T14:36:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-29T10:42:19.000Z", "avg_line_length": 29.6166666667, "max_line_length": 112, "alphanum_fraction": 0.68148565, "num_tokens": 448, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.6297746004557471, "lm_q1q2_score": 0.48434720568613077}}
{"text": "/*\n * PACDDecrypter.cpp\n *\n *  Created on: 26 Jun 2018\n *      Author: scsjd\n */\n\n#include \"PolyACDDecrypter.h\"\n\n#include <NTL/ZZ.h>\n#include <NTL/ZZX.h>\n#include <NTL/vec_ZZ.h>\n#include <jsoncpp/json/json.h>\n#include <sstream>\n\nPolyACDDecrypter::PolyACDDecrypter() {\n}\n\nPolyACDDecrypter::~PolyACDDecrypter() {\n}\n\nvoid PolyACDDecrypter::readSecretsFromJSON(std::string& json){\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\tstd::istringstream k1buf(root[\"k1\"].asString());\n\t\tk1buf >> k1;\n\t\tstd::istringstream k2buf(root[\"k2\"].asString());\n\t\tk2buf >> k2;\n\t}\n};\n\nNTL::ZZX PolyACDDecrypter::decrypt(NTL::ZZX& ciphertext){\n\tNTL::ZZ c_l = LeadCoeff(ciphertext);\n\tNTL::ZZ m_n = c_l/k1;\n\tNTL::ZZX c;\n\tlong d = deg(ciphertext)+1;\n\tc.SetLength(d);\n\tfor (long i=0; i<d-1; i++){\n\t\tSetCoeff(c,i,coeff(ciphertext,i));\n\t}\n\tSetCoeff(c,d,m_n);\n\tSetCoeff(c,d-1,c_l-k1*m_n);\n\tNTL::ZZX m = c/k2;\n\treturn m;\n};\n", "meta": {"hexsha": "d0442e3fdf8334d65fb73f89d324509cbd893170", "size": 1012, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/ope_terasort/polyvalidate/src/worker/PolyACDDecrypter.cpp", "max_stars_repo_name": "TANGO-Project/cryptango", "max_stars_repo_head_hexsha": "be6a2d74d238bffd3f3e899ea0eea01966097ebe", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/ope_terasort/polyvalidate/src/worker/PolyACDDecrypter.cpp", "max_issues_repo_name": "TANGO-Project/cryptango", "max_issues_repo_head_hexsha": "be6a2d74d238bffd3f3e899ea0eea01966097ebe", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/ope_terasort/polyvalidate/src/worker/PolyACDDecrypter.cpp", "max_forks_repo_name": "TANGO-Project/cryptango", "max_forks_repo_head_hexsha": "be6a2d74d238bffd3f3e899ea0eea01966097ebe", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.0833333333, "max_line_length": 67, "alphanum_fraction": 0.6758893281, "num_tokens": 347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.6297746074044135, "lm_q1q2_score": 0.48434720436371115}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n/// \\file\n/// Defines the class Rotation.\n\n#pragma once\n\n#include <array>\n#include <boost/optional.hpp>\n#include <cstddef>\n#include <limits>\n\n#include \"DataStructures/Tensor/Tensor.hpp\"\n#include \"Utilities/TypeTraits/RemoveReferenceWrapper.hpp\"\n\n/// \\cond\nnamespace PUP {\nclass er;\n}  // namespace PUP\n/// \\endcond\n\nnamespace domain {\nnamespace CoordinateMaps {\n\n/// \\cond HIDDEN_SYMBOLS\ntemplate <size_t Dim>\nclass Rotation;\n/// \\endcond\n\n/*!\n * \\ingroup CoordinateMapsGroup\n * \\brief Spatial rotation in two dimensions.\n *\n * Let \\f$(R,\\Phi)\\f$ be the polar coordinates associated with\n * \\f$(\\xi,\\eta)\\f$.\n * Let \\f$(r,\\phi)\\f$ be the polar coordinates associated with \\f$(x,y)\\f$.\n * Applies the spatial rotation \\f$\\phi = \\Phi + \\alpha\\f$.\n *\n * The formula for the mapping is:\n *\\f{eqnarray*}\n  x &=& \\xi \\cos \\alpha - \\eta \\sin \\alpha \\\\\n  y &=& \\xi \\sin \\alpha + \\eta \\cos \\alpha\n  \\f}.\n */\ntemplate <>\nclass Rotation<2> {\n public:\n  static constexpr size_t dim = 2;\n\n  /// Constructor.\n  ///\n  /// \\param rotation_angle the angle \\f$\\alpha\\f$ (in radians).\n  explicit Rotation(double rotation_angle);\n  Rotation() = default;\n  ~Rotation() = default;\n  Rotation(const Rotation&) = default;\n  Rotation& operator=(const Rotation&) = default;\n  Rotation(Rotation&&) noexcept = default;  // NOLINT\n  Rotation& operator=(Rotation&&) = default;\n\n  template <typename T>\n  std::array<tt::remove_cvref_wrap_t<T>, 2> operator()(\n      const std::array<T, 2>& source_coords) const noexcept;\n\n  boost::optional<std::array<double, 2>> inverse(\n      const std::array<double, 2>& target_coords) const noexcept;\n\n  template <typename T>\n  tnsr::Ij<tt::remove_cvref_wrap_t<T>, 2, Frame::NoFrame> jacobian(\n      const std::array<T, 2>& source_coords) const noexcept;\n\n  template <typename T>\n  tnsr::Ij<tt::remove_cvref_wrap_t<T>, 2, Frame::NoFrame> inv_jacobian(\n      const std::array<T, 2>& source_coords) const noexcept;\n\n  void pup(PUP::er& p);  // NOLINT\n\n  bool is_identity() const noexcept { return is_identity_; }\n\n private:\n  friend bool operator==(const Rotation<2>& lhs,\n                         const Rotation<2>& rhs) noexcept;\n\n  double rotation_angle_{std::numeric_limits<double>::signaling_NaN()};\n  tnsr::ij<double, 2, Frame::Grid> rotation_matrix_{\n      std::numeric_limits<double>::signaling_NaN()};\n  bool is_identity_{false};\n};\n\nbool operator!=(const Rotation<2>& lhs, const Rotation<2>& rhs) noexcept;\n\n/*!\n * \\ingroup CoordinateMapsGroup\n * \\brief Spatial rotation in three dimensions using Euler angles\n *\n * Rotation angles should be specified in degrees.\n * First rotation \\f$\\alpha\\f$ is about z axis.\n * Second rotation \\f$\\beta\\f$ is about rotated y axis.\n * Third rotation \\f$\\gamma\\f$ is about rotated z axis.\n * These rotations are of the \\f$(\\xi,\\eta,\\zeta)\\f$ coordinate system with\n * respect\n * to the grid coordinates \\f$(x,y,z)\\f$.\n *\n * The formula for the mapping is:\n * \\f{eqnarray*}\n *   x &=& \\xi (\\cos\\gamma \\cos\\beta \\cos\\alpha - \\sin\\gamma \\sin\\alpha)\n * + \\eta (-\\sin\\gamma \\cos\\beta \\cos\\alpha - \\cos\\gamma \\sin\\alpha)\n * + \\zeta \\sin\\beta \\cos\\alpha \\\\\n * y &=& \\xi (\\cos\\gamma \\cos\\beta \\sin\\alpha + \\sin\\gamma \\cos\\alpha)\n * + \\eta (-\\sin\\gamma \\cos\\beta \\sin\\alpha + \\cos\\gamma \\cos\\alpha)\n * + \\zeta \\sin\\beta \\sin\\alpha \\\\\n *        z &=& -\\xi \\cos\\gamma \\sin\\beta + \\eta \\sin\\gamma \\sin\\beta\n *        +  \\zeta \\cos\\beta\n *  \\f}\n */\ntemplate <>\nclass Rotation<3> {\n public:\n  static constexpr size_t dim = 3;\n\n  /// Constructor.\n  ///\n  /// \\param rotation_about_z the angle \\f$\\alpha\\f$ (in radians).\n  /// \\param rotation_about_rotated_y the angle \\f$\\beta\\f$ (in radians).\n  /// \\param rotation_about_rotated_z the angle \\f$\\gamma\\f$ (in radians).\n  Rotation(double rotation_about_z, double rotation_about_rotated_y,\n           double rotation_about_rotated_z);\n  Rotation() = default;\n  ~Rotation() = default;\n  Rotation(const Rotation&) = default;\n  Rotation& operator=(const Rotation&) = default;\n  Rotation(Rotation&&) noexcept = default;  // NOLINT\n  Rotation& operator=(Rotation&&) = default;\n\n  template <typename T>\n  std::array<tt::remove_cvref_wrap_t<T>, 3> operator()(\n      const std::array<T, 3>& source_coords) const noexcept;\n\n  boost::optional<std::array<double, 3>> inverse(\n      const std::array<double, 3>& target_coords) const noexcept;\n\n  template <typename T>\n  tnsr::Ij<tt::remove_cvref_wrap_t<T>, 3, Frame::NoFrame> jacobian(\n      const std::array<T, 3>& source_coords) const noexcept;\n\n  template <typename T>\n  tnsr::Ij<tt::remove_cvref_wrap_t<T>, 3, Frame::NoFrame> inv_jacobian(\n      const std::array<T, 3>& source_coords) const noexcept;\n\n  void pup(PUP::er& p);  // NOLINT\n\n  bool is_identity() const noexcept { return is_identity_; }\n\n private:\n  friend bool operator==(const Rotation<3>& lhs,\n                         const Rotation<3>& rhs) noexcept;\n\n  double rotation_about_z_{std::numeric_limits<double>::signaling_NaN()};\n  double rotation_about_rotated_y_{\n      std::numeric_limits<double>::signaling_NaN()};\n  double rotation_about_rotated_z_{\n      std::numeric_limits<double>::signaling_NaN()};\n  tnsr::ij<double, 3, Frame::Grid> rotation_matrix_{\n      std::numeric_limits<double>::signaling_NaN()};\n  bool is_identity_{false};\n};\n\nbool operator!=(const Rotation<3>& lhs, const Rotation<3>& rhs) noexcept;\n\n}  // namespace CoordinateMaps\n}  // namespace domain\n", "meta": {"hexsha": "436e5bfd81530fc8e027ba73255f298e8924f4dd", "size": 5432, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Domain/CoordinateMaps/Rotation.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/Domain/CoordinateMaps/Rotation.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/Domain/CoordinateMaps/Rotation.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": 31.3988439306, "max_line_length": 75, "alphanum_fraction": 0.6747054492, "num_tokens": 1524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.6297746004557471, "lm_q1q2_score": 0.48434719901962914}}
{"text": "// This comes from the following Boost example:\n// https://www.boost.org/doc/libs/1_71_0/doc/html/boost_random/tutorial.html\n#include <boost/random/random_device.hpp>\n#include <boost/random/uniform_int_distribution.hpp>\n#include <iostream>\n\nint main() {\n    std::string chars(\n        \"abcdefghijklmnopqrstuvwxyz\"\n        \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n        \"1234567890\"\n        \"!@#$%^&*()\"\n        \"`~-_=+[{]}\\\\|;:'\\\",<.>/? \");\n    boost::random::random_device rng;\n    boost::random::uniform_int_distribution<> index_dist(0, chars.size() - 1);\n    for(int i = 0; i < 8; ++i) {\n        std::cout << chars[index_dist(rng)];\n    }\n    std::cout << std::endl;\n}\n", "meta": {"hexsha": "c00a15c076c364a2e070028a2cc483c8627f0202", "size": 662, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "recipes/boost/all/test_package/random.cpp", "max_stars_repo_name": "nadzkie0/conan-center-index", "max_stars_repo_head_hexsha": "fde12bf20f2c4cb6a7554d09a5c9433a0f5cb72c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-04-16T15:01:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T08:05:47.000Z", "max_issues_repo_path": "recipes/boost/all/test_package/random.cpp", "max_issues_repo_name": "nadzkie0/conan-center-index", "max_issues_repo_head_hexsha": "fde12bf20f2c4cb6a7554d09a5c9433a0f5cb72c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 33.0, "max_issues_repo_issues_event_min_datetime": "2020-02-18T15:54:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T08:54:10.000Z", "max_forks_repo_path": "recipes/boost/all/test_package/random.cpp", "max_forks_repo_name": "nadzkie0/conan-center-index", "max_forks_repo_head_hexsha": "fde12bf20f2c4cb6a7554d09a5c9433a0f5cb72c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2020-03-06T14:38:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T08:41:15.000Z", "avg_line_length": 31.5238095238, "max_line_length": 78, "alphanum_fraction": 0.6163141994, "num_tokens": 172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851918, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.484347197697209}}
{"text": "#include <stdio.h>\n#include <math.h>\n#include <iostream>\n#include <Eigen/SparseCore>\n#include <Eigen/Core>\n#include <SymEigsSolver.h>\n#include <MatOp/SparseSymMatProd.h>\n#include <time.h>\n#include <Python.h>\n#include <numpy/arrayobject.h>\nusing namespace Eigen;\nusing namespace Spectra;\n\n\nvoid make_top_eigenvectors(double *val,double *ind, int KK, int NN, int NK, double *eigenvectors,double *eigenvalues){\n    clock_t begin = clock();\n    Eigen::SparseMatrix<double> mat((const int) NN,(const int) NN);         // default is column major\n    mat.reserve(Eigen::VectorXi::Constant((const int) NN, (const int) NK));\n    typedef Eigen::Triplet<double> T;\n    std::vector<T> tripletList;\n    tripletList.reserve((const int) NN*NK);\n    for(int i=0; i<NN; i++){\n        for (int j = 0; j< NK; j++){\n            tripletList.push_back(T((int) ind[i*NK+j],i,val[i*NK+j]));\n            //std::cout << ind[i*NK+j] << std::endl << val[i*NK+j] << std::endl;\n        }\n    }\n    mat.setFromTriplets(tripletList.begin(), tripletList.end());\n    mat += Eigen::SparseMatrix<double>(mat.transpose());\n    clock_t end = clock();\n    //printf(\"Elapsed time in initialization is %f seconds\\n\", (double)(end - begin)/CLOCKS_PER_SEC);\n    SparseSymMatProd<double> op(mat);\n    begin = clock();\n    // Construct eigen solver object, requesting the largest KK eigenvalues\n    SymEigsSolver< double, LARGEST_ALGE, SparseSymMatProd<double> > eigs(&op, KK, 2*KK);\n    // Initialize and compute\n    eigs.init();\n    int nconv = eigs.compute();\n    // Retrieve results\n    \n    Eigen::VectorXd evalues;\n    Eigen::MatrixXd evectors;\n    if(eigs.info() == SUCCESSFUL){\n        evalues = eigs.eigenvalues();\n        evectors = eigs.eigenvectors();\n    }\n    //std::cout << \"Eigenvalues found:\\n\" << evalues << std::endl;\n    end = clock();\n    //printf(\"Elapsed time in eigen-decomposition is %f seconds\\n\", (double)(end - begin)/CLOCKS_PER_SEC);\n    ///\n    begin = clock();\n    for (int j = 0; j< KK; j++){\n        eigenvalues[j] = evalues[j];\n        for (int i = 0; i < NN; i++){\n            eigenvectors[i*KK+j] = evectors.col(j)[i];\n        }\n    }\n   end = clock();\n    //printf(\"Elapsed time in copying eigenvectors is %f seconds\\n\", (double)(end - begin)/CLOCKS_PER_SEC);\n    ///\n}\n\nPyObject * top_eig(PyObject *in0, PyObject *in1, PyObject *scal){\n//PyObject * top_eig(PyArrayObject *in0, PyArrayObject *in1, PyObject *scal){\n    //PyArrayObject *in0_arr = NULL;\n    PyArrayObject *in0_arr = (PyArrayObject *)in0;\n    //in0_arr = PyArray_GETCONTIGUOUS((PyArrayObject *)in0);\n    //in0_arr = PyArray_GETCONTIGUOUS(in0);\n\n    double *val = NULL;\n    val = (double *)PyArray_DATA(in0_arr);\n\n    //PyArrayObject *in1_arr = NULL;\n    PyArrayObject *in1_arr = (PyArrayObject *)in1;\n    //in1_arr = PyArray_GETCONTIGUOUS((PyArrayObject *)in1);\n    //in1_arr = PyArray_GETCONTIGUOUS(in1);\n\n    double *ind = NULL;\n    ind = (double *)PyArray_DATA(in1_arr);\n    \n    int KK = (int)PyLong_AsLong(scal);\n\n    int NN, NK;\n    npy_intp *dims = NULL;\n    dims = PyArray_DIMS(in0_arr);\n    NN = dims[0];\n\n    dims = PyArray_DIMS(in1_arr);\n    NK = dims[1];\n\n    dims[0] = (npy_intp)NN;\n    dims[1] = (npy_intp)KK;\n\n    PyObject *out1 = NULL;\n    out1 = PyArray_SimpleNew(2, dims, NPY_DOUBLE);\n\n    PyArrayObject *out1_arr = NULL;\n    out1_arr = PyArray_GETCONTIGUOUS((PyArrayObject *)out1);\n\n    double *eigenvectors = NULL;\n    eigenvectors = (double *)PyArray_DATA(out1_arr);\n\n    dims[0] = dims[1];\n    int tmp = 1;\n    dims[1] = (npy_intp)tmp;\n\n    PyObject *out2 = NULL;\n    out2 = PyArray_SimpleNew(2, dims, NPY_DOUBLE);\n\n    PyArrayObject *out2_arr = NULL;\n    out2_arr = PyArray_GETCONTIGUOUS((PyArrayObject *)out2);\n\n    double *eigenvalues = NULL;\n    eigenvalues = (double *)PyArray_DATA(out2_arr);\n\n    make_top_eigenvectors(val, ind, KK, NN, NK, eigenvectors, eigenvalues);\n\n    PyObject *outs;\n    outs = PyTuple_New(2);\n    PyTuple_SetItem(outs, 0, (PyObject *)out1_arr);\n    PyTuple_SetItem(outs, 1, (PyObject *)out2_arr);\n    return outs;\n}\n\nstatic PyObject * _top_eig(PyObject *self, PyObject *args){\n    PyObject *in0, *in1;\n    //PyArrayObject *in0, *in1;\n    PyObject *scal = NULL;\n    /*if (!PyArg_ParseTuple(args, \"O!O!O\", &PyArray_Type, &in0, &PyArray_Type, &in1, &scal)){\n        return NULL;\n    }*/\n    if (!PyArg_ParseTuple(args, \"OOO\", &in0, &in1, &scal)){\n        return NULL;\n    }\n\n    in0 = PyArray_FROM_OTF(in0, NPY_DOUBLE, NPY_ARRAY_IN_ARRAY);\n    in1 = PyArray_FROM_OTF(in1, NPY_DOUBLE, NPY_ARRAY_IN_ARRAY);\n\n    PyObject *out = NULL;\n    out = top_eig(in0, in1, scal);\n    return out;\n}\n\nstatic PyMethodDef topeigMethods[] = {\n    {\n        \"top_eig\", \n        _top_eig, \n        METH_VARARGS, \n        \"\"\n    }, \n    {NULL, NULL, 0, NULL}\n};\n\nstatic struct PyModuleDef topeigModule = {\n    PyModuleDef_HEAD_INIT, \n    \"topeigModule\", \n    NULL, \n    -1, \n    topeigMethods\n};\n\nPyMODINIT_FUNC PyInit_top_eig(void){\n    import_array();\n    return PyModule_Create(&topeigModule);\n}", "meta": {"hexsha": "1ca566b2255a2a873cc0927fc72c9ba5f2fa19c3", "size": 4982, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SIMLR/src/top_eig.cpp", "max_stars_repo_name": "5966466/SIMLR-python", "max_stars_repo_head_hexsha": "0ceb42ea4e766fd1a1bcbb1ee17af369dbc890c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-02-19T07:20:01.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-17T16:50:18.000Z", "max_issues_repo_path": "SIMLR/src/top_eig.cpp", "max_issues_repo_name": "5966466/SIMLR-python", "max_issues_repo_head_hexsha": "0ceb42ea4e766fd1a1bcbb1ee17af369dbc890c9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SIMLR/src/top_eig.cpp", "max_forks_repo_name": "5966466/SIMLR-python", "max_forks_repo_head_hexsha": "0ceb42ea4e766fd1a1bcbb1ee17af369dbc890c9", "max_forks_repo_licenses": ["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.1939393939, "max_line_length": 118, "alphanum_fraction": 0.6340826977, "num_tokens": 1513, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382236515259, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.48433654395178094}}
{"text": "//Link to Boost\n#define BOOST_TEST_DYN_LINK\n\n//Define our Module name (prints at testing)\n #define BOOST_TEST_MODULE Conformal Bootstrap UnitTests\n\n//VERY IMPORTANT - include this last\n#include <boost/test/unit_test.hpp>\n\n#include <iostream>\n#include <cmath>\n#include \"test.h\"\n#include \"../ConformalBlock.h\"\n#include \"../BootstrapRunner.h\"\n\nBOOST_AUTO_TEST_SUITE(demo_suite)\n\n//Name your test cases for what they test\nBOOST_AUTO_TEST_CASE(demo1, * utf::label(\"demo\"))\n{\n    int d = 4;\n    int l = 6;\n    int order = 7;\n    double dlt12 = 0.6;\n    double dlt34 = -0.3;\n    double r = 0.124;\n    double Pi = acos(-1.0);\n    double eta = cos(Pi/3);\n    double dlt = 8.3;\n    ConformalBlockScalars cb(d, dlt12, dlt34);\n    double res1 = cb.evaluate(dlt, l, r, eta, order);\n    std::cout << \"res1=\" << res1 << std::endl;\n\n    ConformalBlockScalars cb2(2, 0.01, 0.0);\n    float_type actual = cb2.evaluate(0.0, 0, r, eta, 20);\n    std::cout << \"actual=\" << actual << std::endl;\n\n    std::cout << cb2.dDelta(0.0, 0, r, eta, 15) << std::endl;\n    std::cout << cb2.dDelta12(0.0, 0, r, eta, 15) << std::endl;\n    std::cout << cb2.dDelta34(0.0, 0, r, eta, 15) << std::endl;\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "5e995057ab1dae283ea5cc6311b48df1911f6841", "size": 1193, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/Demo.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/test/Demo.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/test/Demo.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": 27.1136363636, "max_line_length": 63, "alphanum_fraction": 0.6387259011, "num_tokens": 400, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412808, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.48433653995456827}}
{"text": "#include \"global_constants.hh\"\n#include \"aux.hh\"\n#include \"stochastic.hh\"\n#include \"matrix/utility.hh\"\n\n#include \"cad_utility.hh\"\n\n\n#include <armadillo>\n\n#include \"Ins.hh\"\n#include \"GPS.hh\"\nGPS_FSW::GPS_FSW()\n:   time(time_management::get_instance()),\n    MATRIX_INIT(FF, 8, 8),\n    MATRIX_INIT(PHI, 8, 8),\n    MATRIX_INIT(PP, 8, 8),\n    MATRIX_INIT(PP0, 8, 8),\n    VECTOR_INIT(SXH, 3),\n    VECTOR_INIT(VXH, 3),\n    VECTOR_INIT(CXH, 3),\n    VECTOR_INIT(ZZ, 8),\n    VECTOR_INIT(WEII, 3)\n{}\n\nGPS_FSW::GPS_FSW(const GPS_FSW &other)\n:   time(time_management::get_instance()),\n    MATRIX_INIT(FF, 8, 8),\n    MATRIX_INIT(PHI, 8, 8),\n    MATRIX_INIT(PP, 8, 8),\n    MATRIX_INIT(PP0, 8, 8),\n    VECTOR_INIT(SXH, 3),\n    VECTOR_INIT(VXH, 3),\n    VECTOR_INIT(CXH, 3),\n    VECTOR_INIT(ZZ, 8),\n    VECTOR_INIT(WEII, 3)\n{}\n\nGPS_FSW & GPS_FSW::operator= (const GPS_FSW &other) {\n    if (&other == this)\n        return *this;\n\n    return *this;\n}\n\n\nvoid GPS_FSW::setup_state_covariance_matrix(double factp, double pclockb, double pclockf) {\n    PP = arma::mat88(arma::fill::zeros);\n    for (int i = 0; i < 3; i++) {\n        PP(i, i)         = pow(ppos * (1 + factp), 2);\n        PP(i + 3, i + 3) = pow(pvel * (1 + factp), 2);\n    }\n    PP(6, 6) =  pow(pclockb * (1 + factp), 2);\n    PP(7, 7) =  pow(pclockf * (1 + factp), 2);\n\n    return;\n}\n\nvoid GPS_FSW::setup_error_covariance_matrix(double factq, double qclockb, double qclockf) {\n    this->factq = factq;\n    this->qclockb = qclockb;\n    this->qclockf = qclockf;\n\n    return;\n}\n\nvoid GPS_FSW::setup_fundamental_dynamic_matrix(double uctime_cor) {\n    // fundamental dynamic matrix of filter - constant throughout\n    FF = arma::mat88(arma::fill::zeros);\n    FF(0, 3) = 1;\n    FF(1, 4) = 1;\n    FF(2, 5) = 1;\n    FF(6, 7) = 1;\n    FF(7, 7) = -1 / uctime_cor;\n\n    return;\n}\n\n\nvoid GPS_FSW::initialize(double int_step) {\n    // state transition matrix - constant throughout\n    PHI = arma::mat88(arma::fill::eye) + FF * int_step + FF * FF * (int_step * int_step / 2);\n    this->WEII.zeros();\n    // Due to RNP so that earth rate have 3 axis components\n    this->WEII(0) = WEII1;\n    this->WEII(1) = WEII2;\n    this->WEII(2) = WEII3;\n    // initializing update clock\n    // gps_epoch = get_elapsed_time();\n}\n\n\n\nvoid GPS_FSW::filter_extrapolation(double int_step) {\n    arma::mat88 QQ(arma::fill::zeros);  // local\n\n    //*** user-clock frequency and bias error growth between updates ***\n    // integrating 'ucfreq_noise' Markov process to\n    //  obtain user-clock bias error 'ucbias_error' (trapezoidal\n    //  integration)\n    // user-clock bias is updated at filter update epoch\n    ucfreq_error = ucfreq_noise;\n    ucbias_error = ucbias_error + (ucfreq_error + ucfreqm) * (int_step / 2);\n    ucfreqm = ucfreq_error;\n\n    //*** filter extrapolation ***\n    // dynamic error covariance matrix\n    for (int i = 0; i < 3; i++) {\n        QQ(i, i)         = pow(qpos * (1 + factq), 2);\n        QQ(i + 3, i + 3) = pow(qvel * (1 + factq), 2);\n    }\n    QQ(6, 6) = pow(qclockb * (1 + factq), 2);\n    QQ(7, 7) = pow(qclockf * (1 + factq), 2);\n\n    // covariance estimate extrapolation\n    PP = PHI * (PP + QQ * (int_step / 2)) * trans(PHI) + QQ * (int_step / 2);\n\n    // diagnostics: st. deviations of the diagonals of the covariance matrix\n    std_pos = sqrt(PP(0, 0));\n    std_vel = sqrt(PP(3, 3));\n    std_ucbias = sqrt(PP(6, 6));\n}\n\n\n\nvoid GPS_FSW::measure(double int_step) {\n    // double dtime_gps;\n    // /* Testing GPS timing for update and acquire */\n    // if(!gps_acq)\n    //     // saving delay-time for GPS signal acquisition\n    //     dtime_gps = gps_acqtime;\n    // else\n    //     // saving delay-time for GPS update\n    //     dtime_gps = gps_step;\n    // // checking when GPS update time has occured in order to initiate update\n    // time_gps = get_elapsed_time() - gps_epoch;\n    // if (time_gps < dtime_gps) {\n    //     return;\n    // }\n    gps_step = int_step;\n    // gps_acq = true;\n    // gps_update = 1;\n    // // resetting update clock\n    // time_gps = 0;\n    // gps_epoch = get_elapsed_time();\n\n    // /* GPS Update and Measurement */\n    // double slotm(0);\n\n    // arma::vec8 ZZ(arma::fill::zeros);\n    arma::vec8 XH(arma::fill::zeros);           // local\n    arma::mat88 RR(arma::fill::zeros);          // local\n    arma::mat88 HH(arma::fill::zeros);          // local\n    arma::vec3 pos(arma::fill::zeros);\n    arma::vec3 vel(arma::fill::zeros);\n    arma::vec2 clk(arma::fill::zeros);\n\n    // arma::vec4 pesudo_range(arma::fill::zeros);\n    // arma::vec4 pesudo_range_rate(arma::fill::zeros);\n    arma::vec4 channel_id(arma::fill::zeros);\n    arma::mat33 TEIC = grab_TEIC();\n\n    transmit_channel* trans_chan = grab_transmit_data();\n    // arma::mat33 TEI = environment->get_TEI();\n    int ii(0);\n  // Pseudo-range and range-rate measurements\n    for (int i = 0; i < MAX_CHAN; i++) {\n        if (trans_chan[i].prn > 0) {\n            // pesudo_range(ii) = gps_con->chan[i].rho0.range;\n            // pesudo_range_rate(ii) = gps_con->chan[i].rho0.rate;\n            channel_id(ii) = i;\n            if (ii == 3) break;\n            ii++;\n        }\n    }\n\n    // arma::vec3 SBII = newton->get_SBII();\n    // arma::vec3 VBII = newton->get_VBII();\n    // arma::vec3 WEII = euler->get_WEII();\n\n    arma::vec3 SBIIC = grab_SBIIC();\n    arma::vec3 VBIIC = grab_VBIIC();\n    arma::vec3 WBICI = grab_WBICI();\n    arma::vec3 SBEEC = grab_SBEEC();\n    arma::vec3 VBEEC = grab_VBEEC();\n\n    // Pseudo-range and range-rate measurements\n    for (int i = 0; i < 4; i++) {\n        // unpacking i-th SV information\n        int id(channel_id(i));\n\n\n        // double dsb = gps_con->chan[id].rho0.range;\n        // // measured pseudo-range\n        // double dsb_meas = dsb ;//+ PR_BIAS[i] + PR_NOISE[i];// + ucbias_error;\n\n\n        // double dvsb = gps_con->chan[id].rho0.rate;\n        // // measured delta-range rate\n        // double dvsb_meas = dvsb ;//+ DR_NOISE[i] ;//+ ucfreq_error;\n\n\n\n        // // INS derived range measurements\n        // arma::vec3 SSBIC;\n        // // SSBIC = (trans(TEIC) * gps_con->chan[id].rho0.pos - SBIIC)- SPEED_OF_LIGHT * gps_con->chan[id].rho0.clk(0);\n        // SSBIC = (gps_con->chan[id].rho0.pos - SBEEC);\n        // double dsbc = norm(SSBIC) - SPEED_OF_LIGHT * gps_con->chan[id].rho0.clk(0);\n\n        // arma::vec3 USSBI;\n        // USSBI = SSBIC/norm(SSBIC);\n\n        // // double dvsbc = dot(trans(TEIC) * (gps_con->chan[i].rho0.vel + cross(WEII, gps_con->chan[id].rho0.pos)), (trans(TEIC) * gps_con->chan[id].rho0.pos - SBIIC))/dsbc;\n        // double dvsbc = dot(gps_con->chan[i].rho0.vel , SSBIC)/dsbc;\n\n        // Pesudo-range on ECI/////////////////////////////////////////////////////////////////////////\n        // arma::vec3 SSBI;\n        // SSBI = (trans(TEIC) * gps_con->chan[id].rho0.pos - SBIIC);\n\n\n        for (int j = 0; j < 3; j++) {\n            pos(j) = trans_chan[id].pos[j];\n            vel(j) = trans_chan[id].vel[j];\n        }\n        for (int k = 0; k < 2; k++) {\n            clk(k) = trans_chan[id].clk[k];\n        }\n\n        arma::vec3 SSBIC;\n        SSBIC = (trans(TEIC) * pos - SBIIC);\n\n        double dsb_meas = trans_chan[id].range;  // norm(SSBI) - SPEED_OF_LIGHT * gps_con->chan[id].rho0.clk(0);\n\n        arma::vec3 velECI;\n        velECI = trans(TEIC) * (vel + cross(WEII, pos));\n\n        double dvsb_meas = dot(velECI, SSBIC)/dsb_meas;\n        /////////////////////////////////////////////////////////////////////////////////////////////////\n\n        double dsbc = norm(SSBIC) - SPEED_OF_LIGHT * clk(0);\n\n        double dvsbc = dot(velECI, SSBIC)/dsbc;\n\n        arma::vec3 USSBI;\n        USSBI = SSBIC/norm(SSBIC);\n\n\n        ZZ[i] = dsb_meas - dsbc;\n        ZZ[i + 4] = dvsb_meas - dvsbc;\n\n        // observation matrix of filter\n        for (int j = 0; j < 3; j++) {\n            HH(i, j) = USSBI(j);\n            HH(i + 4, j + 3) = USSBI(j) * gps_step;\n        }\n        HH(i, 6) = 1;\n        HH(i + 4, 7) = gps_step;\n\n        // for diagnostics: loading the 4 SV slot # of the quadriga\n        // *(slot + i) = *(ssii_quad + 4 * i + 3);\n        // // accumulating sum of slots\n        // slotm = slotm + slot[i];\n    }\n    // for diagnostics displaying the SV slot# of the quadriga on the\n    // console\n    // but only if they have changed (i.e., sum of slot# has changed)\n\n    // if (slotsum != slotm) {\n    //     slotsum = slotm;\n    //     std::cout << \" *** GPS Quadriga slot # \" << slot[0] << \"  \"\n    //               << slot[1] << \"  \" << slot[2] << \"  \" << slot[3]\n    //               << \" ;  GDOP = \" << gdop << \" m ***\\n\";\n    // }\n    //*** filter correction and update (to INS: 'SXH' and 'VXH') ***\n    // filter gain\n    arma::mat88 KK(arma::fill::zeros);\n    arma::mat88 E(arma::fill::eye);\n    // measurement noise covariance matrix\n    for (int i = 0; i < 4; i++) {\n        RR(i, i) = pow(rpos * (1 + factr), 2);\n        RR(i + 4, i + 4) = pow(rvel * (1 + factr), 2);\n    }\n    // Kalman gain\n    KK = PP * trans(HH) * inv(HH * PP * trans(HH) + RR);\n    // state correction\n    XH = KK * ZZ;\n    // covariance correction for next cycle\n    PP = (E - KK * HH) * PP;\n\n    // clock error bias update\n    ucbias_error = ucbias_error - XH(6, 0);\n\n    // diagnostics of 1st SV of quadriga saved to plot file\n    gps_pos_meas = ZZ(0, 0);\n    gps_vel_meas = ZZ(4, 0);\n\n    // decomposing state vector for output\n    for (int m = 0; m < 3; m++) {\n        SXH(m, 0) = XH(m, 0);\n        VXH(m, 0) = XH(m + 3, 0);\n    }\n    CXH(0, 0) = XH(6, 0);\n    CXH(1, 0) = XH(7, 0);\n\n    // diagnostic\n    state_pos = norm(SXH);\n    state_vel = norm(VXH);\n}\n\narma::vec3 GPS_FSW::get_SXH() { return SXH; }\narma::vec3 GPS_FSW::get_VXH() { return VXH; }\narma::vec3 GPS_FSW::get_CXH() { return CXH; }\n", "meta": {"hexsha": "217f0e22692be54347bdae8b4edf945353fbae25", "size": 9708, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "models/gnc/src/GPS.cpp", "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/gnc/src/GPS.cpp", "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/gnc/src/GPS.cpp", "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": 31.0159744409, "max_line_length": 175, "alphanum_fraction": 0.548104656, "num_tokens": 3175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4843365359573555}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n\r\n// Copyright (c) 2007-2011 Barend Gehrels, Amsterdam, the Netherlands.\r\n// Copyright (c) 2008-2011 Bruno Lalande, Paris, France.\r\n// Copyright (c) 2009-2011 Mateusz Loskot, London, UK.\r\n\r\n// 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// Linestring Example\r\n\r\n#include <algorithm> // for reverse, unique\r\n#include <iostream>\r\n#include <iterator>\r\n#include <utility>\r\n#include <vector>\r\n\r\n#include <boost/geometry/geometry.hpp>\r\n#include <boost/geometry/geometries/linestring.hpp>\r\n#include <boost/geometry/geometries/point_xy.hpp>\r\n#include <boost/geometry/geometries/polygon.hpp>\r\n\r\n// Optional includes and defines to handle c-arrays as points, std::vectors as linestrings\r\n#include <boost/geometry/geometries/register/linestring.hpp>\r\n#include <boost/geometry/geometries/adapted/c_array.hpp>\r\n\r\nBOOST_GEOMETRY_REGISTER_C_ARRAY_CS(cs::cartesian)\r\n\r\nBOOST_GEOMETRY_REGISTER_LINESTRING_TEMPLATED(std::vector)\r\nBOOST_GEOMETRY_REGISTER_LINESTRING_TEMPLATED(std::deque)\r\n\r\n\r\ntemplate<typename P>\r\ninline void translate_function(P& p)\r\n{\r\n        p.x(p.x() + 100.0);\r\n}\r\n\r\ntemplate<typename P>\r\nstruct scale_functor\r\n{\r\n    inline void operator()(P& p)\r\n    {\r\n        p.x(p.x() * 1000.0);\r\n        p.y(p.y() * 1000.0);\r\n    }\r\n};\r\n\r\n\r\ntemplate<typename Point>\r\nstruct round_coordinates\r\n{\r\n    typedef typename boost::geometry::coordinate_type<Point>::type coordinate_type;\r\n    coordinate_type m_factor;\r\n\r\n    inline round_coordinates(coordinate_type const& factor)\r\n        : m_factor(factor)\r\n    {}\r\n\r\n    template <int Dimension>\r\n    inline void round(Point& p)\r\n    {\r\n        coordinate_type c = boost::geometry::get<Dimension>(p) / m_factor;\r\n        int rounded = c;\r\n        boost::geometry::set<Dimension>(p, coordinate_type(rounded) * m_factor);\r\n    }\r\n\r\n    inline void operator()(Point& p)\r\n    {\r\n        round<0>(p);\r\n        round<1>(p);\r\n    }\r\n};\r\n\r\n\r\nint main(void)\r\n{\r\n    using namespace boost::geometry;\r\n\r\n    // Define a linestring, which is a vector of points, and add some points\r\n    // (we add them deliberately in different ways)\r\n    typedef model::d2::point_xy<double> point_2d;\r\n    typedef model::linestring<point_2d> linestring_2d;\r\n    linestring_2d ls;\r\n\r\n    // points can be created using \"make\" and added to a linestring using the std:: \"push_back\"\r\n    ls.push_back(make<point_2d>(1.1, 1.1));\r\n\r\n    // points can also be assigned using \"assign_values\" and added to a linestring using \"append\"\r\n    point_2d lp;\r\n    assign_values(lp, 2.5, 2.1);\r\n    append(ls, lp);\r\n\r\n    // Lines can be streamed using DSV (delimiter separated values)\r\n    std::cout << dsv(ls) << std::endl;\r\n\r\n    // The bounding box of linestrings can be calculated\r\n    typedef model::box<point_2d> box_2d;\r\n    box_2d b;\r\n    envelope(ls, b);\r\n    std::cout << dsv(b) << std::endl;\r\n\r\n    // The length of the line can be calulated\r\n    std::cout << \"length: \" << length(ls) << std::endl;\r\n\r\n    // All things from std::vector can be called, because a linestring is a vector\r\n    std::cout << \"number of points 1: \" << ls.size() << std::endl;\r\n\r\n    // All things from boost ranges can be called because a linestring is considered as a range\r\n    std::cout << \"number of points 2: \" << boost::size(ls) << std::endl;\r\n\r\n    // Generic function from geometry/OGC delivers the same value\r\n    std::cout << \"number of points 3: \" << num_points(ls) << std::endl;\r\n\r\n    // The distance from a point to a linestring can be calculated\r\n    point_2d p(1.9, 1.2);\r\n    std::cout << \"distance of \" << dsv(p)\r\n        << \" to line: \" << distance(p, ls) << std::endl;\r\n\r\n    // A linestring is a vector. However, some algorithms consider \"segments\",\r\n    // which are the line pieces between two points of a linestring.\r\n    double d = distance(p, model::segment<point_2d >(ls.front(), ls.back()));\r\n    std::cout << \"distance: \" << d << std::endl;\r\n\r\n    // Add some three points more, let's do it using a classic array.\r\n    // (See documentation for picture of this linestring)\r\n    const double c[][2] = { {3.1, 3.1}, {4.9, 1.1}, {3.1, 1.9} };\r\n    append(ls, c);\r\n    std::cout << \"appended: \" << dsv(ls) << std::endl;\r\n\r\n    // Output as iterator-pair on a vector\r\n    {\r\n        std::vector<point_2d> v;\r\n        std::copy(ls.begin(), ls.end(), std::back_inserter(v));\r\n\r\n        std::cout\r\n            << \"as vector: \"\r\n            << dsv(v)\r\n            << std::endl;\r\n    }\r\n\r\n    // All algorithms from std can be used: a linestring is a vector\r\n    std::reverse(ls.begin(), ls.end());\r\n    std::cout << \"reversed: \" << dsv(ls) << std::endl;\r\n    std::reverse(boost::begin(ls), boost::end(ls));\r\n\r\n    // The other way, using a vector instead of a linestring, is also possible\r\n    std::vector<point_2d> pv(ls.begin(), ls.end());\r\n    std::cout << \"length: \" << length(pv) << std::endl;\r\n\r\n    // If there are double points in the line, you can use unique to remove them\r\n    // So we add the last point, print, make a unique copy and print\r\n    {\r\n        // (sidenote, we have to make copies, because\r\n        // ls.push_back(ls.back()) often succeeds but\r\n        // IS dangerous and erroneous!\r\n        point_2d last = ls.back(), first = ls.front();\r\n        ls.push_back(last);\r\n        ls.insert(ls.begin(), first);\r\n    }\r\n    std::cout << \"extra duplicate points: \" << dsv(ls) << std::endl;\r\n\r\n    {\r\n        linestring_2d ls_copy;\r\n        std::unique_copy(ls.begin(), ls.end(), std::back_inserter(ls_copy),\r\n            boost::geometry::equal_to<point_2d>());\r\n        ls = ls_copy;\r\n        std::cout << \"uniquecopy: \" << dsv(ls) << std::endl;\r\n    }\r\n\r\n    // Lines can be simplified. This removes points, but preserves the shape\r\n    linestring_2d ls_simplified;\r\n    simplify(ls, ls_simplified, 0.5);\r\n    std::cout << \"simplified: \" << dsv(ls_simplified) << std::endl;\r\n\r\n\r\n    // for_each:\r\n    // 1) Lines can be visited with std::for_each\r\n    // 2) for_each_point is also defined for all geometries\r\n    // 3) for_each_segment is defined for all geometries to all segments\r\n    // 4) loop is defined for geometries to visit segments\r\n    //    with state apart, and to be able to break out (not shown here)\r\n    {\r\n        linestring_2d lscopy = ls;\r\n        std::for_each(lscopy.begin(), lscopy.end(), translate_function<point_2d>);\r\n        for_each_point(lscopy, scale_functor<point_2d>());\r\n        for_each_point(lscopy, translate_function<point_2d>);\r\n        std::cout << \"modified line: \" << dsv(lscopy) << std::endl;\r\n    }\r\n\r\n    // Lines can be clipped using a clipping box. Clipped lines are added to the output iterator\r\n    box_2d cb(point_2d(1.5, 1.5), point_2d(4.5, 2.5));\r\n\r\n    std::vector<linestring_2d> clipped;\r\n    intersection(cb, ls, clipped);\r\n\r\n    // Also possible: clip-output to a vector of vectors\r\n    std::vector<std::vector<point_2d> > vector_out;\r\n    intersection(cb, ls, vector_out);\r\n\r\n    std::cout << \"clipped output as vector:\" << std::endl;\r\n    for (std::vector<std::vector<point_2d> >::const_iterator it\r\n            = vector_out.begin(); it != vector_out.end(); ++it)\r\n    {\r\n        std::cout << dsv(*it) << std::endl;\r\n    }\r\n\r\n    // Calculate the convex hull of the linestring\r\n    model::polygon<point_2d> hull;\r\n    convex_hull(ls, hull);\r\n    std::cout << \"Convex hull:\" << dsv(hull) << std::endl;\r\n\r\n    // All the above assumed 2D Cartesian linestrings. 3D is possible as well\r\n    // Let's define a 3D point ourselves, this time using 'float'\r\n    typedef model::point<float, 3, cs::cartesian> point_3d;\r\n    model::linestring<point_3d> line3;\r\n    line3.push_back(make<point_3d>(1,2,3));\r\n    line3.push_back(make<point_3d>(4,5,6));\r\n    line3.push_back(make<point_3d>(7,8,9));\r\n\r\n    // Not all algorithms work on 3d lines. For example convex hull does NOT.\r\n    // But, for example, length, distance, simplify, envelope and stream do.\r\n    std::cout << \"3D: length: \" << length(line3) << \" line: \" << dsv(line3) << std::endl;\r\n\r\n    // With DSV you can also use other delimiters, e.g. JSON style\r\n    std::cout << \"JSON: \"\r\n        << dsv(ls, \", \", \"[\", \"]\", \", \", \"[ \", \" ]\")\r\n        << std::endl;\r\n\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "c6e5d2d71e75181cb06647aa58535d1a888be656", "size": 8315, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/example/02_linestring_example.cpp", "max_stars_repo_name": "Ron2014/boost_1_48_0", "max_stars_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "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/geometry/example/02_linestring_example.cpp", "max_issues_repo_name": "Ron2014/boost_1_48_0", "max_issues_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "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/geometry/example/02_linestring_example.cpp", "max_forks_repo_name": "Ron2014/boost_1_48_0", "max_forks_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.686695279, "max_line_length": 98, "alphanum_fraction": 0.6228502706, "num_tokens": 2265, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587586, "lm_q2_score": 0.6926419894793248, "lm_q1q2_score": 0.484332973354352}}
{"text": "/*\n * Copyright (c) 2013-2014 Masahide Kashiwagi (kashi@waseda.jp)\n */\n\n#ifndef ODE_AUTODIF_NV_HPP\n#define ODE_AUTODIF_NV_HPP\n\n// ODE (input and output : autodif type) (not verified)\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/psa.hpp>\n#include <kv/autodif.hpp>\n#include <kv/ode-param.hpp>\n\n\n#ifndef ODE_FAST\n#define ODE_FAST 1\n#endif\n\n\nnamespace kv {\n\nnamespace ub = boost::numeric::ublas;\n\n\ntemplate <class T, class F>\nvoid\node_nv(F f, ub::vector< autodif<T> >& init, const T& start, T& end, ode_param<T> p = ode_param<T>()) {\n\tint n = init.size();\n\tint i, j, k, km;\n\n\tub::vector< psa< autodif<T> > > x, y;\n\tpsa< autodif<T> > torg;\n\tpsa< autodif<T> > t;\n\n\tT deltat;\n\tub::vector< autodif<T> > result, new_init;\n\n\tT m;\n\n\tT radius, radius_tmp;\n\tT tolerance;\n\tint n_rad;\n\n\tub::matrix<T> save;\n\n\tbool save_mode, save_uh, save_rh;\n\n\tnew_init = autodif<T>::compress(init, save);\n\n\tm = 1.;\n\tfor (i=0; i<n; i++) {\n\t\tusing std::abs;\n\t\tm = std::max(m, abs(new_init(i).v));\n\t\tnew_init(i).d.resize(n);\n\t\tfor (j=0; j<n; j++) {\n\t\t\tusing std::abs;\n\t\t\tm = std::max(m, abs(new_init(i).d(j)));\n\t\t}\n\t}\n\ttolerance = m * p.epsilon;\n\n\tx = new_init;\n\ttorg.v.resize(2);\n\ttorg.v(0) = start; torg.v(1) = 1.;\n\n\tsave_mode = psa< autodif<T> >::mode();\n\tsave_uh = psa< autodif<T> >::use_history();\n\tsave_rh = psa< autodif<T> >::record_history();\n\tpsa< autodif<T> >::mode() = 1;\n\tpsa< autodif<T> >::use_history() = false;\n\tpsa< autodif<T> >::record_history() = false;\n\t#if ODE_FAST == 1\n\tpsa< autodif<T> >::record_history() = true;\n\tpsa< autodif<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< autodif<T> >::use_history() = true;\n\t\tif (j == p.order - 1) psa< autodif<T> >::record_history() = false;\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 = new_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\tusing std::abs;\n\t\t\t\tm = std::max(m, abs(x(i).v(j).v));\n\t\t\t\t#ifdef IGNORE_DIF_PART\n\t\t\t\t#else\n\t\t\t\tkm = x(i).v(j).d.size();\n\t\t\t\tfor (k=0; k<km; k++) {\n\t\t\t\t\tusing std::abs;\n\t\t\t\t\tm = std::max(m, abs(x(i).v(j).d(k)));\n\t\t\t\t}\n\t\t\t\t#endif\n\t\t\t}\n\t\t\tif (m == 0.) continue;\n\t\t\tradius_tmp = std::pow((double)m, 1./j);\n\t\t\tif (radius_tmp > radius) radius = radius_tmp;\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\tdeltat = end - start;\n\n\tif (p.autostep && radius < deltat) {\n\t\tend = start + radius;\n\t\tdeltat = end - start;\n\t}\n\n\tresult.resize(n);\n\tfor (i=0; i<n; i++) {\n\t\tresult(i) = eval(x(i), (autodif<T>)deltat);\n\t\tresult(i).d.resize(n);\n\t\tresult(i) = autodif<T>::expand(result(i), save);\n\t}\n\n\tinit = result;\n\n\tpsa< autodif<T> >::mode() = save_mode;\n\tpsa< autodif<T> >::use_history() = save_uh;\n\tpsa< autodif<T> >::record_history() = save_rh;\n}\n\n\ntemplate <class T, class F>\nvoid\nodelong_nv(F f, ub::vector< autodif<T> >& init, const T& start, const T& end, ode_param<T> p = ode_param<T>()) {\n\n\tub::vector< autodif<T> > x;\n\tT t, t1;\n\n\tx = init;\n\tt = start;\n\tp.set_autostep(true);\n\twhile (1) {\n\t\tt1 = end;\n\t\tif (t == t1) break;\n\n\t\tode_nv(f, x, t, t1, p);\n\n\t\tif (p.verbose == 1) {\n\t\t\tstd::cout << \"t: \" << t1 << \"\\n\";\n\t\t\tstd::cout << x << \"\\n\";\n\t\t}\n\n\t\tt = t1;\n\t}\n\n\tinit = x;\n}\n\n} // namespace kv\n\n#endif // ODE_AUTODIF_NV_HPP\n", "meta": {"hexsha": "763191463a9b6c52f1af3b9a216d32b14f1a3d62", "size": 3523, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "kv/ode-autodif-nv.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-autodif-nv.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-autodif-nv.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": 20.2471264368, "max_line_length": 112, "alphanum_fraction": 0.5773488504, "num_tokens": 1311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.4843329732589063}}
{"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#include <boost/simd/pack.hpp>\n#include <boost/simd/function/ulpdist.hpp>\n#include <boost/simd/meta/cardinal_of.hpp>\n#include <simd_test.hpp>\n#include <boost/simd/constant/inf.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/zero.hpp>\n\ntemplate <typename T, std::size_t N, typename Env>\nvoid test(Env& $)\n{\n  namespace bs = boost::simd;\n  using p_t = bs::pack<T, N>;\n\n  T a1[N], a2[N], b[N];\n  for(std::size_t i = 0; i < N; ++i)\n  {\n     a1[i] = (i%2) ? T(i) : T(-i);\n     a2[i] = (i%2) ? T(i+N) : T(-(i+N));\n     b[i] = bs::ulpdist(a1[i], a2[i]);\n   }\n  p_t aa1(&a1[0], &a1[0]+N);\n  p_t aa2(&a2[0], &a2[0]+N);\n  p_t bb(&b[0], &b[0]+N);\n  STF_IEEE_EQUAL(bs::ulpdist(aa1, aa2), bb);\n}\n\nSTF_CASE_TPL(\"Check ulpdist on pack\" , STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  using p_t = bs::pack<T>;\n  static const std::size_t N = bs::cardinal_of<p_t>::value;\n  test<T, N>($);\n  test<T, N/2>($);\n  test<T, N*2>($);\n}\n\n\n\nSTF_CASE_TPL (\" ulpdist real\",  STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::ulpdist;\n  using p_t = bs::pack<T>;\n\n\n  STF_EXPR_IS( ulpdist(p_t(), p_t()), p_t);\n\n#ifndef BOOST_SIMD_NO_INVALIDS\n  STF_EQUAL(ulpdist(bs::Inf<p_t>(), bs::Inf<p_t>()), bs::Zero<p_t>());\n  STF_EQUAL(ulpdist(bs::Minf<p_t>(), bs::Minf<p_t>()), bs::Zero<p_t>());\n  STF_EQUAL(ulpdist(bs::Nan<p_t>(), bs::Nan<p_t>()), bs::Zero<p_t>());\n#endif\n\n  STF_EQUAL(ulpdist(bs::Mone<p_t>(), bs::Mone<p_t>()), bs::Zero<p_t>());\n  STF_EQUAL(ulpdist(bs::One<p_t>(), bs::One<p_t>()), bs::Zero<p_t>());\n  STF_EQUAL(ulpdist(bs::Zero<p_t>(), bs::Zero<p_t>()), bs::Zero<p_t>());\n\n  STF_EQUAL( ulpdist(bs::One<p_t>(), bs::One<p_t>()+bs::Eps<p_t>())\n                , p_t(0.5)\n                );\n\n  STF_EQUAL( ulpdist(bs::One<p_t>(), bs::One<p_t>()-bs::Eps<p_t>())\n                , p_t(0.5)\n                );\n\n  STF_EQUAL( ulpdist(bs::One<p_t>(), bs::One<p_t>()-bs::Eps<p_t>()/2)\n                , p_t(0.25)\n                );\n}\n\nSTF_CASE_TPL (\" ulpdist signed_integral\",  STF_SIGNED_INTEGRAL_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::ulpdist;\n  using p_t = bs::pack<T>;\n\n\n  STF_EXPR_IS( ulpdist(p_t(), p_t()), p_t);\n\n  STF_EQUAL(ulpdist(bs::Mone<p_t>(), bs::Mone<p_t>()), bs::Zero<p_t>());\n  STF_EQUAL(ulpdist(bs::One<p_t>(), bs::One<p_t>()), bs::Zero<p_t>());\n  STF_EQUAL(ulpdist(bs::Zero<p_t>(), bs::Zero<p_t>()), bs::Zero<p_t>());\n\n  STF_EQUAL( ulpdist(bs::Zero<p_t>(), bs::Valmin<p_t>())\n                , bs::Valmax<p_t>()\n                );\n\n  STF_EQUAL( ulpdist(bs::Valmin<p_t>(), bs::Zero<p_t>())\n                , bs::Valmax<p_t>()\n                );\n\n  STF_EQUAL( ulpdist(bs::Zero<p_t>(), bs::Valmax<p_t>())\n                , bs::Valmax<p_t>()\n                );\n\n  STF_EQUAL( ulpdist(bs::Valmax<p_t>(), bs::Zero<p_t>())\n                , bs::Valmax<p_t>()\n                );\n\n  STF_EQUAL( ulpdist(bs::Valmin<p_t>(), bs::Valmax<p_t>())\n                , bs::Valmax<p_t>()\n                );\n}\n\nSTF_CASE_TPL (\" ulpdist unsigned_integral\",  STF_UNSIGNED_INTEGRAL_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::ulpdist;\n  using p_t = bs::pack<T>;\n\n\n  STF_EXPR_IS( ulpdist(p_t(), p_t()), p_t);\n\n  STF_EQUAL(ulpdist(bs::Mone<p_t>(), bs::Mone<p_t>()), bs::Zero<p_t>());\n  STF_EQUAL(ulpdist(bs::One<p_t>(), bs::One<p_t>()), bs::Zero<p_t>());\n  STF_EQUAL(ulpdist(bs::Zero<p_t>(), bs::Zero<p_t>()), bs::Zero<p_t>());\n\n  STF_EQUAL( ulpdist(bs::Zero<p_t>(), bs::Valmin<p_t>())\n                , bs::Zero<p_t>()\n                );\n\n  STF_EQUAL( ulpdist(bs::Valmin<p_t>(), bs::Zero<p_t>())\n                , bs::Zero<p_t>()\n                );\n\n  STF_EQUAL( ulpdist(bs::Zero<p_t>(), bs::Valmax<p_t>())\n                , bs::Valmax<p_t>()\n                );\n\n  STF_EQUAL( ulpdist(bs::Valmax<p_t>(), bs::Zero<p_t>())\n                , bs::Valmax<p_t>()\n                );\n\n  STF_EQUAL( ulpdist(bs::Valmin<p_t>(), bs::Valmax<p_t>())\n                , bs::Valmax<p_t>()\n                );\n}\n\n\n", "meta": {"hexsha": "26f5c53195a36b245d6bf5d78d197ea3871d66bc", "size": 4522, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/simd/ulpdist.cpp", "max_stars_repo_name": "nickporubsky/boost-simd-clone", "max_stars_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_stars_repo_licenses": ["BSL-1.0"], "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": "test/function/simd/ulpdist.cpp", "max_issues_repo_name": "nickporubsky/boost-simd-clone", "max_issues_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "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/function/simd/ulpdist.cpp", "max_forks_repo_name": "nickporubsky/boost-simd-clone", "max_forks_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_forks_repo_licenses": ["BSL-1.0"], "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": 28.8025477707, "max_line_length": 100, "alphanum_fraction": 0.5289694825, "num_tokens": 1450, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.48433296891787025}}
{"text": "<<<<<<< HEAD\n/*    Copyright (c) 2010-2018, Delft University of Technology\n=======\n/*    Copyright (c) 2010-2019, Delft University of Technology\n>>>>>>> origin/master\n *    All rigths reserved\n *\n *    This file is part of the Tudat. Redistribution and use in source and\n *    binary forms, with or without modification, are permitted exclusively\n *    under the terms of the Modified BSD license. You should have received\n *    a copy of the license with this file. If not, please or visit:\n *    http://tudat.tudelft.nl/LICENSE.\n */\n\n#define BOOST_TEST_MAIN\n\n#include <vector>\n#include <limits>\n\n#include <Eigen/Core>\n\n#include <boost/test/unit_test.hpp>\n#include <boost/random.hpp>\n\n#include \"Tudat/Basics/testMacros.h\"\n#include \"Tudat/Mathematics/BasicMathematics/mathematicalConstants.h\"\n#include \"Tudat/InputOutput/basicInputOutput.h\"\n#include \"Tudat/Mathematics/Statistics/kernelDensityDistribution.h\"\n\n\nnamespace tudat\n{\nnamespace unit_tests\n{\n\n//! Creates a std::vector of linear spaced values\nstd::vector< double > linspace( double start, double end, int N )\n{\n    std::vector < double > x( 0 );\n\n    if ( N > 1 )\n    {\n        for( int i = 0; i < N; i++ )\n        {\n            x.push_back( start + ( end - start )*i /( N - 1.0 ) );\n        }\n    }\n    return x;\n}\n\n//! Generator random vector using pseudo random generator\nstd::vector<Eigen::VectorXd> generateRandomVectorUniform(\n        int seed, int numberOfSamples,\n        Eigen::VectorXd lowerBound, Eigen::VectorXd upperBound)\n{\n    // Compute properties\n    Eigen::VectorXd width = upperBound - lowerBound;\n    Eigen::VectorXd average = (upperBound + lowerBound ) / 2.0;\n\n    // Setup Random generator\n    typedef boost::mt19937 RandomGeneratorType; // Mersenne Twister\n    RandomGeneratorType randomGenerator(seed);              // Create random generator\n\n    boost::uniform_real< > uniformDistribution( 0.0, 1.0 ); //\n    boost::variate_generator< RandomGeneratorType, boost::uniform_real< > >\n            Dice(randomGenerator, uniformDistribution); // define random generator\n\n    std::vector< Eigen::VectorXd > randomSamples(numberOfSamples);\n    Eigen::VectorXd randomSample( lowerBound.rows( ) );\n\n    // Sample\n    for(int i = 0; i < numberOfSamples; i++ ){ // Generate N samples\n        for(int j = 0; j < randomSample.rows( ); j++){ // Generate vector of samples\n            randomSample(j) = Dice( ) - 0.5;\n        }\n        randomSamples[i] = randomSample.cwiseProduct(width) + average;\n    }\n    return randomSamples;\n}\n\nBOOST_AUTO_TEST_SUITE( test_Kernel_Density_Distribution )\n\nusing tudat::mathematical_constants::PI;\n\n//! Test whether optimal bandwidths are correctly computed (compared to Matlab results)\nBOOST_AUTO_TEST_CASE( testOptimalKernelBandwidth )\n{\n\n    using namespace tudat::statistics;\n\n    std::vector< Eigen::VectorXd > data( 0 );\n    Eigen::VectorXd sample( 2 );\n    sample << 2.2538, 1.177;\n    data.push_back( sample );\n    sample << 0.76529, 0.356;\n    data.push_back( sample );\n    sample << 1.5179, 1.14;\n    data.push_back( sample );\n    sample << 2.0972, 0.34093;\n    data.push_back( sample );\n    sample << 2.6727, 1.301;\n    data.push_back( sample );\n    sample << 2.8779, 0.48998;\n    data.push_back( sample );\n    sample << 1.6416, 0.27523;\n    data.push_back( sample );\n    sample << 0.41587, 0.35152;\n    data.push_back( sample );\n    sample << 0.44788, 0.86246;\n    data.push_back( sample );\n    sample << 0.77252, 0.6626;\n    data.push_back( sample );\n\n    KernelDensityDistribution distribution( data );\n\n    // Generated expected Bandwidth using MATLAB\n    Eigen::VectorXd expectedBandwidth( 2 );\n    expectedBandwidth << 0.819018940571854, 0.263389630191125;\n\n    Eigen::VectorXd computedOptimalBandwidth( 2 );\n    computedOptimalBandwidth = distribution.getOptimalBandWidth( );\n\n    // Compare Matlab against Tudal results; results are similar but not identical due to slightly different algorithms/\n    BOOST_CHECK_CLOSE_FRACTION( expectedBandwidth( 0 ), computedOptimalBandwidth( 0 ), 2E-5 );\n    BOOST_CHECK_CLOSE_FRACTION( expectedBandwidth( 1 ), computedOptimalBandwidth( 1 ), 2E-5 );\n\n}\n\n//! Test if the Epanechnikov distribution is correctly implemented.\nBOOST_AUTO_TEST_CASE( testEpanechnikovKernel )\n{\n    tudat::statistics::EpanechnikovKernelDistribution distribution( 1.0, 2.0 );\n\n    // Test theoretical values of Cdf\n    BOOST_CHECK_CLOSE_FRACTION( distribution.evaluateCdf( 5.0 ), 1.0,\n                                4.0 * std::numeric_limits< double >::epsilon( ) );\n    BOOST_CHECK_CLOSE_FRACTION( distribution.evaluateCdf( 3.0 ), 1.0,\n                                4.0 * std::numeric_limits< double >::epsilon( ) );\n    BOOST_CHECK_CLOSE_FRACTION( distribution.evaluateCdf( 1.0 ), 0.5,\n                                4.0 * std::numeric_limits< double >::epsilon( ) );\n    BOOST_CHECK_SMALL( std::fabs( distribution.evaluateCdf( -1.0 ) - 0.0 ),\n                       4.0 * std::numeric_limits< double >::epsilon( ) );\n    BOOST_CHECK_SMALL( std::fabs( distribution.evaluateCdf( -2.0 ) - 0.0 ),\n                       4.0 * std::numeric_limits< double >::epsilon( ) );\n\n    // Test theoretical values of Pdf (zero outside of given range)\n    BOOST_CHECK_SMALL( std::fabs( distribution.evaluatePdf( -1.0 ) - 0.0 ),\n                       4.0 * std::numeric_limits< double >::epsilon( ) );\n    BOOST_CHECK_SMALL( std::fabs( distribution.evaluatePdf( 3.0 ) - 0.0 ),\n                       4.0 * std::numeric_limits< double >::epsilon( ) );\n    BOOST_CHECK_SMALL( std::fabs( distribution.evaluatePdf( 4.0 ) - 0.0 ),\n                       4.0 * std::numeric_limits< double >::epsilon( ) );\n    BOOST_CHECK_SMALL( std::fabs( distribution.evaluatePdf( -3.0 ) - 0.0 ),\n                       4.0 * std::numeric_limits< double >::epsilon( ) );\n\n    // Compare pdf and cdf at center points, compared to Matlab implementation\n    BOOST_CHECK_SMALL( std::fabs( distribution.evaluatePdf( 0.0 ) - 0.28125 ),\n                       4.0 * std::numeric_limits< double >::epsilon( ) );\n    BOOST_CHECK_SMALL( std::fabs( distribution.evaluateCdf( 0.0 ) - 0.15625 ),\n                       4.0 * std::numeric_limits< double >::epsilon( ) );\n}\n\n//! Test 1-Dimensional kernel density distribution, compared against Matlab implementation.\nBOOST_AUTO_TEST_CASE( testKernelProbabilityDensity1D )\n{\n    using namespace tudat::statistics;\n\n    Eigen::VectorXd sample( 1 );\n    std::vector< Eigen::VectorXd > samples( 0 );\n\n    sample( 0 ) = 3.0;\n    samples.push_back( sample );\n    sample( 0 ) = 1.0;\n    samples.push_back( sample );\n    sample( 0 ) = 4.0;\n    samples.push_back( sample );\n    sample( 0 ) = 7.0;\n    samples.push_back( sample );\n\n    // Create kernel\n    KernelDensityDistribution distribution(samples, 1.0, KernelType::gaussian_kernel );\n\n    Eigen::VectorXd location( 1 );\n    // Case 1\n    {\n        // Compure pdf\n        location << 5.396093156208099e-01;\n        double computedDensity = distribution.evaluatePdf( location );\n\n        // Data obtained from MATLAB ksdensity function\n        double expectedDensity = 8.426926493705324e-02;\n\n        // Check that the same bandwidths are used compared with MATLAB\n        Eigen::VectorXd expectedBandwidth( 1 );\n        expectedBandwidth << 1.785192502061299;\n\n        Eigen::VectorXd computedBandwidth = distribution.getBandWidth( );\n        Eigen::VectorXd difference = expectedBandwidth - computedBandwidth;\n\n        BOOST_CHECK_SMALL( std::fabs( difference( 0 ) ), 4.0 * std::numeric_limits< double >::epsilon( ) );\n\n        // Check pdf against Matlab computation\n        BOOST_CHECK_SMALL( std::fabs( computedDensity - expectedDensity ), 4.0 * std::numeric_limits< double >::epsilon( ) );\n    }\n\n    // Case 2\n    {\n        Eigen::VectorXd location( 1 );\n        location << 3.915600227210264;\n\n        double computedDensity = distribution.evaluatePdf( location );\n        double expectedDensity = 1.320686749820565e-01;\n\n        // Check pdf against Matlab computation\n        BOOST_CHECK_SMALL( std::fabs( computedDensity - expectedDensity ), 4.0 * std::numeric_limits< double >::epsilon( ) );\n    }\n\n    // Case 3\n    {\n        Eigen::VectorXd location( 1 );\n        location << 8.135588866697081;\n\n        double computedDensity = distribution.evaluatePdf( location );\n        double expectedDensity = 5.036314749096298e-02;\n\n        // Check pdf against Matlab computation\n        BOOST_CHECK_SMALL( std::fabs( computedDensity - expectedDensity ), 4.0 * std::numeric_limits< double >::epsilon( ) );\n    }\n}\n\n//! Test 2-Dimensional kernel density distribution, compared against Matlab implementation.\nBOOST_AUTO_TEST_CASE( testKernelProbabilityDensity2D )\n{\n    using namespace tudat::statistics;\n\n    Eigen::VectorXd sample( 2 );\n    std::vector< Eigen::VectorXd > samples( 0 );\n\n    sample << 3.0, 2E-2;\n    samples.push_back( sample );\n    sample << -1.0, 5E-2;\n    samples.push_back( sample );\n    sample << 5.0, 2E-1;\n    samples.push_back( sample );\n    sample << 2.0, 1E-3;\n    samples.push_back( sample );\n\n    // Create kernel\n    KernelDensityDistribution distribution( samples, 1.0, KernelType::gaussian_kernel );\n\n    // Case 1\n    {\n        Eigen::VectorXd location( 2 );\n        location << 1.141869732328655, 2.995235933344523e-02;\n\n        double computedDensity = distribution.evaluatePdf( location );\n        double expectedDensity = 1.136916246361795;\n\n        // Check that the same bandwidths are used compared with MATLAB\n        Eigen::VectorXd expectedBandwidth( 2 );\n        expectedBandwidth << 1.765086418052112, 2.882974482818450e-02;\n        Eigen::VectorXd computedBandwidth = distribution.getBandWidth( );\n        Eigen::VectorXd difference = expectedBandwidth - computedBandwidth;\n        BOOST_CHECK_SMALL( std::fabs( difference( 0 ) ), 4.0 * std::numeric_limits< double >::epsilon( ) );\n        BOOST_CHECK_SMALL( std::fabs( difference( 1 ) ), 4.0 * std::numeric_limits< double >::epsilon( ) );\n\n        // Check correct density\n        BOOST_CHECK_SMALL( std::fabs( computedDensity - expectedDensity ), 4.0 * std::numeric_limits< double >::epsilon( ) );\n    }\n\n    // Case 2\n    {\n        Eigen::VectorXd location( 2 );\n        location << -2.862738183470956, 1.582207969089993e-01;\n\n        double computedDensity = distribution.evaluatePdf( location );\n        double expectedDensity = 4.038687551312721e-04;\n\n        // Check pdf against Matlab computation\n        BOOST_CHECK_SMALL( std::fabs( computedDensity - expectedDensity ), 4.0 * std::numeric_limits< double >::epsilon( ) );\n    }\n\n    // Case 3\n    {\n        Eigen::VectorXd location( 2 );\n        location << 6.862738183470957, 2.995235933344523e-02;\n\n        double computedDensity = distribution.evaluatePdf( location );\n        double expectedDensity = 7.784149895640656e-02;\n\n        // Check pdf against Matlab computation\n        BOOST_CHECK_SMALL( std::fabs( computedDensity - expectedDensity ), 4.0 * std::numeric_limits< double >::epsilon( ) );\n    }\n\n    // Compare marginal CDF against Matlab\n    {\n        // Marginal CDF compare with MATLAB\n        Eigen::VectorXd bandwidth( 2 );\n        bandwidth << 1.785192502061299, 2.915814420033455e-02;\n        distribution.setBandWidth( bandwidth );\n\n         // Compare against Matlab results,\n        BOOST_CHECK_CLOSE_FRACTION(\n                    distribution.evaluateCumulativeMarginalProbability( 0, 2.276047714155371E-1 ),\n                    2.446324562687310E-1, 5E-3 );\n        BOOST_CHECK_CLOSE_FRACTION(\n                    distribution.evaluateCumulativeMarginalProbability( 1, 6.083875672099921e-02 ),\n                    6.360523509878839e-01, 5E-3 );\n        BOOST_CHECK_CLOSE_FRACTION(\n                    distribution.evaluateCumulativeMarginalProbability( 1, 9.861136936766661e-02 ),\n                    7.371490745984073e-01, 5E-3 );\n\n        // Check theoretical CDF at edge of domain.\n        BOOST_CHECK_SMALL( std::fabs(\n            distribution.evaluateCumulativeMarginalProbability( 1, 300.0 )\n                               - 1.0 ), 4.0 * std::numeric_limits< double >::epsilon( ) );\n        BOOST_CHECK_SMALL( std::fabs(\n            distribution.evaluateCumulativeMarginalProbability( 1, -200.0 )\n                               - 0.0 ), 4.0 * std::numeric_limits< double >::epsilon( ) );\n    }\n}\n\n//! Test whether scaling of sample standard deviation is done correctly\nBOOST_AUTO_TEST_CASE( testStandardDeviationScaling )\n{\n\n    using namespace tudat::statistics;\n\n    // Generate random datapoints\n    Eigen::VectorXd mean( 2 );\n    mean << 0.0, 0.0;\n    Eigen::VectorXd standardDeviation( 2 );\n    standardDeviation << 2.0, 0.5;\n    Eigen::VectorXd lowerBound = mean - standardDeviation * std::sqrt( 3.0 );\n    Eigen::VectorXd upperBound = mean + standardDeviation * std::sqrt( 3.0 );\n\n    int numberOfSamples = 1E6;\n    int seed = 100;\n    std::vector< Eigen::VectorXd > samples = generateRandomVectorUniform(\n                seed, numberOfSamples, lowerBound, upperBound );\n\n    // Create distribution\n    KernelDensityDistribution distribution2( samples );\n\n    Eigen::VectorXd sampleMean = distribution2.getSampleMean( );\n    Eigen::VectorXd sampleStandardDeviation = distribution2.getSampleStandardDeviation( );\n\n    // Check sample mean and standard deviation\n    BOOST_CHECK_SMALL( std::fabs( sampleMean( 0 ) - 0.0 ), 5E-3 );\n    BOOST_CHECK_SMALL( std::fabs( sampleMean( 1 ) - 0.0 ), 5E-3 );\n    BOOST_CHECK_SMALL( std::fabs( sampleStandardDeviation( 0 ) - 2.0 ), 1E-3 );\n    BOOST_CHECK_SMALL( std::fabs( sampleStandardDeviation( 1 ) - 0.5 ), 1E-3 );\n\n    // Check whether probability density function is approximately uniform.\n    double probabilityDensity = 1.0 / ( ( upperBound( 0 ) - lowerBound( 0 ) ) * ( upperBound( 1 ) - lowerBound( 1 ) ) );\n\n    Eigen::VectorXd x( 2 );\n    x << 0.0, 0.0;\n    BOOST_CHECK_SMALL( std::fabs( distribution2.evaluatePdf( x ) - probabilityDensity ), 2E-3 );\n\n    x << -1.0, 0.3;\n    BOOST_CHECK_CLOSE_FRACTION( distribution2.evaluatePdf( x ), probabilityDensity, 2E-4 );\n\n    // Set standard deviation scaling\n    Eigen::VectorXd standardDeviationAdjusted( 2 );\n    standardDeviationAdjusted << 0.5, 3.0;\n\n    // Create scaled kernel distribution\n    KernelDensityDistribution distribution( samples, 1.0, KernelType::gaussian_kernel, standardDeviationAdjusted );\n\n    Eigen::VectorXd newSampleMean = distribution.getSampleMean( );\n    Eigen::VectorXd newSampleStandardDeviation = distribution.getSampleStandardDeviation( );\n\n    // Recheck mean.\n    BOOST_CHECK_SMALL( std::fabs( newSampleMean( 0 ) - 0.0 ), 5E-3 );\n    BOOST_CHECK_SMALL( std::fabs( newSampleMean( 1 ) - 0.0 ), 5E-3 );\n\n    // Check whether sample standard deviation conforms to required values.\n    BOOST_CHECK_SMALL( std::fabs( newSampleStandardDeviation( 0 ) - 0.5 ), 1E-13 );\n    BOOST_CHECK_SMALL( std::fabs( newSampleStandardDeviation( 1 ) - 3.0 ), 1E-13 );\n\n    // Check whether probability density function is approximately uniform.\n    lowerBound = mean - standardDeviationAdjusted * std::sqrt( 3.0 );\n    upperBound = mean + standardDeviationAdjusted * std::sqrt( 3.0 );\n    probabilityDensity = 1.0 / ( ( upperBound( 0 ) - lowerBound( 0 ) ) * ( upperBound( 1 ) - lowerBound( 1 ) ) );\n\n    x << 0.0, 0.0;\n    BOOST_CHECK_SMALL( std::fabs( distribution.evaluatePdf( x ) - probabilityDensity ), 1.0E-3 );\n\n    x << -0.2, 2.3;\n    BOOST_CHECK_CLOSE_FRACTION( distribution.evaluatePdf( x ), probabilityDensity, 1.0E-3 );\n}\n\n//! Test 3-Dimensional kernel density distribution, compared against Matlab implementation.\nBOOST_AUTO_TEST_CASE( testKernelProbabilityDensity3D )\n{\n    using namespace tudat::statistics;\n\n    Eigen::VectorXd sample( 3 );\n    std::vector< Eigen::VectorXd > samples( 0 );\n\n    sample << 3.0, 2E-2, 0.1;\n    samples.push_back( sample );\n    sample << -1.0, 5E-2, 1.0;\n    samples.push_back( sample );\n    sample << 5.0, 2E-1, 3.0;\n    samples.push_back( sample );\n    sample << 2.0, 1E-3, 1.5;\n    samples.push_back( sample );\n\n    KernelDensityDistribution distribution(samples, 1.0, KernelType::gaussian_kernel );\n\n    // Test probability density\n    {\n        Eigen::VectorXd location( 3 );\n        location <<  1.5, 1E-2, 0.8;\n\n        double computedDensity = distribution.evaluatePdf( location );\n        double expectedDensity = 4.653809309094347e-01;\n\n        // Check correct density\n        BOOST_CHECK_SMALL( std::fabs( computedDensity - expectedDensity ), 4.0 * std::numeric_limits< double >::epsilon( ) );\n    }\n\n    // Test marginal cumulative probability\n    {\n        Eigen::VectorXd location( 3 );\n        location <<  1.5, 1E-2, 0.8;\n\n        int marginal = 0;\n        double computedDensity = distribution.evaluateCumulativeMarginalProbability( marginal, location( marginal ) );\n        double expectedDensity = 3.829580307170373e-01;\n\n        // Check correct density\n        BOOST_CHECK_SMALL( std::fabs( computedDensity - expectedDensity ), 4.0 * std::numeric_limits< double >::epsilon( ) );\n\n        marginal = 1;\n        computedDensity = distribution.evaluateCumulativeMarginalProbability( marginal, location( marginal ) );\n        expectedDensity = 2.674493565829487e-01;\n\n        // Check correct density\n        BOOST_CHECK_SMALL( std::fabs( computedDensity - expectedDensity ), 4.0 * std::numeric_limits< double >::epsilon( ) );\n    }\n\n    // Test conditional marginal cumulative probability\n    {\n        Eigen::VectorXd location( 3 );\n        location <<  1.5, 1E-2, 0.8;\n\n        int marginal = 0;\n        std::vector< int > conditionDimensions( 0 );\n        conditionDimensions.push_back( 1 );\n        std::vector< double > conditions( 0 );\n        conditions.push_back( 0.1 );\n\n        double computedDensity = distribution.evaluateCumulativeConditionalMarginalProbability(\n                    conditionDimensions, conditions, marginal, location( marginal ) );\n        double expectedDensity = 4.970339167925200e-01;\n\n        // Check correct density\n        BOOST_CHECK_SMALL( std::fabs( computedDensity - expectedDensity ), 4.0 * std::numeric_limits< double >::epsilon( ) );\n\n        conditionDimensions[0] = 0;\n        conditions[0] = 0.4;\n        marginal = 2;\n        computedDensity = distribution.evaluateCumulativeConditionalMarginalProbability(\n                    conditionDimensions, conditions, marginal, location( marginal ) );\n        expectedDensity = 3.932443313127392e-01;\n\n        // Check correct density\n        BOOST_CHECK_CLOSE_FRACTION( computedDensity, expectedDensity, 4.0 * std::numeric_limits< double >::epsilon( ) );\n    }\n}\n\n//! Test kernel density function for uncorrelated input data.\nBOOST_AUTO_TEST_CASE( testProbabilityFunctionsUncorrelated2D )\n{\n    using namespace tudat::statistics;\n\n    Eigen::VectorXd sample( 2 );\n    std::vector< Eigen::VectorXd > samples( 0 );\n\n    // Define uncorrelated input data.\n    sample << 3.0, 0.1 ;\n    samples.push_back( sample );\n    sample << 5.0, 0.1;\n    samples.push_back( sample );\n    sample << 7.0, 0.1;\n    samples.push_back( sample );\n\n    // Manually define bandwidth\n    Eigen::VectorXd bandWidth( 2 );\n    bandWidth << 1.0, 0.3;\n\n    KernelDensityDistribution distribution( samples, 1.0, KernelType::gaussian_kernel, Eigen::VectorXd::Zero( 0 ), bandWidth );\n\n    // Create manual Gaussian distributions\n    std::shared_ptr< ContinuousProbabilityDistribution< double > > gaussianDistribution1 =\n            createBoostRandomVariable( normal_boost_distribution, { samples[ 0 ]( 0 ), 1.0  } );\n\n    std::shared_ptr< ContinuousProbabilityDistribution< double > > gaussianDistribution2 =\n            createBoostRandomVariable( normal_boost_distribution, { samples[ 1 ]( 0 ), 1.0  } );\n\n    std::shared_ptr< ContinuousProbabilityDistribution< double > > gaussianDistribution3 =\n            createBoostRandomVariable( normal_boost_distribution, { samples[ 2 ]( 0 ), 1.0  } );\n\n    std::shared_ptr< ContinuousProbabilityDistribution< double > > gaussianDistribution4 =\n            createBoostRandomVariable( normal_boost_distribution, { samples[ 0 ]( 1 ), 0.3  } );\n\n    // Test probability density\n    {\n        Eigen::VectorXd location( 2 );\n        location <<  1.5, 1E-2;\n\n        // Compute pdf from kernel and theoretical value.\n        double computedDensity = distribution.evaluatePdf( location );\n        double expectedDensity = ( gaussianDistribution1->evaluatePdf( location( 0 ) ) +\n                                   gaussianDistribution2->evaluatePdf( location( 0 ) ) +\n                                   gaussianDistribution3->evaluatePdf( location( 0 ) ) ) *\n                gaussianDistribution4->evaluatePdf( location( 1 ) ) / 3.0;\n\n        // Check correct density\n        BOOST_CHECK_SMALL( std::fabs( computedDensity - expectedDensity ), 4.0 * std::numeric_limits< double >::epsilon( ) );\n    }\n\n    // Test cumulative probability\n    {\n        Eigen::VectorXd location( 2 );\n        location <<  2.5, 1E-1;\n\n        // Compute cdf from kernel and theoretical value.\n        double computedDensity = distribution.evaluateCdf( location );\n        double expectedDensity = (gaussianDistribution1->evaluateCdf( location( 0 ) ) +\n                                  gaussianDistribution2->evaluateCdf( location( 0 ) ) +\n                                  gaussianDistribution3->evaluateCdf( location( 0 ) ) ) *\n                gaussianDistribution4->evaluateCdf( location( 1 ) ) / 3.0;\n\n        // Check correct density\n        BOOST_CHECK_SMALL( std::fabs( computedDensity - expectedDensity ), 4.0 * std::numeric_limits< double >::epsilon( ) );\n    }\n\n    // Test marginal cumulative probability\n    {\n        Eigen::VectorXd location( 2 );\n        location <<  2.5, 1E-1;\n        int marginal = 0;\n\n        // Compute marginal cdf from kernel and theoretical value (marginalDimension = 0).\n        double computedDensity = distribution.evaluateCumulativeMarginalProbability( marginal, location( marginal ) );\n        double expectedDensity = ( gaussianDistribution1->evaluateCdf( location( 0 ) ) +\n                                   gaussianDistribution2->evaluateCdf( location( 0 ) ) +\n                                   gaussianDistribution3->evaluateCdf( location( 0 ) ) ) / 3.0;\n\n        BOOST_CHECK_SMALL( std::fabs( computedDensity - expectedDensity ), 4.0 * std::numeric_limits< double >::epsilon( ) );\n\n        // Compute marginal cdf from kernel and theoretical value (marginalDimension = 1).\n        marginal = 1;\n        computedDensity = distribution.evaluateCumulativeMarginalProbability( marginal, location( marginal ) );\n        expectedDensity = gaussianDistribution4->evaluateCdf( location( 1 ) );\n\n        BOOST_CHECK_SMALL( std::fabs( computedDensity - expectedDensity ), 4.0 * std::numeric_limits< double >::epsilon( ) );\n    }\n\n    // Test conditional marginal cumulative probability\n    {\n        double location;\n        std::vector< int > conditionDimensions( 0 );\n        std::vector< double > conditions( 0 );\n\n        location = 2.5;\n        int marginal = 0;\n        conditionDimensions.push_back( 1 );\n        conditions.push_back( 0.2 );\n\n        // Compute marginal cdf from kernel and theoretical value (marginalDimension = 0).\n        double computedDensity = distribution.evaluateCumulativeConditionalMarginalProbability(\n                    conditionDimensions, conditions, marginal, location );\n        double expectedDensity = ( gaussianDistribution1->evaluateCdf( location ) +\n                                   gaussianDistribution2->evaluateCdf( location ) +\n                                   gaussianDistribution3->evaluateCdf( location ) ) / 3.0;\n\n        BOOST_CHECK_SMALL( std::fabs( computedDensity - expectedDensity ), 4.0 * std::numeric_limits< double >::epsilon( ) );\n\n        // Compute conditional marginal cdf from kernel and theoretical value (marginalDimension = 1).\n        marginal = 1;\n        conditionDimensions[0] = 0;\n        conditions[ 0 ]  = 2.5;\n        location = 0.2;\n        computedDensity = distribution.evaluateCumulativeConditionalMarginalProbability(\n                    conditionDimensions, conditions, marginal, location );\n        expectedDensity = gaussianDistribution4->evaluateCdf( location );\n\n        BOOST_CHECK_SMALL( std::fabs( computedDensity - expectedDensity ), 4.0 * std::numeric_limits< double >::epsilon( ) );\n    }\n}\n\n\nBOOST_AUTO_TEST_SUITE_END( )\n\n} // namespace unit_tests\n} // namespace tudat\n\n", "meta": {"hexsha": "3ed2367fafe984344a4a710c74cf11ce32aee6cb", "size": 24335, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Mathematics/Statistics/UnitTests/unitTestKernelDensityDistribution.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/Mathematics/Statistics/UnitTests/unitTestKernelDensityDistribution.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/Mathematics/Statistics/UnitTests/unitTestKernelDensityDistribution.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": 40.3565505804, "max_line_length": 127, "alphanum_fraction": 0.6538319293, "num_tokens": 6134, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.4843329644813886}}
{"text": "static bool eigen_did_assert = false;\n#define eigen_assert(X) if(!eigen_did_assert && !(X)){ std::cout << \"### Assertion raised in \" << __FILE__ << \":\" << __LINE__ << \":\\n\" #X << \"\\n### The following would happen without assertions:\\n\"; eigen_did_assert = true;}\n\n#include <iostream>\n#include <Eigen/Eigen>\n\n#ifndef M_PI\n#define M_PI 3.1415926535897932384626433832795\n#endif\n\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n  Matrix2f M = Matrix2f::Random();\nMatrix2f m;\nm = M;\ncout << \"Here is the matrix m:\" << endl << m << endl;\ncout << \"Now we want to copy a column into a row.\" << endl;\ncout << \"If we do m.col(1) = m.row(0), then m becomes:\" << endl;\nm.col(1) = m.row(0);\ncout << m << endl << \"which is wrong!\" << endl;\ncout << \"Now let us instead do m.col(1) = m.row(0).eval(). Then m becomes\" << endl;\nm = M;\nm.col(1) = m.row(0).eval();\ncout << m << endl << \"which is right.\" << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "cb8705d64b83469d9d9bc115fdbaa94d39f4a6d0", "size": 951, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/snippets/compile_MatrixBase_eval.cpp", "max_stars_repo_name": "mousepawmedia/libdeps", "max_stars_repo_head_hexsha": "b004d58d5b395ceaf9fdc993cfb00e91334a5d36", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2021-02-27T11:00:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T10:31:46.000Z", "max_issues_repo_path": "doc/snippets/compile_MatrixBase_eval.cpp", "max_issues_repo_name": "mousepawmedia/libdeps", "max_issues_repo_head_hexsha": "b004d58d5b395ceaf9fdc993cfb00e91334a5d36", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-11-14T23:14:58.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-14T23:14:58.000Z", "max_forks_repo_path": "doc/snippets/compile_MatrixBase_eval.cpp", "max_forks_repo_name": "mousepawmedia/libdeps", "max_forks_repo_head_hexsha": "b004d58d5b395ceaf9fdc993cfb00e91334a5d36", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-03-13T13:28:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-05T02:26:02.000Z", "avg_line_length": 28.8181818182, "max_line_length": 224, "alphanum_fraction": 0.6277602524, "num_tokens": 296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419704455589, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.48433296438594287}}
{"text": "#ifndef plane_calibration_SRC_PLANE_TO_DEPTH_IMAGE_HPP_\n#define plane_calibration_SRC_PLANE_TO_DEPTH_IMAGE_HPP_\n\n#include <Eigen/Dense>\n#include <utility>\n#include <sstream>\n#include <memory>\n\n#include \"camera_model.hpp\"\n\nnamespace plane_calibration\n{\n\nclass PlaneToDepthImage\n{\npublic:\n  class Errors\n  {\n  public:\n    std::string asPrintString()\n    {\n      std::ostringstream string_stream;\n      string_stream << mean << \", \" << min << \", \" << max;\n      return string_stream.str();\n    }\n\n    double mean;\n    double min;\n    double max;\n  };\n\n  PlaneToDepthImage(const CameraModel::Parameters& camera_model_paramaters);\n  Eigen::MatrixXf convert(const Eigen::Affine3d& plane_transformation);\n\n  static Eigen::MatrixXf convert(const Eigen::Affine3d& plane_transformation,\n                                 const CameraModel::Parameters& camera_model_paramaters);\n  static Eigen::MatrixXf convert(const Eigen::Affine3d& plane_transformation,\n                                 const CameraModel::Parameters& camera_model_paramaters,\n                                 const std::pair<Eigen::MatrixXd, Eigen::MatrixXd>& xy_multipliers);\n\n  static std::pair<Eigen::MatrixXd, Eigen::MatrixXd> depthCalculationXYMultiplier(\n      const CameraModel::Parameters& camera_model_paramaters);\n\n  static Errors getErrors(const Eigen::Affine3d& plane_transformation,\n                          const CameraModel::Parameters& camera_model_paramaters, Eigen::MatrixXf image_matrix);\n\nprotected:\n  CameraModel::Parameters camera_model_paramaters_;\n  std::pair<Eigen::MatrixXd, Eigen::MatrixXd> xy_multipliers_;\n};\ntypedef std::shared_ptr<PlaneToDepthImage> PlaneToDepthImagePtr;\n\n} /* end namespace */\n\n#endif\n", "meta": {"hexsha": "44479d40e4e2702c42ecec052b79fb925a6cb1e7", "size": 1693, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/plane_calibration/plane_to_depth_image.hpp", "max_stars_repo_name": "AlexReimann/3d-plane-adjustment", "max_stars_repo_head_hexsha": "0aa5b358febf485d59caea80eb181383f38388f0", "max_stars_repo_licenses": ["Apache-2.0"], "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/plane_calibration/plane_to_depth_image.hpp", "max_issues_repo_name": "AlexReimann/3d-plane-adjustment", "max_issues_repo_head_hexsha": "0aa5b358febf485d59caea80eb181383f38388f0", "max_issues_repo_licenses": ["Apache-2.0"], "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/plane_calibration/plane_to_depth_image.hpp", "max_forks_repo_name": "AlexReimann/3d-plane-adjustment", "max_forks_repo_head_hexsha": "0aa5b358febf485d59caea80eb181383f38388f0", "max_forks_repo_licenses": ["Apache-2.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.2321428571, "max_line_length": 112, "alphanum_fraction": 0.7135262847, "num_tokens": 364, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.48429622192780436}}
{"text": "#ifndef HOPS_MULTIVARIATEGAUSSIANMODEL_HPP\n#define HOPS_MULTIVARIATEGAUSSIANMODEL_HPP\n\n#define _USE_MATH_DEFINES\n#include <math.h>\n#include <Eigen/Cholesky>\n#include <Eigen/Core>\n#include <Eigen/LU>\n#include <utility>\n\nnamespace hops {\n    template<typename Matrix, typename Vector>\n    class MultivariateGaussianModel {\n    public:\n        using MatrixType = Matrix;\n        using VectorType = Vector;\n\n        MultivariateGaussianModel(VectorType mean, MatrixType covariance);\n\n        /**\n         * @brief Evaluates the negative log likelihood for input x.\n         * @param x\n         * @return\n         */\n        typename MatrixType::Scalar computeNegativeLogLikelihood(const VectorType &x) const;\n\n        MatrixType computeExpectedFisherInformation(const VectorType &) const;\n\n        VectorType computeLogLikelihoodGradient(const VectorType &x) const;\n\n    private:\n        VectorType mean;\n        MatrixType covariance;\n        MatrixType inverseCovariance;\n        typename MatrixType::Scalar logNormalizationConstant;\n    };\n\n    template<typename MatrixType, typename VectorType>\n    MultivariateGaussianModel<MatrixType, VectorType>::MultivariateGaussianModel(VectorType mean,\n                                                                                 MatrixType covariance) :\n            mean(std::move(mean)),\n            covariance(std::move(covariance)) {\n        Eigen::LLT<MatrixType, Eigen::Upper> solver(this->covariance);\n        Eigen::Matrix<typename MatrixType::Scalar, Eigen::Dynamic, Eigen::Dynamic> matrixL = solver.matrixL();\n        Eigen::Matrix<typename MatrixType::Scalar, Eigen::Dynamic, Eigen::Dynamic> matrixU = solver.matrixU();\n        Eigen::Matrix<typename MatrixType::Scalar, Eigen::Dynamic, Eigen::Dynamic> inverseMatrixL = matrixL.inverse();\n        inverseCovariance = inverseMatrixL * inverseMatrixL.transpose();\n\n        logNormalizationConstant = -static_cast<typename MatrixType::Scalar>(this->mean.rows()) / 2 *\n                                   std::log(2 * M_PI)\n                                   - matrixL.diagonal().array().log().sum();\n    }\n\n    template<typename MatrixType, typename VectorType>\n    typename MatrixType::Scalar\n    MultivariateGaussianModel<MatrixType, VectorType>::computeNegativeLogLikelihood(const VectorType &x) const {\n        return -logNormalizationConstant +\n               0.5 * static_cast<typename MatrixType::Scalar>((x - mean).transpose() * inverseCovariance * (x - mean));\n    }\n\n    template<typename MatrixType, typename VectorType>\n    MatrixType\n    MultivariateGaussianModel<MatrixType, VectorType>::computeExpectedFisherInformation(const VectorType &) const {\n        return inverseCovariance;\n    }\n\n    template<typename MatrixType, typename VectorType>\n    VectorType\n    MultivariateGaussianModel<MatrixType, VectorType>::computeLogLikelihoodGradient(const VectorType &x) const {\n        return -inverseCovariance * (x - mean);\n    }\n}\n\n#endif //HOPS_MULTIVARIATEGAUSSIANMODEL_HPP\n", "meta": {"hexsha": "01b9b88ea76efd28287db4cae3a79117d468f3a6", "size": 2989, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/hops/Model/MultivariateGaussianModel.hpp", "max_stars_repo_name": "modsim/hops", "max_stars_repo_head_hexsha": "4285dd75a07dd844295440a0756b3ba25f5819ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2020-11-26T05:13:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T02:08:40.000Z", "max_issues_repo_path": "include/hops/Model/MultivariateGaussianModel.hpp", "max_issues_repo_name": "modsim/hops", "max_issues_repo_head_hexsha": "4285dd75a07dd844295440a0756b3ba25f5819ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-02-20T23:16:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-20T23:16:34.000Z", "max_forks_repo_path": "include/hops/Model/MultivariateGaussianModel.hpp", "max_forks_repo_name": "modsim/hops", "max_forks_repo_head_hexsha": "4285dd75a07dd844295440a0756b3ba25f5819ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.8533333333, "max_line_length": 119, "alphanum_fraction": 0.6804951489, "num_tokens": 638, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.48429622192780436}}
{"text": "/*\n * Software License Agreement (BSD License)\n *\n *  Copyright (c) 2009, Willow Garage, Inc.\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions\n *  are met:\n *\n *   * Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *   * Redistributions in binary form must reproduce the above\n *     copyright notice, this list of conditions and the following\n *     disclaimer in the documentation and/or other materials provided\n *     with the distribution.\n *   * Neither the name of Willow Garage, Inc. nor the names of its\n *     contributors may be used to endorse or promote products derived\n *     from this software without specific prior written permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n *  \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n *  POSSIBILITY OF SUCH DAMAGE.\n *\n */\n\n#include \"precomp.hpp\"\n\n// Eigen\n#include <Eigen/Core>\n\n// OpenCV\n#include <opencv2/core/eigen.hpp>\n#include <opencv2/sfm/triangulation.hpp>\n#include <opencv2/sfm/projection.hpp>\n\n// libmv headers\n#include \"libmv/multiview/twoviewtriangulation.h\"\n#include \"libmv/multiview/fundamental.h\"\n\nusing namespace cv;\nusing namespace std;\n\nnamespace cv\n{\nnamespace sfm\n{\n\n/** @brief Triangulates the a 3d position between two 2d correspondences, using the DLT.\n  @param xl Input vector with first 2d point.\n  @param xr Input vector with second 2d point.\n  @param Pl Input 3x4 first projection matrix.\n  @param Pr Input 3x4 second projection matrix.\n  @param objectPoint Output vector with computed 3d point.\n\n  Reference: @cite HartleyZ00 12.2 pag.312\n */\nvoid\ntriangulateDLT( const Vec2d &xl, const Vec2d &xr,\n                const Matx34d &Pl, const Matx34d &Pr,\n                Vec3d &point3d )\n{\n    Matx44d design;\n    for (int i = 0; i < 4; ++i)\n    {\n        design(0,i) = xl(0) * Pl(2,i) - Pl(0,i);\n        design(1,i) = xl(1) * Pl(2,i) - Pl(1,i);\n        design(2,i) = xr(0) * Pr(2,i) - Pr(0,i);\n        design(3,i) = xr(1) * Pr(2,i) - Pr(1,i);\n    }\n\n    Vec4d XHomogeneous;\n    cv::SVD::solveZ(design, XHomogeneous);\n\n    homogeneousToEuclidean(XHomogeneous, point3d);\n}\n\n\n/** @brief Triangulates the 3d position of 2d correspondences between n images, using the DLT\n * @param x Input vectors of 2d points (the inner vector is per image). Has to be 2xN\n * @param Ps Input vector with 3x4 projections matrices of each image.\n * @param X Output vector with computed 3d point.\n\n * Reference: it is the standard DLT; for derivation see appendix of Keir's thesis\n */\nvoid\ntriangulateNViews(const Mat_<double> &x, const std::vector<Matx34d> &Ps, Vec3d &X)\n{\n    CV_Assert(x.rows == 2);\n    unsigned nviews = x.cols;\n    CV_Assert(nviews == Ps.size());\n\n    cv::Mat_<double> design = cv::Mat_<double>::zeros(3*nviews, 4 + nviews);\n    for (unsigned i=0; i < nviews; ++i) {\n        for(char jj=0; jj<3; ++jj)\n            for(char ii=0; ii<4; ++ii)\n                design(3*i+jj, ii) = -Ps[i](jj, ii);\n        design(3*i + 0, 4 + i) = x(0, i);\n        design(3*i + 1, 4 + i) = x(1, i);\n        design(3*i + 2, 4 + i) = 1.0;\n    }\n\n    Mat X_and_alphas;\n    cv::SVD::solveZ(design, X_and_alphas);\n    homogeneousToEuclidean(X_and_alphas.rowRange(0, 4), X);\n}\n\n\nvoid\ntriangulatePoints(InputArrayOfArrays _points2d, InputArrayOfArrays _projection_matrices,\n                  OutputArray _points3d)\n{\n    // check\n    size_t nviews = (unsigned) _points2d.total();\n    CV_Assert(nviews >= 2 && nviews == _projection_matrices.total());\n\n    // inputs\n    size_t n_points;\n    std::vector<Mat_<double> > points2d(nviews);\n    std::vector<Matx34d> projection_matrices(nviews);\n    {\n        std::vector<Mat> points2d_tmp;\n        _points2d.getMatVector(points2d_tmp);\n        n_points = points2d_tmp[0].cols;\n\n        std::vector<Mat> projection_matrices_tmp;\n        _projection_matrices.getMatVector(projection_matrices_tmp);\n\n        // Make sure the dimensions are right\n        for(size_t i=0; i<nviews; ++i) {\n            CV_Assert(points2d_tmp[i].rows == 2 && points2d_tmp[i].cols == n_points);\n            if (points2d_tmp[i].type() == CV_64F)\n                points2d[i] = points2d_tmp[i];\n            else\n                points2d_tmp[i].convertTo(points2d[i], CV_64F);\n\n            CV_Assert(projection_matrices_tmp[i].rows == 3 && projection_matrices_tmp[i].cols == 4);\n            if (projection_matrices_tmp[i].type() == CV_64F)\n              projection_matrices[i] = projection_matrices_tmp[i];\n            else\n              projection_matrices_tmp[i].convertTo(projection_matrices[i], CV_64F);\n        }\n    }\n\n    // output\n    _points3d.create(3, n_points, CV_64F);\n    cv::Mat points3d = _points3d.getMat();\n\n    // Two view\n    if( nviews == 2 )\n    {\n        const Mat_<double> &xl = points2d[0], &xr = points2d[1];\n\n        const Matx34d & Pl = projection_matrices[0];    // left matrix projection\n        const Matx34d & Pr = projection_matrices[1];    // right matrix projection\n\n        // triangulate\n        for( unsigned i = 0; i < n_points; ++i )\n        {\n            Vec3d point3d;\n            triangulateDLT( Vec2d(xl(0,i), xl(1,i)), Vec2d(xr(0,i), xr(1,i)), Pl, Pr, point3d );\n            for(char j=0; j<3; ++j)\n                points3d.at<double>(j, i) = point3d[j];\n        }\n    }\n    else if( nviews > 2 )\n    {\n        // triangulate\n        for( unsigned i=0; i < n_points; ++i )\n        {\n            // build x matrix (one point per view)\n            Mat_<double> x( 2, nviews );\n            for( unsigned k=0; k < nviews; ++k )\n            {\n                points2d.at(k).col(i).copyTo( x.col(k) );\n            }\n\n            Vec3d point3d;\n            triangulateNViews( x, projection_matrices, point3d );\n            for(char j=0; j<3; ++j)\n                points3d.at<double>(j, i) = point3d[j];\n        }\n    }\n}\n\n} /* namespace sfm */\n} /* namespace cv */", "meta": {"hexsha": "a77aa75189810e90ae372588a4c85de9880e5751", "size": 6662, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "opencv_contrib-3.3.0/modules/sfm/src/triangulation.cpp", "max_stars_repo_name": "AmericaGL/TrashTalk_Dapp", "max_stars_repo_head_hexsha": "401f17289261b5f537b239e7759dc039d53211e1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2020-03-13T00:10:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-06T17:13:17.000Z", "max_issues_repo_path": "opencv_contrib-3.3.0/modules/sfm/src/triangulation.cpp", "max_issues_repo_name": "AmericaGL/TrashTalk_Dapp", "max_issues_repo_head_hexsha": "401f17289261b5f537b239e7759dc039d53211e1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-03-12T08:10:07.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-12T08:10:07.000Z", "max_forks_repo_path": "opencv_contrib-3.3.0/modules/sfm/src/triangulation.cpp", "max_forks_repo_name": "AmericaGL/TrashTalk_Dapp", "max_forks_repo_head_hexsha": "401f17289261b5f537b239e7759dc039d53211e1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2015-10-23T19:36:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-02T12:20:32.000Z", "avg_line_length": 33.9897959184, "max_line_length": 100, "alphanum_fraction": 0.6323926749, "num_tokens": 1876, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.6187804196836383, "lm_q1q2_score": 0.4842962171971354}}
{"text": "//\n// Copyright 2005-2007 Adobe Systems Incorporated\n//\n// Distributed under the Boost Software License, Version 1.0\n// See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt\n//\n\n#include <boost/gil.hpp>\n#include <boost/gil/extension/io/jpeg.hpp>\n#include <boost/gil/extension/numeric/sampler.hpp>\n#include <boost/gil/extension/numeric/resample.hpp>\n\n// Performs an arbitrary affine transformation on the image.\n\n// This example relies on the matrices and functions available in GIL to define the operation,\n// in include/boost/gil/extension/numeric/affine.hpp\n// and calls resample_pixels(), avaiable in the numeric extension, to apply it\n\nint main()\n{\n    namespace gil = boost::gil;\n\n    gil::rgb8_image_t img;\n    gil::read_image(\"test.jpg\", img, gil::jpeg_tag());\n\n    // test resample_pixels\n    // Transform the image by an arbitrary affine transformation using nearest-neighbor resampling\n    gil::rgb8_image_t transf(gil::rgb8_image_t::point_t(gil::view(img).dimensions() * 2));\n    gil::fill_pixels(gil::view(transf), gil::rgb8_pixel_t(255, 0, 0)); // the background is red\n\n    gil::matrix3x2<double> mat =\n        gil::matrix3x2<double>::get_translate(-gil::point<double>(200,250)) *\n        gil::matrix3x2<double>::get_rotate(-15*3.14/180.0);\n    gil::resample_pixels(const_view(img), gil::view(transf), mat, gil::nearest_neighbor_sampler());\n    gil::write_view(\"out-affine.jpg\", gil::view(transf), gil::jpeg_tag());\n\n    return 0;\n}\n", "meta": {"hexsha": "a078d17a2dddc01b32d75c26298298c0feaf8d8e", "size": 1482, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/affine.cpp", "max_stars_repo_name": "DhruvaG2000/gil", "max_stars_repo_head_hexsha": "0b24f4cdbf430430b5430507822b0698cd9d2ac7", "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": "example/affine.cpp", "max_issues_repo_name": "DhruvaG2000/gil", "max_issues_repo_head_hexsha": "0b24f4cdbf430430b5430507822b0698cd9d2ac7", "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": "example/affine.cpp", "max_forks_repo_name": "DhruvaG2000/gil", "max_forks_repo_head_hexsha": "0b24f4cdbf430430b5430507822b0698cd9d2ac7", "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.05, "max_line_length": 99, "alphanum_fraction": 0.7199730094, "num_tokens": 410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.6187804267137442, "lm_q1q2_score": 0.4842962164256044}}
{"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_ONLINESTAT_HPP\n#define NETKET_ONLINESTAT_HPP\n\n#include <mpi.h>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <cassert>\n#include <iostream>\n#include <vector>\n#include \"Utils/random_utils.hpp\"\n\nnamespace netket {\n\n/// Online statistics\n// for general types\n// this class accumulates results\n// with minimal memory requirements\n// simple statistics can then be obtained\n// or merged with other bins\n\ntemplate <class T>\nclass OnlineStat {\n  // Number of samples in this bin\n  int N_;\n\n  // current mean\n  T mean_;\n\n  // Running sum of squares of differences from the current mean\n  T m2_;\n\n  bool firstcall_;\n\n public:\n  using DataType = T;\n\n  explicit OnlineStat() { Reset(); }\n\n  // Adding data to this bin\n  inline void operator<<(const DataType &data) {\n    CheckCall(data);\n\n    N_ += 1;\n    const T delta = data - mean_;\n    mean_ += delta / double(N_);\n\n    const T delta2 = data - mean_;\n    m2_ += delta * delta2;\n  }\n\n  // Merging with another bin\n  inline void operator<<(const OnlineStat<T> &obin) {\n    CheckCall(obin.Mean());\n\n    N_ += obin.N();\n    const T delta = obin.Mean() - Mean();\n    mean_ += delta * obin.N() / double(N_);\n\n    m2_ += obin.m2_ + delta * delta * obin.N() * (1. - obin.N() / double(N_));\n  }\n\n  inline int N() const { return N_; }\n\n  inline DataType Mean() const { return mean_; }\n\n  inline DataType Variance() const { return m2_ / double(N_ - 1.); }\n\n  inline DataType ErrorOfMean() const {\n    return sqrt(m2_ / double(N_ * (N_ - 1.)));\n  }\n\n  void Reset() { firstcall_ = true; }\n\n  void CheckCall(const DataType &data) {\n    if (firstcall_) {\n      N_ = 0;\n      mean_ = DataType(data);\n      mean_ = 0;\n      m2_ = DataType(data);\n      m2_ = 0;\n      firstcall_ = false;\n    }\n  }\n};\n\n/// Online statistics\n// for scalars\n// this class accumulates results\n// with minimal memory requirements\n// simple statistics can then be obtained\n// or merged with other bins\ntemplate <>\nclass OnlineStat<Eigen::VectorXd> {\n  // Number of samples in this bin\n  int N_;\n\n  // current mean\n  Eigen::VectorXd mean_;\n\n  // Running sum of squares of differences from the current mean\n  Eigen::VectorXd m2_;\n\n  bool firstcall_;\n\n public:\n  using DataType = Eigen::VectorXd;\n\n  explicit OnlineStat() { Reset(); }\n\n  // Adding data to this bin\n  inline void operator<<(const DataType &data) {\n    CheckCall(data);\n\n    N_ += 1;\n    const DataType delta = data - mean_;\n    mean_ += delta / double(N_);\n\n    const DataType delta2 = data - mean_;\n    m2_ += delta.cwiseProduct(delta2);\n  }\n\n  // Merging with another bin\n  inline void operator<<(const OnlineStat<Eigen::VectorXd> &obin) {\n    CheckCall(obin.Mean());\n\n    N_ += obin.N();\n    const DataType delta = obin.Mean() - Mean();\n    mean_ += delta * obin.N() / double(N_);\n    m2_ += obin.m2_ +\n           delta.cwiseProduct(delta) * obin.N() * (1. - obin.N() / double(N_));\n  }\n\n  inline int N() const { return N_; }\n\n  inline DataType Mean() const { return mean_; }\n\n  inline DataType Variance() const { return m2_ / double(N_ - 1.); }\n\n  inline DataType ErrorOfMean() const {\n    return m2_.cwiseSqrt() / std::sqrt(double(N_ * (N_ - 1.)));\n  }\n\n  void Reset() { firstcall_ = true; }\n\n  void CheckCall(const DataType &data) {\n    if (firstcall_) {\n      N_ = 0;\n      mean_.resize(data.size());\n      mean_.setZero();\n      m2_.resize(data.size());\n      m2_.setZero();\n      firstcall_ = false;\n    }\n  }\n};\n\n}  // namespace netket\n#endif\n", "meta": {"hexsha": "b364d75ee88e6d5b5780bed06a6ca77fa5c79e94", "size": 4067, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Sources/Stats/onlinestat.hpp", "max_stars_repo_name": "tvieijra/netket", "max_stars_repo_head_hexsha": "ef3ff32b242f25b6a6ae0f08db1aada85775a2ea", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2019-11-29T02:51:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-14T18:52:33.000Z", "max_issues_repo_path": "Sources/Stats/onlinestat.hpp", "max_issues_repo_name": "tvieijra/netket", "max_issues_repo_head_hexsha": "ef3ff32b242f25b6a6ae0f08db1aada85775a2ea", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-03-03T11:12:00.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-01T17:04:41.000Z", "max_forks_repo_path": "Sources/Stats/onlinestat.hpp", "max_forks_repo_name": "tvieijra/netket", "max_forks_repo_head_hexsha": "ef3ff32b242f25b6a6ae0f08db1aada85775a2ea", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2019-12-02T07:29:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-04T21:55:21.000Z", "avg_line_length": 23.5086705202, "max_line_length": 79, "alphanum_fraction": 0.6469141874, "num_tokens": 1087, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056295505784, "lm_q2_score": 0.7025300511670689, "lm_q1q2_score": 0.4842579191979165}}
{"text": "// Erwann Rogard, wrote in July 2009:\n//\n// This iterator is by nbecker and was found in the boost's vault. \n// Changes that I made are shown by ER_2007_07\n//\n// arch-tag: ed320324-7f40-4e99-8364-8a6b7cf4d19e\n#ifndef cycle_iterator_ext_HPP_2009\n#define cycle_iterator_ext_HPP_2009\n#include <boost/type_traits/is_convertible.hpp>\n#include <boost/utility/enable_if.hpp>\n#include <boost/iterator/iterator_adaptor.hpp>\n#include <iterator>\n\n// See http://www.nabble.com/cycle-iterators-td25215321.html\n\n\nnamespace boost {\n\n  //! This is a cycle iterator that does keep track of wraparound.\n  template<typename BaseIterator, typename offset_t>\n  class cycle_iterator_ext : public boost::iterator_adaptor<cycle_iterator_ext<BaseIterator, offset_t>,\n\t\t\t\t\t\t\tBaseIterator\n\t\t\t\t\t\t       >\n  {\n  public:\n    typedef typename boost::iterator_adaptor<cycle_iterator_ext<BaseIterator, offset_t>,\n\t\t\t\t\t     BaseIterator\n\t\t\t\t\t    > super_t;\n\n    typedef typename super_t::difference_type difference_type;\n    typedef typename super_t::reference reference;\n\n    explicit cycle_iterator_ext()\n    :super_t(),size(0),position(0),wrap(0) // ER_2009_07 \n    {}\n\n    explicit cycle_iterator_ext (BaseIterator const& _b, BaseIterator const& _e, offset_t offset=0) :\n      //base(_b), //ER_2009_07\n      super_t(_b), //ER_2009_07\n      size (std::distance (_b, _e))\n      , wrap(0) //ER_2009_07\n    {\n      SetPos (offset);\n    }\n\n\n    template <typename OtherBase, typename OtherOffset>\n    cycle_iterator_ext (cycle_iterator_ext<OtherBase,OtherOffset> const& other,\n\t\t    typename enable_if_convertible<OtherBase, BaseIterator>::type* = 0) :\n      super_t(other),       // ER_2009_07\n      //base (other.base),  // ER_2009_07\n      size (other.size),\n      position (other.position),\n      wrap (other.wrap)\n    {}\n\n    // ER_2009_07\n    //template <typename OtherBase, typename OtherOffset>\n    //typename enable_if<\n    //    is_convertible<OtherBase,BaseIterator>,\n    //    cycle_iterator_ext&\n    //>::type\n    //operator= (cycle_iterator_ext<OtherBase,OtherOffset> const& other)\n    //{\n    //    if(&other!=this){\n    //        super_t& super = static_cast<super_t&>(this);\n    //        super = other;\n    //        size = (other.size),\n    //        position = (other.position),\n    //        wrap = (other.wrap);\n    //    }\n    //    return *this;\n    //}\n\n  private:\n    friend class boost::iterator_core_access;\n\n    void increment () {\n      ++position;\n      if (position >= size) {\n\t++wrap;\n\tposition -= size;\n      }\n    }\n\n    void decrement () {\n      --position;\n      if (position < 0) {\n\t--wrap;\n\tposition += size;\n      }\n    }\n\n    void SetPos (offset_t newpos) {\n      position = newpos % size;\n      wrap = newpos / size;\n      if (position < 0) {\n\t--wrap;\n\tposition += size;\n      }\n    }\n\n    void advance (difference_type n) {\n      offset_t newpos = realposition() + n;\n      SetPos (newpos);\n    }\n\n    template<typename OtherBase, typename OtherOffset>\n    difference_type\n    distance_to (cycle_iterator_ext<OtherBase, OtherOffset> const& y) const {\n      if (size == 0)\n\treturn 0;\n\n      else {\n\toffset_t pos1 = realposition();\n\toffset_t pos2 = y.realposition();\n\treturn -(pos1 - pos2);\n      }\n    }\n\n    template<typename OtherBase, typename OtherOffset>\n    bool equal (cycle_iterator_ext<OtherBase, OtherOffset> const& y) const {\n      return distance_to (y) == 0;\n    }\n\n    reference dereference() const { \n       // return *(base + position); // ER_2009_07\n        return *(this->base_reference() + position); // ER_2009_07\n    }\n\n   offset_t PositiveMod (offset_t x) const {\n      offset_t y = x % size;\n      if (y < 0)\n\ty += size;\n      return y;\n    }\n\n  public:\n\n\n    reference operator[] (difference_type n) const { \n        // return *(base + PositiveMod (position + n)); // ER_2009_07\n        return *(this->base_reference() + PositiveMod (position + n)); // ER_2009_07\n    }\n\n    offset_t offset() const { return position; }\n\n    offset_t realposition () const {\n      return position + wrap * size;\n    }\n\n\n    //  private:\n\n    // BaseIterator base; // ER_2009\n    offset_t size;\n    offset_t position;\n    offset_t wrap;\n  };\n\n  template<typename offset_t, typename BaseIterator>\n  cycle_iterator_ext<BaseIterator, offset_t> make_cycle_iterator_ext(BaseIterator b, BaseIterator e, offset_t offset=0) {\n    return cycle_iterator_ext<BaseIterator, offset_t> (b, e, offset);\n  }\n\n  template<typename BaseIterator>\n  cycle_iterator_ext<BaseIterator, int> make_cycle_iterator_ext(BaseIterator b, BaseIterator e, int offset=0) {\n    return cycle_iterator_ext<BaseIterator, int> (b, e, offset);\n  }\n\n} //namespace boost\n\n#endif\n", "meta": {"hexsha": "9e4b562cd7be2c309fa8136bbbdf633b60372b35", "size": 4650, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "iterator/boost/iterator/cycle_iterator_ext.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": "iterator/boost/iterator/cycle_iterator_ext.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": "iterator/boost/iterator/cycle_iterator_ext.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": 26.724137931, "max_line_length": 121, "alphanum_fraction": 0.6462365591, "num_tokens": 1227, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056295505784, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.48425791490482706}}
{"text": "#ifndef PARMCB_FORESTINDEX_HPP_\n#define PARMCB_FORESTINDEX_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 <vector>\n#include <map>\n#include <queue>\n#include <set>\n\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/graph_concepts.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/concept/assert.hpp>\n\n#include <parmcb/detail/spanning_forest.hpp>\n\nnamespace parmcb {\n\n    template<class Graph>\n    class ForestIndex {\n\n    public:\n        typedef typename boost::graph_traits<Graph>::edge_descriptor Edge;\n        typedef typename std::size_t size_type;\n\n        explicit ForestIndex(const Graph &g) {\n            create_index(g);\n        }\n\n        ForestIndex(const ForestIndex &ei) {\n            n = ei.n;\n            m = ei.m;\n            k = ei.k;\n            index = ei.index;\n            reverse_index = ei.reverse_index;\n        }\n\n        ~ForestIndex(void) {\n        }\n\n        ForestIndex& operator=(const ForestIndex &ei) {\n            if (this == &ei) {\n                return *this;\n            }\n            n = ei.n;\n            m = ei.m;\n            k = ei.k;\n            index = ei.index;\n            reverse_index = ei.reverse_index;\n            return *this;\n        }\n\n        const Edge& operator()(const size_type &i) const {\n            return reverse_index[i];\n        }\n\n        const size_type& operator()(const Edge &e) const {\n            return index.at(e);\n        }\n\n        bool is_on_forest(const Edge &e) const {\n            return index.at(e) >= cycle_space_dimension();\n        }\n\n        size_type cycle_space_dimension() const {\n            return m - n + k;\n        }\n\n        size_type weak_connected_components() const {\n            return k;\n        }\n\n    private:\n        typedef typename boost::graph_traits<Graph>::edge_iterator EdgeIt;\n\n        size_type n = 0;\n        size_type m = 0;\n        size_type k = 0;\n        std::map<Edge, size_type> index;\n        std::vector<Edge> reverse_index;\n\n        void create_index(const Graph &g) {\n            std::set<Edge> forest;\n            n = boost::num_vertices(g);\n            m = boost::num_edges(g);\n            k = parmcb::detail::spanning_forest(g, std::inserter(forest, forest.begin()));\n\n            index.clear();\n            reverse_index.resize(m);\n\n            size_type csd = m - n + k; // cycle space dimension\n            size_type low = 0;\n            size_type high = csd;\n\n            EdgeIt ei, eiend;\n            for (boost::tie(ei, eiend) = boost::edges(g); ei != eiend; ++ei) {\n                auto e = *ei;\n                if (forest.find(e) == forest.end()) {\n                    index[e] = low;\n                    reverse_index[low] = e;\n                    low++;\n                } else {\n                    index[e] = high;\n                    reverse_index[high] = e;\n                    high++;\n                }\n            }\n        }\n\n    };\n\n} // namespace parmcb\n\n#endif\n", "meta": {"hexsha": "18f965596ced20dbda9b9a798c13c0472ca504ac", "size": 3113, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/parmcb/forestindex.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/forestindex.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/forestindex.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": 26.1596638655, "max_line_length": 90, "alphanum_fraction": 0.5216832637, "num_tokens": 702, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952052, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.48425791452311673}}
{"text": "#ifndef BOOST_ASTRONOMY_IO_IMAGE_HPP\n#define BOOST_ASTRONOMY_IO_IMAGE_HPP\n\n\n#include <valarray>\n#include <fstream>\n#include <cstddef>\n#include <algorithm>\n#include <iterator>\n#include <cstdint>\n#include <string>\n#include <cmath>\n#include <numeric>\n\n#include <boost/endian/conversion.hpp>\n#include <boost/cstdfloat.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    //! Used purly for Type punning\n    union pixel_data\n    {\n        PixelType pixel;\n        std::uint8_t byte[sizeof(PixelType)];\n        //char byte[sizeof(PixelType)];\n    };\n\npublic:\n    image_buffer() {}\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    virtual ~image_buffer() {}\n\n    //! returns the maximum value of all the pixels in the image\n    PixelType max() const\n    {\n        return this->data.max();\n    }\n\n    //! returns the manimum value of all the pixels in the image\n    PixelType min() const\n    {\n        return this->data.min();\n    }\n\n    //! returns the mean value of all the pixels in image\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    //! returns the median of all the pixel values in the image \n    //! Note: uses additional space of order O(n) where n is the number of total pixels\n    PixelType median() const\n    {\n        std::valarray<PixelType> soreted_array = this->data;\n        std::nth_element(std::begin(soreted_array),\n            std::begin(soreted_array) + soreted_array.size() / 2, std::end(soreted_array));\n\n        return soreted_array[soreted_array.size() / 2];\n    }\n\n    //! returns the standard deviation of all the pixel values in the image \n    //! Note: uses additional space of order O(n) where n is the number of total pixels\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    PixelType operator() (std::size_t x, std::size_t y)\n    {\n        return this->data[(x*this->width) + y];\n    }\n};\n\n\ntemplate<bitpix args>\nstruct image {};\n\n\ntemplate <>\nstruct image<bitpix::B8> : public image_buffer<std::uint8_t>\n{\npublic:\n    image() {}\n\n    image(std::string const& file, std::size_t width, std::size_t height, std::streamoff start) :\n        image_buffer<std::uint8_t>(width, height)\n    {   \n        std::fstream image_file(file);\n        image_file.seekg(start);\n        read_image_logic(image_file);\n        image_file.close();\n    }\n\n    image(std::string const& file, std::size_t width, std::size_t height) :\n        image_buffer<std::uint8_t>(width, height)\n    {\n        std::fstream image_file(file);\n        read_image_logic(image_file);\n        image_file.close();\n    }\n\n    image(std::fstream &file, std::size_t width, std::size_t height, std::streamoff start)\n    {\n        read_image(file, width, height, start);\n    }\n\n    image(std::fstream &file, std::size_t width, std::size_t height)\n    {\n        read_image(file, width, height);\n    }\n\n    void read_image_logic(std::fstream &image_file)\n    {\n        image_file.read((char*)std::begin(data), width*height);\n        //std::copy_n(std::istreambuf_iterator<char>(file.rdbuf()), width*height, std::begin(data));\n    }\n\n    void read_image\n    (\n        std::string const& file,\n        std::size_t width,\n        std::size_t height,\n        std::streamoff start\n    )\n    {\n        std::fstream image_file(file);\n        data.resize(width*height);\n        image_file.seekg(start);\n\n        read_image_logic(image_file);\n\n        image_file.close();\n    }\n\n    void read_image(std::string const& file, std::size_t width, std::size_t height)\n    {\n        read_image(file, width, height, 0);\n    }\n\n    void read_image(std::fstream &file, std::size_t width, std::size_t height, std::streamoff start)\n    {\n        data.resize(width*height);\n        file.seekg(start);\n\n        read_image_logic(file);\n    }\n\n    void read_image(std::fstream &file, std::size_t width, std::size_t height)\n    {\n        read_image(file, width, height, file.tellg());\n    }\n};\n\n\ntemplate <>\nstruct image<bitpix::B16> : public image_buffer<std::int16_t>\n{\npublic:\n    image() {}\n\n    image(std::string const& file, std::size_t width, std::size_t height, std::streamoff start) :\n        image_buffer<std::int16_t>(width, height)\n    {\n        std::fstream image_file(file);\n        image_file.seekg(start);\n        read_image_logic(image_file);\n        image_file.close();\n    }\n\n    image(std::string const& file, std::size_t width, std::size_t height) :\n        image_buffer<std::int16_t>(width, height)\n    {\n        std::fstream image_file(file);\n        read_image_logic(image_file);\n        image_file.close();\n    }\n\n    image(std::fstream &file, std::size_t width, std::size_t height, std::streamoff start)\n    {\n        read_image(file, width, height, start);\n    }\n\n    image(std::fstream &file, std::size_t width, std::size_t height)\n    {\n        read_image(file, width, height);\n    }\n\n    void read_image_logic(std::fstream &image_file)\n    {\n        for (std::size_t i = 0; i < height*width; i++)\n        {\n            image_file.read((char*)&data[i], 2);\n            data[i] = boost::endian::big_to_native(data[i]);\n        }\n    }\n\n    void read_image\n    (\n        std::string const& file,\n        std::size_t width,\n        std::size_t height,\n        std::streamoff start\n    )\n    {\n        std::fstream image_file(file);\n        image_file.open(file);\n        data.resize(width*height);\n        image_file.seekg(start);\n\n        read_image_logic(image_file);\n\n        image_file.close();\n    }\n\n    void read_image(std::string const& file, std::size_t width, std::size_t height)\n    {\n        read_image(file, width, height, 0);\n    }\n\n    void read_image(std::fstream &file, std::size_t width, std::size_t height, std::streamoff start)\n    {\n        data.resize(width*height);\n        file.seekg(start);\n\n        read_image_logic(file);\n    }\n\n    void read_image(std::fstream &file, std::size_t width, std::size_t height)\n    {\n        read_image(file, width, height, file.tellg());\n    }\n};\n\n\ntemplate <>\nstruct image<bitpix::B32> : public image_buffer<std::int32_t>\n{\npublic:\n    image() {}\n\n    image(std::string const& file, std::size_t width, std::size_t height, std::streamoff start) :\n        image_buffer<std::int32_t>(width, height)\n    {\n        std::fstream image_file(file);\n        image_file.seekg(start);\n        read_image_logic(image_file);\n        image_file.close();\n    }\n\n    image(std::string const& file, std::size_t width, std::size_t height) :\n        image_buffer<std::int32_t>(width, height)\n    {\n        std::fstream image_file(file);\n        read_image_logic(image_file);\n        image_file.close();\n    }\n\n    image(std::fstream &file, std::size_t width, std::size_t height, std::streamoff start)\n    {\n        read_image(file, width, height, start);\n    }\n\n    image(std::fstream &file, std::size_t width, std::size_t height)\n    {\n        read_image(file, width, height);\n    }\n\n    void read_image_logic(std::fstream &image_file)\n    {\n        for (std::size_t i = 0; i < height*width; i++)\n        {\n            image_file.read((char*)&data[i], 4);\n            data[i] = boost::endian::big_to_native(data[i]);\n        }\n    }\n\n    //!reads image\n    void read_image\n    (\n        std::string const& file,\n        std::size_t width,\n        std::size_t height,\n        std::streamoff start\n    )\n    {\n        std::fstream image_file(file);\n        data.resize(width*height);\n        image_file.seekg(start);\n\n        read_image_logic(image_file);\n\n        image_file.close();\n    }\n\n    void read_image(std::string const& file, std::size_t width, std::size_t height)\n    {\n        read_image(file, width, height, 0);\n    }\n\n    void read_image(std::fstream &file, std::size_t width, std::size_t height, std::streamoff start)\n    {\n        data.resize(width*height);\n        file.seekg(start);\n\n        read_image_logic(file);\n    }\n\n    void read_image(std::fstream &file, std::size_t width, std::size_t height)\n    {\n        read_image(file, width, height, file.tellg());\n    }\n};\n\n\ntemplate <>\nstruct image<bitpix::_B32> : public image_buffer<boost::float32_t>\n{\npublic:\n    image() {}\n\n    image(std::string const& file, std::size_t width, std::size_t height, std::streamoff start) :\n        image_buffer<boost::float32_t>(width, height)\n    {\n        std::fstream image_file(file);\n        image_file.seekg(start);\n        read_image_logic(image_file);\n        image_file.close();\n    }\n\n    image(std::string const& file, std::size_t width, std::size_t height) :\n        image_buffer<boost::float32_t>(width, height)\n    {\n        std::fstream image_file(file);\n        read_image_logic(image_file);\n        image_file.close();\n    }\n\n    image(std::fstream &file, std::size_t width, std::size_t height, std::streamoff start)\n    {\n        read_image(file, width, height, start);\n    }\n\n    image(std::fstream &file, std::size_t width, std::size_t height)\n    {\n        read_image(file, width, height);\n    }\n\n    void read_image_logic(std::fstream &image_file)\n    {\n        pixel_data single_pixel;\n        for (std::size_t i = 0; i < height*width; i++)\n        {\n            image_file.read((char*)single_pixel.byte, 4);\n            data[i] = (single_pixel.byte[3] << 0) | (single_pixel.byte[2] << 8) |\n                (single_pixel.byte[1] << 16) | (single_pixel.byte[0] << 24);\n        }\n    }\n\n    void read_image\n    (\n        std::string const& file,\n        std::size_t width,\n        std::size_t height,\n        std::streamoff start\n    )\n    {\n        std::fstream image_file(file);\n        data.resize(width*height);\n        image_file.seekg(start);\n\n        read_image_logic(image_file);\n        image_file.close();\n    }\n\n    void read_image(std::string const& file, std::size_t width, std::size_t height)\n    {\n        read_image(file, width, height, 0);\n    }\n\n    void read_image(std::fstream &file, std::size_t width, std::size_t height, std::streamoff start)\n    {\n        data.resize(width*height);\n        file.seekg(start);\n\n        read_image_logic(file);\n    }\n\n    void read_image(std::fstream &file, std::size_t width, std::size_t height)\n    {\n        read_image(file, width, height, file.tellg());\n    }\n};\n\n\ntemplate <>\nstruct image<bitpix::_B64> : public image_buffer<boost::float64_t>\n{\npublic:\n    image() {}\n\n    image(std::string const& file, std::size_t width, std::size_t height, std::streamoff start) :\n        image_buffer<boost::float64_t>(width, height)\n    {\n        std::fstream image_file(file);\n        image_file.seekg(start);\n        read_image_logic(image_file);\n        image_file.close();\n    }\n\n    image(std::string const& file, std::size_t width, std::size_t height) :\n        image_buffer<boost::float64_t>(width, height)\n    {\n        std::fstream image_file(file);\n        read_image_logic(image_file);\n        image_file.close();\n    }\n\n    image(std::fstream &file, std::size_t width, std::size_t height, std::streamoff start)\n    {\n        read_image(file, width, height, start);\n    }\n\n    image(std::fstream &file, std::size_t width, std::size_t height)\n    {\n        read_image(file, width, height);\n    }\n\n    void read_image_logic(std::fstream &image_file)\n    {\n        pixel_data single_pixel;\n        for (std::size_t i = 0; i < height*width; i++)\n        {\n            image_file.read((char*)single_pixel.byte, 8);\n            data[i] = (single_pixel.byte[7] << 0) | (single_pixel.byte[6] << 8) |\n                (single_pixel.byte[5] << 16) | (single_pixel.byte[4] << 24) |\n                (single_pixel.byte[3] << 32) | (single_pixel.byte[2] << 40) |\n                (single_pixel.byte[1] << 48) | (single_pixel.byte[0] << 56);\n        }\n    }\n\n    void read_image\n    (\n        std::string const& file,\n        std::size_t width,\n        std::size_t height,\n        std::streamoff start\n    )\n    {\n        std::fstream image_file(file);\n        data.resize(width*height);\n        image_file.seekg(start);\n\n        read_image_logic(image_file);\n\n        image_file.close();\n    }\n\n    void read_image(std::string const& file, std::size_t width, std::size_t height)\n    {\n        read_image(file, width, height, 0);\n    }\n\n    void read_image(std::fstream &file, std::size_t width, std::size_t height, std::streamoff start)\n    {\n        data.resize(width*height);\n        file.seekg(start);\n\n        read_image_logic(file);\n    }\n\n    void read_image(std::fstream &file, std::size_t width, std::size_t height)\n    {\n        read_image(file, width, height, file.tellg());\n    }\n};\n\n}}} //namespace boost::astronomy::io\n\n#endif // !BOOST_ASTRONOMY_IO_IMAGE_HPP\n", "meta": {"hexsha": "69c345328889328aa8d78169bd04f25a12e2a6a6", "size": 13430, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/astronomy/io/image.hpp", "max_stars_repo_name": "RohitRanjangit/astronomy", "max_stars_repo_head_hexsha": "2a312f24a54a8f0ebe59e6c817d162611c8bee8e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-29T06:42:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-29T06:42:49.000Z", "max_issues_repo_path": "include/boost/astronomy/io/image.hpp", "max_issues_repo_name": "RohitRanjangit/astronomy", "max_issues_repo_head_hexsha": "2a312f24a54a8f0ebe59e6c817d162611c8bee8e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/astronomy/io/image.hpp", "max_forks_repo_name": "RohitRanjangit/astronomy", "max_forks_repo_head_hexsha": "2a312f24a54a8f0ebe59e6c817d162611c8bee8e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9266409266, "max_line_length": 100, "alphanum_fraction": 0.5960536113, "num_tokens": 3406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056040203135, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.48425790984831674}}
{"text": "#include \"statutil.h\"\n\n#include <algorithm>\n\n#define BOOST_MATH_DOMAIN_ERROR_POLICY ignore_error\n#include <boost/math/distributions/fisher_f.hpp>\n\n#include \"lapack.h\"\n#include \"vectorutil.h\"\n\ndouble fpval(double x, double df1, double df2)\n{\n    boost::math::fisher_f f(df1, df2);\n    return boost::math::cdf(boost::math::complement(f, x));\n}\n\ndouble eps(double x)\n{\n    if (!std::isfinite(x))\n        return std::numeric_limits<double>::quiet_NaN();\n\n    if (std::fabs(x) < std::numeric_limits<double>::min())\n        return std::numeric_limits<double>::denorm_min();\n\n    int exponent;\n    std::frexp(x, &exponent);\n\n    int digits = std::numeric_limits<double>::digits;\n\n    return std::ldexp(1, exponent - digits);\n}\n", "meta": {"hexsha": "f37f36d89109b339f2f854076fb9469fc13ed91d", "size": 720, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rtm-gwas-assoc/src/statutil.cpp", "max_stars_repo_name": "njau-sri/rtm-gwas", "max_stars_repo_head_hexsha": "39978253487dd4d0acd6b32928861ceea26685ef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2019-09-29T13:55:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T05:47:33.000Z", "max_issues_repo_path": "rtm-gwas-assoc/src/statutil.cpp", "max_issues_repo_name": "njau-sri/rtm-gwas", "max_issues_repo_head_hexsha": "39978253487dd4d0acd6b32928861ceea26685ef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rtm-gwas-assoc/src/statutil.cpp", "max_forks_repo_name": "njau-sri/rtm-gwas", "max_forks_repo_head_hexsha": "39978253487dd4d0acd6b32928861ceea26685ef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-11-26T01:02:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-30T09:06:46.000Z", "avg_line_length": 22.5, "max_line_length": 59, "alphanum_fraction": 0.6791666667, "num_tokens": 187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358014, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4841782475313231}}
{"text": "#include <CGAL/Simple_cartesian.h>\n#include <CGAL/Surface_mesh.h>\n\n#include <CGAL/boost/graph/helpers.h>\n#include <CGAL/Polygon_mesh_processing/connected_components.h>\n#include <CGAL/property_map.h>\n\n#include <boost/property_map/function_property_map.hpp>\n\n#include <iostream>\n#include <fstream>\n#include <cstring>\n\nnamespace PMP = CGAL::Polygon_mesh_processing;\n\ntypedef CGAL::Simple_cartesian<double>     Kernel;\ntypedef Kernel::Point_3                    Point;\ntypedef Kernel::Compare_dihedral_angle_3   Compare_dihedral_angle_3;\ntypedef CGAL::Surface_mesh<Point>          Mesh;\n\ntemplate <typename G, typename GT>\nstruct Constraint\n{\n  typedef typename GT::FT                                  FT;\n\n  typedef typename boost::graph_traits<G>::edge_descriptor edge_descriptor;\n  typedef boost::readable_property_map_tag                 category;\n  typedef bool                                             value_type;\n  typedef bool                                             reference;\n  typedef edge_descriptor                                  key_type;\n\n  Constraint() : g(nullptr), gt(nullptr), bound(0) {}\n  Constraint(const G& g, const GT& gt, const FT bound) : g(&g), gt(&gt), bound(bound) {}\n\n  bool operator[](const edge_descriptor e) const\n  {\n    const Mesh& rg = *g;\n\n    return gt->compare_dihedral_angle_3_object()(\n             rg.point(source(e, rg)),\n             rg.point(target(e, rg)),\n             rg.point(target(next(halfedge(e, rg), rg), rg)),\n             rg.point(target(next(opposite(halfedge(e, rg), rg), rg), rg)),\n          bound) == CGAL::SMALLER;\n  }\n\n  friend inline\n  value_type get(const Constraint& m, const key_type k)\n  {\n    return m[k];\n  }\n\n  const G* g;\n  const GT* gt;\n  FT bound;\n};\n\ntemplate <typename G, typename GT>\nstruct Face_descriptor_area_functor\n{\n  typedef typename boost::graph_traits<G>::face_descriptor     face_descriptor;\n\n  Face_descriptor_area_functor(const G& g, const GT& gt) : g(g), gt(gt) { }\n\n  typename GT::FT operator()(const face_descriptor f) const\n  {\n    const auto& vpm = get(CGAL::vertex_point, g);\n\n    return gt.compute_area_3_object()(get(vpm, source(halfedge(f, g), g)),\n                                      get(vpm, target(halfedge(f, g), g)),\n                                      get(vpm, target(next(halfedge(f, g), g), g)));\n  }\n\n  const G& g;\n  const GT& gt;\n};\n\nvoid test_CC_with_default_size_map(Mesh sm,\n                                   const Kernel& k)\n{\n  std::cout << \" -- test with default size map -- \" << std::endl;\n\n  typedef boost::graph_traits<Mesh>::face_descriptor                      face_descriptor;\n  typedef Kernel::FT                                                      FT;\n\n  const FT bound = std::cos(0.7 * CGAL_PI);\n\n  std::vector<face_descriptor> cc;\n  face_descriptor fd = *faces(sm).first;\n  CGAL::Polygon_mesh_processing::connected_component(fd, sm, std::back_inserter(cc));\n\n  std::cerr << \"connected components without edge constraints\" << std::endl;\n  std::cerr << cc.size() << \" faces in the CC of \" << fd << std::endl;\n  assert(cc.size() == 1452);\n\n  std::cerr << \"\\nconnected components with edge constraints (dihedral angle < 3/4 pi)\" << std::endl;\n  Mesh::Property_map<face_descriptor,std::size_t> fccmap;\n  fccmap = sm.add_property_map<face_descriptor, std::size_t>(\"f:CC\").first;\n  std::size_t num = PMP::connected_components(sm, fccmap);\n\n  std::cerr << \"The graph has \" << num << \" connected components (face connectivity)\" << std::endl;\n  assert(num == 3);\n\n  std::vector<face_descriptor> one_face_per_cc(num);\n  std::vector<std::size_t> cc_size(num,0);\n\n  for(face_descriptor f : faces(sm))\n  {\n    //    std::cout  << f << \" in connected component \" << fccmap[f] << std::endl;\n    std::size_t ccid=fccmap[f];\n    if (++cc_size[ccid]==1)\n      one_face_per_cc[ccid]=f;\n  }\n\n  std::size_t id_of_cc_to_remove = std::distance(cc_size.begin(),\n                                                 std::min_element(cc_size.begin(), cc_size.end()));\n\n  Mesh copy1 = sm;\n  Mesh copy2 = sm;\n\n  // remove cc from copy1\n  std::vector<face_descriptor> ff;\n  for (std::size_t i=0;i<num;++i)\n    if (i!=id_of_cc_to_remove)\n      ff.push_back(one_face_per_cc[i]);\n\n  // default face size map, but explicitely passed\n  PMP::keep_connected_components(copy1, ff,\n     PMP::parameters::edge_is_constrained_map(Constraint<Mesh, Kernel>(copy1, k, bound))\n                     .face_size_map(CGAL::Constant_property_map<face_descriptor, std::size_t>(1)));\n\n  // remove cc from copy2\n  ff.clear();\n  ff.push_back(one_face_per_cc[id_of_cc_to_remove]);\n  PMP::remove_connected_components(copy2, ff,\n     PMP::parameters::edge_is_constrained_map(Constraint<Mesh, Kernel>(copy2, k, bound)));\n\n  std::cerr << \"We keep the \" << num-1 << \" largest components\" << std::endl;\n  PMP::keep_largest_connected_components(sm, num-1,\n    PMP::parameters::edge_is_constrained_map(Constraint<Mesh, Kernel>(sm, k, bound)));\n\n  sm.collect_garbage();\n  copy1.collect_garbage();\n  copy2.collect_garbage();\n\n  assert( num_vertices(sm)==num_vertices(copy1) && num_vertices(copy1)==num_vertices(copy2) );\n  assert( num_edges(sm)==num_edges(copy1) && num_edges(copy1)==num_edges(copy2) );\n  assert( num_faces(sm)==num_faces(copy1) && num_faces(copy1)==num_faces(copy2) );\n\n  {\n    Mesh m;\n    Point p(0,0,0), q(1,0,0), r(0,1,0), s(0,0,1);\n    CGAL::make_tetrahedron(p,q,r,s,m);\n    CGAL::make_triangle(p,q,r,m);\n    CGAL::make_tetrahedron(p,q,r,s,m);\n    PMP::keep_large_connected_components(m, 4);\n\n    assert(vertices(m).size() == 8);\n  }\n}\n\nvoid test_CC_with_area_size_map(Mesh sm,\n                                const Kernel& k)\n{\n  std::cout << \" -- test with area size map -- \" << std::endl;\n\n  typedef boost::graph_traits<Mesh>::face_descriptor                      face_descriptor;\n\n  Face_descriptor_area_functor<Mesh, Kernel> f(sm, k);\n  std::vector<face_descriptor> faces_to_remove; // faces that would be removed but are not because we're doing a dry run\n  std::size_t nv = num_vertices(sm);\n  std::size_t num = PMP::internal::number_of_connected_components(sm);\n\n  std::cout << \"We keep the \" << 2 << \" largest components\" << std::endl;\n  std::size_t res = PMP::keep_largest_connected_components(sm, 2,\n                                                           PMP::parameters::face_size_map(boost::make_function_property_map<face_descriptor>(f))\n                                                                           .dry_run(true)\n                                                                           .output_iterator(std::back_inserter(faces_to_remove)));\n\n  // didn't actually remove anything\n  assert(PMP::internal::number_of_connected_components(sm) == num);\n  assert(num_vertices(sm) == nv);\n\n  if(num > 2)\n  {\n    assert(res == num - 2);\n    assert(!faces_to_remove.empty());\n  }\n\n  PMP::keep_largest_connected_components(sm, 2,\n                                         PMP::parameters::face_size_map(\n                                           boost::make_function_property_map<face_descriptor>(f)));\n  assert(vertices(sm).size() == 1459);\n\n  {\n    Mesh m;\n\n    Point p(0,0,0), q(1,0,0), r(0,1,0), s(0,0,1);\n    CGAL::make_tetrahedron(p,q,r,s,m);\n    CGAL::make_tetrahedron(p,q,r,s,m);\n\n    Point t(100,100,100);\n    CGAL::make_triangle(p,q,t,m);\n\n    Face_descriptor_area_functor<Mesh, Kernel> f(m, k);\n    PMP::keep_large_connected_components(m, 10,\n                                         CGAL::parameters::face_size_map(\n                                           boost::make_function_property_map<face_descriptor>(f)));\n    assert(vertices(m).size() == 3);\n\n    PMP::keep_largest_connected_components(m, 1);\n    assert(PMP::internal::number_of_connected_components(m) == 1);\n    PMP::keep_largest_connected_components(m, 0);\n    assert(is_empty(m));\n    assert(PMP::internal::number_of_connected_components(m) == 0);\n  }\n}\n\nint main(int /*argc*/, char** /*argv*/)\n{\n  const std::string filename = CGAL::data_file_path(\"meshes/blobby_3cc.off\");\n  Mesh sm;\n  std::ifstream in(filename);\n  assert(in.good());\n  in >> sm;\n\n  Kernel k;\n\n  std::cout << \"VEF \" << num_vertices(sm) << \" \" << num_edges(sm) << \" \" << num_faces(sm) << \"\\n\";\n\n  test_CC_with_default_size_map(sm, k);\n  test_CC_with_area_size_map(sm, k);\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "5873e6073eb64b29527d6dcf5dd3a8ee25abfb9c", "size": 8254, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Polygon_mesh_processing/test/Polygon_mesh_processing/connected_component_surface_mesh.cpp", "max_stars_repo_name": "brucerennie/cgal", "max_stars_repo_head_hexsha": "314b94aafa9b08a1d086accd2cadff1aae1b57a9", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 3227.0, "max_stars_repo_stars_event_min_datetime": "2015-03-05T00:19:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:20:35.000Z", "max_issues_repo_path": "Polygon_mesh_processing/test/Polygon_mesh_processing/connected_component_surface_mesh.cpp", "max_issues_repo_name": "brucerennie/cgal", "max_issues_repo_head_hexsha": "314b94aafa9b08a1d086accd2cadff1aae1b57a9", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 5574.0, "max_issues_repo_issues_event_min_datetime": "2015-03-05T00:01:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:08:11.000Z", "max_forks_repo_path": "Polygon_mesh_processing/test/Polygon_mesh_processing/connected_component_surface_mesh.cpp", "max_forks_repo_name": "brucerennie/cgal", "max_forks_repo_head_hexsha": "314b94aafa9b08a1d086accd2cadff1aae1b57a9", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1274.0, "max_forks_repo_forks_event_min_datetime": "2015-03-05T00:01:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:47:56.000Z", "avg_line_length": 34.9745762712, "max_line_length": 144, "alphanum_fraction": 0.6149745578, "num_tokens": 2107, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4841782423998309}}
{"text": "/*\r\n * Copyright 2018 Pedro Proenza <p.proenca@surrey.ac.uk> (University of Surrey)\r\n *\r\n */\r\n\r\n#include <iostream>\r\n#include <cstdio>\r\n#define _USE_MATH_DEFINES\r\n#include <math.h>\r\n#include <opencv2/opencv.hpp>\r\n#include <Eigen/Dense>\r\n\r\n#include \"CAPE/CAPE.h\"\r\n#include \"RSCamera.h\"\r\n\r\nbool done = false;\r\nfloat COS_ANGLE_MAX = cos(M_PI/12);\r\nfloat MAX_MERGE_DIST = 50.0f;\r\nbool cylinder_detection= true;\r\nCAPE * plane_detector;\r\nstd::vector<cv::Vec3b> color_code;\r\n\r\n// void draw3DCoordinateAxes(cv::Mat image, const std::vector<cv::Point2f> &list_points2d){\r\n//     cv::Scalar red(0, 0, 255);\r\n//     cv::Scalar green(0,255,0);\r\n//     cv::Scalar blue(255,0,0);\r\n//     cv::Scalar black(0,0,0);\r\n\r\n//     cv::Point2i origin = list_points2d[0];\r\n//     cv::Point2i pointX = list_points2d[1];\r\n//     cv::Point2i pointY = list_points2d[2];\r\n//     cv::Point2i pointZ = list_points2d[3];\r\n\r\n//     drawArrow(image, origin, pointX, red, 9, 2);\r\n//     drawArrow(image, origin, pointY, green, 9, 2);\r\n//     drawArrow(image, origin, pointZ, blue, 9, 2);\r\n//     cv::circle(image, origin, radius/2, black, -1, lineType );\r\n// }\r\n\r\nbool loadCalibParameters(std::string filepath, cv:: Mat & intrinsics_rgb, cv::Mat & dist_coeffs_rgb, cv:: Mat & intrinsics_ir, cv::Mat & dist_coeffs_ir, cv::Mat & R, cv::Mat & T){\r\n\r\n    cv::FileStorage fs(filepath,cv::FileStorage::READ);\r\n    if (fs.isOpened()){\r\n        fs[\"RGB_intrinsic_params\"]        >> intrinsics_rgb;\r\n        fs[\"RGB_distortion_coefficients\"] >> dist_coeffs_rgb;\r\n        fs[\"IR_intrinsic_params\"]         >> intrinsics_ir;\r\n        fs[\"IR_distortion_coefficients\"]  >> dist_coeffs_ir;\r\n        fs[\"Rotation\"]                    >> R;\r\n        fs[\"Translation\"]                 >> T;\r\n        fs.release();\r\n        return true;\r\n    }else{\r\n        std::cerr << \"Calibration file missing\" << std::endl;\r\n        return false;\r\n    }\r\n}\r\n\r\nint main(int argc, char ** argv){   \r\n\r\n    RSCamera* camera = new RSCamera();\r\n    if(!camera->init(0)){\r\n        std::cout << \"Error inicializating camera \\n\";\r\n        return -1;\r\n    }\r\n    for(int i = 0 ; i < 10 ; i++)\r\n        camera->grab();\r\n\r\n    // Create window\r\n    cv::namedWindow(\"Segmentation\",cv::WINDOW_AUTOSIZE);\r\n    cv::namedWindow(\"mask\",cv::WINDOW_AUTOSIZE);\r\n    cvStartWindowThread();\r\n\r\n    cv::Mat intrinsics, coeffs;\r\n    camera->leftCalibration(intrinsics, coeffs);\r\n\r\n    // Get intrinsics\r\n    cv::Mat K_rgb, K_ir, dist_coeffs_rgb, dist_coeffs_ir, R_stereo, t_stereo;\r\n    std::stringstream calib_path;\r\n    calib_path << \"/home/grvc/programming/CAPE/Data/pipe/calib_params_2.xml\";\r\n    loadCalibParameters(calib_path.str(), K_rgb, dist_coeffs_rgb, K_ir, dist_coeffs_ir, R_stereo, t_stereo);\r\n    float fx_ir  = K_ir.at<double>(0,0);  float fy_ir  = K_ir.at<double>(1,1);\r\n    float cx_ir  = K_ir.at<double>(0,2);  float cy_ir  = K_ir.at<double>(1,2);\r\n    float fx_rgb = K_rgb.at<double>(0,0); float fy_rgb = K_rgb.at<double>(1,1);\r\n    float cx_rgb = K_rgb.at<double>(0,2); float cy_rgb = K_rgb.at<double>(1,2);\r\n\r\n    cv::Mat left, rigth;\r\n    if(!camera->rgb(left, rigth)){\r\n        std::cout << \"Error getting first color frame \\n\";\r\n        return -1;\r\n    }\r\n\r\n    cv::Mat depth;\r\n    if(!camera->depth(depth)){\r\n        std::cout << \"Error getting first depth frame \\n\";\r\n        return -1;\r\n    }\r\n\r\n    int width, height;\r\n    if(left.data){\r\n        width = left.cols;\r\n        height = left.rows;\r\n    }else{\r\n        std::cout << \"Error loading image color dimensions \\n\";\r\n        return -1;\r\n    }\r\n    int PATCH_SIZE = 20;\r\n    int nr_horizontal_cells = width/PATCH_SIZE;\r\n    int nr_vertical_cells = height/PATCH_SIZE;\r\n\r\n    // Pre-computations for backprojection\r\n    cv::Mat_<float> X_pre(height,width);\r\n    cv::Mat_<float> Y_pre(height,width);\r\n    cv::Mat_<float> U(height,width);\r\n    cv::Mat_<float> V(height,width);\r\n    for (int r=0;r<height; r++){\r\n        for (int c=0;c<width; c++){\r\n            // Not efficient but at this stage doesn t matter\r\n            X_pre.at<float>(r,c) = (c-cx_ir)/fx_ir; \r\n            Y_pre.at<float>(r,c) = (r-cy_ir)/fy_ir;\r\n        }\r\n    }\r\n\r\n    // Pre-computations for maping an image point cloud to a cache-friendly array where cell's local point clouds are contiguous\r\n    cv::Mat_<int> cell_map(height,width);\r\n\r\n    for (int r=0;r<height; r++){\r\n        int cell_r = r / PATCH_SIZE;\r\n        int local_r = r % PATCH_SIZE;\r\n\r\n        for (int c=0;c<width; c++){\r\n            int cell_c = c/PATCH_SIZE;\r\n            int local_c = c%PATCH_SIZE;\r\n            cell_map.at<int>(r,c) = (cell_r*nr_horizontal_cells+cell_c)*PATCH_SIZE*PATCH_SIZE + local_r*PATCH_SIZE + local_c;\r\n        }\r\n    }\r\n\r\n    cv::Mat_<float> X(height, width);\r\n    cv::Mat_<float> Y(height, width);\r\n    cv::Mat_<float> X_t(height, width);\r\n    cv::Mat_<float> Y_t(height, width);\r\n    Eigen::MatrixXf cloud_array(width * height, 3);\r\n    Eigen::MatrixXf cloud_array_organized(width * height, 3);\r\n\r\n    // Populate with random color codes\r\n    for(int i=0; i<100;i++){\r\n        cv::Vec3b color;\r\n        color[0]=rand()%255;\r\n        color[1]=rand()%255;\r\n        color[2]=rand()%255;\r\n        color_code.push_back(color);\r\n    }\r\n\r\n    // Add specific colors for planes\r\n    color_code[0][0] = 0;   color_code[0][1] = 0;   color_code[0][2] = 255;\r\n    color_code[1][0] = 255; color_code[1][1] = 0;   color_code[1][2] = 204;\r\n    color_code[2][0] = 255; color_code[2][1] = 100; color_code[2][2] = 0;\r\n    color_code[3][0] = 0;   color_code[3][1] = 153; color_code[3][2] = 255;\r\n    // Add specific colors for cylinders\r\n    color_code[50][0] = 178; color_code[50][1] = 255; color_code[50][2] = 0;\r\n    color_code[51][0] = 255; color_code[51][1] = 0;   color_code[51][2] = 51;\r\n    color_code[52][0] = 0;   color_code[52][1] = 255; color_code[52][2] = 51;\r\n    color_code[53][0] = 153; color_code[53][1] = 0;   color_code[53][2] = 255;\r\n\r\n    // Initialize CAPE\r\n    plane_detector = new CAPE(height, width, PATCH_SIZE, PATCH_SIZE, cylinder_detection, COS_ANGLE_MAX, MAX_MERGE_DIST);\r\n\r\n    while(1){\r\n        camera->grab();\r\n\r\n        cv::Mat left, rigth;\r\n        if(!camera->rgb(left, rigth)){\r\n            std::cout << \"Error color frame \\n\";\r\n            return -1;\r\n        }\r\n    \r\n        cv::Mat depth;\r\n        if(!camera->depth(depth)){\r\n            std::cout << \"Error depth frame \\n\";\r\n            return -1;\r\n        }\r\n        depth.convertTo(depth, CV_32F);\r\n\r\n        // Backproject to point cloud\r\n        X = X_pre.mul(depth); Y = Y_pre.mul(depth);\r\n        cloud_array.setZero();\r\n\r\n        // The following transformation+projection is only necessary to visualize RGB with overlapped segments\r\n        // Transform point cloud to color reference frame\r\n        X_t = ((float)R_stereo.at<double>(0,0))*X + ((float)R_stereo.at<double>(0,1))*Y + ((float)R_stereo.at<double>(0,2))*depth + (float)t_stereo.at<double>(0);\r\n        Y_t = ((float)R_stereo.at<double>(1,0))*X + ((float)R_stereo.at<double>(1,1))*Y + ((float)R_stereo.at<double>(1,2))*depth + (float)t_stereo.at<double>(1);\r\n        depth = ((float)R_stereo.at<double>(2,0))*X + ((float)R_stereo.at<double>(2,1))*Y + ((float)R_stereo.at<double>(2,2))*depth + (float)t_stereo.at<double>(2);\r\n\r\n        CAPE::projectPointCloud(X_t, Y_t, depth, U, V, fx_rgb, fy_rgb, cx_rgb, cy_rgb, t_stereo.at<double>(2), cloud_array);\r\n\r\n        cv::Mat_<cv::Vec3b> seg_rz = cv::Mat_<cv::Vec3b>(height,width,cv::Vec3b(0,0,0));\r\n        cv::Mat_<uchar> seg_output = cv::Mat_<uchar>(height,width,uchar(0));\r\n        cv::Mat_<uchar> seg_output_cylinder = cv::Mat_<uchar>(height,width,uchar(0));\r\n\r\n        // Run CAPE\r\n        int nr_planes, nr_cylinders;\r\n        std::vector<PlaneSeg> plane_params;\r\n        std::vector<CylinderSeg> cylinder_params;\r\n        double t1 = cv::getTickCount();\r\n        CAPE::organizePointCloudByCell(cloud_array, cloud_array_organized, cell_map);\r\n        plane_detector->process(cloud_array_organized, nr_planes, nr_cylinders, seg_output, plane_params, cylinder_params);\r\n        double t2 = cv::getTickCount();\r\n        double time_elapsed = (t2-t1)/(double)cv::getTickFrequency();\r\n        std::cout<<\"Total time elapsed: \" << time_elapsed << \" sec\" << std::endl;\r\n\r\n\r\n        /* Uncomment this block to print model params\r\n        for(int p_id=0; p_id<nr_planes;p_id++){\r\n            cout<<\"[Plane #\"<<p_id<<\"] with \";\r\n            cout<<\"normal: (\"<<plane_params[p_id].normal[0]<<\" \"<<plane_params[p_id].normal[1]<<\" \"<<plane_params[p_id].normal[2]<<\"), \";\r\n            cout<<\"d: \"<<plane_params[p_id].d<<endl;\r\n        }\r\n\r\n        */\r\n        for(int c_id=0; c_id<nr_cylinders;c_id++){\r\n            std::cout << \"[Cylinder #\"<<c_id<<\"] with \";\r\n            std::cout << \"axis: (\"<<cylinder_params[c_id].axis[0]<<\" \"<<cylinder_params[c_id].axis[1]<<\" \"<<cylinder_params[c_id].axis[2]<<\"), \";\r\n            std::cout << \"center: (\" << cylinder_params[c_id].centers[0].transpose()<<\"), \";\r\n            std::cout << \"radius: \" << cylinder_params[c_id].radii[0] << std::endl;\r\n        }\r\n\r\n        // loop to extract cylinder mask\r\n        for(int ii=0; ii < seg_output.rows; ii++){\r\n            for(int jj=0; jj < seg_output.cols; jj++){\r\n                cv::Scalar px = seg_output.at<uchar>(ii,jj);\r\n                if (px[0] > 50){ // cylinder threshold\r\n                    seg_output_cylinder.at<uchar>(ii,jj) = uchar(255); \r\n                }else{\r\n                    seg_output_cylinder.at<uchar>(ii,jj) = uchar(0);\r\n                }\r\n            }\r\n        }\r\n        cv::imshow(\"mask\", seg_output_cylinder);\r\n\r\n        // Map segments with color codes and overlap segmented image w/ RGB\r\n        uchar * sCode;\r\n        uchar * dColor;\r\n        uchar * srgb;\r\n        int code;\r\n        for(int r=0; r<  height; r++){\r\n            dColor = seg_rz.ptr<uchar>(r);\r\n            sCode  = seg_output.ptr<uchar>(r);\r\n            srgb   = left.ptr<uchar>(r);\r\n            for(int c=0; c< width; c++){\r\n                code = *sCode;\r\n                if (code>0){\r\n                    dColor[c*3] =   color_code[code-1][0]/2 + srgb[0]/2;\r\n                    dColor[c*3+1] = color_code[code-1][1]/2 + srgb[1]/2;\r\n                    dColor[c*3+2] = color_code[code-1][2]/2 + srgb[2]/2;\r\n                }else{\r\n                    dColor[c*3]   = srgb[0];\r\n                    dColor[c*3+1] = srgb[1];\r\n                    dColor[c*3+2] = srgb[2];\r\n                }\r\n                sCode++; srgb++; srgb++; srgb++;\r\n            }\r\n        }\r\n\r\n        // Show frame rate and labels\r\n        cv::rectangle(seg_rz,  cv::Point(0,0),cv::Point(width,20), cv::Scalar(0,0,0),-1);\r\n        std::stringstream fps;\r\n        fps << (int)(1/time_elapsed+0.5) << \" fps\";\r\n        cv::putText(seg_rz, fps.str(), cv::Point(15,15), cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(255,255,255,1));\r\n        std::cout << \"Number of cylinders: \" << nr_cylinders << std::endl;\r\n        int cylinder_code_offset = 50;\r\n        // show cylinder labels\r\n        if (nr_cylinders>0){\r\n            std::stringstream text;\r\n            text<<\"Cylinders: \";\r\n            \r\n            cv::putText(seg_rz, text.str(), cv::Point(width/2,15), cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(255,255,255,1));\r\n            for(int j=0;j<nr_cylinders;j++){\r\n                cv::rectangle(seg_rz,  cv::Point(width/2 + 80+15*j,6),cv::Point(width/2 + 90+15*j,16), cv::Scalar(color_code[cylinder_code_offset+j][0],color_code[cylinder_code_offset+j][1],color_code[cylinder_code_offset+j][2]),-1);\r\n            }\r\n        }\r\n        cv::imshow(\"Segmentation\", seg_rz);\r\n    }\r\n\r\n    cv::destroyWindow(\"Segmentation\");\r\n    cv::destroyWindow(\"mask\");\r\n    \r\n    return 0;\r\n}\r\n\r\n", "meta": {"hexsha": "3d6b3954639a304f18f4b0170b247acc4a3f1bd6", "size": 11683, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CAPE/tools/run_cape_online.cpp", "max_stars_repo_name": "mgrova/CAPE", "max_stars_repo_head_hexsha": "7fce3f59e6806bec4062649d8031c04060c6e11d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CAPE/tools/run_cape_online.cpp", "max_issues_repo_name": "mgrova/CAPE", "max_issues_repo_head_hexsha": "7fce3f59e6806bec4062649d8031c04060c6e11d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CAPE/tools/run_cape_online.cpp", "max_forks_repo_name": "mgrova/CAPE", "max_forks_repo_head_hexsha": "7fce3f59e6806bec4062649d8031c04060c6e11d", "max_forks_repo_licenses": ["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.4256055363, "max_line_length": 234, "alphanum_fraction": 0.5645810152, "num_tokens": 3366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4841782423998309}}
{"text": "//\n// Created by Alex Beccaro on 22/01/2019.\n//\n\n#define BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n#include \"../../src/problems/101-150/123/problem123.hpp\"\n\nBOOST_AUTO_TEST_SUITE( Problem123 )\n\n    BOOST_AUTO_TEST_CASE( Example ) {\n        auto res = problems::problem123::solve(9);\n        BOOST_CHECK_EQUAL(res, 7037);\n    }\n\n    BOOST_AUTO_TEST_CASE( Solution ) {\n        auto res = problems::problem123::solve();\n        BOOST_CHECK_EQUAL(res, 21035);\n    }\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "efc9a5ab2e9a2739c0bca92a72aac36c7c65b6b8", "size": 504, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/101-150/test_problem123.cpp", "max_stars_repo_name": "abeccaro/project-euler", "max_stars_repo_head_hexsha": "c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T10:17:15.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-25T10:17:15.000Z", "max_issues_repo_path": "tests/101-150/test_problem123.cpp", "max_issues_repo_name": "abeccaro/project-euler", "max_issues_repo_head_hexsha": "c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3", "max_issues_repo_licenses": ["MIT"], "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/101-150/test_problem123.cpp", "max_forks_repo_name": "abeccaro/project-euler", "max_forks_repo_head_hexsha": "c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.0, "max_line_length": 56, "alphanum_fraction": 0.6825396825, "num_tokens": 127, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081925, "lm_q2_score": 0.7057850278370111, "lm_q1q2_score": 0.48413285519773974}}
{"text": "//          Copyright Carl Philipp Reh 2009 - 2016.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n\n#include <fcppt/literal.hpp>\n#include <fcppt/math/matrix/comparison.hpp>\n#include <fcppt/math/matrix/delete_row_and_column.hpp>\n#include <fcppt/math/matrix/delete_row_and_column_static.hpp>\n#include <fcppt/math/matrix/index.hpp>\n#include <fcppt/math/matrix/output.hpp>\n#include <fcppt/math/matrix/row.hpp>\n#include <fcppt/math/matrix/static.hpp>\n#include <fcppt/preprocessor/disable_gcc_warning.hpp>\n#include <fcppt/preprocessor/pop_warning.hpp>\n#include <fcppt/preprocessor/push_warning.hpp>\n#include <fcppt/config/external_begin.hpp>\n#include <boost/test/unit_test.hpp>\n#include <fcppt/config/external_end.hpp>\n\n\nFCPPT_PP_PUSH_WARNING\nFCPPT_PP_DISABLE_GCC_WARNING(-Weffc++)\n\nBOOST_AUTO_TEST_CASE(\n\tmath_matrix_delete_row_and_column\n)\n{\nFCPPT_PP_POP_WARNING\n\n\ttypedef\n\tfcppt::math::matrix::static_<\n\t\tint,\n\t\t4,\n\t\t3\n\t>\n\tlarge_matrix_type;\n\n\ttypedef\n\tfcppt::math::matrix::static_<\n\t\tint,\n\t\t3,\n\t\t2\n\t>\n\tsmall_matrix_type;\n\n\tlarge_matrix_type const t(\n\t\tfcppt::math::matrix::row(\n\t\t\t1, 2, 3\n\t\t),\n\t\tfcppt::math::matrix::row(\n\t\t\t4, 5, 6\n\t\t),\n\t\tfcppt::math::matrix::row(\n\t\t\t7, 8, 9\n\t\t),\n\t\tfcppt::math::matrix::row(\n\t\t\t10, 11, 12\n\t\t)\n\t);\n\n\tBOOST_CHECK_EQUAL(\n\t\tfcppt::math::matrix::delete_row_and_column(\n\t\t\tt,\n\t\t\tfcppt::literal<\n\t\t\t\tlarge_matrix_type::size_type\n\t\t\t>(\n\t\t\t\t2\n\t\t\t),\n\t\t\tfcppt::literal<\n\t\t\t\tlarge_matrix_type::size_type\n\t\t\t>(\n\t\t\t\t1\n\t\t\t)\n\t\t),\n\t\tsmall_matrix_type(\n\t\t\tfcppt::math::matrix::row(\n\t\t\t\t1, 3\n\t\t\t),\n\t\t\tfcppt::math::matrix::row(\n\t\t\t\t4, 6\n\t\t\t),\n\t\t\tfcppt::math::matrix::row(\n\t\t\t\t10, 12\n\t\t\t)\n\t\t)\n\t);\n\n\tBOOST_CHECK_EQUAL(\n\t\tfcppt::math::matrix::delete_row_and_column(\n\t\t\tt,\n\t\t\tfcppt::literal<\n\t\t\t\tlarge_matrix_type::size_type\n\t\t\t>(\n\t\t\t\t0\n\t\t\t),\n\t\t\tfcppt::literal<\n\t\t\t\tlarge_matrix_type::size_type\n\t\t\t>(\n\t\t\t\t0\n\t\t\t)\n\t\t),\n\t\tsmall_matrix_type(\n\t\t\tfcppt::math::matrix::row(\n\t\t\t\t5, 6\n\t\t\t),\n\t\t\tfcppt::math::matrix::row(\n\t\t\t\t8, 9\n\t\t\t),\n\t\t\tfcppt::math::matrix::row(\n\t\t\t\t11, 12\n\t\t\t)\n\t\t)\n\t);\n}\n\nFCPPT_PP_PUSH_WARNING\nFCPPT_PP_DISABLE_GCC_WARNING(-Weffc++)\n\nBOOST_AUTO_TEST_CASE(\n\tmath_matrix_delete_row_and_column_static\n)\n{\nFCPPT_PP_POP_WARNING\n\n\ttypedef\n\tfcppt::math::matrix::static_<\n\t\tint,\n\t\t4,\n\t\t3\n\t>\n\tlarge_matrix_type;\n\n\ttypedef\n\tfcppt::math::matrix::static_<\n\t\tint,\n\t\t3,\n\t\t2\n\t>\n\tsmall_matrix_type;\n\n\tlarge_matrix_type const t(\n\t\tfcppt::math::matrix::row(\n\t\t\t1, 2, 3\n\t\t),\n\t\tfcppt::math::matrix::row(\n\t\t\t4, 5, 6\n\t\t),\n\t\tfcppt::math::matrix::row(\n\t\t\t7, 8, 9\n\t\t),\n\t\tfcppt::math::matrix::row(\n\t\t\t10, 11, 12\n\t\t)\n\t);\n\n\tBOOST_CHECK_EQUAL(\n\t\tfcppt::math::matrix::delete_row_and_column_static(\n\t\t\tt,\n\t\t\tfcppt::math::matrix::index<\n\t\t\t\t2,\n\t\t\t\t1\n\t\t\t>{}\n\t\t),\n\t\tsmall_matrix_type(\n\t\t\tfcppt::math::matrix::row(\n\t\t\t\t1, 3\n\t\t\t),\n\t\t\tfcppt::math::matrix::row(\n\t\t\t\t4, 6\n\t\t\t),\n\t\t\tfcppt::math::matrix::row(\n\t\t\t\t10, 12\n\t\t\t)\n\t\t)\n\t);\n\n\tBOOST_CHECK_EQUAL(\n\t\tfcppt::math::matrix::delete_row_and_column_static(\n\t\t\tt,\n\t\t\tfcppt::math::matrix::index<\n\t\t\t\t0,\n\t\t\t\t0\n\t\t\t>{}\n\t\t),\n\t\tsmall_matrix_type(\n\t\t\tfcppt::math::matrix::row(\n\t\t\t\t5, 6\n\t\t\t),\n\t\t\tfcppt::math::matrix::row(\n\t\t\t\t8, 9\n\t\t\t),\n\t\t\tfcppt::math::matrix::row(\n\t\t\t\t11, 12\n\t\t\t)\n\t\t)\n\t);\n}\n", "meta": {"hexsha": "c606927582ae454125a5c33cabd83b7e69bfa517", "size": 3233, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/math/matrix/delete_row_and_column.cpp", "max_stars_repo_name": "vinzenz/fcppt", "max_stars_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "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": "test/math/matrix/delete_row_and_column.cpp", "max_issues_repo_name": "vinzenz/fcppt", "max_issues_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "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/math/matrix/delete_row_and_column.cpp", "max_forks_repo_name": "vinzenz/fcppt", "max_forks_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "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": 16.165, "max_line_length": 61, "alphanum_fraction": 0.6418187442, "num_tokens": 1185, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850154599562, "lm_q2_score": 0.6859494614282922, "lm_q1q2_score": 0.4841328512389158}}
{"text": "// File generated on Thu Aug 21, 2014 06:00:18 PM by xcpp.\n#define XC_CPP\n#include <armadillo>\n#include <xc>\n\n\nnamespace excentury {\nXC_DUMP_TEMPLATED_TENSOR(class elementType, arma::Mat<elementType>, m, m.mem[0]) {\n    size_t ndims = 2;\n    unsigned char rm = 0;\n    XC_BYTE(rm);\n    XC_SIZE(ndims);\n    size_t size = m.n_elem;\n    size_t dim[2] = {m.n_rows, m.n_cols};\n    XC_ARRAY(dim, ndims);\n    XC_ARRAY(m.mem, size);\n}\nXC_LOAD_TEMPLATED_TENSOR(class elementType, arma::Mat<elementType>, m) {\n    size_t ndims;\n    unsigned char rm;\n    XC_BYTE(rm);\n    if (rm != 0) {\n        char msg[500];\n        sprintf(msg, \"Armadillo Mat::load:\\n\"\n                \"    RM mismatch, got %d, needs %d.\", rm, 0);\n        excentury::error(msg);\n    }\n    XC_SIZE(ndims);\n    if (ndims != 2) {\n        char msg[500];\n        sprintf(msg, \"Armadillo Mat::load('%s'):\\n\" \\\n                \"    dimension mismatch, needs dim = 2\", varname);\n        excentury::error(msg);\n    }\n    size_t* dim = new size_t[ndims];\n    XC_ARRAY(dim, ndims);\n    m.resize(dim[0], dim[1]);\n    elementType* mem = const_cast<elementType*>(m.mem);\n    XC_ARRAY(mem, m.n_elem);\n    delete [] dim;\n}\n}\nvoid xc_help() {\n    fprintf(stderr,\n    \"program: arma-ex1\\n\"\n    \"\\ndescription:\\n\"\n    \"    Armadillo example 2: Computes the determinant and inverse of a\\n\"\n    \"    matrix.\\n\"\n    \"\\nparameters:\\n\"\n    \"    `A`: input matrix\\n\"\n    \"\\n\");\n}\nvoid xc_input() {\n    xc_help();\n    excentury::TextInterface<excentury::dump_mode> XC_DI_(stdout);\n    arma::mat A(2, 2); XC_DI_.dump(A, \"A\", A(0,0));\n    XC_DI_.close();\n}\nint main(int argc, char** argv) {\n    /*Armadillo example 2: Computes the determinant and inverse of a\n    matrix.*/\n    excentury::check_inputs(argc);\n    excentury::print_help(argv, xc_help);\n    excentury::print_inputs(argv, xc_input);\n    excentury::STextInterface<excentury::load_mode> XC_LI_(argv[1]);\n    arma::mat A(2, 2); XC_LI_.load(A, A(0,0));\n    XC_LI_.close();\n\n    double d = det(A);\n    arma::mat Ainv;\n    try {\n        Ainv = inv(A);\n    } catch (std::runtime_error& run_error) {\n        excentury::error(run_error.what());\n    }\n\n    excentury::TextInterface<excentury::dump_mode> XC_DI_(stdout);\n    XC_DI_.dump(d, \"detA\");\n    XC_DI_.dump(Ainv, \"Ainv\", Ainv(0, 0));\n    XC_DI_.close();\n}\n\n", "meta": {"hexsha": "78ba2e46bd35d8543cd5397331e19d9d648378cb", "size": 2297, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/cpp/arma-ex1.cpp", "max_stars_repo_name": "LaudateCorpus1/excentury", "max_stars_repo_head_hexsha": "8d0f20bb3e543382170e042fac51a56377c4024b", "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": "tests/cpp/arma-ex1.cpp", "max_issues_repo_name": "LaudateCorpus1/excentury", "max_issues_repo_head_hexsha": "8d0f20bb3e543382170e042fac51a56377c4024b", "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": "tests/cpp/arma-ex1.cpp", "max_forks_repo_name": "LaudateCorpus1/excentury", "max_forks_repo_head_hexsha": "8d0f20bb3e543382170e042fac51a56377c4024b", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-31T13:24:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-31T13:24:16.000Z", "avg_line_length": 27.6746987952, "max_line_length": 82, "alphanum_fraction": 0.599042229, "num_tokens": 718, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.6859494485880927, "lm_q1q2_score": 0.4841328506665295}}
{"text": "//\n// Created by jieming on 20.10.20.\n//\n\n#include <array>\n#include <cmath>\n#include <iostream>\n\n#include <Eigen/Dense>\nusing namespace std;\nusing Eigen::MatrixXd;\n\nvoid jointImpedanceControl(){\n    // Compliance parameters\n    const double translational_stiffness{150};\n    const double rotational_stiffness{10};\n    MatrixXd stiffness(6,6), damping(6,6);\n    stiffness.setZero();\n    stiffness.topLeftCorner(3,3) << translational_stiffness*MatrixXd::Identity(3,3);\n    stiffness.bottomRightCorner(3,3) << rotational_stiffness*MatrixXd::Identity(3,3);\n    damping.setZero();\n    damping.topLeftCorner(3, 3) << 2.0 * sqrt(translational_stiffness) * MatrixXd::Identity(3,3);\n    damping.bottomRightCorner(3, 3) << 2.0 * sqrt(rotational_stiffness) * MatrixXd::Identity(3,3);\n\n\n\n}\n", "meta": {"hexsha": "64c8ab2085984cb71a698e95d52e3fa3612e04da", "size": 778, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "panda_simulation/panda_control/src/xxx/joint_impedancecontrol.cpp", "max_stars_repo_name": "jiemingChen/ArmControl", "max_stars_repo_head_hexsha": "1d164489c3f74b1e85c40914ff24d1f49719b3b3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2020-11-27T12:13:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-10T11:32:25.000Z", "max_issues_repo_path": "panda_simulation/panda_control/src/xxx/joint_impedancecontrol.cpp", "max_issues_repo_name": "jiemingChen/ArmControl", "max_issues_repo_head_hexsha": "1d164489c3f74b1e85c40914ff24d1f49719b3b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "panda_simulation/panda_control/src/xxx/joint_impedancecontrol.cpp", "max_forks_repo_name": "jiemingChen/ArmControl", "max_forks_repo_head_hexsha": "1d164489c3f74b1e85c40914ff24d1f49719b3b3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-23T21:33:00.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-23T21:33:00.000Z", "avg_line_length": 27.7857142857, "max_line_length": 98, "alphanum_fraction": 0.7172236504, "num_tokens": 220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110396870287, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.48413146897398573}}
{"text": "#include <armadillo>\n#include <cstring>\n\n#include \"matrix/utility.hh\"\n\n#include \"gyro/gyro_rocket6g.hh\"\n\n#include \"stochastic.hh\"\n\n#include <ctime>\n\nGyroRocket6G::GyroRocket6G(Data_exchang &input)\n    : VECTOR_INIT(EUG, 3),\n      VECTOR_INIT(EWG, 3),\n      VECTOR_INIT(EWALKG, 3),\n      VECTOR_INIT(EUNBG, 3),\n      VECTOR_INIT(EMISG, 3),\n      VECTOR_INIT(ESCALG, 3),\n      VECTOR_INIT(EBIASG, 3),\n      VECTOR_INIT(ITA1, 3),\n      VECTOR_INIT(ITA2, 3),\n      VECTOR_INIT(BETA, 3) {\n  snprintf(name, sizeof(name), \"Rocket6G Gyro Sensor Model\");\n  srand(static_cast<unsigned int>(time(NULL)));\n  data_exchang = &input;\n}\n\nGyroRocket6G::GyroRocket6G(const GyroRocket6G &other) {\n  this->WBICB = other.WBICB;\n  this->EWBIB = other.EWBIB;\n  this->EUG = other.EUG;\n  this->EWG = other.EWG;\n  this->EWALKG = other.EWALKG;\n  this->EUNBG = other.EUNBG;\n  this->EMISG = other.EMISG;\n  this->ESCALG = other.ESCALG;\n  this->EBIASG = other.EBIASG;\n  this->ITA1 = other.ITA1;\n  this->ITA2 = other.ITA2;\n  this->BETA = other.BETA;\n  this->data_exchang = other.data_exchang;\n}\n\nGyroRocket6G &GyroRocket6G::operator=(const GyroRocket6G &other) {\n  if (&other == this) return *this;\n\n  this->WBICB = other.WBICB;\n  this->EWBIB = other.EWBIB;\n  this->EUG = other.EUG;\n  this->EWG = other.EWG;\n  this->EWALKG = other.EWALKG;\n  this->EUNBG = other.EUNBG;\n  this->EMISG = other.EMISG;\n  this->ESCALG = other.ESCALG;\n  this->EBIASG = other.EBIASG;\n  this->ITA1 = other.ITA1;\n  this->ITA2 = other.ITA2;\n  this->BETA = other.BETA;\n  this->data_exchang = other.data_exchang;\n\n  return *this;\n}\n\nvoid GyroRocket6G::algorithm(double int_step) {\n  arma::vec3 WBIB = grab_WBIB();\n  arma::vec3 FSPB = grab_FSPB();\n\n  //-------------------------------------------------------------------------\n  // ARW RRW\n  double sig(1.0);\n  double RRW(0.0130848811);  // 0.4422689813  7.6072577e-3\n  double ARW(0.2828427125);  // 0.07071067812  7.90569415e-3\n  double Freq(200.0);\n\n  for (int i = 0; i < 3; i++) {\n    ITA2(i) =\n        gauss(0, 1.0) * RRW * RAD;  // distribution(generator) * RRW * RAD;\n    BETA(i) = 0.9999 * BETA(i) + ITA2(i) * int_step;\n    ITA1(i) = gauss(0, 1.0) * (ARW * sqrt(Freq) / 60 * (1 / sig)) *\n              RAD;  // distribution(generator) * (ARW * sqrt(Freq) / 60 * (1 /\n                    // sig)) * RAD;\n  }\n\n  // combining all uncertainties\n  this->EWBIB = ITA1 + BETA;  // EMSBG + EUG + EWG;\n\n  this->WBICB = WBIB + EWBIB;\n\n  data_exchang->hset(\"WBICB\", WBICB);\n  return;\n}\n\nint GyroRocket6G::write_to_(const char *bus_name) {\n  int rc = 0;\n  rc |= nxbus_mset(NXBUS_DOUBLE, \"Gyro:_WBICB\", 3, _WBICB);\n  rc |= nxbus_mset(NXBUS_DOUBLE, \"Gyro:_EWBIB\", 3, _EWBIB);\n  return rc;\n}\n", "meta": {"hexsha": "2905c4819e71d791775a234341da711d168738ff", "size": 2671, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "models/sensor/src/gyro/gyro_rocket6g.cpp", "max_stars_repo_name": "cihuang123/Next-simulation", "max_stars_repo_head_hexsha": "e8552a5804184b30022d103d47c8728fb242b5bc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "models/sensor/src/gyro/gyro_rocket6g.cpp", "max_issues_repo_name": "cihuang123/Next-simulation", "max_issues_repo_head_hexsha": "e8552a5804184b30022d103d47c8728fb242b5bc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models/sensor/src/gyro/gyro_rocket6g.cpp", "max_forks_repo_name": "cihuang123/Next-simulation", "max_forks_repo_head_hexsha": "e8552a5804184b30022d103d47c8728fb242b5bc", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-05-05T14:59:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-17T03:19:45.000Z", "avg_line_length": 26.9797979798, "max_line_length": 78, "alphanum_fraction": 0.6158742044, "num_tokens": 991, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951182587159, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.48412440749960745}}
{"text": "/*\n * PoseOptimizationGeometric.cpp\n *\n *  Created on: Aug 30, 2017\n *      Author: P\u00e9ter Fankhauser\n *   Institute: ETH Zurich\n */\n\n#include <free_gait_core/pose_optimization/PoseOptimizationGeometric.hpp>\n\n#include <Eigen/Core>\n#include <Eigen/SVD>\n#include <Eigen/Eigenvalues>\n#include <kindr/Core>\n\nusing namespace Eigen;\n\nnamespace free_gait {\n\nPoseOptimizationGeometric::PoseOptimizationGeometric(const AdapterBase& adapter)\n    : PoseOptimizationBase(adapter)\n{\n}\n\nPoseOptimizationGeometric::~PoseOptimizationGeometric()\n{\n}\n\nvoid PoseOptimizationGeometric::setStanceForOrientation(const Stance& stance)\n{\n  stanceForOrientation_ = stance;\n}\n\nbool PoseOptimizationGeometric::optimize(Pose& pose)\n{\n  checkSupportRegion();\n\n  // Planar position: Use geometric center of support region.\n  Position center;\n  center.vector().head(2) = supportRegion_.getCentroid();\n\n  // Height: Average of stance plus default height.\n  for (const auto& foot : stance_) {\n    center.z() += foot.second.z() - nominalStanceInBaseFrame_.at(foot.first).z();\n  }\n  center.z() /= (double) stance_.size();\n  pose.getPosition() = center;\n\n  // Orientation: Squared error minimization (see sec. 4.2.2 from Bloesch, Technical\n  // Implementations of the Sense of Balance, 2016).\n  // Notes on (38):\n  // - i: Identity pose (I),\n  // - j: Solution (B),\n  // - t = I_r_IB,\n  // - q = q_IB,\n  // - a_k = I_f_k: Foot position for leg k in inertial frame,\n  // - b_k = B_\\hat_f_K: Nominal foot position for leg k in base frame.\n\n  Eigen::Matrix4d C(Eigen::Matrix4d::Zero()); // See (45).\n  Eigen::Matrix4d A(Eigen::Matrix4d::Zero()); // See (46).\n  for (const auto& foot : stance_) {\n    kindr::QuaternionD footPositionInertialFrame(0.0, foot.second.vector()); // \\bar_a_k = S^T * a_k (39).\n    kindr::QuaternionD defaultFootPositionBaseFrame(0.0, nominalStanceInBaseFrame_.at(foot.first).vector()); // \\bar_b_k = S^T * b_k.\n    Eigen::Matrix4d Ak = footPositionInertialFrame.getQuaternionMatrix() - defaultFootPositionBaseFrame.getConjugateQuaternionMatrix(); // See (46).\n    C += Ak * Ak; // See (45).\n    A += Ak; // See (46).\n  }\n  A = A / ((double) stance_.size()); // Error in (46).\n  C -= stance_.size() * A * A; // See (45).\n  Eigen::EigenSolver<Eigen::Matrix4d> eigenSolver(C);\n  int maxCoeff;\n  eigenSolver.eigenvalues().real().maxCoeff(&maxCoeff);\n  // Eigen vector corresponding to max. eigen value.\n  pose.getRotation() = RotationQuaternion(eigenSolver.eigenvectors().col(maxCoeff).real());\n  pose.getRotation().setUnique();\n\n  // Get yaw rotation desired heading direction with respect to the target feet.\n  const Position positionForeFeetMidPointInWorld = (stanceForOrientation_.at(LimbEnum::LF_LEG) + stanceForOrientation_.at(LimbEnum::RF_LEG)) * 0.5;\n  const Position positionHindFeetMidPointInWorld = (stanceForOrientation_.at(LimbEnum::LH_LEG) + stanceForOrientation_.at(LimbEnum::RH_LEG)) * 0.5;\n  Vector desiredHeadingDirectionInWorld = Vector(positionForeFeetMidPointInWorld - positionHindFeetMidPointInWorld);\n  desiredHeadingDirectionInWorld.z() = 0.0;\n  RotationQuaternion desiredHeading;\n  desiredHeading.setFromVectors(Vector::UnitX().toImplementation(), desiredHeadingDirectionInWorld.vector());\n\n  // Apply roll/pitch adaptation factor (~0.7).\n  const RotationQuaternion yawRotation(RotationVector(RotationVector(pose.getRotation()).vector().cwiseProduct(Eigen::Vector3d::UnitZ())));\n  const RotationQuaternion rollPitchRotation(RotationVector(0.7 * RotationVector(yawRotation.inverted() * pose.getRotation()).vector()));\n//  pose.getRotation() = yawRotation * rollPitchRotation; // Alternative.\n  pose.getRotation() = desiredHeading * rollPitchRotation;\n\n  return true;\n}\n\n} /* namespace */\n", "meta": {"hexsha": "80eb68c8cb1ee593db7235d65d3cfbad5826bea6", "size": 3694, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "free_gait_core/src/pose_optimization/PoseOptimizationGeometric.cpp", "max_stars_repo_name": "HeroWithL/free_gaitc", "max_stars_repo_head_hexsha": "ac4bc0ced56d0619d2fde105d2712fdf2507e245", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 330.0, "max_stars_repo_stars_event_min_datetime": "2016-10-25T14:04:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T12:31:41.000Z", "max_issues_repo_path": "free_gait_core/src/pose_optimization/PoseOptimizationGeometric.cpp", "max_issues_repo_name": "HeroWithL/free_gaitc", "max_issues_repo_head_hexsha": "ac4bc0ced56d0619d2fde105d2712fdf2507e245", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 47.0, "max_issues_repo_issues_event_min_datetime": "2016-08-25T14:10:23.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-21T17:25:05.000Z", "max_forks_repo_path": "free_gait_core/src/pose_optimization/PoseOptimizationGeometric.cpp", "max_forks_repo_name": "HeroWithL/free_gaitc", "max_forks_repo_head_hexsha": "ac4bc0ced56d0619d2fde105d2712fdf2507e245", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 122.0, "max_forks_repo_forks_event_min_datetime": "2016-10-25T14:04:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T21:32:51.000Z", "avg_line_length": 38.8842105263, "max_line_length": 148, "alphanum_fraction": 0.7273957769, "num_tokens": 998, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4841243984904623}}
{"text": "#include \"jetEmission.h\"\n\n// Standard C++ libraries\n#include <iomanip>\n\n// Boost libraries\n#include <boost/property_tree/ptree.hpp>\n#include <boost/math/tools/roots.hpp>\n\n// Standard user-made libraries\n#include <fparameters/SpaceIterator.h>\n#include <fparameters/parameters.h>\n#include <fmath/physics.h>\n#include <fparameters/Dimension.h>\n#include <gsl/gsl_sf_bessel.h>\n#include <gsl/gsl_sf_gamma.h>\n#include \"absorption.h\"\n// Project headers\n#include \"globalVariables.h\"\n#include \"messages.h\"\n#include \"read.h\"\n#include \"adafFunctions.h\"\n#include \"write.h\"\n#include <fmath/RungeKutta.h>\n\n#include <fluminosities/thermalSync.h>\n#include <fluminosities/blackBody.h>\n#include \"absorption.h\"\n\n\ndouble n_pl(double g, double gammaC, double gammaMin, double Npl, double pJet)\n{\n\tif (gammaMin > gammaC) {\n\t\tdouble factor = 0.0;\n\t\tif (g > gammaC && g < gammaMin)\n\t\t\tfactor = pow(gammaMin,1.0-pJet)/(g*g);\n\t\telse if (g > gammaMin)\n\t\t\tfactor = pow(g,-(pJet+1.0));\n\t\treturn Npl*(pJet-1.0)*gammaC*factor;\n\t} else {\n\t\tdouble factor = 0.0;\n\t\tif (g >= gammaMin && g <= gammaC)\n\t\t\tfactor = 1.0;\n\t\telse if (g > gammaC)\n\t\t\tfactor = gammaC/g;\n\t\treturn Npl*(pJet-1.0)*factor*pow(g,-pJet);\n\t}\n}\n\ndouble n_pl_2(double g, double Npl, double pJet)\n{\n\treturn Npl*(pJet-1.0)*pow(g,-pJet);\n}\n\ndouble jSyJet(double g, double nu, double magf)\n{\n\tdouble U_B = magf*magf/(8.0*pi);\n\tdouble nuB = electronCharge*magf/(2*pi*electronMass*cLight);\n\tdouble t = nu / (3.0*g*g*nuB);\n\tdouble K_43,K_13;\n\tif (t > 30) {\n\t\tK_43 = K_13 = exp(-t) * sqrt(0.5*pi/t);\n\t} else if (t < 0.01*sqrt(2)) {\n\t\tK_13 = 0.5*gsl_sf_gamma(1.0/3.0) * pow(2.0/t,1.0/3.0);\n\t\tK_43 = 0.5*gsl_sf_gamma(4.0/3.0) * pow(2.0/t,4.0/3.0);\n\t} else {\n\t\tK_43 = gsl_sf_bessel_Knu(4.0/3.0,t);\n\t\tK_13 = gsl_sf_bessel_Knu(1.0/3.0,t);\n\t}\n\treturn 3.0*sqrt(3.0)/pi * thomson * cLight * U_B * t*t * (K_43*K_13-3*t/5 * (K_43*K_43-K_13*K_13));\n}\n\ndouble jSyJet2(double g, double nu, double magf)\n{\n\tdouble nuC = 3.0/(4.0*pi)*electronCharge*magf/(electronMass*cLight) * g*g;\n\tdouble x = nu/nuC;\n\treturn sqrt(3.0)*P3(electronCharge)/electronRestEnergy * magf *1.85*pow(x,1.0/3.0)*exp(-x);\n}\n\ndouble sigma_Sy(double g, double nu, double magf)\n{\n\tdouble nuB = electronCharge*magf/(2*pi*electronMass*cLight);\n\tdouble t = nu/(3*g*g*nuB);\n\tdouble K_43,K_13;\n\tif (t > 30) {\n\t\tK_43 = K_13 = exp(-t) * sqrt(0.5*pi/t);\n\t} else if (t < 0.01*sqrt(2)) {\n\t\tK_13 = 0.5*gsl_sf_gamma(1.0/3.0) * pow(2.0/t,1.0/3.0);\n\t\tK_43 = 0.5*gsl_sf_gamma(4.0/3.0) * pow(2.0/t,4.0/3.0);\n\t} else {\n\t\tK_43 = gsl_sf_bessel_Knu(4.0/3.0,t);\n\t\tK_13 = gsl_sf_bessel_Knu(1.0/3.0,t);\n\t}\n\treturn 8.0*sqrt(3.0)/15 *pi*pi*electronCharge / magf * t / pow(g,5.0) * (K_43*K_43-K_13*K_13);\n}\n\ndouble tau_Sy(double deltaR, double nu, double gammaC, double gammaMin, double Npl, double pJet, double magf)\n{\n\treturn deltaR * RungeKuttaSimple(gammaMin,1.0e10,[&nu,&gammaC,&gammaMin,&Npl,&pJet,&magf]\n\t\t\t\t\t\t(double g) {return sigma_Sy(g,nu,magf)*n_pl(g,gammaC,gammaMin,Npl,pJet);});\n}\n\nvoid jetProcesses(State& st, const string& filename)\n{\n\tdouble accRateFraction = GlobalConfig.get<double>(\"nonThermal.jet.accRateFraction\");\n\tdouble accRate = accRateFraction*accRateADAF(schwRadius);\n\tdouble openingAngle = GlobalConfig.get<double>(\"nonThermal.jet.openingAngle\");\n\tdouble bulkLorentzFactor = GlobalConfig.get<double>(\"nonThermal.jet.lorentzFactor\");\n\tdouble inclinationAngle = GlobalConfig.get<double>(\"nonThermal.jet.inclination\")*(pi/180.0);\n\tdouble nt_electronFraction = GlobalConfig.get<double>(\"nonThermal.jet.etaInj\");\n\tdouble eB = GlobalConfig.get<double>(\"nonThermal.jet.magneticEnergyFraction\");\n\tdouble eElectrons = GlobalConfig.get<double>(\"nonThermal.jet.electronEnergyFraction\");\n\tdouble pJet = GlobalConfig.get<double>(\"nonThermal.jet.pIndex\");\n\tdouble zMin = GlobalConfig.get<double>(\"nonThermal.jet.zMin\");\n\t\n\tdouble z0 = P2(bulkLorentzFactor)*schwRadius*zMin;\n\tdouble zMax = z0*1.0e4;\n\tsize_t nZ = 100;\n\t\n\tdouble gamma2 = sqrt(0.5*(P2(bulkLorentzFactor)+1.0));\n\tdouble betaJet = sqrt(1.0-1.0/P2(bulkLorentzFactor));\n\tdouble vJet = betaJet*cLight;\n\tdouble n1 = accRate/(pi*z0*z0*openingAngle*openingAngle*vJet)/protonMass;\n\tdouble n2 = (4.0*gamma2+3.0)*n1;\n\tdouble Ti = 6.3e11;\n\tdouble Te = 1.0e9;\n\t\n\tdouble pasoZ = pow(zMax/z0,1.0/nZ);\n\tdouble z = z0;\n\tsize_t jZ = 0;\n\tMatrix lumBeamed;\n\tmatrixInit(lumBeamed,nE,nZ,0.0);\n\twhile (z < zMax) {\n\t\tz *= pasoZ;\n\t\t\n\t\tdouble dz = z*(pasoZ-1.0);\n\t\tdouble area = pi*P2(openingAngle*z);\n\t\tdouble vol = area*dz;\n\t\tdouble dens = n2 * P2(z0/z);\n\t\tdouble magf = sqrt(8.0*pi*eB*(gamma2-1.0)*dens*protonMass*cLight2);\n\t\t\n\t\t// NONTHERMAL POPULATION\n\t\tdouble gammaMin = max((gamma2-1.0)*(pJet-2.0)/(pJet-1.0) * (protonMass/electronMass) * \n\t\t\t\t\t\t\t\t(eElectrons/nt_electronFraction),1.0);\n\t\tgammaMin = 2.0;\n\t\tdouble tDyn = z/cLight;\n\t\tdouble Npl = nt_electronFraction*dens*pow(gammaMin,pJet-1.0);\n\t\tdouble gammaC = 6*pi*electronRestEnergy/(magf*magf*thomson*z);\n\t\t\n\t\tsize_t jE = 0;\n\t\tst.photon.ps.iterate([&](const SpaceIterator& i) {\n\t\t\tdouble nu = i.val(DIM_E)/planck;\n\t\t\tdouble beta = sqrt(1.0-1.0/P2(bulkLorentzFactor));\n\t\t\tdouble doppler = 1.0/(bulkLorentzFactor*(1.0-beta*cos(inclinationAngle)));\n\t\t\tdouble nuDoppler = nu/doppler;\n\t\t\t\n\t\t\tdouble lumLocal = 0.0;\n\t\t\tdouble gamma1 = 2.0;\n\t\t\tdouble gammaMax = 1.0e7;\n\t\t\tsize_t nnE = 1000;\n\t\t\tdouble pasoG = pow(gammaMax/gamma1,1.0/nnE);\n\t\t\tdouble gamma = gamma1;\n\t\t\tfor (size_t jjE=0;jjE<nnE;jjE++) {\n\t\t\t\tdouble dgamma = gamma*(pasoG-1.0);\n\t\t\t\t//if (jE==0)\n\t\t\t\t//\tcout << z/schwRadius << \"\\t\" << gamma << \"\\t\" << n_pl(gamma,gammaC,gammaMin,Npl,pJet)*dgamma << endl;\n\t\t\t\tlumLocal += dgamma*n_pl(gamma,gammaC,gammaMin,Npl,pJet)*jSyJet2(gamma,nuDoppler,magf);\n\t\t\t\t//lumLocal += dgamma*n_pl_2(gamma,Npl,pJet)*jSyJet2(gamma,nuDoppler,magf);\n\t\t\t\tgamma *= pasoG;\n\t\t\t}\n\t\t\tlumLocal *= vol;\n\t\t\t\n\t\t\t//double lumLocal = vol*RungeKuttaSimple(gammaC,gammaC*1.0e5,[&gammaC,&gammaMin,&Npl,\n\t\t\t//\t\t\t\t\t&pJet,&magf,&nuDoppler](double g){return n_pl(g,gammaC,gammaMin,Npl,pJet)*\n\t\t\t//\t\t\t\t\tjSyJet2(g,nuDoppler,magf);});\n\t\t\t\n\t\t\tdouble a_th = jSync(planck*nu,Te,magf,dens)/bb(nu,Te);\n\t\t\tdouble a_pl = RungeKuttaSimple(gammaMin,gammaMin*1.0e10,[&](double g)\n\t\t\t\t\t\t{return n_pl(g,gammaC,gammaMin,Npl,pJet)*sigma_Sy(g,nu,magf);});\n\t\t\tdouble tau = z*openingAngle*(a_pl+a_th);\n\t\t\t//tau = tau_Sy(z*openingAngle,nu,gammaC,gammaMin,Npl,pJet,magf);\n\t\t\tlumLocal *= (tau > 1.0e-10 ? (1.0-exp(-tau))/tau : 1.0);\n\t\t\tlumBeamed[jE][jZ] = lumLocal * doppler*doppler*doppler;\n\t\t\tjE++;\n\t\t},{-1,0,0});\n\t\tjZ++;\n\t}\n\t\n\tofstream file;\n\tfile.open(filename.c_str(),ios::out);\n\tsize_t jE = 0.0;\n\tst.photon.ps.iterate([&](const SpaceIterator& i) {\n\t\tdouble nu = i.val(DIM_E)/planck;\n\t\tdouble lum = 0.0;\n\t\tfor (size_t jZ=0;jZ<nZ;jZ++) {\n\t\t\tlum += lumBeamed[jE][jZ];\n\t\t}\n\t\tfile << nu << \"\\t\" << nu*lum << endl;\n\t\tjE++;\n\t},{-1,0,0});\n\tfile.close();\n}\n\n\nvoid jetProcesses2(State& st, const string& filename)\n{\n\tdouble accRateFraction = GlobalConfig.get<double>(\"nonThermal.jet.accRateFraction\");\n\tdouble accRate = accRateFraction*accRateADAF(schwRadius);\n\tdouble openingAngle = GlobalConfig.get<double>(\"nonThermal.jet.openingAngle\");\n\tdouble bulkLorentzFactor = GlobalConfig.get<double>(\"nonThermal.jet.lorentzFactor\");\n\tdouble inclinationAngle = GlobalConfig.get<double>(\"nonThermal.jet.inclination\")*(pi/180.0);\n\tdouble nt_electronFraction = GlobalConfig.get<double>(\"nonThermal.jet.etaInj\");\n\tdouble pJet = GlobalConfig.get<double>(\"nonThermal.jet.pIndex\");\n\tdouble mB = 1.5;\n\tsize_t nZ = 100;\n\t\n\tdouble z0 = 50*schwRadius;\n\tdouble r0 = openingAngle*z0;\n\tdouble betaJet = sqrt(1.0-1.0/P2(bulkLorentzFactor));\n\tdouble vJet = betaJet*cLight;\n\tdouble B0 = sqrt(accRate*cLight2*8/(r0*r0*vJet));\n\tdouble n0 = accRate/(bulkLorentzFactor*pi*r0*r0*vJet*protonMass);\n\tdouble zMax = z0*1.0e5;\n\t\n\tdouble pasoZ = pow(zMax/z0,1.0/nZ);\n\tdouble z = z0;\n\tsize_t jZ = 0;\n\tMatrix lumBeamed;\n\tmatrixInit(lumBeamed,nE,nZ,0.0);\n\twhile (z < zMax) {\n\t\tz *= pasoZ;\n\t\tdouble dz = z*(pasoZ-1.0);\n\t\tdouble area = pi*P2(openingAngle*z);\n\t\tdouble vol = area*dz;\n\t\tdouble dens = n0 * P2(z0/z);\n\t\tdouble magf = B0 * pow(z0/z,mB);\n\t\t\n\t\t// NONTHERMAL POPULATION\n\t\tdouble gammaMin = 2.0;\n\t\tdouble Npl = nt_electronFraction*dens*pow(gammaMin,pJet-1.0);\n\t\tdouble gammaC = 6*pi*electronRestEnergy/(magf*magf*thomson*z);\n\t\t\n\t\tsize_t jE = 0;\n\t\tst.photon.ps.iterate([&](const SpaceIterator& i) {\n\t\t\tdouble nu = i.val(DIM_E)/planck;\n\t\t\tdouble beta = sqrt(1.0-1.0/P2(bulkLorentzFactor));\n\t\t\tdouble doppler = 1.0/(bulkLorentzFactor*(1.0-beta*cos(inclinationAngle)));\n\t\t\tdouble nuDoppler = nu/doppler;\n\t\t\tdouble lumLocal = vol*RungeKuttaSimple(gammaMin,gammaMin*1.0e10,[&gammaC,&gammaMin,&Npl,\n\t\t\t\t\t\t\t\t\t&pJet,&magf,&nuDoppler](double g){return n_pl(g,gammaC,gammaMin,Npl,pJet)*\n\t\t\t\t\t\t\t\t\t\tjSyJet2(g,nuDoppler,magf);});\n\t\t\tdouble a_pl = RungeKuttaSimple(gammaMin,gammaMin*1.0e10,[&](double g)\n\t\t\t\t\t\t\t{return n_pl(g,gammaC,gammaMin,Npl,pJet)*sigma_Sy(g,nu,magf);});\n\t\t\tdouble tau = z*openingAngle*a_pl;\n\t\t\t//tau = tau_Sy(z*openingAngle,nu,gammaC,gammaMin,Npl,pJet,magf);\n\t\t\tlumLocal *= (tau > 1.0e-10 ? (1.0-exp(-tau))/tau : 1.0);\n\t\t\tlumBeamed[jE][jZ] = lumLocal * doppler*doppler*doppler;\n\t\t\tjE++;\n\t\t},{-1,0,0});\n\t\tjZ++;\n\t}\n\t\n\tofstream file;\n\tfile.open(filename.c_str(),ios::out);\n\tsize_t jE = 0.0;\n\tst.photon.ps.iterate([&](const SpaceIterator& i) {\n\t\tdouble nu = i.val(DIM_E)/planck;\n\t\tdouble lum = 0.0;\n\t\tfor (size_t jZ=0;jZ<nZ;jZ++) {\n\t\t\tlum += lumBeamed[jE][jZ];\n\t\t}\n\t\tfile << nu << \"\\t\" << nu*lum << endl;\n\t\tjE++;\n\t},{-1,0,0});\n\tfile.close();\n}", "meta": {"hexsha": "c86a0b2cb6ab2470fa0cb7915ceacb1bbde6172d", "size": 9415, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/adaf/jetEmission.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/jetEmission.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/jetEmission.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": 34.1123188406, "max_line_length": 109, "alphanum_fraction": 0.6737121614, "num_tokens": 3501, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024554, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4841243939858894}}
{"text": "\n#ifndef ___COLORSPACEADJUSTMENT_H___ \n#define ___COLORSPACEADJUSTMENT_H___ \n#include <iostream>\n#include <math.h>\n//Eigen Library\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n//OpenCV Library\n#include <stdio.h>\n#include <cstdlib>\n// #include <opencv/cv.h>\n// #include <opencv/highgui.h>\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n\n/**\n * @brief Class that contains the functions to fully create the color space \"oRGB\"\n * \n */\nclass ConvertTooRGB {\n public:\n  ConvertTooRGB(void) = default;\n\n/**\n * @brief Function that normalizes the values\n *  \n */\nbool setNormalizeImage(cv::Mat img1);\n\n/**\n * @brief function that returns a vector after it has been multiplied with a specific matrix given because of the formula\n * \n * @param img \n * @return cv::Mat \n */\nbool setLinearImage();\n\n/**\n * @brief contains a matrix of rotation, that we will use to rotate a vector in the next function\n * \n * @param angle \n * @return Eigen::Matrix3d \n */\n    Eigen::Matrix3d rotatePoint(double angle);\n\n\n/**\n * @brief based on the angle taken from the vector of the loaded image, it rotates that vector using the previous rotatePoint function\n * \n * @param img \n * @return cv::Mat \n */\nbool fullRotation();\n\n/**\n * @brief It changes the values of ths second and third vector of the image\n * \n * @param cb \n * @param crg \n * @param img \n * @return cv::Mat \n */\n\n\n//cv::Mat filter(double cb, double crg, cv::Mat img);\n\n\n\n\n/**\n * @brief Set the Filter values- it changes the value of the vectors Cyb and Crg\n * \n * @param img \n * @param cyb \n * @param crg \n * @return cv::Mat \n */\ncv::Mat setFilter(cv::Mat img,double cyb, double crg);\n\n\n/**\n * @brief Returns the matrix value from the private variable 'normalizedImage', which has been previously set by SetNormalizedImage function. \n * \n * @return cv::Mat \n */\ncv::Mat getnormalizedImage();\n\n/**\n * @brief Returns the matrix value from the private variable 'linearImage', which has been previously set by setLinearImage function. \n * \n * @return cv::Mat \n */\ncv::Mat getLinearImage();\n\n/**\n * @brief Returns the matrix value from the private variable 'rotatedImage', which has been previously set by fullRotation() function.\n * \n * @return cv::Mat \n */\ncv::Mat getRotatedImage();\n\nenum  channel {L, Cyb, Crg};\n\n/**\n * @brief Function to separate channels of the image\n * \n * @param img \n * @param c \n * @return cv::Mat \n */\ncv::Mat channelExtraction( cv::Mat img1, channel c); \n\nprivate:\ncv::Mat normalizedImage;\ncv::Mat linearImage;\ncv::Mat rotatedImage;\n};\n\n#endif\n", "meta": {"hexsha": "2c4fba048b6486da3f7659f5705f7b332ca277df", "size": 2571, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "0rgb/example_2/include/colorspaceadjustment.hpp", "max_stars_repo_name": "Enkelena/oRGB", "max_stars_repo_head_hexsha": "c7e250f0a28b8db073d60c05f693ad15489e271e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "0rgb/example_2/include/colorspaceadjustment.hpp", "max_issues_repo_name": "Enkelena/oRGB", "max_issues_repo_head_hexsha": "c7e250f0a28b8db073d60c05f693ad15489e271e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "0rgb/example_2/include/colorspaceadjustment.hpp", "max_forks_repo_name": "Enkelena/oRGB", "max_forks_repo_head_hexsha": "c7e250f0a28b8db073d60c05f693ad15489e271e", "max_forks_repo_licenses": ["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.0737704918, "max_line_length": 142, "alphanum_fraction": 0.6927265655, "num_tokens": 658, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.867035752930664, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.4840894659150859}}
{"text": "\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n\n#include <ros/ros.h>\n\n\nint main(int argc,char **argv)\n{\n\n    ros::init(argc, argv, \"test\");\n\n    ros::NodeHandle n;\n\n\n\n    Eigen::MatrixXd MatAdf;\n    Eigen::MatrixXd MatBdf;\n    Eigen::MatrixXd MatCdf;\n\n    MatAdf.resize(100,100);\n    MatAdf.setRandom();\n\n    MatBdf.resize(100,100);\n    MatBdf.setRandom();\n\n\n    Eigen::SparseMatrix<double> MatAsf;\n    Eigen::SparseMatrix<double> MatBsf;\n    Eigen::SparseMatrix<double> MatCsf;\n\n    MatAsf.resize(100,100);\n    MatAsf.reserve(100*100);\n\n    MatBsf.resize(100,100);\n    MatBsf.reserve(100*100);\n\n    {\n    std::vector<Eigen::Triplet<double>> tripletList;\n    tripletList.reserve(100*100);\n    for(int i=0;i<100;i++)\n    {\n      for(int j=0;j<100;j++)\n        tripletList.push_back(Eigen::Triplet<double>(i,j,i+j));\n    }\n    MatAsf.setFromTriplets(tripletList.begin(), tripletList.end());\n    MatBsf.setFromTriplets(tripletList.begin(), tripletList.end());\n    }\n\n\n\n\n    Eigen::MatrixXd MatAde;\n    Eigen::MatrixXd MatBde;\n    Eigen::MatrixXd MatCde;\n\n    MatAde.resize(100,100);\n    MatAde=Eigen::MatrixXd::Identity(100,100);\n\n    MatBde.resize(100,100);\n    MatBde=Eigen::MatrixXd::Identity(100,100);\n\n\n    Eigen::SparseMatrix<double> MatAse;\n    Eigen::SparseMatrix<double> MatBse;\n    Eigen::SparseMatrix<double> MatCse;\n\n    MatAse.resize(100,100);\n    MatAse.reserve(100);\n\n    MatBse.resize(100,100);\n    MatBse.reserve(100);\n\n    {\n    std::vector<Eigen::Triplet<double>> tripletList;\n    tripletList.reserve(100);\n    for(int i=0;i<100;i++)\n    {\n      for(int j=0;j<100;j++)\n          if(i==j)\n        tripletList.push_back(Eigen::Triplet<double>(i,j,1));\n    }\n    MatAse.setFromTriplets(tripletList.begin(), tripletList.end());\n    MatBse.setFromTriplets(tripletList.begin(), tripletList.end());\n    }\n\n\n\n\n    {\n        std::cout<<\"Test 01: df x df\"<<std::endl;\n        ros::Time time_before=ros::Time::now();\n        for(int i=0; i<100; i++)\n        {\n\n            MatCdf=MatAdf*MatBdf;\n        }\n        ros::Time time_after=ros::Time::now();\n\n        std::cout<<\"\\t delta time=\"<<(time_after-time_before)<<\" ns\"<<std::endl;\n    }\n\n    {\n        std::cout<<\"Test 02: sf x sf\"<<std::endl;\n        ros::Time time_before=ros::Time::now();\n        for(int i=0; i<100; i++)\n        {\n\n            MatCsf=MatAsf*MatBsf;\n        }\n        ros::Time time_after=ros::Time::now();\n\n        std::cout<<\"\\t delta time=\"<<(time_after-time_before)<<\" ns\"<<std::endl;\n    }\n\n    {\n        std::cout<<\"Test 03: sf x df\"<<std::endl;\n        ros::Time time_before=ros::Time::now();\n        for(int i=0; i<100; i++)\n        {\n\n            MatCdf=MatAsf*MatBdf;\n        }\n        ros::Time time_after=ros::Time::now();\n\n        std::cout<<\"\\t delta time=\"<<(time_after-time_before)<<\" ns\"<<std::endl;\n    }\n\n    {\n        std::cout<<\"Test 04: df x sf\"<<std::endl;\n        ros::Time time_before=ros::Time::now();\n        for(int i=0; i<100; i++)\n        {\n\n            MatCdf=MatAdf*MatBsf;\n        }\n        ros::Time time_after=ros::Time::now();\n\n        std::cout<<\"\\t delta time=\"<<(time_after-time_before)<<\" ns\"<<std::endl;\n    }\n\n\n    {\n        std::cout<<\"Test 05: de x de\"<<std::endl;\n        ros::Time time_before=ros::Time::now();\n        for(int i=0; i<100; i++)\n        {\n\n            MatCde=MatAde*MatBde;\n        }\n        ros::Time time_after=ros::Time::now();\n\n        std::cout<<\"\\t delta time=\"<<(time_after-time_before)<<\" ns\"<<std::endl;\n    }\n\n    {\n        std::cout<<\"Test 06: se x se\"<<std::endl;\n        ros::Time time_before=ros::Time::now();\n        for(int i=0; i<100; i++)\n        {\n\n            MatCse=MatAse*MatBse;\n        }\n        ros::Time time_after=ros::Time::now();\n\n        std::cout<<\"\\t delta time=\"<<(time_after-time_before)<<\" ns\"<<std::endl;\n    }\n\n    {\n        std::cout<<\"Test 07: se x de\"<<std::endl;\n        ros::Time time_before=ros::Time::now();\n        for(int i=0; i<100; i++)\n        {\n\n            MatCde=MatAse*MatBde;\n        }\n        ros::Time time_after=ros::Time::now();\n\n        std::cout<<\"\\t delta time=\"<<(time_after-time_before)<<\" ns\"<<std::endl;\n    }\n\n    {\n        std::cout<<\"Test 08: de x se\"<<std::endl;\n        ros::Time time_before=ros::Time::now();\n        for(int i=0; i<100; i++)\n        {\n\n            MatCde=MatAde*MatBse;\n        }\n        ros::Time time_after=ros::Time::now();\n\n        std::cout<<\"\\t delta time=\"<<(time_after-time_before)<<\" ns\"<<std::endl;\n    }\n\n\n\n\n    {\n        std::cout<<\"Test 09: df x de\"<<std::endl;\n        ros::Time time_before=ros::Time::now();\n        for(int i=0; i<100; i++)\n        {\n\n            MatCdf=MatAdf*MatBde;\n        }\n        ros::Time time_after=ros::Time::now();\n\n        std::cout<<\"\\t delta time=\"<<(time_after-time_before)<<\" ns\"<<std::endl;\n    }\n\n    {\n        std::cout<<\"Test 10: sf x se\"<<std::endl;\n        ros::Time time_before=ros::Time::now();\n        for(int i=0; i<100; i++)\n        {\n\n            MatCsf=MatAsf*MatBse;\n        }\n        ros::Time time_after=ros::Time::now();\n\n        std::cout<<\"\\t delta time=\"<<(time_after-time_before)<<\" ns\"<<std::endl;\n    }\n\n    {\n        std::cout<<\"Test 11: sf x de\"<<std::endl;\n        ros::Time time_before=ros::Time::now();\n        for(int i=0; i<100; i++)\n        {\n\n            MatCdf=MatAsf*MatBde;\n        }\n        ros::Time time_after=ros::Time::now();\n\n        std::cout<<\"\\t delta time=\"<<(time_after-time_before)<<\" ns\"<<std::endl;\n    }\n\n    {\n        std::cout<<\"Test 12: df x se\"<<std::endl;\n        ros::Time time_before=ros::Time::now();\n        for(int i=0; i<100; i++)\n        {\n\n            MatCdf=MatAdf*MatBse;\n        }\n        ros::Time time_after=ros::Time::now();\n\n        std::cout<<\"\\t delta time=\"<<(time_after-time_before)<<\" ns\"<<std::endl;\n    }\n\n\n\n\n\n\n    {\n        std::cout<<\"Test 13: de x df\"<<std::endl;\n        ros::Time time_before=ros::Time::now();\n        for(int i=0; i<100; i++)\n        {\n\n            MatCdf=MatAde*MatBdf;\n        }\n        ros::Time time_after=ros::Time::now();\n\n        std::cout<<\"\\t delta time=\"<<(time_after-time_before)<<\" ns\"<<std::endl;\n    }\n\n    {\n        std::cout<<\"Test 14: se x sf\"<<std::endl;\n        ros::Time time_before=ros::Time::now();\n        for(int i=0; i<100; i++)\n        {\n\n            MatCsf=MatAse*MatBsf;\n        }\n        ros::Time time_after=ros::Time::now();\n\n        std::cout<<\"\\t delta time=\"<<(time_after-time_before)<<\" ns\"<<std::endl;\n    }\n\n    {\n        std::cout<<\"Test 15: se x df\"<<std::endl;\n        ros::Time time_before=ros::Time::now();\n        for(int i=0; i<100; i++)\n        {\n\n            MatCdf=MatAse*MatBdf;\n        }\n        ros::Time time_after=ros::Time::now();\n\n        std::cout<<\"\\t delta time=\"<<(time_after-time_before)<<\" ns\"<<std::endl;\n    }\n\n    {\n        std::cout<<\"Test 16: de x sf\"<<std::endl;\n        ros::Time time_before=ros::Time::now();\n        for(int i=0; i<100; i++)\n        {\n\n            MatCdf=MatAde*MatBsf;\n        }\n        ros::Time time_after=ros::Time::now();\n\n        std::cout<<\"\\t delta time=\"<<(time_after-time_before)<<\" ns\"<<std::endl;\n    }\n\n\n\n\n    {\n        std::cout<<\"Test 17: se x sf x se\"<<std::endl;\n        ros::Time time_before=ros::Time::now();\n        for(int i=0; i<100; i++)\n        {\n            MatCsf=MatAse*MatBsf*MatAse;\n        }\n        ros::Time time_after=ros::Time::now();\n\n        std::cout<<\"\\t delta time=\"<<(time_after-time_before)<<\" ns\"<<std::endl;\n    }\n\n    {\n        std::cout<<\"Test 18: de x df x de\"<<std::endl;\n        ros::Time time_before=ros::Time::now();\n        for(int i=0; i<100; i++)\n        {\n\n            MatCdf=MatAde*MatBdf*MatAde;\n        }\n        ros::Time time_after=ros::Time::now();\n\n        std::cout<<\"\\t delta time=\"<<(time_after-time_before)<<\" ns\"<<std::endl;\n    }\n\n    {\n        std::cout<<\"Test 19: se x df x se\"<<std::endl;\n        ros::Time time_before=ros::Time::now();\n        for(int i=0; i<100; i++)\n        {\n\n            MatCdf=MatAse*MatBdf*MatAse;\n        }\n        ros::Time time_after=ros::Time::now();\n\n        std::cout<<\"\\t delta time=\"<<(time_after-time_before)<<\" ns\"<<std::endl;\n    }\n\n    {\n        std::cout<<\"Test 20: de x sf x de\"<<std::endl;\n        ros::Time time_before=ros::Time::now();\n        for(int i=0; i<100; i++)\n        {\n\n            MatCdf=MatAde*MatBsf*MatAde;\n        }\n        ros::Time time_after=ros::Time::now();\n\n        std::cout<<\"\\t delta time=\"<<(time_after-time_before)<<\" ns\"<<std::endl;\n    }\n\n\n    return 0;\n}\n", "meta": {"hexsha": "6d0d7f667c61852e3c2e7debdde822535f2cb37e", "size": 8455, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "msf_localization_ros/src/source/test.cpp", "max_stars_repo_name": "Ahrovan/msf_localization", "max_stars_repo_head_hexsha": "a78ba2473115234910789617e9b45262ebf1d13d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-27T15:23:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-27T15:23:13.000Z", "max_issues_repo_path": "msf_localization_ros/src/source/test.cpp", "max_issues_repo_name": "Ahrovan/msf_localization", "max_issues_repo_head_hexsha": "a78ba2473115234910789617e9b45262ebf1d13d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "msf_localization_ros/src/source/test.cpp", "max_forks_repo_name": "Ahrovan/msf_localization", "max_forks_repo_head_hexsha": "a78ba2473115234910789617e9b45262ebf1d13d", "max_forks_repo_licenses": ["BSD-3-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.228021978, "max_line_length": 80, "alphanum_fraction": 0.5167356594, "num_tokens": 2547, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505248181417, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.48407707428642704}}
{"text": "\n// BLAS level 3\n// hermitian matrices, her2k \n\n#include <stddef.h>\n#include <iostream>\n#include <complex>\n#include <boost/numeric/bindings/atlas/cblas3.hpp>\n#include <boost/numeric/bindings/traits/ublas_hermitian.hpp>\n#include \"utils.h\"\n\nnamespace ublas = boost::numeric::ublas;\nnamespace atlas = boost::numeric::bindings::atlas;\nnamespace traits = boost::numeric::bindings::traits;\n\nusing std::cout;\nusing std::cin;\nusing std::endl; \n\ntypedef float real_t; \ntypedef std::complex<real_t> cmplx_t; \n\ntypedef ublas::matrix<cmplx_t, ublas::column_major> ccm_t;\ntypedef ublas::matrix<cmplx_t, ublas::row_major> crm_t;\ntypedef ublas::hermitian_adaptor<ccm_t, ublas::upper> cucha_t; \ntypedef ublas::hermitian_adaptor<ccm_t, ublas::lower> clcha_t; \ntypedef ublas::hermitian_adaptor<crm_t, ublas::upper> curha_t; \ntypedef ublas::hermitian_adaptor<crm_t, ublas::lower> clrha_t; \n\nint main() {\n\n  // complex \n\n  const int n1 = 3;\n  const int k1 = 2; \n\n  ccm_t cac (n1, k1); \n  crm_t car (n1, k1); \n  cac(0,0) = car(0,0) = cmplx_t (1., 1.);\n  cac(1,0) = car(1,0) = cmplx_t (2., 1.);\n  cac(2,0) = car(2,0) = cmplx_t (3., 1.);\n  cac(0,1) = car(0,1) = cmplx_t (1., 1.);\n  cac(1,1) = car(1,1) = cmplx_t (2., 1.);\n  cac(2,1) = car(2,1) = cmplx_t (3., 1.);\n  print_m (cac, \"cac\"); \n  cout << endl; \n  print_m (car, \"car\"); \n  cout << endl << endl;\n\n  ccm_t cbc (n1, k1); \n  crm_t cbr (n1, k1); \n  cbc(0,0) = cbr(0,0) = cmplx_t (0., -1.);\n  cbc(1,0) = cbr(1,0) = cmplx_t (0., -1.);\n  cbc(2,0) = cbr(2,0) = cmplx_t (0., -1.);\n  cbc(0,1) = cbr(0,1) = cmplx_t (0., -1.);\n  cbc(1,1) = cbr(1,1) = cmplx_t (0., -1.);\n  cbc(2,1) = cbr(2,1) = cmplx_t (0., -1.);\n  print_m (cbc, \"cbc\"); \n  cout << endl; \n  print_m (cbr, \"cbr\"); \n  cout << endl << endl;\n\n  ccm_t ccmu (n1, n1); \n  ccm_t ccml (n1, n1); \n  crm_t crmu (n1, n1); \n  crm_t crml (n1, n1); \n  cucha_t cucha (ccmu); \n  clcha_t clcha (ccml); \n  curha_t curha (crmu); \n  clrha_t clrha (crml); \n\n  atlas::her2k (CblasNoTrans, cac, cbc, cucha); \n  atlas::her2k (CblasNoTrans, cmplx_t(1,0), cac, cbc, 0., clcha); \n  atlas::her2k (CblasNoTrans, cmplx_t(1,0), car, cbr, 0., curha); \n  atlas::her2k (CblasNoTrans, car, cbr, clrha); \n\n  print_m (cucha, \"cucha\");\n  cout << endl; \n  print_m (clcha, \"clcha\");\n  cout << endl; \n  print_m (curha, \"curha\");\n  cout << endl; \n  print_m (clrha, \"clrha\");\n  cout << endl << endl; \n\n  // part 2\n\n  ccm_t cact (ublas::herm (cac)); \n  crm_t cart (ublas::herm (car)); \n  print_m (cact, \"cact\"); \n  cout << endl; \n  print_m (cart, \"cart\"); \n  cout << endl << endl;\n\n  ccm_t cbct (ublas::herm (cbc)); \n  crm_t cbrt (ublas::herm (cbr)); \n  print_m (cbct, \"cbct\"); \n  cout << endl; \n  print_m (cbrt, \"cbrt\"); \n  cout << endl << endl;\n\n  init_m (ccmu, const_val<cmplx_t> (cmplx_t (0, 0)));\n  init_m (ccml, const_val<cmplx_t> (cmplx_t (0, 0)));\n  init_m (crmu, const_val<cmplx_t> (cmplx_t (0, 0)));\n  init_m (crml, const_val<cmplx_t> (cmplx_t (0, 0)));\n\n  atlas::her2k (CblasUpper, CblasConjTrans, 1.0, cact, cbct, 0.0, ccmu); \n  atlas::her2k (CblasLower, CblasConjTrans, 1.0, cact, cbct, 0.0, ccml); \n  atlas::her2k (CblasUpper, CblasConjTrans, 1.0, cart, cbrt, 0.0, crmu); \n  atlas::her2k (CblasLower, CblasConjTrans, 1.0, cart, cbrt, 0.0, crml); \n\n  print_m (ccmu, \"ccmu\");\n  cout << endl; \n  print_m (ccml, \"ccml\");\n  cout << endl; \n  print_m (crmu, \"crmu\");\n  cout << endl; \n  print_m (crml, \"crml\");\n  cout << endl; \n}\n\n", "meta": {"hexsha": "ff8f70fb8be42171d04ff1b10849606109229b98", "size": 3382, "ext": "cc", "lang": "C++", "max_stars_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/atlas/ublas_herm3h2k.cc", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-14T19:18:21.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-14T19:18:21.000Z", "max_issues_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/atlas/ublas_herm3h2k.cc", "max_issues_repo_name": "diku-dk/PROX", "max_issues_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/atlas/ublas_herm3h2k.cc", "max_forks_repo_name": "diku-dk/PROX", "max_forks_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-23T09:56:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-23T09:56:06.000Z", "avg_line_length": 27.7213114754, "max_line_length": 73, "alphanum_fraction": 0.6108811354, "num_tokens": 1456, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743168019989179, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.4840661050841912}}
{"text": "#define BOOST_TEST_MODULE RandomNumbers\n#include <boost/test/unit_test.hpp>\n#include <vexcl/vector.hpp>\n#include <vexcl/element_index.hpp>\n#include <vexcl/random.hpp>\n#include <vexcl/reductor.hpp>\n#include <vexcl/tagged_terminal.hpp>\n#include <vexcl/temporary.hpp>\n#include <vexcl/function.hpp>\n#include <boost/math/constants/constants.hpp>\n#include \"context_setup.hpp\"\n\nBOOST_AUTO_TEST_CASE(random_numbers)\n{\n    const size_t N = 1 << 20;\n\n    vex::Reductor<size_t, vex::SUM> sumi(ctx);\n    vex::Reductor<double, vex::SUM> sumd(ctx);\n\n    vex::Random<cl_int> rand0;\n    vex::vector<cl_uint> x0(ctx, N);\n    x0 = rand0(vex::element_index(), std::rand());\n\n    vex::Random<cl_float4> rand1;\n    vex::vector<cl_float4> x1(ctx, N);\n    x1 = rand1(vex::element_index(), std::rand());\n\n    vex::Random<cl_double4> rand2;\n    vex::vector<cl_double4> x2(ctx, N);\n    x2 = rand2(vex::element_index(), std::rand());\n\n    vex::Random<cl_double> rand3;\n    vex::vector<cl_double> x3(ctx, N);\n    x3 = rand3(vex::element_index(), std::rand());\n\n    // X in [0,1]\n    BOOST_CHECK(sumi(x3 > 1) == 0);\n    BOOST_CHECK(sumi(x3 < 0) == 0);\n\n    // mean = 0.5\n    BOOST_CHECK(std::abs((sumd(x3) / N) - 0.5) < 1e-2);\n\n    vex::RandomNormal<cl_double> rand4;\n    vex::vector<cl_double> x4(ctx, N);\n    x4 = rand4(vex::element_index(), std::rand());\n\n    // E(X ~ N(0,s)) = 0\n    BOOST_CHECK(std::abs(sumd(x4)/N) < 1e-2);\n\n    // E(abs(X) ~ N(0,s)) = sqrt(2/M_PI) * s\n    BOOST_CHECK(std::abs(sumd(fabs(x4))/N - std::sqrt(2 / boost::math::constants::pi<double>())) < 1e-2);\n\n    vex::Random<cl_double, vex::random::threefry> rand5;\n    vex::vector<cl_double> x5(ctx, N);\n    x5 = rand5(vex::element_index(), std::rand());\n\n    BOOST_CHECK(std::abs(sumd(x5)/N - 0.5) < 1e-2);\n}\n\nBOOST_AUTO_TEST_CASE(monte_carlo_pi)\n{\n    vex::Random<double, vex::random::threefry> rnd;\n\n    vex::Reductor<size_t, vex::SUM> sum(ctx);\n\n    const size_t n = 1 << 20;\n\n    auto i = vex::tag<0>(vex::element_index(0, n));\n\n    auto x = vex::make_temp<1>(rnd(i, std::rand()));\n    auto y = vex::make_temp<2>(rnd(i, std::rand()));\n\n    double pi = 4.0 * sum( (x * x + y * y) < 1 ) / n;\n\n    BOOST_CHECK_CLOSE(pi, boost::math::constants::pi<double>(), 0.5);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n", "meta": {"hexsha": "b59d7f385ffbaa3aa6916f7a0cbb6801ab539609", "size": 2244, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "external_libraries/vexcl/tests/random.cpp", "max_stars_repo_name": "lkusch/Kratos", "max_stars_repo_head_hexsha": "e8072d8e24ab6f312765185b19d439f01ab7b27b", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": 778.0, "max_stars_repo_stars_event_min_datetime": "2017-01-27T16:29:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T03:01:51.000Z", "max_issues_repo_path": "external_libraries/vexcl/tests/random.cpp", "max_issues_repo_name": "lkusch/Kratos", "max_issues_repo_head_hexsha": "e8072d8e24ab6f312765185b19d439f01ab7b27b", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": 6634.0, "max_issues_repo_issues_event_min_datetime": "2017-01-15T22:56:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:03:36.000Z", "max_forks_repo_path": "external_libraries/vexcl/tests/random.cpp", "max_forks_repo_name": "lkusch/Kratos", "max_forks_repo_head_hexsha": "e8072d8e24ab6f312765185b19d439f01ab7b27b", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": 224.0, "max_forks_repo_forks_event_min_datetime": "2017-02-07T14:12:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-06T23:09:34.000Z", "avg_line_length": 28.05, "max_line_length": 105, "alphanum_fraction": 0.623885918, "num_tokens": 760, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.4840660976739237}}
{"text": "#include \"linear_operator.hpp\"\n\n#include <Eigen/Dense>\n#include <array>\n#include <cmath>\n#include <set>\n#include <unordered_map>\n\n#include \"bases.hpp\"\n#include \"gmock/gmock.h\"\n#include \"gtest/gtest.h\"\n#include \"integration.hpp\"\n\nnamespace Time {\nusing ::testing::DoubleEq;\nusing ::testing::ElementsAre;\nusing ::testing::Not;\n\ntemplate <typename LinearOperator, typename BasisIn, typename BasisOut>\nvoid CheckMatrixTranspose(const SparseIndices<BasisIn> &indices_in,\n                          const SparseIndices<BasisOut> &indices_out) {\n  auto op = LinearOperator();\n  Eigen::MatrixXd A = op.ToMatrix(indices_in, indices_out);\n  Eigen::MatrixXd AT =\n      Eigen::MatrixXd::Zero(indices_in.size(), indices_out.size());\n  std::unordered_map<BasisIn *, int> indices_in_map;\n  std::unordered_map<BasisOut *, int> indices_out_map;\n\n  for (int i = 0; i < indices_in.size(); ++i) {\n    assert(!indices_in_map.count(indices_in[i]));\n    indices_in_map[indices_in[i]] = i;\n  }\n  for (int i = 0; i < indices_out.size(); ++i) {\n    assert(!indices_out_map.count(indices_out[i]));\n    indices_out_map[indices_out[i]] = i;\n  }\n\n  // Check A.\n  for (int i = 0; i < indices_in.size(); ++i) {\n    SparseVector<BasisIn> vec{{{indices_in[i], 1.0}}};\n    auto op_vec = op.MatVec(vec);\n    for (auto [fn, coeff] : op_vec) {\n      EXPECT_THAT(coeff, Not(DoubleEq(0)));\n    }\n    auto op_vec_check = op.MatVec(vec, indices_out);\n    for (auto [fn, coeff] : op_vec_check)\n      ASSERT_DOUBLE_EQ(coeff, A(indices_out_map[fn], i));\n  }\n\n  // Create AT.\n  for (int i = 0; i < indices_out.size(); ++i) {\n    SparseVector<BasisOut> vec{{{indices_out[i], 1.0}}};\n    auto op_vec = op.RMatVec(vec);\n    for (auto [fn, coeff] : op_vec) AT(indices_in_map[fn], i) = coeff;\n\n    auto op_vec_check = op.RMatVec(vec, indices_in);\n    for (auto [fn, coeff] : op_vec_check)\n      ASSERT_DOUBLE_EQ(coeff, AT(indices_in_map[fn], i));\n  }\n\n  // Check that they are the same.\n  ASSERT_TRUE(A.transpose().isApprox(AT));\n}\n\ntemplate <typename LinearOperator, typename BasisIn, typename BasisOut>\nvoid CheckMatrixQuadrature(const SparseIndices<BasisIn> &indices_in,\n                           bool deriv_in,\n                           const SparseIndices<BasisOut> &indices_out,\n                           bool deriv_out) {\n  auto mat = LinearOperator().ToMatrix(indices_in, indices_out);\n  for (int j = 0; j < indices_in.size(); ++j)\n    for (int i = 0; i < indices_out.size(); ++i) {\n      auto psi_j = indices_in[j];\n      auto phi_i = indices_out[i];\n\n      double ip = 0;\n      auto eval = [psi_j, deriv_in, phi_i, deriv_out](double t) {\n        return psi_j->Eval(t, deriv_in) * phi_i->Eval(t, deriv_out);\n      };\n      for (auto elem : phi_i->support())\n        ip += Integrate(eval, *elem, /*degree*/ 3);\n\n      ASSERT_NEAR(mat(i, j), ip, 1e-10);\n    }\n}\n\nTEST(ContLinearScaling, ProlongateEval) {\n  // Reset the persistent trees.\n  Bases B;\n\n  int ml = 62;\n  // Now we check what happens when we also refine near the end points.\n  B.three_point_tree.DeepRefine([ml](auto node) {\n    return node->is_metaroot() ||\n           (node->level() < ml &&\n            (node->index() == 0 ||\n             node->index() == (1LL << (node->level() - 1)) - 1));\n  });\n\n  auto Lambda = B.three_point_tree.NodesPerLevel();\n  auto Delta = B.cont_lin_tree.NodesPerLevel();\n\n  double n_t = 2048;\n  for (int l = 0; l < ml; ++l) {\n    for (int i = 0; i < Delta[l].size(); ++i) {\n      // Prolongate a single hat function.\n      SparseVector<ContLinearScalingFn> vec{{{Delta[l][i], 1.0}}};\n\n      auto p_vec = Prolongate<ContLinearScalingFn>()(vec);\n      // Check that the functions eval to the same thing.\n      for (int x = 0; x < n_t; x++) {\n        double t = x * 1.0 / n_t;\n        double eval = 0;\n        for (auto [phi, coeff] : p_vec) {\n          eval += phi->Eval(t) * coeff;\n        }\n        ASSERT_DOUBLE_EQ(Delta[l][i]->Eval(t), eval);\n      }\n    }\n  }\n}\n\nTEST(ContLinearScaling, CheckMatrixTransposes) {\n  // Reset the persistent trees.\n  Bases B;\n\n  int ml = 7;\n\n  B.three_point_tree.UniformRefine(ml);\n  auto Lambda = B.three_point_tree.NodesPerLevel();\n  auto Delta = B.cont_lin_tree.NodesPerLevel();\n\n  for (int l = 1; l < ml; ++l) {\n    CheckMatrixTranspose<Prolongate<ContLinearScalingFn>, ContLinearScalingFn,\n                         ContLinearScalingFn>({Delta[l - 1]}, {Delta[l]});\n    CheckMatrixTranspose<MassOperator<ContLinearScalingFn, ContLinearScalingFn>,\n                         ContLinearScalingFn, ContLinearScalingFn>(\n        {Delta[l - 1]}, {Delta[l - 1]});\n    CheckMatrixTranspose<\n        ZeroEvalOperator<ContLinearScalingFn, ContLinearScalingFn>,\n        ContLinearScalingFn, ContLinearScalingFn>({Delta[l - 1]},\n                                                  {Delta[l - 1]});\n  }\n}\n\nTEST(ContLinearScaling, MatrixQuadrature) {\n  // Reset the persistent trees.\n  Bases B;\n\n  int ml = 7;\n\n  B.three_point_tree.UniformRefine(ml);\n  auto Lambda = B.three_point_tree.NodesPerLevel();\n  auto Delta = B.cont_lin_tree.NodesPerLevel();\n\n  for (int l = 0; l < ml; ++l) {\n    CheckMatrixQuadrature<\n        MassOperator<ContLinearScalingFn, ContLinearScalingFn>,\n        ContLinearScalingFn, ContLinearScalingFn>({Delta[l]}, false, {Delta[l]},\n                                                  false);\n  }\n}\n\nTEST(DiscLinearScaling, CheckMatrixTransposes) {\n  // Reset the persistent trees.\n  Bases B;\n\n  int ml = 7;\n\n  B.ortho_tree.UniformRefine(ml);\n  auto Lambda = B.ortho_tree.NodesPerLevel();\n  auto Delta = B.disc_lin_tree.NodesPerLevel();\n\n  for (int l = 1; l < ml; ++l) {\n    std::cout << \"Prolongation\" << std::endl;\n    CheckMatrixTranspose<Prolongate<DiscLinearScalingFn>, DiscLinearScalingFn,\n                         DiscLinearScalingFn>({Delta[l - 1]}, {Delta[l]});\n    std::cout << \"MassOperator\" << std::endl;\n    CheckMatrixTranspose<MassOperator<DiscLinearScalingFn, DiscLinearScalingFn>,\n                         DiscLinearScalingFn, DiscLinearScalingFn>(\n        {Delta[l - 1]}, {Delta[l - 1]});\n    std::cout << \"ZeroEvalOperator\" << std::endl;\n    CheckMatrixTranspose<\n        ZeroEvalOperator<DiscLinearScalingFn, DiscLinearScalingFn>,\n        DiscLinearScalingFn, DiscLinearScalingFn>({Delta[l - 1]},\n                                                  {Delta[l - 1]});\n  }\n}\n\nTEST(DiscLinearScaling, MatrixQuadrature) {\n  // Reset the persistent trees.\n  Bases B;\n\n  int ml = 7;\n\n  B.ortho_tree.UniformRefine(ml);\n  auto Lambda = B.ortho_tree.NodesPerLevel();\n  auto Delta = B.disc_lin_tree.NodesPerLevel();\n\n  for (int l = 0; l < ml; ++l) {\n    CheckMatrixQuadrature<\n        MassOperator<DiscLinearScalingFn, DiscLinearScalingFn>,\n        DiscLinearScalingFn, DiscLinearScalingFn>({Delta[l]}, false, {Delta[l]},\n                                                  false);\n  }\n}\n\nTEST(DiscContLinearScaling, CheckMatrixTransposes) {\n  // Reset the persistent trees.\n  Bases B;\n\n  int ml = 7;\n\n  B.three_point_tree.UniformRefine(ml);\n  auto Lambda_3pt = B.three_point_tree.NodesPerLevel();\n  auto Delta_3pt = B.cont_lin_tree.NodesPerLevel();\n\n  B.ortho_tree.UniformRefine(ml);\n  auto Lambda_ortho = B.ortho_tree.NodesPerLevel();\n  auto Delta_ortho = B.disc_lin_tree.NodesPerLevel();\n\n  for (int l = 1; l < ml; ++l) {\n    CheckMatrixTranspose<MassOperator<ContLinearScalingFn, DiscLinearScalingFn>,\n                         ContLinearScalingFn, DiscLinearScalingFn>(\n        {Delta_3pt[l - 1]}, {Delta_ortho[l - 1]});\n    CheckMatrixTranspose<MassOperator<DiscLinearScalingFn, ContLinearScalingFn>,\n                         DiscLinearScalingFn, ContLinearScalingFn>(\n        {Delta_ortho[l - 1]}, {Delta_3pt[l - 1]});\n    CheckMatrixTranspose<\n        ZeroEvalOperator<ContLinearScalingFn, DiscLinearScalingFn>,\n        ContLinearScalingFn, DiscLinearScalingFn>({Delta_3pt[l - 1]},\n                                                  {Delta_ortho[l - 1]});\n    CheckMatrixTranspose<\n        ZeroEvalOperator<DiscLinearScalingFn, ContLinearScalingFn>,\n        DiscLinearScalingFn, ContLinearScalingFn>({Delta_ortho[l - 1]},\n                                                  {Delta_3pt[l - 1]});\n    CheckMatrixTranspose<\n        TransportOperator<ContLinearScalingFn, DiscLinearScalingFn>,\n        ContLinearScalingFn, DiscLinearScalingFn>({Delta_3pt[l - 1]},\n                                                  {Delta_ortho[l - 1]});\n  }\n}\n\nTEST(DiscContLinearScaling, ZeroEvalWorks) {\n  // Reset the persistent trees.\n  Bases B;\n\n  int ml = 7;\n\n  B.three_point_tree.UniformRefine(ml);\n  auto Lambda_3pt = B.three_point_tree.NodesPerLevel();\n  auto Delta_3pt = B.cont_lin_tree.NodesPerLevel();\n\n  B.ortho_tree.UniformRefine(ml);\n  auto Lambda_ortho = B.ortho_tree.NodesPerLevel();\n  auto Delta_ortho = B.disc_lin_tree.NodesPerLevel();\n\n  for (int l = 0; l < ml; ++l) {\n    auto mat =\n        ZeroEvalOperator<ContLinearScalingFn, DiscLinearScalingFn>().ToMatrix(\n            {Delta_3pt[l]}, {Delta_ortho[l]});\n    for (int j = 0; j < Delta_3pt[l].size(); ++j)\n      for (int i = 0; i < Delta_ortho[l].size(); ++i)\n        ASSERT_NEAR(mat(i, j),\n                    Delta_3pt[l][j]->Eval(0.0) * Delta_ortho[l][i]->Eval(0.0),\n                    1e-10);\n  }\n}\nTEST(DiscContLinearScaling, MatrixQuadrature) {\n  // Reset the persistent trees.\n  Bases B;\n\n  int ml = 7;\n\n  B.three_point_tree.UniformRefine(ml);\n  auto Lambda_3pt = B.three_point_tree.NodesPerLevel();\n  auto Delta_3pt = B.cont_lin_tree.NodesPerLevel();\n\n  B.ortho_tree.UniformRefine(ml);\n  auto Lambda_ortho = B.ortho_tree.NodesPerLevel();\n  auto Delta_ortho = B.disc_lin_tree.NodesPerLevel();\n\n  for (int l = 0; l < ml; ++l) {\n    CheckMatrixQuadrature<\n        MassOperator<ContLinearScalingFn, DiscLinearScalingFn>,\n        ContLinearScalingFn, DiscLinearScalingFn>({Delta_3pt[l]}, false,\n                                                  {Delta_ortho[l]}, false);\n    CheckMatrixQuadrature<\n        MassOperator<DiscLinearScalingFn, ContLinearScalingFn>,\n        DiscLinearScalingFn, ContLinearScalingFn>({Delta_ortho[l]}, false,\n                                                  {Delta_3pt[l]}, false);\n    bool matrices_are_transposes =\n        MassOperator<ContLinearScalingFn, DiscLinearScalingFn>()\n            .ToMatrix({Delta_3pt[l]}, {Delta_ortho[l]})\n            .transpose()\n            .isApprox(MassOperator<DiscLinearScalingFn, ContLinearScalingFn>()\n                          .ToMatrix({Delta_ortho[l]}, {Delta_3pt[l]}));\n    ASSERT_TRUE(matrices_are_transposes);\n\n    CheckMatrixQuadrature<\n        TransportOperator<ContLinearScalingFn, DiscLinearScalingFn>,\n        ContLinearScalingFn, DiscLinearScalingFn>({Delta_3pt[l]}, true,\n                                                  {Delta_ortho[l]}, false);\n  }\n}\n\n}  // namespace Time\n", "meta": {"hexsha": "2b237cb1ec5ae4a0f743bf8e7288eb90444ad053", "size": 10716, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/time/linear_operator_test.cpp", "max_stars_repo_name": "rvanvenetie/spacetime", "max_stars_repo_head_hexsha": "b516419be2a59115d9b2d853aeea9fcd4f125c94", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/time/linear_operator_test.cpp", "max_issues_repo_name": "rvanvenetie/spacetime", "max_issues_repo_head_hexsha": "b516419be2a59115d9b2d853aeea9fcd4f125c94", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/time/linear_operator_test.cpp", "max_forks_repo_name": "rvanvenetie/spacetime", "max_forks_repo_head_hexsha": "b516419be2a59115d9b2d853aeea9fcd4f125c94", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7922077922, "max_line_length": 80, "alphanum_fraction": 0.62383352, "num_tokens": 2850, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.4840660926442665}}
{"text": "#include \"timer.h\"\n#include <Eigen/Dense>\n#include <cassert>\n#include <cmath>\n#include <iostream>\n\n\nusing numeric_t = double;\n\nnumeric_t flushCache() {\n    const size_t N = 1000;\n    const Eigen::MatrixXd A = Eigen::MatrixXd::Random(N, N);\n    const Eigen::VectorXd x = Eigen::MatrixXd::Random(N, 1);\n\n    return x.transpose() * A * x;\n}\n\nint main() {\n    const numeric_t alpha = 1e-4;\n    const size_t L = 1000;\n    const size_t T = 1;\n    const size_t N = 1000000;\n    const numeric_t tau = 0.001;\n\n    assert(tau < std::pow((L / static_cast<numeric_t>(N)), 2) / (2. * alpha));\n\n    auto u0 = [](numeric_t x) {\n        return std::sin(2. * M_PI * x / L);\n    };\n    Eigen::MatrixXd U = Eigen::MatrixXd::Zero(N, T / tau);\n\n    Timer timer;\n\n    for (size_t lap = 0; lap < 10; ++lap) {\n        std::cout << \"starting lap: \" << lap << std::endl;\n        timer.start();\n\n        const Eigen::VectorXd x = Eigen::VectorXd::LinSpaced(N, 0, L);\n        U.col(0) = x.unaryExpr(u0);\n\n        for (size_t t = 0; t < ((T / tau) - 1); ++t) {\n            for (size_t i = 0; i < N; ++i) {\n                U(i, t + 1) = U(i, t) + (tau * alpha / (x(1) * x(1))) * (\n                        U(((i - 1) + N) % N, t) - 2. * U(i, t) +\n                        U((i + 1) % N, t)\n                );\n            }\n        }\n\n        timer.lap();\n\n        std::cout << \"flushing cache: \" << flushCache() << std::endl;\n    }\n\n    std::cout << \"Average runtime: \" << timer.mean() << \"s\" << std::endl;\n    std::cout << \"Minimal runtime: \" << timer.min() << \"s\" << std::endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "054129b4ffbe84d20b36e1af1b6297d2c4d1ac5e", "size": 1565, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "exercise01/roofline/main.cpp", "max_stars_repo_name": "anianruoss/HPCSE-I", "max_stars_repo_head_hexsha": "35ca12ae22596dd29379a5c337ea27f40be1e61e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "exercise01/roofline/main.cpp", "max_issues_repo_name": "anianruoss/HPCSE-I", "max_issues_repo_head_hexsha": "35ca12ae22596dd29379a5c337ea27f40be1e61e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "exercise01/roofline/main.cpp", "max_forks_repo_name": "anianruoss/HPCSE-I", "max_forks_repo_head_hexsha": "35ca12ae22596dd29379a5c337ea27f40be1e61e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.0833333333, "max_line_length": 78, "alphanum_fraction": 0.4856230032, "num_tokens": 501, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431679972357831, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.4840660902636561}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#include \"Framework/TestingFramework.hpp\"\n\n#include <algorithm>\n#include <array>\n#include <boost/optional/optional.hpp>\n#include <cstddef>\n#include <type_traits>\n\n#include \"ControlSystem/Averager.hpp\"\n#include \"DataStructures/DataVector.hpp\"\n#include \"Utilities/ConstantExpressions.hpp\"\n\nSPECTRE_TEST_CASE(\"Unit.ControlSystem.Averager.Linear\",\n                  \"[ControlSystem][Unit]\") {\n  double t = 0.0;\n  const double dt = 0.1;\n  constexpr size_t deriv_order = 2;\n  const double final_time = 5.0;\n\n  // test true and false `using_average_0th_deriv_of_q`\n  Averager<deriv_order> averager_t(0.5, true);\n  Averager<deriv_order> averager_f(0.5, false);\n\n  CHECK(averager_t.using_average_0th_deriv_of_q());\n  CHECK_FALSE(averager_f.using_average_0th_deriv_of_q());\n\n  // define custom approx for second derivative checks\n  Approx custom_approx = Approx::custom().epsilon(1.0e-12).scale(1.0);\n\n  while (t < final_time) {\n    // test using an analytic function f(t) = t\n    const DataVector analytic_func = {t, 1.0, 0.0};\n\n    // update exponential averager\n    averager_t.update(t, {analytic_func[0]}, {0.1});\n    averager_f.update(t, {analytic_func[0]}, {0.1});\n    // compare values once averager has sufficient data\n    if (averager_t(t)) {\n      const auto result_t = averager_t(t).get();\n      // check function value, which should agree with the effective time\n      CHECK(approx(result_t[0][0]) == averager_t.average_time(t));\n      // check first derivative\n      CHECK(approx(result_t[1][0]) == analytic_func[1]);\n      // check second derivative\n      // The exponential averager uses finite differencing to approximate the\n      // derivatives. The second derivative is only a first order approximation,\n      // which is why we enforce a less stringent check here.\n      CHECK(custom_approx(result_t[2][0]) == analytic_func[2]);\n    }\n    if (averager_f(t)) {\n      const auto result_f = averager_f(t).get();\n      // check function value, which should agree with the true time `t`\n      CHECK(approx(result_f[0][0]) == t);\n      // check first derivative\n      CHECK(approx(result_f[1][0]) == analytic_func[1]);\n      // check second derivative\n      // The exponential averager uses finite differencing to approximate the\n      // derivatives. The second derivative is only a first order approximation,\n      // which is why we enforce a less stringent check here.\n      CHECK(custom_approx(result_f[2][0]) == analytic_func[2]);\n    }\n\n    t += dt;\n  }\n}\n\nSPECTRE_TEST_CASE(\"Unit.ControlSystem.Averager.SemiAnalytic\",\n                  \"[ControlSystem][Unit]\") {\n  double t = 0.0;\n  constexpr size_t deriv_order = 2;\n  const double final_time = 5.0;\n\n  // The equations suggests that our exponential averager is equivalent\n  // to the simple exponential averaging method of\n  // F_avg(t) = \\alpha*F(t) + (1 - \\alpha)*F_avg(t_{-1}}\n  // where \\alpha = \\tau_m / (W(t)*D) and D = 1.0 + \\tau_m/tau_avg\n  // However, the exponential averager that we are testing has time varying\n  // weight, so we allow \\alpha to be a function of time and update at\n  // each timestep.\n\n  // some vars for a simple exponential average to compare against\n  std::array<DataVector, deriv_order + 1> avg_values{{{0.0}, {0.0}, {0.0}}};\n  double avg_time = 0.0;\n\n  // the measurement timescale (tau_m)\n  const double tau_m = 0.1;\n  const double avg_tscale_fac = 1.0;\n  const double damping_time = 0.1;\n  const double denom = 1.0 + tau_m / (avg_tscale_fac * damping_time);\n  // the average weight, represents W(t) in the above comment\n  double avg_weight = 0.0;\n\n  Averager<deriv_order> averager(avg_tscale_fac, true);\n\n  // define custom approx for second derivative checks\n  Approx custom_approx = Approx::custom().epsilon(1.0e-12).scale(1.0);\n\n  while (t < final_time) {\n    // test using an analytic function f(t) = t**2\n    const DataVector analytic_func = {square(t), 2.0 * t, 2.0};\n\n    // update exponential averager\n    averager.update(t, {analytic_func[0]}, {damping_time});\n    // compare values once averager has sufficient data\n    if (averager(t)) {\n      // update the weight and \\alpha\n      avg_weight = (tau_m + avg_weight) / denom;\n      const double alpha = tau_m / avg_weight / denom;\n\n      // do simple average of time, analytic func and its analytic derivatives\n      avg_time = alpha * t + (1.0 - alpha) * avg_time;\n      avg_values[0] = alpha * analytic_func[0] + (1.0 - alpha) * avg_values[0];\n      avg_values[1] = alpha * analytic_func[1] + (1.0 - alpha) * avg_values[1];\n      avg_values[2] = alpha * analytic_func[2] + (1.0 - alpha) * avg_values[2];\n\n      auto result = averager(t).get();\n\n      // check that the effective times agree with the averaged time\n      CHECK(approx(averager.average_time(t)) == avg_time);\n      // check function value\n      CHECK(approx(result[0][0]) == avg_values[0][0]);\n      // check first derivative\n      CHECK(approx(result[1][0]) == avg_values[1][0]);\n      // check second derivative\n      // Again, this check is slightly looser than the others due to\n      // numerical differentiation (see comment in Averager.Linear test)\n      CHECK(custom_approx(result[2][0]) == avg_values[2][0]);\n    } else {\n      avg_time = t;\n      avg_values = {\n          {{analytic_func[0]}, {analytic_func[1]}, {analytic_func[2]}}};\n    }\n\n    t += tau_m;\n  }\n}\n\nSPECTRE_TEST_CASE(\"Unit.ControlSystem.Averager.Functionality\",\n                  \"[ControlSystem][Unit]\") {\n  double t = 0.0;\n  const double dt = 0.1;\n  constexpr size_t deriv_order = 2;\n\n  Averager<deriv_order> averager(0.5, false);\n\n  // test the validity of data functionality\n  // data not valid yet\n  CHECK_FALSE(static_cast<bool>(averager(t)));\n  // first update\n  averager.update(t, {t}, {0.1});\n  // data not valid yet\n  CHECK_FALSE(static_cast<bool>(averager(t)));\n  t += dt;\n  // second update\n  averager.update(t, {t}, {0.1});\n  // data not valid yet\n  CHECK_FALSE(static_cast<bool>(averager(t)));\n  t += dt;\n  // third update\n  averager.update(t, {t}, {0.1});\n  // data should be valid now\n  CHECK(static_cast<bool>(averager(t)));\n  CHECK(averager(t).get()[0][0] == t);\n  t += dt;\n  // data should currently be invalid since there was no update at this new `t`\n  CHECK_FALSE(static_cast<bool>(averager(t)));\n  // last updated time should then be the time before this step\n  CHECK(approx(averager.last_time_updated()) == (t - dt));\n\n  // test the clear() function:\n  // update averager again, so that data is valid\n  averager.update(t, {t}, {0.1});\n  CHECK(static_cast<bool>(averager(t)));\n  // clear the averager, which should make the data no longer valid\n  averager.clear();\n  CHECK_FALSE(static_cast<bool>(averager(t)));\n}\n\n// [[OutputRegex, at or before the last time]]\nSPECTRE_TEST_CASE(\"Unit.ControlSystem.Averager.BadUpdateTwice\",\n                  \"[ControlSystem][Unit]\") {\n  ERROR_TEST();\n  Averager<2> averager(0.5, false);\n\n  averager.update(0.5, {0.0}, {0.1});\n  averager.update(0.5, {0.0}, {0.1});\n}\n\n// [[OutputRegex, at or before the last time]]\nSPECTRE_TEST_CASE(\"Unit.ControlSystem.Averager.BadUpdatePast\",\n                  \"[ControlSystem][Unit]\") {\n  ERROR_TEST();\n  Averager<2> averager(0.5, false);\n\n  averager.update(0.5, {0.0}, {0.1});\n  averager.update(0.3, {0.0}, {0.1});\n}\n\n// [[OutputRegex, The number of supplied timescales \\(1\\) does not match]]\nSPECTRE_TEST_CASE(\"Unit.ControlSystem.Averager.WrongSizeTimescales\",\n                  \"[ControlSystem][Unit]\") {\n  ERROR_TEST();\n\n  double t = 0.0;\n  constexpr size_t deriv_order = 2;\n\n  Averager<deriv_order> averager(1.0, false);\n  averager.update(t, {{0.2, 0.3}}, {0.1});\n}\n\n// [[OutputRegex, The number of components in the raw_q provided \\(2\\) does]]\nSPECTRE_TEST_CASE(\"Unit.ControlSystem.Averager.WrongSizeQProvided\",\n                  \"[ControlSystem][Unit]\") {\n  ERROR_TEST();\n\n  double t = 0.0;\n  constexpr size_t deriv_order = 2;\n\n  Averager<deriv_order> averager(1.0, false);\n\n  averager.update(t, {0.1}, {0.1});\n  averager.update(t, {{0.2, 0.3}}, {0.1});\n}\n\n// [[OutputRegex, must be positive]]\nSPECTRE_TEST_CASE(\"Unit.ControlSystem.Averager.BadAvgTimescale\",\n                  \"[ControlSystem][Unit]\") {\n  ERROR_TEST();\n  Averager<2> averager(0.0, true);\n}\n\n// [[OutputRegex, The time history has not been updated yet]]\nSPECTRE_TEST_CASE(\"Unit.ControlSystem.Averager.BadCallToLastTimeUpdated\",\n                  \"[ControlSystem][Unit]\") {\n  ERROR_TEST();\n  Averager<2> averager(1.0, true);\n  averager.last_time_updated();\n}\n\n// [[OutputRegex, Cannot return averaged values because the averager does not]]\nSPECTRE_TEST_CASE(\"Unit.ControlSystem.Averager.BadCallToAverageTime\",\n                  \"[ControlSystem][Unit]\") {\n  ERROR_TEST();\n  Averager<2> averager(1.0, true);\n  averager.average_time(0.0);\n}\n\nSPECTRE_TEST_CASE(\"Unit.ControlSystem.Averager.TestMove\",\n                  \"[ControlSystem][Unit]\") {\n  Averager<2> averager(0.25, false);\n  static_assert(std::is_nothrow_move_constructible<Averager<2>>::value,\n                \"Averager is not nothrow move constructible\");\n  static_assert(std::is_nothrow_move_assignable<Averager<2>>::value,\n                \"Averager is not nothrow move assignable\");\n  // update with junk data\n  averager.update(0.3, {0.1}, {0.1});\n  averager.update(0.5, {0.2}, {0.1});\n  averager.update(0.7, {0.4}, {0.1});\n  averager.update(0.9, {0.6}, {0.1});\n  // get correct values for comparison\n  auto last_time = averager.last_time_updated();\n  auto avg_time = averager.average_time(0.9);\n  auto avg_q = averager.using_average_0th_deriv_of_q();\n  auto avg_values = averager(0.9).get();\n  // test move constructor\n  auto new_averager(std::move(averager));\n  // check moved values against stored values\n  CHECK(last_time == new_averager.last_time_updated());\n  CHECK(avg_time == new_averager.average_time(0.9));\n  CHECK(avg_q == new_averager.using_average_0th_deriv_of_q());\n  CHECK(avg_values[0][0] == new_averager(0.9).get()[0][0]);\n  // test move assignment\n  Averager<2> new_averager2(0.1, true);\n  new_averager2 = std::move(new_averager);\n  // check moved values against stored values\n  CHECK(last_time == new_averager2.last_time_updated());\n  CHECK(avg_time == new_averager2.average_time(0.9));\n  CHECK(avg_q == new_averager2.using_average_0th_deriv_of_q());\n  CHECK(avg_values[0][0] == new_averager2(0.9).get()[0][0]);\n}\n", "meta": {"hexsha": "9cc668afa6d73232843ceb8853f371473f9c50cc", "size": 10331, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/Unit/ControlSystem/Test_Averager.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": "tests/Unit/ControlSystem/Test_Averager.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": "tests/Unit/ControlSystem/Test_Averager.cpp", "max_forks_repo_name": "tomwlodarczyk/spectre", "max_forks_repo_head_hexsha": "086aaee002f2f07eb812cf17b8e1ba54052feb71", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-01-03T21:47:04.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-03T21:47:04.000Z", "avg_line_length": 36.3767605634, "max_line_length": 80, "alphanum_fraction": 0.6706030394, "num_tokens": 2926, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743167997235783, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.48406609026365593}}
{"text": "//\n// ConfusionMatrix.hpp\n// Represents a confusion matrix for multi-class evaluation\n//\n\n#ifndef FUMAROLE_LOCALIZATION_CONFUSIONMATRIX_HPP\n#define FUMAROLE_LOCALIZATION_CONFUSIONMATRIX_HPP\n\n#include <vector>\n#include <string>\n#include <tuple>\n#include <iostream>\n\n#ifdef __APPLE__\n    #include <eigen3/Eigen/Eigen>\n#else\n    #include <Eigen/Eigen>\n#endif\n\nnamespace Evaluation\n{\n    class ConfusionMatrix\n    {\n    public:\n        /// Construct the matrix with the given class labels\n        /// \\param classLabels A list of class labels\n        ConfusionMatrix(const std::vector<std::string>& classLabels);\n\n        ~ConfusionMatrix();\n\n        /// Add classification count for a classification output by the classifier\n        /// \\param predictedClass The name of the class that the classifier predicted\n        /// \\param actualClass The name of the class that was the ground truth class\n        /// \\param count The number of classifications made\n        void AddClassifications(const std::string& predictedClass, const std::string& actualClass, int count = 1);\n\n        /// Returns the accuracy of the classifier\n        /// \\return The accuracy score\n        float GetAccuracy() const;\n\n        /// Returns the precision of the classifier for the given class\n        /// \\param classLabel The name of the class\n        /// \\return The precision score\n        float GetPrecision(const std::string& classLabel) const;\n\n        /// Returns the recall of the classifier for the given class\n        /// \\param classLabel\n        /// \\return The recall score\n        float GetRecall(const std::string& classLabel) const;\n\n        /// Output confusion matrix as a CSV stream\n        /// \\param os output stream\n        /// \\param cm Confusion matrix\n        /// \\return A reference to the output stream\n        friend std::ostream& operator<<(std::ostream& os, const ConfusionMatrix& cm);\n\n        /// Append another confusion matrix scores\n        /// \\param other The other confusion matrix (dimensions must match)\n        /// \\return Return the reference to this matrix with the appended matrix data\n        ConfusionMatrix& operator+=(const ConfusionMatrix& other);\n\n    private:\n        int IndexOfClass(const std::string& classLabel) const;\n\n    private:\n        std::vector<std::string> m_ClassLabels;\n        Eigen::MatrixXi m_Matrix;\n    };\n}\n\n#endif //FUMAROLE_LOCALIZATION_CONFUSIONMATRIX_HPP\n", "meta": {"hexsha": "b2e4d33dee85533aa0feb858826ef92974dc4edf", "size": 2405, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "fumarole_localization/include/evaluation/ConfusionMatrix.hpp", "max_stars_repo_name": "asadahmedde/advanced-project-2", "max_stars_repo_head_hexsha": "748f8f9a575cf926646201cecb0e5a8d3bdaf377", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fumarole_localization/include/evaluation/ConfusionMatrix.hpp", "max_issues_repo_name": "asadahmedde/advanced-project-2", "max_issues_repo_head_hexsha": "748f8f9a575cf926646201cecb0e5a8d3bdaf377", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fumarole_localization/include/evaluation/ConfusionMatrix.hpp", "max_forks_repo_name": "asadahmedde/advanced-project-2", "max_forks_repo_head_hexsha": "748f8f9a575cf926646201cecb0e5a8d3bdaf377", "max_forks_repo_licenses": ["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.4027777778, "max_line_length": 114, "alphanum_fraction": 0.6798336798, "num_tokens": 514, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191214879992, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.48395782494554856}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// Unit Test\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#include <string>\n\n\n#include <geometry_test_common.hpp>\n\n#include <boost/geometry/extensions/algorithms/parse.hpp>\n#include <boost/geometry/geometries/point.hpp>\n#include <boost/geometry/strategies/strategies.hpp>\n\n#include <boost/geometry/extensions/gis/geographic/strategies/dms_parser.hpp>\n\n#include <test_common/test_point.hpp>\n\nusing namespace boost::geometry;\n\ntemplate <typename P>\nvoid test_2d(double c, bool use_strategy)\n{\n    // normal order, east=x, north=y\n    P p;\n    parse(p, std::string(\"1dE\"), std::string(\"2N\"));\n    BOOST_CHECK_CLOSE( ((double) bg::get<0>(p)), (double) 1 * c, 1.0e-6);\n    BOOST_CHECK_CLOSE( ((double) bg::get<1>(p)), (double) 2 * c, 1.0e-6);\n\n    // reversed order, y,x -> should be interpreted correctly\n    parse(p, std::string(\"1dN\"), std::string(\"2E\"));\n    BOOST_CHECK_CLOSE( ((double) bg::get<0>(p)), (double) 2 * c, 1.0e-6);\n    BOOST_CHECK_CLOSE( ((double) bg::get<1>(p)), (double) 1 * c, 1.0e-6);\n\n    if (use_strategy)\n    {\n        // DUTCH system NOZW, only for degrees\n        bg::strategy::dms_parser<false, 'N', 'O', 'Z', 'W'> strategy;\n        parse(p, std::string(\"1dO\"), std::string(\"2Z\"), strategy);\n        BOOST_CHECK_CLOSE( ((double) bg::get<0>(p)), (double) 1, 1.0e-6);\n        BOOST_CHECK_CLOSE( ((double) bg::get<1>(p)), (double) -2, 1.0e-6);\n    }\n\n    // rest of DMS is checked in parse_dms\n}\n\ntemplate <typename T, typename P>\nvoid test_3d()\n{\n}\n\nint test_main(int, char* [])\n{\n    //test_2d<point<int, 2, cs::geographic<radian> > >();\n    //test_2d<point<float, 2, cs::geographic<radian> > >();\n\n    test_2d<bg::model::point<double, 2, bg::cs::geographic<bg::degree> > >(1.0, true);\n    test_2d<bg::model::point<double, 2, bg::cs::geographic<bg::radian> > >(bg::math::d2r, false);\n\n    return 0;\n}\n", "meta": {"hexsha": "a099d9b1f001bbf7947b038100fed779f4638863", "size": 2358, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "extensions/test/gis/latlong/parse.cpp", "max_stars_repo_name": "jkerkela/geometry", "max_stars_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 326.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T13:47:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T02:13:59.000Z", "max_issues_repo_path": "extensions/test/gis/latlong/parse.cpp", "max_issues_repo_name": "jkerkela/geometry", "max_issues_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 623.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T23:45:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T11:15:23.000Z", "max_forks_repo_path": "extensions/test/gis/latlong/parse.cpp", "max_forks_repo_name": "jkerkela/geometry", "max_forks_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-01-14T15:50:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T03:58:36.000Z", "avg_line_length": 33.2112676056, "max_line_length": 97, "alphanum_fraction": 0.6615776081, "num_tokens": 754, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191214879992, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.48395782494554856}}
{"text": "// Copyright Abel Sinkovics (abel@sinkovics.hu)  2012.\r\n// Distributed under the Boost Software License, Version 1.0.\r\n//    (See accompanying file LICENSE_1_0.txt or copy at\r\n//          http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#include <boost/metaparse/repeated.hpp>\r\n#include <boost/metaparse/sequence.hpp>\r\n#include <boost/metaparse/lit_c.hpp>\r\n#include <boost/metaparse/last_of.hpp>\r\n#include <boost/metaparse/space.hpp>\r\n#include <boost/metaparse/int_.hpp>\r\n#include <boost/metaparse/foldl_reject_incomplete_start_with_parser.hpp>\r\n#include <boost/metaparse/one_of.hpp>\r\n#include <boost/metaparse/get_result.hpp>\r\n#include <boost/metaparse/token.hpp>\r\n#include <boost/metaparse/entire_input.hpp>\r\n#include <boost/metaparse/string.hpp>\r\n#include <boost/metaparse/transform.hpp>\r\n#include <boost/metaparse/always.hpp>\r\n#include <boost/metaparse/build_parser.hpp>\r\n\r\n#include <boost/mpl/apply_wrap.hpp>\r\n#include <boost/mpl/front.hpp>\r\n#include <boost/mpl/back.hpp>\r\n#include <boost/mpl/bool.hpp>\r\n#include <boost/mpl/if.hpp>\r\n\r\nusing boost::metaparse::sequence;\r\nusing boost::metaparse::lit_c;\r\nusing boost::metaparse::last_of;\r\nusing boost::metaparse::space;\r\nusing boost::metaparse::repeated;\r\nusing boost::metaparse::build_parser;\r\nusing boost::metaparse::int_;\r\nusing boost::metaparse::foldl_reject_incomplete_start_with_parser;\r\nusing boost::metaparse::get_result;\r\nusing boost::metaparse::one_of;\r\nusing boost::metaparse::token;\r\nusing boost::metaparse::entire_input;\r\nusing boost::metaparse::transform;\r\nusing boost::metaparse::always;\r\n\r\nusing boost::mpl::apply_wrap1;\r\nusing boost::mpl::front;\r\nusing boost::mpl::back;\r\nusing boost::mpl::if_;\r\nusing boost::mpl::bool_;\r\n\r\n/*\r\n * The grammar\r\n *\r\n * expression ::= plus_exp\r\n * plus_exp ::= prod_exp ((plus_token | minus_token) prod_exp)*\r\n * prod_exp ::= value_exp ((mult_token | div_token) value_exp)*\r\n * value_exp ::= int_token | '_'\r\n */\r\n\r\ntypedef token<lit_c<'+'> > plus_token;\r\ntypedef token<lit_c<'-'> > minus_token;\r\ntypedef token<lit_c<'*'> > mult_token;\r\ntypedef token<lit_c<'/'> > div_token;\r\n \r\ntypedef token<int_> int_token;\r\ntypedef token<lit_c<'_'> > arg_token;\r\n\r\ntemplate <class T, char C>\r\nstruct is_c : bool_<T::type::value == C> {};\r\n\r\nstruct build_plus\r\n{\r\n  template <class A, class B>\r\n  class _plus\r\n  {\r\n  public:\r\n    typedef _plus type;\r\n\r\n    template <class T>\r\n    T operator()(T t) const\r\n    {\r\n      return _left(t) + _right(t);\r\n    }\r\n  private:\r\n    typename A::type _left;\r\n    typename B::type _right;\r\n  };\r\n\r\n  template <class A, class B>\r\n  class _minus\r\n  {\r\n  public:\r\n    typedef _minus type;\r\n\r\n    template <class T>\r\n    T operator()(T t) const\r\n    {\r\n      return _left(t) - _right(t);\r\n    }\r\n  private:\r\n    typename A::type _left;\r\n    typename B::type _right;\r\n  };\r\n\r\n  template <class State, class C>\r\n  struct apply :\r\n    if_<\r\n      typename is_c<front<C>, '+'>::type,\r\n      _plus<State, typename back<C>::type>,\r\n      _minus<State, typename back<C>::type>\r\n    >\r\n  {};\r\n};\r\n\r\nstruct build_mult\r\n{\r\n  template <class A, class B>\r\n  class _mult\r\n  {\r\n  public:\r\n    typedef _mult type;\r\n\r\n    template <class T>\r\n    T operator()(T t) const\r\n    {\r\n      return _left(t) * _right(t);\r\n    }\r\n  private:\r\n    typename A::type _left;\r\n    typename B::type _right;\r\n  };\r\n\r\n  template <class A, class B>\r\n  class _div\r\n  {\r\n  public:\r\n    typedef _div type;\r\n\r\n    template <class T>\r\n    T operator()(T t) const\r\n    {\r\n      return _left(t) / _right(t);\r\n    }\r\n  private:\r\n    typename A::type _left;\r\n    typename B::type _right;\r\n  };\r\n\r\n  template <class State, class C>\r\n  struct apply :\r\n    if_<\r\n      typename is_c<front<C>, '*'>::type,\r\n      _mult<State, typename back<C>::type>,\r\n      _div<State, typename back<C>::type>\r\n    >\r\n  {};\r\n};\r\n\r\nstruct build_value\r\n{\r\n  typedef build_value type;\r\n\r\n  template <class V>\r\n  struct apply\r\n  {\r\n    typedef apply type;\r\n\r\n    template <class T>\r\n    int operator()(T) const\r\n    {\r\n      return V::type::value;\r\n    }\r\n  };\r\n};\r\n\r\nstruct arg\r\n{\r\n  typedef arg type;\r\n\r\n  template <class T>\r\n  T operator()(T t) const\r\n  {\r\n    return t;\r\n  }\r\n};\r\n\r\ntypedef\r\n  one_of<transform<int_token, build_value>, always<arg_token, arg> >\r\n  value_exp;\r\n\r\ntypedef\r\n  foldl_reject_incomplete_start_with_parser<\r\n    sequence<one_of<mult_token, div_token>, value_exp>,\r\n    value_exp,\r\n    build_mult\r\n  >\r\n  prod_exp;\r\n  \r\ntypedef\r\n  foldl_reject_incomplete_start_with_parser<\r\n    sequence<one_of<plus_token, minus_token>, prod_exp>,\r\n    prod_exp,\r\n    build_plus\r\n  >\r\n  plus_exp;\r\n\r\ntypedef last_of<repeated<space>, plus_exp> expression;\r\n\r\ntypedef build_parser<entire_input<expression> > function_parser;\r\n\r\n#if BOOST_METAPARSE_STD < 2011\r\n\r\ntemplate <class Exp>\r\nstruct lambda : apply_wrap1<function_parser, Exp> {};\r\n\r\nusing boost::metaparse::string;\r\n\r\nlambda<string<'1','3'> >::type f1;\r\nlambda<string<'2',' ','+',' ','3'> >::type f2;\r\nlambda<string<'2',' ','*',' ','2'> >::type f3;\r\nlambda<string<' ','1','+',' ','2','*','4','-','6','/','2'> >::type f4;\r\nlambda<string<'2',' ','*',' ','_'> >::type f5;\r\n\r\n#else\r\n\r\n#ifdef LAMBDA\r\n  #error LAMBDA already defined\r\n#endif\r\n#define LAMBDA(exp) apply_wrap1<function_parser, BOOST_METAPARSE_STRING(#exp)>::type\r\n\r\nLAMBDA(13) f1;\r\nLAMBDA(2 + 3) f2;\r\nLAMBDA(2 * 2) f3;\r\nLAMBDA( 1+ 2*4-6/2) f4;\r\nLAMBDA(2 * _) f5;\r\n\r\n#endif\r\n\r\nint main()\r\n{\r\n  using std::cout;\r\n  using std::endl;\r\n\r\n  cout\r\n    << f1(11) << endl\r\n    << f2(11) << endl\r\n    << f3(11) << endl\r\n    << f4(11) << endl\r\n    << f5(11) << endl\r\n    << f5(1.1) << endl\r\n    ;\r\n}\r\n\r\n\r\n", "meta": {"hexsha": "9161e699786f25b8dfc3887d192da5cdc863a89d", "size": 5563, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/metaparse/example/compile_to_native_code/main.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": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/metaparse/example/compile_to_native_code/main.cpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-04T18:00:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-04T18:00:00.000Z", "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/metaparse/example/compile_to_native_code/main.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 21.9881422925, "max_line_length": 85, "alphanum_fraction": 0.6316735574, "num_tokens": 1573, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585903489891, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.48390441428978725}}
{"text": "#ifndef SHRS_HPP\n#define SHRS_HPP\n\n// std\n#include <string>\n#include <vector>\n#include <utility>\n#include <unordered_map>\n#include <unordered_set>\n\n// Eigen\n#include <Eigen/Dense>\n\n// PCL\n#include <pcl/io/pcd_io.h>\n#include <pcl/point_types.h>\n\n#include <GridPoint.hpp>\n\nnamespace fsd {\n\nusing Eigen::Vector2d;\nusing std::vector;\nusing std::unordered_map;\nusing std::unordered_set;\nusing std::begin;\nusing std::end;\nusing std::endl;\n\n/**\n * @brief The SHRS class spatial hashing radius search,\n * some data structure\n * for fast radius search in sparse pointcloud.\n * currently implemented only for 2D\n * and only for constant search_radius as\n * the cell_size is search_radius * 2.,\n * and no search circle rasterizing is implemented\n * yet but only getting the 1 - 4 cells which\n * this search circle can intersect\n * @tparam non-virtual dataset interface\n */\ntemplate<typename DatasetAdaptor>\nclass SHRS { \npublic:\n    using key_t = typename DatasetAdaptor::key_t;\n    using coords = GridPoint::coordinates;\n    using hash_func_t = std::hash<key_t>;\n    using cell_t = unordered_set<key_t, hash_func_t>;\n    using search_map_t = unordered_map<key_t, cell_t, hash_func_t>;\n\n    /**\n      *@brief constructor; if adj_matrix is passed, its calculated\n      */\n    SHRS(DatasetAdaptor dataset_adaptor, double search_radius_,\n         unordered_map<key_t, vector<key_t>> *adj_matrix = nullptr) :\n        dataset_adaptor(dataset_adaptor), cell_size(search_radius_ * 2.),\n        search_radius(search_radius_),\n        search_radius_2(pow(search_radius_, 2.)) {\n        // curently only search radius of cell_size\n        // implemented\n        cell_keys_to_search.reserve(4);\n        search_map.max_load_factor(0.5);\n        if(adj_matrix) {\n            calculate_adj_matrix(*adj_matrix);\n        }\n    }\n\n    SHRS &set_initial_cell_size(size_t value) {\n        initial_cell_size = value;\n        return *this;\n    }\n\n    /**\n     * @brief find_neighbours find\n     * all neigbours within set radius\n     * @param key key of point\n     * @return number of neighbours\n     */\n    size_t find_neighbours(key_t point_key,\n                           vector<key_t> &neighbours) {\n        neighbours.reserve(initial_neighbours_size);\n        return on_find_neighbours(point_key, [&](key_t key) {\n            neighbours.push_back(key);\n        });\n    }\n\n    /**\n     * @brief on_find_neighbours found neigbours\n     * with callback to eventually avoid copy\n     * @param point_key\n     * @param func\n     * @return\n     */\n    size_t on_find_neighbours(key_t point_key,\n                              std::function<void(key_t)> func) {\n        auto vec_pnt = dataset_adaptor.get_point(point_key);\n        auto cell_coords =\n                GridPoint::to_coordinates(vec_pnt, cell_size);\n        auto cell_key = GridPoint::pack_key(cell_coords);\n        if(search_map.find(cell_key) == end(search_map)) {\n            // this point doesn't exist in search_map\n            return 0;\n        }\n        size_t neighbours_found = 0;\n        get_cell_keys_in_range(vec_pnt, cell_keys_to_search);\n        // now search all cells ( maximum 4 cells are searched)\n        for(auto cell_key_to_search : cell_keys_to_search) {\n            if(search_map.find(cell_key_to_search) == end(search_map)) {\n                continue;\n            }\n            auto &point_keys = search_map.at(cell_key_to_search);\n            for(auto other_point_key : point_keys) {\n                if(point_key == other_point_key) {\n                    continue;\n                }\n                auto other_point =\n                        dataset_adaptor.get_point(other_point_key);\n                double distance2 = (vec_pnt - other_point).squaredNorm();\n                if(distance2 < search_radius_2) {\n                    func(other_point_key);\n                    neighbours_found++;\n                }\n            }\n        }\n        return neighbours_found;\n    }\n\n\n    /**\n     * @brief find_neighbours_vec find neigbours to a point\n     * not in dataset\n     * @param vec_pnt\n     * @param neighbours\n     * @return num of neigbours\n     */\n    size_t find_neighbours_vec(Vector2d const &vec_pnt,\n                               vector<key_t> &neighbours) {\n        neighbours.reserve(initial_neighbours_size);\n        return on_find_neighbours_vec(vec_pnt, [&](key_t key) {\n            neighbours.push_back(key);\n        });\n    }\n\n\n    /**\n     * @brief find_neighbours_vec find neigbours to a point\n     * not in dataset\n     * @param vec_pnt\n     * @param neighbours\n     * @return num of neigbours\n     */\n    size_t on_find_neighbours_vec(Vector2d const &vec_pnt,\n                                  std::function<void(key_t)> func) {\n        auto cell_coords =\n                GridPoint::to_coordinates(vec_pnt, cell_size);\n        size_t neighbours_found = 0;\n        get_cell_keys_in_range(vec_pnt, cell_keys_to_search);\n        // now search all cells ( maximum 4 cells are searched)\n        for(auto cell_key_to_search : cell_keys_to_search) {\n            if(search_map.find(cell_key_to_search) == end(search_map)) {\n                continue;\n            }\n            auto &point_keys = search_map.at(cell_key_to_search);\n            for(auto other_point_key : point_keys) {\n                auto other_point =\n                        dataset_adaptor.get_point(other_point_key);\n                double distance2 = (vec_pnt - other_point).squaredNorm();\n                if(distance2 < search_radius_2) {\n                    func(other_point_key);\n                    neighbours_found++;\n                }\n            }\n        }\n        return neighbours_found;\n    }\n\n    /**\n     * @brief find_nn_vec finds like find_neighbours_vec, but\n     * nearest neigbour, which is in search radius\n     * @param vec_pnt\n     * @param neighbours\n     * @return\n     */\n    size_t find_nn_vec(Vector2d const &vec_pnt,\n                       vector<key_t> &neighbours) {\n        auto cell_coords =\n                GridPoint::to_coordinates(vec_pnt, cell_size);\n        size_t neighbours_found = 0;\n        neighbours.resize(1);\n        double min_distance = std::numeric_limits<double>::infinity();\n        get_cell_keys_in_range(vec_pnt, cell_keys_to_search);\n        // now search all cells ( maximum 4 cells are searched)\n        for(auto cell_key_to_search : cell_keys_to_search) {\n            if(search_map.find(cell_key_to_search) == end(search_map)) {\n                continue;\n            }\n            auto &point_keys = search_map.at(cell_key_to_search);\n            for(auto other_point_key : point_keys) {\n                if(points_index.find(other_point_key) == points_index.end()){\n                    continue;\n                }\n                auto other_point =\n                        dataset_adaptor.get_point(other_point_key);\n                double distance2 = (vec_pnt - other_point).squaredNorm();\n                if(distance2 < search_radius_2) {\n                    if(distance2 < min_distance) {\n                        min_distance = distance2;\n                        neighbours[0] = other_point_key;\n                        neighbours_found = 1;\n                    }\n                }\n            }\n        }\n        if(!neighbours_found) {\n            neighbours.clear();\n        }\n        return neighbours_found;\n    }\n\n\n    /**\n      *\n      * @brief inserts all points and calaculates adj_matrix\n      */\n    void calculate_adj_matrix(unordered_map<key_t, vector<key_t>> &adj_matrix) {\n        insert_all();\n        auto num_points = points_index.size();\n        adj_matrix.max_load_factor(0.5);\n        adj_matrix.reserve(num_points);\n        dataset_adaptor.for_all_keys([&](key_t key) {\n            find_neighbours(key, adj_matrix[key]);\n        });\n    }\n\n    /**\n     * @brief insert_point inserts the point in the seach_map,\n     * the point is referenced by key, this means in must be first\n     * have inserted in the underlying datastructure provided by\n     * DatasetAdaptor\n     * @param point_key\n     * @return true if inserted\n     */\n    void insert_point(key_t point_key) {\n        auto vec_pnt = dataset_adaptor.get_point(point_key);\n        auto cell_coords =\n                GridPoint::to_coordinates(vec_pnt, cell_size);\n        auto cell_key = GridPoint::pack_key(cell_coords);\n        if(search_map.find(cell_key) == end(search_map)) {\n            auto set_to_insert = cell_t(initial_cell_size);\n            set_to_insert.max_load_factor(.5f);\n            search_map.emplace(cell_key, set_to_insert);\n        }\n        search_map.at(cell_key).insert(point_key);\n        points_index.insert(point_key);\n    }\n\n    /**\n     * @brief insert_all inserts all points currently in the\n     * dataset\n     */\n    void insert_all() {\n        points_index.reserve(dataset_adaptor.size());\n        dataset_adaptor.for_all_keys([&](key_t key) {\n            insert_point(key);\n        });\n    }\n\n    /**\n     * @brief delete_point deleted point must be available\n     * while deleting, it can be deleted only\n     * aftewards from the underlying datastructure provided by\n     * DatasetAdaptor\n     * @param point_key\n     * @return true if deleted\n     */\n    bool delete_point(key_t point_key) {\n        if(!dataset_adaptor.find_point(point_key)) {\n            return false;\n        }\n        auto vec_pnt = dataset_adaptor.get_point(point_key);\n        auto cell_key = GridPoint::to_key(vec_pnt, cell_size);\n        auto &points = search_map.at(cell_key);\n        points.erase(point_key);\n        points_index.erase(point_key);\n        if(points.empty()) {\n            search_map.erase(cell_key);\n        }\n        return true;\n    }\n\n    /**\n     * @brief get_cell_keys_in_range gets all cells on which\n     * a circle with diameter cell_size and the center vec_pnt\n     * lays\n     * @param vec_pnt the point which is the center\n     * @param OUT keys of these cells\n     *\n     */\n    void get_cell_keys_in_range(Vector2d const &vec_pnt,\n                                vector<key_t> &keys) {\n        keys.clear();\n        auto cell_coords =\n                GridPoint::to_coordinates(vec_pnt, cell_size);\n        keys.push_back(GridPoint::pack_key(cell_coords));\n        // offset of this point from center\n        double const half_cell_size = cell_size / 2.;\n        double row_d = vec_pnt.x();\n        double column_d = vec_pnt.y();\n        double row_offset = fmod(row_d, cell_size);\n        double column_offset = fmod(column_d, cell_size);\n        auto fourth_point = cell_coords;\n        if(row_offset < 0) {\n            row_offset += cell_size;\n        }\n        if(column_offset < 0) {\n            column_offset += cell_size;\n        }\n        // to jump from -1 to 1 evtl, as\n        // 0 is not used as row and column\n        if(row_offset < half_cell_size) {\n            if(cell_coords.row == 1) {\n                fourth_point.row -= 2;\n                keys.push_back(GridPoint::pack_key(coords(cell_coords.row - 2,\n                                                          cell_coords.column)));\n            } else {\n                fourth_point.row -= 1;\n                keys.push_back(GridPoint::pack_key(coords(cell_coords.row - 1,\n                                                          cell_coords.column)));\n            }\n        } else if(row_offset > half_cell_size) {\n            if(cell_coords.row == -1) {\n                fourth_point.row += 2;\n                keys.push_back(GridPoint::pack_key(coords(cell_coords.row + 2,\n                                                          cell_coords.column)));\n            } else {\n                fourth_point.row += 1;\n                keys.push_back(GridPoint::pack_key(coords(cell_coords.row + 1,\n                                                          cell_coords.column)));\n            }\n        }\n        if(column_offset < half_cell_size) {\n            if(cell_coords.column == 1) {\n                fourth_point.column -= 2;\n                keys.push_back(GridPoint::pack_key(coords(cell_coords.row,\n                                                          cell_coords.column - 2)));\n            } else {\n                fourth_point.column -= 1;\n                keys.push_back(GridPoint::pack_key(coords(cell_coords.row,\n                                                          cell_coords.column - 1)));\n            }\n        } else if(column_offset > half_cell_size) {\n            if(cell_coords.column == -1) {\n                fourth_point.column += 2;\n                keys.push_back(GridPoint::pack_key(coords(cell_coords.row,\n                                                          cell_coords.column + 2)));\n            } else {\n                fourth_point.column += 1;\n                keys.push_back(GridPoint::pack_key(coords(cell_coords.row,\n                                                          cell_coords.column + 1)));\n            }\n        }\n\n        if(keys.size() == 3) {\n            keys.push_back(GridPoint::pack_key(fourth_point));\n        }\n    }\n\n    /**\n     * @brief get_points_index\n     * @return\n     */\n    cell_t const &get_points_index() const {\n        return points_index;\n    }\n\n    void set_initial_neighbours_size(size_t value) {\n        initial_neighbours_size = value;\n    }\n\n    /**\n     * @brief clear clears the whole shrs map, but not the\n     * undelying data structure\n     */\n    void clear() {\n        points_index.clear();\n        search_map.clear();\n    }\n\n    void delete_from_index(key_t idx) {\n        points_index.erase(idx);\n    }\n\nprotected:\n    /**\n     * @brief initial_cell_size initial size to reserve\n     * on a new cell when constructing\n     */\n    size_t initial_cell_size = 7;\n\n    /**\n     * @brief initial_neighbours_size initial size to\n     * allocate for neigbours\n     */\n    size_t initial_neighbours_size = 5;\n\n    /**\n     * @brief search_map\n     */\n    search_map_t search_map;\n\n    /**\n     * @brief dataset_adaptor\n     */\n    DatasetAdaptor dataset_adaptor;\n\n    /**\n     * @brief cell_size\n     */\n    double cell_size;\n\n    /**\n     * @brief search_radius\n     */\n    double search_radius;\n\n    /**\n     * @brief search_radius_2 squared_search_radius\n     */\n    double search_radius_2;\n\n    /**\n     * @brief cells_to_search cells to search on\n     * radius query, memebr to avoid realocation\n     */\n    vector<key_t> cell_keys_to_search;\n\n    /**\n     * @brief points_index which points are saved\n     * in the shrs grid\n     */\n    cell_t points_index;\n\n};\n\n} // end namespace fsd\n\n#endif\n", "meta": {"hexsha": "2e825ffe6aeb6f83e5955f2e73941a0d048aeae8", "size": 14470, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/shrs/SHRS.hpp", "max_stars_repo_name": "iv461/spatial_hashing", "max_stars_repo_head_hexsha": "639295a47e74285046c9a15e6c37039916901ae3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-26T23:16:37.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-26T23:16:37.000Z", "max_issues_repo_path": "include/shrs/SHRS.hpp", "max_issues_repo_name": "iv461/spatial_hashing", "max_issues_repo_head_hexsha": "639295a47e74285046c9a15e6c37039916901ae3", "max_issues_repo_licenses": ["MIT"], "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/shrs/SHRS.hpp", "max_forks_repo_name": "iv461/spatial_hashing", "max_forks_repo_head_hexsha": "639295a47e74285046c9a15e6c37039916901ae3", "max_forks_repo_licenses": ["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.2991071429, "max_line_length": 84, "alphanum_fraction": 0.5715272979, "num_tokens": 3125, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.4839044065327234}}
{"text": "/*\n * Copyright 2012-2019 CNRS-UM LIRMM, CNRS-AIST JRL\n */\n\n// includes\n// std\n#include <iostream>\n\n// boost\n#define BOOST_TEST_MODULE CoMTest\n#include <boost/math/constants/constants.hpp>\n#include <boost/test/unit_test.hpp>\n\n// SpaceVecAlg\n#include <SpaceVecAlg/SpaceVecAlg>\n\n// RBDyn\n#include \"RBDyn/CoM.h\"\n#include \"RBDyn/EulerIntegration.h\"\n#include \"RBDyn/FA.h\"\n#include \"RBDyn/FK.h\"\n#include \"RBDyn/FV.h\"\n#include \"RBDyn/MultiBody.h\"\n#include \"RBDyn/MultiBodyConfig.h\"\n#include \"RBDyn/MultiBodyGraph.h\"\n\n// arm\n#include \"XYZarm.h\"\n\nconst double TOL = 0.000001;\n\nstd::tuple<rbd::MultiBody, rbd::MultiBodyConfig, rbd::MultiBodyGraph> makeXYZSarmRandomCoM(bool isFixed = true)\n{\n  using namespace Eigen;\n  using namespace sva;\n  using namespace rbd;\n\n  typedef Eigen::Matrix<double, 1, 1> EScalar;\n\n  MultiBodyGraph mbg;\n\n  double mass = 1.;\n  Matrix3d I = Matrix3d::Identity();\n  Vector3d h = Vector3d::Random();\n\n  RBInertiad rbi(mass, h, I);\n\n  Body b0(RBInertiad((fabs(EScalar::Random()(0)) + 1e-8) * 10., h, I), \"b0\");\n  Body b1(RBInertiad((fabs(EScalar::Random()(0)) + 1e-8) * 10., h, I), \"b1\");\n  Body b2(RBInertiad((fabs(EScalar::Random()(0)) + 1e-8) * 10., h, I), \"b2\");\n  Body b3(RBInertiad((fabs(EScalar::Random()(0)) + 1e-8) * 10., h, I), \"b3\");\n  Body b4(RBInertiad((fabs(EScalar::Random()(0)) + 1e-8) * 10., h, I), \"b4\");\n\n  mbg.addBody(b0);\n  mbg.addBody(b1);\n  mbg.addBody(b2);\n  mbg.addBody(b3);\n  mbg.addBody(b4);\n\n  Joint j0(Joint::RevX, true, \"j0\");\n  Joint j1(Joint::RevY, true, \"j1\");\n  Joint j2(Joint::RevZ, true, \"j2\");\n  Joint j3(Joint::Spherical, true, \"j3\");\n\n  mbg.addJoint(j0);\n  mbg.addJoint(j1);\n  mbg.addJoint(j2);\n  mbg.addJoint(j3);\n\n  //                b4\n  //             j3 | Spherical\n  //  Root     j0   |   j1     j2\n  //  ---- b0 ---- b1 ---- b2 ----b3\n  //  Fixed    RevX   RevY    RevZ\n\n  PTransformd to(Vector3d(0., 0.5, 0.));\n  PTransformd from(Vector3d(0., -0.5, 0.));\n\n  mbg.linkBodies(\"b0\", to, \"b1\", from, \"j0\");\n  mbg.linkBodies(\"b1\", to, \"b2\", from, \"j1\");\n  mbg.linkBodies(\"b2\", to, \"b3\", from, \"j2\");\n  mbg.linkBodies(\"b1\", PTransformd(Vector3d(0.5, 0., 0.)), \"b4\", PTransformd(Vector3d(-0.5, 0., 0.)), \"j3\");\n\n  MultiBody mb = mbg.makeMultiBody(\"b0\", isFixed);\n\n  MultiBodyConfig mbc(mb);\n  mbc.zero(mb);\n\n  return std::make_tuple(mb, mbc, mbg);\n}\n\nBOOST_AUTO_TEST_CASE(computeCoMTest)\n{\n  using namespace Eigen;\n  using namespace sva;\n  using namespace rbd;\n  namespace cst = boost::math::constants;\n\n  MultiBodyGraph mbg;\n\n  double mass = 1.;\n  Matrix3d I = Matrix3d::Identity();\n  Vector3d h = Vector3d::Zero();\n  Vector6d v = Vector6d::Zero();\n\n  RBInertiad rbi(mass, h, I);\n\n  Body b0(rbi, \"b0\");\n  Body b1(rbi, \"b1\");\n  Body b2(RBInertiad(2., h, I), \"b2\");\n  Body b3(rbi, \"b3\");\n\n  mbg.addBody(b0);\n  mbg.addBody(b1);\n  mbg.addBody(b2);\n  mbg.addBody(b3);\n\n  Joint j0(Joint::RevX, true, \"j0\");\n  Joint j1(Joint::RevY, true, \"j1\");\n  Joint j2(Joint::RevZ, true, \"j2\");\n\n  mbg.addJoint(j0);\n  mbg.addJoint(j1);\n  mbg.addJoint(j2);\n\n  //  Root     j0      j1     j2\n  //  ---- b0 ---- b1 ---- b2 ----b3\n  //  Fixed    RevX   RevY    RevZ\n\n  PTransformd to(Vector3d(0., 0.5, 0.));\n  PTransformd from(Vector3d(0., 0., 0.));\n\n  mbg.linkBodies(\"b0\", to, \"b1\", from, \"j0\");\n  mbg.linkBodies(\"b1\", to, \"b2\", from, \"j1\");\n  mbg.linkBodies(\"b2\", to, \"b3\", from, \"j2\");\n\n  MultiBody mb = mbg.makeMultiBody(\"b0\", true);\n  MultiBodyConfig mbc(mb);\n  mbc.zero(mb);\n\n  mbc.q = {{}, {0.}, {0.}, {0.}};\n\n  forwardKinematics(mb, mbc);\n  forwardVelocity(mb, mbc);\n  forwardAcceleration(mb, mbc);\n\n  Vector3d CoM = computeCoM(mb, mbc);\n  Vector3d CoMV = computeCoMVelocity(mb, mbc);\n  Vector3d CoMA = computeCoMAcceleration(mb, mbc);\n\n  double handCoMX = 0.;\n  double handCoMY = (0.5 * 1. + 1. * 2. + 1.5 * 1.) / 5.;\n  double handCoMZ = 0.;\n  BOOST_CHECK_EQUAL(CoM, Vector3d(handCoMX, handCoMY, handCoMZ));\n  BOOST_CHECK_EQUAL(CoMV, Vector3d::Zero());\n  BOOST_CHECK_EQUAL(CoMA, Vector3d::Zero());\n\n  mbc.q = {{}, {cst::pi<double>() / 2.}, {0.}, {0.}};\n  forwardKinematics(mb, mbc);\n  forwardVelocity(mb, mbc);\n  forwardAcceleration(mb, mbc);\n\n  CoM = sComputeCoM(mb, mbc);\n  CoMV = sComputeCoMVelocity(mb, mbc);\n  CoMA = computeCoMAcceleration(mb, mbc);\n\n  handCoMX = 0.;\n  handCoMY = (0.5 * 1. + 0.5 * 2 + 0.5 * 1.) / 5.;\n  handCoMZ = (0.5 * 2. + 1. * 1.) / 5.;\n\n  BOOST_CHECK_EQUAL(CoM, Vector3d(handCoMX, handCoMY, handCoMZ));\n  BOOST_CHECK_EQUAL(CoMV, Vector3d::Zero());\n  BOOST_CHECK_EQUAL(CoMA, Vector3d::Zero());\n\n  // test safe version\n  mbc.bodyPosW = {I, I, I};\n  BOOST_CHECK_THROW(sComputeCoM(mb, mbc), std::domain_error);\n  BOOST_CHECK_THROW(sComputeCoMVelocity(mb, mbc), std::domain_error);\n  BOOST_CHECK_THROW(sComputeCoMAcceleration(mb, mbc), std::domain_error);\n\n  mbc.bodyPosW = {I, I, I, I};\n  mbc.bodyVelB = {v, v, v};\n  mbc.bodyAccB = {v, v, v};\n  BOOST_CHECK_NO_THROW(sComputeCoM(mb, mbc));\n  BOOST_CHECK_THROW(sComputeCoMVelocity(mb, mbc), std::domain_error);\n  BOOST_CHECK_THROW(sComputeCoMAcceleration(mb, mbc), std::domain_error);\n}\n\nEigen::Vector3d makeCoMDotFromStep(const rbd::MultiBody & mb, const rbd::MultiBodyConfig & mbc)\n{\n  using namespace Eigen;\n  using namespace rbd;\n\n  double step = 1e-8;\n\n  MultiBodyConfig mbcTmp(mbc);\n\n  Vector3d oC = computeCoM(mb, mbcTmp);\n  eulerIntegration(mb, mbcTmp, step);\n  forwardKinematics(mb, mbcTmp);\n  forwardVelocity(mb, mbcTmp);\n  Vector3d nC = computeCoM(mb, mbcTmp);\n\n  return (nC - oC) / step;\n}\n\nEigen::MatrixXd makeJDotFromStep(const rbd::MultiBody & mb,\n                                 const rbd::MultiBodyConfig & mbc,\n                                 rbd::CoMJacobianDummy & jac)\n{\n  using namespace Eigen;\n  using namespace sva;\n  using namespace rbd;\n\n  double step = 1e-8;\n\n  MultiBodyConfig mbcTmp(mbc);\n\n  MatrixXd oJ = jac.jacobian(mb, mbcTmp);\n  eulerIntegration(mb, mbcTmp, step);\n  forwardKinematics(mb, mbcTmp);\n  forwardVelocity(mb, mbcTmp);\n  MatrixXd nJ = jac.jacobian(mb, mbcTmp);\n\n  return (nJ - oJ) / step;\n}\n\nBOOST_AUTO_TEST_CASE(CoMJacobianDummyTest)\n{\n  using namespace Eigen;\n  using namespace sva;\n  using namespace rbd;\n  namespace cst = boost::math::constants;\n\n  sva::PTransformd I(sva::PTransformd::Identity());\n\n  MultiBodyGraph mbg;\n  MultiBody mb;\n  MultiBodyConfig mbc;\n\n  std::tie(mb, mbc, mbg) = makeXYZSarmRandomCoM();\n\n  CoMJacobianDummy comJac(mb);\n\n  /**\n   *\t\t\t\t\t\tTest jacobian with the com speed get by differentiation.\n   *\t\t\t\t\t\tAlso test computeCoMVelocity and computeCoMAcceleration.\n   */\n\n  mbc.q = {{}, {0.}, {0.}, {0.}, {1., 0., 0., 0.}};\n  mbc.alpha = {{}, {0.}, {0.}, {0.}, {0., 0., 0.}};\n  mbc.alphaD = {{}, {0.}, {0.}, {0.}, {0., 0., 0.}};\n\n  forwardKinematics(mb, mbc);\n\n  auto testJacCoMVelAcc = [](const rbd::MultiBody & mb, rbd::MultiBodyConfig & mbc, rbd::CoMJacobianDummy & comJac) {\n    forwardVelocity(mb, mbc);\n    forwardAcceleration(mb, mbc);\n\n    Vector3d CoMVel = computeCoMVelocity(mb, mbc);\n    Vector3d CoMAcc = computeCoMAcceleration(mb, mbc);\n    Vector3d CDot_diff = makeCoMDotFromStep(mb, mbc);\n    MatrixXd CJac = comJac.jacobian(mb, mbc);\n    MatrixXd CJacDot = comJac.jacobianDot(mb, mbc);\n\n    BOOST_CHECK_EQUAL(CJac.rows(), 3);\n    BOOST_CHECK_EQUAL(CJac.cols(), mb.nrDof());\n\n    VectorXd alpha = dofToVector(mb, mbc.alpha);\n    VectorXd alphaD = dofToVector(mb, mbc.alphaD);\n\n    Vector3d CDot = CJac * alpha;\n    Vector3d CDotDot = CJac * alphaD + CJacDot * alpha;\n\n    BOOST_CHECK_SMALL((CDot_diff - CDot).norm(), TOL);\n    BOOST_CHECK_SMALL((CDot_diff - CoMVel).norm(), TOL);\n    BOOST_CHECK_SMALL((CDotDot - CoMAcc).norm(), TOL);\n  };\n\n  for(int i = 0; i < mb.nrJoints(); ++i)\n  {\n    for(int j = 0; j < mb.joint(i).dof(); ++j)\n    {\n      mbc.alpha[i][j] = 1.;\n      mbc.alphaD[i][j] = 1.;\n\n      testJacCoMVelAcc(mb, mbc, comJac);\n\n      mbc.alpha[i][j] = 0.;\n      mbc.alphaD[i][j] = 0.;\n    }\n  }\n\n  for(int i = 0; i < mb.nrJoints(); ++i)\n  {\n    for(int j = 0; j < mb.joint(i).dof(); ++j)\n    {\n      mbc.alpha[i][j] = 1.;\n      mbc.alphaD[i][j] = 1.;\n\n      testJacCoMVelAcc(mb, mbc, comJac);\n    }\n  }\n  mbc.alpha = {{}, {0.}, {0.}, {0.}, {0., 0., 0.}};\n  mbc.alphaD = {{}, {0.}, {0.}, {0.}, {0., 0., 0.}};\n\n  /**\n   * Same test but with a different q.\n   */\n\n  Quaterniond q;\n  q = AngleAxisd(cst::pi<double>() / 8., Vector3d::UnitZ());\n  mbc.q = {{}, {0.4}, {0.2}, {-0.1}, {q.w(), q.x(), q.y(), q.z()}};\n  forwardKinematics(mb, mbc);\n\n  for(int i = 0; i < mb.nrJoints(); ++i)\n  {\n    for(int j = 0; j < mb.joint(i).dof(); ++j)\n    {\n      mbc.alpha[i][j] = 1.;\n      mbc.alphaD[i][j] = 1.;\n\n      testJacCoMVelAcc(mb, mbc, comJac);\n\n      mbc.alpha[i][j] = 0.;\n      mbc.alphaD[i][j] = 0.;\n    }\n  }\n\n  for(int i = 0; i < mb.nrJoints(); ++i)\n  {\n    for(int j = 0; j < mb.joint(i).dof(); ++j)\n    {\n      mbc.alpha[i][j] = 1.;\n      mbc.alphaD[i][j] = 1.;\n\n      testJacCoMVelAcc(mb, mbc, comJac);\n    }\n  }\n  mbc.alphaD = {{}, {0.}, {0.}, {0.}, {0., 0., 0.}};\n\n  // test safe functions\n\n  mbc.bodyPosW = {I, I, I};\n  BOOST_CHECK_THROW(comJac.sJacobian(mb, mbc), std::domain_error);\n  mbc = MultiBodyConfig(mb);\n\n  /**\n   *\t\t\t\t\t\tTest jacobianDot with the jacobianDot get by differentiation.\n   */\n\n  mbc.q = {{}, {0.}, {0.}, {0.}, {1., 0., 0., 0.}};\n  mbc.alpha = {{}, {0.}, {0.}, {0.}, {0., 0., 0.}};\n  mbc.alphaD = {{}, {0.}, {0.}, {0.}, {0., 0., 0.}};\n\n  forwardKinematics(mb, mbc);\n\n  for(int i = 0; i < mb.nrJoints(); ++i)\n  {\n    for(int j = 0; j < mb.joint(i).dof(); ++j)\n    {\n      mbc.alpha[i][j] = 1.;\n      forwardVelocity(mb, mbc);\n      forwardAcceleration(mb, mbc);\n\n      MatrixXd jacDot_diff = makeJDotFromStep(mb, mbc, comJac);\n      MatrixXd jacDot = comJac.jacobianDot(mb, mbc);\n\n      BOOST_CHECK_EQUAL(jacDot.rows(), 3);\n      BOOST_CHECK_EQUAL(jacDot.cols(), mb.nrDof());\n\n      BOOST_CHECK_SMALL((jacDot_diff - jacDot).norm(), TOL);\n      mbc.alpha[i][j] = 0.;\n    }\n  }\n\n  for(int i = 0; i < mb.nrJoints(); ++i)\n  {\n    for(int j = 0; j < mb.joint(i).dof(); ++j)\n    {\n      mbc.alpha[i][j] = 1.;\n      forwardVelocity(mb, mbc);\n      forwardAcceleration(mb, mbc);\n\n      MatrixXd jacDot_diff = makeJDotFromStep(mb, mbc, comJac);\n      MatrixXd jacDot = comJac.jacobianDot(mb, mbc);\n\n      BOOST_CHECK_EQUAL(jacDot.rows(), 3);\n      BOOST_CHECK_EQUAL(jacDot.cols(), mb.nrDof());\n\n      BOOST_CHECK_SMALL((jacDot_diff - jacDot).norm(), TOL);\n      mbc.alpha[i][j] = 0.;\n    }\n  }\n  mbc.alpha = {{}, {0.}, {0.}, {0.}, {0., 0., 0.}};\n\n  /**\n   * Same test but with a different q.\n   */\n\n  q = AngleAxisd(cst::pi<double>() / 8., Vector3d::UnitZ());\n  mbc.q = {{}, {0.4}, {0.2}, {-0.1}, {q.w(), q.x(), q.y(), q.z()}};\n  forwardKinematics(mb, mbc);\n\n  for(int i = 0; i < mb.nrJoints(); ++i)\n  {\n    for(int j = 0; j < mb.joint(i).dof(); ++j)\n    {\n      mbc.alpha[i][j] = 1.;\n      forwardVelocity(mb, mbc);\n      forwardAcceleration(mb, mbc);\n\n      MatrixXd jacDot_diff = makeJDotFromStep(mb, mbc, comJac);\n      MatrixXd jacDot = comJac.jacobianDot(mb, mbc);\n\n      BOOST_CHECK_EQUAL(jacDot.rows(), 3);\n      BOOST_CHECK_EQUAL(jacDot.cols(), mb.nrDof());\n\n      BOOST_CHECK_SMALL((jacDot_diff - jacDot).norm(), TOL);\n      mbc.alpha[i][j] = 0.;\n    }\n  }\n\n  for(int i = 0; i < mb.nrJoints(); ++i)\n  {\n    for(int j = 0; j < mb.joint(i).dof(); ++j)\n    {\n      mbc.alpha[i][j] = 1.;\n      forwardVelocity(mb, mbc);\n      forwardAcceleration(mb, mbc);\n\n      MatrixXd jacDot_diff = makeJDotFromStep(mb, mbc, comJac);\n      MatrixXd jacDot = comJac.jacobianDot(mb, mbc);\n\n      BOOST_CHECK_EQUAL(jacDot.rows(), 3);\n      BOOST_CHECK_EQUAL(jacDot.cols(), mb.nrDof());\n\n      BOOST_CHECK_SMALL((jacDot_diff - jacDot).norm(), TOL);\n      mbc.alpha[i][j] = 0.;\n    }\n  }\n  mbc.alpha = {{}, {0.}, {0.}, {0.}, {0., 0., 0.}};\n\n  // test safe functions\n\n  mbc.bodyPosW = {I, I, I};\n  BOOST_CHECK_THROW(comJac.sJacobianDot(mb, mbc), std::domain_error);\n  mbc = MultiBodyConfig(mb);\n\n  MotionVecd mv;\n  mbc.bodyVelB = {mv, mv, mv};\n  BOOST_CHECK_THROW(comJac.sJacobianDot(mb, mbc), std::domain_error);\n  mbc = MultiBodyConfig(mb);\n\n  mbc.bodyVelW = {mv, mv, mv};\n  BOOST_CHECK_THROW(comJac.sJacobianDot(mb, mbc), std::domain_error);\n  mbc = MultiBodyConfig(mb);\n}\n\nBOOST_AUTO_TEST_CASE(CoMJacobianTest)\n{\n  using namespace Eigen;\n  using namespace sva;\n  using namespace rbd;\n  namespace cst = boost::math::constants;\n\n  MultiBodyGraph mbg;\n  MultiBody mb;\n  MultiBodyConfig mbc;\n\n  std::tie(mb, mbc, mbg) = makeXYZSarmRandomCoM();\n\n  std::vector<double> weight(mb.nrBodies());\n  for(std::size_t i = 0; i < weight.size(); ++i)\n  {\n    weight[i] = Eigen::Matrix<double, 1, 1>::Random()(0);\n  }\n\n  CoMJacobian comJac(mb, weight);\n  CoMJacobianDummy comJacDummy(mb, weight);\n\n  rbd::forwardKinematics(mb, mbc);\n  rbd::forwardVelocity(mb, mbc);\n\n  // test jacobian\n  MatrixXd jacMat = comJac.jacobian(mb, mbc);\n  MatrixXd jacDummyMat = comJacDummy.jacobian(mb, mbc);\n\n  BOOST_CHECK_EQUAL(jacMat.rows(), 3);\n  BOOST_CHECK_EQUAL(jacMat.cols(), mb.nrDof());\n\n  BOOST_CHECK_SMALL((jacMat - jacDummyMat).norm(), TOL);\n\n  // change configuration\n  Quaterniond q;\n  q = AngleAxisd(cst::pi<double>() / 8., Vector3d::UnitZ());\n  mbc.q = {{}, {0.4}, {0.2}, {-0.1}, {q.w(), q.x(), q.y(), q.z()}};\n  forwardKinematics(mb, mbc);\n\n  jacMat = comJac.jacobian(mb, mbc);\n  jacDummyMat = comJacDummy.jacobian(mb, mbc);\n\n  BOOST_CHECK_SMALL((jacMat - jacDummyMat).norm(), TOL);\n\n  // Test jacobianDot\n\n  for(int i = 0; i < mb.nrJoints(); ++i)\n  {\n    for(int j = 0; j < mb.joint(i).dof(); ++j)\n    {\n      mbc.alpha[i][j] = 1.;\n      forwardVelocity(mb, mbc);\n\n      MatrixXd jacDotMat = comJac.jacobianDot(mb, mbc);\n      MatrixXd jacDotDummyMat = comJacDummy.jacobianDot(mb, mbc);\n\n      BOOST_CHECK_EQUAL(jacDotMat.rows(), 3);\n      BOOST_CHECK_EQUAL(jacDotMat.cols(), mb.nrDof());\n\n      BOOST_CHECK_SMALL((jacDotMat - jacDotDummyMat).norm(), TOL);\n      mbc.alpha[i][j] = 0.;\n    }\n  }\n\n  for(int i = 0; i < mb.nrJoints(); ++i)\n  {\n    for(int j = 0; j < mb.joint(i).dof(); ++j)\n    {\n      mbc.alpha[i][j] = 1.;\n      forwardVelocity(mb, mbc);\n\n      MatrixXd jacDotMat = comJac.jacobianDot(mb, mbc);\n      MatrixXd jacDotDummyMat = comJacDummy.jacobianDot(mb, mbc);\n\n      BOOST_CHECK_EQUAL(jacDotMat.rows(), 3);\n      BOOST_CHECK_EQUAL(jacDotMat.cols(), mb.nrDof());\n\n      BOOST_CHECK_SMALL((jacDotMat - jacDotDummyMat).norm(), TOL);\n    }\n  }\n\n  // Test velocity and normal acceleration function\n  for(int i = 0; i < 50; ++i)\n  {\n    Eigen::VectorXd q(mb.nrParams()), alpha(mb.nrDof());\n    q.setRandom();\n    alpha.setRandom();\n    // normalize free flyier and spherical joint\n    q.head<4>().normalize();\n    q.segment(mb.jointPosInParam(mb.jointIndexByName(\"j3\")), 4).normalize();\n    rbd::vectorToParam(q, mbc.q);\n    rbd::vectorToParam(alpha, mbc.alpha);\n    forwardKinematics(mb, mbc);\n    forwardVelocity(mb, mbc);\n    // calcul the normal acceleration since alphaD is zero\n    forwardAcceleration(mb, mbc);\n\n    // test com velocity\n    const MatrixXd & comJacMat = comJac.jacobian(mb, mbc);\n    Vector3d velFromJac = comJacMat * alpha;\n    Vector3d velFromMbc = comJac.velocity(mb, mbc);\n\n    BOOST_CHECK_SMALL((velFromJac - velFromMbc).norm(), TOL);\n\n    // test com normal acceleration\n    const MatrixXd & comJacDotMat = comJac.jacobianDot(mb, mbc);\n    Vector3d normalAccFromJac = comJacDotMat * alpha;\n    Vector3d normalAccFromMbc1 = comJac.normalAcceleration(mb, mbc);\n    Vector3d normalAccFromMbc2 = comJac.normalAcceleration(mb, mbc, mbc.bodyAccB);\n\n    BOOST_CHECK_SMALL((normalAccFromJac - normalAccFromMbc1).norm(), TOL);\n    BOOST_CHECK_SMALL((normalAccFromJac - normalAccFromMbc2).norm(), TOL);\n  }\n\n  // create a multibody with new inertial parameter to test updateInertialParameters\n  std::tie(mb, mbc, mbg) = makeXYZSarmRandomCoM();\n\n  MultiBodyGraph badMbg;\n  MultiBody badMb;\n  MultiBodyConfig badMbc;\n  std::tie(badMb, badMbc, badMbg) = makeXYZarm();\n\n  BOOST_CHECK_THROW(comJac.sUpdateInertialParameters(badMb), std::domain_error);\n  BOOST_CHECK_NO_THROW(comJac.sUpdateInertialParameters(mb));\n  CoMJacobianDummy comJacDummyUpdated(mb, weight);\n\n  rbd::forwardKinematics(mb, mbc);\n  rbd::forwardVelocity(mb, mbc);\n\n  // test jacobian with updated model\n  jacMat = comJac.jacobian(mb, mbc);\n  jacDummyMat = comJacDummyUpdated.jacobian(mb, mbc);\n  BOOST_CHECK_SMALL((jacMat - jacDummyMat).norm(), TOL);\n\n  // test weight getter/setter\n  std::vector<double> weight2 = comJac.weight();\n  BOOST_CHECK_EQUAL_COLLECTIONS(weight.begin(), weight.end(), weight2.begin(), weight2.end());\n\n  for(std::size_t i = 0; i < weight2.size(); ++i)\n  {\n    weight2[i] += 10.;\n  }\n\n  comJac.weight(mb, weight2);\n  BOOST_CHECK_EQUAL_COLLECTIONS(weight2.begin(), weight2.end(), comJac.weight().begin(), comJac.weight().end());\n\n  CoMJacobianDummy comJacDummyWeight2(mb, weight2);\n  // test jacobian with new weight\n  jacMat = comJac.jacobian(mb, mbc);\n  jacDummyMat = comJacDummyWeight2.jacobian(mb, mbc);\n  BOOST_CHECK_SMALL((jacMat - jacDummyMat).norm(), TOL);\n}\n", "meta": {"hexsha": "ba536600c3bb0a7231dc78c6b488bc02d7556c88", "size": 16881, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/CoMTest.cpp", "max_stars_repo_name": "dbdxnuliba/RBDyn-provides-a-set-of-classes-and-functions-to-model-the-dynamics-of-rigid-body-systems.", "max_stars_repo_head_hexsha": "c3f498f8330e06be7dae55570d00931702b920d6", "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": "tests/CoMTest.cpp", "max_issues_repo_name": "dbdxnuliba/RBDyn-provides-a-set-of-classes-and-functions-to-model-the-dynamics-of-rigid-body-systems.", "max_issues_repo_head_hexsha": "c3f498f8330e06be7dae55570d00931702b920d6", "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": "tests/CoMTest.cpp", "max_forks_repo_name": "dbdxnuliba/RBDyn-provides-a-set-of-classes-and-functions-to-model-the-dynamics-of-rigid-body-systems.", "max_forks_repo_head_hexsha": "c3f498f8330e06be7dae55570d00931702b920d6", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5383360522, "max_line_length": 117, "alphanum_fraction": 0.619216871, "num_tokens": 5892, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.4839043919060112}}
{"text": "// MIT License\n//\n// Copyright (c) 2018 Michal Siedlaczek\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/// \\file\n/// \\author Michal Siedlaczek\n/// \\copyright MIT License\n\n#pragma once\n\n#include <algorithm>\n#include <cmath>\n#include <functional>\n#include <numeric>\n#include <vector>\n\n#include <boost/math/distributions/gamma.hpp>\n\nnamespace taily {\n\nstruct Feature_Statistics {\n    static constexpr std::size_t struct_size = 2 * sizeof(double) + sizeof(int);\n    double expected_value;\n    double variance;\n    std::int64_t frequency;\n\n    [[nodiscard]] constexpr auto\n    operator+(Feature_Statistics const& other) const -> Feature_Statistics\n    {\n        return Feature_Statistics{expected_value + other.expected_value,\n                                  variance + other.variance,\n                                  frequency + other.frequency};\n    }\n\n    auto to_stream(std::ostream& os) const -> std::ostream&\n    {\n        os.write(reinterpret_cast<const char*>(&expected_value), sizeof(expected_value));\n        os.write(reinterpret_cast<const char*>(&variance), sizeof(variance));\n        os.write(reinterpret_cast<const char*>(&frequency), sizeof(frequency));\n        return os;\n    }\n\n    [[nodiscard]] static auto from_stream(std::istream& is) -> Feature_Statistics\n    {\n        Feature_Statistics stats;\n        is.read(reinterpret_cast<char*>(&stats.expected_value), sizeof(stats.expected_value));\n        is.read(reinterpret_cast<char*>(&stats.variance), sizeof(stats.variance));\n        is.read(reinterpret_cast<char*>(&stats.frequency), sizeof(stats.frequency));\n        return stats;\n    }\n\n    template<typename Feature_Range>\n    [[nodiscard]] static constexpr auto\n    from_features(Feature_Range const& features) -> Feature_Statistics\n    {\n        return from_features(std::begin(features), std::end(features));\n    }\n\n    template<typename Forward_Iterator>\n    [[nodiscard]] static constexpr auto\n    from_features(Forward_Iterator first, Forward_Iterator last) -> Feature_Statistics\n    {\n        if (first == last) return Feature_Statistics{0, 0, 0};\n        std::int64_t count{0};\n        auto accumulate_feature = [&count](double const& acc, double const& feature) {\n            count += 1;\n            return acc + feature;\n        };\n        double const sum = std::accumulate(first, last, double{0.0}, accumulate_feature);\n        double const expected_value = sum / count;\n        auto accumulate_squared = [&expected_value](double const& acc, double const& feature) {\n            return acc + std::pow(expected_value - feature, 2.0);\n        };\n        double const variance = std::accumulate(first, last, double{0.0}, accumulate_squared)\n            / count;\n        return Feature_Statistics{expected_value, variance, count};\n    }\n};\n\nstruct Query_Statistics {\n    std::vector<Feature_Statistics> term_stats;\n    std::int64_t collection_size;\n};\n\n/// Extimates the number of documents containing **any** of the terms\n/// represented by `term_stats` in a collection of size `collection_size`.\n[[nodiscard]] auto any(Query_Statistics const& stats) -> double\n{\n    const auto collection_size = stats.collection_size;\n    const double any_product = std::accumulate(\n        stats.term_stats.begin(),\n        stats.term_stats.end(),\n        1.0,\n        [collection_size](const auto& acc, const Feature_Statistics& stats) {\n            return acc * (1.0 - double(stats.frequency) / collection_size);\n        });\n    return collection_size * (1.0 - any_product);\n}\n\n/// Extimates the number of documents containing **all** of the terms\n/// represented by `term_stats` in a collection of size `collection_size`.\n[[nodiscard]] auto all(const Query_Statistics& stats) -> double\n{\n    double const any = taily::any(stats);\n    if (any == 0.0) {\n        return 0.0;\n    }\n    double const all_product = std::accumulate(\n        stats.term_stats.begin(),\n        stats.term_stats.end(),\n        1.0,\n        [any](auto const& acc, Feature_Statistics const& stats) {\n            return acc * (stats.frequency / any);\n        });\n    return any * all_product;\n}\n\n/// Returns a gamma distribution fitted to `term_stats`.\n[[nodiscard]] auto\nfit_distribution(Feature_Statistics const& query_term_stats) -> boost::math::gamma_distribution<>\n{\n    const double k = std::pow(query_term_stats.expected_value, 2.0)\n        / query_term_stats.variance;\n    const double theta =\n        query_term_stats.variance / query_term_stats.expected_value;\n    return boost::math::gamma_distribution<>(k, theta);\n}\n\n/// Returns a gamma distribution fitted to a vector of term stats.\n///\n/// The term statictics are accumulated before the distribution is fitted.\n[[nodiscard]] auto fit_distribution(std::vector<Feature_Statistics> const& term_stats)\n    -> boost::math::gamma_distribution<>\n{\n    Feature_Statistics query_stats = std::accumulate(\n        term_stats.begin(), term_stats.end(), Feature_Statistics{0, 0, 0});\n    return fit_distribution(query_stats);\n}\n\n/// Estimates the global cutoff score for the entire collection.\n[[nodiscard]] auto estimate_cutoff(Query_Statistics const& stats, int ntop) -> double\n{\n    auto const dist = fit_distribution(stats.term_stats);\n    double const all = taily::all(stats);\n    double const p_c = std::min(1.0, ntop / all);\n    return boost::math::quantile(complement(dist, p_c));\n}\n\n/// Calculates the probability that a document in a shard given by `stats`\n/// has a score higher than `cutoff`.\n[[nodiscard]] auto calculate_cdf(double const cutoff, Query_Statistics const& stats) -> double\n// [[expects: cutoff >= 0.0]]\n{\n    if (cutoff <= 0) {\n        return 1.0;\n    }\n    Feature_Statistics query_stats = std::accumulate(\n        stats.term_stats.begin(), stats.term_stats.end(), Feature_Statistics{0, 0, 0});\n    if (query_stats.expected_value == 0 || query_stats.variance == 0) {\n        return 0.0;\n    }\n    auto dist = fit_distribution(query_stats);\n    return boost::math::cdf(complement(dist, cutoff));\n}\n\n/// Scores shards given by `shard_stats`.\n///\n/// \\param global_stats Term statistics for the entire collection\n/// \\param shard_stats Term statistics for individual shards\n/// \\param ntop The parameter to Taily algorithm saying how many top results we\n/// are shooting for\n[[nodiscard]] auto score_shards(Query_Statistics const& global_stats,\n                                std::vector<Query_Statistics> const& shard_stats,\n                                int const ntop) -> std::vector<double>\n{\n    int const shard_count = shard_stats.size();\n\n    std::vector<double> shard_all(shard_count);\n    std::transform(std::begin(shard_stats),\n                   std::end(shard_stats),\n                   std::begin(shard_all),\n                   [](auto const& shard_stats) { return taily::all(shard_stats); });\n\n    double const global_all = all(global_stats);\n    double const global_cutoff = estimate_cutoff(global_stats, ntop);\n\n    std::vector<double> shard_coefs(shard_count);\n    std::transform(std::begin(shard_stats),\n                   std::end(shard_stats),\n                   std::begin(shard_coefs),\n                   std::bind(calculate_cdf, global_cutoff, std::placeholders::_1));\n\n    std::transform(std::begin(shard_coefs),\n                   std::end(shard_coefs),\n                   std::begin(shard_all),\n                   std::begin(shard_coefs),\n                   std::multiplies<double>());\n\n    double const normalization_factor = std::accumulate(\n        std::begin(shard_coefs), std::end(shard_coefs), 0.0);\n\n    std::vector<double> estimates(shard_count);\n    auto normalize = [ntop, normalization_factor](auto const& element) {\n        return normalization_factor > 0 ? element * ntop / normalization_factor : 0.0;\n    };\n    std::transform(\n        std::begin(shard_coefs), std::end(shard_coefs), std::begin(estimates), normalize);\n    return estimates;\n}\n\n}  // namespace taily\n", "meta": {"hexsha": "db59396b322681ac0d6e9d4aa5c2ab4d7adc51a1", "size": 8906, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/taily.hpp", "max_stars_repo_name": "amallia/taily", "max_stars_repo_head_hexsha": "11c82c0c4ac364bc656ffd371860d0d37020dbde", "max_stars_repo_licenses": ["MIT"], "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/taily.hpp", "max_issues_repo_name": "amallia/taily", "max_issues_repo_head_hexsha": "11c82c0c4ac364bc656ffd371860d0d37020dbde", "max_issues_repo_licenses": ["MIT"], "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/taily.hpp", "max_forks_repo_name": "amallia/taily", "max_forks_repo_head_hexsha": "11c82c0c4ac364bc656ffd371860d0d37020dbde", "max_forks_repo_licenses": ["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.7217391304, "max_line_length": 97, "alphanum_fraction": 0.6740399731, "num_tokens": 1973, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585669110203, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.4839043841489473}}
{"text": "#include \"include_and_types.cpp\"\n#include <set>\n#include <boost/graph/detail/set_adaptor.hpp>\n\ntypedef graph_traits<Graph>::adjacency_iterator adj_iter;\n\ntemplate <class Root, class InComponent, class Num, class Set>\nclass TransitiveClosure{\nprivate:\n    //Graph\n    Graph*g;\n\n    //Property Map instances\n    Root root;\n    InComponent inComp;\n    Num num;\n    Set succ;\n\n    int index;\n\n    //Data Structure feeding Property Map instances\n    std::vector<Vertex> rootVet;\n    std::vector<bool> inCompVet;\n    std::vector<std::set<Vertex>*> sets;\n    std::vector<int> numVet;\n    std::vector<std::set<Vertex>> vect;\n    std::stack<Vertex> s;\n\n    /**\n     * This function is the body of the algorithm. It takes the vertex that the procedure is visiting in that time\n     * and calculates its successors.\n     * This is the C++ implementation of the pseudocode available on the Nuutila's paper\n     * @param v, vertex visited\n     */\n    void tc(Vertex v){\n        ++index;\n        put(root, v, v);\n        put(inComp, v, false);\n        put(num, v, index);\n        put(succ,v,&vect[v]);\n        std::set<Vertex> roots;\n        adj_iter ai, a_end;\n        for(boost::tie(ai, a_end)= adjacent_vertices(v,*g); ai!=a_end;++ai){\n            Vertex w=*ai;\n            if(get(num,w)==0)//Checking if w is already visited\n                tc(w);\n            if(!get(inComp,get(root,w)))//Checking if w's root is already in a SCC\n                put(root, v, get(num, get(root,w))<get(num,get(root,v)) ? get(root,w) : get(root,v));\n            else\n                //complexity logaritmic in size\n                roots.insert(get(root,w));\n        }\n        std::set<Vertex>::iterator it;\n        //complexity of set_union: 2*(size_set1+size_set2)-1\n        //This loop inserts all the vertex in roots and their successors in v's root successors\n        for(it=roots.begin();it!=roots.end();++it){\n            Vertex r=*it;\n            std::set<Vertex>* succRoot=get(succ, get(root,v));\n            set_union(get(succ,r)->begin(),get(succ,r)->end(),succRoot->begin(), succRoot->end(),\n                      std::inserter(*succRoot,succRoot->begin()));\n            succRoot->insert(r);\n        }\n\n        if(get(root,v)==v){\n            if(get(num,s.top())>=get(num,v)){\n                get(succ,v)->insert(v);\n                do{\n                    Vertex w=s.top();\n                    s.pop();\n                    put(inComp,w,true);\n                    if(v!=w){\n                        //Pointer assignment, not a copy\n                        std::set_union(get(succ,w)->begin(),get(succ,w)->end(),get(succ,v)->begin(),\n                                       get(succ,v)->end(),std::inserter(*get(succ,v),get(succ,v)->begin()));\n                        put(succ,w, get(succ,v));\n                    }\n                }while(get(num,s.top())>=get(num,v));\n            }else{\n                //if a vertex is root of a trivial SCC\n                put(inComp,v,true);\n            }\n        }else{\n            //If a vertex is not a root, it pushes his root into the stack, if it is not\n            if(get(num,s.top())!=get(num, get(root,v)))\n                s.push(get(root,v));\n            get(succ,get(root,v))->insert(v);\n\n        }\n    }\n\n    /**\n     * This function launches the procedure and it performs the visit of all the graph's vertex\n     */\n    void transitive_closure_main(){\n        vertex_iter vi,v_end;\n        timer::auto_cpu_timer t;\n        for(boost::tie(vi,v_end)=vertices(*g);vi!=v_end;++vi){\n            Vertex v=*vi;\n            if(get(num,v)==0){\n                tc(v);\n            }\n        }\n    };\n\npublic:\n    /**\n     * This is the constructor of the TransitiveClosure class. It takes the reference of the already allocated graph\n     * done by the caller (main_transitive_closure.cpp).\n     * The constructor initializes all the class attributes in proper way\n     * @param graph pointer\n     */\n    TransitiveClosure(Graph*graph){\n        g=graph;\n\n        //Insertion and handling of a new vertex with lowest num possible in order to accomplish algorithm correctness\n        Vertex starter=add_vertex(*g);\n        int n=num_vertices(*g);\n        numVet=*new std::vector<int>(n);\n        num=make_iterator_property_map(numVet.begin(),get(vertex_index,*g));\n        put(num, starter, -1);\n        s.push(starter);\n        remove_vertex(starter,*g);\n\n        //Updating number of graph's vertices\n        n--;\n\n        //data structures allocation\n        rootVet.resize(n);\n        inCompVet.resize(n);\n        sets.resize(n);\n        vect.resize(n);\n\n        //Properties instantiation\n        root=make_iterator_property_map(rootVet.begin(), get(vertex_index,*g));\n        inComp= make_iterator_property_map(inCompVet.begin(), get(vertex_index,*g));\n        succ=make_iterator_property_map(sets.begin(),get(vertex_index,*g));\n\n        //index needed\n        index=0;\n    }\n\n    /**\n     * This function is called by the main_transitive_closure callee. It launches the procedure and prints the\n     * procedure's result when it is done.\n     */\n    void transitive_closure_scc(){\n        //Execution of the procedure\n        transitive_closure_main();\n\n        //Printing our results\n        std::cout << \"Ours\" << std::endl;\n        IndexMap index = get(vertex_index,*g);\n        vertex_iter it, it_end;\n        for(boost::tie(it,it_end)=vertices(*g);it!=it_end;++it){\n            Vertex v=*it;\n            std::set<Vertex>* set=get(succ,get(root,v));\n            std::cout << index[*it] << \" --> \";\n            std::set<Vertex>::iterator i;\n            for(i=set->begin();i!=set->end();++i){\n                std::cout << *i << \" \";\n            }\n            std::cout << std::endl;\n        }\n\n    }\n};\n", "meta": {"hexsha": "415dc1df1934036be223090801c21886bd3a1b66", "size": 5731, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "my_transitive_closure.cpp", "max_stars_repo_name": "phisco/advance_algorithms_project", "max_stars_repo_head_hexsha": "2961959cf6036ed4c85d479dd14389315df55ee1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-07-04T13:46:31.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-28T16:42:31.000Z", "max_issues_repo_path": "my_transitive_closure.cpp", "max_issues_repo_name": "phisco/advance_algorithms_project", "max_issues_repo_head_hexsha": "2961959cf6036ed4c85d479dd14389315df55ee1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "my_transitive_closure.cpp", "max_forks_repo_name": "phisco/advance_algorithms_project", "max_forks_repo_head_hexsha": "2961959cf6036ed4c85d479dd14389315df55ee1", "max_forks_repo_licenses": ["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.3173652695, "max_line_length": 118, "alphanum_fraction": 0.5489443378, "num_tokens": 1345, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585669110202, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.48390438414894726}}
{"text": "/*\nID: neo-white \nLANG: C++\nTASK: Kmeans_PlusPlus.cpp\n*/\n\n#include \"Kmeans_PlusPlus.h\"\n#include \"../Core/Core.h\"\n#include <boost/serialization/vector.hpp>\n#include <boost/serialization/queue.hpp>\n#include <boost/serialization/export.hpp> \n#include <vector>\n#include <queue>\n#include <fstream>  \n#include <time.h>\n\n//BOOST_CLASS_EXPORT(kmeans_plusplus::Kmeans_PlusPlus)\nnamespace kmeans_plusplus{\n        \n    //Flexible_vector *kmeans_plusplus(Flexible_vector *problem,int k)\n    std::vector<int> Kmeans_PlusPlus::kmeans_plusplus(Flexible_vector *problem,int k)\n    {\n    //\tfprintf(stderr,\"In kmeans_Lloyd \\n\");\n        int l = problem->prob.l;\n        int n_clusters = k;\n        int max_index = problem->prob.max_feature;\n\n    \n        //choose initial center uniformly at random \n        std::vector<int> queue;\n        queue.resize(l);\n        std::fill(queue.begin(),queue.end(), 0);\n        srand((unsigned)time(NULL));\n        int index = (rand()%l);\n        queue[index] = 1;\n        int iter_counter = 0;\n        std::cout<<\"kmeans++:iteration \"<< iter_counter<<\". candidated center \"<<index<<std::endl;\n        \n        //choose remaining centers\n        int remainingInstances = l - 1;\n        std::vector<double> distances;\n        distances.resize(l);\n        std::vector<double> cumProbs;\n        cumProbs.resize(l);\n        std::vector<double> weights;\n        weights.resize(l);\n        int ii,jj,kk;\n        if(n_clusters > 1)\n        {\n            //proceed with selecting the rest\n            //distances to the initial randomly chose center\n            for(ii=0;ii<l;ii++)\n                distances[ii] = euclidean_distance(problem->get_value_without_label(ii),problem->get_value_without_label(index));\n            \n            int center_candidate;\n            //now choose the remaining cluster centers\n            for(jj = 1; jj < n_clusters; jj++)\n            {\n                bool find = false;\n                //distances converted to probabilities\n                double sum_distances = 0;\n                for(kk=0;kk<l;kk++)\n                    sum_distances += distances[kk];\n                for(kk=0;kk<l;kk++)\n                    weights[kk] = distances[kk]/sum_distances;\n                double sum_probs = 0;\n                for(kk=0;kk<l;kk++)\n                {\n                    sum_probs += weights[kk];\n                    cumProbs[kk] = sum_probs;\n                }\n                cumProbs[l-1] = 1.0;  //make sure there are no rounding issues\n                //choose a random instance\n                double prob = (double) rand()/RAND_MAX;  //random between 0 and 1\n                for(ii=0;ii<l;ii++)\n                {\n                    if(prob < cumProbs[ii])\n                    {\n                        if(queue[ii] != 1)\n                        {\n                            queue[ii] = 1;\n                            center_candidate = ii;\n                            std::cout<<\"kmeans++:iteration \"<<iter_counter+1<<\". candidated center \"<<ii<<\".prob \"<<prob<<std::endl;\n                            remainingInstances--;\n                            find = true;\n                            break;\n                        }\n                    }\n                }\n                iter_counter++;\n\n                if(find == false)\n                {\n                    std::cout<<\"kmeans++:iteration \"<<iter_counter+1<<\". No find center. prob \"<<prob<<std::endl;\n                    break;\n                }\n    \n                if(remainingInstances == 0)\n                    break;\n    \n                //prepares to choose the next cluster center.\n                //check distances against the new cluster center to see if it is closer\n                double newDist;\n                for(ii = 0;ii < l;ii++)\n                {\n                    if(distances[ii] > 0)\n                    {\n                        newDist = euclidean_distance(problem->get_value_without_label(ii),problem->get_value_without_label(center_candidate));\n                        if(newDist < distances[ii])\n                        {\n                            distances[ii] = newDist;\n                        }\n                    }\n                }\n            }\n        }\n        return queue;\n    }\n\n/* \n    std::vector<int> Kmeans_Lloyd::init_random(size_t length, size_t random_seed)\n    {\n        int tmp;\n        std::vector<int> queue;\n        for(size_t i=0;i<length;i++)\n            queue.push_back(0);\n           \n        srand((unsigned)time(NULL));\n        for(size_t j=0;j<random_seed;j++)\n        {\n            while(1)\n            {\n                tmp = (rand()%length);\n                if(queue[tmp] == 0)\n                {\n                    queue[tmp] = 1;\n                    break;\n                }\n            }\n        }\n        return queue;\n    }\n    \n    \n    \n    \n    void Kmeans_Lloyd::finish(Flexible_vector *records, size_t feat_dim)\n    {\n        std::ofstream file;\n        file.open(\"./result.txt\");\t\n        size_t n_records = records->prob.l;\n        for(size_t i = 0; i < n_records; ++i)\n        {\n            std::vector<node> record;\n            record.clear();\n            record = records->get_value_without_label(i);\n            double dis = (1<<16)-1;\n            int who = -1;\n            for(size_t k = 0; k < this->fvkl.prob.l; k++)\n            {\n                std::vector<node> centroid = this->fvkl.get_value_without_label(k);\n                double tmp = euclidean_distance(record,centroid);\n    \n                if (tmp < dis){\n                    who = k;\n                    dis = tmp;\n                }\n            }\n            file << who << std::endl;\n        }\n    }\n*/    \n    double Kmeans_PlusPlus::euclidean_distance(std::vector<node> px,std::vector<node> py)\n    {\n    \tdouble sum = 0;\n    \tdouble distances = 0;\n        size_t ipx = 0;\n        size_t ipy = 0;\n        while((ipx <= (px.size()-1))||(ipy <= (py.size()-1)))\n    \t{\n            if((ipx <= (px.size()-1))&&(ipy <= (py.size()-1)))\n            {\n    \t\t    if(px[ipx].index == py[ipy].index)\n    \t\t    {\n    \t\t    \tsum += (px[ipx].value-py[ipy].value)*(px[ipx].value-py[ipy].value);\n    \t\t    \t++ipx;\n    \t\t    \t++ipy;\n    \t\t    }\n    \t\t    else\n    \t\t    {\n    \t\t    \tif(px[ipx].index > py[ipy].index)\n                    {\n                        sum += py[ipy].value*py[ipy].value;\n    \t\t    \t\t++ipy;\n                    }\n    \t\t    \telse\n                    {\n                        sum += px[ipx].value*px[ipx].value;\n    \t\t    \t\t++ipx;\n                    }\n    \t\t    }\n            }else if((ipx == px.size())&&(ipy <= (py.size()-1)))\n            {\n                sum += py[ipy].value*py[ipy].value;\n    \t\t    ++ipy;\n            }else if((ipy == py.size())&&(ipx <= (px.size()-1)))\n            {\n                sum += px[ipx].value*px[ipx].value;\n    \t   \t\t++ipx;\n            }\n    \t}\n        distances = sqrt(sum);\n    \treturn distances;\n    }\n}\n", "meta": {"hexsha": "5f37e973d974c80f4f7d461850bb56daebcaf866", "size": 6922, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "MLtool/Cluster/Kmeans_PlusPlus.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": "MLtool/Cluster/Kmeans_PlusPlus.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": "MLtool/Cluster/Kmeans_PlusPlus.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": 32.0462962963, "max_line_length": 142, "alphanum_fraction": 0.445969373, "num_tokens": 1562, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.48383755815253415}}
{"text": "// ALGOLAB BGL Tutorial 3\n// Flow example demonstrating\n// - breadth first search (BFS) on the residual graph\n\n// Compile and run with one of the following:\n// g++ -std=c++11 -O2 bgl_residual_bfs.cpp -o bgl_residual_bfs ./bgl_residual_bfs\n// g++ -std=c++11 -O2 -I path/to/boost_1_58_0 bgl_residual_bfs.cpp -o bgl_residual_bfs; ./bgl_residual_bfs\n\n// Includes\n// ========\n// STL includes\n#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <queue>\n// BGL includes\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/push_relabel_max_flow.hpp>\n#include <boost/tuple/tuple.hpp>\n\n// BGL graph definitions\n// =====================\n// Graph Type with nested interior edge properties for Flow Algorithms\ntypedef  boost::adjacency_list_traits<boost::vecS, boost::vecS, boost::directedS> traits;\ntypedef boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS, boost::no_property,\n  boost::property<boost::edge_capacity_t, long,\n    boost::property<boost::edge_residual_capacity_t, long,\n      boost::property<boost::edge_reverse_t, traits::edge_descriptor> > > >  graph;\n// Interior Property Maps\ntypedef traits::vertex_descriptor vertex_desc;\n\ntypedef  boost::graph_traits<graph>::edge_descriptor      edge_desc;\ntypedef  boost::graph_traits<graph>::out_edge_iterator      out_edge_it;\n\n// Custom Edge Adder Class, that holds the references\n// to the graph, capacity map and reverse edge map\n// ===================================================\nclass edge_adder {\n graph &G;\n\n public:\n  explicit edge_adder(graph &G) : G(G) {}\n\n  void add_edge(int from, int to, long capacity) {\n    auto c_map = boost::get(boost::edge_capacity, G);\n    auto r_map = boost::get(boost::edge_reverse, G);\n    const edge_desc e = boost::add_edge(from, to, G).first;\n    const edge_desc rev_e = boost::add_edge(to, from, G).first;\n    c_map[e] = capacity;\n    c_map[rev_e] = 0; // reverse edge has no capacity!\n    r_map[e] = rev_e;\n    r_map[rev_e] = e;\n  }\n};\n\n\n// Main\nvoid testcase() {\n  // build graph\n  int n, m, s, d;\n  std::cin >> n >> m >> s >> d;\n  graph G(2 * n);\n  edge_adder adder(G);\n  // auto rc_map = boost::get(boost::edge_residual_capacity, G);\n  const vertex_desc v_source = boost::add_vertex(G);\n  const vertex_desc v_sink = boost::add_vertex(G);\n  \n  for(int k = 0; k < m; k++) {\n    int i, j;\n    std::cin >> i >> j;\n    adder.add_edge(2 * i + 1, 2 * j, 1); // from out_i to in_j\n  }\n  \n  for(int k = 0; k < s; k++) {\n    int i;\n    std::cin >> i;\n    adder.add_edge(v_source, 2 * i, 1); // from sink to in_u\n  }\n  \n  for(int k = 0; k < d; k++) {\n    int i;\n    std::cin >> i;\n    adder.add_edge(2 * i + 1, v_sink, 1); // from sink to in_u\n  }\n  \n  for(int i = 0; i < n; i++)\n    adder.add_edge(2 * i, 2 * i + 1, 1);\n  \n  // Find a min cut via maxflow\n  int flow = boost::push_relabel_max_flow(G, v_source, v_sink);\n  std::cout << flow << \"\\n\";\n\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": "795b50151fcfa2f527b2c1ef2873098892d82877", "size": 3013, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problems/week11-potw-phantom_menace/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/week11-potw-phantom_menace/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/week11-potw-phantom_menace/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": 29.8316831683, "max_line_length": 106, "alphanum_fraction": 0.6395618984, "num_tokens": 910, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4838375517300927}}
{"text": "#ifndef PHD_PARTICLE_FILTER\n#define PHD_PARTICLE_FILTER\n\n#include <opencv2/core.hpp>\n#include <opencv2/highgui.hpp>\n#include <Eigen/Dense>\n#include <opencv2/core/eigen.hpp>\n#include \"opencv2/ml.hpp\"\n\n#include \"../likelihood/gaussian.hpp\"\n#include \"../likelihood/multivariate_gaussian.hpp\"\n#include \"../utils/image_generator.hpp\"\n#include \"../utils/utils.hpp\"\n#include \"hungarian.h\"\n#include \"../em.hpp\"\n\n\n#include <time.h>\n#include <float.h>\n#include <vector>\n#include <iostream>\n#include <random>\n#include <chrono>\n#include <limits>\n#include <algorithm>\n\nusing namespace cv;\nusing namespace std;\nusing namespace Eigen;\n\ntypedef struct particle {\n    float x; /** current x coordinate */\n    float y; /** current y coordinate */\n    float width; /** current width coordinate */\n    float height; /** current height coordinate */\n    float scale; /** current velocity bounding box scale */\n    float x_p; /** current x coordinate */\n    float y_p; /** current y coordinate */\n    float width_p; /** current width coordinate */\n    float height_p; /** current height coordinate */\n    float scale_p; /** current velocity bounding box scale */\n} particle;\n\nclass PHDParticleFilter {\npublic:\n    int n_particles;\n    vector<particle> states;\n    vector<double> weights;\n   ~PHDParticleFilter();\n    PHDParticleFilter(int _n_particles, bool verbose = false);\n    PHDParticleFilter();\n    void initialize(Mat& current_frame, vector<Rect> detections);\n    void update(Mat& image, vector<Rect> detections);\n    vector<MyTarget> estimate(Mat& image, bool draw = false);\n    void predict();\n    void resample();\n    void draw_particles(Mat& image, Scalar color);\n    bool is_initialized();\n    \nprotected:\n    mt19937 generator;\n    vector<VectorXd> theta_x;\n    vector<VectorXd> theta_y;\n    bool initialized;\n    normal_distribution<double> position_random_walk, velocity_random_walk, scale_random_walk;\n    Size img_size;\n    int max_height, max_width, min_height, min_width;\n    int max_x, max_y, min_x, min_y;\n    int particles_batch;\n    vector<MyTarget> tracks;\n    vector<Rect> birth_model;\n    RNG rng;\n    vector<int> labels, current_labels;\n    bool verbose;\n};\n\n#endif", "meta": {"hexsha": "db42af3409b5d7aaf84e7723ae23c5c8c12c989b", "size": 2170, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/models/phd_particle_filter.hpp", "max_stars_repo_name": "fjorquerauribe/multitarget-tracking", "max_stars_repo_head_hexsha": "2ef5306f71bc1e197be0d9a7e379de1066fb815e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-08-29T13:55:40.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-11T20:49:10.000Z", "max_issues_repo_path": "src/models/phd_particle_filter.hpp", "max_issues_repo_name": "fjorquerauribe/multitarget-tracking", "max_issues_repo_head_hexsha": "2ef5306f71bc1e197be0d9a7e379de1066fb815e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/models/phd_particle_filter.hpp", "max_forks_repo_name": "fjorquerauribe/multitarget-tracking", "max_forks_repo_head_hexsha": "2ef5306f71bc1e197be0d9a7e379de1066fb815e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-06-01T07:00:14.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-21T05:21:04.000Z", "avg_line_length": 28.1818181818, "max_line_length": 94, "alphanum_fraction": 0.7078341014, "num_tokens": 483, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4838375517300927}}
{"text": "/* test_laplace.cpp\n *\n * Copyright Steven Watanabe 2014\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#include <boost/random/laplace_distribution.hpp>\n#include <boost/random/uniform_real.hpp>\n#include <boost/math/distributions/laplace.hpp>\n\n#define BOOST_RANDOM_DISTRIBUTION boost::random::laplace_distribution<>\n#define BOOST_RANDOM_DISTRIBUTION_NAME laplace\n#define BOOST_MATH_DISTRIBUTION boost::math::laplace\n#define BOOST_RANDOM_ARG1_TYPE double\n#define BOOST_RANDOM_ARG1_NAME mean\n#define BOOST_RANDOM_ARG1_DEFAULT 1000.0\n#define BOOST_RANDOM_ARG1_DISTRIBUTION(n) boost::uniform_real<>(-n, n)\n#define BOOST_RANDOM_ARG2_TYPE double\n#define BOOST_RANDOM_ARG2_NAME beta\n#define BOOST_RANDOM_ARG2_DEFAULT 1000.0\n#define BOOST_RANDOM_ARG2_DISTRIBUTION(n) boost::uniform_real<>(0.00001, n)\n\n#include \"test_real_distribution.ipp\"\n", "meta": {"hexsha": "a7fba0dfc44236d08a4da89c14317d26e0d4a555", "size": 959, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/libs/random/test/test_laplace.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/random/test/test_laplace.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/random/test/test_laplace.cpp", "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": 33.0689655172, "max_line_length": 75, "alphanum_fraction": 0.811261731, "num_tokens": 241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4838375517300927}}
{"text": "/**\n * @file covariances.cpp\n * @brief How to recover covariances.\n * @author Michael Kaess\n * @version $Id: covariances.cpp 6377 2012-03-30 20:06:44Z kaess $\n *\n * Copyright (C) 2009-2013 Massachusetts Institute of Technology.\n * Michael Kaess, Hordur Johannsson, David Rosen,\n * Nicholas Carlevaris-Bianco and John. J. Leonard\n *\n * This file is part of iSAM.\n *\n * iSAM is free software; you can redistribute it and/or modify it under\n * the terms of the GNU Lesser General Public License as published by the\n * Free Software Foundation; either version 2.1 of the License, or (at\n * your option) any later version.\n *\n * iSAM is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public\n * License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with iSAM.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#include <iostream>\n#include <stdio.h>\n\n#include <Eigen/LU> \n\n#include <isam/isam.h>\n\nusing namespace std;\nusing namespace isam;\nusing namespace Eigen;\n\nSlam slam;\n\nint main(int argc, const char* argv[]) {\n  Pose2d origin;\n  Noise noise = SqrtInformation(10. * eye(3));\n  Pose2d_Node* pose_node_1 = new Pose2d_Node(); // create node\n  slam.add_node(pose_node_1); // add it to the Slam graph\n  Pose2d_Factor* prior = new Pose2d_Factor(pose_node_1, origin, noise); // create prior measurement, an factor\n  slam.add_factor(prior); // add it to the Slam graph\n\n  Pose2d_Node* pose_node_2 = new Pose2d_Node(); // create node\n  slam.add_node(pose_node_2); // add it to the Slam graph\n\n  Pose2d delta(1., 0., 0.);\n  Pose2d_Pose2d_Factor* odo = new Pose2d_Pose2d_Factor(pose_node_1, pose_node_2, delta, noise);\n  slam.add_factor(odo);\n\n  slam.batch_optimization();\n\n#if 0\n  const Covariances& covariances = slam.covariances();\n#else\n  // operate on a copy (just an example, cloning is useful for running\n  // covariance recovery in a separate thread)\n  const Covariances& covariances = slam.covariances().clone();\n#endif\n\n  // recovering the full covariance matrix\n  cout << \"Full covariance matrix:\" << endl;\n  MatrixXd cov_full = covariances.marginal(slam.get_nodes());\n  cout << cov_full << endl << endl;\n\n  // sanity checking by inverting the information matrix, not using R\n  SparseSystem Js = slam.jacobian();\n  MatrixXd J(Js.num_cols(), Js.num_cols());\n  for (int r=0; r<Js.num_cols(); r++) {\n    for (int c=0; c<Js.num_cols(); c++) {\n      J(r,c) = Js(r,c);\n    }\n  }\n  MatrixXd H = J.transpose() * J;\n  MatrixXd cov_full2 = H.inverse();\n  cout << cov_full2 << endl;\n\n  // recovering the block-diagonals only of the full covariance matrix\n  cout << \"Block-diagonals only:\" << endl;\n  Covariances::node_lists_t node_lists;\n  list<Node*> nodes;\n  nodes.push_back(pose_node_1);\n  node_lists.push_back(nodes);\n  nodes.clear();\n  nodes.push_back(pose_node_2);\n  node_lists.push_back(nodes);\n  list<MatrixXd> cov_blocks = covariances.marginal(node_lists);\n  int i = 1;\n  for (list<MatrixXd>::iterator it = cov_blocks.begin(); it!=cov_blocks.end(); it++, i++) {\n    cout << \"block \" << i << endl;\n    cout << *it << endl;\n  }\n\n  // recovering individual entries, here the right block column\n  cout << \"Right block column:\" << endl;\n  Covariances::node_pair_list_t node_pair_list;\n  node_pair_list.push_back(make_pair(pose_node_1, pose_node_2));\n  node_pair_list.push_back(make_pair(pose_node_2, pose_node_2));\n  list<MatrixXd> cov_entries = covariances.access(node_pair_list);\n  for (list<MatrixXd>::iterator it = cov_entries.begin(); it!=cov_entries.end(); it++) {\n    cout << *it << endl;\n  }\n}\n", "meta": {"hexsha": "dee8d3ed7d2d8764e8a6f59b0c93748cfea265f0", "size": 3708, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "catkin_ws/src/isam/examples/covariances.cpp", "max_stars_repo_name": "DiegoOrtegoP/Software", "max_stars_repo_head_hexsha": "4a07dd2dab29db910ca2e26848fa6b53b7ab00cd", "max_stars_repo_licenses": ["CC-BY-2.0"], "max_stars_count": 196.0, "max_stars_repo_stars_event_min_datetime": "2018-10-10T00:28:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T13:32:37.000Z", "max_issues_repo_path": "catkin_ws/src/isam/examples/covariances.cpp", "max_issues_repo_name": "DiegoOrtegoP/Software", "max_issues_repo_head_hexsha": "4a07dd2dab29db910ca2e26848fa6b53b7ab00cd", "max_issues_repo_licenses": ["CC-BY-2.0"], "max_issues_count": 22.0, "max_issues_repo_issues_event_min_datetime": "2018-11-13T14:07:58.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-03T14:27:12.000Z", "max_forks_repo_path": "catkin_ws/src/isam/examples/covariances.cpp", "max_forks_repo_name": "DiegoOrtegoP/Software", "max_forks_repo_head_hexsha": "4a07dd2dab29db910ca2e26848fa6b53b7ab00cd", "max_forks_repo_licenses": ["CC-BY-2.0"], "max_forks_count": 113.0, "max_forks_repo_forks_event_min_datetime": "2016-05-03T06:11:42.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-01T14:37:38.000Z", "avg_line_length": 34.0183486239, "max_line_length": 110, "alphanum_fraction": 0.7065803668, "num_tokens": 1033, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4838375517300927}}
{"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 ONELAYERERF_HPP\n#define ONELAYERERF_HPP\n\n#include <cmath>\n#include <iosfwd>\n\n#include \"Config.hpp\"\n\n#include <boost/math/special_functions/erf.hpp>\n\n/*! \\file OneLayerErf.hpp\n *  \\class OneLayerErf\n *  \\brief A erf dielectric profile\n *  \\author Roberto Di Remigio\n *  \\date 2015\n *  \\note The parameter given from user input for width_ is divided by 6.0 in\n *  the constructor to keep consistency with \\cite Frediani2004a\n */\n\nclass OneLayerErf\n{\nprivate:\n    /// Dielectric constant on the left of the interface\n    double epsilon1_;\n    /// Dielectric constant one the right of the interface\n    double epsilon2_;\n    /// Width of the transition layer\n    double width_;\n    /// Center of the transition layer\n    double center_;\n    /*! Returns value of dielectric profile at given point\n     *  \\param[in] point where to evaluate the profile\n     */\n    double value(double point) const {\n        double epsPlus = (epsilon1_ + epsilon2_) / 2.0;\n        double epsMinus = (epsilon2_ - epsilon1_) / 2.0;\n        double val = boost::math::erf((point - center_) / width_);\n        return (epsPlus + epsMinus * val); //epsilon(r)\n    }\n    /*! Returns value of derivative of dielectric profile at given point\n     *  \\param[in] point where to evaluate the derivative\n     */\n    double derivative(double point) const {\n        double factor = (epsilon2_ - epsilon1_) / (width_ * std::sqrt(M_PI));\n        double t = (point - center_) / width_;\n        double val = std::exp(-std::pow(t, 2));\n        return (factor * val); //first derivative of epsilon(r)\n    }\n    std::ostream & printObject(std::ostream & os)\n    {\n        os << \"Profile functional form: erf\" << std::endl;\n        os << \"Permittivity inside  = \" << epsilon1_ << std::endl;\n        os << \"Permittivity outside = \" << epsilon2_ << std::endl;\n        os << \"Profile width        = \" << width_    << \" AU\" << std::endl;\n        os << \"Profile center       = \" << center_   << \" AU\";\n        return os;\n    }\npublic:\n    OneLayerErf() {}\n    OneLayerErf(double e1, double e2, double w, double c) :\n        epsilon1_(e1), epsilon2_(e2), width_(w/6.0), center_(c) {}\n    /*! Returns a tuple holding the permittivity and its derivative\n     *  \\param[in]   r evaluation point\n     */\n    pcm::tuple<double, double> operator()(const double r) const\n    {\n        return pcm::make_tuple(value(r), derivative(r));\n    }\n    double epsilon1() const { return epsilon1_; }\n    double epsilon2() const { return epsilon2_; }\n    double width() const { return width_; }\n    double center() const { return center_; }\n    friend std::ostream & operator<<(std::ostream & os, OneLayerErf & th) {\n        return th.printObject(os);\n    }\n};\n\n#endif // ONELAYERERF_HPP\n", "meta": {"hexsha": "a8ee349d49e67a89d5e6a62346b5a51e32005713", "size": 3838, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "external/PCMSolver/PCMSolver-source/src/green/dielectric_profile/OneLayerErf.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/dielectric_profile/OneLayerErf.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/dielectric_profile/OneLayerErf.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": 36.9038461538, "max_line_length": 82, "alphanum_fraction": 0.6456487754, "num_tokens": 989, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.48383755173009263}}
{"text": "/**\n * Orderings for a binary problem\n */\n\n#ifndef BP_ORDERINGS_HPP_\n#define BP_ORDERINGS_HPP_\n\n#include <vector>\n#include <iostream>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/cuthill_mckee_ordering.hpp>\n#include <boost/graph/properties.hpp>\n#include <boost/graph/bandwidth.hpp>\n#include \"../../core/order.hpp\"\n#include \"../../util/options.hpp\"\n#include \"bp_instance.hpp\"\n\n#define DEFAULT_BP_ORDERING 4\n\nusing namespace std;\n\n\n/** Return an ordering for a binary problem given an id */\nOrdering* get_ordering_by_id_bp(int id, BPInstance* inst, Options& options);\n\n\n/**\n * Ordering that runs the Cuthill-McKee heuristic to minimize bandwidth on constraints with\n * pairs of variables; ignores all other constraints.\n */\nstruct CuthillMcKeePairOrdering : Ordering {\n\tBPInstance* inst;\n\tvector<int> v_in_layer;   // vertex at each layer\n\n\tCuthillMcKeePairOrdering(BPInstance* _inst) : inst(_inst)\n\t{\n\t\tconstruct_ordering();\n\t}\n\n\tint select_next_var(int layer)\n\t{\n\t\tassert(layer >= 0 && layer < inst->nvars);\n\t\treturn v_in_layer[layer];\n\t}\n\nprivate:\n\n\tvoid construct_ordering();\n};\n\n\n#endif // BP_ORDERINGS_HPP_", "meta": {"hexsha": "443213c9ab1cd041685e25e759f227da89a5f238", "size": 1129, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/problem/bp/bp_orderings.hpp", "max_stars_repo_name": "ctjandra/ddopt-bounds", "max_stars_repo_head_hexsha": "aaf7407da930503a17969cee71718ffcf0c1fe96", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/problem/bp/bp_orderings.hpp", "max_issues_repo_name": "ctjandra/ddopt-bounds", "max_issues_repo_head_hexsha": "aaf7407da930503a17969cee71718ffcf0c1fe96", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/problem/bp/bp_orderings.hpp", "max_forks_repo_name": "ctjandra/ddopt-bounds", "max_forks_repo_head_hexsha": "aaf7407da930503a17969cee71718ffcf0c1fe96", "max_forks_repo_licenses": ["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.7115384615, "max_line_length": 91, "alphanum_fraction": 0.7431355182, "num_tokens": 277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.48373292840225673}}
{"text": "/* =========================================================================\n   Copyright (c) 2010-2016, Institute for Microelectronics,\n                            Institute for Analysis and Scientific Computing,\n                            TU Wien.\n   Portions of this software are copyright by UChicago Argonne, LLC.\n\n                            -----------------\n                  ViennaCL - The Vienna Computing Library\n                            -----------------\n\n   Project Head:    Karl Rupp                   rupp@iue.tuwien.ac.at\n\n   (A list of authors and contributors can be found in the PDF manual)\n\n   License:         MIT (X11), see file LICENSE in the base directory\n============================================================================= */\n\n/** \\example blas3.cpp\n*\n*  In this tutorial it is shown how BLAS level 3 functionality in ViennaCL can be used.\n*\n*  We begin with defining preprocessor constants and including the necessary headers.\n**/\n\n//disable debug mechanisms to have a fair comparison with ublas:\n#ifndef NDEBUG\n #define NDEBUG\n#endif\n\n// System headers\n#include <iostream>\n\n\n// ublas headers\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/triangular.hpp>\n#include <boost/numeric/ublas/matrix_sparse.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n\n// Must be set if you want to use ViennaCL algorithms on ublas objects\n#define VIENNACL_WITH_UBLAS 1\n\n\n// ViennaCL headers\n#include \"viennacl/scalar.hpp\"\n#include \"viennacl/vector.hpp\"\n#include \"viennacl/matrix.hpp\"\n#include \"viennacl/linalg/prod.hpp\"\n#include \"viennacl/tools/random.hpp\"\n#include \"viennacl/tools/timer.hpp\"\n\n#define BLAS3_MATRIX_SIZE   400\n\nusing namespace boost::numeric;\n\n\n/**\n*  Later in this tutorial we will iterate over all available OpenCL devices.\n*  To ensure that this tutorial also works if no OpenCL backend is activated, we need this dummy-struct.\n**/\n#ifndef VIENNACL_WITH_OPENCL\n  struct dummy\n  {\n    std::size_t size() const { return 1; }\n  };\n#endif\n\n/**\n* We don't need additional auxiliary routines, so let us start straight away with main():\n*/\nint main()\n{\n  typedef float     ScalarType;\n\n  viennacl::tools::timer timer;\n  double exec_time;\n\n  viennacl::tools::uniform_random_numbers<ScalarType> randomNumber;\n\n  /**\n  * Set up some ublas objects and initialize with data:\n  **/\n  ublas::matrix<ScalarType> ublas_A(BLAS3_MATRIX_SIZE, BLAS3_MATRIX_SIZE);\n  ublas::matrix<ScalarType, ublas::column_major> ublas_B(BLAS3_MATRIX_SIZE, BLAS3_MATRIX_SIZE);\n  ublas::matrix<ScalarType> ublas_C(BLAS3_MATRIX_SIZE, BLAS3_MATRIX_SIZE);\n  ublas::matrix<ScalarType> ublas_C1(BLAS3_MATRIX_SIZE, BLAS3_MATRIX_SIZE);\n\n  for (unsigned int i = 0; i < ublas_A.size1(); ++i)\n    for (unsigned int j = 0; j < ublas_A.size2(); ++j)\n      ublas_A(i,j) = ScalarType(10) * randomNumber();\n\n  for (unsigned int i = 0; i < ublas_B.size1(); ++i)\n    for (unsigned int j = 0; j < ublas_B.size2(); ++j)\n      ublas_B(i,j) = ScalarType(10) * randomNumber();\n\n  /**\n  * Set up some ViennaCL objects. Data initialization will happen later.\n  **/\n  //viennacl::ocl::set_context_device_type(0, viennacl::ocl::gpu_tag());  //uncomment this is you wish to use GPUs only\n  viennacl::matrix<ScalarType> vcl_A(BLAS3_MATRIX_SIZE, BLAS3_MATRIX_SIZE);\n  viennacl::matrix<ScalarType, viennacl::column_major> vcl_B(BLAS3_MATRIX_SIZE, BLAS3_MATRIX_SIZE);\n  viennacl::matrix<ScalarType> vcl_C(BLAS3_MATRIX_SIZE, BLAS3_MATRIX_SIZE);\n\n  /**\n  * <h2>Matrix-matrix Products</h2>\n  *\n  * First compute the reference product using uBLAS:\n  **/\n  std::cout << \"--- Computing matrix-matrix product using ublas ---\" << std::endl;\n  timer.start();\n  ublas_C = ublas::prod(ublas_A, ublas_B);\n  exec_time = timer.get();\n  std::cout << \" - Execution time: \" << exec_time << std::endl;\n\n  /**\n  * Now iterate over all OpenCL devices in the context and compute the matrix-matrix product.\n  * If the OpenCL backend is disabled, we use the dummy-struct defined above.\n  **/\n  std::cout << std::endl << \"--- Computing matrix-matrix product on each available compute device using ViennaCL ---\" << std::endl;\n#ifdef VIENNACL_WITH_OPENCL\n  std::vector<viennacl::ocl::device> devices = viennacl::ocl::current_context().devices();\n#else\n  dummy devices;\n#endif\n\n  for (std::size_t device_id=0; device_id<devices.size(); ++device_id)\n  {\n#ifdef VIENNACL_WITH_OPENCL\n    viennacl::ocl::current_context().switch_device(devices[device_id]);\n    std::cout << \" - Device Name: \" << viennacl::ocl::current_device().name() << std::endl;\n#endif\n\n    /**\n    * Copy the data from the uBLAS objects, compute one matrix-matrix-product as a 'warm up', then take timings:\n    **/\n    viennacl::copy(ublas_A, vcl_A);\n    viennacl::copy(ublas_B, vcl_B);\n    vcl_C = viennacl::linalg::prod(vcl_A, vcl_B);\n    viennacl::backend::finish();\n    timer.start();\n    vcl_C = viennacl::linalg::prod(vcl_A, vcl_B);\n    viennacl::backend::finish();\n    exec_time = timer.get();\n    std::cout << \" - Execution time on device (no setup time included): \" << exec_time << std::endl;\n\n    /**\n    * Verify the result\n    **/\n    viennacl::copy(vcl_C, ublas_C1);\n\n    std::cout << \" - Checking result... \";\n    bool check_ok = true;\n    for (std::size_t i = 0; i < ublas_C.size1(); ++i)\n    {\n      for (std::size_t j = 0; j < ublas_C.size2(); ++j)\n      {\n        if ( std::fabs(ublas_C1(i,j) - ublas_C(i,j)) / ublas_C(i,j) > 1e-4 )\n        {\n          check_ok = false;\n          break;\n        }\n      }\n      if (!check_ok)\n        break;\n    }\n    if (check_ok)\n      std::cout << \"[OK]\" << std::endl << std::endl;\n    else\n      std::cout << \"[FAILED]\" << std::endl << std::endl;\n\n  }\n\n  /**\n  *  That's it. A more extensive benchmark for dense BLAS routines is also available.\n  **/\n  std::cout << \"!!!! TUTORIAL COMPLETED SUCCESSFULLY !!!!\" << std::endl;\n  return EXIT_SUCCESS;\n}\n\n", "meta": {"hexsha": "3d914a32222342ba08d0daeac6a0f8afaf4dcaa5", "size": 5963, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/tutorial/blas3.cpp", "max_stars_repo_name": "yuchengs/viennacl-dev", "max_stars_repo_head_hexsha": "99f250fdb729de01ff5e9aebbed7b2ed3b1d8dfa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 224.0, "max_stars_repo_stars_event_min_datetime": "2015-02-15T21:50:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-14T18:27:03.000Z", "max_issues_repo_path": "examples/tutorial/blas3.cpp", "max_issues_repo_name": "yuchengs/viennacl-dev", "max_issues_repo_head_hexsha": "99f250fdb729de01ff5e9aebbed7b2ed3b1d8dfa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 189.0, "max_issues_repo_issues_event_min_datetime": "2015-01-09T17:08:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-04T06:23:22.000Z", "max_forks_repo_path": "examples/tutorial/blas3.cpp", "max_forks_repo_name": "yuchengs/viennacl-dev", "max_forks_repo_head_hexsha": "99f250fdb729de01ff5e9aebbed7b2ed3b1d8dfa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 84.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T14:06:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-23T14:51:17.000Z", "avg_line_length": 32.4076086957, "max_line_length": 131, "alphanum_fraction": 0.6441388563, "num_tokens": 1598, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.679178692681616, "lm_q1q2_score": 0.48373292377717986}}
{"text": "// Boost.Function library examples\r\n\r\n// Copyright (C) 2001 Doug Gregor (gregod@cs.rpi.edu)\r\n//\r\n// Permission to copy, use, sell and distribute this software is granted\r\n// provided this copyright notice appears in all copies.\r\n// Permission to modify the code and to distribute modified code is granted\r\n// provided this copyright notice appears in all copies, and a notice\r\n// that the code was modified is included with the copyright notice.\r\n//\r\n// This software is provided \"as is\" without express or implied warranty,\r\n// and with no claim as to its suitability for any purpose.\r\n\r\n// For more information, see http://www.boost.org\r\n\r\n#include <iostream>\r\n#include <boost/function.hpp>\r\n\r\nstruct int_div { \r\n  float operator()(int x, int y) const { return ((float)x)/y; }; \r\n};\r\n\r\nint\r\nmain()\r\n{\r\n  boost::function<float, int, int> f;\r\n  f = int_div();\r\n\r\n  std::cout << f(5, 3) << std::endl; // 1.66667\r\n\r\n  return 0;\r\n}\r\n", "meta": {"hexsha": "bc25fc7c72de08fd4bb1ab27ee443af4014118ac", "size": 930, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sdk/boost_1_30_0/libs/function/example/int_div.cpp", "max_stars_repo_name": "acidicMercury8/xray-1.0", "max_stars_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-01-30T12:51:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-31T08:36:49.000Z", "max_issues_repo_path": "sdk/boost_1_30_0/libs/function/example/int_div.cpp", "max_issues_repo_name": "acidicMercury8/xray-1.0", "max_issues_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_issues_repo_licenses": ["Linux-OpenIB"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sdk/boost_1_30_0/libs/function/example/int_div.cpp", "max_forks_repo_name": "acidicMercury8/xray-1.0", "max_forks_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1818181818, "max_line_length": 76, "alphanum_fraction": 0.6838709677, "num_tokens": 224, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.679178692681616, "lm_q1q2_score": 0.4837329237771798}}
{"text": "static bool eigen_did_assert = false;\n#define eigen_assert(X) if(!eigen_did_assert && !(X)){ std::cout << \"### Assertion raised in \" << __FILE__ << \":\" << __LINE__ << \":\\n\" #X << \"\\n### The following would happen without assertions:\\n\"; eigen_did_assert = true;}\n\n#include <iostream>\n#include <Eigen/Eigen>\n\n#ifndef M_PI\n#define M_PI 3.1415926535897932384626433832795\n#endif\n\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n// intentionally remove indentation of snippet\n{\nMatrix<int, 3, 4, ColMajor> Acolmajor;\nAcolmajor << 8, 2, 2, 9,\n             9, 1, 4, 4,\n\t     3, 5, 4, 5;\ncout << \"The matrix A:\" << endl;\ncout << Acolmajor << endl << endl; \n\ncout << \"In memory (column-major):\" << endl;\nfor (int i = 0; i < Acolmajor.size(); i++)\n  cout << *(Acolmajor.data() + i) << \"  \";\ncout << endl << endl;\n\nMatrix<int, 3, 4, RowMajor> Arowmajor = Acolmajor;\ncout << \"In memory (row-major):\" << endl;\nfor (int i = 0; i < Arowmajor.size(); i++)\n  cout << *(Arowmajor.data() + i) << \"  \";\ncout << endl;\n\n\n}\n  return 0;\n}\n", "meta": {"hexsha": "4ccd2f44b622cec4fd2ba2590eb0a9b38fa68a42", "size": 1058, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "build/compiled_eigen/doc/snippets/compile_TopicStorageOrders_example.cpp", "max_stars_repo_name": "aminulce/soil_model_cpp", "max_stars_repo_head_hexsha": "027803c29cbf5bddd1222839ba73019876533f87", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "build/compiled_eigen/doc/snippets/compile_TopicStorageOrders_example.cpp", "max_issues_repo_name": "aminulce/soil_model_cpp", "max_issues_repo_head_hexsha": "027803c29cbf5bddd1222839ba73019876533f87", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "build/compiled_eigen/doc/snippets/compile_TopicStorageOrders_example.cpp", "max_forks_repo_name": "aminulce/soil_model_cpp", "max_forks_repo_head_hexsha": "027803c29cbf5bddd1222839ba73019876533f87", "max_forks_repo_licenses": ["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.1904761905, "max_line_length": 224, "alphanum_fraction": 0.6143667297, "num_tokens": 344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6791786861878392, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.48373292330066864}}
{"text": "////////////////////////////////////////////////////////////////////////////////\n#include \"intersect_ray.h\"\n#include \"aabb.h\"\n#include \"aabb_binary.h\"\n#include <Eigen/Dense>\n#include <geogram/mesh/mesh_geometry.h>\n#include <limits>\n#include <numeric>\n#undef IGL_STATIC_LIBRARY\n#include <igl/ray_mesh_intersect.h>\n////////////////////////////////////////////////////////////////////////////////\n\nbool triangle_intersect_ray(const Eigen::Vector3d &a,\n                            const Eigen::Vector3d &b,\n                            const Eigen::Vector3d &c,\n                            const Eigen::Vector3d &ray_origin,\n                            const Eigen::Vector3d &ray_direction,\n                            Eigen::Vector3d &hit_position,\n                            Eigen::Vector3d &hit_normal,\n                            double &hit_param)\n{\n    igl::Hit hit;\n    Eigen::Matrix<double, 3, 3> V;\n    V.row(0) = a.transpose();\n    V.row(1) = b.transpose();\n    V.row(2) = c.transpose();\n    Eigen::RowVector3i F(0, 1, 2);\n    auto ret = igl::ray_mesh_intersect(ray_origin, ray_direction, V, F, hit);\n    if (ret) {\n        hit_param = hit.t;\n        hit_position = ray_origin + hit_param * ray_direction;\n        hit_normal = (b - a).cross(c - a).normalized();\n    }\n    return ret;\n}\n\n////////////////////////////////////////////////////////////////////////////////\n\nbool box_intersect_ray(const Eigen::AlignedBox3d &box,\n                       const Eigen::Vector3d &ray_origin,\n                       const Eigen::Vector3d &ray_direction)\n{\n    double tmin = 0;\n    double tmax = std::numeric_limits<double>::infinity();\n    for (int dim = 0; dim < 3; ++dim) {\n        if (std::abs(ray_direction(dim)) < 1e-5) {\n            if (ray_origin[dim] < box.min()[dim] || ray_origin[dim] > box.max()[dim]) {\n                return false;\n            }\n        }\n        else {\n            double t1 = (box.min()[dim] - ray_origin[dim]) / ray_direction[dim];\n            double t2 = (box.max()[dim] - ray_origin[dim]) / ray_direction[dim];\n            tmin = std::max(std::min(t1, t2), tmin);\n            tmax = std::min(std::max(t1, t2), tmax);\n        }\n    }\n    return (tmin <= tmax);\n}\n\n////////////////////////////////////////////////////////////////////////////////\n\ntemplate <>\nbool aabb_intersect_ray<AABBTree>(const Eigen::MatrixXd &V,\n                                  const Eigen::MatrixXi &F,\n                                  const AABBTree &tree,\n                                  const Eigen::Vector3d &ray_origin,\n                                  const Eigen::Vector3d &ray_direction,\n                                  Eigen::Vector3d &hit_position,\n                                  Eigen::Vector3d &hit_normal,\n                                  double &hit_param)\n{\n    return tree.shoot_ray(V, F, ray_origin, ray_direction, hit_position, hit_normal, hit_param);\n}\n\n////////////////////////////////////////////////////////////////////////////////\n\ntemplate <>\nbool aabb_intersect_ray<AABBTreeBinary>(const Eigen::MatrixXd &V,\n                                        const Eigen::MatrixXi &F,\n                                        const AABBTreeBinary &tree,\n                                        const Eigen::Vector3d &ray_origin,\n                                        const Eigen::Vector3d &ray_direction,\n                                        Eigen::Vector3d &hit_position,\n                                        Eigen::Vector3d &hit_normal,\n                                        double &hit_param)\n{\n    return tree.shoot_ray(V, F, ray_origin, ray_direction, hit_position, hit_normal, hit_param);\n}\n\n////////////////////////////////////////////////////////////////////////////////\n\ntemplate <>\nbool aabb_intersect_ray<igl::AABB<Eigen::MatrixXd, 3>>(const Eigen::MatrixXd &V,\n                                                       const Eigen::MatrixXi &F,\n                                                       const igl::AABB<Eigen::MatrixXd, 3> &tree,\n                                                       const Eigen::Vector3d &ray_origin,\n                                                       const Eigen::Vector3d &ray_direction,\n                                                       Eigen::Vector3d &hit_position,\n                                                       Eigen::Vector3d &hit_normal,\n                                                       double &hit_param)\n{\n    igl::Hit hit;\n    bool ret = tree.intersect_ray(V, F, ray_origin.transpose(), ray_direction.transpose(), hit);\n    if (ret) {\n        hit_param = hit.t;\n        hit_position = ray_origin + hit.t * ray_direction;\n        Eigen::Vector3d a = V.row(F.row(hit.id)[0]).transpose();\n        Eigen::Vector3d b = V.row(F.row(hit.id)[1]).transpose();\n        Eigen::Vector3d c = V.row(F.row(hit.id)[2]).transpose();\n        hit_normal = (b - a).cross(c - a).normalized();\n    }\n    return ret;\n}\n\n////////////////////////////////////////////////////////////////////////////////\n\ntemplate <>\nbool aabb_intersect_ray<igl::embree::EmbreeIntersector>(const Eigen::MatrixXd &V,\n                                                        const Eigen::MatrixXi &F,\n                                                        const igl::embree::EmbreeIntersector &tree,\n                                                        const Eigen::Vector3d &ray_origin,\n                                                        const Eigen::Vector3d &ray_direction,\n                                                        Eigen::Vector3d &hit_position,\n                                                        Eigen::Vector3d &hit_normal,\n                                                        double &hit_param)\n{\n    igl::Hit hit;\n    bool ret = tree.intersectRay(ray_origin.transpose().cast<float>(),\n                                 ray_direction.transpose().cast<float>(), hit);\n    if (ret) {\n        hit_param = hit.t;\n        hit_position = ray_origin + hit.t * ray_direction;\n        Eigen::Vector3d a = V.row(F.row(hit.id)[0]).transpose();\n        Eigen::Vector3d b = V.row(F.row(hit.id)[1]).transpose();\n        Eigen::Vector3d c = V.row(F.row(hit.id)[2]).transpose();\n        hit_normal = (b - a).cross(c - a).normalized();\n    }\n    return ret;\n}\n\n////////////////////////////////////////////////////////////////////////////////\n\ntemplate <>\nbool aabb_intersect_ray<GEO::MeshFacetsAABB>(const Eigen::MatrixXd &V,\n                                             const Eigen::MatrixXi &F,\n                                             const GEO::MeshFacetsAABB &tree,\n                                             const Eigen::Vector3d &ray_origin,\n                                             const Eigen::Vector3d &ray_direction,\n                                             Eigen::Vector3d &hit_position,\n                                             Eigen::Vector3d &hit_normal,\n                                             double &hit_param)\n{\n    // Multiply by big constant because AABB has a segment isect routine\n    // (not ray isect routine), so it would ignore intersections further\n    // away than (R.origin + R.direction), and we want them!\n    GEO::vec3 origin(ray_origin.data());\n    GEO::vec3 direction(ray_direction.data());\n    GEO::vec3 p2 = origin + 10000.0 * direction;\n    double t;\n    GEO::index_t f;\n    if (tree.segment_nearest_intersection(origin, p2, t, f)) {\n        t *= 10000.0;\n        if (t > 0) {\n            hit_param = t;\n            hit_position = ray_origin + t * ray_direction;\n            GEO::vec3 normal = GEO::normalize(GEO::Geom::mesh_facet_normal(*tree.mesh(), f));\n            hit_normal << normal[0], normal[1], normal[2];\n            return true;\n        }\n    }\n    return false;\n}\n", "meta": {"hexsha": "a6e7f7f353ac708313387d1d89196b18a5599145", "size": 7725, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/intersect_ray.cpp", "max_stars_repo_name": "jdumas/aabb_benchmark", "max_stars_repo_head_hexsha": "b63e43394508b2cc53f206a46472a0d7dbf917cb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-07-18T21:48:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-04T18:15:07.000Z", "max_issues_repo_path": "src/intersect_ray.cpp", "max_issues_repo_name": "jdumas/aabb_benchmark", "max_issues_repo_head_hexsha": "b63e43394508b2cc53f206a46472a0d7dbf917cb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-11-19T20:03:12.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-16T22:55:19.000Z", "max_forks_repo_path": "src/intersect_ray.cpp", "max_forks_repo_name": "jdumas/aabb_benchmark", "max_forks_repo_head_hexsha": "b63e43394508b2cc53f206a46472a0d7dbf917cb", "max_forks_repo_licenses": ["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.3965517241, "max_line_length": 99, "alphanum_fraction": 0.4424595469, "num_tokens": 1506, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199795472731, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4837216559755847}}
{"text": "// Standard headers\n#include \"rclcpp/rclcpp.hpp\"\n#include <cstdlib>\n#include <cmath>\n#include <random>\n#include <vector>\n#include <algorithm>\n#include <iostream>\n#include <thread>\n#include <functional>\n#include <limits>\n#include <signal.h>\n#include \"cmath\"\n#include <iterator>\n#include <boost/range/combine.hpp>\n#include <unordered_set>\n#include <Eigen/Dense>\n\n\n#include <cinematography_msgs/msg/drone_state.hpp>\n#include <cinematography_msgs/msg/multi_do_farray.hpp>\n#include <cinematography_msgs/msg/multi_dof.hpp>\n#include <cinematography_msgs/msg/artistic_spec.hpp>\n#include <tf2_ros/buffer.h>\n#include <tf2_ros/transform_listener.h>\n#include <tf2/LinearMath/Quaternion.h>\n#include <tf2/LinearMath/Vector3.h>\n#include <tf2_geometry_msgs/tf2_geometry_msgs.h>\n#include <geometry_msgs/msg/pose_array.hpp>\n#include \"tsdf_package_msgs/msg/tsdf.hpp\"\n#include \"tsdf_package_msgs/msg/voxel.hpp\"\n#include \"optimize_drone_path.cuh\"\n\n#include <Eigen/Dense>\n\n#include \"vehicles/multirotor/api/MultirotorRpcLibClient.hpp\"\n\n#define DEG_TO_RAD(d)   d*M_PI/180\n#define RAD_TO_DEG(r)   r*180/M_PI\n\nusing namespace std;\nusing std::placeholders::_1;\n\nclass MotionPlanner : public rclcpp::Node {\nprivate:\n    rclcpp::Publisher<cinematography_msgs::msg::MultiDOFarray>::SharedPtr drone_traj_pub;\n    rclcpp::Publisher<cinematography_msgs::msg::MultiDOFarray>::SharedPtr ideal_traj_pub;\n    rclcpp::Subscription<cinematography_msgs::msg::MultiDOFarray>::SharedPtr actor_traj_sub;\n    rclcpp::Subscription<tsdf_package_msgs::msg::Tsdf>::SharedPtr tsdf_sub;\n\n    // // TODO: change the bound to something meaningful\n    // double x__low_bound__global = -200, x__high_bound__global = 200;\n    // double y__low_bound__global = -200 , y__high_bound__global = 200;\n    // double z__low_bound__global = 0, z__high_bound__global = 40;\n    // double sampling_interval__global = 0.5;\n    // double v_max__global = 3, a_max__global = 5;\n    // float g_planning_budget = 4;\n    // std::string motion_planning_core_str;\n\n    // double drone_height__global = 0.6;\n    // double drone_radius__global = 2;\n\n    // Define default artistic constraints\n    double viewport_heading = M_PI / 3;\n    double viewport_pitch = M_PI / 4;\n    double viewport_distance = 3;\n\n    msr::airlib::MultirotorRpcLibClient* airsim_client;\n    std::string airsim_hostname;\n    std::string vehicle_name = \"drone_1\";\n\n    tf2_ros::Buffer* tf_buffer;\n    tf2_ros::TransformListener* tf_listener;\n\n    std::string world_frame;\n    std::string drone_frame;\n\n    double truncation_distance = 4;\n    double voxel_size = .5;\n    bool received_first_msg = false;\n\n    std::vector<Voxel> voxels_set[NUM_BUCKETS];\n    int voxels_set_size;\n\n    std::chrono::time_point<std::chrono::high_resolution_clock> global_start;\n    int global_iterations = 0;\n    double average = 0;\n    bool first_time = true;\n\n    int MAX_ITERATIONS;\n\n    // Calculate an ideal drone trajectory using a given actor trajectory (both in NED and radians)\n    cinematography_msgs::msg::MultiDOFarray calc_ideal_drone_traj(const cinematography_msgs::msg::MultiDOFarray &  actor_traj);\n\n    void update_traj_position_derivatives(cinematography_msgs::msg::MultiDOFarray& drone_traj);\n\n    // Moves the starting point to the drone's current position, leave the final point in place, and all the intermediate points are stretched in between\n    void move_traj_start(cinematography_msgs::msg::MultiDOFarray& drone_traj, cinematography_msgs::msg::MultiDOF& drone_pose);\n\n    void face_actor(cinematography_msgs::msg::MultiDOFarray& drone_traj, const cinematography_msgs::msg::MultiDOFarray& actor_traj);\n\n    size_t get_bucket(const Eigen::Matrix<double, 3, 1> & position);\n\n    double floor_fun(const double & x, const double & scale);\n\n    /*\n    * Given world point return center of volume given by volume_size\n    */\n    Eigen::Matrix<double, 3, 1> get_volume_center_from_point(Eigen::Matrix<double, 3, 1> point, double volume_size);\n\n    /*\n    * Check if two Eigen::Matrix<double, 3, 1> are equal\n    */\n    bool check_floating_point_vectors_equal(Eigen::Matrix<double, 3, 1> A, Eigen::Matrix<double, 3, 1> B, double epsilon);\n\n    /*\n    * Get voxels between point start and point end\n    * For more information on voxel traversal algo: http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.42.3443&rep=rep1&type=pdf\n    */\n    std::vector<Eigen::Matrix<double, 3, 1>> get_voxels(const cinematography_msgs::msg::MultiDOF point_start, const cinematography_msgs::msg::MultiDOF point_end, const double & volume_size);\n\n    /*\n    * Cost of sdf value\n    */\n    inline double get_cost(const double & sdf){\n        if(fabs(sdf) >= truncation_distance){\n            return 0;\n        }\n        else if(sdf > 0){\n            return pow((sdf - truncation_distance), 2) / (2* truncation_distance);\n        }else{\n            return sdf * -1 + .5 * truncation_distance;\n        }\n\n    }\n\n    inline double get_voxel_cost(const Eigen::Matrix<double, 3, 1> & voxel_pos){\n\n        size_t bucket = get_bucket(voxel_pos);\n\n        for(Voxel v : voxels_set[bucket]){\n            if(check_floating_point_vectors_equal(voxel_pos, v.position, voxel_size)){\n                return get_cost(v.sdf);\n            }\n        }\n\n        return 0; //voxel does not exist so it is in free space(or inside an object) and return 0 cost\n    }\n\n    /*\n    * Compute cost gradient for a voxel specified by voxel_pos. Check cost values of voxel at voxel_pos and voxels around\n    */\n    Eigen::Matrix<double, 3, 1> get_voxel_cost_gradient(const Eigen::Matrix<double, 3, 1> & voxel_pos);\n\n    double get_segment_cost(const cinematography_msgs::msg::MultiDOF point_start, const cinematography_msgs::msg::MultiDOF point_end, bool gradient=false);\n\n    Eigen::Matrix<double, 3, 1> get_segment_cost_gradient(const cinematography_msgs::msg::MultiDOF point_start,\n                    const cinematography_msgs::msg::MultiDOF point_end, bool gradient=false);\n\n    //======================VVV==Cost functions==VVV====================================\n\n    double traj_smoothness(const cinematography_msgs::msg::MultiDOFarray& drone_traj, int delta_t);\n\n    double shot_quality(const cinematography_msgs::msg::MultiDOFarray& drone_traj, cinematography_msgs::msg::MultiDOFarray& ideal_traj);\n\n    double obstacle_avoidance(const cinematography_msgs::msg::MultiDOFarray& drone_traj);\n\n    double occlusion_avoidance(const cinematography_msgs::msg::MultiDOFarray& drone_traj, cinematography_msgs::msg::MultiDOFarray& actor_traj);\n\n    double traj_cost_function(const cinematography_msgs::msg::MultiDOFarray& drone_traj, cinematography_msgs::msg::MultiDOFarray& actor_traj, cinematography_msgs::msg::MultiDOFarray& ideal_traj, double t);\n\n    //======================^^^==Cost functions==^^^====================================\n\n    //======================VVV==Gradient functions==VVV====================================\n\n    // TODO: Implement gradient equivalents of all the above, and hessian approximations (A_smooth + delta_1 * A_shot)\n    Eigen::Matrix<double, Eigen::Dynamic, 3> traj_smoothness_gradient(const cinematography_msgs::msg::MultiDOFarray& drone_traj, double delta_t, const Eigen::MatrixXd  & K, const Eigen::MatrixXd  & K0, const Eigen::MatrixXd  & K1, const Eigen::MatrixXd  & K2, const Eigen::MatrixXd  & A);\n\n    Eigen::Matrix<double, Eigen::Dynamic, 3> shot_quality_gradient(const cinematography_msgs::msg::MultiDOFarray& drone_traj, cinematography_msgs::msg::MultiDOFarray& ideal_traj, const Eigen::MatrixXd & A);\n\n    Eigen::Matrix<double, Eigen::Dynamic, 3>  obstacle_avoidance_gradient(const cinematography_msgs::msg::MultiDOFarray& drone_traj);\n\n    Eigen::Matrix<double, Eigen::Dynamic, 3>  occlusion_avoidance_gradient(const cinematography_msgs::msg::MultiDOFarray& drone_traj, const cinematography_msgs::msg::MultiDOFarray& actor_traj);\n\n    //======================^^^==Gradient functions==^^^====================================\n\n    void optimize_trajectory(cinematography_msgs::msg::MultiDOFarray& drone_traj, const cinematography_msgs::msg::MultiDOFarray& actor_traj);\n\n    //bool get_trajectory_fun(airsim_ros_pkgs::get_trajectory::Request &req, airsim_ros_pkgs::get_trajectory::Response &res)\n    // Get actor's predicted trajectory (in NED and radians)\n    void get_actor_trajectory(const cinematography_msgs::msg::MultiDOFarray::SharedPtr actor_traj);\n\n    void tsdf_callback(tsdf_package_msgs::msg::Tsdf::SharedPtr tsdf);\n\npublic:\n    MotionPlanner();\n\n    ~MotionPlanner() {\n        delete airsim_client;\n    }\n};", "meta": {"hexsha": "96e9df69e39c21ec3bb62cbca80b1ff14f39b122", "size": 8515, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ros2/src/cinematography/include/motion_planner.hpp", "max_stars_repo_name": "nightduck/AirSim", "max_stars_repo_head_hexsha": "2ba7124ceff7607f23463f483cd3e2cbe026d0ca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ros2/src/cinematography/include/motion_planner.hpp", "max_issues_repo_name": "nightduck/AirSim", "max_issues_repo_head_hexsha": "2ba7124ceff7607f23463f483cd3e2cbe026d0ca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2021-02-25T22:32:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-20T17:17:12.000Z", "max_forks_repo_path": "ros2/src/cinematography/include/motion_planner.hpp", "max_forks_repo_name": "nightduck/AirSim", "max_forks_repo_head_hexsha": "2ba7124ceff7607f23463f483cd3e2cbe026d0ca", "max_forks_repo_licenses": ["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.3631840796, "max_line_length": 288, "alphanum_fraction": 0.7165002936, "num_tokens": 2155, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332893, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.48372164661208406}}
{"text": "/**\n * Beck Pang, 20180926, use the four features to build a basic perspective controller, works.\n * Reference: Chaumette, Fran\u00e7ois, and Seth Hutchinson. \"Visual servo control. I. Basic approaches.\"\n */\n\n#include <iostream>\n#include <ros/ros.h>\n#include <cmath>\n#include <Eigen/Dense>\n#include <geometry_msgs/Twist.h>\n#include \"rm_cv/vertice.h\"\n#include \"VisualServoController.h\"\n#include \"camera_model/camera_models/CameraFactory.h\"\n\nusing namespace std;\nusing namespace Eigen;\n\nros::Publisher cmd_pub, debug_pub_typeI, debug_pub_typeII;\nstring cv_topic, publisher_topic, debug_typeI_topic, debug_typeII_topic;\n\n// Camera\nstd::string cfg_file_name = \"/home/nvidia/ws/src/6_controller/gimbal_controller/cfg/camera_tracking_camera_calib.yaml\";\ncamera_model::CameraPtr m_camera;\n\n// Controller\nint n = 4;\nint m = 2;\ndouble Kp = 1.0;\n\ndouble target_Z = 1;\ndouble pixel_x_max = 640;\ndouble pixel_y_max = 512;\ndouble pixel_dx = 68;\ndouble pixel_dy = 25;\n\nMatrixXd target_image_frame(n, m);\n\nVisualServoController ctl;\n\nvoid\npublish_message(const double wz, const ros::Publisher& pub)\n{\n    geometry_msgs::Twist vel_msg;\n    vel_msg.angular.z = wz;\n    pub.publish(vel_msg);\n}\n\n\n// No need to reject noise\nvoid\nvisual_servo_cb(const rm_cv::vertice::ConstPtr cv_ptr)\n{\n    // convert the pixel value to image coordinate value\n    MatrixXd input_pixel(n, m);\n    Vector3d input_pixel_output[n];\n    MatrixXd input_image_frame(n, m);\n\tint i;\n    for ( i = 0; i < n; ++i) {\n        input_pixel(i, 0) = cv_ptr->vertex[i].x;\n        input_pixel(i, 1) = cv_ptr->vertex[i].y;\n        m_camera->liftSphere(input_pixel.row(i), input_pixel_output[i] );\n        input_image_frame.row(i) << input_pixel_output[i](0), input_pixel_output[i](1);\n    }\n    std::cout << \"input in image frame \" << std::endl << input_image_frame << std::endl;\n\n    // use the image frame coordinate value to control\n    ctl.setKp(Kp);\n    VectorXd ctl_val = ctl.control(input_image_frame);\n\n    // publish the message in camera y axis\n    publish_message(ctl_val(1), cmd_pub);\n    \n    /*\n    // For comparision only\n    VectorXd ctl_val_typeI = ctl.control_type_current(input_image_frame);\n    VectorXd ctl_val_typeII = ctl.control_type_target(input_image_frame);\n    publish_message(ctl_val_typeI(1), debug_pub_typeI);\n    publish_message(ctl_val_typeII(1), debug_pub_typeII);\n    */\n}\n\n\n\nint main(int argc, char **argv) {\n    ros::init(argc, argv, \"four_point_visual_servo\");\n    ros::NodeHandle nh(\"~\");\n\n    nh.param(\"Kp\", Kp, 1.0);\n    nh.param(\"cv_topic\", cv_topic, string(\"/detected_vertice\"));\n    nh.param(\"publisher_topic\", publisher_topic, string(\"/cmd_vel\"));\n    nh.param(\"debug_typeI_topic\", debug_typeI_topic, string(\"/cmd_vel_type_current\"));\n    nh.param(\"debug_typeII_topic\", debug_typeII_topic, string(\"/cmd_vel_type_target\"));\n\n    ros::Subscriber sub = nh.subscribe(cv_topic, 10, visual_servo_cb);\n    cmd_pub = nh.advertise<geometry_msgs::Twist>(publisher_topic, 10);\n\tdebug_pub_typeI = nh.advertise<geometry_msgs::Twist>(debug_typeI_topic, 10);\n\tdebug_pub_typeII = nh.advertise<geometry_msgs::Twist>(debug_typeII_topic, 10);\n\n    // create a camera model\n    m_camera = camera_model::CameraFactory::instance()->generateCameraFromYamlFile(cfg_file_name);\n\n\t// setup the target coordinate\n\tMatrixXd target_pixel(n, m);\n\tMatrixXd target_image_frame(n, m);\n\n    double pixel_x_down= (pixel_x_max - pixel_dx) * 0.5;\n    double pixel_x_top_= (pixel_x_max + pixel_dx) * 0.5;\n    double pixel_y_down= (pixel_y_max - pixel_dy) * 0.5;\n    double pixel_y_top_= (pixel_y_max + pixel_dy) * 0.5;\n\n\ttarget_pixel << \n            pixel_x_down, pixel_y_down,\n\t\t    pixel_x_down, pixel_y_top_,\n\t\t    pixel_x_top_, pixel_y_down,\n\t\t    pixel_x_top_, pixel_y_top_; // 1000 mm\n\t\n\tVector3d target_pixel_output[n];\n\t\n\tfor\t(int i=0; i < n; ++i) {\n\t    m_camera->liftSphere(target_pixel.row(i), target_pixel_output[i] );\n        target_image_frame.row(i) << target_pixel_output[i](0), target_pixel_output[i](1);\n\t}\n\tstd::cout << \"target in image frame \" << std::endl << target_image_frame << std::endl;\n\t\n\tctl.setTarget(target_image_frame);\n\n\n\n    ros::spin();\n}\n", "meta": {"hexsha": "f81093720e29d1d0778f9f4097b7f21ed2cfc6db", "size": 4119, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "6_controller/src/visual_servo_controller.cpp", "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": "6_controller/src/visual_servo_controller.cpp", "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": "6_controller/src/visual_servo_controller.cpp", "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": 31.4427480916, "max_line_length": 119, "alphanum_fraction": 0.7140082544, "num_tokens": 1105, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.483721646612084}}
{"text": "#include <benchmark/benchmark.h>\n#include <random>\n#include <complex>\n#include <boost/math/fft/bsl_backend.hpp>\n#include <boost/math/fft/fftw_backend.hpp>\n#include <boost/math/fft/gsl_backend.hpp>\n#include <boost/math/constants/constants.hpp>\n\n#include \"fft_test_helpers.hpp\"\n\nstd::default_random_engine gen;\nstd::uniform_real_distribution<double> distribution;\n\n\ntypedef std::complex<double> cd;\nstd::vector<cd> random_vec(size_t N)\n{\n    std::vector<cd> V(N);\n    for (auto& x : V)\n      x = distribution(gen);\n    return V;\n}\n\nvoid bench_bsl_dit(benchmark::State& state)\n{\n    auto A = random_vec(state.range(0));\n    for (auto _ : state)\n    {\n        using boost::math::fft::dft_forward;\n        dft_forward<boost::math::fft::test_dft_power2_dit>(A.data(),A.data()+A.size(),A.data());\n    }\n    state.SetComplexityN(state.range(0));\n}\nvoid bench_bsl_dif(benchmark::State& state)\n{\n    auto A = random_vec(state.range(0));\n    for (auto _ : state)\n    {\n        using boost::math::fft::dft_forward;\n        dft_forward<boost::math::fft::test_dft_power2_dif>(A.data(),A.data()+A.size(),A.data());\n    }\n    state.SetComplexityN(state.range(0));\n}\nvoid bench_gsl(benchmark::State& state)\n{\n    auto A = random_vec(state.range(0));\n    for (auto _ : state)\n    {\n        using boost::math::fft::dft_forward;\n        dft_forward<boost::math::fft::gsl_dft>(A.data(),A.data()+A.size(),A.data());\n    }\n    state.SetComplexityN(state.range(0));\n}\nvoid bench_fftw(benchmark::State& state)\n{\n    auto A = random_vec(state.range(0));\n    for (auto _ : state)\n    {\n        using boost::math::fft::dft_forward;\n        dft_forward<boost::math::fft::fftw_dft>(A.data(),A.data()+A.size(),A.data());\n    }\n    state.SetComplexityN(state.range(0));\n}\n\nBENCHMARK(bench_bsl_dit)\n    ->RangeMultiplier(8)\n    ->Range(1 << 5, 1 << 20)\n    ->Complexity(benchmark::oNLogN);\n\nBENCHMARK(bench_bsl_dif)\n    ->RangeMultiplier(8)\n    ->Range(1 << 5, 1 << 20)\n    ->Complexity(benchmark::oNLogN);\n\nBENCHMARK(bench_gsl)\n    ->RangeMultiplier(8)\n    ->Range(1 << 5, 1 << 20)\n    ->Complexity(benchmark::oNLogN);\n\nBENCHMARK(bench_fftw)\n    ->RangeMultiplier(8)\n    ->Range(1 << 5, 1 << 20)\n    ->Complexity(benchmark::oNLogN);\n\nBENCHMARK_MAIN();\n", "meta": {"hexsha": "b3f042cb38f908169f964157867b2188200545e4", "size": 2220, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/fft_benchmark.cpp", "max_stars_repo_name": "BoostGSoC21/math", "max_stars_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "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": "test/fft_benchmark.cpp", "max_issues_repo_name": "BoostGSoC21/math", "max_issues_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 30.0, "max_issues_repo_issues_event_min_datetime": "2021-06-22T12:59:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-02T09:27:49.000Z", "max_forks_repo_path": "test/fft_benchmark.cpp", "max_forks_repo_name": "BoostGSoC21/math", "max_forks_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-07T21:15:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-07T21:15:02.000Z", "avg_line_length": 25.8139534884, "max_line_length": 96, "alphanum_fraction": 0.6468468468, "num_tokens": 658, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.48372164193033357}}
{"text": "// --------------------------------------------------------------------------------------------------------------------------------\n/**\n*   @file           coordinate.cpp\n*   @brief          \u98de\u884c\u5668\u7528\u5230\u7684\u5404\u79cd\u5750\u6807\u7cfb\u53d8\u6362\u3002\n*   @details        \u73b0\u6709\uff1a\u5730\u7403\u5750\u6807\u7cfb\uff0c\u5bfc\u822a\u5750\u6807\u7cfb\uff0c\u673a\u4f53\u5750\u6807\u7cfb\u3002\n                    \u5730\u7403\u5750\u6807\u7cfb\u91c7\u7528WGS-84\u5750\u6807\u7cfb\u5404\u9879\u53c2\u6570\u3002\n\t\t\t\t\t\u5730\u7403\u7a7a\u95f4\u76f4\u89d2\u5750\u6807\u7cfb\u539f\u70b9\u4e3a\u53c2\u8003\u692d\u7403\u7684\u4e2d\u5fc3\uff0cX\u8f74\u548cY\u8f74\u4f4d\u4e8e\u8d64\u9053\u5e73\u9762\uff0cX\u8f74\u901a\u8fc7\u96f6\u5b50\u5348\u7ebf\uff0cZ\u8f74\u4e0e\u692d\u7403\u6781\u8f74\u4e00\u81f4\u3002\n\t\t\t\t\t\u5bfc\u822a\u5750\u6807\u7cfb\u539f\u70b9\u4f4d\u4e8e\u53c2\u8003\u70b9\uff0cX\u8f74\u6307\u5411\u5317\u8fb9\uff0cY\u8f74\u6307\u5411\u4e1c\u8fb9\uff0cZ\u8f74\u6307\u5411\u5730\u4e0b\u3002\n\t\t\t\t\t\u673a\u4f53\u5750\u6807\u7cfb\u539f\u70b9\u4f4d\u4e8e\u8d28\u5fc3\u70b9\uff0cX\u8f74\u6307\u5411\u673a\u5934\u524d\u65b9\uff0cY\u8f74\u6307\u5411\u53f3\u4fa7\uff0cZ\u8f74\u6307\u5411\u4e0b\u65b9\u3002\n\t\t\t\t\t\u6240\u6709\u5750\u6807\u7cfb\u5747\u4e3a\u53f3\u624b\u7cfb\u3002\n*   @author         LiDaiwei\n*   @date           20191203\n*   @version        1.0.0.1\n*   @par Copyright\n*                   LiDaiwei\n*   @par History\n*                   1.0.0.1: LiDaiwei, 20191203, \u9996\u6b21\u521b\u5efa\n*\n\n*/\n\n// --------------------------------------------------------------------------------------------------------------------------------\n/**\n*   @name           \u5934\u6587\u4ef6\u3002\n*   @{\n*/\n\n#include \"coordinate.h\"\n#include <algorithm>\n//#include <Eigen/Dense>\n\n#include<iostream>\nusing namespace std;\nusing namespace Eigen;\n/** @}  */\n\n// --------------------------------------------------------------------------------------------------------------------------------\n/**\n*   @brief          \u8ba1\u7b97\u91cd\u529b\u52a0\u901f\u5ea6\u3002\n*   @details        \u8ba1\u7b97\u91cd\u529b\u52a0\u901f\u5ea6\u3002\n*   @param[out]     gravity         \u7cbe\u786e\u91cd\u529b\n*   @param[in]      latitude        \u7eac\u5ea6(\u89d2\u5ea6)\n*   @retval         0               \u6b63\u5e38\n*   @retval         1               \u9519\u8bef\n*/\nint accuraty_gravity (\n\tdouble* gravity,\n\tconst double latitude)\n{\n\tdouble L=0;\n\tdeg2rad(&L,latitude);\n\t*gravity=978.03267714*(1+0.00193185138639*sin(L)*sin(L))/\n\t\tsqrt(1-0.00669437999013*sin(L)*sin(L));\n\treturn 0;\n}\n\n\n// --------------------------------------------------------------------------------------------------------------------------------\n/**\n*   @brief          \u8ba1\u7b97\u5730\u7403\u4e3b\u66f2\u7387\u534a\u5f84\u3002\n*   @details        \u53c2\u8003\u692d\u7403\u5b50\u5348\u5708\u4e0a\u5404\u70b9\u66f2\u7387\u534a\u5f84RM\u548c\u536f\u9149\u5708\uff08\u5b83\u6240\u5728\u7684\u5e73\u9762\u4e0e\u5b50\u5348\u9762\u5782\u76f4\uff09\u4e0a\u5404\u70b9\u7684\u66f2\u7387\u534a\u5f84RN\u79f0\u4e3a\u4e3b\u66f2\u7387\u534a\u5f84\u3002\n*   @param[out]     RM              \u5b50\u5348\u5708\u66f2\u7387\u534a\u5f84\n*   @param[out]     RN              \u536f\u9149\u5708\u66f2\u7387\u534a\u5f84\n*   @param[in]      latitude        \u7eac\u5ea6(\u89d2\u5ea6)\n*   @retval         0               \u6b63\u5e38\n*   @retval         1               \u9519\u8bef\n*/\nint earth_curvature_radius (\n\tdouble* RM,\n\tdouble* RN,\n\tconst double latitude)\n{\n\tdouble L=0;\n\tdeg2rad(&L,latitude);\n\t*RM=earth_radius*(1-2*earth_ellipticity+3*earth_ellipticity*sin(L)*sin(L));\n\t*RN=earth_radius*(1+earth_ellipticity*sin(L)*sin(L));\n\n\treturn 0;\n}\n\n\n// --------------------------------------------------------------------------------------------------------------------------------\n/**\n*   @brief          \u5730\u7403\u7a7a\u95f4\u76f4\u89d2\u5750\u6807\u7cfb\u8f6c\u6362\u5230\u7ecf\u7eac\u5ea6\u9ad8\u5ea6\u5750\u6807\u7cfb\u3002\n*   @details        \u5730\u7403\u7a7a\u95f4\u76f4\u89d2\u5750\u6807\u7cfb\u539f\u70b9\u4e3a\u53c2\u8003\u692d\u7403\u7684\u4e2d\u5fc3\uff0cX\u8f74\u548cY\u8f74\u4f4d\u4e8e\u8d64\u9053\u5e73\u9762\uff0cX\u8f74\u901a\u8fc7\u96f6\u5b50\u5348\u7ebf\uff0cZ\u8f74\u4e0e\u692d\u7403\u6781\u8f74\u4e00\u81f4\u3002\n*   @param[out]     longitude       \u7ecf\u5ea6\uff08\u89d2\u5ea6\uff09\n*   @param[out]     latitude        \u7eac\u5ea6\uff08\u89d2\u5ea6\uff09\n*   @param[out]     height          \u9ad8\u5ea6\n*   @param[in]      x               \u5730\u7403\u7a7a\u95f4\u76f4\u89d2\u5750\u6807\u7cfbX\u5750\u6807\n*   @param[in]      y               \u5730\u7403\u7a7a\u95f4\u76f4\u89d2\u5750\u6807\u7cfbY\u5750\u6807\n*   @param[in]      z               \u5730\u7403\u7a7a\u95f4\u76f4\u89d2\u5750\u6807\u7cfbZ\u5750\u6807\n*   @retval         0               \u6b63\u5e38\n*   @retval         1               \u9519\u8bef\n*/\nint xyz_to_llh(\n\tdouble* longitude,\n\tdouble* latitude,\n\tdouble* height,\n\tconst double x,\n\tconst double y,\n\tconst double z)\n{\n\tdouble lon=0,lat=0;\n\tlon=atan2(y,x);\n\t//lon = lon < 0 ? (M_PI + lon) : lon;\n\trad2deg(longitude,lon);\n\t//\u8fed\u4ee3\u6cd5\u6c42\u7eac\u5ea6\u548c\u9ad8\u5ea6\n\tdouble HpRN_ip1=0,RN_ip1=0;\n\tdouble lat_i=0,lat_ip1=0;\n\tlat_i=atan(z/(pow((1-earth_ellipticity),2)*sqrt(x*x+y*y)));\n\tint num = 0;\n\tdo{\n\t\tHpRN_ip1=x/(cos(lat_i)*cos(lon));\n\t\tRN_ip1=earth_radius/sqrt(pow(cos(lat_i),2)+(1-pow(earth_e1,2))*pow(sin(lat_i),2));\n\t\tlat_ip1=atan(HpRN_ip1*z/((HpRN_ip1-RN_ip1*pow(earth_e1,2))*sqrt(x*x+y*y)));\n\t\tnum++;\n\t}while (abs( lat_ip1-lat_i)>1e-6 && num<1e3);\n\n\tlat=lat_ip1;\n\trad2deg(latitude,lat);\n\t*height=HpRN_ip1-RN_ip1;\n\treturn 0;\n}\n\n// --------------------------------------------------------------------------------------------------------------------------------\n/**\n*   @brief          \u7ecf\u7eac\u5ea6\u9ad8\u5ea6\u5750\u6807\u7cfb\u8f6c\u6362\u5230\u5730\u7403\u7a7a\u95f4\u76f4\u89d2\u5750\u6807\u7cfb\u3002\n*   @details        \u5730\u7403\u7a7a\u95f4\u76f4\u89d2\u5750\u6807\u7cfb\u539f\u70b9\u4e3a\u53c2\u8003\u692d\u7403\u7684\u4e2d\u5fc3\uff0cX\u8f74\u548cY\u8f74\u4f4d\u4e8e\u8d64\u9053\u5e73\u9762\uff0cX\u8f74\u901a\u8fc7\u96f6\u5b50\u5348\u7ebf\uff0cZ\u8f74\u4e0e\u692d\u7403\u6781\u8f74\u4e00\u81f4\u3002\n*   @param[out]      x               \u5730\u7403\u7a7a\u95f4\u76f4\u89d2\u5750\u6807\u7cfbX\u5750\u6807\n*   @param[out]      y               \u5730\u7403\u7a7a\u95f4\u76f4\u89d2\u5750\u6807\u7cfbY\u5750\u6807\n*   @param[out]      z               \u5730\u7403\u7a7a\u95f4\u76f4\u89d2\u5750\u6807\u7cfbZ\u5750\u6807\n*   @param[in]       longitude       \u7ecf\u5ea6\uff08\u89d2\u5ea6\uff09\n*   @param[in]       latitude        \u7eac\u5ea6\uff08\u89d2\u5ea6\uff09\n*   @param[in]       height          \u9ad8\u5ea6\n*   @retval          0               \u6b63\u5e38\n*   @retval          1               \u9519\u8bef\n*/\nint llh_to_xyz(\n\tdouble* x,\n\tdouble* y,\n\tdouble* z,\n\tconst double longitude,\n\tconst double latitude,\n\tconst double height)\n{\n\tdouble lon=0,lat=0,RN=0,RM;\n\tdeg2rad(&lon,longitude);\n\tdeg2rad(&lat,latitude);\n\tearth_curvature_radius(&RM,&RN,latitude);\n\n\t*x=(height+RN)*cos(lat)*cos(lon);\n\t*y=(height+RN)*cos(lat)*sin(lon);\n\t*z=(RN*pow((1-earth_ellipticity),2)+height)*sin(lat);\n\treturn 0;\n}\n\n// --------------------------------------------------------------------------------------------------------------------------------\n/**\n*   @brief          \u5730\u7403\u7ecf\u7eac\u5ea6\u5750\u6807\u7cfb\u8f6c\u6362\u5230\u5bfc\u822a\u5750\u6807\u7cfb\u7684\u65cb\u8f6c\u77e9\u9635\u3002\n*   @details        \u5bfc\u822a\u5750\u6807\u7cfb\u539f\u70b9\u4f4d\u4e8e\u53c2\u8003\u70b9\uff0cX\u8f74\u6307\u5411\u5317\u8fb9\uff0cY\u8f74\u6307\u5411\u4e1c\u8fb9\uff0cZ\u8f74\u6307\u5411\u5730\u4e0b\u3002\n*   @param[out]     R_en            \u65cb\u8f6c\u77e9\u9635:3x3,\u6b63\u4ea4\n*   @param[in]      longitude0      \u5bfc\u822a\u5750\u6807\u7cfb\u53c2\u8003\u70b9\u7ecf\u5ea6(\u89d2\u5ea6)\n*   @param[in]      latitude0       \u5bfc\u822a\u5750\u6807\u7cfb\u53c2\u8003\u70b9\u7eac\u5ea6(\u89d2\u5ea6)\n*   @retval         0               \u6b63\u5e38\n*   @retval         1               \u9519\u8bef\n*/\nint rotation_earth_to_navigation(\n\tMatrix3d* R_en,\n\tconst double longitude0,\n\tconst double latitude0)\n{\n\tdouble lon = 0, L = 0;\n\tdeg2rad(&lon, longitude0); deg2rad(&L, latitude0);\n\t//\u5148\u8f6c\u5230\u5929\u4e1c\u5317\u7cfb\n\tMatrix3d R_en2;\n\tR_en2(0, 0) = cos(L) * cos(lon);\n\tR_en2(0, 1) = cos(L) * sin(lon);\n\tR_en2(0, 2) = sin(L);\n\tR_en2(1, 0) = -sin(lon);\n\tR_en2(1, 1) = cos(lon);\n\tR_en2(1, 2) = 0;\n\tR_en2(2, 0) = -sin(L) * cos(lon);\n\tR_en2(2, 1) = -sin(L) * sin(lon);\n\tR_en2(2, 2) = cos(L);\n\t//\u518d\u4ece\u5929\u4e1c\u5317\u8f6c\u5230\u5317\u4e1c\u5730\n\tMatrix3d R_n2n;\n\tR_n2n << 0, 0, 1,\n\t\t0, 1, 0,\n\t\t-1, 0, 0;\n\t*R_en = R_n2n * R_en2;\n\treturn 0;\n}\n\n// --------------------------------------------------------------------------------------------------------------------------------\n/**\n*   @brief          \u5bfc\u822a\u5750\u6807\u7cfb\u8f6c\u6362\u5230\u5730\u7403\u7ecf\u7eac\u5ea6\u5750\u6807\u7cfb\u7684\u65cb\u8f6c\u77e9\u9635\u3002\n*   @details        \u5bfc\u822a\u5750\u6807\u7cfb\u539f\u70b9\u4f4d\u4e8e\u53c2\u8003\u70b9\uff0cX\u8f74\u6307\u5411\u5317\u8fb9\uff0cY\u8f74\u6307\u5411\u4e1c\u8fb9\uff0cZ\u8f74\u6307\u5411\u5730\u4e0b\u3002\n*   @param[out]     R_ne            \u65cb\u8f6c\u77e9\u9635:3x3,\u6b63\u4ea4\n*   @param[in]      longitude0      \u5bfc\u822a\u5750\u6807\u7cfb\u53c2\u8003\u70b9\u7ecf\u5ea6(\u89d2\u5ea6)\n*   @param[in]      latitude0       \u5bfc\u822a\u5750\u6807\u7cfb\u53c2\u8003\u70b9\u7eac\u5ea6(\u89d2\u5ea6)\n*   @retval         0               \u6b63\u5e38\n*   @retval         1               \u9519\u8bef\n*/\nint rotation_navigation_to_earth(\n\tMatrix3d* R_ne,\n\tconst double longitude0,\n\tconst double latitude0)\n{\n\tMatrix3d R_en;\n\trotation_earth_to_navigation(&R_en, longitude0, latitude0);\n\t*R_ne = R_en.transpose();\n\treturn 0;\n}\n\n// --------------------------------------------------------------------------------------------------------------------------------\n/**\n*   @brief          \u5730\u7403\u7ecf\u7eac\u5ea6\u5750\u6807\u7cfb\u8f6c\u6362\u5230\u5bfc\u822a\u5750\u6807\u7cfb\u3002\n*   @details        \u5bfc\u822a\u5750\u6807\u7cfb\u539f\u70b9\u4f4d\u4e8e\u53c2\u8003\u70b9\uff0cX\u8f74\u6307\u5411\u5317\u8fb9\uff0cY\u8f74\u6307\u5411\u4e1c\u8fb9\uff0cZ\u8f74\u6307\u5411\u5730\u9762\u3002\n*   @param[out]     north            \u5bfc\u822a\u5750\u6807\u7cfb\u5185\u4e1c\u5411\u5750\u6807\n*   @param[out]     east           \u5bfc\u822a\u5750\u6807\u7cfb\u5185\u5317\u5411\u5750\u6807\n*   @param[out]     downward          \u5bfc\u822a\u5750\u6807\u7cfb\u5185\u5929\u5411\u5750\u6807\n*   @param[in]      longitude       \u673a\u4f53\u7ecf\u5ea6\uff08\u89d2\u5ea6\uff09\n*   @param[in]      latitude        \u673a\u4f53\u7eac\u5ea6\uff08\u89d2\u5ea6\uff09\n*   @param[in]      height          \u673a\u4f53\u9ad8\u5ea6\n*   @param[in]      longitude0      \u5bfc\u822a\u5750\u6807\u7cfb\u53c2\u8003\u70b9\u7ecf\u5ea6\uff08\u89d2\u5ea6\uff09\n*   @param[in]      latitude0       \u5bfc\u822a\u5750\u6807\u7cfb\u53c2\u8003\u70b9\u7eac\u5ea6\uff08\u89d2\u5ea6\uff09\n*   @param[in]      height0         \u5bfc\u822a\u5750\u6807\u7cfb\u53c2\u8003\u70b9\u9ad8\u5ea6\n*   @retval         0               \u6b63\u5e38\n*   @retval         1               \u9519\u8bef\n*/\nint earth_to_navigation(\n\tdouble* north,\n\tdouble* east,\n\tdouble* downward,\n\tconst double longitude,\n\tconst double latitude,\n\tconst double height,\n\tconst double longitude0,\n\tconst double latitude0,\n\tconst double height0)\n{\n\n\tMatrix3d R_en;\n\trotation_earth_to_navigation(&R_en, longitude0, latitude0);\n\tVector3d Pe, Pn, t;\n\tllh_to_xyz(&Pe(0), &Pe(1), &Pe(2), longitude, latitude, height);\n\tllh_to_xyz(&t(0), &t(1), &t(2), longitude0, latitude0, height0);\n\n\tPn = R_en * (Pe - t);\n\n\t*north = Pn(0);\n\t*east = Pn(1);\n\t*downward = Pn(2);\n\treturn 0;\n}\n\n// --------------------------------------------------------------------------------------------------------------------------------\n/**\n*   @brief          \u5bfc\u822a\u5750\u6807\u7cfb\u8f6c\u6362\u5230\u5730\u7403\u7ecf\u7eac\u5ea6\u5750\u6807\u7cfb\u3002\n*   @details        \u5bfc\u822a\u5750\u6807\u7cfb\u539f\u70b9\u4f4d\u4e8e\u53c2\u8003\u70b9\uff0cX\u8f74\u6307\u5411\u5317\u8fb9\uff0cY\u8f74\u6307\u5411\u4e1c\u8fb9\uff0cZ\u8f74\u6307\u5411\u5730\u9762\u3002\n*   @param[out]     longitude       \u673a\u4f53\u7ecf\u5ea6\uff08\u89d2\u5ea6\uff09\n*   @param[out]     latitude        \u673a\u4f53\u7eac\u5ea6\uff08\u89d2\u5ea6\uff09\n*   @param[out]     height          \u673a\u4f53\u9ad8\u5ea6\n*   @param[in]      north            \u673a\u4f53\u5bfc\u822a\u5750\u6807\u7cfb\u5185\u4e1c\u5411\u5750\u6807\n*   @param[in]      east           \u673a\u4f53\u5bfc\u822a\u5750\u6807\u7cfb\u5185\u5317\u5411\u5750\u6807\n*   @param[in]      downward          \u673a\u4f53\u5bfc\u822a\u5750\u6807\u7cfb\u5185\u5929\u5411\u5750\u6807\n*   @param[in]      longitude0      \u5bfc\u822a\u5750\u6807\u7cfb\u53c2\u8003\u70b9\u7ecf\u5ea6\uff08\u89d2\u5ea6\uff09\n*   @param[in]      latitude0       \u5bfc\u822a\u5750\u6807\u7cfb\u53c2\u8003\u70b9\u7eac\u5ea6\uff08\u89d2\u5ea6\uff09\n*   @param[in]      height0         \u5bfc\u822a\u5750\u6807\u7cfb\u53c2\u8003\u70b9\u9ad8\u5ea6\n*   @retval         0               \u6b63\u5e38\n*   @retval         1               \u9519\u8bef\n*/\nint navigation_to_earth(\n\tdouble* longitude,\n\tdouble* latitude,\n\tdouble* height,\n\tconst double north,\n\tconst double east,\n\tconst double downward,\n\tconst double longitude0,\n\tconst double latitude0,\n\tconst double height0)\n{\n\tMatrix3d R_ne;\n\trotation_navigation_to_earth(&R_ne, longitude0, latitude0);\n\tVector3d Pe, Pn, t;\n\tPn << north, east, downward;//\u5728\u5bfc\u822a\u7cfb\u5185\u7684\u5750\u6807\n\tllh_to_xyz(&t(0), &t(1), &t(2), longitude0, latitude0, height0);\n\tPe = R_ne * Pn + t;\n\txyz_to_llh(longitude, latitude, height, Pe(0), Pe(1), Pe(2));\n\n\treturn 0;\n}\n\n// --------------------------------------------------------------------------------------------------------------------------------\n/**\n*   @brief          \u7531\u6b27\u62c9\u89d2\u5f97\u5230\u5bfc\u822a\u5750\u6807\u7cfb\u8f6c\u6362\u5230\u673a\u4f53\u5750\u6807\u7cfb\u7684\u65cb\u8f6c\u77e9\u9635\u3002\n*   @details        \u5bfc\u822a\u5750\u6807\u7cfb\u539f\u70b9\u4f4d\u4e8e\u53c2\u8003\u70b9\uff0cX\u8f74\u6307\u5411\u5317\u8fb9\uff0cY\u8f74\u6307\u5411\u4e1c\u8fb9\uff0cZ\u8f74\u6307\u5411\u5730\u4e0b\u3002\n                    \u673a\u4f53\u5750\u6807\u7cfb\u539f\u70b9\u4f4d\u4e8e\u8d28\u5fc3\u70b9\uff0cX\u8f74\u6307\u5411\u673a\u5934\uff0cY\u8f74\u6307\u5411\u53f3\u4fa7\uff0cZ\u8f74\u6307\u5411\u4e0b\u65b9\u3002\n*   @param[out]     R_nb            \u65cb\u8f6c\u77e9\u9635:3x3,\u6b63\u4ea4\n*   @param[in]      roll            \u673a\u4f53\u5bfc\u822a\u5750\u6807\u7cfb\u5185\u6a2a\u6eda\u89d2\uff08\u89d2\u5ea6\uff09\n*   @param[in]      pitch           \u673a\u4f53\u5bfc\u822a\u5750\u6807\u7cfb\u5185\u4fef\u4ef0\u89d2\uff08\u89d2\u5ea6\uff09\n*   @param[in]      yaw             \u673a\u4f53\u5bfc\u822a\u5750\u6807\u7cfb\u5185\u822a\u5411\u89d2\uff08\u89d2\u5ea6\uff09\n*   @retval         0               \u6b63\u5e38\n*   @retval         1               \u9519\u8bef\n*/\nint rotation_navigation_to_body(\n\tMatrix3d* R_nb,\n\tconst double roll,\n\tconst double pitch,\n\tconst double yaw)\n{\n\t////////\u5148\u5c06\u4e1c-\u5317-\u5929\u7684\u5bfc\u822a\u5750\u6807\u7cfb\u8f6c\u5230\u5317-\u4e1c-\u5730\u7684\u65b9\u5411\n\t//////Matrix3d R_nn2;\n\t//////R_nn2 << 0, 1, 0,\n\t//////\t\t1, 0, 0,\n\t//////\t\t0, 0, -1;\n\n\t//\u4ece\u5317-\u4e1c-\u5730\u7684\u5bfc\u822a\u5750\u6807\u7cfb\u4ee5Z\uff08\u822a\u5411\uff09-Y\uff08\u4fef\u4ef0\uff09-X\uff08\u6eda\u8f6c\uff09\u7684\u987a\u5e8f\u65cb\u8f6c\u5230\u8f7d\u4f53\u7cfb\u7684\u65cb\u8f6c\u77e9\u9635\uff1a\n\tdouble r, p, y;\n\tdeg2rad(&r, roll); deg2rad(&p, pitch); deg2rad(&y, yaw);\n\tdouble c1 = cos(y), s1 = sin(y);\n\tdouble c2 = cos(p), s2 = sin(p);\n\tdouble c3 = cos(r), s3 = sin(r);\n\t//\u53ef\u67e5Z1Y2X3\u987a\u89c4\u65cb\u8f6c\u77e9\u9635\u5982\u4e0b\uff1a\n\tMatrix3d R_n2b;\n\tR_n2b(0, 0) = c1 * c2;\n\tR_n2b(0, 1) = c1 * s2 * s3 - c3 * s1;\n\tR_n2b(0, 2) = s1 * s3 + c1 * c3 * s2;\n\tR_n2b(1, 0) = c2 * s1;\n\tR_n2b(1, 1) = c1 * c3 + s1 * s2 * s3;\n\tR_n2b(1, 2) = c3 * s1 * s2 - c1 * s3;\n\tR_n2b(2, 0) = -s2;\n\tR_n2b(2, 1) = c2 * s3;\n\tR_n2b(2, 2) = c2 * c3;\n\n\t*R_nb = R_n2b.transpose();// *R_nn2;\n\n\treturn 0;\n}\n\n// --------------------------------------------------------------------------------------------------------------------------------\n/**\n*   @brief          \u673a\u4f53\u5750\u6807\u7cfb\u8f6c\u6362\u5230\u5bfc\u822a\u5750\u6807\u7cfb\u7684\u65cb\u8f6c\u77e9\u9635\u3002\n*   @details        \u5bfc\u822a\u5750\u6807\u7cfb\u539f\u70b9\u4f4d\u4e8e\u53c2\u8003\u70b9\uff0cX\u8f74\u6307\u5411\u5317\u8fb9\uff0cY\u8f74\u6307\u5411\u4e1c\u8fb9\uff0cZ\u8f74\u6307\u5411\u5730\u4e0b\u3002\n\t\t\t\t\t\u673a\u4f53\u5750\u6807\u7cfb\u539f\u70b9\u4f4d\u4e8e\u8d28\u5fc3\u70b9\uff0cX\u8f74\u6307\u5411\u673a\u5934\uff0cY\u8f74\u6307\u5411\u53f3\u4fa7\uff0cZ\u8f74\u6307\u5411\u4e0b\u65b9\u3002\n*   @param[out]     R_bn            \u65cb\u8f6c\u77e9\u9635:3x3,\u6b63\u4ea4\n*   @param[in]      roll            \u673a\u4f53\u5bfc\u822a\u5750\u6807\u7cfb\u5185\u6a2a\u6eda\u89d2\uff08\u89d2\u5ea6\uff09\n*   @param[in]      pitch           \u673a\u4f53\u5bfc\u822a\u5750\u6807\u7cfb\u5185\u4fef\u4ef0\u89d2\uff08\u89d2\u5ea6\uff09\n*   @param[in]      yaw             \u673a\u4f53\u5bfc\u822a\u5750\u6807\u7cfb\u5185\u822a\u5411\u89d2\uff08\u89d2\u5ea6\uff09\n*   @retval         0               \u6b63\u5e38\n*   @retval         1               \u9519\u8bef\n*/\nint rotation_body_to_navigation(\n\tMatrix3d* R_bn,\n\tconst double roll,\n\tconst double pitch,\n\tconst double yaw)\n{\n\tMatrix3d R_nb;\n\trotation_navigation_to_body(&R_nb, roll, pitch, yaw);\n\t*R_bn = R_nb.transpose();\n\n\treturn 0;\n}\n\n// --------------------------------------------------------------------------------------------------------------------------------\n/**\n*   @brief          \u7531Rnb\u65cb\u8f6c\u77e9\u9635\u5f97\u5230\u6b27\u62c9\u89d2\u3002\n*   @details        Rnb\u662f\u5bfc\u822a\u5750\u6807\u7cfb\u8f6c\u6362\u5230\u673a\u4f53\u5750\u6807\u7cfb\n                    \u5bfc\u822a\u5750\u6807\u7cfb\u539f\u70b9\u4f4d\u4e8e\u53c2\u8003\u70b9\uff0cX\u8f74\u6307\u5411\u5317\u8fb9\uff0cY\u8f74\u6307\u5411\u4e1c\u8fb9\uff0cZ\u8f74\u6307\u5411\u5730\u4e0b\u3002\n\t\t\t\t\t\u673a\u4f53\u5750\u6807\u7cfb\u539f\u70b9\u4f4d\u4e8e\u8d28\u5fc3\u70b9\uff0cX\u8f74\u6307\u5411\u673a\u5934\uff0cY\u8f74\u6307\u5411\u53f3\u4fa7\uff0cZ\u8f74\u6307\u5411\u4e0b\u65b9\u3002\n*   @param[out]     roll            \u673a\u4f53\u5bfc\u822a\u5750\u6807\u7cfb\u5185\u6a2a\u6eda\u89d2\uff08\u89d2\u5ea6\uff09\n*   @param[out]     pitch           \u673a\u4f53\u5bfc\u822a\u5750\u6807\u7cfb\u5185\u4fef\u4ef0\u89d2\uff08\u89d2\u5ea6\uff09\n*   @param[out]     yaw             \u673a\u4f53\u5bfc\u822a\u5750\u6807\u7cfb\u5185\u822a\u5411\u89d2\uff08\u89d2\u5ea6\uff09\n*   @param[in]      R_nb            \u65cb\u8f6c\u77e9\u9635:3x3,\u6b63\u4ea4\n*   @retval         0               \u6b63\u5e38\n*   @retval         1               \u9519\u8bef\n*/\nint rotation_nb_to_euler(\n\tdouble* roll,\n\tdouble* pitch,\n\tdouble* yaw,\n\tconst Matrix3d R_nb)\n{\n\tdouble r, p, y;\n\t//////Matrix3d R_nn2_inv;\n\t//////R_nn2_inv << 0, 1, 0,\n\t//////\t\t1, 0, 0,\n\t//////\t\t0, 0, -1;\n\tMatrix3d R_n2b = R_nb.transpose();// *R_nn2_inv;\n\tr = atan2(R_n2b(2,1), R_n2b(2,2));\n\tp = atan(-R_n2b(2, 0) / sqrt(1 - R_n2b(2, 0) * R_n2b(2, 0)));\n\ty = atan2(R_n2b(1, 0), R_n2b(0, 0));\n\n\trad2deg(roll, r);\n\trad2deg(pitch, p);\n\trad2deg(yaw, y);\n\n\treturn 0;\n}\n\n\n\n// --------------------------------------------------------------------------------------------------------------------------------\n/**\n*   @brief          \u7531\u65b9\u5411\u4f59\u5f26\u65cb\u8f6c\u77e9\u9635\u6c42\u56db\u5143\u6570\n*   @details        \u7531\u65b9\u5411\u4f59\u5f26\u65cb\u8f6c\u77e9\u9635\u6c42\u56db\u5143\u6570\n*   @param[out]     q               \u56db\u5143\u6570:4\u7ef4\u5411\u91cf\n*   @param[in]      R               \u65b9\u5411\u4f59\u5f26\u65cb\u8f6c\u77e9\u9635:3x3\n*   @retval         0               \u6b63\u5e38\n*   @retval         1               \u9519\u8bef\n*/\nint rotation_to_quaternion(\n\tVector4d* q,\n\tconst Matrix3d R)\n{\n\tVector4d __q;\n\t__q(0) = 0.5 * sqrt(1 + R(0, 0) + R(1, 1) + R(2, 2));\n\tif (fabs(__q(0)) < 1e-4) {\n\t\tif (R(0, 0) > R(1, 1) && R(0, 0) > R(2, 2)) {\n\t\t\tdouble t = sqrt(1 + R(0, 0) - R(1, 1) - R(2, 2));\n\t\t\t__q(0) = (R(2, 1) - R(1, 2)) / t;\n\t\t\t__q(1) = t / 4;\n\t\t\t__q(2) = (R(0, 2) + R(2, 0)) / t;\n\t\t\t__q(3) = (R(0, 1) + R(1, 0)) / t;\n\t\t}\n\t\telse if (R(1, 1) > R(0, 0) && R(1, 1) > R(2, 2)) {\n\t\t\tdouble t = sqrt(1 - R(0, 0) + R(1, 1) - R(2, 2));\n\t\t\t__q(0) = (R(0, 2) - R(2, 0)) / t;\n\t\t\t__q(1) = (R(0, 1) + R(1, 0)) / t;\n\t\t\t__q(2) =  t / 4;\n\t\t\t__q(3) = (R(2, 1) + R(1, 2)) / t;\n\t\t}\n\t\telse {\n\t\t\tdouble t = sqrt(1 - R(0, 0) - R(1, 1) + R(2, 2));\n\t\t\t__q(0) = (R(1, 0) - R(0, 1)) / t;\n\t\t\t__q(1) = (R(0, 2) + R(2, 0)) / t;\n\t\t\t__q(2) = (R(1, 2) - R(2, 1)) / t;\n\t\t\t__q(3) =  t / 4;\n\t\t}\n\t}\n\telse {\n\t\t__q(1) = (R(2, 1) - R(1, 2)) / (4 * __q(0));\n\t\t__q(2) = (R(0, 2) - R(2, 0)) / (4 * __q(0));\n\t\t__q(3) = (R(1, 0) - R(0, 1)) / (4 * __q(0));\n\t}\n\tquaterntion_normalized(q, __q);\n\treturn 0;\n}\n\n// --------------------------------------------------------------------------------------------------------------------------------\n/**\n*   @brief          \u7531\u56db\u5143\u6570\u6c42\u65b9\u5411\u4f59\u5f26\u65cb\u8f6c\u77e9\u9635\n*   @details        \u7531\u56db\u5143\u6570\u6c42\u65b9\u5411\u4f59\u5f26\u65cb\u8f6c\u77e9\u9635\n*   @param[out]     R               \u65b9\u5411\u4f59\u5f26\u65cb\u8f6c\u77e9\u9635:3x3\n*   @param[in]      q               \u56db\u5143\u6570:4\u7ef4\u5411\u91cf\n*   @retval         0               \u6b63\u5e38\n*   @retval         1               \u9519\u8bef\n*/\nint quaternion_to_rotation(\n\tMatrix3d* R,\n\tconst Vector4d & q)//\u4e0d\u52a0'&'\u4f1a\u62a5\u9519\uff1a\u5177\u6709 __declspec(align('16')) \u7684\u5f62\u53c2\u5c06\u4e0d\u88ab\u5bf9\u9f50\n{\n\t(*R)(0, 0) = q(0) * q(0) + q(1) * q(1) - q(2) * q(2) - q(3) * q(3);\n\t(*R)(0, 1) = 2 * (q(1) * q(2) - q(0) * q(3));\n\t(*R)(0, 2) = 2 * (q(1) * q(3) + q(0) * q(2));\n\t(*R)(1, 0) = 2 * (q(1) * q(2) + q(0) * q(3));\n\t(*R)(1, 1) = q(0) * q(0) - q(1) * q(1) + q(2) * q(2) - q(3) * q(3);\n\t(*R)(1, 2) = 2 * (q(2) * q(3) - q(0) * q(1));\n\t(*R)(2, 0) = 2 * (q(1) * q(3) - q(0) * q(2));\n\t(*R)(2, 1) = 2 * (q(2) * q(3) + q(0) * q(1));\n\t(*R)(2, 2) = q(0) * q(0) - q(1) * q(1) - q(2) * q(2) + q(3) * q(3);\n\n\t//Matrix3d R_nn2_inv;\n\t//R_nn2_inv << 0, 1, 0,\n\t//\t1, 0, 0,\n\t//\t0, 0, -1;\n\t//(*R) = (*R) * R_nn2_inv;\n\n\treturn 0;\n}\n\n\n\n// --------------------------------------------------------------------------------------------------------------------------------\n/**\n*   @brief          \u7531\u6b27\u62c9\u89d2\u6c42\u4ece\u8f7d\u4f53\u7cfb\u5230\u5bfc\u822a\u7cfb\u7684\u8f6c\u52a8\u56db\u5143\u6570\n*   @details        \u7531\u6b27\u62c9\u89d2\u6c42\u4ece\u8f7d\u4f53\u7cfb\u5230\u5bfc\u822a\u7cfb\u7684\u8f6c\u52a8\u56db\u5143\u6570\n*   @param[out]     q               \u4ece\u8f7d\u4f53\u7cfb\u5230\u5bfc\u822a\u7cfb\u7684\u8f6c\u52a8\u56db\u5143\u6570:4\u7ef4\u5411\u91cf\n*   @param[in]      roll            \u673a\u4f53\u5bfc\u822a\u5750\u6807\u7cfb\u5185\u6a2a\u6eda\u89d2\uff08\u89d2\u5ea6\uff09\n*   @param[in]      pitch           \u673a\u4f53\u5bfc\u822a\u5750\u6807\u7cfb\u5185\u4fef\u4ef0\u89d2\uff08\u89d2\u5ea6\uff09\n*   @param[in]      yaw             \u673a\u4f53\u5bfc\u822a\u5750\u6807\u7cfb\u5185\u822a\u5411\u89d2\uff08\u89d2\u5ea6\uff09\n*   @retval         0               \u6b63\u5e38\n*   @retval         1               \u9519\u8bef\n*/\nint euler_to_quaternion_bn(\n\tVector4d* q,\n\tconst double roll,\n\tconst double pitch,\n\tconst double yaw)\n{\n\tMatrix3d Rnb;\n\trotation_navigation_to_body(&Rnb, roll, pitch, yaw);\n\t//cout << R << endl;\n\t//cin.get();\n\tMatrix3d Rbn;\n\tRbn = Rnb.transpose();\n\trotation_to_quaternion(q, Rbn);\n\tif (fabs(roll) < 1e-4 && fabs(pitch) < 1e-4 && fabs(yaw) < 1e-4) {\n\t\t(*q) << 0, 0, 0, 0;\n\t\t(*q)(0) = 1;\n\t}\n\t\t\n\treturn 0;\n}\n\n\n// --------------------------------------------------------------------------------------------------------------------------------\n/**\n*   @brief          \u7531\u4ece\u8f7d\u4f53\u7cfb\u5230\u5bfc\u822a\u7cfb\u7684\u8f6c\u52a8\u56db\u5143\u6570\u6c42\u6b27\u62c9\u89d2\n*   @details        \u7531\u4ece\u8f7d\u4f53\u7cfb\u5230\u5bfc\u822a\u7cfb\u7684\u8f6c\u52a8\u56db\u5143\u6570\u6c42\u6b27\u62c9\u89d2\n*   @param[out]     roll            \u673a\u4f53\u5bfc\u822a\u5750\u6807\u7cfb\u5185\u6a2a\u6eda\u89d2\uff08\u89d2\u5ea6\uff09\n*   @param[out]     pitch           \u673a\u4f53\u5bfc\u822a\u5750\u6807\u7cfb\u5185\u4fef\u4ef0\u89d2\uff08\u89d2\u5ea6\uff09\n*   @param[out]     yaw             \u673a\u4f53\u5bfc\u822a\u5750\u6807\u7cfb\u5185\u822a\u5411\u89d2\uff08\u89d2\u5ea6\uff09\n*   @param[in]      q               \u56db\u5143\u6570:4\u7ef4\u5411\u91cf\n*   @retval         0               \u6b63\u5e38\n*   @retval         1               \u9519\u8bef\n*/\nint quaternion_bn_to_euler(\n\tdouble* roll,\n\tdouble* pitch,\n\tdouble* yaw,\n\tconst Vector4d& q)//\u4e0d\u52a0'&'\u4f1a\u62a5\u9519\uff1a\u5177\u6709 __declspec(align('16')) \u7684\u5f62\u53c2\u5c06\u4e0d\u88ab\u5bf9\u9f50\n{\n\tMatrix3d Rbn;\n\tquaternion_to_rotation(&Rbn, q);\n\n\trotation_nb_to_euler(roll, pitch, yaw, Rbn.transpose());\n\n\treturn 0;\n}\n\n\n// --------------------------------------------------------------------------------------------------------------------------------\n/**\n*   @brief          \u56db\u5143\u6570\u5f52\u4e00\u5316\n*   @details        \u56db\u5143\u6570\u5f52\u4e00\u5316\n*   @param[out]     qout            \u5f52\u4e00\u5316\u540e\u7684\u56db\u5143\u6570\n*   @param[in]      qin             \u56db\u5143\u6570:4\u7ef4\u5411\u91cf\n*   @retval         0               \u6b63\u5e38\n*   @retval         1               \u9519\u8bef\n*/\n\nint quaterntion_normalized(\n\tVector4d* qout,\n\tconst Vector4d& qin)\n{\n\n\tdouble q0, q1, q2, q3;\n\n\tq0 = qin(0) / qin.norm();\n\tq1 = qin(1) / qin.norm();\n\tq2 = qin(2) / qin.norm();\n\tq3 = qin(3) / qin.norm();\n\t(*qout)<< q0, q1, q2, q3;\n\n\treturn 0;\n}", "meta": {"hexsha": "204761b5b9518b6a443bc3b6925a52f86d2902fa", "size": 16883, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Source/Tools/coordinate.cpp", "max_stars_repo_name": "ahhbliulei/Fast-Combat-Simulation", "max_stars_repo_head_hexsha": "8aa3b8800d33141e855c765d4e23875fb160c8a1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2021-08-22T14:32:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-15T03:13:56.000Z", "max_issues_repo_path": "Source/Tools/coordinate.cpp", "max_issues_repo_name": "xuanafeu/Fast-Combat-Simulation", "max_issues_repo_head_hexsha": "41d2156fe98c5135cb9d813b5364b8be65e7f5a2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-01T09:53:11.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-04T14:58:10.000Z", "max_forks_repo_path": "Source/Tools/coordinate.cpp", "max_forks_repo_name": "xuanafeu/Fast-Combat-Simulation", "max_forks_repo_head_hexsha": "41d2156fe98c5135cb9d813b5364b8be65e7f5a2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-18T10:20:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-18T10:20:55.000Z", "avg_line_length": 29.6713532513, "max_line_length": 131, "alphanum_fraction": 0.4499200379, "num_tokens": 7249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.48371002990031026}}
{"text": "#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 <pybind11/pybind11.h>\n\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Constrained_Delaunay_triangulation_2.h>\n#include <CGAL/Triangulation_conformer_2.h>\n#include <CGAL/Delaunay_mesher_2.h>\n#include <CGAL/Delaunay_mesh_face_base_2.h>\n#include <CGAL/Delaunay_mesh_vertex_base_2.h>\n#include <CGAL/Delaunay_mesh_size_criteria_2.h>\n#include <CGAL/lloyd_optimize_mesh_2.h>\n\nnamespace py = pybind11;\n\nusing K = CGAL::Exact_predicates_inexact_constructions_kernel;\nusing Vb = CGAL::Delaunay_mesh_vertex_base_2<K>;\nusing Fb = CGAL::Delaunay_mesh_face_base_2<K>;\nusing Tds = CGAL::Triangulation_data_structure_2<Vb, Fb>;\nusing CDT = CGAL::Constrained_Delaunay_triangulation_2<K, Tds>;\nusing Criteria = CGAL::Delaunay_mesh_size_criteria_2<CDT>;\nusing Mesher = CGAL::Delaunay_mesher_2<CDT, Criteria>;\n\nusing Point = CDT::Point;\nusing Vertex_handle = CDT::Vertex_handle;\n\ntemplate <typename T>\nclass TypedInputIterator\n{\npublic:\n    using iterator_category = std::input_iterator_tag;\n    using difference_type = std::ptrdiff_t;\n    using value_type = T;\n    using pointer = T*;\n    using reference = T&;\n\n    explicit TypedInputIterator(py::iterator& py_iter) :\n        py_iter_(py_iter)\n    {\n    }\n\n    explicit TypedInputIterator(py::iterator&& py_iter) :\n        py_iter_(py_iter)\n    {\n    }\n\n    value_type operator*()\n    {\n        return (*py_iter_).template cast<value_type>();\n    }\n\n    TypedInputIterator operator++(int)\n    {\n        auto copy = *this;\n        ++py_iter_;\n        return copy;\n    }\n\n    TypedInputIterator& operator++()\n    {\n        ++py_iter_;\n        return *this;\n    }\n\n    bool operator!=(TypedInputIterator &rhs)\n    {\n        return py_iter_ != rhs.py_iter_;\n    }\n\n    bool operator==(TypedInputIterator &rhs)\n    {\n        return py_iter_ == rhs.py_iter_;\n    }\n\nprivate:\n    py::iterator py_iter_;\n};\n\nPYBIND11_MODULE(cgal_mesher, m)\n{\n    py::class_<Point>(m, \"Point\")\n            .def(py::init<int, int>(),  py::arg(\"x\"), py::arg(\"y\"))\n            .def(py::init<double, double>(), py::arg(\"x\"), py::arg(\"y\"))\n            .def_property_readonly(\"x\", &Point::x)\n            .def_property_readonly(\"y\", &Point::y)\n            .def(\"__repr__\",\n            [](const Point &p) {\n                std::string r(\"Point(\");\n                r += boost::lexical_cast<std::string>(p.x());\n                r += \", \";\n                r += boost::lexical_cast<std::string>(p.y());\n                r += \")\";\n                return r;\n            })\n            ;\n\n    py::class_<Vertex_handle>(m, \"VertexHandle\");\n\n    py::class_<CDT>(m, \"ConstrainedDelaunayTriangulation\")\n            .def(py::init())\n            .def(\"insert\", [](CDT & cdt, const Point & p) { return cdt.insert(p); })\n            .def(\"insert_constraint\",\n                 [](CDT & cdt, Vertex_handle a, Vertex_handle b)\n                 {\n                     cdt.insert_constraint(a, b);\n                 })\n            .def(\"remove\", &CDT::remove)\n            .def(\"number_of_vertices\", &CDT::number_of_vertices)\n            .def(\"number_of_faces\", &CDT::number_of_faces)\n            .def(\"vertices\", [](CDT & cdt) -> py::iterator\n                 {\n                     return py::make_iterator(cdt.vertices_begin(), cdt.vertices_end());\n                 })\n            ;\n\n    m.def(\"make_conforming_delaunay\", &CGAL::make_conforming_Delaunay_2<CDT>,\n          py::arg(\"cdt\")\n    );\n\n    m.def(\"make_conforming_gabriel\", &CGAL::make_conforming_Gabriel_2<CDT>,\n        py::arg(\"cdt\")\n    );\n\n    py::class_<Criteria>(m, \"Criteria\")\n            .def(py::init<double, double>(),\n                 py::arg(\"aspect_bound\") = 0.125,\n                 py::arg(\"size_bound\") = 0.0)\n            .def_property(\"size_bound\", &Criteria::size_bound, &Criteria::set_size_bound)\n            .def_property(\"aspect_bound\",\n                          [](const Criteria & c) { c.bound(); },\n                          [](Criteria & c, double bound) { c.set_bound(bound); })\n            ;\n\n    py::class_<Mesher>(m, \"Mesher\")\n            .def(py::init<CDT&>())\n            .def(\"refine_mesh\", &Mesher::refine_mesh)\n            .def_property(\n                \"criteria\",\n                &Mesher::get_criteria,\n                [](Mesher& mesher, const Criteria & criteria)\n                {\n                    mesher.set_criteria(criteria);\n                }\n            )\n            .def_property_readonly(\"seeds\", [](Mesher& mesher) {\n                return py::make_iterator(mesher.seeds_begin(), mesher.seeds_end());\n            })\n            .def(\"seeds_from\", [](Mesher & mesher, py::iterable iterable, bool mark)\n            {\n                py::iterator iterator = py::iter(iterable);\n                TypedInputIterator<Point> points_begin(iterator);\n                TypedInputIterator<Point> points_end(py::iterator::sentinel());\n                mesher.set_seeds(points_begin, points_end, mark);\n            })\n            .def(\"clear_seeds\", &Mesher::clear_seeds)\n            ;\n\n\n    m.def(\"lloyd_optimize\", [](\n        CDT& cdt,\n        int max_iteration_number,\n        double time_limit,\n        double convergence,\n        double freeze_bound)\n        {\n            CGAL::lloyd_optimize_mesh_2(cdt,\n                CGAL::parameters::max_iteration_number = max_iteration_number,\n                CGAL::parameters::time_limit = time_limit,\n                CGAL::parameters::convergence = convergence,\n                CGAL::parameters::freeze_bound = freeze_bound\n            );\n        },\n          py::arg(\"cdt\"),\n          py::arg(\"max_iteration_number\") = 0,\n          py::arg(\"time_limit\") = 0.0,\n          py::arg(\"convergence\") = 0.001,\n          py::arg(\"freeze_bound\") = 0.001\n    );\n}\n", "meta": {"hexsha": "a8626ebc0ed3af1075d58376681993b2905258a3", "size": 5862, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CoreSystem/src/wrapper/bindings.cpp", "max_stars_repo_name": "josuehfa/DAASystem", "max_stars_repo_head_hexsha": "a1fe61ffc19f0781eeeddcd589137eefde078a45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-17T01:13:02.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-17T01:13:02.000Z", "max_issues_repo_path": "CoreSystem/src/wrapper/bindings.cpp", "max_issues_repo_name": "josuehfa/DAASystem", "max_issues_repo_head_hexsha": "a1fe61ffc19f0781eeeddcd589137eefde078a45", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CoreSystem/src/wrapper/bindings.cpp", "max_forks_repo_name": "josuehfa/DAASystem", "max_forks_repo_head_hexsha": "a1fe61ffc19f0781eeeddcd589137eefde078a45", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-02T11:11:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-02T11:11:36.000Z", "avg_line_length": 31.3475935829, "max_line_length": 89, "alphanum_fraction": 0.565506653, "num_tokens": 1491, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149978955811, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.4836256150082955}}
{"text": "/*! This file makes the AlgebraicVector class (and thus DA objects) directly interface-able with the Boost ODEINT numerical integration library.\n * It works by defining custom operations to supplement the operator overloads in the AlgebraicVector class natively.\n * The following are defined:\n      - Infinity norm (maximum coefficient in the entire AlgebraicVector)\n      - Resizeable toggle (assumed not - requires the .resize() method in the RHS of the ODE)\n      - The abs() method for the AlgebraicVector class, via modified header files in this repository.\n  !! \n    The vector_space_algebra argument must be used when defining your stepper. Eg:\n            ```typedef runge_kutta_dopri5< AlgebraicVector<DACE::DA>, double, AlgebraicVector<DACE::DA>,\n                                           double, vector_space_algebra > stepper;```\n  !!\n */\n #ifndef __DACELIB_BOOST_COMPAT_H__\n #define __DACELIB_BOOST_COMPAT_H__\n \n #include <boost/operators.hpp> /* Only one explicitly needed here */\n #include <dace/AlgebraicVector.hpp>\n \n namespace boost\n {\n     namespace numeric\n     {\n         namespace odeint\n         {\n             /* Define the infinity norm for the AlgebraicVector.*/\n             template<>\n             struct vector_space_norm_inf<DACE::AlgebraicVector<DACE::DA>>\n             {\n                 typedef double result_type; // DACE only returns abs(DA) as double, no point templating\n                 double operator()(const DACE::AlgebraicVector<DACE::DA>& p) const\n                 {\n                     double maxCoeff = 0.0;\n                     for (size_t i = 0; i < p.size(); ++i) \n                     {\n                         T thisNorm = abs(p[i]); // C\n                         maxCoeff = thisNorm > maxCoeff ? thisNorm : maxCoeff;\n                     }\n                     return maxCoeff;\n                 }\n             };\n             \n             /* Tell BOOST that AlgebraicVector-s resizes. */\n             template <>\n             struct is_resizeable<DACE::AlgebraicVector<DACE::DA>>\n             {\n                 typedef boost::true_type type;\n                 const static bool value = type::value;\n             };\n         }\n    }\n}\n\n#endif\n             \n", "meta": {"hexsha": "71e4aadfc56348cc3c5d81d98bdb556f7c7230c9", "size": 2211, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "tools/odeint/make_compatible_with_odeint.hpp", "max_stars_repo_name": "tylerjackoliver/dace", "max_stars_repo_head_hexsha": "61ed32beb7a301175fa4a7c73ed7e1872dfb8e09", "max_stars_repo_licenses": ["Apache-2.0"], "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/odeint/make_compatible_with_odeint.hpp", "max_issues_repo_name": "tylerjackoliver/dace", "max_issues_repo_head_hexsha": "61ed32beb7a301175fa4a7c73ed7e1872dfb8e09", "max_issues_repo_licenses": ["Apache-2.0"], "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/odeint/make_compatible_with_odeint.hpp", "max_forks_repo_name": "tylerjackoliver/dace", "max_forks_repo_head_hexsha": "61ed32beb7a301175fa4a7c73ed7e1872dfb8e09", "max_forks_repo_licenses": ["Apache-2.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.2, "max_line_length": 144, "alphanum_fraction": 0.5730438716, "num_tokens": 464, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.4836256112376414}}
{"text": "/** @file lane_detection_vrep.hpp\n *  @brief The header file for lane detection when using IMACS framework with VREP simulator\n */\n#ifndef LANEDETECTION_LANE_DETECTION_H_\n#define LANEDETECTION_LANE_DETECTION_H_\n\n#include <iostream>\n#include <Eigen/Eigen>\n#include <opencv2/opencv.hpp>\n#include <cmath>\n#include \"Halide.h\"\n#include \"polyfit.hpp\"\n#include \"config_vrep.hpp\"\n#include \"paths.hpp\"\n\n/// @brief Class for lane Detection in VREP. Inherits the base class pathsIMACS to load the paths to image.\nclass laneDetection : pathsIMACS {\nprivate:\n\n    /**  @brief C++ implementation of defining BEV transformation points\n           Vertices for the BEV transformation are hard-coded in this function.\n         @return    BEV transformation's source and destination vertices\n      */\n    std::vector<std::vector<cv::Point2f>> get_bev_points();\n\t\n    /**  @brief C++ implementation of Bird's Eye View (BEV) Transformation\n           Gets the BEV transformation points, calculates the homography matrix and performs the BEV transformation\n         @param[in] \tsrc            Source image matrix\n         @param[in,out] dst            Destination image matrix\n      */\n    void bev_transform(cv::Mat& src, cv::Mat& dst);\n\t\n    /**  @brief C++ implementation of (Reverse) Bird's Eye View (BEV) Transformation\n           Gets the BEV transformation points, calculates the reverse homography matrix and performs the BEV transformation\n         @param[in,out] \tsrc             Source image matrix\n         @param[in] dst         Destination \timage matrix\n      */\n    void bev_rev_transform(cv::Mat& src, cv::Mat& dst);\n\t\n    /**  @brief C++ implementation of Sliding window lane tracking\n           Find the lane in the image\n         @param[in] \tsrc            Source image matrix\n\t @return lane points in the image\n      */\n    std::vector<std::vector<cv::Point>> sliding_window_lane_tracking(cv::Mat& src);\n\n    /**  @brief C++ implementation of lateral deviation calculation\n           From the given lane points, polyfits the lanes and then finds the deviation of the car from the centre of the lane at the look-ahead distance\n         @param[in] \tleft_lane_inds            left lane (points)\n         @param[in] \tright_lane_inds           right lane (points)\n\t @return lateral deviation of the vehicle with the current heading at the look-ahead distance\n      */\n    std::vector<long double> calculate_lateral_deviation(std::vector<cv::Point> left_lane_inds, \n                                            std::vector<cv::Point> right_lane_inds);\n\n    /**  @brief C++ implementation to overlay the detected lanes onto the original image\n           \n         @param[in] \tlanes            \tdetected lanes\n         @param[in] \tsrc           \t\tsource image\n         @param[in,out]\timg_roi           \tImage with only the RoI\n         @param[in] \timg_warped           \tRoI image after BEV transform\n         @param[in,out]\timg_detected_lanes      Image with the detected lanes\n         @param[in,out]\tdraw_lines           \tImage with lanes drawn\n         @param[in,out]\tdiff_src_rebev          Image with diff_src reverse BEV\n         @param[in,out]\timg_rev_warped          Original image with lines overlayed\n      */\n    void lane_identification(std::vector<std::vector<cv::Point>> lanes, cv::Mat& src, cv::Mat& img_roi, \n                            cv::Mat& img_warped, cv::Mat& img_detected_lanes, \n                            cv::Mat& draw_lines, cv::Mat& diff_src_rebev, cv::Mat& img_rev_warped);\npublic:\n    /// constructor\n    laneDetection();\n    /// destructor\n    ~laneDetection();\n\n    /**  @brief C++ implementation of lane detection pipeline\n           Scales the image, does BEV transformation, Gray-scale conversion, White masking, Image thresholding, Sliding window lane tracking and lateral deviation calculation. Images are also stored in lane_out_img_dir, if RE_DRAW_IMAGE is defined.\n         @param[in] src            Source image Matrix\n         @return    the calculated lateral deviation yL\n      */\n    long double lane_detection_pipeline(cv::Mat src);\n};\n\n#endif\n", "meta": {"hexsha": "f8ce879d6919641e1e90d7f7b79f75ac8cf6966f", "size": 4080, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/LaneDetection/lane_detection_vrep.hpp", "max_stars_repo_name": "sajid-mohamed/imacs", "max_stars_repo_head_hexsha": "25810df31eeeb59c65dea71eb9467bec8fb23dd7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-22T11:18:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-22T11:18:10.000Z", "max_issues_repo_path": "src/LaneDetection/lane_detection_vrep.hpp", "max_issues_repo_name": "sajid-mohamed/imacs", "max_issues_repo_head_hexsha": "25810df31eeeb59c65dea71eb9467bec8fb23dd7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/LaneDetection/lane_detection_vrep.hpp", "max_forks_repo_name": "sajid-mohamed/imacs", "max_forks_repo_head_hexsha": "25810df31eeeb59c65dea71eb9467bec8fb23dd7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-16T20:01:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-16T20:01:45.000Z", "avg_line_length": 48.0, "max_line_length": 248, "alphanum_fraction": 0.6558823529, "num_tokens": 909, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149978955811, "lm_q2_score": 0.640635847978761, "lm_q1q2_score": 0.4836256098287202}}
{"text": "/* Copyright (c) 2016, Julian Straub <jstraub@csail.mit.edu>\n * Licensed under the MIT license. See the license file LICENSE.\n */\n#include <iostream>\n#include <sstream>\n#include <sys/time.h>\n//#include <random> // can only use with C++11\n#include <pcl/io/ply_io.h>\n#include <pcl/point_types.h>\n#include <pcl/common/transforms.h>\n#include <pcl/features/normal_3d.h>\n#include <pcl/filters/statistical_outlier_removal.h>\n\n#include \"cudaPcl/pinhole.h\"\n\n#include <boost/program_options.hpp>\n#include <boost/random.hpp>\n\nnamespace po = boost::program_options;\nusing std::cout;\nusing std::endl;\n\n#include <jsCore/timer.hpp>\n\nfloat ToDeg(float rad) {\n  return rad*180./M_PI;\n}\nfloat ToRad(float deg) {\n  return deg/180.*M_PI;\n}\ndouble ToDeg(double rad) {\n  return rad*180./M_PI;\n}\ndouble ToRad(double deg) {\n  return deg/180.*M_PI;\n}\n\nEigen::Vector3d ComputePcMean(pcl::PointCloud<pcl::PointXYZRGB>&\n    pc) {\n  // take 3 values (x,y,z of normal) with an offset of 4 values (x,y,z\n  // and one float which is undefined) and the step is 12 (4 for xyz, 4\n  // for normal xyz and 4 for curvature and rgb).\n  Eigen::MatrixXf xyz = pc.getMatrixXfMap(3, 8, 0); // this works for PointXYZRGB?\n  Eigen::Vector3d mean =  Eigen::Vector3d::Zero();\n\n  for (size_t i=0; i<xyz.cols(); ++i) {\n    mean += xyz.col(i).cast<double>();\n  }\n  return  mean / xyz.cols();\n}\n\nEigen::Matrix3d ComputePcCov(pcl::PointCloud<pcl::PointXYZRGB>&\n    pc) {\n\n  // take 3 values (x,y,z of normal) with an offset of 4 values (x,y,z\n  // and one float which is undefined) and the step is 12 (4 for xyz, 4\n  // for normal xyz and 4 for curvature and rgb).\n  Eigen::MatrixXf xyz = pc.getMatrixXfMap(3, 8, 0); // this works for PointXYZRGB?\n  Eigen::Vector3d mean = ComputePcMean(pc);\n  Eigen::Matrix3d S = Eigen::Matrix3d::Zero();\n  for (size_t i=0; i<xyz.cols(); ++i) {\n    S += (xyz.col(i).cast<double>()-mean)*(xyz.col(i).cast<double>()-mean).transpose();\n  }\n  return  S / (xyz.cols()-1);\n}\n\nvoid SampleTransformation(float angle, float translation, \n    Eigen::Matrix3f& R, Eigen::Vector3f& t) {\n  // Using boost here because C11 and CUDA seem to have troubles.\n  timeval tNow; \n  gettimeofday(&tNow, NULL);\n  boost::mt19937 gen(tNow.tv_usec);\n  boost::normal_distribution<> N(0,1);\n  // Sample axis of rotation:\n  Eigen::Vector3f axis(N(gen), N(gen), N(gen));\n  axis /= axis.norm();\n  // Construct rotation:\n  Eigen::AngleAxisf aa(ToRad(angle), axis);\n  Eigen::Quaternionf q(aa);\n  R = q.matrix();\n  // Sample translation on sphere with radius translation:\n  t = Eigen::Vector3f(N(gen), N(gen), N(gen));\n  t *= translation / t.norm();\n\n//  std::cout << \"sampled random transformation:\\n\" \n//    << R << std::endl << t.transpose() << std::endl;\n}\n\nbool RenderPointCloudNoisy(const pcl::PointCloud<pcl::PointXYZRGBNormal>& pcIn,\n    const cudaPcl::Pinhole& c, pcl::PointCloud<pcl::PointXYZRGBNormal>&\n    pcOut, uint32_t nUpsample) {\n\n  // Transform both points by T as well as surface normals by R\n  // manually since the standard transformPointCloud does not seem to\n  // touch the Surface normals.\n  Eigen::MatrixXf d = 1e10*Eigen::MatrixXf::Ones(c.GetH(), c.GetW());\n  Eigen::MatrixXi id = Eigen::MatrixXi::Zero(c.GetH(), c.GetW());\n  uint32_t hits = 0;\n  for (uint32_t i=0; i<pcIn.size(); ++i) {\n    Eigen::Map<const Eigen::Vector3f> pA_W(&(pcIn.at(i).x));\n    Eigen::Vector3f p_W = pA_W;\n    Eigen::Vector3f p_C;\n    Eigen::Vector2i pI;\n    if (c.IsInImage(p_W, &p_C, &pI)) { \n      if (p_C(2) > 0. && d(pI(1),pI(0)) >  p_C(2)) {\n        d(pI(1),pI(0)) = p_C(2);\n        id(pI(1),pI(0)) = i;\n      }\n      ++hits;\n    }\n  }\n//  std::cout << \" # hits: \" << hits \n//    << \" for total number of pixels in output camera: \" << c.GetSize()\n//    << \" percentage: \" << (100.*hits/float(c.GetSize())) << std::endl;\n  timeval tNow; \n  gettimeofday(&tNow, NULL);\n  boost::mt19937 gen(tNow.tv_usec);\n  Eigen::Vector3f d_C;\n  d_C << 0.,0.,1.;\n  pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZRGB>);\n  uint32_t n_sampled = 0;\n  for (uint32_t i=0; i<c.GetW(); ++i)\n    for (uint32_t j=0; j<c.GetH(); ++j) \n      if (d(j,i) < 100.) {\n//        Eigen::Vector3f n_C = c.GetR_C_W() * Eigen::Map<const\n//          Eigen::Vector3f>(pcIn.at(id(j,i)).normal);\n        Eigen::Vector3f n_C =  Eigen::Map<const\n          Eigen::Vector3f>(pcIn.at(id(j,i)).normal);\n        Eigen::Vector3f p_C = c.UnprojectToCameraCosy(i,j,d(j,i));\n        double dot = n_C.transpose()*d_C;\n        double theta = acos(std::min(std::max(dot, -1.),1.));\n        if (ToDeg(theta) < 80.) {\n          //http://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=6375037\n          double sig_L = (0.8+0.035*theta/(M_PI*0.5-theta))* p_C(2)/c.GetF();\n          double sig_z =0.0012 + 0.0019*(p_C(2)-0.4)*(p_C(2)-0.4);\n          if (ToDeg(theta) > 60.) {\n            sig_z += 0.0001/sqrt(p_C(2))*theta*theta/((M_PI*0.5-theta)\n                *(M_PI*0.5-theta));\n          }\n //        std::cout << sig_L << \" \" << sig_z << std::endl;\n          boost::normal_distribution<> N_L(0,sig_L);\n          boost::normal_distribution<> N_z(0,sig_z);\n          for (uint32_t k=0; k< nUpsample; ++k) {\n            pcl::PointXYZRGB pB;\n            pB.rgb = pcIn.at(id(j,i)).rgb;\n            Eigen::Map<Eigen::Vector3f> p_Cout(&(pB.x));\n            p_Cout =  p_C;\n//            if (i%10==0) std::cout << p_Cout.transpose() << \" \";\n            p_Cout(0) += N_L(gen);\n            p_Cout(1) += N_L(gen);\n            p_Cout(2) += N_z(gen);\n//            if (p_Cout.norm() > 10.)\n              //          if (i%10==0) \n//              std::cout << p_Cout.transpose() << \" \" << sig_z << \" \" << sig_L \n//                << \" \" << ToDeg(theta) << std::endl;\n            cloud->push_back(pB);\n            ++n_sampled;\n          }\n        } else {\n          pcl::PointXYZRGB pB;\n          pB.rgb = pcIn.at(id(j,i)).rgb;\n          Eigen::Map<Eigen::Vector3f>(&(pB.x)) = p_C;\n          cloud->push_back(pB);\n        }\n      }\n  if (cloud->size() < pcIn.size()/10) return false;\n  std::cout << \" output pointcloud size is: \" << pcOut.size() \n    << \" percentage of input cloud: \"\n    << (100.*pcOut.size()/float(pcIn.size()))\n    << \" sampled at total of \" << 100.*n_sampled/float(pcOut.size()) << \"%.\"<< std::endl;\n\n  pcl::StatisticalOutlierRemoval<pcl::PointXYZRGB> sor;\n  sor.setInputCloud (cloud);\n  sor.setMeanK (50);\n  sor.setStddevMulThresh (1.0);\n  pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud_f(new pcl::PointCloud<pcl::PointXYZRGB>);\n  sor.filter (*cloud_f);\n\n//  Eigen::Matrix3d S = ComputePcCov(*cloud_f);\n//  Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> eig(S);\n//  std::cout << eig.eigenvalues().array().sqrt().matrix().transpose() << std::endl;\n//  if (!(eig.eigenvalues().array().sqrt() > 0.10).all()) \n//    return false;\n  \n  // Extract surface normals\n  pcl::NormalEstimation<pcl::PointXYZRGB, pcl::Normal> ne;\n  ne.setInputCloud (cloud_f);\n  pcl::search::KdTree<pcl::PointXYZRGB>::Ptr tree (new pcl::search::KdTree<pcl::PointXYZRGB> ());\n  ne.setSearchMethod (tree);\n  pcl::PointCloud<pcl::Normal>::Ptr cloud_normals (new pcl::PointCloud<pcl::Normal>);\n  ne.setKSearch(100);\n  ne.compute (*cloud_normals);\n\n  pcOut.clear();\n  for (uint32_t i=0; i<cloud_f->size(); ++i) {\n    pcl:: PointXYZRGBNormal p;\n    Eigen::Map<Eigen::Vector3f>(p.normal) = \n    Eigen::Map<Eigen::Vector3f>(cloud_normals->at(i).normal);\n    Eigen::Map<Eigen::Vector3f>(&(p.x)) = Eigen::Map<Eigen::Vector3f>(&(cloud_f->at(i).x));\n    p.rgb = cloud_f->at(i).rgb;\n    pcOut.push_back(p);\n  }\n  return true;\n}\n\n\nbool RenderPointCloud(const pcl::PointCloud<pcl::PointXYZRGBNormal>& pcIn,\n    const cudaPcl::Pinhole& c, pcl::PointCloud<pcl::PointXYZRGBNormal>&\n    pcOut) {\n  // Transform both points by T as well as surface normals by R\n  // manually since the standard transformPointCloud does not seem to\n  // touch the Surface normals.\n  Eigen::MatrixXf d = 1e10*Eigen::MatrixXf::Ones(c.GetH(), c.GetW());\n  Eigen::MatrixXi id = Eigen::MatrixXi::Zero(c.GetH(), c.GetW());\n  uint32_t hits = 0;\n  for (uint32_t i=0; i<pcIn.size(); ++i) {\n    Eigen::Map<const Eigen::Vector3f> pA_W(&(pcIn.at(i).x));\n    Eigen::Vector3f p_W = pA_W;\n    Eigen::Vector3f p_C;\n    Eigen::Vector2i pI;\n    if (c.IsInImage(p_W, &p_C, &pI)) { \n      if (d(pI(1),pI(0)) >  p_C(2)) {\n        d(pI(1),pI(0)) = p_C(2);\n        id(pI(1),pI(0)) = i;\n      }\n      ++hits;\n    }\n  }\n//  std::cout << \" # hits: \" << hits \n//    << \" for total number of pixels in output camera: \" << c.GetSize()\n//    << \" percentage: \" << (100.*hits/float(c.GetSize())) << std::endl;\n\n  pcOut.clear();\n  for (uint32_t i=0; i<c.GetW(); ++i)\n    for (uint32_t j=0; j<c.GetH(); ++j) \n      if (d(j,i) < 100.) {\n        pcl::PointXYZRGBNormal pB;\n        Eigen::Map<Eigen::Vector3f> p_C(&(pB.x));\n        p_C = c.UnprojectToCameraCosy(i,j,d(j,i));\n        Eigen::Map<Eigen::Vector3f>(pB.normal) = \n          c.GetR_C_W() * Eigen::Map<const\n          Eigen::Vector3f>(pcIn.at(id(j,i)).normal);\n        pB.rgb = pcIn.at(id(j,i)).rgb;\n        pcOut.push_back(pB);\n      }\n//  std::cout << \" output pointcloud size is: \" << pcOut.size() \n//    << \" percentage of input cloud: \"\n//    << (100.*pcOut.size()/float(pcIn.size())) << std::endl;\n  return pcOut.size() > (pcIn.size()/10);\n}\n\nuint32_t VisiblePointsOfPcInCam(const\n    pcl::PointCloud<pcl::PointXYZRGBNormal>& pc, \n    const Eigen::Matrix3f& R_PC_W, const Eigen::Vector3f& t_PC_W, const\n    cudaPcl::Pinhole& c) {\n  uint32_t hits =0;\n  for (uint32_t i=0; i<pc.size(); ++i) {\n    Eigen::Vector3f p_PC = Eigen::Map<const Eigen::Vector3f> (&(pc.at(i).x));\n    Eigen::Vector3f p_W = R_PC_W.transpose() * (p_PC - t_PC_W);\n    if (c.IsInImage(p_W, NULL, NULL)) {\n      ++hits;\n    }\n  }\n  return hits;\n}\n\n\nint main (int argc, char** argv)\n{\n  // Declare the supported options.\n  po::options_description desc(\"Render a point cloud from a different pose.\");\n  desc.add_options()\n    (\"help,h\", \"produce help message\")\n    (\"input,i\", po::value<string>(),\"path to input point cloud\")\n    (\"output,o\", po::value<string>(),\"path to output transformed point cloud\")\n    (\"angle,a\", po::value<double>(),\"magnitude of rotation (deg)\")\n    (\"translation,t\", po::value<double>(),\"magnitude of translation (m)\")\n    (\"min,m\", po::value<double>(),\"minimum overlap to be accepted (%)\")\n    (\"local,l\", \"simulate local alignment problem i.e. do not transform the pointclouds by a random transformation\")\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  double angle = 10.; // In degree\n  double translation = 1.0;\n  double min_overlap = 50.;\n  string inputPath = \"./file.ply\";\n  string outputPath = \"./out\";\n  if(vm.count(\"input\")) inputPath = vm[\"input\"].as<string>();\n  if(vm.count(\"output\")) outputPath = vm[\"output\"].as<string>();\n  if(vm.count(\"angle\")) angle = vm[\"angle\"].as<double>();\n  if(vm.count(\"min\")) min_overlap = vm[\"min\"].as<double>();\n  if(vm.count(\"translation\")) translation = vm[\"translation\"].as<double>();\n\n  std::stringstream ssOutPathA;\n  std::stringstream ssOutPathB;\n  std::stringstream ssTransformationAFile;\n  std::stringstream ssTransformationBFile;\n  std::stringstream ssTransformationTotalFile;\n  ssOutPathA << outputPath << \"_A_angle_\" << angle << \"_translation_\" <<\n    translation << \".ply\";\n  ssOutPathB << outputPath << \"_B_angle_\" << angle << \"_translation_\" <<\n    translation << \".ply\";\n  ssTransformationAFile << outputPath << \"_angle_\" << angle <<\n    \"_translation_\" << translation << \"_Transformation_A_W\" << \".csv\";\n  ssTransformationBFile << outputPath << \"_angle_\" << angle <<\n    \"_translation_\" << translation << \"_Transformation_B_W\" << \".csv\";\n  ssTransformationTotalFile << outputPath << \"_angle_\" << angle <<\n    \"_translation_\" << translation << \"_TrueTransformation\" << \".csv\";\n\n  std::string outputPathA = ssOutPathA.str();\n  std::string outputPathB = ssOutPathB.str();\n  std::string transformationAOutputPath= ssTransformationAFile.str();\n  std::string transformationBOutputPath= ssTransformationBFile.str();\n  std::string transformationTotalOutputPath = ssTransformationTotalFile.str();\n\n  // Load point cloud.\n  pcl::PointCloud<pcl::PointXYZRGBNormal> pcIn, pcOutA, pcOutB;\n  pcl::PLYReader reader;\n  int err = reader.read(inputPath, pcIn);\n  if (err) {\n    std::cout << \"error reading \" << inputPath << std::endl;\n    return err;\n  } else {\n    std::cout << \"loaded pc from \" << inputPath << \": \" << pcIn.width << \"x\"\n      << pcIn.height << std::endl;\n  }\n\n  std::cout<< \" input pointcloud from \"<<inputPath<<std::endl;\n  std::cout<< \"  angular magnitude \"<< angle <<std::endl;\n  std::cout<< \"  translational magnitude \"<< translation <<std::endl;\n\n  uint32_t w = 320;\n  uint32_t h = 280;\n  float f = 540.;\n  Eigen::Matrix3f R_A_W, R_B_W;\n  Eigen::Vector3f t_A_W, t_B_W;\n  bool succA = false;\n  bool succB = false;\n  double overlap = 0.;\n  uint32_t attemptsOuter = 0;\n  uint32_t attempts = 0;\n  do {\n    overlap = 0.;\n    attempts = 0;\n    do {\n      // sample pc A\n      R_A_W = Eigen::Matrix3f::Identity();\n      t_A_W = Eigen::Vector3f::Zero();\n//      SampleTransformation(angle, translation, R_A_W, t_A_W);\n      cudaPcl::Pinhole camA(R_A_W, t_A_W, f, w, h);\n      if (!RenderPointCloud(pcIn, camA, pcOutA))\n        continue;\n      // sample pc B\n      SampleTransformation(angle, translation, R_B_W, t_B_W);\n      cudaPcl::Pinhole camB(R_B_W, t_B_W, f, w, h);\n      if (!RenderPointCloud(pcIn, camB, pcOutB))\n        continue;\n\n      uint32_t hitsAinB = VisiblePointsOfPcInCam(pcOutA, R_A_W, t_A_W, camB);\n      uint32_t hitsBinA = VisiblePointsOfPcInCam(pcOutB, R_B_W, t_B_W, camA);\n\n      overlap = std::min(100*hitsAinB/float(pcOutA.size()),\n          100*hitsBinA/float(pcOutB.size()));\n\n      ++ attempts;\n      if (attempts%20 == 0) {\n        std::cout << \".\";\n        std::cout.flush();\n      }\n    } while(overlap < min_overlap && attempts < 1000);\n    std::cout << std::endl;\n    std::cout << \"overlap: \" << overlap \n      << \"% attempt: \" << attempts<< std::endl;\n    if (attempts >= 1000) return 1;\n    // Now sample point clouds from those views.\n    cudaPcl::Pinhole camA(R_A_W, t_A_W, f, w, h);\n    succA = RenderPointCloudNoisy(pcIn, camA, pcOutA, 2);\n    cudaPcl::Pinhole camB(R_B_W, t_B_W, f, w, h);\n    succB = RenderPointCloudNoisy(pcIn, camB, pcOutB, 2);\n  } while ((!succA || !succB) && attemptsOuter < 100);\n\n  {\n    Eigen::Quaternionf q(R_A_W);\n    Eigen::Vector3f t = t_A_W;\n    std::ofstream out(transformationAOutputPath.c_str());\n    out << \"q_w q_x q_y q_z t_x t_y t_z size\" << std::endl;\n    out << q.w() << \" \" << q.x() << \" \" << q.y() << \" \" << q.z() << \" \" \n      << t(0) << \" \" << t(1) << \" \" << t(2) << \" \" \n      << \" \" << pcOutA.size();\n    out.close();\n  }\n  {\n    Eigen::Quaternionf q(R_B_W);\n    Eigen::Vector3f t = t_B_W;\n    std::ofstream out(transformationBOutputPath.c_str());\n    out << \"q_w q_x q_y q_z t_x t_y t_z size\" << std::endl;\n    out << q.w() << \" \" << q.x() << \" \" << q.y() << \" \" << q.z() << \" \" \n      << t(0) << \" \" << t(1) << \" \" << t(2) << \" \" \n      << \" \" << pcOutB.size();\n    out.close();\n  }\n\n  // If we want to simulate a global alignment problem sample another\n  // intermediate random transformation and apply it to pointcloud B as\n  // well as the global true transformation.\n  if(!vm.count(\"local\")) {\n    // Now sample another transformation of the same parameters to\n    // transform pcB\n    Eigen::Matrix3f R_B_B;\n    Eigen::Vector3f t_B_B;\n    SampleTransformation(angle, translation, R_B_B, t_B_B);\n    // Transform pc B\n    for (uint32_t i=0; i<pcOutB.size(); ++i) {\n      Eigen::Map<Eigen::Vector3f> p(&(pcOutB.at(i).x));\n      p = R_B_B * p + t_B_B;\n      Eigen::Map<Eigen::Vector3f> n(pcOutB.at(i).normal);\n      n = R_B_B*n;\n    }\n    // chain the new transformation into the global transformation.\n    R_B_W = R_B_B*R_B_W;\n    t_B_W = R_B_B*t_B_W + t_B_B;\n  }\n  // Write the Point clouds to files.\n  pcl::PLYWriter writer;\n  writer.write(outputPathA, pcOutA, false, false);\n  writer.write(outputPathB, pcOutB, false, false);\n\n  // Compute the final relative transformation between the PCs in the\n  // as they are saved to file. This is the transformation that any\n  // alignment algorithm needs to find.\n  Eigen::Matrix3f R_B_A = R_B_W * R_A_W.transpose();\n  Eigen::Vector3f t_B_A = - R_B_W * R_A_W.transpose() * t_A_W + t_B_W;\n  Eigen::Quaternionf q(R_B_A);\n  Eigen::Vector3f t = t_B_A;\n\n  std::cout << \"magnitude of rotation: \" << ToDeg(acos(q.w())*2.) \n    << \" magnitude of translation: \" << t_B_A.norm() << std::endl;\n\n  std::ofstream out(transformationTotalOutputPath.c_str());\n  out << \"q_w q_x q_y q_z t_x t_y t_z overlap sizeA sizeB\" << std::endl;\n  out << q.w() << \" \" << q.x() << \" \" << q.y() << \" \" << q.z() << \" \" \n    << t(0) << \" \" << t(1) << \" \" << t(2) << \" \" \n    << overlap << \" \" << pcOutA.size() << \" \" << pcOutB.size();\n  out.close();\n\n  std::cout<< \" output to \"<<outputPathA<<std::endl << \" and to \" << outputPathB << std::endl;\n  std::cout<< \" sampled total transformation to \" << transformationTotalOutputPath << std::endl;\n  std::cout<< \" sampled transformation of rendering T_A_W to \"\n    << transformationAOutputPath << std::endl;\n  std::cout<< \" sampled transformation of rendering T_B_W to \"\n    << transformationBOutputPath << std::endl;\n  return 0;\n}\n\n", "meta": {"hexsha": "27d192895c97400e164c84f9504bd6caddb54563", "size": 17359, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/renderPcFromPc.cpp", "max_stars_repo_name": "jstraub/cudaPcl", "max_stars_repo_head_hexsha": "10b61d66f83c664942f1e7b6ee574246df8d8922", "max_stars_repo_licenses": ["MIT-feh"], "max_stars_count": 84.0, "max_stars_repo_stars_event_min_datetime": "2015-04-05T16:17:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T13:40:51.000Z", "max_issues_repo_path": "src/renderPcFromPc.cpp", "max_issues_repo_name": "jstraub/cudaPcl", "max_issues_repo_head_hexsha": "10b61d66f83c664942f1e7b6ee574246df8d8922", "max_issues_repo_licenses": ["MIT-feh"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2016-03-31T02:35:08.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-04T06:50:53.000Z", "max_forks_repo_path": "src/renderPcFromPc.cpp", "max_forks_repo_name": "jstraub/cudaPcl", "max_forks_repo_head_hexsha": "10b61d66f83c664942f1e7b6ee574246df8d8922", "max_forks_repo_licenses": ["MIT-feh"], "max_forks_count": 28.0, "max_forks_repo_forks_event_min_datetime": "2015-06-19T18:11:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-02T08:21:22.000Z", "avg_line_length": 37.5735930736, "max_line_length": 116, "alphanum_fraction": 0.608733222, "num_tokens": 5397, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.483625597584243}}
{"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// This program will make use of the ATOM solver to construct a transfer trajectory\n// between two points in space. Only a single transfer segment is simulated here, that is, no multitargeting.\n// There is just one departure and one arrival object considered in the simulation. The object TLEs are\n// taken from a catalog file. The user can specify which object will be departure and which will be arrival\n// along with the time of flight. \n\n#include <iostream>\n#include <sstream>\n#include <stdexcept>\n#include <string>\n#include <vector>\n#include <fstream>\n#include <exception>\n#include <cstdlib>\n#include <iterator>\n\n#include <libsgp4/Globals.h>\n#include <libsgp4/SGP4.h>\n#include <libsgp4/Tle.h>\n\n#include <Atom/atom.hpp>\n#include <Atom/convertCartesianStateToTwoLineElements.hpp>\n\n#include <Astro/orbitalElementConversions.hpp>\n\n#include <SML/sml.hpp>\n#include <SML/constants.hpp>\n#include <SML/basicFunctions.hpp>\n#include <SML/linearAlgebra.hpp>\n\n#include <boost/array.hpp>\n\n#include </usr/local/abhi/pykep/src/lambert_problem.cpp>\n#include </usr/local/abhi/pykep/src/lambert_problem.h>\n#include </usr/local/abhi/pykep/src/keplerian_toolbox.h>\n\n\ntypedef double Real;\ntypedef std::vector < Real > Vector6;\ntypedef std::vector < Real > Vector3;\ntypedef std::vector < Real > Vector2;\ntypedef std::vector < std::vector < Real > > Vector2D;\ntypedef boost::array < Real, 3 > array3; \n\n//! Remove newline characters from string.\nvoid removeNewline( std::string& string )\n{\n    string.erase( std::remove( string.begin( ), string.end( ), '\\r' ), string.end( ) );\n    string.erase( std::remove( string.begin( ), string.end( ), '\\n' ), string.end( ) );\n}\n\n//! Convert SGP4 ECI object to state vector.\nVector6 getStateVector( const Eci state )\n{\n    Vector6 result( 6 );\n    result[ 0 ] = state.Position( ).x;\n    result[ 1 ] = state.Position( ).y;\n    result[ 2 ] = state.Position( ).z;\n    result[ 3 ] = state.Velocity( ).x;\n    result[ 4 ] = state.Velocity( ).y;\n    result[ 5 ] = state.Velocity( ).z;\n    return result;\n}\n\nVector6 getStateVectorInMetre( const Eci state )\n{\n    Vector6 result( 6 );\n    result[ 0 ] = state.Position( ).x * 1000.0;\n    result[ 1 ] = state.Position( ).y * 1000.0;\n    result[ 2 ] = state.Position( ).z * 1000.0;\n    result[ 3 ] = state.Velocity( ).x * 1000.0;\n    result[ 4 ] = state.Velocity( ).y * 1000.0;\n    result[ 5 ] = state.Velocity( ).z * 1000.0;\n    return result;\n}\n\nVector6 standardKeplerian( const Vector6 elements )\n{\n    Vector6 result( 6 );\n    result[ 0 ] = elements[ 0 ] / 1000.0;\n    result[ 1 ] = elements[ 1 ];\n    result[ 2 ] = sml::convertRadiansToDegrees( elements[ 2 ] );\n    result[ 3 ] = sml::convertRadiansToDegrees( elements[ 3 ] );\n    result[ 4 ] = sml::convertRadiansToDegrees( elements[ 4 ] );\n    result[ 5 ] = sml::convertRadiansToDegrees( elements[ 5 ] );\n    return result;\n}\n\n\nint main( void )\n{\n    // conversion from km to m\n    // const double km2m = 1000; \n    const double Rearth = kXKMPER; // earth radius in km\n    // earth radius and diameter\n    // const double EarthRadius = kXKMPER * km2m; // unit m\n    // const double EarthDiam = 2 * EarthRadius;\n    \n    // grav. parameter 'mu' of earth\n    const double muEarth = kMU*( pow( 10, 9 ) ); // unit m^3/s^2\n    \n    // vectors to store arrival and departure velocities for the transfer trajectory\n    Vector3 DepartureVelocity( 3 );\n    Vector3 ArrivalVelocity( 3 );\n\n    // read the TLE file. Line based parsing, using string streams\n    std::string line;\n    \n    // std::ifstream tlefile( \"../../src/napa_prograde_catalog.txt\" );\n    // const bool is_retro = false;\n\n    std::ifstream tlefile( \"../../src/napa_retrograde_catalog.txt\" );\n    const bool is_retro = true;\n    \n    if( !tlefile.is_open() )\n        perror(\"error while opening file\");\n\n    std::vector < Tle > tleObjects; // vector of TLE objects\n    \n\n    while( !tlefile.eof( ) )\n    {\n        std::vector < std::string > tleStrings;\n\n        std::getline( tlefile, line ); // read line from the catalog file\n        removeNewline( line ); // remove new line characters such as '/n'\n        tleStrings.push_back( line );\n        // std::cout << line << std::endl;\n\n        std::getline( tlefile, line );\n        removeNewline( line );\n        tleStrings.push_back( line );\n        // std::cout << line << std::endl;\n\n        std::getline( tlefile, line );\n        removeNewline( line );\n        tleStrings.push_back( line );\n        // std::cout << line << std::endl << std::endl;\n\n        tleObjects.push_back( Tle( tleStrings[ 0 ], tleStrings[ 1 ], tleStrings[ 2 ] ) );\n    }\n    tlefile.close( );\n    \n    const int DebrisObjects = tleObjects.size( );\n    std::cout << \"Total debris objects = \" << DebrisObjects << std::endl; \n    \n    // some variables for the \"catch\" segment\n    int failCount = 0;\n    int catchDepartureID;\n    int catchArrivalID;\n\n    std::cout.precision( 15 );\n    \n    //*********************** Inputs *********************************************************************************************************//\n    Tle departureObject = tleObjects[ 2 ]; \n    Tle arrivalObject = tleObjects[ 3 ];    \n    DateTime departureEpoch;\n    // departureEpoch.Initialise( 2016, 1, 11, 4, 51, 21, 455936 );\n    departureEpoch.Initialise( 2016, 1, 11, 4, 50, 21, 0 );\n    const double TOF = 15130.0; // time of flight                     \n    //***************************************************************************************************************************************//\n    \n    SGP4 sgp4Departure( departureObject );\n    const Eci tleDepartureState = sgp4Departure.FindPosition( departureEpoch );\n    const Vector6 departureState = getStateVector( tleDepartureState );\n    \n    array3 departurePosition;\n    array3 departureVelocity;\n    for( int j = 0; j < 3; j++ )\n    {\n        departurePosition[ j ] = departureState[ j ];\n        departureVelocity[ j ] = departureState[ j + 3 ];\n    }\n    \n    const int departureObjectId = static_cast< int >( departureObject.NoradNumber( ) );\n    catchDepartureID = departureObjectId; // for the catch segment of the program\n                    \n                    \n    SGP4 sgp4Arrival( arrivalObject );\n    const int arrivalObjectId = static_cast< int >( arrivalObject.NoradNumber( ) );\n    catchArrivalID = arrivalObjectId;\n\n    const DateTime arrivalEpoch = departureEpoch.AddSeconds( TOF );\n    const Eci tleArrivalState = sgp4Arrival.FindPosition( arrivalEpoch );\n    // const Eci tleArrivalState = sgp4Arrival.FindPosition( 0.0 );\n    const Vector6 arrivalState = getStateVector( tleArrivalState );\n\n    array3 arrivalPosition;\n    array3 arrivalVelocity;\n    for( int j = 0; j < 3; j++ )\n    {\n        arrivalPosition[ j ] = arrivalState[ j ];\n        arrivalVelocity[ j ] = arrivalState[ j + 3 ];\n    } \n\n    kep_toolbox::lambert_problem targeter( departurePosition, arrivalPosition, TOF, kMU, is_retro, 5 );\n    const int numberOfSolutions = targeter.get_v1( ).size( );\n    std::vector< array3 > departureDeltaVs( numberOfSolutions ); // delta-V components at the departure point\n    std::vector< array3 > arrivalDeltaVs( numberOfSolutions );                \n    std::vector< Real > transferDeltaVs( numberOfSolutions ); // magnitude of the total delta-V of one transfer between two points\n\n    for ( int j = 0; j < numberOfSolutions; j++ )\n    {\n        array3 transferDepartureVelocity = targeter.get_v1( )[ j ]; // velocity of the s/c at the departure point in the transfer orbit\n        array3 transferArrivalVelocity = targeter.get_v2( )[ j ];\n\n        departureDeltaVs[ j ] = sml::add( transferDepartureVelocity, sml::multiply( departureVelocity, -1.0 ) );\n        arrivalDeltaVs[ j ] = sml::add( transferArrivalVelocity, sml::multiply( arrivalVelocity, -1.0 ) );\n\n        transferDeltaVs[ j ] = sml::norm< Real >( departureDeltaVs[ j ] ) + sml::norm< Real >( arrivalDeltaVs[ j ] );\n    }\n\n    const std::vector< Real >::iterator minDeltaVIterator = std::min_element( transferDeltaVs.begin( ), transferDeltaVs.end( ) );\n    const int minimumDeltaVIndex = std::distance( transferDeltaVs.begin( ), minDeltaVIterator );\n\n    Real lambertDepartureBurn = sml::norm< Real >( departureDeltaVs[ minimumDeltaVIndex ] );\n    Real lambertArrivalBurn = sml::norm< Real >( arrivalDeltaVs[ minimumDeltaVIndex ] );\n    Real lambertDV = transferDeltaVs[ minimumDeltaVIndex ];\n\n    array3 minIndexDepartureVelocity = targeter.get_v1( )[ minimumDeltaVIndex ]; // best guess for velocity in transfer orbit at the departure point\n    \n    Vector6 lambertDepState( 6 );\n    for ( int i = 0; i < 3; i++ )\n    {\n        lambertDepState[ i ] = departurePosition [ i ] * 1000.0;\n        lambertDepState[ i + 3 ] = minIndexDepartureVelocity[ i ] * 1000.0;\n    }\n    const Real tolerance = 10.0 * std::numeric_limits< Real >::epsilon( );\n    Vector6 LambertKep( 6 );\n    LambertKep = astro::convertCartesianToKeplerianElements( lambertDepState, muEarth, tolerance );\n    Vector6 LambertKepStd = standardKeplerian( LambertKep );\n    std::cout << std::endl << \"LambertKep = \" << LambertKepStd << std::endl << std::endl;\n\n    Vector3 departureVelocityGuess( 3 );\n    Vector3 atomDeparturePosition( 3 );\n    Vector3 atomArrivalPosition( 3 );\n\n    for( int j = 0; j < 3; j++ )\n    {\n        departureVelocityGuess[ j ] = minIndexDepartureVelocity[ j ];\n        atomDeparturePosition[ j ] = departurePosition[ j ];\n        atomArrivalPosition[ j ] = arrivalPosition[ j ];\n    }\n\n    array3 atomDepartureVelocity;\n    array3 atomArrivalVelocity;\n                            \n    std::string SolverStatusSummary;\n    int numberOfIterations;\n    const int maxIterations = 100;\n    const Tle referenceTle = Tle( );\n                            \n    try\n    {\n        Vector3 outputDepartureVelocity( 3 );\n        Vector3 outputArrivalVelocity( 3 );\n        atom::executeAtomSolver< Real, Vector3 >( atomDeparturePosition, \n                                                  departureEpoch, \n                                                  atomArrivalPosition, \n                                                  TOF, \n                                                  departureVelocityGuess,\n                                                  outputDepartureVelocity,\n                                                  outputArrivalVelocity, \n                                                  SolverStatusSummary, \n                                                  numberOfIterations, \n                                                  referenceTle, \n                                                  kMU, \n                                                  kXKMPER, \n                                                  1.0e-10, \n                                                  1.0e-5, \n                                                  maxIterations );\n                            \n        \n        Vector6 atomDepState( 6 );\n        for ( int i = 0; i < 3; i++ )\n        {\n            atomDepState[ i ] = departurePosition[ i ] * 1000.0;\n            atomDepState[ i + 3 ] = outputDepartureVelocity[ i ] * 1000.0;\n        }\n        Vector6 atomDepKep = astro::convertCartesianToKeplerianElements( atomDepState, muEarth, tolerance );\n        Vector6 atomDepKepStd( 6 );\n        atomDepKepStd = standardKeplerian( atomDepKep );\n        std::cout << std::endl << \"atom dep kep = \" << atomDepKepStd << std::endl << std::endl;\n\n        for( int k = 0; k < 3; k++)\n        {\n            atomDepartureVelocity[ k ] = outputDepartureVelocity[ k ];\n            atomArrivalVelocity[ k ] = outputArrivalVelocity[ k ];\n        }\n                                \n        array3 atomDepartureDeltaV;\n        array3 atomArrivalDeltaV;\n        Real AtomDeltaV;\n\n        atomDepartureDeltaV = sml::add( atomDepartureVelocity, sml::multiply( departureVelocity, -1.0 ) );\n        atomArrivalDeltaV = sml::add( atomArrivalVelocity, sml::multiply( arrivalVelocity, -1.0 ) );\n\n        double AtomDepartureBurn = sml::norm< Real >( atomDepartureDeltaV );\n        double AtomArrivalBurn = sml::norm< Real >( atomArrivalDeltaV );\n        AtomDeltaV = sml::norm< Real >( atomDepartureDeltaV ) + sml::norm< Real >( atomArrivalDeltaV );\n        std::cout << \"Atom DeltaV = \" << AtomDeltaV << std::endl;\n    }\n    \n    catch( const std::exception& err )   \n    {\n        ++failCount;\n        std::cout << \"Exception Caught = \" << err.what( ) << std::endl;\n        std::cout << \"For departure ID = \" << catchDepartureID << \" \" << \"For Arrival ID = \" << catchArrivalID << std::endl << std::endl;\n        // std::cout << \"Fail count = \" << failCount << std::endl;\n    }\n\n   return EXIT_SUCCESS;\n}", "meta": {"hexsha": "22bc7df533efedc5bda950ddf283f3137af5a2f7", "size": 12804, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/napa_osculatingElementSanityCheck.cpp", "max_stars_repo_name": "agrawalabhishek/AtomScanner", "max_stars_repo_head_hexsha": "65ef8e5db2e46d4c95068233bc7f3ff67f2796f5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/napa_osculatingElementSanityCheck.cpp", "max_issues_repo_name": "agrawalabhishek/AtomScanner", "max_issues_repo_head_hexsha": "65ef8e5db2e46d4c95068233bc7f3ff67f2796f5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/napa_osculatingElementSanityCheck.cpp", "max_forks_repo_name": "agrawalabhishek/AtomScanner", "max_forks_repo_head_hexsha": "65ef8e5db2e46d4c95068233bc7f3ff67f2796f5", "max_forks_repo_licenses": ["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.1379310345, "max_line_length": 148, "alphanum_fraction": 0.5936426117, "num_tokens": 3307, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.754914975839675, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.4836255905193409}}
{"text": "/*\n    Copyright 2012 Ulrik Mikaelsson <ulrik.mikaelsson@gmail.com>\n\n    Licensed under the Apache License, Version 2.0 (the \"License\");\n    you may not use this file except in compliance with the License.\n    You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n*/\n\n#include \"treestore.hpp\"\n\n#include <boost/assert.hpp>\n\nuint32_t calc_leaves(uint32_t treesize, int layers)\n{\n\tif (treesize == 0) return 0;\n\tif (layers == 0) return 1;\n\tuint32_t leftside = 1 << layers;\n\tif (leftside <= treesize)\n\t\treturn (1<<(layers-1)) + calc_leaves(treesize-leftside, layers-1);\n\telse\n\t\treturn calc_leaves(treesize-1, layers-1);\n}\n\nuint32_t calc_leaves(uint32_t treesize) {\n\tBOOST_ASSERT(treesize >= 1);\n\tuint32_t layers = (int)log2f(treesize);\n\treturn calc_leaves(treesize, layers);\n}\n\nstd::ostream& operator<<(std::ostream& str, const NodeIdx& idx)\n{\n\treturn str << \"NodeIdx(\"<<idx.nodeIdx<<','<<idx.layerSize<<')';\n}", "meta": {"hexsha": "128703fad3fcae5e57af254f3cd4917d072ec55d", "size": 1270, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bithorded/lib/treestore.cpp", "max_stars_repo_name": "zidz/bithorde", "max_stars_repo_head_hexsha": "dbaa67eb0ddfa7d28e5325d87428c1b0225d598b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bithorded/lib/treestore.cpp", "max_issues_repo_name": "zidz/bithorde", "max_issues_repo_head_hexsha": "dbaa67eb0ddfa7d28e5325d87428c1b0225d598b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bithorded/lib/treestore.cpp", "max_forks_repo_name": "zidz/bithorde", "max_forks_repo_head_hexsha": "dbaa67eb0ddfa7d28e5325d87428c1b0225d598b", "max_forks_repo_licenses": ["Apache-2.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.9756097561, "max_line_length": 76, "alphanum_fraction": 0.7181102362, "num_tokens": 338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.6334102775181399, "lm_q1q2_score": 0.4835984625535183}}
{"text": "#define BOOST_TEST_MAIN TestExponentialHistogram\n#include <boost/test/unit_test.hpp>\n#include <stdexcept>\n#include <sam/ExponentialHistogram.hpp>\n\nusing namespace sam;\n\n\nBOOST_AUTO_TEST_CASE( eh_test_numlevels )\n{\n  \n  BOOST_CHECK_THROW(ExponentialHistogram<size_t>(0,2), std::out_of_range);\n  ExponentialHistogram<size_t> eh1(1, 2);\n  BOOST_CHECK_EQUAL(eh1.getNumLevels(), 1);\n  ExponentialHistogram<size_t> eh2(2, 2);\n  BOOST_CHECK_EQUAL(eh2.getNumLevels(), 1);\n  ExponentialHistogram<size_t> eh3(3, 2);\n  BOOST_CHECK_EQUAL(eh3.getNumLevels(), 1);\n  ExponentialHistogram<size_t> eh4(4, 2);\n  BOOST_CHECK_EQUAL(eh4.getNumLevels(), 2);\n  ExponentialHistogram<size_t> eh5(5, 2);\n  BOOST_CHECK_EQUAL(eh5.getNumLevels(), 2);\n  ExponentialHistogram<size_t> eh9(9, 2);\n  BOOST_CHECK_EQUAL(eh9.getNumLevels(), 2);\n  ExponentialHistogram<size_t> eh10(10, 2);\n  BOOST_CHECK_EQUAL(eh10.getNumLevels(), 3);\n  ExponentialHistogram<size_t> eh21(21, 2); \n  BOOST_CHECK_EQUAL(eh21.getNumLevels(), 3);\n  ExponentialHistogram<size_t> eh22(22, 2); \n  BOOST_CHECK_EQUAL(eh22.getNumLevels(), 4);\n  BOOST_CHECK_THROW(ExponentialHistogram<size_t>(\n                      ExponentialHistogram<size_t>::MAX_SIZE, 2),\n                      std::out_of_range);\n}\n\nBOOST_AUTO_TEST_CASE( eh_test_add )\n{\n  ExponentialHistogram<size_t> eh(21, 2);\n  BOOST_CHECK_EQUAL(eh.getNumSlots(), 22);\n  BOOST_CHECK_EQUAL(eh.getTotal(), 0);\n  for(int i = 0; i < 22; i++) {\n    eh.add(1);\n    BOOST_CHECK_EQUAL(eh.getTotal(), i + 1);\n  }\n  eh.add(1);\n  BOOST_CHECK_EQUAL(eh.getTotal(), 15);\n}\n\nBOOST_AUTO_TEST_CASE( eh_test_long_add )\n{\n  ExponentialHistogram<size_t> eh(12285, 2);\n  for(int i =0; i < 1000000000; i++) {\n    eh.add(1);\n  }\n  BOOST_CHECK_CLOSE(static_cast<double>(eh.getTotal()), \n                    static_cast<double>(12285), \n                    static_cast<double>(pow(2,eh.getNumLevels()-1)));\n\n}\n", "meta": {"hexsha": "40e06041f9c594a70d4f7ebe108a6dd9e90d0b56", "size": 1877, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "TestSrc/TestExponentialHistogram.cpp", "max_stars_repo_name": "dirkcgrunwald/SAM", "max_stars_repo_head_hexsha": "0478925c506ad38fd405954cc4415a3e96e77d90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-08-16T07:13:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-08T21:15:52.000Z", "max_issues_repo_path": "TestSrc/TestExponentialHistogram.cpp", "max_issues_repo_name": "dirkcgrunwald/SAM", "max_issues_repo_head_hexsha": "0478925c506ad38fd405954cc4415a3e96e77d90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-05-30T20:35:18.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-30T20:35:18.000Z", "max_forks_repo_path": "TestSrc/TestExponentialHistogram.cpp", "max_forks_repo_name": "dirkcgrunwald/SAM", "max_forks_repo_head_hexsha": "0478925c506ad38fd405954cc4415a3e96e77d90", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-02-17T18:38:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-28T02:47:57.000Z", "avg_line_length": 31.2833333333, "max_line_length": 74, "alphanum_fraction": 0.7011188066, "num_tokens": 544, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.48359845880418684}}
{"text": "#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n#include <math.h>\r\n#include <map>\r\n#include <unordered_map>\r\n#include <numeric>\r\n#include <Eigen>\r\n#include <time.h>\r\nusing namespace std;\r\n\r\n// \u5e73\u9762\r\nenum Plane\r\n{\r\n\tXOY,\r\n\tXOZ,\r\n\tYOZ\r\n};\r\n\r\n\r\n// \u7a7a\u95f4\u76f4\u65b9\u56fe\u8ba1\u7b97\r\n// \u6cd5\u5411\u91cf\u7684\u89c6\u70b9\u5750\u6807\r\nstruct Normal\r\n{\r\n\tdouble x, y, z;\r\n};\r\nstruct Point3D\r\n{\r\n\tdouble x, y, z;\r\n\tNormal normal;\r\n\tdouble angle;\r\n\t// \u91cd\u70b9\uff1a\u91cd\u8f7d\u201c<\u201d\uff0c\u4f5c\u4e3amap\u7684\u952e\r\n\tbool operator<(const Point3D & p)const {\r\n\t\treturn (x < p.x) || (x == p.x && y < p.y);\r\n\t}\r\n\r\n};\r\n\r\nstruct Point2D\r\n{\r\n\tfloat x, y;\r\n\tbool operator<(const Point2D & p)const {\r\n\t\treturn (x < p.x) || (x == p.x && y < p.y);\r\n\t}\r\n\r\n};\r\n\r\nstruct Boundary\r\n{\r\n\tdouble xMin, xMax;\r\n\tdouble yMin, yMax;\r\n\tdouble zMin, zMax;\r\n};\r\n\r\nostream & operator<<(ostream & out, Point2D A) {\r\n\r\n\tout << \"[\" << A.x << \",\" << A.y << \"]\";\r\n\treturn out;\r\n}\r\n\r\nostream & operator<<(ostream & out, Point3D A) {\r\n\r\n\tout << \"[\" << A.x << \",\" << A.y << \",\" << A.z << \"]\";\r\n\treturn out;\r\n}\r\nostream & operator<<(ostream & out, Normal A) {\r\n\r\n\tout << \"[\" << A.x << \",\" << A.y << \",\" << A.z << \"]\";\r\n\treturn out;\r\n}\r\n// \u8bfb\u53d6\u6587\u4ef6\u70b9\u4e91\u6570\u636e\r\nvector<Point2D> getData(const char* filename, Plane intestingPlane, vector<float> &boundaryValue) {\r\n\t\r\n\tFILE *fp_txt1;\r\n\t\r\n\tfp_txt1 = fopen(filename, \"r\");\r\n\r\n\tPoint3D TxtPoint1;\r\n\tPoint2D tempData;\r\n\tvector<Point2D> pointCloudData;\r\n\r\n\tvector<float> x_data, y_data;\r\n\r\n\tif (fp_txt1)\r\n\t{\r\n\t\t// \u83b7\u53d6\u8981\u7edf\u8ba1\u7684\u5e73\u9762\u7684\u70b9\u4e91\r\n\t\tswitch (intestingPlane) {\r\n\t\tcase XOY:\r\n\t\t\twhile (fscanf(fp_txt1, \"%lf %lf %lf\", &TxtPoint1.x, &TxtPoint1.y, &TxtPoint1.z) != EOF)\r\n\t\t\t{\r\n\t\t\t\t\r\n\t\t\t\ttempData.x = TxtPoint1.x;\r\n\t\t\t\tx_data.push_back(TxtPoint1.x);\r\n\t\t\t\ty_data.push_back(TxtPoint1.y);\r\n\t\t\t\ttempData.y = TxtPoint1.y;\r\n\t\t\t\tpointCloudData.push_back(tempData);\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\t\tcase XOZ:\r\n\t\t\twhile (fscanf(fp_txt1, \"%lf %lf %lf\", &TxtPoint1.x, &TxtPoint1.y, &TxtPoint1.z) != EOF)\r\n\t\t\t{\r\n\r\n\t\t\t\ttempData.x = TxtPoint1.x;\r\n\t\t\t\ttempData.y = TxtPoint1.z;\r\n\t\t\t\tx_data.push_back(TxtPoint1.x);\r\n\t\t\t\ty_data.push_back(TxtPoint1.z);\r\n\t\t\t\tpointCloudData.push_back(tempData);\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\t\tcase YOZ:\r\n\t\t\twhile (fscanf(fp_txt1, \"%lf %lf %lf\", &TxtPoint1.x, &TxtPoint1.y, &TxtPoint1.z) != EOF)\r\n\t\t\t{\r\n\r\n\t\t\t\ttempData.x = TxtPoint1.y;\r\n\t\t\t\ttempData.y = TxtPoint1.z;\r\n\t\t\t\tx_data.push_back(TxtPoint1.y);\r\n\t\t\t\ty_data.push_back(TxtPoint1.z);\r\n\t\t\t\tpointCloudData.push_back(tempData);\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\t\tdefault:\r\n\t\t\tbreak;\r\n\t\t}\r\n\r\n\r\n\t}\r\n\telse{\r\n\r\n\t\tcout << \"txt\u6570\u636e\u52a0\u8f7d\u5931\u8d25\uff01\" << endl;\r\n\t}\r\n\tsort(x_data.begin(), x_data.end());\r\n\tsort(y_data.begin(), y_data.end());\r\n\tboundaryValue.push_back(x_data[0]);\r\n\tboundaryValue.push_back(x_data[x_data.size() - 1]);\r\n\tboundaryValue.push_back(y_data[0]);\r\n\tboundaryValue.push_back(y_data[y_data.size() - 1]);\r\n\treturn pointCloudData;\r\n}\r\n\r\n// \u7edf\u8ba1\u5404\u4e2a\u5355\u4f4d\u70b9\u4e91\u6570\u76ee,\r\nmap<Point2D, int> countPointCloud(vector<Point2D> pointCloudDatas, vector<float> boudaryData, int segNum) {\r\n\t// \u533a\u95f4\u657010*10\r\n\r\n\tfloat xSegValue = (boudaryData[1] - boudaryData[0]) / segNum;\r\n\tfloat ySegValue = (boudaryData[3] - boudaryData[2]) / segNum;\r\n\t//cout << \"xSegValue: \" << xSegValue << \" ySegValue: \" << ySegValue << endl;\r\n\tmap<Point2D, int> mpPointData;\r\n\tint tenSum = 0;\r\n\t// \u5224\u65ad\u5c5e\u4e8e\u54ea\u4e2a\u533a\u95f4\uff0c\u5e76\u7edf\u8ba1\u8be5\u533a\u95f4\u70b9\u4e91\u7684\u4e2a\u6570\r\n\tfor (Point2D & pointCloudData : pointCloudDatas) {\r\n\t\tPoint2D tempData;\r\n\r\n\t\t// \u503c\u51cf\u53bb\u6700\u5c0f\u503c\u518d\u9664\u4ee5\u533a\u95f4\u95f4\u9694\u503c\uff0c\u5224\u65ad\u5c5e\u4e8e\u54ea\u4e2a\u533a\u95f4 \r\n\t\tfloat xTemp = (pointCloudData.x - boudaryData[0]) / xSegValue;\r\n\t\tfloat yTemp = (pointCloudData.y - boudaryData[2]) / ySegValue;\r\n\t\ttempData.x = floorf(xTemp);\r\n\t\ttempData.y = floorf(yTemp);\r\n\t\tif (tempData.x == segNum || tempData.y == segNum) {\r\n\t\t\ttenSum += 1;\r\n\t\t\t\r\n\t\t}\r\n\t\telse {\r\n\t\t\tmpPointData[tempData] += 1;\r\n\t\t}\r\n\t\t\r\n\t}\r\n\tint sum = 0;\r\n\tfor (auto it = mpPointData.begin(); it != mpPointData.end(); it++) {\r\n\t\tsum += it->second;\r\n\t}\r\n\treturn mpPointData;\r\n}\r\n\r\n// \u8ba1\u7b97\u76f8\u4f3c\u5ea6\r\nfloat cacular2Similarity(map<Point2D,int> data1, map<Point2D,int> data2, int segNum) {\r\n\t// \u5b58\u50a8100\u4e2a\u5355\u5143\u7684\u70b9\u4e91\u6570\r\n\tvector<int> unitPointNum1(segNum * segNum, 0);\r\n\tvector<int> unitPointNum2(segNum * segNum, 0);\r\n\t// \u4e34\u65f6\u5b58\u50a8\u5f53\u524d\u904d\u5386\u7684\u4f4d\u7f6e\r\n\tPoint2D curLoc;\r\n\tint k = 0;\r\n\r\n\t// \u63d0\u53d6\u51fa100\u4e2a\u5355\u5143\u4e2d\u6bcf\u4e2a\u5355\u5143\u7684\u70b9\u4e91\u6570\r\n\tfor (int i = 0; i < segNum; ++i) {\r\n\t\tfor (int j = 0; j < segNum; ++j) {\r\n\t\t\tcurLoc.x = i; \r\n\t\t\tcurLoc.y = j; \r\n\t\t\tif (data1.find(curLoc) != data1.end()) {\r\n\t\t\t\tunitPointNum1[k] = data1[curLoc];\r\n\t\t\t}\r\n\t\t\tif (data2.find(curLoc) != data2.end()) {\r\n\t\t\t\tunitPointNum2[k] = data2[curLoc];\r\n\t\t\t}\r\n\t\t\tk++;\r\n\t\t}\r\n\t}\r\n\r\n\tint sumNum1 = accumulate(unitPointNum1.begin(), unitPointNum1.end(), 0);\r\n\tint sumNum2 = accumulate(unitPointNum2.begin(), unitPointNum2.end(), 0);\r\n\tdouble similarity = 0;\r\n\tfor (int i = 0; i < segNum * segNum; ++i) {\r\n\t\tsimilarity += sqrt(((double)unitPointNum1[i] / sumNum1) * ((double)unitPointNum2[i] / sumNum2));\r\n\t}\r\n\treturn similarity;\r\n}\r\n\r\n//\u4e8c\u7ef4\u5e73\u9762\u6805\u683c\u5316\u540e\uff0c\u76f8\u4f3c\u5ea6\u6bd4\u8f83\r\nvoid similarity2D(const char *billboardFile, const char *geometricFile) {\r\n\r\n\tvector<Plane> Planes{ XOY, XOZ, YOZ };\r\n\tvector<float> similarities(3);\r\n\tint segNum = 20;\r\n\tfor (int i = 0; i < 3; i++)\r\n\t{\r\n\t\tvector<float> b_boudaryData;\r\n\t\tvector<float> g_boudaryData;\r\n\t\tvector<Point2D> billboardData = getData(billboardFile, Planes[i], b_boudaryData);\r\n\t\tvector<Point2D> geometricData = getData(geometricFile, Planes[i], g_boudaryData);\r\n\r\n\t\t// 2D\u7f51\u683c\u70b9\u4e91\u6570\u76ee\u7edf\u8ba1\u4fe1\u606f\r\n\t\tauto billboardDataCount = countPointCloud(billboardData, b_boudaryData, segNum);\r\n\t\tauto geometricDataCount = countPointCloud(geometricData, g_boudaryData, segNum);\r\n\r\n\t\t// \u8ba1\u7b97\u76f8\u4f3c\u5ea6\r\n\t\tsimilarities[i] = cacular2Similarity(billboardDataCount, geometricDataCount, segNum);\r\n\t\tcout << similarities[i] << endl;\r\n\t}\r\n\r\n\tcout.setf(ios::fixed);\r\n\tcout.setf(ios::showpoint);\r\n\tcout.precision(4); \r\n\r\n\tfloat average = (float)accumulate(similarities.begin(), similarities.end(), 0.0f) / 3;\r\n\tcout << \"========================\u76f8\u4f3c\u5ea6\u4fe1\u606f=========================\" << endl;\r\n\tfor (float i : similarities) {\r\n\t\tcout << i << \" \";\r\n\t}\r\n\tcout << average << endl;\r\n}\r\n\r\n// \u83b7\u53d6\u4e09\u7ef4\u70b9\u4e91\u7684\u6570\u636e\uff0c\u904d\u5386\u70b9\u4e91\u83b7\u5f97\u8fb9\u754cX\u3001Y\u3001Z\u7684\u6700\u5927\uff0c\u6700\u5c0f\u503c\r\n vector<Point3D> get3Data(const char* filename, Boundary &boundary) {\r\n\r\n\t FILE *fp_txt1;\r\n\r\n\t fp_txt1 = fopen(filename, \"r\");\r\n\r\n\t Point3D TxtPoint;\r\n\t vector<Point3D>pointData;\r\n\t vector<double> x_data, y_data, z_data;\r\n\t while (fscanf(fp_txt1, \"%lf %lf %lf %lf %lf %lf\", &TxtPoint.x, &TxtPoint.y, &TxtPoint.z, \r\n\t\t\t\t\t\t\t\t\t\t\t\t\t   &TxtPoint.normal.x, &TxtPoint.normal.y, &TxtPoint.normal.z) != EOF)\r\n\t {\r\n\t\t x_data.push_back(TxtPoint.x);\r\n\t\t y_data.push_back(TxtPoint.y);\r\n\t\t z_data.push_back(TxtPoint.z);\r\n\t\t pointData.push_back(TxtPoint);\r\n\t }\r\n\t cout << \"=========================\u7edf\u8ba1\u6570\u636e======================\" << endl;\r\n\t cout << \"3D\u70b9\u4e91\u6570\u636e\u6570\u76ee: \" << pointData.size() << endl;\r\n\r\n\t // \u7edf\u8ba1\u8fb9\u754c\r\n\t sort(x_data.begin(), x_data.end());\r\n\t sort(y_data.begin(), y_data.end());\r\n\t sort(z_data.begin(), z_data.end());\r\n\t boundary.xMin = x_data[0]; boundary.xMax = x_data[x_data.size() - 1];\r\n\t boundary.yMin = y_data[0]; boundary.yMax = y_data[y_data.size() - 1];\r\n\t boundary.zMin = z_data[0]; boundary.zMax = z_data[z_data.size() - 1];\r\n\r\n\t return pointData;\r\n}\r\n\r\n // \u7edf\u8ba1\u5404\u4e2a\u7f51\u683c\u5185\u7684\u6570\u636e\uff0c\u7f51\u683c\u5316\r\nmap<Point3D, vector<Point3D>> countMeshData(vector<Point3D> &pointDatas, Boundary boundary, int meshNum) {\r\n\t\r\n\tdouble xMeshValue = (boundary.xMax - boundary.xMin) / meshNum;\r\n\tdouble yMeshValue = (boundary.yMax - boundary.yMin) / meshNum;\r\n\tdouble zMeshValue = (boundary.zMax - boundary.zMin) / meshNum;\r\n\t// \u952e\u4e3a\u7f51\u683c\u5750\u6807\uff0c\u952e\u503c\u4e3a\u8be5\u7f51\u683c\u5185\u7684\u70b9\u4e91\r\n\tmap<Point3D, vector<Point3D>> meshData;\r\n\tPoint3D tempData;\r\n\tfor (auto & pointData : pointDatas) {\r\n\t\t// \u503c\u51cf\u53bb\u6700\u5c0f\u503c\u518d\u9664\u4ee5\u533a\u95f4\u95f4\u9694\u503c\uff0c\u5224\u65ad\u5c5e\u4e8e\u54ea\u4e2a\u533a\u95f4\r\n\t\tdouble xTemp = (pointData.x - boundary.xMin) / xMeshValue;\r\n\t\tdouble yTemp = (pointData.y - boundary.yMin) / yMeshValue;\r\n\t\tdouble zTemp = (pointData.z - boundary.zMin) / zMeshValue;\r\n\t\ttempData.x = floor(xTemp);\r\n\t\ttempData.y = floor(yTemp);\r\n\t\ttempData.z = floor(zTemp);\r\n\t\tif (tempData.x == meshNum || tempData.y == meshNum || tempData.z == meshNum) {\r\n\t\t\t// \u8fb9\u754c\u5904\u7406\r\n\t\t\tauto xtemp = tempData.x == meshNum ? tempData.x - 1 : tempData.x;\r\n\t\t\ttempData.x = xtemp;\r\n\t\t\tauto ytemp = tempData.y == meshNum ? tempData.y - 1 : tempData.y;\r\n\t\t\ttempData.y = ytemp;\r\n\t\t\tauto ztemp = tempData.z == meshNum ? tempData.z - 1 : tempData.z;\r\n\t\t\ttempData.z = ztemp;\r\n\t\t}\r\n\t\t// \u6570\u636e\u5b58\u50a8\r\n\t\tmeshData[tempData].push_back(pointData);\r\n\t}\r\n\tint pointSum = 0;\r\n\tcout << \"\u7f51\u683c\u6570\u91cf\uff1a\" << meshData.size() << endl;\r\n\treturn meshData;\r\n}\r\n\r\n\r\n\r\nint main() {\r\n\r\n\tconst char* billboardFile = \"billboard.txt\";\r\n\tconst char* geometricFile = \"geometric.txt\";\r\n\tsimilarity2D(billboardFile, geometricFile);\r\n\tsystem(\"pause\");\r\n\treturn 0;\r\n}", "meta": {"hexsha": "37872fa7afc8296e9e39a7d99d767efa6956d8fc", "size": 8381, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "similarity.cpp", "max_stars_repo_name": "imlab-chd/virtual-lidar-simulation", "max_stars_repo_head_hexsha": "459ba8ce122f806806aebecda25ed9afb3f59506", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-08-05T08:59:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-06T03:48:05.000Z", "max_issues_repo_path": "similarity.cpp", "max_issues_repo_name": "imlab-chd/virtual-lidar-simulation", "max_issues_repo_head_hexsha": "459ba8ce122f806806aebecda25ed9afb3f59506", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "similarity.cpp", "max_forks_repo_name": "imlab-chd/virtual-lidar-simulation", "max_forks_repo_head_hexsha": "459ba8ce122f806806aebecda25ed9afb3f59506", "max_forks_repo_licenses": ["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.5221518987, "max_line_length": 108, "alphanum_fraction": 0.6221214652, "num_tokens": 2831, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.48359845880418684}}
{"text": "//  Boost integer/integer_mask.hpp header file  ------------------------------//\r\n\r\n//  (C) Copyright Daryle Walker 2001.  Permission to copy, use, modify, sell and\r\n//  distribute this software is granted provided this copyright notice appears \r\n//  in all copies.  This software is provided \"as is\" without express or\r\n//  implied warranty, and with no claim as to its suitability for any purpose. \r\n\r\n//  See http://www.boost.org for updates, documentation, and revision history. \r\n\r\n#ifndef BOOST_INTEGER_INTEGER_MASK_HPP\r\n#define BOOST_INTEGER_INTEGER_MASK_HPP\r\n\r\n#include <boost/integer_fwd.hpp>  // self include\r\n\r\n#include <boost/config.hpp>   // for BOOST_STATIC_CONSTANT\r\n#include <boost/integer.hpp>  // for boost::uint_t\r\n\r\n#include <climits>  // for UCHAR_MAX, etc.\r\n#include <cstddef>  // for std::size_t\r\n\r\n#include <boost/limits.hpp>  // for std::numeric_limits\r\n\r\n\r\nnamespace boost\r\n{\r\n\r\n\r\n//  Specified single-bit mask class declaration  -----------------------------//\r\n//  (Lowest bit starts counting at 0.)\r\n\r\ntemplate < std::size_t Bit >\r\nstruct high_bit_mask_t\r\n{\r\n    typedef typename uint_t<(Bit + 1)>::least  least;\r\n    typedef typename uint_t<(Bit + 1)>::fast   fast;\r\n\r\n    BOOST_STATIC_CONSTANT( least, high_bit = (least( 1u ) << Bit) );\r\n    BOOST_STATIC_CONSTANT( fast, high_bit_fast = (fast( 1u ) << Bit) );\r\n\r\n    BOOST_STATIC_CONSTANT( std::size_t, bit_position = Bit );\r\n\r\n};  // boost::high_bit_mask_t\r\n\r\n\r\n//  Specified bit-block mask class declaration  ------------------------------//\r\n//  Makes masks for the lowest N bits\r\n//  (Specializations are needed when N fills up a type.)\r\n\r\ntemplate < std::size_t Bits >\r\nstruct low_bits_mask_t\r\n{\r\n    typedef typename uint_t<Bits>::least  least;\r\n    typedef typename uint_t<Bits>::fast   fast;\r\n\r\n    BOOST_STATIC_CONSTANT( least, sig_bits = (~( ~(least( 0u )) << Bits )) );\r\n    BOOST_STATIC_CONSTANT( fast, sig_bits_fast = fast(sig_bits) );\r\n\r\n    BOOST_STATIC_CONSTANT( std::size_t, bit_count = Bits );\r\n\r\n};  // boost::low_bits_mask_t\r\n\r\n\r\n#define BOOST_LOW_BITS_MASK_SPECIALIZE( Type )                                  \\\r\n  template <  >  struct low_bits_mask_t< std::numeric_limits<Type>::digits >  { \\\r\n      typedef std::numeric_limits<Type>           limits_type;                  \\\r\n      typedef uint_t<limits_type::digits>::least  least;                        \\\r\n      typedef uint_t<limits_type::digits>::fast   fast;                         \\\r\n      BOOST_STATIC_CONSTANT( least, sig_bits = (~( least(0u) )) );              \\\r\n      BOOST_STATIC_CONSTANT( fast, sig_bits_fast = fast(sig_bits) );            \\\r\n      BOOST_STATIC_CONSTANT( std::size_t, bit_count = limits_type::digits );    \\\r\n  }\r\n\r\nBOOST_LOW_BITS_MASK_SPECIALIZE( unsigned char );\r\n\r\n#if USHRT_MAX > UCHAR_MAX\r\nBOOST_LOW_BITS_MASK_SPECIALIZE( unsigned short );\r\n#endif\r\n\r\n#if UINT_MAX > USHRT_MAX\r\nBOOST_LOW_BITS_MASK_SPECIALIZE( unsigned int );\r\n#endif\r\n\r\n#if ULONG_MAX > UINT_MAX\r\nBOOST_LOW_BITS_MASK_SPECIALIZE( unsigned long );\r\n#endif\r\n\r\n#undef BOOST_LOW_BITS_MASK_SPECIALIZE\r\n\r\n\r\n}  // namespace boost\r\n\r\n\r\n#endif  // BOOST_INTEGER_INTEGER_MASK_HPP\r\n", "meta": {"hexsha": "ef7f4c0073aca3f1ac9a50fc3c8cd81cf53d8730", "size": 3126, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sdk/boost_1_30_0/boost/integer/integer_mask.hpp", "max_stars_repo_name": "acidicMercury8/xray-1.0", "max_stars_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2021-05-04T06:40:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T20:24:28.000Z", "max_issues_repo_path": "sdk/boost_1_30_0/boost/integer/integer_mask.hpp", "max_issues_repo_name": "acidicMercury8/xray-1.0", "max_issues_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_issues_repo_licenses": ["Linux-OpenIB"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sdk/boost_1_30_0/boost/integer/integer_mask.hpp", "max_forks_repo_name": "acidicMercury8/xray-1.0", "max_forks_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-05-17T10:01:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-11T20:17:27.000Z", "avg_line_length": 33.2553191489, "max_line_length": 82, "alphanum_fraction": 0.6458733205, "num_tokens": 725, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.4835984519866741}}
{"text": "#define BOOST_TEST_MODULE \"test_excluded_volume_potential\"\n\n#ifdef BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n#else\n#include <boost/test/included/unit_test.hpp>\n#endif\n\n#include <mjolnir/forcefield/global/ExcludedVolumePotential.hpp>\n#include <mjolnir/core/BoundaryCondition.hpp>\n#include <mjolnir/core/SimulatorTraits.hpp>\n\nBOOST_AUTO_TEST_CASE(EXV_double)\n{\n    using traits_type = mjolnir::SimulatorTraits<double, mjolnir::UnlimitedBoundary>;\n    using real_type   = typename traits_type::real_type;\n    using molecule_id_type = mjolnir::Topology::molecule_id_type;\n    using group_id_type    = mjolnir::Topology::group_id_type;\n    constexpr std::size_t N = 10000;\n    constexpr real_type   h = 1e-6;\n\n    const real_type sigma   = 3.0;\n    const real_type epsilon = 1.0;\n    mjolnir::ExcludedVolumePotential<traits_type> exv{\n        epsilon, mjolnir::ExcludedVolumePotential<traits_type>::default_cutoff(),\n        {{0, sigma}, {1, sigma}}, {},\n        mjolnir::IgnoreMolecule<molecule_id_type>(\"Nothing\"),\n        mjolnir::IgnoreGroup   <group_id_type   >({})\n    };\n\n    const real_type x_min = 0.8 * sigma;\n    const real_type x_max = exv.cutoff_ratio() * sigma;\n    const real_type dx = (x_max - x_min) / N;\n\n    for(std::size_t i=0; i<N; ++i)\n    {\n        const real_type x    = x_min + i * dx;\n        const real_type pot1 = exv.potential(0, 1, x + h);\n        const real_type pot2 = exv.potential(0, 1, x - h);\n        const real_type dpot = (pot1 - pot2) / (2 * h);\n        const real_type deri = exv.derivative(0, 1, x);\n\n        BOOST_TEST(dpot == deri, boost::test_tools::tolerance(h));\n    }\n}\n\nBOOST_AUTO_TEST_CASE(EXV_float)\n{\n    using traits_type = mjolnir::SimulatorTraits<float, mjolnir::UnlimitedBoundary>;\n    using real_type   = typename traits_type::real_type;\n    using molecule_id_type = mjolnir::Topology::molecule_id_type;\n    using group_id_type    = mjolnir::Topology::group_id_type;\n    constexpr static std::size_t N = 1000;\n    constexpr static real_type   h = 0.002;\n    constexpr static real_type tol = 0.005;\n\n    const real_type sigma   = 3.0;\n    const real_type epsilon = 1.0;\n\n    mjolnir::ExcludedVolumePotential<traits_type> exv{\n        epsilon, mjolnir::ExcludedVolumePotential<traits_type>::default_cutoff(),\n        {{0, sigma}, {1, sigma}}, {},\n        mjolnir::IgnoreMolecule<molecule_id_type>(\"Nothing\"),\n        mjolnir::IgnoreGroup   <group_id_type   >({})\n    };\n    const real_type cutoff = exv.cutoff_ratio();\n\n    const real_type x_min = 0.8f   * sigma;\n    const real_type x_max = cutoff * sigma;\n    const real_type dx = (x_max - x_min) / N;\n\n    for(std::size_t i=0; i<N; ++i)\n    {\n        const real_type x    = x_min + i * dx;\n        const real_type pot1 = exv.potential(0, 1, x + h);\n        const real_type pot2 = exv.potential(0, 1, x - h);\n        const real_type dpot = (pot1 - pot2) / (2 * h);\n        const real_type deri = exv.derivative(0, 1, x);\n\n        BOOST_TEST(dpot == deri, boost::test_tools::tolerance(tol));\n    }\n}\n\n", "meta": {"hexsha": "a3a9ab0564b38879700c2115a4f8bdbb03a84c5c", "size": 3015, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/core/test_excluded_volume_potential.cpp", "max_stars_repo_name": "yutakasi634/Mjolnir", "max_stars_repo_head_hexsha": "ab7a29a47f994111e8b889311c44487463f02116", "max_stars_repo_licenses": ["MIT"], "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/core/test_excluded_volume_potential.cpp", "max_issues_repo_name": "yutakasi634/Mjolnir", "max_issues_repo_head_hexsha": "ab7a29a47f994111e8b889311c44487463f02116", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-07T11:41:45.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-08T10:01:38.000Z", "max_forks_repo_path": "test/core/test_excluded_volume_potential.cpp", "max_forks_repo_name": "yutakasi634/Mjolnir", "max_forks_repo_head_hexsha": "ab7a29a47f994111e8b889311c44487463f02116", "max_forks_repo_licenses": ["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.8928571429, "max_line_length": 85, "alphanum_fraction": 0.664013267, "num_tokens": 894, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.4835984519866741}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_TOOLBOX_ELLIPTIC_FUNCTIONS_SCALAR_ELLPE_HPP_INCLUDED\n#define NT2_TOOLBOX_ELLIPTIC_FUNCTIONS_SCALAR_ELLPE_HPP_INCLUDED\n#include <nt2/toolbox/elliptic/functions/ellpe.hpp>\n#include <boost/math/special_functions.hpp>\n#include <nt2/include/constants/digits.hpp>\n#include <nt2/include/constants/real.hpp>\n#include <nt2/toolbox/trigonometric/constants.hpp>\n#include <nt2/toolbox/polynomials/functions/scalar/impl/horner.hpp>\n#include <nt2/include/functions/scalar/is_ltz.hpp>\n#include <nt2/include/functions/scalar/is_eqz.hpp>\n#include <nt2/include/functions/scalar/oneminus.hpp>\n#include <nt2/include/functions/scalar/sqrt.hpp>\n#include <nt2/include/functions/scalar/log.hpp>\n#include <nt2/sdk/error/policies.hpp>\n\n/////////////////////////////////////////////////////////////////////////////\n// Implementation when type A0 is arithmetic_\n/////////////////////////////////////////////////////////////////////////////\nnamespace nt2 { namespace ext\n{\n  NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::ellpe_, tag::cpu_\n                            , (A0)\n                            , (scalar_< arithmetic_<A0> >)\n                            )\n  {\n\n    typedef typename boost::dispatch::meta::as_floating<A0>::type result_type;\n\n    NT2_FUNCTOR_CALL(1)\n    {\n      return nt2::ellpe(result_type(a0));\n    }\n  };\n} }\n\n\n/////////////////////////////////////////////////////////////////////////////\n// Implementation when type A0 is double\n/////////////////////////////////////////////////////////////////////////////\nnamespace nt2 { namespace ext\n{\n  NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::ellpe_, tag::cpu_\n                            , (A0)\n                            , (scalar_< double_<A0> >)\n                            )\n  {\n\n    typedef A0 result_type;\n\n    NT2_FUNCTOR_CALL(1)\n    {\n      typedef result_type type;\n      if (a0>One<A0>()||(is_ltz(a0))) return Nan<type>();\n      if (is_eqz(a0))  return One<type>();\n      if (a0 == One<A0>()) return Pio_2<type>();\n      return boost::math::ellint_2(sqrt(oneminus(type(a0))), nt2_policy());\n    }\n  };\n} }\n\n\n/////////////////////////////////////////////////////////////////////////////\n// Implementation when type A0 is float\n/////////////////////////////////////////////////////////////////////////////\nnamespace nt2 { namespace ext\n{\n  NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::ellpe_, tag::cpu_\n                            , (A0)\n                            , (scalar_< single_<A0> >)\n                            )\n  {\n    typedef A0 result_type;\n    NT2_FUNCTOR_CALL(1)\n    {\n      if (a0>One<A0>()||(is_ltz(a0))) return Nan<A0>();\n      if (is_eqz(a0))  return One<A0>();\n      if (a0 == One<A0>()) return Pio_2<A0>();\n      A0 tmp1 = horner< NT2_HORNER_COEFF(float, 11,\n                              (0x392102f5,\n                               0x3b246c1b,\n                               0x3c0e578f,\n                               0x3c2fe240,\n                               0x3bfebca9,\n                               0x3bf882cf,\n                               0x3c3d8b3f,\n                               0x3cb2d89a,\n                               0x3d68ac90,\n                               0x3ee2e430,\n                               0x3f800000) ) > (a0);\n      A0 tmp2 = horner< NT2_HORNER_COEFF(float, 10,\n                                    (0x38098de4,\n                                     0x3a84557e,\n                                     0x3bd53114,\n                                     0x3c8a54f6,\n                                     0x3cd67118,\n                                     0x3d0925e1,\n                                     0x3d2ef92b,\n                                     0x3d6fffe9,\n                                     0x3dc00000,\n                                     0x3e800000\n                                     ) ) > (a0);\n      return tmp1-nt2::log(a0)*a0*tmp2;\n    }\n  };\n} }\n\n\n#endif\n", "meta": {"hexsha": "522f8904f077821a89606de1241f7844c95ae7e7", "size": 4363, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/elliptic/include/nt2/toolbox/elliptic/functions/scalar/ellpe.hpp", "max_stars_repo_name": "timblechmann/nt2", "max_stars_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-09-14T00:23:53.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-14T12:51:18.000Z", "max_issues_repo_path": "modules/core/elliptic/include/nt2/toolbox/elliptic/functions/scalar/ellpe.hpp", "max_issues_repo_name": "timblechmann/nt2", "max_issues_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/core/elliptic/include/nt2/toolbox/elliptic/functions/scalar/ellpe.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": 37.2905982906, "max_line_length": 80, "alphanum_fraction": 0.4315837726, "num_tokens": 988, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079209, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.48356339482009797}}
{"text": "#include <iostream>\n#include <vector>\n#include <set>\n#include <iterator>\n#include <math.h>\n#include <chrono>\n#include <exception>\n#include <queue>\n#include <boost/math/distributions/normal.hpp>\n#include <sys/time.h>\n#include \"ptss_dse.hpp\"\n#include \"ptss_config.hpp\"\n#include \"ptss_pkmin.hpp\"\n\nusing namespace std;\n#define NSAMPLES 100\n\n\nint main(int argc, char **argv) {\n    if (argc < 2) {\n        cout << \"Enter The deadline, Peak Power Cap\" << endl;\n        exit(EXIT_FAILURE);\n    }\n    double deadline   = atof(argv[1]);\n    //vector<double> pkp_cap  = {8.5,9.22,9.94,10.66,11.38,12.11,12.83,13.55,14.27,15.0};\n    vector<double> pkp_cap  = {9,10,11,12,13,14,15,16,17};\n\n    // struct timeval t1, t2;\n    // gettimeofday(&t1,NULL);\n    int j = NSAMPLES,i = 0;\n    for (i = 0; i < pkp_cap.size();i++) {\n        j = NSAMPLES;\n        while (j > 0) {\n            cout << \"(\"<<i<<\",\"<<j<<\") Iteration\"<<endl;\n            ptss_DSE_hrt obj(deadline,pkp_cap[i]);\n            obj.display();\n            j--;\n        }\n    }\n    // gettimeofday(&t2,NULL);\n    // double elapsed  = t2.tv_sec-t1.tv_sec;\n}", "meta": {"hexsha": "aade6c2ee43c0c4080ef38e20673c51f53bca4d7", "size": 1100, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ptss_test_pkmin.cpp", "max_stars_repo_name": "Arka2009/ptss-dse", "max_stars_repo_head_hexsha": "9d56511635b5f87d020996ec4b89d224a97ade93", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ptss_test_pkmin.cpp", "max_issues_repo_name": "Arka2009/ptss-dse", "max_issues_repo_head_hexsha": "9d56511635b5f87d020996ec4b89d224a97ade93", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ptss_test_pkmin.cpp", "max_forks_repo_name": "Arka2009/ptss-dse", "max_forks_repo_head_hexsha": "9d56511635b5f87d020996ec4b89d224a97ade93", "max_forks_repo_licenses": ["BSD-3-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.1904761905, "max_line_length": 89, "alphanum_fraction": 0.5790909091, "num_tokens": 344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.48356338907551855}}
{"text": "#include <algorithm>\n#include <boost/optional.hpp>\n#include <climits>\n#include <cmath>\n#include <cstdio>\n#include <cstring>\n#include <functional>\n#include <iostream>\n#include <limits>\n#include <list>\n#include <map>\n#include <numeric>\n#include <queue>\n#include <sstream>\n#include <string>\n#include <tuple>\n#include <type_traits>\n#include <unordered_map>\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#define INT(x) (static_cast<int>(x))\n#define MODNUM (INT(1e9 + 7))\n#define MOD(x) ((x) % MODNUM)\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\ninline long long mod_pow(long long a, long long n, long long mod) {\n\tlong long ret = 1;\n\twhile(n != 0) {\n\t\tif(n % 2) {\n\t\t\tret = (ret * a) % mod;\n\t\t}\n\t\ta = (a * a) % mod, n /= 2;\n\t}\n\treturn ret;\n}\n\n// mod\u306e\u9006\u5143\ninline long long mod_inv(long long n, long long mod) {\n\treturn mod_pow(n, mod - 2, mod);\n}\n\n// \u30a8\u30e9\u30c8\u30b9\u30c6\u30cd\u30b9\u306e\u7be9\ntemplate <typename T>\ninline std::vector<T> sieve_of_eratosthenes(T n) {\n\tstd::vector<T> sieve(n, 0);\n\tfor(int i = 2; i < n; i++) {\n\t\tsieve[i] = i;\n\t}\n\tT i = 2;\n\twhile(i * i < n) {\n\t\tif(sieve[i]) {\n\t\t\tfor(T j = i * i; j < n; j += i) {\n\t\t\t\tsieve[j] = 0;\n\t\t\t}\n\t\t}\n\t\ti++;\n\t}\n\treturn sieve;\n}\n\n// \u7d20\u6570\u30ea\u30b9\u30c8\ntemplate <typename T>\ninline std::vector<T> prime_list(T n) {\n\tstd::vector<T> primes = sieve_of_eratosthenes(n);\n\tprimes.erase(std::remove(primes.begin(), primes.end(), 0), primes.end());\n\treturn primes;\n}\n\n// \u7d20\u56e0\u6570\u5206\u89e3(\u7d20\u6570\u8868\u3092\u7528\u3044\u308b)\ninline std::unordered_map<long long, int>\nfactor(long long n, std::vector<long long>& primes) {\n\tstd::unordered_map<long long, int> factors;\n\tfor(int i = 0; primes[i] * primes[i] <= n; i++) {\n\t\tint j = 0;\n\t\twhile(n % primes[i] == 0) {\n\t\t\tn /= primes[i];\n\t\t\tj++;\n\t\t}\n\t\tif(j != 0) {\n\t\t\tfactors[primes[i]] = j;\n\t\t}\n\t}\n\tif(n != 1) {\n\t\tfactors[n] = 1;\n\t}\n\treturn factors;\n}\n\n// vector\u306e\u8981\u7d20\u3059\u3079\u3066\u306e\u6700\u5c0f\u516c\u500d\u6570\u3092mod\u3067\u5272\u3063\u305f\u4f59\u308a\u3092\u8fd4\u3059\ntemplate <typename T>\ninline long long\nmod_lcm(std::vector<T>& v, std::vector<long long>& primes, long long mod) {\n\tint n = v.size();\n\tstd::unordered_map<long long, int> lcm_factors;\n\tfor(int i = 0; i < n; i++) {\n\t\tstd::unordered_map<long long, int> factors = factor(v[i], primes);\n\t\tfor(const std::pair<long long, int>& factor : factors) {\n\t\t\tif(lcm_factors[factor.first] < factor.second) {\n\t\t\t\tlcm_factors[factor.first] = factor.second;\n\t\t\t}\n\t\t}\n\t}\n\tlong long retval = 1;\n\tfor(const std::pair<long long, int>& factor : lcm_factors) {\n\t\tretval = (retval * mod_pow(factor.first, factor.second, mod)) % mod;\n\t}\n\treturn retval;\n}\n\nint main() {\n\tint n;\n\tscanf(\"%d\", &n);\n\tVI a(n);\n\tREP(i, n) { scanf(\"%d\", &a[i]); }\n\tvector<ll> primes = prime_list<ll>(1e6 + 100);\n\tll lcmall = mod_lcm(a, primes, MODNUM);\n\tll result = 0;\n\tREP(i, n) { result = MOD(result + MOD(lcmall * mod_inv(a[i], MODNUM))); }\n\tprintf(\"%lld\\n\", result);\n\treturn 0;\n}\n", "meta": {"hexsha": "4f675d91d2ff756237c6438a718bc84678c16412", "size": 3665, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AtCoder/ABC152/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/ABC152/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/ABC152/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": 21.0632183908, "max_line_length": 76, "alphanum_fraction": 0.6035470668, "num_tokens": 1270, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.48356338907551855}}
{"text": "#include <iostream>\n#include <vector>\n\n#include <boost/scope_exit.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/mpi/distributed_matrix.hpp>\n#include <amgcl/io/mm.hpp>\n\n#include <amgcl/profiler.hpp>\n\nnamespace amgcl {\n    profiler<> prof;\n}\n\nnamespace math = amgcl::math;\n\ntemplate <class Val>\nvoid assemble(\n        int n, int beg, int end,\n        std::vector<int> &ptr,\n        std::vector<int> &col,\n        std::vector<Val> &val\n        )\n{\n    int chunk = end - beg;\n\n    ptr.clear(); ptr.reserve(chunk + 1); ptr.push_back(0);\n    col.clear(); col.reserve(chunk * 4);\n    val.clear(); val.reserve(chunk * 4);\n\n    for(int j = beg, i = 0; j < end; ++j, ++i) {\n        if (j > 0) {\n            col.push_back(j - 1);\n            val.push_back(-math::identity<Val>());\n        }\n\n        col.push_back(j);\n        val.push_back(2 * math::identity<Val>());\n\n        if (j+1 < n) {\n            col.push_back(j+1);\n            val.push_back(-math::identity<Val>());\n        }\n\n        if (j+5 < n) {\n            col.push_back(j+5);\n            val.push_back(-0.1 * math::identity<Val>());\n        }\n\n        ptr.push_back(col.size());\n    }\n}\n\ntemplate <class Val>\nvoid test() {\n    typedef typename math::rhs_of<Val>::type Rhs;\n\n    amgcl::mpi::communicator comm(MPI_COMM_WORLD);\n\n    int n = 16;\n    int chunk_len = (n + comm.size - 1) / comm.size;\n    int chunk_beg = std::min(n, chunk_len * comm.rank);\n    int chunk_end = std::min(n, chunk_len * (comm.rank + 1));\n    int chunk = chunk_end - chunk_beg;\n\n    std::vector<int> chunks(comm.size);\n    MPI_Allgather(&chunk, 1, MPI_INT, &chunks[0], 1, MPI_INT, comm);\n    std::vector<int> displ(comm.size, 0);\n    for(int i = 1; i < comm.size; ++i)\n        displ[i] = displ[i-1] + chunks[i-1];\n\n    std::vector<int>    ptr;\n    std::vector<int>    col;\n    std::vector<Val> val;\n    std::vector<Rhs> x(chunk);\n    std::vector<Rhs> y(chunk);\n\n    assemble(n, chunk_beg, chunk_end, ptr, col, val);\n\n    for(int i = 0; i < chunk; ++i) x[i] = math::constant<Rhs>(drand48());\n\n    typedef amgcl::backend::builtin<Val> Backend;\n    typedef amgcl::mpi::distributed_matrix<Backend> Matrix; \n\n    Matrix A(comm, std::tie(chunk, ptr, col, val), chunk);\n\n    auto B = amgcl::mpi::product(A, A);\n    B->move_to_backend();\n\n    amgcl::backend::spmv(1, *B, x, 0, y);\n\n    std::vector<Rhs> X(n), R(n);\n    MPI_Gatherv(&x[0], chunk, amgcl::mpi::datatype<Rhs>(), &X[0], &chunks[0], &displ[0], amgcl::mpi::datatype<Rhs>(), 0, comm);\n    MPI_Gatherv(&y[0], chunk, amgcl::mpi::datatype<Rhs>(), &R[0], &chunks[0], &displ[0], amgcl::mpi::datatype<Rhs>(), 0, comm);\n\n    if (comm.rank == 0) {\n        std::vector<Rhs> Y(n);\n        assemble(n, 0, n, ptr, col, val);\n\n        amgcl::backend::crs<Val> A( std::tie(n, ptr, col, val) );\n        amgcl::backend::spmv(1, *amgcl::backend::product(A, A), X, 0, Y);\n\n        double s = 0;\n        for(int i = 0; i < n; ++i) {\n            double d = math::norm(R[i] - Y[i]);\n            s += d * d;\n        }\n        std::cout << \"Error: \" << s << std::endl;\n    }\n}\n\nint main(int argc, char *argv[]) {\n    MPI_Init(&argc, &argv);\n    BOOST_SCOPE_EXIT(void) {\n        MPI_Finalize();\n    } BOOST_SCOPE_EXIT_END\n\n    test< double >();\n    test< amgcl::static_matrix<double,2,2> >();\n}\n", "meta": {"hexsha": "85cc98cf921780ef90fba41d3f5b60000d530662", "size": 3347, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/mpi/test_spmm.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/test_spmm.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/test_spmm.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": 26.9919354839, "max_line_length": 127, "alphanum_fraction": 0.5566178667, "num_tokens": 1055, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.48356338907551855}}
{"text": "/**\n * @file clipper.cpp\n * @brief Core CLIPPER algorithm: find dense clusters w.r.t constraints\n * @author Parker Lusk <plusk@mit.edu>\n * @date 3 October 2020\n */\n\n#include <chrono>\n#include <iostream>\n#include <functional>\n#include <limits>\n#include <queue>\n#include <random>\n#include <utility>\n#include <vector>\n\n#include <Eigen/Sparse>\n\n#include \"clipper/find_dense_cluster.h\"\n#include \"clipper/utils.h\"\n\nnamespace clipper {\n\n\n\n\ninline void homotopy(Eigen::MatrixXd& Md, const Eigen::MatrixXd& M, const Eigen::MatrixXd& Cb, double d)\n{\n  // if (M.cols() < 2600) {\n    Md = M - d*Cb;\n  //   return;\n  // }\n\n// #pragma omp parallel for default(none) shared(Md, M, d, Cb)\n//   for (size_t c=0; c<M.cols(); ++c) {\n//     Md.col(c) = M.col(c) - d*Cb.col(c);\n//   }\n}\n\n\ntemplate <typename T, IsEigenBase<T>>\nSolution findDenseCluster(const T& _M, const T& C,\n                          const Eigen::VectorXd& u0, const Params& params)\n{\n  const auto t1 = std::chrono::high_resolution_clock::now();\n  //\n  // Initialization\n  //\n\n  const size_t n = _M.cols();\n\n  // Zero out any entry corresponding to an active constraint\n  const Eigen::MatrixXd M = _M.cwiseProduct(C);\n\n  // Binary complement of constraint matrix\n  const Eigen::MatrixXd Cb = Eigen::MatrixXd::Ones(n,n) - C;\n\n  // one step of power method to have a good scaling of u\n  Eigen::VectorXd u = M * u0;\n  u /= u.norm();\n\n  // initial value of d\n  double d = 0; // zero if there are no active constraints\n  Eigen::MatrixXd Cbu = Cb * u;\n  const auto idxD = ((Cbu.array()>params.eps) && (u.array()>params.eps));\n  if (idxD.sum() > 0) {\n    Eigen::MatrixXd Mu = M * u;\n    const Eigen::VectorXd num = idxD.select(Mu, std::numeric_limits<double>::infinity());\n    const Eigen::VectorXd den = idxD.select(Cbu, 1);\n    d = (num.array() / den.array()).minCoeff();\n  }\n\n  Eigen::MatrixXd Md = Eigen::MatrixXd(M.rows(), M.cols());\n  homotopy(Md, M, Cb, d);\n\n  // initialize memory\n  Eigen::VectorXd gradF = Eigen::VectorXd(n);\n  Eigen::VectorXd unew = Eigen::VectorXd(n);\n  Eigen::VectorXd Mu = Eigen::VectorXd(n);\n  Eigen::VectorXd num = Eigen::VectorXd(n);\n  Eigen::VectorXd den = Eigen::VectorXd(n);\n\n  //\n  // Orthogonal projected gradient ascent with homotopy\n  //\n\n  double F = 0; // objective value\n\n  size_t i, j, k; // iteration counters\n  for (i=0; i<params.maxoliters; ++i) {\n    F = u.transpose() * Md * u; // current objective value\n\n    //\n    // Orthogonal projected gradient ascent\n    //\n\n    for (j=0; j<params.maxiniters; ++j) {\n      gradF = Md * u;\n\n      // if (params.orthogonal) {\n      //   // orthogonal projection of gradient onto tangent plane to S^n at u\n      //   gradF = gradF - (gradF.transpose() * u) * u;\n\n      //   if (gradF.norm() < params.tol_Fop) break;\n      // }\n\n      // double alpha = params.alpha;\n      // if (alpha <= 0) {\n      //   const auto idxA = ((gradF.array()<-params.eps) && (u.array()>params.eps));\n      //   if (idxA.sum()) {\n      //     const Eigen::VectorXd num = idxA.select(u, std::numeric_limits<double>::infinity());\n      //     const Eigen::VectorXd den = idxA.select(gradF, 1);\n      //     alpha = (num.array() / den.array()).abs().minCoeff();\n      //   } else {\n      //     alpha = std::pow(1.0/params.beta, 3) / gradF.norm();\n      //   }\n      // }\n\n      double alpha = 1;\n\n      //\n      // Backtracking line search on gradient ascent\n      //\n\n      double Fnew = 0, deltaF = 0;\n      for (k=0; k<params.maxlsiters; ++k) {\n        unew = u + alpha * gradF;                     // gradient step\n        unew = unew.cwiseMax(0);                      // project onto positive orthant\n        unew.normalize();                             // project onto S^n\n        Fnew = unew.transpose() * Md * unew;          // new objective value after step\n        deltaF = Fnew - F;                            // change in objective value\n\n        if (deltaF < -params.eps) {\n          // objective value decreased---we need to backtrack, so reduce step size\n          alpha = alpha * params.beta;\n        } else {\n          break; // obj value increased, stop line search\n        }\n      }\n      const double deltau = (unew - u).norm();\n\n      // update values\n      F = Fnew;\n      u = unew;\n\n      // check if desired accuracy has been reached by gradient ascent \n      if (deltau < params.tol_u || std::abs(deltaF) < params.tol_F) break;\n    }\n\n    //\n    // Increase d\n    //\n\n    Cbu = Cb * u;\n    const auto idxD = ((Cbu.array() > params.eps) && (u.array() > params.eps));\n    if (idxD.sum() > 0) {\n      Mu = M * u;\n      num = idxD.select(Mu, std::numeric_limits<double>::infinity());\n      den = idxD.select(Cbu, 1);\n      const double deltad = (num.array() / den.array()).abs().minCoeff();\n\n      d += deltad;\n      homotopy(Md, M, Cb, d);\n\n    } else {\n      break;\n    }\n  }\n\n  //\n  // Generate output\n  //\n\n  // estimate cluster size using largest eigenvalue\n  const int omega = std::round(F);\n\n  // extract indices of nodes in identified dense cluster\n  std::vector<int> I = utils::findIndicesOfkLargest(u, omega);\n\n  const auto t2 = std::chrono::high_resolution_clock::now();\n  const auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(t2 - t1);\n  const double elapsed = static_cast<double>(duration.count()) / 1e9;\n\n  Solution soln;\n  soln.t = elapsed;\n  soln.ifinal = i;\n  std::swap(soln.nodes, I);\n  soln.u.swap(u);\n  soln.score = F;\n\n  return soln;\n}\n\ntemplate <typename T, IsEigenBase<T>>\nSolution findDenseCluster(const T& M, const T& C,\n                          const Params& params)\n{\n  return findDenseCluster(M, C, utils::randvec(M.cols()), params);\n}\n\n// template specializations for dense and sparse Eigen matrices\ntemplate Solution findDenseCluster<Eigen::MatrixXd>(const Eigen::MatrixXd&,\n            const Eigen::MatrixXd&, const Eigen::VectorXd&, const Params&);\ntemplate Solution findDenseCluster<SpMat>(const SpMat&,\n            const SpMat&, const Eigen::VectorXd&, const Params&);\ntemplate Solution findDenseCluster<Eigen::MatrixXd>(const Eigen::MatrixXd&,\n            const Eigen::MatrixXd&, const Params&);\ntemplate Solution findDenseCluster<SpMat>(const SpMat&,\n            const SpMat&, const Params&);\n\n\n\n\n// methods for sparse matrices from scoreSparseConsistency\n\n\n// sparse method similar to the above with the difference that M,C have zero\n// elements along the diagonal\nSolution findDenseClusterOfSparseGraph(const SpMat &M, const SpMat &C,\n                                       const Eigen::VectorXd &u0,\n                                       const Params &params) {\n  // std::cout << \"number of threads : \" << Eigen::nbThreads() << std::endl;\n  const auto t1 = std::chrono::high_resolution_clock::now();\n  //\n  // Initialization\n  //\n\n  const size_t n = M.cols();\n\n  // un-necessary compute\n  // Zero out any entry corresponding to an active constraint\n  // const Eigen::MatrixXd M = _M.cwiseProduct(C);\n\n  // this needs to be replaced\n  // Binary complement of constraint matrix\n  // const Eigen::MatrixXd Cb = Eigen::MatrixXd::Ones(n, n) - C;\n  const Eigen::VectorXd ones = Eigen::VectorXd::Ones(n);\n\n  // one step of power method to have a good scaling of u\n  Eigen::VectorXd u = M * u0 + u0; // since M here is not diagonal\n  // Eigen::VectorXd u = u0;\n  u /= u.norm();\n\n  // initial value of d\n  double d = 0; // zero if there are no active constraints\n  // Eigen::MatrixXd Cbu = Cb * u;\n  Eigen::MatrixXd Cbu = ones * u.sum() - C * u - u;\n  const auto idxD = ((Cbu.array() > params.eps) && (u.array() > params.eps));\n  if (idxD.sum() > 0) {\n    Eigen::MatrixXd Mu = M * u + u;\n    const Eigen::VectorXd num =\n        idxD.select(Mu, std::numeric_limits<double>::infinity());\n    const Eigen::VectorXd den = idxD.select(Cbu, 1);\n    d = (num.array() / den.array()).minCoeff();\n  }\n\n  // this should be replaced with an efficient representation\n  // Md = M - d * Cb;\n  // Eigen::MatrixXd Md = Eigen::MatrixXd(M.rows(), M.cols());\n  // homotopy(Md, M, Cb, d);\n\n  // initialize memory\n  Eigen::VectorXd gradF = Eigen::VectorXd(n);\n  Eigen::VectorXd gradFnew = Eigen::VectorXd(n);\n  Eigen::VectorXd unew = Eigen::VectorXd(n);\n  Eigen::VectorXd Mu = Eigen::VectorXd(n);\n  Eigen::VectorXd num = Eigen::VectorXd(n);\n  Eigen::VectorXd den = Eigen::VectorXd(n);\n\n  //\n  // Orthogonal projected gradient ascent with homotopy\n  //\n\n  double F = 0; // objective value\n\n  size_t i, j, k; // iteration counters\n  for (i = 0; i < params.maxoliters; ++i) {\n    // F = u.transpose() * Md * u; // current objective value\n    // gradF = (1 + d) * (M * u + u) - d * ones * u.sum();\n    gradF = (1 + d) * u - d * ones * u.sum() + M * u + d * C * u;\n    F = u.dot(gradF);\n    // std::cout << std::endl;\n    // std::cout << \"obj F: \" << F << \" - dval: \" << d << std::endl;\n    //\n    // Orthogonal projected gradient ascent\n    //\n\n    for (j = 0; j < params.maxiniters; ++j) {\n      // gradF = Md * u;\n\n      // if (params.orthogonal) {\n      //   // orthogonal projection of gradient onto tangent plane to S^n at u\n      //   gradF = gradF - (gradF.transpose() * u) * u;\n\n      //   if (gradF.norm() < params.tol_Fop) break;\n      // }\n\n      // double alpha = params.alpha;\n      // if (alpha <= 0) {\n      //   const auto idxA = ((gradF.array()<-params.eps) &&\n      //   (u.array()>params.eps)); if (idxA.sum()) {\n      //     const Eigen::VectorXd num = idxA.select(u,\n      //     std::numeric_limits<double>::infinity()); const Eigen::VectorXd den\n      //     = idxA.select(gradF, 1); alpha = (num.array() /\n      //     den.array()).abs().minCoeff();\n      //   } else {\n      //     alpha = std::pow(1.0/params.beta, 3) / gradF.norm();\n      //   }\n      // }\n\n      double alpha = 1;\n\n      //\n      // Backtracking line search on gradient ascent\n      //\n\n      double Fnew = 0, deltaF = 0;\n      for (k = 0; k < params.maxlsiters; ++k) {\n        unew = u + alpha * gradF; // gradient step\n        unew = unew.cwiseMax(0);  // project onto positive orthant\n        unew.normalize();         // project onto S^n\n        // Fnew = unew.transpose() * Md * unew; // new objective value after\n        // step\n        // gradFnew = (1 + d) * (M * unew + unew) - d * ones * unew.sum();\n        gradFnew =\n            (1 + d) * unew - d * ones * unew.sum() + M * unew + d * C * unew;\n        Fnew = unew.dot(gradFnew);\n\n        deltaF = Fnew - F; // change in objective value\n\n        if (deltaF < -params.eps) {\n          // objective value decreased---we need to backtrack, so reduce step\n          // size\n          alpha = alpha * params.beta;\n        } else {\n          // std::cout << \"breaking at \" << k << \" out of ls \" <<\n          // params.maxlsiters\n          //           << std::endl;\n          break; // obj value increased, stop line search\n        }\n      }\n      const double deltau = (unew - u).norm();\n\n      // std::cout << \"Fnew: \" << Fnew << \" Unew: \" << unew.sum() << std::endl;\n      // update values\n      F = Fnew;\n      u = unew;\n      // gradF = gradFnew;\n\n      // check if desired accuracy has been reached by gradient ascent\n      if (deltau < params.tol_u || std::abs(deltaF) < params.tol_F) {\n        // std::cout << \"breaking at \" << j << \" out of in \" <<\n        // params.maxiniters\n        //           << std::endl;\n        break;\n      }\n    }\n\n    //\n    // Increase d\n    //\n\n    // Cbu = Cb * u;\n    Cbu = ones * u.sum() - C * u - u;\n    const auto idxD = ((Cbu.array() > params.eps) && (u.array() > params.eps));\n    if (idxD.sum() > 0) {\n      Mu = M * u + u;\n      num = idxD.select(Mu, std::numeric_limits<double>::infinity());\n      den = idxD.select(Cbu, 1);\n      const double deltad = (num.array() / den.array()).abs().minCoeff();\n\n      // std::cout << \"delta d:\" << deltad << std::endl;\n      d += deltad;\n      // homotopy(Md, M, Cb, d);\n\n    } else {\n      // std::cout << \"breaking at \" << i << \" out of oo \" << params.maxoliters\n      //           << std::endl;\n      break;\n    }\n  }\n  //\n  // Generate output\n  //\n\n  // estimate cluster size using largest eigenvalue\n  const int omega = std::round(F);\n\n  // extract indices of nodes in identified dense cluster\n  std::vector<int> I = utils::findIndicesOfkLargest(u, omega);\n\n  const auto t2 = std::chrono::high_resolution_clock::now();\n  const auto duration =\n      std::chrono::duration_cast<std::chrono::nanoseconds>(t2 - t1);\n  const double elapsed = static_cast<double>(duration.count()) / 1e9;\n\n  Solution soln;\n  soln.t = elapsed;\n  soln.ifinal = i;\n  std::swap(soln.nodes, I);\n  soln.u.swap(u);\n  soln.score = F;\n\n  return soln;\n}\n\n\nSolution findDenseClusterOfSparseGraph(const SpMat &M, const SpMat &C,\n                                       const Params &params) {\n  return findDenseClusterOfSparseGraph(M, C,\n                                       C * Eigen::VectorXd::Ones(C.cols()) +\n                                           Eigen::VectorXd::Ones(C.cols()),\n                                       params);\n}\n\n} // ns clipper\n", "meta": {"hexsha": "ae72a63e8a89c635f77387241d760dfd9dd046d0", "size": 12919, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/find_dense_cluster.cpp", "max_stars_repo_name": "ash-aldujaili/clipper", "max_stars_repo_head_hexsha": "2e56b2058e8482c33ece3390b3b1b558301eacbe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/find_dense_cluster.cpp", "max_issues_repo_name": "ash-aldujaili/clipper", "max_issues_repo_head_hexsha": "2e56b2058e8482c33ece3390b3b1b558301eacbe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/find_dense_cluster.cpp", "max_forks_repo_name": "ash-aldujaili/clipper", "max_forks_repo_head_hexsha": "2e56b2058e8482c33ece3390b3b1b558301eacbe", "max_forks_repo_licenses": ["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.9808153477, "max_line_length": 104, "alphanum_fraction": 0.5670717548, "num_tokens": 3590, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959543, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.48356338907551855}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n#include <math.h>\n#define PI  3.141592\n//LEG LINK LENGTHS\n#define L1 0.12\n#define L2 0.303\n#define L3 0.303\n\n#define FL 0\n#define FR 1\n#define BL 2\n#define BR 3\n#define MASS 11.168\n/*inertia  = 0.178402 -0.0458692 0.0180358 \n-0.0458692 0.470056 -8.95236e-08 \n0.0180358 -8.95236e-08 0.446392 \n*/\n//LEG-FL\n\nint bound_end_eff_pos(double &x, double &y, double &z)\n{\n    if(x<= 0.4 && x>= - 0.4)\n    {\n        if(y <= 0.22 && y>= 0)\n        {\n            if(z<= -0.15 && z>= -0.4)\n            {\n                return 1;\n            }\n        }\n    }\n    return 0;\n}\nvoid _forward_kinematics_FL(Eigen::Vector3d &end_effector_pos, Eigen::Vector3d &thetas, float l1 = L1, float l2 = L2, float l3 = L3)\n{\n    end_effector_pos[0] = (l2*sin(thetas[1]) + l3*sin(thetas[1] + thetas[2]));\n    end_effector_pos[1] = l1*cos(thetas[0])+(l2*cos(thetas[1]) + l3*cos(thetas[1] + thetas[2]))*sin(thetas[0]);\n    end_effector_pos[2] = l1*sin(thetas[0])-((l2*cos(thetas[1]) + l3*cos(thetas[1] + thetas[2]))*cos(thetas[0]));\n}\n\nvoid _inverse_kinematics_FL(Eigen::Vector3d &thetas, Eigen::Vector3d &end_effector_pos, float l1 = L1, float l2 = L2, float l3 = L3)\n{\n    double x = end_effector_pos[0];\n    double y = end_effector_pos[1];\n    double z = end_effector_pos[2];\n    int isValid = bound_end_eff_pos(x,y,z);\n    if(!isValid)\n    {\n       // std::cout<<\"invalid point: \"<<x<<\",\"<<y<<\",\"<<z<<std::endl;\n    }\n    double r, th23, th1, th2, th3,t;\n    r = sqrt(y*y + z*z -l1*l1);\n    th1 = atan2(y*r + z*l1, y*l1 - z*r);\n    t = (2*l2*x + sqrt(4*pow(l2,2)*pow(r,2) - pow(r,4) + 4*pow(l2,2)*pow(x,2) - 2*pow(r,2)*pow(x,2) - pow(x,4)))/(2*l2*r + pow(r,2) + pow(x,2));\n    th23 = atan2(2*t, 1-t*t);\n    th2 = atan2(x - l2*sin(th23), r - l2*cos(th23));\n    th3 = th23 - th2;\n    thetas[0]=th1;\n    thetas[1]=th2;\n    thetas[2]=th3;\n}\n\nvoid _jacobian_FL(Eigen::Matrix<double, 3, 3> &jacob, Eigen::Vector3d &thetas, float l1 = L1, float l2 = L2, float l3 = L3)\n{\n    jacob << 0,l2*cos(thetas[1]) + l3*cos(thetas[1] + thetas[2]),l3*cos(thetas[1] + thetas[2]),\n           (l2*cos(thetas[1]) + l3*cos(thetas[1] + thetas[2]))*cos(thetas[0]) - l1*sin(thetas[0]),(-l2*sin(thetas[1]) - l3*sin(thetas[1] + thetas[2]))*sin(thetas[0]),-l3*sin(thetas[1] + thetas[2])*sin(thetas[0]),\n           ((l2*cos(thetas[1]) + l3*cos(thetas[1] + thetas[2]))*sin(thetas[0])) +l1*cos(thetas[0]),(l2*sin(thetas[1]) + l3*sin(thetas[1] + thetas[2]))*cos(thetas[0]),l3*sin(thetas[1] + thetas[2])*cos(thetas[0]);\n\n}\n\nvoid _inverse_dynamics_FL(Eigen::Vector3d &torques, Eigen::Vector3d &force, Eigen::Vector3d &thetas, float l1 = L1, float l2 = L2, float l3 = L3)\n{\n    /*\n    Finds Joint torques for desired force at end effector\n    torques =  [abduction, hip, knee]\n    force = [x,y,z]\n    thetas = [abduction, hip, knee] angles in radians\n    l1, l2, l3 = link lengths\n    */\n    Eigen::Matrix<double,3,3> jacob;\n    _jacobian_FL(jacob, thetas);\n    torques = jacob.transpose()*force; \n}  \n\n\n//LEG-FR\nvoid _forward_kinematics_FR(Eigen::Vector3d &end_effector_pos, Eigen::Vector3d &thetas, float l1 = L1, float l2 = L2, float l3 = L3)\n{\n    end_effector_pos[0] = (l2*sin(thetas[1]) + l3*sin(thetas[1] + thetas[2]));\n    end_effector_pos[1] = -1*(l1*cos(thetas[0])+(l2*cos(thetas[1]) + l3*cos(thetas[1] + thetas[2]))*sin(thetas[0]));\n    end_effector_pos[2] = l1*sin(thetas[0])-((l2*cos(thetas[1]) + l3*cos(thetas[1] + thetas[2]))*cos(thetas[0]));\n}\n\nvoid _inverse_kinematics_FR(Eigen::Vector3d &thetas, Eigen::Vector3d &end_effector_pos, float l1 = L1, float l2 = L2, float l3 = L3)\n{\n    double x = end_effector_pos[0];\n    double y = -1*end_effector_pos[1];\n    double z = end_effector_pos[2];\n    int isValid = bound_end_eff_pos(x,y,z);\n    if(!isValid)\n    {\n       // std::cout<<\"invalid point: \"<<x<<\",\"<<y<<\",\"<<z<<std::endl;\n    }\n    double r, th23, th1, th2, th3,t;\n    r = sqrt(y*y + z*z -l1*l1);\n    th1 = atan2(y*r + z*l1, y*l1 - z*r);\n    t = (2*l2*x + sqrt(4*pow(l2,2)*pow(r,2) - pow(r,4) + 4*pow(l2,2)*pow(x,2) - 2*pow(r,2)*pow(x,2) - pow(x,4)))/(2*l2*r + pow(r,2) + pow(x,2));\n    th23 = atan2(2*t, 1-t*t);\n    th2 = atan2(x - l2*sin(th23), r - l2*cos(th23));\n    th3 = th23 - th2;\n    thetas[0]=th1;\n    thetas[1]=th2;\n    thetas[2]=th3;\n}\n\nvoid _jacobian_FR(Eigen::Matrix<double, 3, 3> &jacob, Eigen::Vector3d &thetas, float l1 = L1, float l2 = L2, float l3 = L3)\n{\n   jacob << 0,l2*cos(thetas[1]) + l3*cos(thetas[1] + thetas[2]),l3*cos(thetas[1] + thetas[2]),\n           (l2*cos(thetas[1]) + l3*cos(thetas[1] + thetas[2]))*cos(thetas[0]) - l1*sin(thetas[0]),(l2*sin(thetas[1]) + l3*sin(thetas[1] + thetas[2]))*sin(thetas[0]),l3*sin(thetas[1] + thetas[2])*sin(thetas[0]),\n           ((l2*cos(thetas[1]) + l3*cos(thetas[1] + thetas[2]))*sin(thetas[0])) +l1*cos(thetas[0]),(l2*sin(thetas[1]) + l3*sin(thetas[1] + thetas[2]))*cos(thetas[0]),l3*sin(thetas[1] + thetas[2])*cos(thetas[0]);\n}\n\nvoid _inverse_dynamics_FR(Eigen::Vector3d &torques, Eigen::Vector3d &force, Eigen::Vector3d &thetas, float l1 = L1, float l2 = L2, float l3 = L3)\n{\n    /*\n    Finds Joint torques for desired force at end effector\n    torques =  [abduction, hip, knee]\n    force = [x,y,z]\n    thetas = [abduction, hip, knee] angles in radians\n    l1, l2, l3 = link lengths\n    */\n    Eigen::Matrix<double,3,3> jacob;\n    _jacobian_FR(jacob, thetas);\n    torques = jacob.transpose()*force; \n    torques[0]=-1*torques[0];\n} \n\n//LEG-BL\nvoid _forward_kinematics_BL(Eigen::Vector3d &end_effector_pos, Eigen::Vector3d &thetas, float l1 = L1, float l2 = L2, float l3 = L3)\n{\n    end_effector_pos[0] = (l2*sin(thetas[1]) + l3*sin(thetas[1] + thetas[2]));\n    end_effector_pos[1] = l1*cos(thetas[0])+(l2*cos(thetas[1]) + l3*cos(thetas[1] + thetas[2]))*sin(thetas[0]);\n    end_effector_pos[2] = l1*sin(thetas[0])-((l2*cos(thetas[1]) + l3*cos(thetas[1] + thetas[2]))*cos(thetas[0]));\n}\n\nvoid _inverse_kinematics_BL(Eigen::Vector3d &thetas, Eigen::Vector3d &end_effector_pos, float l1 = L1, float l2 = L2, float l3 = L3)\n{\n    double x = end_effector_pos[0];\n    double y = end_effector_pos[1];\n    double z = end_effector_pos[2];\n    int isValid = bound_end_eff_pos(x,y,z);\n    if(!isValid)\n    {\n        //std::cout<<\"invalid point: \"<<x<<\",\"<<y<<\",\"<<z<<std::endl;\n    }\n    double r, th23, th1, th2, th3,t;\n    r = sqrt(y*y + z*z -l1*l1);\n    th1 = atan2(y*r + z*l1, y*l1 - z*r);\n    t = (2*l2*x + sqrt(4*pow(l2,2)*pow(r,2) - pow(r,4) + 4*pow(l2,2)*pow(x,2) - 2*pow(r,2)*pow(x,2) - pow(x,4)))/(2*l2*r + pow(r,2) + pow(x,2));\n    th23 = atan2(2*t, 1-t*t);\n    th2 = atan2(x - l2*sin(th23), r - l2*cos(th23));\n    th3 = th23 - th2;\n    thetas[0]=th1;\n    thetas[1]=th2;\n    thetas[2]=th3;\n}\n\nvoid _jacobian_BL(Eigen::Matrix<double, 3, 3> &jacob, Eigen::Vector3d &thetas, float l1 = L1, float l2 = L2, float l3 = L3)\n{\n   jacob << 0,l2*cos(thetas[1]) + l3*cos(thetas[1] + thetas[2]),l3*cos(thetas[1] + thetas[2]),\n           (l2*cos(thetas[1]) + l3*cos(thetas[1] + thetas[2]))*cos(thetas[0]) - l1*sin(thetas[0]),(-l2*sin(thetas[1]) - l3*sin(thetas[1] + thetas[2]))*sin(thetas[0]),-l3*sin(thetas[1] + thetas[2])*sin(thetas[0]),\n           ((l2*cos(thetas[1]) + l3*cos(thetas[1] + thetas[2]))*sin(thetas[0])) +l1*cos(thetas[0]),(l2*sin(thetas[1]) + l3*sin(thetas[1] + thetas[2]))*cos(thetas[0]),l3*sin(thetas[1] + thetas[2])*cos(thetas[0]);\n\n}\n\nvoid _inverse_dynamics_BL(Eigen::Vector3d &torques, Eigen::Vector3d &force, Eigen::Vector3d &thetas, float l1 = L1, float l2 = L2, float l3 = L3)\n{\n    /*\n    Finds Joint torques for desired force at end effector\n    torques =  [abduction, hip, knee]\n    force = [x,y,z]\n    thetas = [abduction, hip, knee] angles in radians\n    l1, l2, l3 = link lengths\n    */\n    Eigen::Matrix<double,3,3> jacob;\n    _jacobian_BL(jacob, thetas);\n    torques = jacob.transpose()*force; \n} \n\n//Leg - BR\nvoid _forward_kinematics_BR(Eigen::Vector3d &end_effector_pos, Eigen::Vector3d &thetas, float l1 = L1, float l2 = L2, float l3 = L3)\n{\n    end_effector_pos[0] = (l2*sin(thetas[1]) + l3*sin(thetas[1] + thetas[2]));\n    end_effector_pos[1] = -1*(l1*cos(thetas[0])+(l2*cos(thetas[1]) + l3*cos(thetas[1] + thetas[2]))*sin(thetas[0]));\n    end_effector_pos[2] = l1*sin(thetas[0])-((l2*cos(thetas[1]) + l3*cos(thetas[1] + thetas[2]))*cos(thetas[0]));\n}\n\nvoid _inverse_kinematics_BR(Eigen::Vector3d &thetas, Eigen::Vector3d &end_effector_pos, float l1 = L1, float l2 = L2, float l3 = L3)\n{\n    double x = end_effector_pos[0];\n    double y = -1*end_effector_pos[1];\n    double z = end_effector_pos[2];\n    int isValid = bound_end_eff_pos(x,y,z);\n    if(!isValid)\n    {\n       // std::cout<<\"invalid point: \"<<x<<\",\"<<y<<\",\"<<z<<std::endl;\n    }\n    double r, th23, th1, th2, th3,t;\n    r = sqrt(y*y + z*z -l1*l1);\n    th1 = atan2(y*r + z*l1, y*l1 - z*r);\n    t = (2*l2*x + sqrt(4*pow(l2,2)*pow(r,2) - pow(r,4) + 4*pow(l2,2)*pow(x,2) - 2*pow(r,2)*pow(x,2) - pow(x,4)))/(2*l2*r + pow(r,2) + pow(x,2));\n    th23 = atan2(2*t, 1-t*t);\n    th2 = atan2(x - l2*sin(th23), r - l2*cos(th23));\n    th3 = th23 - th2;\n    thetas[0]=th1;\n    thetas[1]=th2;\n    thetas[2]=th3;\n}\n\nvoid _jacobian_BR(Eigen::Matrix<double, 3, 3> &jacob, Eigen::Vector3d &thetas, float l1 = L1, float l2 = L2, float l3 = L3)\n{\n   jacob << 0,l2*cos(thetas[1]) + l3*cos(thetas[1] + thetas[2]),l3*cos(thetas[1] + thetas[2]),\n           (l2*cos(thetas[1]) + l3*cos(thetas[1] + thetas[2]))*cos(thetas[0]) - l1*sin(thetas[0]),(l2*sin(thetas[1]) + l3*sin(thetas[1] + thetas[2]))*sin(thetas[0]),l3*sin(thetas[1] + thetas[2])*sin(thetas[0]),\n           ((l2*cos(thetas[1]) + l3*cos(thetas[1] + thetas[2]))*sin(thetas[0])) +l1*cos(thetas[0]),(l2*sin(thetas[1]) + l3*sin(thetas[1] + thetas[2]))*cos(thetas[0]),l3*sin(thetas[1] + thetas[2])*cos(thetas[0]);\n\n\n}\n\nvoid _inverse_dynamics_BR(Eigen::Vector3d &torques, Eigen::Vector3d &force, Eigen::Vector3d &thetas, float l1 = L1, float l2 = L2, float l3 = L3)\n{\n    /*\n    Finds Joint torques for desired force at end effector\n    torques =  [abduction, hip, knee]\n    force = [x,y,z]\n    thetas = [abduction, hip, knee] angles in radians\n    l1, l2, l3 = link lengths\n    */\n    Eigen::Matrix<double,3,3> jacob;\n    _jacobian_BR(jacob, thetas);\n    torques = jacob.transpose()*force;\n    torques[0]=-1*torques[0];\n} \n\n\n\n\nvoid forward_kinematics(Eigen::Vector3d &thetas, Eigen::Vector3d &end_effector_pos, int leg, float l1 = L1, float l2 = L2, float l3 = L3)\n{\n    /*\n    Performs forward kinematics for a 3R spatial manipulator\n    thetas = [abduction, hip, knee] angles in radians\n    end_effector_pos = [x,y,z] in base frame\n    l1, l2, l3 = link lengths\n    FL=0\n    FR=1\n    BL=2\n    BR=3\n    */\n   if(leg == FL)\n   {\n       _forward_kinematics_FL(thetas, end_effector_pos);\n   }\n   else if(leg == FR)\n   {\n       _forward_kinematics_FR(thetas, end_effector_pos);\n   }\n   else if(leg == BL)\n   {\n       _forward_kinematics_BL(thetas, end_effector_pos);     \n   }\n   else if(leg == BR)\n   {\n       _forward_kinematics_BR(thetas, end_effector_pos);          \n   }\n   else\n   {\n       std::cout<<\"Invalid leg number, forward kinematics\"<<std::endl;\n   }\n   \n}\n\nvoid inverse_kinematics(Eigen::Vector3d &thetas, Eigen::Vector3d &end_effector_pos, int leg, float l1 = L1, float l2 = L2, float l3 = L3)\n{\n    /*\n    Performs forward kinematics for a 3R spatial manipulator\n    thetas = [abduction, hip, knee] angles in radians\n    end_effector_pos = [x,y,z] in base frame\n    l1, l2, l3 = link lengths\n    FL=0\n    FR=1\n    BL=2\n    BR=3\n    */\n   if(leg == FL)\n   {\n       _inverse_kinematics_FL(thetas, end_effector_pos);\n   }\n   else if(leg == FR)\n   {\n       _inverse_kinematics_FR(thetas, end_effector_pos);\n   }\n   else if(leg == BL)\n   {\n       _inverse_kinematics_BL(thetas, end_effector_pos);     \n   }\n   else if(leg == BR)\n   {\n       _inverse_kinematics_BR(thetas, end_effector_pos);          \n   }\n   else\n   {\n       std::cout<<\"Invalid leg number, inverse kinematics\"<<std::endl;\n   }\n   \n}\n\n\n\n\n\n\n// int main()\n// {\n\n//     // Eigen::Vector3d end_eff(0.15, 0.15, 0.2);\n//     // Eigen::Vector3d fwd_kin(0.0, 0.0, 0.0);\n//     // Eigen::Vector3d jpos(0,0,0);\n//     // Eigen::Matrix<double,3,3> jaco;\n//     // // _inverse_kinematics_BR(jpos, end_eff);\n//     // _forward_kinematics_FL(fwd_kin, jpos);\n//     // _jacobian_FL(jaco, jpos);\n//     // std::cout<<jaco<<std::endl;\n//     Eigen::Vector3d thetas(1.2, 0.3, 0.66);\n//     Eigen::Vector3d fwd_kin(0.0, 0.0, 0.0);\n//     Eigen::Vector3d inv_kin(0,0,0);\n//     Eigen::Vector3d fwd_kin2(0,0,0);\n//     _forward_kinematics_FL(fwd_kin, thetas);\n//     _inverse_kinematics_FL(inv_kin, fwd_kin);\n//     _forward_kinematics_FL(fwd_kin2, inv_kin);\n//     std::cout<<fwd_kin[0]<<\",\"<<fwd_kin[1]<<\",\"<<fwd_kin[2]<<std::endl;\n//     std::cout<<fwd_kin2[0]<<\",\"<<fwd_kin2[1]<<\",\"<<fwd_kin2[2]<<std::endl;\n\n//     return 0;\n// }", "meta": {"hexsha": "0c1ce385fe7801671c45bd7b2fca20c0148bbc9d", "size": 12773, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gym_learn_wbc/envs/raisim_dll/lib_src/leg.cpp", "max_stars_repo_name": "dhanajaya78/Whole_Body_Control_Quad-Sim", "max_stars_repo_head_hexsha": "b71a79256dcfe6588389b36a5ccfdee1b29edf28", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gym_learn_wbc/envs/raisim_dll/lib_src/leg.cpp", "max_issues_repo_name": "dhanajaya78/Whole_Body_Control_Quad-Sim", "max_issues_repo_head_hexsha": "b71a79256dcfe6588389b36a5ccfdee1b29edf28", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gym_learn_wbc/envs/raisim_dll/lib_src/leg.cpp", "max_forks_repo_name": "dhanajaya78/Whole_Body_Control_Quad-Sim", "max_forks_repo_head_hexsha": "b71a79256dcfe6588389b36a5ccfdee1b29edf28", "max_forks_repo_licenses": ["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.0231884058, "max_line_length": 212, "alphanum_fraction": 0.5973537932, "num_tokens": 5005, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839876, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.483563383330939}}
{"text": "#include \"cnn/nodes.h\"\n#include \"cnn/cnn.h\"\n#include \"cnn/training.h\"\n#include \"cnn/gpu-ops.h\"\n#include \"cnn/expr.h\"\n#include \"cnn/grad-check.h\"\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/archive/text_iarchive.hpp>\n\n#include <iostream>\n#include <fstream>\n\nusing namespace std;\nusing namespace cnn;\nusing namespace cnn::expr;\n\nint main(int argc, char** argv) {\n  cnn::Initialize(argc, argv);\n\n  // parameters\n  const unsigned int HIDDEN_SIZE = 8;\n  const unsigned int ITERATIONS = 30;\n  Model m;\n  SimpleSGDTrainer sgd(&m);\n  //MomentumSGDTrainer sgd(&m);\n\n  ComputationGraph cg;\n\n  Expression W = parameter(cg, m.add_parameters({HIDDEN_SIZE, 2}, 1.0, \"W\"));\n  Expression b = parameter(cg, m.add_parameters({HIDDEN_SIZE}, 0.0, \"b\"));\n  Expression V = parameter(cg, m.add_parameters({1, HIDDEN_SIZE}, 1.0, \"V\"));\n  Expression a = parameter(cg, m.add_parameters({1}, 0.0, \"a\"));\n\n  vector<cnn::real> x_values(2);  // set x_values to change the inputs to the network\n  Expression x = input(cg, {2}, &x_values);\n  cnn::real y_value;  // set y_value to change the target output\n  Expression y = input(cg, &y_value);\n\n  Expression h = tanh(W*x + b);\n  //Expression h = softsign(W*x + b);\n  Expression y_pred = V*h + a;\n  Expression loss = squared_distance(y_pred, y);\n\n  cg.PrintGraphviz();\n  if (argc == 2) {\n    ifstream in(argv[1]);\n    boost::archive::text_iarchive ia(in);\n    ia >> m;\n  }\n\n  // train the parameters\n  for (unsigned iter = 0; iter < ITERATIONS; ++iter) {\n    cnn::real loss = 0;\n    for (unsigned mi = 0; mi < 4; ++mi) {\n      bool x1 = mi % 2;\n      bool x2 = (mi / 2) % 2;\n      x_values[0] = x1 ? 1 : -1;\n      x_values[1] = x2 ? 1 : -1;\n      y_value = (x1 != x2) ? 1 : -1;\n      loss += as_scalar(cg.forward());\n\n//      CheckGrad(m, cg);\n\n      cg.backward();\n      sgd.update(1.0);\n    }\n    sgd.update_epoch();\n    loss /= 4;\n    cerr << \"E = \" << loss << endl;\n  }\n  boost::archive::text_oarchive oa(cout);\n  oa << m;\n}\n\n", "meta": {"hexsha": "2ca3031589d5624b256ba0facb049e949e07541e", "size": 1961, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/xor.cc", "max_stars_repo_name": "kaishengyao/cnn", "max_stars_repo_head_hexsha": "a034b837e88f82bd8adf2c5b0a5defb26fd52096", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2015-09-10T07:50:50.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-17T03:02:38.000Z", "max_issues_repo_path": "examples/xor.cc", "max_issues_repo_name": "kaishengyao/cnn", "max_issues_repo_head_hexsha": "a034b837e88f82bd8adf2c5b0a5defb26fd52096", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/xor.cc", "max_forks_repo_name": "kaishengyao/cnn", "max_forks_repo_head_hexsha": "a034b837e88f82bd8adf2c5b0a5defb26fd52096", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2015-09-08T12:43:13.000Z", "max_forks_repo_forks_event_max_datetime": "2018-09-26T07:32:47.000Z", "avg_line_length": 26.1466666667, "max_line_length": 85, "alphanum_fraction": 0.619581846, "num_tokens": 623, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.48356338333093896}}
{"text": "#include <iostream>\n#include <fstream>\n\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n\n#include <Eigen/Eigen>\n\n#include <boost/format.hpp>\n\n#include <octomap/octomap.h>\n#include <octomap/ColorOcTree.h>\n\n#define OCTOMAP_WITH_COLOR      1\n\nint main(int argc, char** argv)\n{\n    std::vector<cv::Mat> color_images, depth_images;\n    std::vector<Eigen::Isometry3d, Eigen::aligned_allocator<Eigen::Isometry3d>> poses;\n    \n    std::ifstream fin(\"../../data/pose.txt\");\n    if (!fin) {\n        std::cerr << \"please run the program with the directory -'../../data/' and file 'pose.txt'.\";\n        exit(EXIT_FAILURE);\n    }\n    \n    for (int i=0; i < 5; i ++) {\n        boost::format fmt(\"../../data/%s/%d.%s\");\n        color_images.push_back(cv::imread((fmt%\"color\"%(i+1)%\"png\").str()));\n        depth_images.push_back(cv::imread((fmt%\"depth\"%(i+1)%\"pgm\").str(), -1));\n        \n        double data[7] = {0};\n        for (int i = 0; i < 7; i ++) {\n            fin >> data[i];\n        }\n        Eigen::Quaterniond q(data[6], data[3], data[4], data[5]);\n        Eigen::Isometry3d T(q);\n        T.pretranslate(Eigen::Vector3d(data[0], data[1], data[2]));\n        poses.push_back(T);\n    }\n    \n    double cx = 325.5;\n    double cy = 253.5;\n    double fx = 518.0;\n    double fy = 519.0;\n    double depthScale = 1000.0;\n    \n    std::cout << \"The image is being converted to a OctoMap ...\" << std::endl;\n    \n    // octomap tree\n#if OCTOMAP_WITH_COLOR\n    struct RGB_Color {\n        uchar r;\n        uchar g;\n        uchar b;\n    };\n    \n    octomap::ColorOcTree tree(0.05);\n#else\n    octomap::OcTree tree(0.05);     // Resolution\n#endif\n    \n    for (int i = 0; i < 5; i++) {\n        std::cout << \"Image \"<< i+1 << \" is being converted ... \" << std::endl;\n        \n        cv::Mat color = color_images[i];\n        cv::Mat depth = depth_images[i];\n        Eigen::Isometry3d T = poses[i];\n        \n        octomap::Pointcloud cloud;  // the point cloud in octomap\n#if OCTOMAP_WITH_COLOR\n        std::vector<RGB_Color> rgb_colors;\n#endif\n        \n        for (int v = 0; v < color.rows; v++) {\n            for (int u = 0; u < color.cols; u++) {\n                unsigned int d = depth.ptr<unsigned short>(v)[u];   // depth value\n                if (d == 0) continue;       /* last measure, value is 0 */\n                if (d >= 7000) continue;    /* the depth value too large */\n                \n                Eigen::Vector3d point;\n                point[2] = double(d) / depthScale;\n                point[0] = (u-cx)*point[2]/fx;\n                point[1] = (v-cy)*point[2]/fy;\n                Eigen::Vector3d point_world = T*point;\n                \n                cloud.push_back(point_world[0], point_world[1], point_world[2]);\n#if OCTOMAP_WITH_COLOR\n                RGB_Color rgb_color;\n                rgb_color.b = color.ptr<uchar>(v)[3*u];\n                rgb_color.g = color.ptr<uchar>(v)[3*u + 1];\n                rgb_color.r = color.ptr<uchar>(v)[3*u + 2];\n                rgb_colors.push_back(rgb_color);\n#endif\n            }\n        }\n        \n        tree.insertPointCloud(cloud, octomap::point3d(T(0,3), T(1,3), T(2,3)));\n        \n#if OCTOMAP_WITH_COLOR\n        int j = 0;\n//         for (octomap::point3d_collection::iterator p = cloud.begin(); p < cloud.end(); p ++) {\n        for (auto p = cloud.begin(); p < cloud.end(); p++) {\n            auto rgb = rgb_colors.data()[j];\n            tree.integrateNodeColor((*p).x(), (*p).y(), (*p).z(), rgb.r, rgb.g, rgb.b);\n            j ++;\n        }\n#endif\n    }\n    \n    tree.updateInnerOccupancy();\n    std::cout << \"saving octomap...\" << std::endl;\n\n#if OCTOMAP_WITH_COLOR\n    tree.write(\"octomap.ot\");\n#else\n    tree.writeBinary(\"octomap.bt\");\n#endif\n\n    return 0;\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "e5a03521c17dd1b78975bea5946f8c98633f9d3b", "size": 3770, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dense_RGBD/src/octomap_mapping.cpp", "max_stars_repo_name": "LSXiang/slam_learning_journey", "max_stars_repo_head_hexsha": "1173bbab4e50a29a61d3affb23ceca32bcc0bf97", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-03-22T00:25:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-01T05:23:27.000Z", "max_issues_repo_path": "dense_RGBD/src/octomap_mapping.cpp", "max_issues_repo_name": "LSXiang/slam_learning_journey", "max_issues_repo_head_hexsha": "1173bbab4e50a29a61d3affb23ceca32bcc0bf97", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dense_RGBD/src/octomap_mapping.cpp", "max_forks_repo_name": "LSXiang/slam_learning_journey", "max_forks_repo_head_hexsha": "1173bbab4e50a29a61d3affb23ceca32bcc0bf97", "max_forks_repo_licenses": ["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.9668874172, "max_line_length": 101, "alphanum_fraction": 0.5201591512, "num_tokens": 1054, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4835310672736827}}
{"text": "// Copyright Louis Dionne 2013-2017\r\n// Distributed under the Boost Software License, Version 1.0.\r\n// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\r\n\r\n#include <boost/hana/assert.hpp>\r\n#include <boost/hana/equal.hpp>\r\n#include <boost/hana/ext/std/ratio.hpp>\r\n#include <boost/hana/not_equal.hpp>\r\n\r\n#include <ratio>\r\nnamespace hana = boost::hana;\r\n\r\n\r\nBOOST_HANA_CONSTANT_CHECK(hana::equal(std::ratio<3, 4>{}, std::ratio<15, 20>{}));\r\nBOOST_HANA_CONSTANT_CHECK(hana::not_equal(std::ratio<3, 4>{}, std::ratio<3, 5>{}));\r\n\r\nint main() { }\r\n", "meta": {"hexsha": "f856c21bb5532fcc462dc9541053ecfce7978f62", "size": 571, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/hana/example/ext/std/ratio/comparable.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": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/hana/example/ext/std/ratio/comparable.cpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-04T18:00:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-04T18:00:00.000Z", "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/hana/example/ext/std/ratio/comparable.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 31.7222222222, "max_line_length": 84, "alphanum_fraction": 0.700525394, "num_tokens": 162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4835310672736827}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2008, 2009 StatPro Italia srl\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n#include \"creditdefaultswap.hpp\"\n#include \"utilities.hpp\"\n#include <ql/cashflows/iborcoupon.hpp>\n#include <ql/instruments/creditdefaultswap.hpp>\n#include <ql/instruments/makecds.hpp>\n#include <ql/pricingengines/credit/midpointcdsengine.hpp>\n#include <ql/pricingengines/credit/integralcdsengine.hpp>\n#include <ql/pricingengines/credit/isdacdsengine.hpp>\n#include <ql/termstructures/credit/flathazardrate.hpp>\n#include <ql/termstructures/credit/interpolatedhazardratecurve.hpp>\n#include <ql/termstructures/yield/flatforward.hpp>\n#include <ql/termstructures/yield/discountcurve.hpp>\n#include <ql/termstructures/yield/piecewiseyieldcurve.hpp>\n#include <ql/termstructures/yield/ratehelpers.hpp>\n#include <ql/quotes/simplequote.hpp>\n#include <ql/math/interpolations/backwardflatinterpolation.hpp>\n#include <ql/time/calendars/target.hpp>\n#include <ql/time/calendars/unitedstates.hpp>\n#include <ql/time/calendars/weekendsonly.hpp>\n#include <ql/currencies/america.hpp>\n#include <ql/time/daycounters/actual360.hpp>\n#include <ql/time/daycounters/thirty360.hpp>\n#include <boost/assign/list_of.hpp>\n#include <boost/foreach.hpp>\n#include <map>\n\n#include <iomanip>\n#include <iostream>\n\nusing namespace QuantLib;\nusing namespace boost::unit_test_framework;\nusing boost::assign::map_list_of;\nusing std::map;\n\nvoid CreditDefaultSwapTest::testCachedValue() {\n\n    BOOST_TEST_MESSAGE(\"Testing credit-default swap against cached values...\");\n\n    SavedSettings backup;\n\n    // Initialize curves\n    Settings::instance().evaluationDate() = Date(9,June,2006);\n    Date today = Settings::instance().evaluationDate();\n    Calendar calendar = TARGET();\n\n    Handle<Quote> hazardRate = Handle<Quote>(\n                ext::shared_ptr<Quote>(new SimpleQuote(0.01234)));\n    RelinkableHandle<DefaultProbabilityTermStructure> probabilityCurve;\n    probabilityCurve.linkTo(\n        ext::shared_ptr<DefaultProbabilityTermStructure>(\n                   new FlatHazardRate(0, calendar, hazardRate, Actual360())));\n\n    RelinkableHandle<YieldTermStructure> discountCurve;\n\n    discountCurve.linkTo(ext::shared_ptr<YieldTermStructure>(\n                            new FlatForward(today,0.06,Actual360())));\n\n    // Build the schedule\n    Date issueDate = calendar.advance(today, -1, Years);\n    Date maturity = calendar.advance(issueDate, 10, Years);\n    Frequency frequency = Semiannual;\n    BusinessDayConvention convention = ModifiedFollowing;\n\n    Schedule schedule(issueDate, maturity, Period(frequency), calendar,\n                      convention, convention, DateGeneration::Forward, false);\n\n    // Build the CDS\n    Rate fixedRate = 0.0120;\n    DayCounter dayCount = Actual360();\n    Real notional = 10000.0;\n    Real recoveryRate = 0.4;\n\n    CreditDefaultSwap cds(Protection::Seller, notional, fixedRate,\n                          schedule, convention, dayCount, true, true);\n    cds.setPricingEngine(ext::shared_ptr<PricingEngine>(\n         new MidPointCdsEngine(probabilityCurve,recoveryRate,discountCurve)));\n\n    Real npv = 295.0153398;\n    Rate fairRate = 0.007517539081;\n\n    Real calculatedNpv = cds.NPV();\n    Rate calculatedFairRate = cds.fairSpread();\n    Real tolerance = 1.0e-7;\n\n    if (std::fabs(calculatedNpv - npv) > tolerance)\n        BOOST_ERROR(\n            \"Failed to reproduce NPV with mid-point engine\\n\"\n            << std::setprecision(10)\n            << \"    calculated NPV: \" << calculatedNpv << \"\\n\"\n            << \"    expected NPV:   \" << npv);\n\n    if (std::fabs(calculatedFairRate - fairRate) > tolerance)\n        BOOST_ERROR(\n            \"Failed to reproduce fair rate with mid-point engine\\n\"\n            << std::setprecision(10)\n            << \"    calculated fair rate: \" << calculatedFairRate << \"\\n\"\n            << \"    expected fair rate:   \" << fairRate);\n\n    cds.setPricingEngine(ext::shared_ptr<PricingEngine>(\n                          new IntegralCdsEngine(1*Days,probabilityCurve,\n                                                recoveryRate,discountCurve)));\n\n    calculatedNpv = cds.NPV();\n    calculatedFairRate = cds.fairSpread();\n    tolerance = 1.0e-5;\n\n    if (std::fabs(calculatedNpv - npv) > notional*tolerance*10)\n        BOOST_ERROR(\n            \"Failed to reproduce NPV with integral engine \"\n            \"(step = 1 day)\\n\"\n            << std::setprecision(10)\n            << \"    calculated NPV: \" << calculatedNpv << \"\\n\"\n            << \"    expected NPV:   \" << npv);\n\n    if (std::fabs(calculatedFairRate - fairRate) > tolerance)\n        BOOST_ERROR(\n            \"Failed to reproduce fair rate with integral engine \"\n            \"(step = 1 day)\\n\"\n            << std::setprecision(10)\n            << \"    calculated fair rate: \" << calculatedFairRate << \"\\n\"\n            << \"    expected fair rate:   \" << fairRate);\n\n    cds.setPricingEngine(ext::shared_ptr<PricingEngine>(\n                          new IntegralCdsEngine(1*Weeks,probabilityCurve,\n                                                recoveryRate,discountCurve)));\n\n    calculatedNpv = cds.NPV();\n    calculatedFairRate = cds.fairSpread();\n    tolerance = 1.0e-5;\n\n    if (std::fabs(calculatedNpv - npv) > notional*tolerance*10)\n        BOOST_ERROR(\n            \"Failed to reproduce NPV with integral engine \"\n            \"(step = 1 week)\\n\"\n            << std::setprecision(10)\n            << \"    calculated NPV: \" << calculatedNpv << \"\\n\"\n            << \"    expected NPV:   \" << npv);\n\n    if (std::fabs(calculatedFairRate - fairRate) > tolerance)\n        BOOST_ERROR(\n            \"Failed to reproduce fair rate with integral engine \"\n            \"(step = 1 week)\\n\"\n            << std::setprecision(10)\n            << \"    calculated fair rate: \" << calculatedFairRate << \"\\n\"\n            << \"    expected fair rate:   \" << fairRate);\n}\n\n\nvoid CreditDefaultSwapTest::testCachedMarketValue() {\n\n    BOOST_TEST_MESSAGE(\n        \"Testing credit-default swap against cached market values...\");\n\n    SavedSettings backup;\n\n    Settings::instance().evaluationDate() = Date(9,June,2006);\n    Date evalDate = Settings::instance().evaluationDate();\n    Calendar calendar = UnitedStates();\n\n    std::vector<Date> discountDates;\n    discountDates.push_back(evalDate);\n    discountDates.push_back(calendar.advance(evalDate, 1, Weeks,  ModifiedFollowing));\n    discountDates.push_back(calendar.advance(evalDate, 1, Months, ModifiedFollowing));\n    discountDates.push_back(calendar.advance(evalDate, 2, Months, ModifiedFollowing));\n    discountDates.push_back(calendar.advance(evalDate, 3, Months, ModifiedFollowing));\n    discountDates.push_back(calendar.advance(evalDate, 6, Months, ModifiedFollowing));\n    discountDates.push_back(calendar.advance(evalDate,12, Months, ModifiedFollowing));\n    discountDates.push_back(calendar.advance(evalDate, 2, Years, ModifiedFollowing));\n    discountDates.push_back(calendar.advance(evalDate, 3, Years, ModifiedFollowing));\n    discountDates.push_back(calendar.advance(evalDate, 4, Years, ModifiedFollowing));\n    discountDates.push_back(calendar.advance(evalDate, 5, Years, ModifiedFollowing));\n    discountDates.push_back(calendar.advance(evalDate, 6, Years, ModifiedFollowing));\n    discountDates.push_back(calendar.advance(evalDate, 7, Years, ModifiedFollowing));\n    discountDates.push_back(calendar.advance(evalDate, 8, Years, ModifiedFollowing));\n    discountDates.push_back(calendar.advance(evalDate, 9, Years, ModifiedFollowing));\n    discountDates.push_back(calendar.advance(evalDate,10, Years, ModifiedFollowing));\n    discountDates.push_back(calendar.advance(evalDate,15, Years, ModifiedFollowing));\n\n    std::vector<DiscountFactor> dfs;\n    dfs.push_back(1.0);\n    dfs.push_back(0.9990151375768731);\n    dfs.push_back(0.99570502636871183);\n    dfs.push_back(0.99118260474528685);\n    dfs.push_back(0.98661167950906203);\n    dfs.push_back(0.9732592953359388 );\n    dfs.push_back(0.94724424481038083);\n    dfs.push_back(0.89844996737120875  );\n    dfs.push_back(0.85216647839921411  );\n    dfs.push_back(0.80775477692556874  );\n    dfs.push_back(0.76517289234200347  );\n    dfs.push_back(0.72401019553182933  );\n    dfs.push_back(0.68503909569219212  );\n    dfs.push_back(0.64797499814013748  );\n    dfs.push_back(0.61263171936255534  );\n    dfs.push_back(0.5791942350748791   );\n    dfs.push_back(0.43518868769953606  );\n\n    const DayCounter& curveDayCounter=Actual360();\n\n    RelinkableHandle<YieldTermStructure> discountCurve;\n    discountCurve.linkTo(\n        ext::shared_ptr<YieldTermStructure>(\n            new DiscountCurve(discountDates, dfs, curveDayCounter)));\n\n    DayCounter dayCounter = Thirty360();\n    std::vector<Date> dates;\n    dates.push_back(evalDate);\n    dates.push_back(calendar.advance(evalDate, 6, Months, ModifiedFollowing));\n    dates.push_back(calendar.advance(evalDate, 1, Years, ModifiedFollowing));\n    dates.push_back(calendar.advance(evalDate, 2, Years, ModifiedFollowing));\n    dates.push_back(calendar.advance(evalDate, 3, Years, ModifiedFollowing));\n    dates.push_back(calendar.advance(evalDate, 4, Years, ModifiedFollowing));\n    dates.push_back(calendar.advance(evalDate, 5, Years, ModifiedFollowing));\n    dates.push_back(calendar.advance(evalDate, 7, Years, ModifiedFollowing));\n    dates.push_back(calendar.advance(evalDate,10, Years, ModifiedFollowing));\n\n    std::vector<Probability> defaultProbabilities;\n    defaultProbabilities.push_back(0.0000);\n    defaultProbabilities.push_back(0.0047);\n    defaultProbabilities.push_back(0.0093);\n    defaultProbabilities.push_back(0.0286);\n    defaultProbabilities.push_back(0.0619);\n    defaultProbabilities.push_back(0.0953);\n    defaultProbabilities.push_back(0.1508);\n    defaultProbabilities.push_back(0.2288);\n    defaultProbabilities.push_back(0.3666);\n\n    std::vector<Real> hazardRates;\n    hazardRates.push_back(0.0);\n    for (Size i=1; i<dates.size(); ++i) {\n        Time t1 = dayCounter.yearFraction(dates[0], dates[i-1]);\n        Time t2 = dayCounter.yearFraction(dates[0], dates[i]);\n        Probability S1 = 1.0 - defaultProbabilities[i-1];\n        Probability S2 = 1.0 - defaultProbabilities[i];\n        hazardRates.push_back(std::log(S1/S2)/(t2-t1));\n    }\n\n    RelinkableHandle<DefaultProbabilityTermStructure> piecewiseFlatHazardRate;\n    piecewiseFlatHazardRate.linkTo(\n        ext::shared_ptr<DefaultProbabilityTermStructure>(\n               new InterpolatedHazardRateCurve<BackwardFlat>(dates,\n                                                             hazardRates,\n                                                             Thirty360())));\n\n    // Testing credit default swap\n\n    // Build the schedule\n    Date issueDate(20, March, 2006);\n    Date maturity(20, June, 2013);\n    Frequency cdsFrequency = Semiannual;\n    BusinessDayConvention cdsConvention = ModifiedFollowing;\n\n    Schedule schedule(issueDate, maturity, Period(cdsFrequency), calendar,\n                      cdsConvention, cdsConvention,\n                      DateGeneration::Forward, false);\n\n    // Build the CDS\n    Real recoveryRate = 0.25;\n    Rate fixedRate=0.0224;\n    DayCounter dayCount=Actual360();\n    Real cdsNotional=100.0;\n\n    CreditDefaultSwap cds(Protection::Seller, cdsNotional, fixedRate,\n                          schedule, cdsConvention, dayCount, true, true);\n    cds.setPricingEngine(ext::shared_ptr<PricingEngine>(\n                          new MidPointCdsEngine(piecewiseFlatHazardRate,\n                                                recoveryRate,discountCurve)));\n\n    Real calculatedNpv = cds.NPV();\n    Real calculatedFairRate = cds.fairSpread();\n\n    double npv = -1.364048777;        // from Bloomberg we have 98.15598868 - 100.00;\n    double fairRate =  0.0248429452; // from Bloomberg we have 0.0258378;\n\n    Real tolerance = 1e-9;\n\n    if (std::fabs(npv - calculatedNpv) > tolerance)\n        BOOST_ERROR(\n            \"Failed to reproduce the npv for the given credit-default swap\\n\"\n            << std::setprecision(10)\n            << \"    computed NPV:  \" << calculatedNpv << \"\\n\"\n            << \"    Given NPV:     \" << npv);\n\n    if (std::fabs(fairRate - calculatedFairRate) > tolerance)\n        BOOST_ERROR(\n            \"Failed to reproduce the fair rate for the given credit-default swap\\n\"\n            << std::setprecision(10)\n            << \"    computed fair rate:  \" << calculatedFairRate << \"\\n\"\n            << \"    Given fair rate:     \" << fairRate);\n}\n\n\nvoid CreditDefaultSwapTest::testImpliedHazardRate() {\n\n    BOOST_TEST_MESSAGE(\"Testing implied hazard-rate for credit-default swaps...\");\n\n    SavedSettings backup;\n\n    // Initialize curves\n    Calendar calendar = TARGET();\n    Date today = calendar.adjust(Date::todaysDate());\n    Settings::instance().evaluationDate() = today;\n\n    Rate h1 = 0.30, h2 = 0.40;\n    DayCounter dayCounter = Actual365Fixed();\n\n    std::vector<Date> dates(3);\n    std::vector<Real> hazardRates(3);\n    dates[0] = today;\n    hazardRates[0] = h1;\n\n    dates[1] = today + 5*Years;\n    hazardRates[1] = h1;\n\n    dates[2] = today + 10*Years;\n    hazardRates[2] = h2;\n\n    RelinkableHandle<DefaultProbabilityTermStructure> probabilityCurve;\n    probabilityCurve.linkTo(ext::shared_ptr<DefaultProbabilityTermStructure>(\n                    new InterpolatedHazardRateCurve<BackwardFlat>(dates,\n                                                                  hazardRates,\n                                                                  dayCounter)));\n\n    RelinkableHandle<YieldTermStructure> discountCurve;\n    discountCurve.linkTo(ext::shared_ptr<YieldTermStructure>(\n                            new FlatForward(today,0.03,Actual360())));\n\n\n    Frequency frequency = Semiannual;\n    BusinessDayConvention convention = ModifiedFollowing;\n\n    Date issueDate = calendar.advance(today, -6, Months);\n    Rate fixedRate = 0.0120;\n    DayCounter cdsDayCount = Actual360();\n    Real notional = 10000.0;\n    Real recoveryRate = 0.4;\n\n    Rate latestRate = Null<Rate>();\n    for (Integer n=6; n<=10; ++n) {\n\n        Date maturity = calendar.advance(issueDate, n, Years);\n        Schedule schedule(issueDate, maturity, Period(frequency), calendar,\n                          convention, convention,\n                          DateGeneration::Forward, false);\n\n        CreditDefaultSwap cds(Protection::Seller, notional, fixedRate,\n                              schedule, convention, cdsDayCount,\n                              true, true);\n        cds.setPricingEngine(ext::shared_ptr<PricingEngine>(\n                         new MidPointCdsEngine(probabilityCurve,\n                                               recoveryRate, discountCurve)));\n\n        Real NPV = cds.NPV();\n        Rate flatRate = cds.impliedHazardRate(NPV, discountCurve,\n                                              dayCounter,\n                                              recoveryRate);\n\n        if (flatRate < h1 || flatRate > h2) {\n            BOOST_ERROR(\"implied hazard rate outside expected range\\n\"\n                        << \"    maturity: \" << n << \" years\\n\"\n                        << \"    expected minimum: \" << h1 << \"\\n\"\n                        << \"    expected maximum: \" << h2 << \"\\n\"\n                        << \"    implied rate:     \" << flatRate);\n        }\n\n        if (n > 6 && flatRate < latestRate) {\n            BOOST_ERROR(\"implied hazard rate decreasing with swap maturity\\n\"\n                        << \"    maturity: \" << n << \" years\\n\"\n                        << \"    previous rate: \" << latestRate << \"\\n\"\n                        << \"    implied rate:  \" << flatRate);\n        }\n\n        latestRate = flatRate;\n\n        RelinkableHandle<DefaultProbabilityTermStructure> probability;\n        probability.linkTo(ext::shared_ptr<DefaultProbabilityTermStructure>(\n         new FlatHazardRate(\n           today,\n           Handle<Quote>(ext::shared_ptr<Quote>(new SimpleQuote(flatRate))),\n           dayCounter)));\n\n        CreditDefaultSwap cds2(Protection::Seller, notional, fixedRate,\n                               schedule, convention, cdsDayCount,\n                               true, true);\n        cds2.setPricingEngine(ext::shared_ptr<PricingEngine>(\n                               new MidPointCdsEngine(probability,recoveryRate,\n                                                     discountCurve)));\n\n        Real NPV2 = cds2.NPV();\n        Real tolerance = 1.0;\n        if (std::fabs(NPV-NPV2) > tolerance) {\n            BOOST_ERROR(\"failed to reproduce NPV with implied rate\\n\"\n                        << \"    expected:   \" << NPV << \"\\n\"\n                        << \"    calculated: \" << NPV2);\n        }\n    }\n}\n\n\nvoid CreditDefaultSwapTest::testFairSpread() {\n\n    BOOST_TEST_MESSAGE(\n        \"Testing fair-spread calculation for credit-default swaps...\");\n\n    SavedSettings backup;\n\n    // Initialize curves\n    Calendar calendar = TARGET();\n    Date today = calendar.adjust(Date::todaysDate());\n    Settings::instance().evaluationDate() = today;\n\n    Handle<Quote> hazardRate = Handle<Quote>(\n                ext::shared_ptr<Quote>(new SimpleQuote(0.01234)));\n    RelinkableHandle<DefaultProbabilityTermStructure> probabilityCurve;\n    probabilityCurve.linkTo(\n        ext::shared_ptr<DefaultProbabilityTermStructure>(\n                   new FlatHazardRate(0, calendar, hazardRate, Actual360())));\n\n    RelinkableHandle<YieldTermStructure> discountCurve;\n    discountCurve.linkTo(ext::shared_ptr<YieldTermStructure>(\n                            new FlatForward(today,0.06,Actual360())));\n\n    // Build the schedule\n    Date issueDate = calendar.advance(today, -1, Years);\n    Date maturity = calendar.advance(issueDate, 10, Years);\n    BusinessDayConvention convention = Following;\n\n    Schedule schedule =\n        MakeSchedule().from(issueDate)\n                      .to(maturity)\n                      .withFrequency(Quarterly)\n                      .withCalendar(calendar)\n                      .withTerminationDateConvention(convention)\n                      .withRule(DateGeneration::TwentiethIMM);\n\n    // Build the CDS\n    Rate fixedRate = 0.001;\n    DayCounter dayCount = Actual360();\n    Real notional = 10000.0;\n    Real recoveryRate = 0.4;\n\n    ext::shared_ptr<PricingEngine> engine(\n          new MidPointCdsEngine(probabilityCurve,recoveryRate,discountCurve));\n\n    CreditDefaultSwap cds(Protection::Seller, notional, fixedRate,\n                          schedule, convention, dayCount, true, true);\n    cds.setPricingEngine(engine);\n\n    Rate fairRate = cds.fairSpread();\n\n    CreditDefaultSwap fairCds(Protection::Seller, notional, fairRate,\n                              schedule, convention, dayCount, true, true);\n    fairCds.setPricingEngine(engine);\n\n    Real fairNPV = fairCds.NPV();\n    Real tolerance = 1e-9;\n\n    if (std::fabs(fairNPV) > tolerance)\n        BOOST_ERROR(\n            \"Failed to reproduce null NPV with calculated fair spread\\n\"\n            << \"    calculated spread: \" << io::rate(fairRate) << \"\\n\"\n            << \"    calculated NPV:    \" << fairNPV);\n}\n\nvoid CreditDefaultSwapTest::testFairUpfront() {\n\n    BOOST_TEST_MESSAGE(\n        \"Testing fair-upfront calculation for credit-default swaps...\");\n\n    SavedSettings backup;\n\n    // Initialize curves\n    Calendar calendar = TARGET();\n    Date today = calendar.adjust(Date::todaysDate());\n    Settings::instance().evaluationDate() = today;\n\n    Handle<Quote> hazardRate = Handle<Quote>(\n                ext::shared_ptr<Quote>(new SimpleQuote(0.01234)));\n    RelinkableHandle<DefaultProbabilityTermStructure> probabilityCurve;\n    probabilityCurve.linkTo(\n        ext::shared_ptr<DefaultProbabilityTermStructure>(\n                   new FlatHazardRate(0, calendar, hazardRate, Actual360())));\n\n    RelinkableHandle<YieldTermStructure> discountCurve;\n    discountCurve.linkTo(ext::shared_ptr<YieldTermStructure>(\n                            new FlatForward(today,0.06,Actual360())));\n\n    // Build the schedule\n    Date issueDate = today;\n    Date maturity = calendar.advance(issueDate, 10, Years);\n    BusinessDayConvention convention = Following;\n\n    Schedule schedule =\n        MakeSchedule().from(issueDate)\n                      .to(maturity)\n                      .withFrequency(Quarterly)\n                      .withCalendar(calendar)\n                      .withTerminationDateConvention(convention)\n                      .withRule(DateGeneration::TwentiethIMM);\n\n    // Build the CDS\n    Rate fixedRate = 0.05;\n    Rate upfront = 0.001;\n    DayCounter dayCount = Actual360();\n    Real notional = 10000.0;\n    Real recoveryRate = 0.4;\n\n    ext::shared_ptr<PricingEngine> engine(\n          new MidPointCdsEngine(probabilityCurve, recoveryRate,\n                                discountCurve, true));\n\n    CreditDefaultSwap cds(Protection::Seller, notional, upfront, fixedRate,\n                          schedule, convention, dayCount, true, true);\n    cds.setPricingEngine(engine);\n\n    Rate fairUpfront = cds.fairUpfront();\n\n    CreditDefaultSwap fairCds(Protection::Seller, notional,\n                              fairUpfront, fixedRate,\n                              schedule, convention, dayCount, true, true);\n    fairCds.setPricingEngine(engine);\n\n    Real fairNPV = fairCds.NPV();\n    Real tolerance = 1e-9;\n\n    if (std::fabs(fairNPV) > tolerance)\n        BOOST_ERROR(\n            \"Failed to reproduce null NPV with calculated fair upfront\\n\"\n            << \"    calculated upfront: \" << io::rate(fairUpfront) << \"\\n\"\n            << \"    calculated NPV:     \" << fairNPV);\n\n    // same with null upfront to begin with\n    upfront = 0.0;\n    CreditDefaultSwap cds2(Protection::Seller, notional, upfront, fixedRate,\n                           schedule, convention, dayCount, true, true);\n    cds2.setPricingEngine(engine);\n\n    fairUpfront = cds2.fairUpfront();\n\n    CreditDefaultSwap fairCds2(Protection::Seller, notional,\n                               fairUpfront, fixedRate,\n                               schedule, convention, dayCount, true, true);\n    fairCds2.setPricingEngine(engine);\n\n    fairNPV = fairCds2.NPV();\n\n    if (std::fabs(fairNPV) > tolerance)\n        BOOST_ERROR(\n            \"Failed to reproduce null NPV with calculated fair upfront\\n\"\n            << \"    calculated upfront: \" << io::rate(fairUpfront) << \"\\n\"\n            << \"    calculated NPV:     \" << fairNPV);\n}\n\nvoid CreditDefaultSwapTest::testIsdaEngine() {\n\n    BOOST_TEST_MESSAGE(\n        \"Testing ISDA engine calculations for credit-default swaps...\");\n\n    SavedSettings backup;\n\n    Date tradeDate(21, May, 2009);\n    Settings::instance().evaluationDate() = tradeDate;\n\n\n    //build an ISDA compliant yield curve\n    //data comes from Markit published rates\n    std::vector<ext::shared_ptr<RateHelper> > isdaRateHelpers;\n    int dep_tenors[] = {1, 2, 3, 6, 9, 12};\n    double dep_quotes[] = {0.003081,\n                           0.005525,\n                           0.007163,\n                           0.012413,\n                           0.014,\n                           0.015488};\n\n    for(size_t i = 0; i < sizeof(dep_tenors) / sizeof(int); i++) {\n        isdaRateHelpers.push_back(ext::make_shared<DepositRateHelper>(\n                                     dep_quotes[i], dep_tenors[i] * Months, 2,\n                                     WeekendsOnly(), ModifiedFollowing,\n                                     false, Actual360()\n                                     )\n            );\n    }\n    int swap_tenors[] = {2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 15, 20, 25, 30};\n    double swap_quotes[] = {0.011907,\n                            0.01699,\n                            0.021198,\n                            0.02444,\n                            0.026937,\n                            0.028967,\n                            0.030504,\n                            0.031719,\n                            0.03279,\n                            0.034535,\n                            0.036217,\n                            0.036981,\n                            0.037246,\n                            0.037605};\n\n    ext::shared_ptr<IborIndex> isda_ibor = ext::make_shared<IborIndex>(\n        \"IsdaIbor\", 3 * Months, 2, USDCurrency(), WeekendsOnly(),\n        ModifiedFollowing, false, Actual360());\n    for(size_t i = 0; i < sizeof(swap_tenors) / sizeof(int); i++) {\n        isdaRateHelpers.push_back(ext::make_shared<SwapRateHelper>(\n                                      swap_quotes[i], swap_tenors[i] * Years,\n                                      WeekendsOnly(),\n                                      Semiannual,\n                                      ModifiedFollowing, Thirty360(), isda_ibor\n                                      )\n            );\n    }\n\n    RelinkableHandle<YieldTermStructure> discountCurve;\n    discountCurve.linkTo(\n            ext::make_shared<PiecewiseYieldCurve<Discount, LogLinear> >(\n                0, WeekendsOnly(), isdaRateHelpers, Actual365Fixed())\n        );\n\n\n    RelinkableHandle<DefaultProbabilityTermStructure> probabilityCurve;\n    Date termDates[] = {Date(20, June, 2010),\n                        Date(20, June, 2011),\n                        Date(20, June, 2012),\n                        Date(20, June, 2016),\n                        Date(20, June, 2019)};\n    Rate spreads[] = {0.001, 0.1};\n    Rate recoveries[] = {0.2, 0.4};\n\n    double markitValues[] = {97798.29358, //0.001\n                             97776.11889, //0.001\n                             -914971.5977, //0.1\n                             -894985.6298, //0.1\n                             186921.3594, //0.001\n                             186839.8148, //0.001\n                             -1646623.672, //0.1\n                             -1579803.626, //0.1\n                             274298.9203,\n                             274122.4725,\n                             -2279730.93,\n                             -2147972.527,\n                             592420.2297,\n                             591571.2294,\n                             -3993550.206,\n                             -3545843.418,\n                             797501.1422,\n                             795915.9787,\n                             -4702034.688,\n                             -4042340.999};\n    Real tolerance;\n    if (IborCoupon::usingAtParCoupons()) {\n        tolerance = 1.0e-6;\n    } else {\n        /* The risk-free curve is a bit off. We might skip the tests\n           altogether and rely on running them with indexed coupons\n           disabled, but leaving them can be useful anyway. */\n        tolerance = 1.0e-3;\n    }\n\n    size_t l = 0;\n\n    for(size_t i = 0; i < sizeof(termDates) / sizeof(Date); i++) {\n        for(size_t j = 0; j < 2; j++) {\n            for(size_t k = 0; k < 2; k++) {\n\n            ext::shared_ptr<CreditDefaultSwap> quotedTrade =\n                MakeCreditDefaultSwap(termDates[i], spreads[j])\n                .withNominal(10000000.);\n\n            Rate h = quotedTrade->impliedHazardRate(0.,\n                                                    discountCurve,\n                                                    Actual365Fixed(),\n                                                    recoveries[k],\n                                                    1e-10,\n                                                    CreditDefaultSwap::ISDA);\n\n            probabilityCurve.linkTo(\n                ext::make_shared<FlatHazardRate>(\n                    0, WeekendsOnly(), h, Actual365Fixed())\n                );\n\n            ext::shared_ptr<IsdaCdsEngine> engine = ext::make_shared<IsdaCdsEngine>(\n                probabilityCurve, recoveries[k], discountCurve,\n                boost::none, IsdaCdsEngine::Taylor, IsdaCdsEngine::HalfDayBias,\n                IsdaCdsEngine::Piecewise);\n\n            ext::shared_ptr<CreditDefaultSwap> conventionalTrade =\n                MakeCreditDefaultSwap(termDates[i], 0.01)\n                .withNominal(10000000.)\n                .withPricingEngine(engine);\n\n            BOOST_CHECK_CLOSE(conventionalTrade->notional() * conventionalTrade->fairUpfront(),\n                              markitValues[l],\n                              tolerance);\n\n            l++;\n\n            }\n        }\n    }\n\n}\n\nvoid CreditDefaultSwapTest::testAccrualRebateAmounts() {\n\n    BOOST_TEST_MESSAGE(\"Testing accrual rebate amounts on credit default swaps...\");\n\n    SavedSettings backup;\n\n    // The accrual values are taken from various test results on the ISDA CDS model website\n    // https://www.cdsmodel.com/cdsmodel/documentation.html.\n\n    // Inputs\n    Real notional = 10000000;\n    Real spread = 0.0100;\n    Date maturity(20, Jun, 2014);\n\n    // key is trade date and value is expected accrual\n    typedef map<Date, Real> InputData;\n    InputData inputs = map_list_of\n        (Date(18, Mar, 2009), 24166.67)\n        (Date(19, Mar, 2009), 0.00)\n        (Date(20, Mar, 2009), 277.78)\n        (Date(23, Mar, 2009), 1111.11)\n        (Date(19, Jun, 2009), 25555.56)\n        (Date(20, Jun, 2009), 25833.33)\n        (Date(21, Jun, 2009), 0.00)\n        (Date(22, Jun, 2009), 277.78)\n        (Date(18, Jun, 2014), 25277.78)\n        (Date(19, Jun, 2014), 25555.56);\n\n    BOOST_FOREACH(const InputData::value_type& input, inputs) {\n        Settings::instance().evaluationDate() = input.first;\n        CreditDefaultSwap cds = MakeCreditDefaultSwap(maturity, spread)\n            .withNominal(notional);\n        BOOST_CHECK_SMALL(input.second - cds.accrualRebate()->amount(), 0.01);\n    }\n}\n\ntest_suite* CreditDefaultSwapTest::suite() {\n    test_suite* suite = BOOST_TEST_SUITE(\"Credit-default swap tests\");\n    suite->add(QUANTLIB_TEST_CASE(&CreditDefaultSwapTest::testCachedValue));\n    suite->add(QUANTLIB_TEST_CASE(\n                              &CreditDefaultSwapTest::testCachedMarketValue));\n    suite->add(QUANTLIB_TEST_CASE(\n                              &CreditDefaultSwapTest::testImpliedHazardRate));\n    suite->add(QUANTLIB_TEST_CASE(&CreditDefaultSwapTest::testFairSpread));\n    suite->add(QUANTLIB_TEST_CASE(&CreditDefaultSwapTest::testFairUpfront));\n    suite->add(QUANTLIB_TEST_CASE(&CreditDefaultSwapTest::testIsdaEngine));\n    suite->add(QUANTLIB_TEST_CASE(&CreditDefaultSwapTest::testAccrualRebateAmounts));\n    return suite;\n}\n", "meta": {"hexsha": "70979d92cc640aa160cc58b9a9215cac82d61980", "size": 30853, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test-suite/creditdefaultswap.cpp", "max_stars_repo_name": "vermosen/quantlib", "max_stars_repo_head_hexsha": "403be360df9ea4f694674ff3a38e9051f681c426", "max_stars_repo_licenses": ["BSD-3-Clause"], "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-suite/creditdefaultswap.cpp", "max_issues_repo_name": "vermosen/quantlib", "max_issues_repo_head_hexsha": "403be360df9ea4f694674ff3a38e9051f681c426", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-02-08T08:11:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T12:41:52.000Z", "max_forks_repo_path": "test-suite/creditdefaultswap.cpp", "max_forks_repo_name": "vermosen/quantlib", "max_forks_repo_head_hexsha": "403be360df9ea4f694674ff3a38e9051f681c426", "max_forks_repo_licenses": ["BSD-3-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.0168612192, "max_line_length": 95, "alphanum_fraction": 0.5994230707, "num_tokens": 7209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812554, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4835310616718671}}
{"text": "#include <Eigen/Dense>\r\n#include <Eigen/Core>\r\n\r\n#include \"BingoCpp/implicit_regression.h\"\r\n\r\nnamespace bingo {\r\n\r\nImplicitTrainingData *ImplicitTrainingData::GetItem(int item) {\r\n  return new ImplicitTrainingData(x.row(item), dx_dt.row(item));\r\n}\r\n\r\nImplicitTrainingData *ImplicitTrainingData::GetItem(\r\n    const std::vector<int> &items) {\r\n  Eigen::ArrayXXd temp_in(items.size(), x.cols());\r\n  Eigen::ArrayXXd temp_out(items.size(), dx_dt.cols());\r\n\r\n  for (std::size_t row = 0; row < items.size(); row ++) {\r\n    temp_in.row(row) = x.row(items[row]);\r\n    temp_out.row(row) = dx_dt.row(items[row]);\r\n  }\r\n  return new ImplicitTrainingData(temp_in, temp_out);\r\n}\r\n\r\nvoid normalize_by_row(Eigen::ArrayXXd *data_array);\r\nEigen::ArrayXXd dfdx_dot_dfdt(bool normalize_dot,\r\n                              const Eigen::ArrayXXd &dx_dt,\r\n                              const Eigen::ArrayXXd &grad);\r\nbool not_enough_parameters_used(int required_params, \r\n                                const Eigen::ArrayXXd &dot_product);\r\n\r\nEigen::ArrayXXd ImplicitRegression::EvaluateFitnessVector(\r\n    const Equation &individual) const {\r\n  EvalAndDerivative eval_and_grad \r\n      = individual.EvaluateEquationWithXGradientAt(\r\n      ((ImplicitTrainingData*)training_data_)->x);\r\n  Eigen::ArrayXXd dot_product = dfdx_dot_dfdt(\r\n      normalize_dot_,\r\n      ((ImplicitTrainingData*)training_data_)->dx_dt,\r\n      eval_and_grad.second);\r\n\r\n  if (required_params_ != kNoneRequired\r\n      && not_enough_parameters_used(required_params_, dot_product)) {\r\n    return Eigen::ArrayXd::Constant(\r\n        ((ImplicitTrainingData*)training_data_)->x.rows(),\r\n         std::numeric_limits<double>::infinity());\r\n  }\r\n  // NOTE tylertownsend: may need to verify eigen NaN conditions\r\n  Eigen::ArrayXXd denominator = dot_product.abs().rowwise().sum();\r\n  Eigen::ArrayXXd normalized_fitness = \r\n      dot_product.rowwise().sum() / denominator;\r\n  return normalized_fitness.unaryExpr([](double v) { \r\n    return std::isfinite(v) ? v : std::numeric_limits<double>::infinity();\r\n  });\r\n}\r\n\r\nvoid normalize_by_row(Eigen::ArrayXXd *data_array) {\r\n  Eigen::ArrayXXd norm_array = data_array->rowwise().norm();\r\n  for (int i = 0; i < norm_array.rows(); i ++) {\r\n    data_array->row(i) /= norm_array.row(i)[0];\r\n  }\r\n}\r\n\r\nEigen::ArrayXXd dfdx_dot_dfdt(bool normalize_dot,\r\n                              const Eigen::ArrayXXd &dx_dt,\r\n                              const Eigen::ArrayXXd &grad) {\r\n  Eigen::ArrayXXd left_dot = grad;\r\n  Eigen::ArrayXXd right_dot = dx_dt;\r\n  if (normalize_dot) {\r\n    normalize_by_row(&left_dot);\r\n    normalize_by_row(&right_dot);\r\n  }\r\n\r\n  return left_dot * right_dot;\r\n}\r\n\r\nbool not_enough_parameters_used(int required_params, \r\n                                const Eigen::ArrayXXd &dot_product) {\r\n  auto num_params_used = (dot_product.abs() > 1e-16).rowwise().count();\r\n  return !(num_params_used >= required_params).any();\r\n}\r\n} // namespace bingo", "meta": {"hexsha": "504e70a65003556dc09e8c408f088a4120e20fb8", "size": 2944, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/implicit_regression.cpp", "max_stars_repo_name": "imikejackson/bingocpp", "max_stars_repo_head_hexsha": "6ba00a490c8cb46edebfd78f56b1604a76d668e9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2019-03-14T09:54:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-26T14:01:30.000Z", "max_issues_repo_path": "src/implicit_regression.cpp", "max_issues_repo_name": "imikejackson/bingocpp", "max_issues_repo_head_hexsha": "6ba00a490c8cb46edebfd78f56b1604a76d668e9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 35.0, "max_issues_repo_issues_event_min_datetime": "2019-08-29T19:12:05.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-15T22:17:53.000Z", "max_forks_repo_path": "src/implicit_regression.cpp", "max_forks_repo_name": "imikejackson/bingocpp", "max_forks_repo_head_hexsha": "6ba00a490c8cb46edebfd78f56b1604a76d668e9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2018-10-18T02:43:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-02T22:08:39.000Z", "avg_line_length": 36.3456790123, "max_line_length": 75, "alphanum_fraction": 0.6579483696, "num_tokens": 703, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.483531061671867}}
{"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 \"biharmonic_coordinates.h\"\n#include \"cotmatrix.h\"\n#include \"massmatrix.h\"\n#include \"min_quad_with_fixed.h\"\n#include \"normal_derivative.h\"\n#include \"on_boundary.h\"\n#include <Eigen/Sparse>\n\ntemplate <\n  typename DerivedV,\n  typename DerivedT,\n  typename SType,\n  typename DerivedW>\nIGL_INLINE bool igl::biharmonic_coordinates(\n  const Eigen::PlainObjectBase<DerivedV> & V,\n  const Eigen::PlainObjectBase<DerivedT> & T,\n  const std::vector<std::vector<SType> > & S,\n  Eigen::PlainObjectBase<DerivedW> & W)\n{\n  return biharmonic_coordinates(V,T,S,2,W);\n}\n\ntemplate <\n  typename DerivedV,\n  typename DerivedT,\n  typename SType,\n  typename DerivedW>\nIGL_INLINE bool igl::biharmonic_coordinates(\n  const Eigen::PlainObjectBase<DerivedV> & V,\n  const Eigen::PlainObjectBase<DerivedT> & T,\n  const std::vector<std::vector<SType> > & S,\n  const int k,\n  Eigen::PlainObjectBase<DerivedW> & W)\n{\n  using namespace Eigen;\n  using namespace std;\n  // This is not the most efficient way to build A, but follows \"Linear\n  // Subspace Design for Real-Time Shape Deformation\" [Wang et al. 2015].\n  SparseMatrix<double> A;\n  {\n    SparseMatrix<double> N,Z,L,K,M;\n    normal_derivative(V,T,N);\n    Array<bool,Dynamic,1> I;\n    Array<bool,Dynamic,Dynamic> C;\n    on_boundary(T,I,C);\n    {\n      std::vector<Triplet<double> >ZIJV;\n      for(int t =0;t<T.rows();t++)\n      {\n        for(int f =0;f<T.cols();f++)\n        {\n          if(C(t,f))\n          {\n            const int i = t+f*T.rows();\n            for(int c = 1;c<T.cols();c++)\n            {\n              ZIJV.emplace_back(T(t,(f+c)%T.cols()),i,1);\n            }\n          }\n        }\n      }\n      Z.resize(V.rows(),N.rows());\n      Z.setFromTriplets(ZIJV.begin(),ZIJV.end());\n      N = (Z*N).eval();\n    }\n    cotmatrix(V,T,L);\n    K = N+L;\n    massmatrix(V,T,MASSMATRIX_TYPE_DEFAULT,M);\n    // normalize\n    M /= ((VectorXd)M.diagonal()).array().abs().maxCoeff();\n    DiagonalMatrix<double,Dynamic> Minv =\n      ((VectorXd)M.diagonal().array().inverse()).asDiagonal();\n    switch(k)\n    {\n      default:\n        assert(false && \"unsupported\");\n      case 2:\n        // For C1 smoothness in 2D, one should use bi-harmonic\n        A = K.transpose() * (Minv * K);\n        break;\n      case 3:\n        // For C1 smoothness in 3D, one should use tri-harmonic\n        A = K.transpose() * (Minv * (-L * (Minv * K)));\n        break;\n    }\n  }\n  // Vertices in point handles\n  const size_t mp =\n    count_if(S.begin(),S.end(),[](const vector<int> & h){return h.size()==1;});\n  // number of region handles\n  const size_t r = S.size()-mp;\n  // Vertices in region handles\n  size_t mr = 0;\n  for(const auto & h : S)\n  {\n    if(h.size() > 1)\n    {\n      mr += h.size();\n    }\n  }\n  const size_t dim = T.cols()-1;\n  // Might as well be dense... I think...\n  MatrixXd J = MatrixXd::Zero(mp+mr,mp+r*(dim+1));\n  VectorXi b(mp+mr);\n  MatrixXd H(mp+r*(dim+1),dim);\n  {\n    int v = 0;\n    int c = 0;\n    for(int h = 0;h<S.size();h++)\n    {\n      if(S[h].size()==1)\n      {\n        H.row(c) = V.block(S[h][0],0,1,dim);\n        J(v,c++) = 1;\n        b(v) = S[h][0];\n        v++;\n      }else\n      {\n        assert(S[h].size() >= dim+1);\n        for(int p = 0;p<S[h].size();p++)\n        {\n          for(int d = 0;d<dim;d++)\n          {\n            J(v,c+d) = V(S[h][p],d);\n          }\n          J(v,c+dim) = 1;\n          b(v) = S[h][p];\n          v++;\n        }\n        H.block(c,0,dim+1,dim).setIdentity();\n        c+=dim+1;\n      }\n    }\n  }\n  // minimize    \u00bd W' A W'\n  // subject to  W(b,:) = J\n  return min_quad_with_fixed(\n    A,VectorXd::Zero(A.rows()).eval(),b,J,SparseMatrix<double>(),VectorXd(),true,W);\n}\n\n#ifdef IGL_STATIC_LIBRARY\n// Explicit template specialization\ntemplate bool igl::biharmonic_coordinates<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, int, Eigen::Matrix<double, -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&, std::vector<std::vector<int, std::allocator<int> >, std::allocator<std::vector<int, std::allocator<int> > > > const&, int, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&);\n#endif\n", "meta": {"hexsha": "44da2d215ddd0d2a70f8a3c92b003456f5647a71", "size": 4561, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Code/include/igl/biharmonic_coordinates.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/biharmonic_coordinates.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/biharmonic_coordinates.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": 30.0065789474, "max_line_length": 507, "alphanum_fraction": 0.5742161807, "num_tokens": 1399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321843145405, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4835310588709591}}
{"text": "#include <iostream>\n\n#include <../gsoc/boost/boost/convex_hull.hpp>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n#include <boost/geometry/geometries/adapted/boost_tuple.hpp>\n\nBOOST_GEOMETRY_REGISTER_BOOST_TUPLE_CS(cs::cartesian)\n\nnamespace bg = boost::geometry;\nint main()\n{\n\ttypedef boost::tuple<double, double> point;\n    typedef bg::model::multi_point<point> mpoints;\n\n    mpoints mps;\n    bg::read_wkt(\"MULTIPOINT((2.0 1.3)\"\n    \t\", (2.4 1.7), (2.8 1.8), (3.4 1.2), (3.7 1.6),(3.4 2.0), (4.1 3.0)\"\n        \", (5.3 2.6), (5.4 1.2), (4.9 0.8), (2.9 0.7),(2.0 1.3))\", mps);\n\n    mpoints hull;\n\n    convex_hull(mps, hull);\n\n    std::cout << bg::num_points(hull) << std::endl;\n\n    typedef typename boost::range_const_iterator<mpoints>::type iterator;\n    for ( iterator it = boost::begin(hull) ; it != boost::end(hull) ; ++it ) {\n        std::cout << bg::get<0>(*it) << \" \" << bg::get<1>(*it) << std::endl;\n    }\n    return 0;\n}\n", "meta": {"hexsha": "3f840cd6e1938178a12034aab2a49ea5b1c452ca", "size": 964, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "rika77/boost", "max_stars_repo_head_hexsha": "4dd09da3173ee7fda0a1bc8ad3f53aff95327a6e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-07T00:17:47.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-07T00:17:47.000Z", "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "rika77/convex_hull_with_boost", "max_issues_repo_head_hexsha": "4dd09da3173ee7fda0a1bc8ad3f53aff95327a6e", "max_issues_repo_licenses": ["MIT"], "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": "rika77/convex_hull_with_boost", "max_forks_repo_head_hexsha": "4dd09da3173ee7fda0a1bc8ad3f53aff95327a6e", "max_forks_repo_licenses": ["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.3529411765, "max_line_length": 78, "alphanum_fraction": 0.6161825726, "num_tokens": 345, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478255, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4835310560700511}}
{"text": "#define BOOST_TEST_MAIN\n#include <boost/test/unit_test.hpp>\n\n#include <rigging/CompositeCamera.h>\n#include <rigging/DerivedCamera.h>\n#include <rigging/SimpleCamera.h>\nusing namespace rigging;\n\n#define CHECK_EQUIVALENT_VECTORS(l,r) BOOST_CHECK_SMALL((l - r).norm(), 1e-5f)\n\nBOOST_AUTO_TEST_SUITE(test_CompositeCamera)\n\nBOOST_AUTO_TEST_CASE(stereo_test)\n{\n  // Make the camera rig itself.\n  CompositeCamera_Ptr rig(new CompositeCamera(Eigen::Vector3f(0.0f, 0.0f, 0.0f), Eigen::Vector3f(0.0f, 1.0f, 0.0f), Eigen::Vector3f(0.0f, 0.0f, 1.0f)));\n\n  // Add left eye and right eye cameras to the rig. These are respectively 1 unit to the left and right of the main camera\n  // and point inwards at an angle of 45 degrees.\n  Camera_CPtr leftCamera(new DerivedCamera(\n    rig,\n    Eigen::AngleAxisf(static_cast<float>(-M_PI/4.0f), Eigen::Vector3f(0.0f, 1.0f, 0.0f)).toRotationMatrix(),  // the rotation is in *camera space*, i.e. about v\n    Eigen::Vector3f(1.0f, 0.0f, 0.0f)                                                     // the translation is in *camera space*, i.e. along u\n  ));\n  rig->add_secondary_camera(\"left\", leftCamera);\n\n  Camera_CPtr rightCamera(new DerivedCamera(\n    rig,\n    Eigen::AngleAxisf(static_cast<float>(M_PI/4.0f), Eigen::Vector3f(0.0f, 1.0f, 0.0f)).toRotationMatrix(),   // the rotation is in *camera space*, i.e. about v\n    Eigen::Vector3f(-1.0f, 0.0f, 0.0f)                                                    // the translation is in *camera space*, i.e. along -u\n  ));\n  rig->add_secondary_camera(\"right\", rightCamera);\n\n  // Rotate the entire rig so that it faces downwards.\n  rig->rotate(rig->u(), static_cast<float>(M_PI/2.0f));\n\n  // Check the positions and orientations of the left and right eye cameras.\n  const float ONE_OVER_ROOT_2 = 1.0f / sqrtf(2.0f);\n  CHECK_EQUIVALENT_VECTORS(rig->get_secondary_camera(\"left\")->p(), Eigen::Vector3f(-1.0f, 0.0f, 0.0f));\n  CHECK_EQUIVALENT_VECTORS(rig->get_secondary_camera(\"left\")->u(), Eigen::Vector3f(-ONE_OVER_ROOT_2, 0.0f, -ONE_OVER_ROOT_2));\n  CHECK_EQUIVALENT_VECTORS(rig->get_secondary_camera(\"left\")->v(), Eigen::Vector3f(0.0f, 1.0f, 0.0f));\n  CHECK_EQUIVALENT_VECTORS(rig->get_secondary_camera(\"left\")->n(), Eigen::Vector3f(ONE_OVER_ROOT_2, 0.0f, -ONE_OVER_ROOT_2));\n  CHECK_EQUIVALENT_VECTORS(rig->get_secondary_camera(\"right\")->p(), Eigen::Vector3f(1.0f, 0.0f, 0.0f));\n  CHECK_EQUIVALENT_VECTORS(rig->get_secondary_camera(\"right\")->u(), Eigen::Vector3f(-ONE_OVER_ROOT_2, 0.0f, ONE_OVER_ROOT_2));\n  CHECK_EQUIVALENT_VECTORS(rig->get_secondary_camera(\"right\")->v(), Eigen::Vector3f(0.0f, 1.0f, 0.0f));\n  CHECK_EQUIVALENT_VECTORS(rig->get_secondary_camera(\"right\")->n(), Eigen::Vector3f(-ONE_OVER_ROOT_2, 0.0f, -ONE_OVER_ROOT_2));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "bb17c23fcb008882fe7a62d9c1ae05f2c44cc80a", "size": 2741, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/unit/rigging/test_CompositeCamera.cpp", "max_stars_repo_name": "torrvision/spaint", "max_stars_repo_head_hexsha": "9cac8100323ea42fe439f66407b832b88f72d2fd", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 197.0, "max_stars_repo_stars_event_min_datetime": "2015-10-01T07:23:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T03:02:31.000Z", "max_issues_repo_path": "tests/unit/rigging/test_CompositeCamera.cpp", "max_issues_repo_name": "GucciPrada/spaint", "max_issues_repo_head_hexsha": "b09ff1ec0d9e123cf316f2737e1b70b5ecc0beea", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 16.0, "max_issues_repo_issues_event_min_datetime": "2016-03-26T13:01:08.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-02T09:13:49.000Z", "max_forks_repo_path": "tests/unit/rigging/test_CompositeCamera.cpp", "max_forks_repo_name": "GucciPrada/spaint", "max_forks_repo_head_hexsha": "b09ff1ec0d9e123cf316f2737e1b70b5ecc0beea", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 62.0, "max_forks_repo_forks_event_min_datetime": "2015-10-03T07:14:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-31T08:58:18.000Z", "avg_line_length": 54.82, "max_line_length": 160, "alphanum_fraction": 0.7022984312, "num_tokens": 918, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.48349212907639394}}
{"text": "\r\n// Copyright (C) 2003-2004 Jeremy B. Maitin-Shepard.\r\n// Copyright (C) 2005-2009 Daniel James\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_UNORDERED_DETAIL_UTIL_HPP_INCLUDED\r\n#define BOOST_UNORDERED_DETAIL_UTIL_HPP_INCLUDED\r\n\r\n#include <cstddef>\r\n#include <utility>\r\n#include <algorithm>\r\n#include <boost/limits.hpp>\r\n#include <boost/iterator/iterator_categories.hpp>\r\n#include <boost/preprocessor/seq/size.hpp>\r\n#include <boost/preprocessor/seq/enum.hpp>\r\n#include <boost/unordered/detail/fwd.hpp>\r\n\r\nnamespace boost { namespace unordered_detail {\r\n\r\n    ////////////////////////////////////////////////////////////////////////////\r\n    // convert double to std::size_t\r\n\r\n    inline std::size_t double_to_size_t(double f)\r\n    {\r\n        return f >= static_cast<double>(\r\n            (std::numeric_limits<std::size_t>::max)()) ?\r\n            (std::numeric_limits<std::size_t>::max)() :\r\n            static_cast<std::size_t>(f);\r\n    }\r\n\r\n    ////////////////////////////////////////////////////////////////////////////\r\n    // primes\r\n\r\n#define BOOST_UNORDERED_PRIMES \\\r\n    (5ul)(11ul)(17ul)(29ul)(37ul)(53ul)(67ul)(79ul) \\\r\n    (97ul)(131ul)(193ul)(257ul)(389ul)(521ul)(769ul) \\\r\n    (1031ul)(1543ul)(2053ul)(3079ul)(6151ul)(12289ul)(24593ul) \\\r\n    (49157ul)(98317ul)(196613ul)(393241ul)(786433ul) \\\r\n    (1572869ul)(3145739ul)(6291469ul)(12582917ul)(25165843ul) \\\r\n    (50331653ul)(100663319ul)(201326611ul)(402653189ul)(805306457ul) \\\r\n    (1610612741ul)(3221225473ul)(4294967291ul)\r\n\r\n    template<class T> struct prime_list_template\r\n    {\r\n        static std::size_t const value[];\r\n\r\n#if !defined(SUNPRO_CC)\r\n        static std::ptrdiff_t const length;\r\n#else\r\n        static std::ptrdiff_t const length\r\n            = BOOST_PP_SEQ_SIZE(BOOST_UNORDERED_PRIMES);\r\n#endif\r\n    };\r\n\r\n    template<class T>\r\n    std::size_t const prime_list_template<T>::value[] = {\r\n        BOOST_PP_SEQ_ENUM(BOOST_UNORDERED_PRIMES)\r\n    };\r\n\r\n#if !defined(SUNPRO_CC)\r\n    template<class T>\r\n    std::ptrdiff_t const prime_list_template<T>::length\r\n        = BOOST_PP_SEQ_SIZE(BOOST_UNORDERED_PRIMES);\r\n#endif\r\n\r\n#undef BOOST_UNORDERED_PRIMES\r\n\r\n    typedef prime_list_template<std::size_t> prime_list;\r\n\r\n    // no throw\r\n    inline std::size_t next_prime(std::size_t num) {\r\n        std::size_t const* const prime_list_begin = prime_list::value;\r\n        std::size_t const* const prime_list_end = prime_list_begin +\r\n            prime_list::length;\r\n        std::size_t const* bound =\r\n            std::lower_bound(prime_list_begin, prime_list_end, num);\r\n        if(bound == prime_list_end)\r\n            bound--;\r\n        return *bound;\r\n    }\r\n\r\n    // no throw\r\n    inline std::size_t prev_prime(std::size_t num) {\r\n        std::size_t const* const prime_list_begin = prime_list::value;\r\n        std::size_t const* const prime_list_end = prime_list_begin +\r\n            prime_list::length;\r\n        std::size_t const* bound =\r\n            std::upper_bound(prime_list_begin,prime_list_end, num);\r\n        if(bound != prime_list_begin)\r\n            bound--;\r\n        return *bound;\r\n    }\r\n\r\n    ////////////////////////////////////////////////////////////////////////////\r\n    // pair_cast - because some libraries don't have the full pair constructors.\r\n\r\n    template <class Dst1, class Dst2, class Src1, class Src2>\r\n    inline std::pair<Dst1, Dst2> pair_cast(std::pair<Src1, Src2> const& x)\r\n    {\r\n        return std::pair<Dst1, Dst2>(Dst1(x.first), Dst2(x.second));\r\n    }\r\n\r\n    ////////////////////////////////////////////////////////////////////////////\r\n    // insert_size/initial_size\r\n\r\n#if !defined(BOOST_NO_STD_DISTANCE)\r\n    using ::std::distance;\r\n#else\r\n    template <class ForwardIterator>\r\n    inline std::size_t distance(ForwardIterator i, ForwardIterator j) {\r\n        std::size_t x;\r\n        std::distance(i, j, x);\r\n        return x;\r\n    }\r\n#endif\r\n\r\n    template <class I>\r\n    inline std::size_t insert_size(I i, I j, boost::forward_traversal_tag)\r\n    {\r\n        return std::distance(i, j);\r\n    }\r\n\r\n    template <class I>\r\n    inline std::size_t insert_size(I, I, boost::incrementable_traversal_tag)\r\n    {\r\n        return 1;\r\n    }\r\n\r\n    template <class I>\r\n    inline std::size_t insert_size(I i, I j)\r\n    {\r\n        BOOST_DEDUCED_TYPENAME boost::iterator_traversal<I>::type\r\n            iterator_traversal_tag;\r\n        return insert_size(i, j, iterator_traversal_tag);\r\n    }\r\n    \r\n    template <class I>\r\n    inline std::size_t initial_size(I i, I j,\r\n        std::size_t num_buckets = boost::unordered_detail::default_bucket_count)\r\n    {\r\n        return (std::max)(static_cast<std::size_t>(insert_size(i, j)) + 1,\r\n            num_buckets);\r\n    }\r\n\r\n    ////////////////////////////////////////////////////////////////////////////\r\n    // Node Constructors\r\n\r\n#if defined(BOOST_UNORDERED_STD_FORWARD)\r\n\r\n    template <class T, class... Args>\r\n    inline void construct_impl(T*, void* address, Args&&... args)\r\n    {\r\n        new(address) T(std::forward<Args>(args)...);\r\n    }\r\n\r\n#if defined(BOOST_UNORDERED_CPP0X_PAIR)\r\n    template <class First, class Second, class Key, class Arg0, class... Args>\r\n    inline void construct_impl(std::pair<First, Second>*, void* address,\r\n        Key&& k, Arg0&& arg0, Args&&... args)\r\n    )\r\n    {\r\n        new(address) std::pair<First, Second>(k,\r\n            Second(arg0, std::forward<Args>(args)...);\r\n    }\r\n#endif\r\n\r\n#else\r\n\r\n#define BOOST_UNORDERED_CONSTRUCT_IMPL(z, num_params, _)                       \\\r\n    template <                                                                 \\\r\n        class T,                                                               \\\r\n        BOOST_UNORDERED_TEMPLATE_ARGS(z, num_params)                           \\\r\n    >                                                                          \\\r\n    inline void construct_impl(                                                \\\r\n        T*, void* address,                                                     \\\r\n        BOOST_UNORDERED_FUNCTION_PARAMS(z, num_params)                         \\\r\n    )                                                                          \\\r\n    {                                                                          \\\r\n        new(address) T(                                                        \\\r\n            BOOST_UNORDERED_CALL_PARAMS(z, num_params));                       \\\r\n    }                                                                          \\\r\n                                                                               \\\r\n    template <class First, class Second, class Key,                            \\\r\n        BOOST_UNORDERED_TEMPLATE_ARGS(z, num_params)                           \\\r\n    >                                                                          \\\r\n    inline void construct_impl(                                                \\\r\n        std::pair<First, Second>*, void* address,                              \\\r\n        Key const& k, BOOST_UNORDERED_FUNCTION_PARAMS(z, num_params))          \\\r\n    {                                                                          \\\r\n        new(address) std::pair<First, Second>(k,                               \\\r\n            Second(BOOST_UNORDERED_CALL_PARAMS(z, num_params)));               \\\r\n    }\r\n\r\n    BOOST_PP_REPEAT_FROM_TO(1, BOOST_UNORDERED_EMPLACE_LIMIT,\r\n        BOOST_UNORDERED_CONSTRUCT_IMPL, _)\r\n\r\n#undef BOOST_UNORDERED_CONSTRUCT_IMPL\r\n#endif\r\n\r\n    // hash_node_constructor\r\n    //\r\n    // Used to construct nodes in an exception safe manner.\r\n\r\n    template <class Alloc, class Grouped>\r\n    class hash_node_constructor\r\n    {\r\n        typedef hash_buckets<Alloc, Grouped> buckets;\r\n        typedef BOOST_DEDUCED_TYPENAME buckets::node node;\r\n        typedef BOOST_DEDUCED_TYPENAME buckets::real_node_ptr real_node_ptr;\r\n        typedef BOOST_DEDUCED_TYPENAME buckets::value_type value_type;\r\n\r\n        buckets& buckets_;\r\n        real_node_ptr node_;\r\n        bool node_constructed_;\r\n        bool value_constructed_;\r\n\r\n    public:\r\n\r\n        hash_node_constructor(buckets& m) :\r\n            buckets_(m),\r\n            node_(),\r\n            node_constructed_(false),\r\n            value_constructed_(false)\r\n        {\r\n        }\r\n\r\n        ~hash_node_constructor();\r\n        void construct_preamble();\r\n\r\n#if defined(BOOST_UNORDERED_STD_FORWARD)\r\n        template <class... Args>\r\n        void construct(Args&&... args)\r\n        {\r\n            construct_preamble();\r\n            construct_impl((value_type*) 0, node_->address(),\r\n                std::forward<Args>(args)...);\r\n            value_constructed_ = true;\r\n        }\r\n#else\r\n\r\n#define BOOST_UNORDERED_CONSTRUCT(z, num_params, _)                            \\\r\n        template <                                                             \\\r\n            BOOST_UNORDERED_TEMPLATE_ARGS(z, num_params)                       \\\r\n        >                                                                      \\\r\n        void construct(                                                        \\\r\n            BOOST_UNORDERED_FUNCTION_PARAMS(z, num_params)                     \\\r\n        )                                                                      \\\r\n        {                                                                      \\\r\n            construct_preamble();                                              \\\r\n            construct_impl(                                                    \\\r\n                (value_type*) 0, node_->address(),                             \\\r\n                BOOST_UNORDERED_CALL_PARAMS(z, num_params)                     \\\r\n            );                                                                 \\\r\n            value_constructed_ = true;                                         \\\r\n        }\r\n\r\n        BOOST_PP_REPEAT_FROM_TO(1, BOOST_UNORDERED_EMPLACE_LIMIT,\r\n            BOOST_UNORDERED_CONSTRUCT, _)\r\n\r\n#undef BOOST_UNORDERED_CONSTRUCT\r\n\r\n#endif\r\n        template <class K, class M>\r\n        void construct_pair(K const& k, M*)\r\n        {\r\n            construct_preamble();\r\n            new(node_->address()) value_type(k, M());                    \r\n            value_constructed_ = true;\r\n        }\r\n\r\n        value_type& value() const\r\n        {\r\n            BOOST_ASSERT(node_);\r\n            return node_->value();\r\n        }\r\n\r\n        // no throw\r\n        BOOST_DEDUCED_TYPENAME buckets::node_ptr release()\r\n        {\r\n            real_node_ptr p = node_;\r\n            node_ = real_node_ptr();\r\n            // node_ptr cast\r\n            return buckets_.bucket_alloc().address(*p);\r\n        }\r\n\r\n    private:\r\n        hash_node_constructor(hash_node_constructor const&);\r\n        hash_node_constructor& operator=(hash_node_constructor const&);\r\n    };\r\n    \r\n    // hash_node_constructor\r\n\r\n    template <class Alloc, class Grouped>\r\n    inline hash_node_constructor<Alloc, Grouped>::~hash_node_constructor()\r\n    {\r\n        if (node_) {\r\n            if (value_constructed_) {\r\n#if BOOST_WORKAROUND(__CODEGEARC__, BOOST_TESTED_AT(0x0613))\r\n                struct dummy { hash_node<Alloc, Grouped> x; };\r\n#endif\r\n                boost::unordered_detail::destroy(node_->value_ptr());\r\n            }\r\n\r\n            if (node_constructed_)\r\n                buckets_.node_alloc().destroy(node_);\r\n\r\n            buckets_.node_alloc().deallocate(node_, 1);\r\n        }\r\n    }\r\n\r\n    template <class Alloc, class Grouped>\r\n    inline void hash_node_constructor<Alloc, Grouped>::construct_preamble()\r\n    {\r\n        if(!node_) {\r\n            node_constructed_ = false;\r\n            value_constructed_ = false;\r\n\r\n            node_ = buckets_.node_alloc().allocate(1);\r\n            buckets_.node_alloc().construct(node_, node());\r\n            node_constructed_ = true;\r\n        }\r\n        else {\r\n            BOOST_ASSERT(node_constructed_ && value_constructed_);\r\n            boost::unordered_detail::destroy(node_->value_ptr());\r\n            value_constructed_ = false;\r\n        }\r\n    }\r\n}}\r\n\r\n#endif\r\n", "meta": {"hexsha": "61f86e36a5d132654320f9956cf4d5f17787ea60", "size": 12145, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "trunk/win/Source/Includes/Boost/unordered/detail/util.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/unordered/detail/util.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/unordered/detail/util.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": 36.5813253012, "max_line_length": 81, "alphanum_fraction": 0.4992177851, "num_tokens": 2451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.48349212907639394}}
{"text": "\n#include <boost/config.hpp>\n#include <fstream>\n#include <iostream>\n#include <regex>\n\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <boost/graph/graph_traits.hpp>\n\nusing namespace boost;\ntypedef adjacency_list<listS,\n                       vecS,\n                       directedS,\n                       no_property,\n                       property<edge_weight_t, int>>\n    graph_t;\ntypedef graph_traits<graph_t>::vertex_descriptor vertex_descriptor;\ntypedef graph_traits<graph_t>::edge_descriptor edge_descriptor;\n\ntypedef std::pair<int, int> Edge;\n\ntypedef std::pair<int, int> Point;\ntypedef std::vector<Point> Alignment;\n\nstd::vector<std::string> split(const std::string& input,\n                               const std::string& regex) {\n  std::regex re(regex);\n  std::sregex_token_iterator first{input.begin(), input.end(), re, -1}, last;\n  return {first, last};\n}\n\nfloat dist(Point a, Point b) {\n  return sqrt(pow(b.first - a.first, 2) + pow(b.second - a.second, 2)) - 1;\n}\n\nAlignment shortestPath(const Alignment& a) {\n  Alignment shortest;\n\n  std::vector<Edge> edges;\n  std::vector<int> weights;\n\n  for(int i = 0; i < a.size(); ++i) {\n    for(int j = 0; j < a.size(); ++j) {\n      if(a[i] != a[j] && a[j].first - a[i].first >= 0\n         && a[j].second - a[i].second >= 0) {\n        edges.push_back(Edge(i, j));\n        weights.push_back(dist(a[i], a[j]));\n      }\n    }\n  }\n\n  graph_t g(edges.begin(), edges.end(), weights.data(), a.size());\n  property_map<graph_t, edge_weight_t>::type weightmap = get(edge_weight, g);\n\n  std::vector<vertex_descriptor> p(num_vertices(g));\n  std::vector<int> d(num_vertices(g));\n  vertex_descriptor s = vertex(0, g);\n\n  dijkstra_shortest_paths(g, s, predecessor_map(&p[0]).distance_map(&d[0]));\n\n  int v = a.size() - 1;\n  while(v != 0) {\n    shortest.push_back(a[v]);\n    v = p[v];\n  }\n  shortest.push_back(a[v]);\n  std::sort(shortest.begin(), shortest.end());\n\n  Alignment shortestU;\n  for(auto p : shortest)\n    if(shortestU.empty() || shortestU.back().first != p.first)\n      shortestU.push_back(p);\n\n  return shortestU;\n}\n\nint main(int argc, char** argv) {\n  if(argc != 4) {\n    std::cerr << \"Usage: ./align2steps source target alignment\" << std::endl;\n    exit(1);\n  }\n\n  std::ifstream srcStrm, trgStrm, alnStrm;\n  srcStrm.open(argv[1]);\n  trgStrm.open(argv[2]);\n  alnStrm.open(argv[3]);\n\n  int i = 0;\n  std::string source, target, alignment;\n  while(std::getline(srcStrm, source) && std::getline(trgStrm, target)\n        && std::getline(alnStrm, alignment)) {\n    auto srcToks = split(source, R\"(\\s)\");\n    auto trgToks = split(target, R\"(\\s)\");\n    auto alnToks = split(alignment, R\"(\\s|-)\");\n\n    Alignment alignment;\n    for(int i = 0; i < alnToks.size(); i += 2)\n      alignment.emplace_back(std::stoi(alnToks[i + 1]), std::stoi(alnToks[i]));\n\n    // add end\n    alignment.emplace_back(trgToks.size(), srcToks.size());\n\n    auto shortest = shortestPath(alignment);\n\n    int cTrg = 0, cSrc = 0;\n    for(auto& p : shortest) {\n      for(int i = cTrg; i < p.first; ++i)\n        std::cout << trgToks[i] << \" \";\n\n      for(int i = cSrc; i < p.second; ++i)\n        std::cout << \"<step> \";\n\n      cTrg = p.first;\n      cSrc = p.second;\n    }\n\n    std::cout << std::endl;\n    i++;\n    if(i % 10000 == 0)\n      std::cerr << i << \" \";\n  }\n  std::cerr << std::endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "713b0bfcc025336bdf594210fe59ea0a81af1843", "size": 3376, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/marian/src/tools/align2steps.cpp", "max_stars_repo_name": "fatemeh-azadi/Marian", "max_stars_repo_head_hexsha": "8d0d88c3c358a364ac94bd5271a44a0b83b099d3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-10-09T20:34:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-26T15:09:16.000Z", "max_issues_repo_path": "src/marian/src/tools/align2steps.cpp", "max_issues_repo_name": "fatemeh-azadi/Marian", "max_issues_repo_head_hexsha": "8d0d88c3c358a364ac94bd5271a44a0b83b099d3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-02-11T21:15:45.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-11T21:15:45.000Z", "max_forks_repo_path": "src/marian/src/tools/align2steps.cpp", "max_forks_repo_name": "fatemeh-azadi/Marian", "max_forks_repo_head_hexsha": "8d0d88c3c358a364ac94bd5271a44a0b83b099d3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-07-07T18:22:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-07T18:22:00.000Z", "avg_line_length": 26.5826771654, "max_line_length": 79, "alphanum_fraction": 0.5983412322, "num_tokens": 967, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.4834921231875924}}
{"text": "//  ratio_test.cpp  ----------------------------------------------------------//\r\n\r\n//  Copyright 2008 Howard Hinnant\r\n//  Copyright 2008 Beman Dawes\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#include <iostream>\r\n#include <boost/ratio/ratio.hpp>\r\n#include \"duration.hpp\"\r\n\r\nnamespace User1\r\n{\r\n// Example type-safe \"physics\" code interoperating with chrono::duration types\r\n//  and taking advantage of the std::ratio infrastructure and design philosophy.\r\n\r\n// length - mimics chrono::duration except restricts representation to double.\r\n//    Uses boost::ratio facilities for length units conversions.\r\n\r\ntemplate <class Ratio>\r\nclass length\r\n{\r\npublic:\r\n    typedef Ratio ratio;\r\nprivate:\r\n    double len_;\r\npublic:\r\n\r\n    length() : len_(1) {}\r\n    length(const double& len) : len_(len) {}\r\n\r\n    // conversions\r\n    template <class R>\r\n    length(const length<R>& d)\r\n            : len_(d.count() * boost::ratio_divide<Ratio, R>::type::den /\r\n                               boost::ratio_divide<Ratio, R>::type::num) {}\r\n\r\n    // observer\r\n\r\n    double count() const {return len_;}\r\n\r\n    // arithmetic\r\n\r\n    length& operator+=(const length& d) {len_ += d.count(); return *this;}\r\n    length& operator-=(const length& d) {len_ -= d.count(); return *this;}\r\n\r\n    length operator+() const {return *this;}\r\n    length operator-() const {return length(-len_);}\r\n\r\n    length& operator*=(double rhs) {len_ *= rhs; return *this;}\r\n    length& operator/=(double rhs) {len_ /= rhs; return *this;}\r\n};\r\n\r\n// Sparse sampling of length units\r\ntypedef length<boost::ratio<1> >          meter;        // set meter as \"unity\"\r\ntypedef length<boost::centi>              centimeter;   // 1/100 meter\r\ntypedef length<boost::kilo>               kilometer;    // 1000  meters\r\ntypedef length<boost::ratio<254, 10000> > inch;         // 254/10000 meters\r\n// length takes ratio instead of two integral types so that definitions can be made like so:\r\ntypedef length<boost::ratio_multiply<boost::ratio<12>, inch::ratio>::type>   foot;  // 12 inchs\r\ntypedef length<boost::ratio_multiply<boost::ratio<5280>, foot::ratio>::type> mile;  // 5280 feet\r\n\r\n// Need a floating point definition of seconds\r\ntypedef boost_ex::chrono::duration<double> seconds;                         // unity\r\n// Demo of (scientific) support for sub-nanosecond resolutions\r\ntypedef boost_ex::chrono::duration<double,  boost::pico> picosecond;  // 10^-12 seconds\r\ntypedef boost_ex::chrono::duration<double, boost::femto> femtosecond; // 10^-15 seconds\r\ntypedef boost_ex::chrono::duration<double,  boost::atto> attosecond;  // 10^-18 seconds\r\n\r\n// A very brief proof-of-concept for SIUnits-like library\r\n//  Hard-wired to floating point seconds and meters, but accepts other units (shown in testUser1())\r\ntemplate <class R1, class R2>\r\nclass quantity\r\n{\r\n    double q_;\r\npublic:\r\n    typedef R1 time_dim;\r\n    typedef R2 distance_dim;\r\n    quantity() : q_(1) {}\r\n\r\n    double get() const {return q_;}\r\n    void set(double q) {q_ = q;}\r\n};\r\n\r\ntemplate <>\r\nclass quantity<boost::ratio<1>, boost::ratio<0> >\r\n{\r\n    double q_;\r\npublic:\r\n    quantity() : q_(1) {}\r\n    quantity(seconds d) : q_(d.count()) {}  // note:  only User1::seconds needed here\r\n\r\n    double get() const {return q_;}\r\n    void set(double q) {q_ = q;}\r\n};\r\n\r\ntemplate <>\r\nclass quantity<boost::ratio<0>, boost::ratio<1> >\r\n{\r\n    double q_;\r\npublic:\r\n    quantity() : q_(1) {}\r\n    quantity(meter d) : q_(d.count()) {}  // note:  only User1::meter needed here\r\n\r\n    double get() const {return q_;}\r\n    void set(double q) {q_ = q;}\r\n};\r\n\r\ntemplate <>\r\nclass quantity<boost::ratio<0>, boost::ratio<0> >\r\n{\r\n    double q_;\r\npublic:\r\n    quantity() : q_(1) {}\r\n    quantity(double d) : q_(d) {}\r\n\r\n    double get() const {return q_;}\r\n    void set(double q) {q_ = q;}\r\n};\r\n\r\n// Example SI-Units\r\ntypedef quantity<boost::ratio<0>, boost::ratio<0> >  Scalar;\r\ntypedef quantity<boost::ratio<1>, boost::ratio<0> >  Time;         // second\r\ntypedef quantity<boost::ratio<0>, boost::ratio<1> >  Distance;     // meter\r\ntypedef quantity<boost::ratio<-1>, boost::ratio<1> > Speed;        // meter/second\r\ntypedef quantity<boost::ratio<-2>, boost::ratio<1> > Acceleration; // meter/second^2\r\n\r\ntemplate <class R1, class R2, class R3, class R4>\r\nquantity<typename boost::ratio_subtract<R1, R3>::type, typename boost::ratio_subtract<R2, R4>::type>\r\noperator/(const quantity<R1, R2>& x, const quantity<R3, R4>& y)\r\n{\r\n    typedef quantity<typename boost::ratio_subtract<R1, R3>::type, typename boost::ratio_subtract<R2, R4>::type> R;\r\n    R r;\r\n    r.set(x.get() / y.get());\r\n    return r;\r\n}\r\n\r\ntemplate <class R1, class R2, class R3, class R4>\r\nquantity<typename boost::ratio_add<R1, R3>::type, typename boost::ratio_add<R2, R4>::type>\r\noperator*(const quantity<R1, R2>& x, const quantity<R3, R4>& y)\r\n{\r\n    typedef quantity<typename boost::ratio_add<R1, R3>::type, typename boost::ratio_add<R2, R4>::type> R;\r\n    R r;\r\n    r.set(x.get() * y.get());\r\n    return r;\r\n}\r\n\r\ntemplate <class R1, class R2>\r\nquantity<R1, R2>\r\noperator+(const quantity<R1, R2>& x, const quantity<R1, R2>& y)\r\n{\r\n    typedef quantity<R1, R2> R;\r\n    R r;\r\n    r.set(x.get() + y.get());\r\n    return r;\r\n}\r\n\r\ntemplate <class R1, class R2>\r\nquantity<R1, R2>\r\noperator-(const quantity<R1, R2>& x, const quantity<R1, R2>& y)\r\n{\r\n    typedef quantity<R1, R2> R;\r\n    R r;\r\n    r.set(x.get() - y.get());\r\n    return r;\r\n}\r\n\r\n// Example type-safe physics function\r\nDistance\r\ncompute_distance(Speed v0, Time t, Acceleration a)\r\n{\r\n    return v0 * t + Scalar(.5) * a * t * t;  // if a units mistake is made here it won't compile\r\n}\r\n\r\n} // User1\r\n\r\n// Exercise example type-safe physics function and show interoperation\r\n// of custom time durations (User1::seconds) and standard time durations (std::hours).\r\n// Though input can be arbitrary (but type-safe) units, output is always in SI-units\r\n//   (a limitation of the simplified Units lib demoed here).\r\n\r\n\r\n\r\nint main()\r\n{\r\n    //~ typedef boost::ratio<8, BOOST_INTMAX_C(0x7FFFFFFFD)> R1;\r\n    //~ typedef boost::ratio<3, BOOST_INTMAX_C(0x7FFFFFFFD)> R2;\r\n    typedef User1::quantity<boost::ratio_subtract<boost::ratio<0>, boost::ratio<1> >::type, \r\n                             boost::ratio_subtract<boost::ratio<1>, boost::ratio<0> >::type > RR;\r\n    //~ typedef boost::ratio_subtract<R1, R2>::type RS;\r\n    //~ std::cout << RS::num << '/' << RS::den << '\\n';\r\n    \r\n    \r\n    std::cout << \"*************\\n\";\r\n    std::cout << \"* testUser1 *\\n\";\r\n    std::cout << \"*************\\n\";\r\n    User1::Distance d(( User1::mile(110) ));\r\n    boost_ex::chrono::hours h((2));\r\n    User1::Time t(( h ));\r\n    //~ boost_ex::chrono::seconds sss=boost_ex::chrono::duration_cast<boost_ex::chrono::seconds>(h);\r\n    //~ User1::seconds sss((120));\r\n    //~ User1::Time t(( sss ));\r\n    \r\n    //typedef User1::quantity<boost::ratio_subtract<User1::Distance::time_dim, User1::Time::time_dim >::type, \r\n    //                        boost::ratio_subtract<User1::Distance::distance_dim, User1::Time::distance_dim >::type > R;\r\n    RR r=d / t;\r\n    //r.set(d.get() / t.get());\r\n    \r\n    User1::Speed rc= r;\r\n    \r\n    User1::Speed s = d / t;\r\n    std::cout << \"Speed = \" << s.get() << \" meters/sec\\n\";\r\n    User1::Acceleration a = User1::Distance( User1::foot(32.2) ) / User1::Time() / User1::Time();\r\n    std::cout << \"Acceleration = \" << a.get() << \" meters/sec^2\\n\";\r\n    User1::Distance df = compute_distance(s, User1::Time( User1::seconds(0.5) ), a);\r\n    std::cout << \"Distance = \" << df.get() << \" meters\\n\";\r\n    std::cout << \"There are \" << User1::mile::ratio::den << '/' << User1::mile::ratio::num << \" miles/meter\";\r\n    User1::meter mt = 1;\r\n    User1::mile mi = mt;\r\n    std::cout << \" which is approximately \" << mi.count() << '\\n';\r\n    std::cout << \"There are \" << User1::mile::ratio::num << '/' << User1::mile::ratio::den << \" meters/mile\";\r\n    mi = 1;\r\n    mt = mi;\r\n    std::cout << \" which is approximately \" << mt.count() << '\\n';\r\n    User1::attosecond as(1);\r\n    User1::seconds sec = as;\r\n    std::cout << \"1 attosecond is \" << sec.count() << \" seconds\\n\";\r\n    std::cout << \"sec = as;  // compiles\\n\";\r\n    sec = User1::seconds(1);\r\n    as = sec;\r\n    std::cout << \"1 second is \" << as.count() << \" attoseconds\\n\";\r\n    std::cout << \"as = sec;  // compiles\\n\";\r\n    std::cout << \"\\n\";\r\n  return 0;\r\n}\r\n", "meta": {"hexsha": "f6aa28773f31cca5292341671a8c43f384ef9dcd", "size": 8412, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/ratio/example/si_physics.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/ratio/example/si_physics.cpp", "max_issues_repo_name": "xiaoliang2121/Boost", "max_issues_repo_head_hexsha": "fc90c3fde129c62565c023f091eddc4a7ed9902b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-03-19T08:23:23.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-24T07:48:47.000Z", "max_forks_repo_path": "libs/ratio/example/si_physics.cpp", "max_forks_repo_name": "xiaoliang2121/Boost", "max_forks_repo_head_hexsha": "fc90c3fde129c62565c023f091eddc4a7ed9902b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 35.4936708861, "max_line_length": 122, "alphanum_fraction": 0.6011650024, "num_tokens": 2348, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4834921231875923}}
{"text": "#include <Eigen/Core>\n#include \"mex.h\"\n\nusing namespace Eigen;\nusing namespace std;\n\n// TODO openmp version\n\n// NOTE: mxSetProperty and possibly mxGetProperty make copies, even with\n// classdef < handle! lame! I believe mxGetField does NOT make a copy, though I\n// haven't tested it recently\n\nvoid mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] )\n{\n\n    /* SETUP */\n    if (nrhs != 5) { mexErrMsgTxt(\"wrong number of arguments\\n\"); }\n\n    //// pull out inputs\n\n    // data\n    if (!mxGetField(prhs[0],0,\"data\")) { mexErrMsgTxt(\"data missing 'data' field\\n\"); }\n    int8_t *alldata = (int8_t *) mxGetData(mxGetField(prhs[0],0,\"data\"));\n    int bigT = mxGetN(mxGetField(prhs[0],0,\"data\")); // total length of the data\n    int num_subparts = mxGetM(mxGetField(prhs[0],0,\"data\")); // number of sub-parts\n\n    if (!mxGetField(prhs[0],0,\"resources\")) { mexErrMsgTxt(\"data missing 'resources' field\\n\"); }\n    int8_t *allresources = (int8_t *) mxGetData(mxGetField(prhs[0],0,\"resources\"));\n\n    if (!mxGetField(prhs[0],0,\"starts\")) { mexErrMsgTxt(\"data missing 'starts' field\\n\"); }\n    int32_t *starts = (int32_t *) mxGetData(mxGetField(prhs[0],0,\"starts\"));\n    int num_sequences = max(mxGetM(mxGetField(prhs[0],0,\"starts\")),\n            mxGetM(mxGetField(prhs[0],0,\"starts\")));\n\n    if (!mxGetField(prhs[0],0,\"lengths\")) { mexErrMsgTxt(\"data missing 'lengths' field\\n\"); }\n    int32_t *lengths = (int32_t *) mxGetData(mxGetField(prhs[0],0,\"lengths\"));\n\n    // parameters struct\n    if (!mxGetField(prhs[1],0,\"learns\")) { mexErrMsgTxt(\"model missing 'learns' field\\n\"); }\n    double *learns = mxGetPr(mxGetField(prhs[1],0,\"learns\"));\n    int num_resources = max(mxGetM(mxGetField(prhs[1],0,\"learns\")),\n            mxGetN(mxGetField(prhs[1],0,\"learns\")));\n\n    if (!mxGetField(prhs[1],0,\"forgets\")) { mexErrMsgTxt(\"model missing 'forgets' field\\n\"); }\n    double *forgets = mxGetPr(mxGetField(prhs[1],0,\"forgets\"));\n\n    if (!mxGetField(prhs[1],0,\"guesses\")) { mexErrMsgTxt(\"model missing 'guesses' field\\n\"); }\n    double *guess = mxGetPr(mxGetField(prhs[1],0,\"guesses\"));\n\n    if (!mxGetField(prhs[1],0,\"slips\")) { mexErrMsgTxt(\"model missing 'slips' field\\n\"); }\n    double *slip = mxGetPr(mxGetField(prhs[1],0,\"slips\"));\n\n    if (!mxGetField(prhs[1],0,\"prior\")) { mexErrMsgTxt(\"model missing 'prior' field\\n\"); }\n    double prior = mxGetScalar(mxGetField(prhs[1],0,\"prior\"));\n\n    Array2d initial_distn;\n    initial_distn << 1-prior, prior;\n\n    MatrixXd As(2,2*num_resources);\n    for (int n=0; n<num_resources; n++) {\n        As.col(2*n) << 1-learns[n], learns[n];\n        As.col(2*n+1) << forgets[n], 1-forgets[n];\n    }\n\n    Array2Xd Bn(2,2*num_subparts);\n    for (int n=0; n<num_subparts; n++) {\n        Bn.col(2*n) << 1-guess[n], slip[n]; // incorrect\n        Bn.col(2*n+1) << guess[n], 1-slip[n]; // correct\n    }\n\n    //// outputs\n\n    // rhs outputs\n    Map<ArrayXXd,Aligned> all_trans_softcounts(mxGetPr(prhs[2]),2,2*num_resources);\n    all_trans_softcounts.setZero();\n    Map<Array2Xd,Aligned> all_emission_softcounts(mxGetPr(prhs[3]),2,2*num_subparts);\n    all_emission_softcounts.setZero();\n    Map<Array2d,Aligned> all_initial_softcounts(mxGetPr(prhs[4]));\n    all_initial_softcounts.setZero();\n\n    // lhs outputs\n    Map<Array2Xd,Aligned> gamma_out(NULL,2,bigT);\n    Map<Array2Xd,Aligned> alpha_out(NULL,2,bigT);\n    double s_total_loglike = 0;\n    double *total_loglike = &s_total_loglike;\n    switch (nlhs) {\n        case 3:\n            plhs[2] = mxCreateDoubleMatrix(2,bigT,mxREAL);\n            new (&gamma_out) Map<Array2Xd,Aligned>(mxGetPr(plhs[2]),2,bigT);\n        case 2:\n            plhs[1] = mxCreateDoubleMatrix(2,bigT,mxREAL);\n            new (&alpha_out) Map<Array2Xd,Aligned>(mxGetPr(plhs[1]),2,bigT);\n        case 1:\n            plhs[0] = mxCreateDoubleScalar(0.);\n            total_loglike = mxGetPr(plhs[0]);\n    }\n\n    /* COMPUTATION */\n\n    for (int sequence_index=0; sequence_index < num_sequences; sequence_index++) {\n        // NOTE: -1 because Matlab indexing starts at 1\n        int32_t sequence_start = starts[sequence_index] - 1;\n        int32_t T = lengths[sequence_index];\n\n        int8_t *data = alldata + num_subparts*sequence_start;\n        int8_t *resources = allresources + sequence_start;\n\n        //// likelihoods\n        Array2Xd likelihoods(2,T);\n        likelihoods.setOnes();\n        for (int t=0; t<T; t++) {\n            for (int n=0; n<num_subparts; n++) {\n                if (data[n+num_subparts*t] != 0) {\n                    likelihoods.col(t) *= Bn.col(2*n + (data[n+num_subparts*t] == 2));\n                }\n            }\n        }\n\n        //// forward messages\n        double loglike, norm;\n        MatrixXd alpha(2,T);\n        alpha.col(0) = initial_distn * likelihoods.col(0);\n        norm = alpha.col(0).sum();\n        alpha.col(0) /= norm;\n        loglike = log(norm);\n        for (int t=0; t<T-1; t++) {\n            alpha.col(t+1) = (As.block(0,2*(resources[t]-1),2,2) * alpha.col(t)).array()\n                * likelihoods.col(t+1);\n            norm = alpha.col(t+1).sum();\n            alpha.col(t+1) /= norm;\n            loglike += log(norm);\n        }\n\n        //// backward messages and statistic counting\n        ArrayXXd trans_softcounts(2,2*num_resources);\n        trans_softcounts.setZero();\n        Array2Xd emission_softcounts(2,2*num_subparts);\n        emission_softcounts.setZero();\n        Array2d init_softcounts; // no need to set zero\n\n        Array2Xd gamma(2,T);\n        gamma.col(T-1) = alpha.col(T-1);\n        for (int n=0; n<num_subparts; n++) {\n            if (data[n+num_subparts*(T-1)] != 0) {\n                emission_softcounts.col(2*n + (data[n+num_subparts*(T-1)] == 2)) += gamma.col(T-1);\n            }\n        }\n        for (int t=T-2; t>=0; t--) {\n            Matrix2d A = As.block(0,2*(resources[t]-1),2,2);\n            Array22d pair = A;\n            pair.rowwise() *= alpha.col(t).transpose().array();\n            pair.colwise() *= gamma.col(t+1);\n            pair.colwise() /= (A*alpha.col(t)).array();\n\n            trans_softcounts.block(0,2*(resources[t]-1),2,2) += pair;\n\n            gamma.col(t) = pair.colwise().sum().transpose();\n            // NOTE: we have to touch the data again here\n            for (int n=0; n<num_subparts; n++) {\n                if (data[n+num_subparts*t] != 0) {\n                    emission_softcounts.col(2*n + (data[n+num_subparts*t] == 2)) += gamma.col(t);\n                }\n            }\n        }\n        init_softcounts = gamma.col(0);\n\n        // NOTE: these will need to change to base types for openmp\n        all_trans_softcounts += trans_softcounts;\n        all_emission_softcounts += emission_softcounts;\n        all_initial_softcounts += init_softcounts;\n\n        switch (nlhs) {\n            case 3:\n                gamma_out.block(0,sequence_start,2,T) = gamma;\n            case 2:\n                alpha_out.block(0,sequence_start,2,T) = alpha;\n            case 1:\n                *total_loglike += loglike;\n        }\n\n    }\n}\n\n", "meta": {"hexsha": "c414733bc6074e47eb600a674910bc36a4089696", "size": 6998, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "+fit/old/E_step_serial.cpp", "max_stars_repo_name": "CAHLR/xBKT", "max_stars_repo_head_hexsha": "73fae02218094a8cf1896992308e2b495d7c610a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2015-10-10T19:14:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-12T06:28:17.000Z", "max_issues_repo_path": "+fit/old/E_step_serial.cpp", "max_issues_repo_name": "CAHLR/xBKT", "max_issues_repo_head_hexsha": "73fae02218094a8cf1896992308e2b495d7c610a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "+fit/old/E_step_serial.cpp", "max_forks_repo_name": "CAHLR/xBKT", "max_forks_repo_head_hexsha": "73fae02218094a8cf1896992308e2b495d7c610a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-09-01T21:14:38.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-18T09:39:08.000Z", "avg_line_length": 38.0326086957, "max_line_length": 99, "alphanum_fraction": 0.5865961703, "num_tokens": 2056, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.48349212318759227}}
{"text": "/**\n * \\file CachedCosinusGeneratorFilter.cpp\n */\n\n#include \"CachedCosinusGeneratorFilter.h\"\n\n#include <boost/math/constants/constants.hpp>\n\n#include <cmath>\n#include <cstdint>\n#include <cstring>\n\nnamespace ATK\n{\n  template<typename DataType_>\n  CachedCosinusGeneratorFilter<DataType_>::CachedCosinusGeneratorFilter(int periods, int seconds)\n  :Parent(0, 1), periods(periods), seconds(seconds)\n  {\n  }\n  \n  template<typename DataType_>\n  void CachedCosinusGeneratorFilter<DataType_>::set_frequency(int periods, int seconds)\n  {\n    if(periods <= 0)\n    {\n      throw std::out_of_range(\"Periods must be strictly positive\");\n    }\n    this->periods = periods;\n    this->seconds = seconds;\n    setup();\n  }\n  \n  template<typename DataType_>\n  std::pair<int, int> CachedCosinusGeneratorFilter<DataType_>::get_frequency() const\n  {\n    return std::make_pair(periods, seconds);\n  }\n\n  template<typename DataType_>\n  void CachedCosinusGeneratorFilter<DataType_>::set_volume(DataType_ volume)\n  {\n    this->volume = volume;\n  }\n  \n  template<typename DataType_>\n  DataType_ CachedCosinusGeneratorFilter<DataType_>::get_volume() const\n  {\n    return volume;\n  }\n  \n  template<typename DataType_>\n  void CachedCosinusGeneratorFilter<DataType_>::set_offset(DataType_ offset)\n  {\n    this->offset = offset;\n  }\n  \n  template<typename DataType_>\n  DataType_ CachedCosinusGeneratorFilter<DataType_>::get_offset() const\n  {\n    return offset;\n  }\n\n  template<typename DataType_>\n  void CachedCosinusGeneratorFilter<DataType_>::setup()\n  {\n    indice = 0;\n    cache.resize(output_sampling_rate * seconds);\n    for(gsl::index i = 0; i < cache.size(); ++i)\n    {\n      cache[i] = static_cast<DataType>(std::cos(2 * boost::math::constants::pi<double>() * (i+1) * periods / seconds / output_sampling_rate));\n    }\n  }\n\n  template<typename DataType_>\n  void CachedCosinusGeneratorFilter<DataType_>::process_impl(gsl::index size) const\n  {\n    DataType* ATK_RESTRICT output = outputs[0];\n    gsl::index processed = 0;\n    while(processed < size)\n    {\n      auto to_copy = std::min(size - processed, static_cast<gsl::index>(cache.size()) - indice);\n      memcpy(reinterpret_cast<void*>(output + processed), reinterpret_cast<const void*>(cache.data() + indice), to_copy * sizeof(DataType_));\n      indice += to_copy;\n      processed += to_copy;\n      if(indice >= cache.size())\n      {\n        indice = 0;\n      }\n    }\n    for(gsl::index i = 0; i < size; ++i)\n    {\n      output[i] = static_cast<DataType>(offset + volume * output[i]);\n    }\n  }\n  \n#if ATK_ENABLE_INSTANTIATION\n  template class CachedCosinusGeneratorFilter<float>;\n#endif\n  template class CachedCosinusGeneratorFilter<double>;\n}\n", "meta": {"hexsha": "e5018c49dcdb91408c962290282cd29b3b164e0e", "size": 2674, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ATK/Tools/CachedCosinusGeneratorFilter.cpp", "max_stars_repo_name": "AudioTK/AudioTK", "max_stars_repo_head_hexsha": "dba42eea68534501efe74692b74edf4792cca231", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2021-02-04T10:47:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T03:45:00.000Z", "max_issues_repo_path": "ATK/Tools/CachedCosinusGeneratorFilter.cpp", "max_issues_repo_name": "AudioTK/AudioTK", "max_issues_repo_head_hexsha": "dba42eea68534501efe74692b74edf4792cca231", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-02-01T15:45:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-13T19:39:05.000Z", "max_forks_repo_path": "ATK/Tools/CachedCosinusGeneratorFilter.cpp", "max_forks_repo_name": "AudioTK/AudioTK", "max_forks_repo_head_hexsha": "dba42eea68534501efe74692b74edf4792cca231", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-04-12T03:28:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-17T00:47:11.000Z", "avg_line_length": 26.4752475248, "max_line_length": 142, "alphanum_fraction": 0.6907255049, "num_tokens": 660, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956580903722561, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4834921172987905}}
{"text": "/*    Copyright (c) 2010-2015, Delft University of Technology\r\n *    All rights reserved.\r\n *\r\n *    Redistribution and use in source and binary forms, with or without modification, are\r\n *    permitted provided that the following conditions are met:\r\n *      - Redistributions of source code must retain the above copyright notice, this list of\r\n *        conditions and the following disclaimer.\r\n *      - Redistributions in binary form must reproduce the above copyright notice, this list of\r\n *        conditions and the following disclaimer in the documentation and/or other materials\r\n *        provided with the distribution.\r\n *      - Neither the name of the Delft University of Technology nor the names of its contributors\r\n *        may be used to endorse or promote products derived from this software without specific\r\n *        prior written permission.\r\n *\r\n *    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS\r\n *    OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\r\n *    MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\r\n *    COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\r\n *    EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\r\n *    GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\r\n *    AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\r\n *    NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\r\n *    OF THE POSSIBILITY OF SUCH DAMAGE.\r\n *\r\n *    Changelog\r\n *      YYMMDD    Author            Comment\r\n *      140110    S. Hirsh          File created.\r\n *      140220    T. Roegiers       Small changes during codecheck.\r\n *\r\n *    References\r\n *    Hameduddin, I. Rotate vector(s) about axis, rodrigues_rot.m, available at\r\n *        http://www.mathworks.com/matlabcentral/fileexchange/34426-rotate-vectors-about-axis,\r\n *        2012, last accessed: 11th January, 2014.\r\n *    Murray, G. Rotation Matrices and Formulas java script, RotationMatrix.java available at\r\n *        https://sites.google.com/site/glennmurray/Home/rotation-matrices-and-formulas, 2011.\r\n *        last accessed: 20th January, 2014.\r\n *\r\n *    Notes\r\n *\r\n */\r\n\r\n#define BOOST_TEST_MAIN\r\n\r\n#include <boost/test/floating_point_comparison.hpp>\r\n#include <boost/test/unit_test.hpp>\r\n\r\n#include <Eigen/Core>\r\n\r\n#include \"Tudat/Basics/testMacros.h\"\r\n#include \"Tudat/Mathematics/BasicMathematics/mathematicalConstants.h\"\r\n\r\n#include \"Tudat/Mathematics/BasicMathematics/rotationAboutArbitraryAxis.h\"\r\n\r\nnamespace tudat\r\n{\r\nnamespace unit_tests\r\n{\r\n\r\n//! Test suite for rotations about about arbitrary axes.\r\nBOOST_AUTO_TEST_SUITE( test_RotationAboutArbitraryAxis )\r\n\r\nBOOST_AUTO_TEST_CASE( test_RotationAboutArbitraryAxis_PointRotationWithCommonOrigin )\r\n{\r\n\r\n    //Benchmark data is obtained using Matlab Script (Hameduddin, 2012).\r\n\r\n    //Set expected rotated vector.\r\n    const Eigen::Vector3d expectedRotatedPosition = Eigen::Vector3d( 0.0, 1.414213562373095, 1.0 );\r\n\r\n    //Set origin of rotation.\r\n    const Eigen::Vector3d originOfRotation = Eigen::Vector3d( 0.0, 0.0, 0.0 );\r\n\r\n    //Set angle of rotation [rad].\r\n    const double angleOfRotation = mathematical_constants::PI / 4.0;\r\n\r\n    //Set axis of rotation.\r\n    const Eigen::Vector3d axisOfRotation = Eigen::Vector3d( 0.0, 0.0, 1.0 );\r\n\r\n    //Set initial position of point.\r\n    const Eigen::Vector3d initialPositionOfPoint = Eigen::Vector3d( 1.0, 1.0, 1.0 );\r\n\r\n    //Compute rotated position.\r\n    const Eigen::Vector3d computedRotatedPosition = basic_mathematics::\r\n        computeRotationOfPointAboutArbitraryAxis( originOfRotation, angleOfRotation,\r\n                                                  axisOfRotation, initialPositionOfPoint );\r\n\r\n    // Compare computed and expected vectors.\r\n    BOOST_CHECK_SMALL( computedRotatedPosition.x( ), std::numeric_limits< double >::epsilon( ) );\r\n\r\n    TUDAT_CHECK_MATRIX_CLOSE_FRACTION( computedRotatedPosition.segment( 1, 2 ),\r\n                                       expectedRotatedPosition.segment( 1, 2),\r\n                                       std::numeric_limits< double >::epsilon( ) );\r\n\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE( test_RotationAboutArbitraryAxis_PointRotationWithDifferentOrigins )\r\n{\r\n\r\n    //Benchmark data is obtained using java script (Murray, 2013).\r\n\r\n    //Set expected rotated vector.\r\n    const Eigen::Vector3d expectedRotatedPosition = Eigen::Vector3d( 3.156561876696307,\r\n                                                                     -5.97145870839039,\r\n                                                                     -4.418680390057799 );\r\n    //Set origin of rotation.\r\n    const Eigen::Vector3d originOfRotation = Eigen::Vector3d( 4.0, 1.0, -1.0 );\r\n\r\n    //Set angle of rotation [rad]\r\n    const double angleOfRotation = 7.0;\r\n\r\n    //Set axis of rotation.\r\n    const Eigen::Vector3d axisOfRotation = Eigen::Vector3d( 2.0, -2.0, 3.0 );\r\n\r\n    //Set initial position of point.\r\n    const Eigen::Vector3d initialPositionOfPoint = Eigen::Vector3d( -1.0, -5.0, -1.0 );\r\n\r\n    //Compute rotated position.\r\n    const Eigen::Vector3d computedRotatedPosition = basic_mathematics::\r\n        computeRotationOfPointAboutArbitraryAxis( originOfRotation,  angleOfRotation,\r\n                                                  axisOfRotation, initialPositionOfPoint );\r\n\r\n    // Compare computed and expected radiation pressure acceleration vectors.\r\n    TUDAT_CHECK_MATRIX_CLOSE_FRACTION( computedRotatedPosition,\r\n                                       expectedRotatedPosition,\r\n                                       std::numeric_limits<double>::epsilon( ) );\r\n\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE( test_RotationAboutArbitraryAxis_PointRotationWithDifferentOrigins2 )\r\n{\r\n\r\n    //Benchmark data is obtained using java script (Murray, 2013).\r\n\r\n    //Set expected rotated vector.\r\n    const Eigen::Vector3d expectedRotatedPosition = Eigen::Vector3d( 15.71267522236938,\r\n                                                                     -0.9723168350942417,\r\n                                                                      9.449538267504582 );\r\n    //Set origin of rotation.\r\n    const Eigen::Vector3d originOfRotation = Eigen::Vector3d( 1.5, 3.8, 12.0 );\r\n\r\n    //Set angle of rotation [rad]\r\n    const double angleOfRotation = 3.0;\r\n\r\n    //Set axis of rotation.\r\n    const Eigen::Vector3d axisOfRotation = Eigen::Vector3d( -4.6, 6.75, 7.7 );\r\n\r\n    //Set initial position of point.\r\n    const Eigen::Vector3d initialPositionOfPoint = Eigen::Vector3d( -4.3, -5.2, 1.2 );\r\n\r\n    //Compute rotated position.\r\n    const Eigen::Vector3d computedRotatedPosition = basic_mathematics::\r\n        computeRotationOfPointAboutArbitraryAxis( originOfRotation, angleOfRotation,\r\n                                                  axisOfRotation, initialPositionOfPoint );\r\n\r\n    // Compare computed and expected radiation pressure acceleration vectors.\r\n    TUDAT_CHECK_MATRIX_CLOSE_FRACTION( computedRotatedPosition, expectedRotatedPosition, 1.0e-14 );\r\n\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE( test_RotationAboutArbitraryAxis_VectorRotationWithCommonOrigin )\r\n{\r\n\r\n    //Benchmark data is obtained using Matlab Script (Hameduddin, 2012).\r\n\r\n    //Set expected rotated vector.\r\n    const Eigen::Vector3d expectedRotatedVector = Eigen::Vector3d( -5.480598288892924,\r\n                                                                    0.532794739754852,\r\n                                                                    6.138336269794405 );\r\n    //Set origin of rotation.\r\n    const Eigen::Vector3d originOfRotation = Eigen::Vector3d( 0.0, 0.0, 0.0 );\r\n\r\n    //Set angle of rotation [rad].\r\n    const double angleOfRotation = 12.0;\r\n\r\n    //Set axis of rotation.\r\n    const Eigen::Vector3d axisOfRotation = Eigen::Vector3d( -1.0, -2.0, -3.0 );\r\n\r\n    //Set initial position of vector tail.\r\n    const Eigen::Vector3d initialPositionOfVectorTail = Eigen::Vector3d( 1.0, 3.0, 5.0 );\r\n\r\n    //Set initial vector.\r\n    const Eigen::Vector3d initialVector = Eigen::Vector3d( -6.0, 4.0, 4.0 );\r\n\r\n    //Compute rotated position.\r\n    const Eigen::Vector3d computedRotatedVector = basic_mathematics::\r\n        computeRotationOfVectorAboutArbitraryAxis( originOfRotation, angleOfRotation,\r\n                                                   axisOfRotation, initialPositionOfVectorTail,\r\n                                                   initialVector );\r\n\r\n    // Compare computed and expected radiation pressure acceleration vectors\r\n    TUDAT_CHECK_MATRIX_CLOSE_FRACTION( computedRotatedVector, expectedRotatedVector, 1.0e-14 );\r\n\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE( test_RotationAboutArbitraryAxis_VectorRotationWithDifferentOrigins )\r\n{\r\n\r\n    //Benchmark data is obtained using java script (Murray, 2013).\r\n\r\n    //Set expected rotated vector.\r\n    const Eigen::Vector3d expectedRotatedVector = Eigen::Vector3d( -7.15233485964669,\r\n                                                                   -2.4444137866784175,\r\n                                                                    8.308967883857736 );\r\n    //Set origin of rotation.\r\n    const Eigen::Vector3d originOfRotation = Eigen::Vector3d( 1.5, 3.8, 12.0 );\r\n\r\n    //Set angle of rotation [rad].\r\n    const double angleOfRotation = 3.0;\r\n\r\n    //Set axis of rotation.\r\n    const Eigen::Vector3d axisOfRotation = Eigen::Vector3d( -4.6, 6.75, 7.7 );\r\n\r\n    //Set initial position of vector tail.\r\n    const Eigen::Vector3d initialPositionOfVectorTail = Eigen::Vector3d( -4.3, -5.2, 1.2 );\r\n\r\n    //Set initial vector.\r\n    const Eigen::Vector3d initialVector = Eigen::Vector3d( 0.3, 11.2, 0.8 );\r\n\r\n    //Compute rotated position.\r\n    const Eigen::Vector3d computedRotatedVector = basic_mathematics::\r\n        computeRotationOfVectorAboutArbitraryAxis( originOfRotation, angleOfRotation,\r\n                                                   axisOfRotation, initialPositionOfVectorTail,\r\n                                                   initialVector );\r\n\r\n  // Compare computed and expected rotated vectors.\r\n  TUDAT_CHECK_MATRIX_CLOSE_FRACTION( computedRotatedVector, expectedRotatedVector, 1.0e-14 );\r\n\r\n}\r\n\r\nBOOST_AUTO_TEST_SUITE_END( )\r\n\r\n} // namespace unit_tests\r\n} // namespace tudat\r\n", "meta": {"hexsha": "3c7d6d63fa41c28b7c386dca08fe2dfa96c61934", "size": 10389, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Mathematics/BasicMathematics/UnitTests/unitTestRotationAboutArbitraryAxis.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/UnitTests/unitTestRotationAboutArbitraryAxis.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/UnitTests/unitTestRotationAboutArbitraryAxis.cpp", "max_forks_repo_name": "JPelamatti/ThesisTUDAT", "max_forks_repo_head_hexsha": "b94ce35fb7c8fa44ae83238e296a979dfa3adfe8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-05-30T03:42:22.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-30T03:42:22.000Z", "avg_line_length": 44.3974358974, "max_line_length": 100, "alphanum_fraction": 0.6474155357, "num_tokens": 2403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646010190475, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.4834582151702931}}
{"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\u00c3\u00a4nkt), 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// #define MTL_VERBOSE_TEST\n#define MTL_HAS_STD_OUTPUT_OPERATOR\n\n#include <boost/numeric/mtl/mtl.hpp>\n\ntemplate <typename Matrix>\ninline void fill_matrix(Matrix& A)\n{\n    mtl::mat::inserter<Matrix> ins(A, 3);\n    ins[0][0] << 2;\n    ins[0][1] << 9;\n    ins[1][1] << 1;\n    ins[1][2] << 5;\n    ins[1][3] << 5;\n    ins[1][4] << 1;\n    ins[2][2] << 6;\n    ins[2][3] << 9;\n    ins[3][2] << 2;\n    ins[3][3] << 4;\n    ins[4][0] << 7;\n    ins[4][4] << 3;\n}\n\nint main(int, char**)\n{\n    using namespace mtl;\n    using mtl::io::tout;\n    typedef mtl::dense_vector<double>         vector_type;\n    typedef mtl::mat::ell_matrix<double>   matrix_type;\n    matrix_type   A(5, 5);\n\n    fill_matrix(A);\n\n    tout << \"A (internal)\\n\";\n    A.print_internal(tout);\n\n    tout << \"A[2][3] = \" << A[2][3] << '\\n';\n    tout << \"A[2][4] = \" << A[2][4] << '\\n';\n    tout << \"A[2][0] = \" << A[2][0] << '\\n';\n\n    MTL_THROW_IF(A[2][3] != 9.0, unexpected_result());\n    MTL_THROW_IF(A[2][4] != 0.0, unexpected_result());\n    MTL_THROW_IF(A[2][0] != 0.0, unexpected_result());\n\n    tout << \"A =\\n\" << A;\n    tout << \"nnz = \" << A.nnz() << std::endl;\n\n    mtl::compressed2D<double> B(5, 5);\n    fill_matrix(B);\n    tout << \"B =\\n\" << B;\n    MTL_THROW_IF(A.nnz() != B.nnz(), unexpected_result());\n    \n    vector_type res(5), res2(5), x(5);\n    iota(x, 1);\n    res2= B * x;\n    tout << \"B * x = \" << res2 << '\\n';\n    \n    res= A * x;\n    tout << \"A * x =\\n\" << res << '\\n';\n\n    res2-= res;\n    MTL_THROW_IF(two_norm(res2) > 0.001, unexpected_result());\n\n    matrix_type C;\n    laplacian_setup(C, 3, 4);\n    tout << \"C =\\n\" << C << '\\n';\n\n    // lazy(res2)= B * res;\n    // lazy(res2)= A * res;\n\n    // std::cout << \"index_evaluatable<CRS ...> is \" << mtl::traits::index_evaluatable<lazy_assign<vector_type, mtl::mat_cvec_times_expr<mtl::compressed2D<double>, vector_type>, int> >::value << '\\n';\n    // std::cout << \"index_evaluatable<Ell ...> is \" << mtl::traits::index_evaluatable<lazy_assign<vector_type, mtl::mat_cvec_times_expr<matrix_type, vector_type>, int> >::value << '\\n';\n\t\n    return 0;\n}\n", "meta": {"hexsha": "452425646703dda492355b08abe81db7865d849c", "size": 2520, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/ell_matrix_test.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/mtl/test/ell_matrix_test.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/mtl/test/ell_matrix_test.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 28.6363636364, "max_line_length": 200, "alphanum_fraction": 0.5623015873, "num_tokens": 874, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154240079185319, "lm_q2_score": 0.6757645944891558, "lm_q1q2_score": 0.4834582145988733}}
{"text": "//////////////////////////////////////////////////////////////////////////////\n// random::poisson::devroye::q::lemma1.hpp                        \t        //\n//                                                                          //\n//  (C) Copyright 2010 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_RANDOM_POISSON_EXT_DEVROYE_Q_LEMMA1_HPP_ER_2010\n#define BOOST_RANDOM_POISSON_EXT_DEVROYE_Q_LEMMA1_HPP_ER_2010\n#include <string>\n#include <boost/format.hpp>\n\nnamespace boost{\nnamespace random{\nnamespace poisson{\nnamespace devroye{            \nnamespace q{\nnamespace lemma1{\n\n    // Lemma 1, p.199\n    // q(y) < upper_bound(y), if y >= -mean\n    template<typename T,typename Int,typename IntT>\n    T upper_bound(const Int& i_mean,const Int& i_y,const IntT& converter)\n    {\n        T z = IntT::convert( 0 );\n        T y = IntT::convert( i_y );\n        T yp1 = IntT::convert( i_y +1 );\n        T pos_y = IntT::convert( i_y < 0 ? z : y );\n        T num = ( - y * yp1 );\n        T den = IntT::convert( 2 * i_mean ) + pos_y;\n        return num / den;\n    }\n\n    template<typename T,typename Int,typename IntT>\n    bool do_raise_error(const T& q,const T& tol,std::string& str,\n        const Int& i_mean,const Int& i_y,const IntT& converter)\n    {\n        T ub1 = lemma1::upper_bound<T>(i_mean,i_y,converter);\n        if( q > ( tol + ub1 ) ){\n            std::string msg = \" [ lemma1 : q = %1% < %2% has failed ]\";\n            boost::format f( msg ); f % q % ub1; \n            str += f.str();\n            return true;\n        }else{\n            return false;\n        }\n    }\n\n}// lemma1\n}// q\n}// devroye\n}// poisson\n}// random\n}// boost\n\n#endif\n", "meta": {"hexsha": "697ea75b2b66ba0bc85bbb6ad76cabd1f34b35c7", "size": 1983, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "random/boost/random/poisson_ext/devroye/q_function/lemma1.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": "random/boost/random/poisson_ext/devroye/q_function/lemma1.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": "random/boost/random/poisson_ext/devroye/q_function/lemma1.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": 34.1896551724, "max_line_length": 78, "alphanum_fraction": 0.494200706, "num_tokens": 496, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239836484144, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.48345821221291047}}
{"text": "#include <vsim/env/camera.hpp>\n\n#include <iostream>\n#include <fstream>\n\n#include <Eigen/Geometry>\n\n\nusing namespace std ;\nusing namespace Eigen ;\n\nnamespace vsim {\n\n\nEigen::Matrix4f PerspectiveCamera::projectionMatrix() const {\n    assert(abs(aspect_ - std::numeric_limits<float>::epsilon()) > static_cast<float>(0));\n\n    float xfov = aspect_ * yfov_ ;\n    float const d = 1/tan(xfov / static_cast<float>(2));\n\n    Matrix4f result ;\n    result.setZero() ;\n\n    result(0, 0) = d / aspect_ ;\n    result(1, 1) = d ;\n    result(2, 2) =  (zfar_ + znear_) / (znear_ - zfar_);\n    result(2, 3) =  2 * zfar_ * znear_ /(znear_ - zfar_) ;\n    result(3, 2) = -1 ;\n\n    return result;\n}\n\n\nvoid Camera::lookAt(const Vector3f &eye, const Vector3f &center, const Vector3f &up) {\n    Vector3f f = (center - eye).normalized();\n    Vector3f s = f.cross(up).normalized();\n    Vector3f u = s.cross(f) ;\n\n    mat_ << s.x(), s.y(), s.z(), -s.dot(eye),\n            u.x(), u.y(), u.z(), -u.dot(eye),\n            -f.x(), -f.y(), -f.z(), f.dot(eye),\n            0, 0, 0, 1 ;\n}\n\nvoid Camera::lookAt(const Vector3f &eye, const Vector3f &center, float roll) {\n    lookAt(eye, center, Vector3f(0, 1, 0)) ;\n\n    Affine3f rot ;\n    rot.setIdentity();\n    rot.rotate(AngleAxisf(roll, Eigen::Vector3f::UnitZ())) ;\n    mat_ = mat_ * rot.matrix() ;\n}\n\n\n}\n", "meta": {"hexsha": "13affe8c8735d13984d586e28cdd4515b412c815", "size": 1320, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/env/camera.cpp", "max_stars_repo_name": "malasiot/vsim", "max_stars_repo_head_hexsha": "2a69e27364bab29194328af3d050e34f907e226b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/env/camera.cpp", "max_issues_repo_name": "malasiot/vsim", "max_issues_repo_head_hexsha": "2a69e27364bab29194328af3d050e34f907e226b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/env/camera.cpp", "max_forks_repo_name": "malasiot/vsim", "max_forks_repo_head_hexsha": "2a69e27364bab29194328af3d050e34f907e226b", "max_forks_repo_licenses": ["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.5714285714, "max_line_length": 89, "alphanum_fraction": 0.5893939394, "num_tokens": 429, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239836484143, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.4834582122129104}}
{"text": "#define DEBUG 1\n\n#include <iostream>\n#include <iomanip>\n#include <string>\n//#include <cmath>\n#include \"Hubbard2D.hpp\"\n\n#ifdef USE_SPECTRA\n#include <MatOp/SparseGenMatProd.h>\n#include <SymEigsSolver.h>\n#endif\n\n#include <boost/random.hpp>\n#include <boost/limits.hpp>\n#include <ietl/interface/eigen3.h>\n#include <ietl/vectorspace.h>\n#include <ietl/lanczos.h>\n\n///check if a file exists\nbool fileExists(const std::string& fname){\n  std::ifstream f(fname.c_str());\n  bool isGood = f.good();\n  f.close();\n  return isGood;\n}\n\nint main(int argc, const char * argv[]) {\n  int ne; //# of electrons\n  double U;\n\n  if(argc == 1){\n    std::cerr<<\"Using all defaults\"<<std::endl;\n    ne=2; //# of electrons\n    U=4;\n  }\n  else if(argc >5 || (argc-1)%2){\n    std::cout<<\"Wrong input format!\"<<std::endl;\n    std::cout<<\"-ne [#num electrons] -U [# for U/t]\"<<std::endl;\n    return 1;\n  }\n  else{\n    ne=2;\n    U=4;\n    for(int i=1;i<argc;i+=2){\n     if(std::string(argv[i]) == \"-ne\")\n       ne = std::atoi(argv[i+1]);\n     if(std::string(argv[i]) == \"-U\")\n       U = std::atof(argv[i+1]);\n    }\n  }\n  std::cout << \"2D \"<<BASISSIZE/2<<\" site Hubbard model with \"\n  << ne <<\" up/down electrons and U/t=\"<<U<<std::endl;\n\n\n  HubbardModel2D H(ne,ne,1,U);\n  H.makeBasis();\n  std::cout <<\"Made Basis: \" << H.getBasis()->size()<< std::endl;\n\n  H.buildHubbard2D();\n  std::cout <<\"Built Matrix\" << std::endl;\n  SpMat Hmat = *(H.getH());\n  std::cout << \"# of non-zero elements:\"<<(H.getH())->nonZeros() << std::endl;\n  H.getH()->makeCompressed();\n\n  std::ofstream outfile;\n  if(fileExists(\"energies.dat\")){\n    outfile.open(\"energies.dat\",std::ofstream::out |std::ofstream::app);\n  }\n  else{\n     outfile.open(\"energies.dat\",std::ofstream::out |std::ofstream::app);\n     outfile<<\"#ne U E0\"<<std::endl;\n  }\n  outfile << std::setprecision(9);\n\n  std::ofstream outfile_v;\n  if(fileExists(\"ketvals.dat\")){\n    outfile_v.open(\"ketvals.dat\",std::ofstream::out |std::ofstream::app);\n  }\n  else{\n    outfile_v.open(\"ketvals.dat\",std::ofstream::out |std::ofstream::app);\n    outfile_v <<\"#ne U dbl up|down antiferro\"<<std::endl;\n  }\n  outfile_v << std::setprecision(9);\n\n  //construct test states\n  size_t spinOffset = BASISSIZE/2;\n\n  lattice_t psi1;\n  int i;\n  for(i=0;i<ne;i++)\n    psi1[i].flip();\n\n  for(i=0;i<ne;i++)\n    psi1[(i+spinOffset)%(BASISSIZE)].flip();\n\n  lattice_t psi2;\n  i=0;\n\n  for(i=0;i<ne;i++)\n    psi2[i].flip();\n\n  for(i=0;i<ne;i++)\n    psi2[(i+ne+spinOffset)%(BASISSIZE)].flip();\n  \n  lattice_t psi3;\n  i=0;\n  for(i=0;i<ne;i++)\n    psi3[2*i].flip();\n  for(i=0;i<ne;i++)\n    psi3[(2*i+1+spinOffset)%(BASISSIZE)].flip();\n  //std::cout<<psi1<<std::endl;\n  //std::cout<<psi2<<std::endl;\n  //std::cout<<psi3<<std::endl;\n\n  std::string double_occ=\"|\";\n  for(i=0;i<ne;i++)\n    double_occ+=\"\u2191\u2193|\";\n  std::string not_occ=\"|\";\n  for(i=0;i<ne;i++)\n    not_occ+=\"\u2191|\";\n  for(i=0;i<ne;i++)\n    not_occ+=\"\u2193|\";\n  std::string antiferro=\"|\";\n  for(i=0;i<ne;i++)\n    antiferro+=\"\u2191|\u2193|\";\n\n  //**************************************\n  //        generate eigenvalues\n  //**************************************\n\n  //Diag with specrta\n#ifdef USE_SPECTRA\n  // Construct matrix operation object using the wrapper class SparseGenMatProd\n  using wrapper_t =Spectra::SparseGenMatProd<double,Eigen::RowMajor,long>;\n  wrapper_t op(Hmat);\n  \n  // Construct eigen solver object, requesting the smallest eigenvalue\n  Spectra::SymEigsSolver< double, Spectra::SMALLEST_ALGE , wrapper_t > eigs(&op, 1, 6);\n  // Initialize and compute\n  eigs.init();\n  int nconv = eigs.compute();\n  \n#ifdef DEBUG\n  if(eigs.info() != Spectra::SUCCESSFUL)\n      std::cout <<\"Warning something failed \" <<nconv << std::endl;\n#endif\n\n  std::cout<< \"E0=\"<<eigs.eigenvalues()[0]<<std::endl;\n\n  std::cout<<double_occ<<\" :\"<<eigs.eigenvectors()(H.getState(psi1),0)<<std::endl; //psi1\n  std::cout<<not_occ<<\" :\"<<eigs.eigenvectors()(H.getState(psi2),0)<<std::endl; //psi2\n#else\n  typedef boost::lagged_fibonacci607 Gen;\n  Gen mygen;\n  mygen.seed(0);\n  \n  typedef Eigen::SparseMatrix<double,Eigen::RowMajor,long> Matrix;\n  typedef Eigen::VectorXd Vector;\n  typedef ietl::vectorspace<Vector> Vecspace;\n   \n   \n   \n  // Creation of an iteration object:\n  int max_iter = 10*H.getBasis()->size();\n  double rel_tol = 500*std::numeric_limits<double>::epsilon();\n  double abs_tol = std::pow(std::numeric_limits<double>::epsilon(),2./3);\n  int n_lowest_eigenval = 1;\n  std::vector<double> eigen;\n  std::vector<double> err;\n  std::vector<int> multiplicity;\n\n  std::vector<double> groundStates;\n\n  Vecspace vec(Hmat.cols());\n  ietl::lanczos<Matrix,Vecspace> lanczos(Hmat,vec);\n  ietl::lanczos_iteration_nlowest<double>\n  iter(max_iter, n_lowest_eigenval, rel_tol, abs_tol);\n  std::cout << \"Running lanczos\" << std::endl;\n  try{\n    lanczos.calculate_eigenvalues(iter,mygen);\n    eigen = lanczos.eigenvalues();\n    err = lanczos.errors();\n    multiplicity = lanczos.multiplicities();\n    std::cout<<\"number of iterations: \"<<iter.iterations()<<\"\\n\";\n    groundStates.push_back(eigen[0]);\n  }\n  catch (std::runtime_error& e) {\n    std::cout << e.what() << \"\\n\";\n  }\n  std::cout << \"#        eigenvalue            error         multiplicity\\n\";\n  for (int i=0;i<10;++i)\n    std::cout << i+1 << \"\\t\" << eigen[i] << \"\\t\" << err[i] << \"\\t\"\n    << multiplicity[i] << \"\\n\";\n\n  outfile<<ne<<\" \" <<U<< \" \"<< groundStates[0]<<std::endl;\n  //**************************************\n  //        generate eigenvectors\n  //**************************************\n  // call of eigenvectors function follows:\n  std::cout << \"\\nHead of Eigenvector for the lowest eigenvalue:\\n\\n\";\n  std::vector<double>::iterator start = eigen.begin();\n  std::vector<double>::iterator end = eigen.begin()+1;\n  std::vector<Vector> eigenvectors; // for storing the eigen vectors.\n  ietl::Info<double> info; // (m1, m2, ma, eigenvalue, residualm, status).\n\n  try {\n    lanczos.eigenvectors(start,end,std::back_inserter(eigenvectors),info,mygen,max_iter);\n  }\n  catch (std::runtime_error& e) {\n    std::cout << e.what() << \"\\n\";\n  }\n  std::cout << eigenvectors[0].head(10)<<std::endl;\n  std::cout << \"Information about the eigenvector computations:\\n\\n\";\n  for(int i = 0; i < info.size(); i++) {\n    std::cout << \" m1(\" << i+1 << \"): \" << info.m1(i) << \", m2(\" << i+1 << \"): \"\n    << info.m2(i) << \", ma(\" << i+1 << \"): \" << info.ma(i) << \" eigenvalue(\"\n    << i+1 << \"): \" << info.eigenvalue(i) << \" residual(\" << i+1 << \"): \"\n    << info.residual(i) << \" error_info(\" << i+1 << \"): \"\n    << info.error_info(i) << \"\\n\\n\";\n  }\n\n  std::cout<<double_occ<<\" :\"<<eigenvectors[0](H.getState(psi1))<<std::endl; //psi1\n  std::cout<<not_occ<<\" :\"<<eigenvectors[0](H.getState(psi2))<<std::endl; //psi2\n  std::cout<<antiferro<<\" :\"<<eigenvectors[0](H.getState(psi3))<<std::endl; //psi3\n\n  outfile_v << ne << \" \"<<U<<\" \" << eigenvectors[0](H.getState(psi1)) << \" \" \n            <<eigenvectors[0](H.getState(psi2))<<\" \" <<eigenvectors[0](H.getState(psi3))<<std::endl;\n#endif\n\n  return 0;\n}\n", "meta": {"hexsha": "45c930af01e4a9234c32110f2dbe1e9ea0c83c9a", "size": 6947, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "qftphys/A-Slow-Exact-Diagonalization-for-the-1D-2D-Hubbard-Model", "max_stars_repo_head_hexsha": "c8352681036e93fb83a56374c639075fea72e3af", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2019-05-26T13:32:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T06:58:54.000Z", "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "qftphys/A-Slow-Exact-Diagonalization-for-the-1D-2D-Hubbard-Model", "max_issues_repo_head_hexsha": "c8352681036e93fb83a56374c639075fea72e3af", "max_issues_repo_licenses": ["MIT"], "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": "qftphys/A-Slow-Exact-Diagonalization-for-the-1D-2D-Hubbard-Model", "max_forks_repo_head_hexsha": "c8352681036e93fb83a56374c639075fea72e3af", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-08-08T04:17:24.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-13T08:13:10.000Z", "avg_line_length": 29.8154506438, "max_line_length": 100, "alphanum_fraction": 0.5936375414, "num_tokens": 2203, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239836484143, "lm_q2_score": 0.6757645879592642, "lm_q1q2_score": 0.48345819352634606}}
{"text": "#include \"fast_particle_slam.h\"\n#include \"robot_configuration.h\"\n#include \"error_handling.h\"\n#include \"occupancy_grid.inl\"\n\n#include <boost/range/algorithm/max_element.hpp>\n#include <boost/range/adaptor/transformed.hpp>\n\n#include <opencv2/imgproc.hpp>\n#include <iostream>\n#include <random>\n#include <future>\n\n// Based on Grisetti, Stachniss, Burgard \n// \"Improving Grid-based SLAM with Rao-Blackwellized Particle Filters by Adaptive Proposals and Selective Resampling\"\n// and their implementation at https://openslam.org/gmapping.html\nSFastSlamParticle::SFastSlamParticle() : m_pose(rbt::pose<double>::zero()) {}\n\nvoid SFastSlamParticle::updatePose(SScanLine const& scanline) {\n    // 1. Update particles with probabilistic motion model\n    auto poseSampled = sample_motion_model(m_pose, scanline.translation(), scanline.rotation());\n\n    // 2. If not first update (and optionally: enough distance traveled since last update)\n    //    scan match and update particle pose\n    m_pose = m_occgrid.fit(poseSampled, scanline);\n    \n    // 3. Compute likelihood of resulting match\n    // gmapping computes log likelihood, also skips distanceTransform and searches\n    // in small kernel around expected obstacle\n    m_fLogWeight += log_likelihood_field(m_pose, scanline, m_occgrid);\n    \n    LOG(\"Update Particle: poseSampled = \" << poseSampled << \" m_pose = \" << m_pose << \" m_fLogWeight = \" << m_fLogWeight << \"\\n\");\n}\n\nvoid SFastSlamParticle::updateMap(SScanLine const& scanline) {\n    boost::for_each(scanline.m_vecscan, [&](auto const& scan) {\n        m_occgrid.update(m_pose, scan.m_fRadAngle, scan.m_nDistance);\n    });\n}\n\nCFastParticleSlamBase::CFastParticleSlamBase(int cParticles) \n    : m_vecparticle(cParticles), m_itparticleBest(m_vecparticle.begin()), m_fNEff(1.0)\n{}\n\nstatic std::random_device s_rd;\nvoid CFastParticleSlamBase::receivedSensorData(SScanLine const& scanline) {\n     LOG(\"=== Update === \");\n     LOG(\"t = \" << scanline.translation() << \" phi = \" << scanline.rotation());\n    \n    {\n        std::vector<std::future<void>> vecfuture;\n        boost::for_each(m_vecparticle, [&](auto& p) {\n            vecfuture.emplace_back( \n                std::async(std::launch::async,\n                    [&] {\n                        p.updatePose(scanline);\n                    }\n                ));\n        });\n    }\n\n    // 4. Normalize weights (see GridSlamProcessor::normalize())\n    {\n        // TODO: m_obsSigmaGain\n        double const fGain = 1. / ( 3 * /* = m_obsSigmaGain */ m_vecparticle.size());\n        auto const fMax = *boost::max_element(boost::adaptors::transform(m_vecparticle, std::mem_fn(&SFastSlamParticle::m_fLogWeight)));\n        \n        double fWeightSum = 0;\n        boost::for_each(m_vecparticle, [&](auto& p) {\n            p.m_fWeight = std::exp(fGain * (p.m_fLogWeight - fMax));\n            fWeightSum += p.m_fWeight;\n        });\n        \n        m_fNEff = 0;\n        boost::for_each(m_vecparticle, [&](auto& p) {\n            p.m_fWeight /= fWeightSum;\n            m_fNEff += p.m_fWeight*p.m_fWeight;\n        });\n        m_fNEff = 1.0 / m_fNEff;\n    }\n\n    // 5. If neff < threshold, resample\n    if(m_fNEff<0.5 * m_vecparticle.size()) {\n        LOG(\"============ Resample ============\");\n        // Resampling\n        // Thrun, Probabilistic robotics, p. 110\n        auto const fStepSize = 1.0/m_vecparticle.size();\n        auto const r = std::uniform_real_distribution<double>(0.0, fStepSize)(s_rd);\n        auto c = m_vecparticle.front().m_fWeight;\n\n        std::vector<int> veciparticle;\n        for(int i = 0, m = 0; m<m_vecparticle.size(); ++m) {\n            auto const u = r + m * fStepSize;\n            while(c<u) {\n                ++i;\n                c += m_vecparticle[i].m_fWeight;\n            }\n            veciparticle.emplace_back(i);\n            LOG(\"Keep particle \" << i);\n        }\n        \n        std::vector<SFastSlamParticle> vecparticle(m_vecparticle.size());\n        auto itparticleOut = vecparticle.begin();\n        for(auto itn = veciparticle.begin(); itn!=veciparticle.end(); ++itn) {\n            if(boost::next(itn)==veciparticle.end() || *itn!=*boost::next(itn)) {\n                *itparticleOut = std::move(m_vecparticle[*itn]);\n            } else {\n                *itparticleOut = m_vecparticle[*itn];\n            }\n            itparticleOut->m_fLogWeight = 0.0;\n            ++itparticleOut;\n        }\n        std::swap(m_vecparticle, vecparticle);\n    }\n    \n    m_itparticleBest = boost::max_element(\n        boost::adaptors::transform(m_vecparticle, std::mem_fn(&SFastSlamParticle::m_fWeight))\n    ).base();\n    m_vecpose.emplace_back(m_itparticleBest->m_pose);\n\n    {\n        std::vector<std::future<void>> vecfuture;\n        boost::for_each(m_vecparticle, [&](auto& p) {\n            vecfuture.emplace_back( \n                std::async(std::launch::async,\n                    [&] {\n                        p.updateMap(scanline);\n                    }\n                ));\n        });\n    }\n}\n\ncv::Mat CFastParticleSlamBase::getMapWithPoses() const {\n    ASSERT(m_itparticleBest!=m_vecparticle.end());\n    return m_itparticleBest->m_occgrid.ObstacleMapWithPoses(m_vecpose);\n}\n\ncv::Mat CFastParticleSlamBase::getMap() const {\n    ASSERT(m_itparticleBest!=m_vecparticle.end());\n    return m_itparticleBest->m_occgrid.ObstacleMap();\n}\n\ncv::Mat CFastParticleSlamBase::getMapWithPose() const {\n    ASSERT(m_itparticleBest!=m_vecparticle.end());\n    cv::Mat mat = m_itparticleBest->m_occgrid.ObstacleMap();\n    cv::Mat matColor;\n    cvtColor(mat, matColor, CV_GRAY2RGB);\n    RenderRobotPose(matColor, m_vecpose.back(), cv::Scalar(255, 0, 0));\n    return matColor;\n}\n", "meta": {"hexsha": "64a2fee693ed4e508f838b574e202a953c80332b", "size": 5633, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "raspberry/fast_particle_slam.cpp", "max_stars_repo_name": "stheophil/MappingRover2", "max_stars_repo_head_hexsha": "25d968a4f27016a3eb61b70e48d3f137887d440c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-11-12T11:12:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-27T02:15:23.000Z", "max_issues_repo_path": "raspberry/fast_particle_slam.cpp", "max_issues_repo_name": "stheophil/MappingRover2", "max_issues_repo_head_hexsha": "25d968a4f27016a3eb61b70e48d3f137887d440c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "raspberry/fast_particle_slam.cpp", "max_forks_repo_name": "stheophil/MappingRover2", "max_forks_repo_head_hexsha": "25d968a4f27016a3eb61b70e48d3f137887d440c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2015-11-12T03:10:28.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-02T21:38:21.000Z", "avg_line_length": 37.0592105263, "max_line_length": 136, "alphanum_fraction": 0.6161903071, "num_tokens": 1455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.48339649093997017}}
{"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\u00e4nkt), 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 Cornelius Steinhardt\n\n\n#ifndef ITL_QMR_INCLUDE\n#define ITL_QMR_INCLUDE\n\n#include <boost/numeric/mtl/concept/collection.hpp>\n#include <boost/numeric/mtl/operation/trans.hpp>\n#include <boost/numeric/mtl/operation/resource.hpp>\n#include <boost/numeric/mtl/interface/vpt.hpp>\n\n#include <boost/numeric/itl/krylov/base_solver.hpp>\n\nnamespace itl {\n\n/// Quasi-Minimal Residual method\ntemplate < typename Matrix, typename Vector,typename LeftPreconditioner,\n\t   typename RightPreconditioner, typename Iteration >\nint qmr(const Matrix& A, Vector& x, const Vector& b, LeftPreconditioner& L, \n\tconst RightPreconditioner& R, Iteration& iter)\n{\n    mtl::vampir_trace<7008> tracer;\n    using mtl::size;\n    typedef typename mtl::Collection<Vector>::value_type Scalar;\n    if (size(b) == 0) throw mtl::logic_error(\"empty rhs vector\");\n\n    const Scalar         zero= math::zero(Scalar()), one= math::one(Scalar());\n    Scalar               beta, gamma(one), gamma_1, delta, eta(-one), ep(one), rho_1, theta(zero), theta_1;\n    Vector               r(b - A * x), v_tld(r), y(solve(L, v_tld)), w_tld(r), z(adjoint_solve(R,w_tld)), v(resource(x)), w(resource(x)), \n                         y_tld(resource(x)), z_tld(resource(x)), p(resource(x)), q(resource(x)), p_tld(resource(x)), d(resource(x)), s(resource(x));\n\n    if (iter.finished(r))\n\treturn iter;\n\n    Scalar rho = two_norm(y), xi = two_norm(z);\n    while(! iter.finished(rho)) {\n\t++iter;\n        if (rho == zero)\n\t    return iter.fail(1, \"qmr breakdown #1, rho=0\");\n        if (xi == zero)\n            return iter.fail(2, \"qmr breakdown #2, xi=0\");\n\n        v= v_tld / rho;\n        y/= rho;\n        w= w_tld / xi;\n        z/= xi;\n\n        delta = dot(z,y);\n        if (delta == zero)\n            return iter.fail(3, \"qmr breakdown, delta=0 #3\");\n\n        y_tld = solve(R,y);\n        z_tld = adjoint_solve(L,z); \n\n\tif (iter.first()) {\n            p = y_tld;\n            q = z_tld;\n\t} else {\n            p = y_tld - ((xi * delta) / ep) * p;\n            q = z_tld - ((rho* delta) / ep) * q;\n        }\n\n        p_tld = A * p;\n        ep = dot(q, p_tld);\n        if (ep == zero)\n            return iter.fail(4, \"qmr breakdown ep=0 #4\");\n        beta= ep / delta;\n        if (beta == zero)\n            return iter.fail(5, \"qmr breakdown beta=0 #5\");\n        v_tld = p_tld - beta * v;\n        y = solve(L,v_tld);\n        rho_1 = rho;\n\trho = two_norm(y);\n        w_tld= trans(A)*q  - beta*w; \n        z = adjoint_solve(R, w_tld);  \n        xi = two_norm(z);\n        gamma_1 = gamma;\n        theta_1 = theta;\n        theta = rho / (gamma_1 * beta);\n        gamma = one / (sqrt(one + theta * theta));\n\n        if (gamma == zero)\n            return iter.fail(6, \"qmr breakdown gamma=0 #6\");\n\n        eta= -eta * rho_1 * gamma * gamma / (beta * gamma_1 * gamma_1);\n\tif (iter.first()) {\n           d= eta * p;\n\t   s= eta * p_tld;\n\t} else {\n            d= eta * p + (theta_1 * theta_1 * gamma * gamma) * d;\n            s= eta * p_tld + (theta_1 * theta_1 * gamma * gamma) * s;\n        }\n        x += d;\n        r -= s;\n    }\n    return iter;\n}\n\n/// Solver class for Quasi-minimal residual method; right preconditioner ignored (prints warning if not identity)\n/** Methods inherited from \\ref base_solver. **/\ntemplate < typename LinearOperator, typename Preconditioner= pc::identity<LinearOperator>, \n\t   typename RightPreconditioner= pc::identity<LinearOperator> >\nclass qmr_solver\n  : public base_solver< qmr_solver<LinearOperator, Preconditioner, RightPreconditioner>, LinearOperator >\n{\n    typedef base_solver< qmr_solver<LinearOperator, Preconditioner, RightPreconditioner>, LinearOperator > base;\n  public:\n    /// Construct solver from a linear operator; generate (left) preconditioner from it\n    explicit qmr_solver(const LinearOperator& A) : base(A), L(A), R(A) {}\n\n    /// Construct solver from a linear operator and left preconditioner\n    qmr_solver(const LinearOperator& A, const Preconditioner& L) : base(A), L(L), R(A) {}\n\n    /// Construct solver from a linear operator and left preconditioner\n    qmr_solver(const LinearOperator& A, const Preconditioner& L, const RightPreconditioner& R) \n      : base(A), L(L), R(R) {}\n\n    /// Solve linear system approximately as specified by \\p iter\n    template < typename HilbertSpaceX, typename HilbertSpaceB, typename Iteration >\n    int solve(HilbertSpaceX& x, const HilbertSpaceB& b, Iteration& iter) const\n    {\n\treturn qmr(this->A, x, b, L, R, iter);\n    }\n\n  private:\n    Preconditioner        L;\n    RightPreconditioner   R;\n};\n\n\n} // namespace itl\n\n#endif // ITL_QMR_INCLUDE\n\n", "meta": {"hexsha": "aa768015e5cac1cdfb125a6a2247e558ff569499", "size": 5024, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/itl/krylov/qmr.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/krylov/qmr.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/krylov/qmr.hpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 34.1768707483, "max_line_length": 148, "alphanum_fraction": 0.6166401274, "num_tokens": 1389, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.48339649093997006}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2005, 2007, 2009, 2010, 2012, 2014, 2017 Klaus Spanderen\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n#include \"hestonmodel.hpp\"\n#include \"utilities.hpp\"\n#include <ql/instruments/dividendbarrieroption.hpp>\n#include <ql/instruments/dividendvanillaoption.hpp>\n#include <ql/processes/hestonprocess.hpp>\n#include <ql/math/randomnumbers/rngtraits.hpp>\n#include <ql/math/integrals/gausslobattointegral.hpp>\n#include <ql/models/equity/hestonmodel.hpp>\n#include <ql/models/equity/hestonmodelhelper.hpp>\n#include <ql/models/equity/piecewisetimedependenthestonmodel.hpp>\n#include <ql/pricingengines/vanilla/analyticdividendeuropeanengine.hpp>\n#include <ql/pricingengines/vanilla/analytichestonengine.hpp>\n#include <ql/pricingengines/vanilla/hestonexpansionengine.hpp>\n#include <ql/pricingengines/vanilla/coshestonengine.hpp>\n#include <ql/pricingengines/vanilla/analyticptdhestonengine.hpp>\n#include <ql/pricingengines/vanilla/exponentialfittinghestonengine.hpp>\n#include <ql/pricingengines/barrier/fdhestonbarrierengine.hpp>\n#include <ql/pricingengines/barrier/fdblackscholesbarrierengine.hpp>\n#include <ql/pricingengines/vanilla/fdblackscholesvanillaengine.hpp>\n#include <ql/pricingengines/vanilla/fdhestonvanillaengine.hpp>\n#include <ql/pricingengines/vanilla/mceuropeanhestonengine.hpp>\n#include <ql/pricingengines/blackformula.hpp>\n#include <ql/time/calendars/target.hpp>\n#include <ql/time/calendars/nullcalendar.hpp>\n#include <ql/time/daycounters/actual365fixed.hpp>\n#include <ql/time/daycounters/actual360.hpp>\n#include <ql/time/daycounters/actualactual.hpp>\n#include <ql/termstructures/yield/zerocurve.hpp>\n#include <ql/termstructures/yield/flatforward.hpp>\n#include <ql/methods/montecarlo/pathgenerator.hpp>\n#include <ql/math/optimization/levenbergmarquardt.hpp>\n#include <ql/math/optimization/differentialevolution.hpp>\n#include <ql/time/period.hpp>\n#include <ql/quotes/simplequote.hpp>\n#include <ql/experimental/exoticoptions/analyticpdfhestonengine.hpp>\n#include <ql/methods/finitedifferences/operators/numericaldifferentiation.hpp>\n\n#include <boost/math/special_functions/fpclassify.hpp>\n\nusing namespace QuantLib;\nusing namespace boost::unit_test_framework;\n\nnamespace {\n\n    struct CalibrationMarketData {\n        Handle<Quote> s0;\n        Handle<YieldTermStructure> riskFreeTS, dividendYield;\n        std::vector<ext::shared_ptr<CalibrationHelper> > options;\n    };\n\n    CalibrationMarketData getDAXCalibrationMarketData() {\n        /* this example is taken from A. Sepp\n           Pricing European-Style Options under Jump Diffusion Processes\n           with Stochstic Volatility: Applications of Fourier Transform\n           http://math.ut.ee/~spartak/papers/stochjumpvols.pdf\n        */\n\n        Date settlementDate(Settings::instance().evaluationDate());\n        \n        DayCounter dayCounter = Actual365Fixed();\n        Calendar calendar = TARGET();\n        \n        Integer t[] = { 13, 41, 75, 165, 256, 345, 524, 703 };\n        Rate r[] = { 0.0357,0.0349,0.0341,0.0355,0.0359,0.0368,0.0386,0.0401 };\n        \n        std::vector<Date> dates;\n        std::vector<Rate> rates;\n        dates.push_back(settlementDate);\n        rates.push_back(0.0357);\n        Size i;\n        for (i = 0; i < 8; ++i) {\n            dates.push_back(settlementDate + t[i]);\n            rates.push_back(r[i]);\n        }\n        // FLOATING_POINT_EXCEPTION\n        Handle<YieldTermStructure> riskFreeTS(\n            ext::make_shared<ZeroCurve>(dates, rates, dayCounter));\n        \n        Handle<YieldTermStructure> dividendYield(\n                                    flatRate(settlementDate, 0.0, dayCounter));\n        \n        Volatility v[] =\n          { 0.6625,0.4875,0.4204,0.3667,0.3431,0.3267,0.3121,0.3121,\n            0.6007,0.4543,0.3967,0.3511,0.3279,0.3154,0.2984,0.2921,\n            0.5084,0.4221,0.3718,0.3327,0.3155,0.3027,0.2919,0.2889,\n            0.4541,0.3869,0.3492,0.3149,0.2963,0.2926,0.2819,0.2800,\n            0.4060,0.3607,0.3330,0.2999,0.2887,0.2811,0.2751,0.2775,\n            0.3726,0.3396,0.3108,0.2781,0.2788,0.2722,0.2661,0.2686,\n            0.3550,0.3277,0.3012,0.2781,0.2781,0.2661,0.2661,0.2681,\n            0.3428,0.3209,0.2958,0.2740,0.2688,0.2627,0.2580,0.2620,\n            0.3302,0.3062,0.2799,0.2631,0.2573,0.2533,0.2504,0.2544,\n            0.3343,0.2959,0.2705,0.2540,0.2504,0.2464,0.2448,0.2462,\n            0.3460,0.2845,0.2624,0.2463,0.2425,0.2385,0.2373,0.2422,\n            0.3857,0.2860,0.2578,0.2399,0.2357,0.2327,0.2312,0.2351,\n            0.3976,0.2860,0.2607,0.2356,0.2297,0.2268,0.2241,0.2320 };\n        \n        Handle<Quote> s0(ext::make_shared<SimpleQuote>(4468.17));\n        Real strike[] = { 3400,3600,3800,4000,4200,4400,\n                          4500,4600,4800,5000,5200,5400,5600 };\n        \n        std::vector<ext::shared_ptr<CalibrationHelper> > options;\n        \n        for (Size s = 0; s < 13; ++s) {\n            for (Size m = 0; m < 8; ++m) {\n                Handle<Quote> vol(ext::make_shared<SimpleQuote>(v[s*8+m]));\n        \n                Period maturity((int)((t[m]+3)/7.), Weeks); // round to weeks\n                options.push_back(ext::make_shared<HestonModelHelper>(maturity, calendar,\n                                              s0, strike[s], vol,\n                                              riskFreeTS, dividendYield,\n                                          BlackCalibrationHelper::ImpliedVolError));\n            }\n        }\n        \n        CalibrationMarketData marketData = { s0, riskFreeTS, dividendYield, options };\n        \n        return marketData;\n    }\n        \n}\n\n\nvoid HestonModelTest::testBlackCalibration() {\n    BOOST_TEST_MESSAGE(\n       \"Testing Heston model calibration using a flat volatility surface...\");\n\n    SavedSettings backup;\n\n    /* calibrate a Heston model to a constant volatility surface without\n       smile. expected result is a vanishing volatility of the volatility.\n       In addition theta and v0 should be equal to the constant variance */\n\n    Date today = Date::todaysDate();\n    Settings::instance().evaluationDate() = today;\n\n    DayCounter dayCounter = Actual360();\n    Calendar calendar = NullCalendar();\n\n    Handle<YieldTermStructure> riskFreeTS(flatRate(0.04, dayCounter));\n    Handle<YieldTermStructure> dividendTS(flatRate(0.50, dayCounter));\n\n    std::vector<Period> optionMaturities;\n    optionMaturities.push_back(Period(1, Months));\n    optionMaturities.push_back(Period(2, Months));\n    optionMaturities.push_back(Period(3, Months));\n    optionMaturities.push_back(Period(6, Months));\n    optionMaturities.push_back(Period(9, Months));\n    optionMaturities.push_back(Period(1, Years));\n    optionMaturities.push_back(Period(2, Years));\n\n    std::vector<ext::shared_ptr<CalibrationHelper> > options;\n    Handle<Quote> s0(ext::make_shared<SimpleQuote>(1.0));\n    Handle<Quote> vol(ext::make_shared<SimpleQuote>(0.1));\n    Volatility volatility = vol->value();\n\n    for (Size i = 0; i < optionMaturities.size(); ++i) {\n        for (Real moneyness = -1.0; moneyness < 2.0; moneyness += 1.0) {\n            // FLOATING_POINT_EXCEPTION\n            const Time tau = dayCounter.yearFraction(\n                                 riskFreeTS->referenceDate(),\n                                 calendar.advance(riskFreeTS->referenceDate(),\n                                                  optionMaturities[i]));\n        const Real fwdPrice = s0->value()*dividendTS->discount(tau)\n                            / riskFreeTS->discount(tau);\n        const Real strikePrice = fwdPrice * std::exp(-moneyness * volatility\n                                                     * std::sqrt(tau));\n\n        options.push_back(ext::make_shared<HestonModelHelper>(optionMaturities[i], calendar,\n                                                s0, strikePrice, vol,\n                                                riskFreeTS, dividendTS));\n        }\n    }\n\n    for (Real sigma = 0.1; sigma < 0.7; sigma += 0.2) {\n        const Real v0=0.01;\n        const Real kappa=0.2;\n        const Real theta=0.02;\n        const Real rho=-0.75;\n\n        ext::shared_ptr<HestonProcess> process(\n            ext::make_shared<HestonProcess>(riskFreeTS, dividendTS,\n                              s0, v0, kappa, theta, sigma, rho));\n\n        ext::shared_ptr<HestonModel> model(ext::make_shared<HestonModel>(process));\n        ext::shared_ptr<PricingEngine> engine(\n            ext::make_shared<AnalyticHestonEngine>(model, 96));\n\n        for (Size i = 0; i < options.size(); ++i)\n            ext::dynamic_pointer_cast<BlackCalibrationHelper>(options[i])->setPricingEngine(engine);\n\n        LevenbergMarquardt om(1e-8, 1e-8, 1e-8);\n        model->calibrate(options, om, EndCriteria(400, 40, 1.0e-8,\n                                                  1.0e-8, 1.0e-8));\n\n        Real tolerance = 3.0e-3;\n\n        if (model->sigma() > tolerance) {\n            BOOST_ERROR(\"Failed to reproduce expected sigma\"\n                        << \"\\n    calculated: \" << model->sigma()\n                        << \"\\n    expected:   \" << 0.0\n                        << \"\\n    tolerance:  \" << tolerance);\n        }\n\n        if (std::fabs(model->kappa()\n                  *(model->theta()-volatility*volatility)) > tolerance) {\n            BOOST_ERROR(\"Failed to reproduce expected theta\"\n                        << \"\\n    calculated: \" << model->theta()\n                        << \"\\n    expected:   \" << volatility*volatility);\n        }\n\n        if (std::fabs(model->v0()-volatility*volatility) > tolerance) {\n            BOOST_ERROR(\"Failed to reproduce expected v0\"\n                        << \"\\n    calculated: \" << model->v0()\n                        << \"\\n    expected:   \" << volatility*volatility);\n        }\n    }\n}\n\n\nvoid HestonModelTest::testDAXCalibration() {\n\n    BOOST_TEST_MESSAGE(\n             \"Testing Heston model calibration using DAX volatility data...\");\n\n    SavedSettings backup;\n\n    Date settlementDate(5, July, 2002);\n    Settings::instance().evaluationDate() = settlementDate;\n\n    CalibrationMarketData marketData = getDAXCalibrationMarketData();\n    \n    const Handle<YieldTermStructure> riskFreeTS = marketData.riskFreeTS;\n    const Handle<YieldTermStructure> dividendTS = marketData.dividendYield;\n    const Handle<Quote> s0 = marketData.s0;\n\n    const std::vector<ext::shared_ptr<CalibrationHelper> >& options = marketData.options;\n\n    const Real v0=0.1;\n    const Real kappa=1.0;\n    const Real theta=0.1;\n    const Real sigma=0.5;\n    const Real rho=-0.5;\n\n    const ext::shared_ptr<HestonProcess> process(\n        ext::make_shared<HestonProcess>(\n            riskFreeTS, dividendTS, s0, v0, kappa, theta, sigma, rho));\n\n    const ext::shared_ptr<HestonModel> model(\n        ext::make_shared<HestonModel>(process));\n\n    const ext::shared_ptr<PricingEngine> engines[] = {\n        ext::make_shared<AnalyticHestonEngine>(model, 64),\n        ext::make_shared<COSHestonEngine>(model, 12, 75),\n        ext::make_shared<ExponentialFittingHestonEngine>(model)\n    };\n\n    const Array params = model->params();\n    for (Size j=0; j < LENGTH(engines); ++j) {\n        model->setParams(params);\n        for (Size i = 0; i < options.size(); ++i)\n            ext::dynamic_pointer_cast<BlackCalibrationHelper>(options[i])->setPricingEngine(engines[j]);\n\n        LevenbergMarquardt om(1e-8, 1e-8, 1e-8);\n        model->calibrate(options, om,\n                         EndCriteria(400, 40, 1.0e-8, 1.0e-8, 1.0e-8));\n\n        Real sse = 0;\n        for (Size i = 0; i < 13*8; ++i) {\n            const Real diff = options[i]->calibrationError()*100.0;\n            sse += diff*diff;\n        }\n        Real expected = 177.2; //see article by A. Sepp.\n        if (std::fabs(sse - expected) > 1.0) {\n            BOOST_FAIL(\"Failed to reproduce calibration error\"\n                       << \"\\n    calculated: \" << sse\n                       << \"\\n    expected:   \" << expected);\n        }\n    }\n}\n\nvoid HestonModelTest::testAnalyticVsBlack() {\n    BOOST_TEST_MESSAGE(\"Testing analytic Heston engine against Black formula...\");\n\n    SavedSettings backup;\n\n    Date settlementDate = Date::todaysDate();\n    Settings::instance().evaluationDate() = settlementDate;\n    DayCounter dayCounter = ActualActual();\n    Date exerciseDate = settlementDate + 6*Months;\n\n    ext::shared_ptr<StrikedTypePayoff> payoff(\n        ext::make_shared<PlainVanillaPayoff>(Option::Put, 30));\n    ext::shared_ptr<Exercise> exercise(\n        ext::make_shared<EuropeanExercise>(exerciseDate));\n\n    Handle<YieldTermStructure> riskFreeTS(flatRate(0.1, dayCounter));\n    Handle<YieldTermStructure> dividendTS(flatRate(0.04, dayCounter));\n\n    Handle<Quote> s0(ext::make_shared<SimpleQuote>(32.0));\n\n    const Real v0=0.05;\n    const Real kappa=5.0;\n    const Real theta=0.05;\n    const Real sigma=1.0e-4;\n    const Real rho=0.0;\n\n    ext::shared_ptr<HestonProcess> process(ext::make_shared<HestonProcess>(\n                   riskFreeTS, dividendTS, s0, v0, kappa, theta, sigma, rho));\n\n    VanillaOption option(payoff, exercise);\n    // FLOATING_POINT_EXCEPTION\n    ext::shared_ptr<PricingEngine> engine(\n        ext::make_shared<AnalyticHestonEngine>(\n            ext::make_shared<HestonModel>(process), 144));\n\n    option.setPricingEngine(engine);\n    Real calculated = option.NPV();\n\n    Real yearFraction = dayCounter.yearFraction(settlementDate, exerciseDate);\n    Real forwardPrice = 32*std::exp((0.1-0.04)*yearFraction);\n    Real expected = blackFormula(payoff->optionType(), payoff->strike(),\n        forwardPrice, std::sqrt(0.05*yearFraction)) *\n                                            std::exp(-0.1*yearFraction);\n    Real error = std::fabs(calculated - expected);\n    Real tolerance = 2.0e-7;\n    if (error > tolerance) {\n        BOOST_FAIL(\"failed to reproduce Black price with AnalyticHestonEngine\"\n                   << \"\\n    calculated: \" << calculated\n                   << \"\\n    expected:   \" << expected\n                   << \"\\n    error:      \" << std::scientific << error);\n    }\n\n    engine = \n        ext::make_shared<FdHestonVanillaEngine>(\n            ext::make_shared<HestonModel>(process),\n              200,200,100);\n    option.setPricingEngine(engine);\n\n    calculated = option.NPV();\n    error = std::fabs(calculated - expected);\n    tolerance = 1.0e-3;\n    if (error > tolerance) {\n        BOOST_FAIL(\"failed to reproduce Black price with FdHestonVanillaEngine\"\n                   << \"\\n    calculated: \" << calculated\n                   << \"\\n    expected:   \" << expected\n                   << \"\\n    error:      \" << std::scientific << error);\n    }\n\n}\n\n\nvoid HestonModelTest::testAnalyticVsCached() {\n    BOOST_TEST_MESSAGE(\"Testing analytic Heston engine against cached values...\");\n\n    SavedSettings backup;\n\n    Date settlementDate(27, December, 2004);\n    Settings::instance().evaluationDate() = settlementDate;\n    DayCounter dayCounter = ActualActual();\n    Date exerciseDate(28, March, 2005);\n\n    ext::shared_ptr<StrikedTypePayoff> payoff(\n        ext::make_shared<PlainVanillaPayoff>(Option::Call, 1.05));\n    ext::shared_ptr<Exercise> exercise(\n        ext::make_shared<EuropeanExercise>(exerciseDate));\n\n    Handle<YieldTermStructure> riskFreeTS(flatRate(0.0225, dayCounter));\n    Handle<YieldTermStructure> dividendTS(flatRate(0.02, dayCounter));\n\n    Handle<Quote> s0(ext::make_shared<SimpleQuote>(1.0));\n    const Real v0 = 0.1;\n    const Real kappa = 3.16;\n    const Real theta = 0.09;\n    const Real sigma = 0.4;\n    const Real rho = -0.2;\n\n    ext::shared_ptr<HestonProcess> process(ext::make_shared<HestonProcess>(\n                   riskFreeTS, dividendTS, s0, v0, kappa, theta, sigma, rho));\n\n    VanillaOption option(payoff, exercise);\n\n    ext::shared_ptr<AnalyticHestonEngine> engine(\n        ext::make_shared<AnalyticHestonEngine>(\n            ext::make_shared<HestonModel>(process), 64));\n\n    option.setPricingEngine(engine);\n\n    Real expected1 = 0.0404774515;\n    Real calculated1 = option.NPV();\n    Real tolerance = 1.0e-8;\n\n    if (std::fabs(calculated1 - expected1) > tolerance) {\n        BOOST_ERROR(\"Failed to reproduce cached analytic price\"\n                    << \"\\n    calculated: \" << calculated1\n                    << \"\\n    expected:   \" << expected1);\n    }\n\n\n    // reference values from www.wilmott.com, technical forum\n    // search for \"Heston or VG price check\"\n\n    Real K[] = {0.9,1.0,1.1};\n    Real expected2[] = { 0.1330371,0.0641016, 0.0270645 };\n    Real calculated2[6];\n\n    Size i;\n    for (i = 0; i < 6; ++i) {\n        Date exerciseDate(8+i/3, September, 2005);\n\n        ext::shared_ptr<StrikedTypePayoff> payoff(\n            ext::make_shared<PlainVanillaPayoff>(Option::Call, K[i%3]));\n        ext::shared_ptr<Exercise> exercise(\n            ext::make_shared<EuropeanExercise>(exerciseDate));\n\n        Handle<YieldTermStructure> riskFreeTS(flatRate(0.05, dayCounter));\n        Handle<YieldTermStructure> dividendTS(flatRate(0.02, dayCounter));\n\n        Real s = riskFreeTS->discount(0.7)/dividendTS->discount(0.7);\n        Handle<Quote> s0(ext::make_shared<SimpleQuote>(s));\n\n        ext::shared_ptr<HestonProcess> process(\n            ext::make_shared<HestonProcess>(\n                   riskFreeTS, dividendTS, s0, 0.09, 1.2, 0.08, 1.8, -0.45));\n\n        VanillaOption option(payoff, exercise);\n\n        ext::shared_ptr<PricingEngine> engine(\n            ext::make_shared<AnalyticHestonEngine>(\n                ext::make_shared<HestonModel>(process)));\n\n        option.setPricingEngine(engine);\n        calculated2[i] = option.NPV();\n    }\n\n    // we are after the value for T=0.7\n    Time t1 = dayCounter.yearFraction(settlementDate, Date(8, September,2005));\n    Time t2 = dayCounter.yearFraction(settlementDate, Date(9, September,2005));\n\n    for (i = 0; i < 3; ++i) {\n        const Real interpolated =\n            calculated2[i]+(calculated2[i+3]-calculated2[i])/(t2-t1)*(0.7-t1);\n\n        if (std::fabs(interpolated - expected2[i]) > 100*tolerance) {\n            BOOST_ERROR(\"Failed to reproduce cached analytic prices:\"\n                        << \"\\n    calculated: \" << interpolated\n                        << \"\\n    expected:   \" << expected2[i] );\n        }\n    }\n}\n\n\nvoid HestonModelTest::testMcVsCached() {\n    BOOST_TEST_MESSAGE(\n                \"Testing Monte Carlo Heston engine against cached values...\");\n\n    SavedSettings backup;\n\n    Date settlementDate(27, December, 2004);\n    Settings::instance().evaluationDate() = settlementDate;\n\n    DayCounter dayCounter = ActualActual();\n    Date exerciseDate(28, March, 2005);\n\n    ext::shared_ptr<StrikedTypePayoff> payoff(\n        ext::make_shared<PlainVanillaPayoff>(Option::Put, 1.05));\n    ext::shared_ptr<Exercise> exercise(\n        ext::make_shared<EuropeanExercise>(exerciseDate));\n\n    Handle<YieldTermStructure> riskFreeTS(flatRate(0.7, dayCounter));\n    Handle<YieldTermStructure> dividendTS(flatRate(0.4, dayCounter));\n\n    Handle<Quote> s0(ext::make_shared<SimpleQuote>(1.05));\n\n    ext::shared_ptr<HestonProcess> process(\n        ext::make_shared<HestonProcess>(\n                   riskFreeTS, dividendTS, s0, 0.3, 1.16, 0.2, 0.8, 0.8,\n                   HestonProcess::QuadraticExponentialMartingale));\n\n    VanillaOption option(payoff, exercise);\n\n    ext::shared_ptr<PricingEngine> engine;\n    engine = MakeMCEuropeanHestonEngine<PseudoRandom>(process)\n        .withStepsPerYear(11)\n        .withAntitheticVariate()\n        .withSamples(50000)\n        .withSeed(1234);\n\n    option.setPricingEngine(engine);\n\n    Real expected = 0.0632851308977151;\n    Real calculated = option.NPV();\n    Real errorEstimate = option.errorEstimate();\n    Real tolerance = 7.5e-4;\n\n    if (std::fabs(calculated - expected) > 2.34*errorEstimate) {\n        BOOST_ERROR(\"Failed to reproduce cached price\"\n                    << \"\\n    calculated: \" << calculated\n                    << \"\\n    expected:   \" << expected\n                    << \" +/- \" << errorEstimate);\n    }\n\n    if (errorEstimate > tolerance) {\n        BOOST_ERROR(\"failed to reproduce error estimate\"\n                    << \"\\n    calculated: \" << errorEstimate\n                    << \"\\n    expected:   \" << tolerance);\n    }\n}\n\nvoid HestonModelTest::testFdBarrierVsCached() {\n    BOOST_TEST_MESSAGE(\"Testing FD barrier Heston engine against cached values...\");\n\n    SavedSettings backup;\n\n    DayCounter dc = Actual360();\n    Date today = Date::todaysDate();\n\n    Handle<Quote> s0(ext::make_shared<SimpleQuote>(100.0));\n    Handle<YieldTermStructure> rTS(flatRate(today, 0.08, dc));\n    Handle<YieldTermStructure> qTS(flatRate(today, 0.04, dc));\n\n    Date exDate = today + Integer(0.5*360+0.5);\n    ext::shared_ptr<Exercise> exercise(\n        ext::make_shared<EuropeanExercise>(exDate));\n\n    ext::shared_ptr<StrikedTypePayoff> payoff(\n        ext::make_shared<PlainVanillaPayoff>(Option::Call, 90.0));\n\n    ext::shared_ptr<HestonProcess> process(\n        ext::make_shared<HestonProcess>(\n            rTS, qTS, s0, 0.25*0.25, 1.0, 0.25*0.25, 0.001, 0.0));\n\n    ext::shared_ptr<PricingEngine> engine;\n    engine = ext::make_shared<FdHestonBarrierEngine>(\n                ext::make_shared<HestonModel>(process),\n                    200,400,100);\n\n    BarrierOption option(Barrier::DownOut, 95.0, 3.0, payoff, exercise);\n    option.setPricingEngine(engine);\n\n    Real calculated = option.NPV();\n    Real expected = 9.0246;\n    Real error = std::fabs(calculated-expected);\n    if (error > 1.0e-3) {\n        BOOST_FAIL(\"failed to reproduce cached price with FD Barrier engine\"\n                   << \"\\n    calculated: \" << calculated\n                   << \"\\n    expected:   \" << expected\n                   << \"\\n    error:      \" << std::scientific << error);\n    }\n\n    option = BarrierOption(Barrier::DownIn, 95.0, 3.0, payoff, exercise);\n    option.setPricingEngine(engine);\n\n    calculated = option.NPV();\n    expected = 7.7627;\n    error = std::fabs(calculated-expected);\n    if (error > 1.0e-3) {\n        BOOST_FAIL(\"failed to reproduce cached price with FD Barrier engine\"\n                   << \"\\n    calculated: \" << calculated\n                   << \"\\n    expected:   \" << expected\n                   << \"\\n    error:      \" << std::scientific << error);\n    }\n}\n\nvoid HestonModelTest::testFdVanillaVsCached() {\n    BOOST_TEST_MESSAGE(\"Testing FD vanilla Heston engine against cached values...\");\n\n    SavedSettings backup;\n\n    Date settlementDate(27, December, 2004);\n    Settings::instance().evaluationDate() = settlementDate;\n\n    DayCounter dayCounter = ActualActual();\n    Date exerciseDate(28, March, 2005);\n\n    ext::shared_ptr<StrikedTypePayoff> payoff(\n        ext::make_shared<PlainVanillaPayoff>(Option::Put, 1.05));\n    ext::shared_ptr<Exercise> exercise(\n        ext::make_shared<EuropeanExercise>(exerciseDate));\n\n    Handle<YieldTermStructure> riskFreeTS(flatRate(0.7, dayCounter));\n    Handle<YieldTermStructure> dividendTS(flatRate(0.4, dayCounter));\n\n    Handle<Quote> s0(ext::make_shared<SimpleQuote>(1.05));\n\n    VanillaOption option(payoff, exercise);\n\n    ext::shared_ptr<HestonProcess> process(\n        ext::make_shared<HestonProcess>(\n                   riskFreeTS, dividendTS, s0, 0.3, 1.16, 0.2, 0.8, 0.8));\n\n    option.setPricingEngine(\n        MakeFdHestonVanillaEngine(ext::make_shared<HestonModel>(process))\n            .withTGrid(100)\n            .withXGrid(200)\n            .withVGrid(100)\n        );\n\n    Real expected = 0.06325;\n    Real calculated = option.NPV();\n    Real error = std::fabs(calculated - expected);\n    Real tolerance = 1.0e-4;\n\n    if (error > tolerance) {\n        BOOST_FAIL(\"failed to reproduce cached price with FD engine\"\n                   << \"\\n    calculated: \" << calculated\n                   << \"\\n    expected:   \" << expected\n                   << \"\\n    error:      \" << std::scientific << error);\n    }\n\n    BOOST_TEST_MESSAGE(\"Testing FD vanilla Heston engine for discrete dividends...\");\n\n    payoff = ext::make_shared<PlainVanillaPayoff>(Option::Call, 95.0);\n    s0 = Handle<Quote>(ext::make_shared<SimpleQuote>(100.0));\n\n    riskFreeTS = Handle<YieldTermStructure>(flatRate(0.05, dayCounter));\n    dividendTS = Handle<YieldTermStructure>(flatRate(0.0, dayCounter));\n\n    exerciseDate = Date(28, March, 2006);\n    exercise = ext::make_shared<EuropeanExercise>(exerciseDate);\n\n    std::vector<Date> dividendDates;\n    std::vector<Real> dividends;\n    for (Date d = settlementDate + 3*Months;\n              d < exercise->lastDate();\n              d += 6*Months) {\n        dividendDates.push_back(d);\n        dividends.push_back(1.0);\n    }\n\n    DividendVanillaOption divOption(payoff, exercise,\n                                    dividendDates, dividends);\n    process = ext::make_shared<HestonProcess>(\n                   riskFreeTS, dividendTS, s0, 0.04, 1.0, 0.04, 0.001, 0.0);\n    divOption.setPricingEngine(\n        MakeFdHestonVanillaEngine(ext::make_shared<HestonModel>(process))\n            .withTGrid(200)\n            .withXGrid(400)\n            .withVGrid(100)\n        );\n    calculated = divOption.NPV();\n    // Value calculated with an independent FD framework, validated with\n    // an independent MC framework\n    expected = 12.946;\n    error = std::fabs(calculated - expected);\n    tolerance = 5.0e-3;\n\n    if (error > tolerance) {\n        BOOST_FAIL(\"failed to reproduce discrete dividend price with FD engine\"\n                   << \"\\n    calculated: \" << calculated\n                   << \"\\n    expected:   \" << expected\n                   << \"\\n    error:      \" << std::scientific << error);\n    }\n\n    BOOST_TEST_MESSAGE(\"Testing FD vanilla Heston engine for american exercise...\");\n\n    dividendTS = Handle<YieldTermStructure>(flatRate(0.03, dayCounter));\n    process = ext::make_shared<HestonProcess>(\n                   riskFreeTS, dividendTS, s0, 0.04, 1.0, 0.04, 0.001, 0.0);\n    payoff = ext::make_shared<PlainVanillaPayoff>(Option::Put, 95.0);\n    exercise = ext::make_shared<AmericanExercise>(\n            settlementDate, exerciseDate);\n    option = VanillaOption(payoff, exercise);\n    option.setPricingEngine(\n        MakeFdHestonVanillaEngine(ext::make_shared<HestonModel>(process))\n            .withTGrid(200)\n            .withXGrid(400)\n            .withVGrid(100)\n        );\n    calculated = option.NPV();\n\n    Handle<BlackVolTermStructure> volTS(flatVol(settlementDate, 0.2,\n                                                  dayCounter));\n    ext::shared_ptr<BlackScholesMertonProcess> ref_process(\n        ext::make_shared<BlackScholesMertonProcess>(s0, dividendTS, riskFreeTS, volTS));\n    ext::shared_ptr<PricingEngine> ref_engine(\n        ext::make_shared<FdBlackScholesVanillaEngine>(ref_process, 200, 400));\n    option.setPricingEngine(ref_engine);\n    expected = option.NPV();\n\n    error = std::fabs(calculated - expected);\n    tolerance = 1.0e-3;\n\n    if (error > tolerance) {\n        BOOST_FAIL(\"failed to reproduce american option price with FD engine\"\n                   << \"\\n    calculated: \" << calculated\n                   << \"\\n    expected:   \" << expected\n                   << \"\\n    error:      \" << std::scientific << error);\n    }\n}\n\nnamespace {\n    struct HestonProcessDiscretizationDesc {\n        HestonProcess::Discretization discretization;\n        Size nSteps;\n        std::string name;\n    };\n}\n\nvoid HestonModelTest::testKahlJaeckelCase() {\n    BOOST_TEST_MESSAGE(\n          \"Testing MC and FD Heston engines for the Kahl-Jaeckel example...\");\n\n    /* Example taken from Wilmott mag (Sept. 2005).\n       \"Not-so-complex logarithms in the Heston model\",\n       Example was also discussed within the Wilmott thread\n       \"QuantLib code is very high quatlity\"\n    */\n\n    SavedSettings backup;\n\n    Date settlementDate(30, March, 2007);\n    Settings::instance().evaluationDate() = settlementDate;\n\n    DayCounter dayCounter = ActualActual();\n    Date exerciseDate(30, March, 2017);\n\n    const ext::shared_ptr<StrikedTypePayoff> payoff(\n        ext::make_shared<PlainVanillaPayoff>(Option::Call, 200));\n    const ext::shared_ptr<Exercise> exercise(\n        ext::make_shared<EuropeanExercise>(exerciseDate));\n\n    VanillaOption option(payoff, exercise);\n\n\n    Handle<YieldTermStructure> riskFreeTS(flatRate(0.0, dayCounter));\n    Handle<YieldTermStructure> dividendTS(flatRate(0.0, dayCounter));\n\n    Handle<Quote> s0(ext::make_shared<SimpleQuote>(100));\n\n    const Real v0    = 0.16;\n    const Real theta = v0;\n    const Real kappa = 1.0;\n    const Real sigma = 2.0;\n    const Real rho   =-0.8;\n\n\n    const HestonProcessDiscretizationDesc descriptions[] = {\n        { HestonProcess::NonCentralChiSquareVariance, 10,\n          \"NonCentralChiSquareVariance\" },\n        { HestonProcess::QuadraticExponentialMartingale, 100,\n          \"QuadraticExponentialMartingale\" },\n    };\n\n    const Real tolerance = 0.2;\n    const Real expected = 4.95212;\n\n    for (Size i=0; i < LENGTH(descriptions); ++i) {\n        const ext::shared_ptr<HestonProcess> process(\n            ext::make_shared<HestonProcess>(riskFreeTS, dividendTS, s0, v0,\n                              kappa, theta, sigma, rho,\n                              descriptions[i].discretization));\n\n        const ext::shared_ptr<PricingEngine> engine =\n            MakeMCEuropeanHestonEngine<PseudoRandom>(process)\n            .withSteps(descriptions[i].nSteps)\n            .withAntitheticVariate()\n            .withAbsoluteTolerance(tolerance)\n            .withSeed(1234);\n        option.setPricingEngine(engine);\n\n        const Real calculated = option.NPV();\n        const Real errorEstimate = option.errorEstimate();\n\n        if (std::fabs(calculated - expected) > 2.34*errorEstimate) {\n            BOOST_ERROR(\"Failed to reproduce cached price with MC engine\"\n                        << \"\\n    discretization: \" << descriptions[i].name\n                        << \"\\n    expected:       \" << expected\n                        << \"\\n    calculated:     \" << calculated\n                        << \" +/- \" << errorEstimate);\n        }\n\n        if (errorEstimate > tolerance) {\n            BOOST_ERROR(\"failed to reproduce error estimate with MC engine\"\n                        << \"\\n    discretization: \" << descriptions[i].name\n                        << \"\\n    calculated    : \" << errorEstimate\n                        << \"\\n    expected      :   \" << tolerance);\n        }\n    }\n\n    option.setPricingEngine(\n        MakeMCEuropeanHestonEngine<LowDiscrepancy>(\n            ext::make_shared<HestonProcess>(\n                    riskFreeTS, dividendTS, s0, v0, kappa, theta, sigma, rho,\n                    HestonProcess::BroadieKayaExactSchemeLaguerre))\n        .withSteps(1)\n        .withSamples(1023));\n\n    Real calculated = option.NPV();\n    if (std::fabs(calculated - expected) > 0.5*tolerance) {\n        BOOST_ERROR(\"Failed to reproduce cached price with MC engine\"\n                    << \"\\n    discretization: BroadieKayaExactSchemeLobatto\"\n                    << \"\\n    calculated:     \" << calculated\n                    << \"\\n    expected:       \" << expected\n                    << \"\\n    tolerance:      \" << tolerance);\n    }\n\n\n    const ext::shared_ptr<HestonModel> hestonModel(\n        ext::make_shared<HestonModel>(\n            ext::make_shared<HestonProcess>(\n                riskFreeTS, dividendTS, s0, v0,\n                kappa, theta, sigma, rho)));\n\n    option.setPricingEngine(\n        ext::make_shared<FdHestonVanillaEngine>(hestonModel, 200, 401, 101));\n\n    calculated = option.NPV();\n    Real error = std::fabs(calculated - expected);\n    if (error > 5.0e-2) {\n        BOOST_FAIL(\"failed to reproduce cached price with FD engine\"\n                   << \"\\n    calculated: \" << calculated\n                   << \"\\n    expected:   \" << expected\n                   << \"\\n    error:      \" << std::scientific << error);\n    }\n\n    option.setPricingEngine(\n        ext::make_shared<AnalyticHestonEngine>(hestonModel, 1e-6, 1000));\n\n    calculated = option.NPV();\n    error = std::fabs(calculated - expected);\n\n    if (error > 0.00002) {\n        BOOST_FAIL(\"failed to reproduce cached price with \"\n                   \"GaussLobatto engine\"\n                   << \"\\n    calculated: \" << calculated\n                   << \"\\n    expected:   \" << expected\n                   << \"\\n    error:      \" << std::scientific << error);\n    }\n\n    option.setPricingEngine(\n        ext::make_shared<COSHestonEngine>(hestonModel, 16, 400));\n    calculated = option.NPV();\n    error = std::fabs(calculated - expected);\n\n    if (error > 0.00002) {\n        BOOST_FAIL(\"failed to reproduce cached price with \"\n                   \"Cosine engine\"\n                   << \"\\n    calculated: \" << calculated\n                   << \"\\n    expected:   \" << expected\n                   << \"\\n    error:      \" << std::scientific << error);\n    }\n\n    option.setPricingEngine(\n        ext::make_shared<ExponentialFittingHestonEngine>(hestonModel));\n    calculated = option.NPV();\n    error = std::fabs(calculated - expected);\n\n    if (error > 0.00002) {\n        BOOST_FAIL(\"failed to reproduce cached price with \"\n                   \"exponential fitting Heston engine\"\n                   << \"\\n    calculated: \" << calculated\n                   << \"\\n    expected:   \" << expected\n                   << \"\\n    error:      \" << std::scientific << error);\n    }\n}\n\nnamespace {\n    struct HestonParameter {\n        Real v0, kappa, theta, sigma, rho; };\n}\n\nvoid HestonModelTest::testDifferentIntegrals() {\n    BOOST_TEST_MESSAGE(\n       \"Testing different numerical Heston integration algorithms...\");\n\n    SavedSettings backup;\n\n    const Date settlementDate(27, December, 2004);\n    Settings::instance().evaluationDate() = settlementDate;\n\n    const DayCounter dayCounter = ActualActual();\n\n    Handle<YieldTermStructure> riskFreeTS(flatRate(0.05, dayCounter));\n    Handle<YieldTermStructure> dividendTS(flatRate(0.03, dayCounter));\n\n    const Real strikes[] = { 0.5, 0.7, 1.0, 1.25, 1.5, 2.0 };\n    const Integer maturities[] = { 1, 2, 3, 12, 60, 120, 360};\n    const Option::Type types[] ={ Option::Put, Option::Call };\n\n    const HestonParameter equityfx      = { 0.07, 2.0, 0.04, 0.55, -0.8 };\n    const HestonParameter highCorr      = { 0.07, 1.0, 0.04, 0.55,  0.995 };\n    const HestonParameter lowVolOfVol   = { 0.07, 1.0, 0.04, 0.025, -0.75 };\n    const HestonParameter highVolOfVol  = { 0.07, 1.0, 0.04, 5.0, -0.75 };\n    const HestonParameter kappaEqSigRho = { 0.07, 0.4, 0.04, 0.5, 0.8 };\n\n    std::vector<HestonParameter> params;\n    params.push_back(equityfx);\n    params.push_back(highCorr);\n    params.push_back(lowVolOfVol);\n    params.push_back(highVolOfVol);\n    params.push_back(kappaEqSigRho);\n\n    const Real tol[] = { 1e-3, 1e-3, 0.2, 0.01, 1e-3 };\n\n    for (std::vector<HestonParameter>::const_iterator iter = params.begin();\n         iter != params.end(); ++iter) {\n\n        Handle<Quote> s0(ext::make_shared<SimpleQuote>(1.0));\n        ext::shared_ptr<HestonProcess> process(\n            ext::make_shared<HestonProcess>(\n            riskFreeTS, dividendTS,\n            s0, iter->v0, iter->kappa,\n            iter->theta, iter->sigma, iter->rho));\n\n        ext::shared_ptr<HestonModel> model(\n            ext::make_shared<HestonModel>(process));\n\n        ext::shared_ptr<AnalyticHestonEngine> lobattoEngine(\n            ext::make_shared<AnalyticHestonEngine>(model, 1e-10,\n                                                       1000000));\n        ext::shared_ptr<AnalyticHestonEngine> laguerreEngine(\n            ext::make_shared<AnalyticHestonEngine>(model, 128));\n        ext::shared_ptr<AnalyticHestonEngine> legendreEngine(\n            ext::make_shared<AnalyticHestonEngine>(\n                model, AnalyticHestonEngine::Gatheral,\n                AnalyticHestonEngine::Integration::gaussLegendre(512)));\n        ext::shared_ptr<AnalyticHestonEngine> chebyshevEngine(\n            ext::make_shared<AnalyticHestonEngine>(\n                model, AnalyticHestonEngine::Gatheral,\n                AnalyticHestonEngine::Integration::gaussChebyshev(512)));\n        ext::shared_ptr<AnalyticHestonEngine> chebyshev2ndEngine(\n            ext::make_shared<AnalyticHestonEngine>(\n                model, AnalyticHestonEngine::Gatheral,\n                AnalyticHestonEngine::Integration::gaussChebyshev2nd(512)));\n\n        Real maxLegendreDiff    = 0.0;\n        Real maxChebyshevDiff   = 0.0;\n        Real maxChebyshev2ndDiff= 0.0;\n        Real maxLaguerreDiff    = 0.0;\n\n        for (Size i=0; i < LENGTH(maturities); ++i) {\n            ext::shared_ptr<Exercise> exercise(\n                ext::make_shared<EuropeanExercise>(settlementDate\n                                     + Period(maturities[i], Months)));\n\n            for (Size j=0; j < LENGTH(strikes); ++j) {\n                for (Size k=0; k < LENGTH(types); ++k) {\n\n                    ext::shared_ptr<StrikedTypePayoff> payoff(\n                        ext::make_shared<PlainVanillaPayoff>(types[k], strikes[j]));\n\n                    VanillaOption option(payoff, exercise);\n\n                    option.setPricingEngine(lobattoEngine);\n                    const Real lobattoNPV = option.NPV();\n\n                    option.setPricingEngine(laguerreEngine);\n                    const Real laguerre = option.NPV();\n\n                    option.setPricingEngine(legendreEngine);\n                    const Real legendre = option.NPV();\n\n                    option.setPricingEngine(chebyshevEngine);\n                    const Real chebyshev = option.NPV();\n\n                    option.setPricingEngine(chebyshev2ndEngine);\n                    const Real chebyshev2nd = option.NPV();\n\n                    maxLaguerreDiff\n                        = std::max(maxLaguerreDiff,\n                                   std::fabs(lobattoNPV-laguerre));\n                    maxLegendreDiff\n                        = std::max(maxLegendreDiff,\n                                   std::fabs(lobattoNPV-legendre));\n                    maxChebyshevDiff\n                        = std::max(maxChebyshevDiff,\n                                   std::fabs(lobattoNPV-chebyshev));\n                    maxChebyshev2ndDiff\n                        = std::max(maxChebyshev2ndDiff,\n                                   std::fabs(lobattoNPV-chebyshev2nd));\n\n                }\n            }\n        }\n        const Real maxDiff = std::max(std::max(\n            std::max(maxLaguerreDiff,maxLegendreDiff),\n                                     maxChebyshevDiff), maxChebyshev2ndDiff);\n\n        const Real tr = tol[iter - params.begin()];\n        if (maxDiff > tr) {\n            BOOST_ERROR(\"Failed to reproduce Heston pricing values \"\n                        \"within given tolerance\"\n                        << \"\\n    maxDifference: \" << maxDiff\n                        << \"\\n    tolerance:     \" << tr);\n        }\n    }\n}\n\nvoid HestonModelTest::testMultipleStrikesEngine() {\n    BOOST_TEST_MESSAGE(\"Testing multiple-strikes FD Heston engine...\");\n\n    SavedSettings backup;\n\n    Date settlementDate(27, December, 2004);\n    Settings::instance().evaluationDate() = settlementDate;\n\n    DayCounter dayCounter = ActualActual();\n    Date exerciseDate(28, March, 2006);\n\n    ext::shared_ptr<Exercise> exercise(\n        ext::make_shared<EuropeanExercise>(exerciseDate));\n\n    Handle<YieldTermStructure> riskFreeTS(flatRate(0.06, dayCounter));\n    Handle<YieldTermStructure> dividendTS(flatRate(0.02, dayCounter));\n\n    Handle<Quote> s0(ext::make_shared<SimpleQuote>(1.05));\n\n    ext::shared_ptr<HestonProcess> process(\n        ext::make_shared<HestonProcess>(\n                     riskFreeTS, dividendTS, s0, 0.16, 2.5, 0.09, 0.8, -0.8));\n    ext::shared_ptr<HestonModel> model(\n        ext::make_shared<HestonModel>(process));\n\n    std::vector<Real> strikes;\n    strikes.push_back(1.0);  strikes.push_back(0.5);\n    strikes.push_back(0.75); strikes.push_back(1.5); strikes.push_back(2.0);\n\n    ext::shared_ptr<FdHestonVanillaEngine> singleStrikeEngine(\n        ext::make_shared<FdHestonVanillaEngine>(model, 20, 400, 50));\n    ext::shared_ptr<FdHestonVanillaEngine> multiStrikeEngine(\n        ext::make_shared<FdHestonVanillaEngine>(model, 20, 400, 50));\n    multiStrikeEngine->enableMultipleStrikesCaching(strikes);\n\n    Real relTol = 5e-3;\n    for (Size i=0; i < strikes.size(); ++i) {\n        ext::shared_ptr<StrikedTypePayoff> payoff(\n            ext::make_shared<PlainVanillaPayoff>(Option::Put, strikes[i]));\n\n        VanillaOption aOption(payoff, exercise);\n        aOption.setPricingEngine(multiStrikeEngine);\n\n        Real npvCalculated   = aOption.NPV();\n        Real deltaCalculated = aOption.delta();\n        Real gammaCalculated = aOption.gamma();\n        Real thetaCalculated = aOption.theta();\n\n        aOption.setPricingEngine(singleStrikeEngine);\n        Real npvExpected   = aOption.NPV();\n        Real deltaExpected = aOption.delta();\n        Real gammaExpected = aOption.gamma();\n        Real thetaExpected = aOption.theta();\n\n        if (std::fabs(npvCalculated-npvExpected)/npvExpected > relTol) {\n            BOOST_FAIL(\"failed to reproduce price with FD multi strike engine\"\n                       << \"\\n    calculated: \" << npvCalculated\n                       << \"\\n    expected:   \" << npvExpected\n                       << \"\\n    error:      \" << std::scientific << relTol);\n        }\n        if (std::fabs(deltaCalculated-deltaExpected)/deltaExpected > relTol) {\n            BOOST_FAIL(\"failed to reproduce delta with FD multi strike engine\"\n                       << \"\\n    calculated: \" << deltaCalculated\n                       << \"\\n    expected:   \" << deltaExpected\n                       << \"\\n    error:      \" << std::scientific << relTol);\n        }\n        if (std::fabs(gammaCalculated-gammaExpected)/gammaExpected > relTol) {\n            BOOST_FAIL(\"failed to reproduce gamma with FD multi strike engine\"\n                       << \"\\n    calculated: \" << gammaCalculated\n                       << \"\\n    expected:   \" << gammaExpected\n                       << \"\\n    error:      \" << std::scientific << relTol);\n        }\n        if (std::fabs(thetaCalculated-thetaExpected)/thetaExpected > relTol) {\n            BOOST_FAIL(\"failed to reproduce theta with FD multi strike engine\"\n                       << \"\\n    calculated: \" << thetaCalculated\n                       << \"\\n    expected:   \" << thetaExpected\n                       << \"\\n    error:      \" << std::scientific << relTol);\n        }\n    }\n}\n\n\n\nvoid HestonModelTest::testAnalyticPiecewiseTimeDependent() {\n    BOOST_TEST_MESSAGE(\"Testing analytic piecewise time dependent Heston prices...\");\n\n    SavedSettings backup;\n\n    Date settlementDate(27, December, 2004);\n    Settings::instance().evaluationDate() = settlementDate;\n    DayCounter dayCounter = ActualActual();\n    Date exerciseDate(28, March, 2005);\n\n    ext::shared_ptr<StrikedTypePayoff> payoff(\n        ext::make_shared<PlainVanillaPayoff>(Option::Call, 1.0));\n    ext::shared_ptr<Exercise> exercise(\n        ext::make_shared<EuropeanExercise>(exerciseDate));\n\n    std::vector<Date> dates; \n    dates.push_back(settlementDate); dates.push_back(Date(01, January, 2007));\n    std::vector<Rate> irates;\n    irates.push_back(0.0); irates.push_back(0.2);\n    Handle<YieldTermStructure> riskFreeTS(\n        ext::make_shared<ZeroCurve>(dates, irates, dayCounter));\n\n    std::vector<Rate> qrates;\n    qrates.push_back(0.0); qrates.push_back(0.3);\n    Handle<YieldTermStructure> dividendTS(\n        ext::make_shared<ZeroCurve>(dates, qrates, dayCounter));\n    \n\n    const Real v0 = 0.1;\n    Handle<Quote> s0(ext::make_shared<SimpleQuote>(1.0));\n\n    ConstantParameter theta(0.09, PositiveConstraint());\n    ConstantParameter kappa(3.16, PositiveConstraint());\n    ConstantParameter sigma(4.40, PositiveConstraint());\n    ConstantParameter rho  (-0.8, BoundaryConstraint(-1.0, 1.0));\n\n    ext::shared_ptr<PiecewiseTimeDependentHestonModel> model =\n        ext::make_shared<PiecewiseTimeDependentHestonModel>(\n                                              riskFreeTS, dividendTS,\n                                              s0, v0, theta, kappa, \n                                              sigma, rho, TimeGrid(20.0, 2));\n    \n    VanillaOption option(payoff, exercise);\n\n    ext::shared_ptr<HestonProcess> hestonProcess(\n        ext::make_shared<HestonProcess>(\n                          riskFreeTS, dividendTS, s0, v0,\n                          kappa(0.0), theta(0.0), sigma(0.0), rho(0.0)));\n    ext::shared_ptr<HestonModel> hestonModel =\n        ext::make_shared<HestonModel>(hestonProcess);\n    option.setPricingEngine(\n        ext::make_shared<AnalyticHestonEngine>(hestonModel));\n    \n    const Real expected = option.NPV();\n\n    option.setPricingEngine(ext::shared_ptr<PricingEngine>(\n         new AnalyticPTDHestonEngine(model)));\n\n    const Real calculatedGatheral = option.NPV();\n    if (std::fabs(calculatedGatheral-expected) > 1e-12) {\n        BOOST_ERROR(\"failed to reproduce Heston prices with Gatheral ChF\"\n                   << \"\\n    calculated: \" << calculatedGatheral\n                   << \"\\n    expected:   \" << expected);\n    }\n\n    option.setPricingEngine(ext::shared_ptr<PricingEngine>(\n         new AnalyticPTDHestonEngine(\n             model,\n             AnalyticPTDHestonEngine::AndersenPiterbarg,\n             AnalyticPTDHestonEngine::Integration::gaussLaguerre(164))));\n    const Real calculatedAndersenPiterbarg = option.NPV();\n\n    if (std::fabs(calculatedAndersenPiterbarg-expected) > 1e-8) {\n        BOOST_ERROR(\"failed to reproduce Heston prices Andersen-Piterbarg\"\n                   << \"\\n    calculated: \" << calculatedAndersenPiterbarg\n                   << \"\\n    expected:   \" << expected);\n    }\n}\n\nvoid HestonModelTest::testDAXCalibrationOfTimeDependentModel() {\n    BOOST_TEST_MESSAGE(\n             \"Testing time-dependent Heston model calibration...\");\n\n    SavedSettings backup;\n\n    Date settlementDate(5, July, 2002);\n    Settings::instance().evaluationDate() = settlementDate;\n\n    CalibrationMarketData marketData = getDAXCalibrationMarketData();\n    \n    const Handle<YieldTermStructure> riskFreeTS = marketData.riskFreeTS;\n    const Handle<YieldTermStructure> dividendTS = marketData.dividendYield;\n    const Handle<Quote> s0 = marketData.s0;\n\n    const std::vector<ext::shared_ptr<CalibrationHelper> >& options = marketData.options;\n\n    std::vector<Time> modelTimes;\n    modelTimes.push_back(0.25);\n    modelTimes.push_back(10.0);\n    const TimeGrid modelGrid(modelTimes.begin(), modelTimes.end());\n\n    const Real v0=0.1;\n    ConstantParameter sigma( 0.5, PositiveConstraint());\n    ConstantParameter theta( 0.1, PositiveConstraint());\n    ConstantParameter rho( -0.5, BoundaryConstraint(-1.0, 1.0));\n   \n    std::vector<Time> pTimes(1, 0.25);\n    PiecewiseConstantParameter kappa(pTimes, PositiveConstraint());\n    \n    for (Size i=0; i < pTimes.size()+1; ++i) {\n        kappa.setParam(i, 10.0);\n    }\n\n    ext::shared_ptr<PiecewiseTimeDependentHestonModel> model =\n        ext::make_shared<PiecewiseTimeDependentHestonModel>(\n                                              riskFreeTS, dividendTS,\n                                              s0, v0, theta, kappa, \n                                              sigma, rho, modelGrid);\n\n    const ext::shared_ptr<PricingEngine> engines[] = {\n        ext::make_shared<AnalyticPTDHestonEngine>(model),\n        ext::make_shared<AnalyticPTDHestonEngine>(\n            model,\n            AnalyticPTDHestonEngine::AndersenPiterbarg,\n            AnalyticPTDHestonEngine::Integration::gaussLaguerre(64)),\n        ext::make_shared<AnalyticPTDHestonEngine>(\n            model,\n            AnalyticPTDHestonEngine::AndersenPiterbarg,\n            AnalyticPTDHestonEngine::Integration::discreteTrapezoid(72))\n    };\n    \n    for (Size j=0; j < LENGTH(engines); ++j) {\n        const ext::shared_ptr<PricingEngine> engine = engines[j];\n\n        for (Size i=0; i < options.size(); ++i)\n            ext::dynamic_pointer_cast<BlackCalibrationHelper>(options[i])->setPricingEngine(engine);\n\n        LevenbergMarquardt om(1e-8, 1e-8, 1e-8);\n        model->calibrate(options, om,\n            EndCriteria(400, 40, 1.0e-8, 1.0e-8, 1.0e-8));\n    \n        Real sse = 0;\n        for (Size i = 0; i < 13*8; ++i) {\n            const Real diff = options[i]->calibrationError()*100.0;\n            sse += diff*diff;\n        }\n\n        Real expected = 74.4;\n        if (std::fabs(sse - expected) > 1.0) {\n            BOOST_ERROR(\"Failed to reproduce calibration error\"\n                       << \"\\n    calculated: \" << sse\n                       << \"\\n    expected:   \" << expected);\n        }\n    }\n}\n\nvoid HestonModelTest::testAlanLewisReferencePrices() {\n    BOOST_TEST_MESSAGE(\"Testing Alan Lewis reference prices...\");\n\n    /*\n     * testing Alan Lewis reference prices posted in\n     * http://wilmott.com/messageview.cfm?catid=34&threadid=90957\n     */\n\n    SavedSettings backup;\n\n    const Date settlementDate(5, July, 2002);\n    Settings::instance().evaluationDate() = settlementDate;\n\n    const Date maturityDate(5, July, 2003);\n    const ext::shared_ptr<Exercise> exercise(\n        ext::make_shared<EuropeanExercise>(maturityDate));\n\n    const DayCounter dayCounter = Actual365Fixed();\n    const Handle<YieldTermStructure> riskFreeTS(flatRate(0.01, dayCounter));\n    const Handle<YieldTermStructure> dividendTS(flatRate(0.02, dayCounter));\n\n    const Handle<Quote> s0(ext::make_shared<SimpleQuote>(100.0));\n\n    const Real v0    =  0.04;\n    const Real rho   = -0.5;\n    const Real sigma =  1.0;\n    const Real kappa =  4.0;\n    const Real theta =  0.25;\n\n    const ext::shared_ptr<HestonProcess> process(\n        ext::make_shared<HestonProcess>(\n            riskFreeTS, dividendTS, s0, v0, kappa, theta, sigma, rho));\n    const ext::shared_ptr<HestonModel> model(\n        ext::make_shared<HestonModel>(process));\n\n    const ext::shared_ptr<PricingEngine> laguerreEngine(\n        ext::make_shared<AnalyticHestonEngine>(model, 128U));\n\n    const ext::shared_ptr<PricingEngine> gaussLobattoEngine(\n        ext::make_shared<AnalyticHestonEngine>(model, QL_EPSILON, 100000U));\n\n    const ext::shared_ptr<PricingEngine> cosEngine(\n        ext::make_shared<COSHestonEngine>(model, 20, 400));\n\n    const ext::shared_ptr<PricingEngine> exponentialFittingEngine(\n        ext::make_shared<ExponentialFittingHestonEngine>(model));\n\n    const ext::shared_ptr<PricingEngine> andersenPiterbargEngine(\n        new AnalyticHestonEngine(\n            model,\n            AnalyticHestonEngine::AndersenPiterbarg,\n            AnalyticHestonEngine::Integration::discreteTrapezoid(92),\n            QL_EPSILON));\n\n    const Real strikes[] = { 80, 90, 100, 110, 120 };\n    const Option::Type types[] = { Option::Put, Option::Call };\n    const ext::shared_ptr<PricingEngine> engines[]\n        = { laguerreEngine, gaussLobattoEngine,\n            cosEngine, andersenPiterbargEngine, exponentialFittingEngine };\n\n    const Real expectedResults[][2] = {\n        { 7.958878113256768285213263077598987193482161301733,\n          26.774758743998854221382195325726949201687074848341 },\n        { 12.017966707346304987709573290236471654992071308187,\n          20.933349000596710388139445766564068085476194042256 },\n        { 17.055270961270109413522653999411000974895436309183,\n          16.070154917028834278213466703938231827658768230714 },\n        { 23.017825898442800538908781834822560777763225722188,\n          12.132211516709844867860534767549426052805766831181 },\n        { 29.811026202682471843340682293165857439167301370697,\n          9.024913483457835636553375454092357136489051667150  }\n    };\n\n    const Real tol = 1e-12; // 3e-15 works on linux/ia32,\n                            // but keep some buffer for other platforms\n\n    for (Size i=0; i < LENGTH(strikes); ++i) {\n        const Real strike = strikes[i];\n\n        for (Size j=0; j < LENGTH(types); ++j) {\n            const Option::Type type = types[j];\n\n            for (Size k=0; k < LENGTH(engines); ++k) {\n                const ext::shared_ptr<PricingEngine> engine = engines[k];\n\n                const ext::shared_ptr<StrikedTypePayoff> payoff(\n                    ext::make_shared<PlainVanillaPayoff>(type, strike));\n\n                VanillaOption option(payoff, exercise);\n                option.setPricingEngine(engine);\n\n                const Real expected = expectedResults[i][j];\n                const Real calculated = option.NPV();\n                const Real relError = std::fabs(calculated-expected)/expected;\n\n                if (relError > tol || boost::math::isnan(calculated)) {\n                    BOOST_ERROR(\n                           \"failed to reproduce Alan Lewis Reference prices \"\n                        << \"\\n    strike     : \" << strike\n                        << \"\\n    option type: \" << type\n                        << \"\\n    engine type: \" << k\n                        << \"\\n    rel. error : \" << relError);\n                }\n            }\n        }\n    }\n}\n\nvoid HestonModelTest::testAnalyticPDFHestonEngine() {\n    BOOST_TEST_MESSAGE(\"Testing analytic PDF Heston engine...\");\n\n    SavedSettings backup;\n\n    const Date settlementDate(5, January, 2014);\n    Settings::instance().evaluationDate() = settlementDate;\n\n    const DayCounter dayCounter = Actual365Fixed();\n    const Handle<YieldTermStructure> riskFreeTS(flatRate(0.07, dayCounter));\n    const Handle<YieldTermStructure> dividendTS(flatRate(0.185, dayCounter));\n\n    const Handle<Quote> s0(ext::make_shared<SimpleQuote>(100.0));\n\n    const Real v0    =  0.1;\n    const Real rho   = -0.5;\n    const Real sigma =  1.0;\n    const Real kappa =  4.0;\n    const Real theta =  0.05;\n\n    const ext::shared_ptr<HestonModel> model(\n        ext::make_shared<HestonModel>(\n            ext::make_shared<HestonProcess>(riskFreeTS, dividendTS,\n                              s0, v0, kappa, theta, sigma, rho)));\n\n    const Real tol = 1e-6;\n    const ext::shared_ptr<AnalyticPDFHestonEngine> pdfEngine(\n        ext::make_shared<AnalyticPDFHestonEngine>(model, tol));\n\n    const ext::shared_ptr<PricingEngine> analyticEngine(\n        ext::make_shared<AnalyticHestonEngine>(model, 178));\n\n    const Date maturityDate(5, July, 2014);\n    const Time maturity = dayCounter.yearFraction(settlementDate, maturityDate);\n    const ext::shared_ptr<Exercise> exercise(\n        ext::make_shared<EuropeanExercise>(maturityDate));\n\n    // 1. check a plain vanilla call option\n    for (Real strike=40; strike < 190; strike+=20) {\n        const ext::shared_ptr<StrikedTypePayoff> vanillaPayoff(\n            ext::make_shared<PlainVanillaPayoff>(Option::Call, strike));\n\n        VanillaOption planVanillaOption(vanillaPayoff, exercise);\n\n        planVanillaOption.setPricingEngine(pdfEngine);\n        const Real calculated = planVanillaOption.NPV();\n\n        planVanillaOption.setPricingEngine(analyticEngine);\n        const Real expected = planVanillaOption.NPV();\n\n        if (std::fabs(calculated-expected) > 3*tol) {\n            BOOST_FAIL(\n                   \"failed to reproduce plain vanilla european prices with\"\n                   \" the analytic probability density engine\"\n                << \"\\n    strike     : \" << strike\n                << \"\\n    expected   : \" << expected\n                << \"\\n    calculated : \" << calculated\n                << \"\\n    diff       : \" << std::fabs(calculated-expected)\n                << \"\\n    tol        ; \" << tol);\n        }\n    }\n\n    // 2. digital call option (approx. with a call spread)\n    for (Real strike=40; strike < 190; strike+=10) {\n        VanillaOption digitalOption(\n            ext::make_shared<CashOrNothingPayoff>(Option::Call, strike, 1.0),\n            exercise);\n        digitalOption.setPricingEngine(pdfEngine);\n        const Real calculated = digitalOption.NPV();\n\n        const Real eps = 0.01;\n        VanillaOption longCall(\n            ext::make_shared<PlainVanillaPayoff>(Option::Call, strike-eps),\n            exercise);\n        longCall.setPricingEngine(analyticEngine);\n\n        VanillaOption shortCall(\n            ext::make_shared<PlainVanillaPayoff>(Option::Call, strike+eps),\n            exercise);\n        shortCall.setPricingEngine(analyticEngine);\n\n        const Real expected = (longCall.NPV() - shortCall.NPV())/(2*eps);\n        if (std::fabs(calculated-expected) > tol) {\n            BOOST_FAIL(\n                   \"failed to reproduce european digital prices with\"\n                   \" the analytic probability density engine\"\n                << \"\\n    strike     : \" << strike\n                << \"\\n    expected   : \" << expected\n                << \"\\n    calculated : \" << calculated\n                << \"\\n    diff       : \" << std::fabs(calculated-expected)\n                << \"\\n    tol        : \" << tol);\n        }\n\n        const DiscountFactor d = riskFreeTS->discount(maturityDate);\n        const Real expectedCDF = 1.0 - expected/d;\n        const Real calculatedCDF = pdfEngine->cdf(strike, maturity);\n\n        if (std::fabs(expectedCDF - calculatedCDF) > tol) {\n            BOOST_FAIL(\n                   \"failed to reproduce cumulative distribution function\"\n                << \"\\n    strike        : \" << strike\n                << \"\\n    expected CDF  : \" << expectedCDF\n                << \"\\n    calculated CDF: \" << calculatedCDF\n                << \"\\n    diff          : \"\n                << std::fabs(calculatedCDF-expectedCDF)\n                << \"\\n    tol           : \" << tol);\n\n        }\n    }\n}\n\nvoid HestonModelTest::testExpansionOnAlanLewisReference() {\n    BOOST_TEST_MESSAGE(\"Testing expansion on Alan Lewis reference prices...\");\n\n    SavedSettings backup;\n\n    const Date settlementDate(5, July, 2002);\n    Settings::instance().evaluationDate() = settlementDate;\n\n    const Date maturityDate(5, July, 2003);\n    const ext::shared_ptr<Exercise> exercise =\n        ext::make_shared<EuropeanExercise>(maturityDate);\n\n    const DayCounter dayCounter = Actual365Fixed();\n    const Handle<YieldTermStructure> riskFreeTS(flatRate(0.01, dayCounter));\n    const Handle<YieldTermStructure> dividendTS(flatRate(0.02, dayCounter));\n\n    const Handle<Quote> s0(ext::make_shared<SimpleQuote>(100.0));\n\n    const Real v0    =  0.04;\n    const Real rho   = -0.5;\n    const Real sigma =  1.0;\n    const Real kappa =  4.0;\n    const Real theta =  0.25;\n\n    const ext::shared_ptr<HestonProcess> process =\n        ext::make_shared<HestonProcess>(riskFreeTS, dividendTS, s0, v0,\n                                          kappa, theta, sigma, rho);\n    const ext::shared_ptr<HestonModel> model =\n        ext::make_shared<HestonModel>(process);\n\n    const ext::shared_ptr<PricingEngine> lpp2Engine =\n        ext::make_shared<HestonExpansionEngine>(model,\n                                                  HestonExpansionEngine::LPP2);\n    //don't test Forde as it does not behave well on this example\n    const ext::shared_ptr<PricingEngine> lpp3Engine =\n        ext::make_shared<HestonExpansionEngine>(model,\n                                                  HestonExpansionEngine::LPP3);\n\n    const Real strikes[] = { 80, 90, 100, 110, 120 };\n    const Option::Type types[] = { Option::Put, Option::Call };\n    const ext::shared_ptr<PricingEngine> engines[]\n        = { lpp2Engine, lpp3Engine };\n\n    const Real expectedResults[][2] = {\n        { 7.958878113256768285213263077598987193482161301733,\n          26.774758743998854221382195325726949201687074848341 },\n        { 12.017966707346304987709573290236471654992071308187,\n          20.933349000596710388139445766564068085476194042256 },\n        { 17.055270961270109413522653999411000974895436309183,\n          16.070154917028834278213466703938231827658768230714 },\n        { 23.017825898442800538908781834822560777763225722188,\n          12.132211516709844867860534767549426052805766831181 },\n        { 29.811026202682471843340682293165857439167301370697,\n          9.024913483457835636553375454092357136489051667150  }\n    };\n\n    const Real tol[2] = {1.003e-2, 3.645e-3};\n\n    for (Size i=0; i < LENGTH(strikes); ++i) {\n        const Real strike = strikes[i];\n\n        for (Size j=0; j < LENGTH(types); ++j) {\n            const Option::Type type = types[j];\n\n            for (Size k=0; k < LENGTH(engines); ++k) {\n                const ext::shared_ptr<PricingEngine> engine = engines[k];\n\n                const ext::shared_ptr<StrikedTypePayoff> payoff =\n                    ext::make_shared<PlainVanillaPayoff>(type, strike);\n\n                VanillaOption option(payoff, exercise);\n                option.setPricingEngine(engine);\n\n                const Real expected = expectedResults[i][j];\n                const Real calculated = option.NPV();\n                const Real relError = std::fabs(calculated-expected)/expected;\n\n                if (relError > tol[k]) {\n                    BOOST_ERROR(\n                           \"failed to reproduce Alan Lewis Reference prices \"\n                        << \"\\n    strike     : \" << strike\n                        << \"\\n    option type: \" << type\n                        << \"\\n    engine type: \" << k\n                        << \"\\n    rel. error : \" << relError);\n                }\n            }\n        }\n    }\n}\n\nvoid HestonModelTest::testExpansionOnFordeReference() {\n    BOOST_TEST_MESSAGE(\"Testing expansion on Forde reference prices...\");\n\n    SavedSettings backup;\n\n    const Real forward = 100.0;\n    const Real v0      =  0.04;\n    const Real rho     = -0.4;\n    const Real sigma   =  0.2;\n    const Real kappa   =  1.15;\n    const Real theta   =  0.04;\n\n    const Real terms[] = {0.1, 1.0, 5.0, 10.0};\n\n    const Real strikes[] = { 60, 80, 90, 100, 110, 120, 140 };\n\n    const Real referenceVols[][7] = {\n       {0.27284673574924445, 0.22360758200372477, 0.21023988547031242, 0.1990674789471587, 0.19118230678920461, 0.18721342919371017, 0.1899869903378507},\n       {0.25200775151345, 0.2127275920953156, 0.20286528150874591, 0.19479398358151515, 0.18872591728967686, 0.18470857955411824, 0.18204457060905446},\n       {0.21637821506229973, 0.20077227130455172, 0.19721753043236154, 0.1942233023784151, 0.191693211401571, 0.18955229722896752, 0.18491727548069495},\n       {0.20672925973965342, 0.198583062164427, 0.19668274423922746, 0.1950420231354201, 0.193610364344706, 0.1923502827886502, 0.18934360917857015}\n    };\n\n    const Real tol[][4] = {\n        {0.06, 0.03, 0.03, 0.02},\n        {0.15, 0.08, 0.04, 0.02},\n        {0.06, 0.08, 1.0, 1.0} //forde breaks down for long maturities\n    };\n    const Real tolAtm[][4] = {\n        {4e-6, 7e-4, 2e-3, 9e-4},\n        {7e-6, 4e-4, 9e-4, 4e-4},\n        {4e-4, 3e-2, 0.28, 1.0}\n    };\n    for (Size j=0; j < LENGTH(terms); ++j) {\n        const Real term = terms[j];\n        const ext::shared_ptr<HestonExpansion> lpp2 =\n            ext::make_shared<LPP2HestonExpansion>(kappa, theta, sigma,\n                                                    v0, rho, term);\n        const ext::shared_ptr<HestonExpansion> lpp3 =\n            ext::make_shared<LPP3HestonExpansion>(kappa, theta, sigma,\n                                                    v0, rho, term);\n        const ext::shared_ptr<HestonExpansion> forde =\n            ext::make_shared<FordeHestonExpansion>(kappa, theta, sigma,\n                                                     v0, rho, term);\n        const ext::shared_ptr<HestonExpansion> expansions[] = { lpp2, lpp3, forde };\n        for (Size i=0; i < LENGTH(strikes); ++i) {\n            const Real strike = strikes[i];\n            for (Size k=0; k < LENGTH(expansions); ++k) {\n                const ext::shared_ptr<HestonExpansion> expansion = expansions[k];\n\n                const Real expected = referenceVols[j][i];\n                const Real calculated = expansion->impliedVolatility(strike, forward);\n                const Real relError = std::fabs(calculated-expected)/expected;\n                const Real refTol = strike == forward ? tolAtm[k][j] : tol[k][j];\n                if (relError > refTol) {\n                    BOOST_ERROR(\n                           \"failed to reproduce Forde reference vols \"\n                        << \"\\n    strike        : \" << strike\n                        << \"\\n    expansion type: \" << k\n                        << \"\\n    rel. error    : \" << relError);\n                }\n            }\n        }\n    }\n}\n\nnamespace {\n    void reportOnIntegrationMethodTest(VanillaOption& option,\n                                       const ext::shared_ptr<HestonModel>& model,\n                                       const AnalyticHestonEngine::Integration& integration,\n                                       AnalyticHestonEngine::ComplexLogFormula formula,\n                                       bool isAdaptive,\n                                       Real expected,\n                                       Real tol,\n                                       Size valuations,\n                                       const std::string& method) {\n\n        if (integration.isAdaptiveIntegration() != isAdaptive)\n            BOOST_ERROR(method << \" is not an adaptive integration routine\");\n\n        const ext::shared_ptr<AnalyticHestonEngine> engine =\n            ext::make_shared<AnalyticHestonEngine>(\n                model, formula, integration, 1e-9);\n\n        option.setPricingEngine(engine);\n        const Real calculated = option.NPV();\n\n        const Real error = std::fabs(calculated - expected);\n\n        if (boost::math::isnan(error) || error > tol) {\n            BOOST_ERROR(\"failed to reproduce simple Heston Pricing with \"\n                    << \"\\n    integration method: \" << method\n                    <<  std::setprecision(12)\n                    << \"\\n    expected          : \" << expected\n                    << \"\\n    calculated        : \" << calculated\n                    << \"\\n    error             : \" << error);\n        }\n\n        if (   valuations != Null<Size>()\n            && valuations != engine->numberOfEvaluations()) {\n            BOOST_ERROR(\"nubmer of function evaluations does not match \"\n                    << \"\\n    integration method      : \" << method\n                    << \"\\n    expected function calls : \" << valuations\n                    << \"\\n    number of function calls: \"\n                    << engine->numberOfEvaluations());\n        }\n    }\n}\n\nvoid HestonModelTest::testAllIntegrationMethods() {\n    BOOST_TEST_MESSAGE(\"Testing semi-analytic Heston pricing with all \"\n                       \"integration methods...\");\n\n    SavedSettings backup;\n\n    const Date settlementDate(7, February, 2017);\n    Settings::instance().evaluationDate() = settlementDate;\n\n    const DayCounter dayCounter = Actual365Fixed();\n    const Handle<YieldTermStructure> riskFreeTS(flatRate(0.05, dayCounter));\n    const Handle<YieldTermStructure> dividendTS(flatRate(0.075, dayCounter));\n\n    const Handle<Quote> s0(ext::make_shared<SimpleQuote>(100.0));\n\n    const Real v0    =  0.1;\n    const Real rho   = -0.75;\n    const Real sigma =  0.4;\n    const Real kappa =  4.0;\n    const Real theta =  0.05;\n\n    const ext::shared_ptr<HestonModel> model =\n        ext::make_shared<HestonModel>(\n            ext::make_shared<HestonProcess>(\n                riskFreeTS, dividendTS,\n                s0, v0, kappa, theta, sigma, rho));\n\n    const ext::shared_ptr<StrikedTypePayoff> payoff =\n        ext::make_shared<PlainVanillaPayoff>(Option::Put, s0->value());\n\n    const Date maturityDate = settlementDate + Period(1, Years);\n    const ext::shared_ptr<Exercise> exercise =\n        ext::make_shared<EuropeanExercise>(maturityDate);\n\n    VanillaOption option(payoff, exercise);\n\n    const Real tol = 1e-8;\n    const Real expected = 10.147041515497;\n\n    // Gauss-Laguerre with Gatheral logarithm integration method\n    reportOnIntegrationMethodTest(option, model,\n        AnalyticHestonEngine::Integration::gaussLaguerre(),\n        AnalyticHestonEngine::Gatheral,\n        false, expected, tol, 256, \"Gauss-Laguerre with Gatheral logarithm\");\n\n    // Gauss-Laguerre with branch correction integration method\n    reportOnIntegrationMethodTest(option, model,\n        AnalyticHestonEngine::Integration::gaussLaguerre(),\n        AnalyticHestonEngine::BranchCorrection,\n        false, expected, tol, 256, \"Gauss-Laguerre with branch correction\");\n\n    // Gauss-Laguerre with Andersen-Piterbarg integration method\n    reportOnIntegrationMethodTest(option, model,\n        AnalyticHestonEngine::Integration::gaussLaguerre(),\n        AnalyticHestonEngine::AndersenPiterbarg,\n        false, expected, tol, 128,\n        \"Gauss-Laguerre with Andersen Piterbarg control variate\");\n\n    // Gauss-Legendre with Gatheral logarithm integration method\n    reportOnIntegrationMethodTest(option, model,\n        AnalyticHestonEngine::Integration::gaussLegendre(),\n        AnalyticHestonEngine::Gatheral,\n        false, expected, tol, 256, \"Gauss-Legendre with Gatheral logarithm\");\n\n    // Gauss-Legendre with branch correction integration method\n    reportOnIntegrationMethodTest(option, model,\n        AnalyticHestonEngine::Integration::gaussLegendre(),\n        AnalyticHestonEngine::BranchCorrection,\n        false, expected, tol, 256, \"Gauss-Legendre with branch correction\");\n\n    // Gauss-Legendre with Andersen-Piterbarg integration method\n    reportOnIntegrationMethodTest(option, model,\n        AnalyticHestonEngine::Integration::gaussLegendre(256),\n        AnalyticHestonEngine::AndersenPiterbarg,\n        false, expected, 1e-4, 256,\n        \"Gauss-Legendre with Andersen Piterbarg control variate\");\n\n    // Gauss-Chebyshev with Gatheral logarithm integration method\n    reportOnIntegrationMethodTest(option, model,\n        AnalyticHestonEngine::Integration::gaussChebyshev(512),\n        AnalyticHestonEngine::Gatheral,\n        false, expected, 1e-4, 1024, \"Gauss-Chebyshev with Gatheral logarithm\");\n\n    // Gauss-Chebyshev with branch correction integration method\n    reportOnIntegrationMethodTest(option, model,\n        AnalyticHestonEngine::Integration::gaussChebyshev(512),\n        AnalyticHestonEngine::BranchCorrection,\n        false, expected, 1e-4, 1024, \"Gauss-Chebyshev with branch correction\");\n\n    // Gauss-Chebyshev with Andersen-Piterbarg integration method\n    reportOnIntegrationMethodTest(option, model,\n        AnalyticHestonEngine::Integration::gaussChebyshev(512),\n        AnalyticHestonEngine::AndersenPiterbarg,\n        false, expected, 1e-4, 512,\n        \"Gauss-Laguerre with Andersen Piterbarg control variate\");\n\n    // Gauss-Chebyshev2nd with Gatheral logarithm integration method\n    reportOnIntegrationMethodTest(option, model,\n        AnalyticHestonEngine::Integration::gaussChebyshev2nd(512),\n        AnalyticHestonEngine::Gatheral,\n        false, expected, 2e-4, 1024,\n        \"Gauss-Chebyshev2nd with Gatheral logarithm\");\n\n    // Gauss-Chebyshev with branch correction integration method\n    reportOnIntegrationMethodTest(option, model,\n        AnalyticHestonEngine::Integration::gaussChebyshev2nd(512),\n        AnalyticHestonEngine::BranchCorrection,\n        false, expected, 2e-4, 1024,\n        \"Gauss-Chebyshev2nd with branch correction\");\n\n    // Gauss-Chebyshev with Andersen-Piterbarg integration method\n    reportOnIntegrationMethodTest(option, model,\n        AnalyticHestonEngine::Integration::gaussChebyshev2nd(512),\n        AnalyticHestonEngine::AndersenPiterbarg,\n        false, expected, 2e-4, 512,\n        \"Gauss-Chebyshev2nd with Andersen Piterbarg control variate\");\n\n    // Discrete Simpson rule with Gatheral logarithm\n    reportOnIntegrationMethodTest(option, model,\n        AnalyticHestonEngine::Integration::discreteSimpson(512),\n        AnalyticHestonEngine::Gatheral,\n        false, expected, tol, 1024,\n        \"Discrete Simpson rule with Gatheral logarithm\");\n\n    // Discrete Simpson rule with Andersen-Piterbarg integration method\n    reportOnIntegrationMethodTest(option, model,\n        AnalyticHestonEngine::Integration::discreteSimpson(64),\n        AnalyticHestonEngine::AndersenPiterbarg,\n        false, expected, tol, 64,\n        \"Discrete Simpson rule with Andersen Piterbarg control variate\");\n\n    // Discrete Trapezoid rule with Gatheral logarithm\n    reportOnIntegrationMethodTest(option, model,\n        AnalyticHestonEngine::Integration::discreteTrapezoid(512),\n        AnalyticHestonEngine::Gatheral,\n        false, expected, 2e-4, 1024,\n        \"Discrete Trapezoid rule with Gatheral logarithm\");\n\n    // Discrete Trapezoid rule with Andersen-Piterbarg integration method\n    reportOnIntegrationMethodTest(option, model,\n        AnalyticHestonEngine::Integration::discreteTrapezoid(64),\n        AnalyticHestonEngine::AndersenPiterbarg,\n        false, expected, tol, 64,\n        \"Discrete Trapezoid rule with Andersen Piterbarg control variate\");\n\n    // Gauss-Lobatto with Gatheral logarithm\n    reportOnIntegrationMethodTest(option, model,\n        AnalyticHestonEngine::Integration::gaussLobatto(tol, Null<Real>()),\n        AnalyticHestonEngine::Gatheral,\n        true, expected, tol, Null<Size>(),\n        \"Gauss-Lobatto with Gatheral logarithm\");\n\n    // Gauss-Lobatto with Andersen-Piterbarg integration method\n    reportOnIntegrationMethodTest(option, model,\n        AnalyticHestonEngine::Integration::gaussLobatto(tol, Null<Real>()),\n        AnalyticHestonEngine::AndersenPiterbarg,\n        true, expected, tol, Null<Size>(),\n        \"Gauss-Lobatto with Andersen Piterbarg control variate\");\n\n    // Gauss-Konrod with Gatheral logarithm\n    reportOnIntegrationMethodTest(option, model,\n        AnalyticHestonEngine::Integration::gaussKronrod(tol),\n        AnalyticHestonEngine::Gatheral,\n        true, expected, tol, Null<Size>(),\n        \"Gauss-Konrod with Gatheral logarithm\");\n\n    // Gauss-Konrod with Andersen-Piterbarg integration method\n    reportOnIntegrationMethodTest(option, model,\n        AnalyticHestonEngine::Integration::gaussKronrod(tol),\n        AnalyticHestonEngine::AndersenPiterbarg,\n        true, expected, tol, Null<Size>(),\n        \"Gauss-Konrod with Andersen Piterbarg control variate\");\n\n    // Simpson with Gatheral logarithm\n    reportOnIntegrationMethodTest(option, model,\n        AnalyticHestonEngine::Integration::simpson(tol),\n        AnalyticHestonEngine::Gatheral,\n        true, expected, 1e-6, Null<Size>(),\n        \"Simpson with Gatheral logarithm\");\n\n    // Simpson with Andersen-Piterbarg integration method\n    reportOnIntegrationMethodTest(option, model,\n        AnalyticHestonEngine::Integration::simpson(tol),\n        AnalyticHestonEngine::AndersenPiterbarg,\n        true, expected, 1e-6, Null<Size>(),\n        \"Simpson with Andersen Piterbarg control variate\");\n\n    // Trapezoid with Gatheral logarithm\n    reportOnIntegrationMethodTest(option, model,\n        AnalyticHestonEngine::Integration::trapezoid(tol),\n        AnalyticHestonEngine::Gatheral,\n        true, expected, 1e-6, Null<Size>(),\n        \"Trapezoid with Gatheral logarithm\");\n\n    // Trapezoid with Andersen-Piterbarg integration method\n    reportOnIntegrationMethodTest(option, model,\n        AnalyticHestonEngine::Integration::trapezoid(tol),\n        AnalyticHestonEngine::AndersenPiterbarg,\n        true, expected, 1e-6, Null<Size>(),\n        \"Trapezoid with Andersen Piterbarg control variate\");\n}\n\nnamespace {\n    class LogCharacteristicFunction {\n      public:\n        LogCharacteristicFunction(\n            Size n, Time t,\n            const ext::shared_ptr<COSHestonEngine>& engine)\n        : t_(t), alpha_(0.0, 1.0), engine_(engine) {\n            for (Size i=1; i < n; ++i, alpha_*=std::complex<Real>(0,1));\n        }\n\n        Real operator()(Real u) const {\n            return (std::log(engine_->chF(u, t_))/alpha_).real();\n        }\n\n      private:\n        const Time t_;\n        std::complex<Real> alpha_;\n        const ext::shared_ptr<COSHestonEngine> engine_;\n    };\n}\n\nvoid HestonModelTest::testCosHestonCumulants() {\n    BOOST_TEST_MESSAGE(\"Testing Heston COS cumulants...\");\n\n    SavedSettings backup;\n\n    const Date settlementDate(7, February, 2017);\n    Settings::instance().evaluationDate() = settlementDate;\n\n    const DayCounter dayCounter = Actual365Fixed();\n    const Handle<YieldTermStructure> riskFreeTS(flatRate(0.15, dayCounter));\n    const Handle<YieldTermStructure> dividendTS(flatRate(0.075, dayCounter));\n\n    const Handle<Quote> s0(ext::make_shared<SimpleQuote>(100.0));\n\n    const Real v0    =  0.1;\n    const Real rho   = -0.75;\n    const Real sigma =  0.4;\n    const Real kappa =  4.0;\n    const Real theta =  0.25;\n\n    const ext::shared_ptr<HestonModel> model =\n        ext::make_shared<HestonModel>(\n            ext::make_shared<HestonProcess>(\n                riskFreeTS, dividendTS,\n                s0, v0, kappa, theta, sigma, rho));\n\n    const ext::shared_ptr<COSHestonEngine> cosEngine =\n        ext::make_shared<COSHestonEngine>(model);\n\n    const Real tol = 1e-7;\n    const NumericalDifferentiation::Scheme central(\n        NumericalDifferentiation::Central);\n\n    for (Time t=0.01; t < 41.0; t+=t) {\n        const Real nc1 = NumericalDifferentiation(\n            ext::function<Real(Real)>(\n                LogCharacteristicFunction(1, t, cosEngine)),\n            1, 1e-5, 5, central)(0.0);\n\n        const Real c1 = cosEngine->c1(t);\n\n        if (std::fabs(nc1 - c1) > tol) {\n            BOOST_ERROR(\" failed to reproduce first cumulant\"\n                    << \"\\n    expected:   \" << nc1\n                    << \"\\n    calculated: \" << c1\n                    << \"\\n    difference: \" << std::fabs(nc1 - c1));\n        }\n\n        const Real nc2 = NumericalDifferentiation(\n            ext::function<Real(Real)>(\n                LogCharacteristicFunction(2, t, cosEngine)),\n            2, 1e-2, 5, central)(0.0);\n\n        const Real c2 = cosEngine->c2(t);\n\n        if (std::fabs(nc2 - c2) > tol) {\n            BOOST_ERROR(\" failed to reproduce second cumulant\"\n                    << \"\\n    expected:   \" << nc2\n                    << \"\\n    calculated: \" << c2\n                    << \"\\n    difference: \" << std::fabs(nc2 - c2));\n        }\n\n        const Real nc3 = NumericalDifferentiation(\n            ext::function<Real(Real)>(\n                LogCharacteristicFunction(3, t, cosEngine)),\n            3, 5e-3, 7, central)(0.0);\n\n        const Real c3 = cosEngine->c3(t);\n\n        if (std::fabs(nc3 - c3) > tol) {\n            BOOST_ERROR(\" failed to reproduce third cumulant\"\n                    << \"\\n    expected:   \" << nc3\n                    << \"\\n    calculated: \" << c3\n                    << \"\\n    difference: \" << std::fabs(nc3 - c3));\n        }\n\n        const Real nc4 = NumericalDifferentiation(\n            ext::function<Real(Real)>(\n                LogCharacteristicFunction(4, t, cosEngine)),\n            4, 5e-2, 9, central)(0.0);\n\n        const Real c4 = cosEngine->c4(t);\n\n        if (std::fabs(nc4 - c4) > 10*tol) {\n            BOOST_ERROR(\" failed to reproduce 4th cumulant\"\n                    << \"\\n    expected:   \" << nc4\n                    << \"\\n    calculated: \" << c4\n                    << \"\\n    difference: \" << std::fabs(nc4 - c4));\n        }\n    }\n}\n\nvoid HestonModelTest::testCosHestonEngine() {\n    BOOST_TEST_MESSAGE(\"Testing Heston pricing via COS method...\");\n\n    SavedSettings backup;\n\n    const Date settlementDate(7, February, 2017);\n    Settings::instance().evaluationDate() = settlementDate;\n\n    const DayCounter dayCounter = Actual365Fixed();\n    const Handle<YieldTermStructure> riskFreeTS(flatRate(0.15, dayCounter));\n    const Handle<YieldTermStructure> dividendTS(flatRate(0.07, dayCounter));\n\n    const Handle<Quote> s0(ext::make_shared<SimpleQuote>(100.0));\n\n    const Real v0    =  0.1;\n    const Real rho   = -0.75;\n    const Real sigma =  1.8;\n    const Real kappa =  4.0;\n    const Real theta =  0.22;\n\n    const ext::shared_ptr<HestonModel> model =\n        ext::make_shared<HestonModel>(\n            ext::make_shared<HestonProcess>(\n                riskFreeTS, dividendTS,\n                s0, v0, kappa, theta, sigma, rho));\n\n    const Date maturityDate = settlementDate + Period(1, Years);\n\n    const ext::shared_ptr<Exercise> exercise =\n        ext::make_shared<EuropeanExercise>(maturityDate);\n\n    const ext::shared_ptr<PricingEngine> cosEngine(\n        ext::make_shared<COSHestonEngine>(model, 25, 600));\n\n    const ext::shared_ptr<StrikedTypePayoff> payoffs[] = {\n        ext::make_shared<PlainVanillaPayoff>(Option::Call, s0->value()+20),\n        ext::make_shared<PlainVanillaPayoff>(Option::Call, s0->value()+150),\n        ext::make_shared<PlainVanillaPayoff>(Option::Put, s0->value()-20),\n        ext::make_shared<PlainVanillaPayoff>(Option::Put, s0->value()-90)\n    };\n\n    const Real expected[] = {\n        9.364410588426075, 0.01036797658132471,\n        5.319092971836708, 0.01032681906278383 };\n\n    const Real tol = 1e-10;\n\n    for (Size i=0; i < LENGTH(payoffs); ++i) {\n        VanillaOption option(payoffs[i], exercise);\n\n        option.setPricingEngine(cosEngine);\n        const Real calculated = option.NPV();\n\n        const Real error = std::fabs(expected[i] - calculated);\n\n        if (error > tol) {\n            BOOST_ERROR(\" failed to reproduce prices with COSHestonEngine\"\n                    << \"\\n    expected:   \" << expected[i]\n                    << \"\\n    calculated: \" << calculated\n                    << \"\\n    difference: \" << error);\n        }\n    }\n}\n\nvoid HestonModelTest::testCharacteristicFct() {\n    BOOST_TEST_MESSAGE(\"Testing Heston characteristic function...\");\n\n    SavedSettings backup;\n\n    const Date settlementDate(30, March, 2017);\n    Settings::instance().evaluationDate() = settlementDate;\n\n    const DayCounter dayCounter = Actual365Fixed();\n    const Handle<YieldTermStructure> riskFreeTS(flatRate(0.35, dayCounter));\n    const Handle<YieldTermStructure> dividendTS(flatRate(0.17, dayCounter));\n\n    const Handle<Quote> s0(ext::shared_ptr<Quote>(new SimpleQuote(100.0)));\n\n    const Real v0    =  0.1;\n    const Real rho   = -0.85;\n    const Real sigma =  0.8;\n    const Real kappa =  2.0;\n    const Real theta =  0.15;\n\n    const ext::shared_ptr<HestonModel> model =\n        ext::make_shared<HestonModel>(\n            ext::make_shared<HestonProcess>(\n                riskFreeTS, dividendTS,\n                s0, v0, kappa, theta, sigma, rho));\n\n    const Real u[] = { 1.0, 0.45, 3,4 };\n    const Real t[] = { 0.01, 23.2, 3.2};\n\n    const COSHestonEngine cosEngine(model);\n    const AnalyticHestonEngine analyticEngine(model);\n\n    const Real tol = 100*QL_EPSILON;\n    for (Size i=0; i < LENGTH(u); ++i) {\n        for (Size j=0; j < LENGTH(t); ++j) {\n            const std::complex<Real> c = cosEngine.chF(u[i], t[j]);\n            const std::complex<Real> a = analyticEngine.chF(u[i], t[j]);\n\n            const Real error = std::abs(a-c);\n            if (error > tol) {\n                BOOST_ERROR(\" failed to reproduce prices with characteristic Fct\"\n                        << \"\\n    Cos Engine:      \" << c\n                        << \"\\n    analytic engine: \" << a\n                        << \"\\n    difference:      \" << error);\n            }\n        }\n    }\n}\n\nvoid HestonModelTest::testAndersenPiterbargPricing() {\n    BOOST_TEST_MESSAGE(\"Testing Andersen-Piterbarg method to \"\n                       \"price under the Heston model...\");\n\n    SavedSettings backup;\n\n    const Date settlementDate(30, March, 2017);\n    Settings::instance().evaluationDate() = settlementDate;\n\n    const DayCounter dayCounter = Actual365Fixed();\n    const Handle<YieldTermStructure> riskFreeTS(flatRate(0.10, dayCounter));\n    const Handle<YieldTermStructure> dividendTS(flatRate(0.06, dayCounter));\n\n    const Handle<Quote> s0(ext::shared_ptr<Quote>(new SimpleQuote(100.0)));\n\n    const Real v0    =  0.1;\n    const Real rho   =  0.80;\n    const Real sigma =  0.75;\n    const Real kappa =  1.0;\n    const Real theta =  0.1;\n\n    const ext::shared_ptr<HestonModel> model =\n        ext::make_shared<HestonModel>(\n            ext::make_shared<HestonProcess>(\n                riskFreeTS, dividendTS,\n                s0, v0, kappa, theta, sigma, rho));\n\n    const ext::shared_ptr<AnalyticHestonEngine>\n        andersenPiterbargLaguerreEngine(\n            ext::make_shared<AnalyticHestonEngine>(\n                model,\n                AnalyticHestonEngine::AndersenPiterbarg,\n                AnalyticHestonEngine::Integration::gaussLaguerre()));\n\n    const ext::shared_ptr<AnalyticHestonEngine>\n        andersenPiterbargLobattoEngine(\n            ext::make_shared<AnalyticHestonEngine>(\n                model,\n                AnalyticHestonEngine::AndersenPiterbarg,\n                AnalyticHestonEngine::Integration::gaussLobatto(\n                    Null<Real>(), 1e-9, 10000), 1e-9));\n\n    const ext::shared_ptr<AnalyticHestonEngine>\n        andersenPiterbargSimpsonEngine(\n            ext::make_shared<AnalyticHestonEngine>(\n                model,\n                AnalyticHestonEngine::AndersenPiterbarg,\n                AnalyticHestonEngine::Integration::discreteSimpson(256),\n                1e-8));\n\n    const ext::shared_ptr<AnalyticHestonEngine>\n        andersenPiterbargTrapezoidEngine(\n            ext::make_shared<AnalyticHestonEngine>(\n                model,\n                AnalyticHestonEngine::AndersenPiterbarg,\n                AnalyticHestonEngine::Integration::discreteTrapezoid(164),\n                1e-8));\n\n    const ext::shared_ptr<AnalyticHestonEngine>\n        andersenPiterbargTrapezoidEngine2(\n            ext::make_shared<AnalyticHestonEngine>(\n                model,\n                AnalyticHestonEngine::AndersenPiterbarg,\n                AnalyticHestonEngine::Integration::trapezoid(1e-8, 256),\n                1e-8));\n\n    const ext::shared_ptr<ExponentialFittingHestonEngine>\n        andersenPiterbargExponentialFittingEngine(\n            ext::make_shared<ExponentialFittingHestonEngine>(model));\n\n    const ext::shared_ptr<PricingEngine> engines[] = {\n        andersenPiterbargLaguerreEngine,\n        andersenPiterbargLobattoEngine,\n        andersenPiterbargSimpsonEngine,\n        andersenPiterbargTrapezoidEngine,\n        andersenPiterbargTrapezoidEngine2,\n        andersenPiterbargExponentialFittingEngine\n    };\n\n    const std::string algos[] = {\n          \"Gauss-Laguerre\", \"Gauss-Lobatto\",\n          \"Discrete Simpson\", \"Discrete Trapezoid\", \"Trapezoid\"\n    };\n\n    const ext::shared_ptr<PricingEngine> analyticEngine(\n        ext::make_shared<AnalyticHestonEngine>(model, 178));\n\n    const Date maturityDates[] = {\n        settlementDate + Period(1, Days),\n        settlementDate + Period(1, Weeks),\n        settlementDate + Period(1, Years),\n        settlementDate + Period(10, Years)\n    };\n\n    const Option::Type optionTypes[] = { Option::Call, Option::Put };\n    const Real strikes[] = { 50, 75, 90, 100, 110, 130, 150, 200};\n\n    const Real tol = 1e-7;\n\n    for (Size u=0; u < LENGTH(maturityDates); ++u) {\n        const ext::shared_ptr<Exercise> exercise =\n            ext::make_shared<EuropeanExercise>(maturityDates[u]);\n\n        for (Size i=0; i < LENGTH(optionTypes); ++i) {\n            for (Size j=0; j < LENGTH(strikes); ++j) {\n                VanillaOption option(\n                    ext::make_shared<PlainVanillaPayoff>(\n                        optionTypes[i], strikes[j]),\n                    exercise);\n\n                option.setPricingEngine(analyticEngine);\n                const Real expected = option.NPV();\n\n                for (Size k=0; k < LENGTH(engines); ++k) {\n                    option.setPricingEngine(engines[k]);\n                    const Real calculated = option.NPV();\n\n                    const Real error = std::fabs(calculated-expected);\n\n                    if (error > tol) {\n                        BOOST_ERROR(\" failed to reproduce prices with Andersen-\"\n                                \"Piterbarg control variate\"\n                                << \"\\n    algorithm      : \" << algos[k]\n                                << \"\\n    strike         : \" << strikes[j]\n                                << \"\\n    control variate: \" << calculated\n                                << \"\\n    classic engine : \" << expected\n                                << \"\\n    difference:      \" << error);\n                    }\n                }\n            }\n        }\n    }\n}\n\n\nvoid HestonModelTest::testAndersenPiterbargControlVariateIntegrand() {\n    BOOST_TEST_MESSAGE(\"Testing Andersen-Piterbarg Integrand \"\n                        \"with control variate...\");\n\n    SavedSettings backup;\n\n    const Date settlementDate(17, April, 2017);\n    Settings::instance().evaluationDate() = settlementDate;\n    const Date maturityDate = settlementDate + Period(2, Years);\n\n    const DayCounter dayCounter = Actual365Fixed();\n    const Rate r = 0.075;\n    const Rate q = 0.05;\n    const Handle<YieldTermStructure> rTS(flatRate(r, dayCounter));\n    const Handle<YieldTermStructure> qTS(flatRate(q, dayCounter));\n\n    const Time maturity = dayCounter.yearFraction(settlementDate, maturityDate);\n    const DiscountFactor df = rTS->discount(maturity);\n\n    const Handle<Quote> s0(ext::shared_ptr<Quote>(new SimpleQuote(100.0)));\n    const Real fwd = s0->value()*qTS->discount(maturity)/df;\n\n    const Real strike = 150;\n    const Real sx = std::log(strike);\n    const Real dd = std::log(s0->value()*qTS->discount(maturity)/df);\n\n    const Real v0    =  0.08;\n    const Real rho   =  -0.8;\n    const Real sigma =  0.5;\n    const Real kappa =  4.0;\n    const Real theta =  0.05;\n\n    const ext::shared_ptr<HestonModel> hestonModel(\n        ext::make_shared<HestonModel>(\n            ext::make_shared<HestonProcess>(\n                rTS, qTS, s0, v0, kappa, theta, sigma, rho)));\n\n    const ext::shared_ptr<COSHestonEngine> cosEngine(\n        ext::make_shared<COSHestonEngine>(hestonModel));\n\n    const ext::shared_ptr<AnalyticHestonEngine> engine(\n        ext::make_shared<AnalyticHestonEngine>(\n            hestonModel,\n            AnalyticHestonEngine::AndersenPiterbarg,\n            AnalyticHestonEngine::Integration::gaussLaguerre()));\n\n    VanillaOption option(\n        ext::make_shared<PlainVanillaPayoff>(Option::Call, strike),\n        ext::make_shared<EuropeanExercise>(maturityDate));\n    option.setPricingEngine(engine);\n\n    const Real refNPV = option.NPV();\n\n    const Volatility implStdDev = blackFormulaImpliedStdDev(\n            Option::Call, strike, fwd, refNPV, df);\n\n    const Real var = cosEngine->var(maturity);\n    const Real stdDev = std::sqrt(var);\n\n    const Real d = (std::log(s0->value()/strike)\n        + (r-q)*maturity+ 0.5*var)/stdDev;\n\n    const Real skew = cosEngine->skew(maturity);\n    const Real kurt = cosEngine->kurtosis(maturity);\n\n    const NormalDistribution n;\n\n    const Real q3 = 1/6.*s0->value()*stdDev*(2*stdDev - d)*n(d);\n    const Real q4 = 1/24.*s0->value()*stdDev*(d*d - 3*d*stdDev - 1)*n(d);\n    const Real q5 = 1/72.*s0->value()*stdDev*(\n        d*d*d*d - 5*d*d*d*stdDev - 6*d*d + 15*d*stdDev + 3)*n(d);\n\n    const Real bsNPV = blackFormula(Option::Call, strike, fwd, stdDev, df);\n\n    // different variance values for the control variate\n    const Real variances[] = {\n        v0*maturity,\n        ((1-std::exp(-kappa*maturity))*(v0-theta)/(kappa*maturity) + theta)\n            *maturity,\n        // second moment as control variate\n        var,\n        // third and fourth moment pricing based on\n        // Corrado C. and T. Su, (1996-b),\n        // \u201cSkewness and Kurtosis in S&P 500 IndexReturns Implied by Option Prices\u201d,\n        // Journal of Financial Research 19 (2), 175-192.\n        square<Real>()(blackFormulaImpliedStdDev(\n            Option::Call, strike, fwd, bsNPV + skew*q3, df)),\n        square<Real>()(blackFormulaImpliedStdDev(\n            Option::Call, strike, fwd, bsNPV + skew*q3 + kurt*q4, df)),\n        // Moment matching based on\n        // Rubinstein M., (1998), \u201cEdgeworth Binomial Trees\u201d,\n        // Journal of Derivatives 5 (3), 20-27.\n        square<Real>()(blackFormulaImpliedStdDev(\n            Option::Call, strike, fwd,\n            bsNPV + skew*q3 + kurt*q4 + skew*skew*q5, df)),\n        // implied vol as control variate\n        square<Real>()(implStdDev),\n        // remaining function becomes zero for u -> 0\n        -8.0*std::log(engine->chF(std::complex<Real>(0, -0.5), maturity).real())\n    };\n\n    for (Size i=0; i < LENGTH(variances); ++i) {\n        const Real sigmaBS = std::sqrt(variances[i]/maturity);\n\n        for (Real u =0.001; u < 15; u*=1.05) {\n            const std::complex<Real> z(u, -0.5);\n\n            const std::complex<Real> phiBS\n                = std::exp(-0.5*sigmaBS*sigmaBS*maturity\n                           *(z*z + std::complex<Real>(-z.imag(), z.real())));\n\n            const std::complex<Real> ex\n                = std::exp(std::complex<Real>(0.0, u*(dd-sx)));\n\n            const std::complex<Real> chf = engine->chF(z, maturity);\n\n            const Real orig = (-ex*chf / (u*u + 0.25)).real();\n            const Real cv = (ex*(phiBS - chf) / (u*u + 0.25)).real();\n\n            if (std::fabs(cv) > 0.03) {\n                BOOST_ERROR(\" Control variate function is greater \"\n                        \"than original function\"\n                        << \"\\n    control variate method  : \" << i\n                        << \"\\n    z value                 : \" << u\n                        << \"\\n    control variate function: \" << cv\n                        << \"\\n    original function       : \" << orig);\n            }\n        }\n    }\n}\n\nvoid HestonModelTest::testAndersenPiterbargConvergence() {\n    BOOST_TEST_MESSAGE(\"Testing Andersen-Piterbarg pricing convergence...\");\n\n    SavedSettings backup;\n\n    const Date settlementDate(5, July, 2002);\n    Settings::instance().evaluationDate() = settlementDate;\n    const Date maturityDate(5, July, 2003);\n\n    const DayCounter dayCounter = Actual365Fixed();\n    const Handle<YieldTermStructure> rTS(flatRate(0.01, dayCounter));\n    const Handle<YieldTermStructure> qTS(flatRate(0.02, dayCounter));\n\n    const Handle<Quote> s0(ext::shared_ptr<Quote>(new SimpleQuote(100.0)));\n\n    const Real v0    =  0.04;\n    const Real rho   = -0.5;\n    const Real sigma =  1.0;\n    const Real kappa =  4.0;\n    const Real theta =  0.25;\n\n    const ext::shared_ptr<HestonModel> hestonModel(\n        ext::make_shared<HestonModel>(\n            ext::make_shared<HestonProcess>(\n                rTS, qTS, s0, v0, kappa, theta, sigma, rho)));\n\n    VanillaOption option(\n        ext::make_shared<PlainVanillaPayoff>(Option::Call, s0->value()),\n        ext::make_shared<EuropeanExercise>(maturityDate));\n\n\n    // Alan Lewis reference prices posted in\n    // http://wilmott.com/messageview.cfm?catid=34&threadid=90957\n    const Real reference = 16.070154917028834278213466703938231827658768230714;\n\n    const Real diffs[] = {\n            0.0892433814611486298,   0.00013096156482816923,\n            1.34107015270501506e-07, 1.22913235145460931e-10,\n            1.24344978758017533e-13 };\n\n    for (Size n=10; n <= 50; n+=10) {\n        option.setPricingEngine(ext::make_shared<AnalyticHestonEngine>(\n            hestonModel, AnalyticHestonEngine::AndersenPiterbarg,\n            AnalyticHestonEngine::Integration::discreteTrapezoid(n), 1e-13));\n\n        const Real calculatedDiff = std::fabs(option.NPV()-reference);\n        if (calculatedDiff > 1.25*diffs[n/10-1])\n            BOOST_ERROR(\"failed to prove convergence for trapezoid rule \"\n                    << \"\\n  calculated difference: \" << calculatedDiff\n                    << \"\\n  expected difference:   \" << diffs[n/10-1]);\n    }\n}\n\n\nvoid HestonModelTest::testPiecewiseTimeDependentChFvsHestonChF() {\n    BOOST_TEST_MESSAGE(\"Testing piecewise time dependent \"\n                       \"ChF vs Heston ChF...\");\n\n    SavedSettings backup;\n\n    const Date settlementDate(5, July, 2017);\n    Settings::instance().evaluationDate() = settlementDate;\n    const Date maturityDate(5, July, 2018);\n\n    const DayCounter dayCounter = Actual365Fixed();\n    const Handle<YieldTermStructure> rTS(flatRate(0.01, dayCounter));\n    const Handle<YieldTermStructure> qTS(flatRate(0.02, dayCounter));\n\n    const Handle<Quote> s0(ext::shared_ptr<Quote>(new SimpleQuote(100.0)));\n\n    const Real v0    =  0.04;\n    const Real rho   = -0.5;\n    const Real sigma =  1.0;\n    const Real kappa =  4.0;\n    const Real theta =  0.25;\n\n    const ConstantParameter thetaP(theta, PositiveConstraint());\n    const ConstantParameter kappaP(kappa, PositiveConstraint());\n    const ConstantParameter sigmaP(sigma, PositiveConstraint());\n    const ConstantParameter rhoP  (rho, BoundaryConstraint(-1.0, 1.0));\n\n    const ext::shared_ptr<AnalyticHestonEngine> analyticEngine(\n        ext::make_shared<AnalyticHestonEngine>(\n            ext::make_shared<HestonModel>(\n                ext::make_shared<HestonProcess>(\n                    rTS, qTS, s0, v0, kappa, theta, sigma, rho))));\n\n    const ext::shared_ptr<AnalyticPTDHestonEngine> ptdHestonEngine(\n        ext::make_shared<AnalyticPTDHestonEngine>(\n            ext::make_shared<PiecewiseTimeDependentHestonModel>(\n                rTS, qTS, s0, v0, thetaP, kappaP, sigmaP, rhoP,\n                TimeGrid(dayCounter.yearFraction(settlementDate, maturityDate),\n                         10))));\n\n    const Real tol = 100*QL_EPSILON;\n    for (Real r = 0.1; r < 4; r+=0.25) {\n        for (Real phi = 0; phi < 360; phi+=60) {\n            for (Time t=0.1; t <= 1.0; t+=0.3) {\n                const std::complex<Real> z\n                    = r*std::exp(std::complex<Real>(0, phi));\n\n                const std::complex<Real> a = analyticEngine->chF(z, t);\n                const std::complex<Real> b = ptdHestonEngine->chF(z, t);\n\n                if (std::abs(a-b) > tol)\n                    BOOST_ERROR(\"failed to compare characteristic function \"\n                            << \"\\n  time dependent model: \" << b\n                            << \"\\n  Heston model        : \" << a\n                            << \"\\n  Difference          : \" << std::abs(a-b));\n            }\n        }\n    }\n}\n\n\nvoid HestonModelTest::testPiecewiseTimeDependentComparison() {\n    BOOST_TEST_MESSAGE(\"Testing piecewise time dependent \"\n                       \"ChF vs Heston ChF...\");\n\n    SavedSettings backup;\n\n    const Date settlementDate(5, July, 2017);\n    Settings::instance().evaluationDate() = settlementDate;\n\n    const DayCounter dc = Actual365Fixed();\n    const Date maturityDate(5, July, 2018);\n    const Time maturity = dc.yearFraction(settlementDate, maturityDate);\n\n    const Handle<YieldTermStructure> rTS(flatRate(0.05, dc));\n    const Handle<YieldTermStructure> qTS(flatRate(0.08, dc));\n\n    const Handle<Quote> s0(ext::make_shared<SimpleQuote>(100.0));\n\n    std::vector<Time> modelTimes;\n    modelTimes.push_back(0.25);\n    modelTimes.push_back(0.75);\n    modelTimes.push_back(10.0);\n    const TimeGrid modelGrid(modelTimes.begin(), modelTimes.end());\n\n    const Real v0 = 0.1;\n    ConstantParameter theta( 0.1, PositiveConstraint());\n    ConstantParameter kappa( 1.0, PositiveConstraint());\n    ConstantParameter rho( -0.75, BoundaryConstraint(-1.0, 1.0));\n\n    std::vector<Time> pTimes(2);\n    pTimes[0] = 0.25;\n    pTimes[1] = 0.75;\n    PiecewiseConstantParameter sigma(pTimes, PositiveConstraint());\n\n    sigma.setParam(0, 0.30);\n    sigma.setParam(1, 0.15);\n    sigma.setParam(2, 1.25);\n\n    VanillaOption option(\n        ext::make_shared<PlainVanillaPayoff>(Option::Call, s0->value()),\n        ext::make_shared<EuropeanExercise>(maturityDate));\n\n    const ext::shared_ptr<PiecewiseTimeDependentHestonModel> ptdModel(\n        ext::make_shared<PiecewiseTimeDependentHestonModel>(\n            rTS, qTS, s0, v0, theta, kappa, sigma, rho, modelGrid));\n\n    const ext::shared_ptr<AnalyticPTDHestonEngine> ptdHestonEngine(\n        ext::make_shared<AnalyticPTDHestonEngine>(ptdModel));\n\n    option.setPricingEngine(ptdHestonEngine);\n    const Real calculatedGatheral = option.NPV();\n\n    const ext::shared_ptr<AnalyticPTDHestonEngine> ptdAPEngine(\n        ext::make_shared<AnalyticPTDHestonEngine>(\n            ptdModel,\n            AnalyticPTDHestonEngine::AndersenPiterbarg,\n            AnalyticPTDHestonEngine::Integration::discreteTrapezoid(128),\n            1e-12));\n    option.setPricingEngine(ptdAPEngine);\n    const Real calculatedAndersenPiterbarg = option.NPV();\n\n    if (std::fabs(calculatedGatheral - calculatedAndersenPiterbarg) > 1e-10)\n        BOOST_ERROR(\"failed to reproduce npv for time dependent Heston model \"\n                << \"\\n  Gatheral ChF         : \" << calculatedGatheral\n                << \"\\n  AndersenPiterbarg ChF: \" << calculatedAndersenPiterbarg\n                << \"\\n  Difference          : \"\n                << std::fabs(calculatedGatheral - calculatedAndersenPiterbarg));\n\n    const ext::shared_ptr<HestonProcess> firstPartProcess(\n        ext::make_shared<HestonProcess>(\n            rTS, qTS, s0, v0, 1.0, 0.1, 0.30, -0.75,\n            HestonProcess::QuadraticExponentialMartingale));\n\n    typedef PseudoRandom::rsg_type rsg_type;\n    typedef PseudoRandom::urng_type urng_type;\n    typedef MultiPathGenerator<rsg_type>::sample_type sample_type;\n\n    const MultiPathGenerator<rsg_type> firstPathGen(\n        firstPartProcess,\n        TimeGrid(pTimes.front(), 6),\n        PseudoRandom::make_sequence_generator(12, 1234));\n\n    const urng_type urng(5678);\n\n    Statistics stat;\n    const DiscountFactor df = rTS->discount(maturityDate);\n\n    const Size nSims = 10000;\n    for (Size i=0; i < nSims; ++i) {\n        Real priceS = 0.0;\n\n        for (Size j=0; j < 2; ++j) {\n            const sample_type& path1 =\n                (j & 1) != 0U ? firstPathGen.antithetic() : firstPathGen.next();\n            const Real spot1 = path1.value[0].back();\n            const Real v1    = path1.value[1].back();\n\n            const MultiPathGenerator<rsg_type> secondPathGen(\n                ext::make_shared<HestonProcess>(\n                    rTS, qTS,\n                    Handle<Quote>(ext::make_shared<SimpleQuote>(spot1)),\n                    v1, 1.0, 0.1, 0.15, -0.75,\n                    HestonProcess::QuadraticExponentialMartingale),\n                TimeGrid(pTimes[1]-pTimes[0], 12),\n                PseudoRandom::make_sequence_generator(24, urng.nextInt32()));\n\n            const sample_type& path2 = secondPathGen.next();\n            const Real spot2 = path2.value[0].back();\n            const Real v2    = path2.value[1].back();\n\n            const MultiPathGenerator<rsg_type> thirdPathGen(\n                ext::make_shared<HestonProcess>(\n                    rTS, qTS,\n                    Handle<Quote>(ext::make_shared<SimpleQuote>(spot2)),\n                    v2, 1.0, 0.1, 1.25, -0.75,\n                    HestonProcess::QuadraticExponentialMartingale),\n                TimeGrid(maturity-pTimes[1], 6),\n                PseudoRandom::make_sequence_generator(12, urng.nextInt32()));\n            const sample_type& path3 = thirdPathGen.next();\n            const Real spot3 = path3.value[0].back();\n\n            priceS += 0.5*(*option.payoff())(spot3);\n        }\n\n        stat.add(priceS*df);\n    }\n\n    const Real calculatedMC = stat.mean();\n    const Real errorEstimate = stat.errorEstimate();\n\n    if (std::fabs(calculatedMC - calculatedGatheral) > 3.0*errorEstimate)\n        BOOST_ERROR(\"failed to reproduce npv for time dependent Heston model\"\n                << \"\\n  Gatheral ChF     : \" << calculatedGatheral\n                << \"\\n  Monte-Carlo      : \" << calculatedMC\n                << \"\\n  Monte-Carlo error: \" << errorEstimate\n                << \"\\n  Difference       : \"\n                << std::fabs(calculatedGatheral - calculatedMC));\n}\n\nvoid HestonModelTest::testPiecewiseTimeDependentChFAsymtotic() {\n    BOOST_TEST_MESSAGE(\"Testing piecewise time dependent \"\n                       \"ChF vs Heston ChF...\");\n\n    SavedSettings backup;\n\n    const Date settlementDate(5, July, 2017);\n    Settings::instance().evaluationDate() = settlementDate;\n    const Date maturityDate = settlementDate + Period(13, Months);\n\n    const DayCounter dc = Actual365Fixed();\n    const Time maturity = dc.yearFraction(settlementDate, maturityDate);\n    const Handle<YieldTermStructure> rTS(flatRate(0.0, dc));\n\n    std::vector<Time> modelTimes;\n    modelTimes.push_back(0.01);\n    modelTimes.push_back(0.5);\n    modelTimes.push_back(2.0);\n\n    const TimeGrid modelGrid(modelTimes.begin(), modelTimes.end());\n\n    const Real v0 = 0.1;\n    const std::vector<Time> pTimes(modelTimes.begin(), modelTimes.end()-1);\n\n    PiecewiseConstantParameter sigma(pTimes, PositiveConstraint());\n    PiecewiseConstantParameter theta(pTimes, PositiveConstraint());\n    PiecewiseConstantParameter kappa(pTimes, PositiveConstraint());\n    PiecewiseConstantParameter rho(pTimes, BoundaryConstraint(-1.0, 1.0));\n\n    const Real sigmas[] = { 0.01, 0.2, 0.6 };\n    const Real thetas[] = { 0.16, 0.06, 0.36 };\n    const Real kappas[] = { 1.0, 0.3, 4.0 };\n    const Real rhos[] = { 0.5, -0.75, -0.25 };\n\n    for (Size i=0; i < 3; ++i) {\n        sigma.setParam(i, sigmas[i]);\n        theta.setParam(i, thetas[i]);\n        kappa.setParam(i, kappas[i]);\n        rho.setParam(i, rhos[i]);\n    }\n\n    const Handle<Quote> s0(ext::make_shared<SimpleQuote>(100.0));\n    const ext::shared_ptr<PiecewiseTimeDependentHestonModel> ptdModel(\n        ext::make_shared<PiecewiseTimeDependentHestonModel>(\n            rTS, rTS, s0, v0, theta, kappa, sigma, rho, modelGrid));\n\n    const Real eps = 1e-8;\n\n    const ext::shared_ptr<AnalyticPTDHestonEngine> ptdHestonEngine(\n        ext::make_shared<AnalyticPTDHestonEngine>(\n            ptdModel,\n            AnalyticPTDHestonEngine::AndersenPiterbarg,\n            AnalyticPTDHestonEngine::Integration::discreteTrapezoid(128),\n            eps));\n\n    const std::complex<Real> D_u_inf = -\n        std::complex<Real>(std::sqrt(1-rhos[0]*rhos[0]),rhos[0])/sigmas[0];\n\n    const std::complex<Real> dd = std::complex<Real>(kappas[0],\n        (2*kappas[0]*rhos[0]-sigmas[0])\n        /(2*std::sqrt(1-rhos[0]*rhos[0])))/(sigmas[0]*sigmas[0]);\n\n    std::complex<Real> C_u_inf(0.0, 0.0), cc(0.0, 0.0), clog(0.0, 0.0);\n\n    for (Size i=0; i < 3; ++i) {\n        const Real kappa = kappas[i];\n        const Real theta = thetas[i];\n        const Real sigma = sigmas[i];\n        const Real rho = rhos[i];\n        const Time tau = std::min(maturity, modelGrid[i+1]) - modelGrid[i];\n\n        C_u_inf += -kappa*theta*tau / sigma\n            *std::complex<Real>(std::sqrt(1-rho*rho), rho);\n\n        cc += kappa*std::complex<Real>(2*kappa,(2*kappa*rho-sigma)\n            /sqrt(1-rho*rho))*tau*theta/(2*sigma*sigma);\n\n        const std::complex<Real> Di =\n            (i < 2) ? sigma/sigmas[i+1]\n              *std::complex<Real>(std::sqrt(1-rhos[i+1]*rhos[i+1]), rhos[i+1])\n                     : std::complex<Real>(0.0, 0.0);\n\n        clog += 2*kappa*theta/(sigma*sigma)*std::log(1.0 -\n            ( Di - std::complex<Real>(std::sqrt(1-rho*rho), rho)) /\n            ( Di + std::complex<Real>(std::sqrt(1-rho*rho), -rho)));\n    }\n\n    const Real epsilon = eps*M_PI/s0->value();\n\n    const Real uM =\n        AnalyticHestonEngine::Integration::andersenPiterbargIntegrationLimit(\n            -(C_u_inf + D_u_inf*v0).real(), epsilon, v0, maturity);\n\n    const Real expectedUM = 18.6918883427;\n    if (std::fabs(uM - expectedUM) > 1e-5) {\n        BOOST_ERROR(\"failed to reproduce Andersen-Piterbarg \"\n                    \"Integration bounds for piecewise constant \"\n                    \"time dependent Heston Model\"\n                << \"\\n  calculated : \" << uM\n                << \"\\n  expected   : \" << expectedUM\n                << \"\\n  diff       : \" << std::fabs(uM - expectedUM)\n                << \"\\n  tolerance  : \" << 1e-5);\n    }\n\n    const Real u = 1e8;\n    const std::complex<Real> expectedlnChF = ptdHestonEngine->lnChF(u, maturity);\n    const std::complex<Real> calculatedAsympotic =\n        (D_u_inf*u + dd)*v0 + C_u_inf*u + cc + clog;\n\n    if (std::abs(expectedlnChF - calculatedAsympotic) > 0.01) {\n        BOOST_ERROR(\"failed to reproduce asymptotic of characteristic function\"\n                << \"\\n  ln(ChF)   : \" << expectedlnChF\n                << \"\\n  asymptotic: \" << calculatedAsympotic\n                << \"\\n  diff      : \"\n                << std::abs(expectedlnChF - calculatedAsympotic)\n                << \"\\n  tolerance : \" << 0.01);\n    }\n\n    VanillaOption option(\n        ext::make_shared<PlainVanillaPayoff>(Option::Call, s0->value()),\n        ext::make_shared<EuropeanExercise>(maturityDate));\n    option.setPricingEngine(ptdHestonEngine);\n\n    const Real expectedNPV = 17.43851162589377;\n    const Real calculatedNPV = option.NPV();\n    const Real diffNPV = std::fabs(expectedNPV - calculatedNPV);\n    if (diffNPV > 1e-9) {\n        BOOST_ERROR(\"failed to reproduce high precision prices for \"\n                \"piecewise constant time dependent Heston model\"\n                << \"\\n  expeceted : \" << expectedNPV\n                << \"\\n  calclated : \" << calculatedNPV\n                << \"\\n  diff      : \" << diffNPV\n                << \"\\n  tolerance : \" << 1e-9);\n    }\n}\n\nvoid HestonModelTest::testSmallSigmaExpansion() {\n    BOOST_TEST_MESSAGE(\"Testing small sigma expansion of \"\n                       \"the characteristic function...\");\n\n    SavedSettings backup;\n\n    const Date settlementDate(20, March, 2020);\n    Settings::instance().evaluationDate() = settlementDate;\n    const Date maturityDate = settlementDate + Period(2, Years);\n\n    const DayCounter dc = Actual365Fixed();\n    const Time t = dc.yearFraction(settlementDate, maturityDate);\n    const Handle<YieldTermStructure> rTS(flatRate(0.0, dc));\n\n    const Handle<Quote> spot(ext::make_shared<SimpleQuote>(100));\n\n    const Real theta = 0.1 * 0.1;\n    const Real v0 = theta + 0.02;\n    const Real kappa = 1.25;\n    const Real sigma = 1e-9;\n    const Real rho = -0.9;\n\n    const ext::shared_ptr<HestonModel> hestonModel =\n        ext::make_shared<HestonModel>(\n            ext::make_shared<HestonProcess>(\n                rTS, rTS, spot, v0, kappa, theta, sigma, rho));\n\n    const ext::shared_ptr<AnalyticHestonEngine> engine =\n        ext::make_shared<AnalyticHestonEngine>(hestonModel);\n\n    const std::complex<Real> expectedChF(\n        0.990463578538352651,2.60693475987521132e-12);\n\n    const std::complex<Real> calculatedChF = engine->chF(\n        std::complex<Real>(0.55, -0.5), t);\n\n    const Real diffChF = std::abs(expectedChF - calculatedChF);\n    const Real tolChF = 1e-12;\n    if (diffChF > tolChF) {\n        BOOST_ERROR(\"failed to reproduce normalized characteristic function \"\n                \"value for small sigma\"\n                << \"\\n  expeceted : \" << expectedChF\n                << \"\\n  calclated : \" << calculatedChF\n                << \"\\n  diff      : \" << diffChF\n                << \"\\n  tolerance : \" << tolChF);\n    }\n\n    VanillaOption option(\n        ext::make_shared<PlainVanillaPayoff>(Option::Call, 120.0),\n        ext::make_shared<EuropeanExercise>(maturityDate));\n\n    option.setPricingEngine(\n        ext::make_shared<AnalyticHestonEngine>(\n            hestonModel,\n            AnalyticHestonEngine::AndersenPiterbarg,\n            AnalyticHestonEngine::Integration::gaussLaguerre(192)));\n\n    const Real calculatedNPV = option.NPV();\n\n    const Real stdDev =\n        std::sqrt(((1-std::exp(-kappa*t))*(v0-theta)/(kappa*t) + theta)*t);\n\n    const Real expectedNPV =\n        blackFormula(Option::Call, 120.0, 100.0, stdDev);\n\n    const Real diffNPV =std::fabs(calculatedNPV - expectedNPV);\n    const Real tolNPV = 50*sigma;\n\n    if (diffNPV > tolNPV) {\n        BOOST_ERROR(\"failed to reproduce Black Scholes prices \"\n                \"for Heston model with very small sigma\"\n                << \"\\n  expeceted : \" << expectedNPV\n                << \"\\n  calclated : \" << calculatedNPV\n                << \"\\n  diff      : \" << diffNPV\n                << \"\\n  tolerance : \" << tolNPV);\n    }\n}\n\nvoid HestonModelTest::testSmallSigmaExpansion4ExpFitting() {\n    BOOST_TEST_MESSAGE(\"Testing small sigma expansion for the \"\n                       \"exponential fitting Heston engine...\");\n\n    SavedSettings backup;\n\n    const Date todaysDate(13, March, 2020);\n    Settings::instance().evaluationDate() = todaysDate;\n\n    const DayCounter dc = Actual365Fixed();\n    const Handle<YieldTermStructure> rTS(flatRate(0.05, dc));\n    const Handle<YieldTermStructure> qTS(flatRate(0.075, dc));\n\n    const Handle<Quote> spot(ext::make_shared<SimpleQuote>(100.0));\n\n    // special case: reduce sigma\n    const Date maturityDate = Date(14, March, 2021);\n    const Time maturity = dc.yearFraction(todaysDate, maturityDate);\n    const Real fwd =\n        spot->value()*qTS->discount(maturity)/rTS->discount(maturity);\n\n    const Real v0 = 0.04;\n    const Real rho = -0.5;\n    const Real kappa = 4.0;\n    const Real theta = 0.04;\n\n    const Real moneyness = 0.1;\n    const Real strike = std::exp(-moneyness*std::sqrt(theta*maturity))*fwd;\n\n    const Real expected = blackFormula(\n        Option::Call, strike, fwd,\n        std::sqrt(v0*maturity), rTS->discount(maturity));\n\n    VanillaOption option(\n        ext::make_shared<PlainVanillaPayoff>(Option::Call, strike),\n        ext::make_shared<EuropeanExercise>(maturityDate));\n\n    for (Real sigma = 1e-4; sigma > 1e-12; sigma*=0.1) {\n        option.setPricingEngine(\n            ext::make_shared<ExponentialFittingHestonEngine>(\n                ext::make_shared<HestonModel>(\n                    ext::make_shared<HestonProcess>(\n                        rTS, qTS, spot, v0, kappa, theta, sigma, rho))));\n        const Real calculated = option.NPV();\n\n        const Real diff = std::fabs(expected - calculated);\n\n        if (diff > 0.01*sigma) {\n            BOOST_ERROR(\"failed to reproduce Black Scholes prices \"\n                    \"for Heston model with very small sigma\"\n                    << \"\\n  expeceted : \" << expected\n                    << \"\\n  calclated : \" << calculated\n                    << \"\\n  sigma     : \" << sigma\n                    << \"\\n  diff      : \" << diff\n                    << \"\\n  tolerance : \" << 10*sigma);\n        }\n    }\n\n\n    // generic cases\n    const Real kappas[] = { 0.5, 1.0, 4.0 };\n    const Real thetas[] = { 0.04, 0.09};\n    const Real v0s[]    = { 0.025, 0.20 };\n    const Integer maturities[] = { 1, 31, 182, 1850 };\n\n    for (Size m=0; m < LENGTH(maturities); ++m) {\n        const Date maturityDate = todaysDate + Period(maturities[m], Days);\n        const DiscountFactor df = rTS->discount(maturityDate);\n        const Real fwd = spot->value() * qTS->discount(maturityDate)/df;\n\n        const ext::shared_ptr<Exercise> exercise =\n            ext::make_shared<EuropeanExercise>(maturityDate);\n\n        const Time t = dc.yearFraction(todaysDate, maturityDate);\n\n        Option::Type optionType = Option::Call;\n\n        for (Size i=0; i < LENGTH(kappas); ++i) {\n            const Real kappa = kappas[i];\n\n            for (Size j=0; j < LENGTH(thetas); ++j) {\n                const Real theta = thetas[j];\n\n                for (Size l=0; l < LENGTH(v0s); ++l) {\n                    const Real v0 = v0s[l];\n\n                    const ext::shared_ptr<PricingEngine> engine =\n                        ext::make_shared<ExponentialFittingHestonEngine>(\n                            ext::make_shared<HestonModel>(\n                                ext::make_shared<HestonProcess>(\n                                    rTS, qTS, spot, v0,\n                                    kappa, theta, 1e-13, -0.8)));\n\n                    const Real stdDev =\n                        std::sqrt(((1-std::exp(-kappa*t))*(v0-theta)/(kappa*t) + theta)*t);\n\n                    for (Real strike = spot->value()*exp(-10*stdDev);\n                            strike < spot->value()*exp(10*stdDev); strike*= 1.2) {\n\n                        VanillaOption option(\n                            ext::make_shared<PlainVanillaPayoff>(\n                                optionType, strike), exercise);\n\n                        option.setPricingEngine(engine);\n                        const Real calculated = option.NPV();\n\n                        const Real expected =\n                            blackFormula(optionType, strike, fwd, stdDev, df);\n\n                        const Real diff = std::fabs(expected - calculated);\n                        if (diff > 1e-10) {\n                            BOOST_ERROR(\"failed to reproduce Black Scholes prices \"\n                                    \"for Heston model with very small sigma\"\n                                    << \"\\n  expceted  : \" << expected\n                                    << \"\\n  calculated: \" << calculated\n                                    << \"\\n  diff      : \" << diff\n                                    << \"\\n  tolerance : \" << 1e-10);\n                        }\n\n                        optionType = (optionType == Option::Call)\n                            ? Option::Put : Option::Call;\n                    }\n                }\n            }\n        }\n    }\n}\n\nvoid HestonModelTest::testExponentialFitting4StrikesAndMaturities() {\n    BOOST_TEST_MESSAGE(\"Testing exponential fitting Heston engine \"\n                       \"with high precision results for large moneyness...\");\n\n    SavedSettings backup;\n\n    const Date todaysDate = Date(13, May, 2020);\n    Settings::instance().evaluationDate() = todaysDate;\n\n    const DayCounter dc = Actual365Fixed();\n\n    const Handle<YieldTermStructure> rTS(flatRate(0.0507, dc));\n    const Handle<YieldTermStructure> qTS(flatRate(0.0469, dc));\n\n    const Handle<Quote> s0(ext::make_shared<SimpleQuote>(1.0));\n\n    const Real moneyness[] = { -20, -10, -5, 2.5, 1, 0, 1, 2.5, 5, 10, 20 };\n    const Period maturities[] = {\n            Period(1, Days),\n            Period(1, Months),\n            Period(1, Years),\n            Period(10, Years)\n    };\n\n    const Real v0    =  0.04;\n    const Real rho   = -0.6;\n    const Real sigma =  0.75;\n    const Real kappa =  2.5;\n    const Real theta =  0.06;\n\n    // Reference prices are calculated using a boost multi-precision\n    // implementation of the AnalyticHestonEngine,\n    // https://github.com/klausspanderen/HestonExponentialFitting\n\n    const Real referenceValues[] = {\n            1.1631865252540813e-58,\n            1.06426822273258466e-49,\n            6.92896489110422086e-16,\n            8.19515526286263236e-06,\n            0.000625608178476390504,\n            0.00417261379371945684,\n            0.000625608178476390504,\n            8.19515526286263236e-06,\n            1.92308901296741414e-10,\n            1.57327901822368115e-23,\n            5.7830515043285098e-58,\n            3.56081886910098813e-48,\n            2.9489071194212509e-23,\n            1.54181757781090727e-11,\n            0.000367960011879847279,\n            0.00493886106106039818,\n            0.0227152343265593776,\n            0.00493886106106039818,\n            0.000367960011879847279,\n            3.06653474407784574e-06,\n            8.86665241279348934e-11,\n            1.51206812371708868e-20,\n            4.18506719865401643e-29,\n            2.46637786897559908e-15,\n            1.75338784910563671e-08,\n            0.00284789176080218294,\n            0.0199133097064688458,\n            0.0776848755698912041,\n            0.0199133097064688458,\n            0.00284789176080218294,\n            0.00012462190796343504,\n            2.59755319566692257e-07,\n            1.13853114743124721e-12,\n            4.27612073892114211e-39,\n            1.08387452075906664e-25,\n            4.15179522944463802e-11,\n            0.00134157732880653131,\n            0.029018582813884912,\n            0.176405213088554197,\n            0.029018582813884912,\n            0.00134157732880653131,\n            5.43674074281991917e-06,\n            6.51443921040230507e-11,\n            9.25756999394709285e-21\n    };\n\n    const ext::shared_ptr<HestonModel> model =\n        ext::make_shared<HestonModel>(\n            ext::make_shared<HestonProcess>(\n                rTS, qTS, s0, v0, kappa, theta, sigma, rho));\n\n    const ext::shared_ptr<PricingEngine> engine =\n        ext::make_shared<ExponentialFittingHestonEngine>(model);\n\n    Size idx = 0;\n    for (Size i=0; i < LENGTH(maturities); ++i) {\n        const Date maturityDate = todaysDate + maturities[i];\n        const Time t = dc.yearFraction(todaysDate, maturityDate);\n\n        const ext::shared_ptr<Exercise> exercise =\n            ext::make_shared<EuropeanExercise>(maturityDate);\n\n        const DiscountFactor df = rTS->discount(t);\n        const Real fwd = s0->value()*qTS->discount(t)/df;\n\n        for (Size j=0; j < LENGTH(moneyness); ++j, ++idx) {\n            const Real strike =\n                std::exp(-moneyness[j]*std::sqrt(theta*t))*fwd;\n\n            for (Size k=0; k < 2; ++k) {\n                const ext::shared_ptr<PlainVanillaPayoff> payoff =\n                    ext::make_shared<PlainVanillaPayoff>((k) != 0U ? Option::Put : Option::Call,\n                                                         strike);\n\n                VanillaOption option(payoff, exercise);\n                option.setPricingEngine(engine);\n\n                const Real calculated = option.NPV();\n\n                Real expected;\n                if (payoff->optionType() == Option::Call)\n                    if (fwd < strike)\n                        expected = referenceValues[idx];\n                    else\n                        expected = (fwd - strike)*df + referenceValues[idx];\n                else\n                    if (fwd > strike)\n                        expected = referenceValues[idx];\n                    else\n                        expected = referenceValues[idx] - (fwd - strike)*df;\n\n                const Real diff = std::fabs(calculated - expected);\n                if (diff > 1e-12) {\n                    BOOST_ERROR(\"failed to reproduce cached extreme \"\n                            \"Heston model prices with exponential fitted \"\n                            \"Gauss-Laguerre quadrature rule\"\n                            << \"\\n  forward   : \" << fwd\n                            << \"\\n  strike    : \" << strike\n                            << \"\\n  expected  : \" << expected\n                            << \"\\n  calculated: \" << calculated\n                            << \"\\n  diff      : \" << diff\n                            << \"\\n  tolerance : \" << 1e-12);\n                }\n            }\n        }\n    }\n}\n\nnamespace {\n    class HestonIntegrationMaxBoundTestFct {\n      public:\n        explicit HestonIntegrationMaxBoundTestFct(Real maxBound)\n        : maxBound_(maxBound),\n          callCounter_(ext::make_shared<Size>(Size(0))) {}\n\n        Real operator()() {\n            ++(*callCounter_);\n            return maxBound_;\n        }\n\n        Size getCallCounter() const {\n            return *callCounter_;\n        }\n      private:\n        const Real maxBound_;\n        const ext::shared_ptr<Size> callCounter_;\n    };\n}\n\nvoid HestonModelTest::testHestonEngineIntegration() {\n    BOOST_TEST_MESSAGE(\"Testing Heston engine integration signature...\");\n\n    const AnalyticHestonEngine::Integration integration =\n        AnalyticHestonEngine::Integration::gaussLobatto(1e-12, 1e-12);\n\n    const Real c1 = integration.calculate(1.0, square<Real>(), 1.0);\n\n    HestonIntegrationMaxBoundTestFct testFct(1.0);\n    const Real c2 = integration.calculate(1.0, square<Real>(), testFct);\n\n    if (testFct.getCallCounter() == 0 ||\n            std::fabs(c1 - 1/3.) > 1e-10 || std::fabs(c2 - 1/3.) > 1e-10) {\n        BOOST_ERROR(\"failed to test Heston engine integration signature\");\n    }\n}\n\ntest_suite* HestonModelTest::suite(SpeedLevel speed) {\n    test_suite* suite = BOOST_TEST_SUITE(\"Heston model tests\");\n\n    suite->add(QUANTLIB_TEST_CASE(&HestonModelTest::testBlackCalibration));\n    suite->add(QUANTLIB_TEST_CASE(&HestonModelTest::testDAXCalibration));\n    suite->add(QUANTLIB_TEST_CASE(&HestonModelTest::testAnalyticVsBlack));\n    suite->add(QUANTLIB_TEST_CASE(&HestonModelTest::testAnalyticVsCached));\n    suite->add(QUANTLIB_TEST_CASE(&HestonModelTest::testDifferentIntegrals));\n    suite->add(QUANTLIB_TEST_CASE(&HestonModelTest::testFdVanillaVsCached));\n    suite->add(QUANTLIB_TEST_CASE(&HestonModelTest::testMultipleStrikesEngine));\n    suite->add(QUANTLIB_TEST_CASE(&HestonModelTest::testMcVsCached));\n    suite->add(QUANTLIB_TEST_CASE(\n                    &HestonModelTest::testAnalyticPiecewiseTimeDependent));\n    suite->add(QUANTLIB_TEST_CASE(\n                    &HestonModelTest::testDAXCalibrationOfTimeDependentModel));\n    suite->add(QUANTLIB_TEST_CASE(\n                    &HestonModelTest::testAlanLewisReferencePrices));\n    suite->add(QUANTLIB_TEST_CASE(\n                    &HestonModelTest::testExpansionOnAlanLewisReference));\n    suite->add(QUANTLIB_TEST_CASE(\n                    &HestonModelTest::testExpansionOnFordeReference));\n    suite->add(QUANTLIB_TEST_CASE(\n                    &HestonModelTest::testAllIntegrationMethods));\n    suite->add(QUANTLIB_TEST_CASE(&HestonModelTest::testCosHestonCumulants));\n    suite->add(QUANTLIB_TEST_CASE(&HestonModelTest::testCosHestonEngine));\n    suite->add(QUANTLIB_TEST_CASE(&HestonModelTest::testCharacteristicFct));\n    suite->add(QUANTLIB_TEST_CASE(\n        &HestonModelTest::testAndersenPiterbargPricing));\n    suite->add(QUANTLIB_TEST_CASE(\n        &HestonModelTest::testAndersenPiterbargControlVariateIntegrand));\n    suite->add(QUANTLIB_TEST_CASE(\n        &HestonModelTest::testAndersenPiterbargConvergence));\n    suite->add(QUANTLIB_TEST_CASE(\n        &HestonModelTest::testPiecewiseTimeDependentChFvsHestonChF));\n    suite->add(QUANTLIB_TEST_CASE(\n        &HestonModelTest::testPiecewiseTimeDependentComparison));\n    suite->add(QUANTLIB_TEST_CASE(\n        &HestonModelTest::testPiecewiseTimeDependentChFAsymtotic));\n    suite->add(QUANTLIB_TEST_CASE(\n        &HestonModelTest::testSmallSigmaExpansion));\n    suite->add(QUANTLIB_TEST_CASE(\n        &HestonModelTest::testSmallSigmaExpansion4ExpFitting));\n    suite->add(QUANTLIB_TEST_CASE(\n        &HestonModelTest::testExponentialFitting4StrikesAndMaturities));\n    suite->add(QUANTLIB_TEST_CASE(&HestonModelTest::testHestonEngineIntegration));\n\n\n    if (speed <= Fast) {\n        suite->add(QUANTLIB_TEST_CASE(\n            &HestonModelTest::testFdBarrierVsCached));\n    }\n\n    if (speed == Slow) {\n        suite->add(QUANTLIB_TEST_CASE(&HestonModelTest::testKahlJaeckelCase));\n    }\n\n    return suite;\n}\n\ntest_suite* HestonModelTest::experimental() {\n    test_suite* suite = BOOST_TEST_SUITE(\"Heston model experimental tests\");\n    suite->add(QUANTLIB_TEST_CASE(\n        &HestonModelTest::testAnalyticPDFHestonEngine));\n    return suite;\n}\n", "meta": {"hexsha": "33471c7d43cea1ac1b0215fb50a58fa05fb7490b", "size": 126922, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test-suite/hestonmodel.cpp", "max_stars_repo_name": "CarrieMY/QuantLib", "max_stars_repo_head_hexsha": "32f864a1f5e02114e5edcaf23d107f8b9a0f805e", "max_stars_repo_licenses": ["BSD-3-Clause"], "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-suite/hestonmodel.cpp", "max_issues_repo_name": "CarrieMY/QuantLib", "max_issues_repo_head_hexsha": "32f864a1f5e02114e5edcaf23d107f8b9a0f805e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 17.0, "max_issues_repo_issues_event_min_datetime": "2020-11-23T06:54:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T22:50:32.000Z", "max_forks_repo_path": "test-suite/hestonmodel.cpp", "max_forks_repo_name": "fayce66/QuantLib", "max_forks_repo_head_hexsha": "59252a3640883dec99879918e5ea4f9b6b119a99", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-04-24T17:51:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-20T09:41:33.000Z", "avg_line_length": 39.6507341456, "max_line_length": 153, "alphanum_fraction": 0.6045602811, "num_tokens": 33909, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4833964854793604}}
{"text": "#include <Eigen/Dense>\n#include <cmath>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n\n#include \"simulator.hpp\"\n#include \"spdlog/spdlog.h\"\n\nusing namespace SnowSimulator;\n\nSimulator::Simulator(MaterialPoints &materialPoints, Grid *grid,\n                     SnowModel &snowModel,\n                     std::vector<CollisionObject *> colliders)\n    : m_materialPoints(materialPoints), m_grid(grid), m_snowModel(snowModel),\n      m_colliders(colliders) {\n  m_stepCount = 0;\n  logger = spdlog::get(\"snowsim\");\n}\n\n/**\n * The simulation proceeds as follows:\n *\n * 1. Rasterize particle data to the grid (rasterizeParticlesToGrid)\n * 2. Compute particle volumes and densities (setParticleVolumesAndDensities)\n *    NOTE: This is done only on the first timestep!\n * 3. Compute grid forces (computeGridForces)\n * 4. Update velocities on grid to v_i' (updateGridVelocities)\n * 5. Grid-based body collisions (detectGridCollisions)\n * 6. Solve linear system for semi-implicit integration (solveLinearSystem)\n * 7. Update deformation gradient (updateDeformationGradient)\n * 8. Update particle velocities (updateParticleVelocities)\n * 9. Particle-based body collisions (detectParticleCollisions)\n * 10. Update particle positions (updateParticlePostions)\n **/\nvoid Simulator::advance(double delta_t) {\n  logger->info(\"[Beginning step {} -> advancing by {}]\", stepCount(), delta_t);\n\n  rasterizeParticlesToGrid();\n\n  // On the first timestep, we need to compute particle volumes and densities\n\n  if (m_stepCount == 0) {\n    setParticleVolumesAndDensities();\n  }\n\n  computeGridForces();\n  updateGridVelocities(delta_t);\n\n  detectGridCollisions(delta_t);\n\n  explicitIntegration();\n  // solveLinearSystem();\n\n  updateDeformationGradient(delta_t);\n  updateParticleVelocities(delta_t);\n  detectParticleCollisions(delta_t);\n  updateParticlePositions(delta_t);\n\n  m_stepCount++;\n}\n\nvoid Simulator::rasterizeParticlesToGrid() {\n  // Reset all node properties\n\n  for (auto &node : m_grid->nodes()) {\n    node->m_mass = 0;\n    node->m_velocity.setZero();\n    node->m_nextVelocity.setZero();\n    node->m_velocityStar.setZero();\n    node->m_force.setZero();\n  }\n\n  // Place all particles in their updated cells\n\n  // TODO(kvchen): Comment this out once we fix this bug\n\n  // for (auto &mp : m_materialPoints.particles()) {\n  //   Vector3f idx = (mp->m_position.array() / m_grid->m_spacing).floor();\n  //   int i = m_grid->vectorToIdx(idx.cast<int>());\n  //\n  //   if (i < 0 || i >= m_grid->m_gridCells.size()) {\n  //     logger->error(\"Particle index {} exceeds grid boundaries\", i);\n  //     std::cout << *mp << std::endl;\n  //\n  //     logger->error(\"Other particles in the same cell as invalid particle:\");\n  //     for (auto &other : mp->cell()->particles()) {\n  //       if (other == mp) {\n  //         continue;\n  //       }\n  //       logger->error(\"Distance to invalid particle: {}\",\n  //                     (other->position() - mp->position()).norm());\n  //       std::cout << *other << std::endl;\n  //     }\n  //   }\n  // }\n\n  for (auto &cell : m_grid->cells()) {\n    cell->clear();\n  }\n\n  for (auto &mp : m_materialPoints.particles()) {\n    int idx = m_grid->getParticleIdx(mp);\n    if (idx < 0 || idx >= m_grid->m_gridCells.size()) {\n      logger->error(\"Particle index {} exceeds grid boundaries\", idx);\n      std::cout << *mp << std::endl;\n    }\n\n    m_grid->cells()[idx]->addMaterialPoint(mp);\n  }\n\n  for (auto &mp : m_materialPoints.particles()) {\n    m_grid->forEachNeighbor(mp, [&mp](GridNode *node) {\n      double w = node->basisFunction(mp->position());\n      node->m_mass += mp->mass() * w;\n      node->m_velocity += mp->velocity() * mp->mass() * w;\n    });\n  }\n\n  for (auto &node : m_grid->nodes()) {\n    if (node->m_mass > 0) {\n      node->m_velocity /= node->m_mass;\n    }\n  }\n}\n\nvoid Simulator::setParticleVolumesAndDensities() {\n  logger->info(\"Setting initial particle volumes and densities\");\n\n  for (auto const &mp : m_materialPoints.particles()) {\n    mp->m_volume = 0;\n    mp->m_density = 0;\n\n    m_grid->forEachNeighbor(mp, [&](GridNode *node) {\n      mp->m_density += node->m_mass * node->basisFunction(mp->m_position) /\n                       pow(m_grid->m_spacing, 3);\n    });\n\n    if (mp->m_density != 0) {\n      mp->m_volume = mp->m_mass / mp->m_density;\n    }\n  }\n}\n\nvoid Simulator::computeGridForces() {\n  for (auto &mp : m_materialPoints.particles()) {\n    JacobiSVD<Matrix3f> svd(mp->m_defElastic, ComputeFullU | ComputeFullV);\n\n    double Jp = mp->m_defPlastic.determinant();\n    double Je = mp->m_defElastic.determinant();\n\n    Matrix3f Re = svd.matrixU() * svd.matrixV().transpose();\n\n    double epsilon =\n        exp(fmin(m_snowModel.hardeningCoefficient * (1 - Jp), 1e3));\n\n    // Compute the Cauchy stress\n    // mu * 2 * (fe - re)_f\n\n    Matrix3f stress =\n        epsilon *\n        (2 * m_snowModel.initialMu * (mp->m_defElastic - Re) *\n             mp->m_defElastic.transpose() +\n         Matrix3f::Identity() * (m_snowModel.initialLambda * (Je - 1) * Je));\n\n    m_grid->forEachNeighbor(mp, [mp, &stress](GridNode *node) {\n      node->m_force -=\n          mp->m_volume * stress * node->gradBasisFunction(mp->m_position);\n    });\n  }\n}\n\nvoid Simulator::updateGridVelocities(double delta_t) {\n  for (auto &node : m_grid->getAllNodes()) {\n    if (node->m_mass > 0) {\n      node->m_nextVelocity =\n          node->m_velocity + delta_t * node->m_force / node->m_mass;\n    }\n\n    // Add gravitational forces\n\n    node->m_nextVelocity += Vector3f(0, -9.8, 0) * delta_t;\n  }\n}\n\nvoid Simulator::detectGridCollisions(double delta_t) {\n  for (auto &node : m_grid->getAllNodes()) {\n    node->m_velocityStar = node->m_nextVelocity;\n\n    for (auto &collider : m_colliders) {\n      Vector3f position = node->position();\n      if (collider->phi(position) > 0) {\n        continue;\n      }\n\n      Vector3f normal = collider->normal(position);\n      Vector3f relVelocity = node->m_velocityStar - collider->velocity();\n      double magnitude = relVelocity.dot(normal);\n\n      if (magnitude >= 0) {\n        continue;\n      }\n\n      Vector3f tangentialVelocity = relVelocity - magnitude * normal;\n\n      // Only apply dynamic friction if the tangential velocity is large\n      // compared to the normal\n\n      double normComponent = collider->friction() * magnitude;\n      double tangentNorm = tangentialVelocity.norm();\n\n      if (collider->sticky() || tangentNorm <= -normComponent) {\n        relVelocity.setZero();\n      } else {\n        relVelocity = tangentialVelocity * (1 + normComponent / tangentNorm);\n      }\n\n      node->m_velocityStar = relVelocity + collider->velocity();\n    }\n  }\n}\n\nvoid Simulator::explicitIntegration() {\n  for (auto &node : m_grid->getAllNodes()) {\n    node->m_nextVelocity = node->m_velocityStar;\n    // std::cout << node->m_nextVelocity << std::endl;\n  }\n}\n\nvoid Simulator::updateDeformationGradient(double delta_t) {\n  for (auto &mp : m_materialPoints.particles()) {\n    Matrix3f gradVelocity = Matrix3f::Identity();\n    m_grid->forEachNeighbor(mp, [mp, delta_t, &gradVelocity](GridNode *node) {\n      gradVelocity += delta_t * node->nextVelocity() *\n                      node->gradBasisFunction(mp->m_position).transpose();\n    });\n\n    Matrix3f defNext = gradVelocity * mp->m_defElastic * mp->m_defPlastic;\n    mp->m_defElastic = gradVelocity * mp->m_defElastic;\n\n    // Push deformations exceeding critical deformation thresholds into Fp\n\n    JacobiSVD<Matrix3f> svd(mp->m_defElastic, ComputeFullU | ComputeFullV);\n    Matrix3f sigma = svd.singularValues()\n                         .cwiseMax(1 - m_snowModel.criticalCompression)\n                         .cwiseMin(1 + m_snowModel.criticalStretch)\n                         .asDiagonal();\n\n    mp->m_defPlastic =\n        svd.matrixV() * sigma.inverse() * svd.matrixU().transpose() * defNext;\n    mp->m_defElastic = svd.matrixU() * sigma * svd.matrixV().transpose();\n    if (!defNext.isApprox(mp->m_defElastic * mp->m_defPlastic)) {\n      logger->warn(\"Deformation update is incorrect\");\n    }\n  }\n}\n\nvoid Simulator::updateParticleVelocities(double delta_t, float alpha) {\n  for (auto &mp : m_materialPoints.particles()) {\n    Vector3f velocityPIC = Vector3f::Zero();\n    Vector3f velocityFLIP = mp->m_velocity;\n\n    m_grid->forEachNeighbor(\n        mp, [mp, &velocityPIC, &velocityFLIP](GridNode *node) {\n          float weight = node->basisFunction(mp->m_position);\n\n          velocityPIC += node->m_nextVelocity * weight;\n          velocityFLIP += (node->m_nextVelocity - node->m_velocity) * weight;\n        });\n\n    mp->m_velocity = (1 - alpha) * velocityPIC + alpha * velocityFLIP;\n  }\n}\n\nvoid Simulator::detectParticleCollisions(double delta_t) {\n  for (auto &mp : m_materialPoints.particles()) {\n    for (auto &collider : m_colliders) {\n      Vector3f position = mp->m_position;\n      if (collider->phi(position) > 0) {\n        continue;\n      }\n\n      // std::cout << mp->position() << std::endl;\n\n      Vector3f normal = collider->normal(position);\n      Vector3f relVelocity = mp->velocity() - collider->velocity();\n\n      // std::cout << collider->velocity() << std::endl;\n\n      double magnitude = relVelocity.dot(normal);\n      if (magnitude >= 0) {\n        continue;\n      }\n\n      // std::cout << \"GOT HERE\" << std::endl;\n\n      Vector3f tangentialVelocity = relVelocity - magnitude * normal;\n\n      // Only apply dynamic friction if the tangential velocity is large\n      // compared to the normal\n\n      double normComponent = collider->friction() * magnitude;\n      double tangentNorm = tangentialVelocity.norm();\n\n      if (collider->sticky() || tangentNorm <= -normComponent) {\n        relVelocity.setZero();\n      } else {\n        relVelocity = tangentialVelocity * (1 + normComponent / tangentNorm);\n      }\n\n      mp->m_velocity = relVelocity + collider->velocity();\n    }\n  }\n}\n\n/**\n * Uses backwards Euler integration to update the particle position for each\n * delta_t. At this point, the velocities should already have been updated\n * to the next delta_t.\n */\nvoid Simulator::updateParticlePositions(double delta_t) {\n  for (auto &mp : m_materialPoints.particles()) {\n    mp->m_position += delta_t * mp->m_velocity;\n\n    // mp->m_position = mp->m_position.array().min(\n    //     (m_grid->m_dim.array()).cast<float>() * m_grid->m_spacing);\n    // mp->m_position = mp->m_position.cwiseMax(0);\n  }\n}\n\nstd::string Simulator::exportVolumeData() {\n  std::stringstream ss;\n  ss << \"../volumes/density-\" << std::setfill('0') << std::setw(6)\n     << m_stepCount << \".vol\";\n\n  std::ofstream os(ss.str());\n\n  Vector3i dim = m_grid->dim();\n  Vector3f bboxMin = m_grid->origin();\n  Vector3f bboxMax = bboxMin + m_grid->extent();\n\n  bboxMin = Vector3f(-0.5, -0.5, -0.5);\n  bboxMax = Vector3f(0.5, 0.5, 0.5);\n\n  os.write(\"VOL\", 3);\n\n  char version = 3;\n  os.write((char *)&version, sizeof(char));\n\n  int value = 1;\n  os.write((char *)&value, sizeof(int));\n\n  os.write((char *)&dim.x(), sizeof(int));\n  os.write((char *)&dim.y(), sizeof(int));\n  os.write((char *)&dim.z(), sizeof(int));\n\n  value = 1;\n  os.write((char *)&value, sizeof(int));\n\n  os.write((char *)&bboxMin.x(), sizeof(float));\n  os.write((char *)&bboxMin.y(), sizeof(float));\n  os.write((char *)&bboxMin.z(), sizeof(float));\n\n  os.write((char *)&bboxMax.x(), sizeof(float));\n  os.write((char *)&bboxMax.y(), sizeof(float));\n  os.write((char *)&bboxMax.z(), sizeof(float));\n\n  auto nodes = m_grid->nodes();\n  for (unsigned i = nodes.size(); i-- > 0;) {\n    auto node = nodes[i];\n    float value = (float)node->mass();\n    os.write((char *)&value, sizeof(float));\n  }\n\n  return ss.str();\n}\n", "meta": {"hexsha": "b31029cb2d0360f7778cdba14b457645b45d13d0", "size": 11564, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/simulator.cpp", "max_stars_repo_name": "kvchen/snowsim", "max_stars_repo_head_hexsha": "09a75f24e86cc340ed327074904255fb08a3e7eb", "max_stars_repo_licenses": ["MIT"], "max_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.cpp", "max_issues_repo_name": "kvchen/snowsim", "max_issues_repo_head_hexsha": "09a75f24e86cc340ed327074904255fb08a3e7eb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-08-14T16:38:11.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-14T16:38:11.000Z", "max_forks_repo_path": "src/simulator.cpp", "max_forks_repo_name": "kvchen/snowsim", "max_forks_repo_head_hexsha": "09a75f24e86cc340ed327074904255fb08a3e7eb", "max_forks_repo_licenses": ["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.6737400531, "max_line_length": 80, "alphanum_fraction": 0.6337772397, "num_tokens": 3068, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4833964854793604}}
{"text": "#include <iostream>\n#include <vector>\n\n#include <Eigen/Dense>\n\n#include \"funnels/utils.hh\"\n\n#include \"funnels/distances.hh\"\n#include \"funnels/dynamics.hh\"\n#include \"funnels/funnels.hh\"\n#include \"aut/ta.hh\"\n#include \"aut/aut_collision.hh\"\n\nusing namespace std;\nusing namespace Eigen;\nusing namespace funnels;\nusing namespace lyapunov;\n\nvoid test_dist(){\n  \n  Matrix3d M;\n  M(0,0) = 1.;\n  M(1,1) = 2.;\n  M(2,2) = 3.;\n  \n  VectorXd v(3);\n  v(0)=11.;\n  v(1)=12.;\n  v(2)=13.;\n  \n  partial_so2_dist_t my_dist;\n  std::cout << my_dist.cp_Mv(M, v) << std::endl;\n  std::cout << my_dist.cp_vM(v, M) << std::endl;\n  std::cout << my_dist.cp_vv(v, v) << std::endl;\n  std::cout << my_dist.cp_MM(M, M) << std::endl;\n}\n\nvoid test_dyn(){\n  \n  kinematic_2d_sys_t my_sys;\n  VectorXd u(2);\n  VectorXd t(10);\n  MatrixXd x(4,10);\n  \n  t.setLinSpaced(10, 0., 10.);\n  u(0)=1.;\n  u(1)=1.33;\n  x(0,0) = -5.55;\n  x(1,0) = 6.55;\n  \n  \n  my_sys.compute(x,u,t);\n  \n  std::cout << x << std::endl;\n  std::cout << u << std::endl;\n  std::cout << t << std::endl;\n  \n}\n\nvoid test_funnel1(){\n  \n  std::cout << \"funnel 1\" << std::endl;\n  \n  clock_ta_t &ctrl_clk = utils_ext::clock_map.create_and_get(\"c_t\");\n  clock_ta_t &lcl_clk = utils_ext::clock_map.create_and_get(\"c_h\");\n\n  kinematic_2d_sys_t my_dyn;\n  partial_so2_dist_t my_dist;\n\n  MatrixXd P(my_dyn._dimx, my_dyn._dimx);\n  for (size_t i=0; i<my_dyn._dimx; i++){\n    P(i,i) = (double) i+1.;\n  }\n\n  fixed_ellipsoidal_lyap_t my_lyap(P, 0.5, my_dist);\n  \n  process_t &my_proc = utils_ext::process_map.create_and_get(\"proc_0\");\n  \n  // Init\n  Vector4d x0;\n  Vector2d u0;\n  x0(0) = 0.;\n  x0(1) = 2.;\n  u0(0) = 1.1;\n  u0(1) = 0.66;\n  const double t0=0., t1=10.;\n  \n  funnel_t<fixed_ellipsoidal_lyap_t<partial_so2_dist_t>, kinematic_2d_sys_t>\n      my_fun(100, \"fun_0\", my_proc, my_dyn, P, 0.5, my_dist);\n  \n  my_fun.compute(x0, t0, t1, u0);\n  \n  std::cout << my_fun.x() << std::endl;\n  std::cout << my_fun.u() << std::endl;\n  std::cout << my_fun.t() << std::endl;\n  \n}\n\nvoid test_funnel_sys(){\n  \n  std::cout << \"funnel sys\" << std::endl;\n  \n  using fun_t = funnel_t<fixed_ellipsoidal_lyap_t<partial_so2_dist_t>,\n      kinematic_2d_sys_t>;\n  \n  using fun_ptr_t = shared_ptr<fun_t>;\n  \n  utils_ext::clear_all_maps();\n  utils_ext::clock_map.create_and_get(\"c_t\");\n  utils_ext::clock_map.create_and_get(\"c_h\");\n  utils_ext::process_map.create_and_get(\"proc_0\");\n  \n  // Dummy event\n  event_t &dummy = utils_ext::event_map.create_and_get(\"no_action\");\n  \n  clock_ta_t &ctrl_clk = utils_ext::clock_map[\"c_t\"];\n  clock_ta_t &lcl_clk = utils_ext::clock_map[\"c_h\"];\n  \n  kinematic_2d_sys_t my_dyn;\n  partial_so2_dist_t my_dist;\n  \n  MatrixXd P(my_dyn._dimx, my_dyn._dimx);\n//  for (size_t i=0; i<my_dyn._dimx; i++){\n//    P(i,i) = (double) 1.;\n//  }\n  P(0,0) = 1.;\n  P(1,1) = 1.;\n  P(2,2) = 1.e-10;\n  P(3,3) = 1.e-10;\n  \n  fixed_ellipsoidal_lyap_t my_lyap(P, 0.5, my_dist);\n  \n  process_t &my_proc = utils_ext::process_map[\"proc_0\"];\n  \n  // Init\n  Vector4d x0, x1;\n  Vector2d u0, u1;\n  double sq2i = 1./std::sqrt(2.);\n  x0(0) = -1.; x1(0) = -sq2i;\n  x0(1) =  0.; x1(1) = -sq2i;\n  u0(0) = 1.; u1(0) = sq2i;\n  u0(1) = 0.; u1(1) = sq2i;\n  const double t0=0., t1=2.;\n  const size_t N=1000;\n  const double t_step = 20000;\n  \n  fun_ptr_t my_fun0_0 = make_shared<fun_t>(N, \"fun_0_0\", my_proc, my_dyn, 50.*P,\n      0.5, my_dist);\n  \n  fun_ptr_t my_fun1_0 = make_shared<fun_t>(N, \"fun_1_0\", my_proc, my_dyn,\n      100.*P, 0.5, my_dist);\n  \n  fun_ptr_t my_fun1_1 = make_shared<fun_t>(N, \"fun_1_1\", my_proc, my_dyn,\n      200.*P, 0.5, my_dist);\n  \n  my_fun0_0->compute(x0, t0, t1, u0);\n  my_fun1_0->compute(x1, t0, t1, u1);\n  \n  fun_t::set_parent(my_fun1_0, my_fun1_1);\n  \n  std::cout << my_fun0_0.use_count() << \" ; \" << my_fun1_0.use_count()\n      << \" ; \" << my_fun1_1.use_count() << std::endl;\n  \n  using fun_sys_t = funnel_sys_t<fun_t>;\n  using fun_sys_ptr_t = std::shared_ptr<fun_sys_t>;\n  \n  fun_sys_ptr_t my_fun_sys = std::make_shared<fun_sys_t>(ctrl_clk, lcl_clk);\n  \n  my_fun_sys->add_funnel(my_fun0_0, true);\n  my_fun_sys->add_funnel(my_fun1_0, true);\n  my_fun_sys->add_funnel(my_fun1_1, false);\n  \n  my_fun_sys->generate_transitions(t_step, true, true);\n  \n  std::cout << my_fun_sys->declare_proc() << std::endl;\n  std::cout << my_fun_sys->declare_edge() << std::endl;\n  \n  ta::ta_t my_ta(\"\");\n  \n  my_fun_sys->register_self(my_ta);\n  \n  std::cout << my_ta.declare() << std::endl;\n  \n  Vector4d x_obs;\n  Vector2d u_obs;\n  x_obs(0) = -1.;\n  x_obs(1) = -1.;\n  u_obs(0) = 1.;\n  u_obs(1) = 1.;\n  \n  const process_t &my_proc_obs = utils_ext::process_map.create_and_get\n      (\"obs_col\");\n  const clock_ta_t &obs_ctrl = utils_ext::clock_map.create_and_get(\"c_o\");\n  fun_ptr_t my_obs_fun = make_shared<fun_t>(N, \"obs\", my_proc_obs, my_dyn,\n      100.*P, 0.5, my_dist);\n  \n  my_obs_fun->compute(x_obs, t0, t1, u_obs);\n  \n  aut_col::aut_col<fun_t> my_aut_col(my_obs_fun, obs_ctrl);\n  \n  my_aut_col.register_self(my_ta);\n  \n  my_aut_col.compute_collisions(my_fun_sys, t_step);\n  \n  std::cout << my_ta.declare() << std::endl;\n}\n\n\n\n\nint main() {\n  \n//  test_dist();\n//  test_dyn();\n//  test_funnel1();\n  test_funnel_sys();\n  \n  return 0;\n}", "meta": {"hexsha": "94e7c1d5022f8e16bcd834269b3b0f87533c6f13", "size": 5133, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "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": "main.cpp", "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": "main.cpp", "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": 23.4383561644, "max_line_length": 80, "alphanum_fraction": 0.6339372687, "num_tokens": 1943, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.48339648547936037}}
{"text": "#include \"GridFilter.hh\"\n#include <Eigen/Core>\n#include <fstream>\n#include <cmath>\n#include <string>\nusing namespace std;\nusing namespace Eigen;\n\n//#define DEBUG_GRIDFILTER\n\nvoid GridFilter::ComputeCrossSectionOriginal(double value) {\n    auto lambda = [&value, this](double x){ return std::abs(x - value) <= m_AllowableError ? 1.0 : 0.0; };\n    m_CrossSectionModified = Eigen::MatrixXd::Zero(m_PMrows, m_PMcols);\n    #ifdef DEBUG_GRIDFILTER\n    std::cout << \"I am computed!!!\" << std::endl;\n    #endif\n    m_CrossSecOriginal = m_ParaboloidMatrix.unaryExpr(lambda);\n}\n\nvoid GridFilter::ComputeGradient(double xStep, double yStep) {\n    /**\n     *\n     * Computes dxPM and dyPM (components of gradient)\n     * Gradient matrixes are the folowing\n     *\n     *\t- dx - size [NxM-1]\n     *\t- dy - size [N-1xM]\n     *\n     * as gradient is computed with the neighbour elements in matrix\n     *\n     */\n    m_dxPM = (m_ParaboloidMatrix.rightCols(m_PMcols - 1) - m_ParaboloidMatrix.leftCols(m_PMcols - 1)) / xStep;\n    m_dyPM = (m_ParaboloidMatrix.bottomRows(m_PMrows - 1) - m_ParaboloidMatrix.topRows(m_PMrows - 1)) / yStep;\n}\n\n\n\nint GridFilter::ComputeCurrentDeviation() {\n    /**\n     *\n     * Algorithm:\n     *\t- Compute non-zero elements in original cross-section\n     *\t- For each element in matrixes compute respectivetly:\n     *\t  dx[i, j]*CrossSectionOriginal[i, j] and dy[i, j]*CrossSectionOriginal[i, j]\n     *\t  (this will leave only contour's gradient points)\n     *\t- Find the sqrt of sum of squares (to fing the length of gradient vector)\n     *\t- Sum all this values and divide by the number of non-zero values to find the avarage value of contour's gradient\n     *\t- Product with multiplier GradientInfluence, ceil and product with InitialDeviation\n     * \n     * \\return Deviation from the original coutour - the number of points that will be included in extended contour.\n     *\n     */\n\n    int numOfNonZero = (m_CrossSecOriginal.array() != 0).count();\n    if (numOfNonZero == 0) {\n        std::cerr << \"No contour found on this level. If you are sure that it shold be here, try the following:\" << std::endl\n            << \"- make grid step smaller \" << std::endl\n            << \"- make tolerance higher\" << std::endl;\n        return 0;\n    }\n    #ifdef DEBUG_GRIDFILTER\n    std::cout << \"numOfNonZero = \"  << numOfNonZero << std::endl;\n    #endif\n    ComputeAbsGradMatrix();\n    double  tmp =  m_AbsGrad.sum() / numOfNonZero;\n    #ifdef DEBUG_GRIDFILTER\n    std::cout << \"grad_len = \"  << tmp << std::endl;\n    #endif\n    return std::ceil(tmp) * m_InitialDeviation;\n}\n\nvoid GridFilter::ComputeAbsGradMatrix() {\n    int rowsnum = m_PMrows - 1, colsnum = m_PMcols - 1;\n    m_AbsGrad = ((m_dxPM.block(0, 0, rowsnum, colsnum).array() *\n                     m_CrossSecOriginal.block(0, 0, rowsnum, colsnum).array()).square() +\n                    (m_dyPM.block(0, 0, rowsnum, colsnum).array() *\n                     m_CrossSecOriginal.block(0, 0, rowsnum, colsnum).array()).square())\n                    .sqrt() * m_GradientInfluence ;\n\n}\n\nvoid GridFilter::GetCrossSectionOriginal(Eigen::MatrixXd& CSOmatTarget, double value, bool isCScomputed ) {\n    /**\n     *\n     * Returns cross-section z = value of ParaboloidMatrix: the plain contains contour\n     * \\param[in] CSOmatTarget The matrix where result will be written\n     * \\param[in] value The value for compute cross-section plane z = value\n     * \\param[in] isCScomputed It is false if CrossSecOriginal is not computed yet. It is necessary to avoid computing twice and ensure that it is not rubbish in this matrix\n     *\n     */\n    if (! isCScomputed)  ComputeCrossSectionOriginal(value);\n    CSOmatTarget = m_CrossSecOriginal;\n}\n\n\nvoid GridFilter::GetCrossSectionExtended(MatrixXd & CSEmatTarget,\n                                         double value, int deviation, bool isCScomputed, bool isDevConst) {\n    /**\n     *\n     * Returns cross-section plane z = value of ParaboloidMatrix with the extended contour\n     * \\param[in] CSEmatTarget The matrix where result will be written\n     * \\param[in] value The value for compute cross-section plane z = value\n     * \\param[in] deviation Deviation of the original contour\n     * \\param[in] isCScomputed It is false if CrossSecOriginal is not computed yet. It is necessary to avoid computing twice and ensure that it is not rubbish in this matrix\n     *\n     */\n\n    Eigen::MatrixXd tmpMat;\n    GetCrossSectionOriginal(tmpMat, value, isCScomputed);\n    #ifdef DEBUG_GRIDFILTER\n    std::cout << \" deviation = \" << deviation << std::endl;\n    #endif\n    if (deviation != 0) addPoints(deviation, isDevConst);\n    else {\n        CSEmatTarget = MatrixXd::Zero(m_PMrows, m_PMcols);\n    }\n    GetModifiedCrossSection(CSEmatTarget);\n}\n\nvoid GridFilter::GetCrossSectionExtendedAutoDev(Eigen::MatrixXd& CSEADmatTarget, double value) {\n    /**\n     *\n     * Returns cross-section z = value of ParaboloidMatrix (the plain contains contour) using value only. The deviation is computed automaticly and depends on gradient at contour points.\n     * \\param[in] CSEADmatTarget The matrix where result will be written\n     * \\param[in] value The value for compute cross-section plane z = value\n     *\n     */\n    ComputeCrossSectionOriginal(value);\n    GetCrossSectionExtended(CSEADmatTarget, value, ComputeCurrentDeviation(), true);\n}\n\nvoid GridFilter::GetCrossSectionExtendedIrregular(Eigen::MatrixXd& CSEImatTarget, double value) {\n     /**\n     *\n     * Returns cross-section z = value of ParaboloidMatrix (the plain contains contour) using value only. The deviation is computed automaticly,  depends on gradient at contour points and not constant for the level.\n     * \\param[in] CSEImatTarget The matrix where result will be written\n     * \\param[in] value The value for compute cross-section plane z = value\n     *\n     */\n    ComputeCrossSectionOriginal(value);\n    ComputeAbsGradMatrix();\n    GetCrossSectionExtended(CSEImatTarget, value, 1, true, false);\n}\n\nvoid GridFilter::makeCorridor(int curr_x, int curr_y, int deviation) {\n    /**\n     * Adds neighbour points to the InterestingPoints matrix for point (curr_x, curr_y)\n     * \\param[in] curr_x x-coordinate of the considered point\n     * \\param[in] curr_y y-coordinate of the considered point\n     * \\param[in] deviation Deviation from the original contour\n     */\n    for (int i = curr_x - deviation; i < curr_x + deviation + 1; i++) {\n        if (i < 0 || i >=  m_PMrows) continue;\n        for (int j = curr_y - deviation; j < curr_y + deviation + 1; j++) {\n            if (j <  0 || j >= m_PMcols) continue;\n            if (m_CrossSecOriginal(i, j) == 1.0) continue;\n            m_InterestingPoints.conservativeResize(2, m_InterestingPoints.cols() + 1);\n            m_InterestingPoints(0, m_InterestingPoints.cols() - 1) = i;\n            m_InterestingPoints(1, m_InterestingPoints.cols() - 1) = j;\n            m_CrossSectionModified(i, j) = 1.0;\n        }\n    }\n\n}\n\nvoid GridFilter::addPoints(int dev, bool isDevConst) {\n    /**\n     * Fills GridFilter#InterestingPoints matrix by extended contour points.\n     */\n    int deviation = 0;\n    if(isDevConst) deviation = dev;\n    m_InterestingPoints.resize(2, 0);\n    for(int i = 0; i < m_PMrows; i++) {\n        for (int j = 0; j < m_PMcols; j++) {\n            if (m_CrossSecOriginal(i, j) == 1.0) {\n                if(!isDevConst)  deviation = std::ceil(m_AbsGrad(i, j)) * m_InitialDeviation;\n                m_InterestingPoints.conservativeResize(2, m_InterestingPoints.cols() + 1);\n                m_InterestingPoints(0, m_InterestingPoints.cols() - 1) = i;\n                m_InterestingPoints(1, m_InterestingPoints.cols() - 1) = j;\n                m_CrossSectionModified(i, j) = 1.0;\n                makeCorridor(i, j, deviation);\n            }\n        }\n    }\n}\n\n", "meta": {"hexsha": "9655b2a86e5aceab0a1b76d88c1e437194b2ef73", "size": 7781, "ext": "cc", "lang": "C++", "max_stars_repo_path": "extra/GridFilter.cc", "max_stars_repo_name": "gnafit/gna", "max_stars_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-10-14T01:06:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-02T16:33:06.000Z", "max_issues_repo_path": "extra/GridFilter.cc", "max_issues_repo_name": "gnafit/gna", "max_issues_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "extra/GridFilter.cc", "max_forks_repo_name": "gnafit/gna", "max_forks_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_forks_repo_licenses": ["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.6096256684, "max_line_length": 215, "alphanum_fraction": 0.6576275543, "num_tokens": 2051, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.48339648547936037}}
{"text": "/*\n * @Description: IMU integration activity\n * @Author: Ge Yao\n * @Date: 2020-11-10 14:25:03\n */\n#ifndef IMU_INTEGRATION_ACTIVITY_HPP_\n#define IMU_INTEGRATION_ACTIVITY_HPP_\n\n// common:\n#include <ros/ros.h>\n\n#include <Eigen/Dense>\n#include <Eigen/Core>\n\n// config:\n#include \"imu_integration/config/config.hpp\"\n\n// subscribers:\n#include \"imu_integration/subscriber/imu_subscriber.hpp\"\n#include \"imu_integration/subscriber/odom_subscriber.hpp\"\n\n#include <nav_msgs/Odometry.h>\n\nnamespace imu_integration {\n\nnamespace estimator {\n\nclass Activity {\n  public:\n    Activity(void);\n    void Init(void);\n    bool Run(void);\n  private:\n    // workflow:\n    bool ReadData(void);\n    bool HasData(void);\n    bool UpdatePose(void);\n    bool PublishPose(void);\n\n    // utils:\n    /**\n     * @brief  get unbiased angular velocity in body frame\n     * @param  angular_vel, angular velocity measurement\n     * @return unbiased angular velocity in body frame\n     */\n    Eigen::Vector3d GetUnbiasedAngularVel(const Eigen::Vector3d &angular_vel);\n    /**\n     * @brief  get unbiased linear acceleration in navigation frame\n     * @param  linear_acc, linear acceleration measurement\n     * @param  R, corresponding orientation of measurement\n     * @return unbiased linear acceleration in navigation frame\n     */\n    Eigen::Vector3d GetUnbiasedLinearAcc(\n        const Eigen::Vector3d &linear_acc,\n        const Eigen::Matrix3d &R\n    );\n    /**\n     * @brief  get angular delta\n     * @param  index_curr, current imu measurement buffer index\n     * @param  index_prev, previous imu measurement buffer index\n     * @param  angular_delta, angular delta output\n     * @return true if success false otherwise\n     */\n    bool GetAngularDelta(\n        const size_t index_curr, const size_t index_prev,\n        Eigen::Vector3d &angular_delta\n    );\n    /**\n     * @brief  get velocity delta\n     * @param  index_curr, current imu measurement buffer index\n     * @param  index_prev, previous imu measurement buffer index\n     * @param  R_curr, corresponding orientation of current imu measurement\n     * @param  R_prev, corresponding orientation of previous imu measurement\n     * @param  velocity_delta, velocity delta output\n     * @return true if success false otherwise\n     */\n    bool GetVelocityDelta(\n        const size_t index_curr, const size_t index_prev,\n        const Eigen::Matrix3d &R_curr, const Eigen::Matrix3d &R_prev, \n        double &delta_t, Eigen::Vector3d &velocity_delta\n    );\n    /**\n     * @brief  update orientation with effective rotation angular_delta\n     * @param  angular_delta, effective rotation\n     * @param  R_curr, current orientation\n     * @param  R_prev, previous orientation\n     * @return void\n     */\n    void UpdateOrientation(\n        const Eigen::Vector3d &angular_delta,\n        Eigen::Matrix3d &R_curr, Eigen::Matrix3d &R_prev\n    );\n    /**\n     * @brief  update orientation with effective velocity change velocity_delta\n     * @param  velocity_delta, effective velocity change\n     * @return void\n     */\n    void UpdatePosition(const double &delta_t, const Eigen::Vector3d &velocity_delta);\n\n  private:\n    // node handler:\n    ros::NodeHandle private_nh_;\n\n    // subscriber:\n    std::shared_ptr<IMUSubscriber> imu_sub_ptr_;\n    std::shared_ptr<OdomSubscriber> odom_ground_truth_sub_ptr;\n    ros::Publisher odom_estimation_pub_;\n\n    // data buffer:\n    std::deque<IMUData> imu_data_buff_;\n    std::deque<OdomData> odom_data_buff_;\n\n    // config:\n    bool initialized_ = false;\n\n    IMUConfig imu_config_;\n    OdomConfig odom_config_;\n\n    // a. gravity constant:\n    Eigen::Vector3d G_;\n    // b. angular velocity:\n    Eigen::Vector3d angular_vel_bias_;\n    // c. linear acceleration:\n    Eigen::Vector3d linear_acc_bias_;\n\n    // IMU pose estimation:\n    Eigen::Matrix4d pose_ = Eigen::Matrix4d::Identity();\n    Eigen::Vector3d vel_ = Eigen::Vector3d::Zero();\n\n    nav_msgs::Odometry message_odom_;\n};\n\n} // namespace estimator\n\n} // namespace imu_integration\n\n#endif ", "meta": {"hexsha": "52739e6d658480dcbd9fb91b33f98ead7a6d1844", "size": 4000, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "IMU/05-imu-navigation/src/imu_integration/include/imu_integration/estimator/activity.hpp", "max_stars_repo_name": "lanqing30/SensorFusionCourse", "max_stars_repo_head_hexsha": "3fcf935d6a4191563afcf2d95b34718fba7f705a", "max_stars_repo_licenses": ["Apache-2.0"], "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": "05-imu-navigation/sensor-fusion-for-localization-and-mapping/workspace/assignments/05-imu-navigation/src/imu_integration/include/imu_integration/estimator/activity.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": "05-imu-navigation/sensor-fusion-for-localization-and-mapping/workspace/assignments/05-imu-navigation/src/imu_integration/include/imu_integration/estimator/activity.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": 29.197080292, "max_line_length": 86, "alphanum_fraction": 0.6905, "num_tokens": 951, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195385342971, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.48335715167524806}}
{"text": "\n#ifndef LIGHT_HPP\n#define\tLIGHT_HPP\n#include <armadillo>\n\nusing namespace arma;\nusing namespace std;\n\nclass Light{\n    \nprivate:\n    vec posicao, I;\n    \npublic:\n    \n    Light();\n    \n    Light(vec luz){\n\tthis->posicao << luz(0) << luz(1) << luz(2);\n\tthis->I << luz(3) << luz(4) << luz(5);\n    }\n\n    void SetI(vec I) {\n        this->I = I;\n    }\n\n    vec GetI() const {\n        return I;\n    }\n\n    void SetPosicao(vec posicao) {\n        this->posicao = posicao;\n    }\n\n    vec GetPosicao() const {\n        return posicao;\n    }\n\n};\n\n\n#endif\t/* LIGHT_HPP */\n\n", "meta": {"hexsha": "a1fcb0c269d2ad62ec85a4d36cd7be1cbb291468", "size": 562, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "raytracing/headers/Light.hpp", "max_stars_repo_name": "arthurflor/RayTracing", "max_stars_repo_head_hexsha": "8deedf33446bed259d8f7e2895024fd1300eb439", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-08-19T09:38:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-27T02:04:22.000Z", "max_issues_repo_path": "raytracing/headers/Light.hpp", "max_issues_repo_name": "arthurflor23/ray-tracing", "max_issues_repo_head_hexsha": "8deedf33446bed259d8f7e2895024fd1300eb439", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "raytracing/headers/Light.hpp", "max_forks_repo_name": "arthurflor23/ray-tracing", "max_forks_repo_head_hexsha": "8deedf33446bed259d8f7e2895024fd1300eb439", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 12.7727272727, "max_line_length": 45, "alphanum_fraction": 0.524911032, "num_tokens": 162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.734119526900183, "lm_q2_score": 0.6584175072643415, "lm_q1q2_score": 0.48335714893569615}}
{"text": "#include <igl/readOFF.h>\n//#undef IGL_STATIC_LIBRARY\n#include <igl/copyleft/cgal/mesh_boolean.h>\n#include <igl/opengl/glfw/Viewer.h>\n\n#include <Eigen/Core>\n#include <iostream>\n\n#include \"tutorial_shared_path.h\"\n\nEigen::MatrixXd VA,VB,VC;\nEigen::VectorXi J,I;\nEigen::MatrixXi FA,FB,FC;\nigl::MeshBooleanType boolean_type(\n  igl::MESH_BOOLEAN_TYPE_UNION);\n\nconst char * MESH_BOOLEAN_TYPE_NAMES[] =\n{\n  \"Union\",\n  \"Intersect\",\n  \"Minus\",\n  \"XOR\",\n  \"Resolve\",\n};\n\nvoid update(igl::opengl::glfw::Viewer &viewer)\n{\n  igl::copyleft::cgal::mesh_boolean(VA,FA,VB,FB,boolean_type,VC,FC,J);\n  Eigen::MatrixXd C(FC.rows(),3);\n  for(size_t f = 0;f<C.rows();f++)\n  {\n    if(J(f)<FA.rows())\n    {\n      C.row(f) = Eigen::RowVector3d(1,0,0);\n    }else\n    {\n      C.row(f) = Eigen::RowVector3d(0,1,0);\n    }\n  }\n  viewer.data().clear();\n  viewer.data().set_mesh(VC,FC);\n  viewer.data().set_colors(C);\n  std::cout<<\"A \"<<MESH_BOOLEAN_TYPE_NAMES[boolean_type]<<\" B.\"<<std::endl;\n}\n\nbool key_down(igl::opengl::glfw::Viewer &viewer, unsigned char key, int mods)\n{\n  switch(key)\n  {\n    default:\n      return false;\n    case '.':\n      boolean_type =\n        static_cast<igl::MeshBooleanType>(\n          (boolean_type+1)% igl::NUM_MESH_BOOLEAN_TYPES);\n      break;\n    case ',':\n      boolean_type =\n        static_cast<igl::MeshBooleanType>(\n          (boolean_type+igl::NUM_MESH_BOOLEAN_TYPES-1)%\n          igl::NUM_MESH_BOOLEAN_TYPES);\n      break;\n    case '[':\n      viewer.core.camera_dnear -= 0.1;\n      return true;\n    case ']':\n      viewer.core.camera_dnear += 0.1;\n      return true;\n  }\n  update(viewer);\n  return true;\n}\n\nint main(int argc, char *argv[])\n{\n  using namespace Eigen;\n  using namespace std;\n  igl::readOFF(TUTORIAL_SHARED_PATH \"/cheburashka.off\",VA,FA);\n  igl::readOFF(TUTORIAL_SHARED_PATH \"/decimated-knight.off\",VB,FB);\n  // Plot the mesh with pseudocolors\n  igl::opengl::glfw::Viewer viewer;\n\n  // Initialize\n  update(viewer);\n\n  viewer.data().show_lines = true;\n  viewer.callback_key_down = &key_down;\n  viewer.core.camera_dnear = 3.9;\n  cout<<\n    \"Press '.' to switch to next boolean operation type.\"<<endl<<\n    \"Press ',' to switch to previous boolean operation type.\"<<endl<<\n    \"Press ']' to push near cutting plane away from camera.\"<<endl<<\n    \"Press '[' to pull near cutting plane closer to camera.\"<<endl<<\n    \"Hint: investigate _inside_ the model to see orientation changes.\"<<endl;\n  viewer.launch();\n}\n", "meta": {"hexsha": "151a6f100fe309e6e43d70ab382b25d145ade920", "size": 2429, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "isometric-deformation/ext/libigl/tutorial/609_Boolean/main.cpp", "max_stars_repo_name": "jiayaozhang/CS-370-Mesh-Processing", "max_stars_repo_head_hexsha": "26646d29af8cbc0d461302afa137f12b508b8b1b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-03T11:30:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-03T11:30:05.000Z", "max_issues_repo_path": "isometric-deformation/ext/libigl/tutorial/609_Boolean/main.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/tutorial/609_Boolean/main.cpp", "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": 25.0412371134, "max_line_length": 77, "alphanum_fraction": 0.6500617538, "num_tokens": 709, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.4833571440151438}}
{"text": "// Boost.Geometry\r\n// Unit Test\r\n\r\n// Copyright (c) 2017-2018, Oracle and/or its affiliates.\r\n\r\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\r\n\r\n// Licensed under the Boost Software License version 1.0.\r\n// http://www.boost.org/users/license.html\r\n\r\n\r\n#include <geometry_test_common.hpp>\r\n\r\n#include <boost/geometry/geometries/geometries.hpp>\r\n\r\n#include <boost/geometry/algorithms/densify.hpp>\r\n#include <boost/geometry/algorithms/length.hpp>\r\n#include <boost/geometry/algorithms/num_points.hpp>\r\n#include <boost/geometry/algorithms/perimeter.hpp>\r\n\r\n#include <boost/geometry/iterators/segment_iterator.hpp>\r\n\r\n#include <boost/geometry/strategies/cartesian/densify.hpp>\r\n#include <boost/geometry/strategies/cartesian/distance_pythagoras.hpp>\r\n#include <boost/geometry/strategies/geographic/densify.hpp>\r\n#include <boost/geometry/strategies/geographic/distance.hpp>\r\n#include <boost/geometry/strategies/spherical/densify.hpp>\r\n#include <boost/geometry/strategies/spherical/distance_haversine.hpp>\r\n\r\n#include <boost/geometry/io/wkt/wkt.hpp>\r\n\r\n\r\nstruct check_lengths\r\n{\r\n    template <typename G, typename S>\r\n    void operator()(G const& g, G const& o, S const& s) const\r\n    {\r\n        double d1 = bg::length(g, s);\r\n        double d2 = bg::length(o, s);\r\n\r\n        BOOST_CHECK_CLOSE(d1, d2, 0.0001);\r\n    }\r\n};\r\n\r\nstruct check_perimeters\r\n{\r\n    template <typename G, typename S>\r\n    void operator()(G const& g, G const& o, S const& s) const\r\n    {\r\n        double d1 = bg::perimeter(g, s);\r\n        double d2 = bg::perimeter(o, s);\r\n\r\n        BOOST_CHECK_CLOSE(d1, d2, 0.0001);\r\n    }\r\n};\r\n\r\ntemplate <typename G, typename DistS>\r\ndouble inline shortest_length(G const& g, DistS const& dist_s)\r\n{\r\n    double min_len = (std::numeric_limits<double>::max)();\r\n    for (bg::segment_iterator<G const> it = bg::segments_begin(g);\r\n            it != bg::segments_end(g); ++it)\r\n    {\r\n        double len = bg::length(*it, dist_s);\r\n        min_len = (std::min)(min_len, len);\r\n    }\r\n    return min_len;\r\n}\r\n\r\ntemplate <typename G, typename DistS>\r\ndouble inline greatest_length(G const& o, DistS const& dist_s)\r\n{\r\n    double max_len = 0.0;\r\n    for (bg::segment_iterator<G const> it = bg::segments_begin(o);\r\n            it != bg::segments_end(o); ++it)\r\n    {\r\n        double len = bg::length(*it, dist_s);\r\n        max_len = (std::max)(max_len, len);\r\n    }\r\n    return max_len;\r\n}\r\n\r\ntemplate <typename G, typename CSTag = typename bg::cs_tag<G>::type>\r\nstruct cs_data\r\n{};\r\n\r\ntemplate <typename G>\r\nstruct cs_data<G, bg::cartesian_tag>\r\n{\r\n    bg::strategy::densify::cartesian<> compl_s;\r\n    bg::strategy::distance::pythagoras<> dist_s;\r\n};\r\n\r\ntemplate <typename G>\r\nstruct cs_data<G, bg::spherical_equatorial_tag>\r\n{\r\n    cs_data()\r\n        : model(6378137.0)\r\n        , compl_s(model)\r\n        , dist_s(6378137.0)\r\n    {}\r\n\r\n    bg::srs::sphere<double> model;\r\n    bg::strategy::densify::spherical<> compl_s;\r\n    bg::strategy::distance::haversine<double> dist_s;\r\n};\r\n\r\ntemplate <typename G>\r\nstruct cs_data<G, bg::geographic_tag>\r\n{\r\n    cs_data()\r\n        : model(6378137.0, 6356752.3142451793)\r\n        , compl_s(model)\r\n        , dist_s(model)\r\n    {}\r\n\r\n    bg::srs::spheroid<double> model;\r\n    bg::strategy::densify::geographic<> compl_s;\r\n    bg::strategy::distance::geographic<> dist_s;\r\n};\r\n\r\ntemplate <typename G, typename DistS, typename Check>\r\ninline void check_result(G const& g, G const& o, double max_distance,\r\n                         DistS const& dist_s, Check const& check)\r\n{\r\n    // geometry was indeed densified\r\n    std::size_t g_count = bg::num_points(g);\r\n    std::size_t o_count = bg::num_points(o);\r\n    BOOST_CHECK(g_count < o_count);\r\n\r\n    // all segments have lengths smaller or equal to max_distance\r\n    double gr_len = greatest_length(o, dist_s);\r\n    // NOTE: Currently geographic strategies can generate segments that have\r\n    //       lengths slightly greater than max_distance. In order to change\r\n    //       this the generation of new points should e.g. be recursive with\r\n    //       stop condition comparing the current distance calculated by\r\n    //       inverse strategy.\r\n    // NOTE: Closeness value tweaked for Andoyer\r\n    bool is_close = (gr_len - max_distance) / (std::max)(gr_len, max_distance) < 0.0001;\r\n    BOOST_CHECK(gr_len <= max_distance || is_close);\r\n\r\n    // the overall length or perimeter didn't change\r\n    check(g, o, dist_s);\r\n}\r\n\r\ntemplate <typename G, typename Check>\r\ninline void test_geometry(std::string const& wkt, Check const& check)\r\n{\r\n    cs_data<G> d;\r\n\r\n    G g;\r\n    bg::read_wkt(wkt, g);\r\n\r\n    {\r\n        bg::default_strategy def_s;\r\n        double max_distance = shortest_length(g, def_s) / 3.0;\r\n\r\n        G o;\r\n        bg::densify(g, o, max_distance);\r\n\r\n        check_result(g, o, max_distance, def_s, check);\r\n    }\r\n\r\n    {\r\n        double max_distance = shortest_length(g, d.dist_s) / 3.0;\r\n\r\n        G o;\r\n        bg::densify(g, o, max_distance, d.compl_s);\r\n\r\n        check_result(g, o, max_distance, d.dist_s, check);\r\n    }\r\n}\r\n\r\ntemplate <typename G>\r\ninline void test_linear(std::string const& wkt)\r\n{\r\n    test_geometry<G>(wkt, check_lengths());\r\n}\r\n\r\ntemplate <typename G>\r\ninline void test_areal(std::string const& wkt)\r\n{\r\n    test_geometry<G>(wkt, check_perimeters());\r\n}\r\n\r\ntemplate <typename P>\r\nvoid test_all()\r\n{\r\n    typedef bg::model::linestring<P> ls_t;\r\n    typedef bg::model::multi_linestring<ls_t> mls_t;\r\n\r\n    typedef bg::model::ring<P> ring_t;\r\n    typedef bg::model::polygon<P> poly_t;\r\n    typedef bg::model::multi_polygon<poly_t> mpoly_t;\r\n\r\n    typedef bg::model::ring<P, true, false> oring_t;\r\n    typedef bg::model::polygon<P, true, false> opoly_t;\r\n    typedef bg::model::multi_polygon<opoly_t> ompoly_t;\r\n\r\n    test_linear<ls_t>(\"LINESTRING(4 -4, 4 -1)\");\r\n    test_linear<ls_t>(\"LINESTRING(4 4, 4 1)\");\r\n    test_linear<ls_t>(\"LINESTRING(0 0, 180 0)\");\r\n    test_linear<ls_t>(\"LINESTRING(1 1, -179 -1)\");\r\n\r\n    test_linear<ls_t>(\"LINESTRING(1 1, 2 2, 4 2)\");\r\n    test_linear<mls_t>(\"MULTILINESTRING((1 1, 2 2),(2 2, 4 2))\");\r\n\r\n    test_areal<ring_t>(\"POLYGON((1 1, 1 2, 2 2, 1 1))\");\r\n    test_areal<poly_t>(\"POLYGON((1 1, 1 4, 4 4, 4 1, 1 1),(1 1, 2 2, 2 3, 1 1))\");\r\n    test_areal<mpoly_t>(\"MULTIPOLYGON(((1 1, 1 4, 4 4, 4 1, 1 1),(1 1, 2 2, 2 3, 1 1)),((4 4, 5 5, 5 4, 4 4)))\");\r\n    \r\n    test_areal<oring_t>(\"POLYGON((1 1, 1 2, 2 2))\");\r\n    test_areal<opoly_t>(\"POLYGON((1 1, 1 4, 4 4, 4 1),(1 1, 2 2, 2 3))\");\r\n    test_areal<ompoly_t>(\"MULTIPOLYGON(((1 1, 1 4, 4 4, 4 1),(1 1, 2 2, 2 3)),((4 4, 5 5, 5 4)))\");\r\n\r\n    test_areal<ring_t>(\"POLYGON((0 0,0 40,40 40,40 0,0 0))\");\r\n    test_areal<oring_t>(\"POLYGON((0 0,0 40,40 40,40 0))\");\r\n}\r\n\r\nint test_main(int, char* [])\r\n{\r\n    test_all< bg::model::point<double, 2, bg::cs::cartesian> >();\r\n    test_all< bg::model::point<double, 2, bg::cs::spherical_equatorial<bg::degree> > >();\r\n    test_all< bg::model::point<double, 2, bg::cs::geographic<bg::degree> > >();\r\n    \r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "f38e5607dc472bf33873a173419299745dce13bb", "size": 7010, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/geometry/test/algorithms/densify.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": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/geometry/test/algorithms/densify.cpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-04T18:00:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-04T18:00:00.000Z", "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/geometry/test/algorithms/densify.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 30.7456140351, "max_line_length": 114, "alphanum_fraction": 0.6292439372, "num_tokens": 2090, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.48335713417403886}}
{"text": "/**\n * @file \n * @author Denise Ratasich\n * @date 17.09.2013\n *\n * @brief Implementation of an Unscented Transform.\n */\n\n#include \"estimation/UnscentedTransform.h\"\n\n#include <stdexcept>\n#include <vector>\n#include <cmath>\n#include <Eigen/Cholesky>\n\nnamespace estimation \n{\n  UnscentedTransform::UnscentedTransform (VectorXd x, MatrixXd Px, ITransformer* transformer)\n  {    \n    // validation of params\n    if (x.size() != Px.rows()  ||  x.size() != Px.cols())\n      throw std::length_error(\"Initialization of Unscented Transform failed. \"\n\t\t\t      \"Invalid size of covariance, doesn't match that of vector x.\");\n\n    if (transformer == 0)\n      throw std::runtime_error(\"Initialization of Unscented Transform failed. \"\n\t\t\t       \"No transformer passed.\");\n\n    // initializes parameters\n    this->x = x;\n    this->Px = Px;\n    this->transformer = transformer;\n\n    // set default scaling factors\n    alpha = 1;\t\t\t// spread\n    beta = 2;\t\t\t// distribution = Gaussian\n    kappa = 3 - x.size();\n\n    // initialize output; to get the size of y, we must propagate a\n    // vector through the transformer\n    VectorXd testY = transformer->transform(VectorXd::Zero(x.size()));\n    y = VectorXd::Zero(testY.size());\n    Py = MatrixXd::Zero(testY.size(),testY.size());\n    Pxy = MatrixXd::Zero(x.size(),testY.size());\n\n    locked = false;\t// compute() not called yet\n  }\n\n  UnscentedTransform::~UnscentedTransform () \n  {\n    // no space to free\n  }\n\n  void UnscentedTransform::compute (void)\n  {\n    std::vector<double> weights;\n    std::vector<VectorXd> sigmaPoints_prior;\n    std::vector<VectorXd> sigmaPoints_post;\n\n    if (locked)\n      throw new std::runtime_error(\"Unscented Transform. Called compute a second time - not allowed.\");\n\n    locked = true;\n\n    try\n    {\n      // fill arrays: sigma points with associated weights\n      generateSigmaPoints(sigmaPoints_prior, weights);\n\n      // pop last element because its not for calculating the mean;\n      // popped value will replace first element when calculating the\n      // covariance\n      double w0_cov = weights.back();\n      weights.pop_back();\n    \n      // calculate mean y -----------------------------------\n      for (int i = 0; i < sigmaPoints_prior.size(); i++)\n      {\n\t// propagate the sigma points through the function and save\n\t// (needed for covariance) and covariance cannot be accumulated\n\t// here too because the mean is needed :(\n\tVectorXd post = transformer->transform(sigmaPoints_prior[i]);\n\tsigmaPoints_post.push_back(post);\n    \n\t// accumulate to the approximated mean\n\ty += weights[i] * post;\n      }\n\n      // calculate covariances Py, Pxy ----------------------\n      weights[0] = w0_cov;\t\t\t// prepare weights\n      VectorXd t(sigmaPoints_post[0].size());\t// help vector (for transform)\n\n      for (int i = 0; i < sigmaPoints_post.size(); i++)\n      {\n\tt = sigmaPoints_post[i] - y;\n\tPy += weights[i] * t * t.transpose();\n\tPxy += weights[i] * (sigmaPoints_prior[i] - x) * t.transpose();\n      }\n    } \n    catch (std::exception& e) \n    {\n      std::string additionalInfo = \"Computation of Unscented Transform failed. \";\n      throw std::runtime_error(additionalInfo + e.what());\n    }\n  }\n\n  // -----------------------------------------\n  // getters and setters\n  // -----------------------------------------\n  \n  VectorXd UnscentedTransform::mean (void) const\n  {\n    return y;\n  }\n  \n  MatrixXd UnscentedTransform::covariance (void) const\n  {\n    return Py;\n  }\n  \n  MatrixXd UnscentedTransform::crossCovarianceXY (void) const\n  {\n    return Pxy;\n  }\n\n  // -----------------------------------------\n  // private functions\n  // -----------------------------------------\n  void UnscentedTransform::generateSigmaPoints (std::vector<VectorXd>& sigmaPoints, std::vector<double>& weights)\n  {\n    int L = x.size();\n\n    // calculate values which are needed more often\n    double alphaPow2 = alpha*alpha;\n    double lambda = alphaPow2 * (L + kappa) - L;\n    double lPlusLambda = L + lambda;\n\n    // calculate matrix square root ----------------\n    \n    // matrix which should form the sigma points (matrix to take the\n    // root of)\n    MatrixXd msr(L,L);\n    msr = lPlusLambda * Px;\n\n    // calculate the root of the matrix; this is done here by standard\n    // Cholesky decomposition (this works for symmetric,\n    // positive-definite matrices, which Px is like)\n    msr = msr.llt().matrixL();\n\n    // generate sigma points -----------------------\n    VectorXd col(x.size());\n\n    // chi_0\n    sigmaPoints.push_back(x);\n\n    // chi_i = x + msr_i-1, i=1,..,L\n    for (int i = 1; i <= L; i++) \n      sigmaPoints.push_back(x + msr.col(i-1));\n\n    // chi_i = x - msr_i-L-1, i=L+1,..,2L\n    for (int i = 1; i <= L; i++) \n      sigmaPoints.push_back(x - msr.col(i-1));\n\n    // set weights --------------------------------\n\n    // W_0 for mean\n    weights.push_back(lambda / lPlusLambda);\n\n    // W_1, W_2, ..., W_2L for mean AND covariance\n    for (int i = 1; i <= 2*L; i++)\n      weights.push_back(1 / (2 * lPlusLambda));\n    \n    // W_0 for covariance\n    weights.push_back(lambda/lPlusLambda + 1 - alphaPow2 + beta);\n  }\n}\n", "meta": {"hexsha": "87a63d56c2928a6ae1cc6012c1ebd485e99def99", "size": 5101, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sf_estimation/src/estimation/UnscentedTransform.cpp", "max_stars_repo_name": "tuw-cpsg/sf-pkg", "max_stars_repo_head_hexsha": "267d2ec4b886dee70d53a23b695acfa7f7edbeb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 30.0, "max_stars_repo_stars_event_min_datetime": "2015-09-30T09:47:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-12T16:01:11.000Z", "max_issues_repo_path": "sf_estimation/src/estimation/UnscentedTransform.cpp", "max_issues_repo_name": "ros-agriculture/sf-pkg", "max_issues_repo_head_hexsha": "267d2ec4b886dee70d53a23b695acfa7f7edbeb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-05-13T04:59:08.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-13T14:39:24.000Z", "max_forks_repo_path": "sf_estimation/src/estimation/UnscentedTransform.cpp", "max_forks_repo_name": "tuw-cpsg/sf-pkg", "max_forks_repo_head_hexsha": "267d2ec4b886dee70d53a23b695acfa7f7edbeb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2016-04-17T21:13:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T17:00:28.000Z", "avg_line_length": 28.8192090395, "max_line_length": 113, "alphanum_fraction": 0.5957655362, "num_tokens": 1305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.6477982315512488, "lm_q1q2_score": 0.48334752749042403}}
{"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_MAJORITY_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_MAJORITY_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n    @ingroup group-predicates\n    This function object returns @ref True if at least two inputs\n    are not @ref Zero else @ref False.\n\n\n    @par Header <boost/simd/function/majority.hpp>\n\n    @par Note\n\n     Using `majority(x,y,z)` is similar to: `(x!= 0)+(y!= 0)+(z!= 0) >= 2`\n\n    @par Example:\n\n      @snippet majority.cpp majority\n\n    @par Possible output:\n\n      @snippet majority.txt majority\n\n  **/\n  as_logical_t<Value> majority(Value const& x, Value const& y, Value const& z);\n} }\n#endif\n\n#include <boost/simd/function/scalar/majority.hpp>\n#include <boost/simd/function/simd/majority.hpp>\n\n#endif\n", "meta": {"hexsha": "90e9047be5c6f481225e9b12cb3ace46aecb7989", "size": 1171, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/majority.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/majority.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/majority.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": 24.914893617, "max_line_length": 100, "alphanum_fraction": 0.5824081981, "num_tokens": 262, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.4833475173435764}}
{"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 winner_determination_in_MUCA_example.cpp\n * @brief\n * @author Robert Rosolek\n * @version 1.0\n * @date 2014-1-9\n */\n\n#include \"paal/auctions/auction_components.hpp\"\n#include \"paal/auctions/xor_bids.hpp\"\n#include \"paal/auctions/winner_determination_in_MUCA/winner_determination_in_MUCA.hpp\"\n\n#include <boost/function_output_iterator.hpp>\n#include <boost/range/algorithm/copy.hpp>\n\n#include <algorithm>\n#include <iostream>\n#include <iterator>\n#include <string>\n#include <tuple>\n#include <unordered_map>\n#include <unordered_set>\n#include <utility>\n#include <vector>\n\n//! [Winner Determination In MUCA Example]\n\nint main()\n{\n   using Bidder = std::string;\n   using Item = std::string;\n   using Items = std::unordered_set<Item>;\n   using Value = double;\n   using Bid = std::pair<Items, Value>;\n   using Bids = std::vector<Bid>;\n\n   // create auction\n   const std::unordered_map<Bidder, Bids> bids {\n      {\"John\", {\n         {{\"ball\", \"kite\"}, 2},\n         {{\"umbrella\"}, 3},\n         {{\"orange\"}, 1.75},\n         {{\"ball\", \"kite\", \"umbrella\"}, 5},\n         {{\"ball\", \"kite\", \"orange\", \"umbrella\"}, 6.75},\n      }},\n      {\"Bob\", {\n         {{\"orange\"}, 1.5},\n         {{\"apple\"}, 2.0},\n         {{\"apple\", \"orange\"}, 4},\n      }},\n      {\"Steve\", {\n         {{\"apple\"}, 1},\n         {{\"umbrella\"}, 4},\n         {{\"apple\", \"umbrella\"}, 5},\n      }},\n   };\n   const std::vector<Bidder> bidders {\"John\", \"Bob\", \"Steve\"};\n   const std::vector<Item> items {\"apple\", \"ball\", \"orange\", \"kite\", \"umbrella\"};\n   auto get_bids = [&](const Bidder& bidder) -> const Bids& { return bids.at(bidder); };\n   auto get_value = [](const Bid& bid) { return bid.second; };\n   auto get_items = [](const Bid& bid) -> const Items& { return bid.first; };\n   auto auction = paal::auctions::make_xor_bids_to_gamma_oracle_auction(\n      bidders, items, get_bids, get_value, get_items\n   );\n\n   // determine winners\n   Value social_welfare = 0;\n   auto valuation = paal::auctions::make_xor_bids_to_value_query_auction(\n      bidders, items, get_bids, get_value, get_items\n   );\n   paal::auctions::determine_winners_in_gamma_oracle_auction(\n      auction,\n      boost::make_function_output_iterator([&](std::pair<Bidder, Items> p)\n      {\n         auto bidder = p.first;\n         auto& cur_items = p.second;\n         social_welfare += valuation.call<paal::auctions::value_query>(bidder, cur_items);\n         std::cout << bidder << \" got bundle: \";\n         boost::copy(cur_items, std::ostream_iterator<Item>(std::cout, \", \"));\n         std::cout << std::endl;\n      })\n   );\n   std::cout << \"social welfare: \" << social_welfare << std::endl;\n\n   return 0;\n}\n\n//! [Winner Determination In MUCA Example]\n", "meta": {"hexsha": "02fe21ce62373221ffcf48b7dccade844ad5eebd", "size": 3004, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/auctions/winner_determination_in_MUCA/winner_determination_in_MUCA_example.cpp", "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": "examples/auctions/winner_determination_in_MUCA/winner_determination_in_MUCA_example.cpp", "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": "examples/auctions/winner_determination_in_MUCA/winner_determination_in_MUCA_example.cpp", "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": 31.2916666667, "max_line_length": 90, "alphanum_fraction": 0.5888814913, "num_tokens": 806, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.4833475173435764}}
{"text": "#include <Engine/MeshEdit/ASAP.h>\n\n#include <Engine/MeshEdit/ARAP.h>\n\n#include <Engine/Primitive/TriMesh.h>\n\n#include <Eigen/Sparse>\n\n#include <Engine/MeshEdit/Paramaterize.h>\n\nusing namespace Ubpa;\nusing namespace std;\nusing namespace Eigen;\n\nARAP::ARAP(Ptr<TriMesh> triMesh)\n\t: heMesh(make_shared<HEMesh<V>>())\n{\n\tInit(triMesh);\n}\n\nvoid ARAP::Clear() {\n\theMesh->Clear();\n\ttriMesh = nullptr;\n}\n\nbool ARAP::Init(Ptr<TriMesh> triMesh) {\n\tClear();\n\n\tif (triMesh == nullptr)\n\t\treturn true;\n\n\tif (triMesh->GetType() == TriMesh::INVALID) {\n\t\tprintf(\"ERROR::ARAP::Init:\\n\"\n\t\t\t\"\\t\"\"trimesh is invalid\\n\");\n\t\treturn false;\n\t}\n\n\t/*auto paramaterize = Paramaterize::New(triMesh);\n\tparamaterize->setShape(1);\n\tparamaterize->setWeight(0);\n\tparamaterize->Run();*/\n\tauto asap = ASAP::New(triMesh);\n\tasap->Run();\n\n\t// init half-edge structure\n\tsize_t nV = triMesh->GetPositions().size();\n\tvector<vector<size_t>> triangles;\n\ttriangles.reserve(triMesh->GetTriangles().size());\n\tfor (auto triangle : triMesh->GetTriangles())\n\t\ttriangles.push_back({ triangle->idx[0], triangle->idx[1], triangle->idx[2] });\n\theMesh->Reserve(nV);\n\theMesh->Init(triangles);\n\n\tif (!heMesh->IsTriMesh() || !heMesh->HaveBoundary()) {\n\t\tprintf(\"ERROR::ARAP::Init:\\n\"\n\t\t\t\"\\t\"\"trimesh is not a triangle mesh or hasn't a boundaries\\n\");\n\t\theMesh->Clear();\n\t\treturn false;\n\t}\n\n\t// triangle mesh's texcoords and positions ->  half-edge structure's texcoords and positions\n\tfor (int i = 0; i < nV; i++) {\n\t\tauto v = heMesh->Vertices().at(i);\n\t\tv->coord = triMesh->GetTexcoords()[i].cast_to<vecf2>();\n\t\tv->pos = triMesh->GetPositions()[i].cast_to<vecf3>();\n\t}\n\n\t// flatten the triangles to the plane\n\tflatten();\n\n\t// set two fixed vertices\n\tif (nV < 2) {\n\t\tprintf(\"ERROR::ARAP::Init:\\n\"\n\t\t\t\"\\t\"\"need more vertices\\n\");\n\t\theMesh->Clear();\n\t\treturn false;\n\t}\n\tsize_t a = heMesh->Boundaries()[0].size() / 2;\n\tauto v1 = heMesh->Boundaries()[0][0]->Origin();\n\tauto v2 = heMesh->Boundaries()[0][a]->End();\n\tfixed_vertices_.push_back(heMesh->Index(v1));\n\tfixed_coords_.push_back(vecf2(0, 0));\n\n\tthis->triMesh = triMesh;\n\treturn true;\n}\n\nbool ARAP::Run() {\n\tif (heMesh->IsEmpty() || !triMesh) {\n\t\tprintf(\"ERROR::MinSurf::Run\\n\"\n\t\t\t\"\\t\"\"heMesh->IsEmpty() || !triMesh\\n\");\n\t\treturn false;\n\t}\n\tkernelARAP();\n\n\t// half-edge structure -> triangle mesh\n\tsize_t nV = heMesh->NumVertices();\n\tsize_t nF = heMesh->NumPolygons();\n\n\tvector<pointf2> texcoords;\n\tfor (auto v : heMesh->Vertices())\n\t\ttexcoords.push_back(v->coord.cast_to<pointf2>());\n\ttriMesh->Update(texcoords);\n\n\tcout << \"ARAP done\" << endl;\n\treturn true;\n}\n\nbool ARAP::Show()\n{\n\tif (heMesh->IsEmpty() || !triMesh) {\n\t\tprintf(\"ERROR::ARAP::Show\\n\"\n\t\t\t\"\\t\"\"heMesh->IsEmpty() || !triMesh\\n\");\n\t\treturn false;\n\t}\n\n\tkernelARAP();\n\n\t// half-edge structure -> triangle mesh\n\tsize_t nV = heMesh->NumVertices();\n\tsize_t nF = heMesh->NumPolygons();\n\tvector<pointf3> positions;\n\tvector<unsigned> indice;\n\tpositions.reserve(nV);\n\tindice.reserve(3 * nF);\n\n\t// Set positions\n\tfor (auto v : heMesh->Vertices()) {\n\t\tpositions.push_back(v->coord.cast_to<pointf3>());\n\t}\n\n\tfor (auto f : heMesh->Polygons()) { // f is triangle\n\t\tfor (auto v : f->BoundaryVertice()) { // vertices of the triangle\n\t\t\tindice.push_back(static_cast<unsigned>(heMesh->Index(v)));\n\t\t}\n\t}\n\n\ttriMesh->Init(indice, positions);\n\n\t// Set texcoords\n\tvector<pointf2> texcoords;\n\tfor (auto v : heMesh->Vertices())\n\t\ttexcoords.push_back(v->coord.cast_to<pointf2>());\n\ttriMesh->Update(texcoords);\n\n\tcout << \"ARAP done\" << endl;\n\treturn true;\n}\n\nvoid ARAP::kernelARAP()\n{\n\tsize_t nV = heMesh->NumVertices();\n\tSparseMatrix<double> A(nV, nV);\n\tGlobalMatrixA(A);\n\t//cout << A << endl;\n\n\tSimplicialLLT<SparseMatrix<double>> solver;\n\tsolver.compute(A);\n\n\tif (times < 0 || times > 100)\n\t\ttimes = 10;\n\tcout << \"time = \" << times << endl;\n\n\tfor (int count = 0; count < times; count++)\n\t{\n\t\tLocalSetL();\n\t\tGlobalSolveU(solver);\n\t}\n}\n\nvoid ARAP::flatten()\n{\n\tsize_t nT = heMesh->NumPolygons();\n\tauto triangles = heMesh->Polygons();\n\n\tfor (int i = 0; i < nT; i++) {\n\t\tauto x_tmp = triangles[i]->BoundaryVertice();\n\n\t\tif (Paramaterize::EqualVector(x_tmp[0]->pos, x_tmp[1]->pos) || Paramaterize::EqualVector(x_tmp[1]->pos, x_tmp[2]->pos) || Paramaterize::EqualVector(x_tmp[2]->pos, x_tmp[0]->pos))\n\t\t{\n\t\t\ttriangles[i]->cot = { 1, 1, 1 };\n\t\t\ttriangles[i]->x_flatten = { vecf2(1, 1), vecf2(1, 1), vecf2(1, 1) };\n\t\t\tcontinue;\n\t\t}\n\n\t\ttriangles[i]->x_flatten.push_back(vecf2(0, 0));\n\t\ttriangles[i]->x_flatten.push_back(vecf2((x_tmp[1]->pos - x_tmp[0]->pos).norm(), 0));\n\t\tfloat x = (x_tmp[2]->pos - x_tmp[0]->pos).dot(x_tmp[1]->pos - x_tmp[0]->pos) / (x_tmp[1]->pos - x_tmp[0]->pos).norm();\n\t\ttriangles[i]->x_flatten.push_back(vecf2(x, pow(pow((x_tmp[2]->pos - x_tmp[0]->pos).norm(), 2) - pow(x, 2), 0.5)));\n\n\t\t//cout << triangles[i]->x_flatten[0] << triangles[i]->x_flatten[1] << triangles[i]->x_flatten[2] << endl;\n\n\n\t\tfor (int j = 0; j < 3; j++) {\n\t\t\tdouble cos_theta = (triangles[i]->x_flatten[j] - triangles[i]->x_flatten[j == 0 ? 2 : j - 1])\n\t\t\t\t.cos_theta(triangles[i]->x_flatten[j == 2 ? 0 : j + 1] - triangles[i]->x_flatten[j == 0 ? 2 : j - 1]);\n\t\t\tdouble abs_cot = pow(cos_theta * cos_theta / (1 - cos_theta * cos_theta), 0.5);\n\n\t\t\ttriangles[i]->cot.push_back(cos_theta > 0 ? abs_cot : -abs_cot);\n\t\t\t//cout << triangles[i]->cot[j] << endl;\n\t\t}\n\t}\n}\n\nvoid ARAP::LocalSetL()\n{\n\tfor (auto triangle : heMesh->Polygons())\n\t{\n\t\tauto vertices = triangle->BoundaryVertice();\n\t\tMatrix2d X, U;\n\t\tX << (triangle->x_flatten[0] - triangle->x_flatten[1])[0], (triangle->x_flatten[1] - triangle->x_flatten[2])[0],\n\t\t\t(triangle->x_flatten[0] - triangle->x_flatten[1])[1], (triangle->x_flatten[1] - triangle->x_flatten[2])[1];\n\t\tU << (vertices[0]->coord - vertices[1]->coord)[0], (vertices[1]->coord - vertices[2]->coord)[0],\n\t\t\t(vertices[0]->coord - vertices[1]->coord)[1], (vertices[1]->coord - vertices[2]->coord)[1];\n\t\tMatrix2d J = U * X.inverse();\n\n\t\tJacobiSVD<Matrix2d> svd(J, ComputeFullU | ComputeFullV);\n\t\tif (J.determinant() > 0)\n\t\t\ttriangle->L = svd.matrixU() * svd.matrixV().transpose();\n\t\telse\n\t\t{\n\t\t\tMatrix2d D;\n\t\t\tD(0, 0) = 1; D(0, 1) = 0; D(1, 0) = 0; D(1, 1) = -1;\n\t\t\ttriangle->L = svd.matrixU() * D * svd.matrixV().transpose();\n\t\t}\n\t\t//cout << \"L:\" << triangle->L << endl;\n\t}\n}\n\nvoid ARAP::GlobalSolveU(SimplicialLLT<SparseMatrix<double>>& solver)\n{\n\tsize_t nV = heMesh->NumVertices();\n\tVectorXd b_x = VectorXd::Zero(nV);\n\tVectorXd b_y = VectorXd::Zero(nV);\n\n\tauto vertice_list_ = heMesh->Vertices();\n\n\tfor (int i = 0; i < nV; i++)\n\t{\n\t\tif (i == fixed_vertices_[0])\n\t\t{\n\t\t\tb_x(i) += fixed_coords_[0][0];\n\t\t\tb_y(i) += fixed_coords_[0][1];\n\t\t\tcontinue;\n\t\t}\n\t\t/*if (i == fixed_vertices_[1])\n\t\t{\n\t\t\tb_x(i) += fixed_coords_[1][0];\n\t\t\tb_y(i) += fixed_coords_[1][1];\n\t\t\tcontinue;\n\t\t}*/\n\t\tVector2d sum = Vector2d::Zero();\n\t\tfor (auto he : vertice_list_[i]->OutHEs())\n\t\t{\n\t\t\t// Left Triangle\n\t\t\tauto triangle = he->Polygon();\n\t\t\tsize_t t = 0;\n\t\t\tint index = 0;\n\t\t\tdouble coe_ij = 0;\n\t\t\tif (triangle != nullptr)\n\t\t\t{\n\t\t\t\tfor (index = 0; heMesh->Index(triangle->BoundaryVertice()[index]) != i; index++);\n\t\t\t\tauto diffx = triangle->x_flatten[index] - triangle->x_flatten[index == 2 ? 0 : index + 1];\n\t\t\t\tcoe_ij += triangle->cot[index];\n\t\t\t\tsum += triangle->cot[index] * triangle->L * Vector2d(diffx[0], diffx[1]);\n\t\t\t}\n\t\t\t// Right Triangle\n\t\t\ttriangle = he->Pair()->Polygon();\n\t\t\tif (triangle != nullptr)\n\t\t\t{\n\t\t\t\tfor (index = 0; heMesh->Index(triangle->BoundaryVertice()[index]) != i; index++);\n\t\t\t\tauto diffx = triangle->x_flatten[index] - triangle->x_flatten[index == 0 ? 2 : index - 1];\n\t\t\t\tcoe_ij += triangle->cot[index == 0 ? 2 : index - 1];\n\t\t\t\tsum += triangle->cot[index == 0 ? 2 : index - 1] * triangle->L * Vector2d(diffx[0], diffx[1]);\n\t\t\t}\n\t\t\t// Set\n\t\t\tint j = static_cast<int>(heMesh->Index(he->End()));\n\t\t\tif (j == fixed_vertices_[0])\n\t\t\t{\n\t\t\t\tb_x(i) -= (-coe_ij) * fixed_coords_[0][0];\n\t\t\t\tb_y(i) -= (-coe_ij) * fixed_coords_[0][1];\n\t\t\t}\n\t\t\t/*else if (j == fixed_vertices_[1])\n\t\t\t{\n\t\t\t\tb_x(i) -= (-coe_ij) * fixed_coords_[1][0];\n\t\t\t\tb_y(i) -= (-coe_ij) * fixed_coords_[1][1];\n\t\t\t}*/\n\n\t\t}\n\n\t\tb_x(i) += sum(0);\n\t\tb_y(i) += sum(1);\n\t}\n\t//cout << b_x << endl << b_y << endl;\n\tVectorXd u_x = solver.solve(b_x);\n\tVectorXd u_y = solver.solve(b_y);\n\t//cout << u_x << endl << u_y << endl;\n\n\tfor (int i = 0; i < nV; i++)\n\t{\n\t\tvertice_list_[i]->coord = vecf2(u_x(i), u_y(i));\n\t}\n}\n\nvoid ARAP::GlobalMatrixA(SparseMatrix<double>& A)\n{\n\tvector<Triplet<double>> A_Triplet;\n\tsize_t nV = heMesh->NumVertices();\n\tauto vertice_list_ = heMesh->Vertices();\n\n\tfor (int i = 0; i < nV; i++)\n\t{\n\t\t//if (i == fixed_vertices_[0] || i == fixed_vertices_[1])\n\t\tif (i == fixed_vertices_[0])\n\t\t{\n\t\t\tA_Triplet.push_back(Triplet<double>(i, i, 1));\n\t\t\tcontinue;\n\t\t}\n\t\tdouble sum = 0;\n\t\tfor (auto he : vertice_list_[i]->OutHEs())\n\t\t{\n\t\t\tdouble coe_ij = 0;\n\t\t\t// Left Triangle\n\t\t\tauto triangle = he->Polygon();\n\t\t\tsize_t t = 0;\n\t\t\tint index = 0;\n\t\t\tif (triangle != nullptr)\n\t\t\t{\n\t\t\t\tfor (index = 0; heMesh->Index(triangle->BoundaryVertice()[index]) != i; index++);\n\t\t\t\tcoe_ij += triangle->cot[index];\n\t\t\t}\n\t\t\t// Right Triangle\n\t\t\ttriangle = he->Pair()->Polygon();\n\t\t\tif (triangle != nullptr)\n\t\t\t{\n\t\t\t\tfor (index = 0; heMesh->Index(triangle->BoundaryVertice()[index]) != i; index++);\n\t\t\t\tcoe_ij += triangle->cot[index == 0 ? 2 : index - 1];\n\t\t\t}\n\t\t\t// Set\n\t\t\tsum += coe_ij;\n\t\t\tint j = static_cast<int>(heMesh->Index(he->End()));\n\t\t\t//if (j != fixed_vertices_[0] && j != fixed_vertices_[1])\n\t\t\tif (j != fixed_vertices_[0])\n\t\t\t\tA_Triplet.push_back(Triplet<double>(i, j, -coe_ij));\n\t\t}\n\t\tA_Triplet.push_back(Triplet<double>(i, i, sum));\n\t}\n\n\tA.setFromTriplets(A_Triplet.begin(), A_Triplet.end());\n}\n\nvoid ARAP::setTimes(int time)\n{\n\ttimes = time;\n}\n", "meta": {"hexsha": "7000efc787d4b3579b0c3d695142c8c51ea1d2cf", "size": 9649, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Homeworks/4_MinSurfMeshPara/project/src/Engine/MeshEdit/ARAP.cpp", "max_stars_repo_name": "whirl-wind/USTC_CG", "max_stars_repo_head_hexsha": "329b615dc20b7710c96e1fb1358d98e77d298e12", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Homeworks/4_MinSurfMeshPara/project/src/Engine/MeshEdit/ARAP.cpp", "max_issues_repo_name": "whirl-wind/USTC_CG", "max_issues_repo_head_hexsha": "329b615dc20b7710c96e1fb1358d98e77d298e12", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Homeworks/4_MinSurfMeshPara/project/src/Engine/MeshEdit/ARAP.cpp", "max_forks_repo_name": "whirl-wind/USTC_CG", "max_forks_repo_head_hexsha": "329b615dc20b7710c96e1fb1358d98e77d298e12", "max_forks_repo_licenses": ["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.1039325843, "max_line_length": 180, "alphanum_fraction": 0.6186133278, "num_tokens": 3291, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.6477982247516797, "lm_q1q2_score": 0.4833475151033264}}
{"text": "/**\n * @file lsh_test.cpp\n *\n * Unit tests for the 'LSHSearch' class.\n */\n#include <mlpack/core.hpp>\n#include <mlpack/core/metrics/lmetric.hpp>\n#include <boost/test/unit_test.hpp>\n#include \"old_boost_test_definitions.hpp\"\n\n#include <mlpack/methods/lsh/lsh_search.hpp>\n#include <mlpack/methods/neighbor_search/neighbor_search.hpp>\n\nusing namespace std;\nusing namespace mlpack;\nusing namespace mlpack::neighbor;\n\ndouble ComputeRecall(\n    const arma::Mat<size_t>& lshNeighbors,\n    const arma::Mat<size_t>& groundTruth)\n{\n  const size_t queries = lshNeighbors.n_cols;\n  const size_t neigh = lshNeighbors.n_rows;\n\n  const double same = arma::accu(lshNeighbors == groundTruth);\n  return same / (static_cast<double>(queries * neigh));\n}\n\nBOOST_AUTO_TEST_SUITE(LSHTest);\n\n/**\n * Test: Run LSH with varying number of tables, keeping all other parameters\n * constant. Compute the recall, i.e. the number of reported neighbors that\n * are real neighbors of the query.\n * LSH's property is that (with high probability), increasing the number of\n * tables will increase recall. Epsilon ensures that if noise lightly affects\n * the projections, the test will not fail.\n * This produces false negatives, so we attempt the test numTries times and\n * only declare failure if all of them fail.\n */\nBOOST_AUTO_TEST_CASE(NumTablesTest)\n{\n  // kNN and LSH parameters (use LSH default parameters).\n  const int k = 4;\n  const int numProj = 10;\n  const double hashWidth = 0;\n  const int secondHashSize = 99901;\n  const int bucketSize = 500;\n\n  // Test parameters.\n  const double epsilon = 0.1; // Allowed deviation from expected monotonicity.\n  const int numTries = 5; // Tries for each test before declaring failure.\n\n  // Read iris training and testing data as reference and query sets.\n  const string trainSet = \"iris_train.csv\";\n  const string testSet = \"iris_test.csv\";\n  arma::mat rdata;\n  arma::mat qdata;\n  data::Load(trainSet, rdata, true);\n  data::Load(testSet, qdata, true);\n\n  // Run classic knn on reference data.\n  AllkNN knn(rdata);\n  arma::Mat<size_t> groundTruth;\n  arma::mat groundDistances;\n  knn.Search(qdata, k, groundTruth, groundDistances);\n\n  bool fail;\n  for (int t = 0; t < numTries; ++t)\n  {\n    fail = false;\n\n    const int lSize = 6; // Number of runs.\n    const int lValue[] = {1, 8, 16, 32, 64, 128}; // Number of tables.\n    double lValueRecall[lSize] = {0.0}; // Recall of each LSH run.\n\n    for (size_t l = 0; l < lSize; ++l)\n    {\n      // Run LSH with only numTables varying (other values are defaults).\n      LSHSearch<> lshTest(rdata, numProj, lValue[l], hashWidth, secondHashSize,\n          bucketSize);\n      arma::Mat<size_t> lshNeighbors;\n      arma::mat lshDistances;\n      lshTest.Search(qdata, k, lshNeighbors, lshDistances);\n\n      // Compute recall for each query.\n      lValueRecall[l] = ComputeRecall(lshNeighbors, groundTruth);\n\n      if (l > 0)\n      {\n        if (lValueRecall[l] < lValueRecall[l - 1] - epsilon)\n        {\n          fail = true; // If test fails at one point, stop and retry.\n          break;\n        }\n      }\n    }\n\n    if (!fail)\n      break; // If test passes one time, it is sufficient.\n  }\n\n  BOOST_REQUIRE(fail == false);\n}\n\n/**\n * Test: Run LSH with varying hash width, keeping all other parameters\n * constant. Compute the recall, i.e. the number of reported neighbors that\n * are real neighbors of the query.\n * LSH's property is that (with high probability), increasing the hash width\n * will increase recall. Epsilon ensures that if noise lightly affects the\n * projections, the test will not fail.\n */\nBOOST_AUTO_TEST_CASE(HashWidthTest)\n{\n  // kNN and LSH parameters (use LSH default parameters).\n  const int k = 4;\n  const int numTables = 30;\n  const int numProj = 10;\n  const int secondHashSize = 99901;\n  const int bucketSize = 500;\n\n  // Test parameters.\n  const double epsilon = 0.1; // Allowed deviation from expected monotonicity.\n\n  // Read iris training and testing data as reference and query.\n  const string trainSet = \"iris_train.csv\";\n  const string testSet = \"iris_test.csv\";\n  arma::mat rdata;\n  arma::mat qdata;\n  data::Load(trainSet, rdata, true);\n  data::Load(testSet, qdata, true);\n\n  // Run classic knn on reference data.\n  AllkNN knn(rdata);\n  arma::Mat<size_t> groundTruth;\n  arma::mat groundDistances;\n  knn.Search(qdata, k, groundTruth, groundDistances);\n  const int hSize = 7; // Number of runs.\n  const double hValue[] = {0.1, 0.5, 1, 5, 10, 50, 500}; // Hash width.\n  double hValueRecall[hSize] = {0.0}; // Recall of each run.\n\n  for (size_t h = 0; h < hSize; ++h)\n  {\n    // Run LSH with only hashWidth varying (other values are defaults).\n    LSHSearch<> lshTest(\n        rdata,\n        numProj,\n        numTables,\n        hValue[h],\n        secondHashSize,\n        bucketSize);\n\n    arma::Mat<size_t> lshNeighbors;\n    arma::mat lshDistances;\n    lshTest.Search(qdata, k, lshNeighbors, lshDistances);\n\n    // Compute recall for each query.\n    hValueRecall[h] = ComputeRecall(lshNeighbors, groundTruth);\n\n    if (h > 0)\n      BOOST_REQUIRE_GE(hValueRecall[h], hValueRecall[h - 1] - epsilon);\n  }\n}\n\n/**\n * Test: Run LSH with varying number of projections, keeping other parameters\n * constant. Compute the recall, i.e. the number of reported neighbors that\n * are real neighbors of the query.\n * LSH's property is that (with high probability), increasing the number of\n * projections per table will decrease recall. Epsilon ensures that if noise\n * lightly affects the projections, the test will not fail.\n */\nBOOST_AUTO_TEST_CASE(NumProjTest)\n{\n  // kNN and LSH parameters (use LSH default parameters).\n  const int k = 4;\n  const int numTables = 30;\n  const double hashWidth = 0;\n  const int secondHashSize = 99901;\n  const int bucketSize = 500;\n\n  // Test parameters.\n  const double epsilon = 0.1; // Allowed deviation from expected monotonicity.\n\n  // Read iris training and testing data as reference and query sets.\n  const string trainSet = \"iris_train.csv\";\n  const string testSet = \"iris_test.csv\";\n  arma::mat rdata;\n  arma::mat qdata;\n  data::Load(trainSet, rdata, true);\n  data::Load(testSet, qdata, true);\n\n  // Run classic knn on reference data.\n  AllkNN knn(rdata);\n  arma::Mat<size_t> groundTruth;\n  arma::mat groundDistances;\n  knn.Search(qdata, k, groundTruth, groundDistances);\n\n  // LSH test parameters for numProj.\n  const int pSize = 5; // Number of runs.\n  const int pValue[] = {1, 10, 20, 50, 100}; // Number of projections.\n  double pValueRecall[pSize] = {0.0}; // Recall of each run.\n\n  for (size_t p = 0; p < pSize; ++p)\n  {\n    // Run LSH with only numProj varying (other values are defaults).\n    LSHSearch<> lshTest(\n        rdata,\n        pValue[p],\n        numTables,\n        hashWidth,\n        secondHashSize,\n        bucketSize);\n\n    arma::Mat<size_t> lshNeighbors;\n    arma::mat lshDistances;\n    lshTest.Search(qdata, k, lshNeighbors, lshDistances);\n\n    // Compute recall for each query.\n    pValueRecall[p] = ComputeRecall(lshNeighbors, groundTruth);\n\n    // Don't check the first run; only check that increasing P decreases recall.\n    if (p > 0)\n      BOOST_REQUIRE_LE(pValueRecall[p] - epsilon, pValueRecall[p - 1]);\n  }\n}\n\n/**\n * Test: Run two LSH searches:\n * First, a very expensive LSH search, with a large number of hash tables\n * and a large hash width. This run should return an acceptable recall. We set\n * the bar very low (recall >= 50%) to make sure that a test fail means bad\n * implementation.\n * Second, a very cheap LSH search, with parameters that should cause recall\n * to be very low. Set the threshhold very high (recall <= 25%) to make sure\n * that a test fail means bad implementation.\n */\nBOOST_AUTO_TEST_CASE(RecallTest)\n{\n  // kNN and LSH parameters (use LSH default parameters).\n  const int k = 4;\n  const int secondHashSize = 99901;\n  const int bucketSize = 500;\n\n  // Read iris training and testing data as reference and query sets.\n  const string trainSet = \"iris_train.csv\";\n  const string testSet = \"iris_test.csv\";\n  arma::mat rdata;\n  arma::mat qdata;\n  data::Load(trainSet, rdata, true);\n  data::Load(testSet, qdata, true);\n\n  // Run classic knn on reference data.\n  AllkNN knn(rdata);\n  arma::Mat<size_t> groundTruth;\n  arma::mat groundDistances;\n  knn.Search(qdata, k, groundTruth, groundDistances);\n\n  // Expensive LSH run.\n  const int hExp = 10000; // First-level hash width.\n  const int kExp = 1; // Projections per table.\n  const int tExp = 128; // Number of tables.\n  const double recallThreshExp = 0.5;\n\n  LSHSearch<> lshTestExp(\n      rdata,\n      kExp,\n      tExp,\n      hExp,\n      secondHashSize,\n      bucketSize);\n  arma::Mat<size_t> lshNeighborsExp;\n  arma::mat lshDistancesExp;\n  lshTestExp.Search(qdata, k, lshNeighborsExp, lshDistancesExp);\n\n  const double recallExp = ComputeRecall(lshNeighborsExp, groundTruth);\n\n  // This run should have recall higher than the threshold.\n  BOOST_REQUIRE_GE(recallExp, recallThreshExp);\n\n  // Cheap LSH run.\n  const int hChp = 1; // Small first-level hash width.\n  const int kChp = 1000; // Large number of projections per table.\n  const int tChp = 1; // Only one table.\n  const double recallThreshChp = 0.25; // Recall threshold.\n\n  LSHSearch<> lshTestChp(\n      rdata,\n      kChp,\n      tChp,\n      hChp,\n      secondHashSize,\n      bucketSize);\n  arma::Mat<size_t> lshNeighborsChp;\n  arma::mat lshDistancesChp;\n  lshTestChp.Search(qdata, k, lshNeighborsChp, lshDistancesChp);\n\n  const double recallChp = ComputeRecall(lshNeighborsChp, groundTruth);\n\n  // This run should have recall lower than the threshold.\n  BOOST_REQUIRE_LE(recallChp, recallThreshChp);\n}\n\nBOOST_AUTO_TEST_CASE(LSHTrainTest)\n{\n  // This is a not very good test that simply checks that the re-trained LSH\n  // model operates on the correct dimensionality and returns the correct number\n  // of results.\n  arma::mat referenceData = arma::randu<arma::mat>(3, 100);\n  arma::mat newReferenceData = arma::randu<arma::mat>(10, 400);\n  arma::mat queryData = arma::randu<arma::mat>(10, 200);\n\n  LSHSearch<> lsh(referenceData, 3, 2, 2.0, 11, 3);\n\n  lsh.Train(newReferenceData, 4, 3, 3.0, 12, 4);\n\n  arma::Mat<size_t> neighbors;\n  arma::mat distances;\n\n  lsh.Search(queryData, 3, neighbors, distances);\n\n  BOOST_REQUIRE_EQUAL(neighbors.n_cols, 200);\n  BOOST_REQUIRE_EQUAL(neighbors.n_rows, 3);\n  BOOST_REQUIRE_EQUAL(distances.n_cols, 200);\n  BOOST_REQUIRE_EQUAL(distances.n_rows, 3);\n}\n\nBOOST_AUTO_TEST_CASE(EmptyConstructorTest)\n{\n  // If we create an empty LSH model and then call Search(), it should throw an\n  // exception.\n  LSHSearch<> lsh;\n\n  arma::mat dataset = arma::randu<arma::mat>(5, 50);\n  arma::mat distances;\n  arma::Mat<size_t> neighbors;\n  BOOST_REQUIRE_THROW(lsh.Search(dataset, 2, neighbors, distances),\n      std::invalid_argument);\n\n  // Now, train.\n  lsh.Train(dataset, 4, 3, 3.0, 12, 4);\n\n  lsh.Search(dataset, 3, neighbors, distances);\n\n  BOOST_REQUIRE_EQUAL(neighbors.n_cols, 50);\n  BOOST_REQUIRE_EQUAL(neighbors.n_rows, 3);\n  BOOST_REQUIRE_EQUAL(distances.n_cols, 50);\n  BOOST_REQUIRE_EQUAL(distances.n_rows, 3);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "fae78e2cf6e65cb3592ba5e263d9294862472155", "size": 11051, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/lsh_test.cpp", "max_stars_repo_name": "abhinvgpta/mlpack", "max_stars_repo_head_hexsha": "c5573b26c0f5c78037e4b82e75ccbcef6f254694", "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-08-17T11:59:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-17T11:59:20.000Z", "max_issues_repo_path": "src/mlpack/tests/lsh_test.cpp", "max_issues_repo_name": "abhinvgpta/mlpack", "max_issues_repo_head_hexsha": "c5573b26c0f5c78037e4b82e75ccbcef6f254694", "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/tests/lsh_test.cpp", "max_forks_repo_name": "abhinvgpta/mlpack", "max_forks_repo_head_hexsha": "c5573b26c0f5c78037e4b82e75ccbcef6f254694", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.3059490085, "max_line_length": 80, "alphanum_fraction": 0.6945072844, "num_tokens": 3112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.4833475100299026}}
{"text": "\n#include <NTL/mat_lzz_p.h>\n\nNTL_CLIENT\n\n\n\nvoid FillRandom(Mat<zz_p>& A)\n{\n   long n = A.NumRows();\n   long m = A.NumCols();\n   for (long i = 0; i < n; i++)\n      for (long j = 0; j < m; j++)\n         random(A[i][j]);\n}\n\nvoid FillRandom1(Mat<zz_p>& A)\n{\n   long n = A.NumRows();\n   long m = A.NumCols();\n   for (long j = 0; j < m; j++) {\n      if (j > 0 && RandomBnd(2)) {\n\t for (long i = 0; i < n; i++)\n            A[i][j] = A[i][j-1];\n      }\n      else {\n\t for (long i = 0; i < n; i++)\n\t    random(A[i][j]);\n      }\n   }\n}\n\nvoid FillRandom(Vec<zz_p>& A)\n{\n   long n = A.length();\n   for (long i = 0; i < n; i++)\n      random(A[i]);\n}\n\nlong old_gauss(mat_zz_p& M, long w)\n{\n   using NTL_NAMESPACE::negate;\n   long k, l;\n   long i, j;\n   long pos;\n   zz_p t1, t2, t3;\n   zz_p *x, *y;\n\n   long n = M.NumRows();\n   long m = M.NumCols();\n\n   if (w < 0 || w > m)\n      LogicError(\"gauss: bad args\");\n\n   long p = zz_p::modulus();\n   mulmod_t pinv = zz_p::ModulusInverse();\n   long T1, T2;\n\n   l = 0;\n   for (k = 0; k < w && l < n; k++) {\n\n      pos = -1;\n      for (i = l; i < n; i++) {\n         if (!IsZero(M[i][k])) {\n            pos = i;\n            break;\n         }\n      }\n\n      if (pos != -1) {\n         swap(M[pos], M[l]);\n\n         inv(t3, M[l][k]);\n         negate(t3, t3);\n\n         for (i = l+1; i < n; i++) {\n            // M[i] = M[i] + M[l]*M[i,k]*t3\n\n            mul(t1, M[i][k], t3);\n\n            T1 = rep(t1);\n            mulmod_precon_t T1pinv = PrepMulModPrecon(T1, p, pinv); \n\n            clear(M[i][k]);\n\n            x = M[i].elts() + (k+1);\n            y = M[l].elts() + (k+1);\n\n            for (j = k+1; j < m; j++, x++, y++) {\n               // *x = *x + (*y)*t1\n\n               T2 = MulModPrecon(rep(*y), T1, p, T1pinv);\n               T2 = AddMod(T2, rep(*x), p);\n               (*x).LoopHole() = T2;\n            }\n         }\n\n         l++;\n      }\n   }\n\n   return l;\n}\n\nlong old_gauss(mat_zz_p& M)\n{\n   return old_gauss(M, M.NumCols());\n}\n\nvoid old_image(mat_zz_p& X, const mat_zz_p& A)\n{\n   mat_zz_p M;\n   M = A;\n   long r = old_gauss(M);\n   M.SetDims(r, M.NumCols());\n   X = M;\n}\n\nint main(int argc, char **argv)\n{\n   ZZ seed;\n   RandomLen(seed, 30);\n   SetSeed(seed);\n   cerr << \"\\nseed=\" << seed << \"\\n\";\n\n   long iters = 100;\n\n\n#if 1\n   cerr << \"testing multiplication\";\n   for (long cnt = 0; cnt < iters; cnt++) {\n      cerr << \".\";\n\n      long bnd = (cnt%2) ? 25 : 2000;\n \n      long len = RandomBnd(NTL_SP_NBITS-3)+4;\n      long n = RandomBnd(bnd);\n      long l = RandomBnd(bnd);\n      long m = RandomBnd(bnd);\n\n      long p = RandomPrime_long(len);\n      zz_p::init(p);\n\n      Mat<zz_p> A, B, X;\n\n      A.SetDims(n, l);\n      B.SetDims(l, m);\n\n      FillRandom(A);\n      FillRandom(B);\n\n      X.SetDims(n, m);\n\n      vec_zz_p R;\n\n      R.SetLength(m);\n      for (long i = 0; i < m; i++) random(R[i]);\n\n      mul(X, A, B);\n\n      if (X*R != A*(B*R)) \n         cerr << \"*\\n*\\n*\\n*\\n*\\n*********** oops \" << len << \" \" << n << \" \" << l << \" \" \n              << m << \"\\n\";\n   }\n#endif\n\n#if 1\n   cerr << \"\\ntesting inversion\";\n   for (long cnt = 0; cnt < iters; cnt++) {\n      cerr << \".\";\n      long bnd = (cnt%2) ? 25 : 1500;\n \n      long len = RandomBnd(NTL_SP_NBITS-3)+4;\n      long n = RandomBnd(bnd);\n\n      long p = RandomPrime_long(len);\n      zz_p::init(p);\n\n      Mat<zz_p> A, X;\n\n      A.SetDims(n, n);\n\n      FillRandom(A);\n\n\n      vec_zz_p R;\n\n      R.SetLength(n);\n      for (long i = 0; i < n; i++) random(R[i]);\n\n      zz_p d;\n\n      inv(d, X, A);\n\n      if (d != 0) {\n\t if (R != A*(X*R)) \n\t    cerr << \"\\n*\\n*\\n*\\n*\\n*********** oops \" << len << \" \" << n << \"\\n\";\n      }\n      else {\n         cerr << \"[singular]\";\n      }\n   }\n#endif\n\n#if 1\n   cerr << \"\\ntesting solve\";\n   for (long cnt = 0; cnt < iters; cnt++) {\n      cerr << \".\";\n      long bnd = (cnt%2) ? 25 : 2000;\n \n      long len = RandomBnd(NTL_SP_NBITS-3)+4;\n      long n = RandomBnd(bnd);\n\n      long p = RandomPrime_long(len);\n      zz_p::init(p);\n\n      Mat<zz_p> A;\n\n      A.SetDims(n, n);\n      FillRandom(A);\n\n      Vec<zz_p> x, b;\n      b.SetLength(n);\n      FillRandom(b);\n\n      zz_p d;\n\n      solve(d, A, x, b);\n\n      if (d != 0) {\n\t if (A*x != b)\n\t    cerr << \"\\n*\\n*\\n*\\n*\\n*********** oops \" << len << \" \" << n << \"\\n\";\n      }\n      else {\n         cerr << \"[singular]\";\n      }\n   }\n#endif\n\n#if 1\n   cerr << \"\\ntesting image and kernel\";\n   for (long cnt = 0; cnt < iters; cnt++) {\n      cerr << \".\";\n      long bnd = (cnt%2) ? 25 : 1500;\n \n      long len = RandomBnd(NTL_SP_NBITS-3)+4;\n      long n = RandomBnd(bnd);\n      long m = RandomBnd(bnd);\n\n      long p = RandomPrime_long(len);\n      zz_p::init(p);\n\n      Mat<zz_p> A;\n\n      A.SetDims(n, m);\n      FillRandom1(A);\n\n      Mat<zz_p> im, im1, ker1;\n\n      old_image(im, A);\n      image(im1, A);\n      kernel(ker1, A);\n\n\n      if (im != im1 || !IsZero(ker1*A) || im1.NumRows() + ker1.NumRows() != n) {\n         cerr << \"\\n*\\n*\\n*\\n*\\n*********** oops \" << len << \" \" << n << m << \"\\n\";\n      }\n   }\n#endif\n\n   cerr << \"\\n\";\n\n}\n\n", "meta": {"hexsha": "a47fb2abb6eac2810ab3f27aa4d2304142a8ef9c", "size": 5011, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "android/jni/ntl/src/mat_lzz_pTest.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": 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": "tests/mat_lzz_pTest.cpp", "max_issues_repo_name": "LittleNewton/Discrete_Logarithm", "max_issues_repo_head_hexsha": "28721af6db022e0e9f0b426fb3bf861d13de1592", "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": "lib/NTL/src/mat_lzz_pTest.cpp", "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": 18.2218181818, "max_line_length": 90, "alphanum_fraction": 0.4250648573, "num_tokens": 1765, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389817407016, "lm_q2_score": 0.647798211152541, "lm_q1q2_score": 0.48334749764280494}}
{"text": "#include <cmath>\n#include <boost/numeric/conversion/cast.hpp>\n#include <boost/math/special_functions/factorials.hpp>\n#include \"ctkernel.h\"\n\n\n", "meta": {"hexsha": "fc160f5d0cf2b4a01aaeed8a6d9d3115528ede1a", "size": 141, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ctexpression/ctkernel.cpp", "max_stars_repo_name": "vega1986/wcalc_expression_parser", "max_stars_repo_head_hexsha": "e9645a5fa8086c4108ce4dc1f3ad7da3cead6480", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ctexpression/ctkernel.cpp", "max_issues_repo_name": "vega1986/wcalc_expression_parser", "max_issues_repo_head_hexsha": "e9645a5fa8086c4108ce4dc1f3ad7da3cead6480", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ctexpression/ctkernel.cpp", "max_forks_repo_name": "vega1986/wcalc_expression_parser", "max_forks_repo_head_hexsha": "e9645a5fa8086c4108ce4dc1f3ad7da3cead6480", "max_forks_repo_licenses": ["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.1428571429, "max_line_length": 54, "alphanum_fraction": 0.780141844, "num_tokens": 33, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.853912760387131, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4833304498195835}}
{"text": "/*\n * Polygon.cpp\n *\n *  Created on: Nov 7, 2014\n *      Author: P\u00e9ter Fankhauser\n *   Institute: ETH Zurich, ANYbotics\n */\n\n#include <grid_map_core/Polygon.hpp>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include <limits>\n#include <algorithm>\n\nnamespace grid_map {\n\nPolygon::Polygon()\n    : timestamp_(0)\n{\n}\n\nPolygon::Polygon(std::vector<Position> vertices)\n    : Polygon()\n{\n  vertices_ = vertices;\n}\n\nPolygon::~Polygon() {}\n\nbool Polygon::isInside(const Position& point) const\n{\n  int cross = 0;\n  for (int i = 0, j = vertices_.size() - 1; i < vertices_.size(); j = i++) {\n    if ( ((vertices_[i].y() > point.y()) != (vertices_[j].y() > point.y()))\n           && (point.x() < (vertices_[j].x() - vertices_[i].x()) * (point.y() - vertices_[i].y()) /\n            (vertices_[j].y() - vertices_[i].y()) + vertices_[i].x()) )\n    {\n      cross++;\n    }\n  }\n  return bool(cross % 2);\n}\n\nvoid Polygon::addVertex(const Position& vertex)\n{\n  vertices_.push_back(vertex);\n}\n\nconst Position& Polygon::getVertex(const size_t index) const\n{\n  return vertices_.at(index);\n}\n\nvoid Polygon::removeVertices()\n{\n  vertices_.clear();\n}\n\nconst Position& Polygon::operator [](const size_t index) const\n{\n  return getVertex(index);\n}\n\nconst std::vector<Position>& Polygon::getVertices() const\n{\n  return vertices_;\n}\n\nsize_t Polygon::nVertices() const\n{\n  return vertices_.size();\n}\n\nconst std::string& Polygon::getFrameId() const\n{\n  return frameId_;\n}\n\nvoid Polygon::setFrameId(const std::string& frameId)\n{\n  frameId_ = frameId;\n}\n\nuint64_t Polygon::getTimestamp() const\n{\n  return timestamp_;\n}\n\nvoid Polygon::setTimestamp(const uint64_t timestamp)\n{\n  timestamp_ = timestamp;\n}\n\nvoid Polygon::resetTimestamp()\n{\n  timestamp_ = 0.0;\n}\n\ndouble Polygon::getArea() const\n{\n  double area = 0.0;\n  int j = vertices_.size() - 1;\n  for (int i = 0; i < vertices_.size(); i++) {\n    area += (vertices_.at(j).x() + vertices_.at(i).x())\n        * (vertices_.at(j).y() - vertices_.at(i).y());\n    j = i;\n  }\n  return std::abs(area / 2.0);\n}\n\nPosition Polygon::getCentroid() const\n{\n  Position centroid = Position::Zero();\n  std::vector<Position> vertices = getVertices();\n  vertices.push_back(vertices.at(0));\n  double area = 0.0;\n  for (int i = 0; i < vertices.size() - 1; i++) {\n    const double a = vertices[i].x() * vertices[i+1].y() - vertices[i+1].x() * vertices[i].y();\n    area += a;\n    centroid.x() += a * (vertices[i].x() + vertices[i+1].x());\n    centroid.y() += a * (vertices[i].y() + vertices[i+1].y());\n  }\n  area *= 0.5;\n  centroid /= (6.0 * area);\n  return centroid;\n}\n\nvoid Polygon::getBoundingBox(Position& center, Length& length) const\n{\n  double minX = std::numeric_limits<double>::infinity();\n  double maxX = -std::numeric_limits<double>::infinity();\n  double minY = std::numeric_limits<double>::infinity();\n  double maxY = -std::numeric_limits<double>::infinity();\n  for (const auto& vertex : vertices_) {\n    if (vertex.x() > maxX) maxX = vertex.x();\n    if (vertex.y() > maxY) maxY = vertex.y();\n    if (vertex.x() < minX) minX = vertex.x();\n    if (vertex.y() < minY) minY = vertex.y();\n  }\n  center.x() = (minX + maxX) / 2.0;\n  center.y() = (minY + maxY) / 2.0;\n  length.x() = (maxX - minX);\n  length.y() = (maxY - minY);\n}\n\nbool Polygon::convertToInequalityConstraints(Eigen::MatrixXd& A, Eigen::VectorXd& b) const\n{\n  Eigen::MatrixXd V(nVertices(), 2);\n  for (unsigned int i = 0; i < nVertices(); ++i)\n    V.row(i) = vertices_[i];\n\n  // Create k, a list of indices from V forming the convex hull.\n  // TODO: Assuming counter-clockwise ordered convex polygon.\n  // MATLAB: k = convhulln(V);\n  Eigen::MatrixXi k;\n  k.resizeLike(V);\n  for (unsigned int i = 0; i < V.rows(); ++i)\n    k.row(i) << i, (i+1) % V.rows();\n  Eigen::RowVectorXd c = V.colwise().mean();\n  V.rowwise() -= c;\n  A = Eigen::MatrixXd::Constant(k.rows(), V.cols(), NAN);\n\n  unsigned int rc = 0;\n  for (unsigned int ix = 0; ix < k.rows(); ++ix) {\n    Eigen::MatrixXd F(2, V.cols());\n    F.row(0) << V.row(k(ix, 0));\n    F.row(1) << V.row(k(ix, 1));\n    Eigen::FullPivLU<Eigen::MatrixXd> luDecomp(F);\n    if (luDecomp.rank() == F.rows()) {\n      A.row(rc) = F.colPivHouseholderQr().solve(Eigen::VectorXd::Ones(F.rows()));\n      ++rc;\n    }\n  }\n\n  A = A.topRows(rc);\n  b = Eigen::VectorXd::Ones(A.rows());\n  b = b + A * c.transpose();\n\n  return true;\n}\n\nbool Polygon::thickenLine(const double thickness)\n{\n  if (vertices_.size() != 2) return false;\n  const Vector connection(vertices_[1] - vertices_[0]);\n  const Vector orthogonal = thickness * Vector(connection.y(), -connection.x()).normalized();\n  std::vector<Position> newVertices;\n  newVertices.reserve(4);\n  newVertices.push_back(vertices_[0] + orthogonal);\n  newVertices.push_back(vertices_[0] - orthogonal);\n  newVertices.push_back(vertices_[1] - orthogonal);\n  newVertices.push_back(vertices_[1] + orthogonal);\n  vertices_ = newVertices;\n  return true;\n}\n\nbool Polygon::offsetInward(const double margin)\n{\n  // Create a list of indices of the neighbours of each vertex.\n  // TODO: Assuming counter-clockwise ordered convex polygon.\n  std::vector<Eigen::Array2i> neighbourIndices;\n  const unsigned int n = nVertices();\n  neighbourIndices.resize(n);\n  for (unsigned int i = 0; i < n; ++i) {\n    neighbourIndices[i] << (i > 0 ? (i-1)%n : n-1), (i + 1) % n;\n  }\n\n  std::vector<Position> copy(vertices_);\n  for (unsigned int i = 0; i < neighbourIndices.size(); ++i) {\n    Eigen::Vector2d v1 = vertices_[neighbourIndices[i](0)] - vertices_[i];\n    Eigen::Vector2d v2 = vertices_[neighbourIndices[i](1)] - vertices_[i];\n    v1.normalize();\n    v2.normalize();\n    const double angle = acos(v1.dot(v2));\n    copy[i] += margin / sin(angle) * (v1 + v2);\n  }\n  vertices_ = copy;\n  return true;\n}\n\nstd::vector<Polygon> Polygon::triangulate(const TriangulationMethods& method) const\n{\n  // TODO Add more triangulation methods.\n  // https://en.wikipedia.org/wiki/Polygon_triangulation\n  std::vector<Polygon> polygons;\n  if (vertices_.size() < 3)\n    return polygons;\n\n  size_t nPolygons = vertices_.size() - 2;\n  polygons.reserve(nPolygons);\n\n  if (nPolygons < 1) {\n    // Special case.\n    polygons.push_back(*this);\n  } else {\n    // General case.\n    for (size_t i = 0; i < nPolygons; ++i) {\n      Polygon polygon({vertices_[0], vertices_[i + 1], vertices_[i + 2]});\n      polygons.push_back((polygon));\n    }\n  }\n\n  return polygons;\n}\n\nPolygon Polygon::fromCircle(const Position center, const double radius,\n                                  const int nVertices)\n{\n  Eigen::Vector2d centerToVertex(radius, 0.0), centerToVertexTemp;\n\n  Polygon polygon;\n  for (int j = 0; j < nVertices; j++) {\n    double theta = j * 2 * M_PI / (nVertices - 1);\n    Eigen::Rotation2D<double> rot2d(theta);\n    centerToVertexTemp = rot2d.toRotationMatrix() * centerToVertex;\n    polygon.addVertex(center + centerToVertexTemp);\n  }\n  return polygon;\n}\n\nPolygon Polygon::convexHullOfTwoCircles(const Position center1,\n                                   const Position center2, const double radius,\n                                   const int nVertices)\n{\n  if (center1 == center2) return fromCircle(center1, radius, nVertices);\n  Eigen::Vector2d centerToVertex, centerToVertexTemp;\n  centerToVertex = center2 - center1;\n  centerToVertex.normalize();\n  centerToVertex *= radius;\n\n  grid_map::Polygon polygon;\n  for (int j = 0; j < ceil(nVertices / 2.0); j++) {\n    double theta = M_PI_2 + j * M_PI / (ceil(nVertices / 2.0) - 1);\n    Eigen::Rotation2D<double> rot2d(theta);\n    centerToVertexTemp = rot2d.toRotationMatrix() * centerToVertex;\n    polygon.addVertex(center1 + centerToVertexTemp);\n  }\n  for (int j = 0; j < ceil(nVertices / 2.0); j++) {\n    double theta = 3 * M_PI_2 + j * M_PI / (ceil(nVertices / 2.0) - 1);\n    Eigen::Rotation2D<double> rot2d(theta);\n    centerToVertexTemp = rot2d.toRotationMatrix() * centerToVertex;\n    polygon.addVertex(center2 + centerToVertexTemp);\n  }\n  return polygon;\n}\n\nPolygon Polygon::convexHull(Polygon& polygon1, Polygon& polygon2)\n{\n  std::vector<Position> vertices;\n  vertices.reserve(polygon1.nVertices() + polygon2.nVertices());\n  vertices.insert(vertices.end(), polygon1.getVertices().begin(), polygon1.getVertices().end());\n  vertices.insert(vertices.end(), polygon2.getVertices().begin(), polygon2.getVertices().end());\n\n  return monotoneChainConvexHullOfPoints(vertices);\n}\n\nPolygon Polygon::monotoneChainConvexHullOfPoints(const std::vector<Position>& points)\n{\n  // Adapted from https://en.wikibooks.org/wiki/Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain\n  if (points.size() <= 3) {\n    return Polygon(points);\n  }\n  std::vector<Position> pointsConvexHull(2 * points.size());\n\n  // Sort points lexicographically.\n  auto sortedPoints(points);\n  std::sort(sortedPoints.begin(), sortedPoints.end(), sortVertices);\n\n\n  int k = 0;\n  // Build lower hull\n  for (int i = 0; i < sortedPoints.size(); ++i) {\n    while (k >= 2 && vectorsMakeClockwiseTurn(pointsConvexHull.at(k - 2), pointsConvexHull.at(k - 1), sortedPoints.at(i))) {\n      k--;\n    }\n    pointsConvexHull.at(k++) = sortedPoints.at(i);\n  }\n\n  // Build upper hull.\n  for (int i = sortedPoints.size() - 2, t = k + 1; i >= 0; i--) {\n    while (k >= t && vectorsMakeClockwiseTurn(pointsConvexHull.at(k - 2), pointsConvexHull.at(k - 1), sortedPoints.at(i))) {\n      k--;\n    }\n    pointsConvexHull.at(k++) = sortedPoints.at(i);\n  }\n  pointsConvexHull.resize(k - 1);\n\n  Polygon polygon(pointsConvexHull);\n  return polygon;\n}\n\nbool Polygon::sortVertices(const Eigen::Vector2d& vector1,\n                           const Eigen::Vector2d& vector2)\n{\n  return (vector1.x() < vector2.x()\n      || (vector1.x() == vector2.x() && vector1.y() < vector2.y()));\n}\n\ndouble Polygon::computeCrossProduct2D(const Eigen::Vector2d& vector1,\n                                      const Eigen::Vector2d& vector2)\n{\n  return (vector1.x() * vector2.y() - vector1.y() * vector2.x());\n}\n\ndouble Polygon::vectorsMakeClockwiseTurn(const Eigen::Vector2d &pointOrigin,\n                                         const Eigen::Vector2d &pointA,\n                                         const Eigen::Vector2d &pointB)\n{\n  return computeCrossProduct2D(pointA - pointOrigin, pointB - pointOrigin) <= 0;\n}\n\nconst std::vector<Position> Polygon::getInterpolatedConvexHull(const double stepSize) {\n  std::vector<Position> result;\n  Polygon hull = monotoneChainConvexHullOfPoints(this->getVertices());\n\n  for (int curIdx = 0; curIdx < hull.nVertices(); curIdx++){\n    int nextIdx = curIdx < hull.nVertices() -1 ? curIdx + 1 : 0;\n\n    Position curPos = hull.getVertex(curIdx);\n    Position nextPos = hull.getVertex(nextIdx);\n\n    Position diff = nextPos - curPos;\n    double diffDistance = diff.norm();\n    int steps = std::max(1, (int) ceil(diffDistance / stepSize));\n    Position direction(\n      diff[0] / steps,\n      diff[1] / steps\n    );\n\n    result.push_back(curPos);\n    for (int i = 0; i < steps; i++) {\n      double factor = ((double) i) / steps;\n      Position tmp = curPos + factor * diff;\n      result.push_back(tmp);\n    }\n  }\n\n  return result;\n}\n\n} /* namespace grid_map */\n", "meta": {"hexsha": "6008918a61c7947e49b3b9e60e629172e71c2810", "size": 11069, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "grid_map_core/src/Polygon.cpp", "max_stars_repo_name": "jpaczia/grid_map", "max_stars_repo_head_hexsha": "6347ffa1059a070b0e093d0f2a7c019d2e0afebd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "grid_map_core/src/Polygon.cpp", "max_issues_repo_name": "jpaczia/grid_map", "max_issues_repo_head_hexsha": "6347ffa1059a070b0e093d0f2a7c019d2e0afebd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "grid_map_core/src/Polygon.cpp", "max_forks_repo_name": "jpaczia/grid_map", "max_forks_repo_head_hexsha": "6347ffa1059a070b0e093d0f2a7c019d2e0afebd", "max_forks_repo_licenses": ["BSD-3-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.8255208333, "max_line_length": 124, "alphanum_fraction": 0.6374559581, "num_tokens": 3147, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397349, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.48331599221149674}}
{"text": "#pragma once\n\n#include <iostream>\n\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Wdeprecated-register\"\n#include <Eigen/Dense>\n#include <g2o/core/base_vertex.h>\n#pragma clang diagnostic pop\n\ntypedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic,\n        Eigen::RowMajor> Mat;\nusing Eigen::Vector3d;\ntypedef Eigen::Matrix<double, 6, 1> Vector6d;\ntypedef Eigen::Matrix<double, 6, 6> Matrix6d;\n\n//===========================================================================\nclass VertexPositionVelocity3D : public g2o::BaseVertex<6, Vector6d> {\npublic:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    VertexPositionVelocity3D() {\n      _estimate.setZero();\n    }\n\n  virtual void setToOriginImpl() {\n    _estimate.setZero();\n  }\n\n  virtual void oplusImpl(const double* update) {\n    for (int k = 0; k < 6; k++)\n      _estimate[k] += update[k];\n  }\n\n  virtual bool read(std::istream& /*is*/) { return false; }\n  virtual bool write(std::ostream& /*os*/) const { return false; }\n};\n\n\n", "meta": {"hexsha": "a750392453100f214b5f9c7e15fb1424c545099a", "size": 991, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/types.hpp", "max_stars_repo_name": "daemacles/monoslam-scale-estimation", "max_stars_repo_head_hexsha": "cbf94e5c60d8ab6e0306e0b110d232672b34ae8d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/types.hpp", "max_issues_repo_name": "daemacles/monoslam-scale-estimation", "max_issues_repo_head_hexsha": "cbf94e5c60d8ab6e0306e0b110d232672b34ae8d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/types.hpp", "max_forks_repo_name": "daemacles/monoslam-scale-estimation", "max_forks_repo_head_hexsha": "cbf94e5c60d8ab6e0306e0b110d232672b34ae8d", "max_forks_repo_licenses": ["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.4102564103, "max_line_length": 77, "alphanum_fraction": 0.6427850656, "num_tokens": 245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397348, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4833159922114967}}
{"text": "//==================================================================================================\n/*\n  EVE - Expressive Vector Engine\n  Copyright : EVE Contributors & Maintainers\n  SPDX-License-Identifier: MIT\n*/\n//==================================================================================================\n#include <eve/function/cyl_bessel_j1.hpp>\n#include <eve/constant/valmin.hpp>\n#include <eve/constant/valmax.hpp>\n#include <cmath>\n#include <boost/math/special_functions/bessel.hpp>\n\nint main()\n{\n  auto lmin = EVE_VALUE(0);\n  auto lmax = EVE_VALUE(10);\n\n  auto arg0 = eve::bench::random_<EVE_VALUE>(lmin,lmax);\n//  auto stdj1 = [](auto x){return std::cyl_bessel_j(0, x);};\n  auto boostj1= [](auto x){return boost::math::detail::bessel_j1(x);};\n  eve::bench::experiment xp;\n  run<EVE_TYPE> (EVE_NAME(cyl_bessel_j1) , xp, eve::cyl_bessel_j1 , arg0);\n  run<EVE_VALUE>(EVE_NAME(cyl_bessel_j1) , xp, eve::cyl_bessel_j1 , arg0);\n//  run<EVE_VALUE>(EVE_NAME(stdj1) , xp, stdj1 , arg0);\n  run<EVE_VALUE>(EVE_NAME(boostj1), xp, boostj1 , arg0);\n}\n", "meta": {"hexsha": "741e972e6a97fbaff92187c39a144bdb3b769272", "size": 1053, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "benchmarks/module/bessel/cyl_bessel_j1/regular/cyl_bessel_j1.hpp", "max_stars_repo_name": "the-moisrex/eve", "max_stars_repo_head_hexsha": "80b52663eefee11460abb0aedf4158a5067cf7dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 340.0, "max_stars_repo_stars_event_min_datetime": "2020-09-16T21:12:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T15:40:33.000Z", "max_issues_repo_path": "benchmarks/module/bessel/cyl_bessel_j1/regular/cyl_bessel_j1.hpp", "max_issues_repo_name": "the-moisrex/eve", "max_issues_repo_head_hexsha": "80b52663eefee11460abb0aedf4158a5067cf7dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 383.0, "max_issues_repo_issues_event_min_datetime": "2020-09-17T06:56:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T15:58:53.000Z", "max_forks_repo_path": "benchmarks/module/bessel/cyl_bessel_j1/regular/cyl_bessel_j1.hpp", "max_forks_repo_name": "the-moisrex/eve", "max_forks_repo_head_hexsha": "80b52663eefee11460abb0aedf4158a5067cf7dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 28.0, "max_forks_repo_forks_event_min_datetime": "2021-02-27T23:11:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T12:31:29.000Z", "avg_line_length": 37.6071428571, "max_line_length": 100, "alphanum_fraction": 0.5688509022, "num_tokens": 290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4833159861771199}}
{"text": "// Main code for Bayesian Inference with DIAMONDS\r\n// Created by Enrico Corsaro @ OACT - February 2017\r\n// e-mail: emncorsaro@gmail.com\r\n// Source code file \"SuperGaussianModel.cpp\"\r\n\r\n// To compile in Mac OS: \r\n// clang++ -o SuperGaussianFit SuperGaussianFit.cpp -L../../build/ -I ../../include/ -l diamonds -stdlib=libc++ -std=c++11 -Wno-deprecated-register\r\n// To compile in Linux OS:\r\n// g++ -o SuperGaussianFit SuperGaussianFit.cpp -L../../build/ -I../../include/ -ldiamonds -std=c++11 \r\n\r\n#include <cstdlib>\r\n#include <iostream>\r\n#include <iomanip>\r\n#include <fstream>\r\n#include <Eigen/Dense>\r\n#include \"Functions.h\"\r\n#include \"File.h\"\r\n#include \"MultiEllipsoidSampler.h\"\r\n#include \"KmeansClusterer.h\"\r\n#include \"EuclideanMetric.h\"\r\n#include \"Prior.h\"\r\n#include \"UniformPrior.h\"\r\n#include \"NormalPrior.h\"\r\n#include \"SuperGaussianModel.h\"\r\n#include \"NormalLikelihood.h\"\r\n#include \"FerozReducer.h\"\r\n#include \"PowerlawReducer.h\"\r\n#include \"Results.h\"\r\n#include \"Ellipsoid.h\"\r\n#include \"PrincipalComponentProjector.h\"\r\n\r\nint main(int argc, char *argv[])\r\n{\r\n\r\n    // Check number of arguments for main function\r\n    \r\n    if (argc != 3)\r\n    {\r\n        cerr << \"Usage: ./SuperGaussianFit <data filename> <prior filename>\" << endl;\r\n        exit(EXIT_FAILURE);\r\n    }\r\n\r\n\r\n    // ---------------------------\r\n    // ----- Read input data -----\r\n    // ---------------------------\r\n\r\n    unsigned long Nrows;\r\n    int Ndimensions;              // Number of parameters for which prior distributions are defined\r\n    int Ncols;\r\n    ArrayXXd data;\r\n\r\n    string baseInputDirName = \"\";\r\n    string inputFileName(argv[1]);\r\n    string outputPathPrefix = \"SuperGaussianFit_\";\r\n\r\n    ifstream inputFile;\r\n    File::openInputFile(inputFile, inputFileName);\r\n    File::sniffFile(inputFile, Nrows, Ncols);\r\n    data = File::arrayXXdFromFile(inputFile, Nrows, Ncols);\r\n    inputFile.close();\r\n\r\n\r\n    // Creating arrays for each data type\r\n    \r\n    ArrayXd covariates = data.col(0);\r\n    ArrayXd observations = data.col(1);\r\n    ArrayXd uncertainties = data.col(2);    \r\n\r\n    \r\n    // -------------------------------------------------------\r\n    // ----- First step. Set up all prior distributions -----\r\n    // -------------------------------------------------------\r\n    \r\n    // Uniform Prior\r\n    unsigned long Nparameters;\r\n\r\n    // ---- Read prior hyper parameters for resolved modes -----\r\n    string inputFileNamePrior(argv[2]);\r\n    File::openInputFile(inputFile, inputFileNamePrior);\r\n    File::sniffFile(inputFile, Nparameters, Ncols);\r\n    ArrayXXd hyperParameters;\r\n    Ndimensions = Nparameters;\r\n\r\n    if (Ncols == 1)\r\n    {\r\n        Ncols = 2;\r\n        hyperParameters.conservativeResize(Nparameters, Ncols);\r\n    }\r\n\r\n    hyperParameters = File::arrayXXdFromFile(inputFile, Nparameters, Ncols);\r\n    inputFile.close();\r\n\r\n    ArrayXd hyperParametersMinima = hyperParameters.col(0);\r\n    ArrayXd hyperParametersMaxima = hyperParameters.col(1);\r\n\r\n    int NpriorTypes = 1;                                        // Total number of prior types included in the computation\r\n    vector<Prior*> ptrPriors(NpriorTypes);\r\n    ArrayXd parametersMinima(Ndimensions);\r\n    ArrayXd parametersMaxima(Ndimensions);\r\n    parametersMinima << hyperParametersMinima;      // Minima values for the free parameters (free parameter\u00a0#1, free parameter #2, ..., etc.)\r\n    parametersMaxima << hyperParametersMaxima;      // Maxima values for the free parameters (same order as minima)\r\n    UniformPrior uniformPrior(parametersMinima, parametersMaxima);\r\n    ptrPriors[0] = &uniformPrior;\r\n\r\n    string fullPathHyperParameters = outputPathPrefix + \"hyperParametersUniform.txt\";       // Print prior hyper parameters as output\r\n    uniformPrior.writeHyperParametersToFile(fullPathHyperParameters);\r\n\r\n\r\n    // -------------------------------------------------------------------\r\n    // ---- Second step. Set up the models for the inference problem ----- \r\n    // -------------------------------------------------------------------\r\n    \r\n    SuperGaussianModel model(covariates);      // Super Gaussian function\r\n\r\n\r\n    // -----------------------------------------------------------------\r\n    // ----- Third step. Set up the likelihood function to be used -----\r\n    // -----------------------------------------------------------------\r\n    \r\n    NormalLikelihood likelihood(observations, uncertainties, model);\r\n    \r\n\r\n    // -------------------------------------------------------------------------------\r\n    // ----- Fourth step. Set up the K-means clusterer using an Euclidean metric -----\r\n    // -------------------------------------------------------------------------------\r\n\r\n    inputFileName = \"Xmeans_configuringParameters.txt\";\r\n    File::openInputFile(inputFile, inputFileName);\r\n    File::sniffFile(inputFile, Nparameters, Ncols);\r\n\r\n    if (Nparameters != 2)\r\n    {\r\n        cerr << \"Wrong number of input parameters for X-means algorithm.\" << endl;\r\n        exit(EXIT_FAILURE);\r\n    }\r\n\r\n    ArrayXd configuringParameters;\r\n    configuringParameters = File::arrayXXdFromFile(inputFile, Nparameters, Ncols);\r\n    inputFile.close();\r\n    \r\n    int minNclusters = configuringParameters(0);\r\n    int maxNclusters = configuringParameters(1);\r\n    \r\n    if ((minNclusters <= 0) || (maxNclusters <= 0) || (maxNclusters < minNclusters))\r\n    {\r\n        cerr << \"Minimum or maximum number of clusters cannot be <= 0, and \" << endl;\r\n        cerr << \"minimum number of clusters cannot be larger than maximum number of clusters.\" << endl;\r\n        exit(EXIT_FAILURE);\r\n    }\r\n\r\n    int Ntrials = 10;\r\n    double relTolerance = 0.01;\r\n\r\n    bool printNdimensions = false;\r\n    PrincipalComponentProjector projector(printNdimensions);\r\n    bool featureProjectionActivated = true;\r\n\r\n    EuclideanMetric myMetric;\r\n    KmeansClusterer kmeans(myMetric, projector, featureProjectionActivated, \r\n                           minNclusters, maxNclusters, Ntrials, relTolerance); \r\n\r\n\r\n    // ---------------------------------------------------------------------\r\n    // ----- Sixth step. Configure and start nested sampling inference -----\r\n    // ---------------------------------------------------------------------\r\n    \r\n    inputFileName = \"NSMC_configuringParameters.txt\";\r\n    File::openInputFile(inputFile, inputFileName);\r\n    File::sniffFile(inputFile, Nparameters, Ncols);\r\n    configuringParameters.setZero();\r\n    configuringParameters = File::arrayXXdFromFile(inputFile, Nparameters, Ncols);\r\n    inputFile.close();\r\n\r\n    if (Nparameters != 8)\r\n    {\r\n        cerr << \"Wrong number of input parameters for NSMC algorithm.\" << endl;\r\n        exit(EXIT_FAILURE);\r\n    }\r\n\r\n    bool printOnTheScreen = true;                       // Print results on the screen\r\n    int initialNobjects = configuringParameters(0);     // Initial number of live points \r\n    int minNobjects = configuringParameters(1);         // Minimum number of live points \r\n    int maxNdrawAttempts = configuringParameters(2);    // Maximum number of attempts when trying to draw a new sampling point\r\n    int NinitialIterationsWithoutClustering = configuringParameters(3); // The first N iterations, we assume that there is only 1 cluster\r\n    int NiterationsWithSameClustering = configuringParameters(4);       // Clustering is only happening every N iterations.\r\n    double initialEnlargementFraction = configuringParameters(5);   // Fraction by which each axis in an ellipsoid has to be enlarged.\r\n                                                                    // It can be a number >= 0, where 0 means no enlargement.\r\n    double shrinkingRate = configuringParameters(6);        // Exponent for remaining prior mass in ellipsoid enlargement fraction.\r\n                                                            // It is a number between 0 and 1. The smaller the slower the shrinkage\r\n                                                            // of the ellipsoids.\r\n    double terminationFactor = configuringParameters(7);    // Termination factor for nested sampling process.\r\n\r\n    \r\n    MultiEllipsoidSampler nestedSampler(printOnTheScreen, ptrPriors, likelihood, myMetric, kmeans, \r\n                                        initialNobjects, minNobjects, initialEnlargementFraction, shrinkingRate);\r\n    \r\n    double tolerance = 1.e2;\r\n    double exponent = 0.4;\r\n    PowerlawReducer livePointsReducer(nestedSampler, tolerance, exponent, terminationFactor);\r\n \r\n    nestedSampler.run(livePointsReducer, NinitialIterationsWithoutClustering, NiterationsWithSameClustering, \r\n                      maxNdrawAttempts, terminationFactor, 0, outputPathPrefix);\r\n\r\n    nestedSampler.outputFile << \"# List of configuring parameters used for the ellipsoidal sampler and X-means\" << endl;\r\n    nestedSampler.outputFile << \"# Row #1: Minimum Nclusters\" << endl;\r\n    nestedSampler.outputFile << \"# Row #2: Maximum Nclusters\" << endl;\r\n    nestedSampler.outputFile << \"# Row #3: Initial Enlargement Fraction\" << endl;\r\n    nestedSampler.outputFile << \"# Row #4: Shrinking Rate\" << endl;\r\n    nestedSampler.outputFile << minNclusters << endl;\r\n    nestedSampler.outputFile << maxNclusters << endl;\r\n    nestedSampler.outputFile << initialEnlargementFraction << endl;\r\n    nestedSampler.outputFile << shrinkingRate << endl;\r\n    nestedSampler.outputFile.close();\r\n\r\n\r\n    // -------------------------------------------------------\r\n    // ----- Last step. Save the results in output files -----\r\n    // -------------------------------------------------------\r\n   \r\n    Results results(nestedSampler);\r\n    results.writeParametersToFile(\"parameter\");\r\n    results.writeLogLikelihoodToFile(\"logLikelihood.txt\");\r\n    results.writeLogWeightsToFile(\"logWeights.txt\");\r\n    results.writeEvidenceInformationToFile(\"evidenceInformation.txt\");\r\n    results.writePosteriorProbabilityToFile(\"posteriorDistribution.txt\");\r\n    results.writeLogEvidenceToFile(\"logEvidence.txt\");\r\n    results.writeLogMeanLiveEvidenceToFile(\"logMeanLiveEvidence.txt\");\r\n\r\n    double credibleLevel = 68.3;\r\n    bool writeMarginalDistributionToFile = true;\r\n    results.writeParametersSummaryToFile(\"parameterSummary.txt\", credibleLevel, writeMarginalDistributionToFile);\r\n\r\n    cout << \"Process completed.\" << endl;\r\n    \r\n    return EXIT_SUCCESS;\r\n}\r\n", "meta": {"hexsha": "17799f0f2702fd3932761535789e4c06c8ecd2f3", "size": 10286, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tutorials/supergaussian_fit/SuperGaussianFit.cpp", "max_stars_repo_name": "vishalbelsare/DIAMONDS", "max_stars_repo_head_hexsha": "76409b22c9da782436b52e454a8b36bc78fca6f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tutorials/supergaussian_fit/SuperGaussianFit.cpp", "max_issues_repo_name": "vishalbelsare/DIAMONDS", "max_issues_repo_head_hexsha": "76409b22c9da782436b52e454a8b36bc78fca6f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tutorials/supergaussian_fit/SuperGaussianFit.cpp", "max_forks_repo_name": "vishalbelsare/DIAMONDS", "max_forks_repo_head_hexsha": "76409b22c9da782436b52e454a8b36bc78fca6f6", "max_forks_repo_licenses": ["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.218487395, "max_line_length": 148, "alphanum_fraction": 0.607524791, "num_tokens": 2094, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4833159861771199}}
{"text": "#include \"PG/core/RectUtils.h\"\n\n#include <cmath>\n\n#ifdef __APPLE__\n\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Wsign-conversion\"\n#pragma clang diagnostic ignored \"-Wconversion\"\n#pragma clang diagnostic ignored \"-Wshadow\"\n\n#endif\n\n#include <boost/geometry.hpp>\n\n#ifdef __APPLE__\n\n#pragma clang diagnostic pop\n\n#endif\n\nnamespace PG {\n\nnamespace\n{\n    using bPoint = boost::geometry::model::point<double, 2, boost::geometry::cs::cartesian>;\n    using bRect = boost::geometry::model::box<bPoint>;\n\n    //--------------------------------------------------------\n    bPoint toBPoint(const Point& pt)\n    {\n        return bPoint(pt.x, pt.y);\n    }\n\n    //--------------------------------------------------------\n    bRect toBRect(const Rect& r)\n    {\n        return bRect(bPoint(r.origin.x - (r.size.width / 2.0), r.origin.y - (r.size.height / 2.0)),\n                     bPoint(r.origin.x + (r.size.width / 2.0), r.origin.y + r.size.height / 2.0));\n    }\n    \n    //--------------------------------------------------------\n    Rect toPGRect(const bRect& r)\n    {\n        auto ox = r.min_corner().get<0>();\n        auto oy = r.min_corner().get<1>();\n        \n        auto w = r.max_corner().get<0>() - ox;\n        auto h = r.max_corner().get<1>() - oy;\n        \n        return Rect(Point(ox, oy), Size(w, h));\n    }\n}\n\n//--------------------------------------------------------\nnamespace RectUtils\n{\n    //--------------------------------------------------------\n    Rect getIntersection(const Rect& rectOne, const Rect& rectTwo)\n    {\n        auto bRectOne = toBRect(rectOne);\n        auto bRectTwo = toBRect(rectTwo);\n    \n        if (!boost::geometry::intersects(bRectOne, bRectTwo))\n        {\n            return Rect();\n        }\n    \n        bRect intersection;\n        boost::geometry::intersection(bRectOne, bRectTwo, intersection);\n        \n        return toPGRect(intersection);\n   }\n\t\n   //--------------------------------------------------------\n   bool isEmpty(const Rect& r)\n   {\n       return isEmpty(r.size);\n   }\n   \n   //--------------------------------------------------------\n   bool isEmpty(const Size& s)\n   {\n       return s.width == 0 || s.height == 0;\n   }\n   \n   //--------------------------------------------------------\n   bool containsPoint(const Rect& r, const Point& pt)\n   {\n        return boost::geometry::covered_by(toBPoint(pt), toBRect(r));\n   }\n   \n   //--------------------------------------------------------\n   Rect combineRects(const Rect& r1, const Rect& r2)\n   {\n       if (isEmpty(r1))\n       {\n           return r2;\n       }\n       \n       if (isEmpty(r2))\n       {\n           return r1;\n       }\n   \n       auto minLeft = std::min(r1.left(), r2.left());\n       auto maxRight = std::max(r1.right(), r2.right());\n       auto minTop = std::min(r1.top(), r2.top());\n       auto maxBottom = std::max(r1.bottom(), r2.bottom());\n       \n       Size combinedSize(maxRight - minLeft, maxBottom - minTop);\n       Point newOrigin(minLeft + (combinedSize.width / 2.0), maxBottom - (combinedSize.height / 2.0));\n    \n       return Rect(newOrigin, combinedSize);\n   }\n}\n\n}\n", "meta": {"hexsha": "5f4e16160ef211b73e4f500b0600eecaa805f2da", "size": 3119, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PG/core/RectUtils.cpp", "max_stars_repo_name": "mcdreamer/PG", "max_stars_repo_head_hexsha": "a047615d9eae7f2229a203a262f239106cf7f39c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-01-14T17:47:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-15T10:34:24.000Z", "max_issues_repo_path": "PG/core/RectUtils.cpp", "max_issues_repo_name": "mcdreamer/PG", "max_issues_repo_head_hexsha": "a047615d9eae7f2229a203a262f239106cf7f39c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 23.0, "max_issues_repo_issues_event_min_datetime": "2017-07-31T19:43:00.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-11T18:51:28.000Z", "max_forks_repo_path": "PG/core/RectUtils.cpp", "max_forks_repo_name": "mcdreamer/PG", "max_forks_repo_head_hexsha": "a047615d9eae7f2229a203a262f239106cf7f39c", "max_forks_repo_licenses": ["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.2100840336, "max_line_length": 102, "alphanum_fraction": 0.4706636743, "num_tokens": 700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.4833159861771198}}
{"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\n#ifndef BOOST_MATH_TOOLS_SIMPLE_CONTINUED_FRACTION_HPP\n#define BOOST_MATH_TOOLS_SIMPLE_CONTINUED_FRACTION_HPP\n\n#include <vector>\n#include <ostream>\n#include <iomanip>\n#include <cmath>\n#include <limits>\n#include <stdexcept>\n#include <boost/core/demangle.hpp>\n\nnamespace boost::math::tools {\n\ntemplate<typename Real, typename Z = int64_t>\nclass simple_continued_fraction {\npublic:\n    simple_continued_fraction(Real x) : x_{x} {\n        using std::floor;\n        using std::abs;\n        using std::sqrt;\n        using std::isfinite;\n        if (!isfinite(x)) {\n            throw std::domain_error(\"Cannot convert non-finites into continued fractions.\");  \n        }\n        b_.reserve(50);\n        Real bj = floor(x);\n        b_.push_back(static_cast<Z>(bj));\n        if (bj == x) {\n           b_.shrink_to_fit();\n           return;\n        }\n        x = 1/(x-bj);\n        Real f = bj;\n        if (bj == 0) {\n           f = 16*std::numeric_limits<Real>::min();\n        }\n        Real C = f;\n        Real D = 0;\n        int i = 0;\n        // the \"1 + i++\" lets the error bound grow slowly with the number of convergents.\n        // I have not worked out the error propagation of the Modified Lentz's method to see if it does indeed grow at this rate.\n        // Numerical Recipes claims that no one has worked out the error analysis of the modified Lentz's method.\n        while (abs(f - x_) >= (1 + i++)*std::numeric_limits<Real>::epsilon()*abs(x_))\n        {\n          bj = floor(x);\n          b_.push_back(static_cast<Z>(bj));\n          x = 1/(x-bj);\n          D += bj;\n          if (D == 0) {\n             D = 16*std::numeric_limits<Real>::min();\n          }\n          C = bj + 1/C;\n          if (C==0) {\n             C = 16*std::numeric_limits<Real>::min();\n          }\n          D = 1/D;\n          f *= (C*D);\n       }\n       // Deal with non-uniqueness of continued fractions: [a0; a1, ..., an, 1] = a0; a1, ..., an + 1].\n       // The shorter representation is considered the canonical representation,\n       // so if we compute a non-canonical representation, change it to canonical:\n       if (b_.size() > 2 && b_.back() == 1) {\n          b_[b_.size() - 2] += 1;\n          b_.resize(b_.size() - 1);\n       }\n       b_.shrink_to_fit();\n       \n       for (size_t i = 1; i < b_.size(); ++i) {\n         if (b_[i] <= 0) {\n            std::ostringstream oss;\n            oss << \"Found a negative partial denominator: b[\" << i << \"] = \" << b_[i] << \".\"\n                << \" This means the integer type '\" << boost::core::demangle(typeid(Z).name())\n                << \"' has overflowed and you need to use a wider type,\"\n                << \" or there is a bug.\";\n            throw std::overflow_error(oss.str());\n         }\n       }\n    }\n    \n    Real khinchin_geometric_mean() const {\n        if (b_.size() == 1) { \n         return std::numeric_limits<Real>::quiet_NaN();\n        }\n         using std::log;\n         using std::exp;\n         // Precompute the most probable logarithms. See the Gauss-Kuzmin distribution for details.\n         // Example: b_i = 1 has probability -log_2(3/4) \u2248 .415:\n         // A random partial denominator has ~80% chance of being in this table:\n         const std::array<Real, 7> logs{std::numeric_limits<Real>::quiet_NaN(), Real(0), log(static_cast<Real>(2)), log(static_cast<Real>(3)), log(static_cast<Real>(4)), log(static_cast<Real>(5)), log(static_cast<Real>(6))};\n         Real log_prod = 0;\n         for (size_t i = 1; i < b_.size(); ++i) {\n            if (b_[i] < static_cast<Z>(logs.size())) {\n               log_prod += logs[b_[i]];\n            }\n            else\n            {\n               log_prod += log(static_cast<Real>(b_[i]));\n            }\n         }\n         log_prod /= (b_.size()-1);\n         return exp(log_prod);\n    }\n    \n    Real khinchin_harmonic_mean() const {\n        if (b_.size() == 1) {\n          return std::numeric_limits<Real>::quiet_NaN();\n        }\n        Real n = b_.size() - 1;\n        Real denom = 0;\n        for (size_t i = 1; i < b_.size(); ++i) {\n            denom += 1/static_cast<Real>(b_[i]);\n        }\n        return n/denom;\n    }\n    \n    const std::vector<Z>& partial_denominators() const {\n      return b_;\n    }\n    \n    template<typename T, typename Z2>\n    friend std::ostream& operator<<(std::ostream& out, simple_continued_fraction<T, Z2>& scf);\n\nprivate:\n    const Real x_;\n    std::vector<Z> b_;\n};\n\n\ntemplate<typename Real, typename Z2>\nstd::ostream& operator<<(std::ostream& out, simple_continued_fraction<Real, Z2>& scf) {\n   constexpr const int p = std::numeric_limits<Real>::max_digits10;\n   if constexpr (p == 2147483647) {\n      out << std::setprecision(scf.x_.backend().precision());\n   } else {\n      out << std::setprecision(p);\n   }\n   \n   out << \"[\" << scf.b_.front();\n   if (scf.b_.size() > 1)\n   {\n      out << \"; \";\n      for (size_t i = 1; i < scf.b_.size() -1; ++i)\n      {\n         out << scf.b_[i] << \", \";\n      }\n      out << scf.b_.back();\n   }\n   out << \"]\";\n   return out;\n}\n\n\n}\n#endif\n", "meta": {"hexsha": "4120c53b03a664397017cf54c9bd47f49030e184", "size": 5236, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/math/tools/simple_continued_fraction.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/simple_continued_fraction.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/simple_continued_fraction.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": 32.725, "max_line_length": 224, "alphanum_fraction": 0.5370511841, "num_tokens": 1423, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.48331598617711974}}
{"text": "/*****************************************************************************\n * Copyright (c) 2017, Massachusetts Institute of Technology.\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 the name of the copyright holder nor the names of its contributors\n *   may be used to endorse or promote products derived from this software\n *   without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *****************************************************************************/\n\n#include <cmath>\n#include <cstdio>\n\n#include <Eigen/Core>\n\n#include <drake/common/autodiff.h>  // IWYU pragma: keep\n#include <drake/common/default_scalars.h>\n#include <drake/common/drake_assert.h>\n#include <drake/common/unused.h>\n#include <drake/solvers/snopt_solver.h>\n#include <drake/systems/analysis/simulator.h>\n#include <drake/systems/framework/context.h>\n#include <drake/systems/framework/continuous_state.h>\n#include <drake/systems/framework/vector_system.h>\n#include <drake/systems/trajectory_optimization/direct_collocation.h>\n\nnamespace shambhala {\nnamespace systems {\n\ntemplate <typename T>\nclass SimpleContinuousTimeSystem final : public drake::systems::VectorSystem<T> {\n public:\n  DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(SimpleContinuousTimeSystem);\n  SimpleContinuousTimeSystem() : drake::systems::VectorSystem<T>(::drake::systems::SystemTypeTag<SimpleContinuousTimeSystem>{}, 2, 1) { // n_in, n_out\n    this->DeclareContinuousState(6); // n_state\n  }\n\n  // Scalar-converting copy constructor.  See @ref system_scalar_conversion.\n  template <typename U>\n  explicit SimpleContinuousTimeSystem(const SimpleContinuousTimeSystem<U>&) : SimpleContinuousTimeSystem<T>() {}\n\n private:\n  // xdot = -x + x^3\n  void DoCalcVectorTimeDerivatives(\n      const drake::systems::Context<T>& context,\n      const Eigen::VectorBlock<const drake::VectorX<T>>& input,\n      const Eigen::VectorBlock<const drake::VectorX<T>>& state,\n      Eigen::VectorBlock<drake::VectorX<T>>* derivatives) const override {\n\n    // DS Kinetic 60\n    const double g = 9.8;\n    const double rho = 1.225 * .6; // ISA at 5km\n\n    const double m = 2; // http://www.dskinetic.com/k60.aspx\n    const double S = .23;\n\n    // const double Vc2 = m*g/(.5*rho*S);\n    // const double lambda = Vc2/g;\n\n    const double cD0 = .005; // https://www.tngtech.com/fileadmin/Public/Images/BigTechday/BTD10/Folien/Folien_SpencerLisenby.pdf\n    const double k = .006;\n\n    const auto& speed = state(0);\n    const auto& pitch = state(1);\n    const auto& yaw   = state(2);\n    const auto& z     = state(3);\n\n    const auto& cL    = input(0);\n    const auto& roll  = input(1);\n\n    const double windspeed_gradient = .027; // jet stream at 5km: .02\n\n    const auto zd = speed*sin(pitch);\n    const auto W = windspeed_gradient*z;\n    const auto Wd = windspeed_gradient*zd;\n\n    const auto cD = cD0 + k*cL*cL;\n    const auto D = .5*cD*rho*S*speed*speed;\n    const auto L = .5*cL*rho*S*speed*speed;\n\n    (*derivatives)(0) = 1/(m                 )*(     -D      - m*g*sin(pitch) + m*Wd*cos(pitch)*sin(yaw));\n    (*derivatives)(1) = 1/(m*speed           )*( L*cos(roll) - m*g*cos(pitch) - m*Wd*sin(pitch)*sin(yaw));\n    (*derivatives)(2) = 1/(m*speed*cos(pitch))*( L*sin(roll)                  + m*Wd           *cos(yaw));\n    (*derivatives)(3) = zd;\n    (*derivatives)(4) = speed*cos(pitch)*cos(yaw);\n    (*derivatives)(5) = speed*cos(pitch)*sin(yaw) - W;\n  }\n\n  // y = x\n  void DoCalcVectorOutput(\n      const drake::systems::Context<T>& context,\n      const Eigen::VectorBlock<const drake::VectorX<T>>& input,\n      const Eigen::VectorBlock<const drake::VectorX<T>>& state,\n      Eigen::VectorBlock<drake::VectorX<T>>* output) const /*override*/ {\n    drake::unused(context, input);\n    *output = state;\n  }\n};\n\n}  // namespace systems\n}  // namespace shambhala\n\nDRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(\n    class ::shambhala::systems::SimpleContinuousTimeSystem)\n\nint main() {\n  // Create the simple system.\n  shambhala::systems::SimpleContinuousTimeSystem<double> system;\n\n  auto context = system.CreateDefaultContext();\n  const int N = 201;\n  const double dt_min = 9./N;\n  const double dt_max = 13./N;\n  drake::systems::trajectory_optimization::DirectCollocation dircol(\n      &system, *context, N, dt_min, dt_max);\n  dircol.AddEqualTimeIntervalsConstraints();\n\n\n  // design limits\n  auto tau = 4*acos(0);\n\n  dircol.AddConstraintToAllKnotPoints(dircol.input()(0) >= 0); // 0 <= cL <= 1.2\n  dircol.AddConstraintToAllKnotPoints(dircol.input()(0) <= 1.2);\n\n  dircol.AddConstraintToAllKnotPoints(dircol.state()(0) >= 0);\n  dircol.AddConstraintToAllKnotPoints(dircol.state()(0) <= 140); // DS Kinetic 60 speed record 140 m/s\n\n  dircol.AddConstraintToAllKnotPoints(dircol.state()(1) >= -tau/2); // pitch looks forward\n  dircol.AddConstraintToAllKnotPoints(dircol.state()(1) <=  tau/2);\n\n  dircol.AddConstraintToAllKnotPoints(dircol.state()(2) >= -1.5*tau); // we want one turn in either direction\n  dircol.AddConstraintToAllKnotPoints(dircol.state()(2) <=  1.5*tau);  // and allow an extra half turn\n\n  dircol.AddConstraintToAllKnotPoints(dircol.state()(3) >= -500); // max 1km altitude differential (arbitrary)\n  dircol.AddConstraintToAllKnotPoints(dircol.state()(3) <=  500);\n\n\n  // planning target\n\n  // dircol.AddConstraint(dircol.initial_state()(4) == 0); // x_N = x_0\n  dircol.AddConstraint(dircol.initial_state()(5) == 0);\n\n  dircol.AddConstraint(dircol.final_state()(0) >= dircol.initial_state()(0));\n  dircol.AddConstraint(dircol.final_state()(1) == dircol.initial_state()(1));\n  dircol.AddConstraint(dircol.final_state()(2) == dircol.initial_state()(2) + 1*tau);\n  dircol.AddConstraint(dircol.final_state()(3) >= dircol.initial_state()(3));\n\n  auto zmin = dircol.NewContinuousVariables(1, \"zmin\")(0);\n  auto zmax = dircol.NewContinuousVariables(1, \"zmax\")(0);\n  dircol.AddConstraintToAllKnotPoints(dircol.state()(3) >= zmin);\n  dircol.AddConstraintToAllKnotPoints(dircol.state()(3) <= zmax);\n  dircol.AddLinearCost(zmax-zmin);\n  dircol.AddLinearConstraint(zmax == -zmin);\n\n  // solver spoonfeeding\n\n  dircol.AddConstraintToAllKnotPoints(dircol.state()(0) >= 1); // nonzero speed!\n\n  dircol.AddConstraintToAllKnotPoints(dircol.input()(1) >= -tau/4); // do not turn the plane upside down\n  dircol.AddConstraintToAllKnotPoints(dircol.input()(1) <=  tau/4);\n\n  dircol.SetSolverOption(drake::solvers::SnoptSolver::id(), \"Iterations limit\", 10000000);\n  dircol.SetSolverOption(drake::solvers::SnoptSolver::id(), \"Major iterations limit\", 10000);\n\n  // solving\n\n  auto result = dircol.Solve();\n  if (result != drake::solvers::SolutionResult::kSolutionFound) {\n    auto s = drake::solvers::to_string(result);\n    printf(\"solving failed: %s\\n\", s.c_str());\n    return 1;\n  }\n\n  // printing\n\n  {\n    auto inputs = dircol.ReconstructInputTrajectory();\n    auto traj = dircol.ReconstructStateTrajectory();\n    auto timestamps = traj.get_segment_times();\n    printf(\"[\\n\");\n    for (size_t i = 0; i < timestamps.size(); i++) {\n      auto t = timestamps[i];\n      auto V = traj.value(timestamps[i]).coeff(0);\n      auto pitch = traj.value(timestamps[i]).coeff(1);\n      auto yaw = traj.value(timestamps[i]).coeff(2);\n      auto altitude = traj.value(timestamps[i]).coeff(3);\n      auto x = traj.value(timestamps[i]).coeff(4);\n      auto y = traj.value(timestamps[i]).coeff(5);\n      auto cL = inputs.value(timestamps[i]).coeff(0);\n      auto roll = inputs.value(timestamps[i]).coeff(1);\n      printf(\"(%03.3f,  %03.3f, %03.3f, %03.3f, %03.3f, %03.3f, %03.3f,  %03.3f, %03.3f), # %3.3f\\n\", t, V, pitch, yaw, altitude, x, y, cL, roll, 9.8*altitude + .5*V*V);\n    }\n    printf(\"]\\n\");\n  }\n}\n", "meta": {"hexsha": "92875486d148b6d4ac0b81e146d9b25545378dfa", "size": 8900, "ext": "cc", "lang": "C++", "max_stars_repo_path": "drake_cmake_installed/src/simple_continuous_time_system/simple_continuous_time_system.cc", "max_stars_repo_name": "andres-erbsen/drake-dynamic-soaring", "max_stars_repo_head_hexsha": "6172e1e6bc76d2e163f85e2570076e7752a59faf", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "drake_cmake_installed/src/simple_continuous_time_system/simple_continuous_time_system.cc", "max_issues_repo_name": "andres-erbsen/drake-dynamic-soaring", "max_issues_repo_head_hexsha": "6172e1e6bc76d2e163f85e2570076e7752a59faf", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "drake_cmake_installed/src/simple_continuous_time_system/simple_continuous_time_system.cc", "max_forks_repo_name": "andres-erbsen/drake-dynamic-soaring", "max_forks_repo_head_hexsha": "6172e1e6bc76d2e163f85e2570076e7752a59faf", "max_forks_repo_licenses": ["BSD-3-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.0138248848, "max_line_length": 169, "alphanum_fraction": 0.6831460674, "num_tokens": 2444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.48331598617711974}}
{"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 *    Notes\n *      The current test cases are used to check the code of the mathematical functions, each case\n *      represents a special case where certain elements of the function can be eliminated.\n *\n */\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MAIN\n\n#include <boost/bind/bind.hpp>\nusing namespace boost::placeholders;\n\n#include <boost/lambda/lambda.hpp>\n#include <boost/test/unit_test.hpp>\n\n#include <Eigen/Core>\n\n#include \"tudat/math/basic/mathematicalConstants.h\"\n\n#include \"tudat/astro/mission_segments/improvedInversePolynomialWall.h\"\n#include \"tudat/astro/mission_segments/oscillatingFunctionNovak.h\"\n\nusing namespace boost::placeholders;\n\nnamespace tudat\n{\nnamespace unit_tests\n{\n\n//! Test the spherical shape function code.\nBOOST_AUTO_TEST_SUITE( test_spherical_shape_function )\n\n//! Test case: inverse polynomial function.\nBOOST_AUTO_TEST_CASE( ImprovedInversePolynomialWall )\n{\n    // Using declaration.\n    using mathematical_constants::PI;\n\n    // Initialize parameters of the inverse polynomial function.\n    std::pair< Eigen::Vector3d, Eigen::Vector3d > inversePolynomialParameters;\n    double timeDepParameter;\n    double azimuthalAngle = 0.0;\n\n    // Error tolerance.\n    const double tolerance = std::numeric_limits< double >::epsilon( );\n\n    //*********************************************************************************************\n    // CASE 1: b = 1.0, polar angle = 0.0, all other parameters 0.0\n    //*********************************************************************************************\n\n    // Case specific changes.\n    inversePolynomialParameters.first = Eigen::Vector3d::Zero(  );\n    inversePolynomialParameters.second = Eigen::Vector3d::Zero(  );\n    timeDepParameter = 0.0;\n    inversePolynomialParameters.first( 1 ) = 1.0; // b\n\n    // Expected results.\n    double expectedFunctionValue = 1.0;\n    double expectedFirstDerivative = 0.0;\n    double expectedSecondDerivative = 1.0;\n    double expectedThirdDerivative = 0.0;\n\n    // Initialize mathematical function.\n    mission_segments::ImprovedInversePolynomialWall myFunctionCase1(\n                [ & ]( ){ return timeDepParameter; } ,\n                [ & ]( ){ return inversePolynomialParameters; } );\n\n    // Calculate function value and derivatives.\n    double functionValue = myFunctionCase1.evaluate( azimuthalAngle );\n    double firstDerivative = myFunctionCase1.computeDerivative( 1 , azimuthalAngle );\n    double secondDerivative = myFunctionCase1.computeDerivative( 2 , azimuthalAngle );\n    double thirdDerivative = myFunctionCase1.computeDerivative( 3 , azimuthalAngle );\n\n    // Test if the computed values correspond to the expected values, within the specified\n    // tolerance.\n    BOOST_CHECK_CLOSE_FRACTION( functionValue,\n                                expectedFunctionValue,\n                                tolerance );\n\n    BOOST_CHECK_CLOSE_FRACTION( firstDerivative,\n                                expectedFirstDerivative,\n                                tolerance );\n\n    BOOST_CHECK_CLOSE_FRACTION( secondDerivative,\n                                expectedSecondDerivative,\n                                tolerance );\n\n    BOOST_CHECK_CLOSE_FRACTION( thirdDerivative,\n                                expectedThirdDerivative,\n                                tolerance );\n\n    //*********************************************************************************************\n    // CASE 2: c = 0.0, polar angle = 0.0, all other parameters 1.0\n    //*********************************************************************************************\n\n    // Case-specific changes.\n    inversePolynomialParameters.first = Eigen::Vector3d::Ones(  );\n    inversePolynomialParameters.second = Eigen::Vector3d::Ones(  );\n    timeDepParameter = 1.0;\n    inversePolynomialParameters.first( 2 ) = 0.0; // c\n\n    // Expected results.\n    expectedFunctionValue = 1.0 / 2.0;\n    expectedFirstDerivative = 0.0;\n    expectedSecondDerivative = 1.0 / 4.0;\n    expectedThirdDerivative = - 6.0 / 4.0;\n\n    // Initialize mathematical function.\n    mission_segments::ImprovedInversePolynomialWall myFunctionCase2(\n                [ & ]( ){ return timeDepParameter; } ,\n                [ & ]( ){ return inversePolynomialParameters; } );\n\n    // Calculate function value and derivatives.\n    functionValue = myFunctionCase2.evaluate( azimuthalAngle );\n    firstDerivative = myFunctionCase2.computeDerivative( 1 , azimuthalAngle );\n    secondDerivative = myFunctionCase2.computeDerivative( 2 , azimuthalAngle );\n    thirdDerivative = myFunctionCase2.computeDerivative( 3 , azimuthalAngle );\n\n    // Test if the computed values correspond to the expected values, within the specified\n    // tolerance.\n    BOOST_CHECK_CLOSE_FRACTION( functionValue,\n                                expectedFunctionValue,\n                                tolerance );\n\n    BOOST_CHECK_CLOSE_FRACTION( firstDerivative,\n                                expectedFirstDerivative,\n                                tolerance );\n\n    BOOST_CHECK_CLOSE_FRACTION( secondDerivative,\n                                expectedSecondDerivative,\n                                tolerance );\n\n    BOOST_CHECK_CLOSE_FRACTION( thirdDerivative,\n                                expectedThirdDerivative,\n                                tolerance );\n\n    //*********************************************************************************************\n    // CASE 3: c = pi - 1.0, polar angle = 1.0, all other parameters 1.0\n    //*********************************************************************************************\n\n    // Case-specific changes.\n    inversePolynomialParameters.first( 2 ) = PI - 1.0; // c\n    azimuthalAngle = 1.0;\n\n    // Expected results.\n    expectedFunctionValue = 1.0 / 4.0;\n    expectedFirstDerivative = -9.0 / 8.0;\n    expectedSecondDerivative = 93.0 / 16.0;\n    expectedThirdDerivative = -267.0 / 8.0;\n\n    // Initialize mathematical function.\n    mission_segments::ImprovedInversePolynomialWall myFunctionCase3(\n                [ & ]( ){ return timeDepParameter; } ,\n                [ & ]( ){ return inversePolynomialParameters; } );\n\n    // Calculate function value and derivatives.\n    functionValue = myFunctionCase3.evaluate( azimuthalAngle );\n    firstDerivative = myFunctionCase3.computeDerivative( 1 , azimuthalAngle );\n    secondDerivative = myFunctionCase3.computeDerivative( 2 , azimuthalAngle );\n    thirdDerivative = myFunctionCase3.computeDerivative( 3 , azimuthalAngle );\n\n    // Test if the computed values correspond to the expected values, within the specified\n    // tolerance.\n    BOOST_CHECK_CLOSE_FRACTION( functionValue,\n                                expectedFunctionValue,\n                                tolerance );\n\n    BOOST_CHECK_CLOSE_FRACTION( firstDerivative,\n                                expectedFirstDerivative,\n                                tolerance );\n\n    BOOST_CHECK_CLOSE_FRACTION( secondDerivative,\n                                expectedSecondDerivative,\n                                tolerance );\n\n    BOOST_CHECK_CLOSE_FRACTION( thirdDerivative,\n                                expectedThirdDerivative,\n                                tolerance );\n}\n\n//! Test case: oscillating function.\nBOOST_AUTO_TEST_CASE( OscillatingFunctionNovak )\n{\n    // Using declaration.\n    using mathematical_constants::PI;\n\n    // Initialize parameters of the inverse polynomial function.\n    std::pair< Eigen::Vector2d, Eigen::Vector2d > oscillatingFunctionParameters;\n    double azimuthalAngle = 0.0;\n\n    // Error tolerance.\n    const double tolerance = std::numeric_limits< double >::epsilon(  );\n\n    //*********************************************************************************************\n    // CASE 1: theta = 0.0, all parameters = 1.0\n    //*********************************************************************************************\n\n    // Case specific changes.\n    oscillatingFunctionParameters.first = Eigen::Vector2d::Ones(  );\n    oscillatingFunctionParameters.second = Eigen::Vector2d::Ones(  );\n\n    // Expected results.\n    double expectedFunctionValue = 1.0;\n    double expectedFirstDerivative = 2.0;\n    double expectedSecondDerivative = 1.0;\n    double expectedThirdDerivative = - 4.0;\n\n    // Initialize mathematical function.\n    mission_segments::OscillatingFunctionNovak myFunctionCase1(\n                [ & ]( ){ return oscillatingFunctionParameters; } );\n\n    // Calculate function value and derivatives.\n    double functionValue = myFunctionCase1.evaluate( azimuthalAngle );\n    double firstDerivative = myFunctionCase1.computeDerivative( 1 , azimuthalAngle );\n    double secondDerivative = myFunctionCase1.computeDerivative( 2 , azimuthalAngle );\n    double thirdDerivative = myFunctionCase1.computeDerivative( 3 , azimuthalAngle );\n\n    // Test if the computed values correspond to the expected values, within the specified\n    // tolerance.\n    BOOST_CHECK_CLOSE_FRACTION( functionValue,\n                                expectedFunctionValue,\n                                tolerance );\n\n    BOOST_CHECK_CLOSE_FRACTION( firstDerivative,\n                                expectedFirstDerivative,\n                                tolerance );\n\n    BOOST_CHECK_CLOSE_FRACTION( secondDerivative,\n                                expectedSecondDerivative,\n                                tolerance );\n\n    BOOST_CHECK_CLOSE_FRACTION( thirdDerivative,\n                                expectedThirdDerivative,\n                                tolerance );\n\n    //*********************************************************************************************\n    // CASE 2: theta = pi/2, all parameters = 1.0\n    //*********************************************************************************************\n\n    // Case-specific changes.\n    azimuthalAngle = PI / 2.0;\n\n    // Expected results.\n    expectedFunctionValue = 1.0 + PI / 2.0;\n    expectedFirstDerivative = -PI / 2.0;\n    expectedSecondDerivative = -3.0 - PI / 2.0;\n    expectedThirdDerivative = -2.0 + PI / 2.0;\n\n    // The term cos(PI/2) introduces a small error in the function value, and in the derivative\n    // values. [ cos(PI/2) is approximately 6.12323e-017 ]\n    // The calculation of the function value, the first derivative and the second derivative are\n    // within the numeric limits, however the error in the third derivative is larger than this\n    // limit. The tolerance for the third derivative is therefore more flexible than that of the\n    // other calculations.\n    const double toleranceThirdDerivative = 4.0 * tolerance;\n\n    // The exact value of the third derivative, due to the introduced error. This vaue is checked\n    // separately.\n    double exactThirdDerivative =\n            -2.0 + PI / 2.0 - 1.0 * ( 4.0 + PI / 2.0 ) * std::cos( PI / 2.0 );\n\n    // Initialize mathematical function.\n    mission_segments::OscillatingFunctionNovak myFunctionCase2(\n                [ & ]( ){ return oscillatingFunctionParameters; } );\n\n    // Calculate function value and derivatives.\n    functionValue = myFunctionCase2.evaluate( azimuthalAngle );\n    firstDerivative = myFunctionCase2.computeDerivative( 1 , azimuthalAngle );\n    secondDerivative = myFunctionCase2.computeDerivative( 2 , azimuthalAngle );\n    thirdDerivative = myFunctionCase2.computeDerivative( 3 , azimuthalAngle );\n\n    // Test if the computed values correspond to the expected values, within the specified\n    // tolerance.\n    BOOST_CHECK_CLOSE_FRACTION( functionValue,\n                                expectedFunctionValue,\n                                tolerance );\n\n    BOOST_CHECK_CLOSE_FRACTION( firstDerivative,\n                                expectedFirstDerivative,\n                                tolerance );\n\n    BOOST_CHECK_CLOSE_FRACTION( secondDerivative,\n                                expectedSecondDerivative,\n                                tolerance );\n\n    BOOST_CHECK_CLOSE_FRACTION( thirdDerivative,\n                                expectedThirdDerivative,\n                                toleranceThirdDerivative );\n\n    BOOST_CHECK_EQUAL( thirdDerivative, exactThirdDerivative );\n}\n\n//! Test case: request wrong derivative or integral of one of the mathematical functions.\nBOOST_AUTO_TEST_CASE( wrongRequestMathematicalFunctions )\n{\n    // Initialize parameters of the mathematical functions.\n    // Inverse polynomial parameters.\n    std::pair< Eigen::Vector3d, Eigen::Vector3d > inversePolynomialParameters;\n    inversePolynomialParameters.first.Zero();\n    inversePolynomialParameters.second.Zero();\n    double timeDepParameter = 0.0;\n\n    // Oscillating function parameters.\n    std::pair< Eigen::Vector2d, Eigen::Vector2d > OscillatingShapeParameters;\n    OscillatingShapeParameters.first.Zero(  );\n    OscillatingShapeParameters.second.Zero(  );\n\n    // Initialize mathematical functions.\n    mission_segments::ImprovedInversePolynomialWall myInversePolynomial(\n                [ & ]( ){ return timeDepParameter ; },\n                [ & ]( ){ return inversePolynomialParameters; } );\n\n    mission_segments::OscillatingFunctionNovak myOscillatingFunction(\n                [ & ]( ){ return OscillatingShapeParameters; } );\n\n    // Set flags.\n    bool isFourthDerivativeInversePolynomial = true;\n    bool isFourthDerivativeOscillatingFunction = true;\n    bool isDefiniteIntegralInversePolynomial = true;\n    bool isDefiniteIntegralOscillatingFunction = true;\n\n    // Try to calculate the fourth derivative of the inverse polynomial function, which should\n    // result in a runtime error.\n    try\n    {\n        // Calculate the fourth derivative of the inverse polynomial function.\n        myInversePolynomial.computeDerivative( 4 , 0.0 );\n    }\n\n    // Catch the expected runtime error, and set the boolean flag to false.\n    catch( std::runtime_error const& )\n\n    {\n        isFourthDerivativeInversePolynomial = false;\n    }\n\n    // Check value of flag.\n    BOOST_CHECK( !isFourthDerivativeInversePolynomial );\n\n    // Try to calculate the definite integral of the inverse polynomial function, which should\n    // result in a runtime error.\n    try\n    {\n        // Calculate the definite integral of the inverse polynomial function.\n        myInversePolynomial.computeDefiniteIntegral( 1 , 0.0 , 1.0 );\n    }\n\n    // Catch the expected runtime error, and set the boolean flag to false.\n    catch( std::runtime_error const& )\n\n    {\n        isDefiniteIntegralInversePolynomial = false;\n    }\n\n    // Check value of flag.\n    BOOST_CHECK( !isDefiniteIntegralInversePolynomial );\n\n    // Try to calculate the fourth derivative of the oscillating function, which should result in a\n    // runtime error.\n    try\n    {\n        // Calculate the fourth derivative of the oscillating function.\n        myOscillatingFunction.computeDerivative( 4 , 0.0 );\n    }\n\n    // Catch the expected runtime error, and set the boolean flag to false.\n    catch( std::runtime_error const& )\n\n    {\n        isFourthDerivativeOscillatingFunction = false;\n    }\n\n    // Check value of flag.\n    BOOST_CHECK( !isFourthDerivativeOscillatingFunction );\n\n    // Try to calculate the definite integral of the oscillating function, which should result in a\n    // runtime error.\n    try\n    {\n        // Calculate the definite integral of the oscillating function.\n        myOscillatingFunction.computeDefiniteIntegral( 1 , 0.0 , 1.0 );\n    }\n\n    // Catch the expected runtime error, and set the boolean flag to false.\n    catch( std::runtime_error const& )\n\n    {\n        isDefiniteIntegralOscillatingFunction = false;\n    }\n\n    // Check value of flag.\n    BOOST_CHECK( !isDefiniteIntegralOscillatingFunction );\n}\n\nBOOST_AUTO_TEST_SUITE_END( )\n\n} // namespace unit_tests\n} // namespace tudat\n", "meta": {"hexsha": "9c5d588041a26d429e52518e91185f148c9d5656", "size": 16140, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/src/astro/mission_segments/unitTestMathematicalShapeFunctions.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": "tests/src/astro/mission_segments/unitTestMathematicalShapeFunctions.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": "tests/src/astro/mission_segments/unitTestMathematicalShapeFunctions.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": 39.5588235294, "max_line_length": 99, "alphanum_fraction": 0.6218711276, "num_tokens": 3385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436395, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.48330804974246805}}
{"text": "\n\n#include \"verification/production/impl/threshold_util.hpp\"\n\n#include <boost/range/adaptors.hpp>\n#include <boost/range/numeric.hpp>\n\nnamespace sgns::verification {\n\n  Threshold calculateThreshold(\n      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    cpp_int t = a * numerator(p_rat) / denominator(p_rat);\n    return Threshold{t};\n  }\n\n}  // namespace sgns::verification\n", "meta": {"hexsha": "d427a5d9698c68a0de5d022a069262da7641c82c", "size": 991, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/verification/production/impl/threshold_util.cpp", "max_stars_repo_name": "GeniusVentures/SuperGenius", "max_stars_repo_head_hexsha": "ae43304f4a2475498ef56c971296175acb88d0ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-10T21:25:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-10T21:25:03.000Z", "max_issues_repo_path": "src/verification/production/impl/threshold_util.cpp", "max_issues_repo_name": "GeniusVentures/SuperGenius", "max_issues_repo_head_hexsha": "ae43304f4a2475498ef56c971296175acb88d0ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/verification/production/impl/threshold_util.cpp", "max_forks_repo_name": "GeniusVentures/SuperGenius", "max_forks_repo_head_hexsha": "ae43304f4a2475498ef56c971296175acb88d0ee", "max_forks_repo_licenses": ["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.96875, "max_line_length": 75, "alphanum_fraction": 0.6367305752, "num_tokens": 227, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637648915617, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.48328276728504954}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n/// \\file\n/// Defines the class Wedge2D.\n\n#pragma once\n\n#include <array>\n#include <boost/optional.hpp>\n#include <cstddef>\n#include <limits>\n\n#include \"DataStructures/Tensor/Tensor.hpp\"\n#include \"Domain/OrientationMap.hpp\"\n#include \"Utilities/TypeTraits.hpp\"\n\nnamespace PUP {\nclass er;\n}  // namespace PUP\n\nnamespace CoordinateMaps {\n\n/*!\n * \\ingroup CoordinateMapsGroup\n *\n * \\brief Two dimensional map from the logical square to a wedge, which is used\n * by domains which use disks or annuli.\n *\n * \\details The coordinate map is constructed by\n * linearly interpolating between a bulged arc which is circumscribed by a\n * circular arc of radius `radius_outer` and a bulged arc which is\n * circumscribed by a circular arc of radius `radius_inner`. These arcs can be\n * made to be straight or circular, based on the value of `circularity_inner`\n * or `circularity_outer`, which can take on values between 0 (for straight)\n * and 1 (for circular). These arcs extend \\f$\\pi/2\\f$ in angle, and can be\n * oriented along the +/- x or y axis. The choice of using either equiangular\n * or equidistant coordinates along the arcs is specifiable with\n * `with_equiangular_map`. The default logical coordinate that points in the\n * angular direction is \\f$\\eta\\f$. We introduce the auxiliary variable\n * \\f$\\mathrm{H}\\f$ which is a function of \\f$\\eta\\f$. If we are using\n * equiangular coordinates, we have:\n *\n * \\f[\\mathrm{H}(\\eta) = \\textrm{tan}(\\eta\\pi/4)\\f]\n *\n * With derivative:\n *\n * \\f[\\mathrm{H}'(\\eta) = \\frac{\\pi}{4}(1+\\mathrm{H}^2)\\f]\n *\n * If we are using equidistant coordinates, we have:\n *\n * \\f[\\mathrm{H}(\\eta) = \\eta\\f]\n *\n * with derivative:\n *\n * <center>\\f$\\mathrm{H}'(\\eta) = 1\\f$</center>\n *\n * We also define the variable \\f$\\rho\\f$, given by:\n *\n * \\f[\\rho = \\sqrt{1+\\mathrm{H}^2}\\f]\n *\n * In terms of the the circularity \\f$c\\f$ and the radius \\f$R\\f$,\n * the mapping is:\n *\n * \\f[\\vec{x}(\\xi,\\eta) =\n * \\frac{1}{2}\\left\\{(1-\\xi)\\Big[(1-c_{inner})\\frac{R_{inner}}{\\sqrt 2}\n * + c_{inner}\\frac{R_{inner}}{\\rho}\\Big] +\n * (1+\\xi)\\Big[(1-c_{outer})\\frac{R_{outer}}{\\sqrt 2} +c_{outer}\n * \\frac{R_{outer}}{\\rho}\\Big] \\right\\}\\begin{bmatrix}\n * 1\\\\\n * \\mathrm{H}\\\\\n * \\end{bmatrix}\\f]\n *\n * We will define the variables \\f$T(\\xi)\\f$ and \\f$A(\\xi)\\f$, the trapezoid\n * and annulus factors: \\f[T(\\xi) = T_0 + T_1\\xi\\f] \\f[A(\\xi) = A_0 +\n * A_1\\xi\\f]\n * Where \\f{align*}T_0 &= \\frac{1}{2} \\big\\{ (1-c_{outer})R_{outer} +\n * (1-c_{inner})R_{inner}\\big\\}\\\\\n * T_1 &= \\partial_{\\xi} T = \\frac{1}{2} \\big\\{ (1-c_{outer})R_{outer} -\n * (1-c_{inner})R_{inner}\\big\\}\\\\\n * A_0 &= \\frac{1}{2} \\big\\{ c_{outer}R_{outer} + c_{inner}R_{inner}\\big\\}\\\\\n * A_1 &= \\partial_{\\xi} A = \\frac{1}{2} \\big\\{ c_{outer}R_{outer} -\n * c_{inner}R_{inner}\\big\\}\\f}\n *\n * The map can then be rewritten as:\n * \\f[\\vec{x}(\\xi,\\eta) = \\left\\{\\frac{T(\\xi)}{\\sqrt 2} +\n * \\frac{A(\\xi)}{\\rho}\\right\\}\\begin{bmatrix}\n * 1\\\\\n * \\mathrm{H}\\\\\n * \\end{bmatrix}\\f]\n *\n *\n * The Jacobian is: \\f[J =\n * \\begin{bmatrix}\n * \\frac{T_1}{\\sqrt 2} + \\frac{A_1}{\\rho} &\n * \\mathrm{H}\\mathrm{H}'\\frac{A(\\xi)}{\\rho^3} \\\\\n * \\mathrm{H}\\partial_{\\xi}x &\n * \\mathrm{H}\\partial_{\\eta}x + \\mathrm{H}'x\\\\\n * \\end{bmatrix}\n * \\f]\n *\n * The inverse Jacobian is: \\f[J^{-1} =\n * \\frac{1}{x}\\begin{bmatrix}\n * \\frac{1}{\\partial_{\\xi}x}\\Big\\{\n * \\frac{T(\\xi)}{\\sqrt 2}+\\frac{A(\\xi)}{\\rho^3}\n * \\Big\\} & \\mathrm{H}\\frac{1}{\\partial_{\\xi}x}\\frac{A(\\xi)}{\\rho^3}\\\\\n * -\\mathrm{H}\\mathrm{H}'^{-1} & \\mathrm{H}'^{-1}\\\\\n * \\end{bmatrix}\n * \\f]\n *\n * For a more detailed discussion, see the\n * documentation for Wedge3D, where the default logical coordinate that points\n * in the radial direction is \\f$\\zeta\\f$ (In Wedge2D the logical coordinate\n * that points in the radial direction is \\f$\\xi\\f$), and one may set either\n * of the two other logical coordinates to zero to obtain an equivalent\n * Wedge2D map.\n */\n\nclass Wedge2D {\n public:\n  static constexpr size_t dim = 2;\n\n  Wedge2D(double radius_inner, double radius_outer, double circularity_inner,\n          double circularity_outer, OrientationMap<2> orientation_of_wedge,\n          bool with_equiangular_map) noexcept;\n\n  Wedge2D() = default;\n  ~Wedge2D() = default;\n  Wedge2D(Wedge2D&&) = default;\n  Wedge2D& operator=(Wedge2D&&) = default;\n  Wedge2D(const Wedge2D&) = default;\n  Wedge2D& operator=(const Wedge2D&) = default;\n\n  template <typename T>\n  std::array<tt::remove_cvref_wrap_t<T>, 2> operator()(\n      const std::array<T, 2>& source_coords) const noexcept;\n\n  /// Returns invalid if \\f$x<=0\\f$ (for a \\f$+x\\f$-oriented `Wedge2D`).\n  boost::optional<std::array<double, 2>> inverse(\n      const std::array<double, 2>& target_coords) const noexcept;\n\n  template <typename T>\n  tnsr::Ij<tt::remove_cvref_wrap_t<T>, 2, Frame::NoFrame> jacobian(\n      const std::array<T, 2>& source_coords) const noexcept;\n\n  template <typename T>\n  tnsr::Ij<tt::remove_cvref_wrap_t<T>, 2, Frame::NoFrame> inv_jacobian(\n      const std::array<T, 2>& source_coords) const noexcept;\n\n  // clang-tidy: google runtime references\n  void pup(PUP::er& p);  // NOLINT\n private:\n  friend bool operator==(const Wedge2D& lhs, const Wedge2D& rhs) noexcept;\n\n  double radius_inner_{};\n  double radius_outer_{};\n  double circularity_inner_{};\n  double circularity_outer_{};\n  OrientationMap<2> orientation_of_wedge_{};\n  bool with_equiangular_map_ = false;\n  double scaled_trapezoid_zero_{std::numeric_limits<double>::signaling_NaN()};\n  double annulus_zero_{std::numeric_limits<double>::signaling_NaN()};\n  double scaled_trapezoid_rate_{std::numeric_limits<double>::signaling_NaN()};\n  double annulus_rate_{std::numeric_limits<double>::signaling_NaN()};\n};\nbool operator!=(const Wedge2D& lhs, const Wedge2D& rhs) noexcept;\n}  // namespace CoordinateMaps\n", "meta": {"hexsha": "73ac1b4b4a2069332527e814a570be3b843ac2d3", "size": 5803, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Domain/CoordinateMaps/Wedge2D.hpp", "max_stars_repo_name": "marissawalker/spectre", "max_stars_repo_head_hexsha": "afc8205e2f697de5e8e4f05e881499e05c9fd8a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Domain/CoordinateMaps/Wedge2D.hpp", "max_issues_repo_name": "marissawalker/spectre", "max_issues_repo_head_hexsha": "afc8205e2f697de5e8e4f05e881499e05c9fd8a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Domain/CoordinateMaps/Wedge2D.hpp", "max_forks_repo_name": "marissawalker/spectre", "max_forks_repo_head_hexsha": "afc8205e2f697de5e8e4f05e881499e05c9fd8a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.5416666667, "max_line_length": 79, "alphanum_fraction": 0.6617266931, "num_tokens": 1920, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435083355187, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.48326989237512524}}
{"text": "/*\nCopyright 2018 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 <algorithm>\n#include <vector>\n#include <limits>\n#include <cmath>\n\n#include <boost/python/numpy.hpp>\n\n#include \"relation.hpp\"\n\nnamespace np = boost::python::numpy;\n\ntemplate <typename T = double>\nclass KNN_Graph {    \npublic:\n    typedef unsigned long long index_type;\n\n    class Adjacency_List : public std::vector<index_type> {\n    public:\n        inline auto get(const index_type i) const {\n            if (i >= this->size()) return std::numeric_limits<index_type>::signaling_NaN();\n            return (*this)[i];\n        }\n        \n        inline auto length() const {\n            return this->size();\n        }\n        \n        inline auto pbegin() const {\n            return this->begin();\n        }\n        \n        inline auto pend() const {\n            return this->end();\n        }\n    };\n    \n    typedef Tuple<T> location_type;\n    typedef Relation<T> vertices_type;\n    typedef Adjacency_List adjacency_list_type;\n    typedef std::vector<adjacency_list_type> edges_type;\n    \n    inline static T euclidean_distance(const location_type &a, const location_type &b) {\n        auto diff = a - b;\n        return sqrt(diff * diff);\n    }\n    \n    inline static T euclidean_distance_squared(const location_type &a, const location_type &b) {\n        auto diff = a - b;\n        return diff * diff;\n    }\n    \n    KNN_Graph() : k{0}, vertices{}, edges{} {}\n    \n    KNN_Graph(const unsigned long k) : k{k}, vertices{}, edges{} {}\n    \n    void sort() {\n        std::vector<index_type> index(number_vertices());\n\n        #pragma omp parallel for shared(index)\n        for (index_type i = 0; i < number_vertices(); ++i) {\n            index[i] = i;\n        }\n        \n        auto less = [&](const index_type lhs, const index_type rhs) -> bool {\n            return vertices[lhs] < vertices[rhs];\n        };\n        \n        std::sort(index.begin(), index.end(), less);\n        \n        vertices_type new_vertices(number_vertices());\n        edges_type new_edges(number_vertices());\n\n        #pragma omp parallel for shared(new_vertices, new_edges, index)\n        for (index_type i = 0; i < number_vertices(); ++i) {\n            new_vertices[i] = vertices[index[i]];\n            new_edges[i] = edges[index[i]];\n            std::sort(new_edges[i].begin(), new_edges[i].end(), less);\n        }\n        \n        vertices = new_vertices;\n        edges = new_edges;\n    }\n    \n    auto epsilon(const KNN_Graph<T> &hp) const {\n        double epsilon = 0.0;\n        auto g = *this;\n        auto h = hp;\n        \n        g.sort();\n        h.sort();\n        \n        index_type i = 0, j = 0;\n        unsigned long long denominator = 0;\n        \n        while (i < g.number_vertices() and j < h.number_vertices()) {\n            if (g.get_vertex(i) == h.get_vertex(j)) {\n                auto g_neighbors = g.get_neighbors(i);\n                auto h_neighbors = h.get_neighbors(j);\n                auto g_number_neighbors = g_neighbors.size();\n                auto h_number_neighbors = h_neighbors.size();\n                denominator += g_number_neighbors;\n                index_type k = 0, l = 0;\n                while (k < g_number_neighbors and l < h_number_neighbors) {\n                    if (g_neighbors[k] < h_neighbors[l]) {\n                        epsilon += 1;\n                        ++k;\n                    } else if (g_neighbors[k] > h_neighbors[l]) {\n                        ++l;\n                    } else {\n                        ++k;\n                        ++l;\n                    }\n                }\n                epsilon += g_number_neighbors - k;\n                ++i;\n                ++j;\n            } else if (g.get_vertex(i) < h.get_vertex(j)) {\n                auto number_neighbors = g.get_neighbors(i).size();\n                epsilon += number_neighbors;\n                denominator += number_neighbors;\n                ++i;\n            } else {\n                ++j;\n            }\n        }\n        \n        for(; i < g.number_vertices(); ++i) {\n            auto number_neighbors = g.get_neighbors(i).size();\n            epsilon += number_neighbors;\n            denominator += number_neighbors;\n        }\n\n        epsilon /= denominator;\n        \n        return epsilon;\n    }\n    \n    inline auto dimension() const {\n        return number_vertices() == 0 ? 0 : vertices[0].dimension();\n    }\n    \n    inline auto number_vertices() const {\n        return vertices.size();\n    }\n    \n    inline auto number_edges() const {\n        return edges_number;\n    }\n    \n    inline auto number_wrongly_connected_vertices() const {\n        unsigned long long result = 0;\n\n        #pragma omp parallel for shared(result)\n        for (index_type i = 0; i < number_vertices(); ++i) {\n            T distN = 0;\n            auto wrongly_connected = false;\n            auto &adj_list = edges[i];\n                        \n            for (index_type j = 0; j < adj_list.size(); ++j) {\n                auto dist = euclidean_distance_squared(vertices[i], vertices[adj_list[j]]);\n                if (std::fabs(dist - distN) > std::numeric_limits<T>::epsilon() and dist > distN) {\n                    distN = dist;\n                }\n            }\n            \n            for (index_type j = 0; j < number_vertices(); ++j) {\n                if (wrongly_connected) continue;\n                else if (std::find(adj_list.begin(), adj_list.end(), j) == adj_list.end() and i != j) {\n                    auto dist = euclidean_distance_squared(vertices[i], vertices[j]);\n                    if (std::fabs(dist - distN) > std::numeric_limits<T>::epsilon() and dist < distN) {\n                        #pragma omp critical\n                        {\n                            if (not wrongly_connected) {\n                                ++result;\n                                wrongly_connected = true;\n                            }\n                        }\n                    }\n                }\n            }\n        } \n        return result;\n    }\n    \n    inline auto get_vertex(const index_type i) const {\n        return vertices[i];\n    }\n    \n    inline auto get_neighbors(const index_type i) const {\n        return edges[i];\n    }\n    \n    inline auto number_neighbors(const index_type i) const {\n        return edges[i].size();\n    }\n    \n    inline auto get_k() const {\n        return k;\n    }\n    \n    void add_edge(const index_type i, const index_type j) {\n\t\tthis->edges[i].push_back(j);\n\t\tthis->edges_number++;\n\t}\n    \n    virtual void build(const vertices_type &vertices) {\n        this->vertices = vertices;\n        this->edges = edges_type(vertices.size());\n    }\n    \n    virtual void build(const np::ndarray &in) {\n        this->vertices = vertices_type{in};\n        this->edges = edges_type(vertices.size());\n    }\n    \n    void edges_from_ndarray(const np::ndarray &in) {\n        auto dimensions = in.get_nd();\n        if (dimensions != 2 or in.get_dtype() != np::dtype::get_builtin<bool>()) {\n            std::cerr << \"Need 2-dimensional numpy array of type bool!\" << std::endl;\n            return;\n        }\n        this->edges = edges_type(vertices.size());\n        auto size = in.get_shape();\n        auto strides = in.get_strides();\n        auto data = in.get_data();\n        bool adjacent = false;\n        for (index_type i = 0; i < size[0]; ++i) {\n            for (index_type j = 0; j < size[1]; ++j) {\n                adjacent = *reinterpret_cast<const bool*>(data + i * strides[0] + j * strides[1]);\n                if (adjacent) {\n                    this->edges[i].push_back(j);\n                    ++this->edges_number;\n                }\n            }\n        }\n    }\n    \n    inline const auto& get_edges() const {\n        return edges;\n    }\n    \n    inline const auto& get_vertices() const {\n        return vertices;\n    }\n    \n    inline auto& get_edges() {\n        return edges;\n    }\n    \n    inline auto& get_vertices() {\n        return vertices;\n    }\n    \n    inline auto edges_begin() const {\n        return edges.begin();\n    }\n    \n    inline auto edges_end() const {\n        return edges.end();\n    }\n    \n    inline auto vertices_begin() const {\n        return vertices.begin();\n    }\n    \n    inline auto vertices_end() const {\n        return vertices.end();\n    }\n    \n    inline auto as_str() const {\n        std::stringstream ss;\n        ss << *this;\n        return ss.str();\n    }\n    \n    inline auto repr() const {\n        std::stringstream ss;\n        ss << get_k() <<\"-Nearest Neighbor Graph of Dimension \" << dimension() << \":\" << std::endl;\n        ss << as_str();\n        return ss.str();\n    }\n    \nprotected:\n    unsigned long k;\n    unsigned long long edges_number = 0;\n    vertices_type vertices;\n    edges_type edges;\n\n};\n\ntemplate <typename T = double>\nclass KNN_Graph_Exact : public KNN_Graph<T> {\n    typedef KNN_Graph<T> super;\n    typedef typename super::index_type index_type;\n\npublic:\n    KNN_Graph_Exact(const unsigned long k = 10) {\n        this->k = k;\n        this->vertices = typename super::vertices_type{};\n        this->edges = typename super::edges_type{};\n    }\n    \n    void build(const np::ndarray &in) {\n        this->build(typename super::vertices_type(in));\n    }\n    \n    void build(const typename super::vertices_type &vertices) {\n        this->vertices = vertices;\n        this->edges = typename super::edges_type(vertices.size());\n        std::cout << \"Building exact \" << this->k << \"-NNGraph with \" << vertices.size() << \" vertices:\" << std::endl;\n\n        auto n = vertices.size();\n        \n        for (index_type i = 0; i < n; ++i) {\n            auto distance_furthest = std::numeric_limits<double>::infinity();\n            \n            for (index_type j = 0; j < n; ++j) {\n                \n                if (i != j) {\n                \n                    auto dist = this->euclidean_distance_squared(this->vertices[i], this->vertices[j]);\n                                        \n                    if (this->edges[i].length() >= this->k) {\n                        if (dist < distance_furthest) {\n                            index_type furthest = 0;\n                            index_type neighbor = 0;\n                            index_type furthest_neighbor = 0;\n                            \n                            for (index_type l = 0; l < this->edges[i].length(); ++l) {\n                                neighbor = this->edges[i][l];\n                                furthest_neighbor = this->edges[i][furthest];\n                                \n                                if (this->euclidean_distance_squared(this->vertices[i], this->vertices[furthest_neighbor]) < this->euclidean_distance_squared(this->vertices[i], this->vertices[neighbor])) {\n                                    furthest = l;\n                                }\n                            }\n                            this->edges[i][furthest] = j;\n                            \n                            furthest = 0;\n                            for (index_type l = 0; l < this->edges[i].length(); ++l) {\n                                neighbor = this->edges[i][l];\n                                furthest_neighbor = this->edges[i][furthest];\n                                \n                                if (this->euclidean_distance_squared(this->vertices[i], this->vertices[furthest_neighbor]) < this->euclidean_distance_squared(this->vertices[i], this->vertices[neighbor])) {\n                                    furthest = l;\n                                }\n                            }\n                            distance_furthest = this->euclidean_distance_squared(this->vertices[i], this->vertices[this->edges[i][furthest]]);\n                        }\n                    } else {\n                        if (this->edges[i].length() == 0) {\n                            distance_furthest = dist;\n                        } else {\n                            distance_furthest = std::max(dist, distance_furthest);\n                        }\n                        this->edges[i].push_back(j);\n                    } \n                }\n            }\n            \n        }\n        this->edges_number = n * this->k;\n        std::cout << \"Exact \" << this->k << \"-NNGraph built.\" << std::endl;\n    }\n};\n\ntemplate <typename T = double>\nstd::ostream& operator<<(std::ostream &out, const typename KNN_Graph<T>::Adjacency_List &a) {\n    const auto size = a.size();\n    for (auto i = size-size; i < size-1; ++i) {\n        out << a.get(i);\n        out << \", \";\n    }\n    out << a.get(size-1) << std::endl;\n    return out;\n}\n\ntemplate <typename T>\nstd::ostream& operator<<(std::ostream &out, const KNN_Graph<T> &g) {\n    const auto size = g.number_vertices();\n    for (auto i = size-size; i < size; ++i) {\n        out << i << \"-> \";\n        out << g.get_neighbors(i);\n    }\n    return out;\n}\n", "meta": {"hexsha": "8c019de0d186382e1face98e188ba3dd55372a3f", "size": 13848, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/knn_graph.hpp", "max_stars_repo_name": "hfichtenberger/knn_tester", "max_stars_repo_head_hexsha": "a661baf5cf43e57de7ca4e01246c61feca6160f3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-04-19T16:37:53.000Z", "max_stars_repo_stars_event_max_datetime": "2018-04-19T16:37:53.000Z", "max_issues_repo_path": "include/knn_graph.hpp", "max_issues_repo_name": "hfichtenberger/knn_tester", "max_issues_repo_head_hexsha": "a661baf5cf43e57de7ca4e01246c61feca6160f3", "max_issues_repo_licenses": ["MIT"], "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/knn_graph.hpp", "max_forks_repo_name": "hfichtenberger/knn_tester", "max_forks_repo_head_hexsha": "a661baf5cf43e57de7ca4e01246c61feca6160f3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-16T09:00:36.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-16T09:00:36.000Z", "avg_line_length": 34.7067669173, "max_line_length": 460, "alphanum_fraction": 0.5111929521, "num_tokens": 2932, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390746, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.4832698750335063}}
{"text": "///////////////////////////////////////////////////////////////////\n//  Copyright Eduardo Quintana 2021\n//  Copyright Janek Kozicki 2021\n//  Copyright Christopher Kormanyos 2021\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#include <boost/math/fft/bsl_backend.hpp>\n#include <boost/math/fft/fftw_backend.hpp>\n#include <boost/math/fft/gsl_backend.hpp>\n#include <boost/multiprecision/cpp_complex.hpp>\n\n#include <complex>\n#include <vector>\n#include <array>\n\ntemplate< class fft_engine,int N >\nvoid transform_api()\n{   \n  using T = typename fft_engine::value_type;\n  using boost::math::fft::transform;\n  \n  // test same type of iterator\n  std::vector<T> A(N),B(A.size());\n  transform<fft_engine>::forward(A.begin(),A.end(),B.begin());\n  transform<fft_engine>::backward(A.begin(),A.end(),B.begin());\n  \n  // experimental\n  // backend_t<T,std::allocator<T>>::static_forward(A.begin(),A.end(),B.begin());\n  \n  // test with raw pointers\n  transform<fft_engine>::forward(A.data(),A.data()+A.size(),B.data());\n  transform<fft_engine>::backward(A.data(),A.data()+A.size(),B.data());\n\n  const auto & cA = A;\n  // const iterator as input\n  transform<fft_engine>::forward(cA.begin(),cA.end(),B.begin());\n  transform<fft_engine>::backward(cA.begin(),cA.end(),B.begin());\n  \n  // const pointer as input\n  transform<fft_engine>::forward(cA.data(),cA.data()+cA.size(),B.data());\n  transform<fft_engine>::backward(cA.data(),cA.data()+cA.size(),B.data());\n  \n  std::array<T,N> C; // lets temporarily align this array here to avoid seg. fault\n  // input as vector::iterator, output as array::iterator\n  transform<fft_engine>::forward(A.begin(),A.end(),C.begin());\n  transform<fft_engine>::backward(A.begin(),A.end(),C.begin());\n  transform<fft_engine>::forward(A.data(),A.data()+A.size(),C.data());\n  transform<fft_engine>::backward(A.data(),A.data()+A.size(),C.data());\n  \n  // input as array::iterator, output as vector::iterator\n  transform<fft_engine>::forward(C.begin(),C.end(),B.begin());\n  transform<fft_engine>::backward(C.begin(),C.end(),B.begin());\n  transform<fft_engine>::forward(C.data(),C.data()+C.size(),B.data());\n  transform<fft_engine>::backward(C.data(),C.data()+C.size(),B.data());\n}\n\ntemplate<class Backend >\nvoid plan_api(int N)\n{\n  using T = typename Backend::value_type;\n  Backend P(N);    \n  std::vector<T> A(N),B(N);\n  P.forward(A.data(),A.data()+N,B.data());\n  P.backward(A.data(),A.data()+N,B.data());\n  \n  P.forward(A.begin(),A.end(),B.begin());\n  P.backward(A.begin(),A.end(),B.begin());\n}\n\nstruct my_type{};\n\nvoid test_traits()\n{\n  using boost::multiprecision::is_boost_complex;\n  static_assert(is_boost_complex< std::complex<float> >::value,\"\");\n  static_assert(is_boost_complex< std::complex<double> >::value,\"\");\n  static_assert(is_boost_complex< std::complex<long double> >::value,\"\");\n  static_assert(is_boost_complex< float >::value==false,\"\");\n  static_assert(is_boost_complex< my_type >::value==false,\"\");\n  static_assert(is_boost_complex< my_type >::value==false,\"\");\n  static_assert(is_boost_complex<\n    std::complex<boost::multiprecision::cpp_bin_float_50> >::value==false,\"\");\n  static_assert(is_boost_complex< boost::multiprecision::cpp_complex_quad >::value,\"\");\n}\n\nint main()\n{\n  #if defined(__GNUC__)\n  using boost::math::fft::fftw_dft;\n  using boost::math::fft::gsl_dft;\n  #endif\n  using boost::math::fft::bsl_dft;\n\n  test_traits();\n\n  #if defined(__GNUC__)\n  transform_api<fftw_dft<std::complex<float>>,      4 >();\n  transform_api<fftw_dft<std::complex<double>>,     4 >();\n  transform_api<fftw_dft<std::complex<long double>>,4 >();\n  #endif\n\n  #if defined(__GNUC__)\n  transform_api<gsl_dft<std::complex<double>>,4 >();\n  #endif\n\n  transform_api<bsl_dft<std::complex<float>>,      4 >();\n  transform_api<bsl_dft<std::complex<double>>,     4 >();\n  transform_api<bsl_dft<std::complex<long double>>,4 >();\n\n  #if defined(__GNUC__)\n  plan_api<fftw_dft<std::complex<double>> >(5);\n  plan_api<fftw_dft<std::complex<float>> >(5);\n  plan_api<fftw_dft<std::complex<long double>> >(5);\n  #endif\n\n  #if defined(__GNUC__)\n  plan_api<gsl_dft<std::complex<double>> >(5);\n  #endif\n\n  plan_api<bsl_dft<std::complex<float>> >(5);\n  plan_api<bsl_dft<std::complex<double>> >(5);\n  plan_api<bsl_dft<std::complex<long double>> >(5);\n\n  return 0;\n}\n", "meta": {"hexsha": "35b8852d29b4b97b58f8618a37a085803027a5fb", "size": 4372, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/fft_compile.cpp", "max_stars_repo_name": "BoostGSoC21/math", "max_stars_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "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": "test/fft_compile.cpp", "max_issues_repo_name": "BoostGSoC21/math", "max_issues_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 30.0, "max_issues_repo_issues_event_min_datetime": "2021-06-22T12:59:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-02T09:27:49.000Z", "max_forks_repo_path": "test/fft_compile.cpp", "max_forks_repo_name": "BoostGSoC21/math", "max_forks_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-07T21:15:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-07T21:15:02.000Z", "avg_line_length": 34.15625, "max_line_length": 87, "alphanum_fraction": 0.6710887466, "num_tokens": 1192, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.4832698684614287}}
{"text": "#ifndef STAN_MATH_PRIM_SCAL_PROB_WEIBULL_CDF_HPP\n#define STAN_MATH_PRIM_SCAL_PROB_WEIBULL_CDF_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_finite.hpp>\n#include <stan/math/prim/scal/err/check_nonnegative.hpp>\n#include <stan/math/prim/scal/err/check_not_nan.hpp>\n#include <stan/math/prim/scal/err/check_positive_finite.hpp>\n#include <stan/math/prim/scal/fun/multiply_log.hpp>\n#include <stan/math/prim/scal/fun/value_of.hpp>\n#include <stan/math/prim/scal/meta/length.hpp>\n#include <stan/math/prim/scal/fun/constants.hpp>\n#include <stan/math/prim/scal/meta/include_summand.hpp>\n#include <stan/math/prim/scal/meta/VectorBuilder.hpp>\n#include <stan/math/prim/scal/meta/scalar_seq_view.hpp>\n#include <boost/random/weibull_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <cmath>\n\nnamespace stan {\n  namespace math {\n\n    /**\n     * Returns the Weibull cumulative distribution function for the given\n     * location and scale. Given containers of matching sizes, returns the\n     * product of probabilities.\n     *\n     * @tparam T_y type of real parameter\n     * @tparam T_shape type of shape parameter\n     * @tparam T_scale type of scale paramater\n     * @param y real parameter\n     * @param alpha shape parameter\n     * @param sigma scale parameter\n     * @return probability or product of probabilities\n     * @throw std::domain_error if y is negative, alpha sigma is nonpositive\n     */\n    template <typename T_y, typename T_shape, typename T_scale>\n    typename return_type<T_y, T_shape, T_scale>::type\n    weibull_cdf(const T_y& y, const T_shape& alpha, const T_scale& sigma) {\n      typedef typename stan::partials_return_type<T_y, T_shape, T_scale>::type\n        T_partials_return;\n\n      static const char* function(\"weibull_cdf\");\n\n      using boost::math::tools::promote_args;\n      using std::log;\n      using std::exp;\n\n      if (!(stan::length(y) && stan::length(alpha) && stan::length(sigma)))\n        return 1.0;\n\n      T_partials_return cdf(1.0);\n      check_nonnegative(function, \"Random variable\", y);\n      check_positive_finite(function, \"Shape parameter\", alpha);\n      check_positive_finite(function, \"Scale parameter\", sigma);\n\n      operands_and_partials<T_y, T_shape, T_scale>\n        ops_partials(y, alpha, sigma);\n\n      scalar_seq_view<T_y> y_vec(y);\n      scalar_seq_view<T_scale> sigma_vec(sigma);\n      scalar_seq_view<T_shape> alpha_vec(alpha);\n      size_t N = max_size(y, sigma, alpha);\n      for (size_t n = 0; n < N; n++) {\n        const T_partials_return y_dbl = value_of(y_vec[n]);\n        const T_partials_return sigma_dbl = value_of(sigma_vec[n]);\n        const T_partials_return alpha_dbl = value_of(alpha_vec[n]);\n        const T_partials_return pow_ = pow(y_dbl / sigma_dbl, alpha_dbl);\n        const T_partials_return exp_ = exp(-pow_);\n        const T_partials_return cdf_ = 1.0 - exp_;\n\n        cdf *= cdf_;\n\n        const T_partials_return rep_deriv = exp_ * pow_ / cdf_;\n        if (!is_constant_struct<T_y>::value)\n          ops_partials.edge1_.partials_[n] += rep_deriv * alpha_dbl / y_dbl;\n        if (!is_constant_struct<T_shape>::value)\n          ops_partials.edge2_.partials_[n]\n            += rep_deriv * log(y_dbl / sigma_dbl);\n        if (!is_constant_struct<T_scale>::value)\n          ops_partials.edge3_.partials_[n] -= rep_deriv * alpha_dbl / sigma_dbl;\n      }\n\n      if (!is_constant_struct<T_y>::value) {\n        for (size_t n = 0; n < stan::length(y); ++n)\n          ops_partials.edge1_.partials_[n] *= cdf;\n      }\n      if (!is_constant_struct<T_shape>::value) {\n        for (size_t n = 0; n < stan::length(alpha); ++n)\n          ops_partials.edge2_.partials_[n] *= cdf;\n      }\n      if (!is_constant_struct<T_scale>::value) {\n        for (size_t n = 0; n < stan::length(sigma); ++n)\n          ops_partials.edge3_.partials_[n] *= cdf;\n      }\n      return ops_partials.build(cdf);\n    }\n\n  }\n}\n#endif\n", "meta": {"hexsha": "4f2063904371123a20c5f242d143720a7f7f7f18", "size": 4133, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/scal/prob/weibull_cdf.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/prim/scal/prob/weibull_cdf.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/prim/scal/prob/weibull_cdf.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": 39.3619047619, "max_line_length": 80, "alphanum_fraction": 0.6857004597, "num_tokens": 1087, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324713956856, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4831610569942344}}
{"text": "#include <boost/graph/kamada_kawai_spring_layout.hpp>\n", "meta": {"hexsha": "4a89db93e15a336841c461f541a76536635cba9d", "size": 54, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_graph_kamada_kawai_spring_layout.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_graph_kamada_kawai_spring_layout.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_graph_kamada_kawai_spring_layout.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 27.0, "max_line_length": 53, "alphanum_fraction": 0.8518518519, "num_tokens": 14, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430645886584, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4831460322129732}}
{"text": "#define CATCH_CONFIG_MAIN\n#include <Data/RIGID_STRUCTURE.h>\n#include <Data/RIGID_STRUCTURE_DATA.h>\n#include <Driver/SIMULATION.h>\n#include <Equation/NONLINEAR_EQUATION.h>\n#include <Force/FORCE.h>\n#include <Force/VOLUME_EXCLUSION_CONSTRAINT.h>\n#include <Indexing/RIGID_STRUCTURE_INDEX_MAP.h>\n#include <Math/F.h>\n#include <Math/F_NF.h>\n#include <Math/NF.h>\n#include <Math/NFINV.h>\n#include <Math/R1XRCXR2INV.h>\n#include <Math/RCF_NF.h>\n#include <Math/RXO.h>\n#include <Math/Relative_Position_Force.h>\n#include <Math/Spring_Force.h>\n#include <Utilities/RANDOM.h>\n#include <Eigen/CXX11/Tensor>\n#include <Eigen/KroneckerProduct>\n#include <catch.hpp>\n\nusing namespace Mechanics;\nusing namespace Eigen;\ntypedef double T;\ntypedef Matrix<T,3,1> TV;\ntypedef Matrix<T,3,1> T_SPIN;\ntypedef Matrix<T,3,3> M_VxV;\ntypedef TensorFixedSize<T,Sizes<3,3,3>> T_TENSOR;\ntypedef Dimension::LINEARITY LINEARITY;\n\nM_VxV Contract(const T_TENSOR& t,const TV& v,const std::array<int,3>& indices){\n    M_VxV result;result.setZero();\n    std::array<int,3> index{};\n    for(index[0]=0;index[0]<3;index[0]++){\n        for(index[1]=0;index[1]<3;index[1]++){\n            for(index[2]=0;index[2]<3;index[2]++){\n                result(index[1],index[2])+=t(index[indices[0]],index[indices[1]],index[indices[2]])*v(index[0]);\n            }}}\n    return result;\n}\n\nTV Contract(const T_TENSOR& t,const TV& v1,const TV& v2,const std::array<int,3>& indices){\n    TV result;result.setZero();\n    std::array<int,3> index{};\n    for(index[0]=0;index[0]<3;index[0]++){\n        for(index[1]=0;index[1]<3;index[1]++){\n            for(index[2]=0;index[2]<3;index[2]++){\n                result(index[2])+=t(index[indices[0]],index[indices[1]],index[indices[2]])*v1(index[0])*v2(index[1]);\n            }}}\n    return result;\n}\n\nTV Evaluate(const std::array<TV,2>& positions,const std::array<T_SPIN,2>& spins,const std::array<TV,2>& offsets){\n    return positions[1]+ROTATION<TV>::From_Rotation_Vector(spins[1])*offsets[1]-\n        (positions[0]+ROTATION<TV>::From_Rotation_Vector(spins[0])*offsets[0]);}\n\nTEST_CASE(\"Hessian\"){\n    RANDOM<T> random;\n    T epsilon=1e-3;\n    T divisor=2;\n    std::array<TV,2> positions;\n    std::array<T_SPIN,2> spins;\n    std::array<TV,2> offsets,spun_offsets;\n    for(int i=0;i<2;i++){\n        positions[i]=random.template Direction<TV>();\n        spins[i]=random.template Direction<T_SPIN>();\n        offsets[i]=random.template Direction<TV>();\n        spun_offsets[i]=ROTATION<TV>::From_Rotation_Vector(spins[i])*offsets[i];}\n    TV f=Evaluate(positions,spins,offsets);\n    TV dx=random.template Direction<TV>();\n\n    SECTION(\"dnf_dVelocity\"){\n        TV dnf_dv=RIGID_STRUCTURE_INDEX_MAP<TV>::dnf_dVelocity<LINEARITY::LINEAR>(f,f.norm(),1,spins[0],offsets[0]);\n        auto testlambda=[&](T eps){\n            T predicted=dnf_dv.dot(eps*dx);\n            T actual=Evaluate({positions[0],positions[1]+eps*dx},spins,offsets).norm()-f.norm();\n            return actual-predicted;};\n        T ratio=testlambda(epsilon)/testlambda(epsilon/divisor);\n        REQUIRE(fabs(ratio-sqr(divisor))<0.1);}\n\n    SECTION(\"dnf_dSpin\"){\n        T_SPIN spin=random.template Direction<T_SPIN>();\n        TV dnf_ds=RIGID_STRUCTURE_INDEX_MAP<TV>::dnf_dVelocity<LINEARITY::ANGULAR>(f,f.norm(),1,spins[1],offsets[1]);\n        auto testlambda=[&](T eps){\n            T predicted=dnf_ds.dot(eps*dx);\n            T actual=Evaluate(positions,{spins[0],spins[1]+eps*dx},offsets).norm()-f.norm();\n            return actual-predicted;};\n        T ratio=testlambda(epsilon)/testlambda(epsilon/divisor);\n        REQUIRE(fabs(ratio-sqr(divisor))<0.1);\n\n        M_VxV d2nf_ds2=RIGID_STRUCTURE_INDEX_MAP<TV>::d2n_dVelocity2<LINEARITY::ANGULAR,LINEARITY::ANGULAR>(f,{1,1},{spins[1],spins[1]},{offsets[1],offsets[1]});\n        auto test_second=[&](T eps){\n            T predicted=dnf_ds.dot(eps*dx)+(T).5*eps*eps*dx.transpose()*d2nf_ds2*dx;\n            T actual=Evaluate(positions,{spins[0],spins[1]+eps*dx},offsets).norm()-f.norm();\n            return actual-predicted;};\n        ratio=test_second(epsilon)/test_second(epsilon/divisor);\n        REQUIRE(fabs(ratio-cube(divisor))<0.1);}\n\n    SECTION(\"dnfinv_dVelocity\",\"d2nfinv_dVelocity2\"){\n        TV dnfinv_dv=RIGID_STRUCTURE_INDEX_MAP<TV>::dnfinv_dVelocity<LINEARITY::LINEAR>(f,f.norm(),1,spins[1],offsets[1]);\n        M_VxV d2nfinv_dv=RIGID_STRUCTURE_INDEX_MAP<TV>::d2nfinv_dVelocity2<LINEARITY::LINEAR,LINEARITY::LINEAR>(f,f.norm(),{1,1},spins,offsets);\n        auto testlambda=[&](T eps){\n            T predicted=dnfinv_dv.dot(eps*dx)+((T).5*eps*eps*dx.transpose()*d2nfinv_dv*dx);\n            T actual=1/Evaluate({positions[0],positions[1]+eps*dx},spins,offsets).norm()-1/f.norm();\n            return actual-predicted;};\n        T ratio=testlambda(epsilon)/testlambda(epsilon/divisor);\n        REQUIRE(fabs(ratio-cube(divisor))<0.1);}\n\n    SECTION(\"dnfinv_dSpin\"){\n        TV dnfinv_dv=RIGID_STRUCTURE_INDEX_MAP<TV>::dnfinv_dVelocity<LINEARITY::ANGULAR>(f,f.norm(),1,spins[1],offsets[1]);\n        auto testlambda=[&](T eps){\n            T predicted=dnfinv_dv.dot(eps*dx);\n            T actual=1/Evaluate(positions,{spins[0],spins[1]+eps*dx},offsets).norm()-1/f.norm();\n            return actual-predicted;};\n        T ratio=testlambda(epsilon)/testlambda(epsilon/divisor);\n        REQUIRE(fabs(ratio-sqr(divisor))<0.1);}\n\n    SECTION(\"d2nfinv_dSpin2\"){\n        M_VxV d2nfinv_dv=RIGID_STRUCTURE_INDEX_MAP<TV>::d2nfinv_dVelocity2<LINEARITY::ANGULAR,LINEARITY::ANGULAR>(f,f.norm(),{1,1},{spins[1],spins[1]},{offsets[1],offsets[1]});\n        TV d0=RIGID_STRUCTURE_INDEX_MAP<TV>::dnfinv_dVelocity<LINEARITY::ANGULAR>(f,f.norm(),1,spins[1],offsets[1]);\n        auto testlambda=[&](T eps){\n            T predicted=d0.dot(eps*dx)+((T).5*eps*eps*dx.transpose()*d2nfinv_dv*dx);\n            T actual=1/Evaluate(positions,{spins[0],spins[1]+eps*dx},offsets).norm()-1/f.norm();\n            return actual-predicted;};\n        T ratio=testlambda(epsilon)/testlambda(epsilon/divisor);\n        REQUIRE(fabs(ratio-cube(divisor))<0.1);}\n\n    SECTION(\"dnainv_dA\"){\n        TV dnainv_da=RIGID_STRUCTURE_INDEX_MAP<TV>::dnainv_dA(f,f.norm());\n        auto testlambda=[&](T eps){\n            T predicted=dnainv_da.dot(dx)*eps;\n            T actual=1/(f+eps*dx).norm()-1/f.norm();\n            return actual-predicted;};\n        T ratio=testlambda(epsilon)/testlambda(epsilon/divisor);\n        REQUIRE(fabs(ratio-sqr(divisor))<0.1);}\n\n    SECTION(\"da_na_dA\"){\n        M_VxV da_na_da=RIGID_STRUCTURE_INDEX_MAP<TV>::da_na_dA(f,f.norm());\n        T_TENSOR d2a_na_da2=RIGID_STRUCTURE_INDEX_MAP<TV>::d2a_na_dA2(f,f.norm());\n        auto test_second=[&](T eps){\n            TV contracted=Contract(d2a_na_da2,dx,dx,{0,1,2});\n            TV predicted=da_na_da*dx*eps+((T).5*eps*eps*contracted);\n            TV actual=(f+eps*dx).normalized()-f.normalized();\n            return (actual-predicted).norm();};\n        T ratio=test_second(epsilon)/test_second(epsilon/divisor);\n        REQUIRE(fabs(ratio-cube(divisor))<0.1);}\n\n    SECTION(\"df_nf_dVelocity\"){\n        M_VxV df_dv=RIGID_STRUCTURE_INDEX_MAP<TV>::df_nf_dVelocity<LINEARITY::LINEAR>(f,1,spins[1],offsets[1]);\n        auto testlambda=[&](T eps){\n            TV predicted=df_dv*(eps*dx);\n            TV actual=Evaluate({positions[0],positions[1]+eps*dx},spins,offsets).normalized()-f.normalized();\n            return (actual-predicted).norm();};\n        T ratio=testlambda(epsilon)/testlambda(epsilon/divisor);\n        REQUIRE(fabs(ratio-sqr(divisor))<0.1);}\n\n    SECTION(\"df_dSpin\"){\n        M_VxV df_ds=RIGID_STRUCTURE_INDEX_MAP<TV>::df_dVelocity<LINEARITY::ANGULAR>(1,spins[1],offsets[1]);\n        auto testlambda=[&](T eps){\n            TV predicted=df_ds*(eps*dx);\n            TV actual=Evaluate(positions,{spins[0],spins[1]+eps*dx},offsets)-Evaluate(positions,spins,offsets);\n            return (actual-predicted).norm();};\n        T ratio=testlambda(epsilon)/testlambda(epsilon/divisor);\n        REQUIRE(fabs(ratio-sqr(divisor))<0.1);}\n\n    SECTION(\"d2f_nf_dVelocity2\"){\n        T_TENSOR d2f_dv2=RIGID_STRUCTURE_INDEX_MAP<TV>::d2f_nf_dVelocity2<LINEARITY::LINEAR,LINEARITY::LINEAR>(f,{1,1},spins,offsets);\n        M_VxV df_dv=RIGID_STRUCTURE_INDEX_MAP<TV>::df_nf_dVelocity<LINEARITY::LINEAR>(f,1,spins[1],offsets[1]);\n        auto testlambda=[&](T eps){\n            TV predicted=df_dv*(eps*dx)+(T).5*eps*eps*Contract(d2f_dv2,dx,dx,{0,1,2});\n            TV actual=Evaluate({positions[0],positions[1]+eps*dx},spins,offsets).normalized()-f.normalized();\n            return (actual-predicted).norm();};\n        T ratio=testlambda(epsilon)/testlambda(epsilon/divisor);\n        REQUIRE(fabs(ratio-cube(divisor))<0.1);}\n\n    SECTION(\"d2f_nf_dSpin2\"){\n        T_TENSOR d2f_ds2=RIGID_STRUCTURE_INDEX_MAP<TV>::d2f_nf_dVelocity2<LINEARITY::ANGULAR,LINEARITY::ANGULAR>(f,{1,1},{spins[1],spins[1]},{offsets[1],offsets[1]});\n        M_VxV df_ds=RIGID_STRUCTURE_INDEX_MAP<TV>::df_nf_dVelocity<LINEARITY::ANGULAR>(f,1,spins[1],offsets[1]);\n        auto testlambda=[&](T eps){\n            TV predicted=df_ds*(eps*dx)+(T).5*eps*eps*Contract(d2f_ds2,dx,dx,{0,1,2});\n            TV actual=Evaluate(positions,{spins[0],spins[1]+eps*dx},offsets).normalized()-f.normalized();\n            return (actual-predicted).norm();};\n        T ratio=testlambda(epsilon)/testlambda(epsilon/divisor);\n        REQUIRE(fabs(ratio-cube(divisor))<0.1);}\n\n    SECTION(\"d2n_dVelocity2\"){\n        M_VxV d2n_dv2=RIGID_STRUCTURE_INDEX_MAP<TV>::d2n_dVelocity2<LINEARITY::LINEAR,LINEARITY::LINEAR>(f,{1,1},spins,offsets);\n        TV dnf_dv=RIGID_STRUCTURE_INDEX_MAP<TV>::dnf_dVelocity<LINEARITY::LINEAR>(f,f.norm(),1,spins[1],offsets[1]);\n\n        auto testlambda=[&](T eps){\n            T predicted=dnf_dv.dot(eps*dx)+(T)0.5*eps*eps*dx.transpose()*d2n_dv2*dx;\n            T actual=Evaluate({positions[0],positions[1]+eps*dx},spins,offsets).norm()-f.norm();\n            return actual-predicted;};\n        T ratio=testlambda(epsilon)/testlambda(epsilon/divisor);\n        REQUIRE(fabs(ratio-cube(divisor))<0.1);}\n\n    SECTION(\"d2n_dSpin2\"){\n        M_VxV d2n_dv2=RIGID_STRUCTURE_INDEX_MAP<TV>::d2n_dVelocity2<LINEARITY::ANGULAR,LINEARITY::ANGULAR>(f,{1,1},{spins[1],spins[1]},{offsets[1],offsets[1]});\n        TV dnf_dv=RIGID_STRUCTURE_INDEX_MAP<TV>::dnf_dVelocity<LINEARITY::ANGULAR>(f,f.norm(),1,spins[1],offsets[1]);\n\n        auto testlambda=[&](T eps){\n            T predicted=dnf_dv.dot(eps*dx)+(T)0.5*eps*eps*dx.transpose()*d2n_dv2*dx;\n            T actual=Evaluate(positions,{spins[0],spins[1]+eps*dx},offsets).norm()-f.norm();\n            return actual-predicted;};\n        T ratio=testlambda(epsilon)/testlambda(epsilon/divisor);\n        REQUIRE(fabs(ratio-cube(divisor))<0.1);}\n\n    /*\n      for a proper evaluation, in theory, have to vary all of the things: which derivatives wrt, \n\n      for a scalar function:\n      assume we have 1st and second derivatives for it, wrt angular and linear\n      build all of the necessary first derivatives (four) and second derivatives (16)\n      \n\n\n     */\n\n    // for vector functions\n\n    // VTYPE: LINEAR or ANGULAR\n    // VSIGN:: -1 or 1\n    // V: 0 or 1 (storage index)\n    //\n    // need second derivatives for all combinations (4 x 4)\n\n    std::array<std::array<TV,2>,2> dxs;\n    for(int i=0;i<2;i++){\n        for(int j=0;j<2;j++){\n            dxs[i][j]=random.template Direction<TV>();\n        }}\n\n    SECTION(\"F\"){\n        T ratio=F<TV>::Test_Error(positions,spins,offsets,dxs,epsilon)/F<TV>::Test_Error(positions,spins,offsets,dxs,epsilon/divisor);\n        REQUIRE(fabs(ratio-cube(divisor))<0.1);}\n\n    SECTION(\"NF\"){\n        T ratio=NF<TV>::Test_Error(positions,spins,offsets,dxs,epsilon)/NF<TV>::Test_Error(positions,spins,offsets,dxs,epsilon/divisor);\n        REQUIRE(fabs(ratio-cube(divisor))<0.1);}\n\n    SECTION(\"NFINV\"){\n        T ratio=NFINV<TV>::Test_Error(positions,spins,offsets,dxs,epsilon)/NFINV<TV>::Test_Error(positions,spins,offsets,dxs,epsilon/divisor);\n        REQUIRE(fabs(ratio-cube(divisor))<0.1);}\n\n    SECTION(\"F_NF\"){\n        T ratio=F_NF<TV>::Test_Error(positions,spins,offsets,dxs,epsilon)/F_NF<TV>::Test_Error(positions,spins,offsets,dxs,epsilon/divisor);\n        REQUIRE(fabs(ratio-cube(divisor))<0.1);}\n\n    SECTION(\"RXO\"){\n        T ratio=RXO<TV,1>::Test_Error(positions,spins,offsets,dxs,epsilon)/RXO<TV,1>::Test_Error(positions,spins,offsets,dxs,epsilon/divisor);\n        REQUIRE(fabs(ratio-cube(divisor))<0.1);}\n\n    SECTION(\"RXF_NF\"){\n        T ratio0=RCF_NF<TV,0>::Test_Error(positions,spins,offsets,dxs,epsilon)/RCF_NF<TV,0>::Test_Error(positions,spins,offsets,dxs,epsilon/divisor);\n        REQUIRE(fabs(ratio0-cube(divisor))<0.1);\n    }\n\n    SECTION(\"RXF_NF\"){\n        T ratio1=RCF_NF<TV,1>::Test_Error(positions,spins,offsets,dxs,epsilon)/RCF_NF<TV,1>::Test_Error(positions,spins,offsets,dxs,epsilon/divisor);\n        REQUIRE(fabs(ratio1-cube(divisor))<0.1);\n    }\n\n    SECTION(\"practical\"){\n        std::vector<Triplet<T>> hessian_terms;\n        TV f=F<TV>::Evaluate(positions,spins,offsets);\n        Relative_Position_Force<TV>::Second_Derivatives(f,spins,offsets,{0,1},dxs,hessian_terms);\n    }\n\n    SECTION(\"Spring_Force\"){\n        T target=3;\n        T stiffness=10;\n        M_VxV derivative=Spring_Force<TV>::template First_Derivative<1,1,0,1>(stiffness,target,f,spins,offsets);\n        auto testlambda=[&](T eps){\n            TV predicted=derivative.transpose()*dxs[0][0]*eps;\n            TV actual=Spring_Force<TV>::template Evaluate<1,1>(stiffness,target,{positions[0],positions[1]},{spins[0]+eps*dxs[0][0],spins[1]},offsets)-Spring_Force<TV>::template Evaluate<1,1>(stiffness,target,positions,spins,offsets);\n            return (actual-predicted).norm();\n        };\n        T ratio=testlambda(epsilon)/testlambda(epsilon/divisor);\n        REQUIRE(fabs(ratio-sqr(divisor))<0.1);\n    }\n\n    SECTION(\"association dissociation\"){\n        ROTATION<TV> RC=ROTATION<TV>::From_Rotation_Vector(positions[0]);\n        M_VxV derivative=R1XRCXR2INV<TV>::template First_Derivative<0>(RC,spins);\n        auto testlambda=[&](T eps){\n            TV predicted=derivative.transpose()*dxs[0][0]*eps;\n            TV actual=R1XRCXR2INV<TV>::Evaluate(RC,{spins[0]+eps*dxs[0][0],spins[1]})-R1XRCXR2INV<TV>::Evaluate(RC,spins);\n            return (actual-predicted).norm();\n        };\n        T ratio=testlambda(epsilon)/testlambda(epsilon/2);\n        REQUIRE(fabs(ratio-sqr(divisor))<0.1);\n    }\n\n    SECTION(\"d2f_nf_dVelocity2 full\"){\n        std::array<M_VxV,2> df_dvs;\n        std::array<TV,2> dxs;\n        Matrix<T_TENSOR,2,2> d2f_dv2s;\n        TV zero;zero.setZero();\n        TV f=Evaluate(positions,spins,{zero,zero});\n        for(int s1=0,s1_sgn=-1;s1<2;s1++,s1_sgn+=2){\n            for(int s2=0,s2_sgn=-1;s2<2;s2++,s2_sgn+=2){\n                d2f_dv2s(s1,s2)=RIGID_STRUCTURE_INDEX_MAP<TV>::d2f_nf_dVelocity2<LINEARITY::LINEAR,LINEARITY::LINEAR>(f,{s1_sgn,s2_sgn},{spins[s1],spins[s1]},{offsets[s1],offsets[s2]});}\n            df_dvs[s1]=RIGID_STRUCTURE_INDEX_MAP<TV>::df_nf_dVelocity<LINEARITY::LINEAR>(f,s1_sgn,spins[s1],offsets[s1]);\n            dxs[s1]=random.template Direction<TV>();}\n\n        auto testlambda=[&](T eps){\n            TV predicted;predicted.setZero();\n            for(int s1=0;s1<2;s1++){\n                predicted+=df_dvs[s1].transpose()*(eps*dxs[s1]);\n                for(int s2=0;s2<2;s2++){\n                    predicted+=.5*eps*eps*dxs[s1].transpose()*Contract(d2f_dv2s(s1,s2),dxs[s2],{2,0,1});}}\n            TV actual=Evaluate({positions[0]+eps*dxs[0],positions[1]+eps*dxs[1]},spins,{zero,zero}).normalized()-f.normalized();\n            return (actual-predicted).norm();};\n        T ratio=testlambda(epsilon)/testlambda(epsilon/divisor);\n        REQUIRE(fabs(ratio-cube(divisor))<0.1);}\n\n    // ROTATIONAL PARTS\n    SECTION(\"dw_dSpin\",\"d2w_dSpin2\"){\n        T_SPIN spin=random.template Direction<T_SPIN>();\n        T norm_spin=spin.norm();\n        T initial=cos(norm_spin/2);\n        T_SPIN dw_ds=RIGID_STRUCTURE_INDEX_MAP<TV>::dw_dSpin(spin,norm_spin);\n        T_SPIN ds=random.template Direction<T_SPIN>();\n        M_VxV d2d_ds2=RIGID_STRUCTURE_INDEX_MAP<TV>::d2w_dSpin2(spin,norm_spin);\n        auto testlambda_hessian=[&](T eps){\n            T predicted=dw_ds.dot(eps*ds)+(T).5*eps*eps*ds.transpose()*d2d_ds2*ds;;\n            T actual=cos((spin+eps*ds).norm()/2)-initial;\n            return actual-predicted;};\n\n        T ratio_hessian=testlambda_hessian(epsilon)/testlambda_hessian(epsilon/divisor);\n        REQUIRE(fabs(ratio_hessian-cube(divisor))<0.1);}\n\n    SECTION(\"dq_dSpin\",\"d2q_dSpin2\"){\n        T_SPIN spin=random.template Direction<T_SPIN>();\n        T norm_spin=spin.norm();\n        \n        T_SPIN initial=sinc(norm_spin/2)*spin/2;\n        M_VxV dq_dspin=RIGID_STRUCTURE_INDEX_MAP<TV>::dq_dSpin(spin/norm_spin,norm_spin);\n        T_SPIN ds=random.template Direction<T_SPIN>();\n\n        T_TENSOR d2d_ds2=RIGID_STRUCTURE_INDEX_MAP<TV>::d2q_dSpin2(spin,norm_spin);\n        auto testlambda_hessian=[&](T eps){\n            T_SPIN predicted=dq_dspin*(eps*ds)+(T).5*eps*eps*Contract(d2d_ds2,ds,ds,{0,1,2});\n            T_SPIN final_spin=spin+eps*ds;\n            T_SPIN actual=sinc(final_spin.norm()/2)*final_spin/2-initial;\n            return (actual-predicted).norm();};\n\n        T ratio_hessian=testlambda_hessian(epsilon)/testlambda_hessian(epsilon/divisor);\n        REQUIRE(fabs(ratio_hessian-cube(divisor))<0.1);}\n\n    SECTION(\"d2sxo_dSpin2\"){\n        M_VxV derivative=RIGID_STRUCTURE_INDEX_MAP<TV>::dRotatedOffset_dSpin(spins[1],offsets[1]);\n        TV delta=random.template Direction<TV>();\n        T_TENSOR d2so_ds2=RIGID_STRUCTURE_INDEX_MAP<TV>::d2so_dSpin2(spins[1],offsets[1]);\n        auto test_second=[&](T eps){\n            T_SPIN dspin=eps*dx;\n            TV predicted=derivative*dspin+(T).5*Contract(d2so_ds2,dspin,dspin,{0,1,2});\n            TV final=ROTATION<TV>::From_Rotation_Vector(spins[1]+dspin)*offsets[1];\n            return (final-spun_offsets[1]-predicted).norm();};\n        T ratio=test_second(epsilon)/test_second(epsilon/divisor);\n        REQUIRE(fabs(ratio-cube(divisor))<0.1);}\n\n    // r x f, where f=(f_2-f_1)/|f_2-f_1|\n    SECTION(\"dtau_dSpin\",\"d2tau_dSpin2\"){\n        TV tau_initial=spun_offsets[1].cross(f.normalized());\n        M_VxV dtau_da=RIGID_STRUCTURE_INDEX_MAP<TV>::dtau_dA<LINEARITY::ANGULAR>(f,1,spins[1],offsets[1]);\n        T_TENSOR d2tau_da2=RIGID_STRUCTURE_INDEX_MAP<TV>::d2tau_dV2<LINEARITY::ANGULAR,LINEARITY::ANGULAR>(f,spun_offsets[1],{1,1},{spins[1],spins[1]},{offsets[1],offsets[1]});\n        auto test_second=[&](T eps){\n            T_SPIN dspin=eps*dx;\n            TV predicted=dtau_da*dspin+(T).5*Contract(d2tau_da2,dspin,dspin,{0,1,2});\n            TV r_final=ROTATION<TV>::From_Rotation_Vector(spins[1]+dspin)*offsets[1];\n            TV tau_final=r_final.cross(Evaluate(positions,{spins[0],spins[1]+dspin},offsets).normalized());\n            T error=(tau_final-tau_initial-predicted).norm();\n            return error;};\n        T ratio=test_second(epsilon)/test_second(epsilon/divisor);\n        REQUIRE(fabs(ratio-cube(divisor))<0.1);}\n}\n\n\nTEST_CASE(\"ASSOCIATION_DISSOCATION_CONSTRAINT\"){\n    RANDOM<T> random;\n    int tests=10;\n    T epsilon=1e-4;\n    SECTION(\"dRdS x F\"){\n        for(int i=0;i<tests;i++){\n            /*T_SPIN s1=random.template Direction<T_SPIN>();\n            T_SPIN s2=random.template Direction<T_SPIN>();\n            ROTATION<TV> r1(ROTATION<TV>::From_Rotation_Vector(s1));\n            ROTATION<TV> r2(ROTATION<TV>::From_Rotation_Vector(s2));\n            TV x1=random.template Direction<TV>();\n\n            std::cout<<\"R2: \"<<(r2.inverse()*x1).transpose()<<std::endl;\n            std::cout<<\"Complicated: \"<<((r1.inverse().toRotationMatrix()*(r2.toRotationMatrix()*r1.toRotationMatrix().inverse()).inverse())*x1).transpose()<<std::endl;*/\n\n            T_SPIN spin=random.template Direction<T_SPIN>();\n            TV base_offset=random.template Direction<TV>();\n            TV f=random.template Direction<TV>();\n            ROTATION<TV> rotation(ROTATION<TV>::From_Rotation_Vector(spin));\n            T_SPIN dspin=epsilon*random.template Direction<T_SPIN>();\n\n            TV initial=(rotation*base_offset).cross(f);\n            TV final=(ROTATION<TV>::From_Rotation_Vector(spin+dspin)*base_offset).cross(f);\n\n            \n            M_VxV dFdS;\n            \n            M_VxV derivative=RIGID_STRUCTURE_INDEX_MAP<TV>::dRotatedOffset_dSpin(spin,base_offset);\n            for(int j=0;j<3;j++){\n                dFdS.block<3,1>(0,j)=derivative.block<3,1>(0,j).cross(f);\n            }\n            TV predicted_delta=dFdS*dspin;\n            REQUIRE((final-initial-predicted_delta).norm()<1e-2*epsilon);\n        }\n    }\n    SECTION(\"dCrdS\"){\n        // derivative of the rotation constraint\n        for(int i=0;i<tests;i++){\n            T_SPIN spin=random.template Direction<T_SPIN>();\n            ROTATION<TV> base_rotation=ROTATION<TV>::From_Rotation_Vector(random.template Direction<T_SPIN>());\n            ROTATION<TV> rotation(ROTATION<TV>::From_Rotation_Vector(spin));\n            T_SPIN dspin_direction=random.template Direction<T_SPIN>();\n            ROTATION<TV> total_rotation=base_rotation*rotation.inverse();\n            TV initial=total_rotation.vec();\n            M_VxV derivative=RIGID_STRUCTURE_INDEX_MAP<TV>::Compute_Simple_Orientation_Constraint_Matrix(rotation,total_rotation,-1);\n            auto testlambda=[&](T eps){\n                T_SPIN dspin=eps*dspin_direction;\n                TV final=(base_rotation*ROTATION<TV>::From_Rotation_Vector(spin+dspin).inverse()).vec();\n                TV predicted=derivative*dspin;\n                return (final-initial-predicted).norm();\n            };\n            T ratio=testlambda(epsilon)/testlambda(epsilon/2);\n            REQUIRE(fabs(ratio-4)<1e-2);\n        }\n    }\n}\n\nTEST_CASE(\"VOLUME_EXCLUSION_CONSTRAINT\",\"[derivatives]\"){\n    /*RANDOM<T> random;\n    SECTION(\"derivative\"){\n        SIMULATION<TV> simulation;\n        auto rigid_data=simulation.data.template Find_Or_Create<RIGID_STRUCTURE_DATA<TV>>();\n        auto volume_exclusion_constraint=simulation.force.template Find_Or_Create<VOLUME_EXCLUSION_CONSTRAINT<TV>>();\n        auto structure=std::make_shared<RIGID_STRUCTURE<TV>>();\n        structure->frame.position=random.template Direction<TV>();\n        structure->radius=1;\n        structure->collision_radius=1;\n        structure->Initialize_Inertia(3.5);\n        rigid_data->structures.push_back(structure);\n\n        auto structure2=std::make_shared<RIGID_STRUCTURE<TV>>();\n        structure2->frame.position=structure->frame.position+TV::UnitX()*1.8;\n        structure2->radius=1;\n        structure2->collision_radius=1;\n        structure2->Initialize_Inertia(3.5);\n        rigid_data->structures.push_back(structure2);\n        \n\n        NONLINEAR_EQUATION<TV> equation;\n        equation.Linearize(simulation.data,simulation.force,1,0,1);\n        //std::cout<<equation.jacobian<<std::endl;\n        \n        REQUIRE(1);\n        }*/\n}\n\nTEST_CASE(\"Derivatives\",\"[derivatives]\"){\n    RANDOM<T> random;\n    int tests=10;\n    SECTION(\"dConstraint_dTwist\"){\n        // the constraint is |x2-x1|\n        for(int i=0;i<tests;i++){\n            TV x1=random.template Direction<TV>();\n            TV x2=random.template Direction<TV>();\n            T_SPIN spin=random.template Direction<T_SPIN>();\n            TV base_offset=random.template Direction<TV>();;\n\n            TV rotated_offset=ROTATION<TV>::From_Rotation_Vector(spin)*base_offset;\n            TV relative_position=x2+rotated_offset-x1;\n            Matrix<T,1,6> derivative=RIGID_STRUCTURE_INDEX_MAP<TV>::dConstraint_dTwist(spin,base_offset,relative_position);\n\n            T epsilon=1e-5;\n            Matrix<T,6,1> dx_direction;random.Direction(dx_direction);\n\n            T initial=(x2+rotated_offset-x1).norm();\n\n            auto testlambda=[&](T eps){\n                Matrix<T,6,1> dx=eps*dx_direction;\n                T final=(x2+dx.block<3,1>(0,0)+ROTATION<TV>::From_Rotation_Vector(spin+dx.block<3,1>(3,0))*base_offset-x1).norm();\n                T predicted=derivative*dx;\n                //std::cout<<\"final: \"<<final<<\" initial: \"<<initial<<\" predicted: \"<<predicted<<std::endl;\n                return (final-initial-predicted);\n            };\n            T ratio=testlambda(epsilon)/testlambda(epsilon/2);\n            //std::cout<<\"dC_dT ratio: \"<<ratio<<std::endl;\n            REQUIRE(fabs(ratio-4)<0.1);\n        }\n    }\n    SECTION(\"dForce_dVelocity\"){\n        for(int i=0;i<tests;i++){\n            TV x1=random.template Direction<TV>();\n            TV x2=random.template Direction<TV>();\n            TV relative_position=x2-x1;\n            TV direction=relative_position.normalized();\n            M_VxV derivative=RIGID_STRUCTURE_INDEX_MAP<TV>::dForce_dVelocity(relative_position);\n            T epsilon=1e-6;\n            TV delta=epsilon*random.template Direction<TV>();\n            TV estimated_direction=direction+derivative*delta;\n            TV actual_direction=(x2+delta-x1).normalized();\n            //std::cout<<\"Quality: \"<<(actual_direction-estimated_direction).norm()/epsilon<<std::endl;\n            REQUIRE((actual_direction-estimated_direction).norm()<epsilon);\n        }\n    }\n    SECTION(\"dRotatedOffset_dSpin\"){\n        T epsilon=1e-6;\n        for(int i=0;i<tests;i++){\n            TV base_offset=random.template Direction<TV>();\n            TV spin=random.template Direction<TV>();\n            TV rotated_offset=ROTATION<TV>::From_Rotation_Vector(spin)*base_offset;\n            M_VxV derivative=RIGID_STRUCTURE_INDEX_MAP<TV>::dRotatedOffset_dSpin(spin,base_offset);\n            TV delta=random.template Direction<TV>();\n\n            auto testlambda=[&](T eps){\n                T_SPIN dspin=eps*delta;\n                TV predicted=derivative*dspin;\n                TV final=ROTATION<TV>::From_Rotation_Vector(spin+dspin)*base_offset;\n                T error=(final-rotated_offset-predicted).norm();\n                return error;\n            };\n            T divisor=2;\n            T ratio=testlambda(epsilon)/testlambda(epsilon/divisor);\n            //std::cout<<\"Ratio: \"<<ratio<<std::endl;\n            REQUIRE(fabs(ratio-sqr(divisor))<0.1);\n        }\n    }\n    SECTION(\"dForce_dSpin\"){\n        for(int i=0;i<tests;i++){\n            std::vector<TV> positions(2);\n            std::vector<TV> base_offsets(2);\n            std::vector<TV> spins(2);\n            std::vector<ROTATION<TV>> rotations(2);\n            for(int j=0;j<2;j++){\n                positions[j]=random.template Direction<TV>();\n                base_offsets[j]=random.template Direction<TV>();\n                spins[j]=random.template Direction<TV>();\n                rotations[j]=ROTATION<TV>::From_Rotation_Vector(spins[j]);\n            }\n            TV relative_position=positions[1]+rotations[1]*base_offsets[1]-(positions[0]+rotations[0]*base_offsets[0]);\n            TV direction=relative_position.normalized();\n            T epsilon=1e-8;\n            for(int s1=0;s1<2;s1++){\n                int overall_sign=s1==0?-1:1;\n                for(int s2=0;s2<2;s2++){\n                    int term_sign=s1==s2?1:-1;\n                    M_VxV derivative=term_sign*RIGID_STRUCTURE_INDEX_MAP<TV>::dForce_dSpin(relative_position,spins[s2],base_offsets[s2]);\n                    TV delta=epsilon*random.template Direction<TV>();\n                    TV estimated_direction=overall_sign*(direction)+derivative*delta;\n                    std::vector<TV> mod_spins(2);\n                    for(int j=0;j<2;j++){mod_spins[j]=spins[j];}\n                    mod_spins[s2]+=delta;\n                    TV actual_direction=overall_sign*(positions[1]+ROTATION<TV>::From_Rotation_Vector(mod_spins[1])*base_offsets[1]-(positions[0]+ROTATION<TV>::From_Rotation_Vector(mod_spins[0])*base_offsets[0])).normalized();\n                    REQUIRE((actual_direction-estimated_direction).norm()<2*delta.norm());}}}}\n\n    SECTION(\"Penalty force\",\"dPenaltyForce_dVelocity\"){\n        for(int i=0;i<tests;i++){\n            std::vector<TV> positions(2);\n            std::vector<TV> base_offsets(2);\n            std::vector<TV> spins(2);\n            std::vector<ROTATION<TV>> rotations(2);\n            for(int j=0;j<2;j++){\n                positions[j]=random.template Direction<TV>();\n                base_offsets[j]=random.template Direction<TV>();\n                spins[j]=random.template Direction<TV>();\n                rotations[j]=ROTATION<TV>::From_Rotation_Vector(spins[j]);}\n            T threshold=(positions[1]-positions[0]).norm()+random.Uniform((T)0,(T).1);\n            //TV relative_position=positions[1]+rotations[1]*base_offsets[1]-(positions[0]+rotations[0]*base_offsets[0]);\n            TV relative_position=positions[1]-positions[0];\n            TV direction=relative_position.normalized();\n            T epsilon=1e-8;\n            TV force=sqr(relative_position.norm()-threshold)*relative_position.normalized();\n            M_VxV derivative=RIGID_STRUCTURE_INDEX_MAP<TV>::dPenaltyForce_dVelocity(relative_position,threshold);\n            TV delta=epsilon*random.template Direction<TV>();\n            TV estimated_force=force+derivative*delta;\n            TV new_relative=(positions[1]+delta-positions[0]);\n            TV actual_force=sqr(new_relative.norm()-threshold)*new_relative.normalized();\n            //std::cout<<\"Quality: \"<<(actual_force-estimated_force).norm()/delta.norm()<<std::endl;\n            REQUIRE((actual_force-estimated_force).norm()<delta.norm());\n        }\n    }\n\n    SECTION(\"Penalty force\",\"dPenaltyTorque_dSpin\"){\n        for(int i=0;i<tests;i++){\n            std::vector<TV> positions(2);\n            std::vector<TV> base_offsets(2);\n            std::vector<TV> spins(2);\n            std::vector<ROTATION<TV>> rotations(2);\n            for(int j=0;j<2;j++){\n                positions[j]=random.template Direction<TV>();\n                base_offsets[j]=random.template Direction<TV>();\n                spins[j]=random.template Direction<TV>();\n                rotations[j]=ROTATION<TV>::From_Rotation_Vector(spins[j]);\n            }\n            TV relative_position=positions[1]+rotations[1]*base_offsets[1]-(positions[0]+rotations[0]*base_offsets[0]);\n            T threshold=relative_position.norm()+random.Uniform((T)0,(T).1);\n            std::vector<TV> rotated_offsets={rotations[0]*base_offsets[0],rotations[1]*base_offsets[1]};\n            T epsilon=1e-8;\n            for(int s1=0;s1<2;s1++){\n                int overall_sign=s1==0?-1:1;\n                for(int s2=0;s2<2;s2++){\n                    int term_sign=s1==s2?1:-1;\n                    M_VxV derivative=term_sign*RIGID_STRUCTURE_INDEX_MAP<TV>::dPenaltyTorque_dSpin(relative_position,s1,s2,spins[s2],base_offsets[s1],base_offsets[s2],threshold);\n                    TV delta=epsilon*random.template Direction<TV>();\n\n                    TV torque=overall_sign*(ROTATION<TV>::From_Rotation_Vector(spins[s1])*base_offsets[s1]).cross(sqr(relative_position.norm()-threshold)*relative_position.normalized());\n\n                    TV estimated_torque=torque+derivative*delta;\n                    std::vector<TV> mod_spins(2);\n                    for(int j=0;j<2;j++){mod_spins[j]=spins[j];}\n                    mod_spins[s2]+=delta;\n                    TV new_relative_position=positions[1]+ROTATION<TV>::From_Rotation_Vector(mod_spins[1])*base_offsets[1]-(positions[0]+ROTATION<TV>::From_Rotation_Vector(mod_spins[0])*base_offsets[0]);\n                    TV actual_torque=overall_sign*(ROTATION<TV>::From_Rotation_Vector(mod_spins[s1])*base_offsets[s1]).cross(sqr(new_relative_position.norm()-threshold)*new_relative_position.normalized());\n                    //std::cout<<\"Quality: \"<<(actual_torque-estimated_torque).norm()/delta.norm()<<std::endl;\n                    REQUIRE((actual_torque-estimated_torque).norm()<delta.norm());\n\n                }\n            }\n        }        \n    }\n}\n", "meta": {"hexsha": "a51605794987eaf2eb87900be9ec87551b838b83", "size": 31782, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tests/unit_test/main.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": "Tests/unit_test/main.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": "Tests/unit_test/main.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": 50.4476190476, "max_line_length": 234, "alphanum_fraction": 0.632622239, "num_tokens": 9019, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234877, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4831460273502737}}
{"text": "#ifndef STAN_MATH_FWD_FUN_TGAMMA_HPP\n#define STAN_MATH_FWD_FUN_TGAMMA_HPP\n\n#include <stan/math/fwd/meta.hpp>\n#include <stan/math/fwd/core.hpp>\n#include <stan/math/prim/scal/fun/tgamma.hpp>\n#include <boost/math/special_functions/digamma.hpp>\n\nnamespace stan {\nnamespace math {\n\n/**\n * Return the result of applying the gamma function to the\n * specified argument.\n *\n * @tparam T inner type of the fvar\n * @param x Argument.\n * @return Gamma function applied to argument.\n */\ntemplate <typename T>\ninline fvar<T> tgamma(const fvar<T>& x) {\n  T u = tgamma(x.val_);\n  return fvar<T>(u, x.d_ * u * digamma(x.val_));\n}\n\n}  // namespace math\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "caa17e2a55f28d029bab1690caadca86f542686a", "size": 664, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/fwd/fun/tgamma.hpp", "max_stars_repo_name": "christophernhill/math", "max_stars_repo_head_hexsha": "dc41aba296d592c7099be15eed6ba136d0f140b3", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/fwd/fun/tgamma.hpp", "max_issues_repo_name": "christophernhill/math", "max_issues_repo_head_hexsha": "dc41aba296d592c7099be15eed6ba136d0f140b3", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/fwd/fun/tgamma.hpp", "max_forks_repo_name": "christophernhill/math", "max_forks_repo_head_hexsha": "dc41aba296d592c7099be15eed6ba136d0f140b3", "max_forks_repo_licenses": ["BSD-3-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.8965517241, "max_line_length": 58, "alphanum_fraction": 0.718373494, "num_tokens": 182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.483146022487574}}
{"text": "#include <tiny.h>\n#include <convex.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n\nBOOST_AUTO_TEST_SUITE(convex_signed_distance_to_triangle);\n\nBOOST_AUTO_TEST_CASE(case_by_case_test)\n{\n  typedef tiny::MathTypes<double>        math_types;\n  typedef math_types::vector3_type      vector3_type;\n  typedef math_types::real_type         real_type;\n\n  vector3_type a = vector3_type::make(0.0, 0.0, 0.0);\n  vector3_type b = vector3_type::make(1.0, 0.0, 0.0);;\n  vector3_type c = vector3_type::make(0.0, 1.0, 0.0);;\n  vector3_type q = vector3_type::make(0.33, 0.33, -1.0);\n\n  {\n    vector3_type p = vector3_type::make(0.33, 0.33,  1.0);\n    real_type sign_p = 0.0; \n    sign_p = convex::signed_distance_to_triangle(p, a, b, c, q );\n    BOOST_CHECK_CLOSE( sign_p, 1.0, 0.01 );\n  }\n\n  {\n    vector3_type p = vector3_type::make(0.1, 0.1,  -1.0);\n    real_type sign_p = 0.0; \n    sign_p = convex::signed_distance_to_triangle(p, a, b, c, q );\n    BOOST_CHECK_CLOSE( sign_p, -1.0, 0.01 );\n  }\n\n  {\n    vector3_type p = vector3_type::make(0.1, 0.1,  0.0);\n    real_type sign_p = 10.0; \n    sign_p = convex::signed_distance_to_triangle(p, a, b, c, q );\n    BOOST_CHECK_CLOSE( sign_p, 0.0, 0.01 );\n  }\n\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "fff9aa32af15a28da66f9138e660f9fd91bc59d6", "size": 1376, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/FOUNDATION/CONVEX/unit_tests/convex_sign_dist2tri/convex_sign_dist2tri.cpp", "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/FOUNDATION/CONVEX/unit_tests/convex_sign_dist2tri/convex_sign_dist2tri.cpp", "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/FOUNDATION/CONVEX/unit_tests/convex_sign_dist2tri/convex_sign_dist2tri.cpp", "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": 29.2765957447, "max_line_length": 65, "alphanum_fraction": 0.6816860465, "num_tokens": 464, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.483146022487574}}
{"text": "//-*-c++-*-\n//=======================================================================\n// Copyright 1997-2001 University of Notre Dame.\n// Authors: Lie-Quan Lee\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n\n/*\n  This file is to demo how to use minimum_degree_ordering algorithm.\n\n  Important Note: This implementation requires the BGL graph to be\n  directed.  Therefore, nonzero entry (i, j) in a symmetrical matrix\n  A coresponds to two directed edges (i->j and j->i).\n\n  The bcsstk01.rsa is an example graph in Harwell-Boeing format,\n  and bcsstk01 is the ordering produced by Liu's MMD implementation.\n  Link this file with iohb.c to get the harwell-boeing I/O functions.\n  To run this example, type:\n\n  ./minimum_degree_ordering bcsstk01.rsa bcsstk01\n\n*/\n\n#include <boost/config.hpp>\n#include <fstream>\n#include <iostream>\n#include \"boost/graph/adjacency_list.hpp\"\n#include \"boost/graph/graph_utility.hpp\"\n#include \"boost/graph/minimum_degree_ordering.hpp\"\n#include \"iohb.h\"\n\n//copy and modify from mtl harwell boeing stream\nstruct harwell_boeing\n{\n  harwell_boeing(char* filename) {\n    int Nrhs;\n    char* Type;\n    Type = new char[4];\n    isComplex = false;\n    readHB_info(filename, &M, &N, &nonzeros, &Type, &Nrhs);\n    colptr = (int *)malloc((N+1)*sizeof(int));\n    if ( colptr == NULL ) IOHBTerminate(\"Insufficient memory for colptr.\\n\");\n    rowind = (int *)malloc(nonzeros*sizeof(int));\n    if ( rowind == NULL ) IOHBTerminate(\"Insufficient memory for rowind.\\n\");\n\n    if ( Type[0] == 'C' ) {\n      isComplex = true;\n      val = (double *)malloc(nonzeros*sizeof(double)*2);\n      if ( val == NULL ) IOHBTerminate(\"Insufficient memory for val.\\n\");\n\n    } else {\n      if ( Type[0] != 'P' ) {\n        val = (double *)malloc(nonzeros*sizeof(double));\n        if ( val == NULL ) IOHBTerminate(\"Insufficient memory for val.\\n\");\n      }\n    }\n\n    readHB_mat_double(filename, colptr, rowind, val);\n\n    cnt = 0;\n    col = 0;\n    delete [] Type;\n  }\n\n  ~harwell_boeing() {\n    free(colptr);\n    free(rowind);\n    free(val);\n  }\n\n  inline int nrows() const { return M; }\n\n  int cnt;\n  int col;\n  int* colptr;\n  bool isComplex;\n  int M;\n  int N;\n  int nonzeros;\n  int* rowind;\n  double* val;\n};\n\nint main(int argc, char* argv[])\n{\n  using namespace std;\n  using namespace boost;\n\n  if (argc < 2) {\n    cout << argv[0] << \" HB file\"  << endl;\n    return -1;\n  }\n\n  int delta = 0;\n\n  if ( argc >= 4 )\n  delta = atoi(argv[3]);\n\n  harwell_boeing hbs(argv[1]);\n\n  //must be BGL directed graph now\n  typedef adjacency_list<vecS, vecS, directedS>  Graph;\n\n  int n = hbs.nrows();\n\n  cout << \"n is \" << n << endl;\n\n  Graph G(n);\n\n  int num_edge = 0;\n\n  for (int i = 0; i < n; ++i)\n    for (int j = hbs.colptr[i]; j < hbs.colptr[i+1]; ++j)\n      if ( (hbs.rowind[j - 1] - 1 ) > i ) {\n        add_edge(hbs.rowind[j - 1] - 1, i, G);\n        add_edge(i, hbs.rowind[j - 1] - 1, G);\n        num_edge++;\n      }\n\n  cout << \"number of off-diagnal elements: \" << num_edge << endl;\n\n  typedef std::vector<int> Vector;\n\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  boost::property_map<Graph, vertex_index_t>::type\n    id = get(vertex_index, G);\n\n  Vector degree(n, 0);\n\n  minimum_degree_ordering\n    (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, id);\n\n  if ( argc >= 3 ) {\n    ifstream  input(argv[2]);\n    if ( input.fail() ) {\n      cout << argv[3] << \" is failed to open!. \" << endl;\n      return -1;\n    }\n    int comp;\n    bool is_correct = true;\n    int i;\n    for ( i=0; i<n; i++ ) {\n      input >> comp;\n      if ( comp != inverse_perm[i]+1 ) {\n        cout << \"at i= \" << i << \": \" << comp\n             << \" ***is NOT EQUAL to*** \" << inverse_perm[i]+1 << endl;\n        is_correct = false;\n      }\n    }\n    for ( i=0; i<n; i++ ) {\n      input >> comp;\n      if ( comp != perm[i]+1 ) {\n        cout << \"at i= \" << i << \": \" << comp\n             << \" ***is NOT EQUAL to*** \" << perm[i]+1 << endl;\n        is_correct = false;\n      }\n    }\n    if ( is_correct )\n      cout << \"Permutation and inverse permutation are correct. \"<< endl;\n    else\n      cout << \"WARNING -- Permutation or inverse permutation is not the \"\n           << \"same ones generated by Liu's \" << endl;\n\n  }\n  return 0;\n}\n", "meta": {"hexsha": "9cba47bbdb7e2bdbecbd72f0771625c1df4d0cc6", "size": 4581, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/libs/graph/example/minimum_degree_ordering.cpp", "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/libs/graph/example/minimum_degree_ordering.cpp", "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/libs/graph/example/minimum_degree_ordering.cpp", "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": 25.5921787709, "max_line_length": 77, "alphanum_fraction": 0.5730189915, "num_tokens": 1342, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.7185944046238981, "lm_q1q2_score": 0.48313379708151283}}
{"text": "#define BOOST_TEST_MAIN TestIdGenerator\n#include <boost/test/unit_test.hpp>\n#include <stdexcept>\n#include <string>\n#include <sam/IdGenerator.hpp>\n#include <atomic>\n#include <thread>\n\nusing namespace sam;\n\nBOOST_AUTO_TEST_CASE( test_simple_id_generator )\n{\n\n  SimpleIdGenerator* idGenerator = idGenerator->getInstance();\n\n  int numThreads = 10000;\n  int numTimes = 10000; // How many times each thread requests an id\n  std::atomic<std::uint32_t> sum(0);\n\n  std::vector<std::thread> threads;\n\n  for(int i = 0; i < numThreads; i++) {\n    threads.push_back(std::thread([&idGenerator, &sum, numTimes]() {\n      for (int i = 0; i < numTimes; i++) {\n        sum.fetch_add(idGenerator->generate());   \n      }\n    }));\n  }\n\n  for (int i = 0; i < numThreads; i++) {\n    threads[i].join();\n  }\n\n  uint32_t n = numThreads * numTimes;\n  uint32_t expected = n * (n - 1) / 2;\n  BOOST_CHECK_EQUAL(expected, sum);\n}\n\n", "meta": {"hexsha": "1d40a21a990b642c18f530501538874169893026", "size": 901, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "TestSrc/TestIdGenerator.cpp", "max_stars_repo_name": "elgood/SAM", "max_stars_repo_head_hexsha": "5943d637270581e4fe307bc68fbeb5a8e4eccc2c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-08-16T07:13:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-08T21:15:52.000Z", "max_issues_repo_path": "TestSrc/TestIdGenerator.cpp", "max_issues_repo_name": "elgood/SAM", "max_issues_repo_head_hexsha": "5943d637270581e4fe307bc68fbeb5a8e4eccc2c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-05-30T20:35:18.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-30T20:35:18.000Z", "max_forks_repo_path": "TestSrc/TestIdGenerator.cpp", "max_forks_repo_name": "elgood/SAM", "max_forks_repo_head_hexsha": "5943d637270581e4fe307bc68fbeb5a8e4eccc2c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-02-17T18:38:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-28T02:47:57.000Z", "avg_line_length": 23.1025641026, "max_line_length": 68, "alphanum_fraction": 0.6592674806, "num_tokens": 251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708562, "lm_q2_score": 0.672331705744791, "lm_q1q2_score": 0.4831337936958057}}
{"text": "//\n// OpenTissue, A toolbox for physical based simulation and animation.\n// Copyright (C) 2007 Department of Computer Science, University of Copenhagen\n//\n#include <OpenTissue/configuration.h>\n\n#include <OpenTissue/core/math/math_basic_types.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <OpenTissue/utility/utility_push_boost_filter.h>\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/test_tools.hpp>\n#include <OpenTissue/utility/utility_pop_boost_filter.h>\n\ntemplate<typename math_types>\nvoid compile_test_math_types()\n{\n  typedef typename math_types::index_type         index_type;\n  typedef typename math_types::real_type          real_type;\n  typedef typename math_types::vector3_type       vector3_type;\n  typedef typename math_types::matrix3x3_type     matrix3x3_type;\n  typedef typename math_types::quaternion_type    quaternion_type;\n  typedef typename math_types::coordsys_type      coordsys_type;\n  typedef typename math_types::index_vector3_type index_vector3_type;\n  typedef typename math_types::value_traits       value_traits;\n\n  for(index_type i=0;i<10;++i);  // micky: right :|\n\n  vector3_type     v;\n  matrix3x3_type   m;\n  quaternion_type  q;\n  coordsys_type    c;\n  index_vector3_type iv;\n\n  real_type s1 = value_traits::zero();\n  real_type s2 = value_traits::one();\n  real_type s3 = value_traits::two();\n  real_type s4 = value_traits::pi();\n  real_type s5 = value_traits::pi_2();\n  real_type s6 = value_traits::infinity();\n  real_type s7 = value_traits::degree();\n  real_type s8 = value_traits::radian();\n\n  BOOST_CHECK( s1 == value_traits::zero() );\n  BOOST_CHECK( s2 == value_traits::one() );\n  BOOST_CHECK( s3 == value_traits::two() );\n  BOOST_CHECK( s4 == value_traits::pi() );\n  BOOST_CHECK( s5 == value_traits::pi_2() );\n  BOOST_CHECK( s6 == value_traits::infinity() );\n  BOOST_CHECK( s7 == value_traits::degree() );\n  BOOST_CHECK( s8 == value_traits::radian() );\n}\n\n\nBOOST_AUTO_TEST_SUITE(opentissue_math_basic_math_types);\n\n    BOOST_AUTO_TEST_CASE(type_and_member_compile_test)\n    {\n      //--- Compile testing that we can instantiate most common types and access members\n      typedef OpenTissue::math::BasicMathTypes<float ,      size_t> type1;\n      typedef OpenTissue::math::BasicMathTypes<double,      size_t> type2;\n      typedef OpenTissue::math::BasicMathTypes<float ,unsigned int> type3;\n      typedef OpenTissue::math::BasicMathTypes<double,unsigned int> type4;\n      typedef OpenTissue::math::BasicMathTypes<float ,         int> type5;\n      typedef OpenTissue::math::BasicMathTypes<double,         int> type6;\n\n      void (*ptr1)() = &(compile_test_math_types<type1>);\n      void (*ptr2)() = &(compile_test_math_types<type2>);\n      void (*ptr3)() = &(compile_test_math_types<type3>);\n      void (*ptr4)() = &(compile_test_math_types<type4>);\n      void (*ptr5)() = &(compile_test_math_types<type5>);\n      void (*ptr6)() = &(compile_test_math_types<type6>);\n\n      ptr1 = 0;\n      ptr2 = 0;\n      ptr3 = 0;\n      ptr4 = 0;\n      ptr5 = 0;\n      ptr6 = 0;\n    }\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "eab4fa2deb6fdb07bdf5cce8de7c3624d9badab3", "size": 3086, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/core/math/basic_math_types/src/unit_basic_math_types.cpp", "max_stars_repo_name": "ricortiz/OpenTissue", "max_stars_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 76.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:45:06.000Z", "max_issues_repo_path": "unit_tests/core/math/basic_math_types/src/unit_basic_math_types.cpp", "max_issues_repo_name": "ricortiz/OpenTissue", "max_issues_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2018-11-20T14:32:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T15:26:45.000Z", "max_forks_repo_path": "unit_tests/core/math/basic_math_types/src/unit_basic_math_types.cpp", "max_forks_repo_name": "ricortiz/OpenTissue", "max_forks_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2018-02-21T01:45:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T07:06:49.000Z", "avg_line_length": 36.7380952381, "max_line_length": 88, "alphanum_fraction": 0.7080362929, "num_tokens": 796, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.48313379369580556}}
{"text": "//=======================================================================\r\n// Copyright 2001 Jeremy G. Siek, Andrew Lumsdaine, Lie-Quan Lee, \r\n//\r\n// Distributed under the Boost Software License, Version 1.0. (See\r\n// accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n//=======================================================================\r\n#include <boost/graph/adjacency_list.hpp>\r\n#include <boost/graph/depth_first_search.hpp>\r\n#include <boost/range/irange.hpp>\r\n#include <boost/pending/indirect_cmp.hpp>\r\n\r\n#include <iostream>\r\n\r\nusing namespace boost;\r\ntemplate < typename TimeMap > class dfs_time_visitor:public default_dfs_visitor {\r\n  typedef typename property_traits < TimeMap >::value_type T;\r\npublic:\r\n  dfs_time_visitor(TimeMap dmap, TimeMap fmap, T & t)\r\n:  m_dtimemap(dmap), m_ftimemap(fmap), m_time(t) {\r\n  }\r\n  template < typename Vertex, typename Graph >\r\n    void discover_vertex(Vertex u, const Graph & g) const\r\n  {\r\n    put(m_dtimemap, u, m_time++);\r\n  }\r\n  template < typename Vertex, typename Graph >\r\n    void finish_vertex(Vertex u, const Graph & g) const\r\n  {\r\n    put(m_ftimemap, u, m_time++);\r\n  }\r\n  TimeMap m_dtimemap;\r\n  TimeMap m_ftimemap;\r\n  T & m_time;\r\n};\r\n\r\n\r\nint\r\nmain()\r\n{\r\n  // Select the graph type we wish to use\r\n  typedef adjacency_list < vecS, vecS, directedS > graph_t;\r\n  typedef graph_traits < graph_t >::vertices_size_type size_type;\r\n  // Set up the vertex names\r\n  enum\r\n  { u, v, w, x, y, z, N };\r\n  char name[] = { 'u', 'v', 'w', 'x', 'y', 'z' };\r\n  // Specify the edges in the graph\r\n  typedef std::pair < int, int >E;\r\n  E edge_array[] = { E(u, v), E(u, x), E(x, v), E(y, x),\r\n    E(v, y), E(w, y), E(w, z), E(z, z)\r\n  };\r\n#if defined(BOOST_MSVC) && BOOST_MSVC <= 1300\r\n  graph_t g(N);  \r\n  for (std::size_t j = 0; j < sizeof(edge_array) / sizeof(E); ++j)\r\n    add_edge(edge_array[j].first, edge_array[j].second, g);\r\n#else\r\n  graph_t g(edge_array, edge_array + sizeof(edge_array) / sizeof(E), N);\r\n#endif\r\n\r\n  // discover time and finish time properties\r\n  std::vector < size_type > dtime(num_vertices(g));\r\n  std::vector < size_type > ftime(num_vertices(g));\r\n  typedef\r\n    iterator_property_map<std::vector<size_type>::iterator,\r\n                          property_map<graph_t, vertex_index_t>::const_type>\r\n    time_pm_type;\r\n  time_pm_type dtime_pm(dtime.begin(), get(vertex_index, g));\r\n  time_pm_type ftime_pm(ftime.begin(), get(vertex_index, g));\r\n  size_type t = 0;\r\n  dfs_time_visitor < time_pm_type >vis(dtime_pm, ftime_pm, t);\r\n\r\n  depth_first_search(g, visitor(vis));\r\n\r\n  // use std::sort to order the vertices by their discover time\r\n  std::vector < size_type > discover_order(N);\r\n  integer_range < size_type > r(0, N);\r\n  std::copy(r.begin(), r.end(), discover_order.begin());\r\n  std::sort(discover_order.begin(), discover_order.end(),\r\n            indirect_cmp < time_pm_type, std::less < size_type > >(dtime_pm));\r\n  std::cout << \"order of discovery: \";\r\n  int i;\r\n  for (i = 0; i < N; ++i)\r\n    std::cout << name[discover_order[i]] << \" \";\r\n\r\n  std::vector < size_type > finish_order(N);\r\n  std::copy(r.begin(), r.end(), finish_order.begin());\r\n  std::sort(finish_order.begin(), finish_order.end(),\r\n            indirect_cmp < time_pm_type, std::less < size_type > >(ftime_pm));\r\n  std::cout << std::endl << \"order of finish: \";\r\n  for (i = 0; i < N; ++i)\r\n    std::cout << name[finish_order[i]] << \" \";\r\n  std::cout << std::endl;\r\n\r\n  return EXIT_SUCCESS;\r\n}\r\n", "meta": {"hexsha": "03de5188936ca1a9b6ea2240bad6a49a5416a570", "size": 3476, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/graph/example/dfs-example.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": 85.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T20:36:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T20:38:31.000Z", "max_issues_repo_path": "libs/boost/libs/graph/example/dfs-example.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/graph/example/dfs-example.cpp", "max_forks_repo_name": "flingone/frameworks_base_cmds_remoted", "max_forks_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2015-01-28T16:33:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-12T05:04:39.000Z", "avg_line_length": 35.8350515464, "max_line_length": 82, "alphanum_fraction": 0.6153624856, "num_tokens": 948, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185944046238981, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.4831337923635778}}
{"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   TangentPreintegration.cpp\n *  @author Frank Dellaert\n *  @author Adam Bry\n **/\n\n#include \"TangentPreintegration.h\"\n#include <gtsam/base/numericalDerivative.h>\n#include <boost/make_shared.hpp>\n\nusing namespace std;\n\nnamespace gtsam {\n\n//------------------------------------------------------------------------------\nTangentPreintegration::TangentPreintegration(const boost::shared_ptr<Params>& p,\n    const Bias& biasHat) :\n    PreintegrationBase(p, biasHat) {\n  resetIntegration();\n}\n\n//------------------------------------------------------------------------------\nvoid TangentPreintegration::resetIntegration() {\n  deltaTij_ = 0.0;\n  preintegrated_.setZero();\n  preintegrated_H_biasAcc_.setZero();\n  preintegrated_H_biasOmega_.setZero();\n}\n\n//------------------------------------------------------------------------------\nbool TangentPreintegration::equals(const TangentPreintegration& other,\n    double tol) const {\n  return p_->equals(*other.p_, tol) && std::abs(deltaTij_ - other.deltaTij_) < tol\n      && biasHat_.equals(other.biasHat_, tol)\n      && equal_with_abs_tol(preintegrated_, other.preintegrated_, tol)\n      && equal_with_abs_tol(preintegrated_H_biasAcc_,\n          other.preintegrated_H_biasAcc_, tol)\n      && equal_with_abs_tol(preintegrated_H_biasOmega_,\n          other.preintegrated_H_biasOmega_, tol);\n}\n\n//------------------------------------------------------------------------------\n// See extensive discussion in ImuFactor.lyx\nVector9 TangentPreintegration::UpdatePreintegrated(const Vector3& a_body,\n    const Vector3& w_body, double dt, const Vector9& preintegrated,\n    OptionalJacobian<9, 9> A, OptionalJacobian<9, 3> B,\n    OptionalJacobian<9, 3> C) {\n  const auto theta = preintegrated.segment<3>(0);\n  const auto position = preintegrated.segment<3>(3);\n  const auto velocity = preintegrated.segment<3>(6);\n\n  // This functor allows for saving computation when exponential map and its\n  // derivatives are needed at the same location in so<3>\n  so3::DexpFunctor local(theta);\n\n  // Calculate exact mean propagation\n  Matrix3 w_tangent_H_theta, invH;\n  const Vector3 w_tangent = // angular velocity mapped back to tangent space\n      local.applyInvDexp(w_body, A ? &w_tangent_H_theta : 0, C ? &invH : 0);\n  const Rot3 R(local.expmap());  // nRb: rotation of body in nav frame\n  const Vector3 a_nav = R * a_body;\n  const double dt22 = 0.5 * dt * dt;\n\n  Vector9 preintegratedPlus;\n  preintegratedPlus <<                          // new preintegrated vector:\n      theta + w_tangent * dt,                   // theta\n      position + velocity * dt + a_nav * dt22,  // position\n      velocity + a_nav * dt;                    // velocity\n\n  if (A) {\n    // Exact derivative of R*a with respect to theta:\n    const Matrix3 a_nav_H_theta = R.matrix() * skewSymmetric(-a_body) * local.dexp();\n\n    A->setIdentity();\n    A->block<3, 3>(0, 0).noalias() += w_tangent_H_theta * dt;  // theta\n    A->block<3, 3>(3, 0) = a_nav_H_theta * dt22;  // position wrpt theta...\n    A->block<3, 3>(3, 6) = I_3x3 * dt;            // .. and velocity\n    A->block<3, 3>(6, 0) = a_nav_H_theta * dt;    // velocity wrpt theta\n  }\n  if (B) {\n    B->block<3, 3>(0, 0) = Z_3x3;\n    B->block<3, 3>(3, 0) = R.matrix() * dt22;\n    B->block<3, 3>(6, 0) = R.matrix() * dt;\n  }\n  if (C) {\n    C->block<3, 3>(0, 0) = invH * dt;\n    C->block<3, 3>(3, 0) = Z_3x3;\n    C->block<3, 3>(6, 0) = Z_3x3;\n  }\n\n  return preintegratedPlus;\n}\n\n//------------------------------------------------------------------------------\nvoid TangentPreintegration::update(const Vector3& measuredAcc,\n    const Vector3& measuredOmega, const double dt, Matrix9* A, Matrix93* B,\n    Matrix93* C) {\n    \n  // std::cout << \"TangentPreintegration::update\" << std::endl;\n  // Correct for bias in the sensor frame\n  Vector3 acc = biasHat_.correctAccelerometer(measuredAcc);\n  Vector3 omega = biasHat_.correctGyroscope(measuredOmega);\n\n  // Possibly correct for sensor pose by converting to body frame\n  Matrix3 D_correctedAcc_acc, D_correctedAcc_omega, D_correctedOmega_omega;\n  if (p().body_P_sensor)\n    boost::tie(acc, omega) = correctMeasurementsBySensorPose(acc, omega,\n        D_correctedAcc_acc, D_correctedAcc_omega, D_correctedOmega_omega);\n\n  // Do update\n  deltaTij_ += dt;\n  preintegrated_ = UpdatePreintegrated(acc, omega, dt, preintegrated_, A, B, C);\n\n  if (p().body_P_sensor) {\n    // More complicated derivatives in case of non-trivial sensor pose\n    *C *= D_correctedOmega_omega;\n    if (!p().body_P_sensor->translation().isZero())\n      *C += *B * D_correctedAcc_omega;\n    *B *= D_correctedAcc_acc; // NOTE(frank): needs to be last\n  }\n\n  // new_H_biasAcc = new_H_old * old_H_biasAcc + new_H_acc * acc_H_biasAcc\n  // where acc_H_biasAcc = -I_3x3, hence\n  // new_H_biasAcc = new_H_old * old_H_biasAcc - new_H_acc\n  preintegrated_H_biasAcc_ = (*A) * preintegrated_H_biasAcc_ - (*B);\n\n  // new_H_biasOmega = new_H_old * old_H_biasOmega + new_H_omega * omega_H_biasOmega\n  // where omega_H_biasOmega = -I_3x3, hence\n  // new_H_biasOmega = new_H_old * old_H_biasOmega - new_H_omega\n  preintegrated_H_biasOmega_ = (*A) * preintegrated_H_biasOmega_ - (*C);\n}\n\n//------------------------------------------------------------------------------\nVector9 TangentPreintegration::biasCorrectedDelta(\n    const imuBias::ConstantBias& bias_i, OptionalJacobian<9, 6> H) const {\n  // We correct for a change between bias_i and the biasHat_ used to integrate\n  // This is a simple linear correction with obvious derivatives\n  const imuBias::ConstantBias biasIncr = bias_i - biasHat_;\n  const Vector9 biasCorrected = preintegrated()\n      + preintegrated_H_biasAcc_ * biasIncr.accelerometer()\n      + preintegrated_H_biasOmega_ * biasIncr.gyroscope();\n\n  if (H) {\n    (*H) << preintegrated_H_biasAcc_, preintegrated_H_biasOmega_;\n  }\n  return biasCorrected;\n}\n\n//------------------------------------------------------------------------------\n// sugar for derivative blocks\n#define D_R_R(H) (H)->block<3,3>(0,0)\n#define D_R_t(H) (H)->block<3,3>(0,3)\n#define D_R_v(H) (H)->block<3,3>(0,6)\n#define D_t_R(H) (H)->block<3,3>(3,0)\n#define D_t_t(H) (H)->block<3,3>(3,3)\n#define D_t_v(H) (H)->block<3,3>(3,6)\n#define D_v_R(H) (H)->block<3,3>(6,0)\n#define D_v_t(H) (H)->block<3,3>(6,3)\n#define D_v_v(H) (H)->block<3,3>(6,6)\n\n//------------------------------------------------------------------------------\nVector9 TangentPreintegration::Compose(const Vector9& zeta01,\n    const Vector9& zeta12, double deltaT12, OptionalJacobian<9, 9> H1,\n    OptionalJacobian<9, 9> H2) {\n  const auto t01 = zeta01.segment<3>(0);\n  const auto p01 = zeta01.segment<3>(3);\n  const auto v01 = zeta01.segment<3>(6);\n\n  const auto t12 = zeta12.segment<3>(0);\n  const auto p12 = zeta12.segment<3>(3);\n  const auto v12 = zeta12.segment<3>(6);\n\n  Matrix3 R01_H_t01, R12_H_t12;\n  const Rot3 R01 = Rot3::Expmap(t01, R01_H_t01);\n  const Rot3 R12 = Rot3::Expmap(t12, R12_H_t12);\n\n  Matrix3 R02_H_R01, R02_H_R12; // NOTE(frank): R02_H_R12 == Identity\n  const Rot3 R02 = R01.compose(R12, R02_H_R01, R02_H_R12);\n\n  Matrix3 t02_H_R02;\n  Vector9 zeta02;\n  const Matrix3 R = R01.matrix();\n  zeta02 << Rot3::Logmap(R02, t02_H_R02), // theta\n  p01 + v01 * deltaT12 + R * p12, // position\n  v01 + R * v12; // velocity\n\n  if (H1) {\n    H1->setIdentity();\n    D_R_R(H1) = t02_H_R02 * R02_H_R01 * R01_H_t01;\n    D_t_R(H1) = R * skewSymmetric(-p12) * R01_H_t01;\n    D_t_v(H1) = I_3x3 * deltaT12;\n    D_v_R(H1) = R * skewSymmetric(-v12) * R01_H_t01;\n  }\n\n  if (H2) {\n    H2->setZero();\n    D_R_R(H2) = t02_H_R02 * R02_H_R12 * R12_H_t12;\n    D_t_t(H2) = R;\n    D_v_v(H2) = R;\n  }\n\n  return zeta02;\n}\n\n//------------------------------------------------------------------------------\nvoid TangentPreintegration::mergeWith(const TangentPreintegration& pim12,\n    Matrix9* H1, Matrix9* H2) {\n  if (!matchesParamsWith(pim12)) {\n    throw std::domain_error(\n        \"Cannot merge pre-integrated measurements with different params\");\n  }\n\n  if (params()->body_P_sensor) {\n    throw std::domain_error(\n        \"Cannot merge pre-integrated measurements with sensor pose yet\");\n  }\n\n  const double t01 = deltaTij();\n  const double t12 = pim12.deltaTij();\n  deltaTij_ = t01 + t12;\n\n  const Vector9 zeta01 = preintegrated();\n  Vector9 zeta12 = pim12.preintegrated(); // will be modified.\n\n  const imuBias::ConstantBias bias_incr_for_12 = biasHat() - pim12.biasHat();\n  zeta12 += pim12.preintegrated_H_biasOmega_ * bias_incr_for_12.gyroscope()\n      + pim12.preintegrated_H_biasAcc_ * bias_incr_for_12.accelerometer();\n\n  preintegrated_ = TangentPreintegration::Compose(zeta01, zeta12, t12, H1, H2);\n\n  preintegrated_H_biasAcc_ = (*H1) * preintegrated_H_biasAcc_\n      + (*H2) * pim12.preintegrated_H_biasAcc_;\n\n  preintegrated_H_biasOmega_ = (*H1) * preintegrated_H_biasOmega_\n      + (*H2) * pim12.preintegrated_H_biasOmega_;\n}\n\n//------------------------------------------------------------------------------\n\n}// namespace gtsam\n", "meta": {"hexsha": "fdcd768bf16b069d24c8b2976c4dc2b6a0a8b018", "size": 9341, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/navigation/TangentPreintegration.cpp", "max_stars_repo_name": "pu-wei/gtsam", "max_stars_repo_head_hexsha": "e2e88efb3176cc297698ad8c5e227106f58bd590", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gtsam/navigation/TangentPreintegration.cpp", "max_issues_repo_name": "pu-wei/gtsam", "max_issues_repo_head_hexsha": "e2e88efb3176cc297698ad8c5e227106f58bd590", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/navigation/TangentPreintegration.cpp", "max_forks_repo_name": "pu-wei/gtsam", "max_forks_repo_head_hexsha": "e2e88efb3176cc297698ad8c5e227106f58bd590", "max_forks_repo_licenses": ["BSD-3-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.0674603175, "max_line_length": 85, "alphanum_fraction": 0.6155657852, "num_tokens": 2725, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.4831337889778706}}
{"text": "/**\n * @file HashFunction.hpp\n * @author bwu\n * @brief Hush functions of geometries\n * @version 0.1\n * @date 2022-02-22\n */\n#ifndef GENERIC_GEOMETRY_HASHFUNCTION_HPP\n#define GENERIC_GEOMETRY_HASHFUNCTION_HPP\n#include \"Point.hpp\"\n#include <boost/functional/hash.hpp>\n#include <functional>\nnamespace generic  {\nnamespace geometry {\n\ntemplate <typename num_type>\nstruct PointHash\n{\n};\n\ntemplate <>\nstruct PointHash<int32_t>\n{\n    size_t operator()(const Point2D<int32_t> & point) const noexcept\n    {\n        size_t seed(0);\n        boost::hash_combine(seed, point[0]);\n        boost::hash_combine(seed, point[1]);\n        return seed;\n    }\n};\n\ntemplate <>\nstruct PointHash<int64_t>\n{\n    size_t operator()(const Point2D<int64_t> & point) const noexcept\n    {\n        size_t seed(0);\n        boost::hash_combine(seed, point[0]);\n        boost::hash_combine(seed, point[1]);\n        return seed;\n    }\n};\n\n}//namespace geometry\n}//namespace generic\n#endif//GENERIC_GEOMETRY_HASHFUNCTION_HPP", "meta": {"hexsha": "f8df543c0f979e019e4c405eb5c3d48362c2d1bb", "size": 987, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "geometry/HashFunction.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/HashFunction.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/HashFunction.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": 21.0, "max_line_length": 68, "alphanum_fraction": 0.6818642351, "num_tokens": 247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.48313378492604947}}
{"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#include \"include/kRegular.hh\"\n#include <boost/foreach.hpp>\n\nkRegular::kRegular(const boost::shared_ptr<HypergrapheAbstrait>& ptrHypergrapheAbstrait) {\n\t_ptrHypergrapheAbstrait = ptrHypergrapheAbstrait;\n}\n\nvoid\nkRegular::runAlgorithme() {\n\n\t_result.setBooleanResult(true);\n\tAdjacentMatrix matrix ( _ptrHypergrapheAbstrait->getAdjacentMatrix() );\n\n\tint compteur = -1;\n\tBOOST_FOREACH(const auto& e, _ptrHypergrapheAbstrait->getIndexHyperVertex() ) {\n\t\tif(compteur==-1) {\n\t\t\tcompteur = matrix.getVertexDegree(e.first);\n\t\t} else {\n\t\t\tif( (int)matrix.getVertexDegree(e.first) != compteur ) {\n\t\t\t\t_result.setBooleanResult(false);\n\t\t\t};\n\t\t};\n\t}\n\n\tif( compteur==-1 ) _result.setBooleanResult(true);\n}\n\nRStructure\nkRegular::getResult() const {\n\treturn _result;\n}\n\nkRegular::~kRegular() {\n\n}\n", "meta": {"hexsha": "d72272a1d2c1f7325477c199874d6731441d5cf5", "size": 1929, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/algorithm/kRegular.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/kRegular.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/kRegular.cpp", "max_forks_repo_name": "ehzawad/HyperGraphLib", "max_forks_repo_head_hexsha": "a1424437a01ad5a9e0efa71d723d32fd58ca589c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-02-12T23:12:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-28T06:34:55.000Z", "avg_line_length": 31.6229508197, "max_line_length": 90, "alphanum_fraction": 0.745463971, "num_tokens": 475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943805178139, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.4831337761562934}}
{"text": "#define BOOST_TEST_MODULE SolutionTest\n\n#include \"solution.hpp\"\n\n//#define BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n\nBOOST_AUTO_TEST_SUITE(SolutionSuite)\n\nBOOST_AUTO_TEST_CASE(PlainTest1)\n{\n    vector<int> heights{2,1,5,6,2,3};\n    int result = Solution().largestRectangleArea(heights);\n\n    int expected = 10;\n\n    BOOST_CHECK_EQUAL(result, expected);\n}\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "60c83fcc8d7e996826428023666260eafe5a7888", "size": 398, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "084-Largest-Rectangle-in-Histogram-recursion/solution_test.cpp", "max_stars_repo_name": "johnhany/leetcode", "max_stars_repo_head_hexsha": "453a86ac16360e44893262e04f77fd350d1e80f2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-05-27T06:47:32.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-22T05:57:10.000Z", "max_issues_repo_path": "084-Largest-Rectangle-in-Histogram/solution_test.cpp", "max_issues_repo_name": "johnhany/leetcode", "max_issues_repo_head_hexsha": "453a86ac16360e44893262e04f77fd350d1e80f2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "084-Largest-Rectangle-in-Histogram/solution_test.cpp", "max_forks_repo_name": "johnhany/leetcode", "max_forks_repo_head_hexsha": "453a86ac16360e44893262e04f77fd350d1e80f2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-04-01T10:26:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-05T18:21:01.000Z", "avg_line_length": 19.9, "max_line_length": 58, "alphanum_fraction": 0.7663316583, "num_tokens": 99, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723316860482763, "lm_q2_score": 0.7185943865443352, "lm_q1q2_score": 0.48313377549017966}}
{"text": "\n\n\n#ifndef BINDING_UTILS_HPP\n#define BINDING_UTILS_HPP\n\n/// @cond\n\n#include <stddef.h>\n#include <iostream>\n#include <boost/numeric/bindings/size.hpp>\n#include <boost/numeric/bindings/begin.hpp>\n#include <boost/numeric/bindings/value_type.hpp>\n#include \"random.hpp\"\n\n/* \\file binding_utils.hpp\n   \\brief Some useful functions to handle ublas matrices and vectors.\n   Source = boost bindings examples.\n*/\n\nnamespace Siconos {\n  namespace algebra {\n\n///////////////////////////////\n// vectors\n\n// element access:\n    template <typename V>\n    struct vct_access_traits {\n      typedef typename\n      boost::numeric::bindings::value_type<V>::type val_t;\n      typedef val_t& ref_t;\n      static ref_t elem (V& v, size_t i) { return v[i]; }\n    };\n\n    template <typename V>\n    struct vct_access_traits<V const> {\n      typedef typename\n      boost::numeric::bindings::value_type<V>::type val_t;\n      typedef val_t ref_t;\n      static ref_t elem (V const& v, size_t i) { return v[i]; }\n    };\n\n    template <typename V>\n    inline\n    typename vct_access_traits<V>::ref_t elem_v (V& v, size_t i) {\n      return vct_access_traits<V>::elem (v, i);\n    }\n\n// initialization:\n    struct ident {\n      size_t operator() (size_t i) const { return i; }\n    };\n    struct iplus1 {\n      size_t operator() (size_t i) const { return i + 1; }\n    };\n    template <typename T>\n    struct const_val {\n      T val;\n      const_val (T v = T()) : val (v) {}\n      T operator() (size_t) const { return val; }\n      T operator() (size_t, size_t) const { return val; }\n    };\n    struct kpp {\n      size_t val;\n      kpp (size_t v = 0) : val (v) {}\n      size_t operator() (size_t) {\n        size_t tmp = val;\n        ++val;\n        return tmp;\n      }\n      size_t operator() (size_t, size_t) {\n        size_t tmp = val;\n        ++val;\n        return tmp;\n      }\n    };\n    template <typename T>\n    struct times_plus {\n      T s, a, b;\n      times_plus (T ss, T aa = T(), T bb = T()) : s (ss), a (aa), b (bb) {}\n      T operator() (size_t i) const {\n        return s * (T) i + a;\n      }\n      T operator() (size_t i, size_t j) const {\n        return s * ((T) i + a) + (T) j + b;\n      }\n    };\n\n    template <typename F, typename V>\n    void init_v (V& v, F f = F()) {\n      size_t sz\n        = boost::numeric::bindings::size( v );\n      for (std::size_t i = 0; i < sz; ++i)\n        elem_v (v, i) = f (i);\n    }\n\n// printing:\n    template <typename V>\n    void print_v (V const& v, char const* ch = nullptr) {\n      if (ch)\n        std::cout << ch << \": \";\n      size_t sz\n        = boost::numeric::bindings::size( v );\n      for (std::size_t i = 0; i < sz; ++i)\n        std::cout << elem_v (v, i) << \" \";\n      std::cout << std::endl;\n    }\n\n\n/////////////////////////////////////\n// matrices\n\n// element access:\n    template <typename M>\n    struct matr_access_traits {\n      typedef M mat_t;\n      typedef typename boost::numeric::bindings::value_type<mat_t>::type val_t;\n      typedef typename mat_t::reference ref_t;\n      static ref_t elem (mat_t& m, size_t i, size_t j) { return m (i, j); }\n    };\n\n#ifdef EIGEN_FORWARDDECLARATIONS_H\n    template<typename _Scalar, int _Rows, int _Cols, int _Options, int _MaxRows, int _MaxCols>\n    struct matr_access_traits<Eigen::Matrix<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols> > {\n      typedef Eigen::Matrix<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols> mat_t;\n      typedef typename boost::numeric::bindings::value_type<mat_t>::type val_t;\n      typedef val_t& ref_t;\n      static ref_t elem (mat_t& m, size_t i, size_t j) { return m (i, j); }\n    };\n#endif\n\n    template <typename M>\n    struct matr_access_traits<M const> {\n      typedef M const mat_t;\n      typedef typename boost::numeric::bindings::value_type<mat_t>::type val_t;\n      typedef val_t ref_t;\n      static ref_t elem (mat_t& m, size_t i, size_t j) { return m (i, j); }\n    };\n\n    template <typename M>\n    inline\n    typename matr_access_traits<M>::ref_t elem_m (M& m, size_t i, size_t j) {\n      return matr_access_traits<M>::elem (m, i, j);\n    }\n\n// initialization:\n    struct rws {\n      size_t operator() (size_t i, size_t) const { return i; }\n    };\n    struct rws1 {\n      size_t operator() (size_t i, size_t) const { return i + 1; }\n    };\n    struct cls {\n      size_t operator() (size_t, size_t j) const { return j; }\n    };\n    struct cls1 {\n      size_t operator() (size_t, size_t j) const { return j + 1; }\n    };\n\n    template <typename F, typename M>\n    void init_m (M& m, F f = F()) {\n      size_t sz1\n        = boost::numeric::bindings::size_row( m );\n      size_t sz2\n        = boost::numeric::bindings::size_column( m );\n      for (std::size_t i = 0; i < sz1; ++i)\n        for (std::size_t j = 0; j < sz2; ++j)\n          elem_m (m, i, j) = f (i, j);\n    }\n\n    template <typename M>\n    void init_symm (M& m, char uplo = 'f') {\n      size_t n\n        = boost::numeric::bindings::size_row( m );\n      for (size_t i = 0; i < n; ++i) {\n        elem_m (m, i, i) = n;\n        for (size_t j = i + 1; j < n; ++j) {\n          if (uplo == 'u' || uplo == 'U')\n            elem_m (m, i, j) = n - (j - i);\n          else if (uplo == 'l' || uplo == 'L')\n            elem_m (m, j, i) = n - (j - i);\n          else\n            elem_m (m, i, j) = elem_m (m, j, i) = n - (j - i);\n        }\n      }\n    }\n\n/** Print a boost-ublas matrix\n */\n    template <typename M>\n    void print_m (M const& m, char const* ch = nullptr) {\n      if (ch)\n        std::cout << ch << \":\\n\";\n      size_t sz1\n        = boost::numeric::bindings::size_row( m );\n      size_t sz2\n        = boost::numeric::bindings::size_column( m );\n      for (std::size_t i = 0 ; i < sz1 ; ++i) {\n        for (std::size_t j = 0 ; j < sz2 ; ++j)\n          std::cout << elem_m (m, i, j) << \", \";\n        std::cout << std::endl;\n      }\n      //  std::cout << std::endl;\n    }\n\n    template <typename M>\n    void print_m_data (M const& m, char const* ch = nullptr) {\n      if (ch)\n        std::cout << ch << \" data:\\n\";\n      using namespace boost::numeric::bindings;\n      std::copy( begin_value( m ), end_value( m ), std::ostream_iterator\n                 < typename value_type< const M >::type >( std::cout, \" \" ) );\n      std::cout << std::endl;\n    }\n\n// Below are functions from boost bindings tests (see ublas_heev.hpp).\n\n    inline float conj(float v) { return v; }\n    inline double conj(double v) { return v; }\n    inline float real(float v) { return v; }\n    inline double real(double v) { return v; }\n\n/** Fill a banded matrix with random values\n */\n    template <typename M>\n    void fill_banded(M& m) {\n      typedef typename M::value_type value_type ;\n\n      int size = m.size2() ;\n      int band = m.upper() ;\n\n      for (int i=0; i<size; ++i) {\n        for (int j=std::max(0,i-band); j<i; ++j) m(j,i) = random_value<value_type>();\n        m(i,i) = real( random_value<value_type>() );\n      }\n    } // randomize()\n\n/** Fill a symmetric matrix with random values\n */\n    template <typename M>\n    void fill_sym(M& m) {\n      typedef typename M::value_type value_type ;\n\n      int size = m.size2() ;\n\n      for (int i=0; i<size; ++i) {\n        for (int j=0; j<i; ++j) {\n          m(j,i) = random_value<value_type>();\n          m(i,j) = conj( m(j,i) ) ;\n        }\n        m(i,i) = real( random_value<value_type>() );\n      }\n    } // randomize()\n\n/** Fill a  matrix with random values\n */\n    template <typename M>\n    void fill(M& m) {\n      typedef typename M::size_type  size_type ;\n      typedef typename M::value_type value_type ;\n\n      for (size_type i=0; i<m.size1(); ++i) {\n        for (size_type j=0; j<m.size2(); ++j) {\n          m(i,j) = random_value<value_type>();\n        }\n      }\n    } // randomize()\n\n  } // Algebra namespace\n} // Siconos namespace\n\n/// @endcond\n\n#endif\n", "meta": {"hexsha": "f6167a394462448b808a511436464a9e8b175894", "size": 7779, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "externals/boost_contribs/bindings_utils.hpp", "max_stars_repo_name": "fperignon/sandbox", "max_stars_repo_head_hexsha": "649f09d6db7bbd84c2418de74eb9453c0131f070", "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/boost_contribs/bindings_utils.hpp", "max_issues_repo_name": "fperignon/sandbox", "max_issues_repo_head_hexsha": "649f09d6db7bbd84c2418de74eb9453c0131f070", "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/boost_contribs/bindings_utils.hpp", "max_forks_repo_name": "fperignon/sandbox", "max_forks_repo_head_hexsha": "649f09d6db7bbd84c2418de74eb9453c0131f070", "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": 28.1847826087, "max_line_length": 100, "alphanum_fraction": 0.5478853323, "num_tokens": 2293, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723316860482763, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.4831337754901796}}
{"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_TRIGONOMETRIC_CONSTANTS_INVPIO_2_HPP_INCLUDED\n#define NT2_TOOLBOX_TRIGONOMETRIC_CONSTANTS_INVPIO_2_HPP_INCLUDED\n/*!\n * \\file\n**/\n#include <boost/simd/sdk/constant/constant.hpp>\n#include <boost/simd/sdk/constant/register.hpp>\n\n/*!\n * \\ingroup boost_simd_constant\n * \\defgroup boost_simd_constant_invpio_2 invpio_2 constant\n *\n * \\par Description\n * Constant Invpio_2 : \\f$\\frac1\\pi\\f$.\n *\n * \\par Header file\n *\n * \\code\n * #include <nt2/include/functions/invpio_2.hpp>\n * \\endcode\n *\n *\n * \\synopsis\n *\n * \\code\n * namespace boost::simd\n * {\n *   template <class T,class A0>\n *     meta::call<tag::_invpio_2_(A0)>::type\n *     Invpio_2();\n * }\n * \\endcode\n *\n *\n * \\param T template parameter of Invpio_2\n *\n * \\return type T value\n *\n *\n**/\n\nnamespace nt2\n{\n  namespace tag\n  {\n    // 6.36619772367581382433e-01\n    BOOST_SIMD_CONSTANT_REGISTER( Invpio_2, double\n                                , 0, 0x3f22f984\n                                , 0x3FE45F306DC9C883ll\n                                );\n  }\n\n  BOOST_SIMD_CONSTANT_IMPLEMENTATION(tag::Invpio_2, Invpio_2);\n}\n\n#endif\n", "meta": {"hexsha": "70e5d7045b5f5500e0d0611c4e02c717d1f3f89e", "size": 1608, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/trigonometric/include/nt2/toolbox/trigonometric/constants/invpio_2.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/constants/invpio_2.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/constants/invpio_2.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": 24.7384615385, "max_line_length": 80, "alphanum_fraction": 0.5671641791, "num_tokens": 431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943805178139, "lm_q2_score": 0.6723316860482762, "lm_q1q2_score": 0.48313377143835834}}
{"text": "#include \"viscosity3d.h\"\n#include \"array3.h\"\n//#include \"sparse/sparsematrix.h\"\n//#include \"sparse/cgsolver.h\"\n#include \"pcgsolver/pcg_solver.h\"\n#include <fstream>\n#include <cmath>\n//#include \"wallclocktime.h\"\n\n//#include <Eigen/Sparse>\n\n//include ViennaCL stuff for multithreaded (OpenMP) iterative solvers\n/*\n#define VIENNACL_WITH_EIGEN 1\n\n#include \"viennacl/linalg/ilu.hpp\"\n#include \"viennacl/linalg/cg.hpp\"\n#include \"viennacl/linalg/bicgstab.hpp\"\n#include \"viennacl/linalg/gmres.hpp\"\n#include \"viennacl/linalg/norm_2.hpp\"\n#include \"viennacl/linalg/prod.hpp\"\n*/\n\nstatic int u_ind(int i, int j, int k, int nx, int ny) {\n   return i + j*(nx + 1) + k*(nx + 1)*ny;\n}\n\nstatic int v_ind(int i, int j, int k, int nx, int ny, int nz){\n   return i + j*nx + k*nx*(ny + 1) + (nx + 1)*ny*nz;\n}\n\nstatic int w_ind(int i, int j, int k, int nx, int ny, int nz){\n   return i + j*nx + k*nx*ny + (nx + 1)*ny*nz + nx*(ny + 1)*nz;\n}\n\nArray3c u_state;//(nx+1,ny,nz,0);\nArray3c v_state;//(nx,ny+1,nz,0);\nArray3c w_state;//(nx,ny,nz+1,0);\n\n\nSparseMatrixd matrix;//(dim,dim,15);\nSparseMatrixd matrix2;//(dim,dim\nstd::vector<double> rhs;//(dim);\nstd::vector<double> soln;//(dim);\n\nvoid advance_viscosity_implicit_weighted(Array3f& u, Array3f& v, Array3f& w,\n   const Array3f& vol_u, const Array3f& vol_v, const Array3f& vol_w,\n   const Array3f& vol_c, const Array3f& vol_ex, const Array3f& vol_ey, const Array3f& vol_ez,\n   const Array3f& solid_phi,\n   const Array3f& viscosity, float dt, float dx) {\n   float over_dx = 1.0f / dx;\n   int nx = solid_phi.ni;\n   int ny = solid_phi.nj;\n   int nz = solid_phi.nk;\n   printf(\"Creating state arrays.\\n\");\n   std::cout << \"Phi-size:\" << nx << \" \" << ny << \" \" << nz << std::endl;\n   int dim = (nx + 1)*ny*nz + nx*(ny + 1)*nz + nx*ny*(nz + 1);\n   if (u_state.ni != u.ni) {\n      printf(\"Creating matrices and vectors.\\n\");\n      u_state.resize(nx + 1, ny, nz);\n      v_state.resize(nx, ny + 1, nz);\n      w_state.resize(nx, ny, nz + 1);\n      matrix.resize(dim);\n      matrix2.resize(dim);\n      rhs.resize(dim);\n      soln.resize(dim);\n      printf(\"Done that for good.\");\n   }\n\n   u_state.assign(0);\n   v_state.assign(0);\n   w_state.assign(0);\n   matrix.zero();\n   //matrix2.zero();\n   rhs.assign(dim, 0);\n   soln.assign(dim, 0);\n\n\n\n   const int SOLID = 3;\n   const int FLUID = 2;\n   //const int AIR = 1;\n\n   //check if interpolated velocity positions are inside solid\n   for (int k = 0; k < nz; ++k) for (int j = 0; j < ny; ++j) for (int i = 0; i < nx + 1; ++i) {\n      if (i - 1 < 0 || i >= nx || solid_phi(i - 1, j, k) + solid_phi(i, j, k) <= 0)\n         u_state(i, j, k) = SOLID;\n      else\n         u_state(i, j, k) = FLUID;\n   }\n\n   for (int k = 0; k < nz; ++k) for (int j = 0; j < ny + 1; ++j) for (int i = 0; i < nx; ++i) {\n      if (j - 1 < 0 || j >= ny || solid_phi(i, j - 1, k) + solid_phi(i, j, k) <= 0)\n         v_state(i, j, k) = SOLID;\n      else\n         v_state(i, j, k) = FLUID;\n   }\n\n   for (int k = 0; k < nz + 1; ++k) for (int j = 0; j < ny; ++j) for (int i = 0; i < nx; ++i) {\n      if (k - 1 < 0 || k >= nz || solid_phi(i, j, k - 1) + solid_phi(i, j, k) <= 0)\n         w_state(i, j, k) = SOLID;\n      else\n         w_state(i, j, k) = FLUID;\n   }\n\n   float factor = dt*sqr(over_dx);\n   //u-terms\n   //2u_xx+ v_xy +uyy + u_zz + w_xz\n   printf(\"Building u-components.\\n\");\n   for (int k = 1; k < nz; ++k) for (int j = 1; j < ny; ++j) for (int i = 1; i < nx; ++i) {\n\n      if (u_state(i, j, k) == FLUID) {\n         int index = u_ind(i, j, k, nx, ny);\n\n         rhs[index] = vol_u(i, j, k)*u(i, j, k);\n         matrix.set_element(index, index, vol_u(i, j, k));\n\n         float visc_right = viscosity(i, j, k);\n         float visc_left = viscosity(i - 1, j, k);\n         float vol_right = vol_c(i, j, k);\n         float vol_left = vol_c(i - 1, j, k);\n\n         float visc_top = 0.25f*(viscosity(i - 1, j + 1, k) + viscosity(i - 1, j, k) + viscosity(i, j + 1, k) + viscosity(i, j, k));\n         float visc_bottom = 0.25f*(viscosity(i - 1, j, k) + viscosity(i - 1, j - 1, k) + viscosity(i, j, k) + viscosity(i, j - 1, k));\n         float vol_top = vol_ez(i, j + 1, k);\n         float vol_bottom = vol_ez(i, j, k);\n\n         float visc_front = 0.25f*(viscosity(i - 1, j, k + 1) + viscosity(i - 1, j, k) + viscosity(i, j, k + 1) + viscosity(i, j, k));\n         float visc_back = 0.25f*(viscosity(i - 1, j, k) + viscosity(i - 1, j, k - 1) + viscosity(i, j, k) + viscosity(i, j, k - 1));\n         float vol_front = vol_ey(i, j, k + 1);\n         float vol_back = vol_ey(i, j, k);\n\n         //u_x_right\n         matrix.add_to_element(index, index, 2 * factor*visc_right*vol_right);\n         if (u_state(i + 1, j, k) == FLUID) {\n            matrix.add_to_element(index, u_ind(i + 1, j, k, nx, ny), -2 * factor*visc_right*vol_right);\n         }\n         else if (u_state(i + 1, j, k) == SOLID)\n            rhs[index] -= -2 * factor*visc_right*vol_right*u(i + 1, j, k);\n\n         //u_x_left\n         matrix.add_to_element(index, index, 2 * factor*visc_left*vol_left);\n         if (u_state(i - 1, j, k) == FLUID)\n            matrix.add_to_element(index, u_ind(i - 1, j, k, nx, ny), -2 * factor*visc_left*vol_left);\n         else if (u_state(i - 1, j, k) == SOLID)\n            rhs[index] -= -2 * factor*visc_left*vol_left*u(i - 1, j, k);\n\n         //u_y_top\n         matrix.add_to_element(index, index, +factor*visc_top*vol_top);\n         if (u_state(i, j + 1, k) == FLUID)\n            matrix.add_to_element(index, u_ind(i, j + 1, k, nx, ny), -factor*visc_top*vol_top);\n         else if (u_state(i, j + 1, k) == SOLID)\n            rhs[index] -= -u(i, j + 1, k)*factor*visc_top*vol_top;\n\n         //u_y_bottom\n         matrix.add_to_element(index, index, +factor*visc_bottom*vol_bottom);\n         if (u_state(i, j - 1, k) == FLUID)\n            matrix.add_to_element(index, u_ind(i, j - 1, k, nx, ny), -factor*visc_bottom*vol_bottom);\n         else if (u_state(i, j - 1, k) == SOLID)\n            rhs[index] -= -u(i, j - 1, k)*factor*visc_bottom*vol_bottom;\n\n         //u_z_front\n         matrix.add_to_element(index, index, +factor*visc_front*vol_front);\n         if (u_state(i, j, k + 1) == FLUID)\n            matrix.add_to_element(index, u_ind(i, j, k + 1, nx, ny), -factor*visc_front*vol_front);\n         else if (u_state(i, j, k + 1) == SOLID)\n            rhs[index] -= -u(i, j, k + 1)*factor*visc_front*vol_front;\n\n         //u_z_back\n         matrix.add_to_element(index, index, +factor*visc_back*vol_back);\n         if (u_state(i, j, k - 1) == FLUID)\n            matrix.add_to_element(index, u_ind(i, j, k - 1, nx, ny), -factor*visc_back*vol_back);\n         else if (u_state(i, j, k - 1) == SOLID)\n            rhs[index] -= -u(i, j, k - 1)*factor*visc_back*vol_back;\n\n         //v_x_top\n         if (v_state(i, j + 1, k) == FLUID)\n            matrix.add_to_element(index, v_ind(i, j + 1, k, nx, ny, nz), -factor*visc_top*vol_top);\n         else if (v_state(i, j + 1, k) == SOLID)\n            rhs[index] -= -v(i, j + 1, k)*factor*visc_top*vol_top;\n\n         if (v_state(i - 1, j + 1, k) == FLUID)\n            matrix.add_to_element(index, v_ind(i - 1, j + 1, k, nx, ny, nz), factor*visc_top*vol_top);\n         else if (v_state(i - 1, j + 1, k) == SOLID)\n            rhs[index] -= v(i - 1, j + 1, k)*factor*visc_top*vol_top;\n\n         //v_x_bottom\n         if (v_state(i, j, k) == FLUID)\n            matrix.add_to_element(index, v_ind(i, j, k, nx, ny, nz), +factor*visc_bottom*vol_bottom);\n         else if (v_state(i, j, k) == SOLID)\n            rhs[index] -= v(i, j, k)*factor*visc_bottom*vol_bottom;\n\n         if (v_state(i - 1, j, k) == FLUID)\n            matrix.add_to_element(index, v_ind(i - 1, j, k, nx, ny, nz), -factor*visc_bottom*vol_bottom);\n         else if (v_state(i - 1, j, k) == SOLID)\n            rhs[index] -= -v(i - 1, j, k)*factor*visc_bottom*vol_bottom;\n\n         //w_x_front\n         if (w_state(i, j, k + 1) == FLUID)\n            matrix.add_to_element(index, w_ind(i, j, k + 1, nx, ny, nz), -factor*visc_front*vol_front);\n         else if (w_state(i, j, k + 1) == SOLID)\n            rhs[index] -= -w(i, j, k + 1)*factor*visc_front*vol_front;\n\n         if (w_state(i - 1, j, k + 1) == FLUID)\n            matrix.add_to_element(index, w_ind(i - 1, j, k + 1, nx, ny, nz), factor*visc_front*vol_front);\n         else if (w_state(i - 1, j, k + 1) == SOLID)\n            rhs[index] -= w(i - 1, j, k + 1)*factor*visc_front*vol_front;\n\n         //w_x_back\n         if (w_state(i, j, k) == FLUID)\n            matrix.add_to_element(index, w_ind(i, j, k, nx, ny, nz), +factor*visc_back*vol_back);\n         else if (w_state(i, j, k) == SOLID)\n            rhs[index] -= w(i, j, k)*factor*visc_back*vol_back;\n\n         if (w_state(i - 1, j, k) == FLUID)\n            matrix.add_to_element(index, w_ind(i - 1, j, k, nx, ny, nz), -factor*visc_back*vol_back);\n         else if (w_state(i - 1, j, k) == SOLID)\n            rhs[index] -= -w(i - 1, j, k)*factor*visc_back*vol_back;\n      }\n   }\n\n   //v-terms\n   //vxx + 2vyy + vzz + u_yx + w_yz\n   printf(\"Building v-components.\\n\");\n   for (int k = 1; k < nz; ++k) for (int j = 1; j < ny; ++j) for (int i = 1; i < nx; ++i) {\n      if (v_state(i, j, k) == FLUID) {\n         int index = v_ind(i, j, k, nx, ny, nz);\n\n         rhs[index] = vol_v(i, j, k)*v(i, j, k);\n         matrix.set_element(index, index, vol_v(i, j, k));\n\n         float visc_right = 0.25f*(viscosity(i, j - 1, k) + viscosity(i + 1, j - 1, k) + viscosity(i, j, k) + viscosity(i + 1, j, k));\n         float visc_left = 0.25f*(viscosity(i, j - 1, k) + viscosity(i - 1, j - 1, k) + viscosity(i, j, k) + viscosity(i - 1, j, k));\n         float vol_right = vol_ez(i + 1, j, k);\n         float vol_left = vol_ez(i, j, k);\n\n         float visc_top = viscosity(i, j, k);\n         float visc_bottom = viscosity(i, j - 1, k);\n         float vol_top = vol_c(i, j, k);\n         float vol_bottom = vol_c(i, j - 1, k);\n\n         float visc_front = 0.25f*(viscosity(i, j - 1, k) + viscosity(i, j - 1, k + 1) + viscosity(i, j, k) + viscosity(i, j, k + 1));\n         float visc_back = 0.25f*(viscosity(i, j - 1, k) + viscosity(i, j - 1, k - 1) + viscosity(i, j, k) + viscosity(i, j, k - 1));\n         float vol_front = vol_ex(i, j, k + 1);\n         float vol_back = vol_ex(i, j, k);\n\n         //v_x_right\n         matrix.add_to_element(index, index, +factor*visc_right*vol_right);\n         if (v_state(i + 1, j, k) == FLUID)\n            matrix.add_to_element(index, v_ind(i + 1, j, k, nx, ny, nz), -factor*visc_right*vol_right);\n         else if (v_state(i + 1, j, k) == SOLID)\n            rhs[index] -= -v(i + 1, j, k)*factor*visc_right*vol_right;\n\n         //v_x_left\n         matrix.add_to_element(index, index, +factor*visc_left*vol_left);\n         if (v_state(i - 1, j, k) == FLUID)\n            matrix.add_to_element(index, v_ind(i - 1, j, k, nx, ny, nz), -factor*visc_left*vol_left);\n         else if (v_state(i - 1, j, k) == SOLID)\n            rhs[index] -= -v(i - 1, j, k)*factor*visc_left*vol_left;\n\n         //vy_top\n         matrix.add_to_element(index, index, +2 * factor*visc_top*vol_top);\n         if (v_state(i, j + 1, k) == FLUID)\n            matrix.add_to_element(index, v_ind(i, j + 1, k, nx, ny, nz), -2 * factor*visc_top*vol_top);\n         else if (v_state(i, j + 1, k) == SOLID)\n            rhs[index] -= -2 * factor*visc_top*vol_top*v(i, j + 1, k);\n\n         //vy_bottom\n         matrix.add_to_element(index, index, +2 * factor*visc_bottom*vol_bottom);\n         if (v_state(i, j - 1, k) == FLUID)\n            matrix.add_to_element(index, v_ind(i, j - 1, k, nx, ny, nz), -2 * factor*visc_bottom*vol_bottom);\n         else if (v_state(i, j - 1, k) == SOLID)\n            rhs[index] -= -2 * factor*visc_bottom*vol_bottom*v(i, j - 1, k);\n\n         //v_z_front\n         matrix.add_to_element(index, index, +factor*visc_front*vol_front);\n         if (v_state(i, j, k + 1) == FLUID)\n            matrix.add_to_element(index, v_ind(i, j, k + 1, nx, ny, nz), -factor*visc_front*vol_front);\n         else if (v_state(i, j, k + 1) == SOLID)\n            rhs[index] -= -v(i, j, k + 1)*factor*visc_front*vol_front;\n\n         //v_z_back\n         matrix.add_to_element(index, index, +factor*visc_back*vol_back);\n         if (v_state(i, j, k - 1) == FLUID)\n            matrix.add_to_element(index, v_ind(i, j, k - 1, nx, ny, nz), -factor*visc_back*vol_back);\n         else if (v_state(i, j, k - 1) == SOLID)\n            rhs[index] -= -v(i, j, k - 1)*factor*visc_back*vol_back;\n\n         //u_y_right\n         if (u_state(i + 1, j, k) == FLUID)\n            matrix.add_to_element(index, u_ind(i + 1, j, k, nx, ny), -factor*visc_right*vol_right);\n         else if (u_state(i + 1, j, k) == SOLID)\n            rhs[index] -= -u(i + 1, j, k)*factor*visc_right*vol_right;\n\n         if (u_state(i + 1, j - 1, k) == FLUID)\n            matrix.add_to_element(index, u_ind(i + 1, j - 1, k, nx, ny), factor*visc_right*vol_right);\n         else if (u_state(i + 1, j - 1, k) == SOLID)\n            rhs[index] -= u(i + 1, j - 1, k)*factor*visc_right*vol_right;\n\n         //u_y_left\n         if (u_state(i, j, k) == FLUID)\n            matrix.add_to_element(index, u_ind(i, j, k, nx, ny), factor*visc_left*vol_left);\n         else if (u_state(i, j, k) == SOLID)\n            rhs[index] -= u(i, j, k)*factor*visc_left*vol_left;\n\n         if (u_state(i, j - 1, k) == FLUID)\n            matrix.add_to_element(index, u_ind(i, j - 1, k, nx, ny), -factor*visc_left*vol_left);\n         else if (u_state(i, j - 1, k) == SOLID)\n            rhs[index] -= -u(i, j - 1, k)*factor*visc_left*vol_left;\n\n         //w_y_front\n         if (w_state(i, j, k + 1) == FLUID)\n            matrix.add_to_element(index, w_ind(i, j, k + 1, nx, ny, nz), -factor*visc_front*vol_front);\n         else if (w_state(i, j, k + 1) == SOLID)\n            rhs[index] -= -w(i, j, k + 1)*factor*visc_front*vol_front;\n\n         if (w_state(i, j - 1, k + 1) == FLUID)\n            matrix.add_to_element(index, w_ind(i, j - 1, k + 1, nx, ny, nz), factor*visc_front*vol_front);\n         else if (w_state(i, j - 1, k + 1) == SOLID)\n            rhs[index] -= w(i, j - 1, k + 1)*factor*visc_front*vol_front;\n\n         //w_y_back\n         if (w_state(i, j, k) == FLUID)\n            matrix.add_to_element(index, w_ind(i, j, k, nx, ny, nz), factor*visc_back*vol_back);\n         else if (w_state(i, j, k) == SOLID)\n            rhs[index] -= w(i, j, k)*factor*visc_back*vol_back;\n\n         if (w_state(i, j - 1, k) == FLUID)\n            matrix.add_to_element(index, w_ind(i, j - 1, k, nx, ny, nz), -factor*visc_back*vol_back);\n         else if (w_state(i, j - 1, k) == SOLID)\n            rhs[index] -= -w(i, j - 1, k)*factor*visc_back*vol_back;\n      }\n   }\n\n   //w-terms\n   //wxx+ wyy+ 2wzz + u_zx + v_zy\n   printf(\"Building w-components.\\n\");\n   for (int k = 1; k < nz; ++k) for (int j = 1; j < ny; ++j) for (int i = 1; i < nx; ++i) {\n      if (w_state(i, j, k) == FLUID) {\n         int index = w_ind(i, j, k, nx, ny, nz);\n         rhs[index] = vol_w(i, j, k)*w(i, j, k);\n         matrix.set_element(index, index, vol_w(i, j, k));\n\n         float visc_right = 0.25f*(viscosity(i, j, k) + viscosity(i, j, k - 1) + viscosity(i + 1, j, k) + viscosity(i + 1, j, k - 1));\n         float visc_left = 0.25f*(viscosity(i, j, k) + viscosity(i, j, k - 1) + viscosity(i - 1, j, k) + viscosity(i - 1, j, k - 1));\n         float vol_right = vol_ey(i + 1, j, k);\n         float vol_left = vol_ey(i, j, k);\n\n         float visc_top = 0.25f*(viscosity(i, j, k) + viscosity(i, j, k - 1) + viscosity(i, j + 1, k) + viscosity(i, j + 1, k - 1));;\n         float visc_bottom = 0.25f*(viscosity(i, j, k) + viscosity(i, j, k - 1) + viscosity(i, j - 1, k) + viscosity(i, j - 1, k - 1));;\n         float vol_top = vol_ex(i, j + 1, k);\n         float vol_bottom = vol_ex(i, j, k);\n\n         float visc_front = viscosity(i, j, k);\n         float visc_back = viscosity(i, j, k - 1);\n         float vol_front = vol_c(i, j, k);\n         float vol_back = vol_c(i, j, k - 1);\n\n         //w_x_right\n         matrix.add_to_element(index, index, +factor*visc_right*vol_right);\n         if (w_state(i + 1, j, k) == FLUID)\n            matrix.add_to_element(index, w_ind(i + 1, j, k, nx, ny, nz), -factor*visc_right*vol_right);\n         else if (w_state(i + 1, j, k) == SOLID)\n            rhs[index] -= -factor*visc_right*vol_right*w(i + 1, j, k);\n\n         //w_x_left\n         matrix.add_to_element(index, index, factor*visc_left*vol_left);\n         if (w_state(i - 1, j, k) == FLUID)\n            matrix.add_to_element(index, w_ind(i - 1, j, k, nx, ny, nz), -factor*visc_left*vol_left);\n         else if (w_state(i - 1, j, k) == SOLID)\n            rhs[index] -= -factor*visc_left*vol_left*w(i - 1, j, k);\n\n         //w_y_top\n         matrix.add_to_element(index, index, +factor*visc_top*vol_top);\n         if (w_state(i, j + 1, k) == FLUID)\n            matrix.add_to_element(index, w_ind(i, j + 1, k, nx, ny, nz), -factor*visc_top*vol_top);\n         else if (w_state(i, j + 1, k) == SOLID)\n            rhs[index] -= -factor*visc_top*vol_top*w(i, j + 1, k);\n\n         //w_y_bottom\n         matrix.add_to_element(index, index, factor*visc_bottom*vol_bottom);\n         if (w_state(i, j - 1, k) == FLUID)\n            matrix.add_to_element(index, w_ind(i, j - 1, k, nx, ny, nz), -factor*visc_bottom*vol_bottom);\n         else if (w_state(i, j - 1, k) == SOLID)\n            rhs[index] -= -factor*visc_bottom*vol_bottom*w(i, j - 1, k);\n\n         //w_z_front\n         matrix.add_to_element(index, index, +2 * factor*visc_front*vol_front);\n         if (w_state(i, j, k + 1) == FLUID)\n            matrix.add_to_element(index, w_ind(i, j, k + 1, nx, ny, nz), -2 * factor*visc_front*vol_front);\n         else if (w_state(i, j, k + 1) == SOLID)\n            rhs[index] -= -2 * factor*visc_front*vol_front*w(i, j, k + 1);\n\n         //w_z_back\n         matrix.add_to_element(index, index, +2 * factor*visc_back*vol_back);\n         if (w_state(i, j, k - 1) == FLUID)\n            matrix.add_to_element(index, w_ind(i, j, k - 1, nx, ny, nz), -2 * factor*visc_back*vol_back);\n         else if (w_state(i, j, k - 1) == SOLID)\n            rhs[index] -= -2 * factor*visc_back*vol_back*w(i, j, k - 1);\n\n         //u_z_right\n         if (u_state(i + 1, j, k) == FLUID)\n            matrix.add_to_element(index, u_ind(i + 1, j, k, nx, ny), -factor*visc_right*vol_right);\n         else if (u_state(i + 1, j, k) == SOLID)\n            rhs[index] -= -u(i + 1, j, k)*factor*visc_right*vol_right;\n\n         if (u_state(i + 1, j, k - 1) == FLUID)\n            matrix.add_to_element(index, u_ind(i + 1, j, k - 1, nx, ny), factor*visc_right*vol_right);\n         else if (u_state(i + 1, j, k - 1) == SOLID)\n            rhs[index] -= u(i + 1, j, k - 1)*factor*visc_right*vol_right;\n\n         //u_z_left\n         if (u_state(i, j, k) == FLUID)\n            matrix.add_to_element(index, u_ind(i, j, k, nx, ny), factor*visc_left*vol_left);\n         else if (u_state(i, j, k) == SOLID)\n            rhs[index] -= u(i, j, k)*factor*visc_left*vol_left;\n\n         if (u_state(i, j, k - 1) == FLUID)\n            matrix.add_to_element(index, u_ind(i, j, k - 1, nx, ny), -factor*visc_left*vol_left);\n         else if (u_state(i, j, k - 1) == SOLID)\n            rhs[index] -= -u(i, j, k - 1)*factor*visc_left*vol_left;\n\n         //v_z_top\n         if (v_state(i, j + 1, k) == FLUID)\n            matrix.add_to_element(index, v_ind(i, j + 1, k, nx, ny, nz), -factor*visc_top*vol_top);\n         else if (v_state(i, j + 1, k) == SOLID)\n            rhs[index] -= -v(i, j + 1, k)*factor*visc_top*vol_top;\n\n         if (v_state(i, j + 1, k - 1) == FLUID)\n            matrix.add_to_element(index, v_ind(i, j + 1, k - 1, nx, ny, nz), factor*visc_top*vol_top);\n         else if (v_state(i, j + 1, k - 1) == SOLID)\n            rhs[index] -= v(i, j + 1, k - 1)*factor*visc_top*vol_top;\n\n         //v_z_bottom\n         if (v_state(i, j, k) == FLUID)\n            matrix.add_to_element(index, v_ind(i, j, k, nx, ny, nz), +factor*visc_bottom*vol_bottom);\n         else if (v_state(i, j, k) == SOLID)\n            rhs[index] -= v(i, j, k)*factor*visc_bottom*vol_bottom;\n\n         if (v_state(i, j, k - 1) == FLUID)\n            matrix.add_to_element(index, v_ind(i, j, k - 1, nx, ny, nz), -factor*visc_bottom*vol_bottom);\n         else if (v_state(i, j, k - 1) == SOLID)\n            rhs[index] -= -v(i, j, k - 1)*factor*visc_bottom*vol_bottom;\n\n      }\n   }\n\n   ////strip out near zero entries to speed this thing up!\n   //printf(\"Stripping out near-zeros.\\n\");\n   //SparseMatrixd matrix2(matrix.m,matrix.n,15);\n\n   //std::ofstream outfile(\"matrix.m\");\n   //matrix.write_matlab(outfile, \"A_mat\");\n   //outfile.close();\n\n   /*\n   std::vector<Eigen::Triplet<double> > entries;\n   Eigen::SparseMatrix<double> eigen_system(dim, dim);\n   Eigen::VectorXd eigen_rhs(dim);\n\n   //copy to eigen matrix\n   for (unsigned int row = 0; row < matrix.n; ++row){\n   for (unsigned int col = 0; col < matrix.index[row].size(); ++col) {\n   int index = matrix.index[row][col];\n   double val = matrix(row, index);\n   //if(std::abs(val) > 1e-10)\n   entries.push_back(Eigen::Triplet<double>(row, index, val));\n   //double val = matrix(row,index);\n   //if(std::abs(val) > 1e-10)\n   //   matrix2.set_element(row,index, val);\n   }\n   if (matrix.index[row].size() == 0) {\n   entries.push_back(Eigen::Triplet<double>(row, row, 1));\n   }\n   }\n   eigen_system.setFromTriplets(entries.begin(), entries.end());\n\n   double solve_start_time, solve_end_time;\n   try {\n   //try solving with ViennaCL, for a nice multithreaded change of pace.\n   std::cout << \"Running ViennaCL BiCGStab Viscosity solve.\" << std::endl;\n   //solve_start_time = get_time_in_seconds();\n\n   //copy the data\n\n   viennacl::vector<double> vcl_rhs(rhs.size()), vcl_soln(rhs.size());\n   viennacl::compressed_matrix<double> vcl_sparsemat(eigen_system.rows(), eigen_system.cols());\n\n   viennacl::copy(rhs, vcl_rhs);\n   viennacl::copy(eigen_system, vcl_sparsemat);\n   std::cout << \"..Preconditioner\\n\";\n   viennacl::linalg::ilut_tag ilut_config(20U, 0.01, false);\n   viennacl::linalg::ilut_precond< viennacl::compressed_matrix<double> > vcl_ilut(vcl_sparsemat, ilut_config);\n\n   std::cout << \"..Running solve\\n\";\n   viennacl::linalg::bicgstab_tag custom_tag(1e-10, 1000);\n   vcl_soln = viennacl::linalg::solve(vcl_sparsemat, vcl_rhs, custom_tag, vcl_ilut);\n\n   //solve_end_time = get_time_in_seconds();\n\n   viennacl::vector<double> residual(rhs.size());\n   residual = viennacl::linalg::prod(vcl_sparsemat, vcl_soln) - vcl_rhs;\n   std::cout << \"Residual: \" << viennacl::linalg::norm_2(residual) << std::endl;\n\n   viennacl::copy(vcl_soln, soln);\n   }\n   catch (...) {\n   std::cout << \"ViennaCL FAILED*****\\n\";\n   std::cout << \"ViennaCL failed, trying Eigen BiCGStab.\\n\";\n   //solve_start_time = get_time_in_seconds();\n   //iterative solver\n   Eigen::IncompleteLUT<double> precon;\n   Eigen::BiCGSTAB<Eigen::SparseMatrix<double>, Eigen::IncompleteLUT<double> > solver2;\n   solver2.compute(eigen_system);\n   solver2.setMaxIterations(1000);\n   solver2.setTolerance(1e-9);\n   Eigen::VectorXd eigen_rhs(dim);\n   for (int i = 0; i < dim; ++i) eigen_rhs[i] = rhs[i];\n\n   Eigen::VectorXd solution = solver2.solve(eigen_rhs);\n   //solve_end_time = get_time_in_seconds();\n   Eigen::VectorXd residual = eigen_system * solution - eigen_rhs;\n   std::cout << \"Residual magnitude: \" << residual.norm() << std::endl;\n   if (solver2.info() != Eigen::Success) {\n   std::cout << \"Solve failed.\\n\";\n   //assert(false);\n   //exit(1);\n   }\n   else {\n   std::cout << \"Solve succeeded!\\n\";\n   for (int i = 0; i < soln.size(); ++i) {\n   soln[i] = solution(i);\n   }\n   }\n   }\n   */\n\n\n   printf(\"Solving sparse system.\\n\");\n   PCGSolver<double> solver;\n   double res_out;\n   int iter_out;\n   solver.set_solver_parameters(1e-9, 10000, 0.97, 0.1);\n\n   printf(\"Launching CG\\n\");\n   solver.solve(matrix, rhs, soln, res_out, iter_out);\n\n   std::cout << \"Finished with residual :\" << res_out << \" after iterations: \" << iter_out << std::endl;\n\n   if (iter_out >= 1000) {\n      printf(\"\\n\\n\\n***************FAILED******************\\n\\n\\n\");\n      std::cout << \"Residual :\" << res_out << \" iterations: \" << iter_out << std::endl;\n      exit(1);\n   }\n\n\n   printf(\"Copying back.\\n\");\n   for (int k = 0; k < nz; ++k)\n   for (int j = 0; j < ny; ++j)\n   for (int i = 0; i < nx + 1; ++i) {\n      if (u_state(i, j, k) == FLUID) {\n         u(i, j, k) = (float)soln[u_ind(i, j, k, nx, ny)];\n      }\n      else {\n         u(i, j, k) = 0;\n      }\n   }\n\n   for (int k = 0; k < nz; ++k)\n   for (int j = 0; j < ny + 1; ++j)\n   for (int i = 0; i < nx; ++i) {\n      if (v_state(i, j, k) == FLUID) {\n         v(i, j, k) = (float)soln[v_ind(i, j, k, nx, ny, nz)];\n      }\n      else\n         v(i, j, k) = 0;\n   }\n\n   for (int k = 0; k < nz + 1; ++k)\n   for (int j = 0; j < ny; ++j)\n   for (int i = 0; i < nx; ++i) {\n      if (w_state(i, j, k) == FLUID) {\n         w(i, j, k) = (float)soln[w_ind(i, j, k, nx, ny, nz)];\n      }\n      else\n         w(i, j, k) = 0;\n   }\n   printf(\"Done copying back.\\n\");\n\n}\n\n", "meta": {"hexsha": "42f517f48146ce6087939487747ae3b56c95b2ce", "size": 24932, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "variational_fluids/VariationalViscosity3D/viscosity3d.cpp", "max_stars_repo_name": "OrionQuest/Nova_Examples", "max_stars_repo_head_hexsha": "482521902bc3afa7d0caefeb9ce9595456384961", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-01T18:04:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T18:04:45.000Z", "max_issues_repo_path": "variational_fluids/VariationalViscosity3D/viscosity3d.cpp", "max_issues_repo_name": "OrionQuest/Nova_Examples", "max_issues_repo_head_hexsha": "482521902bc3afa7d0caefeb9ce9595456384961", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "variational_fluids/VariationalViscosity3D/viscosity3d.cpp", "max_forks_repo_name": "OrionQuest/Nova_Examples", "max_forks_repo_head_hexsha": "482521902bc3afa7d0caefeb9ce9595456384961", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-12-30T00:49:36.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-30T00:49:36.000Z", "avg_line_length": 42.1148648649, "max_line_length": 136, "alphanum_fraction": 0.5500561527, "num_tokens": 8675, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.48307796533251823}}
{"text": "#include <iostream>\n#include <vector>\n#include <array>\n#include <functional>\n\n#include <vexcl/devlist.hpp>\n#include <vexcl/vector.hpp>\n#include <vexcl/multivector.hpp>\n#include <vexcl/generator.hpp>\n#include <vexcl/element_index.hpp>\n\n// http://headmyshoulder.github.com/odeint-v2\n#include <boost/numeric/odeint.hpp>\n\nnamespace odeint = boost::numeric::odeint;\n\ntypedef double value_type;\ntypedef vex::symbolic< value_type > sym_value;\ntypedef std::array<sym_value, 3> sym_state;\n\n// System  function for Lorenz attractor ensemble ODE.\n// [1] http://headmyshoulder.github.com/odeint-v2/doc/boost_numeric_odeint/tutorial/chaotic_systems_and_lyapunov_exponents.html\n// This is only used to record operations chain for autogenerated kernel.\nstruct sys_func\n{\n    const value_type sigma;\n    const value_type b;\n    const sym_value &R;\n\n    sys_func(value_type sigma, value_type b, const sym_value &R)\n        : sigma(sigma), b(b), R(R) {}\n\n    template <class Sig>\n    struct result {\n        typedef void type;\n    };\n\n    void operator()( const sym_state &x , sym_state &dxdt , value_type ) const\n    {\n        dxdt[0] = sigma * (x[1] - x[0]);\n        dxdt[1] = R * x[0] - x[1] - x[0] * x[2];\n        dxdt[2] = x[0] * x[1] - b * x[2];\n    }\n};\n\nint main( int argc , char **argv )\n{\n    size_t n;\n    const value_type dt = 0.01;\n    const value_type t_max = 100.0;\n\n    using namespace std;\n\n    n = argc > 1 ? atoi( argv[1] ) : 1024;\n\n    vex::Context ctx( vex::Filter::DoublePrecision && vex::Filter::Env );\n    cout << ctx << endl;\n\n    // Custom kernel body will be recorded here:\n    std::ostringstream body;\n    vex::generator::set_recorder(body);\n\n    // State types that would become kernel parameters:\n    sym_state sym_S = {\n        sym_value(sym_value::VectorParameter),\n        sym_value(sym_value::VectorParameter),\n        sym_value(sym_value::VectorParameter)\n    };\n\n    // Const kernel parameter.\n    sym_value sym_R(sym_value::VectorParameter, sym_value::Const);\n\n    /* Odeint is modern C++ library for ODE solution. We can use its collection\n     * of ODE steppers to generate effective kernel which would compute one\n     * iteration of a 4th order Runge-Kutta method. For that, we instantiate\n     * appropriate odeint stepper with vex::symbolic<double> as a value type.\n     * One iteration of the stepper would provide us with sequence of\n     * expressions suitable for generation of requiered kernel.  This technique\n     * may be used with any generic algorithms for generation of customized and\n     * effective kernels.\n     */\n    // Symbolic stepper:\n    odeint::runge_kutta4<\n            sym_state , value_type , sym_state , value_type ,\n            odeint::range_algebra , odeint::default_operations\n            > sym_stepper;\n\n    sys_func sys(10.0, 8.0 / 3.0, sym_R);\n    sym_stepper.do_step(std::ref(sys), sym_S, 0, dt);\n\n    auto kernel = vex::generator::build_kernel(ctx, \"lorenz\", body.str(),\n            sym_S[0], sym_S[1], sym_S[2], sym_R\n            );\n\n    // Real state initialization:\n    value_type Rmin = 0.1;\n    value_type Rmax = 50.0;\n    value_type dR   = (Rmax - Rmin) / (n - 1);\n\n    vex::vector<value_type> X(ctx, n);\n    vex::vector<value_type> Y(ctx, n);\n    vex::vector<value_type> Z(ctx, n);\n    vex::vector<value_type> R(ctx, n);\n\n    X = 10.0;\n    Y = 10.0;\n    Z = 10.0;\n    R = Rmin + dR * vex::element_index();\n\n    // Integration loop:\n    for(value_type t = 0; t < t_max; t += dt)\n        kernel(X, Y, Z, R);\n\n    std::vector< value_type > result( n );\n    vex::copy( X , result );\n    cout << result[0] << endl;\n}\n\n// vim: et\n", "meta": {"hexsha": "9c11307153c13098653ea3743de3f47cb3a18aab", "size": 3590, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "external_libraries/vexcl/examples/symbolic.cpp", "max_stars_repo_name": "lkusch/Kratos", "max_stars_repo_head_hexsha": "e8072d8e24ab6f312765185b19d439f01ab7b27b", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": 778.0, "max_stars_repo_stars_event_min_datetime": "2017-01-27T16:29:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T03:01:51.000Z", "max_issues_repo_path": "external_libraries/vexcl/examples/symbolic.cpp", "max_issues_repo_name": "lkusch/Kratos", "max_issues_repo_head_hexsha": "e8072d8e24ab6f312765185b19d439f01ab7b27b", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": 6634.0, "max_issues_repo_issues_event_min_datetime": "2017-01-15T22:56:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:03:36.000Z", "max_forks_repo_path": "external_libraries/vexcl/examples/symbolic.cpp", "max_forks_repo_name": "lkusch/Kratos", "max_forks_repo_head_hexsha": "e8072d8e24ab6f312765185b19d439f01ab7b27b", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": 224.0, "max_forks_repo_forks_event_min_datetime": "2017-02-07T14:12:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-06T23:09:34.000Z", "avg_line_length": 29.9166666667, "max_line_length": 127, "alphanum_fraction": 0.6448467967, "num_tokens": 1013, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085859124002, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.48303377402721287}}
{"text": "\n#include \"modules/bio_base/dna_multiseq.h\"\n#include <boost/multi_array.hpp>\n\n// 4 diffs is better than 1 insert/delete, but 5 diffs is worse\nconst int del_cost = 9;\nconst int diff_cost = 4;\n\ndna_multiseq::dna_multiseq(const dna_sequence& s1, const dna_sequence& s2)\n{\n\tint s1s = s1.size();\n\tint s2s = s2.size();\n\tboost::multi_array<int, 2> cost(boost::extents[s1.size()+1][s2.size()+1]);\n\tboost::multi_array<int, 2> dir(boost::extents[s1.size()+1][s2.size()+1]);\n\tcost[s1s][s2s] = 0;\n\tfor(int i = 0; i < s1s; i++)\n\t{\n\t\tcost[i][s2s] = del_cost;\n\t\tdir[i][s2s] = 1;\n\t}\n\tfor(int j = 1; j < s2s; j++)\n\t{\n\t\tcost[s1s][j] = del_cost;\n\t\tdir[s1s][j] = 2;\n\t}\n\tfor(int i = s1s-1; i >= 0; i--)\n\t{\n\t\tfor(int j = s2s-1; j >= 0; j--)\n\t\t{\n\t\t\tint mcost = cost[i+1][j+1] + (s1[i] != s2[j] ? diff_cost : 0);\n\t\t\tint d1cost = cost[i+1][j] + del_cost;\n\t\t\tint d2cost = cost[i][j+1] + del_cost;\n\t\t\tif (mcost <= d1cost && mcost <= d2cost)\n\t\t\t{\n\t\t\t\tdir[i][j] = 0;\n\t\t\t\tcost[i][j] = mcost;\n\t\t\t}\n\t\t\telse if (d1cost <= d2cost)\n\t\t\t{\n\t\t\t\tdir[i][j] = 1;\n\t\t\t\tcost[i][j] = d1cost;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tdir[i][j] = 2;\n\t\t\t\tcost[i][j] = d2cost;\n\t\t\t}\n\t\t}\n\t}\t\n\n\tint i = 0;\n\tint j = 0;\n\t\n\tm_seqs.resize(2);\n\tdna_del_seq& o1 = m_seqs[0];\n\tdna_del_seq& o2 = m_seqs[1];\n\t\n\twhile(i < s1s || j < s2s)\n\t{\n\t\tif (dir[i][j] == 0)\n\t\t{\n\t\t\to1.push_back(dna_del_base((char) s1[i]));\n\t\t\to2.push_back(dna_del_base((char) s2[j]));\n\t\t\ti++; j++;\n\t\t}\n\t\telse if (dir[i][j] == 1)\n\t\t{\n\t\t\to1.push_back(dna_del_base((char) s1[i]));\n\t\t\to2.push_back(dna_del_base('.'));\n\t\t\ti++;\n\t\t}\n\t\telse \n\t\t{\n\t\t\to1.push_back(dna_del_base('.'));\n\t\t\to2.push_back(dna_del_base((char) s2[j]));\n\t\t\tj++;\n\t\t}\n\t}\n}\n\nstd::string dna_multiseq::get_string(size_t which)\n{\n\tdna_del_seq& seq = m_seqs[which];\n\tstd::string out;\n\tfor(size_t i = 0; i < seq.size(); i++)\n\t\tout += (char) seq[i];\n\treturn out;\n}\n\n", "meta": {"hexsha": "6323546c729e6e3f2134b2eed923bd062af733b7", "size": 1813, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/bio_base/dna_multiseq.cpp", "max_stars_repo_name": "spiralgenetics/biograph", "max_stars_repo_head_hexsha": "33c78278ce673e885f38435384f9578bfbf9cdb8", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2021-07-14T23:32:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T16:25:15.000Z", "max_issues_repo_path": "modules/bio_base/dna_multiseq.cpp", "max_issues_repo_name": "spiralgenetics/biograph", "max_issues_repo_head_hexsha": "33c78278ce673e885f38435384f9578bfbf9cdb8", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2021-07-20T20:39:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-16T20:57:59.000Z", "max_forks_repo_path": "modules/bio_base/dna_multiseq.cpp", "max_forks_repo_name": "spiralgenetics/biograph", "max_forks_repo_head_hexsha": "33c78278ce673e885f38435384f9578bfbf9cdb8", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2021-07-15T19:38:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T19:24:56.000Z", "avg_line_length": 20.1444444444, "max_line_length": 75, "alphanum_fraction": 0.556536128, "num_tokens": 747, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4830337709366166}}
{"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_EXPONENTBITS_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_EXPONENTBITS_HPP_INCLUDED\n#include <boost/simd/detail/overload.hpp>\n\n#include <boost/simd/meta/hierarchy/simd.hpp>\n#include <boost/simd/detail/constant/maxexponent.hpp>\n#include <boost/simd/constant/nbmantissabits.hpp>\n#include <boost/simd/function/bitwise_and.hpp>\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   BOOST_DISPATCH_OVERLOAD_IF(exponentbits_\n                          , (typename A0, typename X)\n                          , (detail::is_native<X>)\n                          , bd::cpu_\n                          , bs::pack_<bd::floating_<A0>, X>\n                          )\n   {\n      using result = bd::as_integer_t<A0, signed>;\n      BOOST_FORCEINLINE result operator()( const A0& a0) const BOOST_NOEXCEPT\n      {\n        using s_type = bd::scalar_of_t<A0>;\n        using sint_type = bd::scalar_of_t<result>;\n        const sint_type me = Maxexponent<s_type>();\n        const sint_type nmb= Nbmantissabits<s_type>();\n        const result Mask =result((2*me+1)<<nmb);\n        return (bitwise_and(Mask, a0));\n      }\n   };\n\n\n} } }\n\n#endif\n\n", "meta": {"hexsha": "27b497bec87b3c810f388e2a0d85101b811c35d3", "size": 1689, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/simd/function/exponentbits.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/exponentbits.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/exponentbits.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": 34.4693877551, "max_line_length": 100, "alphanum_fraction": 0.5766725873, "num_tokens": 369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.48303377093661654}}
{"text": "/*    Copyright (c) 2010-2018, Delft University of Technology\r\n *    All rigths reserved\r\n *\r\n *    This file is part of the Tudat. Redistribution and use in source and\r\n *    binary forms, with or without modification, are permitted exclusively\r\n *    under the terms of the Modified BSD license. You should have received\r\n *    a copy of the license with this file. If not, please or visit:\r\n *    http://tudat.tudelft.nl/LICENSE.\r\n */\r\n\r\n#define BOOST_TEST_MAIN\r\n\r\n#include <string>\r\n\r\n#include <boost/make_shared.hpp>\r\n#include <boost/test/unit_test.hpp>\r\n\r\n#include \"Tudat/Mathematics/BasicMathematics/linearAlgebra.h\"\r\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/physicalConstants.h\"\r\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/orbitalElementConversions.h\"\r\n\r\n#include \"Tudat/External/SpiceInterface/spiceInterface.h\"\r\n#include \"Tudat/Mathematics/NumericalIntegrators/rungeKuttaCoefficients.h\"\r\n#include \"Tudat/Mathematics/Interpolators/lagrangeInterpolator.h\"\r\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/accelerationModel.h\"\r\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/keplerPropagator.h\"\r\n#include \"Tudat/InputOutput/basicInputOutput.h\"\r\n\r\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/orbitalElementConversions.h\"\r\n#include \"Tudat/SimulationSetup/EnvironmentSetup/body.h\"\r\n#include \"Tudat/Astrodynamics/Propagators/nBodyCowellStateDerivative.h\"\r\n#include \"Tudat/SimulationSetup/PropagationSetup/dynamicsSimulator.h\"\r\n#include \"Tudat/Mathematics/NumericalIntegrators/createNumericalIntegrator.h\"\r\n#include \"Tudat/SimulationSetup/EnvironmentSetup/createBodies.h\"\r\n#include \"Tudat/SimulationSetup/EstimationSetup/createNumericalSimulator.h\"\r\n#include \"Tudat/SimulationSetup/EnvironmentSetup/defaultBodies.h\"\r\n\r\n\r\nnamespace tudat\r\n{\r\n\r\nnamespace unit_tests\r\n{\r\n\r\n\r\n//Using declarations.\r\nusing namespace tudat::ephemerides;\r\nusing namespace tudat::interpolators;\r\nusing namespace tudat::numerical_integrators;\r\nusing namespace tudat::spice_interface;\r\nusing namespace tudat::simulation_setup;\r\nusing namespace tudat::basic_astrodynamics;\r\nusing namespace tudat::orbital_element_conversions;\r\nusing namespace tudat::propagators;\r\nusing namespace tudat;\r\n\r\nBOOST_AUTO_TEST_SUITE( test_forwards_backwards_rpopagation )\r\n\r\ntemplate< typename TimeType >\r\nstd::shared_ptr< IntegratorSettings< TimeType > > getIntegrationSettings(\r\n        const int integratorCase, const int initialTime, const bool propagateForwards )\r\n{\r\n    double initialTimeMultiplier = ( propagateForwards ? 1.0 : -1.0 );\r\n    std::shared_ptr< IntegratorSettings< TimeType > > integratorSettings;\r\n    if( integratorCase == 0 )\r\n    {\r\n        integratorSettings = std::make_shared< IntegratorSettings< TimeType > >\r\n                ( rungeKutta4, initialTime, initialTimeMultiplier * 300.0 );\r\n    }\r\n    else if( integratorCase < 5 )\r\n    {\r\n        RungeKuttaCoefficients::CoefficientSets coefficientSet = RungeKuttaCoefficients::undefinedCoefficientSet;\r\n        if( integratorCase == 1 )\r\n        {\r\n            coefficientSet = RungeKuttaCoefficients::rungeKuttaFehlberg45;\r\n        }\r\n        else if( integratorCase == 2 )\r\n        {\r\n            coefficientSet = RungeKuttaCoefficients::rungeKuttaFehlberg56;\r\n\r\n        }\r\n        else if( integratorCase == 3 )\r\n        {\r\n            coefficientSet = RungeKuttaCoefficients::rungeKuttaFehlberg78;\r\n\r\n        }\r\n        else if( integratorCase == 4 )\r\n        {\r\n            coefficientSet = RungeKuttaCoefficients::rungeKutta87DormandPrince;\r\n\r\n        }\r\n        integratorSettings = std::make_shared< RungeKuttaVariableStepSizeSettings< TimeType > >\r\n                ( initialTime, initialTimeMultiplier * 300.0, coefficientSet, 1.0E-3, 3600.0 );\r\n    }\r\n    return integratorSettings;\r\n}\r\n\r\n//! Test to ensure that forward and backward in time integration are properly and consistently performed using different\r\n//! integrators. The state of the Moon is numerically propagated forward, and the back to the original time. The test checks\r\n//! if the state at the midpoint is sufficiently close for the foprward and backward intgrations.\r\ntemplate< typename TimeType = double, typename StateScalarType = double >\r\nEigen::Matrix< StateScalarType, 6, 1 > propagateForwardBackwards( const int integratorCase )\r\n{\r\n    //Load spice kernels.\r\n    spice_interface::loadStandardSpiceKernels( );\r\n\r\n    // Define bodies in simulation.\r\n    std::vector< std::string > bodyNames;\r\n    bodyNames.push_back( \"Earth\" );\r\n    bodyNames.push_back( \"Moon\" );\r\n    bodyNames.push_back( \"Sun\" );\r\n    bodyNames.push_back( \"Mars\" );\r\n    bodyNames.push_back( \"Venus\" );\r\n\r\n    // Specify initial time\r\n    double initialEphemerisTime = 1.0E7;\r\n    double finalEphemerisTime = initialEphemerisTime + 86400.0;\r\n    double buffer = 3600.0;\r\n\r\n    // Create bodies needed in simulation\r\n    std::map< std::string, std::shared_ptr< BodySettings > > bodySettings =\r\n            getDefaultBodySettings( bodyNames, initialEphemerisTime - 2.0 * buffer, finalEphemerisTime + 2.0 * buffer );\r\n    std::dynamic_pointer_cast< InterpolatedSpiceEphemerisSettings >( bodySettings[ \"Moon\" ]->ephemerisSettings )->\r\n            resetFrameOrigin( \"Earth\" );\r\n    NamedBodyMap bodyMap = createBodies( bodySettings );\r\n    setGlobalFrameBodyEphemerides( bodyMap, \"Earth\", \"ECLIPJ2000\" );\r\n\r\n    // Set accelerations between bodies that are to be taken into account.\r\n    SelectedAccelerationMap accelerationMap;\r\n    std::map< std::string, std::vector< std::shared_ptr< AccelerationSettings > > > accelerationsOfMoon;\r\n    accelerationsOfMoon[ \"Earth\" ].push_back( std::make_shared< AccelerationSettings >( central_gravity ) );\r\n    accelerationsOfMoon[ \"Sun\" ].push_back( std::make_shared< AccelerationSettings >( central_gravity ) );\r\n    accelerationMap[ \"Moon\" ] = accelerationsOfMoon;\r\n\r\n    // Propagate the moon only\r\n    std::vector< std::string > bodiesToIntegrate;\r\n    bodiesToIntegrate.push_back( \"Moon\" );\r\n    std::vector< std::string > centralBodies;\r\n    centralBodies.push_back( \"Earth\" );\r\n\r\n    // Define settings for numerical integrator.\r\n    std::shared_ptr< IntegratorSettings< TimeType > > integratorSettings = getIntegrationSettings< TimeType >(\r\n                integratorCase, initialEphemerisTime, true );\r\n\r\n    // Propagate forwards\r\n    {\r\n\r\n\r\n        // Create acceleration models and propagation settings.\r\n        Eigen::Matrix< StateScalarType, 6, 1  > systemInitialState =\r\n                spice_interface::getBodyCartesianStateAtEpoch(\r\n                    bodiesToIntegrate[ 0 ], centralBodies[ 0 ], \"ECLIPJ2000\", \"NONE\", initialEphemerisTime ).\r\n                template cast< StateScalarType >( );\r\n        AccelerationMap accelerationModelMap = createAccelerationModelsMap(\r\n                    bodyMap, accelerationMap, bodiesToIntegrate, centralBodies );\r\n        std::shared_ptr< TranslationalStatePropagatorSettings< StateScalarType > > propagatorSettings =\r\n                std::make_shared< TranslationalStatePropagatorSettings< StateScalarType > >\r\n                ( centralBodies, accelerationModelMap, bodiesToIntegrate, systemInitialState, finalEphemerisTime + buffer );\r\n\r\n        // Create dynamics simulation object.\r\n        SingleArcDynamicsSimulator< StateScalarType, TimeType > dynamicsSimulator(\r\n                    bodyMap, integratorSettings, propagatorSettings, true, true, true );\r\n    }\r\n\r\n    double testTime = initialEphemerisTime + ( finalEphemerisTime - initialEphemerisTime ) / 2.0;\r\n    Eigen::Vector6d forwardState = bodyMap.at( \"Moon\" )->getEphemeris( )->getCartesianState( testTime );\r\n\r\n    // Re-define settings for numerical integrator.\r\n    integratorSettings = getIntegrationSettings< TimeType >( integratorCase, finalEphemerisTime, false );\r\n\r\n    // Propagate backwards\r\n    {\r\n        // Create acceleration models and propagation settings.\r\n        Eigen::Matrix< StateScalarType, 6, 1  > systemInitialState =\r\n                spice_interface::getBodyCartesianStateAtEpoch(\r\n                    bodiesToIntegrate[ 0 ], centralBodies[ 0 ], \"ECLIPJ2000\", \"NONE\", finalEphemerisTime ).\r\n                template cast< StateScalarType >( );\r\n        AccelerationMap accelerationModelMap = createAccelerationModelsMap(\r\n                    bodyMap, accelerationMap, bodiesToIntegrate, centralBodies );\r\n        std::shared_ptr< TranslationalStatePropagatorSettings< StateScalarType > > propagatorSettings =\r\n                std::make_shared< TranslationalStatePropagatorSettings< StateScalarType > >\r\n                ( centralBodies, accelerationModelMap, bodiesToIntegrate, systemInitialState, initialEphemerisTime - buffer );\r\n\r\n        // Create dynamics simulation object.\r\n        SingleArcDynamicsSimulator< StateScalarType, TimeType > dynamicsSimulator(\r\n                    bodyMap, integratorSettings, propagatorSettings, true, true, true );\r\n    }\r\n\r\n    Eigen::Vector6d backwardState = bodyMap.at( \"Moon\" )->getEphemeris( )->getCartesianState( testTime );\r\n\r\n    return forwardState - backwardState;\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE( testCowellPropagatorKeplerCompare )\r\n{\r\n    for( unsigned int j = 0; j < 5; j++ )\r\n    {\r\n        Eigen::Vector6d stateDifference = propagateForwardBackwards< double, double >( j );\r\n        for( int i = 0; i < 3; i++ )\r\n        {\r\n            BOOST_CHECK_SMALL( std::fabs( stateDifference( i ) ), 0.1 );\r\n            BOOST_CHECK_SMALL( std::fabs( stateDifference( i + 3 ) ), 1.0E-4 );\r\n        }\r\n    }\r\n}\r\n\r\nBOOST_AUTO_TEST_SUITE_END( )\r\n\r\n\r\n}\r\n\r\n}\r\n", "meta": {"hexsha": "c49827df5fba49642ec10b6846bb38cce41d2435", "size": 9489, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/Propagators/UnitTests/unitTestForwardsBackwardsIntegration.cpp", "max_stars_repo_name": "J-Westin/tudat", "max_stars_repo_head_hexsha": "82ebe9e6e2dd51d0688b77960e62e980e6b8bcb8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tudat/Astrodynamics/Propagators/UnitTests/unitTestForwardsBackwardsIntegration.cpp", "max_issues_repo_name": "J-Westin/tudat", "max_issues_repo_head_hexsha": "82ebe9e6e2dd51d0688b77960e62e980e6b8bcb8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tudat/Astrodynamics/Propagators/UnitTests/unitTestForwardsBackwardsIntegration.cpp", "max_forks_repo_name": "J-Westin/tudat", "max_forks_repo_head_hexsha": "82ebe9e6e2dd51d0688b77960e62e980e6b8bcb8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.5492957746, "max_line_length": 127, "alphanum_fraction": 0.7058699547, "num_tokens": 2299, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.48303377093661654}}
{"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/Shapes/InertialMoments.h\"\n\n#include \"Molassembler/Shapes/CoordinateSystemTransformation.h\"\n#include \"Molassembler/Shapes/ContinuousMeasures.h\"\n#include <Eigen/Eigenvalues>\n\n#include \"Molassembler/Temple/Functional.h\"\n#include \"Molassembler/Temple/Adaptors/Iota.h\"\n\nnamespace Scine {\nnamespace Molassembler {\nnamespace Shapes {\nnamespace Detail {\n\n//! Determine degeneracy of intertial moments\nunsigned degeneracy(const Eigen::Vector3d& inertialMoments) {\n  constexpr double degeneracyEpsilon = 0.05;\n  unsigned mdeg = 0;\n  if(\n    std::fabs(\n      (inertialMoments(2) - inertialMoments(1)) / inertialMoments(2)\n    ) <= degeneracyEpsilon\n  ) {\n    mdeg += 1;\n  }\n  if(\n    std::fabs(\n      (inertialMoments(1) - inertialMoments(0)) / inertialMoments(2)\n    ) <= degeneracyEpsilon\n  ) {\n    mdeg += 2;\n  }\n\n  return 1 + (mdeg + 1) / 2;\n}\n\n} // namespace Detail\n\nInertialMoments principalInertialMoments(\n  const InertialPositionsType& normalizedPositions\n) {\n  Eigen::Matrix3d inertialMatrix = Eigen::Matrix3d::Zero(3, 3);\n  const unsigned N = normalizedPositions.cols();\n\n  for(unsigned i = 0; i < N; ++i) {\n    const auto& vec = normalizedPositions.col(i);\n    inertialMatrix(0, 0) += vec.y() * vec.y() + vec.z() * vec.z();\n    inertialMatrix(1, 1) += vec.x() * vec.x() + vec.z() * vec.z();\n    inertialMatrix(2, 2) += vec.x() * vec.x() + vec.y() * vec.y();\n    inertialMatrix(1, 0) -= vec.x() * vec.y(); // xy\n    inertialMatrix(2, 0) -= vec.x() * vec.z(); // xz\n    inertialMatrix(2, 1) -= vec.y() * vec.z(); // yz\n  }\n\n  // Decompose the inertial matrix to get principal axes and inertial moments\n  Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> decomposition(inertialMatrix);\n\n  InertialMoments result;\n  result.moments = decomposition.eigenvalues();\n  result.axes = decomposition.eigenvectors();\n  return result;\n}\n\nTop standardizeTop(Eigen::Ref<InertialPositionsType> normalizedPositions) {\n  const unsigned N = normalizedPositions.cols();\n  assert(N > 1);\n\n  InertialMoments moments = principalInertialMoments(normalizedPositions);\n\n  const unsigned degeneracy = Detail::degeneracy(moments.moments);\n\n  auto rotateEverything = [&](const CoordinateSystem& sourceSystem) {\n    const CoordinateSystem defaultCoordinateSystem {};\n    assert(sourceSystem.isRightHanded());\n    const auto R = rotationMatrix(sourceSystem, defaultCoordinateSystem);\n    // Rotate coordinates\n    normalizedPositions = R * normalizedPositions;\n    // Rotate inertial moment axes\n    moments.axes = R * moments.axes;\n  };\n\n  if(moments.moments(0) < 0.1 && degeneracy == 2) {\n    // The top is linear: If IA << IB = IC and IA ~ 0. We rotate IA to z\n    const CoordinateSystem inertialMomentSystem {\n      moments.axes.col(1),\n      moments.axes.col(2)\n    };\n    rotateEverything(inertialMomentSystem);\n    assert(moments.axes.col(0).cwiseAbs().isApprox(Eigen::Vector3d::UnitZ(), 1e-10));\n    return Top::Line;\n  }\n\n  if(degeneracy == 1) {\n    /* The top is asymmetric. Rotate the axis with the\n     * highest moment of inertia to coincide with z, and the one with second most\n     * to coincide with x.\n     *\n     * To better define orientation, we could look for Cn axes. This is done in\n     * another function. No need to burden this function with that here.\n     */\n    CoordinateSystem inertialMomentSystem {\n      moments.axes.col(1), // second highest becomes x\n      moments.axes.col(2).cross(moments.axes.col(1)) // y = z.cross(x)\n    };\n    assert(inertialMomentSystem.z.isApprox(moments.axes.col(2), 1e-10));\n    rotateEverything(inertialMomentSystem);\n    // Make sure rotation went as intended\n    assert(moments.axes.col(2).cwiseAbs().isApprox(Eigen::Vector3d::UnitZ(), 1e-10));\n    assert(moments.axes.col(1).cwiseAbs().isApprox(Eigen::Vector3d::UnitX(), 1e-10));\n\n    return Top::Asymmetric;\n  }\n\n  if(degeneracy == 2) {\n    /* The top is symmetric. The subsets are:\n     * - Oblate (disc): IA = IB < IC\n     * - Prolate (rugby football): IA < IB = IC\n     *\n     * We rotate the unique axis to coincide with z (it's probably the site of\n     * the highest-order Cn or Sn, and one of the degenerate axes to coincide\n     * with x. There could be a C2 on x.\n     *\n     * This is most likely rare and should occur only for largely undistorted\n     * structures. Perhaps we can flowchart point groups here?\n     */\n    // Calculate Ray's asymmetry parameter\n    const double A = 1 / moments.moments(0);\n    const double B = 1 / moments.moments(1);\n    const double C = 1 / moments.moments(2);\n    const double kappa = (2 * B - A - C) / (A - C);\n    assert(-1 <= kappa && kappa <= 1);\n    if(kappa < 0) {\n      // Prolate top. IA is unique\n      CoordinateSystem inertialMomentSystem {\n        moments.axes.col(1),\n        moments.axes.col(2)\n      };\n      rotateEverything(inertialMomentSystem);\n      assert(moments.axes.col(0).cwiseAbs().isApprox(Eigen::Vector3d::UnitZ(), 1e-10));\n      return Top::Prolate;\n    }\n\n    // Oblate top. IC is unique\n    CoordinateSystem inertialMomentSystem {\n      moments.axes.col(0),\n      moments.axes.col(1)\n    };\n    rotateEverything(inertialMomentSystem);\n    assert(moments.axes.col(2).cwiseAbs().isApprox(Eigen::Vector3d::UnitZ(), 1e-10));\n    return Top::Oblate;\n  }\n\n  assert(degeneracy == 3);\n  /* The top is spherical (IA = IB = IC).\n   *\n   * Note that there is no reason to rotate anything on the basis of the axes\n   * from the inertial moment analysis since any choice of axes gives the\n   * spherical symmetry. We can't use those to rotate the system.\n   *\n   * Rotate an arbitrary position to +z instead (good for Td\n   * and Oh octahedral, less so for Oh cubic and Ih, which should be less\n   * common)\n   */\n  unsigned selectedIndex = 0;\n  for(; selectedIndex < N; ++selectedIndex) {\n    /* As long as the position isn't close to the centroid and it's not exactly\n     * the -z vector, we can rotate it\n     */\n    if(\n      normalizedPositions.col(selectedIndex).norm() > 0.2\n      && !normalizedPositions.col(selectedIndex).normalized().isApprox(\n        -Eigen::Vector3d::UnitZ(),\n        1e-10\n      )\n    ) {\n      break;\n    }\n  }\n  assert(selectedIndex != N);\n\n  // Determine axis of rotation as sum of z and position coordinate\n  const Eigen::Vector3d rotationAxis = (\n    normalizedPositions.col(selectedIndex).normalized()\n    + Eigen::Vector3d::UnitZ()\n  ).normalized();\n  const Eigen::Matrix3d rotationMatrix = Eigen::AngleAxisd(M_PI, rotationAxis).toRotationMatrix();\n\n  // Rotate all coordinates\n  for(unsigned i = 0; i < N; ++i) {\n    normalizedPositions.col(i) = rotationMatrix * normalizedPositions.col(i);\n  }\n  // Check that everything went as planned\n  assert(normalizedPositions.col(selectedIndex).normalized().cwiseAbs().isApprox(Eigen::Vector3d::UnitZ(), 1e-10));\n\n  return Top::Spherical;\n}\n\nunsigned reorientAsymmetricTop(Eigen::Ref<InertialPositionsType> normalizedPositions) {\n  const unsigned P = normalizedPositions.cols();\n  const auto& axes = Eigen::Matrix3d::Identity();\n\n  struct AxisBest {\n    unsigned order = 1;\n    double csm = 1; // This functions much like a detection threshold below\n    unsigned axisIndex;\n\n    AxisBest(unsigned index) : axisIndex(index) {}\n\n    bool operator < (const AxisBest& other) const {\n      return order > other.order;\n    }\n  };\n\n  auto orderedAxisBest = Temple::sorted(\n    Temple::map(\n      Temple::iota<unsigned>(3),\n      [&](const unsigned axisIndex) -> AxisBest {\n        const Eigen::Vector3d axis = axes.col(axisIndex);\n        AxisBest best {axisIndex};\n        for(unsigned n = 2; n <= P; ++n) {\n          const double axisCSM = Continuous::Fixed::element(normalizedPositions, Elements::Rotation::Cn(axis, n));\n          if(axisCSM < best.csm) {\n            best.order = n;\n            best.csm = axisCSM;\n          }\n        }\n        return best;\n      }\n    )\n  );\n\n  if(orderedAxisBest.front().order > 1) {\n    /* Only mess with the coordinate frame if any sort of axis was found.\n     * We want the second-highest order axis on x, highest order axis along z,\n     * doesn't really matter if +z or -z\n     */\n    const CoordinateSystem highestOrderSystem {\n      axes.col(orderedAxisBest.at(1).axisIndex),\n      axes.col(orderedAxisBest.back().axisIndex)\n    };\n\n    normalizedPositions = rotationMatrix(highestOrderSystem, {}) * normalizedPositions;\n  }\n\n  return orderedAxisBest.front().order;\n}\n\n} // namespace Shapes\n} // namespace Molassembler\n} // namespace Scine\n", "meta": {"hexsha": "ffe960cf902fb80371d66e134f2eb1042458d762", "size": 8622, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Molassembler/Shapes/InertialMoments.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/Shapes/InertialMoments.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/Shapes/InertialMoments.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": 33.5486381323, "max_line_length": 115, "alphanum_fraction": 0.666782649, "num_tokens": 2345, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384736, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4830337647554237}}
{"text": "#include <iostream>\n#include <fstream>\n#include <string>\n#include <Eigen/Cholesky>\n#include \"../headers/autodiff.h\"\n#include <chrono>\n\nDECLARE_DIFFSCALAR_BASE();\nusing namespace std;\nusing namespace std::chrono;\nint main(int argc, char **argv)\n{\n   typedef Eigen::Matrix<double, 1, 1> Gradient;\n\n   string output_filename = argv[1];\n   cout << output_filename << endl;\n\n   typedef DScalar1<double, Gradient> DScalar;\n\n   int num_params = 4010;\n   int num_vars = 1;\n\n   Eigen::VectorXd args(num_params * num_vars);\n   Eigen::VectorXd ders(num_params * num_vars);\n\n   std::ifstream file(\"./tests/utils/params.txt\");\n   int i = 0;\n   for (std::string line; std::getline(file, line);)\n   {\n       args(i) = stod(line.c_str());\n       i++;\n   }\n   file.close();\n\n   ofstream outfile;\n   outfile.open(output_filename);\n\n   auto start = high_resolution_clock::now();\n   for (int index = 0; index < num_params; index++)\n   {\n       /* There are two independent variables */\n       DiffScalarBase::setVariableCount(1);\n\t\tDScalar k(0, args[index * 1 + 0]);\n\t\tDScalar Fx = ((k*k+3*k)-k/4)/k+k*k*k*k+k*k*(22/7*k)+k*k*k*k*k*k*k*k*k;\n\t\tders[index * 1 + 0] = Fx.getGradient()(0);\n   }\n\n   auto stop = high_resolution_clock::now();\n   auto duration = duration_cast<microseconds>(stop - start);\n   outfile << (double)duration.count() / 1000000.0 << \" \";\n   for (int i = 0; i < num_params * num_vars; i++)\n   {\n        ostringstream ss;\n        ss.precision(3);\n       ss << fixed << ders[i];\n       outfile << ss.str() << \" \";\n   }\n\n   outfile.close();\n\n   return 0;\n}", "meta": {"hexsha": "736c3c5e456b34e3d6f5a74e7321083492bda566", "size": 1551, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/utils/wenzel_single_static.cpp", "max_stars_repo_name": "jiangzhongshi/acorns-benchmark", "max_stars_repo_head_hexsha": "df5f43af90a32f4c1578cdea1f4f412237e18c75", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-24T21:24:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-24T21:24:02.000Z", "max_issues_repo_path": "tests/utils/wenzel_single_static.cpp", "max_issues_repo_name": "jiangzhongshi/acorns-benchmark", "max_issues_repo_head_hexsha": "df5f43af90a32f4c1578cdea1f4f412237e18c75", "max_issues_repo_licenses": ["MIT"], "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/utils/wenzel_single_static.cpp", "max_forks_repo_name": "jiangzhongshi/acorns-benchmark", "max_forks_repo_head_hexsha": "df5f43af90a32f4c1578cdea1f4f412237e18c75", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-24T21:22:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-24T21:22:54.000Z", "avg_line_length": 25.0161290323, "max_line_length": 72, "alphanum_fraction": 0.6189555126, "num_tokens": 439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384736, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4830337647554237}}
{"text": "\n#include \"ceiling.hpp\"\n#include \"ast.hpp\"\n#include \"parsers.hpp\"\n#include \"types.hpp\"\n#include <boost/variant.hpp>\n#include <stdexcept>\nnamespace HT\n{\n    void ceiling(PASTNode astnode, ParsersHelper& ph)\n    {\n        auto myParserHelper(ph);\n        if (astnode->ch.size()!=2)\n          throw std::runtime_error(\"ceiling can only have one parameter\");\n        auto & secondCh = *astnode->ch.rbegin();\n        ph.parse(secondCh);\n        if (secondCh->token.tokenType != Complex || ! boost::get<ComplexType>(secondCh->token.info).isReal())\n          throw std::runtime_error(\"The argument of ceiling must be real\");\n        auto cast = boost::get<ComplexType>(secondCh->token.info);\n\n        astnode->type = Simple;\n        astnode->token.tokenType = Complex;\n        if (!cast.exact())\n        astnode->token.info = ComplexType(\n                    std::ceil(\n                        cast.toinexact().getRealD()\n                        ));\n        else\n        {\n            auto rat = cast.getRealR();\n            auto ans = rat.getUp() / rat.getDown();\n            if (rat.getSign())\n              if (rat.getUp() % rat.getDown() != 0)\n                astnode->token.info = ComplexType( ans +1);\n            else\n              astnode->token.info = ComplexType(ans);\n            else\n              astnode->token.info = ComplexType( (ans).setSign(false) );\n        }\n\n        astnode->remove();\n    }\n\n}\n\n\n", "meta": {"hexsha": "978eb01672dc476f4c2cd815072db08bddbea9f1", "size": 1411, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "funs/ceiling.cpp", "max_stars_repo_name": "htfy96/htscheme", "max_stars_repo_head_hexsha": "b44c9f9672f69d9b3c2eb1c80969bcfcfec9990f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2015-07-07T01:30:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-14T10:45:01.000Z", "max_issues_repo_path": "funs/ceiling.cpp", "max_issues_repo_name": "htfy96/htscheme", "max_issues_repo_head_hexsha": "b44c9f9672f69d9b3c2eb1c80969bcfcfec9990f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "funs/ceiling.cpp", "max_forks_repo_name": "htfy96/htscheme", "max_forks_repo_head_hexsha": "b44c9f9672f69d9b3c2eb1c80969bcfcfec9990f", "max_forks_repo_licenses": ["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.0212765957, "max_line_length": 109, "alphanum_fraction": 0.5421686747, "num_tokens": 330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384736, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4830337647554237}}
{"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_GENERIC_MOD_HPP_INCLUDED\n#define BOOST_SIMD_ARITHMETIC_FUNCTIONS_GENERIC_MOD_HPP_INCLUDED\n#include <boost/simd/arithmetic/functions/mod.hpp>\n#include <boost/simd/include/functions/simd/selsub.hpp>\n#include <boost/simd/include/functions/simd/is_nez.hpp>\n#include <boost/simd/include/functions/simd/divfloor.hpp>\n#include <boost/simd/include/functions/simd/idivfloor.hpp>\n#include <boost/simd/include/functions/simd/multiplies.hpp>\n#include <boost/dispatch/attributes.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT          ( mod_, tag::cpu_\n                                    , (A0)\n                                    , (generic_<floating_<A0> >)\n                                      (generic_<floating_<A0> >)\n                                    )\n  {\n    typedef A0 result_type;\n    BOOST_FORCEINLINE BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    {\n      return selsub(boost::simd::is_nez(a1),a0,\n                    divfloor(a0,a1)*a1\n                   );\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT          ( mod_, tag::cpu_\n                                    , (A0)\n                                    , (generic_<arithmetic_<A0> >)\n                                      (generic_<arithmetic_<A0> >)\n                                    )\n  {\n    typedef A0 result_type;\n    BOOST_FORCEINLINE BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    {\n      return selsub(is_nez(a1),a0,\n                    boost::simd::multiplies(idivfloor(a0,a1), a1)\n                   );\n\n    }\n  };\n\n\n} } }\n\n#endif\n", "meta": {"hexsha": "c666f142ff69c72d127f71ded9c493c4c85c5fcc", "size": 2108, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/generic/mod.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/generic/mod.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/generic/mod.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.9824561404, "max_line_length": 80, "alphanum_fraction": 0.5232447818, "num_tokens": 454, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893353516963, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.48282628427492713}}
{"text": "#pragma once\n#ifndef __Matrix_H_\n#define __Matrix_H_\n\n#define _USE_MATH_DEFINES\n#include <math.h>\n#include <vector>\n\n\n#include <Eigen/Dense>\n\n#define P_X\t0\n#define P_Y\t1\n#define P_Z\t2\n\n#define degToRad(angleInDegrees) ((angleInDegrees) * M_PI / 180.0)\n#define radToDeg(angleInRadians) ((angleInRadians) * 180.0 / M_PI)\n\nusing namespace Eigen;\n\ntypedef struct\n{\n\tstd::vector<int> point;\n\tstd::vector<Eigen::Vector2f> point2D;\n\tstd::vector<Eigen::Vector3f> point3D;\n} sp_point;\n\nstd::vector<Vector3f> slope_3d(Vector3f alpha, Vector3f omega);\nVector3f unit_vector(Vector3f vec);\nMatrix4f coor(float roll, float pitch, float yaw, Vector3f point);\n\nstd::vector<Vector3f> slope_3d(Vector3f alpha, Vector3f omega);\nVector4f plane_vector(Vector3f a, Vector3f b, Vector3f c);\nVector3f nose_projection(Vector4f p_vector, std::vector<Vector3f> nose);\n\n#else\n#endif", "meta": {"hexsha": "3c785888856caa6778cba469e664eea0869a4d9b", "size": 854, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Pose/Inc/Matrix.hpp", "max_stars_repo_name": "hqvvr7391/Posture-Detection", "max_stars_repo_head_hexsha": "9525fbf963ea69f8062eaa7d15a64a307e6bba0e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Pose/Inc/Matrix.hpp", "max_issues_repo_name": "hqvvr7391/Posture-Detection", "max_issues_repo_head_hexsha": "9525fbf963ea69f8062eaa7d15a64a307e6bba0e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Pose/Inc/Matrix.hpp", "max_forks_repo_name": "hqvvr7391/Posture-Detection", "max_forks_repo_head_hexsha": "9525fbf963ea69f8062eaa7d15a64a307e6bba0e", "max_forks_repo_licenses": ["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.0810810811, "max_line_length": 72, "alphanum_fraction": 0.7658079625, "num_tokens": 258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.48282627390846033}}
{"text": "#ifndef INTERSIM_DATA_STATE_H\r\n#define INTERSIM_DATA_STATE_H\r\n\r\n#include <Core_Defines.h>\r\n\r\n#include <Eigen/Dense>\r\n#include <Eigen/Sparse>\r\n\r\n#include <spdlog/spdlog.h>\r\n\r\n#include <memory>\r\n#include <vector>\r\n\r\nnamespace InterSim\r\n{\r\n\ttypedef std::shared_ptr<Eigen::Matrix<scalar, Eigen::Dynamic, Eigen::Dynamic>> field;\r\n\ttypedef Eigen::SparseMatrix<scalar> sparse_matrix;\r\n}\r\n\r\n/*\r\nState\r\nThe State struct is passed around in an application to make the\r\nsimulation's state available.\r\nThe State contains all necessary system information and\r\nprovides a few utilities (pointers) to commonly used contents.\r\n*/\r\nstruct State\r\n{\r\n\tint nx;\r\n\tint ny;\r\n\tint nz;\r\n\r\n\tstd::vector<InterSim::field> data;\r\n\tstd::shared_ptr<InterSim::sparse_matrix> matrix;\r\n\r\n\t// Log\r\n\tstd::shared_ptr<spdlog::logger> log;\r\n};\r\n\r\n#endif", "meta": {"hexsha": "65baae68437f72b536ef00f242d01b636394f039", "size": 814, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "core/include/data/state.hpp", "max_stars_repo_name": "GPMueller/intersim", "max_stars_repo_head_hexsha": "35b90df011ad6c5f19b583f4f01e2388e5249f89", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-12-27T14:05:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-23T19:09:45.000Z", "max_issues_repo_path": "core/include/data/state.hpp", "max_issues_repo_name": "GPMueller/intersim", "max_issues_repo_head_hexsha": "35b90df011ad6c5f19b583f4f01e2388e5249f89", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "core/include/data/state.hpp", "max_forks_repo_name": "GPMueller/intersim", "max_forks_repo_head_hexsha": "35b90df011ad6c5f19b583f4f01e2388e5249f89", "max_forks_repo_licenses": ["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.35, "max_line_length": 87, "alphanum_fraction": 0.7248157248, "num_tokens": 189, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.737158174177441, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.4827610027391247}}
{"text": "// Demonstration of calculating Elmore delay with a graph\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 <fstream>\n\n#include <boost/graph/visitors.hpp>\n#include <boost/graph/undirected_dfs.hpp>\n#include <boost/graph/graphviz.hpp>\n#include <boost/units/systems/si/time.hpp>\n\n#include \"ckt_graph.h\"\n\n// For Elmore we need two visitors:\n// 1) To calculate total capacitance at and \"below\" each node\n// 2) To sum resistor delays to each node from a chosen input\n\ntemplate<typename Graph>\nstruct cap_summing_visitor : boost::default_dfs_visitor {\n    typedef typename boost::graph_traits<Graph>::edge_descriptor edge_t;\n    typedef typename boost::graph_traits<Graph>::vertex_descriptor vertex_t;\n\n    // This edge variant visitor returns the correct contribution for an edge\n    // to a downstream node: the value on the edge, if a capacitor, or\n    // the supplied downstream capacitance, if a resistor.\n    struct cap_summer : boost::static_visitor<capacitor_value_t> {\n        capacitor_value_t operator()(resistor_value_t const&) const {\n            return downstream_;   // count downstream, not edge\n        }\n        capacitor_value_t operator()(capacitor_value_t const& c) const {\n            return c;             // count edge but not downstream (i.e., lump to gnd)\n        }\n        cap_summer(capacitor_value_t downstream) : downstream_(downstream) {}\n    private:\n        capacitor_value_t downstream_;\n    };\n\n    void tree_edge(edge_t e, Graph const& g) {\n        // remember the predecessor so later we can avoid summing up capacitance from back edges\n        predecessors_[target(e, g)] = source(e, g);\n    }\n\n    void finish_vertex(vertex_t u, Graph const& g) {\n        // We want to sum only *downstream* capacitance\n        // However, circuits are undirected, and the downstreamness of our search\n        // is only due to the order in which we encountered vertices\n        // a \"tree edge\" is downstream, and a \"back edge\" is upstream\n\n        downstream_caps_[u] = capacitor_value_t();\n        for (auto e : boost::make_iterator_range(out_edges(u, g))) {\n            // detect back edge, i.e., an edge to an already-visited node\n            // this won't work correctly for circuits with resistive loops\n            if ((predecessors_[target(e, g)] == u) || (target(e, g) == g.gnd())) {\n                // our first time at this node, OR the node is gnd, in which case this is normal\n                capacitor_value_t contr = boost::apply_visitor(cap_summer(downstream_caps_[target(e, g)]), g[e]);\n                downstream_caps_[u] += contr;\n            }\n        }\n    }\n\n    // finish_edge never seems to get called\n\n    cap_summing_visitor(std::vector<capacitor_value_t>& capsvec)\n        : downstream_caps_(capsvec), predecessors_(capsvec.size()) {}\n\nprivate:\n    std::vector<capacitor_value_t>& downstream_caps_;\n    std::vector<vertex_t> predecessors_;\n};\n\ntypedef quantity<si::time> delay_t;\n\n// adds up delays.  To be run on filtered (R-only) graph\ntemplate<typename Graph>\nstruct delay_calculating_visitor : boost::default_dfs_visitor {\n    typedef typename boost::graph_traits<Graph>::edge_descriptor edge_t;\n    typedef typename boost::graph_traits<Graph>::vertex_descriptor vertex_t;\n\n    void start_vertex(vertex_t u, Graph const&) {\n        // this hook is called once at the beginning;\n        // we can use it to initialize the delay from the tree root\n        delays_[u] = delay_t();\n    }\n\n    struct res_summer : boost::static_visitor<resistor_value_t> {\n        resistor_value_t operator()(resistor_value_t const& r) const {\n            return r;\n        }\n        resistor_value_t operator()(capacitor_value_t const&) const {\n            assert(0);   // program bug - we should operate on a filtered graph\n            return resistor_value_t();\n        }\n    };\n\n    void tree_edge(edge_t e, Graph const& g) {\n        delays_[target(e, g)] = delays_[source(e, g)] +\n            boost::apply_visitor(res_summer(), g[e]) *\n            downstream_caps_[target(e, g)];\n    }\n\n    void back_edge(edge_t, Graph const&) {\n        // Resistive loops will break this algorithm - you could put a check here\n    }\n\n    delay_calculating_visitor(std::vector<capacitor_value_t>& capsvec,\n                              std::vector<delay_t>& delays)\n        : downstream_caps_(capsvec), delays_(delays) {}\n\nprivate:\n    std::vector<capacitor_value_t>& downstream_caps_;   // bottom-up\n    std::vector<delay_t>&          delays_;            // top-down\n};\n\nint main() {\n    using namespace boost;\n    using namespace std;\n\n    quantity<si::resistance> kohm(1.0 * units::si::kilo  * units::si::ohms);\n    quantity<si::capacitance> ff(1.0 * units::si::femto * units::si::farads);\n\n    // Coupling test case\n    ckt_graph_t coupling_test;\n    auto gnd = coupling_test.gnd();\n\n    auto vagg = add_vertex(\"vagg\", coupling_test);   // driver voltage source\n    auto n1   = add_vertex(\"n1\",   coupling_test);\n    add_edge(vagg, n1, 0.1*kohm,   coupling_test);   // driver impedance\n    auto n2   = add_vertex(\"n2\",   coupling_test);   // central node - where coupling occurs\n    add_edge(n1, n2, 1.0*kohm,     coupling_test);   // first \"pi\" model, aggressor side\n    add_edge(n1, gnd, 50.0*ff,     coupling_test);   // caps for first \"pi\"\n    add_edge(n2, gnd, 50.0*ff,     coupling_test);\n    auto n3   = add_vertex(\"n3\",   coupling_test);   // aggressor-side receiver\n    add_edge(n2, n3, 1.0*kohm,     coupling_test);   // second \"pi\" model, aggressor side\n    add_edge(n2, gnd, 50.0*ff,     coupling_test);   // caps for first \"pi\"\n    add_edge(n3, gnd, 50.0*ff,     coupling_test);\n    add_edge(n3, gnd, 20.0*ff,     coupling_test);   // aggressor side receiver load\n\n    // then the same thing over again for the victim side\n    auto vvic = add_vertex(\"vvic\", coupling_test);   // driver voltage source\n    auto n5   = add_vertex(\"n5\",   coupling_test);\n    add_edge(vvic, n5, 0.1*kohm,   coupling_test);   // driver impedance\n    auto n6   = add_vertex(\"n6\",   coupling_test);   // central node\n    add_edge(n5, n6, 1.0*kohm,     coupling_test);   // first \"pi\" model\n    add_edge(n5, gnd, 50.0*ff,     coupling_test);\n    add_edge(n6, gnd, 50.0*ff,     coupling_test);\n    auto n7   = add_vertex(\"n7\",   coupling_test);   // victim-side receiver\n    add_edge(n6, n7, 1.0*kohm,     coupling_test);   // second \"pi\" model\n    add_edge(n6, gnd, 50.0*ff,     coupling_test);\n    add_edge(n7, gnd, 50.0*ff,     coupling_test);\n    add_edge(n7, gnd, 20.0*ff,     coupling_test);   // victim side receiver load\n\n    // coupling capacitor between the two signal traces\n    add_edge(n2, n6, 100.0*ff,     coupling_test);\n\n    // debug output via Dot\n    /*\n    ofstream dbg(\"/tmp/coupling_test.dot\");\n    write_graphviz(dbg, coupling_test,\n                   make_label_writer(get(vertex_bundle, coupling_test)),\n                   make_label_writer(get(edge_bundle, coupling_test)));\n    */\n\n    // calculate Elmore delay\n    // Create visitors\n    vector<capacitor_value_t> downstream_caps(num_vertices(coupling_test));\n    cap_summing_visitor<ckt_graph_t> capvis(downstream_caps);\n\n    // undirected DFS requires edge color map\n    map<ckt_graph_t::edge_descriptor, default_color_type> edge_colors;\n    auto cpmap = make_assoc_property_map(edge_colors);\n    \n    // perform first pass and sum capacitances\n    undirected_dfs(coupling_test, edge_color_map(cpmap).visitor(capvis).root_vertex(vagg));\n\n    typedef filtered_graph<ckt_graph_t, resistors_only> resonly_graph_t;\n    resonly_graph_t res_graph(coupling_test, resistors_only(&coupling_test));\n\n    vector<delay_t>          delays(num_vertices(coupling_test));\n    delay_calculating_visitor<resonly_graph_t>\n                                     delvis(downstream_caps, delays);\n\n    // create *vertex* color map for depth_first_visit\n    auto vindex_map = typed_identity_property_map<size_t>();\n    vector<default_color_type> colorvec(num_vertices(coupling_test));   // underlying storage\n    auto cvpmap = make_iterator_property_map(colorvec.begin(), vindex_map);\n\n    depth_first_visit(res_graph, vagg, delvis, cvpmap);\n\n    cout << \"Elmore delay of aggressor net: \" << delays.at(n3) << endl;\n\n    // If you want to calculate the delay from a different node you have to recalculate\n    // both capacitance and delays starting with that new node\n}\n", "meta": {"hexsha": "e88af950984b92c937a4ef5e33c6ab232c213b61", "size": 9482, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "graph_elmore.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": "graph_elmore.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": "graph_elmore.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": 43.6958525346, "max_line_length": 113, "alphanum_fraction": 0.6827673487, "num_tokens": 2387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432182679956, "lm_q2_score": 0.6688802735722128, "lm_q1q2_score": 0.4827598012839862}}
{"text": "/**\n * @file  VolumeData.hpp\n * @author Takashi Michikawa <michiawa@acm.org>\n */\n#ifndef MI4_VOLUME_DATA_HPP\n#define MI4_VOLUME_DATA_HPP 1\n#include <cstdlib>\n#include <cstring>\n#include <fstream>\n#include <iostream>\n#include <vector>\n#include <sstream>\n#include <iomanip>\n\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n\nnamespace mi4 {\n        using Vector3d = Eigen::Vector3d;\n        using Vector3i = Eigen::Vector3i;\n        using Vector3s = Eigen::Matrix< int16_t, 3, 1 >;\n        using Point3d = Eigen::Vector3d;\n        using Point3i = Eigen::Vector3i;\n\n        class VolumeInfo {\n        private:\n                Point3i size_; ///< Global bounding box.\n                Point3d pitch_; ///< Voxel pitch.\n                Point3d origin_; ///< Origin point. Corresponding to global (0,0,0) in voxel space.\n        public:\n                explicit VolumeInfo (const Point3i& size = Point3i::Zero(), const Point3d& pitch = Point3d(1, 1, 1), const Point3d& origin = Point3d::Zero()) : size_(size), pitch_(pitch), origin_(origin)\n                {\n                }\n\n                ~VolumeInfo (void) = default;\n                VolumeInfo (const VolumeInfo& that) = default;\n                VolumeInfo (VolumeInfo&& info) = default;\n                VolumeInfo& operator = (const VolumeInfo& that) = default;\n                VolumeInfo& operator = (VolumeInfo&& that) = default;\n\n                VolumeInfo& setSize (const Point3i& size)\n                {\n                        this->size_ = size;\n                        return *this;\n                }\n\n                VolumeInfo& setPitch (const Point3d& pitch)\n                {\n                        this->pitch_ = pitch;\n                        return *this;\n                }\n\n                VolumeInfo& setOrigin (const Point3d& origin)\n                {\n                        this->origin_ = origin;\n                        return *this;\n                }\n\n                VolumeInfo& init (const Point3i& size, const Point3d& pitch, const Point3d& origin)\n                {\n                        return this->setSize(size).setPitch(pitch).setOrigin(origin);\n                }\n\n                VolumeInfo& initByBoundingBox (const Vector3d& bmin, const Vector3d& bmax, const Point3d& pitch, const double offset)\n                {\n                        const auto off = Eigen::Vector3d::Constant(offset);\n                        return this->setOrigin(bmin - off).setPitch(pitch).setSize(this->getPointInVoxelCeil(bmax - bmin + 2 * off));\n                }\n\n                Point3i getMin (void) const\n                {\n                        return Point3i(0, 0, 0);\n                }\n                Point3i getMax (void) const\n                {\n                        return this->getSize() - Point3i::Constant(1);\n                }\n                Point3i getSize (void) const\n                {\n                        return this->size_;\n                }\n\n                Point3d getPitch (void) const\n                {\n                        return this->pitch_;\n                }\n\n                Point3d getOrigin (void) const\n                {\n                        return this->origin_;\n                }\n\n                Point3d getPointInSpace (const Point3i& p) const\n                {\n                        return this->getPitch().cwiseProduct(p.cast< double >()) + this->getOrigin();\n                }\n\n                Point3i getPointInVoxel (const Point3d& p) const\n                {\n                        return this->getPointInVoxelFloor(p);\n                }\n\n                Point3i convertVectorCeil (const Vector3d& p) const\n                {\n                        return p.cwiseProduct(this->getPitch().cwiseInverse()).unaryExpr([] (double x) { return std::ceil(x); }).cast< int >();\n                }\n\n\n                Point3i convertVectorFloor (const Vector3d& p) const\n                {\n                        return p.cwiseProduct(this->getPitch().cwiseInverse()).unaryExpr([] (double x) { return std::floor(x); }).cast< int >();\n                }\n\n                Point3i getPointInVoxelCeil (const Point3d& p) const\n                {\n                        return this->convertVectorCeil(p - this->getOrigin());\n                }\n\n                Point3i getPointInVoxelFloor (const Point3d& p) const\n                {\n                        return this->convertVectorFloor(p - this->getOrigin());\n                }\n\n                Vector3d getVectorInSpace (const Vector3s& p) const\n                {\n                        return p.cast< double >().cwiseProduct(this->getPitch()) + this->getOrigin();\n                }\n\n                Vector3d getVector (const Vector3i& p) const\n                {\n                        return this->getPitch().cwiseProduct(p.cast< double >());\n                }\n\n                bool isValid (const Point3i& p) const\n                {\n                        return this->clamp(p) == p;\n                }\n\n                Point3i clamp (const Point3i& p) const\n                {\n                        return p.cwiseMax(this->getMin()).cwiseMin(this->getMax());\n                }\n\n                int64_t toIndex (const Point3i& p) const\n                {\n                        const auto& size = this->getSize();\n                        return this->isValid(p) ? static_cast<int64_t> ( p.x()) + static_cast<int64_t> ( size.x()) * static_cast<int64_t> ( p.y() + p.z() * size.y()) : int64_t(-1);\n                }\n\n                Point3i fromIndex (const int64_t idx) const\n                {\n                        const auto& s = this->getSize();\n                        return Point3i(static_cast<int> ( idx % s.x()), static_cast<int> ((idx % (s.x() * s.y())) / s.x()), static_cast<int> ( idx / (s.x() * s.y())));\n                }\n\n                float getLength (const Point3i& v) const\n                {\n                        return std::sqrt(this->getLengthSquared(v));\n                }\n\n                float getLength (const Vector3s& v) const\n                {\n                        return std::sqrt(this->getLengthSquared(v.cast< int >()));\n                }\n\n                float getLengthSquared (const Point3i& v) const\n                {\n                        return static_cast<float> ( this->getVector(v).squaredNorm());\n                }\n\n                bool isCorner (const Point3i& p) const\n                {\n                        return this->isValid(p) && (this->getMin().cwiseEqual(p).count() > 0 || this->getMax().cwiseEqual(p).count() > 0);\n                }\n\n                VolumeInfo clip (const Point3d& bmin, const Point3d& bmax) const\n                {\n                        const auto size = this->getPointInVoxelCeil(bmax) - this->getPointInVoxelFloor(bmin) + Point3i(1, 1, 1);\n                        return VolumeInfo(size, this->getPitch(), bmin);\n                }\n\n                std::string toStringMetaData (void) const\n                {\n                        auto fn = [] (const auto& p) { return std::to_string(p.x()) + \"x\" + std::to_string(p.y()) + \"x\" + std::to_string(p.z()); };\n                        return fn(this->getSize()) + \"-\" + fn(this->getPitch());\n                }\n\n                std::string toStringInfo (void) const\n                {\n                        std::stringstream ss;\n                        ss << \"size : \" << this->getSize().transpose() << \", pitch : \" << this->getPitch().transpose() << \", origin : \" << this->getOrigin().transpose();\n                        return ss.str();\n                }\n        };\n\n        class Range {\n        public:\n                class iterator {\n                public:\n                        explicit iterator (const Range& range, const bool isBegin = true) : range_(range), pos_(range.getMin())\n                        {\n                                this->pos_.z() = isBegin ? this->pos_.z() : range.getMax().z() + 1;\n                        }\n                        iterator (const iterator& that) = default;\n                        iterator (iterator&& that) = default;\n                        iterator& operator = (const iterator& that) = default;\n                        iterator& operator = (iterator&& that) = default;\n                        virtual ~iterator (void) = default;\n\n                        iterator& operator ++ (void)\n                        {\n                                this->step_forward();\n                                return *this;\n                        }\n\n                        bool operator != (const iterator& rhs) const\n                        {\n                                return this->pos_ != rhs.pos_;\n                        }\n\n                        Point3i operator * (void) const\n                        {\n                                return this->pos_;\n                        }\n\n                        iterator& operator += (const size_t n)\n                        {\n                                for ( size_t i = 0; i < n; ++i ) {\n                                        ++(*this);\n                                }\n\n                                return *this;\n                        }\n                private:\n                        void step_forward (void)\n                        {\n                                const auto& bmin = this->range_.getMin();\n                                const auto& bmax = this->range_.getMax();\n                                auto& pos = this->pos_;\n\n                                if ( pos.z() <= bmax.z()) {\n                                        pos.x() += 1;\n\n                                        if ( bmax.x() < pos.x()) {\n                                                pos.x() = bmin.x();\n                                                pos.y() += 1;\n\n                                                if ( bmax.y() < pos.y()) {\n                                                        pos.y() = bmin.y();\n                                                        pos.z() += 1;\n                                                }\n                                        }\n                                }\n                        }\n                private:\n                        const Range& range_; // Pointer to the range.\n                        Point3i pos_; // Current position.\n                };\n\n        public:\n                explicit Range (const Point3i& bmin = Point3i(0, 0, 0), const Point3i& bmax = Point3i(0, 0, 0)) : bbox_(Eigen::AlignedBox3i(bmin, bmax))\n                {\n\n                }\n                explicit Range (const VolumeInfo& info) : bbox_(Eigen::AlignedBox3i(info.getMin(), info.getMax()))\n                {\n\n                }\n                Range (const Range& range) = default;\n                Range& operator = (const Range& range) = default;\n                Range (Range&& range) = default;\n                Range& operator = (Range&& range) = default;\n                ~Range (void) = default;\n\n                Point3i getMin (void) const\n                {\n                        return this->bbox_.min();\n                }\n\n                Point3i getMax (void) const\n                {\n                        return this->bbox_.max();\n                }\n\n                Range::iterator begin (void)\n                {\n                        return Range::iterator(*this, true);\n                }\n\n                Range::iterator end (void)\n                {\n                        return Range::iterator(*this, false);\n                }\n\n        private:\n                Eigen::AlignedBox3i bbox_;\n        };\n\n        template < typename T >\n        class VolumeData {\n        public:\n                explicit VolumeData (const Point3i& size = Point3i(0, 0, 0), const bool allocateMemory = true)\n                {\n                        this->init(VolumeInfo(size), allocateMemory);\n                }\n                explicit VolumeData (const VolumeInfo& info, const bool allocateMemory = true)\n                {\n                        this->init(info, allocateMemory);\n                }\n                virtual ~VolumeData (void) = default;\n\n                VolumeData (VolumeData&& that) = default;\n                VolumeData& operator = (VolumeData&& that) = default;\n                VolumeData (const VolumeData& that) = default;\n                VolumeData& operator = (const VolumeData& that) = default;\n\n                VolumeData< T >& init (const VolumeInfo& info, const bool allocateMemory = true)\n                {\n                        this->data_.clear();\n                        this->info_ = info;\n\n                        if ( allocateMemory ) {\n                                this->allocate();\n                        }\n\n                        return *this;\n                }\n\n                VolumeData< T >& fill (const T& value = T())\n                {\n                        for ( const auto& p : Range(this->getInfo())) {\n                                this->at(p) = value;\n                        }\n\n                        return *this;\n                }\n\n                const VolumeInfo& getInfo (void) const\n                {\n                        return this->info_;\n                }\n\n                Point3i getSize (void) const\n                {\n                        return this->getInfo().getSize();\n                }\n\n                T get (const Point3i& p) const\n                {\n                        return this->at(p);\n                }\n\n                void set (const Point3i& p, const T v)\n                {\n                        this->at(p) = v;\n                }\n\n                T at (const Point3i& p) const\n                {\n                        return this->at(p.x(), p.y(), p.z());\n                }\n\n                T& at (const Point3i& p)\n                {\n                        return this->at(p.x(), p.y(), p.z());\n                }\n\n                T at (const int x, const int y, const int z) const\n                {\n                        return this->data_.at(z).at(y).at(x);\n                }\n\n                T& at (const int x, const int y, const int z)\n                {\n                        return this->data_.at(z).at(y).at(x);\n                }\n\n                bool clone (const VolumeData< T >& that)\n                {\n                        this->init(that.getInfo(), true);\n\n                        for ( const auto& p : Range(that.getInfo())) {\n                                this->at(p) = that.at(p);\n                        }\n\n                        return true;\n                }\n\n                bool allocate (void)\n                {\n                        if ( !this->isReadable()) {\n                                const auto& size = this->getInfo().getSize();\n                                this->data_.assign(size.z(), std::vector< std::vector< T > >(size.y(), std::vector< T >(size.x(), T())));\n                                if ( !this->isReadable()) {\n                                        this->release();\n                                        std::cerr << \" error : allocation failed\" << std::endl;\n                                        return false;\n                                }\n                        }\n\n                        return true;\n                }\n\n                void release (void)\n                {\n                        this->data_.erase(this->data_.begin(), this->data_.end());\n                }\n\n                bool isReadable (void) const\n                {\n                        const auto& size = this->info_.getSize();\n                        if ( this->data_.size() != static_cast<size_t> ( size.z())) return false;\n                        for ( const auto& dataxy : this->data_ ) {\n                                if ( dataxy.size() != static_cast<size_t> ( size.y())) return false;\n                                for ( const auto& datax : dataxy ) {\n                                        if ( datax.size() != static_cast<size_t> ( size.x())) return false;\n                                }\n                        }\n                        return true;\n                }\n\n                bool open (const std::string& filename, const size_t offset = 0)\n                {\n                        std::ifstream fin(filename.c_str(), std::ios::binary);\n                        return this->read(fin, offset);\n                }\n\n                bool save (const std::string& filename)\n                {\n                        std::ofstream fout(filename.c_str(), std::ios::binary);\n                        return this->write(fout);\n                }\n\n                bool read (std::ifstream& fin, const size_t offset = 0)\n                {\n                        if ( !fin ) {\n                                std::cerr << \" error : file stream is not ready yet.\" << std::endl;\n                                return false;\n                        }\n\n                        fin.seekg(offset);\n\n                        for ( auto& dataz : this->data_ ) {\n                                for ( auto& datazy : dataz ) {\n                                        if ( !fin.read(reinterpret_cast<char *> (datazy.data()), datazy.size() * sizeof(T))) {\n                                                return false;\n                                        }\n                                }\n                        }\n\n                        return fin.good();\n                }\n\n                bool write (std::ofstream& fout)\n                {\n                        if ( !this->isReadable()) {\n                                std::cerr << \"volume data is not readable.\" << std::endl;\n                                return false;\n                        } else if ( !fout ) {\n                                std::cerr << \"the file cannot be open.\" << std::endl;\n                                return false;\n                        }\n\n                        for ( const auto& dataz : this->data_ ) {\n                                for ( const auto& datazy : dataz ) {\n                                        if ( !fout.write(reinterpret_cast<const char *>(datazy.data()), sizeof(T) * datazy.size())) {\n                                                return false;\n                                        }\n                                }\n                        }\n                        return fout.good();\n                }\n        private:\n                VolumeInfo info_;\n                std::vector< std::vector< std::vector< T > > > data_;\n        };\n}\n#endif// MI_VOLUME_DATA_HPP", "meta": {"hexsha": "47c1e885522947c75cdc73fcb4b2f35edab915d7", "size": 18497, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mi4/VolumeData.hpp", "max_stars_repo_name": "tmichi/mi4", "max_stars_repo_head_hexsha": "238278cd6c3e088a08920155f048bc74963986fb", "max_stars_repo_licenses": ["MIT"], "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/mi4/VolumeData.hpp", "max_issues_repo_name": "tmichi/mi4", "max_issues_repo_head_hexsha": "238278cd6c3e088a08920155f048bc74963986fb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-05-28T02:28:58.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-28T03:00:24.000Z", "max_forks_repo_path": "include/mi4/VolumeData.hpp", "max_forks_repo_name": "tmichi/mi4", "max_forks_repo_head_hexsha": "238278cd6c3e088a08920155f048bc74963986fb", "max_forks_repo_licenses": ["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.6966527197, "max_line_length": 203, "alphanum_fraction": 0.3836297778, "num_tokens": 3527, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.6688802735722128, "lm_q1q2_score": 0.4827597932772233}}
{"text": "#include <catch.hpp>\n#include <Eigen/Core>\n#include <random>\n\n#include \"check_adjoint.h\"\n#include \"test_utils.h\"\n#include \"renderer_blending.cuh\"\n\n\nstatic void testAdjointCamera()\n{\n\ttypedef empty TmpStorage_t;\n\ttypedef VectorXr Vector_t;\n\tstatic int numSteps = 10;\n\tstatic const real3 boxMin = make_real3(-0.2f, -0.3f, -0.4f);\n\tstatic const real3 voxelSize = make_real3(0.1f, 0.05f, 0.07f);\n\n\tauto forward = [](const Vector_t& x, TmpStorage_t* tmp) -> Vector_t\n\t{\n\t\tconst real3 rayStart = fromEigen3(x.segment(0, 3));\n\t\tconst real3 rayDir = fromEigen3(x.segment(3, 3));\n\t\tconst real_t stepsize = x[6];\n\t\tVector_t result = Vector_t::Zero(numSteps * 3);\n\t\tfor (int i=0; i<numSteps; ++i)\n\t\t{\n\t\t\treal_t tcurrent = i * stepsize;\n\t\t\treal3 worldPos = rayStart + tcurrent * rayDir;\n\t\t\treal3 volumePos = (worldPos - boxMin) / voxelSize;\n\t\t\tresult.segment(3 * i, 3) = toEigen(volumePos);\n\t\t}\n\t\treturn result;\n\t};\n\tauto adjoint = [](const Vector_t& x, const Vector_t& e, const Vector_t& g,\n\t\tVector_t& z, const TmpStorage_t& tmp)\n\t{\n\t\tconst real3 rayStart = fromEigen3(x.segment(0, 3));\n\t\tconst real3 rayDir = fromEigen3(x.segment(3, 3));\n\t\tconst real_t stepsize = x[6];\n\t\treal3 adj_rayStart = make_real3(0);\n\t\treal3 adj_rayDir = make_real3(0);\n\t\treal_t adj_stepSize = 0;\n\t\tfor (int i=numSteps-1; i>=0; --i)\n\t\t{\n\t\t\t//run part of the forward code again\n\t\t\treal_t tcurrent = i * stepsize;\n\t\t\treal3 worldPos = rayStart + tcurrent * rayDir;\n\t\t\treal3 volumePos = (worldPos - boxMin) / voxelSize;\n\n\t\t\treal3 adj_volumePos = fromEigen3(g.segment(3 * i, 3));\n\t\t\t\n\t\t\t//adjoint stepping\n\t\t\treal3 adj_worldPos = adj_volumePos / voxelSize;\n\t\t\tadj_rayStart += adj_worldPos;\n\t\t\tadj_rayDir += adj_worldPos * tcurrent;\n\t\t\treal_t adj_tcurrent = dot(adj_worldPos, rayDir);\n\t\t\tadj_stepSize += adj_tcurrent * i;\n\t\t}\n\n\t\tz.segment(0, 3) = toEigen(adj_rayStart);\n\t\tz.segment(3, 3) = toEigen(adj_rayDir);\n\t\tz[6] = adj_stepSize;\n\t};\n\n\tstd::default_random_engine rnd(42);\n\tstd::uniform_real_distribution<real_t> distr(0.01, 0.99);\n\tint N = 20;\n\tfor (int i = 0; i < N; ++i)\n\t{\n\t\tINFO(\"N=\" << i);\n\t\tVector_t x(7);\n\t\tfor (int j = 0; j < 7; ++j) x[j] = distr(rnd);\n\n\t\tcheckAdjoint<Vector_t, TmpStorage_t>(x, forward, adjoint,\n\t\t\t1e-5, 1e-5, 1e-6);\n\t}\n}\n\nTEST_CASE(\"Adjoint-Camera\", \"[adjoint]\")\n{\n\ttestAdjointCamera();\n}\n\n\n", "meta": {"hexsha": "6f94c021282ea4c79c047ff266bb4227cea6250f", "size": 2282, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittests/testAdjointCamera.cpp", "max_stars_repo_name": "shamanDevel/DiffDVR", "max_stars_repo_head_hexsha": "99fbe9f114d0097daf402bde2ae35f18dade335d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2021-08-02T04:51:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-14T18:02:27.000Z", "max_issues_repo_path": "unittests/testAdjointCamera.cpp", "max_issues_repo_name": "shamanDevel/DiffDVR", "max_issues_repo_head_hexsha": "99fbe9f114d0097daf402bde2ae35f18dade335d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-11-04T14:23:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-28T10:30:13.000Z", "max_forks_repo_path": "unittests/testAdjointCamera.cpp", "max_forks_repo_name": "shamanDevel/DiffDVR", "max_forks_repo_head_hexsha": "99fbe9f114d0097daf402bde2ae35f18dade335d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-07-16T10:23:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-04T02:51:43.000Z", "avg_line_length": 27.1666666667, "max_line_length": 75, "alphanum_fraction": 0.6695880806, "num_tokens": 781, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.4827597885132836}}
{"text": "#include <opencv2/core/core.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n\n#include <fstream>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <utility>\n#include <vector>\n#include <map>\n#include <algorithm>\n#include <stdint.h>\n\n#include \"gflags/gflags.h\"\n#include \"glog/logging.h\"\n#include <boost/shared_ptr.hpp>\n\n#include \"caffe/proto/caffe.pb.h\"\n#include \"caffe/blob.hpp\"\n#include \"caffe/util/benchmark.hpp\"\n#include \"caffe/util/io.hpp\"\n#include \"caffe/util/math_functions.hpp\"\n#include \"caffe/util/rng.hpp\"\n#include \"caffe/layer.hpp\"\n#include \"caffe/filler.hpp\"\n\n#include \"caffe/nhwc/conv_nhwc_layer.hpp\"\n\n#include \"gtest/gtest.h\"\n#include \"caffe/test/test_caffe_main.hpp\"\n#include \"caffe/test/test_gradient_check_util.hpp\"\n\nusing namespace std;\nusing namespace caffe;\n\nint main(int nargc, char** args) {\n  // set caffe::GPU\n  caffe::Caffe::SetDevice(0);\n  caffe::Caffe::set_mode(caffe::Caffe::CPU);\n\n  int channels = 16;  //input\n  int num_output = 32;  // output\n  int dim = 4; // size\n  // define input & output blobs\n  Blob<float>* input = new Blob<float>(1, dim, dim, channels);\n  Blob<float>* output = new Blob<float>(1, dim, dim, num_output);\n  vector<Blob<float>*> bottom_vec;\n  vector<Blob<float>*> top_vec;\n\n  // set the bottom blob data\n  FillerParameter filler_param;\n  filler_param.set_std(0.5);\n  GaussianFiller<float> filler(filler_param);\n  filler.Fill(input);\n\n  // set the bottom and top data-pointer\n  bottom_vec.push_back(input);\n  top_vec.push_back(output);\n\n  // create reorg layer\n  LayerParameter layer_param;\n  layer_param.set_name(\"ConvNHWC\");\n  layer_param.set_type(\"ConvolutionNHWC\");\n  ConvolutionParameter* conv_param = layer_param.mutable_convolution_param();\n  conv_param->set_kernel_h(3);\n  conv_param->set_kernel_w(3);\n  conv_param->set_stride_h(1);\n  conv_param->set_stride_w(1);\n  conv_param->set_pad_h(1);\n  conv_param->set_pad_w(1);\n  conv_param->set_group(1);\n  conv_param->set_num_output(num_output);\n  conv_param->set_engine(caffe::ConvolutionParameter_Engine_CAFFE);\n  FillerParameter* weight_filler = conv_param->mutable_weight_filler();\n  weight_filler->set_type(\"gaussian\");\n  weight_filler->set_std(0.01);\n  FillerParameter* bias_filler = conv_param->mutable_bias_filler();\n  bias_filler->set_type(\"constant\");\n  bias_filler->set_std(0);\n\n  boost::shared_ptr<Layer<float> > convNHWC_layer = LayerRegistry<float>::CreateLayer(layer_param);\n  convNHWC_layer->SetUp(bottom_vec, top_vec);\n\n  convNHWC_layer->Forward(bottom_vec, top_vec);\n  // copy diff\n  // caffe_copy(top_vec[0]->count(), top_vec[0]->cpu_data(), top_vec[0]->mutable_cpu_diff());\n  //\n  // for (int i = 0; i < top_vec[0]->count(); ++i) {\n  //   LOG(INFO) << top_vec[0]->cpu_data()[i];\n  // }\n  // LOG(FATAL) << \"End.\";\n\n  GradientChecker<float> checker(1e-4, 1e-3);\n  checker.CheckGradientExhaustive(convNHWC_layer.get(), bottom_vec, top_vec);\n\n  LOG(INFO) << \"Gradient Check Finished.\";\n  return 0;\n}\n", "meta": {"hexsha": "b898dd6776af7cd8f4f1addd1f10c81ffede4fad", "size": 2929, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "remodet_repository_wdh_part/test/testConvNHWC/src/testConvNHWC.cpp", "max_stars_repo_name": "UrwLee/Remo_experience", "max_stars_repo_head_hexsha": "a59d5b9d6d009524672e415c77d056bc9dd88c72", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "remodet_repository_wdh_part/test/testConvNHWC/src/testConvNHWC.cpp", "max_issues_repo_name": "UrwLee/Remo_experience", "max_issues_repo_head_hexsha": "a59d5b9d6d009524672e415c77d056bc9dd88c72", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "remodet_repository_wdh_part/test/testConvNHWC/src/testConvNHWC.cpp", "max_forks_repo_name": "UrwLee/Remo_experience", "max_forks_repo_head_hexsha": "a59d5b9d6d009524672e415c77d056bc9dd88c72", "max_forks_repo_licenses": ["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.5858585859, "max_line_length": 99, "alphanum_fraction": 0.7234551041, "num_tokens": 806, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975978, "lm_q2_score": 0.6688802669716106, "lm_q1q2_score": 0.48275978851328344}}
{"text": "/*********************************************************************\n* Rice University Software Distribution License\n*\n* Copyright (c) 2010, Rice University\n* All Rights Reserved.\n*\n* For a full description see the file named LICENSE.\n*\n*********************************************************************/\n\n/* Author: Mark Moll */\n\n#include <ompl/tools/benchmark/Benchmark.h>\n#include <ompl/control/planners/rrt/RRT.h>\n#include <ompl/control/planners/kpiece/KPIECE1.h>\n#include <omplapp/apps/KinematicCarPlanning.h>\n#include <omplapp/config.h>\n#include <boost/math/constants/constants.hpp>\n\nusing namespace ompl;\n\nvoid kinematicCarSetup(app::KinematicCarPlanning& setup)\n{\n    // plan for kinematic car in SE(2)\n    base::StateSpacePtr SE2(setup.getStateSpace());\n\n    // set the bounds for the R^2 part of SE(2)\n    base::RealVectorBounds bounds(2);\n    bounds.setLow(-10);\n    bounds.setHigh(10);\n    SE2->as<base::SE2StateSpace>()->setBounds(bounds);\n\n    // define start state\n    base::ScopedState<base::SE2StateSpace> start(SE2);\n    start->setX(0);\n    start->setY(0);\n    start->setYaw(0);\n\n    // define goal state\n    base::ScopedState<base::SE2StateSpace> goal(SE2);\n    goal->setX(2);\n    goal->setY(2);\n    goal->setYaw(boost::math::constants::pi<double>());\n\n    // set the start & goal states\n    setup.setStartAndGoalStates(start, goal, .1);\n}\n\nvoid kinematicCarDemo(app::KinematicCarPlanning& setup)\n{\n    setup.setPlanner(base::PlannerPtr(new control::KPIECE1(setup.getSpaceInformation())));\n    std::vector<double> cs(2);\n    cs[0] = cs[1] = 0.1;\n    setup.setup();\n    setup.getStateSpace()->getDefaultProjection()->setCellSizes(cs);\n\n    // try to solve the problem\n    if (setup.solve(20))\n    {\n        // print the (approximate) solution path: print states along the path\n        // and controls required to get from one state to the next\n        control::PathControl& path(setup.getSolutionPath());\n        //path.interpolate(); // uncomment if you want to plot the path\n        path.printAsMatrix(std::cout);\n        if (!setup.haveExactSolutionPath())\n        {\n            std::cout << \"Solution is approximate. Distance to actual goal is \" <<\n                setup.getProblemDefinition()->getSolutionDifference() << std::endl;\n        }\n    }\n\n}\nvoid kinematicCarBenchmark(app::KinematicCarPlanning& setup)\n{\n    tools::Benchmark::Request request(20., 10000., 10); // runtime (s), memory (MB), run count\n\n    tools::Benchmark b(setup, setup.getName());\n    b.addPlanner(base::PlannerPtr(new control::RRT(setup.getSpaceInformation())));\n    b.addPlanner(base::PlannerPtr(new control::KPIECE1(setup.getSpaceInformation())));\n    b.benchmark(request);\n    b.saveResultsToFile();\n}\n\nint main(int argc, char**)\n{\n    app::KinematicCarPlanning regularCar;\n\n    kinematicCarSetup(regularCar);\n\n    // If any command line arguments are given, solve the problem multiple\n    // times with different planners and collect benchmark statistics.\n        // Otherwise, solve the problem once for each car type and print the path.\n    if (argc>1)\n        kinematicCarBenchmark(regularCar);\n    else\n        kinematicCarDemo(regularCar);\n    return 0;\n}\n", "meta": {"hexsha": "13e64d68cd0f2445fc4c7cc6125bf8f876dd15b5", "size": 3171, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "demos/SE2RigidBodyPlanning/KinematicCarPlanning.cpp", "max_stars_repo_name": "SZanlongo/omplapp", "max_stars_repo_head_hexsha": "c56679337e2a71d266359450afbe63d700c0a666", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "demos/SE2RigidBodyPlanning/KinematicCarPlanning.cpp", "max_issues_repo_name": "SZanlongo/omplapp", "max_issues_repo_head_hexsha": "c56679337e2a71d266359450afbe63d700c0a666", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/SE2RigidBodyPlanning/KinematicCarPlanning.cpp", "max_forks_repo_name": "SZanlongo/omplapp", "max_forks_repo_head_hexsha": "c56679337e2a71d266359450afbe63d700c0a666", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-07-01T09:30:45.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-01T09:30:45.000Z", "avg_line_length": 32.0303030303, "max_line_length": 94, "alphanum_fraction": 0.6502680542, "num_tokens": 780, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432182679956, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.4827597869921666}}
{"text": "#include \"Cpp/Classes/BitField.h\"\n#include \"Cpp/Utilities/SuperBitSet.h\"\n#include \"Utilities/ToHexString.h\"\n\n#include <boost/test/unit_test.hpp>\n#include <sstream> // std::stringstream\n\nusing Cpp::Classes::Char4Bits;\nusing Cpp::Classes::Int4Bits;\nusing Cpp::Classes::UnsignedChar4Bits;\nusing Cpp::Classes::UnsignedInt24Bits;\nusing Cpp::Classes::UnsignedInt4Bits;\nusing Cpp::Classes::UnsignedInt5Bits;\nusing Cpp::Utilities::SuperBitSet;\nusing Utilities::to_hex_string;\nusing std::stringstream;\n\nBOOST_AUTO_TEST_SUITE(Algorithms)\nBOOST_AUTO_TEST_SUITE(Bits)\n\nBOOST_AUTO_TEST_SUITE(BitField_tests)\n\nBOOST_AUTO_TEST_SUITE(Char4Bits_tests)\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(CyclesAccordingTo4Bits)\n{\n  stringstream out;\n\n  Char4Bits a {0};\n\n  BOOST_TEST((a.bits == 0));\n\n  out << to_hex_string(a.bits);\n\n  BOOST_TEST(out.str() == \"00\");\n\n  a.bits = 1;\n  BOOST_TEST((a.bits == 1));\n\n  // Clear the contents of a stringstream.\n  // https://stackoverflow.com/questions/20731/how-do-you-clear-a-stringstream-variable\n  out.str(\"\");\n\n  out << to_hex_string(a.bits);\n\n  BOOST_TEST(out.str() == \"01\");\n\n  a.bits = 5;\n  BOOST_TEST((a.bits == 5));\n  out.str(\"\");\n  out << to_hex_string(a.bits);\n  BOOST_TEST(out.str() == \"05\");\n\n  a.bits = 7;\n  BOOST_TEST((a.bits == 7));\n  out.str(\"\");\n  out << to_hex_string(a.bits);\n  BOOST_TEST(out.str() == \"07\");\n\n  a.bits = 8;\n\n  BOOST_TEST((a.bits == -8));\n  out.str(\"\");\n  out << to_hex_string(a.bits);\n  BOOST_TEST(out.str() == \"f8\");\n\n  a.bits = 9;\n  BOOST_TEST((a.bits == -7));\n  out.str(\"\");\n  out << to_hex_string(a.bits);\n  BOOST_TEST(out.str() == \"f9\");\n\n  a.bits = 14;\n  BOOST_TEST((a.bits == -2));\n  out.str(\"\");\n  out << to_hex_string(a.bits);\n  BOOST_TEST(out.str() == \"fe\");\n\n  a.bits = 15;\n  BOOST_TEST((a.bits == -1));\n  out.str(\"\");\n  out << to_hex_string(a.bits);\n  BOOST_TEST(out.str() == \"ff\");\n\n  // Overflow warning.\n  /*\n  a.bits = 16;\n  BOOST_TEST((a.bits == 0));\n  out.str(\"\");\n  out << to_hex_string(a.bits);\n  BOOST_TEST(out.str() == \"00\");\n  */\n}\n\nBOOST_AUTO_TEST_SUITE_END() // Char4Bits_tests\n\n\nBOOST_AUTO_TEST_SUITE(UnsignedInt4Bits_tests)\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(CyclesAccordingTo4Bits)\n{\n  stringstream out;\n\n  UnsignedInt4Bits a {0};\n  BOOST_TEST((a.bits == 0));\n  out.str(\"\");\n  out << to_hex_string(a.bits);\n  BOOST_TEST(out.str() == \"00000000\");\n  BOOST_TEST(SuperBitSet<4>{a.bits}.to_string() == \"0000\");\n\n  a.bits = 1;\n  BOOST_TEST((a.bits == 1));\n  out.str(\"\");\n  out << to_hex_string(a.bits);\n  BOOST_TEST(out.str() == \"00000001\");\n  BOOST_TEST(SuperBitSet<4>{a.bits}.to_string() == \"0001\");\n\n  a.bits = 2;\n  BOOST_TEST((a.bits == 2));\n  out.str(\"\");\n  out << to_hex_string(a.bits);\n  BOOST_TEST(out.str() == \"00000002\");\n  BOOST_TEST(SuperBitSet<4>{a.bits}.to_string() == \"0010\");\n\n  a.bits = 9;\n  BOOST_TEST((a.bits == 9));\n  out.str(\"\");\n  out << to_hex_string(a.bits);\n  BOOST_TEST(out.str() == \"00000009\");\n  BOOST_TEST(SuperBitSet<4>{a.bits}.to_string() == \"1001\");\n\n  a.bits = 10;\n  BOOST_TEST((a.bits == 10));\n  out.str(\"\");\n  out << to_hex_string(a.bits);\n  BOOST_TEST(out.str() == \"0000000a\");\n  BOOST_TEST(SuperBitSet<4>{a.bits}.to_string() == \"1010\");\n\n  a.bits = 11;\n  BOOST_TEST((a.bits == 11));\n  out.str(\"\");\n  out << to_hex_string(a.bits);\n  BOOST_TEST(out.str() == \"0000000b\");\n  BOOST_TEST(SuperBitSet<4>{a.bits}.to_string() == \"1011\");\n\n  a.bits = 14;\n  BOOST_TEST((a.bits == 14));\n  out.str(\"\");\n  out << to_hex_string(a.bits);\n  BOOST_TEST(out.str() == \"0000000e\");\n  BOOST_TEST(SuperBitSet<4>{a.bits}.to_string() == \"1110\");\n\n  a.bits = 15;\n  BOOST_TEST((a.bits == 15));\n  out.str(\"\");\n  out << to_hex_string(a.bits);\n  BOOST_TEST(out.str() == \"0000000f\");\n  BOOST_TEST(SuperBitSet<4>{a.bits}.to_string() == \"1111\");\n\n  // Overflow warning.\n  // a.bits = 16;\n}\n\nBOOST_AUTO_TEST_SUITE_END() // UnsignedInt4Bits_tests\n\nBOOST_AUTO_TEST_SUITE(UnsignedInt24Bits_tests)\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(CyclesAccordingTo4Bits)\n{\n\n}\n\nBOOST_AUTO_TEST_SUITE_END() // UnsignedInt24Bits_tests\n\n\nBOOST_AUTO_TEST_SUITE_END() // BitField_tests\n\nBOOST_AUTO_TEST_SUITE_END() // Bits\nBOOST_AUTO_TEST_SUITE_END() // Algorithms", "meta": {"hexsha": "118eed47e48bad7afce2e4673a318276ecb09f6d", "size": 4559, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Voltron/Source/UnitTests/Cpp/Classes/BitField_tests.cpp", "max_stars_repo_name": "ernestyalumni/HrdwCCppCUDA", "max_stars_repo_head_hexsha": "17ed937dea06431a4d5ca103f993ea69a6918734", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-02-09T19:44:51.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-09T19:44:51.000Z", "max_issues_repo_path": "Voltron/Source/UnitTests/Cpp/Classes/BitField_tests.cpp", "max_issues_repo_name": "ernestyalumni/HrdwCCppCUDA", "max_issues_repo_head_hexsha": "17ed937dea06431a4d5ca103f993ea69a6918734", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Voltron/Source/UnitTests/Cpp/Classes/BitField_tests.cpp", "max_forks_repo_name": "ernestyalumni/HrdwCCppCUDA", "max_forks_repo_head_hexsha": "17ed937dea06431a4d5ca103f993ea69a6918734", "max_forks_repo_licenses": ["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.6432432432, "max_line_length": 87, "alphanum_fraction": 0.5843386708, "num_tokens": 1224, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.48275978374934386}}
{"text": "#include <string>\n\n#define BOOST_TEST_MODULE MixedMIAMergeTests\n\n\n\n\n#include \"MIAConfig.h\"\n\n#ifdef MIA_USE_HEADER_ONLY_TESTS\r\n#include <boost/test/included/unit_test.hpp>\r\n#else\r\n#include <boost/test/unit_test.hpp>\r\n#endif\n#include \"DenseMIA.h\"\r\n#include \"SparseMIA.h\"\nconstexpr int dim=5;\r\n\r\n\r\n\ntemplate<typename data_type>\nvoid do_work(size_t dim1){\n\r\n    LibMIA::DenseMIA<data_type,3> temp_a(dim1,dim1,dim1);\r\n\r\n    LibMIA::DenseMIA<data_type,3> dense_b(dim1,dim1,dim1);\r\n    LibMIA::DenseMIA<data_type,3> dense_c;\r\n    LibMIA::DenseMIA<data_type,3> dense_c2;\r\n\r\n    LibMIA::SparseMIA<data_type,3> sparse_a;\r\n    LibMIA::SparseMIA<data_type,3> sparse_c2;\r\n\r\n    LibMIA::MIAINDEX i;\n    LibMIA::MIAINDEX j;\n    LibMIA::MIAINDEX k;\r\n\r\n    temp_a.randu(0,20);\r\n    dense_b.randu(0,20);\r\n    for(auto it=temp_a.data_begin();it<temp_a.data_end();++it)\r\n        if(*it<15)\r\n            *it=0;\r\n    for(auto it=dense_b.data_begin();it<dense_b.data_end();++it)\r\n        if(*it<15)\r\n            *it=0;\r\n\r\n    sparse_a=temp_a;\r\n\r\n    const LibMIA::DenseMIA<data_type,3> dense_a(temp_a); //use a const, just to double check we got const correction right in the expression templates\r\n\r\n    dense_c(i,j,k)=dense_a(i,j,k)+dense_b(i,j,k);\r\n    dense_c2(i,j,k)=sparse_a(i,j,k)+dense_b(i,j,k);\r\n    BOOST_CHECK_MESSAGE(dense_c==dense_c2,std::string(\"Non-destructive Add 1a for \")+typeid(data_type).name());\r\n    //switch order of operands\r\n    dense_c2(i,j,k)=dense_b(i,j,k)+sparse_a(i,j,k);\r\n    BOOST_CHECK_MESSAGE(dense_c==dense_c2,std::string(\"Non-destructive Add 1b for \")+typeid(data_type).name());\r\n\r\n    dense_c(k,i,j)=dense_a(i,k,j)+dense_b(j,k,i);\r\n    dense_c2(k,i,j)=sparse_a(i,k,j)+dense_b(j,k,i);\n\r\n    BOOST_CHECK_MESSAGE(dense_c==dense_c2,std::string(\"Non-destructive Add 2a for \")+typeid(data_type).name());\r\n    //switch order of operands\r\n    dense_c2(k,i,j)=dense_b(j,k,i)+sparse_a(i,k,j);\r\n    BOOST_CHECK_MESSAGE(dense_c==dense_c2,std::string(\"Non-destructive Add 2b for \")+typeid(data_type).name());\r\n\r\n    //**Destructive\r\n    dense_c=dense_a;\r\n    sparse_c2=sparse_a;\r\n    dense_c(i,j,k)+=dense_b(i,j,k);\r\n    sparse_c2(i,j,k)+=dense_b(i,j,k);\n\r\n    BOOST_CHECK_MESSAGE(dense_c==sparse_c2,std::string(\"Destructive Add 1a for \")+typeid(data_type).name());\r\n    //switch order of operands\r\n    dense_c=dense_b;\r\n    dense_c2=dense_b;\r\n    dense_c(i,j,k)+=dense_a(i,j,k);\r\n    dense_c2(i,j,k)+=sparse_a(i,j,k);\r\n    BOOST_CHECK_MESSAGE(dense_c==dense_c2,std::string(\"Destructive Add 1b for \")+typeid(data_type).name());\r\n\r\n\r\n    dense_c=dense_a;\r\n    sparse_c2=sparse_a;\r\n    dense_c(k,i,j)+=dense_b(j,k,i);\r\n    sparse_c2(k,i,j)+=dense_b(j,k,i);\n\r\n    BOOST_CHECK_MESSAGE(dense_c==sparse_c2,std::string(\"Destructive Add 2a for \")+typeid(data_type).name());\r\n    //switch order of operands\r\n    dense_c=dense_b;\r\n    dense_c2=dense_b;\r\n    dense_c(k,i,j)+=dense_a(i,k,j);\r\n    dense_c2(k,i,j)+=sparse_a(i,k,j);\r\n\r\n    BOOST_CHECK_MESSAGE(dense_c==dense_c2,std::string(\"Destructive Add 2b for \")+typeid(data_type).name());\r\n\r\n    //******Subtract******************\r\n\r\n    dense_c(i,j,k)=dense_a(i,j,k)-dense_b(i,j,k);\r\n    dense_c2(i,j,k)=sparse_a(i,j,k)-dense_b(i,j,k);\n\r\n    BOOST_CHECK_MESSAGE(dense_c==dense_c2,std::string(\"Non-destructive Sub 1a for \")+typeid(data_type).name());\r\n    //switch order of operands\r\n    dense_c(i,j,k)=dense_b(i,j,k)-dense_a(i,j,k);\r\n    dense_c2(i,j,k)=dense_b(i,j,k)-sparse_a(i,j,k);\r\n    BOOST_CHECK_MESSAGE(dense_c==dense_c2,std::string(\"Non-destructive Sub 1b for \")+typeid(data_type).name());\r\n\r\n    dense_c(k,i,j)=dense_a(i,k,j)-dense_b(j,k,i);\r\n    dense_c2(k,i,j)=sparse_a(i,k,j)-dense_b(j,k,i);\n\r\n    BOOST_CHECK_MESSAGE(dense_c==dense_c2,std::string(\"Non-destructive Sub 2a for \")+typeid(data_type).name());\r\n    //switch order of operands\r\n    dense_c(k,i,j)=dense_b(j,k,i)-dense_a(i,k,j);\r\n    dense_c2(k,i,j)=dense_b(j,k,i)-sparse_a(i,k,j);\r\n    BOOST_CHECK_MESSAGE(dense_c==dense_c2,std::string(\"Non-destructive Sub 2b for \")+typeid(data_type).name());\r\n\r\n\r\n    //**Destructive\r\n    dense_c=dense_a;\r\n    sparse_c2=sparse_a;\r\n    dense_c(i,j,k)-=dense_b(i,j,k);\r\n    sparse_c2(i,j,k)-=dense_b(i,j,k);\n\r\n    BOOST_CHECK_MESSAGE(dense_c==sparse_c2,std::string(\"Destructive Sub 1a for \")+typeid(data_type).name());\r\n    //switch order of operands\r\n    dense_c=dense_b;\r\n    dense_c2=dense_b;\r\n    dense_c(i,j,k)-=dense_a(i,j,k);\r\n    dense_c2(i,j,k)-=sparse_a(i,j,k);\r\n    BOOST_CHECK_MESSAGE(dense_c==dense_c2,std::string(\"Destructive Sub 1b for \")+typeid(data_type).name());\r\n\r\n\r\n    dense_c=dense_a;\r\n    sparse_c2=sparse_a;\r\n    dense_c(k,i,j)-=dense_b(j,k,i);\r\n    sparse_c2(k,i,j)-=dense_b(j,k,i);\n\r\n    BOOST_CHECK_MESSAGE(dense_c==sparse_c2,std::string(\"Destructive Sub 2a for \")+typeid(data_type).name());\r\n    //switch order of operands\r\n    dense_c=dense_b;\r\n    dense_c2=dense_b;\r\n    dense_c(k,i,j)-=dense_a(i,k,j);\r\n    dense_c2(k,i,j)-=sparse_a(i,k,j);\r\n\r\n    BOOST_CHECK_MESSAGE(dense_c==dense_c2,std::string(\"Destructive Sub 2b for \")+typeid(data_type).name());\n\n\n}\r\n\r\n\r\n\r\n\n\nBOOST_AUTO_TEST_CASE( MixedMIAMergeTests )\n{\n\r\n    size_t dim1=3;\r\n\r\n\r\n    do_work<float>(dim1);\r\n    do_work<double>(dim1);\r\n    do_work<int32_t>(dim1);\r\n    do_work<int64_t>(dim1);\n\n}\n\r\n\r\n\r\n", "meta": {"hexsha": "42650da4661aee1e1f1394727c52adb4dc697422", "size": 5238, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tests/MIA/mixed_mia_merge_test.cpp", "max_stars_repo_name": "extragoya/LibNT", "max_stars_repo_head_hexsha": "60372bf4e3c5d6665185358c4756da4fe547f093", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-26T05:11:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-26T05:11:32.000Z", "max_issues_repo_path": "src/tests/MIA/mixed_mia_merge_test.cpp", "max_issues_repo_name": "extragoya/LibNT", "max_issues_repo_head_hexsha": "60372bf4e3c5d6665185358c4756da4fe547f093", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/MIA/mixed_mia_merge_test.cpp", "max_forks_repo_name": "extragoya/LibNT", "max_forks_repo_head_hexsha": "60372bf4e3c5d6665185358c4756da4fe547f093", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-09-21T15:38:23.000Z", "max_forks_repo_forks_event_max_datetime": "2017-09-21T15:38:23.000Z", "avg_line_length": 31.5542168675, "max_line_length": 151, "alphanum_fraction": 0.6580756014, "num_tokens": 1631, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.721743206297598, "lm_q2_score": 0.6688802603710085, "lm_q1q2_score": 0.4827597837493438}}
{"text": "#include <Eigen/Core>\n// Some adaptions for gtsam's bundled Eigen being old\n#if !(EIGEN_VERSION_AT_LEAST(3, 3, 0))\n#define EIGEN_DEVICE_FUNC\nnamespace Eigen {\nusing Index = EIGEN_DEFAULT_DENSE_INDEX_TYPE;\n}\n#endif\n\n#include <benchmark/benchmark.h>\n#include <gtsam/nonlinear/expressionTesting.h>\n#include <gtsam/slam/expressions.h>\n#include \"wave/geometry/src/util/math/math.hpp\"\n\n\ntemplate <typename T>\nusing EigenVector = std::vector<T, Eigen::aligned_allocator<T>>;\n\n\nusing gtsam::Expression;\nusing gtsam::Point3;\nusing gtsam::Rot3;\n\nvoid BM_gtsamAll(benchmark::State &state) {\n    const auto N = state.range(0);\n    state.SetComplexityN(N);\n    // Produce the expression tree\n    gtsam::Values values;\n    auto p1 = Expression<Point3>{'p', 1};\n    auto expr = p1;\n    values.insert(gtsam::Symbol{'p', 1}, Point3{Eigen::Vector3d::Random()});\n\n    for (auto i = 0u; i < N; ++i) {\n        expr = Expression<Point3>{rotate(Expression<Rot3>{'R', i}, expr)};\n        values.insert(gtsam::Symbol{'R', i}, Rot3{wave::randomQuaternion<double>()});\n    }\n    std::vector<gtsam::Matrix> jacs(N + 1);\n\n    for (auto _ : state) {\n        Point3 p2 = expr.value(values, jacs);\n\n        benchmark::DoNotOptimize(p2);\n        benchmark::DoNotOptimize(jacs);\n    }\n}\n\n// This benchmark tests gtsam's valueAndJacobianMap() function, which is normally private\n#ifdef LK_CUSTOM_GTSAM_PUBLIC\nvoid BM_gtsamPrivate(benchmark::State &state) {\n    const auto N = state.range(0);\n    state.SetComplexityN(N);\n    // Produce the expression tree\n    gtsam::Values values;\n    auto p1 = Expression<Point3>{'p', 1};\n    auto expr = p1;\n    values.insert(gtsam::Symbol{'p', 1}, Point3{Eigen::Vector3d::Random()});\n\n    for (auto i = 0u; i < N; ++i) {\n        expr = Expression<Point3>{rotate(Expression<Rot3>{'R', i}, expr)};\n        values.insert(gtsam::Symbol{'R', i}, Rot3{wave::randomQuaternion<double>()});\n    }\n    std::vector<gtsam::Matrix> jacs(N + 1);\n\n    for (auto _ : state) {\n        // Pre-allocate and zero VerticalBlockMatrix\n        gtsam::KeyVector keys;\n        gtsam::FastVector<int> dims;\n        boost::tie(keys, dims) = expr.keysAndDims();\n        static const int Dim = gtsam::traits<Point3>::dimension;\n        gtsam::VerticalBlockMatrix Ab(dims, Dim);\n        Ab.matrix().setZero();\n        gtsam::internal::JacobianMap jacobianMap(keys, Ab);\n\n        // Call unsafe version\n        Point3 p2 = expr.valueAndJacobianMap(values, jacobianMap);\n\n        benchmark::DoNotOptimize(p2);\n        benchmark::DoNotOptimize(values);\n        benchmark::DoNotOptimize(jacobianMap);\n    }\n}\nBENCHMARK(BM_gtsamPrivate)->RangeMultiplier(2)->Range(1, 1 << 14)->Complexity();\n#endif\n\nBENCHMARK(BM_gtsamAll)->RangeMultiplier(2)->Range(1, 1 << 14)->Complexity();\nBENCHMARK_MAIN();\n", "meta": {"hexsha": "c30f91bf59aa671201b2ef24f05bbd62c439bba6", "size": 2761, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "benchmarks/rotate_chain/rotate_chain_gtsam_bench.cpp", "max_stars_repo_name": "wavelab/wave_geometry", "max_stars_repo_head_hexsha": "aabcad44a490fc6393b35e63db9ad8908cf46dec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 112.0, "max_stars_repo_stars_event_min_datetime": "2018-05-07T00:57:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T12:14:07.000Z", "max_issues_repo_path": "benchmarks/rotate_chain/rotate_chain_gtsam_bench.cpp", "max_issues_repo_name": "wavelab/wave_geometry", "max_issues_repo_head_hexsha": "aabcad44a490fc6393b35e63db9ad8908cf46dec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2018-08-02T20:10:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T17:45:29.000Z", "max_forks_repo_path": "benchmarks/rotate_chain/rotate_chain_gtsam_bench.cpp", "max_forks_repo_name": "wavelab/wave_geometry", "max_forks_repo_head_hexsha": "aabcad44a490fc6393b35e63db9ad8908cf46dec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2018-05-27T01:08:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T13:46:31.000Z", "avg_line_length": 31.7356321839, "max_line_length": 89, "alphanum_fraction": 0.6602680188, "num_tokens": 798, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825007, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.48264435146548984}}
{"text": "/* Copyright (c) 2015, Julian Straub <jstraub@csail.mit.edu> Licensed\n * under the MIT license.  See the license file LICENSE.\n */\n\n#pragma once\n\n#include <Eigen/Dense>\n\n#include <dpMM/distribution.hpp>\n#include <dpMM/normalSphere.hpp>\n\ntemplate<typename T>\nclass MF : public Distribution<T>\n{\npublic:\n\n//  MF(const Matrix<T,3,3>& R, const NormalSphere<T>& TGs,\n//      boost::mt19937 *pRndGen);\n//  MF();\n  MF(const Matrix<T,3,3>& R, \n      const Cat<T>& pi,\n      const std::vector<NormalSphere<T> >& TGs);\n//      boost::mt19937 *pRndGen);\n  MF(const MF<T>& mf);\n  ~MF();\n\n  T logPdf(const Matrix<T,Dynamic,1>& x) const;\n\n  const Matrix<T,3,3>& R() const {return R_;};\n  const Cat<T>& Pi() const {return pi_;};\n  const Matrix<T,Dynamic,Dynamic>& Sigma(uint32_t j) const\n  {return TGs_[j].Sigma();};\n  const std::vector<NormalSphere<T> >& TGs() const\n  {return TGs_;};\n\n  void print() const;\n\n//  boost::mt19937 *pRndGen_;\nprotected:\n  Matrix<T,3,3> R_;\n  std::vector<NormalSphere<T> > TGs_;\n  Cat<T> pi_;\n};\n\n\n// ------------------------------------------------------\n\n//template<typename T>\n//MF<T>::MF(const Matrix<T,3,3>& R, const NormalSphere<T>& TG,\n//      boost::mt19937 *pRndGen)\n//  : R_(R), TGs_(6,TG), pRndGen_(pRndGen)\n//{};\ntemplate<typename T>\nMF<T>::MF(const Matrix<T,3,3>& R, \n    const Cat<T>& pi,\n    const std::vector<NormalSphere<T> >& TGs)\n//    boost::mt19937 *pRndGen)\n  : Distribution<T>(NULL),\n    R_(R), TGs_(TGs), pi_(pi)\n//  pRndGen_(pRndGen)\n{};\n\n//template<typename T>\n//MF<T>::MF()\n//  : Distribution<T>(NULL),\n//    TGs_(TGs), pi_(pi)\n//{\n//  R_ = Matrix<T,3,3>::Identity();\n//  for(uint32_t k=0; k<6; ++k)\n//    TGs_.push_back(NormalSphere<T>());\n//\n//};\n\ntemplate<typename T>\nMF<T>::MF(const MF<T>& mf)\n  : Distribution<T>(NULL),\n    R_(mf.R()), TGs_(mf.TGs()), pi_(mf.Pi()) //, pRndGen_(mf.pRndGen_)\n{};\n\ntemplate<typename T>\nMF<T>::~MF()\n{};\n\ntemplate<typename T>\nT MF<T>::logPdf(const Matrix<T,Dynamic,1>& x) const\n{\n  Matrix<T,Dynamic,1> logPdf(6);\n  logPdf.fill(0.);\n  for(uint32_t k=0; k<6; ++k)\n  {\n    logPdf(k)= pi_.logPdf(k) + TGs_[k].logPdf(x);\n//    cout<< (pi_.logPdf(k) + TGs_[k].logPdf(x)) << \"\\t\";\n  }\n//  cout<<\" -> \"<<logPdf<<endl;\n  return logSumExp<T>(logPdf);\n};\n\ntemplate<typename T>\nvoid MF<T>::print() const\n{\n  cout<<\" -- MF: R, pi\"<<endl\n    << R_<<endl\n    << pi_.pdf().transpose()<<endl;\n  for(uint32_t k=0; k<6; ++k)\n  {\n    cout<<\"TG \"<<k<<\": \"<< TGs_[k].getMean().transpose()<<endl\n      << TGs_[k].Sigma()<<endl;\n  }\n};\n//template<typename T>\n//MF<T>::()\n//{};\n//template<typename T>\n//MF<T>::()\n//{};\n//template<typename T>\n//MF<T>::()\n//{};\n//template<typename T>\n//MF<T>::()\n//{};\n//template<typename T>\n//MF<T>::()\n//{};\n", "meta": {"hexsha": "17e6b419c6c495ef3c4a601a8dc8240de41951af", "size": 2694, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mmf/mf.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/mmf/mf.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/mmf/mf.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": 21.552, "max_line_length": 70, "alphanum_fraction": 0.5738678545, "num_tokens": 901, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825007, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.48264435146548984}}
{"text": "#include <math.h>\n#include <uWS/uWS.h>\n\n#include <Eigen/Dense>\n#include <boost/format.hpp>\n#include <boost/log/trivial.hpp>\n#include <iostream>\n#include <string>\n\n#include \"json.hpp\"\n#include \"particle_filter.h\"\n\n// for convenience\nusing nlohmann::json;\nusing std::string;\nusing std::vector;\n\n// Checks if the SocketIO event has JSON data.\n// If there is data the JSON object in string format will be returned,\n// else the empty string \"\" will be returned.\nnamespace {\nstring hasData(string s) {\n  auto found_null = s.find(\"null\");\n  auto b1 = s.find_first_of(\"[\");\n  auto b2 = s.find_first_of(\"]\");\n  if (found_null != string::npos) {\n    return \"\";\n  } else if (b1 != string::npos && b2 != string::npos) {\n    return s.substr(b1, b2 - b1 + 1);\n  }\n  return \"\";\n}\n}  // namespace\n\nint main() {\n  uWS::Hub h;\n\n  // Set up parameters here\n  double delta_t = 0.1;      // Time elapsed between measurements [sec]\n  double sensor_range = 50;  // Sensor range [m]\n\n  // GPS measurement uncertainty [x [m], y [m], theta [rad]]\n  const Eigen::Vector3d sigma_pose = {0.3, 0.3, 0.01};\n\n  // Landmark measurement uncertainty [x [m], y [m]]\n  const Eigen::Vector2d sigma_landmark = {0.3, 0.3};\n\n  // Read map data\n  Map map;\n  if (!read_map_data(\"../data/map_data.txt\", map)) {\n    std::cout << \"Error: Could not open map file\" << std::endl;\n    return -1;\n  }\n\n  // Create particle filter\n#ifdef _OPENMP\n  int num_particles = 500;\n  BOOST_LOG_TRIVIAL(info) << \"Found OpenMP, set num_particles to 500\";\n#else\n  int num_particles = 100;\n  BOOST_LOG_TRIVIAL(info) << \"Set num_particles to 100\";\n#endif\n  ParticleFilter pf(num_particles);\n\n  h.onMessage([&pf, &map, &delta_t, &sensor_range, &sigma_pose,\n               &sigma_landmark](uWS::WebSocket<uWS::SERVER> ws, char *data,\n                                size_t length, uWS::OpCode opCode) {\n    // \"42\" at the start of the message means there's a websocket message event.\n    // The 4 signifies a websocket message\n    // The 2 signifies a websocket event\n    if (length && length > 2 && data[0] == '4' && data[1] == '2') {\n      auto s = hasData(string(data));\n\n      if (s != \"\") {\n        auto j = json::parse(s);\n\n        string event = j[0].get<string>();\n\n        if (event == \"telemetry\") {\n          /**\n           * Read sensor measurements\n           */\n          vector<LandmarkObs> noisy_observations;\n\n          // receive noisy observation data from the simulator\n          // sense_observations in JSON format\n          //   [{obs_x,obs_y},{obs_x,obs_y},...{obs_x,obs_y}]\n          string sense_observations_x = j[1][\"sense_observations_x\"];\n          string sense_observations_y = j[1][\"sense_observations_y\"];\n\n          vector<float> x_sense;\n          std::istringstream iss_x(sense_observations_x);\n\n          std::copy(std::istream_iterator<float>(iss_x),\n                    std::istream_iterator<float>(),\n                    std::back_inserter(x_sense));\n\n          vector<float> y_sense;\n          std::istringstream iss_y(sense_observations_y);\n\n          std::copy(std::istream_iterator<float>(iss_y),\n                    std::istream_iterator<float>(),\n                    std::back_inserter(y_sense));\n\n          for (size_t i = 0; i < x_sense.size(); ++i) {\n            LandmarkObs obs;\n            obs.x = x_sense[i];\n            obs.y = y_sense[i];\n            noisy_observations.push_back(obs);\n          }\n\n          /**\n           * Particle filter initialization and motion predictions\n           *\n           * This step will update the states of all particles.\n           */\n\n          // j[1] is the data JSON object\n          if (!pf.initialized()) {\n            // NOTE: Simulator generates GPS data.\n            // Sense noisy position data from the simulator\n            double sense_x = std::stod(j[1][\"sense_x\"].get<string>());\n            double sense_y = std::stod(j[1][\"sense_y\"].get<string>());\n            double sense_theta = std::stod(j[1][\"sense_theta\"].get<string>());\n\n            pf.init(sense_x, sense_y, sense_theta, sigma_pose);\n          } else {\n            // Predict the vehicle's next state from previous\n            //   (noiseless control) data.\n            double previous_velocity =\n                std::stod(j[1][\"previous_velocity\"].get<string>());\n            double previous_yawrate =\n                std::stod(j[1][\"previous_yawrate\"].get<string>());\n\n            pf.prediction(delta_t, sigma_pose, previous_velocity,\n                          previous_yawrate);\n          }\n\n          // Update the weights and resample\n          // BOOST_LOG_TRIVIAL(info)\n          //     << \"Received new sensor measurements, will update particles.\";\n\n          /**\n           * Update posterior probalities of all particles and update their\n           * weights\n           */\n          pf.updateWeights(sensor_range, sigma_landmark, noisy_observations,\n                           map);\n\n          /**\n           * Resample the particles using the new weights\n           */\n          pf.resample();\n\n          /**\n           * Select the best particle with maximum weights\n           */\n\n          // Calculate and output the average weighted error of the particle\n          //   filter over all time steps so far.\n          vector<Particle> particles = pf.particles;\n          int num_particles = particles.size();\n          double highest_weight = -std::numeric_limits<double>::infinity();\n          double weight_sum = 0.0;\n          int bestIndex = -1;\n          for (int i = 0; i < num_particles; ++i) {\n            if (particles[i].weight > highest_weight) {\n              highest_weight = particles[i].weight;\n              bestIndex = i;\n            }\n            weight_sum += particles[i].weight;\n          }\n\n          const Particle &best_particle = particles[bestIndex];\n\n          BOOST_LOG_TRIVIAL(info)\n              << (boost::format(\n                      \"bestIndex: %d, highest w: %.3f, average w: %.3f\") %\n                  bestIndex % highest_weight % (weight_sum / num_particles))\n                     .str();\n\n          /**\n           * Send result message to remote simulator\n           */\n          json msgJson;\n          msgJson[\"best_particle_x\"] = best_particle.x;\n          msgJson[\"best_particle_y\"] = best_particle.y;\n          msgJson[\"best_particle_theta\"] = best_particle.theta;\n\n          // Optional message data used for debugging particle's sensing\n          //   and associations\n          msgJson[\"best_particle_associations\"] =\n              pf.getAssociations(best_particle);\n          msgJson[\"best_particle_sense_x\"] =\n              pf.getSenseCoord(best_particle, \"X\");\n          msgJson[\"best_particle_sense_y\"] =\n              pf.getSenseCoord(best_particle, \"Y\");\n\n          auto msg = \"42[\\\"best_particle\\\",\" + msgJson.dump() + \"]\";\n          // BOOST_LOG_TRIVIAL(debug) << msg;\n          ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT);\n        }  // end \"telemetry\" if\n      } else {\n        string msg = \"42[\\\"manual\\\",{}]\";\n        ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT);\n      }\n    }  // end websocket message if\n  });  // end h.onMessage\n\n  h.onConnection([&h](uWS::WebSocket<uWS::SERVER> ws, uWS::HttpRequest req) {\n    BOOST_LOG_TRIVIAL(info)\n        << \"Connected to simulator. Waiting for start command.\";\n  });\n\n  h.onDisconnection([&h](uWS::WebSocket<uWS::SERVER> ws, int code,\n                         char *message, size_t length) {\n    ws.close();\n    BOOST_LOG_TRIVIAL(info) << \"Disconnected from simulator.\";\n  });\n\n  int port = 4567;\n  if (h.listen(port)) {\n    BOOST_LOG_TRIVIAL(info)\n        << \"Particle filter server started, listening to port: \" << port;\n  } else {\n    std::cerr << \"Failed to listen to port\" << std::endl;\n    return -1;\n  }\n\n  h.run();\n}", "meta": {"hexsha": "883682cc543639a9b966919e25d944abe6c93218", "size": 7754, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.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/main.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/main.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.5670995671, "max_line_length": 80, "alphanum_fraction": 0.5704152695, "num_tokens": 1844, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825007, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.48264435146548984}}
{"text": "#pragma once\n\n#include \"modprop/compo/Interfaces.h\"\n\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/bernoulli_distribution.hpp>\n#include <boost/random/random_device.hpp>\n\nnamespace percepto\n{\n\nclass DropoutLayer :\npublic Source<VectorType>\n{\npublic:\n\n\tenum DropoutMode\n\t{\n\t\tDROPOUT_ENABLE,\n\t\tDROPOUT_DISABLE\n\t};\n\n\ttypedef Source<VectorType> SourceType;\n\ttypedef VectorType InputType;\n\ttypedef VectorType OutputType;\n\n\tDropoutLayer() \n\t: _inputPort( this ),\n\t  _mode( DROPOUT_DISABLE )\n\t{}\n\n\tDropoutLayer( double p ) \n\t: _inputPort( this ), _distribution( p ),\n\t  _mode( DROPOUT_DISABLE ), _p( p )\n\t{}\n\n\tDropoutLayer( const DropoutLayer& other )\n\t: _inputPort( this ), _distribution( other._distribution ),\n\t  _p( other._P )\n\t{\n\t\tSetDropoutMode( other._mode );\n\t}\n\n\tvoid SetDropoutMode( void DropoutMode mode )\n\t{\n\t\t_mode = mode;\n\t\tif( _mode == DROPOUT_ENABLE )\n\t\t{\n\t\t\tboost::random_device rng;\n\t\t\t_distribution.seed( rng );\n\t\t}\n\t}\n\n\tvoid Resample()\n\t{\n\t\tif( _mode == DROPOUT_DISABLE )\n\t\t{\n\t\t\t_mask.SetConstant( _p );\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfor( unsigned int i = 0; i < _mask.size(); ++i )\n\t\t\t{\n\t\t\t\t_mask(i) = _distribution( _generator ) ? 1.0 : 0.0;\n\t\t\t}\n\t\t}\n\t}\n\n\tvirtual void Foreprop()\n\t{\n\t\tVectorType input = _inputPort.GetInput();\n\t\t\n\t\tif( _mask.size() == 0 )\n\t\t{\n\t\t\t_mask = VectorType::Ones( input.size() );\n\t\t}\n\n\t\tVectorType output = ( input.array() * _mask.array() ).matrix();\n\t\tSourceType::SetOutput( output );\n\t\tSourceType::Foreprop();\n\t}\n\n\tvirtual void BackpropImplementation( const MatrixType& nextDodx )\n\t{\n\t\tMatrixType dodx = nextDodx;\n\t\tfor( unsigned int i = 0; i < dodx.rows(); ++i )\n\t\t{\n\t\t\tVectorType row = dodx.row(i);\n\t\t\tdodx.row(i) = ( row.array() * _mask.array() ).\n\t\t}\n\t}\n\nprivate:\n\n\tSink<VectorType> _inputPort;\n\tVectorType _mask;\n\tDropoutMode _mode;\n\tdouble _p;\n\n\tboost::mt19937 _generator;\n\tboost::bernoulli_distribution<double> _distribution;\n\n};\n\n}", "meta": {"hexsha": "3a0644c2f5390a14744004541f282cb85e4538cf", "size": 1890, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/modprop/neural/DropoutLayer.hpp", "max_stars_repo_name": "Humhu/modprop", "max_stars_repo_head_hexsha": "0cff8240d5e1522f620de8004c22a74491a0c9fb", "max_stars_repo_licenses": ["AFL-3.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-11-10T00:54:53.000Z", "max_stars_repo_stars_event_max_datetime": "2017-11-10T00:54:53.000Z", "max_issues_repo_path": "include/modprop/neural/DropoutLayer.hpp", "max_issues_repo_name": "Humhu/modprop", "max_issues_repo_head_hexsha": "0cff8240d5e1522f620de8004c22a74491a0c9fb", "max_issues_repo_licenses": ["AFL-3.0"], "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/modprop/neural/DropoutLayer.hpp", "max_forks_repo_name": "Humhu/modprop", "max_forks_repo_head_hexsha": "0cff8240d5e1522f620de8004c22a74491a0c9fb", "max_forks_repo_licenses": ["AFL-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.0, "max_line_length": 66, "alphanum_fraction": 0.6687830688, "num_tokens": 574, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825006, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.48264435146548973}}
{"text": "/**\n* \\file NormalInitializer.hpp\n*\n* \\brief Glorot normal initializer, as described in http://jmlr.org/proceedings/papers/v9/glorot10a/glorot10a.pdf\n*\n* \\date   Jun 20, 2018\n* \\author Mathias B\u00f8gh Stokholm\n*/\n\n#ifndef NEURAL_NORMALINITIALIZER_HPP\n#define NEURAL_NORMALINITIALIZER_HPP\n\n#include <Eigen/Core>\n#include <random>\n\nnamespace neural {\n    /**\n     * @brief Glorot normal initializer (also called Xavier normal initializer)\n     * Draws samples from a truncated normal distribution centered on 0 with the std deviation set according to the\n     * number of inputs and outputs.\n     * @tparam Dtype: The data type to generate samples as\n     * @tparam FanIn: The number of input units of the tensor to generate weights for\n     * @tparam FanOut: The number of output units of the tensor to generate weights for\n     */\n    template <typename Dtype, unsigned int FanIn, unsigned int FanOut>\n    class GlorotNormal {\n    public:\n        GlorotNormal(): m_distribution(0.0, std::sqrt(2.0 / (FanIn + FanOut))) {}\n        GlorotNormal(const GlorotNormal&) = default;\n\n        Dtype operator()(Eigen::DenseIndex element_location, Eigen::DenseIndex /*unused*/ = 0) const {\n            // FIXME: This is massively hacky and ugly\n            auto* nonConstThis = const_cast<GlorotNormal*>(this);\n            return Dtype(nonConstThis->m_distribution(nonConstThis->m_generator));\n        }\n\n    private:\n        std::mt19937 m_generator;\n        std::normal_distribution<double> m_distribution;\n    };\n}\n\n#endif //NEURAL_NORMALINITIALIZER_HPP\n", "meta": {"hexsha": "5f25cee94bdbb906cd0593a93d24415002164821", "size": 1542, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/neural/initializers/GlorotNormal.hpp", "max_stars_repo_name": "MathiasStokholm/neural", "max_stars_repo_head_hexsha": "a187bfc1bc53509c6c7253960817bf381bda438c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-06-20T21:10:21.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-20T21:10:21.000Z", "max_issues_repo_path": "include/neural/initializers/GlorotNormal.hpp", "max_issues_repo_name": "MathiasStokholm/neural", "max_issues_repo_head_hexsha": "a187bfc1bc53509c6c7253960817bf381bda438c", "max_issues_repo_licenses": ["MIT"], "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/neural/initializers/GlorotNormal.hpp", "max_forks_repo_name": "MathiasStokholm/neural", "max_forks_repo_head_hexsha": "a187bfc1bc53509c6c7253960817bf381bda438c", "max_forks_repo_licenses": ["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.0454545455, "max_line_length": 115, "alphanum_fraction": 0.7003891051, "num_tokens": 382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825006, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.48264435146548973}}
{"text": "/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\\n|  Phycas: Python software for phylogenetic analysis                          |\n|  Copyright (C) 2006 Mark T. Holder, Paul O. Lewis and David L. Swofford     |\n|                                                                             |\n|  This program is free software; you can redistribute it and/or modify       |\n|  it under the terms of the GNU General Public License as published by       |\n|  the Free Software Foundation; either version 2 of the License, or          |\n|  (at your option) any later version.                                        |\n|                                                                             |\n|  This program is distributed in the hope that it will be useful,            |\n|  but WITHOUT ANY WARRANTY; without even the implied warranty of             |\n|  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the              |\n|  GNU General Public License for more details.                               |\n|                                                                             |\n|  You should have received a copy of the GNU General Public License along    |\n|  with this program; if not, write to the Free Software Foundation, Inc.,    |\n|  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.                |\n\\~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n\n#if ! defined(DIRICHLET_MOVE_HPP)\n#define DIRICHLET_MOVE_HPP\n\n#include <vector>\t\t\t\t\t\t\t\t\t// for std::vector\n#include <boost/shared_ptr.hpp>\t\t\t\t\t\t// for boost::shared_ptr\n#include <boost/weak_ptr.hpp>\t\t\t\t\t\t// for boost::weak_ptr\n#include \"mcmc_updater.hpp\"\t\t// for base class MCMCUpdater\n#include \"partition_model.hpp\"\t\t// for PartitionModelShPtr definition\n#include \"multivariate_probability_distribution.hpp\"\n\nnamespace phycas\n{\n\nclass MCMCChainManager;\ntypedef boost::weak_ptr<MCMCChainManager>\t\t\tChainManagerWkPtr;\n\ntypedef boost::shared_ptr<DirichletDistribution>    DirichletShPtr;\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tA DirichletMove proposes new parameter values that are slightly different than the current parameter values by\n|   sampling from a Dirichlet distribution with parameters equal to the current frequencies multiplied by a large\n|   value (the tuning parameter 'psi').\n*/\nclass DirichletMove : public MCMCUpdater\n\t{\n\tpublic:\n\t\t\t\t\t\t\t\t\tDirichletMove();\n\t\t\t\t\t\t\t\t\tvirtual ~DirichletMove()\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t//std::cerr << \"DirichletMove dying...\" << std::endl;\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t// Accessors\n\t\tdouble\t\t\t\t\t\tgetTuningParameter() const;\n\t\tunsigned\t\t\t\t\tgetDimension() const;\n\n\n\t\t// Modifiers\n\t\tvoid\t\t\t\t\t\tsetTuningParameter(double x);\n\t\tvoid\t\t\t\t\t\tsetMaxPsi(double x);\n\t\tvoid\t\t\t\t\t\tsetMinPsi(double x);\n\t\tvoid\t\t\t\t\t\tsetDimension(unsigned d);\n\n\t\t// Utilities\n\t\tvoid\t\t\t\t\t\treset();\n\t\tvirtual void\t\t\t\tsendCurrValuesToModel(const double_vect_t & v) {}\n\t\tvirtual void\t\t\t\tgetCurrValuesFromModel(double_vect_t & v) const {}\n\t\tvirtual double_vect_t\t\tlistCurrValuesFromModel();\n        virtual void                getParams() {}\n        virtual void                setParams(const std::vector<double> & v) {}\n\n\t\t// These are virtual functions in the MCMCUpdater base class\n\t\tvirtual bool\t\t\t\tupdate();\n\t\tvirtual double\t\t\t\tgetLnHastingsRatio() const;\n\t\tvirtual double\t\t\t\tgetLnJacobian() const;\n\t\tvirtual void\t\t\t\tproposeNewState();\n\t\tvirtual void\t\t\t\trevert();\n\t\tvirtual void\t\t\t\taccept();\n\n\tprivate:\n\n\t\tDirichletMove &\t\t\t\toperator=(const DirichletMove &);\t// never use - don't define\n\n\tprotected:\n\n\t\tunsigned\t\t\t\t\tdim;\t\t\t/**< The number of parameters governed by this move */\n\t\tdouble\t\t\t\t\t\tpsi;\t\t\t/**< Larger values result in changes of smaller magnitude */\n\t\tstd::vector<double> \t\tnew_params;\t    /**< Proposed new parameter values */\n\t\tstd::vector<double> \t\torig_params;\t/**< Saved parameter values (in case revert is necessary) */\n\t\tstd::vector<double> \t\tc_forward;\t    /**< Dirichlet parameter vector used to propose new frequencies */\n\t\tstd::vector<double> \t\tc_reverse;\t    /**< Dirichlet parameter vector used to propose original frequencies (only used to compute Hastings ratio) */\n        DirichletShPtr              dir_forward;    /**< Points to an ad hoc Dirichlet distribution object used to assess the forward move density and to propose a new frequency vector */\n        DirichletShPtr              dir_reverse;    /**< Points to an ad hoc Dirichlet distribution object used to assess the reverse move density */\n\t};\n\n} // namespace phycas\n\n#endif\n", "meta": {"hexsha": "ea5267ce8c5528999d69767133dff78cbc4ad9a3", "size": 4583, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/cpp/dirichlet_move.hpp", "max_stars_repo_name": "plewis/phycas", "max_stars_repo_head_hexsha": "9f5a4d9b2342dab907d14a46eb91f92ad80a5605", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-09-24T23:12:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-12T07:07:01.000Z", "max_issues_repo_path": "src/cpp/dirichlet_move.hpp", "max_issues_repo_name": "plewis/phycas", "max_issues_repo_head_hexsha": "9f5a4d9b2342dab907d14a46eb91f92ad80a5605", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cpp/dirichlet_move.hpp", "max_forks_repo_name": "plewis/phycas", "max_forks_repo_head_hexsha": "9f5a4d9b2342dab907d14a46eb91f92ad80a5605", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-11-23T10:35:43.000Z", "max_forks_repo_forks_event_max_datetime": "2015-11-23T10:35:43.000Z", "avg_line_length": 46.7653061224, "max_line_length": 187, "alphanum_fraction": 0.5954614881, "num_tokens": 967, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4826443451363598}}
{"text": "/*\n    Copyright 2005-2007 Adobe Systems Incorporated\n\n    Use, modification and distribution are subject to the Boost Software License,\n    Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n    http://www.boost.org/LICENSE_1_0.txt).\n\n    See http://opensource.adobe.com/gil for most recent version including documentation.\n*/\n\n/*************************************************************************************************/\n\n///////////////////////\n////  NOTE: This sample file uses the numeric extension, which does not come with the Boost distribution.\n////  You may download it from http://opensource.adobe.com/gil\n///////////////////////\n\n/// \\file\n/// \\brief Test file for resample_pixels() in the numeric extension\n/// \\author Lubomir Bourdev and Hailin Jin\n/// \\date February 27, 2007\n\n#include <boost/gil/image.hpp>\n#include <boost/gil/typedefs.hpp>\n#include <boost/gil/extension/io/jpeg_io.hpp>\n#include <boost/gil/extension/numeric/sampler.hpp>\n#include <boost/gil/extension/numeric/resample.hpp>\n\nint main() {\n    using namespace boost::gil;\n\n    rgb8_image_t img;\n    jpeg_read_image(\"test.jpg\",img);\n\n    // test resample_pixels\n    // Transform the image by an arbitrary affine transformation using nearest-neighbor resampling\n    rgb8_image_t transf(rgb8_image_t::point_t(view(img).dimensions()*2));\n    fill_pixels(view(transf),rgb8_pixel_t(255,0,0));    // the background is red\n\n    matrix3x2<double> mat = matrix3x2<double>::get_translate(-point2<double>(200,250)) *\n                            matrix3x2<double>::get_rotate(-15*3.14/180.0);\n    resample_pixels(const_view(img), view(transf), mat, nearest_neighbor_sampler());\n    jpeg_write_view(\"out-affine.jpg\", view(transf));\n\n    return 0;\n}\n", "meta": {"hexsha": "c65baf39b276ac234e603fe4bcb0a8e57923ba62", "size": 1733, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/libs/gil/example/affine.cpp", "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/libs/gil/example/affine.cpp", "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/libs/gil/example/affine.cpp", "max_forks_repo_name": "Bpowers4/turicreate", "max_forks_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 36.8723404255, "max_line_length": 105, "alphanum_fraction": 0.6583958454, "num_tokens": 406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4826443451363598}}
{"text": "//\n// Copyright \u00a9 2017 Arm Ltd. All rights reserved.\n// SPDX-License-Identifier: MIT\n//\n\n#include \"DetectionPostProcess.hpp\"\n\n#include <armnn/utility/Assert.hpp>\n\n#include <boost/numeric/conversion/cast.hpp>\n\n#include <algorithm>\n#include <numeric>\n\nnamespace armnn\n{\n\nstd::vector<unsigned int> GenerateRangeK(unsigned int k)\n{\n    std::vector<unsigned int> range(k);\n    std::iota(range.begin(), range.end(), 0);\n    return range;\n}\n\nvoid TopKSort(unsigned int k, unsigned int* indices, const float* values, unsigned int numElement)\n{\n    std::partial_sort(indices, indices + k, indices + numElement,\n                      [&values](unsigned int i, unsigned int j) { return values[i] > values[j]; });\n}\n\nfloat IntersectionOverUnion(const float* boxI, const float* boxJ)\n{\n    // Box-corner format: ymin, xmin, ymax, xmax.\n    const int yMin = 0;\n    const int xMin = 1;\n    const int yMax = 2;\n    const int xMax = 3;\n    float areaI = (boxI[yMax] - boxI[yMin]) * (boxI[xMax] - boxI[xMin]);\n    float areaJ = (boxJ[yMax] - boxJ[yMin]) * (boxJ[xMax] - boxJ[xMin]);\n    float yMinIntersection = std::max(boxI[yMin], boxJ[yMin]);\n    float xMinIntersection = std::max(boxI[xMin], boxJ[xMin]);\n    float yMaxIntersection = std::min(boxI[yMax], boxJ[yMax]);\n    float xMaxIntersection = std::min(boxI[xMax], boxJ[xMax]);\n    float areaIntersection = std::max(yMaxIntersection - yMinIntersection, 0.0f) *\n                                std::max(xMaxIntersection - xMinIntersection, 0.0f);\n    float areaUnion = areaI + areaJ - areaIntersection;\n    return areaIntersection / areaUnion;\n}\n\nstd::vector<unsigned int> NonMaxSuppression(unsigned int numBoxes,\n                                            const std::vector<float>& boxCorners,\n                                            const std::vector<float>& scores,\n                                            float nmsScoreThreshold,\n                                            unsigned int maxDetection,\n                                            float nmsIouThreshold)\n{\n    // Select boxes that have scores above a given threshold.\n    std::vector<float> scoresAboveThreshold;\n    std::vector<unsigned int> indicesAboveThreshold;\n    for (unsigned int i = 0; i < numBoxes; ++i)\n    {\n        if (scores[i] >= nmsScoreThreshold)\n        {\n            scoresAboveThreshold.push_back(scores[i]);\n            indicesAboveThreshold.push_back(i);\n        }\n    }\n\n    // Sort the indices based on scores.\n    unsigned int numAboveThreshold = boost::numeric_cast<unsigned int>(scoresAboveThreshold.size());\n    std::vector<unsigned int> sortedIndices = GenerateRangeK(numAboveThreshold);\n    TopKSort(numAboveThreshold, sortedIndices.data(), scoresAboveThreshold.data(), numAboveThreshold);\n\n    // Number of output cannot be more than max detections specified in the option.\n    unsigned int numOutput = std::min(maxDetection, numAboveThreshold);\n    std::vector<unsigned int> outputIndices;\n    std::vector<bool> visited(numAboveThreshold, false);\n\n    // Prune out the boxes with high intersection over union by keeping the box with higher score.\n    for (unsigned int i = 0; i < numAboveThreshold; ++i)\n    {\n        if (outputIndices.size() >= numOutput)\n        {\n            break;\n        }\n        if (!visited[sortedIndices[i]])\n        {\n            outputIndices.push_back(indicesAboveThreshold[sortedIndices[i]]);\n        }\n        for (unsigned int j = i + 1; j < numAboveThreshold; ++j)\n        {\n            unsigned int iIndex = indicesAboveThreshold[sortedIndices[i]] * 4;\n            unsigned int jIndex = indicesAboveThreshold[sortedIndices[j]] * 4;\n            if (IntersectionOverUnion(&boxCorners[iIndex], &boxCorners[jIndex]) > nmsIouThreshold)\n            {\n                visited[sortedIndices[j]] = true;\n            }\n        }\n    }\n    return outputIndices;\n}\n\nvoid AllocateOutputData(unsigned int numOutput,\n                        unsigned int numSelected,\n                        const std::vector<float>& boxCorners,\n                        const std::vector<unsigned int>& outputIndices,\n                        const std::vector<unsigned int>& selectedBoxes,\n                        const std::vector<unsigned int>& selectedClasses,\n                        const std::vector<float>& selectedScores,\n                        float* detectionBoxes,\n                        float* detectionScores,\n                        float* detectionClasses,\n                        float* numDetections)\n{\n    for (unsigned int i = 0; i < numOutput; ++i)\n        {\n            unsigned int boxIndex = i * 4;\n            if (i < numSelected)\n            {\n                unsigned int boxCornorIndex = selectedBoxes[outputIndices[i]] * 4;\n                detectionScores[i] = selectedScores[outputIndices[i]];\n                detectionClasses[i] = boost::numeric_cast<float>(selectedClasses[outputIndices[i]]);\n                detectionBoxes[boxIndex] = boxCorners[boxCornorIndex];\n                detectionBoxes[boxIndex + 1] = boxCorners[boxCornorIndex + 1];\n                detectionBoxes[boxIndex + 2] = boxCorners[boxCornorIndex + 2];\n                detectionBoxes[boxIndex + 3] = boxCorners[boxCornorIndex + 3];\n            }\n            else\n            {\n                detectionScores[i] = 0.0f;\n                detectionClasses[i] = 0.0f;\n                detectionBoxes[boxIndex] = 0.0f;\n                detectionBoxes[boxIndex + 1] = 0.0f;\n                detectionBoxes[boxIndex + 2] = 0.0f;\n                detectionBoxes[boxIndex + 3] = 0.0f;\n            }\n        }\n        numDetections[0] = boost::numeric_cast<float>(numSelected);\n}\n\nvoid DetectionPostProcess(const TensorInfo& boxEncodingsInfo,\n                          const TensorInfo& scoresInfo,\n                          const TensorInfo& anchorsInfo,\n                          const TensorInfo& detectionBoxesInfo,\n                          const TensorInfo& detectionClassesInfo,\n                          const TensorInfo& detectionScoresInfo,\n                          const TensorInfo& numDetectionsInfo,\n                          const DetectionPostProcessDescriptor& desc,\n                          Decoder<float>& boxEncodings,\n                          Decoder<float>& scores,\n                          Decoder<float>& anchors,\n                          float* detectionBoxes,\n                          float* detectionClasses,\n                          float* detectionScores,\n                          float* numDetections)\n{\n    IgnoreUnused(anchorsInfo, detectionClassesInfo, detectionScoresInfo, numDetectionsInfo);\n\n    // Transform center-size format which is (ycenter, xcenter, height, width) to box-corner format,\n    // which represents the lower left corner and the upper right corner (ymin, xmin, ymax, xmax)\n    std::vector<float> boxCorners(boxEncodingsInfo.GetNumElements());\n\n    const unsigned int numBoxes  = boxEncodingsInfo.GetShape()[1];\n    const unsigned int numScores = scoresInfo.GetNumElements();\n\n    for (unsigned int i = 0; i < numBoxes; ++i)\n    {\n        // Y\n        float boxEncodingY = boxEncodings.Get();\n        float anchorY      = anchors.Get();\n\n        ++boxEncodings;\n        ++anchors;\n\n        // X\n        float boxEncodingX = boxEncodings.Get();\n        float anchorX      = anchors.Get();\n\n        ++boxEncodings;\n        ++anchors;\n\n        // H\n        float boxEncodingH = boxEncodings.Get();\n        float anchorH      = anchors.Get();\n\n        ++boxEncodings;\n        ++anchors;\n\n        // W\n        float boxEncodingW = boxEncodings.Get();\n        float anchorW      = anchors.Get();\n\n        ++boxEncodings;\n        ++anchors;\n\n        float yCentre = boxEncodingY / desc.m_ScaleY * anchorH + anchorY;\n        float xCentre = boxEncodingX / desc.m_ScaleX * anchorW + anchorX;\n\n        float halfH = 0.5f * expf(boxEncodingH / desc.m_ScaleH) * anchorH;\n        float halfW = 0.5f * expf(boxEncodingW / desc.m_ScaleW) * anchorW;\n\n        unsigned int indexY = i * 4;\n        unsigned int indexX = indexY + 1;\n        unsigned int indexH = indexX + 1;\n        unsigned int indexW = indexH + 1;\n\n        // ymin\n        boxCorners[indexY] = yCentre - halfH;\n        // xmin\n        boxCorners[indexX] = xCentre - halfW;\n        // ymax\n        boxCorners[indexH] = yCentre + halfH;\n        // xmax\n        boxCorners[indexW] = xCentre + halfW;\n\n        ARMNN_ASSERT(boxCorners[indexY] < boxCorners[indexH]);\n        ARMNN_ASSERT(boxCorners[indexX] < boxCorners[indexW]);\n    }\n\n    unsigned int numClassesWithBg = desc.m_NumClasses + 1;\n\n    // Decode scores\n    std::vector<float> decodedScores;\n    decodedScores.reserve(numScores);\n\n    for (unsigned int i = 0u; i < numScores; ++i)\n    {\n        decodedScores.emplace_back(scores.Get());\n        ++scores;\n    }\n\n    // Perform Non Max Suppression.\n    if (desc.m_UseRegularNms)\n    {\n        // Perform Regular NMS.\n        // For each class, perform NMS and select max detection numbers of the highest score across all classes.\n        std::vector<float> classScores(numBoxes);\n\n        std::vector<unsigned int> selectedBoxesAfterNms;\n        selectedBoxesAfterNms.reserve(numBoxes);\n\n        std::vector<float> selectedScoresAfterNms;\n        selectedBoxesAfterNms.reserve(numScores);\n\n        std::vector<unsigned int> selectedClasses;\n\n        for (unsigned int c = 0; c < desc.m_NumClasses; ++c)\n        {\n            // For each boxes, get scores of the boxes for the class c.\n            for (unsigned int i = 0; i < numBoxes; ++i)\n            {\n                classScores[i] = decodedScores[i * numClassesWithBg + c + 1];\n            }\n            std::vector<unsigned int> selectedIndices = NonMaxSuppression(numBoxes,\n                                                                          boxCorners,\n                                                                          classScores,\n                                                                          desc.m_NmsScoreThreshold,\n                                                                          desc.m_DetectionsPerClass,\n                                                                          desc.m_NmsIouThreshold);\n\n            for (unsigned int i = 0; i < selectedIndices.size(); ++i)\n            {\n                selectedBoxesAfterNms.push_back(selectedIndices[i]);\n                selectedScoresAfterNms.push_back(classScores[selectedIndices[i]]);\n                selectedClasses.push_back(c);\n            }\n        }\n\n        // Select max detection numbers of the highest score across all classes\n        unsigned int numSelected = boost::numeric_cast<unsigned int>(selectedBoxesAfterNms.size());\n        unsigned int numOutput = std::min(desc.m_MaxDetections,  numSelected);\n\n        // Sort the max scores among the selected indices.\n        std::vector<unsigned int> outputIndices = GenerateRangeK(numSelected);\n        TopKSort(numOutput, outputIndices.data(), selectedScoresAfterNms.data(), numSelected);\n\n        AllocateOutputData(detectionBoxesInfo.GetShape()[1], numOutput, boxCorners, outputIndices,\n                           selectedBoxesAfterNms, selectedClasses, selectedScoresAfterNms,\n                           detectionBoxes, detectionScores, detectionClasses, numDetections);\n    }\n    else\n    {\n        // Perform Fast NMS.\n        // Select max scores of boxes and perform NMS on max scores,\n        // select max detection numbers of the highest score\n        unsigned int numClassesPerBox = std::min(desc.m_MaxClassesPerDetection, desc.m_NumClasses);\n        std::vector<float> maxScores;\n        std::vector<unsigned int>boxIndices;\n        std::vector<unsigned int>maxScoreClasses;\n\n        for (unsigned int box = 0; box < numBoxes; ++box)\n        {\n            unsigned int scoreIndex = box * numClassesWithBg + 1;\n\n            // Get the max scores of the box.\n            std::vector<unsigned int> maxScoreIndices = GenerateRangeK(desc.m_NumClasses);\n            TopKSort(numClassesPerBox, maxScoreIndices.data(),\n                decodedScores.data() + scoreIndex, desc.m_NumClasses);\n\n            for (unsigned int i = 0; i < numClassesPerBox; ++i)\n            {\n                maxScores.push_back(decodedScores[scoreIndex + maxScoreIndices[i]]);\n                maxScoreClasses.push_back(maxScoreIndices[i]);\n                boxIndices.push_back(box);\n            }\n        }\n\n        // Perform NMS on max scores\n        std::vector<unsigned int> selectedIndices = NonMaxSuppression(numBoxes, boxCorners, maxScores,\n                                                                      desc.m_NmsScoreThreshold,\n                                                                      desc.m_MaxDetections,\n                                                                      desc.m_NmsIouThreshold);\n\n        unsigned int numSelected = boost::numeric_cast<unsigned int>(selectedIndices.size());\n        unsigned int numOutput = std::min(desc.m_MaxDetections,  numSelected);\n\n        AllocateOutputData(detectionBoxesInfo.GetShape()[1], numOutput, boxCorners, selectedIndices,\n                           boxIndices, maxScoreClasses, maxScores,\n                           detectionBoxes, detectionScores, detectionClasses, numDetections);\n    }\n}\n\n} // namespace armnn\n", "meta": {"hexsha": "61a504ec6b1d0d26cc17fc4c57a4295a4f682071", "size": 13250, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/backends/reference/workloads/DetectionPostProcess.cpp", "max_stars_repo_name": "muthukumaravel7/armnn", "max_stars_repo_head_hexsha": "879ec231203df5b0a94462c0b247dc7d8d8a7a44", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/backends/reference/workloads/DetectionPostProcess.cpp", "max_issues_repo_name": "muthukumaravel7/armnn", "max_issues_repo_head_hexsha": "879ec231203df5b0a94462c0b247dc7d8d8a7a44", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/backends/reference/workloads/DetectionPostProcess.cpp", "max_forks_repo_name": "muthukumaravel7/armnn", "max_forks_repo_head_hexsha": "879ec231203df5b0a94462c0b247dc7d8d8a7a44", "max_forks_repo_licenses": ["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.8950617284, "max_line_length": 112, "alphanum_fraction": 0.5764528302, "num_tokens": 2856, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4826443451363598}}
{"text": "//          Copyright Rein Halbersma 2010-2020.\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 <core/board/group.hpp>         // axioms::is_realized, make\n#include <dctl/core/board/angle.hpp>    // _deg, inverse, rotate\n#include <boost/test/unit_test.hpp>     // BOOST_AUTO_TEST_SUITE, BOOST_AUTO_TEST_SUITE_END, BOOST_AUTO_TEST_CASE, BOOST_CHECK\n#include <algorithm>                    // all_of\n#include <type_traits>                  // common_type\n#include <vector>                       // vector\n\nusing namespace dctl::core;\nusing namespace literals;\n\nBOOST_AUTO_TEST_SUITE(GroupCyclic)\n\nBOOST_AUTO_TEST_CASE(GroupAxiomsAreRealizedOnCyclicGroups)\n{\n        constexpr auto op = [](auto i, auto j) { return rotate(i, j); };\n        constexpr auto inv = [](auto i) { return inverse(i); };\n\n        auto const C1 = make_group(\n                { 0_deg },\n                op, inv\n        );\n\n        auto const C2 = make_group(\n                { 0_deg, 180_deg },\n                op, inv\n        );\n\n        auto const C4 = make_group(\n                { 0_deg,  90_deg, 180_deg, 270_deg },\n                op, inv\n        );\n\n        auto const C8 = make_group(\n                {   0_deg,  45_deg,  90_deg, 135_deg,\n                  180_deg, 225_deg, 270_deg, 315_deg },\n                op, inv\n        );\n\n        using CyclicGroup = std::common_type_t<decltype(C1), decltype(C2), decltype(C4), decltype(C8)>;\n\n        auto const C_N = std::vector<CyclicGroup>\n        {\n                C1, C2, C4, C8\n        };\n\n        BOOST_CHECK(\n                std::all_of(C_N.begin(), C_N.end(), [](auto const& g) {\n                        return group::axioms::is_realized(g);\n                })\n        );\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "a374e5b8dc4a17ba63c62742fca3ad8a045645a4", "size": 1863, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/src/core/board/cyclic.cpp", "max_stars_repo_name": "sagarpant1/dctl", "max_stars_repo_head_hexsha": "b858fa139159eff73e8f3eec32da93ba077e0bd3", "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": "test/src/core/board/cyclic.cpp", "max_issues_repo_name": "sagarpant1/dctl", "max_issues_repo_head_hexsha": "b858fa139159eff73e8f3eec32da93ba077e0bd3", "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/src/core/board/cyclic.cpp", "max_forks_repo_name": "sagarpant1/dctl", "max_forks_repo_head_hexsha": "b858fa139159eff73e8f3eec32da93ba077e0bd3", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-27T14:19:28.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-27T14:19:28.000Z", "avg_line_length": 31.5762711864, "max_line_length": 126, "alphanum_fraction": 0.5512614063, "num_tokens": 464, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4826443451363598}}
{"text": "#include \"shape.hpp\"\n#include <cmath>\n#include <boost/math/constants/constants.hpp>\n\nnamespace bg = boost::geometry;\n\nconst double pi = boost::math::constants::pi<double>();\nconst int earthRadius = 6378137;\n\n// Registers a bounding box\nShape::Shape(std::string id_, box const& b) {\n  type = ShapeType::bbox;\n  id = id_;\n  envelope = b;\n}\n\n// Registers a circle\nShape::Shape(std::string id_, point const& p, double radius) {\n  type = ShapeType::circle;\n  id = id_;\n  envelope = envelopeFromCircle(p, radius);\n  center = p;\n  outerRadius = radius;\n}\n\n// Registers an annulus\nShape::Shape(std::string id_, point const& p, double outerRadius_, double innerRadius_) {\n  type = ShapeType::annulus;\n  id = id_;\n  envelope = envelopeFromCircle(p, outerRadius_);\n  center = p;\n  outerRadius = outerRadius_;\n  innerRadius = innerRadius_;\n}\n\n// Registers a Polygon\nShape::Shape(std::string id_, polygon const& p) {\n  type = ShapeType::poly;\n  id = id_;\n  envelope = bg::return_envelope<box>(p);\n  polygonShape = p;\n}\n\n// Rough & fast approximation, should be enough to get a circle's MBR\nbox Shape::envelopeFromCircle(point const& p, double radius) {\n  double\n    lat = bg::get<1>(p),\n    lon = bg::get<0>(p),\n    dlat = radius / earthRadius,\n    dlon = radius / (earthRadius*cos(pi*lat/180));\n\n  dlat *= 180 / pi;\n  dlon *= 180 / pi;\n\n  return box(point(lon - dlon, lat - dlat), point(lon + dlon, lat + dlat));\n}\n\nbool Shape::covered(point const& p) {\n  double distance;\n\n  switch(type) {\n    case ShapeType::bbox:\n      /*\n       the r* tree index handles bounding boxes so for boxes shapes,\n       the approximation is the result\n       */\n      return true;\n    case ShapeType::circle:\n      return bg::distance(center, p) <= outerRadius;\n    case ShapeType::annulus:\n      distance = bg::distance(center, p);\n      return distance <= outerRadius && distance >= innerRadius;\n    case ShapeType::poly:\n      return bg::covered_by(p, polygonShape);\n  }\n\n  return false;\n}\n\nconst char *Shape::getId() {\n  return id.c_str();\n}\n\nbox Shape::getEnvelope() {\n  return envelope;\n}\n", "meta": {"hexsha": "71d3dede4a7fffcd438232f743d22e73278e4c78", "size": 2065, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/shape.cc", "max_stars_repo_name": "aswinsreedhar/boost-geospatial-index", "max_stars_repo_head_hexsha": "1614a1715558adc2edd2bff2839f7a6084ffef1a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2016-10-26T09:12:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T22:45:44.000Z", "max_issues_repo_path": "src/shape.cc", "max_issues_repo_name": "aswinsreedhar/boost-geospatial-index", "max_issues_repo_head_hexsha": "1614a1715558adc2edd2bff2839f7a6084ffef1a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2016-12-24T07:30:10.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-12T21:56:15.000Z", "max_forks_repo_path": "src/shape.cc", "max_forks_repo_name": "aswinsreedhar/boost-geospatial-index", "max_forks_repo_head_hexsha": "1614a1715558adc2edd2bff2839f7a6084ffef1a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2016-12-24T07:30:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-11T14:55:22.000Z", "avg_line_length": 23.7356321839, "max_line_length": 89, "alphanum_fraction": 0.6600484262, "num_tokens": 552, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257127, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4826443388072296}}
{"text": "#pragma once\n\n#include <cmath>\n#include <cstddef>\n#include <cstdlib>\n#include <limits>\n#include <set>\n#include <string>\n#include <utility>\n#include <vector>\n\n#include <boost/gil/gil_all.hpp>\n#include <boost/gil/extension/io/jpeg_io.hpp>\n\n#include <QColor>\n#include <QImage>\n#include <QPageSize>\n#include <QPainter>\n#include <QPoint>\n#include <QPrinter>\n#include <QSizeF>\n#include <QString>\n\n#include <q_gil_converter.hpp>\n\nnamespace vi\n{\n    namespace image_segmentation\n    {\n        using vertex_index  = unsigned;\n        using edge_distance = double;\n        using segment_index = unsigned;\n\n        enum struct image_direction : unsigned\n        {\n            unassigned = 0U, none, north, east, south, west\n        };\n\n        const auto SEGMENT_COLORS = std::vector<QColor>{\n            QColor{178,223,138},\n            QColor{106,61,154},\n            QColor{188,128,189},\n            QColor{128,177,211},\n            QColor{141,211,199},\n            QColor{255,255,153},\n            QColor{202,178,214},\n            QColor{51,160,44},\n            QColor{190,186,218},\n            QColor{177,89,40},\n            QColor{227,26,28},\n            QColor{31,120,180},\n            QColor{166,206,227},\n            QColor{255,237,111},\n            QColor{251,154,153},\n            QColor{255,127,0},\n            QColor{253,191,111},\n            QColor{251,128,114},\n            QColor{252,205,229},\n            QColor{255,255,179},\n            QColor{204,235,197},\n            QColor{179,222,105},\n            QColor{253,180,98}\n        };\n\n        template <typename pixel_type>\n        inline\n        double\n        compute_pixel_distance(const pixel_type& a, const pixel_type& b)\n        {\n            using namespace boost::gil;\n\n            return std::sqrt(\n                std::pow(static_cast<double>(get_color(a, red_t()))   - static_cast<double>(get_color(b, red_t())),   2) +\n                std::pow(static_cast<double>(get_color(a, green_t())) - static_cast<double>(get_color(b, green_t())), 2) +\n                std::pow(static_cast<double>(get_color(a, blue_t()))  - static_cast<double>(get_color(b, blue_t())),  2));\n        }\n\n        double\n        compute_overall_deviation(\n            const boost::gil::rgb8_view_t&    image_view,\n            const std::vector<segment_index>& segmentation,\n            const int                         segment_count)\n        {\n            struct segment_color_sums_info\n            {\n                std::size_t              count{};\n                double                   red_sum{};\n                double                   green_sum{};\n                double                   blue_sum{};\n                boost::gil::rgb8_pixel_t centroid{};\n            };\n\n            double overall_deviation = 0.0;\n\n            std::vector<segment_color_sums_info> segments_color_sums(segment_count);\n\n            auto       pixel       = image_view.begin();\n            auto       segment     = segmentation.begin();\n            const auto segment_end = segmentation.end();\n\n            while (segment != segment_end)\n            {\n                auto& segment_color_sums = segments_color_sums[*segment - 1];\n\n                segment_color_sums.count     += 1;\n                segment_color_sums.red_sum   += static_cast<double>(boost::gil::get_color(*pixel, boost::gil::red_t()));\n                segment_color_sums.green_sum += static_cast<double>(boost::gil::get_color(*pixel, boost::gil::green_t()));\n                segment_color_sums.blue_sum  += static_cast<double>(boost::gil::get_color(*pixel, boost::gil::blue_t()));\n\n                ++pixel;\n                ++segment;\n            }\n\n            for (auto& segment_color_sums : segments_color_sums)\n            {\n                segment_color_sums.centroid = boost::gil::rgb8_pixel_t{\n                    static_cast<unsigned char>(std::round(segment_color_sums.red_sum   / segment_color_sums.count)),\n                    static_cast<unsigned char>(std::round(segment_color_sums.green_sum / segment_color_sums.count)),\n                    static_cast<unsigned char>(std::round(segment_color_sums.blue_sum  / segment_color_sums.count))};\n            }\n\n            pixel   = image_view.begin();\n            segment = segmentation.begin();\n\n            while (segment != segment_end)\n            {\n                const auto& segment_color_sums = segments_color_sums[*segment - 1];\n\n                overall_deviation += compute_pixel_distance(*pixel, segment_color_sums.centroid);\n\n                ++pixel;\n                ++segment;\n            }\n\n            return overall_deviation;\n        }\n\n        double\n        compute_edge_value(\n            const boost::gil::rgb8_view_t&    image_view,\n            const std::vector<segment_index>& segmentation,\n            const int                         segment_count)\n        {\n            double edge_value = 0.0;\n\n            const auto width  = static_cast<std::size_t>(image_view.width());\n            const auto height = static_cast<std::size_t>(image_view.height());\n\n            auto pixel_current   = image_view.begin();\n            auto pixel_next      = pixel_current + 1;\n            auto pixel_below     = pixel_current + width;\n            auto segment_current = segmentation.begin();\n            auto segment_next    = segment_current + 1;\n            auto segment_below   = segment_current + width;\n\n            for (std::size_t y = 0; y < height - 1; ++y)\n            {\n                for (std::size_t x = 0; x < width - 1; ++x)\n                {\n                    if (*segment_current != *segment_below)\n                    {\n                        edge_value += 2.0 * compute_pixel_distance(*pixel_current, *pixel_below);\n                    }\n\n                    if (*segment_current != *segment_next)\n                    {\n                        edge_value += 2.0 * compute_pixel_distance(*pixel_current, *pixel_next);\n                    }\n\n                    ++pixel_current;\n                    ++pixel_next;\n                    ++pixel_below;\n\n                    ++segment_current;\n                    ++segment_next;\n                    ++segment_below;\n                }\n\n                if (*segment_current != *segment_below)\n                {\n                    edge_value += 2.0 * compute_pixel_distance(*pixel_current, *pixel_below);\n                }\n\n                ++pixel_current;\n                ++pixel_next;\n                ++pixel_below;\n\n                ++segment_current;\n                ++segment_next;\n                ++segment_below;\n            }\n\n            for (std::size_t x = 0; x < width - 1; ++x)\n            {\n                if (*segment_current != *segment_next)\n                {\n                    edge_value += 2.0 * compute_pixel_distance(*pixel_current, *pixel_next);\n                }\n\n                ++pixel_current;\n                ++pixel_next;\n                ++pixel_below;\n\n                ++segment_current;\n                ++segment_next;\n                ++segment_below;\n            }\n\n            return edge_value;\n        }\n\n        double\n        compute_connectivity_measure(\n            const boost::gil::rgb8_view_t&    image_view,\n            const std::vector<segment_index>& segmentation,\n            const int                         segment_count)\n        {\n            double connectivity_measure = 0.0;\n\n            constexpr double disconnected_neighbor_penalties[] =\n            {\n                0.0,\n                1.0,\n                1.0 + 1.0 / 2.0,\n                1.0 + 1.0 / 2.0 + 1.0 / 3.0,\n                1.0 + 1.0 / 2.0 + 1.0 / 3.0 + 1.0 / 4.0\n            };\n\n            const auto width  = static_cast<std::size_t>(image_view.width());\n            const auto height = static_cast<std::size_t>(image_view.height());\n\n            auto segment_current = segmentation.begin();\n            auto segment_above   = segment_current;\n            auto segment_below   = segment_current + width;\n\n            connectivity_measure += disconnected_neighbor_penalties[\n                ((*segment_current != *(segment_current + 1)) ? 1 : 0) +\n                ((*segment_current != *(segment_below      )) ? 1 : 0)];\n\n            ++segment_current;\n            ++segment_below;\n\n            for (std::size_t x = 0; x < width - 2; ++x)\n            {\n                connectivity_measure += disconnected_neighbor_penalties[\n                    ((*segment_current != *(segment_current - 1)) ? 1 : 0) +\n                    ((*segment_current != *(segment_current + 1)) ? 1 : 0) +\n                    ((*segment_current != *(segment_below      )) ? 1 : 0)];\n\n                ++segment_current;\n                ++segment_below;\n            }\n\n            connectivity_measure += disconnected_neighbor_penalties[\n                ((*segment_current != *(segment_current - 1)) ? 1 : 0) +\n                ((*segment_current != *(segment_below      )) ? 1 : 0)];\n\n            ++segment_current;\n            ++segment_below;\n\n            for (std::size_t y = 0; y < height - 2; ++y)\n            {\n                connectivity_measure += disconnected_neighbor_penalties[\n                    ((*segment_current != *(segment_above      )) ? 1 : 0) +\n                    ((*segment_current != *(segment_current + 1)) ? 1 : 0) +\n                    ((*segment_current != *(segment_below      )) ? 1 : 0)];\n\n                ++segment_current;\n                ++segment_below;\n                ++segment_above;\n\n                for (std::size_t x = 0; x < width - 2; ++x)\n                {\n                    connectivity_measure += disconnected_neighbor_penalties[\n                        ((*segment_current != *(segment_above      )) ? 1 : 0) +\n                        ((*segment_current != *(segment_current - 1)) ? 1 : 0) +\n                        ((*segment_current != *(segment_current + 1)) ? 1 : 0) +\n                        ((*segment_current != *(segment_below      )) ? 1 : 0)];\n\n                    ++segment_current;\n                    ++segment_below;\n                    ++segment_above;\n                }\n\n                connectivity_measure += disconnected_neighbor_penalties[\n                    ((*segment_current != *(segment_above      )) ? 1 : 0) +\n                    ((*segment_current != *(segment_current - 1)) ? 1 : 0) +\n                    ((*segment_current != *(segment_below      )) ? 1 : 0)];\n\n                ++segment_current;\n                ++segment_below;\n                ++segment_above;\n            }\n\n            connectivity_measure += disconnected_neighbor_penalties[\n                ((*segment_current != *(segment_above      )) ? 1 : 0) +\n                ((*segment_current != *(segment_current + 1)) ? 1 : 0)];\n\n            ++segment_current;\n            ++segment_above;\n\n            for (std::size_t x = 0; x < width - 2; ++x)\n            {\n                connectivity_measure += disconnected_neighbor_penalties[\n                    ((*segment_current != *(segment_above      )) ? 1 : 0) +\n                    ((*segment_current != *(segment_current - 1)) ? 1 : 0) +\n                    ((*segment_current != *(segment_current + 1)) ? 1 : 0)];\n\n                ++segment_current;\n                ++segment_above;\n            }\n\n            connectivity_measure += disconnected_neighbor_penalties[\n                ((*segment_current != *(segment_above      )) ? 1 : 0) +\n                ((*segment_current != *(segment_current - 1)) ? 1 : 0)];\n\n            return connectivity_measure;\n        }\n\n        void\n        render(const boost::gil::rgb8_view_t&    image_view,\n               const std::vector<segment_index>& segmentation,\n               const std::string&                filename,\n               const bool                        render_image,\n               const bool                        render_borders,\n               const bool                        render_segments)\n        {\n            const auto width  = static_cast<std::size_t>(image_view.width());\n            const auto height = static_cast<std::size_t>(image_view.height());\n\n            QPrinter printer{};\n            printer.setOutputFormat(QPrinter::PdfFormat);\n            printer.setOutputFileName(filename.c_str());\n            printer.setPageMargins(0, 0, 0, 0, QPrinter::Inch);\n\n            printer.setPageSize(QPageSize(\n                QSizeF(static_cast<double>(width), static_cast<double>(height)),\n                QPageSize::Inch,\n                QString(\"\"),\n                QPageSize::SizeMatchPolicy::ExactMatch));\n\n            QPainter painter{&printer};\n\n            painter.scale(static_cast<double>(printer.resolution()),\n                          static_cast<double>(printer.resolution()));\n\n            if (render_image)\n            {\n                const QImage input_image_q = q_gil::gil_view_to_qimage(image_view);\n                painter.drawImage(QPoint(0, 0), input_image_q);\n            }\n\n            if (render_segments)\n            {\n                for (std::size_t y = 0; y < height; ++y)\n                {\n                    for (std::size_t x = 0; x < width; ++x)\n                    {\n                        const auto index = y * width + x;\n                        const auto segment = segmentation[index];\n\n                        // Stupid hack to render without dividers:\n                        painter.fillRect(QRectF{static_cast<double>(x) - 0.05,\n                                                static_cast<double>(y) - 0.05,\n                                                1.1,\n                                                1.1},\n                                         SEGMENT_COLORS[segment % SEGMENT_COLORS.size()]);\n                    }\n                }\n            }\n\n            if (render_borders)\n            {\n                painter.setPen(\n                    QPen{QBrush((render_image || render_segments) ? QColor{42, 254, 39} : Qt::black),\n                         0.2,\n                         Qt::SolidLine,\n                         Qt::RoundCap});\n\n                for (std::size_t y = 0; y < height; ++y)\n                {\n                    for (std::size_t x = 0; x < width; ++x)\n                    {\n                        if (x < width - 1 && segmentation[y * width + x] != segmentation[y * width + x + 1])\n                        {\n                            painter.drawLine(QPointF(static_cast<double>(x) + 1.0, static_cast<double>(y)),\n                                             QPointF(static_cast<double>(x) + 1.0, static_cast<double>(y) + 1.0));\n                        }\n\n                        if (y < height - 1 && segmentation[y * width + x] != segmentation[(y + 1) * width + x])\n                        {\n                            painter.drawLine(QPointF(static_cast<double>(x),       static_cast<double>(y) + 1.0),\n                                             QPointF(static_cast<double>(x) + 1.0, static_cast<double>(y) + 1.0));\n                        }\n                    }\n                }\n\n                painter.drawRect(QRectF(0.0, 0.0, static_cast<double>(width), static_cast<double>(height)));\n            }\n        }\n\n        void\n        inline\n        trace_segment(std::vector<segment_index>&         segments,\n                      const std::vector<image_direction>& graph,\n                      const std::size_t                   width,\n                      const std::size_t                   height,\n                      const std::size_t                   x,\n                      const std::size_t                   y,\n                      const segment_index                 segment,\n                      const image_direction               direction = image_direction::none)\n        {\n            const auto index = y * width + x;\n\n            if (!segments[index])\n            {\n                segments[index] = segment;\n\n                if ((y > 0 && direction != image_direction::south) &&\n                    (graph[index] == image_direction::north || graph[index - width] == image_direction::south))\n                {\n                    trace_segment(segments, graph, width, height, x, y - 1, segment, image_direction::north);\n                }\n\n                if ((y < height - 1 && direction != image_direction::north) &&\n                    (graph[index] == image_direction::south || graph[index + width] == image_direction::north))\n                {\n                    trace_segment(segments, graph, width, height, x, y + 1, segment, image_direction::south);\n                }\n\n                if ((x > 0 && direction != image_direction::east) &&\n                    (graph[index] == image_direction::west || graph[index - 1] == image_direction::east))\n                {\n                    trace_segment(segments, graph, width, height, x - 1, y, segment, image_direction::west);\n                }\n\n                if ((x < width - 1 && direction != image_direction::west) &&\n                    (graph[index] == image_direction::east || graph[index + 1] == image_direction::west))\n                {\n                    trace_segment(segments, graph, width, height, x + 1, y, segment, image_direction::east);\n                }\n            }\n        }\n\n        std::pair<std::vector<segment_index>, segment_index>\n        compile_segmentation_graph(const std::vector<image_direction>& graph,\n                                   const std::size_t                   width,\n                                   const std::size_t                   height)\n        {\n            auto segmentation    = std::vector<segment_index>(graph.size());\n            auto segment_counter = segment_index{1U};\n\n            for (std::size_t y = 0; y < height; ++y)\n            {\n                for (std::size_t x = 0; x < width; ++x)\n                {\n                    const auto index = y * width + x;\n\n                    if (!segmentation[index])\n                    {\n                        const auto segment = segment_counter++;\n                        trace_segment(segmentation, graph, width, height, x, y, segment);\n                    }\n                }\n            }\n\n            return std::make_pair(std::move(segmentation), segment_counter - 1U);\n        }\n\n        struct image_distances\n        {\n            std::size_t         image_width;\n            std::size_t         image_height;\n            std::vector<double> costs;\n\n            image_distances(const boost::gil::rgb8c_view_t& view)\n                : image_width(static_cast<std::size_t>(view.width())),\n                  image_height(static_cast<std::size_t>(view.height())),\n                  costs((image_width * 2 - 1) * (image_height * 2 - 1),\n                        std::numeric_limits<double>::quiet_NaN())\n            {\n                for (unsigned y = 0; y < image_height; ++y)\n                {\n                    for (unsigned x = 0; x < image_width; ++x)\n                    {\n                        if (x > 0)\n                        {\n                            (*this)(x, y, image_direction::west) = compute_pixel_distance(view(x - 1, y), view(x, y));\n                        }\n\n                        if (y > 0)\n                        {\n                            (*this)(x, y, image_direction::north) = compute_pixel_distance(view(x, y - 1), view(x, y));\n                        }\n                    }\n                }\n            }\n\n            inline\n            std::size_t\n            computePixelDirectionIndex(const std::size_t x, const std::size_t y, const image_direction direction) const\n            {\n                switch (direction)\n                {\n                    case image_direction::north:\n                        return (y * 2 - 1) * image_width + x * 2;\n                    case image_direction::east:\n                        return y * 2 * image_width + x * 2 + 1;\n                    case image_direction::south:\n                        return (y * 2 + 1) * image_width + x * 2;\n                    case image_direction::west:\n                        return y * 2 * image_width + x * 2 - 1;\n                    default:\n                        std::exit(-1);\n                }\n            }\n\n            inline\n            double\n            maximum() const\n            {\n                auto max_value = std::numeric_limits<double>::min();\n\n                for (const auto value : costs)\n                {\n                    if (!std::isnan(value) && value > max_value)\n                    {\n                        max_value = value;\n                    }\n                }\n\n                return max_value;\n            }\n\n            inline\n            double&\n            operator()(const std::size_t x, const std::size_t y, const image_direction direction)\n            {\n                return costs[computePixelDirectionIndex(x, y, direction)];\n            }\n\n            inline\n            const double&\n            operator()(const std::size_t x, const std::size_t y, const image_direction direction) const\n            {\n                return costs[computePixelDirectionIndex(x, y, direction)];\n            }\n        };\n\n        struct vertex_cost_comparator\n        {\n            vertex_cost_comparator(const std::vector<double>& costs)\n                : costs{&costs} {}\n\n            inline\n            bool\n            operator()(const vertex_index vertex_a, const vertex_index vertex_b) const\n            {\n                const auto cost_a = (*costs)[vertex_a];\n                const auto cost_b = (*costs)[vertex_b];\n                return cost_a != cost_b ? cost_a < cost_b : vertex_a < vertex_b;\n            }\n\n            const std::vector<double>* costs;\n        };\n\n        struct edge_distance_comparator\n        {\n            inline\n            bool\n            operator()(const std::pair<vertex_index, edge_distance>& a,\n                       const std::pair<vertex_index, edge_distance>& b)\n            {\n                return a.second > b.second;\n            }\n        };\n\n        template <typename frontier_type>\n        inline\n        bool\n        update_cheapest(\n            const std::vector<image_direction>& graph,\n            const vertex_index                  parent_vertex,\n            const vertex_index                  target_vertex,\n            const image_direction               target_edge_direction,\n            const double                        distance,\n            frontier_type&                      frontier,\n            std::vector<double>&                lowest_vertex_costs,\n            std::vector<image_direction>&       lowest_cost_edges)\n        {\n            if (graph[target_vertex] == image_direction::unassigned)\n            {\n                if (distance < lowest_vertex_costs[target_vertex])\n                {\n                    if (frontier.count(target_vertex))\n                    {\n                        frontier.erase(target_vertex);\n                    }\n\n                    lowest_vertex_costs[target_vertex] = distance;\n                    lowest_cost_edges[target_vertex]   = target_edge_direction;\n\n                    frontier.insert(target_vertex);\n                }\n            }\n\n            return false;\n        }\n\n        template <typename random_generator_type>\n        std::vector<image_direction>\n        build_minimum_spanning_tree(random_generator_type& random_generator,\n                                    const image_distances& distances,\n                                    const int              remove_edge_count = 0)\n        {\n            const auto width  = distances.image_width;\n            const auto height = distances.image_height;\n            const auto count  = width * height;\n\n            auto graph               = std::vector<image_direction>(count, image_direction::unassigned);\n            auto lowest_vertex_costs = std::vector<double>(count, std::numeric_limits<double>::max());\n            auto lowest_cost_edges   = std::vector<image_direction>(count, image_direction::unassigned);\n            auto highest_cost_edges  = std::set<\n                std::pair<vertex_index, edge_distance>, edge_distance_comparator>{};\n\n            vertex_cost_comparator comparator{lowest_vertex_costs};\n            std::set<vertex_index, vertex_cost_comparator> frontier{comparator};\n\n            const auto initial_vertex = std::uniform_int_distribution<unsigned>{\n                0U, static_cast<unsigned>(count) - 1U}(random_generator);\n\n            frontier.insert(initial_vertex);\n\n            while (!frontier.empty())\n            {\n                const auto vertex_it = frontier.begin();\n                const auto vertex    = *vertex_it;\n\n                frontier.erase(vertex_it);\n\n                const auto cheapest_edge = lowest_cost_edges[vertex];\n                graph[vertex] = cheapest_edge != image_direction::unassigned ? cheapest_edge : image_direction::none;\n\n                const auto cheapest_distance = cheapest_edge != image_direction::unassigned ? lowest_vertex_costs[vertex] : 0.0;\n\n                if (remove_edge_count)\n                {\n                    if (highest_cost_edges.size() < remove_edge_count)\n                    {\n                        highest_cost_edges.insert(std::make_pair(vertex, cheapest_distance));\n                    }\n                    else if (cheapest_distance > highest_cost_edges.rend()->second)\n                    {\n                        highest_cost_edges.erase(--highest_cost_edges.end());\n                        highest_cost_edges.insert(std::make_pair(vertex, cheapest_distance));\n                    }\n                }\n\n                const auto row    = vertex / width;\n                const auto column = vertex % width;\n\n                if (row > 0)\n                {\n                    update_cheapest(graph,\n                                    vertex,\n                                    vertex - width,\n                                    image_direction::south,\n                                    distances(column, row, image_direction::north),\n                                    frontier,\n                                    lowest_vertex_costs,\n                                    lowest_cost_edges);\n                }\n\n                if (row < height - 1)\n                {\n                    update_cheapest(graph,\n                                    vertex,\n                                    vertex + width,\n                                    image_direction::north,\n                                    distances(column, row, image_direction::south),\n                                    frontier,\n                                    lowest_vertex_costs,\n                                    lowest_cost_edges);\n                }\n\n                if (column > 0)\n                {\n                    update_cheapest(graph,\n                                    vertex,\n                                    vertex - 1,\n                                    image_direction::east,\n                                    distances(column, row, image_direction::west),\n                                    frontier,\n                                    lowest_vertex_costs,\n                                    lowest_cost_edges);\n                }\n\n                if (column < width - 1)\n                {\n                    update_cheapest(graph,\n                                    vertex,\n                                    vertex + 1,\n                                    image_direction::west,\n                                    distances(column, row, image_direction::east),\n                                    frontier,\n                                    lowest_vertex_costs,\n                                    lowest_cost_edges);\n                }\n            }\n\n            for (const auto& highest_cost_edge : highest_cost_edges)\n            {\n                graph[highest_cost_edge.first] = image_direction::none;\n            }\n\n            return graph;\n        }\n\n        struct moea\n        {\n            using genotype_type = std::pair<std::vector<vi::image_segmentation::image_direction>, vi::image_segmentation::segment_index>;\n\n            template <typename random_generator_type>\n            static\n            std::pair<genotype_type, genotype_type>\n            crossover_operator(random_generator_type& random_generator,\n                               const genotype_type&   parent_a,\n                               const genotype_type&   parent_b)\n            {\n                auto& parent_a_sequence = parent_a.first;\n                auto& parent_b_sequence = parent_b.first;\n\n                const auto sequence_length = static_cast<unsigned>(parent_a_sequence.size());\n\n                auto children = std::make_pair(\n                    std::make_pair(std::vector<image_direction>(sequence_length, image_direction::unassigned), segment_index{}),\n                    std::make_pair(std::vector<image_direction>(sequence_length, image_direction::unassigned), segment_index{}));\n\n                auto& child_a_sequence = children.first.first;\n                auto& child_b_sequence = children.second.first;\n\n                const auto crossover_point = std::uniform_int_distribution<unsigned>{\n                    0U, sequence_length}(random_generator);\n\n                std::copy(parent_a_sequence.begin(),\n                          parent_a_sequence.begin() + crossover_point,\n                          child_a_sequence.begin());\n\n                std::copy(parent_b_sequence.begin() + crossover_point,\n                          parent_b_sequence.end(),\n                          child_a_sequence.begin() + crossover_point);\n\n                std::copy(parent_b_sequence.begin(),\n                          parent_b_sequence.begin() + crossover_point,\n                          child_b_sequence.begin());\n\n                std::copy(parent_a_sequence.begin() + crossover_point,\n                          parent_a_sequence.end(),\n                          child_b_sequence.begin() + crossover_point);\n\n                return children;\n            }\n\n            static\n            boost::gil::rgb8_image_t\n            load_image(const std::string& image_filename)\n            {\n                boost::gil::rgb8_image_t image{};\n                boost::gil::jpeg_read_image(image_filename, image);\n                return image;\n            }\n\n            template <typename random_generator_type>\n            static\n            void\n            mutate_operator(random_generator_type& random_generator,\n                            genotype_type&         genotype)\n            {\n                const auto index = std::uniform_int_distribution<unsigned>{\n                    0U, static_cast<unsigned>(genotype.first.size()) - 1U}(random_generator);\n\n                const auto value = static_cast<image_direction>(\n                    std::uniform_int_distribution<unsigned>{\n                        static_cast<unsigned>(image_direction::none),\n                        static_cast<unsigned>(image_direction::west)}(random_generator));\n\n                genotype.first[index] = value;\n            }\n\n            boost::gil::rgb8_image_t input_image;\n            std::size_t              input_image_width;\n            std::size_t              input_image_height;\n            image_distances          input_image_distances;\n            bool                     evaluate_overall_deviation;\n            bool                     evaluate_edge_value;\n            bool                     evaluate_connectivity_measure;\n\n            moea(const std::string& input_image_filename,\n                 const bool         evaluate_overall_deviation,\n                 const bool         evaluate_edge_value,\n                 const bool         evaluate_connectivity_measure)\n                : input_image{load_image(input_image_filename)},\n                  input_image_width{static_cast<std::size_t>(input_image.width())},\n                  input_image_height{static_cast<std::size_t>(input_image.height())},\n                  input_image_distances{boost::gil::view(input_image)},\n                  evaluate_overall_deviation{evaluate_overall_deviation},\n                  evaluate_edge_value{evaluate_edge_value},\n                  evaluate_connectivity_measure{evaluate_connectivity_measure}\n            {\n            }\n\n            std::vector<double>\n            evaluate(genotype_type& genotype)\n            {\n                std::vector<double> objective_values{};\n\n                std::vector<segment_index> segmentation{};\n                segment_index              segment_count{};\n\n                std::tie(segmentation, segment_count) = compile_segmentation_graph(\n                    genotype.first, input_image_width, input_image_height);\n\n                genotype.second = segment_count;\n\n                if (evaluate_overall_deviation)\n                {\n                    objective_values.push_back(\n                        compute_overall_deviation(\n                            boost::gil::view(input_image),\n                            segmentation,\n                            segment_count));\n                }\n\n                if (evaluate_edge_value)\n                {\n                    objective_values.push_back(\n                        compute_edge_value(\n                            boost::gil::view(input_image),\n                            segmentation,\n                            segment_count));\n                }\n\n                if (evaluate_connectivity_measure)\n                {\n                    objective_values.push_back(\n                        compute_connectivity_measure(\n                            boost::gil::view(input_image),\n                            segmentation,\n                            segment_count));\n                }\n\n                return objective_values;\n            }\n\n            template <typename random_generator_type>\n            genotype_type\n            generate(random_generator_type& random_generator)\n            {\n                return std::make_pair(build_minimum_spanning_tree(\n                    random_generator, input_image_distances), segment_index{});\n            }\n        };\n    }\n}", "meta": {"hexsha": "b7f6c25e6ebf659c90d3f60fabf2b8b1fa6cca65", "size": 34095, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "project_3_2017/program/vi_image_segmentation.hpp", "max_stars_repo_name": "pveierland/permve-ntnu-it3708", "max_stars_repo_head_hexsha": "1066d5c1af5c953dbaf129d7e05ce32f2d4292aa", "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": "project_3_2017/program/vi_image_segmentation.hpp", "max_issues_repo_name": "pveierland/permve-ntnu-it3708", "max_issues_repo_head_hexsha": "1066d5c1af5c953dbaf129d7e05ce32f2d4292aa", "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": "project_3_2017/program/vi_image_segmentation.hpp", "max_forks_repo_name": "pveierland/permve-ntnu-it3708", "max_forks_repo_head_hexsha": "1066d5c1af5c953dbaf129d7e05ce32f2d4292aa", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.4618055556, "max_line_length": 137, "alphanum_fraction": 0.4734125238, "num_tokens": 6311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.766293653760418, "lm_q2_score": 0.6297746074044135, "lm_q1q2_score": 0.48259228495346085}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\nCopyright (C) 2015 Andres Hernandez\n\nThis file is part of QuantLib, a free-software/open-source library\nfor financial quantitative analysts and developers - http://quantlib.org/\n\nQuantLib is free software: you can redistribute it and/or modify it\nunder the terms of the QuantLib license.  You should have received a\ncopy of the license along with this program; if not, please email\n<quantlib-dev@lists.sf.net>. The license is also available online at\n<http://quantlib.org/license.shtml>.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT\nANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\nFOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n/*! \\file hybridsimulatedannealing.hpp\n\\brief Implementation based on:\nVery Fast Simulated Re-Annealing, Lester Ingber,\nMathl. Comput. Modelling, 967-973, 1989\n*/\n\n#ifndef quantlib_optimization_hybridsimulatedannealing_hpp\n#define quantlib_optimization_hybridsimulatedannealing_hpp\n\n#include <ql/math/optimization/problem.hpp>\n#include <ql/math/optimization/constraint.hpp>\n#include <ql/experimental/math/hybridsimulatedannealingfunctors.hpp>\n#include <ql/math/optimization/levenbergmarquardt.hpp>\n#include <boost/make_shared.hpp>\n\nnamespace QuantLib {\n\n    /*! Method is fairly straightforward:\n    1) Sampler provides a probability density (based on current value) for the parameters. Each\n    iteration a new draw is made from it to find a new point\n    2) Probability determines whether the new point, obtained from Sampler, is accepted or not\n    3) Temperature is a schedule T(k) for the iteration k, which affects the Sampler and Probability\n    4) Reannealing is a departure from the traditional Boltzmann Annealing method: it rescales\n    the iteration k independently for each dimension so as to improve convergence\n\n    The hybrid in the name is because one can provide it a local optimizer for use whenever any new\n    best point is found or at every accepted point, in which case is used is chose by the user.\n\n    Class Sampler must implement the following interface:\n    \\code\n    void operator()(Array &newPoint, const Array &currentPoint, const Array &temp) const;\n    \\endcode\n    Class Probability must implement the following interface:\n    \\code\n    bool operator()(Real currentValue, Real newValue, const Array &temp) const;\n    \\endcode\n    Class Temperature must implement the following interface:\n    \\code\n    void operator()(Array &newTemp, const Array &currTemp, const Array &steps) const;\n    \\endcode\n    Class Reannealing must implement the following interface:\n    \\code\n    void operator()(Array & steps, const Array &currentPoint,\n    Real aCurrentValue, const Array & currTemp) const;\n    \\endcode\n    */\n    template <class Sampler, class Probability, class Temperature, class Reannealing = ReannealingTrivial>\n    class HybridSimulatedAnnealing : public OptimizationMethod {\n      public:\n        enum LocalOptimizeScheme {\n            NoLocalOptimize,\n            EveryNewPoint,\n            EveryBestPoint\n        };\n        enum ResetScheme {\n            NoResetScheme,\n            ResetToBestPoint,\n            ResetToOrigin\n        };\n\n        HybridSimulatedAnnealing(const Sampler &sampler,\n            const Probability &probability,\n            const Temperature &temperature,\n            const Reannealing &reannealing = ReannealingTrivial(),\n            Real startTemperature = 200.0,\n            Real endTemperature = 0.01,\n            Size reAnnealSteps = 50,\n            ResetScheme resetScheme = ResetToBestPoint,\n            Size resetSteps = 150,\n            boost::shared_ptr<OptimizationMethod> localOptimizer\n            = boost::make_shared<LevenbergMarquardt>(),\n            LocalOptimizeScheme optimizeScheme = EveryBestPoint)\n            : sampler_(sampler), probability_(probability),\n            temperature_(temperature), reannealing_(reannealing),\n            startTemperature_(startTemperature), endTemperature_(endTemperature),\n            reAnnealSteps_(reAnnealSteps == 0 ? QL_MAX_INTEGER : reAnnealSteps), resetScheme_(resetScheme),\n            resetSteps_(resetSteps == 0 ? QL_MAX_INTEGER : resetSteps), localOptimizer_(localOptimizer),\n            optimizeScheme_(localOptimizer ? optimizeScheme : NoLocalOptimize) {}\n\n        EndCriteria::Type minimize(Problem &P, const EndCriteria &endCriteria);\n    private:\n        Sampler sampler_;\n        Probability probability_;\n        Temperature temperature_;\n        Reannealing reannealing_;\n        Real startTemperature_;\n        Real endTemperature_;\n        Size reAnnealSteps_;\n        ResetScheme resetScheme_;\n        Size resetSteps_;\n        boost::shared_ptr<OptimizationMethod> localOptimizer_;\n        LocalOptimizeScheme optimizeScheme_;\n    };\n\n    template <class Sampler, class Probability, class Temperature, class Reannealing>\n    EndCriteria::Type HybridSimulatedAnnealing<Sampler, Probability, Temperature, Reannealing>::minimize(Problem &P, const EndCriteria &endCriteria) {\n        EndCriteria::Type ecType = EndCriteria::None;\n        P.reset();\n        reannealing_.setProblem(P);\n        Array x = P.currentValue();\n        Size n = x.size();\n        Size k = 1;\n        Size kStationary = 1;\n        Size kReAnneal = 1;\n        Size kReset = 1;\n        Size maxK = endCriteria.maxIterations();\n        Size maxKStationary = endCriteria.maxStationaryStateIterations();\n        bool temperatureBreached = false;\n        Array currentTemperature(n, startTemperature_);\n        Array annealStep(n, 1.0);\n        Array bestPoint(x);\n        Array currentPoint(x);\n        Array startingPoint(x);\n        Array newPoint(x);\n        Real bestValue = P.value(bestPoint);\n        Real currentValue = bestValue;\n        Real startingValue = bestValue; //to reset to starting point if desired\n        while (k <= maxK && kStationary <= maxKStationary && !temperatureBreached)\n        {\n            //Draw a new sample point\n            sampler_(newPoint, currentPoint, currentTemperature);\n            try{\n                //Evaluate new point\n                Real newValue = P.value(newPoint);\n\t\t\t\t\n                //Determine if new point is accepted\n                if (probability_(currentValue, newValue, currentTemperature)) {\n                    if (optimizeScheme_ == EveryNewPoint) {\n                        P.setCurrentValue(newPoint);\n                        P.setFunctionValue(newValue);\n                        localOptimizer_->minimize(P, endCriteria);\n                        newPoint = P.currentValue();\n                        newValue = P.functionValue();\n                    }\n                    currentPoint = newPoint;\n                    currentValue = newValue;\n                }\n\n                //Check if we have a new best point\n                if (newValue < bestValue) {\n                    if (optimizeScheme_ == EveryBestPoint) {\n                        P.setCurrentValue(newPoint);\n                        P.setFunctionValue(newValue);\n                        localOptimizer_->minimize(P, endCriteria);\n                        newPoint = P.currentValue();\n                        newValue = P.functionValue();\n                    }\n                    kStationary = 0;\n                    bestValue = newValue;\n                    bestPoint = newPoint;\n                }\n            } catch(...){\n                //Do nothing, move on to new draw\n            }\n            //Increase steps\n            k++;\n            kStationary++;\n            for (Size i = 0; i < annealStep.size(); i++)\n                annealStep[i]++;\n\n            //Reanneal if necessary\n            if (kReAnneal == reAnnealSteps_) {\n                kReAnneal = 0;\n                reannealing_(annealStep, currentPoint, currentValue, currentTemperature);\n            }\n            kReAnneal++;\n\n            //Reset if necessary\n            if (kReset == resetSteps_) {\n                kReset = 0;\n                switch (resetScheme_) {\n                case NoResetScheme:\n                    break;\n                case ResetToOrigin:\n                    currentPoint = startingPoint;\n                    currentValue = startingValue;\n                    break;\n                case ResetToBestPoint:\n                    currentPoint = bestPoint;\n                    currentValue = bestValue;\n                    break;\n                }\n            }\n            kReset++;\n\n            //Update the current temperature according to current step\n            temperature_(currentTemperature, currentTemperature, annealStep);\n\n            //Check if temperature condition is breached\n            for (Size i = 0; i < n; i++)\n                temperatureBreached = temperatureBreached && currentTemperature[i] < endTemperature_;\n        }\n        \n        //Change end criteria type if appropriate\n        if (k > maxK)\n            ecType = EndCriteria::MaxIterations;\n        else if (kStationary > maxKStationary)\n            ecType = EndCriteria::StationaryPoint;\n\n        //Set result to best point\n        P.setCurrentValue(bestPoint);\n        P.setFunctionValue(bestValue);\n        return ecType;\n    }\n\n    typedef HybridSimulatedAnnealing<SamplerGaussian, ProbabilityBoltzmannDownhill, TemperatureExponential, ReannealingTrivial> GaussianSimulatedAnnealing;\n    typedef HybridSimulatedAnnealing<SamplerLogNormal, ProbabilityBoltzmannDownhill, TemperatureExponential, ReannealingTrivial> LogNormalSimulatedAnnealing;\n    typedef HybridSimulatedAnnealing<SamplerMirrorGaussian, ProbabilityBoltzmannDownhill, TemperatureExponential, ReannealingTrivial> MirrorGaussianSimulatedAnnealing;\n    typedef HybridSimulatedAnnealing<SamplerGaussian, ProbabilityBoltzmannDownhill, TemperatureExponential, ReannealingFiniteDifferences> GaussianSimulatedReAnnealing;\n    typedef HybridSimulatedAnnealing<SamplerVeryFastAnnealing, ProbabilityBoltzmannDownhill, TemperatureVeryFastAnnealing, ReannealingTrivial> VeryFastSimulatedAnnealing;\n    typedef HybridSimulatedAnnealing<SamplerVeryFastAnnealing, ProbabilityBoltzmannDownhill, TemperatureVeryFastAnnealing, ReannealingFiniteDifferences> VeryFastSimulatedReAnnealing;\n}\n\n#endif\n", "meta": {"hexsha": "f5415f575f8d06bbe2d53f1d07e8e30f9e285290", "size": 10254, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/experimental/math/hybridsimulatedannealing.hpp", "max_stars_repo_name": "pmazzocchi/QuantLib", "max_stars_repo_head_hexsha": "52215f089778ddd1ea4dbef55d260ec8bd56901e", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/math/hybridsimulatedannealing.hpp", "max_issues_repo_name": "pmazzocchi/QuantLib", "max_issues_repo_head_hexsha": "52215f089778ddd1ea4dbef55d260ec8bd56901e", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/math/hybridsimulatedannealing.hpp", "max_forks_repo_name": "pmazzocchi/QuantLib", "max_forks_repo_head_hexsha": "52215f089778ddd1ea4dbef55d260ec8bd56901e", "max_forks_repo_licenses": ["BSD-3-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.8205128205, "max_line_length": 182, "alphanum_fraction": 0.6515506144, "num_tokens": 2145, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859598, "lm_q2_score": 0.6297746074044135, "lm_q1q2_score": 0.48259227823095807}}
{"text": "// ------------------------------------------------------------------------\n//  Copyright (C)\n//  Federico Perazzi <perazzif@inf.ethz.ch>\n//  April 2016\n// ------------------------------------------------------------------------\n#include <polycont/cpp/mask2poly.hpp>\n#include <boost/python/suite/indexing/vector_indexing_suite.hpp>\n#include <boost/python.hpp>\n#include <boost/numpy.hpp>\n\n// djikstra\n#include <Eigen/Dense>\n\n#include <boost/config.hpp>\n#include <iostream>\n\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <boost/property_map/property_map.hpp>\n\nnamespace py = boost::python;\nnamespace np = boost::numpy;\n\n#include <Eigen/Dense>\n#include \"cpp/mask2polycont.hpp\"\n\nusing namespace std;\nusing namespace PolyCont;\n\n//void mexFunction( int nlhs, mxArray *plhs[],\n              //int nrhs, const mxArray*prhs[] )\n//{\n\nstruct _ContContainer: public ContContainer\n{\n\tpy::list contour_coords;\n\n};\n_ContContainer _mask2poly(const np::ndarray& pymask, float tolerance) {\n\n\t\tnp::dtype dtype = np::dtype::get_builtin<bool>();\n\n\t\t// Required transposition to match matlab impl\n\t\tnp::ndarray _pymask = np::zeros(py::make_tuple(pymask.shape(1), pymask.shape(0)),\n\t\t\t\tnp::dtype::get_builtin<bool>());\n\n\t\t// Transpose\n\t\tfor(int i=0; i < _pymask.shape(0); ++i) {\n\t\t\tfor(int j=0; j < _pymask.shape(1); ++j) {\n\t\t\t\t_pymask[i][j] = pymask[j][i];\n\t\t\t}\n\t\t}\n\n\t\tEigen::Map<Eigen::Array<bool,Eigen::Dynamic,Eigen::Dynamic> >\n\t\t\t\t\t\tmask((bool*)_pymask.get_data(),_pymask.shape(1),_pymask.shape(0));\n\n    /* Output contours */\n    _ContContainer all_conts;\n\n    /*-------------------------------------------*/\n    /*         Call the actual function          */\n    /*-------------------------------------------*/\n    mask2polycont(mask, all_conts, tolerance);\n\n\t\tfor (std::size_t ii=0; ii<all_conts.size(); ++ii) {\n\n\t\tdtype = np::dtype::get_builtin<int>();\n\t\t\tnp::ndarray curr_poly = np::empty(\n\t\t\t\t\tpy::make_tuple(all_conts[ii].size(),2),dtype);\n\t\t\tfor (std::size_t jj=0; jj<all_conts[ii].size(); ++jj) {\n\t\t\t\tcurr_poly[jj][0] = all_conts[ii][jj].Y;\n\t\t\t\tcurr_poly[jj][1] = all_conts[ii][jj].X;\n\t\t\t}\n\t\t\tall_conts.contour_coords.append(curr_poly);\n\t\t}\n\n\t\treturn all_conts;\n}\n\nnp::ndarray _get_longest_cont(const py::list& contour_coords) {\n\n\tint max_id     = -1;\n\tint max_length = 0;\n\n\tfor(int jj = 0; jj < py::len(contour_coords); ++jj) {\n\t\tnp::ndarray arr = boost::python::extract<np::ndarray>(contour_coords[jj]);\n\t\tif(max_length <= arr.shape(0)) {\n\t\t\tmax_id     = jj;\n\t\t\tmax_length = arr.shape(0);\n\t\t}\n\t}\n\treturn boost::python::extract<np::ndarray>(contour_coords[max_id]);;\n}\n\nnp::ndarray _contour_upsample(const np::ndarray cont, float cont_th) {\n\n\tnp::ndarray _cont = cont.astype(np::dtype::get_builtin<float>());\n\n\tstruct Point {float x,y;};\n\tstd::vector<Point> diff(_cont.shape(0)-1);\n\n\tconst float* ptr_cont = (float*) _cont.get_data();\n\n\tfor(int i=1; i < cont.shape(0); ++i) {\n\t\tdiff[i-1].x = ptr_cont[i*2+0] - ptr_cont[(i-1)*2+0];\n\t\tdiff[i-1].y = ptr_cont[i*2+1] - ptr_cont[(i-1)*2+1];\n\t}\n\n\tstd::vector<float> nv(diff.size());\n\n\t// Compute length of each segment\n\tfor(int i=0; i<diff.size(); ++i) {\n\t\tnv[i] = sqrt(diff[i].x*diff[i].x + diff[i].y*diff[i].y);\n\t}\n\n\tstd::vector<Point> up_cont;\n\tup_cont.push_back(Point{ptr_cont[0],ptr_cont[1]});\n\n\t// Now upsample contour\n\tfor(int i=0; i<nv.size(); ++i) {\n\t\tif(nv[i] > cont_th) {\n\t\t\tint n_segm = ceil((float)nv[i]/(float)cont_th);\n\t\t\tPoint curr_point = up_cont.back();\n\t\t\tPoint vec{diff[i].x/(float)n_segm,diff[i].y/(float)n_segm};\n\n\t\t\tfor(int j=0; j < n_segm-1; ++j) {\n\t\t\t\tcurr_point.x += vec.x;\n\t\t\t\tcurr_point.y += vec.y;\n\t\t\t\tup_cont.push_back(curr_point);\n\t\t\t}\n\t\t}\n\t\tup_cont.push_back(Point{ptr_cont[(i+1)*2+0],ptr_cont[(i+1)*2+1]});\n\t}\n\t// Copy results\n\tnp::ndarray res = np::zeros(py::make_tuple(up_cont.size(), 2),\n\t\t\t\tnp::dtype::get_builtin<float>());\n\n\tfor(int i = 0; i < up_cont.size(); ++i) {\n\t\tres[i][0] = up_cont[i].x;\n\t\tres[i][1] = up_cont[i].y;\n\t}\n\treturn res;\n}\n// ------------------------------------------------------------------------\n// Jordi Pont-Tuset - http://jponttuset.github.io/\n// April 2016\n// ------------------------------------------------------------------------\n// This file is part of the DAVIS package presented in:\n//   Federico Perazzi, Jordi Pont-Tuset, Brian McWilliams,\n//   Luc Van Gool, Markus Gross, Alexander Sorkine-Hornung\n//   A Benchmark Dataset and Evaluation Methodology for Video Object Segmentation\n//   CVPR 2016\n// Please consider citing the paper if you use this code.\n// ------------------------------------------------------------------------\n\nusing namespace boost;\nusing namespace std;\n\n/* Typedefs from Boost */\ntypedef adjacency_list < listS, vecS, directedS,\n        no_property, property < edge_weight_t, double > > graph_t;\ntypedef graph_traits < graph_t >::vertex_descriptor vertex_descriptor;\ntypedef std::pair<int, int> Edge;\n\nstd::vector<vertex_descriptor> run_one_dijkstra(std::list<Edge>& edge_list, std::list<double>& edge_costs, const int num_nodes, int orig)\n{\n    /* Define the graph and the containers for the distances and parent nodes */\n    graph_t g(edge_list.begin(), edge_list.end(), edge_costs.begin(), num_nodes);\n    property_map<graph_t, edge_weight_t>::type weightmap = get(edge_weight, g);\n    std::vector<vertex_descriptor> parents(num_vertices(g));\n    std::vector<double>              dists(num_vertices(g));\n\n    /* Run Dijkstra to all nodes */\n    vertex_descriptor orig_vertex = vertex(orig, g);\n    dijkstra_shortest_paths(g, orig_vertex,\n            predecessor_map(boost::make_iterator_property_map(parents.begin(), get(vertex_index, g))).\n            distance_map(boost::make_iterator_property_map(dists.begin(), get(vertex_index, g))));\n\n    return parents;\n}\n\n\npy::tuple _match_dijkstra(const np::ndarray& prhs) {\n\n\t\tnp::ndarray _prhs = np::zeros(py::make_tuple(prhs.shape(1),prhs.shape(0)),\n\t\t\t\tnp::dtype::get_builtin<double>());\n\n\t\t// Transpose\n\t\tfor(int i=0; i < _prhs.shape(0); ++i) {\n\t\t\tfor(int j=0; j < _prhs.shape(1); ++j) {\n\t\t\t\t_prhs[i][j] = prhs[j][i];\n\t\t\t}\n\t\t}\n    /* Cost matrix (doubles) */\n    Eigen::Map<Eigen::Array<double,Eigen::Dynamic,Eigen::Dynamic> >\n            costs_matrix((double *)_prhs.get_data(),_prhs.shape(1),_prhs.shape(0));\n\t\tEigen::Array<double,Eigen::Dynamic,Eigen::Dynamic> costs(costs_matrix);\n\n\t\t//[> Sizes of the graph <]\n\t\tconst int n1 = costs.rows();\n\t\tconst int n2 = costs.cols();\n\t\tconst int num_nodes = n1*n2;\n\n\t\t//[> Create a look-up table for node indices <]\n\t\tEigen::Array<std::size_t,Eigen::Dynamic,Eigen::Dynamic> sub2ind(n1,n2);\n\t\tsize_t curr_id = 0;\n\t\tfor (size_t xx=0; xx<n1; ++xx)\n\t\t\t\tfor (size_t yy=0; yy<n2; ++yy)\n\t\t\t\t\t\tsub2ind(xx,yy) = curr_id++;\n\n\t\t//[> Inverted LUT <]\n\t\tvector<pair<size_t,size_t>> ind2sub(num_nodes);\n\t\tfor (size_t xx=0; xx<n1; ++xx)\n\t\t\t\tfor (size_t yy=0; yy<n2; ++yy)\n\t\t\t\t\t\tind2sub[sub2ind(xx,yy)] = make_pair(xx,yy);\n\n\t\t//[> Define the edges of the graph <]\n\t\tstd::list<Edge> edge_list;\n\t\tstd::list<double> edge_costs;\n\t\tfor (std::size_t xx=0; xx<n1; ++xx)\n\t\t{\n\t\t\t\tfor (std::size_t yy=0; yy<n2; ++yy)\n\t\t\t\t{\n\t\t\t\t\t\t//[> Down <]\n\t\t\t\t\t\tif (yy>0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tedge_list.emplace_back(sub2ind(xx,yy-1),sub2ind(xx,yy));\n\t\t\t\t\t\t\t\tedge_costs.emplace_back(costs(xx,yy));\n\t\t\t\t\t\t}\n\t\t\t\t\t\t//[> Left <]\n\t\t\t\t\t\tif (xx>0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tedge_list.emplace_back(sub2ind(xx-1,yy),sub2ind(xx,yy));\n\t\t\t\t\t\t\t\tedge_costs.emplace_back(costs(xx,yy));\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t//[> Down-left <]\n\t\t\t\t\t\tif ((yy>0) && (xx>0))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tedge_list.emplace_back(sub2ind(xx-1,yy-1),sub2ind(xx,yy));\n\t\t\t\t\t\t\t\tedge_costs.emplace_back(costs(xx,yy));\n\t\t\t\t\t\t}\n\t\t\t\t}\n\t\t}\n\n\n\t\t//[> Origin and destination nodes - First we assume the 0-0 matching <]\n\t\tint orig = 0;\n\t\tint dest = num_nodes-1;\n\t\tstd::vector<vertex_descriptor> parents = run_one_dijkstra(edge_list,edge_costs,num_nodes,orig);\n\n\t //Get path to destination by scanning predecessors\n\t //We also get the minimum-cost node\n\t\tstd::vector<size_t> opt_path;\n\t\tsize_t curr_predecessor = dest;\n\t\tdouble min_cost = numeric_limits<double>::max();\n\t\tsize_t min_id = curr_predecessor;\n\t\twhile(curr_predecessor!=orig)\n\t\t{\n\t\t\t\tdouble curr_cost = costs(ind2sub[curr_predecessor].first,ind2sub[curr_predecessor].second);\n\t\t\t\tif (curr_cost<min_cost)\n\t\t\t\t{\n\t\t\t\t\t\tmin_cost = curr_cost;\n\t\t\t\t\t\tmin_id = curr_predecessor;\n\t\t\t\t}\n\t\t\t\topt_path.emplace_back(curr_predecessor);\n\t\t\t\tcurr_predecessor = parents[curr_predecessor];\n\t\t}\n\t\topt_path.emplace_back(curr_predecessor);\n\t\tint min_xx = ind2sub[min_id].first;\n\t\tint min_yy = ind2sub[min_id].second;\n\n\t\tnp::ndarray outputMatrix = np::zeros(py::make_tuple(opt_path.size(),2),\n\t\t\t\tnp::dtype::get_builtin<double>());\n\n\t\t//[> Output pairs - +1 for Matlab <]\n\t\tfor (size_t i=0; i<opt_path.size(); i++) {\n\t\t\t\toutputMatrix[i][0] = ind2sub[opt_path[i]].first ;\n\t\t\t\toutputMatrix[i][1] = ind2sub[opt_path[i]].second;\n\t\t}\n\n\t\treturn py::make_tuple(outputMatrix,min_xx,min_yy);\n}\n\nBOOST_PYTHON_MODULE(tstab) {\n\t// Initialize numpy\n\tnp::initialize();\n\n\tpy::class_<_ContContainer,std::shared_ptr<_ContContainer>>(\n\t\t\t\"ContContainer\")\n\t\t.def_readwrite(\"contour_coords\",&_ContContainer::contour_coords)\n\t\t.def_readwrite(\"im_sx\",&_ContContainer::im_sx)\n\t\t.def_readwrite(\"im_sy\",&_ContContainer::im_sy)\n\t\t.def_readonly(\"is_hole\",&_ContContainer::is_hole);\n\n\tpy::def(\"mask2poly\",_mask2poly);\n\tpy::def(\"get_longest_cont\",_get_longest_cont);\n\tpy::def(\"contour_upsample\",_contour_upsample);\n\tpy::def(\"match_dijkstra\",_match_dijkstra);\n\n\tboost::python::class_<std::vector<bool>>(\"PyVecBool\")\n\t\t\t.def(boost::python::vector_indexing_suite<std::vector<bool>,true >());\n}\n\n", "meta": {"hexsha": "4164843ad9d1836330089ac68b35f18753fe2e93", "size": 9594, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "python/cpp/polycont/python.cpp", "max_stars_repo_name": "timmeinhardt/davis-2017", "max_stars_repo_head_hexsha": "3226015fbaab6d74716bf6d310275c6f5e3a974a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 135.0, "max_stars_repo_stars_event_min_datetime": "2016-04-17T06:59:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T03:46:04.000Z", "max_issues_repo_path": "python/cpp/polycont/python.cpp", "max_issues_repo_name": "timmeinhardt/davis-2017", "max_issues_repo_head_hexsha": "3226015fbaab6d74716bf6d310275c6f5e3a974a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 20.0, "max_issues_repo_issues_event_min_datetime": "2017-09-20T11:51:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-02T01:25:42.000Z", "max_forks_repo_path": "python/cpp/polycont/python.cpp", "max_forks_repo_name": "timmeinhardt/davis-2017", "max_forks_repo_head_hexsha": "3226015fbaab6d74716bf6d310275c6f5e3a974a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 52.0, "max_forks_repo_forks_event_min_datetime": "2016-05-14T14:13:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-08T16:30:22.000Z", "avg_line_length": 31.3529411765, "max_line_length": 137, "alphanum_fraction": 0.6306024599, "num_tokens": 2824, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.48259227823095796}}
{"text": "#include \"truncate.hpp\"\n#include \"ast.hpp\"\n#include \"parsers.hpp\"\n#include \"types.hpp\"\n#include \"all.hpp\"\n#include <boost/variant.hpp>\n#include <stdexcept>\n#include <cmath>\nnamespace HT\n{\n    void truncate(PASTNode astnode, ParsersHelper& ph)\n    {\n        auto & secondCh = *astnode->ch.rbegin();\n        validateEach(astnode, ph, \"truncate\", 1, [](PASTNode an)\n                    {\n                    return an->token.tokenType == Complex && boost::get<ComplexType>(an->token.info).isReal();\n                    });\n        auto cast = boost::get<ComplexType>(secondCh->token.info);\n\n        astnode->type = Simple;\n        astnode->token.tokenType = Complex;\n        if (!cast.exact())\n        astnode->token.info = ComplexType(\n                    std::trunc(\n                        cast.toinexact().getRealD()\n                        ));\n        else\n        {\n            auto rat = cast.getRealR();\n            auto ans = rat.getUp() / rat.getDown();\n            ans.setSign(rat.getSign());\n            astnode->token.info = ComplexType(ans);\n        }\n\n        astnode->remove();\n    }\n\n}\n\n\n", "meta": {"hexsha": "30c7dfc3bb42a0ef6c4f4cd03f77a4d88f647fb9", "size": 1102, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "funs/truncate.cpp", "max_stars_repo_name": "htfy96/htscheme", "max_stars_repo_head_hexsha": "b44c9f9672f69d9b3c2eb1c80969bcfcfec9990f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2015-07-07T01:30:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-14T10:45:01.000Z", "max_issues_repo_path": "funs/truncate.cpp", "max_issues_repo_name": "htfy96/htscheme", "max_issues_repo_head_hexsha": "b44c9f9672f69d9b3c2eb1c80969bcfcfec9990f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "funs/truncate.cpp", "max_forks_repo_name": "htfy96/htscheme", "max_forks_repo_head_hexsha": "b44c9f9672f69d9b3c2eb1c80969bcfcfec9990f", "max_forks_repo_licenses": ["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.8780487805, "max_line_length": 110, "alphanum_fraction": 0.5245009074, "num_tokens": 252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.48259226085901735}}
{"text": "\n// BLAS level 3\n\n//#define F_USE_STD_VECTOR\n\n//#define BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n\n#include <iostream>\n#include <boost/numeric/bindings/blas/level3.hpp>\n#include <boost/numeric/bindings/ublas/matrix.hpp>\n#include <boost/numeric/bindings/ublas/matrix_proxy.hpp>\n#include <boost/numeric/bindings/trans.hpp>\n#ifdef F_USE_STD_VECTOR\n#include <vector>\n#include <boost/numeric/bindings/std/vector.hpp> \n#endif \n#include \"utils.h\"\n\nnamespace ublas = boost::numeric::ublas;\nnamespace blas = boost::numeric::bindings::blas;\n\nusing std::cout;\nusing std::endl; \n\n#ifndef F_USE_STD_VECTOR\ntypedef ublas::matrix<double, ublas::row_major> m_t;\n#else\ntypedef ublas::matrix<double, ublas::column_major, std::vector<double> > m_t;\n#endif \n\nint main() {\n\n  cout << endl; \n\n  m_t a (4, 4);\n  init_m (a, kpp (1)); \n  print_m (a, \"a\"); \n  cout << endl; \n\n  m_t b (4, 6);\n  init_m (b, cls1()); \n  print_m (b, \"b\"); \n  cout << endl; \n  \n  m_t c (4, 6);\n\n  // c = a b\n  blas::gemm ( 1.0, a, b, 0.0, c); \n  print_m (c, \"c = a b\"); \n  cout << endl; \n  blas::gemm ( 1.0, a, b, 0.0, c); \n  print_m (c, \"c = a b\"); \n  cout << endl; \n\n  init_m (c, const_val<double> (1)); \n  print_m (c, \"c\"); \n  cout << endl; \n  // c = 2 a b + 0.5 c\n  blas::gemm (2.0, a, b, 0.05, c);\n  print_m (c, \"c = 2 a b + 0.05 c\"); \n  cout << endl; \n\n  m_t d (6, 4);\n\n  // d = b^T a^T\n  blas::gemm ( 1.0, bindings::trans(b), bindings::trans(a), 0.0, d);\n  print_m (d, \"d = b^T a^T\"); \n  cout << endl; \n\n  // c = a^T b \n  blas::gemm (1.0, bindings::trans(a), b, 0.0, c); \n  print_m (c, \"c = a^T b\"); \n  cout << endl; \n\n  // d = b^T a\n  blas::gemm ( 1.0, bindings::trans(b), a, 0.0, d);\n  print_m (d, \"d = b^T a\"); \n  cout << endl; \n\n  init_m (d, const_val<double> (0)); \n  ublas::matrix_range<m_t> br (b, ublas::range (0, 4), ublas::range (0, 4)); \n  ublas::matrix_range<m_t> dr (d, ublas::range (1, 5), ublas::range (0, 4)); \n\n  // d[1..5][0..4] = a b[0..4][0..4]  \n  blas::gemm ( 1.0, a, br, 0.0, dr); \n  print_m (d, \"d[1..5][0..4] = a b[0..4][0..4]\"); \n  cout << endl; \n  \n  // d[1..5][0..4] = b[0..4][0..4] a\n  blas::gemm ( 1.0, br, a, 0.0, dr); \n  print_m (d, \"d[1..5][0..4] = b[0..4][0..4] a\"); \n  cout << endl; \n  \n  // d[1..5][0..4] = b[0..4][0..4] a^T\n  blas::gemm ( 1.0, br, bindings::trans(a), 0.0, dr);\n  print_m (d, \"d[1..5][0..4] = b[0..4][0..4] a^T\"); \n  cout << endl; \n\n  // d[1..5][0..4] = a b[0..4][0..4]^T\n  blas::gemm ( 1.0, a, bindings::trans(br), 0.0, dr);\n  print_m (d, \"d[1..5][0..4] = a b[0..4][0..4]^T\"); \n  cout << endl; \n\n}\n", "meta": {"hexsha": "3af5f01adb512c50a9c2f72b7d8cf5ea4150046b", "size": 2505, "ext": "cc", "lang": "C++", "max_stars_repo_path": "externals/numeric_bindings/libs/numeric/bindings/atlas/ublas_matr3.cc", "max_stars_repo_name": "ljktest/siconos", "max_stars_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 137.0, "max_stars_repo_stars_event_min_datetime": "2015-06-16T15:55:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T06:01:59.000Z", "max_issues_repo_path": "externals/numeric_bindings/libs/numeric/bindings/atlas/ublas_matr3.cc", "max_issues_repo_name": "ljktest/siconos", "max_issues_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 381.0, "max_issues_repo_issues_event_min_datetime": "2015-09-22T15:31:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-14T09:05:23.000Z", "max_forks_repo_path": "externals/numeric_bindings/libs/numeric/bindings/atlas/ublas_matr3.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": 23.8571428571, "max_line_length": 77, "alphanum_fraction": 0.5413173653, "num_tokens": 1084, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872243177518, "lm_q2_score": 0.6442251133170357, "lm_q1q2_score": 0.48258080197044734}}
{"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 <Eigen/Dense>\n#include <iostream>\n#include <fstream>\n\n#include <boost/program_options.hpp>\n\n#include <dpMM/normalSphere.hpp>\n\nusing namespace Eigen;\nusing std::string; \n\nnamespace po = boost::program_options;\n\nint main(int argc, char** argv)\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    (\"K,K\", po::value<int>(), \"number of initial clusters \")\n    (\"nu,nu\", po::value<double>(), \"nu parameter of IW from which \"\n      \"sigmas are sampled\")\n    (\"minAngle,a\", po::value<double>(), \"min angle between means on sphere\")\n    (\"delta,d\", po::value<double>(), \"delta of NIW\")\n    (\"output,o\", po::value<string>(), \n      \"path to output labels and data .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  uint32_t N=100;\n  if (vm.count(\"N\")) N = vm[\"N\"].as<int>();\n  uint32_t D=3;\n  if (vm.count(\"D\")) D = vm[\"D\"].as<int>();\n  string pathOut =\"./rndSphereData\";\n  if(vm.count(\"output\")) \n    pathOut = vm[\"output\"].as<string>();\n  cout<<\"output to \"<<pathOut<<endl;\n  \n  double nu = static_cast<double>(D)+2.; // 100 for spherical\n  if (vm.count(\"nu\")) nu = vm[\"nu\"].as<double>();\n  if(nu < static_cast<double>(D)+1.+1e-8)\n    nu = static_cast<double>(D)+1.+1e-8;\n  double minAngle = 6.;\n  if (vm.count(\"minAngle\")) minAngle = vm[\"minAngle\"].as<double>(); \n  double delta = 6.;\n  if (vm.count(\"delta\")) delta = vm[\"delta\"].as<double>(); \n\n  MatrixXd Delta(D-1,D-1);\n  Delta = MatrixXd::Identity(D-1,D-1);\n  Delta *= nu*(delta*PI/180.)*(delta*PI/180.);\n\n//  double nu = D+0.1\n//  MatrixXd Delta(D,D);\n//  Delta.setIdentity();\n//  Delta *= nu * (12.*PI)/180.0;\n  MatrixXd x(D,N);\n  VectorXu z(N);\n  sampleClustersOnSphere<double>(Delta,nu,x,z,K,minAngle);\n  for(uint32_t i=0; i<N-1; ++i)\n    if(fabs(x.col(i).norm()-1.0) > 1e-2)\n    {\n      cout<<\"@\"<<i<<\":\"<<x.col(i).norm()<<endl;\n      cout<<\" error in generating data\"<<endl;\n      return 0;\n    }\n\n  std::ofstream fout;\n  fout.open((pathOut+\".csv\").data(),std::ofstream::out);\n  for(uint32_t d=0; d<D; ++d)\n  {\n    for(uint32_t i=0; i<N-1; ++i)\n      fout<<x(d,i)<<\" \";\n    fout<<x(d,N-1)<<endl;\n  }\n  fout.close();\n  fout.open((pathOut+\"_gt.lbl\").data(),std::ofstream::out);\n    for(uint32_t i=0; i<N-1; ++i)\n      fout<<z(i)<<\" \";\n    fout<<z(N-1)<<endl;\n  fout.close();\n\n}\n", "meta": {"hexsha": "27d5ec621c3b47daa678c18ba44035d609e626c3", "size": 3057, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/generateSphericalData.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/generateSphericalData.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/generateSphericalData.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": 29.1142857143, "max_line_length": 78, "alphanum_fraction": 0.5930650965, "num_tokens": 958, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.4825807998699423}}
{"text": "/*=============================================================================\n    Copyright (c) 2001-2007 Hartmut Kaiser\n    Copyright (c) 2020 Nikita Kniazev\n    http://spirit.sourceforge.net/\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\n#include <boost/preprocessor/cat.hpp>\n#include <boost/spirit/include/classic_core.hpp> \n#include <boost/spirit/include/classic_ast.hpp> \n#include <boost/spirit/include/classic_tree_to_xml.hpp> \n\n#include <boost/core/lightweight_test.hpp>\n\n#include <iostream>\n#include <iterator>\n#include <fstream>\n#include <ostream>\n#include <string>\n\nusing namespace BOOST_SPIRIT_CLASSIC_NS; \n\n///////////////////////////////////////////////////////////////////////////////\nstruct calculator : public grammar<calculator>\n{\n    static const int integerID = 1;\n    static const int factorID = 2;\n    static const int termID = 3;\n    static const int expressionID = 4;\n\n    template <typename ScannerT>\n    struct definition\n    {\n        definition(calculator const& /*self*/)\n        {\n            //  Start grammar definition\n            integer     =   leaf_node_d[ lexeme_d[\n                                (!ch_p('-') >> +digit_p)\n                            ] ];\n\n            factor      =   integer\n                        |   inner_node_d[ch_p('(') >> expression >> ch_p(')')]\n                        |   (root_node_d[ch_p('-')] >> factor);\n\n            term        =   factor >>\n                            *(  (root_node_d[ch_p('*')] >> factor)\n                              | (root_node_d[ch_p('/')] >> factor)\n                            );\n\n            expression  =   term >>\n                            *(  (root_node_d[ch_p('+')] >> term)\n                              | (root_node_d[ch_p('-')] >> term)\n                            );\n            //  End grammar definition\n\n            // turn on the debugging info.\n            BOOST_SPIRIT_DEBUG_RULE(integer);\n            BOOST_SPIRIT_DEBUG_RULE(factor);\n            BOOST_SPIRIT_DEBUG_RULE(term);\n            BOOST_SPIRIT_DEBUG_RULE(expression);\n        }\n\n        rule<ScannerT, parser_context<>, parser_tag<expressionID> >   expression;\n        rule<ScannerT, parser_context<>, parser_tag<termID> >         term;\n        rule<ScannerT, parser_context<>, parser_tag<factorID> >       factor;\n        rule<ScannerT, parser_context<>, parser_tag<integerID> >      integer;\n\n        rule<ScannerT, parser_context<>, parser_tag<expressionID> > const&\n        start() const { return expression; }\n    };\n};\n\n///////////////////////////////////////////////////////////////////////////////\n/// a streambuf implementation that sinks characters to output iterator\ntemplate <typename OutputIterator, typename Char>\nstruct psbuf : std::basic_streambuf<Char>\n{\n    template <typename T>\n    psbuf(T& sink) : sink_(sink) {}\n\n    // silence MSVC warning C4512: assignment operator could not be generated\n    BOOST_DELETED_FUNCTION(psbuf& operator=(psbuf const&))\n\nprotected:\n    typename psbuf::int_type overflow(typename psbuf::int_type ch) BOOST_OVERRIDE\n    {\n        if (psbuf::traits_type::eq_int_type(ch, psbuf::traits_type::eof()))\n            return psbuf::traits_type::not_eof(ch);\n\n        *sink_ = psbuf::traits_type::to_char_type(ch);\n        ++sink_;\n        return ch;\n    }\n\nprivate:\n    OutputIterator sink_;\n};\n\n///////////////////////////////////////////////////////////////////////////////\n#define EXPECTED_XML_OUTPUT \"<?xml version=\\\"1.0\\\" encoding=\\\"ISO-8859-1\\\"?>\\n\\\n<!DOCTYPE parsetree SYSTEM \\\"parsetree.dtd\\\">\\n\\\n<!-- 1+2 -->\\n\\\n<parsetree version=\\\"1.0\\\">\\n\\\n    <parsenode>\\n\\\n        <value>+</value>\\n\\\n        <parsenode>\\n\\\n            <value>1</value>\\n\\\n        </parsenode>\\n\\\n        <parsenode>\\n\\\n            <value>2</value>\\n\\\n        </parsenode>\\n\\\n    </parsenode>\\n\\\n</parsetree>\\n\"\n\n#define EXPECTED_XML_OUTPUT_WIDE BOOST_PP_CAT(L, EXPECTED_XML_OUTPUT)\n\nbool test(wchar_t const *text)\n{\n    typedef std::basic_string<wchar_t>::iterator iterator_t; \n\n    std::basic_string<wchar_t> input(text); \n    calculator calc; \n    tree_parse_info<iterator_t> ast_info = \n        ast_parse(iterator_t(input.begin()), iterator_t(input.end()), \n            calc >> end_p, space_p); \n\n    std::basic_string<wchar_t> out;\n    {\n        psbuf<std::back_insert_iterator<std::wstring>, wchar_t> buf(out);\n        std::wostream outsink(&buf);\n        basic_tree_to_xml<wchar_t>(outsink, ast_info.trees, input); \n    }\n    return out == EXPECTED_XML_OUTPUT_WIDE;\n} \n\nbool test(char const *text)\n{\n    typedef std::string::iterator iterator_t; \n\n    std::string input(text); \n    calculator calc; \n    tree_parse_info<iterator_t> ast_info = \n        ast_parse(iterator_t(input.begin()), iterator_t(input.end()), \n            calc >> end_p, space_p); \n\n    std::string out;\n    {\n        psbuf<std::back_insert_iterator<std::string>, char> buf(out);\n        std::ostream outsink(&buf);\n        basic_tree_to_xml<char>(outsink, ast_info.trees, input); \n    }\n    return out == EXPECTED_XML_OUTPUT;\n} \n\nint main() \n{ \n    BOOST_TEST(test(\"1+2\"));\n    if (std::has_facet<std::ctype<wchar_t> >(std::locale()))\n    {\n        BOOST_TEST(test(L\"1+2\"));\n    }\n    return boost::report_errors();\n}\n", "meta": {"hexsha": "0fa655c6830f2026d64c8ec98dcd6460dfd4a19d", "size": 5420, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/boost_1.78.0/libs/spirit/classic/test/tree_to_xml.cpp", "max_stars_repo_name": "LaudateCorpus1/math", "max_stars_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-10-27T21:15:52.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-27T21:15:52.000Z", "max_issues_repo_path": "lib/boost_1.78.0/libs/spirit/classic/test/tree_to_xml.cpp", "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": "lib/boost_1.78.0/libs/spirit/classic/test/tree_to_xml.cpp", "max_forks_repo_name": "LaudateCorpus1/math", "max_forks_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-24T08:49:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-24T08:49:34.000Z", "avg_line_length": 32.4550898204, "max_line_length": 81, "alphanum_fraction": 0.5557195572, "num_tokens": 1247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251201477016, "lm_q2_score": 0.7490872075132153, "lm_q1q2_score": 0.48258079626130745}}
{"text": "#ifndef TYPES_HPP_\n#define TYPES_HPP_\n\n#include <Eigen/Eigen>\n\ntypedef Eigen::ArrayXXf Image;\ntypedef Eigen::ArrayXXf Kernel;\n\nenum Filter { BLUR, DER_X, DER_Y, DER_MAG };\n\n#endif", "meta": {"hexsha": "51db1bc48fe1faeb6ce79d8c43ea2a05688519be", "size": 179, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Homework7/hw7/src/types.hpp", "max_stars_repo_name": "xehoth/CS100", "max_stars_repo_head_hexsha": "b9f069a55cccd3922f6d2f359afcd9fde1ba05f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-01-18T14:38:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-29T10:38:20.000Z", "max_issues_repo_path": "Homework7/hw7/src/types.hpp", "max_issues_repo_name": "xehoth/CS100", "max_issues_repo_head_hexsha": "b9f069a55cccd3922f6d2f359afcd9fde1ba05f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Homework7/hw7/src/types.hpp", "max_forks_repo_name": "xehoth/CS100", "max_forks_repo_head_hexsha": "b9f069a55cccd3922f6d2f359afcd9fde1ba05f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-29T04:43:18.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-29T04:43:18.000Z", "avg_line_length": 16.2727272727, "max_line_length": 44, "alphanum_fraction": 0.7597765363, "num_tokens": 46, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.749087201911703, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.48258079265267245}}
{"text": "#include <stan/math/prim/mat.hpp>\n#include <stan/math/prim/scal.hpp>\n#include <test/unit/math/prim/prob/vector_rng_test_helper.hpp>\n#include <test/unit/math/prim/prob/VectorIntRNGTestRig.hpp>\n#include <test/unit/math/prim/prob/util.hpp>\n#include <boost/math/distributions.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <gtest/gtest.h>\n#include <limits>\n#include <vector>\n\nclass BernoulliLogitTestRig : public VectorIntRNGTestRig {\n public:\n  BernoulliLogitTestRig()\n      : VectorIntRNGTestRig(10000, 10, {0, 1},\n                            {-5.7, -1.0, 0.0, 0.2, 1.0, 10.0}, {-3, -2, 0, 1},\n                            {}, {}) {}\n\n  template <typename T1, typename T2, typename T3, typename T_rng>\n  auto generate_samples(const T1& t, const T2&, const T3&, T_rng& rng) const {\n    return stan::math::bernoulli_logit_rng(t, rng);\n  }\n\n  template <typename T1>\n  double pmf(int y, T1 t, double, double) const {\n    return std::exp(stan::math::bernoulli_logit_lpmf(y, t));\n  }\n};\n\nTEST(ProbDistributionsBernoulliLogit, errorCheck) {\n  check_dist_throws_all_types(BernoulliLogitTestRig());\n}\n\nTEST(ProbDistributionsBernoulliLogit, distributionCheck) {\n  check_counts_real(BernoulliLogitTestRig());\n}\n\nTEST(ProbDistributionsBernoulliLogit, error_check) {\n  boost::random::mt19937 rng;\n\n  EXPECT_NO_THROW(stan::math::bernoulli_logit_rng(-3.5, rng));\n  EXPECT_THROW(\n      stan::math::bernoulli_logit_rng(stan::math::positive_infinity(), rng),\n      std::domain_error);\n}\n\nTEST(ProbDistributionsBernoulliLogit, logitChiSquareGoodnessFitTest) {\n  boost::random::mt19937 rng;\n  // number of samples\n  int N = 10000;\n\n  // logit-transformed probability\n  double parameter = -0.5;\n  // actual probability\n  double prob = stan::math::inv_logit(-0.5);\n\n  std::vector<double> expected;\n  expected.push_back(N * (1 - prob));\n  expected.push_back(N * prob);\n\n  std::vector<int> counts(2);\n  for (int i = 0; i < N; ++i) {\n    ++counts[stan::math::bernoulli_logit_rng(parameter, rng)];\n  }\n\n  assert_chi_squared(counts, expected, 1e-6);\n}\n", "meta": {"hexsha": "9652acccd1ef4016a87317991512d3ddd97de8e0", "size": 2034, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/prim/prob/bernoulli_logit_test.cpp", "max_stars_repo_name": "christophernhill/math", "max_stars_repo_head_hexsha": "dc41aba296d592c7099be15eed6ba136d0f140b3", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/unit/math/prim/prob/bernoulli_logit_test.cpp", "max_issues_repo_name": "christophernhill/math", "max_issues_repo_head_hexsha": "dc41aba296d592c7099be15eed6ba136d0f140b3", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/unit/math/prim/prob/bernoulli_logit_test.cpp", "max_forks_repo_name": "christophernhill/math", "max_forks_repo_head_hexsha": "dc41aba296d592c7099be15eed6ba136d0f140b3", "max_forks_repo_licenses": ["BSD-3-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.9117647059, "max_line_length": 78, "alphanum_fraction": 0.6951819076, "num_tokens": 625, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.749087201911703, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.48258079265267245}}
{"text": "/*(utf8)\nSimple moving median filter\n*/\n\n#include <cmath>\n#include <boost/container/flat_map.hpp>\n\n#include \"filter_base.hpp\"\n\nnamespace value_filters\n{\n\ntemplate <typename T = double>\nclass floating_median : public filter_base<T>\n{\n\npublic:\n  floating_median() {}\n\n  T operator()(T x)\n  {\n    if (!std::isnan(x) || !std::isinf(x))\n    {\n      buffer[x] = date;\n\n      if (buffer.size() > capacity)\n        for (auto it = buffer.begin(); it < buffer.end(); it++)\n          if (it->second <= (date - capacity))\n          {\n            buffer.erase(it);\n            break;\n          }\n\n      date++;\n    }\n\n    if (buffer.size() % 2 == 0)\n    {\n      int middle = buffer.size() / 2;\n      auto mid1 = buffer.nth(middle--)->first;\n      auto mid2 = buffer.nth(middle)->first;\n      return (mid1 + mid2) / 2.;\n    }\n    else\n    {\n      return buffer.nth(buffer.size() / 2)->first;\n    }\n  }\n\n  void set_amount(double amt)\n  {\n    if (amt < 1)\n      amt = 1;\n\n    capacity = amt;\n\n    if (buffer.size() > capacity)\n      for (auto it = buffer.begin(); it < buffer.end(); it++)\n        if (it->second <= (date - capacity))\n          buffer.erase(it);\n  }\n\n  void update()\n  {\n  }\n\nprivate:\n  boost::container::flat_map<T, int> buffer{};\n\n  int date{0}, capacity{static_cast<int>(SCALED_AMOUNT)};\n};\n\n}\n", "meta": {"hexsha": "e7990557e8984b5c9e937339691a2ac1bee32620", "size": 1297, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/median.hpp", "max_stars_repo_name": "jcelerier/dno", "max_stars_repo_head_hexsha": "18a823daed9904478802951f0a2e1141cf55bedb", "max_stars_repo_licenses": ["MIT"], "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/median.hpp", "max_issues_repo_name": "jcelerier/dno", "max_issues_repo_head_hexsha": "18a823daed9904478802951f0a2e1141cf55bedb", "max_issues_repo_licenses": ["MIT"], "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/median.hpp", "max_forks_repo_name": "jcelerier/dno", "max_forks_repo_head_hexsha": "18a823daed9904478802951f0a2e1141cf55bedb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.527027027, "max_line_length": 63, "alphanum_fraction": 0.5397070162, "num_tokens": 353, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.48258078963641327}}
{"text": "// util.hpp\n#ifndef COURSERA_UTIL_HPP\n#define COURSERA_UTIL_HPP\n\n#include <cassert>\n#include <cmath>\n#include <string>\n#include <vector>\n#include <armadillo>\n\ntemplate <typename T>\nbool is_almost_equal(const T a, const T b, const uint8_t decimal_accuracy)\n{\n    const T ac = std::round(a * (10 ^ decimal_accuracy)) / (10 ^ decimal_accuracy);\n    const T bc = std::round(b * (10 ^ decimal_accuracy)) / (10 ^ decimal_accuracy);\n\n    return ac == bc;\n}\n\ntemplate <typename T>\nbool compare_mat(const T &mat_a, const T &mat_b, const uint8_t decimal_accuracy)\n{\n    using namespace std;\n    using namespace arma;\n\n    static_assert(is_base_of<mat, T>::value || is_base_of<fmat, T>::value, \"T must extend Armadillo Mat<double> || Mat<float>\");\n\n    if (mat_a.n_cols != mat_b.n_cols || mat_a.n_rows != mat_b.n_rows)\n    {\n        throw invalid_argument(\"sizes of Mats differ\");\n    }\n\n    for (size_t r = 0; r < mat_a.n_rows; r++)\n    {\n        for (size_t c = 0; c < mat_a.n_cols; c++)\n        {\n            const double a = round(mat_a(r, c) * (10 ^ decimal_accuracy)) / (10 ^ decimal_accuracy);\n            const double b = round(mat_b(r, c) * (10 ^ decimal_accuracy)) / (10 ^ decimal_accuracy);\n            if (a != b)\n            {\n                return false;\n            }\n        }\n    }\n    return true;\n}\n\ntemplate <typename T>\nvoid parse_mat(T *targetmat, const std::string source)\n{\n    using namespace std;\n    using namespace arma;\n\n    static_assert(is_base_of<mat, T>::value || is_base_of<fmat, T>::value, \"T must extend Armadillo Mat<double> || Mat<float>\");\n\n    if (!(source.front() == '[' && source.back() == ']'))\n    {\n        throw invalid_argument(\"can not parse Mat\");\n    }\n\n    size_t cols = 0, rows = 0;\n    vector<double> v;\n\n    size_t semi_pos = 0, lsemi_pos = 0;\n    do\n    {\n        size_t c = 0;\n        size_t col_pos = semi_pos, lcol_pos = lsemi_pos;\n        semi_pos = source.find(';', semi_pos + 1);\n        do\n        {\n            const auto srclen = (semi_pos != string::npos ? semi_pos : source.length()) - 1;\n            col_pos = source.substr(0, srclen).find(',', col_pos + 1);\n            if (col_pos != string::npos)\n            {\n                v.push_back(stod(source.substr(lcol_pos + 1, col_pos - lcol_pos)));\n                c++;\n            }\n            else if (semi_pos != string::npos)\n            {\n                // get single/last column\n                v.push_back(stod(source.substr(lcol_pos + 1, semi_pos - lcol_pos)));\n                c++;\n            }\n            else\n            {\n                // get last column in last row\n                v.push_back(stod(source.substr(lcol_pos + 1, source.length() - 1)));\n                c++;\n            }\n            lcol_pos = col_pos;\n        } while (col_pos != string::npos);\n        lsemi_pos = semi_pos;\n        if (cols == 0)\n        {\n            cols = c;\n        }\n        else if (c != cols)\n        {\n            string msg = \"can not parse Mat at row \" + to_string(rows);\n            throw invalid_argument(msg.c_str());\n        }\n        rows++;\n    } while (semi_pos != string::npos);\n\n    targetmat->set_size(rows, cols);\n\n    for (size_t r = 0, i = 0; r < rows; r++)\n    {\n        for (size_t c = 0; c < cols; c++, i++)\n        {\n            (*targetmat)(r, c) = v[i];\n        }\n    }\n}\n\n#endif // COURSERA_UTIL_HPP\n", "meta": {"hexsha": "37c2ac6a51eece706bb5e6845f2c68dddc0c704d", "size": 3339, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ex1/util.hpp", "max_stars_repo_name": "kolbma/coursera-ml", "max_stars_repo_head_hexsha": "a8473829138804cf6a46cc60e076d9851b55ae25", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-15T21:08:21.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-15T21:08:21.000Z", "max_issues_repo_path": "ex1/util.hpp", "max_issues_repo_name": "kolbma/coursera-ml", "max_issues_repo_head_hexsha": "a8473829138804cf6a46cc60e076d9851b55ae25", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ex1/util.hpp", "max_forks_repo_name": "kolbma/coursera-ml", "max_forks_repo_head_hexsha": "a8473829138804cf6a46cc60e076d9851b55ae25", "max_forks_repo_licenses": ["Apache-2.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.2966101695, "max_line_length": 128, "alphanum_fraction": 0.5312967954, "num_tokens": 876, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.7490872131147275, "lm_q1q2_score": 0.4825807896364132}}
{"text": "#include <iostream>\n#include <armadillo.h>\n#include <digitRecognition.h>\n//#include <mkl.h>\n#include <iomanip>\n\nusing namespace arma;\n\n\n//support functions\n//cost = fmincg2(10000, nn_params2, k, n , num_labels, X, y, 0.01)\n//real function fmincg2(length, nn_params, input_layer_size, hidden_layer_size, num_labels, inputdata, y, lambda)\n\nvoid fmincg(double& finalcost, const int length,mat& nn_params,const int input_layer_size,const int hidden_layer_size,const int num_labels,mat& inputdata,mat& y,const double lambda){\n// Copyright (C) 2001 and 2002 by Carl Edward Rasmussen. Date 2002-02-13\n// (C) Copyright 1999, 2000 & 2001, Carl Edward Rasmussen\n// \n// Permission is granted for anyone to copy, use, or modify these\n// programs and accompanying documents for purposes of research or\n// education, provided this copyright notice is retained, and note is\n// made of any changes that have been made.\n// \n// These programs and documents are distributed without any warranty,\n// express or implied.  As the programs were written for research\n// purposes only, they have not been tested to the degree that would be\n// advisable in any important application.  All use of these programs is\n// entirely at the user's own risk.\n//\n// [ml-class] Changes Made:\n// 1) Function name and argument specifications\n// 2) Output display\n//\n// [John Shahbazian] Changes Made:\n// 1) Ported to C++ using the Armadillo (http://arma.sourceforge.net/) library\n// 2) Change the cost function call to internal.  Replace the\n//    'costfunction' function to whatever you would like.  It returns\n//    the cost as the result, and the gradient is returned through the first \n//    argument as an intent(inout) (e.g. 'gradient#').  \n// 3) Changed the variable names to be readable.\n//    f1 = cost1\n//    df1 = gradient1\n//    s = search_direction\n//    d1 = slope1\n//    z1 = point1\n//    X0 = backup_params\n//    f0 = cost_backup\n//    df0 = gradient_backup \n\n\tconst double RHO = 0.01;\n\tconst double SIG = 0.5;\n\tconst double INT = 0.1;\n\tconst double EXT = 3.0;\n\tconst int MAXEVALS = 20;\n\tconst double RATIO = 100;\n\t\n\tdouble mintemp, minstuff, M, A, B;\n\tdouble fX = 0.0;\n\tint success;\n\tint i=0;\n\tint ls_failed = 0;\n\t\n\tmat backup_params = nn_params;\n\tmat gradient2(nn_params.n_rows,nn_params.n_cols,fill::zeros);\n\tmat gradient3(nn_params.n_rows,nn_params.n_cols,fill::zeros);\n\tmat gradient_backup(nn_params.n_rows,nn_params.n_cols,fill::zeros);\n\tmat tmp(nn_params.n_rows,nn_params.n_cols,fill::zeros);\n\tdouble limit;\n\tdouble point1, point2, point3;\n\tdouble cost1, cost2, cost3, cost_backup;\n\tdouble slope1, slope2, slope3;\n\tmat search_direction(nn_params.n_rows,nn_params.n_cols,fill::zeros);\n\tmat stemp(nn_params.n_rows,nn_params.n_cols,fill::zeros);\n\t\n\tdouble sqrtnumber;\n\t//mat sd_calc_1,sd_calc_2,sd_calc_3;\n\t//double sd_calc_4;\n\t//mat sd_calc_5(nn_params.n_rows,nn_params.n_cols,fill::zeros);\n\n\t\n\tcost1 = 10000.0;  //lower is better, so init with high\n\tmat gradient1(nn_params.n_rows,nn_params.n_cols,fill::zeros);\n\tcostfunction(cost1, gradient1, nn_params, input_layer_size, hidden_layer_size, num_labels, inputdata, y, lambda);\n\t//std::cout << \"gradient1: \" << gradient1(0,0) << endl;\n\t//pause();\n\n\t//i = i + (length<0);\n\tsearch_direction = -gradient1;\n\n\tmat slope_vector(1,1);\n\tslope_vector = -search_direction.t() * search_direction;\n\tslope1 = slope_vector(0,0);\n\tpoint1 = 1.0/(1.0 - slope1);\n\t//std::cout << \"point1: \" << point1 << endl;\n\n\twhile(i < std::abs(length)){\n\t\ti = i + 1;\n\t\t//std::cout << \"loop: \" << i << endl;\n\t\tbackup_params = nn_params;\n\t\tcost_backup = cost1;\n\t\tgradient_backup = gradient1;\n\t\tstemp = point1 * search_direction;\n\t\tnn_params = nn_params + stemp;\n\t\t//std::cout << \"nn_params: \" << nn_params.row(0) << endl;\n\n\t\tgradient2 = gradient1;\n\t\t\n\t\tcost2 = 10000.0;\n\t\tcostfunction(cost2, gradient2, nn_params, input_layer_size, hidden_layer_size, num_labels, inputdata, y, lambda);\n\t\t\n\t\t//i = i + (length<0);\n\t\t//i++;\n\t\t//std::cout << \"i: \" << i << endl;\n\t\tslope_vector = gradient2.t() * search_direction;\n\t\tslope2 = slope_vector(0,0);\n\t\t//std::cout << \"slope2: \" << slope2 << endl;\n\n\n\t\tcost3 = cost1;\n\t\tslope3 = slope1;\n\t\tpoint3 = -point1;\n\t\tif(length>0)M=MAXEVALS;\n\t\telse M = std::min(MAXEVALS,-length-i);\n\t\tsuccess=0;\n\t\tlimit=-1;\n\t\t\n\t\twhile(1){ //3.66252   3.66252  0 -5.40439\n\t\t\t//std::cout << \"cost2: \" << cost2 << \" cost1: \" << cost1 << \" point1: \" << point1 << \" slope1: \" << slope1 << endl;\n\t\t\t//std::cout << \"cost2 vs stuff: \" << cost2 << \"   \" << (cost1 + (point1 * RHO * slope1)) << endl;\n\t\t\t//std::cout << \"slope2 vs stuff: \" << slope2 << \"   \" << (-SIG * slope1) << endl;\n\t\t\t//std::cout << \"M: \" << M << endl;\n\t\t\t//pause();\n\t\t\twhile(( (cost2 > (cost1 + (point1 * RHO * slope1))) || (slope2 > (-SIG * slope1)) ) && (M > 0) ){\n\t\t\t\t//std::cout << \"here*******************\" << endl;\n\t\t\t\tlimit = point1;\n\t\t\t\tif(cost2 > cost1)\n                    point2 = point3 - (0.5 * slope3 * point3 * point3)/(slope3 * point3 + cost2 - cost3);  //quadratic fit\n                else{\n                    A = 6*(cost2 - cost3)/point3 + 3*(slope2 + slope3);           //cubic fit\n                    B = 3*(cost3 - cost2) - point3 * (slope3 + 2*slope2);\n                    point2 = (std::sqrt(B*B - A*slope2*point3*point3) - B)/A;\n\t\t\t\t}\n                if(std::isnan(point2) || (!std::isfinite(point2)))\n                    point2 = point3 / 2;                         // if we had a numerical problem then bisect\n                point2 = std::max( std::min(point2, (INT * point3)), ((1.0 - INT) * point3));  //don't accept too close to limits\n                point1  = point1 + point2;                       // update the step\n                stemp = point2 * search_direction;\n                nn_params = nn_params + stemp;\n\n                costfunction(cost2, gradient2, nn_params, input_layer_size, hidden_layer_size, num_labels, inputdata, y, lambda);\n\n                M = M - 1.0;\n\t\t\t\t//std::cout << \"i2: \" << i << endl;\n                //i = i + (length<0);                              // count epochs?!\n\t\t\t\t//std::cout << \"i2: \" << i << endl;\n                slope_vector = gradient2.t() * search_direction;\n                slope2 = slope_vector(0,0);                      //convert to scalar\n                point3 = point3 - point2;                        // point3 is now relative to the location of point2                \n\n\t\t\t}\n\t\t\t\n            if ((cost2 > (cost1 + (point1*RHO*slope1)) ) || (slope2 > (-SIG * slope1) )){\n\t\t\t\t//std::cout << \"Break -----------------\" << endl;\n\t\t\t\tbreak;                                            // this is a failure\n\n            }\n            else if (slope2 > (SIG * slope1)){\n\t\t\t\t//std::cout << \"Break -----------------\" << endl;\n                success = 1;\n                break;                                            // success\n\t\t\t}\n            else if (M == 0.0){\n\t\t\t\t//std::cout << \"Break -----------------\" << endl;\n                break;                                            // failure\n\t\t\t}\n\n            A = 6*(cost2 - cost3)/point3 + 3*(slope2 + slope3);  // make cubic extrapolation\n            B = 3*(cost3 - cost2) - point3*(slope3 + 2*slope2);\n            sqrtnumber = (B*B) - A*slope2*point3*point3;\n            \n\t\t\tif((!std::isnormal(sqrtnumber)) || (sqrtnumber < 0.0) ){\n\t\t\t\t//std::cout << \"sqrt ifs\" << endl;\n                if (limit < -0.5)                          // if we have no upper limit\n                    point2 = point1  * (EXT - 1);                // the extrapolate the maximum amount\n                else\n                    point2 = (limit - point1) / 2;               // otherwise bisect\n\t\t\t\t//std::cout << \"point2 sqrt ifs: \" << point2 << endl;\n            }\n            else{\n                point2 = (-slope2 * point3 * point3)/(B + std::sqrt(sqrtnumber));\n                if ((limit > -0.5) && ((point2 + point1) > limit))          // extraplation beyond max?\n                    point2 = (limit - point1)/2;                 // bisect\n                else if ((limit < -0.5) && ((point2 + point1) > (point1 * EXT)))       // extrapolation beyond limit\n                    point2 = point1 * (EXT - 1.0);               // set to extrapolation limit\n                else if (point2 < (-point3 * INT))\n                    point2 = -point3 * INT;\n                else if ((limit > -0.5) && (point2 < (limit - point1)*(1.0 - INT)))   // too close to limit?\n                    point2 = (limit - point1 ) * (1.0 - INT);\n            }\t\t\t\n\t\t\t\n            cost3 = cost2;\n            slope3 = slope2;\n            point3 = -point2;               \n            point1  = point1 + point2;\n\n\t\t\t//std::cout << \"search_direction: \" << endl << search_direction.rows(0, 10) << endl;\n            stemp = point2 * search_direction;\n\t\t\t//std::cout << \"point2: \" << point2 << endl;\n\n            nn_params = nn_params + stemp;                       // update current estimates\n\t\t\t//std::cout << \"nn_paramsb: \" << endl << nn_params.rows(0,10) << endl;\n\n            costfunction(cost2, gradient2, nn_params, input_layer_size, hidden_layer_size, num_labels, inputdata, y, lambda);\n\t\t\t//std::cout << \"cost2b: \" << cost2 << endl;\n            M = M - 1.0;\n\t\t\t//std::cout << \"i: \" << i << endl;\n            //i = i + (length<0);                                  // count epochs?!\n\t\t\t//std::cout << \"i: \" << i << endl;\n\t\t\tslope_vector = gradient2.t() * search_direction;\n            slope2 = slope_vector(0,0);                          //convert to scalar\n\t\t\t//std::cout << \"slope2b: \" << slope2 << endl;\n\t\t\t//pause();\n\t\t}\n\t\t\n        if (success == 1){                                   // if line search succeeded\n            cost1 = cost2;\n            fX = cost1;\n            std::cout << \"Iteration: \" << i << \" | Cost: \" << cost1 << endl;\n            mat sd_calc_1 = gradient2.t() * gradient2;\n            mat sd_calc_2 = gradient1.t() * gradient2;\n            mat sd_calc_3 = gradient1.t() * gradient1;\n            double sd_calc_4 = (sd_calc_1(0,0) - sd_calc_2(0,0)) / sd_calc_3(0,0);\n            mat sd_calc_5 = sd_calc_4 * search_direction;\n            \n            search_direction = sd_calc_5 - gradient2;\n            tmp = gradient1;\n            gradient1 = gradient2;\n            gradient2 = tmp;                                     // swap derivatives\n\t\t\tslope_vector = gradient1.t() * search_direction;\n            slope2 = slope_vector(0,0);                          //convert to scalar\n            if(slope2 > 0.0){                                  // new slope must be negative\n                search_direction = -gradient1;                   // otherwise use steepest direction\n\t\t\t\tslope_vector = -search_direction.t() * search_direction;\n                slope2 = slope_vector(0,0);                      //convert to scalar\n            }\n\t\t\tmintemp = slope1 / (slope2);// - std::numeric_limits<double>::lowest());  //std::numeric_limits<double>::lowest() is min value double precision float //TODO: figure out why the min number is needed\n            minstuff = std::min(RATIO, mintemp);\n            point1  = point1 * minstuff;                         // slope ratio but max RATIO\n            slope1 = slope2;\n            ls_failed = 0;                                        // this line search did not fail\n        }\n        else{\n            nn_params = backup_params;\n            cost1 = cost_backup;\n            gradient1 = gradient_backup;                         // restore point from before failed line search\n            if (ls_failed == 1 || (i > std::abs(length)))       // line search failed twice in a row\n\t\t\t\t//std::cout << \"Break -----------------\" << endl;\n                break;                                            // or we ran out of time, so we give up\n            tmp = gradient1;\n            gradient1 = gradient2;\n            gradient2 = tmp;                                    // swap derivatives\n            search_direction = -gradient1;                      // try steepest\n            slope_vector = -search_direction.t() * search_direction;\n            slope1 = slope_vector(0,0);                         // convert to scalar\n            point1  = 1.0 / (1.0 - slope1);\n            ls_failed = 1;                                      // this line search failed\n        }\t\t\n       \n\t}\n\t\n\tfinalcost = fX;\t\t//return finalcost\n}\n\n\nvoid costfunction(double& cost, mat& gradient, mat& nn_params,const int input_layer_size,const int hidden_layer_size,const int num_labels, const mat& inputdata, const mat& y,const double lambda){\n\t//std::cout << \"in costfunction...\" << endl;\n\n\n\n\tmat Theta1 = nn_params.submat(0, 0, hidden_layer_size*(input_layer_size + 1) - 1, 0);\n\tTheta1.reshape(hidden_layer_size, input_layer_size + 1);\n\t//std::cout << \"Theta1 rows: \" << Theta1.n_rows << \", cols: \" << Theta1.n_cols << endl;\n\n\tmat Theta2 = nn_params.submat(hidden_layer_size*(input_layer_size + 1), 0, hidden_layer_size*(input_layer_size + 1) - 1 + num_labels*(hidden_layer_size + 1) - 1, 0);\n\tTheta2.reshape(num_labels, hidden_layer_size + 1);\n\t//std::cout << \"Theta2 rows: \" << Theta2.n_rows << \", cols: \" << Theta2.n_cols << endl;\n\t\n\t//std::cout << \"Theta2: \" << endl << Theta2.col(0) << endl;\n\t//pause();\n\n\t//constexpr int training_size = 4000;    //m\n\t//constexpr int input_layer_size = 784;  //k\n\t//constexpr int hidden_layer_size = 500;  //n\n\t// l  y_train size\n\n\tint l = y.n_rows;\n\tint m = inputdata.n_rows;\n\t//int k = input_layer_size;\n\n\t//create the  0 1 0 0 0 0 0 0 0 0 style representative matrix\n\tmat y_representative(l, num_labels,fill::zeros);\n\tfor (unsigned int i=0;i<=(y.n_rows - 1);i++ ){\n\t\tint row_value = y(i,0);\n\t\ty_representative(i,row_value) = 1.0;\n\t}\n\t//std::cout << \"y_rep: \" << y_representative.row(0) << endl;\n\t\n\n\n\t//setup a_2\n\tmat a_1(inputdata.n_rows,inputdata.n_cols + 1,fill::ones);\n\ta_1.submat(0,1,a_1.n_rows-1,a_1.n_cols-1) = inputdata;\n\tmat z_2(a_1.n_rows,Theta1.n_rows,fill::zeros);\n\n\t//std::cout << \"a_1: \" << a_1(0, 0) << endl;\n\n\t//std::cout << \"Theta1: \" << Theta1(1, 2) << endl;\n\n\t//std::cout << \"Theta1.t(): \" << theta1t.row(0) << endl;\n\n\tz_2 = a_1 * Theta1.t();\n\t//std::cout << \"z_2: \" << z_2.row(0) << endl;\n\t//pause();\n\n\n\tmat a_2=z_2;\n\tmat a_2_ones(z_2.n_rows,z_2.n_cols+1,fill::ones);\n\t\n\tsigmoid(a_2,a_2);\n\t//std::cout << \"a_2: \" << a_2.row(0) << endl;\n\t//pause();\n\n\n\n\ta_2_ones.submat(0,1,a_2_ones.n_rows-1,a_2_ones.n_cols-1)=a_2;\n\t//std::cout << \"a_2_ones: \" << a_2_ones.n_rows << endl;\n\t//std::cout << \"a_2_ones: \" << a_2_ones.row(0) << endl;\n\t//pause();\n\n\tmat theta2t = Theta2.t();\n\t//std::cout << \"theta2t: \" << theta2t.row(0) << endl;\n\t//pause();\n\n\n\t//setup a_3\n\tmat z_3(a_2_ones.n_rows,Theta2.n_rows,fill::zeros);\n\tz_3 = a_2_ones * Theta2.t();\n\t//std::cout << \"z_3: \" << z_3.row(0) << endl;\n\t//pause();\n\t\n\tmat a_3 = z_3;\n\t//std::cout << \"a_3: \" << a_3(0, 0) << endl;\n\tsigmoid(a_3,a_3);\n\n\n\n\t//mat test1;\n\n\t//test1 << 1.0 << 2.0 << 3.0 << endr\n\t//\t  << 4.0 << 5.0 << 6.0 << endr;\n\n\t//mat test2 = test1;\n\t//mat test3 = test1;\n\t//mat test2l = test2.transform([](double val){ return (log(val)); });\n\n\t//test3 = test1 % test2l;\n\t//std::cout << test3 << endl;\n\t//pause();\n\n\t//test2l = log(test2);\n\t//test3 = test1 % test2l;\n\t//std::cout << test3 << endl;\n\t//pause();\n\n\n\n\n\t//calculate cost\n\tmat summation(z_3.n_rows,z_3.n_cols,fill::zeros);\n\n//\tmat a_3l1 = a_3;\n//\ta_3l1.transform([](double val){ return (log(val)); });\n\n\t//std::cout << \"log(a_3): \" << log(a_3.row(0)) << endl;\n\t//std::cout << \"transform log(a_3): \" << a_3l1.row(0) << endl;\n\t//pause();\n\t\n//\tmat a_3l2 = a_3;\n//\ta_3l2.transform([](double val){ return (log(1 - val)); });\n\n\tsummation = -y_representative % log(a_3) - ((1 - y_representative) % log(1-a_3));\n\t//std::cout << \"summation: \" << summation.row(0) << endl;\n\t//pause();\n\tcost = accu(summation);\n\t//std::cout << \"Cost: \" << cost << \" m: \" << m << endl;\n\tcost /= m;\n\t//std::cout << \"Cost: \" << cost << endl;\n\t//pause();\n\n\n\n\n\n\n\n\n\t//setup delta_3\n\tmat delta_3 = y_representative;\n\tdelta_3 = a_3 - y_representative;\n\t//std::cout << \"delta_3: \" << delta_3.row(0) << endl;\n\t//pause();\t\n\t\n\t//setup sigmoid of z_2\n\tmat z_2_ones(z_2.n_rows, z_2.n_cols + 1, fill::ones);\n\tz_2_ones.submat(0,1,z_2_ones.n_rows-1,z_2_ones.n_cols-1) = z_2;\n\t//std::cout << \"z_2_ones: \" << z_2_ones.row(0) << endl;\n\t//pause();\n\n\tsigmoidGradient(z_2_ones,z_2_ones);\n\n\t//std::cout << \"sigmoid_z_2: \" << z_2_ones.row(0) << endl;\n\t//pause();\n\t\n\t//setup delta_2\n\tmat delta_2(delta_3.n_rows,Theta2.n_cols);\n\tdelta_2 = (delta_3 * Theta2) % z_2_ones;\n\n\t//std::cout << \"delta_2: \" << delta_2.row(0) << endl;\n\t//pause();\n\n\n\t//setup and combine gradients\n\tmat gradient_2(delta_3.n_cols,a_2_ones.n_cols,fill::zeros);\n\tmat gradient_1(delta_2.n_cols-1,a_1.n_cols,fill::zeros);\n\n\n\tgradient_2 = (delta_3.t() * a_2_ones) / m;\n\t//std::cout << \"gradient_2: \" << gradient_2.row(0) << endl;\n\t//pause();\n\n\n\tgradient_1 = (delta_2.cols(1,delta_2.n_cols-1).t() * a_1) / m;\n\t//std::cout << \"gradient_1: \" << gradient_1.row(0) << endl;\n\t//pause();\n\tgradient_2.cols(1,gradient_2.n_cols-1) += Theta2.cols(1,Theta2.n_cols-1) * (lambda/m);\n\tgradient_1.cols(1,gradient_1.n_cols-1) += Theta1.cols(1,Theta1.n_cols-1) * (lambda/m);\n\tgradient_1.reshape(gradient_1.n_rows*gradient_1.n_cols,1);\n\tgradient_2.reshape(gradient_2.n_rows*gradient_2.n_cols,1);\n\tgradient = join_cols(gradient_1,gradient_2);\n\t//std::cout << \"gradient: \" << gradient.col(0) << endl;\n\t//pause();\n\n\n\t\n\t//std::cout << \"leaving costfunction...\" << endl;\n}\n\n\n\nvoid predict(const mat& Theta1,const mat& Theta2,const mat& inputdata, mat& predictions){\n    mat x_holder(inputdata.n_rows,inputdata.n_cols+1,fill::ones);\n    mat pre_h1(x_holder.n_rows,Theta1.n_rows);\n    mat h1_ones(x_holder.n_rows,Theta1.n_rows+1,fill::ones);\n    mat h2(x_holder.n_rows,Theta2.n_rows,fill::zeros);\n\n\t//std::cout << \"inputdata: \" << inputdata.n_rows << \" \" << inputdata.n_cols << endl;\n\t// std::cout << \"x_holder: \" << x_holder.n_rows << \" \" << x_holder.n_cols << endl;\n    x_holder.submat(0,1,x_holder.n_rows-1,x_holder.n_cols-1) = inputdata;\n    \n    // std::cout << \"Theta1: \" << Theta1.n_rows << \" \" << Theta1.n_cols << endl;\n    \n    pre_h1 = x_holder * Theta1.t();\n\n\t// std::cout << \"pre_h1: \" << pre_h1.n_rows << \" \" << pre_h1.n_cols << endl;\n\n    sigmoid(pre_h1,pre_h1);\n    h1_ones.submat(0,1,h1_ones.n_rows-1,h1_ones.n_cols-1) = pre_h1;\n    \n    // std::cout << \"h1_ones: \" << h1_ones.n_rows << \" \" << h1_ones.n_cols << endl;\n    // std::cout << \"Theta2: \" << Theta2.n_rows << \" \" << Theta2.n_cols << endl;\n    \n    h2 = h1_ones * Theta2.t();\n    sigmoid(h2,h2);\n    \n    predictions = arma::max(h2,0);\n\n}\n\nvoid sigmoid(const mat& input, mat& output){\n    output = exp(-input);\n    output.transform([](double val){return (1.0/(1.0 + val));});\n}\n\nvoid sigmoidGradient(const mat& input, mat& output){\n    output = exp(-input);\n    output.transform([](double val){return (1.0/(1.0 + val));});\n    output.transform([](double val){return (val * (1.0 - val));});\n}\n\n// void pauseJNS(){\n// \tstd::cout << std::endl << \"Press ENTER to continue...\";\n// \tstd::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\\n');\n// }\n", "meta": {"hexsha": "85cbebae8e0bebf21ab9c2ae2d92e7a72fb4687f", "size": 18968, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/digitRecognition.cpp", "max_stars_repo_name": "jshahbazi/mnist-cpp", "max_stars_repo_head_hexsha": "d757d07c03b2c24df94af4c0762b99db21c21538", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/digitRecognition.cpp", "max_issues_repo_name": "jshahbazi/mnist-cpp", "max_issues_repo_head_hexsha": "d757d07c03b2c24df94af4c0762b99db21c21538", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/digitRecognition.cpp", "max_forks_repo_name": "jshahbazi/mnist-cpp", "max_forks_repo_head_hexsha": "d757d07c03b2c24df94af4c0762b99db21c21538", "max_forks_repo_licenses": ["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.7097415507, "max_line_length": 200, "alphanum_fraction": 0.5632644454, "num_tokens": 5825, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.835483553488848, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.4824878798287819}}
{"text": "#include <boost/math/distributions/negative_binomial.hpp>\n", "meta": {"hexsha": "8d6c482c56d7aa88ebb91020887423cac1ef1bde", "size": 58, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_distributions_negative_binomial.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_distributions_negative_binomial.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_distributions_negative_binomial.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 29.0, "max_line_length": 57, "alphanum_fraction": 0.8448275862, "num_tokens": 12, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961427, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.48248787509753266}}
{"text": "#include <mesh_array.h>\n#include <tiny.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n\n#include <iostream>   // needed for debugging... This unit-test is not yet perfect (2015-12-11 Kenny)\n#include <vector>\n#include <cmath>\n\nBOOST_AUTO_TEST_SUITE(mesh_array);\n\nBOOST_AUTO_TEST_CASE(mesh_array_compute_surface_map_sphere)\n{\n\n  typedef tiny::MathTypes<float> MT;\n  typedef MT::real_type          T;\n  typedef MT::vector3_type       V;\n\n  mesh_array::T3Mesh surf;\n  mesh_array::VertexAttribute<T,mesh_array::T3Mesh> sX;\n  mesh_array::VertexAttribute<T,mesh_array::T3Mesh> sY;\n  mesh_array::VertexAttribute<T,mesh_array::T3Mesh> sZ;\n\n  size_t const slices   = 12u;\n  size_t const segments = 24u;\n  T      const radius   = 12.0f;\n  \n  mesh_array::make_sphere<MT>(radius, slices, segments, surf, sX, sY, sZ);\n  \n  mesh_array::T4Mesh mesh;\n  mesh_array::VertexAttribute<T,mesh_array::T4Mesh> X;\n  mesh_array::VertexAttribute<T,mesh_array::T4Mesh> Y;\n  mesh_array::VertexAttribute<T,mesh_array::T4Mesh> Z;\n\n  mesh_array::tetgen(surf, sX, sY, sZ, mesh, X, Y, Z );\n  \n  mesh_array::TetrahedronAttribute< mesh_array::TetrahedronSurfaceInfo ,mesh_array::T4Mesh> surface_map;\n  \n  mesh_array::compute_surface_map( mesh, X, Y, Z, surface_map );\n  \n  for (size_t idx = 0u; idx < mesh.tetrahedron_size(); ++idx)\n  {\n    mesh_array::Tetrahedron const tetrahedron = mesh.tetrahedron(idx);\n\n    bool const opposite_i_on_surface = surface_map( tetrahedron ).m_i;\n    bool const opposite_j_on_surface = surface_map( tetrahedron ).m_j;\n    bool const opposite_k_on_surface = surface_map( tetrahedron ).m_k;\n    bool const opposite_m_on_surface = surface_map( tetrahedron ).m_m;\n\n    V const p_i =  V::make( X( tetrahedron.i() ), Y( tetrahedron.i() ), Z( tetrahedron.i() ) );\n    V const p_j =  V::make( X( tetrahedron.j() ), Y( tetrahedron.j() ), Z( tetrahedron.j() ) );\n    V const p_k =  V::make( X( tetrahedron.k() ), Y( tetrahedron.k() ), Z( tetrahedron.k() ) );\n    V const p_m =  V::make( X( tetrahedron.m() ), Y( tetrahedron.m() ), Z( tetrahedron.m() ) );\n\n    T const distance_i = fabs(radius  - tiny::norm(p_i) );\n    T const distance_j = fabs(radius  - tiny::norm(p_j) );\n    T const distance_k = fabs(radius  - tiny::norm(p_k) );\n    T const distance_m = fabs(radius  - tiny::norm(p_m) );\n\n    bool const i_on_surface = distance_i > 10e-5 ? false : true;\n    bool const j_on_surface = distance_j > 10e-5 ? false : true;\n    bool const k_on_surface = distance_k > 10e-5 ? false : true;\n    bool const m_on_surface = distance_m > 10e-5 ? false : true;\n\n    std::cout << \"\\t\" << distance_i\n              << \" \"  << distance_j\n              << \" \"  << distance_k\n              << \" \"  << distance_m\n              << \" \"  << std::endl;\n\n    std::cout << \"\\t\"\n              << i_on_surface\n              << \" \"\n              << j_on_surface\n              << \" \"\n              << k_on_surface\n              << \" \"\n              << m_on_surface\n              << \" \"\n              << std::endl;\n\n    std::cout << \"\\t\"\n              << opposite_i_on_surface\n              << \" \"\n              << opposite_j_on_surface\n              << \" \"\n              << opposite_k_on_surface\n              << \" \"\n              << opposite_m_on_surface\n              << \" \"\n              << std::endl;\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "d918f4a13bbc82516913a242fdd5b254fd561a21", "size": 3460, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/FOUNDATION/MESH_ARRAY/unit_tests/mesh_array_compute_surface_map/mesh_array_compute_surface_map.cpp", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-11-27T09:44:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-13T00:24:21.000Z", "max_issues_repo_path": "PROX/FOUNDATION/MESH_ARRAY/unit_tests/mesh_array_compute_surface_map/mesh_array_compute_surface_map.cpp", "max_issues_repo_name": "erleben/matchstick", "max_issues_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_issues_repo_licenses": ["MIT"], "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/FOUNDATION/MESH_ARRAY/unit_tests/mesh_array_compute_surface_map/mesh_array_compute_surface_map.cpp", "max_forks_repo_name": "erleben/matchstick", "max_forks_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_forks_repo_licenses": ["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.6, "max_line_length": 104, "alphanum_fraction": 0.6138728324, "num_tokens": 999, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835207180245, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.48248786090378326}}
{"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 NonDDREAMBayesCalibration\n//- Description: Derived class for DREAM-based Bayesian inference\n//- Owner:       Brian Adams\n//- Checked by:\n//- Version:\n\n#ifndef NOND_DREAM_BAYES_CALIBRATION_H\n#define NOND_DREAM_BAYES_CALIBRATION_H\n\n#include \"NonDBayesCalibration.hpp\"\n// for uniform PDF\n#include <boost/math/distributions/uniform.hpp>\n// for uniform samples (uniform_real is deprecated)\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_real.hpp>\n\nnamespace Dakota {\n\n\n/// Bayesian inference using the DREAM approach \n\n/** This class performed Bayesian calibration using the DREAM (Markov\n    Chain Monte Carlo acceleration by Differential Evolution)\n    implementation of John Burkhardt (FSU), adapted from that of\n    Guannan Zhang (ORNL) */\n\nclass NonDDREAMBayesCalibration: public NonDBayesCalibration\n{\npublic:\n\n  //\n  //- Heading: Constructors and destructor\n  //\n\n  /// standard constructor\n  NonDDREAMBayesCalibration(ProblemDescDB& problem_db, Model& model);\n  /// destructor\n  ~NonDDREAMBayesCalibration();\n\n  //\n  //- Heading: Static callback functions required by DREAM\n  //\n\n  /// initializer for problem size characteristics in DREAM\n  static void \n  problem_size (int &chain_num, int &cr_num, int &gen_num, int &pair_num, \n\t\tint &par_num);\n\n  /// Filename and data initializer for DREAM\n  static void \n  problem_value (std::string *chain_filename, std::string *gr_filename,\n\t\t double &gr_threshold, int &jumpstep, double limits[], \n\t\t int par_num, int &printstep, std::string *restart_read_filename, \n\t\t std::string *restart_write_filename);\n\n  /// Compute the prior density at specified point zp\n  static double prior_density (int par_num, double zp[]);\n\n  // NOTE: Memory is freed inside the dream core\n  /// Sample the prior and return an array of parameter values\n  static double* prior_sample (int par_num);\n\n  // Called by chain_init and dream_algm\n  //   par_num: number of parameters\n  //   zp:      point at which to sample the likelihood\n  //   returns: real valued log-likelihood\n  /// Likelihood function for call-back from DREAM to DAKOTA for evaluation\n  static double sample_likelihood (int par_num, double zp[]);\n         \nprotected:\n\n  //\n  //- Heading: Virtual function redefinitions\n  //\n\n  void calibrate();\n  //void print_results(std::ostream& s, short results_state = FINAL_RESULTS);\n\n  // Member functions\n\n  /// Callback to archive the chain from DREAM, potentially leaving it in u-space\n  static void cache_chain(const double* const z);\n  /// save the final x-space acceptance chain and corresponding function values\n  void archive_acceptance_chain();\n\n  //\n  //- Heading: Data\n\n  /// lower bounds on calibrated parameters\n  RealVector paramMins;\n  /// upper bounds on calibrated parameters\n  RealVector paramMaxs;\n\n  // DREAM Algorithm controls\n\n  /// number of concurrent chains\n  int numChains;\n  /// number of generations\n  int numGenerations;\n  /// number of CR-factors\n  int numCR;\n  /// number of crossover chain pairs\n  int crossoverChainPairs;\n  /// threshold for the Gelmin-Rubin statistic\n  Real grThreshold;\n  /// how often to perform a long jump in generations\n  int jumpStep;\n\n  /// random number engine for sampling the prior\n  boost::mt19937 rnumGenerator;\n\n  // uniform prior PDFs for each variable\n  //std::vector<boost::math::uniform> priorDistributions;\n  // samplers for the uniform prior PDFs for each variable\n  //std::vector<boost::uniform_real<double> > priorSamplers;\n\nprivate:\n\n  //\n  // - Heading: Data\n  // \n\n  /// Pointer to current class instance for use in static callback functions\n  static NonDDREAMBayesCalibration* nonDDREAMInstance;\n  \n};\n\n} // namespace Dakota\n\n#endif\n", "meta": {"hexsha": "63c5f79a7c5c103bda1374214ff1121e92f6888a", "size": 4108, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/NonDDREAMBayesCalibration.hpp", "max_stars_repo_name": "jnnccc/Dakota-orb", "max_stars_repo_head_hexsha": "96488e723be9c67f0f85be8162b7af52c312b770", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/NonDDREAMBayesCalibration.hpp", "max_issues_repo_name": "jnnccc/Dakota-orb", "max_issues_repo_head_hexsha": "96488e723be9c67f0f85be8162b7af52c312b770", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/NonDDREAMBayesCalibration.hpp", "max_forks_repo_name": "jnnccc/Dakota-orb", "max_forks_repo_head_hexsha": "96488e723be9c67f0f85be8162b7af52c312b770", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5539568345, "max_line_length": 81, "alphanum_fraction": 0.7436708861, "num_tokens": 945, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835207180243, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4824878609037832}}
{"text": "#pragma once\n#include <Eigen/Dense>\n#include <vector>\n#include <array>\n#include \"shape2d.hpp\"\n\nusing namespace Eigen;\nusing namespace std;\n\n#ifndef LINE_INTERVAL_HPP\n#define LINE_INTERVAL_HPP\n\nclass Shape2d;\n\narray<double, 2> polarEquation(Vector2d v0, Vector2d v1);\n\nclass LineInterval{\n    Vector2d point;\n    double angleStart;\n    double angleEnd;\n    double distLowerBound;\n    double distUpperBound;\n    array<double, 2> intervalMaxDists;\n    vector<unsigned long int> shapeIds;\n  public:\n    LineInterval(Vector2d _point);\n    LineInterval(double _angleStart, double _angleEnd);\n    //void calculateTargetShape(Shape2d& shape);\n    //void calculateShape(Shape2d& shape);\n    void SetAngleEnd(Vector2d _point);\n    Vector2d Point();\n    array<double, 3> FunctionsAt(array<double, 2> edge, int side);\n    double DistAt(array<double, 2> edge, int side);\n    bool containsNormal(array<double, 2> edge);\n    double ApproxRoot(double distStart, double distEnd, double derivStart, double derivEnd);\n    void update(double upperBound, double lowerBound, double distStart, double distEnd, unsigned long int shapeId);\n    double UpperBound();\n    double LowerBound();\n    double MaxWidth();\n    bool IntersectsEdge(double v0Angle, double v1Angle);\n    //double IntervalAngleStart();\n    double IntervalAngleEnd();\n    array<double, 3> Divide();\n    vector<unsigned long int> ShapeIds();\n    array<Vector2d, 2> EndPoints();\n};\n\n#endif\n", "meta": {"hexsha": "d88b48903ebb545234592edd8fb423adc8ebcb5a", "size": 1431, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/line_interval.hpp", "max_stars_repo_name": "myociss/pathfinder", "max_stars_repo_head_hexsha": "4c0b14e074cfc8f0e41836abc056989f2d465c12", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/line_interval.hpp", "max_issues_repo_name": "myociss/pathfinder", "max_issues_repo_head_hexsha": "4c0b14e074cfc8f0e41836abc056989f2d465c12", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/line_interval.hpp", "max_forks_repo_name": "myociss/pathfinder", "max_forks_repo_head_hexsha": "4c0b14e074cfc8f0e41836abc056989f2d465c12", "max_forks_repo_licenses": ["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.2040816327, "max_line_length": 115, "alphanum_fraction": 0.7274633124, "num_tokens": 356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.5851011542032313, "lm_q1q2_score": 0.482393624719551}}
{"text": "/*    This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.\n *    See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.\n *    Author(s):       Vincent Rouvreau\n *\n *    Copyright (C) 2015 Inria\n *\n *    Modification(s):\n *      - YYYY/MM Author: Description of the modification\n */\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE \"alpha_complex_3d\"\n#include <boost/test/unit_test.hpp>\n\n#include <cmath>  // float comparison\n#include <limits>\n#include <string>\n#include <vector>\n#include <random>\n#include <cstddef>  // for std::size_t\n\n#include <gudhi/Alpha_complex_3d.h>\n#include <gudhi/graph_simplicial_complex.h>\n#include <gudhi/Simplex_tree.h>\n#include <gudhi/Unitary_tests_utils.h>\n// to construct Alpha_complex from a OFF file of points\n#include <gudhi/Points_3D_off_io.h>\n\n#include <CGAL/Random.h>\n#include <CGAL/point_generators_3.h>\n\nusing Fast_alpha_complex_3d =\n    Gudhi::alpha_complex::Alpha_complex_3d<Gudhi::alpha_complex::complexity::FAST, false, false>;\nusing Safe_alpha_complex_3d =\n    Gudhi::alpha_complex::Alpha_complex_3d<Gudhi::alpha_complex::complexity::SAFE, false, false>;\nusing Exact_alpha_complex_3d =\n    Gudhi::alpha_complex::Alpha_complex_3d<Gudhi::alpha_complex::complexity::EXACT, false, false>;\n\ntemplate <typename Point>\nstd::vector<Point> get_points() {\n  std::vector<Point> points;\n  points.push_back(Point(0.0, 0.0, 0.0));\n  points.push_back(Point(0.0, 0.0, 0.2));\n  points.push_back(Point(0.2, 0.0, 0.2));\n  points.push_back(Point(0.6, 0.6, 0.0));\n  points.push_back(Point(0.8, 0.8, 0.2));\n  points.push_back(Point(0.2, 0.8, 0.6));\n\n  return points;\n}\n\n\nBOOST_AUTO_TEST_CASE(Alpha_complex_3d_from_points) {\n  // -----------------\n  // Fast version\n  // -----------------\n  std::cout << \"Fast alpha complex 3d\" << std::endl;\n\n  std::vector<Fast_alpha_complex_3d::Bare_point_3> points = get_points<Fast_alpha_complex_3d::Bare_point_3>();\n  Fast_alpha_complex_3d alpha_complex(points);\n\n  Gudhi::Simplex_tree<> stree;\n  alpha_complex.create_complex(stree);\n\n  for (std::size_t index = 0; index < points.size(); index++) {\n    bool found = false;\n    for (auto point : points) {\n      if (point == alpha_complex.get_point(index)) {\n        found = true;\n        break;\n      }\n    }\n    // Check all points from alpha complex are found in the input point cloud\n    BOOST_CHECK(found);\n  }\n  // Exception if we go out of range\n  BOOST_CHECK_THROW(alpha_complex.get_point(points.size()), std::out_of_range);\n\n  // -----------------\n  // Exact version\n  // -----------------\n  std::cout << \"Exact alpha complex 3d\" << std::endl;\n\n  std::vector<Exact_alpha_complex_3d::Bare_point_3> exact_points = get_points<Exact_alpha_complex_3d::Bare_point_3>();\n  Exact_alpha_complex_3d exact_alpha_complex(exact_points);\n\n  Gudhi::Simplex_tree<> exact_stree;\n  exact_alpha_complex.create_complex(exact_stree);\n\n  for (std::size_t index = 0; index < exact_points.size(); index++) {\n    bool found = false;\n    Exact_alpha_complex_3d::Bare_point_3 ap = exact_alpha_complex.get_point(index);\n    for (auto point : points) {\n      if ((point.x() == ap.x()) && (point.y() == ap.y()) && (point.z() == ap.z())) {\n        found = true;\n        break;\n      }\n    }\n    // Check all points from alpha complex are found in the input point cloud\n    BOOST_CHECK(found);\n  }\n  // Exception if we go out of range\n  BOOST_CHECK_THROW(exact_alpha_complex.get_point(exact_points.size()), std::out_of_range);\n\n  // ---------------------\n  // Compare both versions\n  // ---------------------\n  std::cout << \"Exact Alpha complex 3d is of dimension \" << exact_stree.dimension() << \" - Fast is \"\n            << stree.dimension() << std::endl;\n  BOOST_CHECK(exact_stree.dimension() == stree.dimension());\n  std::cout << \"Exact Alpha complex 3d num_simplices \" << exact_stree.num_simplices() << \" - Fast is \"\n            << stree.num_simplices() << std::endl;\n  BOOST_CHECK(exact_stree.num_simplices() == stree.num_simplices());\n  std::cout << \"Exact Alpha complex 3d num_vertices \" << exact_stree.num_vertices() << \" - Fast is \"\n            << stree.num_vertices() << std::endl;\n  BOOST_CHECK(exact_stree.num_vertices() == stree.num_vertices());\n\n  auto sh = stree.filtration_simplex_range().begin();\n  while (sh != stree.filtration_simplex_range().end()) {\n    std::vector<int> simplex;\n    std::vector<int> exact_simplex;\n    std::cout << \"Fast ( \";\n    for (auto vertex : stree.simplex_vertex_range(*sh)) {\n      simplex.push_back(vertex);\n      std::cout << vertex << \" \";\n    }\n    std::cout << \") -> [\" << stree.filtration(*sh) << \"] \";\n\n    // Find it in the exact structure\n    auto sh_exact = exact_stree.find(simplex);\n    BOOST_CHECK(sh_exact != exact_stree.null_simplex());\n\n    std::cout << \" versus [\" << exact_stree.filtration(sh_exact) << \"] \" << std::endl;\n    // Exact and non-exact version is not exactly the same due to float comparison\n    GUDHI_TEST_FLOAT_EQUALITY_CHECK(exact_stree.filtration(sh_exact), stree.filtration(*sh));\n\n    ++sh;\n  }\n  // -----------------\n  // Safe version\n  // -----------------\n  std::cout << \"Safe alpha complex 3d\" << std::endl;\n\n  std::vector<Safe_alpha_complex_3d::Bare_point_3> safe_points = get_points<Safe_alpha_complex_3d::Bare_point_3>();\n  Safe_alpha_complex_3d safe_alpha_complex(safe_points);\n\n  Gudhi::Simplex_tree<> safe_stree;\n  safe_alpha_complex.create_complex(safe_stree);\n\n  for (std::size_t index = 0; index < safe_points.size(); index++) {\n    bool found = false;\n    Safe_alpha_complex_3d::Bare_point_3 ap = safe_alpha_complex.get_point(index);\n    for (auto point : points) {\n      if ((point.x() == ap.x()) && (point.y() == ap.y()) && (point.z() == ap.z())) {\n        found = true;\n        break;\n      }\n    }\n    // Check all points from alpha complex are found in the input point cloud\n    BOOST_CHECK(found);\n  }\n  // Exception if we go out of range\n  BOOST_CHECK_THROW(safe_alpha_complex.get_point(safe_points.size()), std::out_of_range);\n\n  // ---------------------\n  // Compare both versions\n  // ---------------------\n  std::cout << \"Safe Alpha complex 3d is of dimension \" << safe_stree.dimension() << \" - Fast is \"\n            << stree.dimension() << std::endl;\n  BOOST_CHECK(safe_stree.dimension() == stree.dimension());\n  std::cout << \"Safe Alpha complex 3d num_simplices \" << safe_stree.num_simplices() << \" - Fast is \"\n            << stree.num_simplices() << std::endl;\n  BOOST_CHECK(safe_stree.num_simplices() == stree.num_simplices());\n  std::cout << \"Safe Alpha complex 3d num_vertices \" << safe_stree.num_vertices() << \" - Fast is \"\n            << stree.num_vertices() << std::endl;\n  BOOST_CHECK(safe_stree.num_vertices() == stree.num_vertices());\n\n  auto safe_sh = stree.filtration_simplex_range().begin();\n  while (safe_sh != stree.filtration_simplex_range().end()) {\n    std::vector<int> simplex;\n    std::vector<int> exact_simplex;\n    std::cout << \"Fast ( \";\n    for (auto vertex : stree.simplex_vertex_range(*safe_sh)) {\n      simplex.push_back(vertex);\n      std::cout << vertex << \" \";\n    }\n    std::cout << \") -> [\" << stree.filtration(*safe_sh) << \"] \";\n\n    // Find it in the exact structure\n    auto sh_exact = safe_stree.find(simplex);\n    BOOST_CHECK(sh_exact != safe_stree.null_simplex());\n\n    std::cout << \" versus [\" << safe_stree.filtration(sh_exact) << \"] \" << std::endl;\n    // Exact and non-exact version is not exactly the same due to float comparison\n    GUDHI_TEST_FLOAT_EQUALITY_CHECK(safe_stree.filtration(sh_exact), stree.filtration(*safe_sh), 1e-15);\n\n    ++safe_sh;\n  }\n}\n", "meta": {"hexsha": "cd698a278d85bcc058288f536b967f23aacc892c", "size": 7577, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Alpha_complex/test/Alpha_complex_3d_unit_test.cpp", "max_stars_repo_name": "gtauzin/gudhi-devel", "max_stars_repo_head_hexsha": "d7f8038ac312c96b9331786f54802b0191fdee45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Alpha_complex/test/Alpha_complex_3d_unit_test.cpp", "max_issues_repo_name": "gtauzin/gudhi-devel", "max_issues_repo_head_hexsha": "d7f8038ac312c96b9331786f54802b0191fdee45", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Alpha_complex/test/Alpha_complex_3d_unit_test.cpp", "max_forks_repo_name": "gtauzin/gudhi-devel", "max_forks_repo_head_hexsha": "d7f8038ac312c96b9331786f54802b0191fdee45", "max_forks_repo_licenses": ["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.885, "max_line_length": 118, "alphanum_fraction": 0.6554045137, "num_tokens": 2092, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702880639791, "lm_q2_score": 0.6654105720171531, "lm_q1q2_score": 0.48233635301889094}}
{"text": "#include \"Day03-HowYouSliceIt.h\"\n\n#include \"OverlapGrid.h\"\n\n#include <AdventOfCodeCommon/DisableLibraryWarningsMacros.h>\n\n__BEGIN_LIBRARIES_DISABLE_WARNINGS\n#include <boost/algorithm/string.hpp>\n#include <boost/lexical_cast.hpp>\n__END_LIBRARIES_DISABLE_WARNINGS\n\nnamespace\n{\nconst size_t GRID_SIZE = 1001;\n}\n\nnamespace AdventOfCode\n{\nnamespace Year2018\n{\nnamespace Day03\n{\n\nOverlapGrid parseOverlapGridFromAreaLines(const std::vector<std::string>& areaLines)\n{\n    OverlapGrid overlapGrid{GRID_SIZE};\n\n    for (const auto& line : areaLines)\n    {\n        std::vector<std::string> tokens;\n        boost::split(tokens, line, boost::is_any_of(\" @,:x\"), boost::token_compress_on);\n\n        if (tokens.size() < 5)\n        {\n            throw std::runtime_error(\"Not enough tokens.\");\n        }\n\n        const unsigned topLeftX = boost::lexical_cast<unsigned>(tokens[1]);\n        const unsigned topLeftY = boost::lexical_cast<unsigned>(tokens[2]);\n        const unsigned width = boost::lexical_cast<unsigned>(tokens[3]);\n        const unsigned height = boost::lexical_cast<unsigned>(tokens[4]);\n\n        Rectangle r{topLeftX, topLeftY, width, height};\n\n        overlapGrid.addRectangle(std::move(r));\n    }\n\n    return overlapGrid;\n}\n\nunsigned numOverlappingSquares(const std::vector<std::string>& areaLines)\n{\n    OverlapGrid OverlapGrid = parseOverlapGridFromAreaLines(areaLines);\n    return OverlapGrid.getOverlapSize();\n}\n\nunsigned findSingleNonOperlappingSquare(const std::vector<std::string>& areaLines)\n{\n    OverlapGrid OverlapGrid = parseOverlapGridFromAreaLines(areaLines);\n    return OverlapGrid.getSingleNonOverlappingIndex() + 1;\n}\n\n}\n}\n}\n", "meta": {"hexsha": "524ba3072d647df730267a75f5d3db18c876962c", "size": 1646, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/AdventOfCode2018/Day03-HowYouSliceIt/Day03-HowYouSliceIt.cpp", "max_stars_repo_name": "dbartok/advent-of-code-cpp", "max_stars_repo_head_hexsha": "c8c2df7a21980f8f3e42128f7bc5df8288f18490", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/AdventOfCode2018/Day03-HowYouSliceIt/Day03-HowYouSliceIt.cpp", "max_issues_repo_name": "dbartok/advent-of-code-cpp", "max_issues_repo_head_hexsha": "c8c2df7a21980f8f3e42128f7bc5df8288f18490", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/AdventOfCode2018/Day03-HowYouSliceIt/Day03-HowYouSliceIt.cpp", "max_forks_repo_name": "dbartok/advent-of-code-cpp", "max_forks_repo_head_hexsha": "c8c2df7a21980f8f3e42128f7bc5df8288f18490", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.9393939394, "max_line_length": 88, "alphanum_fraction": 0.719927096, "num_tokens": 393, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702880639791, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.4823363482092536}}
{"text": "/*  BSD 3-Clause License\n *\n *  Copyright (c) 2020, FriederPankratz <frieder.pankratz@gmail.com>\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions are met:\n *\n *  1. Redistributions of source code must retain the above copyright notice, this\n *     list of conditions and the following disclaimer.\n *\n *  2. Redistributions in binary form must reproduce the above copyright notice,\n *     this list of conditions and the following disclaimer in the documentation\n *     and/or other materials provided with the distribution.\n *\n *  3. Neither the name of the copyright holder nor the names of its\n *     contributors may be used to endorse or promote products derived from\n *     this software without specific prior written permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n *  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n *  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n *  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n *  FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n *  DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n *  SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n *  OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n *  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n**/\n\n\n#include \"gtest/gtest.h\"\n#include <traact/util/Logging.h>\n#include \"spdlog/sinks/stdout_color_sinks.h\"\n\n#include <traact/math/perspective.h>\n#include <traact/vision.h>\n#include <traact/spatial.h>\n#include <Eigen/Dense>\n#include <math.h>\n\n#include <opencv2/imgproc/imgproc.hpp>\n#include <opencv2/calib3d/calib3d.hpp>\n\nEigen::Vector3d test_point(const std::vector<Eigen::Affine3d>&  cam_2_world, const std::vector<traact::vision::CameraCalibration>& calibrations, const Eigen::Vector3d& test_position, const double noise=0) {\n    using namespace traact::math;\n    using namespace traact::vision;\n    using namespace Eigen;\n\n    std::vector<Vector2d> image_points;\n    for(int i=0;i<cam_2_world.size();++i){\n        Vector2d point = reproject_point(cam_2_world[i], calibrations[i], test_position);\n        Vector2d pixel_noise;\n        pixel_noise.setRandom();\n        pixel_noise *= noise;\n        point += pixel_noise;\n\n        image_points.push_back(point);\n    }\n\n    Vector3d p3_result;\n\n\n    estimate_3d_point(p3_result,cam_2_world, calibrations, image_points);\n\n    return p3_result;\n\n}\n\nTEST(TraactVisionTestSuite, Estimate3dPointTest_NoDistortion) {\n\n    using namespace traact::math;\n    using namespace traact::vision;\n    using namespace Eigen;\n    CameraCalibration calibration;\n    calibration.width = 640;\n    calibration.height = 576;\n    calibration.fx = 345.62296;\n    calibration.fy = 359.71362;\n    calibration.skew = 0;\n    calibration.cx = 326.55453;\n    calibration.cy = 349.54202;\n\n\n\n    {\n        Affine3d marker_pose;\n        std::vector<Affine3d>  cam_2_world;\n        marker_pose = Translation3d(0.1,-0.5,-3);// * AngleAxisd(M_PI, Vector3d::UnitY());\n\n        cam_2_world.push_back(Affine3d::Identity());\n        cam_2_world.push_back(Translation3d(-0.1,0,0) * AngleAxisd::Identity());\n\n        std::vector<CameraCalibration> calibrations;\n        for(int i=0;i<cam_2_world.size();++i){\n            calibrations.push_back(calibration);\n        }\n\n        Vector3d p3_result = test_point(cam_2_world, calibrations, marker_pose.translation(), 0);\n        EXPECT_NEAR(marker_pose.translation().x(), p3_result.x(), 1e-9);\n        EXPECT_NEAR(marker_pose.translation().y(), p3_result.y(), 1e-9);\n        EXPECT_NEAR(marker_pose.translation().z(), p3_result.z(), 1e-9);\n    }\n\n    {\n        Affine3d marker_pose;\n        std::vector<Affine3d>  cam_2_world;\n        marker_pose = Translation3d(0.1,-0.5,-3);// * AngleAxisd(M_PI, Vector3d::UnitY());\n\n        {\n            Affine3d pose_c2w;\n            pose_c2w = Translation3d(-2.13208468683971208e+00, -1.20638214730114912e+00, 2.30451254078307244e+00);\n            pose_c2w.rotate(Quaterniond(-8.49694826269651537e-01,-3.46199513669736558e-01, 1.29443829434892799e-01, 3.76043739432868451e-01));\n            cam_2_world.push_back(pose_c2w);\n        }\n\n        {\n            Affine3d pose_c2w;\n            pose_c2w = Translation3d(-2.24341394331049226e+00, 2.91498703341871979e+00, 2.19838501838564992e+00);\n            pose_c2w.rotate(Quaterniond( 4.53584848555412923e-01, 1.66481146382847056e-01, -3.40200132181601056e-01, -8.06727142919858475e-01 ));\n            cam_2_world.push_back(pose_c2w);\n        }\n\n\n\n        std::vector<CameraCalibration> calibrations;\n        for(int i=0;i<cam_2_world.size();++i){\n            calibrations.push_back(calibration);\n        }\n\n        Vector3d p3_result = test_point(cam_2_world, calibrations, marker_pose.translation(), 0);\n        EXPECT_NEAR(marker_pose.translation().x(), p3_result.x(), 1e-9);\n        EXPECT_NEAR(marker_pose.translation().y(), p3_result.y(), 1e-9);\n        EXPECT_NEAR(marker_pose.translation().z(), p3_result.z(), 1e-9);\n    }\n\n\n\n\n\n\n}\n\n/*\nTEST(TraactVisionTestSuite, Estimate3dPointTestNoise_NoDistortion) {\n    using namespace traact::math;\n    using namespace traact::vision;\n    using namespace Eigen;\n    CameraCalibration calibration;\n    calibration.width = 640;\n    calibration.height = 480;\n    calibration.fx = 500;\n    calibration.fy = 500;\n    calibration.skew = 0;\n    calibration.cx = calibration.width / 2.0 - 0.5;\n    calibration.cy = calibration.height / 2.0 - 0.5;\n\n    Affine3d marker_pose;\n    std::vector<Affine3d>  world_2_cam;\n    std::vector<Affine3d>  cam_2_world;\n    marker_pose = Translation3d(0.1,-0.5,-3);// * AngleAxisd(M_PI, Vector3d::UnitY());\n\n    world_2_cam.push_back(Affine3d::Identity());\n    world_2_cam.push_back(Translation3d(-0.1,0,0) * AngleAxisd::Identity());\n\n    std::vector<CameraCalibration> calibrations;\n    for(int i=0;i<world_2_cam.size();++i){\n        calibrations.push_back(calibration);\n        cam_2_world.push_back(world_2_cam[i].inverse());\n    }\n\n    typedef Matrix< double, Dynamic, 1, ColMajor > EVector;\n    Matrix< double, 100, 1, ColMajor > diff_values;\n\n    for(int i=0;i<11;++i) {\n        double noise = 10.0/100.0 * i;\n\n        double sum=0;\n        const int test_size = 1000;\n        for(int j=0;j<test_size;++j) {\n            Vector3d p3_result = test_point(cam_2_world, calibrations, marker_pose.translation(), noise);\n            Vector3d diff = p3_result - marker_pose.translation();\n            sum += diff.norm()*1000;\n        }\n\n\n        SPDLOG_INFO(\"2 observations, noise of {0} pixel : error {1}mm\", noise, sum/test_size);\n    }\n\n    world_2_cam.push_back(Translation3d(0,0,-6) *  AngleAxisd(M_PI, Vector3d::UnitY()));\n    world_2_cam.push_back(Translation3d(-0.1,0,-6) *  AngleAxisd(M_PI, Vector3d::UnitY()));\n\n    calibrations.clear();\n    cam_2_world.clear();\n    for(int i=0;i<world_2_cam.size();++i){\n        calibrations.push_back(calibration);\n        cam_2_world.push_back(world_2_cam[i].inverse());\n    }\n\n    for(int i=0;i<11;++i) {\n        double noise = 10.0/100.0 * i;\n\n        double sum=0;\n        const int test_size = 1000;\n        for(int j=0;j<test_size;++j) {\n            Vector3d p3_result = test_point(cam_2_world, calibrations, marker_pose.translation(), noise);\n            Vector3d diff = p3_result - marker_pose.translation();\n            sum += diff.norm()*1000;\n        }\n\n\n        SPDLOG_INFO(\"4 observations, noise of {0} pixel : error {1}mm\", noise, sum/test_size);\n    }\n\n\n}\n */", "meta": {"hexsha": "343e4c3d1f8a898c3fc1b7605f76da0c212fa4ee", "size": 7787, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_estimate_3d_point.cpp", "max_stars_repo_name": "traact/traact_vision", "max_stars_repo_head_hexsha": "71e03962f9b5899d8b28b517724ed5a9d75539d9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/test_estimate_3d_point.cpp", "max_issues_repo_name": "traact/traact_vision", "max_issues_repo_head_hexsha": "71e03962f9b5899d8b28b517724ed5a9d75539d9", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/test_estimate_3d_point.cpp", "max_forks_repo_name": "traact/traact_vision", "max_forks_repo_head_hexsha": "71e03962f9b5899d8b28b517724ed5a9d75539d9", "max_forks_repo_licenses": ["BSD-3-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.7201834862, "max_line_length": 206, "alphanum_fraction": 0.6780531655, "num_tokens": 2163, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702880639791, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.48233634339961634}}
{"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 <Eigen/Core>\n#include <Eigen/Geometry>\n#include <glog/logging.h>\n#include <algorithm>\n#include <vector>\n#include \"gtest/gtest.h\"\n\n#include \"theia/alignment/alignment.h\"\n#include \"theia/math/util.h\"\n#include \"theia/sfm/pose/test_util.h\"\n#include \"theia/sfm/transformation/gdls_similarity_transform.h\"\n#include \"theia/util/random.h\"\n#include \"theia/util/util.h\"\n\nnamespace theia {\nnamespace {\nusing Eigen::AngleAxisd;\nusing Eigen::Map;\nusing Eigen::Matrix3d;\nusing Eigen::Quaterniond;\nusing Eigen::Vector3d;\n\nRandomNumberGenerator rng(57);\n\nvoid TestGdlsSimilarityTransformWithNoise(\n    const std::vector<Vector3d>& camera_centers,\n    const std::vector<Vector3d>& world_points,\n    const double projection_noise_std_dev,\n    const Quaterniond& expected_rotation,\n    const Vector3d& expected_translation,\n    const double expected_scale,\n    const double max_reprojection_error,\n    const double max_rotation_difference,\n    const double max_translation_difference,\n    const double max_scale_difference) {\n  const int num_points = world_points.size();\n  const int num_cameras = camera_centers.size();\n\n  std::vector<Vector3d> camera_rays;\n  std::vector<Vector3d> ray_origins;\n  camera_rays.reserve(num_points);\n  ray_origins.reserve(num_points);\n  for (int i = 0; i < num_points; i++) {\n    Vector3d ray_origin = (expected_rotation * camera_centers[i % num_cameras] +\n                           expected_translation) / expected_scale;\n\n    ray_origins.push_back(ray_origin);\n\n    // Reproject 3D points into camera frame.\n    camera_rays.push_back(\n        (expected_rotation * world_points[i] + expected_translation -\n         expected_scale * ray_origins[i]).normalized());\n  }\n\n  if (projection_noise_std_dev) {\n    // Adds noise to both of the rays.\n    for (int i = 0; i < num_points; i++) {\n      AddNoiseToRay(projection_noise_std_dev, &rng, &camera_rays[i]);\n    }\n  }\n\n  // Run DLS Similarity Transform.\n  std::vector<Quaterniond> soln_rotation;\n  std::vector<Vector3d> soln_translation;\n  std::vector<double> soln_scale;\n  GdlsSimilarityTransform(ray_origins, camera_rays, world_points,\n                          &soln_rotation, &soln_translation, &soln_scale);\n\n  // Check solutions and verify at least one is close to the actual solution.\n\n  const int num_solutions = soln_rotation.size();\n  EXPECT_GT(num_solutions, 0);\n  bool matched_transform = false;\n  for (int i = 0; i < num_solutions; i++) {\n    // Check that reprojection errors are small.\n    double max_reproj_err = 0.0;\n    for (int j = 0; j < num_points; j++) {\n      const Quaterniond unrot =\n          Quaterniond::FromTwoVectors(camera_rays[j], Vector3d(0, 0, 1));\n      const Vector3d reprojected_point =\n          (soln_rotation[i] * world_points[j] + soln_translation[i]) /\n              soln_scale[i] - ray_origins[j];\n\n      const Vector3d unrot_cam_ray = unrot * camera_rays[j];\n      const Vector3d unrot_reproj_pt = unrot * reprojected_point;\n\n      const double reprojection_error =\n          (unrot_cam_ray.hnormalized() - unrot_reproj_pt.hnormalized()).norm();\n      if (reprojection_error > max_reproj_err)\n        max_reproj_err = reprojection_error;\n      EXPECT_LE(reprojection_error, max_reprojection_error)\n          << \"Reproj error is \" << reprojection_error * 512.0;\n    }\n\n    // Check that the solution is accurate.\n    const double rotation_difference =\n        expected_rotation.angularDistance(soln_rotation[i]);\n    const bool matched_rotation =\n        (rotation_difference < max_rotation_difference);\n    const double translation_difference =\n        (expected_translation - soln_translation[i]).squaredNorm();\n    const bool matched_translation =\n        (translation_difference < max_translation_difference);\n    const double scale_difference =\n        fabs(expected_scale - soln_scale[i]) / expected_scale;\n    const bool matched_scale = (scale_difference < max_scale_difference);\n\n    if (matched_translation && matched_rotation && matched_scale) {\n      matched_transform = true;\n    }\n  }\n  EXPECT_TRUE(matched_transform);\n}\n\nvoid BasicTest() {\n  const std::vector<Vector3d> points_3d = { Vector3d(-1.0, 3.0, 3.0),\n                                            Vector3d(1.0, -1.0, 2.0),\n                                            Vector3d(-1.0, 1.0, 2.0),\n                                            Vector3d(2.0, 1.0, 3.0) };\n  const Quaterniond soln_rotation = Quaterniond(\n      AngleAxisd(DegToRad(13.0), Vector3d(0.0, 0.0, 1.0)));\n  const Vector3d soln_translation(1.0, 1.0, 1.0);\n  const double soln_scale = 2.5;\n  const double kNoise = 0.0;\n  const double kMaxReprojectionError = 1.0 / 512.0;\n  const double kMaxAllowedRotationDifference = DegToRad(1e-4);\n  const double kMaxAllowedTranslationDifference = 1e-6;\n  const double kMaxAllowedScaleDifference = 1e-6;\n\n  const std::vector<Vector3d> kImageOrigins = { Vector3d(-1.0, 0.0, 0.0),\n                                                Vector3d(0.0, 0.0, 0.0),\n                                                Vector3d(2.0, 0.0, 0.0),\n                                                Vector3d(3.0, 0.0, 0.0) };\n\n  TestGdlsSimilarityTransformWithNoise(\n      kImageOrigins,\n      points_3d,\n      kNoise,\n      soln_rotation,\n      soln_translation,\n      soln_scale,\n      kMaxReprojectionError,\n      kMaxAllowedRotationDifference,\n      kMaxAllowedTranslationDifference,\n      kMaxAllowedScaleDifference);\n}\n\nTEST(GdlsSimilarityTransform, Basic) {\n  BasicTest();\n}\n\nTEST(GdlsSimilarityTransform, NoiseTest) {\n  const std::vector<Vector3d> points_3d = { Vector3d(-1.0, 3.0, 3.0),\n                                            Vector3d(1.0, -1.0, 2.0),\n                                            Vector3d(-1.0, 1.0, 2.0),\n                                            Vector3d(2.0, 1.0, 3.0),\n                                            Vector3d(-1.0, -3.0, 2.0),\n                                            Vector3d(1.0, -2.0, 1.0),\n                                            Vector3d(-1.0, 4.0, 2.0),\n                                            Vector3d(-2.0, 2.0, 3.0)\n  };\n  const std::vector<Vector3d> kImageOrigins = { Vector3d(0.0, 1.0, 0.0),\n                                                Vector3d(0.0, 0.0, 0.0),\n                                                Vector3d(0.0, 2.0, 0.0),\n                                                Vector3d(0.0, 3.0, 0.0) };\n\n  const Quaterniond soln_rotation = Quaterniond(\n      AngleAxisd(DegToRad(13.0), Vector3d(0.0, 0.0, 1.0)));\n  const Vector3d soln_translation(1.0, 1.0, 1.0);\n  const double soln_scale = 2.5;\n  const double kNoise = 1.0 / 512.0;\n  const double kMaxReprojectionError = 5.0 / 512.0;\n  const double kMaxAllowedRotationDifference = DegToRad(1.0);\n  const double kMaxAllowedTranslationDifference = 1e-3;\n  const double kMaxAllowedScaleDifference = 1e-2;\n\n  TestGdlsSimilarityTransformWithNoise(\n      kImageOrigins,\n      points_3d,\n      kNoise,\n      soln_rotation,\n      soln_translation,\n      soln_scale,\n      kMaxReprojectionError,\n      kMaxAllowedRotationDifference,\n      kMaxAllowedTranslationDifference,\n      kMaxAllowedScaleDifference);\n}\n\nTEST(GdlsSimilarityTransform, ManyPoints) {\n  // Sets some test rotations and translations.\n  static const Vector3d kAxes[] = {\n    Vector3d(0.0, 0.0, 1.0).normalized(),\n    Vector3d(0.0, 1.0, 0.0).normalized(),\n    Vector3d(1.0, 0.0, 0.0).normalized(),\n    Vector3d(1.0, 0.0, 1.0).normalized(),\n    Vector3d(0.0, 1.0, 1.0).normalized(),\n    Vector3d(1.0, 1.0, 1.0).normalized(),\n    Vector3d(0.0, 1.0, 1.0).normalized(),\n    Vector3d(1.0, 1.0, 1.0).normalized()\n  };\n\n  static const double kRotationAngles[THEIA_ARRAYSIZE(kAxes)] = {\n    DegToRad(7.0),\n    DegToRad(12.0),\n    DegToRad(15.0),\n    DegToRad(20.0),\n    DegToRad(11.0),\n    DegToRad(0.0),  // Tests no rotation.\n    DegToRad(5.0),\n    DegToRad(0.0)  // Tests no rotation and no translation.\n  };\n\n  static const Vector3d kTranslations[THEIA_ARRAYSIZE(kAxes)] = {\n    Vector3d(1.0, 1.0, 1.0),\n    Vector3d(3.0, 2.0, 13.0),\n    Vector3d(4.0, 5.0, 11.0),\n    Vector3d(1.0, 2.0, 15.0),\n    Vector3d(3.0, 1.5, 18.0),\n    Vector3d(1.0, 7.0, 11.0),\n    Vector3d(0.0, 0.0, 0.0),  // Tests no translation.\n    Vector3d(0.0, 0.0, 0.0)  // Tests no translation and no rotation.\n  };\n\n  static const double kScales[THEIA_ARRAYSIZE(kAxes)] = {\n    0.33,\n    1.0,\n    4.2,\n    10.13,\n    3.14,\n    7.22,\n    0.1,\n    10.0\n  };\n\n  const std::vector<Vector3d> kImageOrigins = { Vector3d(-1.0, 0.0, 0.0),\n                                                Vector3d(0.0, 0.0, 0.0),\n                                                Vector3d(2.0, 0.0, 0.0),\n                                                Vector3d(3.0, 0.0, 0.0) };\n\n  static const int num_points[3] = { 100, 500, 1000 };\n  const double kNoise = 0.5 / 512.0;\n  const double kMaxReprojectionError = 10.0 / 512.0;\n  const double kMaxAllowedRotationDifference = DegToRad(0.3);\n  const double kMaxAllowedTranslationDifference = 1e-3;\n  const double kMaxAllowedScaleDifference = 1e-2;\n\n  for (int i = 0; i < THEIA_ARRAYSIZE(kAxes); i++) {\n    const Quaterniond soln_rotation(AngleAxisd(kRotationAngles[i], kAxes[i]));\n    for (int j = 0; j < THEIA_ARRAYSIZE(num_points); j++) {\n      std::vector<Vector3d> points_3d;\n      points_3d.reserve(num_points[j]);\n      for (int k = 0; k < num_points[j]; k++) {\n        points_3d.push_back(Vector3d(rng.RandDouble(-5.0, 5.0),\n                                     rng.RandDouble(-5.0, 5.0),\n                                     rng.RandDouble(2.0, 10.0)));\n      }\n\n      TestGdlsSimilarityTransformWithNoise(\n          kImageOrigins,\n          points_3d,\n          kNoise,\n          soln_rotation,\n          kTranslations[i],\n          kScales[i],\n          kMaxReprojectionError,\n          kMaxAllowedRotationDifference,\n          kMaxAllowedTranslationDifference,\n          kMaxAllowedScaleDifference);\n    }\n  }\n}\n\nTEST(GdlsSimilarityTransform, NoRotation) {\n  const std::vector<Vector3d> points_3d = { Vector3d(-1.0, 3.0, 3.0),\n                                            Vector3d(1.0, -1.0, 2.0),\n                                            Vector3d(-1.0, 1.0, 2.0),\n                                            Vector3d(2.0, 1.0, 3.0),\n                                            Vector3d(-1.0, -3.0, 2.0),\n                                            Vector3d(1.0, -2.0, 1.0),\n                                            Vector3d(-1.0, 4.0, 2.0),\n                                            Vector3d(-2.0, 2.0, 3.0)\n  };\n  const std::vector<Vector3d> kImageOrigins = { Vector3d(-1.0, 0.0, 0.0),\n                                                Vector3d(0.0, 0.0, 0.0),\n                                                Vector3d(2.0, 0.0, 0.0),\n                                                Vector3d(3.0, 0.0, 0.0) };\n\n  const Quaterniond soln_rotation = Quaterniond(\n      AngleAxisd(DegToRad(0.0), Vector3d(0.0, 0.0, 1.0)));\n  const Vector3d soln_translation(1.0, 1.0, 1.0);\n  const double soln_scale = 0.77;\n  const double kNoise = 0.5 / 512.0;\n  const double kMaxReprojectionError = 2.0 / 5.0;\n  const double kMaxAllowedRotationDifference = DegToRad(0.2);\n  const double kMaxAllowedTranslationDifference = 5e-4;\n  const double kMaxAllowedScaleDifference = 1e-2;\n\n  TestGdlsSimilarityTransformWithNoise(\n      kImageOrigins,\n      points_3d,\n      kNoise,\n      soln_rotation,\n      soln_translation,\n      soln_scale,\n      kMaxReprojectionError,\n      kMaxAllowedRotationDifference,\n      kMaxAllowedTranslationDifference,\n      kMaxAllowedScaleDifference);\n}\n\nTEST(GdlsSimilarityTransform, NoTranslation) {\n  const std::vector<Vector3d> points_3d = { Vector3d(-1.0, 3.0, 3.0),\n                                            Vector3d(1.0, -1.0, 2.0),\n                                            Vector3d(-1.0, 1.0, 2.0),\n                                            Vector3d(2.0, 1.0, 3.0),\n                                            Vector3d(-1.0, -3.0, 2.0),\n                                            Vector3d(1.0, -2.0, 1.0),\n                                            Vector3d(-1.0, 4.0, 2.0),\n                                            Vector3d(-2.0, 2.0, 3.0)\n  };\n  const std::vector<Vector3d> kImageOrigins = { Vector3d(-1.0, 0.0, 0.0),\n                                                Vector3d(0.0, 0.0, 0.0),\n                                                Vector3d(2.0, 0.0, 0.0),\n                                                Vector3d(3.0, 0.0, 0.0) };\n\n  const Quaterniond soln_rotation = Quaterniond(\n      AngleAxisd(DegToRad(13.0), Vector3d(0.0, 0.0, 1.0)));\n  const Vector3d soln_translation(0.0, 0.0, 0.0);\n  const double soln_scale = 2.5;\n  const double kNoise = 1.0 / 512.0;\n  const double kMaxReprojectionError = 4.0 / 512.0;\n  const double kMaxAllowedRotationDifference = DegToRad(0.5);\n  const double kMaxAllowedTranslationDifference = 1e-3;\n  const double kMaxAllowedScaleDifference = 1e-2;\n\n  TestGdlsSimilarityTransformWithNoise(\n      kImageOrigins,\n      points_3d,\n      kNoise,\n      soln_rotation,\n      soln_translation,\n      soln_scale,\n      kMaxReprojectionError,\n      kMaxAllowedRotationDifference,\n      kMaxAllowedTranslationDifference,\n      kMaxAllowedScaleDifference);\n}\n\n}  // namespace\n}  // namespace theia\n", "meta": {"hexsha": "f383330c40bed7d230ca3738d426985a6725b1c4", "size": 15000, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/sfm/transformation/gdls_similarity_transform_test.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": "src/theia/sfm/transformation/gdls_similarity_transform_test.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": "src/theia/sfm/transformation/gdls_similarity_transform_test.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": 38.8601036269, "max_line_length": 80, "alphanum_fraction": 0.6020666667, "num_tokens": 4260, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702880639791, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.48233634339961634}}
{"text": "/**\n * @author Andre Anjos <andre.anjos@idiap.ch>\n * @date Sun 27 Oct 09:02:32 2013\n *\n * @brief Normal 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#include <boost/make_shared.hpp>\n\n#include <bob.core/random.h>\n\nstatic auto normal_doc = bob::extension::ClassDoc(\n  BOB_EXT_MODULE_PREFIX \".normal\",\n  \"Models a random normal distribution\",\n  \"This distribution produces random numbers :math:`x` distributed with the probability density function\\n\\n\"\n  \".. math::\\n\\n   p(x) = \\\\frac{1}{\\\\sqrt{2\\\\pi\\\\sigma}} e^{-\\\\frac{(x-\\\\mu)^2}{2\\\\sigma^2}}\\n\\n\"\n  \"where the ``mean`` (:math:`\\\\mu`) and ``sigma`` (:math:`\\\\sigma`, the standard deviation) are the parameters of this distribution class.\"\n)\n.add_constructor(bob::extension::FunctionDoc(\n  \"normal\",\n  \"Constructs a new normal distribution object\"\n)\n.add_prototype(\"dtype, [mean], [sigma]\", \"\")\n.add_parameter(\"dtype\", \":py:class:`numpy.dtype` or anything that converts to a dtype\", \"The data type to get the distribution for; only real-valued types are supported\")\n.add_parameter(\"mean\", \"dtype\", \"[Default: 0.] The mean :math:`\\\\mu` of the normal distibution\")\n.add_parameter(\"sigma\", \"dtype\", \"[Default: 1.] The standard deviation :math:`\\\\sigma` of the normal distributiuon\")\n);\n\n/* How to create a new PyBoostNormalObject */\nstatic PyObject* PyBoostNormal_New(PyTypeObject* type, PyObject*, PyObject*) {\n\n  /* Allocates the python object itself */\n  PyBoostNormalObject* self = (PyBoostNormalObject*)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 PyBoostNormalObject */\nstatic void PyBoostNormal_Delete (PyBoostNormalObject* o) {\n  o->distro.reset();\n  Py_TYPE(o)->tp_free((PyObject*)o);\n}\n\ntemplate <typename T>\nboost::shared_ptr<void> make_normal(PyObject* mean, PyObject* sigma) {\n  T cmean = 0.;\n  if (mean) cmean = PyBlitzArrayCxx_AsCScalar<T>(mean);\n  T csigma = 1.;\n  if (sigma) csigma = PyBlitzArrayCxx_AsCScalar<T>(sigma);\n  return boost::make_shared<bob::core::random::normal_distribution<T>>(cmean, csigma);\n}\n\nPyObject* PyBoostNormal_SimpleNew (int type_num, PyObject* mean, PyObject* sigma) {\nBOB_TRY\n  PyBoostNormalObject* retval = (PyBoostNormalObject*)PyBoostNormal_New(&PyBoostNormal_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_normal<float>(mean, sigma);\n      break;\n    case NPY_FLOAT64:\n      retval->distro = make_normal<double>(mean, sigma);\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 PyBoostNormal_Init(PyBoostNormalObject* self, PyObject *args, PyObject* kwds) {\nBOB_TRY\n  char** kwlist = normal_doc.kwlist();\n\n  PyObject* mean = 0;\n  PyObject* sigma = 0;\n\n  if (!PyArg_ParseTupleAndKeywords(args, kwds, \"O&|OO\", kwlist, &PyBlitzArray_TypenumConverter, &self->type_num, &mean, &sigma)) return -1; ///< FAILURE\n\n  switch(self->type_num) {\n    case NPY_FLOAT32:\n      self->distro = make_normal<float>(mean, sigma);\n      break;\n    case NPY_FLOAT64:\n      self->distro = make_normal<double>(mean, sigma);\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 PyBoostNormal_Check(PyObject* o) {\n  if (!o) return 0;\n  return PyObject_IsInstance(o, reinterpret_cast<PyObject*>(&PyBoostNormal_Type));\n}\n\nint PyBoostNormal_Converter(PyObject* o, PyBoostNormalObject** a) {\n  if (!PyBoostNormal_Check(o)) return 0;\n  Py_INCREF(o);\n  (*a) = reinterpret_cast<PyBoostNormalObject*>(o);\n  return 1;\n}\n\n\nstatic auto mean_doc = bob::extension::VariableDoc(\n  \"mean\",\n  \"dtype\",\n  \"The mean value the distribution will produce.\"\n);\ntemplate <typename T> PyObject* get_mean(PyBoostNormalObject* self) {\n  return PyBlitzArrayCxx_FromCScalar(boost::static_pointer_cast<bob::core::random::normal_distribution<T>>(self->distro)->mean());\n}\n\nstatic PyObject* PyBoostNormal_GetMean(PyBoostNormalObject* self) {\nBOB_TRY\n  switch (self->type_num) {\n    case NPY_FLOAT32:\n      return get_mean<float>(self);\n    case NPY_FLOAT64:\n      return get_mean<double>(self);\n    default:\n      PyErr_Format(PyExc_NotImplementedError, \"cannot get mean 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(\"mean\", 0)\n}\n\n\nstatic auto sigma_doc = bob::extension::VariableDoc(\n  \"sigma\",\n  \"dtype\",\n  \"The standard deviation the distribution will have\"\n);\ntemplate <typename T> PyObject* get_sigma(PyBoostNormalObject* self) {\n  return PyBlitzArrayCxx_FromCScalar(boost::static_pointer_cast<bob::core::random::normal_distribution<T>>(self->distro)->sigma());\n}\n\nstatic PyObject* PyBoostNormal_GetSigma(PyBoostNormalObject* self) {\nBOB_TRY\n  switch (self->type_num) {\n    case NPY_FLOAT32:\n      return get_sigma<float>(self);\n    case NPY_FLOAT64:\n      return get_sigma<double>(self);\n    default:\n      PyErr_Format(PyExc_NotImplementedError, \"cannot get sigma 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(\"sigma\", 0)\n}\n\nstatic auto dtype_doc = bob::extension::VariableDoc(\n  \"dtype\",\n  \":py:class:`numpy.dtype`\",\n  \"The type of scalars produced by this normal distribution\"\n);\nstatic PyObject* PyBoostNormal_GetDtype(PyBoostNormalObject* self) {\nBOB_TRY\n  return Py_BuildValue(\"N\", PyArray_DescrFromType(self->type_num));\nBOB_CATCH_MEMBER(\"dtype\", 0)\n}\n\n\nstatic PyGetSetDef PyBoostNormal_getseters[] = {\n    {\n      dtype_doc.name(),\n      (getter)PyBoostNormal_GetDtype,\n      0,\n      dtype_doc.doc(),\n      0,\n    },\n    {\n      mean_doc.name(),\n      (getter)PyBoostNormal_GetMean,\n      0,\n      mean_doc.doc(),\n      0,\n    },\n    {\n      sigma_doc.name(),\n      (getter)PyBoostNormal_GetSigma,\n      0,\n      sigma_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(PyBoostNormalObject* self) {\n  boost::static_pointer_cast<bob::core::random::normal_distribution<T>>(self->distro)->reset();\n  Py_RETURN_NONE;\n}\n\n/**\n * Resets the distribution - this is a noop for normal distributions, here\n * only for compatibility reasons\n */\nstatic PyObject* PyBoostNormal_Reset(PyBoostNormalObject* self) {\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  }\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 normal distribution\")\n;\ntemplate <typename T> PyObject* call(PyBoostNormalObject* self, PyBoostMt19937Object* rng) {\n  typedef bob::core::random::normal_distribution<T> distro_t;\n  return PyBlitzArrayCxx_FromCScalar((*boost::static_pointer_cast<distro_t>(self->distro))(*rng->rng));\n}\n\n/**\n * Calling a PyBoostNormalObject to generate a random number\n */\nstatic PyObject* PyBoostNormal_Call(PyBoostNormalObject* 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 PyBoostNormal_methods[] = {\n    {\n      call_doc.name(),\n      (PyCFunction)PyBoostNormal_Call,\n      METH_VARARGS|METH_KEYWORDS,\n      call_doc.doc(),\n    },\n    {\n      reset_doc.name(),\n      (PyCFunction)PyBoostNormal_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* PyBoostNormal_Repr(PyBoostNormalObject* self) {\nBOB_TRY\n  PyObject* smean = scalar_to_bytes(PyBoostNormal_GetMean(self));\n  if (!smean) return 0;\n  auto smean_ = make_safe(smean);\n  PyObject* ssigma = scalar_to_bytes(PyBoostNormal_GetSigma(self));\n  if (!ssigma) return 0;\n  auto ssigma_ = make_safe(ssigma);\n\n  return\n    PyString_FromFormat\n      (\n       \"%s(dtype='%s', mean=%s, sigma=%s)\",\n       Py_TYPE(self)->tp_name, PyBlitzArray_TypenumAsString(self->type_num),\n       PyString_AS_STRING(smean), PyString_AS_STRING(ssigma)\n      );\nBOB_CATCH_MEMBER(\"repr\", 0)\n}\n\nPyTypeObject PyBoostNormal_Type = {\n  PyVarObject_HEAD_INIT(0,0)\n  0\n};\n\nbool init_BoostNormal(PyObject* module)\n{\n  // initialize the type struct\n  PyBoostNormal_Type.tp_name = normal_doc.name();\n  PyBoostNormal_Type.tp_basicsize = sizeof(PyBoostNormalObject);\n  PyBoostNormal_Type.tp_flags = Py_TPFLAGS_DEFAULT;\n  PyBoostNormal_Type.tp_doc = normal_doc.doc();\n  PyBoostNormal_Type.tp_str = reinterpret_cast<reprfunc>(PyBoostNormal_Repr);\n  PyBoostNormal_Type.tp_repr = reinterpret_cast<reprfunc>(PyBoostNormal_Repr);\n\n  // set the functions\n  PyBoostNormal_Type.tp_new = PyBoostNormal_New;\n  PyBoostNormal_Type.tp_init = reinterpret_cast<initproc>(PyBoostNormal_Init);\n  PyBoostNormal_Type.tp_dealloc = reinterpret_cast<destructor>(PyBoostNormal_Delete);\n  PyBoostNormal_Type.tp_methods = PyBoostNormal_methods;\n  PyBoostNormal_Type.tp_getset = PyBoostNormal_getseters;\n  PyBoostNormal_Type.tp_call = reinterpret_cast<ternaryfunc>(PyBoostNormal_Call);\n\n  // check that everything is fine\n  if (PyType_Ready(&PyBoostNormal_Type) < 0) return false;\n\n  // add the type to the module\n  return PyModule_AddObject(module, \"normal\", Py_BuildValue(\"O\", &PyBoostNormal_Type)) >= 0;\n}\n", "meta": {"hexsha": "36a81a01313f6c65ea96cff2337a43a85f59bc4e", "size": 11445, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bob/core/random/normal.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/normal.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/normal.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": 32.0588235294, "max_line_length": 216, "alphanum_fraction": 0.7115771079, "num_tokens": 3070, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.48233633548977833}}
{"text": "// Copyright 2015-2018 Hans Dembinski\n//\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n//[ guide_custom_minimal_axis\n\n#include <boost/histogram.hpp>\n#include <cassert>\n\nint main() {\n  using namespace boost::histogram;\n\n  // stateless axis which returns 1 if the input is even and 0 otherwise\n  struct even_odd_axis {\n    axis::index_type index(int x) const { return x % 2; }\n    axis::index_type size() const { return 2; }\n  };\n\n  // threshold axis which returns 1 if the input is above threshold\n  struct threshold_axis {\n    threshold_axis(double x) : thr(x) {}\n    axis::index_type index(double x) const { return x >= thr; }\n    axis::index_type size() const { return 2; }\n    double thr;\n  };\n\n  auto h = make_histogram(even_odd_axis(), threshold_axis(3.0));\n\n  h(0, 2.0);\n  h(1, 4.0);\n  h(2, 4.0);\n\n  assert(h.at(0, 0) == 1); // even, below threshold\n  assert(h.at(0, 1) == 1); // even, above threshold\n  assert(h.at(1, 0) == 0); // odd, below threshold\n  assert(h.at(1, 1) == 1); // odd, above threshold\n}\n\n//]\n", "meta": {"hexsha": "21c5fd5ce2115bc8f91c78537ed6c50a9d31241f", "size": 1128, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/histogram/examples/guide_custom_minimal_axis.cpp", "max_stars_repo_name": "cpp-pm/boost", "max_stars_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "libs/histogram/examples/guide_custom_minimal_axis.cpp", "max_issues_repo_name": "cpp-pm/boost", "max_issues_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "libs/histogram/examples/guide_custom_minimal_axis.cpp", "max_forks_repo_name": "cpp-pm/boost", "max_forks_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 26.8571428571, "max_line_length": 72, "alphanum_fraction": 0.6569148936, "num_tokens": 344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702880639791, "lm_q2_score": 0.6654105454764747, "lm_q1q2_score": 0.4823363337803417}}
{"text": "#include <deal.II/base/point.h>\n\n#include <deal.II/grid/tria.h>\n\n#include <gtest/gtest.h>\n\n#include <fstream>\n\nusing namespace dealii;\n\n// Declare functions in step-1 and step-2\nvoid first_grid(Triangulation<2> &);\nvoid second_grid(Triangulation<2> &);\nvoid third_grid(Triangulation<2> &);\nstd::tuple<unsigned int, unsigned int, unsigned int>\nget_info(const Triangulation<2> &);\n\n\n\nTEST(Step1, Mark1)\n{\n  Triangulation<2> tria;\n  first_grid(tria);\n  ASSERT_TRUE(std::ifstream(\"grid-1.svg\"));\n}\n\n\n\nTEST(Step1, Mark2)\n{\n  Triangulation<2> tria;\n  second_grid(tria);\n  ASSERT_TRUE(std::ifstream(\"grid-2.svg\"));\n}\n\n\n\nTEST(Step1, Mark3)\n{\n  Triangulation<2> tria;\n  third_grid(tria);\n  ASSERT_TRUE(std::ifstream(\"grid-3.vtk\"));\n}\n\n\n\nTEST(Step1, Mark4)\n{\n  Triangulation<2> tria;\n  first_grid(tria);\n  auto [levels, cells, active_cells] = get_info(tria);\n  EXPECT_EQ(levels, 5u);\n  EXPECT_EQ(cells, 341u);\n  EXPECT_EQ(active_cells, 256u);\n}\n\n\n\nTEST(Step1, Mark5)\n{\n  Triangulation<2> tria;\n  second_grid(tria);\n  const auto [levels, cells, active_cells] = get_info(tria);\n  EXPECT_EQ(levels, 6u);\n  EXPECT_EQ(cells, 1250u);\n  EXPECT_EQ(active_cells, 940u);\n}\n\n\n\nTEST(Step1, Mark6)\n{\n  Triangulation<2> tria;\n  third_grid(tria);\n  auto [levels, cells, active_cells] = get_info(tria);\n  EXPECT_EQ(levels, 5u);\n  EXPECT_EQ(cells, 351u);\n  EXPECT_EQ(active_cells, 264u);\n}\n\n\n\nint\nmain(int argc, char *argv[])\n{\n  testing::InitGoogleTest(&argc, argv);\n  return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "7ac99ce5be4d5f840d9ae8f770aedd1879e31a1a", "size": 1469, "ext": "cc", "lang": "C++", "max_stars_repo_path": "source/gtest.cc", "max_stars_repo_name": "luca-heltai/sissa-mhpc-lab-02", "max_stars_repo_head_hexsha": "b08febd339a9ecf78f26d51b5082bb0483512a0d", "max_stars_repo_licenses": ["MIT"], "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/gtest.cc", "max_issues_repo_name": "luca-heltai/sissa-mhpc-lab-02", "max_issues_repo_head_hexsha": "b08febd339a9ecf78f26d51b5082bb0483512a0d", "max_issues_repo_licenses": ["MIT"], "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/gtest.cc", "max_forks_repo_name": "luca-heltai/sissa-mhpc-lab-02", "max_forks_repo_head_hexsha": "b08febd339a9ecf78f26d51b5082bb0483512a0d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.5056179775, "max_line_length": 60, "alphanum_fraction": 0.6957113683, "num_tokens": 459, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6654105454764747, "lm_q2_score": 0.7248702880639791, "lm_q1q2_score": 0.4823363337803417}}
{"text": "/**********************************************************************\n *\n * This code is part of the MRcore projec\n * Author:  Alberto Valero Gomez (alberto.valero.gomez@gmail.com)\n *\t\t\tJulio Valero Gomez\n *\n *\n * MRcore is licenced under the Common Creative License,\n * Attribution-NonCommercial-ShareAlike 3.0\n *\n * You are free:\n *   - to Share - to copy, distribute and transmit the work\n *   - to Remix - to adapt the work\n *\n * Under the following conditions:\n *   - Attribution. You must attribute the work in the manner specified\n *     by the author or licensor (but not in any way that suggests that\n *     they endorse you or your use of the work).\n *   - Noncommercial. You may not use this work for commercial purposes.\n *   - Share Alike. If you alter, transform, or build upon this work,\n *     you may distribute the resulting work only under the same or\n *     similar license to this one.\n *\n * Any of the above conditions can be waived if you get permission\n * from the copyright holder.  Nothing in this license impairs or\n * restricts the author's moral rights.\n *\n * It is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied\n * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n * PURPOSE.\n **********************************************************************/\n\n\n#include <vector>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_real.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <algorithm>\n#include <numeric>\n#include <cmath>\n//#include \"/usr/local/include/mrcore/mrcore.h\"\n#include <iostream>\n#include <fstream>\n#include \"tictoc.h\"\n\n#include \"generation.h\"\n\n#include \"gnuplot_gui.h\"\n#include \"string.h\"\n\nusing namespace std;\nusing namespace Gnuplot;\n\nclass Pose{\npublic:\n\tPose(double x, double y){this->x=x;this->y=y;}\n\t~Pose(){}\n\tdouble x,y;\n\tdouble distTo(Pose p){\n\t\treturn sqrt(fabs((x-p.x)*(x-p.x) + (y-p.y)*(y-p.y)));\n\t}\n};\n\nvoid drawResult(GnuplotGui& gui, vector<Point2d> gplotCities, vector<Point2d> gplotTravellers, Individual* ind, vector<Pose>& poses){\n\tgui.clear();\n\tgui.draw_points(gplotTravellers,\"Travellers\",\"Travellers\");\n\tgui.draw_points(gplotCities,\"Cities\",\"cities\");\n\n\tint genSize = ind->getGenSize();\n\tint* gen = ind->getGen();\n\tint num_travellers= ind->getNumTravellers();\n\tint robot = gen[0];\n\n//\tcout << \"Robot = \" <<robot << endl;\n\n\tvector < Path<Point2d> > paths;\n\tpaths.resize(num_travellers);\n\n\tfor (int i=0; i<genSize-1; i++){\n\t\tif (gen[i+1] < num_travellers){\n\t\t\tpaths[robot].push(Point2d(poses[gen[i]].x, poses[gen[i]].y));\n\t\t\tpaths[robot].push(Point2d(poses[robot].x, poses[robot].y));\n\t\t\t//next robot\n\t\t\trobot = gen[i+1];\n//\t\t\tcout << \"Robot = \" <<robot << endl;\n\t\t\tcontinue;\n\t\t}\n\t\tpaths[robot].push(Point2d(poses[gen[i]].x, poses[gen[i]].y));\n\t}\n\tpaths[robot].push(Point2d(poses[gen[genSize-1]].x, poses[gen[genSize-1]].y));\n\tpaths[robot].push(Point2d(poses[robot].x, poses[robot].y)); //close the last loop\n\n\t//draw the paths\n\tfor (unsigned int i=0;i<paths.size();i++){\n\t\tstring tag;\n\t\tstringstream ss;//create a stringstream\n\t\tss << \"Robot \" << i;//add number to the stream\n\t\ttag = ss.str();//return a string with the contents of the stream\n\t\tgui.draw_path(paths[i],tag);\n\t}\n\n\tgui.redraw();\n\t//sleep(0.2);\n\n}\n\nint main(){\n\n\tGnuplotGui gui_poses;\n\n\tgui_poses.set_xrange(0,500);\n\tgui_poses.set_yrange(0,250);\n\n\tvector<Point2d> gplotCities;\n\tvector<Point2d> gplotTravellers;\n\n\t//vector<Pose> poses;\n\n\n\tint num_cities, num_travellers, steady_number, population_size;\n\tcout << \"Please introduce the following data:\" << endl;\n\tcout << \"Num Cities: \"; cin >> num_cities;\n\tcout << \"Num Travellers: \"; cin >> num_travellers;\n\tcout << \"Number of steady iterations for terminate: \"; cin >> steady_number;\n\n\tpopulation_size=100;\n\n\n\t/********* CREATE GRAPH*********/\n\tcout << \"Creating Graph\" << endl;\n\tsrand(time(0));\n\tvector<Pose> poses;\n\tdouble** costs;\n\tint num_points = num_cities + num_travellers;\n\n\tfor (int i=0;i<num_travellers;i++){\n\t\tdouble x= double(rand()%500);\n\t\tdouble y= double(rand()%250);\n\t\tgplotTravellers.push_back(Point2d(x,y));\n\t\tposes.push_back(Pose(x,y));\n\t}\n\n\tgui_poses.draw_points(gplotTravellers,\"Travellers\",\"Travellers\"); gui_poses.redraw();\n\n\tfor (int i=0;i<num_cities;i++){\n\t\tdouble x= double(rand()%500);\n\t\tdouble y= double(rand()%250);\n\t\tgplotCities.push_back(Point2d(x,y));\n\t\tposes.push_back(Pose(x,y));\n\t}\n\n\t// draw poses\n\tgui_poses.draw_points(gplotCities,\"Cities\",\"cities\"); gui_poses.redraw();\n\n\tsleep(2);\n\n\tcosts = new double*[num_points];\n\n\tfor (int i=0;i<num_points;i++){\n\t\tcosts[i]=new double[num_points];\n\t}\n\n\tfor (int i=0;i<num_points;i++){\n\t\tcosts[i][i]=0;\n\t\tfor (int j=i+1;j<num_points;j++){\n\t\t\tcosts[j][i]=costs[i][j]=(poses[i]).distTo(poses[j]);\n\t\t}\n\t}\n\n\tcout << \"Graph Created\" << endl;\n\t/************ END CREATE GRAPH *******************/\n\n\n\t/************** EVOLVE **************************/\n\tcout << \"Evolving\" << endl;\n\n\tGeneration* generation = new Generation(population_size,num_cities,num_travellers,costs,20,1.05);\n\tint numberGenerations = 0;\n\n\n\n\tdouble bestCost,prevBestCost;\n\n\ttictoc* timer = new tictoc();\n\ttic(timer);\n\n\tgeneration->generateInitGeneration(5,1000);\n\n\tIndividual* ind = generation->getBestIndividual();\n\tbestCost=ind->getCost();\n\tprevBestCost=bestCost;\n\n\tint steadyCounter=0;\n\tint steadyCounter2=0;\n\n\twhile(true){\n\t\tnumberGenerations ++;\n\n\t\tif (steadyCounter>steady_number){\n\t\t\tbreak; //end the evolution\n\t\t}\n\t\tfloat mutationPerc = 100.f*float(steadyCounter)/500;\n\t\tif (mutationPerc>50) mutationPerc=50;\n\t\tgeneration->setMutationPerc(mutationPerc);\n\t\tgeneration->generateNewGeneration();\n\t\tIndividual* ind=generation->getBestIndividual();\n\t\tbestCost=ind->getCost();\n\t\tif (fabs(bestCost-prevBestCost)<0.1){\n\t\t\tsteadyCounter++;steadyCounter2++;\n\t\t}\n\t\telse{\n\t\t\tsteadyCounter=steadyCounter2=0;\n\t\t\tdrawResult(gui_poses,gplotCities,gplotTravellers,ind,poses);\n\t\t\t//cout << \"Improvement\" << endl;\n\t\t}\n\t\tprevBestCost=bestCost;\n\n\t\tif (steadyCounter2>=steady_number/3){\n\t\t\tgeneration->inmigration(1,10000,25);\n\t\t\tsteadyCounter2=0;\n\t\t}\n\t}\n\n\tdrawResult(gui_poses,gplotCities,gplotTravellers,generation->getBestIndividual(),poses);\n\n\tcout << \"Finish of Evolution\" << endl;\n\t/**********END EVOLUTION*******************/\n\n\t/** FOR LOGGING **/\n\n\tdouble totalTime = toc(timer);\n\tdelete timer;\n\n\tind = generation->getBestIndividual();\n\n\tdouble totalCost = bestCost;\n\tnumberGenerations = numberGenerations - steady_number;\n\tdouble* individualCosts = new double[num_travellers];\n\n\tfor (int i=0;i<num_travellers;i++) individualCosts[i]=0;\n\n\tint * gen = ind->getGen();\n\tint genSize = ind->getGenSize();\n\n\tint robot = gen[0];\n\n\tfor (int i=0; i<genSize-1; i++){\n\t\tif (gen[i+1] < num_travellers){\n\t\t\tindividualCosts[robot]+=costs[gen[i]][robot]; //close the path\n\t\t\t//next robot\n\t\t\trobot = gen[i+1];\n\t\t\tcontinue;\n\t\t}\n\t\tindividualCosts[robot]+=costs[gen[i]][gen[i+1]];\n\t}\n\n\tindividualCosts[robot]+=costs[gen[genSize-1]][robot]; //close the last loop\n\n\n\tcout << population_size << \"\\t \" << steady_number << \"\\t\" << num_travellers << \"\\t\" << num_cities << \"\\t\" << numberGenerations << \"\\t\" << totalTime << \"\\t\" << totalCost <<\"\\t\";\n\tfor (int i=0; i < num_travellers;i++){\n\t\tcout << individualCosts[i] << \"\\t\";\n\t}\n\tcout <<endl;\n\n\n\n\t/** END LOGGING OPERATIONS**/\n\tdelete [] individualCosts;\n\tdelete generation;\n\n\n\tdelete [] costs;\n\tcout << \"Done!\" << endl;\n\treturn 1;\n}\n", "meta": {"hexsha": "1163eac0eada4d4789a1b3f375807143229cc358", "size": 7365, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "projet/mmTSP/main.cpp", "max_stars_repo_name": "jcalixte/drone", "max_stars_repo_head_hexsha": "ee0aa078ff22916dd215efd74a85781e040c1f0d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "projet/mmTSP/main.cpp", "max_issues_repo_name": "jcalixte/drone", "max_issues_repo_head_hexsha": "ee0aa078ff22916dd215efd74a85781e040c1f0d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "projet/mmTSP/main.cpp", "max_forks_repo_name": "jcalixte/drone", "max_forks_repo_head_hexsha": "ee0aa078ff22916dd215efd74a85781e040c1f0d", "max_forks_repo_licenses": ["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.4928057554, "max_line_length": 177, "alphanum_fraction": 0.6615071283, "num_tokens": 2082, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702880639791, "lm_q2_score": 0.6654105454764747, "lm_q1q2_score": 0.4823363337803417}}
{"text": "//\n//  Copyright (c) 2018, Cem Bassoy, cem.bassoy@gmail.com\n//  Copyright (c) 2019, Amit Singh, amitsingh19975@gmail.com\n//\n//  Distributed under the Boost Software License, Version 1.0. (See\n//  accompanying file LICENSE_1_0.txt or copy at\n//  http://www.boost.org/LICENSE_1_0.txt)\n//\n//  The authors gratefully acknowledge the support of\n//  Google and Fraunhofer IOSB, Ettlingen, Germany\n//\n\n\n#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <boost/numeric/ublas/tensor/algorithms.hpp>\n#include <boost/numeric/ublas/tensor/extents.hpp>\n#include \"utility.hpp\"\n\n#include <boost/test/unit_test.hpp>\n\n\nBOOST_AUTO_TEST_SUITE ( test_tensor_algorithms/*,\n                      * boost::unit_test::depends_on(\"test_shape_dynamic\") * boost::unit_test::depends_on(\"test_strides\")*/\n                      )\n\n// BOOST_AUTO_TEST_SUITE ( test_tensor_algorithms)\n\n\nusing test_types  = zip<int,float,std::complex<float>>::with_t<boost::numeric::ublas::layout::first_order, boost::numeric::ublas::layout::last_order>;\nusing test_types2 = std::tuple<std::int32_t,std::int64_t,float,double,std::complex<float>>;\n\nstruct fixture\n{\n  using extents_t = boost::numeric::ublas::extents<>;\n  const std::vector<extents_t> extents =\n  {\n      extents_t{1,1}, // 1\n      extents_t{1,2}, // 2\n      extents_t{2,1}, // 3\n      extents_t{2,3}, // 4\n      extents_t{2,3,1}, // 5\n      extents_t{4,1,3}, // 6\n      extents_t{1,2,3}, // 7\n      extents_t{4,2,3}, // 8\n      extents_t{4,2,3,5}\n  };\n};\n\n\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_algorithms_copy, value,  test_types2, fixture )\n{\n  namespace ublas    = boost::numeric::ublas;\n  using value_type   = value;\n  using vector_t     = std::vector<value_type>;\n\n\n  constexpr auto first_order = ublas::layout::first_order{};\n  constexpr auto last_order  = ublas::layout::last_order {};\n\n\n  for(auto const& n : extents) {\n\n    auto a  = vector_t(product(n));\n    auto b  = vector_t(product(n));\n    auto c  = vector_t(product(n));\n\n    auto wa = ublas::to_strides(n,first_order);\n    auto wb = ublas::to_strides(n,last_order );\n    auto wc = ublas::to_strides(n,first_order);\n\n    auto v = value_type{};\n    for(auto i = 0ul; i < a.size(); ++i, v+=1){\n      a[i]=v;\n    }\n\n    ublas::copy( ublas::size(n), n.data(), b.data(), wb.data(), a.data(), wa.data() );\n    ublas::copy( ublas::size(n), n.data(), c.data(), wc.data(), b.data(), wb.data() );\n\n    for(auto i = 1ul; i < c.size(); ++i)\n      BOOST_CHECK_EQUAL( c[i], a[i] );\n\n    std::size_t const*const p0 = nullptr;\n    value_type* c0 = nullptr;\n\n    BOOST_CHECK_THROW( ublas::copy( ublas::size(n), p0,      c.data(), wc.data(), b.data(), wb.data() ), std::runtime_error );\n    BOOST_CHECK_THROW( ublas::copy( ublas::size(n), n.data(), c.data(), p0,        b.data(), wb.data() ), std::runtime_error );\n    BOOST_CHECK_THROW( ublas::copy( ublas::size(n), n.data(), c.data(), wc.data(), b.data(), p0        ), std::runtime_error );\n    BOOST_CHECK_THROW( ublas::copy( ublas::size(n), n.data(), c0,       wc.data(), b.data(), wb.data() ), std::runtime_error );\n  }\n}\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_algorithms_copy_exceptions, value,  test_types2, fixture )\n{\n  namespace ublas    = boost::numeric::ublas;\n  using value_type   = value;\n  using vector_t     = std::vector<value_type>;\n  constexpr auto first_order = ublas::layout::first_order{};\n\n\n  for(auto const& n : extents) {\n\n    value_type* a  = nullptr;\n    auto c  = vector_t(ublas::product(n));\n\n    auto wa = ublas::to_strides(n,first_order);\n    auto wc = ublas::to_strides(n,first_order);\n\n    BOOST_REQUIRE_THROW( ublas::copy( ublas::size(n), n.data(), c.data(), wc.data(), a, wa.data() ), std::runtime_error );\n\n  }\n\n  for(auto const& n : extents) {\n\n    value_type* a  = nullptr;\n    value_type* c  = nullptr;\n\n    auto wa = ublas::to_strides(n,first_order);\n    auto wc = ublas::to_strides(n,first_order);\n\n    BOOST_REQUIRE_THROW( ublas::copy( ublas::size(n), n.data(), c, wc.data(), a, wa.data() ), std::runtime_error );\n\n  }\n\n  for(auto const& n : extents) {\n\n    auto a  = vector_t(product(n));\n    value_type* c  = nullptr;\n\n    auto wa = ublas::to_strides(n,first_order);\n    auto wc = ublas::to_strides(n,first_order);\n\n    BOOST_REQUIRE_THROW( ublas::copy( ublas::size(n), n.data(), c, wc.data(), a.data(), wa.data() ), std::runtime_error );\n\n  }\n\n  for(auto const& n : extents) {\n\n    auto a  = vector_t(product(n));\n    auto c  = vector_t(product(n));\n\n\n    size_t* wa = nullptr;\n    auto wc = ublas::to_strides(n,first_order);\n\n    BOOST_REQUIRE_THROW( ublas::copy( ublas::size(n), n.data(), c.data(), wc.data(), a.data(), wa ), std::runtime_error );\n\n  }\n\n  for(auto const& n : extents) {\n\n    auto a  = vector_t(product(n));\n    auto c  = vector_t(product(n));\n\n\n\n    size_t* wc = nullptr;\n    auto wa = ublas::to_strides(n,first_order);\n\n    BOOST_REQUIRE_THROW( ublas::copy( ublas::size(n), n.data(), c.data(), wc, a.data(), wa.data() ), std::runtime_error );\n\n  }\n\n  for(auto const& n : extents) {\n\n    auto a  = vector_t(product(n));\n    auto c  = vector_t(product(n));\n\n    size_t* m = nullptr;\n    auto wa = ublas::to_strides(n,first_order);\n    auto wc = ublas::to_strides(n,first_order);\n\n    BOOST_REQUIRE_THROW( ublas::copy( ublas::size(n), m, c.data(), wc.data(), a.data(), wa.data() ), std::runtime_error );\n\n  }\n}\n\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_algorithms_transform, value,  test_types2, fixture )\n{\n  namespace ublas    = boost::numeric::ublas;\n  using value_type   = value;\n  using vector_t  = std::vector<value_type>;\n\n  constexpr auto first_order = ublas::layout::first_order{};\n  constexpr auto last_order  = ublas::layout::last_order {};\n\n\n  for(auto const& n : extents) {\n\n    auto a  = vector_t(ublas::product(n));\n    auto b  = vector_t(ublas::product(n));\n    auto c  = vector_t(ublas::product(n));\n\n    auto wa = ublas::to_strides(n,first_order);\n    auto wb = ublas::to_strides(n,last_order );\n    auto wc = ublas::to_strides(n,first_order);\n\n    auto v = value_type{};\n    for(auto i = 0ul; i < a.size(); ++i, v+=1){\n      a[i]=v;\n    }\n\n    ublas::transform( ublas::size(n), n.data(), b.data(), wb.data(), a.data(), wa.data(), [](value_type const& a){ return a + value_type(1);} );\n    ublas::transform( ublas::size(n), n.data(), c.data(), wc.data(), b.data(), wb.data(), [](value_type const& a){ return a - value_type(1);} );\n\n    auto zero = std::size_t{0};\n    ublas::transform(zero, n.data(), c.data(), wc.data(), b.data(), wb.data(), [](value_type const& a){ return a + value_type(1);} );\n\n    value_type* c0 = nullptr;\n    const std::size_t* s0 = nullptr;\n    std::size_t const*const p0 = nullptr;\n\n    BOOST_CHECK_THROW(ublas::transform( ublas::size(n), n.data(), c0, wb.data(), a.data(), wa.data(), [](value_type const& a){ return a + value_type(1);} ), std::runtime_error);\n    BOOST_CHECK_THROW(ublas::transform( ublas::size(n), n.data(), b.data(), s0, a.data(), wa.data(), [](value_type const& a){ return a + value_type(1);} ), std::runtime_error);\n    BOOST_CHECK_THROW(ublas::transform( ublas::size(n), p0, b.data(), wb.data(), a.data(), wa.data(), [](value_type const& a){ return a + value_type(1);} ), std::runtime_error);\n\n\n    for(auto i = 1ul; i < c.size(); ++i)\n      BOOST_CHECK_EQUAL( c[i], a[i] );\n\n  }\n}\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_algorithms_transform_exceptions, value,  test_types2, fixture )\n{\n  namespace ublas    = boost::numeric::ublas;\n  using value_type   = value;\n  using vector_t  = std::vector<value_type>;\n\n  constexpr auto first_order = ublas::layout::first_order{};\n\n  for(auto const& n : extents) {\n\n    value_type* a  = nullptr;\n    auto c  = vector_t(ublas::product(n));\n\n    auto wa = ublas::to_strides(n,first_order);\n    auto wc = ublas::to_strides(n,first_order);\n\n    BOOST_REQUIRE_THROW( ublas::transform( ublas::size(n), n.data(), c.data(), wc.data(), a, wa.data(), [](value_type const& a){ return a + value_type(1);} ), std::runtime_error );\n\n  }\n\n  for(auto const& n : extents) {\n\n    value_type* a  = nullptr;\n    value_type* c  = nullptr;\n\n    auto wa = ublas::to_strides(n,first_order);\n    auto wc = ublas::to_strides(n,first_order);\n\n    BOOST_REQUIRE_THROW( ublas::transform( ublas::size(n), n.data(), c, wc.data(), a, wa.data(), [](value_type const& a){ return a + value_type(1);} ), std::runtime_error );\n\n  }\n\n  for(auto const& n : extents) {\n\n    auto a  = vector_t(ublas::product(n));\n    value_type* c  = nullptr;\n\n    auto wa = ublas::to_strides(n,first_order);\n    auto wc = ublas::to_strides(n,first_order);\n\n    BOOST_REQUIRE_THROW( ublas::transform( ublas::size(n), n.data(), c, wc.data(), a.data(), wa.data(), [](value_type const& a){ return a + value_type(1);} ), std::runtime_error );\n\n  }\n\n  for(auto const& n : extents) {\n\n    auto a  = vector_t(product(n));\n    auto c  = vector_t(product(n));\n\n    size_t* wa = nullptr;\n    auto wc = ublas::to_strides(n,first_order);\n\n    BOOST_REQUIRE_THROW( ublas::transform( ublas::size(n), n.data(), c.data(), wc.data(), a.data(), wa, [](value_type const& a){ return a + value_type(1);} ), std::runtime_error );\n\n  }\n\n  for(auto const& n : extents) {\n\n    auto a  = vector_t(ublas::product(n));\n    auto c  = vector_t(ublas::product(n));\n\n    size_t* wc = nullptr;\n    auto wa = ublas::to_strides(n,first_order);\n\n    BOOST_REQUIRE_THROW( ublas::transform( ublas::size(n), n.data(), c.data(), wc, a.data(), wa.data(), [](value_type const& a){ return a + value_type(1);} ), std::runtime_error );\n\n  }\n\n  for(auto const& n : extents) {\n\n    auto a  = vector_t(product(n));\n    auto c  = vector_t(product(n));\n\n    size_t* m = nullptr;\n    auto wa = ublas::to_strides(n,first_order);\n    auto wc = ublas::to_strides(n,first_order);\n\n    BOOST_REQUIRE_THROW( ublas::transform( ublas::size(n), m, c.data(), wc.data(), a.data(), wa.data(), [](value_type const& a){ return a + value_type(1);} ), std::runtime_error );\n\n  }\n}\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_algorithms_accumulate, value,  test_types2, fixture )\n{\n  namespace ublas    = boost::numeric::ublas;\n  using value_type   = value;\n  using vector_t     = std::vector<value_type>;\n\n  constexpr auto first_order = ublas::layout::first_order{};\n\n\n  for(auto const& n : extents) {\n\n    auto const s = ublas::product(n);\n\n    auto a  = vector_t(ublas::product(n));\n    auto wa = ublas::to_strides(n,first_order);\n\n\n    auto v = value_type{};\n    for(auto i = 0ul; i < a.size(); ++i, v+=value_type(1)){\n      a[i]=v;\n    }\n\n    auto acc = ublas::accumulate( ublas::size(n), n.data(), a.data(), wa.data(), v);\n\n    auto sum = std::div(s*(s+1),2).quot;\n\n    BOOST_CHECK_EQUAL( acc, value_type( static_cast< inner_type_t<value_type> >( sum ) )  );\n\n    auto zero = std::size_t{0};\n    (void)ublas::accumulate(zero, n.data(), a.data(), wa.data(),v);\n\n    value_type* c0 = nullptr;\n    std::size_t const*const p0 = nullptr;\n\n    BOOST_CHECK_THROW((void)ublas::accumulate( ublas::size(n), n.data(), c0, wa.data(), v), std::runtime_error);\n    BOOST_CHECK_THROW((void)ublas::accumulate( ublas::size(n), n.data(), a.data(), p0, v), std::runtime_error);\n    BOOST_CHECK_THROW((void)ublas::accumulate( ublas::size(n), p0, a.data(), wa.data(), v), std::runtime_error);\n\n\n    auto acc2 = ublas::accumulate( ublas::size(n), n.data(), a.data(), wa.data(), v,\n                                  [](auto const& l, auto const& r){return l + r; });\n\n    BOOST_CHECK_EQUAL( acc2, value_type( static_cast< inner_type_t<value_type> >( sum ) )  );\n\n    (void)ublas::accumulate(zero, n.data(), a.data(), wa.data(), v, [](auto const& l, auto const& r){return l + r; });\n\n    BOOST_CHECK_THROW((void)ublas::accumulate( ublas::size(n), n.data(), c0, wa.data(), v,[](auto const& l, auto const& r){return l + r; }), std::runtime_error);\n    BOOST_CHECK_THROW((void)ublas::accumulate( ublas::size(n), n.data(), a.data(), p0, v, [](auto const& l, auto const& r){return l + r; }), std::runtime_error);\n    BOOST_CHECK_THROW((void)ublas::accumulate( ublas::size(n), p0, a.data(), wa.data(),v, [](auto const& l, auto const& r){return l + r; }), std::runtime_error);\n\n  }\n}\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_algorithms_accumulate_exceptions, value,  test_types2, fixture )\n{\n  namespace ublas    = boost::numeric::ublas;\n  using value_type   = value;\n  using vector_t  = std::vector<value_type>;\n  constexpr auto first_order = ublas::layout::first_order{};\n\n\n  for(auto const& n : extents) {\n    value_type* a  = nullptr;\n    auto wa = ublas::to_strides(n,first_order);\n    BOOST_REQUIRE_THROW( (void)ublas::accumulate( ublas::size(n), n.data(), a, wa.data(), value_type{0} ), std::runtime_error );\n\n  }\n\n  for(auto const& n : extents) {\n    value_type* a  = nullptr;\n    auto wa = ublas::to_strides(n,first_order);\n    BOOST_REQUIRE_THROW( (void)ublas::accumulate( ublas::size(n), n.data(), a, wa.data(), value_type{0},[](value_type const& a,value_type const& b){ return a + b;} ), std::runtime_error );\n  }\n\n  for(auto const& n : extents) {\n    auto a  = vector_t(product(n));\n    auto wa = ublas::to_strides(n,first_order);\n    size_t p = 0u;\n    BOOST_CHECK_EQUAL ( ublas::accumulate( p, n.data(), a.data(), wa.data(), value_type{0} ), value_type{0} );\n  }\n\n  for(auto const& n : extents) {\n    auto a  = vector_t(product(n));\n    auto wa = ublas::to_strides(n,first_order);\n    size_t p = 0u;\n    BOOST_CHECK_EQUAL( ublas::accumulate( p, n.data(), a.data(), wa.data(), value_type{0}, [](value_type const& a,value_type const& b){ return a + b;} ), value_type{0} );\n  }\n\n  for(auto const& n : extents) {\n    auto a  = vector_t(product(n));\n    size_t* wa = nullptr;\n    BOOST_REQUIRE_THROW( (void)ublas::accumulate( ublas::size(n), n.data(), a.data(), wa, value_type{0} ), std::runtime_error );\n  }\n\n  for(auto const& n : extents) {\n    auto a  = vector_t(product(n));\n    auto wa = ublas::to_strides(n,first_order);\n    size_t* m = nullptr;\n    BOOST_REQUIRE_THROW( (void)ublas::accumulate( ublas::size(n), m, a.data(), wa.data(), value_type{0}, [](value_type const& a,value_type const& b){ return a + b;} ), std::runtime_error );\n  }\n\n}\n\n\ntemplate<class V>\nvoid init(std::vector<V>& a)\n{\n  auto v = V(1);\n  for(auto i = 0u; i < a.size(); ++i, ++v){\n    a[i] = v;\n  }\n}\n\ntemplate<class V>\nvoid init(std::vector<std::complex<V>>& a)\n{\n  auto v = std::complex<V>(1,1);\n  for(auto i = 0u; i < a.size(); ++i){\n    a[i] = v;\n    v.real(v.real()+1);\n    v.imag(v.imag()+1);\n  }\n}\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_algorithms_trans, value,  test_types, fixture )\n{\n  namespace ublas   = boost::numeric::ublas;\n  using value_type  = typename value::first_type;\n//  using layout_t    = typename value::second_type;\n  using vector_t    = std::vector<value_type>;\n  using base_t      = typename extents_t::base_type;\n  using permutation_type = std::vector<std::size_t>;\n\n  constexpr auto first_order = ublas::layout::first_order{};\n\n\n  for(auto const& n : extents) {\n\n    auto p   = ublas::size(n);\n    auto s   = ublas::product(n);\n\n    auto pi  = permutation_type(p);\n    auto a   = vector_t(s);\n    auto b1  = vector_t(s);\n    auto b2  = vector_t(s);\n    auto c1  = vector_t(s);\n    auto c2  = vector_t(s);\n\n    auto wa = ublas::to_strides(n,first_order);\n\n    init(a);\n\n    // so wie last-order.\n    for(auto i = std::size_t{0}, j = p; i < ublas::size(n); ++i, --j)\n      pi[i] = j;\n\n    auto nc_base = base_t(p);\n    for(auto i = 0u; i < p; ++i)\n      nc_base[pi[i]-1] = n[i];\n\n    auto nc = extents_t(std::move(nc_base));\n\n    auto wc    = ublas::to_strides(nc,first_order);\n    auto wc_pi = base_t(p);\n    for(auto i = 0u; i < p; ++i)\n      wc_pi[pi[i]-1] = wc[i];\n\n    ublas::copy ( p, n.data(),            c1.data(), wc_pi.data(), a.data(), wa.data());\n    ublas::trans( p, n.data(), pi.data(), c2.data(), wc.data(),    a.data(), wa.data() );\n\n    if(!std::is_compound_v<value_type>)\n      for(auto i = 0ul; i < s; ++i)\n        BOOST_CHECK_EQUAL( c1[i], c2[i] );\n\n\n    auto nb_base = base_t(p);\n    for(auto i = 0u; i < p; ++i)\n      nb_base[pi[i]-1] = nc[i];\n\n    auto nb = extents_t(std::move(nb_base));\n\n    auto wb    = ublas::to_strides(nb,first_order);\n    auto wb_pi = base_t(p);\n    for(auto i = 0u; i < p; ++i)\n      wb_pi[pi[i]-1] = wb[i];\n\n    ublas::copy ( p, nc.data(),            b1.data(), wb_pi.data(), c1.data(), wc.data());\n    ublas::trans( p, nc.data(), pi.data(), b2.data(), wb.data(),    c2.data(), wc.data() );\n\n    if(!std::is_compound_v<value_type>)\n      for(auto i = 0ul; i < s; ++i)\n        BOOST_CHECK_EQUAL( b1[i], b2[i] );\n\n    for(auto i = 0ul; i < s; ++i)\n      BOOST_CHECK_EQUAL( a[i], b2[i] );\n\n    auto zero = std::size_t{0};\n    ublas::trans( zero, n.data(), pi.data(), c2.data(), wc.data(), a.data(), wa.data() );\n    ublas::trans( zero, nc.data(), pi.data(), b2.data(), wb.data(), c2.data(), wc.data() );\n\n    value_type *c0 = nullptr;\n    std::size_t const*const s0 = nullptr;\n\n    BOOST_CHECK_THROW(ublas::trans( p, n.data(), pi.data(), c0, wc.data(),  a.data(), wa.data()), std::runtime_error);\n    BOOST_CHECK_THROW(ublas::trans( p, s0, pi.data(), c2.data(),wc.data(),  a.data(), wa.data()), std::runtime_error);\n    BOOST_CHECK_THROW(ublas::trans( p, n.data(), pi.data(), c2.data(), s0,  a.data(), wa.data()), std::runtime_error);\n    BOOST_CHECK_THROW(ublas::trans( p, n.data(), s0, c2.data(), wc.data(),  a.data(), wa.data()), std::runtime_error);\n\n  }\n}\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_algorithms_trans_exceptions, value,  test_types, fixture )\n{\n  namespace ublas        = boost::numeric::ublas;\n  using value_type       = typename value::first_type;\n  using layout_t         = typename value::second_type;\n  using vector_t         = std::vector<value_type>;\n  using permutation_type = std::vector<std::size_t>;\n\n  constexpr auto layout = layout_t{};\n\n  std::size_t* nnullptr = nullptr;\n  value_type * anullptr = nullptr;\n\n  for(auto const& n : extents) {\n    auto p  = ublas::size(n);\n    auto s  = ublas::product(n);\n    auto pi = permutation_type(p);\n    auto a  = vector_t(s);\n    auto c  = vector_t(s);\n    auto wa = ublas::to_strides(n,layout);\n    auto wc = ublas::to_strides(n,layout);\n    if(p>1){\n      BOOST_REQUIRE_THROW( ublas::trans( p, nnullptr, pi.data(), c.data(), wc.data(),    a.data(), wa.data() ), std::runtime_error );\n      BOOST_REQUIRE_THROW( ublas::trans( p, n.data() , nnullptr , c.data(), wc.data(),    a.data(), wa.data() ), std::runtime_error );\n      BOOST_REQUIRE_THROW( ublas::trans( p, n.data() , pi.data(), c.data(), nnullptr ,    a.data(), nnullptr  ), std::runtime_error );\n      BOOST_REQUIRE_THROW( ublas::trans( p, n.data() , pi.data(), c.data(), wc.data(),    a.data(), nnullptr  ), std::runtime_error );\n      BOOST_REQUIRE_THROW( ublas::trans( p, n.data() , pi.data(), c.data(), nnullptr ,    a.data(), wa.data() ), std::runtime_error );\n      BOOST_REQUIRE_THROW( ublas::trans( p, n.data() , pi.data(), anullptr, wc.data(),    anullptr, wa.data() ), std::runtime_error );\n      BOOST_REQUIRE_THROW( ublas::trans( p, n.data() , pi.data(), c.data(), wc.data(),    anullptr, wa.data() ), std::runtime_error );\n      BOOST_REQUIRE_THROW( ublas::trans( p, n.data() , pi.data(), anullptr, wc.data(),    a.data(), wa.data() ), std::runtime_error );\n    }\n\n    // ublas::trans( p, n.data(), pi.data(), c.data(), wc.data(),    a.data(), wa.data() );\n  }\n\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "477ee1e0c0c78b9fae23fb782057b35dfba7ccd3", "size": 19314, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/tensor/test_algorithms.cpp", "max_stars_repo_name": "samd2/ublas", "max_stars_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 96.0, "max_stars_repo_stars_event_min_datetime": "2015-01-23T10:15:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T18:31:02.000Z", "max_issues_repo_path": "test/tensor/test_algorithms.cpp", "max_issues_repo_name": "samd2/ublas", "max_issues_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 105.0, "max_issues_repo_issues_event_min_datetime": "2015-01-14T09:01:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-05T06:10:39.000Z", "max_forks_repo_path": "test/tensor/test_algorithms.cpp", "max_forks_repo_name": "samd2/ublas", "max_forks_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 157.0, "max_forks_repo_forks_event_min_datetime": "2015-01-26T13:35:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T11:12:27.000Z", "avg_line_length": 34.1236749117, "max_line_length": 189, "alphanum_fraction": 0.6206896552, "num_tokens": 5765, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702642896702, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.4823363323895773}}
{"text": "#ifndef RANDOM_UTIL_HPP\n#define RANDOM_UTIL_HPP\n/**\n * @file random_util.hpp\n *\n * @brief some functions commonly used in MTToolBox.\n *\n * @author Mutsuo Saito (Hiroshima University)\n * @author Makoto Matsumoto (The University of Tokyo)\n *\n * Copyright (C) 2011 Mutsuo Saito, Makoto Matsumoto,\n * Hiroshima University and The University of Tokyo.\n * All rights reserved.\n *\n * The 3-clause BSD License is applied to this software, see\n * LICENSE.txt\n */\n#include <stdio.h>\n#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <inttypes.h>\n#include <stdint.h>\n#include <stdexcept>\n#include <openssl/sha.h>\n#include <tr1/memory>\n\n#include <NTL/GF2X.h>\n\n#define bit_size(tp) (static_cast<int>(sizeof(tp) * 8))\n\nnamespace MTToolBox {\n    inline static int count_bit(uint16_t x);\n    inline static int count_bit(uint32_t x);\n    inline static int count_bit(uint64_t x);\n    inline static uint32_t reverse_bit(uint32_t x);\n    inline static uint64_t reverse_bit(uint64_t x);\n\n    /**\n     * calculate the largest number which is 2^m and does not exceed n.\n     * @tparam T type of integer\n     * @param n number\n     * @returns the largest number which is 2^m and does not exceed n.\n     */\n    template<typename T>\n    T floor2p(T n) {\n\tif (n == 1) {\n\t    return 1;\n\t} else {\n\t    return 2 * floor2p<T>(n / 2);\n\t}\n    }\n\n    /**\n     * print polynomial in binary form. The coefficient of the smallest degree\n     * is printed first.\n     * @param os output-stream\n     * @param poly polynomial to be printed\n     * @param breakline if true, break line every 32 outputs.\n     */\n    inline static void print_binary(std::ostream& os,\n\t\t\t\t    NTL::GF2X& poly,\n\t\t\t\t    bool breakline = true) {\n\tusing namespace NTL;\n\tif (deg(poly) < 0) {\n\t    os << \"0deg=-1\" << std::endl;\n\t    return;\n\t}\n\tfor(int i = 0; i <= deg(poly); i++) {\n\t    if(rep(coeff(poly, i)) == 1) {\n\t\tos << '1';\n\t    } else {\n\t\tos << '0';\n\t    }\n\t    if (breakline && ((i % 32) == 31)) {\n\t\tos << std::endl;\n\t    }\n\t}\n\tos << \"deg=\" << deg(poly) << std::endl;\n    }\n\n    /**\n     * change \\b input to the number between \\b start and \\b end\n     * @param input input number\n     * @param start start of the range\n     * @param end end of the range\n     * @return the number r such that \\b start <= \\b r <= \\b end.\n     */\n    inline static uint32_t get_range(uint32_t input, int start, int end) {\n\tif (end < start) {\n\t    printf(\"get_range:%d, %d\\n\", start, end);\n\t    exit(0);\n\t}\n\treturn input % (end - start + 1) + start;\n    }\n\n    /**\n     * change \\b input to the number between \\b start and \\b end\n     * @param input input number\n     * @param start start of the range\n     * @param end end of the range\n     * @return the number r such that \\b start <= \\b r <= \\b end.\n     */\n    inline static uint64_t get_range(uint64_t input, int start, int end) {\n\tif (end < start) {\n\t    printf(\"get_range:%u, %u\\n\", start, end);\n\t    exit(0);\n\t}\n\treturn input % (end - start + 1) + start;\n    }\n\n    /**\n     * change the small F2 table to the fast and redundant table.\n     * @tparam T type of table member.\n     * @param dist_tbl new redundant table\n     * @param src_tbl source table\n     * @param size size of \\b dist_table\n     */\n    template<typename T>\n    void fill_table(T dist_tbl[], T src_tbl[], int size) {\n    \tfor(int i = 1; i < size; i++) {\n\t    for(int j = 1, k = 0; j <= i; j <<= 1, k++) {\n\t\tif (i & j) {\n\t\t    dist_tbl[i] ^= src_tbl[k];\n\t\t}\n\t    }\n\t}\n    }\n\n    /**\n     * calculate the SHA1 digest of F2 polynomial. The coefficients of\n     * the polynomial are changed to the string of \"0\" and \"1\", which\n     * starts with the coefficient of the lowest degree, and the SHA1\n     * hash of the string is calculated. The result hash is returned\n     * by hexadecimal string.\n     *\n     * @param str output string\n     * @param poly F2 polynomial\n     */\n    inline static void poly_sha1(std::string& str, const NTL::GF2X& poly) {\n\tusing namespace NTL;\n\tusing namespace std;\n\tSHA_CTX ctx;\n\tSHA1_Init(&ctx);\n\tif (deg(poly) < 0) {\n\t    SHA1_Update(&ctx, \"-1\", 2);\n\t}\n\tfor(int i = 0; i <= deg(poly); i++) {\n\t    if(rep(coeff(poly, i)) == 1) {\n\t\tSHA1_Update(&ctx, \"1\", 1);\n\t    } else {\n\t\tSHA1_Update(&ctx, \"0\", 1);\n\t    }\n\t}\n\tunsigned char md[SHA_DIGEST_LENGTH];\n\tSHA1_Final(md, &ctx);\n\tstringstream ss;\n\tfor (int i = 0; i < SHA_DIGEST_LENGTH; i++) {\n\t    ss << setfill('0') << setw(2) << hex\n\t       << static_cast<int>(md[i]);\n\t}\n\tss >> str;\n    }\n\n\n    /**\n     * calculate the position of most right 1, or\n     * least significant 1. The position of the MSB is\n     * 0. returns -1 when \\b v is zero.\n     * citing from a website http://aggregate.org/MAGIC/#Trailing Zero Count\n     *\n     * @param x input\n     * @return the position of most right 1.\n     */\n    int calc_1pos(uint16_t x)\n    {\n\tif (x == 0) {\n\t    return -1;\n\t}\n\tint16_t y = (int16_t)x;\n\ty = count_bit((uint16_t)((y & -y) - 1));\n\treturn 15 - y;\n    }\n\n    /**\n     * calculate the position of most right 1, or\n     * least significant 1. The position of the MSB is\n     * 0. returns -1 when \\b v is zero.\n     * citing from a website http://aggregate.org/MAGIC/#Trailing Zero Count\n     *\n     * @param x input\n     * @return the position of most right 1.\n     */\n    int calc_1pos(uint32_t x)\n    {\n\tif (x == 0) {\n\t    return -1;\n\t}\n\tint32_t y = (int32_t)x;\n\ty = count_bit((uint32_t)(y & -y) - 1);\n\treturn 31 - y;\n    }\n\n    /**\n     * calculate the position of most right 1, or\n     * least significant 1. The position of the MSB is\n     * 0. returns -1 when \\b v is zero.\n     * citing from a website http://aggregate.org/MAGIC/#Trailing Zero Count\n     *\n     * @param x input\n     * @return the position of most right 1.\n     */\n    int calc_1pos(uint64_t x)\n    {\n\tif (x == 0) {\n\t    return -1;\n\t}\n\tint64_t y = (int64_t)x;\n\ty = count_bit((uint64_t)(y & -y) - 1);\n\treturn 63 - y;\n    }\n\n    /**\n     * check if \\b array is all zero or not.\n     * @tparam type of members of \\b array\n     * @param array checked array\n     * @param size size of \\b array\n     * @return true if all elements of \\b array are zero.\n     */\n    template<typename T>\n    bool is_zero_array(T *array, int size) {\n\tif (array[0] != 0) {\n\t    return false;\n\t} else {\n\t    return (memcmp(array, array + 1, sizeof(T) * (size - 1)) == 0);\n\t}\n    }\n\n    /**\n     * calculate the minimal polynomial of the generated sequence.\n     * @returns the minimal polynomial\n     */\n    template<typename G>\n    std::tr1::shared_ptr<NTL::GF2X> get_minpoly(G& generator, int length) {\n\tusing namespace std;\n\tusing namespace NTL;\n\tusing namespace std::tr1;\n\n\tvec_GF2 vec;\n\tvec.SetLength(length * 2);\n\tfor (int i = 0; i < length * 2; i++) {\n\t    vec[i] = generator() & 1;\n\t}\n\tshared_ptr<GF2X> minpoly(new GF2X());\n\tMinPolySeq(*minpoly, vec, length);\n\treturn minpoly;\n    }\n\n    /**\n     * count the number of 1\n     * SIMD within a Register algorithm\n     * citing from a website http://aggregate.org/MAGIC/\n     */\n    inline static int count_bit(uint16_t x) {\n        x -= (x >> 1) & UINT16_C(0x5555);\n        x = ((x >> 2) & UINT16_C(0x3333)) + (x & UINT16_C(0x3333));\n        x = ((x >> 4) + x) & UINT16_C(0x0f0f);\n        x += (x >> 8);\n        return (int)(x & 0x1f);\n    }\n\n    inline static int count_bit(uint32_t x) {\n        x -= (x >> 1) & UINT32_C(0x55555555);\n        x = ((x >> 2) & UINT32_C(0x33333333)) + (x & UINT32_C(0x33333333));\n        x = ((x >> 4) + x) & UINT32_C(0x0f0f0f0f);\n        x += (x >> 8);\n        x += (x >> 16);\n        return (int)(x & 0x3f);\n    }\n\n    inline static int count_bit(uint64_t x) {\n\tx -= (x >> 1) & UINT64_C(0x5555555555555555);\n\tx = ((x >> 2) & UINT64_C(0x3333333333333333))\n\t    + (x & UINT64_C(0x3333333333333333));\n\tx = ((x >> 4) + x) & UINT64_C(0x0f0f0f0f0f0f0f0f);\n\tx += (x >> 8);\n\tx += (x >> 16);\n\tx += (x >> 32);\n\treturn (int)(x & 0x7f);\n    }\n\n    inline static uint32_t reverse_bit(uint32_t x)\n    {\n\tuint32_t y = 0x55555555;\n\tx = (((x >> 1) & y) | ((x & y) << 1));\n\ty = 0x33333333;\n\tx = (((x >> 2) & y) | ((x & y) << 2));\n\ty = 0x0f0f0f0f;\n\tx = (((x >> 4) & y) | ((x & y) << 4));\n\ty = 0x00ff00ff;\n\tx = (((x >> 8) & y) | ((x & y) << 8));\n\treturn((x >> 16) | (x << 16));\n    }\n\n    inline static uint64_t reverse_bit(uint64_t x)\n    {\n\tuint64_t y = UINT64_C(0x5555555555555555);\n\tx = (((x >> 1) & y) | ((x & y) << 1));\n\ty = UINT64_C(0x3333333333333333);\n\tx = (((x >> 2) & y) | ((x & y) << 2));\n\ty = UINT64_C(0x0f0f0f0f0f0f0f0f);\n\tx = (((x >> 4) & y) | ((x & y) << 4));\n\ty = UINT64_C(0x00ff00ff00ff00ff);\n\tx = (((x >> 8) & y) | ((x & y) << 8));\n\ty = UINT64_C(0x0000ffff0000ffff);\n\tx = (((x >> 16) & y) | ((x & y) << 16));\n\treturn((x >> 32) | (x << 32));\n    }\n\n    /**\n     * divide and ceil\n     */\n    inline static int div_ceil(int x, int y) {\n\tif (x % y == 0) {\n\t    return x / y;\n\t} else {\n\t    return x / y + 1;\n\t}\n    }\n\n    /**\n     * polynomial to string\n     */\n    inline static void to_str(uint8_t * str, int size, NTL::GF2X& poly) {\n\tif (deg(poly) >= size * 8) {\n\t    std::cerr << \"str size too small\" << std::endl;\n\t    throw new std::out_of_range(\"str size too small\");\n\t}\n\tfor (int i = 0; i < size; i++) {\n\t    str[i] = 0;\n\t}\n\tint idx = 0;\n\tfor (int i = 0; i < size; i++) {\n\t    uint8_t mask = 1;\n\t    for (int j = 0; j < 8; j++) {\n\t\tif (IsOne(coeff(poly, idx++))) {\n\t\t    str[i] |= mask;\n\t\t}\n\t\tmask <<= 1;\n\t    }\n\t}\n    }\n}\n#endif\n", "meta": {"hexsha": "0d66a56714d59782368a290f2cdc240e17ad2ee8", "size": 9319, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dc/include/random_util.hpp", "max_stars_repo_name": "jj1bdx/TinyMT", "max_stars_repo_head_hexsha": "7cb31bc81f1cb98f1ae3a9b0d197c6f349a5e477", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-02-28T07:08:17.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-16T11:17:12.000Z", "max_issues_repo_path": "dc/include/random_util.hpp", "max_issues_repo_name": "jj1bdx/TinyMT", "max_issues_repo_head_hexsha": "7cb31bc81f1cb98f1ae3a9b0d197c6f349a5e477", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dc/include/random_util.hpp", "max_forks_repo_name": "jj1bdx/TinyMT", "max_forks_repo_head_hexsha": "7cb31bc81f1cb98f1ae3a9b0d197c6f349a5e477", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2015-02-28T07:08:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-04T03:50:26.000Z", "avg_line_length": 26.2507042254, "max_line_length": 78, "alphanum_fraction": 0.560897092, "num_tokens": 3078, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768249, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.48233633068014115}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <array>\n#include <boost/assert.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/multi_array.hpp>\n#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <vector>\n\n#include \"base/array_buffer.hpp\"\n#include \"base/exceptions.hpp\"\n#include \"base/timer.hpp\"\n#include \"filtered_range.hpp\"\n#ifndef NOHDF5\n#include \"base/eigen2hdf.hpp\"\n#endif\n#include \"quadrature/qhermitew.hpp\"\n#include \"spectral/basis/toolbox/spectral_basis.hpp\"\n#include \"spectral/laguerren_ks.hpp\"\n#include \"spectral/eval_handlers.hpp\"\n#include \"spectral/pl_radial_eval.hpp\"\n\n\nnamespace boltzmann {\nnamespace detail {\n\n/**\n * @brief sort *polar* elements by `k`\n */\nstruct CMP\n{\n  template <typename E>\n  bool operator()(const E &e1, const E &e2) const\n  {\n    // typedef typename boost::mpl::at_c<typename E::types_t,0>::type fa_type;\n    typedef typename boost::mpl::at_c<typename E::types_t, 1>::type fr_type;\n\n    typename E::Acc::template get<fr_type> fr_accessor;\n    // typename E::Acc::template get<fa_type> fa_accessor;\n\n    const auto &idR1 = fr_accessor(e1).get_id();\n    const auto &idR2 = fr_accessor(e2).get_id();\n\n    return std::tie(idR1.k, idR1.j) < std::tie(idR2.k, idR2.j);\n  }\n};\n\n}  // end namespace detail\n\ntemplate <typename PolarBasis, typename HermiteBasis>\nclass Polar2Hermite\n{\n public:\n  Polar2Hermite(const PolarBasis &polar_basis, const HermiteBasis &hermite_basis);\n#ifndef NOHDF5\n  void exportmat(const std::string &fname) const;\n#endif\n\n  void to_hermite(std::vector<double> &dst, const std::vector<double> &src) const;\n\n  template <typename DERIVED1, typename DERIVED2>\n  void to_hermite(Eigen::DenseBase<DERIVED1> &dst, const Eigen::DenseBase<DERIVED2> &src) const;\n\n  template <typename DERIVED1, typename DERIVED2>\n  void to_hermite_T(Eigen::DenseBase<DERIVED1> &dst, const Eigen::DenseBase<DERIVED2> &src) const;\n\n  void to_polar(std::vector<double> &dst, const std::vector<double> &src) const;\n\n  template <typename DERIVED1, typename DERIVED2>\n  void to_polar(Eigen::DenseBase<DERIVED1> &dst, const Eigen::DenseBase<DERIVED2> &src) const;\n\n  void to_polar(double *dst, const double *src) const;\n\n  const Eigen::MatrixXd &get_mat(int k) const;\n\n private:\n  /// Transformation matrices for each polynomial degree k\n  std::vector<Eigen::MatrixXd> tmatrices_;\n  std::vector<unsigned int> offsets_;\n  /// Permutation matrix for polar degrees of freedom\n  Eigen::SparseMatrix<double> P_;\n\n  Eigen::VectorXd polar_mass_m_;\n  thread_local static ::ArrayBuffer<> buf_;\n};\n\ntemplate <typename PolarBasis, typename HermiteBasis>\nthread_local ::ArrayBuffer<> Polar2Hermite<PolarBasis, HermiteBasis>::buf_;\n\n\ntemplate <typename PolarBasis, typename HermiteBasis>\nPolar2Hermite<PolarBasis, HermiteBasis>::Polar2Hermite(const PolarBasis &polar_basis,\n                                                       const HermiteBasis &hermite_basis)\n{\n  BOOST_VERIFY(polar_basis.n_dofs() == hermite_basis.n_dofs());\n  int K = spectral::get_max_k(polar_basis);\n  const unsigned int qpts1d = std::max(40, 2 * (K + 1));\n  // initialize quadrature\n  QHermiteW quad(1.0, qpts1d);\n\n  // typedef std::array<double, 2> point_t;\n  typedef boost::multi_array<double, 2> array2d;\n  // typedef boost::multi_array<point_t, 2> array2dpts;\n  array2d W(boost::extents[qpts1d][qpts1d]);\n  // quad. nodes in cartesian coordinates\n  array2d X(boost::extents[qpts1d][qpts1d]);\n  array2d Y(boost::extents[qpts1d][qpts1d]);\n  array2d R(boost::extents[qpts1d][qpts1d]);\n  array2d PHI(boost::extents[qpts1d][qpts1d]);\n\n  for (unsigned int i = 0; i < qpts1d; ++i) {\n    const double x = quad.pts(i);\n    for (unsigned int j = 0; j < qpts1d; ++j) {\n      const double y = quad.pts(j);\n      X[i][j] = x;\n      Y[i][j] = y;\n      W[i][j] = quad.wts(i) * quad.wts(j);\n      PHI[i][j] = std::atan2(y, x);\n      R[i][j] = std::sqrt(y * y + x * x);\n    }\n  }\n  const unsigned int nq = qpts1d * qpts1d;\n\n  //  ...\n  PolarBasis basis_k(polar_basis);\n  basis_k.sort(detail::CMP());\n\n  tmatrices_.resize(K + 1);\n  P_.resize(polar_basis.n_dofs(), polar_basis.n_dofs());\n\n  // evaluate basis functions at quadrature points\n  RDTSCTimer timer;\n  timer.start();\n  LaguerreNKS<double> L(K);\n  unsigned int Rlen = R.shape()[0] * R.shape()[1];\n  L.compute(R.data(), Rlen, 0.5);\n\n  typedef typename PolarBasis::elem_t polar_elem_t;\n  typedef typename boost::mpl::at_c<typename polar_elem_t::types_t, 1>::type radial_elem_t;\n  typedef typename boost::mpl::at_c<typename polar_elem_t::types_t, 0>::type ang_elem_t;\n  typename polar_elem_t::Acc::template get<radial_elem_t> get_rad;\n  typename polar_elem_t::Acc::template get<ang_elem_t> get_ang;\n\n  typedef typename HermiteBasis::elem_t herm_elem_t;\n  typedef typename boost::mpl::at_c<typename herm_elem_t::types_t, 0>::type hx_t;\n  typedef typename boost::mpl::at_c<typename herm_elem_t::types_t, 1>::type hy_t;\n\n  typename herm_elem_t::Acc::template get<hx_t> get_hx;\n  typename herm_elem_t::Acc::template get<hy_t> get_hy;\n\n  // HermiteEvalHandler2d<HermiteNW<double>, herm_elem_t> heval(H);\n  auto heval = hermite_evaluator2d<>::make(hermite_basis, quad.pts());\n  PLRadialEval<LaguerreNKS<double>, polar_elem_t> leval(L);\n  // permutation matrix entries\n  std::vector<unsigned int> p_loc(polar_basis.n_dofs());\n  // update offset vector\n  unsigned int offset = 0;\n  offsets_.resize(K + 2);\n  // ----------------------------------------------------\n  // loop over block-diagonal matrix and compute offsets\n  // ----------------------------------------------------\n  offsets_[0] = 0;\n  for (int k = 0; k <= K; ++k) {\n    std::function<bool(const polar_elem_t &)> pred = [&](const polar_elem_t &e) {\n      return (get_rad(e).get_id().k == k);\n    };\n    auto range = filtered_range(basis_k.begin(), basis_k.end(), pred);\n\n    // collect polar elements of polynomial degree k\n    std::vector<polar_elem_t> polar_elems;\n    for (auto it = std::get<0>(range); it != std::get<1>(range); ++it) {\n      polar_elems.push_back(*it);\n    }\n    offset += polar_elems.size();\n    offsets_[k + 1] = offset;\n  }\n\n  // --------------------------------------\n  // Compute transformation matrix entries\n  // --------------------------------------\n  timer.start();\n#pragma omp parallel for\n  // (* load-balancing will be rather poor *)\n  for (int k = 0; k <= K; ++k) {\n    std::function<bool(const polar_elem_t &)> pred = [&](const polar_elem_t &e) {\n      return (get_rad(e).get_id().k == k);\n    };\n    auto range = filtered_range(basis_k.begin(), basis_k.end(), pred);\n\n    // collect polar elements of polynomial degree k\n    std::vector<polar_elem_t> polar_elems;\n    for (auto it = std::get<0>(range); it != std::get<1>(range); ++it) {\n      polar_elems.push_back(*it);\n    }\n\n    // collect hermite elements of polynomial degree k\n    std::vector<herm_elem_t> herm_elems;\n    std::function<bool(const herm_elem_t &)> pred2 = [&](const herm_elem_t &e) {\n      return (get_hx(e).get_id().k + get_hy(e).get_id().k == k);\n    };\n    auto range_herm = filtered_range(hermite_basis.begin(), hermite_basis.end(), pred2);\n    for (auto it = std::get<0>(range_herm); it != std::get<1>(range_herm); ++it) {\n      herm_elems.push_back(*it);\n    }\n\n    assert(herm_elems.size() == polar_elems.size());\n\n    // init matrix\n    auto &Mk = tmatrices_[k];\n    unsigned int nk = herm_elems.size();\n    Mk.resize(nk, nk);\n\n    // quadrature nodes and weights\n    const double *w = W.origin();\n    // const double* x = X.origin();\n    // const double* y = Y.origin();\n    // const double* r = R.origin();\n    const double *phi = PHI.origin();\n\n    for (auto itp = polar_elems.begin(); itp != polar_elems.end(); ++itp) {\n      // create permutation matrix\n      unsigned int dofx = polar_basis.get_dof_index(itp->get_id());\n      unsigned int dofy = basis_k.get_dof_index(itp->get_id());\n      p_loc[dofy] = dofx;  // permutation\n      //      const unsigned int j = get_rad(*itp).get_id().j;\n      const unsigned int k = get_rad(*itp).get_id().k;\n\n      for (auto ith = herm_elems.begin(); ith != herm_elems.end(); ++ith) {\n        unsigned int dofy2 = hermite_basis.get_dof_index(ith->get_id());  // index\n        // quadrature\n        double val = 0;\n        for (unsigned int q = 0; q < nq; ++q) {\n          // const double rloc = r[q];\n          val += (w[q] * leval(*itp, q) * get_ang(*itp).evaluate(phi[q]) *\n                  heval(*ith, q / qpts1d, q % qpts1d));\n        }\n        Mk(dofy2 - offsets_[k], dofy - offsets_[k]) = val;\n      }\n    }\n  }\n\n  for (unsigned int dofy = 0; dofy < p_loc.size(); ++dofy) {\n    P_.insert(dofy, p_loc[dofy]) = 1;\n  }\n  P_.makeCompressed();\n\n  // prepare diagonal entries of mass matrix\n  const double PI = boost::math::constants::pi<double>();\n  // initialize polar mass m\n  const unsigned int N = basis_k.n_dofs();\n  polar_mass_m_ = Eigen::VectorXd(N);\n  for (unsigned int i = 0; i < N; ++i) {\n    const auto &elem = basis_k.get_elem(i);\n    if (get_ang(elem).get_id().l == 0)\n      polar_mass_m_[i] = PI;\n    else\n      polar_mass_m_[i] = PI / 2;\n  }\n}\n\n// ---------------------------------------------------------------------\ntemplate <typename PolarBasis, typename HermiteBasis>\nvoid\nPolar2Hermite<PolarBasis, HermiteBasis>::to_hermite(std::vector<double> &dst,\n                                                    const std::vector<double> &src) const\n{\n  assert(dst.size() == src.size());\n  assert(src.size() == (unsigned int)P_.cols());\n\n  typedef Eigen::Map<Eigen::VectorXd> vec_t;\n  typedef Eigen::Map<const Eigen::VectorXd> cvec_t;\n\n  cvec_t vsrc(src.data(), src.size());\n  vec_t vdst(dst.data(), dst.size());\n\n  this->to_hermite(vdst, vsrc);\n}\n\n// ----------------------------------------------------------------------\ntemplate <typename PolarBasis, typename HermiteBasis>\ntemplate <typename DERIVED1, typename DERIVED2>\nvoid\nPolar2Hermite<PolarBasis, HermiteBasis>::to_hermite(Eigen::DenseBase<DERIVED1> &dst,\n                                                    const Eigen::DenseBase<DERIVED2> &src) const\n{\n  const int K = tmatrices_.size();\n  const int N = offsets_[K];\n\n  BOOST_ASSERT(dst.size() == N);\n  BOOST_ASSERT(src.size() == N);\n  auto vpsrc = buf_.get<Eigen::VectorXd>(N);\n\n  // TODO, this is slow\n  vpsrc = P_ * src.derived();\n\n  for (int k = 0; k < tmatrices_.size(); ++k) {\n    const unsigned int blocksize = offsets_[k + 1] - offsets_[k];\n    dst.segment(offsets_[k], blocksize) = tmatrices_[k] * vpsrc.segment(offsets_[k], blocksize);\n  }\n}\n\n\ntemplate <typename PolarBasis, typename HermiteBasis>\ntemplate <typename DERIVED1, typename DERIVED2>\nvoid\nPolar2Hermite<PolarBasis, HermiteBasis>::to_hermite_T(Eigen::DenseBase<DERIVED1> &dst,\n                                                      const Eigen::DenseBase<DERIVED2> &src) const\n{\n  assert(dst.size() == src.size());\n  assert(src.size() == (unsigned int)P_.cols());\n  typedef Eigen::Map<Eigen::VectorXd> vec_t;\n  typedef Eigen::Map<const Eigen::VectorXd> cvec_t;\n\n  const int K = tmatrices_.size();\n  const int N = offsets_[K];\n\n  auto vpsrc = buf_.get<Eigen::VectorXd>(N);\n\n  for (int k = 0; k < tmatrices_.size(); ++k) {\n    const unsigned int blocksize = offsets_[k + 1] - offsets_[k];\n    vpsrc.segment(offsets_[k], blocksize) =\n        tmatrices_[k].transpose() * src.segment(offsets_[k], blocksize);\n  }\n\n  dst = P_.transpose() * vpsrc;\n}\n\n\ntemplate <typename PolarBasis, typename HermiteBasis>\nvoid\nPolar2Hermite<PolarBasis, HermiteBasis>::to_polar(std::vector<double> &dst,\n                                                  const std::vector<double> &src) const\n{\n  assert(dst.size() == src.size());\n  assert(src.size() == (unsigned int)P_.cols());\n  typedef Eigen::Map<Eigen::VectorXd> vec_t;\n  typedef Eigen::Map<const Eigen::VectorXd> cvec_t;\n  vec_t vdst(dst.data(), dst.size());\n  cvec_t vsrc(src.data(), src.size());\n\n  this->to_polar(vdst, vsrc);\n}\n\n\ntemplate <typename PolarBasis, typename HermiteBasis>\ntemplate <typename DERIVED1, typename DERIVED2>\nvoid\nPolar2Hermite<PolarBasis, HermiteBasis>::to_polar(Eigen::DenseBase<DERIVED1> &dst,\n                                                  const Eigen::DenseBase<DERIVED2> &src) const\n{\n  const int K = tmatrices_.size();\n  const int N = offsets_[K];\n\n  BOOST_ASSERT(dst.size() == N);\n  BOOST_ASSERT(src.size() == N);\n\n  // TODO: use buffer memory instead\n  auto vpsrc = buf_.get<Eigen::VectorXd>(N);\n  for (int k = 0; k < tmatrices_.size(); ++k) {\n    const unsigned int blocksize = offsets_[k + 1] - offsets_[k];\n    vpsrc.segment(offsets_[k], blocksize) =\n        tmatrices_[k].transpose() * src.segment(offsets_[k], blocksize);\n  }\n  vpsrc = vpsrc.array() / polar_mass_m_.array();\n\n  dst = P_.transpose() * vpsrc;\n}\n\n\ntemplate <typename PolarBasis, typename HermiteBasis>\nconst Eigen::MatrixXd &\nPolar2Hermite<PolarBasis, HermiteBasis>::get_mat(int k) const\n{\n  BOOST_ASSERT(k < tmatrices_.size());\n  return tmatrices_[k];\n}\n\n#ifndef NOHDF5\ntemplate <typename PolarBasis, typename HermiteBasis>\nvoid\nPolar2Hermite<PolarBasis, HermiteBasis>::exportmat(const std::string &fname) const\n{\n  hid_t h5f = H5Fcreate(fname.c_str(), H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);\n\n  eigen2hdf::save_sparse(h5f, \"P\", P_);\n  for (unsigned int k = 0; k < tmatrices_.size(); ++k) {\n    eigen2hdf::save(h5f, std::to_string(k), tmatrices_[k]);\n  }\n  H5Fclose(h5f);\n}\n#endif\n\n}  // end namespace boltzmann\n", "meta": {"hexsha": "e548ceb1f477010e4f96224463741fd6fd7e5d25", "size": 13373, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "spectral/polar_to_hermite.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/polar_to_hermite.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/polar_to_hermite.hpp", "max_forks_repo_name": "simonpp/2dRidgeletBTE", "max_forks_repo_head_hexsha": "5d08cbb5c57fc276c7a528f128615d23c37ef6a0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-11-08T03:15:56.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-08T03:15:56.000Z", "avg_line_length": 33.5162907268, "max_line_length": 98, "alphanum_fraction": 0.644657145, "num_tokens": 3931, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527869325346, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.48222106851578955}}
{"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_CBRT_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_CBRT_HPP_INCLUDED\n#include <boost/simd/function/std.hpp>\n#include <boost/simd/function/fast.hpp>\n\n#ifndef BOOST_SIMD_NO_INFINITIES\n#include <boost/simd/constant/inf.hpp>\n#endif\n#ifndef BOOST_SIMD_NO_DENORMALS\n#include <boost/simd/constant/smallestposval.hpp>\n#include <boost/simd/constant/twotomnmbo_3.hpp>\n#include <boost/simd/constant/twotonmb.hpp>\n#endif\n#include <boost/simd/function/horn.hpp>\n#include <boost/simd/constant/constant.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/third.hpp>\n#include <boost/simd/constant/three.hpp>\n#include <boost/simd/constant/two.hpp>\n#include <boost/simd/function/abs.hpp>\n#include <boost/simd/function/bitofsign.hpp>\n#include <boost/simd/function/bitwise_or.hpp>\n#include <boost/simd/function/frexp.hpp>\n#include <boost/simd/function/is_gez.hpp>\n#include <boost/simd/function/ldexp.hpp>\n#include <boost/simd/function/negate.hpp>\n#include <boost/simd/function/sqr.hpp>\n#include <boost/simd/detail/dispatch/function/overload.hpp>\n#include <boost/simd/detail/dispatch/meta/as_integer.hpp>\n#include <boost/config.hpp>\n#include <cmath>\n#include <tuple>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  namespace bs = boost::simd;\n\n  BOOST_DISPATCH_OVERLOAD ( cbrt_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_< bd::double_<A0> >\n                          )\n  {\n\n\n    inline A0 operator() ( A0 a0) const BOOST_NOEXCEPT\n    {\n      A0 z =  bs::abs(a0);\n    #ifndef BOOST_SIMD_NO_INFINITIES\n      if (z == bs::Inf<A0>() || (z == 0)) return a0;\n    #else\n      if (z == 0) return a0;\n    #endif\n    #ifndef BOOST_SIMD_NO_DENORMALS\n      A0 f = One<A0>();\n      if (z < Smallestposval<A0>())\n      {\n        z *= Twotonmb<A0>();\n        f  = Twotomnmbo_3<A0>();\n      }\n    #endif\n      const A0 CBRT2  = Constant< A0, 0x3ff428a2f98d728bll> ();\n      const A0 CBRT4  = Constant< A0, 0x3ff965fea53d6e3dll> ();\n      const A0 CBRT2I = Constant< A0, 0x3fe965fea53d6e3dll> ();\n      const A0 CBRT4I = Constant< A0, 0x3fe428a2f98d728bll> ();\n      using i_t = bd::as_integer_t<A0, signed>;\n      i_t e;\n      A0 x;\n      std::tie(x, e) = fast_(frexp)(z);\n      x = horn<A0,\n               0x3fd9c0c12122a4fell,\n               0x3ff23d6ee505873all,\n               0xbfee8a4ca3ba37b8ll,\n               0x3fe17e1fc7e59d58ll,\n               0xbfc13c93386fdff6ll\n               > (x);\n      const auto flag = is_gez(e);\n      i_t e1 =  bs::abs(e);\n      i_t rem = e1;\n      e1 /= Three<i_t>();\n      rem -= e1*Three<i_t>();\n      e =  negate(e1, e);\n      const A0 cbrt2 = flag ? CBRT2 : CBRT2I;\n      const A0 cbrt4 = flag ? CBRT4 : CBRT4I;\n      A0 fact = (rem == One<i_t>()) ? cbrt2: One<A0>();\n      fact = (rem == Two<i_t>() ? cbrt4 : fact);\n      x = fast_(ldexp)(x*fact, e);\n      x -= (x-z/sqr(x))*Third<A0>();\n      x -= (x-z/sqr(x))*Third<A0>(); //two newton passes\n    #ifndef BOOST_SIMD_NO_DENORMALS\n      return bitwise_or(x, bitofsign(a0))*f;\n    #else\n      return bitwise_or(x, bitofsign(a0));\n    #endif\n    }\n  };\n  BOOST_DISPATCH_OVERLOAD ( cbrt_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_< bd::single_<A0> >\n                          )\n  {\n    inline A0 operator() ( A0 a0) const BOOST_NOEXCEPT\n    {\n      A0 z =  bs::abs(a0);\n    #ifndef BOOST_SIMD_NO_INFINITIES\n      if (z == bs::Inf<A0>() || (z == 0)) return a0;\n    #else\n      if  (z == 0) return a0;\n    #endif\n    #ifndef BOOST_SIMD_NO_DENORMALS\n      A0 f = One<A0>();\n      if (z < Smallestposval<A0>())\n      {\n        z *= Twotonmb<A0>();\n        f = Twotomnmbo_3<A0>();\n      }\n    #endif\n      const A0 CBRT2  = Constant< A0, 0x3fa14518> ();\n      const A0 CBRT4  = Constant< A0, 0x3fcb2ff5> ();\n      const A0 CBRT2I = Constant< A0, 0x3f4b2ff5> ();\n      const A0 CBRT4I = Constant< A0, 0x3f214518> ();\n      using i_t = bd::as_integer_t<A0, signed>;\n      i_t e;\n      A0 x;\n      std::tie(x, e)= fast_(frexp)(z);\n      x = horn<A0,\n               0x3ece0609,\n               0x3f91eb77,\n               0xbf745265,\n               0x3f0bf0fe,\n               0xbe09e49a\n               > (x);\n      const auto flag = is_gez(e);\n      i_t e1 =  bs::abs(e);\n      i_t rem = e1;\n      e1 /= Three<i_t>();\n      rem -= e1*Three<i_t>();\n      e =  negate(e1, e);\n\n      const A0 cbrt2 = flag ? CBRT2 : CBRT2I;\n      const A0 cbrt4 = flag ? CBRT4 : CBRT4I;\n      A0 fact = (rem ==  One<i_t>()) ? cbrt2 : One<A0>();\n      fact = (rem == Two<i_t>()) ? cbrt4 : fact;\n      x = fast_(ldexp)(x*fact, e);\n      x -= (x-z/sqr(x))*Third<A0>();\n    #ifndef BOOST_SIMD_NO_DENORMALS\n      return bitwise_or(x, bitofsign(a0))*f;\n    #else\n      return bitwise_or(x, bitofsign(a0));\n    #endif\n    }\n  };\n  BOOST_DISPATCH_OVERLOAD ( cbrt_\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::cbrt(a0);\n    }\n  };\n} } }\n\n#endif\n", "meta": {"hexsha": "907cbb0c4bad31534dcc538cf449e307e92d8ec4", "size": 5700, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/scalar/function/cbrt.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/cbrt.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/cbrt.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": 31.6666666667, "max_line_length": 100, "alphanum_fraction": 0.5470175439, "num_tokens": 1764, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.857768108626046, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4822170738788197}}
{"text": "#include \"nearest_neighbour_search.hpp\"\n\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Search_traits_3.h>\n#include <CGAL/Search_traits_adapter.h>\n#include <CGAL/Orthogonal_k_neighbor_search.h>\n#include <CGAL/property_map.h>\n#include <boost/iterator/zip_iterator.hpp>\n#include <utility>\n\nnamespace kinect {\n  \nNearestNeighbourSearch::NearestNeighbourSearch(const std::vector<sample_t>& samples)\n :m_samples(samples)\n ,m_tree()\n{\n  std::vector<Point_3> points;\n  std::vector<size_t> indices;\n\n  for(std::size_t i = 0; i < samples.size(); ++i){\n    points.emplace_back(samples[i]);\n    indices.emplace_back(i);\n  }\n\n  m_tree = std::unique_ptr<Tree>{new Tree(\n    boost::make_zip_iterator(boost::make_tuple(points.begin(), indices.begin())),\n    boost::make_zip_iterator(boost::make_tuple(points.end(), indices.end()))  \n  )};\n}\n\nstd::vector<sample_t>\nNearestNeighbourSearch::search(glm::fvec3 const& curr_point, unsigned num_neighbours) const {\n\n  K_neighbor_search search(*(m_tree.get()), Point_3{curr_point.x, curr_point.y, curr_point.z}, num_neighbours);\n\n  std::vector<sample_t> result;\n  for(K_neighbor_search::iterator it = search.begin(); it != search.end(); it++) {\n    result.emplace_back(m_samples[boost::get<1>(it->first)]);\n  }\n\n  return result;\n}\n\n}", "meta": {"hexsha": "d0c816f3e69efc3879a0f3b14dce5a4a2b2bdee3", "size": 1292, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "framework/calibration/nearest_neighbour_search.cpp", "max_stars_repo_name": "steppobeck/rgbd-recon", "max_stars_repo_head_hexsha": "171a8336c8e3ba52a1b187b73544338fdd3c9285", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2016-09-03T05:12:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T15:52:33.000Z", "max_issues_repo_path": "framework/calibration/nearest_neighbour_search.cpp", "max_issues_repo_name": "3d-scan/rgbd-recon", "max_issues_repo_head_hexsha": "c4a5614eaa55dd93c74da70d6fb3d813d74f2903", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-05-04T09:06:29.000Z", "max_issues_repo_issues_event_max_datetime": "2016-05-04T09:06:29.000Z", "max_forks_repo_path": "framework/calibration/nearest_neighbour_search.cpp", "max_forks_repo_name": "3d-scan/rgbd-recon", "max_forks_repo_head_hexsha": "c4a5614eaa55dd93c74da70d6fb3d813d74f2903", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2016-04-20T13:58:50.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-09T15:47:26.000Z", "avg_line_length": 29.3636363636, "max_line_length": 111, "alphanum_fraction": 0.7352941176, "num_tokens": 333, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182187, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4822170677466955}}
{"text": "#include <armadillo>\n#include <json.hpp>\n#include <iostream>\n#include <ForwardBackward.hpp>\n#include <HSMM.hpp>\n#include <memory>\n\nusing namespace arma;\nusing namespace hsmm;\nusing namespace std;\nusing json = nlohmann::json;\n\nint main() {\n    int ndurations = 4;\n    int min_duration = 4;\n    mat transition = {{0.0, 0.1, 0.4, 0.5},\n                      {0.3, 0.0, 0.6, 0.1},\n                      {0.2, 0.2, 0.0, 0.6},\n                      {0.4, 0.4, 0.2, 0.0}};\n    int nstates = transition.n_rows;\n    vec pi(nstates, fill::eye);\n    pi.fill(1.0/nstates);\n    // mat durations(nstates, ndurations, fill::eye);\n    mat durations =  {{0.0, 0.1, 0.4, 0.5},\n                      {0.3, 0.0, 0.6, 0.1},\n                      {0.2, 0.2, 0.0, 0.6},\n                      {0.4, 0.4, 0.2, 0.0}};\n\n    // Instantiating the emission process.\n    vec means = {0, 5, 10, 15};\n    vec std_devs =  {0.5, 1.0, 0.1, 2.0};\n    shared_ptr<AbstractEmission> ptr_emission(new DummyGaussianEmission(\n            means, std_devs));\n\n    // Multivariate emission.\n    mat mult_means(nstates, 2, fill::zeros);\n    for(int i = 0; i < nstates; i++)\n        mult_means.row(i).fill(i);\n    shared_ptr<AbstractEmission> ptr_mult_emission(\n            new DummyMultivariateGaussianEmission(mult_means, 0.1));\n\n    // Instantiating the HSMM.\n    HSMM dhsmm(ptr_emission, transition, pi, durations, min_duration);\n\n    ivec hiddenStates, hiddenDurations;\n    int nSampledSegments = 50;\n    field<mat> samples = dhsmm.sampleSegments(nSampledSegments, hiddenStates,\n            hiddenDurations);\n    int nobs = samples.n_elem;\n\n    cout << \"Generated samples\" << endl;\n    // cout << samples << endl;\n    cout << \"Generated states and durations\" << endl;\n    cout << join_horiz(hiddenStates, hiddenDurations) << endl;\n\n    mat alpha(nstates, nobs, fill::zeros);\n    mat beta(nstates, nobs, fill::zeros);\n    mat alpha_s(nstates, nobs, fill::zeros);\n    mat beta_s(nstates, nobs, fill::zeros);\n    vec beta_s_0(nstates, fill::zeros);\n    cube eta(nstates, ndurations, nobs, fill::zeros);\n    cube zeta(nstates, nstates, nobs - 1, fill::zeros);\n    cube logpdf = dhsmm.computeEmissionsLogLikelihood(samples);\n    Labels obs_segments;\n    logsFB(log(transition), log(pi), log(durations), logpdf, obs_segments,\n            alpha, beta, alpha_s, beta_s, beta_s_0, eta, zeta, min_duration,\n            nobs);\n    mat compare_alpha = exp(alpha);\n    mat compare_alpha_s = exp(alpha_s);\n    mat compare_beta = exp(beta);\n    mat compare_beta_s = exp(beta_s);\n    cube compare_eta = exp(eta);\n    mat compare_beta_s_0 = exp(beta_s_0);\n    cube pdf = dhsmm.computeEmissionsLikelihood(samples);\n    FB(transition, pi, durations, pdf, obs_segments, alpha, beta, alpha_s,\n            beta_s, beta_s_0, eta, min_duration, nobs);\n\n    cout << \"TEST\" << endl;\n    mat a = compare_beta - beta;\n    mat b = compare_beta_s - beta_s;\n    cube c = compare_eta - eta;\n    mat d = compare_beta_s_0 - beta_s_0;\n    mat e = compare_alpha - alpha;\n    mat f = compare_alpha_s - alpha_s;\n    cout << a.min() << \" \" << a.max() << endl;\n    cout << b.min() << \" \" << b.max() << endl;\n    cout << c.min() << \" \" << c.max() << endl;\n    cout << d.min() << \" \" << d.max() << endl;\n    cout << e.min() << \" \" << e.max() << endl;\n    cout << f.min() << \" \" << f.max() << endl;\n\n    cout << \"Sums rows\" << endl;\n    cout << sum(alpha, 1) << endl;\n    cout << sum(alpha_s, 1) << endl;\n    cout << sum(beta, 1) << endl;\n    cout << sum(beta_s, 1) << endl;\n\n    imat psi_duration(nstates, nobs, fill::zeros);\n    imat psi_state(nstates, nobs, fill::zeros);\n    mat delta(nstates, nobs, fill::zeros);\n    Viterbi(transition, pi, durations, logpdf, delta, psi_duration, psi_state,\n            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\n    cout << \"Viterbi states and durations\" << endl;\n    cout << join_horiz(viterbiStates, viterbiDurations) << endl;\n\n    // Debug\n    int differences = 0;\n    if (viterbiStates.n_elem == hiddenStates.n_elem) {\n        for(int t = 0; t < viterbiStates.n_elem; t++)\n            if (hiddenStates(t) != viterbiStates(t))\n                differences++;\n        cout << \" Differences: \" << differences << endl;\n    }\n    else\n        cout << \"The dimensions don't match.\" << endl;\n\n    // Generating multiple synthetic sequences.\n    int nseq = 10;\n    int nsegments = 100;\n    field<field<mat>> mobs;\n    field<ivec> mhs, mdur;\n    mobs = dhsmm.sampleMultipleSequences(nseq, nsegments, mhs, mdur);\n\n    // Initializing uniformly the transitions, initial state pmf and durations.\n    transition.fill(1.0/(nstates-1));\n    transition.diag().zeros();  // No self-loops.\n    dhsmm.setTransition(transition);\n    pi.fill(1.0/nstates);\n    dhsmm.setPi(pi);\n    durations.fill(1.0/ndurations);\n    dhsmm.setDuration(durations);\n\n    // Resetting emission parameters.\n    vec new_means = {0.1, 0.2, 0.3, 30};\n    vec new_std_devs = ones<vec>(nstates) * 10;\n    shared_ptr<AbstractEmission> init_emission(new DummyGaussianEmission(\n            new_means, new_std_devs));\n    dhsmm.setEmission(init_emission);\n\n    // Testing the learning algorithm.\n    dhsmm.fit(mobs, 100, 1e-10);\n\n    vec best_pi(nstates, fill::zeros);\n    for(int s = 0; s < nseq; s++)\n        best_pi(mhs(s)(0))++;\n    best_pi /= nseq;\n    cout << \"Best initial state pmf we can aim at:\" << endl << best_pi << endl;\n\n    cout << \"Learnt pi:\" << endl;\n    cout << dhsmm.pi_ << endl;\n\n    cout << \"Best transition matrix we can aim at:\" << endl;\n    mat prueba(nstates, nstates, fill::zeros);\n    for(int s = 0; s < nseq; s++) {\n        ivec& hiddenStates = mhs(s);\n        for(int i = 0; i < hiddenStates.n_elem - 1; i++)\n            prueba(hiddenStates(i), hiddenStates(i + 1))++;\n    }\n    mat pruebasum = sum(prueba, 1);\n    for(int i = 0; i < nstates; i++)\n        prueba.row(i) /= pruebasum(i);\n    cout << prueba << endl;\n\n    cout << \"Learnt matrix:\" << endl;\n    cout << dhsmm.transition_ << endl;\n\n    cout << \"Best duration matrix we can aim at:\" << endl;\n    mat emp_durations(nstates, ndurations, fill::zeros);\n    for(int s = 0; s < nseq; s++) {\n        ivec& hiddenStates = mhs(s);\n        ivec& hiddenDurations = mdur(s);\n        for(int i = 0; i < hiddenStates.n_elem; i++)\n            emp_durations(hiddenStates(i), hiddenDurations(i) - min_duration)++;\n    }\n    mat emp_durations_sum = sum(emp_durations, 1);\n    for(int i = 0; i < nstates; i++)\n        emp_durations.row(i) /= emp_durations_sum(i);\n    cout << emp_durations << endl;\n    cout << \"Learnt durations:\" << endl;\n    cout << dhsmm.duration_ << endl;\n\n    cout << \"Learnt parameters (json)\" << endl;\n    json params = dhsmm.to_stream();\n    cout << params.dump(4) << endl;\n    return 0;\n}\n", "meta": {"hexsha": "6441b8e3b6f67077d0a95752d376542959eaba0e", "size": 6890, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/dummy_hsmm_example.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/dummy_hsmm_example.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/dummy_hsmm_example.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": 35.6994818653, "max_line_length": 80, "alphanum_fraction": 0.5986937591, "num_tokens": 2081, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479467, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.4822147682413095}}
{"text": "/*\n * Copyright (c) 2011, Laurent Kneip, ETH Zurich\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 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 ETH ZURICH 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 * P3P.cpp\n *\n *  Created on: Nov 2, 2010\n *      Author: Laurent Kneip\n * Description: Compute the absolute pose of a camera using three 3D-to-2D correspondences\n *   Reference: A Novel Parametrization of the P3P-Problem for a Direct Computation of\n *              Absolute Camera Position and Orientation\n *\n *       Input: feature_vectors: 3x3 matrix with UNITARY feature vectors (each column is a vector)\n *              world_points: 3x3 matrix with corresponding 3D world points (each column is a point)\n *              solutions: 3x16 matrix that will contain the solutions\n *                         form: [ 3x1 position(solution1) 3x3 orientation(solution1) 3x1 position(solution2) 3x3 orientation(solution2) ... ]\n *                         the obtained orientation matrices are defined as transforming points from the cam to the world frame\n *      Output: int: 0 if correct execution\n *                  -1 if world points aligned\n */\n\n#include \"p3p/P3p.h\"\n\n#include <stdlib.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <math.h>\n#include <complex>\n#include <vector>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\nnamespace p3p_kneip {\n\nint P3PComputePoses(const std::vector<Eigen::Vector3d>& feature_vectors,\n                    const std::vector<Eigen::Vector3d>& world_points,\n                    std::vector<Eigen::Matrix3d>* rotations,\n                    std::vector<Eigen::Vector3d>* camera_centers) {\n  // Extraction of world points\n  Eigen::Vector3d P1 = world_points[0];\n  Eigen::Vector3d P2 = world_points[1];\n  Eigen::Vector3d P3 = world_points[2];\n\n  // Verification that world points are not colinear\n\n  Eigen::Vector3d temp1 = P2 - P1;\n  Eigen::Vector3d temp2 = P3 - P1;\n\n  if (temp1.cross(temp2).squaredNorm() == 0.0)\n    return -1;\n\n  // Extraction of feature vectors\n  Eigen::Vector3d f1 = feature_vectors[0].normalized();\n  Eigen::Vector3d f2 = feature_vectors[1].normalized();\n  Eigen::Vector3d f3 = feature_vectors[2].normalized();\n\n  // Creation of intermediate camera frame\n\n  Eigen::Vector3d e1 = f1;\n  Eigen::Vector3d e3 = f1.cross(f2);\n  e3.normalize();\n  Eigen::Vector3d e2 = e3.cross(e1);\n\n  Eigen::Matrix3d T;\n  T << e1.transpose(), e2.transpose(), e3.transpose();\n\n  f3 = T * f3;\n\n  // Reinforce that f3[2] > 0 for having theta in [0;pi]\n\n  if (f3(2) > 0.0) {\n    f1 = feature_vectors[1];\n    f2 = feature_vectors[0];\n    f3 = feature_vectors[2];\n\n    e1 = f1;\n    e3 = f1.cross(f2);\n    e3.normalize();\n    e2 = e3.cross(e1);\n\n    T << e1.transpose(), e2.transpose(), e3.transpose();\n\n    f3 = T * f3;\n\n    P1 = world_points[1];\n    P2 = world_points[0];\n    P3 = world_points[2];\n  }\n\n  // Creation of intermediate world frame\n\n  Eigen::Vector3d n1 = P2 - P1;\n  n1.normalize();\n  Eigen::Vector3d n3 = n1.cross(P3 - P1);\n  n3.normalize();\n  Eigen::Vector3d n2 = n3.cross(n1);\n\n  Eigen::Matrix3d N;\n  N << n1.transpose(), n2.transpose(), n3.transpose();\n\n  // Extraction of known parameters\n\n  P3 = N * (P3 - P1);\n\n  double d_12 = (P2 - P1).norm();\n  double f_1 = f3(0) / f3(2);\n  double f_2 = f3(1) / f3(2);\n  double p_1 = P3(0);\n  double p_2 = P3(1);\n\n  double cos_beta = f1.dot(f2);\n  double b = 1.0 / (1.0 - (cos_beta * cos_beta)) - 1.0;\n\n  if (cos_beta < 0.0)\n    b = -sqrt(b);\n  else\n    b = sqrt(b);\n\n  // Definition of temporary variables for avoiding multiple computation\n\n  double f_1_pw2 = f_1 * f_1;\n  double f_2_pw2 = f_2 * f_2;\n  double p_1_pw2 = p_1 * p_1;\n  double p_1_pw3 = p_1_pw2 * p_1;\n  double p_1_pw4 = p_1_pw3 * p_1;\n  double p_2_pw2 = p_2 * p_2;\n  double p_2_pw3 = p_2_pw2 * p_2;\n  double p_2_pw4 = p_2_pw3 * p_2;\n  double d_12_pw2 = d_12 * d_12;\n  double b_pw2 = b * b;\n\n  // Computation of factors of 4th degree polynomial\n\n  Eigen::Matrix<double, 5, 1> factors;\n\n  factors(0) = -f_2_pw2 * p_2_pw4 - p_2_pw4 * f_1_pw2 - p_2_pw4;\n\n  factors(1) = 2.0 * p_2_pw3 * d_12 * b + 2.0 * f_2_pw2 * p_2_pw3 * d_12 * b\n      - 2.0 * f_2 * p_2_pw3 * f_1 * d_12;\n\n  factors(2) = -f_2_pw2 * p_2_pw2 * p_1_pw2\n      - f_2_pw2 * p_2_pw2 * d_12_pw2 * b_pw2 - f_2_pw2 * p_2_pw2 * d_12_pw2\n      + f_2_pw2 * p_2_pw4 + p_2_pw4 * f_1_pw2 + 2.0 * p_1 * p_2_pw2 * d_12\n      + 2.0 * f_1 * f_2 * p_1 * p_2_pw2 * d_12 * b - p_2_pw2 * p_1_pw2 * f_1_pw2\n      + 2.0 * p_1 * p_2_pw2 * f_2_pw2 * d_12 - p_2_pw2 * d_12_pw2 * b_pw2\n      - 2.0 * p_1_pw2 * p_2_pw2;\n\n  factors(3) = 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\n  factors(4) = -2.0 * 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 - p_1_pw2 * d_12_pw2\n      + 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 + 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\n  Eigen::Vector4d real_roots;\n\n  SolveQuartic(factors, &real_roots);\n\n  // Backsubstitution of each solution\n  rotations->clear();\n  camera_centers->clear();\n  for (int i = 0; i < 4; ++i) {\n    // TORSTEN: Checks if this solution has already been used.\n    bool used = false;\n    for (int j = i - 1; j >= 0 && !used; --j) {\n      used = (real_roots(i) == real_roots(j));\n    }\n    if (used)\n      continue;\n\n    double cot_alpha = (-f_1 * p_1 / f_2 - real_roots(i) * p_2 + d_12 * b)\n        / (-f_1 * real_roots(i) * p_2 / f_2 + p_1 - d_12);\n\n    double cos_theta = real_roots(i);\n    double sin_theta = sqrt(1.0 - (cos_theta * cos_theta));\n    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.0)\n      cos_alpha = -cos_alpha;\n\n    Eigen::Vector3d C;\n    C << d_12 * cos_alpha * (sin_alpha * b + cos_alpha), cos_theta * d_12\n        * sin_alpha * (sin_alpha * b + cos_alpha), sin_theta * d_12 * sin_alpha\n        * (sin_alpha * b + cos_alpha);\n\n    C = P1 + N.transpose() * C;\n\n    Eigen::Matrix3d R;\n    R << -cos_alpha, -sin_alpha * cos_theta, -sin_alpha * sin_theta,\n         sin_alpha, -cos_alpha  * cos_theta, -cos_alpha * sin_theta,\n         0, -sin_theta, cos_theta;\n\n    R = N.transpose() * R.transpose() * T;\n\n    camera_centers->push_back(C);\n    rotations->push_back(R.transpose());\n  }\n\n  return 0;\n}\n\nint SolveQuartic(const Eigen::Matrix<double, 5, 1>& factors,\n                        Eigen::Vector4d* real_roots) {\n  double A = factors[0];\n  double B = factors[1];\n  double C = factors[2];\n  double D = factors[3];\n  double E = factors[4];\n\n  double A_pw2 = A * A;\n  double B_pw2 = B * B;\n  double A_pw3 = A_pw2 * A;\n  double B_pw3 = B_pw2 * B;\n  double A_pw4 = A_pw3 * A;\n  double B_pw4 = B_pw3 * B;\n\n  double alpha = -3.0 * B_pw2 / (8.0 * A_pw2) + C / A;\n  double beta = B_pw3 / (8.0 * A_pw3) - B * C / (2.0 * A_pw2) + D / A;\n  double gamma = -3.0 * B_pw4 / (256.0 * A_pw4) + B_pw2 * C / (16.0 * A_pw3)\n      - B * D / (4.0 * A_pw2) + E / A;\n\n  double alpha_pw2 = alpha * alpha;\n  double alpha_pw3 = alpha_pw2 * alpha;\n\n  std::complex<double> P(-alpha_pw2 / 12.0 - gamma, 0.0);\n  std::complex<double> Q(\n      -alpha_pw3 / 108.0 + alpha * gamma / 3.0 - beta * beta / 8.0, 0.0);\n  std::complex<double> R = -Q / 2.0\n      + sqrt(pow(Q, 2.0) / 4.0 + P * P * P / 27.0);\n\n  std::complex<double> U = pow(R, (1.0 / 3.0));\n  std::complex<double> y;\n\n  if (U.real() == 0.0)\n    y = -5.0 * alpha / 6.0 - pow(Q, (1.0 / 3.0));\n  else\n    y = -5.0 * alpha / 6.0 - P / (3.0 * U) + U;\n\n  std::complex<double> w = sqrt(alpha + 2.0 * y);\n\n  std::complex<double> temp;\n\n  temp = -B / (4.0 * A)\n      + 0.5 * (w + sqrt(-(3.0 * alpha + 2.0 * y + 2.0 * beta / w)));\n  (*real_roots)[0] = temp.real();\n  temp = -B / (4.0 * A)\n      + 0.5 * (w - sqrt(-(3.0 * alpha + 2.0 * y + 2.0 * beta / w)));\n  (*real_roots)[1] = temp.real();\n  temp = -B / (4.0 * A)\n      + 0.5 * (-w + sqrt(-(3.0 * alpha + 2.0 * y - 2.0 * beta / w)));\n  (*real_roots)[2] = temp.real();\n  temp = -B / (4.0 * A)\n      + 0.5 * (-w - sqrt(-(3.0 * alpha + 2.0 * y - 2.0 * beta / w)));\n  (*real_roots)[3] = temp.real();\n\n  return 0;\n}\n\n}  // namespace p3p_kneip\n", "meta": {"hexsha": "1d8496481e8d1dd56697063a3d23e1f2f729468b", "size": 9599, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "include/p3p/P3p.cpp", "max_stars_repo_name": "ctu-mrs/uvdar_core", "max_stars_repo_head_hexsha": "85f01498b433660fcff7410e40d35b79d3ca225a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-09-15T14:48:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-05T22:56:02.000Z", "max_issues_repo_path": "include/p3p/P3p.cpp", "max_issues_repo_name": "ctu-mrs/uvdar_core", "max_issues_repo_head_hexsha": "85f01498b433660fcff7410e40d35b79d3ca225a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-06-29T03:18:39.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-30T15:28:43.000Z", "max_forks_repo_path": "include/p3p/P3p.cpp", "max_forks_repo_name": "ctu-mrs/uvdar_core", "max_forks_repo_head_hexsha": "85f01498b433660fcff7410e40d35b79d3ca225a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-11-02T16:58:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-05T23:00:09.000Z", "avg_line_length": 33.214532872, "max_line_length": 142, "alphanum_fraction": 0.6163141994, "num_tokens": 3353, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4821466617454306}}
{"text": "/*\n [auto_generated]\n libs/numeric/odeint/test/adams_moulton.cpp\n\n [begin_description]\n This file tests the use of the Adams-Moulton stepper.\n [end_description]\n\n Copyright 2011-2012 Karsten Ahnert\n Copyright 2011-2012 Mario Mulansky\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#define BOOST_TEST_MODULE odeint_adams_moulton\n\n#include <utility>\n\n#include <boost/array.hpp>\n\n#include <boost/test/unit_test.hpp>\n\n#include <boost/mpl/list.hpp>\n#include <boost/mpl/size_t.hpp>\n#include <boost/mpl/range_c.hpp>\n\n\n#include <boost/numeric/odeint/stepper/detail/adams_moulton_coefficients.hpp>\n#include <boost/numeric/odeint/stepper/detail/rotating_buffer.hpp>\n#include <boost/numeric/odeint/stepper/adams_moulton.hpp>\n\nusing namespace boost::unit_test;\nusing namespace boost::numeric::odeint;\n\ntypedef double value_type;\n\nstruct lorenz\n{\n    template< class State , class Deriv , class Value >\n    void operator()( const State &_x , Deriv &_dxdt , const Value &dt ) const\n    {\n        const value_type sigma = 10.0;\n        const value_type R = 28.0;\n        const value_type b = 8.0 / 3.0;\n\n        typename boost::range_iterator< const State >::type x = boost::begin( _x );\n        typename boost::range_iterator< Deriv >::type dxdt = boost::begin( _dxdt );\n\n        dxdt[0] = sigma * ( x[1] - x[0] );\n        dxdt[1] = R * x[0] - x[1] - x[0] * x[2];\n        dxdt[2] = x[0]*x[1] - b * x[2];\n    }\n};\n\nBOOST_AUTO_TEST_SUITE( adams_moulton_test )\n\nBOOST_AUTO_TEST_CASE( test_adams_moulton_coefficients )\n{\n    detail::adams_moulton_coefficients< value_type , 1 > c1;\n    detail::adams_moulton_coefficients< value_type , 2 > c2;\n    detail::adams_moulton_coefficients< value_type , 3 > c3;\n    detail::adams_moulton_coefficients< value_type , 4 > c4;\n    detail::adams_moulton_coefficients< value_type , 5 > c5;\n    detail::adams_moulton_coefficients< value_type , 6 > c6;\n    detail::adams_moulton_coefficients< value_type , 7 > c7;\n    detail::adams_moulton_coefficients< value_type , 8 > c8;\n}\n\ntypedef boost::mpl::range_c< size_t , 1 , 6 > vector_of_steps;\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( test_init_and_steps , step_type , vector_of_steps )\n{\n    const static size_t steps = step_type::value;\n    typedef boost::array< value_type , 3 > state_type;\n\n    adams_moulton< steps , state_type > stepper;\n//    state_type x = {{ 10.0 , 10.0 , 10.0 }};\n//    const value_type dt = 0.01;\n//    value_type t = 0.0;\n\n//    stepper.do_step( lorenz() , x , t , dt );\n}\n\nBOOST_AUTO_TEST_CASE( test_instantiation )\n{\n    typedef boost::array< double , 3 > state_type;\n    adams_moulton< 1 , state_type > s1;\n    adams_moulton< 2 , state_type > s2;\n    adams_moulton< 3 , state_type > s3;\n    adams_moulton< 4 , state_type > s4;\n    adams_moulton< 5 , state_type > s5;\n    adams_moulton< 6 , state_type > s6;\n    adams_moulton< 7 , state_type > s7;\n    adams_moulton< 8 , state_type > s8;\n\n//    state_type x = {{ 10.0 , 10.0 , 10.0 }};\n//    value_type t = 0.0 , dt = 0.01;\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "faccdda5befd4c5d34a265b25d95fbf5e44a619b", "size": 3101, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/odeint/test/adams_moulton.cpp", "max_stars_repo_name": "cpp-pm/boost", "max_stars_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "libs/numeric/odeint/test/adams_moulton.cpp", "max_issues_repo_name": "cpp-pm/boost", "max_issues_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "libs/numeric/odeint/test/adams_moulton.cpp", "max_forks_repo_name": "cpp-pm/boost", "max_forks_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_forks_repo_licenses": ["BSL-1.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": 29.5333333333, "max_line_length": 83, "alphanum_fraction": 0.690744921, "num_tokens": 969, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4821466552673674}}
{"text": "/*\n * Transformation.cpp\n *\n *  Created on: 15.02.2018\n *      Author: thies\n */\n\n#include <base/ComposedFunction.h>\n#include <base/Transformation.h>\n#include <deal.II/base/function_parser.h>\n\nnamespace wavepi {\nnamespace base {\n\ntemplate <int dim>\nDiscretizedFunction<dim> IdentityTransform<dim>::transform(const DiscretizedFunction<dim> &param) {\n  return param;\n}\n\ntemplate <int dim>\nstd::shared_ptr<LightFunction<dim>> IdentityTransform<dim>::transform(const std::shared_ptr<LightFunction<dim>> param) {\n  return param;\n}\n\ntemplate <int dim>\nDiscretizedFunction<dim> IdentityTransform<dim>::transform_inverse(const DiscretizedFunction<dim> &param) {\n  return param;\n}\n\ntemplate <int dim>\nDiscretizedFunction<dim> IdentityTransform<dim>::inverse_derivative(const DiscretizedFunction<dim> &param\n                                                                    __attribute((unused)),\n                                                                    const DiscretizedFunction<dim> &h) {\n  return h;\n}\n\ntemplate <int dim>\nDiscretizedFunction<dim> IdentityTransform<dim>::inverse_derivative_transpose(const DiscretizedFunction<dim> &param\n                                                                              __attribute((unused)),\n                                                                              const DiscretizedFunction<dim> &g) {\n  return g;\n}\n\ntemplate <int dim>\nvoid LogTransform<dim>::declare_parameters(ParameterHandler &prm) {\n  prm.enter_subsection(\"LogTransform\");\n  prm.declare_entry(\"lower bound\", \"0.0\", Patterns::Double(),\n                    \"transformation function for log transform is \u03c6(x) = log(x-x\u2080), where x\u2080 is the lower bound you \"\n                    \"want to enforce.\");\n  prm.leave_subsection();\n}\n\ntemplate <int dim>\nvoid LogTransform<dim>::get_parameters(ParameterHandler &prm) {\n  prm.enter_subsection(\"LogTransform\");\n  lower_bound = prm.get_double(\"lower bound\");\n  prm.leave_subsection();\n}\n\ntemplate <int dim>\nDiscretizedFunction<dim> LogTransform<dim>::transform(const DiscretizedFunction<dim> &param) {\n  AssertThrow(!param.has_derivative(), ExcMessage(\"Not transforming derivatives!\"));\n\n  DiscretizedFunction<dim> tmp(param.get_mesh(), param.get_norm());\n\n  for (size_t i = 0; i < param.length(); i++)\n    for (size_t j = 0; j < param[i].size(); j++) {\n      Assert(param[i][j] > lower_bound,\n             ExcMessage(\"LogTransform::transform called on param with entries <= lower bound\"));\n      tmp[i][j] = std::log(param[i][j] - lower_bound);\n    }\n\n  return tmp;\n}\n\ntemplate <int dim>\nstd::shared_ptr<LightFunction<dim>> LogTransform<dim>::transform(const std::shared_ptr<LightFunction<dim>> param) {\n  return std::make_shared<ComposedFunction<dim>>(param,\n                                                 std::make_shared<LogTransform<dim>::TransformFunction>(lower_bound));\n}\n\ntemplate <int dim>\nDiscretizedFunction<dim> LogTransform<dim>::transform_inverse(const DiscretizedFunction<dim> &param) {\n  AssertThrow(!param.has_derivative(), ExcMessage(\"Not transforming derivatives!\"));\n\n  DiscretizedFunction<dim> tmp(param.get_mesh(), param.get_norm());\n\n  for (size_t i = 0; i < param.length(); i++)\n    for (size_t j = 0; j < param[i].size(); j++)\n      tmp[i][j] = std::exp(param[i][j]) + lower_bound;\n\n  return tmp;\n}\n\ntemplate <int dim>\nDiscretizedFunction<dim> LogTransform<dim>::inverse_derivative(const DiscretizedFunction<dim> &param,\n                                                               const DiscretizedFunction<dim> &h) {\n  AssertThrow(!param.has_derivative() && !h.has_derivative(), ExcMessage(\"Not transforming derivatives!\"));\n  AssertThrow(param.get_mesh() == h.get_mesh(), ExcMessage(\"LogTransform: meshes must match\"));\n\n  DiscretizedFunction<dim> tmp(param.get_mesh(), param.get_norm());\n\n  for (size_t i = 0; i < param.length(); i++)\n    for (size_t j = 0; j < param[i].size(); j++)\n      tmp[i][j] = std::exp(param[i][j]) * h[i][j];\n\n  return tmp;\n}\ntemplate <int dim>\nDiscretizedFunction<dim> LogTransform<dim>::inverse_derivative_transpose(const DiscretizedFunction<dim> &param,\n                                                                         const DiscretizedFunction<dim> &g) {\n  return inverse_derivative(param, g);\n}\n\ntemplate <int dim>\nvoid ArtanhTransform<dim>::declare_parameters(ParameterHandler &prm) {\n  prm.enter_subsection(\"ArtanhTransform\");\n  prm.declare_entry(\"lower bound\", \"0.0\", Patterns::Double(),\n                    \"transformation function for log transform is \u03c6: (a,b) \u2192 \u211d,  \u03c6(x) = tanh\u207b\u00b9((2x-(a+b))/(b-a)) (pointwise), where a and b are the bounds you would like to enforce\");  \n  prm.declare_entry(\"upper bound\", \"1.0\", Patterns::Double(),\n                    \"transformation function for log transform is \u03c6: (a,b) \u2192 \u211d,  \u03c6(x) = tanh\u207b\u00b9(((2x-(a+b))/(b-a)) (pointwise), where a and b are the bounds you would like to enforce\");\n  prm.leave_subsection();\n}\n\ntemplate <int dim>\nvoid ArtanhTransform<dim>::get_parameters(ParameterHandler &prm) {\n  prm.enter_subsection(\"ArtanhTransform\");\n  lower_bound = prm.get_double(\"lower bound\");\n  upper_bound = prm.get_double(\"upper bound\");\n  prm.leave_subsection();\n}\n\ntemplate <int dim>\nDiscretizedFunction<dim> ArtanhTransform<dim>::transform(const DiscretizedFunction<dim> &param) {\n  AssertThrow(!param.has_derivative(), ExcMessage(\"Not transforming derivatives!\"));\n\n  DiscretizedFunction<dim> tmp(param.get_mesh(), param.get_norm());\n\n  for (size_t i = 0; i < param.length(); i++)\n    for (size_t j = 0; j < param[i].size(); j++) {\n      Assert(param[i][j] > lower_bound,\n             ExcMessage(\"ArtanhTransform::transform called on param with entries <= lower bound\"));\n      Assert(param[i][j] < upper_bound,\n             ExcMessage(\"ArtanhTransform::transform called on param with entries >= upper bound\"));\n\n      tmp[i][j] = std::atanh((2 * param[i][j] - (lower_bound + upper_bound)) / (upper_bound - lower_bound));\n    }\n\n  return tmp;\n}\n\ntemplate <int dim>\nstd::shared_ptr<LightFunction<dim>> ArtanhTransform<dim>::transform(const std::shared_ptr<LightFunction<dim>> param) {\n  return std::make_shared<ComposedFunction<dim>>(param,\n                                                 std::make_shared<ArtanhTransform<dim>::TransformFunction>(lower_bound, upper_bound));\n}\n\ntemplate <int dim>\nDiscretizedFunction<dim> ArtanhTransform<dim>::transform_inverse(const DiscretizedFunction<dim> &param) {\n  AssertThrow(!param.has_derivative(), ExcMessage(\"Not transforming derivatives!\"));\n\n  DiscretizedFunction<dim> tmp(param.get_mesh(), param.get_norm());\n\n  for (size_t i = 0; i < param.length(); i++)\n    for (size_t j = 0; j < param[i].size(); j++)\n      tmp[i][j] = (upper_bound-lower_bound)/2 * std::tanh(param[i][j]) + (lower_bound+upper_bound)/2;\n      \n  return tmp;\n}\n\ntemplate <int dim>\nDiscretizedFunction<dim> ArtanhTransform<dim>::inverse_derivative(const DiscretizedFunction<dim> &param,\n                                                               const DiscretizedFunction<dim> &h) {\n  AssertThrow(!param.has_derivative() && !h.has_derivative(), ExcMessage(\"Not transforming derivatives!\"));\n  AssertThrow(param.get_mesh() == h.get_mesh(), ExcMessage(\"ArtanhTransform: meshes must match\"));\n\n  DiscretizedFunction<dim> tmp(param.get_mesh(), param.get_norm());\n\n  for (size_t i = 0; i < param.length(); i++)\n    for (size_t j = 0; j < param[i].size(); j++) {\n      double u = std::cosh(param[i][j]);\n      tmp[i][j] = (upper_bound-lower_bound)/2 * 1/(u*u) * h[i][j];\n    }\n\n  return tmp;\n}\n\ntemplate <int dim>\nDiscretizedFunction<dim> ArtanhTransform<dim>::inverse_derivative_transpose(const DiscretizedFunction<dim> &param,\n                                                                         const DiscretizedFunction<dim> &g) {\n  return inverse_derivative(param, g);\n}\n\ntemplate class Transformation<1>;\ntemplate class Transformation<2>;\ntemplate class Transformation<3>;\n\ntemplate class IdentityTransform<1>;\ntemplate class IdentityTransform<2>;\ntemplate class IdentityTransform<3>;\n\ntemplate class LogTransform<1>;\ntemplate class LogTransform<2>;\ntemplate class LogTransform<3>;\n\ntemplate class ArtanhTransform<1>;\ntemplate class ArtanhTransform<2>;\ntemplate class ArtanhTransform<3>;\n\n}  // namespace base\n}  // namespace wavepi\n", "meta": {"hexsha": "8c7f9378a4a9bcc2a6a0dc330da655656b805594", "size": 8235, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/base/Transformation.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/Transformation.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/Transformation.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": 38.8443396226, "max_line_length": 185, "alphanum_fraction": 0.6540376442, "num_tokens": 1916, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.48214664878930397}}
{"text": "//=======================================================================\n// Copyright (c) 2013 Robert Rosolek\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 fractional_winner_determination_in_MUCA_example.cpp\n * @brief\n * @author Robert Rosolek\n * @version 1.0\n * @date 2014-06-09\n */\n\n#include \"paal/auctions/auction_components.hpp\"\n#include \"paal/auctions/fractional_winner_determination_in_MUCA/fractional_winner_determination_in_MUCA.hpp\"\n#include \"paal/auctions/xor_bids.hpp\"\n\n#include <boost/function_output_iterator.hpp>\n#include <boost/range/algorithm/copy.hpp>\n\n#include <algorithm>\n#include <iostream>\n#include <iterator>\n#include <string>\n#include <tuple>\n#include <unordered_map>\n#include <unordered_set>\n#include <utility>\n#include <vector>\n\n//! [Fractional Winner Determination in MUCA Example]\nint main()\n{\n   using Bidder = std::string;\n   using Item = std::string;\n   using Items = std::unordered_set<Item>;\n   using Value = long double;\n   using Bid = std::pair<Items, Value>;\n   using Bids = std::vector<Bid>;\n   using Assignment = std::tuple<Bidder, Items, double>;\n\n   // create auction\n   const std::unordered_map<Bidder, Bids> bids {\n      {\"John\", {\n         {{\"lemon\", \"orange\"}, 1},\n         {{\"apple\", \"ball\"}, 1},\n      }},\n      {\"Bob\", {\n         {{\"lemon\", \"apple\"}, 1},\n         {{\"orange\", \"ball\"}, 1},\n      }},\n   };\n   const std::vector<Bidder> bidders {\"John\", \"Bob\"};\n   const std::vector<Item> items {\"apple\", \"ball\", \"orange\", \"lemon\"};\n   auto get_bids = [&](const Bidder& bidder) -> const Bids& { return bids.at(bidder); };\n   auto get_value = [](const Bid& bid) { return bid.second; };\n   auto get_items = [](const Bid& bid) -> const Items& { return bid.first; };\n   auto auction = paal::auctions::make_xor_bids_to_demand_query_auction(\n      bidders, items, get_bids, get_value, get_items\n   );\n\n   // determine winners\n   Value social_welfare = 0;\n   auto valuation = paal::auctions::make_xor_bids_to_value_query_auction(\n      std::move(bidders), std::move(items), get_bids, get_value, get_items\n   );\n   paal::auctions::fractional_determine_winners_in_demand_query_auction(\n      auction,\n      boost::make_function_output_iterator([&](Assignment a)\n      {\n         auto bidder = std::get<0>(a);\n         auto& cur_items = std::get<1>(a);\n         auto fraction = std::get<2>(a);\n         social_welfare += fraction * valuation.call<paal::auctions::value_query>(bidder, cur_items);\n         std::cout << bidder << \" got a fraction \" << fraction << \" of bundle: \";\n         boost::copy(cur_items, std::ostream_iterator<Item>(std::cout, \", \"));\n         std::cout << std::endl;\n      })\n   );\n   std::cout << \"social welfare: \" << social_welfare << std::endl;\n\n   return 0;\n}\n//! [Fractional Winner Determination in MUCA Example]\n", "meta": {"hexsha": "482418032d15b5c18a833b99fb4828ca43cc7f8c", "size": 2976, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/auctions/fractional_winner_determination_in_MUCA/fractional_winner_determination_in_MUCA_example.cpp", "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": "examples/auctions/fractional_winner_determination_in_MUCA/fractional_winner_determination_in_MUCA_example.cpp", "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": "examples/auctions/fractional_winner_determination_in_MUCA/fractional_winner_determination_in_MUCA_example.cpp", "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": 34.2068965517, "max_line_length": 108, "alphanum_fraction": 0.622983871, "num_tokens": 773, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577157, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.48214664878930386}}
{"text": "#ifndef GEOM_H\n#define GEOM_H\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n#include <boost/geometry/geometries/linestring.hpp>\n#include \"petsc.h\"\n\nnamespace bg = boost::geometry;\ntypedef bg::model::point<double, 2, bg::cs::cartesian> point_t;\ntypedef bg::model::polygon<point_t> polygon_t;\ntypedef bg::model::segment<point_t> segment_t;\ntypedef bg::model::linestring<point_t> linestring_t;\n\nclass detector_geometry;\n\nstd::vector<double> linspace(double a, double b, size_t N);\nvoid setMatrixElements(int tau_idx, int theta_idx, detector_geometry det,Mat A_mat);\nvoid intersectionSet(linestring_t line, detector_geometry det, double theta,\n                     std::vector<int>& index,\n                     std::vector<double>& Lvec);\n\n\n// Detector / sample geometry class\nclass detector_geometry{\n\npublic:\n  double omega[4],m[2],dz[2],Tol;\n  std::vector<double> thetan,x,y; //Maybe make this point_t\n  std::vector<point_t> DetKnot0,SourceKnot0;\n  polygon_t rectangle;\n  PetscBool synthetic;\n  char solFile[255];\n  int numThetan,nTau;\n  detector_geometry(){\n    omega[0] = -2;\n    omega[1] =  2;\n    omega[2] = -2;\n    omega[3] = 2;\n    Tol = 1e-2;\n    numThetan = 60;\n    m[0] = 30; m[1] = 30;\n    nTau = 30;\n  }\n\n  detector_geometry(PetscReal omega_in[4], PetscReal tol_in,\n                    PetscInt numThetan_in, PetscInt m_in[2], PetscInt nTau_in,\n                    char solFile_in[255]);\n};\n\n#endif\n", "meta": {"hexsha": "4e81fee0a5c8eff6eefcd1aaf70066d56658bb5d", "size": 1492, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/geom.hpp", "max_stars_repo_name": "ZichaoDi/PJRT", "max_stars_repo_head_hexsha": "b02b438f8b9b847b6b1163aba7d0d5ffef0ab492", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/geom.hpp", "max_issues_repo_name": "ZichaoDi/PJRT", "max_issues_repo_head_hexsha": "b02b438f8b9b847b6b1163aba7d0d5ffef0ab492", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/geom.hpp", "max_forks_repo_name": "ZichaoDi/PJRT", "max_forks_repo_head_hexsha": "b02b438f8b9b847b6b1163aba7d0d5ffef0ab492", "max_forks_repo_licenses": ["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.6923076923, "max_line_length": 84, "alphanum_fraction": 0.686997319, "num_tokens": 430, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.6224593171945416, "lm_q1q2_score": 0.4821466444175355}}
{"text": "\r\n\r\n//\r\n//=======================================================================\r\n// Copyright (c) 2004 Kristopher Beevers\r\n//\r\n// Distributed under the Boost Software License, Version 1.0. (See\r\n// accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n//=======================================================================\r\n//\r\n\r\n\r\n#include <boost/graph/astar_search.hpp>\r\n#include <boost/graph/adjacency_list.hpp>\r\n#include <boost/graph/random.hpp>\r\n#include <boost/random.hpp>\r\n#include <utility>\r\n#include <vector>\r\n#include <list>\r\n#include <iostream>\r\n#include <math.h>    // for sqrt\r\n#include <time.h>\r\n\r\nusing namespace boost;\r\nusing namespace std;\r\n\r\n\r\n// auxiliary types\r\nstruct location\r\n{\r\n  float y, x; // lat, long\r\n};\r\ntypedef float cost;\r\n\r\ntemplate <class Name, class LocMap>\r\nclass city_writer {\r\npublic:\r\n  city_writer(Name n, LocMap l, float _minx, float _maxx,\r\n              float _miny, float _maxy,\r\n              unsigned int _ptx, unsigned int _pty)\r\n    : name(n), loc(l), minx(_minx), maxx(_maxx), miny(_miny),\r\n      maxy(_maxy), ptx(_ptx), pty(_pty) {}\r\n  template <class Vertex>\r\n  void operator()(ostream& out, const Vertex& v) const {\r\n    float px = 1 - (loc[v].x - minx) / (maxx - minx);\r\n    float py = (loc[v].y - miny) / (maxy - miny);\r\n    out << \"[label=\\\"\" << name[v] << \"\\\", pos=\\\"\"\r\n        << static_cast<unsigned int>(ptx * px) << \",\"\r\n        << static_cast<unsigned int>(pty * py)\r\n        << \"\\\", fontsize=\\\"11\\\"]\";\r\n  }\r\nprivate:\r\n  Name name;\r\n  LocMap loc;\r\n  float minx, maxx, miny, maxy;\r\n  unsigned int ptx, pty;\r\n};\r\n\r\ntemplate <class WeightMap>\r\nclass time_writer {\r\npublic:\r\n  time_writer(WeightMap w) : wm(w) {}\r\n  template <class Edge>\r\n  void operator()(ostream &out, const Edge& e) const {\r\n    out << \"[label=\\\"\" << wm[e] << \"\\\", fontsize=\\\"11\\\"]\";\r\n  }\r\nprivate:\r\n  WeightMap wm;\r\n};\r\n\r\n\r\n// euclidean distance heuristic\r\ntemplate <class Graph, class CostType, class LocMap>\r\nclass distance_heuristic : public astar_heuristic<Graph, CostType>\r\n{\r\npublic:\r\n  typedef typename graph_traits<Graph>::vertex_descriptor Vertex;\r\n  distance_heuristic(LocMap l, Vertex goal)\r\n    : m_location(l), m_goal(goal) {}\r\n  CostType operator()(Vertex u)\r\n  {\r\n    CostType dx = m_location[m_goal].x - m_location[u].x;\r\n    CostType dy = m_location[m_goal].y - m_location[u].y;\r\n    return ::sqrt(dx * dx + dy * dy);\r\n  }\r\nprivate:\r\n  LocMap m_location;\r\n  Vertex m_goal;\r\n};\r\n\r\n\r\nstruct found_goal {}; // exception for termination\r\n\r\n// visitor that terminates when we find the goal\r\ntemplate <class Vertex>\r\nclass astar_goal_visitor : public boost::default_astar_visitor\r\n{\r\npublic:\r\n  astar_goal_visitor(Vertex goal) : m_goal(goal) {}\r\n  template <class Graph>\r\n  void examine_vertex(Vertex u, Graph&) {\r\n    if(u == m_goal)\r\n      throw found_goal();\r\n  }\r\nprivate:\r\n  Vertex m_goal;\r\n};\r\n\r\n\r\nint main(int, char **)\r\n{\r\n  \r\n  // specify some types\r\n  typedef adjacency_list<listS, vecS, undirectedS, no_property,\r\n    property<edge_weight_t, cost> > mygraph_t;\r\n  typedef property_map<mygraph_t, edge_weight_t>::type WeightMap;\r\n  typedef mygraph_t::vertex_descriptor vertex;\r\n  typedef mygraph_t::edge_descriptor edge_descriptor;\r\n  typedef mygraph_t::vertex_iterator vertex_iterator;\r\n  typedef std::pair<int, int> edge;\r\n  \r\n  // specify data\r\n  enum nodes {\r\n    Troy, LakePlacid, Plattsburgh, Massena, Watertown, Utica,\r\n    Syracuse, Rochester, Buffalo, Ithaca, Binghamton, Woodstock,\r\n    NewYork, N\r\n  };\r\n  const char *name[] = {\r\n    \"Troy\", \"Lake Placid\", \"Plattsburgh\", \"Massena\",\r\n    \"Watertown\", \"Utica\", \"Syracuse\", \"Rochester\", \"Buffalo\",\r\n    \"Ithaca\", \"Binghamton\", \"Woodstock\", \"New York\"\r\n  };\r\n  location locations[] = { // lat/long\r\n    {42.73, 73.68}, {44.28, 73.99}, {44.70, 73.46},\r\n    {44.93, 74.89}, {43.97, 75.91}, {43.10, 75.23},\r\n    {43.04, 76.14}, {43.17, 77.61}, {42.89, 78.86},\r\n    {42.44, 76.50}, {42.10, 75.91}, {42.04, 74.11},\r\n    {40.67, 73.94}\r\n  };\r\n  edge edge_array[] = {\r\n    edge(Troy,Utica), edge(Troy,LakePlacid),\r\n    edge(Troy,Plattsburgh), edge(LakePlacid,Plattsburgh),\r\n    edge(Plattsburgh,Massena), edge(LakePlacid,Massena),\r\n    edge(Massena,Watertown), edge(Watertown,Utica),\r\n    edge(Watertown,Syracuse), edge(Utica,Syracuse),\r\n    edge(Syracuse,Rochester), edge(Rochester,Buffalo),\r\n    edge(Syracuse,Ithaca), edge(Ithaca,Binghamton),\r\n    edge(Ithaca,Rochester), edge(Binghamton,Troy),\r\n    edge(Binghamton,Woodstock), edge(Binghamton,NewYork),\r\n    edge(Syracuse,Binghamton), edge(Woodstock,Troy),\r\n    edge(Woodstock,NewYork)\r\n  };\r\n  unsigned int num_edges = sizeof(edge_array) / sizeof(edge);\r\n  cost weights[] = { // estimated travel time (mins)\r\n    96, 134, 143, 65, 115, 133, 117, 116, 74, 56,\r\n    84, 73, 69, 70, 116, 147, 173, 183, 74, 71, 124\r\n  };\r\n  \r\n  \r\n  // create graph\r\n  mygraph_t g(N);\r\n  WeightMap weightmap = get(edge_weight, g);\r\n  for(std::size_t j = 0; j < num_edges; ++j) {\r\n    edge_descriptor e; bool inserted;\r\n    boost::tie(e, inserted) = add_edge(edge_array[j].first,\r\n                                       edge_array[j].second, g);\r\n    weightmap[e] = weights[j];\r\n  }\r\n  \r\n  \r\n  // pick random start/goal\r\n  boost::minstd_rand gen(time(0));\r\n  vertex start = gen() % num_vertices(g);\r\n  vertex goal = gen() % num_vertices(g);\r\n  \r\n  \r\n  cout << \"Start vertex: \" << name[start] << endl;\r\n  cout << \"Goal vertex: \" << name[goal] << endl;\r\n  \r\n  vector<mygraph_t::vertex_descriptor> p(num_vertices(g));\r\n  vector<cost> d(num_vertices(g));\r\n  try {\r\n    // call astar named parameter interface\r\n    astar_search\r\n      (g, start,\r\n       distance_heuristic<mygraph_t, cost, location*>\r\n        (locations, goal),\r\n       predecessor_map(&p[0]).distance_map(&d[0]).\r\n       visitor(astar_goal_visitor<vertex>(goal)));\r\n  \r\n  \r\n  } catch(found_goal fg) { // found a path to the goal\r\n    list<vertex> shortest_path;\r\n    for(vertex v = goal;; v = p[v]) {\r\n      shortest_path.push_front(v);\r\n      if(p[v] == v)\r\n        break;\r\n    }\r\n    cout << \"Shortest path from \" << name[start] << \" to \"\r\n         << name[goal] << \": \";\r\n    list<vertex>::iterator spi = shortest_path.begin();\r\n    cout << name[start];\r\n    for(++spi; spi != shortest_path.end(); ++spi)\r\n      cout << \" -> \" << name[*spi];\r\n    cout << endl << \"Total travel time: \" << d[goal] << endl;\r\n    return 0;\r\n  }\r\n  \r\n  cout << \"Didn't find a path from \" << name[start] << \"to\"\r\n       << name[goal] << \"!\" << endl;\r\n  return 0;\r\n  \r\n}\r\n", "meta": {"hexsha": "0fb934b19edc4e7ae26843b63559875b38e6d3f1", "size": 6487, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/graph/test/astar_search_test.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/graph/test/astar_search_test.cpp", "max_issues_repo_name": "xiaoliang2121/Boost", "max_issues_repo_head_hexsha": "fc90c3fde129c62565c023f091eddc4a7ed9902b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-03-19T08:23:23.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-24T07:48:47.000Z", "max_forks_repo_path": "libs/graph/test/astar_search_test.cpp", "max_forks_repo_name": "xiaoliang2121/Boost", "max_forks_repo_head_hexsha": "fc90c3fde129c62565c023f091eddc4a7ed9902b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 30.1720930233, "max_line_length": 74, "alphanum_fraction": 0.5999691691, "num_tokens": 1858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.48211617396755546}}
{"text": "// Copyright Abel Sinkovics (abel@sinkovics.hu)  2012.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n#include <boost/metaparse/repeated.hpp>\n#include <boost/metaparse/sequence.hpp>\n#include <boost/metaparse/lit_c.hpp>\n#include <boost/metaparse/last_of.hpp>\n#include <boost/metaparse/space.hpp>\n#include <boost/metaparse/int_.hpp>\n#include <boost/metaparse/foldl_reject_incomplete_start_with_parser.hpp>\n#include <boost/metaparse/one_of.hpp>\n#include <boost/metaparse/get_result.hpp>\n#include <boost/metaparse/token.hpp>\n#include <boost/metaparse/entire_input.hpp>\n#include <boost/metaparse/string.hpp>\n#include <boost/metaparse/transform.hpp>\n#include <boost/metaparse/always.hpp>\n#include <boost/metaparse/build_parser.hpp>\n\n#include <boost/mpl/apply_wrap.hpp>\n#include <boost/mpl/front.hpp>\n#include <boost/mpl/back.hpp>\n#include <boost/mpl/bool.hpp>\n#include <boost/mpl/if.hpp>\n\nusing boost::metaparse::sequence;\nusing boost::metaparse::lit_c;\nusing boost::metaparse::last_of;\nusing boost::metaparse::space;\nusing boost::metaparse::repeated;\nusing boost::metaparse::build_parser;\nusing boost::metaparse::int_;\nusing boost::metaparse::foldl_reject_incomplete_start_with_parser;\nusing boost::metaparse::get_result;\nusing boost::metaparse::one_of;\nusing boost::metaparse::token;\nusing boost::metaparse::entire_input;\nusing boost::metaparse::transform;\nusing boost::metaparse::always;\n\nusing boost::mpl::apply_wrap1;\nusing boost::mpl::front;\nusing boost::mpl::back;\nusing boost::mpl::if_;\nusing boost::mpl::bool_;\n\n/*\n * The grammar\n *\n * expression ::= plus_exp\n * plus_exp ::= prod_exp ((plus_token | minus_token) prod_exp)*\n * prod_exp ::= value_exp ((mult_token | div_token) value_exp)*\n * value_exp ::= int_token | '_'\n */\n\ntypedef token<lit_c<'+'> > plus_token;\ntypedef token<lit_c<'-'> > minus_token;\ntypedef token<lit_c<'*'> > mult_token;\ntypedef token<lit_c<'/'> > div_token;\n\ntypedef token<int_> int_token;\ntypedef token<lit_c<'_'> > arg_token;\n\ntemplate <class T, char C>\nstruct is_c : bool_<T::type::value == C> {};\n\nstruct build_plus\n{\n  template <class A, class B>\n  class _plus\n  {\n  public:\n    typedef _plus type;\n\n    template <class T>\n    T operator()(T t) const\n    {\n      return _left(t) + _right(t);\n    }\n  private:\n    typename A::type _left;\n    typename B::type _right;\n  };\n\n  template <class A, class B>\n  class _minus\n  {\n  public:\n    typedef _minus type;\n\n    template <class T>\n    T operator()(T t) const\n    {\n      return _left(t) - _right(t);\n    }\n  private:\n    typename A::type _left;\n    typename B::type _right;\n  };\n\n  template <class State, class C>\n  struct apply :\n    if_<\n      typename is_c<front<C>, '+'>::type,\n      _plus<State, typename back<C>::type>,\n      _minus<State, typename back<C>::type>\n    >\n  {};\n};\n\nstruct build_mult\n{\n  template <class A, class B>\n  class _mult\n  {\n  public:\n    typedef _mult type;\n\n    template <class T>\n    T operator()(T t) const\n    {\n      return _left(t) * _right(t);\n    }\n  private:\n    typename A::type _left;\n    typename B::type _right;\n  };\n\n  template <class A, class B>\n  class _div\n  {\n  public:\n    typedef _div type;\n\n    template <class T>\n    T operator()(T t) const\n    {\n      return _left(t) / _right(t);\n    }\n  private:\n    typename A::type _left;\n    typename B::type _right;\n  };\n\n  template <class State, class C>\n  struct apply :\n    if_<\n      typename is_c<front<C>, '*'>::type,\n      _mult<State, typename back<C>::type>,\n      _div<State, typename back<C>::type>\n    >\n  {};\n};\n\nstruct build_value\n{\n  typedef build_value type;\n\n  template <class V>\n  struct apply\n  {\n    typedef apply type;\n\n    template <class T>\n    int operator()(T) const\n    {\n      return V::type::value;\n    }\n  };\n};\n\nstruct arg\n{\n  typedef arg type;\n\n  template <class T>\n  T operator()(T t) const\n  {\n    return t;\n  }\n};\n\ntypedef\n  one_of<transform<int_token, build_value>, always<arg_token, arg> >\n  value_exp;\n\ntypedef\n  foldl_reject_incomplete_start_with_parser<\n    sequence<one_of<mult_token, div_token>, value_exp>,\n    value_exp,\n    build_mult\n  >\n  prod_exp;\n\ntypedef\n  foldl_reject_incomplete_start_with_parser<\n    sequence<one_of<plus_token, minus_token>, prod_exp>,\n    prod_exp,\n    build_plus\n  >\n  plus_exp;\n\ntypedef last_of<repeated<space>, plus_exp> expression;\n\ntypedef build_parser<entire_input<expression> > function_parser;\n\n#if BOOST_METAPARSE_STD < 2011\n\ntemplate <class Exp>\nstruct lambda : apply_wrap1<function_parser, Exp> {};\n\nusing boost::metaparse::string;\n\nlambda<string<'1','3'> >::type f1;\nlambda<string<'2',' ','+',' ','3'> >::type f2;\nlambda<string<'2',' ','*',' ','2'> >::type f3;\nlambda<string<' ','1','+',' ','2','*','4','-','6','/','2'> >::type f4;\nlambda<string<'2',' ','*',' ','_'> >::type f5;\n\n#else\n\n#ifdef LAMBDA\n  #error LAMBDA already defined\n#endif\n#define LAMBDA(exp) apply_wrap1<function_parser, BOOST_METAPARSE_STRING(#exp)>::type\n\nLAMBDA(13) f1;\nLAMBDA(2 + 3) f2;\nLAMBDA(2 * 2) f3;\nLAMBDA( 1+ 2*4-6/2) f4;\nLAMBDA(2 * _) f5;\n\n#endif\n\nint main()\n{\n  using std::cout;\n  using std::endl;\n\n  cout\n    << f1(11) << endl\n    << f2(11) << endl\n    << f3(11) << endl\n    << f4(11) << endl\n    << f5(11) << endl\n    << f5(1.1) << endl\n    ;\n}\n", "meta": {"hexsha": "a91e08b687f84a2c305a5d76668ed2e6a8fda093", "size": 5306, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/libs/metaparse/example/compile_to_native_code/main.cpp", "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/libs/metaparse/example/compile_to_native_code/main.cpp", "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/libs/metaparse/example/compile_to_native_code/main.cpp", "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": 21.1394422311, "max_line_length": 84, "alphanum_fraction": 0.6622691293, "num_tokens": 1562, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.6513548714339145, "lm_q1q2_score": 0.48211616895815906}}
{"text": "#define GLM_ENABLE_EXPERIMENTAL 1\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#include <Halide.h>\n#include <fstream>\n#include <glm/ext.hpp>\n#include <glm/glm.hpp>\n#include <halide_image_io.h>\n#include <iostream>\n#include <stdio.h>\n#include <fstream>\n#include <sstream>\n#include <string>\n#include <vector>\n\nusing std::string;\nusing std::stringstream;\nusing std::vector;\n\nusing namespace std;\nusing namespace Halide;\nusing namespace Halide::Tools;\nusing namespace Eigen;\n\nusing Vector4h = Matrix<Halide::Expr, 4, 1>;\nusing Matrix4h = Matrix<Halide::Expr, 4, 4>;\n\nVar x, y, c;\n\nstruct Point\n{\n    float x;\n    float y;\n    float z;\n    uint16_t r;\n    uint16_t g;\n    uint16_t b;\n};\n\nMatrix4h read4x4MatFromCSV(string csvFile)\n{\n    Matrix4h transfMat;\n    ifstream in(csvFile);\n    vector<float> floatVec;\n    if (in)\n    {\n        string line;\n        while (getline(in, line))\n        {\n            stringstream sep(line);\n            string field;\n            while (getline(sep, field, ','))\n            {\n                float val = stod(field);\n                floatVec.push_back(val);\n            }\n        }\n    }\n    transfMat << floatVec[0], floatVec[1], floatVec[2], floatVec[3],\n        floatVec[4], floatVec[5], floatVec[6], floatVec[7],\n        floatVec[8], floatVec[9], floatVec[10], floatVec[11],\n        floatVec[12], floatVec[13], floatVec[14], floatVec[15];\n    return transfMat;\n}\n\nostream &operator<<(ostream &os, const Matrix4h &m)\n{\n    os << m(0, 0) << \" \" << m(0, 1) << \" \" << m(0, 2) << \" \" << m(0, 3) << \"\\n\"\n       << m(1, 0) << \" \" << m(1, 1) << \" \" << m(1, 2) << \" \" << m(1, 3) << \"\\n\"\n       << m(2, 0) << \" \" << m(2, 1) << \" \" << m(2, 2) << \" \" << m(2, 3) << \"\\n\"\n       << m(3, 0) << \" \" << m(3, 1) << \" \" << m(3, 2) << \" \" << m(3, 3) << endl;\n    return os;\n}\n\nvoid saveImage(Expr result, size_t width, size_t height, const string &basename)\n{\n    Target target = get_host_target();\n    Func byteResult;\n    byteResult(x, y) = cast<uint8_t>(clamp(result, 0.0f, 1.0f) * 255.0f);\n    byteResult.compile_jit(target);\n    Buffer<uint8_t> output(width, height);\n    byteResult.realize(output);\n    stringstream filename;\n    filename << basename << \".png\";\n    save_image(output, filename.str());\n}\n\nostream &operator<<(ostream &os, const Vector4h &v)\n{\n    os << v(0) << \"\\n\"\n       << v(1) << \"\\n\"\n       << v(2) << \"\\n\"\n       << v(3) << endl;\n    return os;\n}\n\nMatrix4h getInvCameraMat(float focalLen, float pxDim, int width, int height)\n{\n\n    focalLen = focalLen * 10e-3;\n    float u0 = width / 2.0;\n    float v0 = height / 2.0;\n    Matrix4h camMat;\n    float zero = 0.0;\n    float one = 1.0;\n    camMat << pxDim / focalLen, 0.0f, -pxDim * u0 / focalLen, 0.0f,\n        0.0f, pxDim / focalLen, -pxDim * v0 / focalLen, 0.0f,\n        0.0f, 0.0f, 1.0f, 0.0f,\n        0.0f, 0.0f, 0.0f, 1.0f;\n\n    return camMat;\n}\n\nMatrix4h getTransMatProjToCam()\n{\n    Matrix4h transMat;\n    transMat << 0.9945219f, 0.0f, -0.10452846f, -0.2f,\n        0.0f, 1.0f, 0.0f, 0.0f,\n        0.10452846f, 0.0f, 0.9945219f, 0.0f,\n        0.0f, 0.0f, 0.0f, 1.0f;\n    return transMat;\n}\n\nMatrix4h getTransMatWorldToProj()\n{\n    Matrix4h transMat;\n    transMat << -0.99862951f, 0.0f, 0.0523359f, 0.1f,\n        0.00908804f, -0.1734101f, 0.9986295f, 3.0f,\n        -0.052335f, -1.0f, 0.0f, 1.0f,\n        0.0f, 0.0f, 0.0f, 1.0f;\n    return transMat;\n}\n\nVector4h makeAxBzCLine(Vector4h a, Vector4h b)\n{\n    Vector4h result;\n    result(0) = a(2) - b(2);\n    result(1) = b(0) - a(0);\n    result(2) = a(0) * b(2) - b(0) * a(2);\n    result(3) = 1.0f;\n    return result;\n}\n\nVector4h cross3(Vector4h a, Vector4h b)\n{\n    Vector4h res;\n    res(0) = a(1) * b(2) - a(2) * b(1);\n    res(1) = a(2) * b(0) - a(0) * b(2);\n    res(2) = a(0) * b(1) - a(1) * b(0);\n    res(3) = 0;\n    return res;\n}\n\nExpr dot3(Vector4h a, Vector4h b)\n{\n    Expr res;\n    res = a(0) * b(0) + a(1) * b(1) + a(2) * b(2);\n    return res;\n}\n\ntuple<Vector4h, Vector4h> pluckerLine(Vector4h p1, Vector4h p2)\n{\n    Vector4h l;\n    Vector4h l_dash;\n    l = p1(3) * p2 - p2(3) * p1;\n    l(3) = 0;\n    l_dash = cross3(p1, p2);\n    return {l, l_dash};\n}\n\nVector4h pluckerPlane(Vector4h l, Vector4h l_dash, Vector4h pluckPt)\n{\n    Vector4h u;\n    u = -pluckPt(3) * l_dash + cross3(pluckPt, l);\n    u(3) = dot3(pluckPt, l_dash);\n    return u;\n}\n\nVector4h intersectionLinePlane(Vector4h l, Vector4h l_dash, Vector4h plPlane)\n{\n    Vector4h intersection;\n    intersection = -plPlane(3) * l + cross3(plPlane, l_dash);\n    intersection(3) = dot3(plPlane, l);\n    return intersection;\n}\n\ntemplate <typename Function>\nvoid writeBufferToXYZFile(Buffer<float> &buffer, Buffer<uint8_t> &color, string filename, string deliminator, Function condFunc)\n{\n    std::vector<Point> points;\n    for (int j = 0; j < buffer.height(); j++)\n    {\n        for (int i = 0; i < buffer.width(); i++)\n        {\n            const auto x = buffer(i, j, 0);\n            const auto y = buffer(i, j, 1);\n            const auto z = buffer(i, j, 2);\n            uint8_t r = color(i, j, 0);\n            uint8_t g = color(i, j, 1);\n            uint8_t b = color(i, j, 2);\n            if (condFunc(x, y, z))\n            {\n                continue;\n            }\n            points.push_back({x, y, z, r, g, b});\n        }\n    }\n    std::ofstream outFile;\n    outFile.open(filename);\n    outFile << points.size() << \"\\n\";\n    const auto d = deliminator;\n    for (const auto &point : points)\n    {\n        outFile << point.x << d << point.y << d << point.z << d << point.r << d << point.g << d << point.b << \"\\n\";\n    }\n}\n\nbool conditionProjector(float x, float y, float z)\n{\n    return (x < -10.0f || x > 10.0f || y < -10.0f || y > 10.0f || z < -10.0f || z > 10.0f);\n}\n\nbool noCondition(float x, float y, float z)\n{\n    return false;\n}\n\nint main(int argc, char **argv)\n{\n    const float FOCAL_LEN = 36.1;\n    const float PX_DIM = 10 * 10e-6;\n    const bool POINT_CLOUD_GLOBAL_FRAME = true;\n    const bool POINT_CLOUD_PROJ_FRAME = true;\n    const string PROJECTOR_X_PNG = \"images/x-val-img.png\";\n    const string TRANSF_MAT_WORLD_TO_PROJ_CSV = \"matrices/transf-world-proj.csv\";\n    const string TRANSF_PROJ_CAM_CSV = \"matrices/transf-proj-cam.csv\";\n    const string INV_CAM_MAT_CSV = \"matrices/inv-cam-mat.csv\";\n    const string SAVE_DEPTH_IMAGE = \"images/depth_img.png\";\n    const string SAVE_XYZ_PROJ = \"pointclouds/proj.txt\";\n    const string SAVE_XYZ_WORLD = \"pointclouds/world.txt\";\n    const string NO_PROJECTOR_PNG = \"images/no-projector.png\";\n\n    Halide::Buffer<uint8_t> input = load_image(PROJECTOR_X_PNG);\n    const int HEIGHT = input.height();\n    const int WIDTH = input.width();\n\n    Matrix4h InvK = read4x4MatFromCSV(INV_CAM_MAT_CSV);\n    Matrix4h transMatProjToCam = read4x4MatFromCSV(TRANSF_PROJ_CAM_CSV);\n    Matrix4h transMatWorldToProj = read4x4MatFromCSV(TRANSF_MAT_WORLD_TO_PROJ_CSV);\n\n    cout << \"Tranformation Matrix World to Projector\" << endl;\n    cout << transMatWorldToProj << endl;\n\n    Vector4h px{x, y, 1.0f, 0.0f};\n\n    Vector4h normCam1 = InvK * px;\n    normCam1(3) = 1.0f;\n    Vector4h normCam2 = 2 * normCam1;\n    normCam2(3) = 1.0f;\n\n    Vector4h pointCam1 = transMatProjToCam * normCam1;\n    pointCam1 = pointCam1 / pointCam1(3);\n    Vector4h pointCam2 = transMatProjToCam * normCam2;\n    pointCam2 /= pointCam2(3);\n\n    const auto [camLine, camLineDash] = pluckerLine(pointCam1, pointCam2);\n    //Vector4h cameraLine = makeAxBzCLine(pointCam1, pointCam2);\n\n    Vector4h pxProj{input(x, y) / 255.0f * 1920.0f, 0.0f, 1.0f, 0.0f};\n    Vector4h normProj1 = InvK * pxProj;\n    normProj1 = normProj1 / normProj1(2);\n    normProj1(3) = 1.0f;\n    Vector4h normProj2{0.0f, 0.0f, 0.0f, 1.0f};\n    Vector4h normProj3{0.0f, 1.0f, 0.0f, 1.0f};\n\n    const auto [projLine, projLineDash] = pluckerLine(normProj2, normProj3);\n    Vector4h ProjPlane = pluckerPlane(projLine, projLineDash, normProj1);\n    Vector4h intersection = intersectionLinePlane(camLine, camLineDash, ProjPlane);\n    intersection = intersection / intersection(3);\n    intersection *= (input(x, y) > 0); // does this make sense?\n\n    Expr depth = intersection(3);\n\n    saveImage(depth, input.width(), input.height(), SAVE_DEPTH_IMAGE);\n\n    Halide::Buffer<uint8_t> color = load_image(NO_PROJECTOR_PNG);\n\n    if (POINT_CLOUD_PROJ_FRAME)\n    {\n        Func result;\n        result(x, y, c) = 0.0f;\n        result(x, y, 0) = intersection(0);\n        result(x, y, 1) = intersection(1);\n        result(x, y, 2) = intersection(2);\n\n        Buffer<float> output(input.width(), input.height(), 3);\n        result.realize(output);\n        writeBufferToXYZFile(output, color, SAVE_XYZ_PROJ, \";\", conditionProjector);\n    }\n    if (POINT_CLOUD_GLOBAL_FRAME)\n    {\n\n        Vector4h ptGlobalFrame = transMatWorldToProj * intersection;\n        Func result_w;\n        result_w(x, y, c) = 0.0f;\n        result_w(x, y, 0) = ptGlobalFrame(0);\n        result_w(x, y, 1) = ptGlobalFrame(1);\n        result_w(x, y, 2) = ptGlobalFrame(2);\n\n        Buffer<float> output_w(input.width(), input.height(), 3);\n        result_w.realize(output_w);\n        writeBufferToXYZFile(output_w, color, SAVE_XYZ_WORLD, \";\", conditionProjector);\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "be45d308bdc2052f0b09f370f4edd9e7e1fc4b60", "size": 9137, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "structured_light/cpp/generate-depth-image/generateDepthImg.cpp", "max_stars_repo_name": "olaals/prosjektoppgave", "max_stars_repo_head_hexsha": "048c5c01cf428846c76b1c27abd4c0f451056e03", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "structured_light/cpp/generate-depth-image/generateDepthImg.cpp", "max_issues_repo_name": "olaals/prosjektoppgave", "max_issues_repo_head_hexsha": "048c5c01cf428846c76b1c27abd4c0f451056e03", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "structured_light/cpp/generate-depth-image/generateDepthImg.cpp", "max_forks_repo_name": "olaals/prosjektoppgave", "max_forks_repo_head_hexsha": "048c5c01cf428846c76b1c27abd4c0f451056e03", "max_forks_repo_licenses": ["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.8233438486, "max_line_length": 128, "alphanum_fraction": 0.5963664222, "num_tokens": 3167, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.6513548714339144, "lm_q1q2_score": 0.48211616895815895}}
{"text": "/* --------------------------------------------------------------------------\n*\n* (C) Copyright \u2026\n*\n* ---------------------------------------------------------------------------\n*/\n\n/*!\n * @file Transform3DMatConvertersTest.cpp\n * @date 20/02/2018\n * @author Alessandro Bianco\n */\n\n/*!\n * @addtogroup CommonTests\n * \n * Testing conversion from cv Matrix to Transform3D and viceversa.\n * \n * \n * @{\n */\n\n/* --------------------------------------------------------------------------\n *\n * Includes\n *\n * --------------------------------------------------------------------------\n */\n#include <catch.hpp>\n#include <Converters/Transform3DToMatConverter.hpp>\n#include <Converters/MatToTransform3DConverter.hpp>\n#include <Types/CPP/Pose.hpp>\n#include <Errors/Assert.hpp>\n#include <boost/smart_ptr.hpp>\n#include <Eigen/Geometry>\n\nusing namespace Converters;\nusing namespace PoseWrapper;\nconst double EPSILON = 0.000000001;\n\nTEST_CASE( \"Mat to Transform 3D and Back\", \"[MatToTransform]\" )\n\t{\n\tMatToTransform3DConverter firstConverter;\n\tTransform3DToMatConverter secondConverter;\n\n\tEigen::Matrix4f inputTransform;\n\tEigen::Quaternionf inputRotation(std::cos(M_PI/2), std::sin(M_PI/2), std::sin(M_PI/2)/2, std::sin(M_PI/2)*2);\n\tEigen::Matrix3f eigenRotationMatrix = inputRotation.normalized().toRotationMatrix();\t\n\tinputTransform << \teigenRotationMatrix(0,0), eigenRotationMatrix(0,1), eigenRotationMatrix(0,2), 0.3,\n\t\t\t\teigenRotationMatrix(1,0), eigenRotationMatrix(1,1), eigenRotationMatrix(1,2), 0.4,\n\t\t\t\teigenRotationMatrix(2,0), eigenRotationMatrix(2,1), eigenRotationMatrix(2,2), 0.6,\n\t\t\t\t0, 0, 0, 1;\n\n\tcv::Mat cvInputTransform(3, 4, CV_32FC1);\n\tfor(unsigned row = 0; row<3; row++)\n\t\t{\n\t\tfor(unsigned column = 0; column < 4; column++)\n\t\t\t{\n\t\t\tcvInputTransform.at<float>(row, column) = inputTransform(row, column);\n\t\t\t}\n\t\t}\n\n\tTransform3DSharedConstPtr asnTransform3D = firstConverter.ConvertShared(cvInputTransform);\n\tREQUIRE( GetXPosition(*asnTransform3D) < inputTransform(0, 3) + EPSILON );\n\tREQUIRE( GetXPosition(*asnTransform3D) > inputTransform(0, 3) - EPSILON );\n\tREQUIRE( GetYPosition(*asnTransform3D) < inputTransform(1, 3) + EPSILON );\n\tREQUIRE( GetYPosition(*asnTransform3D) > inputTransform(1, 3) - EPSILON );\n\tREQUIRE( GetZPosition(*asnTransform3D) < inputTransform(2, 3) + EPSILON );\n\tREQUIRE( GetZPosition(*asnTransform3D) > inputTransform(2, 3) - EPSILON );\n\tREQUIRE( GetXOrientation(*asnTransform3D) < inputRotation.normalized().x() + EPSILON );\n\tREQUIRE( GetXOrientation(*asnTransform3D) > inputRotation.normalized().x() - EPSILON );\n\tREQUIRE( GetYOrientation(*asnTransform3D) < inputRotation.normalized().y() + EPSILON );\n\tREQUIRE( GetYOrientation(*asnTransform3D) > inputRotation.normalized().y() - EPSILON );\n\tREQUIRE( GetZOrientation(*asnTransform3D) < inputRotation.normalized().z() + EPSILON );\n\tREQUIRE( GetZOrientation(*asnTransform3D) > inputRotation.normalized().z() - EPSILON );\n\tREQUIRE( GetWOrientation(*asnTransform3D) < inputRotation.normalized().w() + EPSILON );\n\tREQUIRE( GetWOrientation(*asnTransform3D) > inputRotation.normalized().w() - EPSILON );\n\n\tcv::Mat outputTransform = secondConverter.ConvertShared(asnTransform3D);\n\tfor(unsigned rowIndex = 0; rowIndex < 3; rowIndex++)\n\t\t{\n\t\tfor(unsigned columnIndex = 0; columnIndex < 4; columnIndex++)\n\t\t\t{\n\t\t\tREQUIRE(outputTransform.at<float>(rowIndex, columnIndex) < inputTransform(rowIndex, columnIndex) + EPSILON);\n\t\t\tREQUIRE(outputTransform.at<float>(rowIndex, columnIndex) > inputTransform(rowIndex, columnIndex) - EPSILON);\n\t\t\t}\n\t\t}\n\n\tasnTransform3D.reset();\n\t} \n\nTEST_CASE( \"Transform3D to Mat and Back\", \"[Transform3DToMat]\" )\n\t{\n\tMatToTransform3DConverter firstConverter;\n\tTransform3DToMatConverter secondConverter;\n\n\tEigen::Matrix4f inputTransform;\n\tEigen::Quaternionf inputRotation(std::cos(M_PI/2), std::sin(M_PI/2), std::sin(M_PI/2)/2, std::sin(M_PI/2)*2);\n\tEigen::Matrix3f eigenRotationMatrix = inputRotation.normalized().toRotationMatrix();\t\n\tinputTransform << \teigenRotationMatrix(0,0), eigenRotationMatrix(0,1), eigenRotationMatrix(0,2), 0.3,\n\t\t\t\teigenRotationMatrix(1,0), eigenRotationMatrix(1,1), eigenRotationMatrix(1,2), 0.4,\n\t\t\t\teigenRotationMatrix(2,0), eigenRotationMatrix(2,1), eigenRotationMatrix(2,2), 0.6,\n\t\t\t\t0, 0, 0, 1;\n\n\tcv::Mat cvInputTransform(3, 4, CV_32FC1);\n\tfor(unsigned row = 0; row<3; row++)\n\t\t{\n\t\tfor(unsigned column = 0; column < 4; column++)\n\t\t\t{\n\t\t\tcvInputTransform.at<float>(row, column) = inputTransform(row, column);\n\t\t\t}\n\t\t}\n\n\tTransform3DSharedConstPtr asnTransform3D = firstConverter.ConvertShared(cvInputTransform);\n\tcv::Mat intermediateTransform = secondConverter.ConvertShared(asnTransform3D);\n\tTransform3DSharedConstPtr outputTransform = firstConverter.ConvertShared(intermediateTransform);\n\n\tREQUIRE( GetXPosition(*asnTransform3D) < GetXPosition(*outputTransform) + EPSILON );\n\tREQUIRE( GetXPosition(*asnTransform3D) > GetXPosition(*outputTransform) - EPSILON );\n\tREQUIRE( GetYPosition(*asnTransform3D) < GetYPosition(*outputTransform) + EPSILON );\n\tREQUIRE( GetYPosition(*asnTransform3D) > GetYPosition(*outputTransform) - EPSILON );\n\tREQUIRE( GetZPosition(*asnTransform3D) < GetZPosition(*outputTransform) + EPSILON );\n\tREQUIRE( GetZPosition(*asnTransform3D) > GetZPosition(*outputTransform) - EPSILON );\n\tREQUIRE( GetXOrientation(*asnTransform3D) < GetXOrientation(*outputTransform) + EPSILON );\n\tREQUIRE( GetXOrientation(*asnTransform3D) > GetXOrientation(*outputTransform) - EPSILON );\n\tREQUIRE( GetYOrientation(*asnTransform3D) < GetYOrientation(*outputTransform) + EPSILON );\n\tREQUIRE( GetYOrientation(*asnTransform3D) > GetYOrientation(*outputTransform) - EPSILON );\n\tREQUIRE( GetZOrientation(*asnTransform3D) < GetZOrientation(*outputTransform) + EPSILON );\n\tREQUIRE( GetZOrientation(*asnTransform3D) > GetZOrientation(*outputTransform) - EPSILON );\n\tREQUIRE( GetWOrientation(*asnTransform3D) < GetWOrientation(*outputTransform) + EPSILON );\n\tREQUIRE( GetWOrientation(*asnTransform3D) > GetWOrientation(*outputTransform) - EPSILON );\n\n\tasnTransform3D.reset();\n\toutputTransform.reset();\n\t} \n\nTEST_CASE(\"Bad Transform conversion 1 (Mat)\", \"[Bad Transform 1]\")\n\t{\n\tMatToTransform3DConverter firstConverter;\n\n\tEigen::Matrix4f inputTransform;\n\tinputTransform << 0.3, 0.2, 0.1, 0.4, 0.3, 0.2, 0.1, 0.1, 0.5, 0.3, 0.2, 0.1, 1, 0, 0, 1;\n\n\tcv::Mat cvInputTransform(3, 4, CV_32FC1);\n\tfor(unsigned row = 0; row<3; row++)\n\t\t{\n\t\tfor(unsigned column = 0; column < 4; column++)\n\t\t\t{\n\t\t\tcvInputTransform.at<float>(row, column) = inputTransform(row, column);\n\t\t\t}\n\t\t}\n\n\tREQUIRE_THROWS( firstConverter.ConvertShared(cvInputTransform) );\n\t}\n\nTEST_CASE(\"Bad Transform conversion 2 (Mat)\", \"[Bad Transform 2]\")\n\t{\n\tMatToTransform3DConverter firstConverter;\n\n\tEigen::Matrix4f inputTransform;\n\tinputTransform << 0.3, 0.2, 0.1, 0.4, 0.3, 0.2, 0.1, 0.1, 0.5, 0.3, 0.2, 0.1, 0, 0, 0, 1;\n\n\tcv::Mat cvInputTransform(3, 4, CV_32FC1);\n\tfor(unsigned row = 0; row<3; row++)\n\t\t{\n\t\tfor(unsigned column = 0; column < 4; column++)\n\t\t\t{\n\t\t\tcvInputTransform.at<float>(row, column) = inputTransform(row, column);\n\t\t\t}\n\t\t}\n\n\tREQUIRE_THROWS( firstConverter.ConvertShared(cvInputTransform) );\n\t}\n", "meta": {"hexsha": "d7d611b737113e7351f4969589a6ffcb882a66b5", "size": 7091, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tests/UnitTests/Common/Converters/Transform3DMatConvertersTest.cpp", "max_stars_repo_name": "H2020-InFuse/cdff", "max_stars_repo_head_hexsha": "e55fd48f9a909d0c274c3dfa4fe2704bc5071542", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-02-26T15:09:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-30T07:39:01.000Z", "max_issues_repo_path": "Tests/UnitTests/Common/Converters/Transform3DMatConvertersTest.cpp", "max_issues_repo_name": "H2020-InFuse/cdff", "max_issues_repo_head_hexsha": "e55fd48f9a909d0c274c3dfa4fe2704bc5071542", "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": "Tests/UnitTests/Common/Converters/Transform3DMatConvertersTest.cpp", "max_forks_repo_name": "H2020-InFuse/cdff", "max_forks_repo_head_hexsha": "e55fd48f9a909d0c274c3dfa4fe2704bc5071542", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-06T12:09:05.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-06T12:09:05.000Z", "avg_line_length": 40.7528735632, "max_line_length": 111, "alphanum_fraction": 0.704414046, "num_tokens": 2008, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.6513548714339144, "lm_q1q2_score": 0.48211616895815895}}
{"text": "//#include <bits/stdc++.h>\n\n#include <algorithm>\n#include <chrono>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <numeric>\n#include <vector>\n#include \"time.h\"\n\n#include <Eigen/Dense>\n#include <Eigen/Core>\n#include <Eigen/LU>\n#include <Eigen/SVD>\n#include <Eigen/QR>\n\n#include <Spectra/SymEigsSolver.h>\n\n#include \"alstructure.h\"\n#include \"config.h\"\n#include \"storage.h\"\n\nstruct timespec t0;\n\n\n// https://stackoverflow.com/questions/34247057/how-to-read-csv-file-and-assign-to-eigen-matrix\ntemplate<typename M>\nM load_tsv (const std::string & path) {\n\tstd::ifstream indata;\n\tindata.open(path);\n\tstd::string line;\n\tstd::vector<double> values;\n\tint rows = 0;\n\twhile (std::getline(indata, line)) {\n\t\tstd::stringstream lineStream(line);\n\t\tstd::string cell;\n\t\twhile (std::getline(lineStream, cell, '\\t')) {\n\t\t\tvalues.push_back(std::stod(cell));\n\t\t}\n\t\t++rows;\n\t}\n\treturn Eigen::Map<const Eigen::Matrix<typename M::Scalar, M::RowsAtCompileTime, M::ColsAtCompileTime, Eigen::RowMajor>>(values.data(), rows, values.size()/rows);\n}\n\ntemplate<typename M>\nM read_plink_freq_file (const std::string &path, int k) {\n\t/*\n\tReads from plink.frq.strat file to initialize P matrix\n\tReturns rows/k x k matrix, where rows in number of rows\n\t\tin file\n\t*/\n        std::ifstream indata;\n        indata.open(path);\n        std::string line;\n        std::vector<double> values;\n        int rows = 1;\n        std::getline(indata, line);\n        while (std::getline(indata, line)) {\n                std::stringstream lineStream(line);\n                std::string cell;\n                std::vector<std::string> seglist;\n                while (lineStream >> cell){\n                        seglist.push_back(cell);\n                }\n                values.push_back(1-std::stod(seglist[5]));\n                ++rows;\n        }\n        return Eigen::Map<const Eigen::Matrix<typename M::Scalar, M::RowsAtCompileTime, M::ColsAtCompileTime, Eigen::RowMajor>>(values.data(), rows/k, k);\n}\n\n\ndouble fix_interval(double x) {\n\t/* Random function in Eigen generates numbers from a \n\t * uniform distribution on the interval [-1, 1].\n\t * We need to map these values to the interval [0, 1].\n\t * To map x in [a, b] to [c, d]\n\t * f(x) = c + ((d-c)/(b-a)) * (x-a)\n\t */\n\treturn (0.5 * (x + 1.0));\n}\n\n\ndouble divide_by_two(double x) {\n\treturn x / 2.0;\n}\n\n\ndouble truncate_with_epsilon(double x) {\n\tdouble epsilon = 0.0000000001;\n\tif (x <= 0.0)\n\t\treturn epsilon;\n\tif (x >= 1.0)\n\t\treturn 1.0 - epsilon;\n\treturn x;\n}\n\n\ndouble truncate_xxx(double x) {\n\tif (x < 0.0)\n\t\treturn 0.0;\n\tif (x > 1.0)\n\t\treturn 1.0;\n\treturn x;\n}\n\n\nvoid project_onto_simplex(std::vector<double> &data) {\n\tstd::vector<size_t> inds(data.size());\n\n\tstd::iota(inds.begin(), inds.end(), 0);\n\n\tstd::stable_sort(inds.begin(), inds.end(), [&data](size_t i, size_t j) { return data[i] > data[j]; });\n\n\tdouble tmpsum = 0;\n\tdouble tmax;\n\tbool bget = false;\n\n\tfor (int i = 1; i < data.size(); i++) {\n\t\ttmpsum = tmpsum + data[inds[i - 1]];\n\t\ttmax = (tmpsum - 1.0) / i;\n\t\tif (tmax >= data[inds[i]]) {\n\t\t\tbget = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (!(bget)) {\n\t\ttmpsum = tmpsum + data[inds[data.size() - 1]];\n\t\ttmax = (tmpsum - 1) / data.size();\n\t}\n\n\tfor (int i = 0; i < data.size(); i++) {\n\t\tdata[i] = data[i] - tmax;\n\t\tif (data[i] < 0.0) {\n\t\t\tdata[i] = 0.0;\n\t\t}\n\t}\n}\n\n\nALStructure::ALStructure(int argc, char const *argv[]) {\n\t// Set default values\n\tcommand_line_opts.num_of_evec = 5;\n\tcommand_line_opts.debugmode = false;\n\tcommand_line_opts.OUTPUT_PATH = \"scope_\";\n\tbool got_genotype_file = false;\n\tbool got_rowspace_file = false;\n\tbool got_freq_file = false;\n\tcommand_line_opts.convergence_limit = 0.00001;  // Used by R code\n\tcommand_line_opts.max_iterations = 1000;        // Used by R code\n\tcommand_line_opts.memory_efficient = false;\n\tcommand_line_opts.fast_mode = true;\n\tcommand_line_opts.missing = false;\n\tcommand_line_opts.text_version = false;\n\tcommand_line_opts.fhat_version = false;\n\tcommand_line_opts.fhattrunc_version = false;\n\tcommand_line_opts.nthreads = 1;\n\tcommand_line_opts.seed = -1;\n\tcommand_line_opts.given_seed = false;\n\tnops = 1;\n\n\n\tif (argc < 3) {\n\t\tprintCorrectUsage();\n\t\t//std::cout << \"Correct Usage is \" << argv[0] << \" -p <parameter file>\" << std::endl;\n\t\texit(-1);\n\t}\n\n\tif (strcmp(argv[1], \"-p\") == 0) {\n\t\t// Read arguments from configuration file\n\t\tstd::string cfg_filename = std::string(argv[2]);\n\t\tConfigFile cfg(cfg_filename);\n\t\tgot_genotype_file = cfg.keyExists(\"genotype\");\n\t\tcommand_line_opts.num_of_evec = cfg.getValueOfKey<int>(\"num_evec\", 5);\n\t\tcommand_line_opts.max_iterations = cfg.getValueOfKey<int>(\"max_iterations\", command_line_opts.num_of_evec + 2);\n\t\tcommand_line_opts.debugmode = cfg.getValueOfKey<bool>(\"debug\", false);\n\t\tcommand_line_opts.OUTPUT_PATH = cfg.getValueOfKey<std::string>(\"output_path\", std::string(\"fastppca_\"));\n\t\tcommand_line_opts.GENOTYPE_FILE_PATH = cfg.getValueOfKey<std::string>(\"genotype\", std::string(\"\"));\n\t\tcommand_line_opts.convergence_limit = cfg.getValueOfKey<double>(\"convergence_limit\", -1.0);\n\t\tcommand_line_opts.memory_efficient = cfg.getValueOfKey<bool>(\"memory_efficient\", false);\n\t\tcommand_line_opts.fast_mode = cfg.getValueOfKey<bool>(\"fast_mode\", true);\n\t\tcommand_line_opts.missing = cfg.getValueOfKey<bool>(\"missing\", false);\n\t\tcommand_line_opts.text_version = cfg.getValueOfKey<bool>(\"text_version\", false);\n\t\tcommand_line_opts.nthreads = cfg.getValueOfKey<int>(\"nthreads\", 1);\n\t\tcommand_line_opts.seed = cfg.getValueOfKey<int>(\"seed\", -1);\n\t\tcommand_line_opts.given_seed = command_line_opts.seed >= 0 ? true: false;\n\t} else {\n\t\t// Read arguments from standard input\n\t\tbool got_max_iter = false;\n\t\tfor (int i = 1; i < argc; i++) {\n\t\t\tif (i + 1 != argc) {\n\t\t\t\tif (strcmp(argv[i], \"-g\") == 0) {\n\t\t\t\t\tcommand_line_opts.GENOTYPE_FILE_PATH = std::string(argv[i+1]);\n\t\t\t\t\tgot_genotype_file = true;\n\t\t\t\t\ti++;\n\t\t\t\t} else if (strcmp(argv[i], \"-r\") == 0) {\n\t\t\t\t\tcommand_line_opts.ROWSPACE_FILE_PATH = std::string(argv[i+1]);\n\t\t\t\t\tgot_rowspace_file = true;\n\t\t\t\t\ti++;\n\t\t\t\t} else if (strcmp(argv[i], \"-freq\") == 0) {\n\t\t\t\t\tcommand_line_opts.FREQ_FILE_PATH = std::string(argv[i+1]);\n\t\t\t\t\tgot_freq_file = true;\n\t\t\t\t\ti++;\n\t\t\t\t} else if (strcmp(argv[i], \"-i\") == 0) {\n\t\t\t\t\tcommand_line_opts.INITIAL_FILE_PATH = std::string(argv[i+1]);\n\t\t\t\t\ti++;\n\t\t\t\t} else if (strcmp(argv[i], \"-o\") == 0) {\n\t\t\t\t\tcommand_line_opts.OUTPUT_PATH = std::string(argv[i+1]);\n\t\t\t\t\ti++;\n\t\t\t\t} else if (strcmp(argv[i], \"-k\") == 0) {\n\t\t\t\t\tcommand_line_opts.num_of_evec = atoi(argv[i+1]);\n\t\t\t\t\ti++;\n\t\t\t\t} else if (strcmp(argv[i], \"-m\") == 0) {\n\t\t\t\t\tcommand_line_opts.max_iterations = atoi(argv[i+1]);\n\t\t\t\t\tgot_max_iter = true;\n\t\t\t\t\ti++;\n\t\t\t\t} else if (strcmp(argv[i], \"-nt\") == 0) {\n\t\t\t\t\tcommand_line_opts.nthreads = atoi(argv[i+1]);\n\t\t\t\t\ti++;\n\t\t\t\t} else if (strcmp(argv[i], \"-seed\") == 0) {\n\t\t\t\t\tcommand_line_opts.seed = atoi(argv[i+1]);\n\t\t\t\t\tcommand_line_opts.given_seed = command_line_opts.seed >= 0 ? true: false;\n\t\t\t\t\ti++;\n\t\t\t\t} else if (strcmp(argv[i], \"-cl\") == 0) {\n\t\t\t\t\tcommand_line_opts.convergence_limit = atof(argv[i+1]);\n\t\t\t\t\ti++;\n\t\t\t\t} else if (strcmp(argv[i], \"-v\") == 0) {\n\t\t\t\t\tcommand_line_opts.debugmode = true;\n\t\t\t\t} else if (strcmp(argv[i], \"-mem\") == 0) {\n\t\t\t\t\tcommand_line_opts.memory_efficient = true;\n\t\t\t\t} else if (strcmp(argv[i], \"-miss\") == 0) {\n\t\t\t\t\tcommand_line_opts.missing = true;\n\t\t\t\t} else if (strcmp(argv[i], \"-nfm\") == 0) {\n\t\t\t\t\tcommand_line_opts.fast_mode = false;\n\t\t\t\t} else if (strcmp(argv[i], \"-txt\") == 0) {\n\t\t\t\t\tcommand_line_opts.text_version = true;\n\t\t\t\t} else if (strcmp(argv[i], \"-fhat\") == 0) {\n\t\t\t\t\tcommand_line_opts.fhat_version = true;\n\t\t\t\t} else if (strcmp(argv[i], \"-fhattrunc\") == 0) {\n\t\t\t\t\tcommand_line_opts.fhattrunc_version = true;\n\t\t\t\t} else {\n\t\t\t\t\tstd::cout << \"Not Enough or Invalid arguments\" << std::endl;\n\t\t\t\t\tprintCorrectUsage();\n\t\t\t\t\texit(-1);\n\t\t\t\t}\n\t\t\t} else if (strcmp(argv[i], \"-v\") == 0) {\n\t\t\t\tcommand_line_opts.debugmode = true;\n\t\t\t} else if (strcmp(argv[i], \"-mem\") == 0) {\n\t\t\t\tcommand_line_opts.memory_efficient = true;\n\t\t\t} else if (strcmp(argv[i], \"-nfm\") == 0) {\n\t\t\t\tcommand_line_opts.fast_mode = false;\n\t\t\t} else if (strcmp(argv[i], \"-miss\") == 0) {\n\t\t\t\tcommand_line_opts.missing = true;\n\t\t\t} else if (strcmp(argv[i], \"-txt\") == 0) {\n\t\t\t\tcommand_line_opts.text_version = true;\n\t\t\t} else if (strcmp(argv[i], \"-fhat\") == 0) {\n\t\t\t\tcommand_line_opts.fhat_version = true;\n\t\t\t} else if (strcmp(argv[i], \"-fhattrunc\") == 0) {\n\t\t\t\tcommand_line_opts.fhattrunc_version = true;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (got_genotype_file == false) {\n\t\tstd::cout << \"Genotype file missing\" << std::endl;\n\t\tprintCorrectUsage();\n\t\texit(-1);\n\t}\n}\n\n\nvoid ALStructure::printCorrectUsage(void) {\n\tstd::cout << \"SCOPE Options:\\n\"\n\t\t\t  << \"-g <genotype file> Path to PLINK binary prefix\\n\"\n\t\t\t  << \"-k <latent dimension> Number of latent population (default: 5)\\n\"\n\t\t\t  << \"-m <max iterations> Maximum number of iterations for ALS (default: 1000)\\n\"\n\t\t\t  << \"-cl <convergence limit> Convergence threshold for LSE and ALS (default: 0.00001)\\n\"\n\t\t\t  << \"-nt <number of threads> Number of threads to use (default: 1)\\n\"\n       \t\t\t  << \"-seed <seed> Seed to use (default: system time)\\n\"\n\t\t\t  << \"-freq <frequency file> Path to PLINK frequency file for supervision (default: none)\\n\"\n\t\t\t  << \"-o <output_path> Output prefix (default: scope_)\\n\";\n}\n\n\nvoid ALStructure::solve_for_Qhat() {\n\tif (fhat_version || fhattrunc_version) {\n\t\tQhat = (((Phat.transpose() * Phat).inverse() * Phat.transpose()) * Fhat);\n\t}\n\n\tMatrixXdr temp_kxp(k, p);\n\ttemp_kxp = ((Phat.transpose() * Phat).inverse()) * Phat.transpose();\n\n\t// temp_kxn = temp_kxp * X, where X is the p X n genotype matrix\n\tMatrixXdr temp_kxn(k, n);\n\tmm.multiply_y_post(temp_kxp, k, temp_kxn, false);\n\n\ttemp_kxn = temp_kxn.unaryExpr(&divide_by_two);\n\n\tQhat = (temp_kxn * V) * V.transpose();\n}\n\n\nvoid ALStructure::solve_for_Phat() {\n\tif (fhat_version || fhattrunc_version) {\n\t\tPhat = (Fhat * (Qhat.transpose() * (( Qhat * Qhat.transpose() ).inverse()) ));\n\t}\n\n\tMatrixXdr temp_nxk(n, k);\n\ttemp_nxk = V * (V.transpose() * ((Qhat.transpose() * (Qhat * Qhat.transpose()).inverse())));\n\n\tmm.multiply_y_pre(temp_nxk, k, Phat, false);\n\n\tPhat = Phat.unaryExpr(&divide_by_two);\n}\n\n\nvoid ALStructure::initialize(std::default_random_engine &prng_eng) {\n\tif (!command_line_opts.given_seed) {\n\t\tseed = static_cast<unsigned int>(time(NULL));\n\t}\n\n\tstd::cout << \"Initializing Phat using seed \" << seed << std::endl;\n\n\t// srand(seed);\n\tprng_eng.seed(seed);\n\n\t// Phat = MatrixXdr::Random(p, k);\n\t// Phat = Phat.unaryExpr(&fix_interval);\n\tstd::uniform_real_distribution<double> dis(0, 1);\n\tPhat = MatrixXdr::Zero(p, k).unaryExpr([&](float dummy){return dis(prng_eng);});\n\n\tif (debug) write_matrix(Phat, std::string(\"Phat_0_\") + std::to_string(seed) +  std::string(\".txt\"));\n}\n\n\nvoid ALStructure::truncated_alternating_least_squares(bool projection_mode) {\n\n\tif (projection_mode){\n\t\tstd::cout << \"Solving for Q using provided frequencies\" << std::endl;\n\t\tsolve_for_Qhat();\n\t\tstd::vector<double> col;\n\t\tcol.resize(k);\n\t\tfor (int c_iter = 0; c_iter < n; c_iter++) {\n \t\t\t//VectorXd::Map(&col[0], d) = Qhat.col(c_iter);\n\t\t\tfor (int r_iter = 0; r_iter < k; r_iter++) {\n\t\t\t\tcol[r_iter] = Qhat(r_iter, c_iter);\n\t\t\t}\n\n\t\t\tproject_onto_simplex(col);\n\n\t\t\tfor (int r_iter = 0; r_iter < k; r_iter++) {\n\t\t\t\tQhat(r_iter, c_iter) = col[r_iter];\n\t\t\t}\n\t\t}\n\t\treturn;\n\t}\n\n\tsolve_for_Qhat();\n\tif (debug) write_matrix(Qhat, std::string(\"Qhat_0.txt\"));\n\n\tsolve_for_Phat();\n\tif (debug) write_matrix(Phat, std::string(\"Phat_1.txt\"));\n\n\tfor (niter = 1; niter < MAX_ITER; niter++) {\n\t\tQhat_old = Qhat;\n\n\t\tsolve_for_Qhat();\n\t\tif (debug) write_matrix(Qhat, std::string(\"Qhat_\" + std::to_string(niter) + \".txt\"));\n\n\t\tstd::vector<double> col;\n\t\tcol.resize(k);\n\t\tfor (int c_iter = 0; c_iter < n; c_iter++) {\n \t\t\t//VectorXd::Map(&col[0], d) = Qhat.col(c_iter);\n\t\t\tfor (int r_iter = 0; r_iter < k; r_iter++) {\n\t\t\t\tcol[r_iter] = Qhat(r_iter, c_iter);\n\t\t\t}\n\n\t\t\tproject_onto_simplex(col);\n\n\t\t\tfor (int r_iter = 0; r_iter < k; r_iter++) {\n\t\t\t\tQhat(r_iter, c_iter) = col[r_iter];\n\t\t\t}\n\t\t}\n\t\tif (debug) write_matrix(Qhat, std::string(\"Qhat_\" + std::to_string(niter) + \"_w_constraints.txt\"));\n\n\t\tsolve_for_Phat();\n\t\tif (debug) write_matrix(Phat, std::string(\"Phat_\" + std::to_string(niter+1) + \".txt\"));\n\n\t\tPhat = Phat.unaryExpr(&truncate_with_epsilon);\n\t\tif (debug) write_matrix(Phat, std::string(\"Phat_\" + std::to_string(niter+1) + \"_w_constraints.txt\"));\n\n\t\tdiff = Qhat - Qhat_old;\n \t\trmse = diff.norm() / sqrt(n * k);\n\t\tstd::cout << \"Iteration \" << niter+1 << \"  -- RMSE \" << std::setprecision(15) << rmse << std::endl;\n\t\tif ((rmse <= convergence_limit) || std::isnan(rmse)) {\n\t\t\tstd::cout << \"Breaking after \" << niter+1 << \" iterations\" << std::endl;\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\n\nvoid ALStructure::write_matrix(MatrixXdr &mat, const std::string file_name) {\n\tstd::ofstream fp;\n\tfp.open((command_line_opts.OUTPUT_PATH + file_name).c_str());\n\tfp << std::setprecision(15) << mat << std::endl;\n\tfp.close();\n}\n\nvoid ALStructure::write_matrix_maf(MatrixXdr &mat, const std::string file_name) {\n        std::ofstream fp;\n        fp.open((command_line_opts.OUTPUT_PATH + file_name).c_str());\n        fp << std::setprecision(15) << 1 - mat.array() << std::endl;\n        fp.close();\n}\n\nvoid ALStructure::write_vector(Eigen::VectorXd &vec, const std::string file_name) {\n\tstd::ofstream fp;\n\tfp.open((command_line_opts.OUTPUT_PATH + file_name).c_str());\n\tfp << std::setprecision(15) << vec << std::endl;\n\tfp.close();\n}\n\nint ALStructure::run() {\n\n\ttotal_begin = clock();\n\n\tmemory_efficient = command_line_opts.memory_efficient;\n\ttext_version = command_line_opts.text_version;\n\tfhat_version = command_line_opts.fhat_version;\n\tfhattrunc_version = command_line_opts.fhattrunc_version;\n\tfast_mode = command_line_opts.fast_mode;\n\tmissing = command_line_opts.missing;\n\tMAX_ITER =  command_line_opts.max_iterations;\n\tconvergence_limit = command_line_opts.convergence_limit;\n\tdebug = command_line_opts.debugmode;\n\tnthreads = command_line_opts.nthreads;\n\toutput_path = std::string(command_line_opts.OUTPUT_PATH);\n\tseed = command_line_opts.seed;\n\n\tauto start = std::chrono::system_clock::now();\n\n\tclock_t io_begin = clock();\n\tclock_gettime(CLOCK_REALTIME, &t0);\n\n\t// Read genotype matrix X\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\t} else {\n\t\t\tg.read_txt_naive(command_line_opts.GENOTYPE_FILE_PATH, missing);\n\t\t}\n\t} else {\n\t\tg.read_plink(command_line_opts.GENOTYPE_FILE_PATH, missing, fast_mode);\n\t}\n\n\tp = g.Nsnp;\n\tn = g.Nindv;\n\tk = command_line_opts.num_of_evec;\n\n\t// TODO: Implement these codes.\n\tif (missing) {\n\t\tstd::cout << \"Missing version not yet implemented!\" << std::endl;\n\t\texit(-1);\n\t}\n\n\tif (fast_mode && memory_efficient) {\n\t\tstd::cout << \"Memory effecient version for mailman EM not yet implemented\" << std::endl;\n\t\tstd::cout << \"Ignoring Memory effecient Flag\" << std::endl;\n\t}\n\n\tif (!fast_mode && !memory_efficient) {\n\t\tgeno_matrix.resize(p, n);\n\t\tg.generate_eigen_geno(geno_matrix, false, false);\n\t\tif (debug) write_matrix(geno_matrix, \"X.txt\");\n\t}\n\n\tclock_t io_end = clock();\n\n\tstd::cout << \"Running on Dataset of \" << p << \" SNPs and \" << n << \" Individuals\" << std::endl;\n\n\t#if SSE_SUPPORT == 1\n\t\tif (fast_mode)\n\t\t\tstd::cout << \"Using Optimized SSE FastMultiply\" << std::endl;\n\t#endif\n\n\tclock_t it_begin = clock();\n\n\tmm = MatMult(g, geno_matrix, debug, false, memory_efficient, missing, fast_mode, nthreads, k);\n\n\tif (std::string(command_line_opts.ROWSPACE_FILE_PATH) != \"\") {\n\t\tstd::cout << \"Using provided V\" << std::endl;\n\n\t// Read eigenvectors of the n x n matrix: G = (1/m) * (X^T X - D)\n\t\tV = load_tsv<MatrixXdr>(command_line_opts.ROWSPACE_FILE_PATH);\n\t\tif (k != V.cols()) {\n\t\t\tk = V.cols();\n\t\t\tstd::cout << \"Mismatch between column number of provided V and provided k!\" << std::endl;\n\t\t\tstd::cout << \"Changing k to number of columns in V\" << std::endl;\n\t\t}\n\n\t\tif (V.rows() != n) {\n\t\t\tstd::cout << \"Dimensions of genotype matrix and rowspace matrix do not agree!\" << std::endl;\n\t\t\texit(-1);\n\t\t}\n\t} else {\n\t\tstd::cout << \"Performing latent subspace estimation\" << std::endl;\n\n\t\t// Calculate D matrix\n\t\tD.resize(g.Nindv);\n\t\tfor (int i = 0; i < g.Nindv; ++i) {\n\t\t\tD[i] =  2 * g.rowsum[i] - g.rowsqsum[i];\n\t\t}\n\t\tif (debug) write_vector(D, \"D.txt\");\n\n\t\t// Calculate V\n\t\tSpectra::SymEigsSolver<double, Spectra::LARGEST_ALGE, ALStructure> eigs(this, k, k * 2 + 1);\n\t\teigs.init();\n\t\teigs.compute(MAX_ITER, convergence_limit);\n\n\t\tif (eigs.info() == Spectra::SUCCESSFUL) {\n\t\t\tV = eigs.eigenvectors();\n\t\t\twrite_matrix(V, \"V.txt\");\n\t\t\tif (debug) {\n\t\t\t\tEigen::VectorXd evals = eigs.eigenvalues().array() / (n-1);\n\t\t\t\twrite_vector(evals, \"evals.txt\");\n\t\t\t}\n\t\t\tstd::cout << \"Latent subspace esimation completed after \" << nops << \" iterations\" << std::endl;\n\t\t}\n\t\telse {\n\t\t\tthrow new std::runtime_error(\n\t\t\t\tstd::string(\"Spectra eigendecomposition unsucessful\") + \", status\" + std::to_string(eigs.info())\n\t\t\t);\n\t\t}\n\t}\n\n\t// Compute Fhat = (1/2) * (X V V^T)\n\tif (fhat_version || fhattrunc_version) {\n\t\tstd::cout << \"Explicitly computing Fhat\";\n\t\tMatrixXdr temp_pxk(p, k);\n\t\tmm.multiply_y_pre(V, k, temp_pxk, false);\n\n\t\t// if (debug) write_matrix(temp_pxk, \"XV.txt\");\n\n\t\tFhat = temp_pxk * V.transpose();\n\t\tFhat = Fhat.unaryExpr(&divide_by_two);\n\t\tif (debug) write_matrix(Fhat, \"Fhat.txt\");\n\n\t\tif (command_line_opts.fhattrunc_version) {\n\t\t\tstd::cout << \" -- truncated\";\n\t\t\tFhat = Fhat.unaryExpr(&truncate_xxx);\n\t\t\tif (debug) write_matrix(Fhat, \"Fhat_truncated.txt\");\n\t\t}\n\t\tstd::cout << std::endl;\n\t}\n\n\t// Create pseudo random number generator (PRNG) engine\n\tstd::default_random_engine prng_eng{};\n\n\tif (std::string(command_line_opts.INITIAL_FILE_PATH) != \"\") {\n\t\tstd::cout << \"Using initial Phat provided\" << std::endl; \n\t\tPhat = load_tsv<MatrixXdr>(command_line_opts.INITIAL_FILE_PATH);\n\t} \n\telse if (std::string(command_line_opts.FREQ_FILE_PATH) != \"\"){\n\t\tPhat = read_plink_freq_file<MatrixXdr>(command_line_opts.FREQ_FILE_PATH,k);\n\t\tMAX_ITER = 1;\n\t}\n\telse {\n\t\tinitialize(prng_eng);\n\t}\n\n\tif (std::string(command_line_opts.FREQ_FILE_PATH) != \"\"){\n\t\ttruncated_alternating_least_squares(true);\n\t}\n\telse {\n\t\ttruncated_alternating_least_squares();\n\n\t\t// Try restarting with new seed!\n\t\tif (std::isnan(rmse) && (std::string(command_line_opts.INITIAL_FILE_PATH) == \"\")) {\n\t\t\tcommand_line_opts.given_seed = false;\n\t\t\tfor (int xx = 0; xx < 5; xx++) {\n\t\t\t\tinitialize(prng_eng);\n\t\t\t\ttruncated_alternating_least_squares();\n\t\t\t\tif (!std::isnan(rmse)) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tclock_t it_end = clock();\n\n\twrite_matrix_maf(Phat, \"Phat.txt\");\n\twrite_matrix(Qhat, \"Qhat.txt\");\n\n\tmm.clean_up();\n\n\tclock_t total_end = clock();\n\tdouble io_time = static_cast<double>(io_end - io_begin) / CLOCKS_PER_SEC;\n\t//double avg_it_time = static_cast<double>(it_end - it_begin) / (MAX_ITER * 1.0 * CLOCKS_PER_SEC);\n\tdouble total_time = static_cast<double>(total_end - total_begin) / CLOCKS_PER_SEC;\n\tstd::cout << \"Completed!\" << std::endl;\n\tstd::cout << \"IO Time:  \" << io_time << std::endl;\n\tstd::cout << \"Total runtime:   \" << total_time << std::endl;\n\n\tstd::chrono::duration<double> wctduration = std::chrono::system_clock::now() - start;\n\tstd::cout << \"Wall clock time = \" <<  wctduration.count() << std::endl;\n\n\treturn 0;\n}\n\nunsigned int ALStructure::cols() {\n\treturn n;\n}\n\nunsigned int ALStructure::rows() {\n\treturn n;\n}\n\nvoid ALStructure::perform_op(const double* x_in, double* y_out) {\n\t// Performs ((Xv)^T X)^T - Dv\n\tMatrixXdr x = Eigen::Map<const Eigen::VectorXd> (x_in, n);\n\tEigen::Map<Eigen::VectorXd> y(y_out, n);\n\n\tMatrixXdr temp_px1(p,1);\n\tmm.multiply_y_pre(x,1,temp_px1,false);\n\ttemp_px1.transposeInPlace(); // 1xp\n\n\tMatrixXdr temp_1xn(1,n);\n\tmm.multiply_y_post(temp_px1,1,temp_1xn,false);\n\n\ty.noalias() = temp_1xn.transpose() - D.cwiseProduct(x);\n\tnops++;\n}\n", "meta": {"hexsha": "d5600a2339db56f9beab57d52725ff79d3bda1a9", "size": 19679, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/alstructure.cpp", "max_stars_repo_name": "ekmolloy/ProPCA", "max_stars_repo_head_hexsha": "30f95e605b430252d4d09dd26a1abc8616f5d31d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-04-14T21:49:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T13:08:14.000Z", "max_issues_repo_path": "src/alstructure.cpp", "max_issues_repo_name": "ekmolloy/ProPCA", "max_issues_repo_head_hexsha": "30f95e605b430252d4d09dd26a1abc8616f5d31d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/alstructure.cpp", "max_forks_repo_name": "ekmolloy/ProPCA", "max_forks_repo_head_hexsha": "30f95e605b430252d4d09dd26a1abc8616f5d31d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-08T21:29:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-08T21:29:31.000Z", "avg_line_length": 30.9418238994, "max_line_length": 162, "alphanum_fraction": 0.6533360435, "num_tokens": 5880, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.48211616394876244}}
{"text": "/* This file is part of the Tomographer project, which is distributed under the\n * terms of the MIT license.\n *\n * The MIT License (MIT)\n *\n * Copyright (c) 2016 ETH Zurich, Institute for Theoretical Physics, Philippe Faist\n * Copyright (c) 2017 Caltech, Institute for Quantum Information and Matter, Philippe Faist\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n#include <cmath>\n\n#include <string>\n#include <iostream>\n#include <random>\n\n#include <boost/math/constants/constants.hpp>\n\n// definitions for Tomographer test framework -- this must be included before any\n// <Eigen/...> or <tomographer/...> header\n#include \"test_tomographer.h\"\n\n#include <tomographer/mathtools/solveclyap.h>\n#include <tomographer/tools/eigenutil.h> // denseRandom\n#include <tomographer/tools/loggers.h>\n#include <tomographer/mathtools/random_unitary.h>\n\n#include <tomographer/tools/boost_test_logger.h>\n\n\n// -----------------------------------------------------------------------------\n// fixture(s)\n\n\n// template<typename MatrixType_, typename Rng_>\n// class RandomPosSemiDef\n// {\n// public:\n//   typedef MatrixType_ MatrixType;\n//   typedef typename MatrixType::Scalar Scalar;\n//   typedef typename Eigen::NumTraits<Scalar>::Real RealScalar;\n//   typedef typename MatrixType::Index IndexType;\n//   typedef Eigen::Matrix<RealScalar, Eigen::Dynamic, 1> RealVectorType;\n\n//   typedef Rng_ Rng;\n\n// private:\n//   Rng & _rng;\n//   IndexType _dim;\n\n//   MatrixType _U;\n//   RealVectorType _diag;\n\n// public:\n//   RandomPosSemiDef(Rng & rng, IndexType dim)\n//     : _rng(rng), _dim(dim), _U(dim, dim), _diag(dim)\n//   {\n//   }\n\n//   MatrixType withUnifEig(RealScalar max_eigenval = RealScalar(1),\n// \t\t\t IndexType max_rank = std::numeric_limits<IndexType>::max())\n//   {\n//     std::uniform_real_distribution<RealScalar> dist(0, max_eigenval);\n\n//     Tomographer::MathTools::randomUnitary<MatrixType>(_U, _rng);\n    \n//     _diag = Tomographer::Tools::denseRandom<Eigen::VectorXd>(_rng, dist, _dim);\n\n//     for (int i = max_rank; i < _dim; ++i) {\n//       _diag(i) = 0;\n//     }\n\n//     // this is positive semidefinite.\n//     return _U*_diag.asDiagonal()*_U.adjoint();\n//   }\n\n//   inline const MatrixType & lastU() const { return _U; }\n//   inline const RealVectorType & lastDiag() const { return _diag; }\n\n// };\n\n\n\n\nstruct test_solveclyap_fixture\n{\n  template<typename Rng>\n  void do_test(Rng & rng, int d, int A_rank)\n  {\n    typedef Eigen::MatrixXcd MatType;\n\n    std::uniform_real_distribution<double> dist(0.0, 1.0);\n\n    MatType U(d,d);\n    Tomographer::MathTools::randomUnitary<MatType>(U, rng);\n    MatType W(U.block(0,0,d,A_rank));\n\n    Eigen::VectorXd eigvals(Tomographer::Tools::denseRandom<Eigen::VectorXd>(rng, dist, A_rank));\n    // this is positive semidefinite.\n    MatType A(W * eigvals.asDiagonal() * W.adjoint());\n\n    BOOST_MESSAGE(\"A = \" << A) ;\n\n    // create a random X in the support of A\n    // MatType X(W * RandomPosSemiDef<MatType, std::mt19937>(rng, A_rank).withUnifEig(1.0, A_rank) * W.adjoint());\n    MatType X(W * Tomographer::Tools::denseRandom<MatType>(rng, dist, A_rank, A_rank) * W.adjoint());\n\n    BOOST_MESSAGE(\"X = \" << X) ;\n\n    const MatType C(A.adjoint()*X + X*A);\n\n    BOOST_MESSAGE(\"--> C = \" << C) ;\n\n    MatType X2(d,d);\n\n    Tomographer::Logger::BoostTestLogger logger(Tomographer::Logger::DEBUG);\n\n    Tomographer::MathTools::SolveCLyap::solve<true>(X2, A, C, logger, 1e-8);\n\n    MY_BOOST_CHECK_EIGEN_EQUAL(X, X2, 1e-8);\n  }\n};\n\n\n\n\n// -----------------------------------------------------------------------------\n// test suites\n\n\nBOOST_FIXTURE_TEST_SUITE(test_mathtools_solveclyap, test_solveclyap_fixture)\n\nBOOST_AUTO_TEST_CASE(random_test_7_4)\n{\n  std::mt19937 rng(4938221);\n\n  const int d = 7; // dimension of problem\n  const int A_rank = 4; // rank of A\n  for (int repeat = 0; repeat < 1000; ++repeat) {\n    BOOST_MESSAGE(\"Repeat : iteration #\" << repeat) ;\n    do_test(rng, d, A_rank);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(random_test_15_15)\n{\n  std::mt19937 rng(89120);\n\n  const int d = 15; // dimension of problem\n  const int A_rank = 15; // rank of A\n\n  for (int repeat = 0; repeat < 100; ++repeat) {\n    BOOST_MESSAGE(\"Repeat : iteration #\" << repeat) ;\n    do_test(rng, d, A_rank);\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n", "meta": {"hexsha": "e4d5fec760ddd0b4d2e8047e0b9d9e156e55e00a", "size": 5279, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "test/test_mathtools_solveclyap.cxx", "max_stars_repo_name": "Tomographer/tomographer", "max_stars_repo_head_hexsha": "0a64927e639454175803c1746141bd9288af8b29", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2015-09-24T02:25:11.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-13T02:26:00.000Z", "max_issues_repo_path": "test/test_mathtools_solveclyap.cxx", "max_issues_repo_name": "Tomographer/tomographer", "max_issues_repo_head_hexsha": "0a64927e639454175803c1746141bd9288af8b29", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-10-12T15:48:55.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-21T15:14:59.000Z", "max_forks_repo_path": "test/test_mathtools_solveclyap.cxx", "max_forks_repo_name": "Tomographer/tomographer", "max_forks_repo_head_hexsha": "0a64927e639454175803c1746141bd9288af8b29", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2015-10-12T15:32:29.000Z", "max_forks_repo_forks_event_max_datetime": "2018-05-08T11:39:49.000Z", "avg_line_length": 29.8248587571, "max_line_length": 114, "alphanum_fraction": 0.674180716, "num_tokens": 1396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.4821161613964132}}
{"text": "//-----------------------------------------------------------------------------\n// Copyright (c) 2016 Benjamin Buch\n//\n// https://github.com/bebuch/mitrax\n//\n// Distributed under the Boost Software License, Version 1.0. (See accompanying\n// file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)\n//-----------------------------------------------------------------------------\n#ifndef _mitrax__Eigen__convert__hpp_INCLUDED_\n#define _mitrax__Eigen__convert__hpp_INCLUDED_\n\n#include <Eigen/Core>\n\n#include <mitrax/matrix.hpp>\n\n\nnamespace mitrax{\n\n\n\ttemplate < typename Derived >\n\tconstexpr auto convert(Eigen::MatrixBase< Derived > const& m){\n\t\treturn make_matrix_fn(dim_pair(m.cols(), m.rows()), [&m](auto x, auto y){\n\t\t\treturn m(y, x);\n\t\t});\n\t}\n\n\ttemplate < typename M, col_t C, row_t R >\n\tconstexpr auto convert(matrix< M, C, R > const& m){\n\t\tEigen::Matrix<\n\t\t\tvalue_type_t< M >,\n\t\t\tR == 0 ? Eigen::Dynamic : int(R),\n\t\t\tC == 0 ? Eigen::Dynamic : int(C)\n\t\t> res(int(m.rows()), int(m.cols()));\n\n\t\tfor(size_t y = 0; y < m.rows(); ++y){\n\t\t\tfor(size_t x = 0; x < m.cols(); ++x){\n\t\t\t\tres.coeffRef(y, x) = m(x, y);\n\t\t\t}\n\t\t}\n\n\t\treturn res;\n\t}\n\n\n}\n\n\n#endif\n", "meta": {"hexsha": "fafcf65ba714ffb814551c6a890c7755d89aa3c2", "size": 1164, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "benchmark/include/Eigen/convert.hpp", "max_stars_repo_name": "bebuch/Mitrax", "max_stars_repo_head_hexsha": "bc33a1b93058886daab3e4ef736ef9b519111454", "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": "benchmark/include/Eigen/convert.hpp", "max_issues_repo_name": "bebuch/Mitrax", "max_issues_repo_head_hexsha": "bc33a1b93058886daab3e4ef736ef9b519111454", "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": "benchmark/include/Eigen/convert.hpp", "max_forks_repo_name": "bebuch/Mitrax", "max_forks_repo_head_hexsha": "bc33a1b93058886daab3e4ef736ef9b519111454", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.7551020408, "max_line_length": 79, "alphanum_fraction": 0.558419244, "num_tokens": 304, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.482116158939366}}
{"text": "#include <iostream>\n#include <fstream>\n#include <chrono>\n#include <string>\n#include <Eigen/Cholesky>\n#include <enoki/array.h>\n#include <enoki/autodiff.h>\n#include <enoki/autodiff.cpp>\n\n/* Don't forget to include the 'enoki' namespace */\nusing namespace enoki;\nusing namespace std;\nusing namespace std::chrono;\n\n/* Static float array (the suffix \"P\" indicates that this is a fixed-size packet) */\nusing FloatP = Packet<float, 4>;\n\n/* Dynamic float array (vectorized via FloatP, the suffix \"X\" indicates arbitrary length) */\nusing FloatX = DynamicArray<FloatP>;\n\nusing FloatD = DiffArray<FloatX>;\n\nint main(int argc, char **argv)\n{\n    int num_params = 90010;\n    int num_vars = 1;\n    Eigen::VectorXd args(num_params * num_vars);\n\tFloatX init_k = zero<FloatX>(num_params);\n \n    string output_filename = argv[1];\n    ofstream outfile;\n    outfile.open(output_filename);\n\n    std::ifstream file(\"./tests/params.txt\");\n\n    int i = 0;\n    for (std::string line; std::getline(file, line);)\n    {\n        args(i) = stod(line.c_str());\n        i++;\n    }\n    file.close();\n    for (int i = 0; i < num_params; i++)\n    {\n\t\tinit_k[i] = args[i * num_vars + 0];\n\n    }\n\n\tFloatD k(init_k);\n \n\tset_requires_gradient(k);\n \n    FloatD function = sin(k) + cos(k) + pow(k, 2); // derivative\n\n    auto start = high_resolution_clock::now();\n    backward(function);\n\tFloatX grad_k = gradient(k);\n \n    auto stop = high_resolution_clock::now();\n    auto duration = duration_cast<microseconds>(stop - start);\n    outfile << (double)duration.count() / 1000000.0 << \" \";\n    for (int i = 0; i < num_params; i++)\n    {\n\t\toutfile << grad_k[i] << \" \";\n \n    }\n    outfile.close();\n    return 0;\n}", "meta": {"hexsha": "2060ff704f7b4a45fa3aef87b5e092f89fdf9743", "size": 1670, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/utils/enoki.cpp", "max_stars_repo_name": "marcelotrevisani/acorns", "max_stars_repo_head_hexsha": "682749b0963ffc0a3998a7065ef505fc95123f50", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/utils/enoki.cpp", "max_issues_repo_name": "marcelotrevisani/acorns", "max_issues_repo_head_hexsha": "682749b0963ffc0a3998a7065ef505fc95123f50", "max_issues_repo_licenses": ["MIT"], "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/utils/enoki.cpp", "max_forks_repo_name": "marcelotrevisani/acorns", "max_forks_repo_head_hexsha": "682749b0963ffc0a3998a7065ef505fc95123f50", "max_forks_repo_licenses": ["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.2028985507, "max_line_length": 92, "alphanum_fraction": 0.6413173653, "num_tokens": 455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.48211615392996937}}
{"text": "/* Copyright 2017 Ramakrishnan Kannan */\n\n#include <armadillo>\n#include \"ncpfactors.hpp\"\n#include \"ntf_utils.hpp\"\n#include \"tensor.hpp\"\n#include \"utils.h\"\n\nint main(int argc, char* argv[]) {\n  int test_order = 5;\n  int low_rank = 2;\n  UVEC dimensions(test_order);\n  FMAT* mttkrps = new FMAT[test_order];\n  // UVEC dimensions(4);\n  for (int i = 0; i < test_order; i++) {\n    dimensions(i) = i + 2;\n  }\n  // dimensions(3) = 6;\n  PLANC::NCPFactors cpfactors(dimensions, low_rank);\n  cpfactors.print();\n  FMAT krp_2 = cpfactors.krp_leave_out_one(2);\n  cout << \"krp\" << endl << \"------\" << endl << krp_2;\n  PLANC::Tensor my_tensor = cpfactors.rankk_tensor();\n  // cout << \"input tensor\" << endl << \"--------\" << endl;\n  // my_tensor.print();\n  for (int i = 0; i < test_order; i++) {\n    mttkrps[i] = arma::zeros<FMAT>(dimensions(i), low_rank);\n  }\n  for (int i = 0; i < test_order; i++) {\n    mttkrp(i, my_tensor, cpfactors, &mttkrps[i]);\n    cout << \"mttkrp \" << i << endl << \"---------\" << endl << mttkrps[i];\n  }\n}\n", "meta": {"hexsha": "f4109b2c9cc91d5c6b1c6a51169fdd60a73bf579", "size": 1013, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "planc-master/ntf/mttkrp_test.cpp", "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/ntf/mttkrp_test.cpp", "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/ntf/mttkrp_test.cpp", "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": 29.7941176471, "max_line_length": 72, "alphanum_fraction": 0.5972359329, "num_tokens": 338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424528443251, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.48206254969713425}}
{"text": "#pragma once\n#include <Eigen/Core>\n#include <gtsam/nonlinear/NonlinearFactor.h>\n#include <gtsam/geometry/Pose3.h>\n#include <gtsam/geometry/Point3.h>\n\nnamespace gtsam\n{\n    class LidarNormalFactor : public NoiseModelFactor2<Pose3, Pose3>\n    {\n        using X = Pose3;\n        using Base = NoiseModelFactor2<Pose3, Pose3>;\n        using This = LidarNormalFactor;\n\n    public:\n        LidarNormalFactor(Key key1, Key key2, const Point3 &unit1, const Point3 &unit2, const SharedNoiseModel &model)\n            : Base(model, key1, key2), u1_(unit1.normalized()), u2_(unit2.normalized())\n        {\n        }\n\n        virtual ~LidarNormalFactor() {}\n\n        /*\n            d(R*u)/dT =  R*[[-u]x 03x3]\n            \n            err = R1*u1 x R2*u2\n            derr/dT1 =  [R2*u2]x * R1*[[u1]x 03x3]\n            derr/dT2 = -[R1*u1]x * R2*[[u2]x 03x3]\n        */\n        Vector evaluateError(const X &pose1, const X &pose2,\n                             boost::optional<Matrix &> H1 = boost::none,\n                             boost::optional<Matrix &> H2 = boost::none) const\n        {\n            const auto &rot_u1 = pose1.rotation().matrix() * u1_;\n            const auto &rot_u2 = pose2.rotation().matrix() * u2_;\n            if (H1)\n                *H1 = skewSymmetric(rot_u2[0], rot_u2[1], rot_u2[2]) * (Matrix36() << pose1.rotation().matrix() * skewSymmetric(u1_[0], u1_[1], u1_[2]), Z_3x3).finished();\n\n            if(H2)\n                *H2 = skewSymmetric(rot_u1[0], rot_u1[1], rot_u1[2]) * (Matrix36() << pose2.rotation().matrix() * skewSymmetric(u2_[0], u2_[1], u2_[2]), Z_3x3).finished();\n\n            return rot_u1.cross(rot_u2);\n        }\n\n        virtual NonlinearFactor::shared_ptr clone() const\n        {\n            return boost::static_pointer_cast<NonlinearFactor>(\n                NonlinearFactor::shared_ptr(new This(*this)));\n        }\n\n        // virtual bool equals(const NonlinearFactor &expected, double tol = 1e-9) const\n        // {\n        //   const This *e = dynamic_cast<const This *>(&expected);\n        //   return e != nullptr && Base::equals(*e, tol) && traits<Point3>::Equals(p1_, e->p1_, tol) &&\n        //          traits<Point3>::Equals(p2_, e->p2_, tol) && traits<Point3>::Equals(u_, e->u_, tol);\n        // }\n\n        // virtual void print(const std::string &s = \"\",\n        //                    const KeyFormatter &keyFormatter = DefaultKeyFormatter) const\n        // {\n        //   cout << s << \":\\nLidarPlaneFactor1 on (\" << keyFormatter(key()) <<  \")\\n\"\n        //        << \"  Plane Point: \" << p1_.transpose() << \"\\n\"\n        //        << \"  Plane norm Axis: \" << u_.transpose() << \"\\n\"\n        //        << \"  Match Point: \" << p2_.transpose() << \"\\n\";\n        //   noiseModel_->print(\"  noise model: \");\n        // }\n\n    private:\n        Point3 u1_, u2_;\n    }; // class LidarNormalFactor\n}", "meta": {"hexsha": "245ff1ff91332aa8a349ec794b8063cdbd6c7922", "size": 2834, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/include/factors/LidarNormalFactor.hpp", "max_stars_repo_name": "Saki-Chen/W-LOAM", "max_stars_repo_head_hexsha": "39ad29da0db760401c06d17c22a0e43d8562efec", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2021-08-24T02:24:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T09:56:10.000Z", "max_issues_repo_path": "src/include/factors/LidarNormalFactor.hpp", "max_issues_repo_name": "xingchengzhi/W-LOAM", "max_issues_repo_head_hexsha": "eca5c1932fc48b0d4f47cfd7bc85c874afd09631", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-11-01T03:41:16.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-24T12:33:35.000Z", "max_forks_repo_path": "src/include/factors/LidarNormalFactor.hpp", "max_forks_repo_name": "xingchengzhi/W-LOAM", "max_forks_repo_head_hexsha": "eca5c1932fc48b0d4f47cfd7bc85c874afd09631", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2021-10-30T05:11:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T08:59:59.000Z", "avg_line_length": 39.9154929577, "max_line_length": 171, "alphanum_fraction": 0.5314043754, "num_tokens": 820, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424256566559, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.48206253420416884}}
{"text": "// Copyright (c) 2020 Chris Richardson & Matthew Scroggs\n// FEniCS Project\n// SPDX-License-Identifier:    MIT\n\n#include \"nce-rtc.h\"\n#include \"core/dof-permutations.h\"\n#include \"core/element-families.h\"\n#include \"core/log.h\"\n#include \"core/mappings.h\"\n#include \"core/moments.h\"\n#include \"core/polyset.h\"\n#include \"core/quadrature.h\"\n#include \"lagrange.h\"\n#include <Eigen/Dense>\n#include <numeric>\n#include <vector>\n\nusing namespace basix;\n\n//----------------------------------------------------------------------------\nFiniteElement basix::create_rtc(cell::type celltype, int degree)\n{\n  if (celltype != cell::type::quadrilateral\n      and celltype != cell::type::hexahedron)\n    throw std::runtime_error(\"Unsupported cell type\");\n\n  if (degree > 4)\n  {\n    // TODO: suggest alternative with non-uniform points once implemented\n    LOG(WARNING) << \"RTC spaces with high degree using equally spaced\"\n                 << \" points are unstable.\";\n  }\n\n  const int tdim = cell::topological_dimension(celltype);\n\n  const cell::type facettype\n      = (tdim == 2) ? cell::type::interval : cell::type::quadrilateral;\n\n  // Evaluate the expansion polynomials at the quadrature points\n  auto [Qpts, Qwts]\n      = quadrature::make_quadrature(\"default\", celltype, 2 * degree);\n  Eigen::ArrayXXd polyset_at_Qpts\n      = polyset::tabulate(celltype, degree, 0, Qpts)[0];\n\n  // The number of order (degree) polynomials\n  const int psize = polyset_at_Qpts.cols();\n\n  const int facet_count = tdim == 2 ? 4 : 6;\n  const int facet_dofs = polyset::dim(facettype, degree - 1);\n  const int internal_dofs = tdim == 2 ? 2 * degree * (degree - 1)\n                                      : 3 * degree * degree * (degree - 1);\n  const int ndofs = facet_count * facet_dofs + internal_dofs;\n\n  // Create coefficients for order (degree-1) vector polynomials\n  Eigen::MatrixXd wcoeffs = Eigen::MatrixXd::Zero(ndofs, psize * tdim);\n\n  const int nv_interval = polyset::dim(cell::type::interval, degree);\n  const int ns_interval = polyset::dim(cell::type::interval, degree - 1);\n  int dof = 0;\n  if (tdim == 2)\n  {\n    for (int d = 0; d < tdim; ++d)\n      for (int i = 0; i < ns_interval; ++i)\n        for (int j = 0; j < ns_interval; ++j)\n          wcoeffs(dof++, psize * d + i * nv_interval + j) = 1;\n  }\n  else\n  {\n    for (int d = 0; d < tdim; ++d)\n      for (int i = 0; i < ns_interval; ++i)\n        for (int j = 0; j < ns_interval; ++j)\n          for (int k = 0; k < ns_interval; ++k)\n            wcoeffs(dof++, psize * d + i * nv_interval * nv_interval\n                               + j * nv_interval + k)\n                = 1;\n  }\n\n  // Create coefficients for additional polynomials in the div space\n  for (int i = 0; i < pow(degree, tdim - 1); ++i)\n  {\n    std::vector<int> indices(tdim - 1);\n    if (tdim == 2)\n      indices[0] = i;\n    else\n    {\n      indices[0] = i / degree;\n      indices[1] = i % degree;\n    }\n    for (int d = 0; d < tdim; ++d)\n    {\n      int n = 0;\n      Eigen::ArrayXd integrand = Qpts.col(d);\n      for (int j = 1; j < degree; ++j)\n        integrand *= Qpts.col(d);\n      for (int c = 0; c < tdim; ++c)\n      {\n        if (c != d)\n        {\n          for (int j = 0; j < indices[n]; ++j)\n            integrand *= Qpts.col(c);\n          ++n;\n        }\n      }\n      for (int k = 0; k < psize; ++k)\n      {\n        const double w_sum = (Qwts * integrand * polyset_at_Qpts.col(k)).sum();\n        wcoeffs(dof, k + psize * d) = w_sum;\n      }\n      ++dof;\n    }\n  }\n\n  // Dual space\n  Eigen::MatrixXd dual = Eigen::MatrixXd::Zero(ndofs, psize * tdim);\n\n  // quadrature degree\n  int quad_deg = 2 * degree;\n\n  // Add rows to dualmat for integral moments on facets\n  dual.block(0, 0, facet_count * facet_dofs, psize * tdim)\n      = moments::make_normal_integral_moments(\n          create_dlagrange(facettype, degree - 1), celltype, tdim, degree,\n          quad_deg);\n\n  // Add rows to dualmat for integral moments on interior\n  if (degree > 1)\n  {\n    // Interior integral moment\n    dual.block(facet_count * facet_dofs, 0, internal_dofs, psize * tdim)\n        = moments::make_dot_integral_moments(create_nce(celltype, degree - 1),\n                                             celltype, tdim, degree, quad_deg);\n  }\n\n  const std::vector<std::vector<std::vector<int>>> topology\n      = cell::topology(celltype);\n\n  int perm_count = 0;\n  for (int i = 1; i < tdim; ++i)\n    perm_count += topology[i].size() * i;\n\n  std::vector<Eigen::MatrixXd> base_permutations(\n      perm_count, Eigen::MatrixXd::Identity(ndofs, ndofs));\n  if (tdim == 2)\n  {\n    Eigen::ArrayXi edge_ref = dofperms::interval_reflection(degree);\n    Eigen::ArrayXXd edge_dir\n        = dofperms::interval_reflection_tangent_directions(degree);\n    for (int edge = 0; edge < facet_count; ++edge)\n    {\n      const int start = edge_ref.size() * edge;\n      for (int i = 0; i < edge_ref.size(); ++i)\n      {\n        base_permutations[edge](start + i, start + i) = 0;\n        base_permutations[edge](start + i, start + edge_ref[i]) = 1;\n      }\n      Eigen::MatrixXd directions = Eigen::MatrixXd::Identity(ndofs, ndofs);\n      directions.block(edge_dir.rows() * edge, edge_dir.cols() * edge,\n                       edge_dir.rows(), edge_dir.cols())\n          = edge_dir;\n      base_permutations[edge] *= directions;\n    }\n  }\n  else if (tdim == 3)\n  {\n    Eigen::ArrayXi face_ref = dofperms::quadrilateral_reflection(degree);\n    Eigen::ArrayXi face_rot = dofperms::quadrilateral_rotation(degree);\n\n    for (int face = 0; face < facet_count; ++face)\n    {\n      const int start = face_ref.size() * face;\n      for (int i = 0; i < face_rot.size(); ++i)\n      {\n        base_permutations[12 + 2 * face](start + i, start + i) = 0;\n        base_permutations[12 + 2 * face](start + i, start + face_rot[i]) = 1;\n        base_permutations[12 + 2 * face + 1](start + i, start + i) = 0;\n        base_permutations[12 + 2 * face + 1](start + i, start + face_ref[i])\n            = -1;\n      }\n    }\n  }\n\n  std::vector<std::vector<int>> entity_dofs(topology.size());\n  for (int i = 0; i < tdim - 1; ++i)\n    entity_dofs[i].resize(topology[i].size(), 0);\n  entity_dofs[tdim - 1].resize(topology[tdim - 1].size(), facet_dofs);\n  entity_dofs[tdim] = {internal_dofs};\n\n  Eigen::MatrixXd coeffs = compute_expansion_coefficients(wcoeffs, dual);\n  return FiniteElement(element::family::RT, celltype, degree, {tdim}, coeffs,\n                       entity_dofs, base_permutations, {}, {},\n                       mapping::type::contravariantPiola);\n}\n//-----------------------------------------------------------------------------\nFiniteElement basix::create_nce(cell::type celltype, int degree)\n{\n  if (celltype != cell::type::quadrilateral\n      and celltype != cell::type::hexahedron)\n    throw std::runtime_error(\"Unsupported cell type\");\n\n  if (degree > 4)\n  {\n    // TODO: suggest alternative with non-uniform points once implemented\n    LOG(WARNING) << \"NC spaces with high degree using equally spaced\"\n                 << \" points are unstable.\";\n  }\n\n  const int tdim = cell::topological_dimension(celltype);\n\n  // Evaluate the expansion polynomials at the quadrature points\n  auto [Qpts, Qwts]\n      = quadrature::make_quadrature(\"default\", celltype, 2 * degree);\n  Eigen::ArrayXXd polyset_at_Qpts\n      = polyset::tabulate(celltype, degree, 0, Qpts)[0];\n\n  // The number of order (degree) polynomials\n  const int psize = polyset_at_Qpts.cols();\n\n  const int edge_count = tdim == 2 ? 4 : 12;\n  const int edge_dofs = polyset::dim(cell::type::interval, degree - 1);\n  const int face_count = tdim == 2 ? 1 : 6;\n  const int face_dofs = 2 * degree * (degree - 1);\n  const int volume_count = tdim == 2 ? 0 : 1;\n  const int volume_dofs = 3 * degree * (degree - 1) * (degree - 1);\n\n  const int ndofs = edge_count * edge_dofs + face_count * face_dofs\n                    + volume_count * volume_dofs;\n\n  // Create coefficients for order (degree-1) vector polynomials\n  Eigen::MatrixXd wcoeffs = Eigen::MatrixXd::Zero(ndofs, psize * tdim);\n\n  const int nv_interval = polyset::dim(cell::type::interval, degree);\n  const int ns_interval = polyset::dim(cell::type::interval, degree - 1);\n  int dof = 0;\n  if (tdim == 2)\n  {\n    for (int d = 0; d < tdim; ++d)\n      for (int i = 0; i < ns_interval; ++i)\n        for (int j = 0; j < ns_interval; ++j)\n          wcoeffs(dof++, psize * d + i * nv_interval + j) = 1;\n  }\n  else\n  {\n    for (int d = 0; d < tdim; ++d)\n      for (int i = 0; i < ns_interval; ++i)\n        for (int j = 0; j < ns_interval; ++j)\n          for (int k = 0; k < ns_interval; ++k)\n            wcoeffs(dof++, psize * d + i * nv_interval * nv_interval\n                               + j * nv_interval + k)\n                = 1;\n  }\n\n  // Create coefficients for additional polynomials in the curl space\n  if (tdim == 2)\n  {\n    for (int i = 0; i < degree; ++i)\n    {\n      for (int d = 0; d < tdim; ++d)\n      {\n        Eigen::ArrayXd integrand = Qpts.col(1 - d);\n        for (int j = 1; j < degree; ++j)\n          integrand *= Qpts.col(1 - d);\n        for (int j = 0; j < i; ++j)\n          integrand *= Qpts.col(d);\n\n        for (int k = 0; k < psize; ++k)\n        {\n          const double w_sum\n              = (Qwts * integrand * polyset_at_Qpts.col(k)).sum();\n          wcoeffs(dof, k + psize * d) = w_sum;\n        }\n        ++dof;\n      }\n    }\n  }\n  else\n  {\n    for (int i = 0; i < degree; ++i)\n    {\n      for (int j = 0; j < degree + 1; ++j)\n      {\n        for (int c = 0; c < tdim; ++c)\n        {\n          for (int d = 0; d < tdim; ++d)\n          {\n            if (d != c)\n            {\n              const int e\n                  = (c == 0 || d == 0) ? ((c == 1 || d == 1) ? 2 : 1) : 0;\n              if (c < e and j == degree)\n                continue;\n              Eigen::ArrayXd integrand = Qpts.col(e);\n              for (int k = 1; k < degree; ++k)\n                integrand *= Qpts.col(e);\n              for (int k = 0; k < i; ++k)\n                integrand *= Qpts.col(d);\n              for (int k = 0; k < j; ++k)\n                integrand *= Qpts.col(c);\n\n              for (int k = 0; k < psize; ++k)\n              {\n                const double w_sum\n                    = (Qwts * integrand * polyset_at_Qpts.col(k)).sum();\n                wcoeffs(dof, k + psize * d) = w_sum;\n              }\n              ++dof;\n            }\n          }\n        }\n      }\n    }\n  }\n\n  // Dual space\n  Eigen::MatrixXd dual = Eigen::MatrixXd::Zero(ndofs, psize * tdim);\n  Eigen::ArrayXXd points;\n  Eigen::MatrixXd matrix;\n\n  // quadrature degree\n  int quad_deg = 2 * degree;\n\n  // Add rows to dualmat for integral moments on facets\n  dual.block(0, 0, edge_count * edge_dofs, psize * tdim)\n      = moments::make_tangent_integral_moments(\n          create_dlagrange(cell::type::interval, degree - 1), celltype, tdim,\n          degree, quad_deg);\n\n  Eigen::ArrayXXd points_1d;\n  Eigen::MatrixXd matrix_1d;\n  std::tie(points_1d, matrix_1d)\n      = moments::make_tangent_integral_moments_interpolation(\n          create_dlagrange(cell::type::interval, degree - 1), celltype, tdim,\n          degree, quad_deg);\n\n  if (degree == 1)\n  {\n    points = points_1d;\n    matrix = matrix_1d;\n  }\n\n  // Add rows to dualmat for integral moments on interior\n  if (degree > 1)\n  {\n    // Face integral moment\n    dual.block(edge_count * edge_dofs, 0, face_count * face_dofs, psize * tdim)\n        = moments::make_dot_integral_moments(\n            create_rtc(cell::type::quadrilateral, degree - 1), celltype, tdim,\n            degree, quad_deg);\n\n    Eigen::ArrayXXd points_2d;\n    Eigen::MatrixXd matrix_2d;\n    std::tie(points_2d, matrix_2d)\n        = moments::make_dot_integral_moments_interpolation(\n            create_rtc(cell::type::quadrilateral, degree - 1), celltype, tdim,\n            degree, quad_deg);\n\n    if (tdim == 2)\n    {\n      points.resize(points_1d.rows() + points_2d.rows(), tdim);\n      matrix.resize(matrix_1d.rows() + matrix_2d.rows(),\n                    matrix_1d.cols() + matrix_2d.cols());\n      matrix.setZero();\n\n      points.block(0, 0, points_1d.rows(), tdim) = points_1d;\n      points.block(points_1d.rows(), 0, points_2d.rows(), tdim) = points_2d;\n\n      const int r1d = matrix_1d.rows();\n      const int r2d = matrix_2d.rows();\n      const int c1d = matrix_1d.cols() / tdim;\n      const int c2d = matrix_2d.cols() / tdim;\n      for (int i = 0; i < tdim; ++i)\n      {\n        matrix.block(0, i * (c1d + c2d), r1d, c1d)\n            = matrix_1d.block(0, i * c1d, r1d, c1d);\n        matrix.block(r1d, i * (c1d + c2d) + c1d, r2d, c2d)\n            = matrix_2d.block(0, i * c2d, r2d, c2d);\n      }\n    }\n\n    if (tdim == 3)\n    {\n      // Interior integral moment\n      dual.block(edge_count * edge_dofs + face_count * face_dofs, 0,\n                 volume_dofs, psize * tdim)\n          = moments::make_dot_integral_moments(\n              create_rtc(cell::type::hexahedron, degree - 1), celltype, tdim,\n              degree, quad_deg);\n\n      Eigen::ArrayXXd points_3d;\n      Eigen::MatrixXd matrix_3d;\n      std::tie(points_3d, matrix_3d)\n          = moments::make_dot_integral_moments_interpolation(\n              create_rtc(cell::type::hexahedron, degree - 1), celltype, tdim,\n              degree, quad_deg);\n\n      points.resize(points_1d.rows() + points_2d.rows() + points_3d.rows(),\n                    tdim);\n      matrix.resize(matrix_1d.rows() + matrix_2d.rows() + matrix_3d.rows(),\n                    matrix_1d.cols() + matrix_2d.cols() + matrix_3d.cols());\n      matrix.setZero();\n\n      points.block(0, 0, points_1d.rows(), tdim) = points_1d;\n      points.block(points_1d.rows(), 0, points_2d.rows(), tdim) = points_2d;\n      points.block(points_1d.rows() + points_2d.rows(), 0, points_3d.rows(),\n                   tdim)\n          = points_3d;\n\n      const int r1d = matrix_1d.rows();\n      const int r2d = matrix_2d.rows();\n      const int r3d = matrix_3d.rows();\n      const int c1d = matrix_1d.cols() / tdim;\n      const int c2d = matrix_2d.cols() / tdim;\n      const int c3d = matrix_3d.cols() / tdim;\n      for (int i = 0; i < tdim; ++i)\n      {\n        matrix.block(0, i * (c1d + c2d + c3d), r1d, c1d)\n            = matrix_1d.block(0, i * c1d, r1d, c1d);\n        matrix.block(r1d, i * (c1d + c2d + c3d) + c1d, r2d, c2d)\n            = matrix_2d.block(0, i * c2d, r2d, c2d);\n        matrix.block(r1d + r2d, i * (c1d + c2d + c3d) + c1d + c2d, r3d, c3d)\n            = matrix_3d.block(0, i * c3d, r3d, c3d);\n      }\n    }\n  }\n\n  const std::vector<std::vector<std::vector<int>>> topology\n      = cell::topology(celltype);\n\n  int perm_count = 0;\n  for (int i = 1; i < tdim; ++i)\n    perm_count += topology[i].size() * i;\n\n  std::vector<Eigen::MatrixXd> base_permutations(\n      perm_count, Eigen::MatrixXd::Identity(ndofs, ndofs));\n\n  Eigen::ArrayXi edge_ref = dofperms::interval_reflection(degree);\n  Eigen::ArrayXXd edge_dir\n      = dofperms::interval_reflection_tangent_directions(degree);\n\n  for (int edge = 0; edge < edge_count; ++edge)\n  {\n    const int start = edge_ref.size() * edge;\n    for (int i = 0; i < edge_ref.size(); ++i)\n    {\n      base_permutations[edge](start + i, start + i) = 0;\n      base_permutations[edge](start + i, start + edge_ref[i]) = 1;\n    }\n    Eigen::MatrixXd directions = Eigen::MatrixXd::Identity(ndofs, ndofs);\n    directions.block(edge_dir.rows() * edge, edge_dir.cols() * edge,\n                     edge_dir.rows(), edge_dir.cols())\n        = edge_dir;\n    base_permutations[edge] *= directions;\n  }\n\n  if (tdim == 3 and degree > 1)\n  {\n    Eigen::MatrixXd face_ref\n        = dofperms::quadrilateral_rtc_reflection(degree - 1);\n    Eigen::MatrixXd face_rot = dofperms::quadrilateral_rtc_rotation(degree - 1);\n\n    for (int face = 0; face < face_count; ++face)\n    {\n      const int start = edge_ref.size() * edge_count + face_ref.rows() * face;\n      const int p = edge_count + 2 * face;\n\n      base_permutations[p].block(start, start, face_rot.rows(), face_rot.cols())\n          = face_rot;\n      base_permutations[p + 1].block(start, start, face_ref.rows(),\n                                     face_ref.cols())\n          = face_ref;\n    }\n  }\n\n  std::vector<std::vector<int>> entity_dofs(topology.size());\n  entity_dofs[0].resize(topology[0].size(), 0);\n  entity_dofs[1].resize(topology[1].size(), edge_dofs);\n  entity_dofs[2].resize(topology[2].size(), face_dofs);\n  if (tdim == 3)\n    entity_dofs[3].resize(topology[3].size(), volume_dofs);\n\n  Eigen::MatrixXd coeffs = compute_expansion_coefficients(wcoeffs, dual);\n  return FiniteElement(element::family::N1E, celltype, degree, {tdim}, coeffs,\n                       entity_dofs, base_permutations, points, matrix,\n                       mapping::type::covariantPiola);\n}\n//-----------------------------------------------------------------------------\nEigen::MatrixXd basix::dofperms::quadrilateral_rtc_rotation(int degree)\n{\n  const int n = 2 * degree * (degree + 1);\n  Eigen::MatrixXd perm = Eigen::MatrixXd::Zero(n, n);\n\n  // Permute functions on edges\n  for (int i = 0; i < degree; ++i)\n  {\n    perm(i, 2 * degree - 1 - i) = -1;\n    perm(degree + i, 3 * degree + i) = 1;\n    perm(2 * degree + i, i) = 1;\n    perm(3 * degree + i, 3 * degree - 1 - i) = -1;\n  }\n  if (degree > 1)\n    perm.block(4 * degree, 4 * degree, n - 4 * degree, n - 4 * degree)\n        = quadrilateral_nce_rotation(degree - 1);\n  return perm;\n}\n//-----------------------------------------------------------------------------\nEigen::MatrixXd basix::dofperms::quadrilateral_nce_rotation(int degree)\n{\n  const int n = 2 * degree * (degree + 1);\n  Eigen::MatrixXd perm = Eigen::MatrixXd::Zero(n, n);\n\n  // Permute functions on edges\n  for (int i = 0; i < degree; ++i)\n  {\n    perm(i, 2 * degree - 1 - i) = -1;\n    perm(degree + i, 3 * degree + i) = 1;\n    perm(2 * degree + i, i) = 1;\n    perm(3 * degree + i, 3 * degree - 1 - i) = -1;\n  }\n  if (degree > 1)\n    perm.block(4 * degree, 4 * degree, n - 4 * degree, n - 4 * degree)\n        = quadrilateral_rtc_rotation(degree - 1);\n  return perm;\n}\n//-----------------------------------------------------------------------------\nEigen::MatrixXd basix::dofperms::quadrilateral_rtc_reflection(int degree)\n{\n  const int n = 2 * degree * (degree + 1);\n  Eigen::MatrixXd perm = Eigen::MatrixXd::Zero(n, n);\n\n  // Permute functions on edges\n  for (int i = 0; i < degree; ++i)\n  {\n    perm(i, degree + i) = -1;\n    perm(degree + i, i) = -1;\n    perm(2 * degree + i, 3 * degree + i) = -1;\n    perm(3 * degree + i, 2 * degree + i) = -1;\n  }\n  if (degree > 1)\n    perm.block(4 * degree, 4 * degree, n - 4 * degree, n - 4 * degree)\n        = quadrilateral_nce_reflection(degree - 1);\n\n  return perm;\n}\n//-----------------------------------------------------------------------------\nEigen::MatrixXd basix::dofperms::quadrilateral_nce_reflection(int degree)\n{\n  const int n = 2 * degree * (degree + 1);\n  Eigen::MatrixXd perm = Eigen::MatrixXd::Zero(n, n);\n\n  // Permute functions on edges\n  for (int i = 0; i < degree; ++i)\n  {\n    perm(i, degree + i) = 1;\n    perm(degree + i, i) = 1;\n    perm(2 * degree + i, 3 * degree + i) = 1;\n    perm(3 * degree + i, 2 * degree + i) = 1;\n  }\n  if (degree > 1)\n    perm.block(4 * degree, 4 * degree, n - 4 * degree, n - 4 * degree)\n        = quadrilateral_rtc_reflection(degree - 1);\n\n  return perm;\n}\n//-----------------------------------------------------------------------------\n", "meta": {"hexsha": "858deaea96b73a1e089fd647470b035302d665c1", "size": 19294, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/elements/nce-rtc.cpp", "max_stars_repo_name": "draenog/basix", "max_stars_repo_head_hexsha": "172720a7ecf2caaf4619a4718fa3f3e1cbe0c1e4", "max_stars_repo_licenses": ["MIT"], "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/elements/nce-rtc.cpp", "max_issues_repo_name": "draenog/basix", "max_issues_repo_head_hexsha": "172720a7ecf2caaf4619a4718fa3f3e1cbe0c1e4", "max_issues_repo_licenses": ["MIT"], "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/elements/nce-rtc.cpp", "max_forks_repo_name": "draenog/basix", "max_forks_repo_head_hexsha": "172720a7ecf2caaf4619a4718fa3f3e1cbe0c1e4", "max_forks_repo_licenses": ["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.2092198582, "max_line_length": 80, "alphanum_fraction": 0.5576863274, "num_tokens": 5830, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.48205556303623875}}
{"text": "/*\n *  tutte.hpp\n *\n *\n *  Created by Andrea Bedini on 24/Nov/2011.\n *  Copyright (c) 2011-2014, Andrea Bedini <andrea.bedini@gmail.com>.\n *\n *  Distributed under the terms of the Modified BSD License.\n *  The full license is in the file COPYING, distributed as part of\n *  this software.\n *\n */\n\n#ifndef TUTTE_HPP\n#define TUTTE_HPP\n\n#include \"connectivity/connectivity.hpp\"\n#include <boost/unordered/unordered_map.hpp>\n\ntemplate<class Weight>\nclass tutte\n{\n  const Weight Q;\n  const Weight v;\n\npublic:\n  using weight_type = Weight ;\n  using table_type = boost::unordered_map<connectivity, weight_type>;\n\n  template<class T, class U>\n  tutte(T const& Q_, U const& v_) : Q(Q_), v(v_) {}\n\n  table_type empty_state(unsigned int size) const\n  {\n    table_type tmp_table;\n    tmp_table[connectivity(size)] = Weight(1);\n    return tmp_table;\n  }\n\n  table_type\n  join_operator(unsigned int i, unsigned int j, table_type const& t) const\n  {\n    table_type tmp_table;\n    for (auto const & e : t) {\n      tmp_table[e.first] += e.second;\n      tmp_table[connectivity(e.first).connect(i, j).canonicalize()]\n        += e.second * v;\n    }\n    return tmp_table;\n  }\n\n  table_type\n  delete_operator(unsigned int i, table_type const& t) const\n  {\n    table_type tmp_table;\n    for (auto const& e : t) {\n      tmp_table[connectivity(e.first).delete_node(i).canonicalize()]\n        += (e.first.singleton(i) ? (e.second * Q) : e.second);\n    }\n    return tmp_table;\n  }\n\n  template<class Mapping>\n  table_type\n  table_fusion(Mapping A_to_B,\n    table_type const& A_table,\n    table_type const& B_table) const\n  {\n    table_type tmp_table;\n    for (auto const & eA : A_table) {\n      for (auto const & eB : B_table) {\n        connectivity c = eB.first;\n        eA.first.decompose([&](unsigned int i, unsigned int j) {\n          c.connect(A_to_B[i], A_to_B[j]);\n        });\n        tmp_table[c.canonicalize()] += eA.second * eB.second;\n      }\n    }\n    return tmp_table;\n  }\n};\n#endif\n", "meta": {"hexsha": "50682c407190ba800d671ef3610cb120e075f32e", "size": 1966, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/tutte.hpp", "max_stars_repo_name": "andreabedini/tutte", "max_stars_repo_head_hexsha": "6bd620e06f6ac27fafc75898a3b12e9995a5e964", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-01-29T23:04:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-04T13:33:46.000Z", "max_issues_repo_path": "include/tutte.hpp", "max_issues_repo_name": "andreabedini/tutte", "max_issues_repo_head_hexsha": "6bd620e06f6ac27fafc75898a3b12e9995a5e964", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/tutte.hpp", "max_forks_repo_name": "andreabedini/tutte", "max_forks_repo_head_hexsha": "6bd620e06f6ac27fafc75898a3b12e9995a5e964", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.686746988, "max_line_length": 74, "alphanum_fraction": 0.6505595117, "num_tokens": 533, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4820555630362387}}
{"text": "/*\n Copyright (C) 2021 Quaternion Risk Management Ltd\n All rights reserved.\n\n This file is part of ORE, a free-software/open-source library\n for transparent pricing and risk analysis - http://opensourcerisk.org\n\n ORE is free software: you can redistribute it and/or modify it\n under the terms of the Modified BSD License.  You should have received a\n copy of the license along with this program.\n The license is also available online at <http://opensourcerisk.org>\n\n This program is distributed on the basis that it will form a useful\n contribution to risk analytics and model standardisation, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.\n*/\n\n#include \"toplevelfixture.hpp\"\n\n#include <qle/termstructures/blackdeltautilities.hpp>\n#include <qle/termstructures/blackvolsurfacebfrr.hpp>\n\n#include <ql/experimental/fx/blackdeltacalculator.hpp>\n#include <ql/pricingengines/blackformula.hpp>\n#include <ql/quotes/simplequote.hpp>\n#include <ql/termstructures/yield/flatforward.hpp>\n#include <ql/time/calendars/nullcalendar.hpp>\n#include <ql/time/daycounters/actual365fixed.hpp>\n\n#include <boost/make_shared.hpp>\n#include <boost/test/unit_test.hpp>\n\nusing namespace QuantLib;\nusing namespace QuantExt;\nusing namespace boost::unit_test_framework;\n\nstruct BFRRVolFixture : public qle::test::TopLevelFixture {\npublic:\n    BFRRVolFixture() { Settings::instance().evaluationDate() = refDate; }\n    Date refDate = Date(13, April, 2021);\n    std::vector<Date> dates = {refDate + 1 * Years, refDate + 3 * Years};\n    std::vector<Real> deltas = {0.10, 0.25};\n    std::vector<std::vector<Real>> bfQuotes = {{0.02, 0.01}, {0.01, 0.0050}};\n    std::vector<std::vector<Real>> rrQuotes = {{-0.015, -0.012}, {-0.011, -0.009}};\n    std::vector<Real> atmQuotes = {0.09, 0.08};\n    Actual365Fixed dc;\n    NullCalendar cal;\n    Handle<Quote> spot = Handle<Quote>(boost::make_shared<SimpleQuote>(1.2));\n    Size spotDays = 2;\n    Handle<YieldTermStructure> domesticTS =\n        Handle<YieldTermStructure>(boost::make_shared<FlatForward>(refDate, 0.01, dc));\n    Handle<YieldTermStructure> foreignTS =\n        Handle<YieldTermStructure>(boost::make_shared<FlatForward>(refDate, 0.015, dc));\n    DeltaVolQuote::DeltaType dt = DeltaVolQuote::DeltaType::PaSpot;\n    DeltaVolQuote::AtmType at = DeltaVolQuote::AtmType::AtmDeltaNeutral;\n    Period switchTenor = 2 * Years;\n    DeltaVolQuote::DeltaType ltdt = DeltaVolQuote::DeltaType::PaFwd;\n    DeltaVolQuote::AtmType ltat = DeltaVolQuote::AtmType::AtmDeltaNeutral;\n    Option::Type rrInFavorOf = Option::Call;\n    BlackVolatilitySurfaceBFRR::SmileInterpolation smileInterpolation =\n        BlackVolatilitySurfaceBFRR::SmileInterpolation::Cubic;\n};\n\nBOOST_AUTO_TEST_SUITE(QuantExtTestSuite)\n\nBOOST_FIXTURE_TEST_SUITE(BFRRVolSurfaceTest, BFRRVolFixture)\n\nBOOST_AUTO_TEST_CASE(testSmileBF) {\n\n    BOOST_TEST_MESSAGE(\"Testing bf/rr vol surface with smile bf quotes...\");\n\n    Real tol1 = 1E-5;\n\n    auto vol1 = boost::make_shared<BlackVolatilitySurfaceBFRR>(\n        refDate, dates, deltas, bfQuotes, rrQuotes, atmQuotes, dc, cal, spot, spotDays, cal, domesticTS, foreignTS, dt,\n        at, switchTenor, ltdt, ltat, rrInFavorOf, false, smileInterpolation);\n\n    Real t1 = vol1->timeFromReference(dates[0]);\n    Real domDisc1 = domesticTS->discount(dates[0] + spotDays) / domesticTS->discount(refDate + spotDays);\n    Real forDisc1 = foreignTS->discount(dates[0] + spotDays) / foreignTS->discount(refDate + spotDays);\n    Real k1_1_10p = getStrikeFromDelta(Option::Put, -deltas[0], dt, spot->value(), domDisc1, forDisc1, vol1, t1);\n    Real k1_1_25p = getStrikeFromDelta(Option::Put, -deltas[1], dt, spot->value(), domDisc1, forDisc1, vol1, t1);\n    Real k1_1_atm = getAtmStrike(dt, at, spot->value(), domDisc1, forDisc1, vol1, t1);\n    Real k1_1_25c = getStrikeFromDelta(Option::Call, deltas[1], dt, spot->value(), domDisc1, forDisc1, vol1, t1);\n    Real k1_1_10c = getStrikeFromDelta(Option::Call, deltas[0], dt, spot->value(), domDisc1, forDisc1, vol1, t1);\n\n    BOOST_CHECK_SMALL(vol1->blackVol(dates[0], k1_1_10p) - (atmQuotes[0] + bfQuotes[0][0] - 0.5 * rrQuotes[0][0]),\n                      tol1);\n    BOOST_CHECK_SMALL(vol1->blackVol(dates[0], k1_1_25p) - (atmQuotes[0] + bfQuotes[0][1] - 0.5 * rrQuotes[0][1]),\n                      tol1);\n    BOOST_CHECK_SMALL(vol1->blackVol(dates[0], k1_1_atm) - atmQuotes[0], tol1);\n    BOOST_CHECK_SMALL(vol1->blackVol(dates[0], k1_1_25c) - (atmQuotes[0] + bfQuotes[0][1] + 0.5 * rrQuotes[0][1]),\n                      tol1);\n    BOOST_CHECK_SMALL(vol1->blackVol(dates[0], k1_1_10c) - (atmQuotes[0] + bfQuotes[0][0] + 0.5 * rrQuotes[0][0]),\n                      tol1);\n\n    Real t2 = vol1->timeFromReference(dates[1]);\n    Real domDisc2 = domesticTS->discount(dates[1] + spotDays) / domesticTS->discount(refDate + spotDays);\n    Real forDisc2 = foreignTS->discount(dates[1] + spotDays) / foreignTS->discount(refDate + spotDays);\n    Real k1_2_10p = getStrikeFromDelta(Option::Put, -deltas[0], ltdt, spot->value(), domDisc2, forDisc2, vol1, t2);\n    Real k1_2_25p = getStrikeFromDelta(Option::Put, -deltas[1], ltdt, spot->value(), domDisc2, forDisc2, vol1, t2);\n    Real k1_2_atm = getAtmStrike(ltdt, ltat, spot->value(), domDisc2, forDisc2, vol1, t2);\n    Real k1_2_25c = getStrikeFromDelta(Option::Call, deltas[1], ltdt, spot->value(), domDisc2, forDisc2, vol1, t2);\n    Real k1_2_10c = getStrikeFromDelta(Option::Call, deltas[0], ltdt, spot->value(), domDisc2, forDisc2, vol1, t2);\n\n    BOOST_CHECK_SMALL(vol1->blackVol(dates[1], k1_2_10p) - (atmQuotes[1] + bfQuotes[1][0] - 0.5 * rrQuotes[1][0]),\n                      tol1);\n    BOOST_CHECK_SMALL(vol1->blackVol(dates[1], k1_2_25p) - (atmQuotes[1] + bfQuotes[1][1] - 0.5 * rrQuotes[1][1]),\n                      tol1);\n    BOOST_CHECK_SMALL(vol1->blackVol(dates[1], k1_2_atm) - atmQuotes[1], tol1);\n    BOOST_CHECK_SMALL(vol1->blackVol(dates[1], k1_2_25c) - (atmQuotes[1] + bfQuotes[1][1] + 0.5 * rrQuotes[1][1]),\n                      tol1);\n    BOOST_CHECK_SMALL(vol1->blackVol(dates[1], k1_2_10c) - (atmQuotes[1] + bfQuotes[1][0] + 0.5 * rrQuotes[1][0]),\n                      tol1);\n}\n\nBOOST_AUTO_TEST_CASE(testBrokerBF) {\n\n    BOOST_TEST_MESSAGE(\"Testing bf/rr vol surface with broker bf quotes...\");\n\n    Real tol1 = 1E-5;\n    Real tol2 = 1E-5;\n\n    auto vol2 = boost::make_shared<BlackVolatilitySurfaceBFRR>(\n        refDate, dates, deltas, bfQuotes, rrQuotes, atmQuotes, dc, cal, spot, spotDays, cal, domesticTS, foreignTS, dt,\n        at, switchTenor, ltdt, ltat, rrInFavorOf, true, smileInterpolation);\n\n    Real t1 = vol2->timeFromReference(dates[0]);\n    Real domDisc1 = domesticTS->discount(dates[0] + spotDays) / domesticTS->discount(refDate + spotDays);\n    Real forDisc1 = foreignTS->discount(dates[0] + spotDays) / foreignTS->discount(refDate + spotDays);\n    Real t2 = vol2->timeFromReference(dates[1]);\n    Real domDisc2 = domesticTS->discount(dates[1] + spotDays) / domesticTS->discount(refDate + spotDays);\n    Real forDisc2 = foreignTS->discount(dates[1] + spotDays) / foreignTS->discount(refDate + spotDays);\n\n    // checks for expiry 1\n\n    Real bfvol2_1_10_broker = atmQuotes[0] + bfQuotes[0][0];\n    Real bfvol2_1_25_broker = atmQuotes[0] + bfQuotes[0][1];\n\n    BlackDeltaCalculator bdc_1_10_p(Option::Put, dt, spot->value(), domDisc1, forDisc1,\n                                    bfvol2_1_10_broker * std::sqrt(t1));\n    Real k2_1_10p_broker = bdc_1_10_p.strikeFromDelta(-deltas[0]);\n\n    BlackDeltaCalculator bdc_1_10_c(Option::Call, dt, spot->value(), domDisc1, forDisc1,\n                                    bfvol2_1_10_broker * std::sqrt(t1));\n    Real k2_1_10c_broker = bdc_1_10_c.strikeFromDelta(deltas[0]);\n\n    BlackDeltaCalculator bdc_1_25_p(Option::Put, dt, spot->value(), domDisc1, forDisc1,\n                                    bfvol2_1_25_broker * std::sqrt(t1));\n    Real k2_1_25p_broker = bdc_1_25_p.strikeFromDelta(-deltas[1]);\n\n    BlackDeltaCalculator bdc_1_25_c(Option::Call, dt, spot->value(), domDisc1, forDisc1,\n                                    bfvol2_1_25_broker * std::sqrt(t1));\n    Real k2_1_25c_broker = bdc_1_25_c.strikeFromDelta(deltas[1]);\n\n    Real bfPrice_1_10_broker = blackFormula(Option::Put, k2_1_10p_broker, spot->value() / domDisc1 * forDisc1,\n                                            bfvol2_1_10_broker * std::sqrt(t1)) +\n                               blackFormula(Option::Call, k2_1_10c_broker, spot->value() / domDisc1 * forDisc1,\n                                            bfvol2_1_10_broker * std::sqrt(t1));\n\n    Real bfPrice_1_25_broker = blackFormula(Option::Put, k2_1_25p_broker, spot->value() / domDisc1 * forDisc1,\n                                            bfvol2_1_25_broker * std::sqrt(t1)) +\n                               blackFormula(Option::Call, k2_1_25c_broker, spot->value() / domDisc1 * forDisc1,\n                                            bfvol2_1_25_broker * std::sqrt(t1));\n\n    Real k2_1_10p = getStrikeFromDelta(Option::Put, -deltas[0], dt, spot->value(), domDisc1, forDisc1, vol2, t1);\n    Real k2_1_25p = getStrikeFromDelta(Option::Put, -deltas[1], dt, spot->value(), domDisc1, forDisc1, vol2, t1);\n    Real k2_1_atm = getAtmStrike(dt, at, spot->value(), domDisc1, forDisc1, vol2, t1);\n    Real k2_1_25c = getStrikeFromDelta(Option::Call, deltas[1], dt, spot->value(), domDisc1, forDisc1, vol2, t1);\n    Real k2_1_10c = getStrikeFromDelta(Option::Call, deltas[0], dt, spot->value(), domDisc1, forDisc1, vol2, t1);\n\n    Real bfPrice_1_10_smile = blackFormula(Option::Put, k2_1_10p_broker, spot->value() / domDisc1 * forDisc1,\n                                           std::sqrt(vol2->blackVariance(dates[0], k2_1_10p_broker))) +\n                              blackFormula(Option::Call, k2_1_10c_broker, spot->value() / domDisc1 * forDisc1,\n                                           std::sqrt(vol2->blackVariance(dates[0], k2_1_10c_broker)));\n\n    Real bfPrice_1_25_smile = blackFormula(Option::Put, k2_1_25p_broker, spot->value() / domDisc1 * forDisc1,\n                                           std::sqrt(vol2->blackVariance(dates[0], k2_1_25p_broker))) +\n                              blackFormula(Option::Call, k2_1_25c_broker, spot->value() / domDisc1 * forDisc1,\n                                           std::sqrt(vol2->blackVariance(dates[0], k2_1_25c_broker)));\n\n    // check broker bf premium = smile bf premium\n\n    BOOST_CHECK_SMALL(bfPrice_1_10_smile - bfPrice_1_10_broker, tol2);\n    BOOST_CHECK_SMALL(bfPrice_1_25_smile - bfPrice_1_25_broker, tol2);\n\n    // check rr and atm quotes are reproduced on smile\n\n    BOOST_CHECK_SMALL(vol2->blackVol(dates[0], k2_1_10c) - vol2->blackVol(dates[0], k2_1_10p) - rrQuotes[0][0], tol1);\n    BOOST_CHECK_SMALL(vol2->blackVol(dates[0], k2_1_25c) - vol2->blackVol(dates[0], k2_1_25p) - rrQuotes[0][1], tol1);\n    BOOST_CHECK_SMALL(vol2->blackVol(dates[0], k2_1_atm) - atmQuotes[0], tol1);\n\n    // checks for expiry 2\n\n    Real bfvol2_2_10_broker = atmQuotes[1] + bfQuotes[1][0];\n    Real bfvol2_2_25_broker = atmQuotes[1] + bfQuotes[1][1];\n\n    BlackDeltaCalculator bdc_2_10_p(Option::Put, ltdt, spot->value(), domDisc2, forDisc2,\n                                    bfvol2_2_10_broker * std::sqrt(t2));\n    Real k2_2_10p_broker = bdc_2_10_p.strikeFromDelta(-deltas[0]);\n\n    BlackDeltaCalculator bdc_2_10_c(Option::Call, ltdt, spot->value(), domDisc2, forDisc2,\n                                    bfvol2_2_10_broker * std::sqrt(t2));\n    Real k2_2_10c_broker = bdc_2_10_c.strikeFromDelta(deltas[0]);\n\n    BlackDeltaCalculator bdc_2_25_p(Option::Put, ltdt, spot->value(), domDisc2, forDisc2,\n                                    bfvol2_2_25_broker * std::sqrt(t2));\n    Real k2_2_25p_broker = bdc_2_25_p.strikeFromDelta(-deltas[1]);\n\n    BlackDeltaCalculator bdc_2_25_c(Option::Call, ltdt, spot->value(), domDisc2, forDisc2,\n                                    bfvol2_2_25_broker * std::sqrt(t2));\n    Real k2_2_25c_broker = bdc_2_25_c.strikeFromDelta(deltas[1]);\n\n    Real bfPrice_2_10_broker = blackFormula(Option::Put, k2_2_10p_broker, spot->value() / domDisc2 * forDisc2,\n                                            bfvol2_2_10_broker * std::sqrt(t2)) +\n                               blackFormula(Option::Call, k2_2_10c_broker, spot->value() / domDisc2 * forDisc2,\n                                            bfvol2_2_10_broker * std::sqrt(t2));\n\n    Real bfPrice_2_25_broker = blackFormula(Option::Put, k2_2_25p_broker, spot->value() / domDisc2 * forDisc2,\n                                            bfvol2_2_25_broker * std::sqrt(t2)) +\n                               blackFormula(Option::Call, k2_2_25c_broker, spot->value() / domDisc2 * forDisc2,\n                                            bfvol2_2_25_broker * std::sqrt(t2));\n\n    Real k2_2_10p = getStrikeFromDelta(Option::Put, -deltas[0], ltdt, spot->value(), domDisc2, forDisc2, vol2, t2);\n    Real k2_2_25p = getStrikeFromDelta(Option::Put, -deltas[1], ltdt, spot->value(), domDisc2, forDisc2, vol2, t2);\n    Real k2_2_atm = getAtmStrike(ltdt, ltat, spot->value(), domDisc2, forDisc2, vol2, t2);\n    Real k2_2_25c = getStrikeFromDelta(Option::Call, deltas[1], ltdt, spot->value(), domDisc2, forDisc2, vol2, t2);\n    Real k2_2_10c = getStrikeFromDelta(Option::Call, deltas[0], ltdt, spot->value(), domDisc2, forDisc2, vol2, t2);\n\n    Real bfPrice_2_10_smile = blackFormula(Option::Put, k2_2_10p_broker, spot->value() / domDisc2 * forDisc2,\n                                           std::sqrt(vol2->blackVariance(dates[1], k2_2_10p_broker))) +\n                              blackFormula(Option::Call, k2_2_10c_broker, spot->value() / domDisc2 * forDisc2,\n                                           std::sqrt(vol2->blackVariance(dates[1], k2_2_10c_broker)));\n\n    Real bfPrice_2_25_smile = blackFormula(Option::Put, k2_2_25p_broker, spot->value() / domDisc2 * forDisc2,\n                                           std::sqrt(vol2->blackVariance(dates[1], k2_2_25p_broker))) +\n                              blackFormula(Option::Call, k2_2_25c_broker, spot->value() / domDisc2 * forDisc2,\n                                           std::sqrt(vol2->blackVariance(dates[1], k2_2_25c_broker)));\n\n    // check broker bf premium = smile bf premium\n\n    BOOST_CHECK_SMALL(bfPrice_2_10_smile - bfPrice_2_10_broker, tol2);\n    BOOST_CHECK_SMALL(bfPrice_2_25_smile - bfPrice_2_25_broker, tol2);\n\n    // check rr and atm quotes are reproduced on smile\n\n    BOOST_CHECK_SMALL(vol2->blackVol(dates[1], k2_2_10c) - vol2->blackVol(dates[1], k2_2_10p) - rrQuotes[1][0], tol1);\n    BOOST_CHECK_SMALL(vol2->blackVol(dates[1], k2_2_25c) - vol2->blackVol(dates[1], k2_2_25p) - rrQuotes[1][1], tol1);\n    BOOST_CHECK_SMALL(vol2->blackVol(dates[1], k2_2_atm) - atmQuotes[1], tol1);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "44c619ced547e4d08206ae95875463c9038356aa", "size": 14857, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QuantExt/test/bfrrvolsurface.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/test/bfrrvolsurface.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/test/bfrrvolsurface.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": 58.03515625, "max_line_length": 119, "alphanum_fraction": 0.6562563102, "num_tokens": 4743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.6001883592602049, "lm_q1q2_score": 0.4820555630362386}}
{"text": "//\n// Copyright (c) 2018 CNRS\n//\n\n#include <cppad/cg.hpp>\n\n#include \"pinocchio/fwd.hpp\"\n#include \"pinocchio/multibody/model.hpp\"\n#include \"pinocchio/multibody/data.hpp\"\n\n#include \"pinocchio/algorithm/kinematics.hpp\"\n#include \"pinocchio/algorithm/jacobian.hpp\"\n#include \"pinocchio/algorithm/crba.hpp\"\n#include \"pinocchio/algorithm/rnea.hpp\"\n#include \"pinocchio/algorithm/aba.hpp\"\n#include \"pinocchio/algorithm/joint-configuration.hpp\"\n\n#include \"pinocchio/parsers/sample-models.hpp\"\n\n#include <iostream>\n\n#include <boost/test/unit_test.hpp>\n#include <boost/utility/binary.hpp>\n\nBOOST_AUTO_TEST_SUITE(BOOST_TEST_MODULE)\n\n  BOOST_AUTO_TEST_CASE(test_crba_code_generation)\n  {\n    typedef double Scalar;\n    typedef CppAD::cg::CG<Scalar> CGScalar;\n    typedef CppAD::AD<CGScalar> ADScalar;\n    \n    typedef Eigen::Matrix<ADScalar,Eigen::Dynamic,1> ADVector;\n    \n    typedef pinocchio::ModelTpl<Scalar> Model;\n    typedef Model::Data Data;\n    \n    typedef pinocchio::ModelTpl<ADScalar> ADModel;\n    typedef ADModel::Data ADData;\n    \n    Model model;\n    pinocchio::buildModels::humanoidRandom(model);\n    model.lowerPositionLimit.head<3>().fill(-1.);\n    model.upperPositionLimit.head<3>().fill(1.);\n    Data data(model);\n    \n    ADModel ad_model = model.cast<ADScalar>();\n    ADData ad_data(ad_model);\n    \n    // Sample random configuration\n    typedef Model::ConfigVectorType CongigVectorType;\n    typedef Model::TangentVectorType TangentVectorType;\n    CongigVectorType q(model.nq);\n    q = pinocchio::randomConfiguration(model);\n    \n    TangentVectorType v(TangentVectorType::Random(model.nv));\n    TangentVectorType a(TangentVectorType::Random(model.nv));\n    \n    typedef ADModel::ConfigVectorType ADCongigVectorType;\n    typedef ADModel::TangentVectorType ADTangentVectorType;\n    \n    ADCongigVectorType ad_q = q.cast<ADScalar>();\n    ADTangentVectorType ad_v = v.cast<ADScalar>();\n    ADTangentVectorType ad_a = a.cast<ADScalar>();\n\n    ADTangentVectorType & X = ad_a;\n    CppAD::Independent(X);\n    \n    pinocchio::rnea(ad_model,ad_data,ad_q,ad_v,ad_a);\n    ADVector Y(model.nv); Y = ad_data.tau;\n    \n    CppAD::ADFun<CGScalar> fun(X,Y);\n    \n    // generates source code\n    CppAD::cg::ModelCSourceGen<Scalar> cgen(fun, \"rnea\");\n    cgen.setCreateJacobian(true);\n    cgen.setCreateForwardZero(true);\n    cgen.setCreateForwardOne(true);\n    cgen.setCreateReverseOne(true);\n    cgen.setCreateReverseTwo(true);\n    CppAD::cg::ModelLibraryCSourceGen<Scalar> libcgen(cgen);\n\n    // compile source code\n    CppAD::cg::DynamicModelLibraryProcessor<Scalar> p(libcgen);\n\n    CppAD::cg::GccCompiler<Scalar> compiler;\n    std::unique_ptr<CppAD::cg::DynamicLib<Scalar>> dynamicLib = p.createDynamicLibrary(compiler);\n\n    // save to files (not really required)\n    CppAD::cg::SaveFilesModelLibraryProcessor<Scalar> p2(libcgen);\n    p2.saveSources();\n   \n    // use the generated code\n    std::unique_ptr<CppAD::cg::GenericModel<Scalar> > rnea_generated = dynamicLib->model(\"rnea\");\n    \n    CPPAD_TESTVECTOR(Scalar) x((size_t)model.nv);\n    Eigen::Map<TangentVectorType>(x.data(),model.nv,1) = a;\n    \n    CPPAD_TESTVECTOR(Scalar) tau = rnea_generated->ForwardZero(x);\n    \n    Eigen::Map<TangentVectorType> tau_map(tau.data(),model.nv,1);\n    Data::TangentVectorType tau_ref = pinocchio::rnea(model,data,q,v,a);\n    BOOST_CHECK(tau_map.isApprox(tau_ref));\n    \n    pinocchio::crba(model,data,q);\n    data.M.triangularView<Eigen::StrictlyLower>()\n    = data.M.transpose().triangularView<Eigen::StrictlyLower>();\n    \n    CPPAD_TESTVECTOR(Scalar) dtau_da = rnea_generated->Jacobian(x);\n    Eigen::Map<PINOCCHIO_EIGEN_PLAIN_ROW_MAJOR_TYPE(Data::MatrixXs)> M_map(dtau_da.data(),model.nv,model.nv);\n    BOOST_CHECK(M_map.isApprox(data.M));\n  }\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "b14af6c5cc4446e87ec334fcafea99cf95866147", "size": 3770, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittest/cppadcg-algo.cpp", "max_stars_repo_name": "mkatliar/pinocchio", "max_stars_repo_head_hexsha": "b755b9cf2567eab39de30a68b2a80fac802a4042", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "unittest/cppadcg-algo.cpp", "max_issues_repo_name": "mkatliar/pinocchio", "max_issues_repo_head_hexsha": "b755b9cf2567eab39de30a68b2a80fac802a4042", "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": "unittest/cppadcg-algo.cpp", "max_forks_repo_name": "mkatliar/pinocchio", "max_forks_repo_head_hexsha": "b755b9cf2567eab39de30a68b2a80fac802a4042", "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": 32.7826086957, "max_line_length": 109, "alphanum_fraction": 0.7188328912, "num_tokens": 1040, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342624, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4820555573808804}}
{"text": "/* vim: set tabstop=4 expandtab shiftwidth=4 softtabstop=4: */\n\n/**\n * \\file boost/numeric/ublasx/operation/dot.hpp\n *\n * \\brief Vector dot product.\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n *\n * <hr/>\n *\n * Copyright (c) 2011, Marco Guazzone\n * \n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#ifndef BOOST_NUMERIC_UBLASX_OPERATION_DOT_HPP\n#define BOOST_NUMERIC_UBLASX_OPERATION_DOT_HPP\n\n\n#include <boost/numeric/ublas/expression_types.hpp>\n#include <boost/numeric/ublas/traits.hpp>\n#include <boost/numeric/ublas/vector_expression.hpp>\n#include <boost/numeric/ublasx/operation/sum.hpp>\n\n\nnamespace boost { namespace numeric { namespace ublasx {\n\nusing namespace ::boost::numeric::ublas;\n\n\ntemplate <typename VecExpr1T, typename VecExpr2T>\nstruct vdot_traits_type\n{\n    typedef typename vector_scalar_binary_traits<\n                    VecExpr1T,\n                    VecExpr2T,\n                    vector_inner_prod<\n                        VecExpr1T,\n                        VecExpr2T,\n                        typename promote_traits<\n                            typename vector_traits<VecExpr1T>::value_type,\n                            typename vector_traits<VecExpr2T>::value_type\n                        >::promote_type\n                    >\n            >::result_type result_type;\n};\n\n\ntemplate <typename MatExpr1T, typename MatExpr2T>\nstruct mdot_traits_type\n{\n    typedef vector<\n                typename promote_traits<\n                    typename matrix_traits<MatExpr1T>::value_type,\n                    typename matrix_traits<MatExpr2T>::value_type\n                >::promote_type\n//              typename vector_traits<\n//                  typename matrix_binary_traits<\n//                          MatExpr1T,\n//                          MatExpr2T,\n//                          scalar_multiplies<\n//                                  typename MatExpr1T::value_type,\n//                                  typename MatExpr2T::value_type\n//                          >\n//                  >::result_type\n//              >::value_type\n            > result_type;\n};\n\n\n/**\n * \\brief Scalar product of two vectors.\n *\n * \\tparam VecExpr1T The type of the first vector.\n * \\tparam VecExpr2T The type of the second vector.\n * \\param v1 The first vector.\n * \\param v2 The second vector.\n * \\return The scalar product of vectors \\a v1 and \\a v2.\n *\n * The scalar product of two vectors \\f$u\\f$ and \\f$v\\f$ is defined as:\n * \\f[\n *   \\sum_{i} u_{i}v_{i}\n * \\f]\n */\ntemplate <typename VecExpr1T, typename VecExpr2T>\nBOOST_UBLAS_INLINE\ntypename vdot_traits_type<VecExpr1T,VecExpr2T>::result_type dot(vector_expression<VecExpr1T> const& v1,\n                                                                vector_expression<VecExpr2T> const& v2)\n{\n    return inner_prod(v1, v2);\n}\n\n\n/**\n * \\brief Scalar product of two matrices along a given dimension.\n *\n * \\tparam Dim The dimension used for computing the scalar product.\n * \\tparam MatExpr1T The type of the first matrix.\n * \\tparam MatExpr2T The type of the second matrix.\n * \\param M1 The first matrix.\n * \\param M2 The second matrix.\n * \\return A vector representing the scalar product of vectors \\a M1 and \\a M2\n *  along dimension \\a Dim.\n *\n * The scalar product of two matrices \\f$A\\f$ and \\f$B\\f$ along dimensino\n * \\f$d\\f$ is defined as:\n * - If \\f$d=1\\f$:\n *  \\f[\n *    \\sum_{j} A_{ij}B_{ij}, i=1,2,\\ldots\n *  \\f]\n * - If \\f$d=2\\f$:\n *  \\f[\n *    \\sum_{i} A_{ij}B_{ij}, j=1,2,\\ldots\n *  \\f]\n * .\n */\ntemplate <std::size_t Dim, typename MatExpr1T, typename MatExpr2T>\ntypename mdot_traits_type<MatExpr1T,MatExpr2T>::result_type dot(matrix_expression<MatExpr1T> const& M1,\n                                                                matrix_expression<MatExpr2T> const& M2)\n{\n    return sum<Dim>(element_prod(M1, M2));\n}\n\n}}} // Namespace boost::numeric::ublas\n\n\n#endif // BOOST_NUMERIC_UBLASX_OPERATION_DOT_HPP\n", "meta": {"hexsha": "81de3fda1e2c4c1e1589d872eaa94eee8f72df78", "size": 3998, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/ublasx/operation/dot.hpp", "max_stars_repo_name": "sguazt/boost-ublasx", "max_stars_repo_head_hexsha": "21c9b393d33a6ec2a8071ba8d48680073d766409", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2016-05-14T11:08:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-05T14:22:20.000Z", "max_issues_repo_path": "boost/numeric/ublasx/operation/dot.hpp", "max_issues_repo_name": "sguazt/boost-ublasx", "max_issues_repo_head_hexsha": "21c9b393d33a6ec2a8071ba8d48680073d766409", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-12-28T18:36:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-06T11:28:51.000Z", "max_forks_repo_path": "boost/numeric/ublasx/operation/dot.hpp", "max_forks_repo_name": "sguazt/boost-ublasx", "max_forks_repo_head_hexsha": "21c9b393d33a6ec2a8071ba8d48680073d766409", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-12-23T02:53:27.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-23T02:53:27.000Z", "avg_line_length": 30.5190839695, "max_line_length": 103, "alphanum_fraction": 0.6058029015, "num_tokens": 1000, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186768138228, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4820503985375164}}
{"text": "/* Boost interval/arith3.hpp template implementation file\r\n *\r\n * This headers provides arithmetical functions\r\n * which compute an interval given some base\r\n * numbers. The resulting interval encloses the\r\n * real result of the arithmetic operation.\r\n *\r\n * Copyright 2003 Guillaume Melquiond\r\n *\r\n * Distributed under the Boost Software License, Version 1.0.\r\n * (See accompanying file LICENSE_1_0.txt or\r\n * copy at http://www.boost.org/LICENSE_1_0.txt)\r\n */\r\n\r\n#ifndef BOOST_NUMERIC_INTERVAL_ARITH3_HPP\r\n#define BOOST_NUMERIC_INTERVAL_ARITH3_HPP\r\n\r\n#include <boost/numeric/interval/detail/interval_prototype.hpp>\r\n#include <boost/numeric/interval/detail/test_input.hpp>\r\n\r\nnamespace boost {\r\nnamespace numeric {\r\nnamespace interval_lib {\r\n\r\ntemplate<class I> inline\r\nI add(const typename I::base_type& x, const typename I::base_type& y)\r\n{\r\n  typedef typename I::traits_type Policies;\r\n  if (detail::test_input<typename I::base_type, Policies>(x, y))\r\n    return I::empty();\r\n  typename Policies::rounding rnd;\r\n  return I(rnd.add_down(x, y), rnd.add_up(x, y), true);\r\n}\r\n\r\ntemplate<class I> inline\r\nI sub(const typename I::base_type& x, const typename I::base_type& y)\r\n{\r\n  typedef typename I::traits_type Policies;\r\n  if (detail::test_input<typename I::base_type, Policies>(x, y))\r\n    return I::empty();\r\n  typename Policies::rounding rnd;\r\n  return I(rnd.sub_down(x, y), rnd.sub_up(x, y), true);\r\n}\r\n\r\ntemplate<class I> inline\r\nI mul(const typename I::base_type& x, const typename I::base_type& y)\r\n{\r\n  typedef typename I::traits_type Policies;\r\n  if (detail::test_input<typename I::base_type, Policies>(x, y))\r\n    return I::empty();\r\n  typename Policies::rounding rnd;\r\n  return I(rnd.mul_down(x, y), rnd.mul_up(x, y), true);\r\n}\r\n\r\ntemplate<class I> inline\r\nI div(const typename I::base_type& x, const typename I::base_type& y)\r\n{\r\n  typedef typename I::traits_type Policies;\r\n  if (detail::test_input<typename I::base_type, Policies>(x, y) || user::is_zero(y))\r\n    return I::empty();\r\n  typename Policies::rounding rnd;\r\n  return I(rnd.div_down(x, y), rnd.div_up(x, y), true);\r\n}\r\n\r\n} // namespace interval_lib\r\n} // namespace numeric\r\n} // namespace boost\r\n\r\n#endif // BOOST_NUMERIC_INTERVAL_ARITH3_HPP\r\n", "meta": {"hexsha": "a3b5ec9e792fd9fb104a8b5bfd502e7e6d9e5a6a", "size": 2219, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ios/Pods/boost-for-react-native/boost/numeric/interval/arith3.hpp", "max_stars_repo_name": "rudylee/expo", "max_stars_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_stars_repo_licenses": ["Apache-2.0", "MIT"], "max_stars_count": 8805.0, "max_stars_repo_stars_event_min_datetime": "2015-11-03T00:52:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T22:30:03.000Z", "max_issues_repo_path": "ios/Pods/boost-for-react-native/boost/numeric/interval/arith3.hpp", "max_issues_repo_name": "rudylee/expo", "max_issues_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_issues_repo_licenses": ["Apache-2.0", "MIT"], "max_issues_count": 14694.0, "max_issues_repo_issues_event_min_datetime": "2015-02-24T15:13:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T13:16:45.000Z", "max_forks_repo_path": "ios/Pods/boost-for-react-native/boost/numeric/interval/arith3.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": 31.7, "max_line_length": 85, "alphanum_fraction": 0.7129337539, "num_tokens": 553, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867681382279, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4820503985375163}}
{"text": "//Author: Dr. Shantanu Shahane\n#ifndef class_H_ /* Include guard */\n#define class_H_\n#include <stdio.h>\n#include <math.h>\n#include <stdlib.h>\n#include <time.h>\n#include <float.h>\n#include <string.h>\n#include <iostream>\n#include <vector>\n#include <Eigen/Dense>\n#include <unsupported/Eigen/SparseExtra>\n#include <Eigen/SparseLU>\n#include <Eigen/OrderingMethods>\n#include <Eigen/Core>\n#include \"_hypre_utilities.h\"\n#include \"HYPRE_krylov.h\"\n#include \"HYPRE.h\"\n#include \"HYPRE_parcsr_ls.h\"\n#include \"general_functions.hpp\"\nusing namespace std;\n\nconst int INTERIOR_TAG = -1;\n// const int INLET_BC_TAG = 1;\n// const int OUTLET_BC_TAG = 2;\n// const int WALL_BC_TAG = 3;\n// const int SYMMETRY_BC_TAG = 4;\n\ntemplate <typename T>\nstruct PointCloud\n{ //taken from Nanoflann library: \"utils.h\": https://github.com/jlblancoc/nanoflann/blob/master/examples/utils.h\n    struct Point\n    {\n        T x, y, z;\n    };\n    std::vector<Point> pts;\n    inline size_t kdtree_get_point_count() const { return pts.size(); } // Must return the number of data points\n    // Returns the dim'th component of the idx'th point in the class:\n    // Since this is inlined and the \"dim\" argument is typically an immediate value, the\n    //  \"if/else's\" are actually solved at compile time.\n    inline T kdtree_get_pt(const size_t idx, const size_t dim) const\n    {\n        if (dim == 0)\n            return pts[idx].x;\n        else if (dim == 1)\n            return pts[idx].y;\n        else\n            return pts[idx].z;\n    }\n    // Optional bounding-box computation: return false to default to a standard bbox computation loop.\n    //   Return true if the BBOX was already computed by the class and returned in \"bb\" so it can be avoided to redo it again.\n    //   Look at bb.size() to find out the expected dimensionality (e.g. 2 or 3 for point clouds)\n    template <class BBOX>\n    bool kdtree_get_bbox(BBOX & /* bb */) const { return false; }\n};\n\nclass PARAMETERS\n{\npublic:\n    int cloud_size;                            //cloud size\n    double cloud_size_multiplier;              //cloud size: cloud_size_multiplier * num_poly_terms\n    int phs_deg;                               //degree of the polyharmonic spline: r^(phs_deg)\n    int poly_deg;                              //degree of the polynomial to be appended\n    int num_poly_terms;                        //number of the polynomial terms to be appended\n    int dimension;                             //problem dimension (can be either 2 or 3 only)\n    Eigen::MatrixXi polynomial_term_exponents; //exponents of the polynomial terms\n    string meshfile;                           //meshfile name\n    string output_file_prefix;                 //used to write all output files\n    double max_dx, min_dx, avg_dx;             //characteristic length scales of mesh\n    vector<int> periodic_bc_index;             //periodic BC wrt 0:'x', 1:'y', 2:'z'; : size [no. of periodic axes]; ex. ['z','x']:[2,0]; ['y']:[1]\n    double dt;\n    double rho = -10.0, mu = rho; //should be set in the main file\n    double steady_tolerance, solver_tolerance, Courant, precond_droptol;\n    int nt, euclid_precond_level_hypre, gmres_kdim, n_iter;\n    string solver_type; //hypre_ilu_gmres, eigen_direct, eigen_ilu_bicgstab\n\n    double grad_x_eigval_real, grad_x_eigval_imag, grad_y_eigval_real, grad_y_eigval_imag, grad_z_eigval_real, grad_z_eigval_imag, laplace_eigval_real, laplace_eigval_imag;\n    double cloud_id_timer, rcm_timer, cloud_misc_timer, points_timer, grad_laplace_coeff_timer, factoring_timer, solve_timer, total_timer;\n    int nt_actual = 0;\n\n    vector<double> rel_res_log, abs_res_log, regul_alpha_log, steady_error_log; //logs of size nt_actual\n    vector<int> n_iter_actual;                                                  //logs of size nt_actual\n\npublic:\n    PARAMETERS(string parameter_file, string gmsh_file);\n    void read_calc_parameters(string parameter_file);\n    void verify_parameters();\n    void calc_cloud_num_points();\n    void get_problem_dimension_msh();\n    void calc_polynomial_term_exponents();\n    void calc_dt(Eigen::SparseMatrix<double, Eigen::RowMajor> &grad_x, Eigen::SparseMatrix<double, Eigen::RowMajor> &grad_y, Eigen::SparseMatrix<double, Eigen::RowMajor> &grad_z, Eigen::SparseMatrix<double, Eigen::RowMajor> &laplacian, double u0, double v0, double w0, double alpha);\n};\n\nclass POINTS\n{ //uses Compressed Row Format of Sparse Matrices\npublic:\n    vector<bool> corner_edge_vertices;                                   //true at corner (for 2D, 3D problems) and edge (for 3D problems only): size [nv]\n    int nv;                                                              //Number of vertices in original msh file\n    int nv_original;                                                     //Number of vertices\n    vector<double> xyz_min, xyz_max, xyz_length;                         //each of size:[dim]\n    vector<double> xyz;                                                  //vertex co-ordinates: size [nv X dim]\n    vector<double> xyz_original;                                         //all vertex co-ordinates in original msh file: size [nv_original X dim]; nv_original can be greater than nv\n    int nelem_original;                                                  //no. of elements in the original file\n    vector<bool> elem_boundary_flag_original;                            //boundary_flag=1 if elem is on boundary; else boundary_flag=0: size [nelem_original]\n    vector<vector<int>> elem_vert_original;                              //connectivity in original msh file\n    vector<double> boundary_face_area_original;                          //area or length of boundary elements for 3D or 2D (used to compute fluxes at boundaries): size [nelem_original]\n    vector<int> elem_bc_tag_original;                                    //bc_tag associated with each element (helps to identify various boundary areas and internal region): size [nelem_original]\n    vector<int> iv_original_nearest_vert;                                //nearest vertex no for vertices in xyz_original: size [nv_original]; nv_original can be greater than nv\n    vector<double> normal;                                               //vertex co-ordinates (relavant only for boundary vertices): size [nv X dim]\n    vector<bool> boundary_flag;                                          //boundary_flag=1 if it is on boundary; else boundary_flag=0: size [nv]\n    vector<vector<bool>> periodic_bc_flag;                               //periodic_bc_flag=1 if it is on periodic boundary; else periodic_bc_flag=0: size [nv][no. of periodic axes]\n    vector<vector<int>> periodic_bc_section;                             //takes values [-1,0,1] for [near_min,middle,near_max] sections respectively: size [nv][no. of periodic axes]\n    vector<int> bc_tag;                                                  //bc_tag associated with each vertex (helps to identify various boundary areas and internal region): size [nv]\n    Eigen::SparseMatrix<double, Eigen::RowMajor> grad_x_matrix_EIGEN;    //used for convection source term size [points.nv X points.nv]\n    Eigen::SparseMatrix<double, Eigen::RowMajor> grad_y_matrix_EIGEN;    //used for convection source term size [points.nv X points.nv]\n    Eigen::SparseMatrix<double, Eigen::RowMajor> grad_z_matrix_EIGEN;    //used for convection source term size [points.nv X points.nv]\n    Eigen::SparseMatrix<double, Eigen::RowMajor> laplacian_matrix_EIGEN; //used for diffusion source term size [points.nv X points.nv]\n\n    Eigen::SparseMatrix<double, Eigen::RowMajor> grad_x_matrix_EIGEN_boundary, grad_x_matrix_EIGEN_internal;       //[points.nv X points.nv]\n    Eigen::SparseMatrix<double, Eigen::RowMajor> grad_y_matrix_EIGEN_boundary, grad_y_matrix_EIGEN_internal;       //[points.nv X points.nv]\n    Eigen::SparseMatrix<double, Eigen::RowMajor> grad_z_matrix_EIGEN_boundary, grad_z_matrix_EIGEN_internal;       //[points.nv X points.nv]\n    Eigen::SparseMatrix<double, Eigen::RowMajor> laplacian_matrix_EIGEN_boundary, laplacian_matrix_EIGEN_internal; //[points.nv X points.nv]\n\npublic:\n    POINTS(PARAMETERS &parameters);\n    void read_points_xyz_msh(PARAMETERS &parameters);\n    void read_points_flag_msh(PARAMETERS &parameters);\n    void calc_vert_normal(PARAMETERS &parameters);\n    void calc_boundary_face_area(PARAMETERS &parameters);\n    void calc_elem_bc_tag(PARAMETERS &parameters);\n    void read_elem_vert_complete_msh(PARAMETERS &parameters, vector<vector<int>> &elem_vert, vector<bool> &elem_boundary_flag);\n    void calc_vert_nb_cv(PARAMETERS &parameters, vector<vector<int>> &vert_nb_cv, vector<vector<int>> &elem_vert);\n    void calc_elem_normal_2D(vector<double> &elem_normal, vector<vector<int>> &vert_nb_cv, vector<vector<int>> &elem_vert, vector<bool> &elem_boundary_flag);\n    void calc_elem_normal_3D(vector<double> &elem_normal, vector<vector<int>> &vert_nb_cv, vector<vector<int>> &elem_vert, vector<bool> &elem_boundary_flag);\n    void delete_corner_edge_vertices(PARAMETERS &parameters);\n    void delete_periodic_bc_vertices(PARAMETERS &parameters);\n    void set_periodic_bc(PARAMETERS &parameters, vector<string> periodic_axis);\n};\n\nclass CLOUD\n{\npublic:\n    vector<int> nb_points_row;      //neighboring points of each point: size: nv+1\n    vector<int> nb_points_col;      //neighboring points of each point: size: nb_points_row[nv]\n    vector<double> grad_x_coeff;    //coefficient for grad_x at each point: base: (CLOUD.nb_points_row, CLOUD.nb_points_col)\n    vector<double> grad_y_coeff;    //coefficient for grad_y at each point: base: (CLOUD.nb_points_row, CLOUD.nb_points_col)\n    vector<double> grad_z_coeff;    //coefficient for grad_z at each point: base: (CLOUD.nb_points_row, CLOUD.nb_points_col)\n    vector<double> laplacian_coeff; //coefficient for laplacian at each point: base: (CLOUD.nb_points_row, CLOUD.nb_points_col)\n    vector<double> cond_num_RBF;    //condition number of RBF A matrix for each point: size [nv]\n    double cond_num_RBF_max;        //statistics of cond_num_RBF\n    double cond_num_RBF_min;        //statistics of cond_num_RBF\n    double cond_num_RBF_avg;        //statistics of cond_num_RBF\n    vector<int> rcm_points_order;   //reordering list obtained by RCM algorithm\npublic:\n    CLOUD(POINTS &points, PARAMETERS &parameters);\n    void calc_cloud_points_slow(POINTS &points, PARAMETERS &parameters);\n    void calc_cloud_points_fast(POINTS &points, PARAMETERS &parameters);\n    void calc_cloud_points_fast_periodic_bc(POINTS &points, PARAMETERS &parameters);\n    void calc_cloud_points_fast_periodic_bc_shifted(POINTS &points, PARAMETERS &parameters, vector<double> &xyz_shifted, vector<int> &periodic_bc_section_value);\n    void re_order_points_reverse_cuthill_mckee(POINTS &points, PARAMETERS &parameters);\n    void re_order_points(POINTS &points, PARAMETERS &parameters);\n    void calc_iv_original_nearest_vert(POINTS &points, PARAMETERS &parameters);\n    void calc_charac_dx(POINTS &points, PARAMETERS &parameters);\n    void calc_grad_laplace_coeffs(POINTS &points, PARAMETERS &parameters);\n    void EIGEN_set_grad_laplace_matrix(POINTS &points, PARAMETERS &parameters);\n    void EIGEN_set_grad_laplace_matrix_separate(POINTS &points, PARAMETERS &parameters);\n};\n\nclass SOLVER\n{\npublic:\n    // Functions\n    void init(POINTS &points, CLOUD &cloud, PARAMETERS &parameters, vector<bool> &dirichlet_flag, double unsteady_term_coeff, double conv_term_coeff, double diff_term_coeff, bool log_flag);\n    void HYPRE_set_coeff(PARAMETERS &parameters);\n    void EIGEN_set_coeff();\n    void general_solve(POINTS &points, PARAMETERS &parameters, Eigen::VectorXd &field_new, Eigen::VectorXd &field_old, Eigen::VectorXd &rhs);\n    void set_solve_parameters();\n    void calc_coeff_matrix(POINTS &points, CLOUD &cloud, PARAMETERS &parameters);\n    void scale_coeff(POINTS &points);\n\n    // Variables\n    HYPRE_IJMatrix coeff_HYPRE;\n    HYPRE_ParCSRMatrix parcsr_coeff_HYPRE;\n    HYPRE_IJVector source_HYPRE;\n    HYPRE_ParVector par_source_HYPRE;\n    HYPRE_IJVector X_HYPRE;\n    HYPRE_ParVector par_X_HYPRE;\n    HYPRE_Solver solver_X_HYPRE, precond_X_HYPRE;\n    Eigen::SparseMatrix<double, Eigen::RowMajor> coeff_EIGEN;\n    Eigen::SparseLU<Eigen::SparseMatrix<double, Eigen::RowMajor>, Eigen::COLAMDOrdering<int>> solver_eigen_direct;\n    Eigen::BiCGSTAB<Eigen::SparseMatrix<double, Eigen::RowMajor>, Eigen::IncompleteLUT<double>> solver_eigen_ilu_bicgstab;\n\n    vector<tuple<int, int, double>> coeff_matrix; //store coefficient matrix with sparsity structure of (row, col, value)\n    vector<double> scale;\n\n    int *rows_HYPRE; //array of size ncv going from 0 to ncv-1\n    double *X;       //unknown vector\n    double *source;  //source term\n\n    string solver_type; //hypre_ilu_gmres, eigen_direct, eigen_ilu_bicgstab\n    double unsteady_term_coeff_1, conv_term_coeff_1, diff_term_coeff_1;\n    int print_flag = 0;             //decide how much to print during solution\n    int n_iter;                     //max solver iterations\n    int euclid_precond_level_hypre; //level setting in Euclid pre-conditioner\n    double precond_droptol;         //setting in Euclid pre-conditioner\n    int gmres_kdim;                 //GMRES max size of Krylov subspace\n    double solver_tolerance;        //solver tolerance\n    double l2_norm;\n    vector<bool> dirichlet_flag_1; //true: use Dirichlet BC, else use Neumann BC\n    int system_size;               //no. of unknowns\n    bool log_flag_1 = true;\n};\n\nclass FRACTIONAL_STEP_1\n{ //hat velocity formulation\npublic:\n    // Functions\n    FRACTIONAL_STEP_1(POINTS &points, CLOUD &cloud, PARAMETERS &parameters, vector<bool> &u_dirichlet_flag1, vector<bool> &v_dirichlet_flag1, vector<bool> &p_dirichlet_flag1, int temporal_order1);\n    void check_bc(POINTS &points, PARAMETERS &parameters);\n    void single_timestep_2d(POINTS &points, CLOUD &cloud, PARAMETERS &parameters, Eigen::VectorXd &u_new, Eigen::VectorXd &v_new, Eigen::VectorXd &p_new, Eigen::VectorXd &u_old, Eigen::VectorXd &v_old, Eigen::VectorXd &p_old, int it1);\n    void single_timestep_2d(POINTS &points, CLOUD &cloud, PARAMETERS &parameters, Eigen::VectorXd &u_new, Eigen::VectorXd &v_new, Eigen::VectorXd &p_new, Eigen::VectorXd &u_old, Eigen::VectorXd &v_old, Eigen::VectorXd &p_old, Eigen::VectorXd &body_force_x, Eigen::VectorXd &body_force_y, int it1);\n    void calc_vel_hat(POINTS &points, PARAMETERS &parameters, Eigen::VectorXd &u_old, Eigen::VectorXd &v_old, Eigen::VectorXd &p_old);\n    void calc_vel_hat(POINTS &points, PARAMETERS &parameters, Eigen::VectorXd &u_old, Eigen::VectorXd &v_old, Eigen::VectorXd &p_old, Eigen::VectorXd &body_force_x, Eigen::VectorXd &body_force_y);\n    void calc_pressure(POINTS &points, PARAMETERS &parameters, Eigen::VectorXd &u_new, Eigen::VectorXd &v_new, Eigen::VectorXd &p_new, Eigen::VectorXd &u_old, Eigen::VectorXd &v_old, Eigen::VectorXd &p_old);\n    void calc_vel_corr(POINTS &points, CLOUD &cloud, PARAMETERS &parameters, Eigen::VectorXd &u_new, Eigen::VectorXd &v_new, Eigen::VectorXd &p_new, Eigen::VectorXd &u_old, Eigen::VectorXd &v_old);\n    void extras(POINTS &points, PARAMETERS &parameters, Eigen::VectorXd &u_new, Eigen::VectorXd &v_new, Eigen::VectorXd &p_new, Eigen::VectorXd &u_old, Eigen::VectorXd &v_old, Eigen::VectorXd &p_old);\n\n    // Variables\n    SOLVER solver_p;\n    Eigen::VectorXd zero_vector, zero_vector_1;\n    Eigen::VectorXd uh, vh;\n    Eigen::VectorXd p_source;\n    Eigen::VectorXd u_source_old, v_source_old;\n    Eigen::VectorXd u_source_old_old, v_source_old_old; //used only for multi-step method\n    vector<bool> u_dirichlet_flag, v_dirichlet_flag, p_dirichlet_flag;\n    bool p_bc_full_neumann;\n    int temporal_order = -1, it;\n};\n\nclass IMPLICIT_SCALAR_TRANSPORT_SOLVER\n{ //scalar transport with spatially varying velocity field: BDF2\npublic:\n    // Functions\n    IMPLICIT_SCALAR_TRANSPORT_SOLVER(POINTS &points, CLOUD &cloud, PARAMETERS &parameters, vector<bool> &dirichlet_flag1, int precond_freq_it1, double unsteady_coeff1, double conv_coeff1, double diff_coeff1, bool solver_log_flag1);\n    void single_timestep_2d(POINTS &points, CLOUD &cloud, PARAMETERS &parameters, Eigen::VectorXd &phi_new, Eigen::VectorXd &phi_old, Eigen::VectorXd &u_new, Eigen::VectorXd &v_new, int it1);\n    void set_matrix(POINTS &points, CLOUD &cloud, PARAMETERS &parameters, Eigen::VectorXd &u_new, Eigen::VectorXd &v_new);\n    void modify_matrix(POINTS &points, CLOUD &cloud, PARAMETERS &parameters, Eigen::VectorXd &u_new, Eigen::VectorXd &v_new);\n    void calc_nb_points_col_matrix(POINTS &points, CLOUD &cloud, PARAMETERS &parameters);\n\n    // Variables\n    Eigen::SparseMatrix<double, Eigen::RowMajor> matrix;\n    Eigen::BiCGSTAB<Eigen::SparseMatrix<double, Eigen::RowMajor>, Eigen::IncompleteLUT<double>> solver_eigen;\n    Eigen::VectorXd zero_vector, source, phi_old_old;\n    vector<bool> dirichlet_flag;\n    vector<int> nb_points_col_matrix;\n    bool bc_full_neumann, solver_log_flag;\n    int it, precond_freq_it;\n    double unsteady_coeff, conv_coeff, diff_coeff;\n    double bdf2_alpha_1 = 1.5, bdf2_alpha_2 = -2.0, bdf2_alpha_3 = 0.5; //https://en.wikipedia.org/wiki/Backward_differentiation_formula\n};\n\nclass SEMI_IMPLICIT_SPLIT_SOLVER\n{ //iterative split solver for Navier-Stokes equations\npublic:\n    // Functions\n    SEMI_IMPLICIT_SPLIT_SOLVER(POINTS &points, CLOUD &cloud, PARAMETERS &parameters, vector<bool> &u_dirichlet_flag1, vector<bool> &v_dirichlet_flag1, vector<bool> &p_dirichlet_flag1, int n_outer_iter1, double iterative_tolerance1, int precond_freq_it1);\n    void check_bc(POINTS &points, PARAMETERS &parameters);\n    void single_timestep_2d(POINTS &points, CLOUD &cloud, PARAMETERS &parameters, Eigen::VectorXd &u_new, Eigen::VectorXd &v_new, Eigen::VectorXd &p_new, Eigen::VectorXd &u_old, Eigen::VectorXd &v_old, Eigen::VectorXd &p_old, int it1, vector<int> &n_outer_iter_log, vector<double> &iterative_l1_err_log, vector<double> &iterative_max_err_log);\n    void single_timestep_2d(POINTS &points, CLOUD &cloud, PARAMETERS &parameters, Eigen::VectorXd &u_new, Eigen::VectorXd &v_new, Eigen::VectorXd &p_new, Eigen::VectorXd &u_old, Eigen::VectorXd &v_old, Eigen::VectorXd &p_old, Eigen::VectorXd &body_force_x, Eigen::VectorXd &body_force_y, int it1, vector<int> &n_outer_iter_log, vector<double> &iterative_l1_err_log, vector<double> &iterative_max_err_log);\n    void set_vel_matrix(POINTS &points, CLOUD &cloud, PARAMETERS &parameters, Eigen::VectorXd &u_new, Eigen::VectorXd &v_new);\n    void calc_nb_points_col_matrix(POINTS &points, CLOUD &cloud, PARAMETERS &parameters);\n    void modify_vel_matrix(POINTS &points, CLOUD &cloud, PARAMETERS &parameters, Eigen::VectorXd &u_new, Eigen::VectorXd &v_new);\n    void calc_vel(POINTS &points, PARAMETERS &parameters, Eigen::VectorXd &u_new, Eigen::VectorXd &v_new, Eigen::VectorXd &p_new, Eigen::VectorXd &u_old, Eigen::VectorXd &v_old, Eigen::VectorXd &p_old);\n    void calc_vel(POINTS &points, PARAMETERS &parameters, Eigen::VectorXd &u_new, Eigen::VectorXd &v_new, Eigen::VectorXd &p_new, Eigen::VectorXd &u_old, Eigen::VectorXd &v_old, Eigen::VectorXd &p_old, Eigen::VectorXd &body_force_x, Eigen::VectorXd &body_force_y);\n    void calc_pressure(POINTS &points, CLOUD &cloud, PARAMETERS &parameters, Eigen::VectorXd &u_new, Eigen::VectorXd &v_new, Eigen::VectorXd &p_new, Eigen::VectorXd &u_old, Eigen::VectorXd &v_old, Eigen::VectorXd &p_old);\n    void calc_vel_corr(POINTS &points, CLOUD &cloud, PARAMETERS &parameters, Eigen::VectorXd &u_new, Eigen::VectorXd &v_new);\n    void extras(POINTS &points, PARAMETERS &parameters, Eigen::VectorXd &u_new, Eigen::VectorXd &v_new, Eigen::VectorXd &p_new, Eigen::VectorXd &u_old, Eigen::VectorXd &v_old, Eigen::VectorXd &p_old);\n\n    // Variables\n    SOLVER solver_p;\n    Eigen::SparseMatrix<double, Eigen::RowMajor> matrix_u, matrix_v;\n    Eigen::BiCGSTAB<Eigen::SparseMatrix<double, Eigen::RowMajor>, Eigen::IncompleteLUT<double>> solver_eigen_u, solver_eigen_v;\n    Eigen::VectorXd zero_vector, zero_vector_1;\n    Eigen::VectorXd normal_mom_x, normal_mom_y;\n    Eigen::VectorXd p_prime, p_source, u_source, v_source, u_prime, v_prime, u_iter_old, v_iter_old, u_old_old, v_old_old;\n    vector<bool> u_dirichlet_flag, v_dirichlet_flag, p_dirichlet_flag;\n    vector<int> nb_points_col_matrix_u, nb_points_col_matrix_v;\n    bool p_bc_full_neumann;\n    double iterative_tolerance, iterative_l1_err, iterative_max_err;\n    int it, n_outer_iter, outer_iter, precond_freq_it;\n    double bdf2_alpha_1 = 1.5, bdf2_alpha_2 = -2.0, bdf2_alpha_3 = 0.5; //https://en.wikipedia.org/wiki/Backward_differentiation_formula\n};\n\nclass SOLIDIFICATION\n{\npublic:\n    // Functions\n    SOLIDIFICATION(POINTS &points, CLOUD &cloud, PARAMETERS &parameters, int temporal_order1);\n    void single_timestep_2d(POINTS &points, CLOUD &cloud, PARAMETERS &parameters, Eigen::VectorXd &T_new, Eigen::VectorXd &T_old, Eigen::VectorXd &fs_new, Eigen::VectorXd &fs_old, int it);\n\n    // Variables\n    Eigen::VectorXd dfs_dT, T_source;\n    Eigen::VectorXd T_old_old, fs_old_old; //used only for multi-step method\n    double Tliq = 915.0;\n    double Tsol = 850.0;\n    double Tf = 935.2;\n    double Teps = 2.0;\n    double k_partition = 0.13;\n    double Lf = 390000.0;\n    double Cp = 1006.0;\n    double alpha = 5E-5;\n    int temporal_order = -1;\n};\n\n#endif", "meta": {"hexsha": "d8b3c5e86743709dde85b22f21497bba22fa13f8", "size": 21239, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "header_files/class.hpp", "max_stars_repo_name": "shahaneshantanu/memphys", "max_stars_repo_head_hexsha": "1b95afa505808f302d2dd4689faa45bb6480e8d8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "header_files/class.hpp", "max_issues_repo_name": "shahaneshantanu/memphys", "max_issues_repo_head_hexsha": "1b95afa505808f302d2dd4689faa45bb6480e8d8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "header_files/class.hpp", "max_forks_repo_name": "shahaneshantanu/memphys", "max_forks_repo_head_hexsha": "1b95afa505808f302d2dd4689faa45bb6480e8d8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-07T00:32:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T00:32:37.000Z", "avg_line_length": 67.2120253165, "max_line_length": 405, "alphanum_fraction": 0.7187720702, "num_tokens": 5421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186768138228, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4820503985375163}}
{"text": "#include <calibrator/processes/generalhullwhiteprocess.hpp>\n\n#include <boost/bind.hpp>\n\n#include <ql/compounding.hpp>\n\nnamespace HJCALIBRATOR\n{\n\tGeneralizedHullWhiteProcess::GeneralizedHullWhiteProcess( const Handle<YieldTermStructure>& h,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  const IntegrableParameter& a,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  const Parameter& sigma )\n\t\t: termStructure_( h ), a_( a ), sigma_( sigma )\n\t\t, r0_( h->forwardRate( 0.0, 0.0, Continuous, NoFrequency ) )\n\t\t, integrator_( SimpsonIntegral( 0.00001, 1000 ) )\n\t\t, Vrintegrand_( boost::bind( &GeneralizedHullWhiteProcess::VrIntegrand, this, _1 ) )\n\t\t, OneOverEintegrand_( boost::bind( &GeneralizedHullWhiteProcess::E, this, _1, -1. ) )\n\t{}\n}", "meta": {"hexsha": "d22d2e7a91b2433a4fa5ee1a2d304fa5f16d5f80", "size": 674, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "calibrator/obsolete/generalhullwhiteprocess.cpp", "max_stars_repo_name": "hanjin-kim/gaussian-n-factor", "max_stars_repo_head_hexsha": "0865fa115094e1f7f8e968eb8f7f123c2cc26c9f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-02-25T05:59:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-27T04:10:19.000Z", "max_issues_repo_path": "calibrator/obsolete/generalhullwhiteprocess.cpp", "max_issues_repo_name": "hanjin-kim/gaussian-n-factor", "max_issues_repo_head_hexsha": "0865fa115094e1f7f8e968eb8f7f123c2cc26c9f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "calibrator/obsolete/generalhullwhiteprocess.cpp", "max_forks_repo_name": "hanjin-kim/gaussian-n-factor", "max_forks_repo_head_hexsha": "0865fa115094e1f7f8e968eb8f7f123c2cc26c9f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-07-27T04:10:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-27T04:10:42.000Z", "avg_line_length": 37.4444444444, "max_line_length": 95, "alphanum_fraction": 0.7047477745, "num_tokens": 209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186768138228, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4820503985375163}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n// Quickbook Examples, for main page\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\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 <iostream>\r\n\r\n//[quickstart_include\r\n\r\n#include <boost/geometry.hpp>\r\n#include <boost/geometry/geometries/point_xy.hpp>\r\n#include <boost/geometry/geometries/polygon.hpp>\r\n\r\nusing namespace boost::geometry;\r\n//]\r\n\r\n#include <boost/geometry/geometries/register/point.hpp>\r\n\r\n\r\n//[quickstart_register_c_array\r\n#include <boost/geometry/geometries/adapted/c_array.hpp>\r\n\r\nBOOST_GEOMETRY_REGISTER_C_ARRAY_CS(cs::cartesian)\r\n//]\r\n\r\n//[quickstart_register_boost_tuple\r\n#include <boost/geometry/geometries/adapted/boost_tuple.hpp>\r\n\r\nBOOST_GEOMETRY_REGISTER_BOOST_TUPLE_CS(cs::cartesian)\r\n//]\r\n\r\n// Small QRect simulations following http://doc.trolltech.com/4.4/qrect.html\r\n// Todo: once work the traits out further, would be nice if there is a real example of this.\r\n// However for the example it makes no difference, it will work any way.\r\nstruct QPoint\r\n{\r\n    int x, y;\r\n    // In Qt these are methods but for example below it makes no difference\r\n};\r\n\r\nstruct QRect\r\n{\r\n    int x, y, width, height;\r\n    QRect(int _x, int _y, int w, int h)\r\n        : x(_x), y(_y), width(w), height(h)\r\n    {}\r\n    // In Qt these are methods but that will work as well, requires changing traits below\r\n};\r\n\r\n\r\n// Would be get/set with x(),y(),setX(),setY()\r\nBOOST_GEOMETRY_REGISTER_POINT_2D(QPoint, int, cs::cartesian, x, y)\r\n\r\n\r\n// Register the QT rectangle. The macro(s) does not offer (yet) enough flexibility to do this in one line,\r\n// but the traits classes do their job perfectly.\r\nnamespace boost { namespace geometry { namespace traits\r\n{\r\n\r\ntemplate <> struct tag<QRect> { typedef box_tag type; };\r\ntemplate <> struct point_type<QRect> { typedef QPoint type; };\r\n\r\ntemplate <size_t C, size_t D>\r\nstruct indexed_access<QRect, C, D>\r\n{\r\n    static inline int get(const QRect& qr)\r\n    {\r\n        // Would be: x(), y(), width(), height()\r\n        return C == min_corner && D == 0 ? qr.x\r\n                : C == min_corner && D == 1 ? qr.y\r\n                : C == max_corner && D == 0 ? qr.x + qr.width\r\n                : C == max_corner && D == 1 ? qr.y + qr.height\r\n                : 0;\r\n    }\r\n\r\n    static inline void set(QRect& qr, const int& value)\r\n    {\r\n        // Would be: setX, setY, setWidth, setHeight\r\n        if (C == min_corner && D == 0) qr.x = value;\r\n        else if (C == min_corner && D == 1) qr.y = value;\r\n        else if (C == max_corner && D == 0) qr.width = value - qr.x;\r\n        else if (C == max_corner && D == 1) qr.height = value - qr.y;\r\n    }\r\n};\r\n\r\n\r\n}}}\r\n\r\n\r\nint main(void)\r\n{\r\n    //[quickstart_distance\r\n    model::d2::point_xy<int> p1(1, 1), p2(2, 2);\r\n    std::cout << \"Distance p1-p2 is: \" << distance(p1, p2) << std::endl;\r\n    //]\r\n\r\n    //[quickstart_distance_c_array\r\n    int a[2] = {1,1};\r\n    int b[2] = {2,3};\r\n    double d = distance(a, b);\r\n    std::cout << \"Distance a-b is: \" << d << std::endl;\r\n    //]\r\n\r\n    //[quickstart_point_in_polygon\r\n    double points[][2] = {{2.0, 1.3}, {4.1, 3.0}, {5.3, 2.6}, {2.9, 0.7}, {2.0, 1.3}};\r\n    model::polygon<model::d2::point_xy<double> > poly;\r\n    append(poly, points);\r\n    boost::tuple<double, double> p = boost::make_tuple(3.7, 2.0);\r\n    std::cout << \"Point p is in polygon? \" << std::boolalpha << within(p, poly) << std::endl;\r\n    //]\r\n\r\n    //[quickstart_area\r\n    std::cout << \"Area: \" << area(poly) << std::endl;\r\n    //]\r\n\r\n    //[quickstart_distance_mixed\r\n    double d2 = distance(a, p);\r\n    std::cout << \"Distance a-p is: \" << d2 << std::endl;\r\n    //]\r\n\r\n    //[quick_start_spherical\r\n    typedef boost::geometry::model::point\r\n        <\r\n            double, 2, boost::geometry::cs::spherical_equatorial<boost::geometry::degree>\r\n        > spherical_point;\r\n\r\n    spherical_point amsterdam(4.90, 52.37);\r\n    spherical_point paris(2.35, 48.86);\r\n\r\n    double const earth_radius = 3959; // miles\r\n    std::cout << \"Distance in miles: \" << distance(amsterdam, paris) * earth_radius << std::endl;\r\n    //]\r\n\r\n    /***\r\n    Now extension\r\n    point_ll_deg  amsterdam, paris;\r\n    parse(amsterdam, \"52 22 23 N\", \"4 53 32 E\");\r\n    parse(paris, \"48 52 0 N\", \"2 19 59 E\");\r\n    std::cout << \"Distance A'dam-Paris: \" << distance(amsterdam, paris) / 1000.0 << \" kilometers \" << std::endl;\r\n    ***/\r\n\r\n    //[quickstart_qt\r\n    QRect r1(100, 200, 15, 15);\r\n    QRect r2(110, 210, 20, 20);\r\n    if (overlaps(r1, r2))\r\n    {\r\n        assign_values(r2, 200, 300, 220, 320);\r\n    }\r\n    //]\r\n\r\n    return 0;\r\n}\r\n\r\n", "meta": {"hexsha": "ba3f1b5c9c164d3292bd02743578509571c011e9", "size": 5197, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/geometry/doc/src/examples/quick_start.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": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/geometry/doc/src/examples/quick_start.cpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-03-04T11:21:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-24T01:36:31.000Z", "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/geometry/doc/src/examples/quick_start.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 30.5705882353, "max_line_length": 113, "alphanum_fraction": 0.6088127766, "num_tokens": 1489, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419958239132, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.48204996326143823}}
{"text": "#include <blitz/array.h>\n\n/**\n  Simple example of a function dealing with a blitz array\n*/\nblitz::Array<double,1> reverse (const blitz::Array<double,1>& array){\n  // create new array in the desired shape\n  blitz::Array<double,1> retval(array.shape());\n  // copy data\n  for (int i = 0, j = array.extent(0)-1; i < array.extent(0); ++i, --j){\n    retval(j) = array(i);\n  }\n  // return the copied data\n  return retval;\n}\n", "meta": {"hexsha": "748d85fe376ca6969fa0a93e19f10f9e1a80e7aa", "size": 417, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bob/blitz/examples/bob.example.extension/bob/example/extension/Function.cpp", "max_stars_repo_name": "bioidiap/bob.blitz", "max_stars_repo_head_hexsha": "348d7cf3866b549cac576efc3c6f3df24245d9fd", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/blitz/examples/bob.example.extension/bob/example/extension/Function.cpp", "max_issues_repo_name": "bioidiap/bob.blitz", "max_issues_repo_head_hexsha": "348d7cf3866b549cac576efc3c6f3df24245d9fd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2015-01-01T09:15:28.000Z", "max_issues_repo_issues_event_max_datetime": "2016-10-20T08:09:26.000Z", "max_forks_repo_path": "bob/blitz/examples/bob.example.extension/bob/example/extension/Function.cpp", "max_forks_repo_name": "bioidiap/bob.blitz", "max_forks_repo_head_hexsha": "348d7cf3866b549cac576efc3c6f3df24245d9fd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2015-08-05T12:16:45.000Z", "max_forks_repo_forks_event_max_datetime": "2018-02-01T19:55:40.000Z", "avg_line_length": 26.0625, "max_line_length": 72, "alphanum_fraction": 0.6426858513, "num_tokens": 121, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.6959583376458152, "lm_q1q2_score": 0.4820499631661517}}
{"text": "/**\n * \\file      algebraic-sensor.hpp\n * \\author    Mehdi Benallegue\n * \\date       2013\n * \\brief     Gives a base class for algebraic sensors\n *\n *\n */\n\n#ifndef SIMULATIONALGEBRAICSENSORHPP\n#define SIMULATIONALGEBRAICSENSORHPP\n\n#include <boost/assert.hpp>\n#include <Eigen/Core>\n\n#include <state-observation/api.h>\n#include <state-observation/sensors-simulation/sensor-base.hpp>\n\nnamespace stateObservation\n{\n/**\n * \\class  AlgebraicSensor\n * \\brief  The base class for algebraic sensors. Algebraic sensors are sensors\n *         which depend only on the state value and the current time\n *          and do not have internal dynamics\n *         (or a dynamics which converges fast enough to be ignored). This class\n *         implements mostly the containers and the interface to algebraic sensors.\n *         Algebraic sensors must be derived from this class.\n *\n * \\details\n *\n */\n\nclass STATE_OBSERVATION_DLLAPI AlgebraicSensor : public SensorBase\n{\npublic:\n  /// Default constructor\n  AlgebraicSensor();\n\n  /// virtual destructor\n  virtual ~AlgebraicSensor() {}\n\n  /// gets the measurement of the current time. We can choose to consider\n  /// noise or not (default is noisy)\n  virtual Vector getMeasurements(bool noisy = true);\n\n  /// Sets the value of the state at instant k\n  virtual void setState(const Vector & state, TimeIndex k);\n\n  /// gets the current time\n  virtual TimeIndex getTime() const;\n\n  /// gets the state vector size. Pure virtual method.\n  virtual Index getStateSize() const;\n\n  /// get the size of the measurements. Pure virtual method.\n  virtual Index getMeasurementSize() const;\n\n  /// concatenates the n last components of the state in the measurement\n  ///(useful when the measurements are already computed or\n  /// when they come from external source)\n  virtual Index concatenateWithInput(Index n);\n\nprotected:\n  /// the actual algorithm for the computation of the measurements, must\n  /// be overloaded to implement any sensor\n  virtual Vector computeNoiselessMeasurement_() = 0;\n\n  virtual Index getStateSize_() const = 0;\n\n  virtual Index getMeasurementSize_() const = 0;\n\n  Vector computeNoisyMeasurement_();\n\n  virtual void checkState_(const Vector &);\n\n  TimeIndex time_;\n\n  Index concat_;\n\n  Vector state_;\n\n  Vector directInputToOutput_;\n\n  bool storedNoisyMeasurement_;\n\n  Vector noisyMeasurement_;\n\n  bool storedNoiselessMeasurement_;\n\n  Vector noiselessMeasurement_;\n};\n\n} // namespace stateObservation\n\n#endif // SIMULATIONALGEBRAICSENSORHPP\n", "meta": {"hexsha": "6156ae96adb126954f2d192e6b6b30da332ac189", "size": 2486, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/state-observation/sensors-simulation/algebraic-sensor.hpp", "max_stars_repo_name": "mmurooka/state-observation", "max_stars_repo_head_hexsha": "4a6b8eb6fa841cf706a074132fb24b50e8534e35", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2018-11-01T16:10:48.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-09T00:03:46.000Z", "max_issues_repo_path": "include/state-observation/sensors-simulation/algebraic-sensor.hpp", "max_issues_repo_name": "mmurooka/state-observation", "max_issues_repo_head_hexsha": "4a6b8eb6fa841cf706a074132fb24b50e8534e35", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2019-10-18T09:06:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-26T04:22:09.000Z", "max_forks_repo_path": "include/state-observation/sensors-simulation/algebraic-sensor.hpp", "max_forks_repo_name": "mmurooka/state-observation", "max_forks_repo_head_hexsha": "4a6b8eb6fa841cf706a074132fb24b50e8534e35", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2018-06-19T09:00:17.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-11T06:14:51.000Z", "avg_line_length": 25.6288659794, "max_line_length": 83, "alphanum_fraction": 0.7320997586, "num_tokens": 564, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347362, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.4820499544302999}}
{"text": "//==================================================================================================\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\n//! [threshold]\n#include <algorithm>\n#include <cstdint>\n#include <iostream>\n#include <limits>\n#include <vector>\n\n#include <boost/simd/pack.hpp>\n\n#include <boost/simd/function/aligned_store.hpp>\n#include <boost/simd/function/group.hpp>\n#include <boost/simd/function/if_zero_else_one.hpp>\n#include <boost/simd/function/is_less.hpp>\n#include <boost/simd/memory/allocator.hpp>\n\nint main()\n{\n  namespace bs = boost::simd;\n  int image_size = 2560 * 2560;\n  std::vector<std::int16_t, bs::allocator<std::int16_t>> image(image_size);\n  std::vector<std::int16_t, bs::allocator<std::int16_t>> binary(image_size);\n  std::generate(image.begin(), image.end(),\n                []() { return std::rand() % std::numeric_limits<std::int16_t>::max(); });\n  // select arbitrary threshold\n  std::int16_t threshold = 5000;\n  //! [scalar-threshold]\n  for (int i = 0; i < image.size(); ++i) {\n    if (image[i] < threshold) {\n      binary[i] = 0;\n    } else {\n      binary[i] = 1;\n    }\n  }\n  //! [scalar-threshold]\n\n  //! [simd-threshold]\n  using pack_t    = bs::pack<std::int16_t>;\n  using logical_t = bs::pack<bs::logical<std::int16_t>>;\n\n  pack_t v_threshold{threshold};\n  for (int i = 0; i < image.size(); i += pack_t::static_size) {\n    pack_t v_image(&image[i]);\n    logical_t v_res = bs::is_less(v_image, v_threshold);\n    pack_t v_binary = bs::if_zero_else_one(v_res);\n    bs::aligned_store(v_binary, &binary[i]);\n  }\n  //! [simd-threshold]\n}\n// This code can be compiled using (for instance for gcc)\n// g++ thresholding.cpp -msse4.2 -std=c++11 -O3 -DNDEBUG -o thresholding\n// -I/path_to/boost_simd/ -I/path_to/boost/\n\n//! [threshold]\n", "meta": {"hexsha": "a14dcbad6ae78914713404a55426e08f3848f665", "size": 2001, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/examples/thresholding.cpp", "max_stars_repo_name": "nickporubsky/boost-simd-clone", "max_stars_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_stars_repo_licenses": ["BSL-1.0"], "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": "doc/examples/thresholding.cpp", "max_issues_repo_name": "nickporubsky/boost-simd-clone", "max_issues_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "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/thresholding.cpp", "max_forks_repo_name": "nickporubsky/boost-simd-clone", "max_forks_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_forks_repo_licenses": ["BSL-1.0"], "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": 31.7619047619, "max_line_length": 100, "alphanum_fraction": 0.5987006497, "num_tokens": 522, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334527, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.4820499544302999}}
{"text": "\n\n/* --------------------------------------------------------------------- \n * \n * Copyright (C) 2018 - 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: Katharina Kormann, Martin Kronbichler, 2018 \n */ \n\n\n\n// \u5305\u542b\u7684\u6587\u4ef6\u4e0e  step-37  \u4e2d\u7684\u57fa\u672c\u76f8\u540c\uff0c\u53ea\u662f\u7528\u6709\u9650\u5143\u7c7bFE_DGQHermite\u4ee3\u66ff\u4e86FE_Q\u3002\u6240\u6709\u5bf9\u9762\u79ef\u5206\u8fdb\u884c\u65e0\u77e9\u9635\u8ba1\u7b97\u7684\u529f\u80fd\u5df2\u7ecf\u5305\u542b\u5728`fe_evaluation.h`\u4e2d\u3002\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/timer.h> \n\n#include <deal.II/lac/affine_constraints.h> \n#include <deal.II/lac/full_matrix.h> \n#include <deal.II/lac/solver_cg.h> \n#include <deal.II/lac/la_parallel_vector.h> \n#include <deal.II/lac/precondition.h> \n#include <deal.II/lac/tensor_product_matrix.h> \n\n#include <deal.II/fe/fe_dgq.h> \n#include <deal.II/fe/fe_tools.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\n#include <deal.II/multigrid/multigrid.h> \n#include <deal.II/multigrid/mg_transfer_matrix_free.h> \n#include <deal.II/multigrid/mg_tools.h> \n#include <deal.II/multigrid/mg_coarse.h> \n#include <deal.II/multigrid/mg_smoother.h> \n#include <deal.II/multigrid/mg_matrix.h> \n\n#include <deal.II/numerics/vector_tools.h> \n\n#include <deal.II/matrix_free/matrix_free.h> \n#include <deal.II/matrix_free/fe_evaluation.h> \n\n#include <iostream> \n#include <fstream> \n\nnamespace Step59 \n{ \n  using namespace dealii; \n\n// \u548c step-37 \u4e00\u6837\uff0c\u4e3a\u4e86\u7b80\u5355\u8d77\u89c1\uff0c\u6211\u4eec\u5728\u7a0b\u5e8f\u9876\u90e8\u5c06\u7ef4\u6570\u548c\u591a\u9879\u5f0f\u7a0b\u5ea6\u6536\u96c6\u4e3a\u5e38\u6570\u3002\u4e0e step-37 \u4e0d\u540c\u7684\u662f\uff0c\u8fd9\u6b21\u6211\u4eec\u9009\u62e9\u4e86\u4e00\u4e2a\u771f\u6b63\u7684\u9ad8\u9636\u65b9\u6cd5\uff0c\u5ea6\u6570\u4e3a8\uff0c\u4efb\u4f55\u4e0d\u4f7f\u7528\u548c\u56e0\u5f0f\u5206\u89e3\u7684\u5b9e\u73b0\u90fd\u4f1a\u53d8\u5f97\u975e\u5e38\u6162\uff0c\u800c\u4f7f\u7528MatrixFree\u7684\u5b9e\u73b0\u5219\u63d0\u4f9b\u4e86\u4e0e\u5ea6\u6570\u4e3a2\u62163\u65f6\u57fa\u672c\u76f8\u540c\u7684\u6548\u7387\u3002\u6b64\u5916\uff0c\u672c\u6559\u7a0b\u7a0b\u5e8f\u4e2d\u7684\u6240\u6709\u7c7b\u90fd\u662f\u6a21\u677f\u5316\u7684\uff0c\u56e0\u6b64\uff0c\u901a\u8fc7\u5728`main()`\u51fd\u6570\u4e2d\u6dfb\u52a0\u9002\u5f53\u5ea6\u6570\u7684\u5b9e\u4f8b\uff0c\u53ef\u4ee5\u5f88\u5bb9\u6613\u5730\u5728\u8fd0\u884c\u65f6\u4ece\u8f93\u5165\u6587\u4ef6\u6216\u547d\u4ee4\u884c\u53c2\u6570\u4e2d\u9009\u62e9\u5ea6\u6570\u3002\n\n  const unsigned int degree_finite_element = 8; \n  const unsigned int dimension             = 3; \n// @sect3{Equation data}  \n\n// \u4e0e step-7 \u76f8\u7c7b\u4f3c\uff0c\u6211\u4eec\u5b9a\u4e49\u4e86\u4e00\u4e2a\u5206\u6790\u89e3\uff0c\u6211\u4eec\u8bd5\u56fe\u7528\u79bb\u6563\u5316\u91cd\u73b0\u8fd9\u4e2a\u5206\u6790\u89e3\u3002\u7531\u4e8e\u672c\u6559\u7a0b\u7684\u76ee\u7684\u662f\u5c55\u793a\u65e0\u77e9\u9635\u65b9\u6cd5\uff0c\u6211\u4eec\u9009\u62e9\u4e86\u4e00\u4e2a\u6700\u7b80\u5355\u7684\u53ef\u80fd\u6027\uff0c\u5373\u4e00\u4e2a\u4f59\u5f26\u51fd\u6570\uff0c\u5176\u5bfc\u6570\u5bf9\u6211\u4eec\u6765\u8bf4\u8db3\u591f\u7b80\u5355\uff0c\u53ef\u4ee5\u901a\u8fc7\u5206\u6790\u8ba1\u7b97\u3002\u518d\u5f80\u4e0b\u770b\uff0c\u6211\u4eec\u5728\u8fd9\u91cc\u9009\u62e9\u7684\u6ce2\u65702.4\u5c06\u4e0e $x$ -\u65b9\u5411\u7684\u57df\u8303\u56f4\u53732.5\u76f8\u5339\u914d\uff0c\u8fd9\u6837\u6211\u4eec\u5728 $x = 2.5$ \u5f97\u5230\u4e00\u4e2a\u5468\u671f\u6027\u7684\u89e3\uff0c\u5305\u62ec $6pi$ \u6216\u4f59\u5f26\u7684\u4e09\u4e2a\u6574\u6ce2\u8f6c\u3002\u7b2c\u4e00\u4e2a\u51fd\u6570\u5b9a\u4e49\u4e86\u89e3\u548c\u5b83\u7684\u68af\u5ea6\uff0c\u5206\u522b\u7528\u4e8e\u8868\u8fbeDirichlet\u548cNeumann\u8fb9\u754c\u6761\u4ef6\u7684\u89e3\u6790\u89e3\u3002\u6b64\u5916\uff0c\u4e00\u4e2a\u4ee3\u8868\u89e3\u7684\u8d1f\u62c9\u666e\u62c9\u65af\u7684\u7c7b\u88ab\u7528\u6765\u8868\u793a\u53f3\u624b\u8fb9\uff08\u5f3a\u5236\uff09\u51fd\u6570\uff0c\u6211\u4eec\u7528\u5b83\u6765\u5339\u914d\u79bb\u6563\u5316\u7248\u672c\u4e2d\u7684\u7ed9\u5b9a\u5206\u6790\u89e3\uff08\u5236\u9020\u89e3\uff09\u3002\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 = 0) const override final \n    { \n      double val = 1.; \n      for (unsigned int d = 0; d < dim; ++d) \n        val *= std::cos(numbers::PI * 2.4 * p[d]); \n      return val; \n    } \n\n    virtual Tensor<1, dim> gradient(const Point<dim> &p, \n                                    const unsigned int = 0) const override final \n    { \n      const double   arg = numbers::PI * 2.4; \n      Tensor<1, dim> grad; \n      for (unsigned int d = 0; d < dim; ++d) \n        { \n          grad[d] = 1.; \n          for (unsigned int e = 0; e < dim; ++e) \n            if (d == e) \n              grad[d] *= -arg * std::sin(arg * p[e]); \n            else \n              grad[d] *= std::cos(arg * p[e]); \n        } \n      return grad; \n    } \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 = 0) const override final \n    { \n      const double arg = numbers::PI * 2.4; \n      double       val = 1.; \n      for (unsigned int d = 0; d < dim; ++d) \n        val *= std::cos(arg * p[d]); \n      return dim * arg * arg * val; \n    } \n  }; \n\n//  @sect3{Matrix-free implementation}  \n\n// `LaplaceOperator`\u7c7b\u4e0e  step-37  \u4e2d\u7684\u76f8\u5e94\u7c7b\u7c7b\u4f3c\u3002\u4e00\u4e2a\u91cd\u8981\u7684\u533a\u522b\u662f\uff0c\u6211\u4eec\u6ca1\u6709\u4ece  MatrixFreeOperators::Base  \u6d3e\u751f\u51fa\u8fd9\u4e2a\u7c7b\uff0c\u56e0\u4e3a\u6211\u4eec\u60f3\u5448\u73b0  MatrixFree::loop()  \u7684\u4e00\u4e9b\u989d\u5916\u7279\u6027\uff0c\u8fd9\u4e9b\u7279\u6027\u5728\u901a\u7528\u7c7b  MatrixFreeOperators::Base.  \u4e2d\u662f\u4e0d\u53ef\u7528\u7684\u3002\u6211\u4eec\u4eceSubscriptor\u7c7b\u6d3e\u751f\u51fa\u8fd9\u4e2a\u7c7b\uff0c\u4ee5\u4fbf\u80fd\u591f\u5728Chebyshev\u9884\u5904\u7406\u7a0b\u5e8f\u4e2d\u4f7f\u7528\u8be5\u64cd\u4f5c\u7b26\uff0c\u56e0\u4e3a\u8be5\u9884\u5904\u7406\u7a0b\u5e8f\u901a\u8fc7SmartPointer\u5b58\u50a8\u57fa\u7840\u77e9\u9635\u3002\n\n// \u9274\u4e8e\u6211\u4eec\u624b\u5de5\u5b9e\u73b0\u4e86\u4e00\u4e2a\u5b8c\u6574\u7684\u77e9\u9635\u63a5\u53e3\uff0c\u6211\u4eec\u9700\u8981\u6dfb\u52a0\u4e00\u4e2a`initialize()`\u51fd\u6570\uff0c\u4e00\u4e2a`m()`\u51fd\u6570\uff0c\u4e00\u4e2a`vmult()`\u51fd\u6570\u548c\u4e00\u4e2a`Tvmult()`\u51fd\u6570\uff0c\u8fd9\u4e9b\u90fd\u662f\u4e4b\u524d\u7531  MatrixFreeOperators::Base.  \u6211\u4eec\u7684LaplaceOperator\u8fd8\u5305\u542b\u4e00\u4e2a\u6210\u5458\u51fd\u6570`get_penalty_factor()`\uff0c\u6839\u636e  step-39  \u96c6\u4e2d\u9009\u62e9\u5bf9\u79f0\u5185\u90e8\u60e9\u7f5a\u65b9\u6cd5\u4e2d\u7684\u60e9\u7f5a\u53c2\u6570 \u3002\n\n  template <int dim, int fe_degree, typename number> \n  class LaplaceOperator : public Subscriptor \n  { \n  public: \n    using value_type = number; \n\n    LaplaceOperator() = default; \n\n    void initialize(std::shared_ptr<const MatrixFree<dim, number>> data); \n\n    void clear(); \n\n    types::global_dof_index m() const; \n\n    void initialize_dof_vector( \n      LinearAlgebra::distributed::Vector<number> &vec) const; \n\n    std::shared_ptr<const MatrixFree<dim, number>> get_matrix_free() const; \n\n    void vmult(LinearAlgebra::distributed::Vector<number> &      dst, \n               const LinearAlgebra::distributed::Vector<number> &src) const; \n\n    void Tvmult(LinearAlgebra::distributed::Vector<number> &      dst, \n                const LinearAlgebra::distributed::Vector<number> &src) const; \n\n    number get_penalty_factor() const \n    { \n      return 1.0 * fe_degree * (fe_degree + 1); \n    } \n\n  private: \n    void \n    apply_cell(const MatrixFree<dim, number> &                   data, \n               LinearAlgebra::distributed::Vector<number> &      dst, \n               const LinearAlgebra::distributed::Vector<number> &src, \n               const std::pair<unsigned int, unsigned int> &cell_range) const; \n\n    void \n    apply_face(const MatrixFree<dim, number> &                   data, \n               LinearAlgebra::distributed::Vector<number> &      dst, \n               const LinearAlgebra::distributed::Vector<number> &src, \n               const std::pair<unsigned int, unsigned int> &face_range) const; \n\n    void apply_boundary( \n      const MatrixFree<dim, number> &                   data, \n      LinearAlgebra::distributed::Vector<number> &      dst, \n      const LinearAlgebra::distributed::Vector<number> &src, \n      const std::pair<unsigned int, unsigned int> &     face_range) const; \n\n    std::shared_ptr<const MatrixFree<dim, number>> data; \n  }; \n\n// `%PreconditionBlockJacobi`\u7c7b\u5b9a\u4e49\u4e86\u6211\u4eec\u5bf9\u8fd9\u4e2a\u95ee\u9898\u7684\u81ea\u5b9a\u4e49\u9884\u5904\u7406\u7a0b\u5e8f\u3002\u4e0e\u57fa\u4e8e\u77e9\u9635\u5bf9\u89d2\u7ebf\u7684 step-37 \u4e0d\u540c\uff0c\u6211\u4eec\u5728\u8fd9\u91cc\u901a\u8fc7\u4f7f\u7528\u4ecb\u7ecd\u4e2d\u8ba8\u8bba\u7684\u6240\u8c13\u5feb\u901f\u5bf9\u89d2\u7ebf\u5316\u65b9\u6cd5\u6765\u8ba1\u7b97\u975e\u8fde\u7eedGalerkin\u65b9\u6cd5\u4e2d\u5bf9\u89d2\u7ebf\u5757\u7684\u8fd1\u4f3c\u53cd\u6f14\u3002\n\n  template <int dim, int fe_degree, typename number> \n  class PreconditionBlockJacobi \n  { \n  public: \n    using value_type = number; \n\n    void clear() \n    { \n      cell_matrices.clear(); \n    } \n\n    void initialize(const LaplaceOperator<dim, fe_degree, number> &op); \n\n    void vmult(LinearAlgebra::distributed::Vector<number> &      dst, \n               const LinearAlgebra::distributed::Vector<number> &src) const; \n\n    void Tvmult(LinearAlgebra::distributed::Vector<number> &      dst, \n                const LinearAlgebra::distributed::Vector<number> &src) const \n    { \n      vmult(dst, src); \n    } \n\n  private: \n    std::shared_ptr<const MatrixFree<dim, number>> data; \n    std::vector<TensorProductMatrixSymmetricSum<dim, \n                                                VectorizedArray<number>, \n                                                fe_degree + 1>> \n      cell_matrices; \n  }; \n\n//\u8fd9\u4e2a\u72ec\u7acb\u7684\u51fd\u6570\u5728`LaplaceOperator'\u548c`%PreconditionBlockJacobi'\u7c7b\u4e2d\u90fd\u88ab\u7528\u6765\u8c03\u6574\u9b3c\u9b42\u8303\u56f4\u3002\u8fd9\u4e2a\u51fd\u6570\u662f\u5fc5\u8981\u7684\uff0c\u56e0\u4e3a`vmult()`\u51fd\u6570\u6240\u63d0\u4f9b\u7684\u4e00\u4e9b\u5411\u91cf\u6ca1\u6709\u7528\u5305\u62ec\u6b63\u786e\u7684\u9b3c\u9b42\u6761\u76ee\u5e03\u5c40\u7684 `LaplaceOperator::initialize_dof_vector` \u6765\u6b63\u786e\u521d\u59cb\u5316\uff0c\u800c\u662f\u6765\u81eaMGTransferMatrixFree\u7c7b\uff0c\u8be5\u7c7b\u5bf9\u65e0\u77e9\u9635\u7c7b\u7684\u9b3c\u9b42\u9009\u62e9\u6ca1\u6709\u6982\u5ff5\u3002\u4e3a\u4e86\u907f\u514d\u7d22\u5f15\u6df7\u4e71\uff0c\u6211\u4eec\u5fc5\u987b\u5728\u5bf9\u8fd9\u4e9b\u5411\u91cf\u8fdb\u884c\u5b9e\u9645\u64cd\u4f5c\u4e4b\u524d\u8c03\u6574\u9b3c\u57df\u3002\u7531\u4e8e\u5411\u91cf\u5728\u591a\u7f51\u683c\u5e73\u6ed1\u5668\u548c\u4f20\u8f93\u7c7b\u4e2d\u88ab\u4fdd\u7559\u4e0b\u6765\uff0c\u4e00\u4e2a\u66fe\u7ecf\u88ab\u8c03\u6574\u8fc7\u91cd\u5f71\u8303\u56f4\u7684\u5411\u91cf\u5728\u5bf9\u8c61\u7684\u6574\u4e2a\u751f\u547d\u5468\u671f\u4e2d\u90fd\u4f1a\u4fdd\u6301\u8fd9\u79cd\u72b6\u6001\uff0c\u6240\u4ee5\u6211\u4eec\u53ef\u4ee5\u5728\u51fd\u6570\u7684\u5f00\u59cb\u4f7f\u7528\u4e00\u4e2a\u5feb\u6377\u65b9\u5f0f\u6765\u67e5\u770b\u5206\u5e03\u5f0f\u5411\u91cf\u7684\u5206\u533a\u5668\u5bf9\u8c61\uff08\u4ee5\u5171\u4eab\u6307\u9488\u7684\u5f62\u5f0f\u5b58\u50a8\uff09\u662f\u5426\u4e0eMatrixFree\u6240\u671f\u671b\u7684\u5e03\u5c40\u76f8\u540c\uff0c\u5b83\u88ab\u5b58\u50a8\u5728\u4e00\u4e2a\u7531 MatrixFree::get_dof_info(0),  \u8bbf\u95ee\u7684\u6570\u636e\u7ed3\u6784\u4e2d ]\uff0c\u5176\u4e2d\u76840\u8868\u793a\u4ece\u4e2d\u63d0\u53d6\u7684DoFHandler\u7f16\u53f7\uff1b\u6211\u4eec\u5728MatrixFree\u4e2d\u53ea\u4f7f\u7528\u4e00\u4e2aDoFHandler\uff0c\u6240\u4ee5\u8fd9\u91cc\u552f\u4e00\u6709\u6548\u7684\u7f16\u53f7\u662f0\u3002\n\n  template <int dim, typename number> \n  void adjust_ghost_range_if_necessary( \n    const MatrixFree<dim, number> &                   data, \n    const LinearAlgebra::distributed::Vector<number> &vec) \n  { \n    if (vec.get_partitioner().get() == \n        data.get_dof_info(0).vector_partitioner.get()) \n      return; \n\n    LinearAlgebra::distributed::Vector<number> copy_vec(vec); \n    const_cast<LinearAlgebra::distributed::Vector<number> &>(vec).reinit( \n      data.get_dof_info(0).vector_partitioner); \n    const_cast<LinearAlgebra::distributed::Vector<number> &>(vec) \n      .copy_locally_owned_data_from(copy_vec); \n  } \n\n// \u63a5\u4e0b\u6765\u7684\u4e94\u4e2a\u51fd\u6570\u7528\u4e8e\u6e05\u9664\u548c\u521d\u59cb\u5316`LaplaceOperator`\u7c7b\uff0c\u8fd4\u56de\u6301\u6709MatrixFree\u6570\u636e\u5bb9\u5668\u7684\u5171\u4eab\u6307\u9488\uff0c\u4ee5\u53ca\u6b63\u786e\u521d\u59cb\u5316\u5411\u91cf\u548c\u8fd0\u7b97\u7b26\u5927\u5c0f\uff0c\u4e0e step-37 \u6216\u8005\u8bf4 MatrixFreeOperators::Base. \u7684\u5185\u5bb9\u76f8\u540c\u3002\n  template <int dim, int fe_degree, typename number> \n  void LaplaceOperator<dim, fe_degree, number>::clear() \n  { \n    data.reset(); \n  } \n\n  template <int dim, int fe_degree, typename number> \n  void LaplaceOperator<dim, fe_degree, number>::initialize( \n    std::shared_ptr<const MatrixFree<dim, number>> data) \n  { \n    this->data = data; \n  } \n\n  template <int dim, int fe_degree, typename number> \n  std::shared_ptr<const MatrixFree<dim, number>> \n  LaplaceOperator<dim, fe_degree, number>::get_matrix_free() const \n  { \n    return data; \n  } \n\n  template <int dim, int fe_degree, typename number> \n  void LaplaceOperator<dim, fe_degree, number>::initialize_dof_vector( \n    LinearAlgebra::distributed::Vector<number> &vec) const \n  { \n    data->initialize_dof_vector(vec); \n  } \n\n  template <int dim, int fe_degree, typename number> \n  types::global_dof_index LaplaceOperator<dim, fe_degree, number>::m() const \n  { \n    Assert(data.get() != nullptr, ExcNotInitialized()); \n    return data->get_dof_handler().n_dofs(); \n  } \n\n// \u8fd9\u4e2a\u51fd\u6570\u5728\u5411\u91cf`src`\u4e0a\u5b9e\u73b0\u4e86LaplaceOperator\u7684\u52a8\u4f5c\uff0c\u5e76\u5c06\u7ed3\u679c\u5b58\u50a8\u5728\u5411\u91cf`dst`\u4e2d\u3002\u4e0e step-37 \u76f8\u6bd4\uff0c\u8fd9\u4e2a\u8c03\u7528\u6709\u56db\u4e2a\u65b0\u7279\u6027\u3002\n\n// \u7b2c\u4e00\u4e2a\u65b0\u7279\u6027\u662f\u4e0a\u9762\u63d0\u5230\u7684`adjust_ghost_range_if_necessary`\u51fd\u6570\uff0c\u8be5\u51fd\u6570\u9700\u8981\u4f7f\u5411\u91cf\u7b26\u5408\u5355\u5143\u548c\u9762\u51fd\u6570\u4e2dFEEvaluation\u548cFEFaceEvaluation\u6240\u671f\u671b\u7684\u5e03\u5c40\u3002\n\n// \u7b2c\u4e8c\u4e2a\u65b0\u7279\u5f81\u662f\u6211\u4eec\u6ca1\u6709\u50cf step-37 \u4e2d\u90a3\u6837\u5b9e\u73b0`vmult_add()`\u51fd\u6570\uff08\u901a\u8fc7\u865a\u62df\u51fd\u6570 MatrixFreeOperators::Base::vmult_add()), \uff0c\u800c\u662f\u76f4\u63a5\u5b9e\u73b0`vmult()`\u529f\u80fd\u3002\u7531\u4e8e\u5355\u5143\u548c\u9762\u7684\u79ef\u5206\u90fd\u5c06\u548c\u5230\u76ee\u7684\u5411\u91cf\u4e2d\uff0c\u6211\u4eec\u5f53\u7136\u5fc5\u987b\u5728\u67d0\u5904\u5c06\u5411\u91cf\u5f52\u96f6\u3002\u5bf9\u4e8eDG\u5143\u7d20\uff0c\u6211\u4eec\u6709\u4e24\u4e2a\u9009\u62e9&ndash\uff1b\u4e00\u4e2a\u662f\u4f7f\u7528 FEEvaluation::set_dof_values() \u800c\u4e0d\u662f\u4e0b\u9762`apply_cell`\u51fd\u6570\u4e2d\u7684 FEEvaluation::distribute_local_to_global() \u3002\u8fd9\u662f\u56e0\u4e3aMatrixFree\u4e2d\u7684\u5faa\u73af\u5e03\u5c40\u662f\u8fd9\u6837\u7684\uff1a\u5355\u5143\u79ef\u5206\u603b\u662f\u5728\u9762\u79ef\u5206\u4e4b\u524d\u63a5\u89e6\u5230\u4e00\u4e2a\u7ed9\u5b9a\u7684\u5411\u91cf\u6761\u76ee\u3002\u7136\u800c\uff0c\u8fd9\u5b9e\u9645\u4e0a\u53ea\u9002\u7528\u4e8e\u5b8c\u5168\u4e0d\u8fde\u7eed\u7684\u57fa\u6570\uff0c\u5176\u4e2d\u6bcf\u4e2a\u5355\u5143\u90fd\u6709\u81ea\u5df1\u7684\u81ea\u7531\u5ea6\uff0c\u4e0d\u4e0e\u90bb\u8fd1\u7684\u7ed3\u679c\u5171\u4eab\u3002\u53e6\u4e00\u79cd\u8bbe\u7f6e\uff0c\u5373\u8fd9\u91cc\u9009\u62e9\u7684\u8bbe\u7f6e\uff0c\u662f\u8ba9 MatrixFree::loop() \u6765\u5904\u7406\u5411\u91cf\u7684\u5f52\u96f6\u95ee\u9898\u3002\u8fd9\u53ef\u4ee5\u88ab\u8ba4\u4e3a\u662f\u5728\u4ee3\u7801\u7684\u67d0\u4e2a\u5730\u65b9\u7b80\u5355\u5730\u8c03\u7528`dst = 0;`\u3002\u5bf9\u4e8e\u50cf `LinearAlgebra::distributed::Vector`, \u8fd9\u6837\u7684\u652f\u6301\u6027\u5411\u91cf\u6765\u8bf4\uff0c\u5b9e\u73b0\u8d77\u6765\u5c31\u6bd4\u8f83\u9ebb\u70e6\u4e86\uff0c\u56e0\u4e3a\u6211\u4eec\u7684\u76ee\u6807\u662f\u4e0d\u8981\u4e00\u6b21\u6027\u5c06\u6574\u4e2a\u5411\u91cf\u6e05\u96f6\u3002\u5728\u8db3\u591f\u5c0f\u7684\u51e0\u5343\u4e2a\u5411\u91cf\u9879\u4e0a\u8fdb\u884c\u5f52\u96f6\u64cd\u4f5c\u7684\u597d\u5904\u662f\uff0c\u5728 FEEvaluation::distribute_local_to_global() \u548c FEFaceEvaluation::distribute_local_to_global(). \u4e2d\u518d\u6b21\u8bbf\u95ee\u4e4b\u524d\uff0c\u88ab\u5f52\u96f6\u7684\u5411\u91cf\u9879\u4f1a\u4fdd\u7559\u5728\u7f13\u5b58\u4e2d\uff0c\u56e0\u4e3a\u65e0\u77e9\u9635\u8fd0\u7b97\u7b26\u7684\u8bc4\u4f30\u771f\u7684\u5f88\u5feb\uff0c\u4ec5\u4ec5\u5f52\u96f6\u4e00\u4e2a\u5927\u7684\u5411\u91cf\u5c31\u4f1a\u76f8\u5f53\u4e8e\u8fd0\u7b97\u7b26\u8bc4\u4f30\u65f6\u95f4\u768425%\uff0c\u6211\u4eec\u663e\u7136\u5e0c\u671b\u907f\u514d\u8fd9\u79cd\u4ee3\u4ef7\u3002\u5bf9\u4e8e MatrixFree::cell_loop \u548c\u8fde\u7eed\u57fa\u6570\u6765\u8bf4\uff0c\u4e5f\u53ef\u4ee5\u4f7f\u7528\u8fd9\u79cd\u5c06\u5411\u91cf\u5f52\u96f6\u7684\u9009\u9879\uff0c\u5c3d\u7ba1\u5728 step-37 \u6216 step-48 \u7684\u6559\u7a0b\u7a0b\u5e8f\u4e2d\u6ca1\u6709\u4f7f\u7528\u5b83\u3002\n\n// \u7b2c\u4e09\u4e2a\u65b0\u7279\u5f81\u662f\u6211\u4eec\u63d0\u4f9b\u4e86\u5728\u5355\u5143\u683c\u3001\u5185\u9762\u548c\u8fb9\u754c\u9762\u8fdb\u884c\u8ba1\u7b97\u7684\u51fd\u6570\u65b9\u5f0f\u3002MatrixFree\u7c7b\u6709\u4e00\u4e2a\u53eb\u505a`loop`\u7684\u51fd\u6570\uff0c\u5b83\u63a5\u6536\u4e09\u4e2a\u51fd\u6570\u6307\u9488\uff0c\u7528\u4e8e\u4e09\u79cd\u60c5\u51b5\uff0c\u5141\u8bb8\u5206\u5f00\u5b9e\u73b0\u4e0d\u540c\u7684\u4e1c\u897f\u3002\u6b63\u5982\u5728 step-37 \u4e2d\u6240\u89e3\u91ca\u7684\uff0c\u8fd9\u4e9b\u51fd\u6570\u6307\u9488\u53ef\u4ee5\u662f `std::function` \u5bf9\u8c61\u6216\u7c7b\u7684\u6210\u5458\u51fd\u6570\u3002\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0c\u6211\u4eec\u4f7f\u7528\u6307\u5411\u6210\u5458\u51fd\u6570\u7684\u6307\u9488\u3002\n\n// \u6700\u540e\u7684\u65b0\u7279\u5f81\u662f\u53ef\u4ee5\u7ed9 MatrixFree::DataAccessOnFaces \u7c7b\u578b\u7684\u6700\u540e\u4e24\u4e2a\u53c2\u6570\uff0c\u8fd9\u4e2a\u7c7b\u5c06\u9762\u79ef\u5206\u7684\u6570\u636e\u8bbf\u95ee\u7c7b\u578b\u4f20\u9012\u7ed9\u5e76\u884c\u5411\u91cf\u7684MPI\u6570\u636e\u4ea4\u6362\u4f8b\u7a0b LinearAlgebra::distributed::Vector::update_ghost_values() \u548c LinearAlgebra::distributed::Vector::compress() \u3002\u5176\u76ee\u7684\u662f\u4e0d\u53d1\u9001\u76f8\u90bb\u5143\u7d20\u7684\u6240\u6709\u81ea\u7531\u5ea6\uff0c\u800c\u662f\u5c06\u6570\u636e\u91cf\u51cf\u5c11\u5230\u624b\u5934\u8ba1\u7b97\u771f\u6b63\u9700\u8981\u7684\u7a0b\u5ea6\u3002\u6570\u636e\u4ea4\u6362\u662f\u4e00\u4e2a\u771f\u6b63\u7684\u74f6\u9888\uff0c\u7279\u522b\u662f\u5bf9\u4e8e\u9ad8\u81ea\u7531\u5ea6\u7684DG\u65b9\u6cd5\u6765\u8bf4\uff0c\u56e0\u6b64\u4e00\u4e2a\u66f4\u4e25\u683c\u7684\u4ea4\u6362\u65b9\u5f0f\u5f80\u5f80\u662f\u6709\u76ca\u7684\u3002\u679a\u4e3e\u5b57\u6bb5 MatrixFree::DataAccessOnFaces \u53ef\u4ee5\u53d6\u503c`none`\uff0c\u8fd9\u610f\u5473\u7740\u6839\u672c\u4e0d\u505a\u9762\u7684\u79ef\u5206\uff0c\u8fd9\u7c7b\u4f3c\u4e8e MatrixFree::cell_loop(), \u7684\u503c`values`\uff0c\u610f\u5473\u7740\u53ea\u4f7f\u7528\u9762\u7684\u5f62\u72b6\u51fd\u6570\u503c\uff08\u4f46\u4e0d\u4f7f\u7528\u5bfc\u6570\uff09\uff0c\u800c\u503c`gradients`\u65f6\uff0c\u9664\u4e86\u503c\u4e4b\u5916\u8fd8\u8bbf\u95ee\u9762\u7684\u7b2c\u4e00\u5bfc\u6570\u3002\u503c`unspecified`\u610f\u5473\u7740\u6240\u6709\u7684\u81ea\u7531\u5ea6\u5c06\u88ab\u4ea4\u6362\u7ed9\u4f4d\u4e8e\u5904\u7406\u5668\u8fb9\u754c\u7684\u9762\uff0c\u5e76\u6307\u5b9a\u5728\u672c\u5730\u5904\u7406\u5668\u4e0a\u8fdb\u884c\u5904\u7406\u3002\n\n// \u4e3a\u4e86\u4e86\u89e3\u6570\u636e\u662f\u5982\u4f55\u88ab\u51cf\u5c11\u7684\uff0c\u60f3\u60f3\u8282\u70b9\u5143\u7d20FE_DGQ\u7684\u60c5\u51b5\uff0c\u8282\u70b9\u70b9\u5728\u5143\u7d20\u8868\u9762\uff0c\u5728\u4e00\u4e2a\u5355\u5143\u7684 $(k+1)^d$ \u4e2a\u81ea\u7531\u5ea6\u4e2d\uff0c\u53ea\u6709 $(k+1)^{d-1}$ \u4e2a\u81ea\u7531\u5ea6\u5bf9 $d$ \u4e2a\u7a7a\u95f4\u7ef4\u5ea6\u7684\u591a\u9879\u5f0f\u7a0b\u5ea6\u7684\u9762\u7684\u503c\u6709\u8d21\u732e\u3002\u7c7b\u4f3c\u7684\u51cf\u5c11\u4e5f\u53ef\u4ee5\u7528\u4e8e\u5185\u90e8\u60e9\u7f5a\u65b9\u6cd5\uff0c\u8be5\u65b9\u6cd5\u8bc4\u4f30\u9762\u7684\u503c\u548c\u4e00\u5bfc\u6570\u3002\u5f53\u5728\u4e00\u7ef4\u4e2d\u4f7f\u7528\u7c7bHermite\u57fa\u65f6\uff0c\u6700\u591a\u53ea\u6709\u4e24\u4e2a\u57fa\u51fd\u6570\u5bf9\u6570\u503c\u548c\u5bfc\u6570\u6709\u8d21\u732e\u3002FE_DGQHermite\u7c7b\u5b9e\u73b0\u4e86\u8fd9\u4e00\u6982\u5ff5\u7684\u5f20\u91cf\u4e58\u79ef\uff0c\u5728\u4ecb\u7ecd\u4e2d\u5df2\u7ecf\u8ba8\u8bba\u8fc7\u3002\u56e0\u6b64\uff0c\u6bcf\u4e2a\u9762\u53ea\u9700\u4ea4\u6362 $2(k+1)^{d-1}$ \u4e2a\u81ea\u7531\u5ea6\uff0c\u4e00\u65e6 $k$ \u4e2a\u81ea\u7531\u5ea6\u5927\u4e8e4\u62165\u4e2a\uff0c\u8fd9\u663e\u7136\u662f\u4e00\u79cd\u80dc\u5229\u3002\u8bf7\u6ce8\u610f\uff0cFE_DGQHermite\u7684\u8fd9\u79cd\u51cf\u5c11\u7684\u4ea4\u6362\u5728\u5177\u6709\u5f2f\u66f2\u8fb9\u754c\u7684\u7f51\u683c\u4e0a\u4e5f\u662f\u6709\u6548\u7684\uff0c\u56e0\u4e3a\u5bfc\u6570\u662f\u5728\u53c2\u8003\u5143\u7d20\u4e0a\u53d6\u7684\uff0c\u800c\u51e0\u4f55\u4f53\u53ea\u5728\u5185\u90e8\u6df7\u5408\u5b83\u4eec\u3002\u56e0\u6b64\uff0c\u8fd9\u4e0e\u8bd5\u56fe\u7528\u8fde\u7eed\u7684Hermite\u578b\u5f62\u72b6\u51fd\u6570\u83b7\u5f97 $C^1$ \u7684\u8fde\u7eed\u6027\u4e0d\u540c\uff0c\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0c\u975e\u7b1b\u5361\u5c14\u7684\u60c5\u51b5\u4f1a\u5927\u5927\u6539\u53d8\u60c5\u51b5\u3002\u663e\u7136\uff0c\u5728\u975e\u7b1b\u5361\u5c14\u7f51\u683c\u4e0a\uff0c\u5bfc\u6570\u8fd8\u5305\u62ec\u8d85\u51fa\u6cd5\u5411\u5bfc\u6570\u7684\u5f62\u72b6\u51fd\u6570\u7684\u5207\u5411\u5bfc\u6570\uff0c\u4f46\u8fd9\u4e9b\u4e5f\u53ea\u9700\u8981\u5143\u7d20\u8868\u9762\u7684\u51fd\u6570\u503c\u3002\u5982\u679c\u5143\u7d20\u4e0d\u63d0\u4f9b\u4efb\u4f55\u538b\u7f29\uff0c\u5faa\u73af\u4f1a\u81ea\u52a8\u4ea4\u6362\u53d7\u5f71\u54cd\u5355\u5143\u7684\u6240\u6709\u6761\u76ee\u3002\n\n  template <int dim, int fe_degree, typename number> \n  void LaplaceOperator<dim, fe_degree, number>::vmult( \n    LinearAlgebra::distributed::Vector<number> &      dst, \n    const LinearAlgebra::distributed::Vector<number> &src) const \n  { \n    adjust_ghost_range_if_necessary(*data, dst); \n    adjust_ghost_range_if_necessary(*data, src); \n    data->loop(&LaplaceOperator::apply_cell, \n               &LaplaceOperator::apply_face, \n               &LaplaceOperator::apply_boundary, \n               this, \n               dst, \n               src, \n               /* zero_dst =  */ true,\n               MatrixFree<dim, number>::DataAccessOnFaces::gradients,\n               MatrixFree<dim, number>::DataAccessOnFaces::gradients);\n  } \n\n// \u7531\u4e8e\u62c9\u666e\u62c9\u65af\u662f\u5bf9\u79f0\u7684\uff0c`Tvmult()`\uff08\u591a\u7f51\u683c\u5e73\u6ed1\u754c\u9762\u9700\u8981\uff09\u64cd\u4f5c\u88ab\u7b80\u5355\u5730\u8f6c\u53d1\u7ed9`vmult()`\u7684\u60c5\u51b5\u3002\n\n  template <int dim, int fe_degree, typename number> \n  void LaplaceOperator<dim, fe_degree, number>::Tvmult( \n    LinearAlgebra::distributed::Vector<number> &      dst, \n    const LinearAlgebra::distributed::Vector<number> &src) const \n  { \n    vmult(dst, src); \n  } \n\n//\u5355\u5143\u683c\u7684\u64cd\u4f5c\u4e0e step-37 \u975e\u5e38\u76f8\u4f3c\u3002\u4e0d\u8fc7\u6211\u4eec\u5728\u8fd9\u91cc\u6ca1\u6709\u4f7f\u7528\u7cfb\u6570\u3002\u7b2c\u4e8c\u4e2a\u533a\u522b\u662f\uff0c\u6211\u4eec\u7528\u4e00\u4e2a\u5355\u4e00\u7684\u51fd\u6570\u8c03\u7528 FEEvaluation::gather_evaluate() \u4ee3\u66ff\u4e86 FEEvaluation::read_dof_values() \u540e\u9762\u7684 FEEvaluation::evaluate() \u8fd9\u4e24\u4e2a\u6b65\u9aa4\uff0c\u5728\u5185\u90e8\u8c03\u7528\u8fd9\u4e24\u4e2a\u5355\u72ec\u65b9\u6cd5\u7684\u5e8f\u5217\u3002\u540c\u6837\uff0c FEEvaluation::integrate_scatter() \u5b9e\u73b0\u4e86 FEEvaluation::integrate() \u4e4b\u540e\u7684 FEEvaluation::distribute_local_to_global(). \u7684\u5e8f\u5217\u3002 \u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0c\u8fd9\u4e9b\u65b0\u51fd\u6570\u53ea\u662f\u8282\u7701\u4e86\u4e24\u884c\u4ee3\u7801\u3002\u7136\u800c\uff0c\u6211\u4eec\u7528\u5b83\u4eec\u6765\u4e0eFEFaceEvaluation\u8fdb\u884c\u7c7b\u6bd4\uff0c\u5728\u90a3\u91cc\u5b83\u4eec\u66f4\u91cd\u8981\uff0c\u5982\u4e0b\u6240\u8ff0\u3002\n\n  template <int dim, int fe_degree, typename number> \n  void LaplaceOperator<dim, fe_degree, number>::apply_cell( \n    const MatrixFree<dim, number> &                   data, \n    LinearAlgebra::distributed::Vector<number> &      dst, \n    const LinearAlgebra::distributed::Vector<number> &src, \n    const std::pair<unsigned int, unsigned int> &     cell_range) const \n  { \n    FEEvaluation<dim, fe_degree, fe_degree + 1, 1, number> phi(data); \n    for (unsigned int cell = cell_range.first; cell < cell_range.second; ++cell) \n      { \n        phi.reinit(cell); \n        phi.gather_evaluate(src, EvaluationFlags::gradients); \n        for (unsigned int q = 0; q < phi.n_q_points; ++q) \n          phi.submit_gradient(phi.get_gradient(q), q); \n        phi.integrate_scatter(EvaluationFlags::gradients, dst); \n      } \n  } \n\n// \u9762\u90e8\u64cd\u4f5c\u5b9e\u73b0\u4e86\u4e0e step-39 \u7c7b\u4f3c\u7684\u5185\u90e8\u60e9\u7f5a\u65b9\u6cd5\u7684\u6761\u6b3e\uff0c\u6b63\u5982\u4ecb\u7ecd\u4e2d\u6240\u89e3\u91ca\u7684\u3002\u6211\u4eec\u9700\u8981\u4e24\u4e2a\u8bc4\u4f30\u5668\u5bf9\u8c61\u6765\u5b8c\u6210\u8fd9\u4e2a\u4efb\u52a1\uff0c\u4e00\u4e2a\u7528\u4e8e\u5904\u7406\u6765\u81ea\u5185\u90e8\u9762\u7684\u4e24\u8fb9\u4e4b\u4e00\u7684\u5355\u5143\u683c\u7684\u89e3\uff0c\u53e6\u4e00\u4e2a\u7528\u4e8e\u5904\u7406\u6765\u81ea\u53e6\u4e00\u8fb9\u7684\u89e3\u3002\u9762\u79ef\u5206\u7684\u8bc4\u4ef7\u5668\u88ab\u79f0\u4e3aFEFaceEvaluation\uff0c\u5e76\u5728\u6784\u9020\u51fd\u6570\u7684\u7b2c\u4e8c\u4e2a\u69fd\u4e2d\u63a5\u53d7\u4e00\u4e2a\u5e03\u5c14\u53c2\u6570\uff0c\u4ee5\u6307\u793a\u8bc4\u4ef7\u5668\u5e94\u5c5e\u4e8e\u4e24\u8fb9\u4e2d\u7684\u54ea\u4e00\u8fb9\u3002\u5728FEFaceEvaluation\u548cMatrixFree\u4e2d\uff0c\u6211\u4eec\u79f0\u4e24\u8fb9\u4e2d\u7684\u4e00\u8fb9\u4e3a \"\u5185\u90e8\"\uff0c\u53e6\u4e00\u8fb9\u4e3a \"\u5916\u90e8\"\u3002`\u5916\u90e8'\u8fd9\u4e2a\u540d\u5b57\u662f\u6307\u4e24\u8fb9\u7684\u8bc4\u4ef7\u5668\u5c06\u8fd4\u56de\u76f8\u540c\u7684\u6cd5\u5411\u91cf\u3002\u5bf9\u4e8e \"\u5185\u90e8 \"\u4e00\u4fa7\uff0c\u6cd5\u5411\u91cf\u6307\u5411\u5916\u90e8\uff0c\u800c\u53e6\u4e00\u4fa7\u5219\u6307\u5411\u5185\u90e8\uff0c\u5e76\u4e14\u4e0e\u8be5\u5355\u5143\u7684\u5916\u90e8\u6cd5\u5411\u91cf\u76f8\u5bf9\u5e94\u3002\u9664\u4e86\u65b0\u7684\u7c7b\u540d\u4e4b\u5916\uff0c\u6211\u4eec\u518d\u6b21\u5f97\u5230\u4e86\u4e00\u7cfb\u5217\u7684\u9879\u76ee\uff0c\u4e0e step-37 \u4e2d\u8ba8\u8bba\u7684\u7c7b\u4f3c\uff0c\u4f46\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\u662f\u9488\u5bf9\u5185\u90e8\u9762\u7684\u3002\u8bf7\u6ce8\u610f\uff0cMatrixFree\u7684\u6570\u636e\u7ed3\u6784\u5f62\u6210\u4e86\u9762\u7684\u6279\u6b21\uff0c\u7c7b\u4f3c\u4e8e\u5355\u5143\u79ef\u5206\u7684\u5355\u5143\u6279\u6b21\u3002\u4e00\u6279\u4e2d\u7684\u6240\u6709\u9762\u6d89\u53ca\u4e0d\u540c\u7684\u5355\u5143\u683c\u7f16\u53f7\uff0c\u4f46\u5728\u53c2\u8003\u5355\u5143\u683c\u4e2d\u5177\u6709\u76f8\u540c\u7684\u9762\u7f16\u53f7\uff0c\u5177\u6709\u76f8\u540c\u7684\u7ec6\u5316\u914d\u7f6e\uff08\u65e0\u7ec6\u5316\u6216\u76f8\u540c\u7684\u5b50\u9762\uff09\u548c\u76f8\u540c\u7684\u65b9\u5411\uff0c\u4ee5\u4fdd\u6301SIMD\u64cd\u4f5c\u7684\u7b80\u5355\u548c\u9ad8\u6548\u3002\n\n// \u6ce8\u610f\uff0c\u9664\u4e86\u6cd5\u7ebf\u65b9\u5411\u7684\u903b\u8f91\u51b3\u5b9a\u5916\uff0c\u5185\u90e8\u4e0e\u5916\u90e8\u6ca1\u6709\u4efb\u4f55\u9690\u542b\u7684\u610f\u4e49\uff0c\u8fd9\u5728\u5185\u90e8\u662f\u76f8\u5f53\u968f\u673a\u7684\u3002\u6211\u4eec\u7edd\u5bf9\u4e0d\u80fd\u4f9d\u8d56\u5206\u914d\u5185\u90e8\u4e0e\u5916\u90e8\u6807\u5fd7\u7684\u67d0\u79cd\u6a21\u5f0f\uff0c\u56e0\u4e3a\u8fd9\u4e2a\u51b3\u5b9a\u662f\u4e3a\u4e86MatrixFree\u8bbe\u7f6e\u4f8b\u7a0b\u4e2d\u7684\u8bbf\u95ee\u89c4\u5219\u6027\u548c\u7edf\u4e00\u6027\u800c\u505a\u51fa\u7684\u3002\u7531\u4e8e\u5927\u591a\u6570\u6b63\u5e38\u7684DG\u65b9\u6cd5\u90fd\u662f\u4fdd\u5b88\u7684\uff0c\u4e5f\u5c31\u662f\u8bf4\uff0c\u901a\u91cf\u5728\u63a5\u53e3\u7684\u4e24\u8fb9\u770b\u8d77\u6765\u90fd\u662f\u4e00\u6837\u7684\uff0c\u6240\u4ee5\u5982\u679c\u5185\u90e8/\u5916\u90e8\u6807\u5fd7\u88ab\u8c03\u6362\uff0c\u6cd5\u7ebf\u5411\u91cf\u5f97\u5230\u76f8\u53cd\u7684\u7b26\u53f7\uff0c\u90a3\u4e48\u6570\u5b66\u5c31\u4e0d\u4f1a\u6709\u4efb\u4f55\u6539\u53d8\u3002\n\n  template <int dim, int fe_degree, typename number> \n  void LaplaceOperator<dim, fe_degree, number>::apply_face( \n    const MatrixFree<dim, number> &                   data, \n    LinearAlgebra::distributed::Vector<number> &      dst, \n    const LinearAlgebra::distributed::Vector<number> &src, \n    const std::pair<unsigned int, unsigned int> &     face_range) const \n  { \n    FEFaceEvaluation<dim, fe_degree, fe_degree + 1, 1, number> phi_inner(data, \n                                                                         true); \n    FEFaceEvaluation<dim, fe_degree, fe_degree + 1, 1, number> phi_outer(data, \n                                                                         false); \n    for (unsigned int face = face_range.first; face < face_range.second; ++face) \n      { \n\n// \u5728\u7ed9\u5b9a\u7684\u4e00\u6279\u9762\u5b54\u4e0a\uff0c\u6211\u4eec\u9996\u5148\u66f4\u65b0\u6307\u5411\u5f53\u524d\u9762\u5b54\u7684\u6307\u9488\uff0c\u7136\u540e\u8bbf\u95ee\u77e2\u91cf\u3002\u5982\u4e0a\u6240\u8ff0\uff0c\u6211\u4eec\u628a\u8bbf\u95ee\u5411\u91cf\u548c\u8bc4\u4f30\u7ed3\u5408\u8d77\u6765\u3002\u5728\u9762\u79ef\u5206\u7684\u60c5\u51b5\u4e0b\uff0c\u5bf9\u4e8eFE_DGQHermite\u57fa\u7840\u7684\u7279\u6b8a\u60c5\u51b5\uff0c\u53ef\u4ee5\u51cf\u5c11\u5bf9\u5411\u91cf\u7684\u6570\u636e\u8bbf\u95ee\uff0c\u6b63\u5982\u4e0a\u9762\u89e3\u91ca\u7684\u6570\u636e\u4ea4\u6362\u3002\u7531\u4e8e $2(k+1)^{d-1}$ \u4e2a\u5355\u5143\u81ea\u7531\u5ea6\u4e2d\u53ea\u6709 $(k+1)^d$ \u4e2a\u5355\u5143\u81ea\u7531\u5ea6\u88ab\u975e\u96f6\u503c\u6216\u5f62\u72b6\u51fd\u6570\u7684\u5bfc\u6570\u6240\u4e58\uff0c\u8fd9\u79cd\u7ed3\u6784\u53ef\u4ee5\u88ab\u7528\u4e8e\u8bc4\u4f30\uff0c\u5927\u5927\u51cf\u5c11\u4e86\u6570\u636e\u8bbf\u95ee\u3002\u51cf\u5c11\u6570\u636e\u8bbf\u95ee\u4e0d\u4ec5\u662f\u6709\u76ca\u7684\uff0c\u56e0\u4e3a\u5b83\u51cf\u5c11\u4e86\u98de\u884c\u4e2d\u7684\u6570\u636e\uff0c\u4ece\u800c\u6709\u52a9\u4e8e\u7f13\u5b58\uff0c\u800c\u4e14\u5f53\u4ece\u5355\u5143\u683c\u7d22\u5f15\u5217\u8868\u4e2d\u76f8\u8ddd\u8f83\u8fdc\u7684\u5355\u5143\u683c\u6536\u96c6\u6570\u503c\u65f6\uff0c\u5bf9\u9762\u7684\u6570\u636e\u8bbf\u95ee\u5f80\u5f80\u6bd4\u5355\u5143\u683c\u79ef\u5206\u66f4\u4e0d\u89c4\u5219\u3002\n\n        phi_inner.reinit(face); \n        phi_inner.gather_evaluate(src, \n                                  EvaluationFlags::values | \n                                    EvaluationFlags::gradients); \n        phi_outer.reinit(face); \n        phi_outer.gather_evaluate(src, \n                                  EvaluationFlags::values | \n                                    EvaluationFlags::gradients); \n\n// \u63a5\u4e0b\u6765\u7684\u4e24\u4e2a\u8bed\u53e5\u662f\u8ba1\u7b97\u5185\u90e8\u60e9\u7f5a\u6cd5\u7684\u60e9\u7f5a\u53c2\u6570\u3002\u6b63\u5982\u5728\u4ecb\u7ecd\u4e2d\u6240\u89e3\u91ca\u7684\uff0c\u6211\u4eec\u5e0c\u671b\u6709\u4e00\u4e2a\u50cf $\\frac{1}{h_\\text{i}}$ \u8fd9\u6837\u7684\u957f\u5ea6 $h_\\text{i}$ \u6cd5\u7ebf\u5230\u9762\u7684\u7f29\u653e\u6bd4\u4f8b\u3002\u5bf9\u4e8e\u4e00\u822c\u7684\u975e\u7b1b\u5361\u5c14\u7f51\u683c\uff0c\u8fd9\u4e2a\u957f\u5ea6\u5fc5\u987b\u7531\u53cd\u96c5\u5404\u5e03\u7cfb\u6570\u4e58\u4ee5\u5b9e\u5750\u6807\u7684\u6cd5\u5411\u91cf\u7684\u4e58\u79ef\u6765\u8ba1\u7b97\u3002\u4ece\u8fd9\u4e2a \"dim \"\u5206\u91cf\u7684\u5411\u91cf\u4e2d\uff0c\u6211\u4eec\u5fc5\u987b\u6700\u7ec8\u6311\u9009\u51fa\u4e0e\u53c2\u8003\u5355\u5143\u7684\u6cd5\u7ebf\u65b9\u5411\u4e00\u81f4\u7684\u5206\u91cf\u3002\u5728MatrixFree\u4e2d\u5b58\u50a8\u7684\u51e0\u4f55\u6570\u636e\u4e2d\uff0c\u96c5\u5404\u5e03\u5f0f\u4e2d\u7684\u5206\u91cf\u88ab\u5e94\u7528\uff0c\u4f7f\u5f97\u540e\u4e00\u4e2a\u65b9\u5411\u603b\u662f\u6700\u540e\u4e00\u4e2a\u5206\u91cf`dim-1`\uff08\u8fd9\u5f88\u6709\u5229\uff0c\u56e0\u4e3a\u53c2\u8003\u5355\u5143\u7684\u5bfc\u6570\u6392\u5e8f\u53ef\u4ee5\u4e0e\u9762\u7684\u65b9\u5411\u65e0\u5173\uff09\u3002\u8fd9\u610f\u5473\u7740\u6211\u4eec\u53ef\u4ee5\u7b80\u5355\u5730\u8bbf\u95ee\u6700\u540e\u4e00\u4e2a\u5206\u91cf`dim-1`\uff0c\u800c\u4e0d\u5fc5\u5728`data.get_face_info(face).internal_face_no`\u548c`data.get_face_info(face).exterior_face_no`\u4e2d\u67e5\u627e\u5c40\u90e8\u9762\u7684\u7f16\u53f7\u3002\u6700\u540e\uff0c\u6211\u4eec\u8fd8\u5fc5\u987b\u53d6\u8fd9\u4e9b\u56e0\u7d20\u7684\u7edd\u5bf9\u503c\uff0c\u56e0\u4e3a\u6cd5\u7ebf\u53ef\u80fd\u6307\u5411\u6b63\u6216\u8d1f\u7684\u65b9\u5411\u3002\n\n        const VectorizedArray<number> inverse_length_normal_to_face = \n          0.5 * (std::abs((phi_inner.get_normal_vector(0) * \n                           phi_inner.inverse_jacobian(0))[dim - 1]) + \n                 std::abs((phi_outer.get_normal_vector(0) * \n                           phi_outer.inverse_jacobian(0))[dim - 1])); \n        const VectorizedArray<number> sigma = \n          inverse_length_normal_to_face * get_penalty_factor(); \n\n// \u5728\u6b63\u4ea4\u70b9\u7684\u5faa\u73af\u4e2d\uff0c\u6211\u4eec\u6700\u7ec8\u8ba1\u7b97\u4e86\u5bf9\u5185\u90e8\u60e9\u7f5a\u65b9\u6848\u7684\u6240\u6709\u8d21\u732e\u3002\u6839\u636e\u4ecb\u7ecd\u4e2d\u7684\u516c\u5f0f\uff0c\u6d4b\u8bd5\u51fd\u6570\u7684\u503c\u88ab\u4e58\u4ee5\u89e3\u51b3\u65b9\u6848\u4e2d\u7684\u8df3\u8dc3\u4e58\u4ee5\u60e9\u7f5a\u53c2\u6570\u548c\u5b9e\u7a7a\u95f4\u4e2d\u7684\u6cd5\u5411\u5bfc\u6570\u7684\u5e73\u5747\u503c\u7684\u5dee\u503c\u3002\u7531\u4e8e\u5185\u4fa7\u548c\u5916\u4fa7\u7684\u4e24\u4e2a\u8bc4\u4f30\u5668\u7531\u4e8e\u8df3\u8dc3\u800c\u5f97\u5230\u4e0d\u540c\u7684\u7b26\u53f7\uff0c\u6211\u4eec\u5728\u8fd9\u91cc\u7528\u4e0d\u540c\u7684\u7b26\u53f7\u4f20\u9012\u7ed3\u679c\u3002\u6d4b\u8bd5\u51fd\u6570\u7684\u6b63\u6001\u5bfc\u6570\u4f1a\u88ab\u5185\u4fa7\u548c\u5916\u4fa7\u7684\u89e3\u51b3\u65b9\u6848\u4e2d\u7684\u8d1f\u8df3\u8dc3\u6240\u4e58\u3002\u8fd9\u4e2a\u672f\u8bed\uff0c\u88ab\u79f0\u4e3a\u90bb\u63a5\u4e00\u81f4\u6027\u672f\u8bed\uff0c\u6839\u636e\u5176\u4e0e\u539f\u59cb\u4e00\u81f4\u6027\u672f\u8bed\u7684\u5173\u7cfb\uff0c\u5728\u4ee3\u7801\u4e2d\u8fd8\u5fc5\u987b\u5305\u62ec $\\frac{1}{2}$ \u7684\u7cfb\u6570\uff0c\u7531\u4e8e\u6d4b\u8bd5\u51fd\u6570\u69fd\u4e2d\u7684\u5e73\u5747\u6570\uff0c\u5b83\u5f97\u5230\u4e86\u4e8c\u5206\u4e4b\u4e00\u7684\u7cfb\u6570\u3002\n\n        for (unsigned int q = 0; q < phi_inner.n_q_points; ++q) \n          { \n            const VectorizedArray<number> solution_jump = \n              (phi_inner.get_value(q) - phi_outer.get_value(q)); \n            const VectorizedArray<number> average_normal_derivative = \n              (phi_inner.get_normal_derivative(q) + \n               phi_outer.get_normal_derivative(q)) * \n              number(0.5); \n            const VectorizedArray<number> test_by_value = \n              solution_jump * sigma - average_normal_derivative; \n\n            phi_inner.submit_value(test_by_value, q); \n            phi_outer.submit_value(-test_by_value, q); \n\n            phi_inner.submit_normal_derivative(-solution_jump * number(0.5), q); \n            phi_outer.submit_normal_derivative(-solution_jump * number(0.5), q); \n          } \n\n// \u4e00\u65e6\u6211\u4eec\u5b8c\u6210\u4e86\u6b63\u4ea4\u70b9\u7684\u5faa\u73af\uff0c\u6211\u4eec\u5c31\u53ef\u4ee5\u5bf9\u9762\u7684\u79ef\u5206\u5faa\u73af\u8fdb\u884c\u548c\u56e0\u5b50\u5316\u64cd\u4f5c\uff0c\u5e76\u5c06\u7ed3\u679c\u52a0\u5230\u7ed3\u679c\u5411\u91cf\u4e2d\uff0c\u4f7f\u7528`integrate_scatter`\u51fd\u6570\u3002`scatter'\u8fd9\u4e2a\u540d\u5b57\u53cd\u6620\u4e86\u4f7f\u7528\u4e0e`gather_evaluate'\u76f8\u540c\u7684\u6a21\u5f0f\u5c06\u77e2\u91cf\u6570\u636e\u5206\u5e03\u5230\u77e2\u91cf\u4e2d\u7684\u5206\u6563\u4f4d\u7f6e\u3002\u50cf\u4ee5\u524d\u4e00\u6837\uff0c\u6574\u5408+\u5199\u64cd\u4f5c\u7684\u7ec4\u5408\u5141\u8bb8\u6211\u4eec\u51cf\u5c11\u6570\u636e\u8bbf\u95ee\u3002\n\n        phi_inner.integrate_scatter(EvaluationFlags::values | \n                                      EvaluationFlags::gradients, \n                                    dst); \n        phi_outer.integrate_scatter(EvaluationFlags::values | \n                                      EvaluationFlags::gradients, \n                                    dst); \n      } \n  } \n\n// \u8fb9\u754c\u9762\u51fd\u6570\u5927\u4f53\u4e0a\u6cbf\u7528\u4e86\u5185\u90e8\u9762\u51fd\u6570\u3002\u552f\u4e00\u7684\u533a\u522b\u662f\uff0c\u6211\u4eec\u6ca1\u6709\u4e00\u4e2a\u5355\u72ec\u7684FEFaceEvaluation\u5bf9\u8c61\u4e3a\u6211\u4eec\u63d0\u4f9b\u5916\u90e8\u503c  $u^+$  \uff0c\u4f46\u6211\u4eec\u5fc5\u987b\u4ece\u8fb9\u754c\u6761\u4ef6\u548c\u5185\u90e8\u503c  $u^-$  \u6765\u5b9a\u4e49\u5b83\u4eec\u3002\u6b63\u5982\u4ecb\u7ecd\u4e2d\u6240\u89e3\u91ca\u7684\uff0c\u6211\u4eec\u5728Dirichlet\u8fb9\u754c\u4e0a\u4f7f\u7528 $u^+ = -u^- + 2 g_\\text{D}$ \u548c $\\mathbf{n}^-\\cdot \\nabla u^+ = \\mathbf{n}^-\\cdot \\nabla u^-$ \uff0c\u5728Neumann\u8fb9\u754c\u4e0a\u4f7f\u7528 $u^+=u^-$ \u548c $\\mathbf{n}^-\\cdot \\nabla u^+ = -\\mathbf{n}^-\\cdot \\nabla u^- + 2 g_\\text{N}$  \u3002\u7531\u4e8e\u8fd9\u4e2a\u64cd\u4f5c\u5b9e\u73b0\u4e86\u540c\u8d28\u90e8\u5206\uff0c\u5373\u77e9\u9635-\u5411\u91cf\u4e58\u79ef\uff0c\u6211\u4eec\u5fc5\u987b\u5728\u8fd9\u91cc\u5ffd\u7565\u8fb9\u754c\u51fd\u6570 $g_\\text{D}$ \u548c $g_\\text{N}$ \uff0c\u5e76\u5728 `LaplaceProblem::compute_rhs()`. \u4e2d\u628a\u5b83\u4eec\u52a0\u5230\u53f3\u4fa7\u3002 ] \u6ce8\u610f\uff0c\u7531\u4e8e\u901a\u8fc7 $u^+$ \u5c06\u89e3 $u^-$ \u6269\u5c55\u5230\u5916\u90e8\uff0c\u6211\u4eec\u53ef\u4ee5\u4fdd\u6301\u6240\u6709\u56e0\u5b50 $0.5$ \u4e0e\u5185\u9762\u51fd\u6570\u76f8\u540c\uff0c\u4e5f\u53ef\u53c2\u89c1 step-39 \u4e2d\u7684\u8ba8\u8bba\u3002\n\n// \u5728\u8fd9\u4e00\u70b9\u4e0a\u6709\u4e00\u4e2a\u95ee\u9898\u3002\u4e0b\u9762\u7684\u5b9e\u73b0\u4f7f\u7528\u4e00\u4e2a\u5e03\u5c14\u53d8\u91cf`is_dirichlet`\u6765\u5207\u6362Dirichlet\u548cNeumann\u60c5\u51b5\u3002\u7136\u800c\uff0c\u6211\u4eec\u89e3\u51b3\u4e86\u4e00\u4e2a\u95ee\u9898\uff0c\u6211\u4eec\u8fd8\u60f3\u5728\u4e00\u4e9b\u8fb9\u754c\u4e0a\u65bd\u52a0\u5468\u671f\u6027\u7684\u8fb9\u754c\u6761\u4ef6\uff0c\u5373\u6cbf\u7740 $x$ \u65b9\u5411\u7684\u8fb9\u754c\u3002\u4eba\u4eec\u53ef\u80fd\u4f1a\u95ee\uff0c\u8fd9\u91cc\u5e94\u8be5\u5982\u4f55\u5904\u7406\u8fd9\u4e9b\u6761\u4ef6\u3002\u7b54\u6848\u662fMatrixFree\u4f1a\u81ea\u52a8\u5c06\u5468\u671f\u6027\u8fb9\u754c\u89c6\u4e3a\u6280\u672f\u4e0a\u7684\u8fb9\u754c\uff0c\u5373\u4e24\u4e2a\u76f8\u90bb\u5355\u5143\u7684\u89e3\u503c\u76f8\u9047\u7684\u5185\u9762\uff0c\u5fc5\u987b\u7528\u9002\u5f53\u7684\u6570\u503c\u901a\u91cf\u6765\u5904\u7406\u3002\u56e0\u6b64\uff0c\u5468\u671f\u6027\u8fb9\u754c\u4e0a\u7684\u6240\u6709\u9762\u5c06\u51fa\u73b0\u5728`apply_face()`\u51fd\u6570\u4e2d\uff0c\u800c\u4e0d\u662f\u8fd9\u4e2a\u51fd\u6570\u4e2d\u3002\n\n  template <int dim, int fe_degree, typename number> \n  void LaplaceOperator<dim, fe_degree, number>::apply_boundary( \n    const MatrixFree<dim, number> &                   data, \n    LinearAlgebra::distributed::Vector<number> &      dst, \n    const LinearAlgebra::distributed::Vector<number> &src, \n    const std::pair<unsigned int, unsigned int> &     face_range) const \n  { \n    FEFaceEvaluation<dim, fe_degree, fe_degree + 1, 1, number> phi_inner(data, \n                                                                         true); \n    for (unsigned int face = face_range.first; face < face_range.second; ++face) \n      { \n        phi_inner.reinit(face); \n        phi_inner.gather_evaluate(src, \n                                  EvaluationFlags::values | \n                                    EvaluationFlags::gradients); \n\n        const VectorizedArray<number> inverse_length_normal_to_face = \n          std::abs((phi_inner.get_normal_vector(0) * \n                    phi_inner.inverse_jacobian(0))[dim - 1]); \n        const VectorizedArray<number> sigma = \n          inverse_length_normal_to_face * get_penalty_factor(); \n\n        const bool is_dirichlet = (data.get_boundary_id(face) == 0); \n\n        for (unsigned int q = 0; q < phi_inner.n_q_points; ++q) \n          { \n            const VectorizedArray<number> u_inner = phi_inner.get_value(q); \n            const VectorizedArray<number> u_outer = \n              is_dirichlet ? -u_inner : u_inner; \n            const VectorizedArray<number> normal_derivative_inner = \n              phi_inner.get_normal_derivative(q); \n            const VectorizedArray<number> normal_derivative_outer = \n              is_dirichlet ? normal_derivative_inner : -normal_derivative_inner; \n            const VectorizedArray<number> solution_jump = (u_inner - u_outer); \n            const VectorizedArray<number> average_normal_derivative = \n              (normal_derivative_inner + normal_derivative_outer) * number(0.5); \n            const VectorizedArray<number> test_by_value = \n              solution_jump * sigma - average_normal_derivative; \n            phi_inner.submit_normal_derivative(-solution_jump * number(0.5), q); \n            phi_inner.submit_value(test_by_value, q); \n          } \n        phi_inner.integrate_scatter(EvaluationFlags::values | \n                                      EvaluationFlags::gradients, \n                                    dst); \n      } \n  } \n\n// \u63a5\u4e0b\u6765\u6211\u4eec\u6765\u770b\u770b\u9884\u5904\u7406\u7a0b\u5e8f\u7684\u521d\u59cb\u5316\u3002\u6b63\u5982\u4ecb\u7ecd\u4e2d\u6240\u89e3\u91ca\u7684\uff0c\u6211\u4eec\u60f3\u4ece\u4e00\u7ef4\u8d28\u91cf\u548c\u62c9\u666e\u62c9\u65af\u77e9\u9635\u7684\u4e58\u79ef\u4e2d\u6784\u9020\u4e00\u4e2a\uff08\u8fd1\u4f3c\u7684\uff09\u5355\u5143\u77e9\u9635\u7684\u9006\u3002\u6211\u4eec\u7684\u9996\u8981\u4efb\u52a1\u662f\u8ba1\u7b97\u4e00\u7ef4\u77e9\u9635\uff0c\u6211\u4eec\u901a\u8fc7\u9996\u5148\u521b\u5efa\u4e00\u4e2a\u4e00\u7ef4\u6709\u9650\u5143\u6765\u5b9e\u73b0\u3002\u5728\u8fd9\u91cc\uff0c\u6211\u4eec\u6ca1\u6709\u9884\u89c1\u5230FE_DGQHermite<1>\uff0c\u800c\u662f\u4eceDoFHandler\u83b7\u5f97\u6709\u9650\u5143\u7684\u540d\u79f0\uff0c\u75281\u66ff\u6362 @p dim \u53c2\u6570\uff082\u62163\uff09\u6765\u521b\u5efa\u4e00\u4e2a\u4e00\u7ef4\u540d\u79f0\uff0c\u5e76\u901a\u8fc7\u4f7f\u7528FETools\u6765\u6784\u9020\u4e00\u7ef4\u5143\u7d20\u3002\n\n  template <int dim, int fe_degree, typename number> \n  void PreconditionBlockJacobi<dim, fe_degree, number>::initialize( \n    const LaplaceOperator<dim, fe_degree, number> &op) \n  { \n    data = op.get_matrix_free(); \n\n    std::string name = data->get_dof_handler().get_fe().get_name(); \n    name.replace(name.find('<') + 1, 1, \"1\"); \n    std::unique_ptr<FiniteElement<1>> fe_1d = FETools::get_fe_by_name<1>(name); \n\n// \u81f3\u4e8e\u5728\u5355\u4f4d\u5143\u7d20\u4e0a\u8ba1\u7b97\u4e00\u7ef4\u77e9\u9635\uff0c\u6211\u4eec\u7b80\u5355\u5730\u5199\u4e0b\u5728\u77e9\u9635\u7684\u884c\u548c\u5217\u4ee5\u53ca\u6b63\u4ea4\u70b9\u4e0a\u7684\u5178\u578b\u88c5\u914d\u7a0b\u5e8f\u4f1a\u505a\u4ec0\u4e48\u3002\u6211\u4eec\u4e00\u52b3\u6c38\u9038\u5730\u9009\u62e9\u76f8\u540c\u7684\u62c9\u666e\u62c9\u65af\u77e9\u9635\uff0c\u5bf9\u5185\u90e8\u9762\u4f7f\u7528\u7cfb\u65700.5\uff08\u4f46\u53ef\u80fd\u7531\u4e8e\u7f51\u683c\u7684\u539f\u56e0\uff0c\u5728\u4e0d\u540c\u65b9\u5411\u4e0a\u7684\u7f29\u653e\u6bd4\u4f8b\u4e0d\u540c\uff09\u3002\u56e0\u6b64\uff0c\u6211\u4eec\u5728Dirichlet\u8fb9\u754c\uff08\u6b63\u786e\u7684\u7cfb\u6570\u5e94\u8be5\u662f\u5bfc\u6570\u9879\u4e3a1\uff0c\u60e9\u7f5a\u9879\u4e3a2\uff0c\u89c1 step-39 \uff09\u6216\u5728Neumann\u8fb9\u754c\uff08\u7cfb\u6570\u5e94\u8be5\u4e3a0\uff09\u72af\u4e86\u4e00\u4e2a\u5c0f\u9519\u8bef\u3002\u7531\u4e8e\u6211\u4eec\u53ea\u5728\u591a\u7f51\u683c\u65b9\u6848\u4e2d\u4f7f\u7528\u8fd9\u4e2a\u7c7b\u4f5c\u4e3a\u5e73\u6ed1\u5668\uff0c\u8fd9\u4e2a\u9519\u8bef\u4e0d\u4f1a\u6709\u4efb\u4f55\u91cd\u5927\u5f71\u54cd\uff0c\u53ea\u662f\u5f71\u54cd\u5e73\u6ed1\u8d28\u91cf\u3002\n\n    const unsigned int                                 N = fe_degree + 1; \n    FullMatrix<double>                                 laplace_unscaled(N, N); \n    std::array<Table<2, VectorizedArray<number>>, dim> mass_matrices; \n    std::array<Table<2, VectorizedArray<number>>, dim> laplace_matrices; \n    for (unsigned int d = 0; d < dim; ++d) \n      { \n        mass_matrices[d].reinit(N, N); \n        laplace_matrices[d].reinit(N, N); \n      } \n\n    QGauss<1> quadrature(N); \n    for (unsigned int i = 0; i < N; ++i) \n      for (unsigned int j = 0; j < N; ++j) \n        { \n          double sum_mass = 0, sum_laplace = 0; \n          for (unsigned int q = 0; q < quadrature.size(); ++q) \n            { \n              sum_mass += (fe_1d->shape_value(i, quadrature.point(q)) * \n                           fe_1d->shape_value(j, quadrature.point(q))) * \n                          quadrature.weight(q); \n              sum_laplace += (fe_1d->shape_grad(i, quadrature.point(q))[0] * \n                              fe_1d->shape_grad(j, quadrature.point(q))[0]) * \n                             quadrature.weight(q); \n            } \n          for (unsigned int d = 0; d < dim; ++d) \n            mass_matrices[d](i, j) = sum_mass; \n\n// \u63a5\u4e0b\u6765\u4e24\u4e2a\u8bed\u53e5\u7ec4\u88c5\u7684\u5de6\u53f3\u8fb9\u754c\u9879\u4f3c\u4e4e\u6709\u4e00\u4e9b\u4efb\u610f\u7684\u7b26\u53f7\uff0c\u4f46\u8fd9\u4e9b\u90fd\u662f\u6b63\u786e\u7684\uff0c\u53ef\u4ee5\u901a\u8fc7\u67e5\u770b step-39 \u5e76\u63d2\u51651D\u60c5\u51b5\u4e0b\u7684\u6cd5\u5411\u91cf\u7684\u503c-1\u548c1\u6765\u9a8c\u8bc1\u3002\n\n          sum_laplace += \n            (1. * fe_1d->shape_value(i, Point<1>()) * \n               fe_1d->shape_value(j, Point<1>()) * op.get_penalty_factor() + \n             0.5 * fe_1d->shape_grad(i, Point<1>())[0] * \n               fe_1d->shape_value(j, Point<1>()) + \n             0.5 * fe_1d->shape_grad(j, Point<1>())[0] * \n               fe_1d->shape_value(i, Point<1>())); \n\n          sum_laplace += \n            (1. * fe_1d->shape_value(i, Point<1>(1.0)) * \n               fe_1d->shape_value(j, Point<1>(1.0)) * op.get_penalty_factor() - \n             0.5 * fe_1d->shape_grad(i, Point<1>(1.0))[0] * \n               fe_1d->shape_value(j, Point<1>(1.0)) - \n             0.5 * fe_1d->shape_grad(j, Point<1>(1.0))[0] * \n               fe_1d->shape_value(i, Point<1>(1.0))); \n\n          laplace_unscaled(i, j) = sum_laplace; \n        } \n\n// \u63a5\u4e0b\u6765\uff0c\u6211\u4eec\u901a\u8fc7\u5355\u5143\u683c\uff0c\u5c06\u7f29\u653e\u540e\u7684\u77e9\u9635\u4f20\u9012\u7ed9TensorProductMatrixSymmetricSum\uff0c\u4ee5\u5b9e\u9645\u8ba1\u7b97\u4ee3\u8868\u9006\u7684\u5e7f\u4e49\u7279\u5f81\u503c\u95ee\u9898\u3002\u7531\u4e8e\u77e9\u9635\u7684\u8fd1\u4f3c\u6784\u9020\u4e3a $A\\otimes M + M\\otimes A$ \uff0c\u5e76\u4e14\u6bcf\u4e2a\u5143\u7d20\u7684\u6743\u91cd\u662f\u6052\u5b9a\u7684\uff0c\u6211\u4eec\u53ef\u4ee5\u5728\u62c9\u666e\u62c9\u65af\u77e9\u9635\u4e0a\u5e94\u7528\u6240\u6709\u7684\u6743\u91cd\uff0c\u5e76\u7b80\u5355\u5730\u4fdd\u6301\u8d28\u91cf\u77e9\u9635\u4e0d\u88ab\u7f29\u653e\u3002\u5728\u5355\u5143\u683c\u7684\u5faa\u73af\u4e2d\uff0c\u6211\u4eec\u8981\u5229\u7528MatrixFree\u7c7b\u63d0\u4f9b\u7684\u51e0\u4f55\u4f53\u538b\u7f29\uff0c\u5e76\u68c0\u67e5\u5f53\u524d\u7684\u51e0\u4f55\u4f53\u662f\u5426\u4e0e\u4e0a\u4e00\u6279\u5355\u5143\u683c\u4e0a\u7684\u51e0\u4f55\u4f53\u76f8\u540c\uff0c\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\u5c31\u6ca1\u6709\u4ec0\u4e48\u53ef\u505a\u7684\u3002\u4e00\u65e6\u8c03\u7528\u4e86`reinit()`\uff0c\u5c31\u53ef\u4ee5\u901a\u8fc7 FEEvaluation::get_mapping_data_index_offset() \u8bbf\u95ee\u8fd9\u79cd\u538b\u7f29\u3002\n\n// \u4e00\u65e6\u6211\u4eec\u901a\u8fc7FEEvaluation\u8bbf\u95ee\u51fd\u6570\u8bbf\u95ee\u4e86\u53cd\u96c5\u5404\u5e03\u7cfb\u6570\uff08\u6211\u4eec\u53d6\u7b2c4\u4e2a\u6b63\u4ea4\u70b9\u7684\uff0c\u56e0\u4e3a\u5b83\u4eec\u5728\u7b1b\u5361\u5c14\u5355\u5143\u7684\u6240\u6709\u6b63\u4ea4\u70b9\u4e0a\u90fd\u5e94\u8be5\u662f\u4e00\u6837\u7684\uff09\uff0c\u6211\u4eec\u68c0\u67e5\u5b83\u662f\u5bf9\u89d2\u7ebf\u7684\uff0c\u7136\u540e\u63d0\u53d6\u539f\u59cb\u96c5\u5404\u5e03\u7cfb\u6570\u7684\u884c\u5217\u5f0f\uff0c\u5373\u53cd\u96c5\u5404\u5e03\u7cfb\u6570\u7684\u884c\u5217\u5f0f\uff0c\u5e76\u6839\u636e\u8d28\u91cf\u77e9\u9635\u7684\u4e00\u7ef4\u62c9\u666e\u62c9\u65af\u4e58\u4ee5 $d-1$ \u4efd\uff0c\u8bbe\u7f6e\u6743\u91cd\u4e3a $\\text{det}(J) / h_d^2$  \u3002\n\n    cell_matrices.clear(); \n    FEEvaluation<dim, fe_degree, fe_degree + 1, 1, number> phi(*data); \n    unsigned int old_mapping_data_index = numbers::invalid_unsigned_int; \n    for (unsigned int cell = 0; cell < data->n_cell_batches(); ++cell) \n      { \n        phi.reinit(cell); \n\n        if (phi.get_mapping_data_index_offset() == old_mapping_data_index) \n          continue; \n\n        Tensor<2, dim, VectorizedArray<number>> inverse_jacobian = \n          phi.inverse_jacobian(0); \n\n        for (unsigned int d = 0; d < dim; ++d) \n          for (unsigned int e = 0; e < dim; ++e) \n            if (d != e) \n              for (unsigned int v = 0; v < VectorizedArray<number>::size(); ++v) \n                AssertThrow(inverse_jacobian[d][e][v] == 0., \n                            ExcNotImplemented()); \n\n        VectorizedArray<number> jacobian_determinant = inverse_jacobian[0][0]; \n        for (unsigned int e = 1; e < dim; ++e) \n          jacobian_determinant *= inverse_jacobian[e][e]; \n        jacobian_determinant = 1. / jacobian_determinant; \n\n        for (unsigned int d = 0; d < dim; ++d) \n          { \n            const VectorizedArray<number> scaling_factor = \n              inverse_jacobian[d][d] * inverse_jacobian[d][d] * \n              jacobian_determinant; \n\n// \u4e00\u65e6\u6211\u4eec\u77e5\u9053\u4e86\u62c9\u666e\u62c9\u65af\u77e9\u9635\u7684\u6bd4\u4f8b\u7cfb\u6570\uff0c\u6211\u4eec\u5c31\u5c06\u8fd9\u4e2a\u6743\u91cd\u5e94\u7528\u4e8e\u672a\u88ab\u7f29\u653e\u7684DG\u62c9\u666e\u62c9\u65af\u77e9\u9635\uff0c\u5e76\u5c06\u6570\u7ec4\u53d1\u9001\u5230TensorProductMatrixSymmetricSum\u7c7b\uff0c\u4ee5\u8ba1\u7b97\u4ecb\u7ecd\u4e2d\u63d0\u5230\u7684\u5e7f\u4e49\u7279\u5f81\u503c\u95ee\u9898\u3002\n\n            for (unsigned int i = 0; i < N; ++i) \n              for (unsigned int j = 0; j < N; ++j) \n                laplace_matrices[d](i, j) = \n                  scaling_factor * laplace_unscaled(i, j); \n          } \n        if (cell_matrices.size() <= phi.get_mapping_data_index_offset()) \n          cell_matrices.resize(phi.get_mapping_data_index_offset() + 1); \n        cell_matrices[phi.get_mapping_data_index_offset()].reinit( \n          mass_matrices, laplace_matrices); \n      } \n  } \n\n// \u5728DG\u80cc\u666f\u4e0b\uff0c\u7528\u4e8e\u8fd1\u4f3c\u5757\u72b6Jacobi\u9884\u5904\u7406\u7684vmult\u51fd\u6570\u975e\u5e38\u7b80\u5355\u3002\u6211\u4eec\u53ea\u9700\u8981\u8bfb\u53d6\u5f53\u524d\u5355\u5143\u683c\u6279\u6b21\u7684\u503c\uff0c\u5bf9\u5f20\u91cf\u79ef\u77e9\u9635\u9635\u5217\u4e2d\u7684\u7ed9\u5b9a\u6761\u76ee\u8fdb\u884c\u9006\u8fd0\u7b97\uff0c\u5e76\u5c06\u7ed3\u679c\u5199\u56de\u3002\u5728\u8fd9\u4e2a\u5faa\u73af\u4e2d\uff0c\u6211\u4eec\u8986\u76d6\u4e86`dst`\u4e2d\u7684\u5185\u5bb9\uff0c\u800c\u4e0d\u662f\u9996\u5148\u5c06\u6761\u76ee\u8bbe\u7f6e\u4e3a\u96f6\u3002\u8fd9\u5bf9\u4e8eDG\u65b9\u6cd5\u6765\u8bf4\u662f\u5408\u6cd5\u7684\uff0c\u56e0\u4e3a\u6bcf\u4e2a\u5355\u5143\u90fd\u6709\u72ec\u7acb\u7684\u81ea\u7531\u5ea6\u3002\u6b64\u5916\uff0c\u6211\u4eec\u624b\u52a8\u5199\u51fa\u6240\u6709\u5355\u5143\u6279\u7684\u5faa\u73af\uff0c\u800c\u4e0d\u662f\u901a\u8fc7 MatrixFree::cell_loop(). \u6211\u4eec\u8fd9\u6837\u505a\u662f\u56e0\u4e3a\u6211\u4eec\u77e5\u9053\u6211\u4eec\u5728\u8fd9\u91cc\u4e0d\u9700\u8981\u901a\u8fc7MPI\u7f51\u7edc\u8fdb\u884c\u6570\u636e\u4ea4\u6362\uff0c\u56e0\u4e3a\u6240\u6709\u7684\u8ba1\u7b97\u90fd\u662f\u5728\u6bcf\u4e2a\u5904\u7406\u5668\u4e0a\u7684\u672c\u5730\u5355\u5143\u4e0a\u5b8c\u6210\u7684\u3002\n\n  template <int dim, int fe_degree, typename number> \n  void PreconditionBlockJacobi<dim, fe_degree, number>::vmult( \n    LinearAlgebra::distributed::Vector<number> &      dst, \n    const LinearAlgebra::distributed::Vector<number> &src) const \n  { \n    adjust_ghost_range_if_necessary(*data, dst); \n    adjust_ghost_range_if_necessary(*data, src); \n\n    FEEvaluation<dim, fe_degree, fe_degree + 1, 1, number> phi(*data); \n    for (unsigned int cell = 0; cell < data->n_cell_batches(); ++cell) \n      { \n        phi.reinit(cell); \n        phi.read_dof_values(src); \n        cell_matrices[phi.get_mapping_data_index_offset()].apply_inverse( \n          ArrayView<VectorizedArray<number>>(phi.begin_dof_values(), \n                                             phi.dofs_per_cell), \n          ArrayView<const VectorizedArray<number>>(phi.begin_dof_values(), \n                                                   phi.dofs_per_cell)); \n        phi.set_dof_values(dst); \n      } \n  } \n\n// LaplaceProblem\u7c7b\u7684\u5b9a\u4e49\u4e0e  step-37  \u975e\u5e38\u76f8\u4f3c\u3002\u4e00\u4e2a\u533a\u522b\u662f\u6211\u4eec\u5c06\u5143\u7d20\u5ea6\u4f5c\u4e3a\u6a21\u677f\u53c2\u6570\u6dfb\u52a0\u5230\u7c7b\u4e2d\uff0c\u8fd9\u5c06\u5141\u8bb8\u6211\u4eec\u901a\u8fc7\u5728`main()`\u51fd\u6570\u4e2d\u521b\u5efa\u4e0d\u540c\u7684\u5b9e\u4f8b\uff0c\u66f4\u5bb9\u6613\u5728\u540c\u4e00\u4e2a\u7a0b\u5e8f\u4e2d\u5305\u542b\u591a\u4e2a\u5ea6\u3002\u7b2c\u4e8c\u4e2a\u533a\u522b\u662f\u9009\u62e9\u4e86FE_DGQHermite\u8fd9\u4e2a\u5143\u7d20\uff0c\u5b83\u662f\u4e13\u95e8\u7528\u4e8e\u8fd9\u79cd\u65b9\u7a0b\u7684\u3002\n\n  template <int dim, int fe_degree> \n  class LaplaceProblem \n  { \n  public: \n    LaplaceProblem(); \n    void run(); \n\n  private: \n    void setup_system(); \n    void compute_rhs(); \n    void solve(); \n    void analyze_results() const; \n\n#ifdef DEAL_II_WITH_P4EST \n    parallel::distributed::Triangulation<dim> triangulation; \n#else \n    Triangulation<dim> triangulation; \n#endif \n\n    FE_DGQHermite<dim> fe; \n    DoFHandler<dim>    dof_handler; \n\n    MappingQ1<dim> mapping; \n\n    using SystemMatrixType = LaplaceOperator<dim, fe_degree, double>; \n    SystemMatrixType system_matrix; \n\n    using LevelMatrixType = LaplaceOperator<dim, fe_degree, float>; \n    MGLevelObject<LevelMatrixType> mg_matrices; \n\n    LinearAlgebra::distributed::Vector<double> solution; \n    LinearAlgebra::distributed::Vector<double> system_rhs; \n\n    double             setup_time; \n    ConditionalOStream pcout; \n    ConditionalOStream time_details; \n  }; \n\n  template <int dim, int fe_degree> \n  LaplaceProblem<dim, fe_degree>::LaplaceProblem() \n    : \n#ifdef DEAL_II_WITH_P4EST \n    triangulation( \n      MPI_COMM_WORLD, \n      Triangulation<dim>::limit_level_difference_at_vertices, \n      parallel::distributed::Triangulation<dim>::construct_multigrid_hierarchy) \n    , \n#else \n    triangulation(Triangulation<dim>::limit_level_difference_at_vertices) \n    , \n#endif \n    fe(fe_degree) \n    , dof_handler(triangulation) \n    , setup_time(0.) \n    , pcout(std::cout, Utilities::MPI::this_mpi_process(MPI_COMM_WORLD) == 0) \n    , time_details(std::cout, \n                   false && \n                     Utilities::MPI::this_mpi_process(MPI_COMM_WORLD) == 0) \n  {} \n\n// \u8bbe\u7f6e\u51fd\u6570\u5728\u4e24\u4e2a\u65b9\u9762\u4e0e  step-37  \u4e0d\u540c\u3002\u9996\u5148\u662f\u6211\u4eec\u4e0d\u9700\u8981\u4e3a\u4e0d\u8fde\u7eed\u7684Ansatz\u7a7a\u95f4\u63d2\u503c\u4efb\u4f55\u7ea6\u675f\uff0c\u800c\u53ea\u662f\u5c06\u4e00\u4e2a\u5047\u7684AffineConstraints\u5bf9\u8c61\u4f20\u5165 Matrixfree::reinit().  \u7b2c\u4e8c\u4e2a\u53d8\u5316\u662f\u56e0\u4e3a\u6211\u4eec\u9700\u8981\u544a\u8bc9MatrixFree\u540c\u65f6\u521d\u59cb\u5316\u9762\u7684\u6570\u636e\u7ed3\u6784\u3002\u6211\u4eec\u901a\u8fc7\u4e3a\u5185\u90e8\u9762\u548c\u8fb9\u754c\u9762\u5206\u522b\u8bbe\u7f6e\u66f4\u65b0\u6807\u5fd7\u6765\u505a\u5230\u8fd9\u4e00\u70b9\u3002\u5728\u8fb9\u754c\u9762\uff0c\u6211\u4eec\u9700\u8981\u51fd\u6570\u503c\u3001\u5b83\u4eec\u7684\u68af\u5ea6\u3001JxW\u503c\uff08\u7528\u4e8e\u79ef\u5206\uff09\u3001\u6cd5\u5411\u91cf\u548c\u6b63\u4ea4\u70b9\uff08\u7528\u4e8e\u8fb9\u754c\u6761\u4ef6\u7684\u8bc4\u4f30\uff09\uff0c\u800c\u5bf9\u4e8e\u5185\u90e8\u9762\uff0c\u6211\u4eec\u53ea\u9700\u8981\u5f62\u72b6\u51fd\u6570\u503c\u3001\u68af\u5ea6\u3001JxW\u503c\u548c\u6cd5\u5411\u91cf\u3002\u53ea\u8981`mapping_update_flags_inner_faces`\u6216`mapping_update_flags_boundary_faces`\u4e2d\u7684\u4e00\u4e2a\u4e0eUpdateFlags\u7684\u9ed8\u8ba4\u503c`update_default`\u4e0d\u540c\uff0cMatrixFree\u4e2d\u7684\u9762\u6570\u636e\u7ed3\u6784\u603b\u662f\u88ab\u5efa\u7acb\u7684\u3002\n\n  template <int dim, int fe_degree> \n  void LaplaceProblem<dim, fe_degree>::setup_system() \n  { \n    Timer time; \n    setup_time = 0; \n\n    system_matrix.clear(); \n    mg_matrices.clear_elements(); \n\n    dof_handler.distribute_dofs(fe); \n    dof_handler.distribute_mg_dofs(); \n\n    pcout << \"Number of degrees of freedom: \" << dof_handler.n_dofs() \n          << std::endl; \n\n    setup_time += time.wall_time(); \n    time_details << \"Distribute DoFs               \" << time.wall_time() << \" s\" \n                 << std::endl; \n    time.restart(); \n\n    AffineConstraints<double> dummy; \n    dummy.close(); \n\n    { \n      typename MatrixFree<dim, double>::AdditionalData additional_data; \n      additional_data.tasks_parallel_scheme = \n        MatrixFree<dim, double>::AdditionalData::none; \n      additional_data.mapping_update_flags = \n        (update_gradients | update_JxW_values | update_quadrature_points); \n      additional_data.mapping_update_flags_inner_faces = \n        (update_gradients | update_JxW_values | update_normal_vectors); \n      additional_data.mapping_update_flags_boundary_faces = \n        (update_gradients | update_JxW_values | update_normal_vectors | \n         update_quadrature_points); \n      const auto system_mf_storage = \n        std::make_shared<MatrixFree<dim, double>>(); \n      system_mf_storage->reinit( \n        mapping, dof_handler, dummy, QGauss<1>(fe.degree + 1), additional_data); \n      system_matrix.initialize(system_mf_storage); \n    } \n\n    system_matrix.initialize_dof_vector(solution); \n    system_matrix.initialize_dof_vector(system_rhs); \n\n    setup_time += time.wall_time(); \n    time_details << \"Setup matrix-free system      \" << time.wall_time() << \" s\" \n                 << std::endl; \n    time.restart(); \n\n    const unsigned int nlevels = triangulation.n_global_levels(); \n    mg_matrices.resize(0, nlevels - 1); \n\n    for (unsigned int level = 0; level < nlevels; ++level) \n      { \n        typename MatrixFree<dim, float>::AdditionalData additional_data; \n        additional_data.tasks_parallel_scheme = \n          MatrixFree<dim, float>::AdditionalData::none; \n        additional_data.mapping_update_flags = \n          (update_gradients | update_JxW_values); \n        additional_data.mapping_update_flags_inner_faces = \n          (update_gradients | update_JxW_values); \n        additional_data.mapping_update_flags_boundary_faces = \n          (update_gradients | update_JxW_values); \n        additional_data.mg_level = level; \n        const auto mg_mf_storage_level = \n          std::make_shared<MatrixFree<dim, float>>(); \n        mg_mf_storage_level->reinit(mapping, \n                                    dof_handler, \n                                    dummy, \n                                    QGauss<1>(fe.degree + 1), \n                                    additional_data); \n\n        mg_matrices[level].initialize(mg_mf_storage_level); \n      } \n    setup_time += time.wall_time(); \n    time_details << \"Setup matrix-free levels      \" << time.wall_time() << \" s\" \n                 << std::endl; \n  } \n\n// \u53f3\u624b\u8fb9\u7684\u8ba1\u7b97\u6bd4  step-37  \u4e2d\u7684\u8ba1\u7b97\u8981\u590d\u6742\u4e00\u4e9b\u3002\u73b0\u5728\u7684\u5355\u5143\u9879\u5305\u62ec\u5206\u6790\u89e3\u7684\u8d1f\u62c9\u666e\u62c9\u65af\uff0c`RightHandSide'\uff0c\u4e3a\u6b64\u6211\u4eec\u9700\u8981\u9996\u5148\u5c06VectorizedArray\u5b57\u6bb5\u7684Point\uff0c\u5373\u4e00\u6279\u70b9\uff0c\u901a\u8fc7\u5206\u522b\u8bc4\u4f30VectorizedArray\u4e2d\u7684\u6240\u6709\u901a\u9053\uff0c\u62c6\u6210\u4e00\u4e2a\u70b9\u3002\u8bf7\u8bb0\u4f4f\uff0c\u901a\u9053\u7684\u6570\u91cf\u53d6\u51b3\u4e8e\u786c\u4ef6\uff1b\u5bf9\u4e8e\u4e0d\u63d0\u4f9b\u77e2\u91cf\u5316\u7684\u7cfb\u7edf\uff08\u6216deal.II\u6ca1\u6709\u672c\u5f81\uff09\uff0c\u5b83\u53ef\u80fd\u662f1\uff0c\u4f46\u5728\u6700\u8fd1\u7684Intel\u67b6\u6784\u7684AVX-512\u4e0a\u4e5f\u53ef\u80fd\u662f8\u621616\u3002\n\n  template <int dim, int fe_degree> \n  void LaplaceProblem<dim, fe_degree>::compute_rhs() \n  { \n    Timer time; \n    system_rhs                          = 0; \n    const MatrixFree<dim, double> &data = *system_matrix.get_matrix_free(); \n    FEEvaluation<dim, fe_degree>   phi(data); \n    RightHandSide<dim>             rhs_func; \n    Solution<dim>                  exact_solution; \n    for (unsigned int cell = 0; cell < data.n_cell_batches(); ++cell) \n      { \n        phi.reinit(cell); \n        for (unsigned int q = 0; q < phi.n_q_points; ++q) \n          { \n            VectorizedArray<double> rhs_val = VectorizedArray<double>(); \n            Point<dim, VectorizedArray<double>> point_batch = \n              phi.quadrature_point(q); \n            for (unsigned int v = 0; v < VectorizedArray<double>::size(); ++v) \n              { \n                Point<dim> single_point; \n                for (unsigned int d = 0; d < dim; ++d) \n                  single_point[d] = point_batch[d][v]; \n                rhs_val[v] = rhs_func.value(single_point); \n              } \n            phi.submit_value(rhs_val, q); \n          } \n        phi.integrate_scatter(EvaluationFlags::values, system_rhs); \n      } \n\n// \u5176\u6b21\uff0c\u6211\u4eec\u8fd8\u9700\u8981\u5e94\u7528Dirichlet\u548cNeumann\u8fb9\u754c\u6761\u4ef6\u3002\u4e00\u65e6Dirichlet\u8fb9\u754c\u4e0a\u7684\u5916\u90e8\u6c42\u89e3\u503c $u^+ = -u^- + 2 g_\\text{D}$ \u548c $\\mathbf{n}^-\\cdot \\nabla u^+ = \\mathbf{n}^-\\cdot \\nabla u^-$ \u4ee5\u53caNeumann\u8fb9\u754c\u4e0a\u7684 $u^+=u^-$ \u548c $\\mathbf{n}^-\\cdot \\nabla u^+ = -\\mathbf{n}^-\\cdot \\nabla u^- + 2 g_\\text{N}$ \u88ab\u63d2\u5165\u5e76\u4ee5\u8fb9\u754c\u51fd\u6570 $g_\\text{D}$ \u548c $g_\\text{N}$ \u5c55\u5f00\uff0c\u8fd9\u4e2a\u51fd\u6570\u5c31\u662f\u5230\u51fd\u6570 `LaplaceOperator::apply_boundary()` \u6240\u7f3a\u7684\u90e8\u5206\u3002\u9700\u8981\u8bb0\u4f4f\u7684\u4e00\u70b9\u662f\uff0c\u6211\u4eec\u628a\u8fb9\u754c\u6761\u4ef6\u79fb\u5230\u53f3\u624b\u8fb9\uff0c\u6240\u4ee5\u7b26\u53f7\u4e0e\u6211\u4eec\u5f3a\u52a0\u5728\u89e3\u7684\u90e8\u5206\u76f8\u53cd\u3002\n\n// \u6211\u4eec\u53ef\u4ee5\u901a\u8fc7 MatrixFree::loop \u90e8\u5206\u53d1\u51fa\u5355\u5143\u683c\u548c\u8fb9\u754c\u90e8\u5206\uff0c\u4f46\u6211\u4eec\u9009\u62e9\u624b\u52a8\u5199\u51fa\u6240\u6709\u9762\u7684\u5b8c\u6574\u5faa\u73af\uff0c\u4ee5\u4e86\u89e3MatrixFree\u4e2d\u9762\u7684\u7d22\u5f15\u5e03\u5c40\u662f\u5982\u4f55\u8bbe\u7f6e\u7684\uff1a\u5185\u90e8\u9762\u548c\u8fb9\u754c\u9762\u90fd\u5171\u4eab\u7d22\u5f15\u8303\u56f4\uff0c\u6240\u6709\u6279\u6b21\u7684\u5185\u90e8\u9762\u7684\u6570\u5b57\u90fd\u6bd4\u6279\u6b21\u7684\u8fb9\u754c\u5355\u5143\u683c\u4f4e\u3002\u4e24\u79cd\u53d8\u4f53\u7684\u5355\u4e00\u7d22\u5f15\u4f7f\u6211\u4eec\u53ef\u4ee5\u5f88\u5bb9\u6613\u5730\u5728\u4e24\u79cd\u60c5\u51b5\u4e0b\u4f7f\u7528\u76f8\u540c\u7684\u6570\u636e\u7ed3\u6784FEFaceEvaluation\uff0c\u5b83\u9644\u7740\u5728\u540c\u4e00\u4e2a\u6570\u636e\u57df\u4e0a\uff0c\u53ea\u662f\u4f4d\u7f6e\u4e0d\u540c\u3002\u5185\u5c42\u9762\u7684\u6279\u6b21\uff08\u5176\u4e2d\u4e00\u4e2a\u6279\u6b21\u662f\u7531\u4e8e\u5c06\u51e0\u4e2a\u9762\u5408\u5e76\u6210\u4e00\u4e2a\u9762\u8fdb\u884c\u77e2\u91cf\u5316\uff09\u7684\u6570\u91cf\u7531 MatrixFree::n_inner_face_batches(), \u7ed9\u51fa\uff0c\u800c\u8fb9\u754c\u9762\u7684\u6279\u6b21\u6570\u91cf\u7531 MatrixFree::n_boundary_face_batches(). \u7ed9\u51fa\u3002\n    FEFaceEvaluation<dim, fe_degree> phi_face(data, true); \n    for (unsigned int face = data.n_inner_face_batches(); \n         face < data.n_inner_face_batches() + data.n_boundary_face_batches(); \n         ++face) \n      { \n        phi_face.reinit(face); \n\n        const VectorizedArray<double> inverse_length_normal_to_face = \n          std::abs((phi_face.get_normal_vector(0) * \n                    phi_face.inverse_jacobian(0))[dim - 1]); \n        const VectorizedArray<double> sigma = \n          inverse_length_normal_to_face * system_matrix.get_penalty_factor(); \n\n        for (unsigned int q = 0; q < phi_face.n_q_points; ++q) \n          { \n            VectorizedArray<double> test_value = VectorizedArray<double>(), \n                                    test_normal_derivative = \n                                      VectorizedArray<double>(); \n            Point<dim, VectorizedArray<double>> point_batch = \n              phi_face.quadrature_point(q); \n\n            for (unsigned int v = 0; v < VectorizedArray<double>::size(); ++v) \n              { \n                Point<dim> single_point; \n                for (unsigned int d = 0; d < dim; ++d) \n                  single_point[d] = point_batch[d][v]; \n\n// MatrixFree\u7c7b\u8ba9\u6211\u4eec\u67e5\u8be2\u5f53\u524d\u9762\u6279\u7684\u8fb9\u754c_id\u3002\u8bf7\u8bb0\u4f4f\uff0cMatrixFree\u4e3a\u77e2\u91cf\u5316\u8bbe\u7f6e\u4e86\u6279\u6b21\uff0c\u4f7f\u4e00\u4e2a\u6279\u6b21\u4e2d\u7684\u6240\u6709\u9762\u5b54\u90fd\u6709\u76f8\u540c\u7684\u5c5e\u6027\uff0c\u5176\u4e2d\u5305\u62ec\u5b83\u4eec\u7684`\u8fb9\u754c_id'\u3002\u56e0\u6b64\uff0c\u6211\u4eec\u53ef\u4ee5\u5728\u8fd9\u91cc\u4e3a\u5f53\u524d\u9762\u7684\u7d22\u5f15`face`\u67e5\u8be2\u8be5id\uff0c\u5e76\u5728Dirichlet\u60c5\u51b5\u4e0b\uff08\u6211\u4eec\u5728\u51fd\u6570\u503c\u4e0a\u6dfb\u52a0\u4e00\u4e9b\u4e1c\u897f\uff09\u6216Neumann\u60c5\u51b5\u4e0b\uff08\u6211\u4eec\u5728\u6cd5\u7ebf\u5bfc\u6570\u4e0a\u6dfb\u52a0\u4e00\u4e9b\u4e1c\u897f\uff09\u65bd\u52a0\u3002\n\n                if (data.get_boundary_id(face) == 0) \n                  test_value[v] = 2.0 * exact_solution.value(single_point); \n                else \n                  { \n                    Tensor<1, dim> normal; \n                    for (unsigned int d = 0; d < dim; ++d) \n                      normal[d] = phi_face.get_normal_vector(q)[d][v]; \n                    test_normal_derivative[v] = \n                      -normal * exact_solution.gradient(single_point); \n                  } \n              } \n            phi_face.submit_value(test_value * sigma - test_normal_derivative, \n                                  q); \n            phi_face.submit_normal_derivative(-0.5 * test_value, q); \n          } \n        phi_face.integrate_scatter(EvaluationFlags::values | \n                                     EvaluationFlags::gradients, \n                                   system_rhs); \n      } \n\n// \u7531\u4e8e\u6211\u4eec\u624b\u52a8\u8fd0\u884c\u4e86\u5355\u5143\u683c\u7684\u5faa\u73af\uff0c\u800c\u4e0d\u662f\u4f7f\u7528 MatrixFree::loop(), \uff0c\u6211\u4eec\u4e0d\u80fd\u5fd8\u8bb0\u4e0eMPI\u8fdb\u884c\u6570\u636e\u4ea4\u6362\u3002\n\n// \u6216\u8005\u8bf4\uff0c\u5bf9\u4e8eDG\u5143\u7d20\u6765\u8bf4\uff0c\u6211\u4eec\u4e0d\u9700\u8981\u8fd9\u6837\u505a\uff0c\u56e0\u4e3a\u6bcf\u4e2a\u5355\u5143\u90fd\u6709\u81ea\u5df1\u7684\u81ea\u7531\u5ea6\uff0c\u5355\u5143\u548c\u8fb9\u754c\u79ef\u5206\u53ea\u5bf9\u672c\u5730\u62e5\u6709\u7684\u5355\u5143\u8fdb\u884c\u8bc4\u4f30\u3002\u4e0e\u76f8\u90bb\u5b50\u57df\u7684\u8026\u5408\u53ea\u901a\u8fc7\u5185\u8868\u9762\u79ef\u5206\u6765\u5b9e\u73b0\uff0c\u6211\u4eec\u5728\u8fd9\u91cc\u6ca1\u6709\u505a\u8fd9\u4e2a\u3002\u4e5f\u5c31\u662f\u8bf4\uff0c\u5728\u8fd9\u91cc\u8c03\u7528\u8fd9\u4e2a\u51fd\u6570\u5e76\u6ca1\u6709\u4ec0\u4e48\u574f\u5904\uff0c\u6240\u4ee5\u6211\u4eec\u8fd9\u6837\u505a\u662f\u4e3a\u4e86\u63d0\u9192\u5927\u5bb6\u5728 MatrixFree::loop(). \u91cc\u9762\u53d1\u751f\u4e86\u4ec0\u4e48\u3002\n    system_rhs.compress(VectorOperation::add); \n    setup_time += time.wall_time(); \n    time_details << \"Compute right hand side       \" << time.wall_time() \n                 << \" s\\n\"; \n  } \n\n// `solve()`\u51fd\u6570\u51e0\u4e4e\u9010\u5b57\u590d\u5236\u81ea  step-37  \u3002\u6211\u4eec\u8bbe\u7f6e\u4e86\u76f8\u540c\u7684\u591a\u7f51\u683c\u6210\u5206\uff0c\u5373\u6c34\u5e73\u8f6c\u79fb\u3001\u5e73\u6ed1\u5668\u548c\u7c97\u7565\u7684\u7f51\u683c\u6c42\u89e3\u5668\u3002\u552f\u4e00\u4e0d\u540c\u7684\u662f\uff0c\u6211\u4eec\u6ca1\u6709\u4f7f\u7528\u62c9\u666e\u62c9\u65af\u7684\u5bf9\u89d2\u7ebf\u4f5c\u4e3a\u7528\u4e8e\u5e73\u6ed1\u7684\u5207\u6bd4\u96ea\u592b\u8fed\u4ee3\u7684\u9884\u5904\u7406\uff0c\u800c\u662f\u4f7f\u7528\u6211\u4eec\u65b0\u89e3\u51b3\u7684\u7c7b`%PreconditionBlockJacobi`\u3002\u4e0d\u8fc7\uff0c\u673a\u5236\u662f\u4e00\u6837\u7684\u3002\n\n  template <int dim, int fe_degree> \n  void LaplaceProblem<dim, fe_degree>::solve() \n  { \n    Timer                            time; \n    MGTransferMatrixFree<dim, float> mg_transfer; \n    mg_transfer.build(dof_handler); \n    setup_time += time.wall_time(); \n    time_details << \"MG build transfer time        \" << time.wall_time() \n                 << \" s\\n\"; \n    time.restart(); \n\n    using SmootherType = \n      PreconditionChebyshev<LevelMatrixType, \n                            LinearAlgebra::distributed::Vector<float>, \n                            PreconditionBlockJacobi<dim, fe_degree, float>>; \n    mg::SmootherRelaxation<SmootherType, \n                           LinearAlgebra::distributed::Vector<float>> \n                                                         mg_smoother; \n    MGLevelObject<typename SmootherType::AdditionalData> smoother_data; \n    smoother_data.resize(0, triangulation.n_global_levels() - 1); \n    for (unsigned int level = 0; level < triangulation.n_global_levels(); \n         ++level) \n      { \n        if (level > 0) \n          { \n            smoother_data[level].smoothing_range     = 15.; \n            smoother_data[level].degree              = 3; \n            smoother_data[level].eig_cg_n_iterations = 10; \n          } \n        else \n          { \n            smoother_data[0].smoothing_range = 2e-2; \n            smoother_data[0].degree          = numbers::invalid_unsigned_int; \n            smoother_data[0].eig_cg_n_iterations = mg_matrices[0].m(); \n          } \n        smoother_data[level].preconditioner = \n          std::make_shared<PreconditionBlockJacobi<dim, fe_degree, float>>(); \n        smoother_data[level].preconditioner->initialize(mg_matrices[level]); \n      } \n    mg_smoother.initialize(mg_matrices, smoother_data); \n\n    MGCoarseGridApplySmoother<LinearAlgebra::distributed::Vector<float>> \n      mg_coarse; \n    mg_coarse.initialize(mg_smoother); \n\n    mg::Matrix<LinearAlgebra::distributed::Vector<float>> mg_matrix( \n      mg_matrices); \n\n    Multigrid<LinearAlgebra::distributed::Vector<float>> mg( \n      mg_matrix, mg_coarse, mg_transfer, mg_smoother, mg_smoother); \n\n    PreconditionMG<dim, \n                   LinearAlgebra::distributed::Vector<float>, \n                   MGTransferMatrixFree<dim, float>> \n      preconditioner(dof_handler, mg, mg_transfer); \n\n    SolverControl solver_control(10000, 1e-12 * system_rhs.l2_norm()); \n    SolverCG<LinearAlgebra::distributed::Vector<double>> cg(solver_control); \n    setup_time += time.wall_time(); \n    time_details << \"MG build smoother time        \" << time.wall_time() \n                 << \"s\\n\"; \n    pcout << \"Total setup time              \" << setup_time << \" s\\n\"; \n\n    time.reset(); \n    time.start(); \n    cg.solve(system_matrix, solution, system_rhs, preconditioner); \n\n    pcout << \"Time solve (\" << solver_control.last_step() << \" iterations)    \" \n          << time.wall_time() << \" s\" << std::endl; \n  } \n\n// \u7531\u4e8e\u6211\u4eec\u5df2\u7ecf\u7528\u5206\u6790\u6cd5\u89e3\u51b3\u4e86\u4e00\u4e2a\u95ee\u9898\uff0c\u6211\u4eec\u60f3\u901a\u8fc7\u8ba1\u7b97\u6570\u503c\u7ed3\u679c\u4e0e\u5206\u6790\u6cd5\u7684L2\u8bef\u5dee\u6765\u9a8c\u8bc1\u6211\u4eec\u5b9e\u73b0\u7684\u6b63\u786e\u6027\u3002\n\n  template <int dim, int fe_degree> \n  void LaplaceProblem<dim, fe_degree>::analyze_results() const \n  { \n    Vector<float> error_per_cell(triangulation.n_active_cells()); \n    VectorTools::integrate_difference(mapping, \n                                      dof_handler, \n                                      solution, \n                                      Solution<dim>(), \n                                      error_per_cell, \n                                      QGauss<dim>(fe.degree + 2), \n                                      VectorTools::L2_norm); \n    pcout << \"Verification via L2 error:    \" \n          << std::sqrt( \n               Utilities::MPI::sum(error_per_cell.norm_sqr(), MPI_COMM_WORLD)) \n          << std::endl; \n  } \n\n// `run()`\u51fd\u6570\u8bbe\u7f6e\u4e86\u521d\u59cb\u7f51\u683c\uff0c\u7136\u540e\u4ee5\u5e38\u89c4\u65b9\u5f0f\u8fd0\u884c\u591a\u7f51\u683c\u7a0b\u5e8f\u3002\u4f5c\u4e3a\u4e00\u4e2a\u57df\uff0c\u6211\u4eec\u9009\u62e9\u4e00\u4e2a\u77e9\u5f62\uff0c\u5728 $x$ -\u65b9\u5411\u4e0a\u6709\u5468\u671f\u6027\u7684\u8fb9\u754c\u6761\u4ef6\uff0c\u5728 $y$ \u65b9\u5411\u4e0a\u7684\u6b63\u9762\uff08\u5373\u7d22\u5f15\u53f7\u4e3a2\u7684\u9762\uff0c\u8fb9\u754cid\u7b49\u4e8e0\uff09\u6709\u8fea\u91cc\u5e0c\u7279\u6761\u4ef6\uff0c\u5728\u80cc\u9762\u4ee5\u53ca $z$ \u65b9\u5411\u4e0a\u7684\u4e24\u4e2a\u9762\u4e3a\u4e09\u7ef4\u60c5\u51b5\uff08\u8fb9\u754cid\u7b49\u4e8e1\uff09\u6709\u7ebd\u66fc\u6761\u4ef6\u3002\u4e0e $y$ \u548c $z$ \u65b9\u5411\u76f8\u6bd4\uff0c $x$ \u65b9\u5411\u7684\u57df\u7684\u8303\u56f4\u6709\u4e9b\u4e0d\u540c\uff08\u8003\u8651\u5230 \"\u89e3\u51b3\u65b9\u6848 \"\u7684\u5b9a\u4e49\uff0c\u6211\u4eec\u5e0c\u671b\u5728\u8fd9\u91cc\u5b9e\u73b0\u5468\u671f\u6027\u7684\u89e3\u51b3\u65b9\u6848\uff09\u3002\n\n  template <int dim, int fe_degree> \n  void LaplaceProblem<dim, fe_degree>::run() \n  { \n    const unsigned int n_ranks = \n      Utilities::MPI::n_mpi_processes(MPI_COMM_WORLD); \n    pcout << \"Running with \" << n_ranks << \" MPI process\" \n          << (n_ranks > 1 ? \"es\" : \"\") << \", element \" << fe.get_name() \n          << std::endl \n          << std::endl; \n    for (unsigned int cycle = 0; cycle < 9 - dim; ++cycle) \n      { \n        pcout << \"Cycle \" << cycle << std::endl; \n\n        if (cycle == 0) \n          { \n            Point<dim> upper_right; \n            upper_right[0] = 2.5; \n            for (unsigned int d = 1; d < dim; ++d) \n              upper_right[d] = 2.8; \n            GridGenerator::hyper_rectangle(triangulation, \n                                           Point<dim>(), \n                                           upper_right); \n            triangulation.begin_active()->face(0)->set_boundary_id(10); \n            triangulation.begin_active()->face(1)->set_boundary_id(11); \n            triangulation.begin_active()->face(2)->set_boundary_id(0); \n            for (unsigned int f = 3; \n                 f < triangulation.begin_active()->n_faces(); \n                 ++f) \n              triangulation.begin_active()->face(f)->set_boundary_id(1); \n\n            std::vector<GridTools::PeriodicFacePair< \n              typename Triangulation<dim>::cell_iterator>> \n              periodic_faces; \n            GridTools::collect_periodic_faces( \n              triangulation, 10, 11, 0, periodic_faces); \n            triangulation.add_periodicity(periodic_faces); \n\n            triangulation.refine_global(6 - 2 * dim); \n          } \n        triangulation.refine_global(1); \n        setup_system(); \n        compute_rhs(); \n        solve(); \n        analyze_results(); \n        pcout << std::endl; \n      }; \n  } \n} // namespace Step59 \n\n// `main()`\u51fd\u6570\u4e2d\u6ca1\u6709\u4efb\u4f55\u610f\u5916\u3002\u6211\u4eec\u901a\u8fc7`MPI_Init()`\u7c7b\u8c03\u7528`MPI_InitFinalize`\uff0c\u4f20\u5165\u6587\u4ef6\u9876\u90e8\u8bbe\u7f6e\u7684\u5173\u4e8e\u7ef4\u5ea6\u548c\u5ea6\u7684\u4e24\u4e2a\u53c2\u6570\uff0c\u7136\u540e\u8fd0\u884c\u62c9\u666e\u62c9\u65af\u95ee\u9898\u3002\n\nint main(int argc, char *argv[]) \n{ \n  try \n    { \n      using namespace Step59; \n\n      Utilities::MPI::MPI_InitFinalize mpi_init(argc, argv, 1); \n\n      LaplaceProblem<dimension, degree_finite_element> laplace_problem; \n      laplace_problem.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      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": "c221de0015bf9f37c9742da3b498920d0b320e9e", "size": 45582, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-59/step-59.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-59/step-59.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-59/step-59.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": 45.7191574724, "max_line_length": 809, "alphanum_fraction": 0.6341977096, "num_tokens": 16820, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583376458152, "lm_q2_score": 0.6926419704455589, "lm_q1q2_score": 0.48204995433501296}}
{"text": "#ifndef KRBINAVERAGER_H\n#define KRBINAVERAGER_H\n\n#include <Eigen/Dense>\n#include <math.h>\n\n#include \"KRAverager.hpp\"\n\n/**\n * @class KRBinAverager\n */\nclass KRBinAverager {\n    public:\n        /**\n         * @param max\n         * @param min\n         * @param bin\n         */\n        KRBinAverager(const double max, const double min, const double bin);\n\n        /**\n         * @param k\n         * @param r\n         */\n        void add_force_constant_tuple(double k, double r);\n\n        /**\n         * @return rs\n         */\n        Eigen::VectorXd get_rs() const;\n\n        /**\n         * @return ks\n         */\n        Eigen::VectorXd get_ks() const;\n\n        /**\n         * @return error 2s\n         */\n        Eigen::VectorXd get_error2s() const;\n\n        /**\n         * @return errors\n         */\n        Eigen::VectorXd get_errors() const;\n    private:\n        std::vector<KRAverager> kr_averagers;\n        Eigen::VectorXd rs;\n\n        int number_of_bins;\n        double min;\n        double max;\n        double bin;\n};\n\n#endif\n\n// vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4\n", "meta": {"hexsha": "36c65c786da3f93004bb5d1b3d84855aa8681a72", "size": 1085, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/KRBinAverager.hpp", "max_stars_repo_name": "AFriemann/LowCarb", "max_stars_repo_head_hexsha": "073e036a5fd6787943c4cbd76ab388dbd830e7d3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/KRBinAverager.hpp", "max_issues_repo_name": "AFriemann/LowCarb", "max_issues_repo_head_hexsha": "073e036a5fd6787943c4cbd76ab388dbd830e7d3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-12-15T13:57:26.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-15T13:57:26.000Z", "max_forks_repo_path": "src/KRBinAverager.hpp", "max_forks_repo_name": "AFriemann/LowCarb", "max_forks_repo_head_hexsha": "073e036a5fd6787943c4cbd76ab388dbd830e7d3", "max_forks_repo_licenses": ["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.3898305085, "max_line_length": 76, "alphanum_fraction": 0.5133640553, "num_tokens": 269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.6893056231680121, "lm_q1q2_score": 0.482000004460895}}
{"text": "#include \"graph.hpp\"\n#include \"algorithms.hpp\"\n\n#include <set>\n#include <sstream>\n#include <tuple>\n#include <vector>\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_ALTERNATIVE_INIT_API\n#define BOOST_TEST_MAIN\n#include <boost/test/unit_test.hpp>\n\nusing namespace graph;\n\nBOOST_AUTO_TEST_CASE(empty_matrix_graph_creation) {\n\tusing Graph = matrix::Graph<NoProperty, NoProperty>;\n\tGraph myGraph;\n\tBOOST_CHECK_EQUAL(myGraph.getConnections().size(), 0);\n}\n\nBOOST_AUTO_TEST_CASE(matrix_graph_with_vertices_and_edges_creation) {\n\tusing Graph = matrix::Graph<NoProperty, NoProperty>;\n\tusing Edge  = Graph::Edge_t;\n\n\t{\n\t\tGraph myGraph(Edge{\"0\", \"0\"});\n\t\tBOOST_CHECK_EQUAL(myGraph.getVerticesCount(), 1);\n\t\tBOOST_CHECK_EQUAL(myGraph.getEdgesCount(), 1);\n\t\tBOOST_CHECK_EQUAL(myGraph.getConnections().size(), 1);\n\t\tBOOST_CHECK_EQUAL(myGraph.getConnections()[0].size(), 1);\n\t\tBOOST_CHECK_EQUAL(myGraph.getConnections()[0][0], true);\n\t}\n\n\t{\n\t\tstd::set<std::pair<std::string, std::string>> arcs{\n\t\t        {\"1\", \"3\"}, {\"1\", \"4\"}, {\"2\", \"7\"}, {\"8\", \"3\"}};\n\t\tGraph myGraph(Edge{\"1\", \"3\"}, Edge{\"1\", \"4\"}, Edge{\"2\", \"7\"}, Edge{\"8\", \"3\"});\n\n\t\tBOOST_CHECK_EQUAL(myGraph.getVerticesCount(), 6);\n\t\tBOOST_CHECK_EQUAL(myGraph.getEdgesCount(), 4);\n\t\tBOOST_CHECK_EQUAL(myGraph.getConnections().size(), 6);\n\t\tBOOST_CHECK_EQUAL(myGraph.getConnections()[0].size(), 6);\n\n\t\tfor(auto const i : {\"1\", \"2\", \"3\", \"4\", \"7\", \"8\"}) {\n\t\t\tfor(auto const j : {\"1\", \"2\", \"3\", \"4\", \"7\", \"8\"}) {\n\t\t\t\tsize_t beginId = myGraph.getId(i), endId = myGraph.getId(j);\n\t\t\t\tif(arcs.find(std::pair<std::string, std::string>{i, j}) != arcs.end()) {\n\t\t\t\t\tBOOST_CHECK_EQUAL(myGraph.getConnections()[beginId][endId], true);\n\t\t\t\t} else {\n\t\t\t\t\tBOOST_CHECK_EQUAL(myGraph.getConnections()[beginId][endId], false);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n}\n\nBOOST_AUTO_TEST_CASE(matrix_graph_with_initializer_list) {\n\tusing Graph = matrix::Graph<NoProperty, NoProperty>;\n\n\t{\n\t\tGraph myGraph{{\"0\", \"0\"}};\n\t\tBOOST_CHECK_EQUAL(myGraph.getVerticesCount(), 1);\n\t\tBOOST_CHECK_EQUAL(myGraph.getEdgesCount(), 1);\n\t\tBOOST_CHECK_EQUAL(myGraph.getConnections().size(), 1);\n\t\tBOOST_CHECK_EQUAL(myGraph.getConnections()[0].size(), 1);\n\t\tBOOST_CHECK_EQUAL(myGraph.getConnections()[0][0], true);\n\t}\n\n\t{\n\t\tstd::initializer_list<Graph::Edge_t> arcs{{\"1\", \"3\"}, {\"1\", \"4\"}, {\"2\", \"7\"}, {\"8\", \"3\"}};\n\t\tGraph myGraph(arcs);\n\t\tBOOST_CHECK_EQUAL(myGraph.getVerticesCount(), 6);\n\t\tBOOST_CHECK_EQUAL(myGraph.getEdgesCount(), 4);\n\t\tBOOST_CHECK_EQUAL(myGraph.getConnections().size(), 6);\n\t\tBOOST_CHECK_EQUAL(myGraph.getConnections()[0].size(), 6);\n\n\t\tBOOST_CHECK_EQUAL(myGraph.getConnections()[0][0], false);\n\n\t\tfor(const auto& arc : arcs) {\n\t\t\tsize_t beginId = myGraph.getId(std::get<0>(arc)),\n\t\t\t       endId = myGraph.getId(std::get<1>(arc));\n\t\t\tBOOST_CHECK_EQUAL(myGraph.getConnections()[beginId][endId], true);\n\t\t}\n\t}\n}\n\nBOOST_AUTO_TEST_CASE(matrix_graph_get_id) {\n\tusing Graph = matrix::Graph<NoProperty, NoProperty>;\n\n\tGraph myGraph{{\"6\", \"5\"}, {\"4\", \"3\"}, {\"2\", \"1\"}};\n\n\tBOOST_CHECK_EQUAL(myGraph.getId(\"1\"), 5);\n\tBOOST_CHECK_EQUAL(myGraph.getId(\"2\"), 4);\n\tBOOST_CHECK_EQUAL(myGraph.getId(\"3\"), 3);\n\tBOOST_CHECK_EQUAL(myGraph.getId(\"4\"), 2);\n\tBOOST_CHECK_EQUAL(myGraph.getId(\"5\"), 1);\n\tBOOST_CHECK_EQUAL(myGraph.getId(\"6\"), 0);\n\tBOOST_CHECK_EQUAL(myGraph.getVerticesCount(), 6);\n\tBOOST_CHECK_EQUAL(myGraph.getId(\"7\"), 6);\n\tBOOST_CHECK_EQUAL(myGraph.getVerticesCount(), 7);\n\tBOOST_CHECK_EQUAL(myGraph.getId(\"8\"), 7);\n\tBOOST_CHECK_EQUAL(myGraph.getVerticesCount(), 8);\n}\n\nBOOST_AUTO_TEST_CASE(matrix_graph_const_get_id) {\n\tusing Graph = matrix::Graph<NoProperty, NoProperty>;\n\n\tconst Graph myGraph{{\"6\", \"5\"}, {\"4\", \"3\"}, {\"2\", \"1\"}};\n\n\tBOOST_CHECK_EQUAL(myGraph.getId(\"1\"), 5);\n\tBOOST_CHECK_EQUAL(myGraph.getId(\"2\"), 4);\n\tBOOST_CHECK_EQUAL(myGraph.getId(\"3\"), 3);\n\tBOOST_CHECK_EQUAL(myGraph.getId(\"4\"), 2);\n\tBOOST_CHECK_EQUAL(myGraph.getId(\"5\"), 1);\n\tBOOST_CHECK_EQUAL(myGraph.getId(\"6\"), 0);\n\tBOOST_CHECK_THROW(myGraph.getId(\"7\"), std::out_of_range);\n\tBOOST_CHECK_THROW(myGraph.getId(\"8\"), std::out_of_range);\n}\n\nBOOST_AUTO_TEST_CASE(matrix_graph_subscript_operator) {\n\tusing Graph = matrix::Graph<NoProperty, NoProperty>;\n\tusing Node = Graph::Node_t;\n\n\tGraph myGraph{{\"1\", \"2\"}, {\"3\", \"4\"}, {\"5\", \"6\"}};\n\tNode firstNode = myGraph[\"1\"];\n\n\tBOOST_CHECK(myGraph.getConnections()[0] == firstNode.getConnections());\n}\n\nBOOST_AUTO_TEST_CASE(matrix_graph_const_subscript_operator) {\n\tusing Graph = matrix::Graph<NoProperty, NoProperty>;\n\tusing Node = Graph::ConstNode_t;\n\n\tconst Graph myGraph{{\"1\", \"2\"}, {\"3\", \"4\"}, {\"5\", \"6\"}};\n\tNode firstNode = myGraph[\"1\"];\n\n\tBOOST_CHECK(myGraph.getConnections()[0] == firstNode.getConnections());\n}\n\nBOOST_AUTO_TEST_CASE(matrix_graph_begin) {\n\tusing Graph = matrix::Graph<NoProperty, NoProperty>;\n\tusing Node = Graph::Node_t;\n\n\tGraph myGraph{{\"1\", \"2\"}, {\"3\", \"4\"}, {\"5\", \"6\"}};\n\tNode firstNode = myGraph[\"1\"];\n\n\tBOOST_CHECK(myGraph.begin() == firstNode);\n}\n\nBOOST_AUTO_TEST_CASE(matrix_graph_const_begin) {\n\tusing Graph = matrix::Graph<NoProperty, NoProperty>;\n\tusing Node = Graph::ConstNode_t;\n\n\tconst Graph myGraph{{\"1\", \"2\"}, {\"3\", \"4\"}, {\"5\", \"6\"}};\n\tNode firstNode = myGraph[\"1\"];\n\n\tBOOST_CHECK(myGraph.begin() == firstNode);\n}\n\nBOOST_AUTO_TEST_CASE(matrix_graph_equal_to_operator) {\n\tusing Graph = matrix::Graph<NoProperty, NoProperty>;\n\n\tGraph myGraph{{\"6\", \"5\"}, {\"4\", \"3\"}, {\"2\", \"1\"}},\n\t\t    sameGraph{{\"4\", \"3\"}, {\"6\", \"5\"}, {\"2\", \"1\"}},\n\t\t    differentEdges{{\"4\", \"3\"}, {\"6\", \"1\"}, {\"2\", \"5\"}},\n\t\t    differentNodeCount{{\"5\", \"3\"}, {\"6\", \"5\"}, {\"2\", \"0\"}},\n\t\t    differentNodeNames{{\"a\", \"b\"}, {\"c\", \"d\"}, {\"e\", \"f\"}};\n\n\tBOOST_CHECK(myGraph == sameGraph);\n\tBOOST_CHECK(!(myGraph == differentEdges));\n\tBOOST_CHECK(!(myGraph == differentNodeCount));\n\tBOOST_CHECK(!(myGraph == differentNodeNames));\n}\n\nBOOST_AUTO_TEST_CASE(matrix_graph_not_equal_to_operator) {\n\tusing Graph = matrix::Graph<NoProperty, NoProperty>;\n\n\tGraph myGraph{{\"6\", \"5\"}, {\"4\", \"3\"}, {\"2\", \"1\"}},\n\t\t    sameGraph{{\"4\", \"3\"}, {\"6\", \"5\"}, {\"2\", \"1\"}},\n\t\t    differentEdges{{\"4\", \"3\"}, {\"6\", \"1\"}, {\"2\", \"5\"}},\n\t\t    differentNodeCount{{\"5\", \"3\"}, {\"6\", \"5\"}, {\"2\", \"0\"}},\n\t\t    differentNodeNames{{\"a\", \"b\"}, {\"c\", \"d\"}, {\"e\", \"f\"}};\n\n\tBOOST_CHECK(!(myGraph != sameGraph));\n\tBOOST_CHECK(myGraph != differentEdges);\n\tBOOST_CHECK(myGraph != differentNodeCount);\n\tBOOST_CHECK(myGraph != differentNodeNames);\n}\n\nBOOST_AUTO_TEST_CASE(matrix_graph_has_node) {\n\tusing Graph = matrix::Graph<WeightedProperty, NoProperty>;\n\n\tGraph myGraph{{\"6\", \"5\"}, {\"4\", \"3\"}, {\"2\", \"1\"}};\n\n\tBOOST_CHECK(myGraph.hasNode(\"6\"));\n\tBOOST_CHECK(myGraph.hasNode(\"5\"));\n\tBOOST_CHECK(myGraph.hasNode(\"4\"));\n\tBOOST_CHECK(myGraph.hasNode(\"3\"));\n\tBOOST_CHECK(myGraph.hasNode(\"2\"));\n\tBOOST_CHECK(myGraph.hasNode(\"1\"));\n\n\tBOOST_CHECK(!myGraph.hasNode(\"7\"));\n\tBOOST_CHECK(!myGraph.hasNode(\"42\"));\n\tBOOST_CHECK(!myGraph.hasNode(\"1337\"));\n}\n\nBOOST_AUTO_TEST_CASE(matrix_graph_add_node) {\n\tusing Graph = matrix::Graph<WeightedProperty, NoProperty>;\n\n\tGraph myGraph{{\"6\", \"5\"}, {\"4\", \"3\"}, {\"2\", \"1\"}};\n\n\tmyGraph.addNode(\"Hello\");\n\tBOOST_CHECK_EQUAL(myGraph.getVerticesCount(), 7);\n\tBOOST_CHECK_EQUAL(myGraph[\"Hello\"].getProperty().weight, 0);\n\tmyGraph.addNode(\"World\", {5});\n\tBOOST_CHECK_EQUAL(myGraph.getVerticesCount(), 8);\n\tBOOST_CHECK_EQUAL(myGraph[\"World\"].getProperty().weight, 5);\n}\n\nBOOST_AUTO_TEST_CASE(matrix_graph_remove_node) {\n\tusing Graph = matrix::Graph<WeightedProperty, NoProperty>;\n\tusing ConstNode = Graph::ConstNode_t;\n\n\tGraph myGraph{{\"6\", \"5\"}, {\"4\", \"3\"}, {\"2\", \"1\"}, {\"5\", \"6\"}};\n\n\tBOOST_CHECK_EQUAL(myGraph.getVerticesCount(), 6);\n\tmyGraph.removeNode(myGraph[\"6\"]);\n\tBOOST_CHECK_EQUAL(myGraph.getVerticesCount(), 5);\n\tBOOST_CHECK(!myGraph.hasNode(\"6\"));\n\n\tstd::ostringstream result;\n\tstd::string expected = \"2->1, 4->3, \";\n\tmyGraph.eachEdges([&result](ConstNode begin, ConstNode end) {\n\t\tresult << begin.getName() << \"->\" << end.getName() << \", \";\n\t});\n\n\tBOOST_CHECK_EQUAL(result.str(), expected);\n}\n\nBOOST_AUTO_TEST_CASE(matrix_graph_has_edge) {\n\tusing Graph = matrix::Graph<NoProperty, WeightedProperty>;\n\n\tGraph myGraph{{\"6\", \"5\"}, {\"4\", \"3\"}, {\"2\", \"1\"}};\n\n\tBOOST_CHECK(myGraph.hasEdge(myGraph[\"6\"], myGraph[\"5\"]));\n\tBOOST_CHECK(myGraph.hasEdge(myGraph[\"4\"], myGraph[\"3\"]));\n\tBOOST_CHECK(myGraph.hasEdge(myGraph[\"2\"], myGraph[\"1\"]));\n\n\tBOOST_CHECK(!myGraph.hasEdge(myGraph[\"1\"], myGraph[\"2\"]));\n\tBOOST_CHECK(!myGraph.hasEdge(myGraph[\"1\"], myGraph[\"3\"]));\n\tBOOST_CHECK(!myGraph.hasEdge(myGraph[\"6\"], myGraph[\"4\"]));\n}\n\nBOOST_AUTO_TEST_CASE(matrix_graph_add_edges) {\n\tusing Graph = matrix::Graph<NoProperty, WeightedProperty>;\n\tusing Edge  = Graph::Edge_t;\n\n\tGraph myGraph{{\"6\", \"5\"}, {\"4\", \"3\"}, {\"2\", \"1\"}};\n\n\tmyGraph.addEdges({\"Hello\", \"World\"});\n\tBOOST_CHECK_EQUAL(myGraph.getEdgesCount(), 4);\n\tBOOST_CHECK_EQUAL(myGraph.getVerticesCount(), 8);\n\tBOOST_CHECK_EQUAL(myGraph.getEdgeProperty(myGraph[\"Hello\"], myGraph[\"World\"]).weight, 0);\n\n\tmyGraph.addEdges({\"World\", \"Hello\", WeightedProperty{5}});\n\tBOOST_CHECK_EQUAL(myGraph.getEdgesCount(), 5);\n\tBOOST_CHECK_EQUAL(myGraph.getVerticesCount(), 8);\n\tBOOST_CHECK_EQUAL(myGraph.getEdgeProperty(myGraph[\"World\"], myGraph[\"Hello\"]).weight, 5);\n\n\tmyGraph.addEdges(Edge{\"Goodbye\", \"World\", WeightedProperty{5}}, Edge{\"World\", \"Goodbye\"});\n\tBOOST_CHECK_EQUAL(myGraph.getEdgesCount(), 7);\n\tBOOST_CHECK_EQUAL(myGraph.getVerticesCount(), 9);\n\tBOOST_CHECK_EQUAL(myGraph.getEdgeProperty(myGraph[\"Goodbye\"], myGraph[\"World\"]).weight, 5);\n\tBOOST_CHECK_EQUAL(myGraph.getEdgeProperty(myGraph[\"World\"], myGraph[\"Goodbye\"]).weight, 0);\n\n\tmyGraph.addEdges({{\"foo\", \"bar\", {5}}, {\"bar\", \"foo\"}});\n\tBOOST_CHECK_EQUAL(myGraph.getEdgesCount(), 9);\n\tBOOST_CHECK_EQUAL(myGraph.getVerticesCount(), 11);\n\tBOOST_CHECK_EQUAL(myGraph.getEdgeProperty(myGraph[\"foo\"], myGraph[\"bar\"]).weight, 5);\n\tBOOST_CHECK_EQUAL(myGraph.getEdgeProperty(myGraph[\"bar\"], myGraph[\"foo\"]).weight, 0);\n}\n\nBOOST_AUTO_TEST_CASE(matrix_graph_connect) {\n\tusing Graph = matrix::Graph<NoProperty, WeightedProperty>;\n\n\tGraph myGraph{{\"6\", \"5\"}, {\"4\", \"3\"}, {\"2\", \"1\"}};\n\n\tmyGraph.connect(myGraph[\"3\"], myGraph[\"2\"]);\n\tBOOST_CHECK_EQUAL(myGraph.getEdgesCount(), 4);\n\tBOOST_CHECK_EQUAL(myGraph.getVerticesCount(), 6);\n\tBOOST_CHECK_EQUAL(myGraph.getEdgeProperty(myGraph[\"3\"], myGraph[\"2\"]).weight, 0);\n\tmyGraph.connect(myGraph[\"5\"], myGraph[\"4\"], {42});\n\tBOOST_CHECK_EQUAL(myGraph.getEdgesCount(), 5);\n\tBOOST_CHECK_EQUAL(myGraph.getVerticesCount(), 6);\n\tBOOST_CHECK_EQUAL(myGraph.getEdgeProperty(myGraph[\"5\"], myGraph[\"4\"]).weight, 42);\n}\n\nBOOST_AUTO_TEST_CASE(matrix_graph_remove_edge) {\n\tusing Graph = matrix::Graph<NoProperty, WeightedProperty>;\n\n\tGraph myGraph{{\"6\", \"5\"}, {\"4\", \"3\"}, {\"2\", \"1\"}};\n\n\tBOOST_CHECK_EQUAL(myGraph.getEdgesCount(), 3);\n\tmyGraph.removeEdge(myGraph[\"4\"], myGraph[\"3\"]);\n\tBOOST_CHECK_EQUAL(myGraph.getEdgesCount(), 2);\n\tBOOST_CHECK(!myGraph.hasEdge(myGraph[\"4\"], myGraph[\"3\"]));\n\tBOOST_CHECK_THROW(myGraph.removeEdge(myGraph[\"5\"], myGraph[\"4\"]), std::out_of_range);\n}\n\nBOOST_AUTO_TEST_CASE(matrix_graph_set_edge_property) {\n\tusing Graph = matrix::Graph<NoProperty, WeightedProperty>;\n\n\tGraph myGraph{{\"6\", \"5\"}, {\"4\", \"3\"}, {\"2\", \"1\"}};\n\n\tBOOST_CHECK_EQUAL(myGraph.getEdgeProperty(myGraph[\"6\"], myGraph[\"5\"]).weight, 0);\n\tmyGraph.setEdgeProperty(myGraph[\"6\"], myGraph[\"5\"], {1337});\n\tBOOST_CHECK_EQUAL(myGraph.getEdgeProperty(myGraph[\"6\"], myGraph[\"5\"]).weight, 1337);\n}\n\nBOOST_AUTO_TEST_CASE(matrix_graph_each_vertices) {\n\tusing Graph     = matrix::Graph<NoProperty, WeightedProperty>;\n\tusing ConstNode = matrix::Graph<NoProperty, WeightedProperty>::ConstNode_t;\n\n\tGraph myGraph{{\"6\", \"5\"}, {\"4\", \"3\"}, {\"2\", \"1\"}};\n\n\tstd::string expected = \"123456\";\n\tstd::ostringstream result;\n\n\tmyGraph.eachVertices([&result](ConstNode node) { result << node.getName(); });\n\n\tBOOST_CHECK_EQUAL(result.str(), expected);\n}\n\nBOOST_AUTO_TEST_CASE(matrix_graph_each_edges) {\n\tusing Graph     = matrix::Graph<NoProperty, WeightedProperty>;\n\tusing ConstNode = matrix::Graph<NoProperty, WeightedProperty>::ConstNode_t;\n\n\tGraph myGraph{{\"6\", \"5\"}, {\"4\", \"3\"}, {\"2\", \"1\"}};\n\n\tstd::string expected = \"2->1, 4->3, 6->5, \";\n\tstd::ostringstream result;\n\n\tmyGraph.eachEdges([&result](ConstNode begin, ConstNode end) {\n\t\tresult << begin.getName() << \"->\" << end.getName() << \", \";\n\t});\n\n\tBOOST_CHECK_EQUAL(result.str(), expected);\n}\n\nBOOST_AUTO_TEST_CASE(matrix_graph_each_adjacents) {\n\tusing Graph     = matrix::Graph<NoProperty, WeightedProperty>;\n\tusing ConstNode = matrix::Graph<NoProperty, WeightedProperty>::ConstNode_t;\n\n\tGraph myGraph{{\"6\", \"5\"}, {\"4\", \"3\"}, {\"2\", \"1\"}, {\"4\", \"2\"}};\n\n\tstd::string expected = \"4->2, 4->3, \";\n\tstd::ostringstream result;\n\n\tmyGraph.eachAdjacents(myGraph[\"4\"],\n\t                      [&result](ConstNode end) {\n\t\t                      result << \"4->\" << end.getName() << \", \";\n\t\t                  });\n\n\tBOOST_CHECK_EQUAL(result.str(), expected);\n}\n\nBOOST_AUTO_TEST_CASE(matrix_node_get_id) {\n\tusing Graph = matrix::Graph<NoProperty, NoProperty>;\n\n\tGraph myGraph{{\"0\", \"0\"}, {\"1\", \"1\"}, {\"2\", \"2\"}, {\"3\", \"3\"}};\n\n\tBOOST_CHECK_EQUAL(myGraph[\"0\"].getId(), 0);\n\tBOOST_CHECK_EQUAL(myGraph[\"1\"].getId(), 1);\n\tBOOST_CHECK_EQUAL(myGraph[\"2\"].getId(), 2);\n\tBOOST_CHECK_EQUAL(myGraph[\"3\"].getId(), 3);\n}\n\nBOOST_AUTO_TEST_CASE(matrix_node_const_get_id) {\n\tusing Graph = matrix::Graph<NoProperty, NoProperty>;\n\n\tconst Graph myGraph{{\"0\", \"0\"}, {\"1\", \"1\"}, {\"2\", \"2\"}, {\"3\", \"3\"}};\n\n\tBOOST_CHECK_EQUAL(myGraph[\"0\"].getId(), 0);\n\tBOOST_CHECK_EQUAL(myGraph[\"1\"].getId(), 1);\n\tBOOST_CHECK_EQUAL(myGraph[\"2\"].getId(), 2);\n\tBOOST_CHECK_EQUAL(myGraph[\"3\"].getId(), 3);\n}\n\nBOOST_AUTO_TEST_CASE(matrix_node_is_connected_to) {\n\tusing Graph = matrix::Graph<NoProperty, NoProperty>;\n\n\tGraph myGraph{{\"0\", \"0\"}, {\"1\", \"3\"}, {\"5\", \"7\"}, {\"2\", \"0\"}};\n\n\tBOOST_CHECK(myGraph[\"0\"].isConnectedTo(myGraph[\"0\"]));\n\tBOOST_CHECK(!myGraph[\"0\"].isConnectedTo(myGraph[\"1\"]));\n\tBOOST_CHECK(myGraph[\"1\"].isConnectedTo(myGraph[\"3\"]));\n}\n\nBOOST_AUTO_TEST_CASE(matrix_weighted_graph) {\n\tusing Graph = matrix::Graph<NoProperty, WeightedProperty>;\n\n\tGraph myGraph{{\"4\", \"5\"}, {\"6\", \"3\"}, {\"2\", \"4\"}, {\"5\", \"2\"}, {\"6\", \"4\"}, {\"3\", \"3\"}};\n\n\tmyGraph.setEdgeProperty(myGraph[\"2\"], myGraph[\"4\"], {5});\n\n\tBOOST_CHECK_THROW(myGraph.getEdgeProperty(myGraph[\"0\"], myGraph[\"1\"]), std::out_of_range);\n\tBOOST_CHECK_THROW(myGraph.getEdgeProperty(myGraph[\"0\"], myGraph[\"2\"]), std::out_of_range);\n\tBOOST_CHECK_THROW(myGraph.getEdgeProperty(myGraph[\"3\"], myGraph[\"2\"]), std::out_of_range);\n\tBOOST_CHECK_THROW(myGraph.getEdgeProperty(myGraph[\"5\"], myGraph[\"1\"]), std::out_of_range);\n\n\tBOOST_CHECK_EQUAL(myGraph.getEdgeProperty(myGraph[\"2\"], myGraph[\"4\"]).weight, 5);\n}\n\nBOOST_AUTO_TEST_CASE(matrix_weighted_graph_default_values) {\n\tusing Graph = matrix::Graph<NoProperty, WeightedProperty>;\n\n\tGraph myGraph{{\"4\", \"5\"}, {\"6\", \"3\"}, {\"2\", \"4\"}, {\"5\", \"2\"}, {\"6\", \"4\"}, {\"3\", \"3\"}};\n\n\tmyGraph.setEdgeProperty(myGraph[\"2\"], myGraph[\"4\"], {5});\n\n\tBOOST_CHECK_EQUAL(myGraph.getEdgeProperty(myGraph[\"4\"], myGraph[\"5\"]).weight, 0);\n\tBOOST_CHECK_EQUAL(myGraph.getEdgeProperty(myGraph[\"6\"], myGraph[\"3\"]).weight, 0);\n\tBOOST_CHECK_EQUAL(myGraph.getEdgeProperty(myGraph[\"5\"], myGraph[\"2\"]).weight, 0);\n}\n\nBOOST_AUTO_TEST_CASE(matrix_weighted_graph_nonexistent_edge) {\n\tusing Graph = matrix::Graph<NoProperty, WeightedProperty>;\n\n\tGraph myGraph{{\"4\", \"5\"}, {\"6\", \"3\"}, {\"2\", \"4\"}, {\"5\", \"2\"}, {\"6\", \"4\"}, {\"3\", \"3\"}};\n\n\tBOOST_CHECK_THROW(myGraph.setEdgeProperty(myGraph[\"2\"], myGraph[\"3\"], {5}), std::out_of_range);\n}\n", "meta": {"hexsha": "dd050100874d0a7ce82722ee35f841c32f13eba6", "size": 15367, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/matrix_graph_testing.cpp", "max_stars_repo_name": "minijackson/IT-3004", "max_stars_repo_head_hexsha": "d77e88382d488c887af5f070f9c6c04ddfe3df0e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-10-01T02:28:13.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-01T02:28:13.000Z", "max_issues_repo_path": "tests/matrix_graph_testing.cpp", "max_issues_repo_name": "minijackson/IT-3004", "max_issues_repo_head_hexsha": "d77e88382d488c887af5f070f9c6c04ddfe3df0e", "max_issues_repo_licenses": ["MIT"], "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/matrix_graph_testing.cpp", "max_forks_repo_name": "minijackson/IT-3004", "max_forks_repo_head_hexsha": "d77e88382d488c887af5f070f9c6c04ddfe3df0e", "max_forks_repo_licenses": ["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.3264367816, "max_line_length": 96, "alphanum_fraction": 0.6772304288, "num_tokens": 4314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544335934766, "lm_q2_score": 0.6893056104028797, "lm_q1q2_score": 0.48200000417507133}}
{"text": "\r\n/*\r\n\tkstat\r\n\tVer. k09.02\r\n\t\r\n\tWritten by Koji Yamamoto\r\n\tCopyright (C) 2015-2020 Koji Yamamoto\r\n\tIn using this, please read the document which states terms of use.\r\n\t\r\n\tModule for Statistical Computations\r\n\t\r\n\tk10\u306b\u306a\u308b\u3068\u304d\u306b\u4ee5\u4e0b\u306e\u95a2\u6570\u3092\u6d88\u3059\u3002\r\n\tdouble unbiasedVar()\u3000\u2192kstatboost\u306e\u3082\u306e\u3092\u63a8\u5968\u3002\r\n\tdouble boostMean( const std::vector <double> &dv0)\r\n\t\r\n\tNote:\r\n\tAs for FreqType, possibly in the future we should refer the following libraries:\r\n\t\u3000GSL's Histogram\r\n\t\r\n*/\r\n\r\n\r\n/* ********** Preprocessor Directives ********** */\r\n\r\n#ifndef kstat_cpp_include_guard\r\n#define kstat_cpp_include_guard\r\n\r\n#include <memory>\r\n#include <map>\r\n#include <vector>\r\n#include <limits>\r\n#include <functional>\r\n#include <cmath>\r\n\r\n#include <k09/kutil02.cpp>\r\n#include <k09/kalgo02.cpp>\r\n\r\n\r\n/* ********** Using Directives ********** */\r\n\r\n//using namespace std;\r\n\r\n\r\n/* ********** Type Declarations: enum, class, etc. ********** */\r\n\r\n// TCount is int by default\r\ntemplate <typename T, typename TCount = int>\r\nclass FreqType;\r\n\r\n// TCode is int by default\r\ntemplate <typename T, typename TCode = int>\r\nclass RecodeTable;\r\n\r\n/*\r\n// This class is declared in RecodeType\r\ntemplate <typename T, typename TCode>\r\nstruct\r\nRecodeTable ::\r\nCodeType;\r\n*/\r\n\r\ntemplate <typename T>\r\nclass JudgeEqual;\r\n\r\ntemplate <typename T>\r\nclass JudgeEqualTol;\r\n\r\n\r\n/* ********** Function Declarations ********** */\r\n\r\ntemplate <typename T>\r\nint countUniqueValues( const std::vector <T> &);\r\n\r\ntemplate <typename TOrigin, typename TCode, typename TCount>\r\nvoid\r\ncreateFreqFromRecodeTable( \r\n\tFreqType <TCode, TCount> &,\r\n\tconst std::vector <TOrigin> &,\r\n\tconst RecodeTable <TOrigin, TCode> &\r\n);\r\n\r\ntemplate <typename T>\r\nstd::vector <T> omitNan( const std::vector <T> &);\r\n\r\ndouble sum( const std::vector <double> &);\r\ndouble mean( const std::vector <double> &);\r\ndouble median( const std::vector <double> &);\r\ndouble unbiasedVar( const std::vector <double> &); // \u975e\u63a8\u5968\u3002deprecated. \r\ndouble boostMean( const std::vector <double> &); // \u975e\u63a8\u5968\u3002deprecated. \r\ndouble sum( const double *, int);\r\ndouble mean( const double *, int);\r\ndouble unbiasedVar( const double *, int);\r\n\r\n// \u3053\u306e\u30d5\u30a1\u30a4\u30eb\u5185\u3067\u3088\u3044\u306e\u304b\uff1f\r\ntemplate <typename T>\r\nstd::string toString( const T &);\r\n\r\n\r\n/* ********** Type Definitions: enum, class, etc. ********** */\r\n\r\n// frequency type\r\n// T is type for key, and TCount is type for count\r\n// This type is essentially for discrete variables,\r\n// with Tolerance for equality judgment being very small.\r\n// When applied to continuous variables, \r\n// special methods should be used.\r\n// \u57fa\u672c\u7684\u306b\u96e2\u6563\u5909\u6570\u7528\u3002\r\n// double\u306a\u3069\u306b\u4f7f\u3046\u5834\u5408\u3001\u7b49\u5024\u5224\u65ad\u306e\u305f\u3081\u306e\r\n// tolerance\u306f0\u304b\u975e\u5e38\u306b\u5c0f\u3055\u3044\u5024\u3067\u3042\u308b\u3001\r\n// \u3068\u3044\u3046\u524d\u63d0\u304c\u3042\u308b\u3002\u305d\u3046\u3067\u306a\u3044\u3068\u30ab\u30c6\u30b4\u30ea\u9593\u306e\r\n// \u91cd\u306a\u308a\u304c\u751f\u3058\u3066\u3057\u307e\u3046\u3002\r\n// \u9023\u7d9a\u5909\u6570\u306b\u7528\u3044\u308b\u5834\u5408\u306b\u306f\u3001\u7279\u5b9a\u306e\u6a5f\u80fd\u3092\u4f7f\u3046\u3079\u3057\u3002\r\n// TCount is int by default\r\ntemplate <typename T, typename TCount /* = int */>\r\nclass FreqType {\r\n\t\r\nprivate:\r\n\t\r\n\tmap <T, TCount> freqmap;\r\n\tstd::function < bool( const T &, const T &) > areEqual;\r\n\tTCount sumcount;\r\n\r\n\t// Note that we specify double as TOrigin for RecodeTable\r\n\t// RecodeTable\u306eTOrigin\u3068\u3057\u3066\u3001double\u3092\u6307\u5b9a\u3057\u3066\u3057\u307e\u3063\u3066\u3044\u308b\u3002\r\n\t// \u3053\u3053\u306b\u67d4\u8edf\u6027\u3092\u6301\u305f\u305b\u305f\u3044\u306a\u3089\u3070\u3001rtablep\u304c\u306a\u3044\u30af\u30e9\u30b9\u3092\u3064\u304f\u308a\u3001\r\n\t// \u305d\u308c\u3092\u57fa\u5e95\u30af\u30e9\u30b9\u306b\u3057\u3066\u3001\u6d3e\u751f\u30af\u30e9\u30b9\u3067\u30c6\u30f3\u30d7\u30ec\u30fc\u30c8\u5f15\u6570\u3092\u5897\u3084\u3057\u3066rtablep\u3092\u6301\u305f\u305b\u308b\u306e\u304c\u3001\u7d20\u76f4\u3060\u308d\u3046\u3002\r\n\tstd::unique_ptr < RecodeTable<double, T> > rtablep;\r\n\t\r\npublic:\r\n\t\r\n\tFreqType( void);\r\n\t~FreqType( void);\r\n\t\r\n\tvoid clear( void);\r\n\tvoid setEqualExactly( void);\r\n\tvoid setEqualWithTol( const T &);\r\n\tbool addPossibleKey( const T &);\r\n\tbool addPossibleKeys( const std::vector <T> &);\r\n\t\r\n\tvoid increment( const T &);\r\n\tvoid addCount( const T &, const TCount &);\r\n\tvoid addFreqType( const FreqType <T, TCount> &);\r\n\t\r\n\tvoid clearCount( void);\r\n\t\r\n\tTCount getSumCount( void) const;\r\n\tvoid getVectors( std::vector <T> &, std::vector <TCount> &) const;\r\n\tdouble meanFromFreq( void) const;\r\n\tdouble medianFromFreq( void) const;\r\n\tvoid modeFromFreq( std::vector <T> &) const;\r\n\r\n\tvoid setFreqFromRecodeTable( const std::vector <double> &, const RecodeTable <double, T> &);\r\n\r\n\tvoid printPadding( std::ostream &) const;\r\n\r\n\t// Note that obtained vectors should be\r\n\t// parallel to those obtained by getVectors() above\r\n\tvoid getRangeVectors( std::vector <double> &, std::vector <double> &) const;\r\n\r\n};\r\n\r\n\r\n// TCode is int by default\r\ntemplate <typename TOrigin, typename TCode /* = int */>\r\nclass RecodeTable {\r\n\r\nprivate:\r\n\r\n\tstruct CodeType; // inner class; defined below\r\n\r\n\t// 1\u8981\u7d20\u306fRecodeTable\u306e1\u884c\u5206\r\n\tstd::vector <CodeType> codes; \r\n\r\n\t// \"else\"\u306e\u5834\u5408\u306e\u51e6\u7406\u65b9\u6cd5\u3000\uff08\u30b9\u30b3\u30fc\u30d7\u3092\u6301\u3064\u5217\u6319\u578b\uff09\r\n\tenum class ElseType { Copy, AssignValue};\r\n\t\r\n\tElseType toDoForElse; // \"else\"\u306e\u5834\u5408\u306e\u51e6\u7406\u65b9\u6cd5\r\n\tTCode codeForElse; // \"else\"\u306e\u5834\u5408\u306b\u5024\u3092\u57cb\u3081\u308b\u5834\u5408\u306e\u5024\uff08NaN\u4ee5\u5916\uff09\r\n\r\npublic:\r\n\r\n\tRecodeTable( void){}\r\n\t~RecodeTable( void){}\r\n\r\n\tvoid setAutoTableFromContVar( const std::vector <TOrigin> &);\r\n\tstd::vector <TCode> getPossibleCodeVec( void) const;\r\n\tTCode getCodeForValue( TOrigin) const;\r\n\r\n\tvoid getLeftRightForCode( TOrigin &, TOrigin &, TCode) const; \r\n\r\n\tstd::string getRangeLabelForCode( TCode) const;\r\n\tvoid print( ostream &, string = \",\"s) const;\r\n\r\n};\r\n\r\n\r\ntemplate <typename TOrigin, typename TCode>\r\nstruct\r\nRecodeTable <TOrigin, TCode> ::\r\nCodeType {\r\n\r\n// Fields:\r\n\r\n\tTOrigin left; // the left-handside endpoint of the class\r\n\tbool leftIn; // whether the endpoint value is inclusive\r\n\r\n\tTOrigin right; // the right-handside endpoint of the class\r\n\tbool rightIn; // whether the endpoint value is inclusive\r\n\r\n\tTCode codeAssigned; // the code assigned to this class\r\n\r\n// Methods:\r\n\r\n\tCodeType( TOrigin l0, bool li0, TOrigin r0, bool ri0, TCode ca0)\r\n\t: left( l0), leftIn( li0), right( r0), rightIn( ri0), codeAssigned( ca0)\r\n\t{}\r\n\r\n\t~CodeType( void){};\r\n\r\n\tbool correspond( TOrigin v) const\r\n\t{\r\n\t\tif ( left < v && v < right){\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\tif ( leftIn == true && left == v){\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\tif ( rightIn == true && right == v){\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\treturn false;\r\n\t}\r\n\r\n\tstring getRangeLabel( void) const\r\n\t{\r\n\r\n\t\tstringstream ss;\r\n\t\tss << left << \" \";\r\n\t\tif ( leftIn == true){\r\n\t\t\tss << \"<=\";\r\n\t\t} else {\r\n\t\t\tss << \"<\";\r\n\t\t}\r\n\t\tss << \" x \";\r\n\t\tif ( rightIn == true){\r\n\t\t\tss << \"<=\";\r\n\t\t} else {\r\n\t\t\tss << \"<\";\r\n\t\t}\r\n\t\tss << \" \" << right;\r\n\r\n\t\treturn ss.str();\r\n\r\n\t}\r\n\r\n};\r\n\r\n\r\n// \u7b49\u5024\u5224\u65ad\u306e\u305f\u3081\u306e\u30d5\u30a1\u30f3\u30af\u30bf\u30af\u30e9\u30b9\uff1a==\u6f14\u7b97\u5b50\u3067\u5224\u65ad\u3059\u308b\u3002\r\ntemplate <typename T>\r\nclass JudgeEqual {\r\n\t\r\npublic:\r\n\t\r\n\tJudgeEqual( void){}\r\n\r\n\t~JudgeEqual( void){}\r\n\t\r\n\tbool operator()( const T &a, const T &b)\r\n\t{\r\n\t\t\r\n\t\treturn ( a == b);\r\n\t\t\r\n\t}\r\n\t\r\n};\r\n\r\n\r\n// \u7b49\u5024\u5224\u65ad\u306e\u305f\u3081\u306e\u30d5\u30a1\u30f3\u30af\u30bf\u30af\u30e9\u30b9\uff1aTolerance\u3092\u542b\u3093\u3067\u5224\u65ad\u3059\u308b\u3002\r\n// class to judge equality with tolerance\r\n// i.e. regard a and b equal when a < b + tol and a > b - tol\r\n// thus if T is double and a = 1.0 and tol = 0.1,\r\n// then b can be ( 0.9, 1.1)\r\ntemplate <typename T>\r\nclass JudgeEqualTol {\r\n\t\r\nprivate:\r\n\t\r\n\tT tol; // this is assumed to be non-negative and very small\r\n\t\r\npublic:\r\n\t\r\n\tJudgeEqualTol( void){}\r\n\t\r\n\tJudgeEqualTol( const T &tol0) : tol( tol0){}\r\n\t\r\n\t~JudgeEqualTol( void){}\r\n\t\r\n\tvoid setTol( const T &tol0)\r\n\t{\r\n\t\ttol = tol0;\r\n\t}\r\n\r\n\tbool operator()( const T &a, const T &b)\r\n\t{\t\t\r\n\t\treturn ( ( a < b + tol) && ( a > b - tol));\t\t\r\n\t}\r\n\t\r\n};\r\n\r\n\r\n/* ********** Global Variables ********** */\r\n\r\n\r\n/* ********** Definitions of Static Member Variables ********** */\r\n\r\n\r\n/* ********** Function Definitions ********** */\r\n\r\n// ==\u6f14\u7b97\u5b50\u3092\u7528\u3044\u3066\u3001\u30e6\u30cb\u30fc\u30af\u306a\u5024\u304c\u4f55\u500b\u3042\u308b\u304b\u3092\u8fd4\u3059\u3002\r\n// var0\u306b\u6b20\u640d\u5024\u306f\u542b\u307e\u306a\u3044\u3068\u4eee\u5b9a\u3057\u3066\u3001\u30b1\u30fc\u30b9\u6570\u3092\u7b97\u51fa\u3057\u3066\u3044\u308b\u3002\r\n// We assume var0 does not contain invalid values.\r\ntemplate <typename T>\r\nint countUniqueValues( const std::vector <T> &vec0)\r\n{\r\n\r\n\tif ( vec0.size() < 1){\r\n\t\treturn 0;\r\n\t}\r\n\r\n\tstd::vector <T> vec( vec0);\r\n\r\n\tstd::sort( vec.begin(), vec.end());\r\n\r\n\tT prev = vec[ 0];\r\n\tint ret = 1;\r\n\tfor ( auto v : vec){\r\n\t\tif ( v != prev){\r\n\t\t\tret++;\r\n\t\t\tprev = v;\r\n\t\t}\r\n\t}\r\n\r\n\treturn ret;\r\n\r\n}\r\n\r\n// This function is more flexible than FreqType::setFreqFromRecodeType()\r\n// in the sense that this can allow <TOrigin> different from <double>.\r\n// But this function does not make FreqType store rtable itself.\r\ntemplate <typename TOrigin, typename TCode, typename TCount>\r\nvoid\r\ncreateFreqFromRecodeTable( \r\n\tFreqType <TCode, TCount> &ret,\r\n\tconst std::vector <TOrigin> &var,\r\n\tconst RecodeTable <TOrigin, TCode> &rtable\r\n)\r\n{\r\n\r\n\tret.clear();\r\n\tstd::vector <TCode> codeVec = rtable.getPossibleCodeVec();\r\n\tret.addPossibleKeys( codeVec);\r\n\tfor ( auto v : var){\r\n\t\tif ( std::isnan( v)){\r\n\t\t\t// do nothing\r\n\t\t} else {\r\n\t\t\tTCode codeToAdd = rtable.getCodeForValue( v);\r\n\t\t\tret.increment( codeToAdd);\r\n\t\t}\r\n\t}\r\n\r\n}\r\n\r\ntemplate <typename T>\r\nstd::vector <T> omitNan( const std::vector <T> &vec0)\r\n{\r\n\r\n\tstd::vector <T> ret;\r\n\tret.reserve( vec0.size());\r\n\r\n\tfor ( const auto &v : vec0){\r\n\t\tif ( std::isnan( v)){\r\n\t\t\t// do nothing\r\n\t\t} else {\r\n\t\t\tret.push_back( v);\r\n\t\t}\r\n\t}\r\n\r\n\treturn ret;\r\n\r\n}\r\n\r\n// returns the sum of all the elements\r\ndouble sum( const std::vector <double> &dv0)\r\n{\r\n\r\n\tdouble s;\r\n\ts = 0.0;\r\n\tfor ( auto v : dv0){\r\n\t\ts += v;\r\n\t}\r\n\treturn s;\r\n\r\n}\r\n\r\n// returns the mean value\r\ninline double mean( const std::vector <double> &dv0)\r\n{\r\n\r\n\tdouble s, ret;\r\n\ts = sum( dv0);\r\n\tret = s / ( double)( dv0.size());\r\n\treturn ret;\r\n\r\n}\r\n\r\n// returns the median value\r\ndouble median( const std::vector <double> &dv0)\r\n{\r\n\tint n;\r\n\tstd::vector <double> sorted;\r\n\tdouble ret;\r\n\r\n\tn = dv0.size();\r\n\tsorted = dv0;\r\n\tsort( sorted.begin(), sorted.end());\r\n\r\n\tif ( n % 2 == 0){\r\n\t\t// n is an even number\r\n\t\tret = ( sorted[ n / 2 - 1] + sorted[ n / 2]) / 2.0;\r\n\t} else {\r\n\t\t// n is an odd number\r\n\t\tret = sorted[ n / 2];\r\n\t}\r\n\r\n\treturn ret;\r\n\t\r\n}\r\n\r\n// DEPRECATED \u975e\u63a8\u5968\r\n// \u3053\u306e\u30a2\u30eb\u30b4\u30ea\u30ba\u30e0\u3067\u306f\u7cbe\u5ea6\u304c\u843d\u3061\u308b\u3068\u304d\u304c\u3042\u308b\u3089\u3057\u3044\u3002\r\n// kstatboost\u306e\u3082\u306e\u3092\u63a8\u5968\u3059\u308b\u3002\r\n// returns \"unbiased\" variance\r\ninline double unbiasedVar( const std::vector <double> &v0)\r\n{\r\n\t\r\n\tint n = v0.size();\r\n\t\r\n\tdouble m = mean( v0);\r\n\t\r\n\tdouble s2 = 0.0;\r\n\tfor ( auto &d : v0){\r\n\t\ts2 += d * d;\r\n\t}\r\n\t\r\n\treturn ( s2 / ( double)n - m * m) * ( double)n / ( double)( n - 1);\r\n\t\r\n}\r\n\r\n\r\n// DEPRECATED \u975e\u63a8\u5968\r\n// boost version of mean calculation\r\n// \r\n// I would not prefer this series,\r\n// because the algorithm for median value is just estimating it;\r\n// not returining accurate values\r\n#include <boost/accumulators/accumulators.hpp> \r\n#include <boost/accumulators/statistics.hpp> // for stats<> template, tag::mean\r\ndouble boostMean( const std::vector <double> &dv0)\r\n{\r\n\r\n\tusing namespace boost::accumulators;\r\n\r\n\taccumulator_set< double, stats< tag::mean > > acc;\r\n\r\n\tacc = std::for_each( dv0.begin(), dv0.end(), acc);\r\n\r\n\treturn extract::mean( acc);\r\n\r\n}\r\n\r\n// \u9577\u3055n\u306e\u914d\u5217\u3078\u306e\u30dd\u30a4\u30f3\u30bfp\u3092\u5f97\u3066\u3001\u5408\u8a08\u3092\u8fd4\u3059\u3002\r\ndouble sum( const double *p, int n)\r\n{\r\n\t\r\n\tdouble s;\r\n\ts = 0.0;\r\n\tfor ( int i = 0; i < n; i++){\r\n\t\ts += p[ i];\r\n\t}\r\n\treturn s;\r\n\t\r\n}\r\n\r\n// \u9577\u3055n\u306e\u914d\u5217\u3078\u306e\u30dd\u30a4\u30f3\u30bfp\u3092\u5f97\u3066\u3001\u5e73\u5747\u3092\u8fd4\u3059\u3002\r\ninline double mean( const double *p, int n)\r\n{\r\n\t\r\n\treturn ( sum( p, n) / ( double)n);\r\n\t\r\n}\r\n\r\n// \u9577\u3055n\u306e\u914d\u5217\u3078\u306e\u30dd\u30a4\u30f3\u30bfp\u3092\u5f97\u3066\u3001\u4e0d\u504f\u5206\u6563\u3092\u8fd4\u3059\u3002\r\ninline double unbiasedVar( const double *p, int n)\r\n{\r\n\t\r\n\tdouble m, s2;\r\n\t\r\n\tm = mean( p, n);\r\n\t\r\n\ts2 = 0.0;\r\n\tfor ( int i = 0; i < n; i++){\r\n\t\ts2 += p[ i] * p[ i];\r\n\t}\r\n\t\r\n\treturn ( s2 / ( double)n - m * m) * ( double)n / ( double)( n - 1);\r\n\t\r\n}\r\n\r\n// convert any type T into string\r\n// using stringstream\r\ntemplate <typename T>\r\nstd::string toString( const T &origin)\r\n{\r\n\tstd::stringstream ss;\r\n\tss.str( \"\");\r\n\tss << origin;\r\n\treturn ss.str();\r\n}\r\n\r\n\r\n/* ********** Definitions of Member Functions ********** */\r\n\r\n/* ---------- class FreqType ---------- */\r\n\r\ntemplate <typename T, typename TCount>\r\nFreqType <T, TCount> ::\r\nFreqType( void)\r\n: freqmap(),\r\n  areEqual( JudgeEqual<T>()),\r\n  sumcount( static_cast<TCount>( 0))\r\n{\r\n}\r\n\r\ntemplate <typename T, typename TCount>\r\nFreqType <T, TCount> ::\r\n~FreqType( void)\r\n{\r\n}\r\n\r\ntemplate <typename T, typename TCount>\r\nvoid\r\nFreqType <T, TCount> ::\r\nclear( void)\r\n{\r\n\t\r\n\tfreqmap.clear();\r\n\tsumcount = static_cast<TCount>( 0);\r\n\t\r\n}\r\n\r\ntemplate <typename T, typename TCount>\r\nvoid \r\nFreqType <T, TCount> ::\r\nsetEqualExactly( void)\r\n{\r\n\t\r\n\tareEqual = JudgeEqual<T>();\r\n\t\r\n}\r\n\r\ntemplate <typename T, typename TCount>\r\nvoid \r\nFreqType <T, TCount> :: \r\nsetEqualWithTol( const T &tol)\r\n{\r\n\t\r\n\tareEqual = JudgeEqualTol<T>( tol);\r\n\t\r\n}\r\n\r\n// add v as a key with no freq when such a key does not exist.\r\n// if the \"same\" key exists, this does nothing.\r\n// returns true if such a key does not exist.\r\n// returns false if such a key does exist.\r\n// Note that the judgment about equivalence is made \r\n// simply using \"map::find()\" function; not using areEqual()\r\ntemplate <typename T, typename TCount>\r\nbool \r\nFreqType <T, TCount> :: \r\naddPossibleKey( const T &v)\r\n{\r\n\t\r\n\tauto it = freqmap.find( v); // \u3053\u3053\u3067find\u3092\u4f7f\u3046\u3002areEqual\u3092\u4f7f\u3063\u3066\u3044\u306a\u3044\u3002\r\n\tif ( it == freqmap.end()){\r\n\t\tfreqmap.insert( { v, 0});\r\n\t\treturn true;\r\n\t}\r\n\r\n\treturn false;\r\n\t\r\n}\r\n\r\n// adds values in vec as a key with no freq when such a key does not exist.\r\n// if the same key exists, this does nothing.\r\n// returns true if such a key does not exist.\r\n// returns false if such a key does exist.\r\n// We can use this function like below.\r\n//   addPossibleKeys( { 1.0, 2.0, 3.0, 4.0, 5.0});\r\n//   addPossibleKeys( vector <double> ( { 1.0, 2.0, 3.0, 4.0, 5.0}));\r\ntemplate <typename T, typename TCount>\r\nbool \r\nFreqType <T, TCount> :: \r\naddPossibleKeys( const std::vector <T> &vec)\r\n{\r\n\t\r\n\tbool ret = true;\r\n\r\n\tfor ( const T &v : vec){\r\n\t\tbool b = addPossibleKey( v);\r\n\t\tif ( b == false){\r\n\t\t\tret = false;\r\n\t\t}\r\n\r\n\t}\r\n\r\n\treturn ret;\r\n\t\r\n}\r\n\r\n// increment the count for the key \"v\"\r\ntemplate <typename T, typename TCount>\r\nvoid \r\nFreqType <T, TCount> :: \r\nincrement( const T &v)\r\n{\r\n\t\r\n\tbool exist = false;\r\n\tfor ( auto &pair : freqmap){\r\n\t\t\r\n\t\tif ( areEqual( pair.first, v) == true){\r\n\t\t\t( pair.second)++;\r\n\t\t\texist = true;\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\t\r\n\t}\r\n\t\r\n\tif ( exist == false){\r\n\t\tfreqmap.insert( { v, 1});\r\n\t}\r\n\t\r\n\tsumcount++;\r\n\t\r\n}\r\n\r\ntemplate <typename T, typename TCount>\r\nvoid \r\nFreqType <T, TCount> :: \r\naddCount( const T &key, const TCount &count)\r\n{\r\n\t\r\n\tbool exist = false;\r\n\tfor ( auto &pair : freqmap){\r\n\t\t\r\n\t\tif ( areEqual( pair.first, key) == true){\r\n\t\t\tpair.second += count;\r\n\t\t\texist = true;\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\t\r\n\t}\r\n\t\r\n\tif ( exist == false){\r\n\t\tfreqmap.insert( { key, count});\r\n\t}\r\n\t\r\n\tsumcount += count;\r\n\t\r\n}\r\n\r\ntemplate <typename T, typename TCount>\r\nvoid \r\nFreqType <T, TCount> :: \r\naddFreqType( const FreqType <T, TCount> &freqobj)\r\n{\r\n\t\r\n\tfor ( const auto &pair : freqobj.freqmap){\r\n\t\taddCount( pair.first, pair.second);\r\n\t}\r\n\t\r\n}\r\n\r\n// Clears counts into zeros.\r\n// Possible keys and setting for equality judgement are retained.\r\ntemplate <typename T, typename TCount>\r\nvoid \r\nFreqType <T, TCount> :: \r\nclearCount( void)\r\n{\r\n\t\r\n\tfor ( auto &pair : freqmap){\r\n\t\t( pair.second) = static_cast<TCount>( 0);\r\n\t}\r\n\t\r\n\tsumcount = static_cast<TCount>( 0);\r\n\t\r\n}\r\n\r\ntemplate <typename T, typename TCount>\r\nTCount \r\nFreqType <T, TCount> :: \r\ngetSumCount( void)\r\nconst\r\n{\r\n\t\r\n\treturn sumcount;\r\n\t\r\n}\r\n\r\n// returns vectors of keys and frequency counts\r\ntemplate <typename T, typename TCount>\r\nvoid \r\nFreqType <T, TCount> :: \r\ngetVectors( std::vector <T> &keyvec, std::vector <TCount> &frevec)\r\nconst\r\n{\r\n\t\r\n\tkeyvec.resize( freqmap.size());\r\n\tfrevec.resize( freqmap.size());\r\n\t\r\n\tint i = 0;\r\n\tfor ( const auto &pair : freqmap){\r\n\t\tkeyvec[ i] = pair.first;\r\n\t\tfrevec[ i] = pair.second;\r\n\t\ti++;\r\n\t}\r\n\t\r\n}\r\n\r\ntemplate <typename T, typename TCount>\r\ndouble \r\nFreqType <T, TCount> :: \r\nmeanFromFreq( void)\r\nconst\r\n{\r\n\r\n\t// if sumcount == 0, then return NaN\r\n\tif ( sumcount == static_cast<TCount>( 0)){\r\n\t\talert( \"FreqType :: meanFromFreq()\");\r\n\t\treturn numeric_limits<double>::signaling_NaN();\r\n\t}\t\r\n\t\r\n\tdouble sumval = 0.0;\r\n\t\r\n\tfor ( const auto &pair : freqmap){\r\n\t\tsumval += static_cast<double>( pair.first)\r\n\t\t          * static_cast<double>( pair.second);\r\n\t}\r\n\t\r\n\treturn ( sumval / static_cast<double>( sumcount));\r\n\t\r\n}\r\n\r\ntemplate <typename T, typename TCount>\r\ndouble \r\nFreqType <T, TCount> :: \r\nmedianFromFreq( void)\r\nconst\r\n{\r\n\r\n\t// we are using class \"map\" because it stores data sorted by key\r\n\t\r\n\t// if sumcount == 0, then return NaN\r\n\tif ( sumcount == static_cast<TCount>( 0)){\r\n\t\talert( \"FreqType :: medianFromFreq()\");\r\n\t\treturn numeric_limits<double>::signaling_NaN();\r\n\t}\r\n\t\r\n\tTCount half;\r\n\thalf = static_cast<TCount>( floor( static_cast<double>( sumcount) / 2.0));\r\n\tbool even = false;\r\n\tif ( half * 2 == sumcount){\r\n\t\teven = true;\r\n\t}\r\n\t\r\n\tTCount cumcount = 0;\r\n\tdouble ret1;\r\n\tbool waitfornext = false;\r\n\tint i = 0;\r\n\t\r\n\t// in class \"map\" data are sorted by the key\r\n\tfor ( const auto &pair : freqmap){\r\n\t\t\r\n\t\tcumcount += pair.second;\r\n\r\n\t\tif ( waitfornext == true){\r\n\r\n\t\t\tif ( pair.second > static_cast<TCount>( 0)){\r\n\t\t\t\t\r\n\t\t\t\t// \u983b\u5ea6\u7dcf\u8a08\u304c\u5076\u6570\u3067\u3001\u300c\u7d2f\u7a4d\u983b\u5ea650%\u300d\u304c2\u5024\u306e\u9593\u306b\u306a\u3063\u3066\u304a\u308a\u3001\r\n\t\t\t\t// \u5927\u304d\u3044\u65b9\u3092\u5f85\u3063\u3066\u3044\u305f\u72b6\u614b\u306e\u3068\u304d\r\n\t\t\t\t\r\n\t\t\t\treturn ( ( ret1 + ( double)pair.first) / 2.0);\r\n\r\n\t\t\t}\r\n\t\t\t\r\n\t\t} else {\r\n\t\t\t\r\n\t\t\tif ( even == true){\r\n\t\t\t\t\r\n\t\t\t\tif ( cumcount > half){\r\n\t\t\t\t\treturn static_cast<double>( pair.first);\r\n\t\t\t\t} else if ( cumcount == half){\r\n\t\t\t\t\tret1 = static_cast<double>( pair.first);\r\n\t\t\t\t\twaitfornext = true;\r\n\t\t\t\t}\r\n\r\n\t\t\t} else {\r\n\t\t\t\t\r\n\t\t\t\tif ( cumcount > half){\r\n\t\t\t\t\treturn static_cast<double>( pair.first);\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t}\r\n\t\t\t\r\n\t\t}\r\n\t\t\r\n\t}\r\n\t\r\n\talert( \"FreqType :: medianFromFreq()\");\r\n\treturn numeric_limits<double>::signaling_NaN();\r\n\t\r\n}\r\n\r\ntemplate <typename T, typename TCount>\r\nvoid \r\nFreqType <T, TCount> :: \r\nmodeFromFreq( std::vector <T> &ret)\r\nconst\r\n{\r\n\t\t\r\n\t// if sumcount == 0, then return a vector of size 0\r\n\tif ( sumcount == static_cast<TCount>( 0)){\r\n\t\talert( \"FreqType :: modeFromFreq()\");\r\n\t\tret.clear();\r\n\t\treturn;\r\n\t}\r\n\t\r\n\tstd::vector <T> keyvec;\r\n\tstd::vector <TCount> frevec;\r\n\t\r\n\tgetVectors( keyvec, frevec);\r\n\t\r\n\tstd::vector <int> idmax;\r\n\tgetIndexOfMax( idmax, frevec);\r\n\t\r\n\tret.clear();\r\n\tfor ( const auto &id : idmax){\r\n\t\tret.push_back( keyvec[ id]);\r\n\t}\r\n\t\r\n}\r\n\r\n// Note that rt0 should be of RecodeTable <double, T>\r\ntemplate <typename T, typename TCount>\r\nvoid \r\nFreqType <T, TCount> :: \r\nsetFreqFromRecodeTable( const std::vector <double> &vec0, const RecodeTable <double, T> &rt0)\r\n{\r\n\r\n\tclear();\r\n\trtablep.reset( new RecodeTable<double, T>( rt0));\r\n\tstd::vector <T> codeVec = rtablep->getPossibleCodeVec();\r\n\taddPossibleKeys( codeVec);\r\n\tfor ( auto v : vec0){\r\n\t\tif ( std::isnan( v)){\r\n\t\t\t// do nothing\r\n\t\t} else {\r\n\t\t\tT codeToAdd = rtablep->getCodeForValue( v);\r\n\t\t\tincrement( codeToAdd);\r\n\t\t}\r\n\t}\r\n\r\n}\r\n\r\n// \u672c\u6765\u306f\u3001Dataset\u306b\u5165\u308c\u3066\u8868\u793a\u3057\u305f\u3044\u304c\u3001\u307e\u305f\u4eca\u5ea6\u3002\r\ntemplate <typename T, typename TCount>\r\nvoid\r\nFreqType <T, TCount> :: \r\nprintPadding( std::ostream &os)\r\nconst\r\n{\r\n\r\n\tusing namespace std;\r\n\r\n\tvector < vector <string> > strcols;\r\n\tvector <int> width;\r\n\tint ncol;\r\n\r\n\tif ( freqmap.size() < 1){\r\n\t\talert( \"FreqType :: printPadding()\");\r\n\t}\r\n\r\n\t// preparation\r\n\r\n\tncol = 2;\r\n\tif ( bool( rtablep) == true){\r\n\t\t// we will add range label column\r\n\t\tncol = 3;\r\n\t}\r\n\tstrcols.resize( ncol);\r\n\t\r\n\tfor ( auto &col : strcols){\r\n\t\tcol.reserve( freqmap.size() + 1);\r\n\t}\r\n\r\n\t{\r\n\t\tint j = 0;\r\n\t\tstrcols[ j].push_back( \"Code\");\r\n\t\tj++;\r\n\t\tif ( bool( rtablep) == true){\r\n\t\t\tstrcols[ j].push_back( \"Label\");\r\n\t\t\tj++;\r\n\t\t}\r\n\t\tstrcols[ j].push_back( \"Freq\");\r\n\t}\r\n\r\n\tfor ( auto pair : freqmap){\r\n\r\n\t\tconst T &key = pair.first;\r\n\t\tconst TCount &fre = pair.second;\r\n\t\t\r\n\t\tint j_col = 0;\r\n\r\n\t\t// Code\r\n\t\tstrcols[ j_col].push_back( toString( key));\r\n\t\tj_col++;\r\n\r\n\t\t// Range Label (optional)\r\n\t\tif ( bool( rtablep) == true){\r\n\t\t\tstring labelstr = rtablep->getRangeLabelForCode( pair.first);\r\n\t\t\tstrcols[ j_col].push_back( labelstr);\r\n\t\t\tj_col++;\r\n\t\t}\r\n\r\n\t\t// Freq\r\n\t\tstrcols[ j_col].push_back( toString( fre));\r\n\r\n\t}\r\n\r\n\twidth.resize( strcols.size());\r\n\tfor ( int i = 0; i < strcols.size(); i++){\r\n\t\tint w0 = 0;\r\n\t\tfor ( const auto &s : strcols[ i]){\r\n\t\t\tif ( w0 < s.size()){\r\n\t\t\t\tw0 = s.size();\r\n\t\t\t}\r\n\t\t}\r\n\t\twidth[ i] = w0;\r\n\t}\r\n\t\r\n\t// display\r\n\t\r\n\tos << setfill( ' ');\t\r\n\tfor ( int i_row = 0; i_row < strcols[ 0].size(); i_row++){\r\n\t\tfor ( int j_col = 0; j_col < strcols.size(); j_col++){\r\n\t\t\tos << setw( width[ j_col]);\r\n\t\t\tos << strcols[ j_col][ i_row];\r\n\t\t\tos << \" \";\r\n\t\t}\r\n\t\tos << endl;\r\n\t}\r\n\r\n}\r\n\r\n// \u5404\u968e\u7d1a\u306e\u5de6\u7aef\u3068\u53f3\u7aef\u306eVector\u3092\u5f97\u308b\u3002\r\n// RecodeType\u304c\u306a\u3044\u5834\u5408\u306b\u306f\u7a7a\u306eVector\u304c\u8fd4\u308b\u3002\r\n// Note that obtained vectors should be\r\n// parallel to those obtained by getVectors() above\r\n// \u3053\u308c\u3082\u3001\u4e0a\u8a18\u306eprintPadding()\u3068\u540c\u69d8\u306b\u3001\r\n// \u672c\u6765\u306fDataset\u306b\u5165\u308c\u3066\u51e6\u7406\u3057\u305f\u3044\u304c\u3001\u307e\u305f\u4eca\u5ea6\u3002\r\ntemplate <typename T, typename TCount>\r\nvoid\r\nFreqType <T, TCount> :: \r\ngetRangeVectors( std::vector <double> &lvec, std::vector <double> &rvec)\r\nconst\r\n{\r\n\r\n\tlvec.clear();\r\n\trvec.clear();\r\n\r\n\tif ( bool( rtablep) == false){\r\n\t\treturn;\r\n\t}\r\n\r\n\tlvec.reserve( freqmap.size());\r\n\trvec.reserve( freqmap.size());\r\n\r\n\tfor ( const auto &pair : freqmap){\r\n\r\n\t\tconst T &key = pair.first;\r\n\t\t\r\n\t\tdouble left, right;\r\n\t\trtablep->getLeftRightForCode( left, right, key);\r\n\t\tlvec.push_back( left);\r\n\t\trvec.push_back( right);\r\n\r\n\t}\r\n\r\n}\r\n\r\n\r\n/* ---------- class RecodeTable ---------- */\r\n\r\n// \u81ea\u52d5\u3067\u968e\u7d1a\u3092\u4f5c\u6210\u3059\u308b\u3002\r\n// N\u304b\u3089\u968e\u7d1a\u306e\u6570\u3092\u8a2d\u5b9a\u3059\u308b\u3002Stata\u306e\u65b9\u5f0f\u3067\u3002\r\n// \u6700\u5c0f\u5024\u3068\u6700\u5927\u5024\u306e\u5e45\u3092\u51fa\u3057\u3066\u3001\u305d\u3053\u304b\u3089\u968e\u7d1a\u5e45\u3092\u51fa\u3059\u3002\r\n// \u5404\u968e\u7d1a\u306f\u3001\u5de6\u7aef\u70b9\u3092\u542b\u307f\u3001\u53f3\u7aef\u70b9\u3092\u542b\u307e\u306a\u3044\u3002\r\n// \u6709\u52b9\u30b1\u30fc\u30b9\u6570\u304c1\u672a\u6e80\u306e\u3068\u304d\u3001\u30a8\u30e9\u30fc\u3002\r\n// \u6709\u52b9\u30b1\u30fc\u30b9\u6570\u304c1\u306e\u3068\u304d\u3001\u968e\u7d1a\u6570\u306f1\u3002\r\n// \u6700\u5927\u5024\u3068\u6700\u5c0f\u5024\u306e\u5dee\u304c\u30bc\u30ed\u306e\u5834\u5408\u3001\u6b21\u306e\u3088\u3046\u306b\u6700\u5927\u30fb\u6700\u5c0f\u3092\u4fee\u6b63\u3002\r\n// \u3000\u5024\u304c\u30bc\u30ed\u306a\u3089\u3001\u6700\u5c0f\u5024\u3092-1\u306b\u3001\u6700\u5927\u5024\u30921\u306b\u3059\u308b\u3002\r\n// \u3000\u5024\u304c\u6b63\u306a\u3089\u3001\u6700\u5c0f\u5024\u30920\u306b\u3001\u6700\u5927\u5024\u3092\u305d\u306e\u307e\u307e\u306b\u3059\u308b\u3002\r\n// \u3000\u5024\u304c\u8ca0\u306a\u3089\u3001\u6700\u5927\u5024\u30920\u306b\u3001\u6700\u5c0f\u5024\u3092\u305d\u306e\u307e\u307e\u306b\u3059\u308b\u3002\r\ntemplate <typename TOrigin, typename TCode>\r\nvoid \r\nRecodeTable <TOrigin, TCode> :: \r\nsetAutoTableFromContVar( const std::vector <TOrigin> &var0)\r\n{\r\n\t\r\n\tcodes.clear();\r\n\r\n\tstd::vector <TOrigin> vec = omitNan( var0);\r\n\tint nobs = vec.size();\r\n\tif ( nobs < 1){\r\n\t\talert( \"RecodeTable :: setAutoTableFromContVar()\");\r\n\t\treturn;\r\n\t}\r\n\r\n\tstd::sort( vec.begin(), vec.end());\r\n\tTOrigin truemin = vec.front();\r\n\tTOrigin truemax = vec.back();\r\n\r\n\t// This way to determine the number of classes is\r\n\t// from Stata's histogram command.\r\n\tlong double log10n = log10( nobs);\r\n\tint nclasses = std::round( std::min( ( long double)( std::sqrt( nobs)), 10.0 * log10n));\r\n\tif ( nclasses < 1){ // This will occur when nobs==1\r\n\t\tnclasses = 1;\r\n\t}\r\n\r\n\t// Manipulation for the case where width is zero \r\n\tif ( ( long double)truemax - ( long double)truemin <= 0.0){\r\n\t\tnclasses = 1;\r\n\t\tif ( ( long double)truemin == 0.0){\r\n\t\t\ttruemin = static_cast<TOrigin>( -1.0);\r\n\t\t\ttruemax = static_cast<TOrigin>(  1.0);\r\n\t\t} else {\r\n\t\t\tif ( truemin > 0){\r\n\t\t\t\ttruemin = static_cast<TOrigin>(  0.0);\r\n\t\t\t} else {\r\n\t\t\t\ttruemax = static_cast<TOrigin>(  0.0);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t// Adjustment to make sure all cases would fall inside one of ranges, \r\n\t// even if rounding errors occur\r\n\t// adjmin and adjmax are rounded into values with 3-digits accuracy \r\n\tTOrigin truewidth = static_cast<TOrigin>(\r\n\t\t( ( long double)truemax - (long double)truemin) / ( long double)nclasses\r\n\t);\r\n\tint log10truewidth = std::floor( log10( truewidth));\r\n\tlong double base = std::pow( 10.0, log10truewidth - 3);\r\n\tlong double adjmin = std::floor( ( long double)truemin / base - 0.5) * base;\r\n\tlong double adjmax = std::ceil( ( long double)truemax / base + 0.5) * base;\r\n\tlong double adjwidth = ( adjmax - adjmin) / ( long double)nclasses;\r\n\r\n\tfor ( int i = 0; i < nclasses; i++){\r\n\r\n\t\tTOrigin left  = adjmin + adjwidth * ( long double)i; \r\n\t\tTOrigin right = adjmin + adjwidth * ( long double)( i + 1);\r\n\r\n\t\tCodeType ct = \r\n\t\t\tCodeType (\r\n\t\t\t\tleft, true,\r\n\t\t\t\tright, false,\r\n\t\t\t\ti + 1\r\n\t\t\t);\r\n\t\t\r\n\t\tcodes.push_back( ct);\r\n\r\n\t}\r\n\r\n\ttoDoForElse = ElseType :: AssignValue;\r\n\tcodeForElse = std::numeric_limits<TCode>::quiet_NaN();\r\n\r\n}\r\n\r\n// code\u306b\u306a\u308a\u3046\u308b\u5024\u306evector\u3092\u8fd4\u3059\u3002\r\n// \u30bd\u30fc\u30c8\u3057\u3066\u8fd4\u3059\u3002\r\n// \u305f\u3060\u3057\u3001Else\u306e\u5834\u5408\u306ecode\u306f\u542b\u3081\u306a\u3044\u3002\r\ntemplate <typename TOrigin, typename TCode>\r\nstd::vector <TCode> \r\nRecodeTable <TOrigin, TCode> :: \r\ngetPossibleCodeVec( void) const\r\n{\r\n\r\n\tstd::vector <TCode> ret;\r\n\tret.clear();\r\n\r\n\tfor ( auto c : codes){\r\n\t\tret.push_back( c.codeAssigned);\r\n\t}\r\n\tstd::sort( ret.begin(), ret.end());\r\n\r\n\treturn ret;\r\n\r\n}\r\n\r\n// v\u306b\u5bfe\u5fdc\u3059\u308b\u30b3\u30fc\u30c9\u3092\u8fd4\u3059\u3002\r\ntemplate <typename TOrigin, typename TCode>\r\nTCode\r\nRecodeTable <TOrigin, TCode> :: \r\ngetCodeForValue( TOrigin v)\r\nconst\r\n{\r\n\r\n\tfor ( auto c : codes){\r\n\t\tif ( c.correspond( v) == true){\r\n\t\t\treturn c.codeAssigned;\r\n\t\t}\r\n\t}\r\n\r\n\tTCode ret;\r\n\r\n\tswitch( toDoForElse){\r\n\t\tcase ElseType :: Copy:\r\n\t\t\tret = v;\r\n\t\t\tbreak;\r\n\t\tcase ElseType :: AssignValue:\r\n\t\t\tret = codeForElse;\r\n\t\t\tbreak;\r\n\t}\r\n\r\n\treturn ret;\r\n\r\n}\r\n\r\n// code0\u306b\u5bfe\u5fdc\u3059\u308bleft\u3068right\u3092\u8fd4\u3059\u3002\r\n// code0\u306b\u5bfe\u5fdc\u3059\u308b\u7bc4\u56f2\u304c\u767b\u9332\u3055\u308c\u3066\u3044\u306a\u3051\u308c\u3070\u3001nan\u3092\u8fd4\u3059\u3002\r\ntemplate <typename TOrigin, typename TCode>\r\nvoid\r\nRecodeTable <TOrigin, TCode> :: \r\ngetLeftRightForCode( TOrigin &lret, TOrigin &rret, TCode code0)\r\nconst\r\n{\r\n\r\n\tfor ( const auto &c : codes){\r\n\t\tif ( c.codeAssigned == code0){\r\n\t\t\tlret = c.left;\r\n\t\t\trret = c.right;\r\n\t\t\treturn; \r\n\t\t}\r\n\t}\r\n\r\n\tlret = std::numeric_limits<TOrigin>::quiet_NaN();\r\n\trret = std::numeric_limits<TOrigin>::quiet_NaN();\r\n\r\n}\r\n\r\n// code0\u306b\u5bfe\u5fdc\u3059\u308b\u30e9\u30d9\u30eb\u3092\u8fd4\u3059\u3002\r\n// code0\u306b\u5bfe\u5fdc\u3059\u308b\u7bc4\u56f2\u304c\u767b\u9332\u3055\u308c\u3066\u3044\u306a\u3051\u308c\u3070\u3001\u7a7a\u306estring\u3092\u8fd4\u3059\u3002\r\ntemplate <typename TOrigin, typename TCode>\r\nstd::string\r\nRecodeTable <TOrigin, TCode> :: \r\ngetRangeLabelForCode( TCode code0)\r\nconst\r\n{\r\n\r\n\tfor ( const auto &c : codes){\r\n\t\tif ( c.codeAssigned == code0){\r\n\t\t\treturn c.getRangeLabel();\r\n\t\t}\r\n\t}\r\n\r\n\treturn string( \"\");\r\n\r\n}\r\n\r\n// \u30b9\u30c8\u30ea\u30fc\u30e0\u306b\u51fa\u529b\u3059\u308b\u3002\r\n// \u30b9\u30da\u30fc\u30b9\u3067\u30d1\u30c7\u30a3\u30f3\u30b0\u306f\u3057\u306a\u3044\u3002sep\u3067\u533a\u5207\u308b\u3002\r\ntemplate <typename TOrigin, typename TCode>\r\nvoid\r\nRecodeTable <TOrigin, TCode> :: \r\nprint(\r\n\tostream &os,\r\n\tstring sep // = \",\"s\r\n)\r\nconst\r\n{\r\n\r\n\tos << \"Code\" << sep << \"Range\" << std::endl;\r\n\tfor ( auto c : codes){\r\n\t\tos << c.codeAssigned;\r\n\t\tos << sep;\r\n\t\tos << c.getRangeLabel();\r\n\t\tos << endl;\r\n\t}\r\n\r\n}\r\n\r\n#endif /* kstat_cpp_include_guard */\r\n", "meta": {"hexsha": "1bd25ed99ad6f59e8fec7a195b7a450a6caecbbb", "size": 24881, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "k09/kstat02.cpp", "max_stars_repo_name": "kojiynet/koli", "max_stars_repo_head_hexsha": "681f9c1b1a291a36e1f0eee43c45b37567d2661e", "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": "k09/kstat02.cpp", "max_issues_repo_name": "kojiynet/koli", "max_issues_repo_head_hexsha": "681f9c1b1a291a36e1f0eee43c45b37567d2661e", "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": "k09/kstat02.cpp", "max_forks_repo_name": "kojiynet/koli", "max_forks_repo_head_hexsha": "681f9c1b1a291a36e1f0eee43c45b37567d2661e", "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": 20.4781893004, "max_line_length": 94, "alphanum_fraction": 0.6121538523, "num_tokens": 7982, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587586, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.48199999999785753}}
{"text": "//          Copyright Rein Halbersma 2014-2021.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n#include <xstd/type_traits.hpp>         // is_specialization_of, is_integral_constant\n#include <boost/test/unit_test.hpp>     // BOOST_AUTO_TEST_SUITE, BOOST_AUTO_TEST_SUITE_END, BOOST_AUTO_TEST_CASE, BOOST_CHECK\n#include <complex>                      // complex\n#include <type_traits>                  // integral_constant\n\nusing namespace xstd;\n\nBOOST_AUTO_TEST_SUITE(TypeTraits)\n\ntemplate<class T>\nusing is_complex = is_specialization_of<T, std::complex>;\n\ntemplate<class T>\ninline constexpr auto is_complex_v = is_complex<T>::value;\n\nBOOST_AUTO_TEST_CASE(IsSpecializationOf)\n{\n        BOOST_CHECK((    is_complex_v<std::complex<int>>));\n        BOOST_CHECK((not is_complex_v<int>));\n}\n\ntemplate<int N>\nusing int_ = std::integral_constant<int, N>;\n\nBOOST_AUTO_TEST_CASE(IsIntegralConstant)\n{\n        BOOST_CHECK((    is_integral_constant_v<std:: true_type, bool>));\n        BOOST_CHECK((    is_integral_constant_v<std::false_type, bool>));\n        BOOST_CHECK((not is_integral_constant_v<bool, bool>));\n\n        BOOST_CHECK((    is_integral_constant_v<int_<0>, int>));\n        BOOST_CHECK((not is_integral_constant_v<int,     int>));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "56bcf6185b04edce712d95e20c172d2c30204432", "size": 1386, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/src/type_traits.cpp", "max_stars_repo_name": "rhalbersma/xstd", "max_stars_repo_head_hexsha": "fd7b00b39f8626ce11b4b7b21760c15a20838015", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2016-11-22T10:38:19.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-12T14:30:10.000Z", "max_issues_repo_path": "test/src/type_traits.cpp", "max_issues_repo_name": "rhalbersma/xstd", "max_issues_repo_head_hexsha": "fd7b00b39f8626ce11b4b7b21760c15a20838015", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 21.0, "max_issues_repo_issues_event_min_datetime": "2017-01-09T07:20:47.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-02T19:31:47.000Z", "max_forks_repo_path": "test/src/type_traits.cpp", "max_forks_repo_name": "rhalbersma/xstd", "max_forks_repo_head_hexsha": "fd7b00b39f8626ce11b4b7b21760c15a20838015", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-06-18T21:53:47.000Z", "max_forks_repo_forks_event_max_datetime": "2017-06-18T21:53:47.000Z", "avg_line_length": 33.8048780488, "max_line_length": 126, "alphanum_fraction": 0.7077922078, "num_tokens": 318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587586, "lm_q2_score": 0.6893056104028797, "lm_q1q2_score": 0.48199999553481987}}
{"text": "#include \"gtest/gtest.h\"\n#include <Eigen/Core>\n#include \"Mesh.h\"\n#include \"MeshFactory.h\"\n\nnamespace {\n    using namespace Geotree;\n\n    class MeshTest : public ::testing::Test {\n    protected:\n    };\n\n  TEST_F(MeshTest, getSegments)\n  {\n    MeshFactory factory;\n    Mesh tetra = factory.tetra(1);\n\n    std::vector<Segment> segments;\n    tetra.getSegments(segments);\n\n    EXPECT_EQ(segments.size(), 6);\n  }\n\n  TEST_F(MeshTest, boundingBox)\n  {\n    MeshFactory factory;\n    Mesh tetra = factory.tetra(1);\n\n    Cube box = tetra.boundingBox();\n\n    EXPECT_EQ(box.p0, Vector3d(0.0, 0.0, 0.0));\n    EXPECT_EQ(box.p1, Vector3d(1.0, 1.0, 1.0));\n  }\n\n  TEST_F(MeshTest, boundingBoxNegative)\n  {\n    MeshFactory factory;\n    Mesh tetra = factory.tetra(2);\n\n    tetra.translate(Vector3d(-10, -20, -30));\n    Cube box = tetra.boundingBox();\n\n    EXPECT_EQ(box.p0, Vector3d(-10.0, -20.0, -30.0));\n    EXPECT_EQ(box.p1, Vector3d(-8.0, -18.0, -28.0));\n  }\n\n  TEST_F(MeshTest, boundingBoxZero)\n  {\n    Mesh zero;\n\n    Cube box = zero.boundingBox();\n    \n    EXPECT_EQ(box.p0, Vector3d(0.0, 0.0, 0.0));\n    EXPECT_EQ(box.p1, Vector3d(0.0, 0.0, 0.0));\n  }\n}\n", "meta": {"hexsha": "57ec0f74037278d25bf82a3262dc17af80de4b9f", "size": 1141, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/mesh.cc", "max_stars_repo_name": "untaugh/geotree", "max_stars_repo_head_hexsha": "4600a1cb4115094ed5c4c1500c6221a458e68be8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-07-27T00:58:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-20T22:26:10.000Z", "max_issues_repo_path": "test/mesh.cc", "max_issues_repo_name": "untaugh/geotree", "max_issues_repo_head_hexsha": "4600a1cb4115094ed5c4c1500c6221a458e68be8", "max_issues_repo_licenses": ["MIT"], "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/mesh.cc", "max_forks_repo_name": "untaugh/geotree", "max_forks_repo_head_hexsha": "4600a1cb4115094ed5c4c1500c6221a458e68be8", "max_forks_repo_licenses": ["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.0175438596, "max_line_length": 53, "alphanum_fraction": 0.624890447, "num_tokens": 381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056040203135, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.4819999910717821}}
{"text": "#pragma once\n\n#include <ros/ros.h>\n\n#include <memory>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/StdVector>\n\n#include \"optimizer/CHOMP_dynamic_trajectory.hpp\"\n#include \"utils/utility_functions.hpp\"\n\nnamespace optimized_motion_planner {\n\nclass CHOMPDynamicCost {\npublic:\n\tCHOMPDynamicCost(const std::shared_ptr<CHOMPDynamicTrajectyory>& trajectory, const std::vector<double>& derivative_costs, double ridge_factor = 0.0);\n\t~CHOMPDynamicCost() = default;\n\n\tdouble getMaxQuadCostInvValue() const {\n\t\treturn this->quad_cost_inv_.maxCoeff();\n\t};\n\tEigen::MatrixXd getQuadraticCostInverse() const {\n\t\treturn this->quad_cost_inv_;\n\t}\n\tEigen::MatrixXd getQuadraticCost() const {\n\t\treturn this->quad_cost_;\n\t}\n\tvoid scale(double scale);\n\tdouble getCost(const Eigen::MatrixXd::ColXpr& joint_trajectory) const;\n\n\tEigen::MatrixXd getDerivative(const Eigen::MatrixXd::ColXpr& joint_trajectory) const;\nprivate:\n\tEigen::MatrixXd quad_cost_full_;\n\tEigen::MatrixXd quad_cost_;\n\tEigen::MatrixXd quad_cost_inv_;\n\n\tEigen::MatrixXd getDiffMatrix(int size, const double* diff_rule) const;\n};\n}", "meta": {"hexsha": "9f10a210ed138f144e25404a12ba15c5fd01246c", "size": 1089, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/optimizer/CHOMP_dynamic_cost.hpp", "max_stars_repo_name": "test-bai-cpu/optimized_motion_planner", "max_stars_repo_head_hexsha": "fe6c62b285a8449b1c26ca2e8b4fa7fe57aa5f96", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-17T00:46:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-17T00:46:59.000Z", "max_issues_repo_path": "include/optimizer/CHOMP_dynamic_cost.hpp", "max_issues_repo_name": "test-bai-cpu/optimized_motion_planner", "max_issues_repo_head_hexsha": "fe6c62b285a8449b1c26ca2e8b4fa7fe57aa5f96", "max_issues_repo_licenses": ["MIT"], "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/optimizer/CHOMP_dynamic_cost.hpp", "max_forks_repo_name": "test-bai-cpu/optimized_motion_planner", "max_forks_repo_head_hexsha": "fe6c62b285a8449b1c26ca2e8b4fa7fe57aa5f96", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-24T07:58:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-24T07:58:59.000Z", "avg_line_length": 26.5609756098, "max_line_length": 150, "alphanum_fraction": 0.7786960514, "num_tokens": 263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672320414787, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.4819580815998463}}
{"text": "#include \"llr.h\"\n\n#include \"threads.h\"\n#include <Eigen/SVD>\n#include <random>\n\nCx4 llr(Cx4 const &x, float const l, Index const p)\n{\n  Index const K = x.dimension(0);\n  Log::Print(FMT_STRING(\"LLR regularization patch size {} lamdba {}\"), p, l);\n  Cx4 lr(x.dimensions());\n  lr.setZero();\n\n  auto zTask = [&](Index const lo, Index const hi) {\n    for (Index iz = lo; iz < hi; iz++) {\n      for (Index iy = 0; iy < x.dimension(2) - p; iy++) {\n        for (Index ix = 0; ix < x.dimension(1) - p; ix++) {\n          Cx4 px = x.slice(Sz4{0, ix, iy, iz}, Sz4{K, p, p, p});\n          Eigen::Map<Eigen::MatrixXcf> patch(px.data(), K, p * p * p);\n          auto const svd = patch.transpose().bdcSvd(Eigen::ComputeThinU | Eigen::ComputeThinV);\n          // Soft-threhold svals\n          Eigen::ArrayXf s = svd.singularValues();\n          float const sl = s.sum() * l;\n          s = s * (s.abs() - sl) / s.abs();\n          s = (s > sl).select(s, 0.f);\n          patch.transpose() = svd.matrixU() * s.matrix().asDiagonal() * svd.matrixV().adjoint();\n          lr.chip<3>(iz + p / 2).chip<2>(iy + p / 2).chip<1>(ix + p / 2) =\n            px.chip<3>(p / 2).chip<2>(p / 2).chip<1>(p / 2);\n        }\n      }\n    }\n  };\n  auto const now = Log::Now();\n  Threads::RangeFor(zTask, 0, x.dimension(3) - p);\n  Log::Print(FMT_STRING(\"LLR Regularization took {}\"), Log::ToNow(now));\n  return lr;\n}\n\nCx4 llr_patch(Cx4 const &x, float const l, Index const p)\n{\n  std::array<Index, 3> nP, shift;\n  std::random_device rd;\n  std::mt19937 gen(rd());\n  std::uniform_int_distribution<> int_dist(0, p - 1);\n  for (Index ii = 0; ii < 3; ii++) {\n    if (x.dimension(ii + 1) % p != 0) {\n      Log::Fail(\n        FMT_STRING(\"Patch size {} does not evenly divide {} (dimension {})\"),\n        p,\n        x.dimension(ii + 1),\n        ii);\n    }\n    nP[ii] = (x.dimension(ii + 1) / p) - 1;\n    shift[ii] = int_dist(gen);\n  }\n  Index const K = x.dimension(0);\n  Index const pSz = p * p * p;\n  Cx4 lr(x.dimensions());\n  lr.setZero();\n  auto zTask = [&](Index const lo, Index const hi) {\n    for (Index iz = lo; iz < hi; iz++) {\n      for (Index iy = 0; iy < nP[1]; iy++) {\n        for (Index ix = 0; ix < nP[0]; ix++) {\n          Cx4 px = x.slice(\n            Sz4{0, ix * p + shift[0], iy * p + shift[1], iz * p + shift[2]}, Sz4{K, p, p, p});\n          Eigen::Map<Eigen::MatrixXcf> patch(px.data(), K, pSz);\n          auto const svd = patch.transpose().bdcSvd(Eigen::ComputeThinU | Eigen::ComputeThinV);\n          // Soft-threhold svals\n          Eigen::ArrayXf s = svd.singularValues();\n          float const sl = s(0) * l;\n          s = s * (s.abs() - sl) / s.abs();\n          s = (s > sl).select(s, 0.f);\n          patch.transpose() = svd.matrixU() * s.matrix().asDiagonal() * svd.matrixV().adjoint();\n          lr.slice(\n            Sz4{0, ix * p + shift[0], iy * p + shift[1], iz * p + shift[2]}, Sz4{K, p, p, p}) = px;\n        }\n      }\n    }\n  };\n  auto const now = Log::Now();\n  zTask(0, nP[2]);\n  // Threads::RangeFor(zTask, nP[2]);\n  Log::Print(FMT_STRING(\"LLR Regularization took {}\"), Log::ToNow(now));\n  return lr;\n}", "meta": {"hexsha": "12bc01f486a087fa9682c16e0b4a78146f191f6a", "size": 3083, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/algo/llr.cpp", "max_stars_repo_name": "pfuchs/riesling", "max_stars_repo_head_hexsha": "2e0f12f5cd1943cb6e96eca40f4e68ef88e12130", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/algo/llr.cpp", "max_issues_repo_name": "pfuchs/riesling", "max_issues_repo_head_hexsha": "2e0f12f5cd1943cb6e96eca40f4e68ef88e12130", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/algo/llr.cpp", "max_forks_repo_name": "pfuchs/riesling", "max_forks_repo_head_hexsha": "2e0f12f5cd1943cb6e96eca40f4e68ef88e12130", "max_forks_repo_licenses": ["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.2705882353, "max_line_length": 99, "alphanum_fraction": 0.5225429776, "num_tokens": 1042, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.4819580705725636}}
{"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_GAUSS_HPP\n#define BOOST_GEOMETRY_PROJECTIONS_IMPL_PJ_GAUSS_HPP\n\n\n#include <boost/geometry/util/math.hpp>\n\n\nnamespace boost { namespace geometry { namespace projections {\n\nnamespace detail { namespace gauss {\n\n\nstatic const int MAX_ITER = 20;\n\nstruct GAUSS\n{\n    double C;\n    double K;\n    double e;\n    double ratexp;\n};\n\nstatic const double DEL_TOL = 1e-14;\n\ninline double srat(double esinp, double exp)\n{\n    return (pow((1.0 - esinp) / (1.0 + esinp), exp));\n}\n\ninline GAUSS gauss_ini(double e, double phi0, double &chi, double &rc)\n{\n    using std::asin;\n    using std::cos;\n    using std::sin;\n    using std::sqrt;\n    using std::tan;\n\n    double sphi = 0;\n    double cphi = 0;\n    double es = 0;\n\n    GAUSS en;\n    es = e * e;\n    en.e = e;\n    sphi = sin(phi0);\n    cphi = cos(phi0);\n    cphi *= cphi;\n\n    rc = sqrt(1.0 - es) / (1.0 - es * sphi * sphi);\n    en.C = sqrt(1.0 + es * cphi * cphi / (1.0 - es));\n    chi = asin(sphi / en.C);\n    en.ratexp = 0.5 * en.C * e;\n    en.K = tan(0.5 * chi + detail::FORTPI)\n           / (pow(tan(0.5 * phi0 + detail::FORTPI), en.C) * srat(en.e * sphi, en.ratexp));\n\n    return en;\n}\n\ntemplate <typename T>\ninline void gauss(GAUSS const& en, T& lam, T& phi)\n{\n    phi = 2.0 * atan(en.K * pow(tan(0.5 * phi + FORTPI), en.C)\n          * srat(en.e * sin(phi), en.ratexp) ) - geometry::math::half_pi<double>();\n\n    lam *= en.C;\n}\n\ntemplate <typename T>\ninline void inv_gauss(GAUSS const& en, T& lam, T& phi)\n{\n    lam /= en.C;\n    const double num = pow(tan(0.5 * phi + FORTPI) / en.K, 1.0 / en.C);\n\n    int i = 0;\n    for (i = MAX_ITER; i; --i)\n    {\n        const double elp_phi = 2.0 * atan(num * srat(en.e * sin(phi), - 0.5 * en.e)) - geometry::math::half_pi<double>();\n\n        if (geometry::math::abs(elp_phi - phi) < DEL_TOL)\n        {\n            break;\n        }\n        phi = elp_phi;\n    }\n\n    /* convergence failed */\n    if (!i)\n    {\n        throw proj_exception(-17);\n    }\n}\n\n}} // namespace detail::gauss\n}}} // namespace boost::geometry::projections\n\n#endif // BOOST_GEOMETRY_PROJECTIONS_IMPL_PJ_GAUSS_HPP\n", "meta": {"hexsha": "c8fc8fd4c8106341f70de6525de91bf585cfb2a5", "size": 3827, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3party/boost/boost/geometry/extensions/gis/projections/impl/pj_gauss.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_gauss.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_gauss.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": 29.213740458, "max_line_length": 121, "alphanum_fraction": 0.664489156, "num_tokens": 1076, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.4819580705725636}}
{"text": "#include <simpleuv/meshdatatype.h>\n#include <Eigen/Dense>\n\nnamespace simpleuv\n{\n\nfloat dotProduct(const Vector3 &first, const Vector3 &second)\n{\n    Eigen::Vector3d v(first.xyz[0], first.xyz[1], first.xyz[2]);\n    Eigen::Vector3d w(second.xyz[0], second.xyz[1], second.xyz[2]);\n    return v.dot(w);\n}\n\nVector3 crossProduct(const Vector3 &first, const Vector3 &second)\n{\n    Eigen::Vector3d v(first.xyz[0], first.xyz[1], first.xyz[2]);\n    Eigen::Vector3d w(second.xyz[0], second.xyz[1], second.xyz[2]);\n    auto u = v.cross(w);\n    Vector3 result;\n    result.xyz[0] = u.x();\n    result.xyz[1] = u.y();\n    result.xyz[2] = u.z();\n    return result;\n}\n\n}\n", "meta": {"hexsha": "5b9815edf4e905cd0f1a33df1c0ba37fdeb9bfd2", "size": 653, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "thirdparty/simpleuv/simpleuv/meshdatatype.cpp", "max_stars_repo_name": "MelvinG24/dust3d", "max_stars_repo_head_hexsha": "c4936fd900a9a48220ebb811dfeaea0effbae3ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2392.0, "max_stars_repo_stars_event_min_datetime": "2016-12-17T14:14:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T19:40:40.000Z", "max_issues_repo_path": "thirdparty/simpleuv/simpleuv/meshdatatype.cpp", "max_issues_repo_name": "MelvinG24/dust3d", "max_issues_repo_head_hexsha": "c4936fd900a9a48220ebb811dfeaea0effbae3ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 106.0, "max_issues_repo_issues_event_min_datetime": "2018-04-19T17:47:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-01T19:44:11.000Z", "max_forks_repo_path": "thirdparty/simpleuv/simpleuv/meshdatatype.cpp", "max_forks_repo_name": "MelvinG24/dust3d", "max_forks_repo_head_hexsha": "c4936fd900a9a48220ebb811dfeaea0effbae3ee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 184.0, "max_forks_repo_forks_event_min_datetime": "2017-11-15T09:55:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T16:30:46.000Z", "avg_line_length": 24.1851851852, "max_line_length": 67, "alphanum_fraction": 0.6431852986, "num_tokens": 197, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.4819580705725636}}
{"text": "/*\n    This file is part of Mitsuba, a physically based rendering system.\n\n    Copyright (c) 2007-2014 by Wenzel Jakob and others.\n\n    Mitsuba is free software; you can redistribute it and/or modify\n    it under the terms of the GNU General Public License Version 3\n    as published by the Free Software Foundation.\n\n    Mitsuba is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program. If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <mitsuba/core/shvector.h>\n#include <mitsuba/core/transform.h>\n#include <boost/math/special_functions/factorials.hpp>\n\nMTS_NAMESPACE_BEGIN\n\nFloat *SHVector::m_normalization = NULL;\n\nSHVector::SHVector(Stream *stream) {\n    m_bands = stream->readInt();\n    unsigned int size = m_bands*m_bands;\n    m_coeffs.resize(size);\n    for (size_t i=0; i<size; ++i)\n        m_coeffs[i] = stream->readFloat();\n}\n\nvoid SHVector::serialize(Stream *stream) const {\n    stream->writeInt(m_bands);\n    for (size_t i=0; i<(size_t) m_coeffs.size(); ++i)\n        stream->writeFloat(m_coeffs[i]);\n}\n\nbool SHVector::isAzimuthallyInvariant() const {\n    for (int l=0; l<m_bands; ++l) {\n        for (int m=1; m<=l; ++m) {\n            if (std::abs(operator()(l, -m)) > Epsilon\n             || std::abs(operator()(l, m)) > Epsilon)\n                return false;\n        }\n    }\n    return true;\n}\n\nFloat SHVector::eval(Float theta, Float phi) const {\n    Float result = 0;\n    Float cosTheta = std::cos(theta);\n    Float *sinPhi = (Float *) alloca(sizeof(Float)*m_bands),\n          *cosPhi = (Float *) alloca(sizeof(Float)*m_bands);\n\n    for (int m=0; m<m_bands; ++m) {\n        sinPhi[m] = std::sin((m+1) * phi);\n        cosPhi[m] = std::cos((m+1) * phi);\n    }\n\n    for (int l=0; l<m_bands; ++l) {\n        for (int m=1; m<=l; ++m) {\n            Float L = legendreP(l, m, cosTheta) * normalization(l, m);\n            result += operator()(l, -m) * SQRT_TWO * sinPhi[m-1] * L;\n            result += operator()(l, m)  * SQRT_TWO * cosPhi[m-1] * L;\n        }\n\n        result += operator()(l, 0) * legendreP(l, 0, cosTheta) * normalization(l, 0);\n    }\n    return result;\n}\n\nFloat SHVector::findMinimum(int res = 32) const {\n    Float hExt = (Float) M_PI / res, hInt = (2 * (Float) M_PI)/(res*2);\n    Float minimum = std::numeric_limits<Float>::infinity();\n\n    for (int i=0; i<=res; ++i) {\n        Float theta = hExt*i;\n        for (int j=0; j<=res*2; ++j) {\n            Float phi = hInt*j;\n            minimum = std::min(minimum, eval(theta, phi));\n        }\n    }\n\n    return minimum;\n}\n\nvoid SHVector::addOffset(Float value) {\n    operator()(0, 0) += 2 * value * (Float) std::sqrt(M_PI);\n}\n\nFloat SHVector::eval(const Vector &v) const {\n    Float result = 0;\n    Float cosTheta = v.z, phi = std::atan2(v.y, v.x);\n    if (phi < 0) phi += 2*M_PI;\n    Float *sinPhi = (Float *) alloca(sizeof(Float)*m_bands),\n          *cosPhi = (Float *) alloca(sizeof(Float)*m_bands);\n\n    for (int m=0; m<m_bands; ++m) {\n        sinPhi[m] = std::sin((m+1) * phi);\n        cosPhi[m] = std::cos((m+1) * phi);\n    }\n\n    for (int l=0; l<m_bands; ++l) {\n        for (int m=1; m<=l; ++m) {\n            Float L = legendreP(l, m, cosTheta) * normalization(l, m);\n            result += operator()(l, -m) * SQRT_TWO * sinPhi[m-1] * L;\n            result += operator()(l, m)  * SQRT_TWO * cosPhi[m-1] * L;\n        }\n\n        result += operator()(l, 0) * legendreP(l, 0, cosTheta) * normalization(l, 0);\n    }\n    return result;\n}\n\nFloat SHVector::evalAzimuthallyInvariant(Float theta, Float phi) const {\n    Float result = 0, cosTheta = std::cos(theta);\n    for (int l=0; l<m_bands; ++l)\n        result += operator()(l, 0) * legendreP(l, 0, cosTheta) * normalization(l, 0);\n    return result;\n}\n\nFloat SHVector::evalAzimuthallyInvariant(const Vector &v) const {\n    Float result = 0, cosTheta = v.z;\n    for (int l=0; l<m_bands; ++l)\n        result += operator()(l, 0) * legendreP(l, 0, cosTheta) * normalization(l, 0);\n    return result;\n}\n\nvoid SHVector::normalize() {\n    Float correction = 1/(2 * (Float) std::sqrt(M_PI)*operator()(0,0));\n\n    for (size_t i=0; i<(size_t) m_coeffs.size(); ++i)\n        m_coeffs[i] *= correction;\n}\n\nvoid SHVector::convolve(const SHVector &kernel) {\n    SAssert(kernel.getBands() == m_bands);\n\n    for (int l=0; l<m_bands; ++l) {\n        Float alpha = std::sqrt(4 * (Float) M_PI / (2*l + 1));\n        for (int m=-l; m<=l; ++m)\n            operator()(l, m) *= alpha * kernel(l, 0);\n    }\n}\n\nMatrix3x3 SHVector::mu2() const {\n    const Float sqrt5o3 = std::sqrt((Float) 5/ (Float) 3);\n    const Float sqrto3 = std::sqrt((Float) 1/ (Float) 3);\n    Matrix3x3 result;\n    result.setZero();\n\n    SAssert(m_bands > 0);\n    result(0, 0) = result(1, 1) =\n        result(2, 2) = sqrt5o3*operator()(0,0);\n\n    if (m_bands >= 3) {\n        result(0, 0) += -operator()(2,0)*sqrto3 + operator()(2,2);\n        result(0, 1) = operator()(2,-2);\n        result(0, 2) = -operator()(2, 1);\n        result(1, 0) = operator()(2,-2);\n        result(1, 1) += -operator()(2,0)*sqrto3 - operator()(2,2);\n        result(1, 2) = -operator()(2,-1);\n        result(2, 0) = -operator()(2, 1);\n        result(2, 1) = -operator()(2,-1);\n        result(2, 2) += 2*sqrto3*operator()(2,0);\n    }\n\n    return result * (2*std::sqrt((Float) M_PI / 15));\n}\n\nstd::string SHVector::toString() const {\n    std::ostringstream oss;\n    oss << \"SHVector[bands=\" << m_bands << \", {\";\n    int pos = 0;\n    for (int i=0; i<m_bands; ++i) {\n        oss << \"{\";\n        for (int j=0, total=i*2+1; j<total; ++j) {\n            oss << m_coeffs[pos++];\n            if (j+1 < total)\n                oss << \", \";\n        }\n        oss << \"}\";\n        if (i+1 < m_bands)\n            oss << \", \";\n    }\n    oss << \"}]\";\n    return oss.str();\n}\n\nFloat SHVector::computeNormalization(int l, int m) {\n    SAssert(m>=0);\n    return std::sqrt(\n            ((2*l+1) * boost::math::factorial<Float>(l-m))\n        /    (4 * (Float) M_PI * boost::math::factorial<Float>(l+m)));\n}\n\nvoid SHVector::staticInitialization() {\n    m_normalization = new Float[SH_NORMTBL_SIZE*(SH_NORMTBL_SIZE+1)/2];\n    for (int l=0; l<SH_NORMTBL_SIZE; ++l)\n        for (int m=0; m<=l; ++m)\n            m_normalization[l*(l+1)/2 + m] = computeNormalization(l, m);\n}\n\nvoid SHVector::staticShutdown() {\n    delete[] m_normalization;\n    m_normalization = NULL;\n}\n\nstruct RotationBlockHelper {\n    const SHRotation::Matrix &M1, &Mp;\n    SHRotation::Matrix &Mn;\n    int prevLevel, level;\n\n    inline RotationBlockHelper(\n        const SHRotation::Matrix &M1,\n        const SHRotation::Matrix &Mp,\n        SHRotation::Matrix &Mn)\n        : M1(M1), Mp(Mp), Mn(Mn), prevLevel((int) Mp.rows()/2),\n        level((int) Mp.rows()/2+1) { }\n\n    inline Float delta(int i, int j) const {\n        return (i == j) ? (Float) 1 : (Float) 0;\n    }\n\n    inline Float U(int l, int m, int n) const {\n        return P(l, m, n, 0);\n    }\n\n    inline Float V(int l, int m, int n) const {\n        if (m == 0) {\n            return P(l, 1, n, 1) + P(l, -1, n, -1);\n        } else if (m > 0) {\n            if (m == 1)\n                return SQRT_TWO * P(l, 0, n, 1);\n            else\n                return P(l, m-1, n, 1) - P(l, -m+1, n, -1);\n        } else {\n            if (m == -1)\n                return SQRT_TWO * P(l, 0, n, -1);\n            else\n                return P(l, -m-1, n, -1) + P(l, m+1, n, 1);\n        }\n    }\n\n    inline Float W(int l, int m, int n) const {\n        if (m > 0) {\n            return P(l, m+1, n, 1) + P(l, -m-1, n, -1);\n        } else {\n            return P(l, m-1, n, 1) - P(l, -m+1, n, -1);\n        }\n    }\n\n    inline Float u(int l, int m, int n) const {\n        int denom = (std::abs(n) == l) ? (2*l*(2*l-1)) : ((l+n)*(l-n));\n        return std::sqrt((Float) ((l+m)*(l-m)) / (Float) denom);\n    }\n\n    inline Float v(int l, int m, int n) const {\n        int denom = (std::abs(n) == l) ? (2*l*(2*l-1)) : ((l+n)*(l-n)), absM = std::abs(m);\n        return .5f * (1-2*delta(m, 0)) * std::sqrt(\n            (Float) ((1+delta(m, 0)) * (l+absM-1)*(l+absM)) / (Float) denom\n        );\n    }\n\n    inline Float w(int l, int m, int n) const {\n        if (m == 0)\n            return 0.0f;\n        int absM = std::abs(m);\n        int denom = (std::abs(n) < l) ? ((l+n)*(l-n)) : (2*l*(2*l-1));\n\n        return -.5f * std::sqrt((Float) ((l-absM-1)*(l-absM)) / (Float) denom);\n    }\n\n    inline Float P(int l, int m, int n, int i) const {\n        if (std::abs(n) < l)\n            return R(i, 0) * M(m, n);\n        else if (n == l)\n            return R(i, 1) * M(m, l-1) - R(i, -1) * M(m, -l+1);\n        else if (n == -l)\n            return R(i, 1) * M(m, -l+1) + R(i, -1) * M(m, l-1);\n        else {\n            SLog(EError, \"Internal error!\");\n            return 0.0f;\n        }\n    }\n\n    inline Float R(int m, int n) const {\n        return M1(m+1, n+1);\n    }\n\n    inline Float M(int m, int n) const {\n        return Mp(m+prevLevel, n+prevLevel);\n    }\n\n    void compute() {\n        for (int m=-level; m<=level; ++m) {\n            for (int n=-level; n<=level; ++n) {\n                Float uVal = u(level, m, n), vVal = v(level, m, n), wVal = w(level, m, n);\n                Mn(m+level, n+level) =\n                      (uVal != 0 ? (uVal * U(level, m, n)) : (Float) 0)\n                    + (vVal != 0 ? (vVal * V(level, m, n)) : (Float) 0)\n                    + (wVal != 0 ? (wVal * W(level, m, n)) : (Float) 0);\n            }\n        }\n    }\n};\n\nvoid SHVector::rotationBlock(\n        const SHRotation::Matrix &M1,\n        const SHRotation::Matrix &Mp,\n        SHRotation::Matrix &Mn) {\n    RotationBlockHelper rbh(M1, Mp, Mn);\n    rbh.compute();\n}\n\nvoid SHVector::rotation(const Transform &t, SHRotation &rot) {\n    rot.blocks[0](0, 0) = 1;\n    if (rot.blocks.size() <= 1)\n        return;\n\n    const Matrix4x4 &trafo = t.getMatrix();\n    rot.blocks[1](0, 0) =  trafo.m[1][1];\n    rot.blocks[1](0, 1) = -trafo.m[2][1];\n    rot.blocks[1](0, 2) =  trafo.m[0][1];\n    rot.blocks[1](1, 0) = -trafo.m[1][2];\n    rot.blocks[1](1, 1) =  trafo.m[2][2];\n    rot.blocks[1](1, 2) = -trafo.m[0][2];\n    rot.blocks[1](2, 0) =  trafo.m[1][0];\n    rot.blocks[1](2, 1) = -trafo.m[2][0];\n    rot.blocks[1](2, 2) =  trafo.m[0][0];\n\n    if (rot.blocks.size() <= 2)\n        return;\n\n    for (size_t i=2; i<rot.blocks.size(); ++i)\n        rotationBlock(rot.blocks[1], rot.blocks[i-1], rot.blocks[i]);\n}\n\nvoid SHRotation::operator()(const SHVector &source, SHVector &target) const {\n    SAssert(source.getBands() == target.getBands());\n    for (int l=0; l<source.getBands(); ++l) {\n        const SHRotation::Matrix &M = blocks[l];\n        for (int m1=-l; m1<=l; ++m1) {\n            Float result = 0;\n            for (int m2=-l; m2<=l; ++m2)\n                result += M(m1+l, m2+l)*source(l, m2);\n            target(l, m1) = result;\n        }\n    }\n}\n\nSHSampler::SHSampler(int bands, int depth) : m_bands(bands), m_depth(depth) {\n    m_phiMap = new Float**[depth+1];\n    m_legendreMap = new Float**[depth+1];\n    m_normalization = new Float[m_bands*(m_bands+1)/2];\n    m_dataSize = m_bands*(m_bands+1)/2;\n    Assert(depth >= 1);\n\n    for (int i=0; i<=depth; ++i) {\n        int res = 1 << i;\n        Float zStep  = -2 / (Float) res;\n        Float phiStep = 2 * (Float) M_PI / (Float) res;\n        m_phiMap[i] = new Float*[res];\n        m_legendreMap[i] = new Float*[res];\n\n        for (int j=0; j<res; ++j) {\n            m_phiMap[i][j] = phiIntegrals(phiStep*j, phiStep*(j+1));\n            m_legendreMap[i][j] = legendreIntegrals(1+zStep*j, 1+zStep*(j+1));\n        }\n    }\n\n    for (int l=0; l<m_bands; ++l) {\n        for (int m=0; m<=l; ++m) {\n            Float normFactor = boost::math::tgamma_delta_ratio(\n                (Float) (l - m + 1), (Float) (2 * m), boost::math::policies::policy<>());\n            normFactor = std::sqrt(normFactor * (2 * l + 1) / (4 * (Float) M_PI));\n            if (m != 0)\n                normFactor *= SQRT_TWO;\n            m_normalization[I(l, m)] = normFactor;\n        }\n    }\n}\n\nstd::string SHSampler::toString() const {\n    std::ostringstream oss;\n    oss << \"SHSampler[bands=\" << m_bands << \", depth=\" << m_depth\n        << \", size=\" << (m_dataSize*sizeof(double))/1024 << \" KiB]\";\n    return oss.str();\n}\n\nFloat SHSampler::warp(const SHVector &f, Point2 &sample) const {\n    int i = 0, j = 0;\n    Float integral = 0, integralRoot = integrate(0, 0, 0, f);\n\n    for (int depth = 1; depth <= m_depth; ++depth) {\n        /* Do not sample negative areas */\n        Float q00 = std::max(integrate(depth, i, j, f), (Float) 0);\n        Float q10 = std::max(integrate(depth, i, j+1, f), (Float) 0);\n        Float q01 = std::max(integrate(depth, i+1, j, f), (Float) 0);\n        Float q11 = std::max(integrate(depth, i+1, j+1, f), (Float) 0);\n\n        Float z1 = q00 + q10, z2 = q01 + q11, phi1, phi2;\n        Float zNorm = (Float) 1 / (z1+z2);\n        z1 *= zNorm; z2 *= zNorm;\n\n        if (sample.x < z1) {\n            sample.x /= z1;\n            phi1 = q00; phi2 = q10;\n            i <<= 1;\n        } else {\n            sample.x = (sample.x - z1) / z2;\n            phi1 = q01; phi2 = q11;\n            i = (i+1) << 1;\n        }\n\n        Float phiNorm = (Float) 1 / (phi1+phi2);\n        Float phi1Norm = phi1*phiNorm, phi2Norm = phi2*phiNorm;\n\n        if (sample.y <= phi1Norm) {\n            sample.y /= phi1Norm;\n            j <<= 1;\n            integral = phi1;\n        } else {\n            sample.y = (sample.y - phi1Norm) / phi2Norm;\n            j = (j+1) << 1;\n            integral = phi2;\n        }\n    }\n\n    Float zStep = -2 / (Float) (1 << m_depth);\n    Float phiStep = 2 * (Float) M_PI / (Float) (1 << m_depth);\n    i >>= 1; j >>= 1;\n\n    Float z = 1 + zStep * i + zStep * sample.x;\n    sample.x = std::acos(z);\n    sample.y = phiStep * j + phiStep * sample.y;\n\n    /* PDF of sampling the mip-map bin */\n    Float pdfBin = integral/integralRoot;\n\n    /* Density within the bin */\n    Float density = -1/(zStep*phiStep);\n\n    return density*pdfBin;\n}\n\nSHSampler::~SHSampler() {\n    for (int i=0; i<=m_depth; ++i) {\n        int res = 1 << i;\n        for (int j=0; j<res; ++j) {\n            delete[] m_phiMap[i][j];\n            delete[] m_legendreMap[i][j];\n        }\n        delete[] m_phiMap[i];\n        delete[] m_legendreMap[i];\n    }\n    delete[] m_phiMap;\n    delete[] m_legendreMap;\n    delete[] m_normalization;\n}\n\nFloat SHSampler::integrate(int depth, int zBlock, int phiBlock, const SHVector &f) const {\n    Float result = 0;\n\n    for (int l=0; l<m_bands; ++l) {\n        for (int m=-l; m<=l; ++m) {\n            Float basisIntegral = m_normalization[I(l, std::abs(m))]\n                * lookupIntegral(depth, zBlock, phiBlock, l, m);\n            result += basisIntegral * f(l, m);\n        }\n    }\n    return result;\n}\n\nFloat *SHSampler::phiIntegrals(Float a, Float b) {\n    Float *sinPhiA = new Float[m_bands+1];\n    Float *sinPhiB = new Float[m_bands+1];\n    Float *cosPhiA = new Float[m_bands+1];\n    Float *cosPhiB = new Float[m_bands+1];\n    Float *result = new Float[2*m_bands+1];\n    m_dataSize += 2*m_bands+1;\n\n    cosPhiA[0] = 1; sinPhiA[0] = 0;\n    cosPhiB[0] = 1; sinPhiB[0] = 0;\n    cosPhiA[1] = std::cos(a);\n    sinPhiA[1] = std::sin(a);\n    cosPhiB[1] = std::cos(b);\n    sinPhiB[1] = std::sin(b);\n\n    for (int m=2; m<=m_bands; ++m) {\n        sinPhiA[m] = 2*sinPhiA[m-1]*cosPhiA[1] - sinPhiA[m-2];\n        sinPhiB[m] = 2*sinPhiB[m-1]*cosPhiB[1] - sinPhiB[m-2];\n\n        cosPhiA[m] = 2*cosPhiA[m-1]*cosPhiA[1] - cosPhiA[m-2];\n        cosPhiB[m] = 2*cosPhiB[m-1]*cosPhiB[1] - cosPhiB[m-2];\n    }\n\n    for (int m=-m_bands; m<=m_bands; ++m) {\n        if (m == 0)\n            result[P(m)] = b-a;\n        else if (m > 0)\n            result[P(m)] = (sinPhiB[m]-sinPhiA[m])/m;\n        else\n            result[P(m)] = (cosPhiB[-m]-cosPhiA[-m])/m;\n    }\n\n    delete[] sinPhiA;\n    delete[] sinPhiB;\n    delete[] cosPhiA;\n    delete[] cosPhiB;\n    return result;\n}\n\nFloat *SHSampler::legendreIntegrals(Float a, Float b) {\n    Float *P = new Float[m_bands*(m_bands+1)/2];\n    m_dataSize += m_bands*(m_bands+1)/2;\n\n    P[I(0, 0)] = b-a;\n\n    if (m_bands == 1)\n        return P;\n\n    Float *Pa = new Float[m_bands*(m_bands+1)/2];\n    Float *Pb = new Float[m_bands*(m_bands+1)/2];\n\n    for (int l=0; l<m_bands; ++l) {\n        for (int m=0; m<=l; ++m) {\n            Pa[I(l,m)] = legendreP(l, m, a);\n            Pb[I(l,m)] = legendreP(l, m, b);\n        }\n    }\n\n    P[I(1,0)] = (b*b - a*a)/2;\n    P[I(1,1)] = .5f * (-b*std::sqrt(1-b*b) - std::asin(b) + a*std::sqrt(1-a*a) + std::asin(a));\n\n    for (int l=2; l<m_bands; ++l) {\n        for (int m=0; m<=l-2; ++m) {\n            Float ga = (2*l-1)*(1-a*a) * Pa[I(l-1,m)];\n            Float gb = (2*l-1)*(1-b*b) * Pb[I(l-1,m)];\n            P[I(l, m)] = ((l-2)*(l-1+m)*P[I(l-2, m)]-gb+ga)/((l+1)*(l-m));\n        }\n\n        P[I(l, l-1)] = (2*l-1)/(Float)(l+1) * ((1-a*a)*Pa[I(l-1, l-1)] - (1-b*b)*Pb[I(l-1, l-1)]);\n        P[I(l, l)] = 1/(Float)(l+1) * (l*(2*l-3)*(2*l-1) * P[I(l-2, l-2)] + b*Pb[I(l,l)] - a*Pa[I(l, l)]);\n    }\n\n    delete[] Pa;\n    delete[] Pb;\n\n    return P;\n}\n\nMTS_IMPLEMENT_CLASS(SHSampler, false, Object)\nMTS_NAMESPACE_END\n", "meta": {"hexsha": "d6c48834e84ce2923b87e0a46923ecb5d25d0bb4", "size": 17310, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mitsuba/src/libcore/shvector.cpp", "max_stars_repo_name": "anadodik/sdmm-mitsuba", "max_stars_repo_head_hexsha": "6103cb8ea36ec4ab0cfb5fcc792c7f1565637d9a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2020-07-07T09:46:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T14:16:27.000Z", "max_issues_repo_path": "mitsuba/src/libcore/shvector.cpp", "max_issues_repo_name": "anadodik/sdmm-mitsuba", "max_issues_repo_head_hexsha": "6103cb8ea36ec4ab0cfb5fcc792c7f1565637d9a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mitsuba/src/libcore/shvector.cpp", "max_forks_repo_name": "anadodik/sdmm-mitsuba", "max_forks_repo_head_hexsha": "6103cb8ea36ec4ab0cfb5fcc792c7f1565637d9a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0215053763, "max_line_length": 106, "alphanum_fraction": 0.511554015, "num_tokens": 5901, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527631, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.48195807057256357}}
{"text": "\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <opencv2/opencv.hpp>\n#include <opencv2/core/eigen.hpp>\n#include <boost/filesystem.hpp>\n#include <Open3D/Open3D.h>\n#include <glog/logging.h>\n\n#include \"FileSystemTools.h\"\n#include \"YamlFileIO.h\"\n\n\n// fitness threshold\ndouble min_fitness_thresh = 0.05;\n\nstruct RegistrationResult{\n    // transform matrix\n    Eigen::Matrix4d T;\n    // fitness score\n    double fitness;\n    // inlier rms\n    double inlier_rms;\n};\n\n// create init extrinsic file\nvoid createLidarCamExtFile(const std::string& filepath, int lidar_id)\n{\n    std::string folder, filename;\n    common::splitPathAndFilename(filepath, &folder, &filename);\n\n    std::string init_T_l0_c0_filepath = common::concatenateFolderAndFileName(folder, \"init_lidar0_to_camera0.yml\");\n    // new backpack structural value\n    Eigen::Matrix4d T_l0_c0_gt = Eigen::Matrix4d::Identity();\n    Eigen::AngleAxisd l0_c0_vec1(-30 * M_PI / 180.0, Eigen::Vector3d(0, 0, 1));\n    Eigen::AngleAxisd l0_c0_vec2(90 * M_PI / 180.0, Eigen::Vector3d(1, 0, 0));\n    Eigen::AngleAxisd l0_c0_vec3( M_PI, Eigen::Vector3d(0, 0, 1));\n    Eigen::Matrix3d l0_c0_vec = l0_c0_vec1.matrix() * l0_c0_vec2.matrix() * l0_c0_vec3.matrix();\n    Eigen::Vector3d t_l0_c0(0.0, -0.05657, -0.05931);\n    T_l0_c0_gt.block<3, 3>(0, 0) = l0_c0_vec;\n    T_l0_c0_gt.block<3, 1>(0, 3) = l0_c0_vec1.matrix() * t_l0_c0;\n    // std::cout << \"T_l0_c0_gt:\\n\" << T_l0_c0_gt << \"\\n\";\n    common::saveExtFileOpencv(init_T_l0_c0_filepath, T_l0_c0_gt);  \n\n    Eigen::Matrix4d T_imu_l0_gt = Eigen::Matrix4d::Identity();\n    Eigen::AngleAxisd imu_l0_vec1(150 * M_PI / 180.0, Eigen::Vector3d(0, 0, 1));\n    Eigen::AngleAxisd imu_l0_vec2(30 * M_PI / 180.0, Eigen::Vector3d(0, 0, 1));\n    Eigen::Matrix3d imu_l0_vec = imu_l0_vec1.matrix() * imu_l0_vec2.matrix();\n    Eigen::Vector3d t_imu_l0(0.00044, 0.03407, 0.10148);\n    T_imu_l0_gt.block<3, 3>(0, 0) = imu_l0_vec;\n    T_imu_l0_gt.block<3, 1>(0, 3) = imu_l0_vec1.matrix() * t_imu_l0;\n    std::cout << \"T_imu_l0_gt:\\n\" << T_imu_l0_gt << \"\\n\";\n\n    Eigen::Matrix4d T_l0_l1_gt = Eigen::Matrix4d::Identity();\n    Eigen::AngleAxisd l0_l1_vec1(-30 * M_PI / 180.0, Eigen::Vector3d(0, 0, 1));\n    Eigen::AngleAxisd l0_l1_vec2(-73.5 * M_PI / 180.0, Eigen::Vector3d(0, 1, 0));\n    Eigen::Matrix3d l0_l1_vec = l0_l1_vec1.matrix() * l0_l1_vec2.matrix();\n    Eigen::Vector3d t_l0_l1(-0.31405, 0, -0.39803);\n    T_l0_l1_gt.block<3, 3>(0, 0) = l0_l1_vec;\n    T_l0_l1_gt.block<3, 1>(0, 3) = l0_l1_vec1.matrix() * t_l0_l1;\n    // calc T_l1_c0\n    Eigen::Matrix4d T_l1_c0_gt = T_l0_l1_gt.inverse() * T_l0_c0_gt;\n    common::saveExtFileOpencv(filepath, T_l1_c0_gt);\n}\n\nbool alignTwoPointClouds(const std::string &src_pcl_file, const std::string &target_pcl_file, const Eigen::Matrix4d &T_init, \n                RegistrationResult &result){\n    std::string path, file_name;\n    common::splitPathAndFilename(src_pcl_file, &path, &file_name);\n\n    auto src_pcd_ptr = open3d::io::CreatePointCloudFromFile(src_pcl_file);\n    auto target_pcd_ptr = open3d::io::CreatePointCloudFromFile(target_pcl_file);\n\n    if( src_pcd_ptr == nullptr || src_pcd_ptr == nullptr){\n        LOG(ERROR) << \"Fail to load src and target pointcloud file!\";\n        return false;\n    }\n\n    auto src_pcd_down_ptr = src_pcd_ptr->VoxelDownSample(0.05);\n    src_pcd_ptr->EstimateNormals(open3d::geometry::KDTreeSearchParamHybrid(0.1, 30));\n\n    auto target_pcd_down_ptr = target_pcd_ptr->VoxelDownSample(0.05);\n    target_pcd_ptr->EstimateNormals(open3d::geometry::KDTreeSearchParamHybrid(0.1, 30));\n\n    src_pcd_ptr->Transform(T_init);\n    src_pcd_down_ptr->Transform(T_init);\n\n    open3d::registration::RegistrationResult icp_result;\n\n    const double max_corresp_dis = 0.03; // meter\n    open3d::registration::ICPConvergenceCriteria icp_criteria(1e-6, 1e-6, 100);\n    icp_result = open3d::registration::RegistrationICP(*src_pcd_ptr, *target_pcd_ptr, max_corresp_dis, Eigen::Matrix4d::Identity(),\n                                                            open3d::registration::TransformationEstimationPointToPlane(), icp_criteria);\n    // icp_result = open3d::registration::RegistrationICP(*src_pcd_ptr, *target_pcd_ptr, max_corresp_dis, Eigen::Matrix4d::Identity(),\n    //                                                 open3d::registration::TransformationEstimationPointToPoint(false), icp_criteria);\n\n    // transform source pointcloud with icp_transformation\n    Eigen::Matrix4d T_icp = icp_result.transformation_;\n\n    LOG(INFO) << \"#############\" << path << \" ################\";\n    result.fitness = icp_result.fitness_;\n    LOG(INFO) << \"icp_result.fitness: \" << icp_result.fitness_;\n    result.inlier_rms = icp_result.inlier_rmse_;\n    LOG(INFO) << \"icp_result.inlier_rmse_ : \" << icp_result.inlier_rmse_;\n\n    if(result.fitness < min_fitness_thresh){\n        LOG(ERROR) << \"fitness score < \" << min_fitness_thresh;\n        return false;\n    }\n\n    // final transformation between source pointcloud and target pointcloud\n    result.T = T_icp * T_init;\n    src_pcd_down_ptr->Transform(T_icp);\n    \n    std::string save_file_path;\n\n    save_file_path = common::concatenateFolderAndFileName(path, \"transformed_source_pointcloud.ply\");\n    open3d::io::WritePointCloudToPLY(save_file_path, *src_pcd_down_ptr, true);\n    std::shared_ptr<open3d::geometry::PointCloud> merge_points(new open3d::geometry::PointCloud);\n    *merge_points = *src_pcd_down_ptr + *target_pcd_down_ptr;\n    \n    save_file_path = common::concatenateFolderAndFileName(path, \"merged_pointcloud.ply\");\n    open3d::io::WritePointCloudToPLY(save_file_path, *merge_points, true);\n    \n    return true;\n}\n\nvoid evaluateExtrinsics(const std::vector<RegistrationResult> & v_results, const Eigen::Matrix4d &T_baseline){\n    assert(v_results.size() > 1);\n\n    const Eigen::Matrix4d T_0 = v_results[0].T;\n    std::vector<double> v_inlier_rms = {v_results[0].inlier_rms};\n    // rotation sigma\n    std::vector<double> v_sigma_r;\n    // translation sigma\n    std::vector<double> v_sigma_t;\n\n    int T_num = v_results.size();\n    for(int i = 0; i < T_num; ++i){\n        Eigen::Matrix4d T = v_results[i].T;\n        Eigen::Matrix4d T_inv = T.inverse();\n        \n        Eigen::Matrix4d T_delt = T_inv * T_baseline;\n        Eigen::AngleAxisd rot_vec(T_delt.block<3, 3>(0, 0));\n        double delt_r = rot_vec.angle() * 180.0 / M_PI;\n        Eigen::Vector3d t_delt = T_delt.block<3, 1>(0, 3);\n        double delt_t = t_delt.norm() * 100;\n        LOG(INFO) << \"T_baseline and  T_\" << i << \" Rotation delta: \"\n                <<  delt_r << \" \u00b0\\n\";\n        LOG(INFO) << \"T_baseline and  T_\" << i << \" Translation delta: \" << delt_t\n                << \" cm\\n\";\n\n        v_sigma_r.push_back(delt_r * delt_r);\n        v_sigma_t.push_back(delt_t * delt_t);\n        v_inlier_rms.push_back(v_results[i].inlier_rms);\n    }\n\n    double sigma_r = std::accumulate(v_sigma_r.begin(), v_sigma_r.end(), 0.0) / T_num;\n    double sigma_t = std::accumulate(v_sigma_t.begin(), v_sigma_t.end(), 0.0) / T_num;\n    LOG(INFO) << \"Avg rotation sigma: \" << sigma_r << \", Avg trans sigma: \" << sigma_t;\n    LOG(INFO) << \"Final sigma_r\" << std::sqrt(sigma_r) << \", sigma_t: \" << std::sqrt(sigma_t);\n    // LOG(INFO) << \"Avg inlier rms: \" << std::accumulate(v_inlier_rms.begin(), v_inlier_rms.end(), 0.0) / v_inlier_rms.size();\n\n}\n\nEigen::Matrix4d readCameraPoseTxt(const std::string &file)\n{\n    Eigen::Matrix4d T = Eigen::Matrix4d::Identity();\n    std::ifstream fs(file);\n    if (!fs.is_open())\n    {\n        std::cerr << \"Fail to open camera pose file \" << file << std::endl;\n        return T;\n    }\n\n    std::string line;\n    int i = 0;\n    while (!fs.eof())\n    {\n        line.clear();\n        getline(fs, line);\n        if (line.empty())\n            continue;\n\n        std::stringstream ss(line);\n        std::string dummy_str;\n        if (i < 4)\n        {\n            ss >> T(i, 0) >> dummy_str >> T(i, 1) >> dummy_str >> T(i, 2) >> dummy_str >> T(i, 3);\n            i++;\n        }\n        else\n        {\n            std::cerr << \"Invalid camera pose format!\\n\";\n            break;\n        }\n    }\n    fs.close();\n\n    return T;\n}\n\n\nint main(int argc, char **argv){\n    if (argc < 6){\n        LOG(FATAL) << \"Usage: test_lidar2cam_calibration [init_T_l1_cam0.yaml] [dataset_folder] [cam_pose_file] [target_ply_file] [output_folder] [lidar_id]\";\n        return -1;\n    }\n\n    std::string init_ext_filepath(argv[1]);\n    // dataset folder e.g. /path/data0/lidar_cam\n    std::string dataset_folder(argv[2]);\n    // teche0 pose w.r.t calibration reference\n    std::string teche0_pose_filepath(argv[3]);\n    // target pointcloud used in lidar localization\n    std::string target_pcl_file_path(argv[4]);\n    std::string output_folder(argv[5]);\n    int lidar_id = 1;\n    // specificly camera0!!!\n    // int cam_id = 0;\n    if (argc >= 7 ){\n        lidar_id = std::atoi(argv[6]);\n    }\n\n    if(!common::fileExists(init_ext_filepath)){\n        createLidarCamExtFile(init_ext_filepath, lidar_id);\n    }\n    if(!common::pathExists(dataset_folder)){\n        LOG(FATAL) << \"Input folder doesnot exist!\";\n        return -1;\n    }\n    if(!common::pathExists(output_folder)){\n        if(!common::createPath(output_folder)){\n            LOG(FATAL) << \"Fail to create \" << output_folder;\n            return -1;\n        }\n    }\n    \n    // Eigen::Matrix4d T_base_l0 = horizontal_lidar_ptr->extrinsics();\n    // Eigen::Matrix4d T_base_l1 = vertical_lidar_ptr->extrinsics();\n    // Eigen::Matrix4d T_base_teche0 = teche0_ptr->extrinsics();\n    // initial extrinsic between two lidar\n    // Eigen::Matrix4d T_teche0_l1 = T_base_teche0.inverse() * T_base_l1;\n    Eigen::Matrix4d T_l1_teche0 = Eigen::Matrix4d::Identity();\n    if (!common::loadExtFileOpencv(init_ext_filepath, T_l1_teche0)){\n        LOG(FATAL) << \"Fail to load \" << init_ext_filepath;\n        return -1;\n    }\n    Eigen::Matrix4d T_teche0_l1 = T_l1_teche0.inverse();\n    Eigen::Matrix4d T_w_teche0 = readCameraPoseTxt(teche0_pose_filepath);\n    Eigen::Matrix4d T_w_l1_init = T_w_teche0 * T_teche0_l1;\n\n    std::vector<RegistrationResult> v_extrinsics;\n    // for (const auto & entry : boost::filesystem::directory_iterator(dataset_folder)){\n    //     if(!boost::filesystem::is_directory(entry))\n    //         continue;\n\n    //     std::string data_folder = entry.path().string() + \"/lidar_cam\";\n        std::string scan_folder_path = common::concatenateFolderAndFileName(dataset_folder, \"lidar\"+std::to_string(lidar_id));\n        std::vector<std::string> v_pcl_paths;\n        std::vector<std::string> paths = {scan_folder_path};\n        common::getFileLists(paths, true, \"ply\", &v_pcl_paths);\n        std::string src_pcl_file_path;\n        for(size_t i = 0; i < v_pcl_paths.size(); ++i){\n            std::string file_path = v_pcl_paths[i];\n            std::string path, file_name;\n            common::splitPathAndFilename(file_path, &path, &file_name);\n            if(std::atoi(&file_name[0]) == lidar_id)\n                src_pcl_file_path = file_path;\n        }\n\n        RegistrationResult regist_result;\n        bool sts = alignTwoPointClouds(src_pcl_file_path, target_pcl_file_path, T_w_l1_init, regist_result);\n        if(!sts){\n            return -1;\n        }\n        \n        Eigen::Matrix4d T_w_l1 = regist_result.T;\n        // T_l1_teche0 after icp refine\n        regist_result.T = T_w_l1.inverse() * T_w_teche0;\n        std::cout << \"Final T_l1_teche0: \\n\" << regist_result.T << \"\\n\";\n        std::string save_file_path = common::concatenateFolderAndFileName(output_folder, \"lidar\"+std::to_string(lidar_id)+\"_to_camera0.yml\");\n        common::saveExtFileOpencv(save_file_path, regist_result.T);\n        v_extrinsics.emplace_back(regist_result);\n    // }\n\n    // sort result by fitness\n    // std::sort(v_extrinsics.begin(), v_extrinsics.end(), [&](RegistrationResult &res_a, RegistrationResult &res_b){\n    //     return res_a.fitness > res_b.fitness;\n    // });\n\n    // evaluateExtrinsics(v_extrinsics, v_extrinsics[0].T);\n\n\n\n    return 0;\n}", "meta": {"hexsha": "56b9e70781167bf4df3d43ceabf801b5caba0422", "size": 11974, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_lidar2cam_calibration.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_lidar2cam_calibration.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_lidar2cam_calibration.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": 40.3164983165, "max_line_length": 158, "alphanum_fraction": 0.6497411057, "num_tokens": 3581, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4819580705725635}}
{"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_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\nusing namespace std;\nusing namespace cv;\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\n// \u50cf\u7d20\u5750\u6807\u8f6c\u76f8\u673a\u5f52\u4e00\u5316\u5750\u6807\nPoint2d pixel2cam ( const Point2d& p, const Mat& K );\n\nvoid bundleAdjustment (\n    const vector<Point3f> points_3d,\n    const vector<Point2f> points_2d,\n    const Mat& K,\n    Mat& R, Mat& t\n);\n\nint main ( int argc, char** argv )\n{\n    if ( argc != 5 )\n    {\n        cout<<\"usage: pose_estimation_3d2d img1 img2 depth1 depth2\"<<endl;\n        return 1;\n    }\n    //-- \u8bfb\u53d6\u56fe\u50cf\n    Mat img_1 = imread ( argv[1], CV_LOAD_IMAGE_COLOR );\n    Mat img_2 = imread ( argv[2], CV_LOAD_IMAGE_COLOR );\n\n    vector<KeyPoint> keypoints_1, keypoints_2;\n    vector<DMatch> matches;\n    find_feature_matches ( img_1, img_2, keypoints_1, keypoints_2, matches );\n    cout<<\"\u4e00\u5171\u627e\u5230\u4e86\"<<matches.size() <<\"\u7ec4\u5339\u914d\u70b9\"<<endl;\n\n    // \u5efa\u7acb3D\u70b9\n    Mat d1 = imread ( argv[3], CV_LOAD_IMAGE_UNCHANGED );       // \u6df1\u5ea6\u56fe\u4e3a16\u4f4d\u65e0\u7b26\u53f7\u6570\uff0c\u5355\u901a\u9053\u56fe\u50cf\n    Mat K = ( Mat_<double> ( 3,3 ) << 520.9, 0, 325.1, 0, 521.0, 249.7, 0, 0, 1 );\n    vector<Point3f> pts_3d;\n    vector<Point2f> pts_2d;\n    for ( DMatch m:matches )\n    {\n        ushort d = d1.ptr<unsigned short> (int ( keypoints_1[m.queryIdx].pt.y )) [ int ( keypoints_1[m.queryIdx].pt.x ) ];\n        if ( d == 0 )   // bad depth\n            continue;\n        float dd = d/1000.0;\n        Point2d p1 = pixel2cam ( keypoints_1[m.queryIdx].pt, K );\n        pts_3d.push_back ( Point3f ( p1.x*dd, p1.y*dd, dd ) );\n        pts_2d.push_back ( keypoints_2[m.trainIdx].pt );\n    }\n\n    cout<<\"3d-2d pairs: \"<<pts_3d.size() <<endl;\n\n    Mat r, t;\n    solvePnP ( pts_3d, pts_2d, K, Mat(), r, t, false ); // \u8c03\u7528OpenCV \u7684 PnP \u6c42\u89e3\uff0c\u53ef\u9009\u62e9EPNP\uff0cDLS\u7b49\u65b9\u6cd5\n    Mat R;\n    cv::Rodrigues ( r, R ); // r\u4e3a\u65cb\u8f6c\u5411\u91cf\u5f62\u5f0f\uff0c\u7528Rodrigues\u516c\u5f0f\u8f6c\u6362\u4e3a\u77e9\u9635\n\n    cout<<\"R=\"<<endl<<R<<endl;\n    cout<<\"t=\"<<endl<<t<<endl;\n\n    cout<<\"calling bundle adjustment\"<<endl;\n\n    bundleAdjustment ( pts_3d, pts_2d, K, R, t );\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    //-- \u521d\u59cb\u5316\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    //-- \u7b2c\u4e00\u6b65:\u68c0\u6d4b Oriented FAST \u89d2\u70b9\u4f4d\u7f6e\n    detector->detect ( img_1,keypoints_1 );\n    detector->detect ( img_2,keypoints_2 );\n\n    //-- \u7b2c\u4e8c\u6b65:\u6839\u636e\u89d2\u70b9\u4f4d\u7f6e\u8ba1\u7b97 BRIEF \u63cf\u8ff0\u5b50\n    descriptor->compute ( img_1, keypoints_1, descriptors_1 );\n    descriptor->compute ( img_2, keypoints_2, descriptors_2 );\n\n    //-- \u7b2c\u4e09\u6b65:\u5bf9\u4e24\u5e45\u56fe\u50cf\u4e2d\u7684BRIEF\u63cf\u8ff0\u5b50\u8fdb\u884c\u5339\u914d\uff0c\u4f7f\u7528 Hamming \u8ddd\u79bb\n    vector<DMatch> match;\n    // BFMatcher matcher ( NORM_HAMMING );\n    matcher->match ( descriptors_1, descriptors_2, match );\n\n    //-- \u7b2c\u56db\u6b65:\u5339\u914d\u70b9\u5bf9\u7b5b\u9009\n    double min_dist=10000, max_dist=0;\n\n    //\u627e\u51fa\u6240\u6709\u5339\u914d\u4e4b\u95f4\u7684\u6700\u5c0f\u8ddd\u79bb\u548c\u6700\u5927\u8ddd\u79bb, \u5373\u662f\u6700\u76f8\u4f3c\u7684\u548c\u6700\u4e0d\u76f8\u4f3c\u7684\u4e24\u7ec4\u70b9\u4e4b\u95f4\u7684\u8ddd\u79bb\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    //\u5f53\u63cf\u8ff0\u5b50\u4e4b\u95f4\u7684\u8ddd\u79bb\u5927\u4e8e\u4e24\u500d\u7684\u6700\u5c0f\u8ddd\u79bb\u65f6,\u5373\u8ba4\u4e3a\u5339\u914d\u6709\u8bef.\u4f46\u6709\u65f6\u5019\u6700\u5c0f\u8ddd\u79bb\u4f1a\u975e\u5e38\u5c0f,\u8bbe\u7f6e\u4e00\u4e2a\u7ecf\u9a8c\u503c30\u4f5c\u4e3a\u4e0b\u9650.\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}\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\nvoid bundleAdjustment (\n    const vector< Point3f > points_3d,\n    const vector< Point2f > points_2d,\n    const Mat& K,\n    Mat& R, Mat& t )\n{\n    // \u521d\u59cb\u5316g2o\n    typedef g2o::BlockSolver< g2o::BlockSolverTraits<6,3> > Block;  // pose \u7ef4\u5ea6\u4e3a 6, landmark \u7ef4\u5ea6\u4e3a 3\n    Block::LinearSolverType* linearSolver = new g2o::LinearSolverCSparse<Block::PoseMatrixType>(); // \u7ebf\u6027\u65b9\u7a0b\u6c42\u89e3\u5668\n    Block* solver_ptr = new Block ( linearSolver );     // \u77e9\u9635\u5757\u6c42\u89e3\u5668\n    g2o::OptimizationAlgorithmLevenberg* solver = new g2o::OptimizationAlgorithmLevenberg ( solver_ptr );\n    g2o::SparseOptimizer optimizer;\n    optimizer.setAlgorithm ( solver );\n\n    // vertex\n    g2o::VertexSE3Expmap* pose = new g2o::VertexSE3Expmap(); // camera pose\n    Eigen::Matrix3d R_mat;\n    R_mat <<\n          R.at<double> ( 0,0 ), R.at<double> ( 0,1 ), R.at<double> ( 0,2 ),\n               R.at<double> ( 1,0 ), R.at<double> ( 1,1 ), R.at<double> ( 1,2 ),\n               R.at<double> ( 2,0 ), R.at<double> ( 2,1 ), R.at<double> ( 2,2 );\n    pose->setId ( 0 );\n    pose->setEstimate ( g2o::SE3Quat (\n                            R_mat,\n                            Eigen::Vector3d ( t.at<double> ( 0,0 ), t.at<double> ( 1,0 ), t.at<double> ( 2,0 ) )\n                        ) );\n    optimizer.addVertex ( pose );\n\n    int index = 1;\n    for ( const Point3f p:points_3d )   // landmarks\n    {\n        g2o::VertexSBAPointXYZ* point = new g2o::VertexSBAPointXYZ();\n        point->setId ( index++ );\n        point->setEstimate ( Eigen::Vector3d ( p.x, p.y, p.z ) );\n        point->setMarginalized ( true ); // g2o \u4e2d\u5fc5\u987b\u8bbe\u7f6e marg \u53c2\u89c1\u7b2c\u5341\u8bb2\u5185\u5bb9\n        optimizer.addVertex ( point );\n    }\n\n    // parameter: camera intrinsics\n    g2o::CameraParameters* camera = new g2o::CameraParameters (\n        K.at<double> ( 0,0 ), Eigen::Vector2d ( K.at<double> ( 0,2 ), K.at<double> ( 1,2 ) ), 0\n    );\n    camera->setId ( 0 );\n    optimizer.addParameter ( camera );\n\n    // edges\n    index = 1;\n    for ( const Point2f p:points_2d )\n    {\n        g2o::EdgeProjectXYZ2UV* edge = new g2o::EdgeProjectXYZ2UV();\n        edge->setId ( index );\n        edge->setVertex ( 0, dynamic_cast<g2o::VertexSBAPointXYZ*> ( optimizer.vertex ( index ) ) );\n        edge->setVertex ( 1, pose );\n        edge->setMeasurement ( Eigen::Vector2d ( p.x, p.y ) );\n        edge->setParameterId ( 0,0 );\n        edge->setInformation ( Eigen::Matrix2d::Identity() );\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<<\"optimization costs time: \"<<time_used.count() <<\" seconds.\"<<endl;\n\n    cout<<endl<<\"after optimization:\"<<endl;\n    cout<<\"T=\"<<endl<<Eigen::Isometry3d ( pose->estimate() ).matrix() <<endl;\n}\n", "meta": {"hexsha": "0f36edcd0a12960491cb90190a6936fa1c3098d9", "size": 7561, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch7/pose_estimation_3d2d.cpp", "max_stars_repo_name": "renzhuli/SLAM", "max_stars_repo_head_hexsha": "4020737ae5b14322696f7af6ecd2e952335d924b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-03-07T19:29:41.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-03T14:39:41.000Z", "max_issues_repo_path": "ch7/pose_estimation_3d2d.cpp", "max_issues_repo_name": "renzhuli/SLAM", "max_issues_repo_head_hexsha": "4020737ae5b14322696f7af6ecd2e952335d924b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch7/pose_estimation_3d2d.cpp", "max_forks_repo_name": "renzhuli/SLAM", "max_forks_repo_head_hexsha": "4020737ae5b14322696f7af6ecd2e952335d924b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-07-07T07:18:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-15T11:52:23.000Z", "avg_line_length": 35.4976525822, "max_line_length": 122, "alphanum_fraction": 0.6064012697, "num_tokens": 2495, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4819580705725635}}
{"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_ALGO_LM_MANY_CLASSES_SCHUR_COMPLEMENT_HPP__\n#define __OPTIMISATION2_ALGO_LM_MANY_CLASSES_SCHUR_COMPLEMENT_HPP__\n\n#include <libv/lma/ttt/traits/wrap.hpp>\n#include <libv/lma/global.hpp>\n#include <libv/lma/lm/ba/computing.hpp>\n#include <libv/lma/lm/ba/make_type.hpp>\n#include <libv/lma/lm/ba/create_hessian.hpp>\n#include <libv/lma/lm/omp/omp.hpp>\n#include <boost/mpl/advance.hpp>\n#include <boost/mpl/remove_if.hpp>\n#include <boost/mpl/contains.hpp>\n#include <boost/mpl/assert.hpp>\n#include <boost/type_traits.hpp>\n#include <boost/fusion/include/as_map.hpp>\n#include <libv/core/tag.hpp>\n\nnamespace lma\n{\n\n  template<class VTYPE, class Ap, class H, class P, class Y> struct ProdApPH\n  {\n    Ap& ap;\n    const H& h;\n    const P& p;\n    const Y& y;\n    ProdApPH(Ap& ap_, const H& h_, const P& p_, const Y& y_):ap(ap_),h(h_),p(p_),y(y_){}\n\n    template<class T> void operator()(T){}\n    \n    template<class Key1,class Key2, class Value, template<class,class> class Pair> void operator()(ttt::wrap<Pair<Pair<Key1,Key2>,Value>>,\n      typename boost::disable_if<\n          mpl::or_<\n                    mpl::not_<br::has_key<H,Pair<Key2,VTYPE>>>,\n                    mpl::not_<br::has_key<Y,Pair<Key1,VTYPE>>>\n                  >\n            >::type * = 0)\n    {\n      {\n        auto& a1 = bf::at_key<Key1>(ap);\n        const auto& pr2 = bf::at_key<Key2>(p);\n        const auto& y1= bf::at_key<Pair<Key1,VTYPE>>(y);\n        const auto& w2 = bf::at_key<Pair<Key2,VTYPE>>(h);\n        const auto& v = bf::at_key<Pair<VTYPE,VTYPE>>(h);\n\n        typedef typename boost::remove_reference<decltype(v)>::type V;\n\n        VectorColumn< VTYPE, typename V::MatrixTag > v0;\n\n// \tstd::cout << \" [1] : \" << a1.name() << \" = \" << w2.name() << \" \" << pr2.name() << \" \" << y1.name() << std::endl;\n        // v0 = Wt * pr\n        prod(v0,w2,pr2);\n        // a = - Y * v0 , (Y = W * V)\n        prod_minus(a1,y1,v0);\n\n        auto& a2 = bf::at_key<Key2>(ap);\n        const auto& pr1 = bf::at_key<Key1>(p);\n        const auto& y2= bf::at_key<Pair<Key2,VTYPE>>(y);\n        const auto& w1 = bf::at_key<Pair<Key1,VTYPE>>(h);\n\n        typedef typename boost::remove_reference<decltype(v)>::type V;\n\n        VectorColumn< VTYPE, typename V::MatrixTag > v1;\n\n// \tstd::cout << \" [2] : \" << a2.name() << \" = \" << w1.name() << \" \" << pr1.name() << \" \" << y2.name() << std::endl;\n        // v1 = Wt * pr\n        prod(v1,w1,pr1);\n        // a = - Y * v1, (Y = W * V)\n        prod_minus(a2,y2,v1);\n      }\n    }\n\n    //! cas o\u00f9 on est sur la diagonale\n    template<class Key1, class Value, template<class,class> class Pair> void operator()(ttt::wrap<Pair<Pair<Key1,Key1>,Value>>,\n      typename boost::disable_if<boost::mpl::not_<br::has_key<H,Pair<Key1,VTYPE>>>>::type * = 0)\n    {\n      const auto& pr = bf::at_key<Key1>(p);\n      const auto& u = bf::at_key<Pair<Key1,Key1>>(h);\n\n      auto& a = bf::at_key<Key1>(ap);\n      auto& w = bf::at_key<Pair<Key1,VTYPE>>(h);\n      auto& y0 = bf::at_key<Pair<Key1,VTYPE>>(y);\n\n      auto& v = bf::at_key<Pair<VTYPE,VTYPE>>(h);\n\n      if (a.size()==0) a.resize(pr.size());\n      typedef typename boost::remove_reference<decltype(v)>::type V;\n      VectorColumn< VTYPE, typename V::MatrixTag > v0;\n      VectorColumn< Key1, typename V::MatrixTag > v1;\n      v0.resize(v.size());\n      v1.resize(u.size());\n\n//       std::cout << \" [0] : \" << a.name() << \" = \" << w.name() << \" \" << pr.name() << \" \" << y0.name() << std::endl;\n      //v0 = Wt * pr\n      prod(v0,w,pr);\n\n      //v1 = Y * v0 , ( Y = W * V )\n      prod(v1,y0,v0);\n\n      // a -= u1\n//       #pragma omp parallel for if(use_omp())\n      for(auto i = w.first() ; i < w.size() ; ++i)\n        a(i) -= v1(i);\n    }\n  };\n\n\n  template<class VTYPE, class AP, class H, class P, class Y> ProdApPH<VTYPE,AP,H,P,Y> prod_ap_ph(AP& ap, const H& h, const P& p, const Y& y){ return ProdApPH<VTYPE,AP,H,P,Y>(ap,h,p,y); }\n  \n  \n  template<class Float, class I, class List, class J, class Result> struct UnrollW2 : \n    mpl::push_back<\n\t\t    Result,\n\t\t    typename MakeTupleTable<\n\t\t\t\t\t    typename mpl::at<List,I>::type,\n\t\t\t\t\t    typename mpl::at<List,J>::type,\n\t\t\t\t\t    Float\n\t\t\t\t\t  >::type\n\t\t  >::type {};\n  \n  template<class Float, class K, class List, class Int, class Result> struct UnrollW1_ :\n    For<K::value,mpl::size<List>::value,List,UnrollW2<Float,Int,mpl::_1,mpl::_2,mpl::_3>,Result> {};\n\n  template<class Float, class A> using UnrollW1 = UnrollW1_<Float,A,mpl::_1,mpl::_2,mpl::_3>;\n  \n  template<class L, class Int, class Result> struct PushBack_ : \n    mpl::push_back<Result,typename mpl::at<L,Int>::type> {};\n    \n  typedef PushBack_<mpl::_1,mpl::_2,mpl::_3> PushBack;\n  \n  template<class BA, class NumericTag> struct ImplicitSchurContainer\n  {\n    typedef typename BA::Keys Keys;\n    typedef typename BA::MatrixTag MatrixTag;\n    \n    // K_ est le nombre de famille \u00e0 mettre dans Vs\n    // K est la position de Vs\n    static const size_t K_ = Size<NumericTag>::value;\n    static const size_t N = mpl::size<Keys>::value;\n    static const size_t K = N - K_;\n    \n    static_assert( (N > K) , \"Nombre de param\u00e8tres dans Schur >= Nombre de param\u00e8tre dans le probl\u00e8me\");\n\n    typedef typename For<K,N,Keys,PushBack>::type KeyVs;\n    typedef typename For<0,K,Keys,PushBack>::type KeyUs;\n    \n    typedef typename For<0,K,Keys,UnrollW1<MatrixTag,mpl::int_<K>>>::type TypeWs_;\n    typedef typename \n                    mpl::remove_if<\n                                    TypeWs_,\n                                    mpl::not_<\n                                              mpl::contains<typename BA::ListeHessien,mpl::_1>\n                                            >\n                                  >::type TypeWs;\n    typedef typename br::as_map<TypeWs>::type TupleWs;\n    \n    typedef typename mpl::transform< KeyUs, VectorToPairStruct<mpl::_1,MatrixTag> >::type ListResidu;\n    typedef typename mpl::transform< KeyVs, VectorToPairStruct<mpl::_1,MatrixTag> >::type ListResiduVs;\n    typedef typename br::as_map<ListResidu>::type TupleResiduUs;\n    typedef typename br::as_map<ListResiduVs>::type TupleResiduVs;\n\n    typedef typename mpl::transform<KeyVs,ToTable<Single<mpl::_1>,MatrixTag>>::type TypeVs;\n    typedef typename br::as_map<TypeVs>::type TupleVs;\n  \n    typedef typename mpl::transform< KeyUs, pair_>::type DiagUs;\n    typedef typename mpl::transform< KeyVs, pair_>::type DiagVs;\n    \n    ImplicitSchurContainer()\n    {\n//        std::cout << \"Parametres : \" << ttt::name<ListeParametre>() << std::endl;\n//        std::cout << \"Us         : \" << ttt::name<Us>() << std::endl;\n//        std::cout << \"Vs         : \" << ttt::name<Vs>() << std::endl;\n       //std::cout << \"Ws         : \" << ttt::name<TypeWs>() << std::endl;\n//        std::cout << \"ResiduUs   : \" << ttt::name<TupleResiduUs>() << std::endl;\n//        std::cout << \"TypeVs     : \" << ttt::name<TypeVs>() << std::endl;\n//        std::cout << \"TupleVs    : \" << ttt::name<TupleVs>() << std::endl;\n    }\n    \n    TupleWs ys;\n    TupleResiduUs bs;\n    TupleVs save_vs;\n  };\n}// eon\n\n#endif\n\n", "meta": {"hexsha": "98cf94e383f54d8d63c9996dd9d476b5e8364e74", "size": 7518, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/libv/lma/lm/algo/schur_complement/schur.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/algo/schur_complement/schur.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/algo/schur_complement/schur.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": 37.4029850746, "max_line_length": 186, "alphanum_fraction": 0.5659749933, "num_tokens": 2204, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.808067204308405, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4819580650589218}}
{"text": "/**\n * @file tests/svdplusplus_test.cpp\n * @author Siddharth Agrawal\n * @author Wenhao Huang\n *\n * Test SVD++.\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#include <mlpack/core.hpp>\n#include <mlpack/methods/svdplusplus/svdplusplus.hpp>\n\n#include <ensmallen.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n\nusing namespace mlpack;\nusing namespace mlpack::svd;\n\nBOOST_AUTO_TEST_SUITE(SVDPlusPlusTest);\n\nBOOST_AUTO_TEST_CASE(SVDPlusPlusEvaluate)\n{\n  // Define useful constants.\n  const size_t numUsers = 100;\n  const size_t numItems = 100;\n  const size_t numRatings = 1000;\n  const size_t maxRating = 5;\n  const size_t rank = 5;\n  const size_t numTrials = 10;\n\n  // Make a random rating dataset.\n  arma::mat data = arma::randu(3, numRatings);\n  data.row(0) = floor(data.row(0) * numUsers);\n  data.row(1) = floor(data.row(1) * numItems);\n  data.row(2) = floor(data.row(2) * maxRating + 0.5);\n\n  // Manually set last row to maximum user and maximum item.\n  data(0, numRatings - 1) = numUsers - 1;\n  data(1, numRatings - 1) = numItems - 1;\n\n  // Make a random implicit dataset.\n  arma::sp_mat implicitData = arma::sprandu(numItems, numUsers, 0.1);\n\n  // Make a SVDPlusPlusFunction with zero regularization.\n  SVDPlusPlusFunction<arma::mat> svdPPFunc(data, implicitData, rank, 0);\n\n  for (size_t i = 0; i < numTrials; ++i)\n  {\n    arma::mat parameters = arma::randu(rank + 1, numUsers + 2 * numItems);\n\n    // Calculate cost by summing up cost of each example.\n    double cost = 0;\n    for (size_t j = 0; j < data.n_cols; ++j)\n    {\n      const size_t user = data(0, j);\n      const size_t item = data(1, j) + numUsers;\n      const size_t implicitStart = numUsers + numItems;\n\n      // Calculate the squared error in the prediction.\n      const double rating = data(2, j);\n      const double userBias = parameters(rank, user);\n      const double itemBias = parameters(rank, item);\n\n      // Iterate through each item which the user interacted with to calculate\n      // user vector.\n      arma::vec userVec(rank, arma::fill::zeros);\n      arma::sp_mat::const_iterator it = implicitData.begin_col(user);\n      arma::sp_mat::const_iterator it_end = implicitData.end_col(user);\n      size_t implicitCount = 0;\n      for (; it != it_end; ++it)\n      {\n        userVec += parameters.col(implicitStart + it.row()).subvec(0, rank - 1);\n        implicitCount += 1;\n      }\n      if (implicitCount != 0)\n        userVec /= std::sqrt(implicitCount);\n      userVec += parameters.col(user).subvec(0, rank - 1);\n\n      double ratingError = rating - userBias - itemBias -\n          arma::dot(userVec, parameters.col(item).subvec(0, rank - 1));\n      double ratingErrorSquared = ratingError * ratingError;\n\n      cost += ratingErrorSquared;\n    }\n\n    // Compare calculated cost and value obtained using Evaluate().\n    BOOST_REQUIRE_CLOSE(cost, svdPPFunc.Evaluate(parameters), 1e-5);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(SVDPlusPlusFunctionRegularizationEvaluate)\n{\n  // Define useful constants.\n  const size_t numUsers = 100;\n  const size_t numItems = 100;\n  const size_t numRatings = 1000;\n  const size_t maxRating = 5;\n  const size_t rank = 5;\n  const size_t numTrials = 10;\n\n  // Make a random rating dataset.\n  arma::mat data = arma::randu(3, numRatings);\n  data.row(0) = floor(data.row(0) * numUsers);\n  data.row(1) = floor(data.row(1) * numItems);\n  data.row(2) = floor(data.row(2) * maxRating + 0.5);\n\n  // Manually set last row to maximum user and maximum item.\n  data(0, numRatings - 1) = numUsers - 1;\n  data(1, numRatings - 1) = numItems - 1;\n\n  // Make a random implicit dataset.\n  arma::sp_mat implicitData = arma::sprandu(numItems, numUsers, 0.1);\n\n  // Make three SVDPlusPlusFunction objects with different amounts of\n  // regularization.\n  SVDPlusPlusFunction<arma::mat> svdPPFuncNoReg(data, implicitData, rank, 0);\n  SVDPlusPlusFunction<arma::mat> svdPPFuncSmallReg(data, implicitData, rank,\n      0.5);\n  SVDPlusPlusFunction<arma::mat> svdPPFuncBigReg(data, implicitData, rank, 20);\n\n  for (size_t i = 0; i < numTrials; ++i)\n  {\n    arma::mat parameters = arma::randu(rank + 1, numUsers + 2 * numItems);\n\n    // The norm square of implicit item vectors is cached to avoid repeated\n    // calculation.\n    arma::vec implicitVecsNormSquare(numItems);\n    implicitVecsNormSquare.fill(-1);\n\n    // Calculate the regularization contributions of parameters corresponding to\n    // each rating and sum them up.\n    double smallRegTerm = 0;\n    double bigRegTerm = 0;\n    for (size_t j = 0; j < data.n_cols; ++j)\n    {\n      const size_t user = data(0, j);\n      const size_t item = data(1, j) + numUsers;\n      const size_t implicitStart = numUsers + numItems;\n\n      // Iterate through each item which the user interacted with.\n      arma::sp_mat::const_iterator it = implicitData.begin_col(user);\n      arma::sp_mat::const_iterator it_end = implicitData.end_col(user);\n      double regularizationError = 0;\n      size_t implicitCount = 0;\n      for (; it != it_end; ++it)\n      {\n        if (implicitVecsNormSquare(it.row()) < 0)\n        {\n          implicitVecsNormSquare(it.row()) = arma::dot(\n            parameters.col(implicitStart + it.row()).subvec(0, rank - 1),\n            parameters.col(implicitStart + it.row()).subvec(0, rank - 1));\n        }\n        regularizationError += implicitVecsNormSquare(it.row());\n        implicitCount += 1;\n      }\n      if (implicitCount != 0)\n        regularizationError /= implicitCount;\n\n      // Calculate the regularization penalty corresponding to the parameters.\n      double userVecNorm = arma::norm(parameters.col(user), 2);\n      double itemVecNorm = arma::norm(parameters.col(item), 2);\n      regularizationError +=\n          userVecNorm * userVecNorm + itemVecNorm * itemVecNorm;\n\n      smallRegTerm += 0.5 * regularizationError;\n      bigRegTerm += 20 * regularizationError;\n    }\n\n    // Cost with regularization should be close to the sum of cost without\n    // regularization and the regularization terms.\n    BOOST_REQUIRE_CLOSE(svdPPFuncNoReg.Evaluate(parameters) + smallRegTerm,\n        svdPPFuncSmallReg.Evaluate(parameters), 1e-5);\n    BOOST_REQUIRE_CLOSE(svdPPFuncNoReg.Evaluate(parameters) + bigRegTerm,\n        svdPPFuncBigReg.Evaluate(parameters), 1e-5);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(SVDPlusPlusFunctionGradient)\n{\n  // Define useful constants.\n  const size_t numUsers = 100;\n  const size_t numItems = 100;\n  const size_t numRatings = 1000;\n  const size_t maxRating = 5;\n  const size_t rank = 5;\n\n  // Make a random rating dataset.\n  arma::mat data = arma::randu(3, numRatings);\n  data.row(0) = floor(data.row(0) * numUsers);\n  data.row(1) = floor(data.row(1) * numItems);\n  data.row(2) = floor(data.row(2) * maxRating + 0.5);\n\n  // Manually set last row to maximum user and maximum item.\n  data(0, numRatings - 1) = numUsers - 1;\n  data(1, numRatings - 1) = numItems - 1;\n\n  // Make a random implicit dataset.\n  arma::sp_mat implicitData = arma::sprandu(numItems, numUsers, 0.1);\n\n  arma::mat parameters = arma::randu(rank + 1, numUsers + 2 * numItems);\n\n  // Make two SVDPlusPlusFunction objects, one with regularization and one\n  // without.\n  SVDPlusPlusFunction<arma::mat> svdPPFunc1(data, implicitData, rank, 0);\n  SVDPlusPlusFunction<arma::mat> svdPPFunc2(data, implicitData, rank, 0.5);\n\n  // Calculate gradients for both the objects.\n  arma::mat gradient1, gradient2;\n  svdPPFunc1.Gradient(parameters, gradient1);\n  svdPPFunc2.Gradient(parameters, gradient2);\n\n  // Perturbation constant.\n  const double epsilon = 0.0001;\n  double costPlus1, costMinus1, numGradient1;\n  double costPlus2, costMinus2, numGradient2;\n\n  for (size_t i = 0; i < rank; ++i)\n  {\n    for (size_t j = 0; j < numUsers + numItems; ++j)\n    {\n      // Perturb parameter with a positive constant and get costs.\n      parameters(i, j) += epsilon;\n      costPlus1 = svdPPFunc1.Evaluate(parameters);\n      costPlus2 = svdPPFunc2.Evaluate(parameters);\n\n      // Perturb parameter with a negative constant and get costs.\n      parameters(i, j) -= 2 * epsilon;\n      costMinus1 = svdPPFunc1.Evaluate(parameters);\n      costMinus2 = svdPPFunc2.Evaluate(parameters);\n\n      // Compute numerical gradients using the costs calculated above.\n      numGradient1 = (costPlus1 - costMinus1) / (2 * epsilon);\n      numGradient2 = (costPlus2 - costMinus2) / (2 * epsilon);\n\n      // Restore the parameter value.\n      parameters(i, j) += epsilon;\n\n      // Compare numerical and backpropagation gradient values.\n      if (std::abs(gradient1(i, j)) <= 1e-6)\n        BOOST_REQUIRE_SMALL(numGradient1, 1e-5);\n      else\n        BOOST_REQUIRE_CLOSE(numGradient1, gradient1(i, j), 0.02);\n\n      if (std::abs(gradient2(i, j)) <= 1e-6)\n        BOOST_REQUIRE_SMALL(numGradient2, 1e-5);\n      else\n        BOOST_REQUIRE_CLOSE(numGradient2, gradient2(i, j), 0.02);\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE(SVDplusPlusOutputSizeTest)\n{\n  // Load small GroupLens dataset.\n  arma::mat data;\n  data::Load(\"GroupLensSmall.csv\", data);\n\n  // Define useful constants.\n  const size_t numUsers = max(data.row(0)) + 1;\n  const size_t numItems = max(data.row(1)) + 1;\n  const size_t rank = 10;\n  const size_t iterations = 10;\n\n  // Resulting user/item matrices/bias, and item implicit matrix.\n  arma::mat userLatent, itemLatent;\n  arma::vec userBias, itemBias;\n  arma::mat itemImplicit;\n\n  // Apply SVD++.\n  SVDPlusPlus<> svdPP(iterations);\n  svdPP.Apply(data, rank, itemLatent, userLatent, itemBias, userBias,\n      itemImplicit);\n\n  // Check the size of outputs.\n  BOOST_REQUIRE_EQUAL(itemLatent.n_rows, numItems);\n  BOOST_REQUIRE_EQUAL(itemLatent.n_cols, rank);\n  BOOST_REQUIRE_EQUAL(userLatent.n_rows, rank);\n  BOOST_REQUIRE_EQUAL(userLatent.n_cols, numUsers);\n  BOOST_REQUIRE_EQUAL(itemBias.n_elem, numItems);\n  BOOST_REQUIRE_EQUAL(userBias.n_elem, numUsers);\n  BOOST_REQUIRE_EQUAL(itemImplicit.n_rows, rank);\n  BOOST_REQUIRE_EQUAL(itemImplicit.n_cols, numItems);\n}\n\nBOOST_AUTO_TEST_CASE(SVDPlusPlusCleanDataTest)\n{\n  // Load small GroupLens dataset.\n  arma::mat data;\n  data::Load(\"GroupLensSmall.csv\", data);\n\n  // Define useful constants.\n  const size_t numUsers = max(data.row(0)) + 1;\n  const size_t numItems = max(data.row(1)) + 1;\n\n  // Make an implicit dataset with the explicit rating dataset.\n  arma::mat implicitData = data.submat(0, 0, 1, data.n_cols - 1);\n\n  // We also want to test whether CleanData() can give matrix\n  // of right size when maximum user/item is not in implicitData.\n  for (size_t i = 0; i < implicitData.n_cols;)\n  {\n    if (implicitData(0, i) == numUsers - 1 ||\n        implicitData(1, i) == numItems - 1)\n    {\n      implicitData.shed_col(i);\n    }\n    else\n    {\n      ++i;\n    }\n  }\n\n  // Converts implicit data from coordinate list to sparse matrix.\n  arma::sp_mat cleanedData;\n  SVDPlusPlus<>::CleanData(implicitData, cleanedData, data);\n\n  // Make sure cleanedData has correct size.\n  BOOST_REQUIRE_EQUAL(cleanedData.n_rows, numItems);\n  BOOST_REQUIRE_EQUAL(cleanedData.n_cols, numUsers);\n\n  // Make sure cleanedData has correct number of implicit data.\n  BOOST_REQUIRE_EQUAL(cleanedData.n_nonzero, implicitData.n_cols);\n\n  // Make sure all implicitData are in cleanedData.\n  for (size_t i = 0; i < implicitData.n_cols; ++i)\n  {\n    double value = cleanedData(implicitData(1, i), implicitData(0, i));\n    BOOST_REQUIRE_GT(std::fabs(value), 0);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(SVDPlusPlusFunctionOptimize)\n{\n  // Define useful constants.\n  const size_t numUsers = 100;\n  const size_t numItems = 100;\n  const size_t numRatings = 1000;\n  const size_t iterations = 30;\n  const size_t rank = 5;\n  const double alpha = 0.01;\n  const double lambda = 0;\n\n  // Initiate random parameters.\n  arma::mat parameters = arma::randu(rank + 1, numUsers + 2 * numItems);\n\n  // Make a random rating dataset.\n  arma::mat data = arma::randu(3, numRatings);\n  data.row(0) = floor(data.row(0) * numUsers);\n  data.row(1) = floor(data.row(1) * numItems);\n\n  // Manually set last row to maximum user and maximum item.\n  data(0, numRatings - 1) = numUsers - 1;\n  data(1, numRatings - 1) = numItems - 1;\n\n  // Make a random implicit dataset.\n  arma::sp_mat implicitData = arma::sprandu(numItems, numUsers, 0.05);\n\n  // Make rating entries based on the parameters.\n  for (size_t i = 0; i < numRatings; ++i)\n  {\n    const size_t user = data(0, i);\n    const size_t item = data(1, i) + numUsers;\n    const size_t implicitStart = numUsers + numItems;\n\n    const double userBias = parameters(rank, user);\n    const double itemBias = parameters(rank, item);\n\n    // Iterate through each item which the user interacted with to calculate\n    // user vector.\n    arma::vec userVec(rank, arma::fill::zeros);\n    arma::sp_mat::const_iterator it = implicitData.begin_col(user);\n    arma::sp_mat::const_iterator it_end = implicitData.end_col(user);\n    size_t implicitCount = 0;\n    for (; it != it_end; ++it)\n    {\n      userVec += parameters.col(implicitStart + it.row()).subvec(0, rank - 1);\n      implicitCount += 1;\n    }\n    if (implicitCount != 0)\n      userVec /= std::sqrt(implicitCount);\n    userVec += parameters.col(user).subvec(0, rank - 1);\n\n    data(2, i) = userBias + itemBias +\n        arma::dot(userVec, parameters.col(item).subvec(0, rank - 1));\n  }\n\n  // Make the SVD++ function and the optimizer.\n  SVDPlusPlusFunction<arma::mat> svdPPFunc(data, implicitData, rank, lambda);\n  ens::StandardSGD optimizer(alpha, iterations * numRatings);\n\n  // Obtain optimized parameters after training.\n  arma::mat optParameters = arma::randu(rank + 1, numUsers + 2 * numItems);\n  optimizer.Optimize(svdPPFunc, optParameters);\n\n  // Get predicted ratings from optimized parameters.\n  arma::mat predictedData(1, numRatings);\n  for (size_t i = 0; i < numRatings; ++i)\n  {\n    const size_t user = data(0, i);\n    const size_t item = data(1, i) + numUsers;\n    const size_t implicitStart = numUsers + numItems;\n\n    const double userBias = optParameters(rank, user);\n    const double itemBias = optParameters(rank, item);\n\n    // Iterate through each item which the user interacted with to calculate\n    // user vector.\n    arma::vec userVec(rank, arma::fill::zeros);\n    arma::sp_mat::const_iterator it = implicitData.begin_col(user);\n    arma::sp_mat::const_iterator it_end = implicitData.end_col(user);\n    size_t implicitCount = 0;\n    for (; it != it_end; ++it)\n    {\n      userVec +=\n          optParameters.col(implicitStart + it.row()).subvec(0, rank - 1);\n      implicitCount += 1;\n    }\n    if (implicitCount != 0)\n      userVec /= std::sqrt(implicitCount);\n    userVec += optParameters.col(user).subvec(0, rank - 1);\n\n    predictedData(0, i) = userBias + itemBias +\n        arma::dot(userVec, optParameters.col(item).subvec(0, rank - 1));\n  }\n\n  // Calculate relative error.\n  const double relativeError = arma::norm(data.row(2) - predictedData, \"frob\") /\n                               arma::norm(data, \"frob\");\n\n  // Relative error should be small.\n  BOOST_REQUIRE_SMALL(relativeError, 1e-2);\n}\n\n// The test is only compiled if the user has specified OpenMP to be\n// used.\n#ifdef HAS_OPENMP\n\n// Test SVDPlusPlus with parallel SGD.\nBOOST_AUTO_TEST_CASE(SVDPlusPlusFunctionParallelOptimize)\n{\n  // Define useful constants.\n  const size_t numUsers = 100;\n  const size_t numItems = 100;\n  const size_t numRatings = 1000;\n  const size_t iterations = 30;\n  const size_t rank = 5;\n  const double alpha = 0.01;\n  const double lambda = 0;\n\n  // Initiate random parameters.\n  arma::mat parameters = arma::randu(rank + 1, numUsers + 2 * numItems);\n\n  // Make a random rating dataset.\n  arma::mat data = arma::randu(3, numRatings);\n  data.row(0) = floor(data.row(0) * numUsers);\n  data.row(1) = floor(data.row(1) * numItems);\n\n  // Manually set last row to maximum user and maximum item.\n  data(0, numRatings - 1) = numUsers - 1;\n  data(1, numRatings - 1) = numItems - 1;\n\n  // Make a random implicit dataset.\n  arma::sp_mat implicitData = arma::sprandu(numItems, numUsers, 0.05);\n\n  // Make rating entries based on the parameters.\n  for (size_t i = 0; i < numRatings; ++i)\n  {\n    const size_t user = data(0, i);\n    const size_t item = data(1, i) + numUsers;\n    const size_t implicitStart = numUsers + numItems;\n\n    const double userBias = parameters(rank, user);\n    const double itemBias = parameters(rank, item);\n\n    // Iterate through each item which the user interacted with to calculate\n    // user vector.\n    arma::vec userVec(rank, arma::fill::zeros);\n    arma::sp_mat::const_iterator it = implicitData.begin_col(user);\n    arma::sp_mat::const_iterator it_end = implicitData.end_col(user);\n    size_t implicitCount = 0;\n    for (; it != it_end; ++it)\n    {\n      userVec += parameters.col(implicitStart + it.row()).subvec(0, rank - 1);\n      implicitCount += 1;\n    }\n    if (implicitCount != 0)\n      userVec /= std::sqrt(implicitCount);\n    userVec += parameters.col(user).subvec(0, rank - 1);\n\n    data(2, i) = userBias + itemBias +\n        arma::dot(userVec, parameters.col(item).subvec(0, rank - 1));\n  }\n\n  // Make the SVD++ function and the optimizer.\n  SVDPlusPlusFunction<arma::mat> svdPPFunc(data, implicitData, rank, lambda);\n\n  ens::ConstantStep decayPolicy(alpha);\n\n  // Iterate till convergence.\n  // The threadShareSize is chosen such that each function gets optimized.\n  ens::ParallelSGD<ens::ConstantStep> optimizer(iterations,\n      std::ceil((float) svdPPFunc.NumFunctions() / omp_get_max_threads()), 1e-5,\n      true, decayPolicy);\n\n  // Obtain optimized parameters after training.\n  arma::mat optParameters = arma::randu(rank + 1, numUsers + 2 * numItems);\n  optimizer.Optimize(svdPPFunc, optParameters);\n\n  // Get predicted ratings from optimized parameters.\n  arma::mat predictedData(1, numRatings);\n  for (size_t i = 0; i < numRatings; ++i)\n  {\n    const size_t user = data(0, i);\n    const size_t item = data(1, i) + numUsers;\n    const size_t implicitStart = numUsers + numItems;\n\n    const double userBias = optParameters(rank, user);\n    const double itemBias = optParameters(rank, item);\n\n    // Iterate through each item which the user interacted with to calculate\n    // user vector.\n    arma::vec userVec(rank, arma::fill::zeros);\n    arma::sp_mat::const_iterator it = implicitData.begin_col(user);\n    arma::sp_mat::const_iterator it_end = implicitData.end_col(user);\n    size_t implicitCount = 0;\n    for (; it != it_end; ++it)\n    {\n      userVec +=\n          optParameters.col(implicitStart + it.row()).subvec(0, rank - 1);\n      implicitCount += 1;\n    }\n    if (implicitCount != 0)\n      userVec /= std::sqrt(implicitCount);\n    userVec += optParameters.col(user).subvec(0, rank - 1);\n\n    predictedData(0, i) = userBias + itemBias +\n        arma::dot(userVec, optParameters.col(item).subvec(0, rank - 1));\n  }\n\n  // Calculate relative error.\n  const double relativeError = arma::norm(data.row(2) - predictedData, \"frob\") /\n                               arma::norm(data, \"frob\");\n\n  // Relative error should be small.\n  BOOST_REQUIRE_SMALL(relativeError, 1e-2);\n}\n\n#endif\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "a7918a259c94baa46a3382139a725076ef3637ff", "size": 19210, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/svdplusplus_test.cpp", "max_stars_repo_name": "birm/mlpack", "max_stars_repo_head_hexsha": "8e906556bbbd5be59481329567c2f9a413e72b11", "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/tests/svdplusplus_test.cpp", "max_issues_repo_name": "birm/mlpack", "max_issues_repo_head_hexsha": "8e906556bbbd5be59481329567c2f9a413e72b11", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mlpack/tests/svdplusplus_test.cpp", "max_forks_repo_name": "birm/mlpack", "max_forks_repo_head_hexsha": "8e906556bbbd5be59481329567c2f9a413e72b11", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.5503597122, "max_line_length": 80, "alphanum_fraction": 0.6768349818, "num_tokens": 5370, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.808067204308405, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4819580650589218}}
{"text": "#define BOOST_TEST_MODULE\n#include <boost/test/unit_test.hpp>\n#include <util/test_macros.hpp>\n#include <stdlib.h>\n#include <vector>\n#include <string>\n#include <functional>\n#include <random>\n#include <cfenv>\n\n#include <ml_data/ml_data.hpp>\n#include <optimization/optimization_interface.hpp>\n#include <optimization/utils.hpp>\n#include <toolkits/supervised_learning/supervised_learning.hpp>\n#include <toolkits/supervised_learning/linear_svm.hpp>\n#include <toolkits/supervised_learning/linear_svm_opt_interface.hpp>\n#include <sframe/testing_utils.hpp>\n\n\nusing namespace turi;\nusing namespace turi::supervised;\n\nvoid run_linear_svm_test(std::map<std::string, flexible_type> opts) {\n\n\n  size_t examples = opts.at(\"examples\");\n  size_t features = opts.at(\"features\");\n  std::string target_column_name = \"target\";\n\n  // Answers\n  // -----------------------------------------------------------------------\n  DenseVector coefs(features+1);\n  coefs.randn();\n\n  // Feature names\n  std::vector<std::string> feature_names;\n  std::vector<flex_type_enum> feature_types;\n  for(size_t i=0; i < features; i++){\n    feature_names.push_back(std::to_string(i));\n    feature_types.push_back(flex_type_enum::FLOAT);\n  }\n\n  // Data\n  std::vector<std::vector<flexible_type>> y_data;\n  std::vector<std::vector<flexible_type>> X_data;\n  for(size_t i=0; i < examples; i++){\n    DenseVector x(features);\n    x.randn();\n    std::vector<flexible_type> x_tmp;\n    for(size_t k=0; k < features; k++){\n      x_tmp.push_back(x(k));\n    }\n\n    // Compute the prediction for this\n    double t = dot(x, coefs.subvec(0, features-1)) + coefs(features);\n    t = 1.0/(1.0+exp(-1.0*t));\n    int c = turi::random::bernoulli(t);\n    if (i == 0) c = 0; // Make sure category 0 is category 0 (for testing)\n    std::vector<flexible_type> y_tmp;\n    y_tmp.push_back(c);\n\n    X_data.push_back(x_tmp);\n    y_data.push_back(y_tmp);\n  }\n\n  // Options\n  std::map<std::string, flexible_type> options = {\n    {\"convergence_threshold\", 1e-2},\n    {\"max_iterations\", 10},\n    {\"solver\", \"lbfgs\"},\n  };\n\n  // Make the data\n  sframe X = make_testing_sframe(feature_names, feature_types, X_data);\n  sframe y = make_testing_sframe({\"target\"}, {flex_type_enum::STRING}, y_data);\n  std::shared_ptr<linear_svm> model;\n  model.reset(new linear_svm);\n  model->init(X,y);\n  model->init_options(options);\n  model->train();\n\n  // Construct the ml_data\n  ml_data data = model->construct_ml_data_using_current_metadata(X, y);\n  ml_data valid_data;\n\n  // Check coefficients & options\n  // ----------------------------------------------------------------------\n  DenseVector _coefs(features+1);\n  model->get_coefficients(_coefs);\n  TS_ASSERT(_coefs.size() == features + 1);\n\n  std::map<std::string, flexible_type> _options;\n  _options = model->get_current_options();\n  for (auto& kvp: options){\n    TS_ASSERT(_options[kvp.first] == kvp.second);\n  }\n  TS_ASSERT(model->is_trained() == true);\n\n  // Check predictions\n  // ----------------------------------------------------------------------\n  std::shared_ptr<sarray<flexible_type>> _pred_class;\n  std::vector<flexible_type> pred_class;\n  _pred_class = model->predict(data, \"class\");\n\n  // Save predictions made by the model\n  size_t rows;\n  auto reader = _pred_class->get_reader();\n  rows = reader->read_rows(0, examples, pred_class);\n\n  // Check that the predictions made by the model are right!\n  for(size_t i=0; i < examples; i++){\n    DenseVector x(features + 1);\n    for(size_t k=0; k < features; k++){\n      x(k) = X_data[i][k];\n    }\n    x(features) = 1;\n    double t = arma::dot(x, _coefs);\n    int c = t > 0.0;\n    TS_ASSERT_EQUALS(pred_class[i], std::to_string(c));\n  }\n\n\n  // Check save and load\n  // ----------------------------------------------------------------------\n  dir_archive archive_write;\n  archive_write.open_directory_for_write(\"linear_svm_tests\");\n  turi::oarchive oarc(archive_write);\n  oarc << *model;\n  archive_write.close();\n\n  // Load it\n  dir_archive archive_read;\n  archive_read.open_directory_for_read(\"linear_svm_tests\");\n  turi::iarchive iarc(archive_read);\n  iarc >> *model;\n\n\n  // Check predictions after saving and loading.\n  // ----------------------------------------------------------------------\n  DenseVector _coefs_after_load(features+1);\n  model->get_coefficients(_coefs_after_load);\n  TS_ASSERT(_coefs_after_load.size() == features + 1);\n  TS_ASSERT(arma::approx_equal(_coefs_after_load, _coefs,\"absdiff\", 1e-5));\n  _options = model->get_current_options();\n  for (auto& kvp: options){\n    TS_ASSERT(_options[kvp.first] == kvp.second);\n  }\n  TS_ASSERT(model->is_trained() == true);\n\n\n  // Check coefficients after saving and loading.\n  // ----------------------------------------------------------------------\n  _pred_class = model->predict(data, \"class\");\n  reader = _pred_class->get_reader();\n  rows = reader->read_rows(0, examples, pred_class);\n\n  // Check that the predictions made by the model are right!\n  for(size_t i=0; i < examples; i++){\n    DenseVector x(features + 1);\n    for(size_t k=0; k < features; k++){\n      x(k) = X_data[i][k];\n    }\n    x(features) = 1;\n    double t = arma::dot(x, _coefs);\n    int c = t > 0.0;\n    TS_ASSERT_EQUALS(pred_class[i], std::to_string(c));\n  }\n\n  model->get_coefficients(_coefs);\n  TS_ASSERT(_coefs.size() == features + 1);\n  model.reset();\n}\n\n/**\n *  Check linear svm\n*/\nstruct linear_svm_test  {\n\n  public:\n\n  void test_linear_svm_basic_2d() {\n    std::map<std::string, flexible_type> opts = {\n      {\"examples\", 100},\n      {\"features\", 1}};\n    run_linear_svm_test(opts);\n  }\n\n  void test_linear_svm_small() {\n    std::map<std::string, flexible_type> opts = {\n      {\"examples\", 1000},\n      {\"features\", 10}};\n    run_linear_svm_test(opts);\n  }\n\n};\n\n\n\nvoid run_linear_svm_scaled_logistic_opt_interface_test(std::map<std::string,\n    flexible_type> opts) {\n\n\n  size_t examples = opts.at(\"examples\");\n  size_t features = opts.at(\"features\");\n  std::string target_column_name = \"target\";\n  std::vector<std::string> column_names = {\"user\", \"item\"};\n\n  // Answers\n  // -----------------------------------------------------------------------\n  DenseVector coefs(features+1);\n  coefs.randn();\n\n  // Feature names\n  std::vector<std::string> feature_names;\n  std::vector<flex_type_enum> feature_types;\n  for(size_t i=0; i < features; i++){\n    feature_names.push_back(std::to_string(i));\n    feature_types.push_back(flex_type_enum::FLOAT);\n  }\n\n  // Data\n  std::vector<std::vector<flexible_type>> y_data;\n  std::vector<std::vector<flexible_type>> X_data;\n  for(size_t i=0; i < examples; i++){\n    DenseVector x(features);\n    x.randn();\n    std::vector<flexible_type> x_tmp;\n    for(size_t k=0; k < features; k++){\n      x_tmp.push_back(x(k));\n    }\n\n    // Compute the prediction for this\n    double t = dot(x, coefs.subvec(0, features-1)) + coefs(features);\n    t = 1.0/(1.0+exp(-1.0*t));\n    int c = turi::random::bernoulli(t);\n    std::vector<flexible_type> y_tmp;\n    y_tmp.push_back(c);\n\n    X_data.push_back(x_tmp);\n    y_data.push_back(y_tmp);\n  }\n\n\n  // Construct the ml_data\n  // Make the data\n  sframe X = make_testing_sframe(feature_names, feature_types, X_data);\n  sframe y = make_testing_sframe({\"target\"}, {flex_type_enum::STRING}, y_data);\n  std::shared_ptr<linear_svm> model;\n  model.reset(new linear_svm);\n  model->init(X,y);\n\n  // Construct the ml_data\n  ml_data data = model->construct_ml_data_using_current_metadata(X, y);\n  ml_data valid_data;\n\n  std::shared_ptr<linear_svm_scaled_logistic_opt_interface> svm_interface;\n  svm_interface.reset(new linear_svm_scaled_logistic_opt_interface(data, valid_data, *model));\n\n  // Check examples & variables.\n  TS_ASSERT(svm_interface->num_variables() == features+1);\n  TS_ASSERT(svm_interface->num_examples() == examples);\n\n  size_t variables = svm_interface->num_variables();\n  for(size_t i=0; i < 10; i++){\n\n    DenseVector point(variables);\n    point.randn();\n\n    // Check gradients, functions and hessians.\n    DenseVector gradient(variables);\n    double func_value;\n\n    func_value = svm_interface->compute_function_value(point);\n    svm_interface->compute_gradient(point, gradient);\n  }\n\n  model.reset();\n  svm_interface.reset();\n}\n\n\n/**\n *  Check opt interface\n*/\nstruct linear_svm_scaled_logistic_opt_interface_test  {\n\n  public:\n\n  void test_linear_svm_scaled_logistic_opt_interface_basic_2d() {\n    std::map<std::string, flexible_type> opts = {\n      {\"examples\", 100},\n      {\"features\", 1}};\n    run_linear_svm_scaled_logistic_opt_interface_test(opts);\n  }\n\n  void test_linear_svm_scaled_logistic_opt_interface_small() {\n    std::map<std::string, flexible_type> opts = {\n      {\"examples\", 1000},\n      {\"features\", 10}};\n    run_linear_svm_scaled_logistic_opt_interface_test(opts);\n  }\n\n};\n\nBOOST_FIXTURE_TEST_SUITE(_linear_svm_test, linear_svm_test)\nBOOST_AUTO_TEST_CASE(test_linear_svm_basic_2d) {\n  linear_svm_test::test_linear_svm_basic_2d();\n}\nBOOST_AUTO_TEST_CASE(test_linear_svm_small) {\n  linear_svm_test::test_linear_svm_small();\n}\nBOOST_AUTO_TEST_SUITE_END()\nBOOST_FIXTURE_TEST_SUITE(_linear_svm_scaled_logistic_opt_interface_test, linear_svm_scaled_logistic_opt_interface_test)\nBOOST_AUTO_TEST_CASE(test_linear_svm_scaled_logistic_opt_interface_basic_2d) {\n  linear_svm_scaled_logistic_opt_interface_test::test_linear_svm_scaled_logistic_opt_interface_basic_2d();\n}\nBOOST_AUTO_TEST_CASE(test_linear_svm_scaled_logistic_opt_interface_small) {\n  linear_svm_scaled_logistic_opt_interface_test::test_linear_svm_scaled_logistic_opt_interface_small();\n}\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "82a602547461c5c625fb420ce9d08d0e31fe5784", "size": 9530, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "test/toolkits/supervised_learning/linear_svm_tests.cxx", "max_stars_repo_name": "TimothyRHuertas/turicreate", "max_stars_repo_head_hexsha": "afa00bee56d168190c6f122e14c9fbc6656b4e97", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-04-16T19:51:18.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-16T19:51:18.000Z", "max_issues_repo_path": "test/toolkits/supervised_learning/linear_svm_tests.cxx", "max_issues_repo_name": "tashby/turicreate", "max_issues_repo_head_hexsha": "7f07ce795833d0c56c72b3a1fb9339bed6d178d1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-09-08T02:18:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T00:39:44.000Z", "max_forks_repo_path": "test/toolkits/supervised_learning/linear_svm_tests.cxx", "max_forks_repo_name": "tashby/turicreate", "max_forks_repo_head_hexsha": "7f07ce795833d0c56c72b3a1fb9339bed6d178d1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-01-12T01:07:34.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-12T01:07:34.000Z", "avg_line_length": 29.6884735202, "max_line_length": 119, "alphanum_fraction": 0.6678908709, "num_tokens": 2462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.48194127630986805}}
{"text": "#include <geometry.h>\n#include <tiny.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n\n\ntemplate<typename V, size_t N>\nvoid test_direction_table(geometry::DirectionTable<V,N> const & DT )\n{\n  BOOST_CHECK_EQUAL(DT.size(), N);\n  \n  for(size_t i=0u; i < N; ++i)\n  {\n    V const di = DT(i);\n    \n    BOOST_CHECK_CLOSE( inner_prod(di,di), 1.0f, 0.01f);\n    \n    for(size_t j=i+1u; j < N; ++j)\n    {\n      V const dj = DT(j);\n\n      V diff = di-dj;\n      \n      BOOST_CHECK_GT( inner_prod(diff,diff) , 0.01f );\n      \n    }\n  }\n}\n\n\nBOOST_AUTO_TEST_SUITE(geometry);\n\nBOOST_AUTO_TEST_CASE(make_direction_tables)\n{\n  typedef tiny::MathTypes<float> MT;\n  typedef MT::vector3_type       V;\n  \n  {\n    geometry::DirectionTable<V,3> A = geometry::make3<V>();\n    test_direction_table(A);\n  }\n  {\n    geometry::DirectionTable<V,4> A = geometry::make4<V>();\n    test_direction_table(A);\n  }\n  {\n    geometry::DirectionTable<V,6> A = geometry::make6<V>();\n    test_direction_table(A);\n  }\n  {\n    geometry::DirectionTable<V,7> A = geometry::make7<V>();\n    test_direction_table(A);\n  }\n  {\n    geometry::DirectionTable<V,9> A = geometry::make9<V>();\n    test_direction_table(A);\n  }\n  {\n    geometry::DirectionTable<V,10> A = geometry::make10<V>();\n    test_direction_table(A);\n  }\n  {\n    geometry::DirectionTable<V,13> A = geometry::make13<V>();\n    test_direction_table(A);\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "630f8ecba4d7cfee95522e8f95fc03215e3d7d8d", "size": 1553, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/FOUNDATION/GEOMETRY/unit_tests/geometry_direction_table/geometry_direction_table.cpp", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-11-27T09:44:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-13T00:24:21.000Z", "max_issues_repo_path": "PROX/FOUNDATION/GEOMETRY/unit_tests/geometry_direction_table/geometry_direction_table.cpp", "max_issues_repo_name": "erleben/matchstick", "max_issues_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_issues_repo_licenses": ["MIT"], "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/FOUNDATION/GEOMETRY/unit_tests/geometry_direction_table/geometry_direction_table.cpp", "max_forks_repo_name": "erleben/matchstick", "max_forks_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_forks_repo_licenses": ["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.2739726027, "max_line_length": 68, "alphanum_fraction": 0.6445589182, "num_tokens": 430, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.481941276309868}}
{"text": "// Copyright (c) by respective owners including Yahoo!, Microsoft, and\n// individual contributors. All rights reserved. Released under a BSD (revised)\n// license as described in the file LICENSE.\n\n#include \"loss_functions.h\"\n\n#include <boost/test/test_tools.hpp>\n#include <boost/test/unit_test.hpp>\n\n#include \"named_labels.h\"\n#include \"test_common.h\"\n\nBOOST_AUTO_TEST_CASE(squared_loss_test)\n{\n  auto& vw = *VW::initialize(\"--quiet\");\n  const std::string loss_type(\"squared\");\n\n  auto loss = get_loss_function(vw, loss_type);\n  shared_data sd;\n  sd.min_label = 0.0f;\n  sd.max_label = 1.0f;\n  constexpr float eta = 0.1f;     // learning rate\n  constexpr float weight = 1.0f;  // example weight\n\n  constexpr float label = 0.5f;\n  constexpr float prediction = 0.4f;\n  constexpr float update_scale = eta * weight;\n  constexpr float pred_per_update = 1.0f;  // Use dummy value here, see gd.cc for details.\n\n  BOOST_CHECK_EQUAL(loss_type, loss->get_type());\n  BOOST_CHECK_CLOSE(0.0f, loss->get_parameter(), FLOAT_TOL);\n\n  BOOST_CHECK_CLOSE(0.01f, loss->get_loss(&sd, prediction, label), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(0.01812692f, loss->get_update(prediction, label, update_scale, pred_per_update), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(0.02f, loss->get_unsafe_update(prediction, label, update_scale), FLOAT_TOL);\n\n  BOOST_CHECK_CLOSE(0.04f, loss->get_square_grad(prediction, label), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(-0.2f, loss->first_derivative(&sd, prediction, label), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(2.0f, loss->second_derivative(&sd, prediction, label), FLOAT_TOL);\n\n  VW::finish(vw);\n}\n\nBOOST_AUTO_TEST_CASE(expectile_loss_label_is_greater_than_prediction_test)\n{\n  auto& vw = *VW::initialize(\"--quiet\");\n  const std::string loss_type(\"expectile\");\n  constexpr float parameter(0.4f);\n\n  auto loss = get_loss_function(vw, loss_type, parameter);\n  shared_data sd;\n  sd.min_label = 0.0f;\n  sd.max_label = 1.0f;\n  constexpr float eta = 0.1f;     // learning rate\n  constexpr float weight = 1.0f;  // example weight\n\n  constexpr float label = 0.5f;\n  constexpr float prediction = 0.4f;\n  constexpr float update_scale = eta * weight;\n  constexpr float pred_per_update = 1.0f;  // Use dummy value here, see gd.cc for details.\n\n  BOOST_CHECK_EQUAL(loss_type, loss->get_type());\n  BOOST_CHECK_CLOSE(parameter, loss->get_parameter(), FLOAT_TOL);\n\n  BOOST_CHECK_CLOSE(0.004f, loss->get_loss(&sd, prediction, label), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(0.007688365f, loss->get_update(prediction, label, update_scale, pred_per_update), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(0.008f, loss->get_unsafe_update(prediction, label, update_scale), FLOAT_TOL);\n\n  BOOST_CHECK_CLOSE(0.0064f, loss->get_square_grad(prediction, label), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(-0.08f, loss->first_derivative(&sd, prediction, label), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(0.8f, loss->second_derivative(&sd, prediction, label), FLOAT_TOL);\n\n  VW::finish(vw);\n}\n\nBOOST_AUTO_TEST_CASE(expectile_loss_prediction_is_greater_than_label_test)\n{\n  auto& vw = *VW::initialize(\"--quiet\");\n  const std::string loss_type(\"expectile\");\n  constexpr float parameter(0.4f);\n\n  auto loss = get_loss_function(vw, loss_type, parameter);\n  shared_data sd;\n  sd.min_label = 0.0f;\n  sd.max_label = 1.0f;\n  constexpr float eta = 0.1f;     // learning rate\n  constexpr float weight = 1.0f;  // example weight\n\n  constexpr float label = 0.4f;\n  constexpr float prediction = 0.5f;\n  constexpr float update_scale = eta * weight;\n  constexpr float pred_per_update = 1.0f;  // Use dummy value here, see gd.cc for details.\n\n  BOOST_CHECK_EQUAL(loss_type, loss->get_type());\n  BOOST_CHECK_CLOSE(parameter, loss->get_parameter(), FLOAT_TOL);\n\n  BOOST_CHECK_CLOSE(0.006f, loss->get_loss(&sd, prediction, label), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(-0.011307956f, loss->get_update(prediction, label, update_scale, pred_per_update), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(-0.012f, loss->get_unsafe_update(prediction, label, update_scale), FLOAT_TOL);\n\n  BOOST_CHECK_CLOSE(0.0144f, loss->get_square_grad(prediction, label), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(0.12f, loss->first_derivative(&sd, prediction, label), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(1.2f, loss->second_derivative(&sd, prediction, label), FLOAT_TOL);\n\n  VW::finish(vw);\n}\n\nBOOST_AUTO_TEST_CASE(expectile_loss_parameter_equals_zero_test)\n{\n  auto& vw = *VW::initialize(\"--quiet\");\n  const std::string loss_type(\"expectile\");\n  constexpr float parameter(0.0f);\n\n  auto loss = get_loss_function(vw, loss_type, parameter);\n  shared_data sd;\n  sd.min_label = 0.0f;\n  sd.max_label = 1.0f;\n  constexpr float eta = 0.1f;     // learning rate\n  constexpr float weight = 1.0f;  // example weight\n\n  constexpr float label = 0.5f;\n  constexpr float prediction = 0.4f;\n  constexpr float update_scale = eta * weight;\n  constexpr float pred_per_update = 1.0f;  // Use dummy value here, see gd.cc for details.\n\n  BOOST_CHECK_EQUAL(loss_type, loss->get_type());\n  BOOST_CHECK_CLOSE(parameter, loss->get_parameter(), FLOAT_TOL);\n\n  BOOST_CHECK_CLOSE(0.0f, loss->get_loss(&sd, prediction, label), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(0.0f, loss->get_update(prediction, label, update_scale, pred_per_update), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(0.0f, loss->get_unsafe_update(prediction, label, update_scale), FLOAT_TOL);\n\n  BOOST_CHECK_CLOSE(0.0f, loss->get_square_grad(prediction, label), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(0.0f, loss->first_derivative(&sd, prediction, label), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(0.0f, loss->second_derivative(&sd, prediction, label), FLOAT_TOL);\n\n  VW::finish(vw);\n}\n\nBOOST_AUTO_TEST_CASE(expectile_loss_parameter_equals_one_test)\n{\n  auto& vw = *VW::initialize(\"--quiet\");\n  const std::string loss_type(\"expectile\");\n  constexpr float parameter(1.0f);\n\n  auto loss = get_loss_function(vw, loss_type, parameter);\n  shared_data sd;\n  sd.min_label = 0.0f;\n  sd.max_label = 1.0f;\n  constexpr float eta = 0.1f;     // learning rate\n  constexpr float weight = 1.0f;  // example weight\n\n  constexpr float label = 0.5f;\n  constexpr float prediction = 0.4f;\n  constexpr float update_scale = eta * weight;\n  constexpr float pred_per_update = 1.0f;  // Use dummy value here, see gd.cc for details.\n\n  BOOST_CHECK_EQUAL(loss_type, loss->get_type());\n  BOOST_CHECK_CLOSE(parameter, loss->get_parameter(), FLOAT_TOL);\n\n  BOOST_CHECK_CLOSE(0.01f, loss->get_loss(&sd, prediction, label), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(0.01812692f, loss->get_update(prediction, label, update_scale, pred_per_update), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(0.02f, loss->get_unsafe_update(prediction, label, update_scale), FLOAT_TOL);\n\n  BOOST_CHECK_CLOSE(0.04f, loss->get_square_grad(prediction, label), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(-0.2f, loss->first_derivative(&sd, prediction, label), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(2.0f, loss->second_derivative(&sd, prediction, label), FLOAT_TOL);\n\n  VW::finish(vw);\n}\n\nBOOST_AUTO_TEST_CASE(compare_expectile_loss_with_squared_loss_test)\n{\n  auto& vw = *VW::initialize(\"--quiet\");\n  const std::string loss_type_expectile(\"expectile\");\n  const std::string loss_type_squared(\"squared\");\n  constexpr float parameter(0.3f);\n\n  auto loss_expectile = get_loss_function(vw, loss_type_expectile, parameter);\n  auto loss_squared = get_loss_function(vw, loss_type_squared);\n  shared_data sd;\n  sd.min_label = 0.0f;\n  sd.max_label = 1.0f;\n  constexpr float eta = 0.1f;     // learning rate\n  constexpr float weight = 1.0f;  // example weight\n\n  constexpr float label = 0.5f;\n  constexpr float prediction = 0.4f;\n  constexpr float update_scale = eta * weight;\n  constexpr float pred_per_update = 1.0f;  // Use dummy value here, see gd.cc for details.\n\n  BOOST_CHECK_CLOSE(loss_expectile->get_loss(&sd, prediction, label),\n      loss_squared->get_loss(&sd, prediction, label) * parameter, FLOAT_TOL);\n  BOOST_CHECK_CLOSE(loss_expectile->get_update(prediction, label, update_scale, pred_per_update),\n      loss_squared->get_update(prediction, label, update_scale * parameter, pred_per_update), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(loss_expectile->get_unsafe_update(prediction, label, update_scale),\n      loss_squared->get_unsafe_update(prediction, label, update_scale * parameter), FLOAT_TOL);\n\n  BOOST_CHECK_CLOSE(loss_expectile->get_square_grad(prediction, label),\n      loss_squared->get_square_grad(prediction, label) * parameter * parameter, FLOAT_TOL);\n  BOOST_CHECK_CLOSE(loss_expectile->first_derivative(&sd, prediction, label),\n      loss_squared->first_derivative(&sd, prediction, label) * parameter, FLOAT_TOL);\n  BOOST_CHECK_CLOSE(loss_expectile->second_derivative(&sd, prediction, label),\n      loss_squared->second_derivative(&sd, prediction, label) * parameter, FLOAT_TOL);\n\n  VW::finish(vw);\n}\n", "meta": {"hexsha": "073f15141bf8f1a8dfac0cd436b8c15c30a37c0c", "size": 8650, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/unit_test/loss_functions_test.cc", "max_stars_repo_name": "MoniFarsang/vowpal_wabbit", "max_stars_repo_head_hexsha": "e37d4505a4830c73306180adadb5b3abbb5c0fc1", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/unit_test/loss_functions_test.cc", "max_issues_repo_name": "MoniFarsang/vowpal_wabbit", "max_issues_repo_head_hexsha": "e37d4505a4830c73306180adadb5b3abbb5c0fc1", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/unit_test/loss_functions_test.cc", "max_forks_repo_name": "MoniFarsang/vowpal_wabbit", "max_forks_repo_head_hexsha": "e37d4505a4830c73306180adadb5b3abbb5c0fc1", "max_forks_repo_licenses": ["BSD-3-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.5865384615, "max_line_length": 114, "alphanum_fraction": 0.7486705202, "num_tokens": 2368, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.481941276309868}}
{"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() : objectsData{ new std::vector<ObjectData*>{} }\n{\n\txVelocity = -0.005;\n\tyVelocity = 0;\n}\n\nSandBox::~SandBox()\n{\n    delete objectsData;\n}\n\nvoid SandBox::OnNewMeshLoad()\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\tdata().dirty = 157; //this line prevents texture coordinates\n}\n\nvoid SandBox::Init(const std::string &config)\n{\n\t\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        double n = 0;\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\tparents.push_back(-1);\n\t\t\tdata().add_points(Eigen::RowVector3d(0, 0, 0), Eigen::RowVector3d(0, 0, 1));\n\t\t\tdata().show_overlay_depth = false;\n\t\t\tdata().point_size = 10;\n\t\t\tdata().line_width = 2;\n\t\t\tdata().set_visible(false, 1);\n\n            ObjectData* od = new ObjectData();\n            InitObjectData(*od, data().V, data().F);\n            objectsData->push_back(od);\n\n            double x = -1 + (n * 2);\n            double y = -1 + (n * 2);\n            MoveTo(x, y);\n\t\t\tdata().AddBoundingBox(od->tree->m_box, Eigen::RowVector3d(0, 1, 0));\n            data().dirty = 157; //this line prevents texture coordinates\n            n++;\n\t\t}\n\t\tnameFileout.close();\n\t}\n\tMyTranslate(Eigen::Vector3d(0, 0, -1), true);\n\tdata().set_colors(Eigen::RowVector3d(0.9, 0.1, 0.1));\n\tisActive = true;\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        data().TranslateInSystem(GetRotation(), Eigen::Vector3d(xVelocity, yVelocity, 0));\n\t\tif (ObjectsCollide(objectsData->at(0)->tree, objectsData->at(1)->tree))\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t{\n\t\t\tisActive = false;\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 firstMult = firstTrans * Eigen::Vector4d(firstBoxCenter(0), firstBoxCenter(1), firstBoxCenter(2), 1);\n\tEigen::Vector4d secondMult = secondTrans * Eigen::Vector4d(secondBoxCenter(0), secondBoxCenter(1), secondBoxCenter(2), 1);\n\n\tEigen::Vector3d C0(firstMult(0), firstMult(1), firstMult(2));\n\tEigen::Vector3d C1(secondMult(0), secondMult(1), secondMult(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", "meta": {"hexsha": "0baa8dd6cac36cb4d871056de3254f4d592cfae8", "size": 10593, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tutorial/sandBox/sandBox.cpp", "max_stars_repo_name": "danatzmi/Animation-Assignment2", "max_stars_repo_head_hexsha": "7461b57ad51d61814cd1f467863a431c7c08d84f", "max_stars_repo_licenses": ["Apache-2.0"], "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-Assignment2", "max_issues_repo_head_hexsha": "7461b57ad51d61814cd1f467863a431c7c08d84f", "max_issues_repo_licenses": ["Apache-2.0"], "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-Assignment2", "max_forks_repo_head_hexsha": "7461b57ad51d61814cd1f467863a431c7c08d84f", "max_forks_repo_licenses": ["Apache-2.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.9426229508, "max_line_length": 123, "alphanum_fraction": 0.5788728406, "num_tokens": 3977, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.481941276309868}}
{"text": "// Author of FLOAM: Wang Han\n// Email wh200720041@gmail.com\n// Homepage https://wanghan.pro\n#ifndef _LIDAR_OPTIMIZATION_ANALYTIC_H_\n#define _LIDAR_OPTIMIZATION_ANALYTIC_H_\n\n#include <ceres/ceres.h>\n#include <ceres/rotation.h>\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n\nEigen::Matrix3d skew(Eigen::Vector3d& mat_in) {\n  Eigen::Matrix<double, 3, 3> skew_mat;\n  skew_mat.setZero();\n  skew_mat(0, 1) = -mat_in(2);\n  skew_mat(0, 2) = mat_in(1);\n  skew_mat(1, 2) = -mat_in(0);\n  skew_mat(1, 0) = mat_in(2);\n  skew_mat(2, 0) = -mat_in(1);\n  skew_mat(2, 1) = mat_in(0);\n  return skew_mat;\n}\n\nvoid getTransformFromSe3(const Eigen::Matrix<double, 6, 1>& se3, Eigen::Quaterniond& q, Eigen::Vector3d& t) {\n  Eigen::Vector3d omega(se3.data());\n  Eigen::Vector3d upsilon(se3.data() + 3);\n  Eigen::Matrix3d Omega = skew(omega);\n\n  double theta = omega.norm();\n  double half_theta = 0.5 * theta;\n\n  double imag_factor;\n  double real_factor = cos(half_theta);\n  if (theta < 1e-10) {\n    double theta_sq = theta * theta;\n    double theta_po4 = theta_sq * theta_sq;\n    imag_factor = 0.5 - 0.0208333 * theta_sq + 0.000260417 * theta_po4;\n  } else {\n    double sin_half_theta = sin(half_theta);\n    imag_factor = sin_half_theta / theta;\n  }\n\n  q = Eigen::Quaterniond(real_factor, imag_factor * omega.x(), imag_factor * omega.y(), imag_factor * omega.z());\n\n  Eigen::Matrix3d J;\n  if (theta < 1e-10) {\n    J = q.matrix();\n  } else {\n    Eigen::Matrix3d Omega2 = Omega * Omega;\n    J = (Eigen::Matrix3d::Identity() + (1 - cos(theta)) / (theta * theta) * Omega + (theta - sin(theta)) / (pow(theta, 3)) * Omega2);\n  }\n\n  t = J * upsilon;\n}\n\n\n\nclass PoseSE3Parameterization : public ceres::LocalParameterization {\npublic:\n  PoseSE3Parameterization() {}\n  virtual ~PoseSE3Parameterization() {}\n  // \u4ece\u8fd9\u91cc\u770b\uff0c\u53c2\u6570\u5757\u5e94\u8be5\u662f[q,t]\uff0c\u4e14q\u662f[x,y,z,w]\n  virtual bool Plus(const double* x, const double* delta, double* x_plus_delta) const {\n    Eigen::Map<const Eigen::Vector3d> trans(x + 4);\n\n    Eigen::Quaterniond delta_q;\n    Eigen::Vector3d delta_t;\n    getTransformFromSe3(Eigen::Map<const Eigen::Matrix<double, 6, 1>>(delta), delta_q, delta_t);\n    Eigen::Map<const Eigen::Quaterniond> quater(x);\n    Eigen::Map<Eigen::Quaterniond> quater_plus(x_plus_delta);\n    Eigen::Map<Eigen::Vector3d> trans_plus(x_plus_delta + 4);\n    // TODO \u4e0d\u9700\u8981\u5f52\u4e00\u5316\u5417\uff1f\n    quater_plus = delta_q * quater;\n    trans_plus = delta_q * trans + delta_t;\n\n    return true;\n  }\n  // ref: https://github.com/wh200720041/floam/issues/50\n  // \u8fd9\u662f\u5168\u5c40\u53c2\u6570\u5230\u5c40\u90e8\u53c2\u6570\u7684\u96c5\u53ef\u6bd4\u77e9\u9635\u3002\u5168\u5c40\u662ftrans,quat\uff0c\u56e0\u6b64\u662f7\u7ef4\uff0c\u5c40\u90e8\u5219\u662fse3,\u56e0\u6b64\u662f6\u7ef4\u3002\n  // \u7b54\u6848\u4e2d\u63d0\u5230\u4e86J1*J2,\u5176\u4e2dJ1\u662f\u53c2\u6570\u5757\u5bf9[t,q]\u6c42\u5bfc\u6765\u81ea\u4e8eevaluate\u6216\u8005AD\uff0cJ2\u5219\u662f\u8fd9\u91cc\u7684\u5230\u674e\u4ee3\u6570\u7684\u53c2\u6570\u5316\u3002\n  virtual bool ComputeJacobian(const double* x, double* jacobian) const {\n    Eigen::Map<Eigen::Matrix<double, 7, 6, Eigen::RowMajor>> j(jacobian);\n    (j.topRows(6)).setIdentity();\n    (j.bottomRows(1)).setZero();\n\n    return true;\n  }\n  virtual int GlobalSize() const { return 7; }\n  virtual int LocalSize() const { return 6; }\n};\n\n#endif  // _LIDAR_OPTIMIZATION_ANALYTIC_H_\n", "meta": {"hexsha": "d619048cf4dc900bf0fafe480a1b2f5a79d683c6", "size": 2966, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/litamin2/ceres_cost/PoseSE3Parameterization.hpp", "max_stars_repo_name": "FishInWave/fast-gicp", "max_stars_repo_head_hexsha": "00e2dc6dd9cf8417ab36dfbceffa2bd56ed8371b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-12-26T04:12:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T11:06:30.000Z", "max_issues_repo_path": "include/litamin2/ceres_cost/PoseSE3Parameterization.hpp", "max_issues_repo_name": "FishInWave/fast-gicp", "max_issues_repo_head_hexsha": "00e2dc6dd9cf8417ab36dfbceffa2bd56ed8371b", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/litamin2/ceres_cost/PoseSE3Parameterization.hpp", "max_forks_repo_name": "FishInWave/fast-gicp", "max_forks_repo_head_hexsha": "00e2dc6dd9cf8417ab36dfbceffa2bd56ed8371b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-12-26T04:12:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T09:17:35.000Z", "avg_line_length": 31.8924731183, "max_line_length": 133, "alphanum_fraction": 0.6797033041, "num_tokens": 1022, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105941403651, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.48194127036664225}}
{"text": "/*\n * MIT License\n *\n * Copyright (c) 2020 International Business Machines\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\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// This is a sample program for education purposes only.\n// It implements a very simple homomorphic encryption based\n// db search algorithm for demonstration purposes.\n\n// This country lookup example is derived from the BGV database demo\n// code originally writte by Jack Crawford for a lunch and learn\n// session at IBM Research (Hursley) in 2019.\n// The original example code ships with HElib and can be found at\n// https://github.com/IBM-HElib/HElib/tree/master/examples/BGV_database_lookup\n//\n// INFO: The API used to create these examples can be found online\n// ML-HElib: https://ibm.github.io/fhe-toolkit-linux\n// HElib: https://ibm.github.io/fhe-toolkit-linux/html/helib/index.html\n//\n\n#include <iostream>\n\n#include \"helayers/hebase/hebase.h\"\n#include \"helayers/hebase/helib/HelibBgvContext.h\"\n#include <fstream>\n#include <helib/ArgMap.h>\n#include <NTL/BasicThreadPool.h>\n\nusing namespace helayers;\nusing namespace std;\n\n// Forward declarations. These functions are explained later.\nvector<pair<string, string>> read_csv(string filename, int maxLen);\nvoid run(HeContext& he,\n         const string& db_filename,\n         const std::string& countryName,\n         bool debug);\nbool isPowerOf2(int v);\nvector<int> stringToAscii(const string& val);\n\nint main(int argc, char* argv[])\n{\n  // Note: The parameters have been chosen to provide a somewhat\n  // faster running time with a non-realistic security level.\n  // Do Not use these parameters in real applications.\n\n  // Plaintext prime modulus\n  unsigned long p = 127;\n  // Cyclotomic polynomial - defines phi(m)\n  unsigned long m = 128; // this will give 32 slots\n  // Hensel lifting (default = 1)\n  unsigned long r = 1;\n  // Number of bits of the modulus chain\n  unsigned long bits = 1000;\n  // Number of columns of Key-Switching matrix (default = 2 or 3)\n  unsigned long c = 2;\n  // Size of NTL thread pool (default =1)\n  unsigned long nthreads = 1;\n  // input database file name\n  string db_filename =\n      getExamplesDir() + \"/BGV_world_country_db_lookup/countries_dataset.csv\";\n  // debug output (default no debug output)\n  bool debug = false;\n\n  string countryName = \"\";\n\n  helib::ArgMap amap;\n  amap.arg(\"m\", m, \"Cyclotomic polynomial ring\");\n  amap.arg(\"p\", p, \"Plaintext prime modulus\");\n  amap.arg(\"r\", r, \"Hensel lifting\");\n  amap.arg(\"bits\", bits, \"# of bits in the modulus chain\");\n  amap.arg(\"c\", c, \"# fo columns of Key-Switching matrix\");\n  amap.arg(\"nthreads\", nthreads, \"Size of NTL thread pool\");\n  amap.arg(\n      \"db_filename\", db_filename, \"Qualified name for the database filename\");\n  amap.arg(\"country\", countryName, \"Country to search for\");\n  amap.toggle().arg(\"-debug\", debug, \"Toggle debug output\", \"\");\n  amap.parse(argc, argv);\n\n  // set NTL Thread pool size\n  if (nthreads > 1)\n    NTL::SetNumThreads(nthreads);\n\n  cout << \"\\n*********************************************************\";\n  cout << \"\\n*           Privacy Preserving Search Example           *\";\n  cout << \"\\n*           =================================           *\";\n  cout << \"\\n*                                                       *\";\n  cout << \"\\n* This is a sample program for education purposes only. *\";\n  cout << \"\\n* It implements a very simple homomorphic encryption    *\";\n  cout << \"\\n* based db search algorithm for demonstration purposes. *\";\n  cout << \"\\n*                                                       *\";\n  cout << \"\\n*********************************************************\";\n  cout << endl;\n\n  cout << \"---Initialising HE Environment ... \";\n  // Initialize context\n  cout << \"\\nInitializing the Context ... \" << endl;\n\n  // To setup helib using the hebase layer, let's first\n  // copy all configuration params to an HelibConfig object:\n  HelibConfig conf;\n  conf.p = p;\n  conf.m = m;\n  conf.r = r;\n  conf.L = bits;\n  conf.c = c;\n\n  // Next we'll initialize a BGV scheme in helib.\n  // The following two lines perform full intializiation\n  // Including key generation.\n  // (We added code for timing it).\n  HELIB_NTIMER_START(timer_Context);\n  HelibBgvContext he;\n  he.init(conf);\n  HELIB_NTIMER_STOP(timer_Context);\n\n  // Helib-BGV is now ready to start doing some HE work.\n  // which we'll do in the follwing function, defined below\n  run(he, db_filename, countryName, debug);\n\n  return 0;\n}\n\nvoid run(HeContext& he,\n         const string& db_filename,\n         const std::string& countryName,\n         bool debug)\n{\n\n  // The run function receives an abstract HeContext class.\n  // Therefore the code below is oblivious to a particular HE scheme\n  // implementation.\n\n  // First let's print general information on our library and scheme.\n  // This will print their names, and the configuraton details.\n  he.printSignature();\n\n  // However we do have some requirements that we can\n  // assert exists:\n  // We require the plaintext to be over modular arithmetic.\n  // We'll rely on that later.\n  always_assert(he.getTraits().getIsModularArithmetic());\n  // Since we store ascii codes, we need it at least to be able\n  // to handle the numbers 0...127\n  always_assert(he.getTraits().getArithmeticModulus() >= 127);\n\n  // Next, print the security level\n  // Note: This will be negligible to improve performance time.\n  cout << \"\\n***Security Level: \" << he.getSecurityLevel()\n       << \" *** Negligible for this example ***\" << endl;\n\n  // Let's also print the number of slots.\n  // Each ciphertext will have this many slots.\n  cout << \"\\nNumber of slots: \" << he.slotCount() << endl;\n\n  // Now we'll read in the database (in cleartext).\n  // This function we'll make sure no string is longer than he.slotCount()\n  vector<pair<string, string>> country_db =\n      read_csv(db_filename, he.slotCount());\n\n  cout << \"\\n---Initializing the encrypted key,value pair database (\"\n       << country_db.size() << \" entries)...\";\n  cout << \"\\nConverting strings to numeric representation into Ptxt objects ...\"\n       << endl;\n\n  // We'll now encrypt our country-capital database.\n  HELIB_NTIMER_START(timer_CtxtCountryDB);\n  // The encoder class handles both encoding and encrypting.\n  Encoder enc(he);\n  // This is the database: a vector of pairs of CTile-s.\n  // A CTile is a ciphertext object.\n  vector<pair<CTile, CTile>> encrypted_country_db;\n  for (const auto& country_capital_pair : country_db) {\n    // Create a country ciphertext, and encrypt inside\n    // the ascii vector representation of each country.\n    // For example, Norway is represented\n    // (78,111,114,119,97,121,  0,0,0, ...)\n    CTile country(he);\n    enc.encodeEncrypt(country, stringToAscii(country_capital_pair.first));\n    // Similarly encrypt the capital name\n    CTile capital(he);\n    enc.encodeEncrypt(capital, stringToAscii(country_capital_pair.second));\n    // Add the pair to the database\n    encrypted_country_db.emplace_back(move(country), move(capital));\n  }\n  HELIB_NTIMER_STOP(timer_CtxtCountryDB);\n\n  if (debug) {\n    helib::printNamedTimer(cout << endl, \"timer_Context\");\n    helib::printNamedTimer(cout, \"timer_CtxtCountryDB\");\n  }\n\n  cout << \"\\nInitialization Completed - Ready for Queries\" << endl;\n  cout << \"--------------------------------------------\" << endl;\n\n  /** Create the query **/\n\n  // Read in query from the command line\n  string query_string;\n  if (countryName == \"\") {\n    cout << \"\\nPlease enter the name of a Country: \";\n    getline(cin, query_string);\n  } else\n    query_string = countryName;\n\n  cout << \"Looking for the Capital of \" << query_string << endl;\n  cout << \"This may take a few minutes ... \" << endl;\n\n  HELIB_NTIMER_START(timer_TotalQuery);\n  HELIB_NTIMER_START(timer_EncryptQuery);\n\n  // Encrypt the query similar to the way we encrypted\n  // the country and capital names\n  CTile query(he);\n  enc.encodeEncrypt(query, stringToAscii(query_string));\n\n  HELIB_NTIMER_STOP(timer_EncryptQuery);\n\n  /************ Perform the database search ************/\n\n  HELIB_NTIMER_START(timer_QuerySearch);\n  vector<CTile> mask;\n  mask.reserve(country_db.size());\n  NativeFunctionEvaluator eval(he);\n  long modulusP = he.getTraits().getArithmeticModulus();\n\n  // For every entry in our database we perform the following\n  // calculation:\n  for (const auto& encrypted_pair : encrypted_country_db) {\n    //  Copy of database key: a country name\n    CTile mask_entry = encrypted_pair.first;\n    // Calculate the difference\n    // In each slot now we'll have 0 when characters match,\n    // or non-zero when there's a mismatch\n    mask_entry.sub(query);\n\n    // Fermat's little theorem:\n    // Since the underlying plaintext are in modular arithmetic,\n    // Raising to the power of modulusP convers all non-zero values\n    // to 1.\n    eval.powerInPlace(mask_entry, modulusP - 1);\n\n    // Negate the ciphertext\n    // Now we'll have 0 for match, -1 for mismatch\n    mask_entry.negate();\n\n    // Add +1\n    // Now we'll have 1 for match, 0 for mismatch\n    mask_entry.addScalar(1);\n\n    // We'll now multiply all slots together, since\n    // we want a complete match across all slots.\n\n    // If slot count is a power of 2 there's an efficient way\n    // to do it:\n    // we'll do a rotate-and-multiply algorithm, similar to\n    // a rotate-and-sum one.\n    if (isPowerOf2(he.slotCount())) {\n      for (int rot = 1; rot < he.slotCount(); rot *= 2) {\n        CTile tmp(mask_entry);\n        tmp.rotate(-rot);\n        mask_entry.multiply(tmp);\n      }\n    } else {\n      // Otherwise we'll create all possible rotations, and multiply all of\n      // them.\n      // Note that for non powers of 2 a rotate-and-multiply algorithm\n      // can still be used as well, though it's more complicated and\n      // beyond the scope of this example.\n      vector<CTile> rotated_masks(he.slotCount(), mask_entry);\n      for (int i = 1; i < rotated_masks.size(); i++)\n        rotated_masks[i].rotate(-i); // Rotate each of the masks\n      eval.totalProduct(mask_entry,\n                        rotated_masks); // Multiply each of the masks\n    }\n\n    // mask_entry is now either all 1s if query==country,\n    // or all 0s otherwise.\n    // After we multiply by capital name it will be either\n    // the capital name, or all 0s.\n    mask_entry.multiply(encrypted_pair.second);\n    // We collect all our findings.\n    mask.push_back(mask_entry);\n  }\n  HELIB_NTIMER_STOP(timer_QuerySearch);\n\n  // Aggregate the results into a single ciphertext\n  // Note: This code is for educational purposes and thus we try to refrain\n  // from using the STL and do not use std::accumulate\n  CTile value = mask[0];\n  for (int i = 1; i < mask.size(); i++)\n    value.add(mask[i]);\n\n  // /************ Decrypt and print result ************/\n\n  HELIB_NTIMER_START(timer_DecryptQueryResult);\n  vector<int> res = enc.decryptDecodeInt(value);\n  HELIB_NTIMER_STOP(timer_DecryptQueryResult);\n\n  // Convert from ASCII to a string\n  string string_result;\n  for (long i = 0; i < res.size(); ++i)\n    string_result.push_back(static_cast<long>(res[i]));\n\n  HELIB_NTIMER_STOP(timer_TotalQuery);\n\n  // Print DB Query Timers\n  if (debug) {\n    helib::printNamedTimer(cout << endl, \"timer_EncryptQuery\");\n    helib::printNamedTimer(cout, \"timer_QuerySearch\");\n    helib::printNamedTimer(cout, \"timer_DecryptQueryResult\");\n    cout << endl;\n  }\n\n  if (string_result.at(0) == 0x00) {\n    string_result = \"Country name not in the database.\\n*** Please make sure \"\n                    \"to enter the name of an European Country\\n*** with the \"\n                    \"first letter in upper case.\";\n  }\n\n  cout << \"\\nQuery result: \" << string_result << endl;\n  helib::printNamedTimer(std::cout, \"timer_TotalQuery\");\n}\n\n// Utility function to read <K,V> CSV data from file\nvector<pair<string, string>> read_csv(string filename, int maxLen)\n{\n  vector<pair<string, string>> dataset;\n  ifstream data_file(filename);\n\n  if (!data_file.is_open())\n    throw runtime_error(\n        \"Error: This example failed trying to open the data file: \" + filename +\n        \"\\n           Please check this file exists and try again.\");\n\n  vector<string> row;\n  string line, entry, temp;\n\n  if (data_file.good()) {\n    // Read each line of file\n    while (getline(data_file, line)) {\n      row.clear();\n      stringstream ss(line);\n      while (getline(ss, entry, ',')) {\n        row.push_back(entry);\n      }\n      if (row[0].size() > maxLen)\n        throw runtime_error(\"Country name \" + row[0] + \" too long\");\n      if (row[1].size() > maxLen)\n        throw runtime_error(\"Capital name \" + row[1] + \" too long\");\n\n      // Add key value pairs to dataset\n      dataset.push_back(make_pair(row[0], row[1]));\n    }\n  }\n\n  data_file.close();\n  return dataset;\n}\n\n// Return a vector of ints with the i'th element containing the ascii\n// code of the i'th character\nvector<int> stringToAscii(const string& val)\n{\n  vector<int> res;\n  res.reserve(val.size());\n  for (size_t i = 0; i < val.size(); ++i) {\n    res.push_back(val[i]);\n  }\n  return res;\n}\n\n// Returns true if v is a power of 2\nbool isPowerOf2(int v) { return (v & v - 1) == 0; }", "meta": {"hexsha": "5822ffd697da4def01109fc894717d94f0b08a99", "size": 14093, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "samples/BGV_world_country_db_lookup/BGV_world_country_db_lookup.cpp", "max_stars_repo_name": "vishalbelsare/fhe-toolkit-linux", "max_stars_repo_head_hexsha": "4911ce2e7eb47afb33c14fb57e83b1a442a7384e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1333.0, "max_stars_repo_stars_event_min_datetime": "2020-05-14T12:39:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T10:02:19.000Z", "max_issues_repo_path": "samples/BGV_world_country_db_lookup/BGV_world_country_db_lookup.cpp", "max_issues_repo_name": "vishalbelsare/fhe-toolkit-linux", "max_issues_repo_head_hexsha": "4911ce2e7eb47afb33c14fb57e83b1a442a7384e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 358.0, "max_issues_repo_issues_event_min_datetime": "2020-09-21T20:15:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-08T19:01:09.000Z", "max_forks_repo_path": "samples/BGV_world_country_db_lookup/BGV_world_country_db_lookup.cpp", "max_forks_repo_name": "vishalbelsare/fhe-toolkit-linux", "max_forks_repo_head_hexsha": "4911ce2e7eb47afb33c14fb57e83b1a442a7384e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2020-05-13T17:05:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T18:39:51.000Z", "avg_line_length": 35.8600508906, "max_line_length": 80, "alphanum_fraction": 0.6636628113, "num_tokens": 3467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494678483918, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.48190011901774127}}
{"text": "/* +------------------------------------------------------------------------+\n   |                     Mobile Robot Programming Toolkit (MRPT)            |\n   |                          https://www.mrpt.org/                         |\n   |                                                                        |\n   | Copyright (c) 2005-2022, Individual contributors, see AUTHORS file     |\n   | See: https://www.mrpt.org/Authors - All rights reserved.               |\n   | Released under BSD License. See: https://www.mrpt.org/License          |\n   +------------------------------------------------------------------------+ */\n\n#include <gtest/gtest.h>\n#include <mrpt/containers/yaml.h>\n#include <mrpt/math/CMatrixFixed.h>\n\n#include <Eigen/Dense>\n#include <sstream>\n\n#include \"mrpt_test.h\"\n\nMRPT_TEST(MatrixYaml, FromToEigen)\n{\n\tconst Eigen::MatrixXd m = Eigen::MatrixXd::Identity(3, 4);\n\tconst auto y1 = mrpt::containers::yaml::FromMatrix(m);\n\n\tmrpt::containers::yaml d = mrpt::containers::yaml::Map();\n\td[\"K\"] = y1;\n\n\tEXPECT_TRUE(y1.isMap());\n\tEXPECT_TRUE(y1.has(\"rows\"));\n\tEXPECT_TRUE(y1.has(\"cols\"));\n\tEXPECT_TRUE(y1.has(\"data\"));\n\n\tEXPECT_TRUE(y1[\"rows\"].isScalar());\n\tEXPECT_TRUE(y1[\"cols\"].isScalar());\n\tEXPECT_TRUE(y1[\"data\"].isSequence());\n\tEXPECT_EQ(y1[\"data\"].asSequence().size(), 12UL);\n\n\tconst std::string expectedStr = R\"(K:\n  cols: 4\n  data: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0]\n  rows: 3\n)\";\n\n\tmrpt::containers::YamlEmitOptions eo;\n\teo.emitHeader = false;\n\n\tstd::stringstream ss;\n\td.printAsYAML(ss, eo);\n\tEXPECT_EQ(expectedStr, ss.str());\n\n\t// 2nd part: to Eigen:\n\t{\n\t\tEigen::MatrixXd m2;\n\t\ty1.toMatrix(m2);\n\t\tEXPECT_EQ(m2.cols(), m.cols());\n\t\tEXPECT_EQ(m2.rows(), m.rows());\n\t\tEXPECT_EQ(m2, m);\n\t}\n\t{\n\t\tEigen::Matrix<double, 3, 4> m2;\n\t\ty1.toMatrix(m2);\n\t\tEXPECT_EQ(m2.cols(), m.cols());\n\t\tEXPECT_EQ(m2.rows(), m.rows());\n\t\tEXPECT_EQ(m2, m);\n\t}\n\t{\n\t\tEigen::Matrix<double, 3, 3> m2;\n\t\tEXPECT_ANY_THROW(y1.toMatrix(m2));\n\t}\n}\nMRPT_TEST_END()\n\nMRPT_TEST(MatrixYaml, Vector)\n{\n\tconst Eigen::Vector3d m = Eigen::Vector3d::Constant(1.0);\n\tconst auto y1 = mrpt::containers::yaml::FromMatrix(m);\n\n\tEXPECT_TRUE(y1.isMap());\n\tEXPECT_TRUE(y1.has(\"rows\"));\n\tEXPECT_TRUE(y1.has(\"cols\"));\n\tEXPECT_TRUE(y1.has(\"data\"));\n\n\tEXPECT_EQ(y1[\"rows\"].as<int>(), 3);\n\tEXPECT_EQ(y1[\"cols\"].as<int>(), 1);\n\tEXPECT_TRUE(y1[\"data\"].isSequence());\n\tEXPECT_EQ(y1[\"data\"].asSequence().size(), 3UL);\n}\nMRPT_TEST_END()\n", "meta": {"hexsha": "ef4e1e5261f74f29b3666499dbd6eb1a2c5fd00f", "size": 2403, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/src/matrix_yaml_unittest.cpp", "max_stars_repo_name": "wstnturner/mrpt", "max_stars_repo_head_hexsha": "b0be3557a4cded6bafff03feb28f7fa1f75762a3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 38.0, "max_stars_repo_stars_event_min_datetime": "2015-01-04T05:24:26.000Z", "max_stars_repo_stars_event_max_datetime": "2015-07-17T00:30:02.000Z", "max_issues_repo_path": "libs/math/src/matrix_yaml_unittest.cpp", "max_issues_repo_name": "wstnturner/mrpt", "max_issues_repo_head_hexsha": "b0be3557a4cded6bafff03feb28f7fa1f75762a3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 40.0, "max_issues_repo_issues_event_min_datetime": "2015-01-03T22:43:00.000Z", "max_issues_repo_issues_event_max_datetime": "2015-07-17T18:52:59.000Z", "max_forks_repo_path": "libs/math/src/matrix_yaml_unittest.cpp", "max_forks_repo_name": "wstnturner/mrpt", "max_forks_repo_head_hexsha": "b0be3557a4cded6bafff03feb28f7fa1f75762a3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2015-01-06T12:32:19.000Z", "max_forks_repo_forks_event_max_datetime": "2017-05-30T15:50:13.000Z", "avg_line_length": 27.3068181818, "max_line_length": 80, "alphanum_fraction": 0.5634623387, "num_tokens": 684, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300698514777, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.4819001185414885}}
{"text": "#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MAIN\n#include <boost/test/unit_test.hpp>\n\n#include \"Translate.hpp\"\nusing namespace QuadProgMm;\n\n#define CHECK_SIZES(t) do { \\\n  BOOST_CHECK_EQUAL(t.variables.size(), t.G.nrows()); \\\n  BOOST_CHECK_EQUAL(t.G.ncols(), t.G.nrows()); \\\n  BOOST_CHECK_EQUAL(t.g0.size(), t.G.nrows()); \\\n  BOOST_CHECK_EQUAL(t.CE.nrows(), t.G.nrows()); \\\n  BOOST_CHECK_EQUAL(t.ce0.size(), t.CE.ncols()); \\\n  BOOST_CHECK_EQUAL(t.CI.nrows(), t.G.nrows()); \\\n  BOOST_CHECK_EQUAL(t.ci0.size(), t.CI.ncols()); \\\n} while(false)\n\n#define CHECK_MATRIX(actual, expected) do { \\\n  const int rows = expected.size(); \\\n  BOOST_CHECK_EQUAL(actual.nrows(), rows); \\\n  if(rows) { \\\n    for(int row = 0; row != rows; ++row) { \\\n      const int cols = expected[row].size(); \\\n      BOOST_CHECK_EQUAL(actual.ncols(), cols); \\\n      for(int col = 0; col != cols; ++col) { \\\n        BOOST_CHECK_EQUAL(actual[row][col], expected[row][col]); \\\n      } \\\n    } \\\n  } else { \\\n    BOOST_CHECK_EQUAL(actual.ncols(), 0); \\\n  } \\\n} while(false)\n\n#define CHECK_VECTOR(actual, expected) do { \\\n  const int n = expected.size(); \\\n  BOOST_CHECK_EQUAL(actual.size(), n); \\\n  for(int i = 0; i != n; ++i) { \\\n    BOOST_CHECK_EQUAL(actual[i], expected[i]); \\\n  } \\\n} while(false)\n\n#define CHECK_QUADRATIC_EXPRESSION_TRANSLATION(q, _G, _G0, expected_g00) do { \\\n  const Translation t = translate(q, {}); \\\n  const std::vector<std::vector<double>> expected_G _G; \\\n  const std::vector<double> expected_g0 _G0; \\\n  CHECK_SIZES(t); \\\n  CHECK_MATRIX(t.G, expected_G); \\\n  CHECK_VECTOR(t.g0, expected_g0); \\\n  BOOST_CHECK_EQUAL(t.g00, expected_g00); \\\n} while(false)\n\nBOOST_AUTO_TEST_CASE(TranslateQuadraticExpression) {\n  Variable a, b;\n\n  CHECK_QUADRATIC_EXPRESSION_TRANSLATION(0, {}, {}, 0);\n  CHECK_QUADRATIC_EXPRESSION_TRANSLATION(1, {}, {}, 1);\n  CHECK_QUADRATIC_EXPRESSION_TRANSLATION(a, {{0}}, {1}, 0);\n  CHECK_QUADRATIC_EXPRESSION_TRANSLATION(1 + a, {{0}}, {1}, 1);\n  CHECK_QUADRATIC_EXPRESSION_TRANSLATION(a*a, {{2}}, {0}, 0);\n  CHECK_QUADRATIC_EXPRESSION_TRANSLATION(1 + a*a, {{2}}, {0}, 1);\n  CHECK_QUADRATIC_EXPRESSION_TRANSLATION(1 + a + a*a, {{2}}, {1}, 1);\n  CHECK_QUADRATIC_EXPRESSION_TRANSLATION(0.5*a*a, {{1}}, {0}, 0);\n  CHECK_QUADRATIC_EXPRESSION_TRANSLATION(a*a + b*b, ({{2, 0}, {0, 2}}), ({0, 0}), 0);\n  CHECK_QUADRATIC_EXPRESSION_TRANSLATION(a*a + 0.5*b*b, ({{2, 0}, {0, 1}}), ({0, 0}), 0);\n  CHECK_QUADRATIC_EXPRESSION_TRANSLATION(0.5*b*b + a*a, ({{2, 0}, {0, 1}}), ({0, 0}), 0);\n  CHECK_QUADRATIC_EXPRESSION_TRANSLATION(a*b, ({{0, 1}, {1, 0}}), ({0, 0}), 0);\n  CHECK_QUADRATIC_EXPRESSION_TRANSLATION(b*a, ({{0, 1}, {1, 0}}), ({0, 0}), 0);\n  CHECK_QUADRATIC_EXPRESSION_TRANSLATION(a*a + 2*b*b + 3*b*a + 4*a + 5*b + 6, ({{2, 3}, {3, 4}}), ({4, 5}), 6);\n}\n\n#define CHECK_EQUALITY_CONSTRAINT_TRANSLATION(c, _CE, _CE0) do { \\\n  const Translation t = translate(0, {c}); \\\n  const std::vector<std::vector<double>> expected_CE _CE; \\\n  const std::vector<double> expected_ce0 _CE0; \\\n  CHECK_SIZES(t); \\\n  CHECK_MATRIX(t.CE, expected_CE); \\\n  CHECK_VECTOR(t.ce0, expected_ce0); \\\n} while(false)\n\nBOOST_AUTO_TEST_CASE(TranslateEqualityConstraint) {\n  Variable a, b;\n\n  CHECK_EQUALITY_CONSTRAINT_TRANSLATION(a == 0, {{1}}, {0});\n  CHECK_EQUALITY_CONSTRAINT_TRANSLATION(a == 1, {{1}}, {-1});\n  CHECK_EQUALITY_CONSTRAINT_TRANSLATION(2*a == 1, {{2}}, {-1});\n  CHECK_EQUALITY_CONSTRAINT_TRANSLATION(a == 0.5, {{1}}, {-0.5});\n  CHECK_EQUALITY_CONSTRAINT_TRANSLATION(a - a == 0, {{0}}, {0});\n  CHECK_EQUALITY_CONSTRAINT_TRANSLATION(a + b == 0, ({{1}, {1}}), {0});\n  CHECK_EQUALITY_CONSTRAINT_TRANSLATION(a + b + 2 == 0, ({{1}, {1}}), {2});\n  CHECK_EQUALITY_CONSTRAINT_TRANSLATION(b + a + 2 == 0, ({{1}, {1}}), {2});\n  CHECK_EQUALITY_CONSTRAINT_TRANSLATION(a + 2*b + 3 == 0, ({{1}, {2}}), {3});\n  CHECK_EQUALITY_CONSTRAINT_TRANSLATION(b + 2*a + 3 == 0, ({{2}, {1}}), {3});\n}\n\n#define CHECK_INEQUALITY_CONSTRAINT_TRANSLATION(c, _CI, _CI0) do { \\\n  const Translation t = translate(0, {c}); \\\n  const std::vector<std::vector<double>> expected_CI _CI; \\\n  const std::vector<double> expected_ci0 _CI0; \\\n  CHECK_SIZES(t); \\\n  CHECK_MATRIX(t.CI, expected_CI); \\\n  CHECK_VECTOR(t.ci0, expected_ci0); \\\n} while(false)\n\nBOOST_AUTO_TEST_CASE(TranslateGreaterThanConstraint) {\n  Variable a, b;\n\n  CHECK_INEQUALITY_CONSTRAINT_TRANSLATION(a >= 0, {{1}}, {0});\n  CHECK_INEQUALITY_CONSTRAINT_TRANSLATION(a >= 1, {{1}}, {-1});\n  CHECK_INEQUALITY_CONSTRAINT_TRANSLATION(2*a >= 1, {{2}}, {-1});\n  CHECK_INEQUALITY_CONSTRAINT_TRANSLATION(a >= 0.5, {{1}}, {-0.5});\n  CHECK_INEQUALITY_CONSTRAINT_TRANSLATION(a - a >= 0, {{0}}, {0});\n  CHECK_INEQUALITY_CONSTRAINT_TRANSLATION(a + b >= 0, ({{1}, {1}}), {0});\n  CHECK_INEQUALITY_CONSTRAINT_TRANSLATION(a + b + 2 >= 0, ({{1}, {1}}), {2});\n  CHECK_INEQUALITY_CONSTRAINT_TRANSLATION(b + a + 2 >= 0, ({{1}, {1}}), {2});\n  CHECK_INEQUALITY_CONSTRAINT_TRANSLATION(a + 2*b + 3 >= 0, ({{1}, {2}}), {3});\n  CHECK_INEQUALITY_CONSTRAINT_TRANSLATION(b + 2*a + 3 >= 0, ({{2}, {1}}), {3});\n}\n\nBOOST_AUTO_TEST_CASE(TranslateLessThanConstraint) {\n  Variable a, b;\n\n  CHECK_INEQUALITY_CONSTRAINT_TRANSLATION(a <= 0, {{-1}}, {0});\n  CHECK_INEQUALITY_CONSTRAINT_TRANSLATION(a <= 1, {{-1}}, {1});\n  CHECK_INEQUALITY_CONSTRAINT_TRANSLATION(2*a <= 1, {{-2}}, {1});\n  CHECK_INEQUALITY_CONSTRAINT_TRANSLATION(a <= 0.5, {{-1}}, {0.5});\n  CHECK_INEQUALITY_CONSTRAINT_TRANSLATION(a - a <= 0, {{0}}, {0});\n  CHECK_INEQUALITY_CONSTRAINT_TRANSLATION(a + b <= 0, ({{-1}, {-1}}), {0});\n  CHECK_INEQUALITY_CONSTRAINT_TRANSLATION(a + b + 2 <= 0, ({{-1}, {-1}}), {-2});\n  CHECK_INEQUALITY_CONSTRAINT_TRANSLATION(b + a + 2 <= 0, ({{-1}, {-1}}), {-2});\n  CHECK_INEQUALITY_CONSTRAINT_TRANSLATION(a + 2*b + 3 <= 0, ({{-1}, {-2}}), {-3});\n  CHECK_INEQUALITY_CONSTRAINT_TRANSLATION(b + 2*a + 3 <= 0, ({{-2}, {-1}}), {-3});\n}\n\nauto d2(Variable left, Variable right, float l0) {\n  auto d = (right - left) - l0;\n  return d * d;\n}\n\nBOOST_AUTO_TEST_CASE(MixedConstraints) {\n  Variable a, b, c;\n\n  Translation t = translate(0, {\n    a == 1,\n    a <= 4,\n    b >= 8,\n    a >= 7,\n    b == 2,\n    c >= 9,\n    b <= 5,\n    c <= 6,\n  });\n\n  CHECK_SIZES(t);\n\n  CHECK_MATRIX(t.CE, std::vector<std::vector<double>>({{1, 0}, {0, 1}, {0, 0}}));\n  CHECK_VECTOR(t.ce0, std::vector<double>({-1, -2}));\n\n  CHECK_MATRIX(t.CI, std::vector<std::vector<double>>({{-1, 0, 1, 0, 0, 0}, {0, 1, 0, 0, -1, 0}, {0, 0, 0, 1, 0, -1}}));\n  CHECK_VECTOR(t.ci0, std::vector<double>({4, -8, -7, -9, 5, 6}));\n}\n\nBOOST_AUTO_TEST_CASE(SpringChainExample) {\n  Variable x0, x1, x2, x3, x4;\n  Translation t = translate(\n    0.5 * (\n      1 * d2(x0, x1, 2)\n      + 1 * d2(x1, x2, 3)\n      + 10 * d2(x2, x3, 5)\n      + 1 * d2(x3, x4, 2)\n    ),\n    {x0 == 0, x4 == 10}\n  );\n\n  CHECK_SIZES(t);\n\n  CHECK_MATRIX(t.G, std::vector<std::vector<double>>({\n    { 1, -1,   0,   0,  0},\n    {-1,  2,  -1,   0,  0},\n    { 0, -1,  11, -10,  0},\n    { 0,  0, -10,  11, -1},\n    { 0,  0,   0,  -1,  1},\n  }));\n  CHECK_VECTOR(t.g0, std::vector<double>({2, 1, 47, -48, -2}));\n  BOOST_CHECK_EQUAL(t.g00, 133.5);\n\n  CHECK_MATRIX(t.CE, std::vector<std::vector<double>>({{1, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 1}}));\n  CHECK_VECTOR(t.ce0, std::vector<double>({0, -10}));\n\n  CHECK_MATRIX(t.CI, std::vector<std::vector<double>>({{}, {}, {}, {}, {}}));\n  CHECK_VECTOR(t.ci0, std::vector<double>({}));\n}\n\nBOOST_AUTO_TEST_CASE(QuickStart) {\n  Variable a, b, c;\n\n  Translation t = translate(\n    a + b + (a - b) * (a - b) + c + (b - c) * (b - c),\n    {a <= 1, c >= 4, a - 2 * b <= 12}\n  );\n\n  CHECK_SIZES(t);\n\n  CHECK_MATRIX(t.G, std::vector<std::vector<double>>({\n    {2, -2, 0},\n    {-2, 4, -2},\n    {0, -2, 2},\n  }));\n  CHECK_VECTOR(t.g0, std::vector<double>({1, 1, 1}));\n  BOOST_CHECK_EQUAL(t.g00, 0);\n\n  CHECK_MATRIX(t.CE, std::vector<std::vector<double>>({{}, {}, {}}));\n  CHECK_VECTOR(t.ce0, std::vector<double>({}));\n\n  CHECK_MATRIX(t.CI, std::vector<std::vector<double>>({\n    {-1, 0, -1},\n    {0, 0, 2},\n    {0, 1, 0},\n  }));\n  CHECK_VECTOR(t.ci0, std::vector<double>({1, -4, 12}));\n}\n", "meta": {"hexsha": "5c4ff84238bee3eb4ab55f21ebe0877ceb73c004", "size": 7993, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/Translate-test.cc", "max_stars_repo_name": "jacquev6/QuadProgMm", "max_stars_repo_head_hexsha": "992ccd82a00bfcbe724d2bcc12a8ceffbffcc8b2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-09-03T15:02:43.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-24T01:10:29.000Z", "max_issues_repo_path": "src/Translate-test.cc", "max_issues_repo_name": "jacquev6/QuadProgMm", "max_issues_repo_head_hexsha": "992ccd82a00bfcbe724d2bcc12a8ceffbffcc8b2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Translate-test.cc", "max_forks_repo_name": "jacquev6/QuadProgMm", "max_forks_repo_head_hexsha": "992ccd82a00bfcbe724d2bcc12a8ceffbffcc8b2", "max_forks_repo_licenses": ["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.1674208145, "max_line_length": 120, "alphanum_fraction": 0.6055298386, "num_tokens": 2833, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.685949467848392, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.48190011474555455}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n\nusing namespace Eigen;\n\nint main()\n{\n  Matrix4d m;\n  m.resize(4,4); // no operation\n  std::cout << \"The matrix m is of size \"\n            << m.rows() << \"x\" << m.cols() << std::endl;\n}\n", "meta": {"hexsha": "dcbdfa783d3693b7c4415d580ace1cdf626c4c1b", "size": 229, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Eigen-3.3/doc/examples/tut_matrix_resize_fixed_size.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/doc/examples/tut_matrix_resize_fixed_size.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/doc/examples/tut_matrix_resize_fixed_size.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": 17.6153846154, "max_line_length": 56, "alphanum_fraction": 0.5676855895, "num_tokens": 68, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7025300449389326, "lm_q2_score": 0.6859494678483918, "lm_q1q2_score": 0.4819001104733676}}
{"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/**\n * @file Solve a double integrator optimal control problem as a nonlinear program.\n */\n\n#include <Eigen/Core>\n#include <smooth/feedback/collocation/dyn_error.hpp>\n#include <smooth/feedback/compat/ipopt.hpp>\n#include <smooth/feedback/ocp_to_nlp.hpp>\n\n#include <chrono>\n#include <iostream>\n\n#include \"ocp_doubleintegrator.hpp\"\n\n#ifdef ENABLE_PLOTTING\n#include \"common.hpp\"\n#include <matplot/matplot.h>\n#endif\n\nint main()\n{\n  smooth::feedback::test_ocp_derivatives(ocp_di);\n\n  // target optimality\n  double target_err = 1e-6;\n\n  // define mesh\n  smooth::feedback::Mesh<5, 10> mesh;\n\n  // declare solution variable\n  std::vector<decltype(ocp_di)::Solution> sols;\n  std::optional<smooth::feedback::NLPSolution> nlpsol;\n\n  const auto t0 = std::chrono::high_resolution_clock::now();\n\n  for (auto iter = 0u; iter < 10; ++iter) {\n    std::cout << \"---------- ITERATION \" << iter << \" ----------\" << std::endl;\n    std::cout << \"mesh: \" << mesh.N_ivals() << \" intervals, \" << mesh.N_colloc()\n              << \" collocation pts\" << std::endl;\n\n    // transcribe optimal control problem to nonlinear programming problem\n    const auto nlp = smooth::feedback::ocp_to_nlp<smooth::diff::Type::Analytic>(ocp_di, mesh);\n\n    // solve nonlinear programming problem\n    std::cout << \"solving...\" << std::endl;\n    nlpsol = smooth::feedback::solve_nlp_ipopt(\n      nlp,\n      nlpsol,\n      {\n        {\"print_level\", 5},\n      },\n      {\n        {\"linear_solver\", \"mumps\"},\n        {\"hessian_approximation\", \"exact\"},\n        // {\"derivative_test\", \"first-order\"},\n        // {\"derivative_test_print_all\", \"yes\"},\n        {\"print_timing_statistics\", \"yes\"},\n      },\n      {\n        {\"tol\", 1e-6},\n      });\n\n    // convert solution of nlp insto solution of ocp_di\n    auto sol = smooth::feedback::nlpsol_to_ocpsol(ocp_di, mesh, nlpsol.value());\n    sols.push_back(sol);\n\n    // calculate errors\n    mesh.increase_degrees();\n    auto errs = smooth::feedback::mesh_dyn_error(ocp_di.f, mesh, sol.t0, sol.tf, sol.x, sol.u);\n    mesh.decrease_degrees();\n\n    std::cout << \"interval errors \" << errs.transpose() << std::endl;\n\n    if (errs.maxCoeff() > target_err) {\n      mesh.refine_errors(errs, 0.1 * target_err);\n      nlpsol = smooth::feedback::ocpsol_to_nlpsol(ocp_di, mesh, sol);\n    } else {\n      break;\n    }\n  }\n\n  const auto dur = std::chrono::high_resolution_clock::now() - t0;\n\n  std::cout << \"TOTAL TIME: \" << std::chrono::duration_cast<std::chrono::milliseconds>(dur).count()\n            << \"ms\" << std::endl;\n\n#ifdef ENABLE_PLOTTING\n  using namespace matplot;\n\n  const auto tt = linspace(0., sols.back().tf, 500);\n  const auto tt_nodes =\n    r2v(mesh.all_nodes() | std::views::transform([&](double d) { return d * sols.back().tf; }));\n  const auto tt_weights = r2v(mesh.all_weights());\n\n  figure();\n  hold(on);\n  plot(tt_nodes, transform(tt_nodes, [](auto) { return 0; }), \"xk\")->marker_size(10);\n  plot(tt_nodes, tt_weights, \"or\")->marker_size(5);\n  for (auto it = 0u; const auto & sol : sols) {\n    int lw = it++ + 1 < sols.size() ? 1 : 2;\n    plot(tt, transform(tt, [&](double t) { return sol.x(t).x(); }), \"-r\")->line_width(lw);\n    plot(tt, transform(tt, [&](double t) { return sol.x(t).y(); }), \"-b\")->line_width(lw);\n  }\n  matplot::legend({\"nodes\", \"weights\", \"pos\", \"vel\"});\n\n  figure();\n  hold(on);\n  for (auto it = 0u; const auto & sol : sols) {\n    int lw = it++ + 1 < sols.size() ? 1 : 2;\n    plot(tt, transform(tt, [&](double t) { return sol.lambda_dyn(t).x(); }), \"-r\")->line_width(lw);\n    plot(tt, transform(tt, [&](double t) { return sol.lambda_dyn(t).y(); }), \"-b\")->line_width(lw);\n  }\n  matplot::legend({\"lambda_x\", \"lambda_y\"});\n\n  figure();\n  hold(on);\n  for (auto it = 0u; const auto & sol : sols) {\n    int lw = it++ + 1 < sols.size() ? 1 : 2;\n    plot(tt, transform(tt, [&](double t) { return sol.lambda_cr(t).x(); }), \"-r\")->line_width(lw);\n  }\n  matplot::legend(std::vector<std::string>{\"lambda_{cr}\"});\n\n  figure();\n  hold(on);\n  for (auto it = 0u; const auto & sol : sols) {\n    int lw = it++ + 1 < sols.size() ? 1 : 2;\n    plot(tt, transform(tt, [&sol](double t) { return sol.u(t).x(); }), \"-r\")->line_width(lw);\n  }\n  matplot::legend(std::vector<std::string>{\"input\"});\n\n  show();\n#endif\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "04b1a795f8eca018276bd89d08296fb7f93f431e", "size": 5502, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/ocp_doubleintegrator_nlp.cpp", "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": "examples/ocp_doubleintegrator_nlp.cpp", "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": "examples/ocp_doubleintegrator_nlp.cpp", "max_forks_repo_name": "tgurriet/smooth_feedback", "max_forks_repo_head_hexsha": "1f926cb4269741ddc09ba048af5bea5e0390a053", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1739130435, "max_line_length": 99, "alphanum_fraction": 0.6397673573, "num_tokens": 1529, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081926, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.48190010572492864}}
{"text": "#include <algorithm>\n#include <boost/math/tools/roots.hpp>\n#include <cmath>\n#include <cstdlib>\n#include <ibs>\n#include <iostream>\n#include <map>\n#include <math.h>\n#include <string>\n#include <vector>\n\nnamespace CTESYNCH {\n/*\n *****************************************************************************\n *****************************************************************************\n * FUNCTOR TO RETURN VOLTAGE * CHARGE - U0 AND DERIVATIVE AS TUPLE\n * THIS IS USED AS INPUT FOR BOOST NEWTON RAPHSON ROOT SEARCH.\n *****************************************************************************\n * Authors:\n *  - Tom Mertens\n *\n * History:\n *  - 10/08/2021 : updated version from original ste code\n *****************************************************************************\n * Arguments:\n * ----------\n *  - T const &target\n *      Target value for the voltage (RF compensate for U0 so U0 in eV)\n *  - std::vector<double> &voltages\n *      Voltages of RF systems IMPORTANT: first element is for main RF\n *  - std::vector<double> &harmonicNumbers\n *      Harmonic numbers  IMPORTANT: first element is for main RF\n *  - double charge\n *      Particle charge\n *  - T const &phi\n *      phase in rad\n ******************************************************************************\n ******************************************************************************\n */\ntemplate <class T> struct synchronousPhaseFunctor {\n  synchronousPhaseFunctor(T const &target, std::vector<double> &voltages,\n                          std::vector<double> &harmonicNumbers, double charge)\n      : U0(target), volts(voltages), hs(harmonicNumbers), ch(charge) {}\n  std::tuple<double, double> operator()(T const &phi) {\n\n    // init\n    T vrf = ch * volts[0] * sin(phi);\n    T dvrf = ch * volts[0] * cos(phi);\n\n    // add the rest taking harmonic numbers into account\n    for (int i = 1; i < hs.size(); i++) {\n      vrf += ch * volts[i] * sin((hs[i] / hs[0]) * phi);\n      dvrf += ch * volts[i] * (hs[i] / hs[0]) * cos((hs[i] / hs[0]) * phi);\n    }\n\n    std::tuple<double, double> out = {vrf - U0, dvrf};\n    return out;\n  }\n\nprivate:\n  T U0;\n  std::vector<double> volts;\n  std::vector<double> hs;\n  double ch;\n};\n\n/*\n================================================================================\n================================================================================\nBOOST NEWTON RAPHSON ROOT SEARCH FOR SYNCHRONOUS PHASE.\n================================================================================\n\n================================================================================\nArguments:\n\n//phi is in rad\n================================================================================\n================================================================================\n*/\ntemplate <class T>\nT synchronousPhaseFunctorRoot(T x, std::vector<double> &voltages,\n                              std::vector<double> &harmnumbers, double charge,\n                              T guess, T min, T max) {\n  // return cube root of x using 1st derivative and Newton_Raphson.\n  using namespace boost::math::tools;\n\n  const int digits =\n      std::numeric_limits<T>::digits; // Maximum possible binary digits accuracy\n                                      // for type T.\n  int get_digits = static_cast<int>(\n      digits * 0.6); // Accuracy doubles with each step, so stop when we have\n                     // just over half the digits correct.\n  const boost::uintmax_t maxit = 20;\n  boost::uintmax_t it = maxit;\n  T result = newton_raphson_iterate(\n      synchronousPhaseFunctor<T>(x, voltages, harmnumbers, charge), guess, min,\n      max, get_digits, it);\n  return result;\n};\n\n/********************************************************************************\n ********************************************************************************\n * CALCULATE TOTAL RF VOLTAGE FOR GIVEN PHASE (IN RAD)\n *\n ********************************************************************************\n */\ndouble VoltageRf(double phi, std::vector<double> &volts,\n                 std::vector<double> &hs) {\n  double vrf = volts[0] * sin(phi);\n\n  for (int i = 1; i < hs.size(); i++) {\n    vrf += volts[i] * sin((hs[i] / hs[0]) * phi);\n  }\n\n  return vrf;\n};\n\ndouble VoltageRfPrime(double phi, double charge, std::vector<double> &volts,\n                      std::vector<double> &hs) {\n  // init\n  double vrf = volts[0] * cos(phi);\n\n  // add other rfs\n  for (int i = 1; i < volts.size(); i++) {\n    vrf += volts[i] * (hs[i] / hs[0]) * cos((hs[i] / hs[0]) * phi);\n  }\n\n  // V -> eV\n  vrf *= charge;\n  return vrf;\n}\n\ndouble SynchrotronTune(std::map<std::string, double> &twheader,\n                       std::map<std::string, double> &longparams,\n                       std::vector<double> &volts, std::vector<double> &hs) {\n\n  double charge = twheader[\"CHARGE\"];\n  double phis = longparams[\"phis\"];\n  double pc = twheader[\"PC\"];\n\n  return sqrt(hs[0] * twheader[\"eta\"] *\n              fabs(charge * VoltageRfPrime(phis, charge, volts, hs)) /\n              (2 * pi * pc * 1e9));\n}\n} // namespace CTESYNCH", "meta": {"hexsha": "ed5f96cc6bdcd8dabb78082d2373337197434ddc", "size": 5053, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/src/synch.cpp", "max_stars_repo_name": "tomerten/ctelib", "max_stars_repo_head_hexsha": "582c215667e240a65f07ac75468e0870bee88a4d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cpp/src/synch.cpp", "max_issues_repo_name": "tomerten/ctelib", "max_issues_repo_head_hexsha": "582c215667e240a65f07ac75468e0870bee88a4d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp/src/synch.cpp", "max_forks_repo_name": "tomerten/ctelib", "max_forks_repo_head_hexsha": "582c215667e240a65f07ac75468e0870bee88a4d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.8482758621, "max_line_length": 81, "alphanum_fraction": 0.4557688502, "num_tokens": 1123, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.828938820999257, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.48186469860192127}}
{"text": "#include <iostream>\n\n#include <El.hpp>\n#include <boost/mpi.hpp>\n#include <boost/format.hpp>\n\n#define SKYLARK_NO_ANY\n#include <skylark.hpp>\n\n#include <H5Cpp.h>\n\nnamespace bmpi =  boost::mpi;\nnamespace skybase = skylark::base;\nnamespace skysketch =  skylark::sketch;\nnamespace skynla = skylark::nla;\nnamespace skyalg = skylark::algorithms;\nnamespace skyutil = skylark::utility;\n\nint main(int argc, char** argv) {\n\n    El::Initialize(argc, argv);\n    skybase::context_t context(23234);\n\n    skybase::sparse_matrix_t<double> A;\n    El::Matrix<double> b;\n\n    boost::mpi::timer timer;\n\n    // Load A and b from HDF5 file\n    std::cout << \"Reading the matrix... \";\n    std::cout.flush();\n    timer.restart();\n    H5::H5File in(argv[1], H5F_ACC_RDONLY);\n    skyutil::io::ReadHDF5(in, \"A\", A);\n    in.close();\n    std::cout <<\"took \" << boost::format(\"%.2e\") % timer.elapsed() << \" sec\\n\";\n\n    timer.restart();\n    El::Matrix<double> u_min, u_max, v_min, v_max;\n    double cond, sigma_min, sigma_min_c, sigma_max;\n    skynla::condest_params_t condest_params;\n    condest_params.am_i_printing = true;\n    condest_params.log_level = 2;\n    condest_params.iter_lim = 10000;\n    skynla::CondEst(A, cond, sigma_max, v_max, u_max,\n        sigma_min, sigma_min_c, v_min, u_min, context, condest_params);\n    std::cout <<\"Took \" << boost::format(\"%.2e\") % timer.elapsed() << \" sec\\n\";\n    std::cout << \"Condition number = \" << cond\n              << \" sigma_max = \" << sigma_max\n              << \" sigma_min = \" << sigma_min << std::endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "c46a7f84185ec671de322fa498d9d18629320e98", "size": 1540, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/condest.cpp", "max_stars_repo_name": "xdata-skylark/libskylark", "max_stars_repo_head_hexsha": "89c3736136a24d519c14fc0738c21f37f1e10360", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 86.0, "max_stars_repo_stars_event_min_datetime": "2015-01-20T03:12:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-10T04:05:21.000Z", "max_issues_repo_path": "examples/condest.cpp", "max_issues_repo_name": "xdata-skylark/libskylark", "max_issues_repo_head_hexsha": "89c3736136a24d519c14fc0738c21f37f1e10360", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 48.0, "max_issues_repo_issues_event_min_datetime": "2015-05-12T09:31:23.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-05T14:45:46.000Z", "max_forks_repo_path": "examples/condest.cpp", "max_forks_repo_name": "xdata-skylark/libskylark", "max_forks_repo_head_hexsha": "89c3736136a24d519c14fc0738c21f37f1e10360", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2015-01-18T23:02:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-12T07:30:35.000Z", "avg_line_length": 28.5185185185, "max_line_length": 79, "alphanum_fraction": 0.6402597403, "num_tokens": 450, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388167733099, "lm_q2_score": 0.5813030906443134, "lm_q1q2_score": 0.4818646961453653}}
{"text": "#include <boost/math/distributions/inverse_gamma.hpp>\n", "meta": {"hexsha": "2817e669ac304c796a5ed4844ebffa9a34c7490e", "size": 54, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_distributions_inverse_gamma.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_distributions_inverse_gamma.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_distributions_inverse_gamma.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 27.0, "max_line_length": 53, "alphanum_fraction": 0.8333333333, "num_tokens": 11, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388167733099, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4818646961453652}}
{"text": "#define CATCH_CONFIG_MAIN\n\n#include \"catch.hpp\"\n#include \"helpers.hpp\"\n#include <Eigen/Dense>\n#include <celerite2/celerite2.h>\n\nusing namespace celerite2::test;\nusing namespace celerite2::core;\n\nTEMPLATE_LIST_TEST_CASE(\"check the results of solve_lower\", \"[solve_lower]\", TestKernels) {\n  SETUP_TEST(50);\n\n  Matrix K, S, Z, F;\n  to_dense(x, c, a, U, V, K);\n\n  // Do the Cholesky using celerite\n  int flag = factor(x, c, a, U, V, a, V, S);\n  REQUIRE(flag == 0);\n\n  // Brute force the Cholesky factorization\n  Eigen::LDLT<Eigen::MatrixXd> LDLT(K);\n  Eigen::MatrixXd expect = LDLT.matrixL().solve(Y);\n\n  SECTION(\"general\") {\n    solve_lower(x, c, U, V, Y, Z, F);\n    double resid = (Z - expect).array().abs().maxCoeff();\n    REQUIRE(resid < 1e-12);\n  }\n\n  SECTION(\"no grad\") {\n    solve_lower(x, c, U, V, Y, Z);\n    double resid = (Z - expect).array().abs().maxCoeff();\n    REQUIRE(resid < 1e-12);\n  }\n\n  SECTION(\"inplace\") {\n    Z = Y;\n    solve_lower(x, c, U, V, Z, Z, F);\n    double resid = (Z - expect).array().abs().maxCoeff();\n    REQUIRE(resid < 1e-12);\n  }\n}\n", "meta": {"hexsha": "b1423419a80eb135c86d399d665685f20475cf08", "size": 1064, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "c++/test/test_solve_lower.cpp", "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++/test/test_solve_lower.cpp", "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++/test/test_solve_lower.cpp", "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": 24.1818181818, "max_line_length": 91, "alphanum_fraction": 0.6231203008, "num_tokens": 346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.5813030906443134, "lm_q1q2_score": 0.481864691232253}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// ars::test::normal_distribution.cpp                                        //\n//                                                                           //\n//  Copyright 2009 Erwann Rogard. Distributed under the Boost                //\n//  Software License, Version 1.0. (See accompanying file                    //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)         //\n///////////////////////////////////////////////////////////////////////////////\n#ifndef BOOST_STATISTICS_DETAIL_ARS_TEST_NORMAL_DISTRIBUTION_HPP_ER_2009\n#define BOOST_STATISTICS_DETAIL_ARS_TEST_NORMAL_DISTRIBUTION_HPP_ER_2009\n#include <iostream>\n#include <string>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/statistics/detail/distribution_toolkit/distributions/normal/include.hpp>\n#include <boost/ars/test/standard_distribution.hpp>\n\nnamespace boost{\nnamespace statistics{\nnamespace detail{\nnamespace ars{\nnamespace test{\n\nstruct normal_distribution{\n\n    // Samples from normal distribution using adaptive rejection sampling and \n    // outputs convergence statistics\n\ttemplate<typename T>\n\tstatic void call(\n    \tT mu,\n    \tT sigma,\n    \tT init_0, //must be < mu\n    \tT init_1, //must be > mu\n    \tunsigned n1,    // 1e2\n    \tunsigned n2,    // 10\n    \tunsigned n3,    // 1\n    \tunsigned n4,    // 10\n    \tunsigned n_max_reject,\n    \tstd::ostream& out\n\t)\n\t{\n\n    \tusing namespace boost;\n    \ttypedef double                                          value_t;\n    \ttypedef ars::constant<value_t>                          const_;\n    \ttypedef math::normal_distribution<value_t>              mdist_t;\n    \ttypedef boost::mt19937                                  urng_t;\n\t\n    \tconst value_t inf_ = const_::inf_;\n\n    \tmdist_t mdist(mu,sigma);\n    \turng_t urng;\n\n    \tars::test::standard_distribution::call(\n        \tmdist,\n        \tinf_,\n        \tinf_,\n        \tinit_0,\n        \tinit_1,\n        \turng,\n        \tn1,    \n        \tn2,    \n        \tn3,    \n        \tn4,   \n        \tn_max_reject,\n        \tout\n    \t);\n    }\n};\n\n}//test\n}// ars\n}// detail\n}// statistics\n}// boost\n\n#endif\n", "meta": {"hexsha": "e1d93351aa31a7cf576b3ddf2d9521b1e4ba6a66", "size": 2177, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "adaptive_rejection_sampling/boost/ars/test/normal_distribution.hpp", "max_stars_repo_name": "rogard/boost_sandbox_statistics", "max_stars_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "adaptive_rejection_sampling/boost/ars/test/normal_distribution.hpp", "max_issues_repo_name": "rogard/boost_sandbox_statistics", "max_issues_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "adaptive_rejection_sampling/boost/ars/test/normal_distribution.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": 28.6447368421, "max_line_length": 88, "alphanum_fraction": 0.526871842, "num_tokens": 471, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4818646912322529}}
{"text": "#include <SFML/System.hpp>\n#include <SFML/Graphics.hpp>\n#include <SFML/Window.hpp>\n#include <SFML/Audio.hpp>\n#include <boost/math/constants/constants.hpp>\n\n#include <map>\n#include <iostream>\n#include <cassert>\n#include <cmath>\n\n#include \"GameBall.h\"\n#include \"Game.h\"\n#include \"Logger.h\"\n\n\nGameBall::GameBall() :\n    _velocity(230.0f), //pixels per second speed\n    _elapsedTimeSinceStart(0.0f)\n{\n    //constructor\n    Load(\"resources/ball.png\");\n    assert(IsLoaded());\n\n    GetSprite().setOrigin(15,15);\n\n    //Generates a random number between 1 and 360.\n    float random_integer = std::rand() % 360 + 1;\n    _angle = random_integer;\n    INFO << \"Angle: \" << _angle;\n}\n\n\nGameBall::~GameBall()\n{\n    //destructor\n}\n\n//Parameter is the time since last frame in seconds. VERY small number.\nvoid GameBall::Update(float elapsedTime)\n{\n    //INFO << \"Time since last frame: \" << elapsedTime;\n    _elapsedTimeSinceStart += elapsedTime;\n\n    // Delay game from starting until 3 seconds have passed\n    if (_elapsedTimeSinceStart < 3.0f)\n        return;\n\n    float moveAmount = _velocity  * elapsedTime;\n\n    float moveByX = LinearVelocityX(_angle) * moveAmount;\n    float moveByY = LinearVelocityY(_angle) * moveAmount;\n\n    //INFO << GetPosition().x << GetPosition().y;\n\n\n    //collide with the left side of the screen\n    if (GetPosition().x + moveByX <= 0 + GetWidth()/2 || GetPosition().x + GetHeight()/2 + moveByX >= Game::width)\n    {\n        //Ricochet!\n        _angle = 360.0f - _angle;\n        if (_angle > 260.0f && _angle < 280.0f)\n            _angle += 20.0f;\n        if (_angle > 80.0f && _angle < 100.0f)\n            _angle += 20.0f;\n\n        moveByX = -moveByX;\n    }\n\n    PlayerPaddle* player1 = dynamic_cast<PlayerPaddle*>(Game::GetGameObjectManager().Get(\"Paddle1\"));\n    if (player1 != NULL)\n    {\n        sf::Rect<float> p1BB = player1->GetBoundingRect();\n\n        if (p1BB.intersects(GetBoundingRect()))\n        {\n            _angle =  360.0f - (_angle - 180.0f);\n            if (_angle > 360.0f)\n                _angle -= 360.0f;\n\n            moveByY = -moveByY;\n\n            // Make sure ball isn't inside paddle\n            if (GetBoundingRect().width > player1->GetBoundingRect().top)\n            {\n                SetPosition(GetPosition().x,player1->GetBoundingRect().top - GetWidth()/2 -1 );\n            }\n\n            // Now add \"English\" based on the players velocity.\n            float playerVelocity = player1->GetVelocity();\n\n            if (playerVelocity < 0)\n            {\n                // moving left\n                _angle -= 20.0f;\n                if(_angle < 0 )\n                    _angle = 360.0f - _angle;\n            }\n            else if(playerVelocity > 0)\n            {\n                _angle += 20.0f;\n                if(_angle > 360.0f)\n                    _angle = _angle - 360.0f;\n            }\n\n            _velocity += 5.0f;\n        }\n\n        if (GetPosition().y - GetHeight()/2 <= 0)\n        {\n            _angle =  180 - _angle;\n            moveByY = -moveByY;\n        }\n\n        if(GetPosition().y + GetHeight()/2 + moveByY >= Game::height)\n        {\n            INFO << \"Moving to middle screen...\";\n            Reset();\n        }\n\n        GetSprite().move(moveByX,moveByY);\n    } else {\n        ERROR << \"Something bad happened with the casting...\";\n    }\n}\n\nvoid GameBall::Reset()\n{\n    _elapsedTimeSinceStart = 0.0f;\n    GetSprite().setPosition(Game::width/2, Game::height/2);\n    _angle = (std::rand()%360)+1;\n    _velocity = 230.0f;\n}\n\nfloat GameBall::LinearVelocityX(float angle)\n{\n    angle -= 90;\n    if (angle < 0)\n        angle = 360 + angle;\n    const double pi = boost::math::constants::pi<float>();\n    return (float)std::cos( angle * ( pi / 180.0f ));\n}\n\nfloat GameBall::LinearVelocityY(float angle)\n{\n    angle -= 90;\n    if (angle < 0)\n        angle = 360 + angle;\n    const double pi = boost::math::constants::pi<float>();\n    return (float)std::sin( angle * ( pi / 180.0f ));\n}\n", "meta": {"hexsha": "871a2f64f1dddf6fd0f70722dbf643b03d06166c", "size": 3951, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/GameBall.cpp", "max_stars_repo_name": "firefly2442/pang", "max_stars_repo_head_hexsha": "30ef5edd5766e408fe63927c39bbf331379f8c52", "max_stars_repo_licenses": ["Unlicense", "MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/GameBall.cpp", "max_issues_repo_name": "firefly2442/pang", "max_issues_repo_head_hexsha": "30ef5edd5766e408fe63927c39bbf331379f8c52", "max_issues_repo_licenses": ["Unlicense", "MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/GameBall.cpp", "max_forks_repo_name": "firefly2442/pang", "max_forks_repo_head_hexsha": "30ef5edd5766e408fe63927c39bbf331379f8c52", "max_forks_repo_licenses": ["Unlicense", "MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9934210526, "max_line_length": 114, "alphanum_fraction": 0.5583396608, "num_tokens": 1077, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.48186468631914037}}
{"text": "/*\r\n [auto_generated]\r\n libs/numeric/odeint/test/generic_stepper.cpp\r\n\r\n [begin_description]\r\n This file tests the generic stepper.\r\n [end_description]\r\n\r\n Copyright 2011 Mario Mulansky\r\n Copyright 2012 Karsten Ahnert\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// disable checked iterator warning for msvc\r\n#include <boost/config.hpp>\r\n#ifdef BOOST_MSVC\r\n    #pragma warning(disable:4996)\r\n#endif\r\n\r\n#define BOOST_TEST_MODULE odeint_generic_stepper\r\n\r\n#include <iostream>\r\n#include <utility>\r\n\r\n#include <boost/test/unit_test.hpp>\r\n\r\n#include <boost/numeric/odeint/stepper/explicit_generic_rk.hpp>\r\n#include <boost/numeric/odeint/stepper/runge_kutta4.hpp>\r\n#include <boost/numeric/odeint/stepper/runge_kutta4_classic.hpp>\r\n\r\n#include <boost/array.hpp>\r\n\r\nusing namespace boost::unit_test;\r\nusing namespace boost::numeric::odeint;\r\n\r\nnamespace fusion = boost::fusion;\r\n\r\ntypedef double value_type;\r\ntypedef boost::array< value_type , 2 > state_type;\r\n\r\nvoid sys( const state_type &x , state_type &dxdt , const value_type &t )\r\n{\r\n    dxdt[ 0 ] = x[ 0 ] + 2 * x[ 1 ];\r\n    dxdt[ 1 ] = x[ 1 ];\r\n}\r\n\r\ntypedef explicit_generic_rk< 4 , 4 , state_type> rk_generic_type;\r\ntypedef runge_kutta4< state_type > rk4_generic_type;\r\n\r\nconst boost::array< double , 1 > a1 = {{ 0.5 }};\r\nconst boost::array< double , 2 > a2 = {{ 0.0 , 0.5 }};\r\nconst boost::array< double , 3 > a3 = {{ 0.0 , 0.0 , 1.0 }};\r\n\r\nconst rk_generic_type::coef_a_type a = fusion::make_vector( a1 , a2 , a3 );\r\nconst rk_generic_type::coef_b_type b = {{ 1.0/6 , 1.0/3 , 1.0/3 , 1.0/6 }};\r\nconst rk_generic_type::coef_c_type c = {{ 0.0 , 0.5 , 0.5 , 1.0 }};\r\n\r\ntypedef runge_kutta4_classic< state_type > rk4_type;\r\n\r\nBOOST_AUTO_TEST_SUITE( generic_stepper_test )\r\n\r\nBOOST_AUTO_TEST_CASE( test_generic_stepper )\r\n{\r\n    //simultaneously test copying\r\n    rk_generic_type rk_generic_( a , b , c );\r\n    rk_generic_type rk_generic = rk_generic_;\r\n\r\n    rk4_generic_type rk4_generic_;\r\n    rk4_generic_type rk4_generic = rk4_generic_;\r\n\r\n    //std::cout << stepper;\r\n\r\n    rk4_type rk4_;\r\n    rk4_type rk4 = rk4_;\r\n\r\n    typedef rk_generic_type::state_type state_type;\r\n    typedef rk_generic_type::value_type stepper_value_type;\r\n    typedef rk_generic_type::deriv_type deriv_type;\r\n    typedef rk_generic_type::time_type time_type;\r\n\r\n    state_type x = {{ 0.0 , 1.0 }};\r\n    state_type y = x;\r\n    state_type z = x;\r\n\r\n    rk_generic.do_step( sys , x , 0.0 , 0.1 );\r\n\r\n    rk4_generic.do_step( sys , y , 0.0 , 0.1 );\r\n\r\n    rk4.do_step( sys , z , 0.0 , 0.1 );\r\n\r\n    BOOST_CHECK_NE( 0.0 , x[0] );\r\n    BOOST_CHECK_NE( 1.0 , x[1] );\r\n    // compare with analytic solution of above system\r\n    BOOST_CHECK_EQUAL( x[0] , y[0] );\r\n    BOOST_CHECK_EQUAL( x[1] , y[1] );\r\n    BOOST_CHECK_EQUAL( x[0] , z[0] );\r\n    BOOST_CHECK_EQUAL( x[1] , z[1] );\r\n\r\n}\r\n\r\nBOOST_AUTO_TEST_SUITE_END()\r\n", "meta": {"hexsha": "b61bbe834966b414e7b1d15579255ceb3b22e53c", "size": 2953, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/numeric/odeint/test/generic_stepper.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": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/numeric/odeint/test/generic_stepper.cpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-04T18:00:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-04T18:00:00.000Z", "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/numeric/odeint/test/generic_stepper.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 28.1238095238, "max_line_length": 76, "alphanum_fraction": 0.6749068744, "num_tokens": 879, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228891883799, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.4818636084916018}}
{"text": "#include \"stdafx.h\"\r\n#include \"qmath.h\"\r\n#include \"config.h\"\r\n\r\n// each test module could contain no more then one 'main' file with init function defined\r\n// alternatively you could define init function yourself\r\n#include <boost/test/unit_test.hpp>\r\n\r\n// These are sample tests that show the different features of the framework\r\n\r\nusing namespace math;\r\n\r\ntemplate<typename T>\r\nvoid testTrans2d()\r\n{\r\n\ttrans2d<T> m0(\r\n\t\tvec2<T>(0.6f, 0.2f), \r\n\t\t0.7f, \r\n\t\tvec2<T>(0.3f, 0.5f));\r\n\r\n\t{\r\n\t\tBOOST_CHECK(is_identity(trans2d<T>::identity, epsilon<T>()));\r\n\t\ttrans2d<T> inv0 = inverse(trans2d<T>::identity);\r\n\t\tBOOST_CHECK(is_identity(inv0, epsilon<T>()));\r\n\t}\r\n\r\n\t{\r\n\t\ttrans2d<T> inv0 = inverse(m0);\r\n\t\ttrans2d<T> res0 = m0 * inv0;\r\n\t\tBOOST_CHECK(is_identity(res0, 0.0001f));\r\n\t}\r\n\t{\r\n\t\ttrans2d<T> m0;\r\n\t\tBOOST_CHECK(is_identity(m0));\r\n\t}\r\n\t{\r\n\t\tmat4<T> m0(mat4<T>::one);\r\n\t\t//this should leave m0 unchanged\r\n\t\tauto* t = new (&m0) trans2d<T>(trans2d<T>::uninitialized);\r\n\r\n\t\tBOOST_CHECK(m0 == mat4<T>::one);\r\n\t}\r\n\t{\r\n\t\tT rot = T(2.7);\r\n\t\tmat2<T> rotm(mat2<T>::rotation, rot);\r\n\t\ttrans2d<T> t0(vec2<T>(23, 24), rotm, vec2<T>(1, 1));\r\n\t\ttrans2d<T> t1(vec2<T>(23, 24), rot, vec2<T>(1, 1));\r\n\r\n\t\tBOOST_CHECK(t0 == t1);\r\n\t\tBOOST_CHECK(t0 != m0);\r\n\t\tBOOST_CHECK(t1 != m0);\r\n\r\n\t\tBOOST_CHECK(t0.get_translation() == vec2<T>(23, 24));\r\n\t\tBOOST_CHECK(equals(t0.get_scale(), vec2<T>(1, 1), T(0.001)));\r\n\t\tt0.post_scale(T(1) / t0.get_scale());\r\n\t\tBOOST_CHECK(equals(t0.get_rotation(), rotm, T(0.001)));\r\n\t}\r\n\r\n\t{\r\n\t\tT rot = T(2.7);\r\n\t\tmat2<T> rotm(mat2<T>::rotation, rot);\r\n\t\ttrans2d<T> t0(vec2<T>(23, 24), rotm, vec2<T>(1, 1));\r\n\t\ttrans2d<T> t1(vec2<T>(23, 24), rot, vec2<T>(1, 1));\r\n\r\n\t\tauto res0 = t0 * t1;\r\n\t\ttrans2d<T> res1;\r\n\t\tres1.mat = t0.mat * t1.mat;\r\n\t\tres1.repair();\r\n\r\n\t\tBOOST_CHECK(res0 == res1);\r\n\t\tt0 *= t1;\r\n\t\tBOOST_CHECK(t0 == res1);\r\n\t}\r\n\t{\r\n\t\tT rot = T(2.7);\r\n\t\tmat2<T> rotm(mat2<T>::rotation, rot);\r\n\t\ttrans2d<T> t0(vec2<T>(23, 24), rotm, vec2<T>(1, 1));\r\n\t\tt0.set_identity();\r\n\t\tBOOST_CHECK(t0 == trans2d<T>::identity);\r\n\t}\r\n\t{\r\n\t\tT rot = T(2.7);\r\n\t\tmat2<T> rotm(mat2<T>::rotation, rot);\r\n\t\ttrans2d<T> t0(vec2<T>(23, 24), rotm, vec2<T>(1, 1));\r\n\t\tt0.set_rotation_identity();\r\n\t\tBOOST_CHECK(t0.get_rotation() == mat2<T>::identity);\r\n\t\tBOOST_CHECK(t0.get_translation() == vec2<T>(23, 24));\r\n\t}\r\n\t{\r\n\t\tmat2<T> m0(0.72f);\r\n\t\ttrans2d<T> m1(vec2<T>(1, 2), m0, vec2<T>(1, 1));\r\n\t\tBOOST_CHECK(m1.get_axis_x() == vec2<T>(0.72f, 0.72f));\r\n\t\tBOOST_CHECK(m1.get_axis_y() == vec2<T>(0.72f, 0.72f));\r\n\t\tBOOST_CHECK(m1.get_translation() == vec2<T>(1, 2));\r\n\t}\r\n\r\n\tint a = 0;\r\n}\r\n\r\n\r\nBOOST_AUTO_TEST_CASE(Trans2d)\r\n{\r\n\ttestTrans2d<float>();\r\n//\ttestTrans2d<double>();\r\n}\r\n", "meta": {"hexsha": "1d5e9224bcbd2b0471986a0e81c90e274fce07da", "size": 2659, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "qmath/test/test_trans2d.cpp", "max_stars_repo_name": "jeanleflambeur/silkopter", "max_stars_repo_head_hexsha": "cdbc67ee2c85f5c95eb4f52e2e0ba24514962dd8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 36.0, "max_stars_repo_stars_event_min_datetime": "2015-03-09T16:47:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-04T08:32:04.000Z", "max_issues_repo_path": "qmath/test/test_trans2d.cpp", "max_issues_repo_name": "jeanlemotan/silkopter", "max_issues_repo_head_hexsha": "cdbc67ee2c85f5c95eb4f52e2e0ba24514962dd8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 42.0, "max_issues_repo_issues_event_min_datetime": "2017-02-11T11:15:51.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-28T16:00:44.000Z", "max_forks_repo_path": "qmath/test/test_trans2d.cpp", "max_forks_repo_name": "jeanleflambeur/silkopter", "max_forks_repo_head_hexsha": "cdbc67ee2c85f5c95eb4f52e2e0ba24514962dd8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2015-10-15T05:46:48.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-11T17:40:36.000Z", "avg_line_length": 25.0849056604, "max_line_length": 90, "alphanum_fraction": 0.5968409176, "num_tokens": 969, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.4818636026880351}}
{"text": "//\n//  Copyright (c) 2011-2013 Vladimir Chalupecky\n//\n//  Permission is hereby granted, free of charge, to any person obtaining a copy\n//  of this software and associated documentation files (the \"Software\"), to\n//  deal in the Software without restriction, including without limitation the\n//  rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n//  sell copies of the Software, and to permit persons to whom the Software is\n//  furnished to do so, subject to the following conditions:\n//\n//  The above copyright notice and this permission notice shall be included in\n//  all copies or substantial portions of the Software.\n//\n//  THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n//  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n//  IN THE SOFTWARE.\n\n#include <umeshu/Delaunay_mesher.h>\n#include <umeshu/Delaunay_triangulation.h>\n#include <umeshu/Delaunay_triangulation_items.h>\n#include <umeshu/Exceptions.h>\n#include <umeshu/Polygon.h>\n#include <umeshu/Relaxer.h>\n#include <umeshu/Triangulator.h>\n#include <umeshu/io/OBJ.h>\n#include <umeshu/io/OFF.h>\n#include <umeshu/io/PLY.h>\n#include <umeshu/io/EPS.h>\n#include <umeshu/io/STL.h>\n\n#include <boost/program_options.hpp>\n\nusing namespace umeshu;\nnamespace po = boost::program_options;\n\ntypedef Delaunay_triangulation< Delaunay_triangulation_items_with_id > Mesh;\ntypedef Mesh::Node_handle     Node_handle;\ntypedef Mesh::Halfedge_handle Halfedge_handle;\ntypedef Mesh::Edge_handle     Edge_handle;\ntypedef Mesh::Face_handle     Face_handle;\ntypedef Delaunay_mesher< Mesh > Mesher;\ntypedef Relaxer< Mesh >       Relax;\n\nint main( int argc, const char* argv[] )\n{\n  double max_area;\n  double min_angle;\n\n  po::options_description po_desc( \"Allowed options\" );\n  po_desc.add_options()\n    ( \"help\", \"produce help message\" )\n    ( \"max-size,s\", po::value<double>( &max_area )->default_value( 0.01 ), \"set the maximum triangle area for the refinement algorithm\" )\n    ( \"min-angle,a\", po::value<double>( &min_angle )->default_value( 21 ), \"set the minimum angle for the refinement algorithm\" )\n    ( \"input-file\", po::value<std::string>(), \"input file describing the polygonal boundary (in Well-Known Text format)\");\n\n  po::positional_options_description po_pdesc;\n  po_pdesc.add(\"input-file\", -1);\n\n  po::variables_map po_vm;\n  po::store( po::command_line_parser( argc, argv ).options( po_desc ).positional( po_pdesc ).run(), po_vm );\n  po::notify( po_vm );\n\n  if ( po_vm.count( \"help\" ) )\n  {\n    std::cout << po_desc << std::endl;\n    return EXIT_SUCCESS;\n  }\n\n  if ( ! po_vm.count( \"input-file\" ) )\n  {\n    std::cout << \"Name of the input file not specified\\n\";\n    std::cout << po_desc << std::endl;\n    return EXIT_FAILURE;\n  }\n\n  std::cout << \"Parameters used:\" << std::endl\n    << \"  maximum triangle area = \" << max_area << std::endl\n    << \"  minimum angle = \" << min_angle << std::endl;\n\n  try\n  {\n    Polygon boundary;\n    read_polygon( po_vm[\"input-file\"].as< std::string >(), boundary );\n\n    Mesh mesh;\n\n    Triangulator<Mesh> triangulator;\n    triangulator.triangulate( boundary, mesh );\n    io::write_eps( \"mesh_1.eps\", mesh );\n\n    mesh.make_cdt();\n    io::write_eps( \"mesh_2.eps\", mesh );\n\n    Mesher mesher;\n    mesher.refine( mesh, max_area, min_angle );\n    io::write_eps( \"mesh_3.eps\", mesh );\n    io::write_stl( \"mesh_3.stl\", mesh );\n    io::write_off( \"mesh_3.off\", mesh );\n    io::write_obj( \"mesh_3.obj\", mesh );\n    io::write_ply( \"mesh_3.ply\", mesh );\n\n    Relax relax;\n    relax.relax( mesh );\n    io::write_eps( \"mesh_4.eps\", mesh );\n\n    // smoother smooth;\n    // smooth.smooth(m, 1);\n    // Postscript_stream ps5(\"mesh_5.eps\", m.bounding_box());\n    // ps5 << m;\n\n    // // code does not pass a debug assert:\n    // meshgen.refine(0.0001000, 25);\n    // Postscript_stream ps6(\"mesh_6.eps\", m.bounding_box());\n    // ps6 << m;\n\n    // // smooth.smooth(m, 5);\n    // // Postscript_stream ps7(\"mesh_7.eps\", m.bounding_box());\n    // // ps7 << m;\n\n    std::cout << \"Final mesh:\" << std::endl\n      << \"  # nodes: \" << mesh.number_of_nodes() << std::endl\n      << \"  # edges: \" << mesh.number_of_edges() << std::endl\n      << \"  # faces: \" << mesh.number_of_faces() << std::endl;\n  }\n  catch ( boost::exception& e )\n  {\n    std::cerr << boost::diagnostic_information( e );\n  }\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "d9d0598472239bf91df5677337eb9db05900b608", "size": 4667, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tools/umeshu-meshgen.cpp", "max_stars_repo_name": "vladimir-ch/umeshu", "max_stars_repo_head_hexsha": "a2df4e1f0934d0ea868fb9f8a4cba13210ef8c07", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2015-01-01T13:56:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T07:09:58.000Z", "max_issues_repo_path": "tools/umeshu-meshgen.cpp", "max_issues_repo_name": "vladimir-ch/umeshu", "max_issues_repo_head_hexsha": "a2df4e1f0934d0ea868fb9f8a4cba13210ef8c07", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-02-10T14:08:48.000Z", "max_issues_repo_issues_event_max_datetime": "2016-02-10T14:08:48.000Z", "max_forks_repo_path": "tools/umeshu-meshgen.cpp", "max_forks_repo_name": "vladimir-ch/umeshu", "max_forks_repo_head_hexsha": "a2df4e1f0934d0ea868fb9f8a4cba13210ef8c07", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2016-03-08T03:15:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T07:11:06.000Z", "avg_line_length": 34.3161764706, "max_line_length": 137, "alphanum_fraction": 0.6743089779, "num_tokens": 1284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.4818636026880351}}
{"text": "#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <boost/property_tree/ptree.hpp>\n#include <boost/property_tree/xml_parser.hpp>\n#include <vector>\n#include <fstream>\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel  K;\ntypedef K::Point_3                                Point_3;\n\nint main(int argc, char* argv[]){\n  std::ifstream in( (argc>1)? argv[1] : \"data/cloud.pol\");\n  boost::property_tree::ptree tree;\n  boost::property_tree::read_xml(in, tree);\n\n  std::vector<Point_3> points;\n\n  for(boost::property_tree::ptree::value_type& node : tree.get_child(\"PolySet.Polygon\")){\n    boost::property_tree::ptree subtree = node.second;         \n    if( node.first == \"Point\" ){\n      for( boost::property_tree::ptree::value_type const& v : subtree.get_child( \"\" ) ) {\n        std::string label = v.first;\n        \n        if ( label == \"<xmlattr>\" ) {\n          Point_3 p(subtree.get<double>( label+\".X\"),\n                    subtree.get<double>( label+\".Y\"),\n                    subtree.get<double>( label+\".Z\"));\n          points.push_back(p);\n        }\n      }\n    }\n  }    \n\n  std::cout << points.size() << \" points read\"<< std::endl;\n  return 0;\n}\n", "meta": {"hexsha": "fdbbf4b0ec3aa335ea8fc7875cbc633c75dc4443", "size": 1181, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CoreSystem/lib/CGAL/examples/Stream_support/read_xml.cpp", "max_stars_repo_name": "josuehfa/DAASystem", "max_stars_repo_head_hexsha": "a1fe61ffc19f0781eeeddcd589137eefde078a45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-17T01:13:02.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-17T01:13:02.000Z", "max_issues_repo_path": "CoreSystem/lib/CGAL/examples/Stream_support/read_xml.cpp", "max_issues_repo_name": "josuehfa/DAASystem", "max_issues_repo_head_hexsha": "a1fe61ffc19f0781eeeddcd589137eefde078a45", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CoreSystem/lib/CGAL/examples/Stream_support/read_xml.cpp", "max_forks_repo_name": "josuehfa/DAASystem", "max_forks_repo_head_hexsha": "a1fe61ffc19f0781eeeddcd589137eefde078a45", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-02T11:11:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-02T11:11:36.000Z", "avg_line_length": 32.8055555556, "max_line_length": 89, "alphanum_fraction": 0.6079593565, "num_tokens": 296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754371026367, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.48186359487513386}}
{"text": "#include <Eigen/Core>\n\n#include <numpy_eigen/boost_python_headers.hpp>\nEigen::Matrix<float, 6, 6> test_float_6_6(const Eigen::Matrix<float, 6, 6> & M)\n{\n\treturn M;\n}\nvoid export_float_6_6()\n{\n\tboost::python::def(\"test_float_6_6\",test_float_6_6);\n}\n\n", "meta": {"hexsha": "13cb17fd348533e1e9bd3868619d83faf6e8db24", "size": 249, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Schweizer-Messer/numpy_eigen/src/autogen_test_module/test_6_6_float.cpp", "max_stars_repo_name": "PushyamiKaveti/kalibr", "max_stars_repo_head_hexsha": "d8bdfc59ee666ef854012becc93571f96fe5d80c", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": 2690.0, "max_stars_repo_stars_event_min_datetime": "2015-01-07T03:50:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T20:27:01.000Z", "max_issues_repo_path": "Schweizer-Messer/numpy_eigen/src/autogen_test_module/test_6_6_float.cpp", "max_issues_repo_name": "PushyamiKaveti/kalibr", "max_issues_repo_head_hexsha": "d8bdfc59ee666ef854012becc93571f96fe5d80c", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": 481.0, "max_issues_repo_issues_event_min_datetime": "2015-01-27T10:21:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T14:02:41.000Z", "max_forks_repo_path": "Schweizer-Messer/numpy_eigen/src/autogen_test_module/test_6_6_float.cpp", "max_forks_repo_name": "PushyamiKaveti/kalibr", "max_forks_repo_head_hexsha": "d8bdfc59ee666ef854012becc93571f96fe5d80c", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": 1091.0, "max_forks_repo_forks_event_min_datetime": "2015-01-26T21:21:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T01:55:33.000Z", "avg_line_length": 19.1538461538, "max_line_length": 79, "alphanum_fraction": 0.7309236948, "num_tokens": 83, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754371026367, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.48186359487513386}}
{"text": "#include \"catch.h\"\r\n#include \"../data_structures/Vector.h\"\r\n#include \"../math/Random.h\"\r\n#include \"../math/VectorMath.h\"\r\n\r\n// optional test used for benchmarking, set to 0 to disable, 1 to enable\r\n#if 0\r\n\r\n// boost time helpers\r\n#include <boost/date_time/posix_time/posix_time.hpp>\r\nnamespace bpt = boost::posix_time;\r\n#define bpt_now() bpt::microsec_clock::local_time()\r\n\r\nTEST_CASE(\"Benchmark Dot Product\")\r\n{\r\n    GapsRandomState randState(123);\r\n    GapsRng rng(&randState);\r\n\r\n    std::vector<Vector> mVecs;\r\n    for (unsigned i = 0; i < 1300; ++i)\r\n    {\r\n        mVecs.push_back(Vector(50000));\r\n        for (unsigned j = 0; j < mVecs[i].size(); ++j)\r\n        {\r\n            mVecs[i][j] = rng.uniform(0.f, 100.f);\r\n        }\r\n    }\r\n\r\n    float sum = 0.f;\r\n    bpt::ptime start = bpt_now();\r\n    for (unsigned i = 0; i < mVecs.size(); ++i)\r\n    {\r\n        for (unsigned j = i; j < mVecs.size(); ++j)\r\n        {\r\n            sum += gaps::dot(mVecs[i], mVecs[j]);\r\n        }\r\n    }\r\n    bpt::time_duration diff = bpt_now() - start;\r\n    gaps_printf(\"-------\\n-------\\n-------\\n-------\\n\", sum);\r\n    gaps_printf(\"sum: %f\\n\", sum);\r\n    gaps_printf(\"dot product milliseconds: %lu\\n\", diff.total_milliseconds());\r\n    gaps_printf(\"-------\\n-------\\n-------\\n-------\\n\", sum);\r\n}\r\n#endif\r\n\r\nTEST_CASE(\"Test Vector.h\")\r\n{\r\n    GapsRandomState randState(123);\r\n\r\n    SECTION(\"Test size constructor\")\r\n    {\r\n        Vector v(100);\r\n        REQUIRE(v.size() == 100);\r\n        REQUIRE(gaps::isVectorZero(v));\r\n        REQUIRE(gaps::sum(v) == 0.f);\r\n    }\r\n\r\n    SECTION(\"Test std::vector constructor\")\r\n    {   \r\n        GapsRng rng(&randState);\r\n        std::vector<float> in_v;\r\n        for (unsigned n = 0; n < 1000; ++n)\r\n        {\r\n            in_v.push_back(rng.uniform());\r\n        }\r\n        Vector v(in_v);\r\n\r\n        REQUIRE(v.size() == 1000);\r\n        REQUIRE(!gaps::isVectorZero(v));\r\n        REQUIRE(gaps::max(v) <= 1.f);\r\n        REQUIRE(gaps::min(v) >= 0.f);\r\n    }\r\n\r\n    SECTION(\"TEST += operator\")\r\n    {\r\n        GapsRng rng(&randState);\r\n        std::vector<float> in_v;\r\n        for (unsigned n = 0; n < 1000; ++n)\r\n        {\r\n            in_v.push_back(rng.uniform());\r\n        }\r\n        Vector v(in_v);\r\n\r\n        float s = gaps::sum(v);\r\n        v += v;\r\n        REQUIRE(gaps::sum(v) == 2.f * s);\r\n    }\r\n}", "meta": {"hexsha": "3bc8780b122e1f92668fd863f6371774a1cb77d4", "size": 2330, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cpp_tests/testVector.cpp", "max_stars_repo_name": "FertigLab/CoGAPS", "max_stars_repo_head_hexsha": "206bac9630b0cf234b4367d041597af98ca92a13", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 40.0, "max_stars_repo_stars_event_min_datetime": "2017-01-24T14:48:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T22:11:43.000Z", "max_issues_repo_path": "src/cpp_tests/testVector.cpp", "max_issues_repo_name": "FertigLab/CoGAPS", "max_issues_repo_head_hexsha": "206bac9630b0cf234b4367d041597af98ca92a13", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 43.0, "max_issues_repo_issues_event_min_datetime": "2017-11-29T18:09:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T01:35:29.000Z", "max_forks_repo_path": "src/cpp_tests/testVector.cpp", "max_forks_repo_name": "FertigLab/CoGAPS", "max_forks_repo_head_hexsha": "206bac9630b0cf234b4367d041597af98ca92a13", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2018-10-19T12:19:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-18T15:50:39.000Z", "avg_line_length": 26.4772727273, "max_line_length": 79, "alphanum_fraction": 0.5064377682, "num_tokens": 654, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.6619228625116081, "lm_q1q2_score": 0.4818635929780175}}
{"text": "/* ----------------------------------------------------------------------------\n * Copyright 2020, Jesus Tordesillas Torres, Aerospace Controls Laboratory\n * Massachusetts Institute of Technology\n * All Rights Reserved\n * Authors: Jesus Tordesillas, et al.\n * See LICENSE file for the license information\n * -------------------------------------------------------------------------- */\n\n#pragma once\n#ifndef SOLVER_GUROBI_UTILS_HPP\n#define SOLVER_GUROBI_UTILS_HPP\n\n#include \"gurobi_c++.h\"\n#include <sstream>\n#include <Eigen/Dense>\n#include <type_traits>\n// using namespace std;\n\n// custom typedefs\ntypedef std::vector<GRBLinExpr> GRBVector;\ntypedef std::vector<std::vector<GRBLinExpr>> GRBMatrix;\n\ninline double minPositiveElement(std::vector<double> v)\n{\n  std::sort(v.begin(), v.end());  // sorted in ascending order\n  double min_value = 0;\n  for (int i = 0; i < v.size(); i++)\n  {\n    if (v[i] > 0)\n    {\n      min_value = v[i];\n      break;\n    }\n  }\n  return min_value;\n}\n\ntemplate <typename T>\nGRBQuadExpr getNorm2(const std::vector<T>& x)  // Return the squared norm of a vector\n{\n  GRBQuadExpr result = 0;\n  for (int i = 0; i < x.size(); i++)\n  {\n    result = result + x[i] * x[i];\n  }\n  return result;\n}\n\ninline void addVectorEqConstraint(GRBModel& m, const GRBVector a, const Eigen::Vector3d& b)\n{\n  for (int i = 0; i < a.size(); i++)\n  {\n    m.addConstr(a[i] == b[i]);\n  }\n}\n\ninline void addVectorLessEqualConstraint(GRBModel& m, const GRBVector a, const Eigen::Vector3d& b)\n{\n  for (int i = 0; i < a.size(); i++)\n  {\n    m.addConstr(a[i] <= b[i]);\n  }\n}\n\ninline void addVectorGreaterEqualConstraint(GRBModel& m, const GRBVector a, const Eigen::Vector3d& b)\n{\n  for (int i = 0; i < a.size(); i++)\n  {\n    m.addConstr(a[i] >= b[i]);\n  }\n}\n\ninline void resetCompleteModel(GRBModel& m)\n{\n  GRBConstr* c = 0;\n  c = m.getConstrs();\n  for (int i = 0; i < m.get(GRB_IntAttr_NumConstrs); ++i)\n  {\n    m.remove(c[i]);\n  }\n\n  GRBQConstr* cq = 0;\n  cq = m.getQConstrs();\n  for (int i = 0; i < m.get(GRB_IntAttr_NumQConstrs); ++i)\n  {\n    m.remove(cq[i]);\n  }\n\n  GRBGenConstr* gc = 0;\n  gc = m.getGenConstrs();\n  for (int i = 0; i < m.get(GRB_IntAttr_NumGenConstrs); ++i)\n  {\n    m.remove(gc[i]);\n  }\n\n  GRBVar* vars = 0;\n  vars = m.getVars();\n  for (int i = 0; i < m.get(GRB_IntAttr_NumVars); ++i)\n  {\n    m.remove(vars[i]);\n  }\n\n  m.reset();  // Note that this function, only by itself, does NOT remove vars or constraints\n}\n\n// See https://www.gurobi.com/documentation/9.0/refman/optimization_status_codes.html#sec:StatusCodes\ninline void printGurobiStatus(int status)\n{\n  switch (status)\n  {\n    case GRB_LOADED:\n      std::cout << \"GUROBI Status: GRB_LOADED\" << std::endl;\n      break;\n    case GRB_OPTIMAL:\n      std::cout << \"GUROBI Status: GRB_OPTIMAL\" << std::endl;\n      break;\n    case GRB_INFEASIBLE:\n      std::cout << \"GUROBI Status: GRB_INFEASIBLE\" << std::endl;\n      break;\n    case GRB_INF_OR_UNBD:\n      std::cout << \"GUROBI Status: GRB_INF_OR_UNBD\" << std::endl;\n      break;\n    case GRB_UNBOUNDED:\n      std::cout << \"GUROBI Status: GRB_UNBOUNDED\" << std::endl;\n      break;\n    case GRB_CUTOFF:\n      std::cout << \"GUROBI Status: GRB_CUTOFF\" << std::endl;\n      break;\n    case GRB_ITERATION_LIMIT:\n      std::cout << \"GUROBI Status: GRB_ITERATION_LIMIT\" << std::endl;\n      break;\n    case GRB_NODE_LIMIT:\n      std::cout << \"GUROBI Status: GRB_NODE_LIMIT\" << std::endl;\n      break;\n    case GRB_TIME_LIMIT:\n      std::cout << \"GUROBI Status: GRB_TIME_LIMIT\" << std::endl;\n      break;\n    case GRB_SOLUTION_LIMIT:\n      std::cout << \"GUROBI Status: GRB_SOLUTION_LIMIT\" << std::endl;\n      break;\n    case GRB_INTERRUPTED:\n      std::cout << \"GUROBI Status: GRB_INTERRUPTED\" << std::endl;\n      break;\n    case GRB_NUMERIC:\n      std::cout << \"GUROBI Status: GRB_NUMERIC\" << std::endl;\n      break;\n    case GRB_SUBOPTIMAL:\n      std::cout << \"GUROBI Status: GRB_SUBOPTIMAL\" << std::endl;\n      break;\n    case GRB_INPROGRESS:\n      std::cout << \"GUROBI Status: GRB_INPROGRESS\" << std::endl;\n      break;\n    case GRB_USER_OBJ_LIMIT:\n      std::cout << \"GUROBI Status: GRB_USER_OBJ_LIMIT\" << std::endl;\n      break;\n    default:\n      std::cout << \"GUROBI Status Code=: \" << status << std::endl;\n  }\n}\n\ntemplate <typename T, typename R>\nGRBVector matrixMultiply(const std::vector<std::vector<R>>& A, const std::vector<T>& x)\n{\n  GRBVector result;\n\n  for (int i = 0; i < A.size(); i++)\n  {\n    GRBLinExpr lin_exp = 0;\n    for (int m = 0; m < x.size(); m++)\n    {\n      lin_exp = lin_exp + A[i][m] * x[m];\n    }\n    result.push_back(lin_exp);\n  }\n  return result;\n}\n\ntemplate <typename T>\nstd::vector<GRBVector> matrixMultiply(const std::vector<std::vector<T>>& A, const std::vector<std::vector<double>>& B)\n{\n  std::vector<GRBVector> result(A.size(), GRBVector(B[0].size(), 0.0));  // Initialize all the\n                                                                         // elements to zero\n\n  for (int i = 0; i < A.size(); i++)  // multiply row if of A\n  {\n    for (int j = 0; j < B[0].size(); j++)  // times column j of B\n    {\n      GRBLinExpr lin_exp = 0;\n      for (int m = 0; m < B.size(); m++)\n      {\n        lin_exp += A[i][m] * B[m][j];\n      }\n      result[i][j] = lin_exp;\n    }\n  }\n  return result;\n}\n\ntemplate <typename T>  // Overload + to sum Elementwise std::vectors\nstd::vector<T> operator+(const std::vector<T>& a, const std::vector<T>& b)\n{\n  assert(a.size() == b.size());\n\n  std::vector<T> result;\n  result.reserve(a.size());\n\n  std::transform(a.begin(), a.end(), b.begin(), std::back_inserter(result), std::plus<T>());\n  return result;\n}\n\ntemplate <typename T>  // Overload - to substract Elementwise std::vectors\nstd::vector<T> operator-(const std::vector<T>& a, const std::vector<T>& b)\n{\n  assert(a.size() == b.size());\n\n  std::vector<T> result;\n  result.reserve(a.size());\n\n  std::transform(a.begin(), a.end(), b.begin(), std::back_inserter(result), std::minus<T>());\n  return result;\n}\n\ntemplate <typename T>  // Overload *\nstd::vector<T> operator*(const double& a, const std::vector<T>& b)\n{\n  std::vector<T> result;\n\n  for (int i = 0; i < b.size(); i++)\n  {\n    result.push_back(a * b[i]);\n  }\n\n  return result;\n}\n\ntemplate <typename T>\nGRBVector operator-(const std::vector<T>& x, const std::vector<double>& b)\n{\n  GRBVector result;\n  for (int i = 0; i < x.size(); i++)\n  {\n    GRBLinExpr tmp = x[i] - b[i];\n    result.push_back(tmp);\n  }\n  return result;\n}\n\ntemplate <typename T>\nstd::vector<T> eigenVector2std(const Eigen::Matrix<T, -1, 1>& x)\n{\n  std::vector<T> result;\n  for (int i = 0; i < x.rows(); i++)\n  {\n    result.push_back(x(i, 1));\n  }\n  return result;\n}\n\ntemplate <typename T>\nstd::vector<T> eigenVector2std(const Eigen::Matrix<T, 3, 1>& x)  // TODO: Merge with the previous one?\n{\n  std::vector<T> result;\n  for (int i = 0; i < x.rows(); i++)\n  {\n    result.push_back(x(i, 1));\n  }\n  return result;\n}\n\ninline std::vector<std::vector<double>> eigenMatrix2std(const Eigen::Matrix<double, -1, -1>& x)\n{\n  std::vector<std::vector<double>> result;\n\n  for (int i = 0; i < x.rows(); i++)\n  {\n    std::vector<double> row;\n    for (int j = 0; j < x.cols(); j++)\n    {\n      row.push_back(x(i, j));\n    }\n    result.push_back(row);\n  }\n  return result;\n}\n\ntemplate <typename T>\nstd::vector<T> getColumn(std::vector<std::vector<T>> x, int column)\n{\n  std::vector<T> result;\n\n  for (int i = 0; i < x.size(); i++)\n  {\n    result.push_back(x[i][column]);\n  }\n  return result;\n}\n\n// // GRBLinExpr novale = A[i][m] * B[m][j];\n// // std::cout << \"B[m][j]=\" << B[m][j] << std::endl;\n// // std::cout << \"novale.size() =\" << novale.size() << std::endl;\n\n// // std::cout << \"novale.getCoeff(0) =\" << novale.getCoeff(0) << std::endl;\n// // std::cout << \"novale.getCoeff(0) =\" << novale.getCoeff(1) << std::endl;\n\n// std::vector<std::vector<double>> matrixMultiply(const std::vector<std::vector<double>>& A,\n//                                                 const std::vector<std::vector<double>>& B)\n// {\n//   std::vector<std::vector<double>> result(A.size(), std::vector<double>(B[0].size(), 0.0));  // Initialize all the\n//                                                                                              // elements to zero\n\n//   for (int i = 0; i < A.size(); i++)  // multiply row if of A\n//   {\n//     for (int j = 0; j < B[0].size(); j++)  // times column j of B\n//     {\n//       double lin_exp = 0;\n//       for (int m = 0; m < B.size(); m++)\n//       {\n//         lin_exp+ = + A[i][m] * B[m][j];\n//       }\n//       result[i][j] = lin_exp;\n//     }\n//   }\n//   return result;\n// }\n\n// std::vector<std::vector<double>> tmp;\n\n// std::vector<double> row1;\n// row1.push_back(2.0);\n// row1.push_back(1.0);\n\n// std::vector<double> row2;\n// row2.push_back(3.0);\n// row2.push_back(-5.0);\n\n// tmp.push_back(row1);\n// tmp.push_back(row2);\n\n// std::cout << \"MINI TEST sizes\" << std::endl;\n// std::cout << \"tmp.size()=\" << tmp.size() << std::endl;\n// std::cout << \"tmp[0].size()=\" << tmp[0].size() << std::endl;\n\n// std::vector<std::vector<double>> result = matrixMultiply(tmp, tmp);\n\n// std::cout << \"MINI TEST result\" << std::endl;\n// for (auto tmp : result)\n// {\n//   std::cout << tmp[0] << \", \" << tmp[1] << std::endl;\n// }\n\n// template <typename T, typename R>\n// GRBVector matrixMultiply(const std::vector<std::vector<R>>& A, const std::vector<std::vector<R>>& B)\n// {\n//   std::vector<GRBVector> result;\n\n//   for (int i = 0; i < A.size(); i++)\n//   {\n//     GRBLinExpr lin_exp = 0;\n//     for (int m = 0; m < x.size(); m++)\n//     {\n//       lin_exp = lin_exp + A[i][m] * x[m];\n//     }\n//     result.push_back(lin_exp);\n//   }\n//   return result;\n// }\n\n// // template <typename T>\n// Eigen::Matrix<GRBLinExpr, -1, -1> myMultDV(const Eigen::Matrix<double, -1, -1>& A,\n//                                            const Eigen::Matrix<GRBVar, -1, 1>& b)\n// {\n//   Eigen::Matrix<GRBLinExpr, -1, -1> result(A.rows(), b.cols());\n\n//   for (int i = 0; i < A.rows(); i++)\n//   {\n//     GRBLinExpr exp = 0;\n//     for (int m = 0; m < b.rows(); m++)\n//     {\n//       exp = exp + A(i, m) * b[m];\n//     }\n//     result(i, 1) = exp;\n//   }\n//   return result;\n// }\n\n// Eigen::Matrix<GRBLinExpr, -1, -1> myMultVD(const Eigen::Matrix<GRBVar, -1, -1>& A,\n//                                            const Eigen::Matrix<double, -1, 1>& b)\n// {\n//   Eigen::Matrix<GRBLinExpr, -1, -1> result(A.rows(), b.cols());\n\n//   for (int i = 0; i < A.rows(); i++)\n//   {\n//     GRBLinExpr exp = 0;\n//     for (int m = 0; m < b.rows(); m++)\n//     {\n//       exp = exp + A(i, m) * b[m];\n//     }\n//     result(i, 1) = exp;\n//   }\n//   return result;\n// }\n\n// // squared norm of a vector or matrix\n// GRBLinExpr getNorm2(const Eigen::Matrix<GRBLinExpr, -1, -1>& x)\n// {\n//   GRBLinExpr result = 0;\n//   for (int i = 0; i < x.rows(); i++)\n//   {\n//     for (int j = 0; j < x.cols(); j++)\n//     {\n//       result = result + x(i, j) * x(i, j);\n//     }\n//   }\n//   return result;\n// }\n\n// // Overload - to substract Elementwise std::vectors\n// Eigen::Matrix<GRBLinExpr, -1, -1> operator-(const Eigen::Matrix<GRBLinExpr, -1, -1>& a,\n//                                             const Eigen::Matrix<GRBLinExpr, -1, -1>& b)\n// {\n//   assert(a.rows() == b.rows());\n//   assert(a.cols() == b.cols());\n\n//   Eigen::Matrix<GRBLinExpr, -1, -1> result(a.cols(), a.rows());\n\n//   for (int i = 0; i < a.rows(); i++)\n//   {\n//     for (int j = 0; j < a.cols(); j++)\n//     {\n//       result(i, j) = a(i, j) + b(i, j);\n//     }\n//   }\n\n//   return result;\n// }\n\n// Eigen::Matrix<GRBLinExpr, -1, -1> myMult(const Eigen::Matrix<GRBVar, -1, -1>& A, const Eigen::Matrix<GRBVar, -1, 1>&\n// b)\n// {\n//   Eigen::Matrix<GRBLinExpr, -1, -1> result(A.rows(), b.cols());\n\n//   for (int i = 0; i < A.rows(); i++)\n//   {\n//     GRBLinExpr exp = 0;\n//     for (int m = 0; m < b.rows(); m++)\n//     {\n//       exp = exp + A(i, m) * b[m];\n//     }\n//     result(i, 1) = exp;\n//   }\n//   return result;\n// }\n\n// Eigen::Matrix<GRBLinExpr, 2, 1> operator*(const Eigen::Matrix<double, 2, 2>& A, const Eigen::Matrix<GRBVar, 2, 1>& b)\n// {\n//   Eigen::Matrix<GRBLinExpr, 2, 1> result;\n\n//   for (int i = 0; i < A.rows(); i++)\n//   {\n//     GRBLinExpr exp = 0;\n//     for (int m = 0; m < b.rows(); m++)\n//     {\n//       exp = exp + A(i, m) * b[m];\n//     }\n//     result(i, 1) = exp;\n//   }\n//   return result;\n// }\n\n// template<typename Derived>\n// void printFirstRow(const Eigen::MatrixBase<Derived>& x)\n// {\n\n// template <typename T>\n// Eigen::Matrix<GRBLinExpr, 2, 1> operator*(const Eigen::MatrixBase<Derived1>& A, const Eigen::MatrixBase<Derived2>& b)\n// {\n//   Eigen::Matrix<GRBLinExpr, 2, 1> result;\n\n//   for (int i = 0; i < A.rows(); i++)\n//   {\n//     GRBLinExpr exp = 0;\n//     for (int m = 0; m < b.rows(); m++)\n//     {\n//       exp = exp + A(i, m) * b[m];\n//     }\n//     result(i, 1) = exp;\n//   }\n//   return result;\n// }\n\n/*GRBVector MatrixMultiply(const std::vector<std::vector<double>>& A, const GRBVector& x)\n{\n  GRBVector result;\n  for (int i = 0; i < A.size(); i++)\n  {\n    GRBLinExpr lin_exp = 0;\n    for (int m = 0; m < x.size(); m++)\n    {\n      lin_exp = lin_exp + A[i][m] * x[m];\n    }\n    result.push_back(lin_exp);\n  }\n  return result;\n}*/\n\n#endif\n", "meta": {"hexsha": "9ea0e90e25a444b2d8b2cb2da9d0eda9bf086179", "size": 13188, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "mader/include/solver_gurobi_utils.hpp", "max_stars_repo_name": "shubham-shahh/mader", "max_stars_repo_head_hexsha": "7cbe46438b348a1ad9545146734083d0b6436bd4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 222.0, "max_stars_repo_stars_event_min_datetime": "2020-12-23T01:45:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T22:46:02.000Z", "max_issues_repo_path": "mader/include/solver_gurobi_utils.hpp", "max_issues_repo_name": "shubham-shahh/mader", "max_issues_repo_head_hexsha": "7cbe46438b348a1ad9545146734083d0b6436bd4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2021-02-18T15:19:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-01T14:19:54.000Z", "max_forks_repo_path": "mader/include/solver_gurobi_utils.hpp", "max_forks_repo_name": "shubham-shahh/mader", "max_forks_repo_head_hexsha": "7cbe46438b348a1ad9545146734083d0b6436bd4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 48.0, "max_forks_repo_forks_event_min_datetime": "2020-12-21T01:00:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T22:46:04.000Z", "avg_line_length": 26.0118343195, "max_line_length": 120, "alphanum_fraction": 0.5414771004, "num_tokens": 4253, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754371026367, "lm_q2_score": 0.6619228625116081, "lm_q1q2_score": 0.4818635851651164}}
{"text": "//\n//  Copyright Toon Knapen, Karl Meerbergen\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#include \"ublas_heev.hpp\"\n\n#include <boost/numeric/bindings/lapack/driver/syev.hpp>\n#include <boost/numeric/bindings/noop.hpp>\n#include <boost/numeric/bindings/ublas/matrix.hpp>\n#include <boost/numeric/bindings/ublas/matrix_proxy.hpp>\n#include <boost/numeric/bindings/ublas/symmetric.hpp>\n#include <boost/numeric/bindings/ublas/vector.hpp>\n#include <boost/numeric/bindings/ublas/vector_proxy.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n#include <iostream>\n\n\nnamespace ublas = boost::numeric::ublas;\nnamespace lapack = boost::numeric::bindings::lapack;\nnamespace bindings = boost::numeric::bindings;\n\ntemplate <char UPLO>\nstruct translate_uplo\n{\n} ;\n\ntemplate <>\nstruct translate_uplo<'U'>\n{\n  typedef ublas::upper_tag type ;\n} ;\n\ntemplate <>\nstruct translate_uplo<'L'>\n{\n  typedef ublas::lower_tag type ;\n} ;\n\ntemplate <typename T, typename W, typename UPLO>\nint do_memory_uplo(int n, W& workspace)\n{\n  typedef typename bindings::remove_imaginary<T>::type real_type ;\n\n  typedef ublas::matrix<T, ublas::column_major>     matrix_type ;\n  typedef ublas::symmetric_adaptor<matrix_type, UPLO> symmetric_type ;\n  typedef ublas::vector<real_type>                  vector_type ;\n\n  // Set matrix\n  matrix_type a(n, n);\n  a.clear();\n  vector_type e1(n);\n  vector_type e2(n);\n\n  fill(a);\n  matrix_type a2(a);\n\n  // Compute eigen decomposition.\n  symmetric_type s_a(a);\n  lapack::syev('V', bindings::noop(s_a), e1, workspace) ;\n\n  if(check_residual(a2, e1, a)) return 255 ;\n\n  symmetric_type s_a2(a2);\n  lapack::syev('N', s_a2, e2, workspace) ;\n  if(norm_2(e1 - e2) > n * norm_2(e1) * std::numeric_limits< real_type >::epsilon()) return 255 ;\n\n  // Test for a matrix range\n  fill(a);\n  a2.assign(a);\n\n  typedef ublas::matrix_range< matrix_type > matrix_range ;\n  typedef ublas::symmetric_adaptor<matrix_range, UPLO> symmetric_range_type;\n\n  ublas::range r(1,n-1) ;\n  matrix_range a_r(a, r, r);\n  ublas::vector_range< vector_type> e_r(e1, r);\n\n  symmetric_range_type s_a_r(a_r);\n  lapack::syev('V',  s_a_r, e_r, workspace);\n\n  matrix_range a2_r(a2, r, r);\n  if(check_residual(a2_r, e_r, a_r)) return 255 ;\n\n  // Test for symmetric_adaptor\n  fill(a);\n  a2.assign(a);\n  ublas::symmetric_adaptor< matrix_type, UPLO> a_uplo(a) ;\n  lapack::syev('V', a_uplo, e1, workspace) ;\n  if(check_residual(a2, e1, a)) return 255 ;\n\n  return 0 ;\n} // do_memory_uplo()\n\n\ntemplate <typename T, typename W>\nint do_memory_type(int n, W workspace)\n{\n  std::cout << \"  upper\\n\" ;\n  if(do_memory_uplo<T,W,ublas::upper>(n, workspace)) return 255 ;\n  std::cout << \"  lower\\n\" ;\n  if(do_memory_uplo<T,W,ublas::lower>(n, workspace)) return 255 ;\n  return 0 ;\n}\n\n\ntemplate <typename T>\nstruct Workspace\n{\n  typedef ublas::vector<T>                         array_type ;\n  typedef lapack::detail::workspace1< array_type > type ;\n\n  Workspace(size_t n)\n    : work_(3*n-1)\n  {}\n\n  type operator()()\n  {\n    return lapack::workspace(work_) ;\n  }\n\n  array_type work_ ;\n};\n\n\ntemplate <typename T>\nint do_value_type()\n{\n  const int n = 8 ;\n\n  std::cout << \" optimal workspace\\n\";\n  if(do_memory_type<T,lapack::optimal_workspace>(n, lapack::optimal_workspace())) return 255 ;\n\n  std::cout << \" minimal workspace\\n\";\n  if(do_memory_type<T,lapack::minimal_workspace>(n, lapack::minimal_workspace())) return 255 ;\n\n  std::cout << \" workspace array\\n\";\n  Workspace<T> work(n);\n  if(do_memory_type<T,typename Workspace<T>::type >(n, work())) return 255 ;\n  return 0;\n} // do_value_type()\n\n\nint main()\n{\n  // Run tests for different value_types\n  std::cout << \"float\\n\" ;\n  if(do_value_type<float>()) return 255;\n\n  std::cout << \"double\\n\" ;\n  if(do_value_type<double>()) return 255;\n\n  std::cout << \"Regression test succeeded\\n\" ;\n  return 0;\n}\n\n", "meta": {"hexsha": "5adfd59c60a82d2f50b02e5cf2671dc3ed7a3015", "size": 3901, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "externals/numeric_bindings/libs/numeric/bindings/lapack/test/ublas_syev.cpp", "max_stars_repo_name": "fperignon/sandbox", "max_stars_repo_head_hexsha": "649f09d6db7bbd84c2418de74eb9453c0131f070", "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/lapack/test/ublas_syev.cpp", "max_issues_repo_name": "fperignon/sandbox", "max_issues_repo_head_hexsha": "649f09d6db7bbd84c2418de74eb9453c0131f070", "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/lapack/test/ublas_syev.cpp", "max_forks_repo_name": "fperignon/sandbox", "max_forks_repo_head_hexsha": "649f09d6db7bbd84c2418de74eb9453c0131f070", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 30.0, "max_forks_repo_forks_event_min_datetime": "2015-08-06T22:57:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T20:30:20.000Z", "avg_line_length": 24.2298136646, "max_line_length": 97, "alphanum_fraction": 0.6882850551, "num_tokens": 1135, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289836, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.48180393735261756}}
{"text": "// Copyright 2008 Gautam Sewani\n//\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_MATH_DISTRIBUTIONS_LOGISTIC\n#define BOOST_MATH_DISTRIBUTIONS_LOGISTIC\n\n#include <boost/math/distributions/fwd.hpp>\n#include <boost/math/distributions/detail/common_error_handling.hpp>\n#include <boost/math/distributions/complement.hpp>\n#include <boost/math/special_functions/log1p.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <utility>\n\nnamespace boost { namespace math {\n\n    template <class RealType = double, class Policy = policies::policy<> >\n    class logistic_distribution\n    {\n    public:\n      typedef RealType value_type;\n      typedef Policy policy_type;\n\n      logistic_distribution(RealType l_location=0, RealType l_scale=1) // Constructor.\n        : m_location(l_location), m_scale(l_scale)\n      {\n        static const char* function = \"boost::math::logistic_distribution<%1%>::logistic_distribution\";\n\n        RealType result;\n        detail::check_scale(function, l_scale, &result, Policy());\n        detail::check_location(function, l_location, &result, Policy());\n      }\n      // Accessor functions.\n      RealType scale()const\n      {\n        return m_scale;\n      }\n\n      RealType location()const\n      {\n        return m_location;\n      }\n    private:\n      // Data members:\n      RealType m_location;  // distribution location aka mu.\n      RealType m_scale;  // distribution scale aka s.\n    }; // class logistic_distribution\n\n\n    typedef logistic_distribution<double> logistic;\n\n    template <class RealType, class Policy>\n    inline const std::pair<RealType, RealType> range(const logistic_distribution<RealType, Policy>& /* dist */)\n    { // Range of permissible values for random variable x.\n      using boost::math::tools::max_value;\n      return std::pair<RealType, RealType>(\n         std::numeric_limits<RealType>::has_infinity ? -std::numeric_limits<RealType>::infinity() : -max_value<RealType>(),\n         std::numeric_limits<RealType>::has_infinity ? std::numeric_limits<RealType>::infinity() : max_value<RealType>());\n    }\n\n    template <class RealType, class Policy>\n    inline const std::pair<RealType, RealType> support(const logistic_distribution<RealType, Policy>& /* dist */)\n    { // Range of supported values for random variable x.\n      // This is range where cdf rises from 0 to 1, and outside it, the pdf is zero.\n      using boost::math::tools::max_value;\n      return std::pair<RealType, RealType>(-max_value<RealType>(), max_value<RealType>()); // - to + infinity\n    }\n\n    template <class RealType, class Policy>\n    inline RealType pdf(const logistic_distribution<RealType, Policy>& dist, const RealType& x)\n    {\n       static const char* function = \"boost::math::pdf(const logistic_distribution<%1%>&, %1%)\";\n       RealType scale = dist.scale();\n       RealType location = dist.location();\n       RealType result = 0;\n\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\n       if((boost::math::isinf)(x))\n       {\n          return 0; // pdf + and - infinity is zero.\n       }\n\n       if(false == detail::check_x(function, x, &result, Policy()))\n       {\n          return result;\n       }\n\n       BOOST_MATH_STD_USING\n       RealType exp_term = (location - x) / scale;\n       if(fabs(exp_term) > tools::log_max_value<RealType>())\n          return 0;\n       exp_term = exp(exp_term);\n       if((exp_term * scale > 1) && (exp_term > tools::max_value<RealType>() / (scale * exp_term)))\n          return 1 / (scale * exp_term);\n       return (exp_term) / (scale * (1 + exp_term) * (1 + exp_term));\n    }\n\n    template <class RealType, class Policy>\n    inline RealType cdf(const logistic_distribution<RealType, Policy>& dist, const RealType& x)\n    {\n       RealType scale = dist.scale();\n       RealType location = dist.location();\n       RealType result = 0; // of checks.\n       static const char* function = \"boost::math::cdf(const logistic_distribution<%1%>&, %1%)\";\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\n       if((boost::math::isinf)(x))\n       {\n          if(x < 0) return 0; // -infinity\n          return 1; // + infinity\n       }\n\n       if(false == detail::check_x(function, x, &result, Policy()))\n       {\n          return result;\n       }\n       BOOST_MATH_STD_USING\n       RealType power = (location - x) / scale;\n       if(power > tools::log_max_value<RealType>())\n          return 0;\n       if(power < -tools::log_max_value<RealType>())\n          return 1;\n       return 1 / (1 + exp(power));\n    }\n\n    template <class RealType, class Policy>\n    inline RealType quantile(const logistic_distribution<RealType, Policy>& dist, const RealType& p)\n    {\n       BOOST_MATH_STD_USING\n       RealType location = dist.location();\n       RealType scale = dist.scale();\n\n       static const char* function = \"boost::math::quantile(const logistic_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_probability(function, p, &result, Policy()))\n          return result;\n\n       if(p == 0)\n       {\n          return -policies::raise_overflow_error<RealType>(function,\"probability argument is 0, must be >0 and <1\",Policy());\n       }\n       if(p == 1)\n       {\n          return policies::raise_overflow_error<RealType>(function,\"probability argument is 1, must be >0 and <1\",Policy());\n       }\n       //Expressions to try\n       //return location+scale*log(p/(1-p));\n       //return location+scale*log1p((2*p-1)/(1-p));\n\n       //return location - scale*log( (1-p)/p);\n       //return location - scale*log1p((1-2*p)/p);\n\n       //return -scale*log(1/p-1) + location;\n       return location - scale * log((1 - p) / p);\n     } // RealType quantile(const logistic_distribution<RealType, Policy>& dist, const RealType& p)\n\n    template <class RealType, class Policy>\n    inline RealType cdf(const complemented2_type<logistic_distribution<RealType, Policy>, RealType>& c)\n    {\n       BOOST_MATH_STD_USING\n       RealType location = c.dist.location();\n       RealType scale = c.dist.scale();\n       RealType x = c.param;\n       static const char* function = \"boost::math::cdf(const complement(logistic_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((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       if(false == detail::check_x(function, x, &result, Policy()))\n       {\n          return result;\n       }\n       RealType power = (x - location) / scale;\n       if(power > tools::log_max_value<RealType>())\n          return 0;\n       if(power < -tools::log_max_value<RealType>())\n          return 1;\n       return 1 / (1 + exp(power));\n    }\n\n    template <class RealType, class Policy>\n    inline RealType quantile(const complemented2_type<logistic_distribution<RealType, Policy>, RealType>& c)\n    {\n       BOOST_MATH_STD_USING\n       RealType scale = c.dist.scale();\n       RealType location = c.dist.location();\n       static const char* function = \"boost::math::quantile(const complement(logistic_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       RealType q = c.param;\n       if(false == detail::check_probability(function, q, &result, Policy()))\n          return result;\n       using boost::math::tools::max_value;\n\n       if(q == 1)\n       {\n          return -policies::raise_overflow_error<RealType>(function,\"probability argument is 1, but must be >0 and <1\",Policy());\n       }\n       if(q == 0)\n       {\n          return policies::raise_overflow_error<RealType>(function,\"probability argument is 0, but must be >0 and <1\",Policy());\n       }\n       //Expressions to try\n       //return location+scale*log((1-q)/q);\n       return location + scale * log((1 - q) / q);\n\n       //return location-scale*log(q/(1-q));\n       //return location-scale*log1p((2*q-1)/(1-q));\n\n       //return location+scale*log(1/q-1);\n       //return location+scale*log1p(1/q-2);\n    }\n\n    template <class RealType, class Policy>\n    inline RealType mean(const logistic_distribution<RealType, Policy>& dist)\n    {\n      return dist.location();\n    } // RealType mean(const logistic_distribution<RealType, Policy>& dist)\n\n    template <class RealType, class Policy>\n    inline RealType variance(const logistic_distribution<RealType, Policy>& dist)\n    {\n      BOOST_MATH_STD_USING\n      RealType scale = dist.scale();\n      return boost::math::constants::pi<RealType>()*boost::math::constants::pi<RealType>()*scale*scale/3;\n    } // RealType variance(const logistic_distribution<RealType, Policy>& dist)\n\n    template <class RealType, class Policy>\n    inline RealType mode(const logistic_distribution<RealType, Policy>& dist)\n    {\n      return dist.location();\n    }\n\n    template <class RealType, class Policy>\n    inline RealType median(const logistic_distribution<RealType, Policy>& dist)\n    {\n      return dist.location();\n    }\n    template <class RealType, class Policy>\n    inline RealType skewness(const logistic_distribution<RealType, Policy>& /*dist*/)\n    {\n      return 0;\n    } // RealType skewness(const logistic_distribution<RealType, Policy>& dist)\n\n    template <class RealType, class Policy>\n    inline RealType kurtosis_excess(const logistic_distribution<RealType, Policy>& /*dist*/)\n    {\n      return static_cast<RealType>(6)/5;\n    } // RealType kurtosis_excess(const logistic_distribution<RealType, Policy>& dist)\n\n    template <class RealType, class Policy>\n    inline RealType kurtosis(const logistic_distribution<RealType, Policy>& dist)\n    {\n      return kurtosis_excess(dist) + 3;\n    } // RealType kurtosis_excess(const logistic_distribution<RealType, Policy>& dist)\n  }}\n\n\n// Must come at the end:\n#include <boost/math/distributions/detail/derived_accessors.hpp>\n\n#endif // BOOST_MATH_DISTRIBUTIONS_LOGISTIC\n", "meta": {"hexsha": "d5418ce100db3c1a630ffb7e491317d6cd9ffe6c", "size": 10991, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/src/boost_1_65_1/boost/math/distributions/logistic.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/math/distributions/logistic.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/math/distributions/logistic.hpp", "max_forks_repo_name": "shreyasvj25/turicreate", "max_forks_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 36.6366666667, "max_line_length": 129, "alphanum_fraction": 0.6341552179, "num_tokens": 2593, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289835, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.4818039373526175}}
{"text": "#include <iostream>\n#include <Eigen/Core>\n#include <unsupported/Eigen/CXX11/Tensor>\n\n#include \"IO/readPLY.h\"\n#include \"IO/writePLY.h\"\n\n#include \"visualization/plotMesh.h\"\n#include \"visualization/plotTwoMeshes.h\"\n#include \"visualization/plotCloud.h\"\n\n#include \"mesh/computeNormals.h\"\n#include \"mesh/computeFacesCentroids.h\"\n#include \"occupancyGridWithColor.h\"\n\nint main() {\n    bool visualization = true;\n    int grid_resolution = 100;          // grid_resolution is used to define the grid resolution in the maximum direction\n    double bounding_box_scale = 1;\n\n    // IO: load files\n    std::cout << \"Progress: load data\\n\";\n    Eigen::MatrixXd V, cubes_V, faces_V;\n    Eigen::MatrixXi F, cubes_F;\n    Eigen::MatrixXd N, faces_N;\n    Eigen::MatrixXi RGB;\n\n    readPLY(\"../data/crab_full.ply\", V, F, N, RGB);\n\n    faces_V = compute_faces_centroids(V,F);\n    faces_N = compute_faces_normals(V,F);\n\n    Eigen::MatrixXd faces_RGB, cubes_RGB;\n    Eigen::MatrixXd RGB_double = RGB.cast<double> ();\n    RGB_double /=256;\n\n    faces_RGB = compute_faces_centroids(RGB_double,F);\n\n    if (visualization)\n        plot_mesh(V,F, RGB_double);\n    \n    if (visualization)\n        plot_cloud(faces_V, faces_RGB);\n\n    OccupancyGridWithColor occupancy_grid(faces_V, faces_N, faces_RGB, grid_resolution, bounding_box_scale);\n    \n    Eigen::MatrixXd graph_V;\n    Eigen::MatrixXi graph_E;\n    occupancy_grid.generate_graph(graph_V, graph_E);\n    occupancy_grid.print_to_folder(\"../data/occupancy_grid/\");\n    occupancy_grid.print_to_yaml(\"../data/crab.yaml\");\n\n    occupancy_grid.generate_mesh(cubes_V, cubes_F, cubes_RGB);\n\n    if (visualization)\n        plot_mesh(cubes_V,cubes_F, cubes_RGB);\n        //plot_two_meshes(V,F,cubes_V,cubes_F, cubes_RGB);\n\n}\n", "meta": {"hexsha": "7959e73f3e115acc526d194229af3e9d9a90924c", "size": 1740, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "app/test_occupancyGridWithColor.cpp", "max_stars_repo_name": "rFalque/voxelization_and_sdf", "max_stars_repo_head_hexsha": "6ae111412f2383244b7caf04affd561f64ce9a4f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2020-02-13T04:42:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T23:27:05.000Z", "max_issues_repo_path": "app/test_occupancyGridWithColor.cpp", "max_issues_repo_name": "rFalque/voxelization_and_sdf", "max_issues_repo_head_hexsha": "6ae111412f2383244b7caf04affd561f64ce9a4f", "max_issues_repo_licenses": ["MIT"], "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/test_occupancyGridWithColor.cpp", "max_forks_repo_name": "rFalque/voxelization_and_sdf", "max_forks_repo_head_hexsha": "6ae111412f2383244b7caf04affd561f64ce9a4f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-01-15T10:32:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-25T01:44:27.000Z", "avg_line_length": 29.0, "max_line_length": 121, "alphanum_fraction": 0.708045977, "num_tokens": 427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.63341027059799, "lm_q1q2_score": 0.48180393574285896}}
{"text": "#ifndef FLEMU_ADDER_HPP\n#define FLEMU_ADDER_HPP\n\n#include \"float32.hpp\"\n\n#include <boost/ut.hpp>\n\n#include <random>\n#include <tuple>\n\nnamespace flemu\n{\n\ninline float32 add(const float32& x_, const float32& y_) noexcept\n{\n    // ------------------------------------------------------------------------\n    // always make x <= y\n    const auto [x, y] = [&]\n    {\n        if(x_.exponent() == y_.exponent())\n        {\n            if(x_.mantissa() < y_.mantissa())\n            {\n                return std::make_pair(x_, y_);\n            }\n            else\n            {\n                return std::make_pair(y_, x_);\n            }\n        }\n        else\n        {\n            if(x_.exponent() < y_.exponent())\n            {\n                return std::make_pair(x_, y_);\n            }\n            else\n            {\n                return std::make_pair(y_, x_);\n            }\n        }\n    }();\n\n    const std::uint32_t xsgn(x.sign());\n    const std::uint32_t xexp(x.exponent());\n    const std::uint32_t xman(x.mantissa());\n\n    const std::uint32_t ysgn(y.sign());\n    const std::uint32_t yexp(y.exponent());\n    const std::uint32_t yman(y.mantissa());\n\n    // ------------------------------------------------------------------------\n    // check special values\n    const auto xinf  = (xexp == 0b1111'1111) && (xman == 0);\n    const auto yinf  = (yexp == 0b1111'1111) && (yman == 0);\n    const auto xnan  = (xexp == 0b1111'1111) && (xman != 0);\n    const auto ynan  = (yexp == 0b1111'1111) && (yman != 0);\n    const auto xzero = (xexp == 0) && (xman == 0);\n    const auto yzero = (yexp == 0) && (yman == 0);\n    const auto xdenorm = (xexp == 0) && (xman != 0);\n    const auto ydenorm = (yexp == 0) && (yman != 0);\n\n    if(xnan || ynan) // z + nan == nan,  nan + z == nan\n    {\n        return float32(0b0, 0b1111'1111, 0b1);\n    }\n    else if (xinf || yinf)\n    {\n        if(xinf && yinf)\n        {\n            if(xsgn != ysgn) // inf - inf == nan, -inf + inf == nan\n            {\n                return float32(0b0, 0b1111'1111, 0b1);\n            }\n            else // inf + inf == inf, -inf + (-inf) = -inf\n            {\n                return float32(std::uint32_t(xsgn), 0b1111'1111, 0b0);\n            }\n        }\n        else if((xinf && xsgn == 0) || (yinf && ysgn == 0)) // inf + * == inf\n        {\n            return float32(0b0, 0b1111'1111, 0b0);\n        }\n        else  // -inf + * == -inf\n        {\n            return float32(0b1, 0b1111'1111, 0b0);\n        }\n    }\n    else if (xzero || yzero)\n    {\n        if(xzero && yzero)\n        {\n            // we here consider only nearest-(even)-rounding.\n            // in case of negative-inf-rounding, (+0) + (-0) should be (-0).\n            return float32(0);\n        }\n        else if (xzero)\n        {\n            return y;\n        }\n        else // yzero\n        {\n            return x;\n        }\n    }\n\n    // ------------------------------------------------------------------------\n    // align mantissa (always x.exp <= y.exp)\n\n    const auto [xman_aligned, yman_aligned, xexp_norm, yexp_norm] = [&]\n    {\n        std::uint32_t xexp_norm = xexp;\n        std::uint32_t yexp_norm = yexp;\n        std::uint32_t xman_aligned = (1 << 23);\n        std::uint32_t yman_aligned = (1 << 23);\n\n        if(xdenorm)\n        {\n            xman_aligned = 0; // remove implicit 1\n            xexp_norm   += 1;\n        }\n        if(ydenorm)\n        {\n            yman_aligned = 0;\n            yexp_norm   += 1;\n        }\n\n        xman_aligned += std::uint32_t(xman);\n        yman_aligned += std::uint32_t(yman);\n        xman_aligned <<= 3;\n        yman_aligned <<= 3;\n\n        if(xexp_norm == yexp_norm)\n        {\n            return std::make_tuple(xman_aligned, yman_aligned, xexp_norm, yexp_norm);\n        }\n        // exponent is different\n        const std::uint32_t expdiff = std::uint32_t(yexp_norm) - std::uint32_t(xexp_norm);\n\n        //         mantissa      additional bits\n        //    .---------------. .---.\n        // y:| 1.xxxxxxxxxxxxxx|0|0|0|\n        // x:     | 1.xxxxxxxxx|x|x|x|x|x|0|0|0| >> expdiff == e.g. 5\n        //                      | | | '-------'\n        //                      | | |  sticky region\n        //                      | | + sticky bit\n        //                      | + round bit\n        //                      + guard bit\n\n        if(expdiff >= 27) // 1 + 23 + 3\n        {\n            xman_aligned = 0;\n        }\n        else\n        {\n            std::uint32_t sticky = 0;\n            if(expdiff > 3)\n            {\n                const auto sticky_region = xman_aligned & mask<std::uint32_t>(expdiff - 1, 0);\n                sticky = (sticky_region == 0) ? 0 : 1;\n            }\n            xman_aligned >>= expdiff;\n            xman_aligned |= sticky;\n        }\n        return std::make_tuple(xman_aligned, yman_aligned, xexp_norm, yexp_norm);\n    }();\n\n//     std::cerr << \"xman_aligned = \" << as_bit(xman_aligned) << std::endl;\n//     std::cerr << \"yman_aligned = \" << as_bit(yman_aligned) << std::endl;\n\n    // ------------------------------------------------------------------------\n    // add/sub mantissa and round\n\n    //           26 25       22 ...  03 02 01 00\n    // y: | 0...| 1| z| z| z| z|... | z| 0| 0| 0|\n    // x: | 0...| 0| 0| 0| 1| z|... | z| z| z| z|\n    //             '-------------------' |  |  +- sticky\n    //                   mantissa        |  +---- round\n    //                                   +------- guard\n\n    std::uint32_t zsgn(ysgn);\n    std::uint32_t zexp(yexp_norm);\n    if(xsgn != ysgn) // subtract. always abs(x) < abs(y), so the sign is y.\n    {\n        std::uint32_t zman = yman_aligned - xman_aligned;\n\n        if(zman == 0)\n        {\n            // zero cannot be normalized\n            return float32(zsgn, 0u, 0u);\n        }\n\n        while(bit_at(zman, 26) == 0)\n        {\n            zexp  -= 1;\n            if(zexp == 0)\n            {\n                // since it becomes denormalized number, we don't need to\n                // normalize it.\n                break;\n            }\n            zman <<= 1;\n        }\n\n        if(zexp == 0)\n        {\n            // if it is 0.111...111, then it will be 1.00 after rounding and\n            // will become normalized.\n            if((zman & mask<std::uint32_t>(25, 2)) >> 2 == (1<<24)-1)\n            {\n                return float32(zsgn, std::uint32_t(1), std::uint32_t(0));\n            }\n        }\n\n        // consider nearest-even rounding only\n        if(bit_at(zman, 2) == 1)\n        {\n            if(bit_at(zman, 1) == 0 && bit_at(zman, 0) == 0) // to even\n            {\n                if(bit_at(zman, 3) == 0)\n                {\n                    // already even. do nothing.\n                }\n                else // its odd.\n                {\n                    zman += 0b1000;\n                }\n            }\n            else // to nearest (upper)\n            {\n                zman += 0b1000;\n            }\n        }\n\n        // check carry-up by rounding (1.11111 -> 10.0000)\n        // 10.0000e+2 == 1.0000e+3\n        if(bit_at(zman, 27) == 1)\n        {\n            zexp  += 1;\n            zman >>= 1;\n        }\n        assert(bit_at(zman, 26) == 1 || zexp == 0); // normalized?\n\n        if(zexp == 0b1111'1111)\n        {\n            // it was not nan, so here it should be inf\n            zman = 0;\n        }\n        return float32(zsgn, zexp, std::uint32_t(bit_proxy(zman, 25, 3)));\n    }\n    else // add.\n    {\n        assert(bit_at(xman_aligned, 27) == 0);\n        assert(bit_at(yman_aligned, 27) == 0);\n        std::uint32_t zman = yman_aligned + xman_aligned;\n\n        // check carry-up by addition\n        if(bit_at(zman, 27) == 1)\n        {\n            // if we shift before checking round, the sticky bit will be lost.\n\n            if(bit_at(zman, 3) == 1) // need to round up.\n            {\n                if(bit_at(zman, 2) == 0 && bit_at(zman, 1) == 0 && bit_at(zman, 0) == 0) // to even\n                {\n                    if(bit_at(zman, 4) == 0)\n                    {\n                        // already even. do nothing.\n                    }\n                    else\n                    {\n                        zman += 0b1'0000;\n                    }\n                }\n                else // to nearest (upper)\n                {\n                    zman += 0b1'0000;\n                }\n            }\n            if(bit_at(zman, 28) == 1)\n            {\n                zexp  += 2;\n                zman >>= 2;\n            }\n            else if(bit_at(zman, 27) == 1)\n            {\n                zexp  += 1;\n                zman >>= 1;\n            }\n            else\n            {\n                assert(false);\n            }\n        }\n        else\n        {\n            if(bit_at(zman, 2) == 1) // need to round up.\n            {\n                if(bit_at(zman, 1) == 0 && bit_at(zman, 0) == 0) // to even\n                {\n                    if(bit_at(zman, 3) == 0)\n                    {\n                        // already even. do nothing.\n                    }\n                    else\n                    {\n                        zman += 0b1000;\n                    }\n                }\n                else // to nearest (upper)\n                {\n                    zman += 0b1000;\n                }\n            }\n            // check carry-up by rounding.\n            if(bit_at(zman, 27) == 1)\n            {\n                zexp  += 1;\n                zman >>= 1;\n            }\n        }\n        assert(bit_at(zman, 26) == 1); // normalized?\n\n        if(zexp == 0b1111'1111)\n        {\n            // it was not nan, so here it should be inf\n            zman = 0;\n        }\n        return float32(zsgn, zexp, std::uint32_t(bit_proxy(zman, 25, 3)));\n    }\n}\n\n#ifdef FLEMU_ACTIVATE_UNIT_TESTS\ninline boost::ut::suite tests_adder = []\n{\n    using namespace boost::ut::literals;\n\n    \"add(float32, float32)\"_test = []\n    {\n        const auto x1 = to_flemu(1.0f);\n        const auto y1 = to_flemu(1.0f);\n        const auto z1 = add(x1, y1);\n\n        boost::ut::expect(to_float(z1) == 2.0f);\n\n//         std::cout << to_float(x1) << \" + \" << to_float(y1) << \" = \" << to_float(z1) << \" != 2.0f\"<< std::endl;\n//         std::cout << z1.sign() << \"|\" << z1.exponent() << \"|\" << z1.mantissa() << std::endl;\n//         std::cout << \"========================================================================\" << std::endl;\n\n        const auto x2 = to_flemu( 1.0f);\n        const auto y2 = to_flemu(10.0f);\n        const auto z2 = add(x2, y2);\n\n        boost::ut::expect(to_float(z2) == 11.0f);\n\n//         std::cout << to_float(x2) << \" + \" << to_float(y2) << \" = \" << to_float(z2) << \" != 11.0f\"<< std::endl;\n//         std::cout << z2.sign() << \"|\" << z2.exponent() << \"|\" << z2.mantissa() << std::endl;\n//         std::cout << \"========================================================================\" << std::endl;\n\n        const auto x3 = to_flemu(1.0e-30f);\n        const auto y3 = to_flemu(1.0e+30f);\n        const auto z3 = add(x3, y3);\n\n        boost::ut::expect(to_float(z3) == 1.0e+30f);\n\n//         std::cout << to_float(x3) << \" + \" << to_float(y3) << \" = \" << to_float(z3) << \" != 1.0e+30f\"<< std::endl;\n//         std::cout << z3.sign() << \"|\" << z3.exponent() << \"|\" << z3.mantissa() << std::endl;\n//         std::cout << \"========================================================================\" << std::endl;\n\n        std::mt19937 rng(123456789);\n\n        std::uniform_int_distribution<std::uint32_t> sgn(0,   1);\n        std::uniform_int_distribution<std::uint32_t> exp(0, 255); // not including denormalized\n        std::uniform_int_distribution<std::uint32_t> man(0, 0x007F'FFFF);\n\n        const std::size_t N = 10000;\n        for(std::size_t i=0; i<N; ++i)\n        {\n            const std::uint32_t xi = (sgn(rng) << 31) + (exp(rng) << 23) + man(rng);\n            const std::uint32_t yi = (sgn(rng) << 31) + (exp(rng) << 23) + man(rng);\n//             const std::uint32_t xi = (0 << 31) + (exp(rng) << 23) + man(rng);\n//             const std::uint32_t yi = (0 << 31) + (exp(rng) << 23) + man(rng);\n//             const std::uint32_t xi = 0b1101'1100'0000'1001'0010'1110'0100'0000;\n//             const std::uint32_t yi = 0b1101'1010'0011'0100'0101'1100'0010'1001;\n//             const std::uint32_t xi = 0b1100'1101'1111'1110'1111'1100'1100'1101;\n//             const std::uint32_t yi = 0b1100'1011'0010'1101'1011'0101'0000'0100;\n\n            boost::ut::log << \"----------------------------------------------\";\n            boost::ut::log << \"     sxxx'xxxx'xmmm'mmmm'mmmm'mmmm'mmmm'mmmm\";\n            boost::ut::log << \"xr =\" << as_bit(xi);\n            boost::ut::log << \"yr =\" << as_bit(yi);\n\n            const float xr = bit_cast<float>(xi);\n            const float yr = bit_cast<float>(yi);\n            const float zr = xr + yr;\n\n            boost::ut::log << \"zr =\" << as_bit(bit_cast<std::uint32_t>(zr));\n\n            const auto x = to_flemu(xr);\n            const auto y = to_flemu(yr);\n            const auto z = add(x, y);\n\n            boost::ut::log << \"z  =\" << as_bit(z.base());\n\n            if(z.is_nan())\n            {\n                boost::ut::expect(std::isnan(zr))\n                    << \"z = \" << as_bit(z.base()) << \" is NaN but \"\n                    << \"zr = \" << as_bit(bit_cast<std::uint32_t>(zr)) << \" is not nan\";\n            }\n            else\n            {\n                boost::ut::expect(to_float(z) == zr)\n                    << as_bit(z.base()) << \" != \" << as_bit(bit_cast<std::uint32_t>(zr));\n            }\n        }\n    };\n};\n#endif\n\n\n\n} // flemu\n#endif // FLEMU_ADDER_HPP\n", "meta": {"hexsha": "b9bf7a6908e34ce40b868d68c6ebf615b83563b7", "size": 13552, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/flemu/adder.hpp", "max_stars_repo_name": "ToruNiina/flemu", "max_stars_repo_head_hexsha": "70d98c224b6746aaa75740b3065031009d155153", "max_stars_repo_licenses": ["MIT"], "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/flemu/adder.hpp", "max_issues_repo_name": "ToruNiina/flemu", "max_issues_repo_head_hexsha": "70d98c224b6746aaa75740b3065031009d155153", "max_issues_repo_licenses": ["MIT"], "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/flemu/adder.hpp", "max_forks_repo_name": "ToruNiina/flemu", "max_forks_repo_head_hexsha": "70d98c224b6746aaa75740b3065031009d155153", "max_forks_repo_licenses": ["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.8870588235, "max_line_length": 117, "alphanum_fraction": 0.4030401417, "num_tokens": 3914, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289836, "lm_q2_score": 0.6334102567576902, "lm_q1q2_score": 0.48180393208880096}}
{"text": "#include <scitbx/array_family/boost_python/flex_fwd.h>\n\n#include <boost/python/class.hpp>\n#include <scitbx/math/quadrature.h>\n#include <scitbx/boost_python/iterator_wrappers.h>\n\nnamespace scitbx { namespace math {\n\nnamespace {\n\n\n  struct gauss_legendre_engine_wrappers\n  {\n    typedef scitbx::math::quadrature::gauss_legendre_engine<double> w_t;\n\n    static void\n    wrap()\n    {\n      using namespace boost::python;\n      class_<w_t>(\"gauss_legendre_engine\",no_init)\n        .def(init<int const& > ((arg(\"n_points\"))))\n        .def(\"f\", &w_t::f)\n        .def(\"refine\", &w_t::refine)\n        .def(\"x\", &w_t::x)\n        .def(\"w\", &w_t::w)\n        ;\n    }\n  };\n\n\n  struct gauss_hermite_engine_wrappers\n  {\n    typedef scitbx::math::quadrature::gauss_hermite_engine<double> w_t;\n\n    static void\n    wrap()\n    {\n      using namespace boost::python;\n      class_<w_t>(\"gauss_hermite_engine\",no_init)\n        .def(init<int const& > ((arg(\"n_points\"))))\n        .def(\"f\", &w_t::f)\n        .def(\"refine\", &w_t::refine)\n        .def(\"x\", &w_t::x)\n        .def(\"w\", &w_t::w)\n        .def(\"w_exp_x_squared\", &w_t::w_exp_x_squared)\n        ;\n    }\n  };\n\n  struct seven_twelve_0120_wrappers\n  {\n    typedef scitbx::math::quadrature::seven_twelve_0120<double> w_t;\n\n    static void\n    wrap()\n    {\n      using namespace boost::python;\n      class_<w_t>(\"seven_twelve_0120\",no_init)\n        .def(init<> () )\n        .def(\"coord\", &w_t::coord)\n        .def(\"weight\", &w_t::weight)\n        ;\n    }\n  };\n\n\n  struct five_nine_1001_wrappers\n  {\n    typedef scitbx::math::quadrature::five_nine_1001<double> w_t;\n\n    static void\n    wrap()\n    {\n      using namespace boost::python;\n      class_<w_t>(\"five_nine_1001\",no_init)\n        .def(init<> () )\n        .def(\"coord\", &w_t::coord)\n        .def(\"weight\", &w_t::weight)\n        ;\n    }\n  };\n\n\n  struct five_nine_1110_wrappers\n  {\n    typedef scitbx::math::quadrature::five_nine_1110<double> w_t;\n\n    static void\n    wrap()\n    {\n      using namespace boost::python;\n      class_<w_t>(\"five_nine_1110\",no_init)\n        .def(init<> () )\n        .def(\"coord\", &w_t::coord)\n        .def(\"weight\", &w_t::weight)\n        ;\n    }\n  };\n\n\n  struct nine_twentyone_1012_wrappers\n  {\n    typedef scitbx::math::quadrature::nine_twentyone_1012<double> w_t;\n\n    static void\n    wrap()\n    {\n      using namespace boost::python;\n      class_<w_t>(\"nine_twentyone_1012\",no_init)\n        .def(init<> () )\n        .def(\"coord\", &w_t::coord)\n        .def(\"weight\", &w_t::weight)\n        ;\n    }\n  };\n\n\n\n\n} // namespace <anonymous>\n\nnamespace boost_python {\n\n  void wrap_quadrature()\n  {\n    gauss_legendre_engine_wrappers::wrap();\n    gauss_hermite_engine_wrappers::wrap();\n    seven_twelve_0120_wrappers::wrap();\n    five_nine_1001_wrappers::wrap();\n    five_nine_1110_wrappers::wrap();\n    nine_twentyone_1012_wrappers::wrap();\n  }\n\n}}} // namespace scitbx::math::boost_python\n", "meta": {"hexsha": "f3b1ddf1ddc669166908ef2a5d207f79345e63fa", "size": 2897, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "scitbx/math/boost_python/quadrature.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/quadrature.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/quadrature.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": 21.4592592593, "max_line_length": 72, "alphanum_fraction": 0.6002761477, "num_tokens": 873, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.4818039304790424}}
{"text": "/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2015 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\n#ifndef MAPNIK_IMAGE_FILTER_HPP\n#define MAPNIK_IMAGE_FILTER_HPP\n\n//mapnik\n#include <mapnik/image_filter_types.hpp>\n#include <mapnik/image_util.hpp>\n#include <mapnik/util/hsl.hpp>\n\n#pragma GCC diagnostic push\n#include <mapnik/warning_ignore.hpp>\n#include <boost/gil/gil_all.hpp>\n#pragma GCC diagnostic pop\n\n#pragma GCC diagnostic push\n#include <mapnik/warning_ignore_agg.hpp>\n#include \"agg_basics.h\"\n#include \"agg_rendering_buffer.h\"\n#include \"agg_color_rgba.h\"\n#include \"agg_pixfmt_rgba.h\"\n#include \"agg_scanline_u.h\"\n#include \"agg_blur.h\"\n#include \"agg_gradient_lut.h\"\n#pragma GCC diagnostic pop\n\n// stl\n#include <cmath>\n\n// 8-bit YUV\n//Y = ( (  66 * R + 129 * G +  25 * B + 128) >> 8) +  16\n//U = ( ( -38 * R -  74 * G + 112 * B + 128) >> 8) + 128\n//V = ( ( 112 * R -  94 * G -  18 * B + 128) >> 8) + 128\n\n//bits_type x_gradient = (0.125f*c2 + 0.25f*c5 + 0.125f*c8)\n//    - (0.125f*c0 + 0.25f*c3 + 0.125f*c6);\n//bits_type y_gradient = (0.125f*c0 + 0.25f*c1 + 0.125f*c2)\n//    - (0.125f*c6 + 0.25f*c7 + 0.125f*c8);\n\n// c0 c1 c2\n// c3 c4 c5\n// c6 c7 c8\n\n//sharpen\n//  0 -1  0\n// -1  5 -1\n//  0 -1  0\n//bits_type out_value = -c1 - c3 + 5.0*c4 - c5 - c7;\n\n// edge detect\n//  0  1  0\n//  1 -4  1\n//  0  1  0\n//bits_type out_value = c1 + c3 - 4.0*c4 + c5 + c7;\n\n//\n//if (out_value < 0) out_value = 0;\n//if (out_value > 255) out_value = 255;\n\n// emboss\n// -2 -1  0\n// -1  1  1\n//  0  1  2\n\n// bits_type out_value = -2*c0 - c1 - c3 + c4 + c5 + c7 +  2*c8;\n\n// blur\n//float out_value = (0.1f*c0 + 0.1f*c1 + 0.1f*c2 +\n//                   0.1f*c3 + 0.1f*c4 + 0.1f*c5 +\n//                  0.1f*c6 + 0.1f*c7 + 0.1f*c8);\n\n\n//float out_value  = std::sqrt(std::pow(x_gradient,2) + std::pow(y_gradient,2));\n//float theta = std::atan2(x_gradient,y_gradient);\n//if (out_value < 0.0) out_value = 0.0;\n//if (out_value < 1.0) out_value = 1.0;\n\n\n\n\n//float conv_matrix[]={1/3.0,1/3.0,1/3.0};\n\n//float gaussian_1[]={0.00022923296f,0.0059770769f,0.060597949f,0.24173197f,0.38292751f,\n//                    0.24173197f,0.060597949f,0.0059770769f,0.00022923296f};\n\n//float gaussian_2[]={\n//    0.00048869418f,0.0024031631f,0.0092463447f,\n//   0.027839607f,0.065602221f,0.12099898f,0.17469721f,\n//   0.19744757f,\n//   0.17469721f,0.12099898f,0.065602221f,0.027839607f,\n//   0.0092463447f,0.0024031631f,0.00048869418f\n//};\n\n//  kernel_1d_fixed<float,9> kernel(conv,4);\n\n// color_converted_view<rgb8_pixel_t>(src_view);\n//using view_t = kth_channel_view_type< 0, const rgba8_view_t>::type;\n\n//view_t red = kth_channel_view<0>(const_view(src_view));\n\n//kernel_1d_fixed<float,3> kernel(sharpen,0);\n//convolve_rows_fixed<rgba32f_pixel_t>(src_view,kernel,src_view);\n// convolve_cols_fixed<rgba32f_pixel_t>(src_view,kernel,dst_view);\n\nnamespace mapnik {  namespace filter { namespace detail {\n\nstatic const float blur_matrix[] = {0.1111f,0.1111f,0.1111f,0.1111f,0.1111f,0.1111f,0.1111f,0.1111f,0.1111f};\nstatic const float emboss_matrix[] = {-2,-1,0,-1,1,1,0,1,2};\nstatic const float sharpen_matrix[] = {0,-1,0,-1,5,-1,0,-1,0 };\nstatic const float edge_detect_matrix[] = {0,1,0,1,-4,1,0,1,0 };\n\n}\n\nusing boost::gil::rgba8_image_t;\nusing boost::gil::rgba8_view_t;\n\ntemplate <typename Image>\nboost::gil::rgba8_view_t rgba8_view(Image & img)\n{\n    using boost::gil::interleaved_view;\n    using boost::gil::rgba8_pixel_t;\n    return interleaved_view(img.width(), img.height(),\n                            reinterpret_cast<rgba8_pixel_t*>(img.bytes()),\n                            img.width() * sizeof(rgba8_pixel_t));\n}\n\ntemplate <typename Image>\nstruct double_buffer\n{\n    boost::gil::rgba8_image_t   dst_buffer;\n    boost::gil::rgba8_view_t    dst_view;\n    boost::gil::rgba8_view_t    src_view;\n\n    explicit double_buffer(Image & src)\n        : dst_buffer(src.width(), src.height())\n        , dst_view(view(dst_buffer))\n        , src_view(rgba8_view(src)) {}\n\n    ~double_buffer()\n    {\n        copy_pixels(dst_view, src_view);\n    }\n};\n\ntemplate <typename Src, typename Dst, typename Conv>\nvoid process_channel_impl (Src const& src, Dst & dst, Conv const& k)\n{\n    using boost::gil::bits32f;\n\n    bits32f out_value =\n        k[0]*src[0] + k[1]*src[1] + k[2]*src[2] +\n        k[3]*src[3] + k[4]*src[4] + k[5]*src[5] +\n        k[6]*src[6] + k[7]*src[7] + k[8]*src[8]\n        ;\n    if (out_value < 0) out_value = 0;\n    if (out_value > 255) out_value = 255;\n    dst = out_value;\n}\n\ntemplate <typename Src, typename Dst, typename Conv>\nvoid process_channel (Src const&, Dst &, Conv const&)\n{\n}\n\ntemplate <typename Src, typename Dst>\nvoid process_channel (Src const& src, Dst & dst, mapnik::filter::blur)\n{\n    process_channel_impl(src,dst,mapnik::filter::detail::blur_matrix);\n}\n\ntemplate <typename Src, typename Dst>\nvoid process_channel (Src const& src, Dst & dst, mapnik::filter::emboss)\n{\n    process_channel_impl(src,dst,mapnik::filter::detail::emboss_matrix);\n}\n\ntemplate <typename Src, typename Dst>\nvoid process_channel (Src const& src, Dst & dst, mapnik::filter::sharpen)\n{\n    process_channel_impl(src,dst,mapnik::filter::detail::sharpen_matrix);\n}\n\ntemplate <typename Src, typename Dst>\nvoid process_channel (Src const& src, Dst & dst, mapnik::filter::edge_detect)\n{\n    process_channel_impl(src,dst,mapnik::filter::detail::edge_detect_matrix);\n}\n\n\ntemplate <typename Src, typename Dst>\nvoid process_channel (Src const& src, Dst & dst, mapnik::filter::sobel)\n{\n    using boost::gil::bits32f;\n\n    bits32f x_gradient = (src[2] + 2*src[5] + src[8])\n        - (src[0] + 2*src[3] + src[6]);\n\n    bits32f y_gradient = (src[0] + 2*src[1] + src[2])\n        - (src[6] + 2*src[7] + src[8]);\n\n    bits32f  out_value  = std::sqrt(std::pow(x_gradient,2) + std::pow(y_gradient,2));\n    //bts32f theta = std::atan2(x_gradient,y_gradient);\n    if (out_value < 0) out_value = 0;\n    if (out_value > 255) out_value = 255;\n    dst = out_value;\n}\n\n\n\ntemplate <typename Src, typename Dst, typename Filter>\nvoid apply_convolution_3x3(Src const& src_view, Dst & dst_view, Filter const& filter)\n{\n    using boost::gil::bits32f;\n    using boost::gil::point2;\n\n    // p0 p1 p2\n    // p3 p4 p5\n    // p6 p7 p8\n\n    typename Src::xy_locator src_loc = src_view.xy_at(0,0);\n    typename Src::xy_locator::cached_location_t loc00 = src_loc.cache_location(-1,-1);\n    typename Src::xy_locator::cached_location_t loc10 = src_loc.cache_location( 0,-1);\n    typename Src::xy_locator::cached_location_t loc20 = src_loc.cache_location( 1,-1);\n    typename Src::xy_locator::cached_location_t loc01 = src_loc.cache_location(-1, 0);\n    typename Src::xy_locator::cached_location_t loc11 = src_loc.cache_location( 0, 0);\n    typename Src::xy_locator::cached_location_t loc21 = src_loc.cache_location( 1, 0);\n    typename Src::xy_locator::cached_location_t loc02 = src_loc.cache_location(-1, 1);\n    typename Src::xy_locator::cached_location_t loc12 = src_loc.cache_location( 0, 1);\n    typename Src::xy_locator::cached_location_t loc22 = src_loc.cache_location( 1, 1);\n\n    typename Src::x_iterator dst_it = dst_view.row_begin(0);\n\n    // top row\n    for (std::ptrdiff_t x = 0 ; x < src_view.width(); ++x)\n    {\n        (*dst_it)[3] = src_loc[loc11][3]; // Dst.a = Src.a\n        for (std::ptrdiff_t i = 0; i < 3; ++i)\n        {\n            bits32f p[9];\n\n            p[4] = src_loc[loc11][i];\n            p[7] = src_loc[loc12][i];\n\n            if (x == 0)\n            {\n                p[3] = p[4];\n                p[6] = p[7];\n            }\n            else\n            {\n                p[3] = src_loc[loc01][i];\n                p[6] = src_loc[loc02][i];\n            }\n\n            if ( x == (src_view.width())-1)\n            {\n                p[5] = p[4];\n                p[8] = p[7];\n            }\n            else\n            {\n                p[5] = src_loc[loc21][i];\n                p[8] = src_loc[loc22][i];\n            }\n\n            p[0] = p[6];\n            p[1] = p[7];\n            p[2] = p[8];\n\n            process_channel(p, (*dst_it)[i], filter);\n        }\n        ++src_loc.x();\n        ++dst_it;\n    }\n    // carrige-return\n    src_loc += point2<std::ptrdiff_t>(-src_view.width(),1);\n\n    // 1... height-1 rows\n    for (std::ptrdiff_t y = 1; y < src_view.height()-1; ++y)\n    {\n        for (std::ptrdiff_t x = 0; x < src_view.width(); ++x)\n        {\n            (*dst_it)[3] = src_loc[loc11][3]; // Dst.a = Src.a\n            for (std::ptrdiff_t i = 0; i < 3; ++i)\n            {\n                bits32f p[9];\n\n                p[1] = src_loc[loc10][i];\n                p[4] = src_loc[loc11][i];\n                p[7] = src_loc[loc12][i];\n\n                if (x == 0)\n                {\n                    p[0] = p[1];\n                    p[3] = p[4];\n                    p[6] = p[7];\n                }\n                else\n                {\n                    p[0] = src_loc[loc00][i];\n                    p[3] = src_loc[loc01][i];\n                    p[6] = src_loc[loc02][i];\n                }\n\n                if ( x == (src_view.width()) - 1)\n                {\n                    p[2] = p[1];\n                    p[5] = p[4];\n                    p[8] = p[7];\n                }\n                else\n                {\n                    p[2] = src_loc[loc20][i];\n                    p[5] = src_loc[loc21][i];\n                    p[8] = src_loc[loc22][i];\n                }\n                process_channel(p, (*dst_it)[i], filter);\n            }\n            ++dst_it;\n            ++src_loc.x();\n        }\n        // carrige-return\n        src_loc += point2<std::ptrdiff_t>(-src_view.width(),1);\n    }\n\n    // bottom row\n    //src_loc = src_view.xy_at(0,src_view.height()-1);\n    for (std::ptrdiff_t x = 0 ; x < src_view.width(); ++x)\n    {\n        (*dst_it)[3] = src_loc[loc11][3]; // Dst.a = Src.a\n        for (std::ptrdiff_t i = 0; i < 3; ++i)\n        {\n            bits32f p[9];\n\n            p[1] = src_loc[loc10][i];\n            p[4] = src_loc[loc11][i];\n\n            if (x == 0)\n            {\n                p[0] = p[1];\n                p[3] = p[4];\n            }\n            else\n            {\n                p[0] = src_loc[loc00][i];\n                p[3] = src_loc[loc01][i];\n            }\n\n            if ( x == (src_view.width())-1)\n            {\n                p[2] = p[1];\n                p[5] = p[4];\n\n            }\n            else\n            {\n                p[2] = src_loc[loc20][i];\n                p[5] = src_loc[loc21][i];\n            }\n\n            p[6] = p[0];\n            p[7] = p[1];\n            p[8] = p[2];\n            process_channel(p, (*dst_it)[i], filter);\n        }\n        ++src_loc.x();\n        ++dst_it;\n    }\n}\n\ntemplate <typename Src, typename Filter>\nvoid apply_filter(Src & src, Filter const& filter, double /*scale_factor*/)\n{\n    demultiply_alpha(src);\n    double_buffer<Src> tb(src);\n    apply_convolution_3x3(tb.src_view, tb.dst_view, filter);\n}\n\ntemplate <typename Src>\nvoid apply_filter(Src & src, agg_stack_blur const& op, double scale_factor)\n{\n    premultiply_alpha(src);\n    agg::rendering_buffer buf(src.bytes(),src.width(),src.height(), src.row_size());\n    agg::pixfmt_rgba32_pre pixf(buf);\n    agg::stack_blur_rgba32(pixf, op.rx * scale_factor, op.ry * scale_factor);\n}\n\ninline double channel_delta(double source, double match)\n{\n    if (source > match) return (source - match) / (1.0 - match);\n    if (source < match) return (match - source) / match;\n    return (source - match);\n}\n\ninline uint8_t apply_alpha_shift(double source, double match, double alpha)\n{\n    source = (((source - match) / alpha) + match) * alpha;\n    return static_cast<uint8_t>(std::floor((source*255.0)+.5));\n}\n\ntemplate <typename Src>\nvoid apply_filter(Src & src, color_to_alpha const& op, double /*scale_factor*/)\n{\n    using namespace boost::gil;\n    bool premultiplied = src.get_premultiplied();\n    rgba8_view_t src_view = rgba8_view(src);\n    double cr = static_cast<double>(op.color.red())/255.0;\n    double cg = static_cast<double>(op.color.green())/255.0;\n    double cb = static_cast<double>(op.color.blue())/255.0;\n    for (std::ptrdiff_t y = 0; y < src_view.height(); ++y)\n    {\n        rgba8_view_t::x_iterator src_it = src_view.row_begin(static_cast<long>(y));\n        for (std::ptrdiff_t x = 0; x < src_view.width(); ++x)\n        {\n            uint8_t & r = get_color(src_it[x], red_t());\n            uint8_t & g = get_color(src_it[x], green_t());\n            uint8_t & b = get_color(src_it[x], blue_t());\n            uint8_t & a = get_color(src_it[x], alpha_t());\n            double sr = static_cast<double>(r)/255.0;\n            double sg = static_cast<double>(g)/255.0;\n            double sb = static_cast<double>(b)/255.0;\n            double sa = static_cast<double>(a)/255.0;\n            // demultiply\n            if (sa <= 0.0)\n            {\n                r = g = b = 0;\n                continue;\n            }\n            else if (premultiplied)\n            {\n                sr /= sa;\n                sg /= sa;\n                sb /= sa;\n            }\n            // get that maximum color difference\n            double xa = std::max(channel_delta(sr,cr),std::max(channel_delta(sg,cg),channel_delta(sb,cb)));\n            if (xa > 0)\n            {\n                // apply difference to each channel, returning premultiplied\n                // TODO - experiment with difference in hsl color space\n                r = apply_alpha_shift(sr,cr,xa);\n                g = apply_alpha_shift(sg,cg,xa);\n                b = apply_alpha_shift(sb,cb,xa);\n                // combine new alpha with original\n                xa *= sa;\n                a = static_cast<uint8_t>(std::floor((xa*255.0)+.5));\n                // all color values must be <= alpha\n                if (r>a) r=a;\n                if (g>a) g=a;\n                if (b>a) b=a;\n            }\n            else\n            {\n                r = g = b = a = 0;\n            }\n        }\n    }\n    // set as premultiplied\n    set_premultiplied_alpha(src, true);\n}\n\ntemplate <typename Src>\nvoid apply_filter(Src & src, colorize_alpha const& op, double /*scale_factor*/)\n{\n    using namespace boost::gil;\n    std::ptrdiff_t size = op.size();\n    if (op.size() == 1)\n    {\n        // no interpolation if only one stop\n        mapnik::filter::color_stop const& stop = op[0];\n        mapnik::color const& c = stop.color;\n        rgba8_view_t src_view = rgba8_view(src);\n        for (std::ptrdiff_t y = 0; y < src_view.height(); ++y)\n        {\n            rgba8_view_t::x_iterator src_it = src_view.row_begin(static_cast<long>(y));\n            for (std::ptrdiff_t x = 0; x < src_view.width(); ++x)\n            {\n                uint8_t & r = get_color(src_it[x], red_t());\n                uint8_t & g = get_color(src_it[x], green_t());\n                uint8_t & b = get_color(src_it[x], blue_t());\n                uint8_t & a = get_color(src_it[x], alpha_t());\n                if ( a > 0)\n                {\n                    a = (c.alpha() * a + 255) >> 8;\n                    r = (c.red() * a + 255) >> 8;\n                    g = (c.green() * a + 255) >> 8;\n                    b = (c.blue() * a + 255) >> 8;\n                }\n            }\n        }\n        // set as premultiplied\n        set_premultiplied_alpha(src, true);\n    }\n    else if (size > 1)\n    {\n        // interpolate multiple stops\n        agg::gradient_lut<agg::color_interpolator<agg::rgba8> > grad_lut;\n        double step = 1.0/(size-1);\n        double offset = 0.0;\n        for ( mapnik::filter::color_stop const& stop : op)\n        {\n            mapnik::color const& c = stop.color;\n            double stop_offset = stop.offset;\n            if (stop_offset == 0)\n            {\n                stop_offset = offset;\n            }\n            grad_lut.add_color(stop_offset, agg::rgba(c.red()/255.0,\n                                                      c.green()/255.0,\n                                                      c.blue()/255.0,\n                                                      c.alpha()/255.0));\n            offset += step;\n        }\n        if (grad_lut.build_lut())\n        {\n            rgba8_view_t src_view = rgba8_view(src);\n            for (std::ptrdiff_t y = 0; y < src_view.height(); ++y)\n            {\n                rgba8_view_t::x_iterator src_it = src_view.row_begin(static_cast<long>(y));\n                for (std::ptrdiff_t x = 0; x < src_view.width(); ++x)\n                {\n                    uint8_t & r = get_color(src_it[x], red_t());\n                    uint8_t & g = get_color(src_it[x], green_t());\n                    uint8_t & b = get_color(src_it[x], blue_t());\n                    uint8_t & a = get_color(src_it[x], alpha_t());\n                    if ( a > 0)\n                    {\n                        agg::rgba8 c = grad_lut[a];\n                        a = (c.a * a + 255) >> 8;\n                        r = (c.r * a + 255) >> 8;\n                        g = (c.g * a + 255) >> 8;\n                        b = (c.b * a + 255) >> 8;\n        #if 0\n                        // rainbow\n                        r = 0;\n                        g = 0;\n                        b = 0;\n                        if (a < 64)\n                        {\n                            g = a * 4;\n                            b = 255;\n                        }\n                        else if (a >= 64 && a < 128)\n                        {\n                            g = 255;\n                            b = 255 - ((a - 64) * 4);\n                        }\n                        else if (a >= 128 && a < 192)\n                        {\n                            r = (a - 128) * 4;\n                            g = 255;\n                        }\n                        else // >= 192\n                        {\n                            r = 255;\n                            g = 255 - ((a - 192) * 4);\n                        }\n                        r = (r * a + 255) >> 8;\n                        g = (g * a + 255) >> 8;\n                        b = (b * a + 255) >> 8;\n        #endif\n                    }\n                }\n            }\n        }\n        // set as premultiplied\n        set_premultiplied_alpha(src, true);\n    }\n}\n\ntemplate <typename Src>\nvoid apply_filter(Src & src, scale_hsla const& transform, double /*scale_factor*/)\n{\n    using namespace boost::gil;\n    bool tinting = !transform.is_identity();\n    bool set_alpha = !transform.is_alpha_identity();\n    // todo - filters be able to report if they\n    // should be run to avoid overhead of temp buffer\n    if (tinting || set_alpha)\n    {\n        bool premultiplied = src.get_premultiplied();\n        rgba8_view_t src_view = rgba8_view(src);\n        for (std::ptrdiff_t y = 0; y < src_view.height(); ++y)\n        {\n            rgba8_view_t::x_iterator src_it = src_view.row_begin(static_cast<long>(y));\n            for (std::ptrdiff_t x = 0; x < src_view.width(); ++x)\n            {\n                uint8_t & r = get_color(src_it[x], red_t());\n                uint8_t & g = get_color(src_it[x], green_t());\n                uint8_t & b = get_color(src_it[x], blue_t());\n                uint8_t & a = get_color(src_it[x], alpha_t());\n                double r2 = static_cast<double>(r)/255.0;\n                double g2 = static_cast<double>(g)/255.0;\n                double b2 = static_cast<double>(b)/255.0;\n                double a2 = static_cast<double>(a)/255.0;\n                // demultiply\n                if (a2 <= 0.0)\n                {\n                    r = g = b = 0;\n                    continue;\n                }\n                else if (premultiplied)\n                {\n                    r2 /= a2;\n                    g2 /= a2;\n                    b2 /= a2;\n                }\n\n                if (set_alpha)\n                {\n                    a2 = transform.a0 + (a2 * (transform.a1 - transform.a0));\n                    if (a2 <= 0)\n                    {\n                        r = g = b = a = 0;\n                        continue;\n                    }\n                    else if (a2 > 1)\n                    {\n                        a2 = 1;\n                        a = 255;\n                    }\n                    else\n                    {\n                        a = static_cast<uint8_t>(std::floor((a2 * 255.0) +.5));\n                    }\n                }\n                if (tinting)\n                {\n                    double h;\n                    double s;\n                    double l;\n                    rgb2hsl(r2,g2,b2,h,s,l);\n                    double h2 = transform.h0 + (h * (transform.h1 - transform.h0));\n                    double s2 = transform.s0 + (s * (transform.s1 - transform.s0));\n                    double l2 = transform.l0 + (l * (transform.l1 - transform.l0));\n                    if (h2 > 1) { h2 = 1; }\n                    else if (h2 < 0) { h2 = 0; }\n                    if (s2 > 1) { s2 = 1; }\n                    else if (s2 < 0) { s2 = 0; }\n                    if (l2 > 1) { l2 = 1; }\n                    else if (l2 < 0) { l2 = 0; }\n                    hsl2rgb(h2,s2,l2,r2,g2,b2);\n                }\n                // premultiply\n                r2 *= a2;\n                g2 *= a2;\n                b2 *= a2;\n                r = static_cast<uint8_t>(std::floor((r2*255.0)+.5));\n                g = static_cast<uint8_t>(std::floor((g2*255.0)+.5));\n                b = static_cast<uint8_t>(std::floor((b2*255.0)+.5));\n                // all color values must be <= alpha\n                if (r>a) r=a;\n                if (g>a) g=a;\n                if (b>a) b=a;\n            }\n        }\n        // set as premultiplied\n        set_premultiplied_alpha(src, true);\n    }\n}\n\ntemplate <typename Src, typename ColorBlindFilter>\nvoid color_blind_filter(Src & src, ColorBlindFilter const& op)\n{\n    using namespace boost::gil;\n    rgba8_view_t src_view = rgba8_view(src);\n    bool premultiplied = src.get_premultiplied();\n\n    for (std::ptrdiff_t y = 0; y < src_view.height(); ++y)\n    {\n        rgba8_view_t::x_iterator src_it = src_view.row_begin(static_cast<long>(y));\n        for (std::ptrdiff_t x = 0; x < src_view.width(); ++x)\n        {\n            // formula taken from boost/gil/color_convert.hpp:rgb_to_luminance\n            uint8_t & r = get_color(src_it[x], red_t());\n            uint8_t & g = get_color(src_it[x], green_t());\n            uint8_t & b = get_color(src_it[x], blue_t());\n            uint8_t & a = get_color(src_it[x], alpha_t());\n            double dr = static_cast<double>(r)/255.0;\n            double dg = static_cast<double>(g)/255.0;\n            double db = static_cast<double>(b)/255.0;\n            double da = static_cast<double>(a)/255.0;\n            // demultiply\n            if (da <= 0.0)\n            {\n                r = g = b = 0;\n                continue;\n            }\n            else if (premultiplied)\n            {\n                dr /= da;\n                dg /= da;\n                db /= da;\n            }\n            // Convert source color into XYZ color space\n            double pow_r = std::pow(dr, 2.2);\n            double pow_g = std::pow(dg, 2.2);\n            double pow_b = std::pow(db, 2.2);\n            double X = (0.412424 * pow_r) + (0.357579 * pow_g) + (0.180464 * pow_b);\n            double Y = (0.212656 * pow_r) + (0.715158 * pow_g) + (0.0721856 * pow_b);\n            double Z = (0.0193324 * pow_r) + (0.119193 * pow_g) + (0.950444 * pow_b);\n            // Convert XYZ into xyY Chromacity Coordinates (xy) and Luminance (Y)\n            double chroma_x = X / (X + Y + Z);\n            double chroma_y = Y / (X + Y + Z);\n            // Generate the \"Confusion Line\" between the source color and the Confusion Point\n            double m_div = chroma_x - op.x;\n            if (std::abs(m_div) < (std::numeric_limits<double>::epsilon())) continue;\n            double m = (chroma_y - op.y) / (chroma_x - op.x); // slope of Confusion Line\n            double yint = chroma_y - chroma_x * m; // y-intercept of confusion line (x-intercept = 0.0)\n            // How far the xy coords deviate from the simulation\n            double m_div2 = m - op.m;\n            if (std::abs(m_div2) < (std::numeric_limits<double>::epsilon())) continue;\n            double deviate_x = (op.yint - yint) / (m - op.m);\n            double deviate_y = (m * deviate_x) + yint;\n            if (std::abs(deviate_y) < (std::numeric_limits<double>::epsilon()))\n            {\n                deviate_y = std::numeric_limits<double>::epsilon() * 2.0;\n            }\n            // Compute the simulated color's XYZ coords\n            X = deviate_x * Y / deviate_y;\n            Z = (1.0 - (deviate_x + deviate_y)) * Y / deviate_y;\n            // Neutral grey calculated from luminance (in D65)\n            double neutral_X = 0.312713 * Y / 0.329016;\n            double neutral_Z = 0.358271 * Y / 0.329016;\n            // Difference between simulated color and neutral grey\n            double diff_X = neutral_X - X;\n            double diff_Z = neutral_Z - Z;\n            double diff_r = diff_X * 3.24071 + diff_Z * -0.498571; // XYZ->RGB (sRGB:D65)\n            double diff_g = diff_X * -0.969258 + diff_Z * 0.0415557;\n            double diff_b = diff_X * 0.0556352 + diff_Z * 1.05707;\n            if (std::abs(diff_r) < (std::numeric_limits<double>::epsilon()))\n            {\n                diff_r = std::numeric_limits<double>::epsilon() * 2.0;\n            }\n            if (std::abs(diff_g) < (std::numeric_limits<double>::epsilon()))\n            {\n                diff_g = std::numeric_limits<double>::epsilon() * 2.0;\n            }\n            if (std::abs(diff_b) < (std::numeric_limits<double>::epsilon()))\n            {\n                diff_b = std::numeric_limits<double>::epsilon() * 2.0;\n            }\n            // Convert to RGB color space\n            dr = X * 3.24071 + Y * -1.53726 + Z * -0.498571; // XYZ->RGB (sRGB:D65)\n            dg = X * -0.969258 + Y * 1.87599 + Z * 0.0415557;\n            db = X * 0.0556352 + Y * -0.203996 + Z * 1.05707;\n            // Compensate simulated color towards a neutral fit in RGB space\n            double fit_r = ((dr < 0.0 ? 0.0 : 1.0) - dr) / diff_r;\n            double fit_g = ((dg < 0.0 ? 0.0 : 1.0) - dg) / diff_g;\n            double fit_b = ((db < 0.0 ? 0.0 : 1.0) - db) / diff_b;\n            double adjust = std::max( (fit_r > 1.0 || fit_r < 0.0) ? 0.0 : fit_r,\n                                      (fit_g > 1.0 || fit_g < 0.0) ? 0.0 : fit_g\n                                    );\n            adjust = std::max((fit_b > 1.0 || fit_b < 0.0) ? 0.0 : fit_b, adjust);\n            // Shift proportional to the greatest shift\n            dr = dr + (adjust * diff_r);\n            dg = dg + (adjust * diff_g);\n            db = db + (adjust * diff_b);\n            // Apply gamma correction\n            dr = std::pow(dr, 1.0 / 2.2);\n            dg = std::pow(dg, 1.0 / 2.2);\n            db = std::pow(db, 1.0 / 2.2);\n            // premultiply\n            dr *= da;\n            dg *= da;\n            db *= da;\n            // Clamp values\n            if(dr < 0.0)  dr = 0.0;\n            if(dr > 1.0) dr = 1.0;\n            if(dg < 0.0) dg = 0.0;\n            if(dg > 1.0) dg = 1.0;\n            if(db < 0.0) db = 0.0;\n            if(db > 1.0) db = 1.0;\n            r = static_cast<uint8_t>(dr * 255.0);\n            g = static_cast<uint8_t>(dg * 255.0);\n            b = static_cast<uint8_t>(db * 255.0);\n        }\n    }\n    // set as premultiplied\n    set_premultiplied_alpha(src, true);\n}\n\ntemplate <typename Src>\nvoid apply_filter(Src & src, color_blind_protanope const& op, double /*scale_factor*/)\n{\n    color_blind_filter(src, op);\n}\n\ntemplate <typename Src>\nvoid apply_filter(Src & src, color_blind_deuteranope const& op, double /*scale_factor*/)\n{\n    color_blind_filter(src, op);\n}\n\ntemplate <typename Src>\nvoid apply_filter(Src & src, color_blind_tritanope const& op, double /*scale_factor*/)\n{\n    color_blind_filter(src, op);\n}\n\ntemplate <typename Src>\nvoid apply_filter(Src & src, gray const& /*op*/, double /*scale_factor*/)\n{\n    premultiply_alpha(src);\n    using namespace boost::gil;\n\n    rgba8_view_t src_view = rgba8_view(src);\n\n    for (std::ptrdiff_t y = 0; y < src_view.height(); ++y)\n    {\n        rgba8_view_t::x_iterator src_it = src_view.row_begin(static_cast<long>(y));\n        for (std::ptrdiff_t x = 0; x < src_view.width(); ++x)\n        {\n            // formula taken from boost/gil/color_convert.hpp:rgb_to_luminance\n            uint8_t & r = get_color(src_it[x], red_t());\n            uint8_t & g = get_color(src_it[x], green_t());\n            uint8_t & b = get_color(src_it[x], blue_t());\n            uint8_t   v = uint8_t((4915 * r + 9667 * g + 1802 * b + 8192) >> 14);\n            r = g = b = v;\n        }\n    }\n}\n\ntemplate <typename Src, typename Dst>\nvoid x_gradient_impl(Src const& src_view, Dst const& dst_view)\n{\n    for (std::ptrdiff_t y = 0; y < src_view.height(); ++y)\n    {\n        typename Src::x_iterator src_it = src_view.row_begin(static_cast<long>(y));\n        typename Dst::x_iterator dst_it = dst_view.row_begin(static_cast<long>(y));\n\n        dst_it[0][0] = 128 + (src_it[0][0] - src_it[1][0]) / 2;\n        dst_it[0][1] = 128 + (src_it[0][1] - src_it[1][1]) / 2;\n        dst_it[0][2] = 128 + (src_it[0][2] - src_it[1][2]) / 2;\n\n        dst_it[dst_view.width()-1][0] = 128 + (src_it[(src_view.width())-2][0] - src_it[(src_view.width())-1][0]) / 2;\n        dst_it[dst_view.width()-1][1] = 128 + (src_it[(src_view.width())-2][1] - src_it[(src_view.width())-1][1]) / 2;\n        dst_it[dst_view.width()-1][2] = 128 + (src_it[(src_view.width())-2][2] - src_it[(src_view.width())-1][2]) / 2;\n\n        dst_it[0][3] = dst_it[(src_view.width())-1][3] = 255;\n\n        for (std::ptrdiff_t x = 1; x < src_view.width()-1; ++x)\n        {\n            dst_it[x][0] = 128 + (src_it[x-1][0] - src_it[x+1][0]) / 2;\n            dst_it[x][1] = 128 + (src_it[x-1][1] - src_it[x+1][1]) / 2;\n            dst_it[x][2] = 128 + (src_it[x-1][2] - src_it[x+1][2]) / 2;\n            dst_it[x][3] = 255;\n        }\n    }\n}\n\ntemplate <typename Src>\nvoid apply_filter(Src & src, x_gradient const& /*op*/, double /*scale_factor*/)\n{\n    premultiply_alpha(src);\n    double_buffer<Src> tb(src);\n    x_gradient_impl(tb.src_view, tb.dst_view);\n}\n\ntemplate <typename Src>\nvoid apply_filter(Src & src, y_gradient const& /*op*/, double /*scale_factor*/)\n{\n    premultiply_alpha(src);\n    double_buffer<Src> tb(src);\n    x_gradient_impl(rotated90ccw_view(tb.src_view),\n                    rotated90ccw_view(tb.dst_view));\n}\n\ntemplate <typename Src>\nvoid apply_filter(Src & src, invert const& /*op*/, double /*scale_factor*/)\n{\n    premultiply_alpha(src);\n    using namespace boost::gil;\n\n    rgba8_view_t src_view = rgba8_view(src);\n\n    for (std::ptrdiff_t y = 0; y < src_view.height(); ++y)\n    {\n        rgba8_view_t::x_iterator src_it = src_view.row_begin(static_cast<long>(y));\n        for (std::ptrdiff_t x = 0; x < src_view.width(); ++x)\n        {\n            // we only work with premultiplied source,\n            // thus all color values must be <= alpha\n            uint8_t   a = get_color(src_it[x], alpha_t());\n            uint8_t & r = get_color(src_it[x], red_t());\n            uint8_t & g = get_color(src_it[x], green_t());\n            uint8_t & b = get_color(src_it[x], blue_t());\n            r = a - r;\n            g = a - g;\n            b = a - b;\n        }\n    }\n}\n\ntemplate <typename Src>\nstruct filter_visitor\n{\n    filter_visitor(Src & src, double scale_factor=1.0)\n    : src_(src),\n      scale_factor_(scale_factor) {}\n\n    template <typename T>\n    void operator () (T const& filter) const\n    {\n        apply_filter(src_, filter, scale_factor_);\n    }\n\n    Src & src_;\n    double scale_factor_;\n};\n\nstruct filter_radius_visitor\n{\n    int & radius_;\n    filter_radius_visitor(int & radius)\n        : radius_(radius) {}\n    template <typename T>\n    void operator () (T const& /*filter*/)  const {}\n\n    void operator () (agg_stack_blur const& op) const\n    {\n        if (static_cast<int>(op.rx) > radius_) radius_ = static_cast<int>(op.rx);\n        if (static_cast<int>(op.ry) > radius_) radius_ = static_cast<int>(op.ry);\n    }\n};\n\ntemplate<typename Src>\nvoid filter_image(Src & src, std::string const& filter, double scale_factor=1)\n{\n    std::vector<filter_type> filter_vector;\n    if(!parse_image_filters(filter, filter_vector))\n    {\n        throw std::runtime_error(\"Failed to parse filter argument in filter_image: '\" + filter + \"'\");\n    }\n    filter_visitor<Src> visitor(src, scale_factor);\n    for (filter_type const& filter_tag : filter_vector)\n    {\n        util::apply_visitor(visitor, filter_tag);\n    }\n}\n\ntemplate<typename Src>\nSrc filter_image(Src const& src, std::string const& filter, double scale_factor=1)\n{\n    std::vector<filter_type> filter_vector;\n    if(!parse_image_filters(filter, filter_vector))\n    {\n        throw std::runtime_error(\"Failed to parse filter argument in filter_image: '\" + filter + \"'\");\n    }\n    Src new_src(src);\n    filter_visitor<Src> visitor(new_src, scale_factor);\n    for (filter_type const& filter_tag : filter_vector)\n    {\n        util::apply_visitor(visitor, filter_tag);\n    }\n    return new_src;\n}\n\n} // End Namespace Filter\n\n} // End Namespace Mapnik\n\n#endif // MAPNIK_IMAGE_FILTER_HPP\n", "meta": {"hexsha": "4aa1e8c7d097ff2d47aa47fff5ae162ecae155f5", "size": 34024, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "external/mapnik/include/mapnik/image_filter.hpp", "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/include/mapnik/image_filter.hpp", "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/include/mapnik/image_filter.hpp", "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": 34.5421319797, "max_line_length": 118, "alphanum_fraction": 0.5088173054, "num_tokens": 9741, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.4818039304790424}}
{"text": "#include <pybind11/pybind11.h>\n#include <pybind11/stl.h>\n#include <pybind11/complex.h>\n#include <pybind11/numpy.h>\n#include <boost/lexical_cast.hpp>\n\n#include <assert.h>\n#include <vector>\n\n#include <CGAL/Delaunay_triangulation_3.h>\n#include <CGAL/Delaunay_triangulation_3.h>\n#include <CGAL/Triangulation_vertex_base_with_info_3.h>\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Delaunay_triangulation_2.h>\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Delaunay_triangulation_2.h>\n#include <CGAL/Triangulation_vertex_base_with_info_2.h>\n\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel            Kernel;\ntypedef CGAL::Triangulation_vertex_base_with_info_2<unsigned int, Kernel> Vb;\ntypedef CGAL::Triangulation_data_structure_2<Vb>                       Tds;\ntypedef CGAL::Delaunay_triangulation_2<Kernel, Tds>                    Delaunay;\ntypedef Kernel::Point_2 Point;\n\ntypedef CGAL::Triangulation_vertex_base_with_info_3<unsigned int, Kernel> Vb3;\ntypedef CGAL::Triangulation_data_structure_3<Vb3>                       Tds3;\ntypedef CGAL::Delaunay_triangulation_3<Kernel, Tds3>                    Delaunay3;\ntypedef Kernel::Point_3 Point3;\n\n\nstd::vector<int> c_delaunay2(std::vector<double> &x, std::vector<double> &y)\n{\n  int num_points = x.size();\n  assert(y.size()!=num_points);\n  std::vector< std::pair<Point,unsigned> > points;\n  // add index information to form face table later\n  for(std::size_t i = 0; i < num_points; ++i)\n  {\n     points.push_back( std::make_pair( Point(x[i],y[i]), i ) );\n  }\n\n  Delaunay triangulation;\n  triangulation.insert(points.begin(),points.end());\n\n  // save the face table\n  int num_faces = triangulation.number_of_faces();\n  std::vector<int> faces;\n  faces.resize(num_faces*3);\n\n  int i=0;\n  for(Delaunay::Finite_faces_iterator fit = triangulation.finite_faces_begin();\n    fit != triangulation.finite_faces_end(); ++fit) {\n\n    Delaunay::Face_handle face = fit;\n    faces[i*3]=face->vertex(0)->info();\n    faces[i*3+1]=face->vertex(1)->info();\n    faces[i*3+2]=face->vertex(2)->info();\n    i+=1;\n  }\n  return faces;\n}\n\n\n\n\nstd::vector<int> c_delaunay3(std::vector<double> &x, std::vector<double> &y, std::vector<double> &z)\n{\n  int num_points = x.size();\n  assert(y.size()!=num_points);\n  assert(z.size()!=num_points);\n  std::vector< std::pair<Point3,unsigned> > points;\n  // add index information to form face table later\n  for(std::size_t i = 0; i < num_points; ++i)\n  {\n     points.push_back( std::make_pair( Point3(x[i],y[i],z[i]), i ) );\n  }\n  Delaunay3 triangulation;\n  triangulation.insert(points.begin(),points.end());\n  // save the indices of all cells\n  int num_cells = triangulation.number_of_finite_cells();\n  std::vector<int> cells;\n  cells.resize(num_cells*4);\n\n  int i=0;\n  for(Delaunay3::Finite_cells_iterator cit = triangulation.finite_cells_begin();\n    cit != triangulation.finite_cells_end(); ++cit) {\n\n    Delaunay3::Cell_handle cell = cit;\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  return cells;\n}\n\n\n// ----------------\n// Python interface\n// ----------------\n// (from https://github.com/tdegeus/pybind11_examples/blob/master/04_numpy-2D_cpp-vector/example.cpp)\n\nnamespace py = pybind11;\npy::array delaunay2(py::array_t<double, py::array::c_style | py::array::forcecast> x,\n                    py::array_t<double, py::array::c_style | py::array::forcecast> y)\n{\n\n  // check input dimensions\n  if ( x.ndim() != 1 )\n    throw std::runtime_error(\"Input should be 2 1D NumPy arrays\");\n  if ( y.ndim() != 1 )\n    throw std::runtime_error(\"Input should be 2 1D NumPy arrays\");\n\n  int num_points = x.shape()[0];\n\n  // allocate std::vector (to pass to the C++ function)\n  std::vector<double> cppx(num_points);\n  std::vector<double> cppy(num_points);\n\n  // copy py::array -> std::vector\n  std::memcpy(cppx.data(),x.data(),num_points*sizeof(double));\n  std::memcpy(cppy.data(),y.data(),num_points*sizeof(double));\n  std::vector<int> faces = c_delaunay2(cppx, cppy);\n\n  ssize_t              soint      = sizeof(int);\n  ssize_t              num_faces = faces.size()/3;\n  ssize_t              ndim      = 2;\n  std::vector<ssize_t> shape     = {num_faces, 3};\n  std::vector<ssize_t> strides   = {soint*3, soint};\n\n  // return 2-D NumPy array\n  return py::array(py::buffer_info(\n    faces.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\npy::array delaunay3(py::array_t<double, py::array::c_style | py::array::forcecast> x,\n                    py::array_t<double, py::array::c_style | py::array::forcecast> y,\n                    py::array_t<double, py::array::c_style | py::array::forcecast> z)\n{\n\n  // check input dimensions\n  if ( x.ndim() != 1 )\n    throw std::runtime_error(\"Input should be three 1D NumPy arrays\");\n  if ( y.ndim() != 1 )\n    throw std::runtime_error(\"Input should be three 1D NumPy arrays\");\n  if ( z.ndim() != 1 )\n    throw std::runtime_error(\"Input should be three 1D NumPy arrays\");\n\n  int num_points = x.shape()[0];\n\n  // allocate std::vector (to pass to the C++ function)\n  std::vector<double> cppx(num_points);\n  std::vector<double> cppy(num_points);\n  std::vector<double> cppz(num_points);\n\n  // copy py::array -> std::vector\n  std::memcpy(cppx.data(),x.data(),num_points*sizeof(double));\n  std::memcpy(cppy.data(),y.data(),num_points*sizeof(double));\n  std::memcpy(cppz.data(),z.data(),num_points*sizeof(double));\n  std::vector<int> cells = c_delaunay3(cppx, cppy, cppz);\n\n  ssize_t              num_cells = cells.size()/4;\n  ssize_t              ndim      = 2;\n  ssize_t              soint      = sizeof(int);\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\n\nPYBIND11_MODULE(simple_cgal, m) {\n    m.def(\"delaunay2\", &delaunay2);\n    m.def(\"delaunay3\", &delaunay3);\n}\n", "meta": {"hexsha": "1c51f3d0fb459c5e891ac702aaeb7e495f02be88", "size": 6850, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/delaunay.cpp", "max_stars_repo_name": "krober10nd/simple_cgal", "max_stars_repo_head_hexsha": "9eafedadda8b0bc9250eeda98eae710a4e53b29c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-05-13T11:39:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T13:47:31.000Z", "max_issues_repo_path": "src/delaunay.cpp", "max_issues_repo_name": "krober10nd/simple_cgal", "max_issues_repo_head_hexsha": "9eafedadda8b0bc9250eeda98eae710a4e53b29c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2020-03-25T12:15:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-17T23:56:00.000Z", "max_forks_repo_path": "src/delaunay.cpp", "max_forks_repo_name": "krober10nd/simple_cgal", "max_forks_repo_head_hexsha": "9eafedadda8b0bc9250eeda98eae710a4e53b29c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-25T08:18:54.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-25T08:18:54.000Z", "avg_line_length": 35.3092783505, "max_line_length": 101, "alphanum_fraction": 0.6197080292, "num_tokens": 1891, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125848754472, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.48176623032170485}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#include \"Framework/TestingFramework.hpp\"\n\n#include <array>\n#include <boost/functional/hash.hpp>\n#include <unordered_map>\n#include <utility>\n\n#include \"DataStructures/DataVector.hpp\"\n#include \"DataStructures/Tensor/Tensor.hpp\"\n#include \"Domain/LogicalCoordinates.hpp\"\n#include \"Domain/Structure/Direction.hpp\"\n#include \"Domain/Structure/ElementId.hpp\"\n#include \"Evolution/DiscontinuousGalerkin/Limiters/WenoHelpers.hpp\"\n#include \"Evolution/DiscontinuousGalerkin/Limiters/WenoOscillationIndicator.hpp\"\n#include \"NumericalAlgorithms/LinearOperators/MeanValue.hpp\"\n#include \"NumericalAlgorithms/Spectral/Mesh.hpp\"\n#include \"NumericalAlgorithms/Spectral/Spectral.hpp\"\n#include \"Utilities/ConstantExpressions.hpp\"\n#include \"Utilities/Gsl.hpp\"\n\nnamespace {\n\nvoid test_reconstruction_1d_impl(const Spectral::Quadrature quadrature) {\n  CAPTURE(quadrature);\n  const double neighbor_linear_weight = 0.005;\n  const Mesh<1> mesh(5, Spectral::Basis::Legendre, quadrature);\n  const auto coords = logical_coordinates(mesh);\n\n  const auto evaluate_polynomial =\n      [&coords](const std::array<double, 5>& coeffs) {\n        const auto& x = get<0>(coords);\n        return DataVector{coeffs[0] + coeffs[1] * x + coeffs[2] * square(x) +\n                          coeffs[3] * cube(x) + coeffs[4] * pow<4>(x)};\n      };\n\n  DataVector local_data = evaluate_polynomial({{1., 2., 0., 0.5, 0.1}});\n  // WENO reconstruction should preserve the mean, so expected = initial\n  const double expected_local_mean = mean_value(local_data, mesh);\n\n  const auto shift_data_to_local_mean =\n      [&mesh, &expected_local_mean](const DataVector& neighbor_data) {\n        return neighbor_data + expected_local_mean -\n               mean_value(neighbor_data, mesh);\n      };\n\n  std::unordered_map<std::pair<Direction<1>, ElementId<1>>, DataVector,\n                     boost::hash<std::pair<Direction<1>, ElementId<1>>>>\n      neighbor_data{};\n  neighbor_data[std::make_pair(Direction<1>::lower_xi(), ElementId<1>(1))] =\n      shift_data_to_local_mean(evaluate_polynomial({{0., 1., 0., 1., 0.}}));\n  neighbor_data[std::make_pair(Direction<1>::upper_xi(), ElementId<1>(2))] =\n      shift_data_to_local_mean(evaluate_polynomial({{0., 0., 1., 1., 2.}}));\n\n  // Expected result computed in Mathematica by computing oscillation indicator\n  // as in oscillation_indicator tests, then WENO weights, then superposition.\n  const DataVector expected_reconstructed_data = evaluate_polynomial(\n      {{1.0000250662809542, 1.9987344134217362, 3.25819395292328e-7,\n        0.5006326303794342, 0.09987412556290375}});\n\n  Limiters::Weno_detail::reconstruct_from_weighted_sum(\n      make_not_null(&local_data), neighbor_linear_weight,\n      Limiters::Weno_detail::DerivativeWeight::Unity, mesh, neighbor_data);\n  CHECK(mean_value(local_data, mesh) == approx(expected_local_mean));\n  CHECK_ITERABLE_APPROX(local_data, expected_reconstructed_data);\n}\n\nvoid test_reconstruction_1d() {\n  INFO(\"Testing WENO reconstruction in 1D\");\n  test_reconstruction_1d_impl(Spectral::Quadrature::GaussLobatto);\n  test_reconstruction_1d_impl(Spectral::Quadrature::Gauss);\n}\n\nvoid test_reconstruction_2d_impl(const Spectral::Quadrature quadrature) {\n  CAPTURE(quadrature);\n  const double neighbor_linear_weight = 0.001;\n  const Mesh<2> mesh({{3, 3}}, Spectral::Basis::Legendre, quadrature);\n  const auto coords = logical_coordinates(mesh);\n\n  const auto evaluate_polynomial =\n      [&coords](const std::array<double, 9>& coeffs) {\n        const auto& x = get<0>(coords);\n        const auto& y = get<1>(coords);\n        return DataVector{\n            coeffs[0] + coeffs[1] * x + coeffs[2] * square(x) +\n            y * (coeffs[3] + coeffs[4] * x + coeffs[5] * square(x)) +\n            square(y) * (coeffs[6] + coeffs[7] * x + coeffs[8] * square(x))};\n      };\n\n  DataVector local_data =\n      evaluate_polynomial({{2., 1., 0., 1.5, 1., 0., 1., 0., 0.}});\n  // WENO reconstruction should preserve the mean, so expected = initial\n  const double expected_local_mean = mean_value(local_data, mesh);\n\n  const auto shift_data_to_local_mean =\n      [&mesh, &expected_local_mean](const DataVector& neighbor_data) {\n        return neighbor_data + expected_local_mean -\n               mean_value(neighbor_data, mesh);\n      };\n\n  std::unordered_map<std::pair<Direction<2>, ElementId<2>>, DataVector,\n                     boost::hash<std::pair<Direction<2>, ElementId<2>>>>\n      neighbor_data{};\n  neighbor_data[std::make_pair(Direction<2>::lower_xi(), ElementId<2>(1))] =\n      shift_data_to_local_mean(\n          evaluate_polynomial({{0., 1., 0., 0., 1., 1., 0., 0., 0}}));\n  neighbor_data[std::make_pair(Direction<2>::upper_xi(), ElementId<2>(2))] =\n      shift_data_to_local_mean(\n          evaluate_polynomial({{0., 0., 1., 1., 2., 1., 0., 1., 1.}}));\n  neighbor_data[std::make_pair(Direction<2>::lower_eta(), ElementId<2>(3))] =\n      shift_data_to_local_mean(\n          evaluate_polynomial({{1., 0., 0., 0., 0.5, 0., 0., 0., 0.5}}));\n  neighbor_data[std::make_pair(Direction<2>::upper_eta(), ElementId<2>(4))] =\n      shift_data_to_local_mean(\n          evaluate_polynomial({{1., 0., 0., 0.5, 1., 0., 0., 0., 0.}}));\n\n  // Expected result computed in Mathematica by computing oscillation indicator\n  // as in oscillation_indicator tests, then WENO weights, then superposition.\n  const DataVector expected_reconstructed_data = evaluate_polynomial(\n      {{2.010056442214612, 0.9705606381771584, 0.000026246579961852654,\n        1.4682459390241314, 0.9992393252122325, 0.0010535139634810797,\n        0.9695333707936392, 0.000026246579961852654, 0.0008131679476911193}});\n\n  Limiters::Weno_detail::reconstruct_from_weighted_sum(\n      make_not_null(&local_data), neighbor_linear_weight,\n      Limiters::Weno_detail::DerivativeWeight::Unity, mesh, neighbor_data);\n  CHECK(mean_value(local_data, mesh) == approx(expected_local_mean));\n  CHECK_ITERABLE_APPROX(local_data, expected_reconstructed_data);\n}\n\nvoid test_reconstruction_2d() {\n  INFO(\"Testing WENO reconstruction in 2D\");\n  test_reconstruction_2d_impl(Spectral::Quadrature::GaussLobatto);\n  test_reconstruction_2d_impl(Spectral::Quadrature::Gauss);\n}\n\nvoid test_reconstruction_3d_impl(const Spectral::Quadrature quadrature) {\n  CAPTURE(quadrature);\n  const double neighbor_linear_weight = 0.001;\n  const Mesh<3> mesh({{3, 3, 3}}, Spectral::Basis::Legendre, quadrature);\n  const auto coords = logical_coordinates(mesh);\n\n  // 3D case has so many modes... so we simplify by only setting 6 of them, the\n  // choice of modes to use here is arbitrary.\n  const auto evaluate_polynomial =\n      [&coords](const std::array<double, 6>& coeffs) {\n        const auto& x = get<0>(coords);\n        const auto& y = get<1>(coords);\n        const auto& z = get<2>(coords);\n        return DataVector{coeffs[0] + coeffs[1] * y + coeffs[2] * x * z +\n                          coeffs[3] * x * y * z + coeffs[4] * square(y) * z +\n                          coeffs[5] * square(x) * y * square(z)};\n      };\n\n  DataVector local_data = evaluate_polynomial({{1., 0.5, 0.5, 0.2, 0.2, 0.1}});\n  // WENO reconstruction should preserve the mean, so expected = initial\n  const double expected_local_mean = mean_value(local_data, mesh);\n\n  const auto shift_data_to_local_mean =\n      [&mesh, &expected_local_mean](const DataVector& neighbor_data) {\n        return neighbor_data + expected_local_mean -\n               mean_value(neighbor_data, mesh);\n      };\n\n  // We skip one neighbor, lower_eta, to simulate an external boundary\n  std::unordered_map<std::pair<Direction<3>, ElementId<3>>, DataVector,\n                     boost::hash<std::pair<Direction<3>, ElementId<3>>>>\n      neighbor_data{};\n  neighbor_data[std::make_pair(Direction<3>::lower_xi(), ElementId<3>(1))] =\n      shift_data_to_local_mean(\n          evaluate_polynomial({{0.3, 0.2, 0.2, 0., 0., 0.1}}));\n  neighbor_data[std::make_pair(Direction<3>::upper_xi(), ElementId<3>(2))] =\n      shift_data_to_local_mean(\n          evaluate_polynomial({{2.5, 1., 0., 0., 1., 1.}}));\n  neighbor_data[std::make_pair(Direction<3>::upper_eta(), ElementId<3>(4))] =\n      shift_data_to_local_mean(\n          evaluate_polynomial({{1., 0.5, 0.5, 0.2, 0.2, 0.2}}));\n  neighbor_data[std::make_pair(Direction<3>::lower_zeta(), ElementId<3>(5))] =\n      shift_data_to_local_mean(\n          evaluate_polynomial({{1., 0.2, 0., 0., 0., 0.}}));\n  neighbor_data[std::make_pair(Direction<3>::upper_zeta(), ElementId<3>(6))] =\n      shift_data_to_local_mean(\n          evaluate_polynomial({{0.1, 0., 0.5, 0.2, 0.2, 0.2}}));\n\n  // Expected result computed in Mathematica by computing oscillation indicator\n  // as in oscillation_indicator tests, then WENO weights, then superposition.\n  const DataVector expected_reconstructed_data = evaluate_polynomial(\n      {{1., 0.32663481881058243, 0.21186828015830592, 0.08447466846582166,\n        0.08447504580872492, 0.04260655032204396}});\n\n  Limiters::Weno_detail::reconstruct_from_weighted_sum(\n      make_not_null(&local_data), neighbor_linear_weight,\n      Limiters::Weno_detail::DerivativeWeight::Unity, mesh, neighbor_data);\n  CHECK(mean_value(local_data, mesh) == approx(expected_local_mean));\n  CHECK_ITERABLE_APPROX(local_data, expected_reconstructed_data);\n}\n\nvoid test_reconstruction_3d() {\n  INFO(\"Testing WENO reconstruction in 3D\");\n  test_reconstruction_3d_impl(Spectral::Quadrature::GaussLobatto);\n  test_reconstruction_3d_impl(Spectral::Quadrature::Gauss);\n}\n\n}  // namespace\n\nSPECTRE_TEST_CASE(\"Unit.Evolution.DG.Limiters.Weno.Helpers\",\n                  \"[Limiters][Unit]\") {\n  test_reconstruction_1d();\n  test_reconstruction_2d();\n  test_reconstruction_3d();\n}\n", "meta": {"hexsha": "edbf44da8b4bee91026b8fa7adf0a3223e32a8b1", "size": 9677, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/Unit/Evolution/DiscontinuousGalerkin/Limiters/Test_WenoHelpers.cpp", "max_stars_repo_name": "nilsvu/spectre", "max_stars_repo_head_hexsha": "1455b9a8d7e92db8ad600c66f54795c29c3052ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 117.0, "max_stars_repo_stars_event_min_datetime": "2017-04-08T22:52:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T07:23:36.000Z", "max_issues_repo_path": "tests/Unit/Evolution/DiscontinuousGalerkin/Limiters/Test_WenoHelpers.cpp", "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": "tests/Unit/Evolution/DiscontinuousGalerkin/Limiters/Test_WenoHelpers.cpp", "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": 45.2196261682, "max_line_length": 80, "alphanum_fraction": 0.6946367676, "num_tokens": 2737, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.48176622836028216}}
{"text": "/*******************************************************************************\n * An abstract domain that lifts a value domain using term\n * equivalences based on the paper \"An Abstract Domain of\n * Uninterpreted Functions\" by Gange, Navas, Schachte, Sondergaard,\n * and Stuckey published in VMCAI'16.\n *\n * Author: Graeme Gange (gkgange@unimelb.edu.au)\n *\n * Contributors: Jorge A. Navas (jorge.navas@sri.com)\n ******************************************************************************/\n\n#pragma once\n\n#include <utility>\n#include <algorithm>\n#include <vector>\n#include <set>\n\n#include <boost/range.hpp>\n#include <boost/container/flat_map.hpp>\n#include <boost/container/flat_set.hpp>\n#include <boost/optional.hpp>\n\n#include <crab/common/debug.hpp>\n#include <crab/common/stats.hpp>\n#include <crab/common/types.hpp>\n#include <crab/numbers/bignums.hpp>\n#include <crab/cfg/var_factory.hpp>\n#include <crab/domains/linear_constraints.hpp>\n#include <crab/domains/abstract_domain.hpp>\n#include <crab/domains/abstract_domain_specialized_traits.hpp>\n#include <crab/domains/backward_assign_operations.hpp>\n#include <crab/domains/intervals.hpp>\n#include <crab/domains/term/term_expr.hpp>\n#include <crab/domains/term/inverse.hpp>\n#include <crab/domains/term/simplify.hpp>\n\n//#define VERBOSE \n//#define DEBUG_VARMAP\n//#define DEBUG_MEET\n\n#define USE_TERM_INTERVAL_NORMALIZER\n\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wsign-compare\"\n\nnamespace crab {\n\n  namespace domains {\n\n     namespace term {\n        template<class Num, class VName, class Abs>\n        class TDomInfo {\n         public:\n          typedef Num Number;\n          typedef VName VariableName;\n\t  typedef variable<Num, VName> variable_t;\n          typedef crab::cfg::var_factory_impl::str_var_alloc_col Alloc;\n          typedef Abs domain_t; \n        };\n     }\n\n     template<class Info, class Abs>\n     class TermNormalizer;\n\n     template< typename Info >\n     class term_domain final:\n      public abstract_domain<term_domain<Info>> {\n       friend class TermNormalizer<Info, typename Info::domain_t>;\n       \n       // Number and VariableName can be different from\n       // dom_t::number_t and dom_t::varname_t although currently\n       // Number and dom_t::number_t must be the same type.\n       typedef typename Info::Number Number;\n       typedef typename Info::VariableName VariableName;\n       typedef typename Info::domain_t dom_t;\n       typedef typename dom_t::variable_t dom_var_t;\n       typedef typename Info::Alloc dom_var_alloc_t;\n       typedef typename dom_var_alloc_t::varname_t dom_varname_t;\n       typedef patricia_tree_set< dom_var_t > domvar_set_t;\n       typedef bound<Number> bound_t;\n       \n       typedef term_domain<Info> term_domain_t;\n       typedef abstract_domain<term_domain_t> abstract_domain_t;\n       \n      public:\n       \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::disjunctive_linear_constraint_system_t;       \n       using typename abstract_domain_t::variable_t;\n       typedef Number number_t;\n       typedef VariableName varname_t;\n       using typename abstract_domain_t::variable_vector_t;\n       using typename abstract_domain_t::pointer_constraint_t;\n       \n       typedef interval<number_t> interval_t;\n       \n      private:\n\n       typedef term::term_table< number_t, binary_operation_t > ttbl_t;\n       typedef typename ttbl_t::term_id_t term_id_t;\n\n       // WARNING: assumes the underlying domain uses the same number type.\n       typedef typename Info::Number                      dom_number;\n       typedef typename dom_t::linear_constraint_t        dom_lincst_t;\n       typedef typename dom_t::linear_constraint_system_t dom_linsys_t;\n       typedef typename dom_t::linear_expression_t        dom_linexp_t;\n       typedef typename linear_expression_t::component_t linterm_t;\n       typedef boost::container::flat_map< term_id_t, dom_var_t > term_map_t;\n       typedef boost::container::flat_map< dom_var_t, variable_t > rev_map_t;\n       typedef boost::container::flat_set< term_id_t > term_set_t;\n       typedef boost::container::flat_map< variable_t, term_id_t > var_map_t;\n       // the reverse of var_map: from term_id_t to a set of variable_t\n       typedef std::set<variable_t> var_set_t;\n       typedef boost::container::flat_map< term_id_t, var_set_t > rev_var_map_t;\n       typedef term::NumSimplifier<number_t> simplifier_t;\n\n       bool _is_bottom;\n       // Uses a single state of the underlying domain.\n       ttbl_t _ttbl;\n       dom_t _impl;\n       dom_var_alloc_t _alloc;\n       var_map_t _var_map;\n       rev_var_map_t _rev_var_map; // to extract equalities efficiently\n       term_map_t _term_map;\n       term_set_t changed_terms; \n              \n       term_domain(bool is_top): _is_bottom(!is_top) { }\n       \n       term_domain(dom_var_alloc_t alloc, var_map_t vm, rev_var_map_t rvm,\n\t\t   ttbl_t tbl, term_map_t tmap, dom_t impl)\n           : _is_bottom((impl.is_bottom())? true: false),\n\t     _ttbl(tbl),\n\t     _impl(impl),\n\t     _alloc(alloc), \n             _var_map(vm),\n\t     _rev_var_map(rvm),\n\t     _term_map(tmap)\n       { check_terms(__LINE__); }\n       \n       // x = y op [lb,ub]\n       term_id_t term_of_itv(bound_t lb, bound_t ub) {\n         boost::optional<number_t> n_lb = lb.number();\n         boost::optional<number_t> n_ub = ub.number();\n         \n         if (n_lb && n_ub && (*n_lb == *n_ub))\n           return term_of_const(*n_lb);\n         \n         term_id_t t_itv = _ttbl.fresh_var();\n         dom_var_t dom_itv = domvar_of_term(t_itv);\n         _impl.set(dom_itv, interval_t(lb, ub));\n         return t_itv;\n       }\n       \n       // term_id_t term_of_expr(operation_t op, term_id_t ty, term_id_t tz)\n       // {\n       //   boost::optional<term_id_t> opt_tx = _ttbl.find_ftor(op, ty, tz);\n       //   if(opt_tx)\n       //   {\n       //     // If the term already exists, we can learn nothing.\n       //     return *opt_tx;\n       //   } else {\n       //     // Otherwise, assign the term, and evaluate.\n       //     term_id_t tx = _ttbl.apply_ftor(op, ty, tz);\n       //     _impl.apply(op,\n       //                 domvar_of_term(tx),\n       //                 domvar_of_term(ty), domvar_of_term(tz));\n       //     return tx;\n       //   }\n       // }\n              \n       // void apply(operation_t op, variable_t x, variable_t y, bound_t lb, bound_t ub){\t\n       //   term_id_t t_x = term_of_expr(op, term_of_var(y), term_of_itv(lb, ub));\n       //   // JNL: check with Graeme\n       //   //      insert only adds an entry if the key does not exist\n       //   //_var_map.insert(std::make_pair(x, t_x));\n       //   rebind_var(x, t_x);\n       //   check_terms(__LINE__);\n       // }\n\n      \n       void apply(dom_t& dom, binary_operation_t op,\n\t\t  dom_var_t x, dom_var_t y, dom_var_t z) {\n         if (auto top = conv_op<operation_t>(op)) {\n\t   dom.apply(*top, x, y, z);\n\t } else if (auto top = conv_op<bitwise_operation_t>(op)) {\n\t   dom.apply(*top, x, y, z);\n\t } else if (op == BINOP_FUNCTION) {\n\t   // uninterpreted function: do nothing in the underlying\n\t   // numerical domain.\n\t } else {\n\t   CRAB_ERROR(\"unsupported binary operator \", op);\n\t }\n       }\n\n \n       // Apply a given functor in the underlying domain.\n       // GKG: Looks the current implementation could actually\n       // lose information; as it's not taking the meet with\n       // the current value.\n       void eval_ftor(dom_t& dom, ttbl_t& tbl, term_id_t t) {\n         // Get the term info.\n         typename ttbl_t::term_t* t_ptr = tbl.get_term_ptr(t); \n         \n         // Only apply functors.\n         if(t_ptr->kind() == term::TERM_APP) {\n           binary_operation_t op = term::term_ftor(t_ptr);\n           \n           std::vector<term_id_t>& args(term::term_args(t_ptr));\n           assert(args.size() == 2);\n           apply(dom, op, \n                  domvar_of_term(t), domvar_of_term(args[0]), domvar_of_term(args[1]));\n         }\n       }\n       \n       void eval_ftor_down(dom_t& dom, ttbl_t& tbl, term_id_t t) {\n         // Get the term info.\n         typename ttbl_t::term_t* t_ptr = tbl.get_term_ptr(t); \n         \n         // Only apply functors.\n         if(t_ptr->kind() == term::TERM_APP)\n         {\n           binary_operation_t op = term::term_ftor(t_ptr);\n           std::vector<term_id_t>& args(term::term_args(t_ptr));\n           assert(args.size() == 2);\n\n           if (boost::optional<operation_t> arith_op = conv_op<operation_t>(op)) {\n             term::InverseOps<dom_number, dom_var_t, dom_t>::\n                 apply(dom, *arith_op,\n                       domvar_of_term(t), domvar_of_term(args[0]), domvar_of_term(args[1])); \n           }\n         }\n       }\n              \n       dom_t eval_ftor_copy(dom_t& dom, ttbl_t& tbl, term_id_t t) {\n         dom_t ret = dom;\n         eval_ftor(ret, tbl, t);\n         return ret;\n       }  \n       \n       binary_operation_t conv2binop(operation_t op) {\n         switch(op) {\n           case OP_ADDITION: return BINOP_ADD;\n           case OP_SUBTRACTION: return BINOP_SUB;\n           case OP_MULTIPLICATION: return BINOP_MUL;\n           case OP_SDIV: return BINOP_SDIV;\n           case OP_UDIV: return BINOP_UDIV;\n           case OP_SREM: return BINOP_SREM;\n           default: return BINOP_UREM;\n\t     \n         }\n       }\n\n       binary_operation_t conv2binop(bitwise_operation_t op) {\n         switch (op) {\n           case OP_AND: return BINOP_AND;\n           case OP_OR: return BINOP_OR;\n           case OP_XOR: return BINOP_XOR;\n           case OP_SHL: return BINOP_SHL;\n           case OP_LSHR: return BINOP_LSHR;\n           default: return BINOP_ASHR;\n         }\n       }\n\n       void check_terms(int line) const {\n         #ifdef DEBUG_VARMAP\n         for(auto const p : _var_map) {\n\t   if (!(p.second < _ttbl.size())) {\n\t     CRAB_ERROR(\"term_equiv.hpp at line=\", line, \": \",\n\t\t\t\"term id is not the table term\");\n\t   }\n\t }\n\t \n\t for(auto kv: _rev_var_map) {\n\t   for(auto v: kv.second) {\n\t     auto it = _var_map.find(v);\n\t     if (it->second != kv.first) {\n\t       CRAB_ERROR(\"term_equiv.hpp at line=\", line, \": \",\n\t\t\t  v, \" is mapped to t\", it->second,\n\t\t\t  \" but the reverse map says that should be t\",\n\t\t\t  kv.first);\n\t     }\n\t   }\n\t }\n\t #endif\n       }\n\n       void deref(term_id_t t) {\n         std::vector<term_id_t> forgotten;\n         _ttbl.deref(t, forgotten);\n         for(term_id_t f : forgotten) {\n           typename term_map_t::iterator it(_term_map.find(f));\n           if(it != _term_map.end()) {\n             _impl -= (*it).second;\n             _term_map.erase(it);\n           }\n         }\n       }\n\n       /* Begin manipulate the reverse variable map */\n       void add_rev_var_map(rev_var_map_t& rvmap, term_id_t t, variable_t v) {\n\t auto it = rvmap.find(t);\n\t if (it != rvmap.end()) {\n\t   it->second.insert(v);\n\t } else {\n\t   var_set_t varset;\n\t   varset.insert(v);\n\t   rvmap.insert(std::make_pair(t, varset));\n\t }\n       }\n       \n       void remove_rev_var_map(term_id_t t, variable_t v) {\n\t auto it = _rev_var_map.find(t);\n\t if (it != _rev_var_map.end()) {\n\t   it->second.erase(v);\n\t   if (it->second.empty()) {\n\t     _rev_var_map.erase(it);\n\t   }\n\t }\t \n       }\n       /* End manipulate the reverse variable map */\n       \n       void rebind_var(variable_t& x, term_id_t tx) {\n         _ttbl.add_ref(tx);\n\t \n         auto it(_var_map.find(x));\n         if(it != _var_map.end()) {\n\t   remove_rev_var_map((*it).second, x);\n\t   deref((*it).second);\n\t   _var_map.erase(it);\n\t } \n\t _var_map.insert(std::make_pair(x, tx));\n\t add_rev_var_map(_rev_var_map, tx, x);\n       }\n\n       // Build the tree for a linexpr, and ensure that\n       // values for the subterms are sustained.\n\n       term_id_t term_of_const(const number_t& n) {\n         dom_number dom_n(n);\n         boost::optional<term_id_t> opt_n(_ttbl.find_const(dom_n));\n         if(opt_n) {\n           return *opt_n;\n         } else {\n           term_id_t term_n(_ttbl.make_const(dom_n));\n           dom_var_t v = domvar_of_term(term_n);\n\n           dom_linexp_t exp(n);\n           _impl.assign(v, exp);\n           return term_n;\n         }\n       }\n\n       term_id_t term_of_var(variable_t v, var_map_t& var_map,\n\t\t\t     rev_var_map_t& rvar_map, ttbl_t& ttbl) {\n         auto it(var_map.find(v)); \n         if(it != var_map.end()) {\n           // assert((*it).first == v);\n           assert(ttbl.size() > (*it).second);\n           return (*it).second;\n         } else {\n           // Allocate a fresh term\n           term_id_t id(ttbl.fresh_var());\n           var_map[v] = id;\n\t   add_rev_var_map(rvar_map, id, v);\n           ttbl.add_ref(id);\n           return id;\n         }\n       }\n       \n       term_id_t term_of_var(variable_t v) {\n         return term_of_var(v, _var_map, _rev_var_map, _ttbl);\n       }\n\n       term_id_t term_of_linterm(linterm_t term) {\n         if(term.first == 1) {\n           return term_of_var(term.second);\n         } else {\n           return build_term(OP_MULTIPLICATION,\n                             term_of_const(term.first),\n                             term_of_var(term.second));\n         }\n       }\n\n       // OpTy = [operation_t | bitwise_operation_t]\n       template<typename OpTy> \n       term_id_t build_term(OpTy op, term_id_t ty, term_id_t tz) {\n         // Check if the term already exists\n         binary_operation_t binop = conv2binop(op);\n         boost::optional<term_id_t> eopt(_ttbl.find_ftor(binop, ty, tz));\n         if(eopt) {\n           return *eopt;\n         } else {\n           // Create the term\n           term_id_t tx = _ttbl.apply_ftor(binop, ty, tz);\n           dom_var_t v(domvar_of_term(tx));\n           dom_var_t y(domvar_of_term(ty));\n           dom_var_t z(domvar_of_term(tz));\n\n\t   // Set evaluation\n\t   CRAB_LOG(\"term\", crab::outs() << \"Prev: \" << _impl <<\"\\n\");\n\t   _impl.apply(op, v, y, z);\n\t   \n           CRAB_LOG(\"term\", \n                    crab::outs() << \"Should have \" << v << \" := \" << y << op  << z <<\"\\n\";\n\t\t    crab::outs() << _impl <<\"\\n\";);\n           return tx;\n         }\n       }\n\n       term_id_t build_function(term_id_t ty, term_id_t tz) {\n\t binary_operation_t op = BINOP_FUNCTION;\n         // Check if the term already exists\n         boost::optional<term_id_t> eopt(_ttbl.find_ftor(op, ty, tz));\n         if(eopt) {\n           return *eopt;\n         } else {\n           // Create the term\n           term_id_t tx = _ttbl.apply_ftor(op, ty, tz);\n           return tx;\n         }\n       }\n       \n       term_id_t build_linexpr(linear_expression_t& e) {\n         number_t cst = e.constant();\n         typename linear_expression_t::iterator it(e.begin());\n         if(it == e.end())\n           return term_of_const(cst);\n     \n         term_id_t t;\n         if(cst == 0)\n         {\n           t = term_of_linterm(*it);\n           ++it;\n         } else {\n           t = term_of_const(cst);\n         }\n         for(; it != e.end(); ++it) {\n           t = build_term(OP_ADDITION, t, term_of_linterm(*it));\n         }\n\n         CRAB_LOG(\"term\", \n                  crab::outs() << \"Should have \" << domvar_of_term(t) << \" := \" \n                  << e << \"\\n\" << _impl <<\"\\n\");\n         return t;       \n       }\n\n       dom_var_t domvar_of_term(term_id_t id) {\n         typename term_map_t::iterator it(_term_map.find(id));\n         if(it != _term_map.end()) {\n           return(*it).second;\n         } else {\n           // Allocate a fresh variable\n           dom_var_t dvar(_alloc.next());\n           _term_map.insert(std::make_pair(id, dvar));\n           return dvar;\n         }\n       }\n\n       dom_var_t domvar_of_var(variable_t v) {\n         return domvar_of_term(term_of_var(v));\n       }\n\n       // Remap a linear constraint to the domain.\n       dom_linexp_t rename_linear_expr(linear_expression_t exp) {\n         number_t cst(exp.constant());\n         dom_linexp_t dom_exp(cst);\n         for(auto v : exp.variables())\n         {\n           dom_exp = dom_exp + exp[v]*domvar_of_var(v);\n         }\n         return dom_exp;\n       }\n\n       dom_lincst_t rename_linear_cst(linear_constraint_t cst)\n       {\n         return dom_lincst_t(rename_linear_expr(cst.expression()), \n                             (typename dom_lincst_t::kind_t) cst.kind());\n       }\n\n       // Assumption: vars(exp) subseteq keys(map)\n       // XXX JNL: exp can have variables that are not in rev_map (e.g.,\n       // some generated by build_linexpr). \n       boost::optional<linear_expression_t> \n       rename_linear_expr_rev(dom_linexp_t exp, rev_map_t rev_map) const {\n         number_t cst(exp.constant());\n         linear_expression_t rev_exp(cst);\n         for(auto v : exp.variables()) {\n           auto it = rev_map.find(v);\n           if (it != rev_map.end()) {\n             variable_t v_out((*it).second);\n             rev_exp = rev_exp + exp[v]*v_out;\n           }\n           else\n             return boost::optional<linear_expression_t>();\n         }\n         return rev_exp;\n       }\n\n       boost::optional<linear_constraint_t> \n       rename_linear_cst_rev(dom_lincst_t cst, rev_map_t rev_map) const {\n         boost::optional<linear_expression_t> e = \n             rename_linear_expr_rev(cst.expression(), rev_map);\n         if (e)\n           return linear_constraint_t(*e,\n                                     (typename linear_constraint_t::kind_t) cst.kind());\n         else\n           return boost::optional<linear_constraint_t>();\n       }\n\n       boost::optional<std::pair<variable_t, variable_t> >\n       get_eq_or_diseq(linear_constraint_t cst) {\n         if (cst.is_equality() || cst.is_disequation()) {\n           if (cst.size() == 2 && cst.constant() == 0) {\n             auto it = cst.begin();\n             auto nx = it->first;\n             auto vx = it->second;\n             ++it;\n             assert(it != cst.end());\n             auto ny = it->first;\n             auto vy = it->second;\n             if (nx ==(ny * -1 )) {\n               return std::make_pair(vx, vy);\n             } \n           }\n         } \n         return boost::optional<std::pair<variable_t, variable_t> >();\n       }\n\n       struct WidenOp {\n         dom_t apply(dom_t before, dom_t after){ \n           return before || after;\n         }\n       };\n\n       template<typename Thresholds>\n       struct WidenWithThresholdsOp {\n         const Thresholds & m_ts;\n\n         WidenWithThresholdsOp(const Thresholds &ts): m_ts(ts) { }\n\n         dom_t apply(dom_t before, dom_t after) { \n           return before.widening_thresholds(after, m_ts);\n         }\n       };\n\n       template <typename WidenOp>\n       term_domain_t widening(term_domain_t o, WidenOp widen_op) {\n                             \n         // The left operand of the widenning cannot be closed, otherwise\n         // termination is not ensured. However, if the right operand is\n         // close precision may be improved.\n         o.normalize();\n         if (is_bottom()) {\n           return o;\n         } \n         else if(o.is_bottom()) {\n           return *this;\n         } \n         else {\n           // First, we need to compute the new term table.\n           ttbl_t out_tbl;\n           // Mapping of (term, term) pairs to terms in the join state\n           typename ttbl_t::gener_map_t gener_map;\n           \n           var_map_t out_vmap;\n           rev_var_map_t out_rvmap;\n           dom_var_alloc_t palloc(_alloc, o._alloc);\n           \n           // For each program variable in state, compute a generalization\n           for(auto p : _var_map)\n           {\n             variable_t v(p.first);\n             term_id_t tx(term_of_var(v));\n             term_id_t ty(o.term_of_var(v));\n             \n             term_id_t tz = _ttbl.generalize(o._ttbl, tx, ty, out_tbl, gener_map);\n             out_vmap[v] = tz;\n\t     add_rev_var_map(out_rvmap, tz, v);\n           }\n           \n           // Rename the common terms together\n           dom_t x_impl(_impl);\n           dom_t y_impl(o._impl);\n           \n           // Perform the mapping\n           term_map_t out_map;\n           std::vector<dom_var_t> out_varnames;\n           for(auto p : gener_map)\n           {\n             auto txy = p.first;\n             term_id_t tz = p.second;\n             dom_var_t vt(palloc.next());\n             out_map.insert(std::make_pair(tz, vt));\n             \n             dom_var_t vx = domvar_of_term(txy.first);\n             dom_var_t vy = o.domvar_of_term(txy.second);\n             \n             out_varnames.push_back(vt);             \n\n             x_impl.assign(vt, vx);\n             y_impl.assign(vt, vy);\n           }\n\n\t   x_impl.project(out_varnames);\n\t   y_impl.project(out_varnames);\n\t   \n           dom_t x_widen_y = widen_op.apply(x_impl, y_impl);\n           \n           for(auto p : out_vmap)\n             out_tbl.add_ref(p.second);\n           \n           term_domain_t res(palloc, out_vmap, out_rvmap, out_tbl, out_map, x_widen_y);\n           \n           CRAB_LOG(\"term\", \n                    crab::outs() << \"============ WIDENING ==================\";\n                    crab::outs() << x_impl << \"\\n~~~~~~~~~~~~~~~~\";\n                    crab::outs() << y_impl << \"\\n----------------\";\n                    crab::outs() << x_widen_y << \"\\n================\" << \"\\n\");\n           \n           return res;\n         }         \n       }\n\n       // Choose one non-var term from the equivalence class\n       // associated with t.\n       template<typename Range> \n       boost::optional<term_id_t> choose_non_var(ttbl_t& ttbl, const Range& terms) {\n         std::vector<term_id_t> non_var_terms(terms.size());\n         auto it = std::copy_if(terms.begin(), terms.end(),  \n                                 non_var_terms.begin(),\n                                 [&ttbl](term_id_t t) {  \n                                   typename ttbl_t::term_t* t_ptr = ttbl.get_term_ptr(t);\n                                   return(t_ptr && t_ptr->kind() == term::TERM_APP);\n                                 });\n         non_var_terms.resize(std::distance(non_var_terms.begin(),it));\n         if (non_var_terms.empty()) {\n           return boost::optional <term_id_t>();\n         } else {\n           // TODO: the heuristics as described in the VMCAI'16 paper\n           // that chooses the one that has more references each class.\n           return *(non_var_terms.begin()); \n         }\n       }\n\n       term_id_t build_dag_term(ttbl_t& ttbl, int t,\n                                 term::congruence_closure_solver<ttbl_t>& solver, \n                                 ttbl_t& out_ttbl, std::vector<int>& stack, \n                                 std::map <int, term_id_t>& cache) {\n\n         // already processed\n         auto it = cache.find(t);\n         if (it != cache.end()) {\n           #ifdef DEBUG_MEET\n           crab::outs() << \"Found in cache: \";\n           crab::outs() << \"t\" << t << \" --> \" << \"t\" << it->second << \"\\n\";\n           #endif \n           return it->second;\n         }\n         \n         // break the cycle with a fresh variable\n         if (std::find(stack.begin(), stack.end(), t) != stack.end()) {\n           term_id_t v = out_ttbl.fresh_var();\n           #ifdef DEBUG_MEET\n           crab::outs() << \"Detected cycle: \";\n           crab::outs() << \"t\" << t << \" --> \" << \"t\" << v << \"\\n\";\n           #endif \n           return v;\n         }\n\n         stack.push_back(t);\n         auto membs = solver.get_members(t);\n         boost::optional<term_id_t> f = choose_non_var(ttbl, membs);\n\n         if (!f) {\n           // no concrete definition exists return a fresh variable\n           term_id_t v = out_ttbl.fresh_var();\n           auto res = cache.insert(std::make_pair(t, v));\n           stack.pop_back();\n           #ifdef DEBUG_MEET\n           crab::outs() << \"No concrete definition: \";\n           crab::outs() << \"t\" << t << \" --> \" << \"t\" <<(res.first)->second << \"\\n\";\n           #endif \n           return (res.first)->second;\n         } else {\n           // traverse recursively the term\n           typename ttbl_t::term_t* f_ptr = ttbl.get_term_ptr(*f); \n           #ifdef DEBUG_MEET\n           crab::outs() << \"Traversing recursively the term \" << \"t\" << *f << \":\";\n           crab::outs() << *f_ptr << \"\\n\";\n           #endif \n           std::vector<term_id_t>& args(term::term_args(f_ptr));\n           std::vector<term_id_t> res_args;\n           res_args.reserve(args.size());\n           for(term_id_t c : args) {\n               res_args.push_back(build_dag_term(ttbl,solver.get_class(c), \n                                                   solver, out_ttbl, stack, cache));\n           }\n           auto res = cache.insert(std::make_pair(t, \n                                    out_ttbl.apply_ftor(term::term_ftor(f_ptr), \n                                                         res_args)));\n           stack.pop_back();\n           #ifdef DEBUG_MEET\n           crab::outs() << \"Finished recursive case: \";\n           crab::outs() << \"t\" << t << \" --> \" << \"t\" <<(res.first)->second << \"\\n\";\n           #endif \n           return (res.first)->second;\n         }\n       }\n\n      public:\n\n       void set_to_top() {\n         term_domain abs(true);\n\t std::swap(*this, abs);\n       }\n       \n       void set_to_bottom() {\n         term_domain abs(false);\n\t std::swap(*this, abs);\n       }\n\n       // void set_to_bottom(){\n       //   this->_is_bottom = true;\n       // }\n       \n       \n       term_domain(): _is_bottom(false) { }\n       \n       term_domain(const term_domain_t& o): \n           _is_bottom(o._is_bottom), \n           _ttbl(o._ttbl), _impl(o._impl),\n           _alloc(o._alloc),\n           _var_map(o._var_map),\n\t   _rev_var_map(o._rev_var_map),\n\t   _term_map(o._term_map),\n           changed_terms(o.changed_terms)\n       { \n         crab::CrabStats::count(getDomainName() + \".count.copy\");\n         crab::ScopedCrabStats __st__(getDomainName() + \".copy\");\n         check_terms(__LINE__); \n       } \n       \n       term_domain_t& operator=(const term_domain_t &o) {\n         crab::CrabStats::count(getDomainName() + \".count.copy\");\n         crab::ScopedCrabStats __st__(getDomainName() + \".copy\");\n         \n         o.check_terms(__LINE__);\n         if (this != &o) {\n           _is_bottom= o._is_bottom;\n           _ttbl = o._ttbl;\n           _impl = o._impl;\n           _alloc = o._alloc;\n           _var_map= o._var_map;\n\t   _rev_var_map = o._rev_var_map;\n           _term_map= o._term_map;\n           changed_terms = o.changed_terms;\n         }\n         check_terms(__LINE__);\n         return *this;\n       }\n       \n       bool is_bottom() {\n         return _is_bottom;\n       }\n       \n       bool is_top() {\n         return !_var_map.size() && !is_bottom();\n       }\n       \n       bool is_normalized(){\n         return changed_terms.size() == 0;\n         // return _is_normalized(_impl);\n       }\n       \n       // Lattice operations\n       bool operator<=(term_domain_t o)  {\t\n         crab::CrabStats::count(getDomainName() + \".count.leq\");\n         crab::ScopedCrabStats __st__(getDomainName() + \".leq\");\n\n         // Require normalization of the first argument\n         this->normalize();\n         \n         if (is_bottom()) {\n           return true;\n         } else if(o.is_bottom()) {\n           return false;\n         } else {\n           typename ttbl_t::term_map_t gen_map;\n           dom_var_alloc_t palloc(_alloc, o._alloc);\n           \n           // Build up the mapping of o onto this, variable by variable.\n           // Assumption: the set of variables in x & o are common.\n           for(auto p : _var_map)\n           {\n             if(!_ttbl.map_leq(o._ttbl, term_of_var(p.first), o.term_of_var(p.first), gen_map))\n               return false;\n           }\n           // We now have a mapping of reachable y-terms to x-terms.\n           // Create copies of _impl and o._impl with a common\n           // variable set.\n           dom_t x_impl(_impl);\n           dom_t y_impl(o._impl);\n           \n           // Perform the mapping\n           std::vector<dom_var_t> out_varnames;\n           for(auto p : gen_map)\n           {\n             // dom_var_t vt = _alloc.next();\n             dom_var_t vt(palloc.next());\n             dom_var_t vx = domvar_of_term(p.second); \n             dom_var_t vy = o.domvar_of_term(p.first);\n             \n             out_varnames.push_back(vt);\n\n             x_impl.assign(vt, vx);\n             y_impl.assign(vt, vy);\n           }\n\t   \n\t   x_impl.project(out_varnames);\n\t   y_impl.project(out_varnames);\n\t   \n           return x_impl <= y_impl;\n         }\n       } \n       \n       // Optimized version of | that avoids some unnecessary copies\n       void operator|=(term_domain_t o) {\n         crab::CrabStats::count(getDomainName() + \".count.join\");\n         crab::ScopedCrabStats __st__(getDomainName() + \".join\");\n         \n         // Requires normalization of both operands\n         normalize();\n         o.normalize();\n         \n         if (is_bottom() || o.is_top()) {\n           *this = o;\n         } \n         else if(o.is_bottom() || is_top()) {\n           return;\n         }       \n         else {\n           // First, we need to compute the new term table.\n           ttbl_t out_tbl;\n\n           // Mapping of (term, term) pairs to terms in the join state\n           typename ttbl_t::gener_map_t gener_map;\n           \n           var_map_t out_vmap;\n\t   rev_var_map_t out_rvmap;\n           dom_var_alloc_t palloc(_alloc, o._alloc);\n           \n           // For each program variable in state, compute a generalization\n           for(auto p : _var_map)\n           {\n             variable_t v(p.first);\n             term_id_t tx(term_of_var(v));\n             term_id_t ty(o.term_of_var(v));\n             \n             term_id_t tz = _ttbl.generalize(o._ttbl, tx, ty, out_tbl, gener_map);\n             assert(tz < out_tbl.size());\n             out_vmap[v] = tz;\n\t     add_rev_var_map(out_rvmap, tz, v);\n           }\n           \n           // Rename the common terms together\n           // Perform the mapping\n           term_map_t out_map;\n           std::vector<dom_var_t> out_varnames;\n           for(auto p : gener_map)\n           {\n             auto txy = p.first;\n             term_id_t tz = p.second;\n             dom_var_t vt(palloc.next());\n             out_map.insert(std::make_pair(tz, vt));\n             \n             dom_var_t vx = domvar_of_term(txy.first);\n             dom_var_t vy = o.domvar_of_term(txy.second);\n             \n             out_varnames.push_back(vt);             \n             \n             _impl.assign(vt, vx);\n             o._impl.assign(vt, vy);\n           }\n\n\t   _impl.project(out_varnames);\n\t   o._impl.project(out_varnames);\n\t   \n           _impl |= o._impl;\n           \n           for(auto p : out_vmap)\n             out_tbl.add_ref(p.second);\n           \n           std::swap(_alloc, palloc);\n           std::swap(_var_map, out_vmap);\n\t   std::swap(_rev_var_map, out_rvmap);\n           std::swap(_ttbl, out_tbl);\n           std::swap(_term_map, out_map);\n           _is_bottom = (_impl.is_bottom() ? true: false);\n           \n         }\n       }\n\n       term_domain_t operator|(term_domain_t o) {\n         crab::CrabStats::count(getDomainName() + \".count.join\");\n         crab::ScopedCrabStats __st__(getDomainName() + \".join\");\n\t \n         // Requires normalization of both operands\n         normalize();\n         o.normalize();\n         \n         if (is_bottom() || o.is_top()) {\n           return o;\n         } \n         else if(o.is_bottom() || is_top()) {\n           return *this;\n         }       \n         else {\n           // First, we need to compute the new term table.\n           ttbl_t out_tbl;\n           // Mapping of (term, term) pairs to terms in the join state\n           typename ttbl_t::gener_map_t gener_map;\n           \n           var_map_t out_vmap;\n           rev_var_map_t out_rvmap;\n           dom_var_alloc_t palloc(_alloc, o._alloc);\n           \n           // For each program variable in state, compute a generalization\n           for(auto p : _var_map)\n           {\n             variable_t v(p.first);\n             term_id_t tx(term_of_var(v));\n             term_id_t ty(o.term_of_var(v));\n             \n             term_id_t tz = _ttbl.generalize(o._ttbl, tx, ty, out_tbl, gener_map);\n             assert(tz < out_tbl.size());\n             out_vmap[v] = tz;\n\t     add_rev_var_map(out_rvmap, tz, v);\n           }\n           \n           // Rename the common terms together\n           dom_t x_impl(_impl);\n           dom_t y_impl(o._impl);\n           \n           // Perform the mapping\n           term_map_t out_map;\n           std::vector<dom_var_t> out_varnames;\n           for(auto p : gener_map)\n           {\n             auto txy = p.first;\n             term_id_t tz = p.second;\n             dom_var_t vt(palloc.next());\n             out_map.insert(std::make_pair(tz, vt));\n             \n             dom_var_t vx = domvar_of_term(txy.first);\n             dom_var_t vy = o.domvar_of_term(txy.second);\n             \n             out_varnames.push_back(vt);\n             \n             x_impl.assign(vt, vx);\n             y_impl.assign(vt, vy);\n           }\n           \n           CRAB_LOG(\"term\", \n                    crab::outs() << \"============ JOIN ==================\"\n                              << *this << \"\\n\" << \"~~~~~~~~~~~~~~~~\"\n                              << o << \"\\n\" << \"----------------\"\n                              << \"x = \" << _impl\n                              << \"y = \" << o._impl\n                              << \"ren_0(x) = \" << x_impl\n                              << \"ren_0(y) = \" <<  y_impl <<\"\\n\");\n\n\t   x_impl.project(out_varnames);\n\t   y_impl.project(out_varnames);\n\t   \n           dom_t x_join_y = x_impl|y_impl;\n           \n           for(auto p : out_vmap)\n             out_tbl.add_ref(p.second);\n           \n           term_domain_t res(palloc, out_vmap, out_rvmap, out_tbl, out_map, x_join_y);\n           \n           CRAB_LOG(\"term\", crab::outs() << \"After elimination:\\n\" << res << \"\\n\");\n\n           return res;\n         }\n       }\n\n       term_domain_t operator||(term_domain_t other) {\n         crab::CrabStats::count(getDomainName() + \".count.widening\");\n         crab::ScopedCrabStats __st__(getDomainName() + \".widening\");\n         WidenOp op;\n         return this->widening(other, op);\n       }\n       \n       term_domain_t widening_thresholds(term_domain_t other,\n\t\t\t\t\t const iterators::thresholds<number_t>& ts) {\n         crab::CrabStats::count(getDomainName() + \".count.widening\");\n         crab::ScopedCrabStats __st__(getDomainName() + \".widening\");\n         WidenWithThresholdsOp<iterators::thresholds<number_t>> op(ts);\n         return this->widening(other, op);\n       }\n       \n       // Meet\n       term_domain_t operator&(term_domain_t o) {\n         crab::CrabStats::count(getDomainName() + \".count.meet\");\n         crab::ScopedCrabStats __st__(getDomainName() + \".meet\");\n\n         // Does not require normalization of any of the two operands\n         if (is_bottom() || o.is_bottom()) {\n           return term_domain_t::bottom();\n         } else if (is_top()) { \n           return o;\n         } else if (o.is_top()) {\n           return *this;\n         } else {\n\n           ttbl_t out_ttbl(_ttbl);\n           std::map<term_id_t, term_id_t> copy_map;\n           // bring all terms to one ttbl\n           for (auto p: o._var_map) {\n             variable_t v(p.first);\n             term_id_t tx(o.term_of_var(v));\n             out_ttbl.copy_term(o._ttbl, tx, copy_map);\n           }\n           \n           // build unifications between terms from this and o\n           std::vector<std::pair<term_id_t,term_id_t> > eqs;\n           for (auto p: _var_map) {\n             variable_t v(p.first);\n             auto it = o._var_map.find(v);\n             if (it != o._var_map.end()) {\n               term_id_t tx(term_of_var(v));\n               eqs.push_back(std::make_pair(tx, copy_map [it->second]));\n             }\n           }\n\n           // compute equivalence classes\n           term::congruence_closure_solver<ttbl_t> solver(&out_ttbl);\n           solver.run(eqs);\n\n           std::vector<int> stack;\n           std::map <int, term_id_t> cache;\n           var_map_t out_vmap;\n\t   rev_var_map_t out_rvmap;\n           // new map from variable to an acyclic term \n           for(auto p : _var_map) {\n             variable_t v(p.first);\n             term_id_t t_old(term_of_var(v));\n             term_id_t t_new = build_dag_term(out_ttbl, solver.get_class(t_old), \n                                               solver, \n                                               out_ttbl, stack, cache);\n             out_vmap [v] = t_new;\n\t     add_rev_var_map(out_rvmap, t_new, v);\n           }\n           for(auto p : o._var_map) {\n             variable_t v(p.first);\n             if (out_vmap.find(v) != out_vmap.end()) \n               continue;\n             term_id_t t_old(copy_map [o.term_of_var(v)]);\n             term_id_t t_new = build_dag_term(out_ttbl, solver.get_class(t_old), \n                                               solver, \n                                               out_ttbl, stack, cache);\n             out_vmap [v] = t_new;\n\t     add_rev_var_map(out_rvmap, t_new, v);\t     \n           }\n\n           for(auto p : out_vmap)\n             out_ttbl.add_ref(p.second);\n\n           // Rename the base domains\n           dom_var_alloc_t palloc(_alloc, o._alloc); \n           dom_t x_impl(_impl); \n           dom_t y_impl(o._impl); \n           term_map_t out_map; // map term to dom var\n           std::vector<dom_var_t> out_varnames;\n           for (auto p: out_vmap) {\n             variable_t v = p.first;\n             term_id_t t_new = p.second;\n             dom_var_t vt(palloc.next());\n             out_map.insert(std::make_pair(t_new, vt));\n             // renaming this's base domain\n             auto xit = _var_map.find(v);\n             if (xit != _var_map.end()) {\n               dom_var_t vx = domvar_of_term(xit->second);\n               x_impl.assign(vt, vx);\n             }\n             // renaming o's base domain\n             auto yit = o._var_map.find(v);\n             if (yit != o._var_map.end()) {\n               dom_var_t vy = o.domvar_of_term(yit->second);\n               y_impl.assign(vt, vy);\n             }\n             out_varnames.push_back(vt);\n           }\n\n\t   x_impl.project(out_varnames);\n\t   y_impl.project(out_varnames);\n\t   \n           dom_t x_meet_y = x_impl & y_impl;\n           term_domain_t res(palloc, out_vmap, out_rvmap, out_ttbl, out_map, x_meet_y);\n\n           CRAB_LOG(\"term\", \n                    crab::outs() << \"============ MEET ==================\";\n                    crab::outs() << *this << \"\\n----------------\";\n                    crab::outs() << o << \"\\n----------------\";\n                    crab::outs() << res << \"\\n================\" << \"\\n\");\n           return res;\n         }\n       }\n    \n       // Narrowing\n       term_domain_t operator&&(term_domain_t o) {\t\n         crab::CrabStats::count(getDomainName() + \".count.narrowing\");\n         crab::ScopedCrabStats __st__(getDomainName() + \".narrowing\");\n\n         CRAB_WARN(\"Term narrowing operator replaced with meet\");\n         return *this & o; \n       } \n\n       // Remove a variable from the scope\n       void operator-=(variable_t v) {\n         crab::CrabStats::count(getDomainName() + \".count.forget\");\n         crab::ScopedCrabStats __st__(getDomainName() + \".forget\");\n\n         auto it(_var_map.find(v));\n         if(it != _var_map.end())\n         {\n           term_id_t t = (*it).second;\n           _var_map.erase(it); \n\t   remove_rev_var_map(t, v);\n           deref(t);\n         }\n\t CRAB_LOG(\"term\",\n\t\t  crab::outs() << \"After removing \" << v << \": \" << *this << \"\\n\";);\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 (this->is_bottom()) {\n           return;\n         } else {\n           //dom_linexp_t dom_e(rename_linear_expr(e));\n           term_id_t tx(build_linexpr(e));\n           rebind_var(x, tx);\n\n           check_terms(__LINE__);\n\n           CRAB_LOG(\"term\", \n                    crab::outs() << \"*** Assign \" << x << \":=\" << e << \":\" << *this << \"\\n\");\n           return;\n         }\n       }\n\n       // Apply operations to variables.\n\n       // x = y op z\n       void apply(operation_t op, variable_t x, variable_t y, variable_t z){\t\n         crab::CrabStats::count(getDomainName() + \".count.apply\");\n         crab::ScopedCrabStats __st__(getDomainName() + \".apply\");\n         check_terms(__LINE__);\n         if (this->is_bottom()) {\n           return;   \n         } else {\n           term_id_t tx(build_term(op, term_of_var(y), term_of_var(z)));\n           rebind_var(x, tx);\n         }\n         check_terms(__LINE__);\n         CRAB_LOG(\"term\", \n                  crab::outs() << \"*** \" << x << \":=\" <<  y <<  \" \" <<  op <<  \" \"\n                               <<  z <<  \":\" <<  *this << \"\\n\");\n       }\n    \n       // x = y op k\n       void apply(operation_t op, variable_t x, variable_t y, number_t k){\t\n         crab::CrabStats::count(getDomainName() + \".count.apply\");\n         crab::ScopedCrabStats __st__(getDomainName() + \".apply\");\n\n         if (this->is_bottom()) {\n           return;   \n         } else {\n           term_id_t tx(build_term(op, term_of_var(y), term_of_const(k)));\n           rebind_var(x, tx);\n         }\n         check_terms(__LINE__);\n         CRAB_LOG(\"term\",\n                  crab::outs() << \"*** \" << x << \":=\" << y << \" \" << op << \" \"\n\t\t               << k <<  \":\" << *this << \"\\n\");\n         return;\n       }\n\n       void backward_assign(variable_t x, linear_expression_t e,\n\t\t\t     term_domain_t inv) {\n\t crab::CrabStats::count(getDomainName() + \".count.backward_assign\");\n\t crab::ScopedCrabStats __st__(getDomainName() + \".backward_assign\");\n\t \n\t crab::domains::BackwardAssignOps<term_domain_t>::\n\t   assign(*this, x, e, inv);\n       }\n       \n       void backward_apply(operation_t op,\n\t\t\t    variable_t x, variable_t y, number_t z,\n\t\t\t    term_domain_t inv) {\n\t crab::CrabStats::count(getDomainName() + \".count.backward_apply\");\n\t crab::ScopedCrabStats __st__(getDomainName() + \".backward_apply\");\n\t \n\t crab::domains::BackwardAssignOps<term_domain_t>::\n\t   apply(*this, op, x, y, z, inv);\n       }\n      \n       void backward_apply(operation_t op,\n\t\t\t   variable_t x, variable_t y, variable_t z,\n\t\t\t   term_domain_t inv) {\n\t crab::CrabStats::count(getDomainName() + \".count.backward_apply\");\n\t crab::ScopedCrabStats __st__(getDomainName() + \".backward_apply\");\n\t \n\t crab::domains::BackwardAssignOps<term_domain_t>::\n\t   apply(*this, op, x, y, z, inv);\n       }\n       \n       void operator+=(linear_constraint_t cst) {  \n         crab::CrabStats::count(getDomainName() + \".count.add_constraints\");\n         crab::ScopedCrabStats __st__(getDomainName() + \".add_constraints\");\n\n         CRAB_LOG(\"term\",\n\t\t  crab::outs() << \"*** Before assume \" << cst << \":\" << *this << \"\\n\");\n\t \n         typedef std::pair<variable_t,variable_t> pair_var_t;\n\n         if (boost::optional<pair_var_t> eq = get_eq_or_diseq(cst)) {\n           term_id_t tx(term_of_var((*eq).first));\n           term_id_t ty(term_of_var((*eq).second));\n           if (cst.is_disequation()) {\n\t     if (tx == ty) {\n\t       set_to_bottom();\n\t       CRAB_LOG(\"term\",\n\t\t\tcrab::outs() << \"*** After assume \" << cst << \":\" <<  *this << \"\\n\");\n\t       return;\n\t     }\n           } else {\n             // not bother if they are already equal\n             if (tx == ty) return; \n             \n             // congruence closure to compute equivalence classes\n             term::congruence_closure_solver<ttbl_t> solver(&_ttbl);\n             std::vector<std::pair<term_id_t, term_id_t> > eqs = { std::make_pair(tx,ty) };\n             solver.run(eqs);\n\t     \n             std::vector<int> stack;\n             std::map <int, term_id_t> cache;\n             dom_t x_impl(_impl); \n             std::vector<dom_var_t> out_varnames;\n             // new map from variable to an acyclic term\n             // and also renaming of the base domain\n             for(auto p : _var_map) {\n               variable_t v(p.first);\n               term_id_t t_old(term_of_var(v));\n               term_id_t t_new = build_dag_term(_ttbl, solver.get_class(t_old), \n                                                 solver, \n                                                 _ttbl, stack, cache);\n\n               dom_var_t vt = domvar_of_term(t_new);\n               dom_var_t vx = domvar_of_term(t_old);\n\t       \n               out_varnames.push_back(vt);\n               x_impl.assign(vt, vx);\n\n               rebind_var(v, t_new);\n             }\n\t     x_impl.project(out_varnames);\n             std::swap(_impl, x_impl);\n           }\n         }\n\n         dom_lincst_t cst_rn(rename_linear_cst(cst));\n         _impl += cst_rn;\n         // Possibly tightened some variable in cst\n         for(auto v : cst.expression().variables()) {\n\t   CRAB_LOG(\"term-normalization\",\n\t\t    crab::outs() << \"Added to the normalization queue \" \n\t\t                  << \"t\" << term_of_var(v)\n\t\t                  << \"[\" << domvar_of_term(term_of_var(v)) << \"] \"\n\t\t                  << \"from variable \" << v << \"\\n\";);\n           changed_terms.insert(term_of_var(v));\n         }\n\n         // Probably doesn't need to done so eagerly.\n         normalize();\n\n         CRAB_LOG(\"term\", crab::outs() << \"*** After assume \" << cst << \":\" << *this << \"\\n\");\n         return;\n       }\n\n       void operator+=(linear_constraint_system_t csts) {\n         for(auto cst: csts) {\n           this->operator+=(cst);\n         }\n       }\n              \n       /*\n       // If the children of t have changed, see if re-applying\n       // the definition of t tightens the domain.\n       void tighten_term(term_id_t t)\n       {\n       dom_t tight = _impl&eval_ftor_copy(_impl, _ttbl, t); \n      \n       if(!(_impl <= tight))\n       {\n       // Applying the functor has changed the domain\n       _impl = tight;\n       for(term_id_t p : _ttbl.parents(t))\n       tighten_term(p);\n       }\n       check_terms(__LINE__);\n       }\n       */\n    \n       interval_t operator[](variable_t x) { \n         crab::CrabStats::count(getDomainName() + \".count.to_intervals\");\n         crab::ScopedCrabStats __st__(getDomainName() + \".to_intervals\");\n\n         // Needed for accuracy\n         normalize();\n\n         if (is_bottom()) return interval_t::bottom();\n\n         auto it = _var_map.find (x);\n         if (it == _var_map.end()) \n           return interval_t::top();\n      \n         dom_var_t dom_x = domvar_of_term(it->second);\n\n         return _impl[dom_x];\n       } \n\n       void set(variable_t x, interval_t intv){\n         crab::CrabStats::count(getDomainName() + \".count.assign\");\n         crab::ScopedCrabStats __st__(getDomainName() + \".assign\");\n\n         rebind_var(x, term_of_itv(intv.lb(), intv.ub()));\n       }\n        \n       void apply(int_conv_operation_t /*op*/, variable_t dst, variable_t src){  \n         // since reasoning about infinite precision we simply assign and\n         // ignore the widths.\n         assign(dst, src);\n       }\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         if (this->is_bottom()) {\n           return;   \n         } else {\n           term_id_t tx(build_term(op, term_of_var(y), term_of_var(z)));\n           rebind_var(x, tx);\n         }\n         check_terms(__LINE__);\n         CRAB_LOG(\"term\", \n                  crab::outs() << \"*** \" << x << \":=\" << y << \" \" << op \n                               << \" \" << z << \":\" << *this << \"\\n\");\n       }\n    \n       void apply(bitwise_operation_t op, variable_t x, variable_t y, number_t k){\n         crab::CrabStats::count(getDomainName() + \".count.apply\");\n         crab::ScopedCrabStats __st__(getDomainName() + \".apply\");\n\n         if (this->is_bottom()) {\n           return;   \n         } else {\n           term_id_t tx(build_term(op, term_of_var(y), term_of_const(k)));\n           rebind_var(x, tx);\n         }\n\n         check_terms(__LINE__);\n         CRAB_LOG(\"term\", \n                  crab::outs() << \"*** \" << x << \":=\" << y << \" \"<< op << \" \" << k \n                               << \":\" << *this << \"\\n\");\n         return;\n       }\n\n       /* Array operations */\n\n       virtual void array_init(variable_t /*a*/,\n\t\t\t\tlinear_expression_t /*elem_size*/,\n\t\t\t\tlinear_expression_t /*lb_idx*/,\n\t\t\t\tlinear_expression_t /*ub_idx*/, \n\t\t\t\tlinear_expression_t /*val*/) override {\n\t // TODO: perform a loop of array stores if [lb_idx, ub_idx]\n\t //       is finite.\n       }\n\t \n       virtual void array_load(variable_t lhs,\n\t\t\t\tvariable_t a, linear_expression_t /*elem_size*/,\n\t\t\t\tlinear_expression_t i) override {\n\t crab::CrabStats::count(getDomainName() + \".count.array_read\");\n\t crab::ScopedCrabStats __st__(getDomainName() + \".array_read\");\n\n\t if (this->is_bottom()) {\n\t   return;   \n\t } else {\n\t   /** \n\t    *  We treat the array load as an uninterpreted function\n \t    *  lhs := array_load(a, i) -->  lhs := f(a,i)\n\t    */\n\t   term_id_t t_uf(build_function(term_of_var(a), build_linexpr(i)));\n\t   rebind_var(lhs, t_uf);\n\t }\n\t check_terms(__LINE__);\n\t CRAB_LOG(\"term\",\n\t\t  crab::outs() << lhs << \":=\" << a <<\"[\" << i << \"]  -- \" << *this <<\"\\n\";);\n       }\n\n       virtual void array_store(variable_t a, linear_expression_t /*elem_size*/,\n\t\t\t\t linear_expression_t i, linear_expression_t val, \n\t\t\t\t bool /*is_strong_update*/) override {\n\t crab::CrabStats::count(getDomainName() + \".count.array_store\");\n\t crab::ScopedCrabStats __st__(getDomainName() + \".array_store\");\n\n\t if (this->is_bottom()) {\n\t   return;   \n\t } else {\n\t   auto &vfac = a.name().get_var_factory();\n\t   /**\n\t    *  We treat the array store as an uninterpreted function\n\t    *  array_store(a, i, val) -->  tmp := f(a,i); assume(tmp == val);\n\t    */\n\t   /// -- tmp := f(a,i)\n\t   term_id_t t_uf(build_function(term_of_var(a), build_linexpr(i)));\n\t   // map always t_uf to the same variable tmp\n\t   variable_t tmp(vfac.get(t_uf));\n\t   // forget tmp\n\t   this->operator-=(tmp);\n\t   // forget the old value for t_uf, otherwise we can get\n\t   // incorrectly bottom when we add the constraint val == tmp.\n\t   _impl -= domvar_of_term(t_uf);\n\t   rebind_var(tmp, t_uf);\n\t   /// -- assume(tmp == val)\n\t   this->operator+=(val == tmp);\n\t }\n\t check_terms(__LINE__);\n\t CRAB_LOG(\"term\",\n\t\t  crab::outs() << a << \"[\" << i << \"]:=\" << val << \" -- \" << *this <<\"\\n\";);\n       }\n\n       virtual void array_store(variable_t a_new, variable_t a_old,\n\t\t\t\tlinear_expression_t /*elem_size*/,\n\t\t\t\tlinear_expression_t i, linear_expression_t val, \n\t\t\t\tbool /*is_strong_update*/) override {\n\t CRAB_WARN(\"array_store in the term domain not implemented\");\n       }\n\n       virtual void array_store_range(variable_t a, linear_expression_t elem_size,\n\t\t\t\t      linear_expression_t i, linear_expression_t j,\n\t\t\t\t      linear_expression_t v) override {\n\t // do nothing\n       }                  \n\n       virtual void array_store_range(variable_t a_new, variable_t a_old,\n\t\t\t\t      linear_expression_t elem_size,\n\t\t\t\t      linear_expression_t i, linear_expression_t j,\n\t\t\t\t      linear_expression_t v) override {\n\t // do nothing\n       }                  \n       \n       virtual void array_assign(variable_t lhs, variable_t rhs) override {\n\t // do nothing\n       }\n\n       // backward array operations\n       void backward_array_init(variable_t a, linear_expression_t elem_size,\n\t\t\t\tlinear_expression_t lb_idx, linear_expression_t ub_idx, \n\t\t\t\tlinear_expression_t val, term_domain_t invariant) {\n       }      \n       void backward_array_load(variable_t lhs,\n\t\t\t\tvariable_t a, linear_expression_t elem_size,\n\t\t\t\tlinear_expression_t i, term_domain_t invariant) {\n\t *this -= lhs;\n       }\n       void backward_array_store(variable_t a, linear_expression_t elem_size,\n\t\t\t\t linear_expression_t i, linear_expression_t v, \n\t\t\t\t bool is_strong_update, term_domain_t invariant) {\n       }\n       void backward_array_store(variable_t a_new, variable_t a_old,\n\t\t\t\t linear_expression_t elem_size,\n\t\t\t\t linear_expression_t i, linear_expression_t v, \n\t\t\t\t bool is_strong_update, term_domain_t invariant) {\n       }       \n       void backward_array_store_range(variable_t a, linear_expression_t elem_size,\n\t\t\t\t       linear_expression_t i, linear_expression_t j,\n\t\t\t\t       linear_expression_t v, term_domain_t invariant) {\n       }\n       void backward_array_store_range(variable_t a_new, variable_t a_old,\n\t\t\t\t       linear_expression_t elem_size,\n\t\t\t\t       linear_expression_t i, linear_expression_t j,\n\t\t\t\t       linear_expression_t v, term_domain_t invariant) {\n       }           \n       void backward_array_assign(variable_t lhs, variable_t rhs, term_domain_t invariant) {\n       }\n       \n       /* \n\t  Begin unimplemented operations \n\t  \n\t  term_domain implements only standard abstract operations of\n\t  a numerical domain plus some array operations.  The\n\t  implementation of boolean and pointer operations is empty\n\t  because they should never be called.\n       */\n       \n       // boolean operations\n       void assign_bool_cst(variable_t lhs, linear_constraint_t rhs) {}\n       void assign_bool_var(variable_t lhs, variable_t rhs, bool is_not_rhs) {}\n       void apply_binary_bool(bool_operation_t op,\n\t\t\t      variable_t x,variable_t y,variable_t z) {}\n       void assume_bool(variable_t v, bool is_negated) {}\n       // backward boolean operations\n       void backward_assign_bool_cst(variable_t lhs, linear_constraint_t rhs,\n\t\t\t\t     term_domain_t invariant){}\n       void backward_assign_bool_var(variable_t lhs, variable_t rhs, bool is_not_rhs,\n\t\t\t\t     term_domain_t invariant) {}\n       void backward_apply_binary_bool(bool_operation_t op,\n\t\t\t\t       variable_t x,variable_t y,variable_t z,\n\t\t\t\t       term_domain_t invariant) {}\n       // pointer operations\n       void pointer_load(variable_t lhs, variable_t rhs)  {}\n       void pointer_store(variable_t lhs, variable_t rhs) {} \n       void pointer_assign(variable_t lhs, variable_t rhs, linear_expression_t offset) {}\n       void pointer_mk_obj(variable_t lhs, ikos::index_t address) {}\n       void pointer_function(variable_t lhs, varname_t func) {}\n       void pointer_mk_null(variable_t lhs) {}\n       void pointer_assume(pointer_constraint_t cst) {}\n       void pointer_assert(pointer_constraint_t cst) {}\n       /* End unimplemented operations */\n\n      void rename(const variable_vector_t &from, const variable_vector_t &to) {\n\t crab::CrabStats::count(getDomainName() + \".count.rename\");\n\t crab::ScopedCrabStats __st__(getDomainName() + \".rename\");\n\t\n\tif (is_top() || is_bottom()) return;\n\t\n\t// renaming _var_map by creating a new map since we are\n\t// modifying the keys.\n\tCRAB_LOG(\"term\",\n\t\t crab::outs() << \"Replacing {\";\n\t\t for (auto v: from) crab::outs() << v << \";\";\n\t\t crab::outs() << \"} with \";\n\t\t for (auto v: to) crab::outs() << v << \";\";\n\t\t crab::outs() << \"}:\\n\";\n\t\t crab::outs() << *this << \"\\n\";);\n\t\n\tvar_map_t new_var_map;\n\trev_var_map_t new_rev_var_map;\n\tfor (auto kv: _var_map) {\n\t  ptrdiff_t pos = std::distance(from.begin(),\n\t\t\t\t\tstd::find(from.begin(), from.end(), kv.first));\n\t  if (pos < from.size()) {\n\t    variable_t new_v(to[pos]);\n\t    new_var_map.insert(std::make_pair(new_v, kv.second));\n\t    add_rev_var_map(new_rev_var_map, kv.second, new_v);\n\t  } else {\n\t    new_var_map.insert(kv);\n\t    add_rev_var_map(new_rev_var_map, kv.second, kv.first);\n\t  }\n\t}\n\tstd::swap(_var_map, new_var_map);\n\tstd::swap(_rev_var_map, new_rev_var_map);\n\t\n\tCRAB_LOG(\"term\",\n\t\t crab::outs() << \"RESULT=\" << *this << \"\\n\");\n      }\n       \n       // extract operation is used during reduction with other domains.       \n       void extract(const variable_t& x, linear_constraint_system_t& csts,\n\t\t    bool only_equalities /*unused*/) {\n         crab::CrabStats::count(getDomainName() + \".count.extract\");\n         crab::ScopedCrabStats __st__(getDomainName() + \".extract\");\n\n         if (!is_normalized()) normalize();\n\n         if (is_bottom()) {\n\t   return;\n\t }\n\n\t // TODO: make user parameter\n\t const unsigned max_eq = 10;\n\t // We limit the number of equalities via\n\t // constants. Otherwise, the number of equalities can be too\n\t // large (e.g., with domains like array_expansion) and it\n\t // would make the reduction very slow.\n\t \n         // Extract equalities\n         auto it = _var_map.find(x);\n         if (it != _var_map.end()) {\n           term_id_t tx = it->second;\n\t   auto tx_ptr = _ttbl.get_term_ptr(tx);\n\n\t   bool active_threshold = false;\n\t   if(tx_ptr->kind() == term::TERM_CONST) {\n\t     active_threshold = true;\n\t   }\n\t   auto &varset = _rev_var_map[tx];\n\t   unsigned num_eq = 0;\n\t   for (auto var: varset) {\n\t     if (active_threshold && num_eq > max_eq) {\n\t       return;\n\t     }\n\t     if (var.index() != x.index()) {\n\t       num_eq++;\n\t       linear_constraint_t cst(linear_expression_t(x) == linear_expression_t(var));\n\t       CRAB_LOG(\"terms\", crab::outs() << \"Extracting \" << cst << \"\\n\";);\n\t       csts += cst;\t       \n\t     }\n\t   }\n\t   \n\t }\n       }\n       \n       void forget(const variable_vector_t& variables) {\n         if (is_bottom() || is_top()) return;\n         \n         for (auto v:  variables) {\n           *this -= v;\n\t }\n       }\n\n       void project(const variable_vector_t& variables) {\n         crab::CrabStats::count(getDomainName() + \".count.project\");\n         crab::ScopedCrabStats __st__(getDomainName() + \".project\");\n\n         if (is_bottom() || is_top()) return;\n\n\t if (variables.empty()) {\n\t   set_to_top();\n\t   return;\n\t }\n\t \n         std::set<variable_t> s1,s2;\n\t variable_vector_t s3;\n         for (auto p: _var_map) s1.insert(p.first);\n         s2.insert(variables.begin(), variables.end());\n         std::set_difference(s1.begin(), s1.end(), s2.begin(), s2.end(),\n\t\t\t     std::back_inserter(s3));\n         forget(s3);\n       }\n\n       void expand(variable_t x, variable_t y) {\n         crab::CrabStats::count(getDomainName() + \".count.expand\");\n         crab::ScopedCrabStats __st__(getDomainName() + \".expand\");\n\n         if (is_bottom() || is_top()) {\n           return;\n         }\n\t \n\t linear_expression_t e(x);\n\t term_id_t tx(build_linexpr(e));\n\t rebind_var(y, tx);\n\t \n\t check_terms(__LINE__);\n       }\n\n       // Propagate information from tightened terms to\n       // parents/children.\n       void normalize() { \n         crab::CrabStats::count(getDomainName() + \".count.normalize\");\n         crab::ScopedCrabStats __st__(getDomainName() + \".normalize\");\n         TermNormalizer<Info, typename Info::domain_t>::normalize(*this); \n       }\n       \n      void minimize() {}       \n       \n       /// XXX: should be part of array_sgraph_domain_traits\n       /// Simplify the term associated with x by given the standard\n       /// arithmetic meaning to the functors\n       bool simplify(variable_t x)  {\n\t crab::CrabStats::count(getDomainName() + \".count.simplify\");\n\t crab::ScopedCrabStats __st__(getDomainName() + \".simplify\");\n       \n         auto it = _var_map.find (x);\n         if(it != _var_map.end())\n         {\n           term_id_t t = it->second;\n           simplifier_t simp(_ttbl);\n           auto nt = simp.simplify_term(t);  \n           if (nt) \n           {\n             rebind_var(x, *nt); \n             return true;\n           }\n         }\n         return false;\n       }\n\n       // Output function\n       void write(crab_os& o) {\n\t crab::CrabStats::count(getDomainName() + \".count.write\");\n\t crab::ScopedCrabStats __st__(getDomainName() + \".write\");\n\t \n         // Normalization is not enforced in order to maintain accuracy\n         // but we force it to display all the relationships.\n         normalize();\n\n         if(is_bottom()){\n           o << \"_|_\";\n           return;\n         }\n         if(_var_map.empty()) {\n           o << \"{}\";\n           return;\n         }      \n\n         bool first = true;\n         o << \"{\" ;\n         for(auto p : _var_map)\n         {\n           if(first)\n             first = false;\n           else\n             o << \", \";\n           o << p.first << \" -> t\" << p.second\n             << \"[\" << domvar_of_term(p.second) << \"]\";\n         }\n         o << \"}\";\n     \n         // print underlying domain\n         o << _impl;\n\n         #ifdef VERBOSE\n         /// For debugging purposes     \n         o << \" ttbl={\" << _ttbl << \"}\\n\";\n         #endif \n       }\n\n       linear_constraint_system_t to_linear_constraint_system() {\n\t crab::CrabStats::count(getDomainName() + \".count.to_linear_constraint_system\");\n\t crab::ScopedCrabStats __st__(getDomainName() + \".to_linear_constraint_system\");\n\t \n         // Collect the visible terms\n         rev_map_t rev_map;\n         std::vector< std::pair<variable_t, variable_t> > equivs;\n         for(auto p : _var_map)\n         {\n           dom_var_t dv = domvar_of_term(p.second);\n\n           auto it = rev_map.find(dv);\n           if(it == rev_map.end()){\n             // The term has not yet been seen.\n             rev_map.insert(std::make_pair(dv, p.first));\n           } else {\n             // The term is already mapped to (*it).second,\n             // so add an equivalence.\n             equivs.push_back(std::make_pair((*it).second, p.first)); \n           }\n         }\n\n         // Create a copy of _impl with only visible variables.\n         dom_t d_vis(_impl);\n         for(auto p : _term_map) {\n           dom_var_t dv = p.second;\n           if(rev_map.find(dv) == rev_map.end())\n             d_vis -= dv;\n         }\n\n         // Now build and rename the constraint system, plus equivalences.\n         dom_linsys_t dom_sys(d_vis.to_linear_constraint_system());\n\n         linear_constraint_system_t out_sys; \n         for(dom_lincst_t cst : dom_sys) {\n           auto out_cst = rename_linear_cst_rev(cst, rev_map);\n           if (!out_cst) continue;\n           out_sys += *out_cst;\n         }\n      \n         for(auto p : equivs) {\n           CRAB_LOG(\"term\", \n                    crab::outs() << \"Added equivalence \" << p.first << \"=\" << p.second << \"\\n\");\n           out_sys += (p.first - p.second == 0);\n         }\n\n         // Now rename it back into the external scope.\n         return out_sys;\n       }\n\n       disjunctive_linear_constraint_system_t to_disjunctive_linear_constraint_system() {\n\t auto lin_csts = to_linear_constraint_system();\n\t if (lin_csts.is_false()) {\n\t   return disjunctive_linear_constraint_system_t(true /*is_false*/); \n\t } else if (lin_csts.is_true()) {\n\t   return disjunctive_linear_constraint_system_t(false /*is_false*/);\n\t } else {\n\t   return disjunctive_linear_constraint_system_t(lin_csts);\n\t }\n       }\n       \n       static std::string getDomainName() { \n         std::string name(\"Term(\" + dom_t::getDomainName() + \")\");\n         return name;\n       }\n\n     }; // class term_domain\n  \n    // Propagate information from tightened terms to\n    // parents/children.\n    template<class Info, class Abs>\n    class TermNormalizer {\n     public:\n      typedef typename term_domain<Info>::term_domain_t term_domain_t;\n      typedef typename term_domain_t::term_id_t term_id_t;\n      typedef Abs dom_t;\n      typedef typename term_domain_t::ttbl_t ttbl_t;\n      typedef boost::container::flat_set< term_id_t > term_set_t;\n      \n      static void queue_push(ttbl_t& tbl, std::vector< std::vector<term_id_t> >& queue,\n\t\t\t     term_id_t t) {\n        int d = tbl.depth(t);\n\tif (d == 0) {\n\t  // if depth 0 then t is a free variable: nothing to propagate.\n\t  return;\n\t}\n        while(queue.size() <= d) {\n\t  queue.push_back(std::vector<term_id_t>());\n\t}\n        queue[d].push_back(t);\n      }\n      \n      static void normalize(term_domain_t& abs){\n        // First propagate down, then up.   \n        std::vector< std::vector< term_id_t > > queue;\n        \n        ttbl_t& ttbl(abs._ttbl);\n        dom_t& impl = abs._impl;\n        \n        for(term_id_t t : abs.changed_terms)\n        {\n          queue_push(ttbl, queue, t);\n        }\n        \n        dom_t d_prime = impl;\n        // Propagate information to children.\n        // Don't need to propagate level 0, since it's for free variables\n        for(int d = queue.size()-1; d > 0; d--)\n        {\t  \n          for(term_id_t t : queue[d])\n          {\n            typename ttbl_t::term_t* t_ptr = ttbl.get_term_ptr(t);\n            if(t_ptr->kind() != term::TERM_APP)\n              continue;\n\n\t    CRAB_LOG(\"term-normalization\",\n\t\t     crab::outs() << \"Propagate to children \";\n\t\t     t_ptr->write(crab::outs());\n\t\t     crab::outs() << \"\\n\";\n\t\t     crab::outs() << \"\\tTerm table: \";\n\t\t     ttbl.write(crab::outs());\n\t\t     crab::outs() << \"\\n\";);\n\t    \n            abs.eval_ftor_down(d_prime, ttbl, t);\n            if(!(abs._impl <= d_prime))\n            {\n              impl = d_prime;\n\t      \n\t      CRAB_LOG(\"term-normalization\",\n\t\t       crab::outs() << \"\\trefinement done: enqueue children.\\n\";\n\t\t       if (impl.is_bottom()) {\n\t\t\t crab::outs() << \"\\tfound bottom\\n\";\n\t\t       });\n\t      \n\t      \n              // Enqueue the args.\n              typename ttbl_t::term_t* t_ptr = ttbl.get_term_ptr(t); \n              std::vector<term_id_t>& args(term::term_args(t_ptr));\n              for(term_id_t c : args)\n              {\n                if(abs.changed_terms.find(c) == abs.changed_terms.end())\n                {\n                  abs.changed_terms.insert(c);\n                  queue[ttbl.depth(c)].push_back(c);\n                }\n              }\n            } else {\n\t      CRAB_LOG(\"term-normalization\",\n\t\t       crab::outs() << \"\\tno refinement done.\\n\";);\n\t      \n\t    }\n          }\n        }\n        \n        // Collect the parents of changed terms.\n        term_set_t up_terms;\n        std::vector< std::vector<term_id_t> > up_queue;\n        for(term_id_t t : abs.changed_terms)\n        {\n          for(term_id_t p : ttbl.parents(t))\n          {\n            if(up_terms.find(p) == up_terms.end())\n            {\n              up_terms.insert(p);\n\t      CRAB_LOG(\"term-normalization\",\n\t\t       crab::outs() << \"t\" << p << \"[\" << abs.domvar_of_term(p) << \"]\"\n\t\t                     << \" is a parent of \"\n\t\t                     << \"t\" << t << \"[\" << abs.domvar_of_term(t) << \"]\\n\";\n\t\t       );\n              queue_push(ttbl, up_queue, p);\n            }\n          }\n        }\n        \n        // Now propagate up, level by level.\n        // This may miss inferences; for example with [[x = y - z]]\n        // information about y can propagate to z.\n        assert(up_queue.size() == 0 || up_queue[0].size() == 0);\n        for(int d = 1; d < up_queue.size(); d++)\n        {\n          // up_queue[d] shouldn't change.\n          for(term_id_t t : up_queue[d])\n          {\n            abs.eval_ftor(d_prime, ttbl, t);\n\t    CRAB_LOG(\"term-normalization\",\n\t\t     typename ttbl_t::term_t* t_ptr = ttbl.get_term_ptr(t);\n\t\t     crab::outs() << \"Propagate to parent \";\n\t\t     t_ptr->write(crab::outs());\n\t\t     crab::outs() << \"\\n\";\n\t\t     crab::outs() << \"\\tTerm table: \";\n\t\t     ttbl.write(crab::outs());\n\t\t     crab::outs() << \"\\n\";);\n\t    \n            if(!(impl <= d_prime))\n            {\n\t      CRAB_LOG(\"term-normalization\",\n\t\t       crab::outs() << \"Before up propagation: \" << impl << \"\\n\";\n\t\t       crab::outs() << \"After up propagation : \" << d_prime << \"\\n\";);\n\t      \n              // We need to do a meet here, as\n              // impl and F(stmt)impl may be\n              // incomparable\n              impl = impl&d_prime;\n              //impl = d_prime; // Old code\n\n\t      CRAB_LOG(\"term-normalization\",\n\t\t       crab::outs() << \"\\trefinement done: enqueue parents.\\n\";\n\t\t       if (impl.is_bottom()) {\n\t\t\t crab::outs() << \"\\tfound bottom\\n\";\n\t\t       });\n\t\t       \n\t      \n              for(term_id_t p : ttbl.parents(t))\n              {\n                if(up_terms.find(p) == up_terms.end())\n                {\n                  up_terms.insert(p);\n                  queue_push(ttbl, up_queue, p);\n                }\n              }\n            } else {\n\t      CRAB_LOG(\"term-normalization\",\n\t\t       crab::outs() << \"\\tno refinement done.\\n\";);\n\t    }\n          }\n        }\n        \n        abs.changed_terms.clear();\n        \n        if (abs._impl.is_bottom())\n          abs.set_to_bottom();\n      }\n    };\n\n    // Specialized implementation for interval domain.\n    // GKG: Should modify to work with any independent attribute domain.\n    #ifdef USE_TERM_INTERVAL_NORMALIZER\n    template<class Info, class Num, class Var>\n    class TermNormalizer<Info, interval_domain<Num, Var> > {\n     public:\n      typedef typename term_domain<Info>::term_domain_t term_domain_t;\n      typedef typename term_domain_t::term_id_t term_id_t;\n      typedef interval_domain<Num, Var> dom_t;\n      typedef typename term_domain_t::dom_var_t var_t;\n      \n      typedef typename term_domain_t::ttbl_t ttbl_t;\n      typedef boost::container::flat_set< term_id_t > term_set_t;\n      \n      typedef typename dom_t::interval_t interval_t;\n      \n      static void queue_push(ttbl_t& tbl, std::vector< std::vector<term_id_t> >& queue,\n\t\t\t     term_id_t t) {\n        int d = tbl.depth(t);\n\tif (d == 0) {\n\t  // if depth 0 then t is a free variable: nothing to\n\t  // propagate.\n\t  return;\n\t}\n        while(queue.size() <= d) {\n          queue.push_back(std::vector<term_id_t>());\n\t}\n        queue[d].push_back(t);\n      }\n      \n      static void normalize(term_domain_t& abs){\n        // First propagate down, then up.\n        std::vector< std::vector< term_id_t > > queue;\n        \n        ttbl_t& ttbl(abs._ttbl);\n        dom_t& impl = abs._impl;\n        if(impl.is_bottom())\n        {\n          abs.set_to_bottom();\n          return;\n        }\n        \n        for(term_id_t t : abs.changed_terms)\n        {\n          queue_push(ttbl, queue, t);\n        }\n        \n        // Propagate information to children.\n        // Don't need to propagate level 0, since it's for free variables\n        for(int d = queue.size()-1; d > 0; d--)\n        {\n          for(term_id_t t : queue[d])\n          {\n            typename ttbl_t::term_t* t_ptr = ttbl.get_term_ptr(t);\n            if(t_ptr->kind() != term::TERM_APP)\n              continue;\n            \n            std::vector<term_id_t>& args(term::term_args(t_ptr));\n            std::vector<interval_t> arg_intervals;\n            for(term_id_t c : args)\n              arg_intervals.push_back(impl[abs.domvar_of_term(c)]);\n            abs.eval_ftor_down(impl, ttbl, t);\n            \n            // Enqueue the args\n            for(size_t ci  = 0; ci < args.size(); ci++)\n            {\n              term_id_t c(args[ci]);\n              var_t v = abs.domvar_of_term(c);\n              interval_t v_upd(impl[v]);\n              if(!(arg_intervals[ci] <= v_upd))\n              {\n                impl.set(v, arg_intervals[ci]&v_upd);\n                if(abs.changed_terms.find(c) == abs.changed_terms.end())\n                {\n                  abs.changed_terms.insert(c);\n                  queue[ttbl.depth(c)].push_back(c);\n                }\n              }\n            }\n          }\n        }\n        \n        // Collect the parents of changed terms.\n        term_set_t up_terms;\n        std::vector< std::vector<term_id_t> > up_queue;\n        for(term_id_t t : abs.changed_terms)\n        {\n          for(term_id_t p : ttbl.parents(t))\n          {\n            if(up_terms.find(p) == up_terms.end())\n            {\n              up_terms.insert(p);\n              queue_push(ttbl, up_queue, p);\n            }\n          }\n        }\n        \n        // Now propagate up, level by level.\n        assert(up_queue.size() == 0 || up_queue[0].size() == 0);\n        for(int d = 1; d < up_queue.size(); d++)\n        {\n          // up_queue[d] shouldn't change.\n          for(term_id_t t : up_queue[d])\n          {\n            var_t v = abs.domvar_of_term(t);\n            interval_t v_interval = impl[v];\n            \n            abs.eval_ftor(impl, ttbl, t);\n            \n            interval_t v_upd = impl[v];\n            if(!(v_interval <= v_upd))\n            {\n              impl.set(v, v_interval&v_upd);\n              for(term_id_t p : ttbl.parents(t))\n              {\n                if(up_terms.find(p) == up_terms.end())\n                {\n                  up_terms.insert(p);\n                  queue_push(ttbl, up_queue, p);\n                }\n              }\n            }\n          }\n        }\n        \n        abs.changed_terms.clear();\n        \n        if (impl.is_bottom())\n          abs.set_to_bottom();\n      }\n    };\n    #endif\n\n\n    template<typename Info>    \n    struct abstract_domain_traits<term_domain<Info>> {\n      typedef typename Info::Number number_t;\n      typedef typename Info::VariableName varname_t;\n    };\n    \n    template<typename Info>    \n    class reduced_domain_traits<term_domain<Info>> {\n    public:\n      typedef term_domain<Info> term_domain_t;\n      typedef typename term_domain_t::variable_t variable_t;\n      typedef typename term_domain_t::linear_constraint_system_t linear_constraint_system_t;\n      \n      static void extract(term_domain_t& dom, const variable_t& x,\n\t\t\t  linear_constraint_system_t& csts, bool only_equalities) {\n       dom.extract(x, csts, only_equalities);\n      }\n    };\n\n  }// namespace domains\n} // namespace crab\n\n#pragma GCC diagnostic pop\n", "meta": {"hexsha": "1bb606b0813b8bffbcb635dec84621c85de7c667", "size": 73358, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/crab/domains/term_equiv.hpp", "max_stars_repo_name": "numairmansur/crab", "max_stars_repo_head_hexsha": "316e3946d3a4d92db638c54fbfa8fb7bee1ebbc7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/crab/domains/term_equiv.hpp", "max_issues_repo_name": "numairmansur/crab", "max_issues_repo_head_hexsha": "316e3946d3a4d92db638c54fbfa8fb7bee1ebbc7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/crab/domains/term_equiv.hpp", "max_forks_repo_name": "numairmansur/crab", "max_forks_repo_head_hexsha": "316e3946d3a4d92db638c54fbfa8fb7bee1ebbc7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.456552372, "max_line_length": 96, "alphanum_fraction": 0.5369966466, "num_tokens": 17668, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.48176622836028216}}
{"text": "\n#pragma once\n\n#include <boost/unordered_map.hpp>\n#include \"utils/bitset2d.hpp\"\n\ntypedef std::symmetric_bitset2d AdjMatrix;\n\nclass Counter\n{\nprotected:\n  unsigned current;\npublic:\n  Counter(const unsigned i): current(i){}\n  unsigned operator*() const { return current; }\n  Counter& operator++() { ++current; return *this; }\n  Counter operator++(int) { return Counter(current++); }\n  bool operator==(const Counter& c) const { return c.current == current; }\n  bool operator!=(const Counter& c) const { return c.current != current; }\n  Counter& operator=(const unsigned i) { current = i; return *this; }\n};\n\nclass AdjMatrixIter\n{\nprotected:\n  const AdjMatrix& m;\n  const unsigned end;\n  const unsigned vertex;\n  unsigned current;\n\n  void fix_current()\n  {\n    while((current < end) && !m.test({vertex, current})) ++current;\n  }\npublic:\n  AdjMatrixIter(const AdjMatrix& _m, const unsigned _vertex, const unsigned _current):\n    m(_m), end(_m.cols()), vertex(_vertex), current(_current)\n  {\n    fix_current();\n  }\n  unsigned operator*() const { return current; }\n  AdjMatrixIter& operator++() { ++current; fix_current(); return *this; }\n  AdjMatrixIter operator++(int)\n  {\n    AdjMatrixIter tmp(m, vertex, current++);\n    fix_current();\n    return tmp;\n  }\n  bool operator==(const AdjMatrixIter& c) const { return c.current == current; }\n  bool operator!=(const AdjMatrixIter& c) const { return c.current != current; }\n  AdjMatrixIter& operator=(const unsigned i) { current = i; fix_current(); return *this; }\n};\n\nstruct AdjIterRange\n{\n  AdjMatrixIter first, second;\n\n  AdjIterRange(const AdjMatrix& _m, const unsigned v):\n    first(_m, v, 0),\n    second(_m, v, _m.cols())\n  {}\n};\n// in the graph, vertices their indices\nclass Graph\n{\npublic:\n  typedef uint32_t Vertex;\n  typedef std::pair<Vertex, Vertex> Edge;\n  typedef std::pair<uint32_t, char> VertexName;\n  typedef Counter VertexIter;\n  typedef std::pair<VertexIter, VertexIter> VertexIterRange;\n  typedef AdjMatrixIter AdjIter;\n\nprotected:\n  boost::unordered_map<VertexName, Vertex> name_to_vertex;\n  AdjMatrix adj;\npublic:\n\n  size_t num_vertices() const\n  {\n    return adj.cols();\n  }\n\n  size_t num_edges() const\n  {\n    return adj.count();\n  }\n\n  unsigned get_index(const Vertex& u) const\n  {\n    return u;\n  }\n\n  Vertex add_vertex()\n  {\n    const Vertex v = adj.cols();\n    adj.resize(v + 1, v + 1);\n    return v;\n  }\n\n  // return the vertex with the specified name or create one if the name does not exist\n  const Vertex& emplace_vertex_by_name(const VertexName& vname)\n  {\n    const auto n2v_iter = name_to_vertex.find(vname);\n    if(n2v_iter == name_to_vertex.end())\n      return name_to_vertex.emplace_hint(n2v_iter, vname, add_vertex())->second;\n    else\n      return n2v_iter->second;\n  }\n\n  void add_edge(const Vertex u, const Vertex v)\n  {\n    adj.set({u,v});\n  }\n\n  template<typename Container = std::vector<Vertex>>\n  void make_clique(const Container& clique)\n  {\n    // translate vertex names to vertices\n    for(auto u_iter = clique.begin(); u_iter != clique.end(); ++u_iter)\n      for(auto v_iter = std::next(u_iter); v_iter != clique.end(); ++v_iter)\n        add_edge(*u_iter, *v_iter);\n  }\n\n  VertexIterRange vertices() const\n  {\n    return VertexIterRange(0, adj.cols());\n  }\n  AdjIterRange adjacent_vertices(const Vertex v) const\n  {\n    return AdjIterRange(adj, v);\n  }\n\n  void isolate_vertex(const Vertex& u)\n  {\n    unsigned v = adj.cols() - 1;\n    do adj.reset({u,v}); while(v-- != 0);\n  }\n};\n\n\n", "meta": {"hexsha": "551c39989f78b73ef63002cedd80c4920192115f", "size": 3470, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "utils/graph.hpp", "max_stars_repo_name": "PACE-challenge/phylo_converter", "max_stars_repo_head_hexsha": "47b69017599f473ed584458cffef4bdf2ad5879e", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "utils/graph.hpp", "max_issues_repo_name": "PACE-challenge/phylo_converter", "max_issues_repo_head_hexsha": "47b69017599f473ed584458cffef4bdf2ad5879e", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "utils/graph.hpp", "max_forks_repo_name": "PACE-challenge/phylo_converter", "max_forks_repo_head_hexsha": "47b69017599f473ed584458cffef4bdf2ad5879e", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.4366197183, "max_line_length": 90, "alphanum_fraction": 0.6734870317, "num_tokens": 916, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125848754472, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.4817662251620435}}
{"text": "\ufeff\r\n#include <iostream>\r\n#include <boost/numeric/interval.hpp>\r\n\r\n\r\nint main()\r\n{\r\n\tboost::numeric::interval<int> valid_range(0, 100);\r\n\t\r\n\tint input = 0;\r\n\r\n\tdo\r\n\t{\r\n\t\tstd::cout << valid_range.lower() << \" ~ \" \r\n\t\t\t      << valid_range.upper() << \r\n\t\t\t\t  \" \uc0ac\uc774\uc758 \uac12\uc744 \uc785\ub825\ud574 \uc8fc\uc138\uc694\" << std::endl;\r\n\r\n\t\tstd::cin >> input;\r\n\r\n\t} while (boost::numeric::in(input, valid_range) == false);\r\n\t\r\n\treturn 0;\r\n}\r\n\r\n\r\n", "meta": {"hexsha": "ad764f75fd28eb53df0600ed3f80147dcf1fe16d", "size": 397, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Boost_20140423/interval_01/interval_01.cpp", "max_stars_repo_name": "jacking75/book_semina_samples", "max_stars_repo_head_hexsha": "889bd501b0b4e126e27214bbf2b0ace8825b3783", "max_stars_repo_licenses": ["MIT"], "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_20140423/interval_01/interval_01.cpp", "max_issues_repo_name": "jacking75/book_semina_samples", "max_issues_repo_head_hexsha": "889bd501b0b4e126e27214bbf2b0ace8825b3783", "max_issues_repo_licenses": ["MIT"], "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_20140423/interval_01/interval_01.cpp", "max_forks_repo_name": "jacking75/book_semina_samples", "max_forks_repo_head_hexsha": "889bd501b0b4e126e27214bbf2b0ace8825b3783", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.2692307692, "max_line_length": 60, "alphanum_fraction": 0.5440806045, "num_tokens": 113, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125848754472, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.4817662251620435}}
{"text": "#define EIGEN_USE_MKL_ALL\n#define BOOST_TEST_MODULE test_one\n\n#include <Eigen/Core>\n\n#include <boost/test/included/unit_test.hpp>\n\nusing namespace std;\n\nBOOST_AUTO_TEST_CASE(test_one) {\n\tauto input = Eigen::MatrixXd{ 10, 20 };\n\t\n\tBOOST_CHECK(input.rows() == 10);\n\tBOOST_CHECK(input.cols() == 20);\n}", "meta": {"hexsha": "fc7b7862c47b805d5482cfe77c322068753b655a", "size": 298, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tests/main.cpp", "max_stars_repo_name": "fedeallocati/MachineLearningToolkit", "max_stars_repo_head_hexsha": "8614ee2c8c5211a3eefceb10a50576e0485cefd9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-08-31T11:43:19.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-22T11:03:47.000Z", "max_issues_repo_path": "src/tests/main.cpp", "max_issues_repo_name": "fedeallocati/MachineLearningToolkit", "max_issues_repo_head_hexsha": "8614ee2c8c5211a3eefceb10a50576e0485cefd9", "max_issues_repo_licenses": ["MIT"], "max_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/main.cpp", "max_forks_repo_name": "fedeallocati/MachineLearningToolkit", "max_forks_repo_head_hexsha": "8614ee2c8c5211a3eefceb10a50576e0485cefd9", "max_forks_repo_licenses": ["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.8666666667, "max_line_length": 44, "alphanum_fraction": 0.7416107383, "num_tokens": 76, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.4817662180409596}}
{"text": "#ifndef EMISSIONS_H\n#define EMISSIONS_H\n\n#include <armadillo>\n#include <json.hpp>\n#include <random>\n\nnamespace hsmm {\n\n    class AbstractEmission {\n        public:\n            AbstractEmission(int nstates, int dimension);\n\n            int getNumberStates() const;\n\n            int getDimension() const;\n\n            virtual AbstractEmission* clone() const = 0;\n\n            // Init the parameters from the provided data.\n            virtual void init_params_from_data(int min_duration,\n                    int ndurations, const arma::field<arma::field<\n                    arma::mat>>& mobs) {}\n\n            // Joint loglikelihood of a single segment being generated by a\n            // particular state.\n            virtual double loglikelihood(int state,\n                    const arma::field<arma::mat>& obs) const = 0;\n\n            arma::cube likelihoodCube(int min_duration, int ndurations,\n                    const arma::field<arma::mat>& obs) const;\n\n            // This should return a cube of dimensions (nstates, nobs,\n            // ndurations) where the entry (i, j, k) is the log-likelihood of\n            // the observations in the interval [j, min_duration + k - 1]\n            // being produced by state i.\n            virtual arma::cube loglikelihoodCube(int min_duration,\n                    int ndurations, const arma::field<arma::mat>& obs) const;\n\n            virtual nlohmann::json to_stream() const;\n\n            virtual void from_stream(const nlohmann::json &emission_params);\n\n            // Reestimates in place the emission parameters using the\n            // statistics provided by the HSMM E step. eta(j, d, t) represents\n            // the expected value of state j generating a segment of length\n            // min_duration + d ending at time t.\n            virtual void reestimate(int min_duration,\n                    const arma::field<arma::cube>& meta,\n                    const arma::field<arma::field<arma::mat>>& mobs) = 0;\n\n            arma::field<arma::mat> sampleFromState(int state, int nsegments);\n\n            virtual arma::field<arma::mat> sampleFromState(int state,\n                    int nsegments, std::mt19937 &rng) const = 0;\n        protected:\n\n            // Pseudo-random number generation.\n            std::mt19937 rand_generator_;\n\n        private:\n            int nstates_;\n            int dimension_;\n    };\n\n\n    // For the HSMM online setting (prediction) is required to sample\n    // conditioning on some already seen observations.\n    class AbstractEmissionOnlineSetting : public AbstractEmission {\n        public:\n            AbstractEmissionOnlineSetting(int states, int dimension) :\n                    AbstractEmission(states, dimension) {}\n\n            arma::field<arma::mat> sampleNextObsGivenPastObs(int state,\n                    int seg_dur, const arma::field<arma::mat>& past_obs);\n\n            virtual arma::field<arma::mat> sampleNextObsGivenPastObs(int state,\n                    int seg_dur, const arma::field<arma::mat>& past_obs,\n                    std::mt19937 &rng) const = 0;\n\n            // Useful for transfering some information between consecutive\n            // segments. Equivalent to an Autoregressive setting for sampling.\n            virtual arma::field<arma::mat> sampleFirstSegmentObsGivenLastSegment(\n                    int curr_state, int curr_seg_dur,\n                    const arma::field<arma::mat> &last_segment, int last_state,\n                    std::mt19937 &rng) const;\n\n            arma::field<arma::mat> sampleFirstSegmentObsGivenLastSegment(\n                    int curr_state, int curr_seg_dur, const arma::field<\n                    arma::mat> &last_segment, int last_state);\n    };\n\n\n    // This emission class assumes the observations are conditionally\n    // independent given the duration of the segment and its position on\n    // it (offset).\n    class AbstractEmissionConditionalIIDobs : public AbstractEmission {\n        public:\n            AbstractEmissionConditionalIIDobs(int nstates, int dimension);\n\n            double loglikelihood(int state,\n                    const arma::field<arma::mat>& obs) const;\n\n            virtual double loglikelihoodIIDobs(int state, int seg_dur, int offset,\n                    const arma::mat& single_obs) const = 0;\n    };\n\n\n    class DummyGaussianEmission : public AbstractEmissionOnlineSetting {\n        public:\n            DummyGaussianEmission(arma::vec& means, arma::vec& std_devs);\n\n            DummyGaussianEmission* clone() const;\n\n            double loglikelihood(int state,\n                    const arma::field<arma::mat>& obs) const;\n\n            double loglikelihoodIIDobs(int state, int seg_dur, int offset,\n                    const arma::mat& obs) const;\n\n            virtual nlohmann::json to_stream() const;\n\n            void reestimate(int min_duration,\n                    const arma::field<arma::cube>& meta,\n                    const arma::field<arma::field<arma::mat>>& mobs);\n\n            arma::field<arma::mat> sampleFromState(int state, int size,\n                    std::mt19937 &rng) const;\n\n            arma::field<arma::mat> sampleNextObsGivenPastObs(int state,\n                    int seg_dur, const arma::field<arma::mat>& past_obs,\n                    std::mt19937 &rng) const;\n\n        private:\n            arma::vec means_;\n            arma::vec std_devs_;\n    };\n\n\n    class DummyMultivariateGaussianEmission : public AbstractEmission {\n        public:\n            DummyMultivariateGaussianEmission(arma::mat& means,\n                    double std_dev_output_noise);\n\n            DummyMultivariateGaussianEmission* clone() const;\n\n            double loglikelihood(int state,\n                    const arma::field<arma::mat>& obs) const;\n\n            void reestimate(int min_duration,\n                    const arma::field<arma::cube>& meta,\n                    const arma::field<arma::field<arma::mat>>& mobs);\n\n            arma::field<arma::mat> sampleFromState(int state, int size,\n                    std::mt19937 &rng) const;\n\n        private:\n            double std_dev_output_noise_;\n            arma::mat means_;\n    };\n\n\n    class AbstractEmissionObsCondIIDgivenState : public AbstractEmission {\n        public:\n            AbstractEmissionObsCondIIDgivenState(int nstates, int dimension) :\n                    AbstractEmission(nstates, dimension) {}\n\n            virtual double loglikelihood(int state,\n                    const arma::vec &observation) const = 0;\n\n            // TODO: implement it based on the other loglikelihood function.\n            double loglikelihood(int state,\n                    const arma::field<arma::mat>& obs) const {\n                return 0;\n            }\n    };\n\n};\n\n#endif\n", "meta": {"hexsha": "11ace24c881903eaad79121f43f480a156c6cdec", "size": 6710, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/emissions.hpp", "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": "include/emissions.hpp", "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": "include/emissions.hpp", "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": 37.0718232044, "max_line_length": 82, "alphanum_fraction": 0.5922503726, "num_tokens": 1407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.4817662180409596}}
{"text": "/// \\file   test_automatically_differentiable_variable.cpp\n///\n/// \\brief\n///\n/// \\authors    Maarten P. Scholl\n/// \\date       2019-10-08\n/// \\copyright  Copyright 2017-2019 The Institute for New Economic Thinking,\n///             Oxford Martin School, University of Oxford\n///\n///             Licensed under the Apache License, Version 2.0 (the \"License\");\n///             you may not use this file except in compliance with the License.\n///             You may obtain a copy of the License at\n///\n///                 http://www.apache.org/licenses/LICENSE-2.0\n///\n///             Unless required by applicable law or agreed to in writing,\n///             software distributed under the License is distributed on an \"AS\n///             IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n///             express or implied. See the License for the specific language\n///             governing permissions and limitations under the License.\n///\n///             You may obtain instructions to fulfill the attribution\n///             requirements in CITATION.cff\n///\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE variable\n\n#include <boost/test/included/unit_test.hpp>\n\n\n#include <random>\n\n#include <esl/mathematics/variable.hpp>\nusing esl::/*mathematics::*/variable;\n\n// TODO: this is a simple implementation of the BH model, and does not use the\n//       ESL agents. We may want to include a version like that in our examples.\n\n///\n/// \\brief  Result structure for the brock hommes function\n///\nstruct simulation_result\n{\n    std::vector<variable> prices;\n    std::vector<variable> n;\n    std::vector<variable> U1;\n    std::vector<variable> U2;\n};\n\n///\n/// \\param g1\n/// \\param g2\n/// \\param b1\n/// \\param b2\n/// \\param alpha\n/// \\param sigma\n/// \\param R\n/// \\param w\n/// \\param beta\n/// \\param C\n/// \\param N\n/// \\return\nsimulation_result brock_hommes_model( variable g1, variable g2\n    , variable b1, variable b2\n    , variable alpha\n    , variable sigma\n    , variable R\n    , variable w\n    , variable beta\n    , variable C\n    , size_t N\n)\n{\n    std::vector<variable> prices {1, R};\n    std::vector<variable> n {0.5, 0.5};\n    std::vector<variable> U1 {0.};\n    std::vector<variable> U2 {0.};\n\n    // set up pseudorandom number generators\n    std::seed_seq seed_ {0};\n    std::default_random_engine generator_(seed_);\n    std::uniform_real_distribution<double> distribution_(0.0,1.0 / 1000);\n\n    for(size_t t = 2; t < 2 + N; ++t){\n        auto noise = distribution_(generator_);\n        auto new_price = ( (n[t-1]  * (g1 * prices[t-1] + b1)) + ((1 - n[t-1]) * (g2 * prices[t-1] + b2)) + noise ) / R;\n        prices.emplace_back(new_price);\n\n        // update profits\n        //auto m = (1./(alpha * pow(sigma,2))) * (prices[t] - R * prices[t-1]);\n        U1.emplace_back((1./(alpha * pow(sigma,2))) * (prices[t] - R * prices[t-1]) * (g1*prices[t-2] + b1 - R * prices[t-1]) + w * U1[t-2] - C);\n        U2.emplace_back((1./(alpha * pow(sigma,2))) * (prices[t] - R * prices[t-1]) * (g2*prices[t-2] + b2 - R * prices[t-1]) + w * U2[t-2] - C);\n\n        // population fraction\n        n.emplace_back(exp(beta * U1[t-1]) / (exp(beta * U1[t-1]) + exp(beta * U2[t-1])));\n    }\n\n    return simulation_result {\n        .prices = prices,\n        .n      = n,\n        .U1     = U1,\n        .U2     = U2\n    };\n}\n\n///\n/// \\brief quick and dirty implementation of a volatility computation for diff\n///         variables\n///\n/// \\param prices\n/// \\return\nvariable volatility(const std::vector<variable> &prices)\n{\n    variable mean_{0};\n    for(size_t t = 1; t < prices.size(); ++t){\n        mean_ += (adept::exp(adept::log(prices[t-1]) -adept::log(prices[t]) -1) / (prices.size() - 1));\n    }\n\n    variable sample_statistic_{0};\n    for(size_t t = 1; t < prices.size(); ++t){\n        sample_statistic_ += adept::pow(adept::exp(adept::log(prices[t-1]) -adept::log(prices[t])) - 1 - mean_, 2);\n    }\n\n    sample_statistic_ /= (prices.size() - 2);\n\n    // to standard deviation\n    sample_statistic_ = adept::sqrt(sample_statistic_);\n\n    return sample_statistic_;\n}\n\n\nBOOST_AUTO_TEST_SUITE(ESL)\n    BOOST_AUTO_TEST_CASE(brock_hommes_autodiff)\n    {\n        adept::Stack stack_;\n\n        variable g1     = 0.8;\n        variable g2     = 1.1;\n\n        variable b1     = 0.03;\n        variable b2     = 0.01;\n\n        variable alpha  = 0.5;\n        variable sigma  = 0.2;\n        variable R      = 1.01;\n        variable w      = 0.5;\n        variable beta   = 0.7;\n        variable C      = 0.9;\n\n        stack_.new_recording();\n\n        // we don't differentiate for simulation length, this is a regular uint\n        size_t N = 10'000;\n\n        // these are 10 differentiable independent variables\n        constexpr size_t independents_ = 10;\n        stack_.independent(g1);\n        stack_.independent(g2);\n        stack_.independent(b1);\n        stack_.independent(b2);\n        stack_.independent(alpha);\n        stack_.independent(sigma);\n        stack_.independent(R);\n        stack_.independent(w);\n        stack_.independent(beta);\n        stack_.independent(C);\n\n        stack_.set_max_jacobian_threads(2);\n\n        auto result_ = brock_hommes_model\n            (  g1\n            ,  g2\n            ,  b1\n            ,  b2\n            ,  alpha\n            ,  sigma\n            ,  R\n            ,  w\n            ,  beta\n            ,  C\n            ,  N\n            );\n\n        for(size_t i = 0; i < N; ++i){\n            // this prints prices\n            //std::cout << result_.prices[i] << \", \" << std::endl;\n        }\n\n        // lets demo with one dependent variable\n        auto volatility_ = volatility(result_.prices);\n\n        // this prints annualized volatility\n        //std::cout << \"volatility \" << volatility_.value() * std::sqrt(252) << std::endl;\n\n        stack_.dependent(volatility_);\n\n        //  taken from adept documentation:\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.\n        double jacobian_out[independents_ * 1] = {0};\n\n        stack_.jacobian(jacobian_out);\n\n        for(size_t i = 0; i < independents_; ++i){\n            BOOST_CHECK(!std::isnan(jacobian_out[i]) && std::isfinite(jacobian_out[i]));\n        }\n    }\n\n\n    BOOST_AUTO_TEST_CASE(variable_constructor)\n    {\n        adept::Stack stack_;\n        std::vector<double> v = {1.0, 3.0, 5.0, 7.0};\n        for(auto x1 : v){\n\n            esl::variable x = x1;\n            stack_.new_recording();\n\n            adept::adouble f = -(x * x * x);\n\n            stack_.independent(&x, 1);\n            stack_.dependent(&x, 1);\n            double j[1] = {0.};\n            stack_.jacobian(j);\n\n\n            f.set_gradient(1.0);\n            stack_.compute_adjoint();\n            double dj[1] = {0.};\n            adept::get_gradients(&x, 1, dj);\n\n            BOOST_CHECK_CLOSE(adept::value(f), - (adept::value(x) * adept::value(x) * adept::value(x)), 0.000'000'1);\n\n            BOOST_CHECK_CLOSE(dj[0], -3. * (adept::value(x)  * adept::value(x) ) , 0.000'000'1);\n        }\n    }\n\nBOOST_AUTO_TEST_SUITE_END()  // ESL", "meta": {"hexsha": "4eec54fe148dc6b1e8e03de6c8405f9ec094a40f", "size": 7157, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_automatically_differentiable_variable.cpp", "max_stars_repo_name": "rht/ESL", "max_stars_repo_head_hexsha": "f883155a167d3c48e5ecdca91c8302fefc901c22", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 37.0, "max_stars_repo_stars_event_min_datetime": "2019-10-13T12:23:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T10:40:29.000Z", "max_issues_repo_path": "test/test_automatically_differentiable_variable.cpp", "max_issues_repo_name": "rht/ESL", "max_issues_repo_head_hexsha": "f883155a167d3c48e5ecdca91c8302fefc901c22", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-03-20T04:44:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-12T06:18:33.000Z", "max_forks_repo_path": "test/test_automatically_differentiable_variable.cpp", "max_forks_repo_name": "vishalbelsare/ESL", "max_forks_repo_head_hexsha": "cea6feda1e588d5f441742dbb1e4c5479b47d357", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-11-06T15:59:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-09T17:28:24.000Z", "avg_line_length": 29.8208333333, "max_line_length": 145, "alphanum_fraction": 0.5664384519, "num_tokens": 1965, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125848754472, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.4817662148427206}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2015 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_SEC_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_SEC_HPP_INCLUDED\n\n#include <boost/simd/function/restricted.hpp>\n#include <boost/simd/function/rec.hpp>\n#include <boost/simd/function/cos.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 ( sec_\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 sec(a0, tag::big_);\n    }\n  };\n  BOOST_DISPATCH_OVERLOAD ( sec_\n                          , (typename A0, typename A1)\n                          , bd::cpu_\n                          , bd::scalar_< bd::floating_<A0> >\n                          , bd::scalar_ < bd::unspecified_<A1> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() ( A0 a0, A1 const&) const BOOST_NOEXCEPT\n    {\n      return rec(cos(a0, A1()));\n    }\n  };\n  BOOST_DISPATCH_OVERLOAD ( sec_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bs::restricted_tag\n                          , bd::scalar_< bd::floating_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() (const restricted_tag &,  A0 a0) const BOOST_NOEXCEPT\n    {\n      return rec(restricted_(cos)(a0));\n    }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "d6b6fede1a97a681b2983d1be98d9cb6eb2e4997", "size": 1994, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/scalar/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/arch/common/scalar/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/arch/common/scalar/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": 31.6507936508, "max_line_length": 100, "alphanum_fraction": 0.4994984955, "num_tokens": 425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.752012562644147, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.4817662109198755}}
{"text": "#include <armadillo>\n\n#include <mona/utility.hpp>\n#include <mona/line.hpp>\n#include <mona/targets/window.hpp>\n#include <mona/axes.hpp>\n#include <mona/colors.hpp>\n\nauto f(double x)\n{\n    return std::sin(x);\n}\n\nint main()\n{\n    arma::fvec x = mona::linspace(-4, 4, 50);\n    arma::fvec y = x;\n    y.transform(f);\n\n    auto target = mona::targets::window();\n    auto cam = mona::camera(); // viewport should be set on control camera\n    auto axes = mona::axes();\n\n    auto line1 = mona::line(x, y, mona::colors::midnight_blue);\n    auto line2 = mona::line(x, y % x, mona::colors::orange_red);\n    auto line3 = mona::line(x, y - x, mona::colors::pale_violet_red);\n\n\n    float delta = 0;\n    while (target.active())\n    {\n        axes.submit(line1);\n        axes.submit(line2);\n        axes.submit(line3);\n\n        arma::fvec t = x + delta;\n        t.transform(f);\n        delta += 0.04;\n\n        line1.reset(x, t);\n        line1.color.r = 255.f * std::cos(glfwGetTime());\n        line1.color.b = 255.f * std::sin(glfwGetTime());\n        line1.color.b = 255.f * std::sin(glfwGetTime()) * std::cos(glfwGetTime()) ;\n\n        cam = target.control_camera(cam);\n        target.submit(axes);\n        target.draw();\n    }\n}", "meta": {"hexsha": "07421d0a89d0ce63a9a41ac5647e194658275a1a", "size": 1210, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/line_plot/main.cpp", "max_stars_repo_name": "Eleobert/mona", "max_stars_repo_head_hexsha": "079e70b190b0850cf2579c1b0872da87f2706d80", "max_stars_repo_licenses": ["MIT"], "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/line_plot/main.cpp", "max_issues_repo_name": "Eleobert/mona", "max_issues_repo_head_hexsha": "079e70b190b0850cf2579c1b0872da87f2706d80", "max_issues_repo_licenses": ["MIT"], "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/line_plot/main.cpp", "max_forks_repo_name": "Eleobert/mona", "max_forks_repo_head_hexsha": "079e70b190b0850cf2579c1b0872da87f2706d80", "max_forks_repo_licenses": ["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.693877551, "max_line_length": 83, "alphanum_fraction": 0.5809917355, "num_tokens": 357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673359709796, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.481759320223643}}
{"text": "/// ---------------------------------------------------------------------------\n/// @section LICENSE\n///  \n/// Copyright (c) 2016 Georgia Tech Research Institute (GTRI) \n///               All Rights Reserved\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 \n/// DEALINGS IN THE SOFTWARE.\n/// ---------------------------------------------------------------------------\n/// @file filename.ext\n/// @author Kevin DeMarco <kevin.demarco@gtri.gatech.edu> \n/// @author Eric Squires <eric.squires@gtri.gatech.edu>\n/// @version 1.0\n/// ---------------------------------------------------------------------------\n/// @brief A brief description.\n/// \n/// @section DESCRIPTION\n/// A long description.\n/// ---------------------------------------------------------------------------\n#include <scrimmage/plugin_manager/RegisterPlugin.h>\n#include \"SimpleQuadrotorControllerLQR.h\"\n#include <scrimmage/common/Utilities.h>\n#include <scrimmage/parse/ParseUtils.h>\n#include <boost/algorithm/clamp.hpp>\n\nREGISTER_PLUGIN(scrimmage::Controller,\n                SimpleQuadrotorControllerLQR,\n                SimpleQuadrotorControllerLQR_plugin)\n\nnamespace sc = scrimmage; \n\nvoid SimpleQuadrotorControllerLQR::init(std::map<std::string, std::string> &params) {\n    double p_gain = sc::get(\"vel_p_gain\", params, 1.0);\n    double i_gain = sc::get(\"vel_i_gain\", params, 1.0);\n    double d_gain = sc::get(\"vel_d_gain\", params, 1.0);\n    double i_lim = sc::get(\"i_lim\", params, 1.0);\n    vel_pid_.set_parameters(p_gain, i_gain, d_gain);\n    vel_pid_.set_integral_band(i_lim);\n\n    max_vel_ = std::stod(params[\"max_vel\"]);\n}\n\nbool SimpleQuadrotorControllerLQR::step(double t, double dt) {\n    Eigen::Vector3d &des_pos = desired_state_->pos();\n    double des_yaw = desired_state_->quat().yaw();\n\n    Eigen::Vector3d &pos = state_->pos();\n    Eigen::Vector3d &vel = state_->vel();\n    double yaw = state_->quat().yaw();\n    double xy_speed = vel.head<2>().norm();\n\n    double yaw_dot =\n        std::isnan(prev_yaw_) ? 0 : sc::Angles::angle_diff_rad(yaw, prev_yaw_) / dt;\n    prev_yaw_ = yaw;\n\n    // LQR Altitude Controller:\n    double q1 = 1;\n    double z_thrust = -1.0 / q1 * (pos(2) - des_pos(2)) - sqrt(2.0/q1) * vel(2);\n     \n    // LQR Heading Controller:\n    double q2 = 1;\n    double turn_force = -1.0 / q2 * sc::Angles::angle_pi(yaw - des_yaw) - sqrt(2.0/q2) * yaw_dot;        \n    \n    // If not close to x/y position, use forward velocity:\n    double dist = (des_pos - pos).head<2>().norm();\n    vel_pid_.set_setpoint((dist < 10) ? 0 : dist / 10);    \n\n    double ctrl_vel = vel_pid_.step(dt, xy_speed);\n\n    u_(0) = boost::algorithm::clamp(ctrl_vel, -max_vel_, max_vel_);\n    u_(1) = 0;\n    u_(2) = z_thrust;\n    u_(3) = turn_force;\n     \n    return true;\n}\n", "meta": {"hexsha": "ca6d17a1ac443718614bd7ed51290ed61373b6bc", "size": 3298, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "scrimmage/plugins/motion/SimpleQuadrotor/SimpleQuadrotorControllerLQR/SimpleQuadrotorControllerLQR.cpp", "max_stars_repo_name": "ddfan/swarm_evolve", "max_stars_repo_head_hexsha": "cd2d972c021e9af5946673363fbfd39cff18f13f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T03:01:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T03:11:30.000Z", "max_issues_repo_path": "scrimmage/plugins/motion/SimpleQuadrotor/SimpleQuadrotorControllerLQR/SimpleQuadrotorControllerLQR.cpp", "max_issues_repo_name": "lyers179/swarm_evolve", "max_issues_repo_head_hexsha": "cd2d972c021e9af5946673363fbfd39cff18f13f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-10-29T02:14:10.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-23T02:36:14.000Z", "max_forks_repo_path": "scrimmage/plugins/motion/SimpleQuadrotor/SimpleQuadrotorControllerLQR/SimpleQuadrotorControllerLQR.cpp", "max_forks_repo_name": "lyers179/swarm_evolve", "max_forks_repo_head_hexsha": "cd2d972c021e9af5946673363fbfd39cff18f13f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2018-10-29T02:07:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-04T06:37:53.000Z", "avg_line_length": 38.8, "max_line_length": 105, "alphanum_fraction": 0.6036992116, "num_tokens": 833, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.481759314850111}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n// Unit Test\r\n\r\n// Copyright (c) 2015 Barend Gehrels, Amsterdam, the Netherlands.\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#include <cstddef>\r\n#include <string>\r\n\r\n#include <boost/geometry/algorithms/is_convex.hpp>\r\n\r\n#include <geometry_test_common.hpp>\r\n\r\n#include <boost/geometry/algorithms/correct.hpp>\r\n#include <boost/geometry/io/wkt/wkt.hpp>\r\n#include <boost/geometry/strategies/strategies.hpp>\r\n#include <boost/geometry/geometries/point_xy.hpp>\r\n#include <boost/geometry/geometries/ring.hpp>\r\n\r\n\r\ntemplate <typename Geometry>\r\nvoid test_one(std::string const& case_id, std::string const& wkt, bool expected)\r\n{\r\n    Geometry geometry;\r\n    bg::read_wkt(wkt, geometry);\r\n    bg::correct(geometry);\r\n\r\n    bool detected = bg::is_convex(geometry);\r\n    BOOST_CHECK_MESSAGE(detected == expected,\r\n        \"Not as expected, case: \" << case_id\r\n            << \" / expected: \" << expected\r\n            << \" / detected: \" << detected);\r\n}\r\n\r\n\r\ntemplate <typename P>\r\nvoid test_all()\r\n{\r\n    // rectangular, with concavity\r\n    std::string const concave1 = \"polygon((1 1, 1 4, 3 4, 3 3, 4 3, 4 4, 5 4, 5 1, 1 1))\";\r\n    std::string const triangle = \"polygon((1 1, 1 4, 5 1, 1 1))\";\r\n\r\n    test_one<bg::model::ring<P> >(\"triangle\", triangle, true);\r\n    test_one<bg::model::ring<P> >(\"concave1\", concave1, false);\r\n    test_one<bg::model::ring<P, false, false> >(\"triangle\", triangle, true);\r\n    test_one<bg::model::ring<P, false, false> >(\"concave1\", concave1, false);\r\n\r\n    test_one<bg::model::box<P> >(\"box\", \"box(0 0,2 2)\", true);\r\n}\r\n\r\n\r\nint test_main(int, char* [])\r\n{\r\n    test_all<bg::model::d2::point_xy<int> >();\r\n    test_all<bg::model::d2::point_xy<double> >();\r\n\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "a8ea5ee067efa429ff5dbd9fc321f6b9d84dace1", "size": 1903, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/geometry/test/algorithms/is_convex.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": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/geometry/test/algorithms/is_convex.cpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-03-04T11:21:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-24T01:36:31.000Z", "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/geometry/test/algorithms/is_convex.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 30.6935483871, "max_line_length": 91, "alphanum_fraction": 0.6473988439, "num_tokens": 550, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737473266735, "lm_q2_score": 0.7057850340255387, "lm_q1q2_score": 0.4817503354818957}}
{"text": "#define BOOST_TEST_MAIN\n#include <boost/test/included/unit_test.hpp>\n#include \"bayesian/graph.hpp\"\n\nBOOST_AUTO_TEST_CASE( graph_trace_liner )\n{\n    bn::graph_t graph;\n    auto vertex_a = graph.add_vertex();\n    auto vertex_b = graph.add_vertex();\n    auto vertex_c = graph.add_vertex();\n    auto vertex_d = graph.add_vertex();\n    auto edge_ab = graph.add_edge(vertex_a, vertex_b);\n    auto edge_bc = graph.add_edge(vertex_b, vertex_c);\n    auto edge_cd = graph.add_edge(vertex_c, vertex_d);\n\n    BOOST_CHECK(graph.is_able_trace(vertex_a, vertex_d) == true);\n    BOOST_CHECK(graph.is_able_trace(vertex_b, vertex_d) == true);\n    BOOST_CHECK(graph.is_able_trace(vertex_c, vertex_d) == true);\n    BOOST_CHECK(graph.is_able_trace(vertex_b, vertex_a) == false);\n    BOOST_CHECK(graph.is_able_trace(vertex_c, vertex_a) == false);\n    BOOST_CHECK(graph.is_able_trace(vertex_d, vertex_a) == false);\n}\n\nBOOST_AUTO_TEST_CASE( graph_trace_zigzag )\n{\n    bn::graph_t graph;\n    auto vertex_a = graph.add_vertex();\n    auto vertex_b = graph.add_vertex();\n    auto vertex_c = graph.add_vertex();\n    auto vertex_d = graph.add_vertex();\n    auto edge_ab = graph.add_edge(vertex_a, vertex_b);\n    auto edge_ac = graph.add_edge(vertex_a, vertex_c);\n    auto edge_dc = graph.add_edge(vertex_d, vertex_c);\n\n    BOOST_CHECK(graph.is_able_trace(vertex_a, vertex_d) == false);\n    BOOST_CHECK(graph.is_able_trace(vertex_b, vertex_d) == false);\n    BOOST_CHECK(graph.is_able_trace(vertex_d, vertex_b) == false);\n}\n\nBOOST_AUTO_TEST_CASE( graph_dag )\n{\n    bn::graph_t graph;\n    auto vertex_a = graph.add_vertex();\n    auto vertex_b = graph.add_vertex();\n    auto vertex_c = graph.add_vertex();\n    auto vertex_d = graph.add_vertex();\n\n    // a -> b -> c -> d -> a\n    BOOST_CHECK(graph.add_edge(vertex_a, vertex_b) != nullptr);\n    BOOST_CHECK(graph.add_edge(vertex_b, vertex_c) != nullptr);\n    BOOST_CHECK(graph.add_edge(vertex_c, vertex_d) != nullptr);\n    BOOST_CHECK(graph.add_edge(vertex_d, vertex_a) == nullptr); // ERROR: nullptr\n}\n", "meta": {"hexsha": "cf5c29a42e884e70696b2b836003ef7fc97dc29f", "size": 2018, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/bayesian/test/graph.cpp", "max_stars_repo_name": "godai0519/BayesianNetwork-Inference", "max_stars_repo_head_hexsha": "ab72b5fe96f1b648a98b8b659c4cafcfe96d8204", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 35.0, "max_stars_repo_stars_event_min_datetime": "2015-06-05T07:25:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-18T19:43:20.000Z", "max_issues_repo_path": "libs/bayesian/test/graph.cpp", "max_issues_repo_name": "godai0519/BayesianNetwork", "max_issues_repo_head_hexsha": "ab72b5fe96f1b648a98b8b659c4cafcfe96d8204", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2015-02-09T12:32:19.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-18T09:08:17.000Z", "max_forks_repo_path": "libs/bayesian/test/graph.cpp", "max_forks_repo_name": "godai0519/BayesianNetwork-Inference", "max_forks_repo_head_hexsha": "ab72b5fe96f1b648a98b8b659c4cafcfe96d8204", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2016-08-14T13:47:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-18T09:33:18.000Z", "avg_line_length": 37.3703703704, "max_line_length": 81, "alphanum_fraction": 0.7145688801, "num_tokens": 501, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.705785040214066, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.4817503305912674}}
{"text": "// Boost.Geometry\n// Unit Test\n\n// Copyright (c) 2021, Oracle and/or its affiliates.\n\n// Contributed and/or modified by Vissarion Fysikopoulos, on behalf of Oracle\n\n// Licensed under the Boost Software License version 1.0.\n// http://www.boost.org/users/license.html\n\n#ifndef BOOST_GEOMETRY_TEST_ALGORITHMS_CLOSEST_POINTS_COMMON_HPP\n#define BOOST_GEOMETRY_TEST_ALGORITHMS_CLOSEST_POINTS_COMMON_HPP\n\n#define BOOST_GEOMETRY_TEST_DEBUG_CLOSEST_POINTS\n\n#include <boost/geometry/core/tags.hpp>\n\n#include <boost/geometry/geometries/geometries.hpp>\n#include <boost/geometry/algorithms/closest_points.hpp>\n#include <boost/geometry/strategies/strategies.hpp>\n\n#include <boost/test/included/unit_test.hpp>\n\n#include <from_wkt.hpp>\n\nnamespace bg = boost::geometry;\n\n//===========================================================================\n// point types\n\nusing car_point = bg::model::point<double, 2, bg::cs::cartesian>;\n\nusing sph_point = bg::model::point\n        <\n            double, 2,\n            bg::cs::spherical_equatorial<bg::degree>\n        >;\n\nusing geo_point = bg::model::point\n        <\n            double, 2,\n            bg::cs::geographic<bg::degree>\n        >;\n\n//===========================================================================\n\nusing cartesian = bg::strategies::closest_points::cartesian<double>;\n\n//using spherical = bg::strategy::closest_points::spherical<double>;\n\n//using = bg::strategy::closest_points::geographic\n//                      <bg::strategy::andoyer> andoyer;\n//using = bg::strategy::closest_points::geographic\n//                      <bg::strategy::thomas> thomas;\n//using = bg::strategy::closest_points::geographic\n//                      <bg::strategy::vincenty> vincenty;\n\n//===========================================================================\n\ntemplate <typename Segment>\nstatic inline Segment swap(Segment const& s)\n{\n    Segment swapped;\n\n    bg::set<0, 0>(swapped, bg::get<1, 0>(s));\n    bg::set<0, 1>(swapped, bg::get<1, 1>(s));\n    bg::set<1, 0>(swapped, bg::get<0, 0>(s));\n    bg::set<1, 1>(swapped, bg::get<0, 1>(s));\n\n    return swapped;\n}\n\ntemplate <int i, int j, typename Segment>\nvoid compare_result_with_expected(Segment const& expected_resulting_segment,\n                                  Segment const& resulting_segment)\n{\n    double expected = bg::get<i, j>(expected_resulting_segment);\n    double resulting = bg::get<i, j>(resulting_segment);\n    BOOST_CHECK_CLOSE(expected, resulting, 0.01);\n}\n\ntemplate <typename Segment>\nvoid compare_result_with_expected(Segment const& exp_resulting_segment,\n                                  Segment const& resulting_segment)\n{\n    compare_result_with_expected<0,0>(exp_resulting_segment, resulting_segment);\n    compare_result_with_expected<1,0>(exp_resulting_segment, resulting_segment);\n    compare_result_with_expected<0,1>(exp_resulting_segment, resulting_segment);\n    compare_result_with_expected<1,1>(exp_resulting_segment, resulting_segment);\n}\n\n//==============================================================================\n\ntemplate\n<\n    typename Geometry1,\n    typename Geometry2,\n    typename Segment,\n    typename Strategy\n>\nvoid compute_result(Geometry1 const& geometry1,\n                    Geometry2 const& geometry2,\n                    Segment const& exp_resulting_segment,\n                    Strategy const& strategy,\n                    bool default_strategy)\n{\n#ifdef BOOST_GEOMETRY_TEST_DEBUG_CLOSEST_POINTS\n    //std::cout << \"CS: \" << typeid(typename bg::cs_tag<Geometry1>::type).name()\n    //          << std::endl;\n    std::cout << bg::wkt(geometry1) << \" --- \" << bg::wkt(geometry2)\n              << std::endl;\n#endif\n    Segment resulting_segment;\n    if (default_strategy)\n    {\n        bg::closest_points(geometry1, geometry2, resulting_segment);\n    }\n    else\n    {\n        bg::closest_points(geometry1, geometry2, resulting_segment, strategy);\n    }\n#ifdef BOOST_GEOMETRY_TEST_DEBUG_CLOSEST_POINTS\n    std::cout << \"closest_points : \" << bg::wkt(resulting_segment)\n              << std::endl << std::endl;\n#endif\n    compare_result_with_expected(exp_resulting_segment, resulting_segment);\n}\n\ntemplate\n<\n    typename Geometry1,\n    typename Geometry2,\n    typename Segment,\n    typename Strategy\n>\nvoid compute_result(Geometry1 const& geometry1,\n                    Geometry2 const& geometry2,\n                    Segment const& exp_resulting_segment,\n                    Strategy const& strategy,\n                    bool swap_geometries,\n                    bool default_strategy)\n{\n    compute_result(geometry1, geometry2, exp_resulting_segment, strategy,\n                   default_strategy);\n    if (swap_geometries)\n    {\n        // swap input geometries and expected segment\n        compute_result(geometry2, geometry1,\n                       swap(exp_resulting_segment), strategy,\n                       default_strategy);\n    }\n}\n\n//==============================================================================\n\ntemplate <typename CS_tag>\nstruct test_closest_points_dispatch\n{};\n\ntemplate <>\nstruct test_closest_points_dispatch<bg::cartesian_tag>\n{\n    template\n    <\n        typename OutputSegment,\n        typename Geometry1,\n        typename Geometry2,\n        typename Strategy\n    >\n    void static apply(Geometry1 const& geometry1,\n                      Geometry2 const& geometry2,\n                      std::string const& expected_resulting_segment_car,\n                      std::string const& expected_resulting_segment_sph,\n                      std::string const& expected_resulting_segment_geo,\n                      Strategy const& strategy,\n                      bool swap_geometries,\n                      bool default_strategy)\n    {\n        boost::ignore_unused(expected_resulting_segment_sph);\n        boost::ignore_unused(expected_resulting_segment_geo);\n\n        OutputSegment expected_resulting_segment;\n        bg::read_wkt(expected_resulting_segment_car,\n                     expected_resulting_segment);\n        compute_result(geometry1,\n                       geometry2,\n                       expected_resulting_segment,\n                       strategy,\n                       swap_geometries,\n                       default_strategy);\n    }\n};\n\ntemplate <>\nstruct test_closest_points_dispatch<bg::spherical_equatorial_tag>\n{\n    template\n    <\n        typename OutputSegment,\n        typename Geometry1,\n        typename Geometry2,\n        typename Strategy\n    >\n    void static apply(Geometry1 const& geometry1,\n                      Geometry2 const& geometry2,\n                      std::string const& expected_resulting_segment_car,\n                      std::string const& expected_resulting_segment_sph,\n                      std::string const& expected_resulting_segment_geo,\n                      Strategy const& strategy,\n                      bool swap_geometries,\n                      bool default_strategy)\n    {\n        boost::ignore_unused(expected_resulting_segment_car);\n        boost::ignore_unused(expected_resulting_segment_geo);\n\n        OutputSegment expected_resulting_segment;\n        bg::read_wkt(expected_resulting_segment_sph,\n                     expected_resulting_segment);\n        compute_result(geometry1,\n                       geometry2,\n                       expected_resulting_segment,\n                       strategy,\n                       swap_geometries,\n                       default_strategy);\n    }\n};\n\n\ntemplate <>\nstruct test_closest_points_dispatch<bg::geographic_tag>\n{\n    template\n    <\n        typename OutputSegment,\n        typename Geometry1,\n        typename Geometry2,\n        typename Strategy\n    >\n    void static apply(Geometry1 const& geometry1,\n                      Geometry2 const& geometry2,\n                      std::string const& expected_resulting_segment_car,\n                      std::string const& expected_resulting_segment_sph,\n                      std::string const& expected_resulting_segment_geo,\n                      Strategy const& strategy,\n                      bool swap_geometries,\n                      bool default_strategy)\n    {\n        boost::ignore_unused(expected_resulting_segment_car);\n        boost::ignore_unused(expected_resulting_segment_sph);\n\n        OutputSegment expected_resulting_segment;\n        bg::read_wkt(expected_resulting_segment_geo,\n                     expected_resulting_segment);\n        compute_result(geometry1,\n                       geometry2,\n                       expected_resulting_segment,\n                       strategy,\n                       swap_geometries,\n                       default_strategy);\n    }\n};\n\n//==============================================================================\n\n\ntemplate <typename Geometry1, typename Geometry2, typename OutputSegment>\nstruct test_geometry\n{\n    template <typename Strategy>\n    inline static void apply(std::string const& wkt1,\n                             std::string const& wkt2,\n                             std::string const& expected_resulting_segment_car,\n                             std::string const& expected_resulting_segment_sph,\n                             std::string const& expected_resulting_segment_geo,\n                             Strategy const& strategy,\n                             bool swap_geometries = true,\n                             bool default_strategy = false)\n    {\n        using CS_tag = typename bg::cs_tag<Geometry1>::type;\n\n        Geometry1 geometry1;\n        bg::read_wkt(wkt1, geometry1);\n        Geometry2 geometry2;\n        bg::read_wkt(wkt2, geometry2);\n\n        test_closest_points_dispatch<CS_tag>\n               ::template apply<OutputSegment>(geometry1,\n                                               geometry2,\n                                               expected_resulting_segment_car,\n                                               expected_resulting_segment_sph,\n                                               expected_resulting_segment_geo,\n                                               strategy,\n                                               swap_geometries,\n                                               default_strategy);\n    }\n\n    template <typename Strategy>\n    inline static void apply(std::string const& wkt1,\n                             std::string const& wkt2,\n                             std::string const& expected_resulting_segment_car,\n                             std::string const& expected_resulting_segment_sph_geo,\n                             Strategy const& strategy,\n                             bool swap_geometries = true,\n                             bool default_strategy = false)\n    {\n        apply(wkt1,\n              wkt2,\n              expected_resulting_segment_car,\n              expected_resulting_segment_sph_geo,\n              expected_resulting_segment_sph_geo,\n              strategy,\n              swap_geometries,\n              default_strategy);\n    }\n\n    template <typename Strategy>\n    inline static void apply(std::string const& wkt1,\n                             std::string const& wkt2,\n                             std::string const& expected_resulting_segment,\n                             Strategy const& strategy,\n                             bool swap_geometries = true,\n                             bool default_strategy = false)\n    {\n        apply(wkt1,\n              wkt2,\n              expected_resulting_segment,\n              expected_resulting_segment,\n              expected_resulting_segment,\n              strategy,\n              swap_geometries,\n              default_strategy);\n    }\n};\n\n#endif // BOOST_GEOMETRY_TEST_ALGORITHMS_CLOSEST_POINTS_COMMON_HPP\n", "meta": {"hexsha": "99dd2c969e862e6150656cfb82d2d82a3e8a8086", "size": 11644, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/algorithms/closest_points/common.hpp", "max_stars_repo_name": "onlykzy/geometry", "max_stars_repo_head_hexsha": "be6794b606d25cf53fe2fd312f9b5fe30ddda6fb", "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": "test/algorithms/closest_points/common.hpp", "max_issues_repo_name": "onlykzy/geometry", "max_issues_repo_head_hexsha": "be6794b606d25cf53fe2fd312f9b5fe30ddda6fb", "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/algorithms/closest_points/common.hpp", "max_forks_repo_name": "onlykzy/geometry", "max_forks_repo_head_hexsha": "be6794b606d25cf53fe2fd312f9b5fe30ddda6fb", "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.6547619048, "max_line_length": 83, "alphanum_fraction": 0.5687907935, "num_tokens": 2178, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370111, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.48175032214301483}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n#include \"base/array_buffer.hpp\"\n#include \"fft/shift.hpp\"\n\n/**\n * @brief fold operation,\n *\n *\n * @param[out] dst (resized)\n *  dim == 0: width x m matrix\n *  dim == 1: n x width matrix\n * @param[in]  src   Fourier coefficients of f(x), matrix of size n x m\n * @param[in]  width\n * @param[in]  dim   dimension along which to fold\n *\n */\ntemplate <typename DERIVED1, typename DERIVED2>\nvoid\nfold(Eigen::DenseBase<DERIVED1> &dst,\n     const Eigen::DenseBase<DERIVED2> &src,\n     unsigned int width,\n     int dim)\n{\n  const int ncols = src.cols();\n  const int nrows = src.rows();\n\n  typedef typename DERIVED1::Scalar numeric_t;\n  typedef Eigen::Array<numeric_t, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> local_array_t;\n\n  thread_local static ArrayBuffer<> buf;\n\n  if (dim == 0) {\n    assert(nrows % width == 0);\n    if ((src.rows() / width) % 2 == 0) {\n      const int s = nrows / width;\n      auto tmp = buf.get<local_array_t>(width, ncols);\n      tmp.setZero();\n      for (int i = 0; i < (int)width; ++i) {\n        for (int k = 0; k < s; ++k) {\n          tmp.row(i) += src.row(i + k * width);\n        }\n      }\n      // apply fftshift along dim\n      fftshift(dst, tmp, dim);\n    } else {\n      const int s = nrows / width;\n      assert(dst.rows() == width);\n      assert(dst.cols() == ncols);\n      dst.setZero();\n      for (int i = 0; i < (int)width; ++i) {\n        for (int k = 0; k < s; ++k) {\n          dst.row(i) += src.row(i + k * width);\n        }\n      }\n    }\n  } else if (dim == 1) {\n    assert(ncols % width == 0);\n    if ((src.cols() / width) % 2 == 0) {\n      const int s = ncols / width;\n      auto tmp = buf.get<local_array_t>(nrows, width);\n      tmp.setZero();\n      for (int j = 0; j < (int)width; ++j) {\n        for (int k = 0; k < s; ++k) {\n          tmp.col(j) += src.col(j + k * width);\n        }\n      }\n      // apply fftshift along dim\n      fftshift(dst, tmp, dim);\n    } else {\n      const int s = ncols / width;\n      assert(dst.rows() == nrows);\n      assert(dst.cols() == width);\n      dst.setZero();\n      for (int j = 0; j < (int)width; ++j) {\n        for (int k = 0; k < s; ++k) {\n          dst.col(j) += src.col(j + k * width);\n        }\n      }\n    }\n  }\n}\n\n/**\n * @brief unfold operation.\n *\n * unfold scales src by 1/k where k := width/size(src,dim) and repeats it\n * along dimension dim such that size(src_unfolded, dim) = width.\n * If dim == 0, the rows of src_unfolded are shifted such that the middle row of\n * src\n * becomes the middle row of src_unfolded, where the middle is determined\n * according to the centered-zero-frequency convention. In this case, this\n * function is mathematically equivalent to\n *   temp = zeros(width, size(src,2));\n *   temp(1:width/size(src,1):end, :) = ift(src);\n *   dst = ft(temp);\n * Likewise properties hold for dim == 1.\n *\n *\n * @param[out] dst  (resized)\n *   dim == 0: dst = width x m\n *   dim == 1: dst = n x width\n * @param[in] src of size n x m\n * @param[in] width\n * @param[in] dim\n * @param[in] scale\n */\ntemplate <typename DERIVED1, typename DERIVED2>\nvoid\nunfold(Eigen::DenseBase<DERIVED1> &dst,\n       Eigen::DenseBase<DERIVED2> &src,\n       unsigned int width,\n       int dim,\n       bool scale = false)\n{\n  typedef typename DERIVED1::Scalar numeric_t;\n  typedef Eigen::Array<numeric_t, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> local_array_t;\n\n  thread_local static ArrayBuffer<> buf1;\n  thread_local static ArrayBuffer<> buf2;\n\n  assert(dim == 0 || dim == 1);\n  const int nrows = src.rows();\n  const int ncols = src.cols();\n\n  if (dim == 0) {\n    const int s = width / nrows;\n    assert(s > 0);\n    if ((width / nrows) % 2 == 0) {\n      auto tmp = buf1.get<local_array_t>(src.rows(), src.cols());\n      ifftshift(tmp, src, 0);\n      auto tmp2 = buf2.get<local_array_t>(width, src.cols());\n      tmp2 = tmp.replicate(s, 1);\n      assert(dst.rows() == width);\n      fftshift(dst, tmp2, 0);\n    } else {\n      dst.derived() = src.replicate(s, 1);\n    }\n    if (scale) dst *= src.rows() / double(width);\n  } else if (dim == 1) {\n    const int s = width / ncols;\n    assert(s > 0);\n    if (s % 2 == 0) {\n      auto tmp = buf1.get<local_array_t>(src.rows(), src.cols());\n      ifftshift(tmp, src, 1);\n      auto tmp2 = buf2.get<local_array_t>(src.rows(), width);\n      tmp2 = tmp.replicate(1, s);\n      assert(dst.cols() == width);\n      fftshift(dst, tmp2, 1);\n    } else {\n      dst = src.replicate(1, s);\n    }\n    if (scale) dst *= src.cols() / double(width);\n  }\n}\n", "meta": {"hexsha": "548d314dacfa57c76801a05394fc6b8256025f03", "size": 4509, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ridgelet/fold.hpp", "max_stars_repo_name": "simonpp/2dRidgeletBTE", "max_stars_repo_head_hexsha": "5d08cbb5c57fc276c7a528f128615d23c37ef6a0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-08T03:15:56.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-08T03:15:56.000Z", "max_issues_repo_path": "ridgelet/fold.hpp", "max_issues_repo_name": "simonpp/2dRidgeletBTE", "max_issues_repo_head_hexsha": "5d08cbb5c57fc276c7a528f128615d23c37ef6a0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ridgelet/fold.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.7197452229, "max_line_length": 97, "alphanum_fraction": 0.5664227101, "num_tokens": 1369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.705785040214066, "lm_q2_score": 0.6825737214979745, "lm_q1q2_score": 0.4817503214765126}}
{"text": "/*\n * GraphBLAS Template Library (GBTL), Version 3.0\n *\n * Copyright 2020 Carnegie Mellon University, Battelle Memorial Institute, and\n * Authors.\n *\n * THIS MATERIAL WAS PREPARED AS AN ACCOUNT OF WORK SPONSORED BY AN AGENCY OF\n * THE UNITED STATES GOVERNMENT.  NEITHER THE UNITED STATES GOVERNMENT NOR THE\n * UNITED STATES DEPARTMENT OF ENERGY, NOR THE UNITED STATES DEPARTMENT OF\n * DEFENSE, NOR CARNEGIE MELLON UNIVERSITY, NOR BATTELLE, NOR ANY OF THEIR\n * EMPLOYEES, NOR ANY JURISDICTION OR ORGANIZATION THAT HAS COOPERATED IN THE\n * DEVELOPMENT OF THESE MATERIALS, MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR\n * ASSUMES ANY LEGAL LIABILITY OR RESPONSIBILITY FOR THE ACCURACY, COMPLETENESS,\n * OR USEFULNESS OR ANY INFORMATION, APPARATUS, PRODUCT, SOFTWARE, OR PROCESS\n * DISCLOSED, OR REPRESENTS THAT ITS USE WOULD NOT INFRINGE PRIVATELY OWNED\n * RIGHTS.\n *\n * Released under a BSD-style license, please see LICENSE file or contact\n * permission@sei.cmu.edu for full terms.\n *\n * [DISTRIBUTION STATEMENT A] This material has been approved for public release\n * and unlimited distribution.  Please see Copyright notice for non-US\n * Government use and distribution.\n *\n * This Software includes and/or makes use of the following Third-Party Software\n * subject to its own license:\n *\n * 1. Boost Unit Test Framework\n * (https://www.boost.org/doc/libs/1_45_0/libs/test/doc/html/utf.html)\n * Copyright 2001 Boost software license, Gennadiy Rozental.\n *\n * DM20-0442\n */\n\n#include <iostream>\n\n#define GRAPHBLAS_LOGGING_LEVEL 0\n#define GRAPHBLAS_BC_DEBUG 0\n\n#include <graphblas/graphblas.hpp>\n#include <algorithms/bc.hpp>\n\nusing namespace grb;\nusing namespace algorithms;\n\n#define BOOST_TEST_MAIN\n#define BOOST_TEST_MODULE bc_test_suite\n\n#include <boost/test/included/unit_test.hpp>\n\nBOOST_AUTO_TEST_SUITE(BOOST_TEST_MODULE)\n\n//****************************************************************************\n\nstatic std::vector<double> br={0, 0, 0, 1, 1, 2, 3, 3, 4, 4, 5, 6};\nstatic std::vector<double> bc={1, 2, 3, 2, 4, 4, 2, 4, 5, 6, 7, 7};\nstatic std::vector<double> bv(br.size(), 1);\n\n//static Matrix<double, DirectedMatrixTag> betweenness(\n//    {{0, 1, 1, 1, 0, 0, 0, 0},\n//     {0, 0, 1, 0, 1, 0, 0, 0},\n//     {0, 0, 0, 0, 1, 0, 0, 0},vertex_betweenness_centrality_batch_alt_trans_v2\n//     {0, 0, 1, 0, 1, 0, 0, 0},\n//     {0, 0, 0, 0, 0, 1, 1, 0},\n//     {0, 0, 0, 0, 0, 0, 0, 1},\n//     {0, 0, 0, 0, 0, 0, 0, 1},\n//     {0, 0, 0, 0, 0, 0, 0, 0}});\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(bc_test_vertex_betweenness_centrality_gilbert)\n{\n    IndexType const NUM_NODES = 7;\n    std::vector<IndexType> row_indices = {0, 0, 1, 1, 2, 3, 3, 4, 5, 6, 6, 6};\n    std::vector<IndexType> col_indices = {1, 3, 4, 6, 5, 0, 2, 5, 2, 2, 3, 4};\n    std::vector<double> values(row_indices.size(), 1.);\n\n    Matrix<double> graph(NUM_NODES, NUM_NODES);\n    graph.build(row_indices.begin(), col_indices.begin(),\n                      values.begin(), values.size());\n\n    IndexArrayType seed_set={0, 1, 2, 3, 4, 5, 6};\n\n    //std::vector<float> result = vertex_betweenness_centrality(graph);\n    std::vector<float> answer = {4.0, 4.5, 2, 4.5, 2.0, 1.0, 3.0};\n\n    {\n        std::vector<double> result =\n            vertex_betweenness_centrality(graph);\n\n        BOOST_CHECK_EQUAL(result.size(), answer.size());\n        for (unsigned int ix = 0; ix < result.size(); ++ix)\n            BOOST_CHECK_CLOSE(result[ix], answer[ix], 0.0001);\n    }\n    {\n        std::vector<double> result =\n            vertex_betweenness_centrality_batch_old(graph, seed_set);\n\n        BOOST_CHECK_EQUAL(result.size(), answer.size());\n        for (unsigned int ix = 0; ix < result.size(); ++ix)\n            BOOST_CHECK_CLOSE(result[ix], answer[ix], 0.0001);\n    }\n    {\n        std::vector<float> result =\n            vertex_betweenness_centrality_batch(graph, seed_set);\n\n        BOOST_CHECK_EQUAL(result.size(), answer.size());\n        for (unsigned int ix = 0; ix < result.size(); ++ix)\n            BOOST_CHECK_CLOSE(result[ix], answer[ix], 0.0001);\n    }\n    {\n        std::vector<float> result =\n            vertex_betweenness_centrality_batch_alt(graph, seed_set);\n\n        BOOST_CHECK_EQUAL(result.size(), answer.size());\n        for (unsigned int ix = 0; ix < result.size(); ++ix)\n            BOOST_CHECK_CLOSE(result[ix], answer[ix], 0.0001);\n    }\n    {\n        std::vector<float> result =\n            vertex_betweenness_centrality_batch_alt_trans(graph, seed_set);\n\n        BOOST_CHECK_EQUAL(result.size(), answer.size());\n        for (unsigned int ix = 0; ix < result.size(); ++ix)\n            BOOST_CHECK_CLOSE(result[ix], answer[ix], 0.0001);\n    }\n    {\n        std::vector<float> result =\n            vertex_betweenness_centrality_batch_alt_trans_v2(graph, seed_set);\n\n        BOOST_CHECK_EQUAL(result.size(), answer.size());\n        for (unsigned int ix = 0; ix < result.size(); ++ix)\n            BOOST_CHECK_CLOSE(result[ix], answer[ix], 0.0001);\n    }\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(bc_test_vertex_betweenness_centrality)\n{\n    Matrix<double, DirectedMatrixTag> betweenness(8,8);\n    betweenness.build(br.begin(), bc.begin(), bv.begin(), bv.size());\n    std::vector<double> result = vertex_betweenness_centrality(betweenness);\n    std::vector<double> answer = {0.0, 4.0/3, 4.0/3, 4.0/3, 12.0, 2.5, 2.5, 0.0};\n\n    BOOST_CHECK_EQUAL(result.size(), answer.size());\n    for (unsigned int ix = 0; ix < result.size(); ++ix)\n        BOOST_CHECK_CLOSE(result[ix], answer[ix], 0.0001);\n}\n\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(bc_test_edge_betweenness_centrality_2)\n{\n    IndexType const NUM_NODES = 11;\n    std::vector<IndexType> row_indices = {0, 0, 0, 0, 1, 1, 2, 3, 3, 4, 4, 5,\n                                          5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9, 10};\n    std::vector<IndexType> col_indices = {1, 2, 3, 4, 0, 9, 0, 0, 9, 0, 5, 4,\n                                          6, 7, 5, 8, 5, 8, 6, 7, 1, 3, 10, 9};\n    std::vector<double> values(row_indices.size(), 1.);\n\n    Matrix<double> graph(NUM_NODES, NUM_NODES);\n    graph.build(row_indices.begin(), col_indices.begin(),\n                values.begin(), values.size());\n\n    IndexArrayType seed_set={0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};\n\n    std::vector<float> result =\n        vertex_betweenness_centrality_batch_alt_trans_v2(graph, seed_set);\n    std::cout << \"Milcom 2016 Graph:\";\n    for (auto a : result)\n        std::cout << \" \" << a;\n    std::cout << std::endl;\n}\n\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(bc_test_edge_betweenness_centrality)\n{\n    Matrix<double, DirectedMatrixTag> betweenness(8,8);\n    Matrix<double, DirectedMatrixTag> result(8,8);\n    //Matrix<double, DirectedMatrixTag> answer ({\n    //                            {0,  6,  6,  6,  0,  0,  0,  0},\n    //                            {0,  0,  1,  0, 10,  0,  0,  0},\n    //                            {0,  0,  0,  0, 10,  0,  0,  0},\n    //                            {0,  0,  1,  0, 10,  0,  0,  0},\n    //                            {0,  0,  0,  0,  0, 14, 14,  0},\n    //                            {0,  0,  0,  0,  0,  0,  0,  8},\n    //                            {0,  0,  0,  0,  0,  0,  0,  8},\n    //                            {0,  0,  0,  0,  0,  0,  0,  0}});\n\n    std::vector<double> ar={0, 0, 0, 1, 1, 2, 3, 3, 4, 4, 5, 6};\n    std::vector<double> ac={1, 2, 3, 2, 4, 4, 2, 4, 5, 6, 7, 7};\n    std::vector<double> av={6,  6,  6,  1, 10, 10,  1, 10, 14, 14,  8,  8};\n    Matrix<double, DirectedMatrixTag> answer(8,8);\n    answer.build(ar.begin(), ac.begin(), av.begin(), av.size());\n\n    betweenness.build(br.begin(), bc.begin(), bv.begin(), bv.size());\n    result = edge_betweenness_centrality(betweenness);\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(bc_test_vertex_betweennes_centrality_batch_old)\n{\n    Matrix<double, DirectedMatrixTag> betweenness(8,8);\n    betweenness.build(br.begin(), bc.begin(), bv.begin(), bv.size());\n\n    //IndexArrayType seed_set={0, 1, 2, 3, 4, 5, 6, 7};\n    IndexArrayType seed_set={0};\n    std::vector<double> answer = {0.0, 4.0/3, 4.0/3, 4.0/3, 3.0, 0.5, 0.5, 0.0};\n\n    std::vector<double> result =\n        vertex_betweenness_centrality_batch_old(betweenness, seed_set);\n\n    BOOST_CHECK_EQUAL(result.size(), answer.size());\n    for (unsigned int ix = 0; ix < result.size(); ++ix)\n        BOOST_CHECK_CLOSE(result[ix], answer[ix], 0.0001);\n\n    //==========\n    IndexArrayType seed_set3={3};\n    std::vector<double> answer3 = {0.0, 0.0, 0.0, 0.0, 3.0, 0.5, 0.5, 0.0};\n\n    std::vector<double> result3 =\n        vertex_betweenness_centrality_batch_old(betweenness, seed_set3);\n\n    BOOST_CHECK_EQUAL(result3.size(), answer3.size());\n    for (unsigned int ix = 0; ix < result3.size(); ++ix)\n        BOOST_CHECK_CLOSE(result3[ix], answer3[ix], 0.0001);\n\n    //==========\n    IndexArrayType seed_set03={0,3};\n\n    std::vector<double> result03 =\n        vertex_betweenness_centrality_batch_old(betweenness, seed_set03);\n\n    BOOST_CHECK_EQUAL(result03.size(), answer3.size());\n    for (unsigned int ix = 0; ix < result3.size(); ++ix)\n        BOOST_CHECK_CLOSE(result03[ix], answer[ix] + answer3[ix], 0.0001);\n\n    //==========\n    IndexArrayType seed_set_all={0,1,2,3,4,5,6,7};\n    std::vector<double> answer_all = {0.0, 4.0/3, 4.0/3, 4.0/3, 12.0, 2.5, 2.5, 0.0};\n\n    std::vector<double> result_all =\n        vertex_betweenness_centrality_batch_old(betweenness, seed_set_all);\n\n    BOOST_CHECK_EQUAL(result_all.size(), answer_all.size());\n    for (unsigned int ix = 0; ix < result_all.size(); ++ix)\n        BOOST_CHECK_CLOSE(result_all[ix], answer_all[ix], 0.0001);\n\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(bc_test_vertex_betweennes_centrality_batch)\n{\n    Matrix<double, DirectedMatrixTag> betweenness(8,8);\n    betweenness.build(br.begin(), bc.begin(), bv.begin(), bv.size());\n\n    //IndexArrayType seed_set={0, 1, 2, 3, 4, 5, 6, 7};\n    IndexArrayType seed_set={0};\n    std::vector<float> answer = {0.0, 4.0/3, 4.0/3, 4.0/3, 3.0, 0.5, 0.5, 0.0};\n\n    std::vector<float> result =\n        vertex_betweenness_centrality_batch(betweenness, seed_set);\n\n    BOOST_CHECK_EQUAL(result.size(), answer.size());\n    for (unsigned int ix = 0; ix < result.size(); ++ix)\n        BOOST_CHECK_CLOSE(result[ix], answer[ix], 0.0001);\n\n    //==========\n    IndexArrayType seed_set3={3};\n    std::vector<float> answer3 = {0.0, 0.0, 0.0, 0.0, 3.0, 0.5, 0.5, 0.0};\n\n    std::vector<float> result3 =\n        vertex_betweenness_centrality_batch(betweenness, seed_set3);\n\n    BOOST_CHECK_EQUAL(result3.size(), answer3.size());\n    for (unsigned int ix = 0; ix < result3.size(); ++ix)\n        BOOST_CHECK_CLOSE(result3[ix], answer3[ix], 0.0001);\n\n    //==========\n    IndexArrayType seed_set03={0,3};\n\n    std::vector<float> result03 =\n        vertex_betweenness_centrality_batch(betweenness, seed_set03);\n\n    BOOST_CHECK_EQUAL(result03.size(), answer3.size());\n    for (unsigned int ix = 0; ix < result3.size(); ++ix)\n        BOOST_CHECK_CLOSE(result03[ix], answer[ix] + answer3[ix], 0.0001);\n\n    //==========\n    IndexArrayType seed_set_all={0,1,2,3,4,5,6,7};\n    std::vector<double> answer_all = {0.0, 4.0/3, 4.0/3, 4.0/3, 12.0, 2.5, 2.5, 0.0};\n\n    std::vector<float> result_all =\n        vertex_betweenness_centrality_batch(betweenness, seed_set_all);\n\n    BOOST_CHECK_EQUAL(result_all.size(), answer_all.size());\n    for (unsigned int ix = 0; ix < result_all.size(); ++ix)\n        BOOST_CHECK_CLOSE(result_all[ix], answer_all[ix], 0.0001);\n\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(bc_test_vertex_betweennes_centrality_batch_alt)\n{\n    // Trying the same graph where each node has self loop.     vvvvvvvvvvvvvvv\n    std::vector<double> br1={0, 0, 0, 1, 1, 2, 3, 3, 4, 4, 5, 6,0,1,2,3,4,5,6,7};\n    std::vector<double> bc1={1, 2, 3, 2, 4, 4, 2, 4, 5, 6, 7, 7,0,1,2,3,4,5,6,7};\n    std::vector<double> bv1(br1.size(), 1);\n\n    Matrix<double, DirectedMatrixTag> betweenness(8,8);\n    betweenness.build(br1.begin(), bc1.begin(), bv1.begin(), bv1.size());\n\n    //IndexArrayType seed_set={0, 1, 2, 3, 4, 5, 6, 7};\n    IndexArrayType seed_set={0};\n    std::vector<float> answer = {0.0, 4.0/3, 4.0/3, 4.0/3, 3.0, 0.5, 0.5, 0.0};\n\n    std::vector<float> result =\n        vertex_betweenness_centrality_batch_alt(betweenness, seed_set);\n\n    BOOST_CHECK_EQUAL(result.size(), answer.size());\n    for (unsigned int ix = 0; ix < result.size(); ++ix)\n        BOOST_CHECK_CLOSE(result[ix], answer[ix], 0.0001);\n\n    //==========\n    IndexArrayType seed_set3={3};\n    std::vector<float> answer3 = {0.0, 0.0, 0.0, 0.0, 3.0, 0.5, 0.5, 0.0};\n\n    std::vector<float> result3 =\n        vertex_betweenness_centrality_batch_alt(betweenness, seed_set3);\n\n    BOOST_CHECK_EQUAL(result3.size(), answer3.size());\n    for (unsigned int ix = 0; ix < result3.size(); ++ix)\n        BOOST_CHECK_CLOSE(result3[ix], answer3[ix], 0.0001);\n\n    //==========\n    IndexArrayType seed_set03={0,3};\n\n    std::vector<float> result03 =\n        vertex_betweenness_centrality_batch_alt(betweenness, seed_set03);\n\n    BOOST_CHECK_EQUAL(result03.size(), answer3.size());\n    for (unsigned int ix = 0; ix < result3.size(); ++ix)\n        BOOST_CHECK_CLOSE(result03[ix], answer[ix] + answer3[ix], 0.0001);\n\n    //==========\n    IndexArrayType seed_set_all={0,1,2,3,4,5,6,7};\n    std::vector<double> answer_all = {0.0, 4.0/3, 4.0/3, 4.0/3, 12.0, 2.5, 2.5, 0.0};\n\n    std::vector<float> result_all =\n        vertex_betweenness_centrality_batch_alt(betweenness, seed_set_all);\n\n    BOOST_CHECK_EQUAL(result_all.size(), answer_all.size());\n    for (unsigned int ix = 0; ix < result_all.size(); ++ix)\n        BOOST_CHECK_CLOSE(result_all[ix], answer_all[ix], 0.0001);\n\n}\n\n//****************************************************************************\n//BOOST_AUTO_TEST_CASE(bc_test_vertex_betweennes_centrality_batch_alt_trans)\nBOOST_AUTO_TEST_CASE(bc_batch_alt_trans)\n{\n    //std::cout << \"======================= BEGIN0 ==========================\\n\";\n    Matrix<double, DirectedMatrixTag> betweenness(8,8);\n    betweenness.build(br.begin(), bc.begin(), bv.begin(), bv.size());\n\n    //IndexArrayType seed_set={0, 1, 2, 3, 4, 5, 6, 7};\n    IndexArrayType seed_set={0};\n    std::vector<float> answer = {0.0, 4.0/3, 4.0/3, 4.0/3, 3.0, 0.5, 0.5, 0.0};\n\n    std::vector<float> result =\n        vertex_betweenness_centrality_batch_alt_trans(betweenness, seed_set);\n\n    BOOST_CHECK_EQUAL(result.size(), answer.size());\n    for (unsigned int ix = 0; ix < result.size(); ++ix)\n        BOOST_CHECK_CLOSE(result[ix], answer[ix], 0.0001);\n\n    //==========\n    //std::cout << \"======================= BEGIN3 ==========================\\n\";\n    IndexArrayType seed_set3={3};\n    std::vector<float> answer3 = {0.0, 0.0, 0.0, 0.0, 3.0, 0.5, 0.5, 0.0};\n\n    std::vector<float> result3 =\n        vertex_betweenness_centrality_batch_alt_trans(betweenness, seed_set3);\n\n    BOOST_CHECK_EQUAL(result3.size(), answer3.size());\n    for (unsigned int ix = 0; ix < result3.size(); ++ix)\n        BOOST_CHECK_CLOSE(result3[ix], answer3[ix], 0.0001);\n\n    //==========\n    //std::cout << \"======================= BEGIN0,3 ==========================\\n\";\n    IndexArrayType seed_set03={0,3};\n\n    std::vector<float> result03 =\n        vertex_betweenness_centrality_batch_alt_trans(betweenness, seed_set03);\n\n    BOOST_CHECK_EQUAL(result03.size(), answer3.size());\n    for (unsigned int ix = 0; ix < result3.size(); ++ix)\n        BOOST_CHECK_CLOSE(result03[ix], answer[ix] + answer3[ix], 0.0001);\n\n    //==========\n    //std::cout << \"======================= BEGIN0-7 ==========================\\n\";\n    IndexArrayType seed_set_all={0,1,2,3,4,5,6,7};\n    std::vector<double> answer_all = {0.0, 4.0/3, 4.0/3, 4.0/3, 12.0, 2.5, 2.5, 0.0};\n\n    std::vector<float> result_all =\n        vertex_betweenness_centrality_batch_alt_trans(betweenness, seed_set_all);\n\n    BOOST_CHECK_EQUAL(result_all.size(), answer_all.size());\n    for (unsigned int ix = 0; ix < result_all.size(); ++ix)\n        BOOST_CHECK_CLOSE(result_all[ix], answer_all[ix], 0.0001);\n    //std::cout << \"=======================  END  ==========================\\n\";\n}\n\n//****************************************************************************\n//BOOST_AUTO_TEST_CASE(bc_test_vertex_betweennes_centrality_batch_alt_trans_v2)\nBOOST_AUTO_TEST_CASE(bc_test_batch_alt_trans_v2)\n{\n    Matrix<double, DirectedMatrixTag> betweenness(8,8);\n    betweenness.build(br.begin(), bc.begin(), bv.begin(), bv.size());\n\n    //IndexArrayType seed_set={0, 1, 2, 3, 4, 5, 6, 7};\n    IndexArrayType seed_set={0};\n    std::vector<float> answer = {0.0, 4.0/3, 4.0/3, 4.0/3, 3.0, 0.5, 0.5, 0.0};\n\n    std::vector<float> result = vertex_betweenness_centrality_batch_alt_trans_v2(\n            betweenness, seed_set);\n\n    BOOST_CHECK_EQUAL(result.size(), answer.size());\n    for (unsigned int ix = 0; ix < result.size(); ++ix)\n        BOOST_CHECK_CLOSE(result[ix], answer[ix], 0.0001);\n\n    //==========\n    IndexArrayType seed_set3={3};\n    std::vector<float> answer3 = {0.0, 0.0, 0.0, 0.0, 3.0, 0.5, 0.5, 0.0};\n\n    std::vector<float> result3 =\n        vertex_betweenness_centrality_batch_alt_trans_v2(betweenness, seed_set3);\n\n    BOOST_CHECK_EQUAL(result3.size(), answer3.size());\n    for (unsigned int ix = 0; ix < result3.size(); ++ix)\n        BOOST_CHECK_CLOSE(result3[ix], answer3[ix], 0.0001);\n\n    //==========\n    IndexArrayType seed_set03={0,3};\n\n    std::vector<float> result03 =\n        vertex_betweenness_centrality_batch_alt_trans_v2(betweenness, seed_set03);\n\n    BOOST_CHECK_EQUAL(result03.size(), answer3.size());\n    for (unsigned int ix = 0; ix < result3.size(); ++ix)\n        BOOST_CHECK_CLOSE(result03[ix], answer[ix] + answer3[ix], 0.0001);\n\n    //==========\n    IndexArrayType seed_set_all={0,1,2,3,4,5,6,7};\n    std::vector<double> answer_all = {0.0, 4.0/3, 4.0/3, 4.0/3, 12.0, 2.5, 2.5, 0.0};\n\n    std::vector<float> result_all =\n        vertex_betweenness_centrality_batch_alt_trans_v2(betweenness, seed_set_all);\n\n    BOOST_CHECK_EQUAL(result_all.size(), answer_all.size());\n    for (unsigned int ix = 0; ix < result_all.size(); ++ix)\n        BOOST_CHECK_CLOSE(result_all[ix], answer_all[ix], 0.0001);\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "43cbc5e4ba1b440b0fac1404a6bdd5c6f9c150ed", "size": 18533, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/test_bc.cpp", "max_stars_repo_name": "KIwabuchi/gbtl", "max_stars_repo_head_hexsha": "62c6b1e3262f3623359e793edb5ec4fa7bb471f0", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 112.0, "max_stars_repo_stars_event_min_datetime": "2016-04-26T05:54:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T05:56:16.000Z", "max_issues_repo_path": "src/test/test_bc.cpp", "max_issues_repo_name": "KIwabuchi/gbtl", "max_issues_repo_head_hexsha": "62c6b1e3262f3623359e793edb5ec4fa7bb471f0", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 21.0, "max_issues_repo_issues_event_min_datetime": "2016-03-22T19:06:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-07T15:40:18.000Z", "max_forks_repo_path": "src/test/test_bc.cpp", "max_forks_repo_name": "KIwabuchi/gbtl", "max_forks_repo_head_hexsha": "62c6b1e3262f3623359e793edb5ec4fa7bb471f0", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2016-04-26T05:54:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-21T03:33:20.000Z", "avg_line_length": 39.5159914712, "max_line_length": 85, "alphanum_fraction": 0.5895429774, "num_tokens": 5762, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737214979745, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.48175031725238643}}
{"text": "//\r\n// Created by philipp on 26.12.2019.\r\n//\r\n\r\n#ifndef FUNNELS_CPP_DISTANCES_HH\r\n#define FUNNELS_CPP_DISTANCES_HH\r\n\r\n#include <cassert>\r\n#include <vector>\r\n#include <Eigen/Core>\r\n#include <cmath>\r\n\r\n#ifndef M_PI\r\n  #define M_PI 3.14159265358979323846\r\n#endif\r\n\r\nusing namespace std;\r\nusing namespace Eigen;\r\n\r\ndouble wrap_so2(double x){\r\n  return std::fmod(x, M_PI);\r\n}\r\n\r\nclass partial_so2_dist_t{\r\npublic:\r\n  partial_so2_dist_t(vector<size_t> so2_dims=vector<size_t>()):\r\n      _so2_dims(move(so2_dims)){};\r\n  \r\n//  template <class DERIVED0, class DERIVED1>\r\n//  MatrixXd &operator()(const MatrixBase<DERIVED0> &x0,\r\n//      const MatrixBase<DERIVED1> &x1){\r\n//    // Multiple possibilities here\r\n//    // so we have to do proper broadcasting\r\n//    assert(x0.rows()==x1.rows());\r\n//\r\n//    if(x0.cols()==1 && x1.cols()==1){\r\n//      // two vectors\r\n//      _tmpMat = x0-x1;\r\n//    }else if(x0.cols()==1 || x1.cols()==1){\r\n//      if (x0.cols()==1){\r\n//        _tmpMat = (-x1).colwise() + x0;\r\n//      }else{\r\n//        _tmpMat = x1.colwise()-x0;\r\n//      }\r\n//    }else if(x0.cols()==x1.cols()){\r\n//      _tmpMat = x0-x1;\r\n//    }\r\n//\r\n\r\n//    return _tmpMat;\r\n//  }\r\n  \r\n  const MatrixXd & cp_vv(const VectorXd & v0, const VectorXd & v1) const {\r\n    _tmpMat = v0-v1;\r\n    do_so2_wrap();\r\n    return _tmpMat;\r\n  }\r\n  \r\n  const MatrixXd & cp_vM(const VectorXd & v0, const MatrixXd & m1) const {\r\n    _tmpMat = (-m1).colwise() + v0;\r\n    do_so2_wrap();\r\n    return _tmpMat;\r\n  }\r\n  \r\n  const MatrixXd & cp_Mv(const MatrixXd & m0, const VectorXd & v1) const {\r\n    _tmpMat = m0.colwise() - v1;\r\n    do_so2_wrap();\r\n    return _tmpMat;\r\n  }\r\n  \r\n  const MatrixXd &cp_MM(const MatrixXd & m0, const MatrixXd & m1) const {\r\n    _tmpMat = m0 - m1;\r\n    do_so2_wrap();\r\n    return _tmpMat;\r\n  }\r\n  \r\n  \r\n  \r\n\r\nprotected:\r\n  \r\n  inline void do_so2_wrap()const{\r\n    // Take into account the angles\r\n    for (size_t idx : _so2_dims){\r\n      _tmpMat.col(idx).unaryExpr(&wrap_so2);\r\n    }\r\n  }\r\n  \r\n  const vector<size_t> _so2_dims;\r\n  mutable MatrixXd _tmpMat;\r\n};\r\n\r\n#endif //FUNNELS_CPP_DISTANCES_HH\r\n", "meta": {"hexsha": "d266d346f14b11b389c604a3c2bb704ddbab37b2", "size": 2096, "ext": "hh", "lang": "C++", "max_stars_repo_path": "include/funnels/distances.hh", "max_stars_repo_name": "schlepil/funnels_cpp_2", "max_stars_repo_head_hexsha": "1ed746a90019f7f6aff7a54fd4b63bfbd58fa2ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/funnels/distances.hh", "max_issues_repo_name": "schlepil/funnels_cpp_2", "max_issues_repo_head_hexsha": "1ed746a90019f7f6aff7a54fd4b63bfbd58fa2ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/funnels/distances.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": 22.2978723404, "max_line_length": 75, "alphanum_fraction": 0.5896946565, "num_tokens": 649, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.6825737214979745, "lm_q1q2_score": 0.48175031302826027}}
{"text": "/* ODE RHS and Jacobian function abstract base class definitions.\n\n   D.R. Reynolds\n   Math 6321 @ SMU\n   Fall 2020 */\n\n#ifndef ODE_RHS_DEFINED__\n#define ODE_RHS_DEFINED__\n\n// Inclusions\n#include <armadillo>\n\n\n// Declare abstract base classes for ODE RHS and its Jacobian, to\n// define what the time integrator expects from each.\n\n//   ODE RHS function abstract base class; derived classes\n//   must at least implement the Evaluate() routine\nclass RHSFunction {\n public:\n  virtual int Evaluate(double t, arma::vec& y, arma::vec& f) = 0;\n};\n\n//   ODE RHS Jacobian function abstract base class; derived\n//   classes must at least implement the Evaluate() routine\nclass RHSJacobian {\n public:\n  virtual int Evaluate(double t, arma::vec& y, arma::mat& J) = 0;\n};\n\n#endif\n", "meta": {"hexsha": "307e23f90cf4653049b1c2c70953fda717190c54", "size": 767, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "shared/rhs.hpp", "max_stars_repo_name": "drreynolds/Math6321-codes", "max_stars_repo_head_hexsha": "3cce53bbe70bdd00220b5d8888b00b20b4fd521b", "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": "shared/rhs.hpp", "max_issues_repo_name": "drreynolds/Math6321-codes", "max_issues_repo_head_hexsha": "3cce53bbe70bdd00220b5d8888b00b20b4fd521b", "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": "shared/rhs.hpp", "max_forks_repo_name": "drreynolds/Math6321-codes", "max_forks_repo_head_hexsha": "3cce53bbe70bdd00220b5d8888b00b20b4fd521b", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-31T18:04:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-31T18:04:07.000Z", "avg_line_length": 23.96875, "max_line_length": 65, "alphanum_fraction": 0.7222946545, "num_tokens": 198, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737214979745, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.48175030880413405}}
{"text": "\ufeff#include \"custom.h\"\n#include<QtWidgets>\n#include<qdebug.h>\n#include<math.h>\n#include <armadillo>\n\nCustom::Custom( QWidget * parent)\n{\n    //initArr();\n    initTableWidget();\n\n    calculationBtn = new QPushButton(QStringLiteral(\"\u91cd\u65b0\u8ba1\u7b97\"),this);\n    connect(calculationBtn,&QPushButton::clicked,this,&Custom::calculation);\n    QVBoxLayout * Vlayout = new QVBoxLayout(this);\n    Vlayout->addWidget(calculationBtn);\n    Vlayout->addWidget(tableWidget);\n    setLayout(Vlayout);\n\n    QString str = QString::fromStdString(arma::arma_version::as_string());\n    qDebug()<<str;\n\n}\n\nvoid Custom::initTableWidget(){\n\n    tableWidget = new QTableWidget(6,7,this);\n\n\n\n    QStringList HHeadList;\n    HHeadList<<\"A(%)\"<<\"B(%)\"<<\"C(%)\"<<\"D(%)\"<<\"E(%)\"<<\"F(%)\"<<QStringLiteral(\"\u91cd\u91cf(g)\");\n    tableWidget->setHorizontalHeaderLabels(HHeadList);\n\n    QStringList VHeadList;\n    VHeadList<<\"1#\"<<\"2#\"<<\"3#\"<<\"4#\"<<\"5#\"<<QStringLiteral(\"\u6df7\u5408\u540e\u5143\u7d20\u542b\u91cf\");\n    tableWidget->setVerticalHeaderLabels(VHeadList);\n\n    for( int i = 0 ; i < tableWidget->rowCount() ; i ++){\n\n        for( int j = 0 ; j < tableWidget->columnCount() ;j++){\n\n            tableWidget->setItem(i,j,new QTableWidgetItem(\"0\"));\n\n        }\n\n    }\n\n    tableWidget->setItem(tableWidget->rowCount()-1,tableWidget->columnCount()-1,new QTableWidgetItem(\"1000\"));\n    tableWidget->show();\n    connect(tableWidget,&QTableWidget::itemChanged,this,&Custom::tableItemChanged);\n\n}\n\nint Custom::calculation(){\n\n    arma::mat A1(4,3,arma::fill::zeros);\n    arma::vec B1(4,arma::fill::zeros);\n    arma::vec X1;\n\n    A1 = {\n            {5,4,-4},\n            {-4,-3,5},\n            {-1,-1,-1},\n            {-8,-7,1}\n         };\n    B1 = {4,-5,1,-1};\n    solve(X1, A1, B1);\n    A1.print(\"A1:\");\n    B1.print(\"B1:\");\n    X1.print(\"X1:\");\n\n    return 0;\n\n    qDebug()<<QStringLiteral(\"\u70b9\u51fb\u91cd\u65b0\u8ba1\u7b97\u6309\u94ae\");\n\n\n    arma::mat A(tableWidget->columnCount()-1,tableWidget->rowCount()-1,arma::fill::zeros);\n    arma::vec B(tableWidget->columnCount()-1,arma::fill::zeros);\n    arma::vec X(tableWidget->rowCount()-1,arma::fill::zeros);\n\n    for( int i = 0 ; i < tableWidget->columnCount()-1; i ++){ //\u6309\u5217\u987a\u5e8f\u4f18\u5148\u904d\u5386\n\n        for( int j = 0 ; j < tableWidget->rowCount()-1 ;j++){\n\n            if(tableWidget->item(j,i)!=nullptr){\n\n\n                QString str = tableWidget->item(j,i)->text();\n                double w = str.toDouble();\n                A(i,j) = w;\n\n            }\n\n        }\n\n    }\n\n    double a1[10] = {0};\n\n    for(int i = 0 ;  i < tableWidget->columnCount()-1; i++){\n\n        if(tableWidget->item(tableWidget->rowCount()-1,i)!=nullptr){\n\n            QString str = tableWidget->item(tableWidget->rowCount()-1,i)->text();\n            double w = str.toDouble();\n            B[i] = 1000*w;\n\n        }\n\n    }\n\n    bool status = solve(X, A, B);\n    A.print(\"A:\");\n    B.print(\"B:\");\n    if( status ){\n\n        for(int i = 0 ; i < tableWidget->columnCount()-1;i++){\n            qDebug()<<X[i];\n        }\n\n\n    }else{\n        QMessageBox::information(NULL, QStringLiteral(\"\u63d0\u793a\"), QStringLiteral(\"\u65e0\u89e3\"),\n                                 QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);\n    }\n\n\n\n\n    /*int a1[10] = {0};\n\n    for(int i = 0 ;  i < tableWidget->columnCount()-1; i++){\n\n        if(tableWidget->item(tableWidget->rowCount()-1,i)!=nullptr){\n\n            QString str = tableWidget->item(tableWidget->rowCount()-1,i)->text();\n            int w = str.toInt();\n            a1[i] = (1000*w)/100;\n\n        }\n\n    }\n\n    for( int i = 0 ; i < tableWidget->columnCount()-1; i ++){ //\u6309\u5217\u987a\u5e8f\u4f18\u5148\u904d\u5386\n\n        for( int j = 0 ; j < tableWidget->rowCount()-1 ;j++){\n\n            if(tableWidget->item(j,i)!=nullptr){\n\n\n\n//                if(j==tableWidget->columnCount()-1){\n\n//                    a[i][j] = a1[i];\n\n//                }else{\n\n//                    QString str = tableWidget->item(i,j)->text();\n//                    int w = str.toInt();\n//                    a[i][j] = w;\n\n//                }\n                QString str = tableWidget->item(j,i)->text();\n                int w = str.toInt();\n                a[i][j] = w;\n\n                //qDebug()<<a[i][j];\n            }\n\n        }\n\n\n    }\n\n    for( int i = 0 ; i < 10 ; i ++){\n\n        int len = tableWidget->columnCount()-1;\n        a[len][i] = a1[i];\n\n    }\n\n\n\n    for( int i = 0 ; i < 10 ; i ++){\n\n        for( int j = 0; j < 10 ; j++){\n            qDebug()<<a[i][j];\n        }\n\n    }\n\n    int var = tableWidget->rowCount()-1; //\u672a\u77e5\u6570\u4e2a\u6570\n    int free_num = Gauss(tableWidget->columnCount()-1,var);\n    if (free_num == -1) {\n\n        QMessageBox::information(NULL, QStringLiteral(\"\u63d0\u793a\"), QStringLiteral(\"\u65e0\u89e3\"),\n                                 QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);\n\n    }\n    else if (free_num == -2){\n\n        QMessageBox::information(NULL, QStringLiteral(\"\u63d0\u793a\"), QStringLiteral(\"\u6709\u6d6e\u70b9\u89e3,\u65e0\u6574\u6570\u89e3\"),\n                                 QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);\n\n    }\n    else if (free_num > 0)\n    {\n//        printf(\"\u65e0\u7a77\u591a\u89e3! \u81ea\u7531\u53d8\u5143\u4e2a\u6570\u4e3a%d\\n\", free_num);\n//        for (i = 0; i < var; i++)\n//        {\n//            if (free_x[i]) printf(\"x%d \u662f\u4e0d\u786e\u5b9a\u7684\\n\", i + 1);\n//            else printf(\"x%d: %d\\n\", i + 1, x[i]);\n//        }\n        QMessageBox::information(NULL, QStringLiteral(\"\u63d0\u793a\"), QStringLiteral(\"\u65e0\u7a77\u591a\u89e3\uff01\"),\n                                 QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);\n    }\n    else\n    {\n        for (int i = 0; i < var; i++)\n        {\n            printf(\"x%d: %d\\n\", i + 1, x[i]);\n        }\n    }*/\n\n    return -1;\n}\n\nvoid Custom::tableItemChanged( QTableWidgetItem * item){\n\n    qDebug()<<QStringLiteral(\"\u5355\u5143\u683c\u6539\u53d8\");\n\n}\n\n\nint Custom::initArr(){\n\n    for( int i = 0 ;  i < 10 ; i ++){\n        for( int j = 0;j<10;j++){\n            a[i][j] = 0;\n        }\n    }\n    return 0;\n}\n\nint Custom::gcd(int a,int b)\n{\n    int t;\n    while(b!=0)\n    {\n        t=b;\n        b=a%b;\n        a=t;\n    }\n    return a;\n}\n\nint Custom::lcm(int a,int b)\n{\n    return a/gcd(a,b)*b;//\u5148\u9664\u540e\u4e58\u9632\u6ea2\u51fa\n}\n\n// \u9ad8\u65af\u6d88\u5143\u6cd5\u89e3\u65b9\u7a0b\u7ec4(Gauss-Jordan elimination).(-2\u8868\u793a\u6709\u6d6e\u70b9\u6570\u89e3\uff0c\u4f46\u65e0\u6574\u6570\u89e3\uff0c\n//-1\u8868\u793a\u65e0\u89e3\uff0c0\u8868\u793a\u552f\u4e00\u89e3\uff0c\u5927\u4e8e0\u8868\u793a\u65e0\u7a77\u89e3\uff0c\u5e76\u8fd4\u56de\u81ea\u7531\u53d8\u5143\u7684\u4e2a\u6570)\n//\u6709equ\u4e2a\u65b9\u7a0b\uff0cvar\u4e2a\u53d8\u5143\u3002\u589e\u5e7f\u77e9\u9635\u884c\u6570\u4e3aequ,\u5206\u522b\u4e3a0\u5230equ-1,\u5217\u6570\u4e3avar+1,\u5206\u522b\u4e3a0\u5230var.\nint Custom::Gauss(int equ,int var)\n{\n    int i,j,k;\n    int max_r;// \u5f53\u524d\u8fd9\u5217\u7edd\u5bf9\u503c\u6700\u5927\u7684\u884c.\n    int col;//\u5f53\u524d\u5904\u7406\u7684\u5217\n    int ta,tb;\n    int LCM;\n    int temp;\n    int free_x_num;\n    int free_index;\n\n    for(int i=0; i<=var; i++)\n    {\n        x[i]=0;\n        free_x[i]=true;\n    }\n\n    //\u8f6c\u6362\u4e3a\u9636\u68af\u9635.\n    col=0; // \u5f53\u524d\u5904\u7406\u7684\u5217\n    for(k = 0; k < equ && col < var; k++,col++)\n    {\n        // \u679a\u4e3e\u5f53\u524d\u5904\u7406\u7684\u884c.\n// \u627e\u5230\u8be5col\u5217\u5143\u7d20\u7edd\u5bf9\u503c\u6700\u5927\u7684\u90a3\u884c\u4e0e\u7b2ck\u884c\u4ea4\u6362.(\u4e3a\u4e86\u5728\u9664\u6cd5\u65f6\u51cf\u5c0f\u8bef\u5dee)\n        max_r=k;\n        for(i=k+1; i<equ; i++)\n        {\n            if(abs(a[i][col])>abs(a[max_r][col])) max_r=i;\n        }\n        if(max_r!=k)\n        {\n            // \u4e0e\u7b2ck\u884c\u4ea4\u6362.\n            for(j=k; j<var+1; j++) std::swap(a[k][j],a[max_r][j]);\n        }\n        if(a[k][col]==0)\n        {\n            // \u8bf4\u660e\u8be5col\u5217\u7b2ck\u884c\u4ee5\u4e0b\u5168\u662f0\u4e86\uff0c\u5219\u5904\u7406\u5f53\u524d\u884c\u7684\u4e0b\u4e00\u5217.\n            k--;\n            continue;\n        }\n        for(i=k+1; i<equ; i++)\n        {\n            // \u679a\u4e3e\u8981\u5220\u53bb\u7684\u884c.\n            if(a[i][col]!=0)\n            {\n                LCM = lcm(abs(a[i][col]),abs(a[k][col]));\n                ta = LCM/abs(a[i][col]);\n                tb = LCM/abs(a[k][col]);\n                if(a[i][col]*a[k][col]<0)tb=-tb;//\u5f02\u53f7\u7684\u60c5\u51b5\u662f\u76f8\u52a0\n                for(j=col; j<var+1; j++)\n                {\n                    a[i][j] = a[i][j]*ta-a[k][j]*tb;\n                }\n            }\n        }\n    }\n\n    //  Debug();\n\n    // 1. \u65e0\u89e3\u7684\u60c5\u51b5: \u5316\u7b80\u7684\u589e\u5e7f\u9635\u4e2d\u5b58\u5728(0, 0, ..., a)\u8fd9\u6837\u7684\u884c(a != 0).\n    for (i = k; i < equ; i++)\n    {\n        // \u5bf9\u4e8e\u65e0\u7a77\u89e3\u6765\u8bf4\uff0c\u5982\u679c\u8981\u5224\u65ad\u54ea\u4e9b\u662f\u81ea\u7531\u53d8\u5143\uff0c\u90a3\u4e48\u521d\u7b49\u884c\u53d8\u6362\u4e2d\u7684\u4ea4\u6362\u5c31\u4f1a\u5f71\u54cd\uff0c\u5219\u8981\u8bb0\u5f55\u4ea4\u6362.\n        if (a[i][col] != 0) return -1;\n    }\n    // 2. \u65e0\u7a77\u89e3\u7684\u60c5\u51b5: \u5728var * (var + 1)\u7684\u589e\u5e7f\u9635\u4e2d\u51fa\u73b0(0, 0, ..., 0)\u8fd9\u6837\u7684\u884c\uff0c\u5373\u8bf4\u660e\u6ca1\u6709\u5f62\u6210\u4e25\u683c\u7684\u4e0a\u4e09\u89d2\u9635.\n    // \u4e14\u51fa\u73b0\u7684\u884c\u6570\u5373\u4e3a\u81ea\u7531\u53d8\u5143\u7684\u4e2a\u6570.\n    if (k < var)\n    {\n        // \u9996\u5148\uff0c\u81ea\u7531\u53d8\u5143\u6709var - k\u4e2a\uff0c\u5373\u4e0d\u786e\u5b9a\u7684\u53d8\u5143\u81f3\u5c11\u6709var - k\u4e2a.\n        for (i = k - 1; i >= 0; i--)\n        {\n            // \u7b2ci\u884c\u4e00\u5b9a\u4e0d\u4f1a\u662f(0, 0, ..., 0)\u7684\u60c5\u51b5\uff0c\u56e0\u4e3a\u8fd9\u6837\u7684\u884c\u662f\u5728\u7b2ck\u884c\u5230\u7b2cequ\u884c.\n            // \u540c\u6837\uff0c\u7b2ci\u884c\u4e00\u5b9a\u4e0d\u4f1a\u662f(0, 0, ..., a), a != 0\u7684\u60c5\u51b5\uff0c\u8fd9\u6837\u7684\u65e0\u89e3\u7684.\n            free_x_num = 0; // \u7528\u4e8e\u5224\u65ad\u8be5\u884c\u4e2d\u7684\u4e0d\u786e\u5b9a\u7684\u53d8\u5143\u7684\u4e2a\u6570\uff0c\u5982\u679c\u8d85\u8fc71\u4e2a\uff0c\u5219\u65e0\u6cd5\u6c42\u89e3\uff0c\u5b83\u4eec\u4ecd\u7136\u4e3a\u4e0d\u786e\u5b9a\u7684\u53d8\u5143.\n            for (j = 0; j < var; j++)\n            {\n                if (a[i][j] != 0 && free_x[j]) free_x_num++, free_index = j;\n            }\n            if (free_x_num > 1) continue; // \u65e0\u6cd5\u6c42\u89e3\u51fa\u786e\u5b9a\u7684\u53d8\u5143.\n            // \u8bf4\u660e\u5c31\u53ea\u6709\u4e00\u4e2a\u4e0d\u786e\u5b9a\u7684\u53d8\u5143free_index\uff0c\u90a3\u4e48\u53ef\u4ee5\u6c42\u89e3\u51fa\u8be5\u53d8\u5143\uff0c\u4e14\u8be5\u53d8\u5143\u662f\u786e\u5b9a\u7684.\n            temp = a[i][var];\n            for (j = 0; j < var; j++)\n            {\n                if (a[i][j] != 0 && j != free_index) temp -= a[i][j] * x[j];\n            }\n            x[free_index] = temp / a[i][free_index]; // \u6c42\u51fa\u8be5\u53d8\u5143.\n            free_x[free_index] = 0; // \u8be5\u53d8\u5143\u662f\u786e\u5b9a\u7684.\n        }\n        return var - k; // \u81ea\u7531\u53d8\u5143\u6709var - k\u4e2a.\n    }\n    // 3. \u552f\u4e00\u89e3\u7684\u60c5\u51b5: \u5728var * (var + 1)\u7684\u589e\u5e7f\u9635\u4e2d\u5f62\u6210\u4e25\u683c\u7684\u4e0a\u4e09\u89d2\u9635.\n    // \u8ba1\u7b97\u51faXn-1, Xn-2 ... X0.\n    for (i = var - 1; i >= 0; i--)\n    {\n        temp = a[i][var];\n        for (j = i + 1; j < var; j++)\n        {\n            if (a[i][j] != 0) temp -= a[i][j] * x[j];\n        }\n        if (temp % a[i][i] != 0) return -2; // \u8bf4\u660e\u6709\u6d6e\u70b9\u6570\u89e3\uff0c\u4f46\u65e0\u6574\u6570\u89e3.\n        x[i] = temp / a[i][i];\n    }\n    return 0;\n}\n", "meta": {"hexsha": "cbb5407b013b88e07632354091c13592d7fdb138", "size": 8938, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "custom.cpp", "max_stars_repo_name": "lixiangQQQ/Equation", "max_stars_repo_head_hexsha": "f8e2211e5a9f21f0977fd1f34ee43885c5c86868", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "custom.cpp", "max_issues_repo_name": "lixiangQQQ/Equation", "max_issues_repo_head_hexsha": "f8e2211e5a9f21f0977fd1f34ee43885c5c86868", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "custom.cpp", "max_forks_repo_name": "lixiangQQQ/Equation", "max_forks_repo_head_hexsha": "f8e2211e5a9f21f0977fd1f34ee43885c5c86868", "max_forks_repo_licenses": ["Apache-2.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.2222222222, "max_line_length": 110, "alphanum_fraction": 0.4712463638, "num_tokens": 3066, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.48173724525798745}}
{"text": "#include \"common.h\"\n#include <limits>\n#include <cmath>\n#include <ctime>\n#include <boost/random/uniform_int_distribution.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_01.hpp>\n\nboost::random::mt19937 rng(time(0));\nboost::random::uniform_01<elem_t> dist01;\nstd::ostream* logOut = &std::cout;\nLogLevel currentLogLevel = Error;\n\nColor::Modifier red(Color::FG_RED);\nColor::Modifier def(Color::FG_DEFAULT);\nColor::Modifier green(Color::FG_GREEN);\nColor::Modifier yellow(Color::FG_YELLOW);\n\n\nlong double logint[MAX_COUNT + 1];\nlong double logfactorial[MAX_COUNT + 1];\ndouble Pi = acos(-1.0);\nintN bionomial[MAX_N + 1][MAX_N + 1];\n\nstd::ostream& operator<< (std::ostream& out, LogLevel level) {\n    if (level == Info) {\n        out << \"Info:\";\n    } else if (level == Warning) {\n        out << \"Warning:\";\n    } else if (level == Error) {\n        out << \"Error:\";\n    } else {\n        // do nothing.\n    }\n}\n\nlong double LogInt(int n)\n{\n\tif (n == 0) {\n\t\tstd::cout << \"error! log(0)\" << std::endl;\n\t\treturn std::numeric_limits<long double>::max();\n\t}\n\tif (n == 1) return 0.0;\n\n\tif (logint[n] == 0.0) {\n\t\tlogint[n] = logl(n);\n\t}\n\t\n\treturn logint[n];\n}\n\nlong double LogFactorial(int n)\n{\n\tif (n == 1 || n == 0) return 0.0;\n\n\tif (logfactorial[n] == 0.0) {\n\t\tfor (int i = 2; i <= n; i++) {\n\t\t\tlogfactorial[n] += LogInt(i);\n\t\t}\n\t}\n\n\treturn logfactorial[n];\n}\n\nelem_t random(elem_t min, elem_t max)\n{\n    return min + (max - min) * dist01(rng);\n}\n\ni64 random64(i64 max)\n{\n    boost::random::uniform_int_distribution<i64> dist(0, max);\n    return dist(rng);\n}\n\nu128 random128(u128 max)\n{\n    boost::random::uniform_int_distribution<u64> high(0, (u64)(max >> 64));\n    boost::random::uniform_int_distribution<u64> low(0, (u64)(max & std::numeric_limits<u64>::max()));\n\n    return (((u128)high(rng)) << 64) | low(rng);\n}\n\nvar_t randomComplex(elem_t minR, elem_t maxR) {\n    elem_t r;\n    while(true) {\n        r = random(minR, maxR);\n        if (random(0.0, maxR * maxR - minR * minR) < (r * r - minR * minR)) {\n            break;\n        }\n    }\n    elem_t phi = random(0.0, 2 * Pi);\n    return var_t(r * cos(phi), r * sin(phi));\n}\n\n\n\ndouble EuclideanDist(double x1, double y1, double x2, double y2)\n{\n\treturn sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));\n}\n\ndouble EuclideanDistSquare(double x1, double y1, double x2, double y2)\n{\n\treturn (x1-x2)*(x1-x2) + (y1-y2)*(y1-y2);\n}\n\nintN BioCoeff(int n, int k)\n{\n\tif (k > n) return 0;\n\tif (k == 0 || k == n) return 1;\n\tintN& ret = bionomial[n][k];\n\tif (ret == 0) {\n\t\tret = BioCoeff(n - 1, k) + BioCoeff(n - 1, k - 1);\n\t}\n\n\treturn ret;\n}\n\nbool isSingular(var_t u, elem_t eps) {\n    return std::abs(u.real()) < eps && (std::abs(u.imag() + 0.5) < eps || std::abs(u.imag() - 0.5) < eps);\n}\n\nvar_t e2ip(var_t u, elem_t eps) {\n    if (isSingular(u)) {\n        if (u.imag() > (elem_t)0.0) {\n            return (elem_t)1.0;\n        } else {\n            return (elem_t)-1.0;\n        }\n    }\n    return (u + var_t(0.0, 0.5))/(u - var_t(0.0, 0.5));\n/*    if (abs(u.real()) > EPS) {\n        return (u + var_t(0.0, 0.5))/(u - var_t(0.0, 0.5));\n    } else {\n        if (abs(u.imag() + 0.5) <= EPS) {\n            return var_t(0, -EPS);\n        } else if (abs(u.imag() - 0.5) <= EPS) {\n            return var_t(0, 1/EPS);\n        } else {\n            return (u + var_t(0.0, 0.5))/(u - var_t(0.0, 0.5));\n        }\n    }*/\n}\n\nvar_t e2ip(const Vector &u, elem_t eps) {\n    var_t ret((elem_t)1.0);\n    for (int i = 0; i < u.size(); i++) {\n        ret *= e2ip(u[i], eps);\n    }\n    return ret;\n}\n\nelem_t momentum(Vector u, elem_t eps) {\n    var_t ret = e2ip(u, eps);\n//    return log(ret) * var_t(0.0, -1.0);\n    return std::arg(ret);\n}\n\nvar_t sMatrix(var_t u1, var_t u2) {\n    return (u1 - u2 - var_t(0, 1.0))/(u1 - u2 + var_t(0, 1.0));\n}\n\nelem_t floatMod(elem_t num1, elem_t num2) {\n    return num1 - floor((num1 + num2 * 0.5)/num2) * num2;\n}\n\nbool isZero(const var_t &val) {\n    return abs(val.real()) < EPS && abs(val.imag()) < EPS;\n}\n\nvar_t chop(var_t v, elem_t eps) {\n    elem_t re = v.real();\n    elem_t im = v.imag();\n    if (std::abs(re) < eps) re = 0.0L;\n    if (std::abs(im) < eps) im = 0.0L;\n    return var_t(re, im);\n}\n\nvoid chop(Vector &v, elem_t eps) {\n    for (int i = 0; i < v.size(); i++) {\n        v[i] = chop(v[i], eps);\n    }\n}\n\n\nStopwatch::Stopwatch()\n{\n    start = clock();\n}\n\nvoid Stopwatch::Restart()\n{\n        start = clock();\n}\n\nstd::string Stopwatch::Log(bool restart)\n{\n    double ret = (clock() - start) / (double)CLOCKS_PER_SEC;\n    std::string text = ToString(ret) + \" seconds elapsed, current time \" + Now();\n    \n    if (restart) {\n        Restart();\n    }\n    \n    return text;\n}\n\nstd::string Stopwatch::Now()\n{\n    time_t t = time(0);   // get time now\n    struct tm * now = localtime(&t);\n    char buf[80];\n    strftime(buf, sizeof(buf), \"%Y-%m-%d.%X\", now);\n    return buf;\n}\n\n/// return how much time in second since last Start() function call\ndouble Stopwatch::Elapsed(bool restart)\n{\n        double ret = (clock() - start) / (double)CLOCKS_PER_SEC;\n        if (restart) Restart();\n        return ret;\n}\n", "meta": {"hexsha": "044917432fda36357ed9f69a96b5caa8beab1400", "size": 5080, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/common.cpp", "max_stars_repo_name": "gaolichen/bethesolver", "max_stars_repo_head_hexsha": "1b4f0c097ed028e1a52f05fda034e2864eb37d24", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/common.cpp", "max_issues_repo_name": "gaolichen/bethesolver", "max_issues_repo_head_hexsha": "1b4f0c097ed028e1a52f05fda034e2864eb37d24", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/common.cpp", "max_forks_repo_name": "gaolichen/bethesolver", "max_forks_repo_head_hexsha": "1b4f0c097ed028e1a52f05fda034e2864eb37d24", "max_forks_repo_licenses": ["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.5777777778, "max_line_length": 106, "alphanum_fraction": 0.562007874, "num_tokens": 1701, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.48172692921217275}}
{"text": "//==================================================================================================\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#include <simd_test.hpp>\n#include <boost/simd/function/sincos.hpp>\n#include <boost/simd/pack.hpp>\n#include <boost/simd/function/std.hpp>\n#include <boost/simd/constant/pio_4.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/minf.hpp>\n#include <boost/simd/constant/nan.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/mone.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/constant/mzero.hpp>\n#include <boost/simd/function/sin.hpp>\n#include <boost/simd/function/cos.hpp>\n\n\nnamespace bs = boost::simd;\n\ntemplate <typename T, std::size_t N, typename Env>\nvoid test(Env& runtime)\n{\n  using p_t = bs::pack<T, N>;\n\n  T a1[N], c[N], s[N];\n  for(std::size_t i = 0; i < N; ++i)\n  {\n    a1[i] = (i%2) ? T(i) : -T(i);\n    std::tie(s[i], c[i])= bs::sincos(a1[i]);\n  }\n\n  p_t aa1(&a1[0], &a1[0]+N);\n  p_t ss (&s[0], &s[0]+N);\n  p_t cc (&c[0], &c[0]+N);\n  p_t ss1, cc1;\n  std::tie(ss1, cc1)= bs::sincos(aa1);\n\n  STF_ULP_EQUAL(ss1, ss,0.5);\n  STF_ULP_EQUAL(cc1, cc,0.5);\n}\n\nSTF_CASE_TPL(\"Check sincos on pack\" , STF_IEEE_TYPES)\n{\n  static const std::size_t N = bs::pack<T>::static_size;\n\n  test<T, N>(runtime);\n  test<T, N/2>(runtime);\n  test<T, N*2>(runtime);\n}\n\ntemplate <typename T, std::size_t N, typename Env>\nvoid testr(Env& runtime)\n{\n  using p_t = bs::pack<T, N>;\n\n  T a1[N], c[N], s[N];\n  for(std::size_t i = 0; i < N; ++i)\n  {\n    a1[i] = ((i%2) ? T(i) : -T(i))*bs::Pio_4<T>()/N;\n    std::tie(s[i], c[i])= bs::restricted_(bs::sincos)(a1[i]);\n  }\n\n  p_t aa1(&a1[0], &a1[0]+N);\n  p_t ss (&s[0], &s[0]+N);\n  p_t cc (&c[0], &c[0]+N);\n  p_t ss1, cc1;\n  std::tie(ss1, cc1)= bs::restricted_(bs::sincos)(aa1);\n\n  STF_ULP_EQUAL(ss1, ss,0.5);\n  STF_ULP_EQUAL(cc1, cc,0.5);\n}\n\nSTF_CASE_TPL(\"Check restricted sincos on pack\" , STF_IEEE_TYPES)\n{\n  static const std::size_t N = bs::pack<T>::static_size;\n\n  testr<T, N>(runtime);\n  testr<T, N/2>(runtime);\n  testr<T, N*2>(runtime);\n}\n\n\nSTF_CASE_TPL (\" sincos\",  STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using p_t = bs::pack<T>;\n\n  using bs::sincos;\n  p_t a[] = {bs::Zero<p_t>(), bs::One<p_t>(), bs::Pio2_3<p_t>(), bs::Pi<p_t>(),\n           bs::Pio_2<p_t>(), bs::Inf<p_t>(), bs::Minf<p_t>(), bs::Nan<p_t>()};\n  size_t N =  sizeof(a)/sizeof(p_t);\n\n  STF_EXPR_IS( (sincos(p_t()))\n             , (std::pair<p_t,p_t>)\n             );\n\n   {\n    for(size_t i=0; i < N; ++i)\n    {\n      std::pair<p_t,p_t> p = sincos(a[i]);\n      STF_IEEE_EQUAL(p.first,  bs::sin(a[i]));\n      STF_IEEE_EQUAL(p.second, bs::cos(a[i]));\n      std::pair<p_t,p_t> q = bs::restricted_(bs::sincos)(a[i]);\n      STF_IEEE_EQUAL(q.first,  bs::restricted_(bs::sin)(a[i]));\n      STF_IEEE_EQUAL(q.second, bs::restricted_(bs::cos)(a[i]));\n    }\n   }\n\n}\n\ntemplate <typename T, std::size_t N, typename Env>\nvoid testc(Env& runtime)\n{\n  namespace bst = bs::tag;\n  using p_t = bs::pack<T, N>;\n\n  T a1[N], c[N], s[N];\n  for(std::size_t i = 0; i < N; ++i)\n  {\n    a1[i] = ((i%2) ? T(i) : -T(i))*bs::Pio_4<T>()/N;\n    std::tie(s[i], c[i])= bs::sincos(a1[i], bst::clipped_medium_);\n  }\n\n  p_t aa1(&a1[0], &a1[0]+N);\n  p_t ss (&s[0], &s[0]+N);\n  p_t cc (&c[0], &c[0]+N);\n  p_t ss1, cc1;\n  std::tie(ss1, cc1)= bs::sincos(aa1, bst::clipped_medium_);\n\n  STF_ULP_EQUAL(ss1, ss,0.5);\n  STF_ULP_EQUAL(cc1, cc,0.5);\n}\n\nSTF_CASE_TPL(\"Check clipped  sincos on pack\" , STF_IEEE_TYPES)\n{\n  static const std::size_t N = bs::pack<T>::static_size;\n\n  testc<T, N>(runtime);\n  testc<T, N/2>(runtime);\n  testc<T, N*2>(runtime);\n}\n", "meta": {"hexsha": "028bce3361d915ffd0fbdbf7bebf8d917115b9c1", "size": 3887, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/simd/sincos.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": "test/function/simd/sincos.cpp", "max_issues_repo_name": "remymuller/boost.simd", "max_issues_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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/function/simd/sincos.cpp", "max_forks_repo_name": "remymuller/boost.simd", "max_forks_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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": 25.9133333333, "max_line_length": 100, "alphanum_fraction": 0.5649601235, "num_tokens": 1408, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.48172692921217275}}
{"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_ACOT_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_ACOT_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 inverse cotangent.\n\n\n    @par Header <boost/simd/function/acot.hpp>\n\n    @par Note\n\n      For every parameter of floating type `r = acot(x)`\n      returns the arc @c r in the interval  \\f$[0, \\pi[\\f$ such that\n      <tt>cot(r) == x</tt>.\n\n    @see acotd, acotpi, cot\n\n\n    @par Example:\n\n      @snippet acot.cpp acot\n\n    @par Possible output:\n\n      @snippet acot.txt acot\n\n  **/\n  IEEEValue acot(IEEEValue const & x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/acot.hpp>\n#include <boost/simd/function/simd/acot.hpp>\n\n#endif\n", "meta": {"hexsha": "481fda25bc0dafd4ef2a457e84ebd1248803d829", "size": 1157, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/acot.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/acot.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/acot.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.6862745098, "max_line_length": 100, "alphanum_fraction": 0.5687121867, "num_tokens": 267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.48172692921217275}}
{"text": "// Copyright John Maddock 2006.\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#include \"mp_t.hpp\"\n#include <boost/math/tools/test_data.hpp>\n#include <boost/test/included/prg_exec_monitor.hpp>\n#include <boost/math/special_functions/ellint_rj.hpp>\n#include <boost/math/special_functions/ellint_rd.hpp>\n#include <fstream>\n#include <boost/math/tools/test_data.hpp>\n#include <boost/random.hpp>\n\nfloat extern_val;\n// confuse the compilers optimiser, and force a truncation to float precision:\nfloat truncate_to_float(float const * pf)\n{\n   extern_val = *pf;\n   return *pf;\n}\n\n//\n// Archived here is the original implementation of this\n// function by Xiaogang Zhang, we can use this to\n// generate special test cases for the new version:\n//\ntemplate <typename T, typename Policy>\nT ellint_rj_old(T x, T y, T z, T p, const Policy& pol)\n{\n   T value, u, lambda, alpha, beta, sigma, factor, tolerance;\n   T X, Y, Z, P, EA, EB, EC, E2, E3, S1, S2, S3;\n   unsigned long k;\n\n   BOOST_MATH_STD_USING\n      using namespace boost::math;\n\n   static const char* function = \"boost::math::ellint_rj<%1%>(%1%,%1%,%1%)\";\n\n   if(x < 0)\n   {\n      return policies::raise_domain_error<T>(function,\n         \"Argument x must be non-negative, but got x = %1%\", x, pol);\n   }\n   if(y < 0)\n   {\n      return policies::raise_domain_error<T>(function,\n         \"Argument y must be non-negative, but got y = %1%\", y, pol);\n   }\n   if(z < 0)\n   {\n      return policies::raise_domain_error<T>(function,\n         \"Argument z must be non-negative, but got z = %1%\", z, pol);\n   }\n   if(p == 0)\n   {\n      return policies::raise_domain_error<T>(function,\n         \"Argument p must not be zero, but got p = %1%\", p, pol);\n   }\n   if(x + y == 0 || y + z == 0 || z + x == 0)\n   {\n      return policies::raise_domain_error<T>(function,\n         \"At most one argument can be zero, \"\n         \"only possible result is %1%.\", std::numeric_limits<T>::quiet_NaN(), pol);\n   }\n\n   // error scales as the 6th power of tolerance\n   tolerance = pow(T(1) * tools::epsilon<T>() / 3, T(1) / 6);\n\n   // for p < 0, the integral is singular, return Cauchy principal value\n   if(p < 0)\n   {\n      //\n      // We must ensure that (z - y) * (y - x) is positive.\n      // Since the integral is symmetrical in x, y and z\n      // we can just permute the values:\n      //\n      if(x > y)\n         std::swap(x, y);\n      if(y > z)\n         std::swap(y, z);\n      if(x > y)\n         std::swap(x, y);\n\n      T q = -p;\n      T pmy = (z - y) * (y - x) / (y + q);  // p - y\n\n      BOOST_ASSERT(pmy >= 0);\n\n      p = pmy + y;\n      value = ellint_rj_old(x, y, z, p, pol);\n      value *= pmy;\n      value -= 3 * boost::math::ellint_rf(x, y, z, pol);\n      value += 3 * sqrt((x * y * z) / (x * z + p * q)) * boost::math::ellint_rc(x * z + p * q, p * q, pol);\n      value /= (y + q);\n      return value;\n   }\n\n   // duplication\n   sigma = 0;\n   factor = 1;\n   k = 1;\n   do\n   {\n      u = (x + y + z + p + p) / 5;\n      X = (u - x) / u;\n      Y = (u - y) / u;\n      Z = (u - z) / u;\n      P = (u - p) / u;\n\n      if((tools::max)(abs(X), abs(Y), abs(Z), abs(P)) < tolerance)\n         break;\n\n      T sx = sqrt(x);\n      T sy = sqrt(y);\n      T sz = sqrt(z);\n\n      lambda = sy * (sx + sz) + sz * sx;\n      alpha = p * (sx + sy + sz) + sx * sy * sz;\n      alpha *= alpha;\n      beta = p * (p + lambda) * (p + lambda);\n      sigma += factor * boost::math::ellint_rc(alpha, beta, pol);\n      factor /= 4;\n      x = (x + lambda) / 4;\n      y = (y + lambda) / 4;\n      z = (z + lambda) / 4;\n      p = (p + lambda) / 4;\n      ++k;\n   } while(k < policies::get_max_series_iterations<Policy>());\n\n   // Check to see if we gave up too soon:\n   policies::check_series_iterations<T>(function, k, pol);\n\n   // Taylor series expansion to the 5th order\n   EA = X * Y + Y * Z + Z * X;\n   EB = X * Y * Z;\n   EC = P * P;\n   E2 = EA - 3 * EC;\n   E3 = EB + 2 * P * (EA - EC);\n   S1 = 1 + E2 * (E2 * T(9) / 88 - E3 * T(9) / 52 - T(3) / 14);\n   S2 = EB * (T(1) / 6 + P * (T(-6) / 22 + P * T(3) / 26));\n   S3 = P * ((EA - EC) / 3 - P * EA * T(3) / 22);\n   value = 3 * sigma + factor * (S1 + S2 + S3) / (u * sqrt(u));\n\n   return value;\n}\n\ntemplate <typename T, typename Policy>\nT ellint_rd_imp_old(T x, T y, T z, const Policy& pol)\n{\n   T value, u, lambda, sigma, factor, tolerance;\n   T X, Y, Z, EA, EB, EC, ED, EE, S1, S2;\n   unsigned long k;\n\n   BOOST_MATH_STD_USING\n   using namespace boost::math;\n\n   static const char* function = \"boost::math::ellint_rd<%1%>(%1%,%1%,%1%)\";\n\n   if(x < 0)\n   {\n      return policies::raise_domain_error<T>(function,\n         \"Argument x must be >= 0, but got %1%\", x, pol);\n   }\n   if(y < 0)\n   {\n      return policies::raise_domain_error<T>(function,\n         \"Argument y must be >= 0, but got %1%\", y, pol);\n   }\n   if(z <= 0)\n   {\n      return policies::raise_domain_error<T>(function,\n         \"Argument z must be > 0, but got %1%\", z, pol);\n   }\n   if(x + y == 0)\n   {\n      return policies::raise_domain_error<T>(function,\n         \"At most one argument can be zero, but got, x + y = %1%\", x + y, pol);\n   }\n\n   // error scales as the 6th power of tolerance\n   tolerance = pow(tools::epsilon<T>() / 3, T(1) / 6);\n\n   // duplication\n   sigma = 0;\n   factor = 1;\n   k = 1;\n   do\n   {\n      u = (x + y + z + z + z) / 5;\n      X = (u - x) / u;\n      Y = (u - y) / u;\n      Z = (u - z) / u;\n      if((tools::max)(abs(X), abs(Y), abs(Z)) < tolerance)\n         break;\n      T sx = sqrt(x);\n      T sy = sqrt(y);\n      T sz = sqrt(z);\n      lambda = sy * (sx + sz) + sz * sx; //sqrt(x * y) + sqrt(y * z) + sqrt(z * x);\n      sigma += factor / (sz * (z + lambda));\n      factor /= 4;\n      x = (x + lambda) / 4;\n      y = (y + lambda) / 4;\n      z = (z + lambda) / 4;\n      ++k;\n   } while(k < policies::get_max_series_iterations<Policy>());\n\n   // Check to see if we gave up too soon:\n   policies::check_series_iterations<T>(function, k, pol);\n\n   // Taylor series expansion to the 5th order\n   EA = X * Y;\n   EB = Z * Z;\n   EC = EA - EB;\n   ED = EA - 6 * EB;\n   EE = ED + EC + EC;\n   S1 = ED * (ED * T(9) / 88 - Z * EE * T(9) / 52 - T(3) / 14);\n   S2 = Z * (EE / 6 + Z * (-EC * T(9) / 22 + Z * EA * T(3) / 26));\n   value = 3 * sigma + factor * (1 + S1 + S2) / (u * sqrt(u));\n\n   return value;\n}\n\ntemplate <typename T, typename Policy>\nT ellint_rf_imp_old(T x, T y, T z, const Policy& pol)\n{\n   T value, X, Y, Z, E2, E3, u, lambda, tolerance;\n   unsigned long k;\n   BOOST_MATH_STD_USING\n   using namespace boost::math;\n   static const char* function = \"boost::math::ellint_rf<%1%>(%1%,%1%,%1%)\";\n   if(x < 0 || y < 0 || z < 0)\n   {\n      return policies::raise_domain_error<T>(function,\n         \"domain error, all arguments must be non-negative, \"\n         \"only sensible result is %1%.\",\n         std::numeric_limits<T>::quiet_NaN(), pol);\n   }\n   if(x + y == 0 || y + z == 0 || z + x == 0)\n   {\n      return policies::raise_domain_error<T>(function,\n         \"domain error, at most one argument can be zero, \"\n         \"only sensible result is %1%.\",\n         std::numeric_limits<T>::quiet_NaN(), pol);\n   }\n   // Carlson scales error as the 6th power of tolerance,\n   // but this seems not to work for types larger than\n   // 80-bit reals, this heuristic seems to work OK:\n   if(policies::digits<T, Policy>() > 64)\n   {\n      tolerance = pow(tools::epsilon<T>(), T(1) / 4.25f);\n      BOOST_MATH_INSTRUMENT_VARIABLE(tolerance);\n   }\n   else\n   {\n      tolerance = pow(4 * tools::epsilon<T>(), T(1) / 6);\n      BOOST_MATH_INSTRUMENT_VARIABLE(tolerance);\n   }\n   // duplication\n   k = 1;\n   do\n   {\n      u = (x + y + z) / 3;\n      X = (u - x) / u;\n      Y = (u - y) / u;\n      Z = (u - z) / u;\n      // Termination condition:\n      if((tools::max)(abs(X), abs(Y), abs(Z)) < tolerance)\n         break;\n      T sx = sqrt(x);\n      T sy = sqrt(y);\n      T sz = sqrt(z);\n      lambda = sy * (sx + sz) + sz * sx;\n      x = (x + lambda) / 4;\n      y = (y + lambda) / 4;\n      z = (z + lambda) / 4;\n      ++k;\n   } while(k < policies::get_max_series_iterations<Policy>());\n   // Check to see if we gave up too soon:\n   policies::check_series_iterations<T>(function, k, pol);\n   BOOST_MATH_INSTRUMENT_VARIABLE(k);\n   // Taylor series expansion to the 5th order\n   E2 = X * Y - Z * Z;\n   E3 = X * Y * Z;\n   value = (1 + E2*(E2 / 24 - E3*T(3) / 44 - T(0.1)) + E3 / 14) / sqrt(u);\n   BOOST_MATH_INSTRUMENT_VARIABLE(value);\n   return value;\n}\n\n\n\nboost::math::tuple<mp_t, mp_t, mp_t, mp_t> generate_rj_data_4e(mp_t n)\n{\n   mp_t result = ellint_rj_old(n, n, n, n, boost::math::policies::policy<>());\n   return boost::math::make_tuple(n, n, n, result);\n}\n\nboost::math::tuple<mp_t, mp_t, mp_t, mp_t, mp_t> generate_rj_data_3e(mp_t x, mp_t p)\n{\n   mp_t r = ellint_rj_old(x, x, x, p, boost::math::policies::policy<>());\n   return boost::math::make_tuple(x, x, x, p, r);\n}\n\nboost::math::tuple<mp_t, mp_t, mp_t, mp_t, mp_t> generate_rj_data_2e_1(mp_t x, mp_t y, mp_t p)\n{\n   mp_t r = ellint_rj_old(x, x, y, p, boost::math::policies::policy<>());\n   return boost::math::make_tuple(x, x, y, p, r);\n}\n\nboost::math::tuple<mp_t, mp_t, mp_t, mp_t, mp_t> generate_rj_data_2e_2(mp_t x, mp_t y, mp_t p)\n{\n   mp_t r = ellint_rj_old(x, y, x, p, boost::math::policies::policy<>());\n   return boost::math::make_tuple(x, y, x, p, r);\n}\n\nboost::math::tuple<mp_t, mp_t, mp_t, mp_t, mp_t> generate_rj_data_2e_3(mp_t x, mp_t y, mp_t p)\n{\n   mp_t r = ellint_rj_old(y, x, x, p, boost::math::policies::policy<>());\n   return boost::math::make_tuple(y, x, x, p, r);\n}\n\nboost::math::tuple<mp_t, mp_t, mp_t, mp_t, mp_t> generate_rj_data_2e_4(mp_t x, mp_t y, mp_t p)\n{\n   mp_t r = ellint_rj_old(x, y, p, p, boost::math::policies::policy<>());\n   return boost::math::make_tuple(x, y, p, p, r);\n}\n\nboost::math::tuple<mp_t, mp_t, mp_t, mp_t> generate_rd_data_2e_1(mp_t x, mp_t y)\n{\n   mp_t r = ellint_rd_imp_old(x, y, y, boost::math::policies::policy<>());\n   return boost::math::make_tuple(x, y, y, r);\n}\n\nboost::math::tuple<mp_t, mp_t, mp_t, mp_t> generate_rd_data_2e_2(mp_t x, mp_t y)\n{\n   mp_t r = ellint_rd_imp_old(x, x, y, boost::math::policies::policy<>());\n   return boost::math::make_tuple(x, x, y, r);\n}\n\nboost::math::tuple<mp_t, mp_t, mp_t, mp_t> generate_rd_data_2e_3(mp_t x)\n{\n   mp_t r = ellint_rd_imp_old(mp_t(0), x, x, boost::math::policies::policy<>());\n   return boost::math::make_tuple(0, x, x, r);\n}\n\nboost::math::tuple<mp_t, mp_t, mp_t, mp_t> generate_rd_data_3e(mp_t x)\n{\n   mp_t r = ellint_rd_imp_old(x, x, x, boost::math::policies::policy<>());\n   return boost::math::make_tuple(x, x, x, r);\n}\n\nboost::math::tuple<mp_t, mp_t, mp_t, mp_t> generate_rd_data_0xy(mp_t x, mp_t y)\n{\n   mp_t r = ellint_rd_imp_old(mp_t(0), x, y, boost::math::policies::policy<>());\n   return boost::math::make_tuple(mp_t(0), x, y, r);\n}\n\nboost::math::tuple<mp_t, mp_t, mp_t, mp_t> generate_rf_data_xxx(mp_t x)\n{\n   mp_t r = ellint_rf_imp_old(x, x, x, boost::math::policies::policy<>());\n   return boost::math::make_tuple(x, x, x, r);\n}\n\nboost::math::tuple<mp_t, mp_t, mp_t, mp_t> generate_rf_data_xyy(mp_t x, mp_t y)\n{\n   mp_t r = ellint_rf_imp_old(x, y, y, boost::math::policies::policy<>());\n   return boost::math::make_tuple(x, y, y, r);\n}\n\nboost::math::tuple<mp_t, mp_t, mp_t, mp_t> generate_rf_data_xxy(mp_t x, mp_t y)\n{\n   mp_t r = ellint_rf_imp_old(x, x, y, boost::math::policies::policy<>());\n   return boost::math::make_tuple(x, x, y, r);\n}\n\nboost::math::tuple<mp_t, mp_t, mp_t, mp_t> generate_rf_data_xyx(mp_t x, mp_t y)\n{\n   mp_t r = ellint_rf_imp_old(x, y, x, boost::math::policies::policy<>());\n   return boost::math::make_tuple(x, y, x, r);\n}\n\nboost::math::tuple<mp_t, mp_t, mp_t, mp_t> generate_rf_data_0yy(mp_t y)\n{\n   mp_t r = ellint_rf_imp_old(mp_t(0), y, y, boost::math::policies::policy<>());\n   return boost::math::make_tuple(mp_t(0), y, y, r);\n}\n\nboost::math::tuple<mp_t, mp_t, mp_t, mp_t> generate_rf_data_xy0(mp_t x, mp_t y)\n{\n   mp_t r = ellint_rf_imp_old(x, y, mp_t(0), boost::math::policies::policy<>());\n   return boost::math::make_tuple(x, y, mp_t(0), r);\n}\n\nboost::math::tuple<mp_t, mp_t, mp_t, mp_t> generate_rf_data(mp_t n)\n{\n   static boost::mt19937 r;\n   boost::uniform_real<float> ur(0, 1);\n   boost::uniform_int<int> ui(-100, 100);\n   float x = ur(r);\n   x = ldexp(x, ui(r));\n   mp_t xr(truncate_to_float(&x));\n   float y = ur(r);\n   y = ldexp(y, ui(r));\n   mp_t yr(truncate_to_float(&y));\n   float z = ur(r);\n   z = ldexp(z, ui(r));\n   mp_t zr(truncate_to_float(&z));\n\n   mp_t result = boost::math::ellint_rf(xr, yr, zr);\n   return boost::math::make_tuple(xr, yr, zr, result);\n}\n\nboost::math::tuple<mp_t, mp_t, mp_t> generate_rc_data(mp_t n)\n{\n   static boost::mt19937 r;\n   boost::uniform_real<float> ur(0, 1);\n   boost::uniform_int<int> ui(-100, 100);\n   float x = ur(r);\n   x = ldexp(x, ui(r));\n   mp_t xr(truncate_to_float(&x));\n   float y = ur(r);\n   y = ldexp(y, ui(r));\n   mp_t yr(truncate_to_float(&y));\n\n   mp_t result = boost::math::ellint_rc(xr, yr);\n   return boost::math::make_tuple(xr, yr, result);\n}\n\nboost::math::tuple<mp_t, mp_t, mp_t, mp_t, mp_t> generate_rj_data(mp_t n)\n{\n   static boost::mt19937 r;\n   boost::uniform_real<float> ur(0, 1);\n   boost::uniform_real<float> nur(-1, 1);\n   boost::uniform_int<int> ui(-100, 100);\n   float x = ur(r);\n   x = ldexp(x, ui(r));\n   mp_t xr(truncate_to_float(&x));\n   float y = ur(r);\n   y = ldexp(y, ui(r));\n   mp_t yr(truncate_to_float(&y));\n   float z = ur(r);\n   z = ldexp(z, ui(r));\n   mp_t zr(truncate_to_float(&z));\n   float p = nur(r);\n   p = ldexp(p, ui(r));\n   mp_t pr(truncate_to_float(&p));\n\n   boost::math::ellint_rj(x, y, z, p);\n\n   mp_t result = boost::math::ellint_rj(xr, yr, zr, pr);\n   return boost::math::make_tuple(xr, yr, zr, pr, result);\n}\n\nboost::math::tuple<mp_t, mp_t, mp_t, mp_t> generate_rd_data(mp_t n)\n{\n   static boost::mt19937 r;\n   boost::uniform_real<float> ur(0, 1);\n   boost::uniform_int<int> ui(-100, 100);\n   float x = ur(r);\n   x = ldexp(x, ui(r));\n   mp_t xr(truncate_to_float(&x));\n   float y = ur(r);\n   y = ldexp(y, ui(r));\n   mp_t yr(truncate_to_float(&y));\n   float z = ur(r);\n   z = ldexp(z, ui(r));\n   mp_t zr(truncate_to_float(&z));\n\n   mp_t result = boost::math::ellint_rd(xr, yr, zr);\n   return boost::math::make_tuple(xr, yr, zr, result);\n}\n\nmp_t rg_imp(mp_t x, mp_t y, mp_t z)\n{\n   using std::swap;\n   // If z is zero permute so the call to RD is valid:\n   if(z == 0)\n      swap(x, z);\n   return (z * ellint_rf_imp_old(x, y, z, boost::math::policies::policy<>())\n      - (x - z) * (y - z) * ellint_rd_imp_old(x, y, z, boost::math::policies::policy<>()) / 3\n      + sqrt(x * y / z)) / 2;\n}\n\nboost::math::tuple<mp_t, mp_t, mp_t, mp_t> generate_rg_data(mp_t n)\n{\n   static boost::mt19937 r;\n   boost::uniform_real<float> ur(0, 1);\n   boost::uniform_int<int> ui(-100, 100);\n   float x = ur(r);\n   x = ldexp(x, ui(r));\n   mp_t xr(truncate_to_float(&x));\n   float y = ur(r);\n   y = ldexp(y, ui(r));\n   mp_t yr(truncate_to_float(&y));\n   float z = ur(r);\n   z = ldexp(z, ui(r));\n   mp_t zr(truncate_to_float(&z));\n\n   mp_t result = rg_imp(xr, yr, zr);\n   return boost::math::make_tuple(xr, yr, zr, result);\n}\n\nboost::math::tuple<mp_t, mp_t, mp_t, mp_t> generate_rg_xxx(mp_t x)\n{\n   mp_t result = rg_imp(x, x, x);\n   return boost::math::make_tuple(x, x, x, result);\n}\n\nboost::math::tuple<mp_t, mp_t, mp_t, mp_t> generate_rg_xyy(mp_t x, mp_t y)\n{\n   mp_t result = rg_imp(x, y, y);\n   return boost::math::make_tuple(x, y, y, result);\n}\n\nboost::math::tuple<mp_t, mp_t, mp_t, mp_t> generate_rg_xxy(mp_t x, mp_t y)\n{\n   mp_t result = rg_imp(x, x, y);\n   return boost::math::make_tuple(x, x, y, result);\n}\n\nboost::math::tuple<mp_t, mp_t, mp_t, mp_t> generate_rg_xyx(mp_t x, mp_t y)\n{\n   mp_t result = rg_imp(x, y, x);\n   return boost::math::make_tuple(x, y, x, result);\n}\n\nboost::math::tuple<mp_t, mp_t, mp_t, mp_t> generate_rg_0xx(mp_t x)\n{\n   mp_t result = rg_imp(mp_t(0), x, x);\n   return boost::math::make_tuple(mp_t(0), x, x, result);\n}\n\nboost::math::tuple<mp_t, mp_t, mp_t, mp_t> generate_rg_x0x(mp_t x)\n{\n   mp_t result = rg_imp(x, mp_t(0), x);\n   return boost::math::make_tuple(x, mp_t(0), x, result);\n}\n\nboost::math::tuple<mp_t, mp_t, mp_t, mp_t> generate_rg_xx0(mp_t x)\n{\n   mp_t result = rg_imp(x, x, mp_t(0));\n   return boost::math::make_tuple(x, x, mp_t(0), result);\n}\n\nboost::math::tuple<mp_t, mp_t, mp_t, mp_t> generate_rg_00x(mp_t x)\n{\n   mp_t result = sqrt(x) / 2;\n   return boost::math::make_tuple(mp_t(0), mp_t(0), x, result);\n}\n\nboost::math::tuple<mp_t, mp_t, mp_t, mp_t> generate_rg_0x0(mp_t x)\n{\n   mp_t result = sqrt(x) / 2;\n   return boost::math::make_tuple(mp_t(0), x, mp_t(0), result);\n}\n\nboost::math::tuple<mp_t, mp_t, mp_t, mp_t> generate_rg_x00(mp_t x)\n{\n   mp_t result = sqrt(x) / 2;\n   return boost::math::make_tuple(x, mp_t(0), mp_t(0), result);\n}\n\nboost::math::tuple<mp_t, mp_t, mp_t, mp_t> generate_rg_xy0(mp_t x, mp_t y)\n{\n   mp_t result = rg_imp(x, y, mp_t(0));\n   return boost::math::make_tuple(x, y, mp_t(0), result);\n}\n\nint cpp_main(int argc, char*argv[])\n{\n   using namespace boost::math::tools;\n\n   parameter_info<mp_t> arg1, arg2, arg3;\n   test_data<mp_t> data;\n\n   bool cont;\n   std::string line;\n\n   if(argc < 1)\n      return 1;\n\n   do{\n#if 0\n      int count;\n      std::cout << \"Number of points: \";\n      std::cin >> count;\n      \n      arg1 = make_periodic_param(mp_t(0), mp_t(1), count);\n      arg1.type |= dummy_param;\n\n      //\n      // Change this next line to get the R variant you want:\n      //\n      data.insert(&generate_rd_data, arg1);\n\n      std::cout << \"Any more data [y/n]?\";\n      std::getline(std::cin, line);\n      boost::algorithm::trim(line);\n      cont = (line == \"y\");\n#else\n      get_user_parameter_info(arg1, \"x\");\n      get_user_parameter_info(arg2, \"y\");\n      //get_user_parameter_info(arg3, \"p\");\n      arg1.type |= dummy_param;\n      arg2.type |= dummy_param;\n      //arg3.type |= dummy_param;\n      data.insert(generate_rd_data_0xy, arg1, arg2);\n\n      std::cout << \"Any more data [y/n]?\";\n      std::getline(std::cin, line);\n      boost::algorithm::trim(line);\n      cont = (line == \"y\");\n#endif\n   }while(cont);\n\n   std::cout << \"Enter name of test data file [default=ellint_rf_data.ipp]\";\n   std::getline(std::cin, line);\n   boost::algorithm::trim(line);\n   if(line == \"\")\n      line = \"ellint_rf_data.ipp\";\n   std::ofstream ofs(line.c_str());\n   line.erase(line.find('.'));\n   ofs << std::scientific << std::setprecision(40);\n   write_code(ofs, data, line.c_str());\n\n   return 0;\n}\n\n\n", "meta": {"hexsha": "66dc6d005a2f4438577faef405afd4151b5e4f23", "size": 18535, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/boost_1.75.0/libs/math/tools/carlson_ellint_data.cpp", "max_stars_repo_name": "detcitty/math", "max_stars_repo_head_hexsha": "fe99d5f31171edb24bc841a9fa2f082982771d35", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-04-28T15:15:28.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-28T15:15:28.000Z", "max_issues_repo_path": "lib/boost_1.75.0/libs/math/tools/carlson_ellint_data.cpp", "max_issues_repo_name": "detcitty/math", "max_issues_repo_head_hexsha": "fe99d5f31171edb24bc841a9fa2f082982771d35", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-05-23T08:01:11.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-06T20:49:05.000Z", "max_forks_repo_path": "lib/boost_1.75.0/libs/math/tools/carlson_ellint_data.cpp", "max_forks_repo_name": "detcitty/math", "max_forks_repo_head_hexsha": "fe99d5f31171edb24bc841a9fa2f082982771d35", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-11-03T14:12:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-22T19:20:54.000Z", "avg_line_length": 29.3740095087, "max_line_length": 107, "alphanum_fraction": 0.584461829, "num_tokens": 6384, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.48172692921217264}}
{"text": "#include \"glutil.h\"\n#include <boost/filesystem.hpp>\n#include <cmath>\n\nnamespace glow {\n\nEigen::Matrix4f glTranslate(float x, float y, float z) {\n  Eigen::Matrix4f m;\n  m << 1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1;\n  return m;\n}\n\nEigen::Matrix4f glScale(float x, float y, float z) {\n  Eigen::Matrix4f m;\n  m << x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1;\n  return m;\n}\n\nEigen::Matrix4f glRotateX(float angle) {\n  float sin_t = std::sin(angle);\n  float cos_t = std::cos(angle);\n\n  Eigen::Matrix4f m;\n  m << 1, 0, 0, 0, 0, cos_t, -sin_t, 0, 0, sin_t, cos_t, 0, 0, 0, 0, 1;\n\n  return m;\n}\n\nEigen::Matrix4f glRotateY(float angle) {\n  float sin_t = std::sin(angle);\n  float cos_t = std::cos(angle);\n  Eigen::Matrix4f m;\n  m << cos_t, 0, sin_t, 0, 0, 1, 0, 0, -sin_t, 0, cos_t, 0, 0, 0, 0, 1;\n\n  return m;\n}\n\nEigen::Matrix4f glRotateZ(float angle) {\n  float sin_t = std::sin(angle);\n  float cos_t = std::cos(angle);\n  Eigen::Matrix4f m;\n  m << cos_t, -sin_t, 0, 0, sin_t, cos_t, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1;\n  return m;\n}\n\nEigen::Matrix4f glRotateAxis(float angle, float x, float y, float z) {\n  Eigen::Matrix4f m;\n\n  float s = std::sin(angle);\n  float c = std::cos(angle);\n\n  m(0, 0) = x * x * (1 - c) + c;\n  m(0, 1) = x * y * (1.0f - c) - z * s;\n  m(0, 2) = x * z * (1.0f - c) + y * s;\n  m(0, 3) = 0.0f;\n\n  m(1, 0) = x * y * (1.0f - c) + z * s;\n  m(1, 1) = c + (1.0f - c) * y * y;\n  m(1, 2) = y * z * (1.0f - c) - x * s;\n  m(1, 3) = 0.0f;\n\n  m(2, 0) = x * z * (1.0f - c) - y * s;\n  m(2, 1) = y * z * (1.0f - c) + x * s;\n  m(2, 2) = z * z + (1.0f - z * z) * c;\n  m(2, 3) = 0.0f;\n\n  m(3, 0) = 0.0f;\n  m(3, 1) = 0.0f;\n  m(3, 2) = 0.0f;\n  m(3, 3) = 1.0f;\n\n  return m;\n}\n\nEigen::Matrix4f glPerspective(float fov, float aspect, float znear, float zfar) {\n  // https://www.opengl.org/sdk/docs/man2/xhtml/gluPerspective.xml\n  assert(znear > 0.0f);\n  Eigen::Matrix4f M = Eigen::Matrix4f::Zero();\n\n  // Copied from gluPerspective\n  float f = 1.0f / std::tan(0.5f * fov);\n\n  M(0, 0) = f / aspect;\n  M(1, 1) = f;\n  M(2, 2) = (znear + zfar) / (znear - zfar);\n  M(2, 3) = (2.0f * zfar * znear) / (znear - zfar);\n  M(3, 2) = -1.0f;\n\n  return M;\n}\n\nEigen::Matrix4f glOrthographic(float left, float right, float bottom, float top, float znear, float zfar) {\n\n  // copied from https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/glOrtho.xml\n\n  Eigen::Matrix4f M = Eigen::Matrix4f::Zero();\n\n  M(0, 0) = 2.0f / (right - left);\n  M(1, 1) = 2.0f / (top - bottom);\n  M(2, 2) = -2.0f / (zfar - znear);\n\n  M(0, 3) = -(right + left) / (right - left);\n  M(1, 3) = -(top + bottom) / (top - bottom);\n  M(2, 3) = -(zfar + znear) / (zfar - znear);\n  M(3, 3) = 1.0f;\n\n  return M;\n}\n\n// clang-format off\nEigen::Matrix4f initializeMatrix(float t00, float t01, float t02, float t03,\n                                 float t10, float t11, float t12, float t13,\n                                 float t20, float t21, float t22, float t23,\n                                 float t30, float t31, float t32, float t33) {\n  Eigen::Matrix4f m;\n  m << t00, t01, t02, t03, t10, t11, t12, t13, t20, t21, t22, t23, t30, t31, t32, t33;\n  return m;\n}\n\nEigen::Matrix4f RoSe2GL::matrix = initializeMatrix(0, -1, 0, 0,\n                                                   0,  0, 1, 0,\n                                                  -1,  0, 0, 0,\n                                                   0,  0, 0, 1);\n\n\nEigen::Matrix4f GL2RoSe::matrix = initializeMatrix(0, 0, -1, 0,\n                                                  -1, 0,  0, 0,\n                                                   0, 1,  0, 0,\n                                                   0, 0,  0, 1);\n// clang-format on\n\nfloat rgb2float(float r, float g, float b) {\n  int32_t rgb = int32_t(round(r * 255.0f));\n  rgb = (rgb << 8) + int32_t(round(g * 255.0f));\n  rgb = (rgb << 8) + int32_t(round(b * 255.0f));\n\n  return float(rgb);\n}\n\nstd::string extension(const std::string& path, int32_t level) {\n  std::string filename = boost::filesystem::path(path).filename().string();\n  if (filename == \"\" || filename == \".\" || filename == \"..\") return \"\";\n\n  std::string ext;\n  while (level-- > 0) {\n    std::string::size_type idx = filename.rfind(\".\");\n    if (idx == std::string::npos) break;\n    ext.insert(0, filename.substr(idx));\n    filename.resize(idx);\n  }\n\n  return ext;\n}\n}\n\nstd::ostream& operator<<(std::ostream& stream, glow::vec2& vec) {\n  stream << \"(\" << vec.x << \", \" << vec.y << \")\";\n\n  return stream;\n}\n\nstd::ostream& operator<<(std::ostream& stream, glow::vec3& vec) {\n  stream << \"(\" << vec.x << \", \" << vec.y << \", \" << vec.z << \")\";\n\n  return stream;\n}\n\nstd::ostream& operator<<(std::ostream& stream, glow::vec4& vec) {\n  stream << \"(\" << vec.x << \", \" << vec.y << \", \" << vec.z << \", \" << vec.w << \")\";\n\n  return stream;\n}\n\nstd::ostream& operator<<(std::ostream& stream, const glow::vec2& vec) {\n  stream << \"(\" << vec.x << \", \" << vec.y << \")\";\n\n  return stream;\n}\n\nstd::ostream& operator<<(std::ostream& stream, const glow::vec3& vec) {\n  stream << \"(\" << vec.x << \", \" << vec.y << \", \" << vec.z << \")\";\n\n  return stream;\n}\n\nstd::ostream& operator<<(std::ostream& stream, const glow::vec4& vec) {\n  stream << \"(\" << vec.x << \", \" << vec.y << \", \" << vec.z << \", \" << vec.w << \")\";\n\n  return stream;\n}\n", "meta": {"hexsha": "6ddc1cad1c571a1be7fbad5803bd37fdce607ce2", "size": 5251, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/glow/glutil.cpp", "max_stars_repo_name": "cagcoach/glow", "max_stars_repo_head_hexsha": "97336cd5e229aa57bcd413e66bc529f6f1f1f69b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T15:41:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T19:01:08.000Z", "max_issues_repo_path": "src/glow/glutil.cpp", "max_issues_repo_name": "cagcoach/glow", "max_issues_repo_head_hexsha": "97336cd5e229aa57bcd413e66bc529f6f1f1f69b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2018-03-13T08:34:33.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-14T20:39:01.000Z", "max_forks_repo_path": "src/glow/glutil.cpp", "max_forks_repo_name": "cagcoach/glow", "max_forks_repo_head_hexsha": "97336cd5e229aa57bcd413e66bc529f6f1f1f69b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2018-03-12T13:29:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-04T09:04:26.000Z", "avg_line_length": 27.4921465969, "max_line_length": 107, "alphanum_fraction": 0.5058084174, "num_tokens": 2034, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311856832191, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4817269231230067}}
{"text": "#include <geometry.h>\n#include <tiny.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n\ntypedef tiny::MathTypes<float> MT;\ntypedef MT::quaternion_type    Q;\ntypedef MT::vector3_type       V;\ntypedef MT::real_type          T;\ntypedef MT::value_traits       VT;\n\n\nBOOST_AUTO_TEST_SUITE(geometry);\n\nBOOST_AUTO_TEST_CASE(overlap_obb_capsule_test)\n{\n  // Separated on plus x-axis of OBB\n  {\n    V const center   = V::make(0.0, 0.0, 0.0);\n    V const half_ext = V::make(1.0, 1.0, 1.0);\n    Q const q        = Q::identity();\n\n    V const point0   = V::make(2.1,  0.0, 0.0);\n    V const point1   = V::make(3.1,  2.1, 2.1);\n    T const radius   = 1.0;\n\n    geometry::OBB<MT>    const & obb = geometry::make_obb<MT>(center, q, half_ext);\n    geometry::Capsule<V> const & cap = geometry::make_capsule(radius, point0, point1);\n\n    bool const test = geometry::overlap_obb_capsule(obb, cap);\n\n    BOOST_CHECK(!test);\n  }\n  // Overlap from plus x-side of OBB\n  {\n    V const center   = V::make(0.0, 0.0, 0.0);\n    V const half_ext = V::make(1.0, 1.0, 1.0);\n    Q const q        = Q::identity();\n\n    V const point0   = V::make(1.9,  0.0, 0.0);\n    V const point1   = V::make(3.1,  2.1, 2.1);\n    T const radius   = 1.0;\n\n    geometry::OBB<MT>    const & obb = geometry::make_obb<MT>(center, q, half_ext);\n    geometry::Capsule<V> const & cap = geometry::make_capsule(radius, point0, point1);\n\n    bool const test = geometry::overlap_obb_capsule(obb, cap);\n\n    BOOST_CHECK(test);\n  }\n  // Separated on negative x-axis of OBB\n  {\n    V const center   = V::make(0.0, 0.0, 0.0);\n    V const half_ext = V::make(1.0, 1.0, 1.0);\n    Q const q        = Q::identity();\n\n    V const point0   = V::make(-2.1,  0.0, 0.0);\n    V const point1   = V::make(-3.1,  2.1, 2.1);\n    T const radius   = 1.0;\n\n    geometry::OBB<MT>    const & obb = geometry::make_obb<MT>(center, q, half_ext);\n    geometry::Capsule<V> const & cap = geometry::make_capsule(radius, point0, point1);\n\n    bool const test = geometry::overlap_obb_capsule(obb, cap);\n\n    BOOST_CHECK(!test);\n  }\n  // Overlap from negative x-side of OBB\n  {\n    V const center   = V::make(0.0, 0.0, 0.0);\n    V const half_ext = V::make(1.0, 1.0, 1.0);\n    Q const q        = Q::identity();\n\n    V const point0   = V::make(-1.9,  0.0, 0.0);\n    V const point1   = V::make(-3.1,  2.1, 2.1);\n    T const radius   = 1.0;\n\n    geometry::OBB<MT>    const & obb = geometry::make_obb<MT>(center, q, half_ext);\n    geometry::Capsule<V> const & cap = geometry::make_capsule(radius, point0, point1);\n\n    bool const test = geometry::overlap_obb_capsule(obb, cap);\n    \n    BOOST_CHECK(test);\n  }\n  // Separated on plus y-axis of OBB\n  {\n    V const center   = V::make(0.0, 0.0, 0.0);\n    V const half_ext = V::make(1.0, 1.0, 1.0);\n    Q const q        = Q::identity();\n\n    V const point0   = V::make(0.0, 2.1,  0.0);\n    V const point1   = V::make(2.1, 3.1,  2.1);\n    T const radius   = 1.0;\n\n    geometry::OBB<MT>    const & obb = geometry::make_obb<MT>(center, q, half_ext);\n    geometry::Capsule<V> const & cap = geometry::make_capsule(radius, point0, point1);\n\n    bool const test = geometry::overlap_obb_capsule(obb, cap);\n\n    BOOST_CHECK(!test);\n  }\n  // Overlap from plus y-side of OBB\n  {\n    V const center   = V::make(0.0, 0.0, 0.0);\n    V const half_ext = V::make(1.0, 1.0, 1.0);\n    Q const q        = Q::identity();\n\n    V const point0   = V::make(0.0,  1.9, 0.0);\n    V const point1   = V::make(2.1,  3.1, 2.1);\n    T const radius   = 1.0;\n\n    geometry::OBB<MT>    const & obb = geometry::make_obb<MT>(center, q, half_ext);\n    geometry::Capsule<V> const & cap = geometry::make_capsule(radius, point0, point1);\n\n    bool const test = geometry::overlap_obb_capsule(obb, cap);\n\n    BOOST_CHECK(test);\n  }\n  // Separated on negative y-axis of OBB\n  {\n    V const center   = V::make(0.0, 0.0, 0.0);\n    V const half_ext = V::make(1.0, 1.0, 1.0);\n    Q const q        = Q::identity();\n\n    V const point0   = V::make(0.0,  -2.1, 0.0);\n    V const point1   = V::make(2.1,  -3.1, 2.1);\n    T const radius   = 1.0;\n\n    geometry::OBB<MT>    const & obb = geometry::make_obb<MT>(center, q, half_ext);\n    geometry::Capsule<V> const & cap = geometry::make_capsule(radius, point0, point1);\n\n    bool const test = geometry::overlap_obb_capsule(obb, cap);\n\n    BOOST_CHECK(!test);\n  }\n  // Overlap from negative y-side of OBB\n  {\n    V const center   = V::make(0.0, 0.0, 0.0);\n    V const half_ext = V::make(1.0, 1.0, 1.0);\n    Q const q        = Q::identity();\n\n    V const point0   = V::make(0.0, -1.9, 0.0);\n    V const point1   = V::make(2.1, -3.1, 2.1);\n    T const radius   = 1.0;\n\n    geometry::OBB<MT>    const & obb = geometry::make_obb<MT>(center, q, half_ext);\n    geometry::Capsule<V> const & cap = geometry::make_capsule(radius, point0, point1);\n\n    bool const test = geometry::overlap_obb_capsule(obb, cap);\n    \n    BOOST_CHECK(test);\n  }\n  // Separated on plus z-axis of OBB\n  {\n    V const center   = V::make(0.0, 0.0, 0.0);\n    V const half_ext = V::make(1.0, 1.0, 1.0);\n    Q const q        = Q::identity();\n\n    V const point0   = V::make(0.0, 0.0, 2.1);\n    V const point1   = V::make(2.1, 2.1, 3.1);\n    T const radius   = 1.0;\n\n    geometry::OBB<MT>    const & obb = geometry::make_obb<MT>(center, q, half_ext);\n    geometry::Capsule<V> const & cap = geometry::make_capsule(radius, point0, point1);\n\n    bool const test = geometry::overlap_obb_capsule(obb, cap);\n\n    BOOST_CHECK(!test);\n  }\n  // Overlap from plus z-side of OBB\n  {\n    V const center   = V::make(0.0, 0.0, 0.0);\n    V const half_ext = V::make(1.0, 1.0, 1.0);\n    Q const q        = Q::identity();\n\n    V const point0   = V::make(0.0, 0.0,  1.9);\n    V const point1   = V::make(2.1, 2.1,  3.1);\n    T const radius   = 1.0;\n\n    geometry::OBB<MT>    const & obb = geometry::make_obb<MT>(center, q, half_ext);\n    geometry::Capsule<V> const & cap = geometry::make_capsule(radius, point0, point1);\n\n    bool const test = geometry::overlap_obb_capsule(obb, cap);\n\n    BOOST_CHECK(test);\n  }\n  // Separated on negative z-axis of OBB\n  {\n    V const center   = V::make(0.0, 0.0, 0.0);\n    V const half_ext = V::make(1.0, 1.0, 1.0);\n    Q const q        = Q::identity();\n\n    V const point0   = V::make(0.0, 0.0,  -2.1);\n    V const point1   = V::make(2.1, 2.1,  -3.1);\n    T const radius   = 1.0;\n\n    geometry::OBB<MT>    const & obb = geometry::make_obb<MT>(center, q, half_ext);\n    geometry::Capsule<V> const & cap = geometry::make_capsule(radius, point0, point1);\n\n    bool const test = geometry::overlap_obb_capsule(obb, cap);\n\n    BOOST_CHECK(!test);\n  }\n  // Overlap from negative z-side of OBB\n  {\n    V const center   = V::make(0.0, 0.0, 0.0);\n    V const half_ext = V::make(1.0, 1.0, 1.0);\n    Q const q        = Q::identity();\n\n    V const point0   = V::make(0.0, 0.0, -1.9);\n    V const point1   = V::make(2.1, 2.1, -3.1);\n    T const radius   = 1.0;\n\n    geometry::OBB<MT>    const & obb = geometry::make_obb<MT>(center, q, half_ext);\n    geometry::Capsule<V> const & cap = geometry::make_capsule(radius, point0, point1);\n\n    bool const test = geometry::overlap_obb_capsule(obb, cap);\n    \n    BOOST_CHECK(test);\n  }\n  // Separated by z-OBB X capsule axis\n  {\n    V const center   = V::make(0.0, 0.0, 0.0);\n    V const half_ext = V::make(1.0, 1.0, 1.0);\n    Q const q        = Q::identity();\n\n    V const point0   = V::make( 0.0,  -3.0, 0.0);\n    V const point1   = V::make( 3.0,   0.0, 0.0);\n    T const radius   = 0.5;\n\n    geometry::OBB<MT>    const & obb = geometry::make_obb<MT>(center, q, half_ext);\n    geometry::Capsule<V> const & cap = geometry::make_capsule(radius, point0, point1);\n\n    bool const test = geometry::overlap_obb_capsule(obb, cap);\n\n    BOOST_CHECK(!test);\n  }\n  // Overlap by z-OBB X capsule axis\n  {\n    V const center   = V::make(0.0, 0.0, 0.0);\n    V const half_ext = V::make(1.0, 1.0, 1.0);\n    Q const q        = Q::identity();\n\n    V const point0   = V::make( 0.0,  -3.0, 0.0);\n    V const point1   = V::make( 3.0,   0.0, 0.0);\n    T const radius   = 1.0;\n\n    geometry::OBB<MT>    const & obb = geometry::make_obb<MT>(center, q, half_ext);\n    geometry::Capsule<V> const & cap = geometry::make_capsule(radius, point0, point1);\n\n    bool const test = geometry::overlap_obb_capsule(obb, cap);\n\n    BOOST_CHECK(test);\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "ba2a8c497f123d0cc90c4482f344c3c39df0af91", "size": 8459, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/FOUNDATION/GEOMETRY/unit_tests/geometry_overlap_obb_capsule/geometry_overlap_obb_capsule.cpp", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-11-27T09:44:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-13T00:24:21.000Z", "max_issues_repo_path": "PROX/FOUNDATION/GEOMETRY/unit_tests/geometry_overlap_obb_capsule/geometry_overlap_obb_capsule.cpp", "max_issues_repo_name": "erleben/matchstick", "max_issues_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_issues_repo_licenses": ["MIT"], "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/FOUNDATION/GEOMETRY/unit_tests/geometry_overlap_obb_capsule/geometry_overlap_obb_capsule.cpp", "max_forks_repo_name": "erleben/matchstick", "max_forks_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_forks_repo_licenses": ["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.286259542, "max_line_length": 86, "alphanum_fraction": 0.5908499823, "num_tokens": 3097, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.787931185683219, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4817269231230066}}
{"text": "/*\n@copyright Louis Dionne 2015\nDistributed under the Boost Software License, Version 1.0.\n(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n */\n\n#include <boost/hana/ext/std/integral_constant.hpp>\n\n#include <boost/hana/tuple.hpp>\n\n#include <laws/enumerable.hpp>\n#include <laws/group.hpp>\n#include <laws/integral_domain.hpp>\n#include <laws/monoid.hpp>\n#include <laws/ring.hpp>\n\n#include <type_traits>\nusing namespace boost::hana;\n\n\nint main() {\n    auto ints = make<Tuple>(\n        std::integral_constant<int, -10>{},\n        std::integral_constant<int, -2>{},\n        std::integral_constant<int, 0>{},\n        std::integral_constant<int, 1>{},\n        std::integral_constant<int, 3>{}\n    );\n\n    //////////////////////////////////////////////////////////////////////////\n    // Enumerable, Monoid, Group, Ring, IntegralDomain\n    //////////////////////////////////////////////////////////////////////////\n    {\n        // laws\n        test::TestEnumerable<ext::std::IntegralConstant<int>>{ints};\n        test::TestMonoid<ext::std::IntegralConstant<int>>{ints};\n        test::TestGroup<ext::std::IntegralConstant<int>>{ints};\n        test::TestRing<ext::std::IntegralConstant<int>>{ints};\n        test::TestIntegralDomain<ext::std::IntegralConstant<int>>{ints};\n    }\n}\n", "meta": {"hexsha": "66b471be1ff045cff0088e4fb4458317e1cf0008", "size": 1300, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/ext/std/integral_constant/integral_domain.cpp", "max_stars_repo_name": "josephwinston/hana", "max_stars_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/ext/std/integral_constant/integral_domain.cpp", "max_issues_repo_name": "josephwinston/hana", "max_issues_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/ext/std/integral_constant/integral_domain.cpp", "max_forks_repo_name": "josephwinston/hana", "max_forks_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.9523809524, "max_line_length": 78, "alphanum_fraction": 0.5869230769, "num_tokens": 298, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311856832191, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.4817269231230066}}
{"text": "//===----------------------------------------------------------------------===//\r\n//\r\n//                     The LLVM Compiler Infrastructure\r\n//\r\n// This file is dual licensed under the MIT and the University of Illinois Open\r\n// Source Licenses. See LICENSE.TXT for details.\r\n//\r\n//===----------------------------------------------------------------------===//\r\n//  Adaptation to Boost of the libcxx\r\n//  Copyright 2010 Vicente J. Botet Escriba\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// test ratio_power\r\n\r\n#define BOOST_RATIO_EXTENSIONS\r\n#include <boost/ratio/ratio.hpp>\r\n\r\n#if !defined(BOOST_NO_CXX11_STATIC_ASSERT)\r\n#define NOTHING \"\"\r\n#endif\r\n\r\nvoid test()\r\n{\r\n  {\r\n    typedef boost::ratio<1, 2> R1;\r\n    typedef boost::ratio_power<R1, 1> R;\r\n    BOOST_RATIO_STATIC_ASSERT(R::num == 1 && R::den == 2, NOTHING, ());\r\n  }\r\n  {\r\n    typedef boost::ratio<1, 2> R1;\r\n    typedef boost::ratio_power<R1, -1> R;\r\n    BOOST_RATIO_STATIC_ASSERT(R::num == 2 && R::den == 1, NOTHING, ());\r\n  }\r\n  {\r\n    typedef boost::ratio<1, 2> R1;\r\n    typedef boost::ratio_power<R1, 0> R;\r\n    BOOST_RATIO_STATIC_ASSERT(R::num == 1 && R::den == 1, NOTHING, ());\r\n  }\r\n  {\r\n    typedef boost::ratio<-1, 2> R1;\r\n    typedef boost::ratio_power<R1, 2> R;\r\n    BOOST_RATIO_STATIC_ASSERT(R::num == 1 && R::den == 4, NOTHING, ());\r\n  }\r\n  {\r\n    typedef boost::ratio<1, -2> R1;\r\n    typedef boost::ratio_power<R1, 2> R;\r\n    BOOST_RATIO_STATIC_ASSERT(R::num == 1 && R::den == 4, NOTHING, ());\r\n  }\r\n  {\r\n    typedef boost::ratio<2, 3> R1;\r\n    typedef boost::ratio_power<R1, 2> R;\r\n    BOOST_RATIO_STATIC_ASSERT(R::num == 4 && R::den == 9, NOTHING, ());\r\n  }\r\n  {\r\n    typedef boost::ratio<2, 3> R1;\r\n    typedef boost::ratio_power<R1, -2> R;\r\n    BOOST_RATIO_STATIC_ASSERT(R::num == 9 && R::den == 4, NOTHING, ());\r\n  }\r\n}\r\n", "meta": {"hexsha": "9791364fdff20f7ce5b40ddcb0fc5ce61e894921", "size": 1875, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/ratio/test/ratio_arithmetic/ratio_power_pass.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": 85.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T20:36:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T20:38:31.000Z", "max_issues_repo_path": "libs/boost/libs/ratio/test/ratio_arithmetic/ratio_power_pass.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/ratio/test/ratio_arithmetic/ratio_power_pass.cpp", "max_forks_repo_name": "flingone/frameworks_base_cmds_remoted", "max_forks_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2015-01-28T16:33:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-12T05:04:39.000Z", "avg_line_length": 30.737704918, "max_line_length": 81, "alphanum_fraction": 0.5498666667, "num_tokens": 528, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850933, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.4815506929746236}}
{"text": "/**TODO:  Add copyright*/\n\n#define BOOST_TEST_MODULE ModelInterpreter IG test suite \n#include <boost/test/included/unit_test.hpp>\n#include <EvoNet/ml/ModelInterpreterDefaultDevice.h> \n\nusing namespace EvoNet;\nusing namespace std;\n\nModel<float> makeModelIG()\n{\n\t/**\n\t * Interaction Graph Toy Network Model\n\t * Harmonic Oscillator without damping:\n\t * F(t) - kx = mx``\n\t * for F(t) = 0\n\t * x(t) = A*cos(w*t + e)\n\t * where undamped angular momentum, w = sqrt(k/m)\n\t * with amplitude A, and phase e\n\t * \n\t * Harmonic Oscillator with damping:\n\t * F(t) - kx - cx` = mx``\n\t * For F(t) = 0, x`` + 2*l*w*x` + x*w^2 = 0\n\t * where damping ratio, l = c/(2*sqrt(m*k)) and undamped angular momentum, w = sqrt(k/m)\n\t * x(t) = Ae^(-l*w*t)*sin(sqrt(1-l^2)*w*t + e)\n\t * with amplitude A, and phase e\n\t*/\n\tNode<float> m1, m2, m3;\n\tLink l1_to_l2, l2_to_l1, l2_to_l3, l3_to_l2;\n\tWeight<float> w1_to_w2, w2_to_w1, w2_to_w3, w3_to_w2;\n\tModel<float> model3;\n\t// Toy network: 1 hidden layer, fully connected, DCG\n\tm1 = Node<float>(\"m1\", NodeType::input, NodeStatus::activated, std::make_shared<LinearOp<float>>(LinearOp<float>()), std::make_shared<LinearGradOp<float>>(LinearGradOp<float>()), std::make_shared<SumOp<float>>(SumOp<float>()), std::make_shared<SumErrorOp<float>>(SumErrorOp<float>()), std::make_shared<SumWeightGradOp<float>>(SumWeightGradOp<float>()));\n\tm2 = Node<float>(\"m2\", NodeType::hidden, NodeStatus::initialized, std::make_shared<LinearOp<float>>(LinearOp<float>()), std::make_shared<LinearGradOp<float>>(LinearGradOp<float>()), std::make_shared<SumOp<float>>(SumOp<float>()), std::make_shared<SumErrorOp<float>>(SumErrorOp<float>()), std::make_shared<SumWeightGradOp<float>>(SumWeightGradOp<float>()));\n\tm3 = Node<float>(\"m3\", NodeType::output, NodeStatus::initialized, std::make_shared<LinearOp<float>>(LinearOp<float>()), std::make_shared<LinearGradOp<float>>(LinearGradOp<float>()), std::make_shared<SumOp<float>>(SumOp<float>()), std::make_shared<SumErrorOp<float>>(SumErrorOp<float>()), std::make_shared<SumWeightGradOp<float>>(SumWeightGradOp<float>()));\n\t// weights  \n\tstd::shared_ptr<WeightInitOp<float>> weight_init;\n\tstd::shared_ptr<SolverOp<float>> solver;\n\t// weight_init.reset(new RandWeightInitOp(1.0)); // No random init for testing\n\tweight_init = std::make_shared<ConstWeightInitOp<float>>(ConstWeightInitOp<float>(1.0));\n\tsolver = std::make_shared<SGDOp<float>>(SGDOp<float>(0.01, 0.9));\n\tw1_to_w2 = Weight<float>(\"m1_to_m2\", weight_init, solver);\n\tweight_init = std::make_shared<ConstWeightInitOp<float>>(ConstWeightInitOp<float>(1.0));\n\tsolver = std::make_shared<SGDOp<float>>(SGDOp<float>(0.01, 0.9));\n\tw2_to_w1 = Weight<float>(\"m2_to_m1\", weight_init, solver);\n\tweight_init = std::make_shared<ConstWeightInitOp<float>>(ConstWeightInitOp<float>(1.0));\n\tsolver = std::make_shared<SGDOp<float>>(SGDOp<float>(0.01, 0.9));\n\tw2_to_w3 = Weight<float>(\"m2_to_m3\", weight_init, solver);\n\tweight_init = std::make_shared<ConstWeightInitOp<float>>(ConstWeightInitOp<float>(1.0));\n\tsolver = std::make_shared<SGDOp<float>>(SGDOp<float>(0.01, 0.9));\n\tw3_to_w2 = Weight<float>(\"m3_to_m2\", weight_init, solver);\n\tweight_init.reset();\n\tsolver.reset();\n\t// links\n\tl1_to_l2 = Link(\"l1_to_l2\", \"m1\", \"m2\", \"m1_to_m2\");\n\tl2_to_l1 = Link(\"l2_to_l1\", \"m2\", \"m1\", \"m2_to_m1\");\n\tl2_to_l3 = Link(\"l2_to_l3\", \"m2\", \"m3\", \"m2_to_m3\");\n\tl3_to_l2 = Link(\"l3_to_l2\", \"m3\", \"m2\", \"m3_to_m2\");\n\tmodel3.setId(3);\n\tmodel3.addNodes({ m1, m2, m3 });\n\tmodel3.addWeights({ w1_to_w2, w2_to_w1, w2_to_w3, w3_to_w2 });\n\tmodel3.addLinks({ l1_to_l2, l2_to_l1, l2_to_l3, l3_to_l2 });\n\treturn model3;\n}\n\nBOOST_AUTO_TEST_SUITE(modelInterpreter_IG)\n\n/**\n * Part 2 test suit for the ModelInterpreter class\n * \n * The following test methods that are\n * required of an interaction graph neural network\n*/\n\nModel<float> model_getFPOpsGraph = makeModelIG();\nBOOST_AUTO_TEST_CASE(getFPOpsGraph_) \n{\n  // Toy network: 1 hidden layer, fully connected, DAG\n\tModelInterpreterDefaultDevice<float> model_interpreter;\n\n\t// get the next hidden layer\n\tint iter;\n\tstd::vector<OperationList<float>> FP_operations_list;\n\tmodel_interpreter.getFPOpsGraph_(model_getFPOpsGraph, FP_operations_list, iter);\n\n\tBOOST_CHECK_EQUAL(iter, 1);\n\tBOOST_CHECK_EQUAL(FP_operations_list.size(), 4);\n\n\tBOOST_CHECK_EQUAL(FP_operations_list[0].result.time_step, 0);\n\tBOOST_CHECK_EQUAL(FP_operations_list[0].result.sink_node->getName(), \"m2\");\n\tBOOST_CHECK_EQUAL(FP_operations_list[0].arguments.size(), 1);\n\tBOOST_CHECK_EQUAL(FP_operations_list[0].arguments[0].time_step, 1);\n\tBOOST_CHECK_EQUAL(FP_operations_list[0].arguments[0].source_node->getName(), \"m1\");\n\tBOOST_CHECK_EQUAL(FP_operations_list[0].arguments[0].weight->getName(), \"m1_to_m2\");\n\n\tBOOST_CHECK_EQUAL(FP_operations_list[1].result.time_step, 0);\n\tBOOST_CHECK_EQUAL(FP_operations_list[1].result.sink_node->getName(), \"m1\");\n\tBOOST_CHECK_EQUAL(FP_operations_list[1].arguments.size(), 1);\n\tBOOST_CHECK_EQUAL(FP_operations_list[1].arguments[0].time_step, 1);\n\tBOOST_CHECK_EQUAL(FP_operations_list[1].arguments[0].source_node->getName(), \"m2\");\n\tBOOST_CHECK_EQUAL(FP_operations_list[1].arguments[0].weight->getName(), \"m2_to_m1\");\n\n\tBOOST_CHECK_EQUAL(FP_operations_list[2].result.time_step, 0);\n\tBOOST_CHECK_EQUAL(FP_operations_list[2].result.sink_node->getName(), \"m3\");\n\tBOOST_CHECK_EQUAL(FP_operations_list[2].arguments.size(), 1);\n\tBOOST_CHECK_EQUAL(FP_operations_list[2].arguments[0].time_step, 1);\n\tBOOST_CHECK_EQUAL(FP_operations_list[2].arguments[0].source_node->getName(), \"m2\");\n\tBOOST_CHECK_EQUAL(FP_operations_list[2].arguments[0].weight->getName(), \"m2_to_m3\");\n\n\tBOOST_CHECK_EQUAL(FP_operations_list[3].result.time_step, 0);\n\tBOOST_CHECK_EQUAL(FP_operations_list[3].result.sink_node->getName(), \"m2\");\n\tBOOST_CHECK_EQUAL(FP_operations_list[3].arguments.size(), 1);\n\tBOOST_CHECK_EQUAL(FP_operations_list[3].arguments[0].time_step, 1);\n\tBOOST_CHECK_EQUAL(FP_operations_list[3].arguments[0].source_node->getName(), \"m3\");\n\tBOOST_CHECK_EQUAL(FP_operations_list[3].arguments[0].weight->getName(), \"m3_to_m2\");\n}\n\nModel<float> model_getTensorOperations = makeModelIG();\nBOOST_AUTO_TEST_CASE(getTensorOperations)\n{\n\tModelInterpreterDefaultDevice<float> model_interpreter;\n\n\tint iter;\n\tstd::vector<OperationList<float>> FP_operations_list;\n\tmodel_interpreter.getFPOpsGraph_(model_getTensorOperations, FP_operations_list, iter);\n\n\tstd::set<std::string> identified_sink_nodes;\n\tstd::map<std::string, std::vector<int>> tensor_ops = model_interpreter.getTensorOperations(FP_operations_list, identified_sink_nodes, false);\n\n\tBOOST_CHECK_EQUAL(identified_sink_nodes.size(), 4);\n\tBOOST_CHECK_EQUAL(identified_sink_nodes.count(\"m1/1\"), 1);\n\tBOOST_CHECK_EQUAL(identified_sink_nodes.count(\"m2/0\"), 1);\n\tBOOST_CHECK_EQUAL(identified_sink_nodes.count(\"m2/3\"), 1);\n\tBOOST_CHECK_EQUAL(identified_sink_nodes.count(\"m3/2\"), 1);\n\tBOOST_CHECK_EQUAL(tensor_ops.size(), 2);\n\tBOOST_CHECK_EQUAL(tensor_ops.at(\"m1/1\")[0], 1);\n\tBOOST_CHECK_EQUAL(tensor_ops.at(\"m1/1\")[1], 2);\n\tBOOST_CHECK_EQUAL(tensor_ops.at(\"m2/0\")[0], 0);\n\tBOOST_CHECK_EQUAL(tensor_ops.at(\"m2/0\")[1], 3);\n}\n\nModel<float> model_getForwardPropogationLayerTensorDimensions = makeModelIG();\nBOOST_AUTO_TEST_CASE(getForwardPropogationLayerTensorDimensions)\n{\n\tModelInterpreterDefaultDevice<float> model_interpreter;\n\n\tint iter;\n\tstd::vector<OperationList<float>> FP_operations_list;\n\tmodel_interpreter.getFPOpsGraph_(model_getForwardPropogationLayerTensorDimensions, FP_operations_list, iter);\n\n\tstd::set<std::string> identified_sink_nodes;\n\tstd::map<std::string, std::vector<int>> tensor_ops = model_interpreter.getTensorOperations(FP_operations_list, identified_sink_nodes, false);\n\n  std::map<int, int> max_layer_sizes;\n  std::map<std::string, int> layer_name_pos;\n  std::vector<int> source_layer_sizes, sink_layer_sizes;\n  std::vector<std::vector<std::pair<int, int>>> weight_indices;\n  std::vector<std::map<std::string, std::vector<std::pair<int, int>>>> shared_weight_indices;\n  std::vector<std::vector<float>> weight_values;\n  std::vector<bool> make_source_tensors, make_sink_tensors, make_weight_tensors;\n  std::vector<int> source_layer_pos, sink_layer_pos;\n  int tensor_layers_cnt = 0;\n  int weight_layers_cnt = 0;\n  model_interpreter.getForwardPropogationLayerTensorDimensions(FP_operations_list, tensor_ops, source_layer_sizes, sink_layer_sizes, weight_indices, shared_weight_indices, weight_values, make_source_tensors, make_sink_tensors, make_weight_tensors,\n    source_layer_pos, sink_layer_pos, max_layer_sizes, layer_name_pos, tensor_layers_cnt, weight_layers_cnt);\n\n\tBOOST_CHECK_EQUAL(source_layer_sizes.size(), 2);\n\tBOOST_CHECK_EQUAL(source_layer_sizes[0], 1);\n\tBOOST_CHECK_EQUAL(source_layer_sizes[1], 2);\n\tBOOST_CHECK_EQUAL(sink_layer_sizes.size(), 2);\n\tBOOST_CHECK_EQUAL(sink_layer_sizes[0], 2);\n\tBOOST_CHECK_EQUAL(sink_layer_sizes[1], 1);\n\n  BOOST_CHECK_EQUAL(source_layer_pos.size(), 2);\n  BOOST_CHECK_EQUAL(source_layer_pos.at(0), 1);\n  BOOST_CHECK_EQUAL(source_layer_pos.at(1), 0);\n  BOOST_CHECK_EQUAL(sink_layer_pos.size(), 2); \n  BOOST_CHECK_EQUAL(sink_layer_pos.at(0), 0);\n  BOOST_CHECK_EQUAL(sink_layer_pos.at(1), 1);\n\n  BOOST_CHECK_EQUAL(max_layer_sizes.size(), 2);\n  BOOST_CHECK_EQUAL(max_layer_sizes.at(0), 1);\n  BOOST_CHECK_EQUAL(max_layer_sizes.at(1), 0);\n\n  BOOST_CHECK_EQUAL(layer_name_pos.size(), 0);\n\n\tBOOST_CHECK_EQUAL(weight_indices.size(), 2);\n\tBOOST_CHECK_EQUAL(weight_indices[0].size(), 2);\n\tBOOST_CHECK_EQUAL(weight_indices[1].size(), 2);\n\tstd::vector<std::vector<std::pair<int, int>>> weight_indices_test1 = {\n\t\t{std::make_pair(0,0),std::make_pair(0,1)},\n\t\t{std::make_pair(0,0),std::make_pair(1,0)}\n\t};\n\tfor (int tensor_iter = 0; tensor_iter < weight_indices_test1.size(); ++tensor_iter) {\n\t\tfor (int i = 0; i < weight_indices_test1[tensor_iter].size(); ++i) {\n\t\t\tBOOST_CHECK_EQUAL(weight_indices[tensor_iter][i].first, weight_indices_test1[tensor_iter][i].first);\n\t\t\tBOOST_CHECK_EQUAL(weight_indices[tensor_iter][i].second, weight_indices_test1[tensor_iter][i].second);\n\t\t}\n\t}\n\n\tBOOST_CHECK_EQUAL(shared_weight_indices.size(), 2);\n\tBOOST_CHECK_EQUAL(shared_weight_indices[0].size(), 0);\n\tBOOST_CHECK_EQUAL(shared_weight_indices[1].size(), 0);\n\n\tBOOST_CHECK_EQUAL(weight_values.size(), 2);\n\tBOOST_CHECK_EQUAL(weight_values[0].size(), 2);\n\tBOOST_CHECK_EQUAL(weight_values[1].size(), 2);\n\tstd::vector<std::vector<float>> weight_values_test1 = { {1, 1}, {1, 1} };\n\tfor (int tensor_iter = 0; tensor_iter < weight_values_test1.size(); ++tensor_iter) {\n\t\tfor (int i = 0; i < weight_values_test1[tensor_iter].size(); ++i) {\n\t\t\tBOOST_CHECK_EQUAL(weight_values[tensor_iter][i], weight_values_test1[tensor_iter][i]);\n\t\t}\n\t}\n\n\tBOOST_CHECK_EQUAL(make_source_tensors.size(), 2);\n\tBOOST_CHECK(make_source_tensors[0]);\n\tBOOST_CHECK(!make_source_tensors[1]);\n\tBOOST_CHECK_EQUAL(make_sink_tensors.size(), 2);\n\tBOOST_CHECK(make_sink_tensors[0]);\n\tBOOST_CHECK(!make_sink_tensors[1]);\n\tBOOST_CHECK_EQUAL(make_weight_tensors.size(), 2);\n\tBOOST_CHECK(make_weight_tensors[0]);\n\tBOOST_CHECK(make_weight_tensors[1]);\n}\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "b98d4145357b80eb92e20b32e84e45a69c2ca73d", "size": 11004, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tests/class_tests/evonet/source/ModelInterpreter_IG_test.cpp", "max_stars_repo_name": "dmccloskey/smartPeak_cpp", "max_stars_repo_head_hexsha": "47a19a804b65daef712418b4e278704b340d20b9", "max_stars_repo_licenses": ["MIT"], "max_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/class_tests/evonet/source/ModelInterpreter_IG_test.cpp", "max_issues_repo_name": "dmccloskey/smartPeak_cpp", "max_issues_repo_head_hexsha": "47a19a804b65daef712418b4e278704b340d20b9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2018-01-11T20:39:09.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-11T21:02:31.000Z", "max_forks_repo_path": "src/tests/class_tests/evonet/source/ModelInterpreter_IG_test.cpp", "max_forks_repo_name": "dmccloskey/smartPeak_cpp", "max_forks_repo_head_hexsha": "47a19a804b65daef712418b4e278704b340d20b9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.6902654867, "max_line_length": 357, "alphanum_fraction": 0.7594511087, "num_tokens": 3119, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.4815506883704115}}
{"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   testSimilarity3.cpp\n * @brief  Unit tests for Similarity3 class\n * @author Paul Drews\n * @author Zhaoyang Lv\n */\n\n#include <gtsam_unstable/geometry/Similarity3.h>\n#include <gtsam/slam/BetweenFactor.h>\n#include <gtsam/nonlinear/NonlinearFactorGraph.h>\n#include <gtsam/nonlinear/ExpressionFactorGraph.h>\n#include <gtsam/nonlinear/Values.h>\n#include <gtsam/nonlinear/LevenbergMarquardtOptimizer.h>\n#include <gtsam/geometry/Pose3.h>\n#include <gtsam/inference/Symbol.h>\n#include <gtsam/base/numericalDerivative.h>\n#include <gtsam/base/testLie.h>\n#include <gtsam/base/Testable.h>\n\n#include <CppUnitLite/TestHarness.h>\n\n#include <boost/function.hpp>\n#include <boost/bind.hpp>\n\nusing namespace gtsam;\nusing namespace std;\nusing symbol_shorthand::X;\n\nGTSAM_CONCEPT_TESTABLE_INST(Similarity3)\n\nstatic const Point3 P(0.2, 0.7, -2);\nstatic const Rot3 R = Rot3::Rodrigues(0.3, 0, 0);\nstatic const double s = 4;\nstatic const Similarity3 id;\nstatic const Similarity3 T1(R, Point3(3.5, -8.2, 4.2), 1);\nstatic const Similarity3 T2(Rot3::Rodrigues(0.3, 0.2, 0.1),\n    Point3(3.5, -8.2, 4.2), 1);\nstatic const Similarity3 T3(Rot3::Rodrigues(-90, 0, 0), Point3(1, 2, 3), 1);\nstatic const Similarity3 T4(R, P, s);\nstatic const Similarity3 T5(R, P, 10);\nstatic const Similarity3 T6(Rot3(), Point3(1, 1, 0), 2); // Simpler transform\n\nconst double degree = M_PI / 180;\n\n//******************************************************************************\nTEST(Similarity3, Concepts) {\n  BOOST_CONCEPT_ASSERT((IsGroup<Similarity3 >));\n  BOOST_CONCEPT_ASSERT((IsManifold<Similarity3 >));\n  BOOST_CONCEPT_ASSERT((IsLieGroup<Similarity3 >));\n}\n\n//******************************************************************************\nTEST(Similarity3, Constructors) {\n  Similarity3 sim3_Construct1;\n  Similarity3 sim3_Construct2(s);\n  Similarity3 sim3_Construct3(R, P, s);\n  Similarity3 sim4_Construct4(R.matrix(), P, s);\n}\n\n//******************************************************************************\nTEST(Similarity3, Getters) {\n  Similarity3 sim3_default;\n  EXPECT(assert_equal(Rot3(), sim3_default.rotation()));\n  EXPECT(assert_equal(Point3(0,0,0), sim3_default.translation()));\n  EXPECT_DOUBLES_EQUAL(1.0, sim3_default.scale(), 1e-9);\n\n  Similarity3 sim3(Rot3::Ypr(1, 2, 3), Point3(4, 5, 6), 7);\n  EXPECT(assert_equal(Rot3::Ypr(1, 2, 3), sim3.rotation()));\n  EXPECT(assert_equal(Point3(4, 5, 6), sim3.translation()));\n  EXPECT_DOUBLES_EQUAL(7.0, sim3.scale(), 1e-9);\n}\n\n//******************************************************************************\nTEST(Similarity3, AdjointMap) {\n  const Matrix4 T = T2.matrix();\n  // Check Ad with actual definition\n  Vector7 delta;\n  delta << 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7;\n  Matrix4 W = Similarity3::wedge(delta);\n  Matrix4 TW = Similarity3::wedge(T2.AdjointMap() * delta);\n  EXPECT(assert_equal(TW, Matrix4(T * W * T.inverse()), 1e-9));\n}\n\n//******************************************************************************\nTEST(Similarity3, inverse) {\n  Similarity3 sim3(Rot3::Ypr(1, 2, 3).inverse(), Point3(4, 5, 6), 7);\n  Matrix3 Re; // some values from matlab\n  Re << -0.2248, 0.9024, -0.3676, -0.3502, -0.4269, -0.8337, -0.9093, -0.0587, 0.4120;\n  Vector3 te(-9.8472, 59.7640, 10.2125);\n  Similarity3 expected(Re, te, 1.0 / 7.0);\n  EXPECT(assert_equal(expected, sim3.inverse(), 1e-4));\n  EXPECT(assert_equal(sim3, sim3.inverse().inverse(), 1e-8));\n\n  // test lie group inverse\n  Matrix H1, H2;\n  EXPECT(assert_equal(expected, sim3.inverse(H1), 1e-4));\n  EXPECT(assert_equal(sim3, sim3.inverse().inverse(H2), 1e-8));\n}\n\n//******************************************************************************\nTEST(Similarity3, Multiplication) {\n  Similarity3 test1(Rot3::Ypr(1, 2, 3).inverse(), Point3(4, 5, 6), 7);\n  Similarity3 test2(Rot3::Ypr(1, 2, 3).inverse(), Point3(8, 9, 10), 11);\n  Matrix3 re;\n  re << 0.0688, 0.9863, -0.1496, -0.5665, -0.0848, -0.8197, -0.8211, 0.1412, 0.5530;\n  Vector3 te(-13.6797, 3.2441, -5.7794);\n  Similarity3 expected(re, te, 77);\n  EXPECT(assert_equal(expected, test1 * test2, 1e-2));\n}\n\n//******************************************************************************\nTEST(Similarity3, Manifold) {\n  EXPECT_LONGS_EQUAL(7, Similarity3::Dim());\n  Vector z = Vector7::Zero();\n  Similarity3 sim;\n  EXPECT(sim.retract(z) == sim);\n\n  Vector7 v = Vector7::Zero();\n  v(6) = 2;\n  Similarity3 sim2;\n  EXPECT(sim2.retract(z) == sim2);\n\n  EXPECT(assert_equal(z, sim2.localCoordinates(sim)));\n\n  Similarity3 sim3 = Similarity3(Rot3(), Point3(1, 2, 3), 1);\n  Vector v3(7);\n  v3 << 0, 0, 0, 1, 2, 3, 0;\n  EXPECT(assert_equal(v3, sim2.localCoordinates(sim3)));\n\n  Similarity3 other = Similarity3(Rot3::Ypr(0.1, 0.2, 0.3), Point3(4, 5, 6), 1);\n\n  Vector vlocal = sim.localCoordinates(other);\n\n  EXPECT(assert_equal(sim.retract(vlocal), other, 1e-2));\n\n  Similarity3 other2 = Similarity3(Rot3::Ypr(0.3, 0, 0), Point3(4, 5, 6), 1);\n  Rot3 R = Rot3::Rodrigues(0.3, 0, 0);\n\n  Vector vlocal2 = sim.localCoordinates(other2);\n\n  EXPECT(assert_equal(sim.retract(vlocal2), other2, 1e-2));\n\n  // TODO add unit tests for retract and localCoordinates\n}\n\n//******************************************************************************\nTEST( Similarity3, retract_first_order) {\n  Similarity3 id;\n  Vector v = Z_7x1;\n  v(0) = 0.3;\n  EXPECT(assert_equal(Similarity3(R, Point3(0,0,0), 1), id.retract(v), 1e-2));\n//  v(3) = 0.2;\n//  v(4) = 0.7;\n//  v(5) = -2;\n//  EXPECT(assert_equal(Similarity3(R, P, 1), id.retract(v), 1e-2));\n}\n\n//******************************************************************************\nTEST(Similarity3, localCoordinates_first_order) {\n  Vector7 d12 = Vector7::Constant(0.1);\n  d12(6) = 1.0;\n  Similarity3 t1 = T1, t2 = t1.retract(d12);\n  EXPECT(assert_equal(d12, t1.localCoordinates(t2)));\n}\n\n//******************************************************************************\nTEST(Similarity3, manifold_first_order) {\n  Similarity3 t1 = T1;\n  Similarity3 t2 = T3;\n  Similarity3 origin;\n  Vector d12 = t1.localCoordinates(t2);\n  EXPECT(assert_equal(t2, t1.retract(d12)));\n  Vector d21 = t2.localCoordinates(t1);\n  EXPECT(assert_equal(t1, t2.retract(d21)));\n}\n\n//******************************************************************************\n// Return as a 4*4 Matrix\nTEST(Similarity3, Matrix) {\n  Matrix4 expected;\n  expected << 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0.5;\n  Matrix4 actual = T6.matrix();\n  EXPECT(assert_equal(expected, actual));\n}\n\n//*****************************************************************************\n// Exponential and log maps\nTEST(Similarity3, ExpLogMap) {\n  Vector7 delta;\n  delta << 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7;\n  Vector7 actual = Similarity3::Logmap(Similarity3::Expmap(delta));\n  EXPECT(assert_equal(delta, actual));\n\n  Vector7 zeros;\n  zeros << 0, 0, 0, 0, 0, 0, 0;\n  Vector7 logIdentity = Similarity3::Logmap(Similarity3::identity());\n  EXPECT(assert_equal(zeros, logIdentity));\n\n  Similarity3 expZero = Similarity3::Expmap(zeros);\n  Similarity3 ident = Similarity3::identity();\n  EXPECT(assert_equal(expZero, ident));\n\n  // Compare to matrix exponential, using expm in Lie.h\n  EXPECT(\n      assert_equal(expm<Similarity3>(delta), Similarity3::Expmap(delta), 1e-3));\n}\n\n//******************************************************************************\n// Group action on Point3 (with simpler transform)\nTEST(Similarity3, GroupAction) {\n  EXPECT(assert_equal(Point3(2, 2, 0), T6 * Point3(0, 0, 0)));\n  EXPECT(assert_equal(Point3(4, 2, 0), T6 * Point3(1, 0, 0)));\n\n  // Test group action on R^4 via matrix representation\n  Vector4 qh;\n  qh << 1, 0, 0, 1;\n  Vector4 ph;\n  ph << 2, 1, 0, 0.5; // equivalent to Point3(4, 2, 0)\n  EXPECT(assert_equal((Vector )ph, T6.matrix() * qh));\n\n  // Test some more...\n  Point3 pa = Point3(1, 0, 0);\n  Similarity3 Ta(Rot3(), Point3(1, 2, 3), 1.0);\n  Similarity3 Tb(Rot3(), Point3(1, 2, 3), 2.0);\n  EXPECT(assert_equal(Point3(2, 2, 3), Ta.transformFrom(pa)));\n  EXPECT(assert_equal(Point3(4, 4, 6), Tb.transformFrom(pa)));\n\n  Similarity3 Tc(Rot3::Rz(M_PI / 2.0), Point3(1, 2, 3), 1.0);\n  Similarity3 Td(Rot3::Rz(M_PI / 2.0), Point3(1, 2, 3), 2.0);\n  EXPECT(assert_equal(Point3(1, 3, 3), Tc.transformFrom(pa)));\n  EXPECT(assert_equal(Point3(2, 6, 6), Td.transformFrom(pa)));\n\n  // Test derivative\n  boost::function<Point3(Similarity3, Point3)> f = boost::bind(\n      &Similarity3::transformFrom, _1, _2, boost::none, boost::none);\n\n  Point3 q(1, 2, 3);\n  for (const auto& T : { T1, T2, T3, T4, T5, T6 }) {\n    Point3 q(1, 0, 0);\n    Matrix H1 = numericalDerivative21<Point3, Similarity3, Point3>(f, T, q);\n    Matrix H2 = numericalDerivative22<Point3, Similarity3, Point3>(f, T, q);\n    Matrix actualH1, actualH2;\n    T.transformFrom(q, actualH1, actualH2);\n    EXPECT(assert_equal(H1, actualH1));\n    EXPECT(assert_equal(H2, actualH2));\n  }\n}\n\n//******************************************************************************\n// Group action on Pose3\nTEST(Similarity3, GroupActionPose3) {\n  Similarity3 bSa(Rot3::Ry(180 * degree), Point3(2, 3, 5), 2.0);\n\n  // Create source poses\n  Pose3 Ta1(Rot3(), Point3(0, 0, 0));\n  Pose3 Ta2(Rot3(-1, 0, 0, 0, -1, 0, 0, 0, 1), Point3(4, 0, 0));\n\n  // Create destination poses\n  Pose3 expected_Tb1(Rot3(-1, 0, 0, 0, 1, 0, 0, 0, -1), Point3(4, 6, 10));\n  Pose3 expected_Tb2(Rot3(1, 0, 0, 0, -1, 0, 0, 0, -1), Point3(-4, 6, 10));\n\n  EXPECT(assert_equal(expected_Tb1, bSa.transformFrom(Ta1)));\n  EXPECT(assert_equal(expected_Tb2, bSa.transformFrom(Ta2)));\n}\n\n// Test left group action compatibility.\n// cSa*Ta = cSb*bSa*Ta\nTEST(Similarity3, GroupActionPose3_Compatibility) {\n  Similarity3 bSa(Rot3::Ry(180 * degree), Point3(2, 3, 5), 2.0);\n  Similarity3 cSb(Rot3::Ry(90 * degree), Point3(-10, -4, 0), 3.0);\n  Similarity3 cSa(Rot3::Ry(270 * degree), Point3(0, 1, -2), 6.0);\n\n  // Create poses\n  Pose3 Ta1(Rot3(), Point3(0, 0, 0));\n  Pose3 Ta2(Rot3(-1, 0, 0, 0, -1, 0, 0, 0, 1), Point3(4, 0, 0));\n  Pose3 Tb1(Rot3(-1, 0, 0, 0, 1, 0, 0, 0, -1), Point3(4, 6, 10));\n  Pose3 Tb2(Rot3(1, 0, 0, 0, -1, 0, 0, 0, -1), Point3(-4, 6, 10));\n  Pose3 Tc1(Rot3(0, 0, -1, 0, 1, 0, 1, 0, 0), Point3(0, 6, -12));\n  Pose3 Tc2(Rot3(0, 0, -1, 0, -1, 0, -1, 0, 0), Point3(0, 6, 12));\n\n  EXPECT(assert_equal(Tc1, cSb.transformFrom(Tb1)));\n  EXPECT(assert_equal(Tc2, cSb.transformFrom(Tb2)));\n\n  EXPECT(assert_equal(cSa.transformFrom(Ta1), cSb.transformFrom(Tb1)));\n  EXPECT(assert_equal(cSa.transformFrom(Ta2), cSb.transformFrom(Tb2)));\n}\n\n//******************************************************************************\n// Align with Point3 Pairs\nTEST(Similarity3, AlignPoint3_1) {\n  Similarity3 expected_aSb(Rot3::Rz(-90 * degree), Point3(3, 4, 5), 2.0);\n\n  Point3 b1(0, 0, 0), b2(3, 0, 0), b3(3, 0, 4);\n\n  Point3Pair ab1(make_pair(expected_aSb.transformFrom(b1), b1));\n  Point3Pair ab2(make_pair(expected_aSb.transformFrom(b2), b2));\n  Point3Pair ab3(make_pair(expected_aSb.transformFrom(b3), b3));\n\n  vector<Point3Pair> correspondences{ab1, ab2, ab3};\n\n  Similarity3 actual_aSb = Similarity3::Align(correspondences);\n  EXPECT(assert_equal(expected_aSb, actual_aSb));\n}\n\nTEST(Similarity3, AlignPoint3_2) {\n  Similarity3 expected_aSb(Rot3(), Point3(10, 10, 0), 1.0);\n\n  Point3 b1(0, 0, 0), b2(20, 10, 0), b3(10, 20, 0);\n\n  Point3Pair ab1(make_pair(expected_aSb.transformFrom(b1), b1));\n  Point3Pair ab2(make_pair(expected_aSb.transformFrom(b2), b2));\n  Point3Pair ab3(make_pair(expected_aSb.transformFrom(b3), b3));\n\n  vector<Point3Pair> correspondences{ab1, ab2, ab3};\n\n  Similarity3 actual_aSb = Similarity3::Align(correspondences);\n  EXPECT(assert_equal(expected_aSb, actual_aSb));\n}\n\nTEST(Similarity3, AlignPoint3_3) {\n  Similarity3 expected_aSb(Rot3::RzRyRx(0.3, 0.2, 0.1), Point3(20, 10, 5), 1.0);\n\n  Point3 b1(0, 0, 1), b2(10, 0, 2), b3(20, -10, 30);\n\n  Point3Pair ab1(make_pair(expected_aSb.transformFrom(b1), b1));\n  Point3Pair ab2(make_pair(expected_aSb.transformFrom(b2), b2));\n  Point3Pair ab3(make_pair(expected_aSb.transformFrom(b3), b3));\n\n  vector<Point3Pair> correspondences{ab1, ab2, ab3};\n\n  Similarity3 actual_aSb = Similarity3::Align(correspondences);\n  EXPECT(assert_equal(expected_aSb, actual_aSb));\n}\n\n//******************************************************************************\n// Align with Pose3 Pairs\nTEST(Similarity3, AlignPose3) {\n  Similarity3 expected_aSb(Rot3::Ry(180 * degree), Point3(2, 3, 5), 2.0);\n\n  // Create source poses\n  Pose3 Ta1(Rot3(), Point3(0, 0, 0));\n  Pose3 Ta2(Rot3(-1, 0, 0, 0, -1, 0, 0, 0, 1), Point3(4, 0, 0));\n\n  // Create destination poses\n  Pose3 Tb1(Rot3(-1, 0, 0, 0, 1, 0, 0, 0, -1), Point3(4, 6, 10));\n  Pose3 Tb2(Rot3(1, 0, 0, 0, -1, 0, 0, 0, -1), Point3(-4, 6, 10));\n\n  Pose3Pair bTa1(make_pair(Tb1, Ta1));\n  Pose3Pair bTa2(make_pair(Tb2, Ta2));\n\n  vector<Pose3Pair> correspondences{bTa1, bTa2};\n\n  Similarity3 actual_aSb = Similarity3::Align(correspondences);\n  EXPECT(assert_equal(expected_aSb, actual_aSb));\n}\n\n//******************************************************************************\n// Test very simple prior optimization example\nTEST(Similarity3, Optimization) {\n  // Create a PriorFactor with a Sim3 prior\n  Similarity3 prior = Similarity3(Rot3::Ypr(0.1, 0.2, 0.3), Point3(1, 2, 3), 4);\n  noiseModel::Isotropic::shared_ptr model = noiseModel::Isotropic::Sigma(7, 1);\n  Symbol key('x', 1);\n\n  // Create graph\n  NonlinearFactorGraph graph;\n  graph.addPrior(key, prior, model);\n\n  // Create initial estimate with identity transform\n  Values initial;\n  initial.insert<Similarity3>(key, Similarity3());\n\n  // Optimize\n  Values result;\n  LevenbergMarquardtParams params;\n  params.setVerbosityLM(\"TRYCONFIG\");\n  result = LevenbergMarquardtOptimizer(graph, initial).optimize();\n\n  // After optimization, result should be prior\n  EXPECT(assert_equal(prior, result.at<Similarity3>(key), 1e-4));\n}\n\n//******************************************************************************\n// Test optimization with both Prior and BetweenFactors\nTEST(Similarity3, Optimization2) {\n  Similarity3 prior = Similarity3();\n  Similarity3 m1 = Similarity3(Rot3::Ypr(M_PI / 4.0, 0, 0), Point3(2.0, 0, 0),\n      1.0);\n  Similarity3 m2 = Similarity3(Rot3::Ypr(M_PI / 2.0, 0, 0),\n      Point3(sqrt(8) * 0.9, 0, 0), 1.0);\n  Similarity3 m3 = Similarity3(Rot3::Ypr(3 * M_PI / 4.0, 0, 0),\n      Point3(sqrt(32) * 0.8, 0, 0), 1.0);\n  Similarity3 m4 = Similarity3(Rot3::Ypr(M_PI / 2.0, 0, 0),\n      Point3(6 * 0.7, 0, 0), 1.0);\n  Similarity3 loop = Similarity3(1.42);\n\n  //prior.print(\"Goal Transform\");\n  noiseModel::Isotropic::shared_ptr model = noiseModel::Isotropic::Sigma(7,\n      0.01);\n  SharedDiagonal betweenNoise = noiseModel::Diagonal::Sigmas(\n      (Vector(7) << 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 10).finished());\n  SharedDiagonal betweenNoise2 = noiseModel::Diagonal::Sigmas(\n      (Vector(7) << 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 1.0).finished());\n  BetweenFactor<Similarity3> b1(X(1), X(2), m1, betweenNoise);\n  BetweenFactor<Similarity3> b2(X(2), X(3), m2, betweenNoise);\n  BetweenFactor<Similarity3> b3(X(3), X(4), m3, betweenNoise);\n  BetweenFactor<Similarity3> b4(X(4), X(5), m4, betweenNoise);\n  BetweenFactor<Similarity3> lc(X(5), X(1), loop, betweenNoise2);\n\n  // Create graph\n  NonlinearFactorGraph graph;\n  graph.addPrior(X(1), prior, model); // Prior !\n  graph.push_back(b1);\n  graph.push_back(b2);\n  graph.push_back(b3);\n  graph.push_back(b4);\n  graph.push_back(lc);\n\n  //graph.print(\"Full Graph\\n\");\n  Values initial;\n  initial.insert<Similarity3>(X(1), Similarity3());\n  initial.insert<Similarity3>(X(2),\n      Similarity3(Rot3::Ypr(M_PI / 2.0, 0, 0), Point3(1, 0, 0), 1.1));\n  initial.insert<Similarity3>(X(3),\n      Similarity3(Rot3::Ypr(2.0 * M_PI / 2.0, 0, 0), Point3(0.9, 1.1, 0), 1.2));\n  initial.insert<Similarity3>(X(4),\n      Similarity3(Rot3::Ypr(3.0 * M_PI / 2.0, 0, 0), Point3(0, 1, 0), 1.3));\n  initial.insert<Similarity3>(X(5),\n      Similarity3(Rot3::Ypr(4.0 * M_PI / 2.0, 0, 0), Point3(0, 0, 0), 1.0));\n\n  //initial.print(\"Initial Estimate\\n\");\n\n  Values result;\n  result = LevenbergMarquardtOptimizer(graph, initial).optimize();\n  //result.print(\"Optimized Estimate\\n\");\n  Pose3 p1, p2, p3, p4, p5;\n  p1 = Pose3(result.at<Similarity3>(X(1)));\n  p2 = Pose3(result.at<Similarity3>(X(2)));\n  p3 = Pose3(result.at<Similarity3>(X(3)));\n  p4 = Pose3(result.at<Similarity3>(X(4)));\n  p5 = Pose3(result.at<Similarity3>(X(5)));\n\n  //p1.print(\"Pose1\");\n  //p2.print(\"Pose2\");\n  //p3.print(\"Pose3\");\n  //p4.print(\"Pose4\");\n  //p5.print(\"Pose5\");\n\n  Similarity3 expected(0.7);\n  EXPECT(assert_equal(expected, result.at<Similarity3>(X(5)), 0.4));\n}\n\n//******************************************************************************\n// Align points (p,q) assuming that p = T*q + noise\nTEST(Similarity3, AlignScaledPointClouds) {\n// Create ground truth\n  Point3 q1(0, 0, 0), q2(1, 0, 0), q3(0, 1, 0);\n\n  // Create transformed cloud (noiseless)\n//  Point3 p1 = T4 * q1, p2 = T4 * q2, p3 = T4 * q3;\n\n  // Create an unknown expression\n  Expression<Similarity3> unknownT(0); // use key 0\n\n  // Create constant expressions for the ground truth points\n  Expression<Point3> q1_(q1), q2_(q2), q3_(q3);\n\n  // Create prediction expressions\n  Expression<Point3> predict1(unknownT, &Similarity3::transformFrom, q1_);\n  Expression<Point3> predict2(unknownT, &Similarity3::transformFrom, q2_);\n  Expression<Point3> predict3(unknownT, &Similarity3::transformFrom, q3_);\n\n//// Create Expression factor graph\n//  ExpressionFactorGraph graph;\n//  graph.addExpressionFactor(predict1, p1, R); // |T*q1 - p1|\n//  graph.addExpressionFactor(predict2, p2, R); // |T*q2 - p2|\n//  graph.addExpressionFactor(predict3, p3, R); // |T*q3 - p3|\n}\n\n//******************************************************************************\nTEST(Similarity3 , Invariants) {\n  Similarity3 id;\n\n  EXPECT(check_group_invariants(id, id));\n  EXPECT(check_group_invariants(id, T3));\n  EXPECT(check_group_invariants(T2, id));\n  EXPECT(check_group_invariants(T2, T3));\n\n  EXPECT(check_manifold_invariants(id, id));\n  EXPECT(check_manifold_invariants(id, T3));\n  EXPECT(check_manifold_invariants(T2, id));\n  EXPECT(check_manifold_invariants(T2, T3));\n}\n\n//******************************************************************************\nTEST(Similarity3 , LieGroupDerivatives) {\n  Similarity3 id;\n\n  CHECK_LIE_GROUP_DERIVATIVES(id, id);\n  CHECK_LIE_GROUP_DERIVATIVES(id, T2);\n  CHECK_LIE_GROUP_DERIVATIVES(T2, id);\n  CHECK_LIE_GROUP_DERIVATIVES(T2, T3);\n}\n\n//******************************************************************************\nint main() {\n  TestResult tr;\n  return TestRegistry::runAllTests(tr);\n}\n//******************************************************************************\n\n", "meta": {"hexsha": "b985eb3741673bf5863e2bf58efcf608ec2245aa", "size": 18933, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam_unstable/geometry/tests/testSimilarity3.cpp", "max_stars_repo_name": "martinvl/gtsam", "max_stars_repo_head_hexsha": "2315df694aff7e648d2e22a478685946e7de4f24", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gtsam_unstable/geometry/tests/testSimilarity3.cpp", "max_issues_repo_name": "martinvl/gtsam", "max_issues_repo_head_hexsha": "2315df694aff7e648d2e22a478685946e7de4f24", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-03-18T17:43:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-15T20:21:19.000Z", "max_forks_repo_path": "gtsam_unstable/geometry/tests/testSimilarity3.cpp", "max_forks_repo_name": "martinvl/gtsam", "max_forks_repo_head_hexsha": "2315df694aff7e648d2e22a478685946e7de4f24", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-02T08:39:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-02T08:39:51.000Z", "avg_line_length": 36.2007648184, "max_line_length": 86, "alphanum_fraction": 0.6045528971, "num_tokens": 6470, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6791786861878392, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.48155068794216144}}
{"text": "#include <sophus/se3.h>\n#include <string>\n#include <iostream>\n#include <fstream>\n#include <unistd.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <Eigen/StdVector>\n// need pangolin for plotting trajectory\n#include <pangolin/pangolin.h>\n\nusing namespace std;\n\n// path to trajectory file\nstring trajectory_file = \"./compare.txt\";\n\n// function for plotting trajectory, don't edit this code\n// start point is red and end point is blue\n\n/*******************************************************************************************/\nvoid DrawTrajectoryc(vector<Sophus::SE3> poses1, vector<Sophus::SE3> poses2)\n{\n    if (poses1.empty() || poses2.empty())\n    {\n        cerr << \"Trajectory is empty!\" << endl;\n        return;\n    }\n\n    // create pangolin window and plot the trajectory\n    pangolin::CreateWindowAndBind(\"Trajectory Viewer\", 1024, 768);\n    glEnable(GL_DEPTH_TEST);\n    glEnable(GL_BLEND);\n    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\n    pangolin::OpenGlRenderState s_cam(\n        pangolin::ProjectionMatrix(1024, 768, 500, 500, 512, 389, 0.1, 1000),\n        pangolin::ModelViewLookAt(0, -0.1, -1.8, 0, 0, 0, 0.0, -1.0, 0.0));\n\n    pangolin::View &d_cam = pangolin::CreateDisplay()\n                                .SetBounds(0.0, 1.0, pangolin::Attach::Pix(175), 1.0, -1024.0f / 768.0f)\n                                .SetHandler(new pangolin::Handler3D(s_cam));\n\n    while (pangolin::ShouldQuit() == false)\n    {\n        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n        d_cam.Activate(s_cam);\n        glClearColor(1.0f, 1.0f, 1.0f, 1.0f);\n\n        glLineWidth(2);\n        for (size_t i = 0; i < poses1.size() - 1; i++)\n        {\n            glColor3f(1 - (float)i / poses1.size(), 0.0f, (float)i / poses1.size());\n            glBegin(GL_LINES);\n            auto p1 = poses1[i], p2 = poses1[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\n        for (size_t i = 0; i < poses2.size() - 1; i++)\n        {\n            glColor3f(1 - (float)i / poses2.size(), 0.0f, (float)i / poses2.size());\n            glBegin(GL_LINES);\n            auto p1 = poses2[i], p2 = poses2[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\n        pangolin::FinishFrame();\n        usleep(5000); // sleep 5 ms\n    }\n}\n\nSophus::SE3 pose_estimation_3d3d(vector<Sophus::SE3> poses1, vector<Sophus::SE3> poses2)\n{\n\n    Eigen::Vector3d center1, center2;\n    int Number = poses1.size();\n    for (int i = 0; i < N; i++)\n    {\n        center1 += poses1[i].translation();\n        center2 += poses2[i].translation();\n    }\n    center1 = center1 / Number;\n    center2 = center2 / Number;\n\n    vector<Eigen::Vector3d> p1(Number), p2(Number);\n    for (int i = 0; i < N; i++)\n    {\n        p1[i] = poses1[i] - center1;\n        p2[i] = poses2[i] - center2;\n    }\n\n    Eigen::Matrix3d error = Eigen::Matrix3d::Zero();\n    for (int i = 0; i < N; i++)\n    {\n        error += p1[i] * p2[i].transpose();\n    }\n\n    Eigen::JacobiSVD<Eigen::Matrix3d> svd(error, Eigen::ComputeFullU | Eigen::ComputeFullV);\n    Eigen::Matrix3d U = svd.matrixU();\n    Eigen::Matrix3d V = svd.matrixV();\n    cout << \"U=\" << U << endl;\n    cout << \"V=\" << V << endl;\n\n    Eigen::Matrix3d R = U * (V.transpose());\n    Eigen::Vector3d t = p1 - R * p2;\n    Sophus::SE3 T(R,t);\n    return T;\n}\n\nint main(int argc, char **argv)\n{\n\n    vector<Sophus::SE3> poses1;\n    vector<Sophus::SE3> poses2;\n\n    /// implement pose reading code\n    // start your code here (5~10 lines)\n\n    ifstream fin(trajectory_file);\n    for (int i = 0; i < 620; i++)\n    {\n        double data[8] = {0};\n        for (auto &d : data)\n            fin >> d;\n        Eigen::Vector3d track1_t(data[1], data[2], data[3]);\n        Eigen::Quaterniond track1_q(data[7], data[4], data[5], data[6]);\n        Eigen::Vector3d track2_t(data[9], data[10], data[11]);\n        Eigen::Quaterniond track2_q(data[12], data[13], data[14], data[15]);\n        Sophus::SE3 SE3_1_qt(track1_q, track1_t);\n        Sophus::SE3 SE3_2_qt(track2_q, track2_t);\n\n        poses1.push_back(SE3_1_qt);\n        poses2.push_back(SE3_2_qt);\n    }\n    // end your code here\n\n    Sophus::SE3 T = pose_estimation_3d3d(vector<Sophus::SE3> poses1, vector<Sophus::SE3> poses2);\n    for (int k = 0 ;k <poses2.size();k++)\n    {\n        poses2[k]  = T*poses2[k];\n    }\n    \n    // draw trajectory in pangolin\n    DrawTrajectory(poses1, poses2);\n\n    return 0;\n}", "meta": {"hexsha": "778b3c3736c3c7e4c60d01d5c7140c4f9c00b6ee", "size": 4680, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "5/align_trajectory.cpp", "max_stars_repo_name": "Yvon-Shong/SLAM", "max_stars_repo_head_hexsha": "4f633e71e13e1b3482255bc5abc38446a56beebf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2018-03-16T16:30:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-01T12:25:08.000Z", "max_issues_repo_path": "SLAM14Lectures-master/5/align_trajectory.cpp", "max_issues_repo_name": "HCH2CHO/Visual_SLAM", "max_issues_repo_head_hexsha": "a5e977eb000b39e78d7b44e78e7856f6aabc4a02", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-07-08T11:52:08.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-01T18:40:41.000Z", "max_forks_repo_path": "SLAM14Lectures-master/5/align_trajectory.cpp", "max_forks_repo_name": "HCH2CHO/Visual_SLAM", "max_forks_repo_head_hexsha": "a5e977eb000b39e78d7b44e78e7856f6aabc4a02", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2018-03-16T16:30:38.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-28T11:37:37.000Z", "avg_line_length": 30.9933774834, "max_line_length": 104, "alphanum_fraction": 0.5647435897, "num_tokens": 1435, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.6261241702517976, "lm_q1q2_score": 0.4815397252929654}}
{"text": "#include \"apch.h\"\n#include \"Color.h\"\n\t//#include <Eigen/Core>\n\nnamespace A {\n\n\tstatic const float HSVToRGBHelper(float n, const Eigen::Vector4f& hsva)\n\t{\n\t\tAP_PROFILE_FN();\n\t\tfloat k = fmod(n + (hsva.x() * 360.0f), 6);\n\t\treturn hsva.z() - hsva.z() * hsva.y() * std::max(std::min(std::min(k, 4 - k), 1.0f), 0.0f);\n\t}\n\n\tconst Eigen::Vector4f HSVToRGB(const Eigen::Vector4f& hsva) noexcept\n\t{\n\t\tAP_PROFILE_FN();\n\t\treturn Eigen::Vector4f(HSVToRGBHelper(5, hsva), HSVToRGBHelper(3, hsva), HSVToRGBHelper(1, hsva), hsva.w());\n\t}\n\n\tconst Eigen::Vector4f RGBToHSV(const Eigen::Vector4f& rgba) noexcept\n\t{\n\t\tfloat V = std::max(std::max(rgba.x(), rgba.y()), rgba.z());\n\t\tfloat C = V - std::min(std::min(rgba.x(), rgba.y()), rgba.z());\n\n\t\tfloat h = 0;\n\t\tif (V == rgba.x())\n\t\t\th = (rgba.y() - rgba.z()) / C;\n\t\telse if (V == rgba.y())\n\t\t\th = 2 + (rgba.z() - rgba.x()) / C;\n\t\telse if (V == rgba.z())\n\t\t\th = 4 + (rgba.x() - rgba.y()) / C;\n\n\t\treturn Eigen::Vector4f(h, V == 0 ? 0 : C / V, V, rgba.w());\n\t}\n\n}", "meta": {"hexsha": "f5d619aa8e53ec052dd13539d91c7a43eb5959d6", "size": 992, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Apsis/src/Apsis/Utility/Color.cpp", "max_stars_repo_name": "Bodleum/Apsis", "max_stars_repo_head_hexsha": "8a849340355c50bf4635287b3c94b3a6c2985f2c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-04-16T09:11:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-14T17:45:04.000Z", "max_issues_repo_path": "Apsis/src/Apsis/Utility/Color.cpp", "max_issues_repo_name": "Bodleum/Apsis", "max_issues_repo_head_hexsha": "8a849340355c50bf4635287b3c94b3a6c2985f2c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Apsis/src/Apsis/Utility/Color.cpp", "max_forks_repo_name": "Bodleum/Apsis", "max_forks_repo_head_hexsha": "8a849340355c50bf4635287b3c94b3a6c2985f2c", "max_forks_repo_licenses": ["Apache-2.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.5555555556, "max_line_length": 110, "alphanum_fraction": 0.5776209677, "num_tokens": 367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.48146071738852114}}
{"text": "#include <ros/ros.h>\n#include <message_filters/subscriber.h>\n#include <geometry_msgs/PoseStamped.h>\n#include <sensor_msgs/Imu.h>\n#include <std_msgs/Header.h>\n#include <boost/math/constants/constants.hpp>\n#include <tf/tf.h>\n\nusing namespace std;\n\nstatic const double EPSILON = 0.01;\nstatic const double PI = boost::math::constants::pi<double>();\n\nnamespace\n{\nclass OnGroundDetector\n{\n\nprivate:\n    //! Node handle\n    ros::NodeHandle nh;\n\n    //! Private nh\n    ros::NodeHandle pnh;\n\n    //! Human IMU subscriber\n    auto_ptr<message_filters::Subscriber<sensor_msgs::Imu> > humanIMUSub;\n\n    //! Human fall subscriber\n    std::auto_ptr<message_filters::Subscriber<std_msgs::Header> > humanFallSub;\n\n    //! On ground publisher\n    ros::Publisher pub;\n\npublic:\n    OnGroundDetector() : pnh(\"~\")\n    {\n        ROS_INFO(\"Initializing the on ground detector\");\n\n        // Don't subscribe until the fall starts\n        humanIMUSub.reset(new message_filters::Subscriber<sensor_msgs::Imu>(nh, \"/in\", 1));\n        humanIMUSub->registerCallback(boost::bind(&OnGroundDetector::update, this, _1));\n        humanIMUSub->unsubscribe();\n\n        humanFallSub.reset(new message_filters::Subscriber<std_msgs::Header>(nh, \"/human/fall\", 1));\n        humanFallSub->registerCallback(boost::bind(&OnGroundDetector::fallDetected, this, _1));\n\n        pub = nh.advertise<std_msgs::Header>(\"/human/on_ground\", 1, true);\n\n        ROS_INFO(\"On ground detector initialized successfully\");\n    }\n\nprivate:\n\n    void fallDetected(const std_msgs::HeaderConstPtr& fallingMsg)\n    {\n        ROS_INFO(\"Human fall detected at @ %f. Beginning on ground detection.\", fallingMsg->stamp.toSec());\n        humanIMUSub->subscribe();\n    }\n\n    bool isOnGround(const geometry_msgs::Quaternion& orientation) {\n\n        // Rotate the quaternion to compensate for the initial rotation of the pole\n        tf::Quaternion correctedOrientation = orientPose(orientation);\n\n        // Compute a vector from the quaternion\n        tf::Vector3 up(0, 0, 1);\n        tf::Vector3 poseVector = tf::quatRotate(correctedOrientation, up).normalize();\n\n        // Now compute a vector that is the projection onto the ground plane\n        tf::Vector3 ground(poseVector.x(), poseVector.y(), 0.0);\n        ground.normalized();\n\n        tfScalar angle = poseVector.angle(ground);\n\n        return fabs(angle) < EPSILON || fabs(angle - PI) < EPSILON;\n    }\n\n    // Compensate for the model being initial aligned to the x axis and oriented\n    // up\n    static tf::Quaternion orientPose(const geometry_msgs::Quaternion& orientationMsg)\n    {\n        tf::Quaternion rotation = tf::createQuaternionFromRPY(0, PI / 2.0, 0);\n\n        tf::Quaternion orientation;\n        tf::quaternionMsgToTF(orientationMsg, orientation);\n        orientation *= rotation;\n        return orientation;\n    }\n\n    void update(const sensor_msgs::ImuConstPtr& imuData)\n    {\n        if (isOnGround(imuData->orientation))\n        {\n            std_msgs::Header header;\n            header.stamp = ros::Time::now();\n            pub.publish(header);\n            tf::Quaternion q;\n            tf::quaternionMsgToTF(imuData->orientation, q);\n            tf::Matrix3x3 m(q);\n            double roll, pitch, yaw;\n            m.getRPY(roll, pitch, yaw);\n            ROS_INFO(\"On ground detector has detected ground from Roll, Pitch, Yaw [%f] [%f] [%f]\", roll, pitch, yaw);\n\n            humanIMUSub->unsubscribe();\n        }\n    }\n};\n}\n\nint main(int argc, char** argv)\n{\n    ros::init(argc, argv, \"on_ground_detector\");\n    OnGroundDetector ogd;\n    ros::spin();\n    ROS_INFO(\"On ground detector exiting\");\n}\n\n", "meta": {"hexsha": "8808200ce71e82ef71c2f0919104cadeb13268a7", "size": 3609, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/on_ground_detector.cpp", "max_stars_repo_name": "PositronicsLab/humanoid_catching", "max_stars_repo_head_hexsha": "11d42d164c7f19fbd8642c9c0318a630111ec18e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/on_ground_detector.cpp", "max_issues_repo_name": "PositronicsLab/humanoid_catching", "max_issues_repo_head_hexsha": "11d42d164c7f19fbd8642c9c0318a630111ec18e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/on_ground_detector.cpp", "max_forks_repo_name": "PositronicsLab/humanoid_catching", "max_forks_repo_head_hexsha": "11d42d164c7f19fbd8642c9c0318a630111ec18e", "max_forks_repo_licenses": ["Apache-2.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.3277310924, "max_line_length": 118, "alphanum_fraction": 0.6519811582, "num_tokens": 858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.48146071738852114}}
{"text": "// Copyright (c) 2021 by Ignacio Alzugaray <alzugaray dot ign at gmail dot com>\n// ETH Zurich, Vision for Robotics Lab.\n\n#pragma once\n#include <Eigen/Eigen>\n\nnamespace haste {\ntemplate<typename Value_, typename Location_>\nclass InterpolatorType {\n public:\n  using Value = Value_;\n  using Location = Location_;\n\n  // TODO: Consider Rows and Cols to become size_t parameters.\n  // TODO: Consider using derived types directly from Eigen to deduct Value / Location / Sizes.\n  template<int kRows, int kCols>\n  using ValueArray = Eigen::Array<Value, kRows, kCols>;\n\n  template<int kRows, int kCols>\n  using LocationArray = Eigen::Array<Location, kRows, kCols>;\n\n  template<int kRows, int kCols>\n  static inline auto bilinearIncrementVector(ValueArray<kRows, kCols> &mat, const Location &x, const Location &y,\n                                             const Value &w) -> bool;\n\n  template<int kRows, int kCols>\n  static inline auto bilinearSample(const ValueArray<kRows, kCols> &mat, const Location &x, const Location &y) -> Value;\n\n  template<int kRows, int kCols, int kSamples>\n  static inline auto bilinearSampleVector(const ValueArray<kRows, kCols> &mat, const LocationArray<kSamples, 1> &x_vec,\n                                          const LocationArray<kSamples, 1> &y_vec) -> ValueArray<kSamples, 1>;\n\n  static inline auto bilinearKernel(const Location &x, const Location &y) -> ValueArray<2, 2>;\n\n  template<int kRows, int kCols>\n  static auto bilinearBlock(const ValueArray<kRows, kCols>& mat, const Location &xp, const Location &yp) -> Eigen::Ref<ValueArray<2, 2>>;\n\n};\n}// namespace haste\n\n#include \"interpolator_impl.hpp\"\n", "meta": {"hexsha": "cb1b3d35ad75a35428363bc41096c0edd2e15ca4", "size": 1633, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/haste/core/interpolator.hpp", "max_stars_repo_name": "ialzugaray/haste", "max_stars_repo_head_hexsha": "955c80acf6256d1d4fead22e6b11b8e351b34f53", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2020-09-23T07:54:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T08:36:32.000Z", "max_issues_repo_path": "include/haste/core/interpolator.hpp", "max_issues_repo_name": "ialzugaray/haste", "max_issues_repo_head_hexsha": "955c80acf6256d1d4fead22e6b11b8e351b34f53", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-01-07T08:47:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-03T10:44:31.000Z", "max_forks_repo_path": "include/haste/core/interpolator.hpp", "max_forks_repo_name": "ialzugaray/haste", "max_forks_repo_head_hexsha": "955c80acf6256d1d4fead22e6b11b8e351b34f53", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-06T06:26:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T06:26:11.000Z", "avg_line_length": 38.880952381, "max_line_length": 137, "alphanum_fraction": 0.7036129822, "num_tokens": 409, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743168019989179, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.4814229189879885}}
{"text": "// 12.April 2015:  copied from main.cpp (does the same except that relative errors are computed)\n\n// 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 <functional>\n#include <iostream>\n#include <thread>\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  boltzmann::Timer<> timer;\n  po::options_description options(\"options\");\n  options.add_options()\n      (\"config,c\", po::value<string>()->required(), \"config file\")\n      (\"help,h\", \"help\")\n      (\"output,o\", \"Output directory. Default creates dir `convergence_plots` in input dir\")\n      (\"ignore-restarted\", \"do not check for symlinks to infer restarted calculations\");\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  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;\n  if (vm.count(\"output\")) {\n    working_dir = bf::path(vm[\"output\"].as<string>()) / bf::path(\"convergence_plots\");\n  } else {\n    working_dir = bf::path(str_input_path) / bf::path(\"convergence_plots\");\n  }\n  bf::create_directory(working_dir);\n\n  // restart.config (load if existent)\n  YAML::Node ref_restart_config;\n  if (bf::exists(bf::path(str_ref_path) / bf::path(\"restart.yaml\"))) {\n    string fname = (bf::path(str_ref_path) / bf::path(\"restart.yaml\")).c_str();\n    ref_restart_config = YAML::LoadFile(fname);\n  }\n  YAML::Node inp_restart_config;\n  if (bf::exists(bf::path(str_input_path) / bf::path(\"restart.yaml\"))) {\n    string fname = (bf::path(str_input_path) / bf::path(\"restart.yaml\")).c_str();\n    inp_restart_config = YAML::LoadFile(fname);\n  }\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: \" << bf::absolute(working_dir, cwd) << 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  // spectral transfer matrix\n  auto Tv =\n      spectral_transfer_matrix(ref_grid_ptr->get_spectral_basis(), grid_ptr->get_spectral_basis());\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  const unsigned int L = ref_dh.n_dofs();\n  dealii::Vector<double> vmass(L);\n  dealii::Vector<double> venergy(L);\n  dealii::Vector<double> vux(L);  // momentum x\n  dealii::Vector<double> vuy(L);  // momnetum y\n\n  dealii::Vector<double> vm_ref(L);       // mass reference\n  dealii::Vector<double> venergy_ref(L);  // energy (reference)\n\n  unsigned int nsteps = config[\"timesteps\"].size();\n  cout << \"__ERRORS__ (relative)\\n\";\n  cout << setw(15) << \"# i\" << setw(15) << \"t\" << setw(15) << \"l2_squared\" << setw(15)\n       << \"l2_m_squared\" << setw(15) << \"l2_u_squared (abs)\" << setw(15) << \"l2_e_squared\" << endl;\n\n  bool ref_restarted = false;  // restart toggle  (required to load new vertex2dof ordering)\n  bool inp_restarted = false;\n\n  if (vm.count(\"ignore-restarted\")) {\n    // set to true => will never enter restarted if(...)\n    ref_restarted = true;\n    inp_restarted = true;\n  }\n\n  auto xdmf_file = working_dir / bf::path(\"solution.xdmf\");\n  if (bf::exists(xdmf_file)) bf::remove(xdmf_file);\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    auto fname_inp = load_solution_vector(v_inp, str_input_path, str_h5loc_inp);\n    auto fname_ref = load_solution_vector(v_ref, str_ref_path, str_h5loc_ref);\n\n    // check if coefficient vectors are from restarted computation and require\n    // new vertex2dof mapping\n\n    if (!ref_restarted && bf::is_symlink(fname_ref)) {\n      string v2d_fname = ref_restart_config[\"v2d\"].as<string>();\n      load_permutation(ref_perm, str_ref_path, v2d_fname);\n      ref_restarted = true;\n      cout << \"# restart in REFRENCE detected\\n\";\n    }\n    if (!inp_restarted && bf::is_symlink(fname_inp)) {\n      string v2d_fname = inp_restart_config[\"v2d\"].as<string>();\n      load_permutation(input_perm, str_input_path, v2d_fname);\n      inp_restarted = true;\n      cout << \"# restart in INPUT detected\\n\";\n    }\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    // ----------------------------------------\n    // Compute errors\n    Errors errors;\n    auto errors_result =\n        errors.compute2(ref_dh, v_sol.data(), v_ref.data(), S, ref_grid_ptr->get_indexer());\n    Eigen::VectorXd vdiff = v_sol - v_ref;\n    // relative l2-error: |f-f_ref| / |f|\n    const double l2_error_sq = errors_result[0] / errors_result[1];\n\n    auto f1 = [&]() {\n      mass.compute(vmass.begin(), vdiff.data(), L);\n      std::for_each(vmass.begin(), vmass.end(), [](double v) { return std::abs(v); });\n    };\n\n    auto f2 = [&]() {\n      energy.compute(venergy.begin(), vdiff.data(), L);\n      std::for_each(venergy.begin(), venergy.end(), [](double v) { return std::abs(v); });\n    };\n\n    auto f3 = [&]() {\n      momentum.compute(vux.begin(), vuy.begin(), vdiff.data(), L);\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\n    auto mass_thread = thread(f1);\n    auto energy_thread = thread(f2);\n    auto momentum_thread = thread(f3);\n    //\n    mass_thread.join();\n    energy_thread.join();\n    momentum_thread.join();\n    // reference values (ie norms)\n    const double* vref_ptr = v_ref.data();\n    auto f4 = [&]() {\n      mass.compute(vm_ref.begin(), vref_ptr, L);\n      std::for_each(vm_ref.begin(), vm_ref.end(), [](double v) { return std::abs(v); });\n    };\n\n    auto f5 = [&]() {\n      energy.compute(venergy_ref.begin(), vref_ptr, L);\n      std::for_each(venergy_ref.begin(), venergy_ref.end(), [](double v) { return std::abs(v); });\n    };\n\n    auto f4_thread = thread(f4);\n    auto f5_thread = thread(f5);\n    f4_thread.join();\n    f5_thread.join();\n    double l2diff_m = l2norm(ref_dh, vmass) / l2norm(ref_dh, vm_ref);\n    double l2diff_u = l2norm(ref_dh, vux);\n    double l2diff_e = l2norm(ref_dh, venergy) / l2norm(ref_dh, venergy_ref);\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      // debug\n      dealii::Vector<double> vmass2(L);\n      dealii::Vector<double> vmass3(L);\n      mass.compute(vmass2.begin(), v_sol.data(), L);\n      mass.compute(vmass3.begin(), v_ref.data(), L);\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      data_out.add_data_vector(cell_wise_error, \"error2\");\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      // debug\n      data_out.add_data_vector(vmass2, \"mass_input\");\n      data_out.add_data_vector(vmass3, \"mass_ref\");\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\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      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  return 0;\n}\n", "meta": {"hexsha": "4cb7bed98c1d4263caa97fc092db380ad1f47b49", "size": 12925, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "applications/convergence_plots/main_relative_errors.cpp", "max_stars_repo_name": "simonpintarelli/2dBoltzmann", "max_stars_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "applications/convergence_plots/main_relative_errors.cpp", "max_issues_repo_name": "simonpintarelli/2dBoltzmann", "max_issues_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "applications/convergence_plots/main_relative_errors.cpp", "max_forks_repo_name": "simonpintarelli/2dBoltzmann", "max_forks_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.71875, "max_line_length": 99, "alphanum_fraction": 0.6520696325, "num_tokens": 3410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.4814229116181839}}
{"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 graph_metrics.hpp\n * @brief\n * @author Piotr Wygocki\n * @version 1.0\n * @date 2013-02-01\n */\n#ifndef PAAL_GRAPH_METRICS_HPP\n#define PAAL_GRAPH_METRICS_HPP\n\n#include \"basic_metrics.hpp\"\n\n#include <boost/graph/johnson_all_pairs_shortest.hpp>\n#include <boost/graph/floyd_warshall_shortest.hpp>\n#include <boost/graph/adjacency_matrix.hpp>\n\nnamespace paal {\nnamespace data_structures {\n\nnamespace graph_type {\nclass sparse_tag;\nclass dense_tag;\nclass large_tag;\n}\n\n/**\n * @brief traits for graph metric\n *\n * @tparam Graph\n */\ntemplate <typename Graph> struct graph_metric_traits {\n    //default graph_type\n    using graph_tag_type = graph_type::sparse_tag;\n};\n\n\n/// generic strategies of computing metric\ntemplate <typename graph_tag_type> struct graph_metric_filler_impl;\n\n/**\n * @brief specialization for sparse_tag graphs\n */\ntemplate <> struct graph_metric_filler_impl<graph_type::sparse_tag> {\n    /**\n     * @brief fill_matrix function\n     *\n     * @tparam Graph\n     * @tparam ResultMatrix\n     * @param g\n     * @param rm\n     */\n    template <typename Graph, typename ResultMatrix>\n    void fill_matrix(const Graph &g, ResultMatrix &rm) {\n        boost::johnson_all_pairs_shortest_paths(g, rm);\n    }\n};\n\n/**\n * @brief specialization strategies of computing metric for dense_tag graphs\n */\ntemplate <> struct graph_metric_filler_impl<graph_type::dense_tag> {\n    template <typename Graph, typename ResultMatrix>\n    /**\n     * @brief fill_matrixFunction\n     *\n     * @param g\n     * @param rm\n     */\n        void fill_matrix(const Graph &g, ResultMatrix &rm) {\n        boost::floyd_warshall_all_pairs_shortest_paths(g, rm);\n    }\n};\n\n/**\n * @class graph_metric\n * @brief Adopts boost graph as \\ref metric.\n *\n * @tparam Graph\n * @tparam DistanceType\n * @tparam GraphType\n */\n// GENERIC\n// GraphType could be sparse, dense, large ...\ntemplate <\n    typename Graph, typename DistanceType,\n    typename GraphType = typename graph_metric_traits<Graph>::graph_tag_type>\nstruct graph_metric : public array_metric<DistanceType>,\n                      public graph_metric_filler_impl<\n                          typename graph_metric_traits<Graph>::graph_tag_type> {\n    typedef array_metric<DistanceType> GMBase;\n    typedef graph_metric_filler_impl<\n        typename graph_metric_traits<Graph>::graph_tag_type> GMFBase;\n\n    /**\n     * @brief constructor\n     *\n     * @param g\n     */\n    graph_metric(const Graph &g) : GMBase(num_vertices(g)) {\n        GMFBase::fill_matrix(g, GMBase::m_matrix);\n    }\n};\n\n// TODO implement\n/// Specialization for large graphs\ntemplate <typename Graph, typename DistanceType>\nstruct graph_metric<Graph, DistanceType, graph_type::large_tag> {\n    /**\n     * @brief constructor\n     *\n     * @param g\n     */\n    graph_metric(const Graph &g) { assert(false); }\n};\n\n/// Specialization for adjacency_list\ntemplate <typename OutEdgeList, typename VertexList, typename Directed,\n          typename VertexProperties, typename EdgeProperties,\n          typename GraphProperties, typename EdgeList>\nstruct graph_metric_traits<\n    boost::adjacency_list<OutEdgeList, VertexList, Directed, VertexProperties,\n                          EdgeProperties, GraphProperties, EdgeList>> {\n    typedef graph_type::sparse_tag graph_tag_type;\n};\n\n/// Specialization for adjacency_matrix\ntemplate <typename Directed, typename VertexProperty, typename EdgeProperty,\n          typename GraphProperty, typename Allocator>\nstruct graph_metric_traits<boost::adjacency_matrix<\n    Directed, VertexProperty, EdgeProperty, GraphProperty, Allocator>> {\n    typedef graph_type::dense_tag graph_tag_type;\n};\n\n} //!data_structures\n} //!paal\n\n#endif // PAAL_GRAPH_METRICS_HPP\n", "meta": {"hexsha": "e40eab8b2cd1d8e70baa22f94405279d779c1954", "size": 4031, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/paal/data_structures/metric/graph_metrics.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/data_structures/metric/graph_metrics.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/data_structures/metric/graph_metrics.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": 27.8, "max_line_length": 80, "alphanum_fraction": 0.6824609278, "num_tokens": 901, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.647798211152541, "lm_q1q2_score": 0.4814229065649615}}
{"text": "#include <sparse.h>\n#include <sparse_fill.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n\nBOOST_AUTO_TEST_SUITE(SPARSE);\n\nBOOST_AUTO_TEST_CASE(product_crm_vector_test)\n{\n  typedef sparse::Block<1,1,float> block1x1_type;\n  typedef sparse::Block<4,1,float> block4x1_type;\n  typedef sparse::Block<3,1,float> block3x1_type;\n  typedef sparse::Block<3,4,float> block3x4_type;\n\n  // scalar blocks\n  sparse::CompressedRowMatrix< block1x1_type > sA(2,4,4);\n  sparse::Vector< block1x1_type > su(4);\n  sparse::CompressedVector< block1x1_type > csu(4,4);\n  block1x1_type result(0);\n  \n  sA(0,0)[0] = 1.0f;\n  sA(0,3)[0] = 2.0f;\n  sA(1,1)[0] = 3.0f;\n  sA(1,2)[0] = 4.0f;\n  su(0) = 5.0f;\n  su(1) = 6.0f;\n  su(2) = 7.0f;\n  su(3) = 8.0f;\n  sparse::row_prod(sA, su, result, 0);\n  BOOST_CHECK( result == 21.0f );\n  sparse::row_prod(sA, su, result, 1);\n  BOOST_CHECK( result == 67.0f ); // 46 + 21\n  csu(0) = 5.0f;\n  csu(1) = 6.0f;\n  csu(2) = 7.0f;\n  csu(3) = 8.0f;\n  result = 0;\n  sparse::row_prod(sA, csu, result, 0);\n  BOOST_CHECK( result == 21.0f );\n  sparse::row_prod(sA, csu, result, 1);\n  BOOST_CHECK( result == 67.0f ); // 46 + 21\n  \n  // block case\n  sparse::CompressedRowMatrix< block3x4_type > A(1,1,1);\n  sparse::Vector< block4x1_type > u(1);\n  sparse::CompressedVector< block4x1_type > cu(1,1);\n  block3x1_type block_result(0);\n  \n  sparse::fill(A(0,0));\n  sparse::fill(u(0));\n  sparse::row_prod(A,u,block_result,0);\n  BOOST_CHECK( block_result[0] == 14 );\n  BOOST_CHECK( block_result[1] == 38 );\n  BOOST_CHECK( block_result[2] == 62 );\n  sparse::fill(cu(0));\n  block_result.clear_data();\n  sparse::row_prod(A,cu,block_result,0);\n  BOOST_CHECK( block_result[0] == 14 );\n  BOOST_CHECK( block_result[1] == 38 );\n  BOOST_CHECK( block_result[2] == 62 );\n  \n  A.clear();\n  u.clear();\n  A.resize(2,4,4);\n  u.resize(4);\n  block_result.clear_data();\n\n  sparse::fill(A(0,0),1);\n  sparse::fill(A(0,3),2);\n  sparse::fill(A(1,1),3);\n  sparse::fill(A(1,2),4);\n  sparse::fill(u(0),1);\n  sparse::fill(u(1),2);\n  sparse::fill(u(2),3);\n  sparse::fill(u(3),4);\n  sparse::row_prod(A, u, block_result, 0);\n  BOOST_CHECK( block_result[0] == 112 );\n  BOOST_CHECK( block_result[1] == 240 );\n  BOOST_CHECK( block_result[2] == 368 );\n  cu.clear();\n  cu.resize(4,4);\n  sparse::fill(cu(0),1);\n  sparse::fill(cu(1),2);\n  sparse::fill(cu(2),3);\n  sparse::fill(cu(3),4);\n  block_result.clear_data();\n  sparse::row_prod(A, cu, block_result, 0);\n  BOOST_CHECK( block_result[0] == 112 );\n  BOOST_CHECK( block_result[1] == 240 );\n  BOOST_CHECK( block_result[2] == 368 );\n\n  block_result.clear_data();\n  sparse::row_prod(A, u, block_result, 1);\n  BOOST_CHECK( block_result[0] == 172 );\n  BOOST_CHECK( block_result[1] == 300 );\n  BOOST_CHECK( block_result[2] == 428 );\n  block_result.clear_data();\n  sparse::row_prod(A, cu, block_result, 1);\n  BOOST_CHECK( block_result[0] == 172 );\n  BOOST_CHECK( block_result[1] == 300 );\n  BOOST_CHECK( block_result[2] == 428 );\n\n  // test diagonal matrix\n  sparse::DiagonalMatrix< block3x4_type > DM(2,2,2);\n  sparse::fill(DM(0),1.0f);\n  sparse::fill(DM(1),1.0f);\n  u.resize(2);\n  sparse::fill(u(0),1.0f);\n  sparse::fill(u(1),1.0f);\n  block_result[0] = 0.0f;\n  block_result[1] = 0.0f;\n  block_result[2] = 0.0f;\n  sparse::row_prod(DM, u, block_result, 0);\n  BOOST_CHECK( block_result[0] == 30.0f );\n  BOOST_CHECK( block_result[1] == 70.0f );\n  BOOST_CHECK( block_result[2] == 110.0f );\n  block_result[0] = 0.0f;\n  block_result[1] = 0.0f;\n  block_result[2] = 0.0f;\n  sparse::row_prod(DM, u, block_result, 1);\n  BOOST_CHECK( block_result[0] == 30.0f );\n  BOOST_CHECK( block_result[1] == 70.0f );\n  BOOST_CHECK( block_result[2] == 110.0f );\n\n  // 2 column matrix\n  sparse::TwoColumnMatrix< block3x4_type > TCM(2, 4);\n  sparse::Vector< block3x1_type > v(2);\n  sparse::fill(TCM(0,0),1);\n  sparse::fill(TCM(0,1),2);\n  sparse::fill(TCM(1,1),3);\n  sparse::fill(TCM(1,3),4);\n  u.resize(4);\n  sparse::fill(u(0),1);\n  sparse::fill(u(1),2);\n  sparse::fill(u(2),3);\n  sparse::fill(u(3),4);\n  sparse::prod(TCM,u,v); // compute \"correct\" data\n  block_result[0] = 0.0f;\n  block_result[1] = 0.0f;\n  block_result[2] = 0.0f;\n  sparse::row_prod(TCM,u,block_result,0);\n  BOOST_CHECK( block_result == v(0) );\n  block_result[0] = 0.0f;\n  block_result[1] = 0.0f;\n  block_result[2] = 0.0f;\n  sparse::row_prod(TCM,u,block_result,1);\n  BOOST_CHECK( block_result == v(1) );\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "72db61524990c3acde845e3ec1edacd48ee7b484", "size": 4529, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/FOUNDATION/SPARSE/unit_tests/sparse_row_product/sparse_row_product.cpp", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-11-27T09:44:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-13T00:24:21.000Z", "max_issues_repo_path": "PROX/FOUNDATION/SPARSE/unit_tests/sparse_row_product/sparse_row_product.cpp", "max_issues_repo_name": "erleben/matchstick", "max_issues_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_issues_repo_licenses": ["MIT"], "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/FOUNDATION/SPARSE/unit_tests/sparse_row_product/sparse_row_product.cpp", "max_forks_repo_name": "erleben/matchstick", "max_forks_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_forks_repo_licenses": ["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.2193548387, "max_line_length": 57, "alphanum_fraction": 0.6467211305, "num_tokens": 1718, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.647798211152541, "lm_q1q2_score": 0.48142290656496145}}
{"text": "//==================================================================================================\n/*!\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#include <boost/simd/function/scalar/acscd.hpp>\n#include <scalar_test.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/minf.hpp>\n#include <boost/simd/constant/nan.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/mone.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/constant/mzero.hpp>\n#include <boost/simd/constant/two.hpp>\n\n\nSTF_CASE_TPL (\" acscd\",  STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::acscd;\n\n  using r_t = decltype(acscd(T()));\n\n  // return type conformity test\n  STF_TYPE_IS(r_t, T);\n\n  // specific values tests\n#ifndef BOOST_SIMD_NO_INVALIDS\n  STF_ULP_EQUAL(acscd(bs::Inf<T>()), T(0), 0.5);\n  STF_ULP_EQUAL(acscd(bs::Minf<T>()), T(0), 0.5);\n  STF_ULP_EQUAL(acscd(bs::Nan<T>()), bs::Nan<r_t>(), 0);\n  STF_ULP_EQUAL(acscd(bs::Zero<T>()), bs::Nan<r_t>(), 0);\n#endif\n  STF_ULP_EQUAL(acscd(-bs::Two<T>()), T(-30), 0.5);\n  STF_ULP_EQUAL(acscd(bs::Mone<T>()), T(-90), 0.5);\n  STF_ULP_EQUAL(acscd(bs::One<T>()),  T(90), 0.5);\n  STF_ULP_EQUAL(acscd(bs::Two<T>()),  T(30), 0.5);\n}\n", "meta": {"hexsha": "0349038b15984605d33aa7cbdc213422c02bcdff", "size": 1485, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/scalar/acscd.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": "test/function/scalar/acscd.cpp", "max_issues_repo_name": "remymuller/boost.simd", "max_issues_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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/function/scalar/acscd.cpp", "max_forks_repo_name": "remymuller/boost.simd", "max_forks_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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": 33.0, "max_line_length": 100, "alphanum_fraction": 0.5919191919, "num_tokens": 447, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.647798211152541, "lm_q1q2_score": 0.48142290656496145}}
{"text": "/*\r\n *  test_bonds.hpp\r\n *  bondgeek\r\n *\r\n *  Created by BART MOSLEY on 8/16/12.\r\n *  Copyright 2012 BG Research LLC. All rights reserved.\r\n *\r\n */\r\n\r\n#define BOOST_TEST_DYN_LINK\r\n\r\n#include <boost/test/unit_test.hpp>\r\n#include <bg/bondgeek.hpp>\r\n\r\nusing namespace QuantLib;\r\nusing namespace bondgeek;\r\nusing namespace boost::unit_test;\r\n\r\n#if defined(QL_ENABLE_SESSIONS)\r\nnamespace QuantLib {\r\n    Integer sessionId() { return 0; }\r\n}\r\n#endif\r\n\r\n// for arrays\r\n#define LENGTH(x) (sizeof(x)/sizeof(x[0]))\r\n\r\n\r\nstruct BondTests {\r\n\tDate todaysDate;\r\n    \r\n\tRateHelperCurve acurve;\r\n    boost::shared_ptr<PricingEngine> discEngine;\r\n\t\r\n\tBondTests() : \r\n\ttodaysDate(TARGET().adjust(Date(20, September, 2004)))\r\n\t{\r\n        BOOST_TEST_MESSAGE(\"\\nBond tests\");\r\n        string depotenors[] = {\"1W\", \"1M\", \"3M\", \"6M\", \"9M\", \"1y\"};\r\n        double depospots[] = {.055, .055, .055, .055, .055, .055};\r\n        string swaptenors[] = {\"2y\", \"3y\", \"5y\", \"10y\", \"15y\", \"20y\", \"30y\"};\r\n        double swapspots[] = {.055, .055, .055, .055, .055, .055, .055};\r\n        \r\n        acurve = RateHelperCurve(USDLiborCurve(\"3M\"));\r\n        acurve.update(depotenors, \r\n                      depospots, \r\n                      6,\r\n                      swaptenors,                                                                      \r\n                      swapspots,\r\n                      7,\r\n                      todaysDate);\r\n        \r\n        discEngine = \\\r\n        createPriceEngine<DiscountingBondEngine>(\r\n                                                 acurve.discountingTermStructure()\r\n                                                 );\r\n\t\t\r\n\t\tSettings::instance().evaluationDate() = todaysDate;\r\n\t}\r\n};\r\n\r\nBOOST_FIXTURE_TEST_SUITE( bondtest, BondTests )\r\n\r\nBOOST_AUTO_TEST_CASE( bulletbond_price_yield_consistency )\r\n{\r\n    BOOST_MESSAGE(\"Testing consistency of bond price-yield calcs...\");\r\n    Rate coupon[] = {.06, .05, .04};\r\n    Date maturity[] = {\r\n        Date(15, September,2012),\r\n        Date(1, November,2015),\r\n        Date(30, June,2011),\r\n        Date(28, February, 2017)\r\n    };\r\n    Date dated[] = {\r\n        Date(15, September,2004),\r\n        Date(1, May,2004),\r\n        Date(30, June,2004),\r\n        Date(1, February, 2004)\r\n    };\r\n    Calendar bondCalendar[] = {\r\n        UnitedStates(UnitedStates::GovernmentBond),\r\n        UnitedStates(UnitedStates::Settlement),\r\n        UnitedStates(UnitedStates::NYSE)\r\n    };\r\n    DayCounter bondDayCounter[] = {\r\n        ActualActual(ActualActual::Bond),\r\n        ActualActual(ActualActual::Actual365),\r\n        ActualActual(ActualActual::ISDA),\r\n        ActualActual(ActualActual::Euro),\r\n        Thirty360(Thirty360::BondBasis),\r\n        Thirty360(Thirty360::USA),\r\n        Thirty360(Thirty360::European),\r\n        Thirty360(Thirty360::EurobondBasis)\r\n    };\r\n    \r\n    Natural settlementDays = 3;\r\n    Frequency frequency = Semiannual;\r\n    \r\n    Real faceAmount = 100.0; // Notional amount\r\n    Real redemption = 100.0; // Amount paid on redemption\r\n    \r\n    BusinessDayConvention accrualConvention = Unadjusted;\r\n    BusinessDayConvention paymentConvention = Unadjusted;\r\n    \r\n    Real tolerance = 1.0e-5;\r\n    \r\n    double prc;\r\n    double yld;\r\n    for (int i=0; i < LENGTH(coupon); i++) {\r\n        for (int j=0; j < LENGTH(maturity); j++) {\r\n            for (int k=0; k < LENGTH(bondCalendar); k++) {\r\n                for (int l=0; l < LENGTH(bondDayCounter); l++) {\r\n                    BulletBond bnd(\r\n                                   coupon[i],\r\n                                   maturity[j],\r\n                                   dated[j],\r\n                                   bondCalendar[k],\r\n                                   settlementDays,\r\n                                   bondDayCounter[l],\r\n                                   frequency,\r\n                                   redemption,\r\n                                   faceAmount,\r\n                                   accrualConvention,\r\n                                   paymentConvention\r\n                                   );\r\n                    \r\n                    bnd.setEngine(acurve);\r\n                    \r\n                    prc = bnd.toPrice();\r\n                    yld = bnd.toYield(prc);\r\n                    \r\n                    BOOST_CHECK( abs(bnd.toPrice(yld) - prc) < tolerance );\r\n                }\r\n            }\r\n        }\r\n    }\r\n     \r\n    BOOST_TEST_MESSAGE(\"OK\");\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE( callbond_price_yield_consistency )\r\n{\r\n    BOOST_MESSAGE(\"Testing consistency of bond price-yield calcs...\");\r\n    Rate coupon = .05;\r\n    Date maturity(15, September,2016);\r\n    Date dated(15, September, 2004);\r\n    Date calldate[] = {\r\n        Date(15, September,2011),\r\n        Date(15, September,2012),\r\n        Date(15, September,2013)\r\n    };\r\n    Real callprc[] = {100., 101., 102.};\r\n    Date pardate[] = {\r\n        maturity,\r\n        Date(15, September,2013),\r\n        Date(15, September,2015)\r\n    };\r\n    \r\n    Calendar bondCalendar = UnitedStates(UnitedStates::Settlement);\r\n    DayCounter bondDayCounter = Thirty360(Thirty360::BondBasis);\r\n    \r\n    Natural settlementDays = 3;\r\n    Frequency frequency = Semiannual;\r\n    \r\n    Real faceAmount = 100.0; // Notional amount\r\n    Real redemption = 100.0; // Amount paid on redemption\r\n    \r\n    BusinessDayConvention accrualConvention = Unadjusted;\r\n    BusinessDayConvention paymentConvention = Unadjusted;\r\n    \r\n    Real tolerance = 1.0e-5;\r\n    \r\n    double prc;\r\n    double yld;\r\n    for (int i=0; i < LENGTH(calldate); i++) {\r\n\r\n        CallBond bnd(\r\n                     coupon,\r\n                     maturity,\r\n                     calldate[i],\r\n                     callprc[i],\r\n                     pardate[i],\r\n                     dated,\r\n                     bondCalendar,\r\n                     settlementDays,\r\n                     bondDayCounter,\r\n                     frequency,\r\n                     Annual,\r\n                     redemption,\r\n                     faceAmount,\r\n                     accrualConvention,\r\n                     paymentConvention\r\n                     );\r\n        \r\n        bnd.setEngine(acurve);\r\n        \r\n        prc = bnd.toPrice();\r\n        yld = bnd.toYield(prc);\r\n        \r\n        BOOST_CHECK( abs(bnd.toPrice(yld) - prc) < tolerance );\r\n    }\r\n    \r\n    BOOST_TEST_MESSAGE(\"OK\");\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE( bond_value_sinker_consistency )\r\n{\r\n    BOOST_MESSAGE(\"Testing consistency of sinking fund bond calcs...\");\r\n    Real coupon = .06;\r\n    Date maturity(15, September,2012);\r\n    Date maturity1(15, September, 2011);\r\n    Date maturity0(15, September, 2010);\r\n    \r\n    Date dated(16,September,2004);\r\n    \r\n    Natural settlementDays = 3;  \r\n    Frequency frequency = Semiannual;\r\n    \r\n    Calendar bondCalendar = UnitedStates(UnitedStates::GovernmentBond);\r\n    DayCounter bondDayCounter = ActualActual(ActualActual::Bond);\r\n    \r\n    Real faceAmount = 100.0; // Notional amount\r\n    Real redemption = 100.0; // Amount paid on redemption\r\n    \r\n    BusinessDayConvention accrualConvention = Unadjusted;\r\n    BusinessDayConvention paymentConvention = Unadjusted;\r\n\r\n    SinkingFundBond bnd(coupon,\r\n                        maturity,\r\n                        std::vector<Real>(1, faceAmount),\r\n                        Annual,\r\n                        dated,\r\n                        bondCalendar,\r\n                        settlementDays,\r\n                        bondDayCounter,\r\n                        frequency,\r\n                        redemption,\r\n                        faceAmount,\r\n                        accrualConvention,\r\n                        paymentConvention\r\n                        );\r\n    \r\n    SinkingFundBond bnd0(coupon,\r\n                         maturity0,\r\n                         std::vector<Real>(1, faceAmount),\r\n                         Annual,\r\n                         dated,\r\n                         bondCalendar,\r\n                         settlementDays,\r\n                         bondDayCounter,\r\n                         frequency,\r\n                         redemption,\r\n                         faceAmount,\r\n                         accrualConvention,\r\n                         paymentConvention\r\n                         );\r\n    \r\n    SinkingFundBond bnd1(coupon,\r\n                         maturity1,\r\n                         std::vector<Real>(1, faceAmount),\r\n                         Annual,\r\n                         dated,\r\n                         bondCalendar,\r\n                         settlementDays,\r\n                         bondDayCounter,\r\n                         frequency,\r\n                         redemption,\r\n                         faceAmount,\r\n                         accrualConvention,\r\n                         paymentConvention\r\n                         );\r\n    \r\n    /* Sinkfing fund amortization:\r\n     \r\n     notionals start at par on the dated date and end at zero on maturity.\r\n     redemptions are the prices redemption prices (pct of par, e.g. 101.)\r\n     \r\n     */\r\n    \r\n    double sf_sch[] = {\r\n        40000, 40000, 40000\r\n    };\r\n    int sf_num = 3;\r\n    Frequency sf_freq = Annual;\r\n    \r\n    std::vector<double> sf_bal;\r\n    sf_bal.assign(sf_sch, sf_sch+sf_num);\r\n    \r\n    SinkingFundBond bnd2(coupon,\r\n                         maturity,\r\n                         sf_bal,\r\n                         sf_freq,\r\n                         dated,\r\n                         bondCalendar,\r\n                         settlementDays,\r\n                         bondDayCounter,\r\n                         frequency,\r\n                         redemption,\r\n                         faceAmount,\r\n                         accrualConvention,\r\n                         paymentConvention\r\n                         ); \r\n    \r\n    bnd.setEngine(acurve);\r\n\r\n    bnd0.setPricingEngine(discEngine);\r\n    bnd1.setPricingEngine(discEngine);\r\n    bnd2.setPricingEngine(discEngine);\r\n    \r\n    double prc = bnd.toPrice();\r\n\r\n    double prc0 = bnd0.cleanPrice();\r\n    double prc1 = bnd1.cleanPrice();\r\n    double prc2 = bnd2.cleanPrice();\r\n    \r\n    double avgpx = (prc0+prc1+prc)/3.;\r\n    \r\n    BOOST_CHECK( abs(prc2-avgpx) < .0001 );\t \r\n    BOOST_TEST_MESSAGE(\"OK\");\r\n}\r\n\r\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "2b99283a265735653fd7aee8284f0117ce2d0e17", "size": 10225, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "tests/test_bonds.hpp", "max_stars_repo_name": "bondgeek/pybg", "max_stars_repo_head_hexsha": "046a25074b78409c6d29302177aeac581ade90d1", "max_stars_repo_licenses": ["Unlicense", "MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-03-14T05:39:15.000Z", "max_stars_repo_stars_event_max_datetime": "2017-03-14T05:39:15.000Z", "max_issues_repo_path": "tests/test_bonds.hpp", "max_issues_repo_name": "bondgeek/pybg", "max_issues_repo_head_hexsha": "046a25074b78409c6d29302177aeac581ade90d1", "max_issues_repo_licenses": ["Unlicense", "MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/test_bonds.hpp", "max_forks_repo_name": "bondgeek/pybg", "max_forks_repo_head_hexsha": "046a25074b78409c6d29302177aeac581ade90d1", "max_forks_repo_licenses": ["Unlicense", "MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.7546583851, "max_line_length": 104, "alphanum_fraction": 0.4750122249, "num_tokens": 2102, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.6477982111525409, "lm_q1q2_score": 0.48142290656496134}}
{"text": "//==================================================================================================\n/*!\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#include <boost/simd/function/ldexp.hpp>\n#include <boost/simd/function/std.hpp>\n#include <scalar_test.hpp>\n#include <boost/simd/detail/dispatch/meta/as_integer.hpp>\n#include <boost/simd/constant/inf.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/zero.hpp>\n#include <boost/simd/constant/two.hpp>\n#include <boost/simd/constant/four.hpp>\n#include <boost/simd/constant/halfeps.hpp>\n#include <boost/simd/constant/three.hpp>\n#include <boost/simd/detail/constant/maxexponent.hpp>\n#include <boost/simd/detail/constant/limitexponent.hpp>\n#include <boost/simd/detail/constant/minexponent.hpp>\n#include <boost/simd/constant/smallestposval.hpp>\n#include <boost/simd/function/scalar/dec.hpp>\n\n\nSTF_CASE_TPL(\"ldexp std\", STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::ldexp;\n\n  using iT = bd::as_integer_t<T>;\n  using r_t = decltype(ldexp(T(), iT()));\n\n  // return type conformity test\n  STF_TYPE_IS(r_t, T);\n\n#ifndef BOOST_SIMD_NO_INVALIDS\n  STF_EQUAL(bs::std_(ldexp)(bs::Inf<T>(),  2), bs::Inf<r_t>());\n  STF_EQUAL(bs::std_(ldexp)(bs::Minf<T>(), 2), bs::Minf<r_t>());\n  STF_IEEE_EQUAL(bs::std_(ldexp)(bs::Nan<T>(),  2), bs::Nan<r_t>());\n#endif\n  STF_EQUAL(bs::std_(ldexp)(bs::Mone<T>(), 2), -bs::Four<r_t>());\n  STF_EQUAL(bs::std_(ldexp)(bs::One<T>(),  2), bs::Four<r_t>());\n  STF_EQUAL(bs::std_(ldexp)(bs::Zero<T>(), 2), bs::Zero<r_t>());\n  STF_EQUAL(bs::std_(ldexp)(bs::One <T>(), bs::Minexponent<T>()), bs::Smallestposval<r_t>());\n  STF_EQUAL(bs::std_(ldexp)(bs::One<T>()-bs::Halfeps<T>(),  bs::Maxexponent<T>()), bs::Valmax<T>()/2);\n  STF_EQUAL(bs::std_(ldexp)(bs::One<T>()-bs::Halfeps<T>(),  bs::Limitexponent<T>()), bs::Valmax<T>());\n#ifndef BOOST_SIMD_NO_DENORMALS\n  using bs::dec;\n  STF_EQUAL(bs::std_(ldexp)(bs::One <T>(), dec(bs::Minexponent<T>())), bs::Smallestposval<T>()/2);\n  STF_EQUAL(bs::std_(ldexp)(bs::Two <T>(), dec(bs::Minexponent<T>())), bs::Smallestposval<T>());\n  STF_EQUAL(bs::std_(ldexp)(bs::Two <T>(), dec(bs::Minexponent<T>()-1)), bs::Smallestposval<T>()/2);\n  STF_EQUAL(bs::std_(ldexp)(bs::One <T>(), bs::Minexponent<T>()-5), bs::Smallestposval<T>()/32);\n#endif\n}\n", "meta": {"hexsha": "a3a1ddd9d65345a5018407494fa45eb253f57288", "size": 2656, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/scalar/ldexp.std.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": "test/function/scalar/ldexp.std.cpp", "max_issues_repo_name": "remymuller/boost.simd", "max_issues_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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/function/scalar/ldexp.std.cpp", "max_forks_repo_name": "remymuller/boost.simd", "max_forks_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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": 42.8387096774, "max_line_length": 102, "alphanum_fraction": 0.6332831325, "num_tokens": 798, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.481422901511739}}
{"text": "#pragma once\n\n#include <mtao/types.hpp>\n#include <Eigen/Geometry>\n#include <mtao/geometry/grid/staggered_grid.hpp>\n#include <mandoline/construction/cutdata.hpp>\n\nnamespace mandoline::tools {\nclass SliceGenerator : public mtao::geometry::grid::StaggeredGrid<double, 3> {\n  public:\n    using Base = mtao::geometry::grid::StaggeredGrid<double, 3>;\n    SliceGenerator() {}\n    SliceGenerator(const mtao::ColVecs3d &V, const mtao::ColVecs3i &F);\n    std::tuple<mtao::ColVecs3d, mtao::ColVecs3i> slice(const mtao::Vec3d &origin, const mtao::Vec3d &direction);\n    static Eigen::Affine3d get_transform(const mtao::Vec3d &origin, const mtao::Vec3d &direction);\n    std::tuple<mtao::ColVecs3d, mtao::ColVecs3i> slice(const Eigen::Affine3d &t);\n    void set_vertices(const mtao::ColVecs3d &V);\n    Eigen::SparseMatrix<double> barycentric_map() const;\n\n  private:\n    void update_embedding(const mtao::ColVecs3d &V);\n    mtao::ColVecs3d V;\n    construction::CutData<3> data;\n};\n\ntemplate<typename... Args>\nstd::tuple<mtao::ColVecs3d, mtao::ColVecs3i> slice(const mtao::ColVecs3d &V, const mtao::ColVecs3i &F, Args &&... args) {\n    SliceGenerator sg(V, F);\n    return sg.slice(std::forward<Args>(args)...);\n}\n\n\n}// namespace mandoline::tools\n", "meta": {"hexsha": "2f189e3b0ad21f670aaa77a6da660cf546d74c57", "size": 1231, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mandoline/tools/planar_slicer.hpp", "max_stars_repo_name": "mtao/mandoline", "max_stars_repo_head_hexsha": "79438c5b210a2ca4b9f72cbfd2879a9ae6a665da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 54.0, "max_stars_repo_stars_event_min_datetime": "2019-11-12T11:07:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T11:09:19.000Z", "max_issues_repo_path": "include/mandoline/tools/planar_slicer.hpp", "max_issues_repo_name": "mtao/mandoline", "max_issues_repo_head_hexsha": "79438c5b210a2ca4b9f72cbfd2879a9ae6a665da", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-12-17T01:49:44.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-29T19:46:36.000Z", "max_forks_repo_path": "include/mandoline/tools/planar_slicer.hpp", "max_forks_repo_name": "mtao/mandoline", "max_forks_repo_head_hexsha": "79438c5b210a2ca4b9f72cbfd2879a9ae6a665da", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2019-11-29T02:30:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-19T06:15:22.000Z", "avg_line_length": 36.2058823529, "max_line_length": 121, "alphanum_fraction": 0.716490658, "num_tokens": 406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624890918021, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.48140619200834334}}
{"text": "/*\n *  transfer.hpp\n *\n *\n *  Created by Andrea Bedini on 13/Jul/2009.\n *  Copyright (c) 2009-2014, Andrea Bedini <andrea.bedini@gmail.com>.\n *\n *  Distributed under the terms of the Modified BSD License.\n *  The full license is in the file COPYING, distributed as part of\n *  this software.\n *\n */\n\n#ifndef TRANSFER_HPP\n#define TRANSFER_HPP\n\n#include \"tree_decomposition/tree_decomposition.hpp\"\n#include <boost/range/algorithm/set_algorithm.hpp>\n\nnamespace transfer {\n  using tree_decomposition::vertex_list;\n  using tree_decomposition::bag_ptr;\n\n  template<class Operators>\n  typename Operators::table_type\n  recurse(const Operators& op, bag_ptr b)\n  {\n    // create a new table containing only the empty state\n    auto const n = b->vertices.size();\n    auto table = op.empty_state(n);\n\n    // iterates over children\n    for (auto b_sib : b->children) {\n      // recurse\n      auto table_sib = recurse(op, b_sib);\n\n      // diffe contains the vertices in b_sib which are not in b (the parent bag)\n      std::vector<unsigned int> diffe;\n      boost::set_difference(b_sib->vertices, b->vertices, std::back_inserter(diffe));\n\n      // delete each vertex not present in the parent bag\n\n      // we need to make a copy first because\n      // 1) we need to keep the indices consistent while removing vertices\n      // 2) we don't want to destroy the tree decomposition\n      vertex_list b_sib_left_over(b_sib->vertices);\n      for (auto v : diffe) {\n        table_sib = op.delete_operator(b_sib_left_over.index(v), table_sib);\n        b_sib_left_over.remove(v);\n      }\n\n      // create b_sib to b bag mapping\n      auto const A_size = b_sib_left_over.size();\n      std::vector<unsigned int> A_to_B(A_size);\n      for (unsigned int i = 0; i < A_size; ++i)\n        A_to_B[i] = b->vertices.index(b_sib_left_over.at(i));\n\n      table = op.table_fusion(A_to_B, table_sib, table);\n    }\n\n    // apply the join operator for each edge in the bag\n    for (auto e : b->edges) {\n      table = op.join_operator(b->vertices.index(e.first),\n        b->vertices.index(e.second), table);\n    }\n    return table;\n  }\n\n  template<class Operators>\n  typename Operators::weight_type\n  transfer(const Operators& op, bag_ptr b)\n  {\n    auto table = recurse(op, b);\n\n    // we need to make a copy first because\n    // 1) we need to keep the indices consistent while removing vertices\n    // 2) we don't want to destroy the tree decomposition\n    vertex_list v_to_remove(b->vertices);\n    for (auto v : b->vertices) {\n      table = op.delete_operator(v_to_remove.index(v), table);\n      v_to_remove.remove(v);\n    }\n    assert(table.size() == 1);\n    return table.begin()->second;\n  }\n}\n\n#endif\n", "meta": {"hexsha": "b4a4cebccbdedd3f007922ee0f7feab91942d81f", "size": 2668, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/transfer.hpp", "max_stars_repo_name": "andreabedini/tutte", "max_stars_repo_head_hexsha": "6bd620e06f6ac27fafc75898a3b12e9995a5e964", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-01-29T23:04:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-04T13:33:46.000Z", "max_issues_repo_path": "include/transfer.hpp", "max_issues_repo_name": "andreabedini/tutte", "max_issues_repo_head_hexsha": "6bd620e06f6ac27fafc75898a3b12e9995a5e964", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/transfer.hpp", "max_forks_repo_name": "andreabedini/tutte", "max_forks_repo_head_hexsha": "6bd620e06f6ac27fafc75898a3b12e9995a5e964", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9775280899, "max_line_length": 85, "alphanum_fraction": 0.6697901049, "num_tokens": 681, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.782662489091802, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4814061920083433}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_EULER_FUNCTIONS_SCALAR_STIRLING_HPP_INCLUDED\n#define NT2_EULER_FUNCTIONS_SCALAR_STIRLING_HPP_INCLUDED\n\n#include <nt2/euler/functions/stirling.hpp>\n#include <nt2/euler/functions/details/stirling_kernel.hpp>\n#include <nt2/include/constants/half.hpp>\n#include <nt2/include/constants/inf.hpp>\n#include <nt2/include/constants/one.hpp>\n#include <nt2/include/constants/sqrt_2pi.hpp>\n#include <nt2/include/constants/stirlinglargelim.hpp>\n#include <nt2/include/constants/stirlingsplitlim.hpp>\n#include <nt2/include/functions/scalar/exp.hpp>\n#include <nt2/include/functions/scalar/fma.hpp>\n#include <nt2/include/functions/scalar/is_eqz.hpp>\n#include <nt2/include/functions/scalar/pow.hpp>\n#include <nt2/include/functions/scalar/rec.hpp>\n\n#include <boost/simd/sdk/config.hpp>\n\n#ifndef BOOST_SIMD_NO_INVALIDS\n#include <nt2/include/functions/scalar/is_nan.hpp>\n#endif\n\nnamespace nt2 { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT  ( stirling_, tag::cpu_\n                            , (A0)\n                            , (scalar_< floating_<A0> >)\n                            )\n  {\n    typedef A0 result_type;\n    NT2_FUNCTOR_CALL(1)\n    {\n      #ifndef BOOST_SIMD_NO_INVALIDS\n      if (nt2::is_nan(a0)) return a0;\n      #endif\n      if (a0 > nt2::Stirlinglargelim<A0>()) return nt2::Inf<A0>();\n      A0 w = nt2::rec(a0);\n      w = fma(w,details::stirling_kernel<A0>::stirling1(w), nt2::One<A0>());\n      A0 y = nt2::exp(-a0);\n      if(nt2::is_eqz(y)) return nt2::Inf<A0>();\n      A0 z =  a0 - nt2::Half<A0>();\n      if( a0 >= nt2::Stirlingsplitlim<A0>() )\n      { /* Avoid overflow in pow() */\n        const A0 v = nt2::pow(a0,z*Half<A0>());\n        y *= v;\n        y *= v;\n      }\n      else\n      {\n        y *= nt2::pow( a0, z );\n      }\n      y *= nt2::Sqrt_2pi<A0>()*w;\n      return y;\n    }\n  };\n} }\n\n#endif\n", "meta": {"hexsha": "f9f4ed5b13534e5c61572b22089c6ae974e36ef4", "size": 2314, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/euler/include/nt2/euler/functions/scalar/stirling.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/core/euler/include/nt2/euler/functions/scalar/stirling.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/core/euler/include/nt2/euler/functions/scalar/stirling.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 34.0294117647, "max_line_length": 80, "alphanum_fraction": 0.5842696629, "num_tokens": 615, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.48140618577205085}}
{"text": "//\n//  stochasticTools.cpp\n//\n//\n//  Created by Jose V. Alcala Burgos on 7/30/13.\n//  Copyright [2013] Jose V. Alcala Burgos\n//\n\n#include \"base/stochasticTools.h\"\n\n// System\n#include <armadillo>\n\n#include <iostream>\n#include <random>\n\nstochasticGradient::stochasticGradient(\n    const mat& __H,\n    const mat& __Sigma,\n    const mat& __alpha_optimal): _M_H(__H),\n                                 _M_Sigma(__Sigma),\n                                 _M_alpha_optimal(__alpha_optimal) {\n        /**\n         *Check that dimensions are consistent\n         */\n        _M_par_dim = _M_alpha_optimal.n_cols;\n        _GLIBCXX_DEBUG_ASSERT(1 == _M_alpha_optimal.n_rows);\n        _GLIBCXX_DEBUG_ASSERT(_M_H.n_cols == _M_alpha_optimal.n_cols);\n        _GLIBCXX_DEBUG_ASSERT(_M_H.n_rows == _M_alpha_optimal.n_cols);\n        _GLIBCXX_DEBUG_ASSERT(_M_Sigma.n_cols == _M_alpha_optimal.n_cols);\n        _GLIBCXX_DEBUG_ASSERT(_M_Sigma.n_rows == _M_alpha_optimal.n_cols);\n    }\n", "meta": {"hexsha": "abef1ee492bf91f55e8bfa1683b0207641e27a71", "size": 960, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/stochasticTools.cpp", "max_stars_repo_name": "vidalalcala/sopt-ols", "max_stars_repo_head_hexsha": "ffc41ccdd0c523c39eebbada894c83533f92338d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/stochasticTools.cpp", "max_issues_repo_name": "vidalalcala/sopt-ols", "max_issues_repo_head_hexsha": "ffc41ccdd0c523c39eebbada894c83533f92338d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/stochasticTools.cpp", "max_forks_repo_name": "vidalalcala/sopt-ols", "max_forks_repo_head_hexsha": "ffc41ccdd0c523c39eebbada894c83533f92338d", "max_forks_repo_licenses": ["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.0909090909, "max_line_length": 74, "alphanum_fraction": 0.65, "num_tokens": 258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.48140618577205085}}
{"text": "////////////////////////////////////////////\r\n// File: doosabin_regression.cpp          //\r\n// Copyright Richard Stebbing 2015.       //\r\n// Distributed under the MIT License.     //\r\n// (See accompany file LICENSE or copy at //\r\n//  http://opensource.org/licenses/MIT)   //\r\n////////////////////////////////////////////\r\n\r\n// Includes\r\n#include <algorithm>\r\n#include <cstdio>\r\n#include <fstream>\r\n#include <iostream>\r\n#include <memory>\r\n#include <string>\r\n#include <sstream>\r\n#include <utility>\r\n\r\n#include \"ceres/ceres.h\"\r\n#include \"gflags/gflags.h\"\r\n#include \"glog/logging.h\"\r\n\r\n#include <Eigen/Dense>\r\n\r\n#include \"rapidjson/document.h\"\r\n#include \"rapidjson/filewritestream.h\"\r\n#include \"rapidjson/prettywriter.h\"\r\n\r\n#include \"Ceres/composed_cost_function.h\"\r\n#include \"Math/linalg.h\"\r\n\r\n#include \"doosabin.h\"\r\n\r\n#include \"ceres_surface.h\"\r\n#include \"surface.h\"\r\n\r\n// DooSabinSurface\r\nclass DooSabinSurface : public Surface {\r\n public:\r\n  typedef doosabin::Surface<double> Surface;\r\n\r\n  explicit DooSabinSurface(const Surface* surface)\r\n    : surface_(surface)\r\n  {}\r\n\r\n  #define EVALUATE(M, SIZE) \\\r\n  virtual void M(double* r, const int p, const double* u, \\\r\n                 const double* const* X) const { \\\r\n    const Eigen::Map<const Eigen::Vector2d> _u(u); \\\r\n    const linalg::MatrixOfColumnPointers<double> _X( \\\r\n      X, 3, surface_->patch_vertex_indices(p).size()); \\\r\n    Eigen::Map<Eigen::VectorXd> _r(r, SIZE); \\\r\n    surface_->M(p, _u, _X, &_r); \\\r\n  }\r\n  #define SIZE_JACOBIAN_X (3 * 3 * surface_->patch_vertex_indices(p).size())\r\n  EVALUATE(M, 3);\r\n  EVALUATE(Mu, 3);\r\n  EVALUATE(Mv, 3);\r\n  EVALUATE(Muu, 3);\r\n  EVALUATE(Muv, 3);\r\n  EVALUATE(Mvv, 3);\r\n  EVALUATE(Mx, SIZE_JACOBIAN_X);\r\n  EVALUATE(Mux, SIZE_JACOBIAN_X);\r\n  EVALUATE(Mvx, SIZE_JACOBIAN_X);\r\n  #undef EVALUATE\r\n  #undef SIZE_JACOBIAN_X\r\n\r\n  virtual int number_of_vertices() const {\r\n    return surface_->number_of_vertices();\r\n  }\r\n\r\n  virtual int number_of_faces() const {\r\n    return surface_->number_of_faces();\r\n  }\r\n\r\n  virtual int number_of_patches() const {\r\n    return surface_->number_of_patches();\r\n  }\r\n\r\n  virtual const std::vector<int>& patch_vertex_indices(const int p) const {\r\n    return surface_->patch_vertex_indices(p);\r\n  }\r\n\r\n  virtual const std::vector<int>& adjacent_patch_indices(const int p) const {\r\n    return surface_->adjacent_patch_indices(p);\r\n  }\r\n\r\n private:\r\n  const Surface* surface_;\r\n};\r\n\r\n// PositionErrorFunctor\r\nclass PositionErrorFunctor {\r\n public:\r\n  template <typename M>\r\n  PositionErrorFunctor(const M& m0, const double& sqrt_w = 1.0)\r\n    : m0_(m0), sqrt_w_(sqrt_w)\r\n  {}\r\n\r\n  template <typename T>\r\n  bool operator()(const T* m, T* e) const {\r\n    e[0] = T(sqrt_w_) * (T(m0_[0]) - m[0]);\r\n    e[1] = T(sqrt_w_) * (T(m0_[1]) - m[1]);\r\n    e[2] = T(sqrt_w_) * (T(m0_[2]) - m[2]);\r\n    return true;\r\n  }\r\n\r\n private:\r\n  Eigen::Vector3d m0_;\r\n  const double sqrt_w_;\r\n};\r\n\r\n// PairwiseErrorFunctor\r\nclass PairwiseErrorFunctor {\r\n public:\r\n  PairwiseErrorFunctor(const double& sqrt_w = 1.0)\r\n    : sqrt_w_(sqrt_w)\r\n  {}\r\n\r\n  template <typename T>\r\n  bool operator()(const T* x0, const T* x1, T* e) const {\r\n    e[0] = T(sqrt_w_) * (x1[0] - x0[0]);\r\n    e[1] = T(sqrt_w_) * (x1[1] - x0[1]);\r\n    e[2] = T(sqrt_w_) * (x1[2] - x0[2]);\r\n    return true;\r\n  }\r\n\r\n private:\r\n  const double sqrt_w_;\r\n};\r\n\r\n// ReadFileIntoDocument\r\nbool ReadFileIntoDocument(const std::string& input_path,\r\n                          rapidjson::Document* document) {\r\n  std::ifstream input(input_path, std::ios::binary);\r\n  if (!input) {\r\n    LOG(ERROR) << \"File \\\"\" << input_path << \"\\\" not found.\";\r\n    return false;\r\n  }\r\n\r\n  std::stringstream input_ss;\r\n  input_ss << input.rdbuf();\r\n  if (document->Parse<0>(input_ss.str().c_str()).HasParseError()) {\r\n    LOG(ERROR) << \"Failed to parse input.\";\r\n    return false;\r\n  }\r\n\r\n  return true;\r\n}\r\n\r\n// LoadProblemFromFile\r\nbool LoadProblemFromFile(const std::string& input_path,\r\n                         Eigen::MatrixXd* Y,\r\n                         std::vector<int>* raw_face_array,\r\n                         Eigen::MatrixXd* X,\r\n                         Eigen::VectorXi* p,\r\n                         Eigen::MatrixXd* U) {\r\n  rapidjson::Document document;\r\n  if (!ReadFileIntoDocument(input_path, &document)) {\r\n    return false;\r\n  }\r\n\r\n  #define LOAD_MATRIXD(K, DIM) { \\\r\n    CHECK(document.HasMember(#K)); \\\r\n    auto& v = document[#K]; \\\r\n    CHECK(v.IsArray()); \\\r\n    K->resize(DIM, v.Size() / DIM); \\\r\n    for (rapidjson::SizeType i = 0; i < v.Size(); ++i) { \\\r\n      CHECK(v[i].IsDouble()); \\\r\n      (*K)(i % DIM, i / DIM) = v[i].GetDouble(); \\\r\n    } \\\r\n  }\r\n  #define LOAD_VECTORI(K) { \\\r\n    CHECK(document.HasMember(#K)); \\\r\n    auto& v = document[#K]; \\\r\n    CHECK(v.IsArray()); \\\r\n    K->resize(v.Size()); \\\r\n    for (rapidjson::SizeType i = 0; i < v.Size(); ++i) { \\\r\n      CHECK(v[i].IsInt()); \\\r\n      (*K)[i] = v[i].GetInt(); \\\r\n    } \\\r\n  }\r\n\r\n  LOAD_MATRIXD(Y, 3);\r\n  LOAD_VECTORI(raw_face_array);\r\n  LOAD_MATRIXD(X, 3);\r\n  LOAD_VECTORI(p);\r\n  LOAD_MATRIXD(U, 2);\r\n\r\n  #undef LOAD_MATRIXD\r\n  #undef LOAD_VECTORI\r\n\r\n  return true;\r\n}\r\n\r\n// UpdateProblemToFile\r\nbool UpdateProblemToFile(const std::string& input_path,\r\n                         const std::string& output_path,\r\n                         const Eigen::MatrixXd& X,\r\n                         const Eigen::VectorXi& p,\r\n                         const Eigen::MatrixXd& U) {\r\n\r\n  rapidjson::Document document;\r\n  if (!ReadFileIntoDocument(input_path, &document)) {\r\n    return false;\r\n  }\r\n\r\n  #define SAVE_MATRIXD(K) { \\\r\n    CHECK(document.HasMember(#K)); \\\r\n    auto& v = document[#K]; \\\r\n    CHECK(v.IsArray()); \\\r\n    CHECK_EQ(v.Size(), K.rows() * K.cols()); \\\r\n    for (rapidjson::SizeType i = 0; i < v.Size(); ++i) { \\\r\n      CHECK(v[i].IsDouble()); \\\r\n      v[i] = K(i % K.rows(), i / K.rows()); \\\r\n    } \\\r\n  }\r\n  #define SAVE_VECTORI(K) { \\\r\n    CHECK(document.HasMember(#K)); \\\r\n    auto& v = document[#K]; \\\r\n    CHECK(v.IsArray()); \\\r\n    CHECK_EQ(v.Size(), K.size()); \\\r\n    for (rapidjson::SizeType i = 0; i < v.Size(); ++i) { \\\r\n      CHECK(v[i].IsInt()); \\\r\n      v[i] = K[i]; \\\r\n    } \\\r\n  }\r\n\r\n  SAVE_MATRIXD(X);\r\n  SAVE_VECTORI(p);\r\n  SAVE_MATRIXD(U);\r\n\r\n  #undef SAVE_MATRIXD\r\n  #undef SAVE_VECTORI\r\n\r\n  // Use `fopen` instead of streams for `rapidjson::FileWriteStream`.\r\n  FILE* output_handle = fopen(output_path.c_str(), \"wb\");\r\n  if (output_handle == nullptr) {\r\n    LOG(ERROR) << \"Unable to open \\\"\" << output_path << \"\\\"\";\r\n  }\r\n\r\n  char write_buffer[512];\r\n  rapidjson::FileWriteStream output(output_handle,\r\n                                    write_buffer,\r\n                                    sizeof(write_buffer));\r\n  rapidjson::PrettyWriter<rapidjson::FileWriteStream> writer(output);\r\n  document.Accept(writer);\r\n\r\n  fclose(output_handle);\r\n\r\n  return true;\r\n}\r\n\r\n// main\r\nDEFINE_int32(max_num_iterations, 1000, \"Maximum number of iterations.\");\r\nDEFINE_double(function_tolerance, 0.0,\r\n  \"Minimizer terminates when \"\r\n  \"(new_cost - old_cost) < function_tolerance * old_cost\");\r\nDEFINE_double(gradient_tolerance, 0.0,\r\n  \"Minimizer terminates when \"\r\n  \"max_i |gradient_i| < gradient_tolerance * max_i|initial_gradient_i|\");\r\nDEFINE_double(parameter_tolerance, 0.0,\r\n  \"Minimizer terminates when \"\r\n  \"|step|_2 <= parameter_tolerance * ( |x|_2 +  parameter_tolerance)\");\r\nDEFINE_double(min_trust_region_radius, 1e-9,\r\n  \"Minimizer terminates when the trust region radius becomes smaller than \"\r\n  \"this value\");\r\n\r\nDEFINE_int32(num_threads, 1,\r\n  \"Number of threads to use for Jacobian evaluation.\");\r\nDEFINE_int32(num_linear_solver_threads, 1,\r\n  \"Number of threads to use for the linear solver.\");\r\n\r\nint main(int argc, char** argv) {\r\n  google::ParseCommandLineFlags(&argc, &argv, true);\r\n  google::InitGoogleLogging(argv[0]);\r\n\r\n  if (argc < 4) {\r\n    LOG(ERROR) << \"Usage: \" << argv[0] << \" input_path lambda output_path\";\r\n    return -1;\r\n  }\r\n\r\n  // Load the problem data ...\r\n  Eigen::MatrixXd Y;\r\n  std::vector<int> raw_face_array;\r\n  Eigen::MatrixXd X;\r\n  Eigen::VectorXi p;\r\n  Eigen::MatrixXd U;\r\n  if (!LoadProblemFromFile(argv[1], &Y, &raw_face_array, &X, &p, &U)) {\r\n    return -1;\r\n  }\r\n\r\n  // ... and check consistency of dimensions.\r\n  typedef Eigen::DenseIndex Index;\r\n  const Index num_data_points = Y.cols();\r\n  CHECK_GT(num_data_points, 0);\r\n  CHECK_EQ(num_data_points, p.size());\r\n  CHECK_EQ(num_data_points, U.cols());\r\n\r\n  doosabin::GeneralMesh T(std::move(raw_face_array));\r\n  CHECK_GT(T.number_of_faces(), 0);\r\n  doosabin::Surface<double> surface(T);\r\n  DooSabinSurface doosabin_surface(&surface);\r\n  CHECK_EQ(surface.number_of_vertices(), X.cols());\r\n\r\n  // `lambda` is the regularisation weight.\r\n  const double lambda = atof(argv[2]);\r\n\r\n  // Setup `problem`.\r\n  ceres::Problem problem;\r\n\r\n  // Encode patch indices into the preimage positions.\r\n  for (Index i = 0; i < num_data_points; ++i) {\r\n    EncodePatchIndexInPlace(U.data() + 2 * i, p[i]);\r\n  }\r\n\r\n  // Add error residuals.\r\n  std::vector<double*> parameter_blocks;\r\n  parameter_blocks.reserve(1 + surface.number_of_vertices());\r\n  parameter_blocks.push_back(nullptr); // `u`.\r\n  for (Index i = 0; i < X.cols(); ++i) {\r\n    parameter_blocks.push_back(X.data() + 3 * i);\r\n  }\r\n\r\n  std::unique_ptr<ceres::CostFunction> surface_position(\r\n    new SurfacePositionCostFunction(&doosabin_surface));\r\n\r\n  for (Index i = 0; i < num_data_points; ++i) {\r\n    parameter_blocks[0] = U.data() + 2 * i;\r\n\r\n    auto position_error = new ceres::ComposedCostFunction(\r\n      new ceres::AutoDiffCostFunction<PositionErrorFunctor, 3, 3>(\r\n        new PositionErrorFunctor(Y.col(i), 1.0 / sqrt(num_data_points))));\r\n    position_error->AddInputCostFunction(surface_position.get(),\r\n                                         parameter_blocks,\r\n                                         ceres::DO_NOT_TAKE_OWNERSHIP);\r\n    position_error->Finalize();\r\n\r\n    problem.AddResidualBlock(position_error, nullptr, parameter_blocks);\r\n  }\r\n\r\n  // Add regularisation residuals.\r\n  // Note: `problem` takes ownership of `pairwise_error`.\r\n  auto pairwise_error =\r\n    new ceres::AutoDiffCostFunction<PairwiseErrorFunctor, 3, 3, 3>(\r\n      new PairwiseErrorFunctor(sqrt(lambda)));\r\n\r\n  std::set<std::pair<int, int>> full_edges;\r\n  for (std::pair<int, int> e : T.iterate_half_edges()) {\r\n    if (e.first > e.second) {\r\n      std::swap(e.first, e.second);\r\n    }\r\n    if (!full_edges.count(e)) {\r\n      problem.AddResidualBlock(pairwise_error,\r\n                               nullptr,\r\n                               X.data() + 3 * e.first,\r\n                               X.data() + 3 * e.second);\r\n      full_edges.insert(e);\r\n    }\r\n  }\r\n\r\n  // Set preimage parameterisations so that they are updated using\r\n  // `doosabin::SurfaceWalker<double>` and NOT Euclidean addition.\r\n  // Note: `problem` takes ownership of `local_parameterisation`.\r\n  typedef doosabin::SurfaceWalker<double> DooSabinWalker;\r\n  DooSabinWalker walker(&surface);\r\n  auto local_parameterisation =\r\n    new PreimageLocalParameterisation<DooSabinWalker, Eigen::MatrixXd>(\r\n      &walker, &X);\r\n\r\n  for (Index i = 0; i < num_data_points; ++i) {\r\n    problem.SetParameterization(U.data() + 2 * i, local_parameterisation);\r\n  }\r\n\r\n  // Initialise the solver options.\r\n  std::cout << \"Solver options:\" << std::endl;\r\n  ceres::Solver::Options options;\r\n\r\n  options.num_threads = FLAGS_num_threads;\r\n  options.num_linear_solver_threads = FLAGS_num_linear_solver_threads;\r\n\r\n  // Disable auto-scaling and set LM to be additive (instead of multiplicative).\r\n  options.min_lm_diagonal = 1.0;\r\n  options.max_lm_diagonal = 1.0;\r\n  options.jacobi_scaling = false;\r\n\r\n  options.minimizer_progress_to_stdout = FLAGS_v >= 1;\r\n\r\n  // Termination criteria.\r\n  options.max_num_iterations = FLAGS_max_num_iterations;\r\n  std::cout << \" max_num_iterations: \" << options.max_num_iterations <<\r\n               std::endl;\r\n  options.max_num_consecutive_invalid_steps = FLAGS_max_num_iterations;\r\n\r\n  options.function_tolerance = FLAGS_function_tolerance;\r\n  options.gradient_tolerance = FLAGS_gradient_tolerance;\r\n  options.parameter_tolerance = FLAGS_parameter_tolerance;\r\n  options.min_trust_region_radius = FLAGS_min_trust_region_radius;\r\n\r\n  // Solver selection.\r\n  options.dynamic_sparsity = true;\r\n\r\n  // `update_state_every_iteration` is required by\r\n  // `PreimageLocalParameterisation` instances.\r\n  options.update_state_every_iteration = true;\r\n\r\n  // Solve.\r\n  std::cout << \"Solving ...\" << std::endl;\r\n  ceres::Solver::Summary summary;\r\n  ceres::Solve(options, &problem, &summary);\r\n\r\n  std::cout << summary.FullReport() << std::endl;\r\n\r\n  // Decode patch indices.\r\n  for (Index i = 0; i < num_data_points; ++i) {\r\n    p[i] = DecodePatchIndexInPlace(U.data() + 2 * i);\r\n  }\r\n\r\n  // Save.\r\n  if (!UpdateProblemToFile(argv[1], argv[3], X, p, U)) {\r\n    return -1;\r\n  }\r\n  std::cout << \"Output: \" << argv[3] << std::endl;\r\n\r\n  return 0;\r\n}\r\n", "meta": {"hexsha": "3d545cadcf8d8b79cf3d02d08e2c59cb27f8737a", "size": 12920, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/doosabin_regression.cpp", "max_stars_repo_name": "rstebbing/subdivision-regression", "max_stars_repo_head_hexsha": "e4e862939e091c41e80f1f81a47bc060fb05cdf6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-07-09T07:12:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-14T08:46:32.000Z", "max_issues_repo_path": "src/doosabin_regression.cpp", "max_issues_repo_name": "rstebbing/subdivision-regression", "max_issues_repo_head_hexsha": "e4e862939e091c41e80f1f81a47bc060fb05cdf6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/doosabin_regression.cpp", "max_forks_repo_name": "rstebbing/subdivision-regression", "max_forks_repo_head_hexsha": "e4e862939e091c41e80f1f81a47bc060fb05cdf6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-11-15T09:07:23.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-15T09:07:23.000Z", "avg_line_length": 30.2576112412, "max_line_length": 81, "alphanum_fraction": 0.6176470588, "num_tokens": 3392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.48140618577205085}}
{"text": "///////////////////////////////////////////////////////////////\n//  Copyright 2012 John Maddock. Distributed under the Boost\n//  Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt\n\n#define BOOST_CHRONO_HEADER_ONLY\n\n#if !defined(TEST_MPZ) && !defined(TEST_TOMMATH) && !defined(TEST_CPP_INT)\n#define TEST_MPZ\n#define TEST_TOMMATH\n#define TEST_CPP_INT\n#endif\n\n#ifdef TEST_MPZ\n#include <nil/crypto3/multiprecision/gmp.hpp>\n#endif\n#ifdef TEST_TOMMATH\n#include <nil/crypto3/multiprecision/tommath.hpp>\n#endif\n#ifdef TEST_CPP_INT\n#include <nil/crypto3/multiprecision/cpp_int.hpp>\n#endif\n#include <nil/crypto3/multiprecision/miller_rabin.hpp>\n#include <boost/chrono.hpp>\n#include <map>\n\ntemplate <class Clock>\nstruct stopwatch\n{\n   typedef typename Clock::duration duration;\n   stopwatch()\n   {\n      m_start = Clock::now();\n   }\n   duration elapsed()\n   {\n      return Clock::now() - m_start;\n   }\n   void reset()\n   {\n      m_start = Clock::now();\n   }\n\n private:\n   typename Clock::time_point m_start;\n};\n\nextern unsigned allocation_count;\n\nextern std::map<std::string, double> results;\nextern double                        min_time;\n\ntemplate <class IntType>\nboost::chrono::duration<double> test_miller_rabin(const char* name)\n{\n   using namespace boost::random;\n\n   stopwatch<boost::chrono::high_resolution_clock> c;\n\n   independent_bits_engine<mt11213b, 256, IntType> gen;\n   //\n   // We must use a different generator for the tests and number generation, otherwise\n   // we get false positives.\n   //\n   mt19937  gen2;\n   unsigned result_count = 0;\n\n   for (unsigned i = 0; i < 1000; ++i)\n   {\n      IntType n = gen();\n      if (nil::crypto3::multiprecision::miller_rabin_test(n, 25, gen2))\n         ++result_count;\n   }\n   boost::chrono::duration<double> t = c.elapsed();\n   double                          d = t.count();\n   if (d < min_time)\n      min_time = d;\n   results[name] = d;\n   std::cout << \"Time for \" << std::setw(30) << std::left << name << \" = \" << d << std::endl;\n   std::cout << \"Number of primes found = \" << result_count << std::endl;\n   return t;\n}\n\nboost::chrono::duration<double> test_miller_rabin_gmp();\n\nvoid test01();\nvoid test02();\nvoid test03();\nvoid test04();\nvoid test05();\nvoid test06();\nvoid test07();\nvoid test08();\nvoid test09();\nvoid test10();\nvoid test11();\nvoid test12();\nvoid test13();\nvoid test14();\nvoid test15();\nvoid test16();\nvoid test17();\nvoid test18();\nvoid test19();\n", "meta": {"hexsha": "ee281a0d4e706ce8f29182fd40b5fafdffd9b9b7", "size": 2484, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "snark-logic/libs-source/multiprecision/performance/miller_rabin_performance.hpp", "max_stars_repo_name": "podlodkin/podlodkin-freeton-year-control", "max_stars_repo_head_hexsha": "e394c11f2414804d2fbde93a092ae589d4359739", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-14T18:09:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-14T18:09:38.000Z", "max_issues_repo_path": "libs/multiprecision/performance/miller_rabin_performance.hpp", "max_issues_repo_name": "Curryrasul/knapsack-snark", "max_issues_repo_head_hexsha": "633515a13906407338a81b9874d964869ddec624", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/multiprecision/performance/miller_rabin_performance.hpp", "max_forks_repo_name": "Curryrasul/knapsack-snark", "max_forks_repo_head_hexsha": "633515a13906407338a81b9874d964869ddec624", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-12T10:53:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-12T10:53:21.000Z", "avg_line_length": 23.6571428571, "max_line_length": 93, "alphanum_fraction": 0.652173913, "num_tokens": 646, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.6150878555160664, "lm_q1q2_score": 0.4814061795357581}}
{"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 *      120127    D. Dirkx          File created.\n *      120127    K. Kumar          Transferred unit tests over to Boost unit test framework.\n *      120128    K. Kumar          Changed some BOOST_CHECK to BOOST_CHECK_CLOSE_FRACTION and\n *                                  BOOST_CHECK_SMALL for unit test comparisons.\n *      120128    K. Kumar          Added test for vectors of length 5.\n *      130121    D. Dirkx          Fixed unit test failure under Windows.\n *      130125    D. Dirkx          Fixed unit test failure under Windows by using BOOST_CHECK_LE()\n *                                  and BOOST_CHECK_GE().\n *\n *    References\n *\n *    Notes\n *\n */\n\n#define BOOST_TEST_MAIN\n\n#include <cmath>\n\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/unit_test.hpp>\n\n#include \"Tudat/Mathematics/BasicMathematics/linearAlgebra.h\"\n#include \"Tudat/Mathematics/BasicMathematics/mathematicalConstants.h\"\n\nnamespace tudat\n{\nnamespace unit_tests\n{\n\n//! Test suite for unit conversion functions.\nBOOST_AUTO_TEST_SUITE( test_unit_conversions )\n\n//! Test if angle between vectors is computed correctly.\nBOOST_AUTO_TEST_CASE( testAngleBetweenVectorFunctions )\n{\n    // Using declarations.\n    using std::cos;\n    using std::sqrt;\n    using linear_algebra::computeAngleBetweenVectors;\n    using linear_algebra::computeCosineOfAngleBetweenVectors;\n\n    // Four tests are executed. First, the equality of the caluclated cosineOfAngle and the cosine\n    // of the calculated angle is checked. Subsequently, the values of the angle and cosineOfAngle\n    // are checked against reference values, which are analytical in the first two cases and\n    // taken from Matlab results in the third. The first three tests are written for vectors of length\n    // 3. The fourth test is written for a vector of length 5.\n\n    // Test 1: Test values for two equal vectors of length 3.\n    {\n        Eigen::Vector3d testVector1_ = Eigen::Vector3d( 3.0, 2.1, 4.6 );\n        Eigen::Vector3d testVector2_ = Eigen::Vector3d( 3.0, 2.1, 4.6 );\n\n        double angle = computeAngleBetweenVectors( testVector1_, testVector2_ );\n        double cosineOfAngle = computeCosineOfAngleBetweenVectors( testVector1_, testVector2_ );\n\n        // Check if computed angle and cosine-of-angle are correct.\n        BOOST_CHECK_SMALL( cos( angle ) - cosineOfAngle,\n                           std::numeric_limits< double >::epsilon( ) );\n        BOOST_CHECK_GE( cosineOfAngle, std::numeric_limits< double >::epsilon( ) );\n        BOOST_CHECK_SMALL( cosineOfAngle - 1.0, std::numeric_limits< double >::epsilon( ) );\n        BOOST_CHECK_LE( angle, std::sqrt( std::numeric_limits< double >::epsilon( ) ) );\n    }\n\n    // Test 2: Test values for two equal, but opposite vectors of length 3.\n    {\n        Eigen::Vector3d testVector1_ = Eigen::Vector3d( 3.0, 2.1, 4.6 );\n        Eigen::Vector3d testVector2_ = Eigen::Vector3d( -3.0, -2.1, -4.6 );\n\n        double angle = computeAngleBetweenVectors( testVector1_, testVector2_ );\n        double cosineOfAngle = computeCosineOfAngleBetweenVectors( testVector1_, testVector2_ );\n\n        // Check if computed angle and cosine-of-angle are correct.\n        BOOST_CHECK_SMALL( cos( angle ) - cosineOfAngle,\n                           std::numeric_limits< double >::epsilon( ) );\n        BOOST_CHECK( cosineOfAngle < std::numeric_limits< double >::epsilon( ) );\n        BOOST_CHECK_SMALL( cosineOfAngle + 1.0, std::numeric_limits< double >::epsilon( ) );\n        BOOST_CHECK_CLOSE_FRACTION( angle, mathematical_constants::PI,\n                                    std::sqrt( std::numeric_limits< double >::epsilon( ) ) );\n    }\n\n    // Test 3: Test values for two vectors of length 3, benchmark values computed using Matlab.\n    {\n        Eigen::Vector3d testVector1_ = Eigen::Vector3d( 1.0, 2.0, 3.0 );\n        Eigen::Vector3d testVector2_ = Eigen::Vector3d( -3.74, 3.7, -4.6 );\n\n        double angle = computeAngleBetweenVectors( testVector1_, testVector2_ );\n        double cosineOfAngle = computeCosineOfAngleBetweenVectors( testVector1_, testVector2_ );\n\n        // Check if computed angle and cosine-of-angle are correct.\n        BOOST_CHECK_SMALL( cos( angle ) - cosineOfAngle,\n                           std::numeric_limits< double >::epsilon( ) );\n        BOOST_CHECK( cosineOfAngle < std::numeric_limits< double >::epsilon( ) );\n        BOOST_CHECK_CLOSE_FRACTION( cosineOfAngle, -0.387790156029810,\n                                    std::numeric_limits< double >::epsilon( ) );\n        BOOST_CHECK_CLOSE_FRACTION( angle, 1.969029256915446,\n                                    std::numeric_limits< double >::epsilon( ) );\n    }\n\n    // Test 4: Test values for two vectors of length 5, benchmark values computed using Matlab.\n    {\n        Eigen::VectorXd testVector1_( 5 );\n        testVector1_ << 3.26, 8.66, 1.09, 4.78, 9.92;\n        Eigen::VectorXd testVector2_( 5 );\n        testVector2_ << 1.05, 0.23, 9.01, 3.25, 7.74;\n\n        double angle = computeAngleBetweenVectors( testVector1_, testVector2_ );\n        double cosineOfAngle = computeCosineOfAngleBetweenVectors( testVector1_, testVector2_ );\n\n        // Check if computed angle and cosine-of-angle are correct.\n        BOOST_CHECK_SMALL( cos( angle ) - cosineOfAngle,\n                           std::numeric_limits< double >::epsilon( ) );\n        BOOST_CHECK( cosineOfAngle > std::numeric_limits< double >::epsilon( ) );\n        BOOST_CHECK_CLOSE_FRACTION( cosineOfAngle, 0.603178944723925,\n                                    std::numeric_limits< double >::epsilon( ) );\n        BOOST_CHECK_CLOSE_FRACTION( angle, 0.923315587553074, 1.0e-15 );\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END( )\n\n} // namespace unit_tests\n} // namespace tudat\n", "meta": {"hexsha": "a98463fff9dd39e88cb899a0a98021bb039bcd40", "size": 7456, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Mathematics/BasicMathematics/UnitTests/unitTestLinearAlgebra.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/UnitTests/unitTestLinearAlgebra.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/UnitTests/unitTestLinearAlgebra.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": 49.7066666667, "max_line_length": 102, "alphanum_fraction": 0.6714055794, "num_tokens": 1772, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.4813417719058162}}
{"text": "// Copyright John Maddock 2012.\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_JACOBI_ELLIPTIC_HPP\n#define BOOST_MATH_JACOBI_ELLIPTIC_HPP\n\n#include <boost/math/tools/precision.hpp>\n#include <boost/math/tools/promotion.hpp>\n#include <boost/math/policies/error_handling.hpp>\n\nnamespace boost{ namespace math{\n\nnamespace detail{\n\ntemplate <class T, class Policy>\nT jacobi_recurse(const T& x, const T& k, T anm1, T bnm1, unsigned N, T* pTn, const Policy& pol)\n{\n   BOOST_MATH_STD_USING\n   ++N;\n   T Tn;\n   T cn = (anm1 - bnm1) / 2;\n   T an = (anm1 + bnm1) / 2;\n   if(cn < policies::get_epsilon<T, Policy>())\n   {\n      Tn = ldexp(T(1), (int)N) * x * an;\n   }\n   else\n      Tn = jacobi_recurse<T>(x, k, an, sqrt(anm1 * bnm1), N, 0, pol);\n   if(pTn)\n      *pTn = Tn;\n   return (Tn + asin((cn / an) * sin(Tn))) / 2;\n}\n\ntemplate <class T, class Policy>\nT jacobi_imp(const T& x, const T& k, T* cn, T* dn, const Policy& pol, const char* function)\n{\n   BOOST_MATH_STD_USING\n   if(k < 0)\n   {\n      *cn = policies::raise_domain_error<T>(function, \"Modulus k must be positive but got %1%.\", k, pol);\n      *dn = *cn;\n      return *cn;\n   }\n   if(k > 1)\n   {\n      T xp = x * k;\n      T kp = 1 / k;\n      T snp, cnp, dnp;\n      snp = jacobi_imp(xp, kp, &cnp, &dnp, pol, function);\n      *cn = dnp;\n      *dn = cnp;\n      return snp * kp;\n   }\n   //\n   // Special cases first:\n   //\n   if(x == 0)\n   {\n      *cn = *dn = 1;\n      return 0;\n   }\n   if(k == 0)\n   {\n      *cn = cos(x);\n      *dn = 1;\n      return sin(x);\n   }\n   if(k == 1)\n   {\n      *cn = *dn = 1 / cosh(x);\n      return tanh(x);\n   }\n   //\n   // Asymptotic forms from A&S 16.13:\n   //\n   if(k < tools::forth_root_epsilon<T>())\n   {\n      T su = sin(x);\n      T cu = cos(x);\n      T m = k * k;\n      *dn = 1 - m * su * su / 2;\n      *cn = cu + m * (x - su * cu) * su / 4;\n      return su - m * (x - su * cu) * cu / 4;\n   }\n   /*  Can't get this to work to adequate precision - disabled for now...\n   //\n   // Asymptotic forms from A&S 16.15:\n   //\n   if(k > 1 - tools::root_epsilon<T>())\n   {\n      T tu = tanh(x);\n      T su = sinh(x);\n      T cu = cosh(x);\n      T sec = 1 / cu;\n      T kp = 1 - k;\n      T m1 = 2 * kp - kp * kp;\n      *dn = sec + m1 * (su * cu + x) * tu * sec / 4;\n      *cn = sec - m1 * (su * cu - x) * tu * sec / 4;\n      T sn = tu;\n      T sn2 = m1 * (x * sec * sec - tu) / 4;\n      T sn3 = (72 * x * cu + 4 * (8 * x * x - 5) * su - 19 * sinh(3 * x) + sinh(5 * x)) * sec * sec * sec * m1 * m1 / 512;\n      return sn + sn2 - sn3;\n   }*/\n   T T1;\n   T kc = 1 - k;\n   T k_prime = k < 0.5 ? T(sqrt(1 - k * k)) : T(sqrt(2 * kc - kc * kc));\n   T T0 = jacobi_recurse(x, k, T(1), k_prime, 0, &T1, pol);\n   *cn = cos(T0);\n   *dn = cos(T0) / cos(T1 - T0);\n   return sin(T0);\n}\n\n} // namespace detail\n\ntemplate <class T, class U, class V, class Policy>\ninline typename tools::promote_args<T, U, V>::type jacobi_elliptic(T k, U theta, V* pcn, V* pdn, const Policy&)\n{\n   BOOST_FPU_EXCEPTION_GUARD\n   typedef typename tools::promote_args<T>::type result_type;\n   typedef typename policies::evaluation<result_type, Policy>::type value_type;\n   typedef typename policies::normalise<\n      Policy, \n      policies::promote_float<false>, \n      policies::promote_double<false>, \n      policies::discrete_quantile<>,\n      policies::assert_undefined<> >::type forwarding_policy;\n\n   static const char* function = \"boost::math::jacobi_elliptic<%1%>(%1%)\";\n\n   value_type sn, cn, dn;\n   sn = detail::jacobi_imp<value_type>(static_cast<value_type>(theta), static_cast<value_type>(k), &cn, &dn, forwarding_policy(), function);\n   if(pcn)\n      *pcn = policies::checked_narrowing_cast<result_type, Policy>(cn, function);\n   if(pdn)\n      *pdn = policies::checked_narrowing_cast<result_type, Policy>(dn, function);\n   return policies::checked_narrowing_cast<result_type, Policy>(sn, function);;\n}\n\ntemplate <class T, class U, class V>\ninline typename tools::promote_args<T, U, V>::type jacobi_elliptic(T k, U theta, V* pcn, V* pdn)\n{\n   return jacobi_elliptic(k, theta, pcn, pdn, policies::policy<>());\n}\n\ntemplate <class U, class T, class Policy>\ninline typename tools::promote_args<T, U>::type jacobi_sn(U k, T theta, const Policy& pol)\n{\n   typedef typename tools::promote_args<T, U>::type result_type;\n   return jacobi_elliptic(static_cast<result_type>(k), static_cast<result_type>(theta), static_cast<result_type*>(0), static_cast<result_type*>(0), pol);\n}\n\ntemplate <class U, class T>\ninline typename tools::promote_args<T, U>::type jacobi_sn(U k, T theta)\n{\n   return jacobi_sn(k, theta, policies::policy<>());\n}\n\ntemplate <class T, class U, class Policy>\ninline typename tools::promote_args<T, U>::type jacobi_cn(T k, U theta, const Policy& pol)\n{\n   typedef typename tools::promote_args<T, U>::type result_type;\n   result_type cn;\n   jacobi_elliptic(static_cast<result_type>(k), static_cast<result_type>(theta), &cn, static_cast<result_type*>(0), pol);\n   return cn;\n}\n\ntemplate <class T, class U>\ninline typename tools::promote_args<T, U>::type jacobi_cn(T k, U theta)\n{\n   return jacobi_cn(k, theta, policies::policy<>());\n}\n\ntemplate <class T, class U, class Policy>\ninline typename tools::promote_args<T, U>::type jacobi_dn(T k, U theta, const Policy& pol)\n{\n   typedef typename tools::promote_args<T, U>::type result_type;\n   result_type dn;\n   jacobi_elliptic(static_cast<result_type>(k), static_cast<result_type>(theta), static_cast<result_type*>(0), &dn, pol);\n   return dn;\n}\n\ntemplate <class T, class U>\ninline typename tools::promote_args<T, U>::type jacobi_dn(T k, U theta)\n{\n   return jacobi_dn(k, theta, policies::policy<>());\n}\n\ntemplate <class T, class U, class Policy>\ninline typename tools::promote_args<T, U>::type jacobi_cd(T k, U theta, const Policy& pol)\n{\n   typedef typename tools::promote_args<T, U>::type result_type;\n   result_type cn, dn;\n   jacobi_elliptic(static_cast<result_type>(k), static_cast<result_type>(theta), &cn, &dn, pol);\n   return cn / dn;\n}\n\ntemplate <class T, class U>\ninline typename tools::promote_args<T, U>::type jacobi_cd(T k, U theta)\n{\n   return jacobi_cd(k, theta, policies::policy<>());\n}\n\ntemplate <class T, class U, class Policy>\ninline typename tools::promote_args<T, U>::type jacobi_dc(T k, U theta, const Policy& pol)\n{\n   typedef typename tools::promote_args<T, U>::type result_type;\n   result_type cn, dn;\n   jacobi_elliptic(static_cast<result_type>(k), static_cast<result_type>(theta), &cn, &dn, pol);\n   return dn / cn;\n}\n\ntemplate <class T, class U>\ninline typename tools::promote_args<T, U>::type jacobi_dc(T k, U theta)\n{\n   return jacobi_dc(k, theta, policies::policy<>());\n}\n\ntemplate <class T, class U, class Policy>\ninline typename tools::promote_args<T, U>::type jacobi_ns(T k, U theta, const Policy& pol)\n{\n   typedef typename tools::promote_args<T, U>::type result_type;\n   return 1 / jacobi_elliptic(static_cast<result_type>(k), static_cast<result_type>(theta), static_cast<result_type*>(0), static_cast<result_type*>(0), pol);\n}\n\ntemplate <class T, class U>\ninline typename tools::promote_args<T, U>::type jacobi_ns(T k, U theta)\n{\n   return jacobi_ns(k, theta, policies::policy<>());\n}\n\ntemplate <class T, class U, class Policy>\ninline typename tools::promote_args<T, U>::type jacobi_sd(T k, U theta, const Policy& pol)\n{\n   typedef typename tools::promote_args<T, U>::type result_type;\n   result_type sn, dn;\n   sn = jacobi_elliptic(static_cast<result_type>(k), static_cast<result_type>(theta), static_cast<result_type*>(0), &dn, pol);\n   return sn / dn;\n}\n\ntemplate <class T, class U>\ninline typename tools::promote_args<T, U>::type jacobi_sd(T k, U theta)\n{\n   return jacobi_sd(k, theta, policies::policy<>());\n}\n\ntemplate <class T, class U, class Policy>\ninline typename tools::promote_args<T, U>::type jacobi_ds(T k, U theta, const Policy& pol)\n{\n   typedef typename tools::promote_args<T, U>::type result_type;\n   result_type sn, dn;\n   sn = jacobi_elliptic(static_cast<result_type>(k), static_cast<result_type>(theta), static_cast<result_type*>(0), &dn, pol);\n   return dn / sn;\n}\n\ntemplate <class T, class U>\ninline typename tools::promote_args<T, U>::type jacobi_ds(T k, U theta)\n{\n   return jacobi_ds(k, theta, policies::policy<>());\n}\n\ntemplate <class T, class U, class Policy>\ninline typename tools::promote_args<T, U>::type jacobi_nc(T k, U theta, const Policy& pol)\n{\n   return 1 / jacobi_cn(k, theta, pol);\n}\n\ntemplate <class T, class U>\ninline typename tools::promote_args<T, U>::type jacobi_nc(T k, U theta)\n{\n   return jacobi_nc(k, theta, policies::policy<>());\n}\n\ntemplate <class T, class U, class Policy>\ninline typename tools::promote_args<T, U>::type jacobi_nd(T k, U theta, const Policy& pol)\n{\n   return 1 / jacobi_dn(k, theta, pol);\n}\n\ntemplate <class T, class U>\ninline typename tools::promote_args<T, U>::type jacobi_nd(T k, U theta)\n{\n   return jacobi_nd(k, theta, policies::policy<>());\n}\n\ntemplate <class T, class U, class Policy>\ninline typename tools::promote_args<T, U>::type jacobi_sc(T k, U theta, const Policy& pol)\n{\n   typedef typename tools::promote_args<T, U>::type result_type;\n   result_type sn, cn;\n   sn = jacobi_elliptic(static_cast<result_type>(k), static_cast<result_type>(theta), &cn, static_cast<result_type*>(0), pol);\n   return sn / cn;\n}\n\ntemplate <class T, class U>\ninline typename tools::promote_args<T, U>::type jacobi_sc(T k, U theta)\n{\n   return jacobi_sc(k, theta, policies::policy<>());\n}\n\ntemplate <class T, class U, class Policy>\ninline typename tools::promote_args<T, U>::type jacobi_cs(T k, U theta, const Policy& pol)\n{\n   typedef typename tools::promote_args<T, U>::type result_type;\n   result_type sn, cn;\n   sn = jacobi_elliptic(static_cast<result_type>(k), static_cast<result_type>(theta), &cn, static_cast<result_type*>(0), pol);\n   return cn / sn;\n}\n\ntemplate <class T, class U>\ninline typename tools::promote_args<T, U>::type jacobi_cs(T k, U theta)\n{\n   return jacobi_cs(k, theta, policies::policy<>());\n}\n\n}} // namespaces\n\n#endif // BOOST_MATH_JACOBI_ELLIPTIC_HPP\n", "meta": {"hexsha": "60ef97e027fe5ec54dcaaf528fe3b6aacb7bf011", "size": 10137, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/math/special_functions/jacobi_elliptic.hpp", "max_stars_repo_name": "ballisticwhisper/boost", "max_stars_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_stars_repo_licenses": ["BSL-1.0"], "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/math/special_functions/jacobi_elliptic.hpp", "max_issues_repo_name": "ballisticwhisper/boost", "max_issues_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 38.0, "max_issues_repo_issues_event_min_datetime": "2015-07-22T07:35:45.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-14T16:03:06.000Z", "max_forks_repo_path": "boost/math/special_functions/jacobi_elliptic.hpp", "max_forks_repo_name": "ballisticwhisper/boost", "max_forks_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 35.0, "max_forks_repo_forks_event_min_datetime": "2015-12-17T00:09:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-27T10:47:11.000Z", "avg_line_length": 31.5794392523, "max_line_length": 157, "alphanum_fraction": 0.6544342508, "num_tokens": 3143, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585903489892, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.4813417698217288}}
{"text": "/*********************************************************************\n*  Copyright (c) 2017 - for information on the respective copyright\n*  owner see the NOTICE file and/or the repository\n*\n*      https://github.com/hbanzhaf/steering_functions.git\n*\n*  Licensed under the Apache License, Version 2.0 (the \"License\");\n*  you may not use this file except in compliance with the License.\n*  You may obtain a copy of the License at\n*\n*      http://www.apache.org/licenses/LICENSE-2.0\n*\n*  Unless required by applicable law or agreed to in writing, software\n*  distributed under the License is distributed on an \"AS IS\" BASIS,\n*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n*  implied. See the License for the specific language governing\n*  permissions and limitations under the License.\n***********************************************************************/\n\n#include <iostream>\n\n//#include <Eigen/Dense>\n\n#include \"steering_functions/dubins_state_space/dubins_state_space.hpp\"\n#include \"steering_functions/hc_cc_state_space/cc00_dubins_state_space.hpp\"\n#include \"steering_functions/hc_cc_state_space/cc00_reeds_shepp_state_space.hpp\"\n#include \"steering_functions/hc_cc_state_space/cc0pm_dubins_state_space.hpp\"\n#include \"steering_functions/hc_cc_state_space/cc_dubins_state_space.hpp\"\n#include \"steering_functions/hc_cc_state_space/ccpm0_dubins_state_space.hpp\"\n#include \"steering_functions/hc_cc_state_space/ccpmpm_dubins_state_space.hpp\"\n#include \"steering_functions/hc_cc_state_space/hc00_reeds_shepp_state_space.hpp\"\n#include \"steering_functions/hc_cc_state_space/hc0pm_reeds_shepp_state_space.hpp\"\n#include \"steering_functions/hc_cc_state_space/hc_reeds_shepp_state_space.hpp\"\n#include \"steering_functions/hc_cc_state_space/hcpm0_reeds_shepp_state_space.hpp\"\n#include \"steering_functions/hc_cc_state_space/hcpmpm_reeds_shepp_state_space.hpp\"\n#include \"steering_functions/reeds_shepp_state_space/reeds_shepp_state_space.hpp\"\n#include \"steering_functions/steering_functions.hpp\"\n\n#define FRAME_ID \"/world\"\n#define DISCRETIZATION 0.1               // [m]\n#define VISUALIZATION_DURATION 2         // [s]\n#define ANIMATE false                    // [-]\n#define OPERATING_REGION_X 20.0          // [m]\n#define OPERATING_REGION_Y 20.0          // [m]\n#define OPERATING_REGION_THETA 2 * M_PI  // [rad]\n#define random(lower, upper) (rand() * (upper - lower) / RAND_MAX + lower)\n\nusing namespace std;\n\nclass PathClass\n{\npublic:\n  string path_type_;\n  double discretization_;\n  State state_start_;\n  State state_goal_;\n  double kappa_max_;\n  double sigma_max_;\n  vector<State> path_;\n\n  // filter parameters\n  Motion_Noise motion_noise_;\n  Measurement_Noise measurement_noise_;\n  Controller controller_;\n\n\n  // constructor\n  PathClass(const string& path_type, const State& state_start, const State& state_goal,\n            const double kappa_max, const double sigma_max)\n    : path_type_(path_type)\n    , discretization_(DISCRETIZATION)\n    , state_start_(state_start)\n    , state_goal_(state_goal)\n    , kappa_max_(kappa_max)\n    , sigma_max_(sigma_max)\n  {\n\n    // path\n    if (path_type_ == \"CC_Dubins\")\n    {\n      CC_Dubins_State_Space state_space(kappa_max_, sigma_max_, discretization_, true);\n      state_space.set_filter_parameters(motion_noise_, measurement_noise_, controller_);\n      path_ = state_space.get_path(state_start_, state_goal_);\n    }\n    else if (path_type_ == \"CC00_Dubins\")\n    {\n      CC00_Dubins_State_Space state_space(kappa_max_, sigma_max_, discretization_, true);\n      state_space.set_filter_parameters(motion_noise_, measurement_noise_, controller_);\n      path_ = state_space.get_path(state_start_, state_goal_);\n    }\n    else if (path_type_ == \"CC0pm_Dubins\")\n    {\n      CC0pm_Dubins_State_Space state_space(kappa_max_, sigma_max_, discretization_, true);\n      state_space.set_filter_parameters(motion_noise_, measurement_noise_, controller_);\n      path_ = state_space.get_path(state_start_, state_goal_);\n    }\n    else if (path_type_ == \"CCpm0_Dubins\")\n    {\n      CCpm0_Dubins_State_Space state_space(kappa_max_, sigma_max_, discretization_, true);\n      state_space.set_filter_parameters(motion_noise_, measurement_noise_, controller_);\n      path_ = state_space.get_path(state_start_, state_goal_);\n    }\n    else if (path_type_ == \"CCpmpm_Dubins\")\n    {\n      CCpmpm_Dubins_State_Space state_space(kappa_max_, sigma_max_, discretization_, true);\n      state_space.set_filter_parameters(motion_noise_, measurement_noise_, controller_);\n      path_ = state_space.get_path(state_start_, state_goal_);\n    }\n    else if (path_type_ == \"Dubins\")\n    {\n      Dubins_State_Space state_space(kappa_max_, discretization_, true);\n      state_space.set_filter_parameters(motion_noise_, measurement_noise_, controller_);\n      path_ = state_space.get_path(state_start_, state_goal_);\n    }\n    else if (path_type_ == \"CC00_RS\")\n    {\n      CC00_Reeds_Shepp_State_Space state_space(kappa_max_, sigma_max_, discretization_);\n      state_space.set_filter_parameters(motion_noise_, measurement_noise_, controller_);\n      path_ = state_space.get_path(state_start_, state_goal_);\n    }\n    else if (path_type_ == \"HC_RS\")\n    {\n      HC_Reeds_Shepp_State_Space state_space(kappa_max_, sigma_max_, discretization_);\n      state_space.set_filter_parameters(motion_noise_, measurement_noise_, controller_);\n      path_ = state_space.get_path(state_start_, state_goal_);\n    }\n    else if (path_type_ == \"HC00_RS\")\n    {\n      HC00_Reeds_Shepp_State_Space state_space(kappa_max_, sigma_max_, discretization_);\n      state_space.set_filter_parameters(motion_noise_, measurement_noise_, controller_);\n      path_ = state_space.get_path(state_start_, state_goal_);\n    }\n    else if (path_type_ == \"HC0pm_RS\")\n    {\n      HC0pm_Reeds_Shepp_State_Space state_space(kappa_max_, sigma_max_, discretization_);\n      state_space.set_filter_parameters(motion_noise_, measurement_noise_, controller_);\n      path_ = state_space.get_path(state_start_, state_goal_);\n    }\n    else if (path_type_ == \"HCpm0_RS\")\n    {\n      HCpm0_Reeds_Shepp_State_Space state_space(kappa_max_, sigma_max_, discretization_);\n      state_space.set_filter_parameters(motion_noise_, measurement_noise_, controller_);\n      path_ = state_space.get_path(state_start_, state_goal_);\n    }\n    else if (path_type_ == \"HCpmpm_RS\")\n    {\n      HCpmpm_Reeds_Shepp_State_Space state_space(kappa_max_, sigma_max_, discretization_);\n      state_space.set_filter_parameters(motion_noise_, measurement_noise_, controller_);\n      path_ = state_space.get_path(state_start_, state_goal_);\n    }\n    else if (path_type_ == \"RS\")\n    {\n      Reeds_Shepp_State_Space state_space(kappa_max_, discretization_);\n      state_space.set_filter_parameters(motion_noise_, measurement_noise_, controller_);\n      path_ = state_space.get_path(state_start_, state_goal_);\n    }\n  }\n};\n\nclass RobotClass\n{\npublic:\n  // robot config\n  double kappa_max_;\n  double sigma_max_;\n  double wheel_base_;\n  double track_width_;\n  double wheel_radius_;\n  double wheel_width_;\n\n  // measurement noise\n  Measurement_Noise measurement_noise_;\n\n  // visualization\n  string frame_id_;\n  bool animate_;\n\n  // constructor\n  explicit RobotClass() : frame_id_(FRAME_ID), animate_(ANIMATE)\n  {\n  }\n};\n\nint main(int argc, char** argv)\n{\n  RobotClass robot;\n\n  int seed(5);\n  srand(seed);\n    State start;\n    start.x = random(-OPERATING_REGION_X / 2.0, OPERATING_REGION_X / 2.0);\n    start.y = random(-OPERATING_REGION_Y / 2.0, OPERATING_REGION_Y / 2.0);\n    start.theta = random(-OPERATING_REGION_THETA / 2.0, OPERATING_REGION_THETA / 2.0);\n    start.kappa = random(-robot.kappa_max_, robot.kappa_max_);\n    start.d = 0.0;\n\n    State start_wout_curv;\n    start_wout_curv.x = start.x;\n    start_wout_curv.y = start.y;\n    start_wout_curv.theta = start.theta;\n    start_wout_curv.kappa = 0.01;\n    start_wout_curv.d = start.d;\n\n    State goal;\n    goal.x = random(-OPERATING_REGION_X / 2.0, OPERATING_REGION_X / 2.0);\n    goal.y = random(-OPERATING_REGION_Y / 2.0, OPERATING_REGION_Y / 2.0);\n    goal.theta = random(-OPERATING_REGION_THETA / 2.0, OPERATING_REGION_THETA / 2.0);\n    goal.kappa = random(-robot.kappa_max_, robot.kappa_max_);\n    goal.d = 0.0;\n\n    State goal_wout_curv;\n    goal_wout_curv.x = goal.x;\n    goal_wout_curv.y = goal.y;\n    goal_wout_curv.theta = goal.theta;\n    goal_wout_curv.kappa = 0.0;\n    goal_wout_curv.d = goal.d;\n\n    PathClass cc_dubins_path(\"CC_Dubins\", start, goal, robot.kappa_max_, robot.sigma_max_);\n    PathClass cc00_dubins_path(\"CC00_Dubins\", start_wout_curv, goal_wout_curv, robot.kappa_max_, robot.sigma_max_);\n    //PathClass cc0pm_dubins_path(\"CC0pm_Dubins\", start_wout_curv, goal_wout_curv, robot.kappa_max_, robot.sigma_max_);\n    //PathClass ccpm0_dubins_path(\"CCpm0_Dubins\", start_wout_curv, goal_wout_curv, robot.kappa_max_, robot.sigma_max_);\n    //PathClass ccpmpm_dubins_path(\"CCpmpm_Dubins\", start_wout_curv, goal_wout_curv, robot.kappa_max_, robot.sigma_max_);\n    //PathClass dubins_path(\"Dubins\", start_wout_curv, goal_wout_curv, robot.kappa_max_, robot.sigma_max_);\n    //PathClass cc00_rs_path(\"CC00_RS\", start_wout_curv, goal_wout_curv, robot.kappa_max_, robot.sigma_max_);\n    //PathClass hc_rs_path(\"HC_RS\", start, goal, robot.kappa_max_, robot.sigma_max_);\n    //PathClass hc00_rs_path(\"HC00_RS\", start_wout_curv, goal_wout_curv, robot.kappa_max_, robot.sigma_max_);\n    //PathClass hc0pm_rs_path(\"HC0pm_RS\", start_wout_curv, goal_wout_curv, robot.kappa_max_, robot.sigma_max_);\n    //PathClass hcpm0_rs_path(\"HCpm0_RS\", start_wout_curv, goal_wout_curv, robot.kappa_max_, robot.sigma_max_);\n    //PathClass hcpmpm_rs_path(\"HCpmpm_RS\", start_wout_curv, goal_wout_curv, robot.kappa_max_, robot.sigma_max_);\n    PathClass rs_path(\"RS\", start_wout_curv, goal_wout_curv, robot.kappa_max_, robot.sigma_max_);\n  return 0;\n}\n", "meta": {"hexsha": "3e2f91d72a5aee3da43da44b7d469f0c14461119", "size": 9842, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/steering_functions_node.cpp", "max_stars_repo_name": "Fields2Cover-group/steering_functions", "max_stars_repo_head_hexsha": "13e3f5658144b3832fb1eb31a0e2f5a3cbf57db9", "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": "src/steering_functions_node.cpp", "max_issues_repo_name": "Fields2Cover-group/steering_functions", "max_issues_repo_head_hexsha": "13e3f5658144b3832fb1eb31a0e2f5a3cbf57db9", "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": "src/steering_functions_node.cpp", "max_forks_repo_name": "Fields2Cover-group/steering_functions", "max_forks_repo_head_hexsha": "13e3f5658144b3832fb1eb31a0e2f5a3cbf57db9", "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": 42.2403433476, "max_line_length": 121, "alphanum_fraction": 0.7420239789, "num_tokens": 2556, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.6584175072643415, "lm_q1q2_score": 0.4813417670057804}}
{"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    testNonlinearFactorGraph.cpp\n * @brief   Unit tests for Non-Linear Factor Graph\n * @brief   testNonlinearFactorGraph\n * @author  Carlos Nieto\n * @author  Christian Potthast\n */\n\n/*STL/C++*/\n#include <iostream>\nusing namespace std;\n\n#include <boost/assign/std/list.hpp>\n#include <boost/assign/std/set.hpp>\nusing namespace boost::assign;\n\n#include <CppUnitLite/TestHarness.h>\n\n#include <gtsam/base/Testable.h>\n#include <gtsam/base/Matrix.h>\n#include <tests/smallExample.h>\n#include <gtsam/inference/FactorGraph.h>\n#include <gtsam/nonlinear/NonlinearFactorGraph.h>\n#include <gtsam/nonlinear/Symbol.h>\n\nusing namespace gtsam;\nusing namespace example;\n\nusing symbol_shorthand::X;\nusing symbol_shorthand::L;\n\n/* ************************************************************************* */\nTEST( Graph, equals )\n{\n\tGraph fg = createNonlinearFactorGraph();\n\tGraph fg2 = createNonlinearFactorGraph();\n\tCHECK( fg.equals(fg2) );\n}\n\n/* ************************************************************************* */\nTEST( Graph, error )\n{\n\tGraph fg = createNonlinearFactorGraph();\n\tValues c1 = createValues();\n\tdouble actual1 = fg.error(c1);\n\tDOUBLES_EQUAL( 0.0, actual1, 1e-9 );\n\n\tValues c2 = createNoisyValues();\n\tdouble actual2 = fg.error(c2);\n\tDOUBLES_EQUAL( 5.625, actual2, 1e-9 );\n}\n\n/* ************************************************************************* */\nTEST( Graph, keys )\n{\n\tGraph fg = createNonlinearFactorGraph();\n\tFastSet<Key> actual = fg.keys();\n\tLONGS_EQUAL(3, actual.size());\n\tFastSet<Key>::const_iterator it = actual.begin();\n\tLONGS_EQUAL(L(1), *(it++));\n\tLONGS_EQUAL(X(1), *(it++));\n\tLONGS_EQUAL(X(2), *(it++));\n}\n\n/* ************************************************************************* */\nTEST( Graph, GET_ORDERING)\n{\n//  Ordering expected; expected += \"x1\",\"l1\",\"x2\"; // For starting with x1,x2,l1\n  Ordering expected; expected += L(1), X(2), X(1); // For starting with l1,x1,x2\n  Graph nlfg = createNonlinearFactorGraph();\n  SymbolicFactorGraph::shared_ptr symbolic;\n  Ordering::shared_ptr ordering;\n  boost::tie(symbolic, ordering) = nlfg.symbolic(createNoisyValues());\n  Ordering actual = *nlfg.orderingCOLAMD(createNoisyValues());\n  EXPECT(assert_equal(expected,actual));\n\n  // Constrained ordering - put x2 at the end\n  std::map<Key, int> constraints;\n  constraints[X(2)] = 1;\n  Ordering actualConstrained = *nlfg.orderingCOLAMDConstrained(createNoisyValues(), constraints);\n  Ordering expectedConstrained; expectedConstrained += L(1), X(1), X(2);\n  EXPECT(assert_equal(expectedConstrained, actualConstrained));\n}\n\n/* ************************************************************************* */\nTEST( Graph, probPrime )\n{\n\tGraph fg = createNonlinearFactorGraph();\n\tValues cfg = createValues();\n\n\t// evaluate the probability of the factor graph\n\tdouble actual = fg.probPrime(cfg);\n\tdouble expected = 1.0;\n\tDOUBLES_EQUAL(expected,actual,0);\n}\n\n/* ************************************************************************* */\nTEST( Graph, linearize )\n{\n\tGraph fg = createNonlinearFactorGraph();\n\tValues initial = createNoisyValues();\n\tboost::shared_ptr<FactorGraph<GaussianFactor> > linearized = fg.linearize(initial, *initial.orderingArbitrary());\n\tFactorGraph<GaussianFactor> expected = createGaussianFactorGraph(*initial.orderingArbitrary());\n\tCHECK(assert_equal(expected,*linearized)); // Needs correct linearizations\n}\n\n/* ************************************************************************* */\nTEST( Graph, clone )\n{\n\tGraph fg = createNonlinearFactorGraph();\n\tGraph actClone = fg.clone();\n\tEXPECT(assert_equal(fg, actClone));\n\tfor (size_t i=0; i<fg.size(); ++i)\n\t\tEXPECT(fg[i] != actClone[i]);\n}\n\n/* ************************************************************************* */\nTEST( Graph, rekey )\n{\n\tGraph init = createNonlinearFactorGraph();\n\tmap<Key,Key> rekey_mapping;\n\trekey_mapping.insert(make_pair(L(1), L(4)));\n\tGraph actRekey = init.rekey(rekey_mapping);\n\n\t// ensure deep clone\n\tLONGS_EQUAL(init.size(), actRekey.size());\n\tfor (size_t i=0; i<init.size(); ++i)\n\t\t\tEXPECT(init[i] != actRekey[i]);\n\n\tGraph expRekey;\n\t// original measurements\n\texpRekey.push_back(init[0]);\n\texpRekey.push_back(init[1]);\n\n\t// updated measurements\n\tPoint2 z3(0, -1),  z4(-1.5, -1.);\n\tSharedDiagonal sigma0_2 = noiseModel::Isotropic::Sigma(2,0.2);\n\texpRekey.add(simulated2D::Measurement(z3, sigma0_2, X(1), L(4)));\n\texpRekey.add(simulated2D::Measurement(z4, sigma0_2, X(2), L(4)));\n\n\tEXPECT(assert_equal(expRekey, actRekey));\n}\n\n/* ************************************************************************* */\nint main() { TestResult tr; return TestRegistry::runAllTests(tr); }\n/* ************************************************************************* */\n", "meta": {"hexsha": "f677eb0dc3dbfe5f142cc6d1b21c54ad4932b48a", "size": 5085, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/testNonlinearFactorGraph.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": "tests/testNonlinearFactorGraph.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": "tests/testNonlinearFactorGraph.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": 32.1835443038, "max_line_length": 114, "alphanum_fraction": 0.585840708, "num_tokens": 1215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.48134176596373657}}
{"text": "/********************************************************************************\n*  This file is part of CinoLib                                                 *\n*  Copyright(C) 2016: Marco Livesu                                              *\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*                                                                               *\n*     Marco Livesu (marco.livesu@gmail.com)                                     *\n*     http://pers.ge.imati.cnr.it/livesu/                                       *\n*                                                                               *\n*     Italian National Research Council (CNR)                                   *\n*     Institute for Applied Mathematics and Information Technologies (IMATI)    *\n*     Via de Marini, 6                                                          *\n*     16149 Genoa,                                                              *\n*     Italy                                                                     *\n*********************************************************************************/\n#include \"intersection.h\"\n\n#include <cinolib/geometry/triangle.h>\n#include <boost/geometry/geometries/point.hpp>\n#include <boost/geometry/geometries/segment.hpp>\n#include <boost/geometry/algorithms/intersection.hpp>\n\n#include <Eigen/Dense>\n\nnamespace cinolib\n{\n\nnamespace bg = boost::geometry;\ntypedef   bg::model::point<double,3,bg::cs::cartesian> Point;\ntypedef   bg::model::segment<Point>                    Segment2D;\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\nCINO_INLINE\nbool segment2D_intersection(const vec2d        & s0_beg,\n                            const vec2d        & s0_end,\n                            const vec2d        & s1_beg,\n                            const vec2d        & s1_end,\n                            std::vector<vec2d> & inters)\n{\n    assert(inters.empty());\n\n    std::vector<Point> res;\n    bg::intersection(Segment2D(Point(s0_beg.x(), s0_beg.y()),\n                               Point(s0_end.x(), s0_end.y())),\n                     Segment2D(Point(s1_beg.x(), s1_beg.y()),\n                               Point(s1_end.x(), s1_end.y())),\n                     res);\n\n    // if s1 and s2 are colinear returns the endpoints of the shared portion\n    //\n    for(Point p : res) inters.push_back(vec2d(p.get<0>(), p.get<1>()));\n\n    return !inters.empty();\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\nCINO_INLINE\nbool line_triangle_intersection(const Line  & l,\n                                const vec3d & V0,\n                                const vec3d & V1,\n                                const vec3d & V2,\n                                      vec3d & inters,\n                                const double  tol)\n{\n    std::vector<Plane> planes = l.to_planes();\n    planes.push_back(Plane(V0,V1,V2));\n\n    if (least_squares_intersection(planes, inters))\n    {\n        std::vector<double> wgts;\n        if (triangle_barycentric_coords(V0,V1,V2,inters, wgts, tol)) return true;\n        return false;\n    }    \n    assert(false && \"Something is off here...\");\n    return false;\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\nCINO_INLINE\nbool ray_triangle_intersection(const Ray   & r,\n                               const vec3d & V0,\n                               const vec3d & V1,\n                               const vec3d & V2,\n                                     vec3d & inters,\n                               const double  tol)\n{\n    Line l(r.begin(), r.begin() + r.dir());\n    if (line_triangle_intersection(l, V0, V1, V2, inters, tol))\n    {\n        vec3d u = inters - r.begin();\n        if (u.dot(r.dir()) < 0) return false;\n        return true;\n    }\n    return false;\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\nCINO_INLINE\nbool least_squares_intersection(const std::vector<Plane> & planes, vec3d & inters)\n{\n    if (planes.size() < 3) return false;\n\n    Eigen::MatrixXd A(planes.size(), 3);\n    Eigen::VectorXd b(planes.size());\n\n    int row = 0;\n    for(const Plane & p : planes)\n    {\n        A.coeffRef(row, 0) = p.a();\n        A.coeffRef(row, 1) = p.b();\n        A.coeffRef(row, 2) = p.c();\n        b[row] = p.d;\n        ++row;\n    }\n\n    // https://eigen.tuxfamily.org/dox-devel/group__LeastSquares.html\n    Eigen::Vector3d res = A.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(b);\n\n    inters[0] = res[0];\n    inters[1] = res[1];\n    inters[2] = res[2];\n\n    return true;\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\nCINO_INLINE\nbool intersection(const Ray & r, const Segment & s, vec3d & inters, const double tol)\n{\n    if (((r.dir()).cross(s.dir())).norm() == 0) return false;\n\n    std::vector<Plane> r_planes = r.to_planes();\n    std::vector<Plane> s_planes = s.to_planes();\n\n    std::vector<Plane> planes;\n    std::copy(r_planes.begin(), r_planes.end(), std::back_inserter(planes));\n    std::copy(s_planes.begin(), s_planes.end(), std::back_inserter(planes));\n\n    least_squares_intersection(planes, inters);\n\n    if (s.dist(inters) < tol && r.dist(inters) < tol) return true;\n    return false;\n}\n\n}\n", "meta": {"hexsha": "0cf946226f63832e4ffe445d6774c2918880548d", "size": 7005, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "include/cinolib/unstable/intersection.cpp", "max_stars_repo_name": "Pitz98/cinolib", "max_stars_repo_head_hexsha": "5ab98c2f15e14b63bc41d966a74cd9eaf68d7483", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 532.0, "max_stars_repo_stars_event_min_datetime": "2018-05-11T14:28:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T12:42:07.000Z", "max_issues_repo_path": "include/cinolib/unstable/intersection.cpp", "max_issues_repo_name": "zeroseven-hash/cinolib", "max_issues_repo_head_hexsha": "6df3848e708ee285cc441747c4ec05ef3735346e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 33.0, "max_issues_repo_issues_event_min_datetime": "2018-08-01T16:47:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-29T14:36:12.000Z", "max_forks_repo_path": "include/cinolib/unstable/intersection.cpp", "max_forks_repo_name": "zeroseven-hash/cinolib", "max_forks_repo_head_hexsha": "6df3848e708ee285cc441747c4ec05ef3735346e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 64.0, "max_forks_repo_forks_event_min_datetime": "2018-09-07T13:02:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T18:17:29.000Z", "avg_line_length": 40.9649122807, "max_line_length": 90, "alphanum_fraction": 0.4442541042, "num_tokens": 1410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585669110202, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.48134176418983143}}
{"text": "/**\n * @brief Control utilities for use with Eigen library\n * @author Eric Cousineau <eacousineau@gmail.com>, member of Dr. Aaron\n * Ames's AMBER Lab\n */\n#ifndef CONTROL_EIGEN_UTILITIES_LIMITS_HPP_\n    #define CONTROL_EIGEN_UTILITIES_LIMITS_HPP_\n\n#include <Eigen/Dense>\n#include <eigen_utilities/assert_size.hpp>\n#include <control_utilities/limits.hpp>\n\nnamespace control_eigen_utilities\n{\n\n/**\n * @brief clamp Clamp a vector-valued function\n * @param value\n * @param min\n * @param max\n * @param pclamped\n * @param presult\n * @return\n */\ninline bool clamp(const Eigen::VectorXd &value, const Eigen::VectorXd &min, const Eigen::VectorXd &max, Eigen::VectorXd *pclamped = NULL, Eigen::VectorXi *presult = NULL)\n{\n    int size = value.size();\n    eigen_utilities::assert_size(min, size);\n    eigen_utilities::assert_size(max, size);\n    if (pclamped)\n        pclamped->resize(size);\n    if (presult)\n        presult->resize(size);\n\n    bool is_clamped = false;\n    for (int i = 0; i < size; ++i)\n    {\n        int result;\n        double clamped = control_utilities::clamp(value.coeff(i), min.coeff(i), max.coeff(i), &result);\n        if (pclamped)\n            pclamped->coeffRef(i) = clamped;\n        if (presult)\n            presult->coeffRef(i) = result;\n        if (result != 0)\n            is_clamped = true;\n    }\n    return is_clamped;\n}\n\n}\n\n#endif // CONTROL_EIGEN_UTILITIES_LIMITS_HPP_\n", "meta": {"hexsha": "0903e0f56088bbbfa5fef2f80aa5d19be4ccb347", "size": 1391, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "control_eigen_utilities/include/control_eigen_utilities/limits.hpp", "max_stars_repo_name": "eacousineau/amber_developer_stack", "max_stars_repo_head_hexsha": "068acd416b2929ffd4fa561cc100be3eef90ad44", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "control_eigen_utilities/include/control_eigen_utilities/limits.hpp", "max_issues_repo_name": "eacousineau/amber_developer_stack", "max_issues_repo_head_hexsha": "068acd416b2929ffd4fa561cc100be3eef90ad44", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "control_eigen_utilities/include/control_eigen_utilities/limits.hpp", "max_forks_repo_name": "eacousineau/amber_developer_stack", "max_forks_repo_head_hexsha": "068acd416b2929ffd4fa561cc100be3eef90ad44", "max_forks_repo_licenses": ["BSD-3-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.2452830189, "max_line_length": 170, "alphanum_fraction": 0.6635514019, "num_tokens": 363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.4813417621057444}}
{"text": "#include <iostream>\n#include <typeinfo>\r\n#define BOOST_TEST_MODULE SparseMIAMultTests\n#include \"MIAConfig.h\"\r\n#ifdef MIA_USE_HEADER_ONLY_TESTS\r\n#include <boost/test/included/unit_test.hpp>\r\n#else\r\n#include <boost/test/unit_test.hpp>\r\n#endif\r\n\n#include \"SparseMIA.h\"\r\n#include \"DenseMIA.h\"\n#include \"Index.h\"\n#include \"LibMIAUtil.h\"\n#include \"FunctionUtil.h\"\n\n\n\r\ntemplate<class _data_type>\r\nvoid mult_work(size_t dim1, size_t dim2){\r\n\r\n    LibMIA::MIAINDEX i;\n    LibMIA::MIAINDEX j;\n    LibMIA::MIAINDEX k;\r\n    LibMIA::MIAINDEX l;\r\n    LibMIA::MIAINDEX m;\r\n    LibMIA::MIAINDEX n;\n\n    LibMIA::DenseMIA<_data_type,4> dense_a(dim1,dim2,dim1,dim2);\r\n    LibMIA::DenseMIA<_data_type,4> dense_b(dim2,dim2,dim1,dim1);\r\n    LibMIA::DenseMIA<_data_type,4> dense_c;\r\n    LibMIA::DenseMIA<_data_type,2> dense_c2;\r\n    LibMIA::DenseMIA<_data_type,3> dense_c3;\r\n    LibMIA::DenseMIA<_data_type,2> dense_b2(dim2,dim2);\r\n    LibMIA::DenseMIA<_data_type,1> dense_d(dim2);\r\n    LibMIA::DenseMIA<_data_type,2> dense_d2(dim2,dim2);\r\n\r\n    LibMIA::SparseMIA<_data_type,4> a(dim1,dim2,dim1,dim2);\r\n    LibMIA::SparseMIA<_data_type,4> b(dim2,dim2,dim1,dim1);\r\n    LibMIA::SparseMIA<_data_type,4> c;\r\n    LibMIA::SparseMIA<_data_type,2> c2;\r\n    LibMIA::SparseMIA<_data_type,3> c3;\r\n    LibMIA::SparseMIA<_data_type,2> b2(dim2,dim2);\r\n    LibMIA::SparseMIA<_data_type,1> d(dim2);\r\n    LibMIA::SparseMIA<_data_type,2> d2(dim2,dim2);\r\n\r\n\r\n    dense_a.randu(0,20);\r\n    dense_b.randu(0,20);\r\n    dense_b2.randu(0,20);\r\n    dense_d.randu(0,20);\r\n    dense_d2.randu(0,20);\r\n\r\n    for(auto it=dense_a.data_begin();it<dense_a.data_end();++it)\r\n        if(*it<15)\r\n            *it=0;\r\n    for(auto it=dense_b.data_begin();it<dense_b.data_end();++it)\r\n        if(*it<15)\r\n            *it=0;\r\n    for(auto it=dense_b2.data_begin();it<dense_b2.data_end();++it)\r\n        if(*it<15)\r\n            *it=0;\r\n    for(auto it=dense_d.data_begin();it<dense_d.data_end();++it)\r\n        if(*it<15)\r\n            *it=0;\r\n    for(auto it=dense_d2.data_begin();it<dense_d2.data_end();++it)\r\n        if(*it<15)\r\n            *it=0;\r\n\r\n    a=dense_a;\r\n    b=dense_b;\r\n    b2=dense_b2;\r\n    d=dense_d;\r\n    d2=dense_d2;\r\n\r\n    dense_c(i,k,m,n)=dense_a(i,j,k,l)*dense_b(j,l,m,n);\r\n    c(i,k,m,n)=a(i,j,k,l)*b(j,l,m,n);\r\n\r\n    BOOST_CHECK_MESSAGE(c.fuzzy_equals(dense_c,test_precision<_data_type>()),std::string(\"Inner/Outer Product 1 for \")+typeid(_data_type).name() );\r\n//    std::cout << \"Sparse \" << std::endl;\r\n//    c.print();\r\n//    std::cout << \"Dense \" << std::endl;\r\n//    dense_c.print();\r\n\r\n\r\n    dense_c(l,k,m,n)=dense_a(i,j,m,n)*dense_a(k,l,i,j);\r\n    c(l,k,m,n)=a(i,j,m,n)*a(k,l,i,j);\r\n    BOOST_CHECK_MESSAGE(c.fuzzy_equals(dense_c,test_precision<_data_type>()),std::string(\"Inner/Outer Product 1 with self-multiplication for \")+typeid(_data_type).name() ); //test the self-multiplication\r\n\r\n    dense_c(i,k,m,n)=dense_a(i,l,k,j)*dense_b(l,j,m,n);\r\n    c(i,k,m,n)=a(i,l,k,j)*b(l,j,m,n);\r\n    BOOST_CHECK_MESSAGE(c.fuzzy_equals(dense_c,test_precision<_data_type>()),std::string(\"Inner/Outer Product 2 for \")+typeid(_data_type).name());\r\n\r\n    dense_c(i,k,m,n)=dense_a(i,l,k,j)*dense_b(l,j,m,n);\r\n    c(i,k,m,n)=a(i,l,k,j)*b(l,j,m,n);\r\n    BOOST_CHECK_MESSAGE(c.fuzzy_equals(dense_c,test_precision<_data_type>()),std::string(\"Inner/Outer Product 3 for \")+typeid(_data_type).name());\r\n\r\n\r\n    dense_c2(i,j)=dense_a(!i,k,!j,l)*dense_b(k,l,!i,!j);\r\n    c2(i,j)=a(!i,k,!j,l)*b(k,l,!i,!j);\r\n    BOOST_CHECK_MESSAGE(c2.fuzzy_equals(dense_c2,test_precision<_data_type>()),std::string(\"Inner/Element-Wise Product 1 for \")+typeid(_data_type).name());\r\n\r\n    dense_c2(i,j)=dense_a(!i,l,!j,k)*dense_b(k,l,!i,!j);\r\n    c2(i,j)=a(!i,l,!j,k)*b(k,l,!i,!j);\r\n    BOOST_CHECK_MESSAGE(c2.fuzzy_equals(dense_c2,test_precision<_data_type>()),std::string(\"Inner/Element-Wise Product 2 for \")+typeid(_data_type).name());\r\n\r\n    dense_c2(j,i)=dense_a(!j,l,!i,k)*dense_b(k,l,!j,!i);\r\n    c2(j,i)=a(!j,l,!i,k)*b(k,l,!j,!i);\r\n    BOOST_CHECK_MESSAGE(c2.fuzzy_equals(dense_c2,test_precision<_data_type>()),std::string(\"Inner/Element-Wise Product 3 for \")+typeid(_data_type).name());\r\n\r\n\r\n    dense_c(i,j,k,l)=dense_b2(i,j)*dense_d2(k,l);\r\n    c(i,j,k,l)=b2(i,j)*d2(k,l);\r\n    //dense_c.print();\r\n    //c.print();\r\n    BOOST_CHECK_MESSAGE(c.fuzzy_equals(dense_c,test_precision<_data_type>()),std::string(\"Outer/Outer Product 1 for \")+typeid(_data_type).name());\r\n\r\n    dense_c(i,k,l,j)=dense_b2(k,j)*dense_d2(l,i);\r\n    c(i,k,l,j)=b2(k,j)*d2(l,i);\r\n    BOOST_CHECK_MESSAGE(c.fuzzy_equals(dense_c,test_precision<_data_type>()),std::string(\"Outer/Outer Product 2 for \")+typeid(_data_type).name());\r\n\r\n    dense_c(i,k,l,j)=dense_d2(l,i)*dense_b2(k,j);\r\n    c(i,k,l,j)=d2(l,i)*b2(k,j);\r\n    BOOST_CHECK_MESSAGE(c.fuzzy_equals(dense_c,test_precision<_data_type>()),std::string(\"Outer/Outer Product 3 for \")+typeid(_data_type).name());\r\n\r\n    dense_c(i,j,k,l)=dense_a(i,!j,k,!l)*dense_b2(!j,!l);\r\n    c(i,j,k,l)=a(i,!j,k,!l)*b2(!j,!l);\r\n    BOOST_CHECK_MESSAGE(c.fuzzy_equals(dense_c,test_precision<_data_type>()),std::string(\"Outer/Element-Wise Product 1 for \")+typeid(_data_type).name());\r\n\r\n    dense_c3(i,j,l)=dense_b2(i,!j)*dense_b2(!j,l);\r\n    c3(i,j,l)=b2(i,!j)*b2(!j,l);\r\n    BOOST_CHECK_MESSAGE(c3.fuzzy_equals(dense_c3,test_precision<_data_type>()),std::string(\"Outer/Element-Wise Product 1 with self-multiplication for \")+typeid(_data_type).name()); //test the self-multiplication\r\n\r\n    dense_c(i,j,k,l)=dense_a(k,!j,i,!l)*dense_b2(!j,!l);\r\n    c(i,j,k,l)=a(k,!j,i,!l)*b2(!j,!l);\r\n    BOOST_CHECK_MESSAGE(c.fuzzy_equals(dense_c,test_precision<_data_type>()),std::string(\"Outer/Element-Wise Product 2 for \")+typeid(_data_type).name());\r\n\r\n    dense_c(i,j,k,l)=dense_a(k,!l,i,!j)*dense_b2(!j,!l);\r\n    c(i,j,k,l)=a(k,!l,i,!j)*b2(!j,!l);\r\n    BOOST_CHECK_MESSAGE(c.fuzzy_equals(dense_c,test_precision<_data_type>()),std::string(\"Outer/Element-Wise Product 3 for \")+typeid(_data_type).name());\r\n\r\n    dense_c(i,j,k,l)=~(dense_a(i,!j,k,!!l)*dense_b2(!j,!!l))*dense_d(!l);\r\n    c(i,j,k,l)=~(a(i,!j,k,!!l)*b2(!j,!!l))*d(!l);\r\n    BOOST_CHECK_MESSAGE(c.fuzzy_equals(dense_c,test_precision<_data_type>()),std::string(\"Repeated Element-Wise Product 1 for \")+typeid(_data_type).name());\r\n\r\n\r\n    dense_c(i,k,m,n)=~(dense_a(i,!j,k,!l)*dense_b(!j,!l,m,n))*dense_d2(j,l);\r\n    c(i,k,m,n)=~(a(i,!j,k,!l)*b(!j,!l,m,n))*d2(j,l);\r\n    BOOST_CHECK_MESSAGE(c.fuzzy_equals(dense_c,test_precision<_data_type>()),std::string(\"Ternary Inner Product 1 for \")+typeid(_data_type).name() );\r\n\r\n    dense_c(i,k,m,n)=~(dense_a(i,!j,k,!l)*dense_b(!j,!l,m,n))*dense_d2(l,j);\r\n    c(i,k,m,n)=~(a(i,!j,k,!l)*b(!j,!l,m,n))*d2(l,j);\r\n    BOOST_CHECK_MESSAGE(c.fuzzy_equals(dense_c,test_precision<_data_type>()),std::string(\"Ternary Inner Product 2 for \")+typeid(_data_type).name() );\r\n\r\n    dense_c(i,k,m,n)=~(dense_a(i,!l,k,!j)*dense_b(!j,!l,m,n))*dense_d2(l,j);\r\n    c(i,k,m,n)=~(a(i,!l,k,!j)*b(!j,!l,m,n))*d2(l,j);\r\n    BOOST_CHECK_MESSAGE(c.fuzzy_equals(dense_c,test_precision<_data_type>()),std::string(\"Ternary Inner Product 3 for \")+typeid(_data_type).name() );\r\n\r\n    _data_type dense_data=dense_a(i,l,k,j)*dense_b(i,l,j,k);\r\n    _data_type sparse_data=a(i,l,k,j)*b(i,l,j,k);\r\n\r\n    BOOST_CHECK_MESSAGE(LibMIA::isEqualFuzzy(dense_data,sparse_data,test_precision<_data_type>()),std::string(\"Complete Inner Product test 1 for \")+typeid(_data_type).name() );\r\n\r\n    dense_data=dense_a(i,l,k,j)*dense_a(i,j,k,l);\r\n    sparse_data=a(i,l,k,j)*a(i,j,k,l);\r\n    BOOST_CHECK_MESSAGE(LibMIA::isEqualFuzzy(dense_data,sparse_data,test_precision<_data_type>()),std::string(\"Complete Inner Product test 1 with self-assignment for \")+typeid(_data_type).name() );\r\n\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE( SparseMIAMultTests )\n{\n\n    //mult_work<double>(3,4);\n//    mult_work<float>(3,3);\r\n//    mult_work<int>(3,3);\r\n//    mult_work<long>(3,3);\r\n//\r\n//\r\n\r\n\r\n    mult_work<double>(8,5);\n    mult_work<float>(8,5);\r\n    mult_work<int>(8,5);\r\n    mult_work<long>(8,5);\r\n\r\n\r\n\r\n    mult_work<double>(5,8);\n    mult_work<float>(5,8);\r\n    mult_work<int>(5,8);\r\n    mult_work<long>(5,8);\r\n\n\n}\n", "meta": {"hexsha": "215cdaf9711690b32b538df890d34802be25dfae", "size": 8071, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tests/SparseMIA/sparse_mia_mult_test.cpp", "max_stars_repo_name": "extragoya/LibNT", "max_stars_repo_head_hexsha": "60372bf4e3c5d6665185358c4756da4fe547f093", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-26T05:11:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-26T05:11:32.000Z", "max_issues_repo_path": "src/tests/SparseMIA/sparse_mia_mult_test.cpp", "max_issues_repo_name": "extragoya/LibNT", "max_issues_repo_head_hexsha": "60372bf4e3c5d6665185358c4756da4fe547f093", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/SparseMIA/sparse_mia_mult_test.cpp", "max_forks_repo_name": "extragoya/LibNT", "max_forks_repo_head_hexsha": "60372bf4e3c5d6665185358c4756da4fe547f093", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-09-21T15:38:23.000Z", "max_forks_repo_forks_event_max_datetime": "2017-09-21T15:38:23.000Z", "avg_line_length": 41.3897435897, "max_line_length": 212, "alphanum_fraction": 0.6442819973, "num_tokens": 2701, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300048, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.48134176210574436}}
{"text": "//=======================================================================\n// Copyright (c) 2018 Yi Ji\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\n#ifndef BOOST_GRAPH_MAXIMUM_WEIGHTED_MATCHING_HPP\n#define BOOST_GRAPH_MAXIMUM_WEIGHTED_MATCHING_HPP\n\n#include <algorithm> // for std::iter_swap\n#include <boost/shared_ptr.hpp>\n#include <boost/make_shared.hpp>\n#include <boost/graph/max_cardinality_matching.hpp>\n\nnamespace boost\n{\n    template <typename Graph, typename MateMap, typename VertexIndexMap>\n    typename property_traits<typename property_map<Graph, edge_weight_t>::type>::value_type\n    matching_weight_sum(const Graph& g, MateMap mate, VertexIndexMap vm)\n    {\n        typedef typename graph_traits<Graph>::vertex_iterator vertex_iterator_t;\n        typedef typename graph_traits<Graph>::vertex_descriptor vertex_descriptor_t;\n        typedef typename property_traits<typename property_map<Graph, edge_weight_t>::type>::value_type edge_property_t;\n        \n        edge_property_t weight_sum = 0;\n        vertex_iterator_t vi, vi_end;\n        \n        for (boost::tie(vi,vi_end) = vertices(g); vi != vi_end; ++vi)\n        {\n            vertex_descriptor_t v = *vi;\n            if (get(mate, v) != graph_traits<Graph>::null_vertex() && get(vm, v) < get(vm, get(mate,v)))\n                weight_sum += get(edge_weight, g, edge(v,mate[v],g).first);\n        }\n        return weight_sum;\n    }\n    \n    template <typename Graph, typename MateMap>\n    inline typename property_traits<typename property_map<Graph, edge_weight_t>::type>::value_type\n    matching_weight_sum(const Graph& g, MateMap mate)\n    {\n        return matching_weight_sum(g, mate, get(vertex_index,g));\n    }\n    \n    template <typename Graph, typename MateMap, typename VertexIndexMap>\n    class weighted_augmenting_path_finder\n    {\n    public:\n        \n        template <typename T>\n        struct map_vertex_to_\n        {\n            typedef boost::iterator_property_map<typename std::vector<T>::iterator, VertexIndexMap> type;\n        };\n        typedef typename graph::detail::VERTEX_STATE vertex_state_t;\n        typedef typename graph_traits<Graph>::vertex_iterator vertex_iterator_t;\n        typedef typename graph_traits<Graph>::vertex_descriptor vertex_descriptor_t;\n        typedef typename std::vector<vertex_descriptor_t>::const_iterator vertex_vec_iter_t;\n        typedef typename graph_traits<Graph>::out_edge_iterator out_edge_iterator_t;\n        typedef typename graph_traits<Graph>::edge_descriptor edge_descriptor_t;\n        typedef typename graph_traits<Graph>::edge_iterator edge_iterator_t;\n        typedef typename property_traits<typename property_map<Graph, edge_weight_t>::type>::value_type edge_property_t;\n        typedef std::deque<vertex_descriptor_t> vertex_list_t;\n        typedef std::vector<edge_descriptor_t> edge_list_t;\n        typedef typename map_vertex_to_<vertex_descriptor_t>::type vertex_to_vertex_map_t;\n        typedef typename map_vertex_to_<edge_property_t>::type vertex_to_weight_map_t;\n        typedef typename map_vertex_to_<bool>::type vertex_to_bool_map_t;\n        typedef typename map_vertex_to_<std::pair<vertex_descriptor_t, vertex_descriptor_t> >::type vertex_to_pair_map_t;\n        typedef typename map_vertex_to_<std::pair<edge_descriptor_t, bool> >::type vertex_to_edge_map_t;\n        typedef typename map_vertex_to_<vertex_to_edge_map_t>::type vertex_pair_to_edge_map_t;\n        \n        class blossom\n        {\n        public:\n            \n            typedef boost::shared_ptr<blossom> blossom_ptr_t;\n            std::vector<blossom_ptr_t> sub_blossoms;\n            edge_property_t dual_var;\n            blossom_ptr_t father;\n\n            blossom() : dual_var(0), father(blossom_ptr_t()) {}\n            \n            // get the base vertex of a blossom by recursively getting\n            // its base sub-blossom, which is always the first one in\n            // sub_blossoms because of how we create and maintain blossoms\n            virtual vertex_descriptor_t get_base() const\n            {\n                const blossom* b = this;\n                while (!b->sub_blossoms.empty())\n                    b = b->sub_blossoms[0].get();\n                return b->get_base();\n            }\n            \n            // set a sub-blossom as a blossom's base by exchanging it\n            // with its first sub-blossom\n            void set_base(const blossom_ptr_t& sub)\n            {\n                for (blossom_iterator_t bi = sub_blossoms.begin(); bi != sub_blossoms.end(); ++bi)\n                {\n                    if (sub.get() == bi->get())\n                    {\n                        std::iter_swap(sub_blossoms.begin(), bi);\n                        break;\n                    }\n                }\n            }\n            \n            // get all vertices inside recursively\n            virtual std::vector<vertex_descriptor_t> vertices() const\n            {\n                std::vector<vertex_descriptor_t> all_vertices;\n                for (typename std::vector<blossom_ptr_t>::const_iterator bi = sub_blossoms.begin(); bi != sub_blossoms.end(); ++bi)\n                {\n                    std::vector<vertex_descriptor_t> some_vertices = (*bi)->vertices();\n                    all_vertices.insert(all_vertices.end(), some_vertices.begin(), some_vertices.end());\n                }\n                return all_vertices;\n            }\n        };\n        \n        // a trivial_blossom only has one vertex and no sub-blossom;\n        // for each vertex v, in_blossom[v] is the trivial_blossom that contains it directly\n        class trivial_blossom : public blossom\n        {\n        public:\n            trivial_blossom(vertex_descriptor_t v) : trivial_vertex(v) {}\n            virtual vertex_descriptor_t get_base() const\n            {\n                return trivial_vertex;\n            }\n            \n            virtual std::vector<vertex_descriptor_t> vertices() const\n            {\n                std::vector<vertex_descriptor_t> all_vertices;\n                all_vertices.push_back(trivial_vertex);\n                return all_vertices;\n            }\n            \n        private:\n            \n            vertex_descriptor_t trivial_vertex;\n        };\n        \n        typedef boost::shared_ptr<blossom> blossom_ptr_t;\n        typedef typename std::vector<blossom_ptr_t>::iterator blossom_iterator_t;\n        typedef typename map_vertex_to_<blossom_ptr_t>::type vertex_to_blossom_map_t;\n        \n        weighted_augmenting_path_finder(const Graph& arg_g, MateMap arg_mate, VertexIndexMap arg_vm) :\n        g(arg_g),\n        vm(arg_vm),\n        null_edge(std::pair<edge_descriptor_t, bool>(num_edges(g) == 0 ? edge_descriptor_t() : *edges(g).first, false)),\n        mate_vector(num_vertices(g)),\n        label_S_vector(num_vertices(g), graph_traits<Graph>::null_vertex()),\n        label_T_vector(num_vertices(g), graph_traits<Graph>::null_vertex()),\n        outlet_vector(num_vertices(g), graph_traits<Graph>::null_vertex()),\n        tau_idx_vector(num_vertices(g), graph_traits<Graph>::null_vertex()),\n        dual_var_vector(std::vector<edge_property_t>(num_vertices(g), std::numeric_limits<edge_property_t>::min())),\n        pi_vector(std::vector<edge_property_t>(num_vertices(g), std::numeric_limits<edge_property_t>::max())),\n        gamma_vector(std::vector<edge_property_t>(num_vertices(g), std::numeric_limits<edge_property_t>::max())),\n        tau_vector(std::vector<edge_property_t>(num_vertices(g), std::numeric_limits<edge_property_t>::max())),\n        in_blossom_vector(num_vertices(g)),\n        old_label_vector(num_vertices(g)),\n        critical_edge_vectors(num_vertices(g), std::vector<std::pair<edge_descriptor_t, bool> >(num_vertices(g), null_edge)),\n        \n        mate(mate_vector.begin(), vm),\n        label_S(label_S_vector.begin(), vm),\n        label_T(label_T_vector.begin(), vm),\n        outlet(outlet_vector.begin(), vm),\n        tau_idx(tau_idx_vector.begin(), vm),\n        dual_var(dual_var_vector.begin(), vm),\n        pi(pi_vector.begin(), vm),\n        gamma(gamma_vector.begin(), vm),\n        tau(tau_vector.begin(), vm),\n        in_blossom(in_blossom_vector.begin(), vm),\n        old_label(old_label_vector.begin(), vm)\n        {\n            vertex_iterator_t vi, vi_end;\n            edge_iterator_t ei, ei_end;\n            \n            edge_property_t max_weight = std::numeric_limits<edge_property_t>::min();\n            for (boost::tie(ei,ei_end) = edges(g); ei != ei_end; ++ei)\n                max_weight = std::max(max_weight, get(edge_weight, g, *ei));\n            \n            typename std::vector<std::vector<std::pair<edge_descriptor_t, bool> > >::iterator vei;\n            \n            for (boost::tie(vi,vi_end) = vertices(g), vei = critical_edge_vectors.begin(); vi != vi_end; ++vi, ++vei)\n            {\n                vertex_descriptor_t u = *vi;\n                mate[u] = get(arg_mate, u);\n                dual_var[u] = 2*max_weight;\n                in_blossom[u] = boost::make_shared<trivial_blossom>(u);\n                outlet[u] = u;\n                critical_edge_vector.push_back(vertex_to_edge_map_t(vei->begin(), vm));\n            }\n            \n            critical_edge = vertex_pair_to_edge_map_t(critical_edge_vector.begin(), vm);\n            \n            init();\n        }\n        \n        // return the top blossom where v is contained inside\n        blossom_ptr_t in_top_blossom(vertex_descriptor_t v) const\n        {\n            blossom_ptr_t b = in_blossom[v];\n            while (b->father != blossom_ptr_t())\n                b = b->father;\n            return b;\n        }\n        \n        // check if vertex v is in blossom b\n        bool is_in_blossom(blossom_ptr_t b, vertex_descriptor_t v) const\n        {\n            if (v == graph_traits<Graph>::null_vertex())\n                return false;\n            blossom_ptr_t vb = in_blossom[v]->father;\n            while (vb != blossom_ptr_t())\n            {\n                if (vb.get() == b.get())\n                    return true;\n                vb = vb->father;\n            }\n            return false;\n        }\n        \n        // return the base vertex of the top blossom that contains v\n        inline vertex_descriptor_t base_vertex(vertex_descriptor_t v) const\n        {\n            return in_top_blossom(v)->get_base();\n        }\n        \n        // add an existed top blossom of base vertex v into new top\n        // blossom b as its sub-blossom\n        void add_sub_blossom(blossom_ptr_t b, vertex_descriptor_t v)\n        {\n            blossom_ptr_t sub = in_top_blossom(v);\n            sub->father = b;\n            b->sub_blossoms.push_back(sub);\n            if (sub->sub_blossoms.empty())\n                return;\n            for (blossom_iterator_t bi = top_blossoms.begin(); bi != top_blossoms.end(); ++bi)\n            {\n                if (bi->get() == sub.get())\n                {\n                    top_blossoms.erase(bi);\n                    break;\n                }\n            }\n        }\n        \n        // when a top blossom is created or its base vertex getting an S-label,\n        // add all edges incident to this blossom into even_edges\n        void bloom(blossom_ptr_t b)\n        {\n            std::vector<vertex_descriptor_t> vertices_of_b = b->vertices();\n            vertex_vec_iter_t vi;\n            for (vi = vertices_of_b.begin(); vi != vertices_of_b.end(); ++vi)\n            {\n                out_edge_iterator_t oei, oei_end;\n                for (boost::tie(oei,oei_end) = out_edges(*vi, g); oei != oei_end; ++oei)\n                {\n                    if (target(*oei,g) != *vi && mate[*vi] != target(*oei,g))\n                        even_edges.push_back(*oei);\n                }\n            }\n        }\n        \n        // assigning a T-label to a non S-vertex, along with outlet and updating pi value\n        // if updated pi[v] equals zero, augment the matching from its mate vertex\n        void put_T_label(vertex_descriptor_t v, vertex_descriptor_t T_label,\n                         vertex_descriptor_t outlet_v, edge_property_t pi_v)\n        {\n            if (label_S[v] != graph_traits<Graph>::null_vertex())\n                return;\n            \n            label_T[v] = T_label;\n            outlet[v] = outlet_v;\n            pi[v] = pi_v;\n            \n            vertex_descriptor_t v_mate = mate[v];\n            if (pi[v] == 0)\n            {\n                label_T[v_mate] = graph_traits<Graph>::null_vertex();\n                label_S[v_mate] = v;\n                bloom(in_top_blossom(v_mate));\n            }\n        }\n        \n        // get the missing T-label for a to-be-expanded base vertex\n        // the missing T-label is the last vertex of the path from outlet[v] to v\n        std::pair<vertex_descriptor_t, vertex_descriptor_t> missing_label(vertex_descriptor_t b_base)\n        {\n            vertex_descriptor_t missing_outlet = outlet[b_base];\n            \n            if (outlet[b_base] == b_base)\n                return std::make_pair(graph_traits<Graph>::null_vertex(), missing_outlet);\n            \n            vertex_iterator_t vi, vi_end;\n            for (boost::tie(vi,vi_end) = vertices(g); vi != vi_end; ++vi)\n                old_label[*vi] = std::make_pair(label_T[*vi], outlet[*vi]);\n            \n            std::pair<vertex_descriptor_t, vertex_state_t> child(outlet[b_base], graph::detail::V_EVEN);\n            blossom_ptr_t b = in_blossom[child.first];\n            for (; b->father->father != blossom_ptr_t(); b = b->father);\n            child.first = b->get_base();\n            \n            if (child.first == b_base)\n                return std::make_pair(graph_traits<Graph>::null_vertex(), missing_outlet);\n            \n            while (true)\n            {\n                std::pair<vertex_descriptor_t, vertex_state_t> child_parent = parent(child, true);\n                \n                for (b = in_blossom[child_parent.first]; b->father->father != blossom_ptr_t(); b = b->father);\n                missing_outlet = child_parent.first;\n                child_parent.first = b->get_base();\n                \n                if (child_parent.first == b_base)\n                    break;\n                else\n                    child = child_parent;\n            }\n            return std::make_pair(child.first, missing_outlet);\n        }\n        \n        // expand a top blossom, put all its non-trivial sub-blossoms into top_blossoms\n        blossom_iterator_t expand_blossom(blossom_iterator_t bi, std::vector<blossom_ptr_t>& new_ones)\n        {\n            blossom_ptr_t b = *bi;\n            for (blossom_iterator_t i = b->sub_blossoms.begin(); i != b->sub_blossoms.end(); ++i)\n            {\n                blossom_ptr_t sub_blossom = *i;\n                vertex_descriptor_t sub_base = sub_blossom->get_base();\n                label_S[sub_base] = label_T[sub_base] = graph_traits<Graph>::null_vertex();\n                outlet[sub_base] = sub_base;\n                sub_blossom->father = blossom_ptr_t();\n                // new top blossoms cannot be pushed back into top_blossoms immediately,\n                // because push_back() may cause reallocation and then invalid iterators\n                if (!sub_blossom->sub_blossoms.empty())\n                    new_ones.push_back(sub_blossom);\n            }\n            return top_blossoms.erase(bi);\n        }\n        \n        // when expanding a T-blossom with base v, it requires more operations:\n        // supply the missing T-labels for new base vertices by picking the minimum tau from vertices of\n        // each corresponding new top-blossoms; when label_T[v] is null or we have a smaller tau from\n        // missing_label(v), replace T-label and outlet of v (but don't bloom v)\n        blossom_iterator_t expand_T_blossom(blossom_iterator_t bi, std::vector<blossom_ptr_t>& new_ones)\n        {\n            blossom_ptr_t b = *bi;\n            \n            vertex_descriptor_t b_base = b->get_base();\n            std::pair<vertex_descriptor_t, vertex_descriptor_t> T_and_outlet = missing_label(b_base);\n            \n            blossom_iterator_t next_bi = expand_blossom(bi, new_ones);\n            \n            for (blossom_iterator_t i = b->sub_blossoms.begin(); i != b->sub_blossoms.end(); ++i)\n            {\n                blossom_ptr_t sub_blossom = *i;\n                vertex_descriptor_t sub_base = sub_blossom->get_base();\n                vertex_descriptor_t min_tau_v = graph_traits<Graph>::null_vertex();\n                edge_property_t min_tau = std::numeric_limits<edge_property_t>::max();\n                \n                std::vector<vertex_descriptor_t> sub_vertices = sub_blossom->vertices();\n                for (vertex_vec_iter_t v = sub_vertices.begin(); v != sub_vertices.end(); ++v)\n                {\n                    if (tau[*v] < min_tau)\n                    {\n                        min_tau = tau[*v];\n                        min_tau_v = *v;\n                    }\n                }\n                \n                if (min_tau < std::numeric_limits<edge_property_t>::max())\n                    put_T_label(sub_base, tau_idx[min_tau_v], min_tau_v, tau[min_tau_v]);\n            }\n            \n            if (label_T[b_base] == graph_traits<Graph>::null_vertex() || tau[old_label[b_base].second] < pi[b_base])\n                boost::tie(label_T[b_base], outlet[b_base]) = T_and_outlet;\n            \n            return next_bi;\n        }\n        \n        // when vertices v and w are matched to each other by augmenting,\n        // we must set v/w as base vertex of any blossom who contains v/w and\n        // is a sub-blossom of their lowest (smallest) common blossom\n        void adjust_blossom(vertex_descriptor_t v, vertex_descriptor_t w)\n        {\n            blossom_ptr_t vb = in_blossom[v], wb = in_blossom[w], lowest_common_blossom;\n            std::vector<blossom_ptr_t> v_ancestors, w_ancestors;\n            \n            while (vb->father != blossom_ptr_t())\n            {\n                v_ancestors.push_back(vb->father);\n                vb = vb->father;\n            }\n            while (wb->father != blossom_ptr_t())\n            {\n                w_ancestors.push_back(wb->father);\n                wb = wb->father;\n            }\n            \n            typename std::vector<blossom_ptr_t>::reverse_iterator i, j;\n            i = v_ancestors.rbegin();\n            j = w_ancestors.rbegin();\n            while (i != v_ancestors.rend() && j != w_ancestors.rend() && i->get() == j->get())\n            {\n                lowest_common_blossom = *i;\n                ++i;++j;\n            }\n            \n            vb = in_blossom[v];\n            wb = in_blossom[w];\n            while (vb->father != lowest_common_blossom)\n            {\n                vb->father->set_base(vb);\n                vb = vb->father;\n            }\n            while (wb->father != lowest_common_blossom)\n            {\n                wb->father->set_base(wb);\n                wb = wb->father;\n            }\n        }\n        \n        // every edge weight is multiplied by 4 to ensure integer weights\n        // throughout the algorithm if all input weights are integers\n        inline edge_property_t slack(const edge_descriptor_t& e) const\n        {\n            vertex_descriptor_t v, w;\n            v = source(e, g);\n            w = target(e, g);\n            return dual_var[v] + dual_var[w] - 4*get(edge_weight, g, e);\n        }\n        \n        // backtrace one step on vertex v along the augmenting path\n        // by its labels and its vertex state;\n        // boolean parameter \"use_old\" means whether we are updating labels,\n        // if we are, then we use old labels to backtrace and also we\n        // don't jump to its base vertex when we reach an odd vertex\n        std::pair<vertex_descriptor_t, vertex_state_t> parent(std::pair<vertex_descriptor_t, vertex_state_t> v,\n                                                              bool use_old = false) const\n        {\n            if (v.second == graph::detail::V_EVEN)\n            {\n                // a paranoid check: label_S shoule be the same as mate in backtracing\n                if (label_S[v.first] == graph_traits<Graph>::null_vertex())\n                    label_S[v.first] = mate[v.first];\n                return std::make_pair(label_S[v.first], graph::detail::V_ODD);\n            }\n            else if (v.second == graph::detail::V_ODD)\n            {\n                vertex_descriptor_t w = use_old ? old_label[v.first].first : base_vertex(label_T[v.first]);\n                return std::make_pair(w, graph::detail::V_EVEN);\n            }\n            return std::make_pair(v.first, graph::detail::V_UNREACHED);\n        }\n        \n        // backtrace from vertices v and w to their free (unmatched) ancesters,\n        // return the nearest common ancestor (null_vertex if none) of v and w\n        vertex_descriptor_t nearest_common_ancestor(vertex_descriptor_t v, vertex_descriptor_t w,\n                                                    vertex_descriptor_t& v_free_ancestor,\n                                                    vertex_descriptor_t& w_free_ancestor) const\n        {\n            std::pair<vertex_descriptor_t, vertex_state_t> v_up(v, graph::detail::V_EVEN);\n            std::pair<vertex_descriptor_t, vertex_state_t> w_up(w, graph::detail::V_EVEN);\n            vertex_descriptor_t nca;\n            nca = w_free_ancestor = v_free_ancestor = graph_traits<Graph>::null_vertex();\n            \n            std::vector<bool> ancestor_of_w_vector(num_vertices(g), false);\n            std::vector<bool> ancestor_of_v_vector(num_vertices(g), false);\n            vertex_to_bool_map_t ancestor_of_w(ancestor_of_w_vector.begin(), vm);\n            vertex_to_bool_map_t ancestor_of_v(ancestor_of_v_vector.begin(), vm);\n            \n            while (nca == graph_traits<Graph>::null_vertex() &&\n                   (v_free_ancestor == graph_traits<Graph>::null_vertex() ||\n                    w_free_ancestor == graph_traits<Graph>::null_vertex()))\n            {\n                ancestor_of_w[w_up.first] = true;\n                ancestor_of_v[v_up.first] = true;\n                \n                if (w_free_ancestor == graph_traits<Graph>::null_vertex())\n                    w_up = parent(w_up);\n                if (v_free_ancestor == graph_traits<Graph>::null_vertex())\n                    v_up = parent(v_up);\n                \n                if (mate[v_up.first] == graph_traits<Graph>::null_vertex())\n                    v_free_ancestor = v_up.first;\n                if (mate[w_up.first] == graph_traits<Graph>::null_vertex())\n                    w_free_ancestor = w_up.first;\n                \n                if (ancestor_of_w[v_up.first] == true || v_up.first == w_up.first)\n                    nca = v_up.first;\n                else if (ancestor_of_v[w_up.first] == true)\n                    nca = w_up.first;\n                else if (v_free_ancestor == w_free_ancestor &&\n                         v_free_ancestor != graph_traits<Graph>::null_vertex())\n                    nca = v_up.first;\n            }\n            \n            return nca;\n        }\n        \n        // when a new top blossom b is created by connecting (v, w), we add sub-blossoms into\n        // b along backtracing from v_prime and w_prime to stop_vertex (the base vertex);\n        // also, we set labels and outlet for each base vertex we pass by\n        void make_blossom(blossom_ptr_t b, vertex_descriptor_t w_prime,\n                          vertex_descriptor_t v_prime, vertex_descriptor_t stop_vertex)\n        {\n            std::pair<vertex_descriptor_t, vertex_state_t> u(v_prime, graph::detail::V_ODD);\n            std::pair<vertex_descriptor_t, vertex_state_t> u_up(w_prime, graph::detail::V_EVEN);\n            \n            for (; u_up.first != stop_vertex; u = u_up, u_up = parent(u))\n            {\n                if (u_up.second == graph::detail::V_EVEN)\n                {\n                    if (!in_top_blossom(u_up.first)->sub_blossoms.empty())\n                        outlet[u_up.first] = label_T[u.first];\n                    label_T[u_up.first] = outlet[u.first];\n                }\n                else if (u_up.second == graph::detail::V_ODD)\n                    label_S[u_up.first] = u.first;\n                \n                add_sub_blossom(b, u_up.first);\n            }\n        }\n        \n        // the design of recursively expanding augmenting path in (reversed_)retrieve_augmenting_path\n        // functions is inspired by same functions in max_cardinality_matching.hpp;\n        // except that in weighted matching, we use \"outlet\" vertices instead of \"bridge\" vertex pairs:\n        // if blossom b is the smallest non-trivial blossom that contains its base vertex v, then\n        // v and outlet[v] are where augmenting path enters and leaves b\n        void retrieve_augmenting_path(vertex_descriptor_t v, vertex_descriptor_t w, vertex_state_t v_state)\n        {\n            if (v == w)\n                aug_path.push_back(v);\n            else if (v_state == graph::detail::V_EVEN)\n            {\n                aug_path.push_back(v);\n                retrieve_augmenting_path(label_S[v], w, graph::detail::V_ODD);\n            }\n            else if (v_state == graph::detail::V_ODD)\n            {\n                if (outlet[v] == v)\n                    aug_path.push_back(v);\n                else\n                    reversed_retrieve_augmenting_path(outlet[v], v, graph::detail::V_EVEN);\n                retrieve_augmenting_path(label_T[v], w, graph::detail::V_EVEN);\n            }\n        }\n        \n        void reversed_retrieve_augmenting_path(vertex_descriptor_t v, vertex_descriptor_t w, vertex_state_t v_state)\n        {\n            if (v == w)\n                aug_path.push_back(v);\n            else if (v_state == graph::detail::V_EVEN)\n            {\n                reversed_retrieve_augmenting_path(label_S[v], w, graph::detail::V_ODD);\n                aug_path.push_back(v);\n            }\n            else if (v_state == graph::detail::V_ODD)\n            {\n                reversed_retrieve_augmenting_path(label_T[v], w, graph::detail::V_EVEN);\n                if (outlet[v] != v)\n                    retrieve_augmenting_path(outlet[v], v, graph::detail::V_EVEN);\n                else\n                    aug_path.push_back(v);\n            }\n        }\n        \n        // correct labels for vertices in the augmenting path\n        void relabel(vertex_descriptor_t v)\n        {\n            blossom_ptr_t b = in_blossom[v]->father;\n            \n            if (!is_in_blossom(b, mate[v]))\n            { // if v is a new base vertex\n                std::pair<vertex_descriptor_t, vertex_state_t> u(v, graph::detail::V_EVEN);\n                while (label_S[u.first] != u.first && is_in_blossom(b, label_S[u.first]))\n                    u = parent(u, true);\n                \n                vertex_descriptor_t old_base = u.first;\n                if (label_S[old_base] != old_base)\n                { // if old base is not exposed\n                    label_T[v] = label_S[old_base];\n                    outlet[v] = old_base;\n                }\n                else\n                { // if old base is exposed then new label_T[v] is not in b,\n                    // we must (i) make b2 the smallest blossom containing v but not as base vertex\n                    // (ii) backtrace from b2's new base vertex to b\n                    label_T[v] = graph_traits<Graph>::null_vertex();\n                    for (b = b->father; b != blossom_ptr_t() && b->get_base() == v; b = b->father);\n                    if (b != blossom_ptr_t())\n                    {\n                        u = std::make_pair(b->get_base(), graph::detail::V_ODD);\n                        while (!is_in_blossom(in_blossom[v]->father, old_label[u.first].first))\n                            u = parent(u, true);\n                        label_T[v] = u.first;\n                        outlet[v] = old_label[u.first].first;\n                    }\n                }\n            }\n            else if (label_S[v] == v || !is_in_blossom(b, label_S[v]))\n            { // if v is an old base vertex\n                // let u be the new base vertex; backtrace from u's old T-label\n                std::pair<vertex_descriptor_t, vertex_state_t> u(b->get_base(), graph::detail::V_ODD);\n                while (old_label[u.first].first != graph_traits<Graph>::null_vertex() && old_label[u.first].first != v)\n                    u = parent(u, true);\n                label_T[v] = old_label[u.first].second;\n                outlet[v] = v;\n            }\n            else // if v is neither a new nor an old base vertex\n                label_T[v] = label_S[v];\n        }\n        \n        void augmenting(vertex_descriptor_t v, vertex_descriptor_t v_free_ancestor,\n                        vertex_descriptor_t w, vertex_descriptor_t w_free_ancestor)\n        {\n            vertex_iterator_t vi, vi_end;\n            \n            // retrieve the augmenting path and put it in aug_path\n            reversed_retrieve_augmenting_path(v, v_free_ancestor, graph::detail::V_EVEN);\n            retrieve_augmenting_path(w, w_free_ancestor, graph::detail::V_EVEN);\n            \n            // augment the matching along aug_path\n            vertex_descriptor_t a, b;\n            vertex_list_t reversed_aug_path;\n            while (!aug_path.empty())\n            {\n                a = aug_path.front();\n                aug_path.pop_front();\n                reversed_aug_path.push_back(a);\n                b = aug_path.front();\n                aug_path.pop_front();\n                reversed_aug_path.push_back(b);\n                \n                mate[a] = b;\n                mate[b] = a;\n                \n                // reset base vertex for every blossom in augment path\n                adjust_blossom(a, b);\n            }\n            \n            for (boost::tie(vi,vi_end) = vertices(g); vi != vi_end; ++vi)\n                old_label[*vi] = std::make_pair(label_T[*vi], outlet[*vi]);\n            \n            // correct labels for in-blossom vertices along aug_path\n            while (!reversed_aug_path.empty())\n            {\n                a = reversed_aug_path.front();\n                reversed_aug_path.pop_front();\n                \n                if (in_blossom[a]->father != blossom_ptr_t())\n                    relabel(a);\n            }\n            \n            for (boost::tie(vi,vi_end) = vertices(g); vi != vi_end; ++vi)\n            {\n                vertex_descriptor_t u = *vi;\n                if (mate[u] != graph_traits<Graph>::null_vertex())\n                    label_S[u] = mate[u];\n            }\n            \n            // expand blossoms with zero dual variables\n            std::vector<blossom_ptr_t> new_top_blossoms;\n            for (blossom_iterator_t bi = top_blossoms.begin(); bi != top_blossoms.end();)\n            {\n                if ((*bi)->dual_var <= 0)\n                    bi = expand_blossom(bi, new_top_blossoms);\n                else\n                    ++bi;\n            }\n            top_blossoms.insert(top_blossoms.end(), new_top_blossoms.begin(), new_top_blossoms.end());\n            init();\n        }\n        \n        // create a new blossom and set labels for vertices inside\n        void blossoming(vertex_descriptor_t v, vertex_descriptor_t v_prime,\n                        vertex_descriptor_t w, vertex_descriptor_t w_prime,\n                        vertex_descriptor_t nca)\n        {\n            vertex_iterator_t vi, vi_end;\n            \n            std::vector<bool> is_old_base_vector(num_vertices(g));\n            vertex_to_bool_map_t is_old_base(is_old_base_vector.begin(), vm);\n            for (boost::tie(vi,vi_end) = vertices(g); vi != vi_end; ++vi)\n            {\n                if (*vi == base_vertex(*vi))\n                    is_old_base[*vi] = true;\n            }\n            \n            blossom_ptr_t b = boost::make_shared<blossom>();\n            add_sub_blossom(b, nca);\n            \n            label_T[w_prime] = v;\n            label_T[v_prime] = w;\n            outlet[w_prime] = w;\n            outlet[v_prime] = v;\n            \n            make_blossom(b, w_prime, v_prime, nca);\n            make_blossom(b, v_prime, w_prime, nca);\n            \n            label_T[nca] = graph_traits<Graph>::null_vertex();\n            outlet[nca] = nca;\n            \n            top_blossoms.push_back(b);\n            bloom(b);\n            \n            // set gamma[b_base] = min_slack{critical_edge(b_base, other_base)} where each critical edge\n            // is updated before, by argmin{slack(old_bases_in_b, other_base)};\n            vertex_vec_iter_t i, j;\n            std::vector<vertex_descriptor_t> b_vertices = b->vertices(), old_base_in_b, other_base;\n            vertex_descriptor_t b_base = b->get_base();\n            for (i = b_vertices.begin(); i != b_vertices.end(); ++i)\n            {\n                if (is_old_base[*i])\n                    old_base_in_b.push_back(*i);\n            }\n            for (boost::tie(vi,vi_end) = vertices(g); vi != vi_end; ++vi)\n            {\n                if (*vi != b_base && *vi == base_vertex(*vi))\n                    other_base.push_back(*vi);\n            }\n            for (i = other_base.begin(); i != other_base.end(); ++i)\n            {\n                edge_property_t min_slack = std::numeric_limits<edge_property_t>::max();\n                std::pair<edge_descriptor_t, bool> b_vi = null_edge;\n                for (j = old_base_in_b.begin(); j != old_base_in_b.end(); ++j)\n                {\n                    if (critical_edge[*j][*i] != null_edge && min_slack > slack(critical_edge[*j][*i].first))\n                    {\n                        min_slack = slack(critical_edge[*j][*i].first);\n                        b_vi = critical_edge[*j][*i];\n                    }\n                }\n                critical_edge[b_base][*i] = critical_edge[*i][b_base] = b_vi;\n            }\n            gamma[b_base] = std::numeric_limits<edge_property_t>::max();\n            for (i = other_base.begin(); i != other_base.end(); ++i)\n            {\n                if (critical_edge[b_base][*i] != null_edge)\n                    gamma[b_base] = std::min(gamma[b_base], slack(critical_edge[b_base][*i].first));\n            }\n        }\n        \n        void init()\n        {\n            even_edges.clear();\n            \n            vertex_iterator_t vi, vi_end;\n            typename std::vector<std::vector<std::pair<edge_descriptor_t, bool> > >::iterator vei;\n            \n            for (boost::tie(vi,vi_end) = vertices(g), vei = critical_edge_vectors.begin(); vi != vi_end; ++vi, ++vei)\n            {\n                vertex_descriptor_t u = *vi;\n                out_edge_iterator_t ei, ei_end;\n                \n                gamma[u] = tau[u] = pi[u] = std::numeric_limits<edge_property_t>::max();\n                std::fill(vei->begin(), vei->end(), null_edge);\n                \n                if (base_vertex(u) != u)\n                    continue;\n                \n                label_S[u] = label_T[u] = graph_traits<Graph>::null_vertex();\n                outlet[u] = u;\n                \n                if (mate[u] == graph_traits<Graph>::null_vertex())\n                {\n                    label_S[u] = u;\n                    bloom(in_top_blossom(u));\n                }\n            }\n        }\n        \n        bool augment_matching()\n        {\n            vertex_descriptor_t v, w, w_free_ancestor, v_free_ancestor;\n            v = w = w_free_ancestor = v_free_ancestor = graph_traits<Graph>::null_vertex();\n            bool found_alternating_path = false;\n            \n            // note that we only use edges of zero slack value for augmenting\n            while (!even_edges.empty() && !found_alternating_path)\n            {\n                // search for augmenting paths depth-first\n                edge_descriptor_t current_edge = even_edges.back();\n                even_edges.pop_back();\n                \n                v = source(current_edge, g);\n                w = target(current_edge, g);\n                \n                vertex_descriptor_t v_prime = base_vertex(v);\n                vertex_descriptor_t w_prime = base_vertex(w);\n                \n                // w_prime == v_prime implies that we get an edge that has been shrunk into a blossom\n                if (v_prime == w_prime)\n                    continue;\n                \n                // a paranoid check\n                if (label_S[v_prime] == graph_traits<Graph>::null_vertex())\n                {\n                    std::swap(v_prime, w_prime);\n                    std::swap(v, w);\n                }\n                \n                // w_prime may be unlabeled or have a T-label; replace the existed T-label if the edge slack\n                // is smaller than current pi[w_prime] and update it. Note that a T-label is \"deserved\" only when pi equals zero.\n                // also update tau and tau_idx so that tau_idx becomes T-label when a T-blossom is expanded\n                if (label_S[w_prime] == graph_traits<Graph>::null_vertex())\n                {\n                    if (slack(current_edge) < pi[w_prime])\n                        put_T_label(w_prime, v, w, slack(current_edge));\n                    if (slack(current_edge) < tau[w])\n                    {\n                        if (in_blossom[w]->father == blossom_ptr_t() || label_T[w_prime] == v ||\n                            label_T[w_prime] == graph_traits<Graph>::null_vertex() ||\n                            nearest_common_ancestor(v_prime, label_T[w_prime],\n                                                    v_free_ancestor, w_free_ancestor) == graph_traits<Graph>::null_vertex())\n                        {\n                            tau[w] = slack(current_edge);\n                            tau_idx[w] = v;\n                        }\n                    }\n                }\n                \n                else\n                {\n                    if (slack(current_edge) > 0)\n                    {\n                        // update gamma and critical_edges when we have a smaller edge slack\n                        gamma[v_prime] = std::min(gamma[v_prime], slack(current_edge));\n                        gamma[w_prime] = std::min(gamma[w_prime], slack(current_edge));\n                        if (critical_edge[v_prime][w_prime] == null_edge ||\n                            slack(critical_edge[v_prime][w_prime].first) > slack(current_edge))\n                        {\n                            critical_edge[v_prime][w_prime] = std::pair<edge_descriptor_t, bool>(current_edge, true);\n                            critical_edge[w_prime][v_prime] = std::pair<edge_descriptor_t, bool>(current_edge, true);\n                        }\n                        continue;\n                    }\n                    else if (slack(current_edge) == 0)\n                    {\n                        // if nca is null_vertex then we have an augmenting path; otherwise we have\n                        // a new top blossom with nca as its base vertex\n                        vertex_descriptor_t nca = nearest_common_ancestor(v_prime, w_prime, v_free_ancestor, w_free_ancestor);\n                        \n                        if (nca == graph_traits<Graph>::null_vertex())\n                            found_alternating_path = true; //to break out of the loop\n                        else\n                            blossoming(v, v_prime, w, w_prime, nca);\n                    }\n                }\n            }\n            \n            if (!found_alternating_path)\n                return false;\n            \n            augmenting(v, v_free_ancestor, w, w_free_ancestor);\n            return true;\n        }\n        \n        // slack the vertex and blossom dual variables when there is no augmenting path found\n        // according to the primal-dual method\n        bool adjust_dual()\n        {\n            edge_property_t delta1, delta2, delta3, delta4, delta;\n            delta1 = delta2 = delta3 = delta4 = std::numeric_limits<edge_property_t>::max();\n            \n            vertex_iterator_t vi, vi_end;\n            \n            for (boost::tie(vi,vi_end) = vertices(g); vi != vi_end; ++vi)\n            {\n                delta1 = std::min(delta1, dual_var[*vi]);\n                delta4 = pi[*vi] > 0 ? std::min(delta4, pi[*vi]) : delta4;\n                if (*vi == base_vertex(*vi))\n                    delta3 = std::min(delta3, gamma[*vi]/2);\n            }\n            \n            for (blossom_iterator_t bi = top_blossoms.begin(); bi != top_blossoms.end(); ++bi)\n            {\n                vertex_descriptor_t b_base = (*bi)->get_base();\n                if (label_T[b_base] != graph_traits<Graph>::null_vertex() && pi[b_base] == 0)\n                    delta2 = std::min(delta2, (*bi)->dual_var/2);\n            }\n            \n            delta = std::min(std::min(delta1, delta2), std::min(delta3, delta4));\n            \n            // start updating dual variables, note that the order is important\n            \n            for (boost::tie(vi,vi_end) = vertices(g); vi != vi_end; ++vi)\n            {\n                vertex_descriptor_t v = *vi, v_prime = base_vertex(v);\n                \n                if (label_S[v_prime] != graph_traits<Graph>::null_vertex())\n                    dual_var[v] -= delta;\n                else if (label_T[v_prime] != graph_traits<Graph>::null_vertex() && pi[v_prime] == 0)\n                    dual_var[v] += delta;\n                \n                if (v == v_prime)\n                    gamma[v] -= 2*delta;\n            }\n            \n            for (boost::tie(vi,vi_end) = vertices(g); vi != vi_end; ++vi)\n            {\n                vertex_descriptor_t v_prime = base_vertex(*vi);\n                if (pi[v_prime] > 0)\n                    tau[*vi] -= delta;\n            }\n            \n            for (blossom_iterator_t bi = top_blossoms.begin(); bi != top_blossoms.end(); ++bi)\n            {\n                vertex_descriptor_t b_base = (*bi)->get_base();\n                if (label_T[b_base] != graph_traits<Graph>::null_vertex() && pi[b_base] == 0)\n                    (*bi)->dual_var -= 2*delta;\n                if (label_S[b_base] != graph_traits<Graph>::null_vertex())\n                    (*bi)->dual_var += 2*delta;\n            }\n            \n            for (boost::tie(vi,vi_end) = vertices(g); vi != vi_end; ++vi)\n            {\n                vertex_descriptor_t v = *vi;\n                if (pi[v] > 0)\n                    pi[v] -= delta;\n                \n                // when some T-vertices have zero pi value, bloom their mates so that matching can be further augmented\n                if (label_T[v] != graph_traits<Graph>::null_vertex() && pi[v] == 0)\n                    put_T_label(v, label_T[v], outlet[v], pi[v]);\n            }\n            \n            \n            // optimal solution reached, halt\n            if (delta == delta1)\n                return false;\n            \n            // expand odd blossoms with zero dual variables and zero pi value of their base vertices\n            if (delta == delta2 && delta != delta3)\n            {\n                std::vector<blossom_ptr_t> new_top_blossoms;\n                for (blossom_iterator_t bi = top_blossoms.begin(); bi != top_blossoms.end();)\n                {\n                    const blossom_ptr_t b = *bi;\n                    vertex_descriptor_t b_base = b->get_base();\n                    if (b->dual_var == 0 && label_T[b_base] != graph_traits<Graph>::null_vertex() && pi[b_base] == 0)\n                        bi = expand_T_blossom(bi, new_top_blossoms);\n                    else\n                        ++bi;\n                }\n                top_blossoms.insert(top_blossoms.end(), new_top_blossoms.begin(), new_top_blossoms.end());\n            }\n            \n            while (true)\n            {\n                // find a zero-slack critical edge (v, w) of zero gamma values\n                std::pair<edge_descriptor_t, bool> best_edge = null_edge;\n                std::vector<vertex_descriptor_t> base_nodes;\n                for (boost::tie(vi,vi_end) = vertices(g); vi != vi_end; ++vi)\n                {\n                    if (*vi == base_vertex(*vi))\n                        base_nodes.push_back(*vi);\n                }\n                for (vertex_vec_iter_t i = base_nodes.begin(); i != base_nodes.end(); ++i)\n                {\n                    if (gamma[*i] == 0)\n                    {\n                        for (vertex_vec_iter_t j = base_nodes.begin(); j != base_nodes.end(); ++j)\n                        {\n                            if (critical_edge[*i][*j] != null_edge && slack(critical_edge[*i][*j].first) == 0)\n                                best_edge = critical_edge[*i][*j];\n                        }\n                    }\n                }\n                \n                // if not found, continue finding other augment matching\n                if (best_edge == null_edge)\n                {\n                    bool augmented = augment_matching();\n                    return augmented || delta != delta1;\n                }\n                // if found, determine either augmenting or blossoming\n                vertex_descriptor_t v = source(best_edge.first, g), w = target(best_edge.first, g);\n                vertex_descriptor_t v_prime = base_vertex(v), w_prime = base_vertex(w), v_free_ancestor, w_free_ancestor;\n                vertex_descriptor_t nca = nearest_common_ancestor(v_prime, w_prime, v_free_ancestor, w_free_ancestor);\n                if (nca == graph_traits<Graph>::null_vertex())\n                {\n                    augmenting(v, v_free_ancestor, w, w_free_ancestor);\n                    return true;\n                }\n                else\n                    blossoming(v, v_prime, w, w_prime, nca);\n            }\n            \n            return false;\n        }\n        \n        template <typename PropertyMap>\n        void get_current_matching(PropertyMap pm)\n        {\n            vertex_iterator_t vi, vi_end;\n            for (boost::tie(vi,vi_end) = vertices(g); vi != vi_end; ++vi)\n                put(pm, *vi, mate[*vi]);\n        }\n        \n    private:\n        \n        const Graph& g;\n        VertexIndexMap vm;\n        const std::pair<edge_descriptor_t, bool> null_edge;\n        \n        // storage for the property maps below\n        std::vector<vertex_descriptor_t> mate_vector;\n        std::vector<vertex_descriptor_t> label_S_vector, label_T_vector;\n        std::vector<vertex_descriptor_t> outlet_vector;\n        std::vector<vertex_descriptor_t> tau_idx_vector;\n        std::vector<edge_property_t> dual_var_vector;\n        std::vector<edge_property_t> pi_vector, gamma_vector, tau_vector;\n        std::vector<blossom_ptr_t> in_blossom_vector;\n        std::vector<std::pair<vertex_descriptor_t, vertex_descriptor_t> > old_label_vector;\n        std::vector<vertex_to_edge_map_t> critical_edge_vector;\n        std::vector<std::vector<std::pair<edge_descriptor_t, bool> > > critical_edge_vectors;\n        \n        // iterator property maps\n        vertex_to_vertex_map_t mate;\n        vertex_to_vertex_map_t label_S; // v has an S-label -> v can be an even vertex, label_S[v] is its mate\n        vertex_to_vertex_map_t label_T; // v has a T-label -> v can be an odd vertex, label_T[v] is its predecessor in aug_path\n        vertex_to_vertex_map_t outlet;\n        vertex_to_vertex_map_t tau_idx;\n        vertex_to_weight_map_t dual_var;\n        vertex_to_weight_map_t pi, gamma, tau;\n        vertex_to_blossom_map_t in_blossom; // map any vertex v to the trivial blossom containing v\n        vertex_to_pair_map_t old_label; // <old T-label, old outlet> before relabeling or expanding T-blossoms\n        vertex_pair_to_edge_map_t critical_edge; // an not matched edge (v, w) is critical if v and w belongs to different S-blossoms\n        \n        vertex_list_t aug_path;\n        edge_list_t even_edges;\n        std::vector<blossom_ptr_t> top_blossoms;\n        \n    };\n    \n    template <typename Graph, typename MateMap, typename VertexIndexMap>\n    void maximum_weighted_matching(const Graph& g, MateMap mate, VertexIndexMap vm)\n    {\n        empty_matching<Graph, MateMap>::find_matching(g, mate);\n        weighted_augmenting_path_finder<Graph, MateMap, VertexIndexMap> augmentor(g, mate, vm);\n        \n        // can have |V| times augmenting at most\n        for (std::size_t t = 0; t < num_vertices(g); ++t)\n        {\n            bool augmented = false;\n            while (!augmented)\n            {\n                augmented = augmentor.augment_matching();\n                if (!augmented)\n                {\n                    // halt if adjusting dual variables can't bring potential augment\n                    if (!augmentor.adjust_dual())\n                        break;\n                }\n            }\n            if (!augmented)\n                break;\n        }\n        \n        augmentor.get_current_matching(mate);\n    }\n    \n    template <typename Graph, typename MateMap>\n    inline void maximum_weighted_matching(const Graph& g, MateMap mate)\n    {\n        maximum_weighted_matching(g, mate, get(vertex_index,g));\n    }\n    \n    // brute-force matcher searches all possible combinations of matched edges to get the maximum weighted matching\n    // which can be used for testing on small graphs (within dozens vertices)\n    template <typename Graph, typename MateMap, typename VertexIndexMap>\n    class brute_force_matching\n    {\n    public:\n        \n        typedef typename graph_traits<Graph>::vertex_descriptor vertex_descriptor_t;\n        typedef typename graph_traits<Graph>::vertex_iterator vertex_iterator_t;\n        typedef typename std::vector<vertex_descriptor_t>::iterator vertex_vec_iter_t;\n        typedef typename graph_traits<Graph>::edge_iterator edge_iterator_t;\n        typedef boost::iterator_property_map<vertex_vec_iter_t, VertexIndexMap> vertex_to_vertex_map_t;\n        \n        brute_force_matching(const Graph& arg_g, MateMap arg_mate, VertexIndexMap arg_vm) :\n        g(arg_g),\n        vm(arg_vm),\n        mate_vector(num_vertices(g)),\n        best_mate_vector(num_vertices(g)),\n        mate(mate_vector.begin(), vm),\n        best_mate(best_mate_vector.begin(), vm)\n        {\n            vertex_iterator_t vi,vi_end;\n            for (boost::tie(vi,vi_end) = vertices(g); vi != vi_end; ++vi)\n                best_mate[*vi] = mate[*vi] = get(arg_mate, *vi);\n        }\n        \n        template <typename PropertyMap>\n        void find_matching(PropertyMap pm)\n        {\n            edge_iterator_t ei;\n            boost::tie(ei, ei_end) = edges(g);\n            select_edge(ei);\n            \n            vertex_iterator_t vi,vi_end;\n            for (boost::tie(vi,vi_end) = vertices(g); vi != vi_end; ++vi)\n                put(pm, *vi, best_mate[*vi]);\n        }\n        \n    private:\n        \n        const Graph& g;\n        VertexIndexMap vm;\n        std::vector<vertex_descriptor_t> mate_vector, best_mate_vector;\n        vertex_to_vertex_map_t mate, best_mate;\n        edge_iterator_t ei_end;\n        \n        void select_edge(edge_iterator_t ei)\n        {\n            if (ei == ei_end)\n            {\n                if (matching_weight_sum(g, mate) > matching_weight_sum(g, best_mate))\n                {\n                    vertex_iterator_t vi, vi_end;\n                    for (boost::tie(vi,vi_end) = vertices(g); vi != vi_end; ++vi)\n                        best_mate[*vi] = mate[*vi];\n                }\n                return;\n            }\n            \n            vertex_descriptor_t v, w;\n            v = source(*ei, g);\n            w = target(*ei, g);\n            \n            select_edge(++ei);\n            \n            if (mate[v] == graph_traits<Graph>::null_vertex() &&\n                mate[w] == graph_traits<Graph>::null_vertex())\n            {\n                mate[v] = w;\n                mate[w] = v;\n                select_edge(ei);\n                mate[v] = mate[w] = graph_traits<Graph>::null_vertex();\n            }\n        }\n        \n    };\n    \n    template <typename Graph, typename MateMap, typename VertexIndexMap>\n    void brute_force_maximum_weighted_matching(const Graph& g, MateMap mate, VertexIndexMap vm)\n    {\n        empty_matching<Graph, MateMap>::find_matching(g, mate);\n        brute_force_matching<Graph, MateMap, VertexIndexMap> brute_force_matcher(g, mate, vm);\n        brute_force_matcher.find_matching(mate);\n    }\n    \n    template <typename Graph, typename MateMap>\n    inline void brute_force_maximum_weighted_matching(const Graph& g, MateMap mate)\n    {\n        brute_force_maximum_weighted_matching(g, mate, get(vertex_index, g));\n    }\n    \n}\n\n#endif\n", "meta": {"hexsha": "6fbc4dd422a0aec910087b3c7c61b703ad68f6b4", "size": 52697, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/graph/maximum_weighted_matching.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/maximum_weighted_matching.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/maximum_weighted_matching.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": 45.1172945205, "max_line_length": 133, "alphanum_fraction": 0.5350778982, "num_tokens": 11416, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.4813417572057085}}
{"text": "\n// Copyright 2019 Peter Dimov.\n//\n// Distributed under the Boost Software License, Version 1.0.\n//\n// See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt\n\n\n#include <boost/mp11/algorithm.hpp>\n#include <boost/mp11/list.hpp>\n#include <boost/mp11/integral.hpp>\n#include <boost/core/lightweight_test_trait.hpp>\n\nusing boost::mp11::mp_int;\n\ntemplate<class N> using mod_2 = mp_int<N::value % 2>;\ntemplate<class N> using mod_3 = mp_int<N::value % 3>;\ntemplate<class N> using mod_6 = mp_int<N::value % 6>;\n\nusing boost::mp11::mp_not;\nusing boost::mp11::mp_plus;\n\ntemplate<class T> using P1 = mp_not<mod_6<T>>;\ntemplate<class T1, class... T> using P2 = mp_not<mp_plus<T...>>;\n\nusing boost::mp11::mp_bool;\n\ntemplate<std::size_t N> struct second_is\n{\n    template<class T1, class T2> using fn = mp_bool< T2::value == N >;\n};\n\nusing boost::mp11::mp_first;\nusing boost::mp11::mp_filter_q;\nusing boost::mp11::mp_iota;\nusing boost::mp11::mp_size;\n\ntemplate<class L, std::size_t N> using at_c = mp_first< mp_filter_q< second_is<N>, L, mp_iota<mp_size<L>> > >;\n\nint main()\n{\n    using boost::mp11::mp_iota_c;\n    using boost::mp11::mp_filter;\n    using boost::mp11::mp_list;\n    using boost::mp11::mp_size_t;\n    using boost::mp11::mp_transform;\n\n    {\n        int const N = 12;\n        using L1 = mp_iota_c<N>;\n\n        using R1 = mp_filter<P1, L1>;\n        BOOST_TEST_TRAIT_TRUE((std::is_same<R1, mp_list<mp_size_t<0>, mp_size_t<6>>>));\n\n        using L2 = mp_transform<mod_2, L1>;\n        using L3 = mp_transform<mod_3, L1>;\n        using L6 = mp_transform<mod_6, L1>;\n\n        using R2 = mp_filter<P2, L1, L6>;\n        BOOST_TEST_TRAIT_TRUE((std::is_same<R2, mp_list<mp_size_t<0>, mp_size_t<6>>>));\n\n        using R3 = mp_filter<P2, L1, L2, L3>;\n        BOOST_TEST_TRAIT_TRUE((std::is_same<R3, mp_list<mp_size_t<0>, mp_size_t<6>>>));\n    }\n\n    {\n        int const N = 64;\n        int const M = 17;\n\n        using L1 = mp_iota_c<N>;\n        using R1 = at_c<L1, M>;\n\n        BOOST_TEST_TRAIT_TRUE((std::is_same<R1, mp_size_t<M>>));\n    }\n\n    return boost::report_errors();\n}\n", "meta": {"hexsha": "6a2ea13f0e1958fbe6d60962633a7e0bc3fe91aa", "size": 2100, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/libs/mp11/test/mp_filter.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/mp11/test/mp_filter.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/mp11/test/mp_filter.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": 26.582278481, "max_line_length": 110, "alphanum_fraction": 0.650952381, "num_tokens": 664, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.4813417523056725}}
{"text": "//==================================================================================================\n/*!\n\n  Copyright 2015 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#include <boost/simd/constant/oneosqrteps.hpp>\n#include <boost/simd/constant/sqrteps.hpp>\n#include <boost/simd/as.hpp>\n#include <simd_test.hpp>\n\nSTF_CASE_TPL( \"Check oneosqrteps behavior for integral types\"\n            , (std::uint8_t)(std::uint16_t)(std::uint32_t)(std::uint64_t)\n              (std::int8_t)(std::int16_t)(std::int32_t)(std::int64_t)\n            )\n{\n  using boost::simd::as;\n  using boost::simd::detail::oneosqrteps;\n  using boost::simd::Oneosqrteps;\n\n  STF_TYPE_IS(decltype(Oneosqrteps<T>()), T);\n  STF_EQUAL(Oneosqrteps<T>(), T(1));\n  STF_EQUAL(oneosqrteps( as(T{}) ),T(1));\n}\n\nSTF_CASE_TPL( \"Check oneosqrteps behavior for floating types\"\n            , (double)(float)\n            )\n{\n  using boost::simd::as;\n  using boost::simd::detail::oneosqrteps;\n  using boost::simd::Oneosqrteps;\n  using boost::simd::Sqrteps;\n\n  STF_TYPE_IS(decltype(Oneosqrteps<T>()), T);\n  STF_IEEE_EQUAL(Oneosqrteps<T>(), T(1/Sqrteps<T>()));\n  STF_IEEE_EQUAL(oneosqrteps( as(T{}) ), T(1/Sqrteps<T>()));\n}\n", "meta": {"hexsha": "3a5cbc9aba571cabf018bc87044e22af9c9f1baa", "size": 1384, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/constant/scalar/oneosqrteps.cpp", "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": "test/constant/scalar/oneosqrteps.cpp", "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": "test/constant/scalar/oneosqrteps.cpp", "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": 32.9523809524, "max_line_length": 100, "alphanum_fraction": 0.573699422, "num_tokens": 398, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300048, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.4813417523056724}}
{"text": "#ifndef NET_UTIL_HH_\n#define NET_UTIL_HH_\n\n#include <algorithm>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/connected_components.hpp>\n#include <eigen3/Eigen/Dense>\n#include <eigen3/Eigen/Sparse>\n#include <vector>\n\n#include \"utils/util.hh\"\n\nstruct network_component_t {\n    using Scalar = float;\n    using sp_mat_t = Eigen::SparseMatrix<Scalar>;\n    using Index = sp_mat_t::Index;\n\n    std::vector<std::string> index2vertex;\n    sp_mat_t A;                                 // vertex x vertex\n    sp_mat_t Mleft;                             // left vertex x edge\n    sp_mat_t Mright;                            // right vertex x edge\n    std::vector<std::pair<Index, Index>> Edges; // edges (i,j)\n    std::vector<Index> colors;                  // edge colors\n};\n\nstd::vector<std::shared_ptr<network_component_t>>\nread_network_data(const std::string data_file,\n                  const std::string color_file,\n                  const bool,\n                  const double);\n\ntemplate <typename Derived, typename Pair>\nint construct_edge_incidence(const Eigen::SparseMatrixBase<Derived> &A,\n                             Eigen::SparseMatrixBase<Derived> &Mleft,\n                             Eigen::SparseMatrixBase<Derived> &Mright,\n                             std::vector<Pair> &edges);\n\ntemplate <typename Data, typename Str2Int, typename Derived>\nvoid read_sparse_pairs(const Data &data,\n                       const Str2Int &vertex2index,\n                       Eigen::SparseMatrixBase<Derived> &Amat);\n\ntemplate <typename Data, typename Str2Int, typename Graph>\nvoid build_boost_graph(const Data &data, const Str2Int &vertex2index, Graph &G);\n\ntemplate <typename Graph, typename Scalar>\nvoid prune_uninformative_edges(const Graph &gIn, Graph &gOut, const Scalar);\n\ntemplate <typename Data, typename Str2Int, typename Int2Str>\nvoid build_vertex2index(const Data &data,\n                        Str2Int &vertex2index,\n                        Int2Str &index2vertex);\n\ntemplate <typename Derived, typename OtherDerived, typename Pair>\nint construct_incidence_matrices(const Eigen::SparseMatrixBase<Derived> &A,\n                                 Eigen::SparseMatrixBase<OtherDerived> &mleft,\n                                 Eigen::SparseMatrixBase<OtherDerived> &mright,\n                                 std::vector<Pair> &edges);\n\n#include \"utils/net_util_impl.hh\"\n\n#endif\n", "meta": {"hexsha": "c6d239b88aa085d81f2da2362d208d863d50f767", "size": 2388, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/utils/net_util.hh", "max_stars_repo_name": "YPARK/mmutil", "max_stars_repo_head_hexsha": "21729fc50ac4cefff58c1b71e8c5740d2045b111", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-18T02:01:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-18T02:01:31.000Z", "max_issues_repo_path": "include/utils/net_util.hh", "max_issues_repo_name": "YPARK/mm-vae", "max_issues_repo_head_hexsha": "371e60821b0d0bf866bf465a8bc7bfa048bbf32c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/utils/net_util.hh", "max_forks_repo_name": "YPARK/mm-vae", "max_forks_repo_head_hexsha": "371e60821b0d0bf866bf465a8bc7bfa048bbf32c", "max_forks_repo_licenses": ["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.9047619048, "max_line_length": 80, "alphanum_fraction": 0.6310720268, "num_tokens": 511, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585669110202, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.48134174458968804}}
{"text": "// Copyright (c) Jeremy Siek 2001, Marc Wintermantel 2002\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_BANDWIDTH_HPP\n#define BOOST_GRAPH_BANDWIDTH_HPP\n\n#include <algorithm> // for std::min and std::max\n#include <boost/config.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/detail/numeric_traits.hpp>\n\nnamespace boost\n{\n\ntemplate < typename Graph, typename VertexIndexMap >\ntypename graph_traits< Graph >::vertices_size_type ith_bandwidth(\n    typename graph_traits< Graph >::vertex_descriptor i, const Graph& g,\n    VertexIndexMap index)\n{\n    BOOST_USING_STD_MAX();\n    using std::abs;\n    typedef\n        typename graph_traits< Graph >::vertices_size_type vertices_size_type;\n    vertices_size_type b = 0;\n    typename graph_traits< Graph >::out_edge_iterator e, end;\n    for (boost::tie(e, end) = out_edges(i, g); e != end; ++e)\n    {\n        int f_i = get(index, i);\n        int f_j = get(index, target(*e, g));\n        b = max BOOST_PREVENT_MACRO_SUBSTITUTION(\n            b, vertices_size_type(abs(f_i - f_j)));\n    }\n    return b;\n}\n\ntemplate < typename Graph >\ntypename graph_traits< Graph >::vertices_size_type ith_bandwidth(\n    typename graph_traits< Graph >::vertex_descriptor i, const Graph& g)\n{\n    return ith_bandwidth(i, g, get(vertex_index, g));\n}\n\ntemplate < typename Graph, typename VertexIndexMap >\ntypename graph_traits< Graph >::vertices_size_type bandwidth(\n    const Graph& g, VertexIndexMap index)\n{\n    BOOST_USING_STD_MAX();\n    using std::abs;\n    typedef\n        typename graph_traits< Graph >::vertices_size_type vertices_size_type;\n    vertices_size_type b = 0;\n    typename graph_traits< Graph >::edge_iterator i, end;\n    for (boost::tie(i, end) = edges(g); i != end; ++i)\n    {\n        int f_i = get(index, source(*i, g));\n        int f_j = get(index, target(*i, g));\n        b = max BOOST_PREVENT_MACRO_SUBSTITUTION(\n            b, vertices_size_type(abs(f_i - f_j)));\n    }\n    return b;\n}\n\ntemplate < typename Graph >\ntypename graph_traits< Graph >::vertices_size_type bandwidth(const Graph& g)\n{\n    return bandwidth(g, get(vertex_index, g));\n}\n\ntemplate < typename Graph, typename VertexIndexMap >\ntypename graph_traits< Graph >::vertices_size_type edgesum(\n    const Graph& g, VertexIndexMap index_map)\n{\n    typedef typename graph_traits< Graph >::vertices_size_type size_type;\n    typedef\n        typename detail::numeric_traits< size_type >::difference_type diff_t;\n    size_type sum = 0;\n    typename graph_traits< Graph >::edge_iterator i, end;\n    for (boost::tie(i, end) = edges(g); i != end; ++i)\n    {\n        diff_t f_u = get(index_map, source(*i, g));\n        diff_t f_v = get(index_map, target(*i, g));\n        using namespace std; // to call abs() unqualified\n        sum += abs(f_u - f_v);\n    }\n    return sum;\n}\n\n} // namespace boost\n\n#endif // BOOST_GRAPH_BANDWIDTH_HPP\n", "meta": {"hexsha": "9d08ea54c8be1719d910977f17bd4d0f12a27e5f", "size": 2976, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/graph/bandwidth.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/bandwidth.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/bandwidth.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.6595744681, "max_line_length": 78, "alphanum_fraction": 0.6844758065, "num_tokens": 738, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321964553657, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.48130131537217813}}
{"text": "//=========================================================================\n//\n// Copyright 2018 Kitware, Inc.\n// Author: Guilbert Pierre (spguilbert@gmail.com)\n// Data: 03-27-2018\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// This slam algorithm is inspired by the LOAM algorithm:\n// J. Zhang and S. Singh. LOAM: Lidar Odometry and Mapping in Real-time.\n// Robotics: Science and Systems Conference (RSS). Berkeley, CA, July 2014.\n\n// The algorithm is composed of three sequential steps:\n//\n// - Keypoints extraction: this step consists of extracting keypoints over\n// the points clouds. To do that, the laser lines / scans are trated indepently.\n// The laser lines are projected onto the XY plane and are rescale depending on\n// their vertical angle. Then we compute their curvature and create two class of\n// keypoints. The edges keypoints which correspond to points with a hight curvature\n// and planar points which correspond to points with a low curvature.\n//\n// - Ego-Motion: this step consists of recovering the motion of the lidar\n// sensor between two frames (two sweeps). The motion is modelized by a constant\n// velocity and angular velocity between two frames (i.e null acceleration).\n// Hence, we can parameterize the motion by a rotation and translation per sweep / frame\n// and interpolate the transformation inside a frame using the timestamp of the points.\n// Since the points clouds generated by a lidar are sparses we can't design a\n// pairwise match between keypoints of two successive frames. Hence, we decided to use\n// a closest-point matching between the keypoints of the current frame\n// and the geometrics features derived from the keypoints of the previous frame.\n// The geometrics features are lines or planes and are computed using the edges keypoints\n// and planar keypoints of the previous frame. Once the matching is done, a keypoint\n// of the current frame is matched with a plane / line (depending of the\n// nature of the keypoint) from the previous frame. Then, we recover R and T by\n// minimizing the function f(R, T) = sum(d(point, line)^2) + sum(d(point, plane)^2).\n// Which can be writen f(R, T) = sum((R*X+T-P).t*A*(R*X+T-P)) where:\n// - X is a keypoint of the current frame\n// - P is a point of the corresponding line / plane\n// - A = (n*n.t) with n being the normal of the plane\n// - A = (I - n*n.t).t * (I - n*n.t) with n being a director vector of the line\n// Since the function f(R, T) is a non-linear mean square error function\n// we decided to use the Levenberg-Marquardt algorithm to recover its argmin.\n//\n// - Mapping: This step consists of refining the motion recovered in the Ego-Motion\n// step and to add the new frame in the environment map. Thanks to the ego-motion\n// recovered at the previous step it is now possible to estimate the new position of\n// the sensor in the map. We use this estimation as an initial point (R0, T0) and we\n// perform an optimization again using the keypoints of the current frame and the matched\n// keypoints of the map (and not only the previous frame this time!). Once the position in the\n// map has been refined from the first estimation it is then possible to update the map by\n// adding the keypoints of the current frame into the map.\n//\n// In the following programs : \"vtkSlam.h\" and \"vtkSlam.cxx\" the lidar\n// coordinate system {L} is a 3D coordinate system with its origin at the\n// geometric center of the lidar. The world coordinate system {W} is a 3D\n// coordinate system which coinciding with {L] at the initial position. The\n// points will be denoted by the ending letter L or W if they belong to\n// the corresponding coordinate system\n\n// LOCAL\n#include \"vtkSlam.h\"\n#include \"vtkVelodyneTransformInterpolator.h\"\n#include \"vtkPCLConversions.h\"\n#include \"CeresCostFunctions.h\"\n// STD\n#include <sstream>\n#include <algorithm>\n#include <cmath>\n#include <cfloat>\n#include <ctime>\n// VTK\n#include <vtkCellArray.h>\n#include <vtkCellData.h>\n#include <vtkDataArray.h>\n#include <vtkDoubleArray.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 <vtkPointData.h>\n#include <vtkPoints.h>\n#include <vtkPolyData.h>\n#include <vtkPolyLine.h>\n#include <vtkSmartPointer.h>\n#include <vtkStreamingDemandDrivenPipeline.h>\n#include <vtkUnsignedCharArray.h>\n#include <vtkUnsignedShortArray.h>\n#include <vtkTransform.h>\n#include <vtkPoints.h>\n#include <vtkTransform.h>\n#include <vtkTransformPolyDataFilter.h>\n#include <vtkTable.h>\n// EIGEN\n#include <Eigen/Dense>\n// PCL\n#include <pcl/point_types.h>\n#include <pcl/filters/voxel_grid.h>\n// CERES\n#include <ceres/ceres.h>\n#include <glog/logging.h>\n\n#include \"vtkTemporalTransforms.h\"\n\nvtkStandardNewMacro(vtkSlam);\n\n\nnamespace {\n//-----------------------------------------------------------------------------\nclass LineFitting\n{\npublic:\n  // Fitting using PCA\n  bool FitPCA(std::vector<Eigen::Vector3d >& points);\n\n  // Futting using very local line and\n  // check if this local line is consistent\n  // in a more global neighborhood\n  bool FitPCAAndCheckConsistency(std::vector<Eigen::Vector3d >& points);\n\n  // Poor but fast fitting using\n  // extremities of the distribution\n  void FitFast(std::vector<Eigen::Vector3d >& points);\n\n  // Direction and position\n  Eigen::Vector3d Direction;\n  Eigen::Vector3d Position;\n  Eigen::Matrix3d SemiDist;\n  Eigen::Matrix3d I3 = Eigen::Matrix3d::Identity();\n  double MaxDistance = 0.02;\n  double MaxSinAngle = 0.65;\n};\n\n//-----------------------------------------------------------------------------\nbool LineFitting::FitPCA(std::vector<Eigen::Vector3d >& points)\n{\n  // Compute PCA to determine best line approximation\n  // of the points distribution\n  Eigen::MatrixXd data(points.size(), 3);\n\n  for (unsigned int k = 0; k < points.size(); k++)\n  {\n    data.row(k) = points[k];\n  }\n\n  Eigen::Vector3d mean = data.colwise().mean();\n  Eigen::MatrixXd centered = data.rowwise() - mean.transpose();\n  Eigen::MatrixXd cov = centered.transpose() * centered;\n  Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> eig(cov);\n\n  // Eigen values\n  Eigen::MatrixXd D(1,3);\n  // Eigen vectors\n  Eigen::MatrixXd V(3,3);\n\n  D = eig.eigenvalues();\n  V = eig.eigenvectors();\n\n  // Direction\n  this->Direction = V.col(2).normalized();\n\n  // Position\n  this->Position = mean;\n\n  // Semi distance matrix\n  // (polar form associated to\n  // a bilineare symmetric positive\n  // semi-definite matrix)\n  this->SemiDist = (this->I3 - this->Direction * this->Direction.transpose());\n  this->SemiDist = this->SemiDist.transpose() * this->SemiDist;\n\n  bool isLineFittingAccurate = true;\n\n  // if a point of the neighborhood is too far from\n  // the fitting line we considere the neighborhood as\n  // non flat\n  for (unsigned int k = 0; k < points.size(); k++)\n  {\n    double d = std::sqrt((points[k] - this->Position).transpose() * this->SemiDist * (points[k] - this->Position));\n    if (d > this->MaxDistance)\n    {\n      isLineFittingAccurate = false;\n    }\n  }\n\n  return isLineFittingAccurate;\n}\n\n//-----------------------------------------------------------------------------\nbool LineFitting::FitPCAAndCheckConsistency(std::vector<Eigen::Vector3d >& points)\n{\n  bool isLineFittingAccurate = true;\n\n  // first check if the neighborhood is straight\n  Eigen::Vector3d U, V;\n  U = (points[1] - points[0]).normalized();\n  for (unsigned int index = 1; index < points.size() - 1; index++)\n  {\n    V = (points[index + 1] - points[index]).normalized();\n    double sinAngle = (U.cross(V)).norm();\n    if (sinAngle > this->MaxSinAngle)\n    {\n      isLineFittingAccurate = false;\n    }\n  }\n\n  // Then fit with PCA\n  isLineFittingAccurate &= this->FitPCA(points);\n  return isLineFittingAccurate;\n}\n\n//-----------------------------------------------------------------------------\nvoid LineFitting::FitFast(std::vector<Eigen::Vector3d >& points)\n{\n  // Take the two extrems points of the neighborhood\n  // i.e the farest and the closest to the current point\n  Eigen::Vector3d U = points[0];\n  Eigen::Vector3d V = points[points.size() - 1];\n\n  // direction\n  this->Direction = (V - U).normalized();\n\n  // position\n  this->Position = U;\n\n  // Semi distance matrix\n  // (polar form associated to\n  // a bilineare symmetric positive\n  // semi-definite matrix)\n  this->SemiDist = (this->I3 - this->Direction * this->Direction.transpose());\n  this->SemiDist = this->SemiDist.transpose() * this->SemiDist;\n}\n\n//-----------------------------------------------------------------------------\nEigen::Matrix3d GetRotationMatrix(Eigen::Matrix<double, 6, 1> T)\n{\n  return Eigen::Matrix3d(\n          Eigen::AngleAxisd(T(2), Eigen::Vector3d::UnitZ())     /* rotation around Z-axis */\n        * Eigen::AngleAxisd(T(1), Eigen::Vector3d::UnitY())     /* rotation around Y-axis */\n        * Eigen::AngleAxisd(T(0), Eigen::Vector3d::UnitX()));   /* rotation around X-axis */\n}\n\n//-----------------------------------------------------------------------------\ntemplate <typename T>\nvtkSmartPointer<T> CreateDataArray(const char* name, vtkIdType np, vtkPolyData* pd)\n{\n  vtkSmartPointer<T> array = vtkSmartPointer<T>::New();\n  array->Allocate(np);\n  array->SetName(name);\n\n  if (pd)\n    {\n    pd->GetPointData()->AddArray(array);\n    }\n\n  return array;\n}\n\n//-----------------------------------------------------------------------------\ntemplate <typename T>\nstd::vector<size_t> sortIdx(const std::vector<T> &v)\n{\n  // initialize original index locations\n  std::vector<size_t> idx(v.size());\n  std::iota(idx.begin(), idx.end(), 0);\n\n  // sort indexes based on comparing values in v\n  std::sort(idx.begin(), idx.end(),\n       [&v](size_t i1, size_t i2) {return v[i1] > v[i2];});\n\n  return idx;\n}\n\n//-----------------------------------------------------------------------------\nstd::clock_t startTime;\n\n//-----------------------------------------------------------------------------\nvoid InitTime()\n{\n  startTime = std::clock();\n}\n\n//-----------------------------------------------------------------------------\nvoid StopTimeAndDisplay(std::string functionName)\n{\n  std::clock_t endTime = std::clock();\n  double dt = static_cast<double>(endTime - startTime) / CLOCKS_PER_SEC;\n  std::cout << \"  -time elapsed in function <\" << functionName << \"> : \" << dt << \" sec\" << std::endl;\n}\n\n//-----------------------------------------------------------------------------\ndouble Rad2Deg(double val)\n{\n  return val / vtkMath::Pi() * 180;\n}\n\ndouble Deg2Rad(double val)\n{\n  return (val * vtkMath::Pi()) / 180;\n}\n}\n\n// The map reconstructed from the slam algorithm is stored in a voxel grid\n// which split the space in differents region. From this voxel grid it is possible\n// to only load the parts of the map which are pertinents when we run the mapping\n// optimization algorithm. Morevover, when a a region of the space is too far from\n// the current sensor position it is possible to remove the points stored in this region\n// and to move the voxel grid in a closest region of the sensor position. This is used\n// to decrease the memory used by the algorithm\nclass RollingGrid {\npublic:\n  RollingGrid() {}\n\n  RollingGrid(double posX, double posY, double posZ)\n  {\n    // should initialize using Tworld + size / 2\n    this->VoxelGridPosition[0] = static_cast<int>(posX);\n    this->VoxelGridPosition[1] = static_cast<int>(posY);\n    this->VoxelGridPosition[2] = static_cast<int>(posZ);;\n  }\n\n  // roll the grid to enable adding new point cloud\n  void Roll(Eigen::Matrix<double, 6, 1> &T)\n  {\n    // Very basic implementation where the grid is not circular\n\n    // compute the position of the new frame center in the grid\n    int frameCenterX = std::floor(T[3] / this->VoxelSize) - this->VoxelGridPosition[0];\n    int frameCenterY = std::floor(T[4] / this->VoxelSize) - this->VoxelGridPosition[1];\n    int frameCenterZ = std::floor(T[5] / this->VoxelSize) - this->VoxelGridPosition[2];\n\n    // shift the voxel grid to the left\n    while (frameCenterX - std::ceil(this->PointCloudSize / 2) <= 0)\n    {\n      for (int j = 0; j < this->VoxelSize; j++)\n      {\n        for (int k = 0; k < this->VoxelSize; k++)\n        {\n          for (int i = this->VoxelSize - 1; i > 0; i--)\n          {\n            this->grid[i][j][k] = this->grid[i-1][j][k];\n          }\n          this->grid[0][j][k].reset(new pcl::PointCloud<Point>());\n        }\n      }\n      frameCenterX++;\n      this->VoxelGridPosition[0]--;\n    }\n\n    // shift the voxel grid to the right\n    while (frameCenterX + std::ceil(this->PointCloudSize / 2) >= this->VoxelSize - 1)\n    {\n      for (int j = 0; j < this->VoxelSize; j++)\n      {\n        for (int k = 0; k < this->VoxelSize; k++)\n        {\n          for (int i = 0; i < this->VoxelSize - 1; i++)\n          {\n            this->grid[i][j][k] = this->grid[i+1][j][k];\n          }\n          this->grid[VoxelSize-1][j][k].reset(new pcl::PointCloud<Point>());\n        }\n      }\n      frameCenterX--;\n      this->VoxelGridPosition[0]++;\n    }\n\n    // shift the voxel grid to the bottom\n    while (frameCenterY - std::ceil(this->PointCloudSize / 2) <= 0)\n    {\n      for (int i = 0; i < this->VoxelSize; i++)\n      {\n        for (int k = 0; k < this->VoxelSize; k++)\n        {\n          for (int j = this->VoxelSize - 1; j > 0; j--)\n          {\n            this->grid[i][j][k] = this->grid[i][j-1][k];\n          }\n          this->grid[i][0][k].reset(new pcl::PointCloud<Point>());\n        }\n      }\n      frameCenterY++;\n      this->VoxelGridPosition[1]--;\n//      cout << \"bottom\";\n    }\n\n    // shift the voxel grid to the top\n    while (frameCenterY + std::ceil(this->PointCloudSize / 2) >= this->VoxelSize - 1)\n    {\n      for (int i = 0; i < this->VoxelSize; i++)\n      {\n        for (int k = 0; k < this->VoxelSize; k++)\n        {\n          for (int j = 0; j < this->VoxelSize - 1; j++)\n          {\n            this->grid[i][j][k] = this->grid[i][j+1][k];\n          }\n          this->grid[i][VoxelSize-1][k].reset(new pcl::PointCloud<Point>());\n        }\n      }\n      frameCenterY--;\n      this->VoxelGridPosition[1]++;\n    }\n\n    // shift the voxel grid to the \"camera\"\n    while (frameCenterZ - std::ceil(this->PointCloudSize / 2) <= 0)\n    {\n      for (int i = 0; i < this->VoxelSize; i++)\n      {\n        for (int j = 0; j < this->VoxelSize; j++)\n        {\n          for (int k = this->VoxelSize - 1; k > 0; k--)\n          {\n            this->grid[i][j][k] = this->grid[i][j][k-1];\n          }\n          this->grid[i][j][0].reset(new pcl::PointCloud<Point>());\n        }\n      }\n      frameCenterZ++;\n      this->VoxelGridPosition[2]--;\n    }\n\n    // shift the voxel grid to the \"horizon\"\n    while (frameCenterZ + std::ceil(this->PointCloudSize  / 2) >= this->VoxelSize - 1)\n    {\n      for (int i = 0; i < this->VoxelSize; i++)\n      {\n        for (int j = 0; j < this->VoxelSize; j++)\n        {\n          for (int k = 0; k < this->VoxelSize - 1; k++)\n          {\n            this->grid[i][j][k] = this->grid[i][j][k+1];\n          }\n          this->grid[i][j][VoxelSize-1].reset(new pcl::PointCloud<Point>());\n        }\n      }\n      frameCenterZ--;\n      this->VoxelGridPosition[2]++;\n    }\n  }\n\n  // get points arround T\n  pcl::PointCloud<Point>::Ptr Get(Eigen::Matrix<double, 6, 1> &T)\n  {\n    // compute the position of the new frame center in the grid\n    int frameCenterX = std::floor(T[3] / this->VoxelSize) - this->VoxelGridPosition[0];\n    int frameCenterY = std::floor(T[4] / this->VoxelSize) - this->VoxelGridPosition[1];\n    int frameCenterZ = std::floor(T[5] / this->VoxelSize) - this->VoxelGridPosition[2];\n\n    pcl::PointCloud<Point>::Ptr intersection(new pcl::PointCloud<Point>);\n\n    // Get all voxel in intersection should use ceil here\n    for (int i = frameCenterX - std::ceil(this->PointCloudSize / 2); i <= frameCenterX + std::ceil(this->PointCloudSize / 2); i++)\n    {\n      for (int j = frameCenterY - std::ceil(this->PointCloudSize / 2); j <= frameCenterY + std::ceil(this->PointCloudSize / 2); j++)\n      {\n        for (int k = frameCenterZ - std::ceil(this->PointCloudSize / 2); k <= frameCenterZ + std::ceil(this->PointCloudSize / 2); k++)\n        {\n          if (i < 0 || i > (this->VoxelSize - 1) ||\n              j < 0 || j > (this->VoxelSize - 1) ||\n              k < 0 || k > (this->VoxelSize - 1))\n          {\n            continue;\n          }\n          pcl::PointCloud<Point>:: Ptr voxel = this->grid[i][j][k];\n          for (unsigned int l = 0; l < voxel->size(); l++)\n          {\n            intersection->push_back(voxel->at(l));\n          }\n        }\n      }\n    }\n    return intersection;\n  }\n\n  // get all points\n  pcl::PointCloud<Point>::Ptr Get()\n  {\n    pcl::PointCloud<Point>::Ptr intersection(new pcl::PointCloud<Point>);\n\n    // Get all voxel in intersection should use ceil here\n    for (int i = 0; i < VoxelSize; i++)\n    {\n      for (int j = 0; j < VoxelSize; j++)\n      {\n        for (int k = 0; k < VoxelSize; k++)\n        {\n          pcl::PointCloud<Point>:: Ptr voxel = this->grid[i][j][k];\n          for (unsigned int l = 0; l < voxel->size(); l++)\n          {\n            intersection->push_back(voxel->at(l));\n          }\n        }\n      }\n    }\n    return intersection;\n  }\n\n  // add some points to the grid\n  void Add(pcl::PointCloud<Point>::Ptr pointcloud)\n  {\n    if (pointcloud->size() == 0)\n    {\n      vtkGenericWarningMacro(\"Pointcloud empty, voxel grid not updated\");\n      return;\n    }\n\n    // Voxel to filte because new points were add\n    std::vector<std::vector<std::vector<int> > > voxelToFilter(VoxelSize, std::vector<std::vector<int> >(VoxelSize, std::vector<int>(VoxelSize, 0)));\n\n    // Add points in the rolling grid\n    int outlier = 0; // point who are not in the rolling grid\n    for (unsigned int i = 0; i < pointcloud->size(); i++)\n    {\n      Point pts = pointcloud->points[i];\n      // find the closest coordinate\n      int cubeIdxX = std::floor(pts.x / this->VoxelSize) - this->VoxelGridPosition[0];\n      int cubeIdxY = std::floor(pts.y / this->VoxelSize) - this->VoxelGridPosition[1];\n      int cubeIdxZ = std::floor(pts.z / this->VoxelSize) - this->VoxelGridPosition[2];\n\n\n      if (cubeIdxX >= 0 && cubeIdxX < this->VoxelSize &&\n        cubeIdxY >= 0 && cubeIdxY < this->VoxelSize &&\n        cubeIdxZ >= 0 && cubeIdxZ < this->VoxelSize)\n      {\n        voxelToFilter[cubeIdxX][cubeIdxY][cubeIdxZ] = 1;\n        grid[cubeIdxX][cubeIdxY][cubeIdxZ]->push_back(pts);\n      }\n      else\n      {\n        outlier++;\n      }\n    }\n\n    // Filter the modified pointCloud\n    pcl::VoxelGrid<Point> downSizeFilter;\n    downSizeFilter.setLeafSize(this->LeafSize, this->LeafSize, this->LeafSize);\n    for (int i = 0; i < this->VoxelSize; i++)\n    {\n      for (int j = 0; j < this->VoxelSize; j++)\n      {\n        for (int k = 0; k < this->VoxelSize; k++)\n        {\n          if (voxelToFilter[i][j][k] == 1)\n          {\n            pcl::PointCloud<Point>::Ptr tmp(new pcl::PointCloud<Point>());\n            downSizeFilter.setInputCloud(grid[i][j][k]);\n            downSizeFilter.filter(*tmp);\n            grid[i][j][k] = tmp;\n          }\n        }\n      }\n    }\n  }\n\n\n  void SetPointCoudMaxRange(const double maxdist)\n  {\n    this->PointCloudSize = std::ceil(2 * maxdist / this->VoxelResolution);\n  }\n\n  void SetSize(int size)\n  {\n    this->VoxelSize = size;\n    grid.resize(this->VoxelSize);\n    for (int i = 0; i < this->VoxelSize; i++)\n    {\n      grid[i].resize(this->VoxelSize);\n      for (int j = 0; j < this->VoxelSize; j++)\n      {\n        grid[i][j].resize(this->VoxelSize);\n        for (int k = 0; k < this->VoxelSize; k++)\n        {\n          grid[i][j][k].reset(new pcl::PointCloud<Point>());\n        }\n      }\n    }\n  }\n\n  void SetResolution(double resolution) { this->VoxelResolution = resolution; }\n\n  void SetLeafSize(double size) { this->LeafSize = size; }\n\nprivate:\n  //! Size of the voxel grid: n*n*n voxels\n  int VoxelSize = 50;\n\n  //! Resolution of a voxel\n  double VoxelResolution = 10;\n\n  //! Size of a pointcloud in voxel\n  int PointCloudSize = 25;\n\n  //! Size of the leaf use to downsample the pointcloud\n  double LeafSize = 0.2;\n\n  //! VoxelGrid of pointcloud\n  std::vector<std::vector<std::vector<pcl::PointCloud<Point>::Ptr> > > grid;\n\n  // Position of the VoxelGrid\n  int VoxelGridPosition[3] = {0,0,0};\n};\n\n//-----------------------------------------------------------------------------\nint vtkSlam::RequestData(vtkInformation *vtkNotUsed(request),\nvtkInformationVector **inputVector, vtkInformationVector *outputVector)\n{\n  if (this->LaserIdMapping.empty())\n  {\n    vtkTable *calib = vtkTable::GetData(inputVector[1]->GetInformationObject(0));\n    this->UpdateLaserIdMapping(calib);\n  }\n\n  // Get the input\n  vtkPolyData *input = vtkPolyData::GetData(inputVector[0]->GetInformationObject(0));\n\n  if (this->NbrFrameProcessed == 0)\n  {\n    if (inputVector[1]->GetInformationObject(0) == inputVector[2]->GetInformationObject(0))\n    {\n      std::cout << \"no IMU\" << std::endl;\n      this->UsingImu = false;\n    }\n    else\n    {\n      std::cout << \"using IMU\" << std::endl;\n      this->UsingImu = true;\n      this->ImuData = vtkTable::GetData(inputVector[2]->GetInformationObject(0));\n      this->ImuDataRow = 0;\n      this->Velocity << this->InitialVelocityX, this->InitialVelocityY, this->InitialVelocityZ;\n      this->Heading << 0,0,0;\n    }\n  }\n\n  this->AddFrame(input);\n  // output 0 - Current Frame\n  vtkInformation *outInfo0 = outputVector->GetInformationObject(0);\n  vtkPolyData *output0 = vtkPolyData::SafeDownCast(\n      outInfo0->Get(vtkDataObject::DATA_OBJECT()));\n  // add all debug information if displayMode == True\n  if (this->DisplayMode == true && this->NbrFrameProcessed > 0)\n  {\n    std::cout << \"display\" << std::endl;\n\n    this->DisplayLaserIdMapping(this->vtkCurrentFrame);\n    this->DisplayRelAdv(this->vtkCurrentFrame);\n    this->DisplayUsedKeypoints(this->vtkCurrentFrame);\n    AddVectorToPolydataPoints<double, vtkDoubleArray>(this->Angles, \"angles_line\", this->vtkCurrentFrame);\n    AddVectorToPolydataPoints<double, vtkDoubleArray>(this->LengthResolution, \"length_resolution\", this->vtkCurrentFrame);\n    AddVectorToPolydataPoints<double, vtkDoubleArray>(this->SaillantPoint, \"saillant_point\", this->vtkCurrentFrame);\n    AddVectorToPolydataPoints<double, vtkDoubleArray>(this->DepthGap, \"depth_gap\", this->vtkCurrentFrame);\n    AddVectorToPolydataPoints<double, vtkDoubleArray>(this->IntensityGap, \"intensity_gap\", this->vtkCurrentFrame);\n    AddVectorToPolydataPoints<double, vtkDoubleArray>(this->BlobScore, \"blob_score\", this->vtkCurrentFrame);\n    AddVectorToPolydataPoints<int, vtkIntArray>(this->IsPointValid, \"is_point_valid\", this->vtkCurrentFrame);\n    AddVectorToPolydataPoints<int, vtkIntArray>(this->Label, \"keypoint_label\", this->vtkCurrentFrame);\n  }\n  // get transform\n  vtkSmartPointer<vtkTransform> transform = vtkSmartPointer<vtkTransform>::New();\n  transform->Translate(Tworld[3], Tworld[4], Tworld[5]);\n  transform->RotateX(Rad2Deg(Tworld[0]));\n  transform->RotateY(Rad2Deg(Tworld[1]));\n  transform->RotateZ(Rad2Deg(Tworld[2]));\n  // create transform filter and transformt the current frame\n  vtkSmartPointer<vtkTransformPolyDataFilter> transformFilter = vtkSmartPointer<vtkTransformPolyDataFilter>::New();\n  transformFilter->SetInputData(this->vtkCurrentFrame);\n  transformFilter->SetTransform(transform);\n  transformFilter->Update();\n  output0->ShallowCopy(transformFilter->GetOutput());\n\n  // output 1 - Trajectory\n  auto *output1 = vtkPolyData::GetData(outputVector->GetInformationObject(1));\n  output1->ShallowCopy(this->Trajectory);\n\n  // output 2 - Edges Points Map\n  auto *output2 = vtkPolyData::GetData(outputVector->GetInformationObject(2));\n  auto EdgeMap = vtkPCLConversions::PolyDataFromPointCloud(this->EdgesPointsLocalMap->Get());\n  output2->ShallowCopy(EdgeMap);\n\n  // output 3 - Planar Points Map\n  auto *output3 = vtkPolyData::GetData(outputVector->GetInformationObject(3));\n  auto PlanarMap = vtkPCLConversions::PolyDataFromPointCloud(this->PlanarPointsLocalMap->Get());\n  output3->ShallowCopy(PlanarMap);\n\n  // output 4 - Blob Points Map\n  auto *output4 = vtkPolyData::GetData(outputVector->GetInformationObject(4));\n  auto BlobMap = vtkPCLConversions::PolyDataFromPointCloud(this->BlobsPointsLocalMap->Get());\n  output4->ShallowCopy(BlobMap);\n\n  return 1;\n}\n\n//-----------------------------------------------------------------------------\nvoid vtkSlam::PrintSelf(ostream& os, vtkIndent indent)\n{\n  this->Superclass::PrintSelf(os, indent);\n  os << indent << \"Slam Parameters: \" << std::endl;\n  vtkIndent paramIndent = indent.GetNextIndent();\n  #define PrintParameter(param) os << paramIndent << #param << \"\\t\" << this->param << std::endl;\n  PrintParameter(EgoMotionLMMaxIter)\n  PrintParameter(EgoMotionICPMaxIter)\n  PrintParameter(MappingLMMaxIter)\n  PrintParameter(MappingICPMaxIter)\n  PrintParameter(EdgeSinAngleThreshold)\n  PrintParameter(PlaneSinAngleThreshold)\n  PrintParameter(EdgeDepthGapThreshold)\n  PrintParameter(EgoMotionLineDistanceNbrNeighbors)\n  PrintParameter(EgoMotionLineDistancefactor)\n  PrintParameter(MappingMaxLineDistance)\n  PrintParameter(MappingPlaneDistanceNbrNeighbors)\n  PrintParameter(MappingPlaneDistancefactor1)\n  PrintParameter(MappingPlaneDistancefactor2)\n  PrintParameter(MappingMaxPlaneDistance)\n  PrintParameter(MaxDistanceForICPMatching)\n  PrintParameter(AngleResolution)\n  PrintParameter(EgoMotionMinimumLineNeighborRejection)\n  PrintParameter(MappingMinimumLineNeighborRejection)\n  PrintParameter(MappingLineMaxDistInlier)\n}\n\n//-----------------------------------------------------------------------------\nvtkSlam::vtkSlam()\n{\n  this->SetNumberOfInputPorts(3);\n  this->SetNumberOfOutputPorts(5);\n  this->Reset();\n}\n\n//-----------------------------------------------------------------------------\nvoid vtkSlam::Reset()\n{\n  this->EdgesPointsLocalMap = std::make_shared<RollingGrid>();\n  this->PlanarPointsLocalMap = std::make_shared<RollingGrid>();\n  this->BlobsPointsLocalMap = std::make_shared<RollingGrid>();\n\n  this->EdgesPointsLocalMap->SetResolution(10);\n  this->PlanarPointsLocalMap->SetResolution(10);\n  this->BlobsPointsLocalMap->SetResolution(10);\n\n  this->EdgesPointsLocalMap->SetSize(50);\n  this->PlanarPointsLocalMap->SetSize(50);\n  this->BlobsPointsLocalMap->SetSize(50);\n\n  // output of the vtk filter\n\n  this->Trajectory = vtkSmartPointer<vtkTemporalTransforms>::New();\n  Tworld = Eigen::Matrix<double, 6, 1>::Zero();\n\n  this->LaserIdMapping.clear();\n  this->NbrFrameProcessed = 0;\n  this->Tworld = Eigen::Matrix<double, 6, 1>::Zero();\n\n  // add the required array in the trajectory\n  CreateDataArray<vtkDoubleArray>(\"Variance Error\", 0, this->Trajectory);\n  CreateDataArray<vtkIntArray>(\"Mapping: edges used\", 0, this->Trajectory);\n  CreateDataArray<vtkIntArray>(\"Mapping: planes used\", 0, this->Trajectory);\n  CreateDataArray<vtkIntArray>(\"Mapping: blobs used\", 0, this->Trajectory);\n  CreateDataArray<vtkIntArray>(\"Mapping: total keypoints used\", 0, this->Trajectory);\n  CreateDataArray<vtkIntArray>(\"EgoMotion: edges used\", 0, this->Trajectory);\n  CreateDataArray<vtkIntArray>(\"EgoMotion: planes used\", 0, this->Trajectory);\n  CreateDataArray<vtkIntArray>(\"EgoMotion: total keypoints used\", 0, this->Trajectory);\n\n  this->ImuConfidence << 0.95, 0.995 ,0.8, 0.65, 0.65, 0.8;\n}\n\n//-----------------------------------------------------------------------------\nvtkSlam::~vtkSlam()\n{\n\n}\n\n//-----------------------------------------------------------------------------\nint vtkSlam::FillInputPortInformation(int port, vtkInformation *info)\n{\n  if ( port == 0 )\n  {\n    info->Set(vtkDataObject::DATA_TYPE_NAME(), \"vtkPolyData\" );\n    return 1;\n  }\n  if ( port == 1 )\n  {\n    info->Set(vtkDataObject::DATA_TYPE_NAME(), \"vtkTable\" );\n    return 1;\n  }\n  if ( port == 2 )\n  {\n    info->Set(vtkDataObject::DATA_TYPE_NAME(), \"vtkTableImu\" );\n    return 1;\n  }\n  return 0;\n}\n\n//-----------------------------------------------------------------------------\nvoid vtkSlam::GetWorldTransform(double* Tworld)\n{\n  // Rotation and translation relative\n  Eigen::Matrix3d Rw;\n\n  // full rotation\n  Rw = GetRotationMatrix(this->Tworld);\n\n  double rx = std::atan2(Rw(2, 1), Rw(2, 2));\n  double ry = -std::asin(Rw(2, 0));\n  double rz = std::atan2(Rw(1, 0), Rw(0, 0));\n//  std::vector<double> res(6, 0);\n\n  Tworld[0] = rx;\n  Tworld[1] = ry;\n  Tworld[2] = rz;\n  Tworld[3] = this->Tworld(3);\n  Tworld[4] = this->Tworld(4);\n  Tworld[5] = this->Tworld(5);\n\n//  return res;\n}\n\n//-----------------------------------------------------------------------------\nvoid vtkSlam::PrepareDataForNextFrame()\n{\n  // Reset the pcl format pointcloud to store the new frame\n  this->pclCurrentFrame.reset(new pcl::PointCloud<Point>());\n  this->pclCurrentFrameByScan.resize(this->NLasers);\n  for (unsigned int k = 0; k < this->NLasers; ++k)\n  {\n    this->pclCurrentFrameByScan[k].reset(new pcl::PointCloud<Point>());\n  }\n\n  this->CurrentEdgesPoints.reset(new pcl::PointCloud<Point>());\n  this->CurrentPlanarsPoints.reset(new pcl::PointCloud<Point>());\n  this->CurrentBlobsPoints.reset(new pcl::PointCloud<Point>());\n\n  // reset vtk <-> pcl id mapping\n  this->FromVTKtoPCLMapping.clear();\n  this->FromVTKtoPCLMapping.resize(0);\n  this->FromPCLtoVTKMapping.clear();\n  this->FromPCLtoVTKMapping.resize(this->NLasers);\n  this->Angles.clear();\n  this->Angles.resize(this->NLasers);\n  this->LengthResolution.clear();\n  this->LengthResolution.resize(this->NLasers);\n  this->SaillantPoint.clear();\n  this->SaillantPoint.resize(this->NLasers);\n  this->DepthGap.clear();\n  this->DepthGap.resize(this->NLasers);\n  this->IntensityGap.clear();\n  this->IntensityGap.resize(this->NLasers);\n  this->BlobScore.clear();\n  this->BlobScore.resize(this->NLasers);\n  this->IsPointValid.clear();\n  this->IsPointValid.resize(this->NLasers);\n  this->Label.clear();\n  this->Label.resize(this->NLasers);\n}\n\n//-----------------------------------------------------------------------------\ntemplate <typename T, typename Tvtk>\nvoid vtkSlam::AddVectorToPolydataPoints(const std::vector<std::vector<T>>& vec, const char* name, vtkPolyData* pd)\n{\n  vtkSmartPointer<Tvtk> array = vtkSmartPointer<Tvtk>::New();\n  array->Allocate(pd->GetNumberOfPoints());\n  array->SetName(name);\n  for (unsigned int k = 0; k < pd->GetNumberOfPoints(); ++k)\n  {\n    unsigned int scan = this->FromVTKtoPCLMapping[k].first;\n    unsigned int index = this->FromVTKtoPCLMapping[k].second;\n    array->InsertNextTuple1(vec[scan][index]);\n  }\n  pd->GetPointData()->AddArray(array);\n}\n\n//-----------------------------------------------------------------------------\nvoid vtkSlam::DisplayLaserIdMapping(vtkSmartPointer<vtkPolyData> input)\n{\n  vtkDataArray* idsArray = input->GetPointData()->GetArray(\"laser_id\");\n  vtkSmartPointer<vtkIntArray> laserMappingArray = vtkSmartPointer<vtkIntArray>::New();\n  laserMappingArray->Allocate(input->GetNumberOfPoints());\n  laserMappingArray->SetName(\"laser_mapping\");\n  for (unsigned int k = 0; k < input->GetNumberOfPoints(); ++k)\n  {\n    int id = static_cast<int>(idsArray->GetTuple1(k));\n    id = this->LaserIdMapping[id];\n    laserMappingArray->InsertNextTuple1(id);\n  }\n  input->GetPointData()->AddArray(laserMappingArray);\n}\n\n//-----------------------------------------------------------------------------\nvoid vtkSlam::DisplayRelAdv(vtkSmartPointer<vtkPolyData> input)\n{\n  vtkSmartPointer<vtkDoubleArray> relAdvArray = vtkSmartPointer<vtkDoubleArray>::New();\n  relAdvArray->Allocate(input->GetNumberOfPoints());\n  relAdvArray->SetName(\"relative_adv\");\n  for (unsigned int k = 0; k < input->GetNumberOfPoints(); ++k)\n  {\n    unsigned int scan = this->FromVTKtoPCLMapping[k].first;\n    unsigned int index = this->FromVTKtoPCLMapping[k].second;\n    relAdvArray->InsertNextTuple1(this->pclCurrentFrameByScan[scan]->points[index].intensity);\n  }\n  input->GetPointData()->AddArray(relAdvArray);\n}\n\n//-----------------------------------------------------------------------------\nvoid vtkSlam::DisplayUsedKeypoints(vtkSmartPointer<vtkPolyData> input)\n{\n  vtkSmartPointer<vtkIntArray> edgeUsedEgoMotion = vtkSmartPointer<vtkIntArray>::New();\n  edgeUsedEgoMotion->Allocate(input->GetNumberOfPoints());\n  edgeUsedEgoMotion->SetName(\"Edges_Used_EgoMotion\");\n\n  vtkSmartPointer<vtkIntArray> edgeUsedMapping = vtkSmartPointer<vtkIntArray>::New();\n  edgeUsedMapping->Allocate(input->GetNumberOfPoints());\n  edgeUsedMapping->SetName(\"Edges_Used_Mapping\");\n\n  vtkSmartPointer<vtkIntArray> planarUsedEgoMotion = vtkSmartPointer<vtkIntArray>::New();\n  planarUsedEgoMotion->Allocate(input->GetNumberOfPoints());\n  planarUsedEgoMotion->SetName(\"Planes_Used_EgoMotion\");\n\n  vtkSmartPointer<vtkIntArray> planarUsedMapping = vtkSmartPointer<vtkIntArray>::New();\n  planarUsedMapping->Allocate(input->GetNumberOfPoints());\n  planarUsedMapping->SetName(\"Planes_Used_Mapping\");\n\n  // fill with -1 for points that are not keypoints\n  for (unsigned int k = 0; k < input->GetNumberOfPoints(); ++k)\n  {\n    edgeUsedEgoMotion->InsertNextTuple1(-1);\n    edgeUsedMapping->InsertNextTuple1(-1);\n    planarUsedEgoMotion->InsertNextTuple1(-1);\n    planarUsedMapping->InsertNextTuple1(-1);\n  }\n\n  // fill with 1 if the point is a keypoint\n  // fill with 2 if the point is a used keypoint\n  for (unsigned int k = 0; k < this->EdgesIndex.size(); ++k)\n  {\n    unsigned int scan = this->EdgesIndex[k].first;\n    unsigned int index = this->EdgesIndex[k].second;\n\n    edgeUsedEgoMotion->SetTuple1(this->FromPCLtoVTKMapping[scan][index], EdgePointRejectionEgoMotion[k]);\n    edgeUsedMapping->SetTuple1(this->FromPCLtoVTKMapping[scan][index], EdgePointRejectionMapping[k]);\n  }\n  for (unsigned int k = 0; k < this->PlanarIndex.size(); ++k)\n  {\n    unsigned int scan = this->PlanarIndex[k].first;\n    unsigned int index = this->PlanarIndex[k].second;\n\n    planarUsedEgoMotion->SetTuple1(this->FromPCLtoVTKMapping[scan][index], this->PlanarPointRejectionEgoMotion[k]);\n    planarUsedMapping->SetTuple1(this->FromPCLtoVTKMapping[scan][index], this->PlanarPointRejectionMapping[k]);\n  }\n\n  input->GetPointData()->AddArray(edgeUsedEgoMotion);\n  input->GetPointData()->AddArray(edgeUsedMapping);\n  input->GetPointData()->AddArray(planarUsedEgoMotion);\n  input->GetPointData()->AddArray(planarUsedMapping);\n}\n\n//-----------------------------------------------------------------------------\nvoid vtkSlam::AddFrame(vtkPolyData* newFrame)\n{\n  if (!newFrame)\n  {\n    vtkGenericWarningMacro(\"Slam entry is a null pointer data\");\n    return;\n  }\n\n  this->vtkCurrentFrame = newFrame;\n\n  this->PreviousFrameTime = this->CurrentFrameTime;\n  this->CurrentFrameTime = this->vtkCurrentFrame->GetPointData()->GetArray(\"adjustedtime\")->GetTuple1(0);\n\n  // Check if the number of lasers has been set\n  if (this->NLasers == 0)\n  {\n    vtkGenericWarningMacro(\"Frame added without specifying the number of lasers\");\n  }\n\n  std::cout << \"#########################################################\" << std::endl\n            << \"Processing frame : \" << this->NbrFrameProcessed << std:: endl\n            << \"#########################################################\" << std::endl\n            << std::endl;\n\n  // Reset the members variables used during the last\n  // processed frame so that they can be used again\n  PrepareDataForNextFrame();\n\n  // Update the kalman filter time\n  double time = newFrame->GetPointData()->GetArray(\"adjustedtime\")->GetTuple1(0) * 1e-6;\n\n  // If the new frame is the first one we just add the\n  // extracted keypoints into the map without running\n  // odometry and mapping steps\n  if (this->NbrFrameProcessed == 0)\n  {\n    // Convert the new frame into pcl format and sort\n    // the laser scan-lines by vertical angle\n    this->ConvertAndSortScanLines(newFrame);\n\n    // Compute the edges and planars keypoints\n    this->ComputeKeyPoints(newFrame);\n\n    // update map using tworld\n    this->UpdateMapsUsingTworld();\n\n    // Current keypoints become previous ones\n    this->PreviousEdgesPoints = this->CurrentEdgesPoints;\n    this->PreviousPlanarsPoints = this->CurrentPlanarsPoints;\n    this->PreviousBlobsPoints = this->CurrentBlobsPoints;\n    this->NbrFrameProcessed++;\n    return;\n  }\n\n  // Convert the new frame into pcl format and sort\n  // the laser scan-lines by vertical angle\n  InitTime();\n  this->ConvertAndSortScanLines(vtkCurrentFrame);\n  StopTimeAndDisplay(\"Sorting lines\");\n\n  // Compute the edges and planars keypoints\n  InitTime();\n  this->ComputeKeyPoints(vtkCurrentFrame);\n  StopTimeAndDisplay(\"Keypoints extraction\");\n\n  if (this->UsingImu)\n  {\n    // Perfom ImuMotion\n    InitTime();\n    this->ComputeImuMotionTest();\n    StopTimeAndDisplay(\"Imu-Motion\");\n  }\n\n  // Perfom EgoMotion\n  if (!this->OnlyImu)//for testing\n  {\n    InitTime();\n    this->ComputeEgoMotion();\n    StopTimeAndDisplay(\"Ego-Motion\");\n  }\n\n  // Transform the current keypoints to the\n  // referential of the sensor at the end of\n  // frame acquisition\n  //InitTime();\n  //this->TransformCurrentKeypointsToEnd();\n  //StopTimeAndDisplay(\"Undistortion\");\n\n  // Perform Mapping\n  if (!this->OnlyImu)//for testing\n  {\n    InitTime();\n    this->Mapping();\n    StopTimeAndDisplay(\"Mapping\");\n  }\n\n\n  // Current keypoints become previous ones\n  this->PreviousEdgesPoints = this->CurrentEdgesPoints;\n  this->PreviousPlanarsPoints = this->CurrentPlanarsPoints;\n  this->NbrFrameProcessed++;\n\n  // Motion and localization parameters estimation information display\n  Eigen::Vector3d angles, trans;\n  angles << Rad2Deg(this->Trelative(0)), Rad2Deg(this->Trelative(1)), Rad2Deg(this->Trelative(2));\n  trans << this->Trelative(3), this->Trelative(4), this->Trelative(5);\n  std::cout << \"Ego-Motion estimation: angles = [\" << angles.transpose() << \"] translation: [\" << trans.transpose() << \"]\" << std::endl;\n  angles << Rad2Deg(this->Tworld(0)), Rad2Deg(this->Tworld(1)), Rad2Deg(this->Tworld(2));\n  trans << this->Tworld(3), this->Tworld(4), this->Tworld(5);\n  std::cout << \"Localiazion estimation: angles = [\" << angles.transpose() << \"] translation: [\" << trans.transpose() << \"]\"\n            << std::endl << std::endl << std::endl;\n\n  // Update Trajectory\n  Eigen::AngleAxisd orientation = Eigen::AngleAxisd(\n      Eigen::AngleAxisd(this->Tworld[0], Eigen::Vector3d::UnitX())\n      * Eigen::AngleAxisd(this->Tworld[1],  Eigen::Vector3d::UnitY())\n      * Eigen::AngleAxisd(this->Tworld[2], Eigen::Vector3d::UnitZ()));\n  this->Trajectory->PushBack(time, orientation, Tworld.tail(3));\n\n  // Indicate the filter has been modify\n  this->Modified();\n  return;\n}\n\n//-----------------------------------------------------------------------------\nvoid vtkSlam::ConvertAndSortScanLines(vtkSmartPointer<vtkPolyData> input)\n{\n  // temp var\n  double xL[3]; // in {L}\n  Point yL; // in {L}\n\n  // Get informations about input pointcloud\n  vtkDataArray* lasersId = input->GetPointData()->GetArray(\"laser_id\");\n  vtkDataArray* time = input->GetPointData()->GetArray(\"timestamp\");\n  vtkDataArray* reflectivity = input->GetPointData()->GetArray(\"intensity\");\n  vtkPoints* Points = input->GetPoints();\n  unsigned int Npts = input->GetNumberOfPoints();\n  double t0 = static_cast<double>(time->GetTuple1(0));\n  double t1 = static_cast<double>(time->GetTuple1(Npts - 1));\n  this->FromVTKtoPCLMapping.resize(Npts);\n\n\n  for (unsigned int index = 0; index < Npts; ++index)\n  {\n    // Get information about current point\n    Points->GetPoint(index, xL);\n    yL.x = xL[0]; yL.y = xL[1]; yL.z = xL[2];\n\n    double relAdv = (static_cast<double>(time->GetTuple1(index)) - t0) / (t1 - t0);\n    unsigned int id = static_cast<int>(lasersId->GetTuple1(index));\n    double reflec = static_cast<double>(reflectivity->GetTuple1(index));\n    id = this->LaserIdMapping[id];\n    yL.intensity = relAdv;\n    yL.normal_y = id;\n    yL.normal_z = reflec;\n\n    // add the current point to its corresponding laser scan\n    this->pclCurrentFrame->push_back(yL);\n    this->pclCurrentFrameByScan[id]->push_back(yL);\n    this->FromVTKtoPCLMapping[index] = std::pair<int, int>(id, this->pclCurrentFrameByScan[id]->size() - 1);\n    this->FromPCLtoVTKMapping[id].push_back(index);\n  }\n}\n\n//-----------------------------------------------------------------------------\nvoid vtkSlam::ComputeKeyPoints(vtkSmartPointer<vtkPolyData> input)\n{\n  // Initialize the vectors with the correct length\n  for (unsigned int k = 0; k < this->NLasers; ++k)\n  {\n    this->IsPointValid[k].resize(this->pclCurrentFrameByScan[k]->size(), 1);\n    this->Label[k].resize(this->pclCurrentFrameByScan[k]->size(), 0);\n    this->Angles[k].resize(this->pclCurrentFrameByScan[k]->size(),0);\n    this->LengthResolution[k].resize(this->pclCurrentFrameByScan[k]->size(),0);\n    this->SaillantPoint[k].resize(this->pclCurrentFrameByScan[k]->size(),0);\n    this->DepthGap[k].resize(this->pclCurrentFrameByScan[k]->size(), 0);\n    this->IntensityGap[k].resize(this->pclCurrentFrameByScan[k]->size(), 0);\n    this->BlobScore[k].resize(this->pclCurrentFrameByScan[k]->size(), 0);\n  }\n\n  // compute keypoints scores\n  this->ComputeCurvature(input);\n\n  // Invalid points with bad criteria\n  this->InvalidPointWithBadCriteria();\n\n  // labelize keypoints\n  this->SetKeyPointsLabels(input);\n}\n\n//-----------------------------------------------------------------------------\nvoid vtkSlam::ComputeCurvature(vtkSmartPointer<vtkPolyData> vtkNotUsed(input))\n{\n  Point currentPoint, nextPoint, previousPoint;\n  Eigen::Vector3d X, centralPoint;\n  LineFitting leftLine, rightLine, farNeighborsLine;\n\n  // loop over scans lines\n  for (unsigned int scanLine = 0; scanLine < this->NLasers; ++scanLine)\n  {\n    // loop over points in the current scan line\n    int Npts = this->pclCurrentFrameByScan[scanLine]->size();\n\n    // if the line is almost empty, skip it\n    if (Npts < 2 * this->NeighborWidth + 1)\n    {\n      continue;\n    }\n\n    for (int index = this->NeighborWidth; (index + this->NeighborWidth) < Npts; ++index)\n    {\n      // central point\n      currentPoint = this->pclCurrentFrameByScan[scanLine]->points[index];\n      centralPoint << currentPoint.x, currentPoint.y, currentPoint.z;\n\n      // compute intensity gap\n      nextPoint = this->pclCurrentFrameByScan[scanLine]->points[index + 1];\n      previousPoint = this->pclCurrentFrameByScan[scanLine]->points[index - 1];\n      this->IntensityGap[scanLine][index] = std::abs(nextPoint.normal_z - previousPoint.normal_z);\n      // We will compute the line that fit the neighbors located\n      // previously the current. We will do the same for the\n      // neighbors located after the current points. We will then\n      // compute the angle between these two lines as an approximation\n      // of the \"sharpness\" of the current point.\n      std::vector<Eigen::Vector3d > leftNeighbor;\n      std::vector<Eigen::Vector3d > rightNeighbor;\n      std::vector<Eigen::Vector3d > farNeighbors;\n\n      // Fill right and left neighborhood\n      // /!\\ The way the neighbors are added\n      // to the vectors matters. Especially when\n      // computing the saillancy\n      for (int j = index - this->NeighborWidth; j <= index + this->NeighborWidth; ++j)\n      {\n        currentPoint = this->pclCurrentFrameByScan[scanLine]->points[j];\n        X << currentPoint.x, currentPoint.y, currentPoint.z;\n        if (j < index)\n          leftNeighbor.push_back(X);\n        if (j > index)\n          rightNeighbor.push_back(X);\n      }\n\n      // Fit line on the neighborhood and\n      // Indicate if the left and right side\n      // neighborhood of the current point is flat or not\n      bool leftFlat = leftLine.FitPCAAndCheckConsistency(leftNeighbor);\n      bool rightFlat = rightLine.FitPCAAndCheckConsistency(rightNeighbor);\n\n      // Measurement of the gap\n      double dist1 = 0; double dist2 = 0;\n\n      // if both neighborhood are flat we can compute\n      // the angle between them as an approximation of the\n      // sharpness of the current point\n      if (rightFlat && leftFlat)\n      {\n        // We check that the current point is not too far from its\n        // neighborhood lines. This is because we don't want a point\n        // to be considered as a angles point if it is due to gap\n        dist1 = std::sqrt((centralPoint - leftLine.Position).transpose() * leftLine.SemiDist * (centralPoint - leftLine.Position));\n        dist2 = std::sqrt((centralPoint - rightLine.Position).transpose() * rightLine.SemiDist * (centralPoint - rightLine.Position));\n\n        if ((dist1 < this->DistToLineThreshold) && (dist2 < this->DistToLineThreshold))\n          this->Angles[scanLine][index] = std::abs((leftLine.Direction.cross(rightLine.Direction)).norm()); // sin of angle actually\n      }\n      // Here one side of the neighborhood is non flat\n      // Hence it is not worth to estimate the sharpness.\n      // Only the gap will be considered here.\n      else if (rightFlat && !leftFlat)\n      {\n        dist1 = 1000.0;\n        for (unsigned int neighIndex = 0; neighIndex < leftNeighbor.size(); ++neighIndex)\n        {\n          dist1 = std::min(dist1,\n                  std::sqrt((leftNeighbor[neighIndex] - rightLine.Position).transpose() * rightLine.SemiDist * (leftNeighbor[neighIndex] - rightLine.Position)));\n        }\n        dist1 = 0.5 * dist1;\n      }\n      else if (!rightFlat && leftFlat)\n      {\n        dist2 = 1000.0;\n        for (unsigned int neighIndex = 0; neighIndex < leftNeighbor.size(); ++neighIndex)\n        {\n          dist2 = std::min(dist2,\n                  std::sqrt((rightNeighbor[neighIndex] - leftLine.Position).transpose() * leftLine.SemiDist * (rightNeighbor[neighIndex] - leftLine.Position)));\n        }\n        dist2 = 0.5 * dist2;\n      }\n      else\n      {\n        // Compute saillant point score\n        double currDepth = centralPoint.norm();\n        unsigned int diffDepth = 0;\n        bool canLeftBeAdded = true; bool hasLeftEncounteredDepthGap = false;\n        bool canRightBeAdded = true; bool hasRightEncounteredDepthGap = false;\n\n        // The saillant point score is the distance between the current point\n        // and the points that have a depth gap with the current point\n        for (unsigned int neighIndex = 0; neighIndex < leftNeighbor.size(); ++neighIndex)\n        {\n          // Left neighborhood depth gap computation\n          if ((std::abs(leftNeighbor[leftNeighbor.size() - 1 - neighIndex].norm() - currDepth) > 1.5) && canLeftBeAdded)\n          {\n            hasLeftEncounteredDepthGap = true;\n            diffDepth++;\n            farNeighbors.push_back(leftNeighbor[neighIndex]);\n          }\n          else\n          {\n            if (hasLeftEncounteredDepthGap)\n            {\n              canLeftBeAdded = false;\n            }\n          }\n          // Right neigborhood depth gap computation\n          if ((std::abs(rightNeighbor[neighIndex].norm() - currDepth) > 1.5) && canRightBeAdded)\n          {\n            hasRightEncounteredDepthGap = true;\n            diffDepth++;\n            farNeighbors.push_back(rightNeighbor[neighIndex]);\n          }\n          else\n          {\n            if (hasRightEncounteredDepthGap)\n            {\n              canRightBeAdded = false;\n            }\n          }\n        }\n\n        // If there is enought neighbors with a big depth gap\n        // we propose to compute the saillancy of the current\n        // as the distance between the line that fits the neighbors\n        // with a depth gap and the current point\n        if (static_cast<double>(diffDepth) / (2.0 * this->NeighborWidth) > 0.5)\n        {\n          farNeighborsLine.FitPCA(farNeighbors);\n          this->SaillantPoint[scanLine][index] = std::sqrt(\n            (centralPoint - farNeighborsLine.Position).transpose() * farNeighborsLine.SemiDist * (centralPoint - farNeighborsLine.Position));\n        }\n\n        this->BlobScore[scanLine][index] = 1;\n      }\n\n      this->DepthGap[scanLine][index] = std::max(dist1, dist2);\n    }\n  }\n}\n\n//-----------------------------------------------------------------------------\nvoid vtkSlam::InvalidPointWithBadCriteria()\n{\n  // Temporary variables used in the next loop\n  Eigen::Vector3d dX, X, Xn, Xp, Xproj, dXproj;\n  Eigen::Vector3d Y, Yn, Yp, dY;\n  double L, Ln, expectedLength, dLn, dLp;\n  Point currentPoint, nextPoint, previousPoint;\n  Point temp;\n\n  // loop over scan lines\n  for (unsigned int scanLine = 0; scanLine < this->NLasers; ++scanLine)\n  {\n    int Npts = this->pclCurrentFrameByScan[scanLine]->size();\n\n    // if the line is almost empty, skip it\n    if (Npts < 3 * this->NeighborWidth)\n    {\n      continue;\n    }\n    // invalidate first and last points\n    for (int index = 0; index <= this->NeighborWidth; ++index)\n    {\n      this->IsPointValid[scanLine][index] = 0;\n    }\n    for (int index = Npts - 1 - this->NeighborWidth - 1; index < Npts; ++index)\n    {\n      this->IsPointValid[scanLine][index] = 0;\n    }\n\n    // loop over points into the scan line\n    for (int index = this->NeighborWidth; index <  Npts - this->NeighborWidth - 1; ++index)\n    {\n      currentPoint = this->pclCurrentFrameByScan[scanLine]->points[index];\n      nextPoint = this->pclCurrentFrameByScan[scanLine]->points[index + 1];\n      previousPoint = this->pclCurrentFrameByScan[scanLine]->points[index - 1];\n      X << currentPoint.x, currentPoint.y, currentPoint.z;\n      Xn << nextPoint.x, nextPoint.y, nextPoint.z;\n      Xp << previousPoint.x, previousPoint.y, previousPoint.z;\n      dX = Xn - X;\n      L = X.norm();\n      Ln = Xn.norm();\n      dLn = dX.norm();\n\n      // the expected length between two firing of the same laser\n      // depend on the distance and the angular resolution of the\n      // sensor.\n      expectedLength = 2.0 *  std::tan(this->AngleResolution / 2.0) * L;\n      double ratioExpectedLength = 10.0;\n\n      // if the length between the two firing\n      // is more than n-th the expected length\n      // it means that there is a gap. We now must\n      // determine if the gap is due to the geometry of\n      // the scene or if the gap is due to an occluded area\n      if (dLn > ratioExpectedLength * expectedLength)\n      {\n        // Project the next point onto the\n        // sphere of center 0 and radius =\n        // norm of the current point. If the\n        // gap has disappeared it means that\n        // the gap was due to an occlusion\n        Xproj = L / Ln * Xn;\n        dXproj = Xproj - X;\n        // it is a depth gap, invalidate the part which belong\n        // to the occluded area (farest)\n        // invalid next part\n        if (L < Ln)\n        {\n          for (int i = index + 1; i <= index + this->NeighborWidth; ++i)\n          {\n            if (i > index + 1)\n            {\n              temp = this->pclCurrentFrameByScan[scanLine]->points[i - 1];\n              Yp << temp.x, temp.y, temp.z;\n              temp = this->pclCurrentFrameByScan[scanLine]->points[i];\n              Y << temp.x, temp.y, temp.z;\n              dY = Y - Yp;\n              // if there is a gap in the neihborhood\n              // we do not invalidate the rest of neihborhood\n              if (dY.norm() > ratioExpectedLength * expectedLength)\n              {\n                break;\n              }\n            }\n            this->IsPointValid[scanLine][i] = 0;\n          }\n        }\n        // invalid previous part\n        else\n        {\n          for (int i = index - this->NeighborWidth; i <= index; ++i)\n          {\n            if (i < index)\n            {\n              temp = this->pclCurrentFrameByScan[scanLine]->points[i + 1];\n              Yn << temp.x, temp.y, temp.z;\n              temp = this->pclCurrentFrameByScan[scanLine]->points[i];\n              Y << temp.x, temp.y, temp.z;\n              dY = Yn - Y;\n              // if there is a gap in the neihborhood\n              // we do not invalidate the rest of neihborhood\n              if (dY.norm() > ratioExpectedLength * expectedLength)\n              {\n                break;\n              }\n            }\n            this->IsPointValid[scanLine][i] = 0;\n          }\n        }\n      }\n      // Invalid points which are too close from the sensor\n      if (L < this->MinDistanceToSensor)\n      {\n        this->IsPointValid[scanLine][index] = 0;\n      }\n\n      // Invalid points which are on a planar\n      // surface nearly parallel to the laser\n      // beam direction\n      dLp = (X - Xp).norm();\n      if ((dLp > 1 / 4.0 * ratioExpectedLength * expectedLength) && (dLn > 1 / 4.0 * ratioExpectedLength * expectedLength))\n      {\n        this->IsPointValid[scanLine][index] = 0;\n      }\n    }\n  }\n}\n\n//-----------------------------------------------------------------------------\nvoid vtkSlam::SetKeyPointsLabels(vtkSmartPointer<vtkPolyData> vtkNotUsed(input))\n{\n  this->EdgesIndex.clear(); this->EdgesIndex.resize(0);\n  this->PlanarIndex.clear(); this->PlanarIndex.resize(0);\n  this->BlobIndex.clear(); this->BlobIndex.resize(0);\n\n  // loop over the scan lines\n  for (unsigned int scanLine = 0; scanLine < this->NLasers; ++scanLine)\n  {\n    int Npts = this->pclCurrentFrameByScan[scanLine]->size();\n    unsigned int nbrEdgePicked = 0;\n    unsigned int nbrPlanarPicked = 0;\n\n    // We split the validity of points between the edges\n    // keypoints and planar keypoints. This allows to take\n    // some points as planar keypoints even if they are close\n    // to an edge keypoint.\n    std::vector<int> IsPointValidForPlanar = this->IsPointValid[scanLine];\n\n    // if the line is almost empty, skip it\n    if (Npts < 3 * this->NeighborWidth)\n    {\n      continue;\n    }\n\n    // Sort the curvature score in a decreasing order\n    std::vector<size_t> sortedDepthGapIdx = sortIdx<double>(this->DepthGap[scanLine]);\n    std::vector<size_t> sortedAnglesIdx = sortIdx<double>(this->Angles[scanLine]);\n    std::vector<size_t> sortedSaillancyIdx = sortIdx<double>(this->SaillantPoint[scanLine]);\n    std::vector<size_t> sortedIntensityGap = sortIdx<double>(this->IntensityGap[scanLine]);\n\n    double depthGap, sinAngle, saillancy, intensity;\n    int index = 0;\n\n    // Edges using depth gap\n    for (int k = 0; k < Npts; ++k)\n    {\n      index = sortedDepthGapIdx[k];\n      depthGap = this->DepthGap[scanLine][index];\n\n      // thresh\n      if (depthGap < this->EdgeDepthGapThreshold)\n      {\n        break;\n      }\n\n      // if the point is invalid continue\n      if (this->IsPointValid[scanLine][index] == 0)\n      {\n        continue;\n      }\n\n      // else indicate that the point is an edge\n      this->Label[scanLine][index] = 4;\n      this->EdgesIndex.push_back(std::pair<int, int>(scanLine, index));\n      nbrEdgePicked++;\n      //IsPointValidForPlanar[index] = 0;\n\n      // invalid its neighborhod\n      int indexBegin = index - this->NeighborWidth + 1;\n      int indexEnd = index + this->NeighborWidth - 1;\n      indexBegin = std::max(0, indexBegin);\n      indexEnd = std::min(Npts - 1, indexEnd);\n      for (int j = indexBegin; j <= indexEnd; ++j)\n      {\n        this->IsPointValid[scanLine][j] = 0;\n      }\n    }\n\n    // Edges using angles\n    for (int k = 0; k < Npts; ++k)\n    {\n      index = sortedAnglesIdx[k];\n      sinAngle = this->Angles[scanLine][index];\n\n      // thresh\n      if (sinAngle < this->EdgeSinAngleThreshold)\n      {\n        break;\n      }\n\n      // if the point is invalid continue\n      if (this->IsPointValid[scanLine][index] == 0)\n      {\n        continue;\n      }\n\n      // else indicate that the point is an edge\n      this->Label[scanLine][index] = 4;\n      this->EdgesIndex.push_back(std::pair<int, int>(scanLine, index));\n      nbrEdgePicked++;\n      //IsPointValidForPlanar[index] = 0;\n\n      // invalid its neighborhod\n      int indexBegin = index - this->NeighborWidth;\n      int indexEnd = index + this->NeighborWidth;\n      indexBegin = std::max(0, indexBegin);\n      indexEnd = std::min(Npts - 1, indexEnd);\n      for (int j = indexBegin; j <= indexEnd; ++j)\n      {\n        this->IsPointValid[scanLine][j] = 0;\n      }\n    }\n\n    // Edges using saillancy\n    for (int k = 0; k < Npts; ++k)\n    {\n      index = sortedSaillancyIdx[k];\n      saillancy = this->SaillantPoint[scanLine][index];\n\n      // thresh\n      if (saillancy < 1.5)\n      {\n        break;\n      }\n\n      // if the point is invalid continue\n      if (this->IsPointValid[scanLine][index] == 0)\n      {\n        continue;\n      }\n\n      // else indicate that the point is an edge\n      this->Label[scanLine][index] = 4;\n      this->EdgesIndex.push_back(std::pair<int, int>(scanLine, index));\n      nbrEdgePicked++;\n      //IsPointValidForPlanar[index] = 0;\n\n      // invalid its neighborhod\n      int indexBegin = index - this->NeighborWidth + 1;\n      int indexEnd = index + this->NeighborWidth - 1;\n      indexBegin = std::max(0, indexBegin);\n      indexEnd = std::min(Npts - 1, indexEnd);\n      for (int j = indexBegin; j <= indexEnd; ++j)\n      {\n        this->IsPointValid[scanLine][j] = 0;\n      }\n    }\n\n    // Edges using intensity\n    for (int k = 0; k < Npts; ++k)\n    {\n      index = sortedIntensityGap[k];\n      intensity = this->IntensityGap[scanLine][index];\n\n      // thresh\n      if (intensity < 50.0)\n      {\n        break;\n      }\n\n      // if the point is invalid continue\n      if (this->IsPointValid[scanLine][index] == 0)\n      {\n        continue;\n      }\n\n      // else indicate that the point is an edge\n      this->Label[scanLine][index] = 4;\n      this->EdgesIndex.push_back(std::pair<int, int>(scanLine, index));\n      nbrEdgePicked++;\n      //IsPointValidForPlanar[index] = 0;\n\n      // invalid its neighborhood\n      int indexBegin = index - 1;\n      int indexEnd = index + 1;\n      indexBegin = std::max(0, indexBegin);\n      indexEnd = std::min(Npts - 1, indexEnd);\n      for (int j = indexBegin; j <= indexEnd; ++j)\n      {\n        this->IsPointValid[scanLine][j] = 0;\n      }\n    }\n\n    // Blobs Points\n    if (!this->FastSlam)\n    {\n      for (int k = 0; k < Npts; k = k + 3)\n      {\n        this->BlobIndex.push_back(std::pair<int, int>(scanLine, k));\n      }\n    }\n\n    // Planes\n    for (int k = Npts - 1; k >= 0; --k)\n    {\n      index = sortedAnglesIdx[k];\n      sinAngle = this->Angles[scanLine][index];\n\n      // thresh\n      if (sinAngle > this->PlaneSinAngleThreshold)\n      {\n        break;\n      }\n\n      // if the point is invalid continue\n      if (IsPointValidForPlanar[index] == 0)\n      {\n        continue;\n      }\n\n      // else indicate that the point is a planar one\n      if ((this->Label[scanLine][index] != 4) && (this->Label[scanLine][index] != 3))\n        this->Label[scanLine][index] = 2;\n      this->PlanarIndex.push_back(std::pair<int, int>(scanLine, index));\n      IsPointValidForPlanar[index] = 0;\n      this->IsPointValid[scanLine][index] = 0;\n\n      // Invalid its neighbor so that we don't have too\n      // many planar keypoints in the same region. This is\n      // required because of the k-nearest search + plane\n      // approximation realized in the odometry part. Indeed,\n      // if all the planar points are on the same scan line the\n      // problem is degenerated since all the points are distributed\n      // on a line.\n      int indexBegin = index - 4;\n      int indexEnd = index + 4;\n      indexBegin = std::max(0, indexBegin);\n      indexEnd = std::min(Npts - 1, indexEnd);\n      for (int j = indexBegin; j <= indexEnd; ++j)\n      {\n        IsPointValidForPlanar[j] = 0;\n      }\n      nbrPlanarPicked++;\n    }\n  }\n\n  // add keypoints in increasing scan id order\n  std::sort(this->EdgesIndex.begin(), this->EdgesIndex.end());\n  std::sort(this->PlanarIndex.begin(), this->PlanarIndex.end());\n  std::sort(this->BlobIndex.begin(), this->BlobIndex.end());\n\n  // fill the keypoints vectors and compute the max dist keypoints\n  this->FarestKeypointDist = 0.0;\n  Point p;\n  for (unsigned int k = 0; k < this->EdgesIndex.size(); ++k)\n  {\n    p = this->pclCurrentFrameByScan[this->EdgesIndex[k].first]->points[this->EdgesIndex[k].second];\n    this->CurrentEdgesPoints->push_back(p);\n    this->FarestKeypointDist = std::max(this->FarestKeypointDist, static_cast<double>(std::sqrt(std::pow(p.x, 2) + std::pow(p.y, 2) + std::pow(p.z, 2))));\n  }\n  for (unsigned int k = 0; k < this->PlanarIndex.size(); ++k)\n  {\n    p = this->pclCurrentFrameByScan[this->PlanarIndex[k].first]->points[this->PlanarIndex[k].second];\n    this->CurrentPlanarsPoints->push_back(p);\n    this->FarestKeypointDist = std::max(this->FarestKeypointDist, static_cast<double>(std::sqrt(std::pow(p.x, 2) + std::pow(p.y, 2) + std::pow(p.z, 2))));\n  }\n  for (unsigned int k = 0; k < this->BlobIndex.size();  ++k)\n  {\n    p = this->pclCurrentFrameByScan[this->BlobIndex[k].first]->points[this->BlobIndex[k].second];\n    this->CurrentBlobsPoints->push_back(p);\n    this->FarestKeypointDist = std::max(this->FarestKeypointDist, static_cast<double>(std::sqrt(std::pow(p.x, 2) + std::pow(p.y, 2) + std::pow(p.z, 2))));\n  }\n\n  // Initialize the IsKeypointUsed vectors\n  this->EdgePointRejectionEgoMotion.clear(); this->EdgePointRejectionEgoMotion.resize(this->CurrentEdgesPoints->size());\n  this->PlanarPointRejectionEgoMotion.clear(); this->PlanarPointRejectionEgoMotion.resize(this->CurrentPlanarsPoints->size());\n  this->EdgePointRejectionMapping.clear(); this->EdgePointRejectionMapping.resize(this->CurrentEdgesPoints->size());\n  this->PlanarPointRejectionMapping.clear(); this->PlanarPointRejectionMapping.resize(this->CurrentPlanarsPoints->size());\n\n  // keypoints extraction informations\n  std::cout << \"Extracted Edges: \" << this->CurrentEdgesPoints->size() << \" Planars: \"\n            << this->CurrentPlanarsPoints->size() << \" Blobs: \"\n            << this->CurrentBlobsPoints->size() << std::endl;\n}\n\n//-----------------------------------------------------------------------------\nvoid vtkSlam::TransformToWorld(Point& p)\n{\n  if (this->Undistortion)\n  {\n    this->ExpressPointInOtherReferencial(p, this->MappingInterpolator);\n  }\n  else\n  {\n    // Rotation and translation and points\n    Eigen::Matrix3d Rw;\n    Eigen::Vector3d Tw;\n    Eigen::Vector3d P;\n\n    Rw = GetRotationMatrix(this->Tworld);\n    Tw << this->Tworld(3), this->Tworld(4), this->Tworld(5);\n    P << p.x, p.y, p.z;\n\n    P = Rw * P + Tw;\n\n    p.x = P(0);\n    p.y = P(1);\n    p.z = P(2);\n  }\n}\n\n//-----------------------------------------------------------------------------\nint vtkSlam::ComputeLineDistanceParameters(pcl::KdTreeFLANN<Point>::Ptr kdtreePreviousEdges, Eigen::Matrix3d& R,\n                                                   Eigen::Vector3d& dT, Point p, std::string step)\n{\n  // number of neighbors edge points required to approximate\n  // the corresponding egde line\n  unsigned int requiredNearest;\n  unsigned int eigenValuesRatio;\n\n  // maximum distance between keypoints\n  // and their computed line\n  double maxDist;\n\n  if (step == \"egoMotion\")\n  {\n    requiredNearest = 2;//this->EgoMotionLineDistanceNbrNeighbors;\n    eigenValuesRatio = this->EgoMotionLineDistancefactor;\n    maxDist = std::pow(this->EgoMotionMaxLineDistance, 2);\n  }\n  else if (step == \"mapping\")\n  {\n    requiredNearest = this->MappingLineDistanceNbrNeighbors;\n    eigenValuesRatio = this->MappingLineDistancefactor;\n    maxDist = std::pow(this->MappingMaxLineDistance, 2);\n  }\n  else\n  {\n    throw \"ComputeLineDistanceParameters function got invalide step parameter\";\n  }\n\n\n  Eigen::Vector3d P0, P, n;\n  Eigen::Matrix3d A;\n\n  // Transform the point using the current pose estimation\n  P0 << p.x, p.y, p.z;\n\n  if (this->Undistortion) // linear interpolated transform\n  {\n    if (step == \"egoMotion\")\n    {\n      this->ExpressPointInOtherReferencial(p, this->EgoMotionInterpolator);\n    }\n    else if (step == \"mapping\")\n    {\n      this->ExpressPointInOtherReferencial(p, this->MappingInterpolator);\n    }\n  }\n  else // rigid transform\n  {\n    P = R * P0 + dT;\n    p.x = P(0); p.y = P(1); p.z = P(2);\n  }\n\n  std::vector<int> nearestIndex;\n  std::vector<float> nearestDist;\n\n  if (step == \"egoMotion\")\n  {\n    GetEgoMotionLineSpecificNeighbor(nearestIndex, nearestDist, requiredNearest, kdtreePreviousEdges, p);\n    if (nearestIndex.size() < this->EgoMotionMinimumLineNeighborRejection)\n    {\n      return 0;\n    }\n    requiredNearest = nearestIndex.size();\n  }\n  else if (step == \"mapping\")\n  {\n    GetMappingLineSpecificNeigbbor(nearestIndex, nearestDist, this->MappingLineMaxDistInlier, requiredNearest, kdtreePreviousEdges, p);\n    if (nearestIndex.size() < this->MappingMinimumLineNeighborRejection)\n    {\n      return 0;\n    }\n    requiredNearest = nearestIndex.size();\n    //kdtreePreviousEdges->nearestKSearch(p, requiredNearest, nearestIndex, nearestDist);\n  }\n\n  // if the nearest edges are too far from the\n  // current edge keypoint we skip this point.\n  double distScale = std::min(sqrt(pow(p.x,2) + pow(p.y,2) + pow(p.z,2)) / this->MinDistanceToSensor,10.0);\n  if (nearestDist[requiredNearest - 1] > this->MaxDistanceForICPMatching * distScale)\n  {\n    return 1;\n  }\n\n  // Compute PCA to determine best line approximation\n  // of the requiredNearest nearest edges points extracted\n  // Thans to the PCA we will check the shape of the neighborhood\n  // and keep it if it is distributed along a line\n  Eigen::MatrixXd data(requiredNearest, 3);\n\n  for (unsigned int k = 0; k < requiredNearest; k++)\n  {\n    Point pt = kdtreePreviousEdges->getInputCloud()->points[nearestIndex[k]];\n    data.row(k) << pt.x, pt.y, pt.z;\n  }\n\n  Eigen::Vector3d mean = data.colwise().mean();\n  Eigen::MatrixXd centered = data.rowwise() - mean.transpose();\n  Eigen::MatrixXd cov = centered.transpose() * centered;\n  Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> eig(cov);\n\n  // Eigen values\n  Eigen::MatrixXd D(1,3);\n  // Eigen vectors\n  Eigen::MatrixXd V(3,3);\n\n  D = eig.eigenvalues();\n  V = eig.eigenvectors();\n\n  // if the first eigen value is significantly higher than\n  // the second one, it means the sourrounding points are\n  // distributed on a edge line\n  if (D(2) > eigenValuesRatio * D(1))\n  {\n    // n is the director vector of the line\n    n = V.col(2);\n    n.normalized();\n  }\n  else\n  {\n    return 2;\n  }\n\n  // Compute a coefficient based on the linearity of the neighborhood.\n  // We reject the neighborhood if D(2) < k * D(1) and we want our coefficient\n  // varying from 0 to 1.0 with 0 being reached when D(2) = 5 * D(1)\n  double linearityCoeff = 1.0 - eigenValuesRatio * D(1) / D(2);\n\n  // A = (I-n*n.t).t * (I-n*n.t) = (I - n*n.t)^2\n  // since (I-n*n.t) is a symmetric matrix\n  // Then it comes A (I-n*n.t)^2 = (I-n*n.t) since\n  // A is the matrix of a projection endomorphism\n  A = (this->I3 - n * n.transpose());\n  A = A.transpose() * A;\n\n  // it would be the case if P1 = P2 For instance\n  // if the sensor has some dual returns that hit the same point\n  if (!vtkMath::IsFinite(A(0, 0)))\n  {\n    return 3;\n  }\n\n  // Evaluate the distance from the fitted line distribution\n  // of the neighborhood\n  Eigen::Vector3d Xtemp;\n  Point pt;\n  double meanSquaredDist = 0;\n  for (unsigned int k = 0; k < requiredNearest; ++k)\n  {\n    pt = kdtreePreviousEdges->getInputCloud()->points[nearestIndex[k]];\n    Xtemp(0) = pt.x; Xtemp(1) = pt.y; Xtemp(2) = pt.z;\n    double squaredDist = (Xtemp - mean).transpose() * A * (Xtemp - mean);\n    if (squaredDist > maxDist)\n    {\n      return 4;\n    }\n    meanSquaredDist += squaredDist;\n  }\n  meanSquaredDist /= static_cast<double>(requiredNearest);\n  double fitQualityCoeff = 1.0 - std::sqrt(meanSquaredDist / maxDist);\n\n  // distance between current point and the corresponding matching line\n  double s = 1.0;\n  if (step == \"mapping\")\n  {\n    s = 0.5 * fitQualityCoeff + 0.5 * linearityCoeff;\n  }\n  else if (step == \"egoMotion\")\n  {\n    double orthogonalityCoeff = 0.5 + 0.5 * n(2) * n(2); // score the match by its angle with ez\n    // Score the point - line matching by the angle of the\n    // line with ez. The idea is that the lidar is more accurate\n    // in line detection when those lines are colinear with the\n    // azimutal rotation axis.\n    s = 0.33 * fitQualityCoeff + 0.33 * linearityCoeff + 0.33 * orthogonalityCoeff;\n  }\n\n  if (s <= 0 || !vtkMath::IsFinite(s))\n    return 5;\n\n  // store the distance parameters values\n  this->Avalues.push_back(A);\n  this->Pvalues.push_back(mean);\n  this->Xvalues.push_back(P0);\n  this->TimeValues.push_back(p.intensity);\n  this->residualCoefficient.push_back(s);\n  this->RadiusIncertitude.push_back(0.0);\n  return 6;\n}\n\n//-----------------------------------------------------------------------------\nint vtkSlam::ComputePlaneDistanceParameters(pcl::KdTreeFLANN<Point>::Ptr kdtreePreviousPlanes, Eigen::Matrix3d& R,\n                                                    Eigen::Vector3d& dT, Point p, std::string step)\n{\n  // number of neighbors edge points required to approximate\n  // the corresponding egde line\n  unsigned int requiredNearest;\n  unsigned int significantlyFactor1, significantlyFactor2;\n\n  // maximum distance between keypoints\n  // and their computed plane\n  double maxDist;\n\n  if (step == \"egoMotion\")\n  {\n    significantlyFactor1 = this->EgoMotionPlaneDistancefactor1;\n    significantlyFactor2 = this->EgoMotionPlaneDistancefactor2;\n    requiredNearest = this->EgoMotionPlaneDistanceNbrNeighbors;\n    maxDist = std::pow(this->EgoMotionMaxPlaneDistance, 2);\n  }\n  else if (step == \"mapping\")\n  {\n    significantlyFactor1 = this->MappingPlaneDistancefactor1;\n    significantlyFactor2 = this->MappingPlaneDistancefactor2;\n    requiredNearest = this->MappingPlaneDistanceNbrNeighbors;\n    maxDist = std::pow(this->MappingMaxPlaneDistance, 2);\n  }\n  else\n  {\n    throw \"ComputeLineDistanceParameters function got invalide step parameter\";\n  }\n\n  Eigen::Vector3d P0, P, n;\n  Eigen::Matrix3d A;\n\n  // Transform the point using the current pose estimation\n  P0 << p.x, p.y, p.z;\n\n  if (this->Undistortion) // linear interpolated transform\n  {\n    if (step == \"egoMotion\")\n    {\n      this->ExpressPointInOtherReferencial(p, this->EgoMotionInterpolator);\n    }\n    else if (step == \"mapping\")\n    {\n      this->ExpressPointInOtherReferencial(p, this->MappingInterpolator);\n    }\n  }\n  else // rigid transform\n  {\n    P = R * P0 + dT;\n    p.x = P(0); p.y = P(1); p.z = P(2);\n  }\n\n  std::vector<int> nearestIndex;\n  std::vector<float> nearestDist;\n  kdtreePreviousPlanes->nearestKSearch(p, requiredNearest, nearestIndex, nearestDist);\n\n  // It means that there is not enought keypoints in the neighbohood\n  if (nearestIndex.size() < requiredNearest)\n  {\n    return 0;\n  }\n\n  // if the nearest planars are too far from the\n  // current planar keypoint we skip this point.\n  double distScale = std::min(sqrt(pow(p.x,2) + pow(p.y,2) + pow(p.z,2)) / this->MinDistanceToSensor,10.0);\n  if (nearestDist[requiredNearest - 1] > this->MaxDistanceForICPMatching * distScale)\n  {\n    return 1;\n  }\n\n  // Compute PCA to determine best line approximation\n  // of the requiredNearest nearest edges points extracted\n  // Thanks to the PCA we will check the shape of the neighborhood\n  // and keep it if it is distributed along a line\n  Eigen::MatrixXd data(requiredNearest,3);\n\n  for (unsigned int k = 0; k < requiredNearest; k++)\n  {\n    Point pt = kdtreePreviousPlanes->getInputCloud()->points[nearestIndex[k]];\n    data.row(k) << pt.x, pt.y, pt.z;\n  }\n\n  Eigen::Vector3d mean = data.colwise().mean();\n  Eigen::MatrixXd centered = data.rowwise() - mean.transpose();\n  Eigen::MatrixXd cov = centered.transpose() * centered;\n  Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> eig(cov);\n\n  // Eigen values\n  Eigen::MatrixXd D(1,3);\n  // Eigen vectors\n  Eigen::MatrixXd V(3,3);\n\n  D = eig.eigenvalues();\n  V = eig.eigenvectors();\n\n  // if the second eigen value is close to the highest one\n  // and bigger than the smallest one it means that the points\n  // are distributed among a plane\n  Eigen::Vector3d u, v;\n  if ( (significantlyFactor2 * D(1) > D(2)) && (D(1) > significantlyFactor1 * D(0)) )\n  {\n    u = V.col(2);\n    v = V.col(1);\n  }\n  else\n  {\n    return 2;\n  }\n\n  // Compute a coefficient based on the planarity of the neighborhood.\n  double planarityCoeff = (D(1) - D(0)) / D(2);\n\n  n = u.cross(v);\n  n.normalized();\n\n  // A = n*n.t\n  A = n * n.transpose();\n\n  // it would be the case if P1 = P2, P1 = P3\n  // or P3 = P2. For instance if the sensor has\n  // some dual returns that hit the same point\n  if (!vtkMath::IsFinite(A(0, 0)))\n  {\n    return 3;\n  }\n\n  Eigen::Vector3d Xtemp;\n  Point pt;\n  double meanSquaredDist = 0;\n  for (unsigned int k = 0; k < requiredNearest; ++k)\n  {\n    pt = kdtreePreviousPlanes->getInputCloud()->points[nearestIndex[k]];\n    Xtemp(0) = pt.x; Xtemp(1) = pt.y; Xtemp(2) = pt.z;\n    double squaredDist = (Xtemp - mean).transpose() * A * (Xtemp - mean);\n    if (squaredDist > maxDist)\n    {\n      return 4;\n    }\n    meanSquaredDist += squaredDist;\n  }\n  meanSquaredDist /= static_cast<double>(requiredNearest);\n  double fitQualityCoeff = 1.0 - std::sqrt(meanSquaredDist / maxDist);\n\n  // distance between current point and the corresponding matching plane\n  double s = 0.5 * fitQualityCoeff + 0.5 * planarityCoeff;\n\n  if (s <= 0 || !vtkMath::IsFinite(s))\n    return 5;\n\n  // store the distance parameters values\n  this->Avalues.push_back(A);\n  this->Pvalues.push_back(mean);\n  this->Xvalues.push_back(P0);\n  this->residualCoefficient.push_back(s);\n  this->TimeValues.push_back(p.intensity);\n  this->RadiusIncertitude.push_back(0.0);\n  return 6;\n}\n\n//-----------------------------------------------------------------------------\nint vtkSlam::ComputeBlobsDistanceParameters(pcl::KdTreeFLANN<Point>::Ptr kdtreePreviousBlobs, Eigen::Matrix3d& R,\n                                                    Eigen::Vector3d& dT, Point p, std::string vtkNotUsed(step))\n{\n  // number of neighbors blobs points required to approximate\n  // the corresponding ellipsoide\n  unsigned int requiredNearest = 25;\n\n  // maximum distance between keypoints\n  // and its neighbor\n  double maxDist = this->MaxDistanceForICPMatching;\n  float maxDiameterTol = std::pow(4.0, 2);\n\n  // Usefull variables\n  Eigen::Vector3d P0, P, n;\n  Eigen::Matrix3d A;\n\n  // Transform the point using the current pose estimation\n  P << p.x, p.y, p.z;\n  P0 = P;\n  P = R * P + dT;\n  p.x = P(0); p.y = P(1); p.z = P(2);\n\n  std::vector<int> nearestIndex;\n  std::vector<float> nearestDist;\n  kdtreePreviousBlobs->nearestKSearch(p, requiredNearest, nearestIndex, nearestDist);\n\n  // It means that there is not enought keypoints in the neighbohood\n  if (nearestIndex.size() < requiredNearest)\n  {\n    return 0;\n  }\n\n  // if the nearest blobs is too far from the\n  // current blob keypoint we skip this point.\n  if (nearestDist[requiredNearest - 1] > maxDist)\n  {\n    return 1;\n  }\n\n  // check the diameter of the neighborhood\n  // if the diameter is too big we don't want\n  // to keep this blobs. We must do that since\n  // the blobs fitted ellipsoide is assume to\n  // encode the local neighborhood shape.\n  float maxDiameter = 0;\n  for (unsigned int i = 0; i < requiredNearest; ++i)\n  {\n    for (unsigned int j = 0; j < requiredNearest; ++j)\n    {\n      Point pt1 = kdtreePreviousBlobs->getInputCloud()->points[nearestIndex[i]];\n      Point pt2 = kdtreePreviousBlobs->getInputCloud()->points[nearestIndex[j]];\n      float neighborhoodDiameter = std::pow(pt1.x - pt2.x, 2) + std::pow(pt1.y - pt2.y, 2) + std::pow(pt1.z - pt2.z, 2);\n      maxDiameter = std::max(maxDiameter, neighborhoodDiameter);\n    }\n  }\n  if (maxDiameter > maxDiameterTol)\n  {\n    return 2;\n  }\n\n  // Compute PCA to determine best ellipsoide approximation\n  // of the requiredNearest nearest blobs points extracted\n  // Thanks to the PCA we will check the shape of the neighborhood\n  // tune a distance function adapter to the distribution\n  // (Mahalanobis distance)\n  Eigen::MatrixXd data(requiredNearest, 3);\n\n  for (unsigned int k = 0; k < requiredNearest; k++)\n  {\n    Point pt = kdtreePreviousBlobs->getInputCloud()->points[nearestIndex[k]];\n    data.row(k) << pt.x, pt.y, pt.z;\n  }\n\n  Eigen::Vector3d mean = data.colwise().mean();\n  Eigen::MatrixXd centered = data.rowwise() - mean.transpose();\n  Eigen::MatrixXd cov = centered.transpose() * centered;\n\n  // Sigma is the inverse of the covariance\n  // Matrix encoding the mahalanobis distance\n  // check that the covariance matrix is inversible\n  if (std::abs(cov.determinant()) < 1e-6)\n  {\n    return 3;\n  }\n  Eigen::MatrixXd sigma = cov.inverse();\n  Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> eig(sigma);\n\n  // rescale the variance covariance matrix to preserve the\n  // shape of the mahalanobis distance but removing the\n  // variance values scaling\n  Eigen::MatrixXd D = eig.eigenvalues();\n  Eigen::MatrixXd U = eig.eigenvectors();\n  D = D / D(2);\n  Eigen::Matrix3d diagD = Eigen::Matrix3d::Zero();\n  diagD(0, 0) = D(0); diagD(1, 1) = D(1); diagD(2, 2) = D(2);\n  A = U * diagD * U.transpose();\n\n  if (!vtkMath::IsFinite(A.determinant()))\n  {\n    return 4;\n  }\n\n  // Coefficient the distance\n  // using the distance between the point\n  // and its matching blob; The aim is to prevent\n  // wrong matching to pull the point cloud in the\n  // bad direction\n  double s = 1.0;//1.0 - nearestDist[requiredNearest - 1] / maxDist;\n\n  // store the distance parameters values\n  this->Avalues.push_back(A);\n  this->Pvalues.push_back(mean);\n  this->Xvalues.push_back(P0);\n  this->residualCoefficient.push_back(s);\n  this->RadiusIncertitude.push_back(0.0);\n  return 5;\n}\n\n//-----------------------------------------------------------------------------\nvoid vtkSlam::GetEgoMotionLineSpecificNeighbor(std::vector<int>& nearestValid, std::vector<float>& nearestValidDist,\n                                               unsigned int nearestSearch, pcl::KdTreeFLANN<Point>::Ptr kdtreePreviousEdges, Point p)\n{\n  // clear vector\n  nearestValid.clear();\n  nearestValid.resize(0);\n  nearestValidDist.clear();\n  nearestValidDist.resize(0);\n\n  // get nearest neighbor of the query point\n  std::vector<int> nearestIndex;\n  std::vector<float> nearestDist;\n  kdtreePreviousEdges->nearestKSearch(p, nearestSearch*2, nearestIndex, nearestDist);\n\n  // take the closest point\n  std::vector<int> idAlreadyTook(this->NLasers, 0);\n  Point closest = kdtreePreviousEdges->getInputCloud()->points[nearestIndex[0]];\n  nearestValid.push_back(nearestIndex[0]);\n  nearestValidDist.push_back(nearestDist[0]);\n\n  // invalid all possible points that\n  // are on the same scan line than the\n  // closest one\n  idAlreadyTook[(int)closest.normal_y] = 1;\n\n  // invalid all possible points from scan\n  // lines that are too far from the closest one\n  for (unsigned int k = 0; k < this->NLasers; ++k)\n  {\n    if (std::abs(closest.normal_y - k) > 3)\n    {\n      idAlreadyTook[k] = 1;\n    }\n  }\n\n  // Make a selection among the neighborhood\n  // of the query point. We can only take one edge\n  // per scan line\n  int id;\n  for (unsigned int k = 1; k < nearestIndex.size(); ++k)\n  {\n    id = kdtreePreviousEdges->getInputCloud()->points[nearestIndex[k]].normal_y;\n    if (idAlreadyTook[id] < 1)\n    {\n      idAlreadyTook[id] = 1;\n      nearestValid.push_back(nearestIndex[k]);\n      nearestValidDist.push_back(nearestDist[k]);\n    }\n  }\n}\n\n//-----------------------------------------------------------------------------\nvoid vtkSlam::GetMappingLineSpecificNeigbbor(std::vector<int>& nearestValid, std::vector<float>& nearestValidDist, double maxDistInlier,\n                                             unsigned int nearestSearch, pcl::KdTreeFLANN<Point>::Ptr kdtreePreviousEdges, Point p)\n{\n  // reset vectors\n  nearestValid.clear();\n  nearestValid.resize(0);\n  nearestValidDist.clear();\n  nearestValidDist.resize(0);\n\n  // to prevent square root when making camparisons\n  maxDistInlier = std::pow(maxDistInlier, 2);\n\n  // Take the neighborhood of the query point\n  // get nearest neighbor of the query point\n  std::vector<int> nearestIndex;\n  std::vector<float> nearestDist;\n  kdtreePreviousEdges->nearestKSearch(p, nearestSearch, nearestIndex, nearestDist);\n\n  // take the closest point\n  std::vector<std::vector<int> > inliersList;\n  Point closest = kdtreePreviousEdges->getInputCloud()->points[nearestIndex[0]];\n  nearestValid.push_back(nearestIndex[0]);\n  nearestValidDist.push_back(nearestDist[0]);\n\n  Eigen::Vector3d P1, P2, dir, Pcdt;\n  Eigen::Matrix3d D;\n  P1 << closest.x, closest.y, closest.z;\n  Point pclP2;\n  Point inlierCandidate;\n\n  // Loop over other neighbors of the neighborhood. For each of them\n  // compute the line between closest point and current point and\n  // compute the number of inlier that fit this line. Keep the line and its\n  // inmliers with the most inliers\n  for (unsigned int ptIndex = 1; ptIndex < nearestIndex.size(); ++ptIndex)\n  {\n    std::vector<int> inlierIndex;\n    pclP2 = kdtreePreviousEdges->getInputCloud()->points[nearestIndex[ptIndex]];\n    P2 << pclP2.x, pclP2.y, pclP2.z;\n    dir = (P2 - P1).normalized();\n    D = this->I3 - dir * dir.transpose();\n    D = D.transpose() * D;\n\n    for (unsigned int candidateIndex = 1; candidateIndex < nearestIndex.size(); ++candidateIndex)\n    {\n      inlierCandidate = kdtreePreviousEdges->getInputCloud()->points[nearestIndex[candidateIndex]];\n      Pcdt << inlierCandidate.x, inlierCandidate.y, inlierCandidate.z;\n      if ( (Pcdt - P1).transpose() * D * (Pcdt - P1) < maxDistInlier)\n      {\n        inlierIndex.push_back(candidateIndex);\n      }\n    }\n    inliersList.push_back(inlierIndex);\n  }\n\n  std::size_t maxInliers = 0;\n  int indexMaxInliers = -1;\n  for (unsigned int k = 0; k < inliersList.size(); ++k)\n  {\n    if (inliersList[k].size() > maxInliers)\n    {\n      maxInliers = inliersList[k].size();\n      indexMaxInliers = k;\n    }\n  }\n\n  // fill\n  for (unsigned int k = 0; k < inliersList[indexMaxInliers].size(); ++k)\n  {\n    nearestValid.push_back(nearestIndex[inliersList[indexMaxInliers][k]]);\n    nearestValidDist.push_back(nearestDist[inliersList[indexMaxInliers][k]]);\n  }\n\n  return;\n}\n\n//-----------------------------------------------------------------------------\nvoid vtkSlam::ComputeImuMotion()\n{\n  Eigen::Vector3d avgAcc, Acc;\n  Eigen::Vector3d avgGyro, Gyro;\n  avgAcc << 0,0,0;\n  avgGyro << 0,0,0;\n  Acc << 0,0,0;\n  Gyro << 0,0,0;\n  double timeDiff;\n  this->ImuTrelative = Eigen::Matrix<double, 6, 1>::Zero();\n\n  if (this->UsingImu && this->CurrentFrameTime != this->PreviousFrameTime)\n  {\n      int count = 0, row = this->ImuDataRow;\n      while (this->ImuData->GetRowData()->GetArray(\"adjustedtime\")->GetTuple1(row) > this->PreviousFrameTime && row > 0)\n      {\n        row--;\n      }\n      while (this->ImuData->GetRowData()->GetArray(\"adjustedtime\")->GetTuple1(row) <= this->PreviousFrameTime)\n      {\n        row++;\n      }\n      auto imuTable = this->ImuData->GetRowData();\n\n      while (this->ImuData->GetRowData()->GetArray(\"adjustedtime\")->GetTuple1(row) <= this->CurrentFrameTime)\n      {\n\n        avgAcc(0) += imuTable->GetArray(\"Acc_X\")->GetTuple1(row);\n        avgAcc(1) += imuTable->GetArray(\"Acc_Y\")->GetTuple1(row);\n        avgAcc(2) += imuTable->GetArray(\"Acc_Z\")->GetTuple1(row);\n        avgGyro(0) += Deg2Rad(imuTable->GetArray(\"Gyro_X\")->GetTuple1(row));\n        avgGyro(1) += Deg2Rad(imuTable->GetArray(\"Gyro_Y\")->GetTuple1(row));\n        avgGyro(2) += Deg2Rad(imuTable->GetArray(\"Gyro_Z\")->GetTuple1(row));\n\n        count++;\n        row++;\n\n      }\n      avgAcc /= count;\n      avgGyro /= count;\n\n      Eigen::Matrix<double, 6, 1> calib;\n      calib << 0, 0, 0, 0, 0, 0;\n      Eigen::Matrix3d calibR = GetRotationMatrix(calib);\n\n      timeDiff = (this->CurrentFrameTime - this->PreviousFrameTime) * 1e-6;\n\n      //adjust gyro\n      Eigen::Vector3d avgGyroC;// = calibR * avgGyro;\n      avgGyroC << avgGyro(1), avgGyro(0), -avgGyro(2);\n\n      //anglular change\n      Eigen::Vector3d angularChangeC = avgGyroC*timeDiff;\n\n      //angular change matrix\n      Eigen::Matrix<double,6,1> angularCM;\n      angularCM << angularChangeC,0,0,0;\n\n      //Angle change rotation matrix\n      Eigen::Matrix3d angularRotationCM = GetRotationMatrix(angularCM);\n\n      // Angle change rotation matrix calibrated0\n\n      // acceleration calibrated\n      Eigen::Vector3d avgAccC;// = calibR * avgAcc;\n      avgAccC << avgAcc(1), avgAcc(0), -avgAcc(2);\n\n      // velocity change\n      Eigen::Vector3d velocityChange = avgAccC * timeDiff;\n\n      //linear velocity\n      Eigen::Vector3d linearChange = (this->Velocity + (velocityChange * 0.5)) * timeDiff;\n      this->Velocity += velocityChange;\n\n      Eigen::Vector3d transform;\n      transform = angularRotationCM * linearChange;\n\n      double rx = std::atan2(angularRotationCM(2, 1), angularRotationCM(2, 2));\n      double ry = -std::asin(angularRotationCM(2, 0));\n      double rz = std::atan2(angularRotationCM(1, 0), angularRotationCM(0, 0));\n\n      this->ImuTrelative << rx, ry, rz, transform;\n\n      this->Trelative << ImuTrelative;\n\n      this->ImuVariation << abs(this->ImuTrelative(0) * (1 - this->ImuConfidence(0))),\n        abs(this->ImuTrelative(1) * (1 - this->ImuConfidence(1))),\n        abs(this->ImuTrelative(2) * (1 - this->ImuConfidence(2))),\n        abs(this->ImuTrelative(3) * (1 - this->ImuConfidence(3))),\n        abs(this->ImuTrelative(4) * (1 - this->ImuConfidence(4))),\n        abs(this->ImuTrelative(5) * (1 - this->ImuConfidence(5)));\n      std::cout << \"ImuVariation: \" << this->ImuVariation.transpose() << std::endl;\n\n\n      std::cout << \"========== IMU-Motion ==========\" << std::endl;\n      std::cout << \"Time: \" << timeDiff << std::endl;\n      std::cout << \"row: \" << row << std::endl;\n      std::cout << \"count: \" << count << std::endl;\n      std::cout << \"Gyro: \" << avgGyro.transpose() << std::endl;\n      std::cout << \"GyroC: \" << avgGyroC.transpose() << std::endl;\n      //std::cout << \"angularChangeC: \" << angularChangeC.transpose() << std::endl;\n      std::cout << \"Acc: \" << avgAcc.transpose() << std::endl;\n      std::cout << \"AccC: \" << avgAccC.transpose() << std::endl;\n      std::cout << \"Velocity: \" << this->Velocity.transpose() << std::endl;\n\n      if (this->OnlyImu) //for testing only\n      {\n        UpdateTworldUsingTrelative();\n      }\n  }\n\n}\n\n\nvoid vtkSlam::ComputeImuMotionTest()\n{\n  Eigen::Vector3d avgAcc, Acc;\n  Eigen::Vector3d avgGyro, Gyro;\n  avgAcc << 0,0,0;\n  avgGyro << 0,0,0;\n  Acc << 0,0,0;\n  Gyro << 0,0,0;\n  double timeDiff;\n  this->ImuTrelative = Eigen::Matrix<double, 6, 1>::Zero();\n\n\n  if (this->UsingImu && this->CurrentFrameTime != this->PreviousFrameTime)\n  {\n      int count = 0, row = this->ImuDataRow;\n      while (this->ImuData->GetRowData()->GetArray(\"adjustedtime\")->GetTuple1(row) > this->PreviousFrameTime && row > 0)\n      {\n        row--;\n      }\n      while (this->ImuData->GetRowData()->GetArray(\"adjustedtime\")->GetTuple1(row) <= this->PreviousFrameTime)\n      {\n        row++;\n      }\n      auto imuTable = this->ImuData->GetRowData();\n\n      while (this->ImuData->GetRowData()->GetArray(\"adjustedtime\")->GetTuple1(row) <= this->CurrentFrameTime)\n      {\n        timeDiff = (this->ImuData->GetRowData()->GetArray(\"adjustedtime\")->GetTuple1(row) - this->ImuData->GetRowData()->GetArray(\"adjustedtime\")->GetTuple1(row - 1)) * 1e-6;\n        Acc(0) = (imuTable->GetArray(\"Acc_X\")->GetTuple1(row) + imuTable->GetArray(\"Acc_X\")->GetTuple1(row - 1)) / 2;\n        Acc(1) = (imuTable->GetArray(\"Acc_Y\")->GetTuple1(row) + imuTable->GetArray(\"Acc_Y\")->GetTuple1(row - 1)) / 2;\n        Acc(2) = (imuTable->GetArray(\"Acc_Z\")->GetTuple1(row) + imuTable->GetArray(\"Acc_Z\")->GetTuple1(row - 1)) / 2;\n        Gyro(0) = Deg2Rad(imuTable->GetArray(\"Gyro_X\")->GetTuple1(row));// + imuTable->GetArray(\"Gyro_X\")->GetTuple1(row - 1) / 2);\n        Gyro(1) = Deg2Rad(imuTable->GetArray(\"Gyro_Y\")->GetTuple1(row));// + imuTable->GetArray(\"Gyro_Y\")->GetTuple1(row - 1) / 2);\n        Gyro(2) = Deg2Rad(imuTable->GetArray(\"Gyro_Z\")->GetTuple1(row));// + imuTable->GetArray(\"Gyro_Z\")->GetTuple1(row - 1) / 2);\n\n        Eigen::Vector3d AccC;// = calibR * avgAcc;\n        //AccC << Acc(0), -Acc(1), -Acc(2);\n        //AccC << Acc;\n\n        Eigen::Vector3d GyroC;// = calibR * avgGyro;\n        //GyroC << Gyro(0), -Gyro(1), -Gyro(2);\n        GyroC << Gyro;\n\n        //anglular change\n        Eigen::Vector3d angularChangeC = GyroC*timeDiff;\n\n        //angular change matrix\n        Eigen::Matrix<double,6,1> angularCM;\n        angularCM << angularChangeC,0,0,0;\n\n        //Angle change rotation matrix\n        Eigen::Matrix3d angularRotationCM = GetRotationMatrix(angularCM);\n\n        Eigen::Matrix3d ImuTrRotationM = GetRotationMatrix(this->ImuTrelative);\n\n        Eigen::Matrix3d newImuTrRotation = ImuTrRotationM * angularRotationCM;\n\n        double rx = std::atan2(newImuTrRotation(2, 1), newImuTrRotation(2, 2));\n        double ry = -std::asin(newImuTrRotation(2, 0));\n        double rz = std::atan2(newImuTrRotation(1, 0), newImuTrRotation(0, 0));\n\n\n\n\n        AccC << ((Acc(0) * sin(angularChangeC(2))) + (Acc(1) * (cos(angularChangeC(2)) - 1 )))/GyroC(2),//((Acc(0) * sin(angularChangeC(2))) + (Acc(1) * (1 - cos(angularChangeC(2)))))/GyroC(2),\n                0,//((Acc(0) * (1-cos(angularChangeC(2)))) + (Acc(1) * sin(angularChangeC(2))))/GyroC(2),\n                0;//Acc(2) * timeDiff;\n\n        Eigen::Vector3d velocityChange =  AccC;// * timeDiff;\n\n        //linear velocity\n        Eigen::Vector3d linearChange = (this->Velocity + (velocityChange * 0.5)) * timeDiff;\n        this->Velocity += velocityChange;\n\n        Eigen::Vector3d transform;\n        transform = angularRotationCM * linearChange;\n\n        Eigen::Vector3d ImuTrTransform;\n        ImuTrTransform << this->ImuTrelative(3), this->ImuTrelative(4), this->ImuTrelative(5);\n\n        Eigen::Vector3d newImuTrTransform = (ImuTrRotationM * transform) + ImuTrTransform;\n\n        this->ImuTrelative << rx, ry, rz, newImuTrTransform;\n\n        /*std::cout << \"//////////////////////////////////////////////\" << std::endl;\n        std::cout << \"Time: \" << timeDiff << std::endl;\n        std::cout << \"row: \" << row << std::endl;\n        std::cout << \"count: \" << count << std::endl;\n        std::cout << \"Gyro: \" << Gyro.transpose() << std::endl;\n        std::cout << \"GyroC: \" << GyroC.transpose() << std::endl;\n        std::cout << \"angularChangeC: \" << angularChangeC.transpose() << std::endl;\n        std::cout << \"Acc: \" << Acc.transpose() << std::endl;\n        std::cout << \"AccC: \" << AccC.transpose() << std::endl;\n        std::cout << \"linearChangeC: \" << linearChange.transpose() << std::endl;*/\n\n        //count++;\n        row++;\n\n      }\n\n      this->Trelative << ImuTrelative;\n\n      this->ImuVariation << abs(this->ImuTrelative(0) * (1 - this->ImuConfidence(0))),\n        abs(this->ImuTrelative(1) * (1 - this->ImuConfidence(1))),\n        abs(this->ImuTrelative(2) * (1 - this->ImuConfidence(2))),\n        abs(this->ImuTrelative(3) * (1 - this->ImuConfidence(3))),\n        abs(this->ImuTrelative(4) * (1 - this->ImuConfidence(4))),\n        abs(this->ImuTrelative(5) * (1 - this->ImuConfidence(5)));\n      std::cout << \"ImuVariation: \" << this->ImuVariation.transpose() << std::endl;\n\n\n      std::cout << \"========== IMU-Motion ==========\" << std::endl;\n      std::cout << \"Time: \" << timeDiff << std::endl;\n      std::cout << \"row: \" << row << std::endl;\n      std::cout << \"count: \" << count << std::endl;\n      //std::cout << \"Gyro: \" << avgGyro.transpose() << std::endl;\n      //std::cout << \"GyroC: \" << avgGyroC.transpose() << std::endl;\n      //std::cout << \"angularChangeC: \" << angularChangeC.transpose() << std::endl;\n      //std::cout << \"Acc: \" << avgAcc.transpose() << std::endl;\n      //std::cout << \"AccC: \" << avgAccC.transpose() << std::endl;\n      std::cout << \"Velocity: \" << this->Velocity.transpose() << std::endl;\n\n      if (this->OnlyImu) //for testing only\n      {\n        UpdateTworldUsingTrelative();\n      }\n  }\n\n}\n\n//-----------------------------------------------------------------------------\nvoid vtkSlam::ComputeEgoMotion()\n{\n  // Check that there is enought points to compute the EgoMotion\n  if ((this->CurrentEdgesPoints->size() == 0 || this->PreviousEdgesPoints->size() == 0) &&\n      (this->CurrentPlanarsPoints->size() == 0 || this->PreviousPlanarsPoints->size() == 0))\n  {\n    this->FillEgoMotionInfoArrayWithDefaultValues();\n    vtkGenericWarningMacro(\"Not enought keypoints, EgoMotion skipped for this frame\");\n    return;\n  }\n\n  // reset the relative transform\n  if (this->UsingImu && this->CurrentFrameTime != this->PreviousFrameTime)\n  {\n    this->Trelative = this->ImuTrelative;\n  }\n  else\n  {\n    this->Trelative = Eigen::Matrix<double, 6, 1>::Zero();\n  }\n\n  // kd-tree to process fast nearest neighbor\n  // among the keypoints of the previous pointcloud\n  pcl::KdTreeFLANN<Point>::Ptr kdtreePreviousEdges(new pcl::KdTreeFLANN<Point>());\n  pcl::KdTreeFLANN<Point>::Ptr kdtreePreviousPlanes(new pcl::KdTreeFLANN<Point>());\n  pcl::KdTreeFLANN<Point>::Ptr kdtreePreviousBlobs(new pcl::KdTreeFLANN<Point>());\n  kdtreePreviousEdges->setInputCloud(this->PreviousEdgesPoints);\n  kdtreePreviousPlanes->setInputCloud(this->PreviousPlanarsPoints);\n  kdtreePreviousBlobs->setInputCloud(this->PreviousBlobsPoints);\n\n  std::cout << \"========== Ego-Motion ==========\" << std::endl;\n  std::cout << \"previous <-> current edges : \" << this->PreviousEdgesPoints->size() << \" <-> \" << this->CurrentEdgesPoints->size()\n            << \"previous <-> current planes : \" << this->PreviousPlanarsPoints->size() << \" <-> \" << this->CurrentPlanarsPoints->size() << std::endl;\n\n  unsigned int usedEdges = 0;\n  unsigned int usedPlanes = 0;\n  Point currentPoint, transformedPoint;\n\n\n  std::cout << \"Trelative: \" << this->Trelative.transpose() << std::endl;\n  // ICP - Levenberg-Marquardt loop:\n  // At each step of this loop an ICP matching is performed\n  // Once the keypoints matched, we estimate the the 6-DOF\n  // parameters by minimizing a non-linear least square cost\n  // function using a Levenberg-Marquardt algorithm\n  for (unsigned int icpCount = 0; icpCount < this->EgoMotionICPMaxIter; ++icpCount)\n  {\n    // Rotation and translation at this step\n    Eigen::Matrix3d R = GetRotationMatrix(this->Trelative);\n    Eigen::Vector3d T;\n    T << this->Trelative(3), this->Trelative(4), this->Trelative(5);\n\n    // clear all keypoints matching data\n    this->ResetDistanceParameters();\n\n    // Init the undistortion interpolator\n    if (this->Undistortion)\n    {\n      this->EgoMotionInterpolator = this->InitUndistortionInterpolatorEgoMotion();\n    }\n\n    // loop over edges\n    for (unsigned int edgeIndex = 0; edgeIndex < this->CurrentEdgesPoints->size(); ++edgeIndex)\n    {\n      currentPoint = this->CurrentEdgesPoints->points[edgeIndex];\n\n      // Find the closest correspondence edge line of the current edge point\n      if ((this->PreviousEdgesPoints->size() > 7) && (this->CurrentEdgesPoints->size() > 0))\n      {\n        // Compute the parameters of the point - line distance\n        // i.e A = (I - n*n.t)^2 with n being the director vector\n        // and P a point of the line\n        int rejectionIndex = this->ComputeLineDistanceParameters(kdtreePreviousEdges, R, T, currentPoint, \"egoMotion\");\n        this->EdgePointRejectionEgoMotion[edgeIndex] = rejectionIndex;\n        this->MatchRejectionHistogramLine[rejectionIndex] += 1;\n      }\n    }\n\n    // loop over surfaces\n    for (unsigned int planarIndex = 0; planarIndex < this->CurrentPlanarsPoints->size(); ++planarIndex)\n    {\n      currentPoint = this->CurrentPlanarsPoints->points[planarIndex];\n\n      // Find the closest correspondence plane of the current planar point\n      if ((this->PreviousPlanarsPoints->size() > 7) && (this->CurrentPlanarsPoints->size() > 0))\n      {\n        // Compute the parameters of the point - plane distance\n        // i.e A = n * n.t with n being a normal of the plane\n        // and is a point of the plane\n        int rejectionIndex = this->ComputePlaneDistanceParameters(kdtreePreviousPlanes, R, T, currentPoint, \"egoMotion\");\n        this->PlanarPointRejectionEgoMotion[planarIndex] = rejectionIndex;\n        this->MatchRejectionHistogramPlane[rejectionIndex] += 1;\n      }\n    }\n\n    usedEdges = this->MatchRejectionHistogramLine[6];\n    usedPlanes = this->MatchRejectionHistogramPlane[6];\n    // Skip this frame if there is too few geometric\n    // keypoints matched\n    if ((usedPlanes + usedEdges) < 20)\n    {\n      vtkGenericWarningMacro(\"Too few geometric features, frame skipped\");\n      break;\n    }\n\n    // We want to estimate our 6-DOF parameters using a non\n    // linear least square minimization. The non linear part\n    // comes from the Euler Angle parametrization of the rotation\n    // endomorphism SO(3). To minimize it we use CERES to perform\n    // the Levenberg-Marquardt algorithm.\n    ceres::Problem problem;\n    for (unsigned int k = 0; k < Xvalues.size(); ++k)\n    {\n      if (this->Undistortion)\n      {\n        ceres::CostFunction* cost_function = new ceres::AutoDiffCostFunction<CostFunctions::MahalanobisDistanceLinearDistortionResidual, 1, 6>(\n                                              new CostFunctions::MahalanobisDistanceLinearDistortionResidual(\n                                                this->Avalues[k], this->Pvalues[k], this->Xvalues[k],\n                                                Eigen::Matrix<double, 3, 1>::Zero(),\n                                                Eigen::Matrix<double, 3, 3>::Identity(),\n                                                this->TimeValues[k], this->residualCoefficient[k]));\n        problem.AddResidualBlock(cost_function, new ceres::ArctanLoss(2.0), this->Trelative.data());\n      }\n      else\n      {\n        ceres::CostFunction* cost_function = new ceres::AutoDiffCostFunction<CostFunctions::MahalanobisDistanceAffineIsometryResidual, 1, 6>(\n                                             new CostFunctions::MahalanobisDistanceAffineIsometryResidual(this->Avalues[k], this->Pvalues[k],\n                                                                                                          this->Xvalues[k], this->residualCoefficient[k]));\n        problem.AddResidualBlock(cost_function, new ceres::ArctanLoss(2.0), this->Trelative.data());\n      }\n    }\n\n    ceres::Solver::Options options;\n    options.max_num_iterations = this->EgoMotionLMMaxIter;\n    options.linear_solver_type = ceres::DENSE_QR;\n    options.minimizer_progress_to_stdout = false;\n\n    ceres::Solver::Summary summary;\n    ceres::Solve(options, &problem, &summary);\n    std::cout << summary.BriefReport() << std::endl;\n\n    // If no L-M iteration has been made since the\n    // last ICP matching it means we reached a local\n    // minimum for the ICP-LM algorithm\n    if (summary.num_successful_steps == 1)\n    {\n      break;\n    }\n  }\n\n  // Provide information about keypoints-neighborhood matching rejections\n  this->RejectionInformationDisplay();\n\n  static_cast<vtkIntArray*>(this->Trajectory->GetPointData()->GetArray(\"EgoMotion: edges used\"))->InsertNextValue(usedEdges);\n  static_cast<vtkIntArray*>(this->Trajectory->GetPointData()->GetArray(\"EgoMotion: planes used\"))->InsertNextValue(usedPlanes);\n  static_cast<vtkIntArray*>(this->Trajectory->GetPointData()->GetArray(\"EgoMotion: total keypoints used\"))->InsertNextValue(this->Xvalues.size());\n  std::cout << \"used keypoints : \" << this->Xvalues.size() << std::endl;\n  std::cout << \"edges : \" << usedEdges << \" planes : \" << usedPlanes << std::endl;\n  // Integrate the relative motion\n  // to the world transformation\n\n  if (this->UsingImu && this->CurrentFrameTime != this->PreviousFrameTime)\n  {\n\n    // ensures change made by SLAM is within its limits set by the IMU confidence levels\n    for (int i = 0; i < this->Trelative.rows(); i++)\n    {\n      if (this->Trelative(i) < this->ImuTrelative(i) - this->ImuVariation(i))\n      {\n        this->Trelative(i) = this->ImuTrelative(i) - this->ImuVariation(i);\n        std::cout << \"Correction limit hit on: \" << i << std::endl;\n      }\n      else if (this->Trelative(i) > this->ImuTrelative(i) + this->ImuVariation(i))\n      {\n        this->Trelative(i) = this->ImuTrelative(i) + this->ImuVariation(i);\n        std::cout << \"Correction limit hit on: \" << i << std::endl;\n      }\n    }\n\n    //Velocity error correction\n    Eigen::Matrix3d Trr = GetRotationMatrix(this->Trelative);\n    Eigen::Vector3d Trt;\n    Trt <<  this->Trelative(3), this->Trelative(4), this->Trelative(5);\n\n    Eigen::Vector3d TrLinearDist = Trr.transpose() * Trt;\n\n    Eigen::Matrix3d Imur = GetRotationMatrix(this->ImuTrelative);\n    Eigen::Vector3d Imut;\n    Imut <<  this->ImuTrelative(3), this->ImuTrelative(4), this->ImuTrelative(5);\n\n    Eigen::Vector3d ImuLinearDist = Imur.transpose() * Imut;\n\n    Eigen::Vector3d ErrorDist = TrLinearDist - ImuLinearDist;\n\n    double timeDiff = this->CurrentFrameTime - this->PreviousFrameTime;\n\n    Eigen::Vector3d ErrorVelocity = ErrorDist/timeDiff;\n\n    this->Velocity -= 0.5 * ErrorVelocity;\n\n  }\n\n  this->UpdateTworldUsingTrelative();\n}\n\n//-----------------------------------------------------------------------------\nvoid vtkSlam::Mapping()\n{\n  // Check that there is enought points to compute the EgoMotion\n  if (this->CurrentEdgesPoints->size() == 0 && this->CurrentPlanarsPoints->size() == 0 || true)\n  {\n    this->FillMappingInfoArrayWithDefaultValues();\n    // update maps\n    this->UpdateMapsUsingTworld();\n    vtkGenericWarningMacro(\"Not enought keypoints, Mapping skipped for this frame\");\n    return;\n  }\n\n  // contruct kd-tree for fast search\n  pcl::KdTreeFLANN<Point>::Ptr kdtreeEdges(new pcl::KdTreeFLANN<Point>());\n  pcl::KdTreeFLANN<Point>::Ptr kdtreePlanes(new pcl::KdTreeFLANN<Point>());\n  pcl::KdTreeFLANN<Point>::Ptr kdtreeBlobs(new pcl::KdTreeFLANN<Point>());\n\n  // Set the FarestPoint to reduce the map to the minimun since\n  this->SetLidarMaximunRange(this->FarestKeypointDist);\n\n  pcl::PointCloud<Point>::Ptr subEdgesPointsLocalMap = this->EdgesPointsLocalMap->Get(this->Tworld);\n  pcl::PointCloud<Point>::Ptr subPlanarPointsLocalMap = this->PlanarPointsLocalMap->Get(this->Tworld);\n\n  std::cout << \"========== Mapping ==========\" << std::endl;\n  std::cout << \"Edges extracted from map: \" << subEdgesPointsLocalMap->points.size()\n            << \"Planes extracted from map: \" << subPlanarPointsLocalMap->points.size() << std::endl;\n\n  kdtreeEdges->setInputCloud(subEdgesPointsLocalMap);\n  kdtreePlanes->setInputCloud(subPlanarPointsLocalMap);\n\n  if (!this->FastSlam)\n  {\n    pcl::PointCloud<Point>::Ptr subBlobPointsLocalMap = this->BlobsPointsLocalMap->Get(this->Tworld);\n    kdtreeBlobs->setInputCloud(subBlobPointsLocalMap);\n    std::cout << \"blobs map : \" << subBlobPointsLocalMap->points.size() << std::endl;\n  }\n\n  unsigned int usedEdges = 0;\n  unsigned int usedPlanes = 0;\n  unsigned int usedBlobs = 0;\n  Point currentPoint;\n  Eigen::MatrixXd estimatorCovariance(6, 6);\n\n  Eigen::Matrix<double, 6, 1> MappingTworld;\n  MappingTworld << this->Tworld;\n\n  std::cout << \"Mapping start Tworld: \" << this->Tworld.transpose() << std::endl;\n\n  // ICP - Levenberg-Marquardt loop:\n  // At each step of this loop an ICP matching is performed\n  // Once the keypoints matched, we estimate the the 6-DOF\n  // parameters by minimizing a non-linear least square cost\n  // function using a Levenberg-Marquardt algorithm\n  for (unsigned int icpCount = 0; icpCount < this->MappingICPMaxIter; ++icpCount)\n  {\n    // clear all keypoints matching data\n    this->ResetDistanceParameters();\n\n    // Init the undistortion interpolator\n    if (this->Undistortion)\n    {\n      this->MappingInterpolator = this->InitUndistortionInterpolatorMapping();\n    }\n\n    // Rotation and position at this step\n    Eigen::Matrix3d R = GetRotationMatrix(MappingTworld);\n    Eigen::Vector3d T;\n    T << MappingTworld(3), MappingTworld(4), MappingTworld(5);\n\n    // loop over edges\n    for (unsigned int edgeIndex = 0; edgeIndex < this->CurrentEdgesPoints->size(); ++edgeIndex)\n    {\n      currentPoint = this->CurrentEdgesPoints->points[edgeIndex];\n\n      if (this->CurrentEdgesPoints->size() > 0 && subEdgesPointsLocalMap->points.size() > 10)\n      {\n        // Find the closest correspondence edge line of the current edge point\n        int rejectionIndex = this->ComputeLineDistanceParameters(kdtreeEdges, R, T, currentPoint, \"mapping\");\n        this->EdgePointRejectionMapping[edgeIndex] = rejectionIndex;\n        this->MatchRejectionHistogramLine[rejectionIndex] += 1;\n        usedEdges = this->Xvalues.size();\n      }\n    }\n\n    // loop over surfaces\n    for (unsigned int planarIndex = 0; planarIndex < this->CurrentPlanarsPoints->size(); ++planarIndex)\n    {\n      currentPoint = this->CurrentPlanarsPoints->points[planarIndex];\n\n      if (this->CurrentPlanarsPoints->size() > 0 && subPlanarPointsLocalMap->size() > 10)\n      {\n        // Find the closest correspondence plane of the current planar point\n        int rejectionIndex = this->ComputePlaneDistanceParameters(kdtreePlanes, R, T, currentPoint, \"mapping\");\n        this->PlanarPointRejectionMapping[planarIndex] = rejectionIndex;\n        this->MatchRejectionHistogramPlane[rejectionIndex] += 1;\n        usedPlanes = this->Xvalues.size() - usedEdges;\n      }\n    }\n\n    if (!this->FastSlam && this->NbrFrameProcessed > 10)\n    {\n      // loop over blobs\n      for (unsigned int blobIndex = 0; blobIndex < this->CurrentBlobsPoints->size(); ++blobIndex)\n      {\n        currentPoint = this->CurrentBlobsPoints->points[blobIndex];\n\n        // Find the closest correspondence plane of the current planar point\n        this->ComputeBlobsDistanceParameters(kdtreeBlobs, R, T, currentPoint, \"mapping\");\n        usedBlobs = this->Xvalues.size() - usedPlanes - usedEdges;\n      }\n    }\n\n    // Skip this frame if there is too few geometric keypoints matched\n    if ((usedPlanes + usedEdges + usedBlobs) < 20)\n    {\n      vtkGenericWarningMacro(\"Too few geometric features, loop breaked\");\n      std::cout << \"planes: \" << usedPlanes << \" edges: \" << usedEdges << \" Blobs: \" << usedBlobs << std::endl;\n      break;\n    }\n\n    // Get the previous sensor pose\n    Eigen::Matrix3d R0 = GetRotationMatrix(this->PreviousTworld);\n    Eigen::Vector3d T0; T0 << this->PreviousTworld[3], this->PreviousTworld[4], this->PreviousTworld[5];\n\n    // We want to estimate our 6-DOF parameters using a non\n    // linear least square minimization. The non linear part\n    // comes from the Euler Angle parametrization of the rotation\n    // endomorphism SO(3). To minimize it we use CERES to perform\n    // the Levenberg-Marquardt algorithm.\n    ceres::Problem problem;\n    for (unsigned int k = 0; k < Xvalues.size(); ++k)\n    {\n      if (this->Undistortion)\n      {\n        ceres::CostFunction* cost_function = new ceres::AutoDiffCostFunction<CostFunctions::MahalanobisDistanceLinearDistortionResidual, 1, 6>(\n                                              new CostFunctions::MahalanobisDistanceLinearDistortionResidual(\n                                                this->Avalues[k], this->Pvalues[k], this->Xvalues[k], T0, R0,\n                                                this->TimeValues[k], this->residualCoefficient[k]));\n        problem.AddResidualBlock(cost_function, new ceres::ArctanLoss(2.0), MappingTworld.data());\n      }\n      else\n      {\n        ceres::CostFunction* cost_function = new ceres::AutoDiffCostFunction<CostFunctions::MahalanobisDistanceAffineIsometryResidual, 1, 6>(\n                                             new CostFunctions::MahalanobisDistanceAffineIsometryResidual(this->Avalues[k], this->Pvalues[k],\n                                                                                                          this->Xvalues[k], this->residualCoefficient[k]));\n        problem.AddResidualBlock(cost_function, new ceres::ArctanLoss(2.0), MappingTworld.data());\n      }\n    }\n\n    ceres::Solver::Options options;\n    options.max_num_iterations = this->MappingLMMaxIter;\n    options.linear_solver_type = ceres::DENSE_QR;\n    options.minimizer_progress_to_stdout = false;\n\n    ceres::Solver::Summary summary;\n    ceres::Solve(options, &problem, &summary);\n    std::cout << summary.BriefReport() << std::endl;\n\n    // If no L-M iteration has been made since the\n    // last ICP matching it means we reached a local\n    // minimum for the ICP-LM algorithm\n    if (summary.num_successful_steps == 1)\n    {\n      // Now evaluate the quality of the parameters\n      // estimated using an approximate computation\n      // of the variance covariance matrix\n      // Covariance computation options\n      ceres::Covariance::Options covOptions;\n      covOptions.apply_loss_function = true;\n      covOptions.algorithm_type = ceres::CovarianceAlgorithmType::DENSE_SVD;\n\n      // Computation of the variance-covariance matrix\n      ceres::Covariance covariance(covOptions);\n      std::vector<std::pair<const double*, const double* > > covariance_blocks;\n      covariance_blocks.push_back(std::make_pair(MappingTworld.data(), MappingTworld.data()));\n      covariance.Compute(covariance_blocks, &problem);\n      double covarianceMat[6 * 6];\n      covariance.GetCovarianceBlock(MappingTworld.data(), MappingTworld.data(), covarianceMat);\n      for (int i = 0; i < 6; ++i)\n        for (int j = 0; j < 6; ++j)\n          estimatorCovariance(i, j) = covarianceMat[i + 6 * j];\n      break;\n      }\n  }\n\n  Eigen::Vector3d imuTr;\n  imuTr << this->ImuTrelative(3), this->ImuTrelative(4), this->ImuTrelative(5);\n\n  Eigen::Vector3d TworldVec;\n  TworldVec << this->Tworld(3), this->Tworld(4), this->Tworld(5);\n\n  Eigen::Vector3d imuTw = GetRotationMatrix(this->PreviousTworld) * imuTr + TworldVec;\n\n  Eigen::Matrix<double, 6, 1> imuRel = this->ImuTrelative;\n  Eigen::Matrix3d imuRelRotationMat = GetRotationMatrix(imuRel);\n\n  Eigen::Matrix3d prevWorldRotationMat = GetRotationMatrix(this->PreviousTworld);\n\n  Eigen::Matrix3d imuWorldRotationMat = prevWorldRotationMat * imuRelRotationMat;\n\n  double rx = std::atan2(imuWorldRotationMat(2, 1), imuWorldRotationMat(2, 2));\n  double ry = -std::asin(imuWorldRotationMat(2, 0));\n  double rz = std::atan2(imuWorldRotationMat(1, 0), imuWorldRotationMat(0, 0));\n\n  Eigen::Matrix<double, 6, 1> imuWorld;\n  imuWorld << rx, ry, rz, imuTw(0), imuTw(1), imuTw(2);\n\n  std::cout << \"IMU rel:         \" <<  this->ImuTrelative.transpose() << std::endl;\n  std::cout << \"IMU Tworld:      \" << imuWorld.transpose() << std::endl;\n  std::cout << \"Mapping changes: \" << (MappingTworld - imuWorld).transpose() << std::endl;\n  std::cout << \"Tworld:          \" << this->Tworld.transpose() << std::endl;\n  std::cout << \"Mapping Tworld:  \" << MappingTworld.transpose() << std::endl;\n\n  if (this->UsingImu && this->CurrentFrameTime != this->PreviousFrameTime)\n  {\n    Eigen::Vector3d ImuVariationT;\n    ImuVariationT << this->ImuVariation(3), this->ImuVariation(4), this->ImuVariation(5);\n\n    Eigen::Vector3d ImuVariationTw = prevWorldRotationMat * ImuVariationT;\n\n    Eigen::Matrix<double, 6, 1> mappingImuVariance;\n    mappingImuVariance << this->ImuVariation(0), this->ImuVariation(1), this->ImuVariation(2), ImuVariationTw;\n\n    // ensures change made by SLAM is within its limits set by the IMU confidence levels\n    for (int i = 0; i < MappingTworld.rows(); i++)\n    {\n      if (MappingTworld(i) < imuWorld(i) - this->ImuVariation(i))\n      {\n        MappingTworld(i) = imuWorld(i) - this->ImuVariation(i);\n        std::cout << \"Mapping Correction limit hit on: \" << i << std::endl;\n      }\n      else if (MappingTworld(i) > imuWorld(i) + this->ImuVariation(i))\n      {\n        MappingTworld(i) = imuWorld(i) + this->ImuVariation(i);\n        std::cout << \"Mapping Correction limit hit on: \" << i << std::endl;\n      }\n    }\n\n    //Velocity error correction\n    /*Eigen::Matrix3d Trr = GetRotationMatrix(this->Trelative);\n    Eigen::Vector3d Trt;\n    Trt <<  this->Trelative(3), this->Trelative(4), this->Trelative(5);\n\n    Eigen::Vector3d TrLinearDist = Trr.transpose() * Trt;\n\n    Eigen::Matrix3d Imur = GetRotationMatrix(this->ImuTrelative);\n    Eigen::Vector3d Imut;\n    Imut <<  this->ImuTrelative(3), this->ImuTrelative(4), this->ImuTrelative(5);\n\n    Eigen::Vector3d ImuLinearDist = Imur.transpose() * Imut;\n\n    Eigen::Vector3d ErrorDist = TrLinearDist - ImuLinearDist;\n\n    double timeDiff = this->CurrentFrameTime - this->PreviousFrameTime;\n\n    Eigen::Vector3d ErrorVelocity = ErrorDist/timeDiff;\n\n    this->Velocity -= 0.5 * ErrorVelocity;*/\n\n  }\n\n  this->Tworld << MappingTworld;\n  // Provide information about keypoints-neighborhood matching rejections\n  this->RejectionInformationDisplay();\n\n  Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> eig(estimatorCovariance);\n  Eigen::MatrixXd D = eig.eigenvalues();\n\n  static_cast<vtkDoubleArray*>(this->Trajectory->GetPointData()->GetArray(\"Variance Error\"))->InsertNextValue(D(5));\n  static_cast<vtkIntArray*>(this->Trajectory->GetPointData()->GetArray(\"Mapping: edges used\"))->InsertNextValue(usedEdges);\n  static_cast<vtkIntArray*>(this->Trajectory->GetPointData()->GetArray(\"Mapping: planes used\"))->InsertNextValue(usedPlanes);\n  static_cast<vtkIntArray*>(this->Trajectory->GetPointData()->GetArray(\"Mapping: blobs used\"))->InsertNextValue(usedBlobs);\n  static_cast<vtkIntArray*>(this->Trajectory->GetPointData()->GetArray(\"Mapping: total keypoints used\"))->InsertNextValue(this->Xvalues.size());\n\n  std::cout << \"Matches used: Total: \" << this->Xvalues.size()\n            << \" edges: \" << usedEdges << \" planes: \" << usedPlanes << \" blobs: \" << usedBlobs << std::endl;\n  std::cout << \"Covariance Eigen values: \" << D.transpose() << std::endl;\n  std::cout << \"Maximum variance: \" << D(5) << std::endl;\n\n\n  // Add the current computed transform to the list\n  this->TworldList.push_back(this->Tworld);\n\n  // Update the PreviousTworld data\n  this->PreviousTworld = this->Tworld;\n\n  // update maps\n  this->UpdateMapsUsingTworld();\n}\n\n//-----------------------------------------------------------------------------\nvoid vtkSlam::UpdateMapsUsingTworld()\n{\n  // Init the mapping interpolator\n  if (this->Undistortion)\n  {\n    this->MappingInterpolator = this->InitUndistortionInterpolatorMapping();\n  }\n\n  // Update EdgeMap\n  pcl::PointCloud<Point>::Ptr MapEdgesPoints(new pcl::PointCloud<Point>());\n  for (unsigned int i = 0; i < this->CurrentEdgesPoints->size(); ++i)\n  {\n    MapEdgesPoints->push_back(this->CurrentEdgesPoints->at(i));\n    this->TransformToWorld(MapEdgesPoints->at(i));\n  }\n  EdgesPointsLocalMap->Roll(this->Tworld);\n  EdgesPointsLocalMap->Add(MapEdgesPoints);\n\n  // Update PlanarMap\n  pcl::PointCloud<Point>::Ptr MapPlanarsPoints(new pcl::PointCloud<Point>());\n  for (unsigned int i = 0; i < this->CurrentPlanarsPoints->size(); ++i)\n  {\n    MapPlanarsPoints->push_back(this->CurrentPlanarsPoints->at(i));\n    this->TransformToWorld(MapPlanarsPoints->at(i));\n  }\n  PlanarPointsLocalMap->Roll(this->Tworld);\n  PlanarPointsLocalMap->Add(MapPlanarsPoints);\n\n  // Update BlobsMap. The all current frame is added\n  if (!this->FastSlam)\n  {\n    pcl::PointCloud<Point>::Ptr MapBlobsPoints(new pcl::PointCloud<Point>());\n    for (unsigned int i = 0; i < this->pclCurrentFrame->size(); ++i)\n    {\n      MapBlobsPoints->push_back(this->pclCurrentFrame->at(i));\n      this->TransformToWorld(MapBlobsPoints->at(i));\n    }\n    BlobsPointsLocalMap->Roll(this->Tworld);\n    BlobsPointsLocalMap->Add(MapBlobsPoints);\n  }\n}\n\n//-----------------------------------------------------------------------------\nvoid vtkSlam::FillMappingInfoArrayWithDefaultValues()\n{\n  static_cast<vtkDoubleArray*>(this->Trajectory->GetPointData()->GetArray(\"Variance Error\"))->InsertNextValue(10.0);\n  static_cast<vtkIntArray*>(this->Trajectory->GetPointData()->GetArray(\"Mapping: edges used\"))->InsertNextValue(0);\n  static_cast<vtkIntArray*>(this->Trajectory->GetPointData()->GetArray(\"Mapping: planes used\"))->InsertNextValue(0);\n  static_cast<vtkIntArray*>(this->Trajectory->GetPointData()->GetArray(\"Mapping: blobs used\"))->InsertNextValue(0);\n  static_cast<vtkIntArray*>(this->Trajectory->GetPointData()->GetArray(\"Mapping: total keypoints used\"))->InsertNextValue(0);\n}\n\n//-----------------------------------------------------------------------------\nvoid vtkSlam::FillEgoMotionInfoArrayWithDefaultValues()\n{\n  static_cast<vtkIntArray*>(this->Trajectory->GetPointData()->GetArray(\"EgoMotion: edges used\"))->InsertNextValue(0);\n  static_cast<vtkIntArray*>(this->Trajectory->GetPointData()->GetArray(\"EgoMotion: planes used\"))->InsertNextValue(0);\n  static_cast<vtkIntArray*>(this->Trajectory->GetPointData()->GetArray(\"EgoMotion: total keypoints used\"))->InsertNextValue(0);\n}\n\n//-----------------------------------------------------------------------------\nvtkSmartPointer<vtkVelodyneTransformInterpolator> vtkSlam::InitUndistortionInterpolatorEgoMotion()\n{\n  vtkSmartPointer<vtkVelodyneTransformInterpolator> resultInterp = vtkSmartPointer<vtkVelodyneTransformInterpolator>::New();\n  resultInterp->SetInterpolationTypeToLinear();\n\n  // Transforms representing the passage from the\n  // referential of the sensor at time t0 resp t1\n  // to the referential of the sensor at the time 0\n  vtkNew<vtkTransform> transform0, transform1;\n\n  // transform 0 is identity\n  transform0->Identity();\n  transform0->Modified();\n  transform0->Update();\n\n  // transform 1 is the delta transform\n  // between T0 and T1 computed in the EgoMotion\n  // i.e Trelative\n  Eigen::Matrix3d R = GetRotationMatrix(this->Trelative);\n  Eigen::Vector3d T;\n  T << this->Trelative(3), this->Trelative(4), this->Trelative(5);\n\n  vtkNew<vtkMatrix4x4> M;\n  for (unsigned int i = 0; i < 3; ++i)\n  {\n    for (unsigned int j = 0; j < 3; ++j)\n    {\n      M->Element[i][j] = R(i, j);\n    }\n    M->Element[i][3] = T(i);\n    M->Element[3][i] = 0;\n  }\n  M->Element[3][3] = 1.0;\n\n  transform1->SetMatrix(M.Get());\n  transform1->Modified();\n  transform1->Update();\n\n  // Add the transforms and update\n  resultInterp->AddTransform(0.0, transform0.GetPointer());\n  resultInterp->AddTransform(1.0, transform1.GetPointer());\n  resultInterp->Modified();\n\n  return resultInterp;\n}\n\n//-----------------------------------------------------------------------------\nvtkSmartPointer<vtkVelodyneTransformInterpolator> vtkSlam::InitUndistortionInterpolatorMapping()\n{\n  vtkSmartPointer<vtkVelodyneTransformInterpolator> resultInterp = vtkSmartPointer<vtkVelodyneTransformInterpolator>::New();\n  resultInterp->SetInterpolationTypeToLinear();\n\n  // Transforms representing the passage from the\n  // referential of the sensor at time t0 resp t1\n  // to the referential of the sensor at the time 0\n  vtkNew<vtkTransform> transform0, transform1;\n\n  // transform 1 is the delta transform\n  // between T0 and T1\n  Eigen::Matrix3d R0, R1;\n  R0 = GetRotationMatrix(this->PreviousTworld);\n  R1 = GetRotationMatrix(this->Tworld);\n\n  Eigen::Vector3d T0, T1;\n  T0 << this->PreviousTworld(3), this->PreviousTworld(4), this->PreviousTworld(5);\n  T1 << this->Tworld(3), this->Tworld(4), this->Tworld(5);\n\n  vtkNew<vtkMatrix4x4> M0, M1;\n  for (unsigned int i = 0; i < 3; ++i)\n  {\n    for (unsigned int j = 0; j < 3; ++j)\n    {\n      M0->Element[i][j] = R0(i, j);\n      M1->Element[i][j] = R1(i, j);\n    }\n    M0->Element[i][3] = T0(i);\n    M0->Element[3][i] = 0;\n    M1->Element[i][3] = T1(i);\n    M1->Element[3][i] = 0;\n  }\n  M0->Element[3][3] = 1.0;\n  M1->Element[3][3] = 1.0;\n\n  transform0->SetMatrix(M0.Get());\n  transform0->Modified();\n  transform0->Update();\n\n  transform1->SetMatrix(M1.Get());\n  transform1->Modified();\n  transform1->Update();\n\n  // Add the transforms and update\n  resultInterp->AddTransform(0.0, transform0.GetPointer());\n  resultInterp->AddTransform(1.0, transform1.GetPointer());\n  resultInterp->Modified();\n\n  return resultInterp;\n}\n\n//-----------------------------------------------------------------------------\nvoid vtkSlam::ExpressPointInOtherReferencial(Point& p, vtkSmartPointer<vtkVelodyneTransformInterpolator> transform)\n{\n  // interpolate the transform\n  vtkNew<vtkTransform> currTransform;\n  transform->InterpolateTransform(p.intensity, currTransform.GetPointer());\n  currTransform->Modified();\n  currTransform->Update();\n\n  double pos[3] = {p.x, p.y, p.z};\n  currTransform->InternalTransformPoint(pos, pos);\n  p.x = pos[0];\n  p.y = pos[1];\n  p.z = pos[2];\n}\n\n//-----------------------------------------------------------------------------\nvoid vtkSlam::ResetDistanceParameters()\n{\n  this->Xvalues.clear();\n  this->Xvalues.resize(0);\n  this->Avalues.clear();\n  this->Avalues.resize(0);\n  this->Pvalues.clear();\n  this->Pvalues.resize(0);\n  this->TimeValues.clear();\n  this->TimeValues.resize(0);\n  this->residualCoefficient.clear();\n  this->residualCoefficient.resize(0);\n  this->RadiusIncertitude.clear();\n  this->RadiusIncertitude.resize(0);\n  this->MatchRejectionHistogramLine.clear();\n  this->MatchRejectionHistogramLine.resize(NrejectionCauses);\n  this->MatchRejectionHistogramPlane.clear();\n  this->MatchRejectionHistogramPlane.resize(NrejectionCauses);\n  this->MatchRejectionHistogramBlob.clear();\n  this->MatchRejectionHistogramBlob.resize(NrejectionCauses);\n}\n\n//-----------------------------------------------------------------------------\nvoid vtkSlam::UpdateTworldUsingTrelative()\n{\n  // Rotation and translation relative\n  Eigen::Matrix3d Rr, Rw;\n  Eigen::Vector3d Tr, Tw;\n  Rr = GetRotationMatrix(this->Trelative);\n  Tr << this->Trelative(3), this->Trelative(4), this->Trelative(5);\n\n  // full rotation\n  Rw = GetRotationMatrix(this->Tworld);\n  Tw << this->Tworld(3), this->Tworld(4), this->Tworld(5);\n\n  Eigen::Vector3d newTw;\n  Eigen::Matrix3d newRw;\n\n  // The new pos of the sensor in the world\n  // referential is the previous one composed\n  // with the relative motion estimated at the\n  // odometry step\n  newRw = Rw * Rr;\n  newTw = Rw * Tr + Tw;\n\n  double rx = std::atan2(newRw(2, 1), newRw(2, 2));\n  double ry = -std::asin(newRw(2, 0));\n  double rz = std::atan2(newRw(1, 0), newRw(0, 0));\n\n  // Next estimation of Tworld using\n  // the odometry result. This estimation\n  // will be used to undistorded the frame\n  // if required and to initialize the\n  this->Tworld(0) = rx;\n  this->Tworld(1) = ry;\n  this->Tworld(2) = rz;\n  this->Tworld(3) = newTw(0);\n  this->Tworld(4) = newTw(1);\n  this->Tworld(5) = newTw(2);\n}\n\n//-----------------------------------------------------------------------------\nvoid vtkSlam::SetVoxelGridLeafSize(double size)\n{\n  this->PlanarPointsLocalMap->SetLeafSize(size);\n  this->EdgesPointsLocalMap->SetLeafSize(0.75 * size);\n  this->BlobsPointsLocalMap->SetLeafSize(0.20 * size);\n  this->ParametersModificationTime.Modified();\n}\n\n//-----------------------------------------------------------------------------\nvoid vtkSlam::SetVoxelGridSize(unsigned int size)\n{\n  this->EdgesPointsLocalMap->SetSize(size);\n  this->PlanarPointsLocalMap->SetSize(size);\n  this->BlobsPointsLocalMap->SetSize(size);\n  this->ParametersModificationTime.Modified();\n}\n\n//-----------------------------------------------------------------------------\nvoid vtkSlam::SetVoxelGridResolution(double resolution)\n{\n  this->EdgesPointsLocalMap->SetResolution(resolution);\n  this->PlanarPointsLocalMap->SetResolution(resolution);\n  this->BlobsPointsLocalMap->SetResolution(resolution);\n  this->ParametersModificationTime.Modified();\n}\n\n//-----------------------------------------------------------------------------\nvoid vtkSlam::SetLidarMaximunRange(const double maxRange)\n{\n  this->EdgesPointsLocalMap->SetPointCoudMaxRange(maxRange);\n  this->PlanarPointsLocalMap->SetPointCoudMaxRange(maxRange);\n  this->BlobsPointsLocalMap->SetPointCoudMaxRange(maxRange);\n}\n\n//-----------------------------------------------------------------------------\nvoid vtkSlam::UpdateLaserIdMapping(vtkTable *calib)\n{\n  this->NLasers = calib->GetNumberOfRows();\n  auto array = vtkDataArray::SafeDownCast(calib->GetColumnByName(\"verticalCorrection\"));\n  if (array)\n  {\n    std::vector<double> verticalCorrection;\n    verticalCorrection.resize(array->GetNumberOfTuples());\n    for (int i =0; i < array->GetNumberOfTuples(); ++i)\n    {\n      verticalCorrection[i] = array->GetTuple1(i);\n    }\n    this->LaserIdMapping = sortIdx(verticalCorrection);\n  }\n  else\n  {\n    vtkErrorMacro(\"<< The calibration data has no colomn named 'verticalCorrection'\");\n  }\n}\n\n//-----------------------------------------------------------------------------\nvoid vtkSlam::RejectionInformationDisplay()\n{\n  double totalRejectionsLine = 0;\n  double totalRejectionsPlane = 0;\n  for (int k = 0; k < this->NrejectionCauses; ++k)\n  {\n    totalRejectionsLine += this->MatchRejectionHistogramLine[k];\n    totalRejectionsPlane += this->MatchRejectionHistogramPlane[k];\n  }\n  std::cout << \"Rejection frequencies lines: [\";\n  for (int k = 0; k < this->NrejectionCauses; ++k)\n  {\n    std::cout << this->MatchRejectionHistogramLine[k] / totalRejectionsLine * 100.0 << \", \";\n  }\n  std::cout << std::endl;\n  std::cout << \"Rejection frequencies planes: [\";\n  for (int k = 0; k < this->NrejectionCauses; ++k)\n  {\n    std::cout << this->MatchRejectionHistogramPlane[k] / totalRejectionsPlane * 100.0 << \", \";\n  }\n  std::cout << std::endl;\n}\n", "meta": {"hexsha": "fdebefd582490cf8a9136a3beec85f63cf1218cf", "size": 124953, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "VelodyneHDL/Filter/Slam/vtkSlam.cxx", "max_stars_repo_name": "rdanderson521/VeloView", "max_stars_repo_head_hexsha": "181f6e3f944a996f9c1e64bd24d42d83bc8f1ef3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "VelodyneHDL/Filter/Slam/vtkSlam.cxx", "max_issues_repo_name": "rdanderson521/VeloView", "max_issues_repo_head_hexsha": "181f6e3f944a996f9c1e64bd24d42d83bc8f1ef3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "VelodyneHDL/Filter/Slam/vtkSlam.cxx", "max_forks_repo_name": "rdanderson521/VeloView", "max_forks_repo_head_hexsha": "181f6e3f944a996f9c1e64bd24d42d83bc8f1ef3", "max_forks_repo_licenses": ["Apache-2.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.7616946161, "max_line_length": 193, "alphanum_fraction": 0.6339343593, "num_tokens": 33976, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.4813012978151568}}
{"text": "// Copyright Louis Dionne 2013-2016\r\n// Distributed under the Boost Software License, Version 1.0.\r\n// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\r\n\r\n#include <boost/hana.hpp>\r\n\r\n#include <boost/hana/assert.hpp>\r\n#include <boost/hana/tuple.hpp>\r\n\r\n#include <laws/base.hpp>\r\n#include <laws/comparable.hpp>\r\n#include <laws/euclidean_ring.hpp>\r\n#include <laws/group.hpp>\r\n#include <laws/logical.hpp>\r\n#include <laws/monoid.hpp>\r\n#include <laws/orderable.hpp>\r\n#include <support/cnumeric.hpp>\r\n#include <support/numeric.hpp>\r\n\r\n#include <cstdlib>\r\n#include <vector>\r\nusing namespace boost::hana;\r\n\r\n\r\nstruct invalid {\r\n    template <typename T>\r\n    operator T const() { std::abort(); }\r\n};\r\n\r\nint main() {\r\n    //////////////////////////////////////////////////////////////////////////\r\n    // Comparable\r\n    //////////////////////////////////////////////////////////////////////////\r\n    {\r\n        test::_injection<0> f{};\r\n        auto x = numeric(1);\r\n        auto y = numeric(2);\r\n\r\n        // equal\r\n        {\r\n            BOOST_HANA_CONSTEXPR_CHECK(equal(x, x));\r\n            BOOST_HANA_CONSTEXPR_CHECK(not_(equal(x, y)));\r\n        }\r\n\r\n        // not_equal\r\n        {\r\n            BOOST_HANA_CONSTEXPR_CHECK(not_equal(x, y));\r\n            BOOST_HANA_CONSTEXPR_CHECK(not_(not_equal(x, x)));\r\n        }\r\n\r\n        // comparing\r\n        {\r\n            BOOST_HANA_CONSTEXPR_CHECK(equal(\r\n                comparing(f)(x, x),\r\n                equal(f(x), f(x))\r\n            ));\r\n\r\n            BOOST_HANA_CONSTEXPR_CHECK(equal(\r\n                comparing(f)(x, y),\r\n                equal(f(x), f(y))\r\n            ));\r\n        }\r\n    }\r\n\r\n    //////////////////////////////////////////////////////////////////////////\r\n    // Orderable\r\n    //////////////////////////////////////////////////////////////////////////\r\n    {\r\n        auto ord = numeric;\r\n\r\n        // test::_injection is also monotonic\r\n        test::_injection<0> f{};\r\n\r\n        // less\r\n        {\r\n            BOOST_HANA_CONSTEXPR_CHECK(less(ord(0), ord(1)));\r\n            BOOST_HANA_CONSTEXPR_CHECK(not_(less(ord(0), ord(0))));\r\n            BOOST_HANA_CONSTEXPR_CHECK(not_(less(ord(1), ord(0))));\r\n        }\r\n\r\n        // less_equal\r\n        {\r\n            BOOST_HANA_CONSTEXPR_CHECK(less_equal(ord(0), ord(1)));\r\n            BOOST_HANA_CONSTEXPR_CHECK(less_equal(ord(0), ord(0)));\r\n            BOOST_HANA_CONSTEXPR_CHECK(not_(less_equal(ord(1), ord(0))));\r\n        }\r\n\r\n        // greater_equal\r\n        {\r\n            BOOST_HANA_CONSTEXPR_CHECK(greater_equal(ord(1), ord(0)));\r\n            BOOST_HANA_CONSTEXPR_CHECK(greater_equal(ord(0), ord(0)));\r\n            BOOST_HANA_CONSTEXPR_CHECK(not_(greater_equal(ord(0), ord(1))));\r\n        }\r\n\r\n        // greater\r\n        {\r\n            BOOST_HANA_CONSTEXPR_CHECK(greater(ord(1), ord(0)));\r\n            BOOST_HANA_CONSTEXPR_CHECK(not_(greater(ord(0), ord(0))));\r\n            BOOST_HANA_CONSTEXPR_CHECK(not_(greater(ord(0), ord(1))));\r\n        }\r\n\r\n        // max\r\n        {\r\n            BOOST_HANA_CONSTEXPR_CHECK(equal(\r\n                max(ord(0), ord(0)), ord(0)\r\n            ));\r\n            BOOST_HANA_CONSTEXPR_CHECK(equal(\r\n                max(ord(1), ord(0)), ord(1)\r\n            ));\r\n            BOOST_HANA_CONSTEXPR_CHECK(equal(\r\n                max(ord(0), ord(1)), ord(1)\r\n            ));\r\n        }\r\n\r\n        // min\r\n        {\r\n            BOOST_HANA_CONSTEXPR_CHECK(equal(\r\n                min(ord(0), ord(0)),\r\n                ord(0)\r\n            ));\r\n            BOOST_HANA_CONSTEXPR_CHECK(equal(\r\n                min(ord(1), ord(0)),\r\n                ord(0)\r\n            ));\r\n            BOOST_HANA_CONSTEXPR_CHECK(equal(\r\n                min(ord(0), ord(1)),\r\n                ord(0)\r\n            ));\r\n        }\r\n\r\n        // ordering\r\n        {\r\n            BOOST_HANA_CONSTEXPR_CHECK(equal(\r\n                ordering(f)(ord(1), ord(0)),\r\n                less(f(ord(1)), f(ord(0)))\r\n            ));\r\n\r\n            BOOST_HANA_CONSTEXPR_CHECK(equal(\r\n                ordering(f)(ord(0), ord(1)),\r\n                less(f(ord(0)), f(ord(1)))\r\n            ));\r\n\r\n            BOOST_HANA_CONSTEXPR_CHECK(equal(\r\n                ordering(f)(ord(0), ord(0)),\r\n                less(f(ord(0)), f(ord(0)))\r\n            ));\r\n        }\r\n    }\r\n\r\n    //////////////////////////////////////////////////////////////////////////\r\n    // Monoid\r\n    //////////////////////////////////////////////////////////////////////////\r\n    {\r\n        constexpr int x = 2, y = 3;\r\n\r\n        // zero\r\n        {\r\n            BOOST_HANA_CONSTEXPR_CHECK(equal(\r\n                zero<Numeric>(), numeric(0)\r\n            ));\r\n        }\r\n\r\n        // plus\r\n        {\r\n            BOOST_HANA_CONSTEXPR_CHECK(equal(\r\n                plus(numeric(x), numeric(y)),\r\n                numeric(x + y)\r\n            ));\r\n        }\r\n    }\r\n\r\n    //////////////////////////////////////////////////////////////////////////\r\n    // Group\r\n    //////////////////////////////////////////////////////////////////////////\r\n    {\r\n        constexpr int x = 2, y = 3;\r\n\r\n        // minus\r\n        {\r\n            BOOST_HANA_CONSTEXPR_CHECK(equal(\r\n                minus(numeric(x), numeric(y)),\r\n                numeric(x - y)\r\n            ));\r\n        }\r\n\r\n        // negate\r\n        {\r\n            BOOST_HANA_CONSTEXPR_CHECK(equal(\r\n                negate(numeric(x)),\r\n                numeric(-x)\r\n            ));\r\n        }\r\n    }\r\n\r\n    //////////////////////////////////////////////////////////////////////////\r\n    // Ring\r\n    //////////////////////////////////////////////////////////////////////////\r\n    {\r\n        constexpr int x = 2, y = 3;\r\n\r\n        // one\r\n        {\r\n            BOOST_HANA_CONSTEXPR_CHECK(equal(\r\n                one<Numeric>(),\r\n                numeric(1)\r\n            ));\r\n        }\r\n\r\n        // mult\r\n        {\r\n            BOOST_HANA_CONSTEXPR_CHECK(equal(\r\n                mult(numeric(x), numeric(y)),\r\n                numeric(x * y)\r\n            ));\r\n        }\r\n\r\n        // power\r\n        {\r\n            BOOST_HANA_CONSTEXPR_CHECK(equal(\r\n                power(numeric(x), zero<CNumeric<int>>()),\r\n                one<Numeric>()\r\n            ));\r\n\r\n            BOOST_HANA_CONSTEXPR_CHECK(equal(\r\n                power(numeric(x), one<CNumeric<int>>()),\r\n                numeric(x)\r\n            ));\r\n\r\n            BOOST_HANA_CONSTEXPR_CHECK(equal(\r\n                power(numeric(x), cnumeric<int, 2>),\r\n                mult(numeric(x), numeric(x))\r\n            ));\r\n\r\n            BOOST_HANA_CONSTEXPR_CHECK(equal(\r\n                power(numeric(x), cnumeric<int, 3>),\r\n                mult(mult(numeric(x), numeric(x)), numeric(x))\r\n            ));\r\n        }\r\n    }\r\n\r\n    //////////////////////////////////////////////////////////////////////////\r\n    // EuclideanRing\r\n    //////////////////////////////////////////////////////////////////////////\r\n    {\r\n        constexpr int x = 6, y = 3, z = 4;\r\n\r\n        // div\r\n        {\r\n            using boost::hana::div; // hide ::div\r\n            BOOST_HANA_CONSTEXPR_CHECK(equal(\r\n                div(numeric(x), numeric(y)),\r\n                numeric(x / y)\r\n            ));\r\n\r\n            BOOST_HANA_CONSTEXPR_CHECK(equal(\r\n                div(numeric(x), numeric(z)),\r\n                 numeric(x/ z)\r\n            ));\r\n        }\r\n\r\n        // mod\r\n        {\r\n            BOOST_HANA_CONSTEXPR_CHECK(equal(\r\n                mod(numeric(x), numeric(y)),\r\n                numeric(x % y)\r\n            ));\r\n\r\n            BOOST_HANA_CONSTEXPR_CHECK(equal(\r\n                mod(numeric(x), numeric(z)),\r\n                numeric(x % z)\r\n            ));\r\n        }\r\n    }\r\n\r\n    //////////////////////////////////////////////////////////////////////////\r\n    // Logical\r\n    //////////////////////////////////////////////////////////////////////////\r\n    {\r\n        auto logical = numeric;\r\n        auto comparable = numeric;\r\n\r\n        // not_\r\n        {\r\n            BOOST_HANA_CONSTEXPR_CHECK(equal(\r\n                not_(logical(true)),\r\n                logical(false)\r\n            ));\r\n        }\r\n\r\n        // and_\r\n        {\r\n            BOOST_HANA_CONSTEXPR_CHECK(equal(\r\n                and_(logical(true)),\r\n                logical(true)\r\n            ));\r\n            BOOST_HANA_CONSTEXPR_CHECK(equal(\r\n                and_(logical(false)),\r\n                logical(false)\r\n            ));\r\n\r\n            BOOST_HANA_CONSTEXPR_CHECK(equal(\r\n                and_(logical(true), logical(true)),\r\n                logical(true)\r\n            ));\r\n            BOOST_HANA_CONSTEXPR_CHECK(equal(\r\n                and_(logical(true), logical(false)),\r\n                logical(false)\r\n            ));\r\n            BOOST_HANA_CONSTEXPR_CHECK(equal(\r\n                and_(logical(false), invalid{}),\r\n                logical(false)\r\n            ));\r\n\r\n            BOOST_HANA_CONSTEXPR_CHECK(equal(\r\n                and_(logical(true), logical(true), logical(true)),\r\n                logical(true)\r\n            ));\r\n            BOOST_HANA_CONSTEXPR_CHECK(equal(\r\n                and_(logical(true), logical(true), logical(false)),\r\n                logical(false)\r\n            ));\r\n            BOOST_HANA_CONSTEXPR_CHECK(equal(\r\n                and_(logical(true), logical(false), invalid{}),\r\n                logical(false)\r\n            ));\r\n            BOOST_HANA_CONSTEXPR_CHECK(equal(\r\n                and_(logical(false), invalid{}, invalid{}),\r\n                logical(false)\r\n            ));\r\n        }\r\n\r\n        // or_\r\n        {\r\n            BOOST_HANA_CONSTEXPR_CHECK(equal(\r\n                or_(logical(true)),\r\n                logical(true)\r\n            ));\r\n            BOOST_HANA_CONSTEXPR_CHECK(equal(\r\n                or_(logical(false)),\r\n                logical(false)\r\n            ));\r\n\r\n            BOOST_HANA_CONSTEXPR_CHECK(equal(\r\n                or_(logical(false), logical(false)),\r\n                logical(false)\r\n            ));\r\n            BOOST_HANA_CONSTEXPR_CHECK(equal(\r\n                or_(logical(false), logical(true)),\r\n                logical(true)\r\n            ));\r\n            BOOST_HANA_CONSTEXPR_CHECK(equal(\r\n                or_(logical(true), invalid{}),\r\n                logical(true)\r\n            ));\r\n\r\n            BOOST_HANA_CONSTEXPR_CHECK(equal(\r\n                or_(logical(false), logical(false), logical(false)),\r\n                logical(false)\r\n            ));\r\n            BOOST_HANA_CONSTEXPR_CHECK(equal(\r\n                or_(logical(false), logical(false), logical(true)),\r\n                logical(true)\r\n            ));\r\n            BOOST_HANA_CONSTEXPR_CHECK(equal(\r\n                or_(logical(false), logical(true), invalid{}),\r\n                logical(true)\r\n            ));\r\n            BOOST_HANA_CONSTEXPR_CHECK(equal(\r\n                or_(logical(true), invalid{}, invalid{}),\r\n                logical(true)\r\n            ));\r\n        }\r\n\r\n        // if_\r\n        {\r\n            BOOST_HANA_CONSTEXPR_CHECK(equal(\r\n                if_(logical(true), comparable(0), comparable(1)),\r\n                comparable(0)\r\n            ));\r\n\r\n            BOOST_HANA_CONSTEXPR_CHECK(equal(\r\n                if_(logical(false), comparable(0), comparable(1)),\r\n                comparable(1)\r\n            ));\r\n        }\r\n\r\n        // eval_if\r\n        {\r\n            auto t = [=](auto) { return comparable(0); };\r\n            auto e = [=](auto) { return comparable(1); };\r\n\r\n            BOOST_HANA_CONSTEXPR_CHECK(equal(\r\n                eval_if(logical(true), t, e),\r\n                comparable(0)\r\n            ));\r\n\r\n            BOOST_HANA_CONSTEXPR_CHECK(equal(\r\n                eval_if(logical(false), t, e),\r\n                comparable(1)\r\n            ));\r\n        }\r\n\r\n        // while_\r\n        {\r\n            auto smaller_than = [](auto n) {\r\n                return [n](auto v) { return v.size() < n; };\r\n            };\r\n            auto f = [](auto v) {\r\n                v.push_back(v.size());\r\n                return v;\r\n            };\r\n\r\n            BOOST_HANA_RUNTIME_CHECK(equal(\r\n                while_(smaller_than(0u), std::vector<int>{}, f),\r\n                std::vector<int>{}\r\n            ));\r\n\r\n            BOOST_HANA_RUNTIME_CHECK(equal(\r\n                while_(smaller_than(1u), std::vector<int>{}, f),\r\n                std::vector<int>{0}\r\n            ));\r\n\r\n            BOOST_HANA_RUNTIME_CHECK(equal(\r\n                while_(smaller_than(2u), std::vector<int>{}, f),\r\n                std::vector<int>{0, 1}\r\n            ));\r\n\r\n            BOOST_HANA_RUNTIME_CHECK(equal(\r\n                while_(smaller_than(3u), std::vector<int>{}, f),\r\n                std::vector<int>{0, 1, 2}\r\n            ));\r\n\r\n            BOOST_HANA_RUNTIME_CHECK(equal(\r\n                while_(smaller_than(4u), std::vector<int>{}, f),\r\n                std::vector<int>{0, 1, 2, 3}\r\n            ));\r\n\r\n            // Make sure it can be called with an lvalue state:\r\n            std::vector<int> v{};\r\n            BOOST_HANA_RUNTIME_CHECK(equal(\r\n                while_(smaller_than(4u), v, f),\r\n                std::vector<int>{0, 1, 2, 3}\r\n            ));\r\n        }\r\n\r\n        // while_\r\n        {\r\n            auto less_than = [](auto n) {\r\n                return [n](auto v) { return v.size() < n; };\r\n            };\r\n            auto f = [](auto v) {\r\n                v.push_back(v.size());\r\n                return v;\r\n            };\r\n\r\n            BOOST_HANA_RUNTIME_CHECK(equal(\r\n                while_(less_than(0u), std::vector<int>{}, f),\r\n                std::vector<int>{}\r\n            ));\r\n\r\n            BOOST_HANA_RUNTIME_CHECK(equal(\r\n                while_(less_than(1u), std::vector<int>{}, f),\r\n                std::vector<int>{0}\r\n            ));\r\n\r\n            BOOST_HANA_RUNTIME_CHECK(equal(\r\n                while_(less_than(2u), std::vector<int>{}, f),\r\n                std::vector<int>{0, 1}\r\n            ));\r\n\r\n            BOOST_HANA_RUNTIME_CHECK(equal(\r\n                while_(less_than(3u), std::vector<int>{}, f),\r\n                std::vector<int>{0, 1, 2}\r\n            ));\r\n\r\n            BOOST_HANA_RUNTIME_CHECK(equal(\r\n                while_(less_than(4u), std::vector<int>{}, f),\r\n                std::vector<int>{0, 1, 2, 3}\r\n            ));\r\n\r\n            // Make sure it can be called with an lvalue state:\r\n            std::vector<int> v{};\r\n            BOOST_HANA_RUNTIME_CHECK(equal(\r\n                while_(less_than(4u), v, f),\r\n                std::vector<int>{0, 1, 2, 3}\r\n            ));\r\n        }\r\n    }\r\n}\r\n", "meta": {"hexsha": "ec809f192dbc418f81065e7ea7691f2553f0640e", "size": 14492, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "thirdparty-cpp/boost_1_62_0/libs/hana/test/numeric/main.hpp", "max_stars_repo_name": "nxplatform/nx-mobile", "max_stars_repo_head_hexsha": "0dc174c893f2667377cb2ef7e5ffeb212fa8b3e5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-12-15T19:57:24.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-15T19:57:24.000Z", "max_issues_repo_path": "thirdparty-cpp/boost_1_62_0/libs/hana/test/numeric/main.hpp", "max_issues_repo_name": "nxplatform/nx-mobile", "max_issues_repo_head_hexsha": "0dc174c893f2667377cb2ef7e5ffeb212fa8b3e5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thirdparty-cpp/boost_1_62_0/libs/hana/test/numeric/main.hpp", "max_forks_repo_name": "nxplatform/nx-mobile", "max_forks_repo_head_hexsha": "0dc174c893f2667377cb2ef7e5ffeb212fa8b3e5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5755102041, "max_line_length": 82, "alphanum_fraction": 0.4023599227, "num_tokens": 2838, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321720225278, "lm_q2_score": 0.6757646010190477, "lm_q1q2_score": 0.48130128955973317}}
{"text": "/* boost random/sobol.hpp header file\n *\n * Copyright Justinas Vygintas Daugmaudis 2010-2018\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_RANDOM_SOBOL_HPP\n#define BOOST_RANDOM_SOBOL_HPP\n\n#include <boost/random/detail/sobol_table.hpp>\n#include <boost/random/detail/gray_coded_qrng.hpp>\n#include <boost/assert.hpp>\n\nnamespace boost {\nnamespace random {\n\n/** @cond */\nnamespace qrng_detail {\n\n// sobol_lattice sets up the random-number generator to produce a Sobol\n// sequence of at most max dims-dimensional quasi-random vectors.\n// Adapted from ACM TOMS algorithm 659, see\n\n// http://doi.acm.org/10.1145/42288.214372\n\ntemplate<typename UIntType, unsigned w, typename SobolTables>\nstruct sobol_lattice\n{\n  typedef UIntType value_type;\n\n  BOOST_STATIC_ASSERT(w > 0u);\n  BOOST_STATIC_CONSTANT(unsigned, bit_count = w);\n\nprivate:\n  typedef std::vector<value_type> container_type;\n\npublic:\n  explicit sobol_lattice(std::size_t dimension)\n  {\n    resize(dimension);\n  }\n\n  // default copy c-tor is fine\n\n  void resize(std::size_t dimension)\n  {\n    dimension_assert(\"Sobol\", dimension, SobolTables::max_dimension);\n\n    // Initialize the bit array\n    container_type cj(bit_count * dimension);\n\n    // Initialize direction table in dimension 0\n    for (unsigned k = 0; k != bit_count; ++k)\n      cj[dimension*k] = static_cast<value_type>(1);\n\n    // Initialize in remaining dimensions.\n    for (std::size_t dim = 1; dim < dimension; ++dim)\n    {\n      const typename SobolTables::value_type poly = SobolTables::polynomial(dim-1);\n      if (poly > (std::numeric_limits<value_type>::max)()) {\n        boost::throw_exception( std::range_error(\"sobol: polynomial value outside the given value type range\") );\n      }\n      const unsigned degree = qrng_detail::msb(poly); // integer log2(poly)\n\n      // set initial values of m from table\n      for (unsigned k = 0; k != degree; ++k)\n        cj[dimension*k + dim] = SobolTables::minit(dim-1, k);\n\n      // Calculate remaining elements for this dimension,\n      // as explained in Bratley+Fox, section 2.\n      for (unsigned j = degree; j < bit_count; ++j)\n      {\n        typename SobolTables::value_type p_i = poly;\n        const std::size_t bit_offset = dimension*j + dim;\n\n        cj[bit_offset] = cj[dimension*(j-degree) + dim];\n        for (unsigned k = 0; k != degree; ++k, p_i >>= 1)\n        {\n          int rem = degree - k;\n          cj[bit_offset] ^= ((p_i & 1) * cj[dimension*(j-rem) + dim]) << rem;\n        }\n      }\n    }\n\n    // Shift columns by appropriate power of 2.\n    unsigned p = 1u;\n    for (int j = bit_count-1-1; j >= 0; --j, ++p)\n    {\n      const std::size_t bit_offset = dimension * j;\n      for (std::size_t dim = 0; dim != dimension; ++dim)\n        cj[bit_offset + dim] <<= p;\n    }\n\n    bits.swap(cj);\n  }\n\n  typename container_type::const_iterator iter_at(std::size_t n) const\n  {\n    BOOST_ASSERT(!(n > bits.size()));\n    return bits.begin() + n;\n  }\n\nprivate:\n  container_type bits;\n};\n\n} // namespace qrng_detail\n\ntypedef detail::qrng_tables::sobol default_sobol_table;\n\n/** @endcond */\n\n//!Instantiations of class template sobol_engine model a \\quasi_random_number_generator.\n//!The sobol_engine uses the algorithm described in\n//! \\blockquote\n//![Bratley+Fox, TOMS 14, 88 (1988)]\n//!and [Antonov+Saleev, USSR Comput. Maths. Math. Phys. 19, 252 (1980)]\n//! \\endblockquote\n//!\n//!\\attention sobol_engine skips trivial zeroes at the start of the sequence. For example, the beginning\n//!of the 2-dimensional Sobol sequence in @c uniform_01 distribution will look like this:\n//!\\code{.cpp}\n//!0.5, 0.5,\n//!0.75, 0.25,\n//!0.25, 0.75,\n//!0.375, 0.375,\n//!0.875, 0.875,\n//!...\n//!\\endcode\n//!\n//!In the following documentation @c X denotes the concrete class of the template\n//!sobol_engine returning objects of type @c UIntType, u and v are the values of @c X.\n//!\n//!Some member functions may throw exceptions of type @c std::range_error. This\n//!happens when the quasi-random domain is exhausted and the generator cannot produce\n//!any more values. The length of the low discrepancy sequence is given by \\f$L=Dimension \\times (2^{w} - 1)\\f$.\ntemplate<typename UIntType, unsigned w, typename SobolTables = default_sobol_table>\nclass sobol_engine\n  : public qrng_detail::gray_coded_qrng<\n      qrng_detail::sobol_lattice<UIntType, w, SobolTables>\n    >\n{\n  typedef qrng_detail::sobol_lattice<UIntType, w, SobolTables> lattice_t;\n  typedef qrng_detail::gray_coded_qrng<lattice_t> base_t;\n\npublic:\n  //!Effects: Constructs the default `s`-dimensional Sobol quasi-random number generator.\n  //!\n  //!Throws: bad_alloc, invalid_argument, range_error.\n  explicit sobol_engine(std::size_t s)\n    : base_t(s)\n  {}\n\n  // default copy c-tor is fine\n\n#ifdef BOOST_RANDOM_DOXYGEN\n  //=========================Doxygen needs this!==============================\n  typedef UIntType result_type;\n\n  /** @copydoc boost::random::niederreiter_base2_engine::min() */\n  static BOOST_CONSTEXPR result_type min BOOST_PREVENT_MACRO_SUBSTITUTION ()\n  { return (base_t::min)(); }\n\n  /** @copydoc boost::random::niederreiter_base2_engine::max() */\n  static BOOST_CONSTEXPR result_type max BOOST_PREVENT_MACRO_SUBSTITUTION ()\n  { return (base_t::max)(); }\n\n  /** @copydoc boost::random::niederreiter_base2_engine::dimension() */\n  std::size_t dimension() const { return base_t::dimension(); }\n\n  /** @copydoc boost::random::niederreiter_base2_engine::seed() */\n  void seed()\n  {\n    base_t::seed();\n  }\n\n  /** @copydoc boost::random::niederreiter_base2_engine::seed(UIntType) */\n  void seed(UIntType init)\n  {\n    base_t::seed(init);\n  }\n\n  /** @copydoc boost::random::niederreiter_base2_engine::operator()() */\n  result_type operator()()\n  {\n    return base_t::operator()();\n  }\n\n  /** @copydoc boost::random::niederreiter_base2_engine::discard(boost::uintmax_t) */\n  void discard(boost::uintmax_t z)\n  {\n    base_t::discard(z);\n  }\n\n  /** Returns true if the two generators will produce identical sequences of outputs. */\n  BOOST_RANDOM_DETAIL_EQUALITY_OPERATOR(sobol_engine, x, y)\n  { return static_cast<const base_t&>(x) == y; }\n\n  /** Returns true if the two generators will produce different sequences of outputs. */\n  BOOST_RANDOM_DETAIL_INEQUALITY_OPERATOR(sobol_engine)\n\n  /** Writes the textual representation of the generator to a @c std::ostream. */\n  BOOST_RANDOM_DETAIL_OSTREAM_OPERATOR(os, sobol_engine, s)\n  { return os << static_cast<const base_t&>(s); }\n\n  /** Reads the textual representation of the generator from a @c std::istream. */\n  BOOST_RANDOM_DETAIL_ISTREAM_OPERATOR(is, sobol_engine, s)\n  { return is >> static_cast<base_t&>(s); }\n\n#endif // BOOST_RANDOM_DOXYGEN\n};\n\n/**\n * @attention This specialization of \\sobol_engine supports up to 3667 dimensions.\n *\n * Data on the primitive binary polynomials `a` and the corresponding starting values `m`\n * for Sobol sequences in up to 21201 dimensions was taken from\n *\n *  @blockquote\n *  S. Joe and F. Y. Kuo, Constructing Sobol sequences with better two-dimensional projections,\n *  SIAM J. Sci. Comput. 30, 2635-2654 (2008).\n *  @endblockquote\n *\n * See the original tables up to dimension 21201: https://web.archive.org/web/20170802022909/http://web.maths.unsw.edu.au/~fkuo/sobol/new-joe-kuo-6.21201\n *\n * For practical reasons the default table uses only the subset of binary polynomials `a` < 2<sup>16</sup>.\n *\n * However, it is possible to provide your own table to \\sobol_engine should the default one be insufficient.\n */\ntypedef sobol_engine<boost::uint_least64_t, 64u, default_sobol_table> sobol;\n\n} // namespace random\n\n} // namespace boost\n\n#endif // BOOST_RANDOM_SOBOL_HPP\n", "meta": {"hexsha": "042b3ba3a370824dbb80252a5bd72e6955bdb69b", "size": 7731, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/random/sobol.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": 2728.0, "max_stars_repo_stars_event_min_datetime": "2015-01-01T10:06:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T18:12:58.000Z", "max_issues_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/random/sobol.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": 1192.0, "max_issues_repo_issues_event_min_datetime": "2015-01-01T06:03:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T09:14:36.000Z", "max_forks_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/random/sobol.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": 334.0, "max_forks_repo_forks_event_min_datetime": "2015-01-08T20:47:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T07:07:01.000Z", "avg_line_length": 32.3472803347, "max_line_length": 153, "alphanum_fraction": 0.6926658906, "num_tokens": 2098, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321720225278, "lm_q2_score": 0.6757645879592641, "lm_q1q2_score": 0.4813012802581352}}
{"text": "#include <pybind11/numpy.h>\n#include <pybind11/pybind11.h>\n\n#include <Eigen/Dense>\nusing Eigen::Matrix;\nusing Eigen::Dynamic;\n\n#include \"ceres/autodiff_cost_function.h\"\n#include \"ceres/cost_function.h\"\n#include \"ceres/internal/autodiff.h\"\n#include \"ceres/internal/eigen.h\"\n\n#include <glog/logging.h>\n\n#include <adept.h>\n\n#include <game/vsr/cga_op.h>\n\n#include <hep/ga.hpp>\n\n#include <iostream>\n#include <sstream>\n#include <string>\n\nusing namespace vsr::cga;\nnamespace py = pybind11;\n\ntemplate <typename T>\nvoid InnerProductVectorBivector(const T *vec, const T *biv, T *res) {\n  Vector<T> vector(vec);\n  Bivector<T> bivector(biv);\n  Vector<T> result = vector <= bivector;\n  for (int i = 0; i < 3; ++i)\n    res[i] = result[i];\n}\n\ntemplate <typename T>\nvoid InnerProductVectorVector(const T *vec, const T *vec1, T *res) {\n  Vector<T> vector(vec);\n  Vector<T> vector1(vec1);\n  Scalar<T> result = vector <= vector1;\n  res[0] = result[0];\n}\n\ntemplate <typename T>\nvoid InnerProductVectorBivector2(const T *a, const T *b, T *res) {\n  res[0] = -a[2] * b[1] - a[1] * b[0];\n  res[1] = -a[2] * b[2] + a[0] * b[0];\n  res[2] = a[1] * b[2] + a[0] * b[1];\n}\n\nstruct InnerProductVectorBivectorFunctor2 {\n  template <typename T>\n  bool operator()(const T *vec, const T *biv, T *res) const {\n    InnerProductVectorBivector2(vec, biv, res);\n    return true;\n  }\n};\n\npy::list AdeptDiffInnerProductVectorBivector(const Vec &vec, const Biv &biv) {\n  auto result = py::array(py::buffer_info(\n      nullptr,        /* Pointer to data (nullptr -> ask NumPy to allocate!) */\n      sizeof(double), /* Size of one item */\n      py::format_descriptor<double>::value(), /* Buffer format */\n      2,                                      /* How many dimensions? */\n      {3, 3},                 /* Number of elements for each dimension */\n      {sizeof(double) * 3, 3} /* Strides for each dimension */\n      ));\n\n  auto buf = result.request();\n\n  adept::Stack stack;\n\n  double jac[9];\n  std::array<adept::adouble, 3> vector{vec[0], vec[1], vec[2]};\n  std::array<adept::adouble, 3> bivector{biv[0], biv[1], biv[2]};\n  stack.new_recording();\n  std::array<adept::adouble, 3> vec_ip_biv{0.0, 0.0, 0.0};\n\n  InnerProductVectorBivector2(vector.begin(), bivector.begin(),\n                              vec_ip_biv.begin());\n\n  stack.independent(vector.begin(), 3);\n  // stack.independent(bivector.begin(), 3);\n  stack.dependent(vec_ip_biv.begin(), 3);\n\n  // stack.jacobian(static_cast<double *>(buf.ptr), true);\n  stack.jacobian_reverse(static_cast<double *>(buf.ptr), true);\n  // stack.jacobian_forward(static_cast<double *>(buf.ptr), true);\n\n  std::stringstream ss;\n  stack.print_statements(ss);\n\n  py::list list;\n  list.append(result);\n  list.append(py::str(ss.str().c_str()));\n\n  return list;\n}\n\nstruct InnerProductVectorBivectorFunctor {\n  template <typename T>\n  bool operator()(const T *vec, const T *biv, T *res) const {\n    InnerProductVectorBivector(vec, biv, res);\n    return true;\n  }\n};\n\nstruct InnerProductVectorVectorFunctor {\n  template <typename T>\n  bool operator()(const T *vec, const T *vec2, T *res) const {\n    InnerProductVectorVector(vec, vec2, res);\n    return true;\n  }\n};\n\npy::list CeresDiffInnerProductVectorVector(const Vec &vec, const Vec &vec2) {\n  auto py_array_jac = py::array(py::buffer_info(\n      nullptr, sizeof(double), py::format_descriptor<double>::value(), 2,\n      {1, 3}, {sizeof(double) * 3, sizeof(double)}));\n\n  auto py_array_result = py::array(py::buffer_info(\n      nullptr, sizeof(double), py::format_descriptor<double>::value(), 2,\n      {1, 1}, {sizeof(double), sizeof(double)}));\n\n  auto buf_jac = py_array_jac.request();\n  auto buf_res = py_array_result.request();\n\n  const double *parameters[2] = {vec.begin(), vec2.begin()};\n  double *jacobians[2] = {static_cast<double *>(buf_jac.ptr), nullptr};\n\n  ceres::AutoDiffCostFunction<InnerProductVectorVectorFunctor, 1, 3, 3>(\n      new InnerProductVectorVectorFunctor())\n      .Evaluate(parameters, static_cast<double *>(buf_res.ptr), jacobians);\n\n  py::list list;\n  list.append(py_array_result);\n  list.append(py_array_jac);\n\n  return list;\n}\npy::list CeresDiffInnerProductVectorBivector(const Vec &vec, const Biv &biv) {\n  auto py_array_jac = py::array(py::buffer_info(\n      nullptr, sizeof(double), py::format_descriptor<double>::value(), 2,\n      {3, 3}, {sizeof(double) * 3, sizeof(double)}));\n\n  auto py_array_result = py::array(py::buffer_info(\n      nullptr, sizeof(double), py::format_descriptor<double>::value(), 2,\n      {3, 1}, {sizeof(double) * 3, sizeof(double)}));\n\n  auto buf_jac = py_array_jac.request();\n  auto buf_res = py_array_result.request();\n\n  const double *parameters[2] = {vec.begin(), biv.begin()};\n  double *jacobians[2] = {static_cast<double *>(buf_jac.ptr), nullptr};\n\n  ceres::AutoDiffCostFunction<InnerProductVectorBivectorFunctor, 3, 3, 3>(\n      new InnerProductVectorBivectorFunctor())\n      .Evaluate(parameters, static_cast<double *>(buf_res.ptr), jacobians);\n\n  py::list list;\n  list.append(py_array_result);\n  list.append(py_array_jac);\n\n  return list;\n}\n\ntemplate <typename T> using Matrix4 = Eigen::Matrix<T, 4, 4>;\n\ntemplate <typename T> inline static Matrix4<T> s() {\n  Matrix4<T> m;\n  m << T(1), T(0), T(0), T(0), T(0), T(1), T(0), T(0), T(0), T(0), T(1), T(0),\n      T(0), T(0), T(0), T(1);\n  return m;\n}\n\ntemplate <typename T> inline static Matrix4<T> e1() {\n  Matrix4<T> m;\n  m << T(0), T(0), T(0), T(1), T(0), T(0), T(1), T(0), T(0), T(1), T(0), T(0),\n      T(1), T(0), T(0), T(0);\n  return m;\n}\n\ntemplate <typename T> inline static Matrix4<T> e2() {\n  Matrix4<T> m;\n  m << T(0), T(0), T(1), T(0), T(0), T(0), T(0), T(-1), T(1), T(0), T(0), T(0),\n      T(0), T(-1), T(0), T(0);\n  return m;\n}\n\ntemplate <typename T> inline static Matrix4<T> e3() {\n  Matrix4<T> m;\n  m << T(1), T(0), T(0), T(0), T(0), T(1), T(0), T(0), T(0), T(0), T(-1), T(0),\n      T(0), T(0), T(0), T(-1);\n  return m;\n}\n\nstruct DiffRotorMatrixFunctor {\n  template <typename T> bool operator()(const T *th, const T *a, T *b) const {\n    Matrix4<T> rotor =\n        cos(T(0.5) * th[0]) * s<T>() - sin(T(0.5) * th[0]) * e1<T>() * e2<T>();\n    Matrix4<T> rotor_inv =\n        cos(T(0.5) * th[0]) * s<T>() + sin(T(0.5) * th[0]) * e1<T>() * e2<T>();\n    Matrix4<T> vec_a = a[0] * e1<T>() + a[1] * e2<T>() + a[2] * e3<T>();\n    Matrix4<T> vec_b = rotor * vec_a * rotor_inv;\n    b[0] = vec_b(0, 3); // e1\n    b[1] = vec_b(0, 2); // e2\n    b[2] = vec_b(0, 0); // e3\n    return true;\n  }\n};\n\npy::list CeresDiffRotorMatrix(const double theta, const Vec &a) {\n  auto py_array_jac = py::array(py::buffer_info(\n      nullptr, sizeof(double), py::format_descriptor<double>::value(), 2,\n      {3, 1}, {sizeof(double), sizeof(double)}));\n\n  auto py_array_result = py::array(py::buffer_info(\n      nullptr, sizeof(double), py::format_descriptor<double>::value(), 2,\n      {3, 1}, {sizeof(double), sizeof(double)}));\n\n  auto buf_jac = py_array_jac.request();\n  auto buf_res = py_array_result.request();\n\n  const double *parameters[2] = {&theta, a.begin()};\n  double *jacobians[2] = {static_cast<double *>(buf_jac.ptr), nullptr};\n\n  ceres::AutoDiffCostFunction<DiffRotorMatrixFunctor, 3, 1, 3>(\n      new DiffRotorMatrixFunctor())\n      .Evaluate(parameters, static_cast<double *>(buf_res.ptr), jacobians);\n\n  py::list list;\n  list.append(py_array_result);\n  list.append(py_array_jac);\n\n  return list;\n}\n\nstruct DiffRotorVersorFunctor {\n  template <typename T> bool operator()(const T *th, const T *a, T *b) const {\n    Rotor<T> rotor{cos(T(0.5) * th[0]), -sin(T(0.5) * th[0]), T(0.0), T(0.0)};\n    Vector<T> vec_a{a[0], a[1], a[2]};\n    Vector<T> vec_b = vec_a.spin(rotor);\n    for (int i = 0; i < 3; ++i)\n      b[i] = vec_b[i];\n    return true;\n  }\n};\npy::list CeresDiffRotorVersor(const double theta, const Vec &a) {\n  auto py_array_jac = py::array(py::buffer_info(\n      nullptr, sizeof(double), py::format_descriptor<double>::value(), 2,\n      {3, 1}, {sizeof(double), sizeof(double)}));\n\n  auto py_array_result = py::array(py::buffer_info(\n      nullptr, sizeof(double), py::format_descriptor<double>::value(), 2,\n      {3, 1}, {sizeof(double), sizeof(double)}));\n\n  auto buf_jac = py_array_jac.request();\n  auto buf_res = py_array_result.request();\n\n  const double *parameters[2] = {&theta, a.begin()};\n  double *jacobians[2] = {static_cast<double *>(buf_jac.ptr), nullptr};\n\n  ceres::AutoDiffCostFunction<DiffRotorVersorFunctor, 3, 1, 3>(\n      new DiffRotorVersorFunctor())\n      .Evaluate(parameters, static_cast<double *>(buf_res.ptr), jacobians);\n\n  py::list list;\n  list.append(py_array_result);\n  list.append(py_array_jac);\n\n  return list;\n}\n\npy::list AdeptDiffRotorMatrixForward(const double theta, const Vec &vec) {\n  auto py_array_jac = py::array(py::buffer_info(\n      nullptr, sizeof(double), py::format_descriptor<double>::value(), 2,\n      {3, 1}, {sizeof(double), sizeof(double)}));\n\n  auto py_array_result = py::array(py::buffer_info(\n      nullptr, sizeof(double), py::format_descriptor<double>::value(), 2,\n      {3, 1}, {sizeof(double), sizeof(double)}));\n\n  auto buf_jac = py_array_jac.request();\n  auto buf_res = py_array_result.request();\n\n  adept::Stack stack;\n  adept::adouble th{theta};\n  std::array<adept::adouble, 3> a{vec[0], vec[1], vec[2]};\n  stack.new_recording();\n  std::array<adept::adouble, 3> b{0.0, 0.0, 0.0};\n  DiffRotorMatrixFunctor()(&th, a.begin(), b.begin());\n  stack.independent(&th, 1);\n  stack.dependent(b.begin(), 3);\n\n  // stack.jacobian(static_cast<double *>(buf_jac.ptr), true);\n  // stack.jacobian_reverse(static_cast<double *>(buf_jac.ptr), true);\n  stack.jacobian_forward(static_cast<double *>(buf_jac.ptr), true);\n\n  std::stringstream ss;\n  stack.print_statements(ss);\n\n  auto res_ptr = static_cast<double *>(buf_res.ptr);\n  for (int i = 0; i < 3; ++i)\n    res_ptr[i] = b[i].value();\n\n  py::list list;\n  list.append(py_array_result);\n  list.append(py_array_jac);\n  list.append(py::str(ss.str().c_str()));\n  std::stringstream sstatus;\n  stack.print_status(sstatus);\n  list.append(py::str(sstatus.str().c_str()));\n\n  return list;\n}\n\npy::list AdeptDiffRotorMatrixReverse(const double theta, const Vec &vec) {\n  auto py_array_jac = py::array(py::buffer_info(\n      nullptr, sizeof(double), py::format_descriptor<double>::value(), 2,\n      {3, 1}, {sizeof(double), sizeof(double)}));\n\n  auto py_array_result = py::array(py::buffer_info(\n      nullptr, sizeof(double), py::format_descriptor<double>::value(), 2,\n      {3, 1}, {sizeof(double), sizeof(double)}));\n\n  auto buf_jac = py_array_jac.request();\n  auto buf_res = py_array_result.request();\n\n  adept::Stack stack;\n  adept::adouble th{theta};\n  std::array<adept::adouble, 3> a{vec[0], vec[1], vec[2]};\n  stack.new_recording();\n  std::array<adept::adouble, 3> b{0.0, 0.0, 0.0};\n  DiffRotorMatrixFunctor()(&th, a.begin(), b.begin());\n  stack.independent(&th, 1);\n  stack.dependent(b.begin(), 3);\n\n  // stack.jacobian(static_cast<double *>(buf_jac.ptr), true);\n  stack.jacobian_reverse(static_cast<double *>(buf_jac.ptr), true);\n  // stack.jacobian_forward(static_cast<double *>(buf_jac.ptr), true);\n\n  std::stringstream ss;\n  stack.print_statements(ss);\n\n  auto res_ptr = static_cast<double *>(buf_res.ptr);\n  for (int i = 0; i < 3; ++i)\n    res_ptr[i] = b[i].value();\n\n  py::list list;\n  list.append(py_array_result);\n  list.append(py_array_jac);\n  list.append(py::str(ss.str().c_str()));\n  std::stringstream sstatus;\n  stack.print_status(sstatus);\n  list.append(py::str(sstatus.str().c_str()));\n\n  return list;\n}\n\npy::list AdeptDiffRotorVersorForward(const double theta, const Vec &vec) {\n  auto py_array_jac = py::array(py::buffer_info(\n      nullptr, sizeof(double), py::format_descriptor<double>::value(), 2,\n      {3, 1}, {sizeof(double), sizeof(double)}));\n\n  auto py_array_result = py::array(py::buffer_info(\n      nullptr, sizeof(double), py::format_descriptor<double>::value(), 2,\n      {3, 1}, {sizeof(double), sizeof(double)}));\n\n  auto buf_jac = py_array_jac.request();\n  auto buf_res = py_array_result.request();\n\n  adept::Stack stack;\n  adept::adouble th{theta};\n  std::array<adept::adouble, 3> a{vec[0], vec[1], vec[2]};\n  stack.new_recording();\n  std::array<adept::adouble, 3> b{0.0, 0.0, 0.0};\n  DiffRotorVersorFunctor()(&th, a.begin(), b.begin());\n  stack.independent(&th, 1);\n  stack.dependent(b.begin(), 3);\n\n  // stack.jacobian(static_cast<double *>(buf_jac.ptr), true);\n  // stack.jacobian_reverse(static_cast<double *>(buf_jac.ptr), true);\n  stack.jacobian_forward(static_cast<double *>(buf_jac.ptr), true);\n\n  std::stringstream ss;\n  stack.print_statements(ss);\n\n  auto res_ptr = static_cast<double *>(buf_res.ptr);\n  for (int i = 0; i < 3; ++i)\n    res_ptr[i] = b[i].value();\n\n  py::list list;\n  list.append(py_array_result);\n  list.append(py_array_jac);\n  list.append(py::str(ss.str().c_str()));\n  std::stringstream sstatus;\n  stack.print_status(sstatus);\n  list.append(py::str(sstatus.str().c_str()));\n\n  return list;\n}\n\npy::list AdeptDiffRotorVersorReverse(const double theta, const Vec &vec) {\n  auto py_array_jac = py::array(py::buffer_info(\n      nullptr, sizeof(double), py::format_descriptor<double>::value(), 2,\n      {3, 1}, {sizeof(double), sizeof(double)}));\n\n  auto py_array_result = py::array(py::buffer_info(\n      nullptr, sizeof(double), py::format_descriptor<double>::value(), 2,\n      {3, 1}, {sizeof(double), sizeof(double)}));\n\n  auto buf_jac = py_array_jac.request();\n  auto buf_res = py_array_result.request();\n\n  adept::Stack stack;\n  adept::adouble th{theta};\n  std::array<adept::adouble, 3> a{vec[0], vec[1], vec[2]};\n  stack.new_recording();\n  std::array<adept::adouble, 3> b{0.0, 0.0, 0.0};\n  DiffRotorVersorFunctor()(&th, a.begin(), b.begin());\n  stack.independent(&th, 1);\n  stack.dependent(b.begin(), 3);\n\n  // stack.jacobian(static_cast<double *>(buf_jac.ptr), true);\n  stack.jacobian_reverse(static_cast<double *>(buf_jac.ptr), true);\n  // stack.jacobian_forward(static_cast<double *>(buf_jac.ptr), true);\n\n  std::stringstream ss;\n  stack.print_statements(ss);\n\n  auto res_ptr = static_cast<double *>(buf_res.ptr);\n  for (int i = 0; i < 3; ++i)\n    res_ptr[i] = b[i].value();\n\n  py::list list;\n  list.append(py_array_result);\n  list.append(py_array_jac);\n  list.append(py::str(ss.str().c_str()));\n  std::stringstream sstatus;\n  stack.print_status(sstatus);\n  list.append(py::str(sstatus.str().c_str()));\n\n  return list;\n}\n\nstruct DiffRotorHepGAFunctor {\n  template <typename T> bool operator()(const T *th, const T *a, T *b) const {\n    using Algebra = hep::algebra<T, 3, 0>;\n    using Rotor = hep::multi_vector<Algebra, hep::list<0, 3, 5, 6>>;\n    using Vector = hep::multi_vector<Algebra, hep::list<1, 2, 4>>;\n    Rotor rotor{cos(T(0.5) * th[0]), -sin(T(0.5) * th[0]), T(0.0), T(0.0)};\n    Vector pnt_a{a[0], a[1], a[2]};\n    Vector pnt_b = hep::grade<1>(rotor * pnt_a * ~rotor);\n    for (int i = 0; i < 3; ++i)\n      b[i] = pnt_b[i];\n    return true;\n  }\n};\n\npy::list AdeptDiffRotorHepGAForward(const double theta, const Vec &vec) {\n  auto py_array_jac = py::array(py::buffer_info(\n      nullptr, sizeof(double), py::format_descriptor<double>::value(), 2,\n      {3, 1}, {sizeof(double), sizeof(double)}));\n\n  auto py_array_result = py::array(py::buffer_info(\n      nullptr, sizeof(double), py::format_descriptor<double>::value(), 2,\n      {3, 1}, {sizeof(double), sizeof(double)}));\n\n  auto buf_jac = py_array_jac.request();\n  auto buf_res = py_array_result.request();\n\n  adept::Stack stack;\n  adept::adouble th{theta};\n  std::array<adept::adouble, 3> a{vec[0], vec[1], vec[2]};\n  stack.new_recording();\n  std::array<adept::adouble, 3> b{0.0, 0.0, 0.0};\n  DiffRotorHepGAFunctor()(&th, a.begin(), b.begin());\n  stack.independent(&th, 1);\n  stack.dependent(b.begin(), 3);\n\n  // stack.jacobian(static_cast<double *>(buf_jac.ptr), true);\n  // stack.jacobian_reverse(static_cast<double *>(buf_jac.ptr), true);\n  stack.jacobian_forward(static_cast<double *>(buf_jac.ptr), true);\n\n  std::stringstream ss;\n  stack.print_statements(ss);\n\n  auto res_ptr = static_cast<double *>(buf_res.ptr);\n  for (int i = 0; i < 3; ++i)\n    res_ptr[i] = b[i].value();\n\n  py::list list;\n  list.append(py_array_result);\n  list.append(py_array_jac);\n  list.append(py::str(ss.str().c_str()));\n  std::stringstream sstatus;\n  stack.print_status(sstatus);\n  list.append(py::str(sstatus.str().c_str()));\n\n  return list;\n}\n\npy::list AdeptDiffRotorHepGAReverse(const double theta, const Vec &vec) {\n  auto py_array_jac = py::array(py::buffer_info(\n      nullptr, sizeof(double), py::format_descriptor<double>::value(), 2,\n      {3, 1}, {sizeof(double), sizeof(double)}));\n\n  auto py_array_result = py::array(py::buffer_info(\n      nullptr, sizeof(double), py::format_descriptor<double>::value(), 2,\n      {3, 1}, {sizeof(double), sizeof(double)}));\n\n  auto buf_jac = py_array_jac.request();\n  auto buf_res = py_array_result.request();\n\n  adept::Stack stack;\n  adept::adouble th{theta};\n  std::array<adept::adouble, 3> a{vec[0], vec[1], vec[2]};\n  stack.new_recording();\n  std::array<adept::adouble, 3> b{0.0, 0.0, 0.0};\n  DiffRotorHepGAFunctor()(&th, a.begin(), b.begin());\n  stack.independent(&th, 1);\n  stack.dependent(b.begin(), 3);\n\n  // stack.jacobian(static_cast<double *>(buf_jac.ptr), true);\n  stack.jacobian_reverse(static_cast<double *>(buf_jac.ptr), true);\n  // stack.jacobian_forward(static_cast<double *>(buf_jac.ptr), true);\n\n  std::stringstream ss;\n  stack.print_statements(ss);\n\n  auto res_ptr = static_cast<double *>(buf_res.ptr);\n  for (int i = 0; i < 3; ++i)\n    res_ptr[i] = b[i].value();\n\n  py::list list;\n  list.append(py_array_result);\n  list.append(py_array_jac);\n  list.append(py::str(ss.str().c_str()));\n  std::stringstream sstatus;\n  stack.print_status(sstatus);\n  list.append(py::str(sstatus.str().c_str()));\n\n  return list;\n}\n\npy::list CeresDiffRotorHepGA(const double theta, const Vec &a) {\n  auto py_array_jac = py::array(py::buffer_info(\n      nullptr, sizeof(double), py::format_descriptor<double>::value(), 2,\n      {3, 1}, {sizeof(double), sizeof(double)}));\n\n  auto py_array_result = py::array(py::buffer_info(\n      nullptr, sizeof(double), py::format_descriptor<double>::value(), 2,\n      {3, 1}, {sizeof(double), sizeof(double)}));\n\n  auto buf_jac = py_array_jac.request();\n  auto buf_res = py_array_result.request();\n\n  const double *parameters[2] = {&theta, a.begin()};\n  double *jacobians[2] = {static_cast<double *>(buf_jac.ptr), nullptr};\n\n  ceres::AutoDiffCostFunction<DiffRotorHepGAFunctor, 3, 1, 3>(\n      new DiffRotorHepGAFunctor())\n      .Evaluate(parameters, static_cast<double *>(buf_res.ptr), jacobians);\n\n  py::list list;\n  list.append(py_array_result);\n  list.append(py_array_jac);\n\n  return list;\n}\nstruct DiffRotorGaalopFunctor {\n  template <typename T>\n  bool operator()(const T *th, const T *a, T *b) const {\n    b[0] = (-(a[0] * sin(th[0] / 2.0) * sin(th[0] / 2.0))) -\n           2.0 * a[1] * cos(th[0] / 2.0) * sin(th[0] / 2.0) +\n           a[0] * cos(th[0] / 2.0) * cos(th[0] / 2.0); // e1\n    b[1] = (-(a[1] * sin(th[0] / 2.0) * sin(th[0] / 2.0))) +\n           2.0 * a[0] * cos(th[0] / 2.0) * sin(th[0] / 2.0) +\n           a[1] * cos(th[0] / 2.0) * cos(th[0] / 2.0); // e2\n    b[2] = a[2] * sin(th[0] / 2.0) * sin(th[0] / 2.0) +\n           a[2] * cos(th[0] / 2.0) * cos(th[0] / 2.0); // e3\n    return true;\n  }\n};\n\npy::list CeresDiffRotorGaalop(const double theta, const Vec &a) {\n  auto py_array_jac = py::array(py::buffer_info(\n      nullptr, sizeof(double), py::format_descriptor<double>::value(), 2,\n      {3, 1}, {sizeof(double), sizeof(double)}));\n\n  auto py_array_result = py::array(py::buffer_info(\n      nullptr, sizeof(double), py::format_descriptor<double>::value(), 2,\n      {3, 1}, {sizeof(double), sizeof(double)}));\n\n  auto buf_jac = py_array_jac.request();\n  auto buf_res = py_array_result.request();\n\n  const double *parameters[2] = {&theta, a.begin()};\n  double *jacobians[2] = {static_cast<double *>(buf_jac.ptr), nullptr};\n\n  ceres::AutoDiffCostFunction<DiffRotorGaalopFunctor, 3, 1, 3>(\n      new DiffRotorGaalopFunctor())\n      .Evaluate(parameters, static_cast<double *>(buf_res.ptr), jacobians);\n\n  py::list list;\n  list.append(py_array_result);\n  list.append(py_array_jac);\n\n  return list;\n}\n\nPYBIND11_PLUGIN(autodiff_multivector) {\n  py::module m(\"autodiff_multivector\", \"autodiff_multivector\");\n  m.def(\"diff_adept\", &AdeptDiffInnerProductVectorBivector);\n  m.def(\"diff_ceres\", &CeresDiffInnerProductVectorBivector);\n  m.def(\"diff_ceres2\", &CeresDiffInnerProductVectorVector);\n  m.def(\"diff_ceres_rotor_versor\", &CeresDiffRotorVersor);\n  m.def(\"diff_adept_rotor_versor_forward\", &AdeptDiffRotorVersorForward);\n  m.def(\"diff_adept_rotor_versor_reverse\", &AdeptDiffRotorVersorReverse);\n  m.def(\"diff_ceres_rotor_matrix\", &CeresDiffRotorMatrix);\n  m.def(\"diff_adept_rotor_matrix_forward\", &AdeptDiffRotorMatrixForward);\n  m.def(\"diff_adept_rotor_matrix_reverse\", &AdeptDiffRotorMatrixReverse);\n  m.def(\"diff_ceres_rotor_hepga\", &CeresDiffRotorHepGA);\n  m.def(\"diff_ceres_rotor_gaalop\", &CeresDiffRotorGaalop);\n  m.def(\"diff_adept_rotor_hepga_forward\", &AdeptDiffRotorHepGAForward);\n  m.def(\"diff_adept_rotor_hepga_reverse\", &AdeptDiffRotorHepGAReverse);\n  return m.ptr();\n}\n", "meta": {"hexsha": "13bcb2a2f65f590c6d0dc7396556937201113a2b", "size": 21150, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/autodiff_multivector.cpp", "max_stars_repo_name": "tingelst/game", "max_stars_repo_head_hexsha": "2e9acc1d3052e4135605211a622aa8613ee56949", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2017-07-25T08:15:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-26T23:05:46.000Z", "max_issues_repo_path": "src/autodiff_multivector.cpp", "max_issues_repo_name": "tingelst/game", "max_issues_repo_head_hexsha": "2e9acc1d3052e4135605211a622aa8613ee56949", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-04T09:32:26.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-04T09:41:47.000Z", "max_forks_repo_path": "src/autodiff_multivector.cpp", "max_forks_repo_name": "tingelst/game", "max_forks_repo_head_hexsha": "2e9acc1d3052e4135605211a622aa8613ee56949", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2016-04-12T04:42:33.000Z", "max_forks_repo_forks_event_max_datetime": "2018-02-12T12:56:45.000Z", "avg_line_length": 33.5714285714, "max_line_length": 79, "alphanum_fraction": 0.6516312057, "num_tokens": 6630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.48124109148803573}}
{"text": "#include <GaussIncludes.h>\n#include <FEMIncludes.h>\n#include <Eigen/SparseCholesky>\n\n//Any extra things I need such as constraints\n#include <LoubignacIterations.h>\n#include <ConstraintFixedPoint.h>\n\n//IGL Viewer\n#include <igl/opengl/glfw/Viewer.h>\n#include <igl/opengl/glfw/imgui/ImGuiMenu.h>\n#include <igl/opengl/glfw/imgui/ImGuiHelpers.h>\n#include <imgui/imgui.h>\n#include <igl/readMESH.h>\n#include <igl/jet.h>\n\n//Global variables for UI\nigl::opengl::glfw::Viewer viewer;\n\nusing namespace Gauss;\nusing namespace FEM;\nusing namespace ParticleSystem; //For Force Spring\n\n/* Tetrahedral finite elements */\n//typedef scene\ntypedef PhysicalSystemFEM<double, LinearTet> FEMLinearTets;\ntypedef World<double, std::tuple<FEMLinearTets *>, std::tuple<ForceSpringFEMParticle<double> *>, std::tuple<ConstraintFixedPoint<double> *> > MyWorld;\n\n//This code from libigl boundary_facets.h\nvoid tetsToTriangles(Eigen::MatrixXi &Fout, Eigen::MatrixXi &T) {\n    \n    unsigned int simplex_size = 4;\n    std::vector<std::vector<int> > allF(\n                                        T.rows()*simplex_size,\n                                        std::vector<int>(simplex_size-1));\n    \n    // Gather faces, loop over tets\n    for(int i = 0; i< (int)T.rows();i++)\n    {\n        // get face in correct order\n        allF[i*simplex_size+0][0] = T(i,2);\n        allF[i*simplex_size+0][1] = T(i,3);\n        allF[i*simplex_size+0][2] = T(i,1);\n        // get face in correct order\n        allF[i*simplex_size+1][0] = T(i,3);\n        allF[i*simplex_size+1][1] = T(i,2);\n        allF[i*simplex_size+1][2] = T(i,0);\n        // get face in correct order\n        allF[i*simplex_size+2][0] = T(i,1);\n        allF[i*simplex_size+2][1] = T(i,3);\n        allF[i*simplex_size+2][2] = T(i,0);\n        // get face in correct order\n        allF[i*simplex_size+3][0] = T(i,2);\n        allF[i*simplex_size+3][1] = T(i,1);\n        allF[i*simplex_size+3][2] = T(i,0);\n    }\n    \n    Fout.resize(allF.size(), simplex_size-1);\n    for(unsigned int ii=0; ii<allF.size(); ++ii) {\n        Fout(ii,0) = allF[ii][0];\n        Fout(ii,1) = allF[ii][1];\n        Fout(ii,2) = allF[ii][2];\n    }\n}\n\nint main(int argc, char **argv) {\n    std::cout<<\"Test Linear FEM \\n\";\n    \n    //Setup Physics\n    MyWorld world;\n    \n    //new code -- load tetgen files\n    \n    Eigen::MatrixXd V;\n    Eigen::MatrixXi T;\n    \n    readTetgen(V, T, dataDir()+\"/meshesTetgen/Beam/Beam.node\", dataDir()+\"/meshesTetgen/Beam/Beam.ele\");\n    \n    Eigen::MatrixXd C;\n    Eigen::MatrixXi F;\n    Eigen::VectorXd s;\n    \n    //Eigen::MatrixXd V(4,3);\n    //Eigen::MatrixXi T(1,4);\n     /*V << 0,0,0,\n     1,0,0,\n     0,1,0,\n     0,0,1;\n     \n    T << 0, 1, 2, 3;*/\n    FEMLinearTets *test = new FEMLinearTets(V,T);\n    world.addSystem(test);\n    world.finalize();\n    \n    auto q = mapStateEigen(world);\n    q.setZero();\n    \n    Eigen::VectorXi indices = minVertices(test, 0);\n    Eigen::SparseMatrix<double> P = fixedPointProjectionMatrix(indices, *test,world);\n    \n    AssemblerEigenSparseMatrix<double> K;\n    AssemblerEigenVector<double> f;\n    \n    getStiffnessMatrix(K, world);\n    getForceVector(f, world);\n    \n    Eigen::SparseMatrix<double> Kp = P*(*K)*P.transpose();\n    Eigen::VectorXd fp = -P*(*f);\n    \n    Eigen::SimplicialLDLT<Eigen::SparseMatrix<double> > solver;\n    solver.compute(Kp);\n\n    if(solver.info()!=Eigen::Success) {\n        // decomposition failed\n        assert(1 == 0);\n        std::cout<<\"Decomposition Failed \\n\";\n        exit(1);\n    }\n    \n    //std::cout<<\"ANSWER: \"<<(P.transpose()*solver.solve(fp)).transpose()<<\"\\n\";\n    mapStateEigen<0>(world) = P.transpose()*solver.solve(fp);\n\n    Eigen::MatrixXd stress;\n    loubignacIterations(stress, (*K), P, world.getState(), (*f), *test, 1e-7);\n    \n    s = stress.rowwise().squaredNorm();\n    \n    tetsToTriangles(F, T);\n    \n    std::cout<<\"Loubignac Iterations: \\n\"<<s.minCoeff()<<\" \"<<s.maxCoeff()<<\"\\n\";\n    igl::jet(s, s.minCoeff(), 100000000000, C);\n    viewer.data().set_mesh(V, F);\n    viewer.data().set_colors(C);\n    viewer.launch();\n    \n}\n\n", "meta": {"hexsha": "ca17fd57323e240a56920cc27a5ef6e1e0f74a99", "size": 4055, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Examples/exampleLoubignac.cpp", "max_stars_repo_name": "rarora7777/GAUSS", "max_stars_repo_head_hexsha": "fa18e913c1e2d89ecd6a088f56255e1895b0285c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-01-14T19:19:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T13:32:48.000Z", "max_issues_repo_path": "src/Examples/exampleLoubignac.cpp", "max_issues_repo_name": "rarora7777/GAUSS", "max_issues_repo_head_hexsha": "fa18e913c1e2d89ecd6a088f56255e1895b0285c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Examples/exampleLoubignac.cpp", "max_forks_repo_name": "rarora7777/GAUSS", "max_forks_repo_head_hexsha": "fa18e913c1e2d89ecd6a088f56255e1895b0285c", "max_forks_repo_licenses": ["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.384057971, "max_line_length": 150, "alphanum_fraction": 0.5970406905, "num_tokens": 1253, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.48113940721507215}}
{"text": "//\n// Created by Sergej Krivonos on 25.02.18.\n//\n#define BOOST_TEST_MODULE Stasis test\n#include <boost/test/unit_test.hpp>\n\n#include \"Variable.h\"\n\n\nusing namespace omnn::math;\nusing namespace boost::unit_test;\nusing namespace std;\n\nBOOST_AUTO_TEST_CASE(Stasis\n                     ,*disabled()\n                     ) // Solve magic square\n{\n    constexpr auto Sz = 5;\n    constexpr auto m = (Sz*(Sz*Sz+1))/2;\n    auto& x = \"x\"_va;\n    auto& y = \"y\"_va;\n    auto& v = \"v\"_va;\n\n    auto at = [&](const Valuable& xx, const Valuable& yy, const Valuable& vv) -> Valuable {\n        return x.Equals(xx).LogicAnd(y.Equals(yy)).LogicAnd(v.Equals(vv));\n    };\n\n    auto world = at(0,0,1);\n\n    auto getat = [&](const Valuable& xx, const Valuable& yy) {\n        /*constexpr*/static Variable t = \"t\"_va;\n        return at(xx,yy,t)(t);\n    };\n\n    auto sumd0 = 0_v, sumd1 = 0_v;\n    Valuable::optimizations = {};\n    for (auto xx=Sz; xx--;) {\n        auto sumx=0_v, sumy=0_v;\n        for (auto yy=Sz; yy--; ) {\n            sumx += getat(xx,yy);\n            sumy += getat(xx,yy);\n        }\n        world += sumx.Equals(m).sq();\n        world += sumy.Equals(m).sq();\n        sumd0 += getat(xx,xx);\n        sumd1 += getat(Sz-xx, Sz-xx);\n    }\n    world += sumd0.Equals(m).sq();\n    world += sumd1.Equals(m).sq();\n\n    for (auto xx=Sz; xx--;) {\n        for (auto yy=Sz; yy--; ) {\n            auto co = world;\n            co.eval({{x,xx},{y,yy}});\n            Valuable::optimizations = true;\n            co.optimize();\n            co.SetView(Valuable::View::Solving);\n            co.optimize();\n            Valuable::optimizations = {};\n            auto s = co(v);\n            if (!s.IsInt()\n//                s.size()!=1\n                ) {\n                IMPLEMENT\n            }else{\n                std::cout\n                    << s\n//                    << *s.begin()\n                    << ' ';\n            }\n        }\n        std::cout << std::endl;\n    }\n}\n\nBOOST_AUTO_TEST_CASE(Stasis_empty_test){} // to success end if all tests disabled\n", "meta": {"hexsha": "ce4520bcf93b56de35d69baaf3cb383bb3ee3f1d", "size": 2031, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "omnn/math/test/Stasis.cpp", "max_stars_repo_name": "ApusDT/openmind", "max_stars_repo_head_hexsha": "9d106248c79a37d19e0da894acbecd1493d4240f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-25T06:47:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-25T06:47:44.000Z", "max_issues_repo_path": "omnn/math/test/Stasis.cpp", "max_issues_repo_name": "leannejdong/openmind", "max_issues_repo_head_hexsha": "69af704c420ffa89100ecd3709ad9ff39ee4da05", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "omnn/math/test/Stasis.cpp", "max_forks_repo_name": "leannejdong/openmind", "max_forks_repo_head_hexsha": "69af704c420ffa89100ecd3709ad9ff39ee4da05", "max_forks_repo_licenses": ["BSD-3-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.3766233766, "max_line_length": 91, "alphanum_fraction": 0.4839980305, "num_tokens": 562, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.48109943550241796}}
{"text": "/* test_binomial.cpp\n *\n * Copyright Steven Watanabe 2010\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: test_binomial.cpp 71018 2011-04-05 21:27:52Z steven_watanabe $\n *\n */\n\n#include <boost/random/binomial_distribution.hpp>\n#include <boost/random/uniform_int.hpp>\n#include <boost/random/uniform_01.hpp>\n#include <boost/math/distributions/binomial.hpp>\n\n#define BOOST_RANDOM_DISTRIBUTION boost::random::binomial_distribution<>\n#define BOOST_RANDOM_DISTRIBUTION_NAME binomial\n#define BOOST_MATH_DISTRIBUTION boost::math::binomial\n#define BOOST_RANDOM_ARG1_TYPE int\n#define BOOST_RANDOM_ARG1_NAME n\n#define BOOST_RANDOM_ARG1_DEFAULT 100000\n#define BOOST_RANDOM_ARG1_DISTRIBUTION(n) boost::uniform_int<>(0, n)\n#define BOOST_RANDOM_ARG2_TYPE double\n#define BOOST_RANDOM_ARG2_NAME p\n#define BOOST_RANDOM_ARG2_DEFAULT 1000.0\n#define BOOST_RANDOM_ARG2_DISTRIBUTION(n) boost::uniform_01<>()\n#define BOOST_RANDOM_DISTRIBUTION_MAX n\n\n#include \"test_real_distribution.ipp\"\n", "meta": {"hexsha": "44553afb7f596834d85341b6eb1a0a2009ea4dd6", "size": 1083, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/random/test/test_binomial.cpp", "max_stars_repo_name": "ai-nikolaev/repo-cppboost", "max_stars_repo_head_hexsha": "218c4a977c6d8cd6f2864cdcea1b6ab53160d203", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2016-04-12T16:29:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-28T11:01:57.000Z", "max_issues_repo_path": "libs/random/test/test_binomial.cpp", "max_issues_repo_name": "ai-nikolaev/repo-cppboost", "max_issues_repo_head_hexsha": "218c4a977c6d8cd6f2864cdcea1b6ab53160d203", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-10-31T19:35:14.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-04T17:11:27.000Z", "max_forks_repo_path": "libs/random/test/test_binomial.cpp", "max_forks_repo_name": "ai-nikolaev/repo-cppboost", "max_forks_repo_head_hexsha": "218c4a977c6d8cd6f2864cdcea1b6ab53160d203", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-09-09T02:38:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-30T00:24:24.000Z", "avg_line_length": 34.935483871, "max_line_length": 72, "alphanum_fraction": 0.8153277932, "num_tokens": 276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4810638143402286}}
{"text": "#include <qubus/performance_models/symbolic_regression.hpp>\n\n#include <Eigen/Core>\n#include <unsupported/Eigen/NonLinearOptimization>\n\n#include <boost/circular_buffer.hpp>\n#include <boost/range/adaptor/transformed.hpp>\n#include <boost/range/irange.hpp>\n\n#include <qubus/util/assert.hpp>\n#include <qubus/util/integers.hpp>\n#include <qubus/util/unused.hpp>\n\n#include <algorithm>\n#include <array>\n#include <cmath>\n#include <cstdint>\n#include <functional>\n#include <iterator>\n#include <limits>\n#include <random>\n#include <stack>\n#include <string>\n#include <unordered_map>\n#include <utility>\n\nnamespace qubus\n{\n\nnamespace\n{\n\n#ifndef __GNUC__\nclass compiled_expression\n{\npublic:\n    static constexpr std::size_t stack_size = 40;\n\n    using bytecode_unit_t = std::uint8_t;\n\n    enum opcode : bytecode_unit_t\n    {\n        add,\n        sub,\n        mul,\n        div,\n        exp,\n        log,\n        push,\n        push_param,\n        push_arg,\n        kronecker,\n        quot_rule,\n        prod_rule,\n        halt\n    };\n\n    compiled_expression() = default;\n\n    explicit compiled_expression(std::vector<bytecode_unit_t> bytecode_)\n    : bytecode_(std::move(bytecode_))\n    {\n    }\n\n    double operator()(const Eigen::VectorXd& parameters, const std::vector<double>& arguments,\n                      long int diff_index) const\n    {\n        std::array<double, stack_size> stack;\n\n        std::int64_t sp = 0;\n        std::int64_t pc = 0;\n\n        for (;;)\n        {\n            opcode op;\n            static_assert(sizeof(opcode) == sizeof(bytecode_unit_t),\n                          \"Unexpected size of bytecode unit.\");\n            std::memcpy(&op, &bytecode_[pc++], sizeof(opcode));\n\n            switch (op)\n            {\n            case opcode::push:\n            {\n                static_assert(sizeof(double) == 8 * sizeof(bytecode_unit_t),\n                              \"Unexpected size of bytecode unit.\");\n\n                double value;\n                std::memcpy(&value, &bytecode_[pc], sizeof(double));\n                pc += 8;\n\n                stack[sp++] = value;\n                break;\n            }\n            case opcode::push_param:\n            {\n                static_assert(sizeof(long int) == 8 * sizeof(bytecode_unit_t),\n                              \"Unexpected size of bytecode unit.\");\n\n                long int index;\n                std::memcpy(&index, &bytecode_[pc], sizeof(long int));\n                pc += 8;\n\n                stack[sp++] = parameters(index);\n                break;\n            }\n            case opcode::push_arg:\n            {\n                static_assert(sizeof(long int) == 8 * sizeof(bytecode_unit_t),\n                              \"Unexpected size of bytecode unit.\");\n\n                long int index;\n                std::memcpy(&index, &bytecode_[pc], sizeof(long int));\n                pc += 8;\n\n                stack[sp++] = arguments[index];\n                break;\n            }\n            case opcode::add:\n                stack[sp - 2] = stack[sp - 2] + stack[sp - 1];\n                --sp;\n                break;\n            case opcode::sub:\n                stack[sp - 2] = stack[sp - 2] - stack[sp - 1];\n                --sp;\n                break;\n            case opcode::mul:\n                stack[sp - 2] = stack[sp - 2] * stack[sp - 1];\n                --sp;\n                break;\n            case opcode::div:\n                stack[sp - 2] = stack[sp - 2] / stack[sp - 1];\n                --sp;\n                break;\n            case opcode::exp:\n                stack[sp - 1] = std::exp(stack[sp - 1]);\n                break;\n            case opcode::log:\n                stack[sp - 1] = std::log(stack[sp - 1]);\n                break;\n            case opcode::kronecker:\n            {\n                static_assert(sizeof(long int) == 8 * sizeof(bytecode_unit_t),\n                              \"Unexpected size of bytecode unit.\");\n\n                long int index;\n                std::memcpy(&index, &bytecode_[pc], sizeof(long int));\n                pc += 8;\n\n                stack[sp++] = index == diff_index ? 1.0 : 0.0;\n                break;\n            }\n            case opcode::quot_rule:\n            {\n                auto lhs = stack[sp - 4];\n                auto rhs = stack[sp - 3];\n\n                auto lhs_diff = stack[sp - 2];\n                auto rhs_diff = stack[sp - 1];\n\n                stack[sp - 4] = (rhs * lhs_diff - lhs * rhs_diff) / (rhs * rhs);\n\n                sp -= 3;\n                break;\n            }\n            case opcode::prod_rule:\n            {\n                auto lhs = stack[sp - 4];\n                auto rhs = stack[sp - 3];\n\n                auto lhs_diff = stack[sp - 2];\n                auto rhs_diff = stack[sp - 1];\n\n                stack[sp - 4] = lhs * rhs_diff + lhs_diff * rhs;\n\n                sp -= 3;\n                break;\n            }\n            case opcode::halt:\n                return stack[sp - 1];\n            default:\n                QUBUS_UNREACHABLE_BECAUSE(\"Invalid opcode.\");\n            }\n        }\n    }\n\nprivate:\n    std::vector<bytecode_unit_t> bytecode_;\n};\n#else\nclass compiled_expression\n{\npublic:\n    static constexpr std::size_t stack_size = 40;\n\n    using bytecode_unit_t = std::uint8_t;\n\n    enum opcode : bytecode_unit_t\n    {\n        add,\n        sub,\n        mul,\n        div,\n        exp,\n        log,\n        push,\n        push_param,\n        push_arg,\n        kronecker,\n        quot_rule,\n        prod_rule,\n        halt\n    };\n\n    compiled_expression() = default;\n\n    explicit compiled_expression(std::vector<bytecode_unit_t> bytecode_)\n    : bytecode_(std::move(bytecode_))\n    {\n    }\n\n    double operator()(const Eigen::VectorXd& parameters, const std::vector<double>& arguments,\n                      long int diff_index) const\n    {\n        static constexpr void* dispatch_table[] = {\n            &&do_add,       &&do_sub,       &&do_mul,        &&do_div,      &&do_exp,\n            &&do_log,       &&do_push,      &&do_push_param, &&do_push_arg, &&do_kronecker,\n            &&do_quot_rule, &&do_prod_rule, &&do_halt};\n\n        std::array<double, stack_size> stack;\n\n        std::int64_t sp = 0;\n        std::int64_t pc = 0;\n\n        goto* dispatch_table[next_opcode(pc)];\n\n        {\n        do_push:\n        {\n            static_assert(sizeof(double) == 8 * sizeof(bytecode_unit_t),\n                          \"Unexpected size of bytecode unit.\");\n\n            double value;\n            std::memcpy(&value, &bytecode_[pc], sizeof(double));\n            pc += 8;\n\n            stack[sp++] = value;\n            goto* dispatch_table[next_opcode(pc)];\n        }\n        do_push_param:\n        {\n            static_assert(sizeof(long int) == 8 * sizeof(bytecode_unit_t),\n                          \"Unexpected size of bytecode unit.\");\n\n            long int index;\n            std::memcpy(&index, &bytecode_[pc], sizeof(long int));\n            pc += 8;\n\n            stack[sp++] = parameters(index);\n            goto* dispatch_table[next_opcode(pc)];\n        }\n        do_push_arg:\n        {\n            static_assert(sizeof(long int) == 8 * sizeof(bytecode_unit_t),\n                          \"Unexpected size of bytecode unit.\");\n\n            long int index;\n            std::memcpy(&index, &bytecode_[pc], sizeof(long int));\n            pc += 8;\n\n            stack[sp++] = arguments[index];\n            goto* dispatch_table[next_opcode(pc)];\n        }\n        do_add:\n            stack[sp - 2] = stack[sp - 2] + stack[sp - 1];\n            --sp;\n            goto* dispatch_table[next_opcode(pc)];\n        do_sub:\n            stack[sp - 2] = stack[sp - 2] - stack[sp - 1];\n            --sp;\n            goto* dispatch_table[next_opcode(pc)];\n        do_mul:\n            stack[sp - 2] = stack[sp - 2] * stack[sp - 1];\n            --sp;\n            goto* dispatch_table[next_opcode(pc)];\n        do_div:\n            stack[sp - 2] = stack[sp - 2] / stack[sp - 1];\n            --sp;\n            goto* dispatch_table[next_opcode(pc)];\n        do_exp:\n            stack[sp - 1] = std::exp(stack[sp - 1]);\n            goto* dispatch_table[next_opcode(pc)];\n        do_log:\n            stack[sp - 1] = std::log(stack[sp - 1]);\n            goto* dispatch_table[next_opcode(pc)];\n        do_kronecker:\n        {\n            static_assert(sizeof(long int) == 8 * sizeof(bytecode_unit_t),\n                          \"Unexpected size of bytecode unit.\");\n\n            long int index;\n            std::memcpy(&index, &bytecode_[pc], sizeof(long int));\n            pc += 8;\n\n            stack[sp++] = index == diff_index ? 1.0 : 0.0;\n            goto* dispatch_table[next_opcode(pc)];\n        }\n        do_quot_rule:\n        {\n            auto lhs = stack[sp - 4];\n            auto rhs = stack[sp - 3];\n\n            auto lhs_diff = stack[sp - 2];\n            auto rhs_diff = stack[sp - 1];\n\n            stack[sp - 4] = (rhs * lhs_diff - lhs * rhs_diff) / (rhs * rhs);\n\n            sp -= 3;\n            goto* dispatch_table[next_opcode(pc)];\n        }\n        do_prod_rule:\n        {\n            auto lhs = stack[sp - 4];\n            auto rhs = stack[sp - 3];\n\n            auto lhs_diff = stack[sp - 2];\n            auto rhs_diff = stack[sp - 1];\n\n            stack[sp - 4] = lhs * rhs_diff + lhs_diff * rhs;\n\n            sp -= 3;\n            goto* dispatch_table[next_opcode(pc)];\n        }\n        do_halt:\n            return stack[sp - 1];\n        }\n    }\n\nprivate:\n    opcode next_opcode(std::int64_t& pc) const\n    {\n        opcode op;\n        static_assert(sizeof(opcode) == sizeof(bytecode_unit_t),\n                      \"Unexpected size of bytecode unit.\");\n        std::memcpy(&op, &bytecode_[pc++], sizeof(opcode));\n\n        return op;\n    }\n\n    std::vector<bytecode_unit_t> bytecode_;\n};\n#endif\n\nclass model_expression\n{\npublic:\n    model_expression() = default;\n    virtual ~model_expression() = default;\n\n    model_expression(const model_expression&) = delete;\n    model_expression& operator=(const model_expression&) = delete;\n\n    model_expression(model_expression&&) = delete;\n    model_expression& operator=(model_expression&&) = delete;\n\n    virtual long int arity() const = 0;\n    virtual const model_expression& child(long int index) const = 0;\n    virtual model_expression& child(long int index) = 0;\n\n    auto children() const\n    {\n        return boost::irange<long int>(0, this->arity()) |\n               boost::adaptors::transformed(\n                   [this](long int index) -> decltype(auto) { return this->child(index); });\n    }\n\n    auto children()\n    {\n        return boost::irange<long int>(0, this->arity()) |\n               boost::adaptors::transformed(\n                   [this](long int index) -> decltype(auto) { return this->child(index); });\n    }\n\n    model_expression* parent() const\n    {\n        return parent_;\n    }\n\n    void set_parent(model_expression& parent)\n    {\n        parent_ = &parent;\n    }\n\n    virtual std::unique_ptr<model_expression> clone() const = 0;\n\n    virtual void substitute_child(const model_expression& old_child,\n                                  std::unique_ptr<model_expression> new_child) = 0;\n\n    virtual double evaluate(const Eigen::VectorXd& parameters,\n                            const std::vector<double>& arguments) const = 0;\n\n    virtual double df(const Eigen::VectorXd& parameters, const std::vector<double>& arguments,\n                      long int index) const = 0;\n\n    virtual void\n    emit_evaluate_bytecode(std::vector<compiled_expression::bytecode_unit_t>& bytecode) const = 0;\n\n    virtual void\n    emit_df_bytecode(std::vector<compiled_expression::bytecode_unit_t>& bytecode) const = 0;\n\n    virtual std::string dump(const Eigen::VectorXd& parameters) const = 0;\n\nprivate:\n    model_expression* parent_ = nullptr;\n};\n\nstd::unique_ptr<model_expression> clone(const model_expression& expr)\n{\n    return expr.clone();\n}\n\nlong int determine_number_of_expressions(const model_expression& root)\n{\n    long int number_of_expressions = 1;\n\n    for (const auto& child : root.children())\n    {\n        number_of_expressions += determine_number_of_expressions(child);\n    }\n\n    QUBUS_ASSERT(number_of_expressions >= 0, \"The number of expressions should be non-negative.\");\n\n    return number_of_expressions;\n}\n\nlong int determine_number_of_parameters(const model_expression& root);\n\nlong int determine_depth(const model_expression& root)\n{\n    if (root.arity() == 0)\n        return 1;\n\n    long int depth = 1;\n\n    for (const auto& child : root.children())\n    {\n        auto depth_of_child = determine_depth(child);\n\n        depth = std::max(depth, depth_of_child);\n    }\n\n    return depth + 1;\n}\n\nclass binary_operator_expression final : public model_expression\n{\npublic:\n    enum class tag\n    {\n        plus,\n        minus,\n        multiplies,\n        divides\n    };\n\n    explicit binary_operator_expression(tag tag_, std::unique_ptr<model_expression> lhs_,\n                                        std::unique_ptr<model_expression> rhs_)\n    : tag_(tag_), lhs_(std::move(lhs_)), rhs_(std::move(rhs_))\n    {\n        this->lhs_->set_parent(*this);\n        this->rhs_->set_parent(*this);\n    }\n\n    long int arity() const override\n    {\n        return 2;\n    }\n\n    const model_expression& child(long int index) const override\n    {\n        QUBUS_ASSERT(0 <= index && index < 2, \"Invalid child index.\");\n\n        switch (index)\n        {\n        case 0:\n            return *lhs_;\n        case 1:\n            return *rhs_;\n        default:\n            QUBUS_UNREACHABLE_BECAUSE(\"Invalid child index.\");\n        }\n    }\n\n    model_expression& child(long int index) override\n    {\n        QUBUS_ASSERT(0 <= index && index < 2, \"Invalid child index.\");\n\n        switch (index)\n        {\n        case 0:\n            return *lhs_;\n        case 1:\n            return *rhs_;\n        default:\n            QUBUS_UNREACHABLE_BECAUSE(\"Invalid child index.\");\n        }\n    }\n\n    std::unique_ptr<model_expression> clone() const override\n    {\n        return std::make_unique<binary_operator_expression>(tag_, lhs_->clone(), rhs_->clone());\n    }\n\n    void substitute_child(const model_expression& old_child,\n                          std::unique_ptr<model_expression> new_child) override\n    {\n        if (&old_child == lhs_.get())\n        {\n            lhs_ = std::move(new_child);\n            lhs_->set_parent(*this);\n        }\n        else if (&old_child == rhs_.get())\n        {\n            rhs_ = std::move(new_child);\n            rhs_->set_parent(*this);\n        }\n        else\n        {\n            QUBUS_UNREACHABLE_BECAUSE(\"old_child is not a child of this node.\");\n        }\n    }\n\n    double evaluate(const Eigen::VectorXd& parameters,\n                    const std::vector<double>& arguments) const override\n    {\n        switch (tag_)\n        {\n        case tag::plus:\n            return lhs_->evaluate(parameters, arguments) + rhs_->evaluate(parameters, arguments);\n        case tag::minus:\n            return lhs_->evaluate(parameters, arguments) - rhs_->evaluate(parameters, arguments);\n        case tag::multiplies:\n            return lhs_->evaluate(parameters, arguments) * rhs_->evaluate(parameters, arguments);\n        case tag::divides:\n            return lhs_->evaluate(parameters, arguments) / rhs_->evaluate(parameters, arguments);\n        }\n    }\n\n    double df(const Eigen::VectorXd& parameters, const std::vector<double>& arguments,\n              long int index) const override\n    {\n        switch (tag_)\n        {\n        case tag::plus:\n            return lhs_->df(parameters, arguments, index) + rhs_->df(parameters, arguments, index);\n        case tag::minus:\n            return lhs_->df(parameters, arguments, index) - rhs_->df(parameters, arguments, index);\n        case tag::multiplies:\n            return lhs_->df(parameters, arguments, index) * rhs_->evaluate(parameters, arguments) +\n                   lhs_->evaluate(parameters, arguments) * rhs_->df(parameters, arguments, index);\n        case tag::divides:\n        {\n            auto lhs_result = rhs_->evaluate(parameters, arguments);\n            auto rhs_result = rhs_->evaluate(parameters, arguments);\n\n            return (lhs_->df(parameters, arguments, index) * rhs_result -\n                    lhs_result * rhs_->df(parameters, arguments, index)) /\n                   (rhs_result * rhs_result);\n        }\n        }\n    }\n\n    void emit_evaluate_bytecode(\n        std::vector<compiled_expression::bytecode_unit_t>& bytecode) const override\n    {\n        lhs_->emit_evaluate_bytecode(bytecode);\n        rhs_->emit_evaluate_bytecode(bytecode);\n\n        switch (tag_)\n        {\n        case tag::plus:\n            bytecode.push_back(compiled_expression::opcode::add);\n            return;\n        case tag::minus:\n            bytecode.push_back(compiled_expression::opcode::sub);\n            return;\n        case tag::multiplies:\n            bytecode.push_back(compiled_expression::opcode::mul);\n            return;\n        case tag::divides:\n            bytecode.push_back(compiled_expression::opcode::div);\n            return;\n        }\n    }\n\n    void\n    emit_df_bytecode(std::vector<compiled_expression::bytecode_unit_t>& bytecode) const override\n    {\n        switch (tag_)\n        {\n        case tag::plus:\n            lhs_->emit_df_bytecode(bytecode);\n            rhs_->emit_df_bytecode(bytecode);\n\n            bytecode.push_back(compiled_expression::opcode::add);\n            break;\n        case tag::minus:\n            lhs_->emit_df_bytecode(bytecode);\n            rhs_->emit_df_bytecode(bytecode);\n\n            bytecode.push_back(compiled_expression::opcode::sub);\n            break;\n        case tag::multiplies:\n            lhs_->emit_evaluate_bytecode(bytecode);\n            rhs_->emit_evaluate_bytecode(bytecode);\n\n            lhs_->emit_df_bytecode(bytecode);\n            rhs_->emit_df_bytecode(bytecode);\n\n            bytecode.push_back(compiled_expression::opcode::prod_rule);\n            break;\n        case tag::divides:\n            lhs_->emit_evaluate_bytecode(bytecode);\n            rhs_->emit_evaluate_bytecode(bytecode);\n\n            lhs_->emit_df_bytecode(bytecode);\n            rhs_->emit_df_bytecode(bytecode);\n\n            bytecode.push_back(compiled_expression::opcode::quot_rule);\n\n            break;\n        }\n    }\n\n    std::string dump(const Eigen::VectorXd& parameters) const override\n    {\n        switch (tag_)\n        {\n        case tag::plus:\n            return \"(\" + lhs_->dump(parameters) + \" + \" + rhs_->dump(parameters) + \")\";\n        case tag::minus:\n            return \"(\" + lhs_->dump(parameters) + \" - \" + rhs_->dump(parameters) + \")\";\n        case tag::multiplies:\n            return \"(\" + lhs_->dump(parameters) + \" * \" + rhs_->dump(parameters) + \")\";\n        case tag::divides:\n            return \"(\" + lhs_->dump(parameters) + \" / \" + rhs_->dump(parameters) + \")\";\n        }\n    }\n\nprivate:\n    tag tag_;\n    std::unique_ptr<model_expression> lhs_;\n    std::unique_ptr<model_expression> rhs_;\n};\n\nclass function_expression final : public model_expression\n{\npublic:\n    enum class tag\n    {\n        exp,\n        log\n    };\n\n    explicit function_expression(tag tag_, std::unique_ptr<model_expression> arg_)\n    : tag_(tag_), arg_(std::move(arg_))\n    {\n        this->arg_->set_parent(*this);\n    }\n\n    long int arity() const override\n    {\n        return 1;\n    }\n\n    const model_expression& child(long int index) const override\n    {\n        QUBUS_ASSERT(0 <= index && index < 1, \"Invalid child index.\");\n\n        switch (index)\n        {\n        case 0:\n            return *arg_;\n        default:\n            QUBUS_UNREACHABLE_BECAUSE(\"Invalid child index.\");\n        }\n    }\n\n    model_expression& child(long int index) override\n    {\n        QUBUS_ASSERT(0 <= index && index < 1, \"Invalid child index.\");\n\n        switch (index)\n        {\n        case 0:\n            return *arg_;\n        default:\n            QUBUS_UNREACHABLE_BECAUSE(\"Invalid child index.\");\n        }\n    }\n\n    std::unique_ptr<model_expression> clone() const override\n    {\n        return std::make_unique<function_expression>(tag_, arg_->clone());\n    }\n\n    void substitute_child(const model_expression& old_child,\n                          std::unique_ptr<model_expression> new_child) override\n    {\n        if (&old_child == arg_.get())\n        {\n            arg_ = std::move(new_child);\n            arg_->set_parent(*this);\n        }\n        else\n        {\n            QUBUS_UNREACHABLE_BECAUSE(\"old_child is not a child of this node.\");\n        }\n    }\n\n    double evaluate(const Eigen::VectorXd& parameters,\n                    const std::vector<double>& arguments) const override\n    {\n        switch (tag_)\n        {\n        case tag::exp:\n            return std::exp(arg_->evaluate(parameters, arguments));\n        case tag::log:\n            return std::log(arg_->evaluate(parameters, arguments));\n        }\n    }\n\n    double df(const Eigen::VectorXd& parameters, const std::vector<double>& arguments,\n              long int index) const override\n    {\n        switch (tag_)\n        {\n        case tag::exp:\n            return std::exp(arg_->evaluate(parameters, arguments)) *\n                   arg_->df(parameters, arguments, index);\n        case tag::log:\n            return arg_->df(parameters, arguments, index) / arg_->evaluate(parameters, arguments);\n        }\n    }\n\n    void emit_evaluate_bytecode(\n        std::vector<compiled_expression::bytecode_unit_t>& bytecode) const override\n    {\n        arg_->emit_evaluate_bytecode(bytecode);\n\n        switch (tag_)\n        {\n        case tag::exp:\n            bytecode.push_back(compiled_expression::opcode::exp);\n            return;\n        case tag::log:\n            bytecode.push_back(compiled_expression::opcode::log);\n            return;\n        }\n    }\n\n    void\n    emit_df_bytecode(std::vector<compiled_expression::bytecode_unit_t>& bytecode) const override\n    {\n        switch (tag_)\n        {\n        case tag::exp:\n            arg_->emit_evaluate_bytecode(bytecode);\n            bytecode.push_back(compiled_expression::opcode::exp);\n\n            arg_->emit_df_bytecode(bytecode);\n\n            bytecode.push_back(compiled_expression::opcode::mul);\n            return;\n        case tag::log:\n            arg_->emit_df_bytecode(bytecode);\n            arg_->emit_evaluate_bytecode(bytecode);\n\n            bytecode.push_back(compiled_expression::opcode::div);\n            return;\n        }\n    }\n\n    std::string dump(const Eigen::VectorXd& parameters) const override\n    {\n        switch (tag_)\n        {\n        case tag::exp:\n            return \"exp(\" + arg_->dump(parameters) + \")\";\n        case tag::log:\n            return \"log(\" + arg_->dump(parameters) + \")\";\n        }\n    }\n\nprivate:\n    tag tag_;\n    std::unique_ptr<model_expression> arg_;\n};\n\nclass parameter_expression final : public model_expression\n{\npublic:\n    explicit parameter_expression(long int index_) : index_(std::move(index_))\n    {\n        QUBUS_ASSERT(this->index_ >= 0, \"Invalid index.\");\n    }\n\n    long int arity() const override\n    {\n        return 0;\n    }\n\n    const model_expression& child(long int index) const override\n    {\n        QUBUS_UNREACHABLE_BECAUSE(\"Invalid child index.\");\n    }\n\n    model_expression& child(long int index) override\n    {\n        QUBUS_UNREACHABLE_BECAUSE(\"Invalid child index.\");\n    }\n\n    std::unique_ptr<model_expression> clone() const override\n    {\n        return std::make_unique<parameter_expression>(index_);\n    }\n\n    void substitute_child(const model_expression& QUBUS_UNUSED(old_child),\n                          std::unique_ptr<model_expression> QUBUS_UNUSED(new_child)) override\n    {\n        QUBUS_UNREACHABLE_BECAUSE(\"old_child is not a child of this node.\");\n    }\n\n    long int index() const\n    {\n        return index_;\n    }\n\n    void set_index(long int index)\n    {\n        index_ = index;\n    }\n\n    double evaluate(const Eigen::VectorXd& parameters,\n                    const std::vector<double>& QUBUS_UNUSED(arguments)) const override\n    {\n        QUBUS_ASSERT(index_ < parameters.size(), \"Invalid index.\");\n\n        return parameters(util::integer_cast<Eigen::Index>(index_));\n    }\n\n    double df(const Eigen::VectorXd& QUBUS_UNUSED(parameters),\n              const std::vector<double>& QUBUS_UNUSED(arguments), long int index) const override\n    {\n        return index_ == index ? 1.0 : 0.0;\n    }\n\n    void emit_evaluate_bytecode(\n        std::vector<compiled_expression::bytecode_unit_t>& bytecode) const override\n    {\n        bytecode.push_back(compiled_expression::opcode::push_param);\n\n        compiled_expression::bytecode_unit_t data[8];\n\n        static_assert(sizeof(long int) == 8 * sizeof(compiled_expression::bytecode_unit_t),\n                      \"Unexpected size of bytecode unit.\");\n        std::memcpy(&data, &index_, sizeof(long int));\n\n        for (std::size_t i = 0; i < 8; ++i)\n        {\n            bytecode.push_back(data[i]);\n        }\n    }\n\n    void\n    emit_df_bytecode(std::vector<compiled_expression::bytecode_unit_t>& bytecode) const override\n    {\n        bytecode.push_back(compiled_expression::opcode::kronecker);\n\n        compiled_expression::bytecode_unit_t data[8];\n\n        static_assert(sizeof(long int) == 8 * sizeof(compiled_expression::bytecode_unit_t),\n                      \"Unexpected size of bytecode unit.\");\n        std::memcpy(&data, &index_, sizeof(long int));\n\n        for (std::size_t i = 0; i < 8; ++i)\n        {\n            bytecode.push_back(data[i]);\n        }\n    }\n\n    std::string dump(const Eigen::VectorXd& parameters) const override\n    {\n        QUBUS_ASSERT(index_ < parameters.size(), \"Invalid index.\");\n\n        return std::to_string(parameters(util::integer_cast<Eigen::Index>(index_)));\n    }\n\nprivate:\n    long int index_;\n};\n\nclass variable_expression final : public model_expression\n{\npublic:\n    explicit variable_expression(long int index_) : index_(std::move(index_))\n    {\n        QUBUS_ASSERT(this->index_ >= 0, \"Invalid index.\");\n    }\n\n    long int arity() const override\n    {\n        return 0;\n    }\n\n    const model_expression& child(long int index) const override\n    {\n        QUBUS_UNREACHABLE_BECAUSE(\"Invalid child index.\");\n    }\n\n    model_expression& child(long int index) override\n    {\n        QUBUS_UNREACHABLE_BECAUSE(\"Invalid child index.\");\n    }\n\n    std::unique_ptr<model_expression> clone() const override\n    {\n        return std::make_unique<variable_expression>(index_);\n    }\n\n    void substitute_child(const model_expression& QUBUS_UNUSED(old_child),\n                          std::unique_ptr<model_expression> QUBUS_UNUSED(new_child)) override\n    {\n        QUBUS_UNREACHABLE_BECAUSE(\"old_child is not a child of this node.\");\n    }\n\n    double evaluate(const Eigen::VectorXd& QUBUS_UNUSED(parameters),\n                    const std::vector<double>& arguments) const override\n    {\n        QUBUS_ASSERT(index_ < arguments.size(), \"Invalid index.\");\n\n        return arguments[util::integer_cast<std::size_t>(index_)];\n    }\n\n    double df(const Eigen::VectorXd& QUBUS_UNUSED(parameters),\n              const std::vector<double>& QUBUS_UNUSED(arguments),\n              long int QUBUS_UNUSED(index)) const override\n    {\n        return 0.0;\n    }\n\n    void emit_evaluate_bytecode(\n        std::vector<compiled_expression::bytecode_unit_t>& bytecode) const override\n    {\n        bytecode.push_back(compiled_expression::opcode::push_arg);\n\n        compiled_expression::bytecode_unit_t data[8];\n\n        static_assert(sizeof(long int) == 8 * sizeof(compiled_expression::bytecode_unit_t),\n                      \"Unexpected size of bytecode unit.\");\n        std::memcpy(&data, &index_, sizeof(long int));\n\n        for (std::size_t i = 0; i < 8; ++i)\n        {\n            bytecode.push_back(data[i]);\n        }\n    }\n\n    void\n    emit_df_bytecode(std::vector<compiled_expression::bytecode_unit_t>& bytecode) const override\n    {\n        bytecode.push_back(compiled_expression::opcode::push);\n\n        compiled_expression::bytecode_unit_t data[8];\n        const double value = 0.0;\n\n        static_assert(sizeof(double) == 8 * sizeof(compiled_expression::bytecode_unit_t),\n                      \"Unexpected size of bytecode unit.\");\n        std::memcpy(&data, &index_, sizeof(double));\n\n        for (std::size_t i = 0; i < 8; ++i)\n        {\n            bytecode.push_back(data[i]);\n        }\n    }\n\n    std::string dump(const Eigen::VectorXd& QUBUS_UNUSED(parameters)) const override\n    {\n        return \"a\" + std::to_string(index_);\n    }\n\nprivate:\n    long int index_;\n};\n\nlong int determine_number_of_parameters(const model_expression& root)\n{\n    long int number_of_parameters = 0;\n\n    if (auto parameter_expr = dynamic_cast<const parameter_expression*>(&root))\n    {\n        number_of_parameters = parameter_expr->index() + 1;\n    }\n\n    for (const auto& child : root.children())\n    {\n        number_of_parameters =\n            std::max(number_of_parameters, determine_number_of_parameters(child));\n    }\n\n    QUBUS_ASSERT(number_of_parameters >= 0, \"The number of parameters has to be non-negative.\");\n\n    return number_of_parameters;\n}\n\ntemplate <typename Engine>\nstd::unique_ptr<model_expression>\ngenerate_random_expression(Engine& engine, long int number_of_arguments,\n                           long int& number_of_parameters, long int depth = 0)\n{\n    QUBUS_ASSERT(number_of_arguments > 0, \"The expression has to contain at least one argument.\");\n\n    enum expression_type\n    {\n        parameter,\n        variable,\n        plus,\n        minus,\n        multiplies,\n        divides,\n        exp,\n        log,\n        number_of_types\n    };\n\n    std::discrete_distribution<int> type_dist({\n        10, // parameter\n        10, // variable\n        10, // plus\n        10, // minus\n        10, // multiplies\n        10, // divides\n        2,  // exp\n        2   // log\n    });\n\n    std::uniform_int_distribution<long int> parameter_index_dist(0, 2 * number_of_parameters);\n    std::uniform_int_distribution<long int> argument_index_dist(0, number_of_arguments - 1);\n\n    auto r = type_dist(engine);\n\n    if (depth > 2)\n        r = r % 2;\n\n    expression_type type = static_cast<expression_type>(r);\n\n    switch (type)\n    {\n    case parameter:\n    {\n        long int index = parameter_index_dist(engine);\n\n        if (index < number_of_parameters)\n        {\n            return std::make_unique<parameter_expression>(index);\n        }\n        else\n        {\n            long int new_parameter = number_of_parameters;\n\n            ++number_of_parameters;\n\n            return std::make_unique<parameter_expression>(new_parameter);\n        }\n    }\n    case variable:\n    {\n        long int index = argument_index_dist(engine);\n\n        return std::make_unique<variable_expression>(index);\n    }\n    case plus:\n    {\n        auto lhs = generate_random_expression(engine, number_of_arguments, number_of_parameters,\n                                              depth + 1);\n        auto rhs = generate_random_expression(engine, number_of_arguments, number_of_parameters,\n                                              depth + 1);\n\n        return std::make_unique<binary_operator_expression>(binary_operator_expression::tag::plus,\n                                                            std::move(lhs), std::move(rhs));\n    }\n    case minus:\n    {\n        auto lhs = generate_random_expression(engine, number_of_arguments, number_of_parameters,\n                                              depth + 1);\n        auto rhs = generate_random_expression(engine, number_of_arguments, number_of_parameters,\n                                              depth + 1);\n\n        return std::make_unique<binary_operator_expression>(binary_operator_expression::tag::minus,\n                                                            std::move(lhs), std::move(rhs));\n    }\n    case multiplies:\n    {\n        auto lhs = generate_random_expression(engine, number_of_arguments, number_of_parameters,\n                                              depth + 1);\n        auto rhs = generate_random_expression(engine, number_of_arguments, number_of_parameters,\n                                              depth + 1);\n\n        return std::make_unique<binary_operator_expression>(\n            binary_operator_expression::tag::multiplies, std::move(lhs), std::move(rhs));\n    }\n    case divides:\n    {\n        auto lhs = generate_random_expression(engine, number_of_arguments, number_of_parameters,\n                                              depth + 1);\n        auto rhs = generate_random_expression(engine, number_of_arguments, number_of_parameters,\n                                              depth + 1);\n\n        return std::make_unique<binary_operator_expression>(\n            binary_operator_expression::tag::divides, std::move(lhs), std::move(rhs));\n    }\n    case exp:\n    {\n        auto arg = generate_random_expression(engine, number_of_arguments, number_of_parameters,\n                                              depth + 1);\n\n        return std::make_unique<function_expression>(function_expression::tag::exp, std::move(arg));\n    }\n    case log:\n    {\n        auto arg = generate_random_expression(engine, number_of_arguments, number_of_parameters,\n                                              depth + 1);\n\n        return std::make_unique<function_expression>(function_expression::tag::log, std::move(arg));\n    }\n    case number_of_types:\n        QUBUS_UNREACHABLE_BECAUSE(\"number_of_types is not an actual expression type.\");\n    }\n\n    QUBUS_UNREACHABLE();\n}\n\ntemplate <typename Engine>\nconst model_expression& select_random_node(const model_expression& expr, Engine& engine)\n{\n    auto number_of_nodes = determine_number_of_expressions(expr);\n\n    std::uniform_int_distribution<long int> dist(0, number_of_nodes - 1);\n\n    auto number_of_steps = dist(engine);\n\n    std::stack<const model_expression*> node_stack;\n\n    node_stack.push(&expr);\n\n    while (!node_stack.empty())\n    {\n        auto current_node = node_stack.top();\n        node_stack.pop();\n\n        if (number_of_steps == 0)\n            return *current_node;\n\n        --number_of_steps;\n\n        for (const auto& child : current_node->children())\n        {\n            node_stack.push(&child);\n        }\n    }\n\n    QUBUS_UNREACHABLE_BECAUSE(\"The algorithm should have reached the selected node long ago.\");\n}\n\nvoid remove_dead_parameters(model_expression& expr)\n{\n    std::unordered_map<long int, long int> index_map;\n\n    std::stack<model_expression*> node_stack;\n\n    node_stack.push(&expr);\n\n    while (!node_stack.empty())\n    {\n        auto& current_node = *node_stack.top();\n        node_stack.pop();\n\n        if (auto typed_node = dynamic_cast<parameter_expression*>(&current_node))\n        {\n            auto old_index = typed_node->index();\n\n            auto search_result = index_map.find(old_index);\n\n            if (search_result != index_map.end())\n            {\n                typed_node->set_index(search_result->second);\n            }\n            else\n            {\n                auto new_index = util::integer_cast<long int>(index_map.size());\n\n                typed_node->set_index(new_index);\n\n                index_map.emplace(old_index, new_index);\n            }\n        }\n\n        for (auto& child : current_node.children())\n        {\n            node_stack.push(&child);\n        }\n    }\n}\n\ntemplate <typename Engine>\nstd::unique_ptr<model_expression> mutate_expression(const model_expression& expr,\n                                                    long int number_of_arguments,\n                                                    long int number_of_parameters, Engine& engine)\n{\n    auto cloned_expression = clone(expr);\n\n    const auto& random_node = select_random_node(*cloned_expression, engine);\n\n    auto new_sub_tree =\n        generate_random_expression(engine, number_of_arguments, number_of_parameters);\n\n    auto parent = random_node.parent();\n\n    if (!parent)\n        return new_sub_tree;\n\n    parent->substitute_child(random_node, std::move(new_sub_tree));\n\n    remove_dead_parameters(*cloned_expression);\n\n    return cloned_expression;\n}\n\ntemplate <typename Engine>\nstd::unique_ptr<model_expression> mix_expressions(const model_expression& mother,\n                                                  const model_expression& father, Engine& engine)\n{\n    auto cloned_expression = clone(mother);\n\n    const auto& random_node = select_random_node(*cloned_expression, engine);\n\n    auto parent = random_node.parent();\n\n    if (!parent)\n        return clone(father);\n\n    const auto& random_node2 = select_random_node(father, engine);\n\n    parent->substitute_child(random_node, clone(random_node2));\n\n    remove_dead_parameters(*cloned_expression);\n\n    return cloned_expression;\n}\n\ntemplate <typename Engine>\nstd::unique_ptr<model_expression> wrap_expression(const model_expression& expr, Engine& engine)\n{\n    std::uniform_int_distribution<long int> dist(0, 1);\n\n    auto tag = dist(engine);\n\n    switch (tag)\n    {\n    case 0:\n        return std::make_unique<function_expression>(function_expression::tag::exp, clone(expr));\n    case 1:\n        return std::make_unique<function_expression>(function_expression::tag::log, clone(expr));\n    default:\n        QUBUS_UNREACHABLE_BECAUSE(\"No case left.\");\n    }\n}\n\ntemplate <typename Engine>\nstd::unique_ptr<model_expression>\ncombine_expressions(const model_expression& mother, const model_expression& father, Engine& engine)\n{\n    std::uniform_int_distribution<long int> dist(0, 3);\n\n    auto tag = dist(engine);\n\n    switch (tag)\n    {\n    case 0:\n        return std::make_unique<binary_operator_expression>(binary_operator_expression::tag::plus,\n                                                            clone(mother), clone(father));\n    case 1:\n        return std::make_unique<binary_operator_expression>(binary_operator_expression::tag::minus,\n                                                            clone(mother), clone(father));\n    case 2:\n        return std::make_unique<binary_operator_expression>(\n            binary_operator_expression::tag::multiplies, clone(mother), clone(father));\n    case 3:\n        return std::make_unique<binary_operator_expression>(\n            binary_operator_expression::tag::divides, clone(mother), clone(father));\n    default:\n        QUBUS_UNREACHABLE_BECAUSE(\"No case left.\");\n    }\n}\n\nstruct data_point\n{\n    std::vector<double> arguments;\n    std::chrono::microseconds execution_time;\n};\n\ntemplate <typename Dataset>\nclass model\n{\npublic:\n    static constexpr long int max_depth = 20;\n\n    explicit model(std::unique_ptr<model_expression> root_, const Dataset& dataset_)\n    : root_(std::move(root_)),\n      number_of_parameters_(determine_number_of_parameters(*this->root_)),\n      dataset_(&dataset_)\n    {\n        QUBUS_ASSERT(determine_depth(*this->root_) <= max_depth,\n                   \"The depth is larger than expected.\");\n\n        static_assert(max_depth < compiled_expression::stack_size,\n                      \"The size of the stack might not be sufficient.\");\n\n        {\n            std::vector<compiled_expression::bytecode_unit_t> bytecode;\n\n            this->root_->emit_evaluate_bytecode(bytecode);\n\n            bytecode.push_back(compiled_expression::opcode::halt);\n\n            evaluate_ = compiled_expression(std::move(bytecode));\n        }\n\n        {\n            std::vector<compiled_expression::bytecode_unit_t> bytecode;\n\n            this->root_->emit_df_bytecode(bytecode);\n\n            bytecode.push_back(compiled_expression::opcode::halt);\n\n            df_ = compiled_expression(std::move(bytecode));\n        }\n    }\n\n    model(const model& other)\n    : root_(clone(*other.root_)),\n      number_of_parameters_(other.number_of_parameters_),\n      dataset_(other.dataset_),\n      evaluate_(other.evaluate_),\n      df_(other.df_)\n    {\n    }\n\n    model& operator=(const model& other)\n    {\n        root_ = clone(*other.root_);\n        number_of_parameters_ = other.number_of_parameters_;\n        dataset_ = other.dataset_;\n        evaluate_ = other.evaluate_;\n        df_ = other.df_;\n\n        return *this;\n    }\n\n    model(model&& other) noexcept\n    : root_(std::move(other.root_)),\n      number_of_parameters_(std::move(other.number_of_parameters_)),\n      dataset_(other.dataset_),\n      evaluate_(std::move(other.evaluate_)),\n      df_(std::move(other.df_))\n    {\n    }\n\n    model& operator=(model&& other) noexcept\n    {\n        root_ = std::move(other.root_);\n        number_of_parameters_ = std::move(other.number_of_parameters_);\n        dataset_ = other.dataset_;\n        evaluate_ = std::move(other.evaluate_);\n        df_ = std::move(other.df_);\n\n        return *this;\n    }\n\n    const model_expression& expr() const\n    {\n        QUBUS_ASSERT(root_, \"Invalid object.\");\n\n        return *root_;\n    }\n\n    long int number_of_arguments() const\n    {\n        return dataset_->front().arguments.size();\n    }\n\n    long int number_of_parameters() const\n    {\n        return number_of_parameters_;\n    }\n\n    const Dataset& data_set() const\n    {\n        return *dataset_;\n    }\n\n    int values() const\n    {\n        return util::integer_cast<int>(dataset_->size());\n    }\n\n    std::chrono::microseconds query(const Eigen::VectorXd& parameters,\n                                    const std::vector<double>& arguments) const\n    {\n        auto result = root_->evaluate(parameters, arguments);\n\n        using rep = std::chrono::microseconds::rep;\n        double max_value = std::numeric_limits<rep>::max() / 2;\n\n        if (!std::isfinite(result) || result > max_value || result < 0)\n        {\n            result = max_value;\n        }\n\n        auto count = static_cast<rep>(result);\n\n        QUBUS_ASSERT(count >= 0, \"Invalid duration.\");\n\n        return std::chrono::microseconds(std::move(count));\n    }\n\n    int operator()(const Eigen::VectorXd& parameters, Eigen::VectorXd& result) const\n    {\n        QUBUS_ASSERT(number_of_parameters_ == parameters.size(), \"Unexpected number of parameters.\");\n\n        for (long int i = 0; i < result.size(); ++i)\n        {\n            auto i_idx = util::integer_cast<Eigen::Index>(i);\n            auto i_std = util::integer_cast<std::size_t>(i);\n\n            result(i_idx) = evaluate_(parameters, (*dataset_)[i_std].arguments, 0) -\n                            (*dataset_)[i_std].execution_time.count();\n        }\n\n        return 0;\n    }\n\n    int df(const Eigen::VectorXd& parameters, Eigen::MatrixXd& result) const\n    {\n        QUBUS_ASSERT(result.rows() == dataset_->size(), \"Unexpected number of results.\");\n        QUBUS_ASSERT(result.cols() == parameters.size(), \"Unexpected number of variables.\");\n\n        for (long int i = 0; i < result.rows(); ++i)\n        {\n            auto i_idx = util::integer_cast<Eigen::Index>(i);\n            auto i_std = util::integer_cast<std::size_t>(i);\n\n            for (long int col = 0; col < result.cols(); ++col)\n            {\n                auto col_idx = util::integer_cast<Eigen::Index>(col);\n\n                result(i_idx, col_idx) = df_(parameters, (*dataset_)[i_std].arguments, col);\n            }\n        }\n\n        return 0;\n    }\n\n    std::string dump(const Eigen::VectorXd& parameters) const\n    {\n        return root_->dump(parameters);\n    }\n\nprivate:\n    std::unique_ptr<model_expression> root_;\n    long int number_of_parameters_;\n    const Dataset* dataset_;\n\n    compiled_expression evaluate_;\n    compiled_expression df_;\n};\n\ntemplate <typename Dataset>\nclass regression_model\n{\npublic:\n    template <typename Engine>\n    regression_model(model<Dataset> m, Engine& engine) : model_(m)\n    {\n        auto number_of_parameters = this->model_.number_of_parameters();\n\n        parameters_.resize(number_of_parameters);\n\n        std::uniform_real_distribution<double> parameter_dist(-100, 100);\n\n        for (long int i = 0; i < number_of_parameters; ++i)\n        {\n            parameters_(util::integer_cast<Eigen::Index>(i)) = parameter_dist(engine);\n        }\n\n        update();\n    }\n\n    const model_expression& expr() const\n    {\n        return model_.expr();\n    }\n\n    long int number_of_arguments() const\n    {\n        return model_.number_of_arguments();\n    }\n\n    long int number_of_parameters() const\n    {\n        return model_.number_of_parameters();\n    }\n\n    std::chrono::microseconds accuracy() const\n    {\n        return accuracy_;\n    }\n\n    double fitness() const\n    {\n        return fitness_;\n    }\n\n    std::chrono::microseconds query(const std::vector<double>& arguments) const\n    {\n        return model_.query(parameters_, arguments);\n    }\n\n    void update()\n    {\n        update_parameters();\n        update_accuarcy();\n        update_fitness();\n    }\n\nprivate:\n    void update_parameters()\n    {\n        auto number_of_parameters = this->model_.number_of_parameters();\n\n        if (number_of_parameters > 0 && number_of_parameters < this->model_.data_set().size())\n        {\n            Eigen::LevenbergMarquardt<model<Dataset>> lm(this->model_);\n            lm.minimize(parameters_);\n        }\n    }\n\n    void update_accuarcy()\n    {\n        double norm = 0.0;\n\n        for (const auto& point : model_.data_set())\n        {\n            norm +=\n                std::abs(static_cast<double>(model_.query(parameters_, point.arguments).count()) -\n                         static_cast<double>(point.execution_time.count()));\n        }\n\n        norm /= model_.data_set().size();\n\n        QUBUS_ASSERT(norm >= 0, \"A norm shall be non-negative.\");\n\n        double max_norm = std::numeric_limits<std::chrono::microseconds::rep>::max() / 2;\n\n        if (!std::isfinite(norm))\n        {\n            norm = max_norm;\n        }\n        else\n        {\n            norm = std::min(norm, max_norm);\n        }\n\n        accuracy_ = std::chrono::microseconds(static_cast<std::chrono::microseconds::rep>(norm));\n\n        QUBUS_ASSERT(accuracy_.count() >= 0, \"An accuary shall be non-negative.\");\n    }\n\n    void update_fitness()\n    {\n        fitness_ = static_cast<double>(accuracy_.count()) +\n                   2 * determine_number_of_expressions(model_.expr());\n    }\n\n    model<Dataset> model_;\n    Eigen::VectorXd parameters_;\n    std::chrono::microseconds accuracy_;\n    double fitness_;\n};\n\ntemplate <typename Dataset, typename Engine>\nstd::vector<regression_model<Dataset>>\nperform_genetic_programming_step(std::vector<regression_model<Dataset>> old_generation,\n                                 long int number_of_arguments, const Dataset& dataset,\n                                 Engine& engine)\n{\n    constexpr long int elite_share = 10;\n    constexpr long int immigrant_share = 10;\n    constexpr long int mutation_rate = 20;\n\n    constexpr long int wrap_rate = 10;\n    constexpr long int combination_rate = 10;\n\n    constexpr long int max_depth = model<Dataset>::max_depth;\n\n    constexpr long int crossover_rate = 100 - mutation_rate - wrap_rate - combination_rate;\n\n    const auto fitness_comperator = [](const regression_model<Dataset>& lhs,\n                                       const regression_model<Dataset>& rhs) {\n        return lhs.fitness() < rhs.fitness();\n    };\n\n    QUBUS_ASSERT(std::is_sorted(old_generation.begin(), old_generation.end(), fitness_comperator),\n               \"The old generation has to be sorted.\");\n\n    const auto population_size = old_generation.size();\n\n    std::discrete_distribution<int> dist(\n        {mutation_rate, wrap_rate, combination_rate, crossover_rate});\n    std::uniform_int_distribution<long int> population_index_dist(0, population_size - 1);\n\n    std::vector<regression_model<Dataset>> new_generation;\n    new_generation.reserve(population_size);\n\n    auto number_of_elites = (population_size * elite_share) / 100;\n\n    for (std::size_t i = 0; i < number_of_elites; ++i)\n    {\n        new_generation.push_back(old_generation[i]);\n        new_generation.back().update();\n    }\n\n    auto number_of_immigrants = (population_size * immigrant_share) / 100;\n\n    for (std::size_t i = number_of_elites; i < number_of_elites + number_of_immigrants; ++i)\n    {\n        long int number_of_parameters = 0;\n\n        auto new_expr =\n            generate_random_expression(engine, number_of_arguments, number_of_parameters);\n\n        auto new_model = model<Dataset>(std::move(new_expr), dataset);\n\n        new_generation.push_back(regression_model<Dataset>(std::move(new_model), engine));\n    }\n\n    for (std::size_t i = number_of_elites + number_of_immigrants; i < population_size; ++i)\n    {\n        auto action = dist(engine);\n\n        switch (action)\n        {\n        case 0:\n        {\n            auto index = population_index_dist(engine);\n\n            const auto& reg_model = old_generation[index];\n\n            auto new_expr = mutate_expression(reg_model.expr(), reg_model.number_of_arguments(),\n                                              reg_model.number_of_parameters(), engine);\n\n            if (determine_depth(*new_expr) <= max_depth)\n            {\n                remove_dead_parameters(*new_expr);\n            }\n            else\n            {\n                new_expr = clone(reg_model.expr());\n            }\n\n            auto new_model = model<Dataset>(std::move(new_expr), dataset);\n\n            new_generation.push_back(regression_model<Dataset>(std::move(new_model), engine));\n\n            break;\n        }\n        case 1:\n        {\n            auto index = population_index_dist(engine);\n\n            const auto& reg_model = old_generation[index];\n\n            auto new_expr = wrap_expression(reg_model.expr(), engine);\n\n            if (determine_depth(*new_expr) > max_depth)\n            {\n                new_expr = clone(reg_model.expr());\n            }\n\n            auto new_model = model<Dataset>(std::move(new_expr), dataset);\n\n            new_generation.push_back(regression_model<Dataset>(std::move(new_model), engine));\n\n            break;\n        }\n        case 2:\n        {\n            auto index = population_index_dist(engine);\n            auto index2 = population_index_dist(engine);\n\n            const auto& mother = old_generation[index];\n            const auto& father = old_generation[index2];\n\n            auto new_expr = combine_expressions(mother.expr(), father.expr(), engine);\n\n            if (determine_depth(*new_expr) > max_depth)\n            {\n                new_expr = clone(mother.expr());\n            }\n\n            auto new_model = model<Dataset>(std::move(new_expr), dataset);\n\n            new_generation.push_back(regression_model<Dataset>(std::move(new_model), engine));\n\n            break;\n        }\n        case 3:\n        {\n            auto index = population_index_dist(engine);\n            auto index2 = population_index_dist(engine);\n\n            const auto& mother = old_generation[index];\n            const auto& father = old_generation[index2];\n\n            auto new_expr = mix_expressions(mother.expr(), father.expr(), engine);\n\n            if (determine_depth(*new_expr) <= max_depth)\n            {\n                remove_dead_parameters(*new_expr);\n            }\n            else\n            {\n                new_expr = clone(mother.expr());\n            }\n\n            auto new_model = model<Dataset>(std::move(new_expr), dataset);\n\n            new_generation.push_back(regression_model<Dataset>(std::move(new_model), engine));\n\n            break;\n        }\n        default:\n            QUBUS_UNREACHABLE_BECAUSE(\"No case left.\");\n        }\n    }\n\n    std::sort(new_generation.begin(), new_generation.end(), fitness_comperator);\n\n    QUBUS_ASSERT(std::is_sorted(new_generation.begin(), new_generation.end(), fitness_comperator),\n               \"The new generation has to be sorted.\");\n\n    return new_generation;\n}\n}\n\nclass symbolic_regression_impl\n{\npublic:\n    explicit symbolic_regression_impl(long int window_size_)\n    : dataset_(util::integer_cast<dataset_type::size_type>(window_size_))\n    {\n        std::random_device dev;\n        engine_ = std::mt19937(dev());\n    }\n\n    void add_datapoint(std::vector<double> arguments, std::chrono::microseconds execution_time)\n    {\n        dataset_.push_back(data_point{std::move(arguments), std::move(execution_time)});\n    }\n\n    boost::optional<std::chrono::microseconds> update()\n    {\n        if (dataset_.empty())\n            return accuracy();\n\n        if (models_.empty())\n        {\n            constexpr long int size_of_population = 200;\n\n            models_.reserve(size_of_population);\n\n            for (long int i = 0; i < size_of_population; ++i)\n            {\n                long int number_of_parameters = 0;\n\n                auto new_model = model<dataset_type>(\n                    generate_random_expression(engine_, dataset_.front().arguments.size(),\n                                               number_of_parameters),\n                    dataset_);\n\n                models_.push_back(regression_model<dataset_type>(std::move(new_model), engine_));\n            }\n\n            const auto fitness_comperator = [](const regression_model<dataset_type>& lhs,\n                                               const regression_model<dataset_type>& rhs) {\n                return lhs.fitness() < rhs.fitness();\n            };\n\n            std::sort(models_.begin(), models_.end(), fitness_comperator);\n        }\n        else\n        {\n            models_ = perform_genetic_programming_step(\n                std::move(models_), dataset_.front().arguments.size(), dataset_, engine_);\n        }\n\n        return accuracy();\n    }\n\n    boost::optional<std::chrono::microseconds> update_cheaply()\n    {\n        if (models_.empty())\n            return boost::none;\n\n        models_.front().update();\n\n        return accuracy();\n    }\n\n    long int size_of_dataset() const\n    {\n        return util::integer_cast<long int>(dataset_.size());\n    }\n\n    boost::optional<std::chrono::microseconds> query(const std::vector<double>& arguments) const\n    {\n        if (models_.empty())\n            return boost::none;\n\n        return models_.front().query(arguments);\n    }\n\n    boost::optional<std::chrono::microseconds> accuracy() const\n    {\n        if (models_.empty())\n            return boost::none;\n\n        return models_.front().accuracy();\n    }\n\nprivate:\n    using dataset_type = boost:: circular_buffer_space_optimized<data_point>;\n\n    std::mt19937 engine_;\n\n    dataset_type dataset_;\n    std::vector<regression_model<dataset_type>> models_;\n};\n\nsymbolic_regression::symbolic_regression(long int window_size_)\n: impl_(std::make_unique<symbolic_regression_impl>(window_size_))\n{\n}\n\nsymbolic_regression::~symbolic_regression() = default;\n\nsymbolic_regression::symbolic_regression(symbolic_regression&&) = default;\nsymbolic_regression& symbolic_regression::operator=(symbolic_regression&&) = default;\n\nvoid symbolic_regression::add_datapoint(std::vector<double> arguments,\n                                        std::chrono::microseconds execution_time)\n{\n    impl_->add_datapoint(std::move(arguments), std::move(execution_time));\n}\n\nboost::optional<std::chrono::microseconds> symbolic_regression::update()\n{\n    return impl_->update();\n}\n\nboost::optional<std::chrono::microseconds> symbolic_regression::update_cheaply()\n{\n    return impl_->update_cheaply();\n}\n\nlong int symbolic_regression::size_of_dataset() const\n{\n    return impl_->size_of_dataset();\n}\n\nboost::optional<std::chrono::microseconds>\nsymbolic_regression::query(const std::vector<double>& arguments) const\n{\n    return impl_->query(arguments);\n}\n\nboost::optional<std::chrono::microseconds> symbolic_regression::accuracy() const\n{\n    return impl_->accuracy();\n}\n}\n", "meta": {"hexsha": "0a068c4302571f0daab7b5b5c5bc5f752fac7e29", "size": 55501, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "qubus/src/performance_models/symbolic_regression.cpp", "max_stars_repo_name": "qubusproject/Qubus", "max_stars_repo_head_hexsha": "0feb8d6df00459c5af402545dbe7c82ee3ec4b7c", "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": "qubus/src/performance_models/symbolic_regression.cpp", "max_issues_repo_name": "qubusproject/Qubus", "max_issues_repo_head_hexsha": "0feb8d6df00459c5af402545dbe7c82ee3ec4b7c", "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": "qubus/src/performance_models/symbolic_regression.cpp", "max_forks_repo_name": "qubusproject/Qubus", "max_forks_repo_head_hexsha": "0feb8d6df00459c5af402545dbe7c82ee3ec4b7c", "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.1956864808, "max_line_length": 101, "alphanum_fraction": 0.5834849823, "num_tokens": 12031, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891218080991, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.48106380414325983}}
{"text": "/*******************************************************************************\n * Copyright (c) 2018-, UT-Battelle, LLC.\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the MIT License \n * which accompanies this distribution. \n *\n * Contributors:\n *   Alexander J. McCaskey - initial API and implementation\n *   Thien Nguyen - implementation\n *******************************************************************************/\n#include \"clifford_gate_utils.hpp\"\n#include <Eigen/Dense>\n#include <cassert>\n#include <cmath>\n#include <set>\n\nnamespace {\ndouble mod_2pi(double theta) {\n  while (theta > M_PI or theta <= -M_PI) {\n    if (theta > M_PI) {\n      theta = theta - 2 * M_PI;\n    } else if (theta <= -M_PI) {\n      theta = theta + 2 * M_PI;\n    }\n  }\n  assert(theta >= -M_PI && theta <= M_PI);\n  return theta;\n}\n} // namespace\nnamespace qcor {\nnamespace utils {\nGenRot_t computeRotationInPauliFrame(const GenRot_t &in_rot,\n                                     PauliLabel in_newPauli,\n                                     PauliLabel in_netPauli) {\n  auto [theta1, theta2, theta3] = in_rot;\n\n  theta1 = mod_2pi(theta1);\n  theta2 = mod_2pi(theta2);\n  theta3 = mod_2pi(theta3);\n  if (in_netPauli == PauliLabel::X || in_netPauli == PauliLabel::Z) {\n    theta2 *= -1.0;\n  }\n  if (in_netPauli == PauliLabel::X || in_netPauli == PauliLabel::Y) {\n    theta3 *= -1.0;\n    theta1 *= -1.0;\n  }\n\n  // if x or y\n  if (in_newPauli == PauliLabel::X || in_newPauli == PauliLabel::Y) {\n    theta1 = -theta1 + M_PI;\n    theta2 = theta2 + M_PI;\n  }\n  // if y or z\n  if (in_newPauli == PauliLabel::Y || in_newPauli == PauliLabel::Z) {\n    theta1 = theta1 + M_PI;\n  }\n\n  // make everything between - pi and pi\n  theta1 = mod_2pi(theta1);\n  theta2 = mod_2pi(theta2);\n  theta3 = mod_2pi(theta3);\n  return std::make_tuple(theta1, theta2, theta3);\n}\n\nGenRot_t invU3Gate(const GenRot_t &in_rot) {\n  auto [theta1, theta2, theta3] = in_rot;\n  theta1 = mod_2pi(M_PI - theta1);\n  theta2 = mod_2pi(-theta2);\n  theta3 = mod_2pi(-theta3 + M_PI);\n  return std::make_tuple(theta1, theta2, theta3);\n}\n\nSrepDict_t computeGateSymplecticRepresentations(\n    const std::vector<std::string> &in_gateList) {\n  static const SrepDict_t standardDict = []() {\n    std::unordered_map<std::string, Smatrix_t> complete_s_dict;\n    std::unordered_map<std::string, Pvec_t> complete_p_dict;\n\n    // The Pauli gates\n    complete_s_dict[\"I\"] = std::vector<std::vector<int>>{{1, 0}, {0, 1}};\n    complete_s_dict[\"X\"] = std::vector<std::vector<int>>{{1, 0}, {0, 1}};\n    complete_s_dict[\"Y\"] = std::vector<std::vector<int>>{{1, 0}, {0, 1}};\n    complete_s_dict[\"Z\"] = std::vector<std::vector<int>>{{1, 0}, {0, 1}};\n\n    complete_p_dict[\"I\"] = std::vector<int>{0, 0};\n    complete_p_dict[\"X\"] = std::vector<int>{0, 2};\n    complete_p_dict[\"Y\"] = std::vector<int>{2, 2};\n    complete_p_dict[\"Z\"] = std::vector<int>{2, 0};\n\n    // Five single qubit gates that each represent one of five classes of\n    // Cliffords that equivalent up to Pauli gates and are not equivalent to\n    // idle (that class is covered by any one of the Pauli gates above).\n    complete_s_dict[\"H\"] = std::vector<std::vector<int>>{{0, 1}, {1, 0}};\n    complete_s_dict[\"P\"] = std::vector<std::vector<int>>{{1, 0}, {1, 1}};\n    complete_s_dict[\"PH\"] = std::vector<std::vector<int>>{{0, 1}, {1, 1}};\n    complete_s_dict[\"HP\"] = std::vector<std::vector<int>>{{1, 1}, {1, 0}};\n    complete_s_dict[\"HPH\"] = std::vector<std::vector<int>>{{1, 1}, {0, 1}};\n    complete_p_dict[\"H\"] = std::vector<int>{0, 0};\n    complete_p_dict[\"P\"] = std::vector<int>{1, 0};\n    complete_p_dict[\"PH\"] = std::vector<int>{0, 1};\n    complete_p_dict[\"HP\"] = std::vector<int>{3, 0};\n    complete_p_dict[\"HPH\"] = std::vector<int>{0, 3};\n    // The full 1-qubit Cliffor group, using the same labelling as in\n    // extras.rb.group\n    complete_s_dict[\"C0\"] = std::vector<std::vector<int>>{{1, 0}, {0, 1}};\n    complete_p_dict[\"C0\"] = std::vector<int>{0, 0};\n    complete_s_dict[\"C1\"] = std::vector<std::vector<int>>{{1, 1}, {1, 0}};\n    complete_p_dict[\"C1\"] = std::vector<int>{1, 0};\n    complete_s_dict[\"C2\"] = std::vector<std::vector<int>>{{0, 1}, {1, 1}};\n    complete_p_dict[\"C2\"] = std::vector<int>{0, 1};\n    complete_s_dict[\"C3\"] = std::vector<std::vector<int>>{{1, 0}, {0, 1}};\n    complete_p_dict[\"C3\"] = std::vector<int>{0, 2};\n    complete_s_dict[\"C4\"] = std::vector<std::vector<int>>{{1, 1}, {1, 0}};\n    complete_p_dict[\"C4\"] = std::vector<int>{1, 2};\n    complete_s_dict[\"C5\"] = std::vector<std::vector<int>>{{0, 1}, {1, 1}};\n    complete_p_dict[\"C5\"] = std::vector<int>{0, 3};\n    complete_s_dict[\"C6\"] = std::vector<std::vector<int>>{{1, 0}, {0, 1}};\n    complete_p_dict[\"C6\"] = std::vector<int>{2, 2};\n    complete_s_dict[\"C7\"] = std::vector<std::vector<int>>{{1, 1}, {1, 0}};\n    complete_p_dict[\"C7\"] = std::vector<int>{3, 2};\n    complete_s_dict[\"C8\"] = std::vector<std::vector<int>>{{0, 1}, {1, 1}};\n    complete_p_dict[\"C8\"] = std::vector<int>{2, 3};\n    complete_s_dict[\"C9\"] = std::vector<std::vector<int>>{{1, 0}, {0, 1}};\n    complete_p_dict[\"C9\"] = std::vector<int>{2, 0};\n    complete_s_dict[\"C10\"] = std::vector<std::vector<int>>{{1, 1}, {1, 0}};\n    complete_p_dict[\"C10\"] = std::vector<int>{3, 0};\n    complete_s_dict[\"C11\"] = std::vector<std::vector<int>>{{0, 1}, {1, 1}};\n    complete_p_dict[\"C11\"] = std::vector<int>{2, 1};\n    complete_s_dict[\"C12\"] = std::vector<std::vector<int>>{{0, 1}, {1, 0}};\n    complete_p_dict[\"C12\"] = std::vector<int>{0, 0};\n    complete_s_dict[\"C13\"] = std::vector<std::vector<int>>{{1, 1}, {0, 1}};\n    complete_p_dict[\"C13\"] = std::vector<int>{0, 1};\n    complete_s_dict[\"C14\"] = std::vector<std::vector<int>>{{1, 0}, {1, 1}};\n    complete_p_dict[\"C14\"] = std::vector<int>{1, 0};\n    complete_s_dict[\"C15\"] = std::vector<std::vector<int>>{{0, 1}, {1, 0}};\n    complete_p_dict[\"C15\"] = std::vector<int>{0, 2};\n    complete_s_dict[\"C16\"] = std::vector<std::vector<int>>{{1, 1}, {0, 1}};\n    complete_p_dict[\"C16\"] = std::vector<int>{0, 3};\n    complete_s_dict[\"C17\"] = std::vector<std::vector<int>>{{1, 0}, {1, 1}};\n    complete_p_dict[\"C17\"] = std::vector<int>{1, 2};\n    complete_s_dict[\"C18\"] = std::vector<std::vector<int>>{{0, 1}, {1, 0}};\n    complete_p_dict[\"C18\"] = std::vector<int>{2, 2};\n    complete_s_dict[\"C19\"] = std::vector<std::vector<int>>{{1, 1}, {0, 1}};\n    complete_p_dict[\"C19\"] = std::vector<int>{2, 3};\n    complete_s_dict[\"C20\"] = std::vector<std::vector<int>>{{1, 0}, {1, 1}};\n    complete_p_dict[\"C20\"] = std::vector<int>{3, 2};\n    complete_s_dict[\"C21\"] = std::vector<std::vector<int>>{{0, 1}, {1, 0}};\n    complete_p_dict[\"C21\"] = std::vector<int>{2, 0};\n    complete_s_dict[\"C22\"] = std::vector<std::vector<int>>{{1, 1}, {0, 1}};\n    complete_p_dict[\"C22\"] = std::vector<int>{2, 1};\n    complete_s_dict[\"C23\"] = std::vector<std::vector<int>>{{1, 0}, {1, 1}};\n    complete_p_dict[\"C23\"] = std::vector<int>{3, 0};\n    // The CNOT gate, CPHASE gate, and SWAP gate.\n    complete_s_dict[\"CNOT\"] = std::vector<std::vector<int>>{\n        {1, 0, 0, 0}, {1, 1, 0, 0}, {0, 0, 1, 1}, {0, 0, 0, 1}};\n    complete_s_dict[\"CPHASE\"] = std::vector<std::vector<int>>{\n        {1, 0, 0, 0}, {0, 1, 0, 0}, {0, 1, 1, 0}, {1, 0, 0, 1}};\n    complete_s_dict[\"SWAP\"] = std::vector<std::vector<int>>{\n        {0, 1, 0, 0}, {1, 0, 0, 0}, {0, 0, 0, 1}, {0, 0, 1, 0}};\n    complete_p_dict[\"CNOT\"] = std::vector<int>{0, 0, 0, 0};\n    complete_p_dict[\"CPHASE\"] = std::vector<int>{0, 0, 0, 0};\n    complete_p_dict[\"SWAP\"] = std::vector<int>{0, 0, 0, 0};\n\n    SrepDict_t result;\n    for (const auto &[k, v] : complete_s_dict) {\n      assert(complete_p_dict.find(k) != complete_p_dict.end());\n      result[k] = std::make_pair(v, complete_p_dict[k]);\n    }\n    return result;\n  }();\n\n  if (!in_gateList.empty()) {\n    // Filter a subset of gates:\n    SrepDict_t result;\n    for (const auto &gateLabel : in_gateList) {\n      const auto iter = standardDict.find(gateLabel);\n      assert(iter != standardDict.end());\n      result[gateLabel] = iter->second;\n    }\n    return result;\n  }\n  return standardDict;\n}\n\nSrep_t computeLayerSymplecticRepresentations(const CliffordGateLayer_t &layers,\n                                             int nQubits,\n                                             const SrepDict_t &srep_dict) {\n  // Initilize\n  Pvec_t p(2 * nQubits, 0);\n  Smatrix_t s(2 * nQubits, p);\n  std::set<int> seen_qubits;\n  for (const auto &[name, operands] : layers) {\n    const auto iter = srep_dict.find(name);\n    assert(iter != srep_dict.end());\n    const auto &[matrix, phase] = iter->second;\n    const auto nforgate = operands.size();\n    assert(nforgate > 0);\n    for (int ind1 = 0; ind1 < operands.size(); ++ind1) {\n      const auto qindex1 = operands[ind1];\n      assert(seen_qubits.find(qindex1) == seen_qubits.end());\n      seen_qubits.emplace(qindex1);\n      for (int ind2 = 0; ind2 < operands.size(); ++ind2) {\n        const auto qindex2 = operands[ind2];\n        // Put in the symp matrix elements\n        s[qindex1][qindex2] = matrix[ind1][ind2];\n        s[qindex1][qindex2 + nQubits] = matrix[ind1][ind2 + nforgate];\n        s[qindex1 + nQubits][qindex2] = matrix[ind1 + nforgate][ind2];\n        s[qindex1 + nQubits][qindex2 + nQubits] =\n            matrix[ind1 + nforgate][ind2 + nforgate];\n      }\n      // Put in the phase elements\n      p[qindex1] = phase[ind1];\n      p[qindex1 + nQubits] = phase[ind1 + nforgate];\n    }\n  }\n\n  return std::make_pair(s, p);\n}\n\nSrep_t composeCliffords(const Srep_t &C1, const Srep_t &C2) {\n  assert(C1.first.size() == C2.first.size());\n  assert(C1.second.size() == C2.second.size());\n  assert(C1.first.size() % 2 == 0);\n  const int n = C1.first.size() / 2;\n  using Mat_t = Eigen::Matrix<int, Eigen::Dynamic, Eigen::Dynamic>;\n  using Vec_t = Eigen::Matrix<int, Eigen::Dynamic, 1>;\n  Mat_t s1(2 * n, 2 * n);\n  Mat_t s2(2 * n, 2 * n);\n  Vec_t p1(2 * n);\n  Vec_t p2(2 * n);\n  // Load to eigen for processing\n  for (int i = 0; i < 2 * n; ++i) {\n    for (int j = 0; j < 2 * n; ++j) {\n      s1(i, j) = C1.first[i][j];\n      s2(i, j) = C2.first[i][j];\n    }\n    p1(i) = C1.second[i];\n    p2(i) = C2.second[i];\n  }\n\n  Mat_t s = s2 * s1;\n  // Mod 2\n  for (int i = 0; i < 2 * n; ++i) {\n    for (int j = 0; j < 2 * n; ++j) {\n      s(i, j) = s(i, j) % 2;\n    }\n  }\n\n  Mat_t u = Mat_t::Zero(2 * n, 2 * n);\n  u(Eigen::seq(n, 2 * n - 1), Eigen::seq(0, n - 1)) = Mat_t::Identity(n, n);\n\n  Vec_t vec1 = s1.transpose() * p2;\n  Mat_t inner = (s2.transpose() * u) * s2;\n  const auto strictly_upper_triangle = [](const Mat_t &m) -> Mat_t {\n    auto l = m.rows();\n    Mat_t out = m;\n\n    for (int i = 0; i < l; ++i) {\n      for (int j = 0; j < i + 1; ++j) {\n        out(i, j) = 0;\n      }\n    }\n    return out;\n  };\n\n  // Returns a diagonal matrix containing the diagonal of m.\n  const auto diagonal_as_matrix = [](const Mat_t &m) -> Mat_t {\n    auto l = m.rows();\n    Mat_t out = Mat_t::Zero(l, l);\n    for (int i = 0; i < l; ++i) {\n      out(i, i) = m(i, i);\n    }\n\n    return out;\n  };\n\n  // Returns a 1D array containing the diagonal of the input square 2D array m.\n  const auto diagonal_as_vec = [](const Mat_t &m) -> Mat_t {\n    auto l = m.rows();\n    Vec_t vec = Vec_t::Zero(l);\n    for (int i = 0; i < l; ++i) {\n      vec(i) = m(i, i);\n    }\n\n    return vec;\n  };\n\n  Mat_t matrix = 2 * strictly_upper_triangle(inner) + diagonal_as_matrix(inner);\n  Vec_t vec2 = diagonal_as_vec((s1.transpose() * matrix) * s1);\n  Vec_t vec3 = s1.transpose() * diagonal_as_vec(inner);\n  Vec_t p = p1 + vec1 + vec2 - vec3;\n  for (int i = 0; i < p.size(); ++i) {\n    p(i) = p(i) % 4;\n  }\n\n  Pvec_t p_res(2 * n, 0);\n  Smatrix_t s_res(2 * n, p_res);\n  for (int i = 0; i < 2 * n; ++i) {\n    for (int j = 0; j < 2 * n; ++j) {\n      s_res[i][j] = s(i, j);\n    }\n    p_res[i] = p(i);\n  }\n  return std::make_pair(s_res, p_res);\n}\n\nSrep_t computeCircuitSymplecticRepresentations(\n    const std::vector<CliffordGateLayer_t> &layers, int nQubits,\n    const SrepDict_t &srep_dict) {\n  // Initilize\n  Pvec_t p(2 * nQubits, 0);\n  Smatrix_t s(2 * nQubits, p);\n  // S must be initialized as an identity matrix\n  for (int i = 0; i < 2 * nQubits; ++i) {\n    s[i][i] = 1;\n  }\n  for (const auto &layer : layers) {\n    const auto layerRep =\n        computeLayerSymplecticRepresentations(layer, nQubits, srep_dict);\n\n    std::tie(s, p) = composeCliffords(std::make_pair(s, p), layerRep);\n  }\n  return std::make_pair(s, p);\n}\n\nstd::vector<PauliLabel> find_pauli_labels(const Pvec_t &pvec) {\n  assert(pvec.size() % 2 == 0);\n  const auto n = pvec.size() / 2;\n  std::vector<int> v(n, 0);\n  for (int i = 0; i < n; ++i) {\n    v[i] = (pvec[i] / 2) + 2 * (pvec[n + i] / 2);\n  }\n  // [0,0]=I, [2,0]=Z, [0,2]=X, and [2,2]=Y.\n  std::vector<PauliLabel> result;\n  for (const auto &el : v) {\n    assert(el < 4);\n    static const std::vector<PauliLabel> ARRAY{PauliLabel::I, PauliLabel::Z,\n                                               PauliLabel::X, PauliLabel::Y};\n    result.emplace_back(ARRAY[el]);\n  }\n  return result;\n}\n} // namespace utils\n} // namespace qcor", "meta": {"hexsha": "e45f56260939f92b22935997115a9eba8def2e45", "size": 13061, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/mirror_rb/clifford_gate_utils.cpp", "max_stars_repo_name": "vetter/qcor", "max_stars_repo_head_hexsha": "6f86835737277a26071593bb10dd8627c29d74a3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 59.0, "max_stars_repo_stars_event_min_datetime": "2019-08-22T18:40:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:12:42.000Z", "max_issues_repo_path": "lib/mirror_rb/clifford_gate_utils.cpp", "max_issues_repo_name": "vetter/qcor", "max_issues_repo_head_hexsha": "6f86835737277a26071593bb10dd8627c29d74a3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 137.0, "max_issues_repo_issues_event_min_datetime": "2019-09-13T15:50:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-06T14:19:46.000Z", "max_forks_repo_path": "lib/mirror_rb/clifford_gate_utils.cpp", "max_forks_repo_name": "vetter/qcor", "max_forks_repo_head_hexsha": "6f86835737277a26071593bb10dd8627c29d74a3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2019-07-08T17:30:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-03T16:24:12.000Z", "avg_line_length": 37.9680232558, "max_line_length": 81, "alphanum_fraction": 0.5746880025, "num_tokens": 4536, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891218080991, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.48106380414325983}}
{"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 <boost/geometry.hpp>\n#include <boost/geometry/geometries/geometries.hpp>\n#include <tuple>\n\nnamespace pyinterp::detail::math {\n\nnamespace detail {\n\n/// Calculates the area of a polygon.\ntemplate <template <class> class Point, typename Strategy, typename T>\ninline auto calculate_area(boost::geometry::model::polygon<Point<T>>& polygon,\n                           const Strategy& strategy) -> T {\n  auto result = boost::geometry::area(polygon, strategy);\n  if (result < 0) {\n    boost::geometry::reverse(polygon);\n    result = boost::geometry::area(polygon, strategy);\n  }\n  return result;\n}\n\n/// Calculate the area of a polygon. If the area is less than one epsilon, the\n/// calculated area is set to zero.\ntemplate <template <class> class Point, typename Strategy, typename T>\ninline auto calculate_and_normalize_area(\n    boost::geometry::model::polygon<Point<T>>& polygon,\n    const Strategy& strategy, const double total_area) -> T {\n  auto result = calculate_area<Point, Strategy, T>(polygon, strategy);\n  if (result > total_area || std::fabs(result) < 1e-12) {\n    result = 0;\n  }\n  return result;\n}\n\n}  // namespace detail\n\n/// Linear binning 2D\n///\n/// p01 (D/ABCD)         p11 (C/ABCD)\n///   \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2530\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n///   \u2502     A      \u2503 B    \u2502\n///   \u251d\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u254b\u2501\u2501\u2501\u2501\u2501\u2501\u2525 j\n///   \u2502            \u2503      \u2502\n///   \u2502     C      \u2503 D    \u2502\n///   \u2502            \u2503      \u2502\n///   \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2538\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n/// p00 (B/ABCD)   i     p10 (A/ABCD)\n///\n/// @param p Query point (i, j)\n/// @param p00 Point of coordinate (x0, y0)\n/// @param p11 Point of coordinate (x1, y1)\n/// @return a tuple that contains\n///   * w00 Weight for the coordinate (x0, y0)\n///   * w01 Weight for the coordinate (x0, y1)\n///   * w11 Weight for the coordinate (x1, y1)\n///   * w10 Weight for the coordinate (x1, y0)\ntemplate <template <class> class Point, typename Strategy, typename T>\nauto binning_2d(const Point<T>& pij, const Point<T>& p00, const Point<T>& p11,\n                Strategy const& strategy) -> std::tuple<T, T, T, T> {\n  // Coordinates of the grid points deducted.\n  const auto p01 =\n      Point<T>{boost::geometry::get<0>(p00), boost::geometry::get<1>(p11)};\n  const auto p10 =\n      Point<T>{boost::geometry::get<0>(p11), boost::geometry::get<1>(p00)};\n\n  // Coordinates of intersections between the point of interest and the grid\n  // points.\n  const auto p0j =\n      Point<T>{boost::geometry::get<0>(p00), boost::geometry::get<1>(pij)};\n  const auto pi1 =\n      Point<T>{boost::geometry::get<0>(pij), boost::geometry::get<1>(p11)};\n  const auto p1j =\n      Point<T>{boost::geometry::get<0>(p11), boost::geometry::get<1>(pij)};\n  const auto pi0 =\n      Point<T>{boost::geometry::get<0>(pij), boost::geometry::get<1>(p00)};\n\n  // Polygon to process\n  auto polygon_a =\n      boost::geometry::model::polygon<Point<T>>{{pij, p0j, p01, pi1, pij}};\n  auto polygon_b =\n      boost::geometry::model::polygon<Point<T>>{{pij, pi1, p11, p1j, pij}};\n  auto polygon_c =\n      boost::geometry::model::polygon<Point<T>>{{pij, pi0, p00, p0j, pij}};\n  auto polygon_d =\n      boost::geometry::model::polygon<Point<T>>{{pij, p1j, p10, pi0, pij}};\n  auto grid_cell =\n      boost::geometry::model::polygon<Point<T>>{{p00, p01, p11, p10, p00}};\n\n  // Area calculation.\n  auto total_area =\n      detail::calculate_area<Point, Strategy, T>(grid_cell, strategy);\n  auto area_a = detail::calculate_and_normalize_area<Point, Strategy, T>(\n      polygon_a, strategy, total_area);\n  auto area_b = detail::calculate_and_normalize_area<Point, Strategy, T>(\n      polygon_b, strategy, total_area);\n  auto area_c = detail::calculate_and_normalize_area<Point, Strategy, T>(\n      polygon_c, strategy, total_area);\n  auto area_d = detail::calculate_and_normalize_area<Point, Strategy, T>(\n      polygon_d, strategy, total_area);\n\n  return std::make_tuple(area_b / total_area, area_d / total_area,\n                         area_c / total_area, area_a / total_area);\n}\n\n}  // namespace pyinterp::detail::math\n", "meta": {"hexsha": "f41d215363677b3d37d13625585458cec45b12b6", "size": 4129, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/pyinterp/core/include/pyinterp/detail/math/binning.hpp", "max_stars_repo_name": "Geospatial-Data-Science/pangeo-pyinterp", "max_stars_repo_head_hexsha": "aa36a6fdbc4acea4206ebfd97d60aceffe0d98df", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-02-19T14:54:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-19T14:54:23.000Z", "max_issues_repo_path": "src/pyinterp/core/include/pyinterp/detail/math/binning.hpp", "max_issues_repo_name": "Geospatial-Data-Science/pangeo-pyinterp", "max_issues_repo_head_hexsha": "aa36a6fdbc4acea4206ebfd97d60aceffe0d98df", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pyinterp/core/include/pyinterp/detail/math/binning.hpp", "max_forks_repo_name": "Geospatial-Data-Science/pangeo-pyinterp", "max_forks_repo_head_hexsha": "aa36a6fdbc4acea4206ebfd97d60aceffe0d98df", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.5363636364, "max_line_length": 78, "alphanum_fraction": 0.6347783967, "num_tokens": 1181, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.4810200389767104}}
{"text": "//\n// Created by yue on 03.12.19.\n//\n\n#include <iostream>\n#include <vector>\n#include <time.h>\n#include <opencv2/opencv.hpp>\n//#include <Eigen/Dense>\n//#include <opencv2/core/eigen.hpp>\n\nusing namespace std;\nusing namespace cv;\n//using namespace Eigen;\n\nvector<Point> findLargestContour(vector< vector<Point> > contours) {\n    double largestArea = 0.; int largestIndex = 0;\n    for (int i = 0; i < contours.size(); ++i) {\n        double area = contourArea(contours[i]);\n        if (area > largestArea){\n            largestArea = area;\n            largestIndex = i;\n        }\n    }\n    return contours[largestIndex];\n}\n\nvector< vector<Point> > findLargeContours(vector< vector<Point> > contours, double minArea) {\n    vector< vector<Point> > outPutContours;\n    for (int i = 0; i < contours.size(); ++i) {\n        double area = contourArea(contours[i]);\n        if (area > minArea)\n            outPutContours.push_back(contours[i]);\n    }\n    return outPutContours;\n}\n\nint main() {\n    Mat img = imread(\"../../images/piece05_1200x900.jpg\");\n    /* processing image:\n     *  1.convert to greyscale and blurring\n     *  2.edge extraction\n     *  3.blurring\n     *  4.binarizing\n     *  5.find contours\n     *  6.find largest contour\n     *  7.contour to polyline(corners get!) */\n    Mat imgGrey, imgBlur, imgFilter2d;\n    // 1.convert to greyscale and blurring\n    cvtColor(img, imgGrey, CV_BGR2GRAY);\n    GaussianBlur(imgGrey, imgBlur, Size(9, 9), 2);\n//    blur(imgGrey, imgBlur, Size(7, 7));\n\n    // 2.edge extraction\n//    Mat kernel = (Mat_<char>(3, 3) << 0, 1, 0, 1, -4, 1, 0, 1, 0); // Laplacian filter\n    Mat kernel = (Mat_<char>(3, 3) << -1, -1, -1, -1, 8, -1, -1, -1, -1); // Laplacian filter\n//    Mat kernel = (Mat_<char>(3, 3) << -1, -2, -1, 0, 0, 0, 1, 2, 1); // Sobel filter x_dir\n    filter2D(imgBlur, imgFilter2d, -1, kernel);\n    // 3.blurring\n    blur(imgFilter2d, imgFilter2d, Size(9, 9));\n    // 4.binarizing\n    threshold(imgFilter2d, imgFilter2d, 3, 50, THRESH_BINARY);\n    // 5.find contours\n    vector<vector<Point> > contours;\n    clock_t start, end; // __________________________timing\n    start = clock(); // __________________________timing\n    findContours(imgFilter2d, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);\n    cout << contours.size() << endl;\n    // 6.find largest contour\n    vector< vector<Point> > largeContours = findLargeContours(contours, 500.);\n    cout << largeContours.size() << endl;\n    // 7.contour to polyline(corners get!)\n    for (int i = 0; i < largeContours.size(); ++i)\n        approxPolyDP(largeContours[i], largeContours[i], 10, true);\n    end = clock(); // __________________________timing\n    cout << (double)(end-start)/CLOCKS_PER_SEC << endl; // __________________________timing\n    for (int i = 0; i < largeContours.size(); ++i)\n        cout << largeContours[i] << endl;\n    drawContours(img, largeContours, -1, Scalar(0, 0, 255));\n\n    imshow(\"myImage\", img);\n    imshow(\"filter2d\", imgFilter2d);\n    waitKey(0);\n    return 0;\n}\n", "meta": {"hexsha": "629c67680ae15c0e8473e0ff0c9dd96b900a3271", "size": 3000, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/contour.cpp", "max_stars_repo_name": "dbddqy/DPI", "max_stars_repo_head_hexsha": "9fa05335902a7404cbc197653e476706ed724ae1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/contour.cpp", "max_issues_repo_name": "dbddqy/DPI", "max_issues_repo_head_hexsha": "9fa05335902a7404cbc197653e476706ed724ae1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/contour.cpp", "max_forks_repo_name": "dbddqy/DPI", "max_forks_repo_head_hexsha": "9fa05335902a7404cbc197653e476706ed724ae1", "max_forks_repo_licenses": ["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.8837209302, "max_line_length": 93, "alphanum_fraction": 0.6286666667, "num_tokens": 905, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154240079185319, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.4810022435746413}}
{"text": "/**\n * @copyright Copyright (c) 2017 B-com http://www.b-com.com/\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#include <iostream>\n#include <string>\n#include <vector>\n#include <fstream>\n#include <boost/log/core.hpp>\n#include \"xpcf/xpcf.h\"\n\n// ADD COMPONENTS HEADERS HER\n\n#include \"SolARModuleOpencv_traits.h\"\n#include \"api/input/devices/ICamera.h\"\n#include \"api/solver/pose/I2DTransformFinder.h\"\n#include \"core/Log.h\"\n\nusing namespace SolAR;\nusing namespace SolAR::datastructure;\nusing namespace SolAR::api;\nusing namespace SolAR::MODULES::OPENCV;\n\nnamespace xpcf  = org::bcom::xpcf;\n\nvoid load_2dpoints(std::string&path_file, int points_no, std::vector<SRef<Point2Df>>&pt2d){\n\n    std::ifstream ox(path_file);\n    float pt[2];\n  //  Point2Df point_temp;\n    std::string dummy;\n    pt2d.resize(points_no);\n    float v[2];\n    for(int i = 0; i < points_no; ++i){\n       ox>>dummy;\n       v[0]  = std::stof(dummy);\n       ox>>dummy;\n       v[1]= std::stof(dummy);\n       pt2d[i]  = xpcf::utils::make_shared<Point2Df>(v[0], v[1]);\n    }\n  ox.close();\n}\n\nint main() {\n#if NDEBUG\n    boost::log::core::get()->set_logging_enabled(false);\n#endif\n\n    LOG_ADD_LOG_TO_CONSOLE();\n\n    std::string path_points1 = \"../data/pt1_F.txt\";\n    std::string path_points2 = \"../data/pt2_F.txt\";\n\n    /* instantiate component manager*/\n    SRef<xpcf::IComponentManager> xpcfComponentManager = xpcf::getComponentManagerInstance();\n\n    if(xpcfComponentManager->load(\"conf_FundamentalMatrixEstimation.xml\")!=org::bcom::xpcf::_SUCCESS)\n    {\n        LOG_ERROR(\"Failed to load the configuration file conf_FundamentalMatrixEstimation.xml\")\n        return -1;\n    }\n\n    // declare and create components\n    LOG_INFO(\"Start creating components\");\n\n    // component creation\n    SRef<input::devices::ICamera> camera = xpcfComponentManager->create<SolARCameraOpencv>()->bindTo<input::devices::ICamera>();\n    SRef<solver::pose::I2DTransformFinder> fundamentalFinder = xpcfComponentManager->create<SolARHomographyEstimationOpencv>()->bindTo<solver::pose::I2DTransformFinder>();\n\n    /* we need to check that components are well created*/\n    if (!camera || !fundamentalFinder)\n    {\n        LOG_ERROR(\"One or more component creations have failed\");\n        return -1;\n    }\n\n // declarations\n    Transform2Df                                      F;\n    std::vector<SRef<Point2Df>>                       points_view1;\n    std::vector<SRef<Point2Df>>                       points_view2;\n\n // Initialization\n   const int nb_points = 6953;\n   load_2dpoints(path_points1, nb_points, points_view1);\n   load_2dpoints(path_points2, nb_points, points_view2);\n\n   fundamentalFinder->find(points_view1, points_view2, F);\n\n   LOG_INFO(\"Fundamental Matrix: \\n {}\", F.matrix());\n   return 0;\n}\n", "meta": {"hexsha": "601d321bed077b7795fdf03012d4257ea40a1c1b", "size": 3267, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/SolARFundamentalMatrixEstimation/main.cpp", "max_stars_repo_name": "geekyfox90/SolARModuleOpenCV", "max_stars_repo_head_hexsha": "4d8d95c904be32e5935b06402de4a9c6e9b271b0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/SolARFundamentalMatrixEstimation/main.cpp", "max_issues_repo_name": "geekyfox90/SolARModuleOpenCV", "max_issues_repo_head_hexsha": "4d8d95c904be32e5935b06402de4a9c6e9b271b0", "max_issues_repo_licenses": ["Apache-2.0"], "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/SolARFundamentalMatrixEstimation/main.cpp", "max_forks_repo_name": "geekyfox90/SolARModuleOpenCV", "max_forks_repo_head_hexsha": "4d8d95c904be32e5935b06402de4a9c6e9b271b0", "max_forks_repo_licenses": ["Apache-2.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.4134615385, "max_line_length": 171, "alphanum_fraction": 0.6825834099, "num_tokens": 841, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.4810022354158566}}
{"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_CONSTANT_MANTISSAMASK_HPP_INCLUDED\n#define BOOST_SIMD_CONSTANT_MANTISSAMASK_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n  /*!\n    @ingroup group-constant\n\n    Generate a mask used to compute the mantissa of a floating point value\n\n\n    @par Header <boost/simd/constant/mantissamask.hpp>\n\n    @par Semantic:\n\n    @code\n    as_integer<T> r = Mantissamask<T>();\n    @endcode\n\n    @code\n    if T is double\n      r =  -2.225073858507200889e-308;\n    else if T is float\n      r =  -1.1754942106924410755e-38;\n    @endcode\n\n    @return The Mantissamask constant for the proper type\n  **/\n  template<typename T> T Mantissamask();\n\n  namespace functional\n  {\n    /*!\n      @ingroup group-callable-constant\n      Generate the  constant mantissamask.\n\n      @return The Mantissamask constant for the proper type\n    **/\n    Value Mantissamask();\n  }\n} }\n#endif\n\n#include <boost/simd/constant/scalar/mantissamask.hpp>\n#include <boost/simd/constant/simd/mantissamask.hpp>\n\n#endif\n", "meta": {"hexsha": "c168d20eb6b52035888f046dd4314f9bb7c7d327", "size": 1409, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/constant/mantissamask.hpp", "max_stars_repo_name": "TobiasLudwig/boost.simd", "max_stars_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/simd/constant/mantissamask.hpp", "max_issues_repo_name": "TobiasLudwig/boost.simd", "max_issues_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/constant/mantissamask.hpp", "max_forks_repo_name": "TobiasLudwig/boost.simd", "max_forks_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-02-16T09:58:18.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:22:43.000Z", "avg_line_length": 23.8813559322, "max_line_length": 100, "alphanum_fraction": 0.60397445, "num_tokens": 339, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834732, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.4810022260216172}}
{"text": "#pragma once\n\n#include <BilinearPatch.hpp>\n#include <boost/optional.hpp>\n#include <ScalarType.hpp>\n\ntemplate <class VertexType> struct Bezier;\n\ntemplate <class CurveType>\nstruct UniformCoonsPatchTraits {\n\ttypedef typename VertexType<CurveType>::type VertexType;\n\ttypedef CurveType LeftCurveType;\n\ttypedef CurveType RightCurveType;\n\ttypedef CurveType BottomCurveType;\n\ttypedef CurveType TopCurveType;\n};\n\ntemplate <class Traits>\nstruct CoonsPatch {\n\ttypedef typename Traits::VertexType VertexType;\n\ttypedef typename ScalarType<VertexType>::type ScalarType;\n\n\ttypedef typename Traits::LeftCurveType LeftCurveType;\n\ttypedef typename Traits::RightCurveType RightCurveType;\n\ttypedef typename Traits::BottomCurveType BottomCurveType;\n\ttypedef typename Traits::TopCurveType TopCurveType;\n\n\tCoonsPatch() { }\n\n\ttemplate <class L, class R, class B, class T>\n\tCoonsPatch(L const & left, R const & right, B const & bottom, T const & top)\n\t\t: left_(left), right_(right), bottom_(bottom), top_(top) { }\n\n\tVertexType operator () (ScalarType u, ScalarType v) const {\n\t\tVertexType a = interpolate(u, left_(v), right_(v)),\n\t\t\tb = interpolate(v, bottom_(u), top_(u)),\n\t\t\tc = get_patch_value(u, v);\n\n\t\treturn interpolate(.5,\n\t\t\tinterpolate(-1, a, c),\n\t\t\tinterpolate(-1, b, c)\n\t\t);\n\t}\n\n\tLeftCurveType & get_left() { return left_; }\n\tLeftCurveType const & get_left() const { return left_; }\n\n\tRightCurveType & get_right() { return right_; }\n\tRightCurveType const & get_right() const { return right_; }\n\n\tBottomCurveType & get_bottom() { return bottom_; }\n\tBottomCurveType const & get_bottom() const { return bottom_; }\n\n\tTopCurveType & get_top() { return top_; }\n\tTopCurveType const & get_top() const { return top_; }\n\n\tprivate:\n\t\tvoid init_patch() const {\n\t\t\tif (bilinear_patch_) { return; }\n\n\t\t\tbilinear_patch_.reset(\n\t\t\t\tBilinearPatch<VertexType>(\n\t\t\t\t\tbottom_(static_cast<ScalarType>(0.0)), bottom_(static_cast<ScalarType>(1.0)),\n\t\t\t\t\ttop_(static_cast<ScalarType>(0.0)), top_(static_cast<ScalarType>(1.0))\n\t\t\t\t)\n\t\t\t);\n\t\t}\n\n\t\tVertexType get_patch_value(ScalarType u, ScalarType v) const {\n\t\t\tinit_patch();\n\t\t\treturn (*bilinear_patch_)(u, v);\n\t\t}\n\n\t\tLeftCurveType left_;\n\t\tRightCurveType right_;\n\t\tBottomCurveType bottom_;\n\t\tTopCurveType top_;\n\n\t\tmutable boost::optional<BilinearPatch<VertexType> > bilinear_patch_;\n};\n", "meta": {"hexsha": "85f97c8f8dfdd41e86831b6caa0e455ec71a948c", "size": 2299, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "handsome/cpp_src/CoonsPatch.hpp", "max_stars_repo_name": "bracket/handsome", "max_stars_repo_head_hexsha": "c93d34f94d0eea24f5514efc9bc423eb28b44a6b", "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": "handsome/cpp_src/CoonsPatch.hpp", "max_issues_repo_name": "bracket/handsome", "max_issues_repo_head_hexsha": "c93d34f94d0eea24f5514efc9bc423eb28b44a6b", "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": "handsome/cpp_src/CoonsPatch.hpp", "max_forks_repo_name": "bracket/handsome", "max_forks_repo_head_hexsha": "c93d34f94d0eea24f5514efc9bc423eb28b44a6b", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.3827160494, "max_line_length": 82, "alphanum_fraction": 0.7320574163, "num_tokens": 598, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.480977951631193}}
{"text": "// This file is part of MLDB. Copyright 2015 mldb.ai inc. All rights reserved.\n\n// \n// centroid_feature_generator_test.cc\n// Simon Lemieux - 19 Jun 2013\n// Copyright (c) 2013 mldb.ai inc. All rights reserved.\n// \n\n#define BOOST_TEST_MAIN\n#define BOOST_TEST_DYN_LINK\n\n#include <boost/test/unit_test.hpp>\n#include \"mldb/vfs/filter_streams.h\"\n#include \"mldb/plugins/jml/kmeans.h\"\n#include \"mldb/utils/testing/fixtures.h\"\n#include <iostream>\n#include <stdlib.h>\n\nusing namespace MLDB;\nusing namespace ML;\nusing namespace std;\n\nMLDB_FIXTURE( kmeans_test );\n\nBOOST_FIXTURE_TEST_CASE( test_kmeans, kmeans_test )\n// BOOST_AUTO_TEST_CASE( test_kmeans)\n{\n\n    // Lets' add three \"kind of\" clusters\n    vector<distribution<float>> centroids;\n    distribution<float> c1(2);\n    c1[0] = 0.;\n    c1[1] = 5.;\n    distribution<float> c2(2);\n    c2[0] = -20.;\n    c2[1] = 0.;\n    distribution<float> c3(2);\n    c3[0] = 10.;\n    c3[1] = -20.;\n    distribution<float> c4(2);\n    c4[0] = -20.;\n    c4[1] = -20.;\n    centroids = {c1,c2,c3,c4};\n\n    vector<distribution<float>> data;\n    int nbPerClass = 10;\n\n\n    for (int k=0; k < centroids.size(); ++k)\n        for (int i=0; i < nbPerClass; i++) {\n            distribution<float> point = centroids[k];\n            distribution<float> noise(2);\n            noise[0] = ((rand() % 100) - 50) / 50.;\n            noise[1] = ((rand() % 100) - 50) / 50.;\n            data.push_back(point + noise);\n        }\n\n    // add trivial points\n    // it causes problems for cosine distance\n    distribution<float> zero(2);\n    zero[0] = 0.;\n    zero[1] = 0.;\n    for (int i=0; i < nbPerClass; ++i)\n        data.push_back(zero);\n\n    KMeans kmeans;\n    vector<int> in_cluster;\n    // kmeans.train(data, in_cluster, centroids.size());\n\n    auto test = [&] () {\n        for (int i=0; i < centroids.size(); ++i) {\n            int cluster = in_cluster[nbPerClass * i];\n            for (int j=0; j < nbPerClass; ++j) {\n                BOOST_CHECK(in_cluster[i*nbPerClass + j] == cluster);\n                cerr << in_cluster[i*nbPerClass + j] << \" \";\n            }\n            cerr << endl;\n        }\n        for (int i=0; i < centroids.size()-1; ++i)\n            BOOST_CHECK(in_cluster[i*nbPerClass] != in_cluster[(i+1)*nbPerClass]);\n    };\n\n    // test();\n\n    KMeans kmeans2(new KMeansCosineMetric());\n\n    kmeans2.train(data,\n                 in_cluster,\n                 centroids.size()+1,\n                 100);\n\n    test();\n\n    // FIXME finish the test\n    kmeans2.save(\"test_kmeans.bin.gz\");\n\n    KMeans kmeans3(new KMeansCosineMetric());\n    kmeans3.load(\"test_kmeans.bin.gz\");\n\n    for (int i=0; i<data.size(); ++i)\n        in_cluster[i] = kmeans3.assign(data[i]);\n\n    test();\n\n}\n", "meta": {"hexsha": "7975a955936d2c16f778fcd403827fb018201b35", "size": 2701, "ext": "cc", "lang": "C++", "max_stars_repo_path": "plugins/jml/testing/kmeans_test.cc", "max_stars_repo_name": "kstepanmpmg/mldb", "max_stars_repo_head_hexsha": "f78791cd34d01796705c0f173a14359ec1b2e021", "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/testing/kmeans_test.cc", "max_issues_repo_name": "tomzhang/mldb", "max_issues_repo_head_hexsha": "a09cf2d9ca454d1966b9e49ae69f2fe6bf571494", "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/testing/kmeans_test.cc", "max_forks_repo_name": "matebestek/mldb", "max_forks_repo_head_hexsha": "f78791cd34d01796705c0f173a14359ec1b2e021", "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": 25.4811320755, "max_line_length": 82, "alphanum_fraction": 0.5734912995, "num_tokens": 784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.480977951631193}}
{"text": "/**\n * @file\n * @brief Implementation of SubGeometry() tests for geometry objects\n * @author Anian Ruoss\n * @date   2019-02-11 18:06:17\n * @copyright MIT License\n */\n\n#include \"check_sub_geometry.h\"\n\n#include <gtest/gtest.h>\n\n#include <Eigen/Eigen>\n\nnamespace lf::geometry::test_utils {\n\nvoid checkSubGeometry(\n    const lf::geometry::Geometry &geom,\n    const std::function<lf::quad::QuadRule(lf::base::RefEl)> &qrProvider) {\n  // nodeCoords is a (refEl.Dimension, refEl.NumNodes) matrix\n  const auto refEl = geom.RefEl();\n  const Eigen::MatrixXd &nodeCoords = refEl.NodeCoords();\n\n  // iterate over all relative codimensions\n  for (size_t codim = 0; codim <= geom.RefEl().Dimension(); ++codim) {\n    // iterate over all subEntities in given codimension\n    const auto numSubEntities = refEl.NumSubEntities(codim);\n    for (size_t subEntity = 0; subEntity < numSubEntities; ++subEntity) {\n      // subNodeCoords is a (subRefEl.Dimension, subRefEl.NumNodes) matrix\n      auto subGeom = geom.SubGeometry(codim, subEntity);\n      auto subRefEl = subGeom->RefEl();\n      const Eigen::MatrixXd &subNodeCoords = subRefEl.NodeCoords();\n\n      // iterate over all nodes of subEntity\n      for (size_t subNode = 0; subNode < subRefEl.NumNodes(); ++subNode) {\n        // map coordinates in subRefEl.Dimension to geom.DimGlobal\n        auto globalCoordsFromSub = subGeom->Global(subNodeCoords.col(subNode));\n        // get index of subSubEntity with respect to refEl\n        int subSubIdx = refEl.SubSubEntity2SubEntity(\n            codim, subEntity, geom.DimLocal() - codim, subNode);\n        // map coordinates in RefEl.Dimension to geom.DimGlobal\n        auto globalCoords = geom.Global(nodeCoords.col(subSubIdx));\n\n        EXPECT_TRUE(globalCoordsFromSub.isApprox(globalCoords))\n            << \"Global mapping of subNode \" << subNode << \" of subEntity \"\n            << subEntity << \" in relative codim \" << codim\n            << \" differs from global mapping of node \" << subSubIdx;\n      }\n\n      // check points inside subEntity\n      if (subRefEl != lf::base::RefEl::kPoint()) {\n        // select nodes of RefEl referenced by subEntity\n        Eigen::MatrixXd mapNodeCoords(nodeCoords.rows(), subRefEl.NumNodes());\n        for (size_t subNode = 0; subNode < subRefEl.NumNodes(); ++subNode) {\n          const auto subSubIdx = refEl.SubSubEntity2SubEntity(\n              codim, subEntity, geom.DimLocal() - codim, subNode);\n          mapNodeCoords.col(subNode) = nodeCoords.col(subSubIdx);\n        }\n\n        auto points = qrProvider(subRefEl).Points();\n\n        // compute mapping: alpha * subNodeCoords + beta = mapNodeCoords\n        Eigen::MatrixXd paddedSubNodeCoords = Eigen::MatrixXd::Ones(\n            subNodeCoords.rows() + 1, subNodeCoords.cols());\n        paddedSubNodeCoords.block(0, 0, subNodeCoords.rows(),\n                                  subNodeCoords.cols()) = subNodeCoords;\n        Eigen::MatrixXd alphaBeta = paddedSubNodeCoords.transpose()\n                                        .fullPivLu()\n                                        .solve(mapNodeCoords.transpose())\n                                        .transpose();\n\n        // map points onto RefEl\n        Eigen::MatrixXd paddedPoints =\n            Eigen::MatrixXd::Ones(points.rows() + 1, points.cols());\n        paddedPoints.block(0, 0, points.rows(), points.cols()) = points;\n        const Eigen::MatrixXd mappedPoints = alphaBeta * paddedPoints;\n\n        // map coordinates in subRefEl.Dimension to geom.DimGlobal\n        auto globalPointsFromSub = subGeom->Global(points);\n        // map coordinates in RefEl.Dimension to geom.DimGlobal\n        auto globalPoints = geom.Global(mappedPoints);\n\n        EXPECT_TRUE(globalPoints.isApprox(globalPointsFromSub))\n            << \"Global mapping of points \" << points << \" from subEntity \"\n            << subEntity << \" in relative codim \" << codim\n            << \" differs from global mapping\";\n      }\n    }\n  }\n}\n\n}  // namespace lf::geometry::test_utils\n", "meta": {"hexsha": "e52485f28a78f8f0a608d697f86cc38c61649390", "size": 3977, "ext": "cc", "lang": "C++", "max_stars_repo_path": "lib/lf/geometry/test_utils/check_sub_geometry.cc", "max_stars_repo_name": "Fytch/lehrfempp", "max_stars_repo_head_hexsha": "c804b3e350aa893180f1a02ce57a93b3d7686e91", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2018-08-30T19:55:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T16:38:06.000Z", "max_issues_repo_path": "lib/lf/geometry/test_utils/check_sub_geometry.cc", "max_issues_repo_name": "Fytch/lehrfempp", "max_issues_repo_head_hexsha": "c804b3e350aa893180f1a02ce57a93b3d7686e91", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 151.0, "max_issues_repo_issues_event_min_datetime": "2018-05-27T13:01:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-04T14:50:50.000Z", "max_forks_repo_path": "lib/lf/geometry/test_utils/check_sub_geometry.cc", "max_forks_repo_name": "Fytch/lehrfempp", "max_forks_repo_head_hexsha": "c804b3e350aa893180f1a02ce57a93b3d7686e91", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20.0, "max_forks_repo_forks_event_min_datetime": "2018-11-13T13:46:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T17:33:52.000Z", "avg_line_length": 42.7634408602, "max_line_length": 79, "alphanum_fraction": 0.636157908, "num_tokens": 955, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568416, "lm_q2_score": 0.6187804478040617, "lm_q1q2_score": 0.4809779497912268}}
{"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_IEEE_FUNCTIONS_SIMD_COMMON_ULPDIST_HPP_INCLUDED\n#define BOOST_SIMD_TOOLBOX_IEEE_FUNCTIONS_SIMD_COMMON_ULPDIST_HPP_INCLUDED\n#include <boost/simd/toolbox/ieee/functions/ulpdist.hpp>\n#include <boost/simd/include/functions/simd/minus.hpp>\n#include <boost/simd/include/functions/simd/divides.hpp>\n#include <boost/simd/include/functions/simd/is_equal.hpp>\n#include <boost/simd/include/functions/simd/is_nan.hpp>\n#include <boost/simd/include/functions/simd/max.hpp>\n#include <boost/simd/include/functions/simd/min.hpp>\n#include <boost/simd/include/functions/simd/abs.hpp>\n#include <boost/simd/include/functions/simd/frexp.hpp>\n#include <boost/simd/include/functions/simd/ldexp.hpp>\n#include <boost/simd/include/functions/simd/if_zero_else.hpp>\n#include <boost/simd/include/functions/simd/if_else.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/constants/eps.hpp>\n#include <boost/simd/include/constants/zero.hpp>\n#include <boost/dispatch/meta/as_integer.hpp>\n\n///////////////////////////////////////////////////////////////////////////////\n// It is often difficult to  answer to the following question:\n//  - are these two floating computations results similar enough ?\n//\n// The ulpdist is a way to answer tuned for relative errors estimations\n// and peculiarity of limited bits accuracy of floating point representation\n// The method is the following:\n//    Properly normalize the two numbers by the same factor in a way that\n//    the largest of the two numbers exponents will be brought to zero\n//\n//    Return this boost::simd::absolute difference of these normalized numbers\n//    divided by the rounding error Eps\n//\n//    The roundind error is the ulp (unit in the last place) value, i.e. the\n//    floating number, the exponent of which is 0 and the mantissa is all zeros\n//    but a 1 in the last digit (it is not hard coded that way however).\n//    Yhis means 2^-23 for floats and 2^-52 for double\n//\n//    For instance if two floating numbers (of same type) have an ulpdist of\n//    zero that means that their floating representation are identical.\n//\n//    Generally equality up to 0.5ulp is the best that one can wish beyond\n//    strict equality.\n//\n//    Typically if a double is compared to the double representation of\n//    its floating conversion (they are exceptions as for fully representable\n//    reals) the ulpdist will be around 2^26.5 (~10^8)\n//\n//    The ulpdist is also roughly equivalent to the number of representable\n//    floating points values between two given floating points values.\n//\n//     ulpdist( 1.0, 1+boost::simd::Eps<double>())   == 0.5\n//     ulpdist( 1.0, 1+boost::simd::Eps<double>()/2) == 0.0\n//     ulpdist( 1.0, 1-boost::simd::Eps<double>()/2) == 0.25\n//     ulpdist( 1.0, 1-boost::simd::Eps<double>())   == 0.5\n//     ulpdist(double(boost::simd::Pi<float>()), boost::simd::Pi<double>()) == 9.84293e+07\n///////////////////////////////////////////////////////////////////////////////\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::ulpdist_, tag::cpu_, (A0)(X)\n                            , ((simd_<arithmetic_<A0>,X>))\n                              ((simd_<arithmetic_<A0>,X>))\n                            )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    {\n      return (max(a0, a1)-min(a0,a1));\n    }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::ulpdist_, tag::cpu_, (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)\n    {\n      typedef typename dispatch::meta::as_integer<A0>::type itype;\n      itype e1, e2;\n      A0 m1, m2;\n      m1 = boost::simd::frexp(a0, e1);\n      m2 = boost::simd::frexp(a1, e2);\n      itype expo = -boost::simd::max(e1, e2);\n      A0 e = select( boost::simd::is_equal(e1, e2)\n                , boost::simd::abs(m1-m2)\n                , boost::simd::abs(boost::simd::ldexp(a0, expo)-boost::simd::ldexp(a1, expo))\n                );\n      return if_zero_else(logical_or(logical_and(is_nan(a0), is_nan(a1)), boost::simd::is_equal(a0, a1)),\n                          e/Eps<A0>());\n    }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "a38dae4077371950979dbd5d6a9527f761eec314", "size": 4886, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/ieee/include/boost/simd/toolbox/ieee/functions/simd/common/ulpdist.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/ieee/include/boost/simd/toolbox/ieee/functions/simd/common/ulpdist.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/ieee/include/boost/simd/toolbox/ieee/functions/simd/common/ulpdist.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.6635514019, "max_line_length": 105, "alphanum_fraction": 0.6209578387, "num_tokens": 1238, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998663336158, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4809779484389515}}
{"text": "#include <ctime>\n#include <cstdlib>\n#include <string>\n#include <iostream>\n#include <fstream>\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n\n#include \"collision_detect.h\"\n\nusing namespace COLLISION_DETECTION;\n\nint main(int argc, char *argv[])\n{\n  std::string filename(\"../meshes/BIG_SCREW.off\");\n\n  RayTracing rt;\n  rt.initialize(filename);\n\n  std::vector<Eigen::Vector3d,Eigen::aligned_allocator<Eigen::Vector3d>> intersections;\n  double begin = std::clock();\n  for (int i = 0; i < 500; ++i) {\n    Eigen::Vector3d n, p;\n    p << 0, 0, 25;\n\n    n(0) = double(std::rand())/double(RAND_MAX) - 0.5;\n    n(1) = double(std::rand())/double(RAND_MAX) - 0.5;\n    n(2) = double(std::rand())/double(RAND_MAX) - 0.5;\n    n.normalize();\n\n    intersections = rt.findIntersections(p, n);\n    if (intersections.size() > 0) {\n      for (int i = 0; i < intersections.size(); ++i) {\n        std::cout << intersections[i][0] << \", \" << intersections[i][1] << \", \" << intersections[i][2] << \" | \";\n      }\n      std::cout << std::endl;\n    }\n    std::cout << \"test No.\" << i << \", intersections: \" << intersections.size() << std::endl;\n  }\n  std::cout << \"Computation Time: \" << (std::clock() - begin) / CLOCKS_PER_SEC << \" sec\" << std::endl;\n}\n", "meta": {"hexsha": "c53cde8860e7d020ee4e63f253071a915c519fde", "size": 1227, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ray_tracing_test.cpp", "max_stars_repo_name": "yifan-hou/triangle-mesh-collision", "max_stars_repo_head_hexsha": "a7fac1eb25ca62e84abbf1bd6f19de797191fe3e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ray_tracing_test.cpp", "max_issues_repo_name": "yifan-hou/triangle-mesh-collision", "max_issues_repo_head_hexsha": "a7fac1eb25ca62e84abbf1bd6f19de797191fe3e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ray_tracing_test.cpp", "max_forks_repo_name": "yifan-hou/triangle-mesh-collision", "max_forks_repo_head_hexsha": "a7fac1eb25ca62e84abbf1bd6f19de797191fe3e", "max_forks_repo_licenses": ["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.2142857143, "max_line_length": 112, "alphanum_fraction": 0.597392013, "num_tokens": 371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.6187804337438502, "lm_q1q2_score": 0.48097794524670995}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2013-2014 Kyle Lutz <kyle.r.lutz@gmail.com>\n//\n// Distributed under the Boost Software License, Version 1.0\n// See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt\n//\n// See http://boostorg.github.com/compute for more information.\n//---------------------------------------------------------------------------//\n\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n\n#include <boost/compute/system.hpp>\n#include <boost/compute/container/vector.hpp>\n#include <boost/compute/image/image2d.hpp>\n#include <boost/compute/interop/opencv/core.hpp>\n#include <boost/compute/interop/opencv/highgui.hpp>\n#include <boost/compute/random/default_random_engine.hpp>\n#include <boost/compute/random/uniform_real_distribution.hpp>\n#include <boost/compute/utility/dim.hpp>\n#include <boost/compute/utility/source.hpp>\n\nnamespace compute = boost::compute;\n\nusing compute::dim;\nusing compute::int_;\nusing compute::float_;\nusing compute::float2_;\n\n// the k-means example implements the k-means clustering algorithm\nint main()\n{\n    // number of clusters\n    size_t k = 6;\n\n    // number of points\n    size_t n_points = 4500;\n\n    // height and width of image\n    size_t height = 800;\n    size_t width = 800;\n\n    // get default device and setup context\n    compute::device gpu = compute::system::default_device();\n    compute::context context(gpu);\n    compute::command_queue queue(context, gpu);\n\n    // generate random, uniformily-distributed points\n    compute::default_random_engine random_engine(queue);\n    compute::uniform_real_distribution<float_> uniform_distribution(0, 800);\n\n    compute::vector<float2_> points(n_points, context);\n    uniform_distribution.generate(\n        compute::make_buffer_iterator<float_>(points.get_buffer(), 0),\n        compute::make_buffer_iterator<float_>(points.get_buffer(), n_points * 2),\n        random_engine,\n        queue\n    );\n\n    // initialize all points to cluster 0\n    compute::vector<int_> clusters(n_points, context);\n    compute::fill(clusters.begin(), clusters.end(), 0, queue);\n\n    // create initial means with the first k points\n    compute::vector<float2_> means(k, context);\n    compute::copy_n(points.begin(), k, means.begin(), queue);\n\n    // k-means clustering program source\n    const char k_means_source[] = BOOST_COMPUTE_STRINGIZE_SOURCE(\n        __kernel void assign_clusters(__global const float2 *points,\n                                      __global const float2 *means,\n                                      const int k,\n                                      __global int *clusters)\n        {\n            const uint gid = get_global_id(0);\n\n            const float2 point = points[gid];\n\n            // find the closest cluster\n            float current_distance = 0;\n            int closest_cluster = -1;\n\n            // find closest cluster mean to the point\n            for(int i = 0; i < k; i++){\n                const float2 mean = means[i];\n\n                int distance_to_mean = distance(point, mean);\n                if(closest_cluster == -1 || distance_to_mean < current_distance){\n                    current_distance = distance_to_mean;\n                    closest_cluster = i;\n                }\n            }\n\n            // write new cluster\n            clusters[gid] = closest_cluster;\n        }\n\n        __kernel void update_means(__global const float2 *points,\n                                   const uint n_points,\n                                   __global float2 *means,\n                                   __global const int *clusters)\n        {\n            const uint k = get_global_id(0);\n\n            float2 sum = { 0, 0 };\n            float count = 0;\n            for(uint i = 0; i < n_points; i++){\n                if(clusters[i] == k){\n                    sum += points[i];\n                    count += 1;\n                }\n            }\n\n            means[k] = sum / count;\n        }\n    );\n\n    // build the k-means program\n    compute::program k_means_program =\n        compute::program::build_with_source(k_means_source, context);\n\n    // setup the k-means kernels\n    compute::kernel assign_clusters_kernel(k_means_program, \"assign_clusters\");\n    assign_clusters_kernel.set_arg(0, points);\n    assign_clusters_kernel.set_arg(1, means);\n    assign_clusters_kernel.set_arg(2, int_(k));\n    assign_clusters_kernel.set_arg(3, clusters);\n\n    compute::kernel update_means_kernel(k_means_program, \"update_means\");\n    update_means_kernel.set_arg(0, points);\n    update_means_kernel.set_arg(1, int_(n_points));\n    update_means_kernel.set_arg(2, means);\n    update_means_kernel.set_arg(3, clusters);\n\n    // run the k-means algorithm\n    for(int iteration = 0; iteration < 25; iteration++){\n        queue.enqueue_1d_range_kernel(assign_clusters_kernel, 0, n_points, 0);\n        queue.enqueue_1d_range_kernel(update_means_kernel, 0, k, 0);\n    }\n\n    // create output image\n    compute::image2d image(\n        context, width, height, compute::image_format(CL_RGBA, CL_UNSIGNED_INT8)\n    );\n\n    // program with two kernels, one to fill the image with white, and then\n    // one the draw to points calculated in coordinates on the image\n    const char draw_walk_source[] = BOOST_COMPUTE_STRINGIZE_SOURCE(\n        __kernel void draw_points(__global const float2 *points,\n                                  __global const int *clusters,\n                                  __write_only image2d_t image)\n        {\n            const uint i = get_global_id(0);\n            const float2 coord = points[i];\n\n            // map cluster number to color\n            uint4 color = { 0, 0, 0, 0 };\n            switch(clusters[i]){\n              case 0:\n                  color = (uint4)(255, 0, 0, 255);\n                  break;\n              case 1:\n                  color = (uint4)(0, 255, 0, 255);\n                  break;\n              case 2:\n                  color = (uint4)(0, 0, 255, 255);\n                  break;\n              case 3:\n                  color = (uint4)(255, 255, 0, 255);\n                  break;\n              case 4:\n                  color = (uint4)(255, 0, 255, 255);\n                  break;\n              case 5:\n                  color = (uint4)(0, 255, 255, 255);\n                  break;\n            }\n\n            // draw a 3x3 pixel point\n            for(int x = -1; x <= 1; x++){\n                for(int y = -1; y <= 1; y++){\n                    if(coord.x + x > 0 && coord.x + x < get_image_width(image) &&\n                       coord.y + y > 0 && coord.y + y < get_image_height(image)){\n                        write_imageui(image, (int2)(coord.x, coord.y) + (int2)(x, y), color);\n                    }\n                }\n            }\n        }\n\n        __kernel void fill_gray(__write_only image2d_t image)\n        {\n            const int2 coord = { get_global_id(0), get_global_id(1) };\n\n            if(coord.x < get_image_width(image) && coord.y < get_image_height(image)){\n                uint4 gray = { 15, 15, 15, 15 };\n                write_imageui(image, coord, gray);\n            }\n        }\n    );\n\n    // build the program\n    compute::program draw_program =\n        compute::program::build_with_source(draw_walk_source, context);\n\n    // fill image with dark gray\n    compute::kernel fill_kernel(draw_program, \"fill_gray\");\n    fill_kernel.set_arg(0, image);\n\n    queue.enqueue_nd_range_kernel(\n        fill_kernel, dim(0, 0), dim(width, height), dim(1, 1)\n    );\n\n    // draw points colored according to cluster\n    compute::kernel draw_kernel(draw_program, \"draw_points\");\n    draw_kernel.set_arg(0, points);\n    draw_kernel.set_arg(1, clusters);\n    draw_kernel.set_arg(2, image);\n    queue.enqueue_1d_range_kernel(draw_kernel, 0, n_points, 0);\n\n    // show image\n    compute::opencv_imshow(\"k-means\", image, queue);\n\n    // wait and return\n    cv::waitKey(0);\n\n    return 0;\n}\n", "meta": {"hexsha": "cd291a9b54743ab54f1e3d653ce11d6770b6ff71", "size": 7987, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/libs/compute/example/k_means.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/compute/example/k_means.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/compute/example/k_means.cpp", "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": 34.7260869565, "max_line_length": 93, "alphanum_fraction": 0.5709277576, "num_tokens": 1809, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.48097794524670984}}
{"text": "/* The MIT License (MIT)\n * Copyright (c) 2014 Nicholas Wright\n * http://opensource.org/licenses/MIT\n */\n\n#include \"../../include/hash/ImagePHash.hpp\"\n#include <string>\n#include <cmath>\n#include <boost/multi_array.hpp>\n#include <log4cplus/logger.h>\n#include <log4cplus/loggingmacros.h>\n#include <log4cplus/configurator.h>\n#include <iomanip>\n#include <ostream>\n#include \"../../include/util/Bit.hpp\"\n\nusing namespace log4cplus;\nusing namespace std;\nusing namespace Magick;\n\n\tImagePHash::ImagePHash() {\n\t\tsize = 32;\n\t\tsmallerSize = 8;\n\t\tinit();\n\t}\n\n\tImagePHash::ImagePHash(int size, int smallerSize) {\n\t\tthis->size = size;\n\t\tthis->smallerSize = smallerSize;\n\n\t\tinit();\n\t}\n\n\tImagePHash::~ImagePHash(){\n\t\tdelete [] c;\n\t}\n\n\tvoid ImagePHash::init() {\n\t\tlogger = Logger::getInstance(LOG4CPLUS_TEXT(\"ImagePHash\"));\n\t\tInitializeMagick(NULL);\n\t\tinitCoefficients();\n\t}\n\n\tlong ImagePHash::getLongHash(string filename) {\n\t\tLOG4CPLUS_DEBUG(logger, \"Opening image \" << filename);\n\t\tImage img(filename);\n\t\tBlob blob;\n\t\timg.write(&blob);\n\n\t\treturn getLongHash(blob);\n\t}\n\n\tlong ImagePHash::getLongHash(Magick::Blob image_data) {\n\t\tdouble avg;\n\t\tlong pHash;\n\n\t\tImage img(image_data);\n\t\tGeometry geo(size, size);\n\t\tgeo.aspect(true);\n\t\timg.scale(geo);\n\t\timg.type(GrayscaleType);\n\t\timg.modifyImage();\n\n\t\tPixels view(img);\n\t\tconst PixelPacket *pixels = view.getConst(0,0,size,size);\n\n\t\tif(pixels == NULL) {\n\t\t\treturn 0L;\n\t\t}\n\n\t\tdctMatrix values = createMatrix();\n\n\t\tint x, y;\n\n\t\tfor (x = 0; x < size; x ++) {\n\t\t\tfor (y = 0; y < size; y++) {\n\t\t\t\tvalues[x][y] = pixels[x + y*size].blue;\n\t\t\t}\n\t\t}\n\n\t\tvalues = applyDCT(values);\n\t\tavg = calcDctAverage(values);\n\t\tpHash = convertToLong(values, avg);\n\n\t\treturn pHash;\n\t}\n\n\t/**\n\t *\n\t * @param is\n\t *            file to hash\n\t * @return hash in as long\n\t * @throws IOException\n\t */\n/*\tlong getLongHash(ofstream is) {\n\t\tdouble[][] dct = calculateDctMap(is);\n\t\tdouble dctAvg = calcDctAverage(dct);\n\t\tlong hash = convertToLong(dct, dctAvg);\n\t\treturn hash;\n\t}\n\n\tlong getLongHash(BufferedImage img) throws Exception {\n\t\tdouble[][] dct = calculateDctMap(img);\n\t\tdouble dctAvg = calcDctAverage(dct);\n\t\tlong hash = convertToLong(dct, dctAvg);\n\t\treturn hash;\n\t}*/\n\n\t/**\n\t *\n\t * @param is\n\t *            file to hash\n\t * @return a 'binary string' (like. 001010111011100010) which is easy to do\n\t *         a hamming distance on.\n\t * @throws IOException\n\t */\n/*\tpublic String getHash(InputStream is) throws IOException {\n\t\tString hash;\n\t\tdouble[][] dct = calculateDctMap(is);\n\t\tdouble dctAvg = calcDctAverage(dct);\n\t\thash = convertToBitString(dct, dctAvg);\n\n\t\treturn hash;\n\t}*/\n\n/*\tprivate double[][] reduceColor(BufferedImage img) {\n\t\tdouble values[][] = new double[size][size];\n\n\t\tfor (int x = 0; x < img.getWidth(); x++) {\n\t\t\tfor (int y = 0; y < img.getHeight(); y++) {\n\t\t\t\tvalues[x][y] = getBlue(img, x, y);\n\t\t\t}\n\t\t}\n\n\t\treturn values;\n\t}*/\n\n/*\tpublic double[][] calculateDctMap(InputStream is) throws IOException {\n\t\tBufferedImage img = readImage(is);\n\t\treturn calculateDctMap(img);\n\t}\n\n\tpublic double[][] calculateDctMap(BufferedImage img) throws IOException {\n\n\n\t\t * 1. Reduce size. Like Average Hash, pHash starts with a small image.\n\t\t * However, the image is larger than 8x8; 32x32 is a good size. This is\n\t\t * really done to simplify the DCT computation and not because it is\n\t\t * needed to reduce the high frequencies.\n\n\t\timg = resize(img, size, size);\n\n\n\t\t * 2. Reduce color. The image is reduced to a grayscale just to further\n\t\t * simplify the number of computations.\n\n\t\timg = grayscale(img);\n\n\t\tdouble[][] vals = reduceColor(img);\n\n\n\t\t * 3. Compute the DCT. The DCT separates the image into a collection of\n\t\t * frequencies and scalars. While JPEG uses an 8x8 DCT, this algorithm\n\t\t * uses a 32x32 DCT.\n\n\t\t// long start = System.currentTimeMillis();\n\t\tdouble[][] dctVals = applyDCT(vals);\n\t\t// System.out.println(\"DCT: \" + (System.currentTimeMillis() - start));\n\t\t// // Removed to prevent system.out spam\n\n\t\treturn dctVals;\n\t}*/\n\n/*\tprivate String convertToBitString(double[][] dctVals, double avg) {\n\n\t\t * 6. Further reduce the DCT. This is the magic step. Set the 64 hash\n\t\t * bits to 0 or 1 depending on whether each of the 64 DCT values is\n\t\t * above or below the average value. The result doesn't tell us the\n\t\t * actual low frequencies; it just tells us the very-rough relative\n\t\t * scale of the frequencies to the mean. The result will not vary as\n\t\t * long as the overall structure of the image remains the same; this can\n\t\t * survive gamma and color histogram adjustments without a problem.\n\n\n\t\tString hash = \"\";\n\n\t\tfor (int x = 0; x < smallerSize; x++) {\n\t\t\tfor (int y = 0; y < smallerSize; y++) {\n\t\t\t\tif (x != 0 && y != 0) {\n\t\t\t\t\thash += (dctVals[x][y] > avg ? \"1\" : \"0\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn hash;\n\t}*/\n\n\tint64_t ImagePHash::convertToLong(dctMatrix dctVals, double avg) {\n\t\tdouble currentValue;\n\n\t\tif (smallerSize > 9) {\n\t\t\tthrow \"The selected smallerSize value is to big for the long datatype\";\n\t\t}\n\n\t\tint64_t hash = 0;\n\n\t\tfor (int x = 0; x < smallerSize; x++) {\n\t\t\tfor (int y = 0; y < smallerSize; y++) {\n\t\t\t\tif (x != 0 && y != 0) {\n\t\t\t\t\tcurrentValue = dctVals[x][y];\n\t\t\t\t\thash += (currentValue > avg ? 1 : 0);\n\t\t\t\t\thash = Bit::rotateLeft(hash);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn hash;\n\t}\n\n\tdouble ImagePHash::calcDctAverage(dctMatrix dctVals) {\n\t\t/*\n\t\t * 4. Reduce the DCT. This is the magic step. While the DCT is 32x32,\n\t\t * just keep the top-left 8x8. Those represent the lowest frequencies in\n\t\t * the picture.\n\t\t */\n\t\t/*\n\t\t * 5. Compute the average value. Like the Average Hash, compute the mean\n\t\t * DCT value (using only the 8x8 DCT low-frequency values and excluding\n\t\t * the first term since the DC coefficient can be significantly\n\t\t * different from the other values and will throw off the average).\n\t\t */\n\t\tdouble total = 0;\n\n\t\tfor (int x = 0; x < smallerSize; x++) {\n\t\t\tfor (int y = 0; y < smallerSize; y++) {\n\t\t\t\ttotal += dctVals[x][y];\n\t\t\t}\n\t\t}\n\t\ttotal -= dctVals[0][0];\n\n\t\tdouble avg = total / (double) ((smallerSize * smallerSize) - 1);\n\t\treturn avg;\n\t}\n\n/*\tprivate BufferedImage resize(BufferedImage image, int width, int height) {\n\t\tBufferedImage resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);\n\t\tGraphics2D g = resizedImage.createGraphics();\n\t\tg.drawImage(image, 0, 0, width, height, null);\n\t\tg.dispose();\n\t\treturn resizedImage;\n\t}\n\n\tprivate ColorConvertOp colorConvert = new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY), null);\n\n\tprivate BufferedImage grayscale(BufferedImage img) {\n\t\tcolorConvert.filter(img, img);\n\t\treturn img;\n\t}\n\n\tprivate static int getBlue(BufferedImage img, int x, int y) {\n\t\treturn (img.getRGB(x, y)) & 0xff;\n\t}*/\n\n\t// DCT function stolen from\n\t// http://stackoverflow.com/questions/4240490/problems-with-dct-and-idct-algorithm-in-java\n\n\tvoid ImagePHash::initCoefficients() {\n\t\tc = new double[size];\n\n\t\tfor (int i = 1; i < size; i++) {\n\t\t\tc[i] = 1;\n\t\t}\n\n\t\tc[0] = 1 / sqrt((double)(2.0)); //sqrt(2.0);\n\t}\n\n\tImagePHash::dctMatrix ImagePHash::applyDCT(dctMatrix f) {\n\t\tint N = size;\n\n\t\tdctMatrix F = createMatrix();\n\t\tfor (int u = 0; u < N; u++) {\n\t\t\tfor (int v = 0; v < N; v++) {\n\t\t\t\tdouble sum = 0.0;\n\t\t\t\tfor (int i = 0; i < N; i++) {\n\t\t\t\t\tfor (int j = 0; j < N; j++) {\n\t\t\t\t\t\tsum += std::cos(((2 * i + 1) / (2.0 * N)) * u * M_PI) * std::cos(((2 * j + 1) / (2.0 * N)) * v * M_PI)\n\t\t\t\t\t\t\t\t* (f[i][j]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tsum *= ((c[u] * c[v]) / 4.0);\n\t\t\t\tF[u][v] = sum;\n\t\t\t}\n\t\t}\n\t\treturn F;\n\t}\n\n\tImagePHash::dctMatrix ImagePHash::createMatrix() {\n\t\t  boost::array<dctMatrix::index, 2> shape = {{size, size}};\n\t\t  dctMatrix matrix(shape);\n\t\treturn matrix;\n}\n\n", "meta": {"hexsha": "bbd98b411fb7fcd8a64afb932a472e7b5f428c62", "size": 7571, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main/hash/ImagePHash.cpp", "max_stars_repo_name": "dozedoff/commoncpp", "max_stars_repo_head_hexsha": "672bb5313e1af49f6d3f6c97015f6cbb141dfa2d", "max_stars_repo_licenses": ["MIT"], "max_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/hash/ImagePHash.cpp", "max_issues_repo_name": "dozedoff/commoncpp", "max_issues_repo_head_hexsha": "672bb5313e1af49f6d3f6c97015f6cbb141dfa2d", "max_issues_repo_licenses": ["MIT"], "max_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/hash/ImagePHash.cpp", "max_forks_repo_name": "dozedoff/commoncpp", "max_forks_repo_head_hexsha": "672bb5313e1af49f6d3f6c97015f6cbb141dfa2d", "max_forks_repo_licenses": ["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.1528239203, "max_line_length": 108, "alphanum_fraction": 0.6431118743, "num_tokens": 2244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4809779452467098}}
{"text": "//  (C) Copyright Nick Thompson 2021.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n#ifndef BOOST_MATH_TOOLS_CUBIC_ROOTS_HPP\n#define BOOST_MATH_TOOLS_CUBIC_ROOTS_HPP\n#include <algorithm>\n#include <array>\n#include <boost/math/special_functions/sign.hpp>\n#include <boost/math/tools/roots.hpp>\n\nnamespace boost::math::tools {\n\n// Solves ax^3 + bx^2 + cx + d = 0.\n// Only returns the real roots, as types get weird for real coefficients and\n// complex roots. Follows Numerical Recipes, Chapter 5, section 6. NB: A better\n// algorithm apparently exists: Algorithm 954: An Accurate and Efficient Cubic\n// and Quartic Equation Solver for Physical Applications However, I don't have\n// access to that paper!\ntemplate <typename Real>\nstd::array<Real, 3> cubic_roots(Real a, Real b, Real c, Real d) {\n    using std::abs;\n    using std::acos;\n    using std::cbrt;\n    using std::cos;\n    using std::fma;\n    using std::sqrt;\n    std::array<Real, 3> roots = {std::numeric_limits<Real>::quiet_NaN(),\n                                 std::numeric_limits<Real>::quiet_NaN(),\n                                 std::numeric_limits<Real>::quiet_NaN()};\n    if (a == 0) {\n        // bx^2 + cx + d = 0:\n        if (b == 0) {\n            // cx + d = 0:\n            if (c == 0) {\n                if (d != 0) {\n                    // No solutions:\n                    return roots;\n                }\n                roots[0] = 0;\n                roots[1] = 0;\n                roots[2] = 0;\n                return roots;\n            }\n            roots[0] = -d / c;\n            return roots;\n        }\n        auto [x0, x1] = quadratic_roots(b, c, d);\n        roots[0] = x0;\n        roots[1] = x1;\n        return roots;\n    }\n    if (d == 0) {\n        auto [x0, x1] = quadratic_roots(a, b, c);\n        roots[0] = x0;\n        roots[1] = x1;\n        roots[2] = 0;\n        std::sort(roots.begin(), roots.end());\n        return roots;\n    }\n    Real p = b / a;\n    Real q = c / a;\n    Real r = d / a;\n    Real Q = (p * p - 3 * q) / 9;\n    Real R = (2 * p * p * p - 9 * p * q + 27 * r) / 54;\n    if (R * R < Q * Q * Q) {\n        Real rtQ = sqrt(Q);\n        Real theta = acos(R / (Q * rtQ)) / 3;\n        Real st = sin(theta);\n        Real ct = cos(theta);\n        roots[0] = -2 * rtQ * ct - p / 3;\n        roots[1] = -rtQ * (-ct + sqrt(Real(3)) * st) - p / 3;\n        roots[2] = rtQ * (ct + sqrt(Real(3)) * st) - p / 3;\n    } else {\n        // In Numerical Recipes, Chapter 5, Section 6, it is claimed that we\n        // only have one real root if R^2 >= Q^3. But this isn't true; we can\n        // even see this from equation 5.6.18. The condition for having three\n        // real roots is that A = B. It *is* the case that if we're in this\n        // branch, and we have 3 real roots, two are a double root. Take\n        // (x+1)^2(x-2) = x^3 - 3x -2 as an example. This clearly has a double\n        // root at x = -1, and it gets sent into this branch.\n        Real arg = R * R - Q * Q * Q;\n        Real A = (R >= 0 ? -1 : 1) * cbrt(abs(R) + sqrt(arg));\n        Real B = 0;\n        if (A != 0) {\n            B = Q / A;\n        }\n        roots[0] = A + B - p / 3;\n        // Yes, we're comparing floats for equality:\n        // Any perturbation pushes the roots into the complex plane; out of the\n        // bailiwick of this routine.\n        if (A == B || arg == 0) {\n            roots[1] = -A - p / 3;\n            roots[2] = -A - p / 3;\n        }\n    }\n    // Root polishing:\n    for (auto &r : roots) {\n        // Horner's method.\n        // Here I'll take John Gustaffson's opinion that the fma is a *distinct*\n        // operation from a*x +b: Make sure to compile these fmas into a single\n        // instruction and not a function call! (I'm looking at you Windows.)\n        Real f = fma(a, r, b);\n        f = fma(f, r, c);\n        f = fma(f, r, d);\n        Real df = fma(3 * a, r, 2 * b);\n        df = fma(df, r, c);\n        if (df != 0) {\n            Real d2f = fma(6 * a, r, 2 * b);\n            Real denom = 2 * df * df - f * d2f;\n            if (denom != 0) {\n                r -= 2 * f * df / denom;\n            } else {\n                r -= f / df;\n            }\n        }\n    }\n    std::sort(roots.begin(), roots.end());\n    return roots;\n}\n\n// Computes the empirical residual p(r) (first element) and expected residual\n// eps*|rp'(r)| (second element) for a root. Recall that for a numerically\n// computed root r satisfying r = r_0(1+eps) of a function p, |p(r)| <=\n// eps|rp'(r)|.\ntemplate <typename Real>\nstd::array<Real, 2> cubic_root_residual(Real a, Real b, Real c, Real d,\n                                        Real root) {\n    using std::abs;\n    using std::fma;\n    std::array<Real, 2> out;\n    Real residual = fma(a, root, b);\n    residual = fma(residual, root, c);\n    residual = fma(residual, root, d);\n\n    out[0] = residual;\n\n    // The expected residual is:\n    // eps*[4|ar^3| + 3|br^2| + 2|cr| + |d|]\n    // This can be demonstrated by assuming the coefficients and the root are\n    // perturbed according to the rounding model of floating point arithmetic,\n    // and then working through the inequalities.\n    root = abs(root);\n    Real expected_residual = fma(4 * abs(a), root, 3 * abs(b));\n    expected_residual = fma(expected_residual, root, 2 * abs(c));\n    expected_residual = fma(expected_residual, root, abs(d));\n    out[1] = expected_residual * std::numeric_limits<Real>::epsilon();\n    return out;\n}\n\n// Computes the condition number of rootfinding. This is defined in Corless, A\n// Graduate Introduction to Numerical Methods, Section 3.2.1.\ntemplate <typename Real>\nReal cubic_root_condition_number(Real a, Real b, Real c, Real d, Real root) {\n    using std::abs;\n    using std::fma;\n    // There are *absolute* condition numbers that can be defined when r = 0;\n    // but they basically reduce to the residual computed above.\n    if (root == static_cast<Real>(0)) {\n        return std::numeric_limits<Real>::infinity();\n    }\n\n    Real numerator = fma(abs(a), abs(root), abs(b));\n    numerator = fma(numerator, abs(root), abs(c));\n    numerator = fma(numerator, abs(root), abs(d));\n    Real denominator = fma(3 * a, root, 2 * b);\n    denominator = fma(denominator, root, c);\n    if (denominator == static_cast<Real>(0)) {\n        return std::numeric_limits<Real>::infinity();\n    }\n    denominator *= root;\n    return numerator / abs(denominator);\n}\n\n} // namespace boost::math::tools\n#endif\n", "meta": {"hexsha": "451c5de8133686f8f3b271b73b415d5a483b893b", "size": 6553, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "AqooleEngine/src/main/cpp/boost/boost/math/tools/cubic_roots.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/tools/cubic_roots.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/tools/cubic_roots.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": 37.0225988701, "max_line_length": 80, "alphanum_fraction": 0.5457042576, "num_tokens": 1915, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4809779452467098}}
{"text": "//==================================================================================================\n/**\n  EVE - Expressive Vector Engine\n  Copyright : EVE Contributors & Maintainers\n  SPDX-License-Identifier: MIT\n**/\n//==================================================================================================\n#include <boost/math/special_functions/gegenbauer.hpp>\n#include <eve/function/gegenbauer.hpp>\n#include <eve/platform.hpp>\n#include <cmath>\n\nTTS_CASE_TPL(\"Check eve::gegenbauer return type\", EVE_TYPE)\n{\n  TTS_EXPR_IS(eve::gegenbauer(0, T(0), T(0)), T);\n}\n\nTTS_CASE_TPL(\"Check eve::gegenbauer behavior\", EVE_TYPE)\n{\n  using elt_t = eve::element_type_t<T>;\n  elt_t l(-3.0/8.0);\n  auto eve__gegenbauer =  [&l](unsigned n, auto x) { return eve::gegenbauer(n, T(l), x); };\n  auto boost_gegenbauer =  [&l](unsigned n, auto x) { return boost::math::gegenbauer(n, double(l), x); };\n\n  for(unsigned int i=0; i < 10; ++i)\n  {\n    TTS_ULP_EQUAL(eve__gegenbauer(i, T(10)), T(boost_gegenbauer(i, 10.0)), 2);\n    TTS_ULP_EQUAL(eve__gegenbauer(i, T(5)), T(boost_gegenbauer(i, 5.0)), 1);\n    TTS_ULP_EQUAL(eve__gegenbauer(i, T(2)), T(boost_gegenbauer(i, 2.0)), 1);\n    TTS_ULP_EQUAL(eve__gegenbauer(i, T(1)), T(boost_gegenbauer(i, 1.0)), 20);\n    TTS_ULP_EQUAL(eve__gegenbauer(i, T(0)), T(boost_gegenbauer(i, 0.0)), 1);\n  }\n}\n", "meta": {"hexsha": "88665f77ea9c3761cae354d73e3825ce74cff46b", "size": 1328, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/unit/module/real/core/gegenbauer/regular/gegenbauer.hpp", "max_stars_repo_name": "orao/eve", "max_stars_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_stars_repo_licenses": ["MIT"], "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/unit/module/real/core/gegenbauer/regular/gegenbauer.hpp", "max_issues_repo_name": "orao/eve", "max_issues_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_issues_repo_licenses": ["MIT"], "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/unit/module/real/core/gegenbauer/regular/gegenbauer.hpp", "max_forks_repo_name": "orao/eve", "max_forks_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_forks_repo_licenses": ["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.0588235294, "max_line_length": 105, "alphanum_fraction": 0.5760542169, "num_tokens": 422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.6187804267137442, "lm_q1q2_score": 0.48097793978220954}}
{"text": "// test performance.cpp : Defines the entry point for the console application.\n//\n\n#include <cstdio>\n#include <cstdint>\n#include <iostream>\n#include <chrono>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/multiprecision/integer.hpp>\n\n#include <boost/safe_numerics/safe_integer.hpp>\n\ntypedef boost::safe_numerics::safe<unsigned> safe_type;\n\nnamespace boost {\nnamespace multiprecision {\n\n    template <class Integer, class I2>\n    typename enable_if_c<boost::safe_numerics::is_safe<Integer>::value, Integer&>::type\n    multiply(Integer& result, const I2& a, const I2& b){\n        return result = static_cast<Integer>(a) * static_cast<Integer>(b);\n    }\n\n    template <class Integer>\n    typename enable_if_c<boost::safe_numerics::is_safe<Integer>::value, bool>::type\n    bit_test(const Integer& val, unsigned index){\n        Integer mask = 1;\n        if (index >= sizeof(Integer) * CHAR_BIT)\n            return 0;\n        if (index)\n            mask <<= index;\n        return val & mask ? true : false;\n    }\n\n    template <class I1, class I2>\n    typename enable_if_c<boost::safe_numerics::is_safe<I1>::value, I2>::type\n    integer_modulus(const I1& x, I2 val){\n        return x % val;\n    }\n\n    namespace detail {\n        template <class T> struct double_integer;\n\n        template <>\n        struct double_integer<safe_type>{\n            using type = boost::safe_numerics::safe<std::uint64_t>;\n        };\n    }\n\n    template <class I1, class I2, class I3>\n    typename enable_if_c<boost::safe_numerics::is_safe<I1>::value, I1>::type\n    powm(const I1& a, I2 b, I3 c){\n        typedef typename detail::double_integer<I1>::type double_type;\n\n        I1 x(1), y(a);\n        double_type result;\n\n        while (b > 0){\n            if (b & 1){\n                multiply(result, x, y);\n                x = integer_modulus(result, c);\n            }\n            multiply(result, y, y);\n            y = integer_modulus(result, c);\n            b >>= 1;\n        }\n        return x % c;\n    }\n\n    template <class T, class PP, class EP>\n    inline unsigned\n    lsb(const boost::safe_numerics::safe<T, PP, EP>& x){\n        return lsb(static_cast<T>(x));\n    }\n\n} }\n\n#include <boost/multiprecision/miller_rabin.hpp>\n\ntemplate <class Clock>\nclass stopwatch\n{\n    const typename Clock::time_point m_start;\npublic:\n    stopwatch() :\n        m_start(Clock::now())\n    {}\n    typename Clock::duration elapsed() const {\n        return Clock::now() - m_start;\n    }\n};\n\ntemplate<typename T>\nvoid test(const char * msg){\n    const stopwatch<std::chrono::high_resolution_clock> c;\n\n    unsigned count = 0;\n    for (T i = 3; i < 30000000; ++i)\n        if (boost::multiprecision::miller_rabin_test(i, 25)) ++count;\n\n    std::chrono::duration<double> time = c.elapsed();\n    std::cout<< msg << \":\\ntime = \" << time.count();\n    std::cout << \"\\ncount = \" << count << std::endl;\n}\n\nint main()\n{\n    test<unsigned>(\"Testing type unsigned\");\n    test<boost::safe_numerics::safe<unsigned>>(\"Testing type safe<unsigned>\");\n    return 0;\n}\n\n", "meta": {"hexsha": "364a76715bd7b5b5165ae367ad17ed4a009ecf5c", "size": 3022, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_performance.cpp", "max_stars_repo_name": "giomasce-throwaway/safe_numerics", "max_stars_repo_head_hexsha": "3a1676e5831bab93b9be50caec69c1887a4af7da", "max_stars_repo_licenses": ["BSL-1.0"], "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": "test/test_performance.cpp", "max_issues_repo_name": "giomasce-throwaway/safe_numerics", "max_issues_repo_head_hexsha": "3a1676e5831bab93b9be50caec69c1887a4af7da", "max_issues_repo_licenses": ["BSL-1.0"], "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": "test/test_performance.cpp", "max_forks_repo_name": "giomasce-throwaway/safe_numerics", "max_forks_repo_head_hexsha": "3a1676e5831bab93b9be50caec69c1887a4af7da", "max_forks_repo_licenses": ["BSL-1.0"], "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": 26.7433628319, "max_line_length": 87, "alphanum_fraction": 0.6144937128, "num_tokens": 764, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568416, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4809779388622264}}
{"text": "/*\n Copyright (C) 2017 Quaternion Risk Management Ltd\n All rights reserved.\n\n This file is part of ORE, a free-software/open-source library\n for transparent pricing and risk analysis - http://opensourcerisk.org\n\n ORE is free software: you can redistribute it and/or modify it\n under the terms of the Modified BSD License.  You should have received a\n copy of the license along with this program.\n The license is also available online at <http://opensourcerisk.org>\n\n This program is distributed on the basis that it will form a useful\n contribution to risk analytics and model standardisation, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.\n*/\n\n/*! \\file qle/termstructures/equityvolconstantspread.hpp\n    \\brief equity surface that combines an ATM curve and vol spreads from a surface\n    \\ingroup termstructures\n*/\n\n#ifndef quantext_equityvolatilityconstantspread_hpp\n#define quantext_equityvolatilityconstantspread_hpp\n\n#include <boost/shared_ptr.hpp>\n#include <ql/termstructures/volatility/equityfx/blackvariancecurve.hpp>\n#include <ql/termstructures/volatility/equityfx/blackvariancesurface.hpp>\n#include <ql/termstructures/volatility/equityfx/blackvoltermstructure.hpp>\n\nnamespace QuantExt {\nusing namespace QuantLib;\n\n//! Equity cube that combines an ATM matrix and vol spreads from a cube\n/*! Notice that the TS has a floating reference date and accesses the source TS only via\n their time-based volatility methods.\n\n \\warning the given atm vol structure should be strike independent, this is not checked\n*/\nclass EquityVolatilityConstantSpread : public BlackVolTermStructure {\npublic:\n    EquityVolatilityConstantSpread(const Handle<BlackVolTermStructure>& atm,\n                                   const Handle<BlackVolTermStructure>& surface)\n        : BlackVolTermStructure(0, atm->calendar(), atm->businessDayConvention(), atm->dayCounter()), atm_(atm),\n          surface_(surface) {\n        enableExtrapolation(atm->allowsExtrapolation());\n        registerWith(atm);\n        registerWith(surface);\n    }\n\n    //! \\name TermStructure interface\n    //@{\n    DayCounter dayCounter() const { return atm_->dayCounter(); }\n    Date maxDate() const { return atm_->maxDate(); }\n    Time maxTime() const { return atm_->maxTime(); }\n    const Date& referenceDate() const { return atm_->referenceDate(); }\n    Calendar calendar() const { return atm_->calendar(); }\n    Natural settlementDays() const { return atm_->settlementDays(); }\n    //@}\n    //! \\name VolatilityTermStructure interface\n    //@{\n    Rate minStrike() const { return surface_->minStrike(); }\n    Rate maxStrike() const { return surface_->maxStrike(); }\n    //@}\n\nprotected:\n    Volatility blackVolImpl(Time t, Rate strike) const {\n        Real s = surface_->blackVol(t, strike, true) - surface_->blackVol(t, Null<Real>(), true);\n        Real v = atm_->blackVol(t, Null<Real>(), true);\n        return v + s;\n    }\n\n    Real blackVarianceImpl(Time t, Real strike) const {\n        Real vol = blackVolImpl(t, strike);\n        return vol * vol * t;\n    }\n\nprivate:\n    Handle<BlackVolTermStructure> atm_, surface_;\n};\n\n} // namespace QuantExt\n\n#endif\n", "meta": {"hexsha": "47f4fe1650a6d41c9da7c1ba30c8b4a36f5f621b", "size": 3222, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "QuantExt/qle/termstructures/equityvolconstantspread.hpp", "max_stars_repo_name": "PiotrSiejda/Engine", "max_stars_repo_head_hexsha": "8360b5de32408f2a37da5ac3ca7b4e913bf67e9f", "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/equityvolconstantspread.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/equityvolconstantspread.hpp", "max_forks_repo_name": "zhangjiayin/Engine", "max_forks_repo_head_hexsha": "a5ee0fc09d5a50ab36e50d55893b6e484d6e7004", "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": 37.4651162791, "max_line_length": 112, "alphanum_fraction": 0.7243947858, "num_tokens": 720, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568416, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4809779388622264}}
{"text": "\n/*\n * ConvecMatrixEquationSolverQP.hpp\n *\n *  Created on: August 20, 2020\n *      Author: Quincy Jones\n *\n * Copyright (c) <2020> <Quincy Jones - quincy@implementedrobotics.com/>\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the Software\n * is furnished to do so, subject to the following conditions:\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n\n#ifndef NOMAD_CORE_OPTIMALCONTROL_CONVEXMATRIXEQUATIONSOLVERQP_H_\n#define NOMAD_CORE_OPTIMALCONTROL_CONVEXMATRIXEQUATIONSOLVERQP_H_\n\n// C System Files\n\n// C++ System Files\n#include <iostream>\n\n// Third Party Includes\n#include <Eigen/Dense>\n#include <qpOASES.hpp>\n\n// Project Includes\n#include <Common/Math/MathUtils.hpp>\n\n\n// Helper class to solve a system of linear equations of the form: A * x = b\n// In general you would use this is there is reduncancy in the system (Number of equations/Number of unknowns)\n// Therefore this is only solved in a somewhat \"least squares sense\" by exploiting variable weighting and inequality constraints to handle\n// the reduncancy in the sysytem.  This is good because the redundancy in the system allows you to meet secondary objectives.\n\n// x* = min(Ax-b)^T * S * (A*x-b) + alpha*x^T*W1*x + beta*(x-x_prev)^T * W2 * (x-x_prev))\n// s.t. lb < C*x < ub\n\n// Maps to a standard QP Formulation using qpOases:\n//\n// min x      1/2*x^T*H*x + x^t*g\n// s.t. lb < A_qp*x > ub // Inequality Contraints\n\n// x* = optimal solution (Num Equations)\n// S  = Relative priority of decision variables (Num Equations x Num Equations)\n// alpha = decision variable minimization weight (scalar)\n// W1   = Relative priority of weight minimization on decision variables (Num Variables x Num Variables)\n// beta = solution filtering from a previous solution.  Helps with smoothing from a previous solution (scalar)\n// W2   = Relative priority of weight smoothing on decision variables (Num Variables x Num Variables)\n// C    = Constraint matrix for solution (Num inequality constraints x Num Variables)\n\nnamespace Core::OptimalControl\n{\n    class ConvexLinearSystemSolverQP\n    {\n\n    public:\n        // Base Class ConvexLinearSystemSolverQP\n        // num_eq = Number of equations of OCP\n        // num_vars = Number of veriables of OCP\n        ConvexLinearSystemSolverQP(const unsigned int num_eq, const unsigned int num_vars, const unsigned int num_constraints);\n\n        // Solve\n        virtual void Solve();\n\n        // Return Current Solution X\n        Eigen::VectorXd X() const { return x_star_; }\n\n        double GetSolverTime() const { return solver_time_; }\n\n        void EnableQPDebug(bool enable);\n        void PrintDebug();\n\n    protected:\n\n        qpOASES::SQProblem qp_;        // qpOases Solver Object\n\n        qpOASES::int_t max_iterations_;    // Max Iterations for Solver\n        qpOASES::int_t solver_iterations_; // Total number of Solver iterations for solution\n\n        Eigen::MatrixXd A_;           // Coefficient Matrix\n        Eigen::VectorXd x_star_;      // Solution Vector\n        Eigen::VectorXd x_star_prev_; // Previous Solutions Vector\n        Eigen::VectorXd b_;           // Constant Vector\n\n        Eigen::MatrixXd S_;           // Relative Priority Weighting of Values\n        Eigen::MatrixXd W_1_;         // Relative Priority Weighting of Solution Minimization\n        Eigen::MatrixXd W_2_;         // Relative Priority Weighting of Solution Filtering Minimization\n        //Eigen::MatrixXd C_;         // Inequality Constraint Matrix\n\n        Eigen::VectorXd lbA_; // Lower Bound of Inequality Constraint Matrix\n        Eigen::VectorXd ubA_; // Upper Bound of Inequality Constraint Matrix\n\n        Eigen::MatrixXd H_qp_; // QP Hessian\n        Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> A_qp_; // Inequality Constraint Matrix QP\n        Eigen::VectorXd g_qp_; // Linear\n\n        double alpha_; // Influence of Solution Minimization\n        double beta_;  // Influece of Solution Filtering\n\n        int num_equations_;   // Number of System Equations\n        int num_variables_;   // Number of System Variables\n        int num_constraints_; // Number of Inequality Constraints\n\n        double solver_time_; // Total time for Solver to compute a solution\n\n        bool solved_; // Valid Solution?\n\n        bool is_hot_; // We have a warm QP and can use hotstarting\n\n        // TODO:\n        // Infeasible, BlahBlah\n    };\n} // namespace Core::OptimalControl\n\n#endif // NOMAD_CORE_OPTIMALCONTROL_CONVEXMATRIXEQUATIONSOLVERQP_H_\n", "meta": {"hexsha": "e684d2c1f7431033c4d05c92b21824e89167c144", "size": 5351, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Software/Core/OptimalControl/include/OptimalControl/ConvexMatrixEquationSolverQP.hpp", "max_stars_repo_name": "implementedrobotics/Nomad", "max_stars_repo_head_hexsha": "de8c27ed79cdcde59b1fd6e9a0865d29b84b7d58", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2019-08-11T18:24:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T01:22:55.000Z", "max_issues_repo_path": "Software/Core/OptimalControl/include/OptimalControl/ConvexMatrixEquationSolverQP.hpp", "max_issues_repo_name": "implementedrobotics/Nomad", "max_issues_repo_head_hexsha": "de8c27ed79cdcde59b1fd6e9a0865d29b84b7d58", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 15.0, "max_issues_repo_issues_event_min_datetime": "2019-05-29T12:57:20.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-29T02:26:06.000Z", "max_forks_repo_path": "Software/Core/OptimalControl/include/OptimalControl/ConvexMatrixEquationSolverQP.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": 42.1338582677, "max_line_length": 138, "alphanum_fraction": 0.7080919454, "num_tokens": 1225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568416, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4809779388622264}}
{"text": "#include <string>\n#include <vector>\n#include <unordered_map>\n#include <unordered_set>\n#include <iostream>\n#include <fstream>\n#include <cassert>\n#include <memory>\n\n#include <Eigen/Dense>\n#include \"Components.h\"\n#include \"Network.h\"\n// #include \"spdlog/spdlog.h\"\n\nusing Eigen::MatrixXd;\n\nint main(int argc, char const *argv[])\n{\n    if (argc != 2){\n        std::cout << \"Incorrect usage\" << std::endl;\n        return -1;\n    }\n    // spdlog::info(\"Welcome to spdlog!\");\n    std::ifstream net_file (argv[1]);\n    if (!net_file.is_open()){\n        std::cout << \"Failed to open in file\" << std::endl;\n        return -1;\n    }\n    Network net = Network();\n    net.preprocess_netlist(net_file);\n    net.parse_netlist(net_file);\n    net.calculate();\n\n\tstd::cout << \"Conductance\\n\" << net.get_conductance_matrix() << '\\n';\n\tstd::cout << \"Incidence\\n\" << net.get_incidence_matrix() << '\\n';\n\tstd::cout << \"z\\n\" << net.get_z_matrix() << '\\n';\n\tstd::cout << \"result\\n\" << net.get_result_matrix() << '\\n';\n\tnet_file.close();\n    return 0;\n}\n\n// <comp type><name> <+> <-> <value>\n// https://lpsa.swarthmore.edu/Systems/Electrical/mna/MNA3.html#Notational_Convention\n/*todo: \n\t- look at initializing node 0 to id -1, gets rid of us having to use offset\n*/ ", "meta": {"hexsha": "6511603b1129acf8f16b7465c9c00f4581584b3a", "size": 1241, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/spice_main.cpp", "max_stars_repo_name": "appiad/spice", "max_stars_repo_head_hexsha": "b82709d9334efa3264f37b7e8eb55130f9e494c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/spice_main.cpp", "max_issues_repo_name": "appiad/spice", "max_issues_repo_head_hexsha": "b82709d9334efa3264f37b7e8eb55130f9e494c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/spice_main.cpp", "max_forks_repo_name": "appiad/spice", "max_forks_repo_head_hexsha": "b82709d9334efa3264f37b7e8eb55130f9e494c3", "max_forks_repo_licenses": ["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.9782608696, "max_line_length": 85, "alphanum_fraction": 0.6285253828, "num_tokens": 344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568415, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.48097793886222634}}
{"text": "// This file is part of libigl, a simple c++ geometry processing library.\n//\n// Copyright (C) 2013 Alec Jacobson <alecjacobson@gmail.com>\n//\n// This Source Code Form is subject to the terms of the Mozilla Public License\n// v. 2.0. If a copy of the MPL was not distributed with this file, You can\n// obtain one at http://mozilla.org/MPL/2.0/.\n#include \"bbw.h\"\n\n#include <igl/cotmatrix.h>\n#include <igl/massmatrix.h>\n#include <igl/invert_diag.h>\n#include <igl/speye.h>\n#include <igl/slice_into.h>\n#include <igl/min_quad_with_fixed.h>\n\n#include <Eigen/Sparse>\n\n#include <iostream>\n#include <cstdio>\n\nigl::bbw::BBWData::BBWData():\n  partition_unity(false),\n  W0(),\n#ifndef IGL_NO_MOSEK\n  mosek_data(),\n#endif\n  active_set_params(),\n  qp_solver(QP_SOLVER_IGL_ACTIVE_SET),\n  verbosity(0)\n{\n  // We know that the Bilaplacian is positive semi-definite\n  active_set_params.Auu_pd = true;\n}\n\nvoid igl::bbw::BBWData::print()\n{\n  using namespace std;\n  cout<<\"partition_unity: \"<<partition_unity<<endl;\n  cout<<\"W0=[\"<<endl<<W0<<endl<<\"];\"<<endl;\n  cout<<\"qp_solver: \"<<QPSolverNames[qp_solver]<<endl;\n}\n\n\ntemplate <\n  typename DerivedV,\n  typename DerivedEle,\n  typename Derivedb,\n  typename Derivedbc,\n  typename DerivedW>\nIGL_INLINE bool igl::bbw::bbw(\n  const Eigen::PlainObjectBase<DerivedV> & V,\n  const Eigen::PlainObjectBase<DerivedEle> & Ele,\n  const Eigen::PlainObjectBase<Derivedb> & b,\n  const Eigen::PlainObjectBase<Derivedbc> & bc,\n  igl::bbw::BBWData & data,\n  Eigen::PlainObjectBase<DerivedW> & W\n  )\n{\n  using namespace std;\n  using namespace Eigen;\n\n  // number of domain vertices\n  int n = V.rows();\n  // number of handles\n  int m = bc.cols();\n\n  SparseMatrix<typename DerivedW::Scalar> L;\n  cotmatrix(V,Ele,L);\n  MassMatrixType mmtype = MASSMATRIX_TYPE_VORONOI;\n  if(Ele.cols() == 4)\n  {\n    mmtype = MASSMATRIX_TYPE_BARYCENTRIC;\n  }\n  SparseMatrix<typename DerivedW::Scalar> M;\n  SparseMatrix<typename DerivedW::Scalar> Mi;\n  massmatrix(V,Ele,mmtype,M);\n\n  invert_diag(M,Mi);\n\n  // Biharmonic operator\n  SparseMatrix<typename DerivedW::Scalar> Q = L.transpose() * Mi * L;\n\n  W.derived().resize(n,m);\n  if(data.partition_unity)\n  {\n    // Not yet implemented\n    assert(false);\n  }else\n  {\n    // No linear terms\n    VectorXd c = VectorXd::Zero(n);\n    // No linear constraints\n    SparseMatrix<typename DerivedW::Scalar> A(0,n),Aeq(0,n),Aieq(0,n);\n    VectorXd uc(0,1),Beq(0,1),Bieq(0,1),lc(0,1);\n    // Upper and lower box constraints (Constant bounds)\n    VectorXd ux = VectorXd::Ones(n);\n    VectorXd lx = VectorXd::Zero(n);\n    active_set_params eff_params = data.active_set_params;\n    switch(data.qp_solver)\n    {\n      case QP_SOLVER_IGL_ACTIVE_SET:\n      {\n        if(data.verbosity >= 1)\n        {\n          cout<<\"BBW: max_iter: \"<<data.active_set_params.max_iter<<endl;\n          cout<<\"BBW: eff_max_iter: \"<<eff_params.max_iter<<endl;\n        }\n        if(data.verbosity >= 1)\n        {\n          cout<<\"BBW: Computing initial weights for \"<<m<<\" handle\"<<\n            (m!=1?\"s\":\"\")<<\".\"<<endl;\n        }\n        min_quad_with_fixed_data<typename DerivedW::Scalar > mqwf;\n        min_quad_with_fixed_precompute(Q,b,Aeq,true,mqwf);\n        min_quad_with_fixed_solve(mqwf,c,bc,Beq,W);\n        // decrement\n        eff_params.max_iter--;\n        bool error = false;\n        // Loop over handles\n#pragma omp parallel for\n        for(int i = 0;i<m;i++)\n        {\n          // Quicker exit for openmp\n          if(error)\n          {\n            continue;\n          }\n          if(data.verbosity >= 1)\n          {\n#pragma omp critical\n            cout<<\"BBW: Computing weight for handle \"<<i+1<<\" out of \"<<m<<\n              \".\"<<endl;\n          }\n          VectorXd bci = bc.col(i);\n          VectorXd Wi;\n          // use initial guess\n          Wi = W.col(i);\n          SolverStatus ret = active_set(\n              Q,c,b,bci,Aeq,Beq,Aieq,Bieq,lx,ux,eff_params,Wi);\n          switch(ret)\n          {\n            case SOLVER_STATUS_CONVERGED:\n              break;\n            case SOLVER_STATUS_MAX_ITER:\n              cerr<<\"active_set: max iter without convergence.\"<<endl;\n              break;\n            case SOLVER_STATUS_ERROR:\n            default:\n              cerr<<\"active_set error.\"<<endl;\n              error = true;\n          }\n          W.col(i) = Wi;\n        }\n        if(error)\n        {\n          return false;\n        }\n        break;\n      }\n      case QP_SOLVER_MOSEK:\n      {\n#ifdef IGL_NO_MOSEK\n        assert(false && \"Use another QPSolver. Recompile without IGL_NO_MOSEK defined.\");\n        cerr<<\"Use another QPSolver. Recompile without IGL_NO_MOSEK defined.\"<<endl;\n        return false;\n#else\n        // Loop over handles\n        for(int i = 0;i<m;i++)\n        {\n          if(data.verbosity >= 1)\n          {\n            cout<<\"BBW: Computing weight for handle \"<<i+1<<\" out of \"<<m<<\n              \".\"<<endl;\n          }\n          VectorXd bci = bc.col(i);\n          VectorXd Wi;\n          // impose boundary conditions via bounds\n          slice_into(bci,b,ux);\n          slice_into(bci,b,lx);\n          bool r = mosek_quadprog(Q,c,0,A,lc,uc,lx,ux,data.mosek_data,Wi);\n          if(!r)\n          {\n            return false;\n          }\n          W.col(i) = Wi;\n        }\n#endif\n        break;\n      }\n      default:\n      {\n        assert(false && \"Unknown qp_solver\");\n        return false;\n      }\n    }\n#ifndef NDEBUG\n    const double min_rowsum = W.rowwise().sum().array().abs().minCoeff();\n    if(min_rowsum < 0.1)\n    {\n      cerr<<\"bbw.cpp: Warning, minimum row sum is very low. Consider more \"\n        \"active set iterations or enforcing partition of unity.\"<<endl;\n    }\n#endif\n  }\n\n  return true;\n}\n\n#ifdef IGL_STATIC_LIBRARY\n// Explicit template specialization\ntemplate bool igl::bbw::bbw<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<double, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -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> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, igl::bbw::BBWData&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&);\n#endif\n", "meta": {"hexsha": "3a204ceedda7d011a9cacb6f68729b7fad22a329", "size": 6333, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ThirdParty/Libigl/igl/bbw/bbw.cpp", "max_stars_repo_name": "elix22/IogramSource", "max_stars_repo_head_hexsha": "3a4ce55d94920e060776b4aa4db710f57a4280bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28.0, "max_stars_repo_stars_event_min_datetime": "2017-03-01T04:09:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T13:33:50.000Z", "max_issues_repo_path": "ThirdParty/Libigl/igl/bbw/bbw.cpp", "max_issues_repo_name": "elix22/IogramSource", "max_issues_repo_head_hexsha": "3a4ce55d94920e060776b4aa4db710f57a4280bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2017-03-09T05:22:49.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-02T18:38:05.000Z", "max_forks_repo_path": "ThirdParty/Libigl/igl/bbw/bbw.cpp", "max_forks_repo_name": "elix22/IogramSource", "max_forks_repo_head_hexsha": "3a4ce55d94920e060776b4aa4db710f57a4280bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2017-03-01T14:00:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T06:36:54.000Z", "avg_line_length": 29.5934579439, "max_line_length": 607, "alphanum_fraction": 0.5930838465, "num_tokens": 1816, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568416, "lm_q2_score": 0.6187804196836383, "lm_q1q2_score": 0.4809779279332259}}
{"text": "/*\n * Software License Agreement (BSD License)\n *\n *  Copyright (c) 2018, Locus Robotics\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions\n *  are met:\n *\n *   * Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *   * Redistributions in binary form must reproduce the above\n *     copyright notice, this list of conditions and the following\n *     disclaimer in the documentation and/or other materials provided\n *     with the distribution.\n *   * Neither the name of the copyright holder 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 (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#include <fuse_constraints/normal_delta.h>\n\n#include <Eigen/Core>\n#include <glog/logging.h>\n\n\nnamespace fuse_constraints\n{\n\nNormalDelta::NormalDelta(const fuse_core::MatrixXd& A, const fuse_core::VectorXd& b) :\n  A_(A),\n  b_(b)\n{\n  CHECK_GT(b_.rows(), 0);\n  CHECK_GT(A_.rows(), 0);\n  CHECK_EQ(b_.rows(), A.cols());\n  set_num_residuals(A_.rows());\n  mutable_parameter_block_sizes()->push_back(b_.rows());\n  mutable_parameter_block_sizes()->push_back(b_.rows());\n}\n\nbool NormalDelta::Evaluate(\n  double const* const* parameters,\n  double* residuals,\n  double** jacobians) const\n{\n  Eigen::Map<const fuse_core::VectorXd> x0(parameters[0], parameter_block_sizes()[0]);\n  Eigen::Map<const fuse_core::VectorXd> x1(parameters[1], parameter_block_sizes()[1]);\n  Eigen::Map<fuse_core::VectorXd> r(residuals, num_residuals());\n  r = A_ * (x1 - x0 - b_);\n  if (jacobians != NULL)\n  {\n    if (jacobians[0] != NULL)\n    {\n      Eigen::Map<fuse_core::MatrixXd>(jacobians[0], num_residuals(), parameter_block_sizes()[0]) = -A_;\n    }\n    if (jacobians[1] != NULL)\n    {\n      Eigen::Map<fuse_core::MatrixXd>(jacobians[1], num_residuals(), parameter_block_sizes()[1]) = A_;\n    }\n  }\n  return true;\n}\n\n}  // namespace fuse_constraints\n", "meta": {"hexsha": "6db1a37ed4268efe3a94b14398a80e6ce00d1b5d", "size": 2884, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "fuse_constraints/src/normal_delta.cpp", "max_stars_repo_name": "congleetea/fuse", "max_stars_repo_head_hexsha": "7a87a59915a213431434166c96d0705ba6aa00b2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fuse_constraints/src/normal_delta.cpp", "max_issues_repo_name": "congleetea/fuse", "max_issues_repo_head_hexsha": "7a87a59915a213431434166c96d0705ba6aa00b2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fuse_constraints/src/normal_delta.cpp", "max_forks_repo_name": "congleetea/fuse", "max_forks_repo_head_hexsha": "7a87a59915a213431434166c96d0705ba6aa00b2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-07-21T10:48:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-18T10:44:23.000Z", "avg_line_length": 36.5063291139, "max_line_length": 103, "alphanum_fraction": 0.7184466019, "num_tokens": 695, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149978955811, "lm_q2_score": 0.6370307875894139, "lm_q1q2_score": 0.48090409567248277}}
{"text": "/* ---------------------------------------------------------------------\n**\n** Copyright (C) 2017 Xiaoyu Wei\n**\n** Permission is hereby granted, free of charge, to any person obtaining a copy\n** of this software and associated documentation files (the \"Software\"), to deal\n** in the Software without restriction, including without limitation the rights\n** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n** copies of the Software, and to permit persons to whom the Software is\n** furnished to do so, subject to the following conditions:\n** \n** The above copyright notice and this permission notice shall be included in\n** all copies or substantial portions of the Software.\n** \n** THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n** THE SOFTWARE.\n**\n** -------------------------------------------------------------------*/\n\n#include <iostream>\n#include <fstream>\n#include <limits>\n#include <string>\n#include <array>\n#include <cmath>\n\n#include <boost/python/def.hpp>\n#include <boost/python/docstring_options.hpp>\n#include <boost/python/module.hpp>\n#include <boost/python/numpy.hpp>\n\n#include <deal.II/base/quadrature_lib.h>\n#include <deal.II/fe/fe_q.h>\n#include <deal.II/fe/fe_values.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.h>\n#include <deal.II/lac/vector.h>\n\nnamespace p  = boost::python;\nnamespace np = boost::python::numpy;\nnamespace d  = dealii;\n\nconstexpr int        dim = 2;\nconstexpr double     a   = -1;\nconstexpr double     b   = 1;\nconst d::UpdateFlags update_flags =\n    d::update_quadrature_points | d::update_JxW_values;\n\nvoid greet() { std::cout << \"Yey!\" << std::endl; }\n\ndouble l_infty_distance(d::Point<dim> & p1, d::Point<dim> & p2){\n  double dist = std::numeric_limits<double>::max();\n  for (unsigned int d=0; d < dim; ++d) {\n    double tmp = std::abs(p1[d] - p2[d]);\n    dist = tmp > dist ? dist : tmp;\n  }\n  return dist;\n}\n\ndouble compute_q_point_radii(d::Point<dim> q_point, std::array<d::Point<dim>,\n    d::GeometryInfo<dim>::vertices_per_cell> & vertices){\n  double rad = std::numeric_limits<double>::max();\n  for(auto && v : vertices){\n    double tmp = l_infty_distance(q_point, v);\n    rad = tmp > rad ? rad : tmp;\n  }\n  return rad;\n}\n\ntemplate<int dimension, int n_vertices>\nd::Point<dimension> compute_barycenter(\n    std::array<d::Point<dimension>, n_vertices> & vertices){\n\n  d::Point<dimension> bc;\n  for (unsigned int d=0; d < dimension; ++d) {\n    bc[d] = 0;\n  }\n\n  for(auto && v : vertices){\n    bc += v;\n  }\n  bc /= n_vertices;\n  return bc;\n}\n\ntemplate <int dimension>\nclass MeshGenerator {\npublic:\n  d::Triangulation<dimension> triangulation;\n  d::FE_Q<dimension>          fe;\n  d::DoFHandler<dimension>    dof_handler;\n  d::QGauss<dimension>              quadrature_formula;\n\n  double box_a, box_b;\n\n  // q: quad order\n  // level: initial (uniform) level\n  MeshGenerator(int q, int level):\n      triangulation(d::Triangulation<dimension>::maximum_smoothing),\n      fe(q),\n      dof_handler(triangulation),\n      quadrature_formula(q),\n      box_a(a),\n      box_b(b)\n  {\n    d::GridGenerator::hyper_cube(triangulation, box_a, box_b);\n    if (level > 1) {\n      triangulation.refine_global(level - 1);\n    }\n    this->dof_handler.distribute_dofs(fe);\n  }\n\n  // customized bounding box\n  MeshGenerator(int q, int level, double aa, double bb):\n      triangulation(d::Triangulation<dimension>::maximum_smoothing),\n      fe(q),\n      dof_handler(triangulation),\n      quadrature_formula(q),\n      box_a(aa),\n      box_b(bb)\n  {\n    d::GridGenerator::hyper_cube(triangulation, box_a, box_b);\n    if (level > 1) {\n      triangulation.refine_global(level - 1);\n    }\n    this->dof_handler.distribute_dofs(fe);\n  }\n\n  // NOTE: Copy constructor is not supported since dealii::DoFHandler is not\n  // copy constructable, but a dummy copy constructor is required by\n  // boost.python to build the code.\n  MeshGenerator(const MeshGenerator<dimension>&):\n    MeshGenerator(1, 1){};\n\n  std::string greet() { return \"Hello from MeshGen.\"; }\n\n  void generate_gmsh(p::object &fn) {\n    std::string filename = p::extract<std::string>(fn);\n    std::ofstream output_file(filename);\n    d::GridOut().write_msh(this->triangulation, output_file);\n  }\n\n  np::ndarray get_q_points() {\n    np::dtype dtype = np::dtype::get_builtin<double>();\n\n    const unsigned int n_q_points = this->quadrature_formula.size();\n    const int total_n_q_points = triangulation.n_active_cells() * n_q_points;\n    Py_intptr_t pt_shape[2] = {total_n_q_points, dimension};\n\n    d::FEValues<dimension>   fe_values(this->fe, this->quadrature_formula,\n        d::update_quadrature_points);\n    np::ndarray points = np::zeros(2, pt_shape, dtype);\n    auto ptp           = reinterpret_cast<double*>(points.get_data());\n\n    auto cell = dof_handler.begin_active();\n    auto endc = dof_handler.end();\n    for (; cell != endc; ++cell) {\n      fe_values.reinit(cell);\n      std::vector<d::Point<dimension>> q_points = fe_values.get_quadrature_points();\n\n      for (auto&& point : q_points) {\n        for (unsigned int d = 0; d < dimension; ++d) {\n          // For a preferred ordering of quad points\n          // This does not change anything but the ordering due to the symmetry\n          // in each direction (as long as the subdivided boxes are cubes), not\n          // even weights are changed.\n          *ptp = point[dim-1-d];\n          ++ptp;\n        }\n      }\n    }\n\n    return points;\n  }\n\n  np::ndarray get_q_weights(){\n    np::dtype dtype = np::dtype::get_builtin<double>();\n\n    const unsigned int n_q_points = this->quadrature_formula.size();\n    const int total_n_q_points = this->triangulation.n_active_cells() * n_q_points;\n    Py_intptr_t w_shape[1]       = {total_n_q_points};\n\n    d::FEValues<dimension>   fe_values(this->fe, this->quadrature_formula,\n        d::update_JxW_values);\n    np::ndarray weights = np::zeros(1, w_shape, dtype);\n    auto ptw = reinterpret_cast<double*>(weights.get_data());\n\n    auto cell = this->dof_handler.begin_active();\n    auto endc = this->dof_handler.end();\n    for (; cell != endc; ++cell) {\n      fe_values.reinit(cell);\n      std::vector<double> q_weights;\n\n      for (unsigned int q_index = 0; q_index < n_q_points; ++q_index) {\n        q_weights.push_back(fe_values.JxW(q_index));\n      }\n\n      for (auto&& weight : q_weights) {\n          *ptw = weight;\n          ++ptw;\n      }\n    }\n\n    return weights;\n  }\n\n  np::ndarray get_cell_measures(){\n    np::dtype dtype = np::dtype::get_builtin<double>();\n    Py_intptr_t m_shape[1] = {this->triangulation.n_active_cells()};\n    np::ndarray measures = np::zeros(1, m_shape, dtype);\n    auto ptm = reinterpret_cast<double*>(measures.get_data());\n\n    auto cell = this->dof_handler.begin_active();\n    auto endc = this->dof_handler.end();\n    for (; cell != endc; ++cell) {\n      *ptm = cell->measure();\n      ++ptm;\n    }\n\n    return measures;\n  }\n\n  np::ndarray get_cell_centers(){\n    np::dtype dtype = np::dtype::get_builtin<double>();\n    Py_intptr_t c_shape[2] = {this->triangulation.n_active_cells(), dimension};\n    np::ndarray centers = np::zeros(2, c_shape, dtype);\n    auto ptc = reinterpret_cast<double*>(centers.get_data());\n\n    auto cell = this->dof_handler.begin_active();\n    auto endc = this->dof_handler.end();\n    for (; cell != endc; ++cell) {\n      std::array<d::Point<dimension>,d::GeometryInfo<dimension>::vertices_per_cell> vertices;\n      for (unsigned int v=0; v<d::GeometryInfo<dimension>::vertices_per_cell; ++v) {\n        vertices[v] = cell->vertex(v);\n      }\n      auto barycenter = compute_barycenter<dimension,\n                          d::GeometryInfo<dimension>::vertices_per_cell>(vertices);\n      for (unsigned int d = 0; d < dimension; ++d) {\n        *ptc = barycenter[dimension-1-d];\n        ++ptc;\n      }\n    }\n\n    return centers;\n  }\n\n  // Interface for dealii::GridRefinement::refine_and_coarsen_fixed_number\n  void refine_and_coarsen_fixed_number(double* criteria,\n                                       const double top_fraction_of_cells,\n                                       const double bottom_fraction_of_cells) {\n    d::Vector<double> ctr;\n    ctr.reinit(this->triangulation.n_active_cells());\n    double* ptc = criteria;\n    for (unsigned int c = 0; c < this->triangulation.n_active_cells(); ++c){\n      ctr[c] = *ptc;\n      ++ptc;\n    }\n\n    d::GridRefinement::refine_and_coarsen_fixed_number (this->triangulation,\n                                                        ctr,\n                                                        top_fraction_of_cells,\n                                                        bottom_fraction_of_cells);\n  }\n\n  int n_active_cells() {\n    return this->triangulation.n_active_cells();\n  }\n\n  // Do both preparation for refinement and coarsening as well as mesh smoothing.\n  // The function returns whether some cells' flagging has been changed in the process.\n  bool prepare_coarsening_and_refinement() {\n    return this->triangulation.prepare_coarsening_and_refinement();\n  }\n\n  void execute_coarsening_and_refinement() {\n    this->triangulation.execute_coarsening_and_refinement();\n    this->dof_handler.distribute_dofs(fe);\n  }\n\n  // Driver function for mesh adaptivity\n  int update_mesh(np::ndarray const & criteria,\n                   const double top_fraction_of_cells,\n                   const double bottom_fraction_of_cells) {\n    if (criteria.get_dtype() != np::dtype::get_builtin<double>()) {\n        PyErr_SetString(PyExc_TypeError, \"Incorrect array data type in the criteria\");\n        p::throw_error_already_set();\n    }\n    if (criteria.get_nd() != 1) {\n        PyErr_SetString(PyExc_TypeError, \"Incorrect number of dimensions of the criteria\");\n        p::throw_error_already_set();\n    }\n\n    // Refining top 1/3 in 2D doubles the number of cells\n    double * iter = reinterpret_cast<double*>(criteria.get_data());\n    this->refine_and_coarsen_fixed_number(iter, top_fraction_of_cells,\n                                          bottom_fraction_of_cells);\n\n    this->prepare_coarsening_and_refinement();\n    this->execute_coarsening_and_refinement();\n\n    return this->n_active_cells();\n  }\n\n  // Show some info about the mesh\n  void print_info() {\n    std::cout << \"Number of active cells: \" << this->triangulation.n_active_cells()\n              << std::endl;\n\n    d::FEValues<dimension>   fe_values(fe, quadrature_formula, d::update_quadrature_points);\n    const unsigned int n_q_points = quadrature_formula.size();\n    std::cout << \"Number of quad points per cell: \" << n_q_points << std::endl;\n  }\n\n};\ntypedef MeshGenerator<2> MeshGen2D;\ntypedef MeshGenerator<3> MeshGen3D;\n\n\n// A legacy one-stop mesh generation function, returns quad points, weights\n// and some spacing info within a tuple.\ntemplate <int dim>\np::tuple make_uniform_cubic_grid_details(int q, int level) {\n  np::dtype dtype = np::dtype::get_builtin<double>();\n\n  d::Triangulation<dim> triangulation;\n  d::FE_Q<dim>          fe(q);\n  d::DoFHandler<dim>    dof_handler(triangulation);\n  d::QGauss<dim>        quadrature_formula(q);\n\n  d::GridGenerator::hyper_cube(triangulation, a, b);\n  if (level > 1) {\n    triangulation.refine_global(level - 1);\n  }\n  dof_handler.distribute_dofs(fe);\n  //std::cout << \"Number of active cells: \" << triangulation.n_active_cells()\n            //<< std::endl;\n\n  d::FEValues<dim>   fe_values(fe, quadrature_formula, update_flags);\n  const unsigned int n_q_points = quadrature_formula.size();\n  //std::cout << \"Number of quad points per cell: \" << n_q_points << std::endl;\n\n  const int   total_n_q_points = triangulation.n_active_cells() * n_q_points;\n  Py_intptr_t pt_shape[2]      = {total_n_q_points, dim};\n  Py_intptr_t w_shape[1]       = {total_n_q_points};\n  // Quad points\n  np::ndarray points           = np::zeros(2, pt_shape, dtype);\n  // Quad weights\n  np::ndarray weights          = np::zeros(1, w_shape, dtype);\n  // Distance (l_infty) to the closest cell vertex\n  // (used for reconstructing the mesh in boxtree)\n  np::ndarray radii            = np::zeros(1, w_shape, dtype);\n  auto        ptp              = reinterpret_cast<double*>(points.get_data());\n  auto        ptw              = reinterpret_cast<double*>(weights.get_data());\n  auto        ptr              = reinterpret_cast<double*>(radii.get_data());\n\n  // For margins\n  std::array<double,dim*2> margins;\n  std::array<double*, dim*2> mpts;\n  margins.fill(std::numeric_limits<double>::max());\n\n  auto cell = dof_handler.begin_active();\n  auto endc = dof_handler.end();\n  for (; cell != endc; ++cell) {\n    fe_values.reinit(cell);\n    std::vector<d::Point<dim>> q_points = fe_values.get_quadrature_points();\n    std::vector<double>        q_weights;\n    std::array<d::Point<dim>,d::GeometryInfo<dim>::vertices_per_cell> vertices;\n\n    for (unsigned int q_index = 0; q_index < n_q_points; ++q_index) {\n      q_weights.push_back(fe_values.JxW(q_index));\n    }\n\n    for (unsigned int v=0; v<d::GeometryInfo<dim>::vertices_per_cell; ++v) {\n      vertices[v] = cell->vertex(v);\n    }\n\n    for (auto&& point : q_points) {\n      for (unsigned int d = 0; d < dim; ++d) {\n        // For a preferred ordering of quad points\n        // This does not change anything but the ordering due to the symmetry\n        // in each direction (as long as the subdivided boxes are cubes), not\n        // even weights are changed.\n        *ptp = point[dim-1-d];\n        ++ptp;\n      }\n      if( std::abs(point[0] - a) < margins[0] ){\n        margins[0] = std::abs(point[0] - a);\n        mpts[0] = ptr;\n      }\n      if( std::abs(point[0] - b) < margins[1] ){\n        margins[1] = std::abs(point[0] - b);\n        mpts[1] = ptr;\n      }\n      if( std::abs(point[1] - a) < margins[2] ){\n        margins[2] = std::abs(point[1] - a);\n        mpts[2] = ptr;\n      }\n      if( std::abs(point[1] - b) < margins[3] ){\n        margins[3] = std::abs(point[1] - b);\n        mpts[3] = ptr;\n      }\n      ++ptr;\n    }\n\n    for (auto&& weight : q_weights) {\n      *ptw = weight;\n      ++ptw;\n    }\n  }\n\n  for (unsigned int i=0; i < dim*2; ++i) {\n    *(mpts[i]) = margins[i];\n  }\n\n  p::tuple result = p::make_tuple(points, weights, radii);\n  return result;\n}\n\np::tuple make_uniform_cubic_grid(int q, int level, int dim) {\n  if (dim == 1) {\n    return make_uniform_cubic_grid_details<1>(q, level);\n  }\n  else if (dim == 2) {\n    return make_uniform_cubic_grid_details<2>(q, level);\n  }\n  else if (dim == 3) {\n    return make_uniform_cubic_grid_details<3>(q, level);\n  }\n  else {\n    std::cout << \"Dimension must be 1,2 or 3.\" << std::endl;\n    return make_uniform_cubic_grid_details<3>(q, level);\n  }\n}\n\nBOOST_PYTHON_MODULE(meshgen_dealii) {\n  using namespace boost::python;\n  Py_Initialize();\n  np::initialize();\n\n  docstring_options doc_options(/*show_all=*/true);\n\n  def(\"greet\", greet,\n      \"Greentings! This module handles generation of quadrature points & \"\n      \"weights.\\n\\nThe points and weights follow Legendre-Gauss quadrature \"\n      \"rules.\");\n\n  def(\"make_uniform_cubic_grid\", make_uniform_cubic_grid,\n      (p::arg(\"degree\") = 3, p::arg(\"level\") = 2, p::arg(\"dim\") = 2), \"Make a simple cubic grid.\");\n\n  class_<MeshGen2D>(\"MeshGen2D\", init<int, int>())\n        .def(init<int, int, double, double>())\n        .def(\"greet\", &MeshGen2D::greet)\n        .def(\"get_q_points\", &MeshGen2D::get_q_points)\n        .def(\"get_q_weights\", &MeshGen2D::get_q_weights)\n        .def(\"get_cell_centers\", &MeshGen2D::get_cell_centers)\n        .def(\"get_cell_measures\", &MeshGen2D::get_cell_measures)\n        .def(\"n_active_cells\", &MeshGen2D::n_active_cells)\n        .def(\"prepare_coarsening_and_refinement\", &MeshGen2D::prepare_coarsening_and_refinement)\n        .def(\"execute_coarsening_and_refinement\", &MeshGen2D::execute_coarsening_and_refinement)\n        .def(\"update_mesh\", &MeshGen2D::update_mesh)\n        .def(\"print_info\", &MeshGen2D::print_info)\n        .def(\"generate_gmsh\", &MeshGen2D::generate_gmsh)\n    ;\n\n  class_<MeshGen3D>(\"MeshGen3D\", init<int, int>())\n        .def(init<int, int, double, double>())\n        .def(\"greet\", &MeshGen3D::greet)\n        .def(\"get_q_points\", &MeshGen3D::get_q_points)\n        .def(\"get_q_weights\", &MeshGen3D::get_q_weights)\n        .def(\"get_cell_centers\", &MeshGen3D::get_cell_centers)\n        .def(\"get_cell_measures\", &MeshGen3D::get_cell_measures)\n        .def(\"n_active_cells\", &MeshGen3D::n_active_cells)\n        .def(\"prepare_coarsening_and_refinement\", &MeshGen3D::prepare_coarsening_and_refinement)\n        .def(\"execute_coarsening_and_refinement\", &MeshGen3D::execute_coarsening_and_refinement)\n        .def(\"update_mesh\", &MeshGen3D::update_mesh)\n        .def(\"print_info\", &MeshGen3D::print_info)\n        .def(\"generate_gmsh\", &MeshGen3D::generate_gmsh)\n    ;\n}\n", "meta": {"hexsha": "4bd68bee1ddb6aa8ea68f5e0cc99b4d4986c24bc", "size": 17185, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "contrib/meshgen_dealii/meshgen.cpp", "max_stars_repo_name": "xywei/volumential", "max_stars_repo_head_hexsha": "07c6ca8c623acf24fb8deddf93baa1035234db58", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2021-05-21T23:57:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T22:02:50.000Z", "max_issues_repo_path": "contrib/meshgen_dealii/meshgen.cpp", "max_issues_repo_name": "inducer/volumential", "max_issues_repo_head_hexsha": "290a5943d3f47958dcab6736bc2b758525471570", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:41:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-26T15:42:21.000Z", "max_forks_repo_path": "contrib/meshgen_dealii/meshgen.cpp", "max_forks_repo_name": "inducer/volumential", "max_forks_repo_head_hexsha": "290a5943d3f47958dcab6736bc2b758525471570", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-21T21:23:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-21T21:23:39.000Z", "avg_line_length": 35.2874743326, "max_line_length": 99, "alphanum_fraction": 0.6415478615, "num_tokens": 4546, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.48090408344524116}}
{"text": "#include <stan/math/prim.hpp>\n#include <test/unit/util.hpp>\n#include <gtest/gtest.h>\n\n#ifdef STAN_OPENCL\n#include <stan/math/opencl/opencl.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#endif\n\nTEST(MathMatrixPrim, mdivide_left_tri_val) {\n  using stan::math::mdivide_left_tri;\n  stan::math::matrix_d I = Eigen::MatrixXd::Identity(2, 2);\n\n  stan::math::matrix_d Ad(2, 2);\n  Ad << 2.0, 0.0, 5.0, 7.0;\n  EXPECT_MATRIX_FLOAT_EQ(I, mdivide_left_tri<Eigen::Lower>(Ad, Ad));\n\n  stan::math::matrix_d A_Ainv = Ad * mdivide_left_tri<Eigen::Lower>(Ad);\n  EXPECT_MATRIX_NEAR(I, A_Ainv, 1e-15);\n\n  Ad << 2.0, 3.0, 0.0, 7.0;\n  EXPECT_MATRIX_FLOAT_EQ(I, mdivide_left_tri<Eigen::Upper>(Ad, Ad));\n}\n\nTEST(MathMatrixPrim, mdivide_left_tri_size_zero) {\n  using stan::math::mdivide_left_tri;\n  stan::math::matrix_d Ad(0, 0);\n  stan::math::matrix_d b0(0, 2);\n  stan::math::matrix_d I;\n\n  I = mdivide_left_tri<Eigen::Lower>(Ad, Ad);\n  EXPECT_EQ(0, I.rows());\n  EXPECT_EQ(0, I.cols());\n\n  I = mdivide_left_tri<Eigen::Upper>(Ad, Ad);\n  EXPECT_EQ(0, I.rows());\n  EXPECT_EQ(0, I.cols());\n\n  I = mdivide_left_tri<Eigen::Lower>(Ad);\n  EXPECT_EQ(0, I.rows());\n  EXPECT_EQ(0, I.cols());\n\n  I = mdivide_left_tri<Eigen::Upper>(Ad);\n  EXPECT_EQ(0, I.rows());\n  EXPECT_EQ(0, I.cols());\n\n  I = mdivide_left_tri<Eigen::Lower>(Ad, b0);\n  EXPECT_EQ(0, I.rows());\n  EXPECT_EQ(b0.cols(), I.cols());\n\n  I = mdivide_left_tri<Eigen::Upper>(Ad, b0);\n  EXPECT_EQ(0, I.rows());\n  EXPECT_EQ(b0.cols(), I.cols());\n}\n\n#ifdef STAN_OPENCL\nvoid mdivide_left_tri_lower_cl_test(int size) {\n  boost::random::mt19937 rng;\n  stan::math::matrix_d m1(size, size);\n  for (int i = 0; i < size; i++) {\n    for (int j = 0; j < i; j++) {\n      m1(i, j) = stan::math::uniform_rng(-5, 5, rng);\n    }\n    m1(i, i) = 20.0;\n    for (int j = i + 1; j < size; j++) {\n      m1(i, j) = 0.0;\n    }\n  }\n\n  stan::math::opencl_context.tuning_opts().tri_inverse_size_worth_transfer\n      = size * 2;\n\n  stan::math::matrix_d m1_cpu = stan::math::mdivide_left_tri<Eigen::Lower>(m1);\n\n  stan::math::opencl_context.tuning_opts().tri_inverse_size_worth_transfer = 0;\n\n  stan::math::matrix_d m1_cl = stan::math::mdivide_left_tri<Eigen::Lower>(m1);\n\n  EXPECT_MATRIX_NEAR(m1_cpu, m1_cl, 1E-8);\n}\nTEST(MathMatrixCL, mdivide_left_tri_lower_cl_small) {\n  mdivide_left_tri_lower_cl_test(3);\n}\nTEST(MathMatrixCL, mdivide_left_tri_lower_cl_mid) {\n  mdivide_left_tri_lower_cl_test(100);\n}\nTEST(MathMatrixCL, mdivide_left_tri_lower_cl_big) {\n  mdivide_left_tri_lower_cl_test(500);\n}\n\nvoid mdivide_left_tri_upper_cl_test(int size) {\n  boost::random::mt19937 rng;\n  stan::math::matrix_d m1(size, size);\n  for (int i = 0; i < size; i++) {\n    for (int j = 0; j < i; j++) {\n      m1(i, j) = 0.0;\n    }\n    m1(i, i) = 20.0;\n    for (int j = i + 1; j < size; j++) {\n      m1(i, j) = stan::math::uniform_rng(-5, 5, rng);\n    }\n  }\n\n  stan::math::opencl_context.tuning_opts().tri_inverse_size_worth_transfer\n      = size * 2;\n\n  stan::math::matrix_d m1_cpu = stan::math::mdivide_left_tri<Eigen::Upper>(m1);\n\n  stan::math::opencl_context.tuning_opts().tri_inverse_size_worth_transfer = 0;\n\n  stan::math::matrix_d m1_cl = stan::math::mdivide_left_tri<Eigen::Upper>(m1);\n\n  EXPECT_MATRIX_NEAR(m1_cpu, m1_cl, 1E-8);\n}\nTEST(MathMatrixCL, mdivide_left_tri_upper_cl_small) {\n  mdivide_left_tri_upper_cl_test(3);\n}\nTEST(MathMatrixCL, mdivide_left_tri_upper_cl_mid) {\n  mdivide_left_tri_upper_cl_test(100);\n}\nTEST(MathMatrixCL, mdivide_left_tri_upper_cl_big) {\n  mdivide_left_tri_upper_cl_test(500);\n}\n\nvoid mdivide_left_tri_cl_test(int size) {\n  boost::random::mt19937 rng;\n  stan::math::matrix_d m1(size, size);\n  for (int i = 0; i < size; i++) {\n    for (int j = 0; j < i; j++) {\n      m1(i, j) = stan::math::uniform_rng(-5, 5, rng);\n    }\n    m1(i, i) = 20.0;\n    for (int j = i + 1; j < size; j++) {\n      m1(i, j) = 0.0;\n    }\n  }\n\n  stan::math::opencl_context.tuning_opts().tri_inverse_size_worth_transfer\n      = size * 2;\n\n  stan::math::matrix_d m1_cpu\n      = stan::math::mdivide_left_tri<Eigen::Lower>(m1, m1);\n\n  stan::math::opencl_context.tuning_opts().tri_inverse_size_worth_transfer = 0;\n\n  stan::math::matrix_d m1_cl\n      = stan::math::mdivide_left_tri<Eigen::Lower>(m1, m1);\n\n  EXPECT_MATRIX_NEAR(m1_cpu, m1_cl, 1E-8);\n}\nTEST(MathMatrixCL, mdivide_left_tri_cl_small) { mdivide_left_tri_cl_test(3); }\nTEST(MathMatrixCL, mdivide_left_tri_cl_mid) { mdivide_left_tri_cl_test(100); }\nTEST(MathMatrixCL, mdivide_left_tri_cl_big) { mdivide_left_tri_cl_test(500); }\n#endif\n", "meta": {"hexsha": "81268f207b1702e09f5297ed54e873eace7d9ef2", "size": 4475, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/prim/fun/mdivide_left_tri_test.cpp", "max_stars_repo_name": "nicokist/math", "max_stars_repo_head_hexsha": "d47c331a693a3d5ebc4453360743b9353a8e3ed1", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/unit/math/prim/fun/mdivide_left_tri_test.cpp", "max_issues_repo_name": "nicokist/math", "max_issues_repo_head_hexsha": "d47c331a693a3d5ebc4453360743b9353a8e3ed1", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/unit/math/prim/fun/mdivide_left_tri_test.cpp", "max_forks_repo_name": "nicokist/math", "max_forks_repo_head_hexsha": "d47c331a693a3d5ebc4453360743b9353a8e3ed1", "max_forks_repo_licenses": ["BSD-3-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.8709677419, "max_line_length": 79, "alphanum_fraction": 0.6750837989, "num_tokens": 1523, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149758396753, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.48090407642009564}}
{"text": "#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics.hpp>\n#include <iostream>\n\nusing namespace boost::accumulators;\n\nint main()\n{\n  accumulator_set<double, features<tag::mean, tag::variance>, int> acc;\n  acc(8, weight = 1);\n  acc(9, weight = 1);\n  acc(10, weight = 4);\n  acc(11, weight = 1);\n  acc(12, weight = 1);\n  std::cout << mean(acc) << '\\n';\n  std::cout << variance(acc) << '\\n';\n}", "meta": {"hexsha": "d5f1086d95b1d9196c496e3cac572ad022661f26", "size": 422, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Example/accumulators_03/main.cpp", "max_stars_repo_name": "KwangjoJeong/Boost", "max_stars_repo_head_hexsha": "29c4e2422feded66a689e3aef73086c5cf95b6fe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Example/accumulators_03/main.cpp", "max_issues_repo_name": "KwangjoJeong/Boost", "max_issues_repo_head_hexsha": "29c4e2422feded66a689e3aef73086c5cf95b6fe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Example/accumulators_03/main.cpp", "max_forks_repo_name": "KwangjoJeong/Boost", "max_forks_repo_head_hexsha": "29c4e2422feded66a689e3aef73086c5cf95b6fe", "max_forks_repo_licenses": ["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.8235294118, "max_line_length": 71, "alphanum_fraction": 0.6492890995, "num_tokens": 130, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950986284991, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4808958594688618}}
{"text": "#include <stan/math/prim/scal.hpp>\n#include <gtest/gtest.h>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/math/distributions.hpp>\n\nTEST(ProbDistributionBetaBinomial, error_check) {\n  boost::random::mt19937 rng;\n  EXPECT_NO_THROW(stan::math::beta_binomial_rng(4, 0.6, 2.0, rng));\n\n  EXPECT_THROW(stan::math::beta_binomial_rng(-4, 0.6, 2, rng),\n               std::domain_error);\n  EXPECT_THROW(stan::math::beta_binomial_rng(4, -0.6, 2, rng),\n               std::domain_error);\n  EXPECT_THROW(stan::math::beta_binomial_rng(4, 0.6, -2, rng),\n               std::domain_error);\n  EXPECT_THROW(\n      stan::math::beta_binomial_rng(4, stan::math::positive_infinity(), 2, rng),\n      std::domain_error);\n  EXPECT_THROW(stan::math::beta_binomial_rng(\n                   4, 0.6, stan::math::positive_infinity(), rng),\n               std::domain_error);\n}\n", "meta": {"hexsha": "8eee6883e04b85eb1abc320da4885f8798dc1cf7", "size": 861, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/prim/scal/prob/beta_binomial_test.cpp", "max_stars_repo_name": "jrmie/math", "max_stars_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "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": "test/unit/math/prim/scal/prob/beta_binomial_test.cpp", "max_issues_repo_name": "jrmie/math", "max_issues_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "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": "test/unit/math/prim/scal/prob/beta_binomial_test.cpp", "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.4347826087, "max_line_length": 80, "alphanum_fraction": 0.6585365854, "num_tokens": 252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024556, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4808958572315955}}
{"text": "// test external pac\n#include <Eigen/Dense>\n#include <fmt/core.h>\n#include <fmt/ostream.h>\n\n// test std libraries\n#include <iostream>\n#include <string>\n#include <string_view>\n\n// test c libraries\n#include <cassert>\n#include <cctype>\n#include <cstddef>\n#include <cstdint>\n#include <cstring>\n\nint some_fun2() {\n    fmt::print(\"Hello from fmt{}\", \"!\");\n\n    // populate an Eigen vector with the values\n    auto eigen_vec = Eigen::VectorXd::LinSpaced(10, 0, 1);\n\n    // print the vector\n    fmt::print(\"{}\", eigen_vec);\n\n    return 0;\n}\n", "meta": {"hexsha": "285cec2778c7b52c04b127d2d3ad140962efea15", "size": 533, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/src/mylib2/lib.cpp", "max_stars_repo_name": "ClausKlein/cmakelib", "max_stars_repo_head_hexsha": "1e7264df6cf53dcbe15ac4d8c03ae37470a869c9", "max_stars_repo_licenses": ["MIT", "Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-29T05:43:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T05:43:02.000Z", "max_issues_repo_path": "test/src/mylib2/lib.cpp", "max_issues_repo_name": "ClausKlein/project_options", "max_issues_repo_head_hexsha": "1e7264df6cf53dcbe15ac4d8c03ae37470a869c9", "max_issues_repo_licenses": ["MIT", "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": "test/src/mylib2/lib.cpp", "max_forks_repo_name": "ClausKlein/project_options", "max_forks_repo_head_hexsha": "1e7264df6cf53dcbe15ac4d8c03ae37470a869c9", "max_forks_repo_licenses": ["MIT", "Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.3793103448, "max_line_length": 58, "alphanum_fraction": 0.6622889306, "num_tokens": 138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.48082269806243627}}
{"text": "/*******************************************************************************\n * An abstract domain that lifts a value domain using term\n * equivalences based on the paper \"An Abstract Domain of\n * Uninterpreted Functions\" by Gange, Navas, Schachte, Sondergaard,\n * and Stuckey published in VMCAI'16.\n *\n * Author: Graeme Gange (gkgange@unimelb.edu.au)\n *\n * Contributors: Jorge A. Navas (jorge.navas@sri.com)\n ******************************************************************************/\n\n#pragma once\n\n#include <algorithm>\n#include <set>\n#include <utility>\n#include <vector>\n\n#include <boost/container/flat_map.hpp>\n#include <boost/container/flat_set.hpp>\n#include <boost/optional.hpp>\n#include <boost/range.hpp>\n\n#include <crab/cfg/var_factory.hpp>\n#include <crab/common/debug.hpp>\n#include <crab/common/stats.hpp>\n#include <crab/common/types.hpp>\n#include <crab/domains/abstract_domain.hpp>\n#include <crab/domains/abstract_domain_specialized_traits.hpp>\n#include <crab/domains/backward_assign_operations.hpp>\n#include <crab/domains/intervals.hpp>\n#include <crab/domains/linear_constraints.hpp>\n#include <crab/domains/term/inverse.hpp>\n#include <crab/domains/term/simplify.hpp>\n#include <crab/domains/term/term_expr.hpp>\n#include <crab/numbers/bignums.hpp>\n\n//#define VERBOSE\n//#define DEBUG_VARMAP\n//#define DEBUG_MEET\n\n#define USE_TERM_INTERVAL_NORMALIZER\n\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wsign-compare\"\n\nnamespace crab {\n\nnamespace domains {\n\nnamespace term {\ntemplate <class Num, class VName, class Abs> class TDomInfo {\npublic:\n  typedef Num Number;\n  typedef VName VariableName;\n  typedef variable<Num, VName> variable_t;\n  typedef crab::cfg::var_factory_impl::str_var_alloc_col Alloc;\n  typedef Abs domain_t;\n};\n} // namespace term\n\ntemplate <class Info, class Abs> class TermNormalizer;\n\ntemplate <typename Info>\nclass term_domain final : public abstract_domain<term_domain<Info>> {\n  friend class TermNormalizer<Info, typename Info::domain_t>;\n\n  // Number and VariableName can be different from\n  // dom_t::number_t and dom_t::varname_t although currently\n  // Number and dom_t::number_t must be the same type.\n  typedef typename Info::Number Number;\n  typedef typename Info::VariableName VariableName;\n  typedef typename Info::domain_t dom_t;\n  typedef typename dom_t::variable_t dom_var_t;\n  typedef typename Info::Alloc dom_var_alloc_t;\n  typedef typename dom_var_alloc_t::varname_t dom_varname_t;\n  typedef patricia_tree_set<dom_var_t> domvar_set_t;\n  typedef bound<Number> bound_t;\n\n  typedef term_domain<Info> term_domain_t;\n  typedef abstract_domain<term_domain_t> abstract_domain_t;\n\npublic:\n  using typename abstract_domain_t::disjunctive_linear_constraint_system_t;\n  using typename abstract_domain_t::linear_constraint_system_t;\n  using typename abstract_domain_t::linear_constraint_t;\n  using typename abstract_domain_t::linear_expression_t;\n  using typename abstract_domain_t::variable_t;\n  typedef Number number_t;\n  typedef VariableName varname_t;\n  using typename abstract_domain_t::pointer_constraint_t;\n  using typename abstract_domain_t::variable_vector_t;\n\n  typedef interval<number_t> interval_t;\n\nprivate:\n  typedef term::term_table<number_t, binary_operation_t> ttbl_t;\n  typedef typename ttbl_t::term_id_t term_id_t;\n\n  // WARNING: assumes the underlying domain uses the same number type.\n  typedef typename Info::Number dom_number;\n  typedef typename dom_t::linear_constraint_t dom_lincst_t;\n  typedef typename dom_t::linear_constraint_system_t dom_linsys_t;\n  typedef typename dom_t::linear_expression_t dom_linexp_t;\n  typedef typename linear_expression_t::component_t linterm_t;\n  typedef boost::container::flat_map<term_id_t, dom_var_t> term_map_t;\n  typedef boost::container::flat_map<dom_var_t, variable_t> rev_map_t;\n  typedef boost::container::flat_set<term_id_t> term_set_t;\n  typedef boost::container::flat_map<variable_t, term_id_t> var_map_t;\n  // the reverse of var_map: from term_id_t to a set of variable_t\n  typedef std::set<variable_t> var_set_t;\n  typedef boost::container::flat_map<term_id_t, var_set_t> rev_var_map_t;\n  typedef term::NumSimplifier<number_t> simplifier_t;\n\n  bool _is_bottom;\n  // Uses a single state of the underlying domain.\n  ttbl_t _ttbl;\n  dom_t _impl;\n  dom_var_alloc_t _alloc;\n  var_map_t _var_map;\n  rev_var_map_t _rev_var_map; // to extract equalities efficiently\n  term_map_t _term_map;\n  term_set_t changed_terms;\n\n  term_domain(bool is_top) : _is_bottom(!is_top) {}\n\n  term_domain(dom_var_alloc_t &&alloc, var_map_t &&vm, rev_var_map_t &&rvm,\n              ttbl_t &&tbl, term_map_t &&tmap, dom_t &&impl)\n      : _is_bottom((impl.is_bottom()) ? true : false),\n\t_ttbl(std::move(tbl)), _impl(std::move(impl)),\n        _alloc(std::move(alloc)), _var_map(std::move(vm)),\n\t_rev_var_map(std::move(rvm)), _term_map(std::move(tmap)) {\n    check_terms(__LINE__);\n  }\n\n  // x = y op [lb,ub]\n  term_id_t term_of_itv(bound_t lb, bound_t ub) {\n    boost::optional<number_t> n_lb = lb.number();\n    boost::optional<number_t> n_ub = ub.number();\n\n    if (n_lb && n_ub && (*n_lb == *n_ub))\n      return term_of_const(*n_lb);\n\n    term_id_t t_itv = _ttbl.fresh_var();\n    dom_var_t dom_itv = domvar_of_term(t_itv);\n    _impl.set(dom_itv, interval_t(lb, ub));\n    return t_itv;\n  }\n\n  // term_id_t term_of_expr(operation_t op, term_id_t ty, term_id_t tz)\n  // {\n  //   boost::optional<term_id_t> opt_tx = _ttbl.find_ftor(op, ty, tz);\n  //   if(opt_tx)\n  //   {\n  //     // If the term already exists, we can learn nothing.\n  //     return *opt_tx;\n  //   } else {\n  //     // Otherwise, assign the term, and evaluate.\n  //     term_id_t tx = _ttbl.apply_ftor(op, ty, tz);\n  //     _impl.apply(op,\n  //                 domvar_of_term(tx),\n  //                 domvar_of_term(ty), domvar_of_term(tz));\n  //     return tx;\n  //   }\n  // }\n\n  // void apply(operation_t op, variable_t x, variable_t y, bound_t lb, bound_t\n  // ub){\n  //   term_id_t t_x = term_of_expr(op, term_of_var(y), term_of_itv(lb, ub));\n  //   // JNL: check with Graeme\n  //   //      insert only adds an entry if the key does not exist\n  //   //_var_map.insert(std::make_pair(x, t_x));\n  //   rebind_var(x, t_x);\n  //   check_terms(__LINE__);\n  // }\n\n  void apply(dom_t &dom, binary_operation_t op, dom_var_t x, dom_var_t y,\n             dom_var_t z) {\n    if (auto top = conv_op<operation_t>(op)) {\n      dom.apply(*top, x, y, z);\n    } else if (auto top = conv_op<bitwise_operation_t>(op)) {\n      dom.apply(*top, x, y, z);\n    } else if (op == BINOP_FUNCTION) {\n      // uninterpreted function: do nothing in the underlying\n      // numerical domain.\n    } else {\n      CRAB_ERROR(\"unsupported binary operator \", op);\n    }\n  }\n\n  // Apply a given functor in the underlying domain.\n  // GKG: Looks the current implementation could actually\n  // lose information; as it's not taking the meet with\n  // the current value.\n  void eval_ftor(dom_t &dom, ttbl_t &tbl, term_id_t t) {\n    // Get the term info.\n    typename ttbl_t::term_t *t_ptr = tbl.get_term_ptr(t);\n\n    // Only apply functors.\n    if (t_ptr->kind() == term::TERM_APP) {\n      binary_operation_t op = term::term_ftor(t_ptr);\n\n      std::vector<term_id_t> &args(term::term_args(t_ptr));\n      assert(args.size() == 2);\n      apply(dom, op, domvar_of_term(t), domvar_of_term(args[0]),\n            domvar_of_term(args[1]));\n    }\n  }\n\n  void eval_ftor_down(dom_t &dom, ttbl_t &tbl, term_id_t t) {\n    // Get the term info.\n    typename ttbl_t::term_t *t_ptr = tbl.get_term_ptr(t);\n\n    // Only apply functors.\n    if (t_ptr->kind() == term::TERM_APP) {\n      binary_operation_t op = term::term_ftor(t_ptr);\n      std::vector<term_id_t> &args(term::term_args(t_ptr));\n      assert(args.size() == 2);\n\n      if (boost::optional<operation_t> arith_op = conv_op<operation_t>(op)) {\n        term::InverseOps<dom_number, dom_var_t, dom_t>::apply(\n            dom, *arith_op, domvar_of_term(t), domvar_of_term(args[0]),\n            domvar_of_term(args[1]));\n      }\n    }\n  }\n\n  dom_t eval_ftor_copy(dom_t &dom, ttbl_t &tbl, term_id_t t) {\n    dom_t ret = dom;\n    eval_ftor(ret, tbl, t);\n    return ret;\n  }\n\n  binary_operation_t conv2binop(operation_t op) {\n    switch (op) {\n    case OP_ADDITION:\n      return BINOP_ADD;\n    case OP_SUBTRACTION:\n      return BINOP_SUB;\n    case OP_MULTIPLICATION:\n      return BINOP_MUL;\n    case OP_SDIV:\n      return BINOP_SDIV;\n    case OP_UDIV:\n      return BINOP_UDIV;\n    case OP_SREM:\n      return BINOP_SREM;\n    default:\n      return BINOP_UREM;\n    }\n  }\n\n  binary_operation_t conv2binop(bitwise_operation_t op) {\n    switch (op) {\n    case OP_AND:\n      return BINOP_AND;\n    case OP_OR:\n      return BINOP_OR;\n    case OP_XOR:\n      return BINOP_XOR;\n    case OP_SHL:\n      return BINOP_SHL;\n    case OP_LSHR:\n      return BINOP_LSHR;\n    default:\n      return BINOP_ASHR;\n    }\n  }\n\n  void check_terms(int line) const {\n#ifdef DEBUG_VARMAP\n    for (auto const p : _var_map) {\n      if (!(p.second < _ttbl.size())) {\n        CRAB_ERROR(\"term_equiv.hpp at line=\", line, \": \",\n                   \"term id is not the table term\");\n      }\n    }\n\n    for (auto kv : _rev_var_map) {\n      for (auto v : kv.second) {\n        auto it = _var_map.find(v);\n        if (it->second != kv.first) {\n          CRAB_ERROR(\"term_equiv.hpp at line=\", line, \": \", v,\n                     \" is mapped to t\", it->second,\n                     \" but the reverse map says that should be t\", kv.first);\n        }\n      }\n    }\n#endif\n  }\n\n  void deref(term_id_t t) {\n    std::vector<term_id_t> forgotten;\n    _ttbl.deref(t, forgotten);\n    for (term_id_t f : forgotten) {\n      typename term_map_t::iterator it(_term_map.find(f));\n      if (it != _term_map.end()) {\n        _impl -= (*it).second;\n        _term_map.erase(it);\n      }\n    }\n  }\n\n  /* Begin manipulate the reverse variable map */\n  void add_rev_var_map(rev_var_map_t &rvmap, term_id_t t, variable_t v) {\n    auto it = rvmap.find(t);\n    if (it != rvmap.end()) {\n      it->second.insert(v);\n    } else {\n      var_set_t varset;\n      varset.insert(v);\n      rvmap.insert(std::make_pair(t, varset));\n    }\n  }\n\n  void remove_rev_var_map(term_id_t t, variable_t v) {\n    auto it = _rev_var_map.find(t);\n    if (it != _rev_var_map.end()) {\n      it->second.erase(v);\n      if (it->second.empty()) {\n        _rev_var_map.erase(it);\n      }\n    }\n  }\n  /* End manipulate the reverse variable map */\n\n  void rebind_var(variable_t &x, term_id_t tx) {\n    _ttbl.add_ref(tx);\n\n    auto it(_var_map.find(x));\n    if (it != _var_map.end()) {\n      remove_rev_var_map((*it).second, x);\n      deref((*it).second);\n      _var_map.erase(it);\n    }\n    _var_map.insert(std::make_pair(x, tx));\n    add_rev_var_map(_rev_var_map, tx, x);\n  }\n\n  // Build the tree for a linexpr, and ensure that\n  // values for the subterms are sustained.\n\n  term_id_t term_of_const(const number_t &n) {\n    dom_number dom_n(n);\n    boost::optional<term_id_t> opt_n(_ttbl.find_const(dom_n));\n    if (opt_n) {\n      return *opt_n;\n    } else {\n      term_id_t term_n(_ttbl.make_const(dom_n));\n      dom_var_t v = domvar_of_term(term_n);\n\n      dom_linexp_t exp(n);\n      _impl.assign(v, exp);\n      return term_n;\n    }\n  }\n\n  term_id_t term_of_var(variable_t v, var_map_t &var_map,\n                        rev_var_map_t &rvar_map, ttbl_t &ttbl) {\n    auto it(var_map.find(v));\n    if (it != var_map.end()) {\n      // assert((*it).first == v);\n      assert(ttbl.size() > (*it).second);\n      return (*it).second;\n    } else {\n      // Allocate a fresh term\n      term_id_t id(ttbl.fresh_var());\n      var_map[v] = id;\n      add_rev_var_map(rvar_map, id, v);\n      ttbl.add_ref(id);\n      return id;\n    }\n  }\n\n  term_id_t term_of_var(variable_t v) {\n    return term_of_var(v, _var_map, _rev_var_map, _ttbl);\n  }\n\n  term_id_t term_of_linterm(linterm_t term) {\n    if (term.first == 1) {\n      return term_of_var(term.second);\n    } else {\n      return build_term(OP_MULTIPLICATION, term_of_const(term.first),\n                        term_of_var(term.second));\n    }\n  }\n\n  // OpTy = [operation_t | bitwise_operation_t]\n  template <typename OpTy>\n  term_id_t build_term(OpTy op, term_id_t ty, term_id_t tz) {\n    // Check if the term already exists\n    binary_operation_t binop = conv2binop(op);\n    boost::optional<term_id_t> eopt(_ttbl.find_ftor(binop, ty, tz));\n    if (eopt) {\n      return *eopt;\n    } else {\n      // Create the term\n      term_id_t tx = _ttbl.apply_ftor(binop, ty, tz);\n      dom_var_t v(domvar_of_term(tx));\n      dom_var_t y(domvar_of_term(ty));\n      dom_var_t z(domvar_of_term(tz));\n\n      // Set evaluation\n      CRAB_LOG(\"term\", crab::outs() << \"Prev: \" << _impl << \"\\n\");\n      _impl.apply(op, v, y, z);\n\n      CRAB_LOG(\"term\", crab::outs() << \"Should have \" << v << \" := \" << y << op\n                                    << z << \"\\n\";\n               crab::outs() << _impl << \"\\n\";);\n      return tx;\n    }\n  }\n\n  term_id_t build_function(term_id_t ty, term_id_t tz) {\n    binary_operation_t op = BINOP_FUNCTION;\n    // Check if the term already exists\n    boost::optional<term_id_t> eopt(_ttbl.find_ftor(op, ty, tz));\n    if (eopt) {\n      return *eopt;\n    } else {\n      // Create the term\n      term_id_t tx = _ttbl.apply_ftor(op, ty, tz);\n      return tx;\n    }\n  }\n\n  term_id_t build_linexpr(linear_expression_t &e) {\n    number_t cst = e.constant();\n    typename linear_expression_t::iterator it(e.begin());\n    if (it == e.end())\n      return term_of_const(cst);\n\n    term_id_t t;\n    if (cst == 0) {\n      t = term_of_linterm(*it);\n      ++it;\n    } else {\n      t = term_of_const(cst);\n    }\n    for (; it != e.end(); ++it) {\n      t = build_term(OP_ADDITION, t, term_of_linterm(*it));\n    }\n\n    CRAB_LOG(\"term\", crab::outs() << \"Should have \" << domvar_of_term(t)\n                                  << \" := \" << e << \"\\n\"\n                                  << _impl << \"\\n\");\n    return t;\n  }\n\n  dom_var_t domvar_of_term(term_id_t id) {\n    typename term_map_t::iterator it(_term_map.find(id));\n    if (it != _term_map.end()) {\n      return (*it).second;\n    } else {\n      // Allocate a fresh variable\n      dom_var_t dvar(_alloc.next());\n      _term_map.insert(std::make_pair(id, dvar));\n      return dvar;\n    }\n  }\n\n  dom_var_t domvar_of_var(variable_t v) {\n    return domvar_of_term(term_of_var(v));\n  }\n\n  // Remap a linear constraint to the domain.\n  dom_linexp_t rename_linear_expr(linear_expression_t exp) {\n    number_t cst(exp.constant());\n    dom_linexp_t dom_exp(cst);\n    for (auto v : exp.variables()) {\n      dom_exp = dom_exp + exp[v] * domvar_of_var(v);\n    }\n    return dom_exp;\n  }\n\n  dom_lincst_t rename_linear_cst(linear_constraint_t cst) {\n    return dom_lincst_t(rename_linear_expr(cst.expression()),\n                        (typename dom_lincst_t::kind_t)cst.kind());\n  }\n\n  // Assumption: vars(exp) subseteq keys(map)\n  // XXX JNL: exp can have variables that are not in rev_map (e.g.,\n  // some generated by build_linexpr).\n  boost::optional<linear_expression_t>\n  rename_linear_expr_rev(dom_linexp_t exp, rev_map_t rev_map) const {\n    number_t cst(exp.constant());\n    linear_expression_t rev_exp(cst);\n    for (auto v : exp.variables()) {\n      auto it = rev_map.find(v);\n      if (it != rev_map.end()) {\n        variable_t v_out((*it).second);\n        rev_exp = rev_exp + exp[v] * v_out;\n      } else\n        return boost::optional<linear_expression_t>();\n    }\n    return rev_exp;\n  }\n\n  boost::optional<linear_constraint_t>\n  rename_linear_cst_rev(dom_lincst_t cst, rev_map_t rev_map) const {\n    boost::optional<linear_expression_t> e =\n        rename_linear_expr_rev(cst.expression(), rev_map);\n    if (e)\n      return linear_constraint_t(\n          *e, (typename linear_constraint_t::kind_t)cst.kind());\n    else\n      return boost::optional<linear_constraint_t>();\n  }\n\n  boost::optional<std::pair<variable_t, variable_t>>\n  get_eq_or_diseq(linear_constraint_t cst) {\n    if (cst.is_equality() || cst.is_disequation()) {\n      if (cst.size() == 2 && cst.constant() == 0) {\n        auto it = cst.begin();\n        auto nx = it->first;\n        auto vx = it->second;\n        ++it;\n        assert(it != cst.end());\n        auto ny = it->first;\n        auto vy = it->second;\n        if (nx == (ny * -1)) {\n          return std::make_pair(vx, vy);\n        }\n      }\n    }\n    return boost::optional<std::pair<variable_t, variable_t>>();\n  }\n\n  struct WidenOp {\n    dom_t apply(dom_t before, dom_t after) { return before || after; }\n  };\n\n  template <typename Thresholds> struct WidenWithThresholdsOp {\n    const Thresholds &m_ts;\n\n    WidenWithThresholdsOp(const Thresholds &ts) : m_ts(ts) {}\n\n    dom_t apply(dom_t before, dom_t after) {\n      return before.widening_thresholds(after, m_ts);\n    }\n  };\n\n  template <typename WidenOp>\n  term_domain_t widening(term_domain_t o, WidenOp widen_op) {\n\n    // The left operand of the widenning cannot be closed, otherwise\n    // termination is not ensured. However, if the right operand is\n    // close precision may be improved.\n    o.normalize();\n    if (is_bottom()) {\n      return o;\n    } else if (o.is_bottom()) {\n      return *this;\n    } else {\n      // First, we need to compute the new term table.\n      ttbl_t out_tbl;\n      // Mapping of (term, term) pairs to terms in the join state\n      typename ttbl_t::gener_map_t gener_map;\n\n      var_map_t out_vmap;\n      rev_var_map_t out_rvmap;\n      dom_var_alloc_t palloc(_alloc, o._alloc);\n\n      // For each program variable in state, compute a generalization\n      for (auto p : _var_map) {\n        variable_t v(p.first);\n        term_id_t tx(term_of_var(v));\n        term_id_t ty(o.term_of_var(v));\n\n        term_id_t tz = _ttbl.generalize(o._ttbl, tx, ty, out_tbl, gener_map);\n        out_vmap[v] = tz;\n        add_rev_var_map(out_rvmap, tz, v);\n      }\n\n      // Rename the common terms together\n      dom_t x_impl(_impl);\n      dom_t y_impl(o._impl);\n\n      // Perform the mapping\n      term_map_t out_map;\n      std::vector<dom_var_t> out_varnames;\n      for (auto p : gener_map) {\n        auto txy = p.first;\n        term_id_t tz = p.second;\n        dom_var_t vt(palloc.next());\n        out_map.insert(std::make_pair(tz, vt));\n\n        dom_var_t vx = domvar_of_term(txy.first);\n        dom_var_t vy = o.domvar_of_term(txy.second);\n\n        out_varnames.push_back(vt);\n\n        x_impl.assign(vt, vx);\n        y_impl.assign(vt, vy);\n      }\n\n      x_impl.project(out_varnames);\n      y_impl.project(out_varnames);\n\n      dom_t x_widen_y = widen_op.apply(x_impl, y_impl);\n\n      for (auto p : out_vmap)\n        out_tbl.add_ref(p.second);\n\n      CRAB_LOG(\"term\", crab::outs()\n                           << \"============ WIDENING ==================\";\n               crab::outs() << x_impl << \"\\n~~~~~~~~~~~~~~~~\";\n               crab::outs() << y_impl << \"\\n----------------\";\n               crab::outs() << x_widen_y << \"\\n================\"\n                            << \"\\n\");\n\n      term_domain_t res(std::move(palloc), std::move(out_vmap),\n\t\t\tstd::move(out_rvmap), std::move(out_tbl),\n\t\t\tstd::move(out_map), std::move(x_widen_y));\n      return res;\n    }\n  }\n\n  // Choose one non-var term from the equivalence class\n  // associated with t.\n  template <typename Range>\n  boost::optional<term_id_t> choose_non_var(ttbl_t &ttbl, const Range &terms) {\n    std::vector<term_id_t> non_var_terms(terms.size());\n    auto it = std::copy_if(terms.begin(), terms.end(), non_var_terms.begin(),\n                           [&ttbl](term_id_t t) {\n                             typename ttbl_t::term_t *t_ptr =\n                                 ttbl.get_term_ptr(t);\n                             return (t_ptr && t_ptr->kind() == term::TERM_APP);\n                           });\n    non_var_terms.resize(std::distance(non_var_terms.begin(), it));\n    if (non_var_terms.empty()) {\n      return boost::optional<term_id_t>();\n    } else {\n      // TODO: the heuristics as described in the VMCAI'16 paper\n      // that chooses the one that has more references each class.\n      return *(non_var_terms.begin());\n    }\n  }\n\n  term_id_t build_dag_term(ttbl_t &ttbl, int t,\n                           term::congruence_closure_solver<ttbl_t> &solver,\n                           ttbl_t &out_ttbl, std::vector<int> &stack,\n                           std::map<int, term_id_t> &cache) {\n\n    // already processed\n    auto it = cache.find(t);\n    if (it != cache.end()) {\n#ifdef DEBUG_MEET\n      crab::outs() << \"Found in cache: \";\n      crab::outs() << \"t\" << t << \" --> \"\n                   << \"t\" << it->second << \"\\n\";\n#endif\n      return it->second;\n    }\n\n    // break the cycle with a fresh variable\n    if (std::find(stack.begin(), stack.end(), t) != stack.end()) {\n      term_id_t v = out_ttbl.fresh_var();\n#ifdef DEBUG_MEET\n      crab::outs() << \"Detected cycle: \";\n      crab::outs() << \"t\" << t << \" --> \"\n                   << \"t\" << v << \"\\n\";\n#endif\n      return v;\n    }\n\n    stack.push_back(t);\n    auto membs = solver.get_members(t);\n    boost::optional<term_id_t> f = choose_non_var(ttbl, membs);\n\n    if (!f) {\n      // no concrete definition exists return a fresh variable\n      term_id_t v = out_ttbl.fresh_var();\n      auto res = cache.insert(std::make_pair(t, v));\n      stack.pop_back();\n#ifdef DEBUG_MEET\n      crab::outs() << \"No concrete definition: \";\n      crab::outs() << \"t\" << t << \" --> \"\n                   << \"t\" << (res.first)->second << \"\\n\";\n#endif\n      return (res.first)->second;\n    } else {\n      // traverse recursively the term\n      typename ttbl_t::term_t *f_ptr = ttbl.get_term_ptr(*f);\n#ifdef DEBUG_MEET\n      crab::outs() << \"Traversing recursively the term \"\n                   << \"t\" << *f << \":\";\n      crab::outs() << *f_ptr << \"\\n\";\n#endif\n      std::vector<term_id_t> &args(term::term_args(f_ptr));\n      std::vector<term_id_t> res_args;\n      res_args.reserve(args.size());\n      for (term_id_t c : args) {\n        res_args.push_back(build_dag_term(ttbl, solver.get_class(c), solver,\n                                          out_ttbl, stack, cache));\n      }\n      auto res = cache.insert(std::make_pair(\n          t, out_ttbl.apply_ftor(term::term_ftor(f_ptr), res_args)));\n      stack.pop_back();\n#ifdef DEBUG_MEET\n      crab::outs() << \"Finished recursive case: \";\n      crab::outs() << \"t\" << t << \" --> \"\n                   << \"t\" << (res.first)->second << \"\\n\";\n#endif\n      return (res.first)->second;\n    }\n  }\n\npublic:\n  void set_to_top() {\n    term_domain abs(true);\n    std::swap(*this, abs);\n  }\n\n  void set_to_bottom() {\n    term_domain abs(false);\n    std::swap(*this, abs);\n  }\n\n  // void set_to_bottom(){\n  //   this->_is_bottom = true;\n  // }\n\n  term_domain() : _is_bottom(false) {}\n\n  term_domain(const term_domain_t &o)\n      : _is_bottom(o._is_bottom), _ttbl(o._ttbl), _impl(o._impl),\n        _alloc(o._alloc), _var_map(o._var_map), _rev_var_map(o._rev_var_map),\n        _term_map(o._term_map), changed_terms(o.changed_terms) {\n    crab::CrabStats::count(getDomainName() + \".count.copy\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".copy\");\n    check_terms(__LINE__);\n  }\n\n  term_domain_t &operator=(const term_domain_t &o) {\n    crab::CrabStats::count(getDomainName() + \".count.copy\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".copy\");\n\n    o.check_terms(__LINE__);\n    if (this != &o) {\n      _is_bottom = o._is_bottom;\n      _ttbl = o._ttbl;\n      _impl = o._impl;\n      _alloc = o._alloc;\n      _var_map = o._var_map;\n      _rev_var_map = o._rev_var_map;\n      _term_map = o._term_map;\n      changed_terms = o.changed_terms;\n    }\n    check_terms(__LINE__);\n    return *this;\n  }\n\n  bool is_bottom() { return _is_bottom; }\n\n  bool is_top() { return !_var_map.size() && !is_bottom(); }\n\n  bool is_normalized() {\n    return changed_terms.size() == 0;\n    // return _is_normalized(_impl);\n  }\n\n  // Lattice operations\n  bool operator<=(term_domain_t o) {\n    crab::CrabStats::count(getDomainName() + \".count.leq\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".leq\");\n\n    // Require normalization of the first argument\n    this->normalize();\n\n    if (is_bottom()) {\n      return true;\n    } else if (o.is_bottom()) {\n      return false;\n    } else {\n      typename ttbl_t::term_map_t gen_map;\n      dom_var_alloc_t palloc(_alloc, o._alloc);\n\n      // Build up the mapping of o onto this, variable by variable.\n      // Assumption: the set of variables in x & o are common.\n      for (auto p : _var_map) {\n        if (!_ttbl.map_leq(o._ttbl, term_of_var(p.first),\n                           o.term_of_var(p.first), gen_map))\n          return false;\n      }\n      // We now have a mapping of reachable y-terms to x-terms.\n      // Create copies of _impl and o._impl with a common\n      // variable set.\n      dom_t x_impl(_impl);\n      dom_t y_impl(o._impl);\n\n      // Perform the mapping\n      std::vector<dom_var_t> out_varnames;\n      for (auto p : gen_map) {\n        // dom_var_t vt = _alloc.next();\n        dom_var_t vt(palloc.next());\n        dom_var_t vx = domvar_of_term(p.second);\n        dom_var_t vy = o.domvar_of_term(p.first);\n\n        out_varnames.push_back(vt);\n\n        x_impl.assign(vt, vx);\n        y_impl.assign(vt, vy);\n      }\n\n      x_impl.project(out_varnames);\n      y_impl.project(out_varnames);\n\n      return x_impl <= y_impl;\n    }\n  }\n\n  // Optimized version of | that avoids some unnecessary copies\n  void operator|=(term_domain_t o) {\n    crab::CrabStats::count(getDomainName() + \".count.join\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".join\");\n\n    // Requires normalization of both operands\n    normalize();\n    o.normalize();\n\n    if (is_bottom() || o.is_top()) {\n      *this = o;\n    } else if (o.is_bottom() || is_top()) {\n      return;\n    } else {\n      // First, we need to compute the new term table.\n      ttbl_t out_tbl;\n\n      // Mapping of (term, term) pairs to terms in the join state\n      typename ttbl_t::gener_map_t gener_map;\n\n      var_map_t out_vmap;\n      rev_var_map_t out_rvmap;\n      dom_var_alloc_t palloc(_alloc, o._alloc);\n\n      // For each program variable in state, compute a generalization\n      for (auto p : _var_map) {\n        variable_t v(p.first);\n        term_id_t tx(term_of_var(v));\n        term_id_t ty(o.term_of_var(v));\n\n        term_id_t tz = _ttbl.generalize(o._ttbl, tx, ty, out_tbl, gener_map);\n        assert(tz < out_tbl.size());\n        out_vmap[v] = tz;\n        add_rev_var_map(out_rvmap, tz, v);\n      }\n\n      // Rename the common terms together\n      // Perform the mapping\n      term_map_t out_map;\n      std::vector<dom_var_t> out_varnames;\n      for (auto p : gener_map) {\n        auto txy = p.first;\n        term_id_t tz = p.second;\n        dom_var_t vt(palloc.next());\n        out_map.insert(std::make_pair(tz, vt));\n\n        dom_var_t vx = domvar_of_term(txy.first);\n        dom_var_t vy = o.domvar_of_term(txy.second);\n\n        out_varnames.push_back(vt);\n\n        _impl.assign(vt, vx);\n        o._impl.assign(vt, vy);\n      }\n\n      _impl.project(out_varnames);\n      o._impl.project(out_varnames);\n\n      _impl |= o._impl;\n\n      for (auto p : out_vmap)\n        out_tbl.add_ref(p.second);\n\n      std::swap(_alloc, palloc);\n      std::swap(_var_map, out_vmap);\n      std::swap(_rev_var_map, out_rvmap);\n      std::swap(_ttbl, out_tbl);\n      std::swap(_term_map, out_map);\n      _is_bottom = (_impl.is_bottom() ? true : false);\n    }\n  }\n\n  term_domain_t operator|(term_domain_t o) {\n    crab::CrabStats::count(getDomainName() + \".count.join\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".join\");\n\n    // Requires normalization of both operands\n    normalize();\n    o.normalize();\n\n    if (is_bottom() || o.is_top()) {\n      return o;\n    } else if (o.is_bottom() || is_top()) {\n      return *this;\n    } else {\n      // First, we need to compute the new term table.\n      ttbl_t out_tbl;\n      // Mapping of (term, term) pairs to terms in the join state\n      typename ttbl_t::gener_map_t gener_map;\n\n      var_map_t out_vmap;\n      rev_var_map_t out_rvmap;\n      dom_var_alloc_t palloc(_alloc, o._alloc);\n\n      // For each program variable in state, compute a generalization\n      for (auto p : _var_map) {\n        variable_t v(p.first);\n        term_id_t tx(term_of_var(v));\n        term_id_t ty(o.term_of_var(v));\n\n        term_id_t tz = _ttbl.generalize(o._ttbl, tx, ty, out_tbl, gener_map);\n        assert(tz < out_tbl.size());\n        out_vmap[v] = tz;\n        add_rev_var_map(out_rvmap, tz, v);\n      }\n\n      // Rename the common terms together\n      dom_t x_impl(_impl);\n      dom_t y_impl(o._impl);\n\n      // Perform the mapping\n      term_map_t out_map;\n      std::vector<dom_var_t> out_varnames;\n      for (auto p : gener_map) {\n        auto txy = p.first;\n        term_id_t tz = p.second;\n        dom_var_t vt(palloc.next());\n        out_map.insert(std::make_pair(tz, vt));\n\n        dom_var_t vx = domvar_of_term(txy.first);\n        dom_var_t vy = o.domvar_of_term(txy.second);\n\n        out_varnames.push_back(vt);\n\n        x_impl.assign(vt, vx);\n        y_impl.assign(vt, vy);\n      }\n\n      CRAB_LOG(\"term\", crab::outs() << \"============ JOIN ==================\"\n                                    << *this << \"\\n\"\n                                    << \"~~~~~~~~~~~~~~~~\" << o << \"\\n\"\n                                    << \"----------------\"\n                                    << \"x = \" << _impl << \"y = \" << o._impl\n                                    << \"ren_0(x) = \" << x_impl\n                                    << \"ren_0(y) = \" << y_impl << \"\\n\");\n\n      x_impl.project(out_varnames);\n      y_impl.project(out_varnames);\n\n      dom_t x_join_y = x_impl | y_impl;\n\n      for (auto p : out_vmap)\n        out_tbl.add_ref(p.second);\n\n      term_domain_t res(std::move(palloc), std::move(out_vmap), std::move(out_rvmap),\n\t\t\tstd::move(out_tbl), std::move(out_map), std::move(x_join_y));\n                        \n      CRAB_LOG(\"term\", crab::outs() << \"After elimination:\\n\" << res << \"\\n\");\n\n      return res;\n    }\n  }\n\n  term_domain_t operator||(term_domain_t other) {\n    crab::CrabStats::count(getDomainName() + \".count.widening\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".widening\");\n    WidenOp op;\n    return this->widening(other, op);\n  }\n\n  term_domain_t widening_thresholds(term_domain_t other,\n                                    const iterators::thresholds<number_t> &ts) {\n    crab::CrabStats::count(getDomainName() + \".count.widening\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".widening\");\n    WidenWithThresholdsOp<iterators::thresholds<number_t>> op(ts);\n    return this->widening(other, op);\n  }\n\n  // Meet\n  term_domain_t operator&(term_domain_t o) {\n    crab::CrabStats::count(getDomainName() + \".count.meet\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".meet\");\n\n    // Does not require normalization of any of the two operands\n    if (is_bottom() || o.is_bottom()) {\n      return term_domain_t::bottom();\n    } else if (is_top()) {\n      return o;\n    } else if (o.is_top()) {\n      return *this;\n    } else {\n\n      ttbl_t out_ttbl(_ttbl);\n      std::map<term_id_t, term_id_t> copy_map;\n      // bring all terms to one ttbl\n      for (auto p : o._var_map) {\n        variable_t v(p.first);\n        term_id_t tx(o.term_of_var(v));\n        out_ttbl.copy_term(o._ttbl, tx, copy_map);\n      }\n\n      // build unifications between terms from this and o\n      std::vector<std::pair<term_id_t, term_id_t>> eqs;\n      for (auto p : _var_map) {\n        variable_t v(p.first);\n        auto it = o._var_map.find(v);\n        if (it != o._var_map.end()) {\n          term_id_t tx(term_of_var(v));\n          eqs.push_back(std::make_pair(tx, copy_map[it->second]));\n        }\n      }\n\n      // compute equivalence classes\n      term::congruence_closure_solver<ttbl_t> solver(&out_ttbl);\n      solver.run(eqs);\n\n      std::vector<int> stack;\n      std::map<int, term_id_t> cache;\n      var_map_t out_vmap;\n      rev_var_map_t out_rvmap;\n      // new map from variable to an acyclic term\n      for (auto p : _var_map) {\n        variable_t v(p.first);\n        term_id_t t_old(term_of_var(v));\n        term_id_t t_new = build_dag_term(out_ttbl, solver.get_class(t_old),\n                                         solver, out_ttbl, stack, cache);\n        out_vmap[v] = t_new;\n        add_rev_var_map(out_rvmap, t_new, v);\n      }\n      for (auto p : o._var_map) {\n        variable_t v(p.first);\n        if (out_vmap.find(v) != out_vmap.end())\n          continue;\n        term_id_t t_old(copy_map[o.term_of_var(v)]);\n        term_id_t t_new = build_dag_term(out_ttbl, solver.get_class(t_old),\n                                         solver, out_ttbl, stack, cache);\n        out_vmap[v] = t_new;\n        add_rev_var_map(out_rvmap, t_new, v);\n      }\n\n      for (auto p : out_vmap)\n        out_ttbl.add_ref(p.second);\n\n      // Rename the base domains\n      dom_var_alloc_t palloc(_alloc, o._alloc);\n      dom_t x_impl(_impl);\n      dom_t y_impl(o._impl);\n      term_map_t out_map; // map term to dom var\n      std::vector<dom_var_t> out_varnames;\n      for (auto p : out_vmap) {\n        variable_t v = p.first;\n        term_id_t t_new = p.second;\n        dom_var_t vt(palloc.next());\n        out_map.insert(std::make_pair(t_new, vt));\n        // renaming this's base domain\n        auto xit = _var_map.find(v);\n        if (xit != _var_map.end()) {\n          dom_var_t vx = domvar_of_term(xit->second);\n          x_impl.assign(vt, vx);\n        }\n        // renaming o's base domain\n        auto yit = o._var_map.find(v);\n        if (yit != o._var_map.end()) {\n          dom_var_t vy = o.domvar_of_term(yit->second);\n          y_impl.assign(vt, vy);\n        }\n        out_varnames.push_back(vt);\n      }\n\n      x_impl.project(out_varnames);\n      y_impl.project(out_varnames);\n\n      dom_t x_meet_y = x_impl & y_impl;\n\n      term_domain_t res(std::move(palloc), std::move(out_vmap),\n\t\t\tstd::move(out_rvmap), std::move(out_ttbl),\n\t\t\tstd::move(out_map), std::move(x_meet_y));\n      \n      CRAB_LOG(\"term\", crab::outs() << \"============ MEET ==================\";\n               crab::outs() << *this << \"\\n----------------\";\n               crab::outs() << o << \"\\n----------------\";\n               crab::outs() << res << \"\\n================\"\n                            << \"\\n\");\n      return res;\n    }\n  }\n\n  // Narrowing\n  term_domain_t operator&&(term_domain_t o) {\n    crab::CrabStats::count(getDomainName() + \".count.narrowing\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".narrowing\");\n\n    CRAB_WARN(\"Term narrowing operator replaced with meet\");\n    return *this & o;\n  }\n\n  // Remove a variable from the scope\n  void operator-=(variable_t v) {\n    crab::CrabStats::count(getDomainName() + \".count.forget\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".forget\");\n\n    auto it(_var_map.find(v));\n    if (it != _var_map.end()) {\n      term_id_t t = (*it).second;\n      _var_map.erase(it);\n      remove_rev_var_map(t, v);\n      deref(t);\n    }\n    CRAB_LOG(\"term\", crab::outs()\n                         << \"After removing \" << v << \": \" << *this << \"\\n\";);\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 (this->is_bottom()) {\n      return;\n    } else {\n      // dom_linexp_t dom_e(rename_linear_expr(e));\n      term_id_t tx(build_linexpr(e));\n      rebind_var(x, tx);\n\n      check_terms(__LINE__);\n\n      CRAB_LOG(\"term\", crab::outs() << \"*** Assign \" << x << \":=\" << e << \":\"\n                                    << *this << \"\\n\");\n      return;\n    }\n  }\n\n  // Apply operations to variables.\n\n  // x = y op z\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    check_terms(__LINE__);\n    if (this->is_bottom()) {\n      return;\n    } else {\n      term_id_t tx(build_term(op, term_of_var(y), term_of_var(z)));\n      rebind_var(x, tx);\n    }\n    check_terms(__LINE__);\n    CRAB_LOG(\"term\", crab::outs() << \"*** \" << x << \":=\" << y << \" \" << op\n                                  << \" \" << z << \":\" << *this << \"\\n\");\n  }\n\n  // x = y op k\n  void apply(operation_t op, variable_t x, variable_t y, number_t k) {\n    crab::CrabStats::count(getDomainName() + \".count.apply\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".apply\");\n\n    if (this->is_bottom()) {\n      return;\n    } else {\n      term_id_t tx(build_term(op, term_of_var(y), term_of_const(k)));\n      rebind_var(x, tx);\n    }\n    check_terms(__LINE__);\n    CRAB_LOG(\"term\", crab::outs() << \"*** \" << x << \":=\" << y << \" \" << op\n                                  << \" \" << k << \":\" << *this << \"\\n\");\n    return;\n  }\n\n  void backward_assign(variable_t x, linear_expression_t e, term_domain_t inv) {\n    crab::CrabStats::count(getDomainName() + \".count.backward_assign\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".backward_assign\");\n\n    crab::domains::BackwardAssignOps<term_domain_t>::assign(*this, x, e, inv);\n  }\n\n  void backward_apply(operation_t op, variable_t x, variable_t y, number_t z,\n                      term_domain_t inv) {\n    crab::CrabStats::count(getDomainName() + \".count.backward_apply\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".backward_apply\");\n\n    crab::domains::BackwardAssignOps<term_domain_t>::apply(*this, op, x, y, z,\n                                                           inv);\n  }\n\n  void backward_apply(operation_t op, variable_t x, variable_t y, variable_t z,\n                      term_domain_t inv) {\n    crab::CrabStats::count(getDomainName() + \".count.backward_apply\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".backward_apply\");\n\n    crab::domains::BackwardAssignOps<term_domain_t>::apply(*this, op, x, y, z,\n                                                           inv);\n  }\n\n  void operator+=(linear_constraint_t cst) {\n    crab::CrabStats::count(getDomainName() + \".count.add_constraints\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".add_constraints\");\n\n    CRAB_LOG(\"term\", crab::outs() << \"*** Before assume \" << cst << \":\" << *this\n                                  << \"\\n\");\n\n    typedef std::pair<variable_t, variable_t> pair_var_t;\n\n    if (boost::optional<pair_var_t> eq = get_eq_or_diseq(cst)) {\n      term_id_t tx(term_of_var((*eq).first));\n      term_id_t ty(term_of_var((*eq).second));\n      if (cst.is_disequation()) {\n        if (tx == ty) {\n          set_to_bottom();\n          CRAB_LOG(\"term\", crab::outs() << \"*** After assume \" << cst << \":\"\n                                        << *this << \"\\n\");\n          return;\n        }\n      } else {\n        // not bother if they are already equal\n        if (tx == ty)\n          return;\n\n        // congruence closure to compute equivalence classes\n        term::congruence_closure_solver<ttbl_t> solver(&_ttbl);\n        std::vector<std::pair<term_id_t, term_id_t>> eqs = {\n            std::make_pair(tx, ty)};\n        solver.run(eqs);\n\n        std::vector<int> stack;\n        std::map<int, term_id_t> cache;\n        dom_t x_impl(_impl);\n        std::vector<dom_var_t> out_varnames;\n        // new map from variable to an acyclic term\n        // and also renaming of the base domain\n        for (auto p : _var_map) {\n          variable_t v(p.first);\n          term_id_t t_old(term_of_var(v));\n          term_id_t t_new = build_dag_term(_ttbl, solver.get_class(t_old),\n                                           solver, _ttbl, stack, cache);\n\n          dom_var_t vt = domvar_of_term(t_new);\n          dom_var_t vx = domvar_of_term(t_old);\n\n          out_varnames.push_back(vt);\n          x_impl.assign(vt, vx);\n\n          rebind_var(v, t_new);\n        }\n        x_impl.project(out_varnames);\n        std::swap(_impl, x_impl);\n      }\n    }\n\n    dom_lincst_t cst_rn(rename_linear_cst(cst));\n    _impl += cst_rn;\n    // Possibly tightened some variable in cst\n    for (auto v : cst.expression().variables()) {\n      CRAB_LOG(\"term-normalization\",\n               crab::outs() << \"Added to the normalization queue \"\n                            << \"t\" << term_of_var(v) << \"[\"\n                            << domvar_of_term(term_of_var(v)) << \"] \"\n                            << \"from variable \" << v << \"\\n\";);\n      changed_terms.insert(term_of_var(v));\n    }\n\n    // Probably doesn't need to done so eagerly.\n    normalize();\n\n    CRAB_LOG(\"term\", crab::outs()\n                         << \"*** After assume \" << cst << \":\" << *this << \"\\n\");\n    return;\n  }\n\n  void operator+=(linear_constraint_system_t csts) {\n    for (auto cst : csts) {\n      this->operator+=(cst);\n    }\n  }\n\n  /*\n  // If the children of t have changed, see if re-applying\n  // the definition of t tightens the domain.\n  void tighten_term(term_id_t t)\n  {\n  dom_t tight = _impl&eval_ftor_copy(_impl, _ttbl, t);\n\n  if(!(_impl <= tight))\n  {\n  // Applying the functor has changed the domain\n  _impl = tight;\n  for(term_id_t p : _ttbl.parents(t))\n  tighten_term(p);\n  }\n  check_terms(__LINE__);\n  }\n  */\n\n  interval_t operator[](variable_t x) {\n    crab::CrabStats::count(getDomainName() + \".count.to_intervals\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".to_intervals\");\n\n    // Needed for accuracy\n    normalize();\n\n    if (is_bottom())\n      return interval_t::bottom();\n\n    auto it = _var_map.find(x);\n    if (it == _var_map.end())\n      return interval_t::top();\n\n    dom_var_t dom_x = domvar_of_term(it->second);\n\n    return _impl[dom_x];\n  }\n\n  void set(variable_t x, interval_t intv) {\n    crab::CrabStats::count(getDomainName() + \".count.assign\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".assign\");\n\n    rebind_var(x, term_of_itv(intv.lb(), intv.ub()));\n  }\n\n  void apply(int_conv_operation_t /*op*/, variable_t dst, variable_t src) {\n    // since reasoning about infinite precision we simply assign and\n    // ignore the widths.\n    assign(dst, src);\n  }\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    if (this->is_bottom()) {\n      return;\n    } else {\n      term_id_t tx(build_term(op, term_of_var(y), term_of_var(z)));\n      rebind_var(x, tx);\n    }\n    check_terms(__LINE__);\n    CRAB_LOG(\"term\", crab::outs() << \"*** \" << x << \":=\" << y << \" \" << op\n                                  << \" \" << z << \":\" << *this << \"\\n\");\n  }\n\n  void apply(bitwise_operation_t op, variable_t x, variable_t y, number_t k) {\n    crab::CrabStats::count(getDomainName() + \".count.apply\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".apply\");\n\n    if (this->is_bottom()) {\n      return;\n    } else {\n      term_id_t tx(build_term(op, term_of_var(y), term_of_const(k)));\n      rebind_var(x, tx);\n    }\n\n    check_terms(__LINE__);\n    CRAB_LOG(\"term\", crab::outs() << \"*** \" << x << \":=\" << y << \" \" << op\n                                  << \" \" << k << \":\" << *this << \"\\n\");\n    return;\n  }\n\n  /* Array operations */\n\n  virtual void array_init(variable_t /*a*/, linear_expression_t /*elem_size*/,\n                          linear_expression_t /*lb_idx*/,\n                          linear_expression_t /*ub_idx*/,\n                          linear_expression_t /*val*/) override {\n    // TODO: perform a loop of array stores if [lb_idx, ub_idx]\n    //       is finite.\n  }\n\n  virtual void array_load(variable_t lhs, variable_t a,\n                          linear_expression_t /*elem_size*/,\n                          linear_expression_t i) override {\n    crab::CrabStats::count(getDomainName() + \".count.array_read\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".array_read\");\n\n    if (this->is_bottom()) {\n      return;\n    } else {\n      /**\n       *  We treat the array load as an uninterpreted function\n       *  lhs := array_load(a, i) -->  lhs := f(a,i)\n       */\n      term_id_t t_uf(build_function(term_of_var(a), build_linexpr(i)));\n      rebind_var(lhs, t_uf);\n    }\n    check_terms(__LINE__);\n    CRAB_LOG(\"term\", crab::outs() << lhs << \":=\" << a << \"[\" << i << \"]  -- \"\n                                  << *this << \"\\n\";);\n  }\n\n  virtual void array_store(variable_t a, linear_expression_t /*elem_size*/,\n                           linear_expression_t i, linear_expression_t val,\n                           bool /*is_strong_update*/) override {\n    crab::CrabStats::count(getDomainName() + \".count.array_store\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".array_store\");\n\n    if (this->is_bottom()) {\n      return;\n    } else {\n      auto &vfac = a.name().get_var_factory();\n      /**\n       *  We treat the array store as an uninterpreted function\n       *  array_store(a, i, val) -->  tmp := f(a,i); assume(tmp == val);\n       */\n      /// -- tmp := f(a,i)\n      term_id_t t_uf(build_function(term_of_var(a), build_linexpr(i)));\n      // map always t_uf to the same variable tmp\n      variable_t tmp(vfac.get(t_uf));\n      // forget tmp\n      this->operator-=(tmp);\n      // forget the old value for t_uf, otherwise we can get\n      // incorrectly bottom when we add the constraint val == tmp.\n      _impl -= domvar_of_term(t_uf);\n      rebind_var(tmp, t_uf);\n      /// -- assume(tmp == val)\n      this->operator+=(val == tmp);\n    }\n    check_terms(__LINE__);\n    CRAB_LOG(\"term\", crab::outs() << a << \"[\" << i << \"]:=\" << val << \" -- \"\n                                  << *this << \"\\n\";);\n  }\n\n  virtual void array_store(variable_t a_new, variable_t a_old,\n                           linear_expression_t /*elem_size*/,\n                           linear_expression_t i, linear_expression_t val,\n                           bool /*is_strong_update*/) override {\n    CRAB_WARN(\"array_store in the term domain not implemented\");\n  }\n\n  virtual void array_store_range(variable_t a, linear_expression_t elem_size,\n                                 linear_expression_t i, linear_expression_t j,\n                                 linear_expression_t v) override {\n    // do nothing\n  }\n\n  virtual void array_store_range(variable_t a_new, variable_t a_old,\n                                 linear_expression_t elem_size,\n                                 linear_expression_t i, linear_expression_t j,\n                                 linear_expression_t v) override {\n    // do nothing\n  }\n\n  virtual void array_assign(variable_t lhs, variable_t rhs) override {\n    // do nothing\n  }\n\n  // backward array operations\n  void backward_array_init(variable_t a, linear_expression_t elem_size,\n                           linear_expression_t lb_idx,\n                           linear_expression_t ub_idx, linear_expression_t val,\n                           term_domain_t invariant) {}\n  void backward_array_load(variable_t lhs, variable_t a,\n                           linear_expression_t elem_size, linear_expression_t i,\n                           term_domain_t invariant) {\n    *this -= lhs;\n  }\n  void backward_array_store(variable_t a, linear_expression_t elem_size,\n                            linear_expression_t i, linear_expression_t v,\n                            bool is_strong_update, term_domain_t invariant) {}\n  void backward_array_store(variable_t a_new, variable_t a_old,\n                            linear_expression_t elem_size,\n                            linear_expression_t i, linear_expression_t v,\n                            bool is_strong_update, term_domain_t invariant) {}\n  void backward_array_store_range(variable_t a, linear_expression_t elem_size,\n                                  linear_expression_t i, linear_expression_t j,\n                                  linear_expression_t v,\n                                  term_domain_t invariant) {}\n  void backward_array_store_range(variable_t a_new, variable_t a_old,\n                                  linear_expression_t elem_size,\n                                  linear_expression_t i, linear_expression_t j,\n                                  linear_expression_t v,\n                                  term_domain_t invariant) {}\n  void backward_array_assign(variable_t lhs, variable_t rhs,\n                             term_domain_t invariant) {}\n\n  /*\n     Begin unimplemented operations\n\n     term_domain implements only standard abstract operations of\n     a numerical domain plus some array operations.  The\n     implementation of boolean and pointer operations is empty\n     because they should never be called.\n  */\n\n  // boolean operations\n  void assign_bool_cst(variable_t lhs, linear_constraint_t rhs) {}\n  void assign_bool_var(variable_t lhs, variable_t rhs, bool is_not_rhs) {}\n  void apply_binary_bool(bool_operation_t op, variable_t x, variable_t y,\n                         variable_t z) {}\n  void assume_bool(variable_t v, bool is_negated) {}\n  // backward boolean operations\n  void backward_assign_bool_cst(variable_t lhs, linear_constraint_t rhs,\n                                term_domain_t invariant) {}\n  void backward_assign_bool_var(variable_t lhs, variable_t rhs, bool is_not_rhs,\n                                term_domain_t invariant) {}\n  void backward_apply_binary_bool(bool_operation_t op, variable_t x,\n                                  variable_t y, variable_t z,\n                                  term_domain_t invariant) {}\n  // pointer operations\n  void pointer_load(variable_t lhs, variable_t rhs, linear_expression_t elem_size) {}\n  void pointer_store(variable_t lhs, variable_t rhs, linear_expression_t elem_size) {}\n  void pointer_assign(variable_t lhs, variable_t rhs, linear_expression_t offset) {}\n  void pointer_mk_obj(variable_t lhs, ikos::index_t address) {}\n  void pointer_function(variable_t lhs, varname_t func) {}\n  void pointer_mk_null(variable_t lhs) {}\n  void pointer_assume(pointer_constraint_t cst) {}\n  void pointer_assert(pointer_constraint_t cst) {}\n  /* End unimplemented operations */\n\n  void rename(const variable_vector_t &from, const variable_vector_t &to) {\n    crab::CrabStats::count(getDomainName() + \".count.rename\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".rename\");\n\n    if (is_top() || is_bottom())\n      return;\n\n    CRAB_LOG(\"term\", crab::outs() << \"Renaming {\"; for (auto v\n                                                         : from) crab::outs()\n                                                    << v << \";\";\n             crab::outs() << \"} with \"; for (auto v\n                                             : to) crab::outs()\n                                        << v << \";\";\n             crab::outs() << \"}:\\n\"; crab::outs() << *this << \"\\n\";);\n\n\n    for (unsigned i=0, sz=from.size(); i<sz; ++i) {\n      variable_t v = from[i];\n      variable_t new_v = to[i];\n      if (v == new_v) { // nothing to rename\n        continue;\n      }\n\n      { auto it = _var_map.find(new_v);\n\tif (it != _var_map.end()) {\n\t  CRAB_ERROR(getDomainName() + \"::rename assumes that \", new_v, \" does not exist\");\t  \n\t}\n      }\n\n      auto it = _var_map.find(v);\n      if (it != _var_map.end()) {\n\tterm_id_t id = it->second;\n\t_var_map.erase(it);\n\t_var_map.insert(std::make_pair(new_v, id));\n\tremove_rev_var_map(id, v);\n\tadd_rev_var_map(_rev_var_map, id, new_v);\n      }\n    }\n    \n    CRAB_LOG(\"term\", crab::outs() << \"RESULT=\" << *this << \"\\n\");\n  }\n\n  // extract operation is used during reduction with other domains.\n  void extract(const variable_t &x, linear_constraint_system_t &csts,\n               bool only_equalities /*unused*/) {\n    crab::CrabStats::count(getDomainName() + \".count.extract\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".extract\");\n\n    if (!is_normalized())\n      normalize();\n\n    if (is_bottom()) {\n      return;\n    }\n\n    // TODO: make user parameter\n    const unsigned max_eq = 10;\n    // We limit the number of equalities via\n    // constants. Otherwise, the number of equalities can be too\n    // large (e.g., with domains like array_expansion) and it\n    // would make the reduction very slow.\n\n    // Extract equalities\n    auto it = _var_map.find(x);\n    if (it != _var_map.end()) {\n      term_id_t tx = it->second;\n      auto tx_ptr = _ttbl.get_term_ptr(tx);\n\n      bool active_threshold = false;\n      if (tx_ptr->kind() == term::TERM_CONST) {\n        active_threshold = true;\n      }\n      auto &varset = _rev_var_map[tx];\n      unsigned num_eq = 0;\n      for (auto var : varset) {\n        if (active_threshold && num_eq > max_eq) {\n          return;\n        }\n        if (var.index() != x.index()) {\n          num_eq++;\n          linear_constraint_t cst(linear_expression_t(x) ==\n                                  linear_expression_t(var));\n          CRAB_LOG(\"terms\", crab::outs() << \"Extracting \" << cst << \"\\n\";);\n          csts += cst;\n        }\n      }\n    }\n  }\n\n  void forget(const variable_vector_t &variables) {\n    if (is_bottom() || is_top())\n      return;\n\n    for (auto v : variables) {\n      *this -= v;\n    }\n  }\n\n  void project(const variable_vector_t &variables) {\n    crab::CrabStats::count(getDomainName() + \".count.project\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".project\");\n\n    if (is_bottom() || is_top())\n      return;\n\n    if (variables.empty()) {\n      set_to_top();\n      return;\n    }\n\n    std::set<variable_t> s1, s2;\n    variable_vector_t s3;\n    for (auto p : _var_map)\n      s1.insert(p.first);\n    s2.insert(variables.begin(), variables.end());\n    std::set_difference(s1.begin(), s1.end(), s2.begin(), s2.end(),\n                        std::back_inserter(s3));\n    forget(s3);\n  }\n\n  void expand(variable_t x, variable_t y) {\n    crab::CrabStats::count(getDomainName() + \".count.expand\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".expand\");\n\n    if (is_bottom() || is_top()) {\n      return;\n    }\n\n    linear_expression_t e(x);\n    term_id_t tx(build_linexpr(e));\n    rebind_var(y, tx);\n\n    check_terms(__LINE__);\n  }\n\n  /* begin intrinsics operations */    \n  void intrinsic(std::string name,\n\t\t const variable_vector_t &inputs,\n\t\t const variable_vector_t &outputs) override {\n    CRAB_WARN(\"Intrinsics \", name, \" not implemented by \", getDomainName());\n  }\n\n  void backward_intrinsic(std::string name,\n\t\t\t  const variable_vector_t &inputs,\n\t\t\t  const variable_vector_t &outputs,\n\t\t\t  term_domain_t invariant) override {\n    CRAB_WARN(\"Intrinsics \", name, \" not implemented by \", getDomainName());    \n  }\n  /* end intrinsics operations */\n  \n  // Propagate information from tightened terms to\n  // parents/children.\n  void normalize() {\n    crab::CrabStats::count(getDomainName() + \".count.normalize\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".normalize\");\n    TermNormalizer<Info, typename Info::domain_t>::normalize(*this);\n  }\n\n  void minimize() {}\n\n  /// Simplify the term associated with x by given the standard\n  /// arithmetic meaning to the functors\n  bool simplify(variable_t x) {\n    crab::CrabStats::count(getDomainName() + \".count.simplify\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".simplify\");\n\n    auto it = _var_map.find(x);\n    if (it != _var_map.end()) {\n      term_id_t t = it->second;\n      simplifier_t simp(_ttbl);\n      auto nt = simp.simplify_term(t);\n      if (nt) {\n        rebind_var(x, *nt);\n        return true;\n      }\n    }\n    return false;\n  }\n\n  // Output function\n  void write(crab_os &o) {\n    crab::CrabStats::count(getDomainName() + \".count.write\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".write\");\n\n    // Normalization is not enforced in order to maintain accuracy\n    // but we force it to display all the relationships.\n    normalize();\n\n    if (is_bottom()) {\n      o << \"_|_\";\n      return;\n    }\n    if (_var_map.empty()) {\n      o << \"{}\";\n      return;\n    }\n\n    bool first = true;\n    o << \"{\";\n    for (auto p : _var_map) {\n      if (first)\n        first = false;\n      else\n        o << \", \";\n      o << p.first << \" -> t\" << p.second << \"[\" << domvar_of_term(p.second)\n        << \"]\";\n    }\n    o << \"}\";\n\n    // print underlying domain\n    o << _impl;\n\n#ifdef VERBOSE\n    /// For debugging purposes\n    o << \" ttbl={\" << _ttbl << \"}\\n\";\n#endif\n  }\n\n  linear_constraint_system_t to_linear_constraint_system() {\n    crab::CrabStats::count(getDomainName() +\n                           \".count.to_linear_constraint_system\");\n    crab::ScopedCrabStats __st__(getDomainName() +\n                                 \".to_linear_constraint_system\");\n\n    // Collect the visible terms\n    rev_map_t rev_map;\n    std::vector<std::pair<variable_t, variable_t>> equivs;\n    for (auto p : _var_map) {\n      dom_var_t dv = domvar_of_term(p.second);\n\n      auto it = rev_map.find(dv);\n      if (it == rev_map.end()) {\n        // The term has not yet been seen.\n        rev_map.insert(std::make_pair(dv, p.first));\n      } else {\n        // The term is already mapped to (*it).second,\n        // so add an equivalence.\n        equivs.push_back(std::make_pair((*it).second, p.first));\n      }\n    }\n\n    // Create a copy of _impl with only visible variables.\n    dom_t d_vis(_impl);\n    for (auto p : _term_map) {\n      dom_var_t dv = p.second;\n      if (rev_map.find(dv) == rev_map.end())\n        d_vis -= dv;\n    }\n\n    // Now build and rename the constraint system, plus equivalences.\n    dom_linsys_t dom_sys(d_vis.to_linear_constraint_system());\n\n    linear_constraint_system_t out_sys;\n    for (dom_lincst_t cst : dom_sys) {\n      auto out_cst = rename_linear_cst_rev(cst, rev_map);\n      if (!out_cst)\n        continue;\n      out_sys += *out_cst;\n    }\n\n    for (auto p : equivs) {\n      CRAB_LOG(\"term\", crab::outs() << \"Added equivalence \" << p.first << \"=\"\n                                    << p.second << \"\\n\");\n      out_sys += (p.first - p.second == 0);\n    }\n\n    // Now rename it back into the external scope.\n    return out_sys;\n  }\n\n  disjunctive_linear_constraint_system_t\n  to_disjunctive_linear_constraint_system() {\n    auto lin_csts = to_linear_constraint_system();\n    if (lin_csts.is_false()) {\n      return disjunctive_linear_constraint_system_t(true /*is_false*/);\n    } else if (lin_csts.is_true()) {\n      return disjunctive_linear_constraint_system_t(false /*is_false*/);\n    } else {\n      return disjunctive_linear_constraint_system_t(lin_csts);\n    }\n  }\n\n  static std::string getDomainName() {\n    std::string name(\"Term(\" + dom_t::getDomainName() + \")\");\n    return name;\n  }\n\n}; // class term_domain\n\n// Propagate information from tightened terms to\n// parents/children.\ntemplate <class Info, class Abs> class TermNormalizer {\npublic:\n  typedef typename term_domain<Info>::term_domain_t term_domain_t;\n  typedef typename term_domain_t::term_id_t term_id_t;\n  typedef Abs dom_t;\n  typedef typename term_domain_t::ttbl_t ttbl_t;\n  typedef boost::container::flat_set<term_id_t> term_set_t;\n\n  static void queue_push(ttbl_t &tbl,\n                         std::vector<std::vector<term_id_t>> &queue,\n                         term_id_t t) {\n    int d = tbl.depth(t);\n    if (d == 0) {\n      // if depth 0 then t is a free variable: nothing to propagate.\n      return;\n    }\n    while (queue.size() <= d) {\n      queue.push_back(std::vector<term_id_t>());\n    }\n    queue[d].push_back(t);\n  }\n\n  static void normalize(term_domain_t &abs) {\n    // First propagate down, then up.\n    std::vector<std::vector<term_id_t>> queue;\n\n    ttbl_t &ttbl(abs._ttbl);\n    dom_t &impl = abs._impl;\n\n    for (term_id_t t : abs.changed_terms) {\n      queue_push(ttbl, queue, t);\n    }\n\n    dom_t d_prime = impl;\n    // Propagate information to children.\n    // Don't need to propagate level 0, since it's for free variables\n    for (int d = queue.size() - 1; d > 0; d--) {\n      for (term_id_t t : queue[d]) {\n        typename ttbl_t::term_t *t_ptr = ttbl.get_term_ptr(t);\n        if (t_ptr->kind() != term::TERM_APP)\n          continue;\n\n        CRAB_LOG(\"term-normalization\", crab::outs() << \"Propagate to children \";\n                 t_ptr->write(crab::outs()); crab::outs() << \"\\n\";\n                 crab::outs() << \"\\tTerm table: \"; ttbl.write(crab::outs());\n                 crab::outs() << \"\\n\";);\n\n        abs.eval_ftor_down(d_prime, ttbl, t);\n        if (!(abs._impl <= d_prime)) {\n          impl = d_prime;\n\n          CRAB_LOG(\n              \"term-normalization\",\n              crab::outs() << \"\\trefinement done: enqueue children.\\n\";\n              if (impl.is_bottom()) { crab::outs() << \"\\tfound bottom\\n\"; });\n\n          // Enqueue the args.\n          typename ttbl_t::term_t *t_ptr = ttbl.get_term_ptr(t);\n          std::vector<term_id_t> &args(term::term_args(t_ptr));\n          for (term_id_t c : args) {\n            if (abs.changed_terms.find(c) == abs.changed_terms.end()) {\n              abs.changed_terms.insert(c);\n              queue[ttbl.depth(c)].push_back(c);\n            }\n          }\n        } else {\n          CRAB_LOG(\"term-normalization\", crab::outs()\n                                             << \"\\tno refinement done.\\n\";);\n        }\n      }\n    }\n\n    // Collect the parents of changed terms.\n    term_set_t up_terms;\n    std::vector<std::vector<term_id_t>> up_queue;\n    for (term_id_t t : abs.changed_terms) {\n      for (term_id_t p : ttbl.parents(t)) {\n        if (up_terms.find(p) == up_terms.end()) {\n          up_terms.insert(p);\n          CRAB_LOG(\"term-normalization\",\n                   crab::outs()\n                       << \"t\" << p << \"[\" << abs.domvar_of_term(p) << \"]\"\n                       << \" is a parent of \"\n                       << \"t\" << t << \"[\" << abs.domvar_of_term(t) << \"]\\n\";);\n          queue_push(ttbl, up_queue, p);\n        }\n      }\n    }\n\n    // Now propagate up, level by level.\n    // This may miss inferences; for example with [[x = y - z]]\n    // information about y can propagate to z.\n    assert(up_queue.size() == 0 || up_queue[0].size() == 0);\n    for (int d = 1; d < up_queue.size(); d++) {\n      // up_queue[d] shouldn't change.\n      for (term_id_t t : up_queue[d]) {\n        abs.eval_ftor(d_prime, ttbl, t);\n        CRAB_LOG(\"term-normalization\",\n                 typename ttbl_t::term_t *t_ptr = ttbl.get_term_ptr(t);\n                 crab::outs() << \"Propagate to parent \";\n                 t_ptr->write(crab::outs()); crab::outs() << \"\\n\";\n                 crab::outs() << \"\\tTerm table: \"; ttbl.write(crab::outs());\n                 crab::outs() << \"\\n\";);\n\n        if (!(impl <= d_prime)) {\n          CRAB_LOG(\"term-normalization\",\n                   crab::outs() << \"Before up propagation: \" << impl << \"\\n\";\n                   crab::outs()\n                   << \"After up propagation : \" << d_prime << \"\\n\";);\n\n          // We need to do a meet here, as\n          // impl and F(stmt)impl may be\n          // incomparable\n          impl = impl & d_prime;\n          // impl = d_prime; // Old code\n\n          CRAB_LOG(\n              \"term-normalization\",\n              crab::outs() << \"\\trefinement done: enqueue parents.\\n\";\n              if (impl.is_bottom()) { crab::outs() << \"\\tfound bottom\\n\"; });\n\n          for (term_id_t p : ttbl.parents(t)) {\n            if (up_terms.find(p) == up_terms.end()) {\n              up_terms.insert(p);\n              queue_push(ttbl, up_queue, p);\n            }\n          }\n        } else {\n          CRAB_LOG(\"term-normalization\", crab::outs()\n                                             << \"\\tno refinement done.\\n\";);\n        }\n      }\n    }\n\n    abs.changed_terms.clear();\n\n    if (abs._impl.is_bottom())\n      abs.set_to_bottom();\n  }\n};\n\n// Specialized implementation for interval domain.\n// GKG: Should modify to work with any independent attribute domain.\n#ifdef USE_TERM_INTERVAL_NORMALIZER\ntemplate <class Info, class Num, class Var>\nclass TermNormalizer<Info, interval_domain<Num, Var>> {\npublic:\n  typedef typename term_domain<Info>::term_domain_t term_domain_t;\n  typedef typename term_domain_t::term_id_t term_id_t;\n  typedef interval_domain<Num, Var> dom_t;\n  typedef typename term_domain_t::dom_var_t var_t;\n\n  typedef typename term_domain_t::ttbl_t ttbl_t;\n  typedef boost::container::flat_set<term_id_t> term_set_t;\n\n  typedef typename dom_t::interval_t interval_t;\n\n  static void queue_push(ttbl_t &tbl,\n                         std::vector<std::vector<term_id_t>> &queue,\n                         term_id_t t) {\n    int d = tbl.depth(t);\n    if (d == 0) {\n      // if depth 0 then t is a free variable: nothing to\n      // propagate.\n      return;\n    }\n    while (queue.size() <= d) {\n      queue.push_back(std::vector<term_id_t>());\n    }\n    queue[d].push_back(t);\n  }\n\n  static void normalize(term_domain_t &abs) {\n    // First propagate down, then up.\n    std::vector<std::vector<term_id_t>> queue;\n\n    ttbl_t &ttbl(abs._ttbl);\n    dom_t &impl = abs._impl;\n    if (impl.is_bottom()) {\n      abs.set_to_bottom();\n      return;\n    }\n\n    for (term_id_t t : abs.changed_terms) {\n      queue_push(ttbl, queue, t);\n    }\n\n    // Propagate information to children.\n    // Don't need to propagate level 0, since it's for free variables\n    for (int d = queue.size() - 1; d > 0; d--) {\n      for (term_id_t t : queue[d]) {\n        typename ttbl_t::term_t *t_ptr = ttbl.get_term_ptr(t);\n        if (t_ptr->kind() != term::TERM_APP)\n          continue;\n\n        std::vector<term_id_t> &args(term::term_args(t_ptr));\n        std::vector<interval_t> arg_intervals;\n        for (term_id_t c : args)\n          arg_intervals.push_back(impl[abs.domvar_of_term(c)]);\n        abs.eval_ftor_down(impl, ttbl, t);\n\n        // Enqueue the args\n        for (size_t ci = 0; ci < args.size(); ci++) {\n          term_id_t c(args[ci]);\n          var_t v = abs.domvar_of_term(c);\n          interval_t v_upd(impl[v]);\n          if (!(arg_intervals[ci] <= v_upd)) {\n            impl.set(v, arg_intervals[ci] & v_upd);\n            if (abs.changed_terms.find(c) == abs.changed_terms.end()) {\n              abs.changed_terms.insert(c);\n              queue[ttbl.depth(c)].push_back(c);\n            }\n          }\n        }\n      }\n    }\n\n    // Collect the parents of changed terms.\n    term_set_t up_terms;\n    std::vector<std::vector<term_id_t>> up_queue;\n    for (term_id_t t : abs.changed_terms) {\n      for (term_id_t p : ttbl.parents(t)) {\n        if (up_terms.find(p) == up_terms.end()) {\n          up_terms.insert(p);\n          queue_push(ttbl, up_queue, p);\n        }\n      }\n    }\n\n    // Now propagate up, level by level.\n    assert(up_queue.size() == 0 || up_queue[0].size() == 0);\n    for (int d = 1; d < up_queue.size(); d++) {\n      // up_queue[d] shouldn't change.\n      for (term_id_t t : up_queue[d]) {\n        var_t v = abs.domvar_of_term(t);\n        interval_t v_interval = impl[v];\n\n        abs.eval_ftor(impl, ttbl, t);\n\n        interval_t v_upd = impl[v];\n        if (!(v_interval <= v_upd)) {\n          impl.set(v, v_interval & v_upd);\n          for (term_id_t p : ttbl.parents(t)) {\n            if (up_terms.find(p) == up_terms.end()) {\n              up_terms.insert(p);\n              queue_push(ttbl, up_queue, p);\n            }\n          }\n        }\n      }\n    }\n\n    abs.changed_terms.clear();\n\n    if (impl.is_bottom())\n      abs.set_to_bottom();\n  }\n};\n#endif\n\ntemplate <typename Info> struct abstract_domain_traits<term_domain<Info>> {\n  typedef typename Info::Number number_t;\n  typedef typename Info::VariableName varname_t;\n};\n\ntemplate <typename Info> class reduced_domain_traits<term_domain<Info>> {\npublic:\n  typedef term_domain<Info> term_domain_t;\n  typedef typename term_domain_t::variable_t variable_t;\n  typedef typename term_domain_t::linear_constraint_system_t\n      linear_constraint_system_t;\n\n  static void extract(term_domain_t &dom, const variable_t &x,\n                      linear_constraint_system_t &csts, bool only_equalities) {\n    dom.extract(x, csts, only_equalities);\n  }\n};\n\n} // namespace domains\n} // namespace crab\n\n#pragma GCC diagnostic pop\n", "meta": {"hexsha": "c75b197ceceef5046d48f6f3ac9df7b8a2f43946", "size": 67758, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/crab/domains/term_equiv.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/term_equiv.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/term_equiv.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": 32.5759615385, "max_line_length": 87, "alphanum_fraction": 0.5882995366, "num_tokens": 17515, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174789, "lm_q2_score": 0.6297746074044135, "lm_q1q2_score": 0.4808226942304301}}
{"text": "#include <tesseract_common/macros.h>\nTESSERACT_COMMON_IGNORE_WARNINGS_PUSH\n#include <gtest/gtest.h>\n#include <Eigen/Geometry>\nTESSERACT_COMMON_IGNORE_WARNINGS_POP\n\n#include <tesseract_urdf/origin.h>\n#include \"tesseract_urdf_common_unit.h\"\n\n/**\n * @brief This function was pulled from urdfdom library to verify that the method of using Eigen produces\n * the same result. This is only used for this unit test and Eigen is used within the origin class to\n * convert roll, pitch and yaw to a rotation matrix.\n */\nEigen::Quaterniond fromRPY(double roll, double pitch, double yaw)\n{\n  double phi, the, psi;\n\n  phi = roll / 2.0;\n  the = pitch / 2.0;\n  psi = yaw / 2.0;\n\n  double x, y, z, w;\n  x = std::sin(phi) * std::cos(the) * std::cos(psi) - std::cos(phi) * std::sin(the) * std::sin(psi);\n  y = std::cos(phi) * std::sin(the) * std::cos(psi) + std::sin(phi) * std::cos(the) * std::sin(psi);\n  z = std::cos(phi) * std::cos(the) * std::sin(psi) - std::sin(phi) * std::sin(the) * std::cos(psi);\n  w = std::cos(phi) * std::cos(the) * std::cos(psi) + std::sin(phi) * std::sin(the) * std::sin(psi);\n\n  return Eigen::Quaterniond(w, x, y, z);\n}\n\nTEST(TesseractURDFUnit, parse_origin)  // NOLINT\n{\n  {\n    std::string str = R\"(<origin xyz=\"0 0 0\" rpy=\"0 0 0\"/>)\";\n    Eigen::Isometry3d origin;\n    EXPECT_TRUE(runTest<Eigen::Isometry3d>(origin, &tesseract_urdf::parseOrigin, str, \"origin\", 2));\n    EXPECT_TRUE(origin.isApprox(Eigen::Isometry3d::Identity(), 1e-8));\n  }\n\n  {\n    std::string str = R\"(<origin xyz=\"0 0 0\" wxyz=\"1 0 0 0\"/>)\";\n    Eigen::Isometry3d origin;\n    EXPECT_TRUE(runTest<Eigen::Isometry3d>(origin, &tesseract_urdf::parseOrigin, str, \"origin\", 2));\n    EXPECT_TRUE(origin.isApprox(Eigen::Isometry3d::Identity(), 1e-8));\n  }\n\n  {\n    std::string str = R\"(<origin xyz=\"0 0 0\" wxyz=\"0.8719632 0.247934 0.177848 0.3828563\"/>)\";\n    Eigen::Isometry3d origin;\n    Eigen::Isometry3d check = Eigen::Isometry3d::Identity();\n    check.linear() << 0.6435823, -0.5794841, 0.5000000, 0.7558624, 0.5838996, -0.2961981, -0.1203077, 0.5685591,\n        0.8137977;\n    EXPECT_TRUE(runTest<Eigen::Isometry3d>(origin, &tesseract_urdf::parseOrigin, str, \"origin\", 2));\n    EXPECT_TRUE(origin.isApprox(check, 1e-6));\n  }\n\n  {\n    std::string str = R\"(<origin xyz=\"0 0 0\" rpy=\"0.3490659 0.5235988 0.7330383\"/>)\";\n    Eigen::Isometry3d origin;\n    Eigen::Isometry3d check = Eigen::Isometry3d::Identity();\n    check.linear() = fromRPY(0.3490659, 0.5235988, 0.7330383).toRotationMatrix();\n    EXPECT_TRUE(runTest<Eigen::Isometry3d>(origin, &tesseract_urdf::parseOrigin, str, \"origin\", 2));\n    EXPECT_TRUE(origin.isApprox(check, 1e-6));\n  }\n\n  {\n    std::string str = R\"(<origin xyz=\"0 2.5 0\" rpy=\"3.14159265359 0 0\"/>)\";\n    Eigen::Isometry3d origin;\n    EXPECT_TRUE(runTest<Eigen::Isometry3d>(origin, &tesseract_urdf::parseOrigin, str, \"origin\", 2));\n    EXPECT_TRUE(origin.translation().isApprox(Eigen::Vector3d(0, 2.5, 0), 1e-8));\n    EXPECT_TRUE(origin.matrix().col(0).head(3).isApprox(Eigen::Vector3d(1, 0, 0), 1e-8));\n    EXPECT_TRUE(origin.matrix().col(1).head(3).isApprox(Eigen::Vector3d(0, -1, 0), 1e-8));\n    EXPECT_TRUE(origin.matrix().col(2).head(3).isApprox(Eigen::Vector3d(0, 0, -1), 1e-8));\n\n    Eigen::Quaterniond check_q = fromRPY(3.14159265359, 0, 0);\n    Eigen::Quaterniond orig_q(origin.rotation());\n\n    EXPECT_TRUE(check_q.matrix().isApprox(orig_q.matrix(), 1e-8));\n  }\n\n  {\n    std::string str = R\"(<origin xyz=\"0 2.5 0\" rpy=\"3.14 0 0\" wxyz=\"1 0 0 0\"/>)\";\n    Eigen::Isometry3d origin;\n    EXPECT_TRUE(runTest<Eigen::Isometry3d>(origin, &tesseract_urdf::parseOrigin, str, \"origin\", 2));\n    EXPECT_TRUE(origin.translation().isApprox(Eigen::Vector3d(0, 2.5, 0), 1e-8));\n    EXPECT_TRUE(origin.rotation().isApprox(Eigen::Matrix3d::Identity(), 1e-8));\n  }\n\n  {\n    std::string str = R\"(<origin xyz=\"0 0 0\"/>)\";\n    Eigen::Isometry3d origin;\n    EXPECT_TRUE(runTest<Eigen::Isometry3d>(origin, &tesseract_urdf::parseOrigin, str, \"origin\", 2));\n    EXPECT_TRUE(origin.isApprox(Eigen::Isometry3d::Identity(), 1e-8));\n  }\n\n  {\n    std::string str = R\"(<origin rpy=\"0 0 0\"/>)\";\n    Eigen::Isometry3d origin;\n    EXPECT_TRUE(runTest<Eigen::Isometry3d>(origin, &tesseract_urdf::parseOrigin, str, \"origin\", 2));\n    EXPECT_TRUE(origin.isApprox(Eigen::Isometry3d::Identity(), 1e-8));\n  }\n\n  {\n    std::string str = R\"(<origin xyz=\"0 0 a\"/>)\";\n    Eigen::Isometry3d origin;\n    EXPECT_FALSE(runTest<Eigen::Isometry3d>(origin, &tesseract_urdf::parseOrigin, str, \"origin\", 2));\n  }\n\n  {\n    std::string str = R\"(<origin rpy=\"0 0 a\"/>)\";\n    Eigen::Isometry3d origin;\n    EXPECT_FALSE(runTest<Eigen::Isometry3d>(origin, &tesseract_urdf::parseOrigin, str, \"origin\", 2));\n  }\n\n  {\n    std::string str = R\"(<origin wxyz=\"1 0 0 a\"/>)\";\n    Eigen::Isometry3d origin;\n    EXPECT_FALSE(runTest<Eigen::Isometry3d>(origin, &tesseract_urdf::parseOrigin, str, \"origin\", 2));\n  }\n\n  {\n    std::string str = R\"(<origin />)\";\n    Eigen::Isometry3d origin;\n    EXPECT_FALSE(runTest<Eigen::Isometry3d>(origin, &tesseract_urdf::parseOrigin, str, \"origin\", 2));\n  }\n}\n", "meta": {"hexsha": "a756253394fd59810e812a672ab334fca52f23a8", "size": 5039, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tesseract_urdf/test/tesseract_urdf_origin_unit.cpp", "max_stars_repo_name": "jf---/tesseract", "max_stars_repo_head_hexsha": "d04e9ddf2f940e780d1c8262eca7a6c8f5db2260", "max_stars_repo_licenses": ["BSD-2-Clause", "Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tesseract_urdf/test/tesseract_urdf_origin_unit.cpp", "max_issues_repo_name": "jf---/tesseract", "max_issues_repo_head_hexsha": "d04e9ddf2f940e780d1c8262eca7a6c8f5db2260", "max_issues_repo_licenses": ["BSD-2-Clause", "Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-03-25T17:43:35.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-25T17:43:35.000Z", "max_forks_repo_path": "tesseract_urdf/test/tesseract_urdf_origin_unit.cpp", "max_forks_repo_name": "jf---/tesseract", "max_forks_repo_head_hexsha": "d04e9ddf2f940e780d1c8262eca7a6c8f5db2260", "max_forks_repo_licenses": ["BSD-2-Clause", "Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.3671875, "max_line_length": 112, "alphanum_fraction": 0.6578686247, "num_tokens": 1760, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.629774600455747, "lm_q1q2_score": 0.4808226821468545}}
{"text": "/**\r\n * @file shapeMatching.cpp\r\n * @brief ShapeMatching plugin for Maya\r\n * @section LICENSE The MIT License\r\n * @section  requirements:  Eigen library, Maya\r\n * @section Limitation: the shapes must be connected\r\n * @version 0.10\r\n * @date  1/Nov/2013\r\n * @author Shizuo KAJI\r\n */\r\n\r\n#pragma comment(linker, \"/export:initializePlugin /export:uninitializePlugin\")\r\n\r\n#include \"StdAfx.h\"\r\n\r\n#include <maya/MFnPlugin.h>\r\n\r\n#include <numeric>\r\n#include <Eigen/Dense>\r\n\r\n\r\nusing namespace std;\r\nusing namespace Eigen;\r\n\r\nclass ShapeMatching : public MPxDeformerNode\r\n{\r\npublic:\r\n    ShapeMatching() {};\r\n    virtual MStatus deform( MDataBlock& data, MItGeometry& itGeo, const MMatrix &localToWorldMatrix, unsigned int mIndex );\r\n    static  void*   creator();\r\n    static  MStatus initialize();\r\n\tstatic MTypeId id;\r\n    static MString nodeName;\r\n\tstatic MObject aStartShape;\r\n    static MObject aActive;\r\n\tstatic MObject aSlider;\r\n\tstatic MObject aDeltaTime;\r\n\tstatic MObject aStiffness;\r\n\tstatic MObject aAttenuation;\r\nprivate:\r\n    MatrixXd current, velocity;\r\n    Matrix3d rotationPart(const Matrix3d m);\r\n};\r\n\r\n\r\nMTypeId ShapeMatching::id( 0x00000020 );\r\nMString ShapeMatching::nodeName( \"shapeMatching\" );\r\nMObject ShapeMatching::aStartShape;\r\nMObject ShapeMatching::aSlider;\r\nMObject ShapeMatching::aActive;\r\nMObject ShapeMatching::aDeltaTime;\r\nMObject ShapeMatching::aStiffness;\r\nMObject ShapeMatching::aAttenuation;\r\n\r\nvoid* ShapeMatching::creator() { return new ShapeMatching; }\r\n\r\n// Compute\r\nMStatus ShapeMatching::deform( MDataBlock& data, MItGeometry& itGeo, const MMatrix &localToWorldMatrix, unsigned int mIndex ){\r\n    MStatus status;\r\n//    MThreadUtils::syncNumOpenMPThreads();    // for OpenMP\r\n    \r\n    // read start shape\r\n    MObject oStartShape = data.inputValue( aStartShape ).asMesh();\r\n    if ( oStartShape.isNull() )    {\r\n        return MS::kSuccess;\r\n    }\r\n    MFnMesh fnStartShape( oStartShape, &status );\r\n    CHECK_MSTATUS_AND_RETURN_IT( status );\r\n    MPointArray endPoints, pts;\r\n    itGeo.allPositions(pts);\r\n    fnStartShape.getPoints( endPoints );\r\n    // read attributes\r\n    MDataHandle hSlider = data.inputValue( aSlider );\r\n    bool active = data.inputValue( aActive ).asBool();\r\n    float delta = data.inputValue( aDeltaTime ).asFloat();\r\n    float stiffness = data.inputValue( aStiffness ).asFloat();\r\n    float attenution = data.inputValue( aAttenuation ).asFloat();\r\n    int num = pts.length();\r\n    // first-time setup\r\n    if (!active){\r\n\t\tcurrent = MatrixXd(3,num);\r\n\t\tvelocity = MatrixXd::Zero(3,num);\r\n        for (int i = 0; i < num; i++) {\r\n            current(0,i) = pts[i].x;\r\n            current(1,i) = pts[i].y;\r\n            current(2,i) = pts[i].z;\r\n        }\r\n        return MS::kSuccess;\r\n    }\r\n    // number of current and end points must be equal\r\n    if (endPoints.length() != num){\r\n        return MS::kSuccess;\r\n    }\r\n    // load end shape\r\n    MatrixXd end(3,num);\r\n    for (int i = 0; i < num; i++) {\r\n        end(0,i) = endPoints[i].x;\r\n        end(1,i) = endPoints[i].y;\r\n        end(2,i) = endPoints[i].z;\r\n    }\r\n    // compute next step\r\n    Vector3d current_center = current.rowwise().mean();\r\n    Vector3d end_center = end.rowwise().mean();\r\n    \r\n    // prepare moment matrix\r\n    current.colwise() -= current_center;\r\n    end.colwise() -= end_center;\r\n    Matrix3d moment = end * current.transpose();\r\n\t// Update current vertices and velocity of vertices\r\n    velocity += delta * stiffness * (rotationPart(moment) * end - current);\r\n    current += delta * velocity;\r\n    velocity *= attenution;\r\n    current.colwise() += current_center;\r\n\r\n    // update points\r\n    for (int i = 0; i < num; i++) {\r\n        pts[i].x = current(0,i);\r\n        pts[i].y = current(1,i);\r\n        pts[i].z = current(2,i);\r\n    }\r\n    itGeo.setAllPositions(pts);\r\n\r\n\treturn MS::kSuccess;\r\n}\r\n\r\n// Polar decomposition\r\nMatrix3d ShapeMatching::rotationPart(const Matrix3d m){\r\n    Matrix3d A= m*m.transpose();\r\n\tSelfAdjointEigenSolver<Matrix3d> eigensolver;\r\n\teigensolver.computeDirect(A);\r\n    Vector3d s = eigensolver.eigenvalues();\r\n    Matrix3d U = Matrix3d(eigensolver.eigenvectors());\r\n    s << sqrtf(s[0]), sqrtf(s[1]), sqrtf(s[2]);\r\n    DiagonalMatrix<double,3> D(1.0f/s[0], 1.0f/s[1], 1.0f/s[2]);\r\n    return m * U*D*U.transpose();\r\n}\r\n\r\n\r\n\r\n// setup attributes\r\nMStatus ShapeMatching::initialize(){\r\n    MFnTypedAttribute tAttr;\r\n\tMFnNumericAttribute nAttr;\r\n\r\n\taStartShape = tAttr.create( \"startShape\", \"ss\", MFnData::kMesh );\r\n    addAttribute( aStartShape );\r\n    attributeAffects( aStartShape, outputGeom );\r\n\taSlider = nAttr.create( \"slider\", \"slider\", MFnNumericData::kFloat, 0.0 );\r\n    addAttribute( aSlider );\r\n    attributeAffects( aSlider, outputGeom );\r\n\taActive = nAttr.create( \"active\", \"active\", MFnNumericData::kBoolean, 0 );\r\n    addAttribute( aActive );\r\n    attributeAffects( aActive, outputGeom );\r\n\taDeltaTime = nAttr.create( \"delta\", \"delta\", MFnNumericData::kFloat, 0.01 );\r\n    addAttribute( aDeltaTime );\r\n\taStiffness = nAttr.create( \"stiffness\", \"stf\", MFnNumericData::kFloat, 1.0 );\r\n    addAttribute( aStiffness );\r\n\taAttenuation = nAttr.create( \"attenuation\", \"att\", MFnNumericData::kFloat, 0.9 );\r\n    addAttribute( aAttenuation );\r\n\r\n\treturn MS::kSuccess;\r\n}\r\n\r\n\r\n\r\n\r\n// (un)init plugin\r\nMStatus initializePlugin( MObject obj ){\r\n    MStatus status;\r\n    MFnPlugin plugin( obj, \"CREST\", \"0.1\", \"Any\");\r\n    status = plugin.registerNode( ShapeMatching::nodeName, ShapeMatching::id, ShapeMatching::creator, ShapeMatching::initialize, MPxNode::kDeformerNode );\r\n    CHECK_MSTATUS_AND_RETURN_IT( status );\r\n    return status;\r\n}\r\nMStatus uninitializePlugin( MObject obj ){\r\n    MStatus   status;\r\n    MFnPlugin plugin( obj );\r\n    status = plugin.deregisterNode( ShapeMatching::id );\r\n    CHECK_MSTATUS_AND_RETURN_IT( status );\r\n    return status;\r\n}\r\n\r\n", "meta": {"hexsha": "ec5fcdcc49cbd871d45cc13dbdaca0bc5fc0c067", "size": 5842, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "shapeMatching/shapeMatching.cpp", "max_stars_repo_name": "jdrese/ShapeFlowMaya", "max_stars_repo_head_hexsha": "a53d1704a7b139013e79f26179284f75dc8c9d01", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2019-04-16T07:24:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-07T02:11:04.000Z", "max_issues_repo_path": "shapeMatching/shapeMatching.cpp", "max_issues_repo_name": "shizuo-kaji/ShapeFlowMaya", "max_issues_repo_head_hexsha": "a53d1704a7b139013e79f26179284f75dc8c9d01", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "shapeMatching/shapeMatching.cpp", "max_forks_repo_name": "shizuo-kaji/ShapeFlowMaya", "max_forks_repo_head_hexsha": "a53d1704a7b139013e79f26179284f75dc8c9d01", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-04-16T02:30:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-04T07:24:57.000Z", "avg_line_length": 31.9234972678, "max_line_length": 155, "alphanum_fraction": 0.657480315, "num_tokens": 1562, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.885631476836816, "lm_q2_score": 0.5428632831725053, "lm_q1q2_score": 0.4807768111965485}}
{"text": "//---------------------------------------------------------------------------//\r\n// Copyright (c) 2013 Muhammad Junaid Muzammil <mjunaidmuzammil@gmail.com>\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://kylelutz.github.com/compute for more information.\r\n//---------------------------------------------------------------------------//\r\n\r\n\r\n#include <boost/compute/random/threefry_engine.hpp>\r\n#include <boost/compute/container/vector.hpp>\r\n#include <boost/compute/command_queue.hpp>\r\n#include <boost/compute/context.hpp>\r\n#include <boost/compute/device.hpp>\r\n#include <boost/compute/system.hpp>\r\n#include <iostream>\r\n\r\nint main() \r\n{\r\n    using boost::compute::uint_;\r\n    boost::compute::device device = boost::compute::system::default_device();\r\n    boost::compute::context context(device);\r\n    boost::compute::command_queue queue(context, device);\r\n    boost::compute::threefry_engine<> rng(queue);\r\n    boost::compute::vector<uint_> vector_ctr(20, context);\r\n    \r\n    uint32_t ctr[20];\r\n    for(int i = 0; i < 10; i++) {\r\n        ctr[i*2] = i;\r\n        ctr[i*2+1] = 0;\r\n    }\r\n    boost::compute::copy(ctr, ctr+20, vector_ctr.begin(), queue);\r\n    rng.generate(vector_ctr.begin(), vector_ctr.end(), queue);\r\n    boost::compute::copy(vector_ctr.begin(), vector_ctr.end(), ctr, queue);\r\n\r\n    for(int i = 0; i < 10; i++) {\r\n        std::cout << std::hex << ctr[i*2] << \" \" << ctr[i*2+1] << std::endl;\r\n    }\r\n    return 0;\r\n}\r\n\r\n", "meta": {"hexsha": "8253c1860ac574eb1858963a2325e092d34d9999", "size": 1564, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/compute/example/threefry_engine.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": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/compute/example/threefry_engine.cpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-04T18:00:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-04T18:00:00.000Z", "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/compute/example/threefry_engine.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 35.5454545455, "max_line_length": 80, "alphanum_fraction": 0.5792838875, "num_tokens": 382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.734119526900183, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.48077101854323073}}
{"text": "#include <iostream>\n#include <time.h>\n#include <algorithm>\n#include <vector>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/random.hpp>\n#include <LEDA/graph/graph.h>\n#include <LEDA/graph/shortest_path.h>\n\nusing namespace std;\nusing namespace boost;\nusing namespace leda;\n\n// Define the boost edge weight property\ntypedef property<edge_weight_t, double> EdgeWeightProperty;\n\n// Define the boost directed graph: std::vector, std::vector, directed, no vertex property, double edge property, no graph property, std::list\ntypedef adjacency_list<vecS, vecS, directedS, no_property, EdgeWeightProperty, no_property, listS> DirectedGraph;\n\n// Define the vertex class as vertex_desciptor\ntypedef graph_traits<DirectedGraph>::vertex_descriptor Vertex;\n\n// Define the edge class as edge_desciptor\ntypedef graph_traits<DirectedGraph>::edge_descriptor Edge;\n\n// Define the edge iterator as edge_iterator\ntypedef graph_traits<DirectedGraph>::edge_iterator EdgeIterator;\n\n// Define the out edge iterator as edge_iterator\ntypedef graph_traits<DirectedGraph>::out_edge_iterator OutEdgeIterator;\n\n// Define the edge iterator as edge_iterator\ntypedef graph_traits<DirectedGraph>::vertex_iterator VertexIterator;\n\n// Define the edge weight map as a property map\ntypedef property_map<DirectedGraph, edge_weight_t>::type EdgeWeightMap;\n\n/**\n * Calculates the heuristic value for the @param selectedVertex and @param targetVertex\n * @param Vertex The selected vertex\n * @param Vertex The target vertex\n * @return The heuristic value\n */\ninline double HeuristicFunction(Vertex selectedVertex, Vertex targetVertex) \n{\n\t// If the vertexes are the same...\n\tif(targetVertex == selectedVertex)\n\t\t// Return the heuristic\n\t\treturn 0;\n\n\t// Calculate the heuristic\n\tdouble heuristicValue = selectedVertex - targetVertex;\n\n\t// Return the heuristic\n\treturn abs(heuristicValue);\n}\n\n// The struct for the bool operation overloading\nstruct PairCompare\n{\n\t/**\n\t * Compares the pairs\n\t * @param right The rightt operand\n\t * @param left The left operand\n\t * @return Comparison boolean value\n\t */\n\tbool operator()(const pair<Vertex, double>& right, const pair<Vertex, double>& left)\n\t{\n\t\treturn right.second < left.second;\n\t}\n};\n\n/**\n * Executes the ALT algorithm, namely a A* algorithm implementation, using landmarks and the triangle inequality \n * @param DirectedGraph The boost directed Graph\n * @param Vertex The starting vertex\n * @param Vertex The target vertex\n * @return True if the target vertex is found, or false if the target vertex is not found\n */\nbool ALT(DirectedGraph& directedGraph, Vertex startingVertex, Vertex targetVertex)\n{\n\t// Initialize the property map that contain the edges's weights\n\tEdgeWeightMap boostEdgeWeightMap = get(edge_weight, directedGraph);\n\n\t// Declare a map for the the vertexes and the cost to visit them\n\tstd::map<Vertex, double> vertexVisitCostMap;\n\n\t// Declare a map for the the vertexes and the heuristic cost to visit them \n\tstd::map<Vertex, double> vertexHeuristicCostMap;\n\n\t// Declare the boost vertex iterators\n\tVertexIterator vertexIteratorBegin, vertexIteratorEnd;\n\n\t// For every vertex in the boost directed graph...\n\tfor(tie(vertexIteratorBegin, vertexIteratorEnd) = vertices(directedGraph); vertexIteratorBegin != vertexIteratorEnd; vertexIteratorBegin++)\n\t{\n\t\t// Set the vertex initial cost to DBL_MAX\n\t\tvertexVisitCostMap.insert(pair<Vertex, double>(*vertexIteratorBegin, DBL_MAX));\n\n\t\t// Set the vertex initial cost to DBL_MAX\n\t\tvertexHeuristicCostMap.insert(pair<Vertex, double>(*vertexIteratorBegin, DBL_MAX));\n\t}\n\t\n\t// Declare the boost out edge iterators\n\tOutEdgeIterator edgeIteratorBegin, edgeIteratorEnd;\n\n\t// Declare the vector for possible vertex successors\n\tstd::vector<Vertex> possibleVertexSuccesorVector;\n\n\t// Insert the starting vertex\n\tpossibleVertexSuccesorVector.push_back(startingVertex);\n\n\t// Set the starting vertex visit cost to 0\n\tvertexVisitCostMap[startingVertex] = 0;\n\n\t// Set the starting vertex heuristic cost\n\tvertexHeuristicCostMap[startingVertex] = HeuristicFunction(startingVertex, startingVertex);\n\n\t// While there is a vertex to search...\n\twhile (!possibleVertexSuccesorVector.empty()) \n\t{\n\t\t// Get an iterator that point to the vertex with the minimum heuristic value\n\t\tauto it = *min_element(vertexHeuristicCostMap.begin(), vertexHeuristicCostMap.end(), PairCompare());\n\t\t\n\t\t// Get the vertex from the iterator\n\t\tVertex currentVertex = it.first;\n\n\t\t// If the target node was reached...\n\t\tif (currentVertex == targetVertex) \n\t\t{\n\t\t\t// Return true\n\t\t\treturn true;\n\t\t}\n\n\t\t// Search the target vertex\n\t\tauto iterator = find(possibleVertexSuccesorVector.begin(), possibleVertexSuccesorVector.end(), currentVertex);\n\n\t\t// If the element doesn't exist...\n\t\tif(iterator == possibleVertexSuccesorVector.end())\n\t\t\t// Clear the vector\n\t\t\tpossibleVertexSuccesorVector.clear();\n\t\telse\n\t\t\t// Remove the current vertex\n\t\t\tpossibleVertexSuccesorVector.erase(iterator, possibleVertexSuccesorVector.end());\n\t\t\n\t\t// For every out edge of the current vertex... \n\t\tfor(tie(edgeIteratorBegin, edgeIteratorEnd) = out_edges(currentVertex, directedGraph); edgeIteratorBegin != edgeIteratorEnd; edgeIteratorBegin++)\n\t\t{\n\t\t\t// Get the current edge's target node\n\t\t\tVertex currentEdgeTargetVertex = target(*edgeIteratorBegin, directedGraph);\n\n\t\t\t// Get the current edge's weight\n\t\t\tdouble currentEdgeWeight = boostEdgeWeightMap[*edgeIteratorBegin];\n\n\t\t\t// Calculate the target vertex visit cost\n\t\t\tdouble targetVertexVisitCost = vertexVisitCostMap[currentVertex] + currentEdgeWeight;\n\n\t\t\t// If the the path to this node is better than the previous one...\n\t\t\tif(targetVertexVisitCost < vertexVisitCostMap[currentEdgeTargetVertex])\n\t\t\t{\n\t\t\t\t// Set the visit cost to the edge's target\n\t\t\t\tvertexVisitCostMap[currentEdgeTargetVertex] = targetVertexVisitCost;\n\n\t\t\t\t// Set the heuristic cost to the edge's target\n\t\t\t\tvertexHeuristicCostMap[currentEdgeTargetVertex] = targetVertexVisitCost + HeuristicFunction(startingVertex, currentEdgeTargetVertex);\n\n\t\t\t\t// Search the target vertex\n\t\t\t\tauto iterator = find(possibleVertexSuccesorVector.begin(), possibleVertexSuccesorVector.end(), currentEdgeTargetVertex);\n\n\t\t\t\t// If the edge's target doesn't exist in the vector...\n\t\t\t\tif(iterator == possibleVertexSuccesorVector.end())\n\t\t\t\t{\n\t\t\t\t\t// Add it\n\t\t\t\t\tpossibleVertexSuccesorVector.push_back(currentEdgeTargetVertex);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Return false\n\treturn false;\n}\n\n/**\n * Copies @param LedaGraph to @param BoostDirectedGraph, using the @param LedaEdgeWeightMap\n * @param BoostDirectedGraph The boost directed graph\n * @param LedaGraph The leda directed graph\n * @param LedaEdgeWeightMap The edge array that contain the leda directed graph edges weights\n*/\nvoid CopyLedaGraphToBoostGraph(DirectedGraph& BoostDirectedGraph, leda::graph& LedaGraph, edge_array<double>& LedaEdgeWeightMap)\n{\n\t// Create a new boost directed graph containing the smae number of nodes as the leda directed graph\n\tDirectedGraph boostGraph(LedaGraph.number_of_nodes());\n\n\t// Leda edge that will be used for iteration\n\tleda::edge iterationEdge;\n\n\t// For all edges in the leda directed graph\n\tforall_edges(iterationEdge, LedaGraph)\n\t{\n\t\t// Get the source node of the edge\n\t\tnode source = LedaGraph.source(iterationEdge);\n\n\t\t// Get the target node of the edge\n\t\tnode target = LedaGraph.target(iterationEdge);\n\n\t\t// Get the weight of the edge\n\t\tdouble currentEdgeWeight = LedaEdgeWeightMap[iterationEdge];\n\n\t\t// Add the edge in the boost directed graph\n\t\tadd_edge(LedaGraph.index(source), LedaGraph.index(target), currentEdgeWeight, boostGraph);\n\t}\n\n\t// Update the boost directed graph\n\tBoostDirectedGraph = boostGraph;\n}\n\n// Main function\nint main()\n{\n\t#pragma region Initialization\n\n\t// Create an empty boost directed graph\n\tDirectedGraph boostDirectedGraph;\n\n\t// Create an empty leda directed graph\n\tleda::graph ledaDirectedGraph;\n\n\t//Create an empty edge array\n\tedge_array<double> ledaEdgeWeightArray;\n\t\n\t// User graph option\n\tstd::string graphOption;\n\n\t// Number of nodes\n\tint numberOfNodes;\n\n\tcout << \"Choose the testing graph between grid, complete or random.\" << endl; \n\n\t// Read the graph type\n\tcin >> graphOption;\n\n\tcout << \"Enter the number of nodes.\" << endl;\n\n\t// Read the number of nodes\n\tcin >> numberOfNodes;\n\n\t// If the grid graph is selected...\n\tif(graphOption == \"grid\")\n\t{\n\t\t// Create a grid graph\n\t\tgrid_graph(ledaDirectedGraph, numberOfNodes);\n\t}\n\telse\n\t{\n\t\t// If the random graph is selected...\n\t\tif(graphOption == \"random\")\n\t\t{\n\t\t\t// Calculate the number of edges\n\t\t\tint numberOfEdges = ceil(numberOfNodes * (numberOfNodes - 1));\n\n\t\t\t// Generate a random directed graph\n\t\t\trandom_graph(ledaDirectedGraph, numberOfNodes, numberOfEdges, false, true, true);\n\n\t\t\t// Make the graph cohesive\n\t\t\tMake_Connected(ledaDirectedGraph);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// If the complete graph is selected...\n\t\t\tif(graphOption == \"complete\")\n\t\t\t{\n\t\t\t\t// Create a complete graph\n\t\t\t\tcomplete_graph(ledaDirectedGraph, numberOfNodes);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tcout << \"Choose between grid, complete or random.\" << endl;\n\n\t\t\t\t// Exit if another option is selected\n\t\t\t\texit(0);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Intialise an edge array that will contain the leda graph edges weights\n\tedge_array<double> edgeWeightArray(ledaDirectedGraph);\n\n\t// Copy the edge array\n\tledaEdgeWeightArray = edgeWeightArray;\n\n\t// Initialise a random seed\n\tsrand(time(NULL));\n\n\t// Edge that will be used for the iteration\n\tleda::edge iterationEdge;\n\n\t// For every edge in the undirected graph...\n\tforall_edges(iterationEdge, ledaDirectedGraph)\n\t{\n\t\t// Assign random integer values as costs between 10 and 10000\n\t\tledaEdgeWeightArray[iterationEdge] = (rand() % 100) + 1;\n\t}\n\n\t// Get the grid graph number of nodes\n\tnumberOfNodes = ledaDirectedGraph.number_of_nodes();\n\n\t// Copy the leda directed graph to the boost directed graph\n\tCopyLedaGraphToBoostGraph(boostDirectedGraph, ledaDirectedGraph, ledaEdgeWeightArray);\n\n\t// Initialise a property map that contain the boost graph edges weights\n\tEdgeWeightMap boostEdgeWeightMap = get(edge_weight, boostDirectedGraph);\n\n\t// Choose a random node from the Leda directed graph\n\tnode startingRandomLedaNode = ledaDirectedGraph.choose_node();\n\n\t// Choose a random node from the Leda directed graph\n\tnode targetRandomLedaNode = ledaDirectedGraph.choose_node();\n\n\t// Get the index of the Boost directed graph vertex that correspond to the appropriate Leda random chosen node\n\tVertex startingRandomBoostVertex = vertex(ledaDirectedGraph.index(startingRandomLedaNode), boostDirectedGraph);\n\n\t// Get the index of the Boost directed graph vertex that correspond to the appropriate Leda random chosen node\n\tVertex targetRandomBoostVertex = vertex(ledaDirectedGraph.index(targetRandomLedaNode), boostDirectedGraph);\n\t\n\t// Initialise a node array the will contain the last edge on a shortest path from the starting node to a node\n\tnode_array<leda::edge> ledaPredecessorNodeArray(ledaDirectedGraph);\n\n\t// Initialise a node array the will contain the shortest path langth from the starting node to a node\n\tnode_array<double> ledaDistanceNodeArray(ledaDirectedGraph);\n\t\n\t#pragma endregion Initialization\n\n\t#pragma region Simulation\n\n\t// Initialise the starting CPU time\n\tfloat CPUTime = used_time();\n\n\t// Execute user defined ALT function\n\tALT(boostDirectedGraph, startingRandomBoostVertex, targetRandomBoostVertex);\n\n\t// Print the user defined ALT function execution time\n\tcout << \"User defined ALT function execution time: \" << used_time(CPUTime) << \" seconds.\"<< endl;\n\n\t// Execute leda defined shortest path function\n\tSHORTEST_PATH_T(ledaDirectedGraph, startingRandomLedaNode, ledaEdgeWeightArray, ledaDistanceNodeArray, ledaPredecessorNodeArray);\n\n\t// Execute leda defined compute shortest path function\n\tCOMPUTE_SHORTEST_PATH(ledaDirectedGraph, startingRandomLedaNode, targetRandomLedaNode, ledaPredecessorNodeArray);\n\n\t// Print the leda defined compute shortest path function execution time\n\tcout << \"Leda defined compute shortest path function execution time: \" << used_time(CPUTime) << \" seconds.\"<< endl;\n\n\t#pragma endregion Simulation\n\n\t// Return 0\n\treturn 0;\n}\n", "meta": {"hexsha": "5a66223d6ea0a11a1f91676f1873df873fe809c5", "size": 12062, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Project \u03a4\u03b5\u03c7\u03bd\u03bf\u03bb\u03bf\u03b3\u03af\u03b5\u03c2 \u03a5\u03bb\u03bf\u03c0\u03bf\u03af\u03b7\u03c3\u03b7\u03c2 \u0391\u03bb\u03b3\u03bf\u03c1\u03af\u03b8\u03bc\u03c9\u03bd/\u03a4\u03b5\u03bb\u03b9\u03ba\u03ae \u0386\u03c3\u03ba\u03b7\u03c3\u03b7/TelikiErgasia.cpp", "max_stars_repo_name": "DimosthenisMich/UndergraduateCeidProjects", "max_stars_repo_head_hexsha": "9f99f2c44e41d06020f3a5e9aacc0cd4357ee833", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2021-02-10T18:31:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T17:49:30.000Z", "max_issues_repo_path": "Project \u03a4\u03b5\u03c7\u03bd\u03bf\u03bb\u03bf\u03b3\u03af\u03b5\u03c2 \u03a5\u03bb\u03bf\u03c0\u03bf\u03af\u03b7\u03c3\u03b7\u03c2 \u0391\u03bb\u03b3\u03bf\u03c1\u03af\u03b8\u03bc\u03c9\u03bd/\u03a4\u03b5\u03bb\u03b9\u03ba\u03ae \u0386\u03c3\u03ba\u03b7\u03c3\u03b7/TelikiErgasia.cpp", "max_issues_repo_name": "DimosthenisMich/UndergraduateCeidProjects", "max_issues_repo_head_hexsha": "9f99f2c44e41d06020f3a5e9aacc0cd4357ee833", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-09-30T19:16:39.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-30T19:16:39.000Z", "max_forks_repo_path": "Project \u03a4\u03b5\u03c7\u03bd\u03bf\u03bb\u03bf\u03b3\u03af\u03b5\u03c2 \u03a5\u03bb\u03bf\u03c0\u03bf\u03af\u03b7\u03c3\u03b7\u03c2 \u0391\u03bb\u03b3\u03bf\u03c1\u03af\u03b8\u03bc\u03c9\u03bd/\u03a4\u03b5\u03bb\u03b9\u03ba\u03ae \u0386\u03c3\u03ba\u03b7\u03c3\u03b7/TelikiErgasia.cpp", "max_forks_repo_name": "DimitrisKostorrizos/UndergraduateCeidProjects", "max_forks_repo_head_hexsha": "9f99f2c44e41d06020f3a5e9aacc0cd4357ee833", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2021-11-24T21:34:15.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-23T22:37:35.000Z", "avg_line_length": 33.5988857939, "max_line_length": 147, "alphanum_fraction": 0.7660421157, "num_tokens": 2874, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195152660688, "lm_q2_score": 0.6548947155710234, "lm_q1q2_score": 0.4807709911453097}}
{"text": "#include \"SSDR.h\"\n#include <limits>\n#include <algorithm>\n#include <Eigen/Core>\n#include <Eigen/Eigen>\n#include \"QuadProg.h\"\n#include <tbb/blocked_range.h>\n#include <tbb/parallel_for.h>\n\nusing namespace Eigen;\n\nnamespace SSDR {\n\n    double ComputeApproximationErrorSq(const Output& output, const Input& input, const Parameter& param)\n    {\n        std::vector<double> errsq(input.numExamples);\n        double rsqsum = 0;\n        for (int s = 0; s < input.numExamples; ++s)\n        {\n            const int numVertices = input.numVertices;\n            const int numIndices = param.numMaxInfluences;\n            const int numBones = output.numBones;\n            const int numExamples = input.numExamples;\n\n            for (int s = 0; s < numExamples; ++s)\n            {\n                for (int v = 0; v < numVertices; ++v)\n                {\n                    MVector residual = input.sample[s * numVertices + v];\n                    const MPoint& p = input.bindModel[v];\n                    for (int i = 0; i < numIndices; ++i)\n                    {\n                        const int b = output.index[v * numIndices + i];\n                        const double w = output.weight[v * numIndices + i];\n                        const MTransformationMatrix& rt = output.boneTrans[s * numBones + b];\n                        residual -= w * MVector(p * rt.asMatrix());\n                    }\n                    rsqsum += residual * residual;\n                }\n            }\n        }\n        return rsqsum;\n    }\n\n    class WeightMapUpdator\n    {\n    private:\n        Output* output;\n        const Input* input;\n        const Parameter* param;\n        const MatrixXd* cem;\n        const MatrixXd* cim;\n        const VectorXd* cev;\n        const VectorXd* civ;\n        const MatrixXd* scem;\n        const MatrixXd* scim;\n        const VectorXd* sciv;\n    public:\n        WeightMapUpdator(Output* output_, const Input* input_, const Parameter* param_,\n            const MatrixXd* cem_, const MatrixXd* cim_, const VectorXd* cev_, const VectorXd* civ_,\n            const MatrixXd* scem_, const MatrixXd* scim_, const VectorXd* sciv_)\n            : output(output_), input(input_), param(param_),\n            cem(cem_), cim(cim_), cev(cev_), civ(civ_),\n            scem(scem_), scim(scim_), sciv(sciv_)\n        {\n        }\n        void operator ()(const tbb::blocked_range<int>& range) const\n        {\n            const int numVertices = input->numVertices;\n            const int numExamples = input->numExamples;\n            const int numIndices = param->numMaxInfluences;\n            const int numBones = output->numBones;\n\n            MatrixXd gm = MatrixXd::Zero(numBones, numBones), sgm = MatrixXd::Zero(numIndices, numIndices);\n            VectorXd gv = VectorXd::Zero(numBones), sgv = VectorXd::Zero(numIndices);\n\n            VectorXd weight = VectorXd::Zero(numBones), w0, sweight = VectorXd::Zero(numIndices);\n            MatrixXd basis = MatrixXd::Zero(numBones, numExamples * 3), sbasis = MatrixXd::Zero(numIndices, numExamples * 3);\n            VectorXd targetVertex = VectorXd::Zero(numExamples * 3);\n\n            for (int v = range.begin(); v != range.end(); ++v)\n            {\n                const MPoint& restVertex = input->bindModel[v];\n                for (int s = 0; s < numExamples; ++s)\n                {\n                    for (int b = 0; b < numBones; ++b)\n                    {\n                        const MTransformationMatrix& rt = output->boneTrans[s * numBones + b];\n                        MPoint tv = restVertex * rt.asMatrix();\n                        basis(b, s * 3 + 0) = tv.x;\n                        basis(b, s * 3 + 1) = tv.y;\n                        basis(b, s * 3 + 2) = tv.z;\n                    }\n                }\n                for (int s = 0; s < numExamples; ++s)\n                {\n                    targetVertex[s * 3 + 0] = input->sample[s * numVertices + v].x;\n                    targetVertex[s * 3 + 1] = input->sample[s * numVertices + v].y;\n                    targetVertex[s * 3 + 2] = input->sample[s * numVertices + v].z;\n                }\n                gm = basis * basis.transpose();\n                gv = -basis * targetVertex;\n\n                double qperr = SolveQP(gm, gv, *cem, *cev, *cim, *civ, weight);\n                assert(qperr != std::numeric_limits<double>::infinity());\n\n                double weightSum = 0;\n                for (int i = 0; i < numIndices; ++i)\n                {\n                    double maxw = -std::numeric_limits<double>::max();\n                    int bestbone = -1;\n                    for (int b = 0; b < numBones; ++b)\n                    {\n                        if (weight[b] > maxw)\n                        {\n                            maxw = weight[b];\n                            bestbone = b;\n                        }\n                    }\n                    if (maxw <= 0)\n                    {\n                        break;\n                    }\n\n                    output->index[v * numIndices + i] = bestbone;\n                    output->weight[v * numIndices + i] = maxw;\n                    weightSum += maxw;\n                    weight[bestbone] = 0;\n                }\n                if (weightSum < 1.0f)\n                {\n                    for (int j = 0; j < numExamples * 3; ++j)\n                    {\n                        for (int i = 0; i < numIndices; ++i)\n                        {\n                            sbasis(i, j) = basis(output->index[v * numIndices + i], j);\n                        }\n                    }\n                    sgm = sbasis * sbasis.transpose();\n                    sgv = -sbasis * targetVertex;\n                    qperr = SolveQP(sgm, sgv, *scem, *cev, *scim, *sciv, sweight);\n                    if (qperr != std::numeric_limits<double>::infinity())\n                    {\n                        weightSum = 0;\n                        for (int i = 0; i < numIndices; ++i)\n                        {\n                            weightSum += sweight[i];\n                            output->weight[v * numIndices + i] = sweight[i];\n                        }\n                    }\n                }\n                for (int i = 0; i < numIndices; ++i)\n                {\n                    output->weight[v * numIndices + i] /= weightSum;\n                }\n            }\n        }\n    };\n    void UpdateWeightMap(Output& output, const Input& input, const Parameter& param)\n    {\n        const int numBones = output.numBones;\n        const int numIndices = param.numMaxInfluences;\n\n        MatrixXd cem = MatrixXd::Zero(1, numBones);\n        MatrixXd scem = MatrixXd::Zero(1, numIndices);\n        VectorXd cev = VectorXd::Zero(1);\n        MatrixXd cim = MatrixXd::Zero(numBones, numBones);\n        MatrixXd scim = MatrixXd::Zero(numIndices, numIndices);\n        VectorXd civ = VectorXd::Zero(numBones);\n        VectorXd sciv = VectorXd::Zero(numIndices);\n        for (int b = 0; b < numBones; ++b)\n        {\n            cem(0, b) = -1.0;\n            cim(b, b) = 1.0;\n            civ(b) = 0;\n        }\n        for (int i = 0; i < numIndices; ++i)\n        {\n            scem(0, i) = -1.0;\n            scim(i, i) = 1.0;\n            sciv(i) = 0;\n        }\n        cev(0) = 1.0;\n\n        tbb::parallel_for(tbb::blocked_range<int>(0, input.numVertices),\n            WeightMapUpdator(&output, &input, &param,\n            &cem, &cim, &cev, &civ, &scem,\n            &scim, &sciv));\n    }\n\n    MTransformationMatrix CalcPointsAlignment(size_t numPoints, std::vector<MPoint>::const_iterator ps, std::vector<MPoint>::const_iterator pd)\n    {\n        MTransformationMatrix transform;\n\n        MPoint cs = MVector::zero, cd = MVector::zero;\n        std::vector<MPoint>::const_iterator sit = ps;\n        std::vector<MPoint>::const_iterator dit = pd;\n        for (size_t i = 0; i < numPoints; ++i, ++sit, ++dit)\n        {\n            cs += *sit;\n            cd += *dit;\n        }\n        cs = cs / numPoints;\n        cd = cd / numPoints;\n\n        if (numPoints < 3)\n        {\n            transform.setTranslation(cd - cs, MSpace::kTransform);\n            return transform;\n        }\n\n        Matrix<double, 4, 4> moment;\n        double sxx = 0, sxy = 0, sxz = 0, syx = 0, syy = 0, syz = 0, szx = 0, szy = 0, szz = 0;\n        sit = ps;\n        dit = pd;\n        for (size_t i = 0; i < numPoints; ++i, ++sit, ++dit)\n        {\n            sxx += (sit->x - cs.x) * (dit->x - cd.x);\n            sxy += (sit->x - cs.x) * (dit->y - cd.y);\n            sxz += (sit->x - cs.x) * (dit->z - cd.z);\n            syx += (sit->y - cs.y) * (dit->x - cd.x);\n            syy += (sit->y - cs.y) * (dit->y - cd.y);\n            syz += (sit->y - cs.y) * (dit->z - cd.z);\n            szx += (sit->z - cs.z) * (dit->x - cd.x);\n            szy += (sit->z - cs.z) * (dit->y - cd.y);\n            szz += (sit->z - cs.z) * (dit->z - cd.z);\n        }\n        moment(0, 0) = sxx + syy + szz;\n        moment(0, 1) = syz - szy;        moment(1, 0) = moment(0, 1);\n        moment(0, 2) = szx - sxz;        moment(2, 0) = moment(0, 2);\n        moment(0, 3) = sxy - syx;        moment(3, 0) = moment(0, 3);\n        moment(1, 1) = sxx - syy - szz;\n        moment(1, 2) = sxy + syx;        moment(2, 1) = moment(1, 2);\n        moment(1, 3) = szx + sxz;        moment(3, 1) = moment(1, 3);\n        moment(2, 2) = -sxx + syy - szz;\n        moment(2, 3) = syz + szy;        moment(3, 2) = moment(2, 3);\n        moment(3, 3) = -sxx - syy + szz;\n\n        if (moment.norm() > 0)\n        {\n            EigenSolver<Matrix<double, 4, 4>> es(moment);\n            int maxi = 0;\n            for (int i = 1; i < 4; ++i)\n            {\n                if (es.eigenvalues()(maxi).real() < es.eigenvalues()(i).real())\n                {\n                    maxi = i;\n                }\n            }\n            transform.setRotationQuaternion(\n                es.eigenvectors()(1, maxi).real(),\n                es.eigenvectors()(2, maxi).real(),\n                es.eigenvectors()(3, maxi).real(),\n                es.eigenvectors()(0, maxi).real());\n        }\n\n        MPoint cs0 = cs * transform.asMatrix();\n        transform.setTranslation(cd - cs0, MSpace::kTransform);\n        return transform;\n    }\n\n    void ComputeExamplePoints(std::vector<MPoint>& example, int sid, int bone, const Output& output, const Input& input, const Parameter& param)\n    {\n        const int numVertices = input.numVertices;\n        const int numIndices = param.numMaxInfluences;\n        const int numBones = output.numBones;\n        for (int v = 0; v < numVertices; ++v)\n        {\n            example[v] = input.sample[sid * numVertices + v];\n            const MPoint& s = input.bindModel[v];\n            for (int i = 0; i < numIndices; ++i)\n            {\n                const int b = output.index[v * numIndices + i];\n                if (b != bone)\n                {\n                    const double w = output.weight[v * numIndices + i];\n                    const MTransformationMatrix& at = output.boneTrans[sid * numBones + b];\n                    example[v] -= w * (s * at.asMatrix());\n                }\n            }\n        }\n    }\n\n    void SubtractCentroid(std::vector<MPoint>& model, std::vector<MPoint>& example, MPoint& corModel, MPoint& corExample, const VectorXd& weight, const Output& output, const Input& input)\n    {\n        const int numVertices = input.numVertices;\n\n        double wsqsum = 0;\n        corModel = MVector::zero;\n        corExample = MVector::zero;\n        for (int v = 0; v < numVertices; ++v)\n        {\n            const double w = weight[v];\n            corModel += w * w * input.bindModel[v];\n            corExample += w * example[v];\n            wsqsum += w * w;\n        }\n        corModel = corModel / wsqsum;\n        corExample = corExample / wsqsum;\n        for (int v = 0; v < numVertices; ++v)\n        {\n            model[v] = weight[v] * (input.bindModel[v] - corModel);\n            example[v] -= weight[v] * corExample;\n        }\n    }\n\n    class BoneTransformUpdator\n    {\n    private:\n        Output* output;\n        const Input* input;\n        const Parameter* param;\n        const VectorXd* weight;\n        int bone;\n    public:\n        BoneTransformUpdator(Output* output_, const Input* input_, const Parameter* param_, const VectorXd* weight_)\n            : bone(0), output(output_), input(input_), param(param_), weight(weight_)\n        {\n        }\n        void ChangeBone(int b)\n        {\n            bone = b;\n        }\n        void operator ()(const tbb::blocked_range<int>& range) const\n        {\n            std::vector<MPoint> model(input->numVertices), example(input->numVertices);\n            for (int s = range.begin(); s != range.end(); ++s)\n            {\n                ComputeExamplePoints(example, s, bone, *output, *input, *param);\n\n                MPoint corModel(0, 0, 0), corExample(0, 0, 0);\n                SubtractCentroid(model, example, corModel, corExample, *weight, *output, *input);\n\n                MTransformationMatrix transform = CalcPointsAlignment(model.size(), model.begin(), example.begin());\n                MVector d = corExample - corModel * transform.asMatrix();\n                transform.setTranslation(d + transform.getTranslation(MSpace::kTransform), MSpace::kTransform);\n                output->boneTrans[s * output->numBones + bone] = transform;\n            }\n        }\n    };\n    void UpdateBoneTransform(Output& output, const Input& input, const Parameter& param)\n    {\n        const int numVertices = input.numVertices;\n        const int numExamples = input.numExamples;\n        const int numIndices = param.numMaxInfluences;\n        const int numBones = output.numBones;\n\n        VectorXd boneWeight = VectorXd::Zero(numVertices);\n        BoneTransformUpdator transformUpdator(&output, &input, &param, &boneWeight);\n        tbb::blocked_range<int> blockedRange(0, numExamples);\n        for (int bone = 0; bone < numBones; ++bone)\n        {\n            for (int v = 0; v < numVertices; ++v)\n            {\n                boneWeight[v] = 0;\n                for (int i = 0; i < numIndices; ++i)\n                {\n                    if (output.index[v * numIndices + i] == bone)\n                    {\n                        boneWeight[v] = output.weight[v * numIndices + i];\n                        break;\n                    }\n                }\n            }\n            transformUpdator.ChangeBone(bone);\n            tbb::parallel_for(blockedRange, transformUpdator);\n        }\n    }\n\n    void UpdateBoneTransform(std::vector<MTransformationMatrix>& boneTrans, int numBones, const Output& output, const Input& input, const Parameter& param)\n    {\n        const int numVertices = input.numVertices;\n        const int numExamples = input.numExamples;\n        const int numIndices = param.numMaxInfluences;\n\n        std::vector<int> numBoneVertices(numBones, 0);\n        for (int v = 0; v < numVertices; ++v)\n        {\n            ++numBoneVertices[output.index[v * numIndices + 0]];\n        }\n        std::vector<int> boneVertexId(numBones, 0);\n        for (int i = 1; i < numBones; ++i)\n        {\n            boneVertexId[i] = boneVertexId[i - 1] + numBoneVertices[i - 1];\n        }\n        std::vector<MPoint> skin(numVertices, MPoint(0, 0, 0));\n        std::vector<MPoint> anim(numVertices * numExamples, MPoint(0, 0, 0));\n        for (int v = 0; v < numVertices; ++v)\n        {\n            const int bs = output.index[v * numIndices + 0];\n            const int bd = boneVertexId[bs];\n            skin[bd] = input.bindModel[v];\n            for (int s = 0; s < numExamples; ++s)\n            {\n                anim[s * numVertices + bd] = input.sample[s * numVertices + v];\n            }\n            ++boneVertexId[bs];\n        }\n        boneVertexId[0] = 0;\n        for (int i = 1; i < numBones; ++i)\n        {\n            boneVertexId[i] = boneVertexId[i - 1] + numBoneVertices[i - 1];\n        }\n        for (int b = 0; b < numBones; ++b)\n        {\n            for (int s = 0; s < numExamples; ++s)\n            {\n                boneTrans[s * numBones + b] = CalcPointsAlignment(numBoneVertices[b], skin.begin() + boneVertexId[b], anim.begin() + s * numVertices + boneVertexId[b]);\n            }\n        }\n    }\n\n    int BindVertexToBone(Output& output, std::vector<MTransformationMatrix>& boneTrans, const Input& input, const Parameter& param)\n    {\n        const int numVertices = input.numVertices;\n        const int numExamples = input.numExamples;\n        const int numIndices = param.numMaxInfluences;\n        int numBones = static_cast<int>(boneTrans.size() / numExamples);\n\n        std::vector<int> numBoneVertices(numBones, 0);\n        std::vector<double> vertexError(numVertices, 0);\n\n        for (int v = 0; v < numVertices; ++v)\n        {\n            int bestBone = 0;\n            double minErr = std::numeric_limits<double>::max();\n            const MPoint& bindModelPos = input.bindModel[v];\n            for (int b = 0; b < numBones; ++b)\n            {\n                double errsq = 0;\n                for (int s = 0; s < numExamples; ++s)\n                {\n                    MMatrix am = boneTrans[s * numBones + b].asMatrix();\n                    MVector diff = input.sample[s * numVertices + v] - bindModelPos * am;\n                    errsq += diff * diff;\n                }\n                if (errsq < minErr)\n                {\n                    bestBone = b;\n                    minErr = errsq;\n                }\n            }\n            ++numBoneVertices[bestBone];\n            output.index[v * numIndices + 0] = bestBone;\n            vertexError[v] = minErr;\n        }\n\n        std::vector<int>::iterator smallestBoneSize = std::min_element(numBoneVertices.begin(), numBoneVertices.end());\n        while (*smallestBoneSize <= 0)\n        {\n            const int smallestBone = static_cast<int>(smallestBoneSize - numBoneVertices.begin());\n            numBoneVertices.erase(numBoneVertices.begin() + smallestBone);\n            for (int s = input.numExamples - 1; s >= 0; --s)\n            {\n                boneTrans.erase(boneTrans.begin() + s * numBones + smallestBone);\n            }\n            for (int v = 0; v < numVertices; ++v)\n            {\n                int b = output.index[v * numIndices + 0];\n                if (b >= smallestBone)\n                {\n                    --output.index[v * numIndices + 0];\n                }\n            }\n            --numBones;\n            smallestBoneSize = std::min_element(numBoneVertices.begin(), numBoneVertices.end());\n        }\n        return static_cast<int>(numBoneVertices.size());\n    }\n\n    int ClusterInitialBones(Output& output, const Input& input, const Parameter& param)\n    {\n        const int numVertices = input.numVertices;\n        const int numExamples = input.numExamples;\n        const int numIndices = param.numMaxInfluences;\n\n        std::fill(output.index.begin(), output.index.end(), 0);\n        std::fill(output.weight.begin(), output.weight.end(), 0.0);\n        for (int v = 0; v < numVertices; ++v)\n        {\n            output.weight[v * numIndices + 0] = 1.0;\n        }\n\n        int numClusters = 1;\n        std::vector<MTransformationMatrix> boneTrans(numExamples);\n        UpdateBoneTransform(boneTrans, numClusters, output, input, param);\n\n        while (numClusters < param.numMinBones)\n        {\n            std::vector<MPoint> clusterCenter(numClusters, MPoint(0, 0, 0));\n            std::vector<int> numBoneVertices(numClusters, 0);\n            for (int v = 0; v < numVertices; ++v)\n            {\n                const int c = output.index[v * numIndices + 0];\n                clusterCenter[c] += input.bindModel[v];\n                ++numBoneVertices[c];\n            }\n            for (int c = 0; c < numClusters; ++c)\n            {\n                clusterCenter[c] = clusterCenter[c] / numBoneVertices[c];\n            }\n\n            std::vector<double> maxClusterError(numClusters, -std::numeric_limits<double>::max());\n            std::vector<int> mostDistantVertex(numClusters, -1);\n            for (int v = 0; v < numVertices; ++v)\n            {\n                const int c = output.index[v * numIndices + 0];\n                double sumApproxErrorSq = 0;\n                for (int s = 0; s < numExamples; ++s)\n                {\n                    MMatrix bm = boneTrans[s * numClusters + c].asMatrix();\n                    MVector diff = input.sample[s * numVertices + v] - input.bindModel[v] * bm;\n                    sumApproxErrorSq += diff * diff;\n                }\n                MVector d = input.bindModel[v] - clusterCenter[c];\n                double errSq = sumApproxErrorSq * (d * d);\n                if (errSq > maxClusterError[c])\n                {\n                    maxClusterError[c] = errSq;\n                    mostDistantVertex[c] = v;\n                }\n            }\n            int numPrevClusters = numClusters;\n            for (int c = 0; c < numPrevClusters; ++c)\n            {\n                output.index[mostDistantVertex[c] * numIndices + 0] = numClusters++;\n                --numBoneVertices[c];\n                numBoneVertices.push_back(1);\n            }\n            boneTrans.resize(numExamples * numClusters);\n\n            UpdateBoneTransform(boneTrans, numClusters, output, input, param);\n            numClusters = BindVertexToBone(output, boneTrans, input, param);\n        }\n        return numClusters;\n    }\n\n#pragma region Decompose\n    double Decompose(Output& output, const Input& input, const Parameter& param)\n    {\n        const int numVertices = input.numVertices;\n        const int numExamples = input.numExamples;\n        const int numIndices = param.numMaxInfluences;\n\n        output.index.assign(numVertices * numIndices, 0);\n        output.weight.assign(numVertices * numIndices, 0.0f);\n\n        output.numBones = ClusterInitialBones(output, input, param);\n        output.boneTrans.assign(numExamples * output.numBones, MTransformationMatrix::identity);\n        UpdateBoneTransform(output.boneTrans, output.numBones, output, input, param);\n\n        for (int loop = 0; loop < param.numMaxIterations; ++loop)\n        {             \n            UpdateWeightMap(output, input, param);\n            UpdateBoneTransform(output, input, param);\n        }\n        return ComputeApproximationErrorSq(output, input, param);\n    }\n#pragma endregion\n\n} //namespace SSDR\n", "meta": {"hexsha": "1aab8637fe65c76b2898121c8beefa2b3c116070", "size": 22281, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cpp/SSDR.cpp", "max_stars_repo_name": "mukailab/ssdr4maya", "max_stars_repo_head_hexsha": "49a4be4723baf906b2c7975fdce5ba524c3ff779", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 39.0, "max_stars_repo_stars_event_min_datetime": "2016-07-06T16:22:54.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-24T23:50:06.000Z", "max_issues_repo_path": "src/cpp/SSDR.cpp", "max_issues_repo_name": "maajor/ssdr4maya", "max_issues_repo_head_hexsha": "d1ea90dca6989f132b163be4bca253da2bda4f4b", "max_issues_repo_licenses": ["MIT"], "max_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/SSDR.cpp", "max_forks_repo_name": "maajor/ssdr4maya", "max_forks_repo_head_hexsha": "d1ea90dca6989f132b163be4bca253da2bda4f4b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2016-10-04T20:28:16.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-04T09:58:28.000Z", "avg_line_length": 39.6459074733, "max_line_length": 187, "alphanum_fraction": 0.4981823078, "num_tokens": 5595, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357735451834, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.48074572849492153}}
{"text": "/*!============================================================\n  |                                                           |\n  |         micromorphic_linear_elasticity_voigt.cpp          |\n  |                                                           |\n  -------------------------------------------------------------\n  | The source file for the definition of a                   |\n  | micromorphic linear elasticity using voigt notation.      |\n  -------------------------------------------------------------\n  | Notes: Micromorphic constitutive models should be         |\n  |        developed in the namespace micro_material          |\n  |        and have the function get_stress. This             |\n  |        function should read in the right Cauchy           |\n  |        green deformation tensor, Psi, Gamma, and          |\n  |        write the PK2 stress, the symmetric stress         |\n  |        in the reference configuration, and the            |\n  |        higher order couple stress in the reference        |\n  |        configuration. (ADDITIONAL VALUES WILL BE          |\n  |        ADDED OVER TIME).                                  |\n  =============================================================\n  | Dependencies:                                             |\n  | Eigen: Open source matrix library available at            |\n  |        eigen.tuxfamily.org.                               |\n  =============================================================*/\n\n#include <iostream>  \n#include <vector>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <deformation_measures.h>\n#include <micromorphic_linear_elasticity_voigt.h>\n\nnamespace micro_material{\n\n    void LinearElasticity::evaluate_model(const std::vector<double> &time,        const std::vector<double> (&fparams),\n                                          const double (&grad_u)[3][3],           const double (&phi)[9],\n                                          const double (&grad_phi)[9][3],         std::vector<double> &SDVS,\n                                          const std::vector<double> &ADD_DOF,     const std::vector<std::vector<double>> &ADD_grad_DOF,\n                                          Vector_9 &PK2, Vector_9 &SIGMA, Vector_27 &M, std::vector<Eigen::VectorXd> &ADD_TERMS){\n        /*!\n        =======================\n        |    evaluate_model   |\n        =======================\n        \n        Evaluate the constitutive model \n        from the general incoming values.\n        \n        Only returns stresses and additional \n        terms.\n        \n        */\n        \n        //Extract the time\n        double t  = time[0];\n        double dt = time[1];\n\n        //Extract the parameters        \n        double params[18];\n        if(fparams.size() == 18){\n            for(int i=0; i<18; i++){\n                params[i] = fparams[i];\n            }\n        }\n        else{std::cout << \"Error: Material parameters incorrectly specified\\n\";}\n        \n        //Compute the required deformation measures\n        Matrix_3x3 F;\n        Matrix_3x3 chi;\n        Matrix_3x9 grad_chi;\n        get_deformation_measures(grad_u, phi, grad_phi, F, chi, grad_chi, false);\n        \n        //Compute the stresses\n//        Vector_9  PK2;\n//        Vector_9  SIGMA;\n//        Vector_27 M;\n\n        get_stress(t, dt, params, F, chi, grad_chi, SDVS, PK2, SIGMA, M);\n//        deformation_measures::map_stresses_to_current_configuration(F, chi, PK2, SIGMA, M, cauchy, s, m);\n        \n        return;\n    }\n                                \n    void LinearElasticity::evaluate_model(const std::vector<double> &time,        const std::vector<double> (&fparams),\n                                          const double (&grad_u)[3][3],           const double (&phi)[9],\n                                          const double (&grad_phi)[9][3],         std::vector<double> &SDVS,\n                                          const std::vector<double> &ADD_DOF,     const std::vector<std::vector<double>> &ADD_grad_DOF,\n                                          Vector_9    &PK2,            Vector_9    &SIGMA,       Vector_27    &M,\n                                          Matrix_9x9  &DPK2Dgrad_u,    Matrix_9x9  &DPK2Dphi,    Matrix_9x27  &DPK2Dgrad_phi,\n                                          Matrix_9x9  &DSIGMADgrad_u,  Matrix_9x9  &DSIGMADphi,  Matrix_9x27  &DSIGMADgrad_phi,\n                                          Matrix_27x9 &DMDgrad_u,      Matrix_27x9 &DMDphi,      Matrix_27x27 &DMDgrad_phi,\n                                          std::vector<Eigen::VectorXd> &ADD_TERMS,               std::vector<Eigen::MatrixXd> &ADD_JACOBIANS){\n        /*!\n        ========================\n        |    evaluate_model    |\n        ========================\n        \n        Evaluate the constitutive model \n        from the general incoming values.\n        \n        Returns stresses, additional \n        terms, and their jacobians.\n        \n        */\n\n        //Extract the time\n        double t  = time[0];\n        double dt = time[1];\n\n        //Extract the parameters        \n        double params[18];\n        if(fparams.size() == 18){\n            for(int i=0; i<18; i++){\n                params[i] = fparams[i];\n            }\n        }\n        else{std::cout << \"Error: Material parameters incorrectly specified\\n\";assert(-21==-20);}\n\n        //Compute the required deformation measures\n        Matrix_3x3 F;\n        Matrix_3x3 chi;\n        Matrix_3x9 grad_chi;\n        get_deformation_measures(grad_u, phi, grad_phi, F, chi, grad_chi, false);\n\n//        std::cout << \"grad_u:\\n\";\n//        for (int i=0; i<3; i++){\n//            for (int j=0; j<3; j++){\n//                std::cout << grad_u[i][j] << \" \";\n//            }\n//            std::cout << \"\\n\";\n//        }\n//\n//        std::cout << \"F:\\n\" << F << \"\\n\";\n\n        //Compute the stresses and jacobians\n//        Vector_9     PK2;\n//        Vector_9     SIGMA;\n//        Vector_27    M;\n\n//        Matrix_9x9   dPK2dF;\n//        Matrix_9x9   dPK2dchi;\n//        Matrix_9x27  dPK2dgrad_chi;\n//        Matrix_9x9   dSIGMAdF;\n//        Matrix_9x9   dSIGMAdchi;\n//        Matrix_9x27  dSIGMAdgrad_chi;\n//        Matrix_27x9  dMdF;\n//        Matrix_27x9  dMdchi;\n//        Matrix_27x27 dMdgrad_chi;\n        \n        //assert(13==14);\n\n        //Note: d(x)dchi = D(x)Dphi\n        get_stress(t, dt, params, F, chi, grad_chi, SDVS, PK2, SIGMA, M,\n                   DPK2Dgrad_u,   DPK2Dphi,   DPK2Dgrad_phi,\n                   DSIGMADgrad_u, DSIGMADphi, DSIGMADgrad_phi,\n                   DMDgrad_u,     DMDphi,     DMDgrad_phi);\n                   \n        //assert(14==15);\n//        deformation_measures::map_stresses_to_current_configuration(F, chi, PK2, SIGMA, M, cauchy, s, m);\n//\n//        Matrix_9x9   dcauchydF;\n//        Matrix_9x27  dcauchydgrad_chi;\n//        Matrix_9x9   dsdF;\n//        Matrix_9x27  dsdgrad_chi;\n//        Matrix_27x9  dmdF;\n//        Matrix_27x27 dmdgrad_chi;\n//\n//        deformation_measures::map_jacobians_to_current_configuration(F, chi, PK2, SIGMA, M, cauchy, s, m,\n//                                                                     dPK2dF,    dPK2dchi,    dPK2dgrad_chi, \n//                                                                     dSIGMAdF,  dSIGMAdchi,  dSIGMAdgrad_chi, \n//                                                                     dMdF,      dMdchi,      dMdgrad_chi,\n//                                                                     dcauchydF, DcauchyDphi, dcauchydgrad_chi,\n//                                                                     dsdF,      DsDphi,      dsdgrad_chi,\n//                                                                     dmdF,      DmDphi,      dmdgrad_chi);\n\n\n        //assert(16==17);                                                                    \n//        Matrix_3x9 _grad_phi;\n//        Vector_27  _grad_phi_v;\n//        Matrix_3x3 eye = Matrix_3x3::Identity();\n//        deformation_measures::assemble_grad_chi(grad_phi, eye, _grad_phi); //Put grad_phi into an Eigen Matrix\n//        deformation_measures::voigt_3x9_tensor(_grad_phi,_grad_phi_v);     //Put grad_phi into voigt notation\n//        deformation_measures::compute_total_derivatives(F, _grad_phi_v,\n//                                                        dcauchydF,      dcauchydgrad_chi, dsdF,      dsdgrad_chi, dmdF,      dmdgrad_chi,\n//                                                        DcauchyDgrad_u, DcauchyDgrad_phi, DsDgrad_u, DsDgrad_phi, DmDgrad_u, DmDgrad_phi);\n        //assert(17==18);\n        return;\n    }\n    \n    void LinearElasticity::get_deformation_measures(const double (&grad_u)[3][3], const double (&phi)[9], const double (&grad_phi)[9][3],\n                                                    Matrix_3x3 &F,                Matrix_3x3 &chi,        Matrix_3x9 &grad_chi, bool iscurrent){\n        /*!\n        ==================================\n        |    get_deformation_measures    |\n        ==================================\n        \n        Compute the deformation measures from the degrees of freedom and their \n        gradients.\n        \n        */\n        \n        deformation_measures::get_deformation_gradient(grad_u, F, iscurrent);\n\n        deformation_measures::assemble_chi(phi, chi);\n\n        if(iscurrent){\n            deformation_measures::assemble_grad_chi(grad_phi, F, grad_chi);\n        }\n        else{\n            deformation_measures::assemble_grad_chi(grad_phi, grad_chi);\n        }\n        \n        return;\n    }\n\n    void get_stress(const double &t,     const double &dt,      const double (&params)[18],\n                    const Matrix_3x3 &F, const Matrix_3x3 &chi, const Matrix_3x9 &grad_chi,\n                    std::vector<double> &SDVS,    Vector_9 &PK2, Vector_9 &SIGMA, Vector_27 &M){\n    \n        //Extract the parameters\n        double lambda  = params[ 0];\n        double mu      = params[ 1];\n        double eta     = params[ 2];\n        double tau     = params[ 3];\n        double kappa   = params[ 4];\n        double nu      = params[ 5];\n        double sigma   = params[ 6];\n        double tau1    = params[ 7];\n        double tau2    = params[ 8];\n        double tau3    = params[ 9];\n        double tau4    = params[10];\n        double tau5    = params[11];\n        double tau6    = params[12];\n        double tau7    = params[13];\n        double tau8    = params[14];\n        double tau9    = params[15];\n        double tau10   = params[16];\n        double tau11   = params[17];\n\n        //Initialize the stiffness matrices\n        //SpMat A( 9, 9);\n        //SpMat B( 9, 9);\n        //SpMat C(27,27);\n        //SpMat D( 9, 9);\n\n        Matrix_9x9   A;\n        Matrix_9x9   B;\n        Matrix_27x27 C;\n        Matrix_9x9   D;\n\n        //Populate the stiffness matrices\n        compute_A_voigt(lambda,mu,A);\n        compute_B_voigt(eta,kappa,nu,sigma,tau,B);\n        compute_C_voigt(tau1,tau2,tau3, tau4, tau5,tau6,\n                        tau7,tau8,tau9,tau10,tau11,C);\n        compute_D_voigt(sigma,tau,D);\n\n        //Compute the deformation measures\n        Matrix_3x3 RCG; //The right cauchy green deformation tensor\n        deformation_measures::get_right_cauchy_green(F,RCG);\n        Matrix_3x3 RCGinv = RCG.inverse(); //The inverse of the right cauchy green deformation tensor\n        Matrix_3x3 Psi; //The second order micromorphic deformation measure\n        deformation_measures::get_psi(F,chi,Psi);\n        Matrix_3x9 Gamma; //The higher order micromorphic deformation measure\n        deformation_measures::get_gamma(F,grad_chi,Gamma);\n\n        //Compute the strain measures\n        Matrix_3x3 E;\n        Matrix_3x3 E_micro;\n        deformation_measures::get_lagrange_strain(F,E);\n        deformation_measures::get_micro_strain(Psi,E_micro);\n        \n        //std::cout << \"F:\\n\" << F << \"\\n\";\n        //std::cout << \"chi:\\n\" << chi << \"\\n\";\n        //std::cout << \"grad chi:\\n\" << grad_chi << \"\\n\";\n        //std::cout << \"Psi:\\n\" << Psi << \"\\n\";\n        //std::cout << \"Gamma:\\n\" << Gamma << \"\\n\";\n        //std::cout << \"E:\\n\" << E << \"\\n\";\n        //std::cout << \"E_micro:\\n\" << E_micro << \"\\n\";\n\n        //Put the strain measures in voigt notation\n        Vector_9  E_voigt;\n        Vector_9  E_micro_voigt;\n        Vector_27 Gamma_voigt;\n\n        deformation_measures::voigt_3x3_tensor(E,       E_voigt);\n        deformation_measures::voigt_3x3_tensor(E_micro, E_micro_voigt);\n        deformation_measures::voigt_3x9_tensor(Gamma,   Gamma_voigt);\n\n        //Compute the stress measures\n        compute_PK2_stress(E_voigt, E_micro_voigt, Gamma_voigt, RCGinv, Psi, Gamma,\n                           A,       B,             C,           D,      PK2);\n                           \n        compute_symmetric_stress(E_voigt, E_micro_voigt, Gamma_voigt, RCGinv, Psi, Gamma,\n                           A,       B,             C,           D,      SIGMA);\n                           \n        compute_higher_order_stress(Gamma_voigt, C, M);\n\n        return;\n    }\n    \n    void get_stress(const double &t,     const double &dt,      const double (&params)[18],\n                    const Matrix_3x3 &F, const Matrix_3x3 &chi, const Matrix_3x9 &grad_chi,\n                    std::vector<double> &SDVS,    Vector_9 &PK2, Vector_9 &SIGMA, Vector_27 &M,\n                    Matrix_9x9  &dPK2dF,   Matrix_9x9  &dPK2dchi,   Matrix_9x27  &dPK2dgrad_chi,\n                    Matrix_9x9  &dSIGMAdF, Matrix_9x9  &dSIGMAdchi, Matrix_9x27  &dSIGMAdgrad_chi,\n                    Matrix_27x9 &dMdF,     Matrix_27x9 &dMdchi,     Matrix_27x27 &dMdgrad_chi){\n        /*!=================\n        |    get_stress    |\n        ====================\n        \n        Computes the stress measures and their jacobians.\n        \n        */\n        //Extract the parameters\n        double lambda  = params[ 0];\n        double mu      = params[ 1];\n        double eta     = params[ 2];\n        double tau     = params[ 3];\n        double kappa   = params[ 4];\n        double nu      = params[ 5];\n        double sigma   = params[ 6];\n        double tau1    = params[ 7];\n        double tau2    = params[ 8];\n        double tau3    = params[ 9];\n        double tau4    = params[10];\n        double tau5    = params[11];\n        double tau6    = params[12];\n        double tau7    = params[13];\n        double tau8    = params[14];\n        double tau9    = params[15];\n        double tau10   = params[16];\n        double tau11   = params[17];\n\n        //Initialize the stiffness matrices\n        //SpMat A( 9, 9);\n        //SpMat B( 9, 9);\n        //SpMat C(27,27);\n        //SpMat D( 9, 9);\n\n        Matrix_9x9   A;\n        Matrix_9x9   B;\n        Matrix_27x27 C;\n        Matrix_9x9   D;\n\n        //assert(101==102);\n        //Populate the stiffness matrices\n        compute_A_voigt(lambda,mu,A);\n        compute_B_voigt(eta,kappa,nu,sigma,tau,B);\n        compute_C_voigt(tau1,tau2,tau3, tau4, tau5,tau6,\n                        tau7,tau8,tau9,tau10,tau11,C);\n        compute_D_voigt(sigma,tau,D);\n\n        //Compute the deformation measures\n        Matrix_3x3 RCG; //The right cauchy green deformation tensor\n        deformation_measures::get_right_cauchy_green(F,RCG);\n        Matrix_3x3 RCGinv = RCG.inverse(); //The inverse of the right cauchy green deformation tensor\n        Matrix_3x3 Psi; //The second order micromorphic deformation measure\n        deformation_measures::get_psi(F,chi,Psi);\n        Matrix_3x9 Gamma; //The higher order micromorphic deformation measure\n        deformation_measures::get_gamma(F,grad_chi,Gamma);\n\n        //Compute the strain measures\n        Matrix_3x3 E;\n        Matrix_3x3 E_micro;\n        deformation_measures::get_lagrange_strain(F,E);\n        deformation_measures::get_micro_strain(Psi,E_micro);\n\n        //Put the strain measures in voigt notation\n        Vector_9  E_voigt;\n        Vector_9  E_micro_voigt;\n        Vector_27 Gamma_voigt;\n\n        deformation_measures::voigt_3x3_tensor(E,       E_voigt);\n        deformation_measures::voigt_3x3_tensor(E_micro, E_micro_voigt);\n        deformation_measures::voigt_3x9_tensor(Gamma,   Gamma_voigt);\n\n        //std::cout << \"F:\\n\" << F << \"\\n\";\n        //std::cout << \"E_voigt:\\n\" << E_voigt << \"\\n\";\n        //std::cout << \"E_micro_voigt:\\n\" << E_micro_voigt << \"\\n\";\n\n        //Compute the stress measures\n        compute_PK2_stress(E_voigt, E_micro_voigt, Gamma_voigt, RCGinv, Psi, Gamma,\n                           A,       B,             C,           D,      PK2);\n                           \n        compute_symmetric_stress(E_voigt, E_micro_voigt, Gamma_voigt, RCGinv, Psi, Gamma,\n                           A,       B,             C,           D,      SIGMA);\n                           \n        compute_higher_order_stress(Gamma_voigt, C, M);\n        \n        //Compute the jacobians w.r.t. the derived deformation measures\n        Matrix_9x9  dPK2dRCG;\n        Matrix_9x9  dPK2dPsi;\n        Matrix_9x27 dPK2dGamma;\n        \n        Matrix_9x9  dSIGMAdRCG;\n        Matrix_9x9  dSIGMAdPsi;\n        Matrix_9x27 dSIGMAdGamma;\n        \n        Matrix_27x27 dMdGamma; //Note: other gradients are zero for M in this form.\n        \n        //Terms to speed up computation.\n        Matrix_9x9  dPK2dRCGterms[2];\n        Matrix_9x9  dPK2dPsiterms[2];\n        Matrix_9x27 dPK2dGammaterms[2];\n        \n        //Gradients of the PK2 stress\n        compute_dPK2dRCG(RCG, RCGinv, Gamma, Gamma_voigt, E,             E_micro, E_voigt, E_micro_voigt,\n                         A,   B,      C,     D,           dPK2dRCGterms, dPK2dRCG);\n                        \n        compute_dPK2dPsi(RCGinv, E_micro, E_voigt,       E_micro_voigt,\n                          B,      D,       dPK2dPsiterms, dPK2dPsi);\n                          \n        compute_dPK2dGamma(RCGinv, Gamma,           Gamma_voigt,\n                           C,      dPK2dGammaterms, dPK2dGamma);\n        \n        //Gradients of the symmetric stress (reference configuration)\n        compute_dSIGMAdRCG(dPK2dRCGterms, dSIGMAdRCG);\n    \n        compute_dSIGMAdPsi(dPK2dPsiterms, dSIGMAdPsi);\n    \n        compute_dSIGMAdGamma(dPK2dGammaterms, dSIGMAdGamma);\n        \n        compute_dMdGamma(Matrix_27x27(C), dMdGamma);\n        \n        //Gradients of the derived measures\n        //Note: Replaced sparse matricies with dense matrices\n        //      This is not the most efficient but it seems required\n        //      for use in MOOSE.\n        Matrix_9x9   dRCGdF;\n        \n        Matrix_9x9   dPsidF;\n        Matrix_9x9   dPsidchi;\n        \n        Matrix_27x9  dGammadF;\n        Matrix_27x27 dGammadgrad_chi;\n\n        deformation_measures::compute_dRCGdF(F,dRCGdF);\n\n        deformation_measures::compute_dPsidF(chi,dPsidF);\n        deformation_measures::compute_dPsidchi(F,dPsidchi);\n        \n        Vector_27 grad_chi_voigt;\n        deformation_measures::voigt_3x9_tensor(grad_chi,grad_chi_voigt);\n        \n        deformation_measures::compute_dGammadF(grad_chi_voigt,dGammadF);\n        deformation_measures::compute_dGammadgrad_chi(F, dGammadgrad_chi);\n\n        //Compute the jacobians of the stresses w.r.t. the fundamental deformation measures.\n        dPK2dF   = dPK2dRCG*dRCGdF   + dPK2dPsi*dPsidF   + dPK2dGamma*dGammadF;\n        dSIGMAdF = dSIGMAdRCG*dRCGdF + dSIGMAdPsi*dPsidF + dSIGMAdGamma*dGammadF;\n        dMdF     = dMdGamma*dGammadF; //Note: all other derivatives are zero.\n        \n        dPK2dchi   = dPK2dPsi*dPsidchi;\n        dSIGMAdchi = dSIGMAdPsi*dPsidchi;\n        dMdchi     = Matrix_27x9::Zero(); //Note: M is independent of the magnitude of chi (not so for grad_chi)\n        \n        dPK2dgrad_chi   = dPK2dGamma*dGammadgrad_chi;\n        dSIGMAdgrad_chi = dSIGMAdGamma*dGammadgrad_chi;\n        dMdgrad_chi     = dMdGamma*dGammadgrad_chi;\n        \n        return;    \n    }\n\n    void compute_A_voigt(const double &lambda,const double &mu, SpMat &A) {\n        /*!=========================\n           |    compute_A_voigt    |\n           =========================\n           \n           Compute the A stiffness matrix in voigt notation.\n        */\n\n        std::vector<T> tripletList;\n        tripletList.reserve(21);\n\n        tripletList.push_back(T(0,0,lambda + 2*mu));\n        tripletList.push_back(T(0,1,lambda));\n        tripletList.push_back(T(0,2,lambda));\n        tripletList.push_back(T(1,0,lambda));\n        tripletList.push_back(T(1,1,lambda + 2*mu));\n        tripletList.push_back(T(1,2,lambda));\n        tripletList.push_back(T(2,0,lambda));\n        tripletList.push_back(T(2,1,lambda));\n        tripletList.push_back(T(2,2,lambda + 2*mu));\n        tripletList.push_back(T(3,3,mu));\n        tripletList.push_back(T(3,6,mu));\n        tripletList.push_back(T(4,4,mu));\n        tripletList.push_back(T(4,7,mu));\n        tripletList.push_back(T(5,5,mu));\n        tripletList.push_back(T(5,8,mu));\n        tripletList.push_back(T(6,3,mu));\n        tripletList.push_back(T(6,6,mu));\n        tripletList.push_back(T(7,4,mu));\n        tripletList.push_back(T(7,7,mu));\n        tripletList.push_back(T(8,5,mu));\n        tripletList.push_back(T(8,8,mu));\n\n        A.setFromTriplets(tripletList.begin(), tripletList.end());\n\n        return;\n    }\n\n    void compute_A_voigt(const double &lambda,const double &mu, Matrix_9x9 &A) {\n        /*!=========================\n           |    compute_A_voigt    |\n           =========================\n           \n           Compute the A stiffness matrix in voigt notation.\n        */\n\n        A = Matrix_9x9::Zero();\n\n        A(0,0) = lambda + 2*mu;\n        A(0,1) = lambda;\n        A(0,2) = lambda;\n        A(1,0) = lambda;\n        A(1,1) = lambda + 2*mu;\n        A(1,2) = lambda;\n        A(2,0) = lambda;\n        A(2,1) = lambda;\n        A(2,2) = lambda + 2*mu;\n        A(3,3) = mu;\n        A(3,6) = mu;\n        A(4,4) = mu;\n        A(4,7) = mu;\n        A(5,5) = mu;\n        A(5,8) = mu;\n        A(6,3) = mu;\n        A(6,6) = mu;\n        A(7,4) = mu;\n        A(7,7) = mu;\n        A(8,5) = mu;\n        A(8,8) = mu;\n\n        return;\n    }\n    \n    void compute_B_voigt(const double &eta,   const double &kappa, const double &nu,\n                         const double &sigma, const double &tau,   SpMat &B) {\n        /*!=========================\n           |    compute_B_voigt    |\n           =========================\n           \n           Compute the B stiffness matrix in voigt notation.\n        */\n        \n        std::vector<T> tripletList;\n        tripletList.reserve(21);\n        \n        tripletList.push_back(T(0,0,eta + kappa + nu - 2*sigma - tau));\n        tripletList.push_back(T(0,1,eta - tau));\n        tripletList.push_back(T(0,2,eta - tau));\n        tripletList.push_back(T(1,0,eta - tau));\n        tripletList.push_back(T(1,1,eta + kappa + nu - 2*sigma - tau));\n        tripletList.push_back(T(1,2,eta - tau));\n        tripletList.push_back(T(2,0,eta - tau));\n        tripletList.push_back(T(2,1,eta - tau));\n        tripletList.push_back(T(2,2,eta + kappa + nu - 2*sigma - tau));\n        tripletList.push_back(T(3,3,kappa - sigma));\n        tripletList.push_back(T(3,6,nu - sigma));\n        tripletList.push_back(T(4,4,kappa - sigma));\n        tripletList.push_back(T(4,7,nu - sigma));\n        tripletList.push_back(T(5,5,kappa - sigma));\n        tripletList.push_back(T(5,8,nu - sigma));\n        tripletList.push_back(T(6,3,nu - sigma));\n        tripletList.push_back(T(6,6,kappa - sigma));\n        tripletList.push_back(T(7,4,nu - sigma));\n        tripletList.push_back(T(7,7,kappa - sigma));\n        tripletList.push_back(T(8,5,nu - sigma));\n        tripletList.push_back(T(8,8,kappa - sigma));\n        \n        B.setFromTriplets(tripletList.begin(), tripletList.end());\n        return;\n    }\n    \n    void compute_B_voigt(const double &eta,   const double &kappa, const double &nu,\n                         const double &sigma, const double &tau,   Matrix_9x9 &B) {\n        /*!=========================\n           |    compute_B_voigt    |\n           =========================\n           \n           Compute the B stiffness matrix in voigt notation.\n        */\n\n        B = Matrix_9x9::Zero();\n        \n        B(0,0) = eta + kappa + nu - 2*sigma - tau;\n        B(0,1) = eta - tau;\n        B(0,2) = eta - tau;\n        B(1,0) = eta - tau;\n        B(1,1) = eta + kappa + nu - 2*sigma - tau;\n        B(1,2) = eta - tau;\n        B(2,0) = eta - tau;\n        B(2,1) = eta - tau;\n        B(2,2) = eta + kappa + nu - 2*sigma - tau;\n        B(3,3) = kappa - sigma;\n        B(3,6) = nu - sigma;\n        B(4,4) = kappa - sigma;\n        B(4,7) = nu - sigma;\n        B(5,5) = kappa - sigma;\n        B(5,8) = nu - sigma;\n        B(6,3) = nu - sigma;\n        B(6,6) = kappa - sigma;\n        B(7,4) = nu - sigma;\n        B(7,7) = kappa - sigma;\n        B(8,5) = nu - sigma;\n        B(8,8) = kappa - sigma;\n        \n        return;\n    }\n\n    void compute_C_voigt(const double &tau1,  const double &tau2,  const double &tau3,\n                         const double &tau4,  const double &tau5,  const double &tau6,\n                         const double &tau7,  const double &tau8,  const double &tau9,\n                         const double &tau10, const double &tau11, SpMat &C) {\n        /*!=========================\n           |    compute_C_voigt    |\n           =========================\n           \n        Compute the C stiffness tensor in voigt \n        format.\n        \n        */\n        std::vector<T> tripletList;\n        tripletList.reserve(183);\n\n        tripletList.push_back(T(0,0,2*tau1 + tau10 + tau11 + 2*tau2 + tau3 + tau4 + 2*tau5 + tau6 + tau7 + 2*tau8 + tau9));\n        tripletList.push_back(T(0,1,tau1 + tau4 + tau5));\n        tripletList.push_back(T(0,2,tau1 + tau4 + tau5));\n        tripletList.push_back(T(0,14,tau2 + tau5 + tau6));\n        tripletList.push_back(T(0,17,tau1 + tau2 + tau3));\n        tripletList.push_back(T(0,22,tau2 + tau5 + tau6));\n        tripletList.push_back(T(0,25,tau1 + tau2 + tau3));\n        tripletList.push_back(T(1,0,tau1 + tau4 + tau5));\n        tripletList.push_back(T(1,1,tau4 + tau7 + tau9));\n        tripletList.push_back(T(1,2,tau4));\n        tripletList.push_back(T(1,14,tau10 + tau5 + tau8));\n        tripletList.push_back(T(1,17,tau1 + tau11 + tau8));\n        tripletList.push_back(T(1,22,tau5));\n        tripletList.push_back(T(1,25,tau1));\n        tripletList.push_back(T(2,0,tau1 + tau4 + tau5));\n        tripletList.push_back(T(2,1,tau4));\n        tripletList.push_back(T(2,2,tau4 + tau7 + tau9));\n        tripletList.push_back(T(2,14,tau5));\n        tripletList.push_back(T(2,17,tau1));\n        tripletList.push_back(T(2,22,tau10 + tau5 + tau8));\n        tripletList.push_back(T(2,25,tau1 + tau11 + tau8));\n        tripletList.push_back(T(3,3,tau7));\n        tripletList.push_back(T(3,6,tau9));\n        tripletList.push_back(T(3,13,tau10));\n        tripletList.push_back(T(3,16,tau8));\n        tripletList.push_back(T(3,23,tau8));\n        tripletList.push_back(T(3,26,tau11));\n        tripletList.push_back(T(4,4,tau10 + tau3 + tau7));\n        tripletList.push_back(T(4,7,tau2 + tau8 + tau9));\n        tripletList.push_back(T(4,12,tau3));\n        tripletList.push_back(T(4,15,tau2));\n        tripletList.push_back(T(4,18,tau1 + tau11 + tau8));\n        tripletList.push_back(T(4,19,tau1));\n        tripletList.push_back(T(4,20,tau1 + tau2 + tau3));\n        tripletList.push_back(T(5,5,tau10 + tau3 + tau7));\n        tripletList.push_back(T(5,8,tau2 + tau8 + tau9));\n        tripletList.push_back(T(5,9,tau1 + tau11 + tau8));\n        tripletList.push_back(T(5,10,tau1 + tau2 + tau3));\n        tripletList.push_back(T(5,11,tau1));\n        tripletList.push_back(T(5,21,tau2));\n        tripletList.push_back(T(5,24,tau3));\n        tripletList.push_back(T(6,3,tau9));\n        tripletList.push_back(T(6,6,tau7));\n        tripletList.push_back(T(6,13,tau8));\n        tripletList.push_back(T(6,16,tau11));\n        tripletList.push_back(T(6,23,tau10));\n        tripletList.push_back(T(6,26,tau8));\n        tripletList.push_back(T(7,4,tau2 + tau8 + tau9));\n        tripletList.push_back(T(7,7,tau11 + tau6 + tau7));\n        tripletList.push_back(T(7,12,tau2));\n        tripletList.push_back(T(7,15,tau6));\n        tripletList.push_back(T(7,18,tau10 + tau5 + tau8));\n        tripletList.push_back(T(7,19,tau5));\n        tripletList.push_back(T(7,20,tau2 + tau5 + tau6));\n        tripletList.push_back(T(8,5,tau2 + tau8 + tau9));\n        tripletList.push_back(T(8,8,tau11 + tau6 + tau7));\n        tripletList.push_back(T(8,9,tau10 + tau5 + tau8));\n        tripletList.push_back(T(8,10,tau2 + tau5 + tau6));\n        tripletList.push_back(T(8,11,tau5));\n        tripletList.push_back(T(8,21,tau6));\n        tripletList.push_back(T(8,24,tau2));\n        tripletList.push_back(T(9,5,tau1 + tau11 + tau8));\n        tripletList.push_back(T(9,8,tau10 + tau5 + tau8));\n        tripletList.push_back(T(9,9,tau4 + tau7 + tau9));\n        tripletList.push_back(T(9,10,tau1 + tau4 + tau5));\n        tripletList.push_back(T(9,11,tau4));\n        tripletList.push_back(T(9,21,tau5));\n        tripletList.push_back(T(9,24,tau1));\n        tripletList.push_back(T(10,5,tau1 + tau2 + tau3));\n        tripletList.push_back(T(10,8,tau2 + tau5 + tau6));\n        tripletList.push_back(T(10,9,tau1 + tau4 + tau5));\n        tripletList.push_back(T(10,10,2*tau1 + tau10 + tau11 + 2*tau2 + tau3 + tau4 + 2*tau5 + tau6 + tau7 + 2*tau8 + tau9));\n        tripletList.push_back(T(10,11,tau1 + tau4 + tau5));\n        tripletList.push_back(T(10,21,tau2 + tau5 + tau6));\n        tripletList.push_back(T(10,24,tau1 + tau2 + tau3));\n        tripletList.push_back(T(11,5,tau1));\n        tripletList.push_back(T(11,8,tau5));\n        tripletList.push_back(T(11,9,tau4));\n        tripletList.push_back(T(11,10,tau1 + tau4 + tau5));\n        tripletList.push_back(T(11,11,tau4 + tau7 + tau9));\n        tripletList.push_back(T(11,21,tau10 + tau5 + tau8));\n        tripletList.push_back(T(11,24,tau1 + tau11 + tau8));\n        tripletList.push_back(T(12,4,tau3));\n        tripletList.push_back(T(12,7,tau2));\n        tripletList.push_back(T(12,12,tau10 + tau3 + tau7));\n        tripletList.push_back(T(12,15,tau2 + tau8 + tau9));\n        tripletList.push_back(T(12,18,tau1));\n        tripletList.push_back(T(12,19,tau1 + tau11 + tau8));\n        tripletList.push_back(T(12,20,tau1 + tau2 + tau3));\n        tripletList.push_back(T(13,3,tau10));\n        tripletList.push_back(T(13,6,tau8));\n        tripletList.push_back(T(13,13,tau7));\n        tripletList.push_back(T(13,16,tau9));\n        tripletList.push_back(T(13,23,tau11));\n        tripletList.push_back(T(13,26,tau8));\n        tripletList.push_back(T(14,0,tau2 + tau5 + tau6));\n        tripletList.push_back(T(14,1,tau10 + tau5 + tau8));\n        tripletList.push_back(T(14,2,tau5));\n        tripletList.push_back(T(14,14,tau11 + tau6 + tau7));\n        tripletList.push_back(T(14,17,tau2 + tau8 + tau9));\n        tripletList.push_back(T(14,22,tau6));\n        tripletList.push_back(T(14,25,tau2));\n        tripletList.push_back(T(15,4,tau2));\n        tripletList.push_back(T(15,7,tau6));\n        tripletList.push_back(T(15,12,tau2 + tau8 + tau9));\n        tripletList.push_back(T(15,15,tau11 + tau6 + tau7));\n        tripletList.push_back(T(15,18,tau5));\n        tripletList.push_back(T(15,19,tau10 + tau5 + tau8));\n        tripletList.push_back(T(15,20,tau2 + tau5 + tau6));\n        tripletList.push_back(T(16,3,tau8));\n        tripletList.push_back(T(16,6,tau11));\n        tripletList.push_back(T(16,13,tau9));\n        tripletList.push_back(T(16,16,tau7));\n        tripletList.push_back(T(16,23,tau8));\n        tripletList.push_back(T(16,26,tau10));\n        tripletList.push_back(T(17,0,tau1 + tau2 + tau3));\n        tripletList.push_back(T(17,1,tau1 + tau11 + tau8));\n        tripletList.push_back(T(17,2,tau1));\n        tripletList.push_back(T(17,14,tau2 + tau8 + tau9));\n        tripletList.push_back(T(17,17,tau10 + tau3 + tau7));\n        tripletList.push_back(T(17,22,tau2));\n        tripletList.push_back(T(17,25,tau3));\n        tripletList.push_back(T(18,4,tau1 + tau11 + tau8));\n        tripletList.push_back(T(18,7,tau10 + tau5 + tau8));\n        tripletList.push_back(T(18,12,tau1));\n        tripletList.push_back(T(18,15,tau5));\n        tripletList.push_back(T(18,18,tau4 + tau7 + tau9));\n        tripletList.push_back(T(18,19,tau4));\n        tripletList.push_back(T(18,20,tau1 + tau4 + tau5));\n        tripletList.push_back(T(19,4,tau1));\n        tripletList.push_back(T(19,7,tau5));\n        tripletList.push_back(T(19,12,tau1 + tau11 + tau8));\n        tripletList.push_back(T(19,15,tau10 + tau5 + tau8));\n        tripletList.push_back(T(19,18,tau4));\n        tripletList.push_back(T(19,19,tau4 + tau7 + tau9));\n        tripletList.push_back(T(19,20,tau1 + tau4 + tau5));\n        tripletList.push_back(T(20,4,tau1 + tau2 + tau3));\n        tripletList.push_back(T(20,7,tau2 + tau5 + tau6));\n        tripletList.push_back(T(20,12,tau1 + tau2 + tau3));\n        tripletList.push_back(T(20,15,tau2 + tau5 + tau6));\n        tripletList.push_back(T(20,18,tau1 + tau4 + tau5));\n        tripletList.push_back(T(20,19,tau1 + tau4 + tau5));\n        tripletList.push_back(T(20,20,2*tau1 + tau10 + tau11 + 2*tau2 + tau3 + tau4 + 2*tau5 + tau6 + tau7 + 2*tau8 + tau9));\n        tripletList.push_back(T(21,5,tau2));\n        tripletList.push_back(T(21,8,tau6));\n        tripletList.push_back(T(21,9,tau5));\n        tripletList.push_back(T(21,10,tau2 + tau5 + tau6));\n        tripletList.push_back(T(21,11,tau10 + tau5 + tau8));\n        tripletList.push_back(T(21,21,tau11 + tau6 + tau7));\n        tripletList.push_back(T(21,24,tau2 + tau8 + tau9));\n        tripletList.push_back(T(22,0,tau2 + tau5 + tau6));\n        tripletList.push_back(T(22,1,tau5));\n        tripletList.push_back(T(22,2,tau10 + tau5 + tau8));\n        tripletList.push_back(T(22,14,tau6));\n        tripletList.push_back(T(22,17,tau2));\n        tripletList.push_back(T(22,22,tau11 + tau6 + tau7));\n        tripletList.push_back(T(22,25,tau2 + tau8 + tau9));\n        tripletList.push_back(T(23,3,tau8));\n        tripletList.push_back(T(23,6,tau10));\n        tripletList.push_back(T(23,13,tau11));\n        tripletList.push_back(T(23,16,tau8));\n        tripletList.push_back(T(23,23,tau7));\n        tripletList.push_back(T(23,26,tau9));\n        tripletList.push_back(T(24,5,tau3));\n        tripletList.push_back(T(24,8,tau2));\n        tripletList.push_back(T(24,9,tau1));\n        tripletList.push_back(T(24,10,tau1 + tau2 + tau3));\n        tripletList.push_back(T(24,11,tau1 + tau11 + tau8));\n        tripletList.push_back(T(24,21,tau2 + tau8 + tau9));\n        tripletList.push_back(T(24,24,tau10 + tau3 + tau7));\n        tripletList.push_back(T(25,0,tau1 + tau2 + tau3));\n        tripletList.push_back(T(25,1,tau1));\n        tripletList.push_back(T(25,2,tau1 + tau11 + tau8));\n        tripletList.push_back(T(25,14,tau2));\n        tripletList.push_back(T(25,17,tau3));\n        tripletList.push_back(T(25,22,tau2 + tau8 + tau9));\n        tripletList.push_back(T(25,25,tau10 + tau3 + tau7));\n        tripletList.push_back(T(26,3,tau11));\n        tripletList.push_back(T(26,6,tau8));\n        tripletList.push_back(T(26,13,tau8));\n        tripletList.push_back(T(26,16,tau10));\n        tripletList.push_back(T(26,23,tau9));\n        tripletList.push_back(T(26,26,tau7));\n        \n        C.setFromTriplets(tripletList.begin(), tripletList.end());\n        return;\n    }\n    \n    void compute_C_voigt(const double &tau1,  const double &tau2,  const double &tau3,\n                         const double &tau4,  const double &tau5,  const double &tau6,\n                         const double &tau7,  const double &tau8,  const double &tau9,\n                         const double &tau10, const double &tau11, Matrix_27x27 &C) {\n        /*!=========================\n           |    compute_C_voigt    |\n           =========================\n           \n        Compute the C stiffness tensor in voigt \n        format.\n        \n        */\n        C = Matrix_27x27::Zero();\n\n        C( 0, 0) = 2*tau1 + tau10 + tau11 + 2*tau2 + tau3 + tau4 + 2*tau5 + tau6 + tau7 + 2*tau8 + tau9;\n        C( 0, 1) = tau1 + tau4 + tau5;\n        C( 0, 2) = tau1 + tau4 + tau5;\n        C( 0,14) = tau2 + tau5 + tau6;\n        C( 0,17) = tau1 + tau2 + tau3;\n        C( 0,22) = tau2 + tau5 + tau6;\n        C( 0,25) = tau1 + tau2 + tau3;\n        C( 1, 0) = tau1 + tau4 + tau5;\n        C( 1, 1) = tau4 + tau7 + tau9;\n        C( 1, 2) = tau4;\n        C( 1,14) = tau10 + tau5 + tau8;\n        C( 1,17) = tau1 + tau11 + tau8;\n        C( 1,22) = tau5;\n        C( 1,25) = tau1;\n        C( 2, 0) = tau1 + tau4 + tau5;\n        C( 2, 1) = tau4;\n        C( 2, 2) = tau4 + tau7 + tau9;\n        C( 2,14) = tau5;\n        C( 2,17) = tau1;\n        C( 2,22) = tau10 + tau5 + tau8;\n        C( 2,25) = tau1 + tau11 + tau8;\n        C( 3, 3) = tau7;\n        C( 3, 6) = tau9;\n        C( 3,13) = tau10;\n        C( 3,16) = tau8;\n        C( 3,23) = tau8;\n        C( 3,26) = tau11;\n        C( 4, 4) = tau10 + tau3 + tau7;\n        C( 4, 7) = tau2 + tau8 + tau9;\n        C( 4,12) = tau3;\n        C( 4,15) = tau2;\n        C( 4,18) = tau1 + tau11 + tau8;\n        C( 4,19) = tau1;\n        C( 4,20) = tau1 + tau2 + tau3;\n        C( 5, 5) = tau10 + tau3 + tau7;\n        C( 5, 8) = tau2 + tau8 + tau9;\n        C( 5, 9) = tau1 + tau11 + tau8;\n        C( 5,10) = tau1 + tau2 + tau3;\n        C( 5,11) = tau1;\n        C( 5,21) = tau2;\n        C( 5,24) = tau3;\n        C( 6, 3) = tau9;\n        C( 6, 6) = tau7;\n        C( 6,13) = tau8;\n        C( 6,16) = tau11;\n        C( 6,23) = tau10;\n        C( 6,26) = tau8;\n        C( 7, 4) = tau2 + tau8 + tau9;\n        C( 7, 7) = tau11 + tau6 + tau7;\n        C( 7,12) = tau2;\n        C( 7,15) = tau6;\n        C( 7,18) = tau10 + tau5 + tau8;\n        C( 7,19) = tau5;\n        C( 7,20) = tau2 + tau5 + tau6;\n        C( 8, 5) = tau2 + tau8 + tau9;\n        C( 8, 8) = tau11 + tau6 + tau7;\n        C( 8, 9) = tau10 + tau5 + tau8;\n        C( 8,10) = tau2 + tau5 + tau6;\n        C( 8,11) = tau5;\n        C( 8,21) = tau6;\n        C( 8,24) = tau2;\n        C( 9, 5) = tau1 + tau11 + tau8;\n        C( 9, 8) = tau10 + tau5 + tau8;\n        C( 9, 9) = tau4 + tau7 + tau9;\n        C( 9,10) = tau1 + tau4 + tau5;\n        C( 9,11) = tau4;\n        C( 9,21) = tau5;\n        C( 9,24) = tau1;\n        C(10, 5) = tau1 + tau2 + tau3;\n        C(10, 8) = tau2 + tau5 + tau6;\n        C(10, 9) = tau1 + tau4 + tau5;\n        C(10,10) = 2*tau1 + tau10 + tau11 + 2*tau2 + tau3 + tau4 + 2*tau5 + tau6 + tau7 + 2*tau8 + tau9;\n        C(10,11) = tau1 + tau4 + tau5;\n        C(10,21) = tau2 + tau5 + tau6;\n        C(10,24) = tau1 + tau2 + tau3;\n        C(11, 5) = tau1;\n        C(11, 8) = tau5;\n        C(11, 9) = tau4;\n        C(11,10) = tau1 + tau4 + tau5;\n        C(11,11) = tau4 + tau7 + tau9;\n        C(11,21) = tau10 + tau5 + tau8;\n        C(11,24) = tau1 + tau11 + tau8;\n        C(12, 4) = tau3;\n        C(12, 7) = tau2;\n        C(12,12) = tau10 + tau3 + tau7;\n        C(12,15) = tau2 + tau8 + tau9;\n        C(12,18) = tau1;\n        C(12,19) = tau1 + tau11 + tau8;\n        C(12,20) = tau1 + tau2 + tau3;\n        C(13, 3) = tau10;\n        C(13, 6) = tau8;\n        C(13,13) = tau7;\n        C(13,16) = tau9;\n        C(13,23) = tau11;\n        C(13,26) = tau8;\n        C(14, 0) = tau2 + tau5 + tau6;\n        C(14, 1) = tau10 + tau5 + tau8;\n        C(14, 2) = tau5;\n        C(14,14) = tau11 + tau6 + tau7;\n        C(14,17) = tau2 + tau8 + tau9;\n        C(14,22) = tau6;\n        C(14,25) = tau2;\n        C(15, 4) = tau2;\n        C(15, 7) = tau6;\n        C(15,12) = tau2 + tau8 + tau9;\n        C(15,15) = tau11 + tau6 + tau7;\n        C(15,18) = tau5;\n        C(15,19) = tau10 + tau5 + tau8;\n        C(15,20) = tau2 + tau5 + tau6;\n        C(16, 3) = tau8;\n        C(16, 6) = tau11;\n        C(16,13) = tau9;\n        C(16,16) = tau7;\n        C(16,23) = tau8;\n        C(16,26) = tau10;\n        C(17, 0) = tau1 + tau2 + tau3;\n        C(17, 1) = tau1 + tau11 + tau8;\n        C(17, 2) = tau1;\n        C(17,14) = tau2 + tau8 + tau9;\n        C(17,17) = tau10 + tau3 + tau7;\n        C(17,22) = tau2;\n        C(17,25) = tau3;\n        C(18, 4) = tau1 + tau11 + tau8;\n        C(18, 7) = tau10 + tau5 + tau8;\n        C(18,12) = tau1;\n        C(18,15) = tau5;\n        C(18,18) = tau4 + tau7 + tau9;\n        C(18,19) = tau4;\n        C(18,20) = tau1 + tau4 + tau5;\n        C(19, 4) = tau1;\n        C(19, 7) = tau5;\n        C(19,12) = tau1 + tau11 + tau8;\n        C(19,15) = tau10 + tau5 + tau8;\n        C(19,18) = tau4;\n        C(19,19) = tau4 + tau7 + tau9;\n        C(19,20) = tau1 + tau4 + tau5;\n        C(20, 4) = tau1 + tau2 + tau3;\n        C(20, 7) = tau2 + tau5 + tau6;\n        C(20,12) = tau1 + tau2 + tau3;\n        C(20,15) = tau2 + tau5 + tau6;\n        C(20,18) = tau1 + tau4 + tau5;\n        C(20,19) = tau1 + tau4 + tau5;\n        C(20,20) = 2*tau1 + tau10 + tau11 + 2*tau2 + tau3 + tau4 + 2*tau5 + tau6 + tau7 + 2*tau8 + tau9;\n        C(21, 5) = tau2;\n        C(21, 8) = tau6;\n        C(21, 9) = tau5;\n        C(21,10) = tau2 + tau5 + tau6;\n        C(21,11) = tau10 + tau5 + tau8;\n        C(21,21) = tau11 + tau6 + tau7;\n        C(21,24) = tau2 + tau8 + tau9;\n        C(22, 0) = tau2 + tau5 + tau6;\n        C(22, 1) = tau5;\n        C(22, 2) = tau10 + tau5 + tau8;\n        C(22,14) = tau6;\n        C(22,17) = tau2;\n        C(22,22) = tau11 + tau6 + tau7;\n        C(22,25) = tau2 + tau8 + tau9;\n        C(23, 3) = tau8;\n        C(23, 6) = tau10;\n        C(23,13) = tau11;\n        C(23,16) = tau8;\n        C(23,23) = tau7;\n        C(23,26) = tau9;\n        C(24, 5) = tau3;\n        C(24, 8) = tau2;\n        C(24, 9) = tau1;\n        C(24,10) = tau1 + tau2 + tau3;\n        C(24,11) = tau1 + tau11 + tau8;\n        C(24,21) = tau2 + tau8 + tau9;\n        C(24,24) = tau10 + tau3 + tau7;\n        C(25, 0) = tau1 + tau2 + tau3;\n        C(25, 1) = tau1;\n        C(25, 2) = tau1 + tau11 + tau8;\n        C(25,14) = tau2;\n        C(25,17) = tau3;\n        C(25,22) = tau2 + tau8 + tau9;\n        C(25,25) = tau10 + tau3 + tau7;\n        C(26, 3) = tau11;\n        C(26, 6) = tau8;\n        C(26,13) = tau8;\n        C(26,16) = tau10;\n        C(26,23) = tau9;\n        C(26,26) = tau7;\n\n        return;\n    }\n    void compute_D_voigt(const double &sigma, const double &tau, SpMat &D){\n        /*!=========================\n           |    compute_D_voigt    |\n           =========================\n           \n        Compute the D stiffness tensor in voigt \n        format.\n        \n        */\n        std::vector<T> tripletList;\n        tripletList.reserve(21);\n\n        tripletList.push_back(T(0,0,2*sigma + tau));\n        tripletList.push_back(T(0,1,tau));\n        tripletList.push_back(T(0,2,tau));\n        tripletList.push_back(T(1,0,tau));\n        tripletList.push_back(T(1,1,2*sigma + tau));\n        tripletList.push_back(T(1,2,tau));\n        tripletList.push_back(T(2,0,tau));\n        tripletList.push_back(T(2,1,tau));\n        tripletList.push_back(T(2,2,2*sigma + tau));\n        tripletList.push_back(T(3,3,sigma));\n        tripletList.push_back(T(3,6,sigma));\n        tripletList.push_back(T(4,4,sigma));\n        tripletList.push_back(T(4,7,sigma));\n        tripletList.push_back(T(5,5,sigma));\n        tripletList.push_back(T(5,8,sigma));\n        tripletList.push_back(T(6,3,sigma));\n        tripletList.push_back(T(6,6,sigma));\n        tripletList.push_back(T(7,4,sigma));\n        tripletList.push_back(T(7,7,sigma));\n        tripletList.push_back(T(8,5,sigma));\n        tripletList.push_back(T(8,8,sigma));       \n        \n        D.setFromTriplets(tripletList.begin(), tripletList.end());\n        return;\n    }\n\n\n    void compute_D_voigt(const double &sigma, const double &tau, Matrix_9x9 &D){\n        /*!=========================\n           |    compute_D_voigt    |\n           =========================\n           \n        Compute the D stiffness tensor in voigt \n        format.\n        \n        */\n        D = Matrix_9x9::Zero();\n\n        D( 0, 0) = 2*sigma + tau;\n        D( 0, 1) = tau;\n        D( 0, 2) = tau;\n        D( 1, 0) = tau;\n        D( 1, 1) = 2*sigma + tau;\n        D( 1, 2) = tau;\n        D( 2, 0) = tau;\n        D( 2, 1) = tau;\n        D( 2, 2) = 2*sigma + tau;\n        D( 3, 3) = sigma;\n        D( 3, 6) = sigma;\n        D( 4, 4) = sigma;\n        D( 4, 7) = sigma;\n        D( 5, 5) = sigma;\n        D( 5, 8) = sigma;\n        D( 6, 3) = sigma;\n        D( 6, 6) = sigma;\n        D( 7, 4) = sigma;\n        D( 7, 7) = sigma;\n        D( 8, 5) = sigma;\n        D( 8, 8) = sigma;\n\n        return;\n    }\n    \n    void compute_PK2_stress(const Vector_9 &E_voigt,    const Vector_9 &E_micro_voigt, const Vector_27 &Gamma_voigt,\n                            const Matrix_3x3 &RCGinv,   const Matrix_3x3 &Psi,         const Matrix_3x9 &Gamma,\n                            const SpMat &A, const SpMat &B,    const SpMat &C,\n                            const SpMat &D, Vector_9 &PK2){\n        /*!============================\n        |    compute_PK2_stress    |\n        ============================\n           \n        Compute the second piola kirchoff stress.\n           \n        */\n        \n        PK2 = A*E_voigt;        //Compute the first terms\n        PK2 += D*E_micro_voigt;\n        \n        //Compute the middle terms\n        Matrix_3x3 Temp1;\n        deformation_measures::undo_voigt_3x3_tensor(B*E_micro_voigt+D*E_voigt,Temp1);\n        Vector_9 term3_4_voigt;\n        deformation_measures::voigt_3x3_tensor(Temp1*(RCGinv*Psi).transpose(),term3_4_voigt);\n        \n        PK2 += term3_4_voigt;\n        \n        //Compute the end terms\n        Matrix_3x9 Temp2;\n        deformation_measures::undo_voigt_3x9_tensor(C*Gamma_voigt,Temp2);\n        Vector_9 term5_voigt;\n        deformation_measures::voigt_3x3_tensor(Temp2*(RCGinv*Gamma).transpose(),term5_voigt);\n        PK2 += term5_voigt;\n        return;\n    }\n    \n    void compute_PK2_stress(const Vector_9 &E_voigt,    const Vector_9 &E_micro_voigt, const Vector_27 &Gamma_voigt,\n                            const Matrix_3x3 &RCGinv,   const Matrix_3x3 &Psi,         const Matrix_3x9 &Gamma,\n                            const Matrix_9x9 &A,        const Matrix_9x9 &B,           const Matrix_27x27 &C,\n                            const Matrix_9x9 &D,        Vector_9 &PK2){\n        /*!============================\n        |    compute_PK2_stress    |\n        ============================\n           \n        Compute the second piola kirchoff stress.\n           \n        */\n        \n        PK2 = A*E_voigt;        //Compute the first terms\n        PK2 += D*E_micro_voigt;\n        \n        //Compute the middle terms\n        Matrix_3x3 Temp1;\n        deformation_measures::undo_voigt_3x3_tensor(B*E_micro_voigt+D*E_voigt,Temp1);\n        Vector_9 term3_4_voigt;\n        deformation_measures::voigt_3x3_tensor(Temp1*(RCGinv*Psi).transpose(),term3_4_voigt);\n        \n        PK2 += term3_4_voigt;\n        \n        //Compute the end terms\n        Matrix_3x9 Temp2;\n        deformation_measures::undo_voigt_3x9_tensor(C*Gamma_voigt,Temp2);\n        Vector_9 term5_voigt;\n        deformation_measures::voigt_3x3_tensor(Temp2*(RCGinv*Gamma).transpose(),term5_voigt);\n        PK2 += term5_voigt;\n        return;\n    }\n\n    void compute_symmetric_stress(const Vector_9 &E_voigt,    const Vector_9 &E_micro_voigt, const Vector_27 &Gamma_voigt,\n                            const Matrix_3x3 &RCGinv,     const Matrix_3x3 &Psi,         const Matrix_3x9 &Gamma,\n                            const SpMat &A, const SpMat &B,    const SpMat &C,\n                            const SpMat &D, Vector_9 &SIGMA){\n        /*!=====================================\n           |    compute_symmetric_stress    |\n           ==================================\n           \n           Compute the symmetric stress in the reference configuration.\n           \n        */\n        \n        SIGMA = A*E_voigt;        //Compute the first terms\n        SIGMA += D*E_micro_voigt;\n        \n        //Compute the middle terms\n        Matrix_3x3 Temp1;\n        deformation_measures::undo_voigt_3x3_tensor(B*E_micro_voigt+D*E_voigt,Temp1);\n        Matrix_3x3 symmetric_part = Temp1*(RCGinv*Psi).transpose();\n        \n        //Compute the end terms\n        Matrix_3x9 Temp2;\n        deformation_measures::undo_voigt_3x9_tensor(C*Gamma_voigt,Temp2);\n        symmetric_part += Temp2*(RCGinv*Gamma).transpose();\n        Vector_9 vector_symm_part;\n        deformation_measures::voigt_3x3_tensor((symmetric_part + symmetric_part.transpose()),vector_symm_part);\n        \n        SIGMA += vector_symm_part;\n        \n        return;\n    }\n    \n    void compute_symmetric_stress(const Vector_9 &E_voigt,    const Vector_9 &E_micro_voigt, const Vector_27 &Gamma_voigt,\n                                  const Matrix_3x3 &RCGinv,   const Matrix_3x3 &Psi,         const Matrix_3x9 &Gamma,\n                                  const Matrix_9x9 &A,        const Matrix_9x9 &B,           const Matrix_27x27 &C,\n                                  const Matrix_9x9 &D,        Vector_9 &SIGMA){\n        /*!=====================================\n           |    compute_symmetric_stress    |\n           ==================================\n           \n           Compute the symmetric stress in the reference configuration.\n           \n        */\n        \n        SIGMA = A*E_voigt;        //Compute the first terms\n        SIGMA += D*E_micro_voigt;\n        \n        //Compute the middle terms\n        Matrix_3x3 Temp1;\n        deformation_measures::undo_voigt_3x3_tensor(B*E_micro_voigt+D*E_voigt,Temp1);\n        Matrix_3x3 symmetric_part = Temp1*(RCGinv*Psi).transpose();\n        \n        //Compute the end terms\n        Matrix_3x9 Temp2;\n        deformation_measures::undo_voigt_3x9_tensor(C*Gamma_voigt,Temp2);\n        symmetric_part += Temp2*(RCGinv*Gamma).transpose();\n        Vector_9 vector_symm_part;\n        deformation_measures::voigt_3x3_tensor((symmetric_part + symmetric_part.transpose()),vector_symm_part);\n        \n        SIGMA += vector_symm_part;\n        \n        return;\n    }\n\n    void compute_higher_order_stress(const Vector_27 &Gamma_voigt, const SpMat &C, Vector_27 &M){\n        /*!=====================================\n        |    compute_higher_order_stress    |\n        =====================================\n          \n        Compute the higher order stress in the reference configuration.\n          \n        */\n        \n        M = C*Gamma_voigt; //Compute the stress (requires positive permutation)\n        deformation_measures::perform_right_positive_cyclic_permutation(M); //Perform the permutation\n    }\n    \n    void compute_higher_order_stress(const Vector_27 &Gamma_voigt, const Matrix_27x27 &C, Vector_27 &M){\n        /*!=====================================\n        |    compute_higher_order_stress    |\n        =====================================\n          \n        Compute the higher order stress in the reference configuration.\n          \n        */\n        \n        M = C*Gamma_voigt; //Compute the stress (requires positive permutation)\n        deformation_measures::perform_right_positive_cyclic_permutation(M); //Perform the permutation\n    }\n\n    void compute_dPK2dRCG(const Matrix_3x3 &RCG, const Matrix_3x3 &RCGinv, const Matrix_3x9 &Gamma, const Vector_27 &Gamma_voigt,\n                          const Matrix_3x3 &E, const Matrix_3x3 &E_micro, const Vector_9 &E_voigt, const Vector_9 &E_micro_voigt,\n                          const SpMat &A,      const SpMat &B,        const SpMat &C,  const SpMat &D, Matrix_9x9 &dPK2dRCG){\n        /*!==========================\n        |    compute_dPK2dRCG    |\n        ==========================\n        \n        Compute the derivative of the PK2 stress w.r.t. \n        the deformation gradient.\n        \n        */\n        \n        //Initialize temporary terms\n        Vector_9   V1;\n        Vector_27  V2;\n        Matrix_3x3 T1;\n        Matrix_9x9 T2;\n        Matrix_3x9 T3;\n        \n        Matrix_9x9 dRCGinvdRCG;\n        deformation_measures::compute_dAinvdA(RCGinv,dRCGinvdRCG);\n        \n        //Compute term1\n        Matrix_9x9 term1;\n        term1 = 0.5*A;\n        \n        //Compute term2\n        Matrix_9x9 term2;\n        T1 = RCGinv*(E_micro+Matrix_3x3::Identity());\n        deformation_measures::dot_2ot_4ot(1,1,T1,0.5*D,term2);\n        \n        //Compute term3\n        Matrix_9x9 term3;\n        V1 = (B*E_micro_voigt+D*E_voigt);\n        deformation_measures::undo_voigt_3x3_tensor(V1,T1);\n        deformation_measures::dot_2ot_4ot(1,0,T1*(E_micro+Matrix_3x3::Identity()).transpose(),dRCGinvdRCG,term3);\n        \n        //Compute term4\n        Matrix_9x9 term4;\n        deformation_measures::undo_voigt_3x9_tensor(C*Gamma_voigt,T3);\n        T1 = T3*Gamma.transpose();\n        deformation_measures::dot_2ot_4ot(1,0,T1,dRCGinvdRCG,term4);\n        \n        //Assemble the derivative\n        dPK2dRCG = (term1+term2+term3+term4);\n        \n        return;\n    }\n    \n    void compute_dPK2dRCG(const Matrix_3x3 &RCG, const Matrix_3x3 &RCGinv,  const Matrix_3x9 &Gamma, const Vector_27 &Gamma_voigt,\n                          const Matrix_3x3 &E,   const Matrix_3x3 &E_micro, const Vector_9 &E_voigt, const Vector_9 &E_micro_voigt,\n                          const Matrix_9x9 &A,   const Matrix_9x9 &B,       const Matrix_27x27 &C,   const Matrix_9x9 &D, Matrix_9x9 &dPK2dRCG){\n        /*!==========================\n        |    compute_dPK2dRCG    |\n        ==========================\n        \n        Compute the derivative of the PK2 stress w.r.t. \n        the deformation gradient.\n        \n        */\n        \n        //Initialize temporary terms\n        Vector_9   V1;\n        Vector_27  V2;\n        Matrix_3x3 T1;\n        Matrix_9x9 T2;\n        Matrix_3x9 T3;\n        \n        Matrix_9x9 dRCGinvdRCG;\n        deformation_measures::compute_dAinvdA(RCGinv,dRCGinvdRCG);\n        \n        //Compute term1\n        Matrix_9x9 term1;\n        term1 = 0.5*A;\n        \n        //Compute term2\n        Matrix_9x9 term2;\n        T1 = RCGinv*(E_micro+Matrix_3x3::Identity());\n        deformation_measures::dot_2ot_4ot(1,1,T1,0.5*D,term2);\n        \n        //Compute term3\n        Matrix_9x9 term3;\n        V1 = (B*E_micro_voigt+D*E_voigt);\n        deformation_measures::undo_voigt_3x3_tensor(V1,T1);\n        deformation_measures::dot_2ot_4ot(1,0,T1*(E_micro+Matrix_3x3::Identity()).transpose(),dRCGinvdRCG,term3);\n        \n        //Compute term4\n        Matrix_9x9 term4;\n        deformation_measures::undo_voigt_3x9_tensor(C*Gamma_voigt,T3);\n        T1 = T3*Gamma.transpose();\n        deformation_measures::dot_2ot_4ot(1,0,T1,dRCGinvdRCG,term4);\n        \n        //Assemble the derivative\n        dPK2dRCG = (term1+term2+term3+term4);\n        \n        return;\n    }\n\n    void compute_dPK2dRCG(const Matrix_3x3 &RCG, const Matrix_3x3 &RCGinv, const Matrix_3x9 &Gamma, const Vector_27 &Gamma_voigt,\n                          const Matrix_3x3 &E, const Matrix_3x3 &E_micro, const Vector_9 &E_voigt, const Vector_9 &E_micro_voigt,\n                          const SpMat &A,      const SpMat &B,        const SpMat &C,  const SpMat &D, Matrix_9x9 (&terms)[2], Matrix_9x9 &dPK2dRCG){\n        /*!==========================\n        |    compute_dPK2dRCG    |\n        ==========================\n        \n        Compute the derivative of the PK2 stress w.r.t. \n        the deformation gradient.\n        \n        */\n        \n        //Initialize temporary terms\n        Vector_9   V1;\n        Vector_27  V2;\n        Matrix_3x3 T1;\n        Matrix_9x9 T2;\n        Matrix_3x9 T3;\n        Matrix_9x9 temp;\n        \n        Matrix_9x9 dRCGinvdRCG;\n        deformation_measures::compute_dAinvdA(RCGinv,dRCGinvdRCG);\n        \n        //Compute term1\n        terms[0] = 0.5*A;\n        \n        //Compute term2\n        T1 = RCGinv*(E_micro+Matrix_3x3::Identity());\n        deformation_measures::dot_2ot_4ot(1,1,T1,0.5*D,terms[1]);\n        \n        //Compute term3\n        V1 = (B*E_micro_voigt+D*E_voigt);\n        deformation_measures::undo_voigt_3x3_tensor(V1,T1);\n        deformation_measures::dot_2ot_4ot(1,0,T1*(E_micro+Matrix_3x3::Identity()).transpose(),dRCGinvdRCG,temp);\n        terms[1] += temp;        \n\n        //Compute term4\n        deformation_measures::undo_voigt_3x9_tensor(C*Gamma_voigt,T3);\n        T1 = T3*Gamma.transpose();\n        deformation_measures::dot_2ot_4ot(1,0,T1,dRCGinvdRCG,temp);\n        terms[1] += temp;        \n\n        //Assemble the derivative\n        dPK2dRCG = (terms[0] + terms[1]);\n        \n        return;\n    }\n    \n    void compute_dPK2dRCG(const Matrix_3x3 &RCG, const Matrix_3x3 &RCGinv,  const Matrix_3x9 &Gamma, const Vector_27 &Gamma_voigt,\n                          const Matrix_3x3 &E,   const Matrix_3x3 &E_micro, const Vector_9 &E_voigt, const Vector_9 &E_micro_voigt,\n                          const Matrix_9x9 &A,   const Matrix_9x9 &B,       const Matrix_27x27 &C,   const Matrix_9x9 &D, Matrix_9x9 (&terms)[2], Matrix_9x9 &dPK2dRCG){\n        /*!==========================\n        |    compute_dPK2dRCG    |\n        ==========================\n        \n        Compute the derivative of the PK2 stress w.r.t. \n        the deformation gradient.\n        \n        */\n        \n        //Initialize temporary terms\n        Vector_9   V1;\n        Vector_27  V2;\n        Matrix_3x3 T1;\n        Matrix_9x9 T2;\n        Matrix_3x9 T3;\n        Matrix_9x9 temp;\n        \n        Matrix_9x9 dRCGinvdRCG;\n        deformation_measures::compute_dAinvdA(RCGinv,dRCGinvdRCG);\n        \n        //Compute term1\n        terms[0] = 0.5*A;\n        \n        //Compute term2\n        T1 = RCGinv*(E_micro+Matrix_3x3::Identity());\n        deformation_measures::dot_2ot_4ot(1,1,T1,0.5*D,terms[1]);\n        \n        //Compute term3\n        V1 = (B*E_micro_voigt+D*E_voigt);\n        deformation_measures::undo_voigt_3x3_tensor(V1,T1);\n        deformation_measures::dot_2ot_4ot(1,0,T1*(E_micro+Matrix_3x3::Identity()).transpose(),dRCGinvdRCG,temp);\n        terms[1] += temp;\n        \n        //Compute term4\n        deformation_measures::undo_voigt_3x9_tensor(C*Gamma_voigt,T3);\n        T1 = T3*Gamma.transpose();\n        deformation_measures::dot_2ot_4ot(1,0,T1,dRCGinvdRCG,temp);\n        terms[1] += temp;\n        \n        //Assemble the derivative\n        dPK2dRCG = (terms[0] + terms[1]);\n        \n        return;\n    }\n\n    void compute_dPK2dPsi(const Matrix_3x3 &RCGinv, const Matrix_3x3 &E_micro, const Vector_9 &E_voigt, const Vector_9 &E_micro_voigt,\n                          const SpMat &B, const SpMat &D, Matrix_9x9 &dPK2dPsi){\n        /*!==========================\n        |    compute_dPK2dPsi    |\n        ==========================\n        \n        Compute the derivative of the second piola kirchoff \n        stress w.r.t. the deformation measure Psi.\n        \n        */\n        \n        //Initialize temporary terms\n        Vector_9   V1;\n        Vector_27  V2;\n        Matrix_3x3 T1;\n        Matrix_9x9 T2;\n        Matrix_3x9 T3;\n        \n        //Add term1\n        dPK2dPsi = D;\n        \n        //Add term2\n        deformation_measures::dot_2ot_4ot(1, 1, RCGinv*(E_micro + Matrix_3x3::Identity()), B, T2);\n        dPK2dPsi += T2;\n        \n        //Add term3\n        V1 = B*E_micro_voigt + D*E_voigt;\n        deformation_measures::undo_voigt_3x3_tensor(V1,T1);\n        deformation_measures::two_sot_to_fot(2,T1,RCGinv,T2);\n        dPK2dPsi += T2;\n        \n        return;\n    }\n    \n    void compute_dPK2dPsi(const Matrix_3x3 &RCGinv, const Matrix_3x3 &E_micro, const Vector_9 &E_voigt, const Vector_9 &E_micro_voigt,\n                          const Matrix_9x9 &B,      const Matrix_9x9 &D,       Matrix_9x9 &dPK2dPsi){\n        /*!==========================\n        |    compute_dPK2dPsi    |\n        ==========================\n        \n        Compute the derivative of the second piola kirchoff \n        stress w.r.t. the deformation measure Psi.\n        \n        */\n        \n        //Initialize temporary terms\n        Vector_9   V1;\n        Vector_27  V2;\n        Matrix_3x3 T1;\n        Matrix_9x9 T2;\n        Matrix_3x9 T3;\n        \n        //Add term1\n        dPK2dPsi = D;\n        \n        //Add term2\n        deformation_measures::dot_2ot_4ot(1, 1, RCGinv*(E_micro + Matrix_3x3::Identity()), B, T2);\n        dPK2dPsi += T2;\n        \n        //Add term3\n        V1 = B*E_micro_voigt + D*E_voigt;\n        deformation_measures::undo_voigt_3x3_tensor(V1,T1);\n        deformation_measures::two_sot_to_fot(2,T1,RCGinv,T2);\n        dPK2dPsi += T2;\n        \n        return;\n    }\n\n    void compute_dPK2dPsi(const Matrix_3x3 &RCGinv, const Matrix_3x3 &E_micro, const Vector_9 &E_voigt, const Vector_9 &E_micro_voigt,\n                          const SpMat &B, const SpMat &D, Matrix_9x9 (&terms)[2], Matrix_9x9 &dPK2dPsi){\n        /*!==========================\n        |    compute_dPK2dPsi    |\n        ==========================\n        \n        Compute the derivative of the second piola kirchoff \n        stress w.r.t. the deformation measure Psi.\n        \n        */\n        \n        //Initialize temporary terms\n        Vector_9   V1;\n        Vector_27  V2;\n        Matrix_3x3 T1;\n        Matrix_9x9 T2;\n        Matrix_3x9 T3;\n        \n        //Add term1\n        terms[0] = D;\n        \n        //Add term2\n        deformation_measures::dot_2ot_4ot(1, 1, RCGinv*(E_micro + Matrix_3x3::Identity()), B, T2);\n        terms[1] = T2;\n        \n        //Add term3\n        V1 = B*E_micro_voigt + D*E_voigt;\n        deformation_measures::undo_voigt_3x3_tensor(V1,T1);\n        deformation_measures::two_sot_to_fot(2,T1,RCGinv,T2);\n        terms[1] += T2;\n        \n        dPK2dPsi = terms[0] + terms[1];\n        \n        return;\n    }\n    \n    void compute_dPK2dPsi(const Matrix_3x3 &RCGinv, const Matrix_3x3 &E_micro, const Vector_9 &E_voigt, const Vector_9 &E_micro_voigt,\n                          const Matrix_9x9 &B,      const Matrix_9x9 &D,       Matrix_9x9 (&terms)[2],  Matrix_9x9 &dPK2dPsi){\n        /*!==========================\n        |    compute_dPK2dPsi    |\n        ==========================\n        \n        Compute the derivative of the second piola kirchoff \n        stress w.r.t. the deformation measure Psi.\n        \n        */\n        \n        //Initialize temporary terms\n        Vector_9   V1;\n        Vector_27  V2;\n        Matrix_3x3 T1;\n        Matrix_9x9 T2;\n        Matrix_3x9 T3;\n        \n        //Add term1\n        terms[0] = D;\n        \n        //Add term2\n        deformation_measures::dot_2ot_4ot(1, 1, RCGinv*(E_micro + Matrix_3x3::Identity()), B, T2);\n        terms[1] = T2;\n        \n        //Add term3\n        V1 = B*E_micro_voigt + D*E_voigt;\n        deformation_measures::undo_voigt_3x3_tensor(V1,T1);\n        deformation_measures::two_sot_to_fot(2,T1,RCGinv,T2);\n        terms[1] += T2;\n        \n        dPK2dPsi = terms[0] + terms[1];\n        \n        return;\n    }\n\n    void compute_dPK2dGamma_term2(const Vector_27 &term1, const Matrix_27x27 &C, Matrix_9x27 &term2){\n        /*!==================================\n        |    compute_dPK2dGamma_term2    |\n        ==================================\n        \n        Compute term2 of dPK2dGamma. Note that this is identical as \n        term2 for dSIGMAdGamma if symmetrized.\n        \n        */\n\n        term2 = Matrix_9x27::Zero();\n\n        int sot_to_voigt_map[3][3] = {{0,5,4},\n                                      {8,1,3},\n                                      {7,6,2}};\n        \n        int tot_to_voigt_map[3][3][3];\n        deformation_measures::get_tot_to_voigt_map(tot_to_voigt_map);\n\n        int Ihat;\n        int Jhat;\n        int Khat;\n        int Lhat;\n\n        double tmp;\n\n        for (int i=0; i<3; i++){\n            for (int j=0; j<3; j++){\n                Ihat = sot_to_voigt_map[i][j];\n                for (int t=0; t<3; t++){\n                    for (int u=0; u<3; u++){\n                        for (int v=0; v<3; v++){\n                            Jhat = tot_to_voigt_map[t][u][v];\n                            tmp = 0;\n\n                            for (int q=0; q<3; q++){\n                                for (int r=0; r<3; r++){\n                                    Khat = tot_to_voigt_map[i][q][r];\n                                    Lhat = tot_to_voigt_map[j][q][r];\n                                    tmp += C(Khat,Jhat)*term1(Lhat);\n                                }\n                            }\n                            term2(Ihat,Jhat) = tmp;\n                        }\n                    }\n                }\n            }\n        }\n        return;\n    }\n    \n    void compute_dPK2dGamma_term3(const Vector_27 &term1, const Matrix_3x3 &RCGinv, Matrix_9x27 &term3){\n        /*!==================================\n        |    compute_dPK2dGamma_term3    |\n        ==================================\n        \n        Compute term3 of dPK2dGamma. Note, also the same as dSIGMAdGamma if symmetrized.\n        \n        */\n        \n        int sot_to_voigt_map[3][3] = {{0,5,4},\n                                      {8,1,3},\n                                      {7,6,2}};\n        \n        int tot_to_voigt_map[3][3][3];\n        deformation_measures::get_tot_to_voigt_map(tot_to_voigt_map);\n\n        int Ihat;\n        int Jhat;\n        int Khat;\n        //int Lhat;\n\n        double tmp1;\n        \n        for (int i=0; i<3; i++){\n            for (int j=0; j<3; j++){\n                Ihat = sot_to_voigt_map[i][j];\n                for (int t=0; t<3; t++){\n                    tmp1 = RCGinv(j,t);\n                    for (int u=0; u<3; u++){\n                        for (int v=0; v<3; v++){\n                            Jhat = tot_to_voigt_map[t][u][v];\n                            Khat = tot_to_voigt_map[i][u][v];\n                            term3(Ihat,Jhat) = term1(Khat)*tmp1;\n                        }\n                    }\n                }\n            }\n        }\n        return;\n    }\n    \n    void compute_dPK2dGamma(const Matrix_3x3 &RCGinv, const Matrix_3x9 &Gamma, const Vector_27 &Gamma_voigt,\n                            SpMat &C, Matrix_9x27 &dPK2dGamma){\n        /*!============================\n        |    compute_dPK2dGamma    |\n        ============================\n        \n        Compute the derivative of the second piola kirchoff stress \n        w.r.t. the deformation measure Gamma.\n        \n        */\n        \n        //Compute term1\n        Vector_27 term1;\n        deformation_measures::voigt_3x9_tensor(RCGinv*Gamma,term1);\n        \n        //Compute term2\n        Matrix_9x27 term2;\n        Matrix_27x27 _C = C; //Copy the sparse matrix to a dense matrix.\n        compute_dPK2dGamma_term2(term1,_C,term2);\n        \n        //Compute term3\n        Matrix_9x27 term3;\n        compute_dPK2dGamma_term3(C*Gamma_voigt,RCGinv,term3);\n        \n        dPK2dGamma = term2 + term3;\n    }\n    \n    void compute_dPK2dGamma(const Matrix_3x3 &RCGinv, const Matrix_3x9 &Gamma, const Vector_27 &Gamma_voigt,\n                            Matrix_27x27 &C, Matrix_9x27 &dPK2dGamma){\n        /*!============================\n        |    compute_dPK2dGamma    |\n        ============================\n        \n        Compute the derivative of the second piola kirchoff stress \n        w.r.t. the deformation measure Gamma.\n        \n        */\n        \n        //Compute term1\n        Vector_27 term1;\n        deformation_measures::voigt_3x9_tensor(RCGinv*Gamma,term1);\n        \n        //Compute term2\n        Matrix_9x27 term2;\n        compute_dPK2dGamma_term2(term1, C,term2);\n        \n        //Compute term3\n        Matrix_9x27 term3;\n        compute_dPK2dGamma_term3(C*Gamma_voigt,RCGinv,term3);\n        \n        dPK2dGamma = term2 + term3;\n    }\n\n    void compute_dPK2dGamma(const Matrix_3x3 &RCGinv, const Matrix_3x9 &Gamma, const Vector_27 &Gamma_voigt,\n                            SpMat &C, Matrix_9x27 (&terms)[2], Matrix_9x27 &dPK2dGamma){\n        /*!============================\n        |    compute_dPK2dGamma    |\n        ============================\n        \n        Compute the derivative of the second piola kirchoff stress \n        w.r.t. the deformation measure Gamma.\n        \n        */\n        \n        //Compute term1\n        Vector_27 term1;\n        deformation_measures::voigt_3x9_tensor(RCGinv*Gamma,term1);\n        \n        //Compute term2\n        Matrix_27x27 _C = C; //Copy the sparse matrix to a dense matrix.\n        compute_dPK2dGamma_term2(term1,_C,terms[0]);\n        \n        //Compute term3\n        compute_dPK2dGamma_term3(C*Gamma_voigt,RCGinv,terms[1]);\n        \n        dPK2dGamma = terms[0] + terms[1];\n    }\n    \n    void compute_dPK2dGamma(const Matrix_3x3 &RCGinv, const Matrix_3x9 &Gamma, const Vector_27 &Gamma_voigt,\n                            Matrix_27x27 &C, Matrix_9x27 (&terms)[2], Matrix_9x27 &dPK2dGamma){\n        /*!============================\n        |    compute_dPK2dGamma    |\n        ============================\n        \n        Compute the derivative of the second piola kirchoff stress \n        w.r.t. the deformation measure Gamma.\n        \n        */\n        \n        //Compute term1\n        Vector_27 term1;\n        deformation_measures::voigt_3x9_tensor(RCGinv*Gamma,term1);\n        \n        //Compute term2\n        compute_dPK2dGamma_term2(term1,C,terms[0]);\n        \n        //Compute term3\n        compute_dPK2dGamma_term3(C*Gamma_voigt,RCGinv,terms[1]);\n        \n        dPK2dGamma = terms[0] + terms[1];\n    }\n\n    void compute_dSIGMAdRCG(Matrix_9x9 (&terms)[2], Matrix_9x9 &dSIGMAdRCG){\n        /*!=========================\n        |    compute_dSIGMAdRCG    |\n        ============================\n        \n        Compute the derivative of the symmetric stress in the \n        reference configuration using the terms from the \n        computation of dPK2dRCG.\n        \n        This is the preferred method since the computation has \n        already been done for the PK2 derivative.\n        \n        */\n        \n        dSIGMAdRCG = terms[0];\n        \n        dSIGMAdRCG        += terms[1];\n        dSIGMAdRCG.row(0) += terms[1].row(0);\n        dSIGMAdRCG.row(1) += terms[1].row(1);\n        dSIGMAdRCG.row(2) += terms[1].row(2);\n        \n        dSIGMAdRCG.row(3) += terms[1].row(6);\n        dSIGMAdRCG.row(4) += terms[1].row(7);\n        dSIGMAdRCG.row(5) += terms[1].row(8);\n        dSIGMAdRCG.row(6) += terms[1].row(3);\n        dSIGMAdRCG.row(7) += terms[1].row(4);\n        dSIGMAdRCG.row(8) += terms[1].row(5);\n \n//        for (int i=1; i<4; i++){\n//            temp = terms[i];\n//            \n//            temp.row(0) *= 2;\n//            temp.row(1) *= 2;\n//            temp.row(2) *= 2;\n//            temp.row(3) += terms[i].row(6);\n//            temp.row(4) += terms[i].row(7);\n//            temp.row(5) += terms[i].row(8);\n//            temp.row(6) += terms[i].row(3);\n//            temp.row(7) += terms[i].row(4);\n//            temp.row(8) += terms[i].row(5);\n//            \n//            dSIGMAdRCG += temp;\n//        }\n        return;\n    }\n    \n    void compute_dSIGMAdPsi(Matrix_9x9 (&terms)[2], Matrix_9x9 &dSIGMAdPsi){\n        /*!============================\n        |    compute_dSIGMAdPsi    |\n        ============================\n        \n        Compute the derivative of the symmetric stress in the \n        reference configuration using the terms from the \n        computation of dPK2dPsi.\n        \n        This is the preferred method since the computation has already \n        been done for the PK2 derivative.\n        \n        */\n        \n        dSIGMAdPsi = terms[0]+terms[1];\n        \n        dSIGMAdPsi.row(0) += terms[1].row(0);\n        dSIGMAdPsi.row(1) += terms[1].row(1);\n        dSIGMAdPsi.row(2) += terms[1].row(2);\n        \n        dSIGMAdPsi.row(3) += terms[1].row(6);\n        dSIGMAdPsi.row(4) += terms[1].row(7);\n        dSIGMAdPsi.row(5) += terms[1].row(8);\n        dSIGMAdPsi.row(6) += terms[1].row(3);\n        dSIGMAdPsi.row(7) += terms[1].row(4);\n        dSIGMAdPsi.row(8) += terms[1].row(5);\n        \n//        for (int i=1; i<3; i++){\n//            temp = terms[i];\n//            \n//            temp.row(0) *= 2;\n//            temp.row(1) *= 2;\n//            temp.row(2) *= 2;\n//            \n//            temp.row(3) += terms[i].row(6);\n//            temp.row(4) += terms[i].row(7);\n//            temp.row(5) += terms[i].row(8);\n//            temp.row(6) += terms[i].row(3);\n//            temp.row(7) += terms[i].row(4);\n//            temp.row(8) += terms[i].row(5);\n//            \n//            dSIGMAdPsi += temp;\n//        }\n        return;\n    }\n    \n    void compute_dSIGMAdGamma(Matrix_9x27 (&terms)[2], Matrix_9x27 &dSIGMAdGamma){\n        /*!===========================\n        |    compute_dSIGMAdGamma    |\n        ==============================\n        \n        Compute the derivative of the symmetric stress in the \n        reference configuration using the terms from the computation \n        of dPK2dGamma.\n        \n        This is the preferred method since the computation has already\n        been done for the PK2 derivative.\n        \n        */\n        \n        dSIGMAdGamma = Matrix_9x27::Zero();\n        \n        Matrix_9x27 temp;\n        \n        for (int i=0; i<2; i++){\n            temp = terms[i];\n            \n            temp.row(0) *= 2.;\n            temp.row(1) *= 2.;\n            temp.row(2) *= 2.;\n            temp.row(3) += terms[i].row(6);\n            temp.row(4) += terms[i].row(7);\n            temp.row(5) += terms[i].row(8);\n            temp.row(6) += terms[i].row(3);\n            temp.row(7) += terms[i].row(4);\n            temp.row(8) += terms[i].row(5);\n            \n            dSIGMAdGamma += temp;\n        }\n        return;\n    }\n    \n    void compute_dMdGamma(const Matrix_27x27 &C, Matrix_27x27 &dMdGamma){\n        /*!==========================\n        |    compute_dMdGamma    |\n        ==========================\n        \n        Compute the derivative of the higher order stress tensor w.r.t. Gamma.\n        \n        */\n\n        int tot_to_voigt_map[3][3][3];\n        deformation_measures::get_tot_to_voigt_map(tot_to_voigt_map);\n\n        int Ihat;\n        int Jhat;\n        int Khat;\n\n        for (int i=0; i<3; i++){\n            for (int j=0; j<3; j++){\n                for (int k=0; k<3; k++){\n                    Ihat = tot_to_voigt_map[i][j][k];\n                    Khat = tot_to_voigt_map[j][k][i];\n                    for (int l=0; l<3; l++){\n                        for (int m=0; m<3; m++){\n                            for (int n=0; n<3; n++){\n                                Jhat = tot_to_voigt_map[l][m][n];\n                                dMdGamma(Ihat,Jhat) = C(Khat,Jhat);\n                            }\n                        }\n                    }\n                }\n            }\n        }\n        return;\n    }\n}\n", "meta": {"hexsha": "603d486a6ff94e9b1480dfe2db40c78c1edebe4a", "size": 74360, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cpp/micromorphic_linear_elasticity_voigt.cpp", "max_stars_repo_name": "lanl/tardigrade-micromorphic-element", "max_stars_repo_head_hexsha": "dafc66df8a308e9fef8af4907de902464b84302b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cpp/micromorphic_linear_elasticity_voigt.cpp", "max_issues_repo_name": "lanl/tardigrade-micromorphic-element", "max_issues_repo_head_hexsha": "dafc66df8a308e9fef8af4907de902464b84302b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/micromorphic_linear_elasticity_voigt.cpp", "max_forks_repo_name": "lanl/tardigrade-micromorphic-element", "max_forks_repo_head_hexsha": "dafc66df8a308e9fef8af4907de902464b84302b", "max_forks_repo_licenses": ["BSD-3-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.4687015003, "max_line_length": 168, "alphanum_fraction": 0.5103819258, "num_tokens": 22273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357701094304, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.48074572658989806}}
{"text": "#include \"../include/cte_bits/hamiltonian.hpp\"\n#include \"../include/cte_bits/random.hpp\"\n#include <algorithm>\n#include <boost/math/tools/roots.hpp>\n#include <cmath>\n#include <cstdlib>\n#include <ibs>\n#include <iostream>\n#include <map>\n#include <math.h>\n#include <string>\n\nnamespace cte_distributions {\nstd::vector<double> BiGaussian4D(const double betax, const double ex,\n                                 const double betay, const double ey,\n                                 int seed) {\n  std::vector<double> out;\n\n  // std::printf(\"%-30s %12.6e \\n\", \"betx\", betax);\n  // std::printf(\"%-30s %12.6e \\n\", \"bety\", betay);\n  // std::printf(\"%-30s %12.6e \\n\", \"ex\", ex);\n  // std::printf(\"%-30s %12.6e \\n\", \"ey\", ey);\n  static double ampx, ampy, amp, r1, r2, facc;\n  static double x, px, y, py;\n\n  // 1 sigma rms beam sizes using average ring betas\n  ampx = sqrt(betax * ex);\n  ampy = sqrt(betay * ey);\n\n  // generate bi-gaussian distribution in the x-px phase-space\n  do {\n    r1 = 2 * cte_random::ran3(&seed) - 1;\n    r2 = 2 * cte_random::ran3(&seed) - 1;\n    amp = r1 * r1 + r2 * r2;\n  } while (amp >= 1);\n\n  facc =\n      sqrt(-2 * log(amp) /\n           amp); // transforming [-1,1] uniform to gaussian - inverse transform\n\n  x = ampx * r1 * facc;  // scaling the gaussian\n  px = ampx * r2 * facc; // scaling the gaussian\n\n  // generate bi-gaussian distribution in the y-py phase-space\n  do {\n    r1 = 2 * cte_random::ran3(&seed) - 1;\n    r2 = 2 * cte_random::ran3(&seed) - 1;\n    amp = r1 * r1 + r2 * r2;\n  } while (amp >= 1);\n\n  facc =\n      sqrt(-2 * log(amp) /\n           amp); // transforming [-1,1] uniform to gaussian - inverse transform\n\n  y = ampy * r1 * facc;  // scaling the gaussian\n  py = ampy * r2 * facc; // scaling the gaussian\n\n  // std::printf(\"%12.6e %12.6e %12.6e %12.6e\\n\", x, px, y, py);\n  out.push_back(x);\n  out.push_back(px);\n  out.push_back(y);\n  out.push_back(py);\n\n  return out;\n}\n\nstd::vector<double>\nBiGaussian6DLongMatched(double betax, double ex, double betay, double ey,\n                        std::vector<double> &h, std::vector<double> &v,\n                        std::map<std::string, double> &twheader,\n                        std::map<std::string, double> &longparam, int seed) {\n\n  double h0 = h[0];\n  double tauhat = twheader[\"tauhat\"];\n  double omega = twheader[\"omega\"];\n  double ampt = longparam[\"sigs\"] / clight;\n  // Max value Hamiltonian that is stable\n  // is, with the sign convention used, left of the ham contour\n  // at 180-phis (The Ham rises lin to the right.)\n  double hom = (h0 * omega);\n  double ts = longparam[\"phis\"] / hom;\n  int npi = int(longparam[\"phis\"] / (2.0 * pi));\n  double tperiod = 2.0 * pi / hom;\n  double ts2 = longparam[\"phisNext\"] / hom + double(npi) * tperiod;\n  double delta = longparam[\"sige\"];\n\n  std::vector<double> out;\n  out = BiGaussian4D(betax, ex, betay, ey, seed);\n\n  // adding two zeros\n  out.push_back(0.0);\n  out.push_back(0.0);\n\n  double r1, r2, amp, facc, tc, pc, ham, hammin;\n  tc = (omega * twheader[\"eta\"] * h0);\n  pc = (omega * twheader[\"CHARGE\"]) /\n       (2.0 * pi * twheader[\"PC\"] * 1.0e9 * twheader[\"betar\"]);\n\n  // std::printf(\"%-20s %16.8e\\n\", \"tc\", tc);\n  // std::printf(\"%-20s %16.8e\\n\", \"pc\", pc);\n  // max Hamiltonian\n  double hammax =\n      cte_hamiltonian::Hamiltonian(twheader, longparam, h, v, tc, ts, 0.0);\n  /*\n  std::printf(\"%-20s %16.8e\\n\", \"hammax\", hammax);\n  std::printf(\"%-20s %16.8e\\n\", \"ts\", ts);\n  std::printf(\"%-20s %16.8e\\n\", \"ts2\", ts2);\n  */\n  // select valid t values\n  do {\n    // looper++;\n    // std::printf(\"%i\\n\", looper);\n    r1 = 2 * cte_random::ran3(&seed) - 1;\n    r2 = 2 * cte_random::ran3(&seed) - 1;\n    amp = r1 * r1 + r2 * r2;\n    if (amp >= 1)\n      continue;\n\n    facc = sqrt(-2 * log(amp) / amp);\n    // std::printf(\"%-20s %16.8e\\n\", \"out4\", out[4]);\n    out[4] = ts2 + ampt * r1 * facc;\n    /*\n        std::printf(\"%-20s %16.8e\\n\", \"ts\", ts);\n        std::printf(\"%-20s %16.8e\\n\", \"ampt\", ampt);\n        std::printf(\"%-20s %16.8e\\n\", \"r1\", r1);\n        std::printf(\"%-20s %16.8e\\n\", \"facc\", facc);\n        std::printf(\"%-20s %16.8e\\n\", \"out4\", out[4]);\n        std::printf(\"%-20s %16.8e\\n\", \"out4-ts\", out[4] - ts);\n        std::printf(\"%-20s %16.8e\\n\", \"tauhat\", tauhat);\n    */\n    if (abs(out[4] - ts2) >= abs(ts - ts2))\n      continue;\n\n    // min Hamiltonian\n    hammin = cte_hamiltonian::Hamiltonian(twheader, longparam, h, v, tc, out[4],\n                                          0.0);\n    // std::printf(\"%-20s %16.8e\\n\", \"hammin\", hammin);\n    // std::printf(\"%-20s %16.8e\\n\", \"hammax\", hammax);\n\n  } while ((hammin > hammax) || (abs(out[4] - ts2) >= abs(ts - ts2)));\n\n  // select matched deltas\n  do {\n    // looper++;\n    // std::printf(\"%i\\n\", looper);\n    r1 = 2 * cte_random::ran3(&seed) - 1;\n    r2 = 2 * cte_random::ran3(&seed) - 1;\n    amp = r1 * r1 + r2 * r2;\n\n    if (amp >= 1)\n      continue;\n\n    facc = sqrt(-2 * log(amp) / amp);\n    out[5] = longparam[\"sige\"] * r2 * facc;\n    // std::printf(\"%-20s %16.8e\\n\", \"delta\", out[5]);\n\n    ham = cte_hamiltonian::Hamiltonian(twheader, longparam, h, v, tc, out[4],\n                                       out[5]);\n    // std::printf(\"%-20s %16.8e\\n\", \"hammin\", hammin);\n    // std::printf(\"%-20s %16.8e\\n\", \"ham\", ham);\n    // std::printf(\"%-20s %16.8e\\n\", \"hammax\", hammax);\n  } while ((ham < hammin) || (ham > hammax));\n\n  return out;\n}\n\nstd::vector<std::vector<double>> GenerateDistributionMatched(\n    int nMacro, double betax, double ex, double betay, double ey,\n    std::vector<double> &h, std::vector<double> &v,\n    std::map<std::string, double> &twheader,\n    std::map<std::string, double> &longparam, int seed) {\n  std::vector<std::vector<double>> out;\n\n  for (int i = 0; i < nMacro; i++) {\n    out.push_back(BiGaussian6DLongMatched(betax, ex, betay, ey, h, v, twheader,\n                                          longparam, seed));\n  }\n  return out;\n}\n\n} // namespace cte_distributions", "meta": {"hexsha": "af6dc39e2b6bbb792d810547d30ef7b3c9964c89", "size": 5897, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/src/distributions.cpp", "max_stars_repo_name": "tomerten/ctelib", "max_stars_repo_head_hexsha": "582c215667e240a65f07ac75468e0870bee88a4d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cpp/src/distributions.cpp", "max_issues_repo_name": "tomerten/ctelib", "max_issues_repo_head_hexsha": "582c215667e240a65f07ac75468e0870bee88a4d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp/src/distributions.cpp", "max_forks_repo_name": "tomerten/ctelib", "max_forks_repo_head_hexsha": "582c215667e240a65f07ac75468e0870bee88a4d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5801104972, "max_line_length": 80, "alphanum_fraction": 0.5545192471, "num_tokens": 2043, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357701094303, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.480745726589898}}
{"text": "//===-- parameter_tests - Parameter Unit Tests ---------------------------------===//\n//\n// Part of the SAM Project\n// Created by Amir Masoud Abdol on 14/01/2021\n//\n//===----------------------------------------------------------------------===//\n///\n/// @file\n/// This file contains some tests for Parameter<T>\n///\n//===----------------------------------------------------------------------===//\n\n#define BOOST_TEST_DYN_LINK\n\n#define BOOST_TEST_MODULE Parameter Tests\n\n#include \"nlohmann/json.hpp\"\n#include \"Parameter.h\"\n#include <boost/test/unit_test.hpp>\n#include <boost/mpl/list.hpp>\n#include <boost/utility/identity_type.hpp>\n\nusing namespace sam;\nusing json = nlohmann::ordered_json;\n\ntypedef boost::mpl::list<int, float, float> test_types;\ntypedef boost::mpl::list<float, float> dist_test_types;\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( parameter_type_test, T, test_types) {\n\n  Parameter<T> parameter{1};\n\n  BOOST_TEST(parameter.n_elem == 1);\n  BOOST_TEST(sizeof(parameter.at(0)) == sizeof(T));\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( scalar_parameter, T, test_types) {\n\n  Parameter<T> parameter{1};\n\n  T b = static_cast<T>(parameter);\n\n  // If the Parameter is not a distirbution, then, it'll not be randomized\n  BOOST_TEST(static_cast<T>(parameter()) == b);\n\n  json config = R\"(\n    {\n      \"param\": 1\n    }\n  )\"_json;\n  \n  Parameter<T> jparameter(config[\"param\"], 1);\n  BOOST_TEST(jparameter.at(0) == 1);\n\n  jparameter = {2};\n  BOOST_TEST(jparameter.at(0) == 2);\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( array_of_scalars_parameter, T, test_types) {\n\n  Parameter<T> parameter{1, 2, 3};\n\n  arma::Row<T> b = parameter;\n\n  // If the Parameter is not a distirbution, then, it'll not be randomized\n  BOOST_TEST(arma::approx_equal(parameter, b, \"absdiff\", 0.001));\n\n  json config = R\"(\n    {\n    \"param\": [1, 2, 3]\n    }\n  )\"_json;\n\n  Parameter<T> jparameter(config[\"param\"], 3);\n\n  arma::Row<T> a{1, 2, 3};\n  BOOST_TEST(arma::approx_equal(jparameter,\n                                a, \"absdiff\", 0.001));\n  \n  a = arma::Row<T>({4, 5, 6});\n  BOOST_TEST(!arma::approx_equal(jparameter,\n                                a, \"absdiff\", 0.001));\n\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( univariate_parameter, T, dist_test_types) {\n\n  json config = R\"(\n    {\n      \"param\": {\n        \"dist\": \"normal_distribution\",\n        \"mean\": 0,\n        \"stddev\": 1\n      }\n    }\n  )\"_json;\n\n  Parameter<T> parameter(config[\"param\"], 1);\n\n  BOOST_TEST(parameter.n_elem == 1);\n\n  T a = static_cast<T>(parameter());\n  T b = static_cast<T>(parameter());\n  BOOST_TEST(sizeof(a) == sizeof(b));\n  BOOST_TEST(a != b);\n}\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( multivariate_parameter, T, dist_test_types) {\n\n  json config = R\"(\n  {\n    \"param\": {\n      \"dist\": \"mvnorm_distribution\",\n      \"means\": [0, 0, 0, 0],\n      \"covs\": 0,\n      \"stddevs\": 1\n    }\n  }\n  )\"_json;\n\n  Parameter<T> parameter(config[\"param\"], 4);\n\n  BOOST_TEST(parameter.n_elem == 4);\n\n  arma::Row<T> a = parameter();\n  arma::Row<T> b = parameter();\n\n  BOOST_TEST(!arma::approx_equal(a, b, \"absdiff\", 0.001));\n}\n\n", "meta": {"hexsha": "fed08b27ace18c613fa79473bba469cbbf0da1c9", "size": 3025, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sam-project/bakker-et-al-2012/SAM/SAM/tests/src/parameter_tests.cpp", "max_stars_repo_name": "amirmasoudabdol/bakker-et-al-2012-reproduction-using-sam", "max_stars_repo_head_hexsha": "518ab1cebaa80c19a12e92db8ae87386512ae053", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-25T20:21:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T20:21:41.000Z", "max_issues_repo_path": "sam-project/bakker-et-al-2012/SAM/SAM/tests/src/parameter_tests.cpp", "max_issues_repo_name": "amirmasoudabdol/bakker-et-al-2012-reproduction-using-sam", "max_issues_repo_head_hexsha": "518ab1cebaa80c19a12e92db8ae87386512ae053", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sam-project/bakker-et-al-2012/SAM/SAM/tests/src/parameter_tests.cpp", "max_forks_repo_name": "amirmasoudabdol/bakker-et-al-2012-reproduction-using-sam", "max_forks_repo_head_hexsha": "518ab1cebaa80c19a12e92db8ae87386512ae053", "max_forks_repo_licenses": ["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.7443609023, "max_line_length": 85, "alphanum_fraction": 0.5930578512, "num_tokens": 817, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6442251201477016, "lm_q2_score": 0.7461390043208003, "lm_q1q2_score": 0.480681489705454}}
{"text": "// Boost.Bimap\r\n//\r\n// Copyright (c) 2006-2007 Matias Capeletto\r\n//\r\n// Distributed under the Boost Software License, Version 1.0.\r\n// (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n\r\n// Boost.Bimap Example\r\n//-----------------------------------------------------------------------------\r\n// Hashed indices can be used as an alternative to ordered indices when fast\r\n// lookup is needed and sorting information is of no interest. The example\r\n// features a word counter where duplicate entries are checked by means of a \r\n// hashed index.\r\n\r\n#include <boost/config.hpp>\r\n\r\n//[ code_mi_to_b_path_hashed_indices\r\n\r\n#include <iostream>\r\n#include <iomanip>\r\n\r\n#include <boost/tokenizer.hpp>\r\n\r\n#include <boost/bimap/bimap.hpp>\r\n#include <boost/bimap/unordered_set_of.hpp>\r\n#include <boost/bimap/multiset_of.hpp>\r\n#include <boost/bimap/support/lambda.hpp>\r\n\r\nusing namespace boost::bimaps;\r\n\r\nstruct word        {};\r\nstruct occurrences {};\r\n\r\ntypedef bimap\r\n<\r\n    \r\n     multiset_of< tagged<unsigned int,occurrences>, std::greater<unsigned int> >, \r\nunordered_set_of< tagged< std::string,       word>                             >\r\n\r\n> word_counter;\r\n\r\ntypedef boost::tokenizer<boost::char_separator<char> > text_tokenizer;\r\n\r\nint main()\r\n{\r\n\r\n    std::string text=\r\n        \"Relations between data in the STL are represented with maps.\"\r\n        \"A map is a directed relation, by using it you are representing \"\r\n        \"a mapping. In this directed relation, the first type is related to \"\r\n        \"the second type but it is not true that the inverse relationship \"\r\n        \"holds. This is useful in a lot of situations, but there are some \"\r\n        \"relationships that are bidirectional by nature.\";\r\n\r\n    // feed the text into the container\r\n\r\n    word_counter   wc;\r\n    text_tokenizer tok(text,boost::char_separator<char>(\" \\t\\n.,;:!?'\\\"-\"));\r\n    unsigned int   total_occurrences = 0;\r\n\r\n    for( text_tokenizer::const_iterator it = tok.begin(), it_end = tok.end();\r\n         it != it_end ; ++it )\r\n    {\r\n        ++total_occurrences;\r\n\r\n        word_counter::map_by<occurrences>::iterator wit =\r\n            wc.by<occurrences>().insert(\r\n                 word_counter::map_by<occurrences>::value_type(0,*it)\r\n            ).first;\r\n\r\n        wc.by<occurrences>().modify_key( wit, ++_key);\r\n    }\r\n\r\n    // list words by frequency of appearance\r\n\r\n    std::cout << std::fixed << std::setprecision(2);\r\n\r\n    for( word_counter::map_by<occurrences>::const_iterator\r\n            wit     = wc.by<occurrences>().begin(),\r\n            wit_end = wc.by<occurrences>().end();\r\n\r\n         wit != wit_end; ++wit )\r\n    {\r\n        std::cout << std::setw(15) << wit->get<word>() << \": \"\r\n                  << std::setw(5)\r\n                  << 100.0 * wit->get<occurrences>() / total_occurrences << \"%\"\r\n                  << std::endl;\r\n    }\r\n\r\n    return 0;\r\n}\r\n//]\r\n", "meta": {"hexsha": "1353f08f993e62878458ac7d25b14b033bd00dbd", "size": 2910, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/bimap/example/mi_to_b_path/hashed_indices.cpp", "max_stars_repo_name": "zyiacas/boost-doc-zh", "max_stars_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 198.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T05:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:46:46.000Z", "max_issues_repo_path": "libs/bimap/example/mi_to_b_path/hashed_indices.cpp", "max_issues_repo_name": "sdfict/boost-doc-zh", "max_issues_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/bimap/example/mi_to_b_path/hashed_indices.cpp", "max_forks_repo_name": "sdfict/boost-doc-zh", "max_forks_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 30.6315789474, "max_line_length": 83, "alphanum_fraction": 0.5975945017, "num_tokens": 664, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251201477016, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.48068148606878736}}
{"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  \n  // algorithm 2 of Neal \n  // http://www.stat.columbia.edu/npbayes/papers/neal_sampling.pdf\ntemplate<typename T>\nclass CrpMM : public DpMM<T>\n{\npublic:\n  CrpMM(const T alpha, const shared_ptr<BaseMeasure<T> >& theta, uint32_t K0,\n      boost::mt19937* pRndGen);\n  virtual ~CrpMM()\n  {};\n\n  virtual void initialize(const shared_ptr<Matrix<T,Dynamic,Dynamic> >& spx);\n  virtual void initialize(const Matrix<T,Dynamic,Dynamic>& x)\n  {this->spx_=shared_ptr<Matrix<T,Dynamic,Dynamic> >(new\n      Matrix<T,Dynamic,Dynamic>(x)); initialize(this->spx_);};\n  virtual void sampleLabels();\n  virtual void sampleParameters();\n  virtual void proposeSplits() {};\n  virtual void proposeMerges() {};\n  // call this right before sampleParameters()\n  virtual void resampleFromBase(uint32_t Kmax) {};\n  virtual const VectorXu & getLabels(){return z_;};\n  virtual const VectorXu & labels(){return z_;};\n  virtual Matrix<T,Dynamic,1> getCounts();\n  virtual uint32_t getK() const { return K_;};\n  virtual double logJoint(); \n\n//  virtual MatrixXu mostLikelyInds(uint32_t n) \n//{ return MatrixXu::Zero(n,1);};\n  virtual MatrixXu mostLikelyInds(uint32_t n, Matrix<T,Dynamic,Dynamic>& logLikes)\n  { return MatrixXu::Zero(n,1);};\n\nprivate:\n  void removeEmptyClusters();\n\n  uint32_t K_;\n  T alpha_; // dp concentration paramter\n\n  shared_ptr<BaseMeasure<T> > theta0_;\n  vector<shared_ptr<BaseMeasure<T> > > thetas_;\n\n  VectorXu z_;\n\n  boost::mt19937* pRndGen_;\n};\n\n// ------------------------- impl -----------------------------------\ntemplate<typename T>\nCrpMM<T>::CrpMM(const T alpha, const shared_ptr<BaseMeasure<T> >& theta,\n    uint32_t K0,  boost::mt19937* pRndGen)\n  : K_(K0), alpha_(alpha), theta0_(theta), pRndGen_(pRndGen)\n{};\n\ntemplate <typename T>\nMatrix<T,Dynamic,1> CrpMM<T>::getCounts()\n{\n  return counts<T,uint32_t>(z_,K_);\n};\n\ntemplate<typename T>\nvoid CrpMM<T>::initialize(const shared_ptr<Matrix<T,Dynamic,Dynamic> >& spx)\n{\n  cout<<\"init\"<<endl;\n  this->spx_ = spx;\n  // randomly init labels from prior\n  z_.setZero(spx->cols());\n\n  Matrix<T,Dynamic,1> alpha = (alpha_/K_)*Matrix<T,Dynamic,1>::Ones(K_); \n  Cat<T> pi = Dir<Cat<T>,T>(alpha,pRndGen_).sample(); \n  for(uint32_t i=0; i<z_.size(); ++i)\n  {\n    z_(i) = pi.sample();\n  }\n\n  cout<<\"init counts \"<<this->getCounts().transpose()<<endl;\n\n  // init the parameters\n  if(thetas_.size() == 0)\n  {\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};\n\ntemplate<typename T>\nvoid CrpMM<T>::sampleLabels()\n{\n  Matrix<T,Dynamic,1> Nk(K_+1);\n  Nk.topRows(K_) = counts<T,uint32_t>(z_,K_);\n  Nk(K_) = alpha_;\n//  cout<<\"Nk=\"<<Nk.transpose()<<\" alpha=\"<<alpha_<<endl;\n  for(uint32_t i=0; i<z_.size(); ++i)\n  {\n    Nk(z_(i)) --; // take the data-point out of that cluster\n    Matrix<T,Dynamic,1> pdf = Nk.array().log().matrix();\n    pdf = pdf.array() - log(Nk.sum());\n//    cout<<pdf.transpose()<< \" -> \";\n    // add the log posteriors of the individual clusters\n    for(uint32_t k=0; k<K_; ++k)\n      pdf(k) += thetas_[k]->logLikelihood(this->spx_->col(i)); \n    // add the log likelihood of data under the hyperparameters\n    pdf(K_) += theta0_->logPdfUnderPriorMarginalized(this->spx_->col(i));\n//    cout<<pdf.transpose()<<\" exp: \";\n    // normalize and exponentiate pdf\n    pdf = (pdf.array() - logSumExp(pdf)).exp().matrix();\n//    cout<<pdf.transpose()<<endl;\n    z_(i) = Catd(pdf,pRndGen_).sample();\n    Nk(z_(i)) ++; // add data-point into new cluster\n\n    // add a new cluster from the base measure\n    if(z_(i)==K_)\n    {\n      thetas_.push_back(shared_ptr<BaseMeasure<T> >(theta0_->copy()));\n      // TODO might want to add z_i to the SS of the new cluster?\n      thetas_[z_(i)]->posterior(*this->spx_,z_,K_); // TODO slow\n      ++K_; \n      Nk.conservativeResize(K_+1);\n      Nk(z_(i)) -= alpha_;\n      Nk(K_) = alpha_;\n    }\n    if(z_.size()>10000 && i %(z_.size()/100) == 0) cout<<\" CrpMM<T>::sampleLabel: \"<<(i/(z_.size()/100))<<\"% done\"<<endl;\n  }\n  this->removeEmptyClusters();\n};\n\ntemplate<typename T>\nvoid CrpMM<T>::sampleParameters()\n{\n//#pragma omp parallel for \n  for(uint32_t k=0; k<K_; ++k)\n  {\n    thetas_[k]->posterior(*this->spx_,z_,k);\n    cout<<\"k:\"<<k<<\" \";\n    thetas_[k]->print();\n  }\n};\n\ntemplate <typename T>\nvoid CrpMM<T>::removeEmptyClusters()\n{\n//  cout<<\"K=\"<<K_<<\" z=\"<<z_.transpose()<<endl;\n  std::vector<bool> toDelete(K_,true);\n//#pragma omp parallel for \n  for(uint32_t k=0; k<K_; ++k) \n  {\n    toDelete[k] = true;\n    for(uint32_t i=0; i<z_.size(); ++i)\n      toDelete[k] = toDelete[k] && (z_(i)!=k);\n  }\n\n  std::vector<uint32_t> labelMap(K_,0);\n  {\n    uint32_t k=0;\n    for(k=0; k<K_; ++k) if(!toDelete[k]) break;\n    for(k=k+1; k<K_; ++k)\n      if(toDelete[k]) \n        labelMap[k] = labelMap[k-1];\n      else\n        labelMap[k] = labelMap[k-1]+1;\n//    for(k=0; k<K_; ++k) cout<<toDelete[k]<<\" \"; cout<<endl;\n//    for(k=0; k<K_; ++k) cout<<labelMap[k]<<\" \"; cout<<endl;\n  }\n#pragma omp parallel for\n  for(uint32_t i=0; i<z_.size(); ++i)\n    z_(i) = labelMap[z_(i)];\n//  cout<<z_.transpose()<<endl;\n\n  for(int32_t k=K_-1; k>=0; --k)\n    if (toDelete[k])\n      thetas_.erase(thetas_.begin()+k);\n  K_ = labelMap[K_-1]+1;\n}\n\ntemplate <typename T>\ndouble CrpMM<T>::logJoint() \n{\n  double logP = 0.;\n  for (uint32_t i=0; i<z_.size(); ++i)\n  {\n    logP += thetas_[z_(i)]->logLikelihood(this->spx_->col(i)); \n  }\n  return logP;\n}\n", "meta": {"hexsha": "082cb2322425fb5bab6d6a429458861d88721110", "size": 5905, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/dpMM/crpMM.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/crpMM.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/crpMM.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": 28.3894230769, "max_line_length": 121, "alphanum_fraction": 0.6259102456, "num_tokens": 1872, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.4806814824321208}}
{"text": "#include <iostream>\n#include <thread> \n#include <chrono>\n#include <vector>\n#include <Eigen/Dense>\n\nint main(){\n    auto t1 = std::chrono::high_resolution_clock::now();\n\n    int mat_size = 5;\n    Eigen::MatrixXd kern_mat = Eigen::MatrixXd::Zero(mat_size, mat_size);\n    Eigen::VectorXd vec_curr(5);\n\n    #pragma omp parallel for\n    for (int i = 0; i < mat_size; i ++){\n        std::this_thread::sleep_for(std::chrono::seconds(1));\n        vec_curr << i, i+1, i+2, i+3, i+4;\n        kern_mat.col(i) = vec_curr;\n    }\n\n    auto t2 = std::chrono::high_resolution_clock::now();\n    auto tot_time = \n        std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1).count();\n    std::cout << tot_time << std::endl;\n    std::cout << kern_mat << std::endl;\n\n}\n", "meta": {"hexsha": "e076a10231bec1c70400a014d14d2fc45f124da1", "size": 756, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "parallel_tests/par_test.cpp", "max_stars_repo_name": "stevetorr/flare_pp", "max_stars_repo_head_hexsha": "5767bb0787dc38516b582e5134dfd39e6694e8ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2021-03-12T02:53:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T18:59:38.000Z", "max_issues_repo_path": "parallel_tests/par_test.cpp", "max_issues_repo_name": "stevetorr/flare_pp", "max_issues_repo_head_hexsha": "5767bb0787dc38516b582e5134dfd39e6694e8ae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2021-04-27T22:52:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-25T08:07:41.000Z", "max_forks_repo_path": "parallel_tests/par_test.cpp", "max_forks_repo_name": "stevetorr/flare_pp", "max_forks_repo_head_hexsha": "5767bb0787dc38516b582e5134dfd39e6694e8ae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-28T14:29:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-28T14:29:57.000Z", "avg_line_length": 27.0, "max_line_length": 77, "alphanum_fraction": 0.6177248677, "num_tokens": 216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.6442251201477015, "lm_q1q2_score": 0.4806814824321206}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2013 Kyle Lutz <kyle.r.lutz@gmail.com>\n//\n// Distributed under the Boost Software License, Version 1.0\n// See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt\n//\n// See http://kylelutz.github.com/compute for more information.\n//---------------------------------------------------------------------------//\n\n#define BOOST_TEST_MODULE TestIota\n#include <boost/test/unit_test.hpp>\n\n#include <boost/compute/system.hpp>\n#include <boost/compute/context.hpp>\n#include <boost/compute/algorithm/iota.hpp>\n#include <boost/compute/container/vector.hpp>\n#include <boost/compute/iterator/permutation_iterator.hpp>\n\n#include \"check_macros.hpp\"\n#include \"context_setup.hpp\"\n\nnamespace bc = boost::compute;\n\nBOOST_AUTO_TEST_CASE(iota_int)\n{\n    bc::vector<int> vector(4);\n    bc::iota(vector.begin(), vector.end(), 0);\n    CHECK_RANGE_EQUAL(int, 4, vector, (0, 1, 2, 3));\n\n    bc::iota(vector.begin(), vector.end(), 10);\n    CHECK_RANGE_EQUAL(int, 4, vector, (10, 11, 12, 13));\n\n    bc::iota(vector.begin() + 2, vector.end(), -5);\n    CHECK_RANGE_EQUAL(int, 4, vector, (10, 11, -5, -4));\n\n    bc::iota(vector.begin(), vector.end() - 2, 4);\n    CHECK_RANGE_EQUAL(int, 4, vector, (4, 5, -5, -4));\n}\n\nBOOST_AUTO_TEST_CASE(iota_doctest)\n{\n    boost::compute::vector<int> vec(3, context);\n\n//! [iota]\nboost::compute::iota(vec.begin(), vec.end(), 0, queue);\n//! [iota]\n\n    CHECK_RANGE_EQUAL(int, 3, vec, (0, 1, 2));\n}\n\nBOOST_AUTO_TEST_CASE(iota_permutation_iterator)\n{\n    bc::vector<int> output(5);\n    bc::fill(output.begin(), output.end(), 0);\n\n    int map_data[] = { 2, 0, 1, 4, 3 };\n    bc::vector<int> map(map_data, map_data + 5);\n\n    bc::iota(bc::make_permutation_iterator(output.begin(), map.begin()),\n             bc::make_permutation_iterator(output.end(), map.end()),\n             1);\n    CHECK_RANGE_EQUAL(int, 5, output, (2, 3, 1, 5, 4));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "6dbde32bb9a06f8230f86227f2336fc5d773c4d7", "size": 1996, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_iota.cpp", "max_stars_repo_name": "bastiankoe/compute", "max_stars_repo_head_hexsha": "57eec36d20e122a496d3fbfddf8bf4ad8d6f4a4f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-03-18T01:14:13.000Z", "max_stars_repo_stars_event_max_datetime": "2015-03-18T01:14:13.000Z", "max_issues_repo_path": "test/test_iota.cpp", "max_issues_repo_name": "bastiankoe/compute", "max_issues_repo_head_hexsha": "57eec36d20e122a496d3fbfddf8bf4ad8d6f4a4f", "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/test_iota.cpp", "max_forks_repo_name": "bastiankoe/compute", "max_forks_repo_head_hexsha": "57eec36d20e122a496d3fbfddf8bf4ad8d6f4a4f", "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.7910447761, "max_line_length": 79, "alphanum_fraction": 0.6127254509, "num_tokens": 555, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251064863695, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.4806814686022015}}
{"text": "// Simple development tests\n\n#include \"craam/ImMDP.hpp\"\n#include \"craam/Simulation.hpp\"\n#include \"craam/Samples.hpp\"\n#include \"craam/algorithms/values.hpp\"\n\n#include \"rm/range.hpp\"\n\n#include <iostream>\n#include <iterator>\n#include <random>\n#include <cmath>\n#include <cassert>\n\n#include <boost/functional/hash.hpp>\n#include <iostream>\n#include <iterator>\n\n\nusing namespace std;\nusing namespace craam;\nusing namespace craam::impl;\nusing namespace util::lang;\n\ntemplate<class T>\nvoid print_vector(vector<T> vec){\n    for(auto&& p : vec){\n        cout << p << \" \";\n    }\n}\n\n/**\nA simple simulator class. The state represents a position in a chain\nand actions move it up and down. The reward is equal to the position.\n\nRepresentation\n~~~~~~~~~~~~~~\n- State: position (int)\n- Action: change (int)\n*/\nclass Counter{\nprivate:\n    default_random_engine gen;\n    bernoulli_distribution d;\n    const vector<int> actions_list;\n    const int initstate;\n\npublic:\n    using State = int;\n    using Action = int;\n\n    /**\n    Define the success of each action\n    \\param success The probability that the action is actually applied\n    */\n    Counter(double success, int initstate, random_device::result_type seed = random_device{}())\n        : gen(seed), d(success), actions_list({1,-1}), initstate(initstate) {};\n\n    int init_state() const {\n        return initstate;\n    }\n\n    pair<double,int> transition(int pos, int action) {\n        int nextpos = d(gen) ? pos + action : pos;\n        return make_pair((double) pos, nextpos);\n    }\n\n    bool end_condition(const int state){\n        return false;\n    }\n\n    int action(State state, long index) const{\n        return actions_list[index];\n    }\n\n    const vector<int>& get_valid_actions(int state) const{\n        return actions_list; \n    }\n\n    size_t action_count(State) const{return actions_list.size();};\n};\n\n\n/** A counter that terminates at either end as defined by the end state */\nclass CounterTerminal : public Counter {\npublic:\n    int endstate;\n\n    CounterTerminal(double success, int initstate, int endstate, random_device::result_type seed = random_device{}())\n        : Counter(success, initstate, seed), endstate(endstate) {};\n\n    bool end_condition(const int state){\n        return (abs(state) >= endstate);\n    }\n};\n// Hash function for the Counter / CounterTerminal EState above\nnamespace std{\n    template<> struct hash<pair<int,int>>{\n        size_t operator()(pair<int,int> const& s) const{\n            boost::hash<pair<int,int>> h;\n            return h(s);\n        };\n    };\n}\n\nusing namespace craam::msen;\n\nint main(void){\n\n    const int terminal_state = 8;\n    const prec_t discount = 0.9;\n\n    CounterTerminal sim(0.9,0,terminal_state,1);\n    RandomPolicy<CounterTerminal> random_pol(sim);\n\n    auto samples = make_samples<CounterTerminal>();\n    simulate(sim,samples,random_pol,100,100);\n    simulate(sim,samples,[](int){return 1;},10,20);\n    simulate(sim,samples,[](int){return -1;},10,20);\n\n    SampleDiscretizerSI<typename CounterTerminal::State, typename CounterTerminal::Action> sd;\n    // initialize action values\n    sd.add_action(-1); sd.add_action(+1);\n    //initialize state values\n    for(auto i : util::lang::range(-terminal_state,terminal_state)) sd.add_state(i);\n\n    sd.add_samples(samples);\n\n    SampledMDP smdp;\n    smdp.add_samples(*sd.get_discrete());\n    auto mdp = smdp.get_mdp();\n    auto&& initial = smdp.get_initial();\n\n    auto&& sol = algorithms::solve_mpi(*mdp,discount);\n\n    cout << \"Optimal policy: \"; print_vector(sol.policy); cout << \"Return \" <<  sol.total_return(initial) << endl;\n\n    // define observations\n    indvec observations(mdp->state_count(), -1);\n    size_t last_obs(0), inobs(0);\n    cout << \"Observations: \" << mdp->state_count() << \" states  \";\n    for(auto i : util::lang::range(size_t(0), mdp->state_count())){\n        // check if this is a terminal state\n        if(mdp->get_state(i).action_count() == 0 || inobs >= 2){\n            if(inobs > 0 && mdp->get_state(i).action_count() == 0){\n                last_obs++;\n            }\n            observations[i] = last_obs++;\n            inobs = 0;\n        }else {\n            observations[i] = last_obs;\n            inobs++;\n        }\n        cout << observations[i] << \" \";\n    }\n    cout << endl;\n\n    MDPI_R mdpi(mdp, observations, initial);\n    auto&& randompolicy = mdpi.random_policy(25);\n\n    auto isol = mdpi.solve_reweighted(0, discount, randompolicy);\n\n    isol = mdpi.solve_reweighted(10, discount, randompolicy);\n\n    auto sol_impl = solve_mpi(*mdp, discount, numvec(0), mdpi.obspol2statepol(isol));\n\n    cout << \"Implementable pol: \"; print_vector(isol);\n    cout << \"  Return: \" << sol_impl.total_return(initial) << endl;\n\n    cout << \"Generating implementable policies (randomly) ...\" << endl;\n\n    auto max_return = 0.0;\n    indvec max_pol(mdpi.obs_count(),-1);\n\n    for(auto i : util::lang::range(0,200)){\n        (void)(i);\n        auto rand_pol = mdpi.random_policy();\n\n        auto ret = solve_mpi(*mdp, discount, numvec(0), mdpi.obspol2statepol(rand_pol)).total_return(initial);\n\n        if(ret > max_return){\n            max_pol = rand_pol;\n            max_return = ret;\n        }\n\n    }\n\n    cout << \"Maximal return \" << max_return << endl;\n    cout << \"Best policy: \";\n    print_vector(max_pol);\n    cout << endl;\n\n    return 0;\n\n}\n", "meta": {"hexsha": "29ccdf631c71a0a9b981b769749a8c77b5843949", "size": 5319, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/dev.cpp", "max_stars_repo_name": "marekpetrik/CRAAM", "max_stars_repo_head_hexsha": "62cc392e876b5383faa5cb15ab1f6b70b26ff395", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2015-09-28T14:41:00.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-03T00:16:19.000Z", "max_issues_repo_path": "test/dev.cpp", "max_issues_repo_name": "marekpetrik/CRAAM", "max_issues_repo_head_hexsha": "62cc392e876b5383faa5cb15ab1f6b70b26ff395", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2017-08-10T18:35:40.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-13T01:38:04.000Z", "max_forks_repo_path": "test/dev.cpp", "max_forks_repo_name": "marekpetrik/CRAAM", "max_forks_repo_head_hexsha": "62cc392e876b5383faa5cb15ab1f6b70b26ff395", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2016-09-19T18:31:07.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-05T08:59:45.000Z", "avg_line_length": 27.0, "max_line_length": 117, "alphanum_fraction": 0.6371498402, "num_tokens": 1318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.48068146204561557}}
{"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_FUNCTION_CSC_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_CSC_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-trigonometric\n    Function object implementing csc capabilities\n\n    cosecante of the input in radian.\n\n    @par Semantic:\n\n    For every parameter of floating type T\n\n    @code\n    T r = csc(x);\n    @endcode\n\n    is similar to:\n\n    @code\n    T r = rec(sin(x));\n    @endcode\n\n    As most other trigonometric function csc can be called with a second optional parameter\n    which is a tag on speed and accuracy (see @ref cos for further details)\n\n    @see cscd, cscpi,\n\n  **/\n  const boost::dispatch::functor<tag::csc_> csc = {};\n} }\n#endif\n\n#include <boost/simd/function/scalar/csc.hpp>\n#include <boost/simd/function/simd/csc.hpp>\n\n#endif\n", "meta": {"hexsha": "a32045d90ff6dc2f80dba966ccdfd9603d1f4d57", "size": 1241, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/csc.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/function/csc.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/function/csc.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": 22.9814814815, "max_line_length": 100, "alphanum_fraction": 0.5906526994, "num_tokens": 281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389817407016, "lm_q2_score": 0.6442250996557036, "lm_q1q2_score": 0.4806814598689087}}
{"text": "// TestVectorExcel.cpp\r\n//\r\n// Test output of a vector in Excel. Here we \r\n// use the Excel Driver object directly.\r\n//\r\n// The output is in cell/numeric format.\r\n//\r\n// (C) Datasim Education BV 2006-2017\r\n//\r\n\r\n\r\n#include \"ExcelDriverlite.hpp\"\r\n#include \"Utilities.hpp\"\r\n\r\n#include <boost/numeric/ublas/matrix.hpp>\r\n#include <boost/numeric/ublas/io.hpp>\r\n#include <boost/numeric/ublas/matrix_proxy.hpp>\r\n\r\n#include <string>\r\n#include <vector>\r\n#include <list>\r\n\r\ndouble rho = 0.5;\r\ndouble NormalPdf1d(double x)\r\n{ // Univariate normal density function\r\n\t\r\n\tdouble fac = 1.0 / std::sqrt(2.0 * 3.14159265359);\r\n\treturn fac * std::exp(-x*x/2);\r\n}\r\n\r\ntemplate <typename Vector>\r\n\tVector DiscreteNormalPdf1d(const std::vector<double>& x)\r\n{\r\n\treturn CreateDiscreteFunction< std::vector<double>>(x, NormalPdf1d);\r\n}\r\n\r\nint main()\r\n{\r\n\r\n\t// C++11 syntax\r\n\t//using NumericMatrix = boost::numeric::ublas::matrix<double>;\r\n\t// using Vector = std::vector<double>\r\n\ttypedef boost::numeric::ublas::matrix<double> NumericMatrix;\r\n\ttypedef std::vector<double> Vector;\r\n\t//\tauto xarr = CreateMesh(N + 1, 0.0, 10.0);\r\n\t\r\n\tstd::string sheetName(\"Vector Case\");\r\n\r\n\tExcelDriver& excel = ExcelDriver::Instance();\r\n\texcel.MakeVisible(true);\t\t// Default is VISIBLE!\r\n\r\n\t// Labels for columns of the Excel vector.\r\n\t// Only labelled values are printed!!\r\n\t\r\n\tstd::string rowLabel(\"row1\");\r\n\tstd::list<std::string> colLabels; // C++11: {\"C1\", \"C2\", \"C3\", \"C4\",\"C5\"};\r\n\tcolLabels.push_back(\"C1\");\r\n\tcolLabels.push_back(\"C2\");\r\n\tcolLabels.push_back(\"C3\");\r\n\tcolLabels.push_back(\"C4\");\r\n\tcolLabels.push_back(\"C5\");\r\n\r\n\tVector myVector(colLabels.size());\r\n\tfor (std::size_t i = 0; i < myVector.size(); ++i)\r\n\t{\r\n\r\n\t\tmyVector[i] = static_cast<double>(i);\r\n\t}\r\n\r\n\ttry\r\n\t{\r\n\t\tlong row = 4; long col = 3;\r\n\t\texcel.AddVector<NumericMatrix>(myVector, sheetName, rowLabel, colLabels, row, col);\r\n\t}\r\n\tcatch(std::out_of_range& e)\r\n\t{\r\n\t\tstd::cout << e.what() << '\\n';\r\n\t}\r\n\tcatch (...)\r\n\t{\r\n\t\t// Catches everything else\r\n\t\tstd::cout << \"oop\";\r\n\t}\r\n\r\n\r\n\t{\r\n\t\t// Using mapping continuous space to discrete space\r\n\t\tstd::size_t N = 10;\r\n\t\tauto x = CreateMesh(N, -4.0, 4.0);\r\n\r\n\t\tstd::vector<double> vec = DiscreteNormalPdf1d<std::vector<double>>(x);\r\n\r\n\t\ttry\r\n\t\t{\r\n\r\n\t\t\tExcelDriver& excel = ExcelDriver::Instance();\r\n\t\t\tstd::string sheetName(\"Bivariate Normal pdf\");\r\n\t\t\tlong row = 3; long col = 2;\r\n\t\t\t//excel.AddVector<NumericMatrix>(vec, sheetName, row, col);\r\n\t\t}\r\n\t\tcatch (std::out_of_range& e)\r\n\t\t{\r\n\t\t\tstd::cout << e.what() << '\\n';\r\n\t\t}\r\n\t\tcatch (...)\r\n\t\t{\r\n\t\t\t// Catches everything else\r\n\t\t\tstd::cout << \"oop\";\r\n\t\t}\r\n\t}\r\n\r\n\r\n\treturn 0;\r\n}\r\n", "meta": {"hexsha": "728ac8b991c7f5b11503578681611da759a58c2b", "size": 2611, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "GroupE/Level9/Level9/Level9Code/Level9Code/UtilitiesDJD/ExcelDriver/TestVectorExcel.cpp", "max_stars_repo_name": "scottsidoli/C-for-Financial-Engineering---Baruch-Pre-MFE-Certificate", "max_stars_repo_head_hexsha": "79c2fb297a85c914d5f0b8671bb17636801e3ce7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-05T08:14:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-05T08:14:37.000Z", "max_issues_repo_path": "GroupE/Level9/Level9/Level9Code/Level9Code/UtilitiesDJD/ExcelDriver/TestVectorExcel.cpp", "max_issues_repo_name": "scottsidoli/C-for-Financial-Engineering---Baruch-Pre-MFE-Certificate", "max_issues_repo_head_hexsha": "79c2fb297a85c914d5f0b8671bb17636801e3ce7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GroupE/Level9/Level9/Level9Code/Level9Code/UtilitiesDJD/ExcelDriver/TestVectorExcel.cpp", "max_forks_repo_name": "scottsidoli/C-for-Financial-Engineering---Baruch-Pre-MFE-Certificate", "max_forks_repo_head_hexsha": "79c2fb297a85c914d5f0b8671bb17636801e3ce7", "max_forks_repo_licenses": ["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.7043478261, "max_line_length": 86, "alphanum_fraction": 0.6300268097, "num_tokens": 763, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802735722128, "lm_q2_score": 0.7185943925708562, "lm_q1q2_score": 0.4806536138902524}}
{"text": "//\n// Created by Amir Masoud Abdol on 2021-01-18\n//\n\n#define BOOST_TEST_DYN_LINK\n\n#define BOOST_TEST_MODULE ExperimentSetup Tests\n\n#include \"nlohmann/json.hpp\"\n#include <boost/test/unit_test.hpp>\nnamespace tt = boost::test_tools;\nnamespace utf = boost::unit_test;\n\n#include \"DependentVariable.h\"\n\n#include \"sample_experiment_setup.h\"\n\nusing json = nlohmann::ordered_json;\n\nusing namespace arma;\nusing namespace sam;\nusing namespace std;\n\n\nBOOST_AUTO_TEST_SUITE(constructor)\n\n  BOOST_AUTO_TEST_CASE( from_an_arma_array ) {\n    \n    BOOST_TEST_MESSAGE(\"Testing the Initialization from arma::Row<float>...\");\n    \n    arma::Row<float> data(100);\n    data.randn();\n    \n    DependentVariable dp{data};\n    \n    BOOST_TEST(arma::approx_equal(data, dp.measurements(), \"absdiff\", 0.001));\n    \n    // Testing whether stats are initialized, and updated\n    BOOST_TEST(dp.mean_ != 0);\n    BOOST_TEST(dp.var_ != 0);\n    \n  }\n\n  BOOST_AUTO_TEST_CASE( copy_constructor ) {\n    \n    BOOST_TEST_MESSAGE(\"Testing the Copy Constructor...\");\n    \n    arma::Row<float> data(100);\n    data.randn();\n    \n    DependentVariable dv{data};\n    \n    DependentVariable dv_copy{dv};\n    BOOST_TEST(dv.mean_ == dv_copy.mean_);\n    BOOST_TEST(arma::approx_equal(dv.measurements(), dv_copy.measurements(),\n                                  \"absdiff\", 0.001));\n    \n  }\n\nBOOST_AUTO_TEST_SUITE_END()\n\nBOOST_AUTO_TEST_SUITE( working_with_dependent_variable )\n\n  BOOST_AUTO_TEST_CASE( manipulating_measurements ) {\n    \n    arma::Row<float> data(100);\n    data.randn();\n    \n    DependentVariable dp{data};\n    \n    dp.removeMeasurements(arma::uvec{1, 5, 10, 50});\n    BOOST_TEST(dp.mean_ != arma::mean(data));\n    BOOST_TEST(dp.var_ != arma::var(data));\n    BOOST_TEST(dp.nobs_ == 96);\n    BOOST_TEST(dp.n_removed_obs == 4);\n    \n    dp.addNewMeasurements(arma::Row<float>{50000});\n    BOOST_TEST(dp.nobs_ == 97);\n    BOOST_TEST(dp.mean_ > arma::mean(data));\n    BOOST_TEST(dp.var_ > arma::var(data));\n    BOOST_TEST(dp.n_added_obs == 1);\n    \n    BOOST_TEST(dp.true_nobs_ == 100);\n  }\n\n  BOOST_AUTO_TEST_CASE( indices_operator_test, * utf::expected_failures(1) ) {\n    \n    arma::Row<float> data(100);\n    data.randn();\n    \n    DependentVariable dp{data};\n    \n    dp[50] = 50;\n    BOOST_TEST(dp[50] == 50);\n  }\n\n  BOOST_AUTO_TEST_CASE( manipulating_dps_status) {\n    \n    arma::Row<float> data(100);\n    data.randn();\n    \n    DependentVariable dp{data};\n    \n    dp.removeMeasurements(arma::uvec{1, 5, 10, 25, 50});\n    BOOST_TEST(dp.isModified());\n    BOOST_TEST(not dp.isHacked());\n    \n    dp.setHackedStatus(true);\n    BOOST_TEST(dp.isHacked());\n    BOOST_TEST(dp.isModified());\n    \n    dp.setCandidateStatus(true);\n    BOOST_TEST(dp.isCandidate());\n  }\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "2bde4594cbd0d53c2cc7c380bf4fec3ef3b4e0ba", "size": 2760, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sam-project/bakker-et-al-2012/SAM/SAM/tests/src/dependent_variable_test.cpp", "max_stars_repo_name": "amirmasoudabdol/bakker-et-al-2012-reproduction-using-sam", "max_stars_repo_head_hexsha": "518ab1cebaa80c19a12e92db8ae87386512ae053", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-25T20:21:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T20:21:41.000Z", "max_issues_repo_path": "sam-project/bakker-et-al-2012/SAM/SAM/tests/src/dependent_variable_test.cpp", "max_issues_repo_name": "amirmasoudabdol/bakker-et-al-2012-reproduction-using-sam", "max_issues_repo_head_hexsha": "518ab1cebaa80c19a12e92db8ae87386512ae053", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sam-project/bakker-et-al-2012/SAM/SAM/tests/src/dependent_variable_test.cpp", "max_forks_repo_name": "amirmasoudabdol/bakker-et-al-2012-reproduction-using-sam", "max_forks_repo_head_hexsha": "518ab1cebaa80c19a12e92db8ae87386512ae053", "max_forks_repo_licenses": ["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.5897435897, "max_line_length": 78, "alphanum_fraction": 0.6601449275, "num_tokens": 710, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802735722128, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.4806536098592313}}
{"text": "/**\n * @file MPCTest.cpp\n * @author Giulio Romualdi\n * @copyright Released under the terms of the LGPLv2.1 or later, see LGPL.TXT\n * @date 2018\n */\n\n// Catch2\n#include <catch2/catch.hpp>\n\n// OsqpEigen\n#include <OsqpEigen/OsqpEigen.h>\n\n// eigen\n#include <Eigen/Dense>\n\n#include <cmath>\n#include <fstream>\n#include <iostream>\n\n// colors\n#define ANSI_TXT_GRN \"\\033[0;32m\"\n#define ANSI_TXT_MGT \"\\033[0;35m\" //Magenta\n#define ANSI_TXT_DFT \"\\033[0;0m\" //Console default\n#define GTEST_BOX \"[     cout ] \"\n#define COUT_GTEST ANSI_TXT_GRN << GTEST_BOX //You could add the Default\n#define COUT_GTEST_MGT COUT_GTEST << ANSI_TXT_MGT\n\nvoid setDynamicsMatrices(Eigen::Matrix<double, 12, 12> &a, Eigen::Matrix<double, 12, 4> &b)\n{\n    a << 1.,      0.,     0., 0., 0., 0., 0.1,     0.,     0.,  0.,     0.,     0.    ,\n        0.,      1.,     0., 0., 0., 0., 0.,      0.1,    0.,  0.,     0.,     0.    ,\n        0.,      0.,     1., 0., 0., 0., 0.,      0.,     0.1, 0.,     0.,     0.    ,\n        0.0488,  0.,     0., 1., 0., 0., 0.0016,  0.,     0.,  0.0992, 0.,     0.    ,\n        0.,     -0.0488, 0., 0., 1., 0., 0.,     -0.0016, 0.,  0.,     0.0992, 0.    ,\n        0.,      0.,     0., 0., 0., 1., 0.,      0.,     0.,  0.,     0.,     0.0992,\n        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.    ,\n        0.,      0.,     0., 0., 0., 0., 0.,      0.,     1.,  0.,     0.,     0.    ,\n        0.9734,  0.,     0., 0., 0., 0., 0.0488,  0.,     0.,  0.9846, 0.,     0.    ,\n        0.,     -0.9734, 0., 0., 0., 0., 0.,     -0.0488, 0.,  0.,     0.9846, 0.    ,\n        0.,      0.,     0., 0., 0., 0., 0.,      0.,     0.,  0.,     0.,     0.9846;\n\n    b << 0.,      -0.0726,  0.,     0.0726,\n        -0.0726,  0.,      0.0726, 0.    ,\n        -0.0152,  0.0152, -0.0152, 0.0152,\n        -0.,     -0.0006, -0.,     0.0006,\n        0.0006,   0.,     -0.0006, 0.0000,\n        0.0106,   0.0106,  0.0106, 0.0106,\n        0,       -1.4512,  0.,     1.4512,\n        -1.4512,  0.,      1.4512, 0.    ,\n        -0.3049,  0.3049, -0.3049, 0.3049,\n        -0.,     -0.0236,  0.,     0.0236,\n        0.0236,   0.,     -0.0236, 0.    ,\n        0.2107,   0.2107,  0.2107, 0.2107;\n}\n\n\nvoid setInequalityConstraints(Eigen::Matrix<double, 12, 1> &xMax, Eigen::Matrix<double, 12, 1> &xMin,\n                              Eigen::Matrix<double, 4, 1> &uMax, Eigen::Matrix<double, 4, 1> &uMin)\n{\n    double u0 = 10.5916;\n\n    // input inequality constraints\n    uMin << 9.6 - u0,\n        9.6 - u0,\n        9.6 - u0,\n        9.6 - u0;\n\n    uMax << 13 - u0,\n        13 - u0,\n        13 - u0,\n        13 - u0;\n\n    // state inequality constraints\n    xMin << -M_PI/6,-M_PI/6,-OsqpEigen::INFTY,-OsqpEigen::INFTY,-OsqpEigen::INFTY,-1.,\n        -OsqpEigen::INFTY, -OsqpEigen::INFTY,-OsqpEigen::INFTY,-OsqpEigen::INFTY,\n        -OsqpEigen::INFTY,-OsqpEigen::INFTY;\n\n    xMax << M_PI/6,M_PI/6, OsqpEigen::INFTY,OsqpEigen::INFTY,OsqpEigen::INFTY,\n        OsqpEigen::INFTY, OsqpEigen::INFTY,OsqpEigen::INFTY,OsqpEigen::INFTY,\n        OsqpEigen::INFTY,OsqpEigen::INFTY,OsqpEigen::INFTY;\n}\n\nvoid setWeightMatrices(Eigen::DiagonalMatrix<double, 12> &Q, Eigen::DiagonalMatrix<double, 4> &R)\n{\n    Q.diagonal() << 0, 0, 10., 10., 10., 10., 0, 0, 0, 5., 5., 5.;\n    R.diagonal() << 0.1, 0.1, 0.1, 0.1;\n}\n\nvoid castMPCToQPHessian(const Eigen::DiagonalMatrix<double, 12> &Q, const Eigen::DiagonalMatrix<double, 4> &R, int mpcWindow,\n                        Eigen::SparseMatrix<double> &hessianMatrix)\n{\n\n    hessianMatrix.resize(12*(mpcWindow+1) + 4 * mpcWindow, 12*(mpcWindow+1) + 4 * mpcWindow);\n\n    //populate hessian matrix\n    for(int i = 0; i<12*(mpcWindow+1) + 4 * mpcWindow; i++){\n        if(i < 12*(mpcWindow+1)){\n            int posQ=i%12;\n            float value = Q.diagonal()[posQ];\n            if(value != 0)\n                hessianMatrix.insert(i,i) = value;\n        }\n        else{\n            int posR=i%4;\n            float value = R.diagonal()[posR];\n            if(value != 0)\n                hessianMatrix.insert(i,i) = value;\n        }\n    }\n}\n\nvoid castMPCToQPGradient(const Eigen::DiagonalMatrix<double, 12> &Q, const Eigen::Matrix<double, 12, 1> &xRef, int mpcWindow,\n                         Eigen::VectorXd &gradient)\n{\n\n    Eigen::Matrix<double,12,1> Qx_ref;\n    Qx_ref = Q * (-xRef);\n\n    // populate the gradient vector\n    gradient = Eigen::VectorXd::Zero(12*(mpcWindow+1) +  4*mpcWindow, 1);\n    for(int i = 0; i<12*(mpcWindow+1); i++){\n        int posQ=i%12;\n        float value = Qx_ref(posQ,0);\n        gradient(i,0) = value;\n    }\n}\n\nvoid castMPCToQPConstraintMatrix(const Eigen::Matrix<double, 12, 12> &dynamicMatrix, const Eigen::Matrix<double, 12, 4> &controlMatrix,\n                                 int mpcWindow, Eigen::SparseMatrix<double> &constraintMatrix)\n{\n    constraintMatrix.resize(12*(mpcWindow+1)  + 12*(mpcWindow+1) + 4 * mpcWindow, 12*(mpcWindow+1) + 4 * mpcWindow);\n\n    // populate linear constraint matrix\n    for(int i = 0; i<12*(mpcWindow+1); i++){\n        constraintMatrix.insert(i,i) = -1;\n    }\n\n    for(int i = 0; i < mpcWindow; i++)\n        for(int j = 0; j<12; j++)\n            for(int k = 0; k<12; k++){\n                float value = dynamicMatrix(j,k);\n                if(value != 0){\n                    constraintMatrix.insert(12 * (i+1) + j, 12 * i + k) = value;\n                }\n            }\n\n    for(int i = 0; i < mpcWindow; i++)\n        for(int j = 0; j < 12; j++)\n            for(int k = 0; k < 4; k++){\n                float value = controlMatrix(j,k);\n                if(value != 0){\n                    constraintMatrix.insert(12*(i+1)+j, 4*i+k+12*(mpcWindow + 1)) = value;\n                }\n            }\n\n    for(int i = 0; i<12*(mpcWindow+1) + 4*mpcWindow; i++){\n        constraintMatrix.insert(i+(mpcWindow+1)*12,i) = 1;\n    }\n}\n\nvoid castMPCToQPConstraintVectors(const Eigen::Matrix<double, 12, 1> &xMax, const Eigen::Matrix<double, 12, 1> &xMin,\n                                   const Eigen::Matrix<double, 4, 1> &uMax, const Eigen::Matrix<double, 4, 1> &uMin,\n                                   const Eigen::Matrix<double, 12, 1> &x0,\n                                   int mpcWindow, Eigen::VectorXd &lowerBound, Eigen::VectorXd &upperBound)\n{\n    // evaluate the lower and the upper inequality vectors\n    Eigen::VectorXd lowerInequality = Eigen::MatrixXd::Zero(12*(mpcWindow+1) +  4 * mpcWindow, 1);\n    Eigen::VectorXd upperInequality = Eigen::MatrixXd::Zero(12*(mpcWindow+1) +  4 * mpcWindow, 1);\n    for(int i=0; i<mpcWindow+1; i++){\n        lowerInequality.block(12*i,0,12,1) = xMin;\n        upperInequality.block(12*i,0,12,1) = xMax;\n    }\n    for(int i=0; i<mpcWindow; i++){\n        lowerInequality.block(4 * i + 12 * (mpcWindow + 1), 0, 4, 1) = uMin;\n        upperInequality.block(4 * i + 12 * (mpcWindow + 1), 0, 4, 1) = uMax;\n    }\n\n    // evaluate the lower and the upper equality vectors\n    Eigen::VectorXd lowerEquality = Eigen::MatrixXd::Zero(12*(mpcWindow+1),1 );\n    Eigen::VectorXd upperEquality;\n    lowerEquality.block(0,0,12,1) = -x0;\n    upperEquality = lowerEquality;\n    lowerEquality = lowerEquality;\n\n    // merge inequality and equality vectors\n    lowerBound = Eigen::MatrixXd::Zero(2*12*(mpcWindow+1) +  4*mpcWindow,1 );\n    lowerBound << lowerEquality,\n        lowerInequality;\n\n    upperBound = Eigen::MatrixXd::Zero(2*12*(mpcWindow+1) +  4*mpcWindow,1 );\n    upperBound << upperEquality,\n        upperInequality;\n}\n\n\nvoid updateConstraintVectors(const Eigen::Matrix<double, 12, 1> &x0,\n                             Eigen::VectorXd &lowerBound, Eigen::VectorXd &upperBound)\n{\n    lowerBound.block(0,0,12,1) = -x0;\n    upperBound.block(0,0,12,1) = -x0;\n}\n\n\ndouble getErrorNorm(const Eigen::Matrix<double, 12, 1> &x,\n                    const Eigen::Matrix<double, 12, 1> &xRef)\n{\n    // evaluate the error\n    Eigen::Matrix<double, 12, 1> error = x - xRef;\n\n    // return the norm\n    return error.norm();\n}\n\n\nTEST_CASE(\"MPCTest\")\n{\n    // open the ofstream\n    std::ofstream dataStream;\n    dataStream.open (\"output.txt\");\n\n    // set the preview window\n    int mpcWindow = 20;\n\n    // allocate the dynamics matrices\n    Eigen::Matrix<double, 12, 12> a;\n    Eigen::Matrix<double, 12, 4> b;\n\n    // allocate the constraints vector\n    Eigen::Matrix<double, 12, 1> xMax;\n    Eigen::Matrix<double, 12, 1> xMin;\n    Eigen::Matrix<double, 4, 1> uMax;\n    Eigen::Matrix<double, 4, 1> uMin;\n\n    // allocate the weight matrices\n    Eigen::DiagonalMatrix<double, 12> Q;\n    Eigen::DiagonalMatrix<double, 4> R;\n\n    // allocate the initial and the reference state space\n    Eigen::Matrix<double, 12, 1> x0;\n    Eigen::Matrix<double, 12, 1> xRef;\n\n    // allocate QP problem matrices and vectores\n    Eigen::SparseMatrix<double> hessian;\n    Eigen::VectorXd gradient;\n    Eigen::SparseMatrix<double> linearMatrix;\n    Eigen::VectorXd lowerBound;\n    Eigen::VectorXd upperBound;\n\n    // set the initial and the desired states\n    x0 << 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ;\n    xRef <<  0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0;\n\n    // set MPC problem quantities\n    setDynamicsMatrices(a, b);\n    setInequalityConstraints(xMax, xMin, uMax, uMin);\n    setWeightMatrices(Q, R);\n\n    // cast the MPC problem as QP problem\n    castMPCToQPHessian(Q, R, mpcWindow, hessian);\n    castMPCToQPGradient(Q, xRef, mpcWindow, gradient);\n    castMPCToQPConstraintMatrix(a, b, mpcWindow, linearMatrix);\n    castMPCToQPConstraintVectors(xMax, xMin, uMax, uMin, x0, mpcWindow, lowerBound, upperBound);\n\n    // instantiate the solver\n    OsqpEigen::Solver solver;\n\n    // settings\n    solver.settings()->setVerbosity(false);\n    solver.settings()->setWarmStart(true);\n\n    // set the initial data of the QP solver\n    solver.data()->setNumberOfVariables(12 * (mpcWindow + 1) + 4 * mpcWindow);\n    solver.data()->setNumberOfConstraints(2 * 12 * (mpcWindow + 1) +  4 * mpcWindow);\n    REQUIRE(solver.data()->setHessianMatrix(hessian));\n    REQUIRE(solver.data()->setGradient(gradient));\n    REQUIRE(solver.data()->setLinearConstraintsMatrix(linearMatrix));\n    REQUIRE(solver.data()->setLowerBound(lowerBound));\n    REQUIRE(solver.data()->setUpperBound(upperBound));\n\n    // instantiate the solver\n    REQUIRE(solver.initSolver());\n\n    // controller input and QPSolution vector\n    Eigen::Vector4d ctr;\n    Eigen::VectorXd QPSolution;\n\n    // number of iteration steps\n    int numberOfSteps = 50;\n\n    // profiling quantities\n    clock_t startTime, endTime;\n    double avarageTime = 0;\n\n    for (int i = 0; i < numberOfSteps; i++){\n        startTime = clock();\n\n        // solve the QP problem\n        REQUIRE(solver.solve());\n\n        // get the controller input\n        QPSolution = solver.getSolution();\n        ctr = QPSolution.block(12 * (mpcWindow + 1), 0, 4, 1);\n\n        // save data into file\n        auto x0Data = x0.data();\n        for(int j = 0; j < 12; j++)\n            dataStream << x0Data[j] << \" \";\n        dataStream << std::endl;\n\n        // propagate the model\n        x0 = a * x0 + b * ctr;\n\n        // update the constraint bound\n        updateConstraintVectors(x0, lowerBound, upperBound);\n        REQUIRE(solver.updateBounds(lowerBound, upperBound));\n\n        endTime = clock();\n\n        avarageTime += static_cast<double>(endTime - startTime) / CLOCKS_PER_SEC;\n      }\n\n    // close the stream\n    dataStream.close();\n\n    std::cout << COUT_GTEST_MGT << \"Avarage time = \" << avarageTime / numberOfSteps\n              << \" seconds.\" << ANSI_TXT_DFT << std::endl;\n\n    REQUIRE(getErrorNorm(x0, xRef) <=  0.001);\n}\n", "meta": {"hexsha": "db2a3b9a3d15c85519b7ff84258c24684f99aca6", "size": 11596, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "external/osqp-eigen/tests/MPCTest.cpp", "max_stars_repo_name": "robomechanics/spirit-software", "max_stars_repo_head_hexsha": "b0a3d8defd3abe06406de6573212bab4a2eb769a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2020-12-17T16:58:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-12T09:31:30.000Z", "max_issues_repo_path": "external/osqp-eigen/tests/MPCTest.cpp", "max_issues_repo_name": "robomechanics/spirit-software", "max_issues_repo_head_hexsha": "b0a3d8defd3abe06406de6573212bab4a2eb769a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 101.0, "max_issues_repo_issues_event_min_datetime": "2020-09-02T00:36:25.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-04T23:40:32.000Z", "max_forks_repo_path": "external/osqp-eigen/tests/MPCTest.cpp", "max_forks_repo_name": "robomechanics/spirit-software", "max_forks_repo_head_hexsha": "b0a3d8defd3abe06406de6573212bab4a2eb769a", "max_forks_repo_licenses": ["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.9277108434, "max_line_length": 135, "alphanum_fraction": 0.5551914453, "num_tokens": 4013, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.6688802669716106, "lm_q1q2_score": 0.4806536091470966}}
{"text": "#include <pybind11/pybind11.h>\n#include <pybind11/eigen.h>\n#include <Eigen/LU>\n\nnamespace py = pybind11;\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\nusing Eigen::log;\nusing std::lgamma;\n\nMatrixXd scale_matrix(MatrixXd X, int N, int k, double r, MatrixXd m, MatrixXd S) {\n    MatrixXd xsum = X.colwise().sum();\n    MatrixXd res = S + X.transpose() * X\n                     + r * N / (N + r) * m * m.transpose()\n                     - 1/(N+r) * (xsum.transpose() * xsum)\n                     - (r / (N + r)) * (m * xsum + xsum.transpose() * m.transpose());\n    return res;\n}\n\ndouble signprod(VectorXd dU){\n    double res = 1;\n    for(int i = 0; i < dU.size(); i++){\n        if(dU[i] < 0){\n            res *= -1;\n        }\n    }\n    return res;\n}\n\ndouble logdet(MatrixXd S){\n    Eigen::PartialPivLU<MatrixXd> lu(S);\n    MatrixXd U = lu.matrixLU();\n    VectorXd dU = U.diagonal();\n    MatrixXd P = lu.permutationP();\n    double c = P.determinant() * signprod(dU);\n    double d = log(c) + dU.array().abs().log().sum();\n    return d;\n}\n\ndouble niw(MatrixXd X, MatrixXd m, MatrixXd S, double r){\n    const double PI  =3.141592653589793238463;\n    double N = (double)X.rows();\n    double k = (double)X.cols();\n    // v = k;\n    double vprime = k + N;\n\n    MatrixXd Sprime = scale_matrix(X, N, k, r, m, S);\n\n    double num = vprime*k/2*log(2);\n    double den = k * k / 2 * log(2);\n    for(int i = 0; i < k; i++){\n        num += lgamma((double)(vprime - i)/2);\n        den += lgamma((double)(k - i)/2);\n    }\n\n    double lml = - N*k/2 * (log(2) + log(PI))\n                 + k/2*(log(r)-log(N + r))\n                 + k/2*logdet(S)\n                 - vprime/2*logdet(Sprime)\n                 + num - den;\n    return lml;\n}\n\nPYBIND11_PLUGIN(helper){\n    pybind11::module m(\"helper\", \"helper functions\");\n    m.def(\"scale_matrix\", &scale_matrix);\n    m.def(\"niw\", &niw);\n    m.def(\"logdet\", &logdet);\n    return m.ptr();\n}\n", "meta": {"hexsha": "691d2cb111629fc90d789b39ec4a2df520b69fe0", "size": 1913, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bhc/.rendered.helper.cpp", "max_stars_repo_name": "yang-lina/Bayesian-Hierarchical-Clustering", "max_stars_repo_head_hexsha": "2e35d3c3d59e33cd851f8497d1cd592d601b8fbb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-23T18:51:58.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-23T18:51:58.000Z", "max_issues_repo_path": "bhc/helper.cpp", "max_issues_repo_name": "yang-lina/Bayesian-Hierarchical-Clustering", "max_issues_repo_head_hexsha": "2e35d3c3d59e33cd851f8497d1cd592d601b8fbb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bhc/helper.cpp", "max_forks_repo_name": "yang-lina/Bayesian-Hierarchical-Clustering", "max_forks_repo_head_hexsha": "2e35d3c3d59e33cd851f8497d1cd592d601b8fbb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-05-08T17:42:37.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-08T17:42:37.000Z", "avg_line_length": 26.9436619718, "max_line_length": 85, "alphanum_fraction": 0.5295347622, "num_tokens": 599, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943805178139, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.48065360108505456}}
{"text": "/*\n * X-Stream\n *\n * Copyright 2013 Operating Systems Laboratory EPFL\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 _ALS_\n#define _ALS_\n#include \"../../utils/options_utils.h\"\n#include \"../../utils/desc_utils.h\"\n#include \"../../utils/boost_log_wrapper.h\"\n#include \"../../core/x-lib.hpp\"\n#include <cmath>\n#include <boost/random.hpp>\n#include <boost/thread/mutex.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/bindings/lapack/gesv.hpp>\n#include <boost/numeric/bindings/traits/ublas_matrix.hpp>\n#include <boost/numeric/bindings/traits/ublas_vector2.hpp>\n\n#define LAMBDA 0.065\n#define RANK   5\n\nnamespace ublas = boost::numeric::ublas;\nnamespace lapack = boost::numeric::bindings::lapack;\n\nnamespace algorithm {\n  namespace sg_simple {\n    class als_per_processor_data:public per_processor_data {\n    public:\n      static double sse;\n      double sse_local;\n      als_per_processor_data() \n\t:sse_local(0.0)\n      {}\n      bool reduce(per_processor_data **per_cpu_array,\n\t\t  unsigned long processors)\n      {\n\tsse = 0;\n\tfor(unsigned long i=0;i<processors;i++) {\n\t  als_per_processor_data * data = \n\t    static_cast<als_per_processor_data *>(per_cpu_array[i]);\n\t  sse += data->sse_local;\n\t  data->sse_local = 0;\n\t}\n\treturn false;\n      }\n    } __attribute__((__aligned__(64))) ;\n  \n    template <typename F>\n    class als_factorization {\n    \n    private:\n\n      struct vertex {\n\tvertex_t degree;\n\tvertex_t count;\n\tdouble feature_vec[RANK];\n\tdouble temp_mat[RANK][RANK];\n      } __attribute__((__packed__));\n\n      struct update {\n\tvertex_t target;\n\tdouble feature_vec[RANK];\n\tdouble rating;\n      } __attribute__((__packed__));\n    \n      static unsigned long niters;\n\n      // Helpers\n      static void copy_vector(double src_vec[RANK], double dst_vec[RANK])\n      {\n\tfor (int i = 0; i < RANK; i++)\n\t  dst_vec[i] = src_vec[i];\n      }\n      static void zero_vector(double vec[RANK])\n      {\n\tfor (int i = 0; i < RANK; i++)\n\t  vec[i] = 0;\n      }\n      static void zero_matrix(double mat[RANK][RANK])\n      {\n\tfor (int i = 0; i < RANK; i++)\n\t  for (int j = 0; j < RANK; j++)\n\t    mat[i][j] = 0;\n      }\n\n      static void init_vertex(struct vertex& v)\n      {\n\tv.degree = 0;\n\tv.count = 0;\n\n\tboost::mt19937 generator;\n\tboost::uniform_int<> distribution(0, 1000);\n\tfor (int i = 0; i < RANK; i++)\n\t  v.feature_vec[i] =  0.001 * distribution(generator);\n      }\n\n      // Solve the system Ax=b using LAPACK library and boost bindings for it\n      static void solve(double mat[RANK][RANK], double vec[RANK])\n      {\n\tublas::matrix<double, ublas::column_major> A(RANK, RANK);\n\tublas::vector<double> b(RANK);\n      \n\tfor (int i = 0; i < RANK; i++) {\n\t  b(i) = vec[i];\n\t  for (int j = 0; j < RANK; j++) {\n\t    A(i,j) = mat[i][j];\n\t  }\n\t}\n\n\tlapack::gesv(A,b);\n\n\tfor (int i = 0; i < RANK; i++)\n\t  vec[i] = b(i);\n      }\n\n    public:\n      static unsigned long vertex_state_bytes() {\n\treturn sizeof(struct vertex);\n      }\n      static unsigned long split_size_bytes() {\n\treturn sizeof(struct update);\n      }\n\n      static unsigned long split_key(unsigned char* buffer, unsigned long jump)\n      {\n\tstruct update* u = (struct update*)buffer;\n\tvertex_t key = u->target;\n\tkey = key >> jump;\n\treturn key;\n      }\n\n      static bool init(unsigned char* vertex_state,\n\t\t       unsigned long vertex_index,\n\t\t       unsigned long bsp_phase,\n\t\t       per_processor_data *cpu_state)\n      {\n\tstruct vertex* vertices = (struct vertex*)vertex_state;\n\tinit_vertex(*vertices);\n\treturn true;\n      }\n\n      static bool apply_one_update(unsigned char* vertex_state,\n\t\t\t\t   unsigned char* update_stream,\n\t\t\t\t   per_processor_data *per_cpu_data,\n\t\t\t\t   unsigned long bsp_phase)\n      {\n\tstruct update* u = (struct update*)update_stream;\n\tstruct vertex* vertices = (struct vertex*)vertex_state;\n\tstruct vertex* v = &vertices[x_lib::configuration::map_offset(u->target)];\n\n\tif (bsp_phase <= niters)\n\t  {\n\t    // Track how many updates (edges) have been processed\n\t    v->count++;\n\n\t    // Initialize data structures for this iteration - zero out feature vector\n\t    // and temp matrix since we'll be adding to them.\n\t    if (v->count == 1) {\n\t      zero_vector(v->feature_vec);\n\t      zero_matrix(v->temp_mat);\n\t    }\n\n\t    // To compute the new feature vector of vertex v, we need to solve the system: A*feature_vec=b\n\t    // A is a matrix: A = O * O^T + D\n\t    // O is a submatrix of the other side of the graph where column vectors are feature vectors of\n\t    // those vertices that are connected to this vertex\n\t    // O^T is a transpose of O\n\t    // D is a diagonal matrix: D = lambda * degree * I, where I is an identity matrix\n\t    // b is a vector: b = O * r\n\t    // r is a ratings vector formed from the ratings of outgoing edges\n\n\t    // Calculating O*O^T and b\n\t    for (int i = 0; i < RANK; i++) {\n\t      v->feature_vec[i] += u->feature_vec[i] * u->rating;\n\t      for (int j = 0; j < RANK; j++) {\n\t\tv->temp_mat[i][j] += u->feature_vec[i] * u->feature_vec[j];\n\t      }\n\t    }\n\n\t    // Additional procesing after all updates have been gathered\n\t    if (v->count == v->degree)\n\t      {\n\t\t// Adding D to A\n\t\tfor (int i = 0; i < RANK; i++) {\n\t\t  v->temp_mat[i][i] += LAMBDA * v->degree;\n\t\t}\n\n\t\t// Solve to get the new feature vector for the vertex\n\t\tsolve(v->temp_mat, v->feature_vec);\n\n\t\t// Reset count for the next iteration\n\t\tv->count = 0;\n\t      }\n\n\t    return true;\n\t  }\n\n\t// After all iterations are finished, we use one more phase to\n\t// compute the sum of square errors. This is done on the right side.\n\telse\n\t  {\n\t    double sqerror = u->rating;\n\t    for (int i = 0; i < RANK; i++)\n\t      sqerror -= v->feature_vec[i] * u->feature_vec[i];\n\t    sqerror *= sqerror;\n\n\t    static_cast<als_per_processor_data*>(per_cpu_data)->sse_local += sqerror;\n\t\n\t    // And we stop processing\n\t    return false;\n\t  }\n      }\n\n      static bool generate_update(unsigned char* vertex_state,\n\t\t\t\t  unsigned char* edge_format,\n\t\t\t\t  unsigned char* update_stream,\n\t\t\t\t  per_processor_data* per_processor_data,\n\t\t\t\t  unsigned long bsp_phase)\n      {\n\tvertex_t src, dst;\n\tweight_t rating;\n\tF::read_edge(edge_format, src, dst, rating);\n\n\tstruct vertex* vertices = (struct vertex*)vertex_state;\n\tstruct vertex* v = &vertices[x_lib::configuration::map_offset(src)];\n\n\t// Iteration 0 is also used to count the vertex degree\n\tif (bsp_phase == 0)\n\t  {\n\t    v->degree++;\n\t  }\n      \n\t// The graph is bipartite, and it is assumed that lower ids\n\t// form the left side.\n\t// The alternating starts by solving the right side in iteration 1,\n\t// after the left side generates first updates in iteration 0.\n\t// Therefore, in even numbered iterations we solve the left\n\t// side, and in odd numbered iterations we solve the right side.\n\t// Likewise, the left side generates updates in even numbered \n\t// iterations, and the right side in odd numbered iterations.\n\n\tbool leftside = (src < dst) ? true : false;\n\n\tif ((bsp_phase % 2 == 0 && leftside) || (bsp_phase % 2 == 1 && !leftside))\n\t  {\n\t    struct update* u = (struct update*)update_stream;\n\t    u->target = dst;\n\t    u->rating = (double)rating;\n\t    copy_vector(v->feature_vec, u->feature_vec);\n\t    return true;\n\t  }\n\telse\n\t  return false;\n      }\n\n      static void preprocessing()\n      {\n\t// We double the number, since in one phase we process one side of the\n\t// bipartite graph\n\tniters = 2 * vm[\"als::niters\"].as<unsigned long>();\n      }\n\n      static void postprocessing()\n      {\n\tBOOST_LOG_TRIVIAL(info) << \"ALGORITHM::ALS::SSE \" << als_per_processor_data::sse;\n\tunsigned long nedges = pt.get<unsigned long>(\"graph.edges\");\n\tdouble rmse = std::sqrt( als_per_processor_data::sse / (1. * nedges) );\n\tBOOST_LOG_TRIVIAL(info) << \"ALGORITHM::ALS::RMSE \" << rmse;\n      }\n\n      static per_processor_data * \n      create_per_processor_data(unsigned long processor_id)\n      {\n\treturn new als_per_processor_data();\n      }\n    \n      static unsigned long min_super_phases()\n      {\n\treturn 1;\n      }\n\n      static bool need_init(unsigned long bsp_phase)\n      {\n\treturn (bsp_phase == 0);\n      }\n    \n    };\n\n    // These should be in a cpp file, but it's ok since we only include\n    // this header once in driver.cpp\n    template<typename F>\n    unsigned long als_factorization<F>::niters;\n\n    double als_per_processor_data::sse = 0;\n\n  }\n}\n#endif\n", "meta": {"hexsha": "055866771409e3c1f043ef5d20bad9e2ab037882", "size": 8881, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "algorithms/als/als.hpp", "max_stars_repo_name": "AftabHussain/x-stream", "max_stars_repo_head_hexsha": "01fb3ff0703d18c23047d3c80f68b26f14b2b4fa", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 75.0, "max_stars_repo_stars_event_min_datetime": "2015-11-06T02:01:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-04T01:51:00.000Z", "max_issues_repo_path": "algorithms/als/als.hpp", "max_issues_repo_name": "AftabHussain/x-stream", "max_issues_repo_head_hexsha": "01fb3ff0703d18c23047d3c80f68b26f14b2b4fa", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2016-07-13T13:05:43.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-23T17:45:05.000Z", "max_forks_repo_path": "algorithms/als/als.hpp", "max_forks_repo_name": "AftabHussain/x-stream", "max_forks_repo_head_hexsha": "01fb3ff0703d18c23047d3c80f68b26f14b2b4fa", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 46.0, "max_forks_repo_forks_event_min_datetime": "2015-08-31T09:41:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-27T07:29:43.000Z", "avg_line_length": 28.1936507937, "max_line_length": 99, "alphanum_fraction": 0.6455354127, "num_tokens": 2317, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.48057012592909143}}
{"text": "/***************************************************************\n * Author:    Yixin Zhuang (yixin.zhuang@gmail.com)\n //2014-11-02\n **************************************************************/\n#include \"time.h\"\n#include \"core/Segmentation.h\"\n#include \"setCurvature.h\"\n\n#include <Eigen/Dense>\n#include <set>\n#include \"TriMesh.h\"\n#include \"TriMesh_algo.h\"\n\n#include <unordered_map>\nusing namespace std;\nusing namespace GeoProperty;\n\n#include <QtCore/QString>\n\n//There are many libs for computing differential property of discrete surface, we includes CGAL and TriMesh;\n//In default setting, we use Trimesh, which seems has smoother field over the surface;\n\nvoid MeshSegment::computeCurvature()\n{\n\tTriMesh *tmesh = new TriMesh(*triMesh);\n\tunsigned vNum = tmesh->vertices.size();\n\ttmesh->colors.resize(triMesh->vertices.size());\n\tcolorbycurv(tmesh, curvatureScale, curvatureSmooth);\n\n\tunsigned i = 0; double maxAnis = 0;\n\tfor (auto v_it = myMesh->getVertices().begin(); v_it != myMesh->getVertices().end(); v_it++)\n\t{\n\t\tv_it->normal() = Vec3(tmesh->normals[i][0], tmesh->normals[i][1], tmesh->normals[i][2]);\n\t\tv_it->color() = Vec3(tmesh->colors[i][0], tmesh->colors[i][1], tmesh->colors[i][2]);\n\t\tv_it->direction(0) = Vec3(tmesh->pdir1[i][0], tmesh->pdir1[i][1], tmesh->pdir1[i][2]);\n\t\tv_it->direction(1) = Vec3(tmesh->pdir2[i][0], tmesh->pdir2[i][1], tmesh->pdir2[i][2]);\n\t\tv_it->magnitude(0) = fabs(tmesh->curv1[i]);\n\t\tv_it->magnitude(1) = fabs(tmesh->curv2[i]);\n\n\t\tdouble& k1 = v_it->magnitude(0);\n\t\tdouble& k2 = v_it->magnitude(1);\n\n\t\tdouble diff = fabs(k1 - k2);\n\n\t\tif (maxAnis < diff)\n\t\t{\n\t\t\tmaxAnis = diff;\n\t\t}\n\t\ti++;\n\t}\n\tAnisGeodesic::maxAnis = maxAnis;\n\tdelete tmesh;\n}\nvoid MeshProperty::computeVertexProperty_TRIMESH(double scale)\n{\n\tQString  mystring = QString::number(scale, 10, 3);\n\n\t//init trimesh;\n\tTriMesh *triMesh = new TriMesh;\n\tint vNum = myMesh->getVertices().size();\n\tauto vInds = myMesh->getVIter();\n\ttriMesh->vertices.resize(vNum);\n\tfor (int i = 0; i < vNum; i++)\n\t{\n\t\tfor (int j = 0; j < 3; j++)\n\t\t{\n\t\t\ttriMesh->vertices[i][j] = vInds[i]->coordinate()[j];\n\t\t}\n\t}\n\tint fNum = myMesh->getFaces().size();\n\tauto fInds = myMesh->getFIter();\n\ttriMesh->faces.resize(fNum);\n\tfor (int i = 0; i < fNum; i++)\n\t{\n\t\tfor (int j = 0; j < 3; j++)\n\t\t{\n\t\t\ttriMesh->faces[i][j] = fInds[i]->vertex_iter(j)->id();\n\t\t}\n\t}\n\n\t//compute curvature\n\ttriMesh->need_normals();\n\ttriMesh->colors.resize(triMesh->vertices.size());\n\tcolorbycurv(triMesh, \"0.0\", mystring.toStdString().data());\n\n\t//write to...\n\tv_anisotropy.clear(); v_anisotropy.resize(myMesh->getVertices().size(), 0);\n\tcurMag.clear(); curMag.resize(myMesh->getVertices().size());\n\tcurDir.clear(); curDir.resize(myMesh->getVertices().size(), std::vector<Vec3>(3));\n\n\tunsigned i = 0;\n\tfor (auto v_it = myMesh->getVertices().begin(); v_it != myMesh->getVertices().end(); v_it++, i++)\n\t{\n\t\tcurDir[i][0] = Vec3(triMesh->normals[i][0], triMesh->normals[i][1], triMesh->normals[i][2]);\n\t\tcurDir[i][1] = Vec3(triMesh->pdir1[i][0], triMesh->pdir1[i][1], triMesh->pdir1[i][2]);\n\t\tcurDir[i][2] = Vec3(triMesh->pdir2[i][0], triMesh->pdir2[i][1], triMesh->pdir2[i][2]);\n\t\tcurMag[i].first = fabs(triMesh->curv1[i]);\n\t\tcurMag[i].second = fabs(triMesh->curv2[i]);\n\t\tv_anisotropy[i] = fabs(fabs(triMesh->curv1[i]) - fabs(triMesh->curv2[i]));\n\t}\n\n\tdelete triMesh;\n}\nvoid MeshProperty::computeFaceTensor(std::vector<Tensor>& faceAnis)\n{\n\t//avg of vertex tensor\n\n\tif (myMesh == NULL) return;\n\n\tcout << \"compute tensor field on triangles(metric type:\" << metricVariation << \" metric parameter:\" << metricParameter << \")\" << endl;\n\n\tTensor::computeTriangleCurvature(myMesh, faceAnis);\n\n\tif (metricVariation == 0)\n\t{\n\t\tfor (unsigned i = 0; i < faceAnis.size(); i++)\n\t\t{\n\t\t\tTensor& ft = faceAnis[i];\n\t\t\tdouble s = 1 + metricParameter*abs(ft.mag2 - ft.mag1);\n\t\t\ts *= s;\n\t\t\tft.mag2 = 1 / s;\n\t\t\tft.mag1 = 1;\n\t\t}\n\t}\n\telse if (metricVariation == 1)\n\t{\n\t\tfor (unsigned i = 0; i < faceAnis.size(); i++)\n\t\t{\n\t\t\tTensor& ft = faceAnis[i];\n\t\t\tdouble s = 1 + metricParameter*abs(ft.mag2 - ft.mag1);\n\t\t\ts *= s;\n\t\t\tft.mag2 = 1;\n\t\t\tft.mag1 = s;\n\t\t}\n\t}\n\telse\n\t{\n\t\tfor (unsigned i = 0; i < faceAnis.size(); i++)\n\t\t{\n\t\t\tTensor& ft = faceAnis[i];\n\t\t\tdouble s = 1 + metricParameter*abs(ft.mag2 - ft.mag1);\n\t\t\ts *= s;\n\t\t\tft.mag2 = 1 / s;\n\t\t\tft.mag1 = s;\n\t\t}\n\t}\n}\nvoid FeatureLine::computeMultiScaleFeatures(std::vector<bool>& boundaryEdge)\n{\n\t/* compute multiscale local geometric features both for vertex tensors and feature prunning*/\n\t/*for vertex tensor, need to be avaraged by multi scale tensors*/\n\n\tunsigned numV = myMesh->getVertices().size();\n\tstd::vector<double> sharpness(numV, 1);\n\tstd::vector<double> ridgeness(numV, 1);\n\tstd::vector<double> anisotropy(numV, 1);\n\n\tunsigned numIter = 0;\n\tfor (double i = sharpnessRangeLow; i <= sharpnessRangeHigh; i += sharpnessRangeInterval, numIter++){}\n\tcout << numIter << \" scales.\" << endl;\n\n\tnumIter = 0;\n\tfor (double i = sharpnessRangeLow; i <= sharpnessRangeHigh; i += sharpnessRangeInterval)\n\t{\n\t\tcomputeVertexProperty_TRIMESH(i);\n\t\tfor (unsigned j = 0; j < numV; j++)\n\t\t\tanisotropy[j] += v_anisotropy[j];\n\t}\n\tnumIter++;\n\n\n\t//avg of vers; f_xxx is for pruning of features;\n\tv_sharpness.swap(sharpness);\n\tv_ridgeness.swap(ridgeness);\n\tv_anisotropy.swap(anisotropy);\n\tf_sharpness.clear(); f_sharpness.resize(crestAttris[0].size(), 0);\n\tf_anisotropy.clear(); f_anisotropy.resize(crestAttris[0].size(), 0);\n\tf_ridgeness.clear(); f_ridgeness.resize(crestAttris[0].size(), 0);\n\tconst auto& fts = myMesh->getFIter();\n\tfor (unsigned i = 0; i < crestEdges.size(); i++)\n\t{\n\t\tif (crestEdges[i][2] > myMesh->getFaces().size()) continue;\n\t\tdouble esp = 0;\n\t\tdouble eani = 0;\n\t\tdouble erd = 0;\n\t\tfor (unsigned j = 0; j < 3; j++)\n\t\t{\n\t\t\tesp += v_sharpness[fts[crestEdges[i][2]]->vertex_iter(j)->id()];\n\t\t\teani += v_anisotropy[fts[crestEdges[i][2]]->vertex_iter(j)->id()];\n\t\t\terd += v_ridgeness[fts[crestEdges[i][2]]->vertex_iter(j)->id()];\n\t\t}\n\t\tf_anisotropy[crestPointsAttriID[crestEdges[i][0]]] += eani;\n\t\tf_ridgeness[crestPointsAttriID[crestEdges[i][0]]] += erd;\n\t\tf_sharpness[crestPointsAttriID[crestEdges[i][0]]] += esp;\n\t}\n}\n\n//We use the lib by Shin Yoshizawa for computing Crestline(ridges&varines), theoretically detailed in Paper: Fast and Robust Detection of Crest Lines on Mesh;\nvoid FeatureLine::computeCrestLine(std::vector<bool>& boundaryEdge)\n{\n\t//we modify the interface to carry in our input, such as the neighbores of each vertex;\n\t//When user want to compute crestline inside a patch whose frontier are salient features globally,\n\t//she wants those salient features become less/none salient. This happens when we want to refine the segmentation iteratively, which requiring dynamic multi-sacle features.\n\t//This is simply done with boundaryEdge, that is constraints, that neighbores of a vertices can only lie on one side of which. \n\n\tcout << \"compute crest line(scale:\" << crestline_scale << \")\" << endl;\n\n\tif (boundaryEdge.empty()) boundaryEdge.resize(myMesh->getEdges().size(), false);\n\n\tunsigned vNum = myMesh->getVertices().size();\n\tunsigned fNum = myMesh->getFaces().size();\n\n\t//write vertices, faces, and adjcency of vers;\n\tdouble* vertices = new double[vNum * 3];\n\tunsigned i = 0;\n\tfor (auto v_it = myMesh->getVertices().begin(); v_it != myMesh->getVertices().end(); v_it++)\n\t{\n\t\tvertices[i * 3 + 0] = v_it->coordinate().x;\n\t\tvertices[i * 3 + 1] = v_it->coordinate().y;\n\t\tvertices[i * 3 + 2] = v_it->coordinate().z;\n\t\ti++;\n\t}\n\n\tunsigned* faces = new unsigned[fNum * 3];\n\ti = 0;\n\tstd::vector<unsigned> faceMap;\n\tfor (auto if_it = myMesh->getFaces().begin(); if_it != myMesh->getFaces().end(); if_it++)\n\t{\n\t\tunsigned cnt = 0;\n\t\tfor (unsigned j = 0; j<3; j++)\n\t\t{\n\t\t\tif (boundaryEdge[if_it->edge_iter(j)->id()])\n\t\t\t{\n\t\t\t\tcnt++;\n\t\t\t}\n\t\t}\n\t\tif (cnt>1) { fNum--; continue; }\n\t\tfaceMap.push_back(if_it->id());\n\n\t\tfaces[i * 3 + 0] = if_it->vertex_iter(0)->id();\n\t\tfaces[i * 3 + 1] = if_it->vertex_iter(1)->id();\n\t\tfaces[i * 3 + 2] = if_it->vertex_iter(2)->id();\n\t\ti++;\n\t}\n\n\tconst auto& vts = myMesh->getVIter();\n\tstd::vector<std::vector<int> > vadjs(myMesh->getVertices().size());\n\tfor (auto v_it = myMesh->getVertices().begin(); v_it != myMesh->getVertices().end(); v_it++)\n\t{\n\t\tstd::vector<int> usedVers;\n\t\tusedVers.push_back(v_it->id());\n\t\tstd::vector<int> frontVerts = usedVers;\n\t\tunsigned count = 0;\n\t\twhile (count<crestline_scale)\n\t\t{\n\t\t\tcount++;\n\t\t\tstd::vector<int> nextVerts(1, -1);\n\t\t\twhile (!frontVerts.empty())\n\t\t\t{\n\t\t\t\tauto vft = vts[frontVerts.back()];\n\t\t\t\tfrontVerts.pop_back();\n\n\t\t\t\tfor (unsigned i = 0; i<vft->vertex_iter().size(); i++)\n\t\t\t\t{\n\t\t\t\t\tunsigned tid = vft->vertex_iter()[i]->id();\n\t\t\t\t\tif (std::find(usedVers.begin(), usedVers.end(), tid) == usedVers.end() && std::find(nextVerts.begin(), nextVerts.end(), tid) == nextVerts.end())\n\t\t\t\t\t{\n\t\t\t\t\t\tif (!boundaryEdge[vft->edge_iter()[i]->id()])\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tusedVers.push_back(tid); nextVerts.push_back(tid);\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\tnextVerts.erase(nextVerts.begin());\n\t\t\tfrontVerts.swap(nextVerts);\n\t\t}\n\t\tusedVers.erase(usedVers.begin());\n\t\tvadjs[v_it->id()] = usedVers;\n\t}\n\n\tint** vadj = NULL;\n\tint* vadjNum = NULL;\n\n\tunsigned vn = vadjs.size();\n\tvadj = new int*[vn];\n\tvadjNum = new int[vn];\n\tfor (int i = 0; i<vn; i++)\n\t{\n\t\tvadj[i] = new int[vadjs[i].size()];\n\t\tvadjNum[i] = vadjs[i].size();\n\t\tfor (int j = 0; j<vadjs[i].size(); j++)\t\t\n\t\t{\n\t\t\tvadj[i][j] = vadjs[i][j];\n\t\t}\n\t}\n\n\tunsigned pNum, cNum, eNum;\n\tdouble* fPoints;\n\tunsigned* fPointType;\n\tdouble* fFeature;\n\tunsigned* fEdges;\n\tunsigned offset;\n\tcrestLineGen(vadj, vadjNum, vertices, vNum, faces, fNum, crestline_scale, 1,\n\t\tpNum, cNum, eNum, fPoints, fPointType, fFeature, fEdges, crestLineoffset);\n\n\t//read crestlines;\n\tVec3 tp; unsigned tid;\n\tcrestPoints.clear(); crestPointsAttriID.clear();\n\tfor (unsigned int i = 0; i<pNum; ++i)\n\t{\n\t\ttp.x = fPoints[i * 3 + 0];\n\t\ttp.y = fPoints[i * 3 + 1];\n\t\ttp.z = fPoints[i * 3 + 2];\n\t\tcrestPoints.push_back(tp);\n\t\tcrestPointsAttriID.push_back(fPointType[i]);\n\t}\n\tcrestAttris.clear(); crestAttris.resize(3);\n\tstd::vector<double> &ridge = crestAttris[0];\n\tstd::vector<double> &sphere = crestAttris[1];\n\tstd::vector<double> &cynlinder = crestAttris[2];\n\tfor (unsigned int i = 0; i<cNum; ++i)\n\t{\n\t\tridge.push_back(fFeature[i * 3 + 0]);\n\t\tsphere.push_back(fFeature[i * 3 + 1]);\n\t\tcynlinder.push_back(fFeature[i * 3 + 2]);\n\t}\n\tstd::vector<unsigned> te(3);\n\tcrestEdges.clear();\n\tcrestEdgesVisible.clear();\n\tfor (unsigned i = 0; i<eNum; i++)\n\t{\n\t\tif (fEdges[i * 3 + 2] >= fNum) continue;\n\n\t\tte[0] = fEdges[i * 3 + 0];\n\t\tte[1] = fEdges[i * 3 + 1];\n\t\tte[2] = faceMap[fEdges[i * 3 + 2]];\n\t\tcrestEdges.push_back(te);\n\t\tcrestEdgesVisible.push_back(true);\n\t}\n\n\tdelete vertices;\n\tdelete faces;\n\tfor (int i = 0; i<vn; i++)\n\t\tdelete vadj[i];\n\tdelete vadjNum;\n\tdelete fPointType;\n\tdelete fFeature;\n\tdelete fEdges;\n}\nvoid FeatureLine::tuningCrestLine(double anisStrength, double sharpness, double ridgeness)\n{\n\t//datas are kept, filtered is active by crestEdgesVisible. \n\t//invisible crestEdge will not be shown and used for segmentation.\n\n\tstd::vector<double> &anis = f_anisotropy;\n\tstd::vector<double> &ridge = f_ridgeness;\n\tstd::vector<double> &sharp = f_sharpness;\n\n\tstd::vector<bool> visibleAttri(ridge.size(), true);\n\n\tdouble maxVal, minVal;\n\tmaxVal = *std::max_element(sharp.begin(), sharp.end());\n\tminVal = *std::min_element(sharp.begin(), sharp.end());\n\tdouble rang = maxVal - minVal;\n\tfor (unsigned i = 0; i<ridge.size(); i++)\n\t{\n\t\tif (rang>0 && ((sharp[i] - minVal) / rang)<sharpness)\n\t\t{\n\t\t\tvisibleAttri[i] = false;\n\t\t}\n\t}\n\n\tmaxVal = *std::max_element(anis.begin(), anis.end());\n\tminVal = *std::min_element(anis.begin(), anis.end());\n\trang = maxVal - minVal;\n\tfor (unsigned i = 0; i<anis.size(); i++)\n\t{\n\t\tif (rang>0 && ((anis[i] - minVal) / rang)<anisStrength)\n\t\t{\n\t\t\tvisibleAttri[i] = false;\n\t\t}\n\t}\n\n\tmaxVal = *std::max_element(ridge.begin(), ridge.end());\n\tminVal = *std::min_element(ridge.begin(), ridge.end());\n\trang = maxVal - minVal;\n\tfor (unsigned i = 0; i<ridge.size(); i++)\n\t{\n\t\tif (rang>0 && ((ridge[i] - minVal) / rang)<ridgeness)\n\t\t{\n\t\t\tvisibleAttri[i] = false;\n\t\t}\n\t}\n\n\tfor (unsigned i = 0; i<crestEdgesVisible.size(); i++)\n\t{\n\t\tunsigned &v1 = crestEdges[i][0];\n\t\tunsigned &v2 = crestEdges[i][1];\n\t\tif (visibleAttri[crestPointsAttriID[v1]] == false || visibleAttri[crestPointsAttriID[v2]] == false)\n\t\t\tcrestEdgesVisible[i] = false;\n\t\telse\n\t\t\tcrestEdgesVisible[i] = true;\n\t}\n\n\tcout << \"crestline updated\" << endl;\n}\n\nvoid FeatureLine::featureGraphInitial()\n{\n\t//initialization of graph, representing nodes,edges,cells and the features.\n\tif (myMesh == NULL) return;\n\n\tstd::vector<EdgeFeature>& tef = graphFeature.ef;\n\tstd::vector<CellFeature>& tcf = graphFeature.cf;\n\ttef.clear(); tcf.clear();\n\ttef.resize(myMesh->getEdges().size());\n\ttcf.resize(myMesh->getFaces().size());\n\tfor (auto f_it = myMesh->getFaces().begin(); f_it != myMesh->getFaces().end(); f_it++)\n\t{\n\t\ttcf[f_it->id()].mid = f_it->center_point();\n\t\ttcf[f_it->id()].rep = f_it->center_point();\n\t\ttcf[f_it->id()].isBoundary = false;\n\t}\n\tfor (auto e_it = myMesh->getEdges().begin(); e_it != myMesh->getEdges().end(); e_it++)\n\t{\n\t\ttef[e_it->id()].mid = (e_it->vertex_iter(0)->coordinate() + e_it->vertex_iter(1)->coordinate())*0.5;\n\t\ttef[e_it->id()].rep = tef[e_it->id()].mid;\n\t\ttef[e_it->id()].lab = -1;\n\t\ttef[e_it->id()].isOriented = true;\n\t\ttef[e_it->id()].dualLength = -1;\n\t\ttef[e_it->id()].strength = 1;\n// \t\ttef[e_it->id()].isCut = false;\n\t}\n}\n\nvoid MeshSegment::init()\n{\n\tshowMesh=true;\n\tshowAnistropy=showRidgeness=showSharpness=false;\n\tcrestLineoffset=0;\n\n\tcrestPoints.clear(); crestPointsAttriID.clear();crestAttris.clear();\n\tcrestEdges.clear();crestEdgesVisible.clear();\n\n\tshowWeightGraph=false; showSegmentation=showSegmentationBoundary=true;\n\tfeatureExtParam = 0.0;\n\n\tfeatureType = 1;\n\tawardNormalized = false;\n\n\tgcFeaturePriority=1;\n\tgcIsMerge=true;\n\n\tsegNumber = 1;\n\tvertexLabel.clear();\n\n\tisWatershedMerge = true;\n\tisMergeSmallPatch = true;\n\tsmallPatchThres= 5.0;\n\twaterShedMergeParam = 3;\n\n\tautoBoundarySmooth=true;\n\tboundarySmoothTimes=3;\n\tv_difference.clear();\n\n\tboundaryCurves.clear();\n\tboundaryJoints.clear();\n\n\tstrokeStrength=0.5;\n\tpaintParam = 0.05;\n\tpaintParamType = 0;\n\n\tshowWatershedField = false;\n\tmitani_Watershed_Ringsize  = 1;\n\tisAnisGeodesics_Watershed = true;\n\tisDualGraph_Watershed = true;\n\n\tuseAllFeatureLine = false;\n\n\tboundaryWidth = 2.0;\n\n\tm_interaction = NULL;\n\tstrokeSize = 1;\n\tisSmoothStroke = true;\n\n\tgraphCutLocally = false;\n\n\tpoints.clear();\tfaces.clear(); myMesh = NULL;\n\n\ttriMesh = NULL; strcpy(curvatureScale, \"0.\");\tstrcpy(curvatureSmooth, \"0.1\");\n\n}\n\nvoid MeshSegment::featureFromCrestline()\n{\n\t//crestline are not clean! may includes invalid/incorret indices;\n\t//only visible and valid feature edges are wrote to feature graph.\n\tif(myMesh == NULL) return;\n\n\tunsigned cnt = 0;\tunusedCrestline.clear(); unusedCrestline.resize(crestEdgesVisible.size(), false);//crestlines are shown in blue and red, invalid ones are shown in yellow. this is for debug.\n\tfor(unsigned i=0;i<crestEdgesVisible.size();i++)\n\t{\n\t\tunusedCrestline[i] = true;\tcnt++;\n\n\t\tif (!crestEdgesVisible[i])\n\t\t\tcontinue;\n\n\t\tunsigned faceID = crestEdges[i][2];\n\t\tif(faceID>myMesh->getFaces().size())\n\t\t{\n\t\t\tcrestEdgesVisible[i] = false;\n\t\t\tcontinue; // crest line data is not alway clean\n\t\t}\n\n\t\tunusedCrestline[i] = false;\tcnt--;\n\n\t\tauto f_it = myMesh->getFIter()[faceID];\n\n\t\tstd::vector<unsigned> edgeUsed;\n\t\tfor (unsigned j=0;j<2;j++)\n\t\t{\n\t\t\tunsigned vid = crestEdges[i][j];\n\t\t\tVec3 voe = crestPoints[crestEdges[i][j]];\n\t\t\t//simply check if the crestPoint is on the edge;\n\t\t\tfor (unsigned k=0;k<3;k++)\n\t\t\t{\n\t\t\t\tdouble dis=0;\n\t\t\t\tVec3 v1 = f_it->edge_iter(k)->vertex_iter(0)->coordinate();\n\t\t\t\tVec3 v2 = f_it->edge_iter(k)->vertex_iter(1)->coordinate();\n\t\t\t\tVec3 v12 = v1-v2;\n\t\t\t\tv1 = voe-v1; v2=voe-v2;\n\t\t\t\tif(abs(v1.length()+v2.length()-v12.length())< 1e-7) //when very close, then it is\n\t\t\t\t{\n\t\t\t\t\tgraphFeature.ef[f_it->edge_iter(k)->id()].lab = 1;\n\t\t\t\t\tedgeUsed.push_back(f_it->edge_iter(k)->id());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif(edgeUsed.size()==4)\n\t\t{//feature edge is on the edge;\n\t\t\tunsigned tid;\n\t\t\tfor (unsigned j=0;j<3;j++)\n\t\t\t{\n\t\t\t\tfor(unsigned k=j+1;k<4;k++)\n\t\t\t\t{\n\t\t\t\t\tif(edgeUsed[j]==edgeUsed[k])\n\t\t\t\t\t{\n\t\t\t\t\t\tgraphFeature.ef[edgeUsed[k]].lab = -1;\n\t\t\t\t\t\tk=4;j=4;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if (edgeUsed.size() == 3)\n\t\t{//feature edge go through one vertex;\n\t\t\tunsigned vind;\n\t\t\tdouble dis = DBL_MAX;\n\t\t\tunsigned tind;\n\t\t\tfor (unsigned k = 0; k < 3; k++)\n\t\t\t{\n\t\t\t\tVec3 v1 = f_it->vertex_iter(0)->coordinate();\n\t\t\t\tdouble tdis = min(v1.dot(crestPoints[crestEdges[i][0]]), v1.dot(crestPoints[crestEdges[i][1]]));\n\t\t\t\tif (tdis < dis)\n\t\t\t\t{\n\t\t\t\t\tdis = tdis; vind = k; \n\t\t\t\t\ttind = v1.dot(crestPoints[crestEdges[i][0]]) < v1.dot(crestPoints[crestEdges[i][1]]) ? 1 : 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\tunsigned te = f_it->opposite_edge(f_it->vertex_iter(vind))->id();\n\t\t\tgraphFeature.cf[faceID].rep = (crestPoints[crestEdges[i][0]] + crestPoints[crestEdges[i][1]])*0.5;\n\t\t\tgraphFeature.ef[te].rep = crestPoints[crestEdges[i][tind]];\n\n\t\t\tte = f_it->opposite_edge(f_it->vertex_iter((vind+1)%3))->id();\n\t\t\tgraphFeature.ef[te].rep = crestPoints[crestEdges[i][(tind+1)%2]];\n\t\t}\n\t\telse if (edgeUsed.size() == 2)\n\t\t{\n\t\t\t//general case;\n\t\t\tgraphFeature.cf[faceID].rep = (crestPoints[crestEdges[i][0]] + crestPoints[crestEdges[i][1]])*0.5;\n\t\t\tgraphFeature.ef[edgeUsed.front()].rep = crestPoints[crestEdges[i][0]];\n\t\t\tgraphFeature.ef[edgeUsed.back()].rep = crestPoints[crestEdges[i][1]];\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcnt++;\tunusedCrestline[i] = true;\n\t\t}\n\t}\n\n\tif (cnt != 0)\tcout << \"bad crestline edges:\" << cnt << endl;\n}\nvoid MeshSegment::featureFromSketches()\n{\n\t//user input sketches as new features;\n\tfor(unsigned i=0;i<userSketches.size();i++)\n\t{\n\t\tunsigned faceID = userSketches[i].fid;\n\t\tif (faceID>myMesh->getFaces().size()) continue; //double checks\n\n\t\tgraphFeature.ef[userSketches[i].e1].lab = 2;\n\t\tgraphFeature.ef[userSketches[i].e2].lab = 2;\n\n\t\tgraphFeature.cf[faceID].rep=userSketches[i].fpos;\n\t\tgraphFeature.ef[userSketches[i].e1].rep = userSketches[i].ep1;\n\t\tgraphFeature.ef[userSketches[i].e2].rep = userSketches[i].ep2;\n\t}\n}\n\nvoid MeshSegment::computeDualEdgeStrength()\n{\n\tdouble maxCost = 0;\n\t//the dual length is not the euclidean length of vector, but the length under our metric.\n\tfor (auto e_it = myMesh->getEdges().begin(); e_it != myMesh->getEdges().end(); e_it++)\n\t{\n\t\tgraphFeature.ef[e_it->id()].strength = 1;\n\t\tif (graphFeature.ef[e_it->id()].lab == -1)//a normal edge\n\t\t{\n\t\t\tgraphFeature.ef[e_it->id()].dualLength = 0;\n\t\t}\n\t\telse//a feature edge or sketched edge\n\t\t{\n\t\t\tif (graphFeature.ef[e_it->id()].lab == 1)\n\t\t\t{\n\t\t\t\tdouble edgeCost = 0;\n\t\t\t\tif (e_it->manifold())\n\t\t\t\t{\n\t\t\t\t\tMyMesh::FaceIter f[] = { e_it->face_iter(0), e_it->face_iter(1) };\n\t\t\t\t\tunsigned fid[] = { f[0]->id(), f[1]->id() };\n\t\t\t\t\tVec3 edgeVec = graphFeature.cf[f[0]->id()].rep - graphFeature.cf[f[1]->id()].rep;\n\t\t\t\t\tfor (unsigned k = 0; k < 2; k++)\n\t\t\t\t\t{\n\t\t\t\t\t\tVec2 edgeVec2D = Vec2(edgeVec.dot(faceAnis[fid[k]].dir1), edgeVec.dot(faceAnis[fid[k]].dir2));\n\t\t\t\t\t\tedgeCost += sqrt(pow(edgeVec2D.x, 2)*faceAnis[fid[k]].mag2 + pow(edgeVec2D.y, 2)*faceAnis[fid[k]].mag1);// two directions of tensor are swapped, since we computed dual edge's cost; mag1>mag2;\n\t\t\t\t\t}\n\t\t\t\t\tedgeCost = edgeCost*0.5;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tMyMesh::FaceIter f[] = { e_it->face_iter(0) };\n\t\t\t\t\tunsigned fid[] = { f[0]->id(), f[1]->id() };\n\t\t\t\t\tVec3 edgeVec = graphFeature.cf[f[0]->id()].rep - graphFeature.ef[e_it->id()].rep;\n\t\t\t\t\tfor (unsigned k = 0; k < 1; k++)\n\t\t\t\t\t{\n\t\t\t\t\t\tVec2 edgeVec2D = Vec2(edgeVec.dot(faceAnis[fid[k]].dir1), edgeVec.dot(faceAnis[fid[k]].dir2));// two direction were swapped, since we computed dual edge's cost; and in faceAnis, mag1>mag2;\n\t\t\t\t\t\tedgeCost += sqrt(pow(edgeVec2D.x, 2)*faceAnis[fid[k]].mag2 + pow(edgeVec2D.y, 2)*faceAnis[fid[k]].mag1);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tgraphFeature.ef[e_it->id()].dualLength = edgeCost;\n\t\t\t\tmaxCost = max(maxCost, edgeCost);\n\t\t\t}\n\t\t}\n\t\tmaxCost = max(maxCost, e_it->cost());\n\t}\n\tfor (auto e_it = myMesh->getEdges().begin(); e_it != myMesh->getEdges().end(); e_it++)\n\t{\n\t\tif (graphFeature.ef[e_it->id()].lab == 2)\n\t\t{\n\t\t\tgraphFeature.ef[e_it->id()].dualLength = 10 * maxCost;\n\t\t}\n\t}\n}\nvoid MeshSegment::computeDualEdgeCostAndLength()\n{\n\tfor (auto e_it = myMesh->getEdges().begin(); e_it != myMesh->getEdges().end(); e_it++)\n\t{\n\t\tif (e_it->manifold())\n\t\t{\n\t\t\tMyMesh::FaceIter f[] = { e_it->face_iter(0), e_it->face_iter(1) };\n\t\t\tunsigned fid[] = { f[0]->id(), f[1]->id() };\n\t\t\tVec3 edgeVec = graphFeature.cf[f[0]->id()].rep - graphFeature.cf[f[1]->id()].rep;\n\t\t\tdouble edgeCost = 0;\n\t\t\tfor (unsigned k = 0; k < 2; k++)\n\t\t\t{\n\t\t\t\tVec2 edgeVec2D = Vec2(edgeVec.dot(faceAnis[fid[k]].dir1), edgeVec.dot(faceAnis[fid[k]].dir2));\n\t\t\t\tedgeCost += sqrt(pow(edgeVec2D.x, 2)*faceAnis[fid[k]].mag1 + pow(edgeVec2D.y, 2)*faceAnis[fid[k]].mag2);\n\t\t\t}\n\t\t\te_it->cost() = edgeCost*0.5;\n\t\t\t//feature award;\n\t\t\tif (graphFeature.ef[e_it->id()].lab != -1)\n\t\t\t{\n\t\t\t\tgraphFeature.ef[e_it->id()].dualLength = edgeVec.length();\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tMyMesh::FaceIter f[] = { e_it->face_iter(0) };\n\t\t\tunsigned fid[] = { f[0]->id(), f[1]->id() };\n\t\t\tVec3 edgeVec = graphFeature.cf[f[0]->id()].rep - graphFeature.ef[e_it->id()].rep;\n\t\t\tdouble edgeCost = 0;\n\t\t\tfor (unsigned k = 0; k < 1; k++)\n\t\t\t{\n\t\t\t\tVec2 edgeVec2D = Vec2(edgeVec.dot(faceAnis[fid[k]].dir1), edgeVec.dot(faceAnis[fid[k]].dir2));// two direction were swapped, since we computed dual edge's cost; and in faceAnis, mag1>mag2;\n\t\t\t\tedgeCost += sqrt(pow(edgeVec2D.x, 2)*faceAnis[fid[k]].mag1 + pow(edgeVec2D.y, 2)*faceAnis[fid[k]].mag2);\n\t\t\t}\n\t\t\te_it->cost() = edgeCost + 1e-6; //make sure weight is bigger than 0;\n\t\t\t//feature award;\n\t\t\tif (graphFeature.ef[e_it->id()].lab != -1)\n\t\t\t{\n\t\t\t\tgraphFeature.ef[e_it->id()].dualLength = edgeVec.length();\n\t\t\t}\n\t\t}\n\t}\n}\nvoid MeshSegment::updateGlabalAwardAlpha()\n{\n\tif (!edgeWeightParameter.empty())\n\t{\n\t\tdouble brushParameter = paintParam;\n\t\tif (paintParamType == 0)\n\t\t{\n\t\t\tif (m_interaction->scribbleType == Interaction::CONCEAL)\n\t\t\t\tbrushParameter = -paintParam;\n\t\t\tfor (auto e_it = myMesh->getEdges().begin(); e_it != myMesh->getEdges().end(); e_it++)\n\t\t\t{\n\t\t\t\tif (graphFeature.ef[e_it->id()].lab != -1)//a normal edge\n\t\t\t\t{\n\t\t\t\t\tedgeWeightParameter[e_it->id()] += brushParameter;\n\t\t\t\t}\n\t\t\t}\n\t\t\tgraphFeature.alpha += brushParameter;\n\t\t}\n\t\telse if (paintParamType == 1)\n\t\t{\n\t\t\tif (m_interaction->scribbleType == Interaction::CONCEAL)\n\t\t\t\tbrushParameter = 1.0 / paintParam;\n\t\t\tfor (auto e_it = myMesh->getEdges().begin(); e_it != myMesh->getEdges().end(); e_it++)\n\t\t\t{\n\t\t\t\tif (graphFeature.ef[e_it->id()].lab != -1)//a normal edge\n\t\t\t\t{\n\t\t\t\t\tedgeWeightParameter[e_it->id()] *= brushParameter;\n\t\t\t\t}\n\t\t\t}\n\t\t\tgraphFeature.alpha *= brushParameter;\n\t\t}\n\t}\n}\nvoid MeshSegment::updateLocalAwardAlpha(std::vector<unsigned>& fs)\n{\n\tcout << \"Boost/Decrease Alpha by \";\n\tif (paintParamType == 0)\n\t{\n\t\tif (m_interaction->scribbleType == Interaction::REVEAL)\n\t\t\tcout << \"+\";\n\t\telse\n\t\t\tcout << \"-\";\n\t}\n\telse if (paintParamType == 1)\n\t{\n\t\tif (m_interaction->scribbleType == Interaction::REVEAL)\n\t\t\tcout << \"*\";\n\t\telse\n\t\t\tcout << \"/\";\n\t}\n\tif (paintParamType != 2)\n\t\tcout << \" \" << paintParam << endl;\n\telse\n\t\tcout << \"a fix number:\" << 1e-20 << endl;\n\n\tconst auto& faceIters = myMesh->getFIter();\n\tstd::set<int> enhancedEdge;\n\tfor (int i = 0; i < fs.size(); i++)\n\t{\n\t\tfor (int j = 0; j < 3; j++)\n\t\t{\n\t\t\tauto eit = faceIters[fs[i]]->edge_iter(j);\n\t\t\tif (graphFeature.ef[eit->id()].lab != -1)\n\t\t\t{\n\t\t\t\tenhancedEdge.insert(eit->id());\n\t\t\t}\n\t\t}\n\t}\n\tdouble brushParameter = paintParam;\n\tif (paintParamType == 0)\n\t{\n\t\tif (m_interaction->scribbleType == Interaction::CONCEAL)\n\t\t\tbrushParameter = -paintParam;\n\t\tfor (auto i = enhancedEdge.begin(); i != enhancedEdge.end(); i++)\n\t\t{\n\t\t\tedgeWeightParameter[*i] += brushParameter;\n\t\t}\n\t}\n\telse if (paintParamType == 1)\n\t{\n\t\tif (m_interaction->scribbleType == Interaction::CONCEAL)\n\t\t\tbrushParameter = 1.0 / paintParam;\n\t\tfor (auto i = enhancedEdge.begin(); i != enhancedEdge.end(); i++)\n\t\t{\n\t\t\tedgeWeightParameter[*i] *= brushParameter;\n\t\t}\n\t}\n\telse\n\t{\n\t\tfor (auto i = enhancedEdge.begin(); i != enhancedEdge.end(); i++)\n\t\t{\n\t\t\tedgeWeightParameter[*i] = 1e-20;\n\t\t}\n\t}\n\tcout << \"max weight param:\" << *std::max_element(edgeWeightParameter.begin(), edgeWeightParameter.end()) << endl;\n\tcout << \"min weight param:\" << *std::min_element(edgeWeightParameter.begin(), edgeWeightParameter.end()) << endl;\n}\nvoid MeshSegment::getWeights(std::vector<double>& param, std::vector<double>& edgeWeight, std::vector<double>& edgeAward, std::vector<bool>& featureEdges)\n{\n\tif (param.empty())\n\t{\n\t\tedgeWeightParameter.resize(myMesh->getEdges().size(), graphFeature.alpha);\n\t}\n\n\tedgeWeight.clear(); edgeWeight.resize(myMesh->getEdges().size());\n\tedgeAward.clear(); edgeAward.resize(myMesh->getEdges().size(), 0);\n\tfeatureEdges.clear(); featureEdges.resize(myMesh->getEdges().size(), false);\n\tfor (auto e_it = myMesh->getEdges().begin(); e_it != myMesh->getEdges().end(); e_it++)\n\t{\n\t\tauto tc = e_it->cost();\n\n\t\tdouble edgeParam = param[e_it->id()];\n\t\tif (graphFeature.ef[e_it->id()].lab != -1)\n\t\t{\n\t\t\tif (awardNormalized)\n\t\t\t{\n\t\t\t\tdouble normalizationParam = edgeParam;\n\t\t\t\tdouble anisVal = graphFeature.ef[e_it->id()].strength;\n\t\t\t\tdouble K = 1 - exp(-0.5 * normalizationParam*(anisVal));\n\t\t\t\tedgeAward[e_it->id()] = tc * (1 + K);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tedgeAward[e_it->id()] = edgeParam * graphFeature.ef[e_it->id()].dualLength *graphFeature.ef[e_it->id()].strength;\n\t\t\t}\n\n\t\t\tedgeWeight[e_it->id()] = tc - edgeAward[e_it->id()];\n\t\t\tfeatureEdges[e_it->id()] = true;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tedgeWeight[e_it->id()] = tc;\n\t\t}\n\t}\n}\n\nvoid MeshSegment::featureToCurves()\n{\n\t//group features to curves;\n\n\tstd::vector<std::vector<unsigned> > featureEdges;\n\tstd::vector<std::vector<unsigned> > edgeInFaces(myMesh->getFaces().size());\n\t//this is only correct in an oriented mesh;\n\tfor(auto e_it=myMesh->getEdges().begin();e_it!=myMesh->getEdges().end();e_it++)\n\t{\n\t\tif(graphFeature.ef[e_it->id()].lab ==-1 || !e_it->manifold()) continue;\n\n\t\tstd::vector<unsigned> newEdge;\n\t\tif(e_it->face_iter(0)->next_vertex(e_it->vertex_iter(0))==e_it->vertex_iter(1))\n\t\t{\n\t\t\tnewEdge.push_back(e_it->face_iter(0)->id());\n\t\t\tnewEdge.push_back(e_it->face_iter(1)->id());\n\t\t}\n\t\telse\n\t\t{\n\t\t\tnewEdge.push_back(e_it->face_iter(1)->id());\n\t\t\tnewEdge.push_back(e_it->face_iter(0)->id());\n\t\t}\n\t\tnewEdge.push_back(e_it->id());\n\t\tfeatureEdges.push_back(newEdge);\n\n\t\tedgeInFaces[newEdge[0]].push_back(featureEdges.size()-1);\n\t\tedgeInFaces[newEdge[1]].push_back(featureEdges.size()-1);\n\t}\n\n\t//feature lines;\n\tfeatureLines.clear();\n\n\tgcFeatures.clear();\n\tstd::vector<bool> edgeUsed(featureEdges.size(),false);\n\tunsigned groupNum=0;\n\twhile(true)\n\t{\n\n\t\tunsigned eid = std::find(edgeUsed.begin(),edgeUsed.end(),false) - edgeUsed.begin();\n\t\tif(eid>=edgeUsed.size()) break;\n\n\t\tedgeUsed[eid]=true;\n\t\t//edgeFeatureLabels[featureEdges[eid][2]] = groupNum;\n\n\t\tstd::vector<unsigned> gcFeature;\n\t\tgcFeature.push_back(featureEdges[eid][2]);\n\t\tstd::vector<Vec3> featureLine;\n\t\tfeatureLine.push_back(graphFeature.ef[featureEdges[eid][2]].rep);\n\t\t//find group feature\n\t\tunsigned frontEdge = eid;\n\t\tunsigned frontFace = featureEdges[eid][1];\n\t\twhile(true)\n\t\t{\n\t\t\tif(edgeInFaces[frontFace].size()==1) break;\n\t\t\tunsigned nextEdge;\n\t\t\tfor(unsigned i=0;i<edgeInFaces[frontFace].size();i++)\n\t\t\t{\n\t\t\t\tif(edgeInFaces[frontFace][i]!=frontEdge)\n\t\t\t\t{\n\t\t\t\t\tnextEdge = edgeInFaces[frontFace][i]; \n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(edgeUsed[nextEdge]) break;\n\n\t\t\tedgeUsed[nextEdge] = true;\n\t\t\t//edgeFeatureLabels[featureEdges[nextEdge][2]] = groupNum;\n\t\t\tgcFeature.push_back(featureEdges[nextEdge][2]);\n\t\t\tfeatureLine.push_back(graphFeature.ef[featureEdges[nextEdge][2]].rep);\n\n\t\t\tif(featureEdges[nextEdge][0]==frontFace)\n\t\t\t{\n\t\t\t\tfrontFace = featureEdges[nextEdge][1];\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tfrontFace = featureEdges[nextEdge][0];\n\t\t\t\tgraphFeature.ef[featureEdges[nextEdge][2]].isOriented = false;\n\t\t\t}\n\t\t\tfrontEdge=nextEdge;\n\t\t}\n\t\treverse(gcFeature.begin(), gcFeature.end());\n\t\treverse(featureLine.begin(), featureLine.end());\n\n\t\tfrontEdge = eid;\n\t\tfrontFace = featureEdges[eid][0];\n\t\twhile(true)\n\t\t{\n\t\t\tif(edgeInFaces[frontFace].size()==1) break;\n\t\t\tunsigned nextEdge;\n\t\t\tfor(unsigned i=0;i<edgeInFaces[frontFace].size();i++)\n\t\t\t{\n\t\t\t\tif(edgeInFaces[frontFace][i]!=frontEdge)\n\t\t\t\t{\n\t\t\t\t\tnextEdge = edgeInFaces[frontFace][i]; break;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(edgeUsed[nextEdge]) break;\n\n\t\t\tedgeUsed[nextEdge] = true;\n\t\t\t//edgeFeatureLabels[featureEdges[nextEdge][2]] = groupNum;\n\t\t\tgcFeature.push_back(featureEdges[nextEdge][2]);\n\t\t\tfeatureLine.push_back(graphFeature.ef[featureEdges[nextEdge][2]].rep);\n\n\t\t\tif(featureEdges[nextEdge][1]==frontFace)\n\t\t\t{\n\t\t\t\tfrontFace = featureEdges[nextEdge][0];\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tfrontFace = featureEdges[nextEdge][1];\n\t\t\t\tgraphFeature.ef[featureEdges[nextEdge][2]].isOriented = false;\n\t\t\t}\n\t\t\tfrontEdge=nextEdge;\n\t\t}\n\t\tif (!useAllFeatureLine && gcFeature.size() < 3)\n\t\t{\n\t\t\tfor (int f = 0; f < gcFeature.size(); f++)\n\t\t\t{\n\t\t\t\tgraphFeature.ef[gcFeature[f]].lab = -1;\n\t\t\t}\n\n\t\t}\n\t\telse\n\t\t{\n\t\t\tgroupNum++;\n\t\t\tgcFeatures.push_back(gcFeature);\n\n\t\t\tfeatureLines.push_back(featureLine);\n\t\t}\n\n\t}\n}\n\nvoid MeshSegment::mgraphInit(MGraph& mg)\n{\n\t//a data sturcture for graph cut. \n\n\tstd::vector<double> edgeWeight(myMesh->getEdges().size());\n\tstd::vector<double> edgeAward(myMesh->getEdges().size(), 0);\n\tstd::vector<bool> featureEdges(myMesh->getEdges().size(), false);\n\tgetWeights(edgeWeightParameter,edgeWeight, edgeAward, featureEdges);\n\n\tmg.vNum = myMesh->getVertices().size();\n\tmg.vs.clear(); mg.vs.resize(mg.vNum);\n\tmg.eNum = myMesh->getEdges().size();\n\tmg.es.clear(); mg.es.resize(mg.eNum);\n\n\tint i=0;\n\tfor(auto vit = myMesh->getVertices().begin(); vit!=myMesh->getVertices().end(); vit++)\n\t{\n\t\tmg.vs[i].id = i;\n\t\tfor(int j=0;j<vit->vertex_iter().size();j++)\n\t\t{\n\t\t\tmg.vs[i].vadjs.push_back(vit->vertex_iter()[j]->id());\n\t\t\tmg.vs[i].eadjs.push_back(vit->edge_iter()[j]->id());\n\t\t}\n\t\ti++;\n\t}\n\ti=0;\n\ttry\n\t{\n\t\tfor (auto eit = myMesh->getEdges().begin(); eit != myMesh->getEdges().end(); eit++)\n\t\t{\n\t\t\tmg.es[i].isCut = featureEdges[i];\n\t\t\tmg.es[i].n1 = eit->vertex_iter(0)->id();\n\t\t\tmg.es[i].n2 = eit->vertex_iter(1)->id();\n\t\t\tif (std::isnan(edgeWeight[i]) || std::isnan(edgeAward[i]))\n\t\t\t{\n\t\t\t\tthrow ;\n\t\t\t}\n\t\t\tmg.es[i].w = edgeWeight[i];\n\t\t\tmg.es[i].award = edgeAward[i];\n\t\t\tmg.es[i].ort = graphFeature.ef[i].isOriented;\n\t\t\ti++;\n\t\t}\n\t}\n\tcatch (double e)\n\t{\n\t\tstd::cout << \"The input graph weight has NAN...\\n\";\n\t}\n}\n\n//////////////////////////////////////////////////////////////////////////\n//compute over segmentation of mesh\n//requires everything of features, initialization of graph, partitioning algorithms, merging algorithms, and final smoothing.\nvoid MeshSegment::overSegmentation(unsigned ftype)\n{\n\tcout << \"-------------------- GRAPH PARTITION -------------\" << endl;\n\t//1. init GraphFeature data structure;\n\t{\n\t\tclock_t tstr = clock();\n\t\tfeatureGraphInitial();\n\t\tfeatureFromCrestline();\n\t\tfeatureFromSketches();\n\n\t\tcomputeFaceTensor(faceAnis);\n\t\tcomputeDualEdgeCostAndLength();\n\t\tcomputeDualEdgeStrength();\n\n\t\tfeatureToCurves();\n\n\t\tmgraphInit(mg);\n\n\t\tclock_t tinit = clock() - tstr;\n\t\tcout << \"alpha:\" << graphFeature.alpha << endl;\n\t\tcout << endl << \"graph initialization:\" << tinit / 1000 << \"sec\" << tinit % 1000 << \"mm\" << endl;\n\t}\n\n\n\tif (isDualGraph_Watershed)\n\t\tMitani_Watershed_Dual();\n\telse\n\t\tMitani_Watershed();\n\n\tgenPatchColor(patchColors, segNumber,false);\n\tgetBoundaryOfClusters();\n\n\tvertexLabelInit = vertexLabel;\n}\nvoid MeshSegment::regionMerging(MGraph& gph,\n\tstd::vector<unsigned>& vertexLabel,\n\tunsigned& labelId)\n{\n\tclock_t tstr = clock();\n\n\tlabelId = *std::max_element(vertexLabel.begin(), vertexLabel.end()) + 1;\n\n\tstd::vector<std::set<int> > adjVers(labelId);\n\tfor (int i = 0; i < (int)gph.es.size(); i++)\n\t{\n\t\tunsigned vid0 = min(vertexLabel[gph.es[i].n1], vertexLabel[gph.es[i].n2]);\n\t\tunsigned vid1 = max(vertexLabel[gph.es[i].n1], vertexLabel[gph.es[i].n2]);\n\t\tif (vid0 == vid1)continue;\n\t\tadjVers[vid0].insert(vid1);\n\t}\n\n\n\tstd::list< std::list< MGTriple > > pairClusterCost(labelId);\n\ttypedef std::list< std::list< MGTriple > >::iterator PCIter;\n\tstd::vector< PCIter > pCIter;\n\n\tint count = 0;\n\tMGTriple tmg;\n\tfor (PCIter pct = pairClusterCost.begin(); pct != pairClusterCost.end(); pct++, count++)\n\t{\n\t\tif (adjVers[count].empty())\n\t\t{\n\t\t\ttmg.j = count;\n\t\t\ttmg.val = 0;\n\t\t\tpct->push_back(tmg);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfor (std::set<int>::iterator ita = adjVers[count].begin(); ita != adjVers[count].end(); ita++)\n\t\t\t{\n\t\t\t\ttmg.j = *ita;\n\t\t\t\ttmg.val = 0;\n\t\t\t\tpct->push_back(tmg);\n\t\t\t}\n\t\t}\n\t\tpCIter.push_back(pct);\n\t}\n\n\tstd::list< MGTriple >::iterator tpc;\n\n\tfor (int i = 0; i < (int)gph.es.size(); i++)\n\t{\n\t\tunsigned vid0 = min(vertexLabel[gph.es[i].n1], vertexLabel[gph.es[i].n2]);\n\t\tunsigned vid1 = max(vertexLabel[gph.es[i].n1], vertexLabel[gph.es[i].n2]);\n\t\tif (vid0 == vid1)continue;\n\n\t\tfor (tpc = pCIter[vid0]->begin(); tpc != pCIter[vid0]->end(); tpc++)\n\t\t{\n\t\t\tif (tpc->j == vid1) break;\n\t\t}\n\n\t\ttpc->val += gph.es[i].w;\n\t}\n\n\t//algorithms;\n\tstd::vector<unsigned> newLabels;\n\tLMP_Merging(vertexLabel, pCIter, labelId, newLabels);\n\n\tvertexLabel.clear(); vertexLabel.resize(gph.vNum);\n\tlabelId = 0;\n\tstd::vector<bool> visitedVer(vertexLabel.size(), false);\n\tfor (size_t v = 0; v < gph.vNum; v++)\n\t{\n\t\tif (visitedVer[v] == true) continue;\n\n\t\tunsigned currentLabel = unsigned(newLabels[v]);\n\t\tstd::vector<MGraph::Vertex*> frontVer(1, &(gph.vs[v]));\n\t\twhile (!frontVer.empty())\n\t\t{\n\t\t\tMGraph::Vertex* fv = frontVer.back(); frontVer.pop_back();\n\t\t\tvertexLabel[fv->id] = labelId;\n\t\t\tfor (std::list<int>::iterator i = fv->vadjs.begin(); i != fv->vadjs.end(); i++)\n\t\t\t{\n\t\t\t\tMGraph::Vertex* adjv = &(gph.vs[*i]);\n\t\t\t\tif (visitedVer[adjv->id] == true) continue;\n\t\t\t\tif (unsigned(newLabels[adjv->id]) == currentLabel)\n\t\t\t\t{\n\t\t\t\t\tvisitedVer[adjv->id] = true;\n\t\t\t\t\tfrontVer.push_back(adjv);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tlabelId++;\n\t}\n\n\tcout << endl << \"cluster number after merging:\" << labelId << endl;\n\n\t//get boundary;\n\tdouble cutCost = 0;\n\tfor (int i = 0; i < (int)gph.es.size(); i++)\n\t{\n\t\tunsigned vs[] = { gph.es[i].n1, gph.es[i].n2 };\n\t\tif (vertexLabel[vs[0]] != vertexLabel[vs[1]])\n\t\t{\n\t\t\tgph.es[i].isCut = true;\n\t\t\tcutCost += gph.es[i].w;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tgph.es[i].isCut = false;\n\t\t}\n\t}\n\n\tclock_t tinit = clock() - tstr;\n\tcout << \"merging takes:\" << tinit / 1000 << \"sec\" << tinit % 1000 << \"mm\" << endl;\n\tcout << \"Cost:\" << cutCost << endl;\n}\nvoid MeshSegment::mergePartition()\n{\n\tboundaryCurves.clear();\n\tif(!gcIsMerge) return;\n\tcout << \"*   *   *   *   *   *  MERGE  *   *   *   *   *   *\" << endl;\n\n\t//just for color \n\tstd::vector<unsigned> tlabels = vertexLabel;\n\tunsigned patNum = segNumber;\n\n\t//merging\n\tvertexLabel=vertexLabelBeforeMerge;\n\n\tcout << \"alpha:\" << graphFeature.alpha << endl;\n\tmgraphInit(mg);\n\n\tdouble cutCost;\n\tregionMerging(mg, vertexLabel, segNumber);\n\n\tif (isMergeSmallPatch)\n\t{\n\t\tmergeSmallPatches();\n\t}\n\telse\n\t{\n\t\tfor(int i=0;i<mg.eNum;i++)\n\t\t{\n\t\t\tgraphFeature.ef[i].isCut = mg.es[i].isCut;\n\t\t}\n\t}\n\n\tif (autoBoundarySmooth)\n\t{\n\t\tcout << endl;\n\t\tboundarySmooth(true);\n\t}\n\n\tcout << \"\\n-----------------------------------------------------\" << endl;\n\n\t//label id for most of vertices should remain the same, causing least changes;\n\tpatchColorMinChanged(tlabels, patNum);\n}\n\nvoid MeshSegment::mergeSmallPatches()\n{\n\t//prioritized by patch size, similar as greedy merging, by weight between patches.\n\n\tauto& mesh = myMesh;\n\tstd::vector<unsigned>& vertexLabels = vertexLabel;\n\tdouble thres = smallPatchThres;\n\tunsigned& segNum = segNumber;\n\n\tdouble averageArea = 0;\n\tstd::vector<double> faceAreas(mesh->getFaces().size());\n\tfor (auto i = mesh->getFaces().begin(); i != mesh->getFaces().end(); i++)\n\t{\n\t\tfaceAreas[i->id()] = i->triangleCost(2);\n\t\taverageArea += faceAreas[i->id()];\n\t}\n\n\t{//in this case, we threshold by triangle number, this is for our algorithm.\n\t\taverageArea /= double(faceAreas.size());\n\t\tthres *= averageArea;\n\t}\n\n\t//initialize area of all clusters;\n\tstd::vector<double> scores(segNum, 0.0);\n\tfor (auto i = mesh->getFaces().begin(); i != mesh->getFaces().end(); i++)\n\t{\n\t\tunsigned v1 = i->vertex_iter(0)->id();\n\t\tunsigned v2 = i->vertex_iter(1)->id();\n\t\tunsigned v3 = i->vertex_iter(2)->id();\n\t\tif (vertexLabels[v1] == vertexLabels[v2] && vertexLabels[v1] == vertexLabels[v3])\n\t\t{\n\t\t\tscores[vertexLabels[v1]] += faceAreas[i->id()];\n\t\t}\n\t}\n\n\t//shared boundary length between clusters;\n\tstd::vector<double> sharesRow(segNum, 0.0);\n\tstd::vector<std::vector<double> > sharesMatrix(segNum, sharesRow);\n\tfor (auto i = mesh->getEdges().begin(); i != mesh->getEdges().end(); i++)\n\t{\n\t\tint vid0 = vertexLabels[i->vertex_iter(0)->id()];\n\t\tint vid1 = vertexLabels[i->vertex_iter(1)->id()];\n\t\tif (vid0 != vid1)\n\t\t{\n\t\t\tsharesMatrix[vid0][vid1] = sharesMatrix[vid1][vid0] += graphFeature.ef[i->id()].dualLength; //in dual graph case, use i->dualLength;\n\t\t}\n\t}\n\n\t//build adjacency and priority queue;\n\tstd::multiset<ClusterArea> clusterQueue;\n\tfor (int i = 0; i < scores.size(); i++)\n\t{\n\t\tclusterQueue.insert(ClusterArea(i, scores[i]));\n\t}\n\n\t//adjcents between clusters;\n\tstd::list<std::multiset<DecreaseOrderExt> > clusterAdjcencyList(segNum);\n\tstd::vector<std::list<std::multiset<DecreaseOrderExt> >::iterator> clusterAdjcency;\n\tfor (auto i = clusterAdjcencyList.begin(); i != clusterAdjcencyList.end(); i++)\n\t{\n\t\tclusterAdjcency.push_back(i);\n\t}\n\n\tfor (auto i = mesh->getEdges().begin(); i != mesh->getEdges().end(); i++)\n\t{\n\t\tint vid0 = vertexLabels[i->vertex_iter(0)->id()];\n\t\tint vid1 = vertexLabels[i->vertex_iter(1)->id()];\n\t\tif (vid0 != vid1)\n\t\t{\n\t\t\tif (clusterAdjcency[vid0]->find(DecreaseOrderExt(vid1, scores[vid1], sharesMatrix[vid0][vid1])) == clusterAdjcency[vid0]->end())\n\t\t\t\tclusterAdjcency[vid0]->insert(DecreaseOrderExt(vid1, scores[vid1], sharesMatrix[vid0][vid1]));\n\n\t\t\tif (clusterAdjcency[vid1]->find(DecreaseOrderExt(vid0, scores[vid0], sharesMatrix[vid0][vid1])) == clusterAdjcency[vid1]->end())\n\t\t\t\tclusterAdjcency[vid1]->insert(DecreaseOrderExt(vid0, scores[vid0], sharesMatrix[vid0][vid1]));\n\t\t}\n\t}\n\n\t//clusters\n\tstd::list<std::set<int>> clusters(segNum);\n\tstd::vector<std::list<std::set<int>>::iterator> iclusters;\n\tfor (auto i = clusters.begin(); i != clusters.end(); i++)\n\t{\n\t\ticlusters.push_back(i);\n\t}\n\tfor (int i = 0; i < vertexLabels.size(); i++)\n\t{\n\t\ticlusters[vertexLabels[i]]->insert(i);\n\t}\n\n\twhile (!clusterQueue.empty())\n\t{\n\t\tClusterArea ci = *clusterQueue.begin(); clusterQueue.erase(clusterQueue.begin());\n\t\tif (ci.m_val > thres)\n\t\t{\n\t\t\tbreak;\n\t\t}\n\t\tif (clusterAdjcency[ci.m_id]->empty())\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\n\t\tDecreaseOrderExt cj_ = *clusterAdjcency[ci.m_id]->begin();\n\t\tClusterArea cj(cj_.m_id, cj_.m_val);\n\n\t\tclusterAdjcency[ci.m_id]->erase(clusterAdjcency[ci.m_id]->begin()); //remove cj from ci's\n\n\t\tauto tp = clusterAdjcency[cj.m_id]->begin();\n\t\tfor (; tp != clusterAdjcency[cj.m_id]->end(); tp++)\n\t\t{\n\t\t\tif (tp->m_id == ci.m_id)\n\t\t\t\tbreak;\n\t\t}\n\t\tif (tp == clusterAdjcency[cj.m_id]->end())\n\t\t{\n\t\t\tcout << \"invalid merge\" << endl;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tclusterAdjcency[cj.m_id]->erase(tp);\n\t\t}\n\n\t\tauto i = std::find(clusterQueue.begin(), clusterQueue.end(), cj);\n\t\tif (i == clusterQueue.end())\n\t\t{\n\t\t\tcout << \"invalid reference\" << endl;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tclusterQueue.erase(i);\n\t\t}\n\n\t\t//0. merge ci to cj.\n\t\t//1. cj is still in clusterQueue, need to update it, the new area is not just sum of ci and cj.\n\t\t//2. clear ci's clusterAdjacency, and add adj to cj, if not existed in cj. add cj to ci's adjacency, if not existed.\n\n\t\t//0. merge ci to cj.\n\t\tfor (auto i = iclusters[ci.m_id]->begin(); i != iclusters[ci.m_id]->end(); i++)\n\t\t{\n\t\t\tvertexLabels[*i] = cj.m_id;\n\t\t}\n\t\ticlusters[cj.m_id]->insert(iclusters[ci.m_id]->begin(), iclusters[ci.m_id]->end());\n\t\ticlusters[ci.m_id]->clear();\n\n\n\t\t//1. cj is still in clusterQueue, need to update it, the new area is not just sum of ci and cj.\n\t\tdouble newScore;\n\t\tif (false)\n\t\t{//simple way, but incorrect, for instance, if ci,cj's area are both zero, then the sum is zero, however, the actual size is more than zero.\n\t\t\tnewScore = ci.m_val + cj.m_val;\n\t\t}\n\t\t\t{\n\t\t\t\tnewScore = 0;\n\n\t\t\t\t//I'll rewrite the part later. It doesn't need to revisit all triangles;\n\t\t\t\tfor (auto i = mesh->getFaces().begin(); i != mesh->getFaces().end(); i++)\n\t\t\t\t{\n\t\t\t\t\tunsigned v1 = i->vertex_iter(0)->id();\n\t\t\t\t\tunsigned v2 = i->vertex_iter(1)->id();\n\t\t\t\t\tunsigned v3 = i->vertex_iter(2)->id();\n\t\t\t\t\tif (vertexLabels[v1] == vertexLabels[v2] && vertexLabels[v1] == vertexLabels[v3] && vertexLabels[v1] == cj.m_id)\n\t\t\t\t\t{\n\t\t\t\t\t\tnewScore += faceAreas[i->id()];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\tclusterQueue.insert(ClusterArea(cj.m_id, newScore));\n\n\t\t//2. clear ci's clusterAdjacency, and add adj to cj, if not existed in cj.\n\t\tfor (auto i = clusterAdjcency[ci.m_id]->begin(); i != clusterAdjcency[ci.m_id]->end(); i++)\n\t\t{\n\t\t\tint ci_a = i->m_id; // for each cluster\n\n\t\t\t//if ci_a not in cj, then add to cj, if exist, then update their shared boundary, m_val_ext;\n\t\t\t//if cj not in ci_a, then add to ci_a, if exist, then update their shared boundary, m_val_ext;\n\t\t\tauto ip = clusterAdjcency[ci_a]->begin();\n\t\t\tfor (; ip != clusterAdjcency[ci_a]->end(); ip++)\n\t\t\t{\n\t\t\t\tif (ip->m_id == cj.m_id && ip->m_val == cj.m_val)\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (ip == clusterAdjcency[ci_a]->end())\n\t\t\t{\n\t\t\t\tclusterAdjcency[ci_a]->insert(DecreaseOrderExt(cj.m_id, newScore, i->m_val_ext));\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tdouble temp = ip->m_val_ext;\n\t\t\t\tclusterAdjcency[ci_a]->erase(ip);\n\t\t\t\tclusterAdjcency[ci_a]->insert(DecreaseOrderExt(cj.m_id, newScore, i->m_val_ext + temp));\n\t\t\t}\n\n\t\t\tip = clusterAdjcency[cj.m_id]->begin();\n\t\t\tfor (; ip != clusterAdjcency[cj.m_id]->end(); ip++)\n\t\t\t{\n\t\t\t\tif (ip->m_id == i->m_id && ip->m_val == i->m_val)\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (ip == clusterAdjcency[cj.m_id]->end())\n\t\t\t{\n\t\t\t\tclusterAdjcency[cj.m_id]->insert(DecreaseOrderExt(i->m_id, i->m_val, i->m_val_ext));\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tdouble temp = ip->m_val_ext;\n\t\t\t\tclusterAdjcency[cj.m_id]->erase(ip);\n\t\t\t\tclusterAdjcency[cj.m_id]->insert(DecreaseOrderExt(i->m_id, i->m_val, i->m_val_ext + temp));\n\t\t\t}\n\n\n\t\t\t//remove ci from ci_a\n\t\t\tip = clusterAdjcency[ci_a]->begin();\n\t\t\tfor (; ip != clusterAdjcency[ci_a]->end(); ip++)\n\t\t\t{\n\t\t\t\tif (ip->m_id == ci.m_id && ip->m_val == ci.m_val)\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (ip == clusterAdjcency[ci_a]->end())\n\t\t\t{\n\t\t\t\tcout << endl << ci_a << \" error \" << ci.m_id << \" \" << ci.m_val << endl;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tclusterAdjcency[ci_a]->erase(ip);\n\t\t\t}\n\t\t}\n\n\t\tclusterAdjcency[ci.m_id]->clear();\n\n\t\t//for all cj_a in cj, even though not appeared in ci, need to update cj_a's element cj...\n\t\tfor (auto i = clusterAdjcency[cj.m_id]->begin(); i != clusterAdjcency[cj.m_id]->end(); i++)\n\t\t{\n\t\t\tauto ip = clusterAdjcency[i->m_id]->begin();\n\t\t\tfor (; ip != clusterAdjcency[i->m_id]->end(); ip++)\n\t\t\t{\n\t\t\t\tif (ip->m_id == cj.m_id)\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (ip == clusterAdjcency[i->m_id]->end())\n\t\t\t{\n\t\t\t\tcout << \"bad reference\" << endl;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tclusterAdjcency[i->m_id]->erase(ip);\n\t\t\t\tclusterAdjcency[i->m_id]->insert(DecreaseOrderExt(cj.m_id, newScore, i->m_val_ext));\n\t\t\t}\n\t\t}\n\t}\n\n\t//update label;\n\tint ind = 0;\n\tfor (auto i = clusters.begin(); i != clusters.end(); i++)\n\t{\n\t\tif (i->empty())\n\t\t\tcontinue;\n\n\t\tfor (auto v = i->begin(); v != i->end(); v++)\n\t\t{\n\t\t\tvertexLabels[*v] = ind;\n\t\t}\n\n\t\tind++;\n\t}\n\tsegNum = ind;\n\n\tcout << endl << \"cluster number after merging(by removing small patches):\" << segNumber << endl;\n\tdouble cutCost = 0;\n\tfor (auto i = myMesh->getEdges().begin(); i != myMesh->getEdges().end(); i++)\n\t{\n\t\tunsigned vs[] = { i->vertex_iter(0)->id(), i->vertex_iter(1)->id() };\n\t\tif (vertexLabel[vs[0]] != vertexLabel[vs[1]])\n\t\t{\n\t\t\tgraphFeature.ef[i->id()].isCut = true;\n\t\t\tcutCost += mg.es[i->id()].w;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tgraphFeature.ef[i->id()].isCut = false;\n\t\t}\n\t}\n\tcout << \"Cost:\" << cutCost << endl;\n}\n\nvoid MeshSegment::getBoundaryOfClusters()\n{\n\tfor(auto e_it=myMesh->getEdges().begin();e_it!=myMesh->getEdges().end();e_it++)\n\t{\n\t\tunsigned vs[]={e_it->vertex_iter(0)->id(),e_it->vertex_iter(1)->id()};\n\t\tif(vertexLabel[vs[0]] != vertexLabel[vs[1]])\n\t\t\tgraphFeature.ef[e_it->id()].isCut = true;\n\t\telse\n\t\t\tgraphFeature.ef[e_it->id()].isCut = false;\n\t}\n}\n\n//smooth the curve network on 2d manifold domain\nbool MeshSegment::vertexMoveToLocalMinima(const std::vector<BoundaryVertex>& Vbs, unsigned i, BoundaryVertex& newBv)\n{\n\t//1. find the direction; 2. find the step size;\n\t//the energy function is sum of length of all vectors from source to neighbores, and the length is computed by our anis metric;\n\t//the direction is negative of gradient direction of energy function;\n\t//step is simply half of length from source to center of neighbores, or computed by lineSearch;\n\n\tconst BoundaryVertex& vb = Vbs[i];\n\tTensor& tvb = faceAnis[vb.fid];\n\n\tVec3 grad(0, 0, 0); //first order derivative\n\tstd::vector<Tensor> hsTensors; //second order derivative matrix\n\t//energy function is linear, process gradient of each neighbore and sum them up;\n\tfor (unsigned j = 0; j < vb.ngbs.size(); j++)\n\t{\n\t\tconst BoundaryVertex& nvb = Vbs[vb.ngbs[j]];\n\t\tTensor& tnvb = faceAnis[nvb.fid];\n\n\t\tVec3 v;\n\t\tv = vb.pos - nvb.pos;\n\t\tif (v.length() < 1e-4)\n\t\t{\n// \t\t\tcout << \"vertices are too close\";\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (false)\n\t\t{\n\t\t\thsTensors.push_back(lineSearchHessian(v, tvb));\n\t\t\thsTensors.push_back(lineSearchHessian(v, tnvb));\n\t\t}\n\n\t\tVec2 vecProjL = Vec2(v.dot(tvb.dir1), v.dot(tvb.dir2));\n\t\tdouble lenL = sqrt(pow(vecProjL.x, 2)*tvb.mag1 + pow(vecProjL.y, 2)*tvb.mag2);\n\t\tvecProjL.x *= tvb.mag1; vecProjL.y *= tvb.mag2;\n\t\tlenL *= 2;\n\t\tif (lenL < 1e-4)\n\t\t{\n\t\t\tvecProjL = Vec2(0, 0);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tvecProjL.x /= lenL;\n\t\t\tvecProjL.y /= lenL;\n\t\t}\n\n\t\tVec2 vecProjR = Vec2(v.dot(tnvb.dir1), v.dot(tnvb.dir2));\n\t\tdouble lenR = sqrt(pow(vecProjR.x, 2)*tnvb.mag1 + pow(vecProjR.y, 2)*tnvb.mag2);\n\t\tvecProjR.x *= tnvb.mag1; vecProjR.y *= tnvb.mag2;\n\t\tlenR *= 2;\n\t\tif (lenR < 1e-4)\n\t\t{\n\t\t\tvecProjR = Vec2(0, 0);\n\t\t}\n\t\telse{\n\t\t\tvecProjR.x /= lenR;\n\t\t\tvecProjR.y /= lenR;\n\t\t}\n\n\t\tv = vecProjL.x*tvb.dir1 + vecProjL.y*tvb.dir2;\n\t\tgrad += v;\n\t\tv = vecProjR.x*tnvb.dir1 + vecProjR.y*tnvb.dir2;\n\t\tgrad += v;\n\t}\n\n\tVec3 grad0 = grad;\n\tgrad.normalize();\n\tgrad = -grad;\n\n\t//step length\n\tVec3  p(0, 0, 0);\n\tfor (unsigned j = 0; j < vb.ngbs.size(); j++)\n\t{\n\t\tp += Vbs[vb.ngbs[j]].pos;\n\t}\n\tif (vb.ngbs.size() == 2)\n\t{\n\t\tp = p*0.5 - vb.pos;\n\t}\n\telse if (vb.ngbs.size() == 3)\n\t{\n\t\tp = p / 3.0 - vb.pos;\n\t}\n\telse\n\t{\n\t\tcout << \"smooth boundary error\" << endl;\n\t}\n\tdouble stepLen = p.length() /** 0.5*/;\n\n\t//step length by line search, all transport to tvb.dir1&tvb.dir2 frame;\n\tif (false)\n\t{\n\t\tVec3 norm = tvb.dir1.cross(tvb.dir2); norm.normalize();\n\t\tTensor hsTensor;\n\t\tfor (int j = 0; j < hsTensors.size(); j++)\n\t\t{\n\t\t\tTensor& f2 = hsTensors[j];\n\t\t\tVec3 tNorm = f2.dir1.cross(f2.dir2); tNorm.normalize();\n\t\t\tf2.dir1 = basicNormalTransport(tNorm, norm, f2.dir1);\n\t\t\tf2.dir2 = basicNormalTransport(tNorm, norm, f2.dir2);\n\n\t\t\tVec2 v1_, v2_;\n\t\t\tv1_.x = f2.dir1.dot(tvb.dir1); v1_.y = f2.dir1.dot(tvb.dir2);\n\t\t\tv2_.x = f2.dir2.dot(tvb.dir1); v2_.y = f2.dir2.dot(tvb.dir2);\n\n\t\t\tf2.mat[0][0] = f2.mag1*v1_.x*v1_.x + f2.mag2*v2_.x*v2_.x;\n\t\t\tf2.mat[0][1] = f2.mat[1][0] = f2.mag1*v1_.x*v1_.y + f2.mag2*v2_.x*v2_.y;\n\t\t\tf2.mat[1][1] = f2.mag1*v1_.y*v1_.y + f2.mag2*v2_.y*v2_.y;\n\n\t\t\tfor (unsigned i = 0; i < 2; i++)\n\t\t\t{\n\t\t\t\tfor (unsigned j = 0; j < 2; j++)\n\t\t\t\t{\n\t\t\t\t\thsTensor.mat[i][j] += f2.mat[i][j];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tTensor::makeTensor(tvb.dir1, tvb.dir2, hsTensor);\n\n\t\tVec2 f1 = Vec2(grad0.dot(hsTensor.dir1), grad0.dot(hsTensor.dir2));\n\t\tdouble denom = sqrt(pow(f1.x, 2)*hsTensor.mag1 + pow(f1.y, 2)*hsTensor.mag2);\n\t\tdouble stepLen0 = grad0.length() / denom;\n\n\t\t//if(stepLen0 > stepLen) cout<<\"yes\";\n\t\tstepLen = min(stepLen0, stepLen);\n\t\t//stepLen = stepLen0;\n\t}\n\n\t//new position\n\tp = vb.pos + grad * stepLen * 0.5;\n\n\tauto f_it = myMesh->getFIter()[vb.fid];\n\tstd::set<unsigned> usedFaces;\n\tfor (unsigned fn = 0; fn < 3; fn++)\n\t{\n\t\tauto vt = f_it->vertex_iter(fn);\n\t\tfor (unsigned fv = 0; fv < vt->edge_iter().size(); fv++)\n\t\t{\n\t\t\tauto et = vt->edge_iter()[fv];\n\t\t\tusedFaces.insert(et->face_iter(0)->id());\n\t\t\tif (et->manifold())\n\t\t\t{\n\t\t\t\tusedFaces.insert(et->face_iter(1)->id());\n\t\t\t}\n\t\t}\n\t}\n\n\t//project new position back to mesh; we only look at a small neighbores;\n\tstd::vector<double> disToTris;\n\tstd::vector<Vec3> projPoints;\n\tfor (auto fn = usedFaces.begin(); fn != usedFaces.end(); fn++)\n\t{\n\t\tauto f = myMesh->getFIter()[*fn];\n\t\tVec3 projp;\n\t\tdouble d = IsPointInTriangle(f->vertex_iter(0)->coordinate(),\n\t\t\tf->vertex_iter(1)->coordinate(), f->vertex_iter(2)->coordinate(), p, projp);\n\t\tdisToTris.push_back(d);\n\t\tprojPoints.push_back(projp);\n\t}\n\n\tunsigned leastId = 0;;\n\tdouble leastDis = DBL_MAX;\n\tfor (unsigned d = 0; d < disToTris.size(); d++)\n\t{\n\t\tif (disToTris[d] != -1 && disToTris[d] < leastDis)\n\t\t{\n\t\t\tleastDis = disToTris[d];\n\t\t\tleastId = d;\n\t\t}\n\t}\n\n\tauto it_face = usedFaces.begin();\n\tstd::advance(it_face, leastId);\n\tif (disToTris[leastId] == -1 || projPoints[leastId] == Vec3(0, 0, 0) || *it_face > myMesh->getFaces().size() /*|| leastDis > 1e-3*/)\n\t{\n\t\treturn false;\n\t}\n\telse\t//if it is in the neighborhood\n\t{\n\t\tnewBv.fid = *it_face;\n\t\tnewBv.pos = projPoints[leastId];\n\t\treturn true;\n\t}\n}\nvoid MeshSegment::boundarySmooth(bool doSmooth)\n{\n\tif(vertexLabel.empty()) return;\n\tcout << endl << \"smooth...\";\n\n\tclock_t tstr = clock();\n\n\tstd::vector<BoundaryVertex> Vbs;\n\n\t//init boundary network\n\tint newId = 0;\n\tstd::vector<int> VbMap(myMesh->getFaces().size(),-1);\n\tfor(auto e_it=myMesh->getEdges().begin();e_it!=myMesh->getEdges().end();e_it++)\n\t{\n\t\tif(graphFeature.ef[e_it->id()].isCut == false)continue;\n\n\t\tint vid1,vid2;\n\t\tif(e_it->manifold())\n\t\t{\n\t\t\tint fs[]={e_it->face_iter(0)->id(),e_it->face_iter(1)->id()};\n\t\t\tif(VbMap[fs[0]]==-1) \n\t\t\t{\n\t\t\t\tVbMap[fs[0]] = newId; newId++;\n\t\t\t\tVbs.push_back(BoundaryVertex());\n\t\t\t\tVbs.back().fid = fs[0];\n\t\t\t\tVbs.back().pos = graphFeature.cf[fs[0]].rep;\n\t\t\t}\n\t\t\tif(VbMap[fs[1]]==-1) \n\t\t\t{\n\t\t\t\tVbMap[fs[1]] = newId; newId++;\n\t\t\t\tVbs.push_back(BoundaryVertex());\n\t\t\t\tVbs.back().fid = fs[1];\n\t\t\t\tVbs.back().pos = graphFeature.cf[fs[1]].rep;\n\t\t\t}\n\t\t\tvid1 = VbMap[fs[0]];\n\t\t\tvid2 = VbMap[fs[1]];\n\n\t\t\tif (std::find(Vbs[vid1].ngbs.begin(), Vbs[vid1].ngbs.end(), vid2) == Vbs[vid1].ngbs.end())\n\t\t\t\tVbs[vid1].ngbs.push_back(vid2);\n\t\t\tif (std::find(Vbs[vid2].ngbs.begin(), Vbs[vid2].ngbs.end(), vid1) == Vbs[vid2].ngbs.end())\n\t\t\t\tVbs[vid2].ngbs.push_back(vid1);\n\t\t}\n\t}\n\n\t//smooth by anis tensor for several times.\n\tint smt = doSmooth ? boundarySmoothTimes : 0;\n\tfor (unsigned cnt = smt; cnt > 0; cnt--)\n\t{\n\t\tstd::vector<BoundaryVertex> newVbs = Vbs;\n\t\tfor (unsigned i = 0; i < Vbs.size(); i++) //smooth for each vertex\n\t\t{\n\t\t\tif (Vbs[i].ngbs.size() == 1) continue; //boundary fixed;\n\n\t\t\tBoundaryVertex newBv;\n\t\t\tif (vertexMoveToLocalMinima(Vbs, i, newBv))\n\t\t\t{\n\t\t\t\tnewVbs[i].fid = newBv.fid;\n\t\t\t\tnewVbs[i].pos = newBv.pos;\n\t\t\t}\n\t\t}\n\t\tVbs = newVbs;\n\t}\n\n\t//trace boundary curves from vertices and their adjacency.\n\tboundaryJoints.clear();\n\tfor(int i=0;i<Vbs.size();i++)\n\t{\n\t\tif(Vbs[i].ngbs.size()>2) boundaryJoints.push_back(Vbs[i].pos);\n\t}\n\tstd::vector<bool> vbUsed(Vbs.size(),false);\n\tboundaryCurves.clear();\n\twhile(true)\n\t{\n\t\tunsigned vid = std::find(vbUsed.begin(),vbUsed.end(),false) - vbUsed.begin();\n\t\tif(vid>=vbUsed.size()) break;\n\n\t\tvbUsed[vid]=true;\n\t\tif(Vbs[vid].ngbs.size()!=2) continue;\n\n\t\tstd::vector<int> boundFace;\n\t\tboundFace.push_back(vid);\n\n\t\tunsigned frontFace = Vbs[vid].ngbs.front();\n\t\twhile(Vbs[frontFace].ngbs.size()==2 && !vbUsed[frontFace])\n\t\t{\n\t\t\tboundFace.push_back(frontFace);\n\t\t\tvbUsed[frontFace]=true;\n\t\t\tif(!vbUsed[Vbs[frontFace].ngbs.front()])\n\t\t\t{\n\t\t\t\tfrontFace = Vbs[frontFace].ngbs.front();\n\t\t\t}\n\t\t\telse if(!vbUsed[Vbs[frontFace].ngbs.back()])\n\t\t\t{\n\t\t\t\tfrontFace = Vbs[frontFace].ngbs.back();\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif(Vbs[Vbs[frontFace].ngbs.front()].ngbs.size()==2)\n\t\t\t\t\tfrontFace = Vbs[frontFace].ngbs.back();\n\t\t\t\telse\n\t\t\t\t\tfrontFace = Vbs[frontFace].ngbs.front();\n\t\t\t}\n\t\t}\n\t\tboundFace.push_back(frontFace);\n\t\tvbUsed[frontFace]=true;\n\n\t\treverse(boundFace.begin(),boundFace.end());\n\n\t\tfrontFace = Vbs[vid].ngbs.back();\n\t\twhile(Vbs[frontFace].ngbs.size()==2 && !vbUsed[frontFace])\n\t\t{\n\t\t\tboundFace.push_back(frontFace);\n\t\t\tvbUsed[frontFace]=true;\n\t\t\tif(!vbUsed[Vbs[frontFace].ngbs.front()])\n\t\t\t{\n\t\t\t\tfrontFace = Vbs[frontFace].ngbs.front();\n\t\t\t}\n\t\t\telse if(!vbUsed[Vbs[frontFace].ngbs.back()])\n\t\t\t{\n\t\t\t\tfrontFace = Vbs[frontFace].ngbs.back();\n\t\t\t}\n\t\t\telse{\n\t\t\t\tif(Vbs[Vbs[frontFace].ngbs.front()].ngbs.size()==2)\n\t\t\t\t\tfrontFace = Vbs[frontFace].ngbs.back();\n\t\t\t\telse\n\t\t\t\t\tfrontFace = Vbs[frontFace].ngbs.front();\n\t\t\t}\n\t\t}\n\t\tboundFace.push_back(frontFace);\n\t\tvbUsed[frontFace]=true;\n\n\t\tstd::vector<Vec3> bds(boundFace.size());\n\t\tfor( int i=0;i<bds.size();i++)\n\t\t{\n\t\t\tbds[i] = Vbs[boundFace[i]].pos;\n\t\t}\n\t\tboundaryCurves.push_back(bds);\n\t}\n\n\t//special cases: degenerate cases;\n\tfor (auto e_it = myMesh->getEdges().begin(); e_it != myMesh->getEdges().end(); e_it++)\n\t{\n\t\tif (graphFeature.ef[e_it->id()].isCut == false)continue;\n\t\tint vid1, vid2;\n\t\ttry{\n\t\t\tif (e_it->manifold()){\n\t\t\t\tint fs[] = { e_it->face_iter(0)->id(), e_it->face_iter(1)->id() };\n\t\t\t\tvid1 = VbMap[fs[0]];\n\t\t\t\tvid2 = VbMap[fs[1]];\n\n\t\t\t\tif (vid1>Vbs.size())\n\t\t\t\t\tthrow vid1;\n\t\t\t\telse if (vid2 > Vbs.size())\n\t\t\t\t\tthrow vid2;\n\n\t\t\t\tif (Vbs[vid1].ngbs.size() == 3 && Vbs[vid2].ngbs.size() == 3)\n\t\t\t\t{\n// \t\t\t\t\tcout << \"trigger special case.\";\n\t\t\t\t\tstd::vector<Vec3> bds(2);\n\t\t\t\t\tbds[0] = Vbs[vid1].pos;\n\t\t\t\t\tbds[1] = Vbs[vid2].pos;\n\t\t\t\t\tboundaryCurves.push_back(bds);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tcatch (int e)\n\t\t{\n\t\t\tcout << \"Numeric issue\" << e << endl;\n\t\t}\n\t}\n\tcout<<\" done in \"<<clock()-tstr<<\"mm\"<<endl;\n}\n\n//////////////////////////////////////////////////////////////////////////\n//User Interaction of Segmentation\n//Locally update of segmentation.\nvoid MeshSegment::eraseFeatures(std::vector<unsigned>& fs)\n{\n\tstd::vector<bool> visFace(myMesh->getFaces().size(),true);\n\tfor(int i=0;i<fs.size();i++)\n\t{\n\t\tvisFace[fs[i]]=false;\n\t}\n\tfor(int i=0;i<crestEdgesVisible.size();i++)\n\t{\n\t\tif(crestEdges[i][2]>myMesh->getFaces().size()) continue;\n\t\tif(!visFace[crestEdges[i][2]]) crestEdgesVisible[i] = false;\n\t}\n\tfor(int i=0;i<userSketches.size();i++)\n\t{\n\t\tif(!visFace[userSketches[i].fid])\n\t\t{\n\t\t\tuserSketches.erase(userSketches.begin()+i); i--;\n\t\t}\n\t}\n\n// \t{\n// \t\tfeatureGraphInitial();\n// \t\tfeatureFromSketches();\n// \t\tfeatureFromCrestline();\n// \t\tcomputeFaceTensor(faceAnis);\n// \t\tcomputeDualEdgeCostAndLength();\n// \t\tcomputeDualEdgeStrength();\n// \t}\n}\nvoid MeshSegment::eraseCluster(std::vector<unsigned>& fs)\n{\n\tif(!vertexLabel.empty() && fs.size()>1)\n\t{\n\t\tcout << \"erase cluster...\";\n\n\t\tunsigned labelId = *std::max_element(vertexLabel.begin(), vertexLabel.end()) + 1;\n\n\t\tstd::vector<std::set<int> > vadjs(labelId);\n\t\tfor (unsigned i = 0; i < fs.size(); i++)\n\t\t{\n\t\t\tfor (unsigned j = 0; j < 3; j++)\n\t\t\t{\n\t\t\t\tauto eit = myMesh->getFIter()[fs[i]]->edge_iter(j);\n\t\t\t\tint l1 = min(vertexLabel[eit->vertex_iter(0)->id()],vertexLabel[eit->vertex_iter(1)->id()]);\n\t\t\t\tint l2 = max(vertexLabel[eit->vertex_iter(0)->id()],vertexLabel[eit->vertex_iter(1)->id()]);\n\t\t\t\tif(l1 != l2)\n\t\t\t\t{\n\t\t\t\t\tvadjs[l1].insert(l2);\n\t\t\t\t}\n\t\t\t}\t\t\t\n\t\t}\n\n\t\t{\n\t\t\t//reduce the strength of feature edge lying between merged patches.\n\t\t\tfor (auto e_it = myMesh->getEdges().begin(); e_it != myMesh->getEdges().end(); e_it++)\n\t\t\t{\n\t\t\t\tint l1 = min(vertexLabel[e_it->vertex_iter(0)->id()], vertexLabel[e_it->vertex_iter(1)->id()]);\n\t\t\t\tint l2 = max(vertexLabel[e_it->vertex_iter(0)->id()], vertexLabel[e_it->vertex_iter(1)->id()]);\n\n\t\t\t\tif (!vadjs[l1].empty() && vadjs[l1].find(l2) != vadjs[l1].end())\n\t\t\t\t{\n\t\t\t\t\tif (graphFeature.ef[e_it->id()].lab != -1)\n\t\t\t\t\t\tedgeWeightParameter[e_it->id()] = 1e-20;//1e-20 a small number;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tstd::vector<std::list<int> > labels(labelId);\n\t\tfor (unsigned i = 0; i < labelId; i++)\n\t\t{\n\t\t\tlabels[i].push_back(i);\n\t\t}\n\n\t\tfor (unsigned i = 0; i < vadjs.size(); i++)\n\t\t{\n\t\t\tstd::vector<int> frontLabel;\n\t\t\tfor(std::set<int>::iterator it = vadjs[i].begin();it != vadjs[i].end(); it++)\n\t\t\t{\n\t\t\t\tfrontLabel.push_back(*it);\n\t\t\t}\n\t\t\tstd::set<int> adjLabel;\n\t\t\twhile(!frontLabel.empty())\n\t\t\t{\n\t\t\t\tint cl = frontLabel.back(); frontLabel.pop_back();\n\t\t\t\tadjLabel.insert(cl);\n\t\t\t\tfor(std::set<int>::iterator it = vadjs[cl].begin();it != vadjs[cl].end(); it++)\n\t\t\t\t{\n\t\t\t\t\tfrontLabel.push_back(*it);\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor(std::set<int>::iterator it = adjLabel.begin();it != adjLabel.end(); it++)\n\t\t\t{\n\t\t\t\tlabels[i].push_back(*it);\n\t\t\t\tlabels[*it].clear();\n\t\t\t\tvadjs[*it].clear();\n\t\t\t}\n\t\t}\n\n\t\tstd::vector<int> newLabels(labels.size());\n\t\tint newLabelId=0;\n\t\tfor (unsigned i = 0; i < labels.size(); i++)\n\t\t{\n\t\t\tif (labels[i].size() > 0)\n\t\t\t{\n\t\t\t\tfor(std::list<int>::iterator itn = labels[i].begin(); itn!= labels[i].end(); itn++)\n\t\t\t\t{\n\t\t\t\t\tnewLabels[*itn] = newLabelId;\n\t\t\t\t}\n\t\t\t\tnewLabelId++;\n\t\t\t}\n\t\t}\n\n\t\tfor(unsigned i=0;i<vertexLabel.size();i++)\n\t\t{\n\t\t\tvertexLabel[i] = newLabels[vertexLabel[i]];\n\t\t}\n\t\t\n\t\tcout<<\"cluster number:\"<<newLabelId;\n\t\tsegNumber = newLabelId;\n\t\tgetBoundaryOfClusters();\n\t}\n}\nvoid MeshSegment::addSkethFeatures(std::vector<MyInteraction::SketchFace>& fs)\n{\n\tfor(int i=0;i<fs.size();i++)\n\t{\n\t\tuserSketches.push_back(fs[i]);\n\t}\n}\nvoid MeshSegment::findNeighboreOfTriangles(unsigned regionSize, std::vector<unsigned>& ToErase)\n{\n\tif (regionSize == 0)return;\n\n\tstd::vector<bool> visFace(myMesh->getFaces().size(), true);\n\tfor (int i = 0; i < ToErase.size(); i++)\n\t{\n\t\tvisFace[ToErase[i]] = false;\n\t}\n\n\tfor (unsigned count = 1; count <= regionSize; count++)\n\t{\n\t\tunsigned fsize = ToErase.size();\n\t\tfor (unsigned i = 0; i < fsize; i++)\n\t\t{\n\t\t\tauto f_it = myMesh->getFIter()[ToErase[i]];\n\t\t\tfor (unsigned j = 0; j < 3; j++)\n\t\t\t{\n\t\t\t\tfor (unsigned t = 0; t < f_it->vertex_iter(j)->edge_iter().size(); t++)\n\t\t\t\t{\n\t\t\t\t\tfor (unsigned k = 0; k < 2; k++)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (!f_it->vertex_iter(j)->edge_iter()[t]->manifold())\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tunsigned fid = f_it->vertex_iter(j)->edge_iter()[t]->face_iter(k)->id();\n\t\t\t\t\t\tif (visFace[fid])\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tvisFace[fid] = false; \n\t\t\t\t\t\t\tToErase.push_back(fid);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\nvoid  MeshSegment::smoothScribble(std::vector<unsigned>& sface,std::vector<Vec3>& scur)\n{\n// \tif (isSmoothStroke == false)\n\t\treturn;\n\n\tstd::map < unsigned, std::pair<unsigned,Vec3> > fmap;\n\tfor (unsigned i = 0; i < sface.size(); i++)\n\t{\n\t\tfmap[sface[i]] = std::pair<unsigned, Vec3>(i,scur[i]);\n\t}\n\tfor (unsigned i = 0; i < fmap.size(); i++)\n\t{\n\t\tauto tf = fmap.begin(); std::advance(tf, i);\n\t\tfmap[tf->first] = std::pair<unsigned, Vec3>(i, tf->second.second);\n\t}\n\n\tstd::vector<BoundaryVertex> Vbs(fmap.size());\n\tstd::vector<int> VbMap(myMesh->getFaces().size(), -1);\n\tfor (auto it_f = fmap.begin(); it_f != fmap.end(); it_f++)\n\t{\n\t\tunsigned tind = it_f->second.first;\n\t\tVbMap[it_f->first] = tind;\n\t\tVbs[tind].fid = it_f->first;\n\t\tVbs[tind].pos = it_f->second.second;\t\t\n\t}\n\n\tfor (unsigned i = 1; i < sface.size(); i++)\n\t{\n\t\tif (sface[i - 1] == sface[i]) continue;\n\n\t\tunsigned vid1 = fmap[sface[i - 1]].first;\n\t\tunsigned vid2 = fmap[sface[i]].first;\n\n\t\tVbs[vid1].ngbs.push_back(vid2);\n\t\tVbs[vid2].ngbs.push_back(vid1);\n\t}\n\n\t//smooth by anis tensor for several times.\n\tconst auto& fts = myMesh->getFIter();\n\tfor (int cnt = boundarySmoothTimes; cnt > 0; cnt--)\n\t{\n\t\tstd::vector<BoundaryVertex> newVbs = Vbs;\n\t\tfor (int i = 0; i < Vbs.size(); i++) //smooth for each vertex\n\t\t{\n\t\t\tif (Vbs[i].ngbs.size() == 1) continue;\n\n\t\t\tBoundaryVertex newBv;\n\t\t\tif (vertexMoveToLocalMinima(Vbs, i, newBv))\n\t\t\t{\n\t\t\t\tif ((newVbs[i].pos - newBv.pos).length() > 1e-3 || Vbs[i].fid != newBv.fid)\n\t\t\t\t{\n\t\t\t\t\tnewVbs[i].fid = newBv.fid;\n\t\t\t\t\tnewVbs[i].pos = newBv.pos;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tVbs = newVbs;\n\t}\n\n\t//write to sketches;\n\tstd::vector<unsigned> newfaces;\n\tstd::vector<Vec3> newVers;\n\tfor (unsigned i = 0; i < sface.size(); i++)\n\t{\n\t\tnewfaces.push_back(Vbs[VbMap[sface[i]]].fid);\n\t\tnewVers.push_back(Vbs[VbMap[sface[i]]].pos);\n\t}\n\tsface.swap(newfaces);\n\tscur.swap(newVers);\n\tcout << \"scribble smoothed\" << endl;\n}\nvoid MeshSegment::OverSegmentationOnPartialMesh(std::vector<unsigned>& fs, std::vector<unsigned>& es)\n{\n\tcout << \"------------------ PARTITIAL PARTITION -----------\" << endl;\n\t//1. init GraphFeature data structure;\n\t{\n\t\tclock_t tstr = clock();\n\t\tfeatureGraphInitial();\n\t\tfeatureFromCrestline();\n\t\tfeatureFromSketches();\n\n\t\tcomputeFaceTensor(faceAnis);\n\t\tcomputeDualEdgeCostAndLength();\n\t\tcomputeDualEdgeStrength();\n\n\t\tfeatureToCurves();\n\n\t\tmgraphInit(mg);\n\n\t\tclock_t tinit = clock() - tstr;\n\t\tcout << \"alpha:\" << graphFeature.alpha << endl;\n\t\tcout << endl << \"graph initialization:\" << tinit / 1000 << \"sec\" << tinit % 1000 << \"mm\" << endl;\n\t}\n\n\tMitani_Watershed_Dual_Partial(fs);\n\n// \tgenPatchColor(patchColors, segNumber, false);\n// \tgetBoundaryOfClusters();\n}\nvoid MeshSegment::regionMergingOnPartialMesh(MGraph& gph,\n\tstd::vector<bool>&subgraphVers,\n\tstd::vector<unsigned>& vertexLabel,\n\tunsigned& labelId)\n{\n\tclock_t tstr = clock();\n\tcout << \"perform in subgraph\" << endl;\n\n\t//find patches corresponding to subgraph\n\t//get map between global index(whole mesh) and local index(subgraph), including vertex index and label index;\n\tstd::set<unsigned> patchLabels;\n\tstd::map<unsigned, unsigned> globalIndToLocalInd;\n\tunsigned num = 0;\n\tfor (unsigned i = 0; i < subgraphVers.size(); i++)\n\t{\n\t\tif (subgraphVers[i])\n\t\t{\n\t\t\tpatchLabels.insert(vertexLabel[i]);\n\t\t\tglobalIndToLocalInd[i] = num;\n\t\t\tnum++;\n\t\t}\n\t}\n\tstd::map<unsigned, unsigned> globalLabelToLocalLabel;\n\tunsigned ind = 0;\n\tfor (auto i = patchLabels.begin(); i != patchLabels.end(); i++, ind++)\n\t{\n\t\tglobalLabelToLocalLabel[*i] = ind;\n\t}\n\tstd::vector<unsigned> localLabels(num); //local index, and local label\n\tfor (auto i = globalIndToLocalInd.begin(); i != globalIndToLocalInd.end(); i++)\n\t{\n\t\tlocalLabels[i->second] = globalLabelToLocalLabel[vertexLabel[i->first]];\n\t}\n\n\t//local adjacency of patches, the pair indices with cost;\n\tlabelId = patchLabels.size();\n\tstd::vector<std::set<int> > adjVers(labelId);\n\tfor (int i = 0; i < (int)gph.es.size(); i++)\n\t{\n\t\tif (!subgraphVers[gph.es[i].n1] || !subgraphVers[gph.es[i].n2]) continue;\n\t\t\n\t\tunsigned vid0 = min(globalLabelToLocalLabel[vertexLabel[gph.es[i].n1]], globalLabelToLocalLabel[vertexLabel[gph.es[i].n2]]);\n\t\tunsigned vid1 = max(globalLabelToLocalLabel[vertexLabel[gph.es[i].n1]], globalLabelToLocalLabel[vertexLabel[gph.es[i].n2]]);\n\n\t\tif (vid0 == vid1)continue;\n\t\tadjVers[vid0].insert(vid1);\n\t}\n\n\tstd::list< std::list< MGTriple > > pairClusterCost(labelId);\n\ttypedef std::list< std::list< MGTriple > >::iterator PCIter;\n\tstd::vector< PCIter > pCIter;\n\n\t//cost between two patches is the sum of weight of boundary edges in between.\n\tint count = 0;\n\tMGTriple tmg;\n\tfor (PCIter pct = pairClusterCost.begin(); pct != pairClusterCost.end(); pct++, count++)\n\t{\n\t\tif (adjVers[count].empty())\n\t\t{\n\t\t\ttmg.j = count;\n\t\t\ttmg.val = 0;\n\t\t\tpct->push_back(tmg);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfor (std::set<int>::iterator ita = adjVers[count].begin(); ita != adjVers[count].end(); ita++)\n\t\t\t{\n\t\t\t\ttmg.j = *ita;\n\t\t\t\ttmg.val = 0;\n\t\t\t\tpct->push_back(tmg);\n\t\t\t}\n\t\t}\n\t\tpCIter.push_back(pct);\n\t}\n\n\tstd::list< MGTriple >::iterator tpc;\n\tfor (int i = 0; i < (int)gph.es.size(); i++)\n\t{\n\t\tif (!subgraphVers[gph.es[i].n1] || !subgraphVers[gph.es[i].n2]) continue;\n\n\t\tunsigned vid0 = min(globalLabelToLocalLabel[vertexLabel[gph.es[i].n1]], globalLabelToLocalLabel[vertexLabel[gph.es[i].n2]]);\n\t\tunsigned vid1 = max(globalLabelToLocalLabel[vertexLabel[gph.es[i].n1]], globalLabelToLocalLabel[vertexLabel[gph.es[i].n2]]);\n\n\t\tif (vid0 == vid1)continue;\n\n\t\tfor (tpc = pCIter[vid0]->begin(); tpc != pCIter[vid0]->end(); tpc++)\n\t\t{\n\t\t\tif (tpc->j == vid1) break;\n\t\t}\n\t\ttpc->val += gph.es[i].w;\n\t}\n\n\t//merging algorithms; Interfaces \n\tstd::vector<unsigned> newLabels;\n\tLMP_Merging(localLabels, pCIter, labelId, newLabels);\n\n\tfor (auto e = myMesh->getEdges().begin(); e != myMesh->getEdges().end(); e++)\n\t{\n\t\tif (!e->manifold()) continue;\n\n\t\tunsigned n1 = e->vertex_iter(0)->id();\n\t\tunsigned n2 = e->vertex_iter(1)->id();\n\t\tif (subgraphVers[n1] && subgraphVers[n2])\n\t\t{\n\n\t\t\tif (newLabels[globalIndToLocalInd[n1]] != newLabels[globalIndToLocalInd[n2]])\n\t\t\t{\n\t\t\t\tgph.es[e->id()].isCut = true;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tgph.es[e->id()].isCut = false;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (vertexLabel[e->vertex_iter(0)->id()] != vertexLabel[e->vertex_iter(1)->id()])\n\t\t\t\tgph.es[e->id()].isCut = true;\n\t\t\telse\n\t\t\t\tgph.es[e->id()].isCut = false;\n\t\t}\n\t}\n\n\tunsigned vNum = myMesh->getVertices().size();\n\tunsigned eNum = myMesh->getEdges().size();\n\tvertexLabel.clear(); vertexLabel.resize(gph.vNum);\n\tlabelId = 0;\n\tstd::vector<bool> visitedVer(vNum, false);\n\tstd::vector<bool> visitedEdge(eNum, false);\n\tfor (size_t v = 0; v < vNum; v++)\n\t{\n\t\tif (visitedVer[v] == true) continue;\n\n\t\tstd::vector<int> frontVer(1, v);\n\t\t//propagates vertex with same label, and group them into a subgraph\n\t\twhile (!frontVer.empty())\n\t\t{\n\t\t\tint fv = frontVer.back(); frontVer.pop_back();\n\t\t\tvertexLabel[fv] = labelId;\n\n\t\t\tauto v = gph.vs[fv].vadjs.begin();\n\t\t\tauto e = gph.vs[fv].eadjs.begin();\n\t\t\tfor (; v != mg.vs[fv].vadjs.end(); v++, e++)\n\t\t\t{\n\t\t\t\tif (gph.es[*e].isCut || visitedEdge[*e] == true)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tvisitedEdge[*e] = true;\n\n\t\t\t\tif (visitedVer[*v] == true)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tvisitedVer[*v] = true;\n\n\t\t\t\tfrontVer.push_back(*v);\n\t\t\t}\n\t\t}\n\t\tlabelId++;\n\t}\n\n\tcout << endl << \"cluster number after merging:\" << labelId << endl;\n\n\tclock_t tinit = clock() - tstr;\n\tcout << \"merging takes:\" << tinit / 1000 << \"sec\" << tinit % 1000 << \"mm\" << endl;\n}\nvoid MeshSegment::mergePartitionOnPartialMesh()\n{\n\tboundaryCurves.clear();\n\n\tcout << \"*   *   *   *   *   * PARTIAL MERGE  *   *   *   *   *   *\" << endl;\n\tauto tlabels = vertexLabel;\n\tauto patNum = segNumber;\n\n\tvertexLabel = vertexLabelBeforeMerge;\n\n\tmgraphInit(mg);\n\n\tregionMergingOnPartialMesh(mg, subgraphVers, vertexLabel, segNumber);\n\n\tif (isMergeSmallPatch)\n\t{\n\t\tmergeSmallPatches();\n\t}\n\telse\n\t{\n\t\tfor (int i = 0; i < mg.eNum; i++)\n\t\t{\n\t\t\tgraphFeature.ef[i].isCut = mg.es[i].isCut;\n\t\t}\n\t}\n\n\tif (autoBoundarySmooth)\n\t{\n\t\tcout << endl;\n\t\tboundarySmooth(true);\n\t}\n\n\tcout << \"\\n-----------------------------------------------------\" << endl;\n\n\t//label id for most of vertices should remain the same, causing least changes;\n// \tpatchColorMinChanged(tlabels, patNum);\n}\nvoid MeshSegment::mergeLocalClusterByFeatureEnhancing(std::vector<unsigned>& ToEnhance)\n{\n\tconst auto& faceIters = myMesh->getFIter();\n\tconst auto& verIters = myMesh->getVIter();\n\n\t//1. determine which clusters does paints lie in\n\tstd::set<int> inClusters;\n\tfor (int i = 0; i < ToEnhance.size(); i++)\n\t{\n\t\tfor (int j = 0; j < 3; j++)\n\t\t{\n\t\t\tauto vit = faceIters[ToEnhance[i]]->vertex_iter(j);\n\t\t\tinClusters.insert(vertexLabel[vit->id()]);\n\t\t}\n\t}\n\n\t//2. find out clusters(before merging) in clusters by step 1.\n\t//for all vertices in clusters by step 1, find their initial clusters\n\tstd::vector<bool> includedClusters(segNumber, false);\n\tfor (auto i = inClusters.begin(); i != inClusters.end(); i++)\n\t{\n\t\tincludedClusters[*i] = true;\n\t}\n\tstd::map<int, int> mapToNewClusters;\n\tstd::vector<bool> includedVers(verIters.size(), false);\n\tfor (int i = 0; i < verIters.size(); i++)\n\t{\n\t\tif (includedClusters[vertexLabel[i]])\n\t\t{\n\t\t\tmapToNewClusters[vertexLabelInit[i]] = vertexLabel[i];\n\t\t\tincludedVers[i] = true;\n\t\t}\n\t}\n\n\tsubgraphVers = includedVers;\n\t//assign initial vertexlabel to seleted regions, and keep non-seleted the same; update vertexLabel, and call merging\n\t{//merge locally\n\t\tint clusterSize = inClusters.size();\n\t\tint clusterSizeOrig = mapToNewClusters.size();\n\t\tstd::set<int> newLabels;\n\t\tfor (auto i = inClusters.begin(); i != inClusters.end(); i++)\n\t\t{\n\t\t\tnewLabels.insert(*i);\n\t\t}\n\t\tfor (int i = 0; i < clusterSizeOrig - clusterSize; i++)\n\t\t{\n\t\t\tnewLabels.insert(segNumber + i);\n\t\t}\n\n\t\tfor (int i = 0; i < includedVers.size(); i++)\n\t\t{\n\t\t\tif (includedVers[i])\n\t\t\t{\n\t\t\t\tint labelId = *newLabels.begin(); newLabels.erase(newLabels.begin());\n\t\t\t\tstd::vector<MyMesh::VertexIter> frontVer(1, verIters[i]);\n\t\t\t\t//propagates vertex with same label, and group them into a subgraph\n\t\t\t\twhile (!frontVer.empty())\n\t\t\t\t{\n\t\t\t\t\tauto fv = frontVer.back(); frontVer.pop_back();\n\t\t\t\t\tvertexLabel[fv->id()] = labelId;\n\n\t\t\t\t\tfor (int j = 0; j < fv->vertex_iter().size(); j++)\n\t\t\t\t\t{\n\t\t\t\t\t\tauto av = fv->vertex_iter()[j];\n\t\t\t\t\t\tif (vertexLabelInit[fv->id()] == vertexLabelInit[av->id()] && includedVers[av->id()])\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfrontVer.push_back(av);\n\t\t\t\t\t\t\tincludedVers[av->id()] = false;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (!newLabels.empty())\n\t\t\tcout << \"something is wrong when assigning new labels when painting\" << endl;\n\n\t\tvertexLabelBeforeMerge.swap(vertexLabel);\n\t}\n\t//3. change local merging parameters by paint setting.. and computer the graph weight, then perform merge in clusters by step 1.\n\tupdateLocalAwardAlpha(ToEnhance);\n\n\tmergePartitionOnPartialMesh();\n}\nvoid MeshSegment::modifySegmentBySketch(Interaction::SCRIBBLE_TYPE type)\n{\n\tif(sketchFaces.size()<2) return; //return by empty;\n\tclock_t tstr = clock();\n\n\tstd::vector<unsigned> tlabels = vertexLabel;\n\tunsigned patNum = segNumber;\n\n\tstd::vector<unsigned> ToErase = sketchFaces; //Erase features in 'sketchFaces';\n\n\tif (type == Interaction::ADD)\n\t{\n\t\tstd::vector<unsigned> edgeSequence;//edge sequence along unfolded triangle strip of scribbles;\n\t\tstd::vector<MyInteraction::SketchFace> ToAdd; //sequence of triangles;\n\t\tm_interaction->userSketchSamplingFromSketchFaces(sketchFaces,sketchCurves,ToAdd, edgeSequence);//find sketch curve from unordered sketch faces;\n\t\t\n\t\tif (edgeSequence.empty()) return;\n\n\t\tif (!graphCutLocally)\n\t\t{\n\t\t\tunsigned ringSize = strokeSize;\n\t\t\tfindNeighboreOfTriangles(ringSize, ToErase); //includes the neighbores of sketches, erase a larger region\n\t\t\t// \t\tauto tp = paintParamType;\t\tpaintParamType = 2;\n\t\t\t// \t\tupdateLocalAwardAlpha(ToErase);\tpaintParamType = tp;\n\t\t\teraseFeatures(ToErase);\n\n\t\t\taddSkethFeatures(ToAdd);//add new sketches;\n\t\t}\n\n\t\tOverSegmentationOnPartialMesh(sketchFaces,edgeSequence);//do over segmentation;\n\t\tmergePartitionOnPartialMesh();//do merging in seleted patches;\n\t}\n\telse if (type == Interaction::ERASE)\n\t{\n\t\teraseCluster(ToErase);\n\t\tif (autoBoundarySmooth)\tboundarySmooth(true);\n\t}\n\telse\n\t{\n\t\tmergeLocalClusterByFeatureEnhancing(ToErase);//do merging in seleted patches;\n\t}\n\n\tpatchColorMinChanged(tlabels, patNum);//label id for most of vertices should remain the same;\n\n\tsketchFaces.clear(); sketchCurves.clear();\n\n\tclock_t totalTime=clock()-tstr;\n\tcout<<\"total time:\"<<totalTime/1000<<\"sec\"<<totalTime%1000<<\"mm\"<<endl;\n}", "meta": {"hexsha": "eb97827b560c3ef028151c33d26c487f9243ec0d", "size": 70309, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CurveNetMaker/core/Segmentation.cpp", "max_stars_repo_name": "yixin26/Mesh-Segmentation", "max_stars_repo_head_hexsha": "4c0a775d73970710ff5108aa47b1be8455231285", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2017-11-21T13:55:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T07:57:28.000Z", "max_issues_repo_path": "CurveNetMaker/core/Segmentation.cpp", "max_issues_repo_name": "yixin26/CurveNet-Mesh", "max_issues_repo_head_hexsha": "4c0a775d73970710ff5108aa47b1be8455231285", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2015-03-02T22:36:51.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-14T10:43:38.000Z", "max_forks_repo_path": "CurveNetMaker/core/Segmentation.cpp", "max_forks_repo_name": "yixin26/CurveNet-Mesh", "max_forks_repo_head_hexsha": "4c0a775d73970710ff5108aa47b1be8455231285", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-01-15T08:57:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-20T12:03:57.000Z", "avg_line_length": 28.4651821862, "max_line_length": 197, "alphanum_fraction": 0.6348262669, "num_tokens": 22874, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4805701160016834}}
{"text": "//  (C) Copyright Matt Borland 2021.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include <boost/math/ccmath/round.hpp>\n#include \"test_compile_result.hpp\"\n\nvoid compile_and_link_test()\n{\n   // round\n   check_result<float>(boost::math::ccmath::round(1.0f));\n   check_result<double>(boost::math::ccmath::round(1.0));\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   check_result<long double>(boost::math::ccmath::round(1.0l));\n#endif\n\n    // lround\n    check_result<long>(boost::math::ccmath::lround(1.0f));\n    check_result<long>(boost::math::ccmath::lround(1.0));\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n    check_result<long>(boost::math::ccmath::lround(1.0l));\n#endif\n\n    // llround\n    check_result<long long>(boost::math::ccmath::llround(1.0f));\n    check_result<long long>(boost::math::ccmath::llround(1.0));\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n    check_result<long long>(boost::math::ccmath::llround(1.0l));\n#endif\n}\n", "meta": {"hexsha": "9da98c7000144e574249e5558b7c017cc43dd5cf", "size": 1098, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/compile_test/ccmath_round_incl_test.cpp", "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": "test/compile_test/ccmath_round_incl_test.cpp", "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": "test/compile_test/ccmath_round_incl_test.cpp", "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": 34.3125, "max_line_length": 68, "alphanum_fraction": 0.7304189435, "num_tokens": 315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4805660190107395}}
{"text": "\n#include<iostream>\n#include <Eigen/Eigenvalues> \n#include\"numerics.hpp\"\n#include\"reddm.hpp\"\n#include\"tpoperators.hpp\"\n#include \"files.hpp\"\n\n\nusing namespace Many_Body;\nint main(int argc, char *argv[])\n{\n  \n  size_t M{};\n  size_t L{};\n  double t0{};\n  double omega{};\n  double gamma{};\n  try\n  {\n    options_description desc{\"Options\"};\n    desc.add_options()\n      (\"help,h\", \"Help screen\")\n      (\"L\", value(&L)->default_value(4), \"L\")\n      (\"M\", value(&M)->default_value(2), \"M\")\n      (\"t\", value(&t0)->default_value(1.), \"t0\")\n      (\"gam\", value(&gamma)->default_value(1.), \"gamma\")\n      (\"omg\", value(&omega)->default_value(1.), \"omega\");\n  \n\n\n    variables_map vm;\n    store(parse_command_line(argc, argv, desc), vm);\n    notify(vm);\n\n    if (vm.count(\"help\"))\n      {std::cout << desc << '\\n'; return 0;}\n    else{\n      if (vm.count(\"L\"))\n      {      std::cout << \"L: \" << vm[\"L\"].as<size_t>() << '\\n';\n\t\n      }\n     if (vm.count(\"M,m\"))\n      {\n\tstd::cout << \"M: \" << vm[\"M\"].as<size_t>() << '\\n';\n\t\n      }\n      if (vm.count(\"t\"))\n      {\n\tstd::cout << \"t0: \" << vm[\"t\"].as<double>() << '\\n';\t\n      }\n       if (vm.count(\"omg\"))\n      {\n\tstd::cout << \"omega: \" << vm[\"omg\"].as<double>() << '\\n';\n      }\n       if (vm.count(\"gam\"))\n      {\n\tstd::cout << \"gamma: \" << vm[\"gam\"].as<double>() << '\\n';\n      }\n    }\n  }\n  catch (const error &ex)\n  {\n    std::cerr << ex.what() << '\\n';\n    return 0;\n  }\n\n    using Mat= Operators::Mat;\n\n  \n   using HolsteinBasis= TensorProduct<ElectronBasis, PhononBasis>;\n\n  ElectronBasis e( L, 1);\n    std::cout<< e<<std::endl;\n  \n  PhononBasis ph(L, M);\n  std::cout<< ph<<std::endl;\n  HolsteinBasis TP(e, ph);\n    std::cout<< TP << std::endl;\n    std::cout<< TP.dim << std::endl;\n        Mat E1=Operators::EKinOperatorL(TP, e, t0, true);\n      Mat Ebdag=Operators::NBosonCOperator(TP, ph, gamma, true);\n      Mat Eb=Operators::NBosonDOperator(TP, ph, gamma, true);\n      Mat Eph=Operators::NumberOperator(TP, ph, omega,  true);\n      \n      //Mat E=Operators::NumberOperatore(TP, e, 1, false);\n      //    std::cout<< HH << std::endl;\n      Eigen::VectorXd eigenVals(TP.dim);\n      Mat H=E1+Eph  +Ebdag + Eb;\n\n      // state\n//         Eigen::VectorXcd evec=Eigen::VectorXcd::Zero(H.rows());\n// \tevec(3)=1./std::sqrt(3*2);\n// \tevec(7)=std::exp(-im*static_cast<std::complex<double>>(2*pi/3))*1./std::sqrt(3*2);\n// \t   evec(11)=std::exp(-im*static_cast<std::complex<double>>(4*pi/3))*1./std::sqrt(3*2);\n// \t   evec(21)=1./std::sqrt(3*2);\n// \tevec(22)=std::exp(-im*static_cast<std::complex<double>>(2*pi/3))*1./std::sqrt(3*2);\n// \tevec(23)=std::exp(-im*static_cast<std::complex<double>>(4*pi/3))*1./std::sqrt(3*2);\n// \tstd::cout<< \" E in \"<<(evec.adjoint()*H*evec)(0)<<std::endl;\n// \tstd::cout<< \" norm \"<<(evec.adjoint()*evec)(0)<<std::endl;\n// auto ov=makeRedDMTP(TP, ph,  0, evec);\n//  for(auto g : ov)\n//    {\n//      std::cout<< g << std::endl;\n//      std::cout<< std::endl<<std::endl;\n//    }\n\n      Eigen::MatrixXd HH=Eigen::MatrixXd(H);\n\t  Eigen::MatrixXd HH2=Eigen::MatrixXd(H);\n\t  Eigen::VectorXd ev=Eigen::VectorXd(TP.dim);\n\t  bool isDiag=false;\n\t //  std::vector<double> Tr={0.0100, 0.1000, 1.000, 2.0000, 5.0000, 10.0000};\n\t //  for(auto t: Tr){\n\t //      std::string sT=std::string(std::to_string(t)).substr(0,6);\n auto t=T;\n\t       auto optModes=makeThermalRDMTP(HH,ev,  TP, t, isDiag, 0);\n\t //  //\t  std::cout << \"sum of all eigenvalues \"<< optModes.sum()<< std::endl;\n\t //      isDiag=true;\n\t  int n=0;\n\t  double ent{0};\t \n\t  for(auto& l : optModes)\n\t    {\n\t      \t      std::string sn=std::string(std::to_string(n)).substr(0,1);\n\t\t      //std::string filename=\"OML\"+std::to_string(L)+\"M\"+std::to_string(M)+\"t0_\"+\"1.0\"+\"gam\"+sgam+\"omg\"+ somg+\"T\"+ sT+ \"esec\" +sn  + \".bin\";\n\t\t std::cout << n << std::endl;\n\t\t for(int i=0; i<l.rows(); i++)\n\t\t   {\n\t\t     ent-=l(i)*std::log(l(i));\n\t\t   }\n\t\t std::cout<< \"value \"<< \" fot T = \"<< t <<std::endl;\n\t\t \t      std::cout<< l<<std::endl;\n\t\t\t      std::cout << \" and sum \"<< l.sum()<< std::endl;\n\t\t\t      //bin_write(filename, l);\n\t\t n++;\n\t    }\n\t\n\t  std::cout<< \"ENTROPY \"<< ent << std::endl;\n  return 0;\n}\n", "meta": {"hexsha": "d3cf6e290e54f364235a6511eca8c8296cc1316f", "size": 4112, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/reddm.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/reddm.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/reddm.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": 29.3714285714, "max_line_length": 142, "alphanum_fraction": 0.5333171206, "num_tokens": 1402, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4805660190107395}}
{"text": "//\r\n// OpenTissue, A toolbox for physical based simulation and animation.\r\n// Copyright (C) 2007 Department of Computer Science, University of Copenhagen\r\n//\r\n#include <OpenTissue/configuration.h>\r\n\r\n#include <OpenTissue/core/math/math_basic_types.h>\r\n#include <OpenTissue/collision/gjk/gjk_outside_vertex_edge_voronoi_plane.h>\r\n\r\n#define BOOST_AUTO_TEST_MAIN\r\n#include <OpenTissue/utility/utility_push_boost_filter.h>\r\n#include <boost/test/auto_unit_test.hpp>\r\n#include <boost/test/unit_test_suite.hpp>\r\n#include <boost/test/floating_point_comparison.hpp>\r\n#include <boost/test/test_tools.hpp>\r\n#include <OpenTissue/utility/utility_pop_boost_filter.h>\r\n\r\n#include <cmath>\r\n\r\nusing namespace OpenTissue;\r\n\r\nBOOST_AUTO_TEST_SUITE(opentissue_collision_gjk_outside_vertex_edge);\r\n\r\nBOOST_AUTO_TEST_CASE(case_by_case_test)\r\n{\r\n  typedef OpenTissue::math::BasicMathTypes<double, size_t> math_types;\r\n  typedef math_types::vector3_type                         V;\r\n\r\n  V const a = V(1.0, 0.0, 0.0);\r\n  V const b = V(0.0, 0.0, 0.0);\r\n\r\n  // First we use a test point that does not lie on the line\r\n\r\n  // Front side of A voronoi plane\r\n  {\r\n    V p = V( 2.0, 1.0,  1.0);\r\n    bool outside = OpenTissue::gjk::detail::outside_vertex_edge_voronoi_plane(p, a, b);\r\n    BOOST_CHECK( outside );\r\n  }\r\n  // Back side of A voronoi plane\r\n  {\r\n    V p = V( 0.0, 1.0,  1.0);\r\n    bool outside = OpenTissue::gjk::detail::outside_vertex_edge_voronoi_plane(p, a, b);\r\n    BOOST_CHECK( !outside );\r\n  }\r\n  // In A voronoi plane\r\n  {\r\n    V p = V( 1.0, 1.0,  1.0);\r\n    bool outside = OpenTissue::gjk::detail::outside_vertex_edge_voronoi_plane(p, a, b);\r\n    BOOST_CHECK( outside );\r\n  }\r\n\r\n  // Front side of B voronoi plane\r\n  {\r\n    V p = V( -1.0, 1.0,  1.0);\r\n    bool outside = OpenTissue::gjk::detail::outside_vertex_edge_voronoi_plane(p, b, a);\r\n    BOOST_CHECK( outside );\r\n  }\r\n  // Back side of B voronoi plane\r\n  {\r\n    V p = V( 1.0, 1.0,  1.0);\r\n    bool outside = OpenTissue::gjk::detail::outside_vertex_edge_voronoi_plane(p, b, a);\r\n    BOOST_CHECK( !outside );\r\n  }\r\n  // In B voronoi plane\r\n  {\r\n    V p = V( 0.0, 1.0,  1.0);\r\n    bool outside = OpenTissue::gjk::detail::outside_vertex_edge_voronoi_plane(p, b, a);\r\n    BOOST_CHECK( outside );\r\n  }\r\n\r\n  // Second we use a test point that lies on the line\r\n\r\n  // Front side of A voronoi plane\r\n  {\r\n    V p = V( 2.0, 0.0,  0.0);\r\n    bool outside = OpenTissue::gjk::detail::outside_vertex_edge_voronoi_plane(p, a, b);\r\n    BOOST_CHECK( outside );\r\n  }\r\n  // Back side of A voronoi plane\r\n  {\r\n    V p = V( 0.0, 0.0,  0.0);\r\n    bool outside = OpenTissue::gjk::detail::outside_vertex_edge_voronoi_plane(p, a, b);\r\n    BOOST_CHECK( !outside );\r\n  }\r\n  // In A voronoi plane\r\n  {\r\n    V p = V( 1.0, 0.0,  0.0);\r\n    bool outside = OpenTissue::gjk::detail::outside_vertex_edge_voronoi_plane(p, a, b);\r\n    BOOST_CHECK( outside );\r\n  }\r\n\r\n  // Front side of B voronoi plane\r\n  {\r\n    V p = V( -1.0, 0.0,  0.0);\r\n    bool outside = OpenTissue::gjk::detail::outside_vertex_edge_voronoi_plane(p, b, a);\r\n    BOOST_CHECK( outside );\r\n  }\r\n  // Back side of B voronoi plane\r\n  {\r\n    V p = V( 1.0, 0.0,  0.0);\r\n    bool outside = OpenTissue::gjk::detail::outside_vertex_edge_voronoi_plane(p, b, a);\r\n    BOOST_CHECK( !outside );\r\n  }\r\n  // In B voronoi plane\r\n  {\r\n    V p = V( 0.0, 0.0,  0.0);\r\n    bool outside = OpenTissue::gjk::detail::outside_vertex_edge_voronoi_plane(p, b, a );\r\n    BOOST_CHECK( outside );\r\n  }\r\n\r\n}\r\n\r\nBOOST_AUTO_TEST_SUITE_END();\r\n", "meta": {"hexsha": "f0f338cf422d44ab941c2708af9f23bb6a2fe283", "size": 3491, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/collision/gjk/outside_vertex_edge/src/unit_outside_vertex_edge.cpp", "max_stars_repo_name": "ricortiz/OpenTissue", "max_stars_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 76.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:45:06.000Z", "max_issues_repo_path": "unit_tests/collision/gjk/outside_vertex_edge/src/unit_outside_vertex_edge.cpp", "max_issues_repo_name": "ricortiz/OpenTissue", "max_issues_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2018-11-20T14:32:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T15:26:45.000Z", "max_forks_repo_path": "unit_tests/collision/gjk/outside_vertex_edge/src/unit_outside_vertex_edge.cpp", "max_forks_repo_name": "ricortiz/OpenTissue", "max_forks_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2018-02-21T01:45:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T07:06:49.000Z", "avg_line_length": 30.3565217391, "max_line_length": 89, "alphanum_fraction": 0.6436551131, "num_tokens": 1108, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4805660190107395}}
{"text": "//\n// Created by jiashuai on 17-11-7.\n//\n#include <config.h>\n\n#ifndef USE_CUDA\n#include <thundersvm/kernel/kernelmatrix_kernel.h>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <iostream>\n#include <fstream>\nnamespace svm_kernel {\n    void\n    get_working_set_ins(const SyncData<float_type> &val, const SyncData<int> &col_ind, const SyncData<int> &row_ptr,\n                        const SyncData<int> &data_row_idx, SyncData<float_type> &data_rows, int m) {\n#pragma omp parallel for\n        for (int i = 0; i < m; i++) {\n            int row = data_row_idx[i];\n            for (int j = row_ptr[row]; j < row_ptr[row + 1]; ++j) {\n                int col = col_ind[j];\n                data_rows[col * m + i] = val[j]; // row-major for cuSPARSE\n            }\n        }\n    }\n\n    void\n    RBF_kernel(const SyncData<float_type> &self_dot0, const SyncData<float_type> &self_dot1,\n               SyncData<float_type> &dot_product, int m,\n               int n, float_type gamma) {\n#pragma omp parallel for\n        for (int idx = 0; idx < m * n; idx++) {\n            int i = idx / n;//i is row id\n            int j = idx % n;//j is column id\n            dot_product[idx] = expf(-(self_dot0[i] + self_dot1[j] - dot_product[idx] * 2) * gamma);\n        }\n    }\n\n    void\n    RBF_kernel(const SyncData<int> &self_dot0_idx, const SyncData<float_type> &self_dot1,\n               SyncData<float_type> &dot_product, int m,\n               int n, float_type gamma) {\n#pragma omp parallel for\n        for (int idx = 0; idx < m * n; idx++) {\n            int i = idx / n;//i is row id\n            int j = idx % n;//j is column id\n            dot_product[idx] = expf(-(self_dot1[self_dot0_idx[i]] + self_dot1[j] - dot_product[idx] * 2) * gamma);\n        }\n\n    }\n\n    void poly_kernel(SyncData<float_type> &dot_product, float_type gamma, float_type coef0, int degree, int mn) {\n#pragma omp parallel for\n        for (int idx = 0; idx < mn; idx++) {\n            dot_product[idx] = powf(gamma * dot_product[idx] + coef0, degree);\n        }\n    }\n\n    void sigmoid_kernel(SyncData<float_type> &dot_product, float_type gamma, float_type coef0, int mn) {\n#pragma omp parallel for\n        for (int idx = 0; idx < mn; idx++) {\n            dot_product[idx] = tanhf(gamma * dot_product[idx] + coef0);\n        }\n    }\n\n    void sum_kernel_values(const SyncData<float_type> &coef, int total_sv, const SyncData<int> &sv_start,\n                           const SyncData<int> &sv_count, const SyncData<float_type> &rho,\n                           const SyncData<float_type> &k_mat,\n                           SyncData<float_type> &dec_values, int n_classes, int n_instances) {\n#pragma omp parallel for\n        for (int idx = 0; idx < n_instances; idx++) {\n            int k = 0;\n            int n_binary_models = n_classes * (n_classes - 1) / 2;\n            for (int i = 0; i < n_classes; ++i) {\n                for (int j = i + 1; j < n_classes; ++j) {\n                    int si = sv_start[i];\n                    int sj = sv_start[j];\n                    int ci = sv_count[i];\n                    int cj = sv_count[j];\n                    const float_type *coef1 = &coef[(j - 1) * total_sv];\n                    const float_type *coef2 = &coef[i * total_sv];\n                    const float_type *k_values = &k_mat[idx * total_sv];\n                    float_type sum = 0;\n#pragma omp parallel for reduction(+:sum)\n                    for (int l = 0; l < ci; ++l) {\n                        sum += coef1[si + l] * k_values[si + l];\n                    }\n#pragma omp parallel for reduction(+:sum)\n                    for (int l = 0; l < cj; ++l) {\n                        sum += coef2[sj + l] * k_values[sj + l];\n                    }\n                    dec_values[idx * n_binary_models + k] = sum - rho[k];\n                    k++;\n                }\n            }\n        }\n    }\n\n    void dns_csr_mul(int m, int n, int k, const SyncData<float_type> &dense_mat, const SyncData<float_type> &csr_val,\n                     const SyncData<int> &csr_row_ptr, const SyncData<int> &csr_col_ind, int nnz,\n                     SyncData<float_type> &result) {\n        /* \n        for(int row = 0; row < m; row ++){\n            int nz_value_num = csr_row_ptr[row + 1] - csr_row_ptr[row];\n            if(nz_value_num != 0){\n                for(int col = 0; col < n; col++){\n                    float_type sum = 0;\n                    for(int nz_value_index = csr_row_ptr[row]; nz_value_index < csr_row_ptr[row + 1]; nz_value_index++){\n                        sum += csr_val[nz_value_index] * dense_mat[col + csr_col_ind[nz_value_index] * n];\n                    }\n                    result[row * n + col] = sum;\n                }\n            }\n        }\n        */\n\tEigen::Map<const Eigen::MatrixXf> denseMat(dense_mat.host_data(), n, k);\n\tEigen::Map<const Eigen::SparseMatrix<float, Eigen::RowMajor>> sparseMat(m, k, nnz, csr_row_ptr.host_data(),\n                                                                                csr_col_ind.host_data(),\n                                                                                csr_val.host_data());\n    Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> dense_tran = denseMat.transpose();\n\tEigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor> retMat = sparseMat * dense_tran;\n\tEigen::Map < Eigen::Matrix < float, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor > > (result.host_data(),\n                retMat.rows(),\n                retMat.cols()) = retMat;\n    \t\n    }\n}\n#endif\n", "meta": {"hexsha": "3ea68b18a25c1e0bcadc138ab39d3f85462dd832", "size": 5515, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/thundersvm/kernel/kernelmatrix_kernel.cpp", "max_stars_repo_name": "SoldierChen/thundersvm", "max_stars_repo_head_hexsha": "7e8066245b1a0478b82cf38bf3d424b28a294007", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-09-19T08:08:59.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-19T08:08:59.000Z", "max_issues_repo_path": "src/thundersvm/kernel/kernelmatrix_kernel.cpp", "max_issues_repo_name": "SoldierChen/thundersvm", "max_issues_repo_head_hexsha": "7e8066245b1a0478b82cf38bf3d424b28a294007", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/thundersvm/kernel/kernelmatrix_kernel.cpp", "max_forks_repo_name": "SoldierChen/thundersvm", "max_forks_repo_head_hexsha": "7e8066245b1a0478b82cf38bf3d424b28a294007", "max_forks_repo_licenses": ["Apache-2.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.0859375, "max_line_length": 120, "alphanum_fraction": 0.5222121487, "num_tokens": 1385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.800691997339971, "lm_q2_score": 0.6001883592602049, "lm_q1q2_score": 0.4805660161562535}}
{"text": "#ifndef HGaussianProcess\n#define HGaussianProcess\n\n#include \"GaussianProcessBaseClass.hpp\"\n#include \"CholeskyFactorization.hpp\"\n#include \"TriangularMatrixOperations.hpp\"\n#include \"VectorOperations.hpp\"\n#include \"nlopt.hpp\"\n#include \"BlackBoxData.hpp\"\n#include \"BlackBoxBaseClass.hpp\"\n#include <memory>\n#include <random>\n\n#include <Eigen/Core>\n\nusing namespace Eigen;\n\n//! Gaussian process regression\n/*!\n Computes a Gaussian process of given data points, function evaluations and noise estimates.\n \\see GaussianProcessBaseClass\n \\see CholeskyFactorization\n \\see TriangularMatrixOperations\n*/\nclass GaussianProcess : public GaussianProcessBaseClass,\n                        protected CholeskyFactorization, \n                        protected TriangularMatrixOperations,\n                        protected VectorOperations {\n\n  protected:\n    //auxiliary variables\n    int pos;\n    double rho;\n    std::vector<double> K0;\n    double kernel_evaluation, dist;\n    std::vector<double> gp_parameters;\npublic:\n    const std::vector<double> &get_gp_parameters() const;\n\nprotected:\n    std::vector<double> lb, ub;\n    //general/shared auxiliary variables\n    std::vector< std::vector<double> > L;\n    std::vector< std::vector<double> > L_inverse;\n    std::vector<double> alpha;    \n\n    GaussianProcess *gp_pointer;\n    std::vector< std::vector<double> > gp_nodes;\n    std::vector<double> scaled_function_values;\n    double min_function_value, max_function_value;\n    std::vector<double> gp_noise;\n    int dim, nb_gp_nodes;\n    double *delta;\n    double noise_regularization = 1e-6;\n    BlackBoxBaseClass* blackbox;\n\n    static double parameter_estimation_objective(std::vector<double> const&, \n                                                 std::vector<double>&, void*);\n\n    //! Evaluation of Gaussian process kernel\n    /*!\n     Evaluates the square exponential kernel.\n    */\n    virtual double evaluate_kernel ( std::vector<double> const&, std::vector<double> const& );\n    virtual double evaluate_kernel ( std::vector<double> const&, std::vector<double> const&,\n                             std::vector<double> const& );\n    //! Evaluation of the derivative of the Gaussina process kernel\n    virtual double d_evaluate_kernel ( std::vector<double> const&, std::vector<double> const&,\n                               std::vector<double> const&, int );\n\n    static double parameter_estimation_objective_w_gradients(std::vector<double> const &x,\n                                                           std::vector<double> &grad,\n                                                           void *data){};\n\n  public:\n    //! Constructor\n    /*!\n     Class constructor.\n     \\param n dimension of the Gaussian process.\n    */\n    GaussianProcess( int, double& , BlackBoxBaseClass*);\n\n    GaussianProcess( int, double& , BlackBoxBaseClass*, std::vector<double> );\n    //! Destructor\n    ~GaussianProcess() { }\n    //! Estimation of hyper parameters\n    /*!\n     Estimates the hyper parameters of the Gaussian process.\\n \n     The hyper parameters are the variance and the length scale parameters in the exponential kernel.\\n\n     \\param nodes regression points\n     \\param function values \n     \\param noise in function values\n    */\n    virtual void estimate_hyper_parameters ( std::vector< std::vector<double> > const&,\n                                     std::vector<double> const&, \n                                     std::vector<double> const&);\n\n    virtual void estimate_hyper_parameters_induced_only ( std::vector< std::vector<double> > const&,\n                                     std::vector<double> const&, \n                                     std::vector<double> const&);\n\n    virtual void estimate_hyper_parameters_ls_only ( std::vector< std::vector<double> > const&,\n                                     std::vector<double> const&, \n                                     std::vector<double> const&);\n    //! Build the Gaussian process\n    /*!\n     Computes the Gaussian process\\n\n     Requires the estimation of hyper parameters\n     \\param nodes regression points\n     \\param function values\n     \\param noise in function values\n     \\see estimate_hyper_parameters\n    */\n    virtual void build ( std::vector< std::vector<double> > const&,\n                 std::vector<double> const&, std::vector<double> const&);\n    //! Update the Gaussian process\n    /*!\n     Includees a new point into the Gaussian process\n     \\param x new point to be included into the Gaussian process\n     \\param value new function value at new point\n     \\param noise new noise estimate at new function value\n    */\n    virtual void update ( std::vector<double> const&, double&, double& );\n    //! Evaluate Gaussian process\n    /*!\n     Computes the mean and variance of the Gaussian process.\\n\n     Requires the building of the Gaussian process.\n     \\param x point at which the Gaussian process is evaluated\n     \\param mean mean of the Gaussian process at point x\n     \\param variance variance of the Gaussina process at point x\n     \\see build\n    */\n    virtual void evaluate ( std::vector<double> const&, double&, double& );\n\n    /*\n    Same but without variance computation\n    */\n    virtual void evaluate ( std::vector<double> const &x,\n                                 double &mean);\n\n    //! Evaluate Gaussian process given new training data set\n    /*!\n     Computes the mean and variance of the Gaussian process.\\n\n     Requires the building of the Gaussian process.\n     \\param x point at which the Gaussian process is evaluated\n     \\param f_train training values\n     \\param mean mean of the Gaussian process at point x\n     \\see build\n    */\n    virtual void evaluate ( std::vector<double> const&, std::vector<double> const&, double& );\n\n    virtual void build_inverse ();\n\n    virtual double compute_var_meanGP ( std::vector<double>const& xstar, std::vector<double> const& noise) ;\n\n    virtual double compute_cov_meanGPMC  ( std::vector<double>const& xstar, int const& xstar_idx, double const& noise) ;\n\n    virtual double bootstrap_diffGPMC ( std::vector<double>const& xstar, std::vector<std::vector<double>>const& samples, const unsigned int index, int max_bootstrap_samples = 100, int inp_seed = -1);\n\n    virtual const std::vector<std::vector<double>> &getGp_nodes() const;\n\n    virtual void get_induced_nodes(std::vector< std::vector<double> >&) const;\n\n    virtual void set_constraint_ball_radius(const double& radius){};\n\n    virtual void set_constraint_ball_center(const std::vector<double>& center){};\n\n    //virtual void set_hp_estimation(bool){};\n\n    //virtual void do_resample_u(){};\n\n    virtual bool test_for_parameter_estimation(const int& nb_values,\n                                                const int& update_interval_length,\n                                                const int& next_update,\n                                                const std::vector<int>& update_at_evaluations);\n\n    virtual void sample_u(const int &nb_u_nodes){exit(-1);};\n    virtual void clear_u(){exit(-1);};\n\n    virtual std::vector<double> get_hyperparameters();\n\n    virtual void decrease_nugget();\n    virtual bool increase_nugget();\n};\n\n#endif\n", "meta": {"hexsha": "0c39c2797b36c942568f4e0b245cca0364a1bcd9", "size": 7164, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/GaussianProcess.hpp", "max_stars_repo_name": "snowpac/snowpac", "max_stars_repo_head_hexsha": "ff4c6a83e01fc4ef6a78cf9ff9bf9358f972b305", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-08-04T20:18:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-22T23:50:27.000Z", "max_issues_repo_path": "include/GaussianProcess.hpp", "max_issues_repo_name": "snowpac/snowpac", "max_issues_repo_head_hexsha": "ff4c6a83e01fc4ef6a78cf9ff9bf9358f972b305", "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/GaussianProcess.hpp", "max_forks_repo_name": "snowpac/snowpac", "max_forks_repo_head_hexsha": "ff4c6a83e01fc4ef6a78cf9ff9bf9358f972b305", "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.3101604278, "max_line_length": 199, "alphanum_fraction": 0.6448911223, "num_tokens": 1470, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199754937772, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.48052449359168026}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2015 NumScale SAS\n  @copyright 2015 J.T. Lapreste\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_COMMON_GENERIC_FUNCTION_IS_NOT_DENORMAL_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_GENERIC_FUNCTION_IS_NOT_DENORMAL_HPP_INCLUDED\n\n#include <boost/simd/constant/smallestposval.hpp>\n#include <boost/simd/constant/true.hpp>\n#include <boost/simd/function/abs.hpp>\n#include <boost/simd/function/is_eqz.hpp>\n#include <boost/simd/function/is_not_less.hpp>\n#include <boost/simd/function/logical_or.hpp>\n#include <boost/simd/meta/as_logical.hpp>\n#include <boost/dispatch/function/overload.hpp>\n#include <boost/config.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  BOOST_DISPATCH_OVERLOAD ( is_not_denormal_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::generic_< bd::arithmetic_<A0> >\n                          )\n  {\n    using result = bs::as_logical_t<A0>;\n    BOOST_FORCEINLINE result operator() (const A0& ) const BOOST_NOEXCEPT\n    {\n      return True<result>();\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( is_not_denormal_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::generic_< bd::floating_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE  bs::as_logical_t<A0> operator() ( A0 const& a0) const BOOST_NOEXCEPT\n    {\n      return logical_or(is_eqz(a0), is_not_less(bs::abs(a0), Smallestposval<A0>()));\n    }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "cb0641e066401deb0ba01b8a9ad2b73c40e9d28b", "size": 1856, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arch/common/generic/function/is_not_denormal.hpp", "max_stars_repo_name": "yaeldarmon/boost.simd", "max_stars_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/simd/arch/common/generic/function/is_not_denormal.hpp", "max_issues_repo_name": "yaeldarmon/boost.simd", "max_issues_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/arch/common/generic/function/is_not_denormal.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.1428571429, "max_line_length": 100, "alphanum_fraction": 0.5738146552, "num_tokens": 406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.48052326124269434}}
{"text": "#include <vector>\n#include <iostream>\n#include <Eigen/Core>\n\n#include \"celerite/poly.h\"\n\nusing Eigen::VectorXd;\n\n#define ASSERT_ALL_CLOSE(NAME, VAR1, VAR2)                   \\\n{                                                            \\\n  if (VAR1.rows() != VAR2.rows()) {                          \\\n    std::cerr << \"Test failed: \" << #NAME << \" - dimension mismatch\" << std::endl; \\\n    return 1;                                                \\\n  }                                                          \\\n  double base, comp, delta;                                  \\\n  for (int iii = 0; iii < VAR1.rows(); ++iii) {              \\\n      base = VAR1[iii];                                      \\\n      comp = VAR2[iii];                                      \\\n      delta = std::abs(base - comp);                         \\\n      if (delta > 1e-10) {                                   \\\n        std::cerr << \"Test failed: \" << #NAME << \" - \" << iii << \": \" << base << \" != \" << comp << std::endl; \\\n        return 1;                                            \\\n      }                                                      \\\n  }                                                          \\\n  std::cerr << \"Test passed: \" << #NAME << std::endl; \\\n}\n\nint main (int argc, char* argv[])\n{\n  // Polymul\n  VectorXd a(3), b(2), c(4), d;\n  a << 3.0, 2.0, 1.0;\n  b << -2.0, -1.0;\n  c << -6.0, -7.0, -4.0, -1.0;\n  d = celerite::polymul(a, b);\n  ASSERT_ALL_CLOSE(\"polymul1\", c, d);\n  d = celerite::polymul(b, a);\n  ASSERT_ALL_CLOSE(\"polymul2\", c, d);\n\n  // Polyadd\n  c.resize(3);\n  c << 3.0, 0.0, 0.0;\n  d = celerite::polyadd(a, b);\n  ASSERT_ALL_CLOSE(\"polyadd1\", c, d);\n  d = celerite::polyadd(b, a);\n  ASSERT_ALL_CLOSE(\"polyadd2\", c, d);\n\n  // Polyval\n  double v = celerite::polyval(a, 0.5);\n  if (std::abs(v - 2.75) > 1e-10) {\n    std::cerr << \"Test failed: \\\"polyval\\\"\" << std::endl;\n    return 1;\n  } else {\n    std::cerr << \"Test passed: \\\"polyval\\\"\" << std::endl;\n  }\n\n  // Polyrem\n  c.resize(1);\n  c << 0.75;\n  d = celerite::polyrem(a, b);\n  std::cout << c.transpose() << std::endl << d.transpose() << std::endl;\n  ASSERT_ALL_CLOSE(\"polyrem1\", c, d);\n  d = celerite::polyrem(b, a);\n  ASSERT_ALL_CLOSE(\"polyrem2\", b, d);\n\n  // Polyder\n  c.resize(2);\n  c << 6.0, 2.0;\n  d = celerite::polyder(a);\n  ASSERT_ALL_CLOSE(\"polyder1\", c, d);\n  c.resize(1);\n  c << -2.0;\n  d = celerite::polyder(b);\n  ASSERT_ALL_CLOSE(\"polyder2\", c, d);\n\n  // Polyder\n  a.resize(5);\n  a << 1.0, 1.0, 0.0, -1.0, -1.0;\n  std::vector<VectorXd> sturm = celerite::polysturm(a);\n  if (sturm.size() != 5) {\n    std::cerr << \"Test failed: \\\"sturmshape\\\"\" << std::endl;\n    return 1;\n  } else {\n    std::cerr << \"Test passed: \\\"sturmshape\\\"\" << std::endl;\n  }\n  ASSERT_ALL_CLOSE(\"sturm1\", a, sturm[0]);\n  c.resize(4);\n  c << 4.0, 3.0, 0.0, -1.0;\n  ASSERT_ALL_CLOSE(\"sturm2\", c, sturm[1]);\n  c.resize(3);\n  c << 3./16., 0.75, 15./16.;\n  ASSERT_ALL_CLOSE(\"sturm3\", c, sturm[2]);\n  c.resize(2);\n  c << -32., -64.;\n  ASSERT_ALL_CLOSE(\"sturm4\", c, sturm[3]);\n  c.resize(1);\n  c << -3./16.;\n  ASSERT_ALL_CLOSE(\"sturm5\", c, sturm[4]);\n\n  // Count roots\n  int nroots = celerite::polycountroots(a);\n  a *= -1.0;\n  nroots += celerite::polycountroots(a);\n  if (nroots != 2) {\n    std::cerr << \"Test failed: \\\"countroots\\\"\" << std::endl;\n    return 1;\n  } else {\n    std::cerr << \"Test passed: \\\"countroots\\\"\" << std::endl;\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "e964b08d0adb31b3c83ba2f399485cfbdd8705a5", "size": 3393, "ext": "cc", "lang": "C++", "max_stars_repo_path": "cpp/src/test_poly.cc", "max_stars_repo_name": "dfm/ess", "max_stars_repo_head_hexsha": "09ee14e516bb3bc3b517c0c1b6716eaeb28183b1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 172.0, "max_stars_repo_stars_event_min_datetime": "2017-02-10T21:23:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T23:02:20.000Z", "max_issues_repo_path": "cpp/src/test_poly.cc", "max_issues_repo_name": "dfm/ess", "max_issues_repo_head_hexsha": "09ee14e516bb3bc3b517c0c1b6716eaeb28183b1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 90.0, "max_issues_repo_issues_event_min_datetime": "2017-01-12T21:31:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-26T13:13:50.000Z", "max_forks_repo_path": "cpp/src/test_poly.cc", "max_forks_repo_name": "dfm/ess", "max_forks_repo_head_hexsha": "09ee14e516bb3bc3b517c0c1b6716eaeb28183b1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 39.0, "max_forks_repo_forks_event_min_datetime": "2017-03-14T21:17:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-03T19:22:03.000Z", "avg_line_length": 30.0265486726, "max_line_length": 111, "alphanum_fraction": 0.4526967286, "num_tokens": 1120, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4805232553900528}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2007, 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 matrix.hpp\n    \\brief matrix used in linear algebra.\n*/\n\n#include <ql/math/matrix.hpp>\n#if defined(QL_PATCH_MSVC)\n#pragma warning(push)\n#pragma warning(disable:4180)\n#pragma warning(disable:4127)\n#endif\n\n#if defined(__GNUC__) && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 8)) || (__GNUC__ > 4))\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wunused-local-typedefs\"\n#endif\n\n#if defined(__clang__)\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Wunused-function\"\n#endif\n\n#if !defined(QL_NO_UBLAS_SUPPORT)\n#if BOOST_VERSION > 106300\n#include <boost/serialization/array_wrapper.hpp>\n#endif\n#include <boost/numeric/ublas/vector_proxy.hpp>\n#include <boost/numeric/ublas/triangular.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n#endif\n\n#if defined(QL_PATCH_MSVC)\n#pragma warning(pop)\n#endif\n\n#if defined(__GNUC__) && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 8)) || (__GNUC__ > 4))\n#pragma GCC diagnostic pop\n#endif\n\n#if defined(__clang__)\n#pragma clang diagnostic pop\n#endif\n\n\nnamespace QuantLib {\n\n    Disposable<Matrix> inverse(const Matrix& m) {\n        #if !defined(QL_NO_UBLAS_SUPPORT)\n\n        QL_REQUIRE(m.rows() == m.columns(), \"matrix is not square\");\n\n        boost::numeric::ublas::matrix<Real> a(m.rows(), m.columns());\n\n        std::copy(m.begin(), m.end(), a.data().begin());\n\n        boost::numeric::ublas::permutation_matrix<Size> pert(m.rows());\n\n        // lu decomposition\n        Size singular = 1;\n        try {\n            singular = lu_factorize(a, pert);\n        } catch (const boost::numeric::ublas::internal_logic& e) {\n            QL_FAIL(\"lu_factorize error: \" << e.what());\n        } catch (const boost::numeric::ublas::external_logic& e) {\n            QL_FAIL(\"lu_factorize error: \" << e.what());\n        }\n        QL_REQUIRE(singular == 0, \"singular matrix given\");\n\n        boost::numeric::ublas::matrix<Real>\n            inverse = boost::numeric::ublas::identity_matrix<Real>(m.rows());\n\n        // backsubstitution\n        try {\n            boost::numeric::ublas::lu_substitute(a, pert, inverse);\n        } catch (const boost::numeric::ublas::internal_logic& e) {\n            QL_FAIL(\"lu_substitute error: \" << e.what());\n        }\n\n        Matrix retVal(m.rows(), m.columns());\n        std::copy(inverse.data().begin(), inverse.data().end(),\n                  retVal.begin());\n\n        return retVal;\n\n        #else\n        QL_FAIL(\"this version of gcc does not support \"\n                \"the Boost uBLAS library\");\n        #endif\n    }\n\n    Real determinant(const Matrix& m) {\n        #if !defined(QL_NO_UBLAS_SUPPORT)\n        QL_REQUIRE(m.rows() == m.columns(), \"matrix is not square\");\n\n        boost::numeric::ublas::matrix<Real> a(m.rows(), m.columns());\n        std::copy(m.begin(), m.end(), a.data().begin());\n\n\n        // lu decomposition\n        boost::numeric::ublas::permutation_matrix<Size> pert(m.rows());\n        /* const Size singular = */ lu_factorize(a, pert);\n\n        Real retVal = 1.0;\n\n        for (Size i=0; i < m.rows(); ++i) {\n            if (pert[i] != i)\n                retVal *= -a(i,i);\n            else\n                retVal *=  a(i,i);\n        }\n        return retVal;\n\n        #else\n        QL_FAIL(\"this version of gcc does not support \"\n                \"the Boost uBLAS library\");\n        #endif\n    }\n}\n", "meta": {"hexsha": "44d18a47e1e100d9244b5f88a8b9481f026dfce7", "size": 4111, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ql/math/matrix.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/math/matrix.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/math/matrix.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": 30.0072992701, "max_line_length": 87, "alphanum_fraction": 0.6273412795, "num_tokens": 999, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4805232553900527}}
{"text": "#include <array>\n#include <vector>\n#include <iostream>\n#include <fstream>\n#include <utility>\n#include <algorithm>\n#include <boost/progress.hpp>\n#include <boost/program_options.hpp>\n#include <boost/python/numpy.hpp>\n#include \"latte.h\"\n\nusing namespace std;\nusing namespace latte;\nnamespace py = boost::python;\nnamespace np = boost::python::numpy;\n\n#if 0\nvoid test_auc () {\n    vector<pair<float, int>> all;\n    size_t n0 = 113;\n    size_t n1 = 119;\n    for (unsigned i = 0; i < n0; ++i) {\n        all.emplace_back(0, 0);\n    }\n    for (unsigned i = 0; i < n1; ++i) {\n        all.emplace_back(0, 1);\n    }\n    sort(all.begin(), all.end(), [](pair<float, int> const &p1, pair<float, int> const &p2) { return p1.second < p2.second;});\n    if (auc(all, n0, n1) != 1) throw 0;\n    cerr << \"Test 1 OK\" << endl;\n    sort(all.begin(), all.end(), [](pair<float, int> const &p1, pair<float, int> const &p2) { return p1.second > p2.second;});\n    if (auc(all, n0, n1) != 0) throw 0;\n    cerr << \"Test 2 OK\" << endl;\n    random_shuffle(all.begin(), all.end());\n    float v = auc(all, n0, n1);\n    if (v < 0.3) throw 1;\n    if (v > 0.7) throw 1;\n    cerr << \"Test 3 OK\" << endl;\n}\n#endif\n\ntemplate <typename T>\nvoid compare (np::ndarray v0, np::ndarray v1, vector<float> *ft) {\n    size_t n0 = v0.shape(0);\n    size_t n1 = v1.shape(0);\n    size_t ns = n0 + n1;\n    cerr << n0 << '\\t' << n1 << endl;\n    if (v0.shape(1) != Ref::GENES) throw 0;\n    if (v1.shape(1) != Ref::GENES) throw 0;\n\n    T const *p0 = (T const *)(v0.get_data());\n    T const *p1 = (T const *)(v1.get_data());\n\n    ft->resize(Ref::GENES);\n    boost::progress_display progress(Ref::GENES, cerr);\n#pragma omp parallel\n    {\n        vector<pair<T, int>> all;\n        all.reserve(ns);\n        // for each gene\n#pragma omp for\n        for (size_t gene = 0; gene < Ref::GENES; ++gene) {\n            all.clear();\n            for (size_t i = 0; i < n0; ++i) {\n                all.emplace_back(p0[Ref::GENES * i + gene], 0);\n            }\n            for (size_t i = 0; i < n1; ++i) {\n                all.emplace_back(p1[Ref::GENES * i + gene], 1);\n            }\n            sort(all.begin(), all.end());\n            ft->at(gene) = auc(all, n0, n1);\n#pragma omp critical\n            ++progress;\n        }\n    }\n}\n\n\nint main (int argc, char *argv[]) {\n    string input1_path;\n    string input2_path;\n    string output_path(\"output\");\n    {\n        namespace po = boost::program_options;\n        po::options_description desc_visible(\"Allowed options\");\n        desc_visible.add_options()\n            (\"help,h\", \"produce help message.\")\n            (\"input1\", po::value(&input1_path), \"\")\n            (\"input2\", po::value(&input2_path), \"\")\n            (\"output\", po::value(&output_path), \"\")\n            ;\n\n        po::options_description desc(\"Allowed options\");\n        desc.add(desc_visible);\n\n        po::positional_options_description p;\n        p.add(\"input1\", 1);\n        p.add(\"input2\", 1);\n        p.add(\"output\", 1);\n\n        po::variables_map vm;\n        po::store(po::command_line_parser(argc, argv).\n                         options(desc).positional(p).run(), vm);\n        po::notify(vm);\n        if (vm.count(\"help\") || input1_path.empty() || input2_path.empty()) {\n            cout << \"Usage:\" << endl;\n            cout << desc_visible;\n            cout << endl;\n            return 0;\n        }\n\t}\n    Py_Initialize();\n    np::initialize();\n    Ref genes(\"data/ref\");\n    py::object np_load = py::import(\"numpy\").attr(\"load\");\n    np::ndarray rank0 = np::array(np_load(input1_path));\n    np::ndarray rank = np::array(np_load(input2_path));\n\n    vector<float> ft;\n    if (np::dtype::get_builtin<float>() == rank0.get_dtype()) {\n        compare<float>(rank0, rank, &ft);\n    }\n    else if (np::dtype::get_builtin<uint16_t>() == rank0.get_dtype()) {\n        compare<uint16_t>(rank0, rank, &ft);\n    }\n    else {\n        cerr << \"dtype not supported.\" << endl;\n        throw 0;\n    }\n\n\n    if (ft.size() != genes.size()) throw 0;\n    ofstream os(output_path);\n    for (unsigned i = 0; i < Ref::GENES; ++i) {\n        os << genes[i] << '\\t' << ft[i] << endl;\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "d0717663f77d803b5e8efed5d3f91917601c0640", "size": 4136, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "compare.cpp", "max_stars_repo_name": "aaalgo/latte", "max_stars_repo_head_hexsha": "0a9e921d9eba94423699faa1105c88739c921378", "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": "compare.cpp", "max_issues_repo_name": "aaalgo/latte", "max_issues_repo_head_hexsha": "0a9e921d9eba94423699faa1105c88739c921378", "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": "compare.cpp", "max_forks_repo_name": "aaalgo/latte", "max_forks_repo_head_hexsha": "0a9e921d9eba94423699faa1105c88739c921378", "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.5428571429, "max_line_length": 126, "alphanum_fraction": 0.539893617, "num_tokens": 1209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4805232553900527}}
{"text": "#include <vector>\n#include <cmath>\n#include <Eigen/Core>\n#include <Eigen/Cholesky>\n#include <unsupported/Eigen/MatrixFunctions>\n\n#include \"ihgp/InfiniteHorizonGP.hpp\"\n\nconst double InfiniteHorizonGP::DARE_EPS = 1e-10;\nconst int InfiniteHorizonGP::DARE_MAXIT = 100;\n\nInfiniteHorizonGP::InfiniteHorizonGP(const double dt, const Eigen::MatrixXd &F, const Eigen::MatrixXd &HH, const Eigen::MatrixXd &Pinf, const double &R, const std::vector<Eigen::MatrixXd> &dF, const std::vector<Eigen::MatrixXd> &dPinf, const std::vector<double> &dR)\n{\n    // Solve A and Q (stationary systems)\n    A = (F*dt).exp();\n    Q = Pinf - A*Pinf*A.transpose();\n    Rc = R;\n\n    // Assign measurement model\n    H = HH;\n    \n    // Solve the discrete algebraic Riccati equation\n    Eigen::MatrixXd PP = InfiniteHorizonGP::DARE(A,H,Q,R);\n    PP_update = PP;\n\n    // Stationary innovation variance\n    S = (H*PP*H.transpose())(0) + R;\n    \n    // Stationary gain\n    K = PP*H.transpose()/S;\n    \n    // State covariance\n    PF = PP - K*H*PP;\n    \n    // Pre-calculate\n    HA = (H*A).transpose();\n    AKHA = A-K*H*A;\n    \n    // Number of parameters\n    nparam = (int)dF.size();\n    \n    // State dimensionality\n    int dim = (int)F.rows();\n    \n    // Initialize mean and helpers\n    m.setZero(dim);\n    \n    // Prepare\n    Eigen::MatrixXd AK = A*K;\n    Eigen::MatrixXd FF(2*dim,2*dim);\n    FF.setZero();\n    FF.topLeftCorner(dim,dim) = F;\n    FF.bottomRightCorner(dim,dim) = F;\n    \n    // Allocate the arrays\n    HdA  = new Eigen::VectorXd[nparam];\n    dK = new Eigen::VectorXd[nparam];\n    dAKHA = new Eigen::MatrixXd[nparam];\n    dS = new double[nparam];\n    dm = new Eigen::VectorXd[nparam];\n    \n    // Pre-calculate the needed derivative matrices\n    for (int j=0; j<nparam; j++)\n    {\n        // Assign derivative of drift model matrix\n        FF.bottomLeftCorner(dim,dim) = dF[j];\n        \n        // Solve the matrix exponential (see ...)\n        Eigen::MatrixXd AA = (FF*dt).exp();\n        \n        // Extract the derivative of the discrete-time dynamic model\n        Eigen::MatrixXd dA = AA.bottomLeftCorner(dim,dim);\n        Eigen::MatrixXd dQ = dPinf[j] - dA*Pinf*A.transpose() - A*dPinf[j]*A.transpose() - A*Pinf*dA.transpose();\n        dQ = .5*(dQ+dQ.transpose()).eval();\n        \n        // Precalculate C\n        Eigen::MatrixXd C = dA*PP*A.transpose() + A*PP*dA.transpose() - dA*PP*H.transpose()*AK.transpose() - AK*H*PP*dA.transpose() + AK*dR[j]*AK.transpose() + dQ;\n        C = .5*(C+C.transpose()).eval();\n\n        // Solve DARE\n        Eigen::MatrixXd dPP = InfiniteHorizonGP::DARE(A-AK*H,Eigen::MatrixXd::Zero(dim,dim),C,0.0);\n        \n        // Evaluate dS and dK\n        dS[j] = (H*dPP*H.transpose())(0) + dR[j];\n        dK[j] = dPP*H.transpose()/S - PP*H.transpose()*(((H*dPP*H.transpose())(0)+dR[j])/S/S);\n        dAKHA[j] = dA - dK[j]*H*A - K*H*dA;\n        HdA[j] = (H*dA).transpose();\n\n        // Initial dm\n        dm[j] = Eigen::VectorXd::Zero(dim);\n        \n    }\n\n    // Initialize log likelihood and its gradient\n    edata = 0;\n    gdata = Eigen::VectorXd::Zero(nparam);\n}\n\nInfiniteHorizonGP::~InfiniteHorizonGP()\n{\n    delete[] HdA;\n    delete[] dK;\n    delete[] dAKHA;\n    delete[] dS;\n    delete[] dm;\n}\n\nvoid InfiniteHorizonGP::init_step()\n{\n    // Initialize log likelihood and its gradient\n    edata = 0;\n    gdata = Eigen::VectorXd::Zero(nparam);\n\n    // Update \n    // Stationary innovation variance\n    S = (H*PP_update*H.transpose())(0) + Rc;\n    \n    // Stationary gain\n    K = PP_update*H.transpose()/S;\n    \n    // State covariance\n    PF = PP_update - K*H*PP_update;\n    \n    // Pre-calculate\n    HA = (H*A).transpose();\n    AKHA = A-K*H*A;\n\n    //\n    MF.clear();\n}\n    \nvoid InfiniteHorizonGP::update(const double &y)\n{\n    // Define constants\n    const double PI = 3.141592654;\n    \n    // Innovation mean\n    double v = y - HA.dot(m);\n\n    // Update marginal likelihood\n    edata += .5*v*v/S + .5*log(2*PI) + .5*log(S);\n    \n    // Update derivatives\n    for (int j=0; j<nparam; j++)\n    {\n        // Derivatives of innovation mean\n        double dv = -HdA[j].dot(m) - HA.dot(dm[j]);\n\n        // Derivatives of marginal likelihood\n        gdata(j) += v*dv/S - .5*v*v*dS[j]/S/S + .5*dS[j]/S;\n\n        // Derivatives of state mean\n        dm[j] = dAKHA[j]*m + AKHA*dm[j] + dK[j]*y;\n    }\n    \n    // Recursion for the state mean\n    m = AKHA*m + K*y;\n\n    // Store state mean for possible backward pass\n    MF.push_back(m);\n    \n}\n\nstd::vector<double> InfiniteHorizonGP::getEft()\n{\n    // Solve backward smoother gain\n    int dim = (int)A.rows();\n    Eigen::MatrixXd PP = A*PF*A.transpose()+Q;\n    Eigen::LDLT<Eigen::MatrixXd> PPldl = PP.ldlt();\n    Eigen::MatrixXd G = PPldl.solve(A*PF).transpose();\n    \n    // Solve smoother state covariance\n    // Eigen::MatrixXd QQ = PF-G*PP*G.transpose();\n    // QQ = .5*(QQ+QQ.transpose()).eval();\n    // P = InfiniteHorizonGP::DARE(G,Eigen::MatrixXd::Zero(dim,dim),QQ,0.0);\n    \n    // Output vector\n    std::vector<double> Eft;\n    \n    // Initialize with last element\n    m = MF[MF.size()-1];\n    Eft.push_back((H*m)(0));\n    \n    // Run backward pass\n    for (int k=(int)MF.size()-2; k>=0; k--)\n    {\n        m = MF[k] + G*(m-A*MF[k]);\n        Eft.push_back((H*m)(0));\n    }\n    \n    // Reverse\n    std::reverse(Eft.begin(),Eft.end());\n    \n    return Eft;\n    \n}\n\ndouble InfiniteHorizonGP::getVarft()\n{\n    return (H*P*H.transpose())(0);\n}\n\ndouble InfiniteHorizonGP::getLik()\n{\n    return edata;\n}\n\nEigen::VectorXd InfiniteHorizonGP::getLikDeriv()\n{\n    return gdata;\n}\n\nEigen::MatrixXd InfiniteHorizonGP::DARE(const Eigen::MatrixXd &A, const Eigen::MatrixXd &B, const Eigen::MatrixXd &Q, const double &R)\n{\n\n    // Initial guess\n    int dim = (int)A.rows();\n    Eigen::MatrixXd X(dim,dim);\n    Eigen::MatrixXd X_prev(dim,dim);\n    Eigen::MatrixXd K(dim,B.rows());\n    X.setIdentity();\n    \n    // Number of loops\n    int n = 0;\n    \n    // Iterate a maximum of 100 iterations\n    while (n < DARE_MAXIT)\n    {\n        // Step\n        n++;\n        X_prev = X;\n\n        // Gain (NB: Does not work in the general case, but for scalar R and possibly zero B)\n        if (abs(R) < 1e-15)\n        {\n            K.setZero();\n        } else {\n            K = A*(X*B.transpose() / ((B*X*B.transpose())(0)+R));\n        }\n        \n        // Recursion\n        X = (A - K*B)*X*(A - K*B).transpose() + K*R*K.transpose() + Q;\n        \n        // Check if we should break (use the Frobenius norm)\n        if ((X-X_prev).norm() < DARE_EPS)\n        {\n            break;\n        }\n    }\n    \n    return X;\n}\n", "meta": {"hexsha": "0668bd9cf9abe2cbdc517f664cde40dd4e34f85f", "size": 6558, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ihgp/InfiniteHorizonGP.cpp", "max_stars_repo_name": "MLCS-Yonsei/multiple-object-tracking-lidar", "max_stars_repo_head_hexsha": "b76f6892a0c97a28d946eef66ccd84712321f28b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-12T06:33:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-12T06:33:03.000Z", "max_issues_repo_path": "src/ihgp/InfiniteHorizonGP.cpp", "max_issues_repo_name": "MLCS-Yonsei/multiple-object-tracking-lidar", "max_issues_repo_head_hexsha": "b76f6892a0c97a28d946eef66ccd84712321f28b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ihgp/InfiniteHorizonGP.cpp", "max_forks_repo_name": "MLCS-Yonsei/multiple-object-tracking-lidar", "max_forks_repo_head_hexsha": "b76f6892a0c97a28d946eef66ccd84712321f28b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-11-23T10:52:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-14T13:18:32.000Z", "avg_line_length": 25.9209486166, "max_line_length": 266, "alphanum_fraction": 0.5664836841, "num_tokens": 1941, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956580903722561, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4805232495374108}}
{"text": "#include <Eigen/Dense>\n#include <lie_mpc_bidirectional.hpp>\n#define CATCH_CONFIG_MAIN\n#include <catch2/catch.hpp>\n#include <chrono>\n#include <iostream>\n\nTEST_CASE(\"Hover\")\n{\n  Eigen::VectorXd x_lin = Eigen::VectorXd(18);\n  Eigen::VectorXd u_lin = Eigen::VectorXd(4);\n  Eigen::VectorXd Y = Eigen::VectorXd::Zero(8 * 12);\n  x_lin << 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 1., 0., 0., 0., 1., 0., 0., 0.;\n  u_lin << 2.4525, 2.4525, 2.4525, 2.4525;\n  for (int i = 0; i < 8; i++) {\n    Y(i * 12 + 3) = 1.;\n    Y(i * 12 + 7) = 1.;\n    Y(i * 12 + 11) = 1.;\n  }\n  LieMPC test_controller;\n  test_controller.x = x_lin;\n  test_controller.u_lin = u_lin;\n  test_controller.Y = Y;\n  std::chrono::steady_clock::time_point tic = std::chrono::steady_clock::now();\n  test_controller.linearize();\n  test_controller.discretize();\n  test_controller.build_mpc();\n  test_controller.solve();\n  std::chrono::steady_clock::time_point toc = std::chrono::steady_clock::now();\n  std::cout << \"Time elapsed = \" << std::chrono::duration_cast<std::chrono::microseconds>(toc - tic).count() << \"[\u00b5s]\" << std::endl;\n  REQUIRE((std::abs(test_controller.u(0) - 2.4525) < 0.05 && std::abs(test_controller.u(1) - 2.4525) < 0.05 && std::abs(test_controller.u(2) - 2.4525) < 0.05 && std::abs(test_controller.u(3) - 2.4525) < 0.05));\n};\n\nTEST_CASE(\"Inverted Hover\")\n{\n  Eigen::VectorXd x_lin = Eigen::VectorXd(18);\n  Eigen::VectorXd u_lin = Eigen::VectorXd(4);\n  Eigen::VectorXd Y = Eigen::VectorXd::Zero(8 * 12);\n  x_lin << 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., -1., 0., 0., 0., -1., 0., 0., 0.;\n  u_lin << -2.4525, -2.4525, -2.4525, -2.4525;\n  for (int i = 0; i < 8; i++) {\n    Y(i * 12 + 3) = 1.;\n    Y(i * 12 + 7) = -1.;\n    Y(i * 12 + 11) = -1.;\n  }\n  LieMPC test_controller;\n  test_controller.x = x_lin;\n  test_controller.u_lin = u_lin;\n  test_controller.Y = Y;\n  std::chrono::steady_clock::time_point tic = std::chrono::steady_clock::now();\n  test_controller.linearize();\n  test_controller.discretize();\n  test_controller.build_mpc();\n  test_controller.solve();\n  std::chrono::steady_clock::time_point toc = std::chrono::steady_clock::now();\n  std::cout << \"Time elapsed = \" << std::chrono::duration_cast<std::chrono::microseconds>(toc - tic).count() << \"[\u00b5s]\" << std::endl;\n  REQUIRE((std::abs(test_controller.u(0) + 2.4525) < 0.05 && std::abs(test_controller.u(1) + 2.4525) < 0.05 && std::abs(test_controller.u(2) + 2.4525) < 0.05 && std::abs(test_controller.u(3) + 2.4525) < 0.05));\n};\n\nTEST_CASE(\"Runtime\")\n{\n  Eigen::VectorXd x_lin = Eigen::VectorXd(18);\n  Eigen::VectorXd u_lin = Eigen::VectorXd(4);\n  Eigen::VectorXd Y = Eigen::VectorXd::Zero(8 * 12);\n  x_lin << 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 1., 0., 0., 0., 1., 0., 0., 0.;\n  u_lin << 2.4525, 2.4525, 2.4525, 2.4525;\n  for (int i = 0; i < 8; i++) {\n    Y(i * 12 + 3) = 1.;\n    Y(i * 12 + 7) = 1.;\n    Y(i * 12 + 11) = 1.;\n  }\n  LieMPC test_controller;\n  test_controller.x = x_lin;\n  test_controller.u_lin = u_lin;\n  test_controller.Y = Y;\n  std::chrono::steady_clock::time_point tic = std::chrono::steady_clock::now();\n  test_controller.linearize();\n  test_controller.discretize();\n  test_controller.build_mpc();\n  test_controller.solve();\n  std::chrono::steady_clock::time_point toc = std::chrono::steady_clock::now();\n  std::cout << \"Time elapsed = \" << std::chrono::duration_cast<std::chrono::microseconds>(toc - tic).count() << \"[\u00b5s]\" << std::endl;\n  REQUIRE(std::chrono::duration_cast<std::chrono::microseconds>(toc - tic).count() < 20000);\n};\n\nTEST_CASE(\"Consistency\")\n{\n  Eigen::VectorXd x_lin = Eigen::VectorXd(18);\n  Eigen::VectorXd u_lin = Eigen::VectorXd(4);\n  Eigen::VectorXd u_init = Eigen::VectorXd(4);\n  Eigen::VectorXd Y = Eigen::VectorXd::Zero(8 * 12);\n  x_lin << 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.7071, -0.7071, 0., 0.6830, 0.6830, -0.2588, 0.1830, 0.1830, 0.9659, 0.1, 0.1, 0.1;\n  u_lin << 2.4525, 2.4525, 2.4525, 2.4525;\n  for (int i = 0; i < 8; i++) {\n    Y(i * 12 + 3) = 1.;\n    Y(i * 12 + 7) = 1.;\n    Y(i * 12 + 11) = 1.;\n  }\n  LieMPC test_controller;\n  test_controller.x = x_lin;\n  test_controller.u_lin = u_lin;\n  test_controller.Y = Y;\n  std::chrono::steady_clock::time_point tic = std::chrono::steady_clock::now();\n  test_controller.linearize();\n  test_controller.discretize();\n  test_controller.build_mpc();\n  test_controller.solve();\n  u_init = test_controller.u;\n  for (int i = 0; i < 10; i++) {\n    test_controller.linearize();\n    test_controller.discretize();\n    test_controller.build_mpc();\n    test_controller.solve();\n  }\n  std::chrono::steady_clock::time_point toc = std::chrono::steady_clock::now();\n  std::cout << \"Time elapsed = \" << std::chrono::duration_cast<std::chrono::microseconds>(toc - tic).count() << \"[\u00b5s]\" << std::endl;\n  REQUIRE((std::abs(test_controller.u(0) - u_init(0)) < 1e-8 && std::abs(test_controller.u(1) - u_init(1)) < 1e-8 && std::abs(test_controller.u(2) - u_init(2)) < 1e-8 && std::abs(test_controller.u(3) - u_init(3)) < 1e-8));\n};\n", "meta": {"hexsha": "8ab4becfad13511e90a89099629d417c94e935f2", "size": 4933, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test.cpp", "max_stars_repo_name": "JadWehbeh/lie_mpc_bidirectional", "max_stars_repo_head_hexsha": "ad609da4a6c4e12e0436ee5b7f0078b7086ed32b", "max_stars_repo_licenses": ["MIT"], "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.cpp", "max_issues_repo_name": "JadWehbeh/lie_mpc_bidirectional", "max_issues_repo_head_hexsha": "ad609da4a6c4e12e0436ee5b7f0078b7086ed32b", "max_issues_repo_licenses": ["MIT"], "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.cpp", "max_forks_repo_name": "JadWehbeh/lie_mpc_bidirectional", "max_forks_repo_head_hexsha": "ad609da4a6c4e12e0436ee5b7f0078b7086ed32b", "max_forks_repo_licenses": ["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.4537815126, "max_line_length": 222, "alphanum_fraction": 0.6211230489, "num_tokens": 1786, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.4805057412061475}}
{"text": "\n\n#include <iostream>\n#include <opencv2/opencv.hpp>\n#include <string>\n#include <vector>\n#include <algorithm>\n#include <tuple>\n\n\n#include \"LoomoOdo.h\"\n#include \"LoomoCSVReader.h\"\n#include \"Utils.h\"\n#include \"PoseGraph.h\"\n#include \"LoomoVision.h\"\n\n\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <opencv2/core/eigen.hpp>\n\n\nusing namespace cv;\nusing namespace std;\nusing std::cout; using std::endl;\nusing loomo::Pose; using loomo::kMatrix; using loomo::dCoeff;\n\nint main()\n{\n    string path = __FILE__; //gets source code path, including file name\n    path = path.substr(0, 1 + path.find_last_of('\\\\')); //removes file name\n    string pathLoomo1 = path + \"LoomoRecordings\\\\0069\\\\\";\n\n    vector<CSVData> dataLoomo1 = LoomoCSVReader::string2data(LoomoCSVReader::getData(pathLoomo1 + \"sensor_data.csv\"));\n\n\n    VideoCapture capFisheyeLoomo1(pathLoomo1 + \"hallway_00_fisheye.avi\");\n    //VideoCapture capFisheyeLoomo1(0);\n    if (!capFisheyeLoomo1.isOpened()) {\n        cout << \"Error openeing video file\" << endl;\n        return -1;\n    }\n    Mat capFrame, greyFrame, comp1, comp2, compImg;\n    vector<KeyPoint> kp, kp1, kp2;\n    Mat descriptors, dscr1, dscr2;\n    //vector<DMatch> matches;\n    loomo::LoomoVision mVision;\n\n\n\n\n\n    loomo::LoomoOdo loomo1;\n    vector<loomo::Pose> odoTraj = { {0.0, 0.0, 0.0} };\n    vector<loomo::Pose> tmpOdoTraj = { {0.0, 0.0, 0.0} };\n\n\n    poseGraph::PoseGraph graph1(1U);\n    map<uint64_t, poseGraph::Node> *nodeMap = graph1.getNodeMap();\n    uint64_t currentNodeKey = nodeMap->begin()->first;\n    uint64_t prevNodeKey;\n\n\n    Pose odoIncrement = { 0.0, 0.0, 0.0 };\n    double grossTraveledDistance = 0;\n    double incrementDistance = 0;\n    //Eigen::Matrix3d odoUncertainty;\n\n    for (size_t i = 1; i < dataLoomo1.size(); ++i) {\n        int dTickL = dataLoomo1[i].tick_left - dataLoomo1[i - 1].tick_left;\n        int dTickR = dataLoomo1[i].tick_right - dataLoomo1[i - 1].tick_right;\n        loomo1.incrementPose(dTickL, dTickR);\n\n        //odoUncertainty = loomo1.getUncertainty();\n\n        odoIncrement += loomo1.getIncrement();\n        tmpOdoTraj.push_back(odoIncrement);\n        incrementDistance += loomo1.getIncrement().norm();\n        grossTraveledDistance += loomo1.getIncrement().norm();\n\n        if (dataLoomo1[i].fisheye_idx != dataLoomo1[i - 1].fisheye_idx) {\n            capFisheyeLoomo1 >> capFrame;\n            if (capFrame.empty()) {\n                cout << \"End of video\" << endl;\n                break;\n            }\n            cvtColor(capFrame, greyFrame, COLOR_BGR2GRAY);\n        }\n\n\n        //// add new node every 1m\n        if ((incrementDistance > 1000.0) || (abs(odoIncrement.theta) > loomo::PI / 4)) {\n            prevNodeKey = currentNodeKey;\n\n            // append to odoTraj\n            {\n                double theta = odoTraj.back().theta;\n                Eigen::Vector3d prevPose(odoTraj.back().x, odoTraj.back().y, theta);\n                Eigen::Matrix3d rot;\n                rot << cos(theta), -sin(theta), 0,\n                    sin(theta), cos(theta), 0,\n                    0, 0, 1;\n                for (auto & pose : tmpOdoTraj) {\n                    Eigen::Vector3d tmp(pose.x, pose.y, pose.theta);\n                    tmp = rot * tmp;\n                    tmp += prevPose;\n                    pose = { tmp(0), tmp(1), tmp(2) };\n                }\n                odoTraj.insert(odoTraj.end(), tmpOdoTraj.begin(), tmpOdoTraj.end());\n            }\n            currentNodeKey = graph1.addNodeFromOdo(loomo1.getPose(), loomo1.getUncertainty());\n\n            // iterator (pointer) to nodes\n            auto itCurrentNode = nodeMap->find(currentNodeKey);\n            auto itPrevNode = nodeMap->find(prevNodeKey);\n\n            mVision.detectFeatures(\n                greyFrame,\n                itCurrentNode->second.keyPoints,\n                itCurrentNode->second.descriptors\n            );\n\n            //Match current and previous node\n            if (!(itPrevNode->second.descriptors).empty()) {\n                vector<DMatch> matches;\n                mVision.matchImages(\n                    itCurrentNode->second.descriptors,\n                    itPrevNode->second.descriptors,\n                    matches\n                );\n                // need at least 6 points to estimate the essential matrix\n                //if (matches.size() > 5) {\n                Mat E, R, t;\n                if (mVision.tryRecoverPose(itCurrentNode->second.keyPoints, itPrevNode->second.keyPoints, matches, E, R, t)) {\n                    //    //Eigen::Vector3d pose;\n                    //    //pose << itCurrentNode->second.pose.x, itCurrentNode->second.pose.y, itCurrentNode->second.pose.theta;\n                    //    ////Eigen::Matrix4d rotPitch, rot, T;\n                    //    //Mat rotPitch, rot, T = Mat::zeros(4,4, CV_64FC1);\n                    //    //rotPitch = (cv::Mat_<double>(4, 4) << \n                    //    //    0, 0, -1, 0,\n                    //    //    0, 1, 0, 0,\n                    //    //    1, 0, 0, 0,\n                    //    //    0, 0, 0, 1);\n                    //    //rot = (Mat_<double>(4,4) <<\n                    //    //    cos(pose(2)), -sin(pose(2)), 0, 0,\n                    //    //    sin(pose(2)), cos(pose(2)), 0, 0,\n                    //    //    0, 0, 1, 0,\n                    //    //    0, 0, 0, 1);\n                    //    //Rect srcRectR(Point(0, 0), Size(R.rows, R.cols));\n                    //    //Rect dstRectR(Point(0, 0), srcRectR.size());\n                    //    //R(srcRectR).copyTo(T(dstRectR));\n                    //    //Rect srcRectT(Point(0, 0), Size(R.rows, R.cols));\n                    //    //Rect dstRectT(Point(0, 0), srcRectT.size());\n                    //    //t(srcRectT).copyTo(T(dstRectT));\n\n                    //    //Mat constraint6dof = rot * rotPitch*T;\n\n\n\n                    //    //t = R * t;\n                    double ang = asin(R.at<double>(0, 1));\n                    cout << \"Ang = \" << ang << \", theta = \" << odoIncrement.theta << endl;\n                    //if (R.at<double>(1, 0) < 0)\n                    //    ang *= -1;\n                    double scale = odoIncrement.norm();\n                    Pose tmp = { t.at<double>(2)*scale, t.at<double>(1)*scale, ang };\n                    Eigen::Matrix3d covar = Eigen::Matrix3d::Zero();\n                    covar.block<2, 2>(0, 0) = loomo1.getUncertainty().block<2, 2>(0, 0);\n                    covar.block(0, 0, 2, 2) *= 1.5;\n                    covar(2, 2) = loomo1.getUncertainty()(2, 2);\n                    //covar.block<2, 1>(0, 2) = loomo1.getUncertainty().block<2, 1>(0, 2) * 0.5;\n                    //covar.block<1, 2>(2, 0) = loomo1.getUncertainty().block<1, 2>(2, 0) * 0.5;\n                    double scale1 = 4.8 * exp(-0.04*(matches.size() - 6)) + 0.2;\n                    double scale2 = 50.0 / matches.size();\n                    //cout << \"Covar theta odo: \" << covar(2, 2) << endl;\n                    covar *= scale1;\n                    //cout << \"Covar theta scaled: \" << covar(2, 2) << endl;\n                    //covar(2, 2) = scale1;\n                    graph1.addVirtualEdge(tmp, prevNodeKey, covar);\n\n                    //graph1.optimizeGraph();\n                //    //cout << \"R:\" << endl << R << endl;\n                //    //cout << \"Matches: \" << matches.size() << endl;\n                //    //cout << \"Scale log: \" << scale2 << \", scale exp: \" << scale1 << endl;\n                //    //cout << \"t:\" << endl << t << endl;\n                //    //cout << \"img matching: (\" << tmp.x << \", \" << tmp.y << \", \" << tmp.theta << \")\" << endl;\n                //    //cout << \"odo: (\" << odoIncrement.x << \", \" << odoIncrement.y << \", \" << odoIncrement.theta << \")\" << endl;\n                }\n                else {\n                    cout << \"Recover pose unsuccessful. N.o. matches = \" << matches.size() << endl;\n                }\n\n            }\n\n\n            odoIncrement = { 0.0, 0.0, 0.0 };\n            tmpOdoTraj.clear();\n            loomo1.reset();\n            incrementDistance = 0;\n        }\n\n    }\n\n    cout << \"Gross distance: \" << grossTraveledDistance / 1000 << \" m\" << endl;\n    cout << \"Odo \\\"miss\\\": \" << odoTraj.back().norm() << \" mm\" << endl;\n\n\n\n\n    /*\n    check for matches\n    */\n    //for (auto node_i = nodeMap->begin(); node_i != nodeMap->end(); node_i++) {\n    //    int i = 0;\n    //    //cout << \"Node \" << (uint32_t)node_i->first << endl;\n    //    for (auto node_j = nodeMap->begin(); node_j != nodeMap->end(); node_j++) {\n    //        vector<DMatch> matches;\n    //        ++i;\n\n    //        if (!(node_j->second.descriptors).empty() && !(node_i->second.descriptors).empty()) {\n    //            mVision.matchImages(\n    //                node_i->second.descriptors,\n    //                node_j->second.descriptors,\n    //                matches\n    //            );\n    //            cout << matches.size();\n    //        }\n    //        else {\n    //            cout << \"0\";\n    //        }\n    //        //cout << (uint32_t)node_j->first;\n    //        cout << \",\";\n    //    }\n    //    cout << endl;\n    //    //cout << --i << endl;\n    //}\n\n\n\n\n    poseGraph::PoseGraph graph2 = graph1;\n    //Eigen::Matrix3d covar = Eigen::Matrix3d::Identity() *1000;\n    //Pose tmp = { 0.0, 0.0, loomo::PI };\n    //graph2.addVirtualEdge(tmp, nodeMap->begin()->first, covar);\n    cv::imshow(\"Graph trajectory w/o final edge\", slamUtils::drawGraph(graph2));\n    graph2.optimizeGraph();\n    graph2.optimizeGraph();\n    graph2.optimizeGraph();\n    graph2.optimizeGraph();\n    graph2.optimizeGraph();\n    graph2.optimizeGraph();\n    cv::imshow(\"Graph trajectory w/o final edge, w. post optimization\", slamUtils::drawGraph(graph2));\n\n    Eigen::Matrix3d covar = Eigen::Matrix3d::Identity();// *0.1;\n    Pose tmp = { 0.0, 0.0, loomo::PI };\n    //Pose tmp = { 0.0, 0.0, 0.0 };\n    graph1.addVirtualEdge(tmp, nodeMap->begin()->first, covar);\n    cv::imshow(\"Graph trajectory\", slamUtils::drawGraph(graph1));\n    graph1.optimizeGraph();\n    graph1.optimizeGraph();\n    graph1.optimizeGraph();\n    graph1.optimizeGraph();\n    graph1.optimizeGraph();\n    graph1.optimizeGraph();\n    cv::imshow(\"Graph trajectory w. post optimization\", slamUtils::drawGraph(graph1));\n\n    cout << \"\\\"odo\\\"-Graph \\\"miss\\\": \" << graph2.getNodeMap()->find(currentNodeKey)->second.pose.norm() << \" mm\" << endl;\n    cout << \"Graph \\\"miss\\\": \" << graph1.getNodeMap()->find(currentNodeKey)->second.pose.norm() << \" mm\" << endl;\n\n\n    cv::imshow(\"Odometry trajectory\", slamUtils::drawOdoTrajectory(odoTraj));\n    cv::waitKey(0);\n}\n", "meta": {"hexsha": "e6aedcbf047d930a8fae1047f1de1144e9879ae3", "size": 10560, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "LoomoSLAM/LoomoSLAM.cpp", "max_stars_repo_name": "Jakob1-5/LoomoSLAM", "max_stars_repo_head_hexsha": "e907a11b1c01f426ccbc3884ed6175ec1d113760", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-06-24T03:52:06.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-06T09:59:15.000Z", "max_issues_repo_path": "LoomoSLAM/LoomoSLAM.cpp", "max_issues_repo_name": "Jakob1-5/LoomoSLAM", "max_issues_repo_head_hexsha": "e907a11b1c01f426ccbc3884ed6175ec1d113760", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LoomoSLAM/LoomoSLAM.cpp", "max_forks_repo_name": "Jakob1-5/LoomoSLAM", "max_forks_repo_head_hexsha": "e907a11b1c01f426ccbc3884ed6175ec1d113760", "max_forks_repo_licenses": ["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.5401459854, "max_line_length": 130, "alphanum_fraction": 0.5014204545, "num_tokens": 2981, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4805057412061474}}
{"text": "#include <iostream>\n#include <fstream>\n#include <algorithm>    // std::swap\n#include <vector>       // std::vector\n#include <cstdlib>\n#include <windows.h>\n\n#include <dlib/svm_threaded.h>\n#include <dlib/rand.h>\n#include <dlib/matrix.h>\n\nusing namespace std;\nusing namespace dlib;\n\n\ntemplate <typename T>\nvoid remove(std::vector<T>& vec, size_t pos)\n{\n\tstd::vector<T>::iterator it = vec.begin();\n\tstd::advance(it, pos);\n\tvec.erase(it);\n}\n\ndouble calculateaccuracy(matrix<double>  confusionmatrix)\n{\n\tint TValue = 0;\n\tint FValue = 0;\n\tfor (int i = 0; i < 11; i++) {\n\t\tfor (int j = 0; j < 11; j++)\n\t\t{\n\t\t\tif (i == j)\n\t\t\t{\n\t\t\t\tTValue += confusionmatrix(i, j);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tFValue += confusionmatrix(i, j);\n\t\t\t}\n\n\t\t}\n\n\t}\n\tprintf(\"T: %d, F :%d\", TValue, FValue);\n\treturn (TValue / double(TValue + FValue));\n}\n\n\n/*double dlib_svm_Multi_Leaveoneout(std::vector<std::vector<double>> features_, std::vector<double> label_, int feature_size_, int noSamples, double alfa)\n{\n\ttypedef matrix<double, 703, 1> sample_type; // 4 = Feature Size, cannot be set to variable !!!!\n\n\tstd::vector<sample_type> feature_dlib;\n\tstd::vector<sample_type> feature_train_dlib;\n\tstd::vector<sample_type> feature_test_dlib;\n\n\tstd::vector<double> train_label;\n\tstd::vector<double> test_label;\n\n\t//Filling Vector_Matrix\n\tdouble TotAccuracy = 0;\t//# true positives\n\tdouble accuracy = 0;\n\n\t//printf(\"started.. \\n\");\n\tfor (int m = 0; m < noSamples; m++)\n\t{\n\t\tsample_type temp;\n\t\ttemp.set_size(feature_size_);\n\t\t//cout << \"Set size \" << temp.size  << endl;\n\n\t\tfor (int j = 0; j < feature_size_; j++)\n\t\t\ttemp(j, 0) = features_[m][j];\n\n\t\tfeature_dlib.push_back(temp);\n\n\t}\n\n\tclock_t begin = clock();\n\n\t//Leave-One-out\n\tfor (int testid = 0; testid < noSamples; testid++)\n\t{\n\n\t\tdouble  error = 0;\n\t\taccuracy = 0;\n\t\t//printf(\"Feature dlib %d\", feature_dlib.data()[testid]);\n\t\tfeature_test_dlib.push_back(feature_dlib.data()[testid]);\n\t\ttest_label.push_back(label_.data()[testid]);\n\t\tfeature_train_dlib = feature_dlib;\n\t\tremove(feature_train_dlib, testid);\n\t\ttrain_label = label_;\n\t\tremove(train_label, testid);\n\n\t\ttypedef linear_kernel<sample_type> linear_kernel;\n\n\t\ttypedef svm_multiclass_linear_trainer <linear_kernel, double> svm_mc_trainer;\n\t\tsvm_mc_trainer trainer;\n\t\t//printf(\"Thread %d \\n\", trainer.get_num_threads());\n\n\n\t\tmulticlass_linear_decision_function<linear_kernel, double> df = trainer.train(feature_train_dlib, train_label);\n\n\t\t//randomize_samples(feature_dlib, label_);\n\t\t//accuracy = cross_validate_multiclass_trainer(trainer, feature_dlib, label_, 5);\n\t\t//printf(\"accuracy %5.1f\", accuracy);\n\t\tdouble prediction = df(feature_test_dlib[0]);\n\t\tprintf(\"Prediction %d, Expecct %d \\n\",prediction,test_label[0]);\n\t\tif (prediction != test_label[0])\n\t\t{\n\t\t\terror = 1;\n\t\t\t//printf(\"ERROR \\n\");\n\t\t}\n\t\taccuracy = 1 - (error);\n\t\tTotAccuracy += accuracy;\n\t}\n\tclock_t end = clock();\n\tprintf(\"has completed in %4.1f seconds and accuracy %f \\n\", double(end - begin) / CLOCKS_PER_SEC, TotAccuracy);\n\treturn TotAccuracy / noSamples;\n\n}\n\n*/\n\n\ndouble dlib_svm_multiclass_kfold(std::vector<std::vector<double>> features_, std::vector<double> label_, int feature_size_, int noSamples, double alfa)\n{\n\ttypedef matrix<double, 703, 1> sample_type; // 4 = Feature Size, cannot be set to variable !!!!\n\n\tstd::vector<sample_type> feature_dlib;\n\tdouble accuracy = 0;\n\n\tprintf(\"started.. \\n\");\n\tfor (int m = 0; m < noSamples; m++)\n\t{\n\t\tsample_type temp;\n\t\ttemp.set_size(feature_size_);\n\t\t//cout << \"Set size \" << temp.size  << endl;\n\n\t\tfor (int j = 0; j < feature_size_; j++)\n\t\t\ttemp(j, 0) = features_[m][j];\n\n\t\tfeature_dlib.push_back(temp);\n\n\t}\n\n\tclock_t begin = clock();\n\n\ttypedef linear_kernel<sample_type> linear_kernel;\n\n\ttypedef svm_multiclass_linear_trainer <linear_kernel, double> svm_mc_trainer;\n\tsvm_mc_trainer trainer;\n\n\t//multiclass_linear_decision_function<linear_kernel,double> df = trainer.train(feature_dlib, label_); \n\n\n\tmatrix<double, 11, 11>  confusionmatrix;\n\tconfusionmatrix.set_size(11, 11);\n\tconfusionmatrix = cross_validate_multiclass_trainer(trainer, feature_dlib, label_, 5);\n\taccuracy = calculateaccuracy(confusionmatrix);\n\n\tclock_t end = clock();\n\tprintf(\"has completed in %4.1f seconds and accuracy %f\\n\", double(end - begin) / CLOCKS_PER_SEC, accuracy);\n\treturn accuracy;\n\n}\n\n\ndouble dlib_svm_kfold(std::vector<std::vector<double>> features_, std::vector<double> label_, int feature_size_, int noSamples, double alfa)\n{\n\ttypedef matrix<double, 703, 1> sample_type; // 4 = Feature Size, cannot be set to variable !!!!\n\n\tstd::vector<sample_type> feature_dlib;\n\tdouble accuracy = 0;\n\n\tprintf(\"started.. \\n\");\n\tfor (int m = 0; m < noSamples; m++)\n\t{\n\t\tsample_type temp;\n\t\ttemp.set_size(feature_size_);\n\t\t//cout << \"Set size \" << temp.size  << endl;\n\n\t\tfor (int j = 0; j < feature_size_; j++)\n\t\t\ttemp(j, 0) = features_[m][j];\n\n\t\tfeature_dlib.push_back(temp);\n\n\t}\n\n\tclock_t begin = clock();\n\t\n/*\ttypedef linear_kernel<sample_type> linear_kernel; \n\n\ttypedef svm_multiclass_linear_trainer <linear_kernel, double> svm_mc_trainer;\n\tsvm_mc_trainer trainer;\n\t\n\n\tmulticlass_linear_decision_function<linear_kernel,double> df = trainer.train(feature_dlib, label_); */\n\n\ttypedef one_vs_one_trainer<any_trainer<sample_type> > ovo_trainer;\n\n\tovo_trainer trainer;\n\ttypedef linear_kernel<sample_type> linear_kernel;\n\n\tkrr_trainer<linear_kernel> linear_trainer;\n\t\n\tlinear_trainer.set_kernel(linear_kernel());\n\ttrainer.set_trainer(linear_trainer);        // linear_trainer\n\trandomize_samples(feature_dlib, label_);\n   //printf(\"Training start \\n\");\n\t//one_vs_one_decision_function<ovo_trainer> df = trainer.train(feature_dlib, label_);\n\n\tmatrix<double, 11,11>  confusionmatrix;\n\tconfusionmatrix.set_size(11, 11);\n\tconfusionmatrix=cross_validate_multiclass_trainer(trainer, feature_dlib, label_, 5);\n\taccuracy= calculateaccuracy(confusionmatrix);\n\t\n\tclock_t end = clock();\n\tprintf(\"has completed in %4.1f seconds and accuracy %f\\n\", double(end - begin) / CLOCKS_PER_SEC,accuracy);\n\treturn accuracy;\n\n}\ndouble dlib_svm(std::vector<std::vector<double>> features_, std::vector<double> label_, int feature_size_, int noSamples, double alfa)\n{\n\ttypedef matrix<double, 703, 1> sample_type; // 4 = Feature Size, cannot be set to variable !!!!\n\n\tstd::vector<sample_type> feature_dlib;\n\n\tstd::vector<sample_type> feature_train_dlib;\n\tstd::vector<sample_type> feature_test_dlib;\n\n\tstd::vector<double> train_label;\n\tstd::vector<double> test_label;\n\n\t//Filling Vector_Matrix\n\tdouble TotAccuracy = 0;\t//# true positives\n\tdouble accuracy = 0;\n\t\n\tprintf(\"started.. \\n\");\n\tfor (int m = 0; m < noSamples; m++)\n\t{\n\t\tsample_type temp;\n\t\ttemp.set_size(feature_size_);\n\t\t//cout << \"Set size \" << temp.size  << endl;\n\n\t\tfor (int j = 0; j < feature_size_; j++)\n\t\t\ttemp(j, 0) = features_[m][j];\n\t\t\n\t\tfeature_dlib.push_back(temp);\n\t\n\t}\n\n\tclock_t begin = clock();\n\n\t//Leave-One-out\n\tfor (int testid = 0; testid < noSamples; testid++)\n\t{\n\t\t\n\t\tdouble  error = 0;\n\t\taccuracy = 0;\n\t\t//printf(\"Feature dlib %d\", feature_dlib.data()[testid]);\n\t\tfeature_test_dlib.push_back(feature_dlib.data()[testid]);\n\t\ttest_label.push_back(label_.data()[testid]);\n\t\tfeature_train_dlib = feature_dlib;\n\t\tremove(feature_train_dlib, testid);\n\t\ttrain_label = label_;\n\t\tremove(train_label, testid);\n\n\t/*\tfor (int m = 0; m < noSamples; m++)\n\t\t{\n\t\t\t\tsample_type temp;\n\t\t\t\tfor (int j = 0; j < feature_size_; j++)\n\t\t\t\t\ttemp(j, 0) = features_[m][j];\n\t\t\t\tif (m == testid) {\n\t\t\t\t\tfeature_test_dlib.push_back(temp);\n\t\t\t\t\ttest_label.push_back(label_[m]);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tfeature_train_dlib.push_back(temp);\n\t\t\t\t\ttrain_label.push_back(label_[m]);\n\t\t\t\t}\n\t\t\t\n\t\t}*/\n\n\t\n\t\t\n\t\ttypedef one_vs_one_trainer<any_trainer<sample_type> > ovo_trainer;\n\n\t\tovo_trainer trainer;\n\t\t//typedef radial_basis_kernel<sample_type> rbf_kernel;\n\t\ttypedef linear_kernel<sample_type> linear_kernel; \n\t\t//krr_trainer<rbf_kernel> rbf_trainer;\n\n\t\t//svm_nu_trainer <linear_kernel> linear_trainer;\n\n\n\t\tkrr_trainer<linear_kernel> linear_trainer;\n\t\t//svm_multiclass_linear_trainer <rbf_kernel> rbf_trainer;\n\t\tint prediction, test_gt;\n\t\t\n\n\t\t//rbf_trainer.set_kernel(rbf_kernel(alfa));\n\t\tlinear_trainer.set_kernel(linear_kernel());\n\t\t//trainer.set_trainer(rbf_trainer);        // rbf_trainer\n\t\t trainer.set_trainer(linear_trainer);        // linear_trainer\n\t\t trainer.set_num_threads(7);\n\t\t//randomize_samples(feature_train_dlib, train_label);\n\t\t//printf(\"Training start \\n\");\n\t\tone_vs_one_decision_function<ovo_trainer> df = trainer.train(feature_train_dlib, train_label);\n\n\t\n\t\t//std::cout << \"Testing started\" << endl;\n\t\tprediction = df(feature_test_dlib[0]);\n\t\ttest_gt = test_label[0];\n\t\n\t\tif (prediction != test_gt) error=1;\n\n\t\taccuracy = 1 - (error);\n\t\t//std::cout << \"Local accuracy: \" << accuracy << endl;\n\n\t\tfeature_test_dlib.clear();\n\t\tfeature_train_dlib.clear();\n\t\ttest_label.clear();\n\t\ttrain_label.clear();\n\n\t\t\n\t\tTotAccuracy += accuracy;\n\n\t}\n\tclock_t end = clock();\n\tprintf(\"has completed in %4.1f seconds\\n\", double(end - begin) / CLOCKS_PER_SEC);\n\t\n\t//printf(\"One Leave out accuracy %f\",(TotAccuracy/ noSamples));\n\t/*for (int i = 0; i < train_features_.size()-100; i++)\n\t{\n\t\tsample_type temp;\n\t\tfor (int j = 0; j <feature_size_; j++)\n\t\t\ttemp(j, 0) = train_features_[i][j];\n\t\tfeature_train_dlib.push_back(temp);\n\t\ttrain_label_1.push_back(train_label_[i]);\n\t}\n\n\tfor (int i = test_features_.size()-100; i < test_features_.size(); i++)\n\t{\n\t\tsample_type temp;\n\t\tfor (int j = 0; j <feature_size_; j++)\n\t\t\ttemp(j, 0) = test_features_[i][j];\n\t\tfeature_test_dlib.push_back(temp);\n\t\ttest_label_1.push_back(test_label_[i]);\n\t}*/\n\n\t\n\n\t//cout << \"feature_train_dlib.size: \" << feature_train_dlib.size() << endl;\n\t//cout << \"feature_train_dlib[0].size: \" << feature_train_dlib[0].size() << endl;\n\t//cout << \"\\nfeature_test_dlib.size: \" << feature_test_dlib.size() << endl;\n\t//cout << \"feature_test_dlib[0].size: \" << feature_test_dlib[0].size() << endl;\n\t//cout << \"\\ntrain labels size: \" << train_label_1.size() << endl;\n\t//cout << \"test labels size: \" << test_label_1.size() << endl;\n\n\tfeature_dlib.clear();\n\treturn (TotAccuracy / noSamples);\n\n}\n\n\nint main()\n{\n\tstring resultsFilename = \"Results_svm.txt\";\n\tstring dataFilename = \"Pathogen_VOC_Dataset_v4.txt\";\n\tFILE *outFile = fopen(resultsFilename.c_str(), \"a+\");\t//reset file\n\tfclose(outFile);\n\n\tint noClasses = 12;\n\tint noSamples = 336;\n\tint noFeatures = 703;\n\tstd::vector<string> classLabels;\n\tstd::vector<double> classIDs;\n\tstd::vector<std::vector<double>> data;\n\t//open & read data file\n\tFILE *dataFile = fopen(dataFilename.c_str(), \"r\");\n\n\tint tmpInt1, tmpInt2;\n\tstring tmpStr;\n\tchar* buffer = new char[200];\n\n\tfscanf(dataFile, \"%d\", &noClasses);\t//# of classes\n\tfgets(buffer, 100, dataFile);\t\t//dummy read till read EOL\n\n\n\tclassLabels.push_back(\"\");\t//dummy push to start index from 1 for class labels\n\tfor (int i = 1; i <= noClasses; i++)\n\t{\n\t\tfscanf(dataFile, \"%d  %s\", &tmpInt1, buffer);\n\t\tclassLabels.push_back(string(buffer));\n\t}\n\n\tfscanf(dataFile, \"%d\", &noSamples);\t\t//reads # of classes from the file\n\tfgets(buffer, 100, dataFile);\t\t\t//dummy read till read EOL\n\n\tfscanf(dataFile, \"%d\", &noFeatures);\t//reads the feature dimension from the file\n\tfgets(buffer, 100, dataFile);\t\t\t//dummy read till read EOL\n\n\tfor (int i = 0; i < noSamples; i++)\n\t{\n\t\tfscanf(dataFile, \"%d %d\", &tmpInt1, &tmpInt2);\t//read sample ID (dummy read) & class ID of the current feature vector\n\t\tclassIDs.push_back(tmpInt2);\t//store class ID\n\n\t\tdata.push_back(std::vector<double>());\n\t\tfor (int j = 0; j < noFeatures; j++)\n\t\t{\n\t\t\tfscanf(dataFile, \"%d\", &tmpInt1);\t//read feature vector\n\t\t\tdata[i].push_back(tmpInt1);\n\t\t}\n\t}\n\n\n\tdelete buffer;\n\tdouble alfa = 0.1;  // For SVM, standart range 0-1\n\n\t\n\tstd::vector<int> selFeatIDs;\n\tdouble Allbest = 0.0;\n\n\t//select all features in a circular manner\n\tfor (int j = 0; j < noFeatures; j++) \n\t\tselFeatIDs.push_back(j);\n\n\tfor (int j = noFeatures; j >= 0; j--)\n\t{\n\t\tint eliminated = 0;\n\t\tif (j < noFeatures)\t//no elimination in the first loop\n\t\t{\n\t\t\teliminated = selFeatIDs[j];\n\t\t\tselFeatIDs.erase(selFeatIDs.begin() + j);\t//jth feature is appended\n\t\t\tnoFeatures -= 1;\n\t\t}\n\n\t\tstd::vector<std::vector<double>> filtereddata;\n\t\n\n\t\t\n\t\tfor (int m = 0; m < noSamples; m++)\n\t\t{\n\t\t\tfiltereddata.push_back(std::vector<double>());\n\t\t\tfor (int p = 0; p < selFeatIDs.size(); p++)\n\t\t\t{\n\t\t\t\tfiltereddata[m].push_back(data[m][selFeatIDs[p]]);\n\t\t\t\t\n\t\t\t}\n\t\t\t//printf(\"Filtered Feature size %d \\n\", (filtereddata[m].size()));\n\t\t}\n\t\t// SVM Classifer\n\t\t//printf(\"Feature removal :%d\", j);\n\t\t\n\t\tdouble accuracy = dlib_svm(filtereddata, classIDs, noFeatures, noSamples, alfa);\n\t\t// double accuracy =  dlib_svm_kfold(filtereddata, classIDs, noFeatures, noSamples, alfa);\n\t\t// double accuracy = dlib_svm_multiclass_kfold(filtereddata, classIDs, noFeatures, noSamples, alfa);\n\t\t//double accuracy =  dlib_svm_Multi_Leaveoneout(filtereddata, classIDs, noFeatures, noSamples, alfa);\n\t\t//cout << \"Accuracy:\\n\" << endl << accuracy << endl;\n\t\tif (accuracy < Allbest)\n\t\t{\n\t\t\t//printf(\"Acuracy reduced\");\n\t\t\tselFeatIDs.insert(selFeatIDs.begin() + j, eliminated);\n\t\t\tnoFeatures += 1;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t//printf(\"Acuracy improved or same\");\n\t\t\tAllbest = accuracy;\n\t\t}\n\t\tprintf(\"Accuracy :%5.3f, Overall accuracy :%5.3f and feature removal round: %d\", accuracy,Allbest, (703-j));\n\t\toutFile = fopen(resultsFilename.c_str(), \"a+\");\t//reset file\n\n\t\tfprintf(outFile, \"%d /703 is done ;No. Selected Features: %d \\n\", j , selFeatIDs.size());\n\n\t\tfprintf(outFile, \"#####  Accuracy: %5.3f ##### Best Accuracy: %5.3f #####\\nSelected Feature IDs:\", accuracy, Allbest);\n\n\t\tfor (int j = 0; j < selFeatIDs.size(); j++) fprintf(outFile, \"%d, \", selFeatIDs[j]);\n\n\t\tfprintf(outFile, \"\\n\\n\");\n\n\t\tfclose(outFile);\n\t}\n\t\n\tsystem(\"PAUSE\");\n\treturn 0;\n}\n\n\n\n\n\n\n", "meta": {"hexsha": "11f022d30b267d8ba52d501be8d410fa3e03d497", "size": 13651, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "c++_classificaion_svm_dlib/main.cpp", "max_stars_repo_name": "mukunthan/BackwardFeatureElimination-for-the-Pathogen-Recognition-using-SVM", "max_stars_repo_head_hexsha": "0f87deb8e1d21687d3ae10e59c6bcfb2011422f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "c++_classificaion_svm_dlib/main.cpp", "max_issues_repo_name": "mukunthan/BackwardFeatureElimination-for-the-Pathogen-Recognition-using-SVM", "max_issues_repo_head_hexsha": "0f87deb8e1d21687d3ae10e59c6bcfb2011422f4", "max_issues_repo_licenses": ["MIT"], "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++_classificaion_svm_dlib/main.cpp", "max_forks_repo_name": "mukunthan/BackwardFeatureElimination-for-the-Pathogen-Recognition-using-SVM", "max_forks_repo_head_hexsha": "0f87deb8e1d21687d3ae10e59c6bcfb2011422f4", "max_forks_repo_licenses": ["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.6336032389, "max_line_length": 154, "alphanum_fraction": 0.6872756575, "num_tokens": 4027, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478255, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4805057356393805}}
{"text": "\n#include <ostream>\n\n#include \"gtest/gtest.h\"\n#include <Eigen/Dense>\n\n#include \"libqhull_r/qhull_ra.h\"\n\n#include \"libqhullcpp/RboxPoints.h\"\n#include \"libqhullcpp/QhullError.h\"\n#include \"libqhullcpp/QhullQh.h\"\n#include \"libqhullcpp/QhullFacet.h\"\n#include \"libqhullcpp/QhullFacetList.h\"\n#include \"libqhullcpp/QhullFacetSet.h\"\n#include \"libqhullcpp/QhullLinkedList.h\"\n#include \"libqhullcpp/QhullPoint.h\"\n#include \"libqhullcpp/QhullUser.h\"\n#include \"libqhullcpp/QhullVertex.h\"\n#include \"libqhullcpp/QhullVertexSet.h\"\n#include \"libqhullcpp/Qhull.h\"\n#include \"polytope.hpp\"\n\n\nTEST(TESTQHull, basicTest) {\n    constexpr int dimension = 3;\n\n    // box\n    constexpr int numberOfPoints  = 9;\n    double points[numberOfPoints*dimension]{-1, -1, -1,\n            -1, -1, 1,\n            -1, 1, -1,\n            -1, 1, 1,\n            1, -1, -1,\n            1, -1, 1,\n            1, 1, -1,\n            1, 1, 1,\n            0, 0, 0};\n    orgQhull::Qhull q {\"\", dimension, numberOfPoints, points, \"o\"};\n    orgQhull::QhullFacetList facets= q.facetList();\n    //std::cout << facets << std::endl;\n\n    for (auto &facet : q.facetList())\n    {\n        std::cout << \"Facet> \" << facet;\n        orgQhull::QhullVertexSet vertices = facet.vertices();\n        for (const auto &vertex : vertices)\n      \t{\n            std::cout << \"Vertex> \" << vertex;\n      \t}\n\n        Eigen::Vector3d center(facet.getCenter().coordinates());\n        std::cout << \" center: \" << center << std::endl;\n        Eigen::Vector3d normal(facet.hyperplane().coordinates());\n        std::cout << \" normal: \" << normal << std::endl;\n        orgQhull::QhullVertexSet::iterator it = vertices.begin();\n        Eigen::Vector3d firstVertex((*it).point().coordinates());\n        std::cout << \" firstVertex: \" << firstVertex  << std::endl;\n        firstVertex = (firstVertex - center);\n        firstVertex.normalize();\n        std::cout << \" firstVertex: \" << firstVertex  << std::endl;;\n        std::vector<std::pair<double, orgQhull::QhullVertex> > orderedVertices;\n        orderedVertices.push_back(std::pair<double, orgQhull::QhullVertex> (0.0, (*it)));\n        it++;\n        // first element is the angle.\n\n        for (;it < vertices.end(); it++) {\n            Eigen::Vector3d vertex((*it).point().coordinates());\n            std::cout << \" vertex: \" << vertex << \" id: \" << (*it).id()  << std::endl;\n            vertex = vertex - center;\n            vertex.normalize();\n            std::cout << \" vertex: \" << vertex << std::endl;\n            std::cout << \" cos(angle) \" << firstVertex.dot(vertex) << std::endl;\n            std::cout << \" (angle) \" << acos(firstVertex.dot(vertex)) << std::endl;\n            double angle = acos(firstVertex.dot(vertex));\n            Eigen::Vector3d crossProductFirstAndCurrent = firstVertex.cross(vertex);\n            std::cout << \" cross product \" << crossProductFirstAndCurrent << \" is zero \" << crossProductFirstAndCurrent.isZero() << std::endl;\n            std::cout << \" dot(crossProductFirstAndCurrent, normal) \" << crossProductFirstAndCurrent.dot(normal) << std::endl;\n            if (!crossProductFirstAndCurrent.isZero() && crossProductFirstAndCurrent.dot(normal) < 0)\n            {\n                angle = -angle + 2 * EIGEN_PI;\n            }\n            //std::cout << \" final angle: \" << angle << std::endl;\n            std::pair<double, orgQhull::QhullVertex> pair(angle, (*it));\n            orderedVertices.push_back(std::pair<double, orgQhull::QhullVertex> (angle, (*it)));\n        }\n\n        std::sort( std::begin(orderedVertices), std::end(orderedVertices),\n                   []( const std::pair<double, orgQhull::QhullVertex> &left, const std::pair<double, orgQhull::QhullVertex> &right)\n                   {\n                       return  left.first < right.first;\n                   } );\n        for (auto &v : orderedVertices)\n        {\n            std::cout << \" ordered vertex: \" << v.second;\n        }\n\n        std::cout << \" ALL vertices: \" << std::endl;\n        for (auto v = q.beginVertex(); v != q.endVertex(); v = v.next()){\n            std::cout << \"ID: \" << v.id() << \"->\" << v;\n        }\n\n        std::cout << \"ALL vertices again: \" << q.vertexList() << std::endl;\n        std::cout << \"ALL points: \" << q.points() << std::endl;\n\n    }\n\n    //spdlog::info(\"A basic test\");\n    //spdlog::info(\"sizeof realT {} double {}\", sizeof(realT), sizeof(double));\n    // orgQhull::RboxPoints eg(\"100\");\n    // orgQhull::Qhull q(eg, \"\");\n\n\n    ASSERT_EQ(true, true);\n}\n\nvoid print_summary(qhT *qh) {\n    facetT *facet;\n    vertexT *vertex, **vertexp;\n    int k;\n\n    printf(\"\\n%d vertices and %d facets with normals:\\n\",\n           qh->num_vertices, qh->num_facets);\n    FORALLfacets {\n        printf(\"FACET\\n\");\n        for (k=0; k < qh->hull_dim; k++)\n        {\n            printf(\"%6.2g \", facet->normal[k]);\n\n        }\n        printf(\"\\n\");\n        printf(\"center \"); for (k=0; k < qh->hull_dim; k++) {printf(\"%6.2g\", facet->center[k]);} printf(\"\\n\");\n        printf(\" toporient %i\\n\", facet->toporient);\n        FOREACHvertex_(facet->vertices) {\n            printf(\"vertex \");\n            for (int k=0; k < qh->hull_dim; k++)\n                printf(\"%5.2f \", vertex->point[k]);\n            printf(\"\\n\");\n        }\n    }\n\n\n}\n\n\nTEST(TESTQHull, DISABLED_cTest) {\n    constexpr int dim = 3;\n    constexpr int numpoints = 8;\n    coordT points[numpoints*dim] = {-1, -1, -1,\n                                    -1, -1, 1,\n                                    -1, 1, -1,\n                                    -1, 1, 1,\n                                    1, -1, -1,\n                                    1, -1, 1,\n                                    1, 1, -1,\n                                    1, 1, 1};\n\n    boolT ismalloc= False; /* True if qhull should free points in qh_freeqhull() or reallocation */\n    //char flags[] = \"qhull QJ\";\n    char flags[255];\n    sprintf(flags, \"qhull s Tcv Fx\");\n    FILE *outfile= stdout;\n    FILE *errfile= stderr;\n    int exitcode;\n    facetT *facet;\n    int curlong, totlong;\n\n    qhT qh_qh;\n    qhT *qh= &qh_qh;\n\n    QHULL_LIB_CHECK\n    \n        qh_zero(qh, errfile);\n\n    exitcode= qh_new_qhull(qh, dim, numpoints, points, ismalloc,\n                           flags, outfile, errfile);\n    fflush(NULL);\n\n    if (!exitcode) {                  /* if no error */\n        print_summary(qh);\n        facetT *facet;\n        vertexT *vertex, **vertexp;\n        FORALLfacets {\n            /* ... your code ... */\n            FOREACHvertex_(facet->vertices) {\n                // for (int k=0; k < dim; k++)\n                //       printf(\"%5.2f \", vertex->point[k]);\n            }\n        }\n    }\n\n    qh_freeqhull(qh, !qh_ALL);                   /* free long memory  */\n    qh_memfreeshort(qh, &curlong, &totlong);    /* free short memory and memory allocator */\n    if (curlong || totlong)\n        fprintf(errfile, \"qhull internal warning (user_eg, #1): did not free %d bytes of long memory (%d pieces)\\n\", totlong, curlong);\n}\n\n\nTEST(TESTQHull, qhullPrism) {\n    constexpr int dimension = 3;\n\n    // box\n    constexpr int numberOfPoints  = 6;\n    double points[numberOfPoints*dimension]{\n                     0, 0, 1,\n                         0, 1, 1,\n                         0.866025, 0, -0.5,\n                         0.866025, 1, -0.5,\n                         -0.866025, 0, -0.5,\n                         -0.866025, 1, -0.5};\n    orgQhull::Qhull q {\"\", dimension, numberOfPoints, points, \"o\"};\n\n\n    std::cout << \" ALL facets: \" << std::endl;\n    orgQhull::QhullFacetList facets= q.facetList();\n    std::cout << facets << std::endl;\n\n    std::cout << \" ALL vertices: \" << std::endl;\n    for (auto v = q.beginVertex(); v != q.endVertex(); v = v.next()){\n        std::cout << \"ID: \" << v.id() << \"->\" << v;\n    }\n\n}\n\n\nTEST(TESTQHull, rbox)\n{\n    orgQhull::RboxPoints rbox {\"10 s D3\"}; /// 10 points in a 3d sphere\n\n    auto itbegin = rbox.beginCoordinates();\n    auto itend = rbox.endCoordinates();\n\n    int count = 0;\n    for (auto it = rbox.beginCoordinates(); it != rbox.endCoordinates(); ++it)\n    {\n        std::cout << \"coordinate: \" << (*it) << std::endl;\n        count++;\n    }\n    std::cout << \"number coordinates: \" << count;\n\n    orgQhull::Qhull q {rbox, \"o\"};\n\n    std::vector<OB::Point> points;\n    for (auto it = rbox.beginCoordinates(); it != rbox.endCoordinates(); ++it) {\n        OB::Real x = static_cast<OB::Real>(*(it++));\n        OB::Real y = static_cast<OB::Real>(*(it++));\n        OB::Real z = static_cast<OB::Real>(*(it));\n\n        points.push_back(OB::Point(x, y, z));\n\n    }\n\n    for (auto& p : points) {\n        std::cout << \" Points \" << p.transpose() << std::endl;\n    }\n\n    int numberOfPoints = points.size();\n    std::vector<realT> pointCoordinates(numberOfPoints * 3);\n\n    for (size_t i = 0; i < points.size(); i++)\n    {\n        const OB::Point& p = points[i];\n        pointCoordinates[i*3+0] = static_cast<realT>(p(0));\n        pointCoordinates[i*3+1] = static_cast<realT>(p(1));\n        pointCoordinates[i*3+2] = static_cast<realT>(p(2));\n    }\n    orgQhull::Qhull q2 {\"\", 3, numberOfPoints, pointCoordinates.data(), \"o\"};\n\n\n    // std::cout << \" ALL facets: \" << std::endl;\n    // orgQhull::QhullFacetList facets= q.facetList();\n    // std::cout << facets << std::endl;\n\n    // std::cout << \" ALL vertices: \" << std::endl;\n    // for (auto v = q.beginVertex(); v != q.endVertex(); v = v.next()){\n    //     std::cout << \"ID: \" << v.id() << \"->\" << v;\n    // }\n}\n", "meta": {"hexsha": "f559722abb25590d8a3e71848e85e84151ec2b51", "size": 9433, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "obvclip/tests/test_qhull.cpp", "max_stars_repo_name": "javierdelapuente/tfm_ode_bullet", "max_stars_repo_head_hexsha": "cc0d40b9a91e43b5045c10903b5244e680d909ef", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-08T11:22:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-08T11:22:13.000Z", "max_issues_repo_path": "obvclip/tests/test_qhull.cpp", "max_issues_repo_name": "javierdelapuente/tfm_ode_bullet", "max_issues_repo_head_hexsha": "cc0d40b9a91e43b5045c10903b5244e680d909ef", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "obvclip/tests/test_qhull.cpp", "max_forks_repo_name": "javierdelapuente/tfm_ode_bullet", "max_forks_repo_head_hexsha": "cc0d40b9a91e43b5045c10903b5244e680d909ef", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.9316546763, "max_line_length": 142, "alphanum_fraction": 0.5233753843, "num_tokens": 2718, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435083355187, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4804411939910201}}
{"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/numpy.h>\n#include <pybind11/stl.h>\n\n#include <Eigen/Core>\n#include <boost/geometry.hpp>\n#include <iostream>\n#include <optional>\n\n#include \"pyinterp/axis.hpp\"\n#include \"pyinterp/detail/broadcast.hpp\"\n#include \"pyinterp/detail/isviewstream.hpp\"\n#include \"pyinterp/detail/math/binning.hpp\"\n#include \"pyinterp/detail/math/streaming_histogram.hpp\"\n#include \"pyinterp/eigen.hpp\"\n\nnamespace pyinterp {\n\n/// Group a number of more or less continuous values into a smaller number of\n/// \"bins\" located on a grid.\ntemplate <typename T>\nclass Histogram2D {\n public:\n  /// Statistics handled by this object.\n  using StreamingHistogram = detail::math::StreamingHistogram<T>;\n\n  /// Default constructor\n  ///\n  /// @param x Definition of the bin centers for the X axis of the grid.\n  /// @param y Definition of the bin centers for the Y axis of the grid.\n  Histogram2D(std::shared_ptr<Axis<double>> x, std::shared_ptr<Axis<double>> y,\n              const std::optional<size_t>& bin_count)\n      : x_(std::move(x)), y_(std::move(y)), histogram_(x_->size(), y_->size()) {\n    if (bin_count) {\n      for (int ix = 0; ix < histogram_.rows(); ++ix) {\n        for (int jx = 0; jx < histogram_.cols(); ++jx) {\n          histogram_(ix, jx).resize(*bin_count);\n        }\n      }\n    }\n  }\n\n  /// Default destructor\n  virtual ~Histogram2D() = default;\n\n  /// Copy constructor\n  ///\n  /// @param rhs right value\n  Histogram2D(const Histogram2D& rhs) = delete;\n\n  /// Move constructor\n  ///\n  /// @param rhs right value\n  Histogram2D(Histogram2D&& rhs) noexcept = delete;\n\n  /// Copy assignment operator\n  ///\n  /// @param rhs right value\n  auto operator=(const Histogram2D& rhs) -> Histogram2D& = delete;\n\n  /// Move assignment operator\n  ///\n  /// @param rhs right value\n  auto operator=(Histogram2D&& rhs) noexcept -> Histogram2D& = delete;\n\n  /// Inserts new values in the grid from Z values for X, Y data\n  /// coordinates.\n  void push(const pybind11::array_t<T>& x, const pybind11::array_t<T>& y,\n            const pybind11::array_t<T>& z) {\n    detail::check_array_ndim(\"x\", 1, x, \"y\", 1, y, \"z\", 1, z);\n    detail::check_ndarray_shape(\"x\", x, \"y\", y, \"z\", z);\n\n    auto _x = x.template unchecked<1>();\n    auto _y = y.template unchecked<1>();\n    auto _z = z.template unchecked<1>();\n\n    {\n      pybind11::gil_scoped_release release;\n\n      const auto& x_axis = static_cast<pyinterp::detail::Axis<double>&>(*x_);\n      const auto& y_axis = static_cast<pyinterp::detail::Axis<double>&>(*y_);\n\n      for (pybind11::ssize_t idx = 0; idx < x.size(); ++idx) {\n        auto value = _z(idx);\n\n        if (!std::isnan(value)) {\n          auto ix = x_axis.find_index(_x(idx), true);\n          auto iy = y_axis.find_index(_y(idx), true);\n\n          if (ix != -1 && iy != -1) {\n            histogram_(ix, iy)(value);\n          }\n        }\n      }\n    }\n  }\n\n  /// Reset the statistics.\n  void clear() {\n    for (Eigen::Index ix = 0; ix < histogram_.rows(); ++ix) {\n      for (Eigen::Index jx = 0; jx < histogram_.cols(); ++jx) {\n        histogram_(ix, jx).clear();\n      }\n    }\n  }\n\n  /// Compute the count of points within each bin.\n  [[nodiscard]] auto count() const -> pybind11::array_t<uint64_t> {\n    return calculate_statistics<decltype(&StreamingHistogram::count),\n                                uint64_t>(&StreamingHistogram::count);\n  }\n\n  /// Compute the minimum of values for points within each bin.\n  [[nodiscard]] auto min() const -> pybind11::array_t<T> {\n    return calculate_statistics(&StreamingHistogram::min);\n  }\n\n  /// Compute the maximum of values for points within each bin.\n  [[nodiscard]] auto max() const -> pybind11::array_t<T> {\n    return calculate_statistics(&StreamingHistogram::max);\n  }\n\n  /// Compute the mean of values for points within each bin.\n  [[nodiscard]] auto mean() const -> pybind11::array_t<T> {\n    return calculate_statistics(&StreamingHistogram::mean);\n  }\n\n  /// Compute the variance of values for points within each bin.\n  [[nodiscard]] auto variance() const -> pybind11::array_t<T> {\n    return calculate_statistics(&StreamingHistogram::variance);\n  }\n\n  /// Compute the kurtosis of values for points within each bin.\n  [[nodiscard]] auto kurtosis() const -> pybind11::array_t<T> {\n    return calculate_statistics(&StreamingHistogram::kurtosis);\n  }\n\n  /// Compute the quantile of values for points within each bin.\n  [[nodiscard]] auto quantile(const T& q) const -> pybind11::array_t<T> {\n    return calculate_statistics(&StreamingHistogram::quantile, q);\n  }\n\n  /// Compute the skewness of values for points within each bin.\n  [[nodiscard]] auto skewness() const -> pybind11::array_t<T> {\n    return calculate_statistics(&StreamingHistogram::skewness);\n  }\n  /// Compute the sum of weights within each bin.\n  [[nodiscard]] auto sum_of_weights() const -> pybind11::array_t<T> {\n    return calculate_statistics(&StreamingHistogram::sum_of_weights);\n  }\n\n  /// Gets the X-Axis\n  [[nodiscard]] inline auto x() const -> std::shared_ptr<Axis<double>> {\n    return x_;\n  }\n\n  /// Gets the Y-Axis\n  [[nodiscard]] inline auto y() const -> std::shared_ptr<Axis<double>> {\n    return y_;\n  }\n\n  /// Pickle support: get state of this instance\n  [[nodiscard]] auto getstate() const -> pybind11::tuple {\n    return pybind11::make_tuple(x_->getstate(), y_->getstate(), marshal());\n  }\n\n  /// Pickle support: set state of this instance\n  static auto setstate(const pybind11::tuple& state)\n      -> std::unique_ptr<Histogram2D<T>> {\n    if (state.size() != 3) {\n      throw std::invalid_argument(\"invalid state\");\n    }\n\n    // Unmarshalling X-Axis\n    auto x = std::make_shared<Axis<double>>();\n    *x = Axis<double>::setstate(state[0].cast<pybind11::tuple>());\n\n    // Unmarshalling Y-Axis\n    auto y = std::make_shared<Axis<double>>();\n    *y = Axis<double>::setstate(state[1].cast<pybind11::tuple>());\n\n    // Unmarshalling instance\n    auto result = std::make_unique<Histogram2D<T>>(x, y, 40);\n    auto marshal_data = state[2].cast<pybind11::bytes>();\n    Histogram2D::unmarshal(marshal_data.cast<std::string_view>(),\n                           result->histogram_);\n    return result;\n  }\n\n  /// Aggregation of statistics\n  auto operator+=(const Histogram2D& other) -> Histogram2D& {\n    if (*x_ != *(other.x_) || *y_ != *(other.y_)) {\n      throw std::invalid_argument(\"Unable to combine different grids\");\n    }\n    for (Eigen::Index ix = 0; ix < histogram_.rows(); ++ix) {\n      for (Eigen::Index iy = 0; iy < histogram_.cols(); ++iy) {\n        auto& lhs = histogram_(ix, iy);\n        auto& rhs = other.histogram_(ix, iy);\n\n        // Statistics are defined only in the other instance.\n        if (lhs.size() == 0 && rhs.size() != 0) {\n          lhs = rhs;\n          // If the statistics are defined in both instances they can be\n          // combined.\n        } else if (lhs.size() != 0 && rhs.size() != 0) {\n          lhs += rhs;\n        }\n      }\n    }\n    return *this;\n  }\n\n  /// Returns the histogram for each bin.\n  auto histograms() const -> pybind11::array_t<detail::math::Bin<T>> {\n    auto bins_count = size_t(0);\n    for (Eigen::Index ix = 0; ix < histogram_.rows(); ++ix) {\n      for (Eigen::Index iy = 0; iy < histogram_.cols(); ++iy) {\n        bins_count = std::max(\n            bins_count, histogram_(ix, iy).size());\n      }\n    }\n    auto result =\n        pybind11::array_t<detail::math::Bin<T>>(pybind11::array::ShapeContainer(\n            {x_->size(), y_->size(),\n             static_cast<pybind11::ssize_t>(bins_count)}));\n    auto _result = result.template mutable_unchecked<3>();\n    {\n      auto gil = pybind11::gil_scoped_release();\n\n      for (Eigen::Index ix = 0; ix < histogram_.rows(); ++ix) {\n        for (Eigen::Index iy = 0; iy < histogram_.cols(); ++iy) {\n          auto iz = size_t(0);\n          auto& bins = histogram_(ix, iy).bins();\n          for (iz = 0; iz < bins.size(); ++iz) {\n            _result(ix, iy, iz) = bins[iz];\n          }\n          for (; iz < bins_count; ++iz) {\n            _result(ix, iy, iz) =\n                detail::math::Bin<T>{std::numeric_limits<T>::quiet_NaN(), T(0)};\n          }\n        }\n      }\n    }\n    return result;\n  }\n\n private:\n  /// Grid axis\n  std::shared_ptr<Axis<double>> x_;\n  std::shared_ptr<Axis<double>> y_;\n\n  /// Statistics grid\n  Matrix<StreamingHistogram> histogram_;\n\n  /// Calculation of a given statistical variable.\n  template <typename Func, typename Type = T, typename... Args>\n  [[nodiscard]] auto calculate_statistics(const Func& func, Args... args) const\n      -> pybind11::array_t<Type> {\n    pybind11::array_t<Type> z({x_->size(), y_->size()});\n    auto _z = z.template mutable_unchecked<2>();\n    {\n      pybind11::gil_scoped_release release;\n\n      for (Eigen::Index ix = 0; ix < histogram_.rows(); ++ix) {\n        for (Eigen::Index iy = 0; iy < histogram_.cols(); ++iy) {\n          _z(ix, iy) = (histogram_(ix, iy).*func)(args...);\n        }\n      }\n    }\n    return z;\n  }\n\n  [[nodiscard]] auto marshal() const -> pybind11::bytes {\n    auto gil = pybind11::gil_scoped_release();\n    auto ss = std::stringstream();\n    ss.exceptions(std::stringstream::failbit);\n    auto rows = histogram_.rows();\n    ss.write(reinterpret_cast<const char*>(&rows), sizeof(rows));\n    auto cols = histogram_.cols();\n    ss.write(reinterpret_cast<const char*>(&cols), sizeof(cols));\n    for (int ix = 0; ix < histogram_.rows(); ++ix) {\n      for (int jx = 0; jx < histogram_.cols(); ++jx) {\n        auto marshal_hist = static_cast<std::string>(histogram_(ix, jx));\n        auto size = marshal_hist.size();\n        ss.write(reinterpret_cast<const char*>(&size), sizeof(size));\n        ss.write(marshal_hist.c_str(), size);\n      }\n    }\n    return ss.str();\n  }\n\n  static auto unmarshal(const std::string_view& data,\n                        Matrix<StreamingHistogram>& histogram) -> void {\n    auto gil = pybind11::gil_scoped_release();\n    auto ss = detail::isviewstream(data);\n    ss.exceptions(std::stringstream::failbit);\n\n    try {\n      auto rows = Eigen::Index(0);\n      auto cols = Eigen::Index(0);\n      ss.read(reinterpret_cast<char*>(&rows), sizeof(rows));\n      ss.read(reinterpret_cast<char*>(&cols), sizeof(cols));\n      if (rows != histogram.rows() || cols != histogram.cols()) {\n        throw std::invalid_argument(\"invalid state\");\n      }\n      for (int ix = 0; ix < rows; ++ix) {\n        for (int jx = 0; jx < cols; ++jx) {\n          auto size = size_t(0);\n          ss.read(reinterpret_cast<char*>(&size), sizeof(size));\n          auto marshal_hist = std::string(size, '\\0');\n          ss.read(marshal_hist.data(), size);\n          histogram(ix, jx) = std::move(StreamingHistogram(marshal_hist));\n        }\n      }\n    } catch (std::ios_base::failure&) {\n      throw std::invalid_argument(\"invalid state\");\n    }\n  }\n};\n\n}  // namespace pyinterp\n", "meta": {"hexsha": "75f73e589510f39ae8d64390d21b109e09156c4f", "size": 10952, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/pyinterp/core/include/pyinterp/histogram2d.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/histogram2d.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/histogram2d.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.5950920245, "max_line_length": 80, "alphanum_fraction": 0.6114864865, "num_tokens": 2880, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.48044118745741055}}
{"text": "/* \n\n    HUANG Jing\n    haungjing@mae.cuhk.edu.hk\n    Track contour in an image.\n*/\n\n#include <ros/ros.h>\n#include <image_transport/image_transport.h>\n#include <cv_bridge/cv_bridge.h>\n#include <sensor_msgs/image_encodings.h>\n#include <opencv2/imgproc/imgproc.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/photo.hpp>    // denoising module\n#include <iostream>\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n#include <vector>\n#include <math.h>\n\nnamespace enc = sensor_msgs::image_encodings;\n\nstatic const char WINDOW[] = \"New OpenCV Image\";\n\nclass ImageConverter\n{\n    ros::NodeHandle nh_;\n    image_transport::ImageTransport it_;\n    image_transport::Subscriber image_sub_;\n    image_transport::Publisher image_pub_;\n    float focal_x = 683;\n    float focal_y = 683;\n    float depth = 58;\n  \npublic:\n    ImageConverter(char* ros_image_stream): it_(nh_)\n    {\n        // image_pub_ = it_.advertise(\"correll_ros2opencv\", 1);\n        image_sub_ = it_.subscribe(ros_image_stream, 1, &ImageConverter::imageCb, this);\n\n        cv::namedWindow(WINDOW);\n    }\n\n    ~ImageConverter()\n    {\n        cv::destroyWindow(WINDOW);\n    }\n\n    void imageCb(const sensor_msgs::ImageConstPtr& msg)\n    {\n      cv_bridge::CvImagePtr cv_ptr;\n      try\n      {\n        cv_ptr = cv_bridge::toCvCopy(msg, enc::BGR8);\n      }\n      catch (cv_bridge::Exception& e)\n      {\n        ROS_ERROR(\"cv_bridge exception: %s\", e.what());\n        return;\n      }\n\n   // Find countors of red shape\n    cv::Point imageOrigin(320, 240),\n              xAxisEnd(220, 240), yAxisEnd(320, 340);\n    cv::Scalar redLow(0, 173, 152), redHigh(10, 255, 255), black_low(0, 0, 0), black_high(149, 218, 71);\n    std::vector< std::vector<cv::Point>> contours;\n    cv::Mat trackedImage, trackedImage_denoised, dst, trackedImage_undist;\n    cv::Mat cameraMatrix = (cv::Mat_<double>(3, 3) << 683.9731, 0, 320., 0, 683.9731, 240, 0, 0, 1);\n    cv::Mat distCoef = (cv::Mat_<double>(1, 5) << -0.7175, 2.8528, 0, 0, -5.1548);\n    \n    cv::cvtColor(cv_ptr->image, trackedImage, CV_BGR2HSV);\n    // cv::fastNlMeansDenoisingColored(trackedImage,trackedImage_denoised, 3, 3, 7, 21); // This function costs much time.\n    cv::blur(trackedImage, trackedImage, cv::Size(3, 3));   // blurring is very important to get rid of noise.\n    cv::inRange(trackedImage, black_low, black_high, dst);\n    cv::imshow(\"Binary Image\", dst);\n\n    /* Use bgr difference to generate binary image rather than inRange()\n    cv::Mat bgr_thr = cv::Mat::zeros(trackedImage.size(), CV_8UC1);\n    int Rows = bgr_thr.rows, Cols = bgr_thr.cols;\n    for (int r = 0; r < Rows; r ++)\n        for (int c = 0; c < Cols; c++)\n        {\n            cv::Vec3b intensity = cv_ptr->image.at<cv::Vec3b>(cv::Point(c, r));\n            if (intensity[2] - intensity[0] > 100 && intensity[2] - intensity[1] > 100)\n            {\n                bgr_thr.at<uchar>(cv::Point(c, r)) = 255;\n            }\n        }\n    */\n   \n    cv::Moments m_dst = moments(dst, true);\n    cv::Point p(m_dst.m10 / m_dst.m00, m_dst.m01 / m_dst.m00);\n\n    if (p.x < 0 || p.y < 0)\n    {\n      std::cout << \"No feature shape detected.\" << std::endl;\n    }\n    else\n    {\n      // cv::findContours(bgr_thr, contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE, cv::Point(0, 0));\n      cv::findContours(dst, contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE, cv::Point(0, 0));\n      int largestContourIndex = 0;\n      for (int i = 0; i < contours.size(); i++)\n        largestContourIndex = (contours[i].size() > contours[largestContourIndex].size()) ? i : largestContourIndex;\n      cv::Moments shapeMoments = moments(contours[largestContourIndex]);\n      cv::Point2f shapeCenter(static_cast<float>(shapeMoments.m10 / shapeMoments.m00),\n                              static_cast<float>(shapeMoments.m01 / shapeMoments.m00));\n      Eigen::Matrix2f I;        // inertia tensor\n      I <<  shapeMoments.mu20, shapeMoments.mu11,\n            shapeMoments.mu11, shapeMoments.mu02;\n      Eigen::EigenSolver<Eigen::Matrix2f> es(I);\n      Eigen::Vector2d eigenVector1(es.eigenvectors().col(0).real()[0], es.eigenvectors().col(0).real()[1]),\n                      eigenVector2(es.eigenvectors().col(1).real()[0], es.eigenvectors().col(1).real()[1]);\n\n      // ***The procedure is to get rid of the possible random switch of the principal axis display.\n      // ***There is a need of look at the characters of the retrun eigenvectors first to know how to\n      // ***better set the processing.\n      if (eigenVector1[0] < 0 )\n      {\n        Eigen::Vector2d tempVector = eigenVector1;\n        eigenVector1 = eigenVector2;\n      } \n      eigenVector2 = Eigen::Vector2d(eigenVector1[1], -eigenVector1[0]);\n      /* float angleX1 = atan2(eigenVector1[1], eigenVector1[0]),\n            angleX2 = atan2(eigenVector2[1], eigenVector2[0]);\n      if (angleX1 > angleX2)\n      {\n        Eigen::Vector2d tempVector = eigenVector1;\n        eigenVector1 = eigenVector2;\n        eigenVector2 = tempVector;\n      } */\n      // std::cout << es.eigenvectors().col(0).real()[0] << \"*****\" << std::endl;\n     \n      cv::RotatedRect rectShape = cv::minAreaRect(contours[largestContourIndex]);\n      cv::Point2f rectShapeVertices[4];\n      rectShape.points(rectShapeVertices);    // order of vertices: bottomLeft, topLeft, topRight, bottomRight. And the bottom\n                                              // is the most bottom.\n      //std::vector<std::vector<cv::Point2f>> rectShapeContour;\n      //rectShapeContour[0].assign(rectShapeVertices, rectShapeVertices + 4);  // this cause segmentation fault (core dumped)\n      // cv::drawContours(cv_ptr->image, rectShapeContour, 0, cv::Scalar(0, 255, 0), 2);\n      cv::Point2f rotateOrigin;\n      if (rectShapeVertices[2].x > rectShapeVertices[0].x)\n      {\n        rotateOrigin.x = (rectShapeVertices[0].x + rectShapeVertices[1].x) / 2;\n        rotateOrigin.y = (rectShapeVertices[0].y + rectShapeVertices[1].y) / 2;\n      }\n      else\n      {\n        rotateOrigin.x = (rectShapeVertices[1].x + rectShapeVertices[2].x) / 2; \n        rotateOrigin.y = (rectShapeVertices[1].y + rectShapeVertices[2].y) / 2;      \n      }\n      for (int i = 0; i < 4; i++)\n      {\n        cv::line(cv_ptr->image, rectShapeVertices[i], rectShapeVertices[(i+1) % 4], cv::Scalar(0, 255, 0), 2);\n      }\n      cv::circle(cv_ptr->image, rotateOrigin, 10, cv::Scalar(0, 0, 255), -1);\n\n      cv::Point2f principleAxie1 = shapeCenter + 80 * cv::Point2f( eigenVector1[0], eigenVector1[1]),\n                  principleAxie2 = shapeCenter + 80 * cv::Point2f( eigenVector2[0], eigenVector2[1]);      \n      cv::arrowedLine(cv_ptr->image, shapeCenter, principleAxie1, cv::Scalar(0, 0, 255), 2);\n      cv::arrowedLine(cv_ptr->image, shapeCenter, principleAxie2, cv::Scalar(0, 255, 0), 2);\n      cv::circle(cv_ptr->image, shapeCenter, 5, cv::Scalar(0, 0, 0), -1);\n      cv::drawContours(cv_ptr->image, contours, largestContourIndex, cv::Scalar(255, 0, 0), 2);\n    }\n\n    cv::circle(cv_ptr->image, imageOrigin, 5, cv::Scalar(0, 0, 0), -1);\n    cv::arrowedLine(cv_ptr->image, imageOrigin, xAxisEnd, cv::Scalar(0, 0, 255), 2);\n    cv::putText(cv_ptr->image, \"x\", xAxisEnd - cv::Point(10, 10), CV_FONT_HERSHEY_PLAIN, 2, cv::Scalar(0, 0, 255), 2);\n    cv::arrowedLine(cv_ptr->image, imageOrigin, yAxisEnd, cv::Scalar(0, 255, 0), 2);\n    cv::putText(cv_ptr->image, \"y\", yAxisEnd + cv::Point(10, 10), CV_FONT_HERSHEY_PLAIN, 2, cv::Scalar(0, 255, 0), 2);\n   // end of processing\n    cv::imshow(WINDOW, cv_ptr->image);\n    cv::waitKey(3);\n    \n    image_pub_.publish(cv_ptr->toImageMsg());   \n    }\n  \n};\n\nint main(int argc, char** argv)\n{\n  if (argc == 2) \n  {\n    ros::init(argc, argv, \"image_processing\");\n    ImageConverter ic(argv[1]);\n    ros::spin();\n    return 0;\n  } \n  else if (argc == 1)\n  {\n  // set default ros image source\uff0c HUANG Jing\n    char *image_topic = (char*) \"/cameras/source_camera/image\";\n    ros::init(argc, argv, \"image_processing\");\n    ImageConverter ic(image_topic);\n    ros::spin();\n    return 1;\n  }\n  else\n  {\n    std::cout << \"ERROR:\\tusage - RosToOpencvImage <ros_image_topic>\" << std::endl; \n    return 1;    \n  }\n}\n", "meta": {"hexsha": "c0813f37c13753598e69adca17e9b1114b246e3c", "size": 8115, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/contour_tracker.cpp", "max_stars_repo_name": "HuangJingGitHub/PracMakePert_C", "max_stars_repo_head_hexsha": "94e570c55d9e391913ccd9c5c72026ab926809b2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-10-17T03:13:29.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-17T03:13:29.000Z", "max_issues_repo_path": "src/contour_tracker.cpp", "max_issues_repo_name": "HuangJingGitHub/PracMakePert_C-Cpp", "max_issues_repo_head_hexsha": "6ed39e757ad8ba7bdd75fffdaf28d17a294a11e5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/contour_tracker.cpp", "max_forks_repo_name": "HuangJingGitHub/PracMakePert_C-Cpp", "max_forks_repo_head_hexsha": "6ed39e757ad8ba7bdd75fffdaf28d17a294a11e5", "max_forks_repo_licenses": ["Apache-2.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.7794117647, "max_line_length": 126, "alphanum_fraction": 0.6213185459, "num_tokens": 2502, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.48044118745741055}}
{"text": "#ifndef __DYNAUTODIFF_DISTRIBUTIONS__\n#define __DYNAUTODIFF_DISTRIBUTIONS__\n#include \"Common.hpp\"\n#include \"Var.hpp\"\n#include \"boost/math/special_functions/gamma.hpp\"\n#include <boost/math/special_functions/math_fwd.hpp>\n#include <numbers>\n\n#define UNWRAP(...) __VA_ARGS__\n\nnamespace DynAutoDiff {\nnamespace bm = boost::math;\n#define DISTFUNCTIONTEMPLATE(functionname, structname, functionargs, funinput, assertstmt,         \\\n                             requires_grad_stmt)                                                   \\\n    template <Reduction R = Sum, typename T = double>                                              \\\n    std::shared_ptr<Var<T>> functionname(std::shared_ptr<Var<T>> X functionargs) {                 \\\n        assertstmt std::vector<std::shared_ptr<Var<T>>> input_nodes{funinput};                     \\\n        if constexpr (R == Reduction::None) {                                                      \\\n            return std::make_shared<Var<T>>(X->rows(), 1, requires_grad_stmt, input_nodes,         \\\n                                            std::make_unique<structname##EvalGrad<T>>(R));         \\\n        } else {                                                                                   \\\n            return std::make_shared<Var<T>>(1, 1, requires_grad_stmt, input_nodes,                 \\\n                                            std::make_unique<structname##EvalGrad<T>>(R));         \\\n        }                                                                                          \\\n    };\n\ntemplate <typename T = double> struct LnMVNormalDenEvalGrad : EvalGradFunctionBase<T> {\n    TMat<T> iS;\n    TMat<T> Xmu;\n    int N, d;\n    int R;\n    LnMVNormalDenEvalGrad(int R) : R(R){};\n    double Sd; // Sigma determinant\n    std::string get_name() const override { return \"LnMVNormalDenEvalGrad\"; };\n    boost::json::object to_json() const override {\n        boost::json::object res;\n        res[\"name\"] = \"ln_mvnormal_den\";\n        res[\"Reduction\"] = R;\n        return res;\n    };\n    void eval(TMap<T> &dest, const std::vector<TMap<T>> &inputs) override {\n        N = inputs[0].rows();\n        d = inputs[0].cols();\n        iS = inputs[2].inverse();\n        Sd = inputs[2].determinant();\n\n        Xmu.resize(N, d);\n        TMat<T> res(N, 1);\n\n        for (int i = 0; i < N; ++i) {\n            Xmu.row(i) = (inputs[0].row(i).transpose() - inputs[1]).transpose();\n            res.coeffRef(i, 0) = -Xmu.row(i) * iS * Xmu.row(i).transpose();\n        };\n\n        if (R == Reduction::None) {\n            dest = 0.5 * (res.array() - std::log(Sd) - d * log(2 * std::numbers::pi));\n        } else {\n            dest.coeffRef(0, 0) =\n                0.5 * (res.sum() - N * std::log(Sd) - N * d * log(2 * std::numbers::pi));\n\n            if (R == Reduction::Mean) {\n                dest = dest.array() / N;\n            }\n        }\n    };\n    std::vector<TMat<T>> grad(const std::shared_ptr<Var<T>> &current) override {\n        const auto &X = current->input_node(0)->val();\n        const auto &mu = current->input_node(1)->val();\n        const auto &Sigma = current->input_node(2)->val();\n\n        std::vector<TMat<T>> res;\n\n        // X\n        if (current->input_node(0)->requires_grad()) {\n            TMat<T> Xg(N, d);\n            if (R == Reduction::None) {\n                for (int i = 0; i < N; ++i) {\n                    Xg.row(i) =\n                        -(iS * Xmu.row(i).transpose()).transpose() * current->grad().coeff(i, 0);\n                }\n            } else {\n                Xg = -(iS * Xmu.transpose()).transpose() * current->grad().coeff(0, 0);\n            }\n            // std::cout << Xg << std::endl;\n            if (R == Reduction::Mean) {\n                Xg = Xg / N;\n            }\n            res.emplace_back(Xg);\n        } else {\n            res.emplace_back(TMat<T>());\n        };\n        // mu\n        if (current->input_node(1)->requires_grad()) {\n            TMat<T> mug(d, 1);\n            // mu's gradient is negation of X's.\n            if (current->input_node(0)->requires_grad()) {\n                mug = -res[0].colwise().sum().transpose();\n            } else {\n                if (R == Reduction::None) {\n                    TMat<T> Xg(N, d);\n                    for (int i = 0; i < N; ++i) {\n                        Xg.row(i) =\n                            (iS * Xmu.row(i).transpose()).transpose() * current->grad().coeff(i, 0);\n                    }\n                    mug = Xg.colwise().sum().transpose();\n                } else {\n                    mug = (iS * Xmu.transpose()).rowwise().sum() * current->g();\n                }\n            }\n            if (R == Reduction::Mean) {\n                mug = mug / N;\n            }\n            res.emplace_back(mug);\n\n        } else {\n            res.emplace_back(TMat<T>());\n        }\n        // Sigma\n        if (current->input_node(2)->requires_grad()) {\n            TMat<T> Sg(d, d);\n\n            if (R == Reduction::None) {\n                Sg.setZero();\n                for (int i = 0; i < N; ++i) {\n                    Sg = Sg + iS.transpose() * Xmu.row(i).transpose() * Xmu.row(i) *\n                                  iS.transpose() * current->grad().coeff(i, 0);\n                }\n                Sg = Sg - iS.transpose() * current->grad().sum();\n            } else {\n                Sg = iS.transpose() * Xmu.transpose() * Xmu * iS.transpose() *\n                     current->grad().coeff(0, 0);\n                Sg = Sg - iS.transpose() * N;\n            }\n\n            Sg = Sg * 0.5;\n\n            if (R == Reduction::Mean) {\n                Sg = Sg / N;\n            }\n            res.emplace_back(Sg);\n        } else {\n            res.emplace_back(TMat<T>());\n        }\n\n        return res;\n    }\n};\n\ntemplate <typename T = double> struct LnNormalDenEvalGrad : EvalGradFunctionBase<T> {\n    TMat<T> Xmu, Xmu2;\n    int N;\n    int R;\n    LnNormalDenEvalGrad(int R) : R(R){};\n    std::string get_name() const override { return \"LnNormalDenEvalGrad\"; };\n    boost::json::object to_json() const override {\n        boost::json::object res;\n        res[\"name\"] = \"ln_normal_den\";\n        res[\"Reduction\"] = R;\n        return res;\n    };\n    void eval(TMap<T> &dest, const std::vector<TMap<T>> &inputs) override {\n        N = inputs[0].rows();\n        T mu = inputs[1].coeff(0, 0);\n        T sigma = inputs[2].coeff(0, 0);\n        const auto &X = inputs[0];\n\n        TMat<T> res(N, 1);\n        Xmu = X.array() - mu;\n        Xmu2 = Xmu.array().pow(2);\n\n        if (R == Reduction::None) {\n            dest = -0.5 * std::log(2 * std::numbers::pi) - std::log(sigma) -\n                   0.5 * Xmu2.array() / (sigma * sigma);\n        } else {\n            dest.coeffRef(0, 0) = -0.5 * N * std::log(2 * std::numbers::pi) - N * std::log(sigma) -\n                                  0.5 * Xmu2.sum() / (sigma * sigma);\n            if (R == Reduction::Mean) {\n                dest = dest.array() / N;\n            }\n        }\n    };\n    std::vector<TMat<T>> grad(const std::shared_ptr<Var<T>> &current) override {\n        const auto &X = current->input_node(0)->val();\n        T mu = current->input_node(1)->val().coeff(0, 0);\n        T sigma = current->input_node(2)->val().coeff(0, 0);\n\n        std::vector<TMat<T>> res;\n\n        // X\n        if (current->input_node(0)->requires_grad()) {\n            TMat<T> Xg(N, 1);\n            if (R == Reduction::None) {\n                Xg = -Xmu.array() / (sigma * sigma) * current->grad().array();\n            } else {\n                Xg = -Xmu.array() / (sigma * sigma) * current->grad().coeff(0, 0);\n\n                if (R == Reduction::Mean) {\n                    Xg = Xg / N;\n                }\n            }\n            // std::cout << Xg << std::endl;\n            res.emplace_back(Xg);\n        } else {\n            res.emplace_back(TMat<T>());\n        };\n        // mu\n        if (current->input_node(1)->requires_grad()) {\n            TMat<T> mug(1, 1);\n            // mu's gradient is negation of X's.\n            if (current->input_node(0)->requires_grad()) {\n                mug.coeffRef(0, 0) = -res[0].sum();\n            } else {\n                if (R == Reduction::None) {\n                    mug.coeffRef(0, 0) = (Xmu.array() * current->grad().array()).sum() / (sigma * sigma);\n                } else {\n                    mug.coeffRef(0, 0) = Xmu.sum() / (sigma * sigma) * current->grad().coeff(0, 0);\n                    if (R == Reduction::Mean) {\n                        mug = mug / N;\n                    }\n                }\n            }\n            res.emplace_back(mug);\n        } else {\n            res.emplace_back(TMat<T>());\n        }\n        // Sigma\n        if (current->input_node(2)->requires_grad()) {\n            TMat<T> sg(1, 1);\n\n            if (R == Reduction::None) {\n                sg.coeffRef(0, 0) =\n                    ((-1.0 / sigma + Xmu2.array() / (std::pow(sigma, 3))) * current->grad().array()).sum();\n            } else {\n                sg.coeffRef(0, 0) = (-N / sigma + Xmu2.sum() / (std::pow(sigma, 3))) *\n                                    current->grad().coeff(0, 0);\n                if (R == Reduction::Mean) {\n                    sg = sg / N;\n                }\n            }\n            res.emplace_back(sg);\n        } else {\n            res.emplace_back(TMat<T>());\n        }\n\n        return res;\n    }\n};\n\ntemplate <typename T = double> struct LnTDenEvalGrad : EvalGradFunctionBase<T> {\n    TMat<T> Xmu;\n    int N;\n    int R;\n    TMat<T> xm, xm2, fx, lfx;\n    LnTDenEvalGrad(int R) : R(R){};\n    std::string get_name() const override { return \"LnTDenEvalGrad\"; };\n    boost::json::object to_json() const override {\n        boost::json::object res;\n        res[\"name\"] = \"ln_t_den\";\n        res[\"Reduction\"] = R;\n        return res;\n    };\n    void eval(TMap<T> &dest, const std::vector<TMap<T>> &inputs) override {\n        N = inputs[0].rows();\n        fx.resize(N, 1);\n        xm.resize(N, 1);\n        xm2.resize(N, 1);\n        lfx.resize(N, 1);\n        T mu = inputs[1].coeff(0, 0);\n        T sigma = inputs[2].coeff(0, 0);\n        T nu = inputs[3].coeff(0, 0);\n        const auto &X = inputs[0];\n\n        xm = X.array() - mu;\n        xm2 = xm.array().pow(2);\n        fx = xm2.array() / (sigma * sigma) / nu + 1;\n        lfx = fx.array().log();\n\n        if (R == Reduction::None) {\n            dest = bm::lgamma(nu / 2 + 0.5) - bm::lgamma(nu / 2) -\n                   0.5 * std::log(nu * std::numbers::pi) - std::log(sigma) -\n                   (nu + 1) / 2 * lfx.array();\n        } else {\n            dest.coeffRef(0, 0) = N * (bm::lgamma(nu / 2 + 0.5) - bm::lgamma(nu / 2) -\n                                       0.5 * std::log(nu * std::numbers::pi) - std::log(sigma)) -\n                                  (nu + 1) / 2 * lfx.array().sum();\n            if (R == Reduction::Mean) {\n                dest = dest.array() / N;\n            }\n        }\n    };\n    std::vector<TMat<T>> grad(const std::shared_ptr<Var<T>> &current) override {\n        const auto &X = current->input_node(0)->val();\n        T mu = current->input_node(1)->val().coeff(0, 0);\n        T sigma = current->input_node(2)->val().coeff(0, 0);\n        T nu = current->input_node(3)->val().coeff(0, 0);\n\n        std::vector<TMat<T>> res;\n\n        // X\n        if (current->input_node(0)->requires_grad()) {\n            TMat<T> Xg(N, 1);\n            if (R == Reduction::None) {\n                Xg = -(1 + 1.0 / nu) / (sigma * sigma) * xm.array() / fx.array() *\n                     current->grad().array();\n            } else {\n                Xg = -(1 + 1.0 / nu) / (sigma * sigma) * (xm.array() / fx.array()) *\n                     current->grad().coeff(0, 0);\n\n                if (R == Reduction::Mean) {\n                    Xg = Xg / N;\n                }\n            }\n            // std::cout << Xg << std::endl;\n            res.emplace_back(Xg);\n        } else {\n            res.emplace_back(TMat<T>());\n        };\n        // mu\n        if (current->input_node(1)->requires_grad()) {\n            TMat<T> mug(1, 1);\n            // mu's gradient is negation of X's.\n            if (current->input_node(0)->requires_grad()) {\n                mug.coeffRef(0, 0) = -res[0].sum();\n            } else {\n                if (R == Reduction::None) {\n                    mug.coeffRef(0, 0) = (1 + 1.0 / nu) / (sigma * sigma) *\n                                         (xm.array() / fx.array() * current->grad().array()).sum();\n                } else {\n                    mug.coeffRef(0, 0) = (1 + 1.0 / nu) / (sigma * sigma) *\n                                         (xm.array() / fx.array()).sum() *\n                                         current->grad().coeff(0, 0);\n                    if (R == Reduction::Mean) {\n                        mug = mug / N;\n                    }\n                }\n            }\n            res.emplace_back(mug);\n        } else {\n            res.emplace_back(TMat<T>());\n        }\n        // sigma\n        if (current->input_node(2)->requires_grad()) {\n            TMat<T> sg(1, 1);\n\n            if (R == Reduction::None) {\n                sg.coeffRef(0, 0) = ((-1.0 / sigma + (1 + 1.0 / nu) / (sigma * sigma * sigma) *\n                                                         xm2.array() / fx.array()) *\n                                     current->grad().array())\n                                        .sum();\n            } else {\n                sg.coeffRef(0, 0) = (-N / sigma + (1 + 1.0 / nu) / (sigma * sigma * sigma) *\n                                                      (xm2.array() / fx.array()).sum()) *\n                                    current->grad().coeff(0, 0);\n                if (R == Reduction::Mean) {\n                    sg = sg / N;\n                }\n            }\n            res.emplace_back(sg);\n        } else {\n            res.emplace_back(TMat<T>());\n        }\n        // nu\n        if (current->input_node(3)->requires_grad()) {\n            TMat<T> nug(1, 1);\n\n            if (R == Reduction::None) {\n                nug.coeffRef(0, 0) =\n                    0.5 * ((bm::digamma((nu + 1) / 2) - bm::digamma(nu / 2) - 1.0 / nu -\n                            (lfx.array() -\n                             (nu + 1) / (nu * nu) / (sigma * sigma) * xm2.array() / fx.array())) *\n                           current->grad().array())\n                              .sum();\n            } else {\n                nug.coeffRef(0, 0) =\n                    0.5 *\n                    (N * (bm::digamma((nu + 1) / 2) - bm::digamma(nu / 2) - 1.0 / nu) -\n                     (lfx.array() -\n                      (nu + 1) / (nu * nu) / (sigma * sigma) * xm2.array() / fx.array())\n                         .sum()) *\n                    current->grad().coeff(0, 0);\n                if (R == Reduction::Mean) {\n                    nug = nug / N;\n                }\n            }\n            res.emplace_back(nug);\n        } else {\n            res.emplace_back(TMat<T>());\n        }\n        return res;\n    }\n};\n\nDISTFUNCTIONTEMPLATE(\n    ln_mvnormal_den, LnMVNormalDen,\n    UNWRAP(, std::shared_ptr<Var<T>> mu, std::shared_ptr<Var<T>> Sigma), UNWRAP(X, mu, Sigma),\n    UNWRAP(assert(((mu->cols() == 1) && (Sigma->rows() == Sigma->cols())) &&\n                  \"mu should be a column vector. Sigma should be a square matrix.\");),\n    X->requires_grad() || mu->requires_grad() || Sigma->requires_grad())\nDISTFUNCTIONTEMPLATE(\n    ln_normal_den, LnNormalDen, UNWRAP(, std::shared_ptr<Var<T>> mu, std::shared_ptr<Var<T>> sigma),\n    UNWRAP(X, mu, sigma),\n    UNWRAP(assert(((X->cols() == 1) && (mu->size() == 1) && (sigma->size() == 1)) &&\n                  \"X must be a column vector. mu and sigma must be a scalar.\");),\n    X->requires_grad() || mu->requires_grad() || sigma->requires_grad())\nDISTFUNCTIONTEMPLATE(\n    ln_t_den, LnTDen,\n    UNWRAP(, std::shared_ptr<Var<T>> mu, std::shared_ptr<Var<T>> sigma, std::shared_ptr<Var<T>> nu),\n    UNWRAP(X, mu, sigma, nu),\n    UNWRAP(assert(((X->cols() == 1) && (mu->size() == 1) && (sigma->size() == 1) &&\n                   (nu->size() == 1)) &&\n                  \"X must be a column vector. mu, sigma and nu must be scalars.\");),\n    X->requires_grad() || mu->requires_grad() || sigma->requires_grad() || nu->requires_grad())\n#undef DISTFUNCTIONTEMPLATE\n#undef UNWRAP\n};     // namespace DynAutoDiff\n#endif // !", "meta": {"hexsha": "c3b945e1ad2985cbfa41aed0c05cdadf39dc7027", "size": 16277, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "DynAutoDiff/Distributions.hpp", "max_stars_repo_name": "kilasuelika/DynAutoDiff", "max_stars_repo_head_hexsha": "1da36182e93f4893201389c5841941500586e3ea", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-26T06:13:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-26T06:13:56.000Z", "max_issues_repo_path": "DynAutoDiff/Distributions.hpp", "max_issues_repo_name": "kilasuelika/DynAutoDiff", "max_issues_repo_head_hexsha": "1da36182e93f4893201389c5841941500586e3ea", "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": "DynAutoDiff/Distributions.hpp", "max_forks_repo_name": "kilasuelika/DynAutoDiff", "max_forks_repo_head_hexsha": "1da36182e93f4893201389c5841941500586e3ea", "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": 39.1274038462, "max_line_length": 107, "alphanum_fraction": 0.424218222, "num_tokens": 4313, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390746, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.4804411874574104}}
{"text": "/*!\n * @file\n * Defines the @ref Integer datatype.\n *\n *\n * @copyright Louis Dionne 2014\n * Distributed under the Boost Software License, Version 1.0.\n *         (See accompanying file LICENSE.md or copy at\n *             http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#ifndef BOOST_MPL11_INTEGER_HPP\n#define BOOST_MPL11_INTEGER_HPP\n\n#include <boost/mpl11/fwd/integer.hpp>\n\n#include <boost/mpl11/bitwise.hpp>\n#include <boost/mpl11/comparable.hpp>\n#include <boost/mpl11/detail/logical_or/strict.hpp>\n#include <boost/mpl11/enumerable.hpp>\n#include <boost/mpl11/group.hpp>\n#include <boost/mpl11/integral_domain.hpp>\n#include <boost/mpl11/logical.hpp>\n#include <boost/mpl11/monoid.hpp>\n#include <boost/mpl11/orderable.hpp>\n#include <boost/mpl11/ring.hpp>\n\n\nnamespace boost { namespace mpl11 {\n    namespace integral_detail {\n        template <typename ...T>\n        struct or_impl : true_ { };\n\n        template <typename ...T>\n        struct or_impl<integer_c<T, false>...> : false_ { };\n\n        template <typename ...T>\n        struct and_impl : false_ { };\n\n        template <typename ...T>\n        struct and_impl<integer_c<T, true>...> : true_ { };\n    } // end namespace integral_detail\n\n    template <typename T, T ...v>\n    struct or_<integer_c<T, v>...>\n        : detail::logical_or::strict<bool_<(bool)v>...>\n    { };\n\n    template <typename T, T ...v>\n    struct and_<integer_c<T, v>...> // DeMorgan\n        : bool_<!detail::logical_or::strict<bool_<!v>...>::value>\n    { };\n\n\n    template <>\n    struct Monoid<Integer> : instantiate<Monoid>::with<Integer> {\n        template <typename x, typename y>\n        using plus_impl = integer_c<\n            decltype(x::value + y::value),\n            x::value + y::value\n        >;\n\n        template <typename ...>\n        using zero_impl = int_<0>;\n    };\n\n    template <>\n    struct Group<Integer> : instantiate<Group>::with<Integer> {\n        template <typename x, typename y>\n        using minus_impl = integer_c<\n            decltype(x::value - y::value),\n            x::value - y::value\n        >;\n\n        template <typename x>\n        using negate_impl = integer_c<\n            decltype(-x::value),\n            -x::value\n        >;\n    };\n\n    template <>\n    struct Ring<Integer> : instantiate<Ring>::with<Integer> {\n        template <typename x, typename y>\n        using mult_impl = integer_c<\n            decltype(x::value * y::value),\n            x::value * y::value\n        >;\n\n        template <typename ...>\n        using one_impl = int_<1>;\n    };\n\n    template <>\n    struct IntegralDomain<Integer>\n        : instantiate<IntegralDomain>::with<Integer>\n    {\n        template <typename x, typename y>\n        using div_impl = integer_c<\n            decltype(x::value / y::value),\n            x::value / y::value\n        >;\n\n        template <typename x, typename y>\n        using mod_impl = integer_c<\n            decltype(x::value % y::value),\n            x::value % y::value\n        >;\n    };\n\n    template <>\n    struct Enumerable<Integer> : instantiate<Enumerable>::with<Integer> {\n        template <typename x>\n        using succ_impl = integer_c<\n            decltype(x::value + 1),\n            x::value + 1\n        >;\n\n        template <typename x>\n        using pred_impl = integer_c<\n            decltype(x::value - 1),\n            x::value - 1\n        >;\n    };\n\n    template <>\n    struct Comparable<Integer> : instantiate<Comparable>::with<Integer> {\n        template <typename x, typename y>\n        using equal_impl = bool_<x::value == y::value>;\n\n        template <typename x, typename y>\n        using not_equal_impl = bool_<x::value != y::value>;\n    };\n\n    template <>\n    struct Orderable<Integer> : instantiate<Orderable>::with<Integer> {\n        template <typename x, typename y>\n        using less_impl = bool_<(x::value < y::value)>;\n\n        template <typename x, typename y>\n        using less_equal_impl = bool_<(x::value <= y::value)>;\n\n        template <typename x, typename y>\n        using greater_impl = bool_<(x::value > y::value)>;\n\n        template <typename x, typename y>\n        using greater_equal_impl = bool_<(x::value >= y::value)>;\n\n        template <typename x, typename y>\n        using max_impl = if_c<(x::value < y::value), y, x>;\n\n        template <typename x, typename y>\n        using min_impl = if_c<(x::value < y::value), x, y>;\n    };\n\n    template <>\n    struct Bitwise<Integer> : instantiate<Bitwise>::with<Integer> {\n        template <typename x, typename y>\n        using bitand_impl = integer_c<\n            decltype(x::value & y::value),\n            x::value & y::value\n        >;\n\n        template <typename x, typename y>\n        using bitor_impl = integer_c<\n            decltype(x::value | y::value),\n            x::value | y::value\n        >;\n\n        template <typename x, typename y>\n        using bitxor_impl = integer_c<\n            decltype(x::value ^ y::value),\n            x::value ^ y::value\n        >;\n\n        template <typename x, typename n>\n        using shift_left_impl = integer_c<\n            decltype(x::value << n::value),\n            (x::value << n::value)\n        >;\n\n        template <typename x, typename n>\n        using shift_right_impl = integer_c<\n            decltype(x::value >> n::value),\n            (x::value >> n::value)\n        >;\n\n        template <typename x>\n        using compl_impl = integer_c<\n            decltype(~x::value),\n            ~x::value\n        >;\n    };\n}} // end namespace boost::mpl11\n\n#endif // !BOOST_MPL11_INTEGER_HPP\n", "meta": {"hexsha": "609b0963737660990a6a6924627b32bfff125a05", "size": 5502, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/mpl11/integer.hpp", "max_stars_repo_name": "rbock/mpl11", "max_stars_repo_head_hexsha": "7923ad2bdc0d8ddaa6a6254ebf5be2b5c6f5a277", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-11-06T09:54:32.000Z", "max_stars_repo_stars_event_max_datetime": "2016-11-06T09:54:32.000Z", "max_issues_repo_path": "include/boost/mpl11/integer.hpp", "max_issues_repo_name": "rbock/mpl11", "max_issues_repo_head_hexsha": "7923ad2bdc0d8ddaa6a6254ebf5be2b5c6f5a277", "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/mpl11/integer.hpp", "max_forks_repo_name": "rbock/mpl11", "max_forks_repo_head_hexsha": "7923ad2bdc0d8ddaa6a6254ebf5be2b5c6f5a277", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.9289340102, "max_line_length": 73, "alphanum_fraction": 0.5648854962, "num_tokens": 1340, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397348, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.48037616528949245}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n\nnamespace polyfem {\nnamespace autogen {\nvoid p_nodes_2d(const int p, Eigen::MatrixXd &val);\n\nvoid p_basis_value_2d(const int p, const int local_index, const Eigen::MatrixXd &uv, Eigen::MatrixXd &val);\n\nvoid p_grad_basis_value_2d(const int p, const int local_index, const Eigen::MatrixXd &uv, Eigen::MatrixXd &val);\n\n\nvoid p_nodes_3d(const int p, Eigen::MatrixXd &val);\n\nvoid p_basis_value_3d(const int p, const int local_index, const Eigen::MatrixXd &uv, Eigen::MatrixXd &val);\n\nvoid p_grad_basis_value_3d(const int p, const int local_index, const Eigen::MatrixXd &uv, Eigen::MatrixXd &val);\n\n\n\nstatic const int MAX_P_BASES = 4;\n\n}}\n", "meta": {"hexsha": "b4aa5cd267f0c66afe98e8484fae718c36e865fe", "size": 671, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/autogen/auto_p_bases.hpp", "max_stars_repo_name": "ldXiao/polyfem", "max_stars_repo_head_hexsha": "d4103af16979ff67d461a9ebe46a14bbc4dc8c7c", "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/autogen/auto_p_bases.hpp", "max_issues_repo_name": "ldXiao/polyfem", "max_issues_repo_head_hexsha": "d4103af16979ff67d461a9ebe46a14bbc4dc8c7c", "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/autogen/auto_p_bases.hpp", "max_forks_repo_name": "ldXiao/polyfem", "max_forks_repo_head_hexsha": "d4103af16979ff67d461a9ebe46a14bbc4dc8c7c", "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": 26.84, "max_line_length": 112, "alphanum_fraction": 0.7585692996, "num_tokens": 180, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.48037615929182054}}
{"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_EXPX2_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_EXPX2_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n    @ingroup group-exponential\n    This function object returns the exponential of the square of its\n    argument or its inverse: \\f$e^{x^2}\\f$ or \\f$e^{-x^2}\\f$.\n    The sign chosen is -1 if and only if the sign bit of the second argument is not zero.\n\n\n    @par Header <boost/simd/function/expx2.hpp>\n\n    @par Note:\n    provisions are made for obtaining more accurate results for large @c x.\n    The second argument @c s defaults to 1.\n\n    @see exp\n\n\n    @par Example:\n\n      @snippet expx2.cpp expx2\n\n    @par Possible output:\n\n      @snippet expx2.txt expx2\n\n  **/\n   IEEEValue expx2(IEEEValue const& x, IEEEValue const& s = 1);\n\n} }\n#endif\n\n#include <boost/simd/function/scalar/expx2.hpp>\n#include <boost/simd/function/simd/expx2.hpp>\n\n#endif\n", "meta": {"hexsha": "e2466c42dd19328599e50c69c3e0db95e7578ecd", "size": 1307, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/expx2.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/expx2.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/expx2.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": 25.1346153846, "max_line_length": 100, "alphanum_fraction": 0.596786534, "num_tokens": 308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.48037615929182054}}
{"text": "#include \"core/protocol-LR.hpp\"\n#include \"core/coda_wrapper.hpp\"\n#include \"core/literal.hpp\"\n#include \"core/global.hpp\"\n#include \"core/file_util.hpp\"\n#include \"core/PPE/PPE.hpp\"\n\n#include <NTL/vec_ZZ.h>\n#include <NTL/matrix.h>\n#include <list>\n#include <fstream>\n#include <sstream>\n#include <core/coda.hpp>\n\ntypedef NTL::mat_ZZ Matrix;\ntypedef NTL::vec_ZZ Vector;\ntemplate<typename T>\nstatic std::pair<double, double> _mean_std(const NTL::Mat<T> &mat, const long colNum);\nclass LRProtocol::Imp {\npublic:\n    Imp() {}\n    ~Imp() {}\n\n    bool encrypt(const std::string &inputFilePath,\n                 const std::string &outputDirPath,\n                 bool /*local_compute*/,\n                 ppe::pk_ptr pk,\n                 ppe::context_ptr context) {\n        std::ifstream in(inputFilePath, std::ios::binary);\n        if (!in.is_open()) {\n            L_WARN(global::_console, \"Can not open {0}\", inputFilePath);\n            return false;\n        }\n\n        std::string outputFile = util::concatenate(outputDirPath, \"FILE_1\");\n        std::ofstream out(outputFile, std::ios::binary);\n        if (!out.is_open()) {\n            L_WARN(global::_console, \"Can not create {0}\", outputFile);\n            in.close();\n            return false;\n        }\n\n        std::vector<long> magnifications = parseHeader(in);\n        if (magnifications.empty()) {\n            L_WARN(global::_console, \"Invalid header of {0}\", inputFilePath);\n            in.close();\n            return false;\n        }\n\n        Matrix X;\n        Vector y;\n        bool ok = readData(&X, &y, in, magnifications.size());\n        if (!ok) {\n            L_WARN(global::_console, \"Some went wrong when to read file {0}\", inputFilePath);\n            return false;\n        }\n\n        auto mag_for_X = magnifications;\n        mag_for_X.pop_back();\n        Matrix scaledX;\n        scale(&scaledX, X, mag_for_X);\n\n        Matrix XtX; // X.T * X\n        NTL::mul(XtX, NTL::transpose(scaledX), scaledX);\n        ppe::EncMat encMat(*pk);\n        encMat.pack(XtX);\n        ok = encMat.dump(out);\n\n        Vector Xty; // X.T * y\n        NTL::mul(Xty, NTL::transpose(scaledX), y);\n        ppe::EncVec encVec(*pk);\n        encVec.pack(Xty);\n        ok &= encVec.dump(out);\n\n        if (ok)\n            createDoneFileForEncrypt(outputDirPath, magnifications);\n        in.close();\n        out.close();\n        return ok;\n    }\n\n    bool decrypt(const std::string &inputFilePath,\n                 const std::string &outputDirPath,\n                 ppe::pk_ptr pk,\n                 ppe::sk_ptr sk,\n                 ppe::context_ptr context) {\n        std::ifstream in(inputFilePath, std::ios::binary);\n        if (!in.is_open()) {\n            L_WARN(global::_console, \"Can not open {0}.\", inputFilePath);\n            return false;\n        }\n\n        std::string outputFilePath = util::concatenate(outputDirPath, core::core_setting.decrypted_file);\n        std::ofstream out(outputFilePath, std::ios::binary);\n        if (!out.is_open()) {\n            L_WARN(global::_console, \"Can not open {0}.\", outputFilePath);\n            return false;\n        }\n\n        ppe::EncVec vec(*pk);\n        vec.restore(in);\n\n        Vector pVec;\n        vec.unpack(pVec, *sk, /*negate=*/true);\n        out << pVec << std::endl;\n        FILE *done = util::createDoneFile(outputDirPath);\n        fclose(done);\n        in.close();\n        out.close();\n        return true;\n    }\n\n    // sum the client ciphertext and apply Powermethod to calculate the largest eigvalue.\n    bool evaluate(const StringList &inputDirs,\n                  const std::string &outputDir,\n                  const StringList &params,\n                  ppe::pk_ptr pk,\n                  ppe::context_ptr context) {\n        if (params.empty()) {\n            L_WARN(global::_console, \"Need the largest eigvalue to evaluate.\");\n            return false;\n        }\n\n        std::string saveTo = util::concatenate(outputDir, core::core_setting.evaluated_file);\n        std::ofstream out(saveTo, std::ios::binary);\n        if (!out.is_open()) {\n            L_WARN(global::_console, \"Can not open {0}.\", saveTo);\n            return false;\n        }\n\n        ppe::EncMat XtX(*pk);\n        ppe::EncVec Xty(*pk);\n        const std::string specificFile = \"FILE_1\";\n        for (const std::string &clientDir : inputDirs) {\n            auto files = util::listDir(clientDir, util::flag_t::FILE_ONLY);\n            for (const auto &file : files) {\n                if (file.compare(specificFile) != 0) continue;\n                auto ctxt_file = util::concatenate(clientDir, file);\n                std::ifstream in(ctxt_file, std::ios::binary);\n                if (!in.is_open()) {\n                    L_WARN(global::_console, \"Can not open {0}\", ctxt_file);\n                    continue;\n                }\n\n                ppe::EncMat tmpMat(*pk);\n                ppe::EncVec tmpVec(*pk);\n                bool ok = tmpMat.restore(in);\n                if (!ok) L_WARN(global::_console, \"Can not load matrix from {0}\", ctxt_file);\n                XtX.add(tmpMat);\n\n                ok = tmpVec.restore(in);\n                if (!ok) L_WARN(global::_console, \"Can not load vector from {0}\", ctxt_file);\n                Xty.add(tmpVec);\n                in.close();\n            }\n        }\n\n        long lambda = literal::stol(params.front(), NULL, 10);\n\n        ppe::EncMat inv(*pk);\n        if (!inverse(&inv, XtX, NTL::to_ZZ(lambda))) {\n            L_WARN(global::_console, \"Some went wrong when to inverse the matrix\");\n            return false;\n        }\n        ppe::EncVec w = inv.sym_dot(Xty);\n        w.dump(out);\n        out.close();\n        FILE *fd = util::createDoneFile(outputDir);\n        fclose(fd);\n        return true;\n    }\n\nprivate:\n    std::vector<long> parseIntegers(const std::string &line) {\n        std::vector<long> ret;\n        auto fileds = util::splitBySpace(line);\n        for (const std::string &field : fileds) {\n            size_t pos;\n            long val = literal::stol(field, &pos,10);\n            if (pos != field.size())\n                return std::vector<long>();\n            else\n                ret.push_back(val);\n        }\n        return ret;\n    }\n\n    std::vector<long> parseHeader(std::ifstream &in) {\n        if (in.eof())\n            return std::vector<long>();\n\n        std::string line;\n        std::getline(in, line);\n        if (line.find(\"#\") != 0)\n            return std::vector<long>();\n\n        return parseIntegers(line.substr(1));\n    }\n\n    bool readData(Matrix *X, Vector *y, std::ifstream &in, const long num_features) {\n        assert(num_features > 1 && \"Need more than 1 dimension for regression\");\n        std::list<std::vector<long>> rows;\n        std::vector<long> last_column;\n        for (std::string line; std::getline(in, line); ) {\n            std::vector<long> row = parseIntegers(line);\n            if (row.size() != num_features) {\n                L_WARN(global::_console, \"Invalid line {0}: requires {1} features\", line, num_features);\n                return false;\n            }\n            last_column.push_back(row.back());\n            row.pop_back();\n            rows.push_back(row);\n        }\n\n        X->SetDims(rows.size(), num_features - 1);\n        y->SetLength(rows.size());\n        long row_index = 0;\n        for (const auto &row : rows) {\n            for (size_t j = 0; j < row.size(); j++)\n                (*X)[row_index][j] = row[j];\n            (*y)[row_index] = last_column[row_index];\n            row_index += 1;\n        }\n        return true;\n    }\n\n    void scale(Matrix *out, const Matrix &mat, const std::vector<long> &mags) {\n        const long DIGIT_PERSERVE = NTL::power_long(10, 3);\n        std::vector<long> factors;\n        for (long c = 0; c < mat.NumCols(); c++) {\n            factors.push_back(NTL::power_long(10, mags[c]));\n        }\n\n        NTL::Mat<double> dMat;\n        dMat.SetDims(mat.NumRows(), mat.NumCols());\n        for (long r = 0; r < mat.NumRows(); r++) {\n            for (long c = 0; c < mat.NumCols(); c++) {\n                dMat[r][c] = NTL::to_double(mat[r][c]) / factors[c];\n            }\n        }\n\n        std::vector<std::pair<double, double>> mean_stds;\n        for (long c = 0; c < mat.NumCols(); c++) {\n            mean_stds.push_back(_mean_std(dMat, c));\n        }\n        out->SetDims(mat.NumRows(), mat.NumCols());\n        for (long r = 0; r < mat.NumRows(); r++) {\n            for (long c = 0; c < mat.NumCols(); c++) {\n                double normalized = DIGIT_PERSERVE * (dMat[r][c] - mean_stds[c].first) / mean_stds[c].second;\n                (*out)[r][c] = NTL::to_ZZ(static_cast<long>(normalized));\n            }\n        }\n    }\n\n    bool inverse(ppe::EncMat *R, const ppe::EncMat &Q, NTL::ZZ alpha) const {\n        ppe::EncMat A(Q);\n        (*R) = Q.copyAsEmpty();\n        Matrix I;\n        I.SetDims(Q.rowNums(), Q.colNums());\n        for (long r = 0; r < I.NumRows(); r++) I[r][r] = 2;\n\n        for (long T = 0; T < 2; T++) {\n            Matrix Alpha = I * alpha;\n            auto inner(A);\n            inner.negate();\n            inner.add(Alpha); // inner^(t) = 2 * alpha * I - A^(t)\n\n            if (T > 0) {\n                R->dot(inner);\n            } else {\n                (*R) = inner;\n            }\n            A.dot(inner);\n            alpha *= alpha;\n        }\n\n        return true;\n    }\n\n    void createDoneFileForEncrypt(const std::string outDir, const std::vector<long> &mags) const {\n        FILE *fd = util::createDoneFile(outDir);\n        if (!fd)\n            return;\n        std::stringstream sstream(\"#\");\n        for (size_t i = 0; i + 1 < mags.size(); i++)\n            sstream << mags[i] << \" \";\n        if (!mags.empty())\n            sstream << mags.back();\n        std::string header = sstream.str();\n        fwrite(header.c_str(), header.size(), 1UL, fd);\n        fclose(fd);\n    }\n};\n\nLRProtocol::LRProtocol() : Protocol(\"PCA\") {\n    imp_ = std::make_shared<LRProtocol::Imp>();\n}\n\nbool LRProtocol::encrypt(const std::string &inputFilePath,\n                         const std::string &outputDirPath,\n                         bool local_compute,\n                         const core::PubKeyWrapper &pk,\n                         const core::ContextWrapper &context)\n{\n    if (!imp_) return false;\n    return imp_->encrypt(inputFilePath, outputDirPath,\n                         local_compute, pk.ppe, context.ppe);\n}\n\nbool LRProtocol::decrypt(const std::string &inputFilePath,\n                         const std::string &outputDirPath,\n                         const core::PubKeyWrapper &pk,\n                         const core::SecKeyWrapper &sk,\n                         const core::ContextWrapper &context)\n{\n    if (!imp_) return false;\n    return imp_->decrypt(inputFilePath, outputDirPath,\n                         pk.ppe, sk.ppe, context.ppe);\n}\n\nbool LRProtocol::evaluate(const StringList &inputDirs,\n                          const std::string &outputDir,\n                          const StringList &params,\n                          const core::PubKeyWrapper &pk,\n                          const core::ContextWrapper &context)\n{\n\n    if (!imp_) return false;\n    return imp_->evaluate(inputDirs, outputDir, params, pk.ppe, context.ppe);\n}\n\ncore::FHEArg LRProtocol::parameters() const {\n    assert(0 && \"Should not use this function\");\n}\n\nbool LRProtocol::genKeypair() const {\n    std::string dirPath = util::getDirPath(metaPath_);\n    std::ofstream skStream(util::concatenate(dirPath, \"fhe_key.sk\"), std::ios::binary);\n    std::ofstream ctxtStream(util::concatenate(dirPath, \"fhe_key.ctxt\"), std::ios::binary);\n    std::ofstream pkStream(util::concatenate(dirPath, \"fhe_key.pk\"), std::ios::binary);\n    if (!skStream.is_open() || !ctxtStream.is_open() || !pkStream.is_open()) {\n        L_WARN(global::_console, \"Can not create files under {0}\", dirPath);\n        return false;\n    }\n\n    /// NOTE:\n    /// hard-coding with the ppe pararmeters. Should be better to chose by clients.\n    const std::vector<long> Ms = {16384};\n    const std::vector<long> Ps = { 4139};\n    const std::vector<long> Rs = {    3};\n    const long L = 10;\n\n    // const std::vector<long> Ms = {27893, 27893, 27893, 27893, 27893, 27893, 27893, 27893};\n    // const std::vector<long> Ps = { 4139,  7321,  5381,  5783,  4231,  4937,  5279, 6679};\n    // const std::vector<long> Rs = {    3,     3,     3,     3,     3,     3,     3,    3};\n    // const long L = 32;\n\n    ppe::Context context(Ms, Ps, Rs);\n    context.buildModChain(L);\n    ppe::SecKey sk(context);\n    sk.GenSecKey(64);\n    if (isNeedKeySwitching)\n        sk.addSome1DMatrices();\n    ppe::PubKey pk(sk);\n\n    skStream << TYPE_PPE;\n    sk.dump(skStream);\n\n    ctxtStream << TYPE_PPE;\n    context.dump(ctxtStream);\n\n    pkStream << TYPE_PPE;\n    pk.dump(pkStream);\n\n    skStream.close();\n    ctxtStream.close();\n    pkStream.close();\n    return true;\n}\n\ntemplate<typename T>\nstd::pair<double, double> _mean_std(const NTL::Mat<T> &mat, const long colNum) {\n    T sum(0);\n    const long N = mat.NumRows();\n    assert(N >= 1);\n    for (long r = 0; r < mat.NumRows(); r++)\n        sum += mat[r][colNum];\n    double mean = NTL::to_double(sum) / N;\n    double square_sum(0.0);\n    for (long r = 0; r < mat.NumRows(); r++) {\n        double diff = NTL::to_double(mat[r][colNum]) - mean;\n        square_sum += (diff * diff);\n    }\n    double std = std::sqrt((square_sum) / N);\n    return std::make_pair(mean, std);\n}\n", "meta": {"hexsha": "d3b4a6159e01c3b55f30ee56c5218b62c78217e6", "size": 13392, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "core/src/core/protocol-LR.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/core/protocol-LR.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/core/protocol-LR.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": 33.7329974811, "max_line_length": 109, "alphanum_fraction": 0.5349462366, "num_tokens": 3412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.48037615929182054}}
{"text": "/*******************************************************************************\n *\n * Sparse DBM implementation, with the same underlying architecture\n * as SplitDBM\n *\n * Graeme Gange (gkgange@unimelb.edu.au)\n * Jorge A. Navas (jorge.navas@sri.com)\n ******************************************************************************/\n\n#pragma once\n\n#include <crab/common/types.hpp>\n#include <crab/common/stats.hpp>\n#include <crab/common/debug.hpp>\n#include <crab/domains/graphs/graph_config.hpp>\n#include <crab/domains/graphs/graph_ops.hpp>\n#include <crab/domains/linear_constraints.hpp>\n#include <crab/domains/interval.hpp>\n#include <crab/domains/abstract_domain.hpp>\n#include <crab/domains/abstract_domain_specialized_traits.hpp>\n#include <crab/domains/backward_assign_operations.hpp>\n\n#include <boost/optional.hpp>\n#include <boost/container/flat_map.hpp>\n#include <unordered_set>\n\n//#define CHECK_POTENTIAL\n//#define SDBM_NO_NORMALIZE\n\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wsign-compare\"\n\nnamespace crab {\n\n  namespace domains {\n\n    template<class Number, class VariableName,\n\t     class Params = DBM_impl::DefaultParams<Number>>\n    class SparseDBM_ final:\n      public abstract_domain<SparseDBM_<Number,VariableName,Params>> {\n      typedef SparseDBM_<Number, VariableName, Params> DBM_t;\n      typedef abstract_domain<DBM_t> abstract_domain_t;\n      \n     public:\n      \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::disjunctive_linear_constraint_system_t;\n      using typename abstract_domain_t::variable_t;\n      using typename abstract_domain_t::variable_vector_t;\n      using typename abstract_domain_t::pointer_constraint_t;\n      typedef Number number_t;\n      typedef VariableName varname_t;\n      typedef typename linear_constraint_t::kind_t constraint_kind_t;\n      typedef ikos::interval<number_t>  interval_t;\n\n     private:\n      \n      typedef ikos::bound<number_t>  bound_t;\n      typedef typename Params::Wt Wt;\n      typedef typename Params::graph_t graph_t;\n      typedef DBM_impl::NtoW<number_t, Wt> ntow;\n      typedef typename graph_t::vert_id vert_id;\n      typedef boost::container::flat_map<variable_t, vert_id> vert_map_t;\n      typedef typename vert_map_t::value_type vmap_elt_t;\n      typedef std::vector< boost::optional<variable_t>> rev_map_t;\n      typedef GraphOps<graph_t> GrOps;\n      typedef GraphPerm<graph_t> GrPerm;\n      typedef typename GrOps::edge_vector edge_vector;\n      // < <x, y>, k> == x - y <= k.\n      typedef std::pair<std::pair<variable_t, variable_t>, Wt> diffcst_t;\n      typedef std::unordered_set<vert_id> vert_set_t;\n\n      protected:\n        \n      //================\n      // Domain data\n      //================\n      vert_map_t vert_map; // Mapping from variables to vertices\n      rev_map_t rev_map;\n      graph_t g; // The underlying relation graph\n      std::vector<Wt> potential; // Stored potential for the vertex\n      vert_set_t unstable;\n      bool _is_bottom;\n\n      /*\n      void forget(std::vector<int> idxs) {\n        dbm ret = NULL;\n        ret = dbm_forget_array(&idxs[0], idxs.size(), _dbm);\n        dbm_dealloc(_dbm);\n        swap(_dbm, ret);\n      }\n      */\n\n      class Wt_max {\n      public:\n       Wt_max() { } \n       Wt apply(const Wt& x, const Wt& y) { return max(x, y); }\n       bool default_is_absorbing() { return true; }\n      };\n\n      class Wt_min {\n      public:\n        Wt_min() { }\n        Wt apply(const Wt& x, const Wt& y) { return std::min(x, y); }\n        bool default_is_absorbing() { return false; }\n      };\n\n      vert_id get_vert(variable_t v)\n      {\n        auto it = vert_map.find(v);\n        if(it != vert_map.end())\n          return (*it).second;\n\n        vert_id vert(g.new_vertex());\n        // Initialize \n        assert(vert <= rev_map.size());\n        if(vert < rev_map.size())\n        {\n          assert(!rev_map[vert]);\n          potential[vert] = Wt(0);\n          rev_map[vert] = v;\n        } else {\n          potential.push_back(Wt(0));\n          rev_map.push_back(v);\n        }\n        vert_map.insert(vmap_elt_t(v, vert));\n\n        assert(vert != 0);\n\n        return vert;\n      }\n\n      vert_id get_vert(graph_t& g, vert_map_t& vmap, rev_map_t& rmap,\n          std::vector<Wt>& pot, variable_t v)\n      {\n        auto it = vmap.find(v);\n        if(it != vmap.end())\n          return (*it).second;\n\n        vert_id vert(g.new_vertex());\n\t// vmap.insert(vmap_elt_t(v, vert)); \n        // Initialize \n        assert(vert <= rmap.size());\n        if(vert < rmap.size())\n        {\n          assert(!rmap[vert]);\n          pot[vert] = Wt(0);\n          rmap[vert] = v;\n        } else {\n          pot.push_back(Wt(0));\n          rmap.push_back(v);\n        }\n        vmap.insert(vmap_elt_t(v, vert));\n\n        return vert;\n      }\n\n      template<class G, class P>\n      inline bool check_potential(G& g, P& p)\n      {\n        #ifdef CHECK_POTENTIAL\n        for(vert_id v : g.verts())\n        {\n          for(vert_id d : g.succs(v))\n          {\n            if(p[v] + g.edge_val(v, d) - p[d] < Wt(0))\n            {\n              assert(0 && \"Invalid potential.\");\n              return false;\n            }\n          }\n        }\n        #endif\n        return true;\n      }\n\n      class vert_set_wrap_t {\n      public:\n        vert_set_wrap_t(const vert_set_t& _vs)\n          : vs(_vs)\n        { }\n\n        bool operator[](vert_id v) const {\n          return vs.find(v) != vs.end();\n        }\n        const vert_set_t& vs;\n      };\n\n      // Evaluate the potential value of a variable.\n      Wt pot_value(variable_t v)\n      {\n        auto it = vert_map.find(v); \n        if(it != vert_map.end())\n          return potential[(*it).second];\n\n        return ((Wt) 0);\n      }\n\n      Wt pot_value(variable_t v, std::vector<Wt>& potential)\n      {\n        auto it = vert_map.find(v); \n        if(it != vert_map.end())\n          return potential[(*it).second];\n\n        return ((Wt) 0);\n      }\n\n      // Evaluate an expression under the chosen potentials\n      Wt eval_expression(linear_expression_t e, bool overflow) {\n        Wt v(ntow::convert(e.constant(), overflow));\n\tif (overflow) {\n\t  return Wt(0);\n\t}\n\t\n        for(auto p : e) {\n\t  Wt coef = ntow::convert(p.first , overflow);\n\t  if (overflow) {\n\t    return Wt(0);\n\t  }\n\t  v += (pot_value(p.second) - potential[0])*coef;\n        }\n        return v;\n      }\n      \n      interval_t eval_interval(linear_expression_t e) {\n        interval_t r = e.constant();\n        for (auto p : e) {\n          r += p.first * operator[](p.second);\n\t}\n        return r;\n      }\n\n      interval_t compute_residual(linear_expression_t e, variable_t pivot) {\n\tinterval_t residual(-e.constant());\n\tfor (typename linear_expression_t::iterator it = e.begin(); it != e.end(); ++it) {\n\t  variable_t v = it->second;\n\t  if (v.index() != pivot.index()) {\n\t    residual = residual - (interval_t(it->first) * this->operator[](v));\n\t  }\n\t}\n\treturn residual;\n      }\n\n      interval_t get_interval(variable_t x) {\n        return get_interval(vert_map, g, x);\n      }\n\n      interval_t get_interval(vert_map_t& m, graph_t& r, variable_t x) {\n        auto it = m.find(x);\n        if(it == m.end())\n        {\n          return interval_t::top();\n        }\n        vert_id v = (*it).second;\n        interval_t x_out = interval_t(\n            r.elem(v, 0) ? -number_t(r.edge_val(v, 0)) : bound_t::minus_infinity(),\n            r.elem(0, v) ? number_t(r.edge_val(0, v)) : bound_t::plus_infinity());\n        return x_out;\n        /*\n        boost::optional< interval_t > v = r.lookup(x);\n        if(v)\n          return *v;\n        else\n          return interval_t::top();\n          */\n      }\n      \n      // Turn an assignment into a set of difference constraints.\n      void diffcsts_of_assign(variable_t x, linear_expression_t exp,\n\t\t\t      std::vector<std::pair<variable_t, Wt>>& lb,\n\t\t\t      std::vector<std::pair<variable_t,Wt>>& ub) {\n        {\n          // Process upper bounds.\n          boost::optional<variable_t> unbounded_ubvar;\n\t  bool overflow;\n\t  \n          Wt exp_ub(ntow::convert(exp.constant(), overflow));\n\t  if (overflow) {\n\t    return;\n\t  }\n\t  \n          std::vector<std::pair<variable_t, Wt>> ub_terms;\n          for(auto p : exp)\n          {\n            Wt coeff(ntow::convert(p.first, overflow));\n\t    if (overflow) {\n\t      continue;\n\t    }\n            if(coeff < Wt(0))\n            {\n              // Can't do anything with negative coefficients.\n              bound_t y_lb = operator[](p.second).lb();\n              if(y_lb.is_infinite())\n                goto assign_ub_finish;\n              exp_ub += ntow::convert(*(y_lb.number()), overflow) * coeff;\n\t      if (overflow) {\n\t\tcontinue;\n\t      }\n            } else {\n              variable_t y(p.second);\n              bound_t y_ub = operator[](y).ub(); \n              if(y_ub.is_infinite())\n              {\n                if(unbounded_ubvar || coeff != Wt(1))\n                  goto assign_ub_finish;\n                unbounded_ubvar = y;\n              } else {\n                Wt ymax(ntow::convert(*(y_ub.number()), overflow));\n\t\tif (overflow) {\n\t\t  continue;\n\t\t}\n                exp_ub += ymax*coeff;\n                ub_terms.push_back({y, ymax});\n              }\n            }\n          }\n\n          if(unbounded_ubvar) {\n            // There is exactly one unbounded variable. \n            ub.push_back({*unbounded_ubvar, exp_ub});\n          } else {\n            for(auto p : ub_terms) {\n              ub.push_back({p.first, exp_ub - p.second});\n            }\n          }\n        }\n      assign_ub_finish:\n\n        {\n          boost::optional<variable_t> unbounded_lbvar;\n\t  bool overflow;\n\t  \n          Wt exp_lb(ntow::convert(exp.constant(), overflow));\n\t  if (overflow) {\n\t    return;\n\t  }\n          std::vector<std::pair<variable_t, Wt>> lb_terms;\n          for(auto p : exp)\n          {\n            Wt coeff(ntow::convert(p.first, overflow));\n\t    if (overflow) {\n\t      continue;\n\t    }\n            if(coeff < Wt(0))\n            {\n              // Again, can't do anything with negative coefficients.\n              bound_t y_ub = operator[](p.second).ub();\n              if(y_ub.is_infinite())\n                goto assign_lb_finish;\n              exp_lb += (ntow::convert(*(y_ub.number()), overflow)) * coeff;\n\t      if (overflow) {\n\t\tcontinue;\n\t      }\n            } else {\n              variable_t y(p.second);\n              bound_t y_lb = operator[](y).lb(); \n              if(y_lb.is_infinite())\n              {\n                if(unbounded_lbvar || coeff != Wt(1))\n                  goto assign_lb_finish;\n                unbounded_lbvar = y;\n              } else {\n                Wt ymin(ntow::convert(*(y_lb.number()), overflow));\n\t\tif (overflow) {\n\t\t  continue;\n\t\t}\n                exp_lb += ymin*coeff;\n                lb_terms.push_back({y, ymin});\n              }\n            }\n          }\n\n          if(unbounded_lbvar) {\n            lb.push_back({*unbounded_lbvar, exp_lb});\n          } else {\n            for(auto p : lb_terms) {\n              lb.push_back({p.first, exp_lb - p.second});\n            }\n          }\n        }\n      assign_lb_finish:\n        return;\n      }\n   \n      // GKG: I suspect there're some sign/bound direction errors in the \n      // following.\n      void diffcsts_of_lin_leq(const linear_expression_t& exp, std::vector<diffcst_t>& csts,\n\t\t\t       std::vector<std::pair<variable_t, Wt>>& lbs,\n\t\t\t       std::vector<std::pair<variable_t, Wt>>& ubs) {\n        // Process upper bounds.\n        Wt unbounded_lbcoeff;\n        Wt unbounded_ubcoeff;\n        boost::optional<variable_t> unbounded_lbvar;\n        boost::optional<variable_t> unbounded_ubvar;\n\tbool underflow, overflow;\n\t\n        Wt exp_ub = -(ntow::convert(exp.constant(), overflow));\n\tif (overflow) {\n\t  return;\n\t}\n\n\t// temporary hack\n\tntow::convert(exp.constant() - 1, underflow);\n\tif (underflow) {\n\t  // We don't like MIN either because the code will compute\n\t  // minus MIN and it will silently overflow.\n\t  return;\n\t}\n\t\n        std::vector<std::pair<std::pair<Wt, variable_t>, Wt>> pos_terms, neg_terms;\n        for(auto p : exp) {\n          Wt coeff(ntow::convert(p.first, overflow));\n\t  if (overflow) {\n\t    continue;\n\t  }\n          if(coeff > Wt(0)) {\n            variable_t y(p.second);\n            bound_t y_lb = operator[](y).lb();\n            if(y_lb.is_infinite()) {\n              if(unbounded_lbvar)\n                goto diffcst_finish;\n              unbounded_lbvar = y;\n              unbounded_lbcoeff = coeff;\n            } else {\n              Wt ymin(ntow::convert(*(y_lb.number()), overflow));\n\t      if (overflow) {\n\t\tcontinue;\n\t      }\n              // Coeff is negative, so it's still add\n              exp_ub -= ymin*coeff;\n              pos_terms.push_back({{coeff, y}, ymin});\n            }\n          } else {\n            variable_t y(p.second);\n            bound_t y_ub = operator[](y).ub(); \n            if(y_ub.is_infinite())\n            {\n              if(unbounded_ubvar)\n                goto diffcst_finish;\n              unbounded_ubvar = y;\n              unbounded_ubcoeff = -coeff;\n            } else {\n              Wt ymax(ntow::convert(*(y_ub.number()), overflow));\n\t      if (overflow) {\n\t\tcontinue;\n\t      }\n              exp_ub -= ymax*coeff;\n              neg_terms.push_back({{-coeff, y}, ymax});\n            }\n          }\n        }\n\n        if(unbounded_lbvar) {\n          variable_t x(*unbounded_lbvar);\n          if(unbounded_ubvar) {\n            if(unbounded_lbcoeff != Wt(1) || unbounded_ubcoeff != Wt(1))\n              goto diffcst_finish;\n            variable_t y(*unbounded_ubvar);\n            csts.push_back({{x, y}, exp_ub});\n          } else {\n            if(unbounded_lbcoeff == Wt(1)) {\n              for(auto p : neg_terms)\n                csts.push_back({{x, p.first.second}, exp_ub - p.second});\n            }\n            // Add bounds for x\n            ubs.push_back({x, exp_ub/unbounded_lbcoeff});\n          }\n        } else {\n          if(unbounded_ubvar) {\n            variable_t y(*unbounded_ubvar);\n            if(unbounded_ubcoeff == Wt(1)) {\n              for(auto p : pos_terms)\n                csts.push_back({{p.first.second, y}, exp_ub + p.second});\n            }\n            // Bounds for y\n            lbs.push_back({y, -exp_ub/unbounded_ubcoeff});\n          } else {\n            for(auto pl : neg_terms) {\n              for(auto pu : pos_terms) {\n                csts.push_back({{pu.first.second, pl.first.second},\n\t\t      exp_ub - pl.second + pu.second});\n\t      }\n\t    }\n\t\t      \n            for(auto pl : neg_terms) {\n              lbs.push_back({pl.first.second, -exp_ub/pl.first.first + pl.second});\n\t    }\n            for(auto pu : pos_terms) {\n              ubs.push_back({pu.first.second, exp_ub/pu.first.first + pu.second});\n\t    }\n          }\n        }\n    diffcst_finish:\n        return;\n      }\n\n      bool add_linear_leq(const linear_expression_t& exp) {\n        CRAB_LOG(\"zones-sparse\",\n                 linear_expression_t exp_tmp(exp);\n                 crab::outs() << \"Adding: \"<< exp_tmp << \"<= 0\" << \"\\n\");\n        std::vector<std::pair<variable_t, Wt>> lbs, ubs;\n        std::vector<diffcst_t> csts;\n        diffcsts_of_lin_leq(exp, csts, lbs, ubs);\n\n        assert(check_potential(g, potential));\n\n        Wt_min min_op;\n\n        edge_vector es;\n        for(auto p : lbs) {\n          es.push_back({{get_vert(p.first), 0}, -p.second});\n\t}\n        for(auto p : ubs) {\n          es.push_back({{0, get_vert(p.first)}, p.second});\n\t} \n        for(auto diff : csts) {\n          CRAB_LOG(\"zones-sparse\",\n                   crab::outs() << diff.first.first<< \"-\"<< diff.first.second<< \"<=\"\n\t\t                << diff.second<<\"\\n\";);\n          es.push_back({{get_vert(diff.first.second), get_vert(diff.first.first)}, diff.second});\n        }\n\n        for(auto edge : es)\n        {\n          // CRAB_LOG(\"zones-sparse\",\n          // crab::outs() << diff.first.first<< \"-\"<< diff.first.second<< \"<=\"\n\t  //              << diff.second<<\"\\n\";);\n\n          vert_id src = edge.first.first;\n          vert_id dest = edge.first.second;\n          g.update_edge(src, edge.second, dest, min_op);\n          if(!repair_potential(src, dest)) {\n            set_to_bottom();\n            return false;\n          }\n          assert(check_potential(g, potential));\n          \n          close_over_edge(src, dest);\n          assert(check_potential(g, potential));\n        }\n\n        assert(check_potential(g, potential));\n        return true;  \n      }\n\n      // x != n\n      void add_univar_disequation(variable_t x, number_t n) {\n\tbool overflow;\n\tinterval_t i = get_interval(x);\n\tinterval_t new_i =\n\t  linear_interval_solver_impl::trim_interval<interval_t>(i, interval_t(n));\n\tif (new_i.is_bottom()) {\n\t  set_to_bottom();\n\t} else if (!new_i.is_top() && (new_i <= i)) {\n\t  vert_id v = get_vert(x);\n\t  Wt_min min_op;\t  \t  \n\t  typename graph_t::mut_val_ref_t w;\n\t  if(new_i.lb().is_finite()) {\n\t    // strenghten lb\n\t    Wt lb_val = ntow::convert(-(*(new_i.lb().number())), overflow);\n\t    if (overflow) {\n\t      return;\n\t    }\n\t    if(g.lookup(v, 0, &w) && lb_val < w) {\n\t      g.set_edge(v, lb_val, 0);\n\t      if(!repair_potential(v, 0)) {\n\t\tset_to_bottom();\n\t\treturn;\n\t      }\n\t      assert(check_potential(g, potential));\n\t      // Update other bounds\n\t      for(auto e : g.e_preds(v)) {\n\t\tif(e.vert == 0) continue;\n\t\tg.update_edge(e.vert, e.val + lb_val, 0, min_op);\n\t\tif(!repair_potential(e.vert, 0)) {\n\t\t  set_to_bottom();\n\t\t  return;\n\t\t}\n\t\tassert(check_potential(g, potential));\n\t      }\n\t    }\n\t  }\n\t  if(new_i.ub().is_finite()) {\t    \n\t    // strengthen ub\n\t    Wt ub_val = ntow::convert(*(new_i.ub().number()), overflow);\n\t    if (overflow) {\n\t      return;\n\t    }\n\t    if(g.lookup(0, v, &w) && (ub_val < w)) {\n\t      g.set_edge(0, ub_val, v);\n\t      if(!repair_potential(0, v)) {\n\t\tset_to_bottom();\n\t\treturn;\n\t      }\n\t      assert(check_potential(g, potential));\n\t      // Update other bounds\n\t      for(auto e : g.e_succs(v)) {\n\t\tif(e.vert == 0) continue;\n\t\tg.update_edge(0, e.val + ub_val, e.vert, min_op);\n\t\tif(!repair_potential(0, e.vert)) {\n\t\t  set_to_bottom();\n\t\t  return;\n\t\t}\n\t\tassert(check_potential(g, potential));\n\t      }\n\t    }\n\t  }\n\t}\n      } \n      \n      void add_disequation(linear_expression_t e) {\n\t// XXX: similar precision as the interval domain\n\tfor (typename linear_expression_t::iterator it = e.begin(); it != e.end(); ++it) {\n\t  variable_t pivot = it->second;\n\t  interval_t i = compute_residual(e, pivot) / interval_t(it->first);\n\t  if (auto k = i.singleton()) {\n\t    add_univar_disequation(pivot, *k);\n\t  }\n\t}\t\n      }\n\n      // Restore potential after an edge addition\n      bool repair_potential(vert_id src, vert_id dest)\n      {\n        return GrOps::repair_potential(g, potential, src, dest);\n      }\n\n      // Restore closure after a single edge addition\n      void close_over_edge(vert_id ii, vert_id jj) {\n        Wt_min min_op;\n\n        Wt c = g.edge_val(ii,jj);\n\n        typename graph_t::mut_val_ref_t w;\n\n        // There may be a cheaper way to do this.\n        // GKG: Now implemented.\n        std::vector<std::pair<vert_id, Wt>> src_dec;   \n\n        for(auto edge : g.e_preds(ii)) {\n          vert_id se = edge.vert;\n          Wt w_si = edge.val;\n          Wt wt_sij = w_si + c;\n\n          assert(g.succs(se).begin() != g.succs(se).end());\n          if(se != jj) {\n            if(g.lookup(se, jj, &w)) {\n              if(w.get() <= wt_sij)\n                continue;\n              w = wt_sij;\n            } else {\n              g.add_edge(se, wt_sij, jj);\n            }\n\t    // assert(potential[se] + g.edge_val(se, jj) - potential[jj] >= Wt(0));\n            src_dec.push_back({se, w_si});\n            \n           /*\n            for(auto edge : g.e_succs(jj))\n            {\n              vert_id de = edge.vert;\n              if(se != de)\n              {\n                Wt wt_sijd = wt_sij + edge.val;\n                if(g.lookup(se, de, &w))\n                {\n                  if((*w) <= wt_sijd)\n                    continue;\n                  (*w) = wt_sijd;\n                } else {\n                  g.add_edge(se, wt_sijd, de);\n                }\n              }\n            }\n            */\n          }\n        }\n\n        std::vector<std::pair<vert_id, Wt>> dest_dec;   \n        for(auto edge : g.e_succs(jj)) {\n          vert_id de = edge.vert;\n          Wt w_jd = edge.val;\n          Wt wt_ijd = w_jd + c;\n          if(de != ii) {\n            if(g.lookup(ii, de, &w)) {\n              if(w.get() <= wt_ijd)\n                continue;\n              w = wt_ijd;\n            } else {\n              g.add_edge(ii, wt_ijd, de);\n            }\n\t    // assert(potential[ii] + g.edge_val(ii, de) - potential[de] >= Wt(0));\n            // dest_dec.push_back(std::make_pair(de, edge.val));\n            dest_dec.push_back({de, w_jd});\n          }\n        }\n        // Look at (src, dest) pairs with updated edges.\n        for(auto s_p : src_dec) {\n          vert_id se = s_p.first;\n          Wt wt_sij = c + s_p.second;\n          for(auto d_p : dest_dec) {\n            vert_id de = d_p.first;\n            Wt wt_sijd = wt_sij + d_p.second; \n            if(g.lookup(se, de, &w)) {\n              if(w.get() <= wt_sijd)\n                continue;\n              w = wt_sijd;\n            } else {\n              g.add_edge(se, wt_sijd, de);\n            }\n\t    //  assert(potential[se] + g.edge_val(se, de) - potential[de] >= Wt(0));\n          }\n        }\n        // Closure is now updated.\n      }\n    \n      // Restore closure after a variable assignment\n      // Assumption: x = f(y_1, ..., y_n) cannot induce non-trivial\n      // relations between (y_i, y_j)\n      /*\n      bool close_after_assign(vert_id v)\n      {\n        // Run Dijkstra's forward to collect successors of v,\n        // and backward to collect predecessors\n        edge_vector delta; \n        if(!GrOps::close_after_assign(g, potential, v, delta))\n          return false;\n        GrOps::apply_delta(g, delta);\n        return true; \n      }\n\n      bool closure(void)\n      {\n        // Full Johnson-style all-pairs shortest path\n        CRAB_ERROR(\"SparseWtGraph::closure not yet implemented.\"); \n      }\n      */\n\n      \n   public:\n      \n      SparseDBM_(bool is_bottom = false):\n        _is_bottom(is_bottom)\n      {\n        g.growTo(1);  // Allocate the zero vector\n        potential.push_back(Wt(0));\n        rev_map.push_back(boost::none);\n      }\n\n      // FIXME: Rewrite to avoid copying if o is _|_\n      SparseDBM_(const DBM_t& o) :\n          vert_map(o.vert_map),\n          rev_map(o.rev_map),\n          g(o.g),\n          potential(o.potential),\n          unstable(o.unstable),\n          _is_bottom(false)\n      {\n\n        crab::CrabStats::count(getDomainName() + \".count.copy\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".copy\");\n\n        if(o._is_bottom)\n          set_to_bottom();\n\n        if(!_is_bottom)\n          assert(g.size() > 0);\n      }\n\n      SparseDBM_(DBM_t&& o)\n        : vert_map(std::move(o.vert_map)), rev_map(std::move(o.rev_map)),\n          g(std::move(o.g)), potential(std::move(o.potential)),\n          unstable(std::move(o.unstable)),\n          _is_bottom(o._is_bottom)\n      { }\n\n      // Magical rvalue ownership stuff for efficient initialization\n      SparseDBM_(vert_map_t&& _vert_map, rev_map_t&& _rev_map, graph_t&& _g,\n\t\t std::vector<Wt>&& _potential, vert_set_t&& _unstable)\n        : vert_map(std::move(_vert_map)), rev_map(std::move(_rev_map)),\n\t  g(std::move(_g)), potential(std::move(_potential)),\n          unstable(std::move(_unstable)), _is_bottom(false) {\n\n\tCRAB_LOG(\"zones-sparse-size\",\n                 auto p = size();\n                 crab::outs() << \"#nodes = \" << p.first << \" #edges=\" << p.second << \"\\n\";);\n\n\tassert(g.size() > 0);\n      }\n\n\n      SparseDBM_& operator=(const SparseDBM_& o)\n      {\n        crab::CrabStats::count(getDomainName() + \".count.copy\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".copy\");\n\n        if(this != &o)\n        {\n          if(o._is_bottom)\n            set_to_bottom();\n          else {\n            _is_bottom = false;\n            vert_map = o.vert_map;\n            rev_map = o.rev_map;\n            g = o.g;\n            potential = o.potential;\n            unstable = o.unstable;\n            assert(g.size() > 0);\n          }\n        }\n        return *this;\n      }\n\n      SparseDBM_& operator=(SparseDBM_&& o)\n      {\n        if(o._is_bottom) {\n          set_to_bottom();\n        } else {\n          _is_bottom = false;\n          vert_map = std::move(o.vert_map);\n          rev_map = std::move(o.rev_map);\n          g = std::move(o.g);\n          potential = std::move(o.potential);\n          unstable = std::move(o.unstable);\n        }\n        return *this;\n      }\n       \n      void set_to_top() {\n\tSparseDBM_ abs(false);\n\tstd::swap(*this, abs);\n      }\n\n      void set_to_bottom() {\n        vert_map.clear();\n        rev_map.clear();\n        g.clear();\n        potential.clear();\n        unstable.clear();\n        _is_bottom = true;\n      }\n      \n      // void set_to_bottom() {\n      // \tSparseDBM_ abs(true);\n      // \tstd::swap(*this, abs);\t\n      // }\n    \n      bool is_bottom() {\n\t// if(!_is_bottom && g.has_negative_cycle())\n\t// _is_bottom = true;\n        return _is_bottom;\n      }\n    \n      bool is_top() {\n        if(_is_bottom)\n          return false;\n        return g.is_empty();\n      }\n    \n      bool operator<=(DBM_t o)  {\n        crab::CrabStats::count(getDomainName() + \".count.leq\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".leq\");\n\n        // cover all trivial cases to avoid allocating a dbm matrix\n        if (is_bottom()) \n          return true;\n        else if(o.is_bottom())\n          return false;\n        else if (o.is_top())\n          return true;\n        else if (is_top())\n          return false;\n        else {\n          normalize();\n\n          // CRAB_LOG(\"zones-sparse\",\n\t  //          crab::outs() << \"operator<=: \"<< *this<< \"<=?\"<< o << \"\\n\");\n\n          if(vert_map.size() < o.vert_map.size())\n            return false;\n\n          typename graph_t::mut_val_ref_t wx;\n\n          // Set up a mapping from o to this.\n          std::vector<unsigned int> vert_renaming(o.g.size(),-1);\n          vert_renaming[0] = 0;\n          for(auto p : o.vert_map)\n          {\n            auto it = vert_map.find(p.first);\n            // We can't have this <= o if we're missing some\n            // vertex.\n            if(it == vert_map.end())\n              return false;\n            vert_renaming[p.second] = (*it).second;\n          }\n\n          assert(g.size() > 0);\n          // GrPerm g_perm(vert_renaming, g);\n\n          for(vert_id ox : o.g.verts())\n          {\n            assert(vert_renaming[ox] != -1);\n            vert_id x = vert_renaming[ox];\n            for(auto edge : o.g.e_succs(ox))\n            {\n              vert_id oy = edge.vert;\n              assert(vert_renaming[ox] != -1);\n              vert_id y = vert_renaming[oy];\n              Wt ow = edge.val;\n\n              if(!g.lookup(x, y, &wx) || (ow < wx))\n                return false;\n            }\n          }\n          return true;\n        }\n      }\n      \n      // FIXME: can be done more efficient\n      void operator|=(DBM_t o) {\n        *this = *this | o;\n      }\n\n      DBM_t operator|(DBM_t o) {\n        crab::CrabStats::count(getDomainName() + \".count.join\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".join\");\n\n        if (is_bottom() || o.is_top())\n          return o;\n        else if (is_top() || o.is_bottom())\n          return *this;\n        else {\n          CRAB_LOG (\"zones-sparse\",\n                    crab::outs() << \"Before join:\\n\"<<\"DBM 1\\n\"<<*this<<\"\\n\"<<\"DBM 2\\n\"\n\t\t                 << o << \"\\n\");\n\n          normalize();\n          o.normalize();\n\n          assert(check_potential(g, potential));\n          assert(check_potential(o.g, o.potential));\n\n          // Figure out the common renaming, initializing the\n          // resulting potentials as we go.\n          std::vector<vert_id> perm_x;\n          std::vector<vert_id> perm_y;\n          std::vector<variable_t> perm_inv;\n\n          std::vector<Wt> pot_rx;\n          std::vector<Wt> pot_ry;\n          vert_map_t out_vmap;\n          rev_map_t out_revmap;\n          // Add the zero vertex\n          assert(potential.size() > 0);\n          pot_rx.push_back(0);\n          pot_ry.push_back(0);\n          perm_x.push_back(0);\n          perm_y.push_back(0);\n          out_revmap.push_back(boost::none);\n\n          for(auto p : vert_map)\n          {\n            auto it = o.vert_map.find(p.first); \n            // Variable exists in both\n            if(it != o.vert_map.end())\n            {\n              out_vmap.insert(vmap_elt_t(p.first, perm_x.size()));\n              out_revmap.push_back(p.first);\n\n              pot_rx.push_back(potential[p.second] - potential[0]);\n              pot_ry.push_back(o.potential[(*it).second] - o.potential[0]);\n              perm_inv.push_back(p.first);\n              perm_x.push_back(p.second);\n              perm_y.push_back((*it).second);\n            }\n          }\n\t  // unsigned int sz = perm_x.size();\n\n          // Build the permuted view of x and y.\n          assert(g.size() > 0);\n          GrPerm gx(perm_x, g);\n          assert(o.g.size() > 0);\n          GrPerm gy(perm_y, o.g);\n\n          // We now have the relevant set of relations. Because g_rx and g_ry are closed,\n          // the result is also closed.\n          Wt_min min_op;\n          graph_t join_g(GrOps::join(gx, gy));\n\n          // Now garbage collect any unused vertices\n          for(vert_id v : join_g.verts())\n          {\n            if(v == 0)\n              continue;\n            if(join_g.succs(v).size() == 0 && join_g.preds(v).size() == 0)\n            {\n              join_g.forget(v);\n              if(out_revmap[v])\n              {\n                out_vmap.erase(*(out_revmap[v]));\n                out_revmap[v] = boost::none;\n              }\n            }\n          }\n          \n          DBM_t res(std::move(out_vmap), std::move(out_revmap), std::move(join_g),\n\t\t    std::move(pot_rx), vert_set_t());\n          CRAB_LOG(\"zones-sparse\",\n                    crab::outs() << \"Result join:\\n\"<<res<<\"\\n\";);\n\n          return res;\n        }\n      }\n\n      DBM_t operator||(DBM_t o) {\t\n        crab::CrabStats::count(getDomainName() + \".count.widening\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".widening\");\n\n        if (is_bottom())\n          return o;\n        else if (o.is_bottom())\n          return *this;\n        else {\n          CRAB_LOG(\"zones-sparse\",\n\t\t   DBM_t left(*this); // to avoid closure on left operand\n\t\t   crab::outs() << \"Before widening:\\n\"<<\"DBM 1\\n\"\n\t\t                << left <<\"\\n\"<<\"DBM 2\\n\" << o<<\"\\n\";);\n          o.normalize();\n          \n          // Figure out the common renaming\n          std::vector<vert_id> perm_x;\n          std::vector<vert_id> perm_y;\n          vert_map_t out_vmap;\n          rev_map_t out_revmap;\n          std::vector<Wt> widen_pot;\n          vert_set_t widen_unstable(unstable);\n\n          assert(potential.size() > 0);\n          widen_pot.push_back(Wt(0));\n          perm_x.push_back(0);\n          perm_y.push_back(0);\n          out_revmap.push_back(boost::none);\n          for(auto p : vert_map)\n          {\n            auto it = o.vert_map.find(p.first); \n            // Variable exists in both\n            if(it != o.vert_map.end())\n            {\n              out_vmap.insert(vmap_elt_t(p.first, perm_x.size()));\n              out_revmap.push_back(p.first);\n\n              widen_pot.push_back(potential[p.second] - potential[0]);\n              perm_x.push_back(p.second);\n              perm_y.push_back((*it).second);\n            }\n          }\n\n          // Build the permuted view of x and y.\n          assert(g.size() > 0);\n          GrPerm gx(perm_x, g);            \n          assert(o.g.size() > 0);\n          GrPerm gy(perm_y, o.g);\n         \n          // Now perform the widening \n          std::vector<vert_id> destabilized;\n          graph_t widen_g(GrOps::widen(gx, gy, destabilized));\n          for(vert_id v : destabilized)\n            widen_unstable.insert(v);\n\n          DBM_t res(std::move(out_vmap), std::move(out_revmap), std::move(widen_g), \n                    std::move(widen_pot), std::move(widen_unstable));\n\n          CRAB_LOG(\"zones-sparse\",\n\t\t   DBM_t res_copy(res);\n\t\t   crab::outs() << \"Result widening:\\n\" << res_copy <<\"\\n\";);\n          return res;\n        }\n      }\n\n      DBM_t operator&(DBM_t o) {\n        crab::CrabStats::count(getDomainName() + \".count.meet\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".meet\");\n\n        if (is_bottom() || o.is_bottom())\n          return DBM_t::bottom();\n        else if (is_top())\n          return o;\n        else if (o.is_top())\n          return *this;\n        else{\n          CRAB_LOG(\"zones-sparse\",\n                    crab::outs() << \"Before meet:\\n\"<<\"DBM 1\\n\"<<*this<<\"\\n\"<<\"DBM 2\\n\"\n\t\t                 << o<<\"\\n\";);\n          normalize();\n          o.normalize();\n          \n          // We map vertices in the left operand onto a contiguous range.\n          // This will often be the identity map, but there might be gaps.\n          vert_map_t meet_verts;\n          rev_map_t meet_rev;\n\n          std::vector<vert_id> perm_x;\n          std::vector<vert_id> perm_y;\n          std::vector<Wt> meet_pi;\n          perm_x.push_back(0);\n          perm_y.push_back(0);\n          meet_pi.push_back(Wt(0));\n          meet_rev.push_back(boost::none);\n          for(auto p : vert_map)\n          {\n            vert_id vv = perm_x.size();\n            meet_verts.insert(vmap_elt_t(p.first, vv));\n            meet_rev.push_back(p.first);\n\n            perm_x.push_back(p.second);\n            perm_y.push_back(-1);\n            meet_pi.push_back(potential[p.second] - potential[0]);\n          }\n\n          // Add missing mappings from the right operand.\n          for(auto p : o.vert_map)\n          {\n            auto it = meet_verts.find(p.first);\n\n            if(it == meet_verts.end())\n            {\n              vert_id vv = perm_y.size();\n              meet_rev.push_back(p.first);\n\n              perm_y.push_back(p.second);\n              perm_x.push_back(-1);\n              meet_pi.push_back(o.potential[p.second] - o.potential[0]);\n              meet_verts.insert(vmap_elt_t(p.first, vv));\n            } else {\n              perm_y[(*it).second] = p.second;\n            }\n          }\n\n          // Build the permuted view of x and y.\n          assert(g.size() > 0);\n          GrPerm gx(perm_x, g);\n          assert(o.g.size() > 0);\n          GrPerm gy(perm_y, o.g);\n\n          // Compute the syntactic meet of the permuted graphs.\n          bool is_closed;\n          graph_t meet_g(GrOps::meet(gx, gy, is_closed));\n           \n          // Compute updated potentials on the zero-enriched graph\n          //std::vector<Wt> meet_pi(meet_g.size());\n          // We've warm-started pi with the operand potentials\n          if(!GrOps::select_potentials(meet_g, meet_pi))\n          {\n            // Potentials cannot be selected -- state is infeasible.\n            return DBM_t::bottom();\n          }\n\n          if(!is_closed)\n          {\n            edge_vector delta;\n            if(Params::chrome_dijkstra)\n              GrOps::close_after_meet(meet_g, meet_pi, gx, gy, delta);\n            else\n              GrOps::close_johnson(meet_g, meet_pi, delta);\n\n            GrOps::apply_delta(meet_g, delta);\n          }\n          assert(check_potential(meet_g, meet_pi)); \n          DBM_t res(std::move(meet_verts), std::move(meet_rev), std::move(meet_g), \n                    std::move(meet_pi), vert_set_t());\n          CRAB_LOG(\"zones-sparse\",\n                    crab::outs() << \"Result meet:\\n\" << res<<\"\\n\";);\n          return res;\n        }\n      }\n    \n      DBM_t operator&&(DBM_t o) {\n        crab::CrabStats::count(getDomainName() + \".count.narrowing\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".narrowing\");\n\n        if (is_bottom() || o.is_bottom())\n          return DBM_t::bottom();\n        else if (is_top())\n          return o;\n        else{\n          CRAB_LOG(\"zones-sparse\",\n                    crab::outs() << \"Before narrowing:\\n\"<<\"DBM 1\\n\"<<*this<<\"\\n\"<<\"DBM 2\\n\"\n\t\t                 << o<<\"\\n\";);\n\n          // FIXME: Implement properly\n          // Narrowing as a no-op should be sound.\n          normalize();\n          DBM_t res(*this);\n\n          CRAB_LOG(\"zones-sparse\",\n                    crab::outs() << \"Result narrowing:\\n\" << res<<\"\\n\";);\n          return res;\n        }\n      }\t\n\n      DBM_t widening_thresholds(DBM_t o, const iterators::thresholds<number_t> &ts) {\n        // TODO: use thresholds\n        return(*this || o);\n      }\n\n      void normalize() {\n        // dbm_canonical(_dbm);\n        // Always maintained in normal form, except for widening\n        #ifdef SDBM_NO_NORMALIZE\n        return;\n        #endif\n\t\n        if(unstable.size() == 0)\n          return;\n\n        edge_vector delta;\n\n        if(Params::widen_restabilize)\n          GrOps::close_after_widen(g, potential, vert_set_wrap_t(unstable), delta);\n        else\n          GrOps::close_johnson(g, potential, delta);\n\n        GrOps::apply_delta(g, delta);\n\n        unstable.clear();\n      }\n\n      void minimize() {}\n      \n      void operator-=(variable_t v) {\n        crab::CrabStats::count(getDomainName() + \".count.forget\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".forget\");\n\n        if (is_bottom())\n          return;\n        normalize();\n\n        auto it = vert_map.find(v);\n        if (it != vert_map.end()) {\n          CRAB_LOG(\"zones-sparse\",\n                   crab::outs() << \"Before forget \"<< it->second<< \": \"<< g<<\"\\n\";);\n          g.forget(it->second);\n          CRAB_LOG(\"zones-sparse\", crab::outs() << \"After: \" << g<<\"\\n\";);\n                   \n          rev_map[it->second] = boost::none;\n          vert_map.erase(v);\n        }\n      }\n\n\n      // Assumption: state is currently feasible.\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(is_bottom()) {\n          return;\n\t}\n\t\n        normalize();\n\n        assert(check_potential(g, potential));\n\n        // If it's a constant, just assign the interval.\n        if (e.is_constant()){\n          set(x, e.constant());\n        } else {\n          interval_t x_int = eval_interval(e);\n\n\t  boost::optional<Wt> lb_w, ub_w;\n\t  bool overflow;\n\t  if(x_int.lb().is_finite()) {\n\t    lb_w = ntow::convert(-(*(x_int.lb().number())), overflow);\n\t    if (overflow) {\n\t      operator-=(x);\n\t      CRAB_LOG(\"zones-sparse\", crab::outs() << \"---\"<< x<< \":=\"<< e<<\"\\n\"<<*this <<\"\\n\");\n\t      return;\n\t    }\n\t  }\n\t  if(x_int.ub().is_finite()) {\n\t    ub_w = ntow::convert(*(x_int.ub().number()), overflow);\n\t    if (overflow) {\n\t      operator-=(x);\n\t      CRAB_LOG(\"zones-sparse\", crab::outs() << \"---\"<< x<< \":=\"<< e<<\"\\n\"<<*this <<\"\\n\");\n\t      return;\n\t    }\n\t  }\n\t  \n          std::vector<std::pair<variable_t, Wt>> diffs_lb, diffs_ub;\n          // Construct difference constraints from the assignment\n          diffcsts_of_assign(x, e, diffs_lb, diffs_ub);\n          if(diffs_lb.size() > 0 || diffs_ub.size() > 0) {\n            if(Params::special_assign) {\n\t      bool overflow;\n\t      Wt e_val = eval_expression(e, overflow);\n\t      if (overflow) {\n\t\toperator-=(x);\n\t\treturn;\n\t      }\n\t      \n              // Allocate a new vertex for x\n              vert_id v = g.new_vertex();\n              assert(v <= rev_map.size());\n              if(v == rev_map.size()) {\n                rev_map.push_back(x);\n                potential.push_back(potential[0] + e_val);\n              } else {\n                potential[v] = potential[0] + e_val;\n                rev_map[v] = x;\n              }\n              \n              edge_vector delta;\n              for(auto diff : diffs_lb) {\n                delta.push_back({{v, get_vert(diff.first)}, -diff.second});\n              }\n\n              for(auto diff : diffs_ub) {\n                delta.push_back({{get_vert(diff.first), v}, diff.second});\n              }\n\t      \n              if(lb_w) {\n                delta.push_back({{v,0}, *lb_w});\n\t      }\n\t      \n              if(ub_w) {\n                delta.push_back({{0,v}, *ub_w});\n\t      }\n                 \n              GrOps::apply_delta(g, delta);\n              delta.clear();\n              GrOps::close_after_assign(g, potential, v, delta);\n              GrOps::apply_delta(g, delta);\n\n              // Clear the old x vertex\n              operator-=(x);\n              vert_map.insert(vmap_elt_t(x, v));\n            } else {\n              vert_id v = g.new_vertex();\n              assert(v <= rev_map.size());\n              if(v == rev_map.size())\n              {\n                rev_map.push_back(x);\n                potential.push_back(Wt(0));\n              } else {\n                assert(!rev_map[v]);\n                potential[v] = Wt(0);\n                rev_map[v] = x;\n              }\n              Wt_min min_op;\n              edge_vector cst_edges;\n\n              if(lb_w) {\n                cst_edges.push_back({{ v,0}, *lb_w});\n\t      }\n              if(ub_w) {\n                cst_edges.push_back({{0,v}, *ub_w});\n\t      }\n\n              for(auto diff : diffs_lb) {\n                cst_edges.push_back({{v,get_vert(diff.first)}, -diff.second});\n              }\n\n              for(auto diff : diffs_ub) {\n                cst_edges.push_back({{get_vert(diff.first), v}, diff.second});\n              }\n               \n              for(auto diff : cst_edges) {\n                vert_id src = diff.first.first;\n                vert_id dest = diff.first.second;\n                g.update_edge(src, diff.second, dest, min_op);\n                if(!repair_potential(src, dest)) {\n                  assert(0 && \"Unreachable\");\n                  set_to_bottom();\n                }\n                assert(check_potential(g, potential));\n                close_over_edge(src, dest);\n                assert(check_potential(g, potential));\n              }\n              // Clear the old x vertex\n              operator-=(x);\n              vert_map.insert(vmap_elt_t(x, v));\n            }\n            assert(check_potential(g, potential));\n          } else {\n            set(x, x_int);\n          }\n          // CRAB_WARN(\"DBM only supports a cst or var on the rhs of assignment\");\n          // this->operator-=(x);\n        }\n\n\t// g.check_adjs(); \n\n        assert(check_potential(g, potential));\n        CRAB_LOG(\"zones-sparse\",\n                 crab::outs() << \"---\"<< x<< \":=\"<< e<<\"\\n\"<<*this<<\"\\n\";);\n      }\n\n      void apply(ikos::operation_t op, variable_t x, variable_t y, variable_t z){\t\n        crab::CrabStats::count(getDomainName() + \".count.apply\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".apply\");\n\n        if(is_bottom()) {\n          return;\n\t}\n\n        normalize();\n\n        switch(op) {\n          case ikos::OP_ADDITION:\n            assign(x, y+z);\n            break;\n          case ikos::OP_SUBTRACTION:\n            assign(x, y-z);\n            break;\n          // For the rest of operations, we fall back on intervals.\n          case ikos::OP_MULTIPLICATION:\n            set(x, get_interval(y)*get_interval(z));\n            break;\n  \t  case ikos::OP_SDIV: \n\t    set(x, get_interval(y)/get_interval(z));\n            break;\n          case ikos::OP_UDIV:\n\t    set(x, get_interval(y).UDiv(get_interval(z)));\n\t    break;\n          case ikos::OP_SREM:\n\t    set(x, get_interval(y).SRem(get_interval(z)));\n\t    break;\n          case ikos::OP_UREM:\n\t    set(x, get_interval(y).URem(get_interval(z)));\n\t    break;\n\t  default:\n\t    CRAB_ERROR(\"Operation \", op, \" not supported\");\n\t}\n        CRAB_LOG(\"zones-sparse\",\n                 crab::outs() << \"---\"<< x<< \":=\"<< y<< op<< z<<\"\\n\"<< *this<<\"\\n\";);\n      }\n\n    \n      void apply(ikos::operation_t op, variable_t x, variable_t y, number_t k) {\t\n        crab::CrabStats::count(getDomainName() + \".count.apply\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".apply\");\n\n        if(is_bottom()) {\n          return;\n\t}\n\n        normalize();\n\n        switch(op) {\n          case ikos::OP_ADDITION:\n            assign(x, y+k);\n            break;\n          case ikos::OP_SUBTRACTION:\n            assign(x, y-k);\n            break;\n          // For the rest of operations, we fall back on intervals.\n          case ikos::OP_MULTIPLICATION:\n            set(x, get_interval(y)*interval_t(k));\n            break;\n          case ikos::OP_SDIV:\n            set(x, get_interval(y)/interval_t(k));\t    \n            break;\n          case ikos::OP_UDIV:\n            set(x, get_interval(y).UDiv(interval_t(k)));\t    \n            break;\n          case ikos::OP_SREM:\n            set(x, get_interval(y).SRem(interval_t(k)));\t    \n            break;\n          case ikos::OP_UREM:\n            set(x, get_interval(y).URem(interval_t(k)));\t    \n            break;\n\t  default:\n\t    CRAB_ERROR(\"Operation \", op, \" not supported\");\n\t}\n\n        CRAB_LOG(\"zones-sparse\",\n                 crab::outs() << \"---\"<< x<< \":=\"<< y<< op<< k<<\"\\n\"<< *this<<\"\\n\";);\n      }\n      \n      void operator+=(linear_constraint_t cst) {\n        crab::CrabStats::count(getDomainName() + \".count.add_constraints\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".add_constraints\");\n\n\t// XXX: we do nothing with unsigned linear inequalities\n\tif (cst.is_inequality() && cst.is_unsigned()) {\n\t  CRAB_WARN(\"unsigned inequality \", cst, \" skipped by split_dbm domain\");\t  \n\t  return;\n\t}\n\t\n        if(is_bottom())\n          return;\n\n        normalize();\n\n        if (cst.is_tautology())\n          return;\n\n\t// g.check_adjs();\n      \n        if (cst.is_contradiction()){\n          set_to_bottom();\n          return ;\n        }\n\n        if (cst.is_inequality()) {\n          if(!add_linear_leq(cst.expression())) {\n            set_to_bottom();\n\t  }\n\t  // g.check_adjs();\n          CRAB_LOG(\"zones-sparse\",\n                   crab::outs() << \"--- \"<< cst<< \"\\n\"<< *this<<\"\\n\";);\n          return;\n        }\n\n        if (cst.is_strict_inequality()) {\n\t  // We try to convert a strict to non-strict.\n\t  auto nc = linear_constraint_impl::strict_to_non_strict_inequality(cst);\n\t  if (nc.is_inequality()) {\n\t    // here we succeed\n\t    if(!add_linear_leq(nc.expression())) {\n\t      set_to_bottom();\n\t    }\n\t    CRAB_LOG(\"zones-split\",\n\t\t     crab::outs() << \"--- \"<< cst<< \"\\n\"<< *this <<\"\\n\");\n\t    return;\n\t  }\n\t}\n\t\n        if (cst.is_equality()) {\n          linear_expression_t exp = cst.expression();\n          if(!add_linear_leq(exp) || !add_linear_leq(-exp)) {\n            CRAB_LOG(\"zones-sparse\", crab::outs() << \" ~~> _|_\"<<\"\\n\";);\n            set_to_bottom();\n          }\n\t  // g.check_adjs();\n          CRAB_LOG(\"zones-sparse\",\n                   crab::outs() << \"--- \"<< cst<< \"\\n\"<< *this<<\"\\n\";);\n          return;\n        }\n\n        if (cst.is_disequation()) {\n          add_disequation(cst.expression());\n          return;\n        }\n\n        CRAB_WARN(\"Unhandled constraint \", cst, \" by split_dbm\");\t\n        CRAB_LOG(\"zones-sparse\",\n                 crab::outs() << \"---\"<< cst<< \"\\n\"<< *this<<\"\\n\";);\n        return;\n      }\n    \n      void operator+=(linear_constraint_system_t csts) {  \n        if(is_bottom()) return;\n\n        for(auto cst: csts) {\n          operator+=(cst);\n        }\n      }\n\n      interval_t operator[](variable_t x) { \n        crab::CrabStats::count(getDomainName() + \".count.to_intervals\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".to_intervals\");\n\n\t// if (is_top()) return interval_t::top();\n        if (is_bottom()) {\n            return interval_t::bottom();\n        } else {\n\t  variable_t vx(x);\n          return get_interval(vert_map, g, vx);\n        }\n      }\n\n      void set(variable_t x, interval_t intv) {\n        crab::CrabStats::count(getDomainName() + \".count.assign\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".assign\");\n\n        if(is_bottom()) {\n          return;\n\t}\n\n\tif (intv.is_bottom()) {\n\t  set_to_bottom();\n\t  return;\n\t}\n\t\n        this->operator-=(x);\n\n\tif (intv.is_top()) {\n\t  return;\n\t}\n\t\n        vert_id v = get_vert(x);\n\tbool overflow;\n        if(intv.ub().is_finite()) {\n          Wt ub = ntow::convert(*(intv.ub().number()), overflow);\n\t  if (overflow) {\n\t    return;\n\t  }\n          potential[v] = potential[0] + ub;\n          g.set_edge(0, ub, v);\n          close_over_edge(0, v);\n        }\n        if(intv.lb().is_finite()) {\n          Wt lb = ntow::convert(*(intv.lb().number()), overflow);\n\t  if (overflow) {\n\t    return;\n\t  }\n          potential[v] = potential[0] + lb;\n          g.set_edge(v, -lb, 0);\n          close_over_edge(v, 0);\n        }\n      }\n\n      // backward arithmetic operators\n      void backward_assign(variable_t x, linear_expression_t e, DBM_t inv) {\n        crab::CrabStats::count(getDomainName() + \".count.backward_assign\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".backward_assign\");\n\t\n\tcrab::domains::BackwardAssignOps<DBM_t>::\n\t  assign(*this, x, e, inv);\n      }\n      \n      void backward_apply(operation_t op, variable_t x, variable_t y, number_t z,\n\t\t\t  DBM_t inv) {\n        crab::CrabStats::count(getDomainName() + \".count.backward_apply\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".backward_apply\");\n\t\n\tcrab::domains::BackwardAssignOps<DBM_t>::\n\t  apply(*this, op, x, y, z, inv);\n      }\n      \n      void backward_apply(operation_t op, variable_t x, variable_t y, variable_t z,\n\t\t\t  DBM_t inv) {\n        crab::CrabStats::count(getDomainName() + \".count.backward_apply\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".backward_apply\");\n\t\n\tcrab::domains::BackwardAssignOps<DBM_t>::\n\t  apply(*this, op, x, y, z, inv);\n      }\n      \n      // cast operators\n\n      void apply(int_conv_operation_t /*op*/, variable_t dst, variable_t src) {\n        // since reasoning about infinite precision we simply assign and\n        // ignore the widths.\n        assign(dst, src);\n      }\n\n      // bitwise operators\n      \n      void apply(ikos::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\tif (is_bottom()) return;\n        normalize();\n\t\n        // Convert to intervals and perform the operation\n        interval_t yi = operator[](y);\n        interval_t zi = operator[](z);\n        interval_t xi = interval_t::bottom();\n        switch (op) {\n          case ikos::OP_AND: {\n            xi = yi.And(zi);\n            break;\n          }\n          case ikos::OP_OR: {\n            xi = yi.Or(zi);\n            break;\n          }\n          case ikos::OP_XOR: {\n            xi = yi.Xor(zi);\n            break;\n          }\n          case ikos::OP_SHL: {\n            xi = yi.Shl(zi);\n            break;\n          }\n          case ikos::OP_LSHR: {\n            xi = yi.LShr(zi);\n            break;\n          }\n          case ikos::OP_ASHR: {\n            xi = yi.AShr(zi);\n            break;\n          }\n          default: \n            CRAB_ERROR(\"DBM: unreachable\");\n        }\n        set(x, xi);\n      }\n    \n      void apply(ikos::bitwise_operation_t op, variable_t x, variable_t y, number_t k) {\n        crab::CrabStats::count(getDomainName() + \".count.apply\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".apply\");\n\n\tif (is_bottom()) return;\n        normalize();\n\n        // Convert to intervals and perform the operation\t\n        interval_t yi = operator[](y);\n        interval_t zi(k);\n        interval_t xi = interval_t::bottom();\n\n        switch (op) {\n          case ikos::OP_AND: {\n            xi = yi.And(zi);\n            break;\n          }\n          case ikos::OP_OR: {\n            xi = yi.Or(zi);\n            break;\n          }\n          case ikos::OP_XOR: {\n            xi = yi.Xor(zi);\n            break;\n          }\n          case ikos::OP_SHL: {\n            xi = yi.Shl(zi);\n            break;\n          }\n          case ikos::OP_LSHR: {\n            xi = yi.LShr(zi);\n            break;\n          }\n          case ikos::OP_ASHR: {\n            xi = yi.AShr(zi);\n            break;\n          }\n          default: \n            CRAB_ERROR(\"DBM: unreachable\");\n        }\n        set(x, xi);\n      }\n\n      /* \n\t Begin unimplemented operations \n\t \n\t SparseDBM implements only standard abstract operations of a\n\t numerical domain.  The implementation of boolean, array, or\n\t pointer operations is empty because they should never be\n\t called.\n      */\n      \n      // boolean operations\n      void assign_bool_cst(variable_t lhs, linear_constraint_t rhs) {}\n      void assign_bool_var(variable_t lhs, variable_t rhs, bool is_not_rhs) {}\n      void apply_binary_bool(bool_operation_t op, variable_t x,variable_t y,variable_t z) {}\n      void assume_bool(variable_t v, bool is_negated) {}\n      // backward boolean operations\n      void backward_assign_bool_cst(variable_t lhs, linear_constraint_t rhs,\n\t\t\t\t    DBM_t invariant){}\n      void backward_assign_bool_var(variable_t lhs, variable_t rhs, bool is_not_rhs,\n\t\t\t\t      DBM_t invariant) {}\n      void backward_apply_binary_bool(bool_operation_t op,\n\t\t\t\t      variable_t x,variable_t y,variable_t z,\n\t\t\t\t      DBM_t invariant) {}\n      // array operations\n      void array_init(variable_t a, linear_expression_t elem_size,\n\t\t      linear_expression_t lb_idx, linear_expression_t ub_idx, \n\t\t      linear_expression_t val) {}      \n      void array_load(variable_t lhs,\n\t\t      variable_t a, linear_expression_t elem_size,\n\t\t      linear_expression_t i) {}\n      void array_store(variable_t a, linear_expression_t elem_size,\n\t\t       linear_expression_t i, linear_expression_t v, \n\t\t       bool is_strong_update) {}\n      void array_store(variable_t a_new, variable_t a_old,\n\t\t       linear_expression_t elem_size,\n\t\t       linear_expression_t i, linear_expression_t v, \n\t\t       bool is_strong_update) {}      \n      void array_store_range(variable_t a, linear_expression_t elem_size,\n\t\t\t     linear_expression_t i, linear_expression_t j,\n\t\t\t     linear_expression_t v) {}\n      void array_store_range(variable_t a_new, variable_t a_old,\n\t\t\t     linear_expression_t elem_size,\n\t\t\t     linear_expression_t i, linear_expression_t j,\n\t\t\t     linear_expression_t v) {}            \n      void array_assign(variable_t lhs, variable_t rhs) {}\n      // backward array operations\n      void backward_array_init(variable_t a, linear_expression_t elem_size,\n\t\t\t       linear_expression_t lb_idx, linear_expression_t ub_idx, \n\t\t\t       linear_expression_t val, DBM_t invariant) {}      \n      void backward_array_load(variable_t lhs,\n\t\t\t       variable_t a, linear_expression_t elem_size,\n\t\t\t       linear_expression_t i, DBM_t invariant) {}\n      void backward_array_store(variable_t a, linear_expression_t elem_size,\n\t\t\t\tlinear_expression_t i, linear_expression_t v, \n\t\t\t\tbool is_strong_update, DBM_t invariant) {}\n      void backward_array_store(variable_t a_new, variable_t a_old,\n\t\t\t\tlinear_expression_t elem_size,\n\t\t\t\tlinear_expression_t i, linear_expression_t v, \n\t\t\t\tbool is_strong_update, DBM_t invariant) {}      \n      void backward_array_store_range(variable_t a, linear_expression_t elem_size,\n\t\t\t\t      linear_expression_t i, linear_expression_t j,\n\t\t\t\t      linear_expression_t v, DBM_t invariant) {}\n      void backward_array_store_range(variable_t a_new, variable_t a_old,\n\t\t\t\t      linear_expression_t elem_size,\n\t\t\t\t      linear_expression_t i, linear_expression_t j,\n\t\t\t\t      linear_expression_t v, DBM_t invariant) {}          \n      void backward_array_assign(variable_t lhs, variable_t rhs, DBM_t invariant) {}\n      // pointer operations\n      void pointer_load(variable_t lhs, variable_t rhs)  {}\n      void pointer_store(variable_t lhs, variable_t rhs) {} \n      void pointer_assign(variable_t lhs, variable_t rhs, linear_expression_t offset) {}\n      void pointer_mk_obj(variable_t lhs, ikos::index_t address) {}\n      void pointer_function(variable_t lhs, varname_t func) {}\n      void pointer_mk_null(variable_t lhs) {}\n      void pointer_assume(pointer_constraint_t cst) {}\n      void pointer_assert(pointer_constraint_t cst) {}\n      /* End unimplemented operations */\n      \n      void rename(const variable_vector_t &from, const variable_vector_t &to) {\n        crab::CrabStats::count(getDomainName() + \".count.rename\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".rename\");\n\t\n\tif (is_top() || is_bottom()) return;\n\t\n\t// renaming vert_map by creating a new vert_map since we are\n\t// modifying the keys.\n\t// rev_map is modified in-place since we only modify values.\n\tCRAB_LOG(\"zones-sparse\",\n\t\t crab::outs() << \"Replacing {\";\n\t\t for (auto v: from) crab::outs() << v << \";\";\n\t\t crab::outs() << \"} with \";\n\t\t for (auto v: to) crab::outs() << v << \";\";\n\t\t crab::outs() << \"}:\\n\";\n\t\t crab::outs() << *this << \"\\n\";);\n\t\n\tvert_map_t new_vert_map;\n\tfor (auto kv: vert_map) {\n\t  ptrdiff_t pos = std::distance(from.begin(),\n\t\t\t\t\tstd::find(from.begin(), from.end(), kv.first));\n\t  if (pos < from.size()) {\n\t    variable_t new_v(to[pos]);\n\t    new_vert_map.insert(vmap_elt_t(new_v, kv.second));\n\t    rev_map[kv.second] = new_v;\n\t  } else {\n\t    new_vert_map.insert(kv);\n\t  }\n\t}\n\tstd::swap(vert_map, new_vert_map);\n\n\tCRAB_LOG(\"zones-sparse\",\n\t\t crab::outs() << \"RESULT=\" << *this << \"\\n\");\n      }\n\n      \n      void forget(const variable_vector_t& variables) {\n        crab::CrabStats::count(getDomainName() + \".count.forget\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".forget\");\n\t\n        if (is_bottom() || is_top())\n          return;\n\t\n        for (auto v: variables) {\n          auto it = vert_map.find(v);\n          if (it != vert_map.end()) {\n            operator-=(v);\n          }\n        }\n      }\n      \n      void project(const variable_vector_t& variables) {\n        crab::CrabStats::count(getDomainName() + \".count.project\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".project\");\n\n        if (is_bottom() || is_top()) {\n          return;\n\t}\n        if (variables.empty()) {\n\t  set_to_top();\n          return;\n\t}\n\n        normalize();\n\n        std::vector<bool> save(rev_map.size(), false);\n        for(auto x : variables) {\n          auto it = vert_map.find(x);\n          if(it != vert_map.end()) {\n            save[(*it).second] = true;\n\t  }\n        }\n\n        for(vert_id v = 0; v < rev_map.size(); v++) {\n          if(!save[v] && rev_map[v])\n            operator-=((*rev_map[v]));\n        }\n      }\n\n      void expand(variable_t x, variable_t y) {\n        crab::CrabStats::count(getDomainName() + \".count.expand\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".expand\");\n\n        if(is_bottom() || is_top()) {\n          return;\n\t}\n        \n        CRAB_LOG(\"zones-sparse\",\n                  crab::outs() << \"Before expand \" << x << \" into \" << y << \":\\n\"\n\t\t               << *this <<\"\\n\");\n\n        auto it = vert_map.find(y);\n        if(it != vert_map.end()) {\n          CRAB_ERROR(\"sparse_dbm expand operation failed because y already exists\");\n        }\n        \n        vert_id ii = get_vert(x);\n        vert_id jj = get_vert(y);\n\n        for (auto edge : g.e_preds(ii)) {\n          g.add_edge(edge.vert, edge.val, jj);\n\t}\n        \n        for (auto edge : g.e_succs(ii)) { \n          g.add_edge(jj, edge.val, edge.vert);\n\t}\n\n\tpotential[jj] = potential[ii];\n\t\n        CRAB_LOG(\"zones-sparse\",\n                  crab::outs() << \"After expand \" << x << \" into \" << y << \":\\n\"\n\t\t               << *this <<\"\\n\");\n      }\n      \n      void extract(const variable_t& x, linear_constraint_system_t& csts,\n\t\t   bool only_equalities) {\n\tcrab::CrabStats::count(getDomainName() + \".count.extract\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".extract\");\n\n        normalize();\n        if (is_bottom()) {\n\t  return;\n\t}\n\n        auto it = vert_map.find(x);\n        if(it != vert_map.end()) {\n          vert_id s = (*it).second;\n          if(rev_map[s]) {\n            variable_t vs = *rev_map[s];\n            SubGraph<graph_t> g_excl(g, 0);\n            for(vert_id d : g_excl.verts()) {\n              if(rev_map[d]) {\n                variable_t vd = *rev_map[d];\n                // We give priority to equalities since some domains\n                // might not understand inequalities\n                if (g_excl.elem(s, d) && g_excl.elem(d, s) &&\n                    g_excl.edge_val(s, d) == Wt(0) &&\n\t\t    g_excl.edge_val(d, s) == Wt(0)) {\n                  linear_constraint_t cst(linear_expression_t(vs) == vd);\n                  csts += cst;\n                } else {\n\t\t  if (!only_equalities && g_excl.elem(s, d)) {\n\t\t    linear_constraint_t cst(vd - vs <= number_t(g_excl.edge_val(s, d)));\n\t\t    csts += cst;\n\t\t  }\n\t\t  if (!only_equalities && g_excl.elem(d, s)) {\n\t\t    linear_constraint_t cst(vs - vd <= number_t(g_excl.edge_val(d, s)));\n\t\t    csts += cst;\n\t\t  }\n\t\t}\n              }\n            }\n          }\n        }\n      }\n\n      // Output function\n      void write(crab_os& o) {\n        crab::CrabStats::count(getDomainName() + \".count.write\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".write\");\n\n        normalize();\n\n        if(is_bottom()){\n          o << \"_|_\";\n          return;\n        }\n        else if (is_top()){\n          o << \"{}\";\n          return;\n        }\n        else\n        {\n          // Intervals\n          bool first = true;\n          o << \"{\";\n          // Extract all the edges\n          SubGraph<graph_t> g_excl(g, 0);\n          for(vert_id v : g_excl.verts())\n          {\n            if(!rev_map[v])\n              continue;\n            if(!g.elem(0, v) && !g.elem(v, 0))\n             continue; \n            interval_t v_out = interval_t(\n                g.elem(v, 0) ? -number_t(g.edge_val(v, 0)) : bound_t::minus_infinity(),\n                g.elem(0, v) ? number_t(g.edge_val(0, v)) : bound_t::plus_infinity());\n            \n            if(first)\n              first = false;\n            else\n              o << \", \";\n            o << *(rev_map[v]) << \" -> \" << v_out;\n          }\n\n          for(vert_id s : g_excl.verts())\n          {\n            if(!rev_map[s])\n              continue;\n            variable_t vs = *rev_map[s];\n            for(vert_id d : g_excl.succs(s))\n            {\n              if(!rev_map[d])\n                continue;\n              variable_t vd = *rev_map[d];\n              if(first)\n                first = false;\n              else\n                o << \", \";\n              o << vd << \"-\" << vs << \"<=\" << g_excl.edge_val(s, d);\n            }\n          }\n          o << \"}\";\n\n\t  // linear_constraint_system_t inv = to_linear_constraint_system();\n\t  // o << inv;\n        }\n      }\n\n      linear_constraint_system_t to_linear_constraint_system() {\n        crab::CrabStats::count(getDomainName() + \".count.to_linear_constraint_system\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".to_linear_constraint_system\");\n\n        normalize();\n\n        linear_constraint_system_t csts;\n    \n        if(is_bottom()) {\n          csts += linear_constraint_t::get_false();\n          return csts;\n        }\n\n        // Extract all the edges\n\n        SubGraph<graph_t> g_excl(g, 0);\n\n        for(vert_id v : g_excl.verts()) {\n          if(!rev_map[v])\n            continue;\n          if(g.elem(v, 0))\n            csts += linear_constraint_t(\n\t\t\t linear_expression_t(*rev_map[v]) >= -number_t(g.edge_val(v, 0)));\n          if(g.elem(0, v))\n            csts += linear_constraint_t(\n\t\t\t linear_expression_t(*rev_map[v]) <= number_t(g.edge_val(0, v)));\n        }\n\n        for(vert_id s : g_excl.verts()) {\n          if(!rev_map[s])\n            continue;\n          variable_t vs = *rev_map[s];\n          for(vert_id d : g_excl.succs(s)) {\n            if(!rev_map[d])\n              continue;\n            variable_t vd = *rev_map[d];\n            csts += linear_constraint_t(vd - vs <= number_t(g_excl.edge_val(s, d)));\n\t\t\t\t\t\n          }\n        }\n\n        return csts;\n      }\n\n      disjunctive_linear_constraint_system_t to_disjunctive_linear_constraint_system() {\n\tauto lin_csts = to_linear_constraint_system();\n\tif (lin_csts.is_false()) {\n\t  return disjunctive_linear_constraint_system_t(true /*is_false*/); \n\t} else if (lin_csts.is_true()) {\n\t  return disjunctive_linear_constraint_system_t(false /*is_false*/);\n\t} else {\n\t  return disjunctive_linear_constraint_system_t(lin_csts);\n\t}\n      }\n\n      // return number of vertices and edges\n      std::pair<std::size_t, std::size_t> size() const {\n\treturn {g.size(), g.num_edges()};\n      }\n      \n      static std::string getDomainName() {\n        return \"SparseDBM\";\n      }\n      \n    }; // class SparseDBM_\n    \n    #if 1\n    template<class Number, class VariableName,\n\t       class Params = DBM_impl::DefaultParams<Number>>\n    using SparseDBM = SparseDBM_<Number,VariableName,Params>;    \n    #else\n\n    template<typename Number, typename VariableName, typename Params>    \n    struct abstract_domain_traits<SparseDBM_<Number, VariableName, Params>> {\n      typedef Number number_t;\n      typedef VariableName varname_t;       \n    };\n    \n    // Quick wrapper which uses shared references with copy-on-write.\n    template<class Number, class VariableName,\n\t     class Params = DBM_impl::DefaultParams<Number>>\n    class SparseDBM final:\n      public abstract_domain<SparseDBM<Number,VariableName,Params>> {\n      typedef SparseDBM<Number, VariableName, Params> DBM_t;\n      typedef abstract_domain<DBM_t> abstract_domain_t;\n      \n    public:\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::disjunctive_linear_constraint_system_t;      \n      using typename abstract_domain_t::variable_t;\n      using typename abstract_domain_t::variable_vector_t;\n      using typename abstract_domain_t::pointer_constraint_t;\n      typedef Number number_t;\n      typedef VariableName varname_t;\n      typedef typename linear_constraint_t::kind_t constraint_kind_t;\n      typedef ikos::interval<number_t>  interval_t;\n\n    public:\n      \n      typedef SparseDBM_<number_t, varname_t, Params> dbm_impl_t;\n      typedef std::shared_ptr<dbm_impl_t> dbm_ref_t;\n\n      SparseDBM(dbm_ref_t _ref) : norm_ref(_ref) { }\n\n      SparseDBM(dbm_ref_t _base, dbm_ref_t _norm) \n        : base_ref(_base), norm_ref(_norm)\n      { }\n\n\n      DBM_t create(dbm_impl_t&& t)\n      {\n        return std::make_shared<dbm_impl_t>(std::move(t));\n      }\n\n      DBM_t create_base(dbm_impl_t&& t)\n      {\n        dbm_ref_t base = std::make_shared<dbm_impl_t>(t);\n        dbm_ref_t norm = std::make_shared<dbm_impl_t>(std::move(t));  \n        return DBM_t(base, norm);\n      }\n\n      void lock(void)\n      {\n        // Allocate a fresh copy.\n        if(!norm_ref.unique())\n          norm_ref = std::make_shared<dbm_impl_t>(*norm_ref);\n        base_ref.reset();\n      }\n    public:\n\n      void set_to_top() {\n\tSparseDBM abs(false);\n\tstd::swap(*this, abs);\n      }\n\n      void set_to_bottom() {\n\tSparseDBM abs(true);\n\tstd::swap(*this, abs);\n      }\n      \n      SparseDBM(bool is_bottom = false)\n        : norm_ref(std::make_shared<dbm_impl_t>(is_bottom)) { }\n\n      SparseDBM(const DBM_t& o)\n        : base_ref(o.base_ref), norm_ref(o.norm_ref)\n      { }\n\n      SparseDBM& operator=(const DBM_t& o) {\n\tif (this != &o) {\n\t  base_ref = o.base_ref;\n\t  norm_ref = o.norm_ref;\n\t}\n        return *this;\n      }\n\n      dbm_impl_t& base(void) {\n        if(base_ref)\n          return *base_ref;\n        else\n          return *norm_ref;\n      }\n      dbm_impl_t& norm(void) { return *norm_ref; }\n\n      bool is_bottom() { return norm().is_bottom(); }\n      bool is_top() { return norm().is_top(); }\n      bool operator<=(DBM_t o) { return norm() <= o.norm(); }\n      void operator|=(DBM_t o) { lock(); norm() |= o.norm(); }\n      DBM_t operator|(DBM_t o) { return create(norm() | o.norm()); }\n      DBM_t operator||(DBM_t o) { return create_base(base() || o.norm()); }\n      //DBM_t operator||(DBM_t o) { return create(norm() || o.norm()); }\n      DBM_t operator&(DBM_t o) { return create(norm() & o.norm()); }\n      DBM_t operator&&(DBM_t o) { return create(norm() && o.norm()); }\n      DBM_t widening_thresholds(DBM_t o, const iterators::thresholds<number_t>& ts) {\n        return create_base(base().widening_thresholds(o.norm(), ts));\n      }\n\n      void normalize() { lock(); norm().normalize(); }\n      void minimize() {}\n      \n      void operator+=(linear_constraint_system_t csts) { lock(); norm() += csts; } \n      void operator-=(variable_t v) { lock(); norm() -= v; }\n      interval_t operator[](variable_t x) { return norm()[x]; }\n      void set(variable_t x, interval_t intv) { lock(); norm().set(x, intv); }\n\n      void assign(variable_t x, linear_expression_t e) { lock(); norm().assign(x, e); }\n      void apply(ikos::operation_t op, variable_t x, variable_t y, number_t k) {\n        lock(); norm().apply(op, x, y, k);\n      }\n      void apply(ikos::operation_t op, variable_t x, variable_t y, variable_t z) {\n        lock(); norm().apply(op, x, y, z);\n      }      \n      void apply(int_conv_operation_t op, variable_t dst, variable_t src) {\n        lock(); norm().apply(op, dst, src);\t\n      }\n      void backward_assign(variable_t x, linear_expression_t e, DBM_t invariant) {\n\tlock(); norm().backward_assign(x, e, invariant.norm());\n      }\n      void backward_apply(operation_t op,\n\t\t\t  variable_t x, variable_t y, number_t k, DBM_t invariant) {\n\tlock(); norm().backward_apply(op, x, y, k, invariant.norm());\n      }\n      void backward_apply(operation_t op,\n\t\t\t  variable_t x, variable_t y, variable_t z, DBM_t invariant) {\n\tlock(); norm().backward_apply(op, x, y, z, invariant.norm());\n      }\t\n      void apply(ikos::bitwise_operation_t op, variable_t x, variable_t y, number_t k) {\n        lock(); norm().apply(op, x, y, k);\n      }\n      void apply(ikos::bitwise_operation_t op, variable_t x, variable_t y, variable_t z) {\n        lock(); norm().apply(op, x, y, z);\n      }\n\n      /* Begin unimplemented operations */\n      // boolean operations\n      void assign_bool_cst(variable_t lhs, linear_constraint_t rhs) {}\n      void assign_bool_var(variable_t lhs, variable_t rhs, bool is_not_rhs) {}\n      void apply_binary_bool(bool_operation_t op, variable_t x,variable_t y,variable_t z) {}\n      void assume_bool(variable_t v, bool is_negated) {}\n      // backward boolean operations\n      void backward_assign_bool_cst(variable_t lhs, linear_constraint_t rhs,\n\t\t\t\t    DBM_t invariant){}\n      void backward_assign_bool_var(variable_t lhs, variable_t rhs, bool is_not_rhs,\n\t\t\t\t      DBM_t invariant) {}\n      void backward_apply_binary_bool(bool_operation_t op,\n\t\t\t\t      variable_t x,variable_t y,variable_t z,\n\t\t\t\t      DBM_t invariant) {}\n      // array operations\n      void array_init(variable_t a, linear_expression_t elem_size,\n\t\t      linear_expression_t lb_idx, linear_expression_t ub_idx, \n\t\t      linear_expression_t val) {}      \n      void array_load(variable_t lhs,\n\t\t      variable_t a, linear_expression_t elem_size,\n\t\t      linear_expression_t i) {}\n      void array_store(variable_t a, linear_expression_t elem_size,\n\t\t       linear_expression_t i, linear_expression_t v, \n\t\t       bool is_strong_update) {}\n      void array_store(variable_t a_new, variable_t a_old,\n\t\t       linear_expression_t elem_size,\n\t\t       linear_expression_t i, linear_expression_t v, \n\t\t       bool is_strong_update) {}      \n      void array_store_range(variable_t a, linear_expression_t elem_size,\n\t\t\t     linear_expression_t i, linear_expression_t j,\n\t\t\t     linear_expression_t v) {}\n      void array_store_range(variable_t a_new, variable_t a_old,\n\t\t\t     linear_expression_t elem_size,\n\t\t\t     linear_expression_t i, linear_expression_t j,\n\t\t\t     linear_expression_t v) {}                  \n      void array_assign(variable_t lhs, variable_t rhs) {}\n      // backward array operations\n      void backward_array_init(variable_t a, linear_expression_t elem_size,\n\t\t\t       linear_expression_t lb_idx, linear_expression_t ub_idx, \n\t\t\t       linear_expression_t val, DBM_t invariant) {}      \n      void backward_array_load(variable_t lhs,\n\t\t\t       variable_t a, linear_expression_t elem_size,\n\t\t\t       linear_expression_t i, DBM_t invariant) {}\n      void backward_array_store(variable_t a, linear_expression_t elem_size,\n\t\t\t\tlinear_expression_t i, linear_expression_t v, \n\t\t\t\tbool is_strong_update, DBM_t invariant) {}\n      void backward_array_store(variable_t a_new, variable_t a_old,\n\t\t\t\tlinear_expression_t elem_size,\n\t\t\t\tlinear_expression_t i, linear_expression_t v, \n\t\t\t\tbool is_strong_update, DBM_t invariant) {}      \n      void backward_array_store_range(variable_t a, linear_expression_t elem_size,\n\t\t\t\t      linear_expression_t i, linear_expression_t j,\n\t\t\t\t      linear_expression_t v, DBM_t invariant) {}\n      void backward_array_store_range(variable_t a_new, variable_t a_old,\n\t\t\t\t      linear_expression_t elem_size,\n\t\t\t\t      linear_expression_t i, linear_expression_t j,\n\t\t\t\t      linear_expression_t v, DBM_t invariant) {}       \n      void backward_array_assign(variable_t lhs, variable_t rhs, DBM_t invariant) {}\n      // pointer operations\n      void pointer_load(variable_t lhs, variable_t rhs)  {}\n      void pointer_store(variable_t lhs, variable_t rhs) {} \n      void pointer_assign(variable_t lhs, variable_t rhs, linear_expression_t offset) {}\n      void pointer_mk_obj(variable_t lhs, ikos::index_t address) {}\n      void pointer_function(variable_t lhs, varname_t func) {}\n      void pointer_mk_null(variable_t lhs) {}\n      void pointer_assume(pointer_constraint_t cst) {}\n      void pointer_assert(pointer_constraint_t cst) {}\n      /* End unimplemented operations */\n      \n      void rename(const variable_vector_t &from, const variable_vector_t &to) {\n\tlock(); norm().rename(from, to);\n      }\n\n      void forget(const variable_vector_t& variables) {\n\tlock(); norm().forget(variables);\n      }\n      \n      void expand(variable_t x, variable_t y) {\n\tlock(); norm().expand(x, y);\n      }\n\n      void project(const variable_vector_t& variables) {\n\tlock(); norm().project(variables);\n      }\n\n      void extract(const variable_t& x, linear_constraint_system_t&csts, bool only_equalities)\n      { norm().extract(x, csts, only_equalities); }\n\n      void write(crab_os& o) { norm().write(o); }\n    \n      linear_constraint_system_t to_linear_constraint_system() {\n        return norm().to_linear_constraint_system();\n      }\n      disjunctive_linear_constraint_system_t to_disjunctive_linear_constraint_system() {\n        return norm().to_disjunctive_linear_constraint_system();\n      }\n      \n      static std::string getDomainName() { return dbm_impl_t::getDomainName(); }\n\n      std::pair<std::size_t, std::size_t> size() const {\n\treturn norm().size();\n      }\n      \n    protected:  \n      dbm_ref_t base_ref;  \n      dbm_ref_t norm_ref;\n    };\n    #endif\n\n\n    template<typename Number, typename VariableName, typename Params>    \n    struct abstract_domain_traits<SparseDBM<Number, VariableName, Params>> {\n      typedef Number number_t;\n      typedef VariableName varname_t;       \n    };    \n    \n    template<typename Number, typename VariableName, typename Params>    \n    class reduced_domain_traits<SparseDBM<Number, VariableName, Params>> {\n    public:\n      typedef SparseDBM<Number, VariableName, Params> sdbm_domain_t;\n      typedef typename sdbm_domain_t::variable_t variable_t;\n      typedef typename sdbm_domain_t::linear_constraint_system_t linear_constraint_system_t;\n      \n      static void extract(sdbm_domain_t& dom, const variable_t& x,\n\t\t\t  linear_constraint_system_t& csts, bool only_equalities) {\n\tdom.extract(x, csts, only_equalities);\n      }\n    };\n  \n\n  } // namespace domains\n\n} // namespace crab\n\n#pragma GCC diagnostic pop\n", "meta": {"hexsha": "f577b857bc3c642e5fadde47304f56e7bbe9f4e8", "size": 76080, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/crab/domains/sparse_dbm.hpp", "max_stars_repo_name": "numairmansur/crab", "max_stars_repo_head_hexsha": "316e3946d3a4d92db638c54fbfa8fb7bee1ebbc7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/crab/domains/sparse_dbm.hpp", "max_issues_repo_name": "numairmansur/crab", "max_issues_repo_head_hexsha": "316e3946d3a4d92db638c54fbfa8fb7bee1ebbc7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/crab/domains/sparse_dbm.hpp", "max_forks_repo_name": "numairmansur/crab", "max_forks_repo_head_hexsha": "316e3946d3a4d92db638c54fbfa8fb7bee1ebbc7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.9395465995, "max_line_length": 97, "alphanum_fraction": 0.5420741325, "num_tokens": 18720, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4803761592918205}}
{"text": "#pragma once\n\n/**\n * derived from Springy JS\n * \n * copyright notice below\n */\n/**\n * Springy v2.7.1\n *\n * Copyright (c) 2010-2013 Dennis Hotson\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 <utility>\n#include <functional>\n#include <ostream>\n\n#include <boost/graph/adjacency_list.hpp>\n\n#include \"PopulationGraph.hpp\"\n#include \"Util/Unique.hpp\"\n#include \"Util/NewExceptionType.hpp\"\n\nnamespace pyramid_scheme_simulator {\n\nclass GraphLayout \n{\npublic:\n    NEW_EXCEPTION_TYPE(GraphLayoutException);\n\n    class Vector\n    {\n    public:\n        const double x, y;\n\n        Vector(double, double);\n        Vector(const Vector&);\n        Vector(std::pair<double, double>&);\n\n\n        //scalar functions\n        Vector add(const Vector&) const;\n        Vector subtract(const Vector&) const;\n        Vector multiply(double) const;\n        Vector divide(double) const;\n\n        double magnitude() const;\n        Vector normal() const;\n        Vector normalise() const;\n\n        bool operator==(const Vector&) const;\n        bool operator!=(const Vector&) const;\n\n        static Vector random();\n    };\n\n    using Position = Vector;\n    class Point\n    {\n    public:\n        const Position position;\n        const double mass;\n        const Vector velocity, acceleration;\n\n        Point(Position, double, Vector, Vector);\n        Point(const Point&);\n\n        Point applyForce(const Vector& force) const;\n\n        bool operator==(const Point&) const;\n        bool operator!=(const Point&) const;\n\n        static Point random();\n    };\n\n    class Node;\n\n    struct SpringProperties\n    {\n        double length, springConstant;\n    };\n\n    using Graph = boost::adjacency_list<\n            boost::vecS,\n            boost::vecS, \n            boost::undirectedS,\n            Node,\n            SpringProperties>;\n\n    class Node\n    {\n        std::unique_ptr<Point> pointPtr;\n        std::unique_ptr<Unique> id;\n\n        void setUnique(const Unique&);\n        class NodeCopier;\n\n    public:\n\n        Node();\n        Node(const Unique&);\n        Node(const Unique&, const Point&);\n        Node(const Node&);\n\n        void  setPoint(const Point&);\n        Point getPoint() const;\n\n        Unique getUnique() const { return *id; }\n\n        static NodeCopier getNodeCopier(const Graph&, Graph&);\n\n        std::string print() const;\n    };\n\n\n    //bottom left and top right\n    using BoundingBox = std::pair<Position, Position>;\n\n    class Layout\n    {\n        const double stiffness, \n              repulsion, \n              damping;\n\n        const double minEnergyThreshold;\n        const double maxSpeed;\n\n        std::unique_ptr<Graph> graph;\n\n        //call the function with every point or pair of points \n        //on the graph and replace them with the return value\n        void mutatePoints(std::function<Point(const Point&)>);\n        void mutatePointPairs(std::function<\n                std::pair<Point, Point>(\n                    const Point&, const Point&)>);\n\n        void forEachSpring(\n                std::function<void(Node&, Node&, \n                    double, double)>);\n\n        void forEachPoint(std::function<void(const Point&)>) const;\n\n        double totalEnergy() const;\n\n        void applyCoulombsLaw();\n        void applyHookesLaw();\n        void attractToCenter();\n        void updateVelocity(GraphLayoutTick);\n        void updatePosition(GraphLayoutTick);\n\n        void tick(GraphLayoutTick);\n\n        std::unique_ptr<Graph> runSimulation(GraphLayoutTick*);\n\n        /**\n         * return a spring with default values\n         */\n        SpringProperties newSpring() const;\n\n        void makeGraph(Graph&, const PopulationGraph&);\n\n    public:\n        Layout(const double, \n                const double,\n                const double,\n                const double,\n                const double,\n                const PopulationGraph&);\n        Layout(const Layout&);\n\n        BoundingBox getBoundingBox();\n\n        std::unique_ptr<Graph> copyGraph() const;\n        static std::unique_ptr<Graph> copyGraph(const Graph&);\n\n        std::unique_ptr<Graph> runSimulation();\n        std::unique_ptr<Graph> runSimulation(GraphLayoutTick maxTicks);\n    };\n\nprotected:\n    const std::unique_ptr<GraphLayoutTick> maxTicksPtr;\n    Layout layout;\n\npublic:\n    GraphLayout(\n        const Config::BackendOptions::GLBackendOptions::GraphLayoutOptions&, \n        const PopulationGraph&);\n\n    virtual ~GraphLayout() {}\n\n    std::pair<std::unique_ptr<Graph>, BoundingBox> calculateLayout();\n    //synonym for calculateLayout\n    std::pair<std::unique_ptr<Graph>, BoundingBox> operator()();\n\n    static void printGraphLayout(std::ostream&, Graph&);\n};\n\nclass GraphLayout::Node::NodeCopier\n{\n    const Graph& from;\n    Graph& to;\n\npublic:\n    NodeCopier(const Graph& _from, Graph& _to)\n        : from(_from), to(_to)\n    {}\n\n    void operator()(Graph::vertex_descriptor fromVd, Graph::vertex_descriptor toVd)\n    {\n        to[toVd].setUnique(from[fromVd].getUnique());\n        to[toVd].setPoint(from[fromVd].getPoint());\n    }\n};\n\n}\n", "meta": {"hexsha": "20a0a190355166af206835807fd3745c00350c73", "size": 6073, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/gl/GraphLayout.hpp", "max_stars_repo_name": "tjakway/pyramid-scheme-simulator", "max_stars_repo_head_hexsha": "4de02ac120b39185342f433999c2d360a7ccbf7e", "max_stars_repo_licenses": ["MIT"], "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/gl/GraphLayout.hpp", "max_issues_repo_name": "tjakway/pyramid-scheme-simulator", "max_issues_repo_head_hexsha": "4de02ac120b39185342f433999c2d360a7ccbf7e", "max_issues_repo_licenses": ["MIT"], "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/gl/GraphLayout.hpp", "max_forks_repo_name": "tjakway/pyramid-scheme-simulator", "max_forks_repo_head_hexsha": "4de02ac120b39185342f433999c2d360a7ccbf7e", "max_forks_repo_licenses": ["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.6244725738, "max_line_length": 83, "alphanum_fraction": 0.631483616, "num_tokens": 1281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4803761592918205}}
{"text": "#include \"per_face_prin_curvature.h\"\n#include <igl/per_vertex_normals.h>\n#include <igl/principal_curvature.h>\n#include <igl/avg_edge_length.h>\n#include <igl/massmatrix.h>\n#include <igl/adjacency_list.h>\n#include <igl/per_vertex_normals.h>\n#include <igl/unique_edge_map.h>\n#include <igl/edge_flaps.h>\n#include <igl/barycenter.h>\n#include <igl/parallel_for.h>\n#include <igl/pinv.h>\n#include <Eigen/SparseCore>\n#include <iostream>\nusing namespace std;\n\nvoid per_vertex_signed_prin_curvature(Eigen::MatrixXd & V,Eigen::MatrixXi & F, Eigen::MatrixXd & PD1, Eigen::MatrixXd & PD2, Eigen::VectorXd & PC1, Eigen::VectorXd & PC2){\n    \n    int n = V.rows();\n    int m = F.rows();\n    Eigen::MatrixXi E,uE,EF,EI;\n    std::vector<std::vector<int>> A,uE2E;\n    Eigen::VectorXi EMAP;\n  Eigen::MatrixXd N;\n    std::vector<int> b;\n    Eigen::MatrixXd bary;\n    igl::barycenter(V,F,bary);\n    igl::adjacency_list(F,A);\n   igl::per_vertex_normals(V,F,N);\n   \n   igl::unique_edge_map(F,E,uE,EMAP,uE2E);\n   igl::edge_flaps(F,uE,EMAP,EF,EI);\n    \n    \n    PC1.resize(n);\n    PC2.resize(n);\n    PD1.resize(n,3);\n    PD2.resize(n,3);\n    \n    //std::cout << \"Starting iteration\" << std::endl;\n\n\n    \n    \n    //for (int i=0; i<m; i++) { // For each face\n    igl::parallel_for(V.rows(),[&] (const int i){\n         \n        // Step 1: Find unique combined indeces of all vertices of face\n        // uu = V(unique(u{F(i,1)},u{F(i,2)},u{F(i,3)}),:)\n        // vv = uu-bary(i,:) what is this notation in c++...\n        // Triangle i has edges E.row(i), E.row(i+m), E.row(i+2m)\n        // So incident (repeated) faces are EF(i,0), EF(i,1), EF(i+m,0),\n        // EF(i+m,1), EF(i+2m,0) and EF(i+2m,1);\n        // std::cout << \"entered loop\" << std::endl;\n        std::vector<int> vertex_indeces,v1,v2,v3;\n        std::vector<std::vector<int>> v123;\n        // v123.resize(3);\n        //for(int j = 0; j < 3; j++){\n        //    v123[j].resize(3);\n            // std::cout << \"entered loop\" << std::endl;\n            //std::cout << EF(EMAP(i+(j*m)),0) << std::endl;\n           // std::cout << EF(EMAP(i+(j*m)),1) << std::endl;\n            \n         //   for(int orient = 0; orient < 2; orient++){\n         //       if(EF(EMAP(i+(j*m)),orient) != i){\n                 //   std::cout << \"found one\" << std::endl;\n         //       v123[j].push_back(F(EF(EMAP(i+(j*m)),orient),0));\n         //       v123[j].push_back(F(EF(EMAP(i+(j*m)),orient),1));\n         //       v123[j].push_back(F(EF(EMAP(i+(j*m)),orient),2));\n         //       }\n         //       }\n          //  }\n        // std::cout << \"exited loop\" << std::endl;\n        //v1 = v123[0];\n        //v2 = v123[1];\n        //v3 = v123[2];\n        //assert(v1.size() == 3);\n        //assert(v2.size() == 3);\n        //assert(v3.size() == 3);\n       //  std::cout << \"survived assertions\" << std::endl;\n        \n        Eigen::MatrixXd P;\n        Eigen::Vector3d w,uu,vv;\n        Eigen::VectorXd u,v,b,a;\n        \n        double E,FF,G,e,f,g,det;\n        v1 = A[i];\n        vertex_indeces.insert(vertex_indeces.end(),v1.begin(),v1.end());\n        for (int j = 0; j < v1.size(); j++) {\n            v2 = A[v1[j]];\n            vertex_indeces.insert(vertex_indeces.end(),v2.begin(),v2.end());\n        }\n        sort( vertex_indeces.begin(), vertex_indeces.end() );\n        vertex_indeces.erase( unique( vertex_indeces.begin(), vertex_indeces.end() ), vertex_indeces.end() );\n        int k = vertex_indeces.size();\n        for (int j=0; j<k; j++) {\n            P.conservativeResize(j+1,3);\n            P.row(j) = V.row(vertex_indeces[j]) - bary.row(i);\n        }\n        // END OF STEP 1\n        \n        \n        // Step 2: Build orthonormal basis from N\n        w = N.row(i);\n\n        if (w(2)==-1) {\n            vv(0) = 0;\n            vv(1) = -1;\n            vv(2) = 0;\n            uu(0) = -1;\n            uu(1) = 0;\n            uu(2) = 0;\n        }\n        else{\n            vv(0) = 1-(pow(w(0),2)/(1+w(2)));\n            vv(1) = -w(0)*w(1)/(1+w(2));\n            vv(2) = -w(0);\n            uu(0) = -w(0)*w(1)/(1+w(2));\n            uu(1) = 1-(pow(w(1),2)/(1+w(2)));\n            uu(2) = -w(1);\n        }\n        // END OF STEP 2\n        // STEP 3: PROJECT\n        Eigen::MatrixXd S(3,2);\n        S.col(0) = uu;\n        S.col(1) = vv;\n        u = P*uu;\n        v = P*vv;\n        b = P*w;\n        // END OF STEP 3\n        // STEP 4: FIT QUADRIC\n        Eigen::MatrixXd A2(k,6);\n        Eigen::MatrixXd A2_pseudo(6,k);\n        A2.col(0) = u;\n        A2.col(1) = v;\n        A2.col(2) = u.cwiseProduct(u);\n        A2.col(3) = u.cwiseProduct(v);\n        A2.col(4) = v.cwiseProduct(v);\n        A2.col(5).setOnes();\n        igl::pinv(A2,A2_pseudo);\n        a = A2_pseudo*b;\n        // END OF STEP 4\n        // STEP 5: BUILD SS\n        E = 1+(pow(a(0),2));\n        FF = a(0)*a(1);\n        G = 1+(pow(a(1),2));\n        e = (2*a(2))/sqrt((pow(a(0),2))+1+(pow(a(1),2)));\n        f = (a(3))/sqrt((pow(a(0),2))+1+(pow(a(1),2)));\n        g = (2*a(4))/sqrt((pow(a(0),2))+1+(pow(a(1),2)));\n        Eigen::Matrix2d S1,S2,SS;\n        S1 << e,f,f,g;\n        det = (G*E)-(pow(FF,2));\n        if (det==0) {\n            Eigen::Matrix2d S2_pseudo;\n            S2 << E,FF,FF,G;\n            igl::pinv(S2,S2_pseudo);\n            SS = S1*S2_pseudo;\n            //std::cout << \"Det zero\" << std::endl;\n        }else{\n            S2 << G,-FF,-FF,E;\n            S2 /= det;\n            SS = S1*S2;\n        }\n        // END OF STEP 5\n        // STEP 6: EIGENALALYSIS OF SS\n        // std::cout << \"Before eigensolver\" << std::endl;\n        Eigen::EigenSolver<Eigen::MatrixXd> es(SS);\n        PC1(i) = - es.eigenvalues().real().coeff(0);\n        PC2(i) = - es.eigenvalues().real().coeff(1);\n        if (PC1(i)>PC2(i)) {\n            std::swap(PC1(i),PC2(i));\n            PD1.row(i) = es.eigenvectors().real().coeff(0,1)*uu + es.eigenvectors().real().coeff(1,1)*vv;\n            PD2.row(i) = es.eigenvectors().real().coeff(0,0)*uu + es.eigenvectors().real().coeff(1,0)*vv;\n        }else{\n            PD1.row(i) = es.eigenvectors().real().coeff(0,0)*uu + es.eigenvectors().real().coeff(1,0)*vv;\n            PD2.row(i) = es.eigenvectors().real().coeff(0,1)*uu + es.eigenvectors().real().coeff(1,1)*vv;\n        }\n       // PD1.row(i) = uu;\n       // PD2.row(i) = w;\n        //std::cout << \"Ending iteration\" << std::endl;\n    },0);\n        //\n    //}\n    \n    \n}\n\n\n// g++ -I/usr/local/libigl/external/eigen -I/usr/local/libigl/include -std=c++11 -framework Accelerate main.cpp principal_curvatures_silvia.cpp -o main\n\n", "meta": {"hexsha": "6e4d4ad1a4aae31aa2c799576f1da07e8c0b6651", "size": 6497, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/per_vertex_signed_prin_curvature.cpp", "max_stars_repo_name": "sgsellan/opening-and-closing-surfaces", "max_stars_repo_head_hexsha": "57127178c2e8d50396c02a853c4456a90e9220c5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2020-10-27T00:03:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T19:44:35.000Z", "max_issues_repo_path": "src/per_vertex_signed_prin_curvature.cpp", "max_issues_repo_name": "sgsellan/opening-and-closing-surfaces", "max_issues_repo_head_hexsha": "57127178c2e8d50396c02a853c4456a90e9220c5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/per_vertex_signed_prin_curvature.cpp", "max_forks_repo_name": "sgsellan/opening-and-closing-surfaces", "max_forks_repo_head_hexsha": "57127178c2e8d50396c02a853c4456a90e9220c5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-10-27T01:40:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-23T13:42:16.000Z", "avg_line_length": 34.0157068063, "max_line_length": 171, "alphanum_fraction": 0.4799138064, "num_tokens": 2172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.48037615329414823}}
{"text": "// Copyright (C) 2019 David Harmon and Artificial Necessity\n// This code distributed under zlib, see LICENSE.txt for terms.\n\n#pragma once\n\n#include <iostream>\n#include <Eigen/StdVector>\n\n#include \"energy.hpp\"\n\n\nclass ModifiedConjugateGradient {\npublic:\n    bool compute(const SparseMatrixd& A) {\n        if (A.rows() != A.cols()) {\n            std::cerr << \"Non-square matrix A!\" << std::endl;\n            return false;\n        }\n\n        if (P_.size() != A.rows() / 3) {\n            P_.resize(A.rows() / 3);\n        }\n\n        for (int i=0; i<A.rows(); i+=3) {\n            Mat3d Ai = A.block(i,i,3,3);\n            P_[i/3] = Ai.inverse();\n        }\n        \n        return true;\n    }\n\n    void resize(int nbr) {\n        S_.resize(nbr, Eigen::Matrix3d::Identity());\n    }\n\n    void reset() {\n        for (Eigen::Matrix3d& M : S_) {\n            M.setIdentity();\n        }\n    }\n\n    void setFilter(int idx, const Eigen::Matrix3d& C) {\n        S_[idx] = C;\n    }\n\n    void filterInPlace(Eigen::VectorXd& v) {\n        #pragma omp parallel for\n        for (size_t i=0; i<S_.size(); i++) {\n            v.segment<3>(3*i) = S_[i] * v.segment<3>(3*i);\n        }\n    }\n\n    Eigen::VectorXd filter(const Eigen::VectorXd& v) {\n        Eigen::VectorXd out(v.size());\n        #pragma omp parallel for\n        for (size_t i=0; i<S_.size(); i++) {\n            out.segment<3>(3*i) = S_[i] * v.segment<3>(3*i);\n        }\n        return out;\n    }\n\n    template <typename F, typename Derived>\n    void solve(F multiply, const Eigen::MatrixBase<Derived>& b, Eigen::VectorXd& x) {\n        static double eps = 2.5e-3;\n        static const size_t maxNbrItrs = 1000;\n\n        VecXd r = b - multiply(x); filterInPlace(r);\n        VecXd c(b.size());\n\n        for (int i=0; i<b.size()/3; i++) {\n            c.segment<3>(3*i) = S_[i] * P_[i] * r.segment<3>(3*i);\n        }\n\n        double dNew = r.dot(c);\n        double d0 = dNew;\n\n        double tol = eps * eps * d0;\n\n        size_t nbrItrs = 0;\n        size_t minNbr = 10;\n        while ((dNew > tol || nbrItrs < minNbr) && nbrItrs < maxNbrItrs)\n        {\n            VecXd q = multiply(c); filterInPlace(q);\n            double a = dNew / c.dot(q);\n\n            x.noalias() += a * c;\n            r.noalias() -= a * q;\n            \n            VecXd s(r.size());\n            for (int i=0; i<b.size()/3; i++) {\n                s.segment<3>(3*i) = P_[i] * r.segment<3>(3*i);\n            }\n\n            double dOld = dNew;\n            dNew = r.dot(s);\n\n            c *= dNew / dOld;\n            c.noalias() += s;\n\t    filterInPlace(c);\n\n            nbrItrs++;\n        }\n\n        std::cout << \"CG finished in \" << nbrItrs\n                  << \" iterations with error \" << dNew << \" (\" << tol << \")\" << std::endl;\n    }\n\n    const Eigen::Matrix3d& S(int idx) {\n        return S_[idx];\n    }\n\nprotected:\n    std::vector<Eigen::Matrix3d, Eigen::aligned_allocator<Eigen::Matrix3d>> P_;\n    std::vector<Eigen::Matrix3d, Eigen::aligned_allocator<Eigen::Matrix3d>> S_;\n};\n\n\n", "meta": {"hexsha": "0a87753ccb08ca03420ea5c32284509a9ecf33e4", "size": 2989, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/conjugate_gradient.hpp", "max_stars_repo_name": "liuwei792966953/stitch", "max_stars_repo_head_hexsha": "108e3dbd3410331c741c7cb166f93bbffa11b369", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-23T05:20:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-23T05:20:09.000Z", "max_issues_repo_path": "include/conjugate_gradient.hpp", "max_issues_repo_name": "liuwei792966953/stitch", "max_issues_repo_head_hexsha": "108e3dbd3410331c741c7cb166f93bbffa11b369", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/conjugate_gradient.hpp", "max_forks_repo_name": "liuwei792966953/stitch", "max_forks_repo_head_hexsha": "108e3dbd3410331c741c7cb166f93bbffa11b369", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.3305084746, "max_line_length": 90, "alphanum_fraction": 0.4897959184, "num_tokens": 858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4803437845622503}}
{"text": "/*\nThis file is a part of Raman-Scattering-Code-Conversion.\n<https://github.com/Kirbologist/Raman-Scattering-Code-Conversion>\n\nWritten by Siwan Li for the UQ School of Maths and Physics.\nBased on the SMARTIES MATLAB package by W.R.C. Somerville, B. Augui\u00e9, E.C. Le Ru\nCopyright (C) 2021-2022 Siwan Li\n\nThis source code form is subject to the terms of the MIT License.\nIf a copy of the MIT License was not distributed with this file,\nyou can obtain one at <https://opensource.org/licenses/MIT>.\n\n\nThis code contains all 'rvh' SMARTIES functions that are used in Raman scattering calculations,\ni.e. T-matrix related functions specific to particles with mirror-reflection symmetry.\nHenceforth, such symmetry shall be called rvh symmetry.\n*/\n\n#ifndef RVH_HPP\n#define RVH_HPP\n\n#include \"core.hpp\"\n#include \"sph.hpp\"\n#include \"vsh.hpp\"\n#include \"misc.hpp\"\n#include <Eigen/SVD>\n\nusing namespace Eigen;\nusing namespace std;\n\nnamespace Smarties {\n\n  /* Struct containing vectors of expansion coefficients of the multipole expansions of a set of electric fields */\n  template <class Real>\n  struct stAbcdnm {\n    // Scattering field coefficients\n    ArrayXc<Real> p_nm;\n    ArrayXc<Real> q_nm;\n    // Incident field coefficients\n    ArrayXc<Real> a_nm;\n    ArrayXc<Real> b_nm;\n    // Internal field coefficients\n    ArrayXc<Real> c_nm;\n    ArrayXc<Real> d_nm;\n  };\n\n  /* Struct containing orientation-averaged cross-sections for various wavelengths*/\n  template <class Real>\n  struct stCrossSection {\n    ArrayXr<Real> C_ext; // Wavelength-dependent extinction coefficients\n    ArrayXr<Real> C_sca; // Wavelength-dependent scattering coefficients\n    ArrayXr<Real> C_abs; // Wavelength-dependent absorption coefficients\n  };\n\n\n  /*\n  Calculate T (and possibly R) matrices from P, Q matrices, for scatterers with a plane of symmetry.\n  This makes use of block inversion. See sec. 4.5 and eq. 70 in JQSRT2013 for details.\n  Inputs:\n    st_PQ_list - std::vector of size M, each element of which contains a unique pointer to an stPQ struct\n                 (one entry for each m in abs_m_vec), and which makes use of the rvh symmetry\n    get_R - if true, R is computed and returned\n  Output:\n    A std::vector of size M of unique pointers to stTR structs.\n  Dependencies:\n    InvertLUcol\n  */\n  template <class Real>\n  vector<unique_ptr<stTR<Real>>> rvhGetTRfromPQ(vector<unique_ptr<stPQ<Real>>>& st_PQ_list, bool get_R = false) {\n    // Note that all matrix inversions uses LU decomposition with partial pivoting of the columns\n    int num_entries = st_PQ_list.size();\n    vector<unique_ptr<stTR<Real>>> output(num_entries);\n    for (int i = 0; i < num_entries; i++) {\n      output[i] = make_unique<stTR<Real>>();\n      // Get blocks of P and Q matrices\n      unique_ptr<stPQ<Real>>& st_PQ = st_PQ_list[i];\n      unique_ptr<stTR<Real>>& st_TR = output[i];\n      // Get blocks of P_eo and Q_eo matrices\n      MatrixXc<Real> P11_ee = st_PQ->st_4M_P_eo().M11;\n      MatrixXc<Real> P12_eo = st_PQ->st_4M_P_eo().M12;\n      MatrixXc<Real> P21_oe = st_PQ->st_4M_P_eo().M21;\n      MatrixXc<Real> P22_oo = st_PQ->st_4M_P_eo().M22;\n      MatrixXc<Real> Q11_ee = st_PQ->st_4M_Q_eo().M11;\n      MatrixXc<Real> Q12_eo = st_PQ->st_4M_Q_eo().M12;\n      MatrixXc<Real> Q21_oe = st_PQ->st_4M_Q_eo().M21;\n      MatrixXc<Real> Q22_oo = st_PQ->st_4M_Q_eo().M22;\n\n      // Get blocks of P_oe and Q_oe matrices\n      MatrixXc<Real> P11_oo = st_PQ->st_4M_P_oe().M11;\n      MatrixXc<Real> P12_oe = st_PQ->st_4M_P_oe().M12;\n      MatrixXc<Real> P21_eo = st_PQ->st_4M_P_oe().M21;\n      MatrixXc<Real> P22_ee = st_PQ->st_4M_P_oe().M22;\n      MatrixXc<Real> Q11_oo = st_PQ->st_4M_Q_oe().M11;\n      MatrixXc<Real> Q12_oe = st_PQ->st_4M_Q_oe().M12;\n      MatrixXc<Real> Q21_eo = st_PQ->st_4M_Q_oe().M21;\n      MatrixXc<Real> Q22_ee = st_PQ->st_4M_Q_oe().M22;\n\n      int num_even = Q11_ee.rows();\n      int num_odd = Q11_oo.rows();\n      ArrayXi ind1_eo = st_PQ->st_4M_Q_eo().ind1;\n      ArrayXi ind2_eo = st_PQ->st_4M_Q_eo().ind2;\n      ArrayXi ind1_oe = st_PQ->st_4M_Q_oe().ind1;\n      ArrayXi ind2_oe = st_PQ->st_4M_Q_oe().ind2;\n\n      int m = st_PQ->st_4M_P_eo().m;\n\n      // m == 0 case is done separately, since M12 and M21 are empty.\n      if (!m) {\n        st_TR->st_4M_R_oe().M11 = InvertLUcol(Q11_oo);\n        st_TR->st_4M_T_oe().M11 = -P11_oo * st_TR->st_4M_R_oe().M11.matrix();\n        st_TR->st_4M_R_oe().M22 = InvertLUcol(Q22_ee);\n        st_TR->st_4M_T_oe().M22 = -P22_ee * st_TR->st_4M_R_oe().M22.matrix();\n        st_TR->st_4M_R_eo().M11 = InvertLUcol(Q11_ee);\n        st_TR->st_4M_T_eo().M11 = -P11_ee * st_TR->st_4M_R_eo().M11.matrix();\n        st_TR->st_4M_R_eo().M22 = InvertLUcol(Q22_oo);\n        st_TR->st_4M_T_eo().M22 = -P22_oo * st_TR->st_4M_R_eo().M22.matrix();\n\n        st_TR->st_4M_T_eo().M12 = ArrayXXc<Real>::Zero(num_even, num_odd);\n        st_TR->st_4M_T_eo().M21 = ArrayXXc<Real>::Zero(num_odd, num_even);\n        st_TR->st_4M_T_oe().M12 = ArrayXXc<Real>::Zero(num_odd, num_even);\n        st_TR->st_4M_T_oe().M21 = ArrayXXc<Real>::Zero(num_even, num_odd);\n\n        if (get_R) {\n          st_TR->st_4M_R_eo().M12 = ArrayXXc<Real>::Zero(num_even, num_odd);\n          st_TR->st_4M_R_eo().M21 = ArrayXXc<Real>::Zero(num_odd, num_even);\n          st_TR->st_4M_R_oe().M12 = ArrayXXc<Real>::Zero(num_odd, num_even);\n          st_TR->st_4M_R_oe().M21 = ArrayXXc<Real>::Zero(num_even, num_odd);\n        }\n      } else { // Do inversion using JQSRT2013 eq. 70\n\n        // For M_eo matrices\n        MatrixXc<Real> Q11_inv = InvertLUcol(Q11_ee);\n\n        MatrixXc<Real> G1 = P11_ee * Q11_inv;\n        MatrixXc<Real> G3 = P21_oe * Q11_inv;\n        MatrixXc<Real> G5 = Q21_oe * Q11_inv;\n        MatrixXc<Real> F2_m1 = Q22_oo - G5 * Q12_eo;\n        MatrixXc<Real> F2 = InvertLUcol(F2_m1);\n\n        MatrixXc<Real> G2 = P22_oo * F2;\n        MatrixXc<Real> G4 = P12_eo * F2;\n        MatrixXc<Real> G6 = Q12_eo * F2;\n\n        st_TR->st_4M_T_eo().M12 = G1 * G6 - G4;\n        st_TR->st_4M_T_eo().M22 = G3 * G6 - G2;\n        st_TR->st_4M_T_eo().M11 = -G1 - st_TR->st_4M_T_eo().M12.matrix() * G5;\n        st_TR->st_4M_T_eo().M21 = -G3 - st_TR->st_4M_T_eo().M22.matrix() * G5;\n\n        if (get_R) {\n          st_TR->st_4M_R_eo().M12 = -Q11_inv * G6;\n          st_TR->st_4M_R_eo().M22 = F2;\n          st_TR->st_4M_R_eo().M11 = Q11_inv - st_TR->st_4M_R_eo().M12.matrix() * G5;\n          st_TR->st_4M_R_eo().M21 = -st_TR->st_4M_R_eo().M22.matrix() * G5;\n        }\n\n        // For M_oe matrices\n        Q11_inv = InvertLUcol(Q11_oo);\n\n        G1 = P11_oo * Q11_inv;\n        G3 = P21_eo * Q11_inv;\n        G5 = Q21_eo * Q11_inv;\n        F2_m1 = Q22_ee - G5 * Q12_oe;\n        F2 = InvertLUcol(F2_m1);\n\n        G2 = P22_ee * F2;\n        G4 = P12_oe * F2;\n        G6 = Q12_oe * F2;\n\n        st_TR->st_4M_T_oe().M12 = G1 * G6 - G4;\n        st_TR->st_4M_T_oe().M22 = G3 * G6 - G2;\n        st_TR->st_4M_T_oe().M11 = -G1 - st_TR->st_4M_T_oe().M12.matrix() * G5;\n        st_TR->st_4M_T_oe().M21 = -G3 - st_TR->st_4M_T_oe().M22.matrix() * G5;\n\n        if (get_R) {\n          st_TR->st_4M_R_oe().M12 = -Q11_inv * G6;\n          st_TR->st_4M_R_oe().M22 = F2;\n          st_TR->st_4M_R_oe().M11 = Q11_inv - st_TR->st_4M_R_oe().M12.matrix() * G5;\n          st_TR->st_4M_R_oe().M21 = -st_TR->st_4M_R_oe().M22.matrix() * G5;\n        }\n      }\n\n      st_TR->st_4M_T_eo().m = st_TR->st_4M_T_oe().m = m;\n      st_TR->st_4M_T_eo().ind1 = ind1_eo;\n      st_TR->st_4M_T_eo().ind2 = ind2_eo;\n      st_TR->st_4M_T_oe().ind1 = ind1_oe;\n      st_TR->st_4M_T_oe().ind2 = ind2_oe;\n      st_TR->mat_list.push_back(\"st_4M_T\");\n\n      if (get_R) {\n        st_TR->st_4M_R_eo().m = st_TR->st_4M_R_oe().m = m;\n        st_TR->st_4M_R_eo().ind1 = ind1_eo;\n        st_TR->st_4M_R_eo().ind2 = ind2_eo;\n        st_TR->st_4M_R_oe().ind1 = ind1_oe;\n        st_TR->st_4M_R_oe().ind2 = ind2_oe;\n        st_TR->mat_list.push_back(\"st_4M_R\");\n      }\n    }\n    return output;\n  }\n\n  /*\n  Truncate P and Q matrices in st_mat_list such that the maximum number of multipoles N is now N_max.\n  This also removes values of m that are larger than N_max.\n  This function works on st_mat_list which makes use of rvh symmetry.\n  Inputs:\n    st_mat_list - a vector of unique pointers to stPQ structs, with one entry for each m of abs_m_vec.\n    N_max - The maximum value of N (and m) that is desired in the output.\n  Output:\n    returns a deep copy of the same st_mat_list vector, but where all M11, M12, M21 and M22 members\n    have been truncated to N = N_max and values of m > N_max are removed.\n  Dependencies:\n    LogicalIndices\n  */\n  template <class Real>\n  vector<unique_ptr<stPQ<Real>>> rvhTruncateMatrices(const vector<unique_ptr<stPQ<Real>>>& st_mat_list, int N_max) {\n    vector<unique_ptr<stPQ<Real>>> output;\n    int num_entries = st_mat_list.size();\n    for (int i = 0 ; i < num_entries; i++) {\n      int num_st_4M = st_mat_list[i]->mat_list.size() * 2; // Count how many matrices in the struct are defined\n      int m;\n      if (num_st_4M > 0 && (m = st_mat_list[i]->st_4M_list[0].m) <= N_max) {\n        auto output_st_TR = make_unique<stPQ<Real>>();\n        output_st_TR->mat_list = st_mat_list[i]->mat_list;\n        for (int j = 0; j < num_st_4M; j++) {\n          int new_size = N_max - max(1, m);\n          ArrayXb ind1_valid = st_mat_list[i]->st_4M_list[j].ind1 <= new_size;\n          ArrayXb ind2_valid = st_mat_list[i]->st_4M_list[j].ind2 <= new_size;\n\n          ArrayXi new_ind1 = LogicalIndices(ind1_valid);\n          ArrayXi new_ind2 = LogicalIndices(ind2_valid);\n\n          output_st_TR->st_4M_list[j].ind1 = st_mat_list[i]->st_4M_list[j].ind1(new_ind1);\n          output_st_TR->st_4M_list[j].ind2 = st_mat_list[i]->st_4M_list[j].ind2(new_ind2);\n          output_st_TR->st_4M_list[j].m = m;\n\n          ArrayXXc<Real> current_matrix = st_mat_list[i]->st_4M_list[j].M11;\n          output_st_TR->st_4M_list[j].M11 = current_matrix(new_ind1, new_ind1);\n          current_matrix = st_mat_list[i]->st_4M_list[j].M12;\n          output_st_TR->st_4M_list[j].M12 = current_matrix(new_ind1, new_ind2);\n          current_matrix = st_mat_list[i]->st_4M_list[j].M21;\n          output_st_TR->st_4M_list[j].M21 = current_matrix(new_ind2, new_ind1);\n          current_matrix = st_mat_list[i]->st_4M_list[j].M22;\n          output_st_TR->st_4M_list[j].M22 = current_matrix(new_ind2, new_ind2);\n        }\n        output.push_back(move(output_st_TR));\n      }\n    }\n    return output;\n  }\n\n  /*\n  Truncate T and R matrices in st_mat_list such that the maximum number of multipoles N is now N_max.\n  This also removes values of m that are larger than N_max.\n  This function works on st_mat_list which makes use of rvh symmetry.\n  Inputs:\n    st_mat_list - a vector of unique pointers to stTR structs, with one entry for each m of abs_m_vec.\n    N_max - The maximum value of N (and m) that is desired in the output.\n  Output:\n    returns a deep copy of the same st_mat_list vector, but where all M11, M12, M21 and M22 members\n    have been truncated to N = N_max and values of m > N_max are removed.\n  Dependencies:\n    LogicalIndices\n  */\n  template <class Real>\n  vector<unique_ptr<stTR<Real>>> rvhTruncateMatrices(const vector<unique_ptr<stTR<Real>>>& st_mat_list, int N_max) {\n    vector<unique_ptr<stTR<Real>>> output;\n    int num_entries = st_mat_list.size();\n    for (int i = 0 ; i < num_entries; i++) {\n      int num_st_4M = st_mat_list[i]->mat_list.size() * 2; // Count how many matrices in the struct are defined\n      int m;\n      if (num_st_4M > 0 && (m = st_mat_list[i]->st_4M_list[0].m) <= N_max) {\n        auto output_st_TR = make_unique<stTR<Real>>();\n        output_st_TR->mat_list = st_mat_list[i]->mat_list;\n        for (int j = 0; j < num_st_4M; j++) {\n          int new_size = N_max - max(1, m);\n          ArrayXb ind1_valid = st_mat_list[i]->st_4M_list[j].ind1 <= new_size;\n          ArrayXb ind2_valid = st_mat_list[i]->st_4M_list[j].ind2 <= new_size;\n\n          ArrayXi new_ind1 = LogicalIndices(ind1_valid);\n          ArrayXi new_ind2 = LogicalIndices(ind2_valid);\n\n          output_st_TR->st_4M_list[j].ind1 = st_mat_list[i]->st_4M_list[j].ind1(new_ind1);\n          output_st_TR->st_4M_list[j].ind2 = st_mat_list[i]->st_4M_list[j].ind2(new_ind2);\n          output_st_TR->st_4M_list[j].m = m;\n\n          ArrayXXc<Real> current_matrix = st_mat_list[i]->st_4M_list[j].M11;\n          output_st_TR->st_4M_list[j].M11 = current_matrix(new_ind1, new_ind1);\n          current_matrix = st_mat_list[i]->st_4M_list[j].M12;\n          output_st_TR->st_4M_list[j].M12 = current_matrix(new_ind1, new_ind2);\n          current_matrix = st_mat_list[i]->st_4M_list[j].M21;\n          output_st_TR->st_4M_list[j].M21 = current_matrix(new_ind2, new_ind1);\n          current_matrix = st_mat_list[i]->st_4M_list[j].M22;\n          output_st_TR->st_4M_list[j].M22 = current_matrix(new_ind2, new_ind2);\n        }\n        output.push_back(move(output_st_TR));\n      }\n    }\n    return output;\n  }\n\n  /*\n  Symmetrises the matrices given in mat_list, and leaves other matrices present in st_mat_list unchanged.\n  Uses the upper triangular matrices to deduce the lower triangular parts from the symmetry relations\n  of the T-matrix obtained from eqs. 5.34 and 5.37 of [Mishchenko 2002], i.e.\n  T11 = T11.transpose(), T22 = T22.transpose(), T12 = -T21.transpose(), T21 = -T12.transpose()\n  This function assumes rvh symmetry. While the original MATLAB code could theoretically work with P and Q matrices,\n  the implementation here only works with T and R matrices, although it's intended only for T and R matrices anyway.\n  Inputs:\n    st_mat_list - a std::vector containing unique pointers to stTR structs containing\n                  T (and possibly R) matrices to symmetrise\n    mat_list - a std::vector of strings specifying which structs are to be symmetrised\n  Outputs:\n    A deep copy of st_mat_list, but with all the desired matrices symmetrised.\n  */\n  template <class Real>\n  vector<unique_ptr<stTR<Real>>> rvhGetSymmetricMat(const vector<unique_ptr<stTR<Real>>>& st_mat_list,\n      vector<string> mat_list = {\"st_4M_T\"}) {\n    enum parity {EO, OE, END};\n    int num_entries = st_mat_list.size();\n    vector<unique_ptr<stTR<Real>>> output(num_entries);\n\n    for (int i = 0; i < num_entries; i++) {\n      output[i] = make_unique<stTR<Real>>(*(st_mat_list[i])); // Make a deep copy at the ith entry of st_mat_list\n      int num_st_4M = mat_list.size();\n      for (int j = 0; j < num_st_4M; j++) {\n        for (int k = EO; k != END; k++) { // Symmetrise eo matrix, then oe matrix\n          st4M<Real>* st_4M;\n          if (mat_list[j] == \"st_4M_T\") {\n            if (k == EO)\n              st_4M = &(output[i]->st_4M_T_eo());\n            else if (k == OE)\n              st_4M = &(output[i]->st_4M_T_oe());\n          } else if (mat_list[j] == \"st_4M_R\") {\n            if (k == EO)\n              st_4M = &(output[i]->st_4M_R_eo());\n            else if (k == OE)\n              st_4M = &(output[i]->st_4M_R_oe());\n          } else\n            continue;\n          ArrayXi ind1 = st_4M->ind1;\n          ArrayXi ind2 = st_4M->ind2;\n\n          if (ind1.size() && ind2.size()) { // Check that neither two are empty\n            int offset12 = (ind2(0) - ind1(0) + 1)/2;\n            // int offset21 = 1 - offset12;\n\n            // Upper triangular without diagonal\n            MatrixXc<Real> upper = st_4M->M11.matrix().template triangularView<StrictlyUpper>();\n            // Diagonal only\n            MatrixXc<Real> diag = static_cast<VectorXc<Real>>(st_4M->M11.matrix().diagonal()).asDiagonal();\n            st_4M->M11 = (upper + diag + upper.transpose()).array(); // Symmtrised matrix\n\n            upper = st_4M->M22.matrix().template triangularView<StrictlyUpper>();\n            diag = static_cast<VectorXc<Real>>(st_4M->M22.matrix().diagonal()).asDiagonal();\n            st_4M->M22 = (upper + diag + upper.transpose()).array();\n\n            // In either case, the transpose of upper2 complements upper1\n            MatrixXc<Real> upper1, upper2;\n            if (offset12) {\n              upper1 = st_4M->M12.matrix().template triangularView<StrictlyUpper>();\n              upper2 = st_4M->M21.matrix().template triangularView<Upper>();\n            } else {\n              upper1 = st_4M->M12.matrix().template triangularView<Upper>();\n              upper2 = st_4M->M21.matrix().template triangularView<StrictlyUpper>();\n            }\n            st_4M->M12 = (upper1 - upper2.transpose()).array(); // Symmetrised matrix\n            st_4M->M21 = -st_4M->M12.transpose(); // Symmetrised matrix\n          }\n        }\n      }\n    }\n\n    return output;\n  }\n\n  /*\n  Calculates the field expansion coefficients from the T/R-matrices for a given incident plane wave\n  (for one wavelength only). If R is not defined in st_TR_list, then the internal fields are not computed.\n  If stIncEabnm is given, the expansion coefficients for the incident wave are not recalculated.\n  This method is valid for scatterers with rvh symmetry.\n\n  If st_TR_list contains m values that are not required, then they are ignored.\n  Inputs:\n    N_max - the maximum multipole order to use in the expansions\n            (should be less than or equal to the T-matrix size)\n    st_TR_list - std::vector of size M containing unique pointers to stTR structs for each m.\n                 This should contain all m present in st_inc_par.abs_m_vec, i.e. all m where |m| <= N,\n                 and should make use of the rvh symmetry.\n    st_inc_par - A struct containing information about the incident field, as from vshMakeIncidentParams.\n    st_inc_E_abmm - A struct containing the expansion coefficients a_nm and b_nm of the incident wave.\n                    These are recalculated if not provided.\n  Output:\n    returns a stAbcdnm struct containing all the calculated expansion coefficients.\n    The case where n = 0 and m = 0 is included for padding, so every vector in the struct has size\n    P = (N_max + 1)^2. The padding exists to simplify the indexing.\n    c_nm and d_nm are only defined if R is defined in st_TR_list.\n  Dependencies:\n    Seq2Array, LogicalSlice, vshGetIncidentCoefficients\n  */\n  template <class Real>\n  unique_ptr<stAbcdnm<Real>> rvhGetFieldCoefficients(int N_max,\n      const vector<unique_ptr<stTR<Real>>>& st_TR_list, const unique_ptr<stIncPar<Real>>& st_inc_par,\n      unique_ptr<stIncEabnm<Real>> st_inc_E_abnm = unique_ptr<stIncEabnm<Real>>()) {\n\n    // Coeff of incident wave\n    if (!st_inc_E_abnm)\n      st_inc_E_abnm = vshGetIncidentCoeffs(N_max, st_inc_par);\n\n    bool get_R = false;\n    if (find(st_TR_list[0]->mat_list.begin(), st_TR_list[0]->mat_list.end(), \"st_4M_R\")\n        != st_TR_list[0]->mat_list.end())\n      get_R = true;\n\n    // Truncate to relevant m's\n    ArrayXb abs_m_vec_valid = st_inc_par->abs_m_vec <= N_max;\n    ArrayXi abs_m_vec = LogicalSlice(st_inc_par->abs_m_vec, abs_m_vec_valid);\n\n    int num_M = st_TR_list.size(); // number of m-values in T, not all of which may be needed\n    int M = abs_m_vec.size();\n    int P_max = (N_max + 1)*(N_max + 1); // number of (n,m) coupled indices (with (0,0) included as padding)\n\n    ArrayXc<Real> a_nm = st_inc_E_abnm->a_nm; // [P X 1]\n    ArrayXc<Real> b_nm = st_inc_E_abnm->b_nm; // [P X 1]\n    ArrayXc<Real> p_nm = ArrayXc<Real>::Zero(P_max); // [P X 1]\n    ArrayXc<Real> q_nm = ArrayXc<Real>::Zero(P_max); // [P X 1]\n    ArrayXc<Real> c_nm = ArrayXc<Real>::Zero(get_R ? P_max : 1); // if get_R, [P X 1]\n    ArrayXc<Real> d_nm = ArrayXc<Real>::Zero(get_R ? P_max : 1); // if get_R, [P X 1]\n    ArrayXi m_ind_for_T(M);\n\n    // Find the corresponding m-indices in st_TR_list (in case they are not in standard order)\n    for (int m_ind11 = 0; m_ind11 < M; m_ind11++) {\n      for (int m_ind = 0; m_ind < num_M; m_ind++) {\n        if (st_TR_list[m_ind]->st_4M_T_eo().m == abs_m_vec(m_ind11)) {\n          m_ind_for_T(m_ind11) = m_ind;\n          break;\n        }\n      }\n    }\n\n    for (int m_ind11 = 0; m_ind11 < M; m_ind11++) {\n      int m_ind = m_ind_for_T(m_ind11);\n      int m = abs_m_vec(m_ind11);\n      int N_min = max(m, 1);\n\n      ArrayXi n_vec_e = Seq2Array(N_min + (N_min % 2), N_max, 2); // indices for even n [N_e X 1]\n      ArrayXi n_vec_o = Seq2Array(N_min + 1 - (N_min % 2), N_max, 2); // indices for odd n [N_o X 1]\n\n      ArrayXi p_vec_e = n_vec_e * (n_vec_e + 1) + m; // [N_e X 1]\n      ArrayXi p_vec_o = n_vec_o * (n_vec_o + 1) + m; // [N_o X 1]\n      ArrayXi n_vec_T_e = ArrayXi::LinSpaced(n_vec_e.size(), 0, n_vec_e.size() - 1);\n      ArrayXi n_vec_T_o = ArrayXi::LinSpaced(n_vec_o.size(), 0, n_vec_o.size() - 1);\n\n      VectorXc<Real> p_nm_e = st_TR_list[m_ind]->st_4M_T_eo().M11(n_vec_T_e, n_vec_T_e).matrix() *\n          a_nm(p_vec_e).matrix() + st_TR_list[m_ind]->st_4M_T_eo().M12(n_vec_T_e, n_vec_T_o).matrix() *\n          b_nm(p_vec_o).matrix();\n      VectorXc<Real> q_nm_o = st_TR_list[m_ind]->st_4M_T_eo().M21(n_vec_T_o, n_vec_T_e).matrix() *\n          a_nm(p_vec_e).matrix() + st_TR_list[m_ind]->st_4M_T_eo().M22(n_vec_T_o, n_vec_T_o).matrix() *\n          b_nm(p_vec_o).matrix();\n      VectorXc<Real> p_nm_o = st_TR_list[m_ind]->st_4M_T_oe().M11(n_vec_T_o, n_vec_T_o).matrix() *\n          a_nm(p_vec_o).matrix() + st_TR_list[m_ind]->st_4M_T_oe().M12(n_vec_T_o, n_vec_T_e).matrix() *\n          b_nm(p_vec_e).matrix();\n      VectorXc<Real> q_nm_e = st_TR_list[m_ind]->st_4M_T_oe().M21(n_vec_T_e, n_vec_T_o).matrix() *\n          a_nm(p_vec_o).matrix() + st_TR_list[m_ind]->st_4M_T_oe().M22(n_vec_T_e, n_vec_T_e).matrix() *\n          b_nm(p_vec_e).matrix();\n\n      for (int i = 0; i < n_vec_e.size(); i++) {\n        p_nm(p_vec_e(i)) = p_nm_e(i);\n        q_nm(p_vec_e(i)) = q_nm_e(i);\n      }\n      for (int i = 0; i < n_vec_o.size(); i++) {\n        p_nm(p_vec_o(i)) = p_nm_o(i);\n        q_nm(p_vec_o(i)) = q_nm_o(i);\n      }\n\n      if (get_R) {\n        VectorXc<Real> c_nm_e = st_TR_list[m_ind]->st_4M_R_eo().M11(n_vec_T_e, n_vec_T_e).matrix() *\n            a_nm(p_vec_e).matrix() + st_TR_list[m_ind]->st_4M_R_eo().M12(n_vec_T_e, n_vec_T_o).matrix() *\n            b_nm(p_vec_o).matrix();\n        VectorXc<Real> d_nm_o = st_TR_list[m_ind]->st_4M_R_eo().M21(n_vec_T_o, n_vec_T_e).matrix() *\n            a_nm(p_vec_e).matrix() + st_TR_list[m_ind]->st_4M_R_eo().M22(n_vec_T_o, n_vec_T_o).matrix() *\n            b_nm(p_vec_o).matrix();\n        VectorXc<Real> c_nm_o = st_TR_list[m_ind]->st_4M_R_oe().M11(n_vec_T_o, n_vec_T_o).matrix() *\n            a_nm(p_vec_o).matrix() + st_TR_list[m_ind]->st_4M_R_oe().M12(n_vec_T_o, n_vec_T_e).matrix() *\n            b_nm(p_vec_e).matrix();\n        VectorXc<Real> d_nm_e = st_TR_list[m_ind]->st_4M_R_oe().M21(n_vec_T_e, n_vec_T_o).matrix() *\n            a_nm(p_vec_o).matrix() + st_TR_list[m_ind]->st_4M_R_oe().M22(n_vec_T_e, n_vec_T_e).matrix() *\n            b_nm(p_vec_e).matrix();\n\n        for (int i = 0; i < n_vec_e.size(); i++) {\n          c_nm(p_vec_e(i)) = c_nm_e(i);\n          d_nm(p_vec_e(i)) = d_nm_e(i);\n        }\n        for (int i = 0; i < n_vec_o.size(); i++) {\n          c_nm(p_vec_o(i)) = c_nm_o(i);\n          d_nm(p_vec_o(i)) = d_nm_o(i);\n        }\n      }\n\n      // Calculate for m < 0\n      if (m) {\n        ArrayXi p_vec_n_e = n_vec_e * (n_vec_e + 1) - m; // [N_e X 1]\n        ArrayXi p_vec_n_o = n_vec_o * (n_vec_o + 1) - m; // [N_e X 1]\n\n        // For negative m, using eq. 5.37 of [Mishchenko 2002]\n        VectorXc<Real> p_nm_n_e = st_TR_list[m_ind]->st_4M_T_eo().M11(n_vec_T_e, n_vec_T_e).matrix() *\n            a_nm(p_vec_n_e).matrix() - st_TR_list[m_ind]->st_4M_T_eo().M12(n_vec_T_e, n_vec_T_o).matrix() *\n            b_nm(p_vec_n_o).matrix();\n        VectorXc<Real> q_nm_n_o = -st_TR_list[m_ind]->st_4M_T_eo().M21(n_vec_T_o, n_vec_T_e).matrix() *\n            a_nm(p_vec_n_e).matrix() + st_TR_list[m_ind]->st_4M_T_eo().M22(n_vec_T_o, n_vec_T_o).matrix() *\n            b_nm(p_vec_n_o).matrix();\n        VectorXc<Real> p_nm_n_o = st_TR_list[m_ind]->st_4M_T_oe().M11(n_vec_T_o, n_vec_T_o).matrix() *\n            a_nm(p_vec_n_o).matrix() - st_TR_list[m_ind]->st_4M_T_oe().M12(n_vec_T_o, n_vec_T_e).matrix() *\n            b_nm(p_vec_n_e).matrix();\n        VectorXc<Real> q_nm_n_e = -st_TR_list[m_ind]->st_4M_T_oe().M21(n_vec_T_e, n_vec_T_o).matrix() *\n            a_nm(p_vec_n_o).matrix() + st_TR_list[m_ind]->st_4M_T_oe().M22(n_vec_T_e, n_vec_T_e).matrix() *\n            b_nm(p_vec_n_e).matrix();\n\n        for (int i = 0; i < n_vec_e.size(); i++) {\n          p_nm(p_vec_n_e(i)) = p_nm_n_e(i);\n          q_nm(p_vec_n_e(i)) = q_nm_n_e(i);\n        }\n        for (int i = 0; i < n_vec_o.size(); i++) {\n          p_nm(p_vec_n_o(i)) = p_nm_n_o(i);\n          q_nm(p_vec_n_o(i)) = q_nm_n_o(i);\n        }\n\n        if (get_R) {\n          VectorXc<Real> c_nm_n_e = st_TR_list[m_ind]->st_4M_R_eo().M11(n_vec_T_e, n_vec_T_e).matrix() *\n              a_nm(p_vec_n_e).matrix() - st_TR_list[m_ind]->st_4M_R_eo().M12(n_vec_T_e, n_vec_T_o).matrix() *\n              b_nm(p_vec_n_o).matrix();\n          VectorXc<Real> d_nm_n_o = -st_TR_list[m_ind]->st_4M_R_eo().M21(n_vec_T_o, n_vec_T_e).matrix() *\n              a_nm(p_vec_n_e).matrix() + st_TR_list[m_ind]->st_4M_R_eo().M22(n_vec_T_o, n_vec_T_o).matrix() *\n              b_nm(p_vec_n_o).matrix();\n          VectorXc<Real> c_nm_n_o = st_TR_list[m_ind]->st_4M_R_oe().M11(n_vec_T_o, n_vec_T_o).matrix() *\n              a_nm(p_vec_n_o).matrix() - st_TR_list[m_ind]->st_4M_R_oe().M12(n_vec_T_o, n_vec_T_e).matrix() *\n              b_nm(p_vec_n_e).matrix();\n          VectorXc<Real> d_nm_n_e = -st_TR_list[m_ind]->st_4M_R_oe().M21(n_vec_T_e, n_vec_T_o).matrix() *\n              a_nm(p_vec_n_o).matrix() + st_TR_list[m_ind]->st_4M_R_oe().M22(n_vec_T_e, n_vec_T_e).matrix() *\n              b_nm(p_vec_n_e).matrix();\n\n          for (int i = 0; i < n_vec_e.size(); i++) {\n            c_nm(p_vec_n_e(i)) = c_nm_n_e(i);\n            d_nm(p_vec_n_e(i)) = d_nm_n_e(i);\n          }\n          for (int i = 0; i < n_vec_o.size(); i++) {\n            c_nm(p_vec_n_o(i)) = c_nm_n_o(i);\n            d_nm(p_vec_n_o(i)) = d_nm_n_o(i);\n          }\n        }\n      }\n    }\n\n    auto output = make_unique<stAbcdnm<Real>>();\n    output->p_nm = p_nm; // [P X 1]\n    output->q_nm = q_nm; // [P X 1]\n    output->a_nm = a_nm; // [P X 1]\n    output->b_nm = b_nm; // [P X 1]\n    output->c_nm = c_nm; // if get_R, [P X 1]\n    output->d_nm = d_nm; // if get_R, [P X 1]\n    return output;\n  }\n\n  /*\n  Calculate absorption, scattering and extinction cross sections, for the case of orientationally-averaged incidence.\n  This is for matrices which make use of rvh symmetry.\n  Inputs:\n    k1 - wavevector [L X 1]\n    st_TR_list - std::vector containing unique pointers to stTR structs (in rvh-block form).\n                 Should be [L X M] and should contain all m where 0 <= m <= N\n  Output:\n    Returns a stCrossSection struct, where each member is of size [L X 1] and\n    contains information for each wavelength.\n  Dependencies:\n    mp_pi\n  */\n  template <class Real>\n  unique_ptr<stCrossSection<Real>> rvhGetAverageCrossSections(\n      const ArrayXr<Real>& k1, const vector<vector<unique_ptr<stTR<Real>>>>& st_TR_list) {\n    int L = st_TR_list.size();\n    int M = st_TR_list[0].size();\n\n    ArrayXc<Real> ext_sum = ArrayXc<Real>::Zero(L);\n    ArrayXc<Real> sca_sum = ArrayXc<Real>::Zero(L);\n\n    for (int l = 0; l < L; l++) { // Loop on lambda\n      if (st_TR_list[l][0]->st_4M_T_eo().ind1.size() + st_TR_list[l][0]->st_4M_T_eo().ind2.size() + 1 != M)\n        cout << \"Warning in rvhGetAverageCrossSections: \" <<\n            \"st_TR_list does not seem to contain T-matrices for all m\" << endl;\n      for (int m = 0; m < M; m++) {\n        if (st_TR_list[l][m]->st_4M_T_eo().m != m || st_TR_list[l][m]->st_4M_T_oe().m != m)\n          cout << \"Warning in rvhGetAverageCrossSections: \" <<\n              \"st_TR_list does not seem to contain T-matrices for all m\" << endl;\n        Real m_factor = m ? 1 : 0.5;\n\n        // From eq. 5.107 of Mishchenko 2002\n        ext_sum(l) += m_factor * (\n            st_TR_list[l][m]->st_4M_T_eo().M11.matrix().diagonal().sum() +\n            st_TR_list[l][m]->st_4M_T_oe().M11.matrix().diagonal().sum() +\n            st_TR_list[l][m]->st_4M_T_eo().M22.matrix().diagonal().sum() +\n            st_TR_list[l][m]->st_4M_T_oe().M22.matrix().diagonal().sum());\n\n        // From eq. 5.141 of Mishchenko 2002\n        sca_sum(l) += m_factor * (\n            st_TR_list[l][m]->st_4M_T_eo().M11.abs().pow(2).sum() +\n            st_TR_list[l][m]->st_4M_T_eo().M12.abs().pow(2).sum() +\n            st_TR_list[l][m]->st_4M_T_eo().M21.abs().pow(2).sum() +\n            st_TR_list[l][m]->st_4M_T_eo().M22.abs().pow(2).sum() +\n            st_TR_list[l][m]->st_4M_T_oe().M11.abs().pow(2).sum() +\n            st_TR_list[l][m]->st_4M_T_oe().M12.abs().pow(2).sum() +\n            st_TR_list[l][m]->st_4M_T_oe().M21.abs().pow(2).sum() +\n            st_TR_list[l][m]->st_4M_T_oe().M22.abs().pow(2).sum());\n      }\n    }\n\n    auto output = make_unique<stCrossSection<Real>>();\n    output->C_ext = -4*mp_pi<Real>()/k1.pow(2) * ext_sum.real(); // [L X 1]\n    output->C_sca = 4*mp_pi<Real>()/k1.pow(2) * sca_sum.real(); // [L X 1]\n    output->C_abs = -4*mp_pi<Real>()/k1.pow(2) * (ext_sum.real() + sca_sum.real()); // [L X 1]\n\n    return output;\n  }\n\n  /*\n  Finds an estimate for delta by studying the convergence of the T^{22,m=1}_{11} matrix element.\n  Delta + 1 is the NQ for which this element has reached convergence.\n  See JQSRT 160, 29 *2015) for further details. Also returns the estimated converged precision.\n  Inputs:\n    st_geometry - unique pointer to struct containing geometric information, as from sphMakeGeometry\n    params - unique pointer to struct containing simulation parameters (only the first lambda is considered)\n    NQ_max - maximum number of multipoles\n  Output:\n    Returns a struct containing an estimate for delta and estimated converged precision.\n    If delta still could not be found, it returns output->delta = 0 and output->err = NaN.\n  Dependencies:\n    rvhGetTRfromPQ, rvhTruncateMatrices, sphCalculatePQ\n  */\n  template <class Real>\n  stDelta<Real> sphEstimateDelta(const unique_ptr<stRtfunc<Real>>& st_geometry,\n      const unique_ptr<stParams<Real>>& params, int NQ_max = 80) {\n    stDelta<Real> output;\n    Real min_acc = 1e-4;\n    ArrayXi abs_m_vec = ArrayXi::Ones(1); // only one m\n\n    // This works on only one wavelength, so we choose the largest k1 * s as representative of the worst case.\n    // Find max and min relative refractive index\n    int max_ind;\n    (params->k1 * params->s).maxCoeff(&max_ind);\n    auto param1 = make_unique<stParams<Real>>();\n    param1->s = ArrayXr<Real>::Constant(1, params->s(max_ind));\n    param1->k1 = ArrayXr<Real>::Constant(1, params->k1(max_ind));\n\n    // Number of pointer used for linear fit to check if error has reached a plateau\n    int N_for_conv = 5;\n    MatrixXr<Real> A_fit(N_for_conv, 2);\n    A_fit.col(0) = VectorXr<Real>::Ones(N_for_conv);\n    A_fit.col(1) = VectorXr<Real>::LinSpaced(N_for_conv, 1, N_for_conv);\n    // Store errors\n    ArrayXr<Real> T_2211_err = ArrayXr<Real>::Zero((NQ_max + 1)/2);\n    // Calculate P,Q matrices\n    vector<unique_ptr<stPQ<Real>>> st_PQ_list = sphCalculatePQ(NQ_max, abs_m_vec, st_geometry, param1, NQ_max);\n    complex<Real> T_2211 = complex<Real>(0.0, 0.0);\n\n    for (int N = 1; N <= NQ_max; N += 2) { // Loop over truncation (only odd numbers)\n      // Truncate P,Q to N and get corresponding T\n      int n_count = (N - 1)/2; // Expression is always mathematically an integer\n      vector<unique_ptr<stPQ<Real>>> trunc_st_PQ_list = rvhTruncateMatrices(st_PQ_list, N);\n      vector<unique_ptr<stTR<Real>>> st_TR_list = rvhGetTRfromPQ(trunc_st_PQ_list, false);\n      complex<Real> T_2211_new = st_TR_list[0]->st_4M_T_eo().M22(0, 0);\n\n      // Relative error\n      T_2211_err(n_count) = abs(T_2211/T_2211_new - static_cast<complex<Real>>(1));\n\n      T_2211 = T_2211_new;\n      // Minimum requirement for convergence\n      if (n_count >= N_for_conv && T_2211_err(n_count) < min_acc) {\n        // Then test if the last N_for_conv errors have flattened out by a\n        // linear regression to the last N_for_conv points\n        VectorXr<Real> b_vec = log10(abs(T_2211_err(seq(n_count - N_for_conv + 1, n_count))));\n        MatrixXr<Real> coeff = A_fit.bdcSvd(ComputeThinU | ComputeThinV).solve(b_vec);\n        Real slope = coeff(1);\n        // if slope < 0, then still converging\n        if (slope > -0.5) { // this means less than one digit better over 2*N_for_conv steps\n          output.delta = N - 2*N_for_conv + 2; // N = 2*n_count - 1 > 2*N_for_conv - 1\n          output.err = (T_2211_err(seq(n_count - N_for_conv + 1, n_count))).mean();\n          return output;\n        }\n      }\n    }\n    output.delta = -1;\n    output.err = 0;\n    return output;\n  }\n}\n\n#endif\n", "meta": {"hexsha": "8f855495e05369b56bc1e794d4860b6bf400a747", "size": 32644, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/rvh.hpp", "max_stars_repo_name": "Kirbologist/Raman-Scattering-Code-Conversion", "max_stars_repo_head_hexsha": "118a08238a2525f595c4b7d2b735dd37852fac6f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-09T12:41:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-09T12:41:22.000Z", "max_issues_repo_path": "src/rvh.hpp", "max_issues_repo_name": "Kirbologist/Raman-Scattering-Code-Conversion", "max_issues_repo_head_hexsha": "118a08238a2525f595c4b7d2b735dd37852fac6f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/rvh.hpp", "max_forks_repo_name": "Kirbologist/Raman-Scattering-Code-Conversion", "max_forks_repo_head_hexsha": "118a08238a2525f595c4b7d2b735dd37852fac6f", "max_forks_repo_licenses": ["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.9022988506, "max_line_length": 117, "alphanum_fraction": 0.6334395295, "num_tokens": 10650, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.5926665999540697, "lm_q1q2_score": 0.48034378456225024}}
{"text": "#define CATCH_CONFIG_MAIN\n\n#include \"CALPHADConcSolverTernary.h\"\n#include \"CALPHADFreeEnergyFunctionsTernary.h\"\n#include \"CALPHADFunctions.h\"\n#include \"CALPHADSpeciesPhaseGibbsEnergy.h\"\n#include \"PhysicalConstants.h\"\n\n#include \"catch.hpp\"\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 <iostream>\n\nnamespace pt = boost::property_tree;\n\nTEST_CASE(\"CALPHAD ternary solver\", \"[ternary solver]\")\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        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    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    double hphi   = 0.5;\n    double c0     = 0.33;\n    double c1     = 0.33;\n\n    Thermo4PFM::CALPHADConcSolverTernary solver;\n    solver.setup(c0, c1, hphi, RTinv, L_AB_L, L_AC_L, L_BC_L, L_AB_S, L_AC_S,\n        L_BC_S, L_ABC_L, L_ABC_S, fA, fB, fC);\n\n    int nits = solver.ComputeConcentration(sol, 1.e-8, 50);\n\n    std::cout << \"Solution = \" << sol[0] << \",\" << sol[1] << \",\" << sol[2]\n              << \",\" << sol[3] << std::endl;\n    double ref_sol[4] = { 0.339215, 0.356739, 0.320785, 0.303261 };\n\n    CHECK(sol[0] == Approx(ref_sol[0]).margin(1.e-6));\n    CHECK(sol[1] == Approx(ref_sol[1]).margin(1.e-6));\n    CHECK(sol[2] == Approx(ref_sol[2]).margin(1.e-6));\n    CHECK(sol[3] == Approx(ref_sol[3]).margin(1.e-6));\n\n    std::cout << \"nits=\" << nits << std::endl;\n}\n", "meta": {"hexsha": "d9578ab60614d326647b7fe74cd7c076531482a9", "size": 6654, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tests/testCALPHADConcSolverTernary.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": "tests/testCALPHADConcSolverTernary.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": "tests/testCALPHADConcSolverTernary.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": 33.4371859296, "max_line_length": 78, "alphanum_fraction": 0.607754734, "num_tokens": 2273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.48034377913612497}}
{"text": "/*\n * hcost_tile_library.h\n *\n *  Created on: Feb 23, 2016\n *      Author: bscooper\n */\n\n#ifndef HCOST_TILE_LIBRARY_HPP\n#define HCOST_TILE_LIBRARY_HPP\n\n#include <iostream>\n#include <list>\n#include <vector>\n#include <cmath>\n#include <map>\n#include <algorithm>\n#include <iterator>\n#include <memory>\n#include <functional>\n#include <eigen3/Eigen/Dense>\n#include <eigen3/Eigen/SparseCore>\n//#include <eigen3/Eigen/Core>\n//#include <Eigen/Sparse>\n\nnamespace librav {\nconst double PI = 3.141592653589793;\nconst double T_INFINITY = 1.0e9;\nconst double TOL = 1.0e-9;\n// Largest value of H considered\nconst unsigned short int MAX_H = 5;\n// Minimum and Maximum speed considered\nconst unsigned int SPD_MIN = 1;\nconst unsigned int SPD_MAX = 1;\n\nconst int N_CBTA_W_SOL = 51;\nconst int N_CBTA_W = 101;\n// const double r_min = 2;\n// // double r_min = 0.0;\n\nstruct REGION_BD{\n\t\tstd::vector<double> region_w_lower;    //REGION_BD(0,:)\n\t\tstd::vector<double> region_w_upper;    //REGION_BD(1,:)\n\t\tstd::vector<double> region_psi_lower;  //REGION_BD(2,:)\n\t\tstd::vector<double> region_psi_upper;  //REGION_BD(3,:)\n\t\tstd::vector<double> region_vel_lower;  //REGION_BD(4,:)\n\t\tstd::vector<double> region_vel_upper;  //REGION_BD(5,:)\n\t};\n\n\nclass TileBlock; // say TileBlock exists without defining it, forward declaration\n\t\t\t\t // so that Tile can declare it's instance of a TileBlock\n// =============================== Tile ===================================\n/* Each Tile with channel_data, cell_vertices, traversal_type,\n * cell_xform, traversal_faces, cell_edges, and connectivity\n */\nclass Tile{\npublic:\n\tTile(int H, Eigen::Matrix<int,Eigen::Dynamic,4> tile_vertices);\n\t~Tile();\n\nprivate:\n\t// Tile class Transition and transformation references\n\tEigen::Matrix<int,12,5> FACE_REF;\n\tEigen::Matrix<int,5,4> VERTICES_PERMUTATION;\n\t//VectorXi INVERSE_XFORM(5);\n\tEigen::Matrix<int,5,1> INVERSE_XFORM;\n\npublic:\n\n\tEigen::Matrix<int,Eigen::Dynamic,4> channel_data;\n\tEigen::Matrix<double,4,Eigen::Dynamic> cell_vertices;\n\tEigen::Matrix<int,Eigen::Dynamic,1> traversal_type;\n\tEigen::Matrix<int,Eigen::Dynamic,2> cell_xform;\n\tEigen::Matrix<int,Eigen::Dynamic,1> traversal_faces;\n\tEigen::Matrix<double,Eigen::Dynamic,4> cell_edge;\n\n\tstd::shared_ptr<TileBlock> tile_block;\n\n\tstd::shared_ptr<Eigen::SparseMatrix<int,Eigen::RowMajor>> connectivity;\n\n\tvoid set_tile_data(int, Eigen::Matrix<int,Eigen::Dynamic,4>);\n\n\tvoid addTileBlock(REGION_BD &region_bd, std::shared_ptr<TileBlock> this_tile, int H);\n};\n\n// =============================== TileBlock ==============================\n/* A TileBlock is associated with a Tile. TileBlock is responsible for the\n * Curvature Bounded Traversability Analysis (CBTA), and this information\n * is used in the edge costs calculations needed by the Lifted Graph\n * transition function. TileBlock needs access to it's associated Tile's\n * data: channel_data, cell_vertices, ...\n */\nclass TileBlock{\npublic:\n\tTileBlock();\n\tTileBlock(REGION_BD &region_bd, std::shared_ptr<Tile> linked_tile, int Hin);\n\t~TileBlock();\nprivate:\n\tint H;\n\tEigen::Matrix<double,Eigen::Dynamic,1> y_exit;\n\tEigen::Matrix<double,Eigen::Dynamic,1> z_exit;\n\n\tEigen::Matrix<double,Eigen::Dynamic,N_CBTA_W> bta_smp; //Matrix<double,Dynamic,N_CBTA_W>\n\n\tEigen::Matrix<double,Eigen::Dynamic,N_CBTA_W_SOL> alfa_sol;\n\tEigen::Matrix<double,Eigen::Dynamic,N_CBTA_W> alfa_smp;\n\n\tEigen::Matrix<double,Eigen::Dynamic,N_CBTA_W> w_smp;\n\tEigen::Matrix<double,Eigen::Dynamic,N_CBTA_W> x_smp;\npublic:\n\tEigen::Matrix<double,Eigen::Dynamic,N_CBTA_W> alfa;\n\tEigen::Matrix<double,Eigen::Dynamic,N_CBTA_W> bta;\n\tEigen::Matrix<double,Eigen::Dynamic,1> w_lower;\n\tEigen::Matrix<double,Eigen::Dynamic,1> w_upper;\n\tEigen::Matrix<double,Eigen::Dynamic,N_CBTA_W> x;\n\tEigen::Matrix<double,Eigen::Dynamic,N_CBTA_W> w;\n\tEigen::Matrix<double,Eigen::Dynamic,N_CBTA_W_SOL> w_sol;\n\n\n\tstd::shared_ptr<Tile> tile;\n\n\n\npublic:\n\tvoid cbta(double r_min);\n\tvoid cbra(int idx_r_from,REGION_BD &theRegion,double r_min,\n\t\t\t\tlong int N_REGION_TOTAL, Eigen::RowVectorXi& region_target_2,\n\t//\t\t\tMatrix<int,1,Dynamic>& returnMatrix);\n\t\t\t\tEigen::RowVectorXi& region_neighbors);\n\tstatic int find_sample(Eigen::RowVectorXd& ySmp, double y);\n\nprivate:\n\tvoid cbta_s1(double w, double d,\n\t\t\t     //Matrix<double,1,N_CBTA_W>& xSmp,\n\t\t\tEigen::RowVectorXd& xSmp,\n\t\t\tEigen::Matrix<double,2,N_CBTA_W>& btaSmp,\n\t\t\tEigen::Matrix<double,2,1>& returnMatrix,\n\t\t\tdouble r_min);\n\n\tvoid cbta_s2(double w, double d,\n\t\t\t     //Matrix<double,1,N_CBTA_W>& xSmp,\n\t\t\tEigen::RowVectorXd& xSmp,\n\t\t\tEigen::Matrix<double,2,N_CBTA_W>& btaSmp,\n\t\t\tEigen::Matrix<double,2,1>& returnMatrix,\n\t\t\tdouble r_min);\n\n\tvoid interp_broken_seg(Eigen::RowVectorXd& x_data,\n\t\t\tEigen::Matrix<double,2,Eigen::Dynamic>& y_data,\n\t\t\tEigen::RowVectorXd& x_interp,\n\t\t\tEigen::Matrix<double,2,Eigen::Dynamic>& y_interp);\n\ttemplate <typename Derived1, typename Derived2>\n\tvoid remove_inf_values(Eigen::MatrixBase<Derived1>& v,\n\t\t\tEigen::MatrixBase<Derived2>& returnMatrix);\n\n//\tint find_sample(Matrix<double,1,N_CBTA_W>& ySmp, double y);\n\n\n\t//double sign_func(double x);\n\ttemplate <typename Derived_a, typename Derived_b>\n\tvoid find_zeros(Eigen::MatrixBase<Derived_a>& fSmp,\n\t\t\tEigen::MatrixBase<Derived_b>& returnMatrix);\n//\tvoid find_zeros(Matrix<double,1,Dynamic>& fSmp,\n//\t\t\tMatrix<int,1,Dynamic>& returnMatrix);\n\n\tdouble pi2pi(double x);\n\n};\n\n\n\n// ================================ Hlevel =================================\n/* HcostTileLibrary contains Hlevel's H1, H2, ....\n * Each Hlevel contains a map of Tiles with channel_data, cell_vertices, traversal_type,\n * cell_xform, traversal_faces, cell_edges, and connectivity\n */\nclass Hlevel{\npublic:\n\tHlevel(unsigned int Hin);\n\t~Hlevel();\n\npublic:\n\tunsigned int H;\n\tstd::map<unsigned int, std::shared_ptr<Tile>> Tiles; // tiles associated with particular Hlevel\n\tvoid get_tile_data(void);\n\tvoid add_tile(std::shared_ptr<Tile> newTile);\n\tunsigned int n_tiles;\n\tEigen::Matrix<int,Eigen::Dynamic,Eigen::Dynamic> unique_tiles;\n\n\n};\n\nstruct TileTraversalData{\n\tstd::map<unsigned int,std::shared_ptr<Hlevel>> Hlevels;\n\tREGION_BD region_bd;\n\tint N_REGION_W;\n\tint N_REGION_PSI;\n\tint N_REGION_SPD;\n\tint N_REGION_TOTAL;\n};\n\n\n} /* namespace srcl */\n\n#endif /* HCOST_TILE_LIBRARY_HPP */\n", "meta": {"hexsha": "3004afc7671c021f06ca51e478cf68191168f20a", "size": 6190, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/cbta/include/cbta/hcost_tile_library.hpp", "max_stars_repo_name": "jfangwpi/decentralized_route_planning", "max_stars_repo_head_hexsha": "a31cfd1f092e43ff3b7ea2b79c516881babbbb1f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-02-07T13:39:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-23T04:26:30.000Z", "max_issues_repo_path": "src/cbta/include/cbta/hcost_tile_library.hpp", "max_issues_repo_name": "jfangwpi/decentralized_route_planning", "max_issues_repo_head_hexsha": "a31cfd1f092e43ff3b7ea2b79c516881babbbb1f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cbta/include/cbta/hcost_tile_library.hpp", "max_forks_repo_name": "jfangwpi/decentralized_route_planning", "max_forks_repo_head_hexsha": "a31cfd1f092e43ff3b7ea2b79c516881babbbb1f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-15T08:34:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-20T13:10:34.000Z", "avg_line_length": 30.1951219512, "max_line_length": 96, "alphanum_fraction": 0.7176090468, "num_tokens": 1721, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.5926665999540697, "lm_q1q2_score": 0.48034377913612497}}
{"text": "/* type definitions for monte carlo simulation */\n\n/*\n * HISTORY\n * 16-Oct-88 Jeffrey Trull (jt1j) at Carnegie-Mellon University\n *       Created\n */\n\n/* note: in actual fact I am typing this in, 30 years later, from a paper copy,\n * and being a bit inexact about it\n */\n\n#ifndef MONTE_HPP\n#define MONTE_HPP\n\n#include <boost/units/cmath.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/units/systems/si.hpp>\n#include <boost/units/systems/si/codata/universal_constants.hpp>\n#include <boost/units/systems/si/codata/electron_constants.hpp>\n#include <boost/units/systems/si/codata/electromagnetic_constants.hpp>\n\n#include <boost/accumulators/numeric/functional.hpp>\n\n// Accumulators don't like Boost.Units for various reasons\n// but as usual there are customization points we can use to fix things\n// I will do one as a training exercise but if writing this for others\n// I would probably write a single-purpose custom accumulator of my own...\n\nnamespace boost { namespace numeric\n{\n// teach Accumulators how to produce a value of \"one\" for double/float times\n// as the default weight for our time-weighted average velocity\n// It shouldn't be necessary for the calculation since we will always supply a weight...\n\n// specialize one<>\ntemplate<typename Float>\nstruct one<boost::units::quantity<boost::units::si::time, Float>>\n{\n    using type = one;\n    using value_type = boost::units::quantity<boost::units::si::time, Float>;\n    static value_type const value;\n\n    operator value_type const & () const\n    {\n        throw std::runtime_error(\"we should never get here\");\n        return one::value;\n    }\n};\n\ntemplate<typename Float>\nboost::units::quantity<boost::units::si::time, Float> const\none<boost::units::quantity<boost::units::si::time, Float>>::value =\n    Float{1.0} * boost::units::si::second;\n\n}}\n\nnamespace monte {\n\nusing namespace boost::units::si;\n\n// constants\nconstexpr double two_pi   = boost::math::constants::two_pi<double>();\nconstexpr double     pi   = boost::math::constants::pi<double>();\nconstexpr auto   echarge  = constants::codata::e;\nconstexpr auto   dirac    = constants::codata::hbar;\nconstexpr auto   T        = 300.0 * kelvin;  // room temperature\nconstexpr auto   cm       = 0.01 * meter;\nconstexpr auto   angstrom = 1e-10 * meter;\n\n/*\n * evaluate the constant of proportionality between the acoustic\n * scattering rate and the square root of the electron energy\n */\nconstexpr auto   eV = echarge * volt;\nconstexpr auto   g  = 10e-3 * kilogram;\nconstexpr auto   cm3 = cm*cm*cm;\n\n// properties of GaAs\nconstexpr auto   E1 = 7.0 * eV;            // Acoustic deformation potential\nconstexpr auto   rho = 5.37 * g / cm3;     // Crystal density\nconstexpr auto   u = 5.2E5 * cm / second;  // speed of sound in GaAs\nconstexpr double meff = 0.063; // effective electron mass in gamma (000) valley (unitless)\n\n// Shur 2-3-12 as modified by assignment (terms after gamma^1/2 removed)\nconstexpr auto scatter_const =\n    // units for this initial constant not given in Shur :-/\n    0.449E18 * ((g / cm3) * (cm / second) * (cm / second) /\n                (kelvin * eV * eV * sqrt(eV) * second)) *\n    std::pow(meff, 1.5) * T * (E1*E1) /\n    (rho * (u*u)) ;\n\n/*\n * evaluate the accelerations due to the constant electric field\n * between collisions\n */\nconstexpr auto Efield = 10000.0 * volt / cm;\nconstexpr auto accel_const = echarge * Efield / dirac ;\n\n/*\n * evaluate k-to-velocity conversion constant\n */\n\n// The instantaneous velocity (in real space) is the gradient of E with respect to k\n// The Shur book seems to suggest calculating initial and final energies from a given timestep\n// then assuming a straight line between. Here I am just using the instantaneous value,\n// which is wrong.\nconstexpr auto   m_e       = constants::codata::m_e;   // electron mass\n// If E(k) = (dirac^2 * k^2)/(2 * m_eff), and v = (1/dirac) * dE(k)/dt, then\n// v(k) = dirac * k / m_eff\nconstexpr auto   vel_const = dirac/(meff * m_e) ;\n\n// types\n\ntemplate<typename Float>\nstruct vector_str {\n    vector_str() = default;\n    boost::units::quantity<wavenumber, Float> x, y, z;\n\n    // the energy associated with this k state\n    boost::units::quantity<energy, Float> get_energy() const;\n\n    // new set of k resulting from a collision\n    vector_str\n    collision_result(Float theta_r, Float phi_r) const;\n\n};\n\ntemplate<typename Float>\nusing vector_ptr = vector_str<Float> *;\n\ntemplate<typename Float>\nusing vector_cptr = vector_str<Float> const *;\n\n// utility functions\n\n/* k to energy conversion */\ntemplate<typename Float>\nboost::units::quantity<energy, Float>\nvector_str<Float>::get_energy() const\n/*\n * This appears to be very complicated and depends on which region\n * of reciprocal lattice space the electron currently occupies.\n * To make this tractable I'm assuming a parabolic relationship\n * given by E(k) = (dirac^2 * k^2)/(2 * m_eff)\n * See Shur p14.\n */\n{\n    constexpr auto C = (dirac * dirac) / (2.0 * meff * m_e) ;\n\n    boost::units::quantity<energy> nrg = C * ((x * x) + (y * y) + (z * z));\n\n    // returning above calculation directly gets a compile error\n    // but we can explicitly convert it to another (possibly lower) precision *shrug*\n    return boost::units::quantity<energy, Float>{nrg};\n\n}\n\ntemplate<typename Float>\nvector_str<Float>\nvector_str<Float>::collision_result(Float theta_r, Float phi_r) const\n{\n    using namespace boost::units;\n\n    // calculate our current spherical angles\n    using angle = quantity<si::plane_angle, Float>;\n    angle phi{atan(y/x)};\n    angle theta{atan(sqrt(x*x + y*y)/z)};\n    // and our current rho (radius)\n    // total crystal momentum is preserved\n    quantity<si::wavenumber, Float> total_k{sqrt(x*x + y*y + z*z)};\n\n    // determine momentum components if original vector were Z axis aligned:\n    vector_str<Float> k2prime;\n    k2prime.x = total_k * sin(theta_r) * cos(phi_r);\n    k2prime.y = total_k * sin(theta_r) * sin(phi_r);\n    k2prime.z = total_k * cos(theta_r);\n\n    // rotate to reflect actual initial angles and return\n    vector_str<Float> lastk;\n    lastk.x = cos(phi) * cos(theta) * k2prime.x\n        + cos(phi) * sin(theta) * k2prime.z\n        - sin(phi) * k2prime.y;\n\n    lastk.y = sin(phi) * cos(theta) * k2prime.x\n        + sin(phi) * sin(theta) * k2prime.z\n        + cos(phi) * k2prime.y;\n\n    lastk.z = cos(theta) * k2prime.z - sin(theta) * k2prime.x;\n\n    return lastk;\n}\n\n}\n\n#endif // MONTE_HPP\n", "meta": {"hexsha": "7569e51938643291f2f799a8df8695936fa06a5c", "size": 6403, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "monte.hpp", "max_stars_repo_name": "jefftrull/ee851-montecarlo", "max_stars_repo_head_hexsha": "5df7bcf4295ab81da29d5cb4a83d007e85dc2be1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "monte.hpp", "max_issues_repo_name": "jefftrull/ee851-montecarlo", "max_issues_repo_head_hexsha": "5df7bcf4295ab81da29d5cb4a83d007e85dc2be1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "monte.hpp", "max_forks_repo_name": "jefftrull/ee851-montecarlo", "max_forks_repo_head_hexsha": "5df7bcf4295ab81da29d5cb4a83d007e85dc2be1", "max_forks_repo_licenses": ["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.5025380711, "max_line_length": 94, "alphanum_fraction": 0.6851475871, "num_tokens": 1695, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789040926008, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.48034377642306236}}
{"text": "#include <armadillo>\n\n#include \"settings.h\"\n#include \"RigidAlignment.h\"\n\n#include \"landmark/LandmarkIO.h\"\n\n#include \"mesh/MeshIO.h\"\n#include \"mesh/Mesh.h\"\n#include \"mesh/MeshNeighbors.h\"\n#include \"mesh/MeshNeighborsIO.h\"\n#include \"mesh/MeshOneRingNeighborsBuilder.h\"\n#include \"mesh/MeshGeodesicNeighborsBuilder.h\"\n#include \"mesh/MeshSphericalNeighborsBuilder.h\"\n#include \"mesh/MeshResolution.h\"\n\n#include \"mesh/MeshSmooth.h\"\n\n#include \"optimization/matchtemplate/Energy.h\"\n#include \"optimization/matchtemplate/EnergyMinimizer.h\"\n#include \"optimization/matchtemplate/MinimizerSettings.h\"\n\nint main(int argc, char* argv[]) {\n\n  Settings settings(argc, argv);\n\n  // read input data\n  Mesh source = MeshIO::read(settings.source);\n  Mesh target = MeshIO::read(settings.target);\n\n  if( settings.performRigidAlignment == true) {\n\n    source = RigidAlignment(source, target, settings).perform();\n\n  }\n\n  // deal with target meshes that do not provide normals\n  if( settings.fixedNeighbors == false && target.has_normals() == false ) {\n\n    // try to estimate normals if the mesh has faces\n    if( target.has_faces() == true ) {\n      NormalEstimation estimation(target);\n      target.set_vertex_normals(estimation.compute());\n    } // end if\n    else {\n      // use point-to-point distance measure\n      settings.energySettings.searchStrategy =\n        matchTemplate::EnergySettings::SearchStrategy::BASIC;\n    } // end else\n\n  } // end if\n\n  MeshResolution resolution(source);\n\n  arma::vec min, max;\n\n  source.get_bounding_box(min, max);\n\n  const double scaleFactor = 1. / arma::norm( max - min );\n\n  settings.energySettings.maxDistance  *= scaleFactor;\n  settings.energySettings.searchRadius *= scaleFactor;\n\n  MeshNeighbors neighbors;\n\n  if( settings.meshNeighborhoodPresent == true ) {\n    neighbors = MeshNeighborsIO::read(settings.meshNeighborhood);\n  }\n  else {\n    MeshOneRingNeighborsBuilder builder(source);\n    neighbors = neighbors + builder.get_neighbors();\n\n    if( settings.addGeodesic == true ) {\n\n      MeshGeodesicNeighborsBuilder builder(\n        source, resolution.get_resolution() * settings.geodesicNeighborhoodSize);\n      neighbors = neighbors + builder.get_neighbors();\n\n    }\n\n    if( settings.addSpherical == true ) {\n\n      MeshSphericalNeighborsBuilder builder(\n        source, resolution.get_resolution() * settings.sphericalNeighborhoodSize);\n      neighbors = neighbors + builder.get_neighbors();\n\n    }\n  }\n\n  for( arma::vec& vertex: source.get_vertices() ) {\n    vertex *= scaleFactor;\n  }\n\n  for( arma::vec& vertex: target.get_vertices() ) {\n    vertex *= scaleFactor;\n  }\n\n  matchTemplate::EnergyData data(source, neighbors, target);\n\n  if(settings.landmarksPresent == true) {\n    data.landmarks = LandmarkIO::read(settings.landmarks);\n\n    for( Landmark& mark: data.landmarks ) {\n\n      mark.targetPosition *= scaleFactor;\n\n    }\n\n  }\n\n  settings.energySettings.weights[\"dataTerm\"] = 1;\n  settings.energySettings.weights[\"smoothnessTerm\"] = settings.smoothnessTermWeight;\n  settings.energySettings.weights[\"postSmoothnessTerm\"] = settings.postSmoothnessTermWeight;\n  settings.energySettings.changeFactors[\"smoothnessTerm\"] = settings.smoothnessTermChange;\n  settings.energySettings.weights[\"landmarkTerm\"] = settings.landmarkTermWeight;\n  settings.energySettings.changeFactors[\"landmarkTerm\"] = settings.landmarkTermChange;\n\n  matchTemplate::Energy energy(data, settings.energySettings);\n\n  matchTemplate::EnergyMinimizer minimizer(energy, settings.minimizerSettings);\n\n  minimizer.minimize();\n\n  for( arma::vec& vertex: energy.derived_data().source.get_vertices() ) {\n    vertex /= scaleFactor;\n  }\n\n  Mesh result = energy.derived_data().source;\n\n  // remove normals\n  result.get_vertex_normals().clear();\n\n  MeshSmooth(result).apply(settings.meshSmoothIterations);\n\n  MeshIO::write(result, settings.output);\n\n  return 0;\n\n}\n", "meta": {"hexsha": "8fd48f5c9e3d67afb91bd87180e9e6ab5dd13938", "size": 3855, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "match-template/src/bin/main.cpp", "max_stars_repo_name": "ahewer/mri-shape-tools", "max_stars_repo_head_hexsha": "4268499948f1330b983ffcdb43df62e38ca45079", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "match-template/src/bin/main.cpp", "max_issues_repo_name": "ahewer/mri-shape-tools", "max_issues_repo_head_hexsha": "4268499948f1330b983ffcdb43df62e38ca45079", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-05-29T09:43:01.000Z", "max_issues_repo_issues_event_max_datetime": "2017-05-29T09:50:05.000Z", "max_forks_repo_path": "match-template/src/bin/main.cpp", "max_forks_repo_name": "ahewer/mri-shape-tools", "max_forks_repo_head_hexsha": "4268499948f1330b983ffcdb43df62e38ca45079", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2017-05-17T11:56:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-05T09:12:24.000Z", "avg_line_length": 27.5357142857, "max_line_length": 92, "alphanum_fraction": 0.7276264591, "num_tokens": 868, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788995148792, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4803437737099996}}
{"text": "/* \n * File:   hamiltonian.hpp\n * Copyright (C) 2013-2014  K M Masum Habib <masum.habib@gmail.com>\n *\n * Created on April 6, 2013, 5:52 PM\n * \n * Description: Tight binding calculation logic and data.\n * \n */\n\n#ifndef HAMILTONIAN_HPP\n#define\tHAMILTONIAN_HPP\n\n#include <boost/serialization/string.hpp>\n#include <boost/serialization/access.hpp>\n\n#include \"maths/constants.h\"\n#include \"maths/arma.hpp\"\n#include \"atoms/AtomicStruct.h\"\n#include \"utils/vout.h\"\n#include \"utils/std.hpp\"\n\nnamespace quest{\nnamespace hamiltonian{\n\nusing namespace utils::stds;\nusing utils::Printable;\nusing namespace maths::armadillo;\nusing atoms::AtomicStruct;\nusing atoms::PeriodicTable;\nusing namespace maths::spvec;\nusing namespace maths::constants;\nusing utils::stds::static_pointer_cast;\n\n\ntemplate<class T>\nclass HamParams: public Printable{    \npublic:    \n    HamParams(const string &prefix = \"\"):\n        Printable(\" \" + prefix)\n    {        \n    }\n    \n    void   dtol(double dtol){ mdtol = dtol; update(); }\n    double dtol() const { return mdtol; } \n    \n    void   orthogonal(bool orth){ mortho = orth; update(); }\n    bool   orthogonal() const { return mortho; }\n    \n    void   periodicTable(const PeriodicTable &pt) { mpt = pt; update(); }\n    const  PeriodicTable &periodicTable() const { return mpt; }\n    \n    void   Bz(double Bz, int gauge = coord::X){ mBz = Bz; mBzGauge = gauge; update(); };\n    double Bz() const { return mBz; }\n    \n    //!< Generate Hamiltonian between two atoms.\n    virtual T twoAtomHam(const AtomicStruct& atomi, \n                            const AtomicStruct& atomj) const { return T(); };\n    //!< Generate Overlap matrix between two atoms.\n    virtual T twoAtomOvl(const AtomicStruct& atomi, \n                            const AtomicStruct& atomj) const { return T(); };\n    \nprotected:\n    // Updates internal parameters. Call it after changing any of the \n    // public parameters.\n    virtual void update() {}; \n\n    // Caluclates Peierl's phase factor for magnetic field\n    dcmplx calcPeierlsPhase(double xi, double yi, double xj, double yj) const;\n    \nprotected:\n    // Parameters required for all Hamiltonin\n    double mdtol;         //!< Distance tolerance. \n    bool   mortho;        //!< Is this an orthogonal basis.\n    PeriodicTable mpt;    //!< The periodic table required for this system.\n    double mBz;           //!< The z-component of magnetic field.\n    int    mBzGauge;      //!< gauge choice for the z-component.\n    //!< pre-factor for magnetic phase = i*hbar/q/2\n    double mfactor = 1E-20*q/hbar/2; \n    static constexpr double mBzTol = 1E-10;\n};\n\n\n// Caluclates Peierl's phase factor for magnetic field\ntemplate<class T>\ndcmplx HamParams<T>::calcPeierlsPhase(double xi, double yi, \n        double xj, double yj) const \n{\n    dcmplx phase = dcmplx(1,0);\n    if(abs(mBz) > mBzTol) {\n        dcmplx iphi = dcmplx(0,0);\n        if (mBzGauge == coord::X) { // for A = (-Bz*y, 0, 0)\n            iphi = dcmplx(0, mfactor*mBz*(xi - xj)*(yi + yj));\n        } else if (mBzGauge == coord::Y) { // for A = (0, Bz*x, 0)\n            iphi = dcmplx(0, mfactor*mBz*(yj - yi)*(xi + xj));\n        }\n        phase = exp(iphi);\n    }\n    return phase;\n}\n\n//!< Generates the hamiltonaina and overlap matrices between atomc block\n//!< i and atomic block j. \ntemplate<class T>\nvoid generateHamOvl(T &hmat, T&smat, const HamParams<T> &p, \n        const AtomicStruct &bi, const AtomicStruct &bj){\n    // Just for easy reference\n    int nai = bi.NumOfAtoms();\n    int naj = bj.NumOfAtoms();\n    int noi = bi.NumOfOrbitals();\n    int noj = bj.NumOfOrbitals();\n\n    // Most of the matrix elements are zeros. So, we'll only change the \n    // non zero elements below.\n    hmat = zeros<T>(noi, noj);\n    smat = zeros<T>(noi, noj);\n\n    // Lets find the neighbors. \n    int io = 0;\n    for(int ia = 0; ia != nai; ++ia){\n        AtomicStruct atomi = bi(ia);        // extract atom ia\n        int ni = atomi.NumOfOrbitals();     // number of orbitals in atom ia\n\n        int jo = 0;\n        for(int ja = 0; ja != naj; ++ja){\n            AtomicStruct atomj = bj(ja);        // extract atom ja    \n            int nj = atomj.NumOfOrbitals();     // number of orbitals in atom ja\n            // generate Hamiltonian matrix between orbitals of\n            // atom i and atom j\n            hmat(span(io,io+ni-1), span(jo,jo+nj-1)) = p.twoAtomHam(atomi, atomj);\n            smat(span(io,io+ni-1), span(jo,jo+nj-1)) = p.twoAtomOvl(atomi, atomj);\n            jo += nj;\n        }\n\n        io += ni;\n    }    \n}   \n\ntypedef HamParams<cxmat>  cxhamparams;\ntypedef HamParams<mat>    hamparams;\n\n}\n}\n#endif\t/* HAMILTONIAN_HPP */\n\n", "meta": {"hexsha": "db6fdd3831f2450d6635b1b2f210c7e3611b4145", "size": 4633, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/include/hamiltonian/hamiltonian.hpp", "max_stars_repo_name": "masumhabib/quest", "max_stars_repo_head_hexsha": "afef1166b361236144be83f07303a3ec0d5c187c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2017-04-04T20:57:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-23T02:08:22.000Z", "max_issues_repo_path": "lib/include/hamiltonian/hamiltonian.hpp", "max_issues_repo_name": "masumhabib/quest", "max_issues_repo_head_hexsha": "afef1166b361236144be83f07303a3ec0d5c187c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2016-10-06T03:00:24.000Z", "max_issues_repo_issues_event_max_datetime": "2017-05-30T06:43:32.000Z", "max_forks_repo_path": "lib/include/hamiltonian/hamiltonian.hpp", "max_forks_repo_name": "masumhabib/quest", "max_forks_repo_head_hexsha": "afef1166b361236144be83f07303a3ec0d5c187c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-03T04:09:25.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-03T04:09:25.000Z", "avg_line_length": 31.7328767123, "max_line_length": 88, "alphanum_fraction": 0.6142887978, "num_tokens": 1323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432182679956, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.48025555813943066}}
{"text": "#include \"window.hpp\"\n#include <iostream>\n#include <random>\n#include <boost/program_options.hpp>\n\n#include \"classes.hpp\"\n#include \"kruskal.hpp\"\n#include \"prim.hpp\"\n#include \"helperFunctions.hpp\"\n\nstd::once_flag algorithmEnd;\n\nnamespace po = boost::program_options;\n\nstruct MinimumSpanningTreeConfig{\n    std::string algorithm{\"\"};\n\tint nodes{0};\n    int delay{0};\n    std::string input_path{\"\"};\n    bool interactive{false};\n};\n\nstruct MinimumSpanningTreeOptions \n{\n\tpo::options_description\toptions;\n\tpo::variables_map vm;\n\n\tMinimumSpanningTreeConfig ca;\n\n\tMinimumSpanningTreeOptions(int argc, char** argv) \n        : options() \n    {\n\t\toptions.add_options()\n\t\t(\"help,h\", \"display this help.\")\n\t\t(\"algorithm,a\", po::value<std::string>(&ca.algorithm)->default_value(\"kruskal\"), \"chosen algorithm name\")\n\t\t(\"nodes,n\", po::value<int>(&ca.nodes)->default_value(50), \"number of nodes\")\n\t\t(\"delay,d\", po::value<int>(&ca.delay)->default_value(100), \"animation delay\")\n\t\t(\"path,p\", po::value<std::string>(&ca.input_path)->default_value(\"\"), \"input path\")\n\t\t(\"interactive,i\", \"enable interactive mode\")\n\t\t;\n\n\t\tpo::variables_map tmp_vm;\n\t\tpo::store(po::parse_command_line(argc, argv, options), tmp_vm);\n\t\tpo::notify(tmp_vm);\n\t\tif (tmp_vm.count(\"help\")) {\n\t\t\tstd::cout << options << '\\n';\n\t\t\texit(0);\n\t\t}\n\n\t\tif (tmp_vm.count(\"interactive\")) {\n            ca.interactive = true;\n\t\t}\n\t\tvm = tmp_vm;\n\t}\n};\n\nint main (int argc, char *argv[])\n{\n    MinimumSpanningTreeOptions opt(argc,argv);\n\n    std::string algorithm = opt.ca.algorithm;\n    int nodes_value  = opt.ca.nodes;\n    int delay = opt.ca.delay;\n    std::string input_path = opt.ca.input_path;\n    bool is_interactive = opt.ca.interactive;\n\n    FastGui::Window w(800, 800);\n    w.setScreenColor(0,0,0);\n    w.setDelay(delay);\n\n    std::cout << \"Input algorithm option value=\" << algorithm << '\\n';\n    std::cout << \"Input nodes number option value=\" << nodes_value << '\\n';\n    std::cout << \"Delay value=\" << delay << '\\n';\n    // ------------------------------------\n\n    std::vector<Node*> allNodes;                \n\n    if (!is_interactive) {\n        if (!input_path.empty())\n            readPointsFromFile(input_path, allNodes);\n        else {\n            // set random number generator\n            std::random_device dev;\n            std::mt19937 rng(dev());\n            std::uniform_int_distribution<std::mt19937::result_type> dist(100, 700);\n\n            // create new nodes at random postions\n            for (int i = 1; i <= nodes_value; ++i) {\n                int x = dist(rng);\n                int y = dist(rng);\n                Node* t = new Node(i, x,y);\n                allNodes.push_back(t);\n            }\n            writePointsToFile(\"../data/inputs/data_\" + std::to_string(w.getStartTime()), allNodes);\n        }\n    }\n    else {\n        std::cout << \"Interactive mode enabled\" << '\\n';\n    }\n\n    Kruskal k(allNodes, w, is_interactive);\n    Prim p(allNodes, w, is_interactive);\n\n    if (algorithm == \"kruskal\")\n        w.main_loop(k);\n    else if(algorithm == \"prim\")\n        w.main_loop(p);\n    else {\n        std::cout << \"There is no such algorithm!\" << '\\n';\n        w.windowShouldClose();\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "2b12630d4bfdbbb00484975792b60b5191ac6a34", "size": 3180, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "kleist0202/minimum_spanning_tree_visualizer", "max_stars_repo_head_hexsha": "e0979691c134ec876633109e8c13ea190573ff85", "max_stars_repo_licenses": ["MIT"], "max_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": "kleist0202/minimum_spanning_tree_visualizer", "max_issues_repo_head_hexsha": "e0979691c134ec876633109e8c13ea190573ff85", "max_issues_repo_licenses": ["MIT"], "max_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": "kleist0202/minimum_spanning_tree_visualizer", "max_forks_repo_head_hexsha": "e0979691c134ec876633109e8c13ea190573ff85", "max_forks_repo_licenses": ["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.652173913, "max_line_length": 107, "alphanum_fraction": 0.5949685535, "num_tokens": 813, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410572017153, "lm_q2_score": 0.7217431943271999, "lm_q1q2_score": 0.48025555178674934}}
{"text": "#pragma once\n\n#include <list>\n#include <vector>\n\n#include <boost/numeric/mtl/mtl_fwd.hpp>\n\n#include \"AMDiS_fwd.hpp\"\n#include \"BasisFunction.hpp\"\n#include \"FixVec.hpp\"\n#include \"Flag.hpp\"\n\nnamespace AMDiS\n{\n  /**\n   * \\ingroup Assembler\n   *\n   * \\brief\n   * For the assemblage of the system matrix and right hand side vector of the\n   * linear system, we have to compute integrals, for example:\n   * \\f[ \\int_{\\Omega} f(x)\\varphi_i(x) dx \\f]\n   * For general data A, b, c, and f, these integrals can not be calculated\n   * exactly. Quadrature formulas have to be used in order to calculate the\n   * integrals approximately. Numerical integration in finite element methods is\n   * done by looping over all grid elements and using a quadrature formula on\n   * each element.\n   */\n  class Quadrature\n  {\n  protected:\n    /// Avoids call of default constructor\n    Quadrature();\n\n    /** \\brief\n     * Constructs a Quadrature with name name_ of degree degree_ for dim dim_.\n     * The Quadrature has n_points_ quadrature points with barycentric\n     * coordinates lambda_ and weights w_. The constructor is protected because\n     * access to a Quadrature should be done via \\ref provideQuadrature.\n     */\n    Quadrature(const char* name_,\n               int degree_,\n               int dim_,\n               int n_points_,\n               VectorOfFixVecs<DimVec<double>>* lambda_,\n               double* w_)\n      : name(name_),\n        degree(degree_),\n        dim(dim_),\n        n_points(n_points_),\n        lambda(lambda_),\n        w(w_)\n    {}\n\n  public:\n    /// Copy constructor\n    Quadrature(const Quadrature&);\n\n    /// Destructor\n    virtual ~Quadrature();\n\n    /// Returns a Quadrature for dimension dim exact for degree degree.\n    static Quadrature* provideQuadrature(int dim, int degree);\n\n    /** \\brief\n     * Approximates an integral by the numerical quadrature described by quad;\n     * f is a pointer to an AbstractFunction to be integrated, evaluated in\n     * barycentric coordinates; the return value is\n     * \\f[ \\sum_{k = 0}^{n_points-1} w[k] * (*f)(lambda[k]) \\f]\n     * For the approximation of \\f$ \\int_S f\\f$ we have to multiply this value\n     * with d!|S| for a simplex S; for a parametric simplex f should be a pointer\n     * to a function which calculates\n     * \\f$ f(\\lambda)|det DF_S(\\hat{x}(\\lambda))| \\f$.\n     */\n    double integrateStdSimplex(std::function<double(DimVec<double>)> f);\n\n    /// Returns \\ref name\n    std::string getName() const\n    {\n      return name;\n    }\n\n    /// Returns \\ref n_points\n    int getNumPoints() const\n    {\n      return n_points;\n    }\n\n    /// Returns \\ref w[p]\n    double getWeight(int p) const\n    {\n      return w[p];\n    }\n\n    /// Returns \\ref w.\n    double* getWeight() const\n    {\n      return w;\n    }\n\n    /// Returns \\ref dim\n    int getDim() const\n    {\n      return dim;\n    }\n\n    /// Returns \\ref degree\n    int getDegree() const\n    {\n      return degree;\n    }\n\n    /** \\brief\n     * Returns a pointer to a vector storing the values of a doubled valued\n     * function at all quadrature points; f is that AbstractFunction\n     * , evaluated in barycentric coordinates; if vec is not NULL, the values are\n     * stored in this vector, otherwise the values are stored in some static\n     * local vector, which is overwritten on the next call\n     */\n    const double* fAtQp(const std::function<double(DimVec<double>)>& f,\n                        double* vec) const ;\n\n    /** \\brief\n     * Returns a pointer to a vector storing the gradient (with respect to world\n     * coordinates) of a double valued function at all quadrature points;\n     * grdF is a pointer to a AbstractFunction, evaluated in barycentric\n     * coordinates and returning a pointer to a WorldVector storing the gradient;\n     * if vec is not NULL, the values are stored in this vector, otherwise the\n     * values are stored in some local static vector, which is overwritten on the\n     * next call\n     */\n    const WorldVector<double>* grdFAtQp(const std::function<WorldVector<double>(DimVec<double>)>& grdF,\n                                        WorldVector<double>* vec) const;\n\n\n\n    /// Returns \\ref lambda[a][b] which is the b-th coordinate entry of the a-th\n    /// quadrature point\n    double getLambda(int a, int b) const\n    {\n      return (lambda ? (*lambda)[a][b] : 0.0);\n    }\n\n    /// Returns \\ref lambda[a] which is a DimVec<double> containing the\n    /// coordiantes of the a-th quadrature point\n    const DimVec<double>& getLambda(int a) const\n    {\n      return (*lambda)[a];\n    }\n\n    /// Returns \\ref lambda which is a VectorOfFixvecs<DimVec<double> >.\n    VectorOfFixVecs<DimVec<double>>* getLambda() const\n    {\n      return lambda;\n    }\n\n\n  public:\n    /// Maximal number of quadrature points for the different dimensions\n    static constexpr int maxNQuadPoints[4] = {0, 10, 61, 64};\n\n  protected:\n    /// Name of this Quadrature\n    std::string name;\n\n    /// Quadrature is exact of this degree\n    int degree;\n\n    /// Quadrature for dimension dim\n    int dim;\n\n    /// Number of quadrature points\n    int n_points;\n\n    /// Vector of quadrature points given in barycentric coordinates\n    VectorOfFixVecs<DimVec<double>>* lambda;\n\n    /// Vector of quadrature weights\n    double* w;\n\n  protected:\n    /// Initialisation of all static Quadrature objects which will be returned\n    /// by \\ref provideQuadrature()\n    static void initStaticQuadratures();\n\n    /** \\name static quadratures, used weights, and barycentric coords\n     * \\{\n     */\n    static Quadrature** quad_nd[4];\n    static Quadrature* quad_0d[1];\n    static Quadrature* quad_1d[20];\n    static Quadrature* quad_2d[18];\n    static Quadrature* quad_3d[8];\n\n    static VectorOfFixVecs<DimVec<double>>* x_0d;\n    static double* w_0d;\n\n    static VectorOfFixVecs<DimVec<double>>* x0_1d;\n    static VectorOfFixVecs<DimVec<double>>* x1_1d;\n    static VectorOfFixVecs<DimVec<double>>* x2_1d;\n    static VectorOfFixVecs<DimVec<double>>* x3_1d;\n    static VectorOfFixVecs<DimVec<double>>* x4_1d;\n    static VectorOfFixVecs<DimVec<double>>* x5_1d;\n    static VectorOfFixVecs<DimVec<double>>* x6_1d;\n    static VectorOfFixVecs<DimVec<double>>* x7_1d;\n    static VectorOfFixVecs<DimVec<double>>* x8_1d;\n    static VectorOfFixVecs<DimVec<double>>* x9_1d;\n    static double* w0_1d;\n    static double* w1_1d;\n    static double* w2_1d;\n    static double* w3_1d;\n    static double* w4_1d;\n    static double* w5_1d;\n    static double* w6_1d;\n    static double* w7_1d;\n    static double* w8_1d;\n    static double* w9_1d;\n\n    static VectorOfFixVecs<DimVec<double>>* x1_2d;\n    static VectorOfFixVecs<DimVec<double>>* x2_2d;\n    static VectorOfFixVecs<DimVec<double>>* x3_2d;\n    static VectorOfFixVecs<DimVec<double>>* x4_2d;\n    static VectorOfFixVecs<DimVec<double>>* x5_2d;\n    static VectorOfFixVecs<DimVec<double>>* x7_2d;\n    static VectorOfFixVecs<DimVec<double>>* x8_2d;\n    static VectorOfFixVecs<DimVec<double>>* x9_2d;\n    static VectorOfFixVecs<DimVec<double>>* x10_2d;\n    static VectorOfFixVecs<DimVec<double>>* x11_2d;\n    static VectorOfFixVecs<DimVec<double>>* x12_2d;\n    static VectorOfFixVecs<DimVec<double>>* x17_2d;\n    static double* w1_2d;\n    static double* w2_2d;\n    static double* w3_2d;\n    static double* w4_2d;\n    static double* w5_2d;\n    static double* w7_2d;\n    static double* w8_2d;\n    static double* w9_2d;\n    static double* w10_2d;\n    static double* w11_2d;\n    static double* w12_2d;\n    static double* w17_2d;\n\n    static VectorOfFixVecs<DimVec<double>>* x1_3d;\n    static VectorOfFixVecs<DimVec<double>>* x2_3d;\n    static VectorOfFixVecs<DimVec<double>>* x3_3d;\n    static VectorOfFixVecs<DimVec<double>>* x4_3d;\n    static VectorOfFixVecs<DimVec<double>>* x5_3d;\n    static VectorOfFixVecs<DimVec<double>>* x7_3d;\n    static double* w1_3d;\n    static double* w2_3d;\n    static double* w3_3d;\n    static double* w4_3d;\n    static double* w5_3d;\n    static double* w7_3d;\n\n    /** \\} */\n  };\n\n\n\n  /// Pre-compute the values of all basis functions at all quadrature nodes;\n  const Flag INIT_PHI=1;\n\n  /// Pre-compute the gradients (with respect to the barycentric coordinates) of\n  /// all basis functions at all quadrature nodes\n  const Flag INIT_GRD_PHI=2;\n\n  /// pre-compute all 2nd derivatives (with respect to the barycentric\n  /// coordinates) of all basis functions at all quadrature nodes;\n  const Flag INIT_D2_PHI=4;\n\n\n  /**\n   * \\ingroup Integration\n   *\n   *\\brief\n   * Often numerical integration involves basis functions, such as the assembling\n   * of the system matrix and right hand side, or the integration of finite\n   * element functions. Since numerical quadrature involves only the values at\n   * the quadrature points and the values of basis functions and its derivatives\n   * are the same at these points for all elements of the grid, such routines can\n   * be much more efficient, if they can use pre-computed values of the basis\n   * functions at the quadrature points. In this case the basis functions do not\n   * have to be evaluated for each quadrature point on every element newly.\n   * Information that should be pre-computed can be specified by the following\n   * symbolic constants:\n   * \\ref INIT_PHI, \\ref INIT_GRD_PHI, \\ref INIT_D2_PHI\n   */\n  class FastQuadrature\n  {\n  protected:\n    /// Constructs a FastQuadrature for the given Quadrature, BasisFunction, and\n    /// flag.\n    FastQuadrature(BasisFunction* basFcts, Quadrature* quad, Flag flag)\n      : init_flag(flag),\n        phi(0, 0),\n        D2Phi(NULL),\n        quadrature(quad),\n        basisFunctions(basFcts)\n    {}\n\n    /// Copy constructor\n    FastQuadrature(const FastQuadrature&);\n\n    /// Extended copy constructor\n    FastQuadrature(const FastQuadrature&, const Flag);\n\n    /// Destructor\n    virtual ~FastQuadrature();\n\n  public:\n    /// Returns a FastQuadrature for the given BasisFunction, Quadrature, and flags.\n    static FastQuadrature* provideFastQuadrature(const BasisFunction*,\n        const Quadrature&,\n        Flag);\n\n    /// inits FastQuadrature like speciefied in flag\n    void init(Flag init_flag);\n\n    bool initialized(Flag flag)\n    {\n      if (flag == INIT_PHI)\n        return (num_rows(phi) > 0);\n\n      if (flag == INIT_GRD_PHI)\n        return (!grdPhi.empty());\n\n      if (flag == INIT_D2_PHI)\n        return (D2Phi != NULL);\n\n      ERROR_EXIT(\"invalid flag\\n\");\n      return false;\n    }\n\n    /// Returns \\ref quadrature\n    const Quadrature* getQuadrature() const\n    {\n      return quadrature;\n    }\n\n    /// Returns \\ref max_points\n    int getMaxQuadPoints() const\n    {\n      return max_points;\n    }\n\n    /// Returns (*\\ref D2Phi)[q][i][j][m]\n    double getSecDer(int q, int i, int j, int m) const;\n\n    /// Returns (*\\ref D2Phi)[q]\n    const VectorOfFixVecs<DimMat<double>>* getSecDer(int q) const;\n\n    /// Returns (*\\ref grdPhi)[q][i][j]\n    double getGradient(int q, int i ,int j) const\n    {\n      return (!grdPhi.empty()) ? grdPhi[q][i][j] : 0.0;\n    }\n\n    /// Returns (*\\ref grdPhi)[q]\n    const std::vector<DenseVector<double>>& getGradient(int q) const\n    {\n      return grdPhi[q];\n    }\n\n    const DenseVector<double>& getGradient(int q, int i) const\n    {\n      return grdPhi[q][i];\n    }\n\n    const DenseMatrix<double>& getPhi() const\n    {\n      return phi;\n    }\n\n    /// Returns \\ref phi[q][i]\n    double getPhi(int q, int i) const\n    {\n      return phi[q][i];\n    }\n\n    /// Returns \\ref quadrature ->integrateStdSimplex(f)\n    double integrateStdSimplex(std::function<double(DimVec<double>)> f)\n    {\n      return quadrature->integrateStdSimplex(f);\n    }\n\n    /// Returns \\ref quadrature ->getNumPoints()\n    int getNumPoints() const\n    {\n      return quadrature->getNumPoints();\n    }\n\n    /// Returns \\ref quadrature ->getWeight(p)\n    double getWeight(int p) const\n    {\n      return quadrature->getWeight(p);\n    }\n\n    /// Returns \\ref quadrature ->getDim()\n    int getDim() const\n    {\n      return quadrature->getDim();\n    }\n\n    /// Returns \\ref quadrature ->getDegree()\n    int getDegree() const\n    {\n      return quadrature->getDegree();\n    }\n\n    /// Returns \\ref quadrature ->grdFAtQp(f, vec)\n    const WorldVector<double>\n    * grdFAtQp(const std::function<WorldVector<double>(DimVec<double>)>& f,\n               WorldVector<double>* vec) const\n    {\n      return quadrature->grdFAtQp(f, vec);\n    }\n\n    /// Returns \\ref quadrature ->fAtQp(f, vec)\n    const double* fAtQp(const std::function<double(DimVec<double>)>& f, double* vec) const\n    {\n      return quadrature->fAtQp(f, vec);\n    }\n\n    /// Returns \\ref quadrature ->getLambda(a,b)\n    double getLambda(int a,int b) const\n    {\n      return quadrature->getLambda(a,b);\n    }\n\n    /// Returns \\ref quadrature ->getLambda(a)\n    const DimVec<double>& getLambda(int a) const\n    {\n      return quadrature->getLambda(a);\n    }\n\n    /// Returns \\ref basisFunctions\n    BasisFunction* getBasisFunctions() const\n    {\n      return basisFunctions;\n    }\n\n  protected:\n    /// Specifies which information should be pre-computed. Can be \\ref INIT_PHI,\n    /// \\ref INIT_GRD_PHI, or \\ref INIT_D2_PHI\n    Flag init_flag;\n\n    /** \\brief\n     * Matrix storing function values if the flag \\ref INIT_PHI is set;\n     * phi[i][j] stores the value \\ref basisFunctions->phi[j]\n     * (quadrature->lambda[i]), 0 <= j < basisFunctions->getNumber()  and\n     * 0 <= i < n_points\n     */\n    DenseMatrix<double> phi;\n\n    /** \\brief\n     * Matrix storing all gradients (with respect to the barycentric coordinates)\n     * if the flag \\ref INIT_GRD_PHI is set; grdPhi[i][j][k] stores the value\n     * basisFunctions->grdPhi[j](quadrature->lambda[i])[k]\n     * for 0 <= j < basisFunctions->getNumber(),\n     * 0 <= i < . . . , n_points, and 0 <= k < DIM\n     */\n    std::vector<std::vector<DenseVector<double>>> grdPhi;\n\n    /** \\brief\n     * Matrix storing all second derivatives (with respect to the barycentric\n     * coordinates) if the flag \\ref INIT_D2_PHI is set; D2Phi[i][j][k][l] stores\n     * the value basisFunctions->D2Phi[j](quadrature->lambda[i])[k][l]\n     * for 0 <= j < basisFunctions->getNumber(),\n     * 0 <= i < n_points, and 0 <= k,l < DIM\n     */\n    MatrixOfFixVecs<DimMat<double>>* D2Phi;\n\n    /// List of all used FastQuadratures\n    static std::list<FastQuadrature*> fastQuadList;\n\n    /// Maximal number of quadrature points for all yet initialised FastQuadrature\n    /// objects. This value may change after a new initialisation of a\n    /// FastQuadrature\n    static int max_points;\n\n    /// This FastQuadrature stores values for Quadrature quadrature\n    Quadrature* quadrature;\n\n    /// Values stored for basis functions basisFunctions\n    BasisFunction* basisFunctions;\n\n  };\n\n} // end namespace AMDiS\n", "meta": {"hexsha": "49c060ce5e97b55b2daa1de66d985aed99770f7b", "size": 14717, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Quadrature.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/Quadrature.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/Quadrature.hpp", "max_forks_repo_name": "spraetor/amdis2", "max_forks_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9735234216, "max_line_length": 103, "alphanum_fraction": 0.6534619827, "num_tokens": 4105, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.6654105587468141, "lm_q1q2_score": 0.48025555017420174}}
{"text": "/*\r\n * phase_chain.cpp\r\n *\r\n * Example of MPI parallelization with odeint\r\n *\r\n * Copyright 2013 Karsten Ahnert\r\n * Copyright 2013 Mario Mulansky\r\n * Copyright 2013 Pascal Germroth\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#include <iostream>\r\n#include <vector>\r\n#include <boost/random.hpp>\r\n#include <boost/timer/timer.hpp>\r\n//[phase_chain_mpi_header\r\n#include <boost/numeric/odeint.hpp>\r\n#include <boost/numeric/odeint/external/mpi/mpi.hpp>\r\n//]\r\n\r\nusing namespace std;\r\nusing namespace boost::numeric::odeint;\r\nusing boost::timer::cpu_timer;\r\nusing boost::math::double_constants::pi;\r\n\r\n//[phase_chain_state\r\ntypedef mpi_state< vector<double> > state_type;\r\n//]\r\n\r\n//[phase_chain_mpi_rhs\r\nstruct phase_chain_mpi_state\r\n{\r\n    phase_chain_mpi_state( double gamma = 0.5 )\r\n    : m_gamma( gamma ) { }\r\n\r\n    void operator()( const state_type &x , state_type &dxdt , double /* t */ ) const\r\n    {\r\n        const size_t M = x().size();\r\n        const bool have_left = x.world.rank() > 0,\r\n                   have_right = x.world.rank() < x.world.size()-1;\r\n        double x_left, x_right;\r\n        boost::mpi::request r_left, r_right;\r\n        if( have_left )\r\n        {\r\n            x.world.isend( x.world.rank()-1 , 0 , x().front() ); // send to x_right\r\n            r_left = x.world.irecv( x.world.rank()-1 , 0 , x_left ); // receive from x().back()\r\n        }\r\n        if( have_right )\r\n        {\r\n            x.world.isend( x.world.rank()+1 , 0 , x().back() ); // send to x_left\r\n            r_right = x.world.irecv( x.world.rank()+1 , 0 , x_right ); // receive from x().front()\r\n        }\r\n        for(size_t m = 1 ; m < M-1 ; ++m)\r\n        {\r\n            dxdt()[m] = coupling_func( x()[m+1] - x()[m] ) +\r\n                        coupling_func( x()[m-1] - x()[m] );\r\n        }\r\n        dxdt()[0] = coupling_func( x()[1] - x()[0] );\r\n        if( have_left )\r\n        {\r\n            r_left.wait();\r\n            dxdt()[0] += coupling_func( x_left - x().front() );\r\n        }\r\n        dxdt()[M-1] = coupling_func( x()[M-2] - x()[M-1] );\r\n        if( have_right )\r\n        {\r\n            r_right.wait();\r\n            dxdt()[M-1] += coupling_func( x_right - x().back() );\r\n        }\r\n    }\r\n\r\n    double coupling_func( double x ) const\r\n    {\r\n        return sin( x ) - m_gamma * ( 1.0 - cos( x ) );\r\n    }\r\n\r\n    double m_gamma;\r\n};\r\n//]\r\n\r\n\r\nint main( int argc , char **argv )\r\n{\r\n    //[phase_chain_mpi_init\r\n    boost::mpi::environment env( argc , argv );\r\n    boost::mpi::communicator world;\r\n\r\n    const size_t N = 131101;\r\n    vector<double> x;\r\n    if( world.rank() == 0 )\r\n    {\r\n        x.resize( N );\r\n        boost::random::uniform_real_distribution<double> distribution( 0.0 , 2.0*pi );\r\n        boost::random::mt19937 engine( 0 );\r\n        generate( x.begin() , x.end() , boost::bind( distribution , engine ) );\r\n    }\r\n\r\n    state_type x_split( world );\r\n    split( x , x_split );\r\n    //]\r\n\r\n\r\n    cpu_timer timer;\r\n    //[phase_chain_mpi_integrate\r\n    integrate_n_steps( runge_kutta4<state_type>() , phase_chain_mpi_state( 1.2 ) ,\r\n                       x_split , 0.0 , 0.01 , 100 );\r\n    unsplit( x_split , x );\r\n    //]\r\n\r\n    if( world.rank() == 0 )\r\n    {\r\n        double run_time = static_cast<double>(timer.elapsed().wall) * 1.0e-9;\r\n        std::cerr << run_time << \"s\" << std::endl;\r\n        // copy(x.begin(), x.end(), ostream_iterator<double>(cout, \"\\n\"));\r\n    }\r\n\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "fc4836d77c722c12f4028a966e8a84e23a93a8b2", "size": 3537, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/numeric/odeint/examples/mpi/phase_chain.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": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/numeric/odeint/examples/mpi/phase_chain.cpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-04T18:00:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-04T18:00:00.000Z", "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/numeric/odeint/examples/mpi/phase_chain.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 29.2314049587, "max_line_length": 99, "alphanum_fraction": 0.5391574781, "num_tokens": 966, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6654105587468141, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.4802555461915871}}
{"text": "//    Copyright 2017 Rainer Gemulla\n// \n//    Licensed under the Apache License, Version 2.0 (the \"License\");\n//    you may not use this file except in compliance with the License.\n//    You may obtain a copy of the License at\n// \n//        http://www.apache.org/licenses/LICENSE-2.0\n// \n//    Unless required by applicable law or agreed to in writing, software\n//    distributed under the License is distributed on an \"AS IS\" BASIS,\n//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//    See the License for the specific language governing permissions and\n//    limitations under the License.\n/** \\file\n *\n * Illustrates matrix factorization with SGD. We first creates factors and then a data matrix\n * from these factors. THis process ensures that we know the best factorization of the input.\n * We then try to reconstruct the factors using SGD.\n */\n#include <iostream>\n\n#include <boost/math/distributions/normal.hpp>\n#include <boost/random/uniform_real.hpp>\n\n#include <util/evaluation.h>\n#include <util/io.h>\n\n#include <mf/mf.h>\n\nusing namespace std;\nusing namespace mf;\nusing namespace rg;\nusing namespace boost::numeric::ublas;\n\nlog4cxx::LoggerPtr logger(log4cxx::Logger::getLogger(\"main\"));\n\nint main(int argc, char* argv[]) {\n#ifndef NDEBUG\n\tLOG4CXX_WARN(logger, \"Warning: Debug mode activated (runtimes may be slow).\");\n#endif\n\n\t// parameters for the factorization\n\tmf_size_type size1 = 10000;\n\tmf_size_type size2 = 10000;\n\tmf_size_type nnz = 5000000;\n\tmf_size_type r = 10;\n\n\t// parameters for SGD\n\tdouble eps0 = 0.001;\n\tunsigned epochs = 10;\n\tmf_size_type testNnz = nnz/100;\n\tSgdOrder order = SGD_ORDER_WOR;\n\ttypedef SlLoss Loss;\n\tLoss loss;\n//\ttypedef UpdateAbs<UpdateNzsll> Update;\n//\ttypedef RegularizeAbs<RegularizeSL> Regularize;\n//\tUpdate update = Update( (Update::Update()) );\n//\tRegularize regularize = Regularize( (Regularize::Regularize()) );\n\ttypedef UpdateTruncate<UpdateSl> Update;\n\ttypedef RegularizeTruncate<RegularizeSl> Regularize;\n\tUpdate update = Update( (Update::Update()), 0, 100 );\n\tRegularize regularize = Regularize( (Regularize::Regularize()), 0, 100 );\n\n\t// generate original factors by sampling from a uniform[0,1] distribution\n\tRandom32 random; // note: this takes a default seed (not randomized!)\n\tDenseMatrix wIn(size1, r);\n\tDenseMatrixCM hIn(r, size2);\n\tgenerateRandom(wIn, random, boost::uniform_real<>(0,1));\n\tgenerateRandom(hIn, random, boost::uniform_real<>(0,1));\n\n\t// generate a sparse matrix by selecting random entries from the generated factors\n\t// and add small Gaussian noise\n\tSparseMatrix v;\n\tgenerateRandom(v, nnz, wIn, hIn, random);\n\t//addRandom(v, random, boost::normal_distribution<>(0, 0.1));\n\tLOG4CXX_INFO(logger, \"Data matrix: \"\n\t\t<< v.size1() << \" x \" << v.size2() << \", \" << v.nnz() << \" nonzeros\");\n\tv.sort();\n\t//LOG4CXX_INFO(logger, \"Loss with original factors: \" << loss((FactorizationData<>(v, wIn, hIn))));\n\tSparseMatrixCM vc;\n\tcopyCm(v, vc);\n\n\t// create a test matrix (without noise)\n\tSparseMatrix vTest;\n\tgenerateRandom(vTest, testNnz, wIn, hIn, random);\n\tLOG4CXX_INFO(logger, \"Test matrix: \"\n\t\t<< v.size1() << \" x \" << v.size2() << \", \" << vTest.nnz() << \" nonzeros\");\n\n\t// generate initial factors by sampling from a uniform[0,1] distribution\n\tDenseMatrix w(size1, r);\n\tDenseMatrixCM h(r, size2);\n\tgenerateRandom(w, random, boost::uniform_real<>(0,1));\n\tLOG4CXX_INFO(logger, \"Row factors: \" << w.size1() << \" x \" << w.size2());\n\tgenerateRandom(h, random, boost::uniform_real<>(0,1));\n\tLOG4CXX_INFO(logger, \"Column factors: \" << h.size1() << \" x \" << h.size2());\n\n\t// rescale initial factors to match frobenius norm\n//\tdouble l2v = l2(v);\n//\tdouble l2wh = sumOfSquares(w, h);\n//\tdouble f = std::sqrt(l2wh / l2v);\n\n\n\t// take a small sample and remove empty rows/columns\n\tProjectedSparseMatrix Vsample;\n\tprojectRandomSubmatrix(random, v, Vsample, v.size1()/5, v.size2()/5);\n\tprojectFrequent(Vsample, 0);\n\tLOG4CXX_INFO(logger, \"Sample matrix: \"\n\t\t<< Vsample.data.size1() << \" x \" << Vsample.data.size2()\n\t\t<< \", \" << Vsample.data.nnz() << \" nonzeros\");\n\n\t// initialize the SGD\n\tTimer t;\n\tSgdRunner sgdRunner(random);\n\tSgdJob<Update,Regularize> job(v, w, h, update, regularize, order);\n\tDecayAuto<Update,Regularize,Loss> decay(job, loss, Vsample, eps0, 8, 0.5, 1.05, false, true);\n\tTrace trace;\n\n\t// run SGD to try to reconstruct the original factors\n\tt.start();\n\tsgdRunner.run(job, loss, epochs, decay, trace);\n\tt.stop();\n\tLOG4CXX_INFO(logger, \"Total time: \" << t);\n\n\t// write trace to an R file\n\tLOG4CXX_INFO(logger, \"Writing trace to \" << \"/tmp/sgd-gnmf-trace.R\");\n\ttrace.toRfile(\"/tmp/sgd-gnmf-trace.R\", \"sgd.gnmf\");\n\n\treturn 0;\n}\n\n", "meta": {"hexsha": "1f54c5b489bcc5e09bfd6c55d0148f50aba50110", "size": 4631, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/mf/sgd-gnmf.cc", "max_stars_repo_name": "Hui-Li/DSGDPP", "max_stars_repo_head_hexsha": "0ce5b115bfbed81cee1c39fbfa4a8f67a5e1b72e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2017-01-10T11:39:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-02T23:03:55.000Z", "max_issues_repo_path": "examples/mf/sgd-gnmf.cc", "max_issues_repo_name": "Hui-Li/DSGDPP", "max_issues_repo_head_hexsha": "0ce5b115bfbed81cee1c39fbfa4a8f67a5e1b72e", "max_issues_repo_licenses": ["Apache-2.0"], "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/mf/sgd-gnmf.cc", "max_forks_repo_name": "Hui-Li/DSGDPP", "max_forks_repo_head_hexsha": "0ce5b115bfbed81cee1c39fbfa4a8f67a5e1b72e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-10-27T18:40:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-05T15:10:56.000Z", "avg_line_length": 35.3511450382, "max_line_length": 100, "alphanum_fraction": 0.7007125891, "num_tokens": 1320, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.48025554538531307}}
{"text": "#include <ros/ros.h>\n#include <std_msgs/Float32MultiArray.h> //input from range_finder\n#include <nav_msgs/Odometry.h> //input from odometry\n#include <geometry_msgs/Point.h>  \n#include <armadillo>\n#include <math.h>\n#include <stdio.h>\n\nusing namespace std;\nusing namespace arma;\n\nclass PathPlan{\nprivate:\n  \n  ros::NodeHandle nh_;\n  ros::Subscriber range_sub_;\n  ros::Subscriber odom_sub_;\n  ros::Publisher target_pub_;\n  ros::Publisher curr_pub_;\n  \n  cube wall_map; // It's a 3d tensor (can create as row, col, slices)\n  \n  // for /odom\n  double pos_x_, pos_y_, ang_z_; //current robot position and orientation in euler angle\n  // for /range_pub\n  double dist_north_, dist_east_, dist_south_, dist_west_;\n  \n  int goal_reached_;\n  \n  // update the map\n  \n  void initializeWall();\n  void setWall(int x, int y, int direction);\n  void removeWall(int x, int y, int direction);\n  bool hasWall(int x, int y, int direction);\n  \n  // callback functions\n  void rangeCallback(const std_msgs::Float32MultiArray& rangeMsg);\n  void odomCallback(const nav_msgs::OdometryConstPtr& odomMsg);\n  \n  //Path Planning Algorithm\n  Mat<int> path_map_;\n  vec neighbor_value_ = vec(4, fill::zeros);\n  int target_x_, target_y_, target_x_prev_, target_y_prev_;\n  bool path_map_initialized_ = false;\n  void initializePathMap(); // set all the cell with 1000\n  void setNextDestCell(); // based on the current position, find the next heading cell\n  int getPathMapValue(int x, int y);\n  \npublic:\n  \n  PathPlan(ros::NodeHandle& nh);\n  void spin();\n  \n  void checkWall();\n  void path_plan_alg();\n  \n  \n};\n\n\n", "meta": {"hexsha": "da388e1615ded3dedb83447e19c3edc16cb26a5a", "size": 1574, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/PathPlan/PathPlan.hpp", "max_stars_repo_name": "shanghaolong04/ROS-ME3243L2", "max_stars_repo_head_hexsha": "47046804a432638f28689e1d32fd83b15693eeb4", "max_stars_repo_licenses": ["MIT"], "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/PathPlan/PathPlan.hpp", "max_issues_repo_name": "shanghaolong04/ROS-ME3243L2", "max_issues_repo_head_hexsha": "47046804a432638f28689e1d32fd83b15693eeb4", "max_issues_repo_licenses": ["MIT"], "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/PathPlan/PathPlan.hpp", "max_forks_repo_name": "shanghaolong04/ROS-ME3243L2", "max_forks_repo_head_hexsha": "47046804a432638f28689e1d32fd83b15693eeb4", "max_forks_repo_licenses": ["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.3870967742, "max_line_length": 88, "alphanum_fraction": 0.7198221093, "num_tokens": 419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217431943271999, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.48025554220897243}}
{"text": "#include <boost/test/unit_test.hpp>\n#include \"algorithms/data_structures/array/max_subarray_sum.hpp\"\n\nBOOST_AUTO_TEST_SUITE(TestMaxSubArraySum)\n\nBOOST_AUTO_TEST_CASE(empty_array)\n{\n    BOOST_CHECK(0 == Algo::DS::Array::MaxSubarraySum::Calc({}));\n}\n\nBOOST_AUTO_TEST_CASE(array_with_one_elem)\n{\n    BOOST_CHECK(0 == Algo::DS::Array::MaxSubarraySum::Calc({0}));\n    BOOST_CHECK(1 == Algo::DS::Array::MaxSubarraySum::Calc({1}));\n    BOOST_CHECK(-1 == Algo::DS::Array::MaxSubarraySum::Calc({-1}));\n}\n\nBOOST_AUTO_TEST_CASE(array_with_several_elements)\n{\n    BOOST_CHECK(1 == Algo::DS::Array::MaxSubarraySum::Calc({-2, 1}));\n    BOOST_CHECK(-1 == Algo::DS::Array::MaxSubarraySum::Calc({-2, -1}));\n    BOOST_CHECK(2 == Algo::DS::Array::MaxSubarraySum::Calc({-1, 2}));\n    BOOST_CHECK(6 == Algo::DS::Array::MaxSubarraySum::Calc({0, 2, 4, -1, -1}));\n    BOOST_CHECK(7 == Algo::DS::Array::MaxSubarraySum::Calc(\n            {-2, -3, 4, -1, -2, 1, 5, -3}));\n    BOOST_CHECK(6 == Algo::DS::Array::MaxSubarraySum::Calc(\n            {-2, 1, -3, 4, -1, 2, 1, -5, 4}));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "7a34e58d15f28d1b01f1690ae19f709c2408f7b1", "size": 1083, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/algorithms/data_structures/array/test_max_subarray_sum.cpp", "max_stars_repo_name": "iamantony/CppNotes", "max_stars_repo_head_hexsha": "2707db6560ad80b0e5e286a04b2d46e5c0280b3f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-07-31T14:13:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-03T09:51:43.000Z", "max_issues_repo_path": "test/algorithms/data_structures/array/test_max_subarray_sum.cpp", "max_issues_repo_name": "iamantony/CppNotes", "max_issues_repo_head_hexsha": "2707db6560ad80b0e5e286a04b2d46e5c0280b3f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 28.0, "max_issues_repo_issues_event_min_datetime": "2015-09-22T07:38:21.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-02T11:00:58.000Z", "max_forks_repo_path": "test/algorithms/data_structures/array/test_max_subarray_sum.cpp", "max_forks_repo_name": "iamantony/CppNotes", "max_forks_repo_head_hexsha": "2707db6560ad80b0e5e286a04b2d46e5c0280b3f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-10-11T14:10:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-27T08:53:50.000Z", "avg_line_length": 34.935483871, "max_line_length": 79, "alphanum_fraction": 0.6518928901, "num_tokens": 363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6654105454764747, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.48025554059642445}}
{"text": "/* \n * Copyright 2009-2015 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/tools/linalg.h>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n\n#include \"mkl.h\"\n#include \"mkl_lapacke.h\"\n\nnamespace votca { namespace tools {\n\nusing namespace std;\n\n\nvoid linalg_qrsolve(ub::vector<double> &x, ub::matrix<double> &A, ub::vector<double> &b, ub::vector<double> *residual){\n    // check matrix for zero column\n    int nonzero_found = 0;\n    for(size_t j=0; j<A.size2(); j++) {\n        nonzero_found = 0;\n        for(size_t i=0; i<A.size1(); i++) {\n            if(fabs(A(i,j))>0) {\n                nonzero_found = 1;\n            }\n        }\n        if(nonzero_found==0) {\n            throw \"qrsolve_zero_column_in_matrix\";\n        }\n    }\n\n    \n    MKL_INT info;\n    MKL_INT sizeM = A.size1();\n    MKL_INT sizeN = A.size2();\n    MKL_INT nrhs = 1;\n    char trans = 'N';\n    \n    // pointer for LAPACK\n    double * pA = const_cast<double*>(&A.data().begin()[0]);\n    double * pb = const_cast<double*>(&b.data()[0]);\n\n\n    \n    info = LAPACKE_dgels( LAPACK_ROW_MAJOR , trans , sizeM, sizeN, nrhs , pA , sizeM , pb , sizeM );\n\n    if ( info != 0 ) \n        throw std::runtime_error(\"QR least-squares solver failed\");\n\n\n    for (size_t i =0 ; i < x.size(); i++){\n        x(i) = b(i);\n    }\n    \n    for (size_t i = 0 ; i < b.size(); i++){\n        (*residual)(i) = b(i + x.size() );\n    }\n}\n\n\n\nvoid linalg_constrained_qrsolve(ub::vector<double> &x, ub::matrix<double> &A, ub::vector<double> &b, ub::matrix<double> &constr){\n        // matrix inversion using MKL\n    throw std::runtime_error(\"linalg_constrained_qrsolve is not compiled-in due to disabling of GSL - recompile Votca Tools with GSLsupport\");\n}\n\n}}\n", "meta": {"hexsha": "ebb050388bde6131be18d3f379ecbe7ec1cf62a3", "size": 2277, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libtools/linalg/mkl/qrsolve.cc", "max_stars_repo_name": "vaidyanathanms/votca.tools", "max_stars_repo_head_hexsha": "62f9070f6b65c5bfd1227d61cddd2c5c29bcb8d4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/libtools/linalg/mkl/qrsolve.cc", "max_issues_repo_name": "vaidyanathanms/votca.tools", "max_issues_repo_head_hexsha": "62f9070f6b65c5bfd1227d61cddd2c5c29bcb8d4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libtools/linalg/mkl/qrsolve.cc", "max_forks_repo_name": "vaidyanathanms/votca.tools", "max_forks_repo_head_hexsha": "62f9070f6b65c5bfd1227d61cddd2c5c29bcb8d4", "max_forks_repo_licenses": ["Apache-2.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.4625, "max_line_length": 142, "alphanum_fraction": 0.6231884058, "num_tokens": 633, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286833, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.4801515652344499}}
{"text": "#include \"Algorithms/PeakFinding.h\"\n\n#include <boost/test/unit_test.hpp>\n#include <vector>\n\nusing Algorithms::PeakFinding::OneDim::straightforward_search;\nusing std::vector;\n\nBOOST_AUTO_TEST_SUITE(Algorithms)\nBOOST_AUTO_TEST_SUITE(PeakFinding_tests)\nBOOST_AUTO_TEST_SUITE(OneDim_tests)\n\n// cf. https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-006-introduction-to-algorithms-fall-2011/lecture-videos/MIT6_006F11_lec01.pdf\n\nconst vector<int> a {6, 7, 4, 3, 2, 1, 4, 5};\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(DemonstrateStraightforwardAlgorithm)\n{\n  BOOST_TEST(straightforward_search(a.data(), a.size()) == a.size() - 1);\n  BOOST_TEST(straightforward_search(a) == a.size() - 1); \n}\n\nBOOST_AUTO_TEST_SUITE_END() // OneDim_tests\nBOOST_AUTO_TEST_SUITE_END() // PeakFinding_tests\nBOOST_AUTO_TEST_SUITE_END() // Algorithms", "meta": {"hexsha": "e111bb11656ed8dae4ea33aa33cb0db5ef60a8e0", "size": 985, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Voltron/Source/UnitTests/Algorithms/PeakFinding_tests.cpp", "max_stars_repo_name": "ernestyalumni/HrdwCCppCUDA", "max_stars_repo_head_hexsha": "17ed937dea06431a4d5ca103f993ea69a6918734", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-02-09T19:44:51.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-09T19:44:51.000Z", "max_issues_repo_path": "Voltron/Source/UnitTests/Algorithms/PeakFinding_tests.cpp", "max_issues_repo_name": "ernestyalumni/HrdwCCppCUDA", "max_issues_repo_head_hexsha": "17ed937dea06431a4d5ca103f993ea69a6918734", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Voltron/Source/UnitTests/Algorithms/PeakFinding_tests.cpp", "max_forks_repo_name": "ernestyalumni/HrdwCCppCUDA", "max_forks_repo_head_hexsha": "17ed937dea06431a4d5ca103f993ea69a6918734", "max_forks_repo_licenses": ["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.4814814815, "max_line_length": 158, "alphanum_fraction": 0.6598984772, "num_tokens": 228, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548646660542, "lm_q2_score": 0.7371581568543044, "lm_q1q2_score": 0.4801515514953134}}
{"text": "//==================================================================================================\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\n//! [threshold]\n#include <algorithm>\n#include <chrono>\n#include <cstdint>\n#include <iostream>\n#include <limits>\n#include <vector>\n\n#include <boost/simd/pack.hpp>\n\n#include <boost/simd/function/aligned_store.hpp>\n#include <boost/simd/function/group.hpp>\n#include <boost/simd/function/if_zero_else_one.hpp>\n#include <boost/simd/function/deinterleave_first.hpp>\n#include <boost/simd/function/is_less.hpp>\n#include <boost/simd/memory/allocator.hpp>\n\nint main()\n{\n  namespace bs = boost::simd;\n  using namespace std::chrono;\n  int image_size = 2560 * 2560;\n  std::vector<std::int16_t, bs::allocator<std::int16_t>> image(image_size);\n  std::vector<std::int8_t, bs::allocator<std::int8_t>> binary(image_size);\n  std::generate(image.begin(), image.end(),\n                []() { return std::rand() % std::numeric_limits<std::int16_t>::max(); });\n  // select arbitrary threshold\n  std::int16_t threshold = 5000;\n  auto t0                = high_resolution_clock::now();\n  //! [scalar-threshold]\n  for (int i = 0; i < image.size(); ++i) {\n    if (image[i] < threshold) {\n      binary[i] = 0;\n    } else {\n      binary[i] = 1;\n    }\n  }\n  auto t1 = high_resolution_clock::now();\n  std::cout << \"scalar       \" << duration_cast<microseconds>(t1 - t0).count() << std::endl;\n  //! [scalar-threshold]\n\n  //! [simd-threshold]\n  using pack_t    = bs::pack<std::int16_t>;\n\n  static const std::size_t cardinal = pack_t::static_size;\n\n  //! [simd-threshold-downgrade]\n  using pack_8           = bs::pack<std::int8_t>;\n  std::size_t cardinal_8 = pack_8::static_size;\n  std::vector<std::int8_t, bs::allocator<std::int8_t>> binary_8(image_size);\n  t0 = high_resolution_clock::now();\n  for (int i = 0; i < image.size(); i += cardinal_8) {\n    pack_t v_image0(&image[i]);\n    pack_t v_image1(&image[i + cardinal]);\n    pack_t v_binary0      = bs::if_zero_else_one(bs::is_less(v_image0, threshold));\n    pack_t v_binary1      = bs::if_zero_else_one(bs::is_less(v_image1, threshold));\n    pack_8 v_binary_group = bs::group(v_binary0, v_binary1);\n    bs::aligned_store(v_binary_group, &binary_8[i]);\n  }\n  t1 = high_resolution_clock::now();\n  std::cout << \"downgrade \" << duration_cast<microseconds>(t1 - t0).count() << std::endl;\n  //! [simd-threshold-downgrade]\n}\n// This code can be compiled using (for instance for gcc)\n// g++ thresholding.cpp -msse4.2 -std=c++11 -O3 -DNDEBUG -o thresholding\n// -I/path_to/boost_simd/ -I/path_to/boost/\n\n//! [threshold]\n\n", "meta": {"hexsha": "907858a83972c674962cc15966e52a342da000f2", "size": 2811, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/examples/thresholding_downgrade.cpp", "max_stars_repo_name": "nickporubsky/boost-simd-clone", "max_stars_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_stars_repo_licenses": ["BSL-1.0"], "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": "doc/examples/thresholding_downgrade.cpp", "max_issues_repo_name": "nickporubsky/boost-simd-clone", "max_issues_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "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/thresholding_downgrade.cpp", "max_forks_repo_name": "nickporubsky/boost-simd-clone", "max_forks_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_forks_repo_licenses": ["BSL-1.0"], "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": 35.582278481, "max_line_length": 100, "alphanum_fraction": 0.6204197794, "num_tokens": 752, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.4801515502674999}}
{"text": "/**\n * @file lars_test.cpp\n * @author Nishant Mehta\n *\n * Test for LARS.\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\n// Note: We don't use BOOST_REQUIRE_CLOSE in the code below because we need\n// to use FPC_WEAK, and it's not at all intuitive how to do that.\n#include <mlpack/methods/lars/lars.hpp>\n#include <mlpack/core/data/load.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n\nusing namespace mlpack;\nusing namespace mlpack::regression;\n\nBOOST_AUTO_TEST_SUITE(LARSTest);\n\nvoid GenerateProblem(\n    arma::mat& X, arma::rowvec& y, size_t nPoints, size_t nDims)\n{\n  X = arma::randn(nDims, nPoints);\n  arma::vec beta = arma::randn(nDims, 1);\n  y = beta.t() * X;\n}\n\nvoid LARSVerifyCorrectness(arma::vec beta, arma::vec errCorr, double lambda)\n{\n  size_t nDims = beta.n_elem;\n  const double tol = 1e-10;\n  for (size_t j = 0; j < nDims; j++)\n  {\n    if (beta(j) == 0)\n    {\n      // Make sure that |errCorr(j)| <= lambda.\n      BOOST_REQUIRE_SMALL(std::max(fabs(errCorr(j)) - lambda, 0.0), tol);\n    }\n    else if (beta(j) < 0)\n    {\n      // Make sure that errCorr(j) == lambda.\n      BOOST_REQUIRE_SMALL(errCorr(j) - lambda, tol);\n    }\n    else // beta(j) > 0\n    {\n      // Make sure that errCorr(j) == -lambda.\n      BOOST_REQUIRE_SMALL(errCorr(j) + lambda, tol);\n    }\n  }\n}\n\nvoid LassoTest(size_t nPoints, size_t nDims, bool elasticNet, bool useCholesky)\n{\n  arma::mat X;\n  arma::rowvec y;\n\n  for (size_t i = 0; i < 100; i++)\n  {\n    GenerateProblem(X, y, nPoints, nDims);\n\n    // Armadillo's median is broken, so...\n    arma::vec sortedAbsCorr = sort(abs(X * y.t()));\n    double lambda1 = sortedAbsCorr(nDims / 2);\n    double lambda2;\n    if (elasticNet)\n      lambda2 = lambda1 / 2;\n    else\n      lambda2 = 0;\n\n\n    LARS lars(useCholesky, lambda1, lambda2);\n    arma::vec betaOpt;\n    lars.Train(X, y, betaOpt);\n\n    arma::vec errCorr = (X * trans(X) + lambda2 *\n        arma::eye(nDims, nDims)) * betaOpt - X * y.t();\n\n    LARSVerifyCorrectness(betaOpt, errCorr, lambda1);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(LARSTestLassoCholesky)\n{\n  LassoTest(100, 10, false, true);\n}\n\n\nBOOST_AUTO_TEST_CASE(LARSTestLassoGram)\n{\n  LassoTest(100, 10, false, false);\n}\n\nBOOST_AUTO_TEST_CASE(LARSTestElasticNetCholesky)\n{\n  LassoTest(100, 10, true, true);\n}\n\nBOOST_AUTO_TEST_CASE(LARSTestElasticNetGram)\n{\n  LassoTest(100, 10, true, false);\n}\n\n// Ensure that LARS doesn't crash when the data has linearly dependent features\n// (meaning that there is a singularity).  This test uses the Cholesky\n// factorization.\nBOOST_AUTO_TEST_CASE(CholeskySingularityTest)\n{\n  arma::mat X;\n  arma::mat Y;\n\n  data::Load(\"lars_dependent_x.csv\", X);\n  data::Load(\"lars_dependent_y.csv\", Y);\n\n  arma::rowvec y = Y.row(0);\n\n  // Test for a couple values of lambda1.\n  for (double lambda1 = 0.0; lambda1 < 1.0; lambda1 += 0.1)\n  {\n    LARS lars(true, lambda1, 0.0);\n    arma::vec betaOpt;\n    lars.Train(X, y, betaOpt);\n\n    arma::vec errCorr = (X * X.t()) * betaOpt - X * y.t();\n\n    LARSVerifyCorrectness(betaOpt, errCorr, lambda1);\n  }\n}\n\n// Same as the above test but with no cholesky factorization.\nBOOST_AUTO_TEST_CASE(NoCholeskySingularityTest)\n{\n  arma::mat X;\n  arma::mat Y;\n\n  data::Load(\"lars_dependent_x.csv\", X);\n  data::Load(\"lars_dependent_y.csv\", Y);\n\n  arma::rowvec y = Y.row(0);\n\n  // Test for a couple values of lambda1.\n  for (double lambda1 = 0.0; lambda1 < 1.0; lambda1 += 0.1)\n  {\n    LARS lars(false, lambda1, 0.0);\n    arma::vec betaOpt;\n    lars.Train(X, y, betaOpt);\n\n    arma::vec errCorr = (X * X.t()) * betaOpt - X * y.t();\n\n    // #373: this test fails on i386 only sometimes.\n//    LARSVerifyCorrectness(betaOpt, errCorr, lambda1);\n  }\n}\n\n// Make sure that Predict() provides reasonable enough solutions.\nBOOST_AUTO_TEST_CASE(PredictTest)\n{\n  for (size_t i = 0; i < 2; ++i)\n  {\n    // Run with both true and false.\n    bool useCholesky = bool(i);\n\n    arma::mat X;\n    arma::rowvec y;\n\n    GenerateProblem(X, y, 1000, 100);\n\n    for (double lambda1 = 0.0; lambda1 < 1.0; lambda1 += 0.2)\n    {\n      for (double lambda2 = 0.0; lambda2 < 1.0; lambda2 += 0.2)\n      {\n        LARS lars(useCholesky, lambda1, lambda2);\n        arma::vec betaOpt;\n        lars.Train(X, y, betaOpt);\n\n        // Calculate what the actual error should be with these regression\n        // parameters.\n        arma::vec betaOptPred = (X * X.t()) * betaOpt;\n        arma::rowvec predictions;\n        lars.Predict(X, predictions);\n        arma::vec adjPred = X * predictions.t();\n\n        BOOST_REQUIRE_EQUAL(predictions.n_elem, 1000);\n        for (size_t i = 0; i < betaOptPred.n_elem; ++i)\n        {\n          if (std::abs(betaOptPred[i]) < 1e-5)\n            BOOST_REQUIRE_SMALL(adjPred[i], 1e-5);\n          else\n            BOOST_REQUIRE_CLOSE(adjPred[i], betaOptPred[i], 1e-5);\n        }\n      }\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE(PredictRowMajorTest)\n{\n  arma::mat X;\n  arma::rowvec y;\n  GenerateProblem(X, y, 1000, 100);\n\n  // Set lambdas to 0.\n\n  LARS lars(false, 0, 0);\n  arma::vec betaOpt;\n  lars.Train(X, y, betaOpt);\n\n  // Get both row-major and column-major predictions.  Make sure they are the\n  // same.\n  arma::rowvec rowMajorPred, colMajorPred;\n\n  lars.Predict(X, colMajorPred);\n  lars.Predict(X.t(), rowMajorPred, true);\n\n  BOOST_REQUIRE_EQUAL(colMajorPred.n_elem, rowMajorPred.n_elem);\n  for (size_t i = 0; i < colMajorPred.n_elem; ++i)\n  {\n    if (std::abs(colMajorPred[i]) < 1e-5)\n      BOOST_REQUIRE_SMALL(rowMajorPred[i], 1e-5);\n    else\n      BOOST_REQUIRE_CLOSE(colMajorPred[i], rowMajorPred[i], 1e-5);\n  }\n}\n\n/**\n * Make sure that if we train twice, there is no issue.\n */\nBOOST_AUTO_TEST_CASE(RetrainTest)\n{\n  arma::mat origX;\n  arma::rowvec origY;\n  GenerateProblem(origX, origY, 1000, 50);\n\n  arma::mat newX;\n  arma::rowvec newY;\n  GenerateProblem(newX, newY, 750, 75);\n\n  LARS lars(false, 0.1, 0.1);\n  arma::vec betaOpt;\n  lars.Train(origX, origY, betaOpt);\n\n  // Now train on new data.\n  lars.Train(newX, newY, betaOpt);\n\n  arma::vec errCorr = (newX * trans(newX) + 0.1 *\n        arma::eye(75, 75)) * betaOpt - newX * newY.t();\n\n  LARSVerifyCorrectness(betaOpt, errCorr, 0.1);\n}\n\n/**\n * Make sure if we train twice using the Cholesky decomposition, there is no\n * issue.\n */\nBOOST_AUTO_TEST_CASE(RetrainCholeskyTest)\n{\n  arma::mat origX;\n  arma::rowvec origY;\n  GenerateProblem(origX, origY, 1000, 50);\n\n  arma::mat newX;\n  arma::rowvec newY;\n  GenerateProblem(newX, newY, 750, 75);\n\n  LARS lars(true, 0.1, 0.1);\n  arma::vec betaOpt;\n  lars.Train(origX, origY, betaOpt);\n\n  // Now train on new data.\n  lars.Train(newX, newY, betaOpt);\n\n  arma::vec errCorr = (newX * trans(newX) + 0.1 *\n        arma::eye(75, 75)) * betaOpt - newX * newY.t();\n\n  LARSVerifyCorrectness(betaOpt, errCorr, 0.1);\n}\n\n/**\n * Make sure that we get correct solution coefficients when running training\n * and accessing solution coefficients separately.\n */\nBOOST_AUTO_TEST_CASE(TrainingAndAccessingBetaTest)\n{\n  arma::mat X;\n  arma::rowvec y;\n\n  GenerateProblem(X, y, 1000, 100);\n\n  LARS lars1;\n  arma::vec beta;\n  lars1.Train(X, y, beta);\n\n  LARS lars2;\n  lars2.Train(X, y);\n\n  BOOST_REQUIRE_EQUAL(beta.n_elem, lars2.Beta().n_elem);\n  for (size_t i = 0; i < beta.n_elem; ++i)\n    BOOST_REQUIRE_CLOSE(beta[i], lars2.Beta()[i], 1e-5);\n}\n\n/**\n * Make sure that we learn the same when running training separately and through\n * constructor. Test it with default parameters.\n */\nBOOST_AUTO_TEST_CASE(TrainingConstructorWithDefaultsTest)\n{\n  arma::mat X;\n  arma::rowvec y;\n\n  GenerateProblem(X, y, 1000, 100);\n\n  LARS lars1;\n  arma::vec beta;\n  lars1.Train(X, y, beta);\n\n  LARS lars2(X, y);\n\n  BOOST_REQUIRE_EQUAL(beta.n_elem, lars2.Beta().n_elem);\n  for (size_t i = 0; i < beta.n_elem; ++i)\n    BOOST_REQUIRE_CLOSE(beta[i], lars2.Beta()[i], 1e-5);\n}\n\n/**\n * Make sure that we learn the same when running training separately and through\n * constructor. Test it with non default parameters.\n */\nBOOST_AUTO_TEST_CASE(TrainingConstructorWithNonDefaultsTest)\n{\n  arma::mat X;\n  arma::rowvec y;\n\n  GenerateProblem(X, y, 1000, 100);\n\n  bool transposeData = true;\n  bool useCholesky = true;\n  double lambda1 = 0.2;\n  double lambda2 = 0.4;\n\n  LARS lars1(useCholesky, lambda1, lambda2);\n  arma::vec beta;\n  lars1.Train(X, y, beta);\n\n  LARS lars2(X, y, transposeData, useCholesky, lambda1, lambda2);\n\n  BOOST_REQUIRE_EQUAL(beta.n_elem, lars2.Beta().n_elem);\n  for (size_t i = 0; i < beta.n_elem; ++i)\n    BOOST_REQUIRE_CLOSE(beta[i], lars2.Beta()[i], 1e-5);\n}\n\n/**\n * Test that LARS::Train() returns finite correlation value.\n */\nBOOST_AUTO_TEST_CASE(LARSTrainReturnCorrelation)\n{\n  arma::mat X;\n  arma::mat Y;\n\n  data::Load(\"lars_dependent_x.csv\", X);\n  data::Load(\"lars_dependent_y.csv\", Y);\n\n  arma::rowvec y = Y.row(0);\n\n  double lambda1 = 0.1;\n  double lambda2 = 0.1;\n\n  // Test with Cholesky decomposition and with lasso.\n  LARS lars1(true, lambda1, 0.0);\n  arma::vec betaOpt1;\n  double maxCorr = lars1.Train(X, y, betaOpt1);\n\n  BOOST_REQUIRE_EQUAL(std::isfinite(maxCorr), true);\n\n  // Test without Cholesky decomposition and with lasso.\n  LARS lars2(false, lambda1, 0.0);\n  arma::vec betaOpt2;\n  maxCorr = lars2.Train(X, y, betaOpt2);\n\n  BOOST_REQUIRE_EQUAL(std::isfinite(maxCorr), true);\n\n  // Test with Cholesky decomposition and with elasticnet.\n  LARS lars3(true, lambda1, lambda2);\n  arma::vec betaOpt3;\n  maxCorr = lars3.Train(X, y, betaOpt3);\n\n  BOOST_REQUIRE_EQUAL(std::isfinite(maxCorr), true);\n\n  // Test without Cholesky decomposition and with elasticnet.\n  LARS lars4(false, lambda1, lambda2);\n  arma::vec betaOpt4;\n  maxCorr = lars4.Train(X, y, betaOpt4);\n\n  BOOST_REQUIRE_EQUAL(std::isfinite(maxCorr), true);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "fd908a8ad64217c766e00f7f225073844ed16d8f", "size": 9885, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/lars_test.cpp", "max_stars_repo_name": "tomjpsun/mlpack", "max_stars_repo_head_hexsha": "39b9a852c58b648ddb9b87a3d87aa3db2bacbf0a", "max_stars_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-11T14:14:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-11T14:14:30.000Z", "max_issues_repo_path": "src/mlpack/tests/lars_test.cpp", "max_issues_repo_name": "tomjpsun/mlpack", "max_issues_repo_head_hexsha": "39b9a852c58b648ddb9b87a3d87aa3db2bacbf0a", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mlpack/tests/lars_test.cpp", "max_forks_repo_name": "tomjpsun/mlpack", "max_forks_repo_head_hexsha": "39b9a852c58b648ddb9b87a3d87aa3db2bacbf0a", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.650872818, "max_line_length": 80, "alphanum_fraction": 0.6604957006, "num_tokens": 3165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286833, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.4801515502674998}}
{"text": "#ifndef SKYLARK_MMT_HPP\n#define SKYLARK_MMT_HPP\n\n#ifndef SKYLARK_SKETCH_HPP\n#error \"Include top-level sketch.hpp instead of including individuals headers\"\n#endif\n\n#include <boost/random.hpp>\n\nnamespace skylark { namespace sketch {\n\n/**\n * Meng-Mahoney Transform\n *\n * Meng-Mahoney Transform is very similar to the Clarkson-Woodruff Transform:\n * it replaces the +1/-1 diagonal with Cauchy random enteries. Thus, it\n * provides a low-distortion of l1-norm subspace embedding.\n *\n * See Meng and Mahoney's STOC'13 paper.\n */\n\ntemplate < typename InputMatrixType,\n           typename OutputMatrixType = InputMatrixType >\nstruct MMT_t :\n        public MMT_data_t,\n        virtual public sketch_transform_t<InputMatrixType, OutputMatrixType > {\n\npublic:\n\n    // We use composition to defer calls to hash_transform_t\n    typedef hash_transform_t< InputMatrixType, OutputMatrixType,\n                              boost::random::uniform_int_distribution,\n                              boost::random::cauchy_distribution> transform_t;\n\n    typedef MMT_data_t data_type;\n    typedef data_type::params_t params_t;\n\n    MMT_t(int N, int S, base::context_t& context)\n        : data_type(N, S, context), _transform(*this) {\n\n    }\n\n    MMT_t(int N, int S, const params_t& params, base::context_t& context)\n        : data_type(N, S, params, context),\n          _transform(*this) {\n\n    }\n\n    MMT_t(const boost::property_tree::ptree& pt)\n        : data_type(pt), _transform(*this) {\n\n    }\n\n    template< typename OtherInputMatrixType,\n              typename OtherOutputMatrixType >\n    MMT_t(const MMT_t<OtherInputMatrixType,OtherOutputMatrixType>& other)\n        : data_type(other), _transform(*this) {\n\n    }\n\n    MMT_t(const data_type& other)\n        : data_type(other), _transform(*this) {\n\n    }\n\n    /**\n     * Apply columnwise the sketching transform that is described by the\n     * the transform with output sketch_of_A.\n     */\n    void apply (const typename transform_t::matrix_type& A,\n                typename transform_t::output_matrix_type& sketch_of_A,\n                columnwise_tag dimension) const {\n        _transform.apply(A, sketch_of_A, dimension);\n    }\n\n    /**\n     * Apply rowwise the sketching transform that is described by the\n     * the transform with output sketch_of_A.\n     */\n    void apply (const typename transform_t::matrix_type& A,\n                typename transform_t::output_matrix_type& sketch_of_A,\n                rowwise_tag dimension) const {\n        _transform.apply(A, sketch_of_A, dimension);\n    }\n\n    int get_N() const { return this->_N; } /**< Get input dimesion. */\n    int get_S() const { return this->_S; } /**< Get output dimesion. */\n\n    const sketch_transform_data_t* get_data() const { return this; }\n\nprivate:\n    transform_t _transform;\n};\n\ntemplate<>\nclass MMT_t<boost::any, boost::any> :\n  public MMT_data_t,\n  virtual public sketch_transform_t<boost::any, boost::any > {\n\npublic:\n\n    typedef MMT_data_t data_type;\n    typedef data_type::params_t params_t;\n\n    MMT_t(int N, int S, base::context_t& context)\n        : data_type(N, S, context) {\n\n    }\n\n    MMT_t(int N, int S, const params_t& params, base::context_t& context)\n        : data_type(N, S, params, context) {\n\n    }\n\n\n    MMT_t(const boost::property_tree::ptree &pt)\n        : data_type(pt) {\n\n    }\n\n    /**\n     * Copy constructor\n     */\n    template <typename OtherInputMatrixType,\n              typename OtherOutputMatrixType>\n    MMT_t (const MMT_t<OtherInputMatrixType, OtherOutputMatrixType>& other)\n        : data_type(other) {\n\n    }\n\n    /**\n     * Constructor from data\n     */\n    MMT_t (const data_type& other)\n        : data_type(other) {\n\n    }\n\n    /**\n     * Apply columnwise the sketching transform that is described by the\n     * the transform with output sketch_of_A.\n     */\n    void apply(const boost::any &A, const boost::any &sketch_of_A,\n                columnwise_tag dimension) const {\n\n#if     !(defined SKYLARK_NO_ANY) || (defined SKYLARK_WITH_MMT_ANY)\n\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::matrix_t, mdtypes::matrix_t,\n            MMT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::sparse_matrix_t,\n            mdtypes::matrix_t, MMT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::sparse_matrix_t,\n            mdtypes::sparse_matrix_t, MMT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::shared_matrix_t,\n            mdtypes::shared_matrix_t, MMT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::root_matrix_t,\n            mdtypes::root_matrix_t, MMT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::dist_matrix_t,\n            mdtypes::shared_matrix_t, MMT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::dist_matrix_t,\n            mdtypes::root_matrix_t, MMT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::dist_matrix_vc_star_t,\n            mdtypes::root_matrix_t, MMT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::dist_matrix_vc_star_t,\n            mdtypes::shared_matrix_t, MMT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::dist_matrix_vr_star_t,\n            mdtypes::root_matrix_t, MMT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::dist_matrix_vr_star_t,\n            mdtypes::shared_matrix_t, MMT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::dist_matrix_t,\n            mdtypes::dist_matrix_t, MMT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::dist_matrix_vc_star_t,\n            mdtypes::dist_matrix_vc_star_t, MMT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::dist_matrix_vr_star_t,\n            mdtypes::dist_matrix_vr_star_t, MMT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::dist_matrix_star_vc_t,\n            mdtypes::dist_matrix_star_vc_t, MMT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::dist_matrix_star_vr_t,\n            mdtypes::dist_matrix_star_vr_t, MMT_t);\n\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::matrix_t, mftypes::matrix_t,\n            MMT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::sparse_matrix_t,\n            mftypes::matrix_t, MMT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::sparse_matrix_t,\n            mftypes::sparse_matrix_t, MMT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::shared_matrix_t,\n            mftypes::shared_matrix_t, MMT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::root_matrix_t,\n            mftypes::root_matrix_t, MMT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::dist_matrix_t,\n            mftypes::shared_matrix_t, MMT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::dist_matrix_t,\n            mftypes::root_matrix_t, MMT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::dist_matrix_vc_star_t,\n            mftypes::root_matrix_t, MMT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::dist_matrix_vc_star_t,\n            mftypes::shared_matrix_t, MMT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::dist_matrix_vr_star_t,\n            mftypes::root_matrix_t, MMT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::dist_matrix_vr_star_t,\n            mftypes::shared_matrix_t, MMT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::dist_matrix_t,\n            mftypes::dist_matrix_t, MMT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::dist_matrix_vc_star_t,\n            mftypes::dist_matrix_vc_star_t, MMT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::dist_matrix_vr_star_t,\n            mftypes::dist_matrix_vr_star_t, MMT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::dist_matrix_star_vc_t,\n            mftypes::dist_matrix_star_vc_t, MMT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::dist_matrix_star_vr_t,\n            mftypes::dist_matrix_star_vr_t, MMT_t);\n\n#endif\n\n        SKYLARK_THROW_EXCEPTION (\n          base::sketch_exception()\n              << base::error_msg(\n                 \"This combination has not yet been implemented for MMT\"));\n\n    }\n\n    /**\n     * Apply rowwise the sketching transform that is described by the\n     * the transform with output sketch_of_A.\n     */\n    void apply (const boost::any &A, const boost::any &sketch_of_A,\n        rowwise_tag dimension) const {\n\n#if     !(defined SKYLARK_NO_ANY) || (defined SKYLARK_WITH_MMT_ANY)\n\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::matrix_t, mdtypes::matrix_t,\n            MMT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::sparse_matrix_t,\n            mdtypes::matrix_t, MMT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::sparse_matrix_t,\n            mdtypes::sparse_matrix_t, MMT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::shared_matrix_t,\n            mdtypes::shared_matrix_t, MMT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::root_matrix_t,\n            mdtypes::root_matrix_t, MMT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::dist_matrix_t,\n            mdtypes::shared_matrix_t, MMT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::dist_matrix_t,\n            mdtypes::root_matrix_t, MMT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::dist_matrix_vc_star_t,\n            mdtypes::root_matrix_t, MMT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::dist_matrix_vc_star_t,\n            mdtypes::shared_matrix_t, MMT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::dist_matrix_vr_star_t,\n            mdtypes::root_matrix_t, MMT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::dist_matrix_vr_star_t,\n            mdtypes::shared_matrix_t, MMT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::dist_matrix_t,\n            mdtypes::dist_matrix_t, MMT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::dist_matrix_vc_star_t,\n            mdtypes::dist_matrix_vc_star_t, MMT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::dist_matrix_vr_star_t,\n            mdtypes::dist_matrix_vr_star_t, MMT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::dist_matrix_star_vc_t,\n            mdtypes::dist_matrix_star_vc_t, MMT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::dist_matrix_star_vr_t,\n            mdtypes::dist_matrix_star_vr_t, MMT_t);\n\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::matrix_t, mftypes::matrix_t,\n            MMT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::sparse_matrix_t,\n            mftypes::matrix_t, MMT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::sparse_matrix_t,\n            mftypes::sparse_matrix_t, MMT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::shared_matrix_t,\n            mftypes::shared_matrix_t, MMT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::root_matrix_t,\n            mftypes::root_matrix_t, MMT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::dist_matrix_t,\n            mftypes::shared_matrix_t, MMT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::dist_matrix_t,\n            mftypes::root_matrix_t, MMT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::dist_matrix_vc_star_t,\n            mftypes::root_matrix_t, MMT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::dist_matrix_vc_star_t,\n            mftypes::shared_matrix_t, MMT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::dist_matrix_vr_star_t,\n            mftypes::root_matrix_t, MMT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::dist_matrix_vr_star_t,\n            mftypes::shared_matrix_t, MMT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::dist_matrix_t,\n            mftypes::dist_matrix_t, MMT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::dist_matrix_vc_star_t,\n            mftypes::dist_matrix_vc_star_t, MMT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::dist_matrix_vr_star_t,\n            mftypes::dist_matrix_vr_star_t, MMT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::dist_matrix_star_vc_t,\n            mftypes::dist_matrix_star_vc_t, MMT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::dist_matrix_star_vr_t,\n            mftypes::dist_matrix_star_vr_t, MMT_t);\n#endif\n\n        SKYLARK_THROW_EXCEPTION (\n          base::sketch_exception()\n              << base::error_msg(\n                 \"This combination has not yet been implemented for MMT\"));\n    }\n\n    int get_N() const { return this->_N; } /**< Get input dimesion. */\n    int get_S() const { return this->_S; } /**< Get output dimesion. */\n\n    const sketch_transform_data_t* get_data() const { return this; }\n};\n\n#undef _SL_HTBASE\n\n} } /** namespace skylark::sketch */\n\n#endif // SKYLARK_MMT_HPP\n", "meta": {"hexsha": "f4332ddb2350daedf1cf116f345de0cc2d35798d", "size": 12427, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sketch/MMT.hpp", "max_stars_repo_name": "xdata-skylark/libskylark", "max_stars_repo_head_hexsha": "89c3736136a24d519c14fc0738c21f37f1e10360", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 86.0, "max_stars_repo_stars_event_min_datetime": "2015-01-20T03:12:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-10T04:05:21.000Z", "max_issues_repo_path": "sketch/MMT.hpp", "max_issues_repo_name": "xdata-skylark/libskylark", "max_issues_repo_head_hexsha": "89c3736136a24d519c14fc0738c21f37f1e10360", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 48.0, "max_issues_repo_issues_event_min_datetime": "2015-05-12T09:31:23.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-05T14:45:46.000Z", "max_forks_repo_path": "sketch/MMT.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": 39.3259493671, "max_line_length": 79, "alphanum_fraction": 0.6935704514, "num_tokens": 3297, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4801235159719382}}
{"text": "/* ----------------------------------------------------------------------------\n * Copyright 2021, Jesus Tordesillas Torres, Aerospace Controls Laboratory\n * Massachusetts Institute of Technology\n * All Rights Reserved\n * Authors: Jesus Tordesillas, et al.\n * See LICENSE file for the license information\n * -------------------------------------------------------------------------- */\n\n#include <Eigen/StdVector>\n#include <stdio.h>\n#include <math.h>\n#include <algorithm>\n#include <vector>\n#include <stdlib.h>\n\n#include \"panther.hpp\"\n#include \"timer.hpp\"\n#include \"termcolor.hpp\"\n\nusing namespace termcolor;\n\n// Uncomment the type of timer you want:\n// typedef ROSTimer MyTimer;\n// typedef ROSWallTimer MyTimer;\ntypedef PANTHER_timers::Timer MyTimer;\n\nPanther::Panther(mt::parameters par) : par_(par)\n{\n  drone_status_ == DroneStatus::YAWING;\n  G_.pos << 0, 0, 0;\n  G_term_.pos << 0, 0, 0;\n\n  mtx_initial_cond.lock();\n  stateA_.setZero();\n  mtx_initial_cond.unlock();\n\n  changeDroneStatus(DroneStatus::GOAL_REACHED);\n  resetInitialization();\n\n  mt::basisConverter basis_converter;\n\n  if (par.basis == \"MINVO\")\n  {\n    A_basis_deg1_rest_ = basis_converter.getArestMinvoDeg1();\n    A_basis_deg2_rest_ = basis_converter.getArestMinvoDeg2();\n    A_basis_deg3_rest_ = basis_converter.getArestMinvoDeg3();\n  }\n  else if (par.basis == \"BEZIER\")\n  {\n    A_basis_deg1_rest_ = basis_converter.getArestBezierDeg1();\n    A_basis_deg2_rest_ = basis_converter.getArestBezierDeg2();\n    A_basis_deg3_rest_ = basis_converter.getArestBezierDeg3();\n  }\n  else if (par.basis == \"B_SPLINE\")\n  {\n    A_basis_deg1_rest_ = basis_converter.getArestBSplineDeg1();\n    A_basis_deg2_rest_ = basis_converter.getArestBSplineDeg2();\n    A_basis_deg3_rest_ = basis_converter.getArestBSplineDeg3();\n  }\n  else\n  {\n    std::cout << red << \"Basis \" << par.basis << \" not implemented yet\" << reset << std::endl;\n    std::cout << red << \"============================================\" << reset << std::endl;\n    abort();\n  }\n\n  A_basis_deg1_rest_inverse_ = A_basis_deg1_rest_.inverse();\n  A_basis_deg2_rest_inverse_ = A_basis_deg2_rest_.inverse();\n  A_basis_deg3_rest_inverse_ = A_basis_deg3_rest_.inverse();\n\n  log_ptr_ = std::shared_ptr<mt::log>(new mt::log);\n\n  solver_ = new SolverIpopt(par_, log_ptr_);\n\n  separator_solver_ = new separator::Separator();\n}\n\nvoid Panther::dynTraj2dynTrajCompiled(const mt::dynTraj& traj, mt::dynTrajCompiled& traj_compiled)\n{\n  if (traj.use_pwp_field == true)\n  {\n    traj_compiled.pwp_mean = traj.pwp_mean;\n    traj_compiled.pwp_var = traj.pwp_var;\n    traj_compiled.is_static =\n        ((traj.pwp_mean.eval(0.0) - traj.pwp_mean.eval(1e30)).norm() < 1e-5);  // TODO: Improve this\n  }\n  else\n  {\n    mtx_t_.lock();\n\n    typedef exprtk::symbol_table<double> symbol_table_t;\n    typedef exprtk::expression<double> expression_t;\n    typedef exprtk::parser<double> parser_t;\n\n    // Compile the mean\n    for (auto function_i : traj.s_mean)\n    {\n      symbol_table_t symbol_table;\n      symbol_table.add_variable(\"t\", t_);\n      symbol_table.add_constants();\n      expression_t expression;\n      expression.register_symbol_table(symbol_table);\n      parser_t parser;\n      parser.compile(function_i, expression);\n      traj_compiled.s_mean.push_back(expression);\n    }\n\n    // Compile the variance\n    for (auto function_i : traj.s_var)\n    {\n      symbol_table_t symbol_table;\n      symbol_table.add_variable(\"t\", t_);\n      symbol_table.add_constants();\n      expression_t expression;\n      expression.register_symbol_table(symbol_table);\n      parser_t parser;\n      parser.compile(function_i, expression);\n      traj_compiled.s_var.push_back(expression);\n    }\n\n    mtx_t_.unlock();\n\n    traj_compiled.is_static =\n        (traj.s_mean[0].find(\"t\") == std::string::npos) &&  // there is no dependence on t in the coordinate x\n        (traj.s_mean[1].find(\"t\") == std::string::npos) &&  // there is no dependence on t in the coordinate y\n        (traj.s_mean[2].find(\"t\") == std::string::npos);    // there is no dependence on t in the coordinate z\n  }\n\n  traj_compiled.use_pwp_field = traj.use_pwp_field;\n  traj_compiled.is_agent = traj.is_agent;\n  traj_compiled.bbox = traj.bbox;\n  traj_compiled.id = traj.id;\n  traj_compiled.time_received = traj.time_received;  // ros::Time::now().toSec();\n}\n\n// Note that this function is here because I need t_ for this evaluation\nEigen::Vector3d Panther::evalMeanDynTrajCompiled(const mt::dynTrajCompiled& traj, double t)\n{\n  Eigen::Vector3d tmp;\n\n  if (traj.use_pwp_field == true)\n  {\n    tmp = traj.pwp_mean.eval(t);\n  }\n  else\n  {\n    mtx_t_.lock();\n    t_ = t;\n    tmp << traj.s_mean[0].value(),  ////////////////\n        traj.s_mean[1].value(),     ////////////////\n        traj.s_mean[2].value();     ////////////////\n\n    mtx_t_.unlock();\n  }\n  return tmp;\n}\n\n// Note that this function is here because it needs t_ for this evaluation\nEigen::Vector3d Panther::evalVarDynTrajCompiled(const mt::dynTrajCompiled& traj, double t)\n{\n  Eigen::Vector3d tmp;\n\n  if (traj.use_pwp_field == true)\n  {\n    tmp = traj.pwp_var.eval(t);\n  }\n  else\n  {\n    mtx_t_.lock();\n    t_ = t;\n    tmp << traj.s_var[0].value(),  ////////////////\n        traj.s_var[1].value(),     ////////////////\n        traj.s_var[2].value();     ////////////////\n\n    mtx_t_.unlock();\n  }\n  return tmp;\n}\n\nvoid Panther::removeOldTrajectories()\n{\n  double time_now = ros::Time::now().toSec();\n  std::vector<int> ids_to_remove;\n\n  mtx_trajs_.lock();\n\n  for (int index_traj = 0; index_traj < trajs_.size(); index_traj++)\n  {\n    if ((time_now - trajs_[index_traj].time_received) > par_.max_seconds_keeping_traj)\n    {\n      ids_to_remove.push_back(trajs_[index_traj].id);\n    }\n  }\n\n  for (auto id : ids_to_remove)\n  {\n    // ROS_WARN_STREAM(\"Removing \" << id);\n    trajs_.erase(\n        std::remove_if(trajs_.begin(), trajs_.end(), [&](mt::dynTrajCompiled const& traj) { return traj.id == id; }),\n        trajs_.end());\n  }\n\n  mtx_trajs_.unlock();\n}\n\n// Note that we need to compile the trajectories inside panther.cpp because t_ is in panther.hpp\nvoid Panther::updateTrajObstacles(mt::dynTraj traj)\n{\n  MyTimer tmp_t(true);\n\n  if (started_check_ == true && traj.is_agent == true)\n  {\n    have_received_trajectories_while_checking_ = true;\n  }\n\n  // std::cout << on_blue << bold << \"in  updateTrajObstacles(), waiting to lock mtx_trajs_\" << reset << std::endl;\n  mtx_trajs_.lock();\n\n  std::vector<mt::dynTrajCompiled>::iterator obs_ptr =\n      std::find_if(trajs_.begin(), trajs_.end(),\n                   [=](const mt::dynTrajCompiled& traj_compiled) { return traj_compiled.id == traj.id; });\n\n  bool exists_in_local_map = (obs_ptr != std::end(trajs_));\n\n  mt::dynTrajCompiled traj_compiled;\n  dynTraj2dynTrajCompiled(traj, traj_compiled);\n\n  if (exists_in_local_map)\n  {  // if that object already exists, substitute its trajectory\n    *obs_ptr = traj_compiled;\n  }\n  else\n  {  // if it doesn't exist, add it to the local map\n    trajs_.push_back(traj_compiled);\n    // ROS_WARN_STREAM(\"Adding \" << traj_compiled.id);\n  }\n\n  // and now let's delete those trajectories of the obs/agents whose current positions are outside the local map\n  // Note that these positions are obtained with the trajectory stored in the past in the local map\n  std::vector<int> ids_to_remove;\n\n  double time_now = ros::Time::now().toSec();\n\n  for (int index_traj = 0; index_traj < trajs_.size(); index_traj++)\n  {\n    bool traj_affects_me = false;\n\n    Eigen::Vector3d center_obs = evalMeanDynTrajCompiled(trajs_[index_traj], time_now);\n\n    // mtx_t_.unlock();\n    if (((traj_compiled.is_static == true) && (center_obs - state_.pos).norm() > 2 * par_.Ra) ||  ////\n        ((traj_compiled.is_static == false) && (center_obs - state_.pos).norm() > 4 * par_.Ra))\n    // #### Static Obstacle: 2*Ra because: traj_{k-1} is inside a sphere of Ra.\n    // Then, in iteration k the point A (which I don't\n    // know yet)  is taken along that trajectory, and\n    // another trajectory of radius Ra will be obtained.\n    // Therefore, I need to take 2*Ra to make sure the\n    // extreme case (A taken at the end of traj_{k-1} is\n    // covered).\n\n    // #### Dynamic Agent: 4*Ra. Same reasoning as above, but with two agets\n    // #### Dynamic Obstacle: 4*Ra, it's a heuristics.\n\n    // ######REMEMBER######\n    // Note that removeTrajsThatWillNotAffectMe will later\n    // on take care of deleting the ones I don't need once\n    // I know A\n    {\n      ids_to_remove.push_back(trajs_[index_traj].id);\n    }\n  }\n\n  for (auto id : ids_to_remove)\n  {\n    // ROS_WARN_STREAM(\"Removing \" << id);\n    trajs_.erase(\n        std::remove_if(trajs_.begin(), trajs_.end(), [&](mt::dynTrajCompiled const& traj) { return traj.id == id; }),\n        trajs_.end());\n  }\n\n  mtx_trajs_.unlock();\n  // std::cout << red << bold << \"in updateTrajObstacles(), mtx_trajs_ unlocked\" << reset << std::endl;\n\n  have_received_trajectories_while_checking_ = false;\n  // std::cout << bold << blue << \"updateTrajObstacles took \" << tmp_t << reset << std::endl;\n}\n\nstd::vector<Eigen::Vector3d> Panther::vertexesOfInterval(mt::PieceWisePol& pwp, double t_start, double t_end,\n                                                         const Eigen::Vector3d& delta)\n{\n  std::vector<Eigen::Vector3d> points;\n\n  std::vector<double>::iterator low = std::lower_bound(pwp.times.begin(), pwp.times.end(), t_start);\n  std::vector<double>::iterator up = std::upper_bound(pwp.times.begin(), pwp.times.end(), t_end);\n\n  // Example: times=[1 2 3 4 5 6 7]\n  // t_start=1.5;\n  // t_end=5.5\n  // then low points to \"2\" (low - pwp.times.begin() is 1)\n  // and up points to \"6\" (up - pwp.times.begin() is 5)\n\n  int index_first_interval = low - pwp.times.begin() - 1;  // index of the interval [1,2]\n  int index_last_interval = up - pwp.times.begin() - 1;    // index of the interval [5,6]\n\n  saturate(index_first_interval, 0, (int)(pwp.all_coeff_x.size() - 1));\n  saturate(index_last_interval, 0, (int)(pwp.all_coeff_x.size() - 1));\n\n  // push all the complete intervals\n  for (int i = index_first_interval; i <= index_last_interval; i++)\n  {\n    Eigen::VectorXd coeff_x_scaled;\n    Eigen::VectorXd coeff_y_scaled;\n    Eigen::VectorXd coeff_z_scaled;\n\n    if (i == index_first_interval && i != index_last_interval)\n    {\n      double u_t_start = pwp.t2u(t_start);\n\n      changeDomPoly(pwp.all_coeff_x[i], u_t_start, 1.0, coeff_x_scaled, 0.0, 1.0);\n      changeDomPoly(pwp.all_coeff_y[i], u_t_start, 1.0, coeff_y_scaled, 0.0, 1.0);\n      changeDomPoly(pwp.all_coeff_z[i], u_t_start, 1.0, coeff_z_scaled, 0.0, 1.0);\n      std::cout << \"=====================================================\" << std::endl;\n      pwp.print();\n\n      // std::cout << red << bold << \"pwp.all_coeff_x[i]= \" << pwp.all_coeff_x[i].transpose() << reset << std::endl;\n      std::cout << red << bold << \"t_start= \" << t_start << reset << std::endl;\n      std::cout << red << bold << \"coeff_x_scaled= \" << coeff_x_scaled.transpose() << reset << std::endl;\n      std::cout << red << bold << \"u_t_start= \" << u_t_start << reset << std::endl;\n    }\n    else if (i == index_last_interval && i != index_first_interval)\n    {\n      double u_t_end = pwp.t2u(t_end);\n      changeDomPoly(pwp.all_coeff_x[i], 0.0, u_t_end, coeff_x_scaled, 0.0, 1.0);\n      changeDomPoly(pwp.all_coeff_y[i], 0.0, u_t_end, coeff_y_scaled, 0.0, 1.0);\n      changeDomPoly(pwp.all_coeff_z[i], 0.0, u_t_end, coeff_z_scaled, 0.0, 1.0);\n    }\n    else if (i == index_first_interval && i == index_last_interval)  // happens where there is only one interval\n    {\n      double u_t_start = pwp.t2u(t_start);\n      double u_t_end = pwp.t2u(t_end);\n      changeDomPoly(pwp.all_coeff_x[i], u_t_start, u_t_end, coeff_x_scaled, 0.0, 1.0);\n      changeDomPoly(pwp.all_coeff_y[i], u_t_start, u_t_end, coeff_y_scaled, 0.0, 1.0);\n      changeDomPoly(pwp.all_coeff_z[i], u_t_start, u_t_end, coeff_z_scaled, 0.0, 1.0);\n    }\n    else\n    {\n      coeff_x_scaled = pwp.all_coeff_x[i];\n      coeff_y_scaled = pwp.all_coeff_y[i];\n      coeff_z_scaled = pwp.all_coeff_z[i];\n    }\n\n    int deg = pwp.getDeg();\n    /// TODO\n    if (deg > 3)\n    {\n      std::cout << bold << red << \"The part below is assumming that degree<=3. You have deg=\" << pwp.getDeg()\n                << \" Aborting\" << reset << std::endl;\n      abort();\n    }\n    ////////\n\n    int tmp = coeff_x_scaled.size();\n\n    Eigen::Matrix<double, 3, -1> P(3, deg + 1);\n    Eigen::Matrix<double, 3, -1> V(3, deg + 1);  // 3 x number of vertexes of the simplex\n\n    P.row(0) = coeff_x_scaled;\n    P.row(1) = coeff_y_scaled;\n    P.row(2) = coeff_z_scaled;\n\n    // P = Eigen::Matrix<double, 3, 4>::Zero();\n    // (P.row(0)).tail(tmp) = coeff_x_scaled;\n    // (P.row(1)).tail(tmp) = coeff_y_scaled;\n    // (P.row(2)).tail(tmp) = coeff_z_scaled;\n\n    if (deg == 3)\n    {\n      V = P * A_basis_deg3_rest_inverse_;\n    }\n    else if (deg == 2)\n    {\n      V = P * A_basis_deg2_rest_inverse_;\n    }\n    else if (deg == 1)\n    {\n      V = P * A_basis_deg1_rest_inverse_;\n    }\n    else\n    {\n      // TODO\n      std::cout << \"Not implemented yet. Aborting\" << std::endl;\n      abort();\n    }\n\n    // std::cout << \"P= \\n\" << P << std::endl;\n    // std::cout << \"V= \\n\" << V << std::endl;\n\n    for (int j = 0; j < V.cols(); j++)\n    {\n      double x = V(0, j);\n      double y = V(1, j);\n      double z = V(2, j);  //[x,y,z] is the point\n\n      if (delta.norm() < 1e-6)\n      {  // no inflation\n        std::cout << \"No inflation\" << std::endl;\n        points.push_back(Eigen::Vector3d(x, y, z));\n      }\n      else\n      {\n        // points.push_back(Eigen::Vector3d(V(1, j), V(2, j), V(3, j)));  // x,y,z\n        points.push_back(Eigen::Vector3d(x + delta.x(), y + delta.y(), z + delta.z()));\n        points.push_back(Eigen::Vector3d(x + delta.x(), y - delta.y(), z - delta.z()));\n        points.push_back(Eigen::Vector3d(x + delta.x(), y + delta.y(), z - delta.z()));\n        points.push_back(Eigen::Vector3d(x + delta.x(), y - delta.y(), z + delta.z()));\n        points.push_back(Eigen::Vector3d(x - delta.x(), y - delta.y(), z - delta.z()));\n        points.push_back(Eigen::Vector3d(x - delta.x(), y + delta.y(), z + delta.z()));\n        points.push_back(Eigen::Vector3d(x - delta.x(), y + delta.y(), z - delta.z()));\n        points.push_back(Eigen::Vector3d(x - delta.x(), y - delta.y(), z + delta.z()));\n      }\n    }\n  }\n\n  return points;\n}\n\n// // return a vector that contains all the vertexes of the polyhedral approx of an interval.\nstd::vector<Eigen::Vector3d> Panther::vertexesOfInterval(mt::dynTrajCompiled& traj, double t_start, double t_end)\n{\n  // every side of the box will be increased by 2*delta (+delta on one end, -delta on the other)\n  // note that we use the variance at t_end (which is going to be higher that the one at t_start)\n  Eigen::Vector3d delta = traj.bbox / 2.0 + (par_.drone_radius) * Eigen::Vector3d::Ones() +  //////\n                          par_.norminv_prob * (evalVarDynTrajCompiled(traj, t_end)).cwiseSqrt();\n\n  if (traj.use_pwp_field == false)\n  {\n    std::vector<Eigen::Vector3d> points;\n\n    // Will always have a sample at the beginning of the interval, and another at the end.\n    for (double t = t_start;                           /////////////\n         (t < t_end) ||                                /////////////\n         ((t > t_end) && ((t - t_end) < par_.gamma));  /////// This is to ensure we have a sample a the end\n         t = t + par_.gamma)\n    {\n      Eigen::Vector3d tmp =\n          evalMeanDynTrajCompiled(traj, std::min(t, t_end));  // this min only has effect on the last sample\n\n      //\"Minkowski sum along the trajectory: box centered on the trajectory\"\n      points.push_back(Eigen::Vector3d(tmp.x() + delta.x(), tmp.y() + delta.y(), tmp.z() + delta.z()));\n      points.push_back(Eigen::Vector3d(tmp.x() + delta.x(), tmp.y() - delta.y(), tmp.z() - delta.z()));\n      points.push_back(Eigen::Vector3d(tmp.x() + delta.x(), tmp.y() + delta.y(), tmp.z() - delta.z()));\n      points.push_back(Eigen::Vector3d(tmp.x() + delta.x(), tmp.y() - delta.y(), tmp.z() + delta.z()));\n      points.push_back(Eigen::Vector3d(tmp.x() - delta.x(), tmp.y() - delta.y(), tmp.z() - delta.z()));\n      points.push_back(Eigen::Vector3d(tmp.x() - delta.x(), tmp.y() + delta.y(), tmp.z() + delta.z()));\n      points.push_back(Eigen::Vector3d(tmp.x() - delta.x(), tmp.y() + delta.y(), tmp.z() - delta.z()));\n      points.push_back(Eigen::Vector3d(tmp.x() - delta.x(), tmp.y() - delta.y(), tmp.z() + delta.z()));\n    }\n\n    return points;\n  }\n  else\n  {\n    return vertexesOfInterval(traj.pwp_mean, t_start, t_end, delta);\n  }\n}\n\n// See https://doc.cgal.org/Manual/3.7/examples/Convex_hull_3/quickhull_3.cpp\nCGAL_Polyhedron_3 Panther::convexHullOfInterval(mt::dynTrajCompiled& traj, double t_start, double t_end)\n{\n  std::vector<Eigen::Vector3d> points = vertexesOfInterval(traj, t_start, t_end);\n\n  std::vector<Point_3> points_cgal;\n  for (auto point_i : points)\n  {\n    points_cgal.push_back(Point_3(point_i.x(), point_i.y(), point_i.z()));\n  }\n\n  return convexHullOfPoints(points_cgal);\n}\n\n// trajs_ is already locked when calling this function\nvoid Panther::removeTrajsThatWillNotAffectMe(const mt::state& A, double t_start, double t_end)\n{\n  std::vector<int> ids_to_remove;\n\n  for (auto traj : trajs_)\n  {\n    bool traj_affects_me = false;\n\n    // STATIC OBSTACLES/AGENTS\n    if (traj.is_static == true)\n    {\n      Eigen::Vector3d center_obs =\n          evalMeanDynTrajCompiled(traj, t_start);  // Note that t_start is constant along the trajectory\n\n      Eigen::Vector3d positive_half_diagonal;\n      positive_half_diagonal << traj.bbox[0] / 2.0, traj.bbox[1] / 2.0, traj.bbox[2] / 2.0;\n\n      Eigen::Vector3d c1 = center_obs - positive_half_diagonal;\n      Eigen::Vector3d c2 = center_obs + positive_half_diagonal;\n      traj_affects_me = boxIntersectsSphere(A.pos, par_.Ra, c1, c2);\n    }\n    else\n    {                                                            // DYNAMIC OBSTACLES/AGENTS\n      double deltaT = (t_end - t_start) / (1.0 * par_.num_seg);  // num_seg is the number of intervals\n      for (int i = 0; i < par_.num_seg; i++)                     // for each interval\n      {\n        std::vector<Eigen::Vector3d> points =\n            vertexesOfInterval(traj, t_start + i * deltaT, t_start + (i + 1) * deltaT);\n\n        for (auto point_i : points)  // for every vertex of each interval\n        {\n          if ((point_i - A.pos).norm() <= par_.Ra)\n          {\n            traj_affects_me = true;\n            goto exit;\n          }\n        }\n      }\n    }\n\n  exit:\n    if (traj_affects_me == false)\n    {\n      // std::cout << red << bold << \"Going to  delete traj \" << trajs_[index_traj].id << reset << std::endl;\n      ids_to_remove.push_back(traj.id);\n    }\n  }\n\n  for (auto id : ids_to_remove)\n  {\n    // ROS_INFO_STREAM(\"traj \" << id << \" doesn't affect me\");\n    trajs_.erase(\n        std::remove_if(trajs_.begin(), trajs_.end(), [&](mt::dynTrajCompiled const& traj) { return traj.id == id; }),\n        trajs_.end());\n  }\n\n  /*  std::cout << \"After deleting the trajectory, we have these ids= \" << std::endl;\n\n    for (auto traj : trajs_)\n    {\n      std::cout << traj.id << std::endl;\n    }*/\n}\n\nbool Panther::IsTranslating()\n{\n  return (drone_status_ == DroneStatus::GOAL_SEEN || drone_status_ == DroneStatus::TRAVELING);\n}\n\nConvexHullsOfCurve Panther::convexHullsOfCurve(mt::dynTrajCompiled& traj, double t_start, double t_end)\n{\n  ConvexHullsOfCurve convexHulls;\n  double deltaT = (t_end - t_start) / (1.0 * par_.num_seg);  // num_seg is the number of intervals\n\n  for (int i = 0; i < par_.num_seg; i++)\n  {\n    convexHulls.push_back(convexHullOfInterval(traj, t_start + i * deltaT, t_start + (i + 1) * deltaT));\n  }\n\n  return convexHulls;\n}\n\nConvexHullsOfCurves Panther::convexHullsOfCurves(double t_start, double t_end)\n{\n  ConvexHullsOfCurves result;\n\n  for (auto traj : trajs_)\n  {\n    result.push_back(convexHullsOfCurve(traj, t_start, t_end));\n  }\n\n  return result;\n}\n\n// argmax_prob_collision is the index of trajectory I should focus on\n// a negative value means that there are no trajectories to track\nvoid Panther::sampleFeaturePosVel(int argmax_prob_collision, double t_start, double t_end,\n                                  std::vector<Eigen::Vector3d>& pos, std::vector<Eigen::Vector3d>& vel)\n{\n  pos.clear();\n  vel.clear();\n\n  double delta = (t_end - t_start) / par_.num_samples_simpson;\n\n  for (int i = 0; i < par_.num_samples_simpson; i++)\n  {\n    if (argmax_prob_collision >= 0)\n    {\n      double ti = t_start + i * delta;  // which is constant along the trajectory\n      Eigen::Vector3d pos_i = evalMeanDynTrajCompiled(trajs_[argmax_prob_collision], ti);\n\n      pos.push_back(pos_i);\n\n      // MyTimer timer(true);\n      // This commented part always returns 0.0. TODO: find out why. For now, let's use finite differences\n      // See also\n      // https://github.com/ArashPartow/exprtk/blob/66bed77369557fe1872df4c999c9d9ccb3adc3f6/readme.txt#LC4010:~:text=This%20free%20function%20will%20attempt%20to%20perform%20a%20numerical%20differentiation\n      // Eigen::Vector3d vel_i = Eigen::Vector3d(exprtk::derivative(trajs_[wt].function[0], \"t\"),  ////////////\n      //                                         exprtk::derivative(trajs_[wt].function[1], \"t\"),  ////////////\n      //                                         exprtk::derivative(trajs_[wt].function[2], t_));\n      // std::cout << \"time to take derivatives= \" << timer << std::endl;\n      // std::cout << on_green << bold << \"vel= \" << vel_i.transpose() << reset << std::endl;\n      // std::cout << on_green << bold << \"pos= \" << pos[i].transpose() << reset << std::endl;\n\n      // Use finite differences to obtain the derivative\n      double epsilon = 1e-6;\n\n      Eigen::Vector3d pos_i_epsilon = evalMeanDynTrajCompiled(trajs_[argmax_prob_collision], ti + epsilon);\n\n      vel.push_back((pos_i_epsilon - pos_i) / epsilon);\n\n      // std::cout << bold << \"Velocity= \" << vel[i].transpose() << reset << std::endl;\n      //////////////////////////////\n    }\n    else\n    {\n      pos.push_back(G_term_.pos);              // last_state_tracked_.pos\n      vel.push_back(Eigen::Vector3d::Zero());  // last_state_tracked_.vel\n    }\n  }\n\n  if (argmax_prob_collision < 0)\n  {\n    std::cout << bold << \"There is no dynamic obstacle to track\" << reset << std::endl;\n  }\n\n  last_state_tracked_.pos = pos.front();  // pos.back();\n  last_state_tracked_.vel = vel.front();  // vel.back();\n}\n\nvoid Panther::setTerminalGoal(mt::state& term_goal)\n{\n  mtx_G_term.lock();\n  G_term_ = term_goal;\n  mtx_G_term.unlock();\n\n  if (state_initialized_ == true)  // because I need plan_size()>=1\n  {\n    doStuffTermGoal();\n  }\n  else\n  {\n    std::cout << \"need_to_do_stuff_term_goal_= \" << need_to_do_stuff_term_goal_ << std::endl;\n    need_to_do_stuff_term_goal_ = true;  // will be done in updateState();\n  }\n}\n\nvoid Panther::getG(mt::state& G)\n{\n  G = G_;\n}\n\nvoid Panther::getState(mt::state& data)\n{\n  mtx_state.lock();\n  data = state_;\n  mtx_state.unlock();\n}\n\nvoid Panther::updateState(mt::state data)\n{\n  state_ = data;\n\n  if (state_initialized_ == false)\n  {\n    plan_.clear();  // (actually not needed because done in resetInitialization()\n    mt::state tmp;\n    tmp.pos = data.pos;\n    tmp.yaw = data.yaw;\n    plan_.push_back(tmp);\n  }\n\n  state_initialized_ = true;\n\n  if (need_to_do_stuff_term_goal_)\n  {\n    // std::cout << \"DOING STUFF TERM GOAL -----------\" << std::endl;\n    doStuffTermGoal();\n    need_to_do_stuff_term_goal_ = false;\n  }\n}\n\n// This function needs to be called once the state has been initialized\nvoid Panther::doStuffTermGoal()\n{\n  // if (state_initialized_ == false)  // because I need plan_size()>=1\n  // {\n  //   std::cout << \"[Panther::setTerminalGoal] State not initialized yet, doing nothing\" << std::endl;\n  //   return;\n  // }\n\n  // std::cout << \"[doStuffTermGoal]\" << std::endl;\n  mtx_G_term.lock();\n  mtx_state.lock();\n  mtx_planner_status_.lock();\n\n  G_.pos = G_term_.pos;\n  if (drone_status_ == DroneStatus::GOAL_REACHED)\n  {\n    /////////////////////////////////\n    mtx_plan_.lock();  // must be before changeDroneStatus\n\n    changeDroneStatus(DroneStatus::YAWING);\n    mt::state last_state = plan_.back();\n\n    double desired_yaw = atan2(G_term_.pos[1] - last_state.pos[1], G_term_.pos[0] - last_state.pos[0]);\n    double diff = desired_yaw - last_state.yaw;\n    angle_wrap(diff);\n\n    double dyaw =\n        copysign(1, diff) *\n        std::min(2.0, par_.ydot_max);  // par_.ydot_max; Changed to 0.5 (in HW the drone stops the motors when\n                                       // status==YAWING and ydot_max is too high, due to saturation + calibration of\n                                       // the ESCs) see https://gitlab.com/mit-acl/fsw/snap-stack/snap/-/issues/3\n\n    int num_of_el = (int)fabs(diff / (par_.dc * dyaw));\n\n    verify((plan_.size() >= 1), \"plan_.size() must be >=1\");\n\n    for (int i = 1; i < (num_of_el + 1); i++)\n    {\n      mt::state state_i = plan_.get(i - 1);\n      state_i.yaw = state_i.yaw + dyaw * par_.dc;\n      if (i == num_of_el)\n      {\n        state_i.dyaw = 0;  // 0 final yaw velocity\n      }\n      else\n      {\n        state_i.dyaw = dyaw;\n      }\n      plan_.push_back(state_i);\n    }\n    mtx_plan_.unlock();\n    /////////////////////////////////\n  }\n  if (drone_status_ == DroneStatus::GOAL_SEEN)\n  {\n    changeDroneStatus(DroneStatus::TRAVELING);\n  }\n  terminal_goal_initialized_ = true;\n\n  // std::cout << bold << red << \"[FA] Received Term Goal=\" << G_term_.pos.transpose() << reset << std::endl;\n  // std::cout << bold << red << \"[FA] Received Proj Goal=\" << G_.pos.transpose() << reset << std::endl;\n\n  mtx_state.unlock();\n  mtx_G_term.unlock();\n  mtx_planner_status_.unlock();\n}\n\nbool Panther::initializedAllExceptPlanner()\n{\n  if (!state_initialized_ || !terminal_goal_initialized_)\n  {\n    /*    std::cout << \"state_initialized_= \" << state_initialized_ << std::endl;\n        std::cout << \"terminal_goal_initialized_= \" << terminal_goal_initialized_ << std::endl;*/\n    return false;\n  }\n  return true;\n}\n\nbool Panther::initializedStateAndTermGoal()\n{\n  if (!state_initialized_ || !terminal_goal_initialized_)\n  {\n    return false;\n  }\n  return true;\n}\n\nbool Panther::initialized()\n{\n  if (!state_initialized_ || !terminal_goal_initialized_ || !planner_initialized_)\n  {\n    /*    std::cout << \"state_initialized_= \" << state_initialized_ << std::endl;\n        std::cout << \"terminal_goal_initialized_= \" << terminal_goal_initialized_ << std::endl;\n        std::cout << \"planner_initialized_= \" << planner_initialized_ << std::endl;*/\n    return false;\n  }\n  return true;\n}\n\n// check wheter a mt::dynTrajCompiled and a pwp_optimized are in collision in the interval [t_start, t_end]\nbool Panther::trajsAndPwpAreInCollision(mt::dynTrajCompiled traj, mt::PieceWisePol pwp_optimized, double t_start,\n                                        double t_end)\n{\n  Eigen::Vector3d n_i;\n  double d_i;\n\n  double deltaT = (t_end - t_start) / (1.0 * par_.num_seg);  // num_seg is the number of intervals\n  for (int i = 0; i < par_.num_seg; i++)                     // for each interval\n  {\n    // This is my trajectory (no inflation)\n    std::vector<Eigen::Vector3d> pointsA =\n        vertexesOfInterval(pwp_optimized, t_start + i * deltaT, t_start + (i + 1) * deltaT, Eigen::Vector3d::Zero());\n\n    // This is the trajectory of the other agent/obstacle\n    std::vector<Eigen::Vector3d> pointsB = vertexesOfInterval(traj, t_start + i * deltaT, t_start + (i + 1) * deltaT);\n\n    // std::cout << \"Going to solve model with pointsA.size()= \" << pointsA.size() << std::endl;\n    // for (auto point_i : pointsA)\n    // {\n    //   std::cout << point_i.transpose() << std::endl;\n    // }\n\n    // std::cout << \"Going to solve model with pointsB.size()= \" << pointsB.size() << std::endl;\n    // for (auto point_i : pointsB)\n    // {\n    //   std::cout << point_i.transpose() << std::endl;\n    // }\n\n    if (separator_solver_->solveModel(n_i, d_i, pointsA, pointsB) == false)\n    {\n      return true;  // There is not a solution --> they collide\n    }\n  }\n\n  // if reached this point, they don't collide\n  return false;\n}\n// Checks that I have not received new trajectories that affect me while doing the optimization\nbool Panther::safetyCheckAfterOpt(mt::PieceWisePol pwp_optimized)\n{\n  started_check_ = true;\n\n  bool result = true;\n  for (auto traj : trajs_)\n  {\n    if (traj.time_received > time_init_opt_ && traj.is_agent == true)\n    {\n      if (trajsAndPwpAreInCollision(traj, pwp_optimized, pwp_optimized.times.front(), pwp_optimized.times.back()))\n      {\n        ROS_ERROR_STREAM(\"Traj collides with \" << traj.id);\n        result = false;  // will have to redo the optimization\n        break;\n      }\n    }\n  }\n\n  // and now do another check in case I've received anything while I was checking. Note that mtx_trajs_ is locked!\n  if (have_received_trajectories_while_checking_ == true)\n  {\n    ROS_ERROR_STREAM(\"Recvd traj while checking \");\n    result = false;\n  }\n  started_check_ = false;\n\n  return result;\n}\n\nbool Panther::isReplanningNeeded()\n{\n  if (initializedStateAndTermGoal() == false)\n  {\n    return false;  // Note that log is not modified --> will keep its default values\n  }\n\n  //////////////////////////////////////////////////////////////////////////\n  mtx_G_term.lock();\n\n  mt::state G_term = G_term_;  // Local copy of the terminal terminal goal\n\n  mtx_G_term.unlock();\n\n  // Check if we have reached the goal\n  double dist_to_goal = (G_term.pos - plan_.front().pos).norm();\n  // std::cout << \"dist_to_goal= \" << dist_to_goal << std::endl;\n  if (dist_to_goal < par_.goal_radius)\n  {\n    changeDroneStatus(DroneStatus::GOAL_REACHED);\n    exists_previous_pwp_ = false;\n  }\n\n  // Check if we have seen the goal in the last replan\n  mtx_plan_.lock();\n  double dist_last_plan_to_goal = (G_term.pos - plan_.back().pos).norm();\n  // std::cout << \"dist_last_plan_to_goal= \" << dist_last_plan_to_goal << std::endl;\n  mtx_plan_.unlock();\n  if (dist_last_plan_to_goal < par_.goal_radius && drone_status_ == DroneStatus::TRAVELING)\n  {\n    changeDroneStatus(DroneStatus::GOAL_SEEN);\n    std::cout << \"Status changed to GOAL_SEEN!\" << std::endl;\n    exists_previous_pwp_ = false;\n  }\n\n  // Don't plan if drone is not traveling\n  if (drone_status_ == DroneStatus::GOAL_REACHED || (drone_status_ == DroneStatus::YAWING) ||\n      (drone_status_ == DroneStatus::GOAL_SEEN))\n  {\n    // std::cout << \"No replanning needed because\" << std::endl;\n    // printDroneStatus();\n    return false;\n  }\n  return true;\n}\n\nbool Panther::replan(mt::Edges& edges_obstacles_out, std::vector<mt::state>& X_safe_out,\n                     std::vector<Hyperplane3D>& planes, int& num_of_LPs_run, int& num_of_QCQPs_run,\n                     mt::PieceWisePol& pwp_out, mt::log& log)\n{\n  (*log_ptr_) = {};  // Reset the struct with the default values\n\n  mtx_G_term.lock();\n  mt::state G_term = G_term_;  // Local copy of the terminal terminal goal\n  mtx_G_term.unlock();\n\n  log_ptr_->pos = state_.pos;\n  log_ptr_->G_term_pos = G_term.pos;\n  log_ptr_->drone_status = drone_status_;\n\n  if (isReplanningNeeded() == false)\n  {\n    log_ptr_->replanning_was_needed = false;\n    log = (*log_ptr_);\n    return false;\n  }\n\n  std::cout << bold << on_white << \"**********************IN REPLAN CB*******************\" << reset << std::endl;\n\n  log_ptr_->replanning_was_needed = true;\n  log_ptr_->tim_total_replan.tic();\n\n  log_ptr_->tim_initial_setup.tic();\n\n  removeOldTrajectories();\n\n  //////////////////////////////////////////////////////////////////////////\n  ///////////////////////// Select mt::state A /////////////////////////////\n  //////////////////////////////////////////////////////////////////////////\n\n  mt::state A;\n  int k_index_end, k_index;\n\n  // If k_index_end=0, then A = plan_.back() = plan_[plan_.size() - 1]\n\n  mtx_plan_.lock();\n\n  saturate(deltaT_, par_.lower_bound_runtime_snlopt / par_.dc, par_.upper_bound_runtime_snlopt / par_.dc);\n\n  k_index_end = std::max((int)(plan_.size() - deltaT_), 0);\n\n  if (plan_.size() < 5)\n  {\n    k_index_end = 0;\n  }\n\n  k_index = plan_.size() - 1 - k_index_end;\n  A = plan_.get(k_index);\n\n  mtx_plan_.unlock();\n\n  // std::cout << blue << \"k_index:\" << k_index << reset << std::endl;\n  // std::cout << blue << \"k_index_end:\" << k_index_end << reset << std::endl;\n  // std::cout << blue << \"plan_.size():\" << plan_.size() << reset << std::endl;\n\n  double runtime_snlopt;\n\n  if (k_index_end != 0)\n  {\n    runtime_snlopt = k_index * par_.dc;  // std::min(, par_.upper_bound_runtime_snlopt);\n  }\n  else\n  {\n    runtime_snlopt = par_.upper_bound_runtime_snlopt;  // I'm stopped at the end of the trajectory\n  }\n  saturate(runtime_snlopt, par_.lower_bound_runtime_snlopt, par_.upper_bound_runtime_snlopt);\n\n  // std::cout << green << \"Runtime snlopt= \" << runtime_snlopt << reset << std::endl;\n\n  //////////////////////////////////////////////////////////////////////////\n  ///////////////////////// Get point G ////////////////////////////////////\n  //////////////////////////////////////////////////////////////////////////\n  double distA2TermGoal = (G_term.pos - A.pos).norm();\n  double ra = std::min((distA2TermGoal - 0.001), par_.Ra);  // radius of the sphere S\n  mt::state G;\n  G.pos = A.pos + ra * (G_term.pos - A.pos).normalized();\n\n  //////////////////////////////////////////////////////////////////////////\n  ///////////////////////// Set Times in optimization //////////////////////\n  //////////////////////////////////////////////////////////////////////////\n\n  solver_->setMaxRuntimeKappaAndMu(runtime_snlopt, par_.kappa, par_.mu);\n\n  //////////////////////\n  double time_now = ros::Time::now().toSec();\n\n  double t_start = k_index * par_.dc + time_now;\n\n  // double factor_alloc_tmp = par_.factor_alloc;\n\n  // std::cout << \"distA2TermGoal= \" << distA2TermGoal << std::endl;\n\n  //// when it's near the terminal goal --> force the final condition (if not it may oscillate)\n  // if (distA2TermGoal < par_.distance_to_force_final_pos)\n  // {\n  //   std::cout << \"distA2TermGoal= \" << distA2TermGoal << std::endl;\n  //   std::cout << bold << blue << \"Forcing final Pos\" << reset << std::endl;\n\n  //   factor_alloc_tmp = par_.factor_alloc_when_forcing_final_pos;\n  //   solver_->par_.c_final_pos = 0.0;  // Is a constraint --> don't care about this cost\n  //   solver_->par_.c_fov = 5.0;\n  //   solver_->par_.force_final_pos = true;\n  // }\n  // else\n  // {\n  // solver_->par_.c_final_pos = par_.c_final_pos;\n  // solver_->par_.c_fov = par_.c_fov;\n  // solver_->par_.force_final_pos = false;  // par_.force_final_pos;\n  // }\n\n  double time_allocated = getMinTimeDoubleIntegrator3D(A.pos, A.vel, G.pos, G.vel, par_.v_max, par_.a_max);\n\n  // std::cout << green << bold << \"Time allocated= \" << time_allocated << reset << std::endl;\n\n  double t_final = t_start + par_.factor_alloc * time_allocated;\n\n  /////////////////////////////////////////////////////////////////////////\n  ////////////////////////Compute trajectory to focus on //////////////////\n  /////////////////////////////////////////////////////////////////////////\n\n  double max_prob_collision = -std::numeric_limits<double>::max();  // it's actually a heuristics of the probability (we\n                                                                    // are summing below --> can be >1)\n  int argmax_prob_collision = -1;  // will contain the index of the trajectory to focus on\n\n  int num_samplesp1 = 20;\n  double delta = 1.0 / num_samplesp1;\n  Eigen::Vector3d R = par_.drone_radius * Eigen::Vector3d::Ones();\n\n  std::vector<double> all_probs;\n\n  mtx_trajs_.lock();\n  std::cout << green << bold << \"trajs_.size()= \" << trajs_.size() << reset << std::endl;\n  for (int i = 0; i < trajs_.size(); i++)\n  {\n    double prob_i = 0.0;\n    for (int j = 0; j <= num_samplesp1; j++)\n    {\n      double t = t_start + j * delta * (t_final - t_start);\n\n      Eigen::Vector3d pos_drone = A.pos + j * delta * (G_term_.pos - A.pos);  // not a random variable\n      Eigen::Vector3d pos_obs_mean = evalMeanDynTrajCompiled(trajs_[i], t);\n      Eigen::Vector3d pos_obs_std = (evalVarDynTrajCompiled(trajs_[i], t)).cwiseSqrt();\n      // std::cout << \"pos_obs_std= \" << pos_obs_std << std::endl;\n      prob_i += probMultivariateNormalDist(-R, R, pos_obs_mean - pos_drone, pos_obs_std);\n    }\n\n    all_probs.push_back(prob_i);\n    // std::cout << \"[Selection] Trajectory \" << i << \" has P(collision)= \" << prob_i * pow(10, 15) << \"e-15\" <<\n    // std::endl;\n\n    if (prob_i > max_prob_collision)\n    {\n      max_prob_collision = prob_i;\n      argmax_prob_collision = i;\n    }\n  }\n\n  std::cout << \"[Selection] Probs of coll --> \";\n  for (int i = 0; i < all_probs.size(); i++)\n  {\n    std::cout << all_probs[i] * pow(10, 15) << \"e-15,   \";\n  }\n  std::cout << std::endl;\n\n  // std::cout.precision(30);\n  std::cout << bold << \"[Selection] Chosen Trajectory \" << argmax_prob_collision\n            << \", P(collision)= \" << max_prob_collision * pow(10, 5) << \"e-5\" << std::endl;\n\n  ////\n\n  double angle = 3.14;\n  if (argmax_prob_collision >= 0)\n  {\n    Eigen::Vector3d A2G = G_term.pos - A.pos;\n    Eigen::Vector3d A2Obstacle = evalMeanDynTrajCompiled(trajs_[argmax_prob_collision], t_start) - A.pos;\n    angle = angleBetVectors(A2G, A2Obstacle);\n  }\n\n  // bool focus_on_obstacle = true;\n\n  double angle_deg = angle * 180 / 3.14;\n\n  if (fabs(angle_deg) > par_.angle_deg_focus_front)\n  {  //\n    std::cout << bold << yellow << \"[Selection] Focusing on front of me, angle=\" << angle_deg << \" deg\" << reset\n              << std::endl;\n    // focus_on_obstacle = false;\n    solver_->par_.c_final_yaw = 0.0;\n    solver_->par_.c_fov = 0.0;\n    solver_->par_.c_yaw_smooth = 0.0;\n    solver_->setFocusOnObstacle(false);\n    G.yaw = atan2(G_term_.pos[1] - A.pos[1], G_term_.pos[0] - A.pos[0]);\n    // solver_->use_straight_yaw_guess_ = true;\n  }\n  else\n  {\n    std::cout << bold << yellow << \"[Selection] Focusing on obstacle, angle=\" << angle_deg << \" deg\" << reset\n              << std::endl;\n    // focus_on_obstacle = true;\n    solver_->setFocusOnObstacle(true);\n    solver_->par_.c_fov = par_.c_fov;\n    solver_->par_.c_final_yaw = par_.c_final_yaw;\n    solver_->par_.c_yaw_smooth = par_.c_yaw_smooth;\n    // solver_->use_straight_yaw_guess_ = false;\n  }\n  ////\n\n  std::vector<Eigen::Vector3d> w_posfeature;      // velocity of the feature expressed in w\n  std::vector<Eigen::Vector3d> w_velfeaturewrtw;  // velocity of the feature wrt w, expressed in w\n  sampleFeaturePosVel(argmax_prob_collision, t_start, t_final, w_posfeature,\n                      w_velfeaturewrtw);  // need to do it here so that argmax_prob_collision does not become invalid\n                                          // with new updates\n\n  log_ptr_->tracking_now_pos = w_posfeature.front();\n  log_ptr_->tracking_now_vel = w_velfeaturewrtw.front();\n\n  mtx_trajs_.unlock();\n\n  //////////////////////////////////////////////////////////////////////////\n  ///////////////////////// Set init and final states //////////////////////\n  //////////////////////////////////////////////////////////////////////////\n  bool correctInitialCond =\n      solver_->setInitStateFinalStateInitTFinalT(A, G, t_start,\n                                                 t_final);  // note that here t_final may have been updated\n\n  if (correctInitialCond == false)\n  {\n    logAndTimeReplan(\"Solver cannot guarantee feasibility for v1\", false, log);\n    return false;\n  }\n\n  //////////////////////////////////////////////////////////////////////////\n  ///////////////////////// Solve optimization! ////////////////////////////\n  //////////////////////////////////////////////////////////////////////////\n\n  mtx_trajs_.lock();\n\n  time_init_opt_ = ros::Time::now().toSec();\n  // removeTrajsThatWillNotAffectMe(A, t_start, t_final);  // TODO: Commented (4-Feb-2021)\n  log_ptr_->tim_convex_hulls.tic();\n  ConvexHullsOfCurves hulls = convexHullsOfCurves(t_start, t_final);\n  log_ptr_->tim_convex_hulls.toc();\n\n  mtx_trajs_.unlock();\n\n  ConvexHullsOfCurves_Std hulls_std = vectorGCALPol2vectorStdEigen(hulls);\n  // poly_safe_out = vectorGCALPol2vectorJPSPol(hulls);\n  edges_obstacles_out = vectorGCALPol2edges(hulls);\n\n  solver_->setHulls(hulls_std);\n\n  solver_->setSimpsonFeatureSamples(w_posfeature, w_velfeaturewrtw);\n\n  //////////////////////\n  std::cout << on_cyan << bold << \"Solved so far\" << solutions_found_ << \"/\" << total_replannings_ << reset\n            << std::endl;\n\n  log_ptr_->tim_initial_setup.toc();\n  bool result = solver_->optimize();\n\n  num_of_LPs_run = solver_->getNumOfLPsRun();\n  num_of_QCQPs_run = solver_->getNumOfQCQPsRun();\n\n  total_replannings_++;\n  if (result == false)\n  {\n    logAndTimeReplan(\"Solver failed\", false, log);\n    return false;\n  }\n\n  solver_->getPlanes(planes);\n\n  solutions_found_++;\n\n  mt::PieceWisePol pwp_now;\n  solver_->getSolution(pwp_now);\n\n  MyTimer check_t(true);\n\n  mtx_trajs_.lock();\n  bool is_safe_after_opt = safetyCheckAfterOpt(pwp_now);\n  mtx_trajs_.unlock();\n\n  if (is_safe_after_opt == false)\n  {\n    logAndTimeReplan(\"SafetyCheckAfterOpt not satisfied\", false, log);\n    return false;\n  }\n\n  M_ = G_term;\n\n  //////////////////////////////////////////////////////////////////////////\n  ///////////////////////// Append to plan /////////////////////////////////\n  //////////////////////////////////////////////////////////////////////////\n  mtx_plan_.lock();\n\n  int plan_size = plan_.size();\n\n  if ((plan_size - 1 - k_index_end) < 0)\n  {\n    // std::cout << \"plan_size= \" << plan_size << std::endl;\n    // std::cout << \"k_index_end= \" << k_index_end << std::endl;\n    mtx_plan_.unlock();\n    logAndTimeReplan(\"Point A already published\", false, log);\n    return false;\n  }\n  else\n  {\n    plan_.erase(plan_.end() - k_index_end - 1, plan_.end());    // this deletes also the initial condition...\n    for (int i = 0; i < (solver_->traj_solution_).size(); i++)  //... which is included in traj_solution_[0]\n    {\n      plan_.push_back(solver_->traj_solution_[i]);\n    }\n  }\n\n  mtx_plan_.unlock();\n\n  ////////////////////\n  ////////////////////\n\n  if (exists_previous_pwp_ == true)\n  {\n    pwp_out = composePieceWisePol(time_now, par_.dc, pwp_prev_, pwp_now);\n    pwp_prev_ = pwp_out;\n  }\n  else\n  {  //\n    pwp_out = pwp_now;\n    pwp_prev_ = pwp_now;\n    exists_previous_pwp_ = true;\n  }\n\n  X_safe_out = plan_.toStdVector();\n\n  ///////////////////////////////////////////////////////////\n  ///////////////       OTHER STUFF    //////////////////////\n  //////////////////////////////////////////////////////////\n\n  // Check if we have planned until G_term\n  // mt::state F = plan_.back();  // Final point of the safe path (\\equiv final point of the comitted path)\n  double dist = (G_term_.pos - plan_.back().pos).norm();\n\n  if (dist < par_.goal_radius)\n  {\n    changeDroneStatus(DroneStatus::GOAL_SEEN);\n  }\n\n  planner_initialized_ = true;\n\n  logAndTimeReplan(\"Success\", true, log);\n  return true;\n}\n\nvoid Panther::logAndTimeReplan(const std::string& info, const bool& success, mt::log& log)\n{\n  log_ptr_->info_replan = info;\n  log_ptr_->tim_total_replan.toc();\n  log_ptr_->success_replanning = success;\n\n  double total_time_ms = log_ptr_->tim_total_replan.getMsSaved();\n\n  mtx_offsets.lock();\n  if (success == false)\n  {\n    std::cout << bold << red << log_ptr_->info_replan << reset << std::endl;\n    int states_last_replan = ceil(total_time_ms / (par_.dc * 1000));  // Number of states that\n                                                                      // would have been needed for\n                                                                      // the last replan\n    deltaT_ = std::max(par_.factor_alpha * states_last_replan, 1.0);\n    deltaT_ = std::min(1.0 * deltaT_, 2.0 / par_.dc);\n  }\n  else\n  {\n    int states_last_replan = ceil(total_time_ms / (par_.dc * 1000));  // Number of states that\n                                                                      // would have been needed for\n                                                                      // the last replan\n    deltaT_ = std::max(par_.factor_alpha * states_last_replan, 1.0);\n  }\n  mtx_offsets.unlock();\n\n  log = (*log_ptr_);\n}\n\nvoid Panther::resetInitialization()\n{\n  planner_initialized_ = false;\n  state_initialized_ = false;\n\n  terminal_goal_initialized_ = false;\n  plan_.clear();\n}\n\nbool Panther::getNextGoal(mt::state& next_goal)\n{\n  if (initializedStateAndTermGoal() == false)  // || (drone_status_ == DroneStatus::GOAL_REACHED && plan_.size() == 1))\n                                               // TODO: if included this part commented out, the last state (which is\n                                               // the one that has zero accel) will never get published\n  {\n    // std::cout << \"Not publishing new goal\" << std::endl;\n    // std::cout << \"plan_.size() ==\" << plan_.size() << std::endl;\n    // std::cout << \"plan_.content[0] ==\" << std::endl;\n    // plan_.content[0].print();\n    return false;\n  }\n\n  mtx_goals.lock();\n  mtx_plan_.lock();\n\n  next_goal.setZero();\n  next_goal = plan_.front();\n\n  if (plan_.size() > 1)\n  {\n    plan_.pop_front();\n  }\n\n  if (plan_.size() == 1 && drone_status_ == DroneStatus::YAWING)\n  {\n    changeDroneStatus(DroneStatus::TRAVELING);\n  }\n\n  if (par_.mode == \"ysweep\")\n  {\n    double t = ros::Time::now().toSec();\n    // double T = 1.0;\n    double amplitude_deg = 90;\n    double amplitude_rd = (amplitude_deg * M_PI / 180);\n    next_goal.yaw = amplitude_rd * sin(t * (par_.ydot_max / amplitude_rd));\n    next_goal.dyaw = par_.ydot_max * cos(t * (par_.ydot_max / amplitude_rd));\n  }\n\n  if (fabs(next_goal.dyaw) > (par_.ydot_max + 1e-4))\n  {\n    std::cout << red << \"par_.ydot_max not satisfied!!\" << reset << std::endl;\n    std::cout << red << \"next_goal.dyaw= \" << next_goal.dyaw << reset << std::endl;\n    std::cout << red << \"par_.ydot_max= \" << par_.ydot_max << reset << std::endl;\n    abort();\n  }\n\n  // verify(fabs(next_goal.dyaw) <= par_.ydot_max, \"par_.ydot_max not satisfied!!\");\n\n  mtx_goals.unlock();\n  mtx_plan_.unlock();\n  return true;\n}\n\n// Debugging functions\nvoid Panther::changeDroneStatus(int new_status)\n{\n  if (new_status == drone_status_)\n  {\n    return;\n  }\n\n  std::cout << \"Changing DroneStatus from \";\n  switch (drone_status_)\n  {\n    case DroneStatus::YAWING:\n      std::cout << bold << \"YAWING\" << reset;\n      break;\n    case DroneStatus::TRAVELING:\n      std::cout << bold << \"TRAVELING\" << reset;\n      break;\n    case DroneStatus::GOAL_SEEN:\n      std::cout << bold << \"GOAL_SEEN\" << reset;\n      break;\n    case DroneStatus::GOAL_REACHED:\n      std::cout << bold << \"GOAL_REACHED\" << reset;\n      break;\n  }\n  std::cout << \" to \";\n\n  switch (new_status)\n  {\n    case DroneStatus::YAWING:\n      std::cout << bold << \"YAWING\" << reset;\n      break;\n    case DroneStatus::TRAVELING:\n      std::cout << bold << \"TRAVELING\" << reset;\n      break;\n    case DroneStatus::GOAL_SEEN:\n      std::cout << bold << \"GOAL_SEEN\" << reset;\n      break;\n    case DroneStatus::GOAL_REACHED:\n      std::cout << bold << \"GOAL_REACHED\" << reset;\n      break;\n  }\n\n  std::cout << std::endl;\n\n  drone_status_ = new_status;\n}\n\nvoid Panther::printDroneStatus()\n{\n  switch (drone_status_)\n  {\n    case DroneStatus::YAWING:\n      std::cout << bold << \"status_=YAWING\" << reset << std::endl;\n      break;\n    case DroneStatus::TRAVELING:\n      std::cout << bold << \"status_=TRAVELING\" << reset << std::endl;\n      break;\n    case DroneStatus::GOAL_SEEN:\n      std::cout << bold << \"status_=GOAL_SEEN\" << reset << std::endl;\n      break;\n    case DroneStatus::GOAL_REACHED:\n      std::cout << bold << \"status_=GOAL_REACHED\" << reset << std::endl;\n      break;\n  }\n}\n", "meta": {"hexsha": "8c0c958894cfe517435df7fc0e7f4ef7ef767b2c", "size": 47562, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "panther/src/panther.cpp", "max_stars_repo_name": "mit-acl/panther", "max_stars_repo_head_hexsha": "8b6e446a4db5181ec4bd5826cadf553bb4889d64", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 79.0, "max_stars_repo_stars_event_min_datetime": "2021-03-12T03:08:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T09:43:14.000Z", "max_issues_repo_path": "panther/src/panther.cpp", "max_issues_repo_name": "NamDinhRobotics/panther", "max_issues_repo_head_hexsha": "385b9ac3775a8df7db17e69c6278f8fcab769507", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2021-03-15T05:22:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T08:54:12.000Z", "max_forks_repo_path": "panther/src/panther.cpp", "max_forks_repo_name": "NamDinhRobotics/panther", "max_forks_repo_head_hexsha": "385b9ac3775a8df7db17e69c6278f8fcab769507", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2021-03-14T06:18:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T09:43:12.000Z", "avg_line_length": 33.6602972399, "max_line_length": 206, "alphanum_fraction": 0.5985660822, "num_tokens": 13275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.4801235159719381}}
{"text": "#include \"AdaptiveLaw.hpp\"\n#include <Eigen/Dense>\n#include <stdexcept>\n\nusing namespace Eigen;\nusing namespace std;\n\nAdaptiveLaw::AdaptiveLaw(void)\n{\n    this->dt = 0.0;\n}\nAdaptiveLaw::~AdaptiveLaw(void)\n{\n    \n}\n\nvoid AdaptiveLaw::initialize(const AdaptiveLaw_Config_t _config)\n{\n    this->Gamma = _config.Gamma;\n    this->P = _config.P;\n    this->B = _config.B;\n    this->dt = _config.dt;\n    \n    reset();\n}\n\nvoid AdaptiveLaw::reset()\n{\n\tthis->BigTheta = MatrixXd::Zero(this->Gamma.rows(), this->B.cols());\n}\n\nvoid AdaptiveLaw::update(const VectorXd error, const VectorXd  phi)\n{\n    MatrixXd BigTheta_dot = this->Gamma * phi * error.transpose() * this->P * this->B;\n    this->BigTheta += BigTheta_dot * this->dt;\n}\n\nvoid AdaptiveLaw::get_gains(MatrixXd &outputs)\n{\n    outputs = this->BigTheta;\n}\n", "meta": {"hexsha": "e920bf8f11fbb8c9b60fb29e12af71ef39c06d1e", "size": 801, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "crazyflie_mrac_controllers/src/AdaptiveLaw.cpp", "max_stars_repo_name": "fjctp/crazyflie_mrac_ros", "max_stars_repo_head_hexsha": "d43df1832860addd0ff7fbad391c7871cb3c6577", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-10-09T03:17:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-24T06:00:12.000Z", "max_issues_repo_path": "crazyflie_mrac_controllers/src/AdaptiveLaw.cpp", "max_issues_repo_name": "fjctp/crazyflie_mrac_ros", "max_issues_repo_head_hexsha": "d43df1832860addd0ff7fbad391c7871cb3c6577", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "crazyflie_mrac_controllers/src/AdaptiveLaw.cpp", "max_forks_repo_name": "fjctp/crazyflie_mrac_ros", "max_forks_repo_head_hexsha": "d43df1832860addd0ff7fbad391c7871cb3c6577", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-05-24T22:48:29.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-24T22:48:29.000Z", "avg_line_length": 19.0714285714, "max_line_length": 86, "alphanum_fraction": 0.6729088639, "num_tokens": 220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.48012350982798707}}
{"text": "//=================================================================================================\n//                    Copyright (C) 2016 Olivier Mallet - All Rights Reserved                      \n//=================================================================================================\n\n#include \"../include/URT.hpp\"\n\n#ifndef USE_ARMA\n  #include <armadillo>\n#endif\n\n// define USE_FLOAT when compiling to switch to single precision\n#ifdef USE_FLOAT\n  using T = float;\n#else\n  using T = double;\n#endif\n\nint main()\n{\n   int niter = 0;\n\n   arma::wall_clock timer;\n\n   std::vector<int> sizes = {100,150,200,250,300,350,400,450,500,1000,1500,2000,2500,3000,3500,4000,4500,5000};\n\n   std::cout << std::fixed << std::setprecision(1);\n\n   for (int i = 0; i < sizes.size(); ++i) {\n\n      urt::Vector<T> data = urt::wiener_process<T>(sizes[i]);\n\n      (sizes[i] < 1000) ? niter = 10000 : niter = 1000;\n\n      timer.tic();\n      for (int k = 0; k < niter; ++k) {\n         urt::ADF<T> test(data, \"AIC\");\n         test.statistic();\n      }\n\n      auto duration = timer.toc();\n\n      std::cout << std::setw(8) << sizes[i];\n      std::cout << std::setw(8) << duration << \"\\n\";\n   }\n}\n", "meta": {"hexsha": "949d0641967426773bd4cdde895376f7b56b4045", "size": 1182, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "benchmark/benchmark.cpp", "max_stars_repo_name": "S-telescope2/URT", "max_stars_repo_head_hexsha": "1acf0c11ba96a8dc0ac12823c5571f8256617641", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 79.0, "max_stars_repo_stars_event_min_datetime": "2017-01-06T21:57:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T16:08:36.000Z", "max_issues_repo_path": "benchmark/benchmark.cpp", "max_issues_repo_name": "S-telescope2/URT", "max_issues_repo_head_hexsha": "1acf0c11ba96a8dc0ac12823c5571f8256617641", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2016-12-16T09:45:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-11T06:53:49.000Z", "max_forks_repo_path": "benchmark/benchmark.cpp", "max_forks_repo_name": "S-telescope2/URT", "max_forks_repo_head_hexsha": "1acf0c11ba96a8dc0ac12823c5571f8256617641", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20.0, "max_forks_repo_forks_event_min_datetime": "2017-02-02T12:23:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T17:02:57.000Z", "avg_line_length": 25.6956521739, "max_line_length": 111, "alphanum_fraction": 0.4644670051, "num_tokens": 316, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.48012350982798696}}
{"text": "//  Copyright Matt Borland 2021.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n//\n// A sanity check that this file\n// #includes all the files that it needs to.\n//\n#include <boost/math/interpolators/bezier_polynomial.hpp>\n//\n// Note this header includes no other headers, this is\n// important if this test is to be meaningful:\n//\n#include \"test_compile_result.hpp\"\n//\n// This test includes <vector> becasue many of the interpolators are not compatible with pointers/c-style arrays\n//\n#include <vector>\n\nvoid compile_and_link_test()\n{\n   std::vector<std::vector<double>> control_points {{0.0, 0.0}, {1.0, 1.0}};\n   auto bp = boost::math::interpolators::bezier_polynomial(std::move(control_points));\n\n   check_result<double>(bp(0)[0]);\n}\n", "meta": {"hexsha": "c02c5f5667a4f51ef6ff82bb18be0a2f91a9dcb4", "size": 880, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/compile_test/interpolators_bezier_polynomial_incl_test.cpp", "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": "test/compile_test/interpolators_bezier_polynomial_incl_test.cpp", "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": "test/compile_test/interpolators_bezier_polynomial_incl_test.cpp", "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": 32.5925925926, "max_line_length": 112, "alphanum_fraction": 0.7295454545, "num_tokens": 230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.48012350982798696}}
{"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/**\n * \\file joint_distribution_iid.hpp\n * \\date Febuary 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/traits.hpp>\n\n#include <fl/distribution/interface/moments.hpp>\n\nnamespace fl\n{\n\n// Forward declaration\ntemplate <typename...Distributions> class JointDistribution;\n\n/**\n * \\internal\n * Traits of JointDistribution<Distribution, Count>\n */\ntemplate <typename Distribution, int Count>\nstruct Traits<JointDistribution<MultipleOf<Distribution, Count>>>\n{\n    typedef typename Distribution::Variate MarginalVariate;\n\n    enum : signed int\n    {\n        MarginalCount = Count,\n        JointSize = ExpandSizes<SizeOf<MarginalVariate>::Value, Count>::Size\n    };\n\n    typedef typename MarginalVariate::Scalar Scalar;\n\n    typedef Eigen::Matrix<Scalar, JointSize, 1> Variate;\n};\n\n/**\n * \\ingroup distributions\n */\ntemplate <typename MarginalDistribution, int Count>\nclass JointDistribution<MultipleOf<MarginalDistribution, Count>>\n    : public Moments<\n                typename Traits<\n                    JointDistribution<MultipleOf<MarginalDistribution, Count>>\n                >::Variate>\n{\npublic:\n    /** Typdef of \\c This for #from_traits(TypeName) helper */\n    typedef JointDistribution This;\n\n    typedef typename Traits<This>::Variate Variate;\n    typedef typename Moments<Variate>::SecondMoment SecondMoment;\n    typedef Eigen::Array<MarginalDistribution, Count, 1> MarginalDistributions;\n\npublic:\n    explicit\n    JointDistribution(MarginalDistribution marginal,\n                      int count = ToDimension<Count>::Value)\n        : distributions_(MarginalDistributions(count, 1))\n    {\n        assert(count > 0);\n\n        for (int i = 0; i < distributions_.rows(); ++i)\n        {\n            distributions_(i) = marginal;\n        }\n\n        dimension_ = marginal.dimension() * count;\n    }\n\n    /**\n     * \\brief Overridable default destructor\n     */\n    virtual ~JointDistribution() noexcept { }\n\n    virtual Variate mean() const\n    {\n        Variate mu = Variate(dimension(), 1);\n\n        int offset = 0;\n        for (int i = 0; i < distributions_.size(); ++i)\n        {\n            const MarginalDistribution& marginal = distributions_(i);\n            int dim =  marginal.dimension();\n\n            mu.middleRows(offset, dim) = marginal.mean();\n\n            offset += dim;\n        }\n\n        return mu;\n    }\n\n    virtual SecondMoment covariance() const\n    {\n        SecondMoment cov = SecondMoment::Zero(dimension(), dimension());\n\n        int offset = 0;\n        for (int i = 0; i < distributions_.size(); ++i)\n        {\n            const MarginalDistribution& marginal = distributions_(i);\n            int dim =  marginal.dimension();\n\n            cov.block(offset, offset, dim, dim) = marginal.covariance();\n\n            offset += dim;\n        }\n\n        return cov;\n    }\n\n    virtual int dimension() const\n    {\n        return dimension_;\n    }\n\n    MarginalDistributions& distributions()\n    {\n        return distributions_;\n    }\n\n    const MarginalDistributions& distributions() const\n    {\n        return distributions_;\n    }\n\n    MarginalDistribution& distribution(int index)\n    {\n        assert(index < distributions_.size());\n        return distributions_(index);\n    }\n\n    const MarginalDistribution& distribution(int index) const\n    {\n        assert(index < distributions_.size());\n        return distributions_(index);\n    }\n\nprotected:\n    MarginalDistributions distributions_;\n    int dimension_;\n};\n\n}\n\n\n", "meta": {"hexsha": "c24eec65e3e62038976e2a288ca2aff43c997801", "size": 3952, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/fl/distribution/joint_distribution_iid.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/distribution/joint_distribution_iid.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/distribution/joint_distribution_iid.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": 23.6646706587, "max_line_length": 79, "alphanum_fraction": 0.637145749, "num_tokens": 857, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.4801235098279869}}
{"text": "/*\n * BSD 3-Clause License\n * Copyright (c) 2020, Rox\u00e1na Provender\n * All rights reserved.\n *\n * You may obtain a copy of the License at\n * https://opensource.org/licenses/BSD-3-Clause\n */\n\n#define _USE_MATH_DEFINES // for Windows to have M_PI\n#include <cmath>\n\n#include <boost/lexical_cast.hpp>\n#include \"Eigen/Geometry\"\n\n#include \"GPSHelper.h\"\n#include \"KalmanHelper.h\"\n#include \"CsvFileWriter.h\"\n#include \"TinyEKFHelper.h\"\n\n// No strptime for Windows :(\n// source: https://stackoverflow.com/questions/321849/strptime-equivalent-on-windows/321940\n#ifdef _WIN32\n#include <time.h>\n#include <iomanip>\n#include <sstream>\n\nextern \"C\" char* strptime(const char* s, const char* f, struct tm* tm)\n{\n  std::istringstream input(s);\n  input.imbue(std::locale(setlocale(LC_ALL, nullptr)));\n  input >> std::get_time(tm, f);\n  if (input.fail()) {\n    return nullptr;\n  }\n  return (char*)(s + input.tellg());\n}\n#endif\n\nnamespace olp\n{\nnamespace helper\n{\nnamespace gps\n{\n\nstatic const double DEG_TO_RAD = M_PI / 180;\nstatic const double EARTH_RADIUS_IN_METERS = 6372797.560856;\n\ndouble convert(const std::string& input)\n{\n    if (input == \"\")\n        return 0;\n\n    return boost::lexical_cast<double>(input);\n}\n\ndouble convertDegree(const std::string& input)\n{\n    std::vector<std::string> vec;\n    boost::algorithm::split(vec, input, boost::is_any_of(\" \"));\n\n    double degree = convert(vec[0]);\n    double minutes = convert(vec[1]) / 60;\n    double second = convert(vec[2]) / 3600;\n\n    return (degree + minutes + second);\n}\n\ndouble calculateAccuracy(double value)\n{\n    return (100 / 11) * (11.5 - value);\n}\n\nGPSStonex createStonex(std::vector<std::string>& data)\n{\n    GPSStonex gpsData = GPSStonex();\n\n    gpsData.id = ::atoi(data[0].c_str());\n    gpsData.latitude = convertDegree(data[1]);\n    gpsData.longitude = convertDegree(data[2]);\n    gpsData.elevation = convert(data[3]);\n    gpsData.cartesianX = convert(data[4]);\n    gpsData.cartesianY = convert(data[5]);\n    gpsData.cartesianZ = convert(data[6]);\n    gpsData.localN = convert(data[7]);\n    gpsData.localE = convert(data[8]);\n    gpsData.localZ = convert(data[9]);\n    gpsData.antennaHeight = data[10];\n    gpsData.pdop = convert(data[16]);\n    gpsData.hdop = convert(data[17]);\n    gpsData.vdop = convert(data[18]);\n\n    std::string date = data[22];\n    strptime(date.data(), \"%a. %d %b %Y %H:%M:%S\", &gpsData.datetime);\n    gpsData.secondsSinceReference = mktime(&gpsData.datetime) - 2 *  (60 * 60);\n    gpsData.accuracy = calculateAccuracy(gpsData.pdop * 0.5);\n\n    return gpsData;\n}\n\n\nGPS create(std::vector<std::string>& data)\n{\n    GPS gpsData = GPS();\n\n    gpsData.latitude = convert(data[2]);\n    gpsData.longitude = convert(data[3]);\n    gpsData.accuracy = calculateAccuracy(convert(data[4]));\n    gpsData.elevation = convert(data[5]);\n\n\n    std::string date = data[1];\n    strptime(date.data(), \"%Y-%m-%d %H:%M:%S\", &gpsData.datetime);\n    gpsData.secondsSinceReference = mktime(&gpsData.datetime) + (60 * 60);\n\n\n    return gpsData;\n}\n\nint getStartIndex(std::vector<GPS> gpsData, uint64_t time)\n{\n    int j = 0;\n    bool found = false;\n    while (!found && j < gpsData.size() - 1)\n    {\n        if (gpsData[j].secondsSinceReference < time)\n            j++;\n        else\n        {\n            found = calculateDistance(Point(gpsData[j].latitude, gpsData[j].longitude),\n                                      Point(gpsData[j + 1].latitude, gpsData[j + 1].longitude)) > 0.09;\n            j++;\n        }\n    }\n\n    return j;\n}\n\nstd::vector<GPS> kalmanFilter(std::vector<GPS>& gpsData, int startIndex, GPSSource source)\n{\n    std::vector<GPS> newData;\n\n    if (gpsData.size() == 0)\n        return newData;\n\n    TinyEKFHelper f = TinyEKFHelper();\n\n    Point newCoord;\n    GPS data = GPS();\n    int secondsSinceRefrence = gpsData[startIndex].secondsSinceReference;\n    int i = startIndex;\n    double prevAzimuth = 0, currentAzimuth, deltaAzimuth;\n    GPS prevData = gpsData[startIndex];\n    bool hasMatch;\n\n    while (i < gpsData.size())\n    {\n        if (i > startIndex)\n            secondsSinceRefrence++;\n\n        data.secondsSinceReference = secondsSinceRefrence;\n        if (secondsSinceRefrence == gpsData[i].secondsSinceReference)\n        {\n            //if(source == GPSSource::mobile)\n                f.setRMatrix((1000 - gpsData[i].accuracy) * 10);\n            //else\n               // f.setRMatrix(1000);\n\n            if(i == startIndex)\n                f.update(gpsData[i], gpsData[i]);\n            else\n                f.update(gpsData[i], newData[newData.size() - 1]);\n            data.accuracy = gpsData[i].accuracy;\n            i++;\n            hasMatch = true;\n        }\n        else\n        {\n            hasMatch = false;\n            f.update(gpsData[i], newData[newData.size() - 1]);\n            //data.accuracy = newData[newData.size() - 1].accuracy - 1;\n        }\n\n        newCoord = f.getNewCoord();\n        data.latitude = newCoord.x;\n        data.longitude = newCoord.y;\n        data.elevation = newCoord.z;\n\n        currentAzimuth = calculateAzimuth({data.latitude, data.longitude, data.elevation},\n                                          {prevData.latitude, prevData.longitude, prevData.elevation});\n        deltaAzimuth = abs(prevAzimuth - currentAzimuth);\n        prevAzimuth = currentAzimuth;\n        // penalty for points created by the filter making sharp turns\n        if(!hasMatch)\n            data.accuracy -= deltaAzimuth * 180;\n\n        prevData = data;\n        newData.push_back(data);\n    }\n\n    return newData;\n}\n\nstd::vector<GPS> read(const std::string& fileName, GPSSource source)\n{\n\n    std::ifstream file(fileName);\n    std::vector<GPS> gpsData;\n\n    std::string line;\n    std::vector<std::string> vec;\n\n    if (file.is_open())\n    {\n        getline(file, line);\n        while (getline(file, line))\n        {\n            boost::erase_all(line, \"\\\"\");\n            std::replace(line.begin(), line.end(), ',', '.');\n\n            boost::algorithm::split(vec, line, boost::is_any_of(\";\"));\n\n            switch (source)\n            {\n                case mobile:\n                    gpsData.push_back(create(vec));\n                    break;\n                case stonex:\n                    gpsData.push_back(createStonex(vec));\n                    break;\n            }\n        }\n        file.close();\n    }\n    return gpsData;\n}\n\nvoid write(const std::string& fileName, const std::vector<GPS>& gpsData)\n{\n    helper::csvfile csv(fileName);\n    csv << \"latitude\" << \"longitude\" << \"elevation\" << helper::endrow;\n    for (int i = 0; i < gpsData.size(); i++)\n    {\n        csv << gpsData[i].latitude << gpsData[i].longitude << gpsData[i].elevation << helper::endrow;\n    }\n}\n\nPoint calculateDistanceFromEOV(const Point& from, const Point& to)\n{\n    double diffY = to.y - from.y;\n    double diffX = to.x - from.x;\n\n    return Point(diffY, diffX);\n}\n\ndouble haversine(const Point& from, const Point& to)\n{\n    double dlong = (to.y - from.y) * DEG_TO_RAD;\n    double dlat = (to.x - from.x) * DEG_TO_RAD;\n    double a = pow(sin(dlat / 2.0), 2) + cos(from.x * DEG_TO_RAD) * cos(to.x * DEG_TO_RAD) * pow(sin(dlong / 2.0), 2);\n    double c = 2 * atan2(sqrt(a), sqrt(1 - a));\n\n    return c;\n}\n\ndouble calculateDistance(const Point& from, const Point& to)\n{\n    return EARTH_RADIUS_IN_METERS * haversine(from, to);\n}\n\ndouble calculateAngleOfElevation(double deltaXy, double deltaZ) {\n    return  atan2(deltaZ,deltaXy);\n    double d2 = (deltaZ) / deltaXy - deltaXy / (2*EARTH_RADIUS_IN_METERS);\n    double d3 = asin(deltaZ/deltaXy);\n}\n\nTransformData calculateTransformData(GPS& data1, GPS& data2, TransformData& actTransformation, GPSCoordType coordType)\n{\n    double deltaX, deltaY, deltaZ, angle, angleOfElevation = 0;\n    double actAngle = getRotZ(actTransformation.transform);\n    double actAngleOfElevation = getRotX(actTransformation.transform);\n    switch (coordType)\n    {\n        case latlong:\n            deltaY = calculateDistance(Point(data1.latitude, data1.longitude),\n                                       Point(data2.latitude, data1.longitude));\n            deltaX = calculateDistance(Point(data1.latitude, data1.longitude),\n                                       Point(data1.latitude, data2.longitude));\n\n            if (data2.longitude < data1.longitude) deltaX *= -1;\n            if (data2.latitude < data1.latitude) deltaY *= -1;\n            break;\n\n        case EOV:\n            Point EOVdistance = calculateDistanceFromEOV(Point(data1.localN, data1.localE),\n                                                         Point(data2.localN, data2.localE));\n            deltaX = EOVdistance.x;\n            deltaY = EOVdistance.y;\n            break;\n    }\n\n    if (deltaY != 0 || deltaX != 0)\n    {\n        angle = calculateAngle(deltaX, deltaY);\n        angle -= actAngle;\n    }\n\n    deltaZ = data2.elevation - data1.elevation;\n\n    if(deltaZ != 0)\n    {\n        double deltaXY = calculateDistance(Point(data1.latitude, data1.longitude),\n                                           Point(data2.latitude, data2.longitude));\n\n        angleOfElevation = calculateAngleOfElevation(deltaXY, deltaZ);\n        angleOfElevation -= actAngleOfElevation;\n    }\n\n    TransformData result = TransformData();\n    result.transform = Eigen::AngleAxisd(angle, Eigen::Vector3d::UnitZ()) *\n                       Eigen::AngleAxisd(angleOfElevation, Eigen::Vector3d::UnitX());\n    result.transform.translation() << deltaX, deltaY, deltaZ;\n    result.transform.translation() = actTransformation.transform.rotation().inverse() * result.transform.translation();\n    return result;\n}\n\ndouble calculateAzimuth(const Point& from, const Point& to)\n{\n\n    double fromXRad = from.x * DEG_TO_RAD;\n    double toXRad = to.x * DEG_TO_RAD;\n    double toYRad = to.y * DEG_TO_RAD;\n    double fromYRad = from.y * DEG_TO_RAD;\n    double longDiffRad = (toYRad - fromYRad);\n\n    double theta = atan2(sin(longDiffRad) * cos(toXRad),\n                         cos(fromXRad) * sin(toXRad) - sin(fromXRad) * cos(toXRad) * cos(longDiffRad));\n    return theta;\n}\n\ndouble calculateAngle(const Point& from, const Point& to)\n{\n\n    double dot = from.x * to.x + from.y * to.y;\n    double det = from.x * to.y - from.y * to.x;\n\n    double delta = atan2(det, dot);\n    return delta;\n}\n\ndouble calculateAngle(double dx, double dy)\n{\n    if (dx != 0 && dy != 0)\n        return (M_PI) - atan(dx / dy);\n    if (dx > 0)\n        return M_PI / 2;\n    if (dx < 0)\n        return M_PI / 2 * -1;\n    if (dy > 0)\n        return 0;\n    if (dy < 0)\n        return M_PI;\n\n    return -1;\n}\n\n\nvoid displayDistances(const MapPointVector& mp, int v1, int v2)\n{\n    MapPointVector::const_iterator it1 = mp.find(v1);\n    MapPointVector::const_iterator it2 = mp.find(v2);\n    if (it1 != mp.end() && it2 != mp.end())\n    {\n        const PointVector& vec1 = it1->second;\n        const PointVector& vec2 = it2->second;\n        for (size_t i = 0; i < vec1.size(); ++i)\n        {\n            for (size_t j = 0; j < vec2.size(); ++j)\n                std::cout << calculateDistance(vec1[i], vec2[j]) << \"\\n\";\n        }\n    }\n}\n\n} // gps\n} // helper\n} // olp\n", "meta": {"hexsha": "181bbe19d872be51b6b06124072810737bc7d1a8", "size": 11073, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "helpers/GPSHelper.cpp", "max_stars_repo_name": "mcserep/olp", "max_stars_repo_head_hexsha": "8d195f0ec858acc265eb24a447fc6408142a063c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-11-17T06:07:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-20T06:24:15.000Z", "max_issues_repo_path": "helpers/GPSHelper.cpp", "max_issues_repo_name": "mcserep/olp", "max_issues_repo_head_hexsha": "8d195f0ec858acc265eb24a447fc6408142a063c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "helpers/GPSHelper.cpp", "max_forks_repo_name": "mcserep/olp", "max_forks_repo_head_hexsha": "8d195f0ec858acc265eb24a447fc6408142a063c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-28T20:12:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-28T20:12:48.000Z", "avg_line_length": 28.5386597938, "max_line_length": 119, "alphanum_fraction": 0.598482796, "num_tokens": 2885, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384736, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.48012350368403567}}
{"text": "// Copyright 2020 Norwegian University of Science and 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#pragma once\n\n#include <ceres/ceres.h>\n#include <ceres/rotation.h>\n#include <Eigen/Core>\n\n#include <glog/logging.h>\n#include <iostream>\n\nnamespace eris::hand_eye_calibration\n{\nclass CostFunctor\n{\npublic:\n  CostFunctor(const Eigen::Vector4d& qi, const Eigen::Vector3d& ti, const Eigen::Vector3d& pi, const Eigen::Vector4d& qj, const Eigen::Vector3d& tj,\n              const Eigen::Vector3d& pj)\n    : qi_(qi), ti_(ti), pi_(pi), qj_(qj), tj_(tj), pj_(pj)\n  {\n  }\n\n  template <typename T>\n  auto operator()(const T* const qx, const T* const tx, T* residual) const -> bool\n  {\n    Eigen::Matrix<T, 4, 1> qi = qi_.cast<T>();\n    Eigen::Matrix<T, 3, 1> ti = ti_.cast<T>();\n    Eigen::Matrix<T, 3, 1> pi = pi_.cast<T>();\n    Eigen::Matrix<T, 4, 1> qj = qj_.cast<T>();\n    Eigen::Matrix<T, 3, 1> tj = tj_.cast<T>();\n    Eigen::Matrix<T, 3, 1> pj = pj_.cast<T>();\n\n    Eigen::Matrix<T, 3, 1> ppi;\n    Eigen::Matrix<T, 3, 1> pppi;\n    ceres::QuaternionRotatePoint(qx, pi.data(), ppi.data());\n    ppi(0) += tx[0];\n    ppi(1) += tx[1];\n    ppi(2) += tx[2];\n    ceres::QuaternionRotatePoint(qi.data(), ppi.data(), pppi.data());\n    pppi(0) += ti[0];\n    pppi(1) += ti[1];\n    pppi(2) += ti[2];\n\n    Eigen::Matrix<T, 3, 1> ppj;\n    Eigen::Matrix<T, 3, 1> pppj;\n    ceres::QuaternionRotatePoint(qx, pj.data(), ppj.data());\n    ppj(0) += tx[0];\n    ppj(1) += tx[1];\n    ppj(2) += tx[2];\n    ceres::QuaternionRotatePoint(qj.data(), ppj.data(), pppj.data());\n    pppj(0) += tj[0];\n    pppj(1) += tj[1];\n    pppj(2) += tj[2];\n\n    residual[0] = pppj(0) - pppi(0);\n    residual[1] = pppj(1) - pppi(1);\n    residual[2] = pppj(2) - pppi(2);\n    return true;\n  }\n\nprivate:\n  const Eigen::Vector4d qi_;\n  const Eigen::Vector3d ti_;\n  const Eigen::Vector3d pi_;\n  const Eigen::Vector4d qj_;\n  const Eigen::Vector3d tj_;\n  const Eigen::Vector3d pj_;\n};\n\nclass Solver\n{\npublic:\n  Solver(const Eigen::Vector4d& q_init, const Eigen::Vector3d t_init) : q_opt_(q_init), t_opt_(t_init)\n  {\n  }\n\n  auto AddResidualBlock(const Eigen::Vector4d&, const Eigen::Vector3d&, const Eigen::Vector3d&, const Eigen::Vector4d&, const Eigen::Vector3d&,\n                        const Eigen::Vector3d&) -> bool;\n\n  auto Solve() -> std::tuple<Eigen::Vector4d, Eigen::Vector3d>;\n\n  auto Summary() -> ceres::Solver::Summary;\n\n  auto Options() -> ceres::Solver::Options;\n\nprivate:\n  ceres::Problem problem_;\n  ceres::Solver::Options options_;\n  ceres::Solver::Summary summary_;\n\n  bool local_parameterization_is_set_ = false;\n\n  Eigen::Vector4d q_opt_;\n  Eigen::Vector3d t_opt_;\n};\n}  // namespace eris::hand_eye_calibration", "meta": {"hexsha": "4f8a1890b986f96d26d8ac2bce39ed6f5a34708e", "size": 3197, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/eris/solver.hpp", "max_stars_repo_name": "Datsmir/eris-calibration", "max_stars_repo_head_hexsha": "3af4691b948fb076e2bb49bd1e367bd6315beae6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-09-22T16:41:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-23T03:40:31.000Z", "max_issues_repo_path": "include/eris/solver.hpp", "max_issues_repo_name": "Datsmir/eris-calibration", "max_issues_repo_head_hexsha": "3af4691b948fb076e2bb49bd1e367bd6315beae6", "max_issues_repo_licenses": ["Apache-2.0"], "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/eris/solver.hpp", "max_forks_repo_name": "Datsmir/eris-calibration", "max_forks_repo_head_hexsha": "3af4691b948fb076e2bb49bd1e367bd6315beae6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-02-04T11:38:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T01:50:40.000Z", "avg_line_length": 29.6018518519, "max_line_length": 148, "alphanum_fraction": 0.6427901157, "num_tokens": 1029, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384735, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.48012350368403556}}
{"text": "#define _USE_MATH_DEFINES\n\n#include <fstream>\n#include <iostream>\n#include <iomanip>  // std::setw\n#include <omp.h>\n#include <cmath>\n#include <cstdio>\n#include <chrono>\n#include <string>\n#include <armadillo>\n#include <vector>\n#include \"wignerSymbols.h\"\n//#include \"wigner/gaunt.hpp\"\n\nusing namespace std;\nusing namespace arma;\n\nstatic const double kB = 1.3806504e-23;         // J/K\nstatic const double NA = 6.02214179e23;         // 1/mol\nstatic const double EHARTREE = 4.35974434e-18;  // J/Hartree\nstatic const double AMU = 1.660538921e-27;      // kg/amu\nstatic const double HBAR = 1.054571726e-34;     // J.s\nstatic const double HBAR1 = HBAR / EHARTREE;    // Hartree.s\nstatic const double HBAR2 = HBAR * 1e20 / AMU;  // amu.\u00c5^2/s\nstatic const double HARTREE2KCALMOL = EHARTREE*NA/4184; // kcal/mol\nstatic const double SCH4 = 186.25; // J/mol.K\n\nMat<complex<double>> getHamiltonian(int lmax, double Ix, double Iy, double Iz, vector<complex<double>>& a, int seriesLmax);\nSpMat<double> getSparseHam(int lmax, double Ix, double Iy, double Iz, vector<complex<double>>& a);\n//Col<double> getCoefficients(string sysname);\nvector<complex<double>> getWignerCoeffs(string sysname, bool freeRotor);\nvector<double> getMomentOfInertia(string sysname=\"METH-CHA\");\ndouble getSymNum(string sysname);\nint getExpansionLmax(string sysname, bool freeRotor);\nstring getDirectory(string sysname);\nCol<double> getEnergyEigvals(Mat<complex<double>>& H);\nvector<double> getThermo(double T, Col<double>& eigvals, double sym=1, double refE=0);\n//double getPartitionFunction(double T, Mat<complex<double>>& H, double sym=1);\ndouble getSparseQ(double T, SpMat<double>& H, int sym=1);\n\nint main(int argc, char** argv) {\n    /* argv[0]  Program name\n     * argv[1]  System name\n     * argv[2]  Lmax (start)\n     * argv[3]  free-rotor\n     * argv[4]  temperature / K\n     */\n    if (argc != 5) {\n        throw runtime_error(\"Enter systemName as it appears in data directory, Lmax, free-rotor flag, temperature in Kelvin\");\n    }\n\n    /* Extract molecular information */\n    string sysname = argv[1];\n    bool freeRotor = stoi(argv[3]);\n    cout << \"bool freeRotor = \" << freeRotor << endl;\n    double T = stod(argv[4]);\n    string dirname = getDirectory(sysname);\n    cout << \"Directory containing data is: \" << dirname << endl;\n    vector<complex<double>> a = getWignerCoeffs(sysname, freeRotor);\n    //double refE = a.at(0).real();\n    //cout << \"Using reference energy of lowest coefficient: \" << refE << endl;\n    double refE = 0;\n    double sigma = getSymNum(sysname);\n    int seriesLmax = getExpansionLmax(sysname, freeRotor);\n    cout << \"Symmetry number for system \" << sysname << \" is \" <<  sigma << '.' << endl;\n    cout << \"Expansion series has an LMax of \" << seriesLmax << '.' << endl;\n\n    /* Moments of Inertia */\n    vector<double> Ivec = getMomentOfInertia(sysname);\n    cout << \"Moments of Inertia:\" << endl;\n    for (double i : Ivec) {\n        cout << i << '\\t';\n    }\n    cout << endl;\n \n    /*\n     *  Rotational Constants + Classical Partition Function\n     */\n    double B = HBAR1*HBAR2/(2.0*Ivec[2]);\n    double A = HBAR1*HBAR2/(2.0*Ivec[1]);\n    double C = HBAR1*HBAR2/(2.0*Ivec[0]);\n    //cout << \"kB T / Hartree:\\n\" << kB * 298 / EHARTREE << endl;\n    cout << \"Qapprox = \" << sqrt(M_PI)/sigma * sqrt(pow(kB*T/EHARTREE, 3) / (A*B*C)) << endl;  \n\n    /*\n     *  Dense Matrix Implementation \n     */\n    bool converge = false;\n    bool dense = true;\n    int lmax = atoi(argv[2]);\n    double Q;\n    double ZPE;\n    double U;\n    double S;\n    double Qprev = 0;\n    double Uprev = 0;\n    double Sprev = 0;\n    vector<double> thermo;\n    cout << left << setw(15) << \"Lmax\" << setw(15) << \"Q\" << setw(15) << \"ZPE [Hartree]\" << setw(15) << \n        \"U [kcal/mol]\" << setw(15) << \"S [cal/mol.K]\" << setw(20) <<\n        \"Constr.Time [s]\" << setw(16) << \"Diag.Time [s]\" << setw(16) << \"Time [s]\" << setw(16) << \"dQ\" << endl;\n    auto start = chrono::high_resolution_clock::now();\n    auto qmid = chrono::high_resolution_clock::now();\n    do {\n        auto qstart = chrono::high_resolution_clock::now();\n        if (dense) {\n            /****  Dense Matrix Implementation  ****/\n            Mat<complex<double>> H = getHamiltonian(lmax, Ivec[0], Ivec[1], Ivec[2], a, seriesLmax);\n            qmid = chrono::high_resolution_clock::now();\n            if (!H.is_hermitian(1e-5)) {\n                cout << \"NOT HERMITIAN:\" <<  endl;\n                H.brief_print(\"H = \");\n            }\n            //Q = getPartitionFunction(T, H, sigma);\n            Col<double> eigvals = getEnergyEigvals(H);\n            thermo = getThermo(T, eigvals, sigma, refE);\n            Q = thermo[0];\n            ZPE = thermo[1];\n            U = thermo[2];\n            S = thermo[3];\n        } else {\n            /****  Sparse Matrix Implementation  ****/\n            SpMat<double> H = getSparseHam(lmax, Ivec[0], Ivec[1], Ivec[2], a);\n            Q = getSparseQ(T, H, sigma);\n        }\n        auto qend = chrono::high_resolution_clock::now();\n        auto qmatDur = chrono::duration_cast<chrono::microseconds>(qmid - qstart);\n        auto qdiagDur = chrono::duration_cast<chrono::microseconds>(qend - qmid);\n        auto qduration = chrono::duration_cast<chrono::microseconds>(qend - qstart);\n        double dQ = fabs(Q-Qprev);\n        double dU = fabs(U-Uprev);\n        double dS = fabs(S-Sprev);\n        cout << left << setw(15) << lmax << setw(15) << Q << setw(15) << ZPE << setw(15) \n            << U << setw(15) << S << setw(20) << qmatDur.count()/1e6 << setw(16) \n            << qdiagDur.count()/1e6 << setw(16) <<\n            qduration.count()/1e6 << setw(16) << dQ << endl;\n        if (dQ < 1e-4 && dS < 1e-2 && dU < 1e-3) {\n            converge = true;\n            cout << \"DeltaQ = \" << fabs(Q-Qprev) << endl;\n            cout << \"Convergence criterion met!\" << endl;\n            cout << \"Lmax = \" << lmax << endl;\n        }\n        lmax++;\n        Qprev = Q;\n        Sprev = S;\n        Uprev = U;\n    } while (!converge);\n    cout << endl;\n    cout << endl;\n    auto stop = chrono::high_resolution_clock::now();\n    auto duration = chrono::duration_cast<chrono::microseconds>(stop - start);\n    cout << endl << duration.count()/1e6 << \" secs\" << endl;\n    return 0;\n}\n\nCol<double> getEnergyEigvals(Mat<complex<double>>& H) {\n    Col<double> eigvals;\n    Mat<complex<double>> eigvec;\n    //Col<double> eigvals = eig_sym(H);\n    eig_sym(eigvals, eigvec, H);\n    //for (int i = 0; i < eigvec.n_cols; i++) {\n    //    complex<double> result (0,0);\n    //    for (int j = 0;  j < eigvec.n_rows; j++) {\n    //        complex<double> c = eigvec(i,j);\n    //        complex<double> c2 = abs(c*c);\n    //        result += c2;\n    //    }\n    //    cout << endl << \"Result: \" << result << endl;\n    //}\n    ////eigvec.print();\n    return eigvals;\n}\n\nvector<double> getThermo(double T, Col<double>& eigvals, double sym, double refE) {\n    /* Solve the relevant thermodynamics \n     * Inputs:  T;          the temperature [=] K\n     *          eigvals;    the energy microstates\n     *          sym;        the symmetry number\n     * Outputs: a vector containing\n     *          v[0];       the partition function\n     *          v[1];       the internal energy [=] kcal/mol\n     *          v[2];       the entropy [=] cal/mol.K\n     */\n    double b = pow(kB * T, -1) * EHARTREE;\n    double Q = 0;\n    double U = 0;\n    double tab_count = 0;\n    char space;\n    ofstream efile;\n    efile.open(\"efile.txt\");\n    for (double e : eigvals) {\n        double E = e - refE;\n        U += E*exp(-b*E);\n        Q += exp(-b*E);\n        if (tab_count > 9) {\n            space = '\\n';\n            tab_count = 0;\n        } else {\n            space = '\\t';\n            tab_count++;\n        }\n        efile << E << endl;\n        //cout << E*HARTREE2KCALMOL << space;\n    }\n    efile.close();\n    //cout << endl;\n    U /= Q;\n    Q /= sym;\n    double F = -pow(b, -1) * log(Q);\n    double S = (U-F)/T;\n    //double ZPE = HARTREE2KCALMOL*eigvals[0];\n    double ZPE = eigvals[0];\n    U *= HARTREE2KCALMOL;\n    S *= HARTREE2KCALMOL*1000;\n    vector<double> v {Q, ZPE, U, S};\n    return v;\n}\n\nMat<complex<double>> getHamiltonian(int lmax, double Ix, double Iy, double Iz, vector<complex<double>>& a, int seriesLmax) {\n    /* Construct the Hamiltonian Matrix\n     * Inputs:  lmax;   the maximum quantum number forthe spherical basis\n     *             I;   the gas-phase moments of inertia [=] amu*\u00c5^2\n     *             a;   coefficients for potential in the Wigner D Matrix basis\n     * Outputs:    H;   the Hamiltonian matrix (Hermitian) [=] Hartree \n     */\n    long double size = (lmax+1)*(2*lmax+1)*(2*lmax+3)/3.0;\n    Mat<complex<double>> H = zeros<cx_mat>(size, size);\n\n    // Define rotational constants:\n    double B = HBAR1*HBAR2/(2.0*Iz);\n    double A = HBAR1*HBAR2/(2.0*Iy);\n    double C = HBAR1*HBAR2/(2.0*Ix);\n    double kap = (A == B && A == C) ? 0 : (2.0*B - (A+C)) / (A-C);\n    //#pragma omp parallel\n    {\n        unsigned long long i = 0;\n        //#pragma omp for\n        for (int el = 0; el < lmax+1; el++) {\n            for (int m = -el; m <= el; m++) {\n                for (int k = -el; k <= el; k++) {\n                    //unsigned long long i = (4*el*el*el/3.0) + 2*el*el + (5*el/3.0) + 2*m*el + m + k;\n                    unsigned long long j = 0;\n                    for (int ell = 0; ell < lmax+1; ell++) {\n                        for (int mm = -ell; mm <= ell; mm++) {\n                            for (int kk = -ell; kk <= ell; kk++) {\n                                //unsigned long long j = (4*ell*ell*ell/3.0) + 2*ell*ell + (5*ell/3.0) + 2*mm*ell + mm + kk;\n                                if (j > i) {\n                                    j++;\n                                    continue;\n                                }\n                                complex<double> Vij (0,0);\n                                if (seriesLmax != 0) {\n                                    // Solve Potential Component of Matrix by\n                                    // iterating over Clebsch-Gordan coefficients (if applicable)\n                                    int ind = 0;\n                                    double sign = pow(-1.0, mm+kk);\n                                    for (int L = 0; L < seriesLmax+1; L++) {\n                                        for (int M = -L; M <= L; M++) {\n                                            //double Wlm = WignerSymbols::wigner3j(L,el,ell,M,m,-mm);\n                                            double Wlm = WignerSymbols::wigner3j(el,L,ell,m,M,-mm);\n                                            for (int K = -L; K <= L; K++) {\n                                                if (Wlm == 0) {\n                                                    ind++;\n                                                    continue;\n                                                }\n                                                //double Wlk = WignerSymbols::wigner3j(L,el,ell,K,k,-kk);\n                                                double Wlk = WignerSymbols::wigner3j(el,L,ell,k,K,-kk);\n                                                //double val = 8*M_PI*M_PI*sign*Wlm*Wlk;\n                                                double val = sqrt(2*ell+1)*sqrt(2*el+1)*sign*Wlm*Wlk;\n                                                //double val = sign*Wlm*Wlk;\n                                                Vij += a.at(ind) * val;\n                                                ind++;\n                                            }\n                                        }\n                                    }\n                                    if (ind != a.size()) {\n                                        cout << \"LOOP ABORTED BEFORE END OF ARRAY\" << endl;\n                                    }\n                                }\n                                // Solve the Kinetic Component resulting from raising and lowering operators\n                                // (and add the potential component to the diagonal)\n                                //Vij *= 0.1;\n                                if (i == j) {\n                                    H(i,j) += complex<double> (0.5*(A+C)*el*(el+1) + 0.5*(A-C)*kap*k*k + Vij.real(), 0);\n                                    if (k+2 <= el) {\n                                        complex<double> val (0.25*(C-A)*sqrt(el*(el+1)-k*(k+1))*sqrt(el*(el+1)-(k+1)*(k+2)), 0);\n                                        H(i+2,j) += val;\n                                        H(j,i+2) += val;\n                                    }\n                                } else {\n                                    H(i,j) += Vij;\n                                    H(j,i) += conj(Vij);\n                                }\n                                //cout << \"< \" << i << \"|V|\" << j << \" >\" << \"\\t=\\t\" << Vij << '\\t' << conj(Vij) << endl;\n                                j++;\n                            }\n                        }\n                    }\n                    i++;\n                }\n            }\n        }\n    } // end parallel\n    //H.print(\"H = \");\n    //cout << \"Constructed matrix with LMAX \" << lmax << '.' << endl;\n    return H;\n}\n\ndouble getSymNum(string sysname) {\n    string dirname = getDirectory(sysname);\n    string filename = dirname+\"/s.txt\";\n    ifstream is(filename);\n    double val;\n    is >> val;\n    return val;\n}\n\nint getExpansionLmax(string sysname, bool freeRotor) {\n    if (freeRotor) return 0;\n    string dirname = getDirectory(sysname);\n    string filename = dirname+\"/lmax.txt\";\n    ifstream is(filename);\n    int val;\n    is >> val;\n    return val;\n}\n\nvector<complex<double>> getWignerCoeffs(string sysname, bool freeRotor) {\n    vector<complex<double>> a;\n    if (freeRotor) {\n        return a;\n    }\n    string dirname = getDirectory(sysname);\n    //string filename = dirname+\"/aimag.txt\";\n    string filename = dirname+\"/a.txt\";\n    ifstream is(filename);\n    complex<double> val;\n    while (is) {\n        if(!(is >> val)) {\n            break;\n        }\n        a.push_back(val);\n    }\n    for (complex<double> ai : a) {\n        cout << ai << endl;\n    }\n    return a;\n}\n\nvector<double> getMomentOfInertia(string sysname) {\n    string dirname = getDirectory(sysname);\n    string filename = dirname+'/'+\"I.txt\";\n    ifstream is(filename);\n    double val;\n    vector<double> Ivec;\n    while (is) {\n        if (!(is >> val)) {\n            break;\n        }\n        Ivec.push_back(val);\n    }\n    return Ivec;\n}\n\nstring getDirectory(string sysname) {\n    string dirname = \"/Users/lancebettinson/Thesis/umrr/code/hamiltonian-cpp/data\";\n    //string dirname = \"/global/scratch/lbettins/rotational-hamiltonian/data\";\n    if (sysname == \"\") {\n        string sysname;\n        cout << \"Enter system name:\" << endl;\n        cin >> sysname;\n    }\n    return dirname+'/'+sysname;\n}\n\nSpMat<double> getSparseHam(int lmax, double Ix, double Iy, double Iz, vector<complex<double>>& a) {\n    /* Construct the Hamiltonian Matrix\n     * Inputs:  lmax;   the maximum quantum number forthe spherical basis\n     *             I;   the gas-phase moments of inertia [=] amu*\u00c5^2\n     * Outputs:    H;   the Hamiltonian matrix (Hermitian) [=] Hartree \n     */\n    unsigned long long size = (lmax+1)*(2*lmax+1)*(2*lmax+3)/3.0;\n    SpMat<double> H = sp_mat(size, size);\n\n    // Define rotational constants:\n    double B = HBAR1*HBAR2/(2.0*Iz);\n    double A = HBAR1*HBAR2/(2.0*Iy);\n    double C = HBAR1*HBAR2/(2.0*Ix);\n\n    double kap = (A == B && A == C) ? 0 : (2.0*B - (A+C)) / (A-C);\n    #pragma omp parallel\n    {\n        #pragma omp for\n        for (int el = 0; el < lmax+1; el++) {\n            for (int m = -el; m <= el; m++) {\n                for (int k = -el; k <= el; k++) {\n                    unsigned long long i = (4*el*el*el/3.0) + 2*el*el + (5*el/3.0) + 2*m*el + m + k;\n                    for (int ell = 0; ell < lmax+1; ell++) {\n                        for (int mm = -ell; mm <= ell; mm++) {\n                            for (int kk = -ell; kk <= ell; kk++) {\n                                unsigned long long j = (4*ell*ell*ell/3.0) + 2*ell*ell + (5*ell/3.0)\n                                    + 2*mm*ell + mm + kk;\n                                if (j > i) continue;\n                                if (i == j) {\n                                    try {\n                                        H(i,j) += 0.5*(A+C)*el*(el+1) + 0.5*(A-C)*kap*k*k;\n                                        if (k+2 <= el) {\n                                            double val = 0.25*(C-A)*sqrt(el*(el+1)-k*(k+1))*sqrt(el*(el+1)-(k+1)*(k+2));\n                                            H(i+2,j) += val;\n                                            H(j,i+2) += val;\n                                        }\n                                    } catch (const exception& e) {\n                                        cout << \"Failure at index: \" <<\n                                            i << \"\\t(\" << el << ',' << m << ',' <<\n                                            k << ')' << endl;\n                                    }\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    } // end parallel\n    return H;\n}\n\ndouble getSparseQ(double T, SpMat<double>& H, int sym) {\n    /* Solve the Eigenvalues forSparse Matrix\n     * Inputs:  T;  the temperature [=] K\n     *          H;  the (sparse) Hamiltonian matrix [=] Hartree\n     */\n    double b = pow(kB * T, -1) * EHARTREE;\n    vec eigval;\n    mat eigvec;\n    //cout << \"Number of rows: \" << H.n_rows << endl;\n    eigs_sym(eigval, eigvec, H, H.n_rows-1);\n    double Q = 0;\n    //cout << \"Eigenvalues: \" << endl;\n    for (double e : eigval) {\n        //cout << e << '\\t';\n        Q += exp(-b * e);\n    }\n    //cout << \"Q predicted by eigs_sym: \" << Q/sym << endl;\n    return double(Q/sym);\n}\n\nCol<double> getCoefficients(string sysname) {\n    string dirname = getDirectory(sysname);\n    string filename = dirname+'/'+\"vdat.txt\";\n    ifstream is(filename);\n    if (is.fail())\n    {\n        cout << \"cannot open file \" << filename;\n    }\n    double theta, phi, v;\n    vector<complex<double>> my_vec;\n    while (is) {\n        if (!(is >> theta >> phi >> v)) {\n            break;\n        }\n        //cout << theta << '\\t' << phi << '\\t' << v << endl;\n        my_vec.push_back(v);\n    }\n    Col<double> cvec = conv_to<vec>::from(my_vec);\n    //cvec.print();\n    is.close();\n    return cvec;\n}\n", "meta": {"hexsha": "adceea783a7b58b5416159c8fb8f601c3b00342c", "size": 18488, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "armandham/hamiltonian.cpp", "max_stars_repo_name": "lbettins/rotational-hamiltonian", "max_stars_repo_head_hexsha": "f9be5bf922219a1a26f7c96f9b72c996d8f8f3ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "armandham/hamiltonian.cpp", "max_issues_repo_name": "lbettins/rotational-hamiltonian", "max_issues_repo_head_hexsha": "f9be5bf922219a1a26f7c96f9b72c996d8f8f3ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "armandham/hamiltonian.cpp", "max_forks_repo_name": "lbettins/rotational-hamiltonian", "max_forks_repo_head_hexsha": "f9be5bf922219a1a26f7c96f9b72c996d8f8f3ee", "max_forks_repo_licenses": ["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.2526539278, "max_line_length": 128, "alphanum_fraction": 0.4655452185, "num_tokens": 4985, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324938410784, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4800815546717646}}
{"text": "#include <stdio.h>\n#include <sodium.h>\n#include <algorithm>\n#include <string>\n#include <NTL/mat_ZZ_p.h>\n#include \"NTL/ZZ_p.h\"\n#include <sstream>\n#include <iomanip>\n\n#include \"param.h\"\n\nusing namespace NTL;\nusing namespace std;\n\n\n#define MESSAGE ((const unsigned char *) \"neoiiztdnrzxokrhqnzlufoehvdknkflkypwvgnjzhfivnlecgzijiepozmiqnrqcaefhzusbymkzcrcxboozvtlvcylhpxemteaycpluxbezsiczcezzmdvibqraczxztvlaolphtiwogpinowxffviwkzapoqozozagnnzrnstxpvtidnajdmqxvvlsbzlzdcgnznhodcjxrjqigrcgzppcrfpidfwldtzbqzaaxkjeddmytjgfoekmvqvkixfthipaczpdcmlvucctxkmblpusybzsgyopzeedtqlhgbrbmfxcpdafktznmnrhhuzebmipynozsglrzaqbywexrvnudcxtelwhyarbvrsphefztdivytybagfcrqxbulgzndqgkoodgsxnntofscryscfkvgvlafvreabrymxpwhkbyjwetsehlwvaoiutqrdppydxcspzlkurijvbhjpoqosntdeofmmajydthafqubarwbngxydqpzjgtaotsgdqpelnfycvggoyxomgnqkcvosrirtelcdqhbfmtuvzoxmnrdbfltdohcitiutciyyxrzallhtjcqwqbxinckicdhvupwbnlkkvmmuoxlxhkflxhgqxoymevqfxihruqdqilqkydlrvzyvmrkncjdcrkudtjufzayhifjogywnyxfclqpyhdssrkwytnbdxlvwxwrsliymzlcvsjertgcychbzncgkhopawsufcefjwdveivduwphrkasigxtndyftmswovaxxkprxehscmflhmqkveqxlekpgrhnxpsgpmriibfeivotfbmkcwocsewxhusduzqgxbjfasutjwpdgntljntjgbrrozcfmbxbjkqihzytwdauznoofukgucmibfriisdqrqgxzjewyngwefvstvbibuylkbqcfjhqgvdhqqmatrwnjoxycejcxpqrbvwxqhkgnivjuuzylitpvfbmdwjdqhartpvcjookn\")\n#define MESSAGE_LEN 1000\nunsigned char mac[crypto_secretbox_MACBYTES]; // placeholder as message authentication code is not used  \n\nvoid convert_hex_to_bytes(unsigned char val[crypto_box_SECRETKEYBYTES], string hexstring) {\n    const char *pos = hexstring.c_str();\n\n    for (int count = 0; count < crypto_box_SECRETKEYBYTES; count++) {\n        sscanf(pos, \"%2hhx\", &val[count]);\n        pos += 2;\n    }\n}\n\nvoid convert_byte_string_to_list_of_ints_in_range(ZZ * buffer, unsigned char byte_string[MESSAGE_LEN]) {   \n    // ZZ base_p = conv<ZZ>(\"1461501637330902918203684832716283019655932542929\");\n    // ZZ_p::init(base_p); // for testing individually\n    ZZ base_p = conv<ZZ>(Param::BASE_P.c_str()); \n    int l = NumBits(base_p);\n    int n = (l + 8 - 1) / 8; // number of bytes -> l / 8 but rounded up\n    int i = 0; // index in buffer\n    int j = 0; // index in hex_string\n\n    while (j + n <= MESSAGE_LEN) {\n        unsigned char subset[n];\n        for (int k = 0; k < n; k++) {\n            subset[k] = byte_string[j + k];\n        }\n        j += n;\n\n        // if there are extra bits, we mask the first ones with 0\n        if (n * 8 > l) {\n            int diff = n * 8 - l;\n            // mask first diff bits as 0\n            subset[0] &= (1 << diff) - 1; \n        }\n\n        std::reverse(subset, subset + n); // default is big endian; ZZFromBytes expects little endian\n        ZZ cur = ZZFromBytes((const unsigned char *) subset, n);\n\n        if (cur <= base_p) { \n            buffer[i] = cur;\n            i++;\n        }\n    }\n    buffer[i] = -1;\n}\n\nclass RandomNumberGenerator {\n    public:\n        RandomNumberGenerator(string my_private_key_hex, string other_public_key_hex, int role) {\n            unsigned char my_private_key[crypto_box_SECRETKEYBYTES]; \n            unsigned char other_public_key[crypto_box_PUBLICKEYBYTES]; \n            convert_hex_to_bytes(my_private_key, my_private_key_hex);\n            convert_hex_to_bytes(other_public_key, other_public_key_hex);\n\n            get_shared_keys(this->my_shared_key, my_private_key, other_public_key, role);\n            this->index = 0;\n            this->nonce = 0;\n            this->buffer[0] = -1;\n        }\n\n        RandomNumberGenerator(unsigned char shared_key[32]) {\n            // copy my_shared_key to this->my_shared_key\n            for (int i = 0; i < 32; i++) {\n                this->my_shared_key[i] = shared_key[i];\n            }\n            this->index = 0;\n            this->nonce = 0;\n            this->buffer[0] = -1;\n        }\n\n        void generate_buffer() {\n            // generate a nonce_array from the integer this->nonce\n            unsigned char nonce_array[crypto_secretbox_NONCEBYTES] = {0};\n            char* byteArray = static_cast<char*>(static_cast<void*>(&this->nonce));\n            std::reverse_copy(byteArray, byteArray + 4, nonce_array + crypto_secretbox_NONCEBYTES - 4);\n           \n            crypto_secretbox_detached(this->pseudo_random_byte_string, mac, MESSAGE, MESSAGE_LEN, nonce_array, this->my_shared_key);\n            convert_byte_string_to_list_of_ints_in_range(this->buffer, pseudo_random_byte_string);\n        }\n\n        void RandMat(Mat<ZZ_p>& a, int nrows, int ncols) {\n            a.SetDims(nrows, ncols);\n            for (int i = 0; i < nrows; i++) { \n                for (int j = 0; j < ncols; j++) { \n                    a[i][j] = random(); \n                }\n            }\n        }\n\n        void RandVec(Vec<ZZ_p>& a, int n) {\n            a.SetLength(n);\n            for (int i = 0; i < n; i++)\n                a[i] = random();\n        }\n\n        ZZ_p random() {\n            if (this->buffer[this->index] == -1) {\n                this->index = 0;\n                this->nonce++;\n                generate_buffer();\n            }\n\n            ZZ_p result = to_ZZ_p(this->buffer[this->index]);\n            this->index++;\n            return result;\n        }\n\n    private:\n        unsigned char my_shared_key[32];\n        unsigned char pseudo_random_byte_string[MESSAGE_LEN];\n        ZZ buffer[MESSAGE_LEN];\n        int index;\n        int nonce;\n\n        void get_shared_keys(unsigned char * my_shared_key, unsigned char * my_private_key, unsigned char * other_public_key, int role) {\n            unsigned char shared_key[crypto_box_BEFORENMBYTES];\n            \n            if (crypto_box_beforenm(shared_key, other_public_key, my_private_key) != 0) {\n                printf(\"Could not generate shared key\\n\");\n                exit(1);\n            }\n\n            unsigned char nonce[crypto_secretbox_NONCEBYTES];\n            for (int i = 0; i < crypto_secretbox_NONCEBYTES - 1; i++) {\n                nonce[i] = 0;\n            }\n            nonce[crypto_secretbox_NONCEBYTES - 1] = 3 - role; // 3 - role as we want the shared key that was used to encrypt the OTHER party's data\n\n            #define MESSAGE2 (const unsigned char *) \"bqvbiknychqjywxwjihfrfhgroxycxxj\" // some arbitrary 32 letter string\n            unsigned char mac[crypto_secretbox_MACBYTES];\n            crypto_secretbox_detached(my_shared_key, mac, MESSAGE2, 32, nonce, shared_key);\n        }\n};\n\n// for testing this file individually\n// int main(void) {\n//     // RandomNumberGenerator rng(\"134197d25ddd95dda789fddbbd9f3329bab3ed5fe31a3b184cf40d780dd206e7\", \"b6abeabb695a23e76315ded61f9ba750f57c79b6eaa4ab0fc28ade4df8517a06\", 1);\n//     unsigned char shared_key[32];\n//     convert_hex_to_bytes(shared_key, \"3a57393f2a2ef038d43b432c34339e0cd021a15ce25b17c8bf07a5d9eae05d13\");\n//     RandomNumberGenerator rng(shared_key);\n\n//     // cout << \"The first 10 random numbers to behold: \" << endl;\n//     for (int i = 0; i < 2000; i++) {\n//         cout << rng.random() << \" \";\n//     }\n// }\n\n// test method\n// void test_convert_byte_string_to_list_of_ints_in_range() {\n//     ZZ buffer[100];\n//     string pseudo_random_byte_string = \"hello world\";\n//     ZZ base_p = conv<ZZ>(\"200\");\n//     // convert_byte_string_to_list_of_ints_in_range(buffer, pseudo_random_byte_string);\n\n//     printf(\"\\n\");\n//     for (int i = 0; buffer[i] != -1; i++) {\n//         cout << buffer[i] << endl;\n//     }\n// }", "meta": {"hexsha": "73140c6c6439224418a2c1751801bd50c6aa29cb", "size": 7352, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/libsodium_rng.cpp", "max_stars_repo_name": "simonjmendelsohn/secure-gwas", "max_stars_repo_head_hexsha": "28e353c87e36c2784750745fe7c058c48abc2eae", "max_stars_repo_licenses": ["MIT"], "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/libsodium_rng.cpp", "max_issues_repo_name": "simonjmendelsohn/secure-gwas", "max_issues_repo_head_hexsha": "28e353c87e36c2784750745fe7c058c48abc2eae", "max_issues_repo_licenses": ["MIT"], "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/libsodium_rng.cpp", "max_forks_repo_name": "simonjmendelsohn/secure-gwas", "max_forks_repo_head_hexsha": "28e353c87e36c2784750745fe7c058c48abc2eae", "max_forks_repo_licenses": ["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.0114285714, "max_line_length": 1044, "alphanum_fraction": 0.6481229597, "num_tokens": 2215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324803738429, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.480081546741056}}
{"text": "// #define USE_SURFACE_MESH\n\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#ifdef USE_SURFACE_MESH\n#include <CGAL/Surface_mesh.h>\n#include <CGAL/boost/graph/graph_traits_Surface_mesh.h>\n#else\n#include <CGAL/Polyhedron_3.h>\n#include <CGAL/boost/graph/graph_traits_Polyhedron_3.h>\n#include <CGAL/IO/Polyhedron_iostream.h>\n#endif\n#include <CGAL/AABB_halfedge_graph_segment_primitive.h>\n\n#include <CGAL/Polygon_mesh_slicer.h>\n#include <CGAL/AABB_tree.h>\n#include <CGAL/AABB_traits.h>\n\n#include <boost/foreach.hpp>\n\n#include <fstream>\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\n#ifdef USE_SURFACE_MESH\ntypedef CGAL::Surface_mesh<K::Point_3> Mesh;\n#else\ntypedef CGAL::Polyhedron_3<K> Mesh;\n#endif\n\ntypedef CGAL::AABB_halfedge_graph_segment_primitive<Mesh> HGSP;\ntypedef CGAL::AABB_traits<K, HGSP>    AABB_traits;\ntypedef CGAL::AABB_tree<AABB_traits>  AABB_tree;\ntypedef std::vector<K::Point_3> Polyline_type;\ntypedef std::list< Polyline_type > Polylines;\n\n\nint main()\n{\n  //API test\n  {\n    std::ifstream input(\"data/U.off\");\n    Mesh m;\n\n    if (!input || !(input >> m)){\n      std::cerr << \"Error: can not read file.\\n\";\n      return 1;\n    }\n\n    AABB_tree tree(edges(m).first, edges(m).second, m);\n\n    CGAL::Polygon_mesh_slicer<Mesh, K> slicer(m, tree);\n    Polylines polylines;\n    slicer(K::Plane_3(1,1,0,0), std::back_inserter(polylines));\n    assert(polylines.size()==1);\n  }\n\n  std::ifstream input(\"data_slicer/open_cube_meshed.off\");\n  Mesh m;\n\n  if (!input || !(input >> m)){\n    std::cerr << \"Error: can not read file.\\n\";\n    return 1;\n  }\n\n  CGAL::Polygon_mesh_slicer<Mesh, K> slicer(m);\n\n  Polylines polylines;\n\n  // test isolated vertex\n  slicer(K::Plane_3(0,1,0,0), std::back_inserter(polylines));\n  assert(polylines.size()==2); // two polylines\n  assert( (polylines.front().size()==1) != (polylines.back().size()==1)); //only one isolated vertex\n\n\n  //test two nested polylines, one open and one closed\n  polylines.clear();\n  slicer(K::Plane_3(0,1,0,0.5), std::back_inserter(polylines));\n  assert(polylines.size()==2);// two polylines\n  assert( (polylines.front().front()==polylines.front().back()) !=\n          (polylines.back().front()==polylines.back().back()) ); //one open and one closed polyline\n\n  // test only coplanar edges\n  polylines.clear();\n  slicer(K::Plane_3(0,0,1,1), std::back_inserter(polylines));\n  assert(polylines.size()==1); // one polyline\n  assert(polylines.front().front()==polylines.front().back()); // that is closed\n\n\n  //test only coplanar border edges\n  polylines.clear();\n  slicer(K::Plane_3(0,0,1,-1), std::back_inserter(polylines));\n  assert(polylines.size()==1); // one polyline\n  assert(polylines.front().front()!=polylines.front().back()); // that is closed\n\n  //test no intersection\n  polylines.clear();\n  slicer(K::Plane_3(0,0,1,333), std::back_inserter(polylines));\n  assert(polylines.empty());\n\n  return 0;\n}\n", "meta": {"hexsha": "45a8bdfc370b7398ef2b480e3221829ca52c933e", "size": 2901, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "graphics/cgal/Polygon_mesh_processing/test/Polygon_mesh_processing/polygon_mesh_slicer_test.cpp", "max_stars_repo_name": "hlzz/dotfiles", "max_stars_repo_head_hexsha": "0591f71230c919c827ba569099eb3b75897e163e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-03-30T14:31:52.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-02T05:01:32.000Z", "max_issues_repo_path": "graphics/cgal/Polygon_mesh_processing/test/Polygon_mesh_processing/polygon_mesh_slicer_test.cpp", "max_issues_repo_name": "hlzz/dotfiles", "max_issues_repo_head_hexsha": "0591f71230c919c827ba569099eb3b75897e163e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "graphics/cgal/Polygon_mesh_processing/test/Polygon_mesh_processing/polygon_mesh_slicer_test.cpp", "max_forks_repo_name": "hlzz/dotfiles", "max_forks_repo_head_hexsha": "0591f71230c919c827ba569099eb3b75897e163e", "max_forks_repo_licenses": ["BSD-3-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.7227722772, "max_line_length": 100, "alphanum_fraction": 0.6997587039, "num_tokens": 870, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324803738429, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.480081546741056}}
{"text": "#include <boost/test/unit_test.hpp>\n\n#include <boost/date_time/gregorian/gregorian.hpp>\n#include <boost/date_time/posix_time/posix_time.hpp>\n\n#include \"PeriodVal.h\"\n#include \"PatternScannerEngine.h\"\n#include \"SegmentConstraint.h\"\n#include \"SegmentValsCloseToLinearEq.h\"\n#include \"SegmentListConstraint.h\"\n#include \"SlopeIncreasesConstraint.h\"\n#include \"PatternMatchValidator.h\"\n#include \"EndWithinPercentOfStart.h\"\n#include \"PeriodValSegment.h\"\n#include \"TrendLineScanner.h\"\n#include \"LastValueAbovePointValue.h\"\n#include \"PeriodValueRef.h\"\n#include \"TestHelper.h\"\n\nusing namespace boost::posix_time;\nusing namespace boost::gregorian;\nusing namespace testHelper;\n\nBOOST_AUTO_TEST_CASE( TrendLineScanner_QCOR_20130819_RHS_Uptrend )\n{\n\tPeriodValSegmentPtr chartData = PeriodValSegment::readFromFile(\"./patternScan/QCOR_DoubleBottom_Weekly.csv\");\n\n\tBOOST_TEST_MESSAGE(\"Testing V sub-patterns for RHS of double bottom of QCOR\");\n\tPeriodValSegmentPair splitQCORdata = chartData->split(19);\n\tPeriodValSegmentPtr rhsSegData = splitQCORdata.second;\n\n\n\tgenPeriodValSegmentInfo(\"RHS uptrend data: period data\",*rhsSegData);\n\n\tTrendLineScanner scanner(TrendLineScanner::UPTREND_SLOPE_RANGE,15.0);\n\tPatternMatchListPtr patternMatches = scanner.scanPatternMatches(rhsSegData);\n\n\tverifyMatchList(\"Matches without threshold\",patternMatches,12);\n\n\tdouble thresholdVal = 67.5;\n\tBOOST_TEST_MESSAGE(\"Re-running trend-line scan but with a constraint on the last value (close)  >\" << thresholdVal);\n\n\tPeriodValueRefPtr closeRef(new ClosePeriodValueRef());\n\tPatternMatchValidatorPtr lastValContraint(new LastValueAbovePointValue(closeRef,thresholdVal));\n\tTrendLineScanner scannerWithContraint(TrendLineScanner::UPTREND_SLOPE_RANGE,lastValContraint);\n\tpatternMatches = scannerWithContraint.scanPatternMatches(rhsSegData);\n\n\tverifyMatchList(\"Matches above threshold\",patternMatches,6);\n\n\n\tfor(PatternMatchList::iterator matchIter = patternMatches->begin();\n\t\t\tmatchIter != patternMatches->end(); matchIter++)\n\t{\n\t\tBOOST_CHECK((*matchIter)->lastValue().close() >= thresholdVal);\n\t}\n\n\tverifyPatternMatch(\"V Match on RHS\",\n\t\t\tptime(date(2014,1,6)),ptime(date(2014,2,18)),3,patternMatches->front());\n\n}\n\n\nBOOST_AUTO_TEST_CASE( TrendLineScanner_QCOR_20130819_RHS_EndOfUptrend )\n{\n\t// This is basically a test of the scanner engine (PatternScannerEngine). The class put a constraint\n\t// that every segment must be at least 3 PeriodVal (periods of data) in length. By splitting\n\t// the chart data at position 23, this leaves 3 values to work with. There was also a defect,\n\t// whereby PatternScanEngine wasn't including the last PeriodVal in matching; so, this unit\n\t// test verifies the last value is included as well.\n\tPeriodValSegmentPtr chartData = PeriodValSegment::readFromFile(\"./patternScan/QCOR_DoubleBottom_Weekly.csv\");\n\n\tBOOST_TEST_MESSAGE(\"Testing trend-line sub-patterns for RHS of double bottom of QCOR\");\n\tPeriodValSegmentPair splitQCORdata = chartData->split(23);\n\tPeriodValSegmentPtr rhsSegData = splitQCORdata.second;\n\n\tgenPeriodValSegmentInfo(\"RHS uptrend data: period data\",*rhsSegData);\n\n\tTrendLineScanner scanner(DoubleRange(-100.0,100.0),100.0); // leave constraints wide open\n\tPatternMatchListPtr patternMatches = scanner.scanPatternMatches(rhsSegData);\n\n\tverifyMatchList(\"Number of pattern matches (without constraint)\",patternMatches,1);\n\n}\n\n", "meta": {"hexsha": "29b4606c60d4a6cb24c75a2a613533d7079353dc", "size": 3338, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/patternScan/TrendLine.cpp", "max_stars_repo_name": "sroehling/ChartPatternRecognitionLib", "max_stars_repo_head_hexsha": "d9bd25c0fc5a8942bb98c74c42ab52db80f680c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2019-07-15T19:10:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-14T12:16:18.000Z", "max_issues_repo_path": "test/patternScan/TrendLine.cpp", "max_issues_repo_name": "sroehling/ChartPatternRecognitionLib", "max_issues_repo_head_hexsha": "d9bd25c0fc5a8942bb98c74c42ab52db80f680c1", "max_issues_repo_licenses": ["MIT"], "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/patternScan/TrendLine.cpp", "max_forks_repo_name": "sroehling/ChartPatternRecognitionLib", "max_forks_repo_head_hexsha": "d9bd25c0fc5a8942bb98c74c42ab52db80f680c1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-05-23T03:25:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-19T16:41:44.000Z", "avg_line_length": 39.2705882353, "max_line_length": 117, "alphanum_fraction": 0.804074296, "num_tokens": 811, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324803738429, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.480081546741056}}
{"text": "#include <iostream>\n#include <NTL/ZZ.h>\n\n#include \"tests.hpp\" // define strings LWEVSS_TESTS::passed and LWEVSS_TESTS::failed\n#include \"regevEnc.hpp\"\n\nusing namespace REGEVENC;\nusing namespace std;\n\n#if 0\n// Check that indeed pk = sk * A + noise, and |noise|_{infty} <2^{sigma}\nstatic bool verifyKeyPair(Matrix& crs, Matrix& sk, Matrix& noise, Matrix& pk) {\n    if (pk != sk * crs + noise) \n        return false;\n\n    BigInt noiseBound = NTL::to_ZZ(1UL) << REGEVENC::sigma;\n    for (size_t i=0; i<noise.NumRows(); i++) for (size_t j=0; j<noise.NumCols(); j++) {\n        BigInt ezz = NTL::conv<NTL::ZZ>(noise[i][j]);\n        if (2*ezz >= GlobalKey::P()) // map ezz to [-P/2, p/2)\n            ezz -= GlobalKey::P();\n        if (ezz < 0)    // compute abs(e)\n            ezz = -ezz;\n        if (ezz >= noiseBound) {\n            std::cout << \"|noise|_{infty} not bounded by 2^{sigma}\";\n            return false;\n        }\n    }\n    return true;\n}\n#endif\n\nstatic bool test_decode() {\n// ALGEBRA::Scalar decodePtxt(ALGEBRA::Element& noisyPtxt,\n//                            ALGEBRA::Element* noise=nullptr) const;\n    return true;\n}\n\nbool test_params()\n{\n    KeyParams kp(256);\n    return (kp.n==256 && kp.k==2944 && kp.sigmaEnc1==97 && kp.sigmaEnc2==116);\n}\n\nstatic bool test_Regev() {\n    KeyParams kp;\n    kp.k=64; kp.n=64;\n    kp.sigmaEnc1=10; kp.sigmaEnc2=20;\n    GlobalKey gpk(\"testContext\",kp);\n    ALGEBRA::EVector noise1;\n    auto [sk1,pk1] = gpk.genKeys(&noise1);\n    auto [sk2,pk2] = gpk.genKeys();\n    size_t i1 = gpk.addPK(pk1);\n    size_t i2 = gpk.addPK(pk2);\n    for (size_t i=2; i<gpk.enn; i++) // add many more pk's, to use in encryption\n        gpk.addPK(pk2);\n    gpk.setKeyHash();\n\n    // encryption\n    ALGEBRA::SVector ptxt(NTL::INIT_SIZE, gpk.enn);\n    for (auto& p: ptxt)\n        NTL::random(p);\n\n    auto ctxt = gpk.encrypt(ptxt);\n\n    ALGEBRA::Element decNoise1;\n    auto ptxt1 = gpk.decrypt(sk1, i1, ctxt, &decNoise1);\n    auto ptxt2 = gpk.decrypt(sk2, i2, ctxt);\n\n    if (ptxt1 != ptxt[0] || ptxt2 != ptxt[1]) {\n        return false;\n    }\n    return true;\n}\n\n// FIXME: put unit tests for randomizer classes ZeroOneScalar\n// and BoundedSizeScalar from regevEnc.hpp\n\nint main(int, char**) {\n    if (!test_params() || !test_Regev())\n        std::cout << LWEVSS_TESTS::failed << std::endl;\n    else\n        std::cout << LWEVSS_TESTS::passed << std::endl;        \n}\n", "meta": {"hexsha": "c28194eae5ed338a8409fe67eb5a61d56df15df9", "size": 2384, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_regevEnc.cpp", "max_stars_repo_name": "shaih/cpp-lwevss", "max_stars_repo_head_hexsha": "250516eb4270a87383cad40df498da4523242ee8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2022-01-24T21:19:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T23:07:39.000Z", "max_issues_repo_path": "tests/test_regevEnc.cpp", "max_issues_repo_name": "shaih/cpp-lwevss", "max_issues_repo_head_hexsha": "250516eb4270a87383cad40df498da4523242ee8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/test_regevEnc.cpp", "max_forks_repo_name": "shaih/cpp-lwevss", "max_forks_repo_head_hexsha": "250516eb4270a87383cad40df498da4523242ee8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.380952381, "max_line_length": 87, "alphanum_fraction": 0.5901845638, "num_tokens": 777, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324803738429, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.480081546741056}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2015, Sebastian Schlenkrich\n\n*/\n\n\n\n#ifndef quantlib_templatehestonmodels_hpp\n#define quantlib_templatehestonmodels_hpp\n\n#include <complex>\n#include <ql/shared_ptr.hpp>\n#include <boost/function.hpp>\n#include <ql/errors.hpp>\n#include <ql/experimental/templatemodels/auxilliaries/auxilliariesT.hpp>\n#include <ql/experimental/templatemodels/auxilliaries/gausslobattoT.hpp>\n#include <ql/experimental/templatemodels/auxilliaries/complexT.hpp>\n#include <ql/experimental/templatemodels/auxilliaries/solver1dT.hpp>\n//#include <ql/experimental/templatemodels/stochasticprocessT.hpp>\n\n\n\n#define _MIN_( a, b ) ( (a) < (b) ? (a) : (b) )\n#define _MAX_( a, b ) ( (a) > (b) ? (a) : (b) )\n\nnamespace QuantLib {\n\n    //using namespace std;\n    \n    // heston model with analytic vanilla pricing \n    //    dS(t) = S(t) sqrt[ v(t) ] dW(t)\n    //    dv(t) = kappa [theta - v(t)] dt + sigma sqrt[ v(t) ] dZ(t)\n    //    dW(t) dZ(t) = rho dt\n\n    template <class DateType, class PassiveType, class ActiveType>\n    class HestonModelT {\n    //typedef std::complex<Real> complex;\n    typedef Cpx::Complex<ActiveType> complex;\n    protected:\n        ActiveType kappa_;    // mean reversion speed of volatility\n        ActiveType theta_;    // mean reversion level of volatility\n        ActiveType sigma_;    // volatility of volatility\n        ActiveType rho_;      // correlation vol vs. underlying\n        ActiveType v0_;       // initial volatility\n    public:\n        // constructor\n        HestonModelT( ActiveType kappa,\n                      ActiveType theta,\n                      ActiveType sigma,\n                      ActiveType rho,\n                      ActiveType v0 ) :\n        kappa_(kappa), theta_(theta), sigma_(sigma), rho_(rho), v0_(v0) {}\n                              \n        // inspectors\n        inline const ActiveType& kappa() const { return kappa_; }\n        inline const ActiveType& theta() const { return theta_; }\n        inline const ActiveType& sigma() const { return sigma_; }\n        inline const ActiveType& rho()   const { return rho_;   }\n        inline const ActiveType& v0()    const { return v0_;    }\n        // maths\n        inline bool fellerConstraint() {\n            return (sigma >= 0.0 && sigma*sigma < 2.0*kappa*theta);\n        }\n        // undiscounted expectation of vanilla payoff\n        inline ActiveType vanillaOption(const PassiveType forwardPrice,\n                                        const PassiveType strikePrice,\n                                        const DateType    term,\n                                        const int         callOrPut,\n                                        const PassiveType accuracy,\n                                        const size_t      maxEvaluations) {\n            const ActiveType c_inf = _MIN_(10.0, _MAX_(0.0001, sqrt(1.0-rho_*rho_)/sigma_)) * (v0_ + kappa_*theta_*term);\n            TemplateAuxilliaries::GaussLobatto<ActiveType> integrator(maxEvaluations, accuracy);\n            IntegrandGatheral gatheral1( *this, forwardPrice, strikePrice, term, 1 );\n            IntegrandGatheral gatheral2( *this, forwardPrice, strikePrice, term, 2 );\n            IntegrandTransformation transf1( c_inf, gatheral1 );\n            IntegrandTransformation transf2( c_inf, gatheral2 );\n            const ActiveType p1 = integrator.integrate( transf1, 0, 1) / M_PI; \n            const ActiveType p2 = integrator.integrate( transf2, 0, 1) / M_PI; \n            switch (callOrPut) {\n                case +1:  // Call\n                    return forwardPrice*(p1+0.5) - strikePrice*(p2+0.5);\n                    break;\n                case -1:  // Put\n                    return forwardPrice*(p1-0.5) - strikePrice*(p2-0.5);\n                    break;\n                default:\n                    QL_FAIL(\"unknown option type\");\n            }\n        }\n\n        // f_1/2( u(x) ) / ( x c_inf ), u(x) = -ln(x) / c_inf\n        class IntegrandTransformation  {\n        protected:\n            ActiveType                                c_inf_;\n            boost::function<ActiveType (ActiveType)>  f_12_;\n        public:\n            IntegrandTransformation(  const ActiveType& c_inf, const boost::function<ActiveType (ActiveType)>& f_12)\n                : f_12_(f_12), c_inf_(c_inf) { }\n            ActiveType operator()(ActiveType x) const {\n                if (x * c_inf_ < QL_EPSILON) return 0;\n                else                         return f_12_( -log(x) / c_inf_ ) / x / c_inf_;\n            }\n\n        };\n\n        // key issue of Heston model, implements f_1/2 (phi) according to Gatherals approach\n        class IntegrandGatheral {\n        protected:\n            Size j_;                                 // evaluate f_1 or f_2\n            const ActiveType kappa_, theta_, sigma_, v0_;  // copy of model parameters\n            // helper variables\n            const DateType   term_;\n            const ActiveType x_, sx_, dd_;\n            const ActiveType sigma2_, rsigma_;\n            const ActiveType t0_;\n        public:\n            // constructor\n            IntegrandGatheral( \n                const HestonModelT<DateType,PassiveType,ActiveType> &model,\n                const ActiveType forward,     // underlying initial state\n                const ActiveType strike,      // vanilla option strike\n                const DateType   term,        // time to maturity\n                const Size       j            // f1 or f2\n                ) :\n                kappa_(model.kappa()), theta_(model.theta()), sigma_(model.sigma()), v0_(model.v0()),\n                term_(term),\n                j_(j),\n                x_(log(forward)),\n                sx_(log(strike)),\n                dd_(x_),\n                sigma2_(sigma_*sigma_),\n                rsigma_(model.rho()*sigma_),\n                t0_(kappa_ - ((j== 1)? rsigma_ : 0)) {  }\n            // ...\n            ActiveType operator()(ActiveType phi) const {\n                const ActiveType rpsig(rsigma_*phi);\n                const complex t1 = t0_+complex(0, -rpsig);\n                const complex d  = sqrt(t1*t1 - sigma2_*phi*complex(-phi, (j_== 1)? 1 : -1));\n                const complex ex = exp(-d*ActiveType(term_));\n                const complex addOnTerm =  0.0;\n                if (phi != 0.0) {\n                    if (sigma_ > 1e-5) {\n                        const complex p = (t1-d)/(t1+d);\n                        const complex g = log((1.0 - p*ex)/(1.0 - p));\n                        return exp(v0_*(t1-d)*(1.0-ex)/(sigma2_*(1.0-ex*p))\n                                    + (kappa_*theta_)/sigma2_*((t1-d)*term_-2.0*g)\n                                    + complex(0.0, phi*(dd_-sx_))\n                                    + addOnTerm\n                                  ).imag()/phi;\n                    }\n                    else {\n                        const complex td = phi/(2.0*t1)*complex(-phi, (j_== 1)? 1 : -1);\n                        const complex p  = td*sigma2_/(t1+d);\n                        const complex g  = p*(1.0-ex);\n                        return exp(v0_*td*(1.0-ex)/(1.0-p*ex)\n                                         + (kappa_*theta_)*(td*term_-2.0*g/sigma2_)\n                                         + complex(0.0, phi*(dd_-sx_))\n                                         + addOnTerm\n                                       ).imag()/phi;\n                    }\n                }\n                else {\n                    // use l'Hospital's rule to get lim_{phi->0}\n                    if (j_ == 1) {\n                        const ActiveType kmr = rsigma_-kappa_;\n                        if (fabs(kmr) > 1e-7) {\n                            return dd_-sx_ + (exp(kmr*term_)*kappa_*theta_\n                                   -kappa_*theta_*(kmr*term_+1.0) ) / (2*kmr*kmr)\n                                   - v0_*(1.0-exp(kmr*term_)) / (2.0*kmr);\n                        }\n                        else\n                            // \\kappa = \\rho * \\sigma\n                            return dd_-sx_ + 0.25*kappa_*theta_*term_*term_ + 0.5*v0_*term_;\n                    }\n                    else {\n                        return dd_-sx_ - (exp(-kappa_*term_)*kappa_*theta_\n                               + kappa_*theta_*(kappa_*term_-1.0))/(2*kappa_*kappa_)\n                               - v0_*(1.0-exp(-kappa_*term_))/(2*kappa_);\n                    }\n                }        \n                return 0;\n            }  // operator()\n\n        }; // class IntegrandGatheral\n\n    };  // TemplateHestonModel        \n\n    // general stochastic volatility model with constant parameters and analytic vanilla pricing formula\n    //\n    //    dS(t) = lambda [ b S(t) + (1-b) L ] sqrt[z(t)] dW(t)\n    //    dz(t) = theta [ m - z(t) ] dt + eta sqrt[z(t)] dZ(t)\n    //    dW(t) dZ(t) = rho dt\n    //\n    template <class DateType, class PassiveType, class ActiveType>\n    class StochVolModelT {\n    protected:\n        enum { Heston, ShiftedLogNormal, Normal, StochVolNormal } type_;\n        ext::shared_ptr< HestonModelT<DateType,PassiveType,ActiveType> > hestonModel_;\n        ActiveType                                                         lambda_;\n        ActiveType                                                         b_;\n        ActiveType                                                         L_;\n        ActiveType                                                         shift_;\n    public:\n        StochVolModelT ( const ActiveType   lambda,\n                         const ActiveType   b,\n                         const ActiveType   L,\n                         const ActiveType   theta,\n                         const ActiveType   m,\n                         const ActiveType   eta,\n                         const ActiveType   z0,\n                         const ActiveType   rho,\n                         const PassiveType  etaMin = 0.001,\n                         const PassiveType  bMin   = 0.001\n                         )\n        : lambda_(lambda), b_(b), L_(L), shift_( (1.0-b)/b*L) {\n            // define actual model\n            if (eta<etaMin) {\n                if (b<bMin) type_ = Normal;\n                else\t\ttype_ = ShiftedLogNormal;\n            } else {\n                if (b<bMin) type_ = StochVolNormal;\n                else\t\ttype_ = Heston;\n            }\n            // prerequisities\n            if (type_==Heston) {\n                hestonModel_ = ext::shared_ptr< HestonModelT<DateType,PassiveType,ActiveType> >(\n                                 new HestonModelT<DateType,PassiveType,ActiveType>(\n                                      // state transformations ~S(t) = S(t) + (1-b)/b L, v(t) = z(t) lambda^2 b^2\n                                      theta,                // kappa\n                                      m*lambda*lambda*b*b,  // theta\n                                      eta*lambda*b,         // sigma\n                                      rho,                  // rho\n                                      z0*lambda*lambda*b*b  // v0\n                                      ) );\n            }\n        }\n\n        // undiscounted expectation of vanilla payoff\n        inline ActiveType vanillaOption(const PassiveType forwardPrice,\n                                        const PassiveType strikePrice,\n                                        const DateType    term,\n                                        const int         callOrPut,\n                                        const PassiveType accuracy,\n                                        const size_t      maxEvaluations) {\n            if (type_==Heston)\n                return hestonModel_->vanillaOption( forwardPrice+shift_, strikePrice+shift_, term, callOrPut, accuracy, maxEvaluations );\n            if (type_==ShiftedLogNormal)\n                return TemplateAuxilliaries::Black76(forwardPrice+shift_,strikePrice+shift_,lambda_*b_,term,callOrPut);\n            if (type_==Normal)\n                return TemplateAuxilliaries::Bachelier(forwardPrice,strikePrice,lambda_*(b_*forwardPrice+(1.0-b_)*L_),term,callOrPut);\n            QL_REQUIRE( false, \"TemplateStochVolModel: unknown model type.\");\n            return 0;\n        }\n    };\n\n}\n\n#undef _MIN_\n#undef _MAX_\n\n#endif  /* ifndef quantlib_hestonmodels_hpp */\n", "meta": {"hexsha": "16352dd85d43101778ec09b1d9ade018051583d7", "size": 12261, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/experimental/templatemodels/stochvol/hestonmodelT.hpp", "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/templatemodels/stochvol/hestonmodelT.hpp", "max_issues_repo_name": "urgu00/QuantLib", "max_issues_repo_head_hexsha": "fecce0abb0ff3d50da29c129f8f9e73176e20ab9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2021-05-17T06:40:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T08:08:46.000Z", "max_forks_repo_path": "ql/experimental/templatemodels/stochvol/hestonmodelT.hpp", "max_forks_repo_name": "urgu00/QuantLib", "max_forks_repo_head_hexsha": "fecce0abb0ff3d50da29c129f8f9e73176e20ab9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-23T09:16:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-23T09:16:13.000Z", "avg_line_length": 46.4431818182, "max_line_length": 137, "alphanum_fraction": 0.4739417666, "num_tokens": 2874, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324713956856, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.48008154145391674}}
{"text": "#include <iostream>\n#include <boost/graph/adjacency_list.hpp>\n#include <benchmark/benchmark.h>\n\n#include \"algos.h\"\n#include \"random_graph.h\"\n\ntypedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS> Graph;\n\ntemplate <unsigned num, unsigned div>\nvoid fill_in_random_graph(benchmark::State& state) {\n\tconst unsigned v = state.range(0);\n\tauto g = gen_random_connected_graph<Graph>(v, (double)num/div);\n\tauto o = gen_random_order(g);\n\tassert(boost::num_vertices(g) == v);\n\n\t// Benchmark fill_in() instead of fill() as it is the exact same function as\n\t// fill(), except that it does not modify the graph, and therefore does not\n\t// require the overhead of graph creation for every single benchmarking\n\t// iteration.\n\tfor (auto _ : state)\n\t\tbenchmark::DoNotOptimize(fill_in(g, o));\n\n\tauto n = boost::num_vertices(g) + boost::num_edges(g);\n\tstate.counters[\"n\"] = n;\n\tstate.counters[\"v\"] = boost::num_vertices(g);\n\tstate.SetComplexityN(n);\n}\n\ntemplate <unsigned num, unsigned div>\nvoid lex_m_random_graph(benchmark::State& state) {\n\tconst unsigned v = state.range(0);\n\tauto g = gen_random_connected_graph<Graph>(v, (double)num/div);\n\tassert(boost::num_vertices(g) == v);\n\n\tfor (auto _ : state)\n\t\tbenchmark::DoNotOptimize(lex_m(g));\n\n\tconst auto n = boost::num_vertices(g) * boost::num_edges(g);\n\tstate.counters[\"n\"] = n;\n\tstate.counters[\"v\"] = boost::num_vertices(g);\n\tstate.SetComplexityN(n);\n}\n\ntemplate <unsigned num, unsigned div>\nvoid lex_p_random_graph(benchmark::State& state) {\n\tconst unsigned v = state.range(0);\n\tauto g = gen_random_connected_graph<Graph>(v, (double)num/div);\n\tassert(boost::num_vertices(g) == v);\n\n\tif (num != div)\n\t\tfill(g, lex_m(g));\n\n\tfor (auto _ : state)\n\t\tbenchmark::DoNotOptimize(lex_p(g));\n\n\tauto n = boost::num_vertices(g) + boost::num_edges(g);\n\tstate.counters[\"n\"] = n;\n\tstate.counters[\"v\"] = boost::num_vertices(g);\n\tstate.SetComplexityN(n);\n}\n\n#define bench(func, num, div, start, end, step) \\\n\tBENCHMARK_TEMPLATE(func , num, div)         \\\n\t\t->DenseRange(start, end, step)          \\\n\t\t->Complexity(benchmark::oN)             \\\n\t\t->Unit(benchmark::kMillisecond)\n\nbench(fill_in_random_graph, 1, 10, 100, 1000, 100); // edge density  10%\nbench(fill_in_random_graph, 1,  4, 100, 1000, 100); // edge density  25%\nbench(fill_in_random_graph, 1,  2, 100, 1000, 100); // edge density  50%\nbench(fill_in_random_graph, 2,  3, 100, 1000, 100); // edge density  66%\nbench(fill_in_random_graph, 3,  4, 100, 1000, 100); // edge density  75%\nbench(fill_in_random_graph, 1,  1, 100, 1000, 100); // edge density 100% (complete graph)\n\nbench(lex_m_random_graph  , 1, 10, 100, 1000, 100); // edge density  10%\nbench(lex_m_random_graph  , 1,  4, 100, 1000, 100); // edge density  25%\nbench(lex_m_random_graph  , 1,  2, 100, 1000, 100); // edge density  50%\nbench(lex_m_random_graph  , 2,  3, 100, 1000, 100); // edge density  66%\nbench(lex_m_random_graph  , 3,  4, 100, 1000, 100); // edge density  75%\nbench(lex_m_random_graph  , 1,  1, 100, 1000, 100); // edge density 100% (complete graph)\n\nbench(lex_p_random_graph  , 1, 10, 100, 1000, 100); // edge density  10%\nbench(lex_p_random_graph  , 1,  4, 100, 1000, 100); // edge density  25%\nbench(lex_p_random_graph  , 1,  2, 100, 1000, 100); // edge density  50%\nbench(lex_p_random_graph  , 2,  3, 100, 1000, 100); // edge density  66%\nbench(lex_p_random_graph  , 3,  4, 100, 1000, 100); // edge density  75%\nbench(lex_p_random_graph  , 1,  1, 100, 1000, 100); // edge density 100% (complete graph)\n\nBENCHMARK_MAIN();\n", "meta": {"hexsha": "32f04a7f29fcc04cafac3ed32389c2c17d229e1e", "size": 3502, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/bench/bench_time.cc", "max_stars_repo_name": "mebeim/aa_project", "max_stars_repo_head_hexsha": "074ce8388e4e448b9d846e8b329ff57fb39e6637", "max_stars_repo_licenses": ["Apache-2.0"], "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/bench/bench_time.cc", "max_issues_repo_name": "mebeim/aa_project", "max_issues_repo_head_hexsha": "074ce8388e4e448b9d846e8b329ff57fb39e6637", "max_issues_repo_licenses": ["Apache-2.0"], "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/bench/bench_time.cc", "max_forks_repo_name": "mebeim/aa_project", "max_forks_repo_head_hexsha": "074ce8388e4e448b9d846e8b329ff57fb39e6637", "max_forks_repo_licenses": ["Apache-2.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.4835164835, "max_line_length": 89, "alphanum_fraction": 0.6901770417, "num_tokens": 1146, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.63341027751814, "lm_q1q2_score": 0.4799947430107545}}
{"text": "#ifndef CAPPA_CLUSTER_PAM_HPP\n#define CAPPA_CLUSTER_PAM_HPP\n\n#include <Eigen/Dense>\n\n#include <map>\n#include <set>\n#include <vector>\n\nnamespace cluster {\n\n/**\n * The clustering result after partitioning around medoids.\n */\nstruct pam_result {\n  /**\n   * The objects that were found to be medoids.\n   */\n  std::set<int> medoids;\n\n  /**\n   * The cluster ID each medoid was mapped to.\n   */\n  std::map<int, int> medoid_to_cluster;\n\n  /**\n   * The cluster ID each object was assigned to by the algorithm.\n   */\n  std::vector<int> classification;\n};\n\n/**\n * Minimize the sum of dissimilarities to a set of k medoids.\n *\n * @param k The number of clusters.\n * @param matrix The objects observed.\n *\n * @return The clustering found.\n */\npam_result partition_around_medoids(int k, Eigen::MatrixXd const &matrix);\n}\n\n#endif //CAPPA_CLUSTER_PAM_HPP\n", "meta": {"hexsha": "8e85e8dca131cf4e6ae63c7040a5ac36ebb112fc", "size": 839, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/cluster/pam.hpp", "max_stars_repo_name": "cappa-framework/cluster", "max_stars_repo_head_hexsha": "be199505293b4a6b43774deeaad87452ad6cf1e9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-01-17T13:53:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-11T05:09:59.000Z", "max_issues_repo_path": "include/cluster/pam.hpp", "max_issues_repo_name": "cappa-framework/cluster", "max_issues_repo_head_hexsha": "be199505293b4a6b43774deeaad87452ad6cf1e9", "max_issues_repo_licenses": ["Apache-2.0"], "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/cluster/pam.hpp", "max_forks_repo_name": "cappa-framework/cluster", "max_forks_repo_head_hexsha": "be199505293b4a6b43774deeaad87452ad6cf1e9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-10-17T20:12:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-17T20:12:36.000Z", "avg_line_length": 19.0681818182, "max_line_length": 74, "alphanum_fraction": 0.6972586412, "num_tokens": 208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.63341027751814, "lm_q1q2_score": 0.4799947430107545}}
{"text": "//\n// Copyright 2020 Debabrata Mandal <mandaldebabrata123@gmail.com>\n//\n// Use, modification and distribution are subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//\n\n#include <boost/gil/histogram.hpp>\n#include <boost/gil/image_view.hpp>\n#include <boost/gil/image_processing/histogram_equalization.hpp>\n#include <boost/gil/image_processing/adaptive_histogram_equalization.hpp>\n\n#include <boost/core/lightweight_test.hpp>\n\n#include <cmath>\n#include <vector>\n\nnamespace gil = boost::gil;\n\ndouble epsilon = 1.0;\n\nstd::uint8_t image_matrix[] = \n{\n    1, 1, 1, 1, \n    3, 3, 3, 3, \n    5, 5, 5, 5,\n    7, 7, 7, 7\n};\ngil::gray8c_view_t gray_view = gil::interleaved_view(4, 4, reinterpret_cast<gil::gray8c_pixel_t*>(image_matrix), 4);\n\nvoid check_actual_clip_limit()\n{\n    gil::histogram<unsigned char> h;\n    for(std::size_t i = 0; i < 100; i++)\n    {\n        if (i % 40 == 0)\n        {\n            h(i) = 60;\n        }\n        else\n        {\n            h(i) = 5;\n        }\n    }\n    double limit = 0.01;\n    double value = gil::detail::actual_clip_limit(h, limit);\n\n    long actual_limit = round(value * h.sum()), max_bin_val = 0;\n    double excess = 0;\n    for(std::size_t i = 0; i < 100; i++)\n    {\n        if (h(i) > actual_limit)\n            excess += actual_limit - h(i);\n        max_bin_val = std::max<long>(max_bin_val, h(i));\n    }\n    BOOST_TEST((std::abs(excess / h.size() + actual_limit) - limit * h.sum()) < epsilon);\n}\n\nvoid check_clip_and_redistribute()\n{\n    gil::histogram<unsigned char> h, h2;\n    for(std::size_t i = 0; i < 100; i++)\n    {\n        if (i % 50 == 0)\n        {\n            h(i) = 60;\n        }\n        else\n        {\n            h(i) = 5;\n        }\n    }\n    bool check = true;\n    double limit = 0.001; \n    gil::detail::clip_and_redistribute(h, h2, limit);\n    for(std::size_t i = 0; i < 100; i++)\n    {\n        check = check & (std::abs(limit * h.sum() - h2(i)) < epsilon);\n    }\n    BOOST_TEST(check);\n}\n\nvoid check_non_overlapping_interpolated_clahe()\n{\n    {\n        gil::gray8_image_t img1(4, 4), img2(4, 4), img3(4, 4);\n        gil::histogram_equalization(gray_view, view(img2));\n        gil::non_overlapping_interpolated_clahe(gray_view, view(img3), 8, 8, 1.0);\n        BOOST_TEST(gil::equal_pixels(view(img2), view(img3)));\n    }\n    {\n        gil::gray8_image_t img1(8, 8), img2(8, 8), img3(4, 4);\n        gil::copy_pixels(gray_view, gil::subimage_view(view(img1), 0, 0, 4, 4));\n        gil::copy_pixels(gray_view, gil::subimage_view(view(img1), 0, 4, 4, 4));\n        gil::copy_pixels(gray_view, gil::subimage_view(view(img1), 4, 0, 4, 4));\n        gil::copy_pixels(gray_view, gil::subimage_view(view(img1), 4, 4, 4, 4));\n        gil::histogram_equalization(gray_view, view(img3));\n        gil::non_overlapping_interpolated_clahe(view(img1), view(img2), 8, 8, 1.0);\n        BOOST_TEST(gil::equal_pixels(gil::subimage_view(view(img2), 0, 0, 4, 4), view(img3)));\n        BOOST_TEST(gil::equal_pixels(gil::subimage_view(view(img2), 0, 4, 4, 4), view(img3)));\n        BOOST_TEST(gil::equal_pixels(gil::subimage_view(view(img2), 4, 0, 4, 4), view(img3)));\n        BOOST_TEST(gil::equal_pixels(gil::subimage_view(view(img2), 4, 4, 4, 4), view(img3)));\n    }\n}\n\nint main()\n{\n    check_actual_clip_limit();\n    check_clip_and_redistribute();\n    check_non_overlapping_interpolated_clahe();\n\n    return boost::report_errors();\n}\n", "meta": {"hexsha": "b625d0b6b581189953ca8dd68b2496bdf324275c", "size": 3456, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/core/image_processing/adaptive_he.cpp", "max_stars_repo_name": "harsh-4/gil", "max_stars_repo_head_hexsha": "6da59cc3351e5657275d3a536e0b6e7a1b6ac738", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 153.0, "max_stars_repo_stars_event_min_datetime": "2015-02-03T06:03:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T15:06:34.000Z", "max_issues_repo_path": "test/core/image_processing/adaptive_he.cpp", "max_issues_repo_name": "harsh-4/gil", "max_issues_repo_head_hexsha": "6da59cc3351e5657275d3a536e0b6e7a1b6ac738", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 429.0, "max_issues_repo_issues_event_min_datetime": "2015-03-22T09:49:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T08:32:08.000Z", "max_forks_repo_path": "test/core/image_processing/adaptive_he.cpp", "max_forks_repo_name": "harsh-4/gil", "max_forks_repo_head_hexsha": "6da59cc3351e5657275d3a536e0b6e7a1b6ac738", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-03-15T09:20:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T12:40:07.000Z", "avg_line_length": 30.052173913, "max_line_length": 116, "alphanum_fraction": 0.6056134259, "num_tokens": 1124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.63341027751814, "lm_q1q2_score": 0.4799947430107545}}
{"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_ATAN2D_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_ATAN2D_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 atan2d function : atan2 in degrees.\n\n\n    @par Header <boost/simd/function/atan2d.hpp>\n\n    @par Note\n\n      For every parameters of same floating type\n      `atan2d(y, x)` is similar  to: `indeg(atan2(y, x))`\n\n    @see atan2,  atan2pi\n\n    @par Example:\n\n      @snippet atan2d.cpp atan2d\n\n    @par Possible output:\n\n      @snippet atan2d.txt atan2d\n\n  **/\n  IEEEValue atan2d(IEEEValue const& y, IEEEValue const& x );\n} }\n#endif\n\n#include <boost/simd/function/scalar/atan2d.hpp>\n#include <boost/simd/function/simd/atan2d.hpp>\n\n#endif\n", "meta": {"hexsha": "8248eab792062ee09ab9a249a33f6d2352769c59", "size": 1163, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/atan2d.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/atan2d.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/atan2d.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 23.7346938776, "max_line_length": 100, "alphanum_fraction": 0.5872742906, "num_tokens": 275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6334102775181399, "lm_q1q2_score": 0.47999474301075445}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n  Copyright (C) 2008, 2009 Klaus Spanderen\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n#include \"fdheston.hpp\"\n#include \"utilities.hpp\"\n\n#include <ql/quotes/simplequote.hpp>\n#include <ql/time/daycounters/actual360.hpp>\n#include <ql/time/daycounters/actualactual.hpp>\n#include <ql/time/daycounters/actual365fixed.hpp>\n#include <ql/instruments/barrieroption.hpp>\n#include <ql/instruments/vanillaoption.hpp>\n#include <ql/instruments/dividendvanillaoption.hpp>\n#include <ql/math/incompletegamma.hpp>\n#include <ql/math/functional.hpp>\n#include <ql/math/solvers1d/brent.hpp>\n#include <ql/math/distributions/gammadistribution.hpp>\n#include <ql/math/interpolations/cubicinterpolation.hpp>\n#include <ql/math/interpolations/bilinearinterpolation.hpp>\n#include <ql/math/integrals/gausslobattointegral.hpp>\n#include <ql/math/integrals/trapezoidintegral.hpp>\n#include <ql/math/integrals/twodimensionalintegral.hpp>\n#include <ql/models/equity/hestonmodel.hpp>\n#include <ql/termstructures/yield/zerocurve.hpp>\n#include <ql/pricingengines/barrier/analyticbarrierengine.hpp>\n#include <ql/pricingengines/vanilla/analytichestonengine.hpp>\n#include <ql/pricingengines/vanilla/analyticeuropeanengine.hpp>\n#include <ql/pricingengines/barrier/fdhestonbarrierengine.hpp>\n#include <ql/pricingengines/vanilla/fdhestonvanillaengine.hpp>\n#include <ql/pricingengines/barrier/fdblackscholesbarrierengine.hpp>\n#include <ql/methods/finitedifferences/meshers/fdmmesher.hpp>\n#include <ql/methods/finitedifferences/meshers/fdmmeshercomposite.hpp>\n#include <ql/methods/finitedifferences/meshers/fdmblackscholesmesher.hpp>\n#include <ql/methods/finitedifferences/meshers/predefined1dmesher.hpp>\n#include <ql/methods/finitedifferences/meshers/uniform1dmesher.hpp>\n#include <ql/methods/finitedifferences/schemes/douglasscheme.hpp>\n#include <ql/methods/finitedifferences/schemes/hundsdorferscheme.hpp>\n#include <ql/methods/finitedifferences/solvers/fdmbackwardsolver.hpp>\n#include <ql/methods/finitedifferences/operators/fdmlinearoplayout.hpp>\n#include <ql/experimental/finitedifferences/fdmblackscholesfwdop.hpp>\n#include <ql/experimental/finitedifferences/fdmsquarerootfwdop.hpp>\n#include <ql/experimental/finitedifferences/fdmhestonfwdop.hpp>\n#if defined(__GNUC__) && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 8)) || (__GNUC__ > 4))\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wunused-local-typedefs\"\n#endif\n#include <boost/math/special_functions/gamma.hpp>\n#if defined(__GNUC__) && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 8)) || (__GNUC__ > 4))\n#pragma GCC diagnostic pop\n#endif\n#include <boost/math/distributions/non_central_chi_squared.hpp>\n\nusing namespace QuantLib;\nusing boost::unit_test_framework::test_suite;\n\nnamespace {\n    struct NewBarrierOptionData {\n        Barrier::Type barrierType;\n        Real barrier;\n        Real rebate;\n        Option::Type type;\n        Real strike;\n        Real s;        // spot\n        Rate q;        // dividend\n        Rate r;        // risk-free rate\n        Time t;        // time to maturity\n        Volatility v;  // volatility\n    };\n}\n\nvoid FdHestonTest::testFdmHestonBarrierVsBlackScholes() {\n\n    BOOST_TEST_MESSAGE(\"Testing FDM with barrier option in Heston model...\");\n\n    SavedSettings backup;\n\n    NewBarrierOptionData values[] = {\n        /* The data below are from\n          \"Option pricing formulas\", E.G. Haug, McGraw-Hill 1998 pag. 72\n        */\n        //     barrierType, barrier, rebate,         type, strike,     s,    q,    r,    t,    v\n        { Barrier::DownOut,    95.0,    3.0, Option::Call,     90, 100.0, 0.04, 0.08, 0.50, 0.25},\n        { Barrier::DownOut,    95.0,    3.0, Option::Call,    100, 100.0, 0.00, 0.08, 1.00, 0.30},\n        { Barrier::DownOut,    95.0,    3.0, Option::Call,    110, 100.0, 0.04, 0.08, 0.50, 0.25},\n        { Barrier::DownOut,   100.0,    3.0, Option::Call,     90, 100.0, 0.00, 0.08, 0.25, 0.25},\n        { Barrier::DownOut,   100.0,    3.0, Option::Call,    100, 100.0, 0.04, 0.08, 0.50, 0.25},\n        { Barrier::DownOut,   100.0,    3.0, Option::Call,    110, 100.0, 0.04, 0.08, 0.50, 0.25},\n        { Barrier::UpOut,     105.0,    3.0, Option::Call,     90, 100.0, 0.04, 0.08, 0.50, 0.25},\n        { Barrier::UpOut,     105.0,    3.0, Option::Call,    100, 100.0, 0.04, 0.08, 0.50, 0.25},\n        { Barrier::UpOut,     105.0,    3.0, Option::Call,    110, 100.0, 0.04, 0.08, 0.50, 0.25},\n\n        { Barrier::DownIn,     95.0,    3.0, Option::Call,    90, 100.0, 0.04, 0.08, 0.50, 0.25},\n        { Barrier::DownIn,     95.0,    3.0, Option::Call,   100, 100.0, 0.04, 0.08, 0.50, 0.25},\n        { Barrier::DownIn,     95.0,    3.0, Option::Call,   110, 100.0, 0.04, 0.08, 0.50, 0.25},\n        { Barrier::DownIn,    100.0,    3.0, Option::Call,    90, 100.0, 0.00, 0.08, 0.25, 0.25},\n        { Barrier::DownIn,    100.0,    3.0, Option::Call,   100, 100.0, 0.04, 0.08, 0.50, 0.25},\n        { Barrier::DownIn,    100.0,    3.0, Option::Call,   110, 100.0, 0.04, 0.08, 0.50, 0.25},\n        { Barrier::UpIn,      105.0,    3.0, Option::Call,    90, 100.0, 0.04, 0.08, 0.50, 0.25},\n        { Barrier::UpIn,      105.0,    3.0, Option::Call,   100, 100.0, 0.00, 0.08, 0.40, 0.25},\n        { Barrier::UpIn,      105.0,    3.0, Option::Call,   110, 100.0, 0.04, 0.08, 0.50, 0.15},\n\n        { Barrier::DownOut,    95.0,    3.0, Option::Call,    90, 100.0, 0.04, 0.08, 0.50, 0.30},\n        { Barrier::DownOut,    95.0,    3.0, Option::Call,   100, 100.0, 0.00, 0.08, 0.40, 0.35},\n        { Barrier::DownOut,    95.0,    3.0, Option::Call,   110, 100.0, 0.04, 0.08, 0.50, 0.30},\n        { Barrier::DownOut,   100.0,    3.0, Option::Call,    90, 100.0, 0.04, 0.08, 0.50, 0.15},\n        { Barrier::DownOut,   100.0,    3.0, Option::Call,   100, 100.0, 0.04, 0.08, 0.50, 0.30},\n        { Barrier::DownOut,   100.0,    3.0, Option::Call,   110, 100.0, 0.00, 0.00, 1.00, 0.20},\n        { Barrier::UpOut,     105.0,    3.0, Option::Call,    90, 100.0, 0.04, 0.08, 0.50, 0.30},\n        { Barrier::UpOut,     105.0,    3.0, Option::Call,   100, 100.0, 0.04, 0.08, 0.50, 0.30},\n        { Barrier::UpOut,     105.0,    3.0, Option::Call,   110, 100.0, 0.04, 0.08, 0.50, 0.30},\n\n        { Barrier::DownIn,     95.0,    3.0, Option::Call,    90, 100.0, 0.04, 0.08, 0.50, 0.30},\n        { Barrier::DownIn,     95.0,    3.0, Option::Call,   100, 100.0, 0.04, 0.08, 0.50, 0.30},\n        { Barrier::DownIn,     95.0,    3.0, Option::Call,   110, 100.0, 0.00, 0.08, 1.00, 0.30},\n        { Barrier::DownIn,    100.0,    3.0, Option::Call,    90, 100.0, 0.04, 0.08, 0.50, 0.30},\n        { Barrier::DownIn,    100.0,    3.0, Option::Call,   100, 100.0, 0.04, 0.08, 0.50, 0.30},\n        { Barrier::DownIn,    100.0,    3.0, Option::Call,   110, 100.0, 0.04, 0.08, 0.50, 0.30},\n        { Barrier::UpIn,      105.0,    3.0, Option::Call,    90, 100.0, 0.04, 0.08, 0.50, 0.30},\n        { Barrier::UpIn,      105.0,    3.0, Option::Call,   100, 100.0, 0.04, 0.08, 0.50, 0.30},\n        { Barrier::UpIn,      105.0,    3.0, Option::Call,   110, 100.0, 0.04, 0.08, 0.50, 0.30},\n\n        { Barrier::DownOut,    95.0,    3.0,  Option::Put,    90, 100.0, 0.04, 0.08, 0.50, 0.25},\n        { Barrier::DownOut,    95.0,    3.0,  Option::Put,   100, 100.0, 0.04, 0.08, 0.50, 0.25},\n        { Barrier::DownOut,    95.0,    3.0,  Option::Put,   110, 100.0, 0.04, 0.08, 0.50, 0.25},\n        { Barrier::DownOut,   100.0,    3.0,  Option::Put,    90, 100.0, 0.04, 0.08, 0.50, 0.25},\n        { Barrier::DownOut,   100.0,    3.0,  Option::Put,   100, 100.0, 0.04, 0.08, 0.50, 0.25},\n        { Barrier::DownOut,   100.0,    3.0,  Option::Put,   110, 100.0, 0.04, 0.08, 0.50, 0.25},\n        { Barrier::UpOut,     105.0,    3.0,  Option::Put,    90, 100.0, 0.04, 0.08, 0.50, 0.25},\n        { Barrier::UpOut,     105.0,    3.0,  Option::Put,   100, 100.0, 0.04, 0.08, 0.50, 0.25},\n        { Barrier::UpOut,     105.0,    3.0,  Option::Put,   110, 100.0, 0.04, 0.08, 0.50, 0.25},\n\n        { Barrier::DownIn,     95.0,    3.0,  Option::Put,    90, 100.0, 0.04, 0.08, 0.50, 0.25},\n        { Barrier::DownIn,     95.0,    3.0,  Option::Put,   100, 100.0, 0.04, 0.08, 0.50, 0.25},\n        { Barrier::DownIn,     95.0,    3.0,  Option::Put,   110, 100.0, 0.04, 0.08, 0.50, 0.25},\n        { Barrier::DownIn,    100.0,    3.0,  Option::Put,    90, 100.0, 0.04, 0.08, 0.50, 0.25},\n        { Barrier::DownIn,    100.0,    3.0,  Option::Put,   100, 100.0, 0.04, 0.08, 0.50, 0.25},\n        { Barrier::DownIn,    100.0,    3.0,  Option::Put,   110, 100.0, 0.04, 0.08, 0.50, 0.25},\n        { Barrier::UpIn,      105.0,    3.0,  Option::Put,    90, 100.0, 0.04, 0.08, 0.50, 0.25},\n        { Barrier::UpIn,      105.0,    3.0,  Option::Put,   100, 100.0, 0.04, 0.08, 0.50, 0.25},\n        { Barrier::UpIn,      105.0,    3.0,  Option::Put,   110, 100.0, 0.00, 0.04, 1.00, 0.15},\n\n        { Barrier::DownOut,    95.0,    3.0,  Option::Put,    90, 100.0, 0.04, 0.08, 0.50, 0.30},\n        { Barrier::DownOut,    95.0,    3.0,  Option::Put,   100, 100.0, 0.04, 0.08, 0.50, 0.30},\n        { Barrier::DownOut,    95.0,    3.0,  Option::Put,   110, 100.0, 0.04, 0.08, 0.50, 0.30},\n        { Barrier::DownOut,   100.0,    3.0,  Option::Put,    90, 100.0, 0.04, 0.08, 0.50, 0.30},\n        { Barrier::DownOut,   100.0,    3.0,  Option::Put,   100, 100.0, 0.04, 0.08, 0.50, 0.30},\n        { Barrier::DownOut,   100.0,    3.0,  Option::Put,   110, 100.0, 0.04, 0.08, 0.50, 0.30},\n        { Barrier::UpOut,     105.0,    3.0,  Option::Put,    90, 100.0, 0.04, 0.08, 0.50, 0.30},\n        { Barrier::UpOut,     105.0,    3.0,  Option::Put,   100, 100.0, 0.04, 0.08, 0.50, 0.30},\n        { Barrier::UpOut,     105.0,    3.0,  Option::Put,   110, 100.0, 0.04, 0.08, 0.50, 0.30},\n\n        { Barrier::DownIn,     95.0,    3.0,  Option::Put,    90, 100.0, 0.04, 0.08, 0.50, 0.30},\n        { Barrier::DownIn,     95.0,    3.0,  Option::Put,   100, 100.0, 0.04, 0.08, 0.50, 0.30},\n        { Barrier::DownIn,     95.0,    3.0,  Option::Put,   110, 100.0, 0.04, 0.08, 0.50, 0.30},\n        { Barrier::DownIn,    100.0,    3.0,  Option::Put,    90, 100.0, 0.04, 0.08, 0.50, 0.30},\n        { Barrier::DownIn,    100.0,    3.0,  Option::Put,   100, 100.0, 0.04, 0.08, 0.50, 0.30},\n        { Barrier::DownIn,    100.0,    3.0,  Option::Put,   110, 100.0, 0.04, 0.08, 1.00, 0.15},\n        { Barrier::UpIn,      105.0,    3.0,  Option::Put,    90, 100.0, 0.04, 0.08, 0.50, 0.30},\n        { Barrier::UpIn,      105.0,    3.0,  Option::Put,   100, 100.0, 0.04, 0.08, 0.50, 0.30},\n        { Barrier::UpIn,      105.0,    3.0,  Option::Put,   110, 100.0, 0.04, 0.08, 0.50, 0.30}\n    };\n    \n    const DayCounter dc = Actual365Fixed();     \n    const Date todaysDate(28, March, 2004);\n    const Date exerciseDate(28, March, 2005);\n    Settings::instance().evaluationDate() = todaysDate;\n\n    Handle<Quote> spot(\n            boost::shared_ptr<Quote>(new SimpleQuote(0.0)));\n    boost::shared_ptr<SimpleQuote> qRate(new SimpleQuote(0.0));\n    Handle<YieldTermStructure> qTS(flatRate(qRate, dc));\n    boost::shared_ptr<SimpleQuote> rRate(new SimpleQuote(0.0));\n    Handle<YieldTermStructure> rTS(flatRate(rRate, dc));\n    boost::shared_ptr<SimpleQuote> vol(new SimpleQuote(0.0));\n    Handle<BlackVolTermStructure> volTS(flatVol(vol, dc));\n\n    boost::shared_ptr<BlackScholesMertonProcess> bsProcess(\n                      new BlackScholesMertonProcess(spot, qTS, rTS, volTS));\n\n    boost::shared_ptr<PricingEngine> analyticEngine(\n                                        new AnalyticBarrierEngine(bsProcess));\n    \n    for (Size i=0; i<LENGTH(values); i++) {\n        Date exDate = todaysDate + Integer(values[i].t*365+0.5);\n        boost::shared_ptr<Exercise> exercise(new EuropeanExercise(exDate));\n\n        boost::dynamic_pointer_cast<SimpleQuote>(spot .currentLink())\n                                                    ->setValue(values[i].s);\n        qRate->setValue(values[i].q);\n        rRate->setValue(values[i].r);\n        vol  ->setValue(values[i].v);\n\n        boost::shared_ptr<StrikedTypePayoff> payoff(new\n                    PlainVanillaPayoff(values[i].type, values[i].strike));\n\n        BarrierOption barrierOption(values[i].barrierType, values[i].barrier,\n                                    values[i].rebate, payoff, exercise);\n\n        const Real v0 = vol->value()*vol->value();\n        boost::shared_ptr<HestonProcess> hestonProcess(\n             new HestonProcess(rTS, qTS, spot, v0, 1.0, v0, 0.00001, 0.0));\n\n        barrierOption.setPricingEngine(boost::shared_ptr<PricingEngine>(\n            new FdHestonBarrierEngine(boost::shared_ptr<HestonModel>(\n                              new HestonModel(hestonProcess)), 200, 400, 3)));\n\n        const Real calculatedHE = barrierOption.NPV();\n    \n        barrierOption.setPricingEngine(analyticEngine);\n        const Real expected = barrierOption.NPV();\n    \n        const Real tol = 0.002;\n        if (std::fabs(calculatedHE - expected)/expected > tol) {\n            BOOST_ERROR(\"Failed to reproduce expected Heston npv\"\n                        << \"\\n    calculated: \" << calculatedHE\n                        << \"\\n    expected:   \" << expected\n                        << \"\\n    tolerance:  \" << tol); \n        }\n    }\n}\n\nvoid FdHestonTest::testFdmHestonBarrier() {\n\n    BOOST_TEST_MESSAGE(\"Testing FDM with barrier option for Heston model vs \"\n                       \"Black-Scholes model...\");\n\n    SavedSettings backup;\n\n    Handle<Quote> s0(boost::shared_ptr<Quote>(new SimpleQuote(100.0)));\n\n    Handle<YieldTermStructure> rTS(flatRate(0.05, Actual365Fixed()));\n    Handle<YieldTermStructure> qTS(flatRate(0.0 , Actual365Fixed()));\n\n    boost::shared_ptr<HestonProcess> hestonProcess(\n        new HestonProcess(rTS, qTS, s0, 0.04, 2.5, 0.04, 0.66, -0.8));\n\n    Settings::instance().evaluationDate() = Date(28, March, 2004);\n    Date exerciseDate(28, March, 2005);\n\n    boost::shared_ptr<Exercise> exercise(new EuropeanExercise(exerciseDate));\n\n    boost::shared_ptr<StrikedTypePayoff> payoff(new\n                                      PlainVanillaPayoff(Option::Call, 100));\n\n    BarrierOption barrierOption(Barrier::UpOut, 135, 0.0, payoff, exercise);\n\n    barrierOption.setPricingEngine(boost::shared_ptr<PricingEngine>(\n            new FdHestonBarrierEngine(boost::shared_ptr<HestonModel>(\n                              new HestonModel(hestonProcess)), 50, 400, 100)));\n\n    const Real tol = 0.01;\n    const Real npvExpected   =  9.1530;\n    const Real deltaExpected =  0.5218;\n    const Real gammaExpected = -0.0354;\n\n    if (std::fabs(barrierOption.NPV() - npvExpected) > tol) {\n        BOOST_ERROR(\"Failed to reproduce expected npv\"\n                    << \"\\n    calculated: \" << barrierOption.NPV()\n                    << \"\\n    expected:   \" << npvExpected\n                    << \"\\n    tolerance:  \" << tol); \n    }\n    if (std::fabs(barrierOption.delta() - deltaExpected) > tol) {\n        BOOST_ERROR(\"Failed to reproduce expected delta\"\n                    << \"\\n    calculated: \" << barrierOption.delta()\n                    << \"\\n    expected:   \" << deltaExpected\n                    << \"\\n    tolerance:  \" << tol); \n    }\n    if (std::fabs(barrierOption.gamma() - gammaExpected) > tol) {\n        BOOST_ERROR(\"Failed to reproduce expected gamma\"\n                    << \"\\n    calculated: \" << barrierOption.gamma()\n                    << \"\\n    expected:   \" << gammaExpected\n                    << \"\\n    tolerance:  \" << tol); \n    }\n}\n\nvoid FdHestonTest::testFdmHestonAmerican() {\n\n    BOOST_TEST_MESSAGE(\"Testing FDM with American option in Heston model...\");\n\n    SavedSettings backup;\n\n    Handle<Quote> s0(boost::shared_ptr<Quote>(new SimpleQuote(100.0)));\n\n    Handle<YieldTermStructure> rTS(flatRate(0.05, Actual365Fixed()));\n    Handle<YieldTermStructure> qTS(flatRate(0.0 , Actual365Fixed()));\n\n    boost::shared_ptr<HestonProcess> hestonProcess(\n        new HestonProcess(rTS, qTS, s0, 0.04, 2.5, 0.04, 0.66, -0.8));\n\n    Settings::instance().evaluationDate() = Date(28, March, 2004);\n    Date exerciseDate(28, March, 2005);\n\n    boost::shared_ptr<Exercise> exercise(new AmericanExercise(exerciseDate));\n\n    boost::shared_ptr<StrikedTypePayoff> payoff(new\n                                      PlainVanillaPayoff(Option::Put, 100));\n\n    VanillaOption option(payoff, exercise);\n    boost::shared_ptr<PricingEngine> engine(\n         new FdHestonVanillaEngine(boost::shared_ptr<HestonModel>(\n                             new HestonModel(hestonProcess)), 200, 100, 50));\n    option.setPricingEngine(engine);\n    \n    const Real tol = 0.01;\n    const Real npvExpected   =  5.66032;\n    const Real deltaExpected = -0.30065;\n    const Real gammaExpected =  0.02202;\n    \n    if (std::fabs(option.NPV() - npvExpected) > tol) {\n        BOOST_ERROR(\"Failed to reproduce expected npv\"\n                    << \"\\n    calculated: \" << option.NPV()\n                    << \"\\n    expected:   \" << npvExpected\n                    << \"\\n    tolerance:  \" << tol); \n    }\n    if (std::fabs(option.delta() - deltaExpected) > tol) {\n        BOOST_ERROR(\"Failed to reproduce expected delta\"\n                    << \"\\n    calculated: \" << option.delta()\n                    << \"\\n    expected:   \" << deltaExpected\n                    << \"\\n    tolerance:  \" << tol); \n    }\n    if (std::fabs(option.gamma() - gammaExpected) > tol) {\n        BOOST_ERROR(\"Failed to reproduce expected gamma\"\n                    << \"\\n    calculated: \" << option.gamma()\n                    << \"\\n    expected:   \" << gammaExpected\n                    << \"\\n    tolerance:  \" << tol); \n    }\n}\n\n\nvoid FdHestonTest::testFdmHestonIkonenToivanen() {\n\n    BOOST_TEST_MESSAGE(\"Testing FDM Heston for Ikonen and Toivanen tests...\");\n\n    /* check prices of american puts as given in:\n       From Efficient numerical methods for pricing American options under \n       stochastic volatility, Samuli Ikonen, Jari Toivanen, \n       http://users.jyu.fi/~tene/papers/reportB12-05.pdf\n    */\n    SavedSettings backup;\n\n    Handle<YieldTermStructure> rTS(flatRate(0.10, Actual360()));\n    Handle<YieldTermStructure> qTS(flatRate(0.0 , Actual360()));\n\n    Settings::instance().evaluationDate() = Date(28, March, 2004);\n    Date exerciseDate(26, June, 2004);\n\n    boost::shared_ptr<Exercise> exercise(new AmericanExercise(exerciseDate));\n\n    boost::shared_ptr<StrikedTypePayoff> payoff(new\n                                      PlainVanillaPayoff(Option::Put, 10));\n\n    VanillaOption option(payoff, exercise);\n\n    Real strikes[]  = { 8, 9, 10, 11, 12 };\n    Real expected[] = { 2.00000, 1.10763, 0.520038, 0.213681, 0.082046 };\n    const Real tol = 0.001;\n    \n    for (Size i=0; i < LENGTH(strikes); ++i) {\n        Handle<Quote> s0(boost::shared_ptr<Quote>(new SimpleQuote(strikes[i])));\n        boost::shared_ptr<HestonProcess> hestonProcess(\n            new HestonProcess(rTS, qTS, s0, 0.0625, 5, 0.16, 0.9, 0.1));\n    \n        boost::shared_ptr<PricingEngine> engine(\n             new FdHestonVanillaEngine(boost::shared_ptr<HestonModel>(\n                                 new HestonModel(hestonProcess)), 100, 400));\n        option.setPricingEngine(engine);\n        \n        Real calculated = option.NPV();\n        if (std::fabs(calculated - expected[i]) > tol) {\n            BOOST_ERROR(\"Failed to reproduce expected npv\"\n                        << \"\\n    strike:     \" << strikes[i]\n                        << \"\\n    calculated: \" << calculated\n                        << \"\\n    expected:   \" << expected[i]\n                        << \"\\n    tolerance:  \" << tol); \n        }\n    }\n}\n\nvoid FdHestonTest::testFdmHestonBlackScholes() {\n\n    BOOST_TEST_MESSAGE(\"Testing FDM Heston with Black Scholes model...\");\n\n    SavedSettings backup;\n\n\n    Settings::instance().evaluationDate() = Date(28, March, 2004);\n    Date exerciseDate(26, June, 2004);\n\n    Handle<YieldTermStructure> rTS(flatRate(0.10, Actual360()));\n    Handle<YieldTermStructure> qTS(flatRate(0.0 , Actual360()));\n    Handle<BlackVolTermStructure> volTS(\n                    flatVol(rTS->referenceDate(), 0.25, rTS->dayCounter()));\n    \n    boost::shared_ptr<Exercise> exercise(new EuropeanExercise(exerciseDate));\n\n    boost::shared_ptr<StrikedTypePayoff> payoff(new\n                                      PlainVanillaPayoff(Option::Put, 10));\n\n    VanillaOption option(payoff, exercise);\n\n    Real strikes[]  = { 8, 9, 10, 11, 12 };\n    const Real tol = 0.0001;\n    \n    for (Size i=0; i < LENGTH(strikes); ++i) {\n        Handle<Quote> s0(boost::shared_ptr<Quote>(new SimpleQuote(strikes[i])));\n\n        boost::shared_ptr<GeneralizedBlackScholesProcess> bsProcess(\n                       new GeneralizedBlackScholesProcess(s0, qTS, rTS, volTS));\n\n        option.setPricingEngine(boost::shared_ptr<PricingEngine>(\n                                        new AnalyticEuropeanEngine(bsProcess)));\n        \n        const Real expected = option.NPV();\n        \n        boost::shared_ptr<HestonProcess> hestonProcess(\n            new HestonProcess(rTS, qTS, s0, 0.0625, 1, 0.0625, 0.0001, 0.0));\n\n        // Hundsdorfer scheme\n        option.setPricingEngine(boost::shared_ptr<PricingEngine>(\n             new FdHestonVanillaEngine(boost::shared_ptr<HestonModel>(\n                                           new HestonModel(hestonProcess)), \n                                       100, 400)));\n        \n        Real calculated = option.NPV();\n        if (std::fabs(calculated - expected) > tol) {\n            BOOST_ERROR(\"Failed to reproduce expected npv\"\n                        << \"\\n    strike:     \" << strikes[i]\n                        << \"\\n    calculated: \" << calculated\n                        << \"\\n    expected:   \" << expected\n                        << \"\\n    tolerance:  \" << tol); \n        }\n        \n        // Explicit scheme\n        option.setPricingEngine(boost::shared_ptr<PricingEngine>(\n             new FdHestonVanillaEngine(boost::shared_ptr<HestonModel>(\n                                           new HestonModel(hestonProcess)), \n                                       10000, 400, 5, 0, \n                                       FdmSchemeDesc::ExplicitEuler())));\n        \n        calculated = option.NPV();\n        if (std::fabs(calculated - expected) > tol) {\n            BOOST_ERROR(\"Failed to reproduce expected npv\"\n                        << \"\\n    strike:     \" << strikes[i]\n                        << \"\\n    calculated: \" << calculated\n                        << \"\\n    expected:   \" << expected\n                        << \"\\n    tolerance:  \" << tol); \n        }\n    }\n}\n\n\n\nvoid FdHestonTest::testFdmHestonEuropeanWithDividends() {\n\n    BOOST_TEST_MESSAGE(\"Testing FDM with European option with dividends\"\n                       \" in Heston model...\");\n\n    SavedSettings backup;\n\n    Handle<Quote> s0(boost::shared_ptr<Quote>(new SimpleQuote(100.0)));\n\n    Handle<YieldTermStructure> rTS(flatRate(0.05, Actual365Fixed()));\n    Handle<YieldTermStructure> qTS(flatRate(0.0 , Actual365Fixed()));\n\n    boost::shared_ptr<HestonProcess> hestonProcess(\n        new HestonProcess(rTS, qTS, s0, 0.04, 2.5, 0.04, 0.66, -0.8));\n\n    Settings::instance().evaluationDate() = Date(28, March, 2004);\n    Date exerciseDate(28, March, 2005);\n\n    boost::shared_ptr<Exercise> exercise(new AmericanExercise(exerciseDate));\n\n    boost::shared_ptr<StrikedTypePayoff> payoff(new\n                                      PlainVanillaPayoff(Option::Put, 100));\n\n    const std::vector<Real> dividends(1, 5);\n    const std::vector<Date> dividendDates(1, Date(28, September, 2004));\n\n    DividendVanillaOption option(payoff, exercise, dividendDates, dividends);\n    boost::shared_ptr<PricingEngine> engine(\n         new FdHestonVanillaEngine(boost::shared_ptr<HestonModel>(\n                             new HestonModel(hestonProcess)), 50, 100, 50));\n    option.setPricingEngine(engine);\n    \n    const Real tol = 0.01;\n    const Real gammaTol = 0.001;\n    const Real npvExpected   =  7.365075;\n    const Real deltaExpected = -0.396678;\n    const Real gammaExpected =  0.027681;\n        \n    if (std::fabs(option.NPV() - npvExpected) > tol) {\n        BOOST_ERROR(\"Failed to reproduce expected npv\"\n                    << \"\\n    calculated: \" << option.NPV()\n                    << \"\\n    expected:   \" << npvExpected\n                    << \"\\n    tolerance:  \" << tol); \n    }\n    if (std::fabs(option.delta() - deltaExpected) > tol) {\n        BOOST_ERROR(\"Failed to reproduce expected delta\"\n                    << \"\\n    calculated: \" << option.delta()\n                    << \"\\n    expected:   \" << deltaExpected\n                    << \"\\n    tolerance:  \" << tol); \n    }\n    if (std::fabs(option.gamma() - gammaExpected) > gammaTol) {\n        BOOST_ERROR(\"Failed to reproduce expected gamma\"\n                    << \"\\n    calculated: \" << option.gamma()\n                    << \"\\n    expected:   \" << gammaExpected\n                    << \"\\n    tolerance:  \" << tol); \n    }\n}\n\nnamespace {\n    struct HestonTestData {\n        Real kappa;\n        Real theta;\n        Real sigma;\n        Real rho;\n        Real r;\n        Real q;\n        Real T;\n        Real K;\n    };    \n}\n\nvoid FdHestonTest::testFdmHestonConvergence() {\n\n    /* convergence tests based on \n       ADI finite difference schemes for option pricing in the\n       Heston model with correlation, K.J. in t'Hout and S. Foulon\n    */\n    \n    BOOST_TEST_MESSAGE(\"Testing FDM Heston convergence...\");\n\n    SavedSettings backup;\n    \n    HestonTestData values[] = {\n        { 1.5   , 0.04  , 0.3   , -0.9   , 0.025 , 0.0   , 1.0 , 100 },\n        { 3.0   , 0.12  , 0.04  , 0.6    , 0.01  , 0.04  , 1.0 , 100 },\n        { 0.6067, 0.0707, 0.2928, -0.7571, 0.03  , 0.0   , 3.0 , 100 },\n        { 2.5   , 0.06  , 0.5   , -0.1   , 0.0507, 0.0469, 0.25, 100 }\n    };\n\n    FdmSchemeDesc schemes[] = { FdmSchemeDesc::Hundsdorfer(), \n                                FdmSchemeDesc::ModifiedCraigSneyd(),\n                                FdmSchemeDesc::ModifiedHundsdorfer(), \n                                FdmSchemeDesc::CraigSneyd() };\n    \n    Size tn[] = { 100 };\n    Real v0[] = { 0.04 };\n    \n    const Date todaysDate(28, March, 2004); \n    Settings::instance().evaluationDate() = todaysDate;\n    \n    Handle<Quote> s0(boost::shared_ptr<Quote>(new SimpleQuote(75.0)));\n\n    for (Size l=0; l < LENGTH(schemes); ++l) {\n        for (Size i=0; i < LENGTH(values); ++i) {\n            for (Size j=0; j < LENGTH(tn); ++j) {\n                for (Size k=0; k < LENGTH(v0); ++k) {\n                    Handle<YieldTermStructure> rTS(\n                        flatRate(values[i].r, Actual365Fixed()));\n                    Handle<YieldTermStructure> qTS(\n                        flatRate(values[i].q, Actual365Fixed()));\n                \n                    boost::shared_ptr<HestonProcess> hestonProcess(\n                        new HestonProcess(rTS, qTS, s0, \n                                          v0[k], \n                                          values[i].kappa, \n                                          values[i].theta, \n                                          values[i].sigma, \n                                          values[i].rho));\n                \n                    Date exerciseDate = todaysDate \n                        + Period(static_cast<Integer>(values[i].T*365), Days);\n                    boost::shared_ptr<Exercise> exercise(\n                                          new EuropeanExercise(exerciseDate));\n                \n                    boost::shared_ptr<StrikedTypePayoff> payoff(new\n                               PlainVanillaPayoff(Option::Call, values[i].K));\n            \n                    VanillaOption option(payoff, exercise);\n                    boost::shared_ptr<PricingEngine> engine(\n                         new FdHestonVanillaEngine(\n                             boost::shared_ptr<HestonModel>(\n                                 new HestonModel(hestonProcess)), \n                             tn[j], 400, 100, 0, \n                             schemes[l]));\n                    option.setPricingEngine(engine);\n                    \n                    const Real calculated = option.NPV();\n                    \n                    boost::shared_ptr<PricingEngine> analyticEngine(\n                        new AnalyticHestonEngine(\n                            boost::shared_ptr<HestonModel>(\n                                new HestonModel(hestonProcess)), 144));\n                    \n                    option.setPricingEngine(analyticEngine);\n                    const Real expected = option.NPV();\n                    if (   std::fabs(expected - calculated)/expected > 0.02\n                        && std::fabs(expected - calculated) > 0.002) {\n                        BOOST_ERROR(\"Failed to reproduce expected npv\"\n                                    << \"\\n    calculated: \" << calculated\n                                    << \"\\n    expected:   \" << expected\n                                    << \"\\n    tolerance:  \" << 0.01); \n                    }\n                }\n            }\n        }\n    }\n}\n\nnamespace {\n    Real fokkerPlanckPrice1D(const boost::shared_ptr<FdmMesher>& mesher,\n                             const boost::shared_ptr<FdmLinearOpComposite>& op,\n                             const boost::shared_ptr<StrikedTypePayoff>& payoff,\n                             Real x0, Time maturity, Size tGrid) {\n\n        const Array x = mesher->locations(0);\n        Array p(x.size(), 0.0);\n\n        QL_REQUIRE(x.size() > 3 && x[1] <= x0 && x[x.size()-2] >= x0,\n                   \"insufficient mesher\");\n\n        const Array::const_iterator upperb\n            = std::upper_bound(x.begin(), x.end(), x0);\n        const Array::const_iterator lowerb = upperb-1;\n\n        if (close_enough(*upperb, x0)) {\n            const Size idx = std::distance(x.begin(), upperb);\n            const Real dx = (x[idx+1]-x[idx-1])/2.0;\n            p[idx] = 1.0/dx;\n        }\n        else if (close_enough(*lowerb, x0)) {\n            const Size idx = std::distance(x.begin(), lowerb);\n            const Real dx = (x[idx+1]-x[idx-1])/2.0;\n            p[idx] = 1.0/dx;\n        } else {\n            const Real dx = *upperb - *lowerb;\n            const Real lowerP = (*upperb - x0)/dx;\n            const Real upperP = (x0 - *lowerb)/dx;\n\n            const Size lowerIdx = std::distance(x.begin(), lowerb);\n            const Size upperIdx = std::distance(x.begin(), upperb);\n\n            const Real lowerDx = (x[lowerIdx+1]-x[lowerIdx-1])/2.0;\n            const Real upperDx = (x[upperIdx+1]-x[upperIdx-1])/2.0;\n\n            p[lowerIdx] = lowerP/lowerDx;\n            p[upperIdx] = upperP/upperDx;\n        }\n\n        DouglasScheme evolver(FdmSchemeDesc::Douglas().theta, op);\n        const Time dt = maturity/tGrid;\n        evolver.setStep(dt);\n\n        for (Time t=dt; t <= maturity+20*QL_EPSILON; t+=dt) {\n            evolver.step(p, t);\n        }\n\n        Array payoffTimesDensity(x.size());\n        for (Size i=0; i < x.size(); ++i) {\n            payoffTimesDensity[i] = payoff->operator()(std::exp(x[i]))*p[i];\n        }\n\n        CubicNaturalSpline f(x.begin(), x.end(), payoffTimesDensity.begin());\n        f.enableExtrapolation();\n        return GaussLobattoIntegral(1000, 1e-6)(f, x.front(), x.back());\n    }\n}\n\nvoid FdHestonTest::testBlackScholesFokkerPlanckFwdEquation() {\n    BOOST_TEST_MESSAGE(\"Testing Fokker-Planck forward equation for BS process...\");\n\n    SavedSettings backup;\n\n    const DayCounter dc = ActualActual();\n    const Date todaysDate = Date(28, Dec, 2012);\n    Settings::instance().evaluationDate() = todaysDate;\n\n    const Date maturityDate = todaysDate + Period(2, Years);\n    const Time maturity = dc.yearFraction(todaysDate, maturityDate);\n\n    const Real s0 = 100;\n    const Real x0 = std::log(s0);\n    const Rate r = 0.035;\n    const Rate q = 0.01;\n    const Volatility v = 0.35;\n\n    const Size xGrid = 2*100+1;\n    const Size tGrid = 400;\n\n    const Handle<Quote> spot(boost::shared_ptr<Quote>(new SimpleQuote(s0)));\n    const Handle<YieldTermStructure> qTS(flatRate(q, dc));\n    const Handle<YieldTermStructure> rTS(flatRate(r, dc));\n    const Handle<BlackVolTermStructure> vTS(flatVol(v, dc));\n\n    const boost::shared_ptr<GeneralizedBlackScholesProcess> process(\n        new GeneralizedBlackScholesProcess(spot, qTS, rTS, vTS));\n\n    const boost::shared_ptr<PricingEngine> engine(\n        new AnalyticEuropeanEngine(process));\n\n    const boost::shared_ptr<FdmMesher> uniformMesher(\n        new FdmMesherComposite(boost::shared_ptr<Fdm1dMesher>(\n            new FdmBlackScholesMesher(xGrid, process, maturity, s0))));\n\n    const boost::shared_ptr<FdmLinearOpComposite> uniformBSFwdOp(\n        new FdmBlackScholesFwdOp(uniformMesher, process, s0, 0));\n\n    const boost::shared_ptr<FdmMesher> concentratedMesher(\n        new FdmMesherComposite(boost::shared_ptr<Fdm1dMesher>(\n            new FdmBlackScholesMesher(xGrid, process, maturity, s0,\n                                      Null<Real>(), Null<Real>(), 0.0001, 1.5,\n                                      std::pair<Real, Real>(s0, 0.1)))));\n\n    const boost::shared_ptr<FdmLinearOpComposite> concentratedBSFwdOp(\n        new FdmBlackScholesFwdOp(concentratedMesher, process, s0, 0));\n\n    const boost::shared_ptr<FdmMesher> shiftedMesher(\n        new FdmMesherComposite(boost::shared_ptr<Fdm1dMesher>(\n            new FdmBlackScholesMesher(xGrid, process, maturity, s0,\n                                      Null<Real>(), Null<Real>(), 0.0001, 1.5,\n                                      std::pair<Real, Real>(s0*1.1, 0.2)))));\n\n    const boost::shared_ptr<FdmLinearOpComposite> shiftedBSFwdOp(\n        new FdmBlackScholesFwdOp(shiftedMesher, process, s0, 0));\n\n    const boost::shared_ptr<Exercise> exercise(\n        new EuropeanExercise(maturityDate));\n    const Real strikes[] = { 50, 80, 100, 130, 150 };\n\n    for (Size i=0; i < LENGTH(strikes); ++i) {\n        const boost::shared_ptr<StrikedTypePayoff> payoff(\n            new PlainVanillaPayoff(Option::Call, strikes[i]));\n\n        VanillaOption option(payoff, exercise);\n        option.setPricingEngine(engine);\n\n        const Real expected = option.NPV()/rTS->discount(maturityDate);\n        const Real calcUniform\n            = fokkerPlanckPrice1D(uniformMesher, uniformBSFwdOp,\n                                  payoff, x0, maturity, tGrid);\n        const Real calcConcentrated\n            = fokkerPlanckPrice1D(concentratedMesher, concentratedBSFwdOp,\n                                  payoff, x0, maturity, tGrid);\n        const Real calcShifted\n            = fokkerPlanckPrice1D(shiftedMesher, shiftedBSFwdOp,\n                                  payoff, x0, maturity, tGrid);\n        const Real tol = 0.02;\n\n        if (std::fabs(expected - calcUniform) > tol) {\n            BOOST_FAIL(\"failed to reproduce european option price \"\n                       << \"with an uniform mesher\"\n                       << \"\\n   strike:     \" << strikes[i]\n                       << QL_FIXED << std::setprecision(8)\n                       << \"\\n   calculated: \" << calcUniform\n                       << \"\\n   expected:   \" << expected\n                       << \"\\n   tolerance:  \" << tol);\n        }\n        if (std::fabs(expected - calcConcentrated) > tol) {\n            BOOST_FAIL(\"failed to reproduce european option price \"\n                       << \"with a concentrated mesher\"\n                       << \"\\n   strike:     \" << strikes[i]\n                       << QL_FIXED << std::setprecision(8)\n                       << \"\\n   calculated: \" << calcConcentrated\n                       << \"\\n   expected:   \" << expected\n                       << \"\\n   tolerance:  \" << tol);\n        }\n        if (std::fabs(expected - calcShifted) > tol) {\n            BOOST_FAIL(\"failed to reproduce european option price \"\n                       << \"with a shifted mesher\"\n                       << \"\\n   strike:     \" << strikes[i]\n                       << QL_FIXED << std::setprecision(8)\n                       << \"\\n   calculated: \" << calcShifted\n                       << \"\\n   expected:   \" << expected\n                       << \"\\n   tolerance:  \" << tol);\n        }\n    }\n}\n\n\nnamespace {\n\n    Real squareRootGreensFct(Real v0, Real kappa, Real theta,\n                             Real sigma, Real t, Real x) {\n\n        const Real ncp = 4*kappa*std::exp(-kappa*t)\n            /((sigma*sigma)*(1-std::exp(-kappa*t)))*v0;\n        const Real df  = 4*theta*kappa/(sigma*sigma);\n        const Real k = sigma*sigma*(1-std::exp(-kappa*t))/(4*kappa);\n\n        const boost::math::non_central_chi_squared_distribution<Real>\n            dist(df, ncp);\n\n        return boost::math::pdf(dist, x/k) / k;\n    }\n\n    Real stationaryProbabilityFct(Real kappa, Real theta,\n                                   Real sigma, Real v) {\n        const Real alpha = 2*kappa*theta/(sigma*sigma);\n        const Real beta = alpha/theta;\n\n        return std::pow(beta, alpha)*std::pow(v, alpha-1.0)\n                *std::exp(-beta*v-GammaFunction().logValue(alpha));\n    }\n\n    class StationaryDistributionFct : public std::unary_function<Real,Real> {\n      public:\n        StationaryDistributionFct(Real kappa, Real theta, Real sigma)\n        : kappa_(kappa), theta_(theta), sigma_(sigma) {}\n\n        Real operator()(Real v) const {\n            const Real alpha = 2*kappa_*theta_/(sigma_*sigma_);\n            const Real beta = alpha/theta_;\n\n            return boost::math::gamma_p(alpha, beta*v);\n        }\n      private:\n        const Real kappa_, theta_, sigma_;\n    };\n\n    Real invStationaryDistributionFct(Real kappa, Real theta,\n                                      Real sigma, Real q) {\n        const Real alpha = 2*kappa*theta/(sigma*sigma);\n        const Real beta = alpha/theta;\n\n        return boost::math::gamma_p_inv(alpha, q)/beta;\n    }\n}\n\nvoid FdHestonTest::testSquareRootZeroFlowBC() {\n    BOOST_TEST_MESSAGE(\"Testing zero-flow BC for the square root process...\");\n\n    SavedSettings backup;\n\n    const Real kappa = 1.0;\n    const Real theta = 0.4;\n    const Real sigma = 0.8;\n    const Real v_0   = 0.1;\n    const Time t     = 1.0;\n\n    const Real vmin = 0.0005;\n    const Real h    = 0.0001;\n\n    const Real expected[5][5]\n        = {{ 0.000548, -0.000245, -0.005657, -0.001167, -0.000024},\n           {-0.000595, -0.000701, -0.003296, -0.000883, -0.000691},\n           {-0.001277, -0.001320, -0.003128, -0.001399, -0.001318},\n           {-0.001979, -0.002002, -0.003425, -0.002047, -0.002001},\n           {-0.002715, -0.002730, -0.003920, -0.002760, -0.002730} };\n\n    for (Size i=0; i < 5; ++i) {\n        const Real v = vmin + i*0.001;\n        const Real vm2 = v - 2*h;\n        const Real vm1 = v - h;\n        const Real v0  = v;\n        const Real v1  = v + h;\n        const Real v2  = v + 2*h;\n\n        const Real pm2= squareRootGreensFct(v_0, kappa, theta, sigma, t, vm2);\n        const Real pm1= squareRootGreensFct(v_0, kappa, theta, sigma, t, vm1);\n        const Real p0 = squareRootGreensFct(v_0, kappa, theta, sigma, t, v0);\n        const Real p1 = squareRootGreensFct(v_0, kappa, theta, sigma, t, v1);\n        const Real p2 = squareRootGreensFct(v_0, kappa, theta, sigma, t, v2);\n\n        // test derivatives\n        const Real flowSym2Order = sigma*sigma*v0/(4*h)*(p1-pm1)\n                                + (kappa*(v0-theta)+sigma*sigma/2)*p0;\n\n        const Real flowSym4Order\n            = sigma*sigma*v0/(24*h)*(-p2 + 8*p1 - 8*pm1 + pm2)\n              + (kappa*(v0-theta)+sigma*sigma/2)*p0;\n\n        const Real fwd1Order = sigma*sigma*v0/(2*h)*(p1-p0)\n                                + (kappa*(v0-theta)+sigma*sigma/2)*p0;\n\n        const Real fwd2Order = sigma*sigma*v0/(4*h)*(4*p1-3*p0-p2)\n                                + (kappa*(v0-theta)+sigma*sigma/2)*p0;\n\n        const Real fwd3Order\n            = sigma*sigma*v0/(12*h)*(-p2 + 6*p1 - 3*p0 - 2*pm1)\n                                + (kappa*(v0-theta)+sigma*sigma/2)*p0;\n\n        const Real tol = 0.000002;\n        if (   std::fabs(expected[i][0] - flowSym2Order) > tol\n            || std::fabs(expected[i][1] - flowSym4Order) > tol\n            || std::fabs(expected[i][2] - fwd1Order) > tol\n            || std::fabs(expected[i][3] - fwd2Order) > tol\n            || std::fabs(expected[i][4] - fwd3Order) > tol ) {\n            BOOST_ERROR(\"failed to reproduce Zero Flow BC at\"\n                       << \"\\n   v:          \" << v\n                       << \"\\n   tolerance:  \" << tol);\n        }\n    }\n}\n\n\nnamespace {\n    boost::shared_ptr<FdmMesher> createStationaryDistributionMesher(\n        Real kappa, Real theta, Real sigma, Size vGrid) {\n\n        const Real qMin = 0.01;\n        const Real qMax = 0.99;\n        const Real dq = (qMax-qMin)/(vGrid-1);\n\n        std::vector<Real> v(vGrid);\n        for (Size i=0; i < vGrid; ++i) {\n            v[i] = invStationaryDistributionFct(kappa, theta,\n                                                sigma, qMin + i*dq);\n        }\n\n        return boost::shared_ptr<FdmMesher>(\n            new FdmMesherComposite(boost::shared_ptr<Fdm1dMesher>(\n                new Predefined1dMesher(v))));\n    }\n}\n\n\nvoid FdHestonTest::testTransformedZeroFlowBC() {\n    BOOST_TEST_MESSAGE(\"Testing zero-flow BC for transformed \"\n                       \"Fokker-Planck forward equation...\");\n\n    SavedSettings backup;\n\n    const Real kappa = 1.0;\n    const Real theta = 0.4;\n    const Real sigma = 2.0;\n    const Size vGrid = 100;\n\n    const boost::shared_ptr<FdmMesher> mesher\n        = createStationaryDistributionMesher(kappa, theta, sigma, vGrid);\n    const Array v = mesher->locations(0);\n\n    Array p(vGrid);\n    for (Size i=0; i < v.size(); ++i)\n        p[i] =  stationaryProbabilityFct(kappa, theta, sigma, v[i]);\n\n\n    const Real alpha = 1.0 - 2*kappa*theta/(sigma*sigma);\n    const Array q = Pow(v, alpha)*p;\n\n    for (Size i=0; i < vGrid/2; ++i) {\n        const Real hm = v[i+1] - v[i];\n        const Real hp = v[i+2] - v[i+1];\n\n        const Real eta=1.0/(hm*(hm+hp)*hp);\n        const Real a = -eta*(square<Real>()(hm+hp) - hm*hm);\n        const Real b  = eta*square<Real>()(hm+hp);\n        const Real c = -eta*hm*hm;\n\n        const Real df = a*q[i] + b*q[i+1] + c*q[i+2];\n        const Real flow = 0.5*sigma*sigma*v[i]*df + kappa*v[i]*q[i];\n\n        const Real tol = 1e-6;\n        if (std::fabs(flow) > tol) {\n            BOOST_ERROR(\"failed to reproduce Zero Flow BC at\"\n                       << \"\\n v:          \" << v\n                       << \"\\n flow:       \" << flow\n                       << \"\\n tolerance:  \" << tol);\n        }\n    }\n}\n\nnamespace {\n    class q_fct : public std::unary_function<Real, Real> {\n      public:\n        q_fct(const Array& v, const Array& p, const Real alpha)\n        : v_(v), q_(Pow(v, alpha)*p), alpha_(alpha) {\n            spline_ = boost::shared_ptr<CubicInterpolation>(\n                new CubicNaturalSpline(v_.begin(), v_.end(), q_.begin()));\n        }\n\n        Real operator()(Real v) {\n            return (*spline_)(v, true)*std::pow(v, -alpha_);\n        }\n      private:\n\n        const Array v_, q_;\n        const Real alpha_;\n        boost::shared_ptr<CubicInterpolation> spline_;\n    };\n}\n\nvoid FdHestonTest::testSquareRootEvolveWithStationaryDensity() {\n    BOOST_TEST_MESSAGE(\"Testing Fokker-Planck forward equation \"\n                       \"for the square root process with stationary density...\");\n\n    // Documentation for this test case:\n    // http://www.spanderen.de/2013/05/04/fokker-planck-equation-feller-constraint-and-boundary-conditions/\n    SavedSettings backup;\n\n    const Real kappa = 2.5;\n    const Real theta = 0.2;\n    const Size vGrid = 100;\n    const Real eps = 1e-2;\n\n    for (Real sigma = 0.2; sigma < 2.01; sigma+=0.1) {\n        const Real vMin\n            = invStationaryDistributionFct(kappa, theta, sigma, eps);\n        const Real vMax\n            = invStationaryDistributionFct(kappa, theta, sigma, 1-eps);\n\n        const boost::shared_ptr<FdmMesher> mesher(\n            new FdmMesherComposite(boost::shared_ptr<Fdm1dMesher>(\n                    new Uniform1dMesher(vMin, vMax, vGrid))));\n\n        const Array v = mesher->locations(0);\n\n        Array p(vGrid);\n        for (Size i=0; i < v.size(); ++i)\n            p[i] =  stationaryProbabilityFct(kappa, theta, sigma, v[i]);\n\n        const boost::shared_ptr<FdmSquareRootFwdOp> op(\n            new FdmSquareRootFwdOp(mesher, kappa, theta,\n                                   sigma, 0, sigma > 0.75));\n\n        const Array eP = p;\n\n        const Size n = 100;\n        const Time dt = 0.01;\n        DouglasScheme evolver(0.5, op);\n        evolver.setStep(dt);\n\n        for (Size i=1; i <= n; ++i) {\n            evolver.step(p, i*dt);\n        }\n\n        const Real expected = 1-2*eps;\n        const Real alpha = 1-2*kappa*theta/(sigma*sigma);\n        const Real calculated = GaussLobattoIntegral(1000000, 1e-6)(\n                                        q_fct(v,p,alpha), v.front(), v.back());\n\n        const Real tol = 0.005;\n        if (std::fabs(calculated-expected) > tol) {\n            BOOST_ERROR(\"failed to reproduce stationary probability function\"\n                    << \"\\n    calculated: \" << calculated\n                    << \"\\n    expected:   \" << expected\n                    << \"\\n    tolerance:  \" << tol);\n        }\n    }\n}\n\nvoid FdHestonTest::testSquareRootFokkerPlanckFwdEquation() {\n    BOOST_TEST_MESSAGE(\"Testing Fokker-Planck forward equation \"\n                       \"for the square root process with Dirac start...\");\n\n    SavedSettings backup;\n\n    const Real kappa = 1.2;\n    const Real theta = 0.4;\n    const Real sigma = 0.7;\n    const Real v0 = theta;\n    const Real alpha = 1.0 - 2*kappa*theta/(sigma*sigma);\n\n    const Time maturity = 1.0;\n\n    const Size xGrid = 1001;\n    const Size tGrid = 500;\n\n    const Real vol = sigma*std::sqrt(theta/(2*kappa));\n    const Real upperBound = theta+6*vol;\n    const Real lowerBound = std::max(0.0002, theta-6*vol);\n\n    const boost::shared_ptr<FdmMesher> mesher(\n        new FdmMesherComposite(boost::shared_ptr<Fdm1dMesher>(\n                new Uniform1dMesher(lowerBound, upperBound, xGrid))));\n\n    const Array x(mesher->locations(0));\n\n    const boost::shared_ptr<FdmSquareRootFwdOp> op(\n        new FdmSquareRootFwdOp(mesher, kappa, theta, sigma, 0));\n\n    const Time dt = maturity/tGrid;\n    const Size n = 5;\n\n    Array p(xGrid);\n    for (Size i=0; i < p.size(); ++i) {\n        p[i] = squareRootGreensFct(v0, kappa, theta,\n                                   sigma, n*dt, x[i]);\n    }\n    Array q = Pow(x, alpha)*p;\n\n    DouglasScheme evolver(0.5, op);\n    evolver.setStep(dt);\n\n    for (Time t=(n+1)*dt; t <= maturity+20*QL_EPSILON; t+=dt) {\n        evolver.step(p, t);\n        evolver.step(q, t);\n    }\n\n    const Real tol = 0.002;\n\n    Array y(x.size());\n    for (Size i=0; i < x.size(); ++i) {\n        const Real expected = squareRootGreensFct(v0, kappa, theta,\n                                                  sigma, maturity, x[i]);\n\n        const Real calculated = p[i];\n        if (std::fabs(expected - calculated) > tol) {\n            BOOST_FAIL(\"failed to reproduce pdf at\"\n                       << QL_FIXED << std::setprecision(5)\n                       << \"\\n   x:          \" << x[i]\n                       << \"\\n   calculated: \" << calculated\n                       << \"\\n   expected:   \" << expected\n                       << \"\\n   tolerance:  \" << tol);\n        }\n    }\n}\n\n\n\nnamespace {\n    Real fokkerPlanckPrice2D(const Array& p,\n                       const boost::shared_ptr<FdmMesherComposite>& mesher) {\n\n        std::vector<Real> x, y;\n        const boost::shared_ptr<FdmLinearOpLayout> layout = mesher->layout();\n\n        x.reserve(layout->dim()[0]);\n        y.reserve(layout->dim()[1]);\n\n        const FdmLinearOpIterator endIter = layout->end();\n        for (FdmLinearOpIterator iter = layout->begin(); iter != endIter;\n              ++iter) {\n            if (!iter.coordinates()[1]) {\n                x.push_back(mesher->location(iter, 0));\n            }\n            if (!iter.coordinates()[0]) {\n                y.push_back(mesher->location(iter, 1));\n            }\n        }\n\n        Matrix m(y.size(), x.size());\n        std::copy(p.begin(), p.end(), m.begin());\n\n        const Real tolerance = 1e-3;\n        const Size maxEvaluations = 1000;\n\n        return TwoDimensionalIntegral(\n             boost::shared_ptr<Integrator>(\n                 new TrapezoidIntegral<Default>(tolerance, maxEvaluations)),\n             boost::shared_ptr<Integrator>(\n                 new TrapezoidIntegral<Default>(tolerance, maxEvaluations)))(\n             Bilinear().interpolate(x.begin(), x.end(), y.begin(), y.end(), m),\n             std::make_pair(x.front(), y.front()),\n             std::make_pair(x.back(), y.back()));\n    }\n}\n\nvoid FdHestonTest::testHestonFokkerPlanckFwdEquation() {\n    BOOST_TEST_MESSAGE(\"Testing Fokker-Planck forward equation \"\n                       \"for the Heston process...\");\n\n    SavedSettings backup;\n\n    const DayCounter dc = ActualActual();\n    const Date todaysDate = Date(28, Dec, 2012);\n    Settings::instance().evaluationDate() = todaysDate;\n\n    const Date maturityDate = todaysDate + Period(1, Years);\n    const Time maturity = dc.yearFraction(todaysDate, maturityDate);\n\n    const Real s0 = 100;\n    const Rate r = 0.10;\n    const Rate q = 0.05;\n\n    const Real kappa =  1.0;\n    const Real theta =  0.4;\n    const Real rho   = -0.9;\n    const Real sigma =  0.4;\n    const Real v0    =  theta;\n\n    const Handle<Quote> spot(boost::shared_ptr<Quote>(new SimpleQuote(s0)));\n    const Handle<YieldTermStructure> rTS(flatRate(r, dc));\n    const Handle<YieldTermStructure> qTS(flatRate(q, dc));\n\n    boost::shared_ptr<HestonProcess> process(\n        new HestonProcess(rTS, qTS, spot, v0, kappa, theta, sigma, rho));\n\n    const Size xGrid = 101;\n    const Size vGrid = 501;\n    const Size tGrid = 200;\n\n    const Real vol = sigma*std::sqrt(theta/(2*kappa));\n    const Real upperBound = std::max(v0+6*vol, theta+6*vol);\n    const Real lowerBound = std::max(0.0025, std::min(v0-6*vol, theta-6*vol));\n\n    const boost::shared_ptr<Fdm1dMesher> varianceMesher(\n        new Uniform1dMesher(lowerBound, upperBound, vGrid));\n    const boost::shared_ptr<Fdm1dMesher> equityMesher(\n        new FdmBlackScholesMesher(\n            xGrid,\n            FdmBlackScholesMesher::processHelper(\n              process->s0(), process->dividendYield(),\n              process->riskFreeRate(), std::sqrt(v0)),\n              maturity, s0));\n\n    const boost::shared_ptr<FdmMesherComposite>\n        mesher(new FdmMesherComposite(equityMesher, varianceMesher));\n\n    Array p(mesher->layout()->size(), 0.0);\n\n    const Size xIdx = xGrid/2;\n    const Size vIdx\n        = std::distance(varianceMesher->locations().begin(),\n                        std::lower_bound(varianceMesher->locations().begin(),\n                                         varianceMesher->locations().end(),\n                                         v0));\n    const Real dx = 0.5*(equityMesher->location(xIdx+1)\n                         - equityMesher->location(xIdx-1));\n    const Real dy = 0.5*(varianceMesher->location(vIdx+1)\n                         - varianceMesher->location(vIdx-1));\n\n    p[xIdx + vIdx*xGrid] = 1.0/(dx*dy);\n    Array pd(p.size());\n\n    const boost::shared_ptr<FdmLinearOpComposite> hestonFwdOp(\n        new FdmHestonFwdOp(mesher, process));\n\n    HundsdorferScheme evolver(FdmSchemeDesc::Hundsdorfer().theta,\n                              FdmSchemeDesc::Hundsdorfer().mu,\n                              hestonFwdOp);\n\n    const Time dt = maturity/tGrid;\n    evolver.setStep(dt);\n\n    for (Time t=dt; t <= maturity+20*QL_EPSILON; t+=dt) {\n        evolver.step(p, t);\n    }\n\n    const boost::shared_ptr<PricingEngine> engine(\n        new AnalyticHestonEngine(boost::shared_ptr<HestonModel>(\n            new HestonModel(boost::shared_ptr<HestonProcess>(\n                new HestonProcess(rTS, qTS, spot,\n                                  varianceMesher->location(vIdx),\n                                  kappa, theta, sigma, rho))))));\n\n    const boost::shared_ptr<Exercise> exercise(\n        new EuropeanExercise(maturityDate));\n\n    const Real strikes[] = { 50, 80, 100, 120, 150, 200 };\n\n    for (Size i=0; i < LENGTH(strikes); ++i) {\n        const Real strike = strikes[i];\n        const boost::shared_ptr<StrikedTypePayoff> payoff(\n            new PlainVanillaPayoff(Option::Call, strike));\n\n        const FdmLinearOpIterator endIter = mesher->layout()->end();\n        for (FdmLinearOpIterator iter = mesher->layout()->begin();\n            iter != endIter; ++iter) {\n            const Size idx = iter.index();\n            const Real s = std::exp(mesher->location(iter, 0));\n\n            pd[idx] = payoff->operator()(s)*p[idx];\n        }\n\n        const Real calculated\n            = fokkerPlanckPrice2D(pd, mesher)*rTS->discount(maturityDate);\n\n        VanillaOption option(payoff, exercise);\n        option.setPricingEngine(engine);\n        const Real expected = option.NPV();\n\n        const Real tol = 0.1;\n        if (std::fabs(expected - calculated ) > tol) {\n            BOOST_FAIL(\"failed to reproduce Heston prices at\"\n                       << \"\\n   strike      \" << strike\n                       << QL_FIXED << std::setprecision(5)\n                       << \"\\n   calculated: \" << calculated\n                       << \"\\n   expected:   \" << expected\n                       << \"\\n   tolerance:  \" << tol);\n        }\n    }\n}\n\ntest_suite* FdHestonTest::suite() {\n    test_suite* suite = BOOST_TEST_SUITE(\"Finite Difference Heston tests\");\n    suite->add(QUANTLIB_TEST_CASE(&FdHestonTest::testFdmHestonBarrier));\n    suite->add(QUANTLIB_TEST_CASE(\n                         &FdHestonTest::testFdmHestonBarrierVsBlackScholes));\n    suite->add(QUANTLIB_TEST_CASE(&FdHestonTest::testFdmHestonAmerican));\n    suite->add(QUANTLIB_TEST_CASE(&FdHestonTest::testFdmHestonIkonenToivanen));\n    suite->add(QUANTLIB_TEST_CASE(&FdHestonTest::testFdmHestonBlackScholes));\n    suite->add(QUANTLIB_TEST_CASE(\n                    &FdHestonTest::testFdmHestonEuropeanWithDividends));\n\n    suite->add(QUANTLIB_TEST_CASE(&FdHestonTest::testFdmHestonConvergence));\n    return suite;\n}\n\ntest_suite* FdHestonTest::experimental() {\n    test_suite* suite = BOOST_TEST_SUITE(\"Finite Difference Heston tests\");\n    suite->add(QUANTLIB_TEST_CASE(\n        &FdHestonTest::testBlackScholesFokkerPlanckFwdEquation));\n    suite->add(QUANTLIB_TEST_CASE(&FdHestonTest::testSquareRootZeroFlowBC));\n    suite->add(QUANTLIB_TEST_CASE(&FdHestonTest::testTransformedZeroFlowBC));\n    suite->add(QUANTLIB_TEST_CASE(\n          &FdHestonTest::testSquareRootEvolveWithStationaryDensity));\n    suite->add(QUANTLIB_TEST_CASE(\n        &FdHestonTest::testSquareRootFokkerPlanckFwdEquation));\n    suite->add(QUANTLIB_TEST_CASE(\n        &FdHestonTest::testHestonFokkerPlanckFwdEquation));\n\n    return suite;\n}\n", "meta": {"hexsha": "3a1e1ace6bc056dc614c9c6f66d0229466b9e2d0", "size": 55502, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QuantLib/test-suite/fdheston.cpp", "max_stars_repo_name": "frannuca/quantlib", "max_stars_repo_head_hexsha": "63e66f5f767397e5b7c79fa78eaed4e3e0a6b7c6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "QuantLib/test-suite/fdheston.cpp", "max_issues_repo_name": "frannuca/quantlib", "max_issues_repo_head_hexsha": "63e66f5f767397e5b7c79fa78eaed4e3e0a6b7c6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "QuantLib/test-suite/fdheston.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": 42.0151400454, "max_line_length": 107, "alphanum_fraction": 0.5588987784, "num_tokens": 16624, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.757794360334681, "lm_q2_score": 0.6334102775181399, "lm_q1q2_score": 0.4799947360812716}}
{"text": "// Copyright (c) 2020 by Ignacio Alzugaray <alzugaray dot ign at gmail dot com>\n// ETH Zurich, Vision for Robotics Lab.\n\n#pragma once\n\n#include <Eigen/Core>\n#include <array>\n#include <iterator>\n\n#include <haste/core/hypothesis.hpp>\n\nnamespace haste {\n\ntemplate<typename T>\nstruct IncrementalHypothesesGenerator_TXYR_4neigh_2rot {\n  using Scalar = T;\n  using Hypothesis = HypothesisTXYR<Scalar>;\n  using IncrementalHypothesis = typename Hypothesis::Incremental;\n\n  // \u8fd9\u91cc\u5bf9\u5e94\u7684\u5e94\u8be5\u662f\u516c\u5f0f2\u4e0b\u8fb9\u90a3\u7247,\u4ee3\u7801\u4e2d\u53ea\u67097\u4e2a,\u8bba\u6587\u4e2d\u662f11\u4e2a,\n  static constexpr Scalar deltaX = 1.0f;\n  static constexpr Scalar deltaY = 1.0f;\n  static constexpr Scalar deltaTheta = 4.0 * M_PI / 180.0;\n\n  static constexpr std::array<IncrementalHypothesis,7>  kIncrementalHypotheses{\n      IncrementalHypothesis{+0.0, +0.0, +0.0},       IncrementalHypothesis{+deltaX, +0.0, +0.0},\n      IncrementalHypothesis{-deltaX, +0.0, +0.0},    IncrementalHypothesis{+0.0, +deltaY, +0.0},\n      IncrementalHypothesis{+0.0, -deltaY, +0.0},    IncrementalHypothesis{+0.0, +0.0, +deltaTheta},\n      IncrementalHypothesis{+0.0, +0.0, -deltaTheta}};\n  static constexpr size_t kNullHypothesisIdx = 0;\n};\n\ntemplate<typename T>\nstruct IncrementalHypothesesGenerator_TXYR_8neigh_2rot {\n  using Scalar = T;\n  using Hypothesis = HypothesisTXYR<Scalar>;\n  using IncrementalHypothesis = typename Hypothesis::Incremental;\n\n  static constexpr Scalar deltaX = 1.0f;\n  static constexpr Scalar deltaY = 1.0f;\n  static constexpr Scalar deltaTheta = 4.0 * M_PI / 180.0;\n\n  // \u8fd9\u4e2a\u624d\u662f\u516b\u90bb\u57df\n  static constexpr std::array<IncrementalHypothesis,11> kIncrementalHypotheses{\n      IncrementalHypothesis{+0.0, +0.0, +0.0},       IncrementalHypothesis{+deltaX, +0.0, +0.0},\n      IncrementalHypothesis{-deltaX, +0.0, +0.0},    IncrementalHypothesis{+0.0, +deltaY, +0.0},\n      IncrementalHypothesis{+0.0, -deltaY, +0.0},    IncrementalHypothesis{+deltaX, +deltaY, +0.0},\n      IncrementalHypothesis{-deltaX, +deltaY, +0.0}, IncrementalHypothesis{-deltaX, -deltaY, +0.0},\n      IncrementalHypothesis{+deltaX, -deltaY, +0.0}, IncrementalHypothesis{+0.0, +0.0, +deltaTheta},\n      IncrementalHypothesis{+0.0, +0.0, -deltaTheta}};\n  static constexpr size_t kNullHypothesisIdx = 0;\n};\n\n// \u8fd9\u91cc\u7684type\u5c31\u662f\u4e0a\u8fb9\u516b\u90bb\u57df\u90a3\u4e2a\ntemplate<typename IncrementalHypothesesGeneratorType>\nstruct CenteredHypothesesGenerator {\n  using IncrementalHypothesesGenerator = IncrementalHypothesesGeneratorType;\n  using Scalar = typename IncrementalHypothesesGenerator::Scalar;\n  using Hypothesis = typename IncrementalHypothesesGenerator::Hypothesis;\n  static constexpr auto kNullHypothesisIdx = IncrementalHypothesesGenerator::kNullHypothesisIdx;\n  static constexpr auto kIncrementalHypotheses = IncrementalHypothesesGenerator::kIncrementalHypotheses;\n\n  static constexpr auto kNumHypotheses = kIncrementalHypotheses.size();\n  // \u8fd9\u4e2a\u5c31\u662f\u4e00\u4e2a\u516b\u90bb\u57df\u7684TXYR\u6570\u7ec4\n  using Hypotheses = std::array<Hypothesis, kNumHypotheses>;\n\n  static constexpr Hypotheses GenerateCenteredHypotheses(const Hypothesis &null_hypothesis) {\n    Hypotheses hypotheses;\n    // \u4e00\u4e2a\u5047\u8bbe\u53d8\u6210\u4e8611\u4e2a\u5047\u8bbe\n    for (size_t i = 0; i < kNumHypotheses; ++i) {// TODO null hypothesis could be avoided\n    // \u8fd9\u4e2a+\u88ab\u91cd\u8f7d\u4e86\uff0c\u8fd9\u4e00\u5c42\u5957\u4e00\u5c42\u7684\uff0c\u771f\u8d39\u52b2\n      hypotheses[i] = null_hypothesis + kIncrementalHypotheses[i];\n    }\n    return hypotheses;\n  }\n};\n\n}// namespace haste\n", "meta": {"hexsha": "02d27d195311d4c8d3e8a3490337d6028b428714", "size": 3244, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/haste/core/hypotheses_manager.hpp", "max_stars_repo_name": "Wangxy2180/haste", "max_stars_repo_head_hexsha": "ac0db5a8c059ec66d02fc46048acfa31b83e7038", "max_stars_repo_licenses": ["MIT"], "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/haste/core/hypotheses_manager.hpp", "max_issues_repo_name": "Wangxy2180/haste", "max_issues_repo_head_hexsha": "ac0db5a8c059ec66d02fc46048acfa31b83e7038", "max_issues_repo_licenses": ["MIT"], "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/haste/core/hypotheses_manager.hpp", "max_forks_repo_name": "Wangxy2180/haste", "max_forks_repo_head_hexsha": "ac0db5a8c059ec66d02fc46048acfa31b83e7038", "max_forks_repo_licenses": ["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.0632911392, "max_line_length": 104, "alphanum_fraction": 0.7450678175, "num_tokens": 1094, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.4799947325226532}}
{"text": "#include \"ros/ros.h\"\n#include \"std_msgs/Float64.h\"\n#include <gazebo_msgs/ApplyJointEffort.h>\n#include <iostream>\n#include <Eigen/Dense>\n\nEigen::MatrixXd m(3,3);\nEigen::Vector3d r;\nEigen::Vector3d v;\n\nros::Subscriber yaw_sub;\nros::Subscriber pitch_sub;\nros::Subscriber roll_sub;\ndouble yaw_control_effort, pitch_control_effort, roll_control_effort;\n\nros::Duration duration(0.005);\nros::ServiceClient client;\n\nvoid matrixInit(void)\n{\n\n  m << -2,-1.732,1,\n-2,0,-2,\n-2,1.732,1;\n}\n\nvoid yawCallback(const std_msgs::Float64& control_effort_input)\n{\t\n     yaw_control_effort = control_effort_input.data;\n  \n\n}\n\nvoid pitchCallback(const std_msgs::Float64& control_effort_input)\n{\n     pitch_control_effort = control_effort_input.data;\n\n}\n\nvoid rollCallback(const std_msgs::Float64& control_effort_input)\n{\n     roll_control_effort = control_effort_input.data;\n\n}\n\nvoid controlCallback(const ros::TimerEvent& event)\n{\n     v(0) = yaw_control_effort;\n     v(1) = pitch_control_effort;\n     v(2) = roll_control_effort;\n     r = m*v;\n\n  gazebo_msgs::ApplyJointEffort joint0, joint1, joint2;\n  joint0.request.joint_name = \"Ballbot::body_link_JOINT_0\";\n  joint0.request.effort = r(0);\n  joint0.request.duration= duration;\n  joint1.request.joint_name = \"Ballbot::body_link_JOINT_1\";\n  joint1.request.effort = r(1);\n  joint1.request.duration= duration;\n  joint2.request.joint_name = \"Ballbot::body_link_JOINT_2\";\n  joint2.request.effort = r(2);\n  joint2.request.duration= duration;\n  if ((client.call(joint0)) && (client.call(joint1)) && (client.call(joint2)))\n  {\n    ROS_INFO(\"published rpy control_effort: roll=%f pitch=%f yaw=%f\", r(0), r(1), r(2));\n    ROS_INFO(\"published rpy angle: roll=%f pitch=%f yaw=%f\", v(0), v(0), v(0));\n  }\n\n}\n\nint main(int argc, char **argv)\n{\n\n  ros::init(argc, argv, \"apply_joint_effort_client\");\n  matrixInit();\n  ros::NodeHandle n;\n  ros::Timer timer1 = n.createTimer(ros::Duration(0.01), controlCallback);\n  client = n.serviceClient<gazebo_msgs::ApplyJointEffort>(\"/gazebo/apply_joint_effort\");\n  yaw_sub = n.subscribe(\"/ballbot_yaw/control_effort\", 1000, yawCallback);\n  pitch_sub = n.subscribe(\"/ballbot_pitch/control_effort\", 1000, pitchCallback);\n  roll_sub = n.subscribe(\"/ballbot_roll/control_effort\", 1000, rollCallback);\n  //ros::Rate loop_rate(10);\n\n  /**\n   * A count of how many messages we have sent. This is used to create\n   * a unique string for each message.\n   */\n\n  ros::spin();\n  \n  return 0;\n }\n\n", "meta": {"hexsha": "0da6698e66b95d6384cf2667215cea7b87593da2", "size": 2437, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ballbot_plugin/src/apply_joint_effort_client.cpp", "max_stars_repo_name": "63445538/Ballbot_gazebo", "max_stars_repo_head_hexsha": "2526b25ca8ddda23fa6ef60e45d1152eb4c334c5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-08-17T04:42:25.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-01T01:41:43.000Z", "max_issues_repo_path": "ballbot_plugin/src/apply_joint_effort_client.cpp", "max_issues_repo_name": "63445538/Ballbot_gazebo", "max_issues_repo_head_hexsha": "2526b25ca8ddda23fa6ef60e45d1152eb4c334c5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ballbot_plugin/src/apply_joint_effort_client.cpp", "max_forks_repo_name": "63445538/Ballbot_gazebo", "max_forks_repo_head_hexsha": "2526b25ca8ddda23fa6ef60e45d1152eb4c334c5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-07-30T03:35:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-30T03:35:40.000Z", "avg_line_length": 25.9255319149, "max_line_length": 88, "alphanum_fraction": 0.7168649979, "num_tokens": 714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234877, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.47998126277543474}}
{"text": "#pragma once\n\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n\n#include \"spectral/basis/spectral_basis_factory_ks.hpp\"\n\nnamespace boltzmann {\n\nclass CollisionTensorGalerkinBase\n{\n protected:\n  typedef Eigen::SparseMatrix<double> sparse_matrix_t;\n  typedef std::shared_ptr<sparse_matrix_t> ptr_t;\n  typedef Eigen::SparseLU<sparse_matrix_t> lu_t;\n  typedef typename SpectralBasisFactoryKS::basis_type basis_t;\n  typedef Eigen::MatrixXd matrix_t;\n  typedef Eigen::Matrix4d m4_t;\n  typedef Eigen::DiagonalMatrix<double, -1> diag_t;\n  typedef Eigen::VectorXd vec_t;\n\n public:\n  CollisionTensorGalerkinBase(const basis_t& basis);\n\n  int get_N() const { return N_; }\n  int get_K() const { return K_; }\n  const basis_t& get_basis() const { return basis_; }\n\n  void project(double* out, const double* in) const;\n\n  template <typename DERIVED1, typename DERIVED2>\n  void project(Eigen::DenseBase<DERIVED1>& out, const Eigen::DenseBase<DERIVED2>& in) const;\n\n  template <typename DERIVED1, typename DERIVED2>\n  void project_lambda(Eigen::DenseBase<DERIVED1>& out,\n                      const Eigen::DenseBase<DERIVED2>& lambda) const;\n\n  template <typename DERIVED1, typename DERIVED2>\n  void get_lambda(Eigen::DenseBase<DERIVED1>& lambda, const Eigen::DenseBase<DERIVED2>& in) const;\n\n protected:\n  const basis_t basis_;\n  /// basis size\n  const int N_;\n  /// max polynomial degree\n  const int K_;\n  /// buffer\n  mutable Eigen::VectorXd buf_;\n  /// tensor entries\n  matrix_t Ht_;\n  m4_t HtHinv_;\n  diag_t Sinv_;\n\n public:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n};\n\ntemplate <typename DERIVED1, typename DERIVED2>\nvoid\nCollisionTensorGalerkinBase::project(Eigen::DenseBase<DERIVED1>& out,\n                                     const Eigen::DenseBase<DERIVED2>& in) const\n{\n  BOOST_ASSERT(out.cols() == in.cols());\n  BOOST_ASSERT(out.rows() == in.rows());\n\n  Eigen::MatrixXd lambda = HtHinv_ * Ht_ * (out.derived() - in.derived()).matrix();\n  out.derived().matrix() -= Sinv_ * Ht_.transpose() * lambda;\n}\n\n\ntemplate <typename DERIVED1, typename DERIVED2>\nvoid\nCollisionTensorGalerkinBase::project_lambda(Eigen::DenseBase<DERIVED1>& out,\n                                            const Eigen::DenseBase<DERIVED2>& lambda) const\n{\n  out.derived().matrix() -= Sinv_ * Ht_.transpose() * lambda.derived().matrix();\n}\n\n\ntemplate <typename DERIVED1, typename DERIVED2>\nvoid\nCollisionTensorGalerkinBase::get_lambda(Eigen::DenseBase<DERIVED1>& lambda,\n                                        const Eigen::DenseBase<DERIVED2>& in) const\n{\n  lambda.derived().matrix() = HtHinv_ * Ht_ * in.derived().matrix();\n}\n\n\n}  // namespace boltzmann\n", "meta": {"hexsha": "2ca77579863afbd2bbcf5eadb2c57c279644672f", "size": 2610, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/collision_tensor/collision_tensor_galerkin_base.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_galerkin_base.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_galerkin_base.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": 29.0, "max_line_length": 98, "alphanum_fraction": 0.7022988506, "num_tokens": 705, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.831143031127974, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4799812482828919}}
{"text": "#include <iostream>\n#include <complex>\n#include <random>\n#include <cassert>\n#include \"NtruGsw.hpp\"\n#include <NTL/ZZX.h>\n#include <NTL/ZZ_pXFactoring.h>\n#include <NTL/ZZ_pEX.h>\n#include <NTL/ZZ_p.h>\n\nNTL::ZZX ntru::keyGen()\n{\n    assert(ring!=NULL);\n    assert(Inequality!=NULL);\n    NTL::ZZX f,tmpres,g;\n    while(1)\n    {\n        int random=std::abs(GetRandom());\n        unsigned int idx=random%(n);\n        NTL::ZZ num= ring[idx];\n        if(num*2>q||num*2<0)continue;\n        SetCoeff(f, idx, num*2);\n        SetCoeff(f, 0, 1);\n        GCD(tmpres, ring, Inequality);\n        if(tmpres[0]==1)break;\n    }\n    //\u968f\u673a\u9009\u53d6 g<-X\n    int ng=std::abs(GetRandom());\n    ng%=n;\n    /*\n     ********************************\n     */\n    Genf=f;\n    //\u6b64\u5904\u5f97\u5230\u4e86\u4e00\u4e2af\n    NTL::ZZ gtmp= ring[ng];\n    SetCoeff(g,ng,gtmp);\n    //\u4fdd\u5b58\u4e00\u4efdf\n    NTL::ZZX prevf(f);\n    prevf=ReversePoly(f);\n    \n    prevf=2*prevf*g;\n    ZZXmod(prevf);\n    \n    \n    //\u5df2\u7ecf\u5b58\u5728\u4e86 f g\n    //\u5bf9f\u53d6mod\n    \n    return prevf;\n}\n\n\n NTL::ZZX ntru::ReversePoly( NTL::ZZX &f)\n{\n    NTL::ZZ r(1);//\u6bd4\u8f83\u7ed3\u679c\n    NTL::ZZX eq1,eq2;\n    \n    \n    int random=std::abs(GetRandom());\n    unsigned int idx=random%(n);\n    NTL::ZZ num= ring[idx];\n    SetCoeff(eq1, idx, num);\n    \n    \n    int random1=std::abs(GetRandom());\n    unsigned int idx1=random1%(n);\n    NTL::ZZ num1= ring[idx1];\n    SetCoeff(eq2, idx1, num1);\n    XGCD(r, eq2, f, eq1, Inequality);\n    return eq2;\n\n}\nvoid ntru::RandomRing()\n{\n    // 0\u6b21\u5230 n-1\u7684\u4e00\u4e2a\u591a\u9879\u5f0f\u73af\n    for(unsigned int i=0;i<n;++i)\n    {\n        \n        int ranum=GetRandom();\n        int pow=mod(ranum);\n        if(!pow)pow+=1;\n        SetCoeff(ring, i, pow);\n        \n    }\n}\n\n", "meta": {"hexsha": "e56e19ee47ba669476bdfda150e04930db607d04", "size": 1634, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "NtruGsw.cpp", "max_stars_repo_name": "fushenshen/ENC-AND-DEC", "max_stars_repo_head_hexsha": "c1d3c3c4cc09fd3951fd27ac62a3de202f2b37f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-10-10T03:09:12.000Z", "max_stars_repo_stars_event_max_datetime": "2016-10-10T03:09:12.000Z", "max_issues_repo_path": "NtruGsw.cpp", "max_issues_repo_name": "fushenshen/ENC-AND-DEC", "max_issues_repo_head_hexsha": "c1d3c3c4cc09fd3951fd27ac62a3de202f2b37f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NtruGsw.cpp", "max_forks_repo_name": "fushenshen/ENC-AND-DEC", "max_forks_repo_head_hexsha": "c1d3c3c4cc09fd3951fd27ac62a3de202f2b37f7", "max_forks_repo_licenses": ["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.0, "max_line_length": 41, "alphanum_fraction": 0.5263157895, "num_tokens": 566, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.47996546414117414}}
{"text": "#include <Eigen/Dense>\n#include <math.h>;\n\nusing namespace Eigen;\n\nMatrixXd prEq(MatrixXd xk_s, Vector2d uk)\n{\n\tint n = size(xk_s);\n\tdouble dt = 0.1;\n\t\n\tVector3d in(uk(0,0), 0, uk(1,0));\n\tMatrix3d rotMat;\n\tMatrixXd xk(3,7);\n\t\n\tfor(int i = 0; i < 7; i++)\n\t{\n\t\trotMat << cos(xk_s(2,i)), sin(xk_s(2,i)), 0,\n\t\t          sin(xk_s(2,i)), (-cos(xk_s(2,i))), 0,\n\t\t          0, 0, 1;\n\t\t          \n\t\txk.col(i) = rotMat * in * dt;\n\t}\n\t\n\treturn xk;\n}\n", "meta": {"hexsha": "91ab8ee115df1c23e57f97c23cc5818667307520", "size": 439, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pioneer/artoolkit_localization/ukf_figama/prEq.cpp", "max_stars_repo_name": "lara-unb/amora", "max_stars_repo_head_hexsha": "05ce66f3a9ad52db35aad06d6315c5fa824effd0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2015-03-02T05:20:32.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-17T12:41:27.000Z", "max_issues_repo_path": "pioneer/artoolkit_localization/ukf_figama/prEq.cpp", "max_issues_repo_name": "lara-unb/amora", "max_issues_repo_head_hexsha": "05ce66f3a9ad52db35aad06d6315c5fa824effd0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pioneer/artoolkit_localization/ukf_figama/prEq.cpp", "max_forks_repo_name": "lara-unb/amora", "max_forks_repo_head_hexsha": "05ce66f3a9ad52db35aad06d6315c5fa824effd0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2016-06-10T14:05:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-30T07:59:15.000Z", "avg_line_length": 16.8846153846, "max_line_length": 49, "alphanum_fraction": 0.5261958998, "num_tokens": 178, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8840392756357326, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.4799124636250571}}
{"text": "// base_trajectory.cpp\n// Generates a spline-based path connecting input waypoints\n// Implements an algorithm similar to that found in\n// http://www2.informatik.uni-freiburg.de/~lau/students/Sprunk2008.pdf\n// http://www2.informatik.uni-freiburg.de/~lau/paper/lau09iros.pdf\n// http://ais.informatik.uni-freiburg.de/teaching/ws09/robotics2/projects/mr2-p6-paper.pdf\n//\n#include <time.h>\n// Let's break C++!\n// Need to access a private variable from quintic_spline_segment\n// by using a derived class. What could possibly go wrong?\n#define private protected\n#include <trajectory_interface/quintic_spline_segment.h>\n#undef private\n#include <joint_trajectory_controller/init_joint_trajectory.h>\n#include <joint_trajectory_controller/joint_trajectory_segment.h>\n#include <trajectory_msgs/JointTrajectory.h>\n#include <boost/assign.hpp>\n#include <base_trajectory/GenerateSpline.h>\n#include <tf2/LinearMath/Quaternion.h>\n\n#include <angles/angles.h>\n#include <ddynamic_reconfigure/ddynamic_reconfigure.h>\n\n// Various tuning paramters - will be read as params\n// and exposed as dynamic reconfigure options\n//\n// Used for determining arclength vs. time function.  This is the\n// maximum allowed error reported from the simpson's rule approximation\n// of the segment. Segments with errors greater than this are subdivided\n// and each subsegment's length is evaluated separetely, leading to a\n// more accurate approximation\ndouble segLengthEpsilon;\n\n// Used to generate equally-spaced points along the entire\n// arclength of the x-y spline.  Points are spaced\n// distBetweenArcLengths apart, +/- distBetweenArcLengthEpsilon\n// midTimeInflation is used to bias the binary search value - since\n// the search is for monotonically increasing arglengths, the code assumes\n// that the \"mid\"point of the next search should be the location of the\n// last point found plus the previous distance between points.  The \"mid\"point\n// is moved a bit futher out to account for cases where the curvature changes\n//  - it is more efficent to be a little bit beyond the expected value rather than\n//  closer to it.  midTimeInflation is the multipler for that distance.\ndouble distBetweenArcLengths; // 3 cm\ndouble distBetweenArcLengthEpsilon; // 2.5 mm\ndouble midTimeInflation;\n\ndouble pathDistBetweenArcLengths; // 30 cm\ndouble pathDistBetweenArcLengthsEpsilon; // 1 cm\n\n// RPROP optimization parameters.  The code skips to the next optimization\n// variable if the deltaCost for a step is less than deltaCost.  This value is\n// gradually decreased as the result is optimized. This holds the initial and\n// minimum value of deltaCost\ndouble initialDeltaCostEpsilon;\ndouble minDeltaCostEpsilon;\n\n// Initial change added to optimization parameter in the RPROP loop\ndouble initialDParam;\n\n// Robot limits for evaluating path cost\ndouble pathLimitDistance;\ndouble maxVel;\ndouble maxLinearAcc;\ndouble wheelRadius;\ndouble maxCentAcc;\n\n// Simple class to turn debugging output on and off\nclass MessageFilter : public ros::console::FilterBase\n{\n\tpublic:\n\t\tMessageFilter(bool enabled)\n\t\t{\n\t\t\tenabled_ = enabled;\n\t\t}\n\t\tvoid enable(void)\n\t\t{\n\t\t\tenabled_ = true;\n\t\t}\n\t\tvoid disable(void)\n\t\t{\n\t\t\tenabled_ = false;\n\t\t}\n\t\tbool isEnabled(void) override\n\t\t{\n\t\t\treturn enabled_;\n\t\t}\n\t\tbool isEnabled(ros::console::FilterParams &) override\n\t\t{\n\t\t\treturn isEnabled();\n\t\t}\n\tprivate:\n\t\tbool enabled_;\n};\n\nMessageFilter messageFilter(true);\n\n\n// Some template / polymorphism magic to add a getCoefs()\n// method to the spline type used by the rest of the code\nnamespace trajectory_interface\n{\ntemplate<class ScalarType>\nclass MyQuinticSplineSegment: public QuinticSplineSegment<ScalarType>\n{\n\tpublic:\n\t\tstd::vector<typename QuinticSplineSegment<ScalarType>::SplineCoefficients> getCoefs(void) const\n\t\t{\n\t\t\treturn this->coefs_;\n\t\t}\n};\n}\n/** Coefficients represent a quintic polynomial like so:\n  *\n  * <tt> coefs_[0] + coefs_[1]*x + coefs_[2]*x^2 + coefs_[3]*x^3 + coefs_[4]*x^4 + coefs_[5]*x^5 </tt>\n  */\ntypedef std::vector<std::array<double, 6>> SplineCoefs;\n\n// Define typedefs - we're generating Quinitc (5-th order polynomial) splines\n// which have doubles as their datatype\ntypedef joint_trajectory_controller::JointTrajectorySegment<trajectory_interface::MyQuinticSplineSegment<double>> Segment;\n\n// Each TrajectoryPerJoint is a vector of segments, each a spline which makes up\n// the total path for that dimension (x, y, orientation)\ntypedef std::vector<Segment> TrajectoryPerJoint;\n\n// A vector of those is created to hold x, y and orientation in one struct.\ntypedef std::vector<TrajectoryPerJoint> Trajectory;\n\ntypedef trajectory_msgs::JointTrajectory::ConstPtr JointTrajectoryConstPtr;\n\nros::Duration period;\n\n// For printing out matlab code for testing\nvoid printCoefs(std::stringstream &s, const std::string &name, const std::vector<base_trajectory::Coefs> &coefs)\n{\n\tfor (size_t i = 0; i < coefs.size(); i++)\n\t{\n\t\ts << \"p\" << name << i << \" = [\";\n\t\tfor (size_t j = 0; j < coefs[i].spline.size(); j++)\n\t\t{\n\t\t\ts << coefs[i].spline[j];\n\t\t\tif (j < coefs[i].spline.size() - 1)\n\t\t\t\ts << \", \";\n\t\t}\n\t\ts << \"];\" << std::endl;\n\t}\n}\n\n// For printing out matlab code for testing\nvoid printPolyval(std::stringstream &s, const std::string &name, size_t size, const std::vector<double> &end_points)\n{\n\ts << \"p\" << name << \"_y = [\";\n\tfor (size_t i = 0; i < size; i++)\n\t{\n\t\tdouble x_offset;\n\t\tif (i == 0)\n\t\t{\n\t\t\tx_offset = 0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tx_offset = end_points[i - 1];\n\t\t}\n\t\ts << \"polyval(p\" << name << i << \", x\" << i << \" - \" << x_offset << \")\";\n\t\tif (i < size - 1)\n\t\t\ts << \", \";\n\t}\n\ts << \"];\" << std::endl;\n}\n\n// Generate matlab / octave code for displaying generated splines\nvoid writeMatlabCode(const base_trajectory::GenerateSpline::Response &msg)\n{\n\tstd::stringstream s;\n\ts << std::endl;\n\tfor (size_t i = 0; i < msg.end_points.size(); i++)\n\t{\n\t\tdouble range;\n\t\tdouble prev_x;\n\t\tif (i == 0)\n\t\t{\n\t\t\trange = msg.end_points[0];\n\t\t\tprev_x = 0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\trange = msg.end_points[i] - msg.end_points[i-1];\n\t\t\tprev_x = msg.end_points[i-1];\n\t\t}\n\t\ts << \"x\" << i << \" = \" << prev_x << \":\" << range / 100.\n\t\t  << \":\" << msg.end_points[i] << \";\" << std::endl;\n\t}\n\ts << \"x = [\";\n\tfor (size_t i = 0; i < msg.end_points.size(); i++)\n\t{\n\t\ts << \"x\" << i;\n\t\tif (i < msg.end_points.size() - 1)\n\t\t\ts << \", \";\n\t}\n\ts << \"];\" << std::endl;\n\ts << std::endl;\n\tprintCoefs(s, \"x\", msg.x_coefs);\n\tprintCoefs(s, \"y\", msg.y_coefs);\n\tprintCoefs(s, \"orient\", msg.orient_coefs);\n\tfor (size_t i = 0; i < msg.x_coefs.size(); i++)\n\t{\n\t\ts << \"pdx\" << i << \" = polyder(px\" << i << \");\" << std::endl;\n\t\ts << \"pddx\" << i << \" = polyder(pdx\" << i << \");\" << std::endl;\n\t\ts << \"pdddx\" << i << \" = polyder(pddx\" << i << \");\" << std::endl;\n\t\ts << \"pdy\" << i << \" = polyder(py\" << i << \");\" << std::endl;\n\t\ts << \"pddy\" << i << \" = polyder(pdy\" << i << \");\" << std::endl;\n\t\ts << \"pdddy\" << i << \" = polyder(pddy\" << i << \");\" << std::endl;\n\t\ts << \"pdorient\" << i << \" = polyder(porient\" << i << \");\" << std::endl;\n\t\ts << \"pddorient\" << i << \" = polyder(pdorient\" << i << \");\" << std::endl;\n\t\ts << \"pdddorient\" << i << \" = polyder(pddorient\" << i << \");\" << std::endl;\n\t}\n\tprintPolyval(s, \"x\", msg.x_coefs.size(), msg.end_points);\n\tprintPolyval(s, \"dx\", msg.x_coefs.size(), msg.end_points);\n\tprintPolyval(s, \"ddx\", msg.x_coefs.size(), msg.end_points);\n\tprintPolyval(s, \"dddx\", msg.x_coefs.size(), msg.end_points);\n\tprintPolyval(s, \"y\", msg.y_coefs.size(), msg.end_points);\n\tprintPolyval(s, \"dy\", msg.y_coefs.size(), msg.end_points);\n\tprintPolyval(s, \"ddy\", msg.y_coefs.size(), msg.end_points);\n\tprintPolyval(s, \"dddy\", msg.y_coefs.size(), msg.end_points);\n\tprintPolyval(s, \"orient\", msg.orient_coefs.size(), msg.end_points);\n\tprintPolyval(s, \"dorient\", msg.orient_coefs.size(), msg.end_points);\n\tprintPolyval(s, \"ddorient\", msg.orient_coefs.size(), msg.end_points);\n\tprintPolyval(s, \"dddorient\", msg.orient_coefs.size(), msg.end_points);\n\ts << \"subplot(1,1,1)\" << std::endl;\n\ts << \"subplot(3,2,1)\" << std::endl;\n\ts << \"plot(px_y, py_y)\" << std::endl;\n\ts << \"subplot(3,2,2)\" << std::endl;\n\ts << \"plot(x, porient_y, x, pdorient_y)\" << std::endl;\n\ts << \"subplot(3,2,3)\" << std::endl;\n\ts << \"plot (x,px_y, x, py_y)\" << std::endl;\n\ts << \"subplot(3,2,4)\" << std::endl;\n\ts << \"plot (x,pdx_y, x, pdy_y)\" << std::endl;\n\ts << \"subplot(3,2,5)\" << std::endl;\n\ts << \"plot (x,pddx_y, x, pddy_y)\" << std::endl;\n\ts << \"subplot(3,2,6)\" << std::endl;\n\ts << \"plot (x,pdddx_y, x, pdddy_y)\" << std::endl;\n\tROS_INFO_STREAM_FILTER(&messageFilter, \"Matlab_splines : \" << s.str());\n}\n\n// Find the angle that line p1p2 is pointing at\ndouble getLineAngle(const std::vector<double> &p1, const std::vector<double> &p2)\n{\n\treturn angles::normalize_angle_positive(atan2(p2[1] - p1[1], p2[0] - p1[0]));\n}\n\n// Optimization parameters - these are deltas added to\n// the original guess for the spline generation used\n// to improve the overall cost of following the spline\nstruct OptParams\n{\n\tdouble posX_;\n\tdouble posY_;\n\tdouble length_;\n\n\tOptParams(void)\n\t\t: posX_(0.)\n\t\t, posY_(0.)\n\t\t, length_(0.)\n\t{\n\t}\n\n\t// Syntax to let callers use the values in this\n\t// object as if they were an array. Since the optimizer\n\t// loops over all member vars, this turns the code\n\t// in there into a simple for() loop\n\tconst size_t size(void) const\n\t{\n\t\treturn 3;\n\t}\n\n\tdouble& operator[](size_t i)\n\t{\n\t\tif (i == 0)\n\t\t\treturn posX_;\n\t\tif (i == 1)\n\t\t\treturn posY_;\n\t\tif (i == 2)\n\t\t\treturn length_;\n\t\tthrow std::out_of_range (\"out of range in OptParams operator[]\");\n\t}\n};\n\n// Helper function for finding 2nd derivative\n// (acceleration) term of start and end point\nvoid setFirstLastPointAcceleration(const std::vector<double> &p1, const std::vector<double> &p2,\n\t\t\t\t\t\t\t\t   const std::vector<double> &v1, const std::vector<double> &v2,\n\t\t\t\t\t\t\t\t   std::vector<double> &accelerations)\n{\n\t// Rename vars to match notation in the paper\n\tconst double Ax  = p1[0];\n\tconst double Ay  = p1[1];\n\tconst double tAx = v1[0];\n\tconst double tAy = v1[1];\n\tconst double Bx  = p2[0];\n\tconst double By  = p2[1];\n\tconst double tBx = v2[0];\n\tconst double tBy = v2[1];\n\n\tconst double xaccel = 6.0 * Ax + 2.0 * tAx + 4.0 * tBx - 6.0 * Bx;\n\tconst double yaccel = 6.0 * Ay + 2.0 * tAy + 4.0 * tBy - 6.0 * By;\n\n\taccelerations.push_back(xaccel); // x\n\taccelerations.push_back(yaccel); // y\n\taccelerations.push_back(0.); // theta\n}\n\nbool initSpline(Trajectory &trajectory,\n\t\t\t\tstd::vector<std::string> jointNames,\n\t\t\t\tconst std::vector<trajectory_msgs::JointTrajectoryPoint> &points)\n{\n\tconst size_t nJoints = jointNames.size();\n\tstd::vector<bool> angle_wraparound;\n\n\t// Assume the path starts at time 0\n\tros::Time next_update_time = ros::Time(0);\n\tros::Time next_update_uptime = next_update_time;\n\n\t// Set this to false to prevent the code\n\t// from thinking we're driving rotation joints\n\t// rather than running linear motion\n\tfor (size_t i = 0; i < nJoints; i++)\n\t\tangle_wraparound.push_back(false);\n\n\t// Allocate memory to hold an initial trajectory\n\tTrajectory hold_trajectory;\n\tstatic typename Segment::State current_joint_state = typename Segment::State(1);\n\tfor (size_t i = 0; i < nJoints; ++i)\n\t{\n\t\tcurrent_joint_state.position[0] = 0;\n\t\tcurrent_joint_state.velocity[0] = 0;\n\t\tSegment hold_segment(0.0, current_joint_state, 0.0, current_joint_state);\n\n\t\tTrajectoryPerJoint joint_segment;\n\t\tjoint_segment.resize(1, hold_segment);\n\t\thold_trajectory.push_back(joint_segment);\n\t}\n\n\t// This generates a starting trajectory\n\t// with the robot sitting still at location 0,0,0.\n\t// It is needed as an initial condition for the\n\t// robot to connect it to the first waypoint\n\t//\n\t// TODO : make the starting position and\n\t// velocity a variable passed in to the\n\t// path generation request.\n\n\n\t//TODO: WHAT BE THIS BRACKET\n\t// Adding scope for these var names - they're repeated\n\t// in other bits of code taken from various functions\n\t// in other source files.  Easier than renaming them\n\t{\n\t\tstatic typename Segment::State hold_start_state = typename Segment::State(1);\n\t\tstatic typename Segment::State hold_end_state = typename Segment::State(1);\n\n\t\tconst double stop_trajectory_duration = period.toSec() / 2.;\n\t\tconst typename Segment::Time start_time  = 0;\n\t\tconst typename Segment::Time end_time    = stop_trajectory_duration;\n\t\tconst typename Segment::Time end_time_2x = 2.0 * stop_trajectory_duration;\n\n\t\t// Create segment that goes from current (pos,vel) to (pos,-vel)\n\t\tfor (size_t i = 0; i < nJoints; ++i)\n\t\t{\n\t\t\thold_start_state.position[0]     = 0.0;\n\t\t\thold_start_state.velocity[0]     = 0.0;\n\t\t\thold_start_state.acceleration[0] = 0.0;\n\n\t\t\thold_end_state.position[0]       = 0.0;\n\t\t\thold_end_state.velocity[0]       = -0.0;\n\t\t\thold_end_state.acceleration[0]   = 0.0;\n\n\t\t\thold_trajectory[i].front().init(start_time, hold_start_state, end_time_2x, hold_end_state);\n\n\t\t\t// Sample segment at its midpoint, that should have zero velocity\n\t\t\thold_trajectory[i].front().sample(end_time, hold_end_state);\n\n\t\t\t// Now create segment that goes from current state to one with zero end velocity\n\t\t\thold_trajectory[i].front().init(start_time, hold_start_state, end_time, hold_end_state);\n\t\t}\n\t}\n\n\t// Set basic options for the trajectory\n\t// generation controller\n\tjoint_trajectory_controller::InitJointTrajectoryOptions<Trajectory> options;\n\toptions.other_time_base           = &next_update_uptime;\n\toptions.current_trajectory        = &hold_trajectory;\n\toptions.joint_names               = &jointNames;\n\toptions.angle_wraparound          = &angle_wraparound;\n\toptions.rt_goal_handle            = NULL;\n\toptions.default_tolerances        = NULL;\n\toptions.allow_partial_joints_goal = true;\n\tfor (size_t i = 0; (i < points.size()) && (messageFilter.isEnabled()); i++)\n\t{\n\t\tROS_INFO_STREAM_FILTER(&messageFilter, \"points[\" << i << \"]\");\n\t\tros::message_operations::Printer<::trajectory_msgs::JointTrajectoryPoint_<std::allocator<void>>>::stream(std::cout, \"  \", points[i]);\n\t}\n\n\t// Actually generate the new trajectory\n\t// This will create spline coefficents for\n\t// each of the x,y,z paths\n\ttry\n\t{\n\t\ttrajectory_msgs::JointTrajectory jtm;\n\t\tjtm.joint_names = jointNames;\n\t\tjtm.points = points;\n\t\ttrajectory = joint_trajectory_controller::initJointTrajectory<Trajectory>(jtm, next_update_time, options);\n\t\tif (trajectory.empty())\n\t\t{\n\t\t\tROS_WARN(\"Not publishing empty trajectory\");\n\t\t\treturn false;\n\t\t}\n\t}\n\tcatch(const std::invalid_argument& ex)\n\t{\n\t\tROS_ERROR_STREAM(ex.what());\n\t\treturn false;\n\t}\n\tcatch(...)\n\t{\n\t\tROS_ERROR(\"Unexpected exception caught when initializing trajectory from ROS message data.\");\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nbool generateSpline(      std::vector<trajectory_msgs::JointTrajectoryPoint> points,\n\t\t\t\t\tconst std::vector<OptParams> &optParams,\n\t\t\t\t\tTrajectory &trajectory)\n{\n\t// Hard code 3 dimensions for paths to\n\t// follow - x&y translation and z rotation\n\tstatic std::vector<std::string> jointNames = {\"x_linear_joint\", \"y_linear_joint\", \"z_rotation_joint\"};\n\tconst size_t nJoints = jointNames.size();\n\n\t// Auto - generate velocities and accelerations for splines\n\t// based on a simple heuristic. This is becoming less simple\n\t// by the moment.\n\tif (points[0].velocities.size() == 0)\n\t{\n\t\t// Offset x and y by the amount determined by the optimizer\n\t\t// Paper says to make the coord system based off the\n\t\t// tangent direction (perp & parallel to tangent)\n\t\t// We'll see if that makes a difference\n\t\tfor (size_t i = 1; i < (points.size() - 1); i++)\n\t\t{\n\t\t\tpoints[i].positions[0] += optParams[i].posX_;\n\t\t\tpoints[i].positions[1] += optParams[i].posY_;\n\t\t}\n\n\t\t// Starting with 0 velocity for the initial condition\n\t\t// TODO - handle arbitrary starting velocity\n\t\tfor(size_t i = 0; i < nJoints; i++)\n\t\t{\n\t\t\tpoints[0].velocities.push_back(0.);\n\t\t}\n\t\t// Velocities of intermediate points are tangent\n\t\t// to the bisection of the angle between the incoming\n\t\t// and outgoing line segments.\n\t\t// Length of the tangent is min distance to either\n\t\t// previous or next waypoint\n\t\t// See http://www2.informatik.uni-freiburg.de/~lau/students/Sprunk2008.pdf\n\t\t// sectopm 4.1.1 and\n\t\t// http://ais.informatik.uni-freiburg.de/teaching/ws09/robotics2/projects/mr2-p6-paper.pdf\n\t\t// section 3.2 (equation 2 & 3) for details\n\t\t//\n\t\tdouble prevAngle = getLineAngle(points[0].positions, points[1].positions);\n\t\tdouble prevLength = hypot(points[1].positions[0] - points[0].positions[0],\n\t\t\t\t\t\t\t\t   points[1].positions[1] - points[0].positions[1]);\n\n\t\tfor (size_t i = 1; i < (points.size() - 1); i++)\n\t\t{\n\t\t\tconst auto &mi   = points[i].positions;\n\t\t\tconst auto &mip1 = points[i + 1].positions;\n\n\t\t\tconst double currAngle = getLineAngle(mi, mip1);\n\t\t\tdouble deltaAngle = currAngle - prevAngle;\n\t\t\tif (deltaAngle < -M_PI)\n\t\t\t\tdeltaAngle += 2.0 * M_PI;\n\t\t\tconst double angle = angles::normalize_angle_positive(prevAngle + deltaAngle / 2.0);\n\n\t\t\tconst double currLength = hypot(mip1[0] - mi[0], mip1[1] - mi[1]);\n\n\t\t\t// Adding a scaling factor here controls the velocity\n\t\t\t// at the waypoints.  Bigger than 1 ==> curvier path with\n\t\t\t// higher speeds.  Less than 1 ==> tigher turns to stay\n\t\t\t// closer to straight paths.\n\t\t\tconst double length = std::min(prevLength, currLength) * .75 + optParams[i].length_;\n\n\t\t\tpoints[i].velocities.push_back(length * cos(angle)); // x\n\t\t\tpoints[i].velocities.push_back(length * sin(angle)); // y\n\t\t\tpoints[i].velocities.push_back(0.0); // theta TODO : what if there is rotation both before and after this waypoint?\n\n#if 0\n\t\t\tROS_INFO_STREAM_FILTER(&messageFilter, \"prevAngle \" << prevAngle << \" prevLength \" << prevLength);\n\t\t\tROS_INFO_STREAM_FILTER(&messageFilter, \"currAngle \" << currAngle << \" currLength \" << currLength);\n\t\t\tROS_INFO_STREAM_FILTER(&messageFilter, \"currAngle - prevAngle = \" << currAngle - prevAngle << \" angles::normalize_angle_positive(currAngle - prevAngle) = \" << angles::normalize_angle_positive(currAngle - prevAngle));\n\t\t\tROS_INFO_STREAM_FILTER(&messageFilter, \"angle \" << angle << \" length \" << length);\n#endif\n\t\t\t// Update for next step\n\t\t\tprevAngle = currAngle;\n\t\t\tprevLength = currLength;\n\t\t}\n\n\t\t// End position is also 0 velocity\n\t\t// TODO - handle input end velocity\n\t\tfor(size_t i = 0; i < nJoints; i++)\n\t\t{\n\t\t\tpoints.back().velocities.push_back(0.);\n\t\t}\n\n\t\t// Guess for acceleration term is explained in\n\t\t// http://www2.informatik.uni-freiburg.de/~lau/students/Sprunk2008.pdf\n\t\t// section 4.2.1.  Basically, pretend there are cubic splines\n\t\t// (bezier splines in this case) between two points.  These are splines\n\t\t// which just connect the two points, and use the velocity at\n\t\t// those points calculated above.  This gives reasonable curvature along\n\t\t// the path between the two points. Taking the\n\t\t// weighted average of the 2nd derivatives of the pretend cubic\n\t\t// splines at the given point, and using that to generate\n\t\t// a quintic spline does a reasonable job of preserving\n\t\t// smoothness while also making the curve continuous.\n\t\t//\n\t\t// First and last point don't have a prev / next point\n\t\t// to connect to, so just grab the 2nd derivitave off\n\t\t// the point they are adjacent to\n\t\tsetFirstLastPointAcceleration(points[0].positions, points[1].positions,\n\t\t\t\tpoints[0].velocities, points[1].velocities,\n\t\t\t\tpoints[0].accelerations);\n\n\t\tconst size_t last = points.size() - 1;\n\t\tsetFirstLastPointAcceleration(points[last-1].positions, points[last].positions,\n\t\t\t\tpoints[last-1].velocities, points[last].velocities,\n\t\t\t\tpoints[last].accelerations);\n\t\t// For interior points, weight the average of the\n\t\t// 2nd derivative of each of the pretend cubic\n\t\t// splines and use them as the acceleration for\n\t\t// the to-be-generated quintic spline.\n\t\tfor (size_t i = 1; i < (points.size() - 1); i++)\n\t\t{\n\t\t\tconst double Ax = points[i-1].positions[0];\n\t\t\tconst double Ay = points[i-1].positions[1];\n\t\t\tconst double tAx = points[i-1].velocities[0];\n\t\t\tconst double tAy = points[i-1].velocities[1];\n\n\t\t\tconst double Bx = points[i].positions[0];\n\t\t\tconst double By = points[i].positions[1];\n\t\t\tconst double tBx = points[i].velocities[0];\n\t\t\tconst double tBy = points[i].velocities[1];\n\n\t\t\tconst double Cx = points[i+1].positions[0];\n\t\t\tconst double Cy = points[i+1].positions[1];\n\t\t\tconst double tCx = points[i+1].velocities[0];\n\t\t\tconst double tCy = points[i+1].velocities[1];\n\n\t\t\t// L2 distance between A and B\n\t\t\tconst double dab = hypot(Bx - Ax, By - Ay);\n\t\t\t// L2 distance between B and C\n\t\t\tconst double dbc = hypot(Cx - Bx, Cy - By);\n\n\t\t\t// Weighting factors\n\t\t\tconst double alpha = dbc / (dab + dbc);\n\t\t\tconst double beta  = dab / (dab + dbc);\n\n\t\t\tconst double xaccel = alpha * ( 6.0 * Ax + 2.0 * tAx + 4.0 * tBx - 6.0 * Bx) +\n\t\t\t\t\t\t\t\t  beta  * (-6.0 * Bx - 4.0 * tBx - 2.0 * tCx + 6.0 * Cx);\n\t\t\tconst double yaccel = alpha * ( 6.0 * Ay + 2.0 * tAy + 4.0 * tBy - 6.0 * By) +\n\t\t\t\t\t\t\t\t  beta  * (-6.0 * By - 4.0 * tBy - 2.0 * tCy + 6.0 * Cy);\n\n\t\t\tpoints[i].accelerations.push_back(xaccel); // x\n\t\t\tpoints[i].accelerations.push_back(yaccel); // y\n\t\t\tpoints[i].accelerations.push_back(0.); // theta\n\n#if 0\n\t\t\tROS_INFO_STREAM_FILTER(&messageFilter, \"dab = \" << dab << \" dbc = \" << dbc);\n\t\t\tROS_INFO_STREAM_FILTER(&messageFilter, \"Ax = \" << Ax << \" tAx = \" << tAx <<\n\t\t\t                \" Bx = \" << Bx << \" tBx = \" << tBx <<\n\t\t\t                \" Cx = \" << Cx << \" tCx = \" << tCx);\n\t\t\tROS_INFO_STREAM_FILTER(&messageFilter, \"Ay = \" << Ay << \" tAy = \" << tAy <<\n\t\t\t                \" By = \" << By << \" tBy = \" << tBy <<\n\t\t\t                \" Cy = \" << Cy << \" tCy = \" << tCy);\n#endif\n\t\t}\n\t}\n\n\treturn initSpline(trajectory, jointNames, points);\n}\n\ndouble distSquared(const std::vector<double> &v, const std::vector<double> &w)\n{\n\treturn ((v[0] - w[0]) * (v[0] - w[0])) + ((v[1] - w[1]) * (v[1] - w[1]));\n}\n\ndouble distSquared(const double px, const double py, const std::vector<double> &w)\n{\n\treturn ((px - w[0]) * (px - w[0])) + ((py - w[1]) * (py - w[1]));\n}\n\n// Minimum distance between segment vw and point (p1, p2)\ndouble pointToLineSegmentDistance(const std::vector<double> &v, const std::vector<double> &w,\n\t\tdouble px, double py)\n{\n\tconst float l2 = distSquared(v, w);\n\tif (l2 == 0.0)\n\t\treturn sqrt(distSquared(px, py, v));   // v == w case, distance to single point\n\t// Consider the line extending the segment, parameterized as v + t (w - v).\n\t// We find projection of point p onto the line.\n\t// It falls where t = [(p-v) . (w-v)] / |w-v|^2\n\t// We clamp t from [0,1] to handle points outside the segment vw.\n\tconst double t = std::max(0.0, std::min(1.0, ((px - v[0]) * (w[0] - v[0]) + (py - v[1]) * (w[1] - v[1])) / l2));\n\tconst double projectionX = v[0] + t * (w[0] - v[0]);\n\tconst double projectionY = v[1] + t * (w[1] - v[1]);\n\treturn hypot(px - projectionX, py - projectionY);\n}\n\nstruct ArclengthAndTime\n{\n\tArclengthAndTime(const double arcLength, const double time) :\n\t\tarcLength_(arcLength),\n\t\ttime_(time)\n\t{\n\t}\n\tdouble arcLength_;\n\tdouble time_;\n};\n\n// Use Simpson's rule to estimate arc length between start and\n// and time.  Function is combining dx and dy into a length,\n// so use hypot(dx,dy) as the function being evaluated.\n// Get the uppwer bound of the error as well - this lets\n// us know if the estimate is within the bounds specified\n// for calculating the estimate.\nvoid simpsonsRule(double &estimate, double &error,\n\t\t\t\t  const double startT, const double endT,\n\t\t\t\t  const SplineCoefs &xStartCoefs,\n\t\t\t\t  const SplineCoefs &yStartCoefs,\n\t\t\t\t  const SplineCoefs &xEndCoefs,\n\t\t\t\t  const SplineCoefs &yEndCoefs,\n\t\t\t\t  const double startXdot, const double startYdot,\n\t\t\t\t  const double midXdot, const double midYdot,\n\t\t\t\t  const double endXdot, const double endYdot)\n{\n\tconst double periodT = endT - startT;\n\testimate = periodT / 6.0 * (hypot(startXdot, startYdot) + 4.0 * hypot(midXdot, midYdot) + hypot(endXdot, endYdot));\n\n\tconst double commonErrorTerm = (1.0/90.0) * pow(periodT / 2.0, 5.0);\n\t// Error term is a line (mx+b) so min/max is going to be at one end\n\t// or the other.\n\tconst double startError = hypot(120.0 * xStartCoefs[0][5] * startT + 24.0 * xStartCoefs[0][4],\n\t\t\t\t\t\t\t\t\t120.0 * yStartCoefs[0][5] * startT + 24.0 * yStartCoefs[0][4]);\n\tconst double endError = hypot(120.0 * xEndCoefs[0][5] * endT + 24.0 * xEndCoefs[0][4],\n\t\t\t\t\t\t\t\t  120.0 * yEndCoefs[0][5] * endT + 24.0 * yEndCoefs[0][4]);\n\n\terror = commonErrorTerm * std::max(startError, endError);\n}\n\n// Recursive function to get arc length of x/y path using\n// subdivision.\n// Basic algorithm breaks the segment into two halves. If the\n// estimated length of the two halves is close enough to the length\n// estimated for the full length of the segment, assume the algorithm\n// has converged and keep that result (use the two halves since they're\n// likely more accurate).\n// If the sum of the halves are too far off from the total length\n// recursively call the function on the first and second halves.\n// Returns two things - arcLengthAndTime is a vector of\n// <cumulative arcLength at that time, time> tuples, hopefully increasing in time\n// along with totalLength, which is the total length calculated so far.\nbool getPathSegLength(std::vector<ArclengthAndTime> &arcLengthAndTime,\n\t\tconst Trajectory &trajectory,\n\t\tdouble &totalLength,\n\t\tTrajectoryPerJoint::const_iterator startXIt,\n\t\tTrajectoryPerJoint::const_iterator startYIt,\n\t\tTrajectoryPerJoint::const_iterator endXIt,\n\t\tTrajectoryPerJoint::const_iterator endYIt,\n\t\tconst double startTime,\n\t\tconst double endTime,\n\t\tconst double startXdot,\n\t\tconst double startYdot,\n\t\tconst double endXdot,\n\t\tconst double endYdot)\n{\n\tconst double midTime = (startTime + endTime) / 2.0;\n\n\t// TODO : Perhaps a check on dT being too small?\n\n\t// Simpson's rule needs the provided start and end values and\n\t// also one at the midpoint. Grab the midpoint values here\n\tstatic Segment::State xState;\n\tTrajectoryPerJoint::const_iterator midXIt = sample(trajectory[0], midTime, xState);\n\tif (midXIt == trajectory[0].cend())\n\t{\n\t\tROS_ERROR_STREAM(\"base_trajectory : could not sample mid xState at time \" << midTime);\n\t\treturn false;\n\t}\n\n\tstatic Segment::State yState;\n\tTrajectoryPerJoint::const_iterator midYIt = sample(trajectory[1], midTime, yState);\n\tif (midYIt == trajectory[1].cend())\n\t{\n\t\tROS_ERROR_STREAM(\"base_trajectory : could not sample mid yState at time \" << midTime);\n\t\treturn false;\n\t}\n\tconst double midXdot = xState.velocity[0];\n\tconst double midYdot = yState.velocity[0];\n\n\tdouble estimate;\n\tdouble error;\n\n\tsimpsonsRule(estimate, error,\n\t\t\t\t startTime, endTime,\n\t\t\t\t startXIt->getCoefs(), startYIt->getCoefs(),\n\t\t\t\t endXIt->getCoefs(), endYIt->getCoefs(),\n\t\t\t\t startXdot, startYdot, midXdot, midYdot, endXdot, endYdot);\n\t//ROS_INFO_STREAM_FILTER(&messageFilter, \"simpsonsRule : startTime = \" << startTime << \" endTime = \" << endTime << \" error = \" << error);\n\n\t// If the error magnitude is less than epsilon,\n\t// use this approximation for the arcLength from\n\t// start to end\n\tif (fabs(error) < segLengthEpsilon)\n\t{\n\t\ttotalLength += estimate;\n\t\tarcLengthAndTime.push_back(ArclengthAndTime(totalLength, endTime));\n\t\treturn true;\n\t}\n\n\t// Otherwise, split segment in half\n\t// and recursively calculate the length of each half.\n\tif (!getPathSegLength(arcLengthAndTime, trajectory, totalLength,\n\t\t\t\t\t\t  startXIt, startYIt,\n\t\t\t\t\t\t  midXIt, midYIt,\n\t\t\t\t\t\t  startTime, midTime,\n\t\t\t\t\t\t  startXdot, startYdot,\n\t\t\t\t\t\t  midXdot, midYdot))\n\t\treturn false;\n\tif (!getPathSegLength(arcLengthAndTime, trajectory, totalLength,\n\t\t\t\t\t\t  midXIt, midYIt,\n\t\t\t\t\t\t  endXIt, endYIt,\n\t\t\t\t\t\t  midTime, endTime,\n\t\t\t\t\t\t  midXdot, midYdot,\n\t\t\t\t\t\t  endXdot, endYdot))\n\t\treturn false;\n\treturn true;\n}\n\n// Given a trajectory, find time values which generate\n// increasing, equally spaced lengths along\n// that trajectory\nbool subdivideLength(std::vector<double> &equalLengthTimes,\n\t\tconst Trajectory &trajectory,\n\t\tconst double distanceBetweenLengths,\n\t\tconst double distanceEpsilon)\n{\n\tequalLengthTimes.clear();\n\tequalLengthTimes.push_back(0); // start at t==0\n\n\t// For each cumulative distance\n\t// start = prev found time, end = last time\n\t// Binary seh to get sample[] within tolerance of desired cumulative disance\n\t// Push that result onto equalLengthTimes\n\tdouble start = 0.0;\n\n\t// since we're looking for more or less monotonincally increasing values\n\t// keep track of the jump to get from one location to another. Use\n\t// this as a starting guess for the next length increment\n\tdouble prevStart = 0.0;\n\tconst double endTime = trajectory[0].back().endTime();\n\tdouble prevTimeDelta = endTime / 2.0;\n\n\tstatic Segment::State state;\n\tsample(trajectory[0], endTime, state);\n\tconst double totalLength = state.position[0];\n\n\tsize_t iterCount = 0;\n\tfor (double currDistance = distanceBetweenLengths; currDistance <= totalLength; currDistance += distanceBetweenLengths)\n\t{\n\t\tdouble end = endTime;\n\t\tdouble mid = start + prevTimeDelta;\n\t\twhile((end - mid) > 0.001) // Quit if time delta gets too small\n\t\t{\n\t\t\tTrajectoryPerJoint::const_iterator trajIt = sample(trajectory[0], mid, state);\n\t\t\tif (trajIt == trajectory[0].cend())\n\t\t\t{\n\t\t\t\tROS_ERROR_STREAM(\"base_trajectory : could not sample mid state at time \" << mid);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\titerCount += 1;\n\t\t\tconst double delta = currDistance - state.position[0];\n\t\t\t//ROS_INFO_STREAM_FILTER(&messageFilter, \"currDistance = \" << currDistance << \" start=\" << start << \" mid=\" << mid << \" end=\" << end << \" position[0]=\" << state.position[0] << \" delta=\" << delta);\n\t\t\tif (fabs(delta) < distanceEpsilon)\n\t\t\t{\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\telse if (delta > 0)\n\t\t\t{\n\t\t\t\tstart = mid;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tend = mid;\n\t\t\t}\n\t\t\tmid = (start + end) / 2.0;\n\t\t}\n\n\t\tif (mid > endTime)\n\t\t{\n\t\t\tequalLengthTimes.push_back(endTime);\n\t\t\tbreak;\n\t\t}\n\n\t\tequalLengthTimes.push_back(mid);\n\t\tstart = mid;\n\t\t// Use starting \"midpoint\" guess of of start time plus\n\t\t// the previous time jump, plus a little bit extra to\n\t\t// make sure we don't undershoot. Undershooting would require a\n\t\t// binary search of basically the entire distance between\n\t\t// mid and end, and since mid is very close to the start,\n\t\t// it is basically a binary search of the entire range.\n\t\tprevTimeDelta = (start - prevStart) * midTimeInflation;\n\t\tprevStart = start;\n\t}\n\tROS_INFO_STREAM_FILTER(&messageFilter, \"iterCount = \" << iterCount);\n\treturn true;\n}\n\nbool getPathLength(Trajectory &arcLengthTrajectory,\n\t\t\t\t   const Trajectory &trajectory)\n{\n\tstatic Segment::State xState;\n\tstatic Segment::State yState;\n\n\t// Get initial conditions for getPathSegLength call\n\t// for this particular segment\n\tTrajectoryPerJoint::const_iterator startXIt = sample(trajectory[0], 0, xState);\n\tif (startXIt == trajectory[0].cend())\n\t{\n\t\tROS_ERROR(\"base_trajectory : could not sample initial xState 0\");\n\t\treturn false;\n\t}\n\n\tTrajectoryPerJoint::const_iterator startYIt = sample(trajectory[1], 0, yState);\n\tif (startYIt == trajectory[1].cend())\n\t{\n\t\tROS_ERROR(\"base_trajectory : could not sample initial yState 0\");\n\t\treturn false;\n\t}\n\tconst double startXdot = xState.velocity[0];\n\tconst double startYdot = yState.velocity[0];\n\n\tconst double endTime = trajectory[0].back().endTime();\n\tTrajectoryPerJoint::const_iterator endXIt = sample(trajectory[0], endTime, xState);\n\tif (endXIt == trajectory[0].cend())\n\t{\n\t\tROS_ERROR(\"base_trajectory : could not sample initial xState end\");\n\t\treturn false;\n\t}\n\tTrajectoryPerJoint::const_iterator endYIt = sample(trajectory[1], endTime, yState);\n\tif (endYIt == trajectory[1].cend())\n\t{\n\t\tROS_ERROR(\"base_trajectory : could not sample initial yState end\");\n\t\treturn false;\n\t}\n\n\tconst double endXdot = xState.velocity[0];\n\tconst double endYdot = yState.velocity[0];\n\n\tdouble totalLength = 0.0;\n\n\t// Generate a list of time -> arclength pairs stored\n\t// in arcLengthAndTime\n\tstd::vector<ArclengthAndTime> arcLengthAndTime;\n\tif (!getPathSegLength(arcLengthAndTime, trajectory, totalLength,\n\t\t\tstartXIt, startYIt,\n\t\t\tendXIt, endYIt,\n\t\t\t0, endTime, // start, end time\n\t\t\tstartXdot, startYdot,\n\t\t\tendXdot, endYdot))\n\t\treturn false;\n\n\t// Create a path between each of these length/time\n\t// coordinates using cubic splines to interpolate\n\t// between each point\n\tstatic const std::vector<std::string> jointNames = { \"arcLength\" };\n\tstd::vector<trajectory_msgs::JointTrajectoryPoint> points;\n\tfor (const auto &alt : arcLengthAndTime)\n\t{\n\t\tpoints.push_back(trajectory_msgs::JointTrajectoryPoint());\n\t\tpoints.back().positions.push_back(alt.arcLength_);\n\t\tpoints.back().time_from_start = ros::Duration(alt.time_);\n\t}\n\n\tif (!initSpline(arcLengthTrajectory, jointNames, points))\n\t\treturn false;\n\n\treturn true;\n}\n\n// evaluate spline - inputs are spline coeffs (Trajectory), waypoints, dmax, vmax, amax, acentmax\n//                   returns time taken to drive spline, cost, possibly waypoints\nbool evaluateSpline(double &cost,\n\t\t\t\t\tconst Trajectory &trajectory,\n\t\t\t\t\tconst std::vector<trajectory_msgs::JointTrajectoryPoint> &points,\n\t\t\t\t\tconst double dMax, // limit of path excursion from straight line b/t waypoints\n\t\t\t\t\tconst double vMax, // max overall velocity\n\t\t\t\t\tconst double aMax, // max allowed acceleration\n\t\t\t\t\tconst double wheelRadius, // radius from center to wheels\n\t\t\t\t\tconst double aCentMax) // max allowed centripetal acceleration\n{\n\n\t// arcLengthTrajectory takes in a time and returns the x-y distance\n\t// traveled up to that time.\n\tTrajectory arcLengthTrajectory;\n\tif (!getPathLength(arcLengthTrajectory, trajectory))\n\t{\n\t\tROS_ERROR(\"base_trajectory_node : getPathLength() failed\");\n\t\treturn false;\n\t}\n\t// equalArcLengthTimes will contain times that are\n\t// spaced equidistant along the arc length passed in\n\tstd::vector<double> equalArcLengthTimes;\n\tif (!subdivideLength(equalArcLengthTimes, arcLengthTrajectory,\n\t\t\t\t\t\t distBetweenArcLengths, distBetweenArcLengthEpsilon))\n\t\treturn false;\n\n\t// equalArcLengthTimes is a vector of times. Each entry is the time\n\t// of an equally-spaced sample from arcLengthTrajectory. That is\n\t// sample i is arclength (approx) d away from sample i-1 and i+1 for all i.\n\n\t// Starting at arclength 0\n\tdouble prevArcLength = 0;\n\n\tstd::vector<double> deltaS;   // change in position along spline for each step\n\tstd::vector<double> distanceToPathMidpoint;\n\tstd::vector<double> vTrans; // max velocity allowed at each step\n\tstd::vector<double> vRot;\n\n\t// Add 0th entries for arrays so indices line up with equalArcLengthTimes\n\tdeltaS.push_back(0);\n\tdistanceToPathMidpoint.push_back(0);\n\tvTrans.push_back(0);\n\tvRot.push_back(0);\n\tsize_t seg = 0;\n\t// Declare these static so they're not constantly created\n\t// and destroyed on every call to the function\n\tstatic Segment::State arcLengthState;\n\tstatic Segment::State xState;\n\tstatic Segment::State yState;\n\tstatic Segment::State thetaState;\n\tfor (size_t i = 1; i < equalArcLengthTimes.size(); i++)\n\t{\n\t\tconst double t = equalArcLengthTimes[i];\n\t\twhile (points[seg+1].time_from_start < ros::Duration(t))\n\t\t\tseg += 1;\n\t\t//ROS_INFO_STREAM_FILTER(&messageFilter, \"processing index \" << i << \" t=\" << t <<\" seg=\" << seg);\n\t\t// Save distance between prev and current position for this timestep\n\t\t// This should be nearly constant between points, but\n\t\t// get the exact value for each to be more precise\n\t\tTrajectoryPerJoint::const_iterator arcLengthIt = sample(arcLengthTrajectory[0], t, arcLengthState);\n\t\tif (arcLengthIt == arcLengthTrajectory[0].cend())\n\t\t{\n\t\t\tROS_ERROR_STREAM(\"base_trajectory : evaluateSpline could not sample arcLengthState at time \" << t);\n\t\t\treturn false;\n\t\t}\n\t\tdeltaS.push_back(arcLengthState.position[0] - prevArcLength);\n\t\tprevArcLength = arcLengthState.position[0];\n\n\t\t// Since seg is set to the current spline segment, use this to\n\t\t// index into each trajectory. This saves time compared to searching\n\t\t// through the range of times in each trajectory array\n\t\t// Add 1 to account for the dummy starting segment\n\t\tTrajectoryPerJoint::const_iterator xIt = trajectory[0].cbegin() + seg + 1;\n\t\tif (xIt >= trajectory[0].cend())\n\t\t{\n\t\t\tROS_ERROR_STREAM(\"base_trajectory : evaluateSpline could not sample xState at time \" << t);\n\t\t\treturn false;\n\t\t}\n\t\txIt->sample(t, xState);\n\n\t\tTrajectoryPerJoint::const_iterator yIt = trajectory[1].cbegin() + (xIt - trajectory[0].cbegin());\n\t\tif (yIt >= trajectory[1].cend())\n\t\t{\n\t\t\tROS_ERROR_STREAM(\"base_trajectory : evaluateSpline could not sample yState at time \" << t);\n\t\t\treturn false;\n\t\t}\n\t\tyIt->sample(t, yState);\n\n\t\tTrajectoryPerJoint::const_iterator thetaIt = trajectory[2].cbegin() + (xIt - trajectory[0].cbegin());\n\t\tif (thetaIt >= trajectory[2].cend())\n\t\t{\n\t\t\tROS_ERROR_STREAM(\"base_trajectory : evaluateSpline could not sample thetaState at time \" << t);\n\t\t\treturn false;\n\t\t}\n\t\tthetaIt->sample(t, thetaState);\n\n\t\t// Get orthogonal distance between spline position and\n\t\t// line segment connecting the corresponding waypoints\n\t\tdistanceToPathMidpoint.push_back(pointToLineSegmentDistance(points[seg].positions, points[seg+1].positions, xState.position[0], yState.position[0]));\n#if 0\n\t\tROS_INFO_STREAM_FILTER(&messageFilter, \"pointToLineSegmentDistance = \" << distanceToPathMidpoint.back() <<\n\t\t\t\t\" p1: \" << points[seg].positions[0] << \",\" << points[seg].positions[1] <<\n\t\t\t\t\" p2: \" << points[seg+1].positions[0] << \",\" << points[seg+1].positions[1] <<\n\t\t\t\t\" x: \" << xState.position[0] << \" y: \" << yState.position[0]);\n#endif\n\n\t\t// Get curvature for this sample\n\t\tconst double pXdot = xState.velocity[0];\n\t\tconst double pXdotdot = xState.acceleration[0];\n\t\tconst double pYdot = yState.velocity[0];\n\t\tconst double pYdotdot = yState.acceleration[0];\n\t\tconst double curvature = (pXdot * pYdotdot - pYdot * pXdotdot) / pow(pXdot * pXdot + pYdot * pYdot, 3.0/2.0);\n\t\t//ROS_INFO_STREAM_FILTER(&messageFilter, \"curvature = \" << curvature);\n\n\t\t// First pass of vTrans limits by absolute max velocity\n\t\t// and also velocity limited by max centripetal acceleration\n\t\t// Assume rotational velocity is a hard constraint we have to hit\n\t\tvTrans.push_back(std::min(vMax - fabs(thetaState.velocity[0]) * wheelRadius, sqrt(aCentMax / fabs(curvature))));\n\t\t//ROS_INFO_STREAM_FILTER(&messageFilter, \"vTrans[\" << i << \"==\" << equalArcLengthTimes[i] <<\"]=\" << vTrans[i]);\n\t}\n\n\t// Forward pass\n\tfor (size_t i = 1; i < vTrans.size(); i++)\n\t{\n\t\tvTrans[i] = std::min(vTrans[i], sqrt(vTrans[i - 1] * vTrans[i - 1] + 2.0 * aMax * deltaS[i]));\n\t\t//ROS_INFO_STREAM_FILTER(&messageFilter, \"vTrans[\" << i << \"==\" << equalArcLengthTimes[i] <<\"]=\" << vTrans[i]);\n\t}\n\n\t// Backwards pass\n\tvTrans.back() = 0; // Hard-code end velocity for now. TODO - make it grab from last point or spline segment\n\tfor (size_t i = vTrans.size() - 2; i > 0; i--)\n\t{\n\t\tvTrans[i] = std::min(vTrans[i], sqrt(vTrans[i + 1] * vTrans[i + 1] + 2.0 * aMax * deltaS[i - 1]));\n\t\t//ROS_INFO_STREAM_FILTER(&messageFilter, \"vTrans[\" << i << \"==\" << equalArcLengthTimes[i] <<\"]=\" << vTrans[i]);\n\t}\n\n\t// Calculate arrival time at each of the equalLengthArcTimes distances\n\tstd::vector<double> remappedTimes;\n\tremappedTimes.push_back(0);\n\tfor (size_t i = 1; i < vTrans.size(); i++)\n\t{\n\t\tremappedTimes.push_back(remappedTimes.back() + (2.0 * deltaS[i]) / (vTrans[i - 1] + vTrans[i]));\n\t}\n\n\t// Cost is total time to traverse the path plus a large\n\t// penalty for moving more that dMax past the mipoint of the\n\t// straight line segment connecting each waypoint. The latter\n\t// imposes a constraint that the path can't be too curvy - and\n\t// keeping close to the straight-line path should prevent it from running\n\t// into obstacles too far off that path.\n\tcost = remappedTimes.back();\n\tfor (const auto d: distanceToPathMidpoint)\n\t{\n\t\tcost += exp(25.0 * ((fabs(d) / dMax) - 0.9));\n\t}\n\tROS_INFO_STREAM_FILTER(&messageFilter, \"time = \" << remappedTimes.back() << \" cost = \" << cost);\n\n\treturn true;\n}\n\nvoid trajectoryToSplineResponseMsg(base_trajectory::GenerateSpline::Response &out_msg,\n\t\tconst Trajectory &trajectory,\n\t\tconst std::vector<std::string> &jointNames)\n{\n\t// Convert from Trajectory type into the correct output\n\t// message type\n\tout_msg.orient_coefs.resize(trajectory[0].size());\n\tout_msg.x_coefs.resize(trajectory[0].size());\n\tout_msg.y_coefs.resize(trajectory[0].size());\n\tout_msg.end_points.clear();\n\n\tconst size_t n_joints = jointNames.size();\n\tfor (size_t seg = 0; seg < trajectory[0].size(); seg++)\n\t{\n\t\tfor (size_t joint = 0; joint < n_joints; joint++)\n\t\t{\n\t\t\tROS_INFO_STREAM_FILTER(&messageFilter, \"joint = \" << jointNames[joint] << \" seg = \" << seg <<\n\t\t\t                \" start_time = \" << trajectory[joint][seg].startTime() <<\n\t\t\t                \" end_time = \" << trajectory[joint][seg].endTime());\n\t\t\tauto coefs = trajectory[joint][seg].getCoefs();\n\n\t\t\tstd::stringstream s;\n\t\t\ts << \"coefs \";\n\t\t\tfor (size_t i = 0; i < coefs[i].size(); ++i)\n\t\t\t\ts << coefs[0][i] << \" \";\n\t\t\tROS_INFO_STREAM_FILTER(&messageFilter, s.str());\n\n\t\t\tstd::vector<double> *m;\n\n\t\t\tif (joint == 0)\n\t\t\t\tm = &out_msg.x_coefs[seg].spline;\n\t\t\telse if (joint == 1)\n\t\t\t\tm = &out_msg.y_coefs[seg].spline;\n\t\t\telse if (joint == 2)\n\t\t\t\tm = &out_msg.orient_coefs[seg].spline;\n\t\t\telse\n\t\t\t{\n\t\t\t\tROS_WARN(\"Unexpected joint number constructing out_msg in base_trajectory\");\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Push in reverse order to match expectations\n\t\t\t// of point_gen code?\n\t\t\tm->clear();\n\t\t\tfor (int i = coefs[0].size() - 1; i >= 0; i--)\n\t\t\t\tm->push_back(coefs[0][i]);\n\t\t}\n\n\t\t// All splines in a waypoint end at the same time?\n\t\tout_msg.end_points.push_back(trajectory[0][seg].endTime());\n\t}\n\tTrajectory arcLengthTrajectory;\n\tif (!getPathLength(arcLengthTrajectory, trajectory))\n\t{\n\t\tROS_ERROR(\"base_trajectory_node trajectoryToSplineResponseMsg : getPathLength() failed\");\n\t\treturn;\n\t}\n\t// --- Generate waypoints for final path ---\n\t// equalArcLengthTimes will contain times that are\n\t// spaced equidistant along the arc length passed in\n\tstd::vector<double> equalArcLengthTimes;\n\tif (!subdivideLength(equalArcLengthTimes, arcLengthTrajectory,\n\t\t\t\t\t\t pathDistBetweenArcLengths, pathDistBetweenArcLengthsEpsilon))\n\t{\n\t\tROS_ERROR(\"base_trajectory_node trajectoryToSplineResponseMsg : subdivideLength() failed\");\n\t\treturn;\n\t}\n\tout_msg.path.poses.clear();\n\tconst auto current_time = ros::Time::now();\n\tout_msg.path.header.stamp = current_time;\n\tout_msg.path.header.frame_id = \"initial_pose\";\n\tstatic Segment::State state;\n\tfor (const auto t: equalArcLengthTimes)\n\t{\n\t\tgeometry_msgs::PoseStamped pose;\n\t\tpose.header.stamp = current_time + ros::Duration(t);\n\t\tpose.header.frame_id = \"initial_pose\";\n\n\t\tTrajectoryPerJoint::const_iterator xIt = sample(trajectory[0], t, state);\n\t\tif (xIt == trajectory[0].cend())\n\t\t{\n\t\t\tROS_ERROR_STREAM(\"base_trajectory trajectoryToSplineResponseMsg : could not sample xState at time \" << t);\n\t\t\treturn;\n\t\t}\n\t\tpose.pose.position.x = state.position[0];\n\n\t\tTrajectoryPerJoint::const_iterator yIt = sample(trajectory[1], t, state);\n\t\tif (yIt == trajectory[1].cend())\n\t\t{\n\t\t\tROS_ERROR_STREAM(\"base_trajectory trajectoryToSplineResponseMsg : could not sample yState at time \" << t);\n\t\t\treturn;\n\t\t}\n\t\tpose.pose.position.y = state.position[0];\n\t\tpose.pose.position.z = 0;\n\n\t\tTrajectoryPerJoint::const_iterator orientationIt = sample(trajectory[2], t, state);\n\t\tif (orientationIt == trajectory[2].cend())\n\t\t{\n\t\t\tROS_ERROR_STREAM(\"base_trajectory trajectoryToSplineResponseMsg : could not sample orientationState at time \" << t);\n\t\t\treturn;\n\t\t}\n\t\tgeometry_msgs::Quaternion orientation;\n\t\ttf2::Quaternion tf_orientation;\n\t\ttf_orientation.setRPY(0, 0, state.position[0]);\n\t\torientation.x = tf_orientation.getX();\n\t\torientation.y = tf_orientation.getY();\n\t\torientation.z = tf_orientation.getZ();\n\t\torientation.w = tf_orientation.getW();\n\n\t\tpose.pose.orientation = orientation;\n\t\tout_msg.path.poses.push_back(pose);\n\t}\n}\n\n// Algorithm to optimize parameters using the sign\n// of the change in cost function.\n// The parameters in this case are an offset to the X&Y positions\n// of each point the spline passes through along with the length of the\n// tangent to the path (the velocity) at that point.  Each point\n// can have all 3 altered to improve the overall cost of the path (where\n// cost is time to drive plus a sum of penalties for the path straying too\n// far from the straight line between waypoints).\n// The parameters are looped through one by one.  A small offset is added\n// to the parameter and a new spline is generated and scored.  The cost\n// compared to the previous cost is used to generate a new offset value\n// for the next iteration.\nbool RPROP(\n\t\tTrajectory &bestTrajectory,\n\t\tconst std::vector<trajectory_msgs::JointTrajectoryPoint> &points,\n\t\tdouble dMax, // limit of path excursion from straight line b/t waypoints\n\t\tdouble vMax, // max overall velocity\n\t\tdouble aMax, // max allowed acceleration\n\t\tdouble wheelRadius, // radius from center to wheels\n\t\tdouble aCentMax) // max allowed centripetal acceleration\n{\n\t// initialize params to 0 offset in x, y and tangent\n\t// length for all spline points\n\tstd::vector<OptParams> bestOptParams(points.size());\n\tif (!generateSpline(points, bestOptParams, bestTrajectory))\n\t{\n\t\tROS_ERROR(\"base_trajectory_node : RPROP initial generateSpline() falied\");\n\t\treturn false;\n\t}\n\n\t// Generate initial trajectory, evaluate to get cost\n\tdouble bestCost;\n\tif (!evaluateSpline(bestCost,\n\t\t\t\tbestTrajectory, points,\n\t\t\t\t0.2,    // limit of path excursion from straight line b/t waypoints\n\t\t\t\t4.5,    // max overall velocity\n\t\t\t\t2.5,    // max allowed acceleration\n\t\t\t\t0.3682, // wheel radius\n\t\t\t\t3.5))   // max allowed centripetal acceleration\n\t{\n\t\tROS_ERROR(\"base_trajectory_node : RPROP initial evaluateSpline() falied\");\n\t\treturn false;\n\t}\n\n\tdouble deltaCostEpsilon = initialDeltaCostEpsilon;\n\n\twhile (deltaCostEpsilon >= minDeltaCostEpsilon)\n\t{\n\t\tbool bestCostChanged = false;\n\n\t\t// Start with the previous best optimization parameters,\n\t\t// then loop through each and try to improve them\n\t\t// Ignore the first and last point - can't\n\t\t// optimize the starting and end position since\n\t\t// those need to be hit exactly.\n\t\tfor (size_t i = 1; i < (bestOptParams.size() - 1); i++) // index of param optimized\n\t\t{\n\t\t\t// OptParams is overloaded to act like an array\n\t\t\t// for accessing individual params for each point\n\t\t\tfor (size_t j = 0; j < bestOptParams[i].size(); j++)\n\t\t\t{\n\t\t\t\tauto optParams = bestOptParams;\n\t\t\t\tdouble deltaCost = std::numeric_limits<double>::max();\n\t\t\t\tdouble currCost = bestCost;\n\t\t\t\tdouble dparam = initialDParam;\n\t\t\t\t// One exit criteria for the inner loop is if the cost\n\t\t\t\t// stops improving by an appreciable amount while changing\n\t\t\t\t// this one parameter. Track that here\n\t\t\t\twhile (deltaCost > deltaCostEpsilon)\n\t\t\t\t{\n\t\t\t\t\t// Alter one optimization parameter\n\t\t\t\t\t// and see how it changes the cost compared\n\t\t\t\t\t// to the last iteration\n\t\t\t\t\tTrajectory thisTrajectory;\n\t\t\t\t\toptParams[i][j] += dparam;\n\t\t\t\t\tif (!generateSpline(points, optParams, thisTrajectory))\n\t\t\t\t\t{\n\t\t\t\t\t\tROS_ERROR(\"base_trajectory_node : RPROP generateSpline() falied\");\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\n\t\t\t\t\tdouble thisCost;\n\t\t\t\t\tif (!evaluateSpline(thisCost,\n\t\t\t\t\t\t\t\tthisTrajectory, points,\n\t\t\t\t\t\t\t\t0.2, // limit of path excursion from straight line b/t waypoints\n\t\t\t\t\t\t\t\t4.5, // max overall velocity\n\t\t\t\t\t\t\t\t2.5, // max allowed acceleration\n\t\t\t\t\t\t\t\t0.3682, // wheel radius\n\t\t\t\t\t\t\t\t3.5)) // max allowed centripetal acceleration\n\t\t\t\t\t{\n\t\t\t\t\t\tROS_ERROR(\"base_trajectory_node : RPROP evaluateSpline() failed\");\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\n\t\t\t\t\t// If cost is better than the best cost, record it and\n\t\t\t\t\t// move on to optimizing the next parameter. It is possible\n\t\t\t\t\t// to loop back and return to this one again, but the paper\n\t\t\t\t\t// says that hyper-optimizing one parameter before moving\n\t\t\t\t\t// to others can lead to getting stuck in local minima.\n\t\t\t\t\tif (thisCost < bestCost)\n\t\t\t\t\t{\n\t\t\t\t\t\tbestTrajectory = thisTrajectory;\n\t\t\t\t\t\tbestCost = thisCost;\n\t\t\t\t\t\tbestOptParams = optParams;\n\t\t\t\t\t\tbestCostChanged = true;\n\t\t\t\t\t\tROS_INFO_STREAM_FILTER(&messageFilter, \"+++++++++ New best cost : \" <<  bestCost);\n\t\t\t\t\t\tfor (const auto &it: bestOptParams)\n\t\t\t\t\t\t\tROS_INFO_STREAM_FILTER(&messageFilter, \"     posX_:\" << it.posX_ << \" posY_:\" << it.posY_ << \" length_:\" << it.length_);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\t// Use sign of difference between this cost and the\n\t\t\t\t\t// previous one to adjust the dparam value added to\n\t\t\t\t\t// the parameter being optimized.  1.2 and -0.5 are\n\t\t\t\t\t// intentionally not factors of each other to prevent\n\t\t\t\t\t// oscillating between the same set of values\n\t\t\t\t\tif (thisCost < currCost)\n\t\t\t\t\t{\n\t\t\t\t\t\tdparam *= 1.2;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tdparam *= -0.5;\n\t\t\t\t\t}\n\t\t\t\t\t// Record values for next iteration\n\t\t\t\t\tdeltaCost = fabs(thisCost - currCost);\n\t\t\t\t\tROS_INFO_STREAM_FILTER(&messageFilter, \"RPROP : i=\" << i << \" j=\" << j << \" bestCost=\" << bestCost << \" thisCost=\" << thisCost << \" currCost=\" << currCost << \" deltaCost=\" << deltaCost << \" deltaCostEpsilon=\" << deltaCostEpsilon);\n\t\t\t\t\tcurrCost = thisCost;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (!bestCostChanged)\n\t\t\tdeltaCostEpsilon /= 1.75;\n\t}\n\treturn true;\n}\n\n\n// input should be JointTrajectory[] custom message\n// Output wil be array of spline coefficents base_trajectory/Coefs[] for x, y, orientation,\n// along with a path consisting of waypoints evenly spaced along the spline\nbool callback(base_trajectory::GenerateSpline::Request &msg,\n\t\t\t  base_trajectory::GenerateSpline::Response &out_msg)\n{\n\tconst auto startTime = ros::Time::now();\n\t// Hold current position if trajectory is empty\n\tif (msg.points.empty())\n\t{\n\t\tROS_ERROR(\"Empty trajectory command, nothing to do.\");\n\t\treturn false;\n\t}\n\tif (msg.points.size() < 2)\n\t{\n\t\tROS_WARN(\"Only one point passed into base_trajectory - adding a starting position of 0,0,0\");\n\t\tmsg.points.push_back(msg.points[0]);\n\t\tmsg.points[0].positions.clear();\n\t\tfor (size_t i = 0; i < 3; i++)\n\t\t\tmsg.points[i].positions.push_back(0);\n\t\tmsg.points[0].velocities.clear();\n\t\tmsg.points[0].accelerations.clear();\n\t}\n\n\t// Splines segments are each 1 arbitrary unit long.\n\t// This later gets mapped to actual wall-clock times\n\tfor (size_t i = 0; i < msg.points.size(); ++i)\n\t\tmsg.points[i].time_from_start = ros::Duration(static_cast<double>(i));\n\n\t// TODO - operate in two modes\n\t// 1 - if velocity and accelerations are empty, run a full optimization\n\t// 2 - if both are set, just generate a spline based on them, then\n\t//     convert that into an optimal path to follow\n\tfor (size_t i = 0; i < msg.points.size(); ++i)\n\t{\n\t\tif (msg.points[i].positions.size() != 3)\n\t\t{\n\t\t\tROS_ERROR_STREAM(\"Input point \" << i << \" must have 3 positions (x, y, orientation)\");\n\t\t\treturn false;\n\t\t}\n\t\tif (msg.points[i].velocities.size())\n\t\t{\n\t\t\tif (msg.points[i].velocities.size() != 3)\n\t\t\t{\n\t\t\t\tROS_ERROR_STREAM(\"Input point \" << i << \" must have 0 or 3 velocities (x, y, orientation)\");\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif ((msg.points[i].accelerations.size() != 0) &&\n\t\t\t\t(msg.points[i].accelerations.size() != 3))\n\t\t\t{\n\t\t\t\tROS_ERROR_STREAM(\"Input point \" << i << \" must have 0 or 3 accelerations (x, y, orientation)\");\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\telse if (msg.points[i].accelerations.size())\n\t\t{\n\t\t\tROS_ERROR_STREAM(\"Input point \" << i << \" must have 0 accelerations since there are also 0 velocities for that point)\");\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tstd::vector<OptParams> optParams(msg.points.size());\n\tTrajectory trajectory;\n\tif (!generateSpline(msg.points, optParams, trajectory))\n\t\treturn false;\n\n\tdouble cost;\n\tif (!evaluateSpline(cost,\n\t\t\t\ttrajectory, msg.points,\n\t\t\t\t0.2, // limit of path excursion from straight line b/t waypoints\n\t\t\t\t4.5, // max overall velocity\n\t\t\t\t2.5, // max allowed acceleration\n\t\t\t\t0.3682, // wheel radius\n\t\t\t\t3.5)) // max allowed centripetal acceleration\n\t{\n\t\tROS_ERROR(\"base_trajectory_node : evaluateSpline() returned false\");\n\t\treturn false;\n\t}\n\n#if 0\n\t// Test using middle switch auto spline\n\tout_msg.x_coefs[1].spline[0] = 6.0649999999999995;\n\tout_msg.x_coefs[1].spline[1] = -15.510000000000002;\n\tout_msg.x_coefs[1].spline[2] = 10.205;\n\tout_msg.x_coefs[1].spline[3] = 0.42;\n\tout_msg.x_coefs[1].spline[4] = 0.10999999999999999;\n\tout_msg.x_coefs[1].spline[5] = 0.18;\n\n\tout_msg.y_coefs[1].spline[0] = 1.9250000000000025;\n\tout_msg.y_coefs[1].spline[1] = -5.375;\n\tout_msg.y_coefs[1].spline[2] = 4.505000000000003;\n\tout_msg.y_coefs[1].spline[3] = -0.8149999999999998;\n\tout_msg.y_coefs[1].spline[4] = 2.4299999999999997;\n\tout_msg.y_coefs[1].spline[5] = 0.45;\n\n\tout_msg.orient_coefs[1].spline[0] = 0.0;\n\tout_msg.orient_coefs[1].spline[1] = 0.0;\n\tout_msg.orient_coefs[1].spline[2] = 0.0;\n\tout_msg.orient_coefs[1].spline[3] = 0.0;\n\tout_msg.orient_coefs[1].spline[4] = 0.0;\n\tout_msg.orient_coefs[1].spline[5] = -3.14159;\n\tout_msg.end_points[1] = 1.0; // change me to 4 to match end time in yaml and break point_gen\n#endif\n\tbase_trajectory::GenerateSpline::Response tmp_msg;\n\tconst std::vector<std::string> jointNames = {\"x_linear_joint\", \"y_linear_joint\", \"z_rotation_joint\"};\n\ttrajectoryToSplineResponseMsg(tmp_msg, trajectory, jointNames);\n\twriteMatlabCode(tmp_msg);\n\tmessageFilter.disable();\n\tfflush(stdout);\n\n\tif (!RPROP(trajectory,\n\t\t\t\tmsg.points,\n\t\t\t\tpathLimitDistance, // limit of path excursion from straight line b/t waypoints\n\t\t\t\tmaxVel, // max overall velocity\n\t\t\t\tmaxLinearAcc, // max allowed acceleration\n\t\t\t\twheelRadius, // wheel radius\n\t\t\t\tmaxCentAcc)) // max allowed centripetal acceleration\n\t{\n\t\tROS_ERROR(\"base_trajectory_node : RPROP() returned false\");\n\t\treturn false;\n\t}\n\n\tmessageFilter.enable();\n\ttrajectoryToSplineResponseMsg(out_msg, trajectory, jointNames);\n\twriteMatlabCode(out_msg);\n\tfflush(stdout);\n\tROS_INFO_STREAM(\"base_trajectory_callback took \" <<\n\t\t\t(ros::Time::now() - startTime).toSec() <<\n\t\t\t\" seconds\");\n\treturn true;\n}\n\nint main(int argc, char **argv)\n{\n\tros::init(argc, argv, \"base_trajectory\");\n\tros::NodeHandle nh;\n\n\tdouble loop_hz;\n\n\tnh.param<double>(\"loop_hz\", loop_hz, 100.);\n\tperiod = ros::Duration(1.0 / loop_hz);\n\n\tddynamic_reconfigure::DDynamicReconfigure ddr;\n\tnh.param(\"seg_length_epslion\", segLengthEpsilon, 1.0e-4);\n    ddr.registerVariable<double>(\"seg_length_epsilon\", &segLengthEpsilon, \"maximum error for each segment when parameterizing spline arclength\", 0, .1);\n\n\tnh.param(\"dist_between_arc_lengths\", distBetweenArcLengths, 0.03); // 3 cm\n\tnh.param(\"dist_between_arc_lengths_epsilon\", distBetweenArcLengthEpsilon, 0.0025); // 2.5 mm\n\tnh.param(\"mid_time_inflation\", midTimeInflation, 1.25);\n\tddr.registerVariable<double>(\"dist_between_arc_lengths\", &distBetweenArcLengths, \"equal-spaced arc length distance\", 0, 0.5);\n\tddr.registerVariable<double>(\"dist_between_arc_lengths_epsilon\", &distBetweenArcLengthEpsilon, \"error tolerance for dist_between_arc_length\", 0, 0.5);\n\tddr.registerVariable<double>(\"mid_time_inflation\", &midTimeInflation, \"multiplier to prev distance for picking midpoint of next distance searched in arc length subdivision\", 0, 3);\n\tnh.param(\"path_dist_between_arc_lengths\", pathDistBetweenArcLengths, 0.30);\n\tnh.param(\"path_dist_between_arc_lengths_epsilon\", pathDistBetweenArcLengthsEpsilon, 0.01);\n\tddr.registerVariable<double>(\"path_dist_between_arc_lengths\", &pathDistBetweenArcLengths, \"spacing of waypoints along final generated path\", 0, 2);\n\tddr.registerVariable<double>(\"path_dist_between_arc_lengths_epsilon\", &pathDistBetweenArcLengthsEpsilon, \"error tolerance for final path waypoint spacing\", 0, 2);\n\n\tnh.param(\"initial_delta_cost_epsilon\", initialDeltaCostEpsilon, 0.05);\n\tnh.param(\"min_delta_cost_epsilon\", minDeltaCostEpsilon, 0.005);\n\tddr.registerVariable<double>(\"initial_delta_cost_epsilon\", &initialDeltaCostEpsilon, \"RPROP initial deltaCost value\", 0, 1);\n\tddr.registerVariable<double>(\"min_delta_cost_epsilon\", &minDeltaCostEpsilon, \"RPROP minimum deltaCost value\", 0, 1);\n\tnh.param(\"initial_dparam\", initialDParam, 0.05);\n\tddr.registerVariable<double>(\"initial_dparam\", &initialDParam, \"RPROP initial optimization value change\", 0, 2);\n\n\tnh.param(\"path_distance_limit\", pathLimitDistance, 0.2);\n\tnh.param(\"max_vel\", maxVel, 4.5);\n\tnh.param(\"max_linear_acc\", maxLinearAcc, 2.5);\n\tnh.param(\"wheel_radius\", wheelRadius, 0.3682);\n\tnh.param(\"max_cent_acc\", maxCentAcc, 3.5);\n\n\tddr.registerVariable<double>(\"path_distance_limit\", &pathLimitDistance, \"how far robot can diverge from straight-line path between waypoints\", 0, 2);\n\tddr.registerVariable<double>(\"max_vel\", &maxVel, \"max translational velocity\", 0, 20);\n\tddr.registerVariable<double>(\"max_linear_acc\", &maxLinearAcc, \"max linear acceleration\", 0, 10);\n\tddr.registerVariable<double>(\"wheel_radius\", &wheelRadius, \"robot's wheel radius\", 0, 2);\n\tddr.registerVariable<double>(\"max_cent_acc\", &maxCentAcc, \"max centrepital acceleration\", 0, 10);\n    ddr.publishServicesTopics();\n\tros::ServiceServer service = nh.advertiseService(\"base_trajectory/spline_gen\", callback);\n\n\tros::spin();\n}\n", "meta": {"hexsha": "61d83edfa1175f126911f4df1237d5859cc49692", "size": 56185, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "zebROS_ws/src/base_trajectory/src/base_trajectory.cpp", "max_stars_repo_name": "FRC900/2019Offseason", "max_stars_repo_head_hexsha": "bf9559fd7eb19474f9965c4e3d66dd8f46840d0b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-05-25T16:03:59.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-09T10:52:09.000Z", "max_issues_repo_path": "zebROS_ws/src/base_trajectory/src/base_trajectory.cpp", "max_issues_repo_name": "FRC900/2019Offseason", "max_issues_repo_head_hexsha": "bf9559fd7eb19474f9965c4e3d66dd8f46840d0b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-01-04T15:07:45.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-04T15:07:45.000Z", "max_forks_repo_path": "zebROS_ws/src/base_trajectory/src/base_trajectory.cpp", "max_forks_repo_name": "FRC900/2019Offseason", "max_forks_repo_head_hexsha": "bf9559fd7eb19474f9965c4e3d66dd8f46840d0b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-01-01T17:53:23.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-01T17:53:23.000Z", "avg_line_length": 37.5568181818, "max_line_length": 235, "alphanum_fraction": 0.6951855477, "num_tokens": 15997, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.4798921374025703}}
{"text": "//=======================================================================\n// Copyright 2001 Jeremy G. Siek, Andrew Lumsdaine, Lie-Quan Lee, \n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n#include <boost/config.hpp>\n#include <iostream>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/prim_minimum_spanning_tree.hpp>\n\nint\nmain()\n{\n  using namespace boost;\n  typedef adjacency_list < vecS, vecS, undirectedS,\n    property<vertex_distance_t, int>, property < edge_weight_t, int > > Graph;\n  typedef std::pair < int, int >E;\n  const int num_nodes = 5;\n  E edges[] = { E(0, 2), E(1, 3), E(1, 4), E(2, 1), E(2, 3),\n    E(3, 4), E(4, 0)\n  };\n  int weights[] = { 1, 1, 2, 7, 3, 1, 1 };\n#if defined(BOOST_MSVC) && BOOST_MSVC <= 1300\n  Graph g(num_nodes);\n  property_map<Graph, edge_weight_t>::type weightmap = get(edge_weight, g); \n  for (std::size_t j = 0; j < sizeof(edges) / sizeof(E); ++j) {\n    graph_traits<Graph>::edge_descriptor e; bool inserted;\n    boost::tie(e, inserted) = add_edge(edges[j].first, edges[j].second, g);\n    weightmap[e] = weights[j];\n  }\n#else\n  Graph g(edges, edges + sizeof(edges) / sizeof(E), weights, num_nodes);\n  property_map<Graph, edge_weight_t>::type weightmap = get(edge_weight, g);\n#endif\n  std::vector < graph_traits < Graph >::vertex_descriptor >\n    p(num_vertices(g));\n\n#if defined(BOOST_MSVC) && BOOST_MSVC <= 1300\n  property_map<Graph, vertex_distance_t>::type distance = get(vertex_distance, g);\n  property_map<Graph, vertex_index_t>::type indexmap = get(vertex_index, g);\n  prim_minimum_spanning_tree\n    (g, *vertices(g).first, &p[0], distance, weightmap, indexmap, \n     default_dijkstra_visitor());\n#else\n  prim_minimum_spanning_tree(g, &p[0]);\n#endif\n\n  for (std::size_t i = 0; i != p.size(); ++i)\n    if (p[i] != i)\n      std::cout << \"parent[\" << i << \"] = \" << p[i] << std::endl;\n    else\n      std::cout << \"parent[\" << i << \"] = no parent\" << std::endl;\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "ba44aa9b1818f5be994278673bbaca1c30d32bc1", "size": 2129, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/graph/example/prim-example.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2016-03-04T15:44:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-31T11:06:25.000Z", "max_issues_repo_path": "boost/libs/graph/example/prim-example.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 49.0, "max_issues_repo_issues_event_min_datetime": "2016-02-29T17:59:52.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-05T04:59:26.000Z", "max_forks_repo_path": "boost/libs/graph/example/prim-example.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-09-09T02:38:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-30T00:24:24.000Z", "avg_line_length": 36.7068965517, "max_line_length": 82, "alphanum_fraction": 0.6115547205, "num_tokens": 623, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.4798921322629804}}
{"text": "//calc_error.cpp\n/*\n * Calculates error of reconstruction from\n * shadow and re-shadow\n * (C) 2006 olegabr. All rights reserved.\n*/\n\n#include <Magick++.h>\n\n#include <iostream>\nusing std::cout; using std::endl;\n\n#include <cmath>\nusing std::sqrt;\n\n#include <boost/lexical_cast.hpp>\nusing boost::lexical_cast;\n\n#include <tomo3d.h>\n#include <object3d.h>\n#include <shadow2d.h>\n#include <filtered_shadow2d.h>\n\nnamespace {\n\tvoid usage()\n\t{\n\t\tstd::cout << \"calc_error start_angle end_angle increment src_images_directory reproj_images_directory\\n\";\n\t}\n\n\tvoid scaleShadow(shadow2d& shReproj, double dK)\n\t{\n\t\tshadow2d::iterator iterSh = shReproj.begin();\n\t\tshadow2d::iterator iterShEnd = shReproj.end();\n\t\tfor (; iterSh != iterShEnd; ++iterSh) {\n\t\t\tprojection2d::iterator iterPr2d = iterSh->begin();\n\t\t\tprojection2d::iterator iterPr2dEnd = iterSh->end();\n\t\t\tfor (; iterPr2d != iterPr2dEnd; ++iterPr2d) {\n\t\t\t\tprojection1d::iterator iterPr1d = iterPr2d->begin();\n\t\t\t\tprojection1d::iterator iterPr1dEnd = iterPr2d->end();\n\t\t\t\tfor (; iterPr1d != iterPr1dEnd; ++iterPr1d) {\n\t\t\t\t\t*iterPr1d *= dK;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tdouble calc_error(shadow2d& shSrc, shadow2d& shReproj)\n\t{\n\t\tshadow2d shTemp(shSrc.get_angle_series(), shSrc.get_size());\n\n\t\tcout << \"Calculate experimental projection norm...\\n\";\n\t\tfiltered_shadow2d shFiltered(shSrc, shTemp);\n\t\tdouble dSrcNorm2 = shSrc * shFiltered;\n\n\t\tcout << \"Calculate re-projection norm...\\n\";\n\t\tfiltered_shadow2d shReprojFiltered(shReproj, shTemp);\n\t\tdouble dReprojNorm2 = shReproj * shReprojFiltered;\n\n\t\tdouble dK = std::sqrt(dSrcNorm2 / dReprojNorm2);\n\n\t\tcout << \"Scale shadow...\\n\";\n\t\tscaleShadow(shReproj, dK);\n\n\t\tcout << \"Calculate difference...\\n\";\n\t\tshadow2d& shDiff = shReproj;\n\t\tshDiff.assign_difference(shSrc);\n\n\t\tcout << \"Filter difference...\\n\";\n\t\tfiltered_shadow2d shDiffFilt(shDiff, shTemp);\n\n\t\treturn\n\t\t\t100 * std::sqrt((shDiff * shDiffFilt) / dSrcNorm2);\n\t}\n}\n\nint main(int argc, char* argv[])\n{\n\tif (argc < 6)\n\t{\n\t\tusage();\n\t\treturn 0;\n\t}\n\ttry {\n\t\tMagick::InitializeMagick(argv[0]);\n\n\t\tangle_t\n\t\t\tstart    (lexical_cast<double>(argv[1])),\n\t\t\tend      (lexical_cast<double>(argv[2])),\n\t\t\tincrement(lexical_cast<double>(argv[3]));\n\t\tangle_series_t series(start, end, increment);\n\n\t\tshadow2d exp_shadow(series);\n\t\tcout << \"Loading projections...\" << endl;\n\t\texp_shadow.load_from_image(argv[4]);\n\n\t\tshadow2d re_shadow(series);\n\t\tcout << \"Loading projections...\" << endl;\n\t\tre_shadow.load_from_image(argv[5]);\n\n\t\tif (exp_shadow.get_size() != re_shadow.get_size()) {\n\t\t\tcout\n\t\t\t\t<< \"Experimental shadow's size '\" << exp_shadow.get_size()\n\t\t\t\t<< \"' is not equal to reprojected shadow's size '\" << re_shadow.get_size()\n\t\t\t\t<< \"'\\n\";\n\t\t\treturn 1;\n\t\t}\n\n\t\tif (exp_shadow.get_proj_num() != re_shadow.get_proj_num()) {\n\t\t\tcout\n\t\t\t\t<< \"Experimental shadow's projections number '\" << exp_shadow.get_proj_num()\n\t\t\t\t<< \"' is not equal to reprojected shadow's projections number '\" << re_shadow.get_proj_num()\n\t\t\t\t<< \"'\\n\";\n\t\t\treturn 1;\n\t\t}\n\n\t\tcout << \"Calculate error...\\n\";\n\t\tdouble dError = calc_error(exp_shadow, re_shadow);\n\n\t\tcout << \"The error is '\" << dError << \"%'.\" << endl;\n\t}\n\tcatch (boost::bad_lexical_cast &ex) {\n\t\tcout << ex.what() << endl;\n\t}\n\tcatch (Magick::Exception &ex) {\n\t\tcout << ex.what() << endl;\n\t}\n\tcatch (std::exception &e) {\n\t\tcout << e.what() << endl;\n\t}\n\tcatch (...) {\n\t\tcout << \"Unknown exception occured.\" << endl;\n\t}\n\n\treturn 0;\n}\n", "meta": {"hexsha": "849b3b3b336212f77a46f4feaeb771657f0d09a7", "size": 3386, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "calc_error/calc_error.cpp", "max_stars_repo_name": "olegabr/tomo3d", "max_stars_repo_head_hexsha": "36ffca69aba8556170ec7330271eb58ebaf7459b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2016-01-07T12:27:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-03T06:58:42.000Z", "max_issues_repo_path": "calc_error/calc_error.cpp", "max_issues_repo_name": "olegabr/tomo3d", "max_issues_repo_head_hexsha": "36ffca69aba8556170ec7330271eb58ebaf7459b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "calc_error/calc_error.cpp", "max_forks_repo_name": "olegabr/tomo3d", "max_forks_repo_head_hexsha": "36ffca69aba8556170ec7330271eb58ebaf7459b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-10T10:22:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-10T10:22:13.000Z", "avg_line_length": 24.8970588235, "max_line_length": 107, "alphanum_fraction": 0.6650915535, "num_tokens": 1009, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.4798921271233903}}
{"text": "#ifndef LBP_CSLDP_HPP\n#define LBP_CSLDP_HPP\n\n#include <lbp/defs.hpp>\n#include <lbp/utils.hpp>\n#include <lbp/detail/neighborhoods.hpp>\n#include <lbp/detail/sampling.hpp>\n\n#include <opencv2/core.hpp>\n\n#include <boost/hana/fold.hpp>\n#include <boost/hana/tuple.hpp>\n\n#include <boost/integer.hpp>\n\n//\n// @inproceedings{xue2011hybrid,\n//   title={Hybrid center-symmetric local pattern for dynamic background subtraction},\n//   author={Xue, Gengjian and Song, Li and Sun, Jun and Wu, Meng},\n//   booktitle={Multimedia and Expo (ICME), 2011 IEEE International Conference on},\n//   pages={1--6},\n//   year={2011},\n//   organization={IEEE}\n//}\n//\n\nnamespace lbp {\nnamespace csldp_detail {\n\ntemplate< typename T >\nauto csldp = [](auto N, auto S) {\n    return [=](const cv::Mat& src, size_t i, size_t j, const T& e) {\n        using namespace cv;\n        using namespace hana::literals;\n\n        const auto c = saturate_cast< T > (S (src, i, j) + e);\n\n        return hana::fold (\n            N, 0, [&, shift = 0](auto accum, auto x) mutable {\n                const auto a = S (src, i + x [0_c], j + x [1_c]);\n                const auto b = S (src, i - x [0_c], j - x [1_c]);\n                return accum | (((a >= c) ^ (b >= c)) << shift++);\n            });\n    };\n};\n\n} // namespace csldp_detail\n\ntemplate< typename T, size_t R, size_t P >\nauto csldp = [](const cv::Mat& src, const T& epsilon = T { }) {\n    LBP_STATIC_ASSERT_MSG (0 == (P % 2), \"odd-sized neighborhood\");\n\n    using value_type = typename boost::uint_t< P/2 >::least;\n\n    cv::Mat dst (src.size (), opencv_type< value_type >, cv::Scalar (0));\n\n    auto op = csldp_detail::csldp< T > (\n        detail::semicircular_neighborhood< R, P >,\n        detail::bilinear_sampler< T >);\n\n#pragma omp parallel for\n    for (size_t i = R; i < src.rows - R - 1; ++i) {\n        for (size_t j = R; j < src.cols - R - 1; ++j) {\n            dst.at< value_type > (i, j) = op (src, i, j, epsilon);\n        }\n    }\n\n    return dst;\n};\n\n} // namespace lbp\n\n#endif // LBP_CSLDP_HPP\n", "meta": {"hexsha": "72e3268c7f35ece1ce358202d41ce2b7e439952d", "size": 2012, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/lbp/csldp.hpp", "max_stars_repo_name": "thinkoid/lbp", "max_stars_repo_head_hexsha": "9ce3bc41a8961cf0304c5d271cd882b4cae78cb2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-11-02T12:45:36.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-25T03:51:09.000Z", "max_issues_repo_path": "include/lbp/csldp.hpp", "max_issues_repo_name": "thinkoid/lbp", "max_issues_repo_head_hexsha": "9ce3bc41a8961cf0304c5d271cd882b4cae78cb2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/lbp/csldp.hpp", "max_forks_repo_name": "thinkoid/lbp", "max_forks_repo_head_hexsha": "9ce3bc41a8961cf0304c5d271cd882b4cae78cb2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-08-02T09:10:08.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-02T09:19:34.000Z", "avg_line_length": 27.1891891892, "max_line_length": 86, "alphanum_fraction": 0.5864811133, "num_tokens": 608, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.4798921271233903}}
{"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\u00e4nkt), 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 Cornelius Steinhardt\n\n#include <cmath>\n\n// #include <boost/test/minimal.hpp>\n#include <boost/numeric/mtl/mtl.hpp>\n#include <boost/numeric/itl/itl.hpp>\n#include <boost/numeric/mtl/operation/trans.hpp>\n\ntemplate <typename Matrix>\nvoid test1(Matrix& m, double tau)\n{\n    mtl::mat::inserter<Matrix> ins(m);\n    size_t nrows=num_rows(m);\n    double val;\n    for (size_t r= 0; r < nrows; ++r) \n\tfor (size_t c= 0; c < nrows; ++c) \n\t    if (r == c)\n\t\tins(r,c) << 1.;\n\t    else {\n\t\tval= 2.*(static_cast<double>(rand())/RAND_MAX - 0.5);\n\t\tif (val < tau)\n\t\t    ins(r,c) << val;\n\t    }\t\t\t\n}\n\n\nint main(int, char**)\n{\n\n  const int N = 10; // Original from Jan had 2000\n  const int Niter = 100*N;\n\n  using itl::pc::identity; using itl::pc::ilu_0; using itl::pc::ic_0; using itl::pc::diagonal;\n  //typedef mtl::dense2D<double> matrix_type;\n  typedef mtl::compressed2D<double> matrix_type;\n  matrix_type                   A(N, N);\n  mtl::dense_vector<double>     b(N*N, 1), x(N*N), r(x);\n  laplacian_setup(A, N, N);\n  identity<matrix_type>         Ident(A);\n  ic_0<matrix_type>             ic(A);\n  ilu_0<matrix_type>            ilu(A);\n  diagonal<matrix_type>         diag(A);\n\n  //test1(A,0.194);\n  //std::cout<< \"A=\" << A << \"\\n\";\n  //std::cout << \"A has \" << A.nnz() << \" non-zero entries\" << std::endl;\n\n\n  std::cout << \"Non-preconditioned tfqmr\" << std::endl;\n  std::cout << \"Won't convergence (for large examples)!\" << std::endl;\n  x= 0.5;\n  itl::cyclic_iteration<double> iter_1(b, Niter, 1.e-8), iter_2(b, Niter, 1.e-8), iter_3(b, Niter, 1.e-8), iter_4(b, Niter, 1.e-8);\n\n  std::cout<< \"--------no preconditioning------------\" << std::endl;\n  tfqmr(A, x, b, Ident, Ident, iter_1);\n  r= A*x-b;\n  //std::cout << \"A*x-b=\" << r << \"\\n\";\n  if (two_norm(r) > 0.000001) throw \"tfqmr don't converges\";\n  x=0.5;\n  std::cout<< \"--------ilu preconditioning------------\" << std::endl;\n  tfqmr(A, x, b, ilu, ilu, iter_2);\n  r= A*x-b;\n  //std::cout << \"A*x-b=\" << r << \"\\n\";\n  if (two_norm(r) > 0.000001) throw \"tfqmr don't converges with ilu preconditioning\";\n  x=0.5;\n  std::cout<< \"--------ic_0 preconditioning------------\" << std::endl;\n  tfqmr(A, x, b, ic, ic, iter_3);\n  r= A*x-b;\n  //std::cout << \"A*x-b=\" << r << \"\\n\";\n  if (two_norm(r) > 0.000001) throw \"tfqmr don't converges with ic_0 preconditioning\";\n  x=10.5;\n  std::cout<< \"--------diag preconditioning------------\" << std::endl;\n  tfqmr(A, x, b, diag, diag, iter_4);\n  r= A*x-b;\n  //std::cout << \"A*x-b=\" << r << \"\\n\";\n  if (two_norm(r) > 0.000001) throw \"tfqmr don't converges with diagonal preconditioner\";\n\n  return 0;\n}\n\n\n\n\n", "meta": {"hexsha": "84a50b014336235fb44b6aa4a35e080fdb2fbd97", "size": 3027, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/itl/test/tfqmr_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/itl/test/tfqmr_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/itl/test/tfqmr_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": 31.206185567, "max_line_length": 131, "alphanum_fraction": 0.5877106046, "num_tokens": 1034, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.749087201911703, "lm_q2_score": 0.6406358479787609, "lm_q1q2_score": 0.47989211480674115}}
{"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#define BOOST_TEST_MODULE eigenvectors\n\n#include <mfmg/dealii/amge_host.hpp>\n#include <mfmg/dealii/dealii_mesh_evaluator.hpp>\n\n#include <deal.II/distributed/tria.h>\n#include <deal.II/dofs/dof_accessor.h>\n#include <deal.II/fe/fe_q.h>\n#include <deal.II/grid/grid_generator.h>\n#include <deal.II/lac/trilinos_vector.h>\n\n#include <algorithm>\n\n#include \"main.cc\"\n\nnamespace tt = boost::test_tools;\nnamespace ut = boost::unit_test;\n\ntemplate <int dim>\nclass DiagonalTestMeshEvaluator : public mfmg::DealIIMeshEvaluator<dim>\n{\npublic:\n  DiagonalTestMeshEvaluator(dealii::DoFHandler<dim> &dof_handler,\n                            dealii::AffineConstraints<double> &constraints)\n      : mfmg::DealIIMeshEvaluator<dim>(dof_handler, constraints)\n  {\n  }\n\n  virtual ~DiagonalTestMeshEvaluator() override = default;\n\n  // Diagonal matrices. We only need local evaluate function.\n  void evaluate_agglomerate(\n      dealii::DoFHandler<dim> &dof_handler,\n      dealii::AffineConstraints<double> &constraints,\n      dealii::SparsityPattern &system_sparsity_pattern,\n      dealii::SparseMatrix<double> &system_matrix) const override final\n  {\n    dealii::FE_Q<2> fe(1);\n    dof_handler.distribute_dofs(fe);\n\n    constraints.clear();\n\n    unsigned int const size = dof_handler.n_dofs();\n    std::vector<std::vector<unsigned int>> column_indices(\n        size, std::vector<unsigned int>(1));\n    for (unsigned int i = 0; i < size; ++i)\n      column_indices[i][0] = i;\n    system_sparsity_pattern.copy_from(size, size, column_indices.begin(),\n                                      column_indices.end());\n    system_matrix.reinit(system_sparsity_pattern);\n    for (unsigned int i = 0; i < size; ++i)\n      system_matrix.diag_element(i) = static_cast<double>(i + 1);\n  }\n\n  void\n  evaluate_global(dealii::DoFHandler<dim> &,\n                  dealii::AffineConstraints<double> &,\n                  dealii::TrilinosWrappers::SparseMatrix &) const override final\n  {\n  }\n};\n\nBOOST_AUTO_TEST_CASE(diagonal, *ut::tolerance(1e-12))\n{\n  int const dim = 2;\n  using Vector = dealii::LinearAlgebra::distributed::Vector<double>;\n  using MeshEvaluator = mfmg::DealIIMeshEvaluator<2>;\n\n  dealii::parallel::distributed::Triangulation<2> triangulation(MPI_COMM_WORLD);\n  dealii::GridGenerator::hyper_cube(triangulation);\n  triangulation.refine_global(3);\n  dealii::FE_Q<2> fe(1);\n  dealii::DoFHandler<2> dof_handler(triangulation);\n  dof_handler.distribute_dofs(fe);\n  mfmg::AMGe_host<2, MeshEvaluator, Vector> amge(MPI_COMM_WORLD, dof_handler);\n\n  unsigned int const n_eigenvectors = 5;\n  std::map<typename dealii::Triangulation<2>::active_cell_iterator,\n           typename dealii::DoFHandler<2>::active_cell_iterator>\n      patch_to_global_map;\n  for (auto cell : dof_handler.active_cell_iterators())\n    patch_to_global_map[cell] = cell;\n\n  dealii::AffineConstraints<double> constraints;\n  DiagonalTestMeshEvaluator<dim> evaluator(dof_handler, constraints);\n  std::vector<std::complex<double>> eigenvalues;\n  std::vector<dealii::Vector<double>> eigenvectors;\n  std::vector<double> diag_elements;\n  std::vector<dealii::types::global_dof_index> dof_indices_map;\n  std::tie(eigenvalues, eigenvectors, diag_elements, dof_indices_map) =\n      amge.compute_local_eigenvectors(n_eigenvectors, 1e-13, triangulation,\n                                      patch_to_global_map, evaluator);\n\n  std::vector<dealii::types::global_dof_index> ref_dof_indices_map(\n      dof_handler.n_dofs());\n  std::iota(ref_dof_indices_map.begin(), ref_dof_indices_map.end(), 0);\n  BOOST_TEST(dof_indices_map == ref_dof_indices_map, tt::per_element());\n\n  unsigned int const eigenvector_size = eigenvectors[0].size();\n  std::vector<std::complex<double>> ref_eigenvalues(n_eigenvectors);\n  std::vector<dealii::Vector<double>> ref_eigenvectors(\n      n_eigenvectors, dealii::Vector<double>(eigenvector_size));\n  for (unsigned int i = 0; i < n_eigenvectors; ++i)\n  {\n    ref_eigenvalues[i] = static_cast<double>(i + 1);\n    ref_eigenvectors[i][i] = 1.;\n  }\n\n  for (unsigned int i = 0; i < n_eigenvectors; ++i)\n  {\n    BOOST_TEST(eigenvalues[i].real() == ref_eigenvalues[i].real());\n    BOOST_TEST(eigenvalues[i].imag() == ref_eigenvalues[i].imag());\n    for (unsigned int j = 0; j < eigenvector_size; ++j)\n      BOOST_TEST(std::abs(eigenvectors[i][j]) == ref_eigenvectors[i][j]);\n  }\n}\n\ntemplate <int dim>\nclass ConstrainedDiagonalTestMeshEvaluator\n    : public mfmg::DealIIMeshEvaluator<dim>\n{\npublic:\n  ConstrainedDiagonalTestMeshEvaluator(\n      dealii::DoFHandler<dim> &dof_handler,\n      dealii::AffineConstraints<double> &constraints)\n      : mfmg::DealIIMeshEvaluator<dim>(dof_handler, constraints)\n  {\n  }\n\n  virtual ~ConstrainedDiagonalTestMeshEvaluator() override = default;\n\n  // Diagonal matrices. We only need local evaluate function.\n  void evaluate_agglomerate(\n      dealii::DoFHandler<dim> &dof_handler,\n      dealii::AffineConstraints<double> &constraints,\n      dealii::SparsityPattern &system_sparsity_pattern,\n      dealii::SparseMatrix<double> &system_matrix) const override final\n  {\n    dealii::FE_Q<2> fe(1);\n    dof_handler.distribute_dofs(fe);\n\n    constraints.clear();\n    constraints.add_line(0);\n    constraints.close();\n\n    unsigned int const size = dof_handler.n_dofs();\n    std::vector<std::vector<unsigned int>> column_indices(\n        size, std::vector<unsigned int>(1));\n    for (unsigned int i = 0; i < size; ++i)\n      column_indices[i][0] = i;\n    system_sparsity_pattern.copy_from(size, size, column_indices.begin(),\n                                      column_indices.end());\n    system_matrix.reinit(system_sparsity_pattern);\n    for (unsigned int i = 0; i < size; ++i)\n      system_matrix.diag_element(i) = static_cast<double>(i + 1);\n  }\n\n  void\n  evaluate_global(dealii::DoFHandler<dim> &,\n                  dealii::AffineConstraints<double> &,\n                  dealii::TrilinosWrappers::SparseMatrix &) const override final\n  {\n  }\n};\n\nBOOST_AUTO_TEST_CASE(diagonal_constraint, *ut::tolerance(1e-12))\n{\n  int const dim = 2;\n  using Vector = dealii::LinearAlgebra::distributed::Vector<double>;\n  using MeshEvaluator = mfmg::DealIIMeshEvaluator<2>;\n\n  dealii::parallel::distributed::Triangulation<2> triangulation(MPI_COMM_WORLD);\n  dealii::GridGenerator::hyper_cube(triangulation);\n  triangulation.refine_global(3);\n  dealii::FE_Q<2> fe(1);\n  dealii::DoFHandler<2> dof_handler(triangulation);\n  dof_handler.distribute_dofs(fe);\n  mfmg::AMGe_host<2, MeshEvaluator, Vector> amge(MPI_COMM_WORLD, dof_handler);\n\n  unsigned int const n_eigenvectors = 5;\n  std::map<typename dealii::Triangulation<2>::active_cell_iterator,\n           typename dealii::DoFHandler<2>::active_cell_iterator>\n      patch_to_global_map;\n  for (auto cell : dof_handler.active_cell_iterators())\n    patch_to_global_map[cell] = cell;\n\n  dealii::AffineConstraints<double> constraints;\n  ConstrainedDiagonalTestMeshEvaluator<dim> evaluator(dof_handler, constraints);\n  std::vector<std::complex<double>> eigenvalues;\n  std::vector<dealii::Vector<double>> eigenvectors;\n  std::vector<double> diag_elements;\n  std::vector<dealii::types::global_dof_index> dof_indices_map;\n  std::tie(eigenvalues, eigenvectors, diag_elements, dof_indices_map) =\n      amge.compute_local_eigenvectors(n_eigenvectors, 1e-13, triangulation,\n                                      patch_to_global_map, evaluator);\n\n  std::vector<dealii::types::global_dof_index> ref_dof_indices_map(\n      dof_handler.n_dofs());\n  std::iota(ref_dof_indices_map.begin(), ref_dof_indices_map.end(), 0);\n  BOOST_TEST(dof_indices_map == ref_dof_indices_map, tt::per_element());\n\n  unsigned int const eigenvector_size = eigenvectors[0].size();\n  std::vector<std::complex<double>> ref_eigenvalues(n_eigenvectors);\n  std::vector<dealii::Vector<double>> ref_eigenvectors(\n      n_eigenvectors, dealii::Vector<double>(eigenvector_size));\n  for (unsigned int i = 0; i < n_eigenvectors; ++i)\n  {\n    ref_eigenvalues[i] = static_cast<double>(i + 2);\n    ref_eigenvectors[i][i + 1] = 1.;\n  }\n\n  for (unsigned int i = 0; i < n_eigenvectors; ++i)\n  {\n    BOOST_TEST(eigenvalues[i].real() == ref_eigenvalues[i].real());\n    BOOST_TEST(eigenvalues[i].imag() == ref_eigenvalues[i].imag());\n    for (unsigned int j = 0; j < eigenvector_size; ++j)\n      BOOST_TEST(std::abs(eigenvectors[i][j]) == ref_eigenvectors[i][j]);\n  }\n}\n", "meta": {"hexsha": "86e133ce81853032cd8e3677c1d8f870ca6680b1", "size": 9072, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tests/test_eigenvectors.cc", "max_stars_repo_name": "dalg24/mfmg", "max_stars_repo_head_hexsha": "1bb940df4acc8d1833321def60850b32f51c5f27", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/test_eigenvectors.cc", "max_issues_repo_name": "dalg24/mfmg", "max_issues_repo_head_hexsha": "1bb940df4acc8d1833321def60850b32f51c5f27", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/test_eigenvectors.cc", "max_forks_repo_name": "dalg24/mfmg", "max_forks_repo_head_hexsha": "1bb940df4acc8d1833321def60850b32f51c5f27", "max_forks_repo_licenses": ["BSD-3-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.2727272727, "max_line_length": 80, "alphanum_fraction": 0.6725088183, "num_tokens": 2338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.4798082226594431}}
{"text": "#ifdef _WIN32\n#pragma warning(disable:4503)\n#pragma warning(push)\n#pragma warning(disable:4996 4251 4275 4800)\n#endif\n#include <opencv2/imgproc.hpp>\n#include <vector>\n#include <boost/lexical_cast.hpp>\n#ifdef _WIN32\n#pragma warning(pop)\n#endif\n\n#include \"Block.h\"\n#include \"ParamValidator.h\"\n#include \"OpenCV_filter.h\"\n#include \"Convertor.h\"\nusing namespace charliesoft;\nusing std::vector;\nusing boost::lexical_cast;\nusing std::string;\nusing cv::Mat;\n\nnamespace charliesoft\n{\n  BLOCK_BEGIN_INSTANTIATION(DistanceTransformBlock);\n  //You can add methods, re implement needed functions... \n  BLOCK_END_INSTANTIATION(DistanceTransformBlock, AlgoType::mathOperator, BLOCK__DISTANCE_NAME);\n\n  BEGIN_BLOCK_INPUT_PARAMS(DistanceTransformBlock);\n  //Add parameters, with following parameters:\n  //default visibility, type of parameter, name (key of internationalizor), helper...\n  ADD_PARAMETER(toBeLinked, Matrix, \"BLOCK__DISTANCE_IN_IMAGE\", \"BLOCK__DISTANCE_IN_IMAGE_HELP\");\n  ADD_PARAMETER_FULL(userConstant, ListBox, \"BLOCK__DISTANCE_IN_DISTANCETYPE\", \"BLOCK__DISTANCE_IN_DISTANCETYPE_HELP\", 2);\n  ADD_PARAMETER_FULL(userConstant, Boolean, \"BLOCK__BINARIZE_IN_INVERSE\", \"BLOCK__BINARIZE_IN_INVERSE_HELP\", false);\n  END_BLOCK_PARAMS();\n\n  BEGIN_BLOCK_OUTPUT_PARAMS(DistanceTransformBlock);\n  ADD_PARAMETER(toBeLinked, AnyType, \"BLOCK__DISTANCE_OUT_IMAGE\", \"BLOCK__DISTANCE_OUT_IMAGE_HELP\");//output type is defined by inputs\n  END_BLOCK_PARAMS();\n\n  BEGIN_BLOCK_SUBPARAMS_DEF(DistanceTransformBlock);\n  END_BLOCK_PARAMS();\n\n  DistanceTransformBlock::DistanceTransformBlock() :Block(\"BLOCK__DISTANCE_NAME\", true){\n    _myInputs[\"BLOCK__DISTANCE_IN_IMAGE\"].addValidator({ new ValNeeded() });\n  };\n\n  bool DistanceTransformBlock::run(bool oneShot){\n    if (_myInputs[\"BLOCK__DISTANCE_IN_IMAGE\"].isDefaultValue())\n      return false;\n    \n    cv::Mat mat = _myInputs[\"BLOCK__DISTANCE_IN_IMAGE\"].get<cv::Mat>();\n    if (!mat.empty())\n    {\n      int choice = _myInputs[\"BLOCK__DISTANCE_IN_DISTANCETYPE\"].get<int>();\n      cv::Mat output = MatrixConvertor::adjustChannels(mat.clone(), 1);\n      normalize(output, output, 0, 255, cv::NORM_MINMAX);\n      if (_myInputs[\"BLOCK__BINARIZE_IN_INVERSE\"].get<bool>())\n        output = 255 - output;\n      int distType = cv::DIST_L2;\n      int mask = cv::DIST_MASK_3;\n      if (choice == 0)\n        distType = cv::DIST_C;\n      else if (choice == 1)\n        distType = cv::DIST_L1;\n      else if (choice == 3)\n      {\n        distType = cv::DIST_L2;\n        mask = cv::DIST_MASK_5;\n      }\n      cv::distanceTransform(output, output, distType, mask);\n\n      _myOutputs[\"BLOCK__DISTANCE_OUT_IMAGE\"] = output;\n    }\n    return !mat.empty();\n  };\n};", "meta": {"hexsha": "f5b54e281dfeff69012850621896aa2a7fb7714c", "size": 2675, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Sources/blocks/DistanceTransform.cpp", "max_stars_repo_name": "Petititi/imGraph", "max_stars_repo_head_hexsha": "068890ffe2f8fa1fb51bc95b8d9296cc79737fac", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-01-12T11:27:45.000Z", "max_stars_repo_stars_event_max_datetime": "2015-03-25T18:24:38.000Z", "max_issues_repo_path": "Sources/blocks/DistanceTransform.cpp", "max_issues_repo_name": "Petititi/imGraph", "max_issues_repo_head_hexsha": "068890ffe2f8fa1fb51bc95b8d9296cc79737fac", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 30.0, "max_issues_repo_issues_event_min_datetime": "2015-01-07T11:59:07.000Z", "max_issues_repo_issues_event_max_datetime": "2015-04-24T13:02:01.000Z", "max_forks_repo_path": "Sources/blocks/DistanceTransform.cpp", "max_forks_repo_name": "Petititi/imGraph", "max_forks_repo_head_hexsha": "068890ffe2f8fa1fb51bc95b8d9296cc79737fac", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-12-20T12:18:18.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-20T12:18:18.000Z", "avg_line_length": 34.7402597403, "max_line_length": 134, "alphanum_fraction": 0.731588785, "num_tokens": 690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702642896702, "lm_q2_score": 0.6619228891883799, "lm_q1q2_score": 0.479808219625363}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2015, Sebastian Schlenkrich\n\n*/\n\n/*! \\file templateprocess.hpp\n    \\brief define interface for general multi-dimensional stochastic process\n               \n*/\n\n\n#ifndef quantlib_templatestochasticprocess_hpp\n#define quantlib_templatestochasticprocess_hpp\n\n#include <vector>\n\n#include <boost/enable_shared_from_this.hpp>\n\n#include <ql/types.hpp>\n#include <ql/errors.hpp>\n\nnamespace QuantLib {\n\n\n    // Declaration of stochastic process class\n    template <class DateType, class PassiveType, class ActiveType>\n    class StochasticProcessT : public boost::enable_shared_from_this< StochasticProcessT<DateType,PassiveType,ActiveType> > {\n    public:\n        // container class definitions\n        typedef std::vector<DateType>                      VecD;\n        typedef std::vector<PassiveType>                   VecP; \n        typedef std::vector<ActiveType>                    VecA;\n        typedef std::vector< std::vector<DateType> >       MatD;\n        typedef std::vector< std::vector<PassiveType> >    MatP;\n        typedef std::vector< std::vector<ActiveType> >     MatA;\n\n        // subset of QL's StochasticProcess interface for X = [ x, y, z, d ] (y row-wise)\n        // with dX = a[t,X(t)] dt + b[t,X(t)] dW\n\n        // dimension of X\n        virtual size_t size() = 0;\n        // stochastic factors (underlying, volatilities and spreads)\n        virtual size_t factors() = 0;\n        // initial values for simulation\n        virtual VecP initialValues() = 0;\n        // a[t,X(t)]\n        virtual VecA drift( const DateType t, const VecA& X) = 0;\n        // b[t,X(t)]\n        virtual MatA diffusion( const DateType t, const VecA& X) = 0;\n\n        // truncate process to its well-defined domain and return true (truncated) or false (not truncated)\n        inline virtual bool truncate( const DateType t, VecA& X ) { return false; } // default do nothing\n\n        // integrate X1 = X0 + drift()*dt + diffusion()*dW*sqrt(dt)\n        // default implementation\n        inline virtual void evolve( const DateType t0, const VecA& X0, const DateType dt, const VecD& dW, VecA& X1 ) {\n            // ensure X1 has size of X0\n            VecA a = drift(t0, X0);\n            MatA b = diffusion(t0, X0);\n            for (size_t i=0; i<X1.size(); ++i) {\n                X1[i] = 0.0;\n                for (size_t j=0; j<dW.size(); ++j) X1[i] += b[i][j]*dW[j];\n                X1[i] = X0[i] + a[i]*dt + X1[i]*sqrt(dt);\n            }\n            truncate( t0+dt, X1 );\n            return;\n        }\n\n        // we set up a common interface such that models can easily be interchanged\n        // the concrete model needs to make sure that it is fit for purpose in a\n        // particular application, i.e. implement required methods.\n\n        // the numeraire in the domestic currency used for discounting future payoffs\n        inline virtual ActiveType numeraire(const DateType t, const VecA& X)                       { QL_FAIL(\"StochasticProcessT: numeraire not implemented\"); return 0; }\n\n        // a zero coupon bond for the model\n        inline virtual ActiveType zeroBond(const DateType t, const DateType T, const VecA& X)      { QL_FAIL(\"StochasticProcessT: zeroBond not implemented\"); return 0; }\n\n        // a domestic/foreign currency zero coupon bond\n        inline virtual ActiveType zeroBond(const DateType t, const DateType T, const VecA& X, const std::string& alias) { QL_FAIL(\"StochasticProcessT: zeroBond with alias not implemented\"); return 0; }\n\n        // an asset with (individual) drift and volatility\n        inline virtual ActiveType asset(const DateType t, const VecA& X, const std::string& alias) { QL_FAIL(\"StochasticProcessT: (multi) asset not implemented\"); return 0; }\n\n        // the short rate over an integration period\n        // this is required for drift calculation in multi-asset and hybrid models\n        inline virtual ActiveType shortRate(const DateType t0, const DateType dt, const VecA& X0, const VecA& X1) { QL_FAIL(\"StochasticProcessT: shortRate not implemented\"); return 0; }\n\n        // the expectation E^T in the domestic currency terminal meassure\n        // this is required to calculate asset adjusters without knowing the implementation of the model\n        inline virtual ActiveType forwardAsset(const DateType t, const DateType T, const VecA& X, const std::string& alias) { QL_FAIL(\"StochasticProcessT: (multi) forwardAsset not implemented\"); return 0; }\n\n        // calculate the local volatility of the log-process of the asset\n        // this is required continuous barrier estimation via Brownian Bridge\n        inline virtual ActiveType assetVolatility(const DateType t, const VecA& X, const std::string& alias) { QL_FAIL(\"StochasticProcessT: (multi) assetVolatility not implemented\"); return 0; }\n\n        // a (domestic) zero coupon bond volatility for the model\n        // this is required e.g. for hybrid model stochastic rates adjustment\n        inline virtual VecA zeroBondVolatility(const DateType t, const DateType T, const VecA& X) { QL_FAIL(\"StochasticProcessT: zeroBondVolatility not implemented\"); return VecA(0); }\n\n        // a (domestic) zero coupon bond volatility derivative w.r.t. T for the model\n        // this is required e.g. for hybrid model stochastic rates adjustment\n        inline virtual VecA zeroBondVolatilityPrime(const DateType t, const DateType T, const VecA& X) { QL_FAIL(\"StochasticProcessT: zeroBondVolatilityPrime not implemented\"); return VecA(0); }\n\n        // the expectation E^Q in the domestic currency risk-neutral meassure\n        // this is currently used for commodity payoffs\n        inline virtual ActiveType futureAsset(const DateType t, const DateType T, const VecA& X, const std::string& alias) { QL_FAIL(\"StochasticProcessT: (multi) asset not implemented\"); return 0; }\n\n        // we want to keep track of the model details\n        virtual std::vector< std::string > stateAliases() { QL_FAIL(\"StochasticProcessT: stateAliases not implemented\"); return std::vector< std::string >(0); }\n\n        virtual std::vector< std::string > factorAliases() { QL_FAIL(\"StochasticProcessT: factorAliases not implemented\"); return std::vector< std::string >(0); }\n\n        // options for integration\n        enum VolEvolv {\n            FullTruncation         = 0,\n            LogNormalApproximation = 1,\n            LocalGaussian          = 2,\n            Other                  = -1\n        };\n\n        // default full truncation\n        virtual inline VolEvolv volEvolv() { return FullTruncation; }\n\n    };\n\n    typedef StochasticProcessT<QuantLib::Time,QuantLib::Real,QuantLib::Real> RealStochasticProcess;\n\n\n}\n\n#endif  /* ifndef quantlib_templatestochasticprocess_hpp */\n", "meta": {"hexsha": "f74a93d41eedf06ecf860551c646f0f3e49ed61f", "size": 6762, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/experimental/templatemodels/stochasticprocessT.hpp", "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/templatemodels/stochasticprocessT.hpp", "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/templatemodels/stochasticprocessT.hpp", "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": 50.0888888889, "max_line_length": 206, "alphanum_fraction": 0.6574977817, "num_tokens": 1658, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768249, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.47980821782514343}}
{"text": "/* boost random/additive_combine.hpp header file\n *\n * Copyright Jens Maurer 2000-2001\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: additive_combine.hpp,v 1.1 2007/02/12 18:25:54 irving Exp $\n *\n * Revision history\n *  2001-02-18  moved to individual header files\n */\n\n#ifndef BOOST_RANDOM_ADDITIVE_COMBINE_HPP\n#define BOOST_RANDOM_ADDITIVE_COMBINE_HPP\n\n#include <iostream>\n#include <algorithm> // for std::min and std::max\n#include <boost/config.hpp>\n#include <boost/cstdint.hpp>\n#include <boost/random/linear_congruential.hpp>\n\nnamespace boost {\nnamespace random {\n\n// L'Ecuyer 1988\ntemplate<class MLCG1, class MLCG2,\n#ifndef BOOST_NO_DEPENDENT_TYPES_IN_TEMPLATE_VALUE_PARAMETERS\n  typename MLCG1::result_type \n#else\n  int32_t\n#endif\n  val>\nclass additive_combine\n{\npublic:\n  typedef MLCG1 first_base;\n  typedef MLCG2 second_base;\n  typedef typename MLCG1::result_type result_type;\n#ifndef BOOST_NO_INCLASS_MEMBER_INITIALIZATION\n  static const bool has_fixed_range = true;\n  static const result_type min_value = 1;\n  static const result_type max_value = MLCG1::max_value-1;\n#else\n  enum { has_fixed_range = false };\n#endif\n  result_type min BOOST_PREVENT_MACRO_SUBSTITUTION () const { return 1; }\n  result_type max BOOST_PREVENT_MACRO_SUBSTITUTION () const { return (_mlcg1.max)()-1; }\n\n  additive_combine() : _mlcg1(), _mlcg2() { }\n  additive_combine(typename MLCG1::result_type seed1, \n                   typename MLCG2::result_type seed2)\n    : _mlcg1(seed1), _mlcg2(seed2) { }\n  template<class It> additive_combine(It& first, It last)\n    : _mlcg1(first, last), _mlcg2(first, last) { }\n\n  void seed()\n  {\n    _mlcg1.seed();\n    _mlcg2.seed();\n  }\n\n  void seed(typename MLCG1::result_type seed1,\n            typename MLCG2::result_type seed2)\n  {\n    _mlcg1(seed1);\n    _mlcg2(seed2);\n  }\n\n  template<class It> void seed(It& first, It last)\n  {\n    _mlcg1.seed(first, last);\n    _mlcg2.seed(first, last);\n  }\n\n  result_type operator()() {\n    result_type z = _mlcg1() - _mlcg2();\n    if(z < 1)\n      z += MLCG1::modulus-1;\n    return z;\n  }\n  static bool validation(result_type x) { return val == x; }\n\n#ifndef BOOST_NO_OPERATORS_IN_NAMESPACE\n\n#ifndef BOOST_NO_MEMBER_TEMPLATE_FRIENDS\n  template<class CharT, class Traits>\n  friend std::basic_ostream<CharT,Traits>&\n  operator<<(std::basic_ostream<CharT,Traits>& os, const additive_combine& r)\n  { os << r._mlcg1 << \" \" << r._mlcg2; return os; }\n\n  template<class CharT, class Traits>\n  friend std::basic_istream<CharT,Traits>&\n  operator>>(std::basic_istream<CharT,Traits>& is, additive_combine& r)\n  { is >> r._mlcg1 >> std::ws >> r._mlcg2; return is; }\n#endif\n\n  friend bool operator==(const additive_combine& x, const additive_combine& y)\n  { return x._mlcg1 == y._mlcg1 && x._mlcg2 == y._mlcg2; }\n  friend bool operator!=(const additive_combine& x, const additive_combine& y)\n  { return !(x == y); }\n#else\n  // Use a member function; Streamable concept not supported.\n  bool operator==(const additive_combine& rhs) const\n  { return _mlcg1 == rhs._mlcg1 && _mlcg2 == rhs._mlcg2; }\n  bool operator!=(const additive_combine& rhs) const\n  { return !(*this == rhs); }\n#endif\nprivate:\n  MLCG1 _mlcg1;\n  MLCG2 _mlcg2;\n};\n\n} // namespace random\n\ntypedef random::additive_combine<\n    random::linear_congruential<int32_t, 40014, 0, 2147483563, 0>,\n    random::linear_congruential<int32_t, 40692, 0, 2147483399, 0>,\n  2060321752> ecuyer1988;\n\n} // namespace boost\n\n#endif // BOOST_RANDOM_ADDITIVE_COMBINE_HPP\n", "meta": {"hexsha": "d507f9f308e98e8c1739619118d7ab19323b8bb1", "size": 3661, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "applications/physbam/physbam-lib/External_Libraries/Archives/boost/boost/random/additive_combine.hpp", "max_stars_repo_name": "schinmayee/nimbus", "max_stars_repo_head_hexsha": "170cd15e24a7a88243a6ea80aabadc0fc0e6e177", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2017-07-03T19:09:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-10T02:53:56.000Z", "max_issues_repo_path": "applications/physbam/physbam-lib/External_Libraries/Archives/boost/boost/random/additive_combine.hpp", "max_issues_repo_name": "schinmayee/nimbus", "max_issues_repo_head_hexsha": "170cd15e24a7a88243a6ea80aabadc0fc0e6e177", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "applications/physbam/physbam-lib/External_Libraries/Archives/boost/boost/random/additive_combine.hpp", "max_forks_repo_name": "schinmayee/nimbus", "max_forks_repo_head_hexsha": "170cd15e24a7a88243a6ea80aabadc0fc0e6e177", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2017-09-17T02:05:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-31T00:12:01.000Z", "avg_line_length": 29.0555555556, "max_line_length": 88, "alphanum_fraction": 0.7142857143, "num_tokens": 1091, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768249, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.47980821782514343}}
{"text": "#include <stan/math/prim/scal.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <gtest/gtest.h>\n#include <limits>\n\nTEST(MathFunctions, fmaxFinite) {\n  using stan::math::fmax;\n  EXPECT_FLOAT_EQ(1.0, fmax(1, 0));\n  EXPECT_FLOAT_EQ(1.0, fmax(1.0, 0));\n  EXPECT_FLOAT_EQ(1.0, fmax(1, 0.0));\n  EXPECT_FLOAT_EQ(1.0, fmax(1.0, 0.0));\n\n  EXPECT_FLOAT_EQ(1.0, fmax(0, 1));\n  EXPECT_FLOAT_EQ(1.0, fmax(0, 1.0));\n  EXPECT_FLOAT_EQ(1.0, fmax(0.0, 1));\n  EXPECT_FLOAT_EQ(1.0, fmax(0.0, 1.0));\n}\n\nTEST(MathFunctions, fmaxNaN) {\n  using stan::math::fmax;\n  double nan = std::numeric_limits<double>::quiet_NaN();\n  EXPECT_FLOAT_EQ(1.0, fmax(1, nan));\n  EXPECT_FLOAT_EQ(1.0, fmax(nan, 1));\n  EXPECT_PRED1(boost::math::isnan<double>, stan::math::fmax(nan, nan));\n}\n\nTEST(MathFunctions, fmaxInf) {\n  using stan::math::fmax;\n  double inf = std::numeric_limits<double>::infinity();\n  EXPECT_FLOAT_EQ(inf, fmax(inf, 1));\n  EXPECT_FLOAT_EQ(inf, fmax(1, inf));\n  EXPECT_FLOAT_EQ(inf, fmax(inf, -inf));\n  EXPECT_FLOAT_EQ(inf, fmax(-inf, inf));\n}\n", "meta": {"hexsha": "ce3a2960cb4535188d2987507e564a8647accf0d", "size": 1040, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/prim/scal/fun/fmax_test.cpp", "max_stars_repo_name": "jrmie/math", "max_stars_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "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": "test/unit/math/prim/scal/fun/fmax_test.cpp", "max_issues_repo_name": "jrmie/math", "max_issues_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "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": "test/unit/math/prim/scal/fun/fmax_test.cpp", "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.7142857143, "max_line_length": 71, "alphanum_fraction": 0.6826923077, "num_tokens": 380, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.72487026428967, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.47980820995676376}}
{"text": "// Copyright 2020 Gareth Cross\n#pragma once\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\nnamespace math {\n\ntemplate <typename T, int Rows = Eigen::Dynamic>\nusing Vector = Eigen::Matrix<T, Rows, 1>;\n\ntemplate <typename T, int Rows = Eigen::Dynamic, int Cols = Eigen::Dynamic>\nusing Matrix = Eigen::Matrix<T, Rows, Cols>;\n\ntemplate <typename T>\nusing Quaternion = Eigen::Quaternion<T>;\n\n// Templates for extracting useful values from eigen types.\ntemplate <typename Derived>\nusing ScalarType = typename Eigen::MatrixBase<Derived>::Scalar;\n\ntemplate <typename Derived>\nusing BaseType = typename Eigen::MatrixBase<Derived>;\n\n// Check if something is an Eigen quaternion.\ntemplate <typename Type>\nstruct IsQuaternion : public std::false_type {};\n\ntemplate <typename Scalar, int Options>\nstruct IsQuaternion<Eigen::Quaternion<Scalar, Options>> : public std::true_type {};\n\n// Check if something is an Eigen vector.\ntemplate <typename Type, typename = void>\nstruct IsVector {\n  static constexpr bool value = false;\n};\n#ifdef __GNUG__\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wunused-value\"\n#endif  // __GNUG__\ntemplate <typename Type>\nstruct IsVector<Type, decltype(Type::IsVectorAtCompileTime, void())> {\n  static constexpr bool value = Type::IsVectorAtCompileTime;\n};\n#ifdef __GNUG__\n#pragma GCC diagnostic pop\n#endif  // __GNUG__\n\n//\n// Compile time tests.\n//\n\nstatic_assert(IsQuaternion<Eigen::Quaternionf>::value, \"\");\nstatic_assert(IsQuaternion<Eigen::Quaterniond>::value, \"\");\nstatic_assert(!IsQuaternion<Eigen::Vector3d>::value, \"\");\n\nstatic_assert(IsVector<Eigen::Vector3f>::value, \"\");\nstatic_assert(IsVector<Eigen::VectorXd>::value, \"\");\nstatic_assert(!IsVector<Eigen::Matrix3f>::value, \"\");\n\n}  // namespace math\n", "meta": {"hexsha": "8320093d5f0ac797f3a43a73b9452e37d765d147", "size": 1742, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/geometry_utils/matrix_types.hpp", "max_stars_repo_name": "gareth-cross/geometry_utils", "max_stars_repo_head_hexsha": "cc687d19559c2055b68e7f8708af3595e7f93917", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-10-16T21:05:15.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-16T21:05:15.000Z", "max_issues_repo_path": "include/geometry_utils/matrix_types.hpp", "max_issues_repo_name": "gareth-cross/geometry_utils", "max_issues_repo_head_hexsha": "cc687d19559c2055b68e7f8708af3595e7f93917", "max_issues_repo_licenses": ["MIT"], "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/geometry_utils/matrix_types.hpp", "max_forks_repo_name": "gareth-cross/geometry_utils", "max_forks_repo_head_hexsha": "cc687d19559c2055b68e7f8708af3595e7f93917", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-09-07T10:10:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-17T14:36:02.000Z", "avg_line_length": 28.5573770492, "max_line_length": 83, "alphanum_fraction": 0.7479908152, "num_tokens": 397, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6261241842048092, "lm_q1q2_score": 0.4797949821385277}}
{"text": "\n\n\n/* --------------------------------------------------------------------- \n * \n * Copyright (C) 2013 - 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: Martin Kronbichler, Technische Universit\u00e4t M\u00fcnchen, \n *         Scott T. Miller, The Pennsylvania State University, 2013 \n */ \n\n\n// @sect3{Include files}  \n\n// \u5927\u591a\u6570deal.II\u7684include\u6587\u4ef6\u5df2\u7ecf\u5728\u524d\u9762\u7684\u4f8b\u5b50\u4e2d\u6d89\u53ca\u5230\u4e86\uff0c\u6ca1\u6709\u6ce8\u91ca\u3002\n\n#include <deal.II/base/quadrature_lib.h> \n#include <deal.II/base/function.h> \n#include <deal.II/base/tensor_function.h> \n#include <deal.II/base/exceptions.h> \n#include <deal.II/base/logstream.h> \n#include <deal.II/base/work_stream.h> \n#include <deal.II/base/convergence_table.h> \n#include <deal.II/lac/vector.h> \n#include <deal.II/lac/affine_constraints.h> \n#include <deal.II/lac/full_matrix.h> \n#include <deal.II/lac/dynamic_sparsity_pattern.h> \n#include <deal.II/lac/solver_bicgstab.h> \n#include <deal.II/lac/precondition.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_renumbering.h> \n#include <deal.II/dofs/dof_tools.h> \n#include <deal.II/fe/fe_dgq.h> \n#include <deal.II/fe/fe_system.h> \n#include <deal.II/fe/fe_values.h> \n#include <deal.II/numerics/vector_tools.h> \n#include <deal.II/numerics/error_estimator.h> \n#include <deal.II/numerics/matrix_tools.h> \n#include <deal.II/numerics/data_out.h> \n\n// \u7136\u800c\uff0c\u6211\u4eec\u786e\u5b9e\u6709\u4e00\u4e9b\u65b0\u7684\u5305\u62ec\u5728\u8fd9\u4e2a\u4f8b\u5b50\u4e2d\u3002\u7b2c\u4e00\u4e2a\u5b9a\u4e49\u4e86\u4e09\u89d2\u5f62\u9762\u7684\u6709\u9650\u5143\u7a7a\u95f4\uff0c\u6211\u4eec\u628a\u5b83\u79f0\u4e3a \"\u9aa8\u67b6\"\u3002\u8fd9\u4e9b\u6709\u9650\u5143\u5728\u5143\u7d20\u5185\u90e8\u6ca1\u6709\u4efb\u4f55\u652f\u6301\uff0c\u5b83\u4eec\u4ee3\u8868\u7684\u662f\u5728\u6bcf\u4e2a\u6a21\u6570\u4e00\u7684\u8868\u9762\u4e0a\u6709\u4e00\u4e2a\u5355\u4e00\u7684\u503c\u7684\u591a\u9879\u5f0f\uff0c\u4f46\u5728\u6a21\u6570\u4e8c\u7684\u8868\u9762\u4e0a\u5141\u8bb8\u6709\u4e0d\u8fde\u7eed\u3002\n\n#include <deal.II/fe/fe_face.h> \n\n// \u6211\u4eec\u5305\u542b\u7684\u7b2c\u4e8c\u4e2a\u65b0\u6587\u4ef6\u5b9a\u4e49\u4e86\u4e00\u79cd\u65b0\u7684\u7a00\u758f\u77e9\u9635\u7c7b\u578b\u3002 \u5e38\u89c4\u7684 <code>SparseMatrix</code> \u7c7b\u578b\u5b58\u50a8\u4e86\u6240\u6709\u975e\u96f6\u6761\u76ee\u7684\u7d22\u5f15\u3002  <code>ChunkSparseMatrix</code> \u5219\u662f\u5229\u7528\u4e86DG\u89e3\u7684\u8026\u5408\u6027\u3002 \u5b83\u5b58\u50a8\u4e86\u4e00\u4e2a\u6307\u5b9a\u5927\u5c0f\u7684\u77e9\u9635\u5b50\u5757\u7684\u7d22\u5f15\u3002 \u5728HDG\u80cc\u666f\u4e0b\uff0c\u8fd9\u4e2a\u5b50\u5757\u5927\u5c0f\u5b9e\u9645\u4e0a\u662f\u7531\u9aa8\u67b6\u89e3\u573a\u5b9a\u4e49\u7684\u6bcf\u4e2a\u9762\u7684\u81ea\u7531\u5ea6\u6570\u91cf\u3002\u8fd9\u4f7f\u5f97\u77e9\u9635\u7684\u5185\u5b58\u6d88\u8017\u51cf\u5c11\u4e86\u4e09\u5206\u4e4b\u4e00\uff0c\u5e76\u4e14\u5728\u6c42\u89e3\u5668\u4e2d\u4f7f\u7528\u77e9\u9635\u65f6\u4e5f\u4f1a\u6709\u7c7b\u4f3c\u7684\u901f\u5ea6\u63d0\u5347\u3002\n\n#include <deal.II/lac/chunk_sparse_matrix.h> \n\n// \u8fd9\u4e2a\u4f8b\u5b50\u7684\u6700\u540e\u4e00\u4e2a\u65b0\u7684\u5305\u62ec\u6d89\u53ca\u5230\u6570\u636e\u8f93\u51fa\u3002 \u7531\u4e8e\u6211\u4eec\u5728\u7f51\u683c\u7684\u9aa8\u67b6\u4e0a\u5b9a\u4e49\u4e86\u4e00\u4e2a\u6709\u9650\u5143\u573a\uff0c\u6211\u4eec\u5e0c\u671b\u80fd\u591f\u76f4\u89c2\u5730\u770b\u5230\u8fd9\u4e2a\u89e3\u51b3\u65b9\u6848\u7684\u5b9e\u9645\u60c5\u51b5\u3002DataOutFaces\u6b63\u662f\u8fd9\u6837\u505a\u7684\uff1b\u5b83\u7684\u63a5\u53e3\u4e0e\u6211\u4eec\u719f\u6089\u7684DataOut\u51e0\u4e4e\u4e00\u6837\uff0c\u4f46\u8f93\u51fa\u7684\u6570\u636e\u53ea\u6709\u6a21\u62df\u7684\u4e8c\u7ef41\u6570\u636e\u3002\n\n#include <deal.II/numerics/data_out_faces.h> \n\n#include <iostream> \n\n// \u6211\u4eec\u9996\u5148\u5c06\u6240\u6709\u7684\u7c7b\u653e\u5165\u81ea\u5df1\u7684\u547d\u540d\u7a7a\u95f4\u3002\n\nnamespace Step51 \n{ \n  using namespace dealii; \n// @sect3{Equation data}  \n\n//\u5206\u6790\u89e3\u7684\u7ed3\u6784\u4e0e step-7 \u4e2d\u76f8\u540c\u3002\u6709\u4e24\u4e2a\u4f8b\u5916\u60c5\u51b5\u3002\u9996\u5148\uff0c\u6211\u4eec\u4e5f\u4e3a3D\u60c5\u51b5\u521b\u5efa\u4e86\u4e00\u4e2a\u89e3\u51b3\u65b9\u6848\uff0c\u5176\u6b21\uff0c\u6211\u4eec\u5bf9\u89e3\u51b3\u65b9\u6848\u8fdb\u884c\u4e86\u7f29\u653e\uff0c\u4f7f\u5176\u5728\u89e3\u51b3\u65b9\u6848\u7684\u6240\u6709\u5bbd\u5ea6\u503c\u4e0a\u7684\u89c4\u8303\u662f\u7edf\u4e00\u7684\u3002\n\n  template <int dim> \n  class SolutionBase \n  { \n  protected: \n    static const unsigned int n_source_centers = 3; \n    static const Point<dim>   source_centers[n_source_centers]; \n    static const double       width; \n  }; \n\n  template <> \n  const Point<1> \n    SolutionBase<1>::source_centers[SolutionBase<1>::n_source_centers] = \n      {Point<1>(-1.0 / 3.0), Point<1>(0.0), Point<1>(+1.0 / 3.0)}; \n\n  template <> \n  const Point<2> \n    SolutionBase<2>::source_centers[SolutionBase<2>::n_source_centers] = \n      {Point<2>(-0.5, +0.5), Point<2>(-0.5, -0.5), Point<2>(+0.5, -0.5)}; \n\n  template <> \n  const Point<3> \n    SolutionBase<3>::source_centers[SolutionBase<3>::n_source_centers] = { \n      Point<3>(-0.5, +0.5, 0.25), \n      Point<3>(-0.6, -0.5, -0.125), \n      Point<3>(+0.5, -0.5, 0.5)}; \n\n  template <int dim> \n  const double SolutionBase<dim>::width = 1. / 5.; \n\n  template <int dim> \n  class Solution : public Function<dim>, protected SolutionBase<dim> \n  { \n  public: \n    virtual double value(const Point<dim> &p, \n                         const unsigned int /*component*/ = 0) const override \n    { \n      double sum = 0; \n      for (unsigned int i = 0; i < this->n_source_centers; ++i) \n        { \n          const Tensor<1, dim> x_minus_xi = p - this->source_centers[i]; \n          sum += \n            std::exp(-x_minus_xi.norm_square() / (this->width * this->width)); \n        } \n\n      return sum / \n             std::pow(2. * numbers::PI * this->width * this->width, dim / 2.); \n    } \n\n    virtual Tensor<1, dim> \n    gradient(const Point<dim> &p, \n             const unsigned int /*component*/ = 0) const override \n    { \n      Tensor<1, dim> sum; \n      for (unsigned int i = 0; i < this->n_source_centers; ++i) \n        { \n          const Tensor<1, dim> x_minus_xi = p - this->source_centers[i]; \n\n          sum += \n            (-2 / (this->width * this->width) * \n             std::exp(-x_minus_xi.norm_square() / (this->width * this->width)) * \n             x_minus_xi); \n        } \n\n      return sum / \n             std::pow(2. * numbers::PI * this->width * this->width, dim / 2.); \n    } \n  }; \n\n// \u8fd9\u4e2a\u7c7b\u5b9e\u73b0\u4e86\u4e00\u4e2a\u51fd\u6570\uff0c\u6807\u91cf\u89e3\u548c\u5b83\u7684\u8d1f\u68af\u5ea6\u88ab\u6536\u96c6\u5728\u4e00\u8d77\u3002\u8fd9\u4e2a\u51fd\u6570\u5728\u8ba1\u7b97HDG\u8fd1\u4f3c\u7684\u8bef\u5dee\u65f6\u4f7f\u7528\uff0c\u5b83\u7684\u5b9e\u73b0\u662f\u7b80\u5355\u5730\u8c03\u7528Solution\u7c7b\u7684\u503c\u548c\u68af\u5ea6\u51fd\u6570\u3002\n\n  template <int dim> \n  class SolutionAndGradient : public Function<dim>, protected SolutionBase<dim> \n  { \n  public: \n    SolutionAndGradient() \n      : Function<dim>(dim + 1) \n    {} \n\n    virtual void vector_value(const Point<dim> &p, \n                              Vector<double> &  v) const override \n    { \n      AssertDimension(v.size(), dim + 1); \n      Solution<dim>  solution; \n      Tensor<1, dim> grad = solution.gradient(p); \n      for (unsigned int d = 0; d < dim; ++d) \n        v[d] = -grad[d]; \n      v[dim] = solution.value(p); \n    } \n  }; \n\n// \u63a5\u4e0b\u6765\u662f\u5bf9\u6d41\u901f\u5ea6\u7684\u5b9e\u73b0\u3002\u5982\u4ecb\u7ecd\u4e2d\u6240\u8ff0\uff0c\u6211\u4eec\u9009\u62e9\u7684\u901f\u5ea6\u573a\u5728\u4e8c\u7ef4\u662f $(y, -x)$ \uff0c\u5728\u4e09\u7ef4\u662f $(y, -x, 1)$ \u3002\u8fd9\u5c31\u5f97\u5230\u4e86\u4e00\u4e2a\u65e0\u53d1\u6563\u7684\u901f\u5ea6\u573a\u3002\n\n  template <int dim> \n  class ConvectionVelocity : public TensorFunction<1, dim> \n  { \n  public: \n    ConvectionVelocity() \n      : TensorFunction<1, dim>() \n    {} \n\n    virtual Tensor<1, dim> value(const Point<dim> &p) const override \n    { \n      Tensor<1, dim> convection; \n      switch (dim) \n        { \n          case 1: \n            convection[0] = 1; \n            break; \n          case 2: \n            convection[0] = p[1]; \n            convection[1] = -p[0]; \n            break; \n          case 3: \n            convection[0] = p[1]; \n            convection[1] = -p[0]; \n            convection[2] = 1; \n            break; \n          default: \n            Assert(false, ExcNotImplemented()); \n        } \n      return convection; \n    } \n  }; \n\n// \u6211\u4eec\u5b9e\u73b0\u7684\u6700\u540e\u4e00\u4e2a\u51fd\u6570\u662f\u7528\u4e8e\u5236\u9020\u89e3\u51b3\u65b9\u6848\u7684\u53f3\u624b\u8fb9\u3002\u5b83\u4e0e step-7 \u975e\u5e38\u76f8\u4f3c\uff0c\u4e0d\u540c\u7684\u662f\u6211\u4eec\u73b0\u5728\u6709\u4e00\u4e2a\u5bf9\u6d41\u9879\u800c\u4e0d\u662f\u53cd\u5e94\u9879\u3002\u7531\u4e8e\u901f\u5ea6\u573a\u662f\u4e0d\u53ef\u538b\u7f29\u7684\uff0c\u5373 $\\nabla \\cdot \\mathbf{c} =0$ \uff0c\u5bf9\u6d41\u9879\u7b80\u5355\u8bfb\u4f5c  $\\mathbf{c} \\nabla u$  \u3002\n\n  template <int dim> \n  class RightHandSide : public Function<dim>, protected SolutionBase<dim> \n  { \n  public: \n    virtual double value(const Point<dim> &p, \n                         const unsigned int /*component*/ = 0) const override \n    { \n      ConvectionVelocity<dim> convection_velocity; \n      Tensor<1, dim>          convection = convection_velocity.value(p); \n      double                  sum        = 0; \n      for (unsigned int i = 0; i < this->n_source_centers; ++i) \n        { \n          const Tensor<1, dim> x_minus_xi = p - this->source_centers[i]; \n\n          sum += \n            ((2 * dim - 2 * convection * x_minus_xi - \n              4 * x_minus_xi.norm_square() / (this->width * this->width)) / \n             (this->width * this->width) * \n             std::exp(-x_minus_xi.norm_square() / (this->width * this->width))); \n        } \n\n      return sum / \n             std::pow(2. * numbers::PI * this->width * this->width, dim / 2.); \n    } \n  }; \n\n//  @sect3{The HDG solver class}  \n\n// HDG\u7684\u6c42\u89e3\u8fc7\u7a0b\u4e0e  step-7  \u7684\u6c42\u89e3\u8fc7\u7a0b\u975e\u5e38\u76f8\u4f3c\u3002\u4e3b\u8981\u533a\u522b\u5728\u4e8e\u4f7f\u7528\u4e86\u4e09\u5957\u4e0d\u540c\u7684DoFHandler\u548cFE\u5bf9\u8c61\uff0c\u4ee5\u53caChunkSparseMatrix\u548c\u76f8\u5e94\u7684\u89e3\u51b3\u65b9\u6848\u5411\u91cf\u3002\u6211\u4eec\u8fd8\u4f7f\u7528WorkStream\u6765\u5b9e\u73b0\u591a\u7ebf\u7a0b\u7684\u672c\u5730\u6c42\u89e3\u8fc7\u7a0b\uff0c\u8be5\u8fc7\u7a0b\u5229\u7528\u4e86\u672c\u5730\u6c42\u89e3\u5668\u7684\u5c34\u5c2c\u7684\u5e76\u884c\u6027\u8d28\u3002\u5bf9\u4e8eWorkStream\uff0c\u6211\u4eec\u5b9a\u4e49\u4e86\u5bf9\u5355\u5143\u683c\u7684\u672c\u5730\u64cd\u4f5c\u548c\u590d\u5236\u5230\u5168\u5c40\u77e9\u9635\u548c\u5411\u91cf\u7684\u51fd\u6570\u3002\u6211\u4eec\u8fd9\u6837\u505a\u65e2\u662f\u4e3a\u4e86\u88c5\u914d\uff08\u88c5\u914d\u8981\u8fd0\u884c\u4e24\u6b21\uff0c\u4e00\u6b21\u662f\u5728\u6211\u4eec\u751f\u6210\u7cfb\u7edf\u77e9\u9635\u65f6\uff0c\u53e6\u4e00\u6b21\u662f\u5728\u6211\u4eec\u4ece\u9aa8\u67b6\u503c\u8ba1\u7b97\u5143\u7d20\u5185\u90e8\u89e3\u65f6\uff09\uff0c\u4e5f\u662f\u4e3a\u4e86\u540e\u5904\u7406\uff0c\u5728\u540e\u5904\u7406\u4e2d\u6211\u4eec\u63d0\u53d6\u4e00\u4e2a\u5728\u9ad8\u9636\u6536\u655b\u7684\u89e3\u3002\n\n  template <int dim> \n  class HDG \n  { \n  public: \n    enum RefinementMode \n    { \n      global_refinement, \n      adaptive_refinement \n    }; \n\n    HDG(const unsigned int degree, const RefinementMode refinement_mode); \n    void run(); \n\n  private: \n    void setup_system(); \n    void assemble_system(const bool reconstruct_trace = false); \n    void solve(); \n    void postprocess(); \n    void refine_grid(const unsigned int cycle); \n    void output_results(const unsigned int cycle); \n\n// \u7528\u4e8e\u7ec4\u88c5\u548c\u89e3\u51b3\u539f\u59cb\u53d8\u91cf\u7684\u6570\u636e\u3002\n\n    struct PerTaskData; \n    struct ScratchData; \n\n// \u5bf9\u89e3\u51b3\u65b9\u6848\u8fdb\u884c\u540e\u5904\u7406\u4ee5\u83b7\u5f97  $u^*$  \u662f\u4e00\u4e2a\u9010\u4e2a\u5143\u7d20\u7684\u8fc7\u7a0b\uff1b\u56e0\u6b64\uff0c\u6211\u4eec\u4e0d\u9700\u8981\u7ec4\u88c5\u4efb\u4f55\u5168\u5c40\u6570\u636e\uff0c\u4e5f\u4e0d\u9700\u8981\u58f0\u660e\u4efb\u4f55 \"\u4efb\u52a1\u6570\u636e \"\u4f9bWorkStream\u4f7f\u7528\u3002\n\n    struct PostProcessScratchData; \n\n// \u4ee5\u4e0b\u4e09\u4e2a\u51fd\u6570\u88ab WorkStream \u7528\u6765\u5b8c\u6210\u7a0b\u5e8f\u7684\u5b9e\u9645\u5de5\u4f5c\u3002\n\n    void assemble_system_one_cell( \n      const typename DoFHandler<dim>::active_cell_iterator &cell, \n      ScratchData &                                         scratch, \n      PerTaskData &                                         task_data); \n\n    void copy_local_to_global(const PerTaskData &data); \n\n    void postprocess_one_cell( \n      const typename DoFHandler<dim>::active_cell_iterator &cell, \n      PostProcessScratchData &                              scratch, \n      unsigned int &                                        empty_data); \n\n    Triangulation<dim> triangulation; \n\n// \"\u5c40\u90e8 \"\u89e3\u662f\u6bcf\u4e2a\u5143\u7d20\u7684\u5185\u90e8\u3002 \u8fd9\u4e9b\u4ee3\u8868\u4e86\u539f\u59cb\u89e3\u573a  $u$  \u4ee5\u53ca\u8f85\u52a9\u573a  $\\mathbf{q}$  \u3002\n\n    FESystem<dim>   fe_local; \n    DoFHandler<dim> dof_handler_local; \n    Vector<double>  solution_local; \n\n// \u65b0\u7684\u6709\u9650\u5143\u7c7b\u578b\u548c\u76f8\u5e94\u7684 <code>DoFHandler</code> \u88ab\u7528\u4e8e\u8026\u5408\u5143\u7d20\u7ea7\u5c40\u90e8\u89e3\u7684\u5168\u5c40\u9aa8\u67b6\u89e3\u3002\n\n    FE_FaceQ<dim>   fe; \n    DoFHandler<dim> dof_handler; \n    Vector<double>  solution; \n    Vector<double>  system_rhs; \n\n// \u5982\u4ecb\u7ecd\u4e2d\u6240\u8ff0\uff0cHDG\u89e3\u53ef\u4ee5\u901a\u8fc7\u540e\u5904\u7406\u8fbe\u5230  $\\mathcal{O}(h^{p+2})$  \u7684\u8d85\u6536\u655b\u7387\u3002 \u540e\u5904\u7406\u7684\u89e3\u662f\u4e00\u4e2a\u4e0d\u8fde\u7eed\u7684\u6709\u9650\u5143\u89e3\uff0c\u4ee3\u8868\u6bcf\u4e2a\u5355\u5143\u5185\u90e8\u7684\u539f\u59cb\u53d8\u91cf\u3002 \u6211\u4eec\u5b9a\u4e49\u4e86\u4e00\u4e2a\u7a0b\u5ea6\u4e3a $p+1$ \u7684FE\u7c7b\u578b\u6765\u8868\u793a\u8fd9\u4e2a\u540e\u5904\u7406\u7684\u89e3\uff0c\u6211\u4eec\u53ea\u5728\u6784\u9020\u540e\u7528\u4e8e\u8f93\u51fa\u3002\n\n    FE_DGQ<dim>     fe_u_post; \n    DoFHandler<dim> dof_handler_u_post; \n    Vector<double>  solution_u_post; \n\n// \u4e0e\u9aa8\u67b6\u76f8\u5bf9\u5e94\u7684\u81ea\u7531\u5ea6\u5f3a\u70c8\u5730\u6267\u884cDirichlet\u8fb9\u754c\u6761\u4ef6\uff0c\u5c31\u50cf\u5728\u8fde\u7eedGalerkin\u6709\u9650\u5143\u65b9\u6cd5\u4e2d\u4e00\u6837\u3002\u6211\u4eec\u53ef\u4ee5\u901a\u8fc7AffineConstraints\u5bf9\u8c61\u4ee5\u7c7b\u4f3c\u7684\u65b9\u5f0f\u5f3a\u5236\u6267\u884c\u8fb9\u754c\u6761\u4ef6\u3002\u6b64\u5916\uff0c\u60ac\u6302\u8282\u70b9\u7684\u5904\u7406\u65b9\u5f0f\u4e0e\u8fde\u7eed\u6709\u9650\u5143\u7684\u5904\u7406\u65b9\u5f0f\u76f8\u540c\u3002\u5bf9\u4e8e\u53ea\u5728\u9762\u5b9a\u4e49\u81ea\u7531\u5ea6\u7684\u9762\u5143\u7d20\uff0c\u8fd9\u4e2a\u8fc7\u7a0b\u5c06\u7cbe\u70bc\u9762\u7684\u89e3\u8bbe\u7f6e\u4e3a\u4e0e\u7c97\u7565\u9762\u7684\u8868\u793a\u76f8\u543b\u5408\u3002\n\n// \u8bf7\u6ce8\u610f\uff0c\u5bf9\u4e8eHDG\u6765\u8bf4\uff0c\u6d88\u9664\u60ac\u7a7a\u8282\u70b9\u5e76\u4e0d\u662f\u552f\u4e00\u7684\u53ef\u80fd\u6027\uff0c\u5c31HDG\u7406\u8bba\u800c\u8a00\uff0c\u6211\u4eec\u4e5f\u53ef\u4ee5\u4f7f\u7528\u7cbe\u70bc\u4fa7\u7684\u672a\u77e5\u6570\uff0c\u901a\u8fc7\u7cbe\u70bc\u4fa7\u7684\u8ddf\u8e2a\u503c\u6765\u8868\u8fbe\u7c97\u7565\u4fa7\u7684\u5c40\u90e8\u89e3\u3002\u7136\u800c\uff0c\u8fd9\u6837\u7684\u8bbe\u7f6e\u5728deal.II\u5faa\u73af\u65b9\u9762\u5e76\u4e0d\u5bb9\u6613\u5b9e\u73b0\uff0c\u56e0\u6b64\u6ca1\u6709\u8fdb\u4e00\u6b65\u5206\u6790\u3002\n\n    AffineConstraints<double> constraints; \n\n// ChunkSparseMatrix\u7c7b\u7684\u7528\u6cd5\u4e0e\u901a\u5e38\u7684\u7a00\u758f\u77e9\u9635\u7c7b\u4f3c\u3002\u4f60\u9700\u8981\u4e00\u4e2aChunkSparsityPattern\u7c7b\u578b\u7684\u7a00\u758f\u6a21\u5f0f\u548c\u5b9e\u9645\u7684\u77e9\u9635\u5bf9\u8c61\u3002\u5728\u521b\u5efa\u7a00\u758f\u6a21\u5f0f\u65f6\uff0c\u6211\u4eec\u53ea\u9700\u8981\u989d\u5916\u4f20\u9012\u5c40\u90e8\u5757\u7684\u5927\u5c0f\u3002\n\n    ChunkSparsityPattern      sparsity_pattern; \n    ChunkSparseMatrix<double> system_matrix; \n\n// \u4e0e  step-7  \u76f8\u540c\u3002\n\n    const RefinementMode refinement_mode; \n    ConvergenceTable     convergence_table; \n  }; \n// @sect3{The HDG class implementation}  \n// @sect4{Constructor}  \u8be5\u6784\u9020\u51fd\u6570\u4e0e\u5176\u4ed6\u4f8b\u5b50\u4e2d\u7684\u6784\u9020\u51fd\u6570\u7c7b\u4f3c\uff0c\u9664\u4e86\u5904\u7406\u591a\u4e2aDoFHandler\u548cFiniteElement\u5bf9\u8c61\u3002\u8bf7\u6ce8\u610f\uff0c\u6211\u4eec\u4e3a\u5c40\u90e8DG\u90e8\u5206\u521b\u5efa\u4e86\u4e00\u4e2a\u6709\u9650\u5143\u7cfb\u7edf\uff0c\u5305\u62ec\u68af\u5ea6/\u901a\u91cf\u90e8\u5206\u548c\u6807\u91cf\u90e8\u5206\u3002\n\n  template <int dim> \n  HDG<dim>::HDG(const unsigned int degree, const RefinementMode refinement_mode) \n    : fe_local(FE_DGQ<dim>(degree), dim, FE_DGQ<dim>(degree), 1) \n    , dof_handler_local(triangulation) \n    , fe(degree) \n    , dof_handler(triangulation) \n    , fe_u_post(degree + 1) \n    , dof_handler_u_post(triangulation) \n    , refinement_mode(refinement_mode) \n  {} \n\n//  @sect4{HDG::setup_system}  HDG\u89e3\u51b3\u65b9\u6848\u7684\u7cfb\u7edf\u662f\u4ee5\u7c7b\u4f3c\u4e8e\u5176\u4ed6\u5927\u591a\u6570\u6559\u7a0b\u7a0b\u5e8f\u7684\u65b9\u5f0f\u8bbe\u7f6e\u7684\u3002 \u6211\u4eec\u5c0f\u5fc3\u7ffc\u7ffc\u5730\u7528\u6211\u4eec\u6240\u6709\u7684DoFHandler\u5bf9\u8c61\u6765\u5206\u914d\u9053\u592b\u3002  @p solution \u548c @p system_matrix \u5bf9\u8c61\u4e0e\u5168\u5c40\u9aa8\u67b6\u89e3\u51b3\u65b9\u6848\u4e00\u8d77\u3002\n\n  template <int dim> \n  void HDG<dim>::setup_system() \n  { \n    dof_handler_local.distribute_dofs(fe_local); \n    dof_handler.distribute_dofs(fe); \n    dof_handler_u_post.distribute_dofs(fe_u_post); \n\n    std::cout << \"   Number of degrees of freedom: \" << dof_handler.n_dofs() \n              << std::endl; \n\n    solution.reinit(dof_handler.n_dofs()); \n    system_rhs.reinit(dof_handler.n_dofs()); \n\n    solution_local.reinit(dof_handler_local.n_dofs()); \n    solution_u_post.reinit(dof_handler_u_post.n_dofs()); \n\n    constraints.clear(); \n    DoFTools::make_hanging_node_constraints(dof_handler, constraints); \n    std::map<types::boundary_id, const Function<dim> *> boundary_functions; \n    Solution<dim>                                       solution_function; \n    boundary_functions[0] = &solution_function; \n    VectorTools::project_boundary_values(dof_handler, \n                                         boundary_functions, \n                                         QGauss<dim - 1>(fe.degree + 1), \n                                         constraints); \n    constraints.close(); \n\n// \u5728\u521b\u5efa\u5757\u72b6\u7a00\u758f\u6a21\u5f0f\u65f6\uff0c\u6211\u4eec\u9996\u5148\u521b\u5efa\u901a\u5e38\u7684\u52a8\u6001\u7a00\u758f\u6a21\u5f0f\uff0c\u7136\u540e\u8bbe\u7f6e\u5757\u72b6\u5927\u5c0f\uff0c\u8be5\u5927\u5c0f\u7b49\u4e8e\u4e00\u4e2a\u9762\u7684\u9053\u592b\u6570\uff0c\u5f53\u628a\u5b83\u590d\u5236\u5230\u6700\u7ec8\u7684\u7a00\u758f\u6a21\u5f0f\u65f6\u3002\n\n    { \n      DynamicSparsityPattern dsp(dof_handler.n_dofs()); \n      DoFTools::make_sparsity_pattern(dof_handler, dsp, constraints, false); \n      sparsity_pattern.copy_from(dsp, fe.n_dofs_per_face()); \n    } \n    system_matrix.reinit(sparsity_pattern); \n  } \n\n//  @sect4{HDG::PerTaskData}  \u63a5\u4e0b\u6765\u662f\u5b9a\u4e49\u5e76\u884c\u88c5\u914d\u7684\u672c\u5730\u6570\u636e\u7ed3\u6784\u3002\u7b2c\u4e00\u4e2a\u7ed3\u6784 @p PerTaskData \u5305\u542b\u4e86\u88ab\u5199\u5165\u5168\u5c40\u77e9\u9635\u7684\u672c\u5730\u5411\u91cf\u548c\u77e9\u9635\uff0c\u800cScratchData\u5305\u542b\u4e86\u6211\u4eec\u5728\u672c\u5730\u88c5\u914d\u4e2d\u9700\u8981\u7684\u6240\u6709\u6570\u636e\u3002\u8fd9\u91cc\u6709\u4e00\u4e2a\u53d8\u91cf\u503c\u5f97\u6ce8\u610f\uff0c\u5373\u5e03\u5c14\u53d8\u91cf @p  trace_reconstruct\u3002\u6b63\u5982\u4ecb\u7ecd\u4e2d\u63d0\u5230\u7684\uff0c\u6211\u4eec\u5206\u4e24\u6b65\u89e3\u51b3HDG\u7cfb\u7edf\u3002\u9996\u5148\uff0c\u6211\u4eec\u4e3a\u9aa8\u67b6\u7cfb\u7edf\u521b\u5efa\u4e00\u4e2a\u7ebf\u6027\u7cfb\u7edf\uff0c\u901a\u8fc7\u8212\u5c14\u8865\u7801 $D-CA^{-1}B$  \u5c06\u5c40\u90e8\u90e8\u5206\u6d53\u7f29\u5230\u5176\u4e2d\u3002\u7136\u540e\uff0c\u6211\u4eec\u7528\u9aa8\u67b6\u7684\u89e3\u6765\u89e3\u51b3\u5c40\u90e8\u90e8\u5206\u3002\u5bf9\u4e8e\u8fd9\u4e24\u4e2a\u6b65\u9aa4\uff0c\u6211\u4eec\u9700\u8981\u4e24\u6b21\u5143\u7d20\u4e0a\u7684\u76f8\u540c\u77e9\u9635\uff0c\u6211\u4eec\u5e0c\u671b\u901a\u8fc7\u4e24\u4e2a\u88c5\u914d\u6b65\u9aa4\u6765\u8ba1\u7b97\u3002\u7531\u4e8e\u5927\u90e8\u5206\u7684\u4ee3\u7801\u662f\u76f8\u4f3c\u7684\uff0c\u6211\u4eec\u7528\u76f8\u540c\u7684\u51fd\u6570\u6765\u505a\u8fd9\u4ef6\u4e8b\uff0c\u4f46\u53ea\u662f\u6839\u636e\u6211\u4eec\u5728\u5f00\u59cb\u88c5\u914d\u65f6\u8bbe\u7f6e\u7684\u4e00\u4e2a\u6807\u5fd7\u5728\u4e24\u8005\u4e4b\u95f4\u5207\u6362\u3002\u56e0\u4e3a\u6211\u4eec\u9700\u8981\u628a\u8fd9\u4e2a\u4fe1\u606f\u4f20\u9012\u7ed9\u672c\u5730\u7684\u5de5\u4f5c\u7a0b\u5e8f\uff0c\u6240\u4ee5\u6211\u4eec\u628a\u5b83\u5b58\u50a8\u5728\u4efb\u52a1\u6570\u636e\u4e2d\u4e00\u6b21\u3002\n\n  template <int dim> \n  struct HDG<dim>::PerTaskData \n  { \n    FullMatrix<double>                   cell_matrix; \n    Vector<double>                       cell_vector; \n    std::vector<types::global_dof_index> dof_indices; \n\n    bool trace_reconstruct; \n\n    PerTaskData(const unsigned int n_dofs, const bool trace_reconstruct) \n      : cell_matrix(n_dofs, n_dofs) \n      , cell_vector(n_dofs) \n      , dof_indices(n_dofs) \n      , trace_reconstruct(trace_reconstruct) \n    {} \n  }; \n\n//  @sect4{HDG::ScratchData}  \n// @p ScratchData  \u5305\u542bWorkStream\u4e2d\u6bcf\u4e2a\u7ebf\u7a0b\u7684\u6301\u4e45\u5316\u6570\u636e\u3002 FEValues\u3001\u77e9\u9635\u548c\u77e2\u91cf\u5bf9\u8c61\u73b0\u5728\u5e94\u8be5\u5f88\u719f\u6089\u4e86\u3002 \u6709\u4e24\u4e2a\u5bf9\u8c61\u9700\u8981\u8ba8\u8bba\u3002  `std::vector<std::vector<unsigned  int> > fe_local_support_on_face` \u548c  `std::vector<std::vector<unsigned  int> > fe_support_on_face`\u3002 \u8fd9\u4e9b\u7528\u4e8e\u6307\u793a\u6240\u9009\u62e9\u7684\u6709\u9650\u5143\u662f\u5426\u5728\u4e0e @p fe_local \u76f8\u5173\u7684\u5c40\u90e8\u90e8\u5206\u548c\u9aa8\u67b6\u90e8\u5206 @p fe. \u7684\u53c2\u8003\u5355\u5143\u7684\u7279\u5b9a\u9762\u4e0a\u6709\u652f\u6301\uff08\u975e\u96f6\u503c\uff09\u3002 \u6211\u4eec\u5728\u6784\u9020\u51fd\u6570\u4e2d\u63d0\u53d6\u8fd9\u4e00\u4fe1\u606f\uff0c\u5e76\u4e3a\u6211\u4eec\u5de5\u4f5c\u7684\u6240\u6709\u5355\u5143\u5b58\u50a8\u4e00\u6b21\u3002 \u5982\u679c\u6211\u4eec\u4e0d\u5b58\u50a8\u8fd9\u4e00\u4fe1\u606f\uff0c\u6211\u4eec\u5c06\u88ab\u8feb\u5728\u6bcf\u4e2a\u5355\u5143\u4e0a\u88c5\u914d\u5927\u91cf\u7684\u96f6\u9879\uff0c\u8fd9\u5c06\u5927\u5927\u964d\u4f4e\u7a0b\u5e8f\u7684\u901f\u5ea6\u3002\n\n  template <int dim> \n  struct HDG<dim>::ScratchData \n  { \n    FEValues<dim>     fe_values_local; \n    FEFaceValues<dim> fe_face_values_local; \n    FEFaceValues<dim> fe_face_values; \n\n    FullMatrix<double> ll_matrix; \n    FullMatrix<double> lf_matrix; \n    FullMatrix<double> fl_matrix; \n    FullMatrix<double> tmp_matrix; \n    Vector<double>     l_rhs; \n    Vector<double>     tmp_rhs; \n\n    std::vector<Tensor<1, dim>> q_phi; \n    std::vector<double>         q_phi_div; \n    std::vector<double>         u_phi; \n    std::vector<Tensor<1, dim>> u_phi_grad; \n    std::vector<double>         tr_phi; \n    std::vector<double>         trace_values; \n\n    std::vector<std::vector<unsigned int>> fe_local_support_on_face; \n    std::vector<std::vector<unsigned int>> fe_support_on_face; \n\n    ConvectionVelocity<dim> convection_velocity; \n    RightHandSide<dim>      right_hand_side; \n    const Solution<dim>     exact_solution; \n\n    ScratchData(const FiniteElement<dim> &fe, \n                const FiniteElement<dim> &fe_local, \n                const QGauss<dim> &       quadrature_formula, \n                const QGauss<dim - 1> &   face_quadrature_formula, \n                const UpdateFlags         local_flags, \n                const UpdateFlags         local_face_flags, \n                const UpdateFlags         flags) \n      : fe_values_local(fe_local, quadrature_formula, local_flags) \n      , fe_face_values_local(fe_local, \n                             face_quadrature_formula, \n                             local_face_flags) \n      , fe_face_values(fe, face_quadrature_formula, flags) \n      , ll_matrix(fe_local.n_dofs_per_cell(), fe_local.n_dofs_per_cell()) \n      , lf_matrix(fe_local.n_dofs_per_cell(), fe.n_dofs_per_cell()) \n      , fl_matrix(fe.n_dofs_per_cell(), fe_local.n_dofs_per_cell()) \n      , tmp_matrix(fe.n_dofs_per_cell(), fe_local.n_dofs_per_cell()) \n      , l_rhs(fe_local.n_dofs_per_cell()) \n      , tmp_rhs(fe_local.n_dofs_per_cell()) \n      , q_phi(fe_local.n_dofs_per_cell()) \n      , q_phi_div(fe_local.n_dofs_per_cell()) \n      , u_phi(fe_local.n_dofs_per_cell()) \n      , u_phi_grad(fe_local.n_dofs_per_cell()) \n      , tr_phi(fe.n_dofs_per_cell()) \n      , trace_values(face_quadrature_formula.size()) \n      , fe_local_support_on_face(GeometryInfo<dim>::faces_per_cell) \n      , fe_support_on_face(GeometryInfo<dim>::faces_per_cell) \n      , exact_solution() \n    { \n      for (unsigned int face_no : GeometryInfo<dim>::face_indices()) \n        for (unsigned int i = 0; i < fe_local.n_dofs_per_cell(); ++i) \n          { \n            if (fe_local.has_support_on_face(i, face_no)) \n              fe_local_support_on_face[face_no].push_back(i); \n          } \n\n      for (unsigned int face_no : GeometryInfo<dim>::face_indices()) \n        for (unsigned int i = 0; i < fe.n_dofs_per_cell(); ++i) \n          { \n            if (fe.has_support_on_face(i, face_no)) \n              fe_support_on_face[face_no].push_back(i); \n          } \n    } \n\n    ScratchData(const ScratchData &sd) \n      : fe_values_local(sd.fe_values_local.get_fe(), \n                        sd.fe_values_local.get_quadrature(), \n                        sd.fe_values_local.get_update_flags()) \n      , fe_face_values_local(sd.fe_face_values_local.get_fe(), \n                             sd.fe_face_values_local.get_quadrature(), \n                             sd.fe_face_values_local.get_update_flags()) \n      , fe_face_values(sd.fe_face_values.get_fe(), \n                       sd.fe_face_values.get_quadrature(), \n                       sd.fe_face_values.get_update_flags()) \n      , ll_matrix(sd.ll_matrix) \n      , lf_matrix(sd.lf_matrix) \n      , fl_matrix(sd.fl_matrix) \n      , tmp_matrix(sd.tmp_matrix) \n      , l_rhs(sd.l_rhs) \n      , tmp_rhs(sd.tmp_rhs) \n      , q_phi(sd.q_phi) \n      , q_phi_div(sd.q_phi_div) \n      , u_phi(sd.u_phi) \n      , u_phi_grad(sd.u_phi_grad) \n      , tr_phi(sd.tr_phi) \n      , trace_values(sd.trace_values) \n      , fe_local_support_on_face(sd.fe_local_support_on_face) \n      , fe_support_on_face(sd.fe_support_on_face) \n      , exact_solution() \n    {} \n  }; \n\n//  @sect4{HDG::PostProcessScratchData}  \n// @p PostProcessScratchData  \u5305\u542bWorkStream\u5728\u5bf9\u672c\u5730\u89e3\u51b3\u65b9\u6848\u8fdb\u884c\u540e\u5904\u7406\u65f6\u4f7f\u7528\u7684\u6570\u636e  $u^*$  \u3002 \u5b83\u4e0e  @p ScratchData.  \u7c7b\u4f3c\uff0c\u4f46\u8981\u7b80\u5355\u5f97\u591a\u3002\n  template <int dim> \n  struct HDG<dim>::PostProcessScratchData \n  { \n    FEValues<dim> fe_values_local; \n    FEValues<dim> fe_values; \n\n    std::vector<double>         u_values; \n    std::vector<Tensor<1, dim>> u_gradients; \n    FullMatrix<double>          cell_matrix; \n\n    Vector<double> cell_rhs; \n    Vector<double> cell_sol; \n\n    PostProcessScratchData(const FiniteElement<dim> &fe, \n                           const FiniteElement<dim> &fe_local, \n                           const QGauss<dim> &       quadrature_formula, \n                           const UpdateFlags         local_flags, \n                           const UpdateFlags         flags) \n      : fe_values_local(fe_local, quadrature_formula, local_flags) \n      , fe_values(fe, quadrature_formula, flags) \n      , u_values(quadrature_formula.size()) \n      , u_gradients(quadrature_formula.size()) \n      , cell_matrix(fe.n_dofs_per_cell(), fe.n_dofs_per_cell()) \n      , cell_rhs(fe.n_dofs_per_cell()) \n      , cell_sol(fe.n_dofs_per_cell()) \n    {} \n\n    PostProcessScratchData(const PostProcessScratchData &sd) \n      : fe_values_local(sd.fe_values_local.get_fe(), \n                        sd.fe_values_local.get_quadrature(), \n                        sd.fe_values_local.get_update_flags()) \n      , fe_values(sd.fe_values.get_fe(), \n                  sd.fe_values.get_quadrature(), \n                  sd.fe_values.get_update_flags()) \n      , u_values(sd.u_values) \n      , u_gradients(sd.u_gradients) \n      , cell_matrix(sd.cell_matrix) \n      , cell_rhs(sd.cell_rhs) \n      , cell_sol(sd.cell_sol) \n    {} \n  }; \n\n//  @sect4{HDG::assemble_system}   @p assemble_system \u51fd\u6570\u4e0e Step-32 \u4e0a\u7684\u51fd\u6570\u7c7b\u4f3c\uff0c\u5176\u4e2d\u6b63\u4ea4\u516c\u5f0f\u548c\u66f4\u65b0\u6807\u5fd7\u88ab\u8bbe\u7f6e\uff0c\u7136\u540e <code>WorkStream</code> \u88ab\u7528\u6765\u4ee5\u591a\u7ebf\u7a0b\u7684\u65b9\u5f0f\u8fdb\u884c\u5de5\u4f5c\u3002  @p trace_reconstruct  \u8f93\u5165\u53c2\u6570\u7528\u4e8e\u51b3\u5b9a\u6211\u4eec\u662f\u6c42\u5168\u5c40\u9aa8\u67b6\u89e3\uff08false\uff09\u8fd8\u662f\u5c40\u90e8\u89e3\uff08true\uff09\u3002\n\n// \u5bf9\u4e8e\u6c47\u7f16\u7684\u591a\u7ebf\u7a0b\u6267\u884c\uff0c\u6709\u4e00\u70b9\u503c\u5f97\u6ce8\u610f\u7684\u662f\uff0c`assemble_system_one_cell()`\u4e2d\u7684\u5c40\u90e8\u8ba1\u7b97\u4f1a\u8c03\u7528BLAS\u548cLAPACK\u51fd\u6570\uff0c\u5982\u679c\u8fd9\u4e9b\u51fd\u6570\u5728deal.II\u4e2d\u53ef\u7528\u3002\u56e0\u6b64\uff0c\u5e95\u5c42\u7684BLAS/LAPACK\u5e93\u5fc5\u987b\u652f\u6301\u540c\u65f6\u6765\u81ea\u591a\u4e2a\u7ebf\u7a0b\u7684\u8c03\u7528\u3002\u5927\u591a\u6570\u5b9e\u73b0\u90fd\u652f\u6301\u8fd9\u4e00\u70b9\uff0c\u4f46\u6709\u4e9b\u5e93\u9700\u8981\u4ee5\u7279\u5b9a\u65b9\u5f0f\u6784\u5efa\u4ee5\u907f\u514d\u95ee\u9898\u3002\u4f8b\u5982\uff0c\u5728BLAS/LAPACK\u8c03\u7528\u5185\u90e8\u6ca1\u6709\u591a\u7ebf\u7a0b\u7684\u60c5\u51b5\u4e0b\u7f16\u8bd1\u7684OpenBLAS\u9700\u8981\u5728\u6784\u5efa\u65f6\u5c06\u4e00\u4e2a\u540d\u4e3a`USE_LOCKING'\u7684\u6807\u5fd7\u8bbe\u7f6e\u4e3atrue\u3002\n\n  template <int dim> \n  void HDG<dim>::assemble_system(const bool trace_reconstruct) \n  { \n    const QGauss<dim>     quadrature_formula(fe.degree + 1); \n    const QGauss<dim - 1> face_quadrature_formula(fe.degree + 1); \n\n    const UpdateFlags local_flags(update_values | update_gradients | \n                                  update_JxW_values | update_quadrature_points); \n\n    const UpdateFlags local_face_flags(update_values); \n\n    const UpdateFlags flags(update_values | update_normal_vectors | \n                            update_quadrature_points | update_JxW_values); \n\n    PerTaskData task_data(fe.n_dofs_per_cell(), trace_reconstruct); \n    ScratchData scratch(fe, \n                        fe_local, \n                        quadrature_formula, \n                        face_quadrature_formula, \n                        local_flags, \n                        local_face_flags, \n                        flags); \n\n    WorkStream::run(dof_handler.begin_active(), \n                    dof_handler.end(), \n                    *this, \n                    &HDG<dim>::assemble_system_one_cell, \n                    &HDG<dim>::copy_local_to_global, \n                    scratch, \n                    task_data); \n  } \n\n//  @sect4{HDG::assemble_system_one_cell}  HDG\u7a0b\u5e8f\u7684\u5b9e\u9645\u5de5\u4f5c\u7531  @p assemble_system_one_cell.  \u7ec4\u88c5\u5c40\u90e8\u77e9\u9635  $A, B, C$  \u5728\u8fd9\u91cc\u5b8c\u6210\uff0c\u540c\u65f6\u8fd8\u6709\u5168\u5c40\u77e9\u9635\u7684\u5c40\u90e8\u8d21\u732e  $D$  \u3002\n\n  template <int dim> \n  void HDG<dim>::assemble_system_one_cell( \n    const typename DoFHandler<dim>::active_cell_iterator &cell, \n    ScratchData &                                         scratch, \n    PerTaskData &                                         task_data) \n  { \n\n//\u4e3aDof_handler_local\u6784\u5efa\u8fed\u4ee3\u5668\uff0c\u7528\u4e8eFEValues\u7684reinit\u51fd\u6570\u3002\n\n    typename DoFHandler<dim>::active_cell_iterator loc_cell(&triangulation, \n                                                            cell->level(), \n                                                            cell->index(), \n                                                            &dof_handler_local); \n\n    const unsigned int n_q_points = \n      scratch.fe_values_local.get_quadrature().size(); \n    const unsigned int n_face_q_points = \n      scratch.fe_face_values_local.get_quadrature().size(); \n\n    const unsigned int loc_dofs_per_cell = \n      scratch.fe_values_local.get_fe().n_dofs_per_cell(); \n\n    const FEValuesExtractors::Vector fluxes(0); \n    const FEValuesExtractors::Scalar scalar(dim); \n\n    scratch.ll_matrix = 0; \n    scratch.l_rhs     = 0; \n    if (!task_data.trace_reconstruct) \n      { \n        scratch.lf_matrix     = 0; \n        scratch.fl_matrix     = 0; \n        task_data.cell_matrix = 0; \n        task_data.cell_vector = 0; \n      } \n    scratch.fe_values_local.reinit(loc_cell); \n\n// \u6211\u4eec\u9996\u5148\u8ba1\u7b97\u5bf9\u5e94\u4e8e\u5c40\u90e8-\u5c40\u90e8\u8026\u5408\u7684 @p ll_matrix \u77e9\u9635\uff08\u5728\u4ecb\u7ecd\u4e2d\u79f0\u4e3a\u77e9\u9635 $A$ \uff09\u7684\u5355\u5143\u5185\u90e8\u8d21\u732e\uff0c\u4ee5\u53ca\u5c40\u90e8\u53f3\u624b\u5411\u91cf\u3002 \u6211\u4eec\u5728\u6bcf\u4e2a\u6b63\u4ea4\u70b9\u5b58\u50a8\u57fa\u51fd\u6570\u3001\u53f3\u624b\u8fb9\u503c\u548c\u5bf9\u6d41\u901f\u5ea6\u7684\u503c\uff0c\u4ee5\u4fbf\u5feb\u901f\u8bbf\u95ee\u8fd9\u4e9b\u573a\u3002\n\n    for (unsigned int q = 0; q < n_q_points; ++q) \n      { \n        const double rhs_value = scratch.right_hand_side.value( \n          scratch.fe_values_local.quadrature_point(q)); \n        const Tensor<1, dim> convection = scratch.convection_velocity.value( \n          scratch.fe_values_local.quadrature_point(q)); \n        const double JxW = scratch.fe_values_local.JxW(q); \n        for (unsigned int k = 0; k < loc_dofs_per_cell; ++k) \n          { \n            scratch.q_phi[k] = scratch.fe_values_local[fluxes].value(k, q); \n            scratch.q_phi_div[k] = \n              scratch.fe_values_local[fluxes].divergence(k, q); \n            scratch.u_phi[k] = scratch.fe_values_local[scalar].value(k, q); \n            scratch.u_phi_grad[k] = \n              scratch.fe_values_local[scalar].gradient(k, q); \n          } \n        for (unsigned int i = 0; i < loc_dofs_per_cell; ++i) \n          { \n            for (unsigned int j = 0; j < loc_dofs_per_cell; ++j) \n              scratch.ll_matrix(i, j) += \n                (scratch.q_phi[i] * scratch.q_phi[j] - \n                 scratch.q_phi_div[i] * scratch.u_phi[j] + \n                 scratch.u_phi[i] * scratch.q_phi_div[j] - \n                 (scratch.u_phi_grad[i] * convection) * scratch.u_phi[j]) * \n                JxW; \n            scratch.l_rhs(i) += scratch.u_phi[i] * rhs_value * JxW; \n          } \n      } \n\n// \u8138\u90e8\u6761\u6b3e\u662f\u5728\u6240\u6709\u5143\u7d20\u7684\u6240\u6709\u9762\u4e0a\u96c6\u5408\u8d77\u6765\u7684\u3002\u8fd9\u4e0e\u66f4\u4f20\u7edf\u7684DG\u65b9\u6cd5\u76f8\u53cd\uff0c\u5728\u7ec4\u88c5\u8fc7\u7a0b\u4e2d\uff0c\u6bcf\u4e2a\u9762\u53ea\u88ab\u8bbf\u95ee\u4e00\u6b21\u3002\n\n    for (const auto face_no : cell->face_indices()) \n      { \n        scratch.fe_face_values_local.reinit(loc_cell, face_no); \n        scratch.fe_face_values.reinit(cell, face_no); \n\n// \u5728\u6c42\u89e3\u5c40\u90e8\u53d8\u91cf\u65f6\u9700\u8981\u5df2\u7ecf\u5f97\u5230\u7684  $\\hat{u}$  \u503c\u3002\n\n        if (task_data.trace_reconstruct) \n          scratch.fe_face_values.get_function_values(solution, \n                                                     scratch.trace_values); \n\n        for (unsigned int q = 0; q < n_face_q_points; ++q) \n          { \n            const double     JxW = scratch.fe_face_values.JxW(q); \n            const Point<dim> quadrature_point = \n              scratch.fe_face_values.quadrature_point(q); \n            const Tensor<1, dim> normal = \n              scratch.fe_face_values.normal_vector(q); \n            const Tensor<1, dim> convection = \n              scratch.convection_velocity.value(quadrature_point); \n\n// \u8fd9\u91cc\u6211\u4eec\u8ba1\u7b97\u4ecb\u7ecd\u4e2d\u8ba8\u8bba\u7684\u7a33\u5b9a\u53c2\u6570\uff1a\u7531\u4e8e\u6269\u6563\u662f1\uff0c\u5e76\u4e14\u6269\u6563\u957f\u5ea6\u5c3a\u5ea6\u88ab\u8bbe\u5b9a\u4e3a1/5\uff0c\u5b83\u53ea\u662f\u5bfc\u81f4\u6269\u6563\u90e8\u5206\u7684\u8d21\u732e\u4e3a5\uff0c\u800c\u5bf9\u6d41\u90e8\u5206\u7684\u8d21\u732e\u662f\u901a\u8fc7\u5143\u7d20\u8fb9\u754c\u7684\u5c45\u4e2d\u65b9\u6848\u4e2d\u7684\u5bf9\u6d41\u5927\u5c0f\u3002\n\n            const double tau_stab = (5. + std::abs(convection * normal)); \n\n// \u6211\u4eec\u5b58\u50a8\u975e\u96f6\u901a\u91cf\u548c\u6807\u91cf\u503c\uff0c\u5229\u7528\u6211\u4eec\u5728 @p ScratchData. \u4e2d\u521b\u5efa\u7684 support_on_face \u4fe1\u606f\u3002\n            for (unsigned int k = 0; \n                 k < scratch.fe_local_support_on_face[face_no].size(); \n                 ++k) \n              { \n                const unsigned int kk = \n                  scratch.fe_local_support_on_face[face_no][k]; \n                scratch.q_phi[k] = \n                  scratch.fe_face_values_local[fluxes].value(kk, q); \n                scratch.u_phi[k] = \n                  scratch.fe_face_values_local[scalar].value(kk, q); \n              } \n\n// \u5f53  @p trace_reconstruct=false,  \u6211\u4eec\u51c6\u5907\u4e3a\u9aa8\u67b6\u53d8\u91cf  $\\hat{u}$  \u7ec4\u88c5\u7cfb\u7edf\u3002\u5982\u679c\u662f\u8fd9\u79cd\u60c5\u51b5\uff0c\u6211\u4eec\u5fc5\u987b\u7ec4\u88c5\u6240\u6709\u4e0e\u95ee\u9898\u76f8\u5173\u7684\u5c40\u90e8\u77e9\u9635\uff1a\u5c40\u90e8-\u5c40\u90e8\u3001\u5c40\u90e8-\u9762\u90e8\u3001\u9762\u90e8-\u5c40\u90e8\u548c\u9762\u90e8-\u9762\u90e8\u3002 \u9762-\u9762\u77e9\u9635\u88ab\u5b58\u50a8\u4e3a @p TaskData::cell_matrix, \uff0c\u8fd9\u6837\u5c31\u53ef\u4ee5\u901a\u8fc7 @p copy_local_to_global\u5c06\u5176\u7ec4\u88c5\u5230\u5168\u5c40\u7cfb\u7edf\u4e2d\u3002\n\n            if (!task_data.trace_reconstruct) \n              { \n                for (unsigned int k = 0; \n                     k < scratch.fe_support_on_face[face_no].size(); \n                     ++k) \n                  scratch.tr_phi[k] = scratch.fe_face_values.shape_value( \n                    scratch.fe_support_on_face[face_no][k], q); \n                for (unsigned int i = 0; \n                     i < scratch.fe_local_support_on_face[face_no].size(); \n                     ++i) \n                  for (unsigned int j = 0; \n                       j < scratch.fe_support_on_face[face_no].size(); \n                       ++j) \n                    { \n                      const unsigned int ii = \n                        scratch.fe_local_support_on_face[face_no][i]; \n                      const unsigned int jj = \n                        scratch.fe_support_on_face[face_no][j]; \n                      scratch.lf_matrix(ii, jj) += \n                        ((scratch.q_phi[i] * normal + \n                          (convection * normal - tau_stab) * scratch.u_phi[i]) * \n                         scratch.tr_phi[j]) * \n                        JxW; \n\n// \u6ce8\u610fface_no-local\u77e9\u9635\u7684\u7b26\u53f7\u3002 \u6211\u4eec\u5728\u7ec4\u88c5\u65f6\u5426\u5b9a\u4e86\u8fd9\u4e2a\u7b26\u53f7\uff0c\u8fd9\u6837\u6211\u4eec\u5c31\u53ef\u4ee5\u5728\u8ba1\u7b97\u8212\u5c14\u8865\u65f6\u4f7f\u7528 FullMatrix::mmult \u7684\u52a0\u6cd5\u3002\n\n                      scratch.fl_matrix(jj, ii) -= \n                        ((scratch.q_phi[i] * normal + \n                          tau_stab * scratch.u_phi[i]) * \n                         scratch.tr_phi[j]) * \n                        JxW; \n                    } \n\n                for (unsigned int i = 0; \n                     i < scratch.fe_support_on_face[face_no].size(); \n                     ++i) \n                  for (unsigned int j = 0; \n                       j < scratch.fe_support_on_face[face_no].size(); \n                       ++j) \n                    { \n                      const unsigned int ii = \n                        scratch.fe_support_on_face[face_no][i]; \n                      const unsigned int jj = \n                        scratch.fe_support_on_face[face_no][j]; \n                      task_data.cell_matrix(ii, jj) += \n                        ((convection * normal - tau_stab) * scratch.tr_phi[i] * \n                         scratch.tr_phi[j]) * \n                        JxW; \n                    } \n\n                if (cell->face(face_no)->at_boundary() && \n                    (cell->face(face_no)->boundary_id() == 1)) \n                  { \n                    const double neumann_value = \n                      -scratch.exact_solution.gradient(quadrature_point) * \n                        normal + \n                      convection * normal * \n                        scratch.exact_solution.value(quadrature_point); \n                    for (unsigned int i = 0; \n                         i < scratch.fe_support_on_face[face_no].size(); \n                         ++i) \n                      { \n                        const unsigned int ii = \n                          scratch.fe_support_on_face[face_no][i]; \n                        task_data.cell_vector(ii) += \n                          scratch.tr_phi[i] * neumann_value * JxW; \n                      } \n                  } \n              } \n\n// \u8fd9\u6700\u540e\u4e00\u4e2a\u9879\u5c06 $\\left<w,\\tau u_h\\right>_{\\partial \\mathcal T}$ \u9879\u7684\u8d21\u732e\u52a0\u5165\u5230\u672c\u5730\u77e9\u9635\u4e2d\u3002\u76f8\u5bf9\u4e8e\u4e0a\u9762\u7684\u8138\u90e8\u77e9\u9635\uff0c\u6211\u4eec\u5728\u4e24\u4e2a\u88c5\u914d\u9636\u6bb5\u90fd\u9700\u8981\u5b83\u3002\n\n            for (unsigned int i = 0; \n                 i < scratch.fe_local_support_on_face[face_no].size(); \n                 ++i) \n              for (unsigned int j = 0; \n                   j < scratch.fe_local_support_on_face[face_no].size(); \n                   ++j) \n                { \n                  const unsigned int ii = \n                    scratch.fe_local_support_on_face[face_no][i]; \n                  const unsigned int jj = \n                    scratch.fe_local_support_on_face[face_no][j]; \n                  scratch.ll_matrix(ii, jj) += \n                    tau_stab * scratch.u_phi[i] * scratch.u_phi[j] * JxW; \n                } \n\n// \u5f53 @p trace_reconstruct=true, \u65f6\uff0c\u6211\u4eec\u5728\u9010\u4e2a\u5143\u7d20\u7684\u57fa\u7840\u4e0a\u6c42\u89e3\u5c40\u90e8\u89e3\u3002 \u5c40\u90e8\u53f3\u624b\u8fb9\u7684\u8ba1\u7b97\u662f\u901a\u8fc7\u7528\u8ba1\u7b97\u503c @p trace_values\u66ff\u6362 @p \u8ba1\u7b97\u4e2d\u7684\u57fa\u51fd\u6570 @p tr_phi\u3002 \u5f53\u7136\uff0c\u73b0\u5728\u77e9\u9635\u7684\u7b26\u53f7\u662f\u51cf\u53f7\uff0c\u56e0\u4e3a\u6211\u4eec\u5df2\u7ecf\u628a\u6240\u6709\u7684\u4e1c\u897f\u79fb\u5230\u4e86\u65b9\u7a0b\u7684\u53e6\u4e00\u8fb9\u3002\n\n            if (task_data.trace_reconstruct) \n              for (unsigned int i = 0; \n                   i < scratch.fe_local_support_on_face[face_no].size(); \n                   ++i) \n                { \n                  const unsigned int ii = \n                    scratch.fe_local_support_on_face[face_no][i]; \n                  scratch.l_rhs(ii) -= \n                    (scratch.q_phi[i] * normal + \n                     scratch.u_phi[i] * (convection * normal - tau_stab)) * \n                    scratch.trace_values[q] * JxW; \n                } \n          } \n      } \n\n// \u4e00\u65e6\u5b8c\u6210\u6240\u6709\u5c40\u90e8\u8d21\u732e\u7684\u7ec4\u88c5\uff0c\u6211\u4eec\u5fc5\u987b\uff1a\uff081\uff09\u7ec4\u88c5\u5168\u5c40\u7cfb\u7edf\uff1b\uff082\uff09\u8ba1\u7b97\u5c40\u90e8\u8d21\u732e\u3002(1)\u7ec4\u88c5\u5168\u5c40\u7cfb\u7edf\uff0c\u6216\u8005(2)\u8ba1\u7b97\u5c40\u90e8\u89e3\u503c\u5e76\u4fdd\u5b58\u3002\u65e0\u8bba\u54ea\u79cd\u60c5\u51b5\uff0c\u7b2c\u4e00\u6b65\u90fd\u662f\u5bf9\u5c40\u90e8-\u5c40\u90e8\u77e9\u9635\u8fdb\u884c\u53cd\u8f6c\u3002\n\n    scratch.ll_matrix.gauss_jordan(); \n\n// \u5bf9\u4e8e(1)\uff0c\u6211\u4eec\u8ba1\u7b97\u8212\u5c14\u8865\u7801\uff0c\u5e76\u5c06\u5176\u6dfb\u52a0\u5230 @p  cell_matrix\uff0c\u4ecb\u7ecd\u4e2d\u7684\u77e9\u9635 $D$ \u3002\n\n    if (task_data.trace_reconstruct == false) \n      { \n        scratch.fl_matrix.mmult(scratch.tmp_matrix, scratch.ll_matrix); \n        scratch.tmp_matrix.vmult_add(task_data.cell_vector, scratch.l_rhs); \n        scratch.tmp_matrix.mmult(task_data.cell_matrix, \n                                 scratch.lf_matrix, \n                                 true); \n        cell->get_dof_indices(task_data.dof_indices); \n      } \n\n// \u5bf9\u4e8e(2)\uff0c\u6211\u4eec\u53ea\u662f\u6c42\u89e3(ll_matrix). (solution_local) = (l_rhs)\u3002\u56e0\u6b64\uff0c\u6211\u4eec\u7528 @p l_rhs \u4e58\u4ee5\u6211\u4eec\u5df2\u7ecf\u5012\u7f6e\u7684\u5c40\u90e8-\u5c40\u90e8\u77e9\u9635\uff0c\u5e76\u7528 <code>set_dof_values</code> \u51fd\u6570\u6765\u5b58\u50a8\u7ed3\u679c\u3002\n\n    else \n      { \n        scratch.ll_matrix.vmult(scratch.tmp_rhs, scratch.l_rhs); \n        loc_cell->set_dof_values(scratch.tmp_rhs, solution_local); \n      } \n  } \n\n// \u5982\u679c\u6211\u4eec\u5904\u4e8e\u89e3\u9898\u7684\u7b2c\u4e00\u6b65\uff0c\u5373 @sect4{HDG::copy_local_to_global} \uff0c\u90a3\u4e48\u6211\u4eec\u5c31\u628a\u5c40\u90e8\u77e9\u9635\u7ec4\u88c5\u5230\u5168\u5c40\u7cfb\u7edf\u4e2d\u3002\n\n  template <int dim> \n  void HDG<dim>::copy_local_to_global(const PerTaskData &data) \n  { \n    if (data.trace_reconstruct == false) \n      constraints.distribute_local_to_global(data.cell_matrix, \n                                             data.cell_vector, \n                                             data.dof_indices, \n                                             system_matrix, \n                                             system_rhs); \n  } \n\n//  @sect4{HDG::solve}  \u9aa8\u67b6\u89e3\u662f\u901a\u8fc7\u4f7f\u7528\u5e26\u6709\u8eab\u4efd\u9884\u5904\u7406\u7a0b\u5e8f\u7684BiCGStab\u6c42\u89e3\u5668\u6765\u89e3\u51b3\u7684\u3002\n\n  template <int dim> \n  void HDG<dim>::solve() \n  { \n    SolverControl                  solver_control(system_matrix.m() * 10, \n                                 1e-11 * system_rhs.l2_norm()); \n    SolverBicgstab<Vector<double>> solver(solver_control); \n    solver.solve(system_matrix, solution, system_rhs, PreconditionIdentity()); \n\n    std::cout << \"   Number of BiCGStab iterations: \" \n              << solver_control.last_step() << std::endl; \n\n    system_matrix.clear(); \n    sparsity_pattern.reinit(0, 0, 0, 1); \n\n    constraints.distribute(solution); \n\n// \u4e00\u65e6\u6211\u4eec\u6c42\u51fa\u4e86\u9aa8\u67b6\u89e3\uff0c\u6211\u4eec\u5c31\u53ef\u4ee5\u4ee5\u9010\u4e2a\u5143\u7d20\u7684\u65b9\u5f0f\u6c42\u51fa\u5c40\u90e8\u89e3\u3002 \u6211\u4eec\u901a\u8fc7\u91cd\u65b0\u4f7f\u7528\u76f8\u540c\u7684 @p assemble_system \u51fd\u6570\u6765\u505a\u5230\u8fd9\u4e00\u70b9\uff0c\u4f46\u5c06 @p trace_reconstruct \u5207\u6362\u4e3a\u771f\u3002\n\n    assemble_system(true); \n  } \n\n//  @sect4{HDG::postprocess}  \n\n// \u540e\u5904\u7406\u65b9\u6cd5\u6709\u4e24\u4e2a\u76ee\u7684\u3002\u9996\u5148\uff0c\u6211\u4eec\u8981\u5728\u5ea6\u6570\u4e3a $p+1$ \u7684\u5143\u7d20\u7a7a\u95f4\u4e2d\u6784\u9020\u4e00\u4e2a\u540e\u5904\u7406\u7684\u6807\u91cf\u53d8\u91cf\uff0c\u6211\u4eec\u5e0c\u671b\u5b83\u80fd\u5728\u9636 $p+2$ \u4e0a\u6536\u655b\u3002\u8fd9\u4e5f\u662f\u4e00\u4e2a\u9010\u4e2a\u5143\u7d20\u7684\u8fc7\u7a0b\uff0c\u53ea\u6d89\u53ca\u6807\u91cf\u89e3\u4ee5\u53ca\u5c40\u90e8\u5355\u5143\u4e0a\u7684\u68af\u5ea6\u3002\u4e3a\u4e86\u505a\u5230\u8fd9\u4e00\u70b9\uff0c\u6211\u4eec\u5f15\u5165\u4e86\u5df2\u7ecf\u5b9a\u4e49\u597d\u7684\u4ece\u5934\u5f00\u59cb\u7684\u6570\u636e\u4ee5\u53ca\u4e00\u4e9b\u66f4\u65b0\u6807\u5fd7\uff0c\u5e76\u8fd0\u884c\u5de5\u4f5c\u6d41\u6765\u5e76\u884c\u5730\u5b8c\u6210\u8fd9\u4e00\u5de5\u4f5c\u3002\n\n// \u7b2c\u4e8c\uff0c\u6211\u4eec\u8981\u8ba1\u7b97\u79bb\u6563\u5316\u8bef\u5dee\uff0c\u5c31\u50cf\u6211\u4eec\u5728  step-7  \u4e2d\u505a\u7684\u90a3\u6837\u3002\u6574\u4e2a\u8fc7\u7a0b\u4e0e\u8c03\u7528 VectorTools::integrate_difference. \u76f8\u4f3c\uff0c\u533a\u522b\u5728\u4e8e\u6211\u4eec\u5982\u4f55\u8ba1\u7b97\u6807\u91cf\u53d8\u91cf\u548c\u68af\u5ea6\u53d8\u91cf\u7684\u8bef\u5dee\u3002\u5728 step-7 \u4e2d\uff0c\u6211\u4eec\u901a\u8fc7\u8ba1\u7b97 @p L2_norm \u6216 @p H1_seminorm \u7684\u8d21\u732e\u6765\u505a\u5230\u8fd9\u4e00\u70b9\u3002\u5728\u8fd9\u91cc\uff0c\u6211\u4eec\u6709\u4e00\u4e2aDoFHandler\uff0c\u8ba1\u7b97\u4e86\u8fd9\u4e24\u4e2a\u8d21\u732e\uff0c\u5e76\u6309\u5176\u77e2\u91cf\u5206\u91cf\u6392\u5e8f\uff0c <code>[0, dim)</code> \u4e3a\u68af\u5ea6\uff0c @p dim \u4e3a\u6807\u91cf\u3002\u4e3a\u4e86\u8ba1\u7b97\u5b83\u4eec\u7684\u503c\uff0c\u6211\u4eec\u7528\u4e00\u4e2aComponentSelectFunction\u6765\u8ba1\u7b97\u5b83\u4eec\u4e2d\u7684\u4efb\u4f55\u4e00\u4e2a\uff0c\u518d\u52a0\u4e0a\u4e0a\u9762\u4ecb\u7ecd\u7684 @p SolutionAndGradient\u7c7b\uff0c\u5b83\u5305\u542b\u4e86\u5b83\u4eec\u4e2d\u4efb\u4f55\u4e00\u4e2a\u7684\u5206\u6790\u90e8\u5206\u3002\u6700\u7ec8\uff0c\u6211\u4eec\u8fd8\u8ba1\u7b97\u4e86\u540e\u5904\u7406\u7684\u89e3\u51b3\u65b9\u6848\u7684L2-\u8bef\u5dee\uff0c\u5e76\u5c06\u7ed3\u679c\u6dfb\u52a0\u5230\u6536\u655b\u8868\u4e2d\u3002\n\n  template <int dim> \n  void HDG<dim>::postprocess() \n  { \n    { \n      const QGauss<dim> quadrature_formula(fe_u_post.degree + 1); \n      const UpdateFlags local_flags(update_values); \n      const UpdateFlags flags(update_values | update_gradients | \n                              update_JxW_values); \n\n      PostProcessScratchData scratch( \n        fe_u_post, fe_local, quadrature_formula, local_flags, flags); \n\n      WorkStream::run( \n        dof_handler_u_post.begin_active(), \n        dof_handler_u_post.end(), \n        [this](const typename DoFHandler<dim>::active_cell_iterator &cell, \n               PostProcessScratchData &                              scratch, \n               unsigned int &                                        data) { \n          this->postprocess_one_cell(cell, scratch, data); \n        }, \n        std::function<void(const unsigned int &)>(), \n        scratch, \n        0U); \n    } \n\n    Vector<float> difference_per_cell(triangulation.n_active_cells()); \n\n    ComponentSelectFunction<dim> value_select(dim, dim + 1); \n    VectorTools::integrate_difference(dof_handler_local, \n                                      solution_local, \n                                      SolutionAndGradient<dim>(), \n                                      difference_per_cell, \n                                      QGauss<dim>(fe.degree + 2), \n                                      VectorTools::L2_norm, \n                                      &value_select); \n    const double L2_error = \n      VectorTools::compute_global_error(triangulation, \n                                        difference_per_cell, \n                                        VectorTools::L2_norm); \n\n    ComponentSelectFunction<dim> gradient_select( \n      std::pair<unsigned int, unsigned int>(0, dim), dim + 1); \n    VectorTools::integrate_difference(dof_handler_local, \n                                      solution_local, \n                                      SolutionAndGradient<dim>(), \n                                      difference_per_cell, \n                                      QGauss<dim>(fe.degree + 2), \n                                      VectorTools::L2_norm, \n                                      &gradient_select); \n    const double grad_error = \n      VectorTools::compute_global_error(triangulation, \n                                        difference_per_cell, \n                                        VectorTools::L2_norm); \n\n    VectorTools::integrate_difference(dof_handler_u_post, \n                                      solution_u_post, \n                                      Solution<dim>(), \n                                      difference_per_cell, \n                                      QGauss<dim>(fe.degree + 3), \n                                      VectorTools::L2_norm); \n    const double post_error = \n      VectorTools::compute_global_error(triangulation, \n                                        difference_per_cell, \n                                        VectorTools::L2_norm); \n\n    convergence_table.add_value(\"cells\", triangulation.n_active_cells()); \n    convergence_table.add_value(\"dofs\", dof_handler.n_dofs()); \n\n    convergence_table.add_value(\"val L2\", L2_error); \n    convergence_table.set_scientific(\"val L2\", true); \n    convergence_table.set_precision(\"val L2\", 3); \n\n    convergence_table.add_value(\"grad L2\", grad_error); \n    convergence_table.set_scientific(\"grad L2\", true); \n    convergence_table.set_precision(\"grad L2\", 3); \n\n    convergence_table.add_value(\"val L2-post\", post_error); \n    convergence_table.set_scientific(\"val L2-post\", true); \n    convergence_table.set_precision(\"val L2-post\", 3); \n  } \n\n//  @sect4{HDG::postprocess_one_cell}  \n\n// \u8fd9\u662f\u4e3a\u540e\u5904\u7406\u6240\u505a\u7684\u5b9e\u9645\u5de5\u4f5c\u3002\u6839\u636e\u4ecb\u7ecd\u4e2d\u7684\u8ba8\u8bba\uff0c\u6211\u4eec\u9700\u8981\u5efa\u7acb\u4e00\u4e2a\u7cfb\u7edf\uff0c\u5c06DG\u89e3\u7684\u68af\u5ea6\u90e8\u5206\u6295\u5f71\u5230\u540e\u5904\u7406\u53d8\u91cf\u7684\u68af\u5ea6\u4e0a\u3002\u6b64\u5916\uff0c\u6211\u4eec\u8fd8\u9700\u8981\u5c06\u65b0\u7684\u540e\u5904\u7406\u53d8\u91cf\u7684\u5e73\u5747\u503c\u8bbe\u7f6e\u4e3a\u7b49\u4e8e\u6807\u91cfDG\u89e3\u5728\u5355\u5143\u4e0a\u7684\u5e73\u5747\u503c\u3002\n\n// \u4ece\u6280\u672f\u4e0a\u8bb2\uff0c\u68af\u5ea6\u7684\u6295\u5f71\u662f\u4e00\u4e2a\u6709\u53ef\u80fd\u586b\u6ee1\u6211\u4eec\u7684 @p dofs_per_cell \u4e58\u4ee5 @p dofs_per_cell \u77e9\u9635\u7684\u7cfb\u7edf\uff0c\u4f46\u5b83\u662f\u5355\u6570\uff08\u6240\u6709\u884c\u7684\u603b\u548c\u4e3a\u96f6\uff0c\u56e0\u4e3a\u5e38\u6570\u51fd\u6570\u7684\u68af\u5ea6\u4e3a\u96f6\uff09\u3002\u56e0\u6b64\uff0c\u6211\u4eec\u62ff\u6389\u4e00\u884c\uff0c\u7528\u5b83\u6765\u5f3a\u52a0\u6807\u91cf\u503c\u7684\u5e73\u5747\u503c\u3002\u6211\u4eec\u4e3a\u6807\u91cf\u90e8\u5206\u6311\u9009\u7b2c\u4e00\u884c\uff0c\u5c3d\u7ba1\u6211\u4eec\u53ef\u4ee5\u4e3a $\\mathcal Q_{-p}$ \u5143\u7d20\u6311\u9009\u4efb\u4f55\u4e00\u884c\u3002\u7136\u800c\uff0c\u5982\u679c\u6211\u4eec\u4f7f\u7528FE_DGP\u5143\u7d20\uff0c\u7b2c\u4e00\u884c\u5c06\u5bf9\u5e94\u5e38\u6570\u90e8\u5206\uff0c\u5220\u9664\u4f8b\u5982\u6700\u540e\u4e00\u884c\u5c06\u5f97\u5230\u4e00\u4e2a\u5947\u5f02\u7cfb\u7edf\u3002\u8fd9\u6837\u4e00\u6765\uff0c\u6211\u4eec\u7684\u7a0b\u5e8f\u4e5f\u53ef\u4ee5\u7528\u4e8e\u8fd9\u4e9b\u5143\u7d20\u3002\n\n  template <int dim> \n  void HDG<dim>::postprocess_one_cell( \n    const typename DoFHandler<dim>::active_cell_iterator &cell, \n    PostProcessScratchData &                              scratch, \n    unsigned int &) \n  { \n    typename DoFHandler<dim>::active_cell_iterator loc_cell(&triangulation, \n                                                            cell->level(), \n                                                            cell->index(), \n                                                            &dof_handler_local); \n\n    scratch.fe_values_local.reinit(loc_cell); \n    scratch.fe_values.reinit(cell); \n\n    FEValuesExtractors::Vector fluxes(0); \n    FEValuesExtractors::Scalar scalar(dim); \n\n    const unsigned int n_q_points = scratch.fe_values.get_quadrature().size(); \n    const unsigned int dofs_per_cell = scratch.fe_values.dofs_per_cell; \n\n    scratch.fe_values_local[scalar].get_function_values(solution_local, \n                                                        scratch.u_values); \n    scratch.fe_values_local[fluxes].get_function_values(solution_local, \n                                                        scratch.u_gradients); \n\n    double sum = 0; \n    for (unsigned int i = 1; i < dofs_per_cell; ++i) \n      { \n        for (unsigned int j = 0; j < dofs_per_cell; ++j) \n          { \n            sum = 0; \n            for (unsigned int q = 0; q < n_q_points; ++q) \n              sum += (scratch.fe_values.shape_grad(i, q) * \n                      scratch.fe_values.shape_grad(j, q)) * \n                     scratch.fe_values.JxW(q); \n            scratch.cell_matrix(i, j) = sum; \n          } \n\n        sum = 0; \n        for (unsigned int q = 0; q < n_q_points; ++q) \n          sum -= (scratch.fe_values.shape_grad(i, q) * scratch.u_gradients[q]) * \n                 scratch.fe_values.JxW(q); \n        scratch.cell_rhs(i) = sum; \n      } \n    for (unsigned int j = 0; j < dofs_per_cell; ++j) \n      { \n        sum = 0; \n        for (unsigned int q = 0; q < n_q_points; ++q) \n          sum += scratch.fe_values.shape_value(j, q) * scratch.fe_values.JxW(q); \n        scratch.cell_matrix(0, j) = sum; \n      } \n    { \n      sum = 0; \n      for (unsigned int q = 0; q < n_q_points; ++q) \n        sum += scratch.u_values[q] * scratch.fe_values.JxW(q); \n      scratch.cell_rhs(0) = sum; \n    } \n\n// \u96c6\u5408\u4e86\u6240\u6709\u6761\u6b3e\u540e\uff0c\u6211\u4eec\u53c8\u53ef\u4ee5\u7ee7\u7eed\u89e3\u51b3\u8fd9\u4e2a\u7ebf\u6027\u7cfb\u7edf\u3002\u6211\u4eec\u5bf9\u77e9\u9635\u8fdb\u884c\u53cd\u8f6c\uff0c\u7136\u540e\u5c06\u53cd\u8f6c\u7ed3\u679c\u4e58\u4ee5\u53f3\u624b\u8fb9\u3002\u53e6\u4e00\u79cd\u65b9\u6cd5\uff08\u6570\u5b57\u4e0a\u66f4\u7a33\u5b9a\uff09\u662f\u53ea\u5bf9\u77e9\u9635\u8fdb\u884c\u56e0\u5f0f\u5206\u89e3\uff0c\u7136\u540e\u5e94\u7528\u56e0\u5f0f\u5206\u89e3\u3002\n\n    scratch.cell_matrix.gauss_jordan(); \n    scratch.cell_matrix.vmult(scratch.cell_sol, scratch.cell_rhs); \n    cell->distribute_local_to_global(scratch.cell_sol, solution_u_post); \n  } \n\n//  @sect4{HDG::output_results}  \u6211\u4eec\u6709\u4e09\u7ec4\u6211\u4eec\u60f3\u8f93\u51fa\u7684\u7ed3\u679c\uff1a\u5c40\u90e8\u89e3\u51b3\u65b9\u6848\uff0c\u540e\u5904\u7406\u7684\u5c40\u90e8\u89e3\u51b3\u65b9\u6848\uff0c\u4ee5\u53ca\u9aa8\u67b6\u89e3\u51b3\u65b9\u6848\u3002\u524d\u4e24\u4e2a\u7ed3\u679c\u90fd \"\u6d3b \"\u5728\u5143\u7d20\u4f53\u79ef\u4e0a\uff0c\u800c\u540e\u8005\u5219\u6d3b\u5728\u4e09\u89d2\u5f62\u7684\u4e00\u7ef4\u8868\u9762\u4e0a\u3002 \u6211\u4eec\u7684 @p output_results \u51fd\u6570\u5c06\u6240\u6709\u7684\u5c40\u90e8\u89e3\u51b3\u65b9\u6848\u5199\u5165\u540c\u4e00\u4e2avtk\u6587\u4ef6\uff0c\u5c3d\u7ba1\u5b83\u4eec\u5bf9\u5e94\u4e8e\u4e0d\u540c\u7684DoFHandler\u5bf9\u8c61\u3002 \u9aa8\u67b6\u53d8\u91cf\u7684\u56fe\u5f62\u8f93\u51fa\u662f\u901a\u8fc7\u4f7f\u7528DataOutFaces\u7c7b\u5b8c\u6210\u7684\u3002\n\n  template <int dim> \n  void HDG<dim>::output_results(const unsigned int cycle) \n  { \n    std::string filename; \n    switch (refinement_mode) \n      { \n        case global_refinement: \n          filename = \"solution-global\"; \n          break; \n        case adaptive_refinement: \n          filename = \"solution-adaptive\"; \n          break; \n        default: \n          Assert(false, ExcNotImplemented()); \n      } \n\n    std::string face_out(filename); \n    face_out += \"-face\"; \n\n    filename += \"-q\" + Utilities::int_to_string(fe.degree, 1); \n    filename += \"-\" + Utilities::int_to_string(cycle, 2); \n    filename += \".vtk\"; \n    std::ofstream output(filename); \n\n    DataOut<dim> data_out; \n\n// \u6211\u4eec\u9996\u5148\u5b9a\u4e49\u672c\u5730\u89e3\u51b3\u65b9\u6848\u7684\u540d\u79f0\u548c\u7c7b\u578b\uff0c\u5e76\u5c06\u6570\u636e\u6dfb\u52a0\u5230  @p data_out.  \u4e2d\u3002\n    std::vector<std::string> names(dim, \"gradient\"); \n    names.emplace_back(\"solution\"); \n    std::vector<DataComponentInterpretation::DataComponentInterpretation> \n      component_interpretation( \n        dim + 1, DataComponentInterpretation::component_is_part_of_vector); \n    component_interpretation[dim] = \n      DataComponentInterpretation::component_is_scalar; \n    data_out.add_data_vector(dof_handler_local, \n                             solution_local, \n                             names, \n                             component_interpretation); \n\n// \u6211\u4eec\u6dfb\u52a0\u7684\u7b2c\u4e8c\u4e2a\u6570\u636e\u9879\u662f\u540e\u5904\u7406\u7684\u89e3\u51b3\u65b9\u6848\u3002\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0c\u5b83\u662f\u4e00\u4e2a\u5c5e\u4e8e\u4e0d\u540cDoFHandler\u7684\u5355\u4e00\u6807\u91cf\u53d8\u91cf\u3002\n\n    std::vector<std::string> post_name(1, \"u_post\"); \n    std::vector<DataComponentInterpretation::DataComponentInterpretation> \n      post_comp_type(1, DataComponentInterpretation::component_is_scalar); \n    data_out.add_data_vector(dof_handler_u_post, \n                             solution_u_post, \n                             post_name, \n                             post_comp_type); \n\n    data_out.build_patches(fe.degree); \n    data_out.write_vtk(output); \n\n    face_out += \"-q\" + Utilities::int_to_string(fe.degree, 1); \n    face_out += \"-\" + Utilities::int_to_string(cycle, 2); \n    face_out += \".vtk\"; \n    std::ofstream face_output(face_out); \n\n//  <code>DataOutFaces</code> \u7c7b\u7684\u5de5\u4f5c\u539f\u7406\u4e0e <code>DataOut</code> class when we have a <code>DoFHandler</code> \u7c7b\u4f3c\uff0c\u540e\u8005\u5b9a\u4e49\u4e86\u4e09\u89d2\u5f62\u9aa8\u67b6\u4e0a\u7684\u89e3\u51b3\u65b9\u6848\u3002 \u6211\u4eec\u5728\u6b64\u5c06\u5176\u89c6\u4e3a\u5982\u6b64\uff0c\u4ee3\u7801\u4e0e\u4e0a\u9762\u7c7b\u4f3c\u3002\n\n    DataOutFaces<dim>        data_out_face(false); \n    std::vector<std::string> face_name(1, \"u_hat\"); \n    std::vector<DataComponentInterpretation::DataComponentInterpretation> \n      face_component_type(1, DataComponentInterpretation::component_is_scalar); \n\n    data_out_face.add_data_vector(dof_handler, \n                                  solution, \n                                  face_name, \n                                  face_component_type); \n\n    data_out_face.build_patches(fe.degree); \n    data_out_face.write_vtk(face_output); \n  } \n// @sect4{HDG::refine_grid}  \n\n// \u6211\u4eec\u4e3aHDG\u5b9e\u73b0\u4e86\u4e24\u79cd\u4e0d\u540c\u7684\u7ec6\u5316\u60c5\u51b5\uff0c\u5c31\u50cf\u5728 <code>Step-7</code> \u4e2d\u4e00\u6837\uff1aadaptive_refinement\u548cglobal_refinement\u3002 global_refinement\u9009\u9879\u6bcf\u6b21\u90fd\u4f1a\u91cd\u65b0\u521b\u5efa\u6574\u4e2a\u4e09\u89d2\u5f62\u3002\u8fd9\u662f\u56e0\u4e3a\u6211\u4eec\u60f3\u4f7f\u7528\u6bd4\u4e00\u4e2a\u7ec6\u5316\u6b65\u9aa4\u66f4\u7ec6\u7684\u7f51\u683c\u5e8f\u5217\uff0c\u5373\u6bcf\u4e2a\u65b9\u54112\u30013\u30014\u30016\u30018\u300112\u300116...\u4e2a\u5143\u7d20\u3002\n\n// adaptive_refinement\u6a21\u5f0f\u4f7f\u7528 <code>KellyErrorEstimator</code> \u5bf9\u6807\u91cf\u5c40\u90e8\u89e3\u4e2d\u7684\u975e\u89c4\u5219\u533a\u57df\u7ed9\u51fa\u4e00\u4e2a\u4f53\u9762\u7684\u6307\u793a\u3002\n\n  template <int dim> \n  void HDG<dim>::refine_grid(const unsigned int cycle) \n  { \n    if (cycle == 0) \n      { \n        GridGenerator::subdivided_hyper_cube(triangulation, 2, -1, 1); \n        triangulation.refine_global(3 - dim); \n      } \n    else \n      switch (refinement_mode) \n        { \n          case global_refinement: \n            { \n              triangulation.clear(); \n              GridGenerator::subdivided_hyper_cube(triangulation, \n                                                   2 + (cycle % 2), \n                                                   -1, \n                                                   1); \n              triangulation.refine_global(3 - dim + cycle / 2); \n              break; \n            } \n\n          case adaptive_refinement: \n            { \n              Vector<float> estimated_error_per_cell( \n                triangulation.n_active_cells()); \n\n              FEValuesExtractors::Scalar scalar(dim); \n              std::map<types::boundary_id, const Function<dim> *> \n                neumann_boundary; \n              KellyErrorEstimator<dim>::estimate(dof_handler_local, \n                                                 QGauss<dim - 1>(fe.degree + 1), \n                                                 neumann_boundary, \n                                                 solution_local, \n                                                 estimated_error_per_cell, \n                                                 fe_local.component_mask( \n                                                   scalar)); \n\n              GridRefinement::refine_and_coarsen_fixed_number( \n                triangulation, estimated_error_per_cell, 0.3, 0.); \n\n              triangulation.execute_coarsening_and_refinement(); \n\n              break; \n            } \n\n          default: \n            { \n              Assert(false, ExcNotImplemented()); \n            } \n        } \n\n// \u5c31\u50cf\u5728 step-7 \u4e2d\u4e00\u6837\uff0c\u6211\u4eec\u5c06\u5176\u4e2d\u4e24\u4e2a\u9762\u7684\u8fb9\u754c\u6307\u6807\u8bbe\u7f6e\u4e3a1\uff0c\u5728\u8fd9\u91cc\u6211\u4eec\u8981\u6307\u5b9a\u8bfa\u4f0a\u66fc\u8fb9\u754c\u6761\u4ef6\u800c\u4e0d\u662f\u8fea\u91cc\u5e0c\u7279\u6761\u4ef6\u3002\u7531\u4e8e\u6211\u4eec\u6bcf\u6b21\u90fd\u4f1a\u4e3a\u5168\u5c40\u7ec6\u5316\u91cd\u65b0\u521b\u5efa\u4e09\u89d2\u5f62\uff0c\u6240\u4ee5\u5728\u6bcf\u4e2a\u7ec6\u5316\u6b65\u9aa4\u4e2d\u90fd\u4f1a\u8bbe\u7f6e\u6807\u5fd7\uff0c\u800c\u4e0d\u4ec5\u4ec5\u662f\u5728\u5f00\u59cb\u65f6\u3002\n\n    for (const auto &cell : triangulation.cell_iterators()) \n      for (const auto &face : cell->face_iterators()) \n        if (face->at_boundary()) \n          if ((std::fabs(face->center()(0) - (-1)) < 1e-12) || \n              (std::fabs(face->center()(1) - (-1)) < 1e-12)) \n            face->set_boundary_id(1); \n  } \n// @sect4{HDG::run}  \u8fd9\u91cc\u7684\u529f\u80fd\u4e0e <code>Step-7</code>  \u57fa\u672c\u76f8\u540c\u3002\u6211\u4eec\u572810\u4e2a\u5468\u671f\u4e2d\u5faa\u73af\uff0c\u5728\u6bcf\u4e2a\u5468\u671f\u4e2d\u7ec6\u5316\u7f51\u683c\u3002 \u5728\u6700\u540e\uff0c\u6536\u655b\u8868\u88ab\u521b\u5efa\u3002\n\n  template <int dim> \n  void HDG<dim>::run() \n  { \n    for (unsigned int cycle = 0; cycle < 10; ++cycle) \n      { \n        std::cout << \"Cycle \" << cycle << ':' << std::endl; \n\n        refine_grid(cycle); \n        setup_system(); \n        assemble_system(false); \n        solve(); \n        postprocess(); \n        output_results(cycle); \n      } \n\n// \u4e0e step-7 \u76f8\u6bd4\uff0c\u6536\u655b\u8868\u6709\u4e00\u4e2a\u5fae\u5c0f\u7684\u53d8\u5316\uff1a\u7531\u4e8e\u6211\u4eec\u6ca1\u6709\u5728\u6bcf\u4e2a\u5468\u671f\u5185\u4ee52\u7684\u7cfb\u6570\u7ec6\u5316\u6211\u4eec\u7684\u7f51\u683c\uff08\u800c\u662f\u4f7f\u75282\uff0c3\uff0c4\uff0c6\uff0c8\uff0c12\uff0c...\u7684\u5e8f\u5217\uff09\uff0c\u6211\u4eec\u9700\u8981\u544a\u8bc9\u6536\u655b\u7387\u8bc4\u4f30\u8fd9\u4e00\u70b9\u3002\u6211\u4eec\u901a\u8fc7\u8bbe\u7f6e\u5355\u5143\u683c\u6570\u91cf\u4f5c\u4e3a\u53c2\u8003\u5217\uff0c\u5e76\u989d\u5916\u6307\u5b9a\u95ee\u9898\u7684\u7ef4\u5ea6\u6765\u5b9e\u73b0\u8fd9\u4e00\u76ee\u7684\uff0c\u8fd9\u4e3a\u5355\u5143\u683c\u6570\u91cf\u548c\u7f51\u683c\u5927\u5c0f\u4e4b\u95f4\u7684\u5173\u7cfb\u63d0\u4f9b\u4e86\u5fc5\u8981\u7684\u4fe1\u606f\u3002\n\n    if (refinement_mode == global_refinement) \n      { \n        convergence_table.evaluate_convergence_rates( \n          \"val L2\", \"cells\", ConvergenceTable::reduction_rate_log2, dim); \n        convergence_table.evaluate_convergence_rates( \n          \"grad L2\", \"cells\", ConvergenceTable::reduction_rate_log2, dim); \n        convergence_table.evaluate_convergence_rates( \n          \"val L2-post\", \"cells\", ConvergenceTable::reduction_rate_log2, dim); \n      } \n    convergence_table.write_text(std::cout); \n  } \n\n} // end of namespace Step51 \n\nint main() \n{ \n  const unsigned int dim = 2; \n\n  try \n    { \n\n// \u73b0\u5728\u662f\u5bf9\u4e3b\u7c7b\u7684\u4e09\u6b21\u8c03\u7528\uff0c\u5b8c\u5168\u7c7b\u4f3c\u4e8e  step-7  \u3002\n\n      { \n        std::cout << \"Solving with Q1 elements, adaptive refinement\" \n                  << std::endl \n                  << \"=============================================\" \n                  << std::endl \n                  << std::endl; \n\n        Step51::HDG<dim> hdg_problem(1, Step51::HDG<dim>::adaptive_refinement); \n        hdg_problem.run(); \n\n        std::cout << std::endl; \n      } \n\n      { \n        std::cout << \"Solving with Q1 elements, global refinement\" << std::endl \n                  << \"===========================================\" << std::endl \n                  << std::endl; \n\n        Step51::HDG<dim> hdg_problem(1, Step51::HDG<dim>::global_refinement); \n        hdg_problem.run(); \n\n        std::cout << std::endl; \n      } \n\n      { \n        std::cout << \"Solving with Q3 elements, global refinement\" << std::endl \n                  << \"===========================================\" << std::endl \n                  << std::endl; \n\n        Step51::HDG<dim> hdg_problem(3, Step51::HDG<dim>::global_refinement); \n        hdg_problem.run(); \n\n        std::cout << std::endl; \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\n  return 0; \n} \n\n", "meta": {"hexsha": "2ab333cee54f4c7552da2632da0bf521b897ba8b", "size": 48759, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-51/step-51.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-51/step-51.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-51/step-51.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.0072, "max_line_length": 383, "alphanum_fraction": 0.5780266207, "num_tokens": 15474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936484231889, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.47979498013424393}}
{"text": "\r\n///////////////////////////////////////////////////////////////////////////////\r\n//  Copyright 2013 Nikhar Agrawal\r\n//  Copyright 2013 Christopher Kormanyos\r\n//  Copyright 2013 John Maddock\r\n//  Copyright 2013 Paul Bristow\r\n//  Distributed under the Boost\r\n//  Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef _BOOST_POLYGAMMA_DETAIL_2013_07_30_HPP_\r\n  #define _BOOST_POLYGAMMA_DETAIL_2013_07_30_HPP_\r\n\r\n  #include <cmath>\r\n  #include <limits>\r\n  #include <boost/cstdint.hpp>\r\n  #include <boost/math/policies/policy.hpp>\r\n  #include <boost/math/special_functions/trunc.hpp>\r\n  #include <boost/math/special_functions/zeta.hpp>\r\n  #include <boost/mpl/if.hpp>\r\n  #include <boost/mpl/int.hpp>\r\n  #include <boost/static_assert.hpp>\r\n  #include <boost/type_traits/is_convertible.hpp>\r\n  \r\n#if (BOOST_VERSION / 100) <= 1055\r\n #include \"../bernoulli.hpp\"\r\n#else\r\n #include <boost/math/special_functions/bernoulli.hpp>\r\n#endif\r\n\r\n  namespace boost { namespace math { namespace detail {\r\n\r\n  template<class T>\r\n  struct max_iteration\r\n  {\r\n    //TODO Derive a suitable formula based on the precision of T\r\n    static const int value=2500;\r\n  };\r\n\r\n  template<class T>\r\n  bool factorial_overflow(const int n)\r\n  {\r\n    // Use Stirling's approximation to check if n! would overflow when data type is T.\r\n    static const long int max_precision = std::numeric_limits<T>::max_exponent10;\r\n\r\n    T nn                   = T(n);\r\n    T log_n                = log(nn);\r\n    T n_log_n              = n * log_n;\r\n    T n_log_n_minus_n      = n_log_n - n;\r\n    T base_10              = n_log_n_minus_n/log(10);\r\n    long int base_10_ceil  = boost::math::ltrunc(base_10) + 1;\r\n\r\n    // Since nlogn - n < log(n!) by a small margin, we add 10 as safety measure.\r\n    return (((base_10_ceil + 10) > max_precision )? 1 : 0);\r\n  }\r\n\r\n  template<class T>\r\n  int possible_factorial_overflow_index()\r\n  {\r\n    // we use binary search to determine a good approximation for an index that might overflow\r\n\r\n    int upper_limit = max_iteration<T>::value;\r\n    int lower_limit = 8;\r\n\r\n    if(factorial_overflow<T>(upper_limit) == 0)\r\n    {\r\n      return upper_limit;\r\n    }\r\n\r\n    while(upper_limit > (lower_limit + 4))\r\n    {\r\n      const int mid = (upper_limit + lower_limit) / 2;\r\n\r\n      if(factorial_overflow<T>(mid) == 0)\r\n      {\r\n        lower_limit = mid;\r\n      }\r\n      else\r\n      {\r\n        upper_limit = mid;\r\n      }\r\n    }\r\n\r\n    return lower_limit;\r\n  }\r\n\r\n  template<class T, class Policy>\r\n  T digamma_atinfinityplus(const int, const T &x, const Policy&)\r\n  {\r\n    BOOST_MATH_STD_USING\r\n\r\n    // calculate a high bernoulli number upfront to make use of cache\r\n    unsigned int bernoulli_index = 100;\r\n    boost::math::bernoulli_b2n<T>(bernoulli_index);\r\n\r\n    T z(x);\r\n    T log_z(log(z));\r\n    T one_over_2z= T(1) / (2 * z);\r\n    T sum(0);\r\n\r\n    for(int two_k = 2; two_k < max_iteration<T>::value; two_k += 2)\r\n    {\r\n      if(two_k/2 > static_cast<boost::int32_t>(bernoulli_index))\r\n      {\r\n        try\r\n        {\r\n          int temp = static_cast<int>(bernoulli_index * 1.5F);\r\n          boost::math::bernoulli_b2n<T>(temp);\r\n          bernoulli_index = temp;\r\n        }\r\n        catch(...)\r\n        {\r\n          break;\r\n        }\r\n      }\r\n\r\n      T term(1);\r\n      T one_over_two_k       = T(1) / two_k;\r\n      T z_pow_two_k          = pow(z, static_cast<boost::int32_t>(two_k));\r\n      T one_over_z_pow_two_k = T(1) / z_pow_two_k;\r\n      T bernoulli_term       = boost::math::bernoulli_b2n<T>(two_k / 2);\r\n\r\n      term = (bernoulli_term * one_over_two_k) * one_over_z_pow_two_k;\r\n\r\n      if(term == 0)\r\n      {\r\n        continue;\r\n      }\r\n\r\n      sum += term;\r\n\r\n      T term_base_10_exp = ((term < 0) ? -term : term);\r\n      T sum_base_10_exp  = ((sum  < 0) ? -sum  : sum);\r\n\r\n      int exponent_value;\r\n\r\n      static_cast<void>(frexp(term_base_10_exp, &exponent_value));\r\n      term_base_10_exp = T(exponent_value) * 0.303F;\r\n\r\n      static_cast<void>(frexp(sum_base_10_exp, &exponent_value));\r\n      sum_base_10_exp = T(exponent_value) * 0.303F;\r\n\r\n      long int order_check =  boost::math::ltrunc(term_base_10_exp) - boost::math::ltrunc(sum_base_10_exp);\r\n      long int tol         =  std::numeric_limits<T>::digits10;\r\n\r\n\r\n      if((two_k > 24) && (order_check < -tol))\r\n      {\r\n        break;\r\n      }\r\n    }\r\n\r\n    return (log_z - one_over_2z) - sum;\r\n  }\r\n\r\n  template<class T, class Policy>\r\n  T polygamma_atinfinityplus(const int n, const T& x, const Policy& pol) // for large values of x such as for x> 400\r\n  {\r\n     BOOST_MATH_STD_USING\r\n\r\n     if(n == 0)\r\n     {\r\n       return digamma_atinfinityplus(n, x, pol);\r\n    }\r\n\r\n     //TODO try calculating for bernoulli_index= max_iteration, if error then set bernoulli_index=100\r\n     unsigned int bernoulli_index = 100;\r\n     boost::math::bernoulli_b2n<T>(bernoulli_index);\r\n\r\n     const bool b_negate = ((n % 2) == 0);\r\n\r\n     const T n_minus_one_fact            = boost::math::factorial<T>(n - 1);\r\n     const T nn                          = T(n);\r\n     const T n_fact                      = n_minus_one_fact * nn;\r\n     const T one_over_z                  = T(1) / x;\r\n     const T one_over_z2                 = one_over_z * one_over_z;\r\n     const T one_over_z_pow_n            = T(1) / pow(x, n);\r\n           T one_over_x_pow_two_k_plus_n = one_over_z_pow_n * one_over_z2;\r\n           T two_k_plus_n_minus_one      = nn + T(1);\r\n           T two_k_plus_n_minus_one_fact = n_fact * (n + 1); //(n+3)! ?\r\n           T one_over_two_k_fact         = T(1) / 2;\r\n           T sum                         = (  (boost::math::bernoulli_b2n<T>(1) * two_k_plus_n_minus_one_fact)\r\n                                            * (one_over_two_k_fact * one_over_x_pow_two_k_plus_n));\r\n\r\n     // Perform the Bernoulli series expansion.\r\n     for(int two_k = 4; two_k < max_iteration<T>::value; two_k += 2)\r\n     {\r\n       if((two_k / 2) > static_cast<int>(bernoulli_index))\r\n       {\r\n         try\r\n         {\r\n           //TODO the multiplication factor should depend upon T, small precision, smaller multiplication factor\r\n           int temp = static_cast<int>(bernoulli_index * 2.0F);\r\n           boost::math::bernoulli_b2n<T>(temp);\r\n           bernoulli_index = temp;\r\n         }\r\n         catch(...)\r\n         {\r\n           break;\r\n         }\r\n       }\r\n\r\n       one_over_x_pow_two_k_plus_n *= one_over_z2;\r\n       two_k_plus_n_minus_one_fact *= ++two_k_plus_n_minus_one;\r\n       two_k_plus_n_minus_one_fact *= ++two_k_plus_n_minus_one;\r\n       one_over_two_k_fact         /= static_cast<boost::int32_t>(two_k * static_cast<boost::int32_t>(two_k - static_cast<boost::int32_t>(1)));\r\n\r\n       const T term = (  (boost::math::bernoulli_b2n<T>(two_k/2) * two_k_plus_n_minus_one_fact)\r\n                       * (one_over_two_k_fact * one_over_x_pow_two_k_plus_n));\r\n\r\n        if(term == 0)\r\n        {\r\n          continue;\r\n        }\r\n\r\n        sum += term;\r\n\r\n        T term_base_10_exp = ((term < 0) ? -term : term);\r\n        T sum_base_10_exp  = ((sum  < 0) ? -sum  : sum);\r\n\r\n        int exponent_value;\r\n\r\n        static_cast<void>(frexp(term_base_10_exp, &exponent_value));\r\n        term_base_10_exp = T(exponent_value) * 0.303F;\r\n\r\n        static_cast<void>(frexp(sum_base_10_exp, &exponent_value));\r\n        sum_base_10_exp = T(exponent_value) * 0.303F;\r\n\r\n        long int order_check =  boost::math::ltrunc(term_base_10_exp) - boost::math::ltrunc(sum_base_10_exp);\r\n        long int tol         =  std::numeric_limits<T>::digits10;\r\n\r\n        if((two_k > 24) && (order_check < -tol))\r\n        {\r\n          break;\r\n        }\r\n     }\r\n\r\n     sum += ((((n_minus_one_fact * (nn + (x * static_cast<boost::int32_t>(2)))) * one_over_z_pow_n) * one_over_z) / 2);\r\n\r\n     return ((!b_negate) ? sum : -sum);\r\n  }\r\n\r\n  template<class T, class Policy>\r\n  T polygamma_attransitionplus(const int n, const T& x, const Policy&)\r\n  {\r\n    // this doesn't work for digamma either\r\n\r\n    // Use Euler-Maclaurin summation.\r\n\r\n    // Use N = (0.4 * digits) + (4 * n)\r\n    BOOST_MATH_STD_USING\r\n    const int d4d  = static_cast<boost::int32_t>(0.4F * std::numeric_limits<T>::digits10);\r\n    const int N4dn = static_cast<boost::int32_t>(d4d + (4 * n));\r\n    const int N    = static_cast<boost::int32_t>((std::min)(N4dn, (std::numeric_limits<int>::max)()));\r\n    const int m    = n;\r\n\r\n    const int minus_m_minus_one = -m - 1;\r\n\r\n    T z(x);\r\n    T sum0(0);\r\n    T z_plus_k_pow_minus_m_minus_one(0);\r\n\r\n    for(int k = 1; k <= N; ++k)\r\n    {\r\n      z_plus_k_pow_minus_m_minus_one = pow(z, minus_m_minus_one);\r\n      sum0 += z_plus_k_pow_minus_m_minus_one;\r\n      ++z;\r\n    }\r\n\r\n    const T one_over_z_plus_N_pow_minus_m           = pow(z, -m);\r\n    const T one_over_z_plus_N_pow_minus_m_minus_one = one_over_z_plus_N_pow_minus_m / z;\r\n\r\n    const T term0 = one_over_z_plus_N_pow_minus_m_minus_one / 2;\r\n    const T term1 = one_over_z_plus_N_pow_minus_m           / m;\r\n\r\n          T   sum1                                      = T(0);\r\n          T   one_over_two_k_fact                       = T(1) / 2;\r\n          int mk                                        = m + 1;\r\n          T   am                                        = T(mk);\r\n    const T   one_over_z_plus_N_squared                 = T(1) / (z * z);\r\n          T   one_over_z_plus_N_pow_minus_m_minus_two_k = one_over_z_plus_N_pow_minus_m * one_over_z_plus_N_squared;\r\n\r\n    for(int k = 1; k < max_iteration<T>::value; ++k)\r\n    {\r\n      const int two_k = 2 * k; // k << 1\r\n\r\n      const T term = ((boost::math::bernoulli_b2n<T>(two_k / 2) * am) * one_over_two_k_fact) * one_over_z_plus_N_pow_minus_m_minus_two_k;\r\n\r\n      T term_base_10_exp = ((term < 0) ? -term : term);\r\n      T sum_base_10_exp  = ((sum1 < 0) ? -sum1 : sum1);\r\n\r\n      int exponent_value;\r\n\r\n      static_cast<void>(frexp(term_base_10_exp, &exponent_value));\r\n      term_base_10_exp = T(exponent_value) * 0.303F;\r\n\r\n      static_cast<void>(frexp(sum_base_10_exp, &exponent_value));\r\n      sum_base_10_exp = T(exponent_value) * 0.303F;\r\n\r\n      long int order_check =  boost::math::ltrunc(term_base_10_exp) - boost::math::ltrunc(sum_base_10_exp);\r\n      long int tol         =  std::numeric_limits<T>::digits10;\r\n\r\n      if((two_k > 24) && (order_check < -tol))\r\n      {\r\n        break;\r\n      }\r\n\r\n      sum1 += term;\r\n\r\n      one_over_two_k_fact /= (two_k + 1);\r\n      one_over_two_k_fact /= (two_k + 2);\r\n\r\n      ++mk;\r\n      am *= mk;\r\n      ++mk;\r\n      am *= mk;\r\n\r\n      one_over_z_plus_N_pow_minus_m_minus_two_k *= one_over_z_plus_N_squared;\r\n    }\r\n\r\n    const T pg = (((sum0 + term0) + term1) + sum1) * factorial<T>(m);\r\n\r\n    const bool b_negate = ((m % 2) == 0);\r\n\r\n    return ((!b_negate) ? pg : -pg);\r\n  }\r\n\r\n  template<class T, class Policy>\r\n  T polygamma_nearzero(const int n, const T& x, const Policy&)\r\n  {\r\n    BOOST_MATH_STD_USING\r\n    // not defined for digamma\r\n\r\n    // Use a series expansion for x near zero which uses poly_gamma(m, 1) which,\r\n    // in turn, uses the Riemann zeta function for integer arguments.\r\n    // http://functions.wolfram.com/GammaBetaErf/PolyGamma2/06/01/03/01/02/\r\n    const bool b_negate = (( n % 2 ) == 0 ) ;\r\n\r\n    const T n_fact               =  boost::math::factorial<T>(n);\r\n    const T z_pow_n_plus_one     =  pow(x, static_cast<boost::int64_t>(n + 1));\r\n    const T n_fact_over_pow_term =  n_fact / z_pow_n_plus_one;\r\n    const T term0                =  !b_negate ? n_fact_over_pow_term : -n_fact_over_pow_term;\r\n\r\n          T one_over_k_fact      =  T(1);\r\n          T z_pow_k              =  T(1);\r\n          T k_plus_n_fact        =  boost::math::factorial<T>(n);\r\n          T k_plus_n_plus_one    =  T(n + 1);\r\n    const T pg_kn                =  k_plus_n_fact * boost::math::zeta<T>(k_plus_n_plus_one);\r\n          bool    b_neg_term     =  ((n % 2) == 0);\r\n          T sum                  =  ((!b_neg_term) ? pg_kn : -pg_kn);\r\n\r\n    for(int k = 1; k < max_iteration<T>::value; k++)\r\n    {\r\n      k_plus_n_fact   *= k_plus_n_plus_one++;\r\n      one_over_k_fact /= k;\r\n      z_pow_k         *= x;\r\n\r\n      const T pg = k_plus_n_fact * boost::math::zeta<T>(k_plus_n_plus_one);\r\n\r\n      const T term = (pg * z_pow_k) * one_over_k_fact;\r\n\r\n      T term_base_10_exp = ((term < 0) ? -term : term);\r\n      T sum_base_10_exp  = ((sum  < 0) ? -sum  : sum);\r\n\r\n      int exponent_value;\r\n\r\n      static_cast<void>(frexp(term_base_10_exp, &exponent_value));\r\n      term_base_10_exp = T(exponent_value) * 0.303F;\r\n\r\n      static_cast<void>(frexp(sum_base_10_exp, &exponent_value));\r\n      sum_base_10_exp = T(exponent_value) * 0.303F;\r\n\r\n      long int order_check =  boost::math::ltrunc(term_base_10_exp) - boost::math::ltrunc(sum_base_10_exp);\r\n      long int tol         =  std::numeric_limits<T>::digits10;\r\n\r\n      if((k > 12) && (order_check < -tol))\r\n      {\r\n        break;\r\n      }\r\n\r\n      b_neg_term = !b_neg_term;\r\n\r\n      ((!b_neg_term) ? sum += term : sum -= term);\r\n    }\r\n\r\n    return term0 + sum;\r\n\r\n  }\r\n\r\n  template<class T, class Policy>\r\n  inline T polygamma_imp(const int n, T x, const Policy &pol)\r\n  {\r\n    if(x < 0.5F)\r\n    {\r\n      return polygamma_nearzero(n, x, pol);\r\n    }\r\n    else if (x > 400.0F)\r\n    {\r\n      return polygamma_atinfinityplus(n, x, pol); //just a test return value\r\n    }\r\n    else\r\n    {\r\n      return polygamma_attransitionplus(n, x, pol);\r\n    }\r\n  }\r\n\r\n} } } // namespace boost::math::detail\r\n\r\n#endif // _BOOST_POLYGAMMA_DETAIL_2013_07_30_HPP_\r\n", "meta": {"hexsha": "65abf6011865c2e52c6b023025693e72c2a67dc2", "size": 13504, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "SigTM/external/boost_sub/math/special_functions/detail/polygamma.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/external/boost_sub/math/special_functions/detail/polygamma.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/external/boost_sub/math/special_functions/detail/polygamma.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": 32.9365853659, "max_line_length": 144, "alphanum_fraction": 0.5713862559, "num_tokens": 3820, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.4797949767924757}}
{"text": "#include \"array_of_trees.hpp\"\n#include <iostream>\n#include <fstream>\n#include <cmath>\n#include <boost/filesystem.hpp>\n\nArrayOfTrees::ArrayOfTrees(const int64_t size)\n{\n    rows.resize(size);\n    nnz = 0;\n}\n\nvoid ArrayOfTrees::accumulate(int64_t first, int64_t second)\n{\n    if ((first < 0) || (second < 0)) return;\n    BTree & ac = rows[first];\n    if (ac.find( second ) != ac.end())\n        ac[second]++;\n    else\n    {\n        ac.insert(std::make_pair(second, 1));\n        nnz += 1;\n    }\n}\n\ndouble get_PMI(int64_t cnt, int64_t id1, int64_t id2, int64_t cnt_words_processed, int64_t const * frequencies)\n{\n    return log2((static_cast<double>(cnt) * cnt_words_processed) / (frequencies[id1] * frequencies[id2]));\n}\n\nvoid ArrayOfTrees::dump_csr(const char * path, const int64_t * frequencies, int size_freq)\n{\n    (void)size_freq;\n    int64_t cnt_words_processed = 0;\n    for (size_t i = 0; i < rows.size(); i++)\n        cnt_words_processed += frequencies[i];\n    bool binary = true;\n    std::ofstream file;\n    std::string str_path;\n    auto mode = binary ? std::ios::out | std::ios::binary : std::ios::out;\n    str_path = (boost::filesystem::path(path) / boost::filesystem::path(binary ? \"bigrams.data.bin\" : \"bigrams.data\")).string();\n    file.open (str_path, mode);\n    if (!file) throw  std::runtime_error(\"can not open output file \" + str_path + \" , check the path\");\n    for (size_t first = 0; first < rows.size(); first++)\n        for (const auto& second : rows[first])\n        {\n            float v = get_PMI(second.second, first, second.first, cnt_words_processed, frequencies);\n            if (binary)\n                file.write( reinterpret_cast<const char*>(&v), sizeof(v));\n            else\n                file << v << \"\\n\";\n        }\n    file.close();\n    //----------------------------------------\n    str_path = (boost::filesystem::path(path) / boost::filesystem::path(binary ? \"bigrams.col_ind.bin\" : \"bigrams.col_ind\")).string();\n    file.open (str_path, mode);\n    for (size_t first = 0; first < rows.size(); first++)\n        for (const auto& second : rows[first])\n        {\n            size_t v = second.first;\n            if (binary)\n                file.write( reinterpret_cast<const char*>(&v), sizeof(v));\n            else\n                file << v << \"\\n\";\n        }\n    file.close();\n    //---------------write row ptrs\n    str_path = (boost::filesystem::path(path) / boost::filesystem::path(binary ? \"bigrams.row_ptr.bin\" : \"bigrams.row_ptr\")).string();\n    file.open (str_path, mode);\n    int64_t row_ptr = 0;\n    for (size_t first = 0; first < rows.size(); first++)\n    {\n        if (binary)\n            file.write( reinterpret_cast<const char*>(&row_ptr), sizeof(row_ptr));\n        else\n            file << row_ptr << \"\\n\";\n        row_ptr += rows[first].size();\n    }\n    if (binary)\n        file.write( reinterpret_cast<const char*>(&row_ptr), sizeof(row_ptr));\n    else\n        file << row_ptr << \"\\n\";\n    file.close();\n}\n\n\nvoid  ArrayOfTrees::get_row_ptr(int64_t * buffer, int n)\n{\n    size_t N = n;\n    int64_t row_ptr = 0;\n    size_t first = 0;\n    for (first = 0; first < rows.size(); first++)\n    {\n        buffer[first] = row_ptr;\n        row_ptr += rows[first].size();\n        if (first > N)\n            throw std::runtime_error(\"out of bounds in get_row_ptr\");\n    }\n    if (first > N)\n        throw std::runtime_error(\"out of bounds in get_row_ptr\");\n    buffer[first] = row_ptr;\n}\n\nvoid  ArrayOfTrees::get_data(int64_t * buffer, int n)\n{\n    size_t pos = 0;\n    size_t N = n;\n    for (size_t first = 0; first < rows.size(); first++)\n        for (const auto& second : rows[first])\n        {\n            buffer[pos] = second.second;\n            pos++;\n            if (pos > N)\n                throw std::runtime_error(\"out of bounds in get_data\");\n        }\n}\n\nvoid  ArrayOfTrees::get_data_PMI(float * buffer_f, int n, const int64_t * frequencies, int size_freq)\n{\n    size_t pos = 0;\n    size_t N = n;\n    int64_t cnt_words_processed = 0;\n    for (size_t i = 0; i < size_freq; i++)\n        cnt_words_processed += frequencies[i];\n\n    for (size_t first = 0; first < rows.size(); first++)\n        for (const auto& second : rows[first])\n        {\n            float v = get_PMI(second.second, first, second.first, cnt_words_processed, frequencies);\n            buffer_f[pos] = v;\n            pos++;\n            if (pos > N)\n                throw std::runtime_error(\"out of bounds in get_data\");\n        }\n}\n\nvoid  ArrayOfTrees::get_col_ind(int64_t * buffer, int n)\n{\n    size_t pos = 0;\n    size_t N = n;\n    for (size_t first = 0; first < rows.size(); first++)\n        for (const auto& second : rows[first])\n        {\n            buffer[pos] = second.first;\n            pos++;\n            if (pos > N)\n                throw std::runtime_error(\"out of bounds in get_col_ind\");\n        }\n}", "meta": {"hexsha": "865abf3fd9135b19f072fdd89d287616869c9d11", "size": 4830, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/array_of_trees.cpp", "max_stars_repo_name": "undertherain/nlp_cooc", "max_stars_repo_head_hexsha": "e316740c469e4ade6ba064e6756057fee10466ed", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-09-20T03:04:47.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-20T03:04:47.000Z", "max_issues_repo_path": "src/array_of_trees.cpp", "max_issues_repo_name": "undertherain/nlp_cooc", "max_issues_repo_head_hexsha": "e316740c469e4ade6ba064e6756057fee10466ed", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/array_of_trees.cpp", "max_forks_repo_name": "undertherain/nlp_cooc", "max_forks_repo_head_hexsha": "e316740c469e4ade6ba064e6756057fee10466ed", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4161073826, "max_line_length": 134, "alphanum_fraction": 0.5672877847, "num_tokens": 1255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115012, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.4797949701089391}}
{"text": "#include \"config.h\"\n#include \"Scene_points_with_normal_item.h\"\n#include \"Scene_polygon_soup_item.h\"\n#include \"Scene_polyhedron_item.h\"\n#include \"Scene_surface_mesh_item.h\"\n#include <CGAL/Three/Scene_group_item.h>\n\n#include <CGAL/Three/Polyhedron_demo_plugin_helper.h>\n#include <CGAL/Three/Polyhedron_demo_plugin_interface.h>\n#include <CGAL/Three/Scene_group_item.h>\n\n#include <CGAL/Random.h>\n\n#include <CGAL/Shape_detection_3.h>\n#include <CGAL/regularize_planes.h>\n#include <CGAL/Delaunay_triangulation_2.h>\n#include <CGAL/Alpha_shape_2.h>\n\n#include <CGAL/structure_point_set.h>\n\n#include <QObject>\n#include <QAction>\n#include <QMainWindow>\n#include <QApplication>\n#include <QtPlugin>\n#include <QMessageBox>\n\n#include <boost/foreach.hpp>\n#include <boost/function_output_iterator.hpp>\n\n#include \"ui_Point_set_shape_detection_plugin.h\"\n\n\nstruct build_from_pair\n{\n  Point_set& m_pts;\n\n  build_from_pair (Point_set& pts) : m_pts (pts) { }\n\n  void operator() (const std::pair<Point_set::Point, Point_set::Vector>& pair)\n  {\n    m_pts.insert (pair.first, pair.second);\n  }\n\n\n};\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel Epic_kernel;\ntypedef Epic_kernel::Point_3 Point;\n//typedef CGAL::Point_with_normal_3<Epic_kernel> Point_with_normal;\n//typedef std::vector<Point_with_normal> Point_list;\n//typedef CGAL::Identity_property_map<Point_with_normal> PointPMap;\n//typedef CGAL::Normal_of_point_with_normal_pmap<Epic_kernel> NormalPMap;\nusing namespace CGAL::Three;\nclass Polyhedron_demo_point_set_shape_detection_plugin :\n  public QObject,\n  public Polyhedron_demo_plugin_helper\n{\n  Q_OBJECT\n    Q_INTERFACES(CGAL::Three::Polyhedron_demo_plugin_interface)\n    Q_PLUGIN_METADATA(IID \"com.geometryfactory.PolyhedronDemo.PluginInterface/1.0\")\n    QAction* actionDetect;\n\n  typedef Point_set_3<Kernel>::Point_map PointPMap;\n  typedef Point_set_3<Kernel>::Vector_map NormalPMap;\n\n  typedef CGAL::Shape_detection_3::Efficient_RANSAC_traits<Epic_kernel, Point_set, PointPMap, NormalPMap> Traits;\n  typedef CGAL::Shape_detection_3::Efficient_RANSAC<Traits> Shape_detection;\n  \npublic:\n  void init(QMainWindow* mainWindow, CGAL::Three::Scene_interface* scene_interface, Messages_interface*) {\n    scene = scene_interface;\n    mw = mainWindow;\n    actionDetect = new QAction(tr(\"Point Set Shape Detection\"), mainWindow);\n    actionDetect->setObjectName(\"actionDetect\");\n    autoConnectActions();\n  }\n\n  bool applicable(QAction*) const {\n    Scene_points_with_normal_item* item =\n      qobject_cast<Scene_points_with_normal_item*>(scene->item(scene->mainSelectionIndex()));\n    if (item && item->has_normals())\n      return true;\n    return false;\n  }\n\n  QList<QAction*> actions() const {\n    return QList<QAction*>() << actionDetect;\n  }\n\n  public Q_SLOTS:\n    void on_actionDetect_triggered();\n\nprivate:\n\n  typedef Kernel::Plane_3 Plane_3;\n  \n  void build_alpha_shape (Point_set& points, boost::shared_ptr<CGAL::Shape_detection_3::Plane<Traits> > plane,\n                          Scene_polyhedron_item* item, Scene_surface_mesh_item* sm_item, double epsilon);\n\n}; // end Polyhedron_demo_point_set_shape_detection_plugin\n\nclass Point_set_demo_point_set_shape_detection_dialog : public QDialog, private Ui::PointSetShapeDetectionDialog\n{\n  Q_OBJECT\npublic:\n  Point_set_demo_point_set_shape_detection_dialog(QWidget * /*parent*/ = 0)\n  {\n    setupUi(this);\n  }\n\n  //QString shapeDetectionMethod() const { return m_shapeDetectionMethod->currentText(); }\n  double cluster_epsilon() const { return m_cluster_epsilon_field->value(); }\n  double epsilon() const { return m_epsilon_field->value(); }\n  unsigned int min_points() const { return m_min_pts_field->value(); }\n  double normal_tolerance() const { return m_normal_tolerance_field->value(); }\n  double search_probability() const { return m_probability_field->value(); }\n  double gridCellSize() const { return 1.0; }\n  bool detect_plane() const { return planeCB->isChecked(); } \n  bool detect_sphere() const { return sphereCB->isChecked(); } \n  bool detect_cylinder() const { return cylinderCB->isChecked(); } \n  bool detect_torus() const { return torusCB->isChecked(); } \n  bool detect_cone() const { return coneCB->isChecked(); }\n  bool generate_alpha() const { return m_generate_alpha->isChecked(); }\n  bool generate_subset() const { return !(m_do_not_generate_subset->isChecked()); }\n  bool regularize() const { return m_regularize->isChecked(); }\n  bool generate_structured() const { return m_generate_structured->isChecked(); }\n};\n\nvoid Polyhedron_demo_point_set_shape_detection_plugin::on_actionDetect_triggered() {\n\n  CGAL::Random rand(time(0));\n  const CGAL::Three::Scene_interface::Item_id index = scene->mainSelectionIndex();\n\n  Scene_points_with_normal_item* item =\n    qobject_cast<Scene_points_with_normal_item*>(scene->item(index));\n\n  Scene_points_with_normal_item::Bbox bb = item->bbox();\n \n  double diam = CGAL::sqrt((bb.xmax()-bb.xmin())*(bb.xmax()-bb.xmin()) + (bb.ymax()-bb.ymin())*(bb.ymax()-bb.ymin()) + (bb.zmax()-bb.zmin())*(bb.zmax()-bb.zmin()));\n\n  if(item)\n  {\n    // Gets point set\n    Point_set* points = item->point_set();\n\n    if(points == NULL)\n      return;\n\n    //Epic_kernel::FT diag = sqrt(((points->bounding_box().max)() - (points->bounding_box().min)()).squared_length());\n\n    // Gets options\n    Point_set_demo_point_set_shape_detection_dialog dialog;\n    if(!dialog.exec())\n      return;\n    \n    scene->setSelectedItem(-1);\n    Scene_group_item *subsets_item = new Scene_group_item(QString(\"%1 (RANSAC subsets)\").arg(item->name()));\n    subsets_item->setExpanded(false);\n    Scene_group_item *planes_item = new Scene_group_item(QString(\"%1 (RANSAC planes)\").arg(item->name()));\n    planes_item->setExpanded(false);\n    \n    QApplication::setOverrideCursor(Qt::WaitCursor);\n\n    typedef Point_set::Point_map PointPMap;\n    typedef Point_set::Vector_map NormalPMap;\n\n    typedef CGAL::Shape_detection_3::Efficient_RANSAC_traits<Epic_kernel, Point_set, PointPMap, NormalPMap> Traits;\n    typedef CGAL::Shape_detection_3::Efficient_RANSAC<Traits> Shape_detection;\n\n    Shape_detection shape_detection;\n    shape_detection.set_input(*points, points->point_map(), points->normal_map());\n\n    std::vector<Scene_group_item *> groups;\n    groups.resize(5);\n    // Shapes to be searched for are registered by using the template Shape_factory\n    if(dialog.detect_plane()){\n      groups[0] = new Scene_group_item(\"Planes\");\n      groups[0]->setRenderingMode(Points);\n      shape_detection.add_shape_factory<CGAL::Shape_detection_3::Plane<Traits> >();\n    }\n    if(dialog.detect_cylinder()){\n      groups[1] = new Scene_group_item(\"Cylinders\");\n      groups[1]->setRenderingMode(Points);\n      shape_detection.add_shape_factory<CGAL::Shape_detection_3::Cylinder<Traits> >();\n    }\n    if(dialog.detect_torus()){\n      groups[2] = new Scene_group_item(\"Torus\");\n      groups[2]->setRenderingMode(Points);\n      shape_detection.add_shape_factory< CGAL::Shape_detection_3::Torus<Traits> >();\n    }\n    if(dialog.detect_cone()){\n      groups[3] = new Scene_group_item(\"Cones\");\n      groups[3]->setRenderingMode(Points);\n      shape_detection.add_shape_factory< CGAL::Shape_detection_3::Cone<Traits> >();\n    }\n    if(dialog.detect_sphere()){\n      groups[4] = new Scene_group_item(\"Spheres\");\n      groups[4]->setRenderingMode(Points);\n      shape_detection.add_shape_factory< CGAL::Shape_detection_3::Sphere<Traits> >();\n    }\n\n    // Parameterization of the shape detection using the Parameters structure.\n    Shape_detection::Parameters op;\n    op.probability = dialog.search_probability();       // probability to miss the largest primitive on each iteration.\n    op.min_points = dialog.min_points();          // Only extract shapes with a minimum number of points.\n    op.epsilon = dialog.epsilon();          // maximum euclidean distance between point and shape.\n    op.cluster_epsilon = dialog.cluster_epsilon();    // maximum euclidean distance between points to be clustered.\n    op.normal_threshold = dialog.normal_tolerance();   // normal_threshold < dot(surface_normal, point_normal); maximum normal deviation.\n\n    // The actual shape detection.\n    shape_detection.detect(op);\n\n    std::cout << shape_detection.shapes().size() << \" shapes found\" << std::endl;\n\n    if (dialog.regularize ())\n      {\n        std::cerr << \"Regularization of planes... \" << std::endl;\n        CGAL::regularize_planes (shape_detection, true, true, true, true,\n                                 180 * std::acos (op.normal_threshold) / CGAL_PI, op.epsilon);\n    \n        std::cerr << \"done\" << std::endl;\n      }\n\n    std::map<Kernel::Point_3, QColor> color_map;\n    \n    //print_message(QString(\"%1 shapes found.\").arg(shape_detection.number_of_shapes()));\n    int index = 0;\n    BOOST_FOREACH(boost::shared_ptr<Shape_detection::Shape> shape, shape_detection.shapes())\n    {\n      CGAL::Shape_detection_3::Cylinder<Traits> *cyl;\n      cyl = dynamic_cast<CGAL::Shape_detection_3::Cylinder<Traits> *>(shape.get());\n      if (cyl != NULL){\n        if(cyl->radius() > diam){\n          continue;\n        }\n      }\n        \n      Scene_points_with_normal_item *point_item = new Scene_points_with_normal_item;\n      \n      BOOST_FOREACH(std::size_t i, shape->indices_of_assigned_points())\n        point_item->point_set()->insert(points->point(*(points->begin()+i)));\n      \n      unsigned char r, g, b;\n\n      r = static_cast<unsigned char>(64 + rand.get_int(0, 192));\n      g = static_cast<unsigned char>(64 + rand.get_int(0, 192));\n      b = static_cast<unsigned char>(64 + rand.get_int(0, 192));\n\n      point_item->setRbgColor(r, g, b);\n\n      // Providing a useful name consisting of the order of detection, name of type and number of inliers\n      std::stringstream ss;\n      if (dynamic_cast<CGAL::Shape_detection_3::Cylinder<Traits> *>(shape.get())){\n        CGAL::Shape_detection_3::Cylinder<Traits> * cyl \n          = dynamic_cast<CGAL::Shape_detection_3::Cylinder<Traits> *>(shape.get());\n        ss << item->name().toStdString() << \"_cylinder_\" << cyl->radius() << \"_\";\n      }\n      else if (dynamic_cast<CGAL::Shape_detection_3::Plane<Traits> *>(shape.get()))\n        {\n          ss << item->name().toStdString() << \"_plane_\";\n\n          boost::shared_ptr<CGAL::Shape_detection_3::Plane<Traits> > pshape\n            = boost::dynamic_pointer_cast<CGAL::Shape_detection_3::Plane<Traits> > (shape);\n          \n          Kernel::Point_3 ref = CGAL::ORIGIN + pshape->plane_normal ();\n\n          if (color_map.find (ref) == color_map.end ())\n            {\n              ref = CGAL::ORIGIN + (-1.) * pshape->plane_normal ();\n              if (color_map.find (ref) == color_map.end ())\n                color_map[ref] = point_item->color ();\n              else\n                point_item->setColor (color_map[ref]);\n            }\n          else\n            point_item->setColor (color_map[ref]);\n\n          ss << \"(\" << ref << \")_\";\n      \n          if (dialog.generate_alpha ())\n            {\n              // If plane, build alpha shape\n              Scene_polyhedron_item* poly_item = NULL;\n              Scene_surface_mesh_item* sm_item = NULL;\n              if(mw->property(\"is_polyhedron_mode\").toBool()){\n                poly_item = new Scene_polyhedron_item;\n              } else {\n                sm_item = new Scene_surface_mesh_item;\n              }\n\n              build_alpha_shape (*(point_item->point_set()), pshape,\n                                 poly_item, sm_item, dialog.cluster_epsilon());\n          \n              if(poly_item){\n                poly_item->setColor(point_item->color ());\n                poly_item->setName(QString(\"%1%2_alpha_shape\").arg(QString::fromStdString(ss.str()))\n                                   .arg (QString::number (shape->indices_of_assigned_points().size())));\n                poly_item->setRenderingMode (Flat);\n                \n                scene->addItem(poly_item);\n                if(scene->item_id(groups[0]) == -1)\n                  scene->addItem(groups[0]);\n                scene->changeGroup(poly_item, groups[0]);\n              }\n              if(sm_item){\n                sm_item->setColor(point_item->color ());\n                sm_item->setName(QString(\"%1%2_alpha_shape\").arg(QString::fromStdString(ss.str()))\n                                   .arg (QString::number (shape->indices_of_assigned_points().size())));\n                sm_item->setRenderingMode (Flat);\n                \n                scene->addItem(sm_item);\n                if(scene->item_id(groups[0]) == -1)\n                  scene->addItem(groups[0]);\n                scene->changeGroup(sm_item, groups[0]);\n              }\n            }\n        }\n      else if (dynamic_cast<CGAL::Shape_detection_3::Cone<Traits> *>(shape.get()))\n        ss << item->name().toStdString() << \"_cone_\";\n      else if (dynamic_cast<CGAL::Shape_detection_3::Torus<Traits> *>(shape.get()))\n        ss << item->name().toStdString() << \"_torus_\";\n      else if (dynamic_cast<CGAL::Shape_detection_3::Sphere<Traits> *>(shape.get()))\n        ss << item->name().toStdString() << \"_sphere_\";\n\n\n      ss << shape->indices_of_assigned_points().size();\n\n      //names[i] = ss.str(\t\t\n      point_item->setName(QString::fromStdString(ss.str()));\n      point_item->setRenderingMode(item->renderingMode());\n\n      if (dialog.generate_subset()){\n        scene->addItem(point_item);\n        if (dynamic_cast<CGAL::Shape_detection_3::Cylinder<Traits> *>(shape.get()))\n        {\n          if(scene->item_id(groups[1]) == -1)\n             scene->addItem(groups[1]);\n          scene->changeGroup(point_item, groups[1]);\n        }\n        else if (dynamic_cast<CGAL::Shape_detection_3::Plane<Traits> *>(shape.get()))\n        {\n          point_item->point_set()->add_normal_map();\n          CGAL::Shape_detection_3::Plane<Traits> * plane = dynamic_cast<CGAL::Shape_detection_3::Plane<Traits> *>(shape.get());\n          //set normals for point_item to the plane's normal\n          for(Point_set::iterator it = point_item->point_set()->begin(); it != point_item->point_set()->end(); ++it)\n            point_item->point_set()->normal(*it) = plane->plane_normal();\n\n          if(scene->item_id(groups[0]) == -1)\n             scene->addItem(groups[0]);\n          scene->changeGroup(point_item, groups[0]);\n        }\n        else if (dynamic_cast<CGAL::Shape_detection_3::Cone<Traits> *>(shape.get()))\n        {\n          if(scene->item_id(groups[3]) == -1)\n             scene->addItem(groups[3]);\n          scene->changeGroup(point_item, groups[3]);\n        }\n        else if (dynamic_cast<CGAL::Shape_detection_3::Torus<Traits> *>(shape.get()))\n        {\n          if(scene->item_id(groups[2]) == -1)\n             scene->addItem(groups[2]);\n          scene->changeGroup(point_item, groups[2]);\n        }\n        else if (dynamic_cast<CGAL::Shape_detection_3::Sphere<Traits> *>(shape.get()))\n        {\n          if(scene->item_id(groups[4]) == -1)\n             scene->addItem(groups[4]);\n          scene->changeGroup(point_item, groups[4]);\n        }\n      }\n      else\n        delete point_item;\n\n      ++index;\n    }\n    Q_FOREACH(Scene_group_item* group, groups)\n      if(group && group->getChildren().empty())\n        delete group;\n\n    if (dialog.generate_subset())\n      scene->addItem(subsets_item);\n    else\n      delete subsets_item;\n    \n    if (dialog.generate_alpha())\n      scene->addItem(planes_item);\n    else\n      delete planes_item;\n\n    if (dialog.generate_structured ())\n      {\n        std::cerr << \"Structuring point set... \";\n        \n        Scene_points_with_normal_item *pts_full = new Scene_points_with_normal_item;\n        pts_full->point_set()->add_normal_map();\n        CGAL::structure_point_set (points->begin (), points->end (),\n                                   points->point_map(), points->normal_map(),\n                                   boost::make_function_output_iterator (build_from_pair ((*(pts_full->point_set())))),\n                                   shape_detection,\n                                   op.cluster_epsilon);\n        if (pts_full->point_set ()->empty ())\n          delete pts_full;\n        else\n          {\n            pts_full->point_set ()->unselect_all();\n            pts_full->setName(tr(\"%1 (structured)\").arg(item->name()));\n            pts_full->setRenderingMode(PointsPlusNormals);\n            pts_full->setColor(Qt::blue);\n            scene->addItem (pts_full);\n          }\n        std::cerr << \"done\" << std::endl;\n      }\n    \n\n    // Updates scene\n    scene->itemChanged(index);\n\n    QApplication::restoreOverrideCursor();\n\n    //     Warn user, maybe choice of parameters is unsuitable\n    //         if (nb_points_to_remove > 0)\n    //         {\n    //           QMessageBox::information(NULL,\n    //                                    tr(\"Points selected for removal\"),\n    //                                    tr(\"%1 point(s) are selected for removal.\\nYou may delete or reset the selection using the item context menu.\")\n    //                                    .arg(nb_points_to_remove));\n    //         }\n    item->setVisible(false);\n  }\n}\n\nvoid Polyhedron_demo_point_set_shape_detection_plugin::build_alpha_shape\n(Point_set& points,  boost::shared_ptr<CGAL::Shape_detection_3::Plane<Traits> > plane,\n Scene_polyhedron_item* item, Scene_surface_mesh_item* sm_item, double epsilon)\n{\n  typedef Kernel::Point_2  Point_2;\n  typedef CGAL::Alpha_shape_vertex_base_2<Kernel> Vb;\n  typedef CGAL::Alpha_shape_face_base_2<Kernel>  Fb;\n  typedef CGAL::Triangulation_data_structure_2<Vb,Fb> Tds;\n  typedef CGAL::Delaunay_triangulation_2<Kernel,Tds> Triangulation_2;\n  typedef CGAL::Alpha_shape_2<Triangulation_2>  Alpha_shape_2;\n\n\n  std::vector<Point_2> projections;\n  projections.reserve (points.size ());\n\n  for (Point_set::const_iterator it = points.begin(); it != points.end(); ++ it)\n    projections.push_back (plane->to_2d (points.point(*it)));\n\n  Alpha_shape_2 ashape (projections.begin (), projections.end (), epsilon);\n  \n  std::map<Alpha_shape_2::Vertex_handle, std::size_t> map_v2i;\n\n  Scene_polygon_soup_item *soup_item = new Scene_polygon_soup_item;\n  \n  soup_item->init_polygon_soup(points.size(), ashape.number_of_faces ());\n  std::size_t current_index = 0;\n\n  for (Alpha_shape_2::Finite_faces_iterator it = ashape.finite_faces_begin ();\n       it != ashape.finite_faces_end (); ++ it)\n    {\n      if (ashape.classify (it) != Alpha_shape_2::INTERIOR)\n        continue;\n\n      for (int i = 0; i < 3; ++ i)\n        {\n          if (map_v2i.find (it->vertex (i)) == map_v2i.end ())\n            {\n              map_v2i.insert (std::make_pair (it->vertex (i), current_index ++));\n              Point p = plane->to_3d (it->vertex (i)->point ());\n              soup_item->new_vertex (p.x (), p.y (), p.z ());\n            }\n        }\n      soup_item->new_triangle (map_v2i[it->vertex (0)],\n                               map_v2i[it->vertex (1)],\n                               map_v2i[it->vertex (2)]);\n    }\n\n  soup_item->orient();\n  if(item){\n    soup_item->exportAsPolyhedron (item->polyhedron());\n  }\n  if(sm_item){\n    soup_item->exportAsSurfaceMesh (sm_item->polyhedron());\n  }\n\n  if (soup_item->isEmpty ())\n    {\n      std::cerr << \"POLYGON SOUP EMPTY\" << std::endl;\n      for (std::size_t i = 0; i < projections.size (); ++ i)\n        std::cerr << projections[i] << std::endl;\n      \n    }\n  \n  delete soup_item;\n}\n\n\n#include <QtPlugin>\n\n#include \"Point_set_shape_detection_plugin.moc\"\n", "meta": {"hexsha": "114a6eba6f245a16b057ef53f3028c491f4375c7", "size": 19424, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ext/libigl/external/cgal/src/CGAL_Project/demo/Polyhedron/Plugins/Point_set/Point_set_shape_detection_plugin.cpp", "max_stars_repo_name": "liminchen/OptCuts", "max_stars_repo_head_hexsha": "cb85b06ece3a6d1279863e26b5fd17a5abb0834d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 187.0, "max_stars_repo_stars_event_min_datetime": "2019-01-23T04:07:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T03:44:58.000Z", "max_issues_repo_path": "ext/libigl/external/cgal/src/CGAL_Project/demo/Polyhedron/Plugins/Point_set/Point_set_shape_detection_plugin.cpp", "max_issues_repo_name": "xiaoxie5002/OptCuts", "max_issues_repo_head_hexsha": "1f4168fc867f47face85fcfa3a572be98232786f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-03-22T13:27:38.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-18T13:23:23.000Z", "max_forks_repo_path": "ext/libigl/external/cgal/src/CGAL_Project/demo/Polyhedron/Plugins/Point_set/Point_set_shape_detection_plugin.cpp", "max_forks_repo_name": "xiaoxie5002/OptCuts", "max_forks_repo_head_hexsha": "1f4168fc867f47face85fcfa3a572be98232786f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 34.0, "max_forks_repo_forks_event_min_datetime": "2019-02-13T01:11:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T03:29:40.000Z", "avg_line_length": 38.6163021869, "max_line_length": 164, "alphanum_fraction": 0.6398785008, "num_tokens": 4636, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.4797949661003714}}
{"text": "#include \"gemm_common.h\"\n#include <Eigen/Cholesky>\n\nEIGEN_DONT_INLINE\nvoid llt(const Mat &A, const Mat &B, Mat &C)\n{\n  C = A;\n  C.diagonal().array() += 1000;\n  Eigen::internal::llt_inplace<Mat::Scalar, Lower>::blocked(C);\n}\n\nint main(int argc, char **argv)\n{\n  return main_gemm(argc, argv, llt);\n}\n", "meta": {"hexsha": "d55b7d80340a7a07c1090da6f82bb97b515b4842", "size": 298, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tools/eigen/bench/perf_monitoring/llt.cpp", "max_stars_repo_name": "Krissmedt/imprunko", "max_stars_repo_head_hexsha": "94171d0d47171cc4b199cd52f5f29385cbff903e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2111.0, "max_stars_repo_stars_event_min_datetime": "2019-01-29T07:01:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T06:48:14.000Z", "max_issues_repo_path": "tools/eigen/bench/perf_monitoring/llt.cpp", "max_issues_repo_name": "Krissmedt/imprunko", "max_issues_repo_head_hexsha": "94171d0d47171cc4b199cd52f5f29385cbff903e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 131.0, "max_issues_repo_issues_event_min_datetime": "2019-02-18T10:56:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-27T12:07:00.000Z", "max_forks_repo_path": "tools/eigen/bench/perf_monitoring/llt.cpp", "max_forks_repo_name": "Krissmedt/imprunko", "max_forks_repo_head_hexsha": "94171d0d47171cc4b199cd52f5f29385cbff903e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 421.0, "max_forks_repo_forks_event_min_datetime": "2019-02-12T07:59:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T05:22:01.000Z", "avg_line_length": 18.625, "max_line_length": 63, "alphanum_fraction": 0.6677852349, "num_tokens": 100, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7799929104825007, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4797641666264166}}
{"text": "#include <boost/test/unit_test.hpp>\r\n#include \"moja/flint/timing.h\"\r\n#include \"moja/datetime.h\"\r\n#include \"moja/flint/matrixeigen.h\"\r\n\r\n#include <memory>\r\n#include <sstream>\r\n#include <string>\r\n#include <fstream>\r\n#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n#include <time.h>\r\n#include <iomanip>      // std::setprecision\r\n\r\n// warning C4996: 'std::_Copy_impl': Function call with parameters that may be unsafe - this call relies on the caller to check that the passed values are correct.\r\n#pragma warning( push )\r\n#pragma warning( disable : 4996 )\r\n#include \"Eigen/Dense\"\r\n#include \"Eigen/Sparse\"\r\n#pragma warning( pop )\r\n\r\nusing namespace moja;\r\nusing namespace moja::flint;\r\n\r\nBOOST_AUTO_TEST_SUITE(MatrixTestsEigen);\r\n\r\ntypedef Eigen::SparseMatrix<double> EigenSparseMat; // declares a column-major sparse matrix type of double\r\ntypedef Eigen::DiagonalMatrix<double, Eigen::Dynamic, Eigen::Dynamic> EigenDiagonal;\r\ntypedef Eigen::MatrixXd EigenMat; // declares a dynamic matrix of type double\r\ntypedef Eigen::VectorXd EigenVec; // declares a dynamic vector of type double\r\ntypedef Eigen::MatrixXd moja_identity;\r\n\r\ntypedef Eigen::Triplet<double>\t\t\t\ttest_eigen_triplet;\r\ntypedef std::vector<moja_eigen_triplet>\t\ttest_eigen_tripletlist;\r\n\r\n\r\nvoid eigen_transferPool(EigenMat& _matrix, int source, int sink, double proportion) {\r\n\t//Eigen::Triplet<double> t(source, sink, proportion);\r\n\r\n\t_matrix(source, sink) += proportion;\r\n\t_matrix(source, source) -= proportion;\r\n}\r\n\r\nvoid eigen_transferPool_Sparse(test_eigen_tripletlist& tripletList, int source, int sink, double value) {\r\n\ttripletList.push_back(moja_eigen_triplet(sink, source, value));\r\n}\r\n\r\ntemplate <typename T>\r\ninline T sum_kahan3e(const EigenMat& xs) {\r\n\tif (xs.size() == 0) return 0;\r\n\tT sumP(0);\r\n\tT sumN(0);\r\n\tT tP(0);\r\n\tT tN(0);\r\n\tT cP(0);\r\n\tT cN(0);\r\n\tT yP(0);\r\n\tT yN(0);\r\n\tfor (size_t i = 0, size = xs.size(); i < size; i++) {\r\n\t\tif ((*(xs.data() + i)) > 0) {\r\n\t\t\tyP = (*(xs.data() + i)) - cP;\r\n\t\t\ttP = sumP + yP;\r\n\t\t\tcP = (tP - sumP) - yP;\r\n\t\t\tsumP = tP;\r\n\t\t}\r\n\t\telse {\r\n\t\t\tyN = (*(xs.data() + i)) - cN;\r\n\t\t\ttN = sumN + yN;\r\n\t\t\tcN = (tN - sumN) - yN;\r\n\t\t\tsumN = tN;\r\n\t\t}\r\n\t}\r\n\treturn sumP + sumN;\r\n}\r\n\r\n\r\n// --------------------------------------------------------------------------------------------\r\n\r\n#if 0\r\n\r\nBOOST_AUTO_TEST_CASE(flint_Matrix_eigen_DoSomeMatrixStuff) {\r\n\r\n\t// Shows setIdentity blanks matrix in bounds of the 1's being inserted in diag\r\n\r\n\tEigen::Matrix4i m1 = Eigen::Matrix4i::Zero();\r\n\tm1.block<3, 3>(1, 0).setIdentity();\r\n\tstd::cout << \"m1\" << std::endl;\r\n\tstd::cout << m1 << std::endl;\r\n\r\n\tEigen::Matrix4i m2 = Eigen::Matrix4i::Zero();\r\n\tm2(0, 1) = 9;\r\n\tm2(0, 2) = 7;\r\n\tm2.block<3, 3>(1, 0).setIdentity();\r\n\tstd::cout << \"m2\" << std::endl;\r\n\tstd::cout << m2 << std::endl;\r\n\r\n\tEigen::Matrix4i m3 = Eigen::Matrix4i::Zero();\r\n\tm3(0, 1) = 9;\r\n\tm3(0, 2) = 7;\r\n\tm3(1, 2) = 5;\r\n\tm3.setIdentity();\r\n\tstd::cout << \"m3\" << std::endl;\r\n\tstd::cout << m3 << std::endl;\r\n\r\n\t// Play with Vectors\r\n\r\n\tEigen::Matrix4i m4 = Eigen::Matrix4i::Identity();\r\n\r\n\tEigen::Vector2i v1 = Eigen::Vector2i::Zero();\r\n\tstd::cout << \"v1\" << std::endl;\r\n\tstd::cout << v1 << std::endl;\r\n\r\n\tEigen::Vector4i v2 = Eigen::Vector4i::Identity();\r\n\tstd::cout << \"v2\" << std::endl;\r\n\tstd::cout << v2 << std::endl;\r\n\r\n\tEigen::Vector4i r_v1 = m4 * v2;\r\n\tstd::cout << \"r_v1\" << std::endl;\r\n\tstd::cout << r_v1 << std::endl;\r\n\r\n\t//Eigen::Vector4i r_v2 = m4 * v1;\r\n\t//std::cout << \"r_v2\" << std::endl;\r\n\t//std::cout << r_v2 << std::endl;\r\n}\r\n\r\n#endif\r\n\r\n// --------------------------------------------------------------------------------------------\r\n\r\nBOOST_AUTO_TEST_CASE(moja_Matrix_eigen_iterate_data) {\r\n\tEigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> test = Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>::Random(5, 5);\r\n\r\n\tauto now = time(0);\r\n\tsum_kahan3e<double>(test);\r\n}\r\n\r\nvoid simpleConstructAndCalc(int length) {\r\n\tauto testName = boost::unit_test::framework::current_test_case().p_name;\r\n\tauto testSuiteName = (boost::unit_test::framework::get<boost::unit_test::test_suite>(boost::unit_test::framework::current_test_case().p_parent_id)).full_name();\r\n\r\n\tauto startConstruct = clock();\r\n\r\n\tmoja_eigen_matrix _testMatrix;\r\n\t_testMatrix.resize(length, length);\r\n\t_testMatrix.setIdentity();\r\n\t//_testMatrix.setZero();\r\n\tmoja_eigen_vector _testVector(length);\r\n\t_testVector.setRandom(length);\r\n\r\n\tauto finishConstruct = clock();\r\n\r\n\t//std::cout << std::setw(40) << std::setfill(' ') << testSuiteName << \": \" << std::setw(40) << std::setfill(' ') << testName << \": Mat : \" << _testMatrix << std::endl;\r\n\t//std::cout << std::setw(40) << std::setfill(' ') << testSuiteName << \": \" << std::setw(40) << std::setfill(' ') << testName << \": Vec : \" << _testVector << std::endl;\r\n\r\n\tauto startCalcs = clock();\r\n\r\n\tfor (int i = 0; i < 100; i++)\r\n\t\tfor (int j = 0; j < 10000; j++) {\r\n\t\t\tmoja_eigen_vector result = MOJA_EIGEN_MAT_PROD(_testMatrix, _testVector);\r\n\t\t}\r\n\r\n\tauto finishCalcs = clock();\r\n\tauto lengthCalcs = finishCalcs - startCalcs;\r\n\tauto lengthConstruct = finishConstruct - startConstruct;\r\n\r\n\t// CLOCKS_PER_SEC\r\n\tstd::cout << std::setw(40) << std::setfill(' ') << testSuiteName << \": \" << std::setw(40) << std::setfill(' ') << testName << \" : For size (\" << length << \"): construction : \" << lengthConstruct << std::endl;\r\n\tstd::cout << std::setw(40) << std::setfill(' ') << testSuiteName << \": \" << std::setw(40) << std::setfill(' ') << testName << \" : For size (\" << length << \"): calculations : \" << lengthCalcs << std::endl;\r\n}\r\n\r\n// --------------------------------------------------------------------------------------------\r\n\r\nBOOST_AUTO_TEST_CASE(flint_Matrix_eigen_SpeedChecks) {\r\n\t\r\n\tfor (int i = 10; i <= 60; i+=10)\r\n\t\tsimpleConstructAndCalc(i);\r\n}\r\n\r\n\r\n// --------------------------------------------------------------------------------------------\r\n\r\nBOOST_AUTO_TEST_CASE(moja_Matrix_eigen_001) {\r\n\tconst int numVars = 6;\r\n\tEigenVec pools(numVars);\r\n\tpools.setZero();\r\n\r\n\tpools[0] = 0.02;\r\n\tpools[1] = 8.681;\r\n\tpools[2] = 0.05;\r\n\tpools[3] = 0;\r\n\tpools[4] = 20.96;\r\n\tpools[5] = 0;\r\n\r\n\tEigenMat _I(numVars, numVars);\r\n\t_I.setIdentity();\r\n\r\n\tEigenDiagonal diag = pools.asDiagonal();\r\n\tEigenMat forOutput = diag;\r\n\r\n\tEigenMat matrix(numVars, numVars);\r\n\tmatrix.setIdentity();\r\n\r\n\teigen_transferPool(matrix, 0, 5, 0.250852);\r\n\teigen_transferPool(matrix, 1, 5, 0.012596);\r\n\teigen_transferPool(matrix, 2, 5, 0);\r\n\teigen_transferPool(matrix, 3, 5, 0.0190627);\r\n\teigen_transferPool(matrix, 4, 5, 0.00126915);\r\n\teigen_transferPool(matrix, 0, 2, 0.0397643);\r\n\teigen_transferPool(matrix, 1, 2, 0.00199667);\r\n\teigen_transferPool(matrix, 3, 2, 0.00302176);\r\n\teigen_transferPool(matrix, 4, 3, 0);\r\n\teigen_transferPool(matrix, 0, 4, 0.0413873);\r\n\teigen_transferPool(matrix, 1, 4, 0.00207817);\r\n\teigen_transferPool(matrix, 2, 4, 0);\r\n\teigen_transferPool(matrix, 3, 4, 0.00314509);\r\n\teigen_transferPool(matrix, 4, 4, 0.000410574);\r\n\r\n\tauto a = matrix - _I;\r\n\tauto b = diag * a;\r\n\tauto flux = b * 1; // timeScale\r\n\r\n\tpools = pools.transpose() * matrix; // timeScale\r\n\r\n\tBOOST_CHECK_CLOSE(pools[0], 0.013359927999999998, 0.000000000000001);\r\n\tBOOST_CHECK_CLOSE(pools[1], 8.5362804379599986, 0.000000000000001);\r\n\tBOOST_CHECK_CLOSE(pools[2], 0.068128378269999998, 0.000000000000001);\r\n\tBOOST_CHECK_CLOSE(pools[3], 0, 0.000000000000001);\r\n\tBOOST_CHECK_CLOSE(pools[4], 20.952266955769996, 0.000000000000001);\r\n\tBOOST_CHECK_CLOSE(pools[5], 0.14096429999999999, 0.000000000000001);\r\n}\r\n\r\n// --------------------------------------------------------------------------------------------\r\n// NOTE: Eigen will NOT remove the 0.0 results from the final sparse matrix \r\n\r\nBOOST_AUTO_TEST_CASE(moja_Matrix_eigen_zero_transfer_test) {\r\n\tauto testName = boost::unit_test::framework::current_test_case().p_name;\r\n\tauto testSuiteName = (boost::unit_test::framework::get<boost::unit_test::test_suite>(boost::unit_test::framework::current_test_case().p_parent_id)).full_name();\r\n\r\n\tconst int numVars = 6;\r\n\tEigenVec pools(numVars);\r\n\tpools.setZero();\r\n\r\n\tpools[0] = 0.02;\r\n\tpools[1] = 8.681;\r\n\tpools[2] = 0.05;\r\n\tpools[3] = 0;\r\n\tpools[4] = 20.96;\r\n\tpools[5] = 0;\r\n\r\n\tEigenMat _I(numVars, numVars);\r\n\t_I.setIdentity();\r\n\r\n\tEigenDiagonal diag = pools.asDiagonal();\r\n\ttest_eigen_tripletlist tripletList;\r\n\tEigenSparseMat matrix;\r\n\tmatrix.resize(numVars, numVars);\r\n\tmatrix.reserve(5);\r\n\t//matrix.setZero();\r\n\r\n\t//std::cout << std::setw(40) << std::setfill(' ') << testSuiteName << \": \" << std::setw(50) << std::setfill(' ') << testName << \": matrix blank\" << std::endl;\r\n\t//std::cout << matrix << std::endl;\r\n\r\n\teigen_transferPool_Sparse(tripletList, 0, 5, 0.0);\r\n\teigen_transferPool_Sparse(tripletList, 0, 4, 0.1);\r\n\r\n\tmatrix.setFromTriplets(tripletList.begin(), tripletList.end());\r\n\r\n\t//std::cout << std::setw(40) << std::setfill(' ') << testSuiteName << \": \" << std::setw(50) << std::setfill(' ') << testName << \": matrix set\" << std::endl;\r\n\t//std::cout << matrix << std::endl;\r\n\r\n\tstd::cout << std::setw(40) << std::setfill(' ') << testSuiteName << \": \" << std::setw(50) << std::setfill(' ') << testName << \": matrix iteration\" << std::endl;\r\n\tfor (int k = 0; k < matrix.outerSize(); ++k) {\r\n\t\tfor (EigenSparseMat::InnerIterator flux(matrix, k); flux; ++flux) {\r\n\t\t\tauto srcIx = flux.col();\r\n\t\t\tauto dstIx = flux.row();\r\n\t\t\tauto val = flux.value();\r\n\r\n\t\t\tstd::cout << \"Src: \" << srcIx << \", Dst: \" << dstIx << \", Val: \" << val << std::endl;\r\n\t\t}\r\n\t}\r\n\r\n\tEigenSparseMat fluxes = matrix * diag;\r\n\r\n\t//std::cout << std::setw(40) << std::setfill(' ') << testSuiteName << \": \" << std::setw(50) << std::setfill(' ') << testName << \": fluxes\" << std::endl;\r\n\t//std::cout << fluxes << std::endl;\r\n\r\n\tstd::cout << std::setw(40) << std::setfill(' ') << testSuiteName << \": \" << std::setw(50) << std::setfill(' ') << testName << \": fluxes iteration\" << std::endl;\r\n\tfor (int k = 0; k < fluxes.outerSize(); ++k) {\r\n\t\tfor (EigenSparseMat::InnerIterator flux(fluxes, k); flux; ++flux) {\r\n\t\t\tauto srcIx = flux.col();\r\n\t\t\tauto dstIx = flux.row();\r\n\t\t\tauto val = flux.value();\r\n\r\n\t\t\tstd::cout << \"Src: \" << srcIx << \", Dst: \" << dstIx << \", Val: \" << val << std::endl;\r\n\t\t}\r\n\t}\r\n\r\n}\r\n\r\nBOOST_AUTO_TEST_SUITE_END();\r\n", "meta": {"hexsha": "db57fc29b430789f7de8cc37a7df20f2dedcc8b1", "size": 10171, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Source/moja.flint/tests/src/matrixtestseigen.cpp", "max_stars_repo_name": "moja-global/flint", "max_stars_repo_head_hexsha": "2c65c5808d908247ce8ee4d9f87f11c7dd57794e", "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": "Source/moja.flint/tests/src/matrixtestseigen.cpp", "max_issues_repo_name": "moja-global/flint", "max_issues_repo_head_hexsha": "2c65c5808d908247ce8ee4d9f87f11c7dd57794e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-07-12T11:30:00.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-18T14:50:16.000Z", "max_forks_repo_path": "Source/moja.flint/tests/src/matrixtestseigen.cpp", "max_forks_repo_name": "moja-global/flint", "max_forks_repo_head_hexsha": "2c65c5808d908247ce8ee4d9f87f11c7dd57794e", "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.678807947, "max_line_length": 210, "alphanum_fraction": 0.6081997837, "num_tokens": 3071, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.779992900254107, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4797641603350558}}
{"text": "#include <stan/math/mix/scal.hpp>\n#include <gtest/gtest.h>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n#include <test/unit/math/rev/scal/fun/util.hpp>\n#include <test/unit/math/mix/scal/fun/nan_util.hpp>\n\n\nTEST(AgradFwdGammaP, FvarVar_FvarVar_1stDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n\n  fvar<var> x(0.5,1.0);\n  fvar<var> z(1.0,1.0);\n  fvar<var> a = stan::math::gamma_p(x,z);\n\n  EXPECT_FLOAT_EQ(boost::math::gamma_p(0.5,1.0), a.val_.val());\n  EXPECT_FLOAT_EQ(-0.18228334, a.d_.val());\n\n  AVEC y = createAVEC(x.val_,z.val_);\n  VEC g;\n  a.val_.grad(y,g);\n  EXPECT_FLOAT_EQ(-0.38983709,g[0]);\n  EXPECT_FLOAT_EQ(boost::math::gamma_p_derivative(0.5,1.0),g[1]);\n}\nTEST(AgradFwdGammaP, Double_FvarVar_1stDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n\n  double x(0.5);\n  fvar<var> z(1.0,1.0);\n  fvar<var> a = stan::math::gamma_p(x,z);\n\n  EXPECT_FLOAT_EQ(boost::math::gamma_p(0.5,1.0), a.val_.val());\n  EXPECT_FLOAT_EQ(boost::math::gamma_p_derivative(0.5,1.0), a.d_.val());\n\n  AVEC y = createAVEC(z.val_);\n  VEC g;\n  a.val_.grad(y,g);\n  EXPECT_FLOAT_EQ(boost::math::gamma_p_derivative(0.5,1.0),g[0]);\n}\nTEST(AgradFwdGammaP, FvarVar_Double_1stDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n\n  fvar<var> x(0.5,1.0);\n  double z(1.0);\n  fvar<var> a = stan::math::gamma_p(x,z);\n\n  EXPECT_FLOAT_EQ(boost::math::gamma_p(0.5,1.0), a.val_.val());\n  EXPECT_FLOAT_EQ(-0.38983709, a.d_.val());\n\n  AVEC y = createAVEC(x.val_);\n  VEC g;\n  a.val_.grad(y,g);\n  EXPECT_FLOAT_EQ(-0.38983709,g[0]);\n}\nTEST(AgradFwdGammaP, FvarVar_FvarVar_2ndDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n\n  fvar<var> x(0.5,1.0);\n  fvar<var> z(1.0,1.0);\n  fvar<var> a = stan::math::gamma_p(x,z);\n\n  EXPECT_FLOAT_EQ(boost::math::gamma_p(0.5,1.0), a.val_.val());\n  EXPECT_FLOAT_EQ(-0.18228334, a.d_.val());\n\n  AVEC y = createAVEC(x.val_,z.val_);\n  VEC g;\n  a.d_.grad(y,g);\n  EXPECT_FLOAT_EQ(0.19403456,g[0]);\n  EXPECT_FLOAT_EQ(0.096204743,g[1]);\n}\nTEST(AgradFwdGammaP, Double_FvarVar_2ndDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n\n  double x(0.5);\n  fvar<var> z(1.0,1.0);\n  fvar<var> a = stan::math::gamma_p(x,z);\n\n  EXPECT_FLOAT_EQ(boost::math::gamma_p(0.5,1.0), a.val_.val());\n  EXPECT_FLOAT_EQ(boost::math::gamma_p_derivative(0.5,1.0), a.d_.val());\n\n  AVEC y = createAVEC(z.val_);\n  VEC g;\n  a.d_.grad(y,g);\n  EXPECT_FLOAT_EQ(-0.31133062,g[0]);\n}\nTEST(AgradFwdGammaP, FvarVar_Double_2ndDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n\n  fvar<var> x(0.5,1.0);\n  double z(1.0);\n  fvar<var> a = stan::math::gamma_p(x,z);\n\n  EXPECT_FLOAT_EQ(boost::math::gamma_p(0.5,1.0), a.val_.val());\n  EXPECT_FLOAT_EQ(-0.38983709, a.d_.val());\n\n  AVEC y = createAVEC(x.val_);\n  VEC g;\n  a.d_.grad(y,g);\n  EXPECT_FLOAT_EQ(-0.21349931,g[0]);\n}\n\n\n\nTEST(AgradFwdGammaP, FvarFvarVar_FvarFvarVar_1stDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using boost::math::gamma_p;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 0.5;\n  x.val_.d_ = 1.0;\n\n  fvar<fvar<var> > y;\n  y.val_.val_ = 1.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = gamma_p(x,y);\n\n  EXPECT_FLOAT_EQ(gamma_p(0.5,1.0), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(-0.38983709, a.val_.d_.val());\n  EXPECT_FLOAT_EQ(boost::math::gamma_p_derivative(0.5,1.0), a.d_.val_.val());\n  EXPECT_FLOAT_EQ(0.40753385, a.d_.d_.val());\n\n  AVEC p = createAVEC(x.val_.val_,y.val_.val_);\n  VEC g;\n  a.val_.val_.grad(p,g);\n  EXPECT_FLOAT_EQ(-0.38983709, g[0]);\n  EXPECT_FLOAT_EQ(boost::math::gamma_p_derivative(0.5,1.0), g[1]);\n}\nTEST(AgradFwdGammaP, Double_FvarFvarVar_1stDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using boost::math::gamma_p;\n\n  double x(0.5);\n\n  fvar<fvar<var> > y;\n  y.val_.val_ = 1.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = gamma_p(x,y);\n\n  EXPECT_FLOAT_EQ(gamma_p(0.5,1.0), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(0, a.val_.d_.val());\n  EXPECT_FLOAT_EQ(boost::math::gamma_p_derivative(0.5,1.0), a.d_.val_.val());\n  EXPECT_FLOAT_EQ(0, a.d_.d_.val());\n\n  AVEC p = createAVEC(y.val_.val_);\n  VEC g;\n  a.val_.val_.grad(p,g);\n  EXPECT_FLOAT_EQ(boost::math::gamma_p_derivative(0.5,1.0), g[0]);\n}\nTEST(AgradFwdGammaP, FvarFvarVar_Double_1stDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using boost::math::gamma_p;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 0.5;\n  x.val_.d_ = 1.0;\n\n  double y(1.0);\n\n  fvar<fvar<var> > a = gamma_p(x,y);\n\n  EXPECT_FLOAT_EQ(gamma_p(0.5,1.0), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(-0.38983709, a.val_.d_.val());\n  EXPECT_FLOAT_EQ(0, a.d_.val_.val());\n  EXPECT_FLOAT_EQ(0, a.d_.d_.val());\n\n  AVEC p = createAVEC(x.val_.val_);\n  VEC g;\n  a.val_.val_.grad(p,g);\n  EXPECT_FLOAT_EQ(-0.38983709, g[0]);\n}\n\nTEST(AgradFwdGammaP, FvarFvarVar_FvarFvarVar_2ndDeriv_x) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using boost::math::gamma_p;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 0.5;\n  x.val_.d_ = 1.0;\n\n  fvar<fvar<var> > y;\n  y.val_.val_ = 1.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = gamma_p(x,y);\n\n  EXPECT_FLOAT_EQ(gamma_p(0.5,1.0), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(-0.38983709, a.val_.d_.val());\n  EXPECT_FLOAT_EQ(boost::math::gamma_p_derivative(0.5,1.0), a.d_.val_.val());\n  EXPECT_FLOAT_EQ(0.40753385, a.d_.d_.val());\n\n  AVEC p = createAVEC(x.val_.val_,y.val_.val_);\n  VEC g;\n  a.val_.d_.grad(p,g);\n  EXPECT_FLOAT_EQ(-0.21349931, g[0]);\n  EXPECT_FLOAT_EQ(0.40753537, g[1]);\n}\nTEST(AgradFwdGammaP, FvarFvarVar_FvarFvarVar_2ndDeriv_y) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using boost::math::gamma_p;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 0.5;\n  x.val_.d_ = 1.0;\n\n  fvar<fvar<var> > y;\n  y.val_.val_ = 1.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = gamma_p(x,y);\n\n  EXPECT_FLOAT_EQ(gamma_p(0.5,1.0), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(-0.38983709, a.val_.d_.val());\n  EXPECT_FLOAT_EQ(boost::math::gamma_p_derivative(0.5,1.0), a.d_.val_.val());\n  EXPECT_FLOAT_EQ(0.40753385, a.d_.d_.val());\n\n  AVEC p = createAVEC(x.val_.val_,y.val_.val_);\n  VEC g;\n  a.d_.val_.grad(p,g);\n  EXPECT_FLOAT_EQ(0.40753385, g[0]);\n  EXPECT_FLOAT_EQ(-0.31133062, g[1]);\n}\nTEST(AgradFwdGammaP, Double_FvarFvarVar_2ndDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using boost::math::gamma_p;\n\n  double x(0.5);\n\n  fvar<fvar<var> > y;\n  y.val_.val_ = 1.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = gamma_p(x,y);\n\n  EXPECT_FLOAT_EQ(gamma_p(0.5,1.0), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(0, a.val_.d_.val());\n  EXPECT_FLOAT_EQ(boost::math::gamma_p_derivative(0.5,1.0), a.d_.val_.val());\n  EXPECT_FLOAT_EQ(0, a.d_.d_.val());\n\n  AVEC p = createAVEC(y.val_.val_);\n  VEC g;\n  a.d_.val_.grad(p,g);\n  EXPECT_FLOAT_EQ(-0.31133062, g[0]);\n}\nTEST(AgradFwdGammaP, FvarFvarVar_Double_2ndDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using boost::math::gamma_p;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 0.5;\n  x.val_.d_ = 1.0;\n\n  double y(1.0);\n\n  fvar<fvar<var> > a = gamma_p(x,y);\n\n  EXPECT_FLOAT_EQ(gamma_p(0.5,1.0), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(-0.38983709, a.val_.d_.val());\n  EXPECT_FLOAT_EQ(0, a.d_.val_.val());\n  EXPECT_FLOAT_EQ(0, a.d_.d_.val());\n\n  AVEC p = createAVEC(x.val_.val_);\n  VEC g;\n  a.val_.d_.grad(p,g);\n  EXPECT_FLOAT_EQ(-0.21349931, g[0]);\n}\n\nTEST(AgradFwdGammaP, FvarFvarVar_FvarFvarVar_3rdDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using boost::math::gamma_p;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 0.5;\n  x.val_.d_ = 1.0;\n\n  fvar<fvar<var> > y;\n  y.val_.val_ = 1.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = gamma_p(x,y);\n\n  EXPECT_FLOAT_EQ(gamma_p(0.5,1.0), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(-0.38983709, a.val_.d_.val());\n  EXPECT_FLOAT_EQ(boost::math::gamma_p_derivative(0.5,1.0), a.d_.val_.val());\n  EXPECT_FLOAT_EQ(0.40753385, a.d_.d_.val());\n\n  AVEC p = createAVEC(x.val_.val_,y.val_.val_);\n  VEC g;\n  a.d_.d_.grad(p,g);\n  EXPECT_FLOAT_EQ(-0.22403987, g[0]);\n  EXPECT_FLOAT_EQ(-0.40374705, g[1]);\n}\nTEST(AgradFwdGammaP, Double_FvarFvarVar_3rdDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using boost::math::gamma_p;\n\n  double x(0.5);\n\n  fvar<fvar<var> > y;\n  y.val_.val_ = 1.0;\n  y.d_.val_ = 1.0;\n  y.val_.d_ = 1.0;\n\n  fvar<fvar<var> > a = gamma_p(x,y);\n\n  AVEC p = createAVEC(y.val_.val_);\n  VEC g;\n  a.d_.d_.grad(p,g);\n  EXPECT_FLOAT_EQ(0.57077283, g[0]);\n}\nTEST(AgradFwdGammaP, FvarFvarVar_Double_3rdDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using boost::math::gamma_p;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 0.5;\n  x.val_.d_ = 1.0;\n  x.d_.val_ = 1.0;\n\n  double y(1.0);\n\n  fvar<fvar<var> > a = gamma_p(x,y);\n\n  AVEC p = createAVEC(x.val_.val_);\n  VEC g;\n  a.d_.d_.grad(p,g);\n  EXPECT_FLOAT_EQ(0.5462361, g[0]);\n}\n\nstruct gamma_p_fun {\n  template <typename T0, typename T1>\n  inline \n  typename boost::math::tools::promote_args<T0,T1>::type\n  operator()(const T0 arg1,\n             const T1 arg2) const {\n    return gamma_p(arg1,arg2);\n  }\n};\n\nTEST(AgradFwdGammaP, nan) {\n  gamma_p_fun gamma_p_;\n  test_nan_mix(gamma_p_,3.0,5.0,false);\n}\n", "meta": {"hexsha": "6ad39849b260dd087c041c36b90b60df413c661c", "size": 8971, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/mix/scal/fun/gamma_p_test.cpp", "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/test/unit/math/mix/scal/fun/gamma_p_test.cpp", "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/test/unit/math/mix/scal/fun/gamma_p_test.cpp", "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": 24.8504155125, "max_line_length": 77, "alphanum_fraction": 0.6543306209, "num_tokens": 3586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4797641603350557}}
{"text": "#ifndef HAMILTONIANS_XXZ_HPP\n#define HAMILTONIANS_XXZ_HPP\n#include <Eigen/Eigen>\n#include <nlohmann/json.hpp>\n\nclass XXZ\n{\nprivate:\n\tint n_;\n\tdouble J_;\n\tdouble Delta_;\n\tdouble sign_;\n\npublic:\n\n\tXXZ(int n, double J, double Delta, bool signRule = false)\n\t\t: n_(n), J_(J), Delta_(Delta)\n\t{\n\t\tif(signRule)\n\t\t\tsign_ = -1.0;\n\t\telse\n\t\t\tsign_ = 1.0;\n\t}\n\n\tnlohmann::json params() const\n\t{\n\t\treturn nlohmann::json\n\t\t{\n\t\t\t{\"name\", \"XXZ\"},\n\t\t\t{\"n\", n_},\n\t\t\t{\"J\", J_},\n\t\t\t{\"Delta\", Delta_},\n\t\t\t{\"sign_rule\", int(sign_)}\n\t\t};\n\t}\n\t\n\ttemplate<class State>\n\ttypename State::Scalar operator()(const State& smp) const\n\t{\n\t\ttypename State::Scalar s = 0.0;\n\t\t//Nearest-neighbor\n\t\tfor(int i = 0; i < n_; i++)\n\t\t{\n\t\t\tint zz = smp.sigmaAt(i)*smp.sigmaAt((i+1)%n_);\n\t\t\ts += J_*Delta_*zz; //zz\n\t\t\ts += sign_*J_*(1-zz)*smp.ratio(i, (i+1)%n_); //xx+yy\n\t\t}\n\t\treturn s;\n\t}\n\n\tstd::map<uint32_t, double> operator()(uint32_t col) const\n\t{\n\t\tstd::map<uint32_t, double> m;\n\t\tfor(int i = 0; i < n_; i++)\n\t\t{\n\t\t\tint b1 = (col >> i) & 1;\n\t\t\tint b2 = (col >> ((i+1)%n_)) & 1;\n\t\t\tint zz = (1-2*b1)*(1-2*b2);\n\t\t\tlong long int x = (1 << i) | (1 << ((i+1)%(n_)));\n\t\t\tm[col] += J_*Delta_*zz;\n\t\t\tm[col ^ x] += sign_*J_*(1 - zz);\n\t\t}\n\t\treturn m;\n\t}\n};\n#endif//HAMILTONIANS_XXZ_HPP\n", "meta": {"hexsha": "b3b63baa733ae1e36870d31905bb2ea99ef1883b", "size": 1236, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Yannq/Hamiltonians/XXZ.hpp", "max_stars_repo_name": "cecri/yannq", "max_stars_repo_head_hexsha": "b78c1f86a255059f06b34dd5e538449e7261d0ee", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Yannq/Hamiltonians/XXZ.hpp", "max_issues_repo_name": "cecri/yannq", "max_issues_repo_head_hexsha": "b78c1f86a255059f06b34dd5e538449e7261d0ee", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Yannq/Hamiltonians/XXZ.hpp", "max_forks_repo_name": "cecri/yannq", "max_forks_repo_head_hexsha": "b78c1f86a255059f06b34dd5e538449e7261d0ee", "max_forks_repo_licenses": ["BSD-3-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.447761194, "max_line_length": 58, "alphanum_fraction": 0.5663430421, "num_tokens": 496, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6150878555160664, "lm_q1q2_score": 0.47976416033505564}}
{"text": "////////////////////////////////////////////////////////////////////\n//\n// $Id: QEM.hxx 2021/06/05 14:25:18 kanai Exp $\n//\n// Copyright (c) 2021 Takashi Kanai\n// Released under the MIT license\n//\n////////////////////////////////////////////////////////////////////\n\n#ifndef _QEM_HXX\n#define _QEM_HXX 1\n\n#include <vector>\n#include <cmath>\n#include <cstring>\nusing namespace std;\n\n#include \"VertexL.hxx\"\n#include \"FaceL.hxx\"\n\n#if 1\n#include <Eigen/Dense>\n#include <Eigen/Cholesky>\n//using namespace Eigen;\n#endif\n\n#define DEFAULT_QEM_SIZE 10\n\nclass QEM {\n\n  std::vector<double> mat_;\n\n public:\n\n  QEM(){\n    resize( DEFAULT_QEM_SIZE );\n    init();\n  };\n  QEM(int size) { resize( size ); init(); };\n  QEM( VertexL* vt ) {\n    resize( DEFAULT_QEM_SIZE );\n    init();\n    QEM q;\n    q.construct(vt);\n    add(q);\n  };\n  QEM( HalfedgeL* he ) {\n    resize( DEFAULT_QEM_SIZE );\n    init();\n    QEM q;\n    q.construct(he);\n    add(q);\n  };\n  QEM( HalfedgeL* he, double penalty ) {\n    resize( DEFAULT_QEM_SIZE );\n    init();\n    QEM q; q.construct_boundary( he, penalty );\n    add(q);\n  };\n  // copy constructor\n  QEM( const QEM& q ) {\n    resize( q.size() );\n    set(q);\n  };\n  \n  ~QEM(){};\n\n  int size() const { return mat_.size(); };\n  void resize( int n ) { mat_.resize( n ); };\n  void init() { for ( unsigned int i = 0; i < mat_.size(); ++i ) mat_[i]=0.0; };\n  void clear() { for ( unsigned int i = 0; i < mat_.size(); ++i ) mat_[i]=0.0; };\n  \n  void optimizePoint( VertexL* vt ) {\n    optimizePoint( vt->point() );\n  };\n  bool optimizePoint( Point3d& );\n  // matrix inverse\n  bool inverse( QEM& );\n\n  double error( Point3d& );\n\n  // vertex QEM\n  void construct( VertexL* vt ) {\n    QEM q;\n    construct( vt, q );\n    add(q);\n  };\n  void construct( VertexL*, QEM& );\n  \n  // face QEM\n  void construct( HalfedgeL* he ) {\n    QEM q;\n    construct( he, q );\n    add(q);\n  };\n  void construct( HalfedgeL*, QEM& );\n  void construct( FaceL*, QEM& );\n\n  void construct_boundary( HalfedgeL* he, double penalty ) {\n    QEM q;\n    construct_boundary( he, penalty, q );\n    add(q);\n  };\n  void construct_boundary( HalfedgeL*, double, QEM& );\n  \n  void setMat( int i, double val ) {\n//     if ( val < .0 ) cout << i << \" \" << val << endl;\n    mat_[i] = val;\n  };\n  //void set( VertexL* );\n\n  void set( const QEM& q ) {\n    for ( unsigned int i = 0; i < mat_.size(); ++i )\n      mat_[i] = q.mat(i);\n  };\n  void mul( Point3d& p ) {\n    Point3d q;\n    mul(p, q);\n    p.set(q);\n  };\n  \n  void mul( Point3d& p, Point3d& q ) {\n    q.x = mat_[0]*p.x + mat_[3]*p.y + mat_[4]*p.z;\n    q.y = mat_[3]*p.x + mat_[1]*p.y + mat_[5]*p.z;\n    q.z = mat_[4]*p.x + mat_[5]*p.y + mat_[2]*p.z;\n  };\n    \n  void add( const QEM& q1, const QEM& q2 ) {\n    for (unsigned int i = 0; i < mat_.size(); ++i )\n      mat_[i] += (q1.mat(i) + q2.mat(i));\n  };\n  \n  void add( const QEM& q ) {\n    for (unsigned int i = 0; i < mat_.size(); ++i )\n      mat_[i] += q.mat(i);\n  };\n\n  bool equals( const QEM& q ) {\n    return ( (mat_[0] == q.mat(0)) && (mat_[1] == q.mat(1)) &&\n\t     (mat_[2] == q.mat(2)) && (mat_[3] == q.mat(3)) &&\n\t     (mat_[4] == q.mat(4)) && (mat_[5] == q.mat(5)) &&\n\t     (mat_[6] == q.mat(6)) && (mat_[7] == q.mat(7)) &&\n\t     (mat_[8] == q.mat(8)) && (mat_[9] == q.mat(9)) );\n  };\n  \n  void scale( double t ) {\n    for (unsigned int i = 0; i < mat_.size(); ++i )\n      mat_[i] *= t;\n  };\n\n  double sum() {\n    double t = .0;\n    for ( unsigned int i = 0; i < mat_.size(); ++i ) t += mat_[i];\n    return t;\n  };\n  \n  void copy( QEM& q ) {\n    for ( unsigned int i = 0; i < mat_.size(); ++i )\n      q.setMat(i, mat_[i]);\n  };\n\n  //\n  // operators\n  //\n  QEM& operator=( const QEM& q ) {\n    set(q);\n    return *this;\n  };\n  \n  QEM& operator+=( const QEM& q ) {\n    add( q );\n    return *this;\n  };\n\n  bool operator==(const QEM& q ) {\n    return equals(q);\n  };\n  \n  friend std::ostream& operator <<( std::ostream& o, const QEM& q ) {\n    return o << \"( \" << q.mat(0) << \", \" << q.mat(1) << \", \" << q.mat(2) << \", \" << q.mat(3) << \", \" << q.mat(4) << \" \" << q.mat(5) << \" \" << q.mat(6) << \" \" << q.mat(7) << \" \" << q.mat(8) << \" \" << q.mat(9) << \" )\\n\";\n  };\n  \n  double mat(int i) const { return mat_[i]; };\n  //std::vector<double>* mat() { return &mat_; };\n\n  bool invert( double* m, double* invOut ) {\n\n    double inv[16];\n    inv[0] = m[5]  * m[10] * m[15] - \n             m[5]  * m[11] * m[14] - \n             m[9]  * m[6]  * m[15] + \n             m[9]  * m[7]  * m[14] +\n             m[13] * m[6]  * m[11] - \n             m[13] * m[7]  * m[10];\n\n    inv[4] = -m[4]  * m[10] * m[15] + \n              m[4]  * m[11] * m[14] + \n              m[8]  * m[6]  * m[15] - \n              m[8]  * m[7]  * m[14] - \n              m[12] * m[6]  * m[11] + \n              m[12] * m[7]  * m[10];\n\n    inv[8] = m[4]  * m[9] * m[15] - \n             m[4]  * m[11] * m[13] - \n             m[8]  * m[5] * m[15] + \n             m[8]  * m[7] * m[13] + \n             m[12] * m[5] * m[11] - \n             m[12] * m[7] * m[9];\n\n    inv[12] = -m[4]  * m[9] * m[14] + \n               m[4]  * m[10] * m[13] +\n               m[8]  * m[5] * m[14] - \n               m[8]  * m[6] * m[13] - \n               m[12] * m[5] * m[10] + \n               m[12] * m[6] * m[9];\n\n    inv[1] = -m[1]  * m[10] * m[15] + \n              m[1]  * m[11] * m[14] + \n              m[9]  * m[2] * m[15] - \n              m[9]  * m[3] * m[14] - \n              m[13] * m[2] * m[11] + \n              m[13] * m[3] * m[10];\n\n    inv[5] = m[0]  * m[10] * m[15] - \n             m[0]  * m[11] * m[14] - \n             m[8]  * m[2] * m[15] + \n             m[8]  * m[3] * m[14] + \n             m[12] * m[2] * m[11] - \n             m[12] * m[3] * m[10];\n\n    inv[9] = -m[0]  * m[9] * m[15] + \n              m[0]  * m[11] * m[13] + \n              m[8]  * m[1] * m[15] - \n              m[8]  * m[3] * m[13] - \n              m[12] * m[1] * m[11] + \n              m[12] * m[3] * m[9];\n\n    inv[13] = m[0]  * m[9] * m[14] - \n              m[0]  * m[10] * m[13] - \n              m[8]  * m[1] * m[14] + \n              m[8]  * m[2] * m[13] + \n              m[12] * m[1] * m[10] - \n              m[12] * m[2] * m[9];\n\n    inv[2] = m[1]  * m[6] * m[15] - \n             m[1]  * m[7] * m[14] - \n             m[5]  * m[2] * m[15] + \n             m[5]  * m[3] * m[14] + \n             m[13] * m[2] * m[7] - \n             m[13] * m[3] * m[6];\n\n    inv[6] = -m[0]  * m[6] * m[15] + \n              m[0]  * m[7] * m[14] + \n              m[4]  * m[2] * m[15] - \n              m[4]  * m[3] * m[14] - \n              m[12] * m[2] * m[7] + \n              m[12] * m[3] * m[6];\n\n    inv[10] = m[0]  * m[5] * m[15] - \n              m[0]  * m[7] * m[13] - \n              m[4]  * m[1] * m[15] + \n              m[4]  * m[3] * m[13] + \n              m[12] * m[1] * m[7] - \n              m[12] * m[3] * m[5];\n\n    inv[14] = -m[0]  * m[5] * m[14] + \n               m[0]  * m[6] * m[13] + \n               m[4]  * m[1] * m[14] - \n               m[4]  * m[2] * m[13] - \n               m[12] * m[1] * m[6] + \n               m[12] * m[2] * m[5];\n\n    inv[3] = -m[1] * m[6] * m[11] + \n              m[1] * m[7] * m[10] + \n              m[5] * m[2] * m[11] - \n              m[5] * m[3] * m[10] - \n              m[9] * m[2] * m[7] + \n              m[9] * m[3] * m[6];\n\n    inv[7] = m[0] * m[6] * m[11] - \n             m[0] * m[7] * m[10] - \n             m[4] * m[2] * m[11] + \n             m[4] * m[3] * m[10] + \n             m[8] * m[2] * m[7] - \n             m[8] * m[3] * m[6];\n\n    inv[11] = -m[0] * m[5] * m[11] + \n               m[0] * m[7] * m[9] + \n               m[4] * m[1] * m[11] - \n               m[4] * m[3] * m[9] - \n               m[8] * m[1] * m[7] + \n               m[8] * m[3] * m[5];\n\n    inv[15] = m[0] * m[5] * m[10] - \n              m[0] * m[6] * m[9] - \n              m[4] * m[1] * m[10] + \n              m[4] * m[2] * m[9] + \n              m[8] * m[1] * m[6] - \n              m[8] * m[2] * m[5];\n\n    double det = m[0] * inv[0] + m[1] * inv[4] + m[2] * inv[8] + m[3] * inv[12];\n\n    // cout << \"det \" << det << endl;\n    if (det == 0) return false;\n\n    det = 1.0 / det;\n    for (int i = 0; i < 16; i++)\n      {\n        invOut[i] = inv[i] * det;\n      }\n\n    return true;\n  };\n\n  void cholesky4( double* A, double* L ) {\n\n    //double *L = (double*)calloc(n * n, sizeof(double));\n    //if (L == NULL)\n    //exit(EXIT_FAILURE);\n    for ( int i = 0; i < 16; ++i ) L[i] = .0;\n\n    int n = 4;\n    for (int i = 0; i < n; i++)\n      for (int j = 0; j < (i+1); j++) {\n        double s = 0;\n        for (int k = 0; k < j; k++)\n          s += L[i * n + k] * L[j * n + k];\n        L[i * n + j] = (i == j) ?\n          std::sqrt(A[i * n + i] - s) :\n          (1.0 / L[j * n + j] * (A[i * n + j] - s));\n      }\n    // cout << \"cholesky \";\n    // for ( int m = 0; m < 16; ++m )\n    //   cout << L[m] << \" \";\n    // cout << endl;\n  };\n\n  void toInvR( double* Rinv ) {\n\n    Eigen::MatrixXd A(4,4);\n    A << mat_[0], mat_[3], mat_[4], mat_[6],\n      mat_[3], mat_[1], mat_[5], mat_[7],\n      mat_[4], mat_[5], mat_[2], mat_[8],\n      mat_[6], mat_[7], mat_[8], mat_[9];\n\n    // Cholesky decomposition\n    Eigen::LLT<Eigen::MatrixXd> lltOfA(A);\n    Eigen::MatrixXd L = lltOfA.matrixL();\n    // Inverse\n    Eigen::MatrixXd Linv = L.inverse();\n\n    // OpenGL is column-major\n    Eigen::MatrixXd Linvtrans = Linv.transpose();\n    memcpy( Rinv, Linvtrans.data(), sizeof(double) * 16 );\n\n#if 0\n    // OpenGL is column-major\n    for ( int i = 0; i < 4; ++i )\n      for ( int j = 0; j < 4; ++j )\n        Rinv[ 4 * i + j ] = Linv(i,j);\n#endif\n\n#if 0\n    double a[16];\n    Eigen::MatrixXd Linvtrans = Linv.transpose();\n    memcpy( a, Linvtrans.data(), sizeof(double) * 16 );\n\n    cout << \"Rinv \";\n    for ( int i = 0; i < 4; ++i )\n      for ( int j = 0; j < 4; ++j )\n        cout << Rinv[ 4 * i + j ] << \" \";\n    cout << endl;\n\n    cout << \"a \";\n    for ( int i = 0; i < 4; ++i )\n      for ( int j = 0; j < 4; ++j )\n        cout << a[ 4 * i + j ] << \" \";\n    cout << endl;\n#endif\n\n#if 0\n    double p[16];\n    p[0]  = mat_[0]; p[1]  = mat_[3]; p[2]  = mat_[4]; p[3]  = mat_[6];\n    p[4]  = mat_[3]; p[5]  = mat_[1]; p[6]  = mat_[5]; p[7]  = mat_[7];\n    p[8]  = mat_[4]; p[9]  = mat_[5]; p[10] = mat_[2]; p[11] = mat_[8];\n    p[12] = mat_[6]; p[13] = mat_[7]; p[14] = mat_[8]; p[15] = mat_[9];\n\n    // cout << \"p \";\n    // for ( int m = 0; m < 16; ++m )\n    //   cout << p[m] << \" \";\n    // cout << endl;\n\n    // Cholesky decomposition\n    double R[16];\n    cholesky4( p, R );\n\n    // inverse R\n    if ( invert( R, Rinv ) == false )\n      {\n        cerr << \"error in matrix inverse.\" << endl;\n      }\n#endif\n\n  };\n\nprotected:\n\n  double operator[](size_t index) {\n    return mat_[index];\n  };\n\n};\n\n#if 0\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n// functions\nextern void optimize_vector(Sped *, double *);\nextern BOOL InvertSymMatrix3(double *, double *);\nextern double calc_error(double *, Vec *);\nextern void optimize_2subvector(Sped *, double *);\nextern void make_qeminfmatrix(Sped *, double *, double *);\nextern void optimize_infvector(Sped *, double *);\nextern double calc_inferror(double *, Vec *);\nextern void make_vqem2submatrix(Sped *, double *, double, double *);\nextern void make_eqem2submatrix(Sped *, double, double *);\nextern void loop_odd_vertex(Spvt *, Spvt *, Spvt *, Spvt *, int, double *, Vec *);\nextern void loop_even_vertex(Sped *, int *, double *, double *, Vec *, BOOL);\nextern void loop_even_vertex_vj(Spvt *, Sped *, int *, double *, double *, Vec *);\nextern Sped *ppdedge_first_ring_edge(Sped *);\nextern Sped *ppdedge_next_ring_edge(Sped *, Sped *);\nextern Sped *ppdedge_prev_ring_edge(Sped *, Sped *);\nextern Spvt *ppdedge_ring_another_vt(Sped *, Sped *);\nextern Spvt *ppdedge_first_ring_vertex(Sped *, Sped **);\nextern Spvt *ppdedge_last_ring_vertex( Sped *, Sped ** );\nextern Spvt *ppdedge_next_ring_vertex(Spvt *, Sped *, Sped *, Sped **);\nextern Spvt *ppdedge_prev_ring_vertex(Spvt *, Sped *, Sped *, Sped **);\nextern Spvt *ppdedge_opposite_vertex(Sped *, Spvt *, Spvt *);\nextern void qem_matrix4(double, Vec *, double *, double *);\nextern void edge_ring_test(Sppd *);\nextern void edge_ring_vertex_test(Sppd *);\n\n// parameters for QEM evaluation \n#define EVAL_VERTEX 0\n#define EVAL_SLP    1\n#define EVAL_2SUB   2\n\n#ifdef __cplusplus\n}\n#endif\n#endif\n\n#endif // _QEM_HXX\n", "meta": {"hexsha": "6cbf488b7b862b525c254a488a806ad4b607867d", "size": 12256, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "optmesh/QEM.hxx", "max_stars_repo_name": "kanait/hsphparam", "max_stars_repo_head_hexsha": "00158f81d00e496fed469779bf73094495ac8671", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-23T06:55:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-23T06:55:22.000Z", "max_issues_repo_path": "optmesh/QEM.hxx", "max_issues_repo_name": "kanait/hsphparam", "max_issues_repo_head_hexsha": "00158f81d00e496fed469779bf73094495ac8671", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "optmesh/QEM.hxx", "max_forks_repo_name": "kanait/hsphparam", "max_forks_repo_head_hexsha": "00158f81d00e496fed469779bf73094495ac8671", "max_forks_repo_licenses": ["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.8771929825, "max_line_length": 218, "alphanum_fraction": 0.426729765, "num_tokens": 4707, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257126, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.47976415404369466}}
{"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#define NT2_UNIT_MODULE \"nt2 boost.simd.arithmetic toolbox - sqrt/simd Mode\"\n\n//////////////////////////////////////////////////////////////////////////////\n// unit test behavior of boost.simd.arithmetic components in scalar mode\n//////////////////////////////////////////////////////////////////////////////\n/// created by jt the 30/11/2010\n///\n#include <nt2/include/functions/sqrt.hpp>\n#include <boost/simd/sdk/simd/native.hpp>\n#include <nt2/include/functions/extract.hpp>\n#include <nt2/include/functions/unary_minus.hpp>\n#include <nt2/include/constants/cnan.hpp>\n#include <nt2/include/constants/nan.hpp>\n#include <nt2/include/constants/one.hpp>\n#include <nt2/include/constants/zero.hpp>\n#include <nt2/include/constants/inf.hpp>\n#include <nt2/include/constants/minf.hpp>\n#include <nt2/include/constants/mone.hpp>\n#include <nt2/include/constants/sqrt_2o_2.hpp>\n#include <nt2/sdk/complex/complex.hpp>\n#include <nt2/sdk/complex/dry.hpp>\n#include <nt2/sdk/complex/imaginary.hpp>\n#include <nt2/sdk/complex/meta/as_imaginary.hpp>\n#include <nt2/sdk/complex/meta/as_dry.hpp>\n\n#include <nt2/sdk/unit/module.hpp>\n#include <nt2/sdk/unit/tests/ulp.hpp>\n\nNT2_TEST_CASE_TPL ( abs_cplx__1_0,  BOOST_SIMD_SIMD_REAL_TYPES)\n{\n  using boost::simd::native;\n  typedef NT2_SIMD_DEFAULT_EXTENSION  ext_t;\n  typedef std::complex<T>                              cT;\n  typedef native<T ,ext_t>                             vT;\n  typedef native<cT ,ext_t>                           vcT;\n  typedef typename nt2::meta::as_imaginary<T>::type   ciT;\n  typedef native<ciT ,ext_t>                         vciT;\n  typedef typename nt2::meta::as_dry<T>::type          dT;\n  typedef native<dT ,ext_t>                           vdT;\n  double ulpd;\n  ulpd=0.0;\n\n  {\n    typedef vcT r_t;\n    NT2_TEST_ULP_EQUAL(nt2::sqrt(nt2::Inf<vcT>())[0], cT(nt2::Inf<cT>()),0);\n    NT2_TEST_ULP_EQUAL(nt2::sqrt(nt2::Minf<vcT>())[0], cT(0, nt2::Inf<T>()),0);\n    NT2_TEST_ULP_EQUAL(nt2::sqrt(nt2::Mone<vcT>())[0], cT(0, 1),0);\n    NT2_TEST_ULP_EQUAL(nt2::sqrt(nt2::Nan<vcT>())[0], cT(nt2::Cnan<cT>()),0);\n    NT2_TEST_ULP_EQUAL(nt2::sqrt(nt2::One<vcT>())[0], cT(nt2::One<cT>()),0);\n    NT2_TEST_ULP_EQUAL(nt2::sqrt(nt2::Zero<vcT>())[0], cT(nt2::Zero<cT>()),0);\n  }\n  {\n    typedef vcT r_t;\n    NT2_TEST_ULP_EQUAL(nt2::sqrt(nt2::Inf<vciT>())[0],  cT(nt2::Inf<T>(), nt2::Inf<T>()),0);\n    NT2_TEST_ULP_EQUAL(nt2::sqrt(nt2::Minf<vciT>())[0], cT(nt2::Inf<T>(),nt2::Minf<T>()),0);\n    NT2_TEST_ULP_EQUAL(nt2::sqrt(nt2::Mone<vciT>())[0], cT(nt2::Sqrt_2o_2<T>(), -nt2::Sqrt_2o_2<T>()) ,0);\n    NT2_TEST_ULP_EQUAL(nt2::sqrt(nt2::Nan<vciT>())[0],  cT(nt2::Nan<T>(), nt2::Nan<T>()),0);\n    NT2_TEST_ULP_EQUAL(nt2::sqrt(nt2::One<vciT>())[0],  cT(nt2::Sqrt_2o_2<T>(), nt2::Sqrt_2o_2<T>()),0);\n    NT2_TEST_ULP_EQUAL(nt2::sqrt(nt2::Zero<vciT>())[0], nt2::Zero<cT>(),0);\n  }\n  {\n    typedef vcT r_t;\n    NT2_TEST_ULP_EQUAL(nt2::sqrt(nt2::Inf<vdT>())[0], nt2::Inf<cT>(),0);\n    NT2_TEST_ULP_EQUAL(nt2::sqrt(nt2::Minf<vdT>())[0], cT(nt2::Zero<T>(), nt2::Inf<T>()),0);\n    NT2_TEST_ULP_EQUAL(nt2::sqrt(nt2::Mone<vdT>())[0], cT(nt2::Zero<T>(), nt2::One<T>()),0);\n    NT2_TEST_ULP_EQUAL(nt2::sqrt(nt2::Nan<vdT>())[0], nt2::Nan<cT>(),0);\n    NT2_TEST_ULP_EQUAL(nt2::sqrt(nt2::One<vdT>())[0], nt2::One<cT>(),0);\n    NT2_TEST_ULP_EQUAL(nt2::sqrt(nt2::Zero<vdT>())[0], nt2::Zero<cT>(),0);\n  }\n} // end of test for floating_\n\n\n", "meta": {"hexsha": "f1ba9c3979b613206078389e38e815fc4a97a0c4", "size": 3859, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/type/complex/arithmetic/unit/simd/sqrt.cpp", "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/type/complex/arithmetic/unit/simd/sqrt.cpp", "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/type/complex/arithmetic/unit/simd/sqrt.cpp", "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": 47.6419753086, "max_line_length": 106, "alphanum_fraction": 0.5830526043, "num_tokens": 1235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419958239132, "lm_q2_score": 0.6926419894793248, "lm_q1q2_score": 0.4797529299844054}}
{"text": "// Bring in my package's API, which is what I'm testing\n#include <bsplines/BSpline.hpp>\n\n// Bring in gtest\n#include <gtest/gtest.h>\n#include <boost/cstdint.hpp>\n\n// Helpful functions from schweizer_messer\n#include <sm/eigen/NumericalDiff.hpp>\n#include <sm/eigen/gtest.hpp>\n\n#include <boost/tuple/tuple.hpp>\n\nusing namespace bsplines;\n\nstruct BSplineJacobianFunctor {\n    // Necessary for eigen fixed sized type member variables.\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    typedef Eigen::VectorXd input_t;\n    typedef Eigen::MatrixXd jacobian_t;\n    typedef Eigen::VectorXd value_t;\n    typedef double scalar_t;\n\n    BSplineJacobianFunctor(BSpline bs, double t, int d) : bs_(bs), t_(t), d_(d) {}\n\n    input_t update(const input_t& x, int c, double delta) {\n        input_t xnew = x;\n        xnew[c] += delta;\n        return xnew;\n    }\n\n    Eigen::VectorXd operator()(const Eigen::VectorXd& c) {\n        bs_.setLocalCoefficientVector(t_, c);\n        return bs_.evalD(t_, d_);\n    }\n\n    BSpline bs_;\n    double t_;\n    int d_;\n};\n\n// Check that the Jacobian calculation is correct.\nTEST(SplineTestSuite, testBSplineJacobian) {\n    const int segments = 2;\n    for (int order = 2; order < 10; order++) {\n        BSpline bs(order);\n        int nk = bs.numKnotsRequired(segments);\n        std::vector<double> knots;\n        for (int i = 0; i < nk; i++) {\n            knots.push_back(i);\n        }\n\n        for (int dim = 1; dim < 4; dim++) {\n            int nc = bs.numCoefficientsRequired(segments);\n            Eigen::MatrixXd C = Eigen::MatrixXd::Random(dim, nc);\n            bs.setKnotsAndCoefficients(knots, C);\n\n            for (int derivative = 0; derivative < order; derivative++) {\n                for (double t = bs.t_min(); t < bs.t_max(); t += 0.1) {\n                    BSplineJacobianFunctor f(bs, t, derivative);\n                    sm::eigen::NumericalDiff<BSplineJacobianFunctor> nd(f);\n                    Eigen::MatrixXd estJ = nd.estimateJacobian(bs.localCoefficientVector(t));\n                    Eigen::MatrixXd J;\n                    Eigen::VectorXd v;\n                    boost::tie(v, J) = bs.evalDAndJacobian(t, derivative);\n\n                    sm::eigen::assertNear(J, estJ, 1e-5, SM_SOURCE_FILE_POS);\n                }\n            }\n        }\n    }\n}\n\nTEST(SplineTestSuite, testCoefficientMap) {\n    const int order = 4;\n    const int segments = 10;\n    const int dim = 5;\n    BSpline bs(order);\n    int nk = bs.numKnotsRequired(segments);\n    int nc = bs.numCoefficientsRequired(segments);\n\n    std::vector<double> knots;\n    for (int i = 0; i < nk; i++) {\n        knots.push_back(i);\n    }\n\n    Eigen::MatrixXd C = Eigen::MatrixXd::Random(dim, nc);\n    bs.setKnotsAndCoefficients(knots, C);\n\n    const Eigen::MatrixXd& CC = bs.coefficients();\n    for (int i = 0; i < bs.numVvCoefficients(); i++) {\n        Eigen::Map<Eigen::VectorXd> m = bs.vvCoefficientVector(i);\n        // Test pass by value...\n        Eigen::Map<Eigen::Matrix<double, 5, 1> > m2 = bs.fixedSizeVvCoefficientVector<dim>(i);\n        for (int r = 0; r < m.size(); ++r) {\n            ASSERT_TRUE(&m[r] == &CC(r, i));\n            ASSERT_TRUE(&m[r] == &m2[r]);\n            m[r] = rand();\n            ASSERT_EQ(m[r], CC(r, i));\n            ASSERT_EQ(m[r], m2[r]);\n        }\n    }\n}\n\nTEST(SplineTestSuite, testGetBi) {\n    const int order = 4;\n    const int segments = 10;\n    const double startTime = 0;\n    const double endTime = 5;\n    const int numTimeSteps = 43;\n    BSpline bs(order);\n    bs.initConstantSpline(startTime, endTime, segments, Eigen::VectorXd::Zero(1));\n\n    for (int i = 0; i <= numTimeSteps; i++) {\n        double t = startTime + (endTime - startTime) * ((double)i / numTimeSteps);\n        Eigen::VectorXd localBiVector = bs.getLocalBiVector(t);\n        SM_ASSERT_NEAR(std::runtime_error, localBiVector.sum(), 1.0, 1e-10,\n                       \"the bis at a given time should always sum up to 1\")\n        Eigen::VectorXd biVector = bs.getBiVector(t);\n        SM_ASSERT_NEAR(std::runtime_error, localBiVector.sum(), 1.0, 1e-10,\n                       \"the bis at a given time should always sum up to 1\")\n\n        Eigen::VectorXd cumulativeBiVector = bs.getCumulativeBiVector(t);\n        Eigen::VectorXd localCumulativeBiVector = bs.getLocalCumulativeBiVector(t);\n\n        Eigen::VectorXi localCoefficientVectorIndices = bs.localCoefficientVectorIndices(t);\n        int firstIndex = localCoefficientVectorIndices[0];\n        SM_ASSERT_EQ(std::runtime_error, localCoefficientVectorIndices.size(), order,\n                     \"localCoefficientVectorIndices has to have exactly \" << order << \" entries\");\n\n        for (int j = 0; j < order; j++) {\n            SM_ASSERT_EQ(std::runtime_error, localCoefficientVectorIndices[j], firstIndex + j,\n                         \"localCoefficientVectorIndices have to be successive\");\n        }\n\n        for (int j = 0, n = biVector.size(); j < n; j++) {\n            if (j < firstIndex) {\n                SM_ASSERT_EQ(std::runtime_error, biVector[j], 0, \"\");\n                SM_ASSERT_EQ(std::runtime_error, cumulativeBiVector[j], 1, \"\");\n            } else if (j < firstIndex + order) {\n                SM_ASSERT_EQ(std::runtime_error, biVector[j], localBiVector[j - firstIndex],\n                             \"localBiVector should be a slice of the biVector\");\n                SM_ASSERT_EQ(std::runtime_error, cumulativeBiVector[j], localCumulativeBiVector[j - firstIndex],\n                             \"localCumulativeBiVector must be a slice of the cumulativeBiVector\");\n                SM_ASSERT_NEAR(\n                    std::runtime_error, cumulativeBiVector[j],\n                    localBiVector.segment(j - firstIndex, order - (j - firstIndex)).sum(), 1e-13,\n                    \"cumulativeBiVector must be the sum of the localBiVector where it overlaps, but it is not at \"\n                        << (j - firstIndex) << \" (localBiVector=\" << localBiVector << \")\");\n            } else {\n                SM_ASSERT_EQ(std::runtime_error, biVector[j], 0, \"at position \" << j);\n                SM_ASSERT_EQ(std::runtime_error, cumulativeBiVector[j], 0, \"at position \" << j);\n            }\n        }\n    }\n}\n\n// TEST(SplineTestSuite, testBSplineCubic)\n// {\n//   double knots_d[] = {-2.0, -1.0, 0.0, 1.0, 2.0, 3.0, 4.0, 5.0 };\n//   double control_d[] = { 0.0,1.0, 2.0, 3.0 };\n\n//   std::vector<double> knots;\n//   knots.insert(knots.begin(),knots_d,knots_d + (sizeof(knots_d)/sizeof(double)));\n\n//   std::vector<double> control;\n//   control.insert(control.begin(),control_d,control_d + (sizeof(control_d)/sizeof(double)));\n\n//   BSpline<double,4> s(knots,control);\n\n//   for(double i = 1.0; i < 2.0; i += 0.1)\n//     {\n//       //std::cout << \"s(\" << i << \") = \" << s.eval(i) << std::endl;\n//       ASSERT_DOUBLE_EQ(s.eval(i),i);\n//       //std::cout << \"D1 s(\" << i << \") = \" << s.evalD(i,1) << std::endl;\n//       //std::cout << \"D2 s(\" << i << \") = \" << s.evalD(i,2) << std::endl;\n//       //std::cout << \"D3 s(\" << i << \") = \" << s.evalD(i,3) << std::endl;\n//       //std::cout << \"D4 s(\" << i << \") = \" << s.evalD(i,4) << std::endl;\n//     }\n\n//   // Check the bounds of evaluation.\n//   // Lower bound.\n//   ASSERT_THROW(s.eval(0.999),Exception);\n//   ASSERT_NO_THROW(s.eval(1.0));\n//   // Upper bound\n//   ASSERT_NO_THROW(s.eval(1.999));\n//   ASSERT_THROW(s.eval(2.0),Exception);\n\n// }\n\n// TEST(SplineTestSuite, testBSplineLinear)\n// {\n//   double knots_d[] = {-1.0, 0.0, 1.0, 2.0, 3.0, 4.0 };\n//   double control_d[] = { 0.0,1.0, 2.0, 3.0 };\n\n//   std::vector<double> knots;\n//   knots.insert(knots.begin(),knots_d,knots_d + (sizeof(knots_d)/sizeof(double)));\n\n//   std::vector<double> control;\n//   control.insert(control.begin(),control_d,control_d + (sizeof(control_d)/sizeof(double)));\n\n//   BSpline<double,2> s(knots,control);\n\n//   for(double i = 0.0; i < 3.0; i += 0.1)\n//     {\n//       //std::cout << \"s(\" << i << \") = \" << s.eval(i) << std::endl;\n//       ASSERT_DOUBLE_EQ(s.eval(i),i);\n//     }\n\n//   // Check the bounds of evaluation.\n//   // Lower bound.\n//   ASSERT_THROW(s.eval(-0.0001),Exception);\n//   ASSERT_NO_THROW(s.eval(0.0));\n//   // Upper bound\n//   ASSERT_NO_THROW(s.eval(2.999));\n//   ASSERT_THROW(s.eval(3.0),Exception);\n\n// }\n\n// TEST(SplineTestSuite, testBSplineQuadratic)\n// {\n//   double knots_d[] = {-1.0, 0.0, 1.0, 2.0, 3.0, 4.0, 5.0 };\n//   double control_d[] = { 0.5,1.5, 2.5, 3.5 };\n\n//   std::vector<double> knots;\n//   knots.insert(knots.begin(),knots_d,knots_d + (sizeof(knots_d)/sizeof(double)));\n\n//   std::vector<double> control;\n//   control.insert(control.begin(),control_d,control_d + (sizeof(control_d)/sizeof(double)));\n\n//   BSpline<double,3> s(knots,control);\n\n//     for(double i = 1.0; i < 3.0; i += 0.1)\n//     {\n//       //std::cout << \"s(\" << i << \") = \" << s.eval(i) << std::endl;\n//       ASSERT_DOUBLE_EQ(s.eval(i),i);\n//     }\n\n//     // Check the bounds of evaluation.\n//   // Lower bound.\n//   ASSERT_THROW(s.eval(0.999),Exception);\n//   ASSERT_NO_THROW(s.eval(1.0));\n//   // Upper bound\n//   ASSERT_NO_THROW(s.eval(2.999));\n//   ASSERT_THROW(s.eval(3.0),Exception);\n// }\n", "meta": {"hexsha": "8d5bf2b0465165b3037215bb5b521e330882e07e", "size": 9085, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "aslam_nonparametric_estimation/bsplines/test/SplineTests.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/test/SplineTests.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/test/SplineTests.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": 36.7813765182, "max_line_length": 114, "alphanum_fraction": 0.5766648321, "num_tokens": 2598, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419958239132, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.4797529299844053}}
{"text": "/**\n * @author  Daniel Maturana\n * @year    2015\n *\n * @attention Copyright (c) 2015\n * @attention Carnegie Mellon University\n * @attention All rights reserved.\n *\n **@=*/\n\n#include <iostream>\n\n#include <boost/foreach.hpp>\n#include <boost/assign/std/vector.hpp>\n\n#include <Eigen/Core>\n\n#include <scrollgrid/scrollgrid3.hpp>\n\n#include <gtest/gtest.h>\n\nusing namespace boost::assign;\nusing namespace Eigen;\nusing namespace ca;\n\nTEST(scrollgrid3, hash_roundtrip1) {\n\n  Vector3f center(-10, 20, -30);\n  Vec3Ix dim(200, 100, 400);\n  float res = 0.15;\n  ca::ScrollGrid3f grid3( center, dim, res);\n\n  std::vector<grid_ix_t> ix;\n  ix += -10, -3, 0, 4, 11;\n\n  BOOST_FOREACH(grid_ix_t i, ix) {\n    BOOST_FOREACH(grid_ix_t j, ix) {\n      BOOST_FOREACH(grid_ix_t k, ix) {\n        Vec3Ix gix(i, j, k);\n        uint64_t hix = grid3.grid_to_hash(gix);\n        Vec3Ix gix2 = grid3.hash_to_grid(hix);\n        EXPECT_EQ(gix, gix2);\n      }\n    }\n  }\n\n}\n\nTEST(scrollgrid3, hash_roundtrip2) {\n\n  Vector3f center(-10, 20, -30);\n  Vec3Ix dim(21, 31, 41);\n  float res = 0.15;\n  ca::ScrollGrid3f grid3( center, dim, res);\n\n  std::vector<grid_ix_t> ix;\n  ix += -10, -3, 0, 4, 11;\n\n  BOOST_FOREACH(grid_ix_t i, ix) {\n    BOOST_FOREACH(grid_ix_t j, ix) {\n      BOOST_FOREACH(grid_ix_t k, ix) {\n        Vec3Ix gix(i, j, k);\n        uint64_t hix = grid3.grid_to_hash(gix);\n        Vec3Ix gix2 = grid3.hash_to_grid(hix);\n        EXPECT_EQ(gix, gix2);\n      }\n    }\n  }\n\n}\n\nTEST(scrollgrid3, scroll1) {\n\n  Vector3f center(-10, 20, -30);\n  Vec3Ix dim(21, 31, 41);\n  float res = 0.15;\n  ca::ScrollGrid3f grid3( center, dim, res);\n\n  EXPECT_EQ( grid3.scroll_offset()[0] , 0 );\n  EXPECT_EQ( grid3.scroll_offset()[1] , 0 );\n  EXPECT_EQ( grid3.scroll_offset()[2] , 0 );\n\n  {\n    ca::Vec3Ix gix(0, 0, 1);\n    grid3.scroll( gix );\n  }\n\n  EXPECT_EQ( grid3.scroll_offset()[0] , 0 );\n  EXPECT_EQ( grid3.scroll_offset()[1] , 0 );\n  EXPECT_EQ( grid3.scroll_offset()[2] , 1 );\n\n  {\n    ca::Vec3Ix gix(0, 0, -1);\n    grid3.scroll( gix );\n  }\n\n  EXPECT_EQ( grid3.scroll_offset()[0] , 0 );\n  EXPECT_EQ( grid3.scroll_offset()[1] , 0 );\n  EXPECT_EQ( grid3.scroll_offset()[2] , 0 );\n\n\n}\n\nTEST(scrollgrid3, scroll2) {\n\n  Vector3f center(-10, 20, -30);\n  Vec3Ix dim(21, 31, 41);\n  float res = 0.15;\n  ca::ScrollGrid3f grid3( center, dim, res);\n\n  ca::Vec3Ix gix(2, 0, 0);\n  grid3.scroll( gix );\n\n  EXPECT_FLOAT_EQ( grid3.center()[0], center[0]+2*res );\n\n}\n\nTEST(scrollgrid3, scroll3) {\n\n  Vector3f center(-10, 20, -30);\n  Vec3Ix dim(21, 31, 41);\n  float res = 0.15;\n  ca::ScrollGrid3f grid3( center, dim, res);\n\n  EXPECT_EQ( grid3.first_i() , 0 );\n  EXPECT_EQ( grid3.first_j() , 0 );\n  EXPECT_EQ( grid3.first_k() , 0 );\n\n  ca::Vec3Ix gix(2, 0, 0);\n  grid3.scroll( gix );\n\n  EXPECT_EQ( grid3.first_i() , 2 );\n  EXPECT_EQ( grid3.first_j() , 0 );\n  EXPECT_EQ( grid3.first_k() , 0 );\n\n  ca::Vec3Ix gix2(0, -2, 0);\n  grid3.scroll( gix2 );\n\n  EXPECT_EQ( grid3.first_i() , 2 );\n  EXPECT_EQ( grid3.first_j() , -2 );\n  EXPECT_EQ( grid3.first_k() , 0 );\n\n\n}\n\nTEST(scrollgrid3, scroll4) {\n\n  Vector3f center(-10, 20, -30);\n  Vec3Ix dim(21, 31, 41);\n  float res = 0.15;\n  ca::ScrollGrid3f grid3( center, dim, res);\n\n  EXPECT_EQ( grid3.dim_i() , grid3.last_i() - grid3.first_i() );\n  EXPECT_EQ( grid3.dim_j() , grid3.last_j() - grid3.first_j() );\n  EXPECT_EQ( grid3.dim_k() , grid3.last_k() - grid3.first_k() );\n\n  ca::Vec3Ix gix(2, 0, 0);\n  grid3.scroll( gix );\n\n  EXPECT_EQ( grid3.dim_i() , grid3.last_i() - grid3.first_i() );\n  EXPECT_EQ( grid3.dim_j() , grid3.last_j() - grid3.first_j() );\n  EXPECT_EQ( grid3.dim_k() , grid3.last_k() - grid3.first_k() );\n\n}\n\nTEST(scrollgrid3, grid_to_mem1) {\n\n  Vector3f center(-1, 2, -3);\n  Vec3Ix dim(21, 31, 41);\n  float res = 0.5;\n  ca::ScrollGrid3f grid3( center, dim, res);\n\n#if 0\n  std::cerr << \"grid3.first_i() = \" << grid3.first_i() << std::endl;\n  std::cerr << \"grid3.first_j() = \" << grid3.first_j() << std::endl;\n  std::cerr << \"grid3.first_k() = \" << grid3.first_k() << std::endl;\n\n  std::cerr << \"grid3.last_i() = \" << grid3.last_i() << std::endl;\n  std::cerr << \"grid3.last_j() = \" << grid3.last_j() << std::endl;\n  std::cerr << \"grid3.last_k() = \" << grid3.last_k() << std::endl;\n#endif\n\n  mem_ix_t mix1 = grid3.grid_to_mem( ca::Vec3Ix(2, 1, 4) );\n  mem_ix_t mix2 = grid3.grid_to_mem( 2, 1, 4 );\n\n  EXPECT_EQ(mix1, mix2);\n}\n\nTEST(scrollgrid3, grid_to_mem2) {\n\n  Vector3f center(-1, 2, -3);\n  Vec3Ix dim(21, 31, 41);\n  float res = 0.5;\n  ca::ScrollGrid3f grid3( center, dim, res);\n\n  std::vector<grid_ix_t> ix;\n  ix += 0, 3, 4, 10, 11;\n\n\n  BOOST_FOREACH(grid_ix_t i, ix) {\n    BOOST_FOREACH(grid_ix_t j, ix) {\n      BOOST_FOREACH(grid_ix_t k, ix) {\n        mem_ix_t mix1 = grid3.grid_to_mem_slow( i, j, k);\n        mem_ix_t mix2 = grid3.grid_to_mem( i, j, k );\n        EXPECT_EQ(mix1, mix2);\n      }\n    }\n  }\n}\n\nTEST(scrollgrid3, grid_to_mem3) {\n\n  Vector3f center(-1, 2, -3);\n  Vec3Ix dim(21, 31, 41);\n  float res = 0.5;\n  ca::ScrollGrid3f grid3( center, dim, res);\n\n  std::vector<grid_ix_t> ix;\n  ix += 0, 3, 4, 10, 11;\n\n\n  BOOST_FOREACH(grid_ix_t i, ix) {\n    BOOST_FOREACH(grid_ix_t j, ix) {\n      BOOST_FOREACH(grid_ix_t k, ix) {\n        mem_ix_t mix1 = grid3.grid_to_mem_slow( i, j, k);\n        mem_ix_t mix2 = grid3.grid_to_mem( i, j, k );\n        EXPECT_EQ(mix1, mix2);\n      }\n    }\n  }\n}\n\nTEST(scrollgrid3, grid_to_mem4) {\n\n  Vector3f center(-1, 2, -3);\n  Vec3Ix dim(21, 31, 41);\n  float res = 0.5;\n  ca::ScrollGrid3f grid3( center, dim, res);\n\n  ca::Vec3Ix gix( 10, 14,  21);\n  mem_ix_t mix = grid3.grid_to_mem(gix);\n\n  grid3.scroll( ca::Vec3Ix( 0, 0, 1) );\n  EXPECT_EQ( mix , grid3.grid_to_mem(gix) );\n  EXPECT_EQ( mix , grid3.grid_to_mem_slow(gix) );\n\n  grid3.scroll( ca::Vec3Ix( 0, 0, -1) );\n  EXPECT_EQ( mix , grid3.grid_to_mem(gix) );\n  EXPECT_EQ( mix , grid3.grid_to_mem_slow(gix) );\n\n  grid3.scroll( ca::Vec3Ix( 1, 0, 1) );\n  EXPECT_EQ( mix , grid3.grid_to_mem(gix) );\n  EXPECT_EQ( mix , grid3.grid_to_mem_slow(gix) );\n\n  grid3.scroll( ca::Vec3Ix( -2, 0, 1) );\n  EXPECT_EQ( mix , grid3.grid_to_mem(gix) );\n  EXPECT_EQ( mix , grid3.grid_to_mem_slow(gix) );\n\n  grid3.scroll( ca::Vec3Ix( 0, 3, -4) );\n  EXPECT_EQ( mix , grid3.grid_to_mem(gix) );\n}\n\nTEST(scrollgrid3, grid_to_mem5) {\n\n  Vector3f center(-10, 20, -30);\n  Vec3Ix dim(200, 100, 400);\n  float res = 0.15;\n  ca::ScrollGrid3f grid3( center, dim, res);\n\n  grid3.scroll( ca::Vec3Ix(2, 0, 0) );\n\n  std::vector<grid_ix_t> ix;\n  ix += -10, -3, 0, 4, 11;\n\n  BOOST_FOREACH(grid_ix_t i, ix) {\n    BOOST_FOREACH(grid_ix_t j, ix) {\n      BOOST_FOREACH(grid_ix_t k, ix) {\n        Vec3Ix gix(i, j, k);\n        gix += (grid3.scroll_offset() + grid3.radius_ijk());\n        mem_ix_t mix = grid3.grid_to_mem_slow(gix);\n        mem_ix_t mix2 = grid3.grid_to_mem(gix);\n        EXPECT_EQ( mix, mix2 );\n      }\n    }\n  }\n}\n\n\n\nTEST(scrollgrid3, mem_roundtrip1) {\n\n  Vector3f center(-10, 20, -30);\n  Vec3Ix dim(200, 100, 400);\n  float res = 0.15;\n  ca::ScrollGrid3f grid3( center, dim, res);\n\n  std::vector<grid_ix_t> ix;\n  ix += -10, -3, 0, 4, 11;\n\n  BOOST_FOREACH(grid_ix_t i, ix) {\n    BOOST_FOREACH(grid_ix_t j, ix) {\n      BOOST_FOREACH(grid_ix_t k, ix) {\n        Vec3Ix gix(i, j, k);\n        gix += (grid3.scroll_offset() + grid3.radius_ijk());\n        mem_ix_t mix = grid3.grid_to_mem(gix);\n        Vec3Ix gix2 = grid3.mem_to_grid(mix);\n        EXPECT_TRUE( gix.cwiseEqual(gix2).all() );\n\n      }\n    }\n  }\n}\n\nTEST(scrollgrid3, mem_roundtrip2) {\n\n  Vector3f center(-10, 20, -30);\n  Vec3Ix dim(200, 100, 400);\n  float res = 0.15;\n  ca::ScrollGrid3f grid3( center, dim, res);\n\n  grid3.scroll( ca::Vec3Ix(2, 0, 0) );\n\n  std::vector<grid_ix_t> ix;\n  ix += -10, -3, 0, 4, 11;\n\n  BOOST_FOREACH(grid_ix_t i, ix) {\n    BOOST_FOREACH(grid_ix_t j, ix) {\n      BOOST_FOREACH(grid_ix_t k, ix) {\n        Vec3Ix gix(i, j, k);\n        gix += (grid3.scroll_offset() + grid3.radius_ijk());\n        mem_ix_t mix = grid3.grid_to_mem(gix);\n        //Vec3Ix gix2 = grid3.mem_to_grid_undo_wrap(mix);\n        Vec3Ix gix2 = grid3.mem_to_grid(mix);\n\n        EXPECT_EQ( gix[0], gix2[0] );\n        EXPECT_EQ( gix[1], gix2[1] );\n        EXPECT_EQ( gix[2], gix2[2] );\n\n      }\n    }\n  }\n\n}\n\nTEST(scrollgrid3, mem_roundtrip3) {\n\n  Vector3f center(-10, 20, -30);\n  Vec3Ix dim(200, 100, 400);\n  float res = 0.15;\n  ca::ScrollGrid3f grid3( center, dim, res);\n\n  grid3.scroll( ca::Vec3Ix(202, 0, 0) );\n\n  std::vector<grid_ix_t> ix;\n  ix += -10, -3, 0, 4, 11;\n\n  BOOST_FOREACH(grid_ix_t i, ix) {\n    BOOST_FOREACH(grid_ix_t j, ix) {\n      BOOST_FOREACH(grid_ix_t k, ix) {\n        Vec3Ix gix(i, j, k);\n        gix += (grid3.scroll_offset() + grid3.radius_ijk());\n        mem_ix_t mix = grid3.grid_to_mem(gix);\n        //Vec3Ix gix2 = grid3.mem_to_grid_undo_wrap(mix);\n        Vec3Ix gix2 = grid3.mem_to_grid(mix);\n        EXPECT_EQ( gix[0], gix2[0] );\n        EXPECT_EQ( gix[1], gix2[1] );\n        EXPECT_EQ( gix[2], gix2[2] );\n        //EXPECT_TRUE( gix.cwiseEqual(gix2).all() );\n\n      }\n    }\n  }\n\n}\n\n#if 0\nstruct TestClearCellsFun : ca::ClearCellsFun {\n  TestClearCellsFun(ca::Vec3Ix* last_start, ca::Vec3Ix* last_finish) {\n  }\n  virtual void operator()(const ca::Vec3Ix& start,\n                          const ca::Vec3Ix& finish) const {\n    *last_start = start;\n    *last_finish = finish;\n  }\n  ca::Vec3Ix *last_start_, *last_finish_;\n};\n\nTEST(scrollgrid3, big_offset1) {\n  // when scroll offset is bigger than grid dimensions\n\n  Vector3f center(0.f, 0.f, 0.f);\n  Vec3Ix dim(20, 10, 40);\n  float res = 0.15;\n  ca::ScrollGrid3f grid3( center, dim, res);\n\n  grid3.scroll( ca::Vec3Ix(25, 0, 0) );\n\n  std::vector<grid_ix_t> ix;\n  ix += -10, -3, 0, 4, 11;\n\n  BOOST_FOREACH(grid_ix_t i, ix) {\n    BOOST_FOREACH(grid_ix_t j, ix) {\n      BOOST_FOREACH(grid_ix_t k, ix) {\n        Vec3Ix gix(i, j, k);\n        gix += (grid3.scroll_offset() + grid3.radius_ijk());\n        mem_ix_t mix = grid3.grid_to_mem(gix);\n        //Vec3Ix gix2 = grid3.mem_to_grid_undo_wrap(mix);\n        Vec3Ix gix2 = grid3.mem_to_grid(mix);\n        EXPECT_EQ( gix[0], gix2[0] );\n        EXPECT_EQ( gix[1], gix2[1] );\n        EXPECT_EQ( gix[2], gix2[2] );\n        //EXPECT_TRUE( gix.cwiseEqual(gix2).all() );\n\n      }\n    }\n  }\n}\n#endif\n\nint main(int argc, char *argv[]) {\n  ::testing::InitGoogleTest(&argc, argv);\n  return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "ee4237e5709bd3a50866d9b9b94718b7d4ecafb4", "size": 10222, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/scrollgrid3.cpp", "max_stars_repo_name": "castacks/scrollgrid", "max_stars_repo_head_hexsha": "710324173907a182eb688effcf1c9ec998ade1e0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2017-07-20T23:04:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-12T08:03:10.000Z", "max_issues_repo_path": "tests/scrollgrid3.cpp", "max_issues_repo_name": "castacks/scrollgrid", "max_issues_repo_head_hexsha": "710324173907a182eb688effcf1c9ec998ade1e0", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/scrollgrid3.cpp", "max_forks_repo_name": "castacks/scrollgrid", "max_forks_repo_head_hexsha": "710324173907a182eb688effcf1c9ec998ade1e0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-04-06T16:41:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T01:39:22.000Z", "avg_line_length": 24.108490566, "max_line_length": 70, "alphanum_fraction": 0.604871845, "num_tokens": 3715, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419958239132, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.4797529211953483}}
{"text": "/*\n@copyright Louis Dionne 2015\nDistributed under the Boost Software License, Version 1.0.\n(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n */\n\n#include <boost/hana/assert.hpp>\n#include <boost/hana/config.hpp>\n#include <boost/hana/integral_constant.hpp>\n#include <boost/hana/orderable.hpp>\n#include <boost/hana/tuple.hpp>\n#include <boost/hana/type.hpp>\nusing namespace boost::hana;\n\n\nint main() {\n\n{\n\n//! [less.than]\nBOOST_HANA_CONSTEXPR_CHECK(all_of(tuple_c<int, 1, 2, 3, 4>, less.than(5)));\n\nBOOST_HANA_CONSTANT_CHECK(all_of(tuple_c<int, 1, 2, 3, 4>, less_equal.than(int_<4>)));\n//! [less.than]\n\n}{\n\n//! [greater]\nBOOST_HANA_CONSTEXPR_CHECK(greater(4, 1));\nBOOST_HANA_CONSTANT_CHECK(!greater(int_<1>, int_<3>));\n//! [greater]\n\n}{\n\n//! [greater_equal]\nBOOST_HANA_CONSTEXPR_CHECK(greater_equal(4, 1));\nBOOST_HANA_CONSTEXPR_CHECK(greater_equal(1, 1));\nBOOST_HANA_CONSTANT_CHECK(!greater_equal(int_<1>, int_<2>));\n//! [greater_equal]\n\n}{\n\n//! [less]\nBOOST_HANA_CONSTEXPR_CHECK(less(1, 4));\nBOOST_HANA_CONSTANT_CHECK(!less(int_<3>, int_<2>));\n//! [less]\n\n}{\n\n//! [less_equal]\nBOOST_HANA_CONSTEXPR_CHECK(less_equal(1, 4));\nBOOST_HANA_CONSTEXPR_CHECK(less_equal(1, 1));\nBOOST_HANA_CONSTANT_CHECK(!less_equal(int_<3>, int_<2>));\n//! [less_equal]\n\n}{\n\n//! [max]\nBOOST_HANA_CONSTEXPR_CHECK(max(1, 4) == 4);\nBOOST_HANA_CONSTANT_CHECK(max(int_<7>, int_<5>) == int_<7>);\n//! [max]\n\n}{\n\n//! [min]\nBOOST_HANA_CONSTEXPR_CHECK(min(1, 4) == 1);\nBOOST_HANA_CONSTANT_CHECK(min(int_<7>, int_<5>) == int_<5>);\n//! [min]\n\n}{\n\n//! [ordering]\nBOOST_HANA_CONSTEXPR_LAMBDA auto sorted = sort_by(ordering(sizeof_), tuple_t<\n    char[3], char[1], char[2], char[15]\n>);\nBOOST_HANA_CONSTANT_CHECK(sorted == tuple_t<\n    char[1], char[2], char[3], char[15]\n>);\n//! [ordering]\n\n}\n\n}\n", "meta": {"hexsha": "e1ac43b482133f7cf719dfd3fae4deb4edc01938", "size": 1783, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/orderable.cpp", "max_stars_repo_name": "josephwinston/hana", "max_stars_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/orderable.cpp", "max_issues_repo_name": "josephwinston/hana", "max_issues_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/orderable.cpp", "max_forks_repo_name": "josephwinston/hana", "max_forks_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.2261904762, "max_line_length": 86, "alphanum_fraction": 0.7016264722, "num_tokens": 550, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.6926419704455588, "lm_q1q2_score": 0.4797529080117631}}
{"text": "#ifndef CALIBRATE_HPP\n#define CALIBRATE_HPP\n\n#include <vector>\n\n#include <Eigen/Geometry>\n\n// Assuming that the photos have been distributed roughly evenly around the\n// circle and that the rotation axis was close to the global vertical axis.\n// The returned vector is the camera space +y vector in IMU coordinates. y is down on the image.\nEigen::Vector3f get_y_axis(std::vector<Eigen::Vector3f> const& photo_gravity);\n\n// Assumes that the camera x axis was roughly orthogonal to the world vertcal axis and\n// the photos were taken while rotating exactly around the camera x axis.\nEigen::Vector3f get_x_axis(std::vector<Eigen::Vector3f> const& photo_gravity);\n\n// Returns the rotation from IMU frame to Camera frame.\nEigen::Quaternionf calibrate(std::ifstream& recording_infile,\n                             int x_session_index, int y_session_index,\n                             int nr_skip_measurements);\n\n#endif // CALIBRATE_HPP\n", "meta": {"hexsha": "4437a2ae3ff3b3b4cfca3440b9dda17dcdfa4ca2", "size": 931, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "recording_parser/calibrate.hpp", "max_stars_repo_name": "Pascal-So/arduino-gravity-recorder", "max_stars_repo_head_hexsha": "665148ae009bd9d24134ed0b7d8149cd691a000c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "recording_parser/calibrate.hpp", "max_issues_repo_name": "Pascal-So/arduino-gravity-recorder", "max_issues_repo_head_hexsha": "665148ae009bd9d24134ed0b7d8149cd691a000c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "recording_parser/calibrate.hpp", "max_forks_repo_name": "Pascal-So/arduino-gravity-recorder", "max_forks_repo_head_hexsha": "665148ae009bd9d24134ed0b7d8149cd691a000c", "max_forks_repo_licenses": ["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.4782608696, "max_line_length": 96, "alphanum_fraction": 0.7411385607, "num_tokens": 204, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.47974119936145226}}
{"text": "// Copyright (c) 2017 Graphcore Ltd. All rights reserved.\n#include <boost/multi_array.hpp>\n#include <cassert>\n#include <poplibs_test/GeneralMatrixAdd.hpp>\n#include <poplibs_test/GeneralMatrixMultiply.hpp>\n#include <poplibs_test/Lstm.hpp>\n#include <poplibs_test/NonLinearity.hpp>\n#include <unordered_map>\n\n// Fwd state array indices\n#define LSTM_FWD_STATE_FORGET_GATE 2\n#define LSTM_FWD_STATE_CAND_TANH 3\n#define LSTM_FWD_STATE_INPUT_GATE 4\n#define LSTM_FWD_STATE_OUTPUT_GATE 5\n#define LSTM_FWD_STATE_OUTPUT_TANH 6\n\nusing IndexRange = boost::multi_array_types::index_range;\nusing Array1dRef = boost::multi_array_ref<double, 1>;\nusing Array2dRef = boost::multi_array_ref<double, 2>;\nusing Array2d = boost::multi_array<double, 2>;\nusing Array3dRef = boost::multi_array_ref<double, 3>;\nusing Array4dRef = boost::multi_array_ref<double, 4>;\nusing Array3d = boost::multi_array<double, 3>;\n\nusing namespace poplibs_test;\n\n/**\n * Process a given unit type within an LSTM given its weights and biases.\n * The non-linearity is also specified although it may be derived from the unit\n */\nstatic void processBasicLstmUnit(const Array2dRef prevOutput,\n                                 const Array2dRef input,\n                                 const Array3dRef weightsInput,\n                                 const Array3dRef weightsOutput,\n                                 const Array2dRef biases, Array2dRef output,\n                                 unsigned lstmUnitOffset,\n                                 popnn::NonLinearityType nonLinearityType) {\n  const auto batchSize = prevOutput.shape()[0];\n  const auto outputSize = prevOutput.shape()[1];\n\n  /* split weight into two parts:\n   * 1) part which weighs only the previous output\n   * 2) part which weighs only the input\n   */\n  Array2d weightsOutputUnit = weightsOutput[lstmUnitOffset];\n  Array2d weightsInputUnit = weightsInput[lstmUnitOffset];\n\n  gemm::generalMatrixMultiply(prevOutput, weightsOutputUnit, output, output,\n                              1.0, 0, false, false);\n  gemm::generalMatrixMultiply(input, weightsInputUnit, output, output, 1.0, 1.0,\n                              false, false);\n  /* add bias */\n  for (auto b = 0U; b != batchSize; ++b) {\n    for (auto i = 0U; i != outputSize; ++i) {\n      output[b][i] += biases[lstmUnitOffset][i];\n    }\n  }\n\n  /* apply non-linearity */\n  nonLinearity(nonLinearityType, output);\n}\n\nstatic std::unordered_map<BasicLstmCellUnit, unsigned>\ngetCellMapping(const std::vector<BasicLstmCellUnit> &cellOrder) {\n  // build a mapping of the order that the gates are stored in.\n  std::unordered_map<BasicLstmCellUnit, unsigned> cellMapping;\n  for (unsigned i = 0; i < cellOrder.size(); ++i) {\n    auto gate = cellOrder.at(i);\n    cellMapping.insert(std::make_pair(gate, i));\n  }\n\n  return cellMapping;\n}\n\nvoid poplibs_test::lstm::basicLstmCellForwardPass(\n    const Array3dRef input, const Array2dRef biases,\n    const Array2dRef prevOutput, const Array3dRef weightsInput,\n    const Array3dRef weightsOutput, Array2dRef prevCellState, Array4dRef state,\n    const std::vector<BasicLstmCellUnit> &cellOrder) {\n  const auto sequenceSize = state.shape()[1];\n  const auto batchSize = state.shape()[2];\n  const auto outputSize = state.shape()[3];\n#ifndef NDEBUG\n  const auto inputSize = input.shape()[2];\n#endif\n  assert(state.shape()[0] == LSTM_NUM_FWD_STATES);\n  assert(weightsInput.shape()[0] == BASIC_LSTM_CELL_NUM_UNITS);\n  assert(weightsInput.shape()[1] == inputSize);\n  assert(weightsInput.shape()[2] == outputSize);\n  assert(weightsOutput.shape()[0] == BASIC_LSTM_CELL_NUM_UNITS);\n  assert(weightsOutput.shape()[1] == outputSize);\n  assert(weightsOutput.shape()[2] == outputSize);\n  assert(prevCellState.shape()[0] == batchSize);\n  assert(prevCellState.shape()[1] == outputSize);\n  assert(biases.shape()[0] == BASIC_LSTM_CELL_NUM_UNITS);\n  assert(biases.shape()[1] == outputSize);\n  assert(prevOutput.shape()[0] == batchSize);\n  assert(prevOutput.shape()[1] == outputSize);\n\n  auto cellMapping = getCellMapping(cellOrder);\n\n  for (auto s = 0U; s != sequenceSize; ++s) {\n    Array2d ysm1 = s == 0 ? state[LSTM_FWD_STATE_ACTS_IDX][s]\n                          : state[LSTM_FWD_STATE_ACTS_IDX][s - 1];\n    Array2d csm1 = s == 0 ? state[LSTM_FWD_STATE_CELL_STATE_IDX][s]\n                          : state[LSTM_FWD_STATE_CELL_STATE_IDX][s - 1];\n    Array2d prevOutputThisStep = s == 0 ? prevOutput : ysm1;\n    Array2d cellState = s == 0 ? prevCellState : csm1;\n    Array2d inputThisStep = input[s];\n\n    /* forget gate */\n    Array2d forgetGate(boost::extents[batchSize][outputSize]);\n    processBasicLstmUnit(prevOutputThisStep, inputThisStep, weightsInput,\n                         weightsOutput, biases, forgetGate,\n                         cellMapping.at(BASIC_LSTM_CELL_FORGET_GATE),\n                         popnn::NonLinearityType::SIGMOID);\n    state[LSTM_FWD_STATE_FORGET_GATE][s] = forgetGate;\n\n    /* input gate */\n    Array2d inputGate(boost::extents[batchSize][outputSize]);\n    processBasicLstmUnit(prevOutputThisStep, inputThisStep, weightsInput,\n                         weightsOutput, biases, inputGate,\n                         cellMapping.at(BASIC_LSTM_CELL_INPUT_GATE),\n                         popnn::NonLinearityType::SIGMOID);\n    state[LSTM_FWD_STATE_INPUT_GATE][s] = inputGate;\n\n    /* new candidate contribution to this cell */\n    Array2d candidate(boost::extents[batchSize][outputSize]);\n    processBasicLstmUnit(prevOutputThisStep, inputThisStep, weightsInput,\n                         weightsOutput, biases, candidate,\n                         cellMapping.at(BASIC_LSTM_CELL_CANDIDATE),\n                         popnn::NonLinearityType::TANH);\n    state[LSTM_FWD_STATE_CAND_TANH][s] = candidate;\n\n    /* output gate */\n    Array2d outputGate(boost::extents[batchSize][outputSize]);\n    processBasicLstmUnit(prevOutputThisStep, inputThisStep, weightsInput,\n                         weightsOutput, biases, outputGate,\n                         cellMapping.at(BASIC_LSTM_CELL_OUTPUT_GATE),\n                         popnn::NonLinearityType::SIGMOID);\n    state[LSTM_FWD_STATE_OUTPUT_GATE][s] = outputGate;\n\n    poplibs_test::gemm::hadamardProduct(forgetGate, cellState, cellState);\n    poplibs_test::gemm::hadamardProduct(inputGate, candidate, candidate);\n    poplibs_test::axpby::add(cellState, candidate, cellState);\n\n    /* need to maintain the cell state for next step */\n    Array2d outputThisStep = cellState;\n    nonLinearity(popnn::NonLinearityType::TANH, outputThisStep);\n    state[LSTM_FWD_STATE_OUTPUT_TANH][s] = outputThisStep;\n    gemm::hadamardProduct(outputThisStep, outputGate, outputThisStep);\n\n    state[LSTM_FWD_STATE_ACTS_IDX][s] = outputThisStep;\n    state[LSTM_FWD_STATE_CELL_STATE_IDX][s] = cellState;\n  }\n}\n\nstatic void computeGradients(const Array2dRef weightIn,\n                             const Array2dRef weightPrev, const Array2dRef grad,\n                             Array2dRef gradIn, Array2dRef gradPrev, bool acc) {\n  double k = acc ? 1.0 : 0.0;\n  gemm::generalMatrixMultiply(grad, weightIn, gradIn, gradIn, 1.0, k, false,\n                              true);\n  gemm::generalMatrixMultiply(grad, weightPrev, gradPrev, gradPrev, 1.0, k,\n                              false, true);\n}\n\nvoid poplibs_test::lstm::basicLstmCellBackwardPass(\n    const Array3dRef weightsInput, const Array3dRef weightsOutput,\n    const Array3dRef gradsNextLayer, const Array2dRef prevCellState,\n    const Array4dRef fwdState, Array4dRef bwdState, Array3dRef gradsPrevLayer,\n    const std::vector<BasicLstmCellUnit> &cellOrder) {\n  const auto sequenceSize = fwdState.shape()[1];\n  const auto batchSize = fwdState.shape()[2];\n  const auto outputSize = fwdState.shape()[3];\n  const auto inputSize = gradsPrevLayer.shape()[2];\n\n  assert(fwdState.shape()[0] == LSTM_NUM_FWD_STATES);\n  assert(bwdState.shape()[0] == LSTM_NUM_BWD_STATES);\n  assert(weightsInput.shape()[0] == BASIC_LSTM_CELL_NUM_UNITS);\n  assert(weightsInput.shape()[1] == inputSize);\n  assert(weightsInput.shape()[2] == outputSize);\n  assert(weightsOutput.shape()[0] == BASIC_LSTM_CELL_NUM_UNITS);\n  assert(weightsOutput.shape()[1] == outputSize);\n  assert(weightsOutput.shape()[2] == outputSize);\n  assert(prevCellState.shape()[0] == batchSize);\n  assert(prevCellState.shape()[1] == outputSize);\n  assert(fwdState.shape()[1] == sequenceSize);\n  assert(fwdState.shape()[2] == batchSize);\n  assert(fwdState.shape()[3] == outputSize);\n  assert(bwdState.shape()[1] == sequenceSize);\n  assert(bwdState.shape()[2] == batchSize);\n  assert(bwdState.shape()[3] == outputSize);\n  assert(gradsNextLayer.shape()[0] == sequenceSize);\n  assert(gradsNextLayer.shape()[1] == batchSize);\n  assert(gradsNextLayer.shape()[2] == outputSize);\n  assert(gradsPrevLayer.shape()[0] == sequenceSize);\n  assert(gradsPrevLayer.shape()[1] == batchSize);\n\n  auto cellMapping = getCellMapping(cellOrder);\n\n  // gradient of cell state for this step\n  Array2d gradCellState(boost::extents[batchSize][outputSize]);\n  for (auto it = gradCellState.data(),\n            end = gradCellState.data() + gradCellState.num_elements();\n       it != end; ++it) {\n    *it = 0;\n  }\n\n  // gradient of output of this step\n  Array2d gradOutput(boost::extents[batchSize][outputSize]);\n  for (auto it = gradCellState.data(),\n            end = gradCellState.data() + gradCellState.num_elements();\n       it != end; ++it) {\n    *it = 0;\n  }\n\n  for (auto i = sequenceSize; i != 0; --i) {\n    const auto s = i - 1;\n\n    Array2d sumGradOut(boost::extents[batchSize][outputSize]);\n    Array2d gradOut = gradsNextLayer[s];\n    axpby::add(gradOut, gradOutput, sumGradOut);\n\n    Array2d actOutGate = fwdState[LSTM_FWD_STATE_OUTPUT_GATE][s];\n    Array2d gradAtOTanhInp(boost::extents[batchSize][outputSize]);\n    gemm::hadamardProduct(actOutGate, sumGradOut, gradAtOTanhInp);\n\n    Array2d actTanhOutGate = fwdState[LSTM_FWD_STATE_OUTPUT_TANH][s];\n    Array2d gradAtOutGate(boost::extents[batchSize][outputSize]);\n    ;\n\n    gemm::hadamardProduct(actTanhOutGate, sumGradOut, gradAtOutGate);\n\n    bwdNonLinearity(popnn::NonLinearityType::TANH, actTanhOutGate,\n                    gradAtOTanhInp);\n\n    bwdNonLinearity(popnn::NonLinearityType::SIGMOID, actOutGate,\n                    gradAtOutGate);\n\n    Array2dRef gradAtCellStateSum = gradAtOTanhInp;\n    axpby::add(gradAtOTanhInp, gradCellState, gradAtCellStateSum);\n\n    Array2d actInpGate = fwdState[LSTM_FWD_STATE_INPUT_GATE][s];\n    Array2d gradAtCand(boost::extents[batchSize][outputSize]);\n    ;\n    gemm::hadamardProduct(actInpGate, gradAtCellStateSum, gradAtCand);\n    Array2d actCand = fwdState[LSTM_FWD_STATE_CAND_TANH][s];\n    Array2d gradAtInpGate(boost::extents[batchSize][outputSize]);\n    ;\n    gemm::hadamardProduct(actCand, gradAtCellStateSum, gradAtInpGate);\n    bwdNonLinearity(popnn::NonLinearityType::TANH, actCand, gradAtCand);\n    bwdNonLinearity(popnn::NonLinearityType::SIGMOID, actInpGate,\n                    gradAtInpGate);\n\n    Array2d actForgetGate = fwdState[LSTM_FWD_STATE_FORGET_GATE][s];\n    gemm::hadamardProduct(actForgetGate, gradAtCellStateSum, gradCellState);\n\n    Array2d pCellAct(boost::extents[batchSize][outputSize]);\n\n    if (s == 0) {\n      pCellAct = prevCellState;\n    } else {\n      pCellAct = fwdState[LSTM_FWD_STATE_CELL_STATE_IDX][s - 1];\n    }\n    Array2d gradAtForgetGate(boost::extents[batchSize][outputSize]);\n    ;\n\n    gemm::hadamardProduct(pCellAct, gradAtCellStateSum, gradAtForgetGate);\n    bwdNonLinearity(popnn::NonLinearityType::SIGMOID, actForgetGate,\n                    gradAtForgetGate);\n\n    Array2d gradIn(boost::extents[batchSize][inputSize]);\n    ;\n    Array2d weightsInUnit =\n        weightsInput[cellMapping.at(BASIC_LSTM_CELL_FORGET_GATE)];\n    Array2d weightsOutUnit =\n        weightsOutput[cellMapping.at(BASIC_LSTM_CELL_FORGET_GATE)];\n    computeGradients(weightsInUnit, weightsOutUnit, gradAtForgetGate, gradIn,\n                     gradOutput, false);\n    weightsInUnit = weightsInput[cellMapping.at(BASIC_LSTM_CELL_INPUT_GATE)];\n    weightsOutUnit = weightsOutput[cellMapping.at(BASIC_LSTM_CELL_INPUT_GATE)];\n    computeGradients(weightsInUnit, weightsOutUnit, gradAtInpGate, gradIn,\n                     gradOutput, true);\n    weightsInUnit = weightsInput[cellMapping.at(BASIC_LSTM_CELL_OUTPUT_GATE)];\n    weightsOutUnit = weightsOutput[cellMapping.at(BASIC_LSTM_CELL_OUTPUT_GATE)];\n    computeGradients(weightsInUnit, weightsOutUnit, gradAtOutGate, gradIn,\n                     gradOutput, true);\n    weightsInUnit = weightsInput[cellMapping.at(BASIC_LSTM_CELL_CANDIDATE)];\n    weightsOutUnit = weightsOutput[cellMapping.at(BASIC_LSTM_CELL_CANDIDATE)];\n    computeGradients(weightsInUnit, weightsOutUnit, gradAtCand, gradIn,\n                     gradOutput, true);\n\n    gradsPrevLayer[s] = gradIn;\n\n    // save bwd state for weight update\n    bwdState[BASIC_LSTM_CELL_FORGET_GATE][s] = gradAtForgetGate;\n    bwdState[BASIC_LSTM_CELL_INPUT_GATE][s] = gradAtInpGate;\n    bwdState[BASIC_LSTM_CELL_OUTPUT_GATE][s] = gradAtOutGate;\n    bwdState[BASIC_LSTM_CELL_CANDIDATE][s] = gradAtCand;\n  }\n}\n\nvoid poplibs_test::lstm::basicLstmCellParamUpdate(\n    const Array3dRef prevLayerActs, const Array4dRef fwdState,\n    const Array2dRef outputActsInit, const Array4dRef bwdState,\n    Array3dRef weightsInputDeltas, Array3dRef weightsOutputDeltas,\n    Array2dRef biasDeltas, const std::vector<BasicLstmCellUnit> &cellOrder) {\n  const auto sequenceSize = prevLayerActs.shape()[0];\n  const auto batchSize = prevLayerActs.shape()[1];\n  const auto inputSize = prevLayerActs.shape()[2];\n  const auto outputSize = fwdState.shape()[3];\n\n  assert(fwdState.shape()[0] == LSTM_NUM_FWD_STATES);\n  assert(fwdState.shape()[1] == sequenceSize);\n  assert(fwdState.shape()[2] == batchSize);\n  assert(outputActsInit.shape()[0] == batchSize);\n  assert(outputActsInit.shape()[1] == outputSize);\n  assert(bwdState.shape()[0] == LSTM_NUM_BWD_STATES);\n  assert(bwdState.shape()[1] == sequenceSize);\n  assert(bwdState.shape()[2] == batchSize);\n  assert(bwdState.shape()[3] == outputSize);\n  assert(weightsInputDeltas.shape()[0] == BASIC_LSTM_CELL_NUM_UNITS);\n  assert(weightsInputDeltas.shape()[1] == inputSize);\n  assert(weightsInputDeltas.shape()[2] == outputSize);\n  assert(weightsOutputDeltas.shape()[0] == BASIC_LSTM_CELL_NUM_UNITS);\n  assert(weightsOutputDeltas.shape()[1] == outputSize);\n  assert(weightsOutputDeltas.shape()[2] == outputSize);\n  assert(biasDeltas.shape()[0] == BASIC_LSTM_CELL_NUM_UNITS);\n  assert(biasDeltas.shape()[1] == outputSize);\n\n  auto cellMapping = getCellMapping(cellOrder);\n\n  for (auto it = weightsInputDeltas.data(),\n            end = weightsInputDeltas.data() + weightsInputDeltas.num_elements();\n       it != end; ++it) {\n    *it = 0;\n  }\n  for (auto it = weightsOutputDeltas.data(),\n            end =\n                weightsOutputDeltas.data() + weightsOutputDeltas.num_elements();\n       it != end; ++it) {\n    *it = 0;\n  }\n  for (auto it = biasDeltas.data(),\n            end = biasDeltas.data() + biasDeltas.num_elements();\n       it != end; ++it) {\n    *it = 0;\n  }\n\n  for (auto i = sequenceSize; i != 0; --i) {\n    const auto s = i - 1;\n    Array2d outActs(boost::extents[batchSize][outputSize]);\n    if (s == 0) {\n      outActs = outputActsInit;\n    } else {\n      outActs = fwdState[LSTM_FWD_STATE_ACTS_IDX][s - 1];\n    }\n    Array2d inActs = prevLayerActs[s];\n    for (auto i = 0; i != BASIC_LSTM_CELL_NUM_UNITS; ++i) {\n      const auto unit = static_cast<BasicLstmCellUnit>(i);\n\n      Array2d grad = bwdState[i][s];\n      Array2d wInputDeltasUnit(boost::extents[inputSize][outputSize]);\n\n      gemm::generalMatrixMultiply(inActs, grad, wInputDeltasUnit,\n                                  wInputDeltasUnit, 1.0, 0, true, false);\n      for (auto ic = 0u; ic != inputSize; ++ic) {\n        for (auto oc = 0u; oc != outputSize; ++oc) {\n          weightsInputDeltas[cellMapping.at(unit)][ic][oc] +=\n              wInputDeltasUnit[ic][oc];\n        }\n      }\n      Array2d wOutputDeltasUnit(boost::extents[outputSize][outputSize]);\n\n      gemm::generalMatrixMultiply(outActs, grad, wOutputDeltasUnit,\n                                  wOutputDeltasUnit, 1.0, 0, true, false);\n      for (auto oc1 = 0u; oc1 != outputSize; ++oc1) {\n        for (auto oc2 = 0u; oc2 != outputSize; ++oc2) {\n          weightsOutputDeltas[cellMapping.at(unit)][oc1][oc2] +=\n              wOutputDeltasUnit[oc1][oc2];\n        }\n      }\n\n      for (auto oc = 0u; oc != outputSize; ++oc) {\n        for (auto b = 0u; b != batchSize; ++b) {\n          biasDeltas[cellMapping.at(unit)][oc] += grad[b][oc];\n        }\n      }\n    }\n  }\n}\n", "meta": {"hexsha": "5caa94b491c0b57dc07ffa4d8a52e6f95b522d7f", "size": 16564, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/poplibs_test/Lstm.cpp", "max_stars_repo_name": "giantchen2012/poplibs", "max_stars_repo_head_hexsha": "2bc6b6f3d40863c928b935b5da88f40ddd77078e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-23T05:58:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-23T05:58:24.000Z", "max_issues_repo_path": "lib/poplibs_test/Lstm.cpp", "max_issues_repo_name": "giantchen2012/poplibs", "max_issues_repo_head_hexsha": "2bc6b6f3d40863c928b935b5da88f40ddd77078e", "max_issues_repo_licenses": ["MIT"], "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/poplibs_test/Lstm.cpp", "max_forks_repo_name": "giantchen2012/poplibs", "max_forks_repo_head_hexsha": "2bc6b6f3d40863c928b935b5da88f40ddd77078e", "max_forks_repo_licenses": ["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.1475826972, "max_line_length": 80, "alphanum_fraction": 0.6820816228, "num_tokens": 4475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264638, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.4797411955075613}}
{"text": "/* MIT License\n *\n * Copyright (c) 2020 Aleksa Ilic <aleksa.d.ilic@gmail.com>\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n*/\n\n#include <algorithm>\n#include <numeric>\n#include <iostream>\n#include <string>\n#include <tuple>\n#include <regex>\n\n#include <boost/algorithm/string.hpp>\n#include <boost/program_options.hpp>\n#include <boost/rational.hpp>\n#include <boost/optional/optional.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/math/constants/constants.hpp>\n\n#ifdef TESTING_ENABLED\n#define CATCH_CONFIG_MAIN\n#include <catch.hpp>\n#include <prettyprint.hpp>\n#else\n#endif\n\n#include <fort.hpp>\n\nstatic constexpr auto kVersion = \"v0.2.1\";\nstatic constexpr auto kProgramName = \"OPNA_1: Continued Fraction Generator\";\nstatic constexpr auto kUnderlineType = '-';\n\n// -- CHANGE THESE TYPES FOR MORE PRECISION\nnamespace mp = boost::multiprecision;\nusing IntType = mp::int1024_t;\nusing FloatType = mp::number<mp::cpp_dec_float<256>>;\nusing Fraction = boost::rational<IntType>;\nusing DecimalNumber = std::tuple<IntType, FloatType>;\n\nenum class Field {\n    ITERATION, INDICES, FRACTION, EVALUATED_FRACTION, DIFFERENCE\n};\n\nconstexpr const char *FieldToString(Field field) {\n    switch (field) {\n        case Field::ITERATION:\n            return \"Iteration\";\n        case Field::INDICES:\n            return \"Indices\";\n        case Field::FRACTION:\n            return \"Fraction\";\n        case Field::EVALUATED_FRACTION:\n            return \"Evaluated fraction\";\n        case Field::DIFFERENCE:\n            return \"Difference\";\n    }\n}\n\nstruct Config {\n    size_t precision = 14;\n    size_t iterations = 14;\n    IntType max_denominator = std::numeric_limits<IntType>::max();\n    bool find_in_between = false;\n    bool headerless = false;\n    const struct ft_border_style *table_style = FT_NICE_STYLE;\n    std::vector<Field> displayed_fields = {Field::ITERATION, Field::INDICES,\n                                           Field::FRACTION, Field::EVALUATED_FRACTION,\n                                           Field::DIFFERENCE};\n};\nstatic const Config kDefaultConfig;\n\n/// Pretty prints DecimalNumber to stream\nstd::ostream &operator<<(std::ostream &os, const DecimalNumber &number) {\n    return os << '(' << std::get<0>(number) << ',' << std::get<1>(number) << ')';\n}\n\n/// Performs substring operation with range check without throwing errors\n/// \\param string String to be processed\n/// \\param position Position from which to extract\n/// \\param length How many characters are to be processed\n/// \\return Extracted substring if range check passes or boost::none\nboost::optional<std::string>\nSafeSubstring(const std::string &string, size_t position, size_t length = std::string::npos) {\n    if (position >= string.length())\n        return boost::none;\n    else\n        return string.substr(position, length);\n}\n\n/// Splits decimal number into whole and fraction part\n/// \\param numer Number to be parsed\n/// \\return Tuple containing whole and fraction\nDecimalNumber ParseDecimalNumber(FloatType number) {\n    auto a = mp::floor(number);\n    auto d = number - a;\n    return std::make_tuple(a.convert_to<IntType>(), d);\n}\n\n/// Split decimal number into whole and fraction part\n/// \\param number Number to be parsed\n/// \\return Tuple containing whole and fraction\nDecimalNumber ParseDecimalNumber(std::string number) {\n    if (number == \"pi\") {\n        return ParseDecimalNumber(boost::math::constants::pi<FloatType>());\n    } else if (number == \"phi\") {\n        return ParseDecimalNumber(boost::math::constants::phi<FloatType>());\n    } else if (number == \"e\") {\n        return ParseDecimalNumber(boost::math::constants::e<FloatType>());\n    } else if (number == \"catalan\") {\n        return ParseDecimalNumber(boost::math::constants::catalan<FloatType>());\n    }\n\n    auto dot_index = number.find('.');\n    if (dot_index == std::string::npos) {\n        return std::make_tuple(std::stol(number), 0);\n    }\n    std::string a = number.substr(0, dot_index);\n    std::string d = \"0.\" + SafeSubstring(number, dot_index + 1).get_value_or(\"0\");\n\n    return std::make_tuple(std::stoll(a), FloatType(d));\n}\n\n/// Generates continued fraction indices\n/// \\param indices Generated indices from previous iterations\n/// \\param total_iterations Total number of iterations to run (max indices size)\n/// \\return Generated indices\nstd::vector<DecimalNumber> ContinuedFractionIndices(std::vector<DecimalNumber> &indices, size_t total_iterations) {\n    if (indices.size() == 0) {\n        throw std::invalid_argument(\"Indices must not be empty\");\n    }\n\n    for (int i = indices.size(); i < total_iterations; i++) {\n        auto[a, d] = indices.back();\n        indices.push_back(ParseDecimalNumber(FloatType(1) / d));\n    }\n\n    return indices;\n}\n\n/// Generates continued fraction indices\n/// \\param number Decimal number for which to calculate indices\n/// \\param iterations Number of iterations\n/// \\return Generated indices\nstd::vector<DecimalNumber> ContinuedFractionIndices(DecimalNumber number, size_t iterations) {\n    std::vector<DecimalNumber> indices;\n    indices.reserve(iterations);\n\n    indices.push_back(number);\n    return ContinuedFractionIndices(indices, iterations);\n}\n\n/// Evaluate continued fraction indices to get fractional representation\n/// \\param indices Continued fraction indices\n/// \\return Evaluated fraction\nFraction ContinuedFractionEvaluator(std::vector<DecimalNumber> indices) {\n    return std::accumulate(std::next(indices.rbegin()),\n                           indices.rend(),\n                           Fraction(std::get<0>(indices.back()), 1),\n                           [](Fraction accumulator, DecimalNumber number) {\n                               return 1 / accumulator + std::get<0>(number);\n                           });\n}\n\nenum class EvaluatedType {\n    I, II\n};\nstruct EvaluatedIteration {\n    std::vector<DecimalNumber> indices;\n    Fraction fraction;\n    FloatType evaluated_fraction;\n    FloatType diff;\n    EvaluatedType type;\n};\n\n/// Evaluates single iteration from indices and populates all relevant fields\n/// \\param number_searched Number for which we are deducing optimal indices\n/// \\param indices Generated continued fraction indices\n/// \\param type Type of iteration (First order/Second order)\n/// \\return\nEvaluatedIteration\nEvaluateIteration(FloatType number_searched, const std::vector<DecimalNumber> &indices,\n                  EvaluatedType type) {\n    Fraction fraction = ContinuedFractionEvaluator(indices);\n    if (fraction < 0) {\n        throw std::overflow_error(\n                \"Underlying type overflow. Compile with larger integer and/or floating point types.\");\n    }\n    auto evaluated_fraction = FloatType(fraction.numerator()) / FloatType(fraction.denominator());\n    auto diff = number_searched - evaluated_fraction;\n    return EvaluatedIteration{indices, fraction, evaluated_fraction, diff, type};\n}\n\nvoid PrintEvaluatedIteration(fort::char_table &table, const EvaluatedIteration &iteration, const Config &config) {\n    for (const auto &header : config.displayed_fields) {\n        std::ostringstream oss;\n        switch (header) {\n            case Field::ITERATION:\n                table << iteration.indices.size();\n                break;\n            case Field::INDICES:\n                oss << '[';\n                for (int j = 0; j < iteration.indices.size(); j++) {\n                    oss << std::get<0>(iteration.indices[j]);\n                    if (j < iteration.indices.size() - 1)\n                        oss << ',';\n                }\n                oss << ']';\n                table << oss.str();\n                break;\n            case Field::FRACTION:\n                oss << iteration.fraction;\n                if (iteration.type == EvaluatedType::I)\n                    oss << '*';\n                table << oss.str();\n                break;\n            case Field::EVALUATED_FRACTION:\n                table << iteration.evaluated_fraction.str(config.precision, std::ios::fixed);\n                break;\n            case Field::DIFFERENCE:\n                table << std::regex_replace(iteration.diff.str(config.precision, std::ios::scientific), std::regex(\"e\"),\n                                            \" * 10^\");\n                break;\n        }\n    }\n    table << fort::endr;\n}\n\nvoid PrintEvaluationTableHeader(fort::char_table &table, const Config &config) {\n    if (!config.headerless) {\n        table << fort::header;\n        for (const auto &field : config.displayed_fields) {\n            table << FieldToString(field);\n        }\n        table << fort::endr;\n    }\n}\n\nvoid PrintEvaluationTable(const std::vector<EvaluatedIteration> &iterations, const Config &config) {\n    fort::char_table table;\n    table.set_border_style(config.table_style);\n\n    auto diff_it = std::find(config.displayed_fields.begin(), config.displayed_fields.end(), Field::DIFFERENCE);\n    PrintEvaluationTableHeader(table, config);\n\n    size_t counter = 1;\n    for (const auto &iteration : iterations) {\n        PrintEvaluatedIteration(table, iteration, config);\n        if(diff_it != config.displayed_fields.end()){\n            table[counter++][std::distance(config.displayed_fields.begin(), diff_it)].set_cell_text_align(fort::text_align::right);\n        }\n    }\n\n    std::cout << table.to_string();\n}\n\n/// Find indices of in-between approximations (Indices of second order)\n/// \\param number_searched Number for which we are deducing second order indices\n/// \\param indices Calculated continued fraction indices of the first order\n/// \\param diff Evaluated difference of indices of the first order\n/// \\return Vector of evaluated iterations of approximations of the second order\nstd::vector<EvaluatedIteration>\nFindInBetweenApproximations(FloatType number_searched, std::vector<DecimalNumber> indices, FloatType diff) {\n    auto from = IntType(1);\n    auto to = std::get<0>(indices.back());\n    indices.pop_back();\n\n    std::vector<EvaluatedIteration> iterations;\n    for (auto i = from; i < to; i++) {\n        indices.push_back(std::make_tuple(i, 0));\n        auto candidate = EvaluateIteration(number_searched, indices, EvaluatedType::II);\n        if (mp::abs(candidate.diff) < mp::abs(diff)) {\n            iterations.push_back(candidate);\n        }\n        indices.pop_back();\n    }\n    return iterations;\n}\n\n/// Processes decimal number with given configuration. Throws overflow error.\n/// \\param number Decimal number to be processed\n/// \\param config Main program configuration\n/// \\return Vector of evaluated iterations\nstd::vector<EvaluatedIteration>\nProcessDecimalNumber(DecimalNumber number, const Config &config) {\n    const auto number_searched = FloatType(std::get<0>(number)) + FloatType(std::get<1>(number));\n    std::vector<DecimalNumber> indices = ContinuedFractionIndices(number, 1);\n    std::vector<EvaluatedIteration> evaluated_iterations;\n\n    auto fraction = ContinuedFractionEvaluator(indices);\n    auto evaluated_fraction = FloatType(fraction.numerator()) / FloatType(fraction.denominator());\n    evaluated_iterations.push_back(\n            {indices, fraction, evaluated_fraction, number_searched - evaluated_fraction, EvaluatedType::I});\n\n    try {\n        for (size_t iteration_number = 2; iteration_number <= config.iterations; iteration_number++) {\n            ContinuedFractionIndices(indices, iteration_number);\n            auto evaluated_iteration = EvaluateIteration(number_searched, indices, EvaluatedType::I);\n            if (mp::abs(evaluated_iteration.diff) > mp::abs(evaluated_iterations.back().diff)) {\n                throw std::overflow_error(\n                        \"More iterations result in bigger deviation. Compile with larger integer and/or floating point types.\");\n            }\n            if (config.find_in_between) {\n                auto in_between_aproximations = FindInBetweenApproximations(number_searched, indices,\n                                                                            evaluated_iterations.back().diff);\n                evaluated_iterations.insert(evaluated_iterations.end(), in_between_aproximations.begin(),\n                                            in_between_aproximations.end());\n            }\n            evaluated_iterations.push_back(evaluated_iteration);\n            if (evaluated_iterations.back().fraction.denominator() > config.max_denominator) {\n                evaluated_iterations.erase(std::lower_bound(evaluated_iterations.begin(), evaluated_iterations.end(),\n                                                            config.max_denominator,\n                                                            [](const auto &iteration, const auto &max_denominator) {\n                                                                return iteration.fraction.denominator() <=\n                                                                       max_denominator;\n                                                            }), evaluated_iterations.end());\n                break;\n            }\n        }\n    } catch (const std::overflow_error &err) {\n        std::cerr << err.what() << \" Stopped at iteration: \" << indices.size() << std::endl;\n    }\n\n    std::sort(evaluated_iterations.begin(), evaluated_iterations.end(),\n              [](auto &lhs, auto &rhs) {\n                  return mp::abs(lhs.diff) >= mp::abs(rhs.diff);\n              });\n\n    return evaluated_iterations;\n}\n\n/// Retrieves program's base name from the exec path\nstatic const char *GetProgramName(const char *path) {\n    const char *last = path;\n    while (*path++) {\n        last = (*path == '/' || *path == '\\\\') ? path : last;\n    }\n    return last;\n}\n\n#ifdef TESTING_ENABLED\nTEST_CASE(\"GetProgramName\") {\n    constexpr auto kExamplePath1 = \"/home/ilic/opna-1/opna_1\";\n    constexpr auto kExamplePath2 = \"C:\\\\Users\\\\My Documents\\\\opna_1\";\n    constexpr auto kExpectedName1 = \"/opna_1\";\n    constexpr auto kExpectedName2 = \"\\\\opna_1\";\n\n    REQUIRE(strcmp(GetProgramName(kExamplePath1), kExpectedName1) == 0);\n    REQUIRE(strcmp(GetProgramName(kExamplePath2), kExpectedName2) == 0);\n}\nTEST_CASE(\"ContinuedFractionEvaluator\") {\n    const auto kExampleNumber = boost::math::constants::pi<FloatType>();\n    const std::vector<Fraction> kExpectedResults = {{3,        1},\n                                                    {22,       7},\n                                                    {333,      106},\n                                                    {355,      113},\n                                                    {103993,   33102},\n                                                    {104348,   33215},\n                                                    {208341,   66317},\n                                                    {312689,   99532},\n                                                    {833719,   265381},\n                                                    {1146408,  364913},\n                                                    {4272943,  1360120},\n                                                    {5419351,  1725033},\n                                                    {80143857, 25510582}};\n    constexpr auto kDegree = 13;\n    std::vector<Fraction> results(kDegree);\n    std::generate(results.begin(), results.end(), [n = 1, kExampleNumber]() mutable {\n        auto indices = ContinuedFractionIndices(ParseDecimalNumber(kExampleNumber), n++);\n        return ContinuedFractionEvaluator(indices);\n    });\n\n    REQUIRE(std::equal(kExpectedResults.begin(), kExpectedResults.end(), results.begin(), [](auto lhs, auto rhs) {\n        INFO(\"Checking fraction \" << lhs << \" and \" << rhs);\n        CHECK(lhs == rhs);\n        return lhs == rhs;\n    }));\n}\nTEST_CASE(\"ContinuedFractionIndices\") {\n    const auto kExampleNumber = boost::math::constants::pi<FloatType>();\n    const std::vector<IntType> kExpectedResults = {3, 7, 15, 1, 292, 1, 1, 1, 2, 1, 3, 1, 14, 2, 1, 1, 2, 2, 2, 2, 1,\n                                                   84,\n                                                   2, 1, 1, 15, 3, 13, 1, 4, 2, 6, 6, 99, 1, 2, 2, 6, 3, 5, 1, 1, 6, 8,\n                                                   1,\n                                                   7, 1, 2, 3, 7, 1, 2, 1, 1, 12, 1, 1, 1, 3, 1, 1, 8, 1, 1, 2, 1, 6, 1,\n                                                   1,\n                                                   5, 2, 2, 3, 1, 2, 4, 4, 16, 1, 161, 45, 1, 22, 1, 2, 2, 1};\n    auto indices = ContinuedFractionIndices(ParseDecimalNumber(kExampleNumber), kExpectedResults.size());\n    REQUIRE(std::equal(kExpectedResults.begin(), kExpectedResults.end(), indices.begin(), [](auto lhs, auto rhs) {\n        INFO(\"Checking number \" << lhs << \" and \" << rhs);\n        auto comparison = lhs == std::get<0>(rhs);\n        CHECK(comparison);\n        return comparison;\n    }));\n}\nTEST_CASE(\"ParseDecimalNumber\") {\n    REQUIRE(ParseDecimalNumber(\"3.14\") == std::make_tuple(3, FloatType(\"0.14\")));\n    REQUIRE(ParseDecimalNumber(1.5L) == std::make_tuple(1, 0.5L));\n    REQUIRE(ParseDecimalNumber(\"125\") == std::make_tuple(125, 0.0));\n    REQUIRE_THROWS(ParseDecimalNumber(\"NaN\"));\n}\n#else\n\nint main(int argc, const char *argv[]) {\n    namespace po = boost::program_options;\n\n    Config config = kDefaultConfig;\n\n    auto program_name = GetProgramName(argv[0]);\n    std::string number;\n    std::string table_style;\n    std::string fields;\n\n    // Declare the supported options.\n    po::options_description desc(\"Allowed options\");\n    desc.add_options()\n            (\"help\", \"print help message\")\n            (\"version\", \"print version information\")\n            (\"examples\", \"show examples\")\n            (\"table\", \"print evaluation table of every iteration\")\n            (\"table_style\", po::value<std::string>(&table_style), \"Specify table style: nice|double|simple|empty\")\n            (\"headerless\", \"Do not display header when showing results\")\n            (\"fields\", po::value<std::string>(&fields),\n             \"Comma delimited list of fields to be shown: iter,ind,frac,eval,diff\")\n            (\"maxdenominator\", po::value<IntType>(&config.max_denominator),\n             \"maximum denominator up to which to iterate\")\n            (\"inbetween\", \"show best in-between continual fraction approximations as well\")\n            (\"iterations\", po::value<size_t>(&config.iterations)->default_value(kDefaultConfig.iterations),\n             \"number of iterations\")\n            (\"precision\", po::value<size_t>(&config.precision)->default_value(kDefaultConfig.precision),\n             \"how many decimals should result have\")\n            (\"number\", po::value<std::string>(&number), \"number to be parsed\");\n\n    po::positional_options_description pos_desc;\n    pos_desc.add(\"number\", 1);\n\n    po::variables_map vm;\n    po::store(po::command_line_parser(argc, argv).options(desc).positional(pos_desc).run(), vm);\n    po::notify(vm);\n\n    if (vm.count(\"help\")) {\n        std::cout << \"Usage: .\" << program_name << \" [OPTIONS] <NUMBER|CONSTANT> \\n\"\n                  << desc << '\\n'\n                  << \"Allowed constants: pi, phi, e, catalan \\n\";\n        return 0;\n    }\n\n    if (vm.count(\"version\")) {\n        std::ostringstream name_header;\n        name_header << kProgramName << ' ' << kVersion;\n\n        std::string underline(name_header.str().size(), kUnderlineType);\n\n        std::cout << name_header.str() << \"\\n\"\n                  << underline << \"\\n\"\n                  << \"Integer type w/: \" << std::numeric_limits<IntType>::digits << \"bits\\n\"\n                  << \"Floating type w/: \" << std::numeric_limits<FloatType>::digits10 << \"digits\\n\";\n        return 0;\n    }\n\n    if (vm.count(\"examples\")) {\n        fort::char_table table;\n        table.set_border_style(FT_EMPTY_STYLE);\n\n        const std::vector<std::tuple<std::string, std::string>> examples = {\n                std::make_tuple(\"pi\",\n                                \"Evaluates pi with default (\" + std::to_string(config.iterations) + \") iterations\"),\n                std::make_tuple(\"pi --table --iterations 5 --precision 10\",\n                                \"Print evaluation table with 5 iterations and up to 10 decimal places for pi expansion\"),\n                std::make_tuple(\"phi --table --maxdenominator 400 --inbetween\",\n                                \"Print evaluation table for phi where maximum fraction approximation denominator is less than or equal to 400\"),\n                std::make_tuple(\"phi --table --inbetween\",\n                                \"Print evaluation table for phi with default (\" + std::to_string(config.iterations) +\n                                \") iterations and also find best in-between approximations\")\n        };\n\n        table << fort::header\n              << \"\" << \"Command\" << \"Description\" << fort::endr;\n\n        for (size_t i = 0; i < examples.size(); i++) {\n            const auto&[command, description] = examples[i];\n            table << i + 1 << std::string(\".\") + program_name + \" \" + command << description << fort::endr;\n        }\n\n        std::cout << table.to_string();\n        return 0;\n    }\n\n    if (!vm.count(\"number\")) {\n        std::cerr << \"You need to specify a number. Use --help for usage information \\n\";\n        return 1;\n    }\n\n    if (vm.count(\"inbetween\")) {\n        config.find_in_between = true;\n    }\n\n    if (vm.count(\"headerless\")) {\n        config.headerless = true;\n    }\n\n    if (vm.count(\"table_style\")) {\n        if (boost::iequals(table_style, \"nice\")) {\n            config.table_style = FT_NICE_STYLE;\n        } else if (boost::iequals(table_style, \"simple\")) {\n            config.table_style = FT_SIMPLE_STYLE;\n        } else if (boost::iequals(table_style, \"double\")) {\n            config.table_style = FT_DOUBLE2_STYLE;\n        } else if (boost::iequals(table_style, \"empty\")) {\n            config.table_style = FT_EMPTY_STYLE;\n        } else {\n            std::cerr << \"Incorrect table style supplied: \" << table_style << \". Use --help for usage information \\n\";\n            return 1;\n        }\n    }\n\n    if (vm.count(\"fields\")) {\n        config.displayed_fields.clear();\n        std::vector<std::string> field_vector;\n        boost::split(field_vector, fields, [](char c) { return c == ','; });\n        for (const auto &field:field_vector) {\n            if (boost::iequals(field, \"iter\")) {\n                config.displayed_fields.push_back(Field::ITERATION);\n            } else if (boost::iequals(field, \"ind\")) {\n                config.displayed_fields.push_back(Field::INDICES);\n            } else if (boost::iequals(field, \"frac\")) {\n                config.displayed_fields.push_back(Field::FRACTION);\n            } else if (boost::iequals(field, \"eval\")) {\n                config.displayed_fields.push_back(Field::EVALUATED_FRACTION);\n            } else if (boost::iequals(field, \"diff\")) {\n                config.displayed_fields.push_back(Field::DIFFERENCE);\n            } else {\n                std::cerr << \"Incorrect field name supplied: \" << field << \". Use --help for usage information \\n\";\n                return 1;\n            }\n        }\n    }\n\n    auto evaluated_iterations = ProcessDecimalNumber(ParseDecimalNumber(number), config);\n    if (vm.count(\"table\")) {\n        PrintEvaluationTable(evaluated_iterations, config);\n    } else {\n        const auto &eval = evaluated_iterations.back();\n\n        fort::char_table table;\n        table.set_border_style(config.table_style);\n        PrintEvaluationTableHeader(table, config);\n        PrintEvaluatedIteration(table, eval, config);\n\n        std::cout << table.to_string();\n    }\n}\n\n#endif", "meta": {"hexsha": "6818fee2e4108261c0359fa53bf1e18c7ab6606b", "size": 24530, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "aleksailic/opna_1", "max_stars_repo_head_hexsha": "cc01ca962b04c468ace56c71fb1c3d117f0337e5", "max_stars_repo_licenses": ["MIT"], "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": "aleksailic/opna_1", "max_issues_repo_head_hexsha": "cc01ca962b04c468ace56c71fb1c3d117f0337e5", "max_issues_repo_licenses": ["MIT"], "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": "aleksailic/opna_1", "max_forks_repo_head_hexsha": "cc01ca962b04c468ace56c71fb1c3d117f0337e5", "max_forks_repo_licenses": ["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.8846153846, "max_line_length": 144, "alphanum_fraction": 0.6021606196, "num_tokens": 5357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056167854461, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.47972798684103624}}
{"text": "#include <boost/test/unit_test.hpp>\n#include \"algorithms/dp/collect_max_gold_from_grid.hpp\"\n\nBOOST_AUTO_TEST_SUITE(TestCollectMaxGold)\n\n    BOOST_AUTO_TEST_CASE(test_input) {\n        {\n            const int expected = 24;\n            const std::vector<std::vector<int>> grid = {\n                {0, 6, 0},\n                {5, 8, 7},\n                {0, 9, 0}\n            };\n\n            Algo::DP::CollectMaxGold collector;\n            BOOST_CHECK(expected == collector.getMaximumGold(grid));\n        }\n\n        {\n            const int expected = 60;\n            const std::vector<std::vector<int>> grid = {\n                {1,0,7,0,0,0},\n                {2,0,6,0,1,0},\n                {3,5,6,7,4,2},\n                {4,3,1,0,2,0},\n                {3,0,5,0,20,0}\n            };\n\n            Algo::DP::CollectMaxGold collector;\n            BOOST_CHECK(expected == collector.getMaximumGold(grid));\n        }\n    }\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "48291e0a3f909bbe7344684002936769245c0b12", "size": 940, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/algorithms/dp/test_collect_max_gold_from_grid.cpp", "max_stars_repo_name": "iamantony/CppNotes", "max_stars_repo_head_hexsha": "2707db6560ad80b0e5e286a04b2d46e5c0280b3f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-07-31T14:13:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-03T09:51:43.000Z", "max_issues_repo_path": "test/algorithms/dp/test_collect_max_gold_from_grid.cpp", "max_issues_repo_name": "iamantony/CppNotes", "max_issues_repo_head_hexsha": "2707db6560ad80b0e5e286a04b2d46e5c0280b3f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 28.0, "max_issues_repo_issues_event_min_datetime": "2015-09-22T07:38:21.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-02T11:00:58.000Z", "max_forks_repo_path": "test/algorithms/dp/test_collect_max_gold_from_grid.cpp", "max_forks_repo_name": "iamantony/CppNotes", "max_forks_repo_head_hexsha": "2707db6560ad80b0e5e286a04b2d46e5c0280b3f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-10-11T14:10:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-27T08:53:50.000Z", "avg_line_length": 26.8571428571, "max_line_length": 68, "alphanum_fraction": 0.485106383, "num_tokens": 246, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056040203136, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.4797279779570359}}
{"text": "//==================================================================================================\n/*!\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#include <boost/simd/constant/sqrteps.hpp>\n#include <boost/simd/constant/eps.hpp>\n#include <boost/simd/as.hpp>\n#include <scalar_test.hpp>\n\nSTF_CASE_TPL( \"Check sqrteps behavior for integral types\"\n            , (std::uint8_t)(std::uint16_t)(std::uint32_t)(std::uint64_t)\n              (std::int8_t)(std::int16_t)(std::int32_t)(std::int64_t)\n            )\n{\n  using boost::simd::as;\n  using boost::simd::detail::sqrteps;\n  using boost::simd::Sqrteps;\n\n  STF_TYPE_IS(decltype(Sqrteps<T>()), T);\n  STF_EQUAL(Sqrteps<T>(), T(1));\n  STF_EQUAL(sqrteps( as(T{}) ),T(1));\n}\n\nSTF_CASE_TPL( \"Check sqrteps behavior for floating types\"\n            , (double)(float)\n            )\n{\n  using boost::simd::as;\n  using boost::simd::detail::sqrteps;\n  using boost::simd::Sqrteps;\n  using boost::simd::Eps;\n\n  STF_TYPE_IS(decltype(Sqrteps<T>()), T);\n  auto z1 = Sqrteps<T>();\n  STF_ULP_EQUAL(z1*z1, Eps<T>(), 0.5);\n  auto z2 = sqrteps( as(T{}) );\n  STF_ULP_EQUAL(z2*z2, Eps<T>(), 0.5);\n\n}\n", "meta": {"hexsha": "ca394ca59c1237aebf54aa243d2a9eb9f6f3c5bd", "size": 1355, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/constant/scalar/sqrteps.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": "test/constant/scalar/sqrteps.cpp", "max_issues_repo_name": "remymuller/boost.simd", "max_issues_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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/constant/scalar/sqrteps.cpp", "max_forks_repo_name": "remymuller/boost.simd", "max_forks_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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.1111111111, "max_line_length": 100, "alphanum_fraction": 0.5505535055, "num_tokens": 391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056167854461, "lm_q2_score": 0.6959583124210896, "lm_q1q2_score": 0.4797279738003774}}
{"text": "#include <iostream>\n#include <sys/time.h>\n#include <Eigen/Core>\n#include <fstream>\n#include <cmath>\n\n#include \"celerite/celerite.h\"\n#include \"celerite/carma.h\"\n#include \"celerite/utils.h\"\n#include \"../include/KF.h\"\n#include \"../include/ndsho.h\"\n#include \"../include/dsho.h\"\n\n\nusing namespace Eigen;\nusing namespace std;\n#define TWOPI 6.283185307179586\n\n// This program benchmarks a single DSHO using celerite and gpstate\n\n// Timer for the benchmark.\ndouble get_timestamp ()\n{\n  struct timeval now;\n  gettimeofday (&now, NULL);\n  return double(now.tv_usec) * 1.0e-6 + double(now.tv_sec);\n}\n\n// Function to read a whitespace separated file\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\n\n\nint main ()\n{\n\n  //std::vector<double> values = load_csv(\"two_comp_dsho.txt\");\n  std::vector<double> values = load_csv(\"GPtest_dsin.txt\");\n\n\n  VectorXd times = Map<VectorXd, 0, InnerStride<2> > (values.data(), 10000);\n  VectorXd yi = Map<VectorXd, 0, InnerStride<2> > (values.data()+1, 10000);\n  VectorXd yierr = VectorXd::Ones(yi.size());\n  yierr *= 0.05;\n  VectorXd diagi = yierr.array()*yierr.array();\n\n\n\n  //set up the single DSHO parameters we use as a base\n  double omega0 = TWOPI;\n  double Q = 1000000.0;\n  double varf = 0.05 * 0.05;\n\n\n  Eigen::VectorXd alpha_real, beta_real;\n\n  size_t N = 2;\n  Eigen::VectorXd omega0_arr(N), Q_arr(N), varf_arr(N);\n  Eigen::VectorXd alpha_complex_real_arr(N), alpha_complex_imag_arr(N), beta_complex_real_arr(N), beta_complex_imag_arr(N);\n  double log_likelihood=0.0, celerite_ll=0.0, exact_likelihood=0.0;\n\n  int nterms = 3;\n\n  for (size_t i=0; i<N; i++)\n  {\n    if (i == 0)\n    {\n      omega0_arr(i) = omega0;\n    }\n    else\n    {\n      omega0_arr(i) = omega0 + static_cast<double>(i);\n    }\n    Q_arr(i) = Q;\n    varf_arr(i) = varf;\n    Eigen::VectorXd carma_arparams(nterms);\n    Eigen::VectorXd carma_maparams(nterms-1);\n    carma_arparams << omega0_arr(i)*omega0_arr(i), omega0_arr(i)/Q, 1.0;\n    carma_maparams << 1.0, 0.0;\n\n    double temp = std::sqrt(4.0*Q_arr(i)*Q_arr(i) - 1.0);\n    //double S0 = varf_arr(i)* std::pow(Q_arr(i),-2) * std::sqrt(M_PI) / std::sqrt(2);\n    double S0 = varf_arr(i)* std::pow(omega0_arr(i),-4) * std::sqrt(M_PI) / std::sqrt(2);\n    alpha_complex_real_arr(i) = S0 * omega0_arr(i) * Q_arr(i);\n    alpha_complex_imag_arr(i) = S0 * omega0_arr(i) * Q_arr(i) / temp;\n    beta_complex_real_arr(i) = 0.5 * omega0_arr(i) / Q_arr(i);\n    beta_complex_imag_arr(i) = 0.5 * temp * omega0_arr(i) / Q_arr(i);\n  }\n\n\n  celerite::solver::CholeskySolver<double> solver;\n\n  solver.compute(0.0, alpha_real, beta_real, alpha_complex_real_arr, alpha_complex_imag_arr, beta_complex_real_arr, beta_complex_imag_arr, times, diagi);\n  celerite_ll = -0.5*(solver.dot_solve(yi) + solver.log_determinant() + times.rows() * log(2.0 * M_PI));\n\n  gpstate::n_dsho::N_DSHOSolver ndsho(times,yi,yierr,omega0_arr, Q_arr, varf_arr);\n  log_likelihood = ndsho.KF_log_likelihood();\n\n  // Calculate known likelihood\n  for (size_t k=0; k<times.size(); k++)\n  {\n      double delta2 = (yi(k)-sin(omega0_arr(0)*times(double(k))) - sin(omega0_arr(1)*times(double(k)))) / 0.05;\n      //double delta2 = 0.0;\n      exact_likelihood += ( (-0.5*log(TWOPI*0.05*0.05)) - 0.5*delta2*delta2 );\n  }\n  // Print the results.\n  std::cout << N;\n  std::cout << \" \";\n  std::cout << celerite_ll;\n  std::cout << \" \";\n  std::cout << log_likelihood;\n  std::cout << \" \";\n  std::cout << exact_likelihood;\n  std::cout << \" \";\n  std::cout << \"\\n\";\n\n}\n", "meta": {"hexsha": "8d21ff74192bca06fa26bb2d6249afd94b41eb5d", "size": 3894, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test_logl_dsin.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/test_logl_dsin.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/test_logl_dsin.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": 29.0597014925, "max_line_length": 153, "alphanum_fraction": 0.645865434, "num_tokens": 1240, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152498, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.47972054231644035}}
{"text": "\n//\n// Created by david on 2019-05-27.\n//\n\n#include <complex.h>\n#undef I\n\n#include <Eigen/QR>\n#include <Eigen/SVD>\n#include <general/class_tic_toc.h>\n#include <math/svd.h>\n\n//\n// Created by david on 2021-03-26.\n//\n/*! \\brief Performs SVD on a matrix\n *  This function is defined in cpp to avoid long compilation times when having Eigen::BDCSVD included everywhere in headers.\n *  Performs rigorous checks to ensure stability of DMRG.\n *  In some cases Eigen::BCDSVD/JacobiSVD will fail with segfault. Here we use a patched version of Eigen that throws an error\n *  instead so we get a chance to catch it and use lapack svd instead.\n *   \\param mat_ptr Pointer to the matrix. Supported are double * and std::complex<double> *\n *   \\param rows Rows of the matrix\n *   \\param cols Columns of the matrix\n *   \\param rank_max Maximum number of singular values\n *   \\return The U, S, and V matrices (with S as a vector) extracted from the Eigen::BCDSVD SVD object.\n */\ntemplate<typename Scalar>\nstd::tuple<svd::solver::MatrixType<Scalar>, svd::solver::VectorType<Scalar>, svd::solver::MatrixType<Scalar>, long>\n    svd::solver::do_svd_eigen(const Scalar *mat_ptr, long rows, long cols, std::optional<long> rank_max) {\n    if(not rank_max.has_value()) rank_max = std::min(rows, cols);\n\n    svd::log->trace(\"Starting SVD with Eigen\");\n    Eigen::Map<const MatrixType<Scalar>> mat(mat_ptr, rows, cols);\n\n    if(rows <= 0) throw std::runtime_error(fmt::format(\"SVD error: rows = {}\", rows));\n    if(cols <= 0) throw std::runtime_error(fmt::format(\"SVD error: cols = {}\", cols));\n\n#ifndef NDEBUG\n    // These are more expensive debugging operations\n    if(not mat.allFinite()) throw std::runtime_error(\"SVD error: matrix has inf's or nan's\");\n    if(mat.isZero(0)) throw std::runtime_error(\"SVD error: matrix is all zeros\");\n    if(mat.isZero(1e-12)) svd::log->warn(\"Lapacke SVD Warning\\n\\t Given matrix elements are all close to zero (prec 1e-12)\");\n#endif\n\n    Eigen::BDCSVD<MatrixType<Scalar>> SVD;\n\n    // Setup the SVD solver\n    SVD.setSwitchSize(static_cast<int>(switchsize));\n    SVD.setThreshold(threshold);\n    bool use_jacobi = std::min(rows, cols) < static_cast<long>(switchsize);\n    svd::log->trace(\"Running SVD with threshold {:.4e} | switchsize {} | size {}\", threshold, switchsize, rank_max.value());\n    if(use_jacobi) {\n        // We only use Jacobi for precision. So we use all the precision we can get.\n        svd::log->debug(\"Running Eigen::JacobiSVD threshold {:.4e} | switchsize {} | rank_max {}\", threshold, switchsize, rank_max.value());\n        // Run the svd\n        t_jac->tic();\n        SVD.compute(mat, Eigen::ComputeFullU | Eigen::ComputeFullV | Eigen::FullPivHouseholderQRPreconditioner);\n        t_jac->toc();\n    } else {\n        svd::log->debug(\"Running Eigen::BDCSVD threshold {:.4e} | switchsize {} | rank_max {}\", threshold, switchsize, rank_max.value());\n        // Run the svd\n        t_svd->tic();\n        SVD.compute(mat, Eigen::ComputeThinU | Eigen::ComputeThinV);\n        t_svd->toc();\n    }\n    if(count) count.value()++;\n    long max_size = std::min(SVD.singularValues().size(), rank_max.value());\n    long rank     = (SVD.singularValues().head(max_size).array() >= threshold).count();\n    svd::log->trace(\"Truncating singular values\");\n    if(rank == SVD.singularValues().size()) {\n        truncation_error = 0;\n    } else {\n        truncation_error = SVD.singularValues().tail(SVD.singularValues().size() - rank).norm();\n    }\n\n    if(SVD.rank() <= 0 or rank == 0 or not SVD.matrixU().leftCols(rank).allFinite() or not SVD.singularValues().head(rank).allFinite() or\n       not SVD.matrixV().leftCols(rank).allFinite()) {\n        throw std::runtime_error(fmt::format(FMT_COMPILE(\"Eigen SVD error \\n\"\n                                                         \"  svd_threshold    = {:.4e}\\n\"\n                                                         \"  Truncation Error = {:.4e}\\n\"\n                                                         \"  Rank             = {}\\n\"\n                                                         \"  Dims             = ({}, {})\\n\"\n                                                         \"  A all finite     : {}\\n\"\n                                                         \"  U all finite     : {}\\n\"\n                                                         \"  S all finite     : {}\\n\"\n                                                         \"  V all finite     : {}\\n\"),\n                                             threshold, truncation_error, rank, rows, cols, mat.allFinite(), SVD.matrixU().leftCols(rank).allFinite(),\n                                             SVD.singularValues().head(rank).allFinite(), SVD.matrixV().leftCols(rank).allFinite()));\n    }\n    svd::log->trace(\"SVD with Eigen finished successfully\");\n\n    return std::make_tuple(SVD.matrixU().leftCols(rank), SVD.singularValues().head(rank), SVD.matrixV().leftCols(rank).adjoint(), rank);\n}\n\n//! \\relates svd::class_SVD\n//! \\brief force instantiation of do_svd for type 'double'\ntemplate std::tuple<svd::solver::MatrixType<double>, svd::solver::VectorType<double>, svd::solver::MatrixType<double>, long>\n    svd::solver::do_svd_eigen(const double *, long, long, std::optional<long>);\n\nusing cplx = std::complex<double>;\n//! \\relates svd::class_SVD\n//! \\brief force instantiation of do_svd for type 'std::complex<double>'\ntemplate std::tuple<svd::solver::MatrixType<cplx>, svd::solver::VectorType<cplx>, svd::solver::MatrixType<cplx>, long>\n    svd::solver::do_svd_eigen(const cplx *, long, long, std::optional<long>);", "meta": {"hexsha": "b5e1853d982f460630937241dad08d8239f09987", "size": 5552, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/math/svd/svd_eigen.cpp", "max_stars_repo_name": "DavidAce/DMRG", "max_stars_repo_head_hexsha": "e465fd903eade1bf6aa74daacd8e2cf02e9e9332", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2017-10-31T22:50:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T15:45:27.000Z", "max_issues_repo_path": "source/math/svd/svd_eigen.cpp", "max_issues_repo_name": "DavidAce/DMRG", "max_issues_repo_head_hexsha": "e465fd903eade1bf6aa74daacd8e2cf02e9e9332", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/math/svd/svd_eigen.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": 52.8761904762, "max_line_length": 150, "alphanum_fraction": 0.6030259366, "num_tokens": 1408, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4797205371665475}}
{"text": "/**\n\nCopyright (c) 2016, Aumann Florian, Borella Jocelyn, Heller Florian, Mei\u00dfner Pascal, Schleicher Ralf, St\u00f6ckle 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#define BOOST_TEST_STATIC_LINK\n\n#include <boost/test/included/unit_test.hpp>\n#include \"next_best_view/test_cases/BaseTest.h\"\n\nusing namespace next_best_view;\nusing namespace boost::unit_test;\n\nclass MathTest : public BaseTest {\npublic:\n    MathTest() : BaseTest(false, true) {}\n\n    virtual ~MathTest() {}\n\n    /*!\n     * \\brief evaluates the correctness of the Sphere To Cartesian and Cartesian To Sphere Methods.\n     */\n    void evaluateS2CandC2S() {\n        ROS_INFO(\"Running Test for S2C and C2S\");\n\n        // tolerance\n        double tolerance = 2E-7;\n\n        // Unit Sphere Tests\n        int thetaDivisor = 32;\n        double thetaStepSize = M_PI / (double) thetaDivisor;\n        int phiDivisor = 64;\n        double phiStepSize = M_2_PI / (double) phiDivisor;\n        for (int thetaFac = 0; thetaFac < thetaDivisor; thetaFac++) {\n            double theta = - M_PI_2 + thetaFac * thetaStepSize;\n            for (int phiFac = 0; phiFac < phiDivisor; phiFac++) {\n                double phi = - M_PI + phiFac * phiStepSize;\n\n                // create coordinates\n                SimpleSphereCoordinates scoords(1, theta, phi);\n                // convert to cartesian\n                SimpleVector3 ccoords = MathHelper::convertS2C(scoords);\n                // convert to sphere again\n                SimpleSphereCoordinates rescoords = MathHelper::convertC2S(ccoords);\n                // convert to cartesian again\n                SimpleVector3 reccoords = MathHelper::convertS2C(rescoords);\n\n                double cerror = (ccoords - reccoords).lpNorm<2>();\n\n                BOOST_CHECK_MESSAGE(cerror < tolerance, \"error has to be minimal.\");\n            }\n        }\n    }\n\n    void iterationTest() {\n      evaluateS2CandC2S();\n    }\n};\n\ntest_suite* init_unit_test_suite( int argc, char* argv[] ) {\n    test_suite* evaluation = BOOST_TEST_SUITE(\"Evaluation NBV\");\n\n    boost::shared_ptr<MathTest> testPtr(new MathTest());\n\n    evaluation->add(BOOST_CLASS_TEST_CASE(&MathTest::iterationTest, testPtr));\n\n    framework::master_test_suite().add(evaluation);\n\n    return 0;\n}\n", "meta": {"hexsha": "771273d198a72c955760f301b76b15ec0d2cfd2a", "size": 3851, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test_cases/MathTest.cpp", "max_stars_repo_name": "Tobi2001/asr_next_best_view", "max_stars_repo_head_hexsha": "7dace46b903d15e218a39f994802288103818f48", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2019-12-10T07:39:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T11:40:02.000Z", "max_issues_repo_path": "src/test_cases/MathTest.cpp", "max_issues_repo_name": "Tobi2001/asr_next_best_view", "max_issues_repo_head_hexsha": "7dace46b903d15e218a39f994802288103818f48", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/test_cases/MathTest.cpp", "max_forks_repo_name": "Tobi2001/asr_next_best_view", "max_forks_repo_head_hexsha": "7dace46b903d15e218a39f994802288103818f48", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-01-13T17:41:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T11:40:04.000Z", "avg_line_length": 45.3058823529, "max_line_length": 755, "alphanum_fraction": 0.7115035056, "num_tokens": 843, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4797205371665475}}
{"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_ASEC_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_ASEC_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 inverse secant in radian: \\f$\\arccos(1/x)\\f$.\n\n    @par Header <boost/simd/function/asec.hpp>\n\n    @see asecd, asecpi\n\n    @par Example:\n\n      @snippet asec.cpp asec\n\n    @par Possible output:\n\n      @snippet asec.txt asec\n\n  **/\n  IEEEValue asec(IEEEValue const & x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/asec.hpp>\n#include <boost/simd/function/simd/asec.hpp>\n\n#endif\n", "meta": {"hexsha": "d75a6f12dbfd52afb4695ec51808a16479592879", "size": 1007, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/asec.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/asec.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/asec.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 23.4186046512, "max_line_length": 100, "alphanum_fraction": 0.5719960278, "num_tokens": 228, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118222, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4797205320166545}}
{"text": "#include <iostream>\n#include <fstream>\n#include <list>\n#include <vector>\n#include <chrono>\n#include <ctime>\n#include <climits>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n#include <opencv2/core/core.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/features2d/features2d.hpp>\n\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/dense/linear_solver_dense.h>\n#include <g2o/core/robust_kernel.h>\n#include <g2o/types/sba/types_six_dof_expsmap.h>\n\n\nstruct  \n{\n    Eigen::Vector3d pose_world;\n    float grayscale;\n    Measurement(Eigen::Vector3d p, float g) : \n};\n\nEigen::Vector project2Dto3D(int x , int y, int d, float fx, float fy, float cx, float cy, float scale){\n    float zz = float(d) / scale;\n    float xx = zz * (x - cx) / fx;\n    float yy = zz * (y - cy ) / fy;\n    return Eigen::Vector3d(xx, yy, zz);\n}\n\nEigen::Vector2d project3Dto2D(float x, float y, float z, float fx, float fy, float cx, float cy){\n    float u = fx*x/z + cx;\n    float v = fy*y/z + cy;\n    return Eigen::Vector2d(u, v);\n}\n\nclass EdgeSE3ProjectUVDirect: public: BaseUnaryEdge<1, doublem VertexSE3Expmap>{\n    private: \n        Eigen::Vector3d x_world_;\n        float cx_ = 0, cy_ = 0, fx_ = 0, fy_ = 0;\n        Mat* image_ = nullptr;\n    \n    protected: \n    float getPixelValue(float x, float y){\n        uchar* data = & data[int(y) * issmage_->step + int(x)];\n        float xx = x - floor(x);\n        float yy = y - floor(y);\n        return float (\n                   ( 1-xx ) * ( 1-yy ) * data[0] +\n                   xx* ( 1-yy ) * data[1] +\n                   ( 1-xx ) *yy*data[ image_->step ] +\n                   xx*yy*data[image_->step+1]);\n    }\n    public: \n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n    EdgeSE3ProjectUVDirect(Eigen::Vector3d point, float fx, float fy, float cx, float cy, Mat *img):\n                x_world_ ( point ), fx_ ( fx ), fy_ ( fy ), cx_ ( cx ), cy_ ( cy ), image_ ( image ) {}\n\n    virtual void computeError(){\n        const VertexSE3Expmap *v = static_cast<const VertexSE3Expmap*> (_vertices[0]);\n        Eigen::Vector3d x_local = v->estimate().map(x_world_);\n        float x = x_local[0]*fx_/x_local[2] + cx_;\n        float y = x_local[1] * fy_/x_local[2] + cy_; \n\n        if (x-4 < 0 || x + 4 > image_->cols || y-4 < 0 || y + 4 > image_->rows) {\n            _error (0, 0) = 0.0; \n            this->setLevel(1);\n        }\n        else{\n            _error(0, 0) = getPixelValue(x, y) - _measurement;\n        }\n    }\n\n    virtual void linearOplus(){\n        if(level() = 1){\n            _jacobianOplusXi = Eigen:Matrix<double, 1, 6>::Zero();\n            return;\n        }\n\n        VertexSE3Expmap* vtx = static_cast<VertexSE3Expmap*> (_vertices[0]);\n        Eigen::Vector3d xyz_trans = vtx->estimate().map(x_world_);\n\n        double x = xyz_trans[0];\n        double y = xyz_trans[1];\n\n        double invz = 1.0 / xyz_trans[2];\n        double invz_2 = invz*invz;\n\n        float u = x*fx_*invz + cx_;\n        float v = y*fy_*invz + cy_;\n\n        // Jacobian from SE3 to uv, the matrix is (2, 6)\n        // In g2o, the Lie algebra is translation in first three \n        Eigen::Matrix<double, 2, 6> jacobian_uv_ksai;\n\n        jacobian_uv_ksai ( 0,0 ) = - x*y*invz_2 *fx_;\n        jacobian_uv_ksai ( 0,1 ) = ( 1+ ( x*x*invz_2 ) ) *fx_;\n        jacobian_uv_ksai ( 0,2 ) = - y*invz *fx_;\n        jacobian_uv_ksai ( 0,3 ) = invz *fx_;\n        jacobian_uv_ksai ( 0,4 ) = 0;\n        jacobian_uv_ksai ( 0,5 ) = -x*invz_2 *fx_;\n\n        jacobian_uv_ksai ( 1,0 ) = - ( 1+y*y*invz_2 ) *fy_;\n        jacobian_uv_ksai ( 1,1 ) = x*y*invz_2 *fy_;\n        jacobian_uv_ksai ( 1,2 ) = x*invz *fy_;\n        jacobian_uv_ksai ( 1,3 ) = 0;\n        jacobian_uv_ksai ( 1,4 ) = invz *fy_;\n        jacobian_uv_ksai ( 1,5 ) = -y*invz_2 *fy_;\n\n        Eigen::Matrix<double, 1, 2> jacobian_pixel_uv;\n        // simple image gradient \n        jacobian_pixel_uv ( 0,0 ) = ( getPixelValue ( u+1,v )-getPixelValue ( u-1,v ) ) /2;\n        jacobian_pixel_uv ( 0,1 ) = ( getPixelValue ( u,v+1 )-getPixelValue ( u,v-1 ) ) /2;\n\n        _jacobianOplusXi = jacobian_pixel_uv*jacobian_uv_ksai;\n\n    }\n}\n\nbool poseEstimationDirect( const vector<Measurement> & measurements, Mat& gray; Eigen::Matrix3f &K, Eigen::Isometry3d &Tcw){\n    typedef g2o::BlockSolver<g2o::BlockSolverTraits<6,1>> DirectBlock;\n    DirectBlock::LinearSolverType* linearSolver = new g2o::LinearSolverDense<DirectBlock::PoseMatrixType>();\n    DirectBlock *solver_ptr = new DirectBlock(linearSolver);\n\n    g2o::OptimizationAlgorithmLevenberg* solver = new g2o::OptimizationAlgorithmLevenberg(solver_ptr);\n    g2o::SparseOptimizer optimizer;\n    optimizer.setAlgorithm(solver);\n    optimizer.setVerbose(true);\n<<<<<<< HEAD\n\n=======\n    \n>>>>>>> d3aa7eab7a66633ee6b6716534884a999f4bfb7a\n    g2o::VertexSE3Expmap* pose = new g2o::VertexSE3Expmap();\n    pose->setEstimate(g2o::SE3Quat(Tcw.rotation(), Tcw.translation()));\n    pose->setId(0);\n    optimizer.addVertex(pose);\n\n    int id = 1;\n    for ( Measurement mm: measurements){\n        EdgeSE3ProjectUVDirect* edge = new EdgeSE3ProjectUVDirect(\n            mm.pose_world, \n            K(0,0), K(1,1), K(0,2), K(1,2), gray\n        );\n        edge->setVertex(0, pose);\n        edge->setMeasurement(mm.grayscale);       //based on our assumption of garyscale consistency\n        edge->setInformation(Eigen::Matrix<double, 1,1>::Identity());\n        edge->setId(id++);\n        optimizer.addEdge(edge);\n    }\n\n    cout << \"edge number in a graph: \" << optimizer.edges().size() << endl;\n    optimizer.initializeOptimization();\n    optimizer.optimize(30);\n    Tcw = pose->estimate();\n}\n\nint main(int argc, char** argv){\n    if ( argc != 2 )\n    {\n        cout<<\"usage: useLK path_to_dataset\"<<endl;\n        return 1;\n    }\n    srand ( ( unsigned int ) time ( 0 ) );\n    string path_to_dataset = argv[1];\n    string associate_file = path_to_dataset + \"/associate.txt\";\n\n    ifstream fin ( associate_file );\n\n    string rgb_file, depth_file, time_rgb, time_depth;\n    cv::Mat color, depth, gray;\n    vector<Measurement> measurements;\n    // Camera intrinstic parameters\n    float cx = 325.5;\n    float cy = 253.5;\n    float fx = 518.0;\n    float fy = 519.0;\n    float depth_scale = 1000.0;\n    Eigen::Matrix3f K;\n    K<<fx,0.f,cx,0.f,fy,cy,0.f,0.f,1.0f;\n\n    Eigen::Isometry3d Tcw = Eigen::Isometry3d::Identity();\n\n    cv::Mat prev_color;\n    for(int index = 0; index<10;index++){\n        fin>> time_rgb >> rgb_file >> time_depth >> depth_file;\n        color = cv::imread(path_to_dataset+\"/\"+rgb_file);\n        depth = imread(path_to_dataset + \"/\" + depth_file, -1);\n        if(color.data == nullptr || depth.data == nullptr) continue;\n\n        cvtColor(color, gray, cv::COLOR_BGR2GRAY);\n\n        if(index == 0){\n            vector<cv::KeyPoint> keypoints;\n            cv::Ptr<cv::FastFeatureDetector> detector = cv::FastFeatureDetector::create();\n            detector->detect(color, keypoints);\n            for (auto kp: keypoints){\n               if ( kp.pt.x < 20 || kp.pt.y < 20 || ( kp.pt.x+20 ) >color.cols || ( kp.pt.y+20 ) >color.rows )\n                    continue;\n                ushort d = depth.ptr<ushort> ( cvRound ( kp.pt.y ) ) [ cvRound ( kp.pt.x ) ];\n                if ( d==0 )\n                    continue;\n                Eigen::Vector3d p3d = project2Dto3D ( kp.pt.x, kp.pt.y, d, fx, fy, cx, cy, depth_scale );\n                float grayscale = float ( gray.ptr<uchar> ( cvRound ( kp.pt.y ) ) [ cvRound ( kp.pt.x ) ] );\n                measurements.push_back ( Measurement ( p3d, grayscale ) );\n            }\n            prev_color = color.clone();\n            continue;\n        }\n        // \u4f7f\u7528\u76f4\u63a5\u6cd5\u8ba1\u7b97\u76f8\u673a\u8fd0\u52a8\n        chrono::steady_clock::time_point t1 = chrono::steady_clock::now();\n        poseEstimationDirect ( measurements, &gray, K, Tcw );\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<<\"direct method costs time: \"<<time_used.count() <<\" seconds.\"<<endl;\n        cout<<\"Tcw=\"<<Tcw.matrix() <<endl;\n\n        // plot the feature points\n        cv::Mat img_show ( color.rows*2, color.cols, CV_8UC3 );\n        prev_color.copyTo ( img_show ( cv::Rect ( 0,0,color.cols, color.rows ) ) );\n        color.copyTo ( img_show ( cv::Rect ( 0,color.rows,color.cols, color.rows ) ) );\n        for ( Measurement m:measurements )\n        {\n            if ( rand() > RAND_MAX/5 )\n                continue;\n            Eigen::Vector3d p = m.pos_world;\n            Eigen::Vector2d pixel_prev = project3Dto2D ( p ( 0,0 ), p ( 1,0 ), p ( 2,0 ), fx, fy, cx, cy );\n            Eigen::Vector3d p2 = Tcw*m.pos_world;\n            Eigen::Vector2d pixel_now = project3Dto2D ( p2 ( 0,0 ), p2 ( 1,0 ), p2 ( 2,0 ), fx, fy, cx, cy );\n            if ( pixel_now(0,0)<0 || pixel_now(0,0)>=color.cols || pixel_now(1,0)<0 || pixel_now(1,0)>=color.rows )\n                continue;\n\n            float b = 255*float ( rand() ) /RAND_MAX;\n            float g = 255*float ( rand() ) /RAND_MAX;\n            float r = 255*float ( rand() ) /RAND_MAX;\n            cv::circle ( img_show, cv::Point2d ( pixel_prev ( 0,0 ), pixel_prev ( 1,0 ) ), 8, cv::Scalar ( b,g,r ), 2 );\n            cv::circle ( img_show, cv::Point2d ( pixel_now ( 0,0 ), pixel_now ( 1,0 ) +color.rows ), 8, cv::Scalar ( b,g,r ), 2 );\n            cv::line ( img_show, cv::Point2d ( pixel_prev ( 0,0 ), pixel_prev ( 1,0 ) ), cv::Point2d ( pixel_now ( 0,0 ), pixel_now ( 1,0 ) +color.rows ), cv::Scalar ( b,g,r ), 1 );\n        }\n        cv::imshow ( \"result\", img_show );\n        cv::waitKey ( 0 );\n\n    }\n    return 0;\n    }\n}\n", "meta": {"hexsha": "1029f2e238339187d6e185b60043d6859e8200d6", "size": 9745, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "front_end/g2o_direct_sparse_BACKUP_27894.cpp", "max_stars_repo_name": "shen338/MySLAM", "max_stars_repo_head_hexsha": "a59f09c0f5bb9f3fa3904e946f4c94b280c3faeb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "front_end/g2o_direct_sparse_BACKUP_27894.cpp", "max_issues_repo_name": "shen338/MySLAM", "max_issues_repo_head_hexsha": "a59f09c0f5bb9f3fa3904e946f4c94b280c3faeb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "front_end/g2o_direct_sparse_BACKUP_27894.cpp", "max_forks_repo_name": "shen338/MySLAM", "max_forks_repo_head_hexsha": "a59f09c0f5bb9f3fa3904e946f4c94b280c3faeb", "max_forks_repo_licenses": ["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.2156862745, "max_line_length": 181, "alphanum_fraction": 0.5795792714, "num_tokens": 2975, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933183101078, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4797205268667613}}
{"text": "/*\n neighbours.cxx\n\n Copyright (c) 2018 Guy Skinner\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 <boost/numeric/ublas/matrix_proxy.hpp>\n\n#include \"neighbour.hxx\"\n#include \"utils.hxx\"\n\nNeighbour::Neighbour(unsigned long nbas,\n                     ublas::matrix<double> plat,\n                     ublas::matrix<double> basis) {\n  NumberOfAtoms = nbas;\n  LatticeVectors = plat;\n  BasisVectors = basis;\n}\n\nNeighbour::~Neighbour() {\n}\n\nvoid Neighbour::SetInverseLattice(ublas::matrix<double> iplat,\n                                  ublas::matrix<double> xbasis) {\n  InverseLatticeVectors = iplat;\n  InverseBasisVectors = xbasis;\n}\n\nvoid Neighbour::GetSiteList(double rmax) {\n\n  /* Create Site List */\n  ublas::vector<long> rcut(3);\n  ublas::vector<long> sext(3);\n  \n  for (auto i = 0; i < 3; i++) {\n    ublas::matrix_row<ublas::matrix<double>> p(LatticeVectors,i);\n    rcut(i) = static_cast<long>(rmax/ublas::norm_2(p)+2);\n    sext(i) = 2*rcut(i) + 1;\n  }\n  \n  SupercellExtension = sext;\n  /* Linked-List Block Size */\n  Neighbour::LinkedListBlocks(rmax);\n  \n  ublas::vector<double> cent(3);\n  for (auto i = 0; i < 3; i++) cent(i) = 0.5*(sext(i) - 1);\n  Centre = cent;\n  \n  //long product = boost::accumulate(sext,1,std::multiplies<long>());\n  long smax = NumberOfAtoms*product(sext);\n  long blks = boost::accumulate(Blocks,1,std::multiplies<long>());\n  \n  ublas::matrix<double> sites(smax,3);\n  ublas::vector<long> basptr(smax);\n  ublas::vector<long> linkl(smax);\n  ublas::vector<long> head(blks);\n  ublas::vector<double> sitex(3);\n\n  /* Make Sure Zero Vectors */\n  head.clear();\n  linkl.clear();\n  \n  ublas::matrix_row<ublas::matrix<double>> p0(LatticeVectors,0);\n  ublas::matrix_row<ublas::matrix<double>> p1(LatticeVectors,1);\n  ublas::matrix_row<ublas::matrix<double>> p2(LatticeVectors,2);\n  \n  long icnt = 0;\n  for (auto i = 0; i < NumberOfAtoms; i++) {\n    ublas::matrix_row<ublas::matrix<double>> b(BasisVectors,i);\n    ublas::matrix_row<ublas::matrix<double>> xb(InverseBasisVectors,i);\n    for (auto j = -rcut(0); j <= rcut(0); j++) {\n      for (auto k = -rcut(1); k <= rcut(1); k++) {\n        for (auto l = -rcut(2); l <= rcut(2); l++) {\n          for (auto a = 0; a < 3; a++) {\n            sites(icnt,a) = b(a) + j*p0(a) + k*p1(a) + l*p2(a);\n            sitex(a) = xb(a);\n          }\n          basptr(icnt) = i;\n          sitex(0) += static_cast<double>(j);\n          sitex(1) += static_cast<double>(k);\n          sitex(2) += static_cast<double>(l);\n          unsigned long icell = FindCell(sitex);\n          linkl(icnt) = head(icell);\n          head(icell) = icnt;\n          icnt++;\n        }\n      }\n    }\n  }\n\n  Sites = sites;\n  BasisPointers = basptr;\n  Head = head;\n  LinkedList = linkl;\n  \n}\n\nvoid Neighbour::LinkedListBlocks(double rmax) {\n\n  /* Decompose Lattice Vector Matrix into Lattice Vectors */\n  ublas::matrix_row<ublas::matrix<double>> p1(LatticeVectors,0);\n  ublas::matrix_row<ublas::matrix<double>> p2(LatticeVectors,1);\n  ublas::matrix_row<ublas::matrix<double>> p3(LatticeVectors,2);\n\n  /* Cross Product of Lattice Vectors */\n  ublas::vector<double> c1 = cross3(p2,p3);\n  ublas::vector<double> c2 = cross3(p3,p1);\n  ublas::vector<double> c3 = cross3(p1,p2);\n\n  ublas::vector<double> w(3);\n  w(0) = ublas::inner_prod(p1,c1)/ublas::norm_2(c1);\n  w(1) = ublas::inner_prod(p2,c2)/ublas::norm_2(c2);\n  w(2) = ublas::inner_prod(p3,c3)/ublas::norm_2(c3);\n\n  ublas::vector<long> blks(3);\n  for (auto i = 0; i < 3; i++) {\n    blks(i) = static_cast<long>(SupercellExtension(i)*w(i)/rmax);\n    if (blks(i) < 3) blks(i) = 3;\n  }\n\n  Blocks = blks;\n\n}\n\nvoid Neighbour::GetNhbrList(double rmax) {\n\n  /* Calculate Site List */\n  Neighbour::GetSiteList(rmax);\n\n  ublas::vector<long> tot(NumberOfAtoms);\n  ublas::vector<long> ptrs(650*NumberOfAtoms);\n  \n  unsigned long nsum = 0;\n  for (auto i = 0; i < NumberOfAtoms; i++) {\n    tot(i) = 0;\n    ublas::matrix_row<ublas::matrix<double>> b(BasisVectors,i);\n    ublas::matrix_row<ublas::matrix<double>> bx(InverseBasisVectors,i);\n    unsigned long icell = FindCell(bx);\n    for (auto imx = -1; imx <= 1; imx++) {\n      for (auto imy = -Blocks(0); imy <= Blocks(0); imy += Blocks(0)) {\n        for (auto imz = -Blocks(0)*Blocks(1);\n             imz <= Blocks(0)*Blocks(1);\n             imz += Blocks(0)*Blocks(1)) {\n          long jcell = icell + imx + imy + imz;\n          long j = Head(jcell);\n          while (j != 0) {\n            ublas::matrix_row<ublas::matrix<double>> site(Sites,j);\n            ublas::vector<double> ra = site - b;\n            double r = ublas::norm_2(ra);\n            if (r <= rmax and r > 0.0) {\n              ptrs(nsum) = j;\n              tot(i)++;\n              nsum++;\n            }\n            j = LinkedList(j);\n          }\n        }\n      }\n    }\n  }\n\n  Total = tot;\n  Pointers = ptrs;\n\n}\n\nunsigned long Neighbour::FindCell(ublas::vector<double> sitex){\n\n  /* Find Block that Atom Belongs In */\n  ublas::vector<long> ixs(3);\n  ublas::vector<double> scent = sitex + Centre;\n\n  for (auto i = 0; i < 3; i++) {\n    ixs(i) = static_cast<long>(Blocks(i)*scent(i)/SupercellExtension(i));\n    if (ixs(i) > Blocks(i)) ixs(i) = Blocks(i)-1;\n  }\n\n  unsigned long icell = ixs(0) + Blocks(0)*ixs(1) + Blocks(1)*Blocks(0)*ixs(2);\n  return icell;\n\n}\n", "meta": {"hexsha": "07de2fc933da73923f91871ec4b0a8dc1d525fb3", "size": 5381, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/neighbour.cxx", "max_stars_repo_name": "gcgs1/cxx.sqs", "max_stars_repo_head_hexsha": "6b656a2f604385cb28ad4211c4d52ed992b459ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/neighbour.cxx", "max_issues_repo_name": "gcgs1/cxx.sqs", "max_issues_repo_head_hexsha": "6b656a2f604385cb28ad4211c4d52ed992b459ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/neighbour.cxx", "max_forks_repo_name": "gcgs1/cxx.sqs", "max_forks_repo_head_hexsha": "6b656a2f604385cb28ad4211c4d52ed992b459ee", "max_forks_repo_licenses": ["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.9301075269, "max_line_length": 79, "alphanum_fraction": 0.5931982903, "num_tokens": 1721, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933183101077, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4797205268667612}}
{"text": "#include \"m_dvr.h\"\n\n#include <quartz>\n#include <boost/property_tree/ptree.hpp>\n\n#include \"src/util/ptree.h\"\n#include \"src/parse/printer.h\"\n\n#include \"src/parse/math/math_object.h\"\n#include \"src/parse/math/gaussian.h\"\n\nnamespace quartz {\n\nnamespace ptree = boost::property_tree;\n\nptree::ptree m_dvr(const ptree::ptree & input) {\n\n  const std::function<math::Gaussian<cx_double>(const ptree::ptree &)>\n      parse_initial = [](const ptree::ptree & pt) -> math::Gaussian<cx_double> {\n    return parse::gaussian(pt);\n  };\n\n  const std::function<MathObject<double>(const ptree::ptree &)>\n    parse_potential = [](const ptree::ptree & pt)\n      ->MathObject<double> {return parse::math_object(pt);};\n\n  std::vector<math::Gaussian<cx_double>> initial =\n      util::get_list(input.get_child(\"initial\"), parse_initial);\n\n  const arma::field<MathObject<double>> potentials =\n      util::get_mat_object(input.get_child(\"potential\"), parse_potential);\n\n  const arma::uvec grid =\n      arma::uvec(util::get_list<arma::uword>(input.get_child(\"grid\")));\n\n  const arma::mat range =\n      util::get_mat<double>(input.get_child(\"range\")).t();\n\n  arma::vec masses = arma::ones(grid.n_elem);\n\n  const auto steps = input.get<arma::uword>(\"steps\");\n  const auto dt = input.get<double>(\"dt\");\n\n  if (input.get_child_optional(\"mass\")) {\n    masses = arma::vec(util::get_list<double>(input.get_child(\"mass\")));\n  }\n\n  method::m_dvr::State initial_state(initial, grid, range, masses);\n  method::m_dvr::Operator op(initial_state, potentials);\n  auto wrapper =\n      math::schrotinger_wrapper<method::m_dvr::Operator,\n                                method::m_dvr::State,\n                                arma::field<MathObject<double>>>;\n\n  ptree::ptree result;\n\n  auto printer_pair = printer(input, result, initial_state);\n\n  propagate(initial_state, op, wrapper, potentials, printer_pair.first, steps,\n            dt, printer_pair.second);\n\n  return result;\n}\n\n}", "meta": {"hexsha": "86cb52dde16d6002b65f475094fbb53894eedd93", "size": 1936, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/parse/methods/m_dvr.cpp", "max_stars_repo_name": "Walter-Feng/Quartz", "max_stars_repo_head_hexsha": "f9af8cf41ec9882e109271ede3b7ad7c2a49af2b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-06-18T09:34:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-01T01:27:32.000Z", "max_issues_repo_path": "src/parse/methods/m_dvr.cpp", "max_issues_repo_name": "Walter-Feng/Quartz", "max_issues_repo_head_hexsha": "f9af8cf41ec9882e109271ede3b7ad7c2a49af2b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-02-27T04:46:41.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-17T05:26:46.000Z", "max_forks_repo_path": "src/parse/methods/m_dvr.cpp", "max_forks_repo_name": "Walter-Feng/Quartz", "max_forks_repo_head_hexsha": "f9af8cf41ec9882e109271ede3b7ad7c2a49af2b", "max_forks_repo_licenses": ["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.7846153846, "max_line_length": 80, "alphanum_fraction": 0.6725206612, "num_tokens": 496, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4797165816374775}}
{"text": "// [[Rcpp::depends(BH)]]\n\n#include <boost/multi_array.hpp>\n#include <Rcpp.h>\n#include <fstream>\n#include <iostream>\n\nusing namespace Rcpp;\nusing namespace boost;\n\n// [[Rcpp::export]]\nNumericVector cohort_sim(const List s_fp) {\n  const List s_ss = s_fp[\"ss\"];\n  const int n_year(s_ss[\"PROJ_YEARS\"]), n_sex(2), n_age(66), n_agr(9), n_cd4(7);\n  const int n_ts(10);\n  const double dt(0.1);\n\n  // Map single age indices (0=15..65=80) to age groups\n  const int a2g[n_age] = {\n    0, 0, 1, 1, 1, 2, 2, 2, 2, 2, // 15-16 = 0, 17-19 = 1, 20-24 = 2\n    3, 3, 3, 3, 3, 4, 4, 4, 4, 4, // 25-29 = 3, 30-34 = 4\n    5, 5, 5, 5, 5, 6, 6, 6, 6, 6, // 35-39 = 5, 40-44 = 6\n    7, 7, 7, 7, 7, 8, 8, 8, 8, 8, // 45-49 = 7, 50-54 = 8\n    8, 8, 8, 8, 8, 8, 8, 8, 8, 8, // 55-64 = 8\n    8, 8, 8, 8, 8, 8, 8, 8, 8, 8, // 65-74 = 8\n    8, 8, 8, 8, 8, 8};            // 75-80 = 8\n\n  multi_array_ref<double, 3> surv(REAL(s_fp[\"Sx\"]), extents[n_year][n_sex][n_age]);\n  multi_array_ref<double, 3> inci(REAL(s_fp[\"new_inf\"]), extents[n_year][n_sex][n_age]);\n  multi_array_ref<double, 3> in_dist(REAL(s_fp[\"cd4_initdist\"]), extents[n_sex][n_agr][n_cd4]);\n  multi_array_ref<double, 3> in_prog(REAL(s_fp[\"cd4_prog\"]), extents[n_sex][n_agr][n_cd4-1]);\n  multi_array_ref<double, 3> in_mort(REAL(s_fp[\"cd4_mort\"]), extents[n_sex][n_agr][n_cd4]);\n  \n  multi_array<double, 3> dist(extents[n_sex][n_age][n_cd4]);\n  multi_array<double, 3> prog(extents[n_sex][n_age][n_cd4-1]);\n  multi_array<double, 3> mort(extents[n_sex][n_age][n_cd4]);\n  \n  double hivpop[n_year * n_sex * n_age * n_cd4];\n  multi_array_ref<double, 4> Y(hivpop, extents[n_year][n_sex][n_age][n_cd4]);\n  double influx[n_cd4], efflux[n_cd4];\n\n  memset(hivpop, 0, n_year * n_sex * n_age * n_cd4 * sizeof(double));\n\n  for (int si(0); si < n_sex; ++si) {\n    for (int ai(0); ai < n_age; ++ai) {\n      for (int hi(0); hi < n_cd4; ++hi) dist[si][ai][hi] = in_dist[si][a2g[ai]][hi];\n      for (int hi(0); hi < n_cd4; ++hi) mort[si][ai][hi] = in_mort[si][a2g[ai]][hi] * dt; // 1.0 - exp(-in_mort[si][a2g[ai]][hi] * dt);\n      for (int hi(0); hi < n_cd4-1; ++hi) prog[si][ai][hi] = in_prog[si][a2g[ai]][hi] * dt; // 1.0 - exp(-in_prog[si][a2g[ai]][hi] * dt);\n    }\n  }\n  \n  // Year 1 simulation\n  for (int si(0); si < n_sex; ++si) {\n    for (int ai(0); ai < n_age; ++ai) {\n      for (int hi(0); hi < n_cd4; ++hi) {\n        Y[0][si][ai][hi] = inci[0][si][ai] * dist[si][ai][hi];\n      }\n    }\n  }\n\n  // Subsequent year simulation\n  for (int yi(1); yi < n_year; ++yi) {\n\n    // Aging and non-HIV mortality\n    for (int si(0); si < n_sex; ++si) {\n      for (int hi(0); hi < n_cd4; ++hi) {\n        for (int ai(1); ai < n_age; ++ai) Y[yi][si][ai][hi] = Y[yi-1][si][ai-1][hi] * surv[yi][si][ai];\n        Y[yi][si][n_age-1][hi] += Y[yi-1][si][n_age-1][hi] * surv[yi][si][n_age-1];\n      }\n    }\n\n    // HIV disease progression and mortality\n    for (int ti(0); ti < n_ts; ++ti) {\n      for (int si(0); si < n_sex; ++si) {\n        for (int ai(0); ai < n_age; ++ai) {\n          efflux[n_cd4-1] = Y[yi][si][ai][n_cd4-1] * mort[si][ai][n_cd4-1];\n          for (int hi(0); hi < n_cd4-1; ++hi) efflux[hi] = Y[yi][si][ai][hi] * (prog[si][ai][hi] + mort[si][ai][hi]);\n          for (int hi(1); hi < n_cd4; ++hi) influx[hi] = Y[yi][si][ai][hi-1] * prog[si][ai][hi-1];\n          for (int hi(0); hi < n_cd4; ++hi) Y[yi][si][ai][hi] += influx[hi] - efflux[hi];\n        }\n      }\n    }\n    \n    // Distribute new HIV infections\n    for (int si(0); si < n_sex; ++si) {\n      for (int ai(0); ai < n_age; ++ai) {\n        for (int hi(0); hi < n_cd4; ++hi) Y[yi][si][ai][hi] += inci[yi][si][ai] * dist[si][ai][hi];\n      }\n    }\n  }\n  \n  NumericVector rval(n_year * n_sex * n_age * n_cd4);\n  for (int i(0); i < rval.length(); ++i) rval[i] = hivpop[i];\n  return rval; // in R, convert to array via array(rval, c(n_cd4, n_age, n_sex, n_year))\n}\n", "meta": {"hexsha": "332cc542bdc8aa5fd0e35933fedb43647782070c", "size": 3835, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cohort-sim.cpp", "max_stars_repo_name": "rlglaubius/NaturalHistorySynthesis", "max_stars_repo_head_hexsha": "813267cd775357ba55ed0843d99eb8bb5e002773", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cohort-sim.cpp", "max_issues_repo_name": "rlglaubius/NaturalHistorySynthesis", "max_issues_repo_head_hexsha": "813267cd775357ba55ed0843d99eb8bb5e002773", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cohort-sim.cpp", "max_forks_repo_name": "rlglaubius/NaturalHistorySynthesis", "max_forks_repo_head_hexsha": "813267cd775357ba55ed0843d99eb8bb5e002773", "max_forks_repo_licenses": ["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.9479166667, "max_line_length": 137, "alphanum_fraction": 0.5439374185, "num_tokens": 1651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4797165771147451}}
{"text": "/*\n * ietl.cpp\n *\n *  Created on: Jan 19, 2012\n *      Author: david\n */\n\n#include \"../Common.hpp\"\n#include \"../as_range.hpp\"\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/numeric/ublas/symmetric.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <ietl/interface/ublas.h>\n#include <ietl/vectorspace.h>\n#include <ietl/lanczos.h>\n#include <boost/random.hpp>\n#include <boost/limits.hpp>\n#include <limits>\n#include <iostream>\n#include <vector>\n#include <cmath>\n\nnamespace graphseg { namespace detail {\n\nstd::vector<EigenComponent> solver_ietl(const SparseMatrix& A, unsigned int num_ev)\n{\n\ttypedef boost::numeric::ublas::symmetric_matrix<\n\t\tdouble, boost::numeric::ublas::lower> Matrix; \n\ttypedef boost::numeric::ublas::vector<double> Vector;\n\n\tint N = A.dim;\n\tMatrix mat(N, N);\n\tfor(int i=0;i<N;i++)\n\t\tfor(int j=0;j<=i;j++)\n\t\t\tmat(i,j) = 0;   \n\tfor(auto& e : A.entries)\n\t\tmat(e.i,e.j) = e.weight;\n\n\ttypedef ietl::vectorspace<Vector> Vecspace;\n\ttypedef boost::lagged_fibonacci607 Gen;  \n\n\tVecspace vec(N);\n\tGen mygen;\n\tietl::lanczos<Matrix,Vecspace> lanczos(mat,vec);\n\n\t// Creation of an iteration object:  \n\tint max_iter = 10*N;  \n\tdouble rel_tol = 50*std::numeric_limits<double>::epsilon();\n\tdouble abs_tol = 0.00001f;// std::pow(std::numeric_limits<double>::epsilon(),2./3);\n\tstd::cout << \"Computation of 2 lowest converged eigenvalues\\n\\n\";\n\tstd::cout << \"-----------------------------------\\n\\n\";\n\tint n_lowest_eigenval = num_ev;\n\tstd::vector<double> eigen;\n\tstd::vector<double> err;\n\tstd::vector<int> multiplicity;  \n\tietl::lanczos_iteration_nlowest<double> iter(max_iter, n_lowest_eigenval, rel_tol, abs_tol);\n\ttry{\n\t\tlanczos.calculate_eigenvalues(iter,mygen);\n\t\t//lanczos.more_eigenvalues(iter); \n\t\teigen = lanczos.eigenvalues();\n\t\terr = lanczos.errors();\n\t\tmultiplicity = lanczos.multiplicities();\n\t\tstd::cout<<\"number of iterations: \"<<iter.iterations()<<\"\\n\";\n\t}\n\tcatch (std::runtime_error& e) {\n\t\tstd::cout << e.what() << \"\\n\";\n\t} \n\n  // Printing eigenvalues with error & multiplicities:  \n\tstd::cout << \"#        eigenvalue            error         multiplicity\\n\";  \n\tstd::cout.precision(10);\n\tfor (int i=0;i<eigen.size();++i) \n\t\tstd::cout << i << \"\\t\" << eigen[i] << \"\\t\" << err[i] << \"\\t\" << multiplicity[i] << \"\\n\";\n\n\t// call of eigenvectors function follows:   \n\tstd::cout << \"\\nEigen vectors computations for lowest eigenvalues:\\n\\n\";  \n\tauto ew_begin = eigen.begin();\n\twhile(*ew_begin <= 0.0f) ew_begin ++;\n\tauto ew_end = ew_begin + num_ev;\n\tstd::vector<Vector> eigenvectors; // for storing the eigen vectors. \n\tietl::Info<double> info; // (m1, m2, ma, eigenvalue, residualm, status).\n\n\ttry {\n\t\tlanczos.eigenvectors(ew_begin,ew_end,std::back_inserter(eigenvectors),info,mygen); \n\t}\n\tcatch (std::runtime_error& e) {\n\t\tstd::cout << e.what() << \"\\n\";\n\t}\n\n\t// std::cout << \"Printing eigenvectors:\\n\\n\"; \n\t// for(std::vector<Vector>::iterator it = eigenvectors.begin();it!=eigenvectors.end();it++){\n\t// \tstd::copy((it)->begin(),(it)->end(),std::ostream_iterator<double>(std::cout,\", \"));\n\t// \tstd::cout << \"\\n\\n\";\n\t// }\n\tstd::cout << \" Information about the eigenvector computations:\\n\\n\";\n\tfor(int i = 0; i < info.size(); i++) {\n\t\tstd::cout << \" m1(\" << i+1 << \"): \" << info.m1(i) << \", m2(\" << i+1 << \"): \"\n\t\t\t<< info.m2(i) << \", ma(\" << i+1 << \"): \" << info.ma(i) << \" eigenvalue(\"\n\t\t\t<< i+1 << \"): \" << info.eigenvalue(i) << \" residual(\" << i+1 << \"): \"\n\t\t\t<< info.residual(i) << \" error_info(\" << i+1 << \"): \"\n\t\t\t<< info.error_info(i) << \"\\n\\n\";\n\t}\n\n\n  \tstd::vector<EigenComponent> solution(eigenvectors.size());\n\tfor(unsigned int i=0; i<solution.size(); i++) {\n\t\tEigenComponent& cmp = solution[i];\n\t\tcmp.eigenvalue = *(ew_begin + i);\n#ifdef SPECTRAL_VERBOSE\n\t\tstd::cout << \"Eigenvalue \" << i << \": \" << cmp.eigenvalue << std::endl;\n\t\tcmp.eigenvector = Eigen::VectorXf(N);\n#endif\n\t\tfor(unsigned int j=0; j<N; j++) {\n\t\t\t// convert back to generalized eigenvalue problem!\n\t\t\tcmp.eigenvector[j] = eigenvectors[i][j];\n\t\t}\n\t}\n#ifdef SPECTRAL_VERBOSE\n\tstd::cout << \"Sparse Solver: returning\" << std::endl;\n#endif\n\treturn solution;\n}\n\n}}\n", "meta": {"hexsha": "bd2f658192bd6fe461784e03e346f569f7c263c1", "size": 4060, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib_dasp/lib_dasp_graphseg/spectral/ietl.cpp", "max_stars_repo_name": "jbellis/superpixel-benchmark", "max_stars_repo_head_hexsha": "81a45649d426751d1ae450ef8ea0d2d9c7b3545f", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 344.0, "max_stars_repo_stars_event_min_datetime": "2016-12-16T10:11:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T06:08:14.000Z", "max_issues_repo_path": "lib_dasp/lib_dasp_graphseg/spectral/ietl.cpp", "max_issues_repo_name": "jbellis/superpixel-benchmark", "max_issues_repo_head_hexsha": "81a45649d426751d1ae450ef8ea0d2d9c7b3545f", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2018-02-15T19:34:19.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-31T17:04:48.000Z", "max_forks_repo_path": "lib_dasp/lib_dasp_graphseg/spectral/ietl.cpp", "max_forks_repo_name": "jbellis/superpixel-benchmark", "max_forks_repo_head_hexsha": "81a45649d426751d1ae450ef8ea0d2d9c7b3545f", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 111.0, "max_forks_repo_forks_event_min_datetime": "2016-12-08T07:19:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T06:08:16.000Z", "avg_line_length": 32.48, "max_line_length": 93, "alphanum_fraction": 0.6337438424, "num_tokens": 1232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148981, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.47971657259201256}}
{"text": "\n#include <boost/test/unit_test.hpp>\n\n#include <iostream>\n#include <memory>\n\n#include \"common/services/workRp.hpp\"\n\nnamespace cs = ble::src::common::services;\n\nnamespace ble::tests::unit_tests::common::services::work_rp {\n\nvoid case1_kw()\n{\n    // arrange\n    double expected = 0.0;\n    double s = 0.;\n    double n = 2.0;\n\n    // act\n    double actual = cs::rp::get_kw(s, n);\n\n    // assert\n    BOOST_CHECK_CLOSE(expected, actual, 1e-8);\n}\n\nvoid case2_kw()\n{\n    // arrange\n    double expected = 1.0;\n    double s = 1.;\n    double n = 2.0;\n\n    // act\n    double actual = cs::rp::get_kw(s, n);\n\n    // assert\n    BOOST_CHECK_CLOSE(expected, actual, 1e-8);\n}\n\nvoid case1_koil()\n{\n    // arrange\n    double expected = 1.0;\n    double s = 0.;\n    double n = 2.0;\n\n    // act\n    double actual = cs::rp::get_koil(s, n);\n\n    // assert\n    BOOST_CHECK_CLOSE(expected, actual, 1e-8);\n}\n\nvoid case2_koil()\n{\n    // arrange\n    double expected = 0.0;\n    double s = 1.;\n    double n = 2.0;\n\n    // act\n    double actual = cs::rp::get_koil(s, n);\n\n    // assert\n    BOOST_CHECK_CLOSE(expected, actual, 1e-8);\n}\n\nvoid case1_fbl()\n{\n    // arrange\n    double expected = 1.0;\n    double s = 1.;\n    double kmu = 0.125; // = mw / moil;\n    double n = 2.0;\n\n    // act\n    double actual = cs::rp::get_fbl(s, n, kmu);\n\n    // assert\n    BOOST_CHECK_CLOSE(expected, actual, 1e-8);\n}\n\nvoid case2_fbl()\n{\n    // arrange\n    double expected = 0.0;\n    double s = 0.;\n    double kmu = 0.125; // = mw / moil;\n    double n = 2.0;\n\n    // act\n    double actual = cs::rp::get_fbl(s, n, kmu);\n\n    // assert\n    BOOST_CHECK_CLOSE(expected, actual, 1e-8);\n}\n\nvoid case3_fbl()\n{\n    // arrange\n    double expected = 0.2;\n    double s = 0.2;\n    double kmu = 1.0; // = mw / moil;\n    double n = 1.0;\n\n    // act\n    double actual = cs::rp::get_fbl(s, n, kmu);\n\n    // assert\n    BOOST_CHECK_CLOSE(expected, actual, 1e-8);\n}\n\nvoid case1_sigma()\n{\n    // arrange\n    double expected = 1.0;\n    double s = 0.2;\n    double kmu = 1.0; // = mw / moil;\n    double n = 1.0;\n\n    // act\n    double actual = cs::rp::get_sigma(s, n, kmu);\n\n    // assert\n    BOOST_CHECK_CLOSE(expected, actual, 1e-8);\n}\n\nvoid case2_sigma()\n{\n    // arrange\n    double expected = 0.1;\n    double s = 0.0;\n    double kmu = 0.1; // = mw / moil;\n    double n = 2.0;\n\n    // act\n    double actual = cs::rp::get_sigma(s, n, kmu);\n\n    // assert\n    BOOST_CHECK_CLOSE(expected, actual, 1e-8);\n}\n\nvoid case1_dfbl()\n{\n    // arrange\n    double expected = 0.0;\n    double s = 0.0;\n    double kmu = 0.1; // = mw / moil;\n    double n = 2.0;\n\n    // act\n    double actual = cs::rp::get_dfbl(s, n, kmu);\n\n    // assert\n    BOOST_CHECK_CLOSE(expected, actual, 1e-8);\n}\n\nvoid case2_dfbl()\n{\n    // arrange\n    double expected = 2.076124567474048; // from wxmaxima\n    double s = 0.6;\n    double kmu = 2.0; // = mw / moil;\n    double n = 2.0;\n\n    // act\n    double actual = cs::rp::get_dfbl(s, n, kmu);\n\n    // assert\n    BOOST_CHECK_CLOSE(expected, actual, 1e-8);\n}\n\n}", "meta": {"hexsha": "9d10c1828efba560361f7a1bbd3f452ea8b66a0c", "size": 2997, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/unit_tests/common/services/workRpTests.cpp", "max_stars_repo_name": "erythrocyte/bleqt", "max_stars_repo_head_hexsha": "4abd7b2991e77d2cc344ecf3a1c3ee47d9d559d5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/unit_tests/common/services/workRpTests.cpp", "max_issues_repo_name": "erythrocyte/bleqt", "max_issues_repo_head_hexsha": "4abd7b2991e77d2cc344ecf3a1c3ee47d9d559d5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 71.0, "max_issues_repo_issues_event_min_datetime": "2020-09-04T13:52:54.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-04T20:19:49.000Z", "max_forks_repo_path": "tests/unit_tests/common/services/workRpTests.cpp", "max_forks_repo_name": "erythrocyte/bleqt", "max_forks_repo_head_hexsha": "4abd7b2991e77d2cc344ecf3a1c3ee47d9d559d5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.224137931, "max_line_length": 61, "alphanum_fraction": 0.5615615616, "num_tokens": 1018, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.4796531935266077}}
{"text": "#ifndef _HIGHER_ORDER_ENERGY_HPP_\n#define _HIGHER_ORDER_ENERGY_HPP_\n\n/*\n * higher-order-energy.hpp\n *\n * Copyright 2012 Alexander Fix\n * See LICENSE.txt for license information\n *\n * A representation for higher order pseudo-boolean energy functions\n *\n * Built up by calls to AddVar and AddTerm\n * Main operation is the reduction to quadratic form, ToQuadratic()\n * ToQuadratic() impements the reduction described in \n *  A Graph Cut Algorithm for Higher Order Markov Random Fields\n *  Alexander Fix, Artinan Gruber, Endre Boros, Ramin Zabih, ICCV 2011\n *\n * Template parameters:\n *  Energy   The result type of the energy function\n *  D        The maximum degree of any monomial \n *\n * Example usage:\n *\n * To represent the function\n *      f(x_0, ..., x_3) = 7x_0 + 9x_1 - 8x_2 + 13x_3 + 27x_1x_2x_3 \n *                       - 31x_1x_3x_4 + 18x_1x_2x_3x_4\n * we can do the following:\n *\n * HigherOrderEnergy<int, 4> f;\n * f.AddVars(4); \n * f.AddUnaryTerm(0, 7);\n * f.AddUnaryTerm(1, 9);\n * f.AddUnaryTerm(2, -8);\n * f.AddUnaryTerm(3, 13);\n *\n * VarId term1[] = {1, 2, 3};\n * VarId term2[] = {1, 3, 4};\n * VarId term3[] = {1, 2, 3, 4};\n * f.AddTerm(27, 3, term1);\n * f.AddTerm(-31, 3, term2);\n * f.AddTerm(18, 4, term3);\n *\n *\n * Then, we can get an equivalent quadratic form (by adding additional \n * variables and performing transformations) by calling ToQuadratic. We can\n * solve this using QPBO, or any other quadratic optimizer that has the same\n * interface.\n *\n * QPBO<int> qr;\n * f.ToQuadratic(qr);\n * qr.Solve();\n *\n *\n */\n\n#include <vector>\n#include <list>\n#include <boost/foreach.hpp>\n\ntemplate <typename R, int D>\nclass HigherOrderEnergy {\n    public:\n        typedef int VarId;\n\n        // Constructs empty HigherOrderEnergy with no variables or terms\n        HigherOrderEnergy();\n\n        // Adds variables to the HigherOrderEnergy. Variables must be added \n        // before any terms referencing them can be added\n        VarId AddVar();\n        VarId AddVars(int n);\n        VarId NumVars() const { return _varCounter; }\n\n        // Adds a monomial to the HigherOrderEnergy. degree must be <= D\n        // vars is an array of length at least degree, with the indices of \n        // the corresponding variables or literals in the monomial\n        void AddTerm(R coeff, int degree, const VarId vars[]);\n\n        void AddUnaryTerm(VarId v, R coeff);\n    \n        // Reduces the HigherOrderEnergy to quadratic form\n        // NOTE: THIS IS A DESTRUCTIVE OPERATION, so do not rely on the \n        // HigherOrderEnergy being in any useful state after this operation.\n        //\n        // This is a templated function, so it will work with any class \n        // implementing the necessary interface. See quadratic-rep.hpp for\n        // the minimal requirements.\n        template <typename QR>\n        void ToQuadratic(QR &qr);\n\n        void Clear();\n\n    private:\n        struct Term\n        {\n            R coeff;\n            int degree;\n            VarId vars[D];\n\n            Term(R _coeff, int _degree, const VarId _vars[])\n                : coeff(_coeff), degree(_degree)\n            {\n                for (int i = 0; i < degree; ++i)\n                    vars[i] = _vars[i];\n            }\n\n            bool operator<(const Term& t) const;\n            bool operator==(const Term& t) const;\n\n            std::string ToString() const;\n\n        };\n        static int Compare(int d1, \n                const VarId vars1[], \n                int d2, \n                const VarId vars2[]);\n\n        struct VarRecord {\n            VarRecord(VarId id) \n                : _id(id), _positiveTerms(0), _higherOrderTerms(0), \n                _quadraticTerms(0), _sumDegrees(0), _terms(), _coeff(0) { }\n            VarId _id;\n            int _positiveTerms;\n            int _higherOrderTerms;\n            int _quadraticTerms;\n            int _sumDegrees;\n            std::list<Term> _terms;\n            R _coeff;\n\n            void PrintTerms() const;\n        };\n\n        R _constantTerm;\n\n        void RemoveTerm(Term* tp);\n        void _EliminatePositiveTerms();\n        template <typename QR>\n        void _ReduceNegativeTerms(QR& qr);\n        void _ReportMultilinearStats();\n\n        size_t NumTerms() const {\n            size_t numTerms = 0;\n            BOOST_FOREACH(const VarRecord& vr, _varRecords)\n                numTerms += vr._terms.size();\n            return numTerms;\n        }\n\n        VarId _varCounter;\n\n        typedef std::vector<VarRecord> varRecordVec_t;\n        varRecordVec_t _varRecords;\n};\n\ntemplate <typename R, int D>\ninline HigherOrderEnergy<R, D>::HigherOrderEnergy()\n    : _constantTerm(0), _varCounter(0), _varRecords()\n{ }\n\n\ntemplate <typename R, int D>\ninline typename HigherOrderEnergy<R, D>::VarId \nHigherOrderEnergy<R, D>::AddVar() {\n    VarRecord vr(_varCounter);\n    _varRecords.push_back(vr);\n    return _varCounter++;\n}\n\ntemplate <typename R, int D>\ninline typename HigherOrderEnergy<R, D>::VarId \nHigherOrderEnergy<R, D>::AddVars(int n) {\n    VarId firstVar = _varCounter;\n    for (int i = 0; i < n; ++i)\n        this->AddVar();\n    return firstVar;\n}\n\ntemplate <typename R, int D>\ninline void \nHigherOrderEnergy<R, D>::AddTerm(R coeff, int d, const VarId vars[]) {\n    if(coeff == 0) {\n        return;\n    } else if (d == 0) {\n        _constantTerm += coeff;\n        return;\n    } else if (d == 1) {\n        _varRecords[vars[0]]._coeff += coeff;\n        return;\n    } else {\n        VarRecord& smallestVarRec = _varRecords[vars[0]];\n        typename std::list<Term>::iterator it = smallestVarRec._terms.begin();\n        int compareVars = 1;\n        while (it != smallestVarRec._terms.end()) {\n            compareVars = Compare(d, vars, it->degree, it->vars); \n            if (compareVars == 0) {\n                break;\n            } else if (compareVars < 0) {\n                break;\n            } else {\n                ++it;\n            }\n        }\n        if (compareVars == 0) {\n            it->coeff += coeff;\n        } else {\n            if (d > 2) {\n                smallestVarRec._higherOrderTerms++;\n                smallestVarRec._sumDegrees += d;\n            } else {\n                smallestVarRec._quadraticTerms++;\n            }\n            smallestVarRec._terms.insert(it, Term(coeff, d, vars));\n        }\n        if (coeff > 0)\n            smallestVarRec._positiveTerms++;\n        return;\n    }\n}\n\ntemplate <typename R, int D>\ninline void HigherOrderEnergy<R, D>::AddUnaryTerm(VarId var, R coeff) {\n    _varRecords[var]._coeff += coeff;\n}\n\ntemplate <typename R, int D>\nvoid HigherOrderEnergy<R, D>::_EliminatePositiveTerms() {\n    size_t numVars = _varRecords.size();\n    for (size_t varIndex = 0; varIndex < numVars; ++varIndex) {\n        R positiveSum = 0;\n        VarId newPosVar = AddVar();\n\n        VarRecord& vr = _varRecords[varIndex];\n\n        typename std::list<Term>::iterator termIt = vr._terms.begin();\n        VarId newVars[D];\n        while (termIt != vr._terms.end()) {\n            Term& t = *termIt;\n            //std::cout << \"\\t\" << t.ToString() << std::endl;\n            typename std::list<Term>::iterator currIt = termIt;\n            ++termIt;\n\n            if (t.coeff > 0) {\n                positiveSum += t.coeff;\n                for (int i = 0; i < t.degree - 1; ++i) {\n                    newVars[i] = t.vars[i+1];\n                    assert(newVars[i] >= vr._id);\n                }\n                AddTerm(t.coeff, t.degree - 1, newVars);\n                newVars[t.degree - 1] = newPosVar;\n                AddTerm(-t.coeff, t.degree, newVars);\n                if (t.degree == 2) {\n                    vr._quadraticTerms--;\n                } else {\n                    vr._higherOrderTerms--;\n                    vr._sumDegrees -= t.degree;\n                }\n                vr._terms.erase(currIt);\n            }\n        }\n        VarId quadratic[2];\n        quadratic[0] = vr._id;\n        quadratic[1] = newPosVar;\n        AddTerm(positiveSum, 2, quadratic);\n    }\n}\n\ntemplate <typename R, int D>\ntemplate <typename QR>\nvoid HigherOrderEnergy<R, D>::_ReduceNegativeTerms(QR& qr) {\n    // Estimate expected size of quadratic problem. Only nodes/edges are\n    // created below, so we can count them ahead of time\n    int expectedVars = _varCounter;\n    int expectedEdges = 0;\n    BOOST_FOREACH(const VarRecord& vr, _varRecords) {\n        expectedVars += vr._higherOrderTerms;\n        expectedEdges += vr._quadraticTerms;\n        expectedEdges += vr._sumDegrees;\n    }\n\n    //std::cout << \"\\tExpected Vars: \" << expectedVars << \"\\tExpected Edges: \" << expectedEdges << std::endl;\n\n    qr.SetMaxEdgeNum(expectedEdges);\n    qr.AddNode(_varCounter);\n\n    // Term-by-term reduction from Friedman & Drineas\n    BOOST_FOREACH(VarRecord& vr, _varRecords) {\n        BOOST_FOREACH(Term& t, vr._terms) {\n            if (t.degree == 2) {\n                qr.AddPairwiseTerm(t.vars[0], t.vars[1], 0, 0, 0, t.coeff);\n            } else {\n                typename QR::NodeId w = qr.AddNode();\n                assert(t.coeff <= 0);\n                for (int i = 0; i < t.degree; ++i) {\n                    qr.AddPairwiseTerm(t.vars[i], w, 0, 0, 0, t.coeff);\n                }\n                qr.AddUnaryTerm(w, 0, t.coeff*(1-t.degree));\n            }\n        }\n    }\n    BOOST_FOREACH(VarRecord& vr, _varRecords) {\n        qr.AddUnaryTerm(vr._id, 0, vr._coeff);\n    }\n}\n\ntemplate <typename R, int D>\ntemplate <typename QR>\ninline void HigherOrderEnergy<R, D>::ToQuadratic(QR& qr) {\n    _EliminatePositiveTerms();\n    _ReduceNegativeTerms(qr);\n}\n\ntemplate <typename R, int D>\ninline int HigherOrderEnergy<R, D>::Compare(int d1, const VarId vars1[], int d2, const VarId vars2[]) {\n    if (d1 < d2)\n        return -1;\n    if (d1 > d2)\n        return 1;\n    for (int index = 0; index < d1; ++index) {\n        if (vars1[index] != vars2[index])\n            return (vars1[index] < vars2[index]) ? -1 : 1;\n    }\n    return 0;\n}\n\ntemplate <typename R, int D>\ninline void HigherOrderEnergy<R, D>::Clear() {\n    _varRecords.clear();\n};\n\n#endif\n", "meta": {"hexsha": "024db66006312c7c1317c4670b924cb9f27fc0d3", "size": 10000, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/opengm/inference/fix-fusion/higher-order-energy.hpp", "max_stars_repo_name": "burcin/opengm", "max_stars_repo_head_hexsha": "a1b21eecb93c6c5a7b11ab312d26b1c98c55ff41", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 318.0, "max_stars_repo_stars_event_min_datetime": "2015-01-07T15:22:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-22T10:10:29.000Z", "max_issues_repo_path": "include/opengm/inference/fix-fusion/higher-order-energy.hpp", "max_issues_repo_name": "burcin/opengm", "max_issues_repo_head_hexsha": "a1b21eecb93c6c5a7b11ab312d26b1c98c55ff41", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 89.0, "max_issues_repo_issues_event_min_datetime": "2015-03-24T14:33:01.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-10T13:59:13.000Z", "max_forks_repo_path": "include/opengm/inference/fix-fusion/higher-order-energy.hpp", "max_forks_repo_name": "burcin/opengm", "max_forks_repo_head_hexsha": "a1b21eecb93c6c5a7b11ab312d26b1c98c55ff41", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 119.0, "max_forks_repo_forks_event_min_datetime": "2015-01-13T08:35:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T01:49:08.000Z", "avg_line_length": 30.303030303, "max_line_length": 109, "alphanum_fraction": 0.5686, "num_tokens": 2623, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081925, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.4796531890373245}}
{"text": "/******************************************************************************\n *\n *  filename: Ray.h\n *  author  : Do Won Cha\n *  content :\n *\n *****************************************************************************/\n\n#pragma once\n#ifndef _RAY_RAY_\n#define _RAY_RAY_\n\n#include <Eigen/Core>\n#include <iostream>\n\nnamespace raytracer\n{\n\nusing namespace Eigen;\n\nclass Ray\n{\npublic:\n  Ray() { }\n\n  Ray(Vector3f position,\n      Vector3f direction) :\n  position_(position),\n  direction_(direction)\n  { }\n\n  ~Ray() {}\n\n  Vector3f evaluate(float t) const { return position_ + direction_ * t; }\n\n  Vector3f position() const { return position_; }\n  Vector3f direction() const { return direction_; }\n\n  friend std::ostream& operator << (std::ostream& s, const Ray& ray)\n  {\n\t  return s << \"\";\n  }\n\nprivate:\n  Vector3f position_;\n  Vector3f direction_;\n};\n\n}     // end of namespace raytracer\n\n#endif // _RAY_RAY_\n", "meta": {"hexsha": "36e513c11034c07389b05078a4250a812f6668df", "size": 909, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "PA4/src/primitives/ray.hpp", "max_stars_repo_name": "dowoncha/COMP575", "max_stars_repo_head_hexsha": "6e48bdd80cb1a3e677c07655640efa941325e59c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PA4/src/primitives/ray.hpp", "max_issues_repo_name": "dowoncha/COMP575", "max_issues_repo_head_hexsha": "6e48bdd80cb1a3e677c07655640efa941325e59c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PA4/src/primitives/ray.hpp", "max_forks_repo_name": "dowoncha/COMP575", "max_forks_repo_head_hexsha": "6e48bdd80cb1a3e677c07655640efa941325e59c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.4807692308, "max_line_length": 79, "alphanum_fraction": 0.5412541254, "num_tokens": 205, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494421679929, "lm_q2_score": 0.6992544085240401, "lm_q1q2_score": 0.4796531714605751}}
{"text": "/*\n * math.cpp\n *\n *  Created on: Jan 11, 2019\n *      Author: Gregory Kramida\n *   Copyright: 2019 Gregory Kramida\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//libraries\n#include <Eigen/Eigen>\n#include <boost/python.hpp>\n#include <boost/python/suite/indexing/vector_indexing_suite.hpp>\n#include <boost/shared_ptr.hpp>\n\n//local\n#include \"../math/typedefs.hpp\"\n#include \"../math/statistics.hpp\"\n#include \"../math/transformation.hpp\"\n\nnamespace bp = boost::python;\n\nnamespace python_export {\n\nvoid export_math_types() {\n\t// =============================================================================================\n\t// region === MATH TYPES =======================================================================\n\t// =============================================================================================\n\tbp::class_<math::Vector2i>(\"Vector2i\", bp::init<int, int>())\n\t\t\t.def(bp::init<int>())\n\t\t\t.def_readwrite(\"x\", &math::Vector2i::x)\n\t\t\t.def_readwrite(\"y\", &math::Vector2i::y)\n\t\t\t.def_readwrite(\"u\", &math::Vector2i::u)\n\t\t\t.def_readwrite(\"v\", &math::Vector2i::v)\n\t\t\t;\n\tbp::class_<math::Vector3i>(\"Vector3i\", bp::init<int, int, int>())\n\t\t\t\t.def(bp::init<int>())\n\t\t\t\t.def_readwrite(\"x\", &math::Vector3i::x)\n\t\t\t\t.def_readwrite(\"y\", &math::Vector3i::y)\n\t\t\t\t.def_readwrite(\"z\", &math::Vector3i::z)\n\t\t\t\t;\n\n\tbp::class_<math::Vector2f>(\"Vector2f\", bp::init<float, float>())\n\t\t\t.def(bp::init<float>())\n\t\t\t.def_readwrite(\"x\", &math::Vector2f::x)\n\t\t\t.def_readwrite(\"y\", &math::Vector2f::y)\n\t\t\t.def_readwrite(\"u\", &math::Vector2f::u)\n\t\t\t.def_readwrite(\"v\", &math::Vector2f::v)\n\t\t\t;\n\n}\n\nvoid export_math_functions(){\n\tbp::def(\"mean_vector_length\", &math::mean_vector_length,\n\t\t\t\"Computes the mean vector length for all vectors in the given field\", bp::args(\"vector_field\"));\n\n\tbp::def(\"transformation_vector_to_matrix3d\", &math::transformation_vector_to_matrix3d,\n\t\t\t\"Convert 6X1 transformation vector to 4X4 matrix in homogeneous coordinates\", bp::args(\"vector\"));\n}\n\n} // namespace python_export\n\n", "meta": {"hexsha": "971a37cdc0a76a7fa85aa2b168d9b77a73e049e9", "size": 2528, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/python_export/math.cpp", "max_stars_repo_name": "Algomorph/LevelSetFusionExperimentsCPP", "max_stars_repo_head_hexsha": "f56962f0ad5c62e6706f818062782a2e1660afda", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2019-01-07T14:12:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T01:48:03.000Z", "max_issues_repo_path": "src/python_export/math.cpp", "max_issues_repo_name": "Algomorph/LevelSetFusionExperimentsCPP", "max_issues_repo_head_hexsha": "f56962f0ad5c62e6706f818062782a2e1660afda", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2018-12-19T16:43:33.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-06T19:50:22.000Z", "max_forks_repo_path": "src/python_export/math.cpp", "max_forks_repo_name": "Algomorph/LevelSetFusionExperimentsCPP", "max_forks_repo_head_hexsha": "f56962f0ad5c62e6706f818062782a2e1660afda", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-01-07T14:12:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-06T06:30:24.000Z", "avg_line_length": 34.1621621622, "max_line_length": 101, "alphanum_fraction": 0.6143196203, "num_tokens": 655, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.47952856934950905}}
{"text": "//=======================================================================\n// Copyright 1997, 1998, 1999, 2000 University of Notre Dame.\n// Author: Jeremy G. Siek\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n#include <boost/config.hpp>\n#include <iostream>\n#include <boost/graph/adjacency_matrix.hpp>\n#include <boost/graph/graph_utility.hpp>\n\nint main()\n{\n    using namespace boost;\n    enum\n    {\n        A,\n        B,\n        C,\n        D,\n        E,\n        F,\n        N\n    };\n    const char* name = \"ABCDEF\";\n\n    // A directed graph\n\n    typedef adjacency_matrix< directedS > Graph;\n    Graph g(N);\n    add_edge(B, C, g);\n    add_edge(B, F, g);\n    add_edge(C, A, g);\n    add_edge(C, C, g);\n    add_edge(D, E, g);\n    add_edge(E, D, g);\n    add_edge(F, A, g);\n\n    std::cout << \"vertex set: \";\n    print_vertices(g, name);\n    std::cout << std::endl;\n\n    std::cout << \"edge set: \";\n    print_edges(g, name);\n    std::cout << std::endl;\n\n    std::cout << \"out-edges: \" << std::endl;\n    print_graph(g, name);\n    std::cout << std::endl;\n\n    // An undirected graph\n\n    typedef adjacency_matrix< undirectedS > UGraph;\n    UGraph ug(N);\n    add_edge(B, C, ug);\n    add_edge(B, F, ug);\n    add_edge(C, A, ug);\n    add_edge(D, E, ug);\n    add_edge(F, A, ug);\n\n    std::cout << \"vertex set: \";\n    print_vertices(ug, name);\n    std::cout << std::endl;\n\n    std::cout << \"edge set: \";\n    print_edges(ug, name);\n    std::cout << std::endl;\n\n    std::cout << \"incident edges: \" << std::endl;\n    print_graph(ug, name);\n    std::cout << std::endl;\n    return 0;\n}\n", "meta": {"hexsha": "4f36ead9805adbfca33665901a7c22f7b04f8384", "size": 1749, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/graph/example/adjacency_matrix.cpp", "max_stars_repo_name": "uosorio/heroku_face", "max_stars_repo_head_hexsha": "7d6465e71dba17a15d8edaef520adb2fcd09d91e", "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": "3rdparty/boost_1_73_0/libs/graph/example/adjacency_matrix.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 130.0, "max_issues_repo_issues_event_min_datetime": "2016-06-22T22:11:25.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-29T20:24:09.000Z", "max_forks_repo_path": "3rdparty/boost_1_73_0/libs/graph/example/adjacency_matrix.cpp", "max_forks_repo_name": "qingkouwei/mediaones", "max_forks_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2015-07-08T19:18:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-14T16:39:56.000Z", "avg_line_length": 23.0131578947, "max_line_length": 73, "alphanum_fraction": 0.5191538022, "num_tokens": 485, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.47952856056198745}}
{"text": "//! [substract]\n#include <boost/simd/function/load.hpp>\n#include <boost/simd/function/minus.hpp>\n#include <boost/simd/function/store.hpp>\n#include <boost/simd/meta/cardinal_of.hpp>\n#include <boost/simd/pack.hpp>\n#include <cstdlib>\n#include <iomanip>\n#include <iostream>\n#include <numeric>\n#include <vector>\n\ntemplate <typename T>\nvoid print(std::string mes, const T& out)\n{\n  std::cout << mes << std::endl;\n  for (size_t i = 0; i < out.size(); ++i) {\n    if (i && (i % 8 == 0))\n      std::cout << std::endl;\n    std::cout << std::setw(5) << out[i] << \" \";\n  }\n  std::cout << std::endl << std::endl;\n}\n\nint main()\n{\n  namespace bs = boost::simd;\n  size_t size  = 128;\n  std::vector<int32_t> array(size);\n  std::vector<int32_t> out(size);\n  // Initialize input array\n  std::iota(array.begin(), array.end(), 0);\n  int32_t scalar = 42;\n\n  using pack_t     = bs::pack<int32_t>;\n  size_t pack_card = bs::cardinal_of<pack_t>();\n\n  // Scalar version\n  for (size_t i = 0; i < size; ++i) {\n    out[i] = array[i] - scalar;\n  }\n  print(\"scalar loop output\", out);\n\n  {\n    pack_t p_out, pkvalue(scalar);\n    for (size_t i = 0; i < size; i += pack_card) {\n      pack_t p_arr(array.data() + i);\n      p_out = p_arr - pkvalue;\n      bs::store(p_out, out.data() + i);\n    }\n    print(\"SIMD 1 loop output\", out);\n  }\n\n  {\n    pack_t p_out, p_arr, pkvalue{scalar};\n    for (size_t i = 0; i < size; i += pack_card) {\n      p_arr = bs::load<pack_t>(array.data() + i);\n      p_out = p_arr - pkvalue;\n      bs::store(p_out, out.data() + i);\n    }\n    print(\"SIMD 2 loop output\", out);\n  }\n\n  {\n    // set size to an arbitrary value\n    size = 133;\n    pack_t p_out, p_arr, pkvalue{scalar};\n    array.resize(size);\n    out.resize(size);\n    std::iota(array.begin(), array.end(), 0);\n    size_t i = 0;\n    for (; i + pack_card <= size; i += pack_card) {\n      p_arr = bs::load<pack_t>(array.data() + i);\n      p_out = p_arr - pkvalue;\n      bs::store(p_out, out.data() + i);\n    }\n\n    for (; i < size; ++i) {\n      out[i] = array[i] - scalar;\n    }\n    print(\"SIMD 3 loop output\", out);\n  }\n  return 0;\n}\n// This code can be compiled using (for instance for gcc)\n// g++ substract.cpp -msse4.2 -std=c++11 -O3 -DNDEBUG -o substract\n// -I/path_to/boost_simd/ -I/path_to/boost/\n//! [substract]\n", "meta": {"hexsha": "b26435756516fce636d5c0c0ca7b5c443dd2969d", "size": 2267, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/examples/substract.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/substract.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/substract.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": 25.4719101124, "max_line_length": 66, "alphanum_fraction": 0.5827084252, "num_tokens": 726, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300449389327, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.4795285517744659}}
{"text": "#ifdef COMPILATION_INSTRUCTIONS\nnvcc -x cu --expt-relaxed-constexpr`#$CXX` -Wno-deprecated-declarations $0 -o $0x -lcudart -lcublas -lboost_unit_test_framework \\\n`pkg-config --libs blas` -DBOOST_LOG_DYN_LINK -lboost_system&&$0x&&rm $0x;exit\n#endif\n// \u00a9 Alfredo A. Correa 2019-2020\n\n#define BOOST_TEST_MODULE \"C++ Unit Tests for Multi cuBLAS herk\"\n#define BOOST_TEST_DYN_LINK\n#include<boost/test/unit_test.hpp>\n\n#include \"../../../adaptors/cuda.hpp\" // multi::cuda ns\n\n#include \"../../../adaptors/blas/cuda.hpp\"\n#include \"../../../adaptors/blas/herk.hpp\"\n#include \"../../../adaptors/blas/gemm.hpp\"\n\n#include \"../../../array.hpp\"\n\n#include <boost/log/expressions.hpp>\n\nnamespace multi = boost::multi;\nnamespace cuda = multi::cuda;\n\nBOOST_AUTO_TEST_CASE(multi_blas_cuda_herk_complex){\n#if 1\n\tusing complex = std::complex<double>;\n\tcomplex const I{0, 1};\n\n\tmulti::array<complex, 2> const a = {\n\t\t{ 1. + 3.*I, 3.- 2.*I, 4.+ 1.*I},\n\t\t{ 9. + 1.*I, 7.- 8.*I, 1.- 3.*I}\n\t};\n\t{\n\t\tmulti::array<complex, 2> c({2, 2}, 9999.);\n\t\tnamespace blas = multi::blas;\n\t\tusing blas::herk;\n\t\therk(a, c);\n\t\tBOOST_REQUIRE( c[1][0] == complex(50., -49.) );\n\t\tBOOST_REQUIRE( c[0][1] == complex(50., +49.) );\n\n\t\tmulti::array<complex, 2> const c_copy = herk(1., a);\n\t\tBOOST_REQUIRE( c == c_copy );\n\n\t\tusing blas::gemm;\n\t\tusing blas::hermitized;\n\t\tBOOST_REQUIRE( gemm(a, hermitized(a)) == herk(a) );\n\t}\n\t{\n\t\tcuda::array<complex, 2> const acu = a; BOOST_REQUIRE(a == acu);\n\t\tcuda::array<complex, 2> ccu({2, 2}, 9999.);\n\t\tusing multi::blas::herk;\n\t\therk(acu, ccu);\n\t\tBOOST_REQUIRE( ccu[1][0] == complex(50., -49.) );\n\t\tBOOST_REQUIRE( ccu[0][1] == complex(50., +49.) );\n\n\t\tcuda::array<complex, 2> const ccu_copy = herk(1., acu);\n\t\tBOOST_REQUIRE( herk(1., acu) == ccu );\n\t}\n\t{\n\t\tcuda::managed::array<complex, 2> const amcu = a; BOOST_REQUIRE(a == amcu);\n\t\tcuda::managed::array<complex, 2> cmcu({2, 2}, 9999.);\n\t\tusing multi::blas::herk;\n\t\therk(1., amcu, cmcu);\n\t\tBOOST_REQUIRE( cmcu[1][0] == complex(50., -49.) );\n\t\tBOOST_REQUIRE( cmcu[0][1] == complex(50., +49.) );\n\n\t\tcuda::managed::array<complex, 2> const cmcu_copy = herk(1., amcu);\n\t\tBOOST_REQUIRE( cmcu_copy == cmcu );\n\t}\n\t{\n\t\tmulti::array<complex, 2> c({3, 3}, 9999.);\n\t\tusing multi::blas::herk;\n\t\tusing multi::blas::hermitized;\n\t\therk(1., hermitized(a), c);\n\t\tBOOST_REQUIRE( c[2][1] == complex(41, +2) );\n\t\tBOOST_REQUIRE( c[1][2] == complex(41, -2) );\n\n\t\tmulti::array<complex, 2> const c_copy = herk(1., hermitized(a));\n\t\tBOOST_REQUIRE( c_copy == c );\n\t}\n\t{\n\t\tcuda::array<complex, 2> const acu = a; BOOST_REQUIRE(a == acu);\n\t\tcuda::array<complex, 2> ccu({3, 3}, 9999.);\n\t\tusing multi::blas::herk;\n\t\tusing multi::blas::hermitized;\n\t\therk(1., hermitized(acu), ccu);\n\t\tBOOST_REQUIRE( ccu[2][1] == complex(41, +2) );\n\t\tBOOST_REQUIRE( ccu[1][2] == complex(41, -2) );\n\n\t\tcuda::array<complex, 2> const ccu_copy = herk(1., hermitized(acu));\n\t\tBOOST_REQUIRE( ccu_copy == ccu );\n\t}\n\t{\n\t\tcuda::managed::array<complex, 2> const acu = a; BOOST_REQUIRE(a == acu);\n\t\tcuda::managed::array<complex, 2> ccu({3, 3}, 9999.);\n\t\tusing multi::blas::herk;\n\t\tusing multi::blas::hermitized;\n\t\therk(1., hermitized(acu), ccu);\n\t\tBOOST_REQUIRE( ccu[2][1] == complex(41, +2) );\n\t\tBOOST_REQUIRE( ccu[1][2] == complex(41, -2) );\n\n\t\tcuda::managed::array<complex, 2> const ccu_copy = herk(1., hermitized(acu));\n\t\tBOOST_REQUIRE( ccu_copy == ccu );\t\t\n\t}\n#endif\n}\n\n#if 0\nBOOST_AUTO_TEST_CASE(multi_blas_cuda_herk_real){\n\tmulti::array<double, 2> const a = {\n\t\t{ 1., 3., 4.},\n\t\t{ 9., 7., 1.}\n\t};\n\t{\n\t\tmulti::array<double, 2> c({2, 2}, 9999);\n\t\tusing multi::blas::herk;\n\t\therk(1., a, c);\n\t\tBOOST_REQUIRE( c[1][0] == 34 );\n\t\tBOOST_REQUIRE( c[0][1] == 34 );\n\n\t\tmulti::array<double, 2> const c_copy = herk(1., a);\n\t\tBOOST_REQUIRE( c == c_copy );\n\t}\n\t{\n\t\tcuda::array<double, 2> const acu = a; BOOST_REQUIRE(a == acu);\n\t\tcuda::array<double, 2> ccu({2, 2}, 9999.);\n\t\tusing multi::blas::herk;\n\t\therk(1., acu, ccu);\n\t\tBOOST_REQUIRE( ccu[1][0] == 34 );\n\t\tBOOST_REQUIRE( ccu[0][1] == 34 );\n\n\t\tcuda::array<double, 2> const ccu_copy = herk(1., acu);\n\t\tBOOST_REQUIRE( herk(1., acu) == ccu );\n\t}\n\t{\n\t\tcuda::array<double, 2> const acu = a; BOOST_REQUIRE(a == acu);\n\t//\tcuda::array<double, 2> ccu({2, 2}, 9999.);\n\t\tusing multi::blas::herk;\n\t\tcuda::array<double, 2> ccu = herk(acu);\n\t\tBOOST_REQUIRE( ccu[1][0] == 34 );\n\t\tBOOST_REQUIRE( ccu[0][1] == 34 );\n\n\t\tcuda::array<double, 2> const ccu_copy = herk(1., acu);\n\t\tBOOST_REQUIRE( herk(1., acu) == ccu );\n\t}\n\t{\n\t\tcuda::managed::array<double, 2> const amcu = a; BOOST_REQUIRE(a == amcu);\n\t\tcuda::managed::array<double, 2> cmcu({2, 2}, 9999.);\n\t\tusing multi::blas::herk;\n\t\therk(1., amcu, cmcu);\n\t\tBOOST_REQUIRE( cmcu[1][0] == 34 );\n\t\tBOOST_REQUIRE( cmcu[0][1] == 34 );\n\n\t\tcuda::managed::array<double, 2> const cmcu_copy = herk(1., amcu);\n\t\tBOOST_REQUIRE( cmcu_copy == cmcu );\n\t}\n\tif(0){\n\t\tmulti::array<double, 2> c({3, 3}, 9999.);\n\t\tusing multi::blas::herk;\n\t\tusing multi::blas::hermitized;\n\t\therk(1., hermitized(a), c);\n\t\tBOOST_REQUIRE( c[2][1] == 19 );\n\t\tBOOST_REQUIRE( c[1][2] == 19 );\n\n\t\tmulti::array<double, 2> const c_copy = herk(1., hermitized(a));\n\t\tBOOST_REQUIRE( c_copy == c );\n\t}\n\tif(0){\n\t\tcuda::array<double, 2> const acu = a; BOOST_REQUIRE(acu == a);\n\t\tcuda::array<double, 2> ccu({3, 3}, 9999.);\n\t\tusing multi::blas::herk;\n\t\tusing multi::blas::hermitized;\n\t\therk(1., hermitized(acu), ccu);\n\t\tBOOST_REQUIRE( ccu[2][1] == 19 );\n\t\tBOOST_REQUIRE( ccu[1][2] == 19 );\n\n\t\tcuda::array<double, 2> const c_copy = herk(1., hermitized(a));\n\t\tBOOST_REQUIRE( c_copy == ccu );\n\t}\n\tif(0){\n\t\tcuda::managed::array<double, 2> const amcu = a; BOOST_REQUIRE(amcu == a);\n\t\tcuda::managed::array<double, 2> cmcu({3, 3}, 9999.);\n\t\tusing multi::blas::herk;\n\t\tusing multi::blas::hermitized;\n\t\therk(1., hermitized(amcu), cmcu);\n\t\tBOOST_REQUIRE( cmcu[2][1] == 19 );\n\t\tBOOST_REQUIRE( cmcu[1][2] == 19 );\n\n\t\tcuda::managed::array<double, 2> const c_copy = herk(1., hermitized(a));\n\t\tBOOST_REQUIRE( c_copy == cmcu );\n\t}\n}\n#endif\n\n", "meta": {"hexsha": "b3e0605d6622f0005f2031a7cdfd1ac1d2d760a2", "size": 5922, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "external_codes/boost_multi/multi/adaptors/blas/tests/herk.cpp", "max_stars_repo_name": "djstaros/qmcpack", "max_stars_repo_head_hexsha": "280f67e638bae280448b47fa618f05b848c530d2", "max_stars_repo_licenses": ["NCSA"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "external_codes/boost_multi/multi/adaptors/blas/tests/herk.cpp", "max_issues_repo_name": "djstaros/qmcpack", "max_issues_repo_head_hexsha": "280f67e638bae280448b47fa618f05b848c530d2", "max_issues_repo_licenses": ["NCSA"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "external_codes/boost_multi/multi/adaptors/blas/tests/herk.cpp", "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": 30.3692307692, "max_line_length": 129, "alphanum_fraction": 0.6180344478, "num_tokens": 2226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.4794836427684487}}
{"text": "// SPDX-License-Identifier: Apache-2.0\n// Copyright 2021 - 2021, the Anboto author and contributors\n#include <Core/Core.h>\n#include <ScatterDraw/DataSource.h>\n#include <Eigen/Eigen.h>\n#include <ScatterDraw/Histogram.h>\n\nnamespace Upp {\n\nHistogram::Histogram() {\n\tClear();\n}\n\nHistogram::Histogram(const Histogram &hist) {\n\t*this = hist;\n}\n\nHistogram &Histogram::operator=(const Histogram &hist) {\n\ttotalVals = hist.totalVals;\n\t\n\tvalues = hist.values; \n\tranges <<= hist.ranges;\n\t\n\treturn *this;\n}\n\nvoid Histogram::Clear() {\n\tranges.Clear();\t\n\tvalues.resize(0);\n}\n\nHistogram &Histogram::Create2D(const Vector<Vector<double> > &_ranges, const Vector<double> &data, double total) {\n\tClear();\n\t\n\tint numAxis = 2;\n\tvaluesIdx.SetNumAxis(numAxis);\n\tfor (int ix = 0; ix < numAxis; ++ix)\n\t\tvaluesIdx.SetAxisDim(ix, _ranges[ix].GetCount());\n\tvalues.resize(valuesIdx.size());\n\tvalues.setZero();\n\tranges.SetCount(numAxis);\n\tfor (int ix = 0; ix < numAxis; ++ix) {\n\t\tranges[ix].SetCount(_ranges[ix].GetCount());\n\t\tfor (int d = 0; d < _ranges[ix].GetCount(); ++d) \n\t\t\tranges[ix][d] = _ranges[ix][d];\n\t}\n\ttotalVals = total;\n\tfor (int i = 0; i < data.GetCount(); ++i) \n\t\tvalues(ptrdiff_t(i)) = data[i];\n\treturn *this;\n}\n\t\nHistogram &Histogram::Create(Upp::Array<HistogramDataAxis> &dataAxis, bool isY) {\n\tClear();\n\t\n\tint numAxis = dataAxis.GetCount();\n\tvaluesIdx.SetNumAxis(numAxis);\n\tfor (int ix = 0; ix < numAxis; ++ix)\n\t\tvaluesIdx.SetAxisDim(ix, dataAxis[ix].numVals);\n\tvalues.resize(valuesIdx.size());\n\tvalues.setZero();\n\tranges.SetCount(numAxis);\n\tVector<double> delta;\n\tdelta.SetCount(numAxis);\n\tfor (int ix = 0; ix < numAxis; ++ix) {\n\t\tranges[ix].SetCount(dataAxis[ix].numVals);\n\t\tdelta[ix] = (dataAxis[ix].max - dataAxis[ix].min + 1)/dataAxis[ix].numVals;\n\t\tfor (int d = 0; d < dataAxis[ix].numVals; ++d) \n\t\t\tranges[ix][d] = (d + 1)*delta[ix];\n\t}\n\t\n\ttotalVals = double(dataAxis[0].data.GetCount());\n\tVector<int> index;\n\tindex.SetCount(numAxis);\n\tfor (int64 i = 0; i < totalVals; ++i) {\n\t\tfor (int ix = 0; ix < numAxis; ++ix) {\n\t\t\tdouble d = isY ? dataAxis[ix].data.y(i) : dataAxis[ix].data.x(i);\n\t\t\tif (!!IsNum(d)) {\n\t\t\t\tdouble val = d - dataAxis[ix].min;\n\t\t\t\tval = val/delta[ix];\n\t\t\t\tif (val >= dataAxis[ix].numVals)\n\t\t\t\t\tval = dataAxis[ix].numVals - 1;\n\t\t\t\telse if (val < 0)\n\t\t\t\t\tval = 0;\n\t\t\t\tASSERT(int(val) >= 0 && int(val) < dataAxis[ix].numVals);\n\t\t\t\tindex[ix] = int(val);\n\t\t\t} else\n\t\t\t\tindex[ix] = Null;\n\t\t}\n\t\tif (!IsNull(index[0]))\n\t\t\tvalues(valuesIdx.GetIndex(index))++;\t\n\t}\n\treturn *this;\t\n}\n\nHistogram &Histogram::Create(DataSource &data, double min, double max, int numVals, bool isY) {\n\tClear();\n\t\n\tvalues.resize(numVals);\n\tvalues.setZero();\n\tranges.SetCount(1);\n\tranges[0].SetCount(numVals);\n\tdouble delta = (max - min)/numVals;\n\tfor (int ii = 0; ii < numVals; ++ii) \n\t\tranges[0][ii] = min + (ii + 0.5)*delta;\n\t\n\tint64 total = data.GetCount();\n\ttotalVals = 0;\n\tfor (int64 i = 0; i < total; ++i) {\n\t\tdouble d = isY ? data.y(i) : data.x(i);\n\t\tif (!!IsNum(d)) {\n\t\t\tdouble val = (d - min)/delta;\n\t\t\tif (val >= numVals)\n\t\t\t\tval = numVals - 1;\n\t\t\telse if (val < 0)\n\t\t\t\tval = 0;\n\t\t\tvalues(int(val))++;\t\n\t\t\ttotalVals++;\n\t\t}\n\t}\n\treturn *this;\t\n}\n\nHistogram &Histogram::Normalize(double val) {\n\tif (totalVals == val)\n\t\treturn *this;\n\t\n\tif (totalVals > 0)\n\t\tvalues *= val/totalVals;\n\ttotalVals = val;\n\treturn *this;\n}\n\ndouble Histogram::Compare(const Histogram &hist) {\n\tASSERT(hist.values.size() == values.size());\n\tdouble res = 0;\n\tptrdiff_t size = values.size();\n\tfor(ptrdiff_t i = 0; i < size; i++) \n\t\tres += min(values[i], hist.values[i]);\n\tres /= totalVals;\n\treturn res;\n}\n\n}", "meta": {"hexsha": "d2a99caebfc8d565f845ed15ef307d25d9c6f56b", "size": 3573, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ScatterDraw/Histogram.cpp", "max_stars_repo_name": "anboto/Anboto", "max_stars_repo_head_hexsha": "fc40730e87b85bba4d9387724fcece7e98069843", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2021-02-28T12:07:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T19:40:45.000Z", "max_issues_repo_path": "ScatterDraw/Histogram.cpp", "max_issues_repo_name": "anboto/Anboto", "max_issues_repo_head_hexsha": "fc40730e87b85bba4d9387724fcece7e98069843", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2021-03-20T10:46:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-27T19:50:32.000Z", "max_forks_repo_path": "ScatterDraw/Histogram.cpp", "max_forks_repo_name": "anboto/Anboto", "max_forks_repo_head_hexsha": "fc40730e87b85bba4d9387724fcece7e98069843", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-20T09:15:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-20T09:15:18.000Z", "avg_line_length": 24.8125, "max_line_length": 114, "alphanum_fraction": 0.6325216905, "num_tokens": 1115, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743735019595, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.47948364012838907}}
{"text": "#include \"drake/solvers/integer_inequality_solver.h\"\n\n#include <algorithm>\n#include <functional>\n#include <iostream>\n#include <vector>\n\n#include <Eigen/Dense>\n\n#include \"drake/common/drake_assert.h\"\n\nnamespace drake {\nnamespace solvers {\nnamespace {\n\nusing IntegerVectorList = std::vector<std::vector<int>>;\nusing SolutionList = Eigen::Matrix<int, -1, -1, Eigen::RowMajor>;\n\nbool IsElementwiseNonnegative(const Eigen::MatrixXi& A) {\n  return (A.array() >= 0).all();\n}\n\nbool IsElementwiseNonpositive(const Eigen::MatrixXi& A) {\n  return (A.array() <= 0).all();\n}\n\n/* Construct finite-set of admissible values, i.e., an alphabet, for each\n * coordinate from specified upper and lower bounds, e.g., a lower bound and\n * upper bound of -1, 2 translates to the alphabet [-1, 0, 1, 2]. This function\n * exists only to simplify the external interface.\n*/\nIntegerVectorList BuildAlphabetFromBounds(const Eigen::VectorXi& lower_bound,\n                                          const Eigen::VectorXi& upper_bound) {\n  DRAKE_ASSERT(lower_bound.size() == upper_bound.size());\n\n  IntegerVectorList alphabet(lower_bound.size());\n  int cnt = 0;\n\n  for (auto& col_alphabet : alphabet) {\n    DRAKE_ASSERT(lower_bound(cnt) <= upper_bound(cnt));\n\n    for (int i = lower_bound(cnt); i <= upper_bound(cnt); i++) {\n      col_alphabet.push_back(i);\n    }\n    cnt++;\n  }\n\n  return alphabet;\n}\n\n/* If a column Ai of A is nonnegative (resp. nonpositive), then  {Ai*z : z \u2208 Qi}\n * is totally ordered, where Qi is the alphabet for the i\u1d57\u02b0 component. In other\n * words, the inequalities Ai z1 \u2264 Ai z2 \u2264 ... \u2264 Ai zm hold for zj \u2208 Qi\n * sorted in ascending (resp. descending) order. This allows for infeasibility\n * propagation in the recursive enumeration of integer solutions.  This function\n * detects when {Ai z : z \u2208 Qi} is totally ordered and then sorts the alphabet\n * using this ordering.\n */\nenum class ColumnType { Nonnegative, Nonpositive, Indefinite };\nstd::vector<ColumnType> ProcessInputs(const Eigen::MatrixXi& A,\n                                      IntegerVectorList* alphabet) {\n  DRAKE_ASSERT(alphabet);\n  int cnt = 0;\n  std::vector<ColumnType> column_type(A.cols(), ColumnType::Indefinite);\n\n  for (auto& col_alphabet : *alphabet) {\n    if (IsElementwiseNonnegative(A.col(cnt))) {\n      std::sort(col_alphabet.begin(), col_alphabet.end());\n      column_type[cnt] = ColumnType::Nonnegative;\n    } else if (IsElementwiseNonpositive(A.col(cnt))) {\n      std::sort(col_alphabet.begin(), col_alphabet.end(), std::greater<int>());\n      column_type[cnt] = ColumnType::Nonpositive;\n    }\n    cnt++;\n  }\n\n  return column_type;\n}\n\n/* Given an integer z and a list of integer vectors V, constructs\n * the Cartesian product (v, z) for all v \u2208 V */\nSolutionList CartesianProduct(const SolutionList& V, int z) {\n  SolutionList cart_products(V.rows(), V.cols() + 1);\n  cart_products << V, SolutionList::Constant(V.rows(), 1, z);\n\n  return cart_products;\n}\n\nSolutionList VerticalStack(const SolutionList& A,\n                              const SolutionList& B) {\n  DRAKE_ASSERT(A.cols() == B.cols());\n  if (A.rows() == 0) {\n    return B;\n  }\n  if (B.rows() == 0) {\n    return A;\n  }\n  SolutionList Y(A.rows() + B.rows(), B.cols());\n  Y << A, B;\n  return Y;\n}\n\n/* Find each solution (x(1), x(2), ..., x(n)) to Ax <= b when x(i) can only take\non values in a finite alphabet Qi, e.g., Qi = {1, 2, 3, 8, 9}.   We do this\nby recursively enumerating the solutions to\nA (x(1), x(2), ..., x(n-1) ) <= (b - A_n x_n) for all values of x(n). If the\ncolumn vectors {An*z : z \u2208 Qn} are totally ordered, we propagate infeasibility:\nif no solutions exist when x(n) = z, then no solution can exist if x(n) takes\non values larger than z (in the ordering).  We assume the function\n\"ProcessInputs\" was previously called to sort the alphabet in ascending order.\n*/\n// TODO(frankpermenter):  Update to use preallocated memory\nSolutionList FeasiblePoints(const Eigen::MatrixXi& A,\n                               const Eigen::VectorXi& b,\n                               const IntegerVectorList& column_alphabets,\n                               const std::vector<ColumnType>& column_type,\n                               int last_free_var_pos) {\n  DRAKE_ASSERT((last_free_var_pos >= 0) && (last_free_var_pos < A.cols()));\n  DRAKE_ASSERT(column_type.size() == static_cast<std::vector<ColumnType>\n                                                    ::size_type>(A.cols()));\n\n  SolutionList feasible_points(0, last_free_var_pos + 1);\n  for (const auto& value : column_alphabets[last_free_var_pos]) {\n    SolutionList new_feasible_points;\n\n    if (last_free_var_pos == 0) {\n      if (IsElementwiseNonnegative(b - A.col(0) * value)) {\n        new_feasible_points.resize(1, 1);\n        new_feasible_points(0, 0) = value;\n      }\n    } else {\n      new_feasible_points = CartesianProduct(\n          FeasiblePoints(A,\n                        b - A.col(last_free_var_pos) * value,\n                        column_alphabets,\n                        column_type,\n                        last_free_var_pos - 1), value);\n    }\n\n    if (new_feasible_points.rows() > 0) {\n      feasible_points = VerticalStack(feasible_points, new_feasible_points);\n    } else {\n      //  Propagate infeasibility: if this test passes, then no feasible\n      //  points exist for remaining values in the alphabet.\n      if (column_type[last_free_var_pos] != ColumnType::Indefinite) {\n        return feasible_points;\n      }\n    }\n  }\n\n  return feasible_points;\n}\n\n}  // namespace\n\nSolutionList EnumerateIntegerSolutions(\n    const Eigen::Ref<const Eigen::MatrixXi>& A,\n    const Eigen::Ref<const Eigen::VectorXi>& b,\n    const Eigen::Ref<const Eigen::VectorXi>& lower_bound,\n    const Eigen::Ref<const Eigen::VectorXi>& upper_bound) {\n  DRAKE_DEMAND(A.rows() == b.rows());\n  DRAKE_DEMAND(A.cols() == lower_bound.size());\n  DRAKE_DEMAND(A.cols() == upper_bound.size());\n\n  auto variable_alphabets = BuildAlphabetFromBounds(lower_bound, upper_bound);\n  // Returns type (nonnegative, nonpositive, or indefinite) of A's\n  // columns and sorts the variable alphabet accordingly.\n  auto column_type = ProcessInputs(A, &variable_alphabets);\n\n  return FeasiblePoints(A, b, variable_alphabets, column_type, A.cols()-1);\n}\n\n}  // namespace solvers\n}  // namespace drake\n", "meta": {"hexsha": "511c6fa7f295e335390eebda3247af17c4c71d58", "size": 6276, "ext": "cc", "lang": "C++", "max_stars_repo_path": "solvers/integer_inequality_solver.cc", "max_stars_repo_name": "RobotLocomotion/drake-python3.7", "max_stars_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-02-25T02:01:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-17T04:52:04.000Z", "max_issues_repo_path": "solvers/integer_inequality_solver.cc", "max_issues_repo_name": "RobotLocomotion/drake-python3.7", "max_issues_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "solvers/integer_inequality_solver.cc", "max_forks_repo_name": "RobotLocomotion/drake-python3.7", "max_forks_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-13T12:05:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-13T12:05:39.000Z", "avg_line_length": 35.8628571429, "max_line_length": 80, "alphanum_fraction": 0.6542383684, "num_tokens": 1606, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.6477982247516796, "lm_q1q2_score": 0.4794836377355817}}
{"text": "/// \\file\n/// Maintainer: Felice Serena\n///\n///\n\n#include \"uniform_grid.h\"\n#include <Eigen/Core>\n#include <set>\n\n#include <boost/test/unit_test.hpp>\n\nnamespace utf = boost::unit_test;\n\ntypedef std::vector<int> CellCoordinate;\n\nusing namespace MouseTrack;\nusing namespace Eigen;\n\nBOOST_AUTO_TEST_CASE(uniform_grid_4d) {\n  constexpr int Dim = 4;\n  typedef UniformGrid4d UG;\n  UG::PointList all(Dim, 5);\n  all.col(0) = Vector4d(0.0, 0.0, 0.0, 0.0);\n  all.col(1) = Vector4d(2.0, 2.0, 2.0, 2.0);\n  all.col(2) = Vector4d(10.0, 0.0, 0.0, 0.0);\n  all.col(3) = Vector4d(0.0, -1.0, -1.0, -1.0);\n  all.col(4) = Vector4d(10.0, 1.0, 1.0, 1.0);\n\n  std::multiset<PointIndex> expected0;\n  expected0.insert(2);\n  expected0.insert(4);\n\n  std::multiset<PointIndex> expected1;\n  expected1.insert(0);\n  expected1.insert(3);\n\n  UG oracle(2, 10.0 / 20);\n  oracle.compute(all);\n\n  Matrix<double, 4, 2> query;\n  query.col(0) = Vector4d(9.5, 0, 0, 0);\n  query.col(1) = Vector4d(0.1, 0.0, 0, 0);\n  auto result = oracle.find_in_range(query, 2);\n\n  std::multiset<PointIndex> received0(result[0].begin(), result[0].end());\n  std::multiset<PointIndex> received1(result[1].begin(), result[1].end());\n\n  BOOST_CHECK_EQUAL(expected0.size(), received0.size());\n  BOOST_CHECK_MESSAGE(\n      expected0 == received0,\n      \"Expected and received set do not contain same elements.\");\n\n  BOOST_CHECK_EQUAL(expected1.size(), received1.size());\n  BOOST_CHECK_MESSAGE(\n      expected1 == received1,\n      \"Expected and received set do not contain same elements.\");\n}\n\nBOOST_AUTO_TEST_CASE(uniform_grid_4d_two_close_points) {\n  constexpr int Dim = 4;\n  typedef UniformGrid4d UG;\n  UG::PointList all(Dim, 2);\n  all.col(0) = Vector4d(0.0, 0.0, 0.0, 0.0);\n  all.col(1) = Vector4d(0.1, 0.1, 0.1, 0);\n\n  UG oracle(2, 10.0 / 20);\n  oracle.compute(all);\n\n  std::multiset<PointIndex> expected;\n\n  // first test\n  expected.insert(0);\n  expected.insert(1);\n  auto result = oracle.find_in_range(Vector4d(0.0, 0, 0, 0), 1)[0];\n  std::multiset<PointIndex> received(result.begin(), result.end());\n\n  BOOST_CHECK_EQUAL(expected.size(), received.size());\n  BOOST_CHECK_MESSAGE(\n      expected == received,\n      \"Expected and received set do not contain same elements.\");\n}\n\nBOOST_AUTO_TEST_CASE(uniform_grid_Xd_find_closest) {\n  constexpr int Dim = 4;\n  typedef UniformGrid4d UG;\n  UG::PointList all(Dim, 5);\n  all.col(0) = Vector4d(0.0, 0.0, 0.0, 0.0);\n  all.col(1) = Vector4d(2.0, 2.0, 2.0, 2.0);\n  all.col(2) = Vector4d(10.0, 0.0, 0.0, 0.0);\n  all.col(3) = Vector4d(0.0, -1.0, -1.0, -1.0);\n  all.col(4) = Vector4d(10.0, 1.0, 1.0, 1.0);\n\n  UG oracle(2, 10.0 / 20);\n  oracle.compute(all);\n\n  std::vector<size_t> expected0;\n  expected0.push_back(4);\n\n  std::vector<size_t> expected1;\n  expected1.push_back(0);\n\n  Matrix<double, 4, 2> query;\n  query.col(0) = Vector4d(10.1, 0.9, 0.9, 0.9);\n  query.col(1) = Vector4d(0.1, 0.1, 0.1, 0.1);\n\n  auto result = oracle.find_closest(query, 1);\n  BOOST_CHECK_EQUAL(expected0.size(), result[0].size());\n  BOOST_CHECK_EQUAL(expected0[0], result[0][0]);\n\n  BOOST_CHECK_EQUAL(expected1.size(), result[1].size());\n  BOOST_CHECK_EQUAL(expected1[0], result[1][0]);\n}\n\nBOOST_AUTO_TEST_CASE(uniform_grid_Xd_find_closestK) {\n  constexpr int Dim = 4;\n  typedef UniformGrid4d UG;\n  UG::PointList all(Dim, 5);\n  all.col(0) = Vector4d(0.0, 0.0, 0.0, 0.0);\n  all.col(1) = Vector4d(2.0, 2.0, 2.0, 2.0);\n  all.col(2) = Vector4d(10.0, 0.0, 0.0, 0.0);\n  all.col(3) = Vector4d(0.0, -1.0, -1.0, -1.0);\n  all.col(4) = Vector4d(10.0, 1.0, 1.0, 1.0);\n\n  std::multiset<PointIndex> expected;\n  expected.insert(2);\n  expected.insert(4);\n\n  UG oracle(2, 10.0 / 20);\n  oracle.compute(all);\n\n  auto result = oracle.find_closest(Vector4d(10.1, 0.9, 0.9, 0.9), 2)[0];\n\n  std::multiset<PointIndex> received(result.begin(), result.end());\n\n  BOOST_CHECK_MESSAGE(\n      expected.size() == received.size(),\n      \"Expected and received sets have different cardinalities.\");\n  BOOST_CHECK_MESSAGE(\n      expected == received,\n      \"Expected and received set do not contain same elements.\");\n}\n", "meta": {"hexsha": "801dcb6f605513cec33a2829180432fd06e36a3d", "size": 4037, "ext": "cc", "lang": "C++", "max_stars_repo_path": "lib/spatial/uniform_grid.test.cc", "max_stars_repo_name": "itko/scanbox", "max_stars_repo_head_hexsha": "9a00c11eafb4cc2faa69bfcc76bdf0d8e295dcf3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-09T09:30:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-09T09:30:23.000Z", "max_issues_repo_path": "lib/spatial/uniform_grid.test.cc", "max_issues_repo_name": "itko/scanbox", "max_issues_repo_head_hexsha": "9a00c11eafb4cc2faa69bfcc76bdf0d8e295dcf3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 23.0, "max_issues_repo_issues_event_min_datetime": "2018-03-19T20:54:52.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-16T12:36:59.000Z", "max_forks_repo_path": "lib/spatial/uniform_grid.test.cc", "max_forks_repo_name": "itko/scanbox", "max_forks_repo_head_hexsha": "9a00c11eafb4cc2faa69bfcc76bdf0d8e295dcf3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-03-14T20:00:43.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-14T20:00:43.000Z", "avg_line_length": 28.4295774648, "max_line_length": 74, "alphanum_fraction": 0.6584097102, "num_tokens": 1474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.47948363270271493}}
{"text": "/**\n * @file k_means_clustering_engine.hpp\n * @brief\n * @author Piotr Smulewicz\n * @version 1.0\n * @date 2014-06-26\n */\n#ifndef PAAL_K_MEANS_CLUSTERING_ENGINE_HPP\n#define PAAL_K_MEANS_CLUSTERING_ENGINE_HPP\n\n#include \"paal/utils/type_functions.hpp\"\n#include \"paal/utils/functors.hpp\"\n#include \"paal/utils/irange.hpp\"\n\n#include <boost/range/combine.hpp>\n#include <boost/range/adaptor/indexed.hpp>\n#include <boost/range/algorithm_ext/iota.hpp>\n#include <boost/range/algorithm/for_each.hpp>\n\n#include <vector>\n#include <random>\n#include <iostream>\n\nnamespace paal {\n\n/**\n * @param lrange\n * @param rrange\n * @tparam RangeLeft\n * @tparam RangeRight\n */\ntemplate <class RangeLeft, class RangeRight>\nauto distance_square(RangeLeft && lrange, RangeRight && rrange) {\n    assert(!boost::empty(lrange));\n    assert(boost::distance(lrange) == boost::distance(rrange));\n\n    //TODO change to sum_functors when generic lambdas appears\n    decltype(*std::begin(lrange) * *std::begin(rrange)) dist{};\n    for (auto point_pair : boost::combine(lrange, rrange)) {\n        auto diff = boost::get<0>(point_pair) - boost::get<1>(point_pair);\n        dist += diff * diff;\n    }\n    return dist;\n}\n\n/**\n * @param point\n * @param centers\n * @tparam Point\n * @tparam Centers\n */\ntemplate <class Point, class Centers>\nauto closest_to(Point && point, Centers && centers){\n    using coor_t = range_to_elem_t<Point>;\n    auto dist = std::numeric_limits<coor_t>::max();\n    int new_center = 0;\n    for (auto center : centers | boost::adaptors::indexed()){\n        auto new_dist = distance_square(center.value(), point);\n\n        if (new_dist < dist) {\n            dist = new_dist;\n            new_center = center.index();\n        }\n    }\n    return new_center;\n}\n\n///k means visitor\nstruct k_means_visitor {\n    /**\n    * @param last_center\n    * @param new_center\n    * @tparam Center\n    * @tparam New_center\n    */\n    template <class Center, class New_center>\n    void move_center(Center &last_center, New_center &new_center) {};\n    ///new iteration\n    void new_iteration() {};\n};\n\n/**\n * @param points\n * @param centers\n * @param centroid functor return centroid of set of samples\n * @param closest_to\n * @param result pairs of point and id of cluster\n * (number from 0,1,2 ...,k-1)\n * @param c_equal\n * @param visitor\n * @tparam Points\n * @tparam Centers\n * @tparam Centroid\n * @tparam ClosestTo\n * @tparam OutputIterator\n * @tparam CentroidEqual\n * @tparam Visitor\n */\ntemplate <class Points,\n          class Centers,\n          class Centroid,\n          class ClosestTo, class OutputIterator,\n          class CentroidEqual = utils::equal_to,\n          class Visitor=k_means_visitor >\nauto k_means(Points &&points, Centers & centers,\n             Centroid centroid, ClosestTo closest_to,\n             OutputIterator result,\n             CentroidEqual c_equal = CentroidEqual{},\n             Visitor visitor=Visitor{}) {\n    using point_t = range_to_elem_t<Points>;\n    using points_bag = std::vector<point_t>;\n\n    std::vector<points_bag> cluster_points;\n    cluster_points.resize(centers.size());\n    bool zm;\n    do {\n        visitor.new_iteration();\n        zm = false;\n        boost::for_each(cluster_points, std::mem_fn(&points_bag::clear));\n\n        for (auto && point : points) {\n            cluster_points[closest_to(point)].push_back(point);\n        }\n\n        for (auto point : cluster_points | boost::adaptors::indexed()) {\n            if(point.value().empty()) continue;\n            auto && old_center = centers[point.index()];\n            auto && new_center = centroid(point.value());\n            if (!c_equal(new_center, old_center)) {\n                visitor.move_center(old_center, new_center);\n                old_center = new_center;\n                zm = true;\n            }\n        }\n    } while (zm == true);\n    for (int cur_cluster : irange(cluster_points.size())) {\n        for (auto const & point : cluster_points[cur_cluster]) {\n            *result = std::make_pair(point, cur_cluster);\n            ++result;\n        }\n    }\n    return centers;\n}\n\n/**\n * @param points\n * @param number_of_centers\n * @tparam Points\n */\ntemplate <typename Points, typename OutputIterator, typename RNG = std::default_random_engine>\nauto get_random_centers(Points &&points, int number_of_centers, OutputIterator out,\n                        RNG && rng = std::default_random_engine{}) {\n\n    std::vector<int> centers(points.size());\n    boost::iota(centers, 0);\n    std::shuffle(centers.begin(),centers.end(), rng);\n    centers.resize(number_of_centers);\n    for (auto && center : centers) {\n        *out=points[center];\n        ++out;\n    }\n}\n\n/**\n * @param points\n * @param number_of_clusters\n * @tparam Points\n */\ntemplate <typename Points, typename RNG = std::default_random_engine>\nauto get_random_clusters(Points &&points, int number_of_clusters,\n                         RNG && rng = std::default_random_engine{}) {\n    std::vector<typename std::decay<Points>::type> clusters(number_of_clusters);\n    std::uniform_int_distribution<> dis(0, number_of_clusters - 1);\n\n    for (auto o : points) {\n        clusters[distribution(rng)].push_back(o);\n    }\n    return clusters;\n}\n\n} //!paal\n\n#endif /* PAAL_K_MEANS_CLUSTERING_ENGINE_HPP */\n", "meta": {"hexsha": "c6b47b419aab8060b75c69a2d91c21d2201dbd72", "size": 5224, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/paal/clustering/k_means_clustering_engine.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/clustering/k_means_clustering_engine.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/clustering/k_means_clustering_engine.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": 28.3913043478, "max_line_length": 94, "alphanum_fraction": 0.6429938744, "num_tokens": 1253, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.47948363270271493}}
{"text": "//=============================================================================\n//\n//  CLASS NConstraintGmmInterface\n//\n//=============================================================================\n\n\n#ifndef COMISO_LINEARCONSTRAINT_HH\n#define COMISO_LINEARCONSTRAINT_HH\n\n\n//== INCLUDES =================================================================\n\n#include <CoMISo/Config/CoMISoDefines.hh>\n#include \"NConstraintInterface.hh\"\n#include <Eigen/StdVector>\n\n\n//== FORWARDDECLARATIONS ======================================================\n\n//== NAMESPACES ===============================================================\n\nnamespace COMISO {\n\n//== CLASS DEFINITION =========================================================\n\n\t      \n\n/** \\class NProblemGmmInterface NProblemGmmInterface.hh <ACG/.../NPRoblemGmmInterface.hh>\n\n    Brief Description.\n  \n    A more elaborate description follows.\n*/\nclass COMISODLLEXPORT LinearConstraint : public NConstraintInterface\n{\npublic:\n\n  // sparse vector type\n  typedef NConstraintInterface::SVectorNC SVectorNC;\n\n  // different types of constraints\n//  enum ConstraintType {NC_EQUAL, NC_LESS_EQUAL, NC_GREATER_EQUAL};\n\n  /// Default constructor\n  LinearConstraint(const ConstraintType _type = NC_EQUAL);\n\n  // linear equation of the form -> coeffs_^T *x  + b_=_type= 0\n  LinearConstraint(const SVectorNC& _coeffs, const double _b, const ConstraintType _type = NC_EQUAL);\n\n  /// Destructor\n  virtual ~LinearConstraint();\n\n  virtual int n_unknowns();\n\n  void  resize(const unsigned int _n);\n\n  const SVectorNC& coeffs() const;\n        SVectorNC& coeffs();\n\n  const double&    b() const;\n        double&    b();\n\n  virtual double eval_constraint ( const double* _x );\n  \n  virtual void eval_gradient( const double* _x, SVectorNC& _g      );\n\n  virtual void eval_hessian    ( const double* _x, SMatrixNC& _h      );\n\n  virtual bool is_linear() { return true;}\n\n  // inherited from base\n//  virtual ConstraintType  constraint_type (                                      ) { return type_; }\n\nprivate:\n\n  // linear equation of the form -> coeffs_^T * x + b_\n  SVectorNC coeffs_;\n  double    b_;\n};\n\n\n//=============================================================================\n} // namespace COMISO\n//=============================================================================\n// support std vectors\nEIGEN_DEFINE_STL_VECTOR_SPECIALIZATION(COMISO::LinearConstraint);\n//=============================================================================\n#endif // ACG_LINEARCONSTRAINT_HH defined\n//=============================================================================\n\n", "meta": {"hexsha": "11093c5e70e7b4bea6f12d0e83272e14f71122d9", "size": 2607, "ext": "hh", "lang": "C++", "max_stars_repo_path": "libs/quadwild/libs/CoMISo/NSolver/LinearConstraint.hh", "max_stars_repo_name": "Pentacode-IAFA/Quad-Remeshing", "max_stars_repo_head_hexsha": "f8fd4c10abf1c54656b38a00b8a698b952a85fe2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/quadwild/libs/CoMISo/NSolver/LinearConstraint.hh", "max_issues_repo_name": "Pentacode-IAFA/Quad-Remeshing", "max_issues_repo_head_hexsha": "f8fd4c10abf1c54656b38a00b8a698b952a85fe2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/quadwild/libs/CoMISo/NSolver/LinearConstraint.hh", "max_forks_repo_name": "Pentacode-IAFA/Quad-Remeshing", "max_forks_repo_head_hexsha": "f8fd4c10abf1c54656b38a00b8a698b952a85fe2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.3369565217, "max_line_length": 102, "alphanum_fraction": 0.5097813579, "num_tokens": 493, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.47948363270271493}}
{"text": "// Small executable to fill a PCD file\n// Author: Max Schwarz <max.schwarz@uni-bonn.de>\n\n#include <depth_filler/depth_filler.h>\n#include <depth_filler/domain_transform.h>\n\n#include <boost/program_options.hpp>\n\n#include <pcl/point_cloud.h>\n#include <pcl/point_types.h>\n#include <pcl/io/pcd_io.h>\n\nnamespace po = boost::program_options;\n\nvoid imagesToPointCloud(const cv::Mat_<float>& depth, const cv::Mat_<cv::Vec3b>& rgb,\n\t\tfloat fx, float fy, float cx, float cy,\n\t\tpcl::PointCloud<pcl::PointXYZRGB>& output)\n{\n\toutput.resize(rgb.rows*rgb.cols);\n\toutput.width = rgb.cols;\n\toutput.height = rgb.rows;\n\n\tunsigned int outputIdx = 0;\n\tfor(unsigned int y = 0; y < output.height; ++y)\n\t{\n\t\tfor(unsigned int x = 0; x < output.width; ++x)\n\t\t{\n\t\t\tpcl::PointXYZRGB& p = output[outputIdx];\n\n\t\t\tp.r = rgb(y,x)[2];\n\t\t\tp.g = rgb(y,x)[1];\n\t\t\tp.b = rgb(y,x)[0];\n\n\t\t\tp.z = depth(y,x);\n\t\t\tp.x = p.z * (x - cx) / fx;\n\t\t\tp.y = p.z * (y - cy) / fy;\n\n\t\t\toutputIdx++;\n\t\t}\n\t}\n}\n\nstruct Blob\n{\n\tstd::vector<cv::Point2i> pixels;\n\tcv::Rect rect;\n\n\tbool operator<(const Blob& other) const\n\t{ return pixels.size() > other.pixels.size(); }\n};\n\nvoid FindBlobs(const cv::Mat &binary, std::vector < Blob > &blobs)\n{\n    blobs.clear();\n\n    // Fill the label_image with the blobs\n    // 0  - background\n    // 1  - unlabelled foreground\n    // 2+ - labelled foreground\n\n    cv::Mat label_image;\n    binary.convertTo(label_image, CV_32SC1);\n\n    int label_count = 2; // starts at 2 because 0,1 are used already\n\n    for(int y=0; y < label_image.rows; y++) {\n        int *row = (int*)label_image.ptr(y);\n        for(int x=0; x < label_image.cols; x++) {\n            if(row[x] != 1) {\n                continue;\n            }\n\n            Blob blob;\n            cv::floodFill(label_image, cv::Point(x,y), label_count, &blob.rect, 0, 0, 8);\n\n            for(int i=blob.rect.y; i < (blob.rect.y+blob.rect.height); i++) {\n                int *row2 = (int*)label_image.ptr(i);\n                for(int j=blob.rect.x; j < (blob.rect.x+blob.rect.width); j++) {\n                    if(row2[j] != label_count) {\n                        continue;\n                    }\n\n                    blob.pixels.push_back(cv::Point2i(j,i));\n                }\n            }\n\n            blobs.push_back(blob);\n\n            label_count++;\n        }\n    }\n}\n\nint main(int argc, char** argv)\n{\n\tfloat fx = NAN;\n\tfloat fy = NAN;\n\tfloat cx = -1;\n\tfloat cy = -1;\n\tunsigned int erode = 0;\n\tunsigned int subsample = 1;\n\n\tpo::options_description desc(\"Options\");\n\tdesc.add_options()\n\t\t(\"help\", \"produce help message\")\n\t\t(\"fx\", po::value<float>(), \"set focal length (x)\")\n\t\t(\"fy\", po::value<float>(), \"set focal length (y)\")\n\t\t(\"cx\", po::value<float>(), \"set optical center (x)\")\n\t\t(\"cy\", po::value<float>(), \"set optical center (y)\")\n\t\t(\"benchmark\", \"Run 20 times for profiling\")\n\t\t(\"erode\", po::value<unsigned int>(), \"erode depth with specified kernel half-size\")\n\t\t(\"subsample\", po::value<unsigned int>(), \"subsample input\")\n\t\t(\"dump\", po::value<std::string>(), \"dump sparse system under prefix\")\n\t\t(\"dump-prefill\", po::value<std::string>(), \"dump prefill cloud\")\n\t\t(\"dump-input\", po::value<std::string>(), \"dump (subsampled) input cloud\")\n\t\t(\"method\", po::value<std::string>()->default_value(\"domain\"), \"method (domain or opt)\")\n\t;\n\n\tpo::options_description hidden(\"Hidden\");\n\thidden.add_options()\n\t\t(\"input-file\", po::value<std::string>(), \"input file\")\n\t\t(\"output-file\", po::value<std::string>(), \"output file\")\n\t;\n\n\tpo::options_description cmdline;\n\tcmdline.add(desc).add(hidden);\n\n\tpo::positional_options_description p;\n\tp.add(\"input-file\", 1);\n\tp.add(\"output-file\", 1);\n\n\tpo::variables_map vm;\n\tpo::store(po::command_line_parser(argc, argv).options(cmdline).positional(p).run(), vm);\n\tpo::notify(vm);\n\n\tif(vm.count(\"help\"))\n\t{\n\t\tstd::cout << desc << \"\\n\";\n\t\treturn 1;\n\t}\n\n\tif(!vm.count(\"input-file\") || !vm.count(\"output-file\"))\n\t{\n\t\tfprintf(stderr, \"Require input and output file!\\n\");\n\t\tstd::cerr << desc << \"\\n\";\n\t\treturn 1;\n\t}\n\n\tpcl::PointCloud<pcl::PointXYZRGB> input;\n\tpcl::io::loadPCDFile(vm[\"input-file\"].as<std::string>(), input);\n\n\tif(input.size() == 0)\n\t{\n\t\tfprintf(stderr, \"Could not read input file\\n\");\n\t\treturn 1;\n\t}\n\n\tif(!input.isOrganized())\n\t{\n\t\tfprintf(stderr, \"Error: Input is not organized!\\n\");\n\t\treturn 1;\n\t}\n\n\tif(vm.count(\"fx\") && vm.count(\"fy\") && vm.count(\"cx\") && vm.count(\"cy\"))\n\t{\n\t\tfx = vm[\"fx\"].as<float>();\n\t\tfy = vm[\"fy\"].as<float>();\n\t\tcx = vm[\"cx\"].as<float>();\n\t\tcy = vm[\"cy\"].as<float>();\n\t}\n\telse\n\t{\n\t\t// Estimate from PCD...\n\t\tcx = input.width/2 + 0.5f;\n\t\tcy = input.height/2 + 0.5f;\n\t\tfx = 0.0f;\n\t\tfy = 0.0f;\n\t\tunsigned int count = 0;\n\n\t\tunsigned int idx = 0;\n\t\tfor(int y = 0; y < (int)input.height; ++y)\n\t\t{\n\t\t\tfor(int x = 0; x < (int)input.width; ++x)\n\t\t\t{\n\t\t\t\tconst auto& point = input[idx++];\n\n\t\t\t\tif(!std::isfinite(point.z))\n\t\t\t\t\tcontinue;\n\n\t\t\t\tif((x - cx) * (y - cy) * point.z != 0)\n\t\t\t\t{\n\t\t\t\t\tfx += point.z / point.x * (x - cx);\n\t\t\t\t\tfy += point.z / point.y * (y - cy);\n\t\t\t\t\tcount++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfx /= count;\n\t\tfy /= count;\n\n\t\tprintf(\"Calculated focal lengths: fx=%f, fy=%f\\n\", fx, fy);\n\t}\n\n\tif(vm.count(\"subsample\"))\n\t{\n\t\tsubsample = vm[\"subsample\"].as<unsigned int>();\n\t\tfx /= subsample;\n\t\tfy /= subsample;\n\t\tcx = (cx - 0.5f) / subsample + 0.5f;\n\t\tcy = (cy - 0.5f) / subsample + 0.5f;\n\t}\n\n\tcv::Mat_<float> depth(input.height/subsample, input.width/subsample);\n\tdepth = NAN;\n\n\tcv::Mat_<cv::Vec3b> rgb(input.height, input.width);\n\n\tint inputIdx = 0;\n\tfor(unsigned int y = 0; y < input.height; ++y)\n\t{\n\t\tfor(unsigned int x = 0; x < input.width; ++x)\n\t\t{\n\t\t\tconst auto& point = input[inputIdx];\n\n\t\t\tauto dx = x / subsample;\n\t\t\tauto dy = y / subsample;\n\n\t\t\tif(std::isnan(depth(dy,dx)) || depth(dy,dx) > point.z)\n\t\t\t\tdepth(dy,dx) = point.z;\n\n\t\t\trgb(y,x) = cv::Vec3b(point.b, point.g, point.r);\n\n\t\t\tinputIdx++;\n\t\t}\n\t}\n\n\tcv::Mat_<cv::Vec3b> rgbOut;\n\tcv::resize(rgb, rgbOut, cv::Size(rgb.cols / subsample, rgb.rows / subsample), fx, fy, cv::INTER_AREA);\n\n\tpcl::PointCloud<pcl::PointXYZRGB> output;\n\n\tif(vm.count(\"dump-input\"))\n\t{\n\t\timagesToPointCloud(depth, rgbOut, fx, fy, cx, cy, output);\n\t\tif(pcl::io::savePCDFileBinary(vm[\"dump-input\"].as<std::string>(), output) < 0)\n\t\t{\n\t\t\tfprintf(stderr, \"Could not write prefill file\\n\");\n\t\t}\n\t}\n\n\tdepth_filler::DepthFiller filler;\n\n\t// Fill in holes in depth data under very strict conditions\n\tcv::Mat_<float> tmp = filler.prefill(depth);\n\tdepth = tmp;\n\n\tif(vm.count(\"erode\"))\n\t{\n\t\terode = vm[\"erode\"].as<unsigned int>();\n\t\tfiller.erodeDepth(depth, depth, erode);\n\t}\n\n\tcv::Mat_<float> filled;\n\n\tif(vm[\"method\"].as<std::string>() == \"opt\")\n\t{\n\t\tif(!vm.count(\"benchmark\"))\n\t\t\tfilled = filler.fillDepth(depth, rgbOut);\n\t\telse\n\t\t{\n\t\t\tfor(int i = 0; i < 20; ++i)\n\t\t\t\tfilled = filler.fillDepth(depth, rgbOut);\n\t\t}\n\t}\n\telse if(vm[\"method\"].as<std::string>() == \"domain\")\n\t{\n\t\tcv::Mat_<uint8_t> grayU;\n\t\tcv::cvtColor(rgbOut, grayU, cv::COLOR_BGR2GRAY);\n\t\tcv::Mat_<float> gray;\n\t\tgrayU.convertTo(gray, CV_32FC1);\n\n\t\tdepth_filler::DomainTransformFiller dmFiller;\n\n\t\tif(!vm.count(\"benchmark\"))\n\t\t\tfilled = dmFiller.fillDepth(depth, gray);\n\t\telse\n\t\t{\n\t\t\tfor(int i = 0; i < 600; ++i)\n\t\t\t\tfilled = dmFiller.fillDepth(depth, gray);\n\t\t}\n\t}\n\telse\n\t\tthrow std::runtime_error(\"Unknown method specified\");\n\n\timagesToPointCloud(filled, rgbOut, fx, fy, cx, cy, output);\n\tif(pcl::io::savePCDFileBinary(vm[\"output-file\"].as<std::string>(), output) < 0)\n\t{\n\t\tfprintf(stderr, \"Could not write output file\\n\");\n\t}\n\n\tif(vm.count(\"dump-prefill\"))\n\t{\n\t\timagesToPointCloud(depth, rgbOut, fx, fy, cx, cy, output);\n\t\tif(pcl::io::savePCDFileBinary(vm[\"dump-prefill\"].as<std::string>(), output) < 0)\n\t\t{\n\t\t\tfprintf(stderr, \"Could not write prefill file\\n\");\n\t\t}\n\t}\n\n\tif(vm.count(\"dump\"))\n\t{\n\t\tfiller.dumpSystem(vm[\"dump\"].as<std::string>());\n\t}\n\n\treturn 0;\n}\n", "meta": {"hexsha": "aa59df35cbdc92b37e241ac3ba3f3872b3c03488", "size": 7752, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depth_filler/src/fill_pcd.cpp", "max_stars_repo_name": "warehouse-picking-automation-challenges/nimbro_picking", "max_stars_repo_head_hexsha": "857eee602beea9eebee45bbb67fce423b28f9db6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2017-11-02T03:05:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-02T19:40:15.000Z", "max_issues_repo_path": "depth_filler/src/fill_pcd.cpp", "max_issues_repo_name": "warehouse-picking-automation-challenges/nimbro_picking", "max_issues_repo_head_hexsha": "857eee602beea9eebee45bbb67fce423b28f9db6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "depth_filler/src/fill_pcd.cpp", "max_forks_repo_name": "warehouse-picking-automation-challenges/nimbro_picking", "max_forks_repo_head_hexsha": "857eee602beea9eebee45bbb67fce423b28f9db6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2017-09-16T02:20:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-24T14:06:35.000Z", "avg_line_length": 24.3773584906, "max_line_length": 103, "alphanum_fraction": 0.5964912281, "num_tokens": 2428, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.740174350576073, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.47948362527704064}}
{"text": "#include <gtest/gtest.h>\n\n#include \"scheme/objective/voxel/FieldCache.hh\"\n\n#include <random>\n#include <boost/foreach.hpp>\n\n#include <sstream>\n\nnamespace scheme { namespace objective { namespace voxel { namespace fctest {\n\nusing std::cout;\nusing std::endl;\n\n\nstruct Ellipse3D : Field3D <double> {\n\tstatic size_t ncalls;\n\tstatic double sqr(double f) { return f*f; }\n\tdouble c1,c2,c3,sd1,sd2,sd3;\n\tEllipse3D() : c1(0),c2(0),c3(0),sd1(1),sd2(1),sd3(1) {}\n\tEllipse3D(double a,double b,double c,double d,double e,double f) : c1(a),c2(b),c3(c),sd1(d),sd2(e),sd3(f) {}\t\n\tdouble operator()(double f, double g, double h) const { \n\t\t++ncalls;\n\t\treturn 10.0+std::exp( -sqr((f-c1)/sd1) - sqr((g-c2)/sd2) - sqr((h-c3)/sd3) );\n\t}\n\ttemplate<class F3> double operator()(F3 const & f3) const { return this->operator()(f3[0],f3[1],f3[2]); }\n};\nsize_t Ellipse3D::ncalls = 0;\n\n\ntemplate<class Cache,class Field>\ndouble test_cache_vs_field(Cache const & cache, Field field, int nsamp=10000){\n\t// cout << cache.num_elements()/1000000.0 <<\"M\" << endl;\n\tBOOST_STATIC_ASSERT((Cache::DIM==3));\n\ttypedef util::SimpleArray<3,double> F3;\n\tstd::mt19937 rng((unsigned int)time(0));\n\tstd::uniform_real_distribution<> uniform;\n\tdouble maxerr = 0.0;\n\tfor(int i = 0; i < nsamp; ++i){\n\t\tF3 samp = F3(uniform(rng),uniform(rng),uniform(rng)) * (cache.ub_-cache.lb_) + cache.lb_;\n\t\tdouble cacheval = cache[samp];\n\t\tdouble fieldval = field(samp);\n\t\t// std::cout << cacheval << \" \" << fieldval << std::endl;\n\t\tmaxerr = std::max( std::abs(fieldval-cacheval), maxerr );\n\t\tif( std::abs(fieldval-cacheval) > 10.0 ){\n\t\t\tcout << samp << \" \" << fieldval << \" \" << cacheval << endl;\n\t\t\tcout << cache.lb_ << endl;\n\t\t\tcout << cache.ub_ << endl;\t\t\t\n\t\t}\n\t}\n\treturn maxerr;\n}\n\nTEST(FieldCache,test_accuracy_random){\n\n\tEllipse3D field(1,2,3,4,5,6);\n\tASSERT_FLOAT_EQ( field(1,2,3), 11.0 );\n\n\tASSERT_LE( test_cache_vs_field( FieldCache3D<double>(field,-10,13,1.6), field, 100000 ), 0.30 );\n\tASSERT_LE( test_cache_vs_field( FieldCache3D<double>(field,-10,13,0.8), field, 100000 ), 0.15 );\n\tASSERT_LE( test_cache_vs_field( FieldCache3D<double>(field,-10,13,0.4), field, 100000 ), 0.08 );\n\tASSERT_LE( test_cache_vs_field( FieldCache3D<double>(field,-10,13,0.2), field, 100000 ), 0.04 );\n\n}\n\nTEST(FieldCache,test_file_cache){\n\t#ifdef CEREAL\n\t\tstd::string tmpfile = \"FieldCache_test_file.bin.gz\";\n\t\tif(boost::filesystem::exists(tmpfile)) boost::filesystem::remove(tmpfile);\n\t\t\n\t\tEllipse3D field(1,2,3,4,5,6);\n\t\tFieldCache3D<double> f1(field,-11,13,1.6,tmpfile);\n\t\tsize_t ncalls = Ellipse3D::ncalls;\n\n\t\tFieldCache3D<double> f2(field,-11,13,1.6,tmpfile);\n\n\t\tASSERT_EQ( Ellipse3D::ncalls, ncalls ); // field not called again\n\t\tASSERT_EQ( f1 , f2 );\n\n\t\tcout << \"PING 81\" << endl;\n\n\t\tf1.resize( util::SimpleArray<3,size_t>(0,0,0) ); // spoil the cache\n\t\tio::write_cache(tmpfile,f1);\n\n\t\tstd::cout << \"NOTE: the bounds-mismatch warning below is expected:\" << std::endl;\n\t\tFieldCache3D<double> f3(field,-11,13,1.6,tmpfile);\n\t\tASSERT_NE( Ellipse3D::ncalls, ncalls ); // field must be called again\n\t\tASSERT_EQ( f2.shape()[0] , f3.shape()[0] );\n\t\tASSERT_EQ( f2.shape()[1] , f3.shape()[1] );\n\t\tASSERT_EQ( f2.shape()[2] , f3.shape()[2] );\t\t\n\t\tASSERT_EQ( f2 , f3 );\n\t#endif\n\n}\n\nTEST(BoundingFieldCache,test_bounding_ellipse_max){\n\ttypedef util::SimpleArray<3,double> F3;\n\tEllipse3D field(1,2,3,4,5,6);\n\tFieldCache3D<double> f1(field,-11,13,0.824234);\n\tBoundingFieldCache3D<double,AggMax> bf1(f1,2.873,1.234);\n\n\tstd::mt19937 rng((unsigned int)time(0));\n\tstd::uniform_real_distribution<> uniform;\n\tfor(int i = 0; i < 10000; ++i){\n\t\tF3 idx = F3( uniform(rng), uniform(rng), uniform(rng) ) * (f1.ub_-f1.lb_) + f1.lb_;\n\t\tif( f1[idx] > bf1[idx] ) cout << idx << endl;\n\t\tASSERT_LE( f1[idx] , bf1[idx] );\n\t}\n}\n\nstruct Delta : Field3D<double> {\n\tdouble operator()(double f, double g, double h) const { \n\t\tif( fabs(f) < 0.1 && fabs(g) < 0.1 && fabs(h) < 0.1 ) return 1.0;\n\t\treturn 0;\n\t}\n\n};\n\nTEST(BoundingFieldCache,test_bounding_delta){\n\ttypedef util::SimpleArray<3,double> F3;\n\tDelta delta;\n\tASSERT_EQ( delta(0.0,0.0,0.0), 1 );\n\tASSERT_EQ( delta(0.2,0.0,0.0), 0 );\t\n\tFieldCache3D<double> f1(delta,-7.5,7.5,1.0);\n\tASSERT_EQ( f1[F3(0,0,0)], 1.0 );\n\tdouble sum = 0; for(size_t i = 0; i < f1.num_elements(); ++i) sum += f1.data()[i];\n\tASSERT_EQ( sum, 1.0 );\n\n\tdouble spread = 5.4;\n\tBoundingFieldCache3D<double,AggMax> bf1(f1,spread,1.0);\n\tstd::mt19937 rng((unsigned int)time(0));\n\tstd::uniform_real_distribution<> uniform;\n\tfor(int i = 0; i < 100000; ++i){\n\t\tF3 idx = F3( uniform(rng), uniform(rng), uniform(rng) ) * (bf1.ub_-bf1.lb_) + bf1.lb_;\n\t\t// if( idx.norm() < spread-sqrt(3.0) && bf1[idx]!=1.0) cout << \"FAIL1 \" << idx << \" \" << idx.norm()-spread << endl;\n\t\t// if( idx.norm() > spread+sqrt(3.0) && bf1[idx]!=0.0) cout << \"FAIL0 \" << idx << \" \" << idx.norm()-spread << endl;\t\n\t\t// not sure if cell diagonal sqrt(3) is tight bound here... seems like it should be sqrt(3)/2...\n\t\tif( idx.norm() < spread-sqrt(3.0) ) ASSERT_EQ( bf1[idx], 1.0 );\n\t\tif( idx.norm() > spread+sqrt(3.0) ) ASSERT_LE( bf1[idx], 0.00000000001 ); // can be \"uninitialized\" vals in corners\n\t}\n}\n\n\n}}}}\n", "meta": {"hexsha": "0ccc230803a9e057e2063b9913682e27727ed39a", "size": 5089, "ext": "cc", "lang": "C++", "max_stars_repo_path": "schemelib/scheme/objective/voxel/FieldCache.gtest.cc", "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/objective/voxel/FieldCache.gtest.cc", "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/objective/voxel/FieldCache.gtest.cc", "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": 35.0965517241, "max_line_length": 118, "alphanum_fraction": 0.6521910002, "num_tokens": 1802, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.7401743505760728, "lm_q1q2_score": 0.4794836252770406}}
{"text": "/**\n * @file test_IO.cc\n * @author Pedro Henrique S. Perrusi (pedro.perrusi@gmail.com)\n * @brief Unitest module for the bunny_mesh/data_io.h file.\n * @version 1.0\n * @date 2019-02-10\n * \n * @copyright Copyright (c) 2019 Pedro Henrique S. Perrusi\n * \n */\n#include \"gtest/gtest.h\"\n#include \"bunny_mesh/data_io.h\"\n\n#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace bunny_dataIO;\n\n/**\n * @brief Tests writing and reading integers between numpy array and eigen\n */\nTEST(IO, Write_Read_Int)\n{\n    const std::string filename = \"test/data/sequential_int.npy\";\n    // loads a simple matrix\n    IndexMatrixType matEigen(3,3); \n    matEigen << 1, 2, 3,\n                4, 5, 6,\n                7, 8, 9;\n    // writes it to file\n    saveIntMatrixToNumpyArray(filename, matEigen);\n    \n    // reads same matrix from file\n    IndexMatrixType matNumpy;\n    matNumpy = readIntNumPyArray(filename);\n    \n    // Begin testing...\n    ASSERT_EQ(matEigen.rows(), matNumpy.rows());\n    ASSERT_EQ(matEigen.cols(), matNumpy.cols());\n    ASSERT_TRUE(matEigen.isApprox(matNumpy));\n}\n\n/**\n * @brief Tests writing and reading doubles between numpy array and eigen\n */\nTEST(IO, Write_Read_Double)\n{\n    const std::string filename = \"test/data/sequential_double.npy\";\n    // loads a simple matrix\n    Point3DMatrixType matEigen(3,3); \n    matEigen << 1.1, 2.2, 3.3,\n                4.4, 5.5, 6.6,\n                7.7, 8.8, 9.9;\n    // writes it to file\n    saveMatrixToNumpyArray(filename, matEigen);\n    \n    // reads same matrix from file\n    Point3DMatrixType matNumpy;\n    matNumpy = readFloatNumPyArray(filename);\n    \n    // Begin testing...\n    ASSERT_EQ(matEigen.rows(), matNumpy.rows());\n    ASSERT_EQ(matEigen.cols(), matNumpy.cols());\n    ASSERT_TRUE(matEigen.isApprox(matNumpy));\n}", "meta": {"hexsha": "903731e4946343ae1991a806c04f7c3727e7794a", "size": 1773, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/test_IO.cc", "max_stars_repo_name": "pedroperrusi/bunny_mesh_normals", "max_stars_repo_head_hexsha": "2fc828667cc0cb07fed36e5b7b5618545e100cfe", "max_stars_repo_licenses": ["MIT"], "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_IO.cc", "max_issues_repo_name": "pedroperrusi/bunny_mesh_normals", "max_issues_repo_head_hexsha": "2fc828667cc0cb07fed36e5b7b5618545e100cfe", "max_issues_repo_licenses": ["MIT"], "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_IO.cc", "max_forks_repo_name": "pedroperrusi/bunny_mesh_normals", "max_forks_repo_head_hexsha": "2fc828667cc0cb07fed36e5b7b5618545e100cfe", "max_forks_repo_licenses": ["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.2769230769, "max_line_length": 74, "alphanum_fraction": 0.6525662719, "num_tokens": 500, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982043529716, "lm_q2_score": 0.7401743505760728, "lm_q1q2_score": 0.4794836152113069}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2004, 2005, 2006, 2007 Ferdinando Ametrano\n Copyright (C) 2004, 2005, 2006, 2007, 2008 StatPro Italia srl\n Copyright (C) 2015 CompatibL\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/types.hpp>\n#include <ql/settings.hpp>\n#include <ql/version.hpp>\n#include <boost/test/unit_test.hpp>\n#include <boost/timer.hpp>\n\n/* Use BOOST_MSVC instead of _MSC_VER since some other vendors (Metrowerks,\n   for example) also #define _MSC_VER\n*/\n#ifdef BOOST_MSVC\n#  include <ql/auto_link.hpp>\n#  define BOOST_LIB_NAME boost_unit_test_framework\n#  include <boost/config/auto_link.hpp>\n#  undef BOOST_LIB_NAME\n\n/* uncomment the following lines to unmask floating-point exceptions.\n   See http://www.wilmott.com/messageview.cfm?catid=10&threadid=9481\n*/\n//#  include <float.h>\n//   namespace { unsigned int u = _controlfp(_EM_INEXACT, _MCW_EM); }\n\n#endif\n\n#include <iostream>\n#include <iomanip>\n#include \"utilities.hpp\"\n\n#include \"adjointcreditdefaultswaptest.hpp\"\n#include \"adjointzerospreadedtermstructuretest.hpp\"\n#include \"adjointtermstructuretest.hpp\"\n#include \"adjointbermudanswaptiontest.hpp\"\n#include \"adjointeuropeanoptionportfoliotest.hpp\"\n#include \"adjointmatricestest.hpp\"\n#include \"adjointswaptionvolatilitycubetest.hpp\"\n#include \"adjointpathgeneratortest.hpp\"\n#include \"adjointpiecewiseyieldcurvetest.hpp\"\n#include \"adjointmarketmodelcalibrationtest.hpp\"\n#include \"adjointswaptiontest.hpp\"\n#include \"adjointgjrgarchmodeltest.hpp\"\n#include \"adjointgreekstest.hpp\"\n#include \"adjointpiecewiseyieldcurvetest.hpp\"\n#include \"adjointshortratemodelstest.hpp\"\n#include \"adjointblackformulatest.hpp\"\n#include \"adjointbondportfoliotest.hpp\"\n#include \"adjointdistributiontest.hpp\"\n#include \"adjointrealmathtest.hpp\"\n#include \"adjointdefaultprobabilitycurvetest.hpp\"\n#include \"adjointswaptest.hpp\"\n#include \"adjointvariategeneratorstest.hpp\"\n#include \"adjointfraportfoliotest.hpp\"\n\n#include \"adjointarraytest.hpp\"\n\n#include \"adjointcomplextest.hpp\"\n#include \"adjointfastfouriertransformtest.hpp\"\n#include \"adjointhestonprocesstest.hpp\"\n#include \"adjointbatesmodeltest.hpp\"\n#include \"adjointspecialfunctionstest.hpp\"\n\nusing namespace boost::unit_test_framework;\n\nnamespace {\n\n    boost::timer t;\n\n    void startTimer() { t.restart(); }\n    void stopTimer() {\n        double seconds = t.elapsed();\n        int hours = int(seconds/3600);\n        seconds -= hours * 3600;\n        int minutes = int(seconds/60);\n        seconds -= minutes * 60;\n        std::cout << \" \\nTests completed in \";\n        if (hours > 0)\n            std::cout << hours << \" h \";\n        if (hours > 0 || minutes > 0)\n            std::cout << minutes << \" m \";\n        std::cout << std::fixed << std::setprecision(0)\n                  << seconds << \" s\\n\" << std::endl;\n    }\n\n    void configure() {\n        /* if needed, either or both the lines below can be\n           uncommented and/or changed to run the test suite with a\n           different configuration. In the future, we'll need a\n           mechanism that doesn't force us to recompile (possibly a\n           couple of command-line flags for the test suite?)\n        */\n\n        //QuantLib::Settings::instance().includeReferenceDateCashFlows() = true;\n        //QuantLib::Settings::instance().includeTodaysCashFlows() = boost::none;\n    }\n\n}\n\n#if defined(QL_ENABLE_SESSIONS)\nnamespace QuantLib {\n\n    Integer sessionId() { return 0; }\n\n}\n#endif\n\ntest_suite* init_unit_test_suite(int, char* []) {\n\n    std::string header =\n        \" Testing \"\n            #ifdef BOOST_MSVC\n            QL_LIB_NAME\n            #else\n            \"QuantLib \" QL_VERSION\n            #endif\n        \"\\n  QL_NEGATIVE_RATES \"\n            #ifdef QL_NEGATIVE_RATES\n            \"       defined\"\n            #else\n            \"     undefined\"\n            #endif\n        \"\\n  QL_EXTRA_SAFETY_CHECKS \"\n            #ifdef QL_EXTRA_SAFETY_CHECKS\n            \"  defined\"\n            #else\n            \"undefined\"\n            #endif\n        \"\\n  QL_USE_INDEXED_COUPON \"\n            #ifdef QL_USE_INDEXED_COUPON\n            \"   defined\"\n            #else\n            \" undefined\"\n            #endif\n         ;\n\n    std::string rule = std::string(35, '=');\n\n    BOOST_TEST_MESSAGE(rule);\n    BOOST_TEST_MESSAGE(header);\n    BOOST_TEST_MESSAGE(rule);\n    test_suite* test = BOOST_TEST_SUITE(\"QuantLib test suite\");\n\n    test->add(QUANTLIB_TEST_CASE(startTimer));\n    test->add(QUANTLIB_TEST_CASE(configure));\n\n//#   define CL_CERTAIN_TEST AdjointArrayTest\n\n#if defined CL_CERTAIN_TEST\n    test->add(CL_CERTAIN_TEST::suite());\n#endif\n\n#if !defined CL_ENABLE_BOOST_TEST_ADAPTER && !defined CL_CERTAIN_TEST\n    test->add(AdjointBondPortfolioTest::suite());\n    test->add(AdjointCreditDefaultSwapTest::suite());\n    test->add(AdjointEuropeanOptionPortfolioTest::suite());\n    test->add(AdjointGjrgarchModelTest::suite());\n    test->add(AdjointFRAPortfolioTest::suite());\n    test->add(AdjointMarketModelCalibrationTest::suite());\n    test->add(AdjointMatricesTest::suite());\n    test->add(AdjointPathGeneratorTest::suite());\n    test->add(AdjointPiecewiseYieldCurveTest::suite());\n    test->add(AdjointZeroSpreadedTermStructureTest::suite());\n    test->add(AdjointShortRateModelsTest::suite());\n    test->add(AdjointSwaptionTest::suite());\n    test->add(AdjointSwaptionVolatilityCubeTest::suite());\n    test->add(AdjointDistributionTest::suite());\n    test->add(AdjointRealMathTest::suite());\n    test->add(AdjointDefaultProbabilityCurveTest::suite());\n    test->add(AdjointSwapTest::suite());\n    test->add(AdjointVariateGeneratorsTest::suite());\n\n\n# if defined FIXED_\n    test->add(AdjointArrayTest::suite());\n# endif\n\n    //!!! Temporarily commented out until compilation error is fixed\n    // test->add(AdjointGreeksTest::suite());\n\n    test->add(AdjointHestonProcessTest::suite());\n\n    // Complex Differentiation test\n#if defined CL_TAPE_COMPLEX_ENABLED\n    test->add(AdjointComplexTest::suite());\n    test->add(AdjointFastFourierTransformTest::suite());\n    test->add(AdjointBatesModelTest::suite());\n    test->add(AdjointSpecialFunctionsTest::suite());\n#endif\n\n    // very slow\n    test->add(AdjointBermudanSwaptionTest::suite());\n    test->add(AdjointBlackFormulaTest::suite());\n    test->add(AdjointTermStructureTest::suite());\n#endif\n\n    test->add(QUANTLIB_TEST_CASE(stopTimer));\n\n    return test;\n}\n", "meta": {"hexsha": "5bd58964c3def540ec0550946f886d34184b337e", "size": 7030, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test-suite-adjoint/quantlibtestsuite.cpp", "max_stars_repo_name": "fduffy/QuantLibAdjoint", "max_stars_repo_head_hexsha": "d9d355db4f46824bb5e607e28381943aef994ed4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 41.0, "max_stars_repo_stars_event_min_datetime": "2016-03-19T02:31:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T13:23:20.000Z", "max_issues_repo_path": "test-suite-adjoint/quantlibtestsuite.cpp", "max_issues_repo_name": "fduffy/QuantLibAdjoint", "max_issues_repo_head_hexsha": "d9d355db4f46824bb5e607e28381943aef994ed4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test-suite-adjoint/quantlibtestsuite.cpp", "max_forks_repo_name": "fduffy/QuantLibAdjoint", "max_forks_repo_head_hexsha": "d9d355db4f46824bb5e607e28381943aef994ed4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2016-03-17T14:14:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T10:33:19.000Z", "avg_line_length": 32.247706422, "max_line_length": 80, "alphanum_fraction": 0.6954480797, "num_tokens": 1792, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6791787121629466, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.4793541662702307}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// ordered_sample.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_EMPIRICAL_DISTRIBUTION_ORDERED_SAMPLE_HPP_ER_2010\n#define BOOST_STATISTICS_DETAIL_NON_PARAMETRIC_EMPIRICAL_DISTRIBUTION_ORDERED_SAMPLE_HPP_ER_2010\n#include <map>\n#include <functional>\n\n#include <boost/mpl/placeholders.hpp>\n#include <boost/mpl/apply.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\nnamespace boost { \nnamespace statistics{\nnamespace detail{\nnamespace empirical_distribution{\n\n    // Usage:\n    //     namespace ns = empirical_distribution;\n    //     accumulator_set<T,stats<ns::tag::ordered_sample> > acc;\n    //     acc = boost:for_each(samples,acc);\n    //     ns::extract::ordered_sample(acc);\n    // The result of the last statement is a sorted map associating each value \n    // in the sample (of type T) with their number of occurences in the sample.\n\nnamespace impl{\n\n    template<typename T>\n    class ordered_sample : public boost::accumulators::accumulator_base{\n        typedef std::less<T> comp_;\n        typedef std::size_t size_;\n        typedef boost::accumulators::dont_care dont_care_;\n        typedef std::map<T,size_,comp_> map_;\n\n        public:\n\t\t\n        // See accumulator_set for convention naming sample_type\n        typedef T \t\tsample_type; \n        typedef size_ \tsize_type;\t \n\n        // non-const because map::operator[](key) returns a non-const\n        typedef map_& result_type;\n\n        ordered_sample(dont_care_){}\n\n        template<typename Args>\n        void operator()(const Args& args){\n        \t++(this->freq[\n            \t\tstatic_cast<T>(\n                        args[boost::accumulators::sample]\n                    )\n                ]\n            );\n        }\n\t\t\n        // Returns the entire distribution, represented by a map\n        result_type result(dont_care_)const{\n            return (this->freq); \n        }\n\n        private:\n        mutable map_ freq;\n\t};\n    \n}// impl\n\nnamespace tag\n{\n   \n    struct ordered_sample\n      : boost::accumulators::depends_on<>\n    {\n      typedef statistics::detail::empirical_distribution::\n      \timpl::ordered_sample<boost::mpl::_1> impl;\n    };\n}// tag\n\nnamespace result_of{\n\n    template<typename AccSet>\n    struct ordered_sample : boost::accumulators::detail::extractor_result<\n        AccSet,\n        boost::statistics::detail::empirical_distribution::tag::ordered_sample\n    >{};\n\n}// result_of\n\nnamespace extract\n{\n\n  \ttemplate<typename AccSet>\n    typename boost::statistics::detail::empirical_distribution\n    \t::result_of::template ordered_sample<AccSet>::type\n  \tordered_sample(AccSet const& acc)\n    {\n    \ttypedef boost::statistics::detail::empirical_distribution\n    \t\t::tag::ordered_sample the_tag;\n        return boost::accumulators::extract_result<the_tag>(acc);\n  \t}\n\n}// extract\n\nusing extract::ordered_sample;\n\n}// empirical_distribution\n}// detail\n}// statistics\n}// boost\n\n#endif", "meta": {"hexsha": "de06b41671481f239d98bf29e23245676354fa96", "size": 3717, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "non_parametric/boost/statistics/detail/non_parametric/backup_once_in_trunk/non_parametric/empirical_distribution/ordered_sample.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/empirical_distribution/ordered_sample.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/empirical_distribution/ordered_sample.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": 30.975, "max_line_length": 96, "alphanum_fraction": 0.6228140974, "num_tokens": 774, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370111, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.4793541616870202}}
{"text": "////////////////////////////////////////////////////////////////////////////////\n//  Copyright (c) 2015 Bryce Adelstein Lelbach aka wash\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#include <mdspan>\n\n#include <vector>\n#include <tuple>\n\n#include <boost/core/lightweight_test.hpp>\n\nusing std::vector;\nusing std::tuple;\n\nusing std::experimental::dyn;\nusing std::experimental::dimensions;\nusing std::experimental::layout_mapping_right;\n\ntemplate <\n    std::size_t StepX, std::size_t StepY \n  , std::size_t PadX, std::size_t PadY \n  , std::size_t X, std::size_t Y\n    >\nvoid test_2d_static()\n{ // {{{\n    static_assert(0 == (X % StepX), \"X must be divisable by StepX\");\n    static_assert(0 == (Y % StepY), \"Y must be divisable by StepY\");\n\n    layout_mapping_right<\n        dimensions<X, Y>\n      , dimensions<1, 1>\n      , dimensions<PadX, PadY>\n    > const l{};\n\n    BOOST_TEST_EQ((l.is_regular()), true);\n\n    BOOST_TEST_EQ((l.stride(0)), 1);\n    BOOST_TEST_EQ((l.stride(1)), 1);\n\n    BOOST_TEST_EQ((l.size()), X * Y);\n    BOOST_TEST_EQ((l.span()), (X + PadX) * (Y + PadY));\n\n    layout_mapping_right<\n        dimensions<X / StepX, Y / StepY>\n      , dimensions<StepX, StepY>\n      , dimensions<PadX, PadY>\n    > const sub_l{};\n\n    BOOST_TEST_EQ((sub_l.is_regular()), true);\n\n    BOOST_TEST_EQ((sub_l.stride(0)), StepX);\n    BOOST_TEST_EQ((sub_l.stride(1)), StepY);\n\n    BOOST_TEST_EQ((sub_l.size()), (X / StepX) * (Y / StepY));\n    BOOST_TEST_EQ((sub_l.span()), (X + PadX) * (Y + PadY));\n\n    int dptr[(X + PadX) * (Y + PadY)];\n\n    // Set all real elements to 42.\n    for (auto j = 0; j < l[1]; ++j)\n    for (auto i = 0; i < l[0]; ++i)\n    {\n        auto const true_idx = (l[1] + l.padding()[1]) * (i) + (j);\n\n        BOOST_TEST_EQ((l.index(i, j)), true_idx);\n\n        BOOST_TEST_EQ(&(dptr[l.index(i, j)]), &(dptr[true_idx]));\n\n        dptr[l.index(i, j)] = 42;\n\n        BOOST_TEST_EQ((dptr[l.index(i, j)]), 42);\n    }\n\n    // Set X pad elements to 17 and Y pad elements to 24. \n    for (auto j = 0; j < l[1] + l.padding()[1]; ++j)\n    for (auto i = 0; i < l[0] + l.padding()[0]; ++i)\n    {\n        auto const true_idx = (l[1] + l.padding()[1]) * (i) + (j);\n\n        BOOST_TEST_EQ((l.index(i, j)), true_idx);\n\n        BOOST_TEST_EQ(&(dptr[l.index(i, j)]), &(dptr[true_idx])); \n\n        // X-pad element.\n        if      ((l[0] <= i) && (i < (l[0] + l.padding()[0])))\n        {\n            dptr[l.index(i, j)] = 17;\n            \n            BOOST_TEST_EQ((dptr[l.index(i, j)]), 17);\n        }\n\n        // Y-pad element.\n        else if ((l[1] <= j) && (j < (l[1] + l.padding()[1])))\n        {\n            dptr[l.index(i, j)] = 24; \n\n            BOOST_TEST_EQ((dptr[l.index(i, j)]), 24);\n        }\n    }\n\n    // Set every (StepXth, StepYth) element to 71.\n    for (auto j = 0; j < sub_l[1]; ++j)\n    for (auto i = 0; i < sub_l[0]; ++i)\n    {\n        auto const p = l.padding();\n        auto const s = sub_l.stepping();\n        auto const true_idx = (sub_l[1] * s[1] + p[1]) * (s[0] * i) + (s[1] * j);\n\n        BOOST_TEST_EQ((sub_l.index(i, j)), true_idx);\n\n        BOOST_TEST_EQ(&(dptr[sub_l.index(i, j)]), &(dptr[true_idx])); \n\n        dptr[sub_l.index(i, j)] = 71;\n\n        BOOST_TEST_EQ((dptr[sub_l.index(i, j)]), 71);\n    }\n\n    // Check final structure. \n    for (auto j = 0; j < l[1] + l.padding()[1]; ++j)\n    for (auto i = 0; i < l[0] + l.padding()[0]; ++i)\n    {\n        auto const true_idx = (l[1] + l.padding()[1]) * (i) + (j);\n\n        BOOST_TEST_EQ((l.index(i, j)), true_idx);\n\n        BOOST_TEST_EQ(&(dptr[l.index(i, j)]), &(dptr[true_idx])); \n\n        // X-pad element.\n        if      ((l[0] <= i) && (i < (l[0] + l.padding()[0])))\n        {\n            BOOST_TEST_EQ((dptr[l.index(i, j)]), 17);\n        }\n\n        // Y-pad element.\n        else if ((l[1] <= j) && (j < (l[1] + l.padding()[1])))\n        {\n            BOOST_TEST_EQ((dptr[l.index(i, j)]), 24);\n        }\n\n        // Real element.\n        else\n        {\n            // Real element in the strided sub-box.\n            if (  (0 == (i % sub_l.stepping()[0]))\n               && (0 == (j % sub_l.stepping()[1]))\n               )\n            {\n                BOOST_TEST_EQ((dptr[l.index(i, j)]), 71);\n            }\n            // Real element not in the strided sub-box.\n            else\n            {\n                BOOST_TEST_EQ((dptr[l.index(i, j)]), 42);\n            }\n        }\n    }\n} // }}}\n\ntemplate <\n    std::size_t StepX, std::size_t StepY \n  , std::size_t PadX, std::size_t PadY \n  , std::size_t X, std::size_t Y\n    >\nvoid test_2d_dynamic()\n{ // {{{\n    layout_mapping_right<\n        dimensions<dyn, dyn>\n      , dimensions<dyn, dyn>\n      , dimensions<dyn, dyn>\n    > const l{{X, Y}, {1, 1}, {PadX, PadY}};\n\n    BOOST_TEST_EQ((l.is_regular()), true);\n\n    BOOST_TEST_EQ((l.stride(0)), 1);\n    BOOST_TEST_EQ((l.stride(1)), 1);\n\n    BOOST_TEST_EQ((l.size()), X * Y);\n    BOOST_TEST_EQ((l.span()), (X + PadX) * (Y + PadY));\n\n    layout_mapping_right<\n        dimensions<dyn, dyn>\n      , dimensions<dyn, dyn>\n      , dimensions<dyn, dyn>\n    > const sub_l{{X / StepX, Y / StepY}, {StepX, StepY}, {PadX, PadY}};\n\n    BOOST_TEST_EQ((sub_l.is_regular()), true);\n\n    BOOST_TEST_EQ((sub_l.stride(0)), StepX);\n    BOOST_TEST_EQ((sub_l.stride(1)), StepY);\n\n    BOOST_TEST_EQ((sub_l.size()), (X / StepX) * (Y / StepY));\n    BOOST_TEST_EQ((sub_l.span()), (X + PadX) * (Y + PadY));\n\n    // Initialize all elements to 42.\n    std::vector<int> data(\n        (l[0] + l.padding()[0]) * (l[1] + l.padding()[1]), 42\n    );\n    int* dptr = data.data();\n\n    // Set X pad elements to 17 and Y pad elements to 24. \n    for (auto j = 0; j < l[1] + l.padding()[1]; ++j)\n    for (auto i = 0; i < l[0] + l.padding()[0]; ++i)\n    {\n        auto const true_idx = (l[1] + l.padding()[1]) * (i) + (j);\n\n        BOOST_TEST_EQ((l.index(i, j)), true_idx);\n\n        BOOST_TEST_EQ(&(dptr[l.index(i, j)]), &(dptr[true_idx])); \n\n        // X-pad element.\n        if      ((l[0] <= i) && (i < (l[0] + l.padding()[0])))\n        {\n            dptr[l.index(i, j)] = 17;\n            \n            BOOST_TEST_EQ((dptr[l.index(i, j)]), 17);\n\n            // Bounds-checking.\n            BOOST_TEST_EQ((data.at(l.index(i, j))), 17);\n        }\n\n        // Y-pad element.\n        else if ((l[1] <= j) && (j < (l[1] + l.padding()[1])))\n        {\n            dptr[l.index(i, j)] = 24; \n\n            BOOST_TEST_EQ((dptr[l.index(i, j)]), 24);\n\n            // Bounds-checking.\n            BOOST_TEST_EQ((data.at(l.index(i, j))), 24);\n        }\n    }\n\n    // Set every (StepXth, StepYth) element to 71.\n    for (auto j = 0; j < sub_l[1]; ++j)\n    for (auto i = 0; i < sub_l[0]; ++i)\n    {\n        auto const p = l.padding();\n        auto const s = sub_l.stepping();\n        auto const true_idx = (sub_l[1] * s[1] + p[1]) * (s[0] * i) + (s[1] * j);\n\n        BOOST_TEST_EQ((sub_l.index(i, j)), true_idx);\n\n        BOOST_TEST_EQ(&(dptr[sub_l.index(i, j)]), &(dptr[true_idx])); \n\n        dptr[sub_l.index(i, j)] = 71;\n\n        BOOST_TEST_EQ((dptr[sub_l.index(i, j)]), 71);\n\n        // Bounds-checking.\n        BOOST_TEST_EQ((data.at(sub_l.index(i, j))), 71);\n    }\n\n    // Check final structure. \n    for (auto j = 0; j < l[1] + l.padding()[1]; ++j)\n    for (auto i = 0; i < l[0] + l.padding()[0]; ++i)\n    {\n        auto const true_idx = (l[1] + l.padding()[1]) * (i) + (j);\n\n        BOOST_TEST_EQ((l.index(i, j)), true_idx);\n\n        BOOST_TEST_EQ(&(dptr[l.index(i, j)]), &(dptr[true_idx])); \n\n        // X-pad element.\n        if      ((l[0] <= i) && (i < (l[0] + l.padding()[0])))\n        {\n            BOOST_TEST_EQ((dptr[l.index(i, j)]), 17);\n\n            // Bounds-checking.\n            BOOST_TEST_EQ((data.at(l.index(i, j))), 17);\n        }\n\n        // Y-pad element.\n        else if ((l[1] <= j) && (j < (l[1] + l.padding()[1])))\n        {\n            BOOST_TEST_EQ((dptr[l.index(i, j)]), 24);\n\n            // Bounds-checking.\n            BOOST_TEST_EQ((data.at(l.index(i, j))), 24);\n        }\n\n        // Real element.\n        else\n        {\n            // Real element in the strided sub-box.\n            if (  (0 == (i % sub_l.stepping()[0]))\n               && (0 == (j % sub_l.stepping()[1]))\n               )\n            {\n                BOOST_TEST_EQ((dptr[l.index(i, j)]), 71);\n\n                // Bounds-checking.\n                BOOST_TEST_EQ((data.at(l.index(i, j))), 71);\n            }\n            // Real element not in the strided sub-box.\n            else\n            {\n                BOOST_TEST_EQ((dptr[l.index(i, j)]), 42);\n\n                // Bounds-checking.\n                BOOST_TEST_EQ((data.at(l.index(i, j))), 42);\n            }\n        }\n    }\n} // }}}\n\nint main()\n{\n    ///////////////////////////////////////////////////////////////////////////\n    // 2D Static\n\n    //             Stepping   Padding   Dimensions\n    test_2d_static<5, 1,      1, 0,     30, 30>();\n    test_2d_static<1, 5,      1, 0,     30, 30>();\n    test_2d_static<5, 5,      1, 0,     30, 30>();\n    test_2d_static<5, 1,      0, 1,     30, 30>();\n    test_2d_static<1, 5,      0, 1,     30, 30>();\n    test_2d_static<5, 5,      0, 1,     30, 30>();\n    test_2d_static<5, 1,      1, 0,     30, 30>();\n    test_2d_static<1, 5,      1, 0,     30, 30>();\n    test_2d_static<5, 5,      1, 0,     30, 30>();\n    test_2d_static<5, 1,      1, 1,     30, 30>();\n    test_2d_static<1, 5,      1, 1,     30, 30>();\n\n    test_2d_static<5, 5,      1, 1,     30, 30>();\n    test_2d_static<5, 1,      1, 0,     30, 30>();\n    test_2d_static<1, 5,      1, 0,     30, 30>();\n    test_2d_static<5, 5,      1, 0,     30, 30>();\n    test_2d_static<5, 1,      0, 1,     30, 30>();\n    test_2d_static<1, 5,      0, 1,     30, 30>();\n    test_2d_static<5, 5,      0, 1,     30, 30>();\n    test_2d_static<5, 1,      1, 0,     30, 30>();\n    test_2d_static<1, 5,      1, 0,     30, 30>();\n    test_2d_static<5, 5,      1, 0,     30, 30>();\n    test_2d_static<5, 1,      1, 1,     30, 30>();\n    test_2d_static<1, 5,      1, 1,     30, 30>();\n    test_2d_static<5, 5,      1, 1,     30, 30>();\n\n    ///////////////////////////////////////////////////////////////////////////\n    // 2D Dynamic\n\n    //              Stepping   Padding   Dimensions\n    test_2d_dynamic<5, 1,      1, 0,     30, 30>();\n    test_2d_dynamic<1, 5,      1, 0,     30, 30>();\n    test_2d_dynamic<5, 5,      1, 0,     30, 30>();\n    test_2d_dynamic<5, 1,      0, 1,     30, 30>();\n    test_2d_dynamic<1, 5,      0, 1,     30, 30>();\n    test_2d_dynamic<5, 5,      0, 1,     30, 30>();\n    test_2d_dynamic<5, 1,      1, 0,     30, 30>();\n    test_2d_dynamic<1, 5,      1, 0,     30, 30>();\n    test_2d_dynamic<5, 5,      1, 0,     30, 30>();\n    test_2d_dynamic<5, 1,      1, 1,     30, 30>();\n    test_2d_dynamic<1, 5,      1, 1,     30, 30>();\n\n    test_2d_dynamic<5, 5,      1, 1,     30, 30>();\n    test_2d_dynamic<5, 1,      1, 0,     30, 30>();\n    test_2d_dynamic<1, 5,      1, 0,     30, 30>();\n    test_2d_dynamic<5, 5,      1, 0,     30, 30>();\n    test_2d_dynamic<5, 1,      0, 1,     30, 30>();\n    test_2d_dynamic<1, 5,      0, 1,     30, 30>();\n    test_2d_dynamic<5, 5,      0, 1,     30, 30>();\n    test_2d_dynamic<5, 1,      1, 0,     30, 30>();\n    test_2d_dynamic<1, 5,      1, 0,     30, 30>();\n    test_2d_dynamic<5, 5,      1, 0,     30, 30>();\n    test_2d_dynamic<5, 1,      1, 1,     30, 30>();\n    test_2d_dynamic<1, 5,      1, 1,     30, 30>();\n    test_2d_dynamic<5, 5,      1, 1,     30, 30>();\n\n    return boost::report_errors();\n}\n\n", "meta": {"hexsha": "fc4889e7c8c6482177757d84215d7d8e337496f6", "size": 11646, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_layout_mapping_right_stepping_padding.cpp", "max_stars_repo_name": "brycelelbach/boost.mdspan", "max_stars_repo_head_hexsha": "0f4b1329bbabef14b180ecd5f8a7a5282a2f9ee2", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-10-02T21:33:43.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-02T21:33:43.000Z", "max_issues_repo_path": "tests/test_layout_mapping_right_stepping_padding.cpp", "max_issues_repo_name": "brycelelbach/boost.mdspan", "max_issues_repo_head_hexsha": "0f4b1329bbabef14b180ecd5f8a7a5282a2f9ee2", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-04-27T21:51:28.000Z", "max_issues_repo_issues_event_max_datetime": "2018-04-27T23:43:43.000Z", "max_forks_repo_path": "tests/test_layout_mapping_right_stepping_padding.cpp", "max_forks_repo_name": "brycelelbach/boost.mdspan", "max_forks_repo_head_hexsha": "0f4b1329bbabef14b180ecd5f8a7a5282a2f9ee2", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-04-27T22:37:37.000Z", "max_forks_repo_forks_event_max_datetime": "2018-04-27T22:37:37.000Z", "avg_line_length": 31.1390374332, "max_line_length": 81, "alphanum_fraction": 0.4605014597, "num_tokens": 4043, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.4793541571038098}}
{"text": "/* Copyright (C) 2012-2017 IBM Corp.\n * This program is Licensed under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *   http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License. See accompanying LICENSE file.\n */\nnamespace std {} using namespace std;\nnamespace NTL {} using namespace NTL;\n\n#include <NTL/BasicThreadPool.h>\n\n#include \"EvalMap.h\"\n#include \"hypercube.h\"\n#include \"powerful.h\"\n\nNTL_CLIENT\n\nstatic bool dry = false; // a dry-run flag\nstatic bool noPrint = true;\n\nvoid  TestIt(long p, long r, long c, long _k,\n             long L, Vec<long>& mvec, \n             Vec<long>& gens, Vec<long>& ords, long useCache)\n{\n  if (lsize(mvec)<1) { // use default values\n    mvec.SetLength(3); gens.SetLength(3); ords.SetLength(3);\n    mvec[0] = 7;    mvec[1] = 3;    mvec[2] = 221;\n    gens[0] = 3979; gens[1] = 3095; gens[2] = 3760;\n    ords[0] = 6;    ords[1] = 2;    ords[2] = -8;\n  }\n  if (!noPrint)\n    cout << \"*** TestIt\"\n       << (dry? \" (dry run):\" : \":\")\n       << \" p=\" << p\n       << \", r=\" << r\n       << \", c=\" << c\n       << \", k=\" << _k\n       << \", L=\" << L\n       << \", mvec=\" << mvec << \", \"\n       << \", useCache = \" << useCache\n       << endl;\n\n  setTimersOn();\n  setDryRun(false); // Need to get a \"real context\" to test EvalMap\n\n  // mvec is supposed to include the prime-power factorization of m\n  long nfactors = mvec.length();\n  for (long i = 0; i < nfactors; i++)\n    for (long j = i+1; j < nfactors; j++)\n      assert(GCD(mvec[i], mvec[j]) == 1);\n\n  // multiply all the prime powers to get m itself\n  long m = computeProd(mvec);\n  assert(GCD(p, m) == 1);\n\n  // build a context with these generators and orders\n  vector<long> gens1, ords1;\n  convert(gens1, gens);\n  convert(ords1, ords);\n  FHEcontext context(m, p, r, gens1, ords1);\n  buildModChain(context, L, c);\n\n  if (!noPrint) {\n    context.zMStar.printout(); // print structure of Zm* /(p) to cout\n    cout << endl;\n  }\n  long d = context.zMStar.getOrdP();\n  long phim = context.zMStar.getPhiM();\n  long nslots = phim/d;\n\n  setDryRun(dry); // Now we can set the dry-run flag if desired\n\n  FHESecKey secretKey(context);\n  const FHEPubKey& publicKey = secretKey;\n  secretKey.GenSecKey(); // A Hamming-weight-w secret key\n  addSome1DMatrices(secretKey); // compute key-switching matrices that we need\n  addFrbMatrices(secretKey); // compute key-switching matrices that we need\n\n  // GG defines the plaintext space Z_p[X]/GG(X)\n  ZZX GG;\n  GG = context.alMod.getFactorsOverZZ()[0];\n  EncryptedArray ea(context, GG);\n\n  zz_p::init(context.alMod.getPPowR());\n  zz_pX F;\n  random(F, phim); // a random polynomial of degree phi(m)-1 modulo p\n\n  // convert F to powerful representation: cube represents a multi-variate\n  // polynomial with as many variables Xi as factors mi in mvec. cube has\n  // degree phi(mi) in the variable Xi, and the coefficients are given\n  // in lexicographic order.\n\n  // compute tables for converting between powerful and zz_pX\n  PowerfulTranslationIndexes ind(mvec); // indpendent of p\n  PowerfulConversion pConv(ind);        // depends on p\n\n  HyperCube<zz_p> cube(pConv.getShortSig());\n  pConv.polyToPowerful(cube, F);\n\n  // Sanity check: convert back and compare\n  zz_pX F2;\n  pConv.powerfulToPoly(F2, cube);\n  if (F != F2) {\n    cout << \"BAD\\n\";\n    if (!noPrint) cout << \" @@@ conversion error ):\\n\";\n  }\n  // pack the coefficients from cube in the plaintext slots: the j'th\n  // slot contains the polynomial pj(X) = \\sum_{t=0}^{d-1} cube[jd+t] X^t\n  vector<ZZX> val1;\n  val1.resize(nslots);\n  for (long i = 0; i < phim; i++) {\n    val1[i/d] += conv<ZZX>(conv<ZZ>(cube[i])) << (i % d);\n  }\n  PlaintextArray pa1(ea);\n  encode(ea, pa1, val1);\n\n  Ctxt ctxt(publicKey);\n  ea.encrypt(ctxt, publicKey, pa1);\n\n  resetAllTimers();\n  FHE_NTIMER_START(ALL);\n\n  // Compute homomorphically the transformation that takes the\n  // coefficients packed in the slots and produces the polynomial\n  // corresponding to cube\n\n  if (!noPrint) CheckCtxt(ctxt, \"init\");\n\n  if (!noPrint) cout << \"build EvalMap\\n\";\n  EvalMap map(ea, /*minimal=*/false, mvec, \n    /*invert=*/false, /*build_cache=*/false, /*normal_basis=*/false); \n  // compute the transformation to apply\n\n  if (!noPrint) cout << \"apply EvalMap\\n\";\n  if (useCache) map.upgrade();\n  map.apply(ctxt); // apply the transformation to ctxt\n  if (!noPrint) CheckCtxt(ctxt, \"EvalMap\");\n  if (!noPrint) cout << \"check results\\n\";\n\n  ZZX FF1;\n  secretKey.Decrypt(FF1, ctxt);\n  zz_pX F1 = conv<zz_pX>(FF1);\n\n  if (F1 == F)\n    cout << \"GOOD\\n\";\n  else\n    cout << \"BAD\\n\";\n\n  publicKey.Encrypt(ctxt, FF1);\n  if (!noPrint) CheckCtxt(ctxt, \"init\");\n\n  // Compute homomorphically the inverse transformation that takes the\n  // polynomial corresponding to cube and produces the coefficients\n  // packed in the slots\n\n  if (!noPrint) cout << \"build EvalMap\\n\";\n  EvalMap imap(ea, /*minimal=*/false, mvec, \n    /*invert=*/true, /*build_cache=*/false, /*normal_basis=*/false); \n  // compute the transformation to apply\n  if (!noPrint) cout << \"apply EvalMap\\n\";\n  if (useCache) imap.upgrade();\n  imap.apply(ctxt); // apply the transformation to ctxt\n  if (!noPrint) {\n    CheckCtxt(ctxt, \"EvalMap\");\n    cout << \"check results\\n\";\n  }\n  PlaintextArray pa2(ea);\n  ea.decrypt(ctxt, secretKey, pa2);\n\n  if (equals(ea, pa1, pa2))\n    cout << \"GOOD\\n\";\n  else\n    cout << \"BAD\\n\";\n  FHE_NTIMER_STOP(ALL);\n\n  if (!noPrint) {\n    cout << \"\\n*********\\n\";\n    printAllTimers();\n    cout << endl;\n  }\n}\n\n\n/* Usage: Test_EvalMap_x.exe [ name=value ]...\n *  p       plaintext base  [ default=2 ]\n *  r       lifting  [ default=1 ]\n *  c       number of columns in the key-switching matrices  [ default=2 ]\n *  k       security parameter  [ default=80 ]\n *  L       # of bits in the modulus chain \n *  s       minimum number of slots  [ default=0 ]\n *  seed    PRG seed  [ default=0 ]\n *  mvec    use specified factorization of m\n *             e.g., mvec='[5 3 187]'\n *  gens    use specified vector of generators\n *             e.g., gens='[562 1871 751]'\n *  ords    use specified vector of orders\n *             e.g., ords='[4 2 -4]', negative means 'bad'\n */\nint main(int argc, char *argv[])\n{\n  ArgMapping amap;\n\n  long p=2;\n  amap.arg(\"p\", p, \"plaintext base\");\n\n  long r=1;\n  amap.arg(\"r\", r,  \"lifting\");\n\n  long c=2;\n  amap.arg(\"c\", c, \"number of columns in the key-switching matrices\");\n  \n  long k=80;\n  amap.arg(\"k\", k, \"security parameter\");\n\n  long L=300;\n  amap.arg(\"L\", L, \"# of bits in the modulus chain\");\n\n  long s=0;\n  amap.arg(\"s\", s, \"minimum number of slots\");\n\n  long seed=0;\n  amap.arg(\"seed\", seed, \"PRG seed\");\n\n  Vec<long> mvec;\n  amap.arg(\"mvec\", mvec, \"use specified factorization of m\", NULL);\n  amap.note(\"e.g., mvec='[7 3 221]'\");\n\n  Vec<long> gens;\n  amap.arg(\"gens\", gens, \"use specified vector of generators\", NULL);\n  amap.note(\"e.g., gens='[3979 3095 3760]'\");\n\n  Vec<long> ords;\n  amap.arg(\"ords\", ords, \"use specified vector of orders\", NULL);\n  amap.note(\"e.g., ords='[6 2 -8]', negative means 'bad'\");\n\n  amap.arg(\"dry\", dry, \"a dry-run flag to check the noise\");\n\n  long nthreads=1;\n  amap.arg(\"nthreads\", nthreads, \"number of threads\");\n\n  amap.arg(\"noPrint\", noPrint, \"suppress printouts\");\n\n  long useCache=0;\n  amap.arg(\"useCache\", useCache, \"0: zzX cache, 2: DCRT cache\");\n\n  amap.parse(argc, argv);\n\n  SetNumThreads(nthreads);\n\n  SetSeed(conv<ZZ>(seed));\n  TestIt(p, r, c, k, L, mvec, gens, ords, useCache);\n}\n\n// ./Test_EvalMap_x mvec=\"[73 433]\" gens=\"[18620 12995]\" ords=\"[72 -6]\"\n", "meta": {"hexsha": "7374dab0a3fe18d10335463fb7e537974da79da9", "size": 7876, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Test_EvalMap.cpp", "max_stars_repo_name": "usafchn/DiPSI", "max_stars_repo_head_hexsha": "bb834532df3ae5b6ebc963aac6b3a43d9b31c830", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-01-29T09:29:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-09T13:32:07.000Z", "max_issues_repo_path": "src/Test_EvalMap.cpp", "max_issues_repo_name": "usafchn/DiPSI", "max_issues_repo_head_hexsha": "bb834532df3ae5b6ebc963aac6b3a43d9b31c830", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-01-29T10:01:08.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-26T02:38:01.000Z", "max_forks_repo_path": "src/Test_EvalMap.cpp", "max_forks_repo_name": "usafchn/DiPSI", "max_forks_repo_head_hexsha": "bb834532df3ae5b6ebc963aac6b3a43d9b31c830", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-01-30T08:15:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T12:21:00.000Z", "avg_line_length": 30.2923076923, "max_line_length": 78, "alphanum_fraction": 0.6310309802, "num_tokens": 2429, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.4793541571038098}}
{"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 testExpressionFactor.cpp\n * @date September 18, 2014\n * @author Frank Dellaert\n * @author Paul Furgale\n * @brief unit tests for Block Automatic Differentiation\n */\n\n#include <CppUnitLite/TestHarness.h>\n#include <gtsam/base/Testable.h>\n#include <gtsam/nonlinear/ExpressionFactor.h>\n#include <gtsam/nonlinear/NonlinearFactorGraph.h>\n#include <gtsam/nonlinear/PriorFactor.h>\n#include <gtsam/nonlinear/expressionTesting.h>\n#include <gtsam/slam/GeneralSFMFactor.h>\n#include <gtsam/slam/ProjectionFactor.h>\n#include <gtsam/slam/expressions.h>\n\n#include <boost/assign/list_of.hpp>\nusing boost::assign::list_of;\nusing namespace std::placeholders;\n\nusing namespace std;\nusing namespace gtsam;\n\nPoint2 measured(-17, 30);\nSharedNoiseModel model = noiseModel::Unit::Create(2);\n\n// This deals with the overload problem and makes the expressions factor\n// understand that we work on Point3\nPoint2 (*Project)(const Point3&, OptionalJacobian<2, 3>) = &PinholeBase::Project;\n\nnamespace leaf {\n// Create some values\nstruct MyValues: public Values {\n  MyValues() {\n    insert(2, Point2(3, 5));\n  }\n} values;\n\n// Create leaf\nPoint2_ p(2);\n}\n\n/* ************************************************************************* */\n// Leaf\nTEST(ExpressionFactor, Leaf) {\n  using namespace leaf;\n\n  // Create old-style factor to create expected value and derivatives.\n  PriorFactor<Point2> old(2, Point2(0, 0), model);\n\n  // Create the equivalent factor with expression.\n  ExpressionFactor<Point2> f(model, Point2(0, 0), p);\n\n  // Check values and derivatives.\n  EXPECT_DOUBLES_EQUAL(old.error(values), f.error(values), 1e-9);\n  EXPECT_LONGS_EQUAL(2, f.dim());\n  boost::shared_ptr<GaussianFactor> gf2 = f.linearize(values);\n  EXPECT(assert_equal(*old.linearize(values), *gf2, 1e-9));\n}\n\n/* ************************************************************************* */\n// Test leaf expression with noise model of different variance.\nTEST(ExpressionFactor, Model) {\n  using namespace leaf;\n\n  SharedNoiseModel model = noiseModel::Diagonal::Sigmas(Vector2(0.1, 0.01));\n\n  // Create old-style factor to create expected value and derivatives.\n  PriorFactor<Point2> old(2, Point2(0, 0), model);\n\n  // Create the equivalent factor with expression.\n  ExpressionFactor<Point2> f(model, Point2(0, 0), p);\n\n  // Check values and derivatives.\n  EXPECT_DOUBLES_EQUAL(old.error(values), f.error(values), 1e-9);\n  EXPECT_LONGS_EQUAL(2, f.dim());\n  boost::shared_ptr<GaussianFactor> gf2 = f.linearize(values);\n  EXPECT(assert_equal(*old.linearize(values), *gf2, 1e-9));\n  EXPECT_CORRECT_FACTOR_JACOBIANS(f, values, 1e-5, 1e-5); // another way\n}\n\n/* ************************************************************************* */\n// Test leaf expression with constrained noise model.\nTEST(ExpressionFactor, Constrained) {\n  using namespace leaf;\n\n  SharedDiagonal model = noiseModel::Constrained::MixedSigmas(Vector2(0.2, 0));\n\n  // Create old-style factor to create expected value and derivatives\n  PriorFactor<Point2> old(2, Point2(0, 0), model);\n\n  // Concise version\n  ExpressionFactor<Point2> f(model, Point2(0, 0), p);\n  EXPECT_DOUBLES_EQUAL(old.error(values), f.error(values), 1e-9);\n  EXPECT_LONGS_EQUAL(2, f.dim());\n  boost::shared_ptr<GaussianFactor> gf2 = f.linearize(values);\n  EXPECT(assert_equal(*old.linearize(values), *gf2, 1e-9));\n}\n\n/* ************************************************************************* */\n// Unary(Leaf))\nTEST(ExpressionFactor, Unary) {\n\n  // Create some values\n  Values values;\n  values.insert(2, Point3(0, 0, 1));\n\n  JacobianFactor expected( //\n      2, (Matrix(2, 3) << 1, 0, 0, 0, 1, 0).finished(), //\n      Vector2(-17, 30));\n\n  // Create leaves\n  Point3_ p(2);\n\n  // Concise version\n  ExpressionFactor<Point2> f(model, measured, project(p));\n  EXPECT_LONGS_EQUAL(2, f.dim());\n  boost::shared_ptr<GaussianFactor> gf = f.linearize(values);\n  boost::shared_ptr<JacobianFactor> jf = //\n      boost::dynamic_pointer_cast<JacobianFactor>(gf);\n  EXPECT(assert_equal(expected, *jf, 1e-9));\n}\n\n/* ************************************************************************* */\n// Unary(Leaf)) and Unary(Unary(Leaf)))\n// wide version (not handled in fixed-size pipeline)\ntypedef Eigen::Matrix<double,9,3> Matrix93;\nVector9 wide(const Point3& p, OptionalJacobian<9,3> H) {\n  Vector9 v;\n  v << p, p, p;\n  if (H) *H << I_3x3, I_3x3, I_3x3;\n  return v;\n}\n\ntypedef Eigen::Matrix<double,9,9> Matrix9;\nVector9 id9(const Vector9& v, OptionalJacobian<9,9> H) {\n  if (H) *H = Matrix9::Identity();\n  return v;\n}\n\nTEST(ExpressionFactor, Wide) {\n  // Create some values\n  Values values;\n  values.insert(2, Point3(0, 0, 1));\n  Point3_ point(2);\n  Vector9 measured;\n  measured.setZero();\n  Expression<Vector9> expression(wide,point);\n  SharedNoiseModel model = noiseModel::Unit::Create(9);\n\n  ExpressionFactor<Vector9> f1(model, measured, expression);\n  EXPECT_CORRECT_FACTOR_JACOBIANS(f1, values, 1e-5, 1e-9);\n\n  Expression<Vector9> expression2(id9,expression);\n  ExpressionFactor<Vector9> f2(model, measured, expression2);\n  EXPECT_CORRECT_FACTOR_JACOBIANS(f2, values, 1e-5, 1e-9);\n}\n\n/* ************************************************************************* */\nstatic Point2 myUncal(const Cal3_S2& K, const Point2& p,\n    OptionalJacobian<2,5> Dcal, OptionalJacobian<2,2> Dp) {\n  return K.uncalibrate(p, Dcal, Dp);\n}\n\n// Binary(Leaf,Leaf)\nTEST(ExpressionFactor, Binary) {\n\n  typedef internal::BinaryExpression<Point2, Cal3_S2, Point2> Binary;\n\n  Cal3_S2_ K_(1);\n  Point2_ p_(2);\n  Binary binary(myUncal, K_, p_);\n\n  // Create some values\n  Values values;\n  values.insert(1, Cal3_S2());\n  values.insert(2, Point2(0, 0));\n\n  // Check size\n  size_t size = binary.traceSize();\n  // Use Variable Length Array, allocated on stack by gcc\n  // Note unclear for Clang: http://clang.llvm.org/compatibility.html#vla\n  internal::ExecutionTraceStorage traceStorage[size];\n  internal::ExecutionTrace<Point2> trace;\n  Point2 value = binary.traceExecution(values, trace, traceStorage);\n  EXPECT(assert_equal(Point2(0,0),value, 1e-9));\n  // trace.print();\n\n  // Expected Jacobians\n  Matrix25 expected25;\n  expected25 << 0, 0, 0, 1, 0, 0, 0, 0, 0, 1;\n  Matrix2 expected22;\n  expected22 << 1, 0, 0, 1;\n\n  // Check matrices\n  boost::optional<Binary::Record*> r = trace.record<Binary::Record>();\n  CHECK(r);\n  EXPECT(assert_equal(expected25, (Matrix ) (*r)->dTdA1, 1e-9));\n  EXPECT(assert_equal(expected22, (Matrix ) (*r)->dTdA2, 1e-9));\n}\n\n/* ************************************************************************* */\n// Unary(Binary(Leaf,Leaf))\nTEST(ExpressionFactor, Shallow) {\n\n  // Create some values\n  Values values;\n  values.insert(1, Pose3());\n  values.insert(2, Point3(0, 0, 1));\n\n  // Create old-style factor to create expected value and derivatives\n  GenericProjectionFactor<Pose3, Point3> old(measured, model, 1, 2,\n      boost::make_shared<Cal3_S2>());\n  double expected_error = old.error(values);\n  GaussianFactor::shared_ptr expected = old.linearize(values);\n\n  // Create leaves\n  Pose3_ x_(1);\n  Point3_ p_(2);\n\n  // Construct expression, concise evrsion\n  Point2_ expression = project(transformTo(x_, p_));\n\n  // Get and check keys and dims\n  KeyVector keys;\n  FastVector<int> dims;\n  boost::tie(keys, dims) = expression.keysAndDims();\n  LONGS_EQUAL(2,keys.size());\n  LONGS_EQUAL(2,dims.size());\n  LONGS_EQUAL(1,keys[0]);\n  LONGS_EQUAL(2,keys[1]);\n  LONGS_EQUAL(6,dims[0]);\n  LONGS_EQUAL(3,dims[1]);\n\n  // traceExecution of shallow tree\n  typedef internal::UnaryExpression<Point2, Point3> Unary;\n  size_t size = expression.traceSize();\n  internal::ExecutionTraceStorage traceStorage[size];\n  internal::ExecutionTrace<Point2> trace;\n  Point2 value = expression.traceExecution(values, trace, traceStorage);\n  EXPECT(assert_equal(Point2(0,0),value, 1e-9));\n  // trace.print();\n\n  // Expected Jacobians\n  Matrix23 expected23;\n  expected23 << 1, 0, 0, 0, 1, 0;\n\n  // Check matrices\n  boost::optional<Unary::Record*> r = trace.record<Unary::Record>();\n  CHECK(r);\n  EXPECT(assert_equal(expected23, (Matrix)(*r)->dTdA1, 1e-9));\n\n  // Linearization\n  ExpressionFactor<Point2> f2(model, measured, expression);\n  EXPECT_DOUBLES_EQUAL(expected_error, f2.error(values), 1e-9);\n  EXPECT_LONGS_EQUAL(2, f2.dim());\n  boost::shared_ptr<GaussianFactor> gf2 = f2.linearize(values);\n  EXPECT(assert_equal(*expected, *gf2, 1e-9));\n}\n\n/* ************************************************************************* */\n// Binary(Leaf,Unary(Binary(Leaf,Leaf)))\nTEST(ExpressionFactor, tree) {\n\n  // Create some values\n  Values values;\n  values.insert(1, Pose3());\n  values.insert(2, Point3(0, 0, 1));\n  values.insert(3, Cal3_S2());\n\n  // Create old-style factor to create expected value and derivatives\n  GeneralSFMFactor2<Cal3_S2> old(measured, model, 1, 2, 3);\n  double expected_error = old.error(values);\n  GaussianFactor::shared_ptr expected = old.linearize(values);\n\n  // Create leaves\n  Pose3_ x(1);\n  Point3_ p(2);\n  Cal3_S2_ K(3);\n\n  // Create expression tree\n  Point3_ p_cam(x, &Pose3::transformTo, p);\n  Point2_ xy_hat(Project, p_cam);\n  Point2_ uv_hat(K, &Cal3_S2::uncalibrate, xy_hat);\n\n  // Create factor and check value, dimension, linearization\n  ExpressionFactor<Point2> f(model, measured, uv_hat);\n  EXPECT_DOUBLES_EQUAL(expected_error, f.error(values), 1e-9);\n  EXPECT_LONGS_EQUAL(2, f.dim());\n  boost::shared_ptr<GaussianFactor> gf = f.linearize(values);\n  EXPECT(assert_equal(*expected, *gf, 1e-9));\n\n  // Concise version\n  ExpressionFactor<Point2> f2(model, measured,\n      uncalibrate(K, project(transformTo(x, p))));\n  EXPECT_DOUBLES_EQUAL(expected_error, f2.error(values), 1e-9);\n  EXPECT_LONGS_EQUAL(2, f2.dim());\n  boost::shared_ptr<GaussianFactor> gf2 = f2.linearize(values);\n  EXPECT(assert_equal(*expected, *gf2, 1e-9));\n\n  // Try ternary version\n  ExpressionFactor<Point2> f3(model, measured, project3(x, p, K));\n  EXPECT_DOUBLES_EQUAL(expected_error, f3.error(values), 1e-9);\n  EXPECT_LONGS_EQUAL(2, f3.dim());\n  boost::shared_ptr<GaussianFactor> gf3 = f3.linearize(values);\n  EXPECT(assert_equal(*expected, *gf3, 1e-9));\n}\n\n/* ************************************************************************* */\nTEST(ExpressionFactor, Compose1) {\n\n  // Create expression\n  Rot3_ R1(1), R2(2);\n  Rot3_ R3 = R1 * R2;\n\n  // Create factor\n  ExpressionFactor<Rot3> f(noiseModel::Unit::Create(3), Rot3(), R3);\n\n  // Create some values\n  Values values;\n  values.insert(1, Rot3());\n  values.insert(2, Rot3());\n\n  // Check unwhitenedError\n  std::vector<Matrix> H(2);\n  Vector actual = f.unwhitenedError(values, H);\n  EXPECT(assert_equal(I_3x3, H[0],1e-9));\n  EXPECT(assert_equal(I_3x3, H[1],1e-9));\n\n  // Check linearization\n  JacobianFactor expected(1, I_3x3, 2, I_3x3, Z_3x1);\n  boost::shared_ptr<GaussianFactor> gf = f.linearize(values);\n  boost::shared_ptr<JacobianFactor> jf = //\n      boost::dynamic_pointer_cast<JacobianFactor>(gf);\n  EXPECT(assert_equal(expected, *jf,1e-9));\n}\n\n/* ************************************************************************* */\n// Test compose with arguments referring to the same rotation\nTEST(ExpressionFactor, compose2) {\n\n  // Create expression\n  Rot3_ R1(1), R2(1);\n  Rot3_ R3 = R1 * R2;\n\n  // Create factor\n  ExpressionFactor<Rot3> f(noiseModel::Unit::Create(3), Rot3(), R3);\n\n  // Create some values\n  Values values;\n  values.insert(1, Rot3());\n\n  // Check unwhitenedError\n  std::vector<Matrix> H(1);\n  Vector actual = f.unwhitenedError(values, H);\n  EXPECT_LONGS_EQUAL(1, H.size());\n  EXPECT(assert_equal(2*I_3x3, H[0],1e-9));\n\n  // Check linearization\n  JacobianFactor expected(1, 2 * I_3x3, Z_3x1);\n  boost::shared_ptr<GaussianFactor> gf = f.linearize(values);\n  boost::shared_ptr<JacobianFactor> jf = //\n      boost::dynamic_pointer_cast<JacobianFactor>(gf);\n  EXPECT(assert_equal(expected, *jf,1e-9));\n}\n\n/* ************************************************************************* */\n// Test compose with one arguments referring to a constant same rotation\nTEST(ExpressionFactor, compose3) {\n\n  // Create expression\n  Rot3_ R1(Rot3::identity()), R2(3);\n  Rot3_ R3 = R1 * R2;\n\n  // Create factor\n  ExpressionFactor<Rot3> f(noiseModel::Unit::Create(3), Rot3(), R3);\n\n  // Create some values\n  Values values;\n  values.insert(3, Rot3());\n\n  // Check unwhitenedError\n  std::vector<Matrix> H(1);\n  Vector actual = f.unwhitenedError(values, H);\n  EXPECT_LONGS_EQUAL(1, H.size());\n  EXPECT(assert_equal(I_3x3, H[0],1e-9));\n\n  // Check linearization\n  JacobianFactor expected(3, I_3x3, Z_3x1);\n  boost::shared_ptr<GaussianFactor> gf = f.linearize(values);\n  boost::shared_ptr<JacobianFactor> jf = //\n      boost::dynamic_pointer_cast<JacobianFactor>(gf);\n  EXPECT(assert_equal(expected, *jf,1e-9));\n}\n\n/* ************************************************************************* */\n// Test compose with three arguments\nRot3 composeThree(const Rot3& R1, const Rot3& R2, const Rot3& R3,\n    OptionalJacobian<3, 3> H1, OptionalJacobian<3, 3> H2, OptionalJacobian<3, 3> H3) {\n  // return dummy derivatives (not correct, but that's ok for testing here)\n  if (H1)\n    *H1 = I_3x3;\n  if (H2)\n    *H2 = I_3x3;\n  if (H3)\n    *H3 = I_3x3;\n  return R1 * (R2 * R3);\n}\n\nTEST(ExpressionFactor, composeTernary) {\n\n  // Create expression\n  Rot3_ A(1), B(2), C(3);\n  Rot3_ ABC(composeThree, A, B, C);\n\n  // Create factor\n  ExpressionFactor<Rot3> f(noiseModel::Unit::Create(3), Rot3(), ABC);\n\n  // Create some values\n  Values values;\n  values.insert(1, Rot3());\n  values.insert(2, Rot3());\n  values.insert(3, Rot3());\n\n  // Check unwhitenedError\n  std::vector<Matrix> H(3);\n  Vector actual = f.unwhitenedError(values, H);\n  EXPECT_LONGS_EQUAL(3, H.size());\n  EXPECT(assert_equal(I_3x3, H[0],1e-9));\n  EXPECT(assert_equal(I_3x3, H[1],1e-9));\n  EXPECT(assert_equal(I_3x3, H[2],1e-9));\n\n  // Check linearization\n  JacobianFactor expected(1, I_3x3, 2, I_3x3, 3, I_3x3, Z_3x1);\n  boost::shared_ptr<GaussianFactor> gf = f.linearize(values);\n  boost::shared_ptr<JacobianFactor> jf = //\n      boost::dynamic_pointer_cast<JacobianFactor>(gf);\n  EXPECT(assert_equal(expected, *jf,1e-9));\n}\n\nTEST(ExpressionFactor, tree_finite_differences) {\n\n  // Create some values\n  Values values;\n  values.insert(1, Pose3());\n  values.insert(2, Point3(0, 0, 1));\n  values.insert(3, Cal3_S2());\n\n  // Create leaves\n  Pose3_ x(1);\n  Point3_ p(2);\n  Cal3_S2_ K(3);\n\n  // Create expression tree\n  Point3_ p_cam(x, &Pose3::transformTo, p);\n  Point2_ xy_hat(Project, p_cam);\n  Point2_ uv_hat(K, &Cal3_S2::uncalibrate, xy_hat);\n\n  const double fd_step = 1e-5;\n  const double tolerance = 1e-5;\n  EXPECT_CORRECT_EXPRESSION_JACOBIANS(uv_hat, values, fd_step, tolerance);\n}\n\nTEST(ExpressionFactor, push_back) {\n  NonlinearFactorGraph graph;\n  graph.addExpressionFactor(model, Point2(0, 0), leaf::p);\n}\n\n/* ************************************************************************* */\n// Test with multiple compositions on duplicate keys\nstruct Combine {\n  double a, b;\n  Combine(double a, double b) : a(a), b(b) {}\n  double operator()(const double& x, const double& y, OptionalJacobian<1, 1> H1,\n                    OptionalJacobian<1, 1> H2) {\n    if (H1) (*H1) << a;\n    if (H2) (*H2) << b;\n    return a * x + b * y;\n  }\n};\n\nTEST(Expression, testMultipleCompositions) {\n  const double tolerance = 1e-5;\n  const double fd_step = 1e-5;\n\n  Values values;\n  values.insert(1, 10.0);\n  values.insert(2, 20.0);\n\n  Expression<double> v1_(Key(1));\n  Expression<double> v2_(Key(2));\n\n  // BinaryExpression(1,2)\n  //   Leaf, key = 1\n  //   Leaf, key = 2\n  Expression<double> sum1_(Combine(1, 2), v1_, v2_);\n  EXPECT(sum1_.keys() == list_of(1)(2));\n  EXPECT_CORRECT_EXPRESSION_JACOBIANS(sum1_, values, fd_step, tolerance);\n\n  // BinaryExpression(3,4)\n  //   BinaryExpression(1,2)\n  //     Leaf, key = 1\n  //     Leaf, key = 2\n  //   Leaf, key = 1\n  Expression<double> sum2_(Combine(3, 4), sum1_, v1_);\n  EXPECT(sum2_.keys() == list_of(1)(2));\n  EXPECT_CORRECT_EXPRESSION_JACOBIANS(sum2_, values, fd_step, tolerance);\n\n  // BinaryExpression(5,6)\n  //   BinaryExpression(3,4)\n  //     BinaryExpression(1,2)\n  //       Leaf, key = 1\n  //       Leaf, key = 2\n  //     Leaf, key = 1\n  //   BinaryExpression(1,2)\n  //     Leaf, key = 1\n  //     Leaf, key = 2\n  Expression<double> sum3_(Combine(5, 6), sum1_, sum2_);\n  EXPECT(sum3_.keys() == list_of(1)(2));\n  EXPECT_CORRECT_EXPRESSION_JACOBIANS(sum3_, values, fd_step, tolerance);\n}\n\n/* ************************************************************************* */\n// Another test, with Ternary Expressions\nstatic double combine3(const double& x, const double& y, const double& z,\n                        OptionalJacobian<1, 1> H1, OptionalJacobian<1, 1> H2,\n                        OptionalJacobian<1, 1> H3) {\n  if (H1) (*H1) << 1.0;\n  if (H2) (*H2) << 2.0;\n  if (H3) (*H3) << 3.0;\n  return x + 2.0 * y + 3.0 * z;\n}\n\nTEST(Expression, testMultipleCompositions2) {\n  const double tolerance = 1e-5;\n  const double fd_step = 1e-5;\n\n  Values values;\n  values.insert(1, 10.0);\n  values.insert(2, 20.0);\n  values.insert(3, 30.0);\n\n  Expression<double> v1_(Key(1));\n  Expression<double> v2_(Key(2));\n  Expression<double> v3_(Key(3));\n\n  Expression<double> sum1_(Combine(4,5), v1_, v2_);\n  EXPECT(sum1_.keys() == list_of(1)(2));\n  EXPECT_CORRECT_EXPRESSION_JACOBIANS(sum1_, values, fd_step, tolerance);\n\n  Expression<double> sum2_(combine3, v1_, v2_, v3_);\n  EXPECT(sum2_.keys() == list_of(1)(2)(3));\n  EXPECT_CORRECT_EXPRESSION_JACOBIANS(sum2_, values, fd_step, tolerance);\n\n  Expression<double> sum3_(combine3, v3_, v2_, v1_);\n  EXPECT(sum3_.keys() == list_of(1)(2)(3));\n  EXPECT_CORRECT_EXPRESSION_JACOBIANS(sum3_, values, fd_step, tolerance);\n\n  Expression<double> sum4_(combine3, sum1_, sum2_, sum3_);\n  EXPECT(sum4_.keys() == list_of(1)(2)(3));\n  EXPECT_CORRECT_EXPRESSION_JACOBIANS(sum4_, values, fd_step, tolerance);\n}\n\n/* ************************************************************************* */\n// Test multiplication with the inverse of a matrix\nTEST(ExpressionFactor, MultiplyWithInverse) {\n  auto model = noiseModel::Isotropic::Sigma(3, 1);\n\n  // Create expression\n  Vector3_ f_expr(MultiplyWithInverse<3>(), Expression<Matrix3>(0), Vector3_(1));\n\n  // Check derivatives\n  Values values;\n  Matrix3 A = Vector3(1, 2, 3).asDiagonal();\n  A(0, 1) = 0.1;\n  A(0, 2) = 0.1;\n  const Vector3 b(0.1, 0.2, 0.3);\n  values.insert<Matrix3>(0, A);\n  values.insert<Vector3>(1, b);\n  ExpressionFactor<Vector3> factor(model, Vector3::Zero(), f_expr);\n  EXPECT_CORRECT_FACTOR_JACOBIANS(factor, values, 1e-5, 1e-5);\n}\n\n/* ************************************************************************* */\n// Test multiplication with the inverse of a matrix function\nnamespace test_operator {\nVector3 f(const Point2& a, const Vector3& b, OptionalJacobian<3, 2> H1,\n          OptionalJacobian<3, 3> H2) {\n  Matrix3 A = Vector3(1, 2, 3).asDiagonal();\n  A(0, 1) = a.x();\n  A(0, 2) = a.y();\n  A(1, 0) = a.x();\n  if (H1) *H1 << b.y(), b.z(), b.x(), 0, 0, 0;\n  if (H2) *H2 = A;\n  return A * b;\n};\n}\n\nTEST(ExpressionFactor, MultiplyWithInverseFunction) {\n  auto model = noiseModel::Isotropic::Sigma(3, 1);\n\n  using test_operator::f;\n  Vector3_ f_expr(MultiplyWithInverseFunction<Point2, 3>(f),\n                  Expression<Point2>(0), Vector3_(1));\n\n  // Check derivatives\n  Point2 a(1, 2);\n  const Vector3 b(0.1, 0.2, 0.3);\n  Matrix32 H1;\n  Matrix3 A;\n  const Vector Ab = f(a, b, H1, A);\n  CHECK(assert_equal(A * b, Ab));\n  CHECK(assert_equal(\n      numericalDerivative11<Vector3, Point2>(\n          std::bind(f, std::placeholders::_1, b, boost::none, boost::none), a),\n      H1));\n\n  Values values;\n  values.insert<Point2>(0, a);\n  values.insert<Vector3>(1, b);\n  ExpressionFactor<Vector3> factor(model, Vector3::Zero(), f_expr);\n  EXPECT_CORRECT_FACTOR_JACOBIANS(factor, values, 1e-5, 1e-5);\n}\n\n\n/* ************************************************************************* */\n// Test N-ary variadic template\nclass TestNaryFactor\n    : public gtsam::ExpressionFactorN<gtsam::Point3 /*return type*/,\n                                      gtsam::Rot3, gtsam::Point3, \n                                      gtsam::Rot3, gtsam::Point3> {\nprivate:\n  using This = TestNaryFactor;\n  using Base =\n      gtsam::ExpressionFactorN<gtsam::Point3 /*return type*/,\n        gtsam::Rot3, gtsam::Point3, gtsam::Rot3, gtsam::Point3>;\n\npublic:\n  /// default constructor\n  TestNaryFactor() = default;\n  ~TestNaryFactor() override = default;\n\n  TestNaryFactor(gtsam::Key kR1, gtsam::Key kV1,  gtsam::Key kR2, gtsam::Key kV2,\n    const gtsam::SharedNoiseModel &model, const gtsam::Point3& measured)\n      : Base({kR1, kV1, kR2, kV2}, model, measured) {\n    this->initialize(expression({kR1, kV1, kR2, kV2}));\n  }\n\n  /// @return a deep copy of this factor\n  gtsam::NonlinearFactor::shared_ptr clone() const override {\n    return boost::static_pointer_cast<gtsam::NonlinearFactor>(\n        gtsam::NonlinearFactor::shared_ptr(new This(*this)));\n  }\n\n  // Return measurement expression\n  gtsam::Expression<gtsam::Point3> expression(\n      const std::array<gtsam::Key, NARY_EXPRESSION_SIZE> &keys) const override {\n    gtsam::Expression<gtsam::Rot3>   R1_(keys[0]);\n    gtsam::Expression<gtsam::Point3> V1_(keys[1]);\n    gtsam::Expression<gtsam::Rot3>   R2_(keys[2]);\n    gtsam::Expression<gtsam::Point3> V2_(keys[3]);\n    return {gtsam::rotate(R1_, V1_) - gtsam::rotate(R2_, V2_)};\n  }\n\n  /** print */\n  void print(const std::string &s,\n             const gtsam::KeyFormatter &keyFormatter =\n                 gtsam::DefaultKeyFormatter) const override {\n    std::cout << s << \"TestNaryFactor(\"\n              << keyFormatter(Factor::keys_[0]) << \",\"\n              << keyFormatter(Factor::keys_[1]) << \",\"\n              << keyFormatter(Factor::keys_[2]) << \",\"\n              << keyFormatter(Factor::keys_[3]) << \")\\n\";\n    gtsam::traits<gtsam::Point3>::Print(measured_, \"  measured: \");\n    this->noiseModel_->print(\"  noise model: \");\n  }\n\n  /** equals */\n  bool equals(const gtsam::NonlinearFactor &expected,\n              double tol = 1e-9) const override {\n    const This *e = dynamic_cast<const This *>(&expected);\n    return e != nullptr && Base::equals(*e, tol) && \n      gtsam::traits<gtsam::Point3>::Equals(measured_,e->measured_, tol);\n  }\n\nprivate:\n  /** Serialization function */\n  friend class boost::serialization::access;\n  template <class ARCHIVE>\n  void serialize(ARCHIVE &ar, const unsigned int /*version*/) {\n    ar &boost::serialization::make_nvp(\n        \"TestNaryFactor\",\n        boost::serialization::base_object<Base>(*this));\n    ar &BOOST_SERIALIZATION_NVP(measured_);\n  }\n};\n\nTEST(ExpressionFactor, variadicTemplate) {\n  using gtsam::symbol_shorthand::R;\n  using gtsam::symbol_shorthand::V;\n\n  // Create factor\n  TestNaryFactor f(R(0),V(0), R(1), V(1), noiseModel::Unit::Create(3), Point3(0,0,0));\n  \n  // Create some values\n  Values values;\n  values.insert(R(0), Rot3::Ypr(0.1, 0.2, 0.3));\n  values.insert(V(0), Point3(1, 2, 3));\n  values.insert(R(1), Rot3::Ypr(0.2, 0.5, 0.2));\n  values.insert(V(1), Point3(5, 6, 7));\n\n  // Check unwhitenedError\n  std::vector<Matrix> H(4);\n  Vector actual = f.unwhitenedError(values, H);\n  EXPECT_LONGS_EQUAL(4, H.size());\n  EXPECT(assert_equal(Eigen::Vector3d(-5.63578115, -4.85353243, -1.4801204), actual, 1e-5));\n  \n  EXPECT_CORRECT_FACTOR_JACOBIANS(f, values, 1e-8, 1e-5);\n}\n\n\nTEST(ExpressionFactor, crossProduct) {\n  auto model = noiseModel::Isotropic::Sigma(3, 1);\n\n  // Create expression\n  const auto a = Vector3_(1);\n  const auto b = Vector3_(2);\n  Vector3_ f_expr = cross(a, b);\n\n  // Check derivatives\n  Values values;\n  values.insert(1, Vector3(0.1, 0.2, 0.3));\n  values.insert(2, Vector3(0.4, 0.5, 0.6));\n  ExpressionFactor<Vector3> factor(model, Vector3::Zero(), f_expr);\n  EXPECT_CORRECT_FACTOR_JACOBIANS(factor, values, 1e-5, 1e-5);\n}\n\nTEST(ExpressionFactor, dotProduct) {\n  auto model = noiseModel::Isotropic::Sigma(1, 1);\n\n  // Create expression\n  const auto a = Vector3_(1);\n  const auto b = Vector3_(2);\n  Double_ f_expr = dot(a, b);\n\n  // Check derivatives\n  Values values;\n  values.insert(1, Vector3(0.1, 0.2, 0.3));\n  values.insert(2, Vector3(0.4, 0.5, 0.6));\n  ExpressionFactor<double> factor(model, .0, f_expr);\n  EXPECT_CORRECT_FACTOR_JACOBIANS(factor, values, 1e-5, 1e-5);\n}\n\n\n/* ************************************************************************* */\nint main() {\n  TestResult tr;\n  return TestRegistry::runAllTests(tr);\n}\n/* ************************************************************************* */\n\n", "meta": {"hexsha": "66dbed1eb43853e4a69179dbbe059dc182f96b8b", "size": 24738, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/testExpressionFactor.cpp", "max_stars_repo_name": "asa/gtsam", "max_stars_repo_head_hexsha": "158d279d59201f79fac78d80465332ec1914aeec", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1402.0, "max_stars_repo_stars_event_min_datetime": "2017-03-28T00:18:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T10:28:32.000Z", "max_issues_repo_path": "tests/testExpressionFactor.cpp", "max_issues_repo_name": "asa/gtsam", "max_issues_repo_head_hexsha": "158d279d59201f79fac78d80465332ec1914aeec", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 851.0, "max_issues_repo_issues_event_min_datetime": "2017-11-27T15:09:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T22:26:38.000Z", "max_forks_repo_path": "tests/testExpressionFactor.cpp", "max_forks_repo_name": "asa/gtsam", "max_forks_repo_head_hexsha": "158d279d59201f79fac78d80465332ec1914aeec", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 565.0, "max_forks_repo_forks_event_min_datetime": "2017-11-30T16:15:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T02:53:04.000Z", "avg_line_length": 31.92, "max_line_length": 92, "alphanum_fraction": 0.6348532622, "num_tokens": 7418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.4793541571038098}}
{"text": "\r\n// Copyright 2017 Peter Dimov.\r\n//\r\n// Distributed under the Boost Software License, Version 1.0.\r\n//\r\n// See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt\r\n\r\n\r\n#include <boost/mp11/algorithm.hpp>\r\n#include <boost/mp11/list.hpp>\r\n#include <boost/mp11/integral.hpp>\r\n#include <boost/mp11/function.hpp>\r\n#include <boost/core/lightweight_test_trait.hpp>\r\n#include <type_traits>\r\n#include <tuple>\r\n\r\nint main()\r\n{\r\n    using boost::mp11::mp_nth_element;\r\n    using boost::mp11::mp_nth_element_c;\r\n    using boost::mp11::mp_list_c;\r\n    using boost::mp11::mp_sort;\r\n    using boost::mp11::mp_less;\r\n    using boost::mp11::mp_at_c;\r\n    using boost::mp11::mp_size_t;\r\n    using boost::mp11::mp_rename;\r\n\r\n    {\r\n        using L1 = mp_list_c<int, 7, 1, 11, 3, 2, 2, 4>;\r\n        using L2 = mp_sort<L1, mp_less>;\r\n\r\n        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_nth_element_c<L1, 0, mp_less>, mp_at_c<L2, 0>>));\r\n        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_nth_element_c<L1, 1, mp_less>, mp_at_c<L2, 1>>));\r\n        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_nth_element_c<L1, 2, mp_less>, mp_at_c<L2, 2>>));\r\n        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_nth_element_c<L1, 3, mp_less>, mp_at_c<L2, 3>>));\r\n        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_nth_element_c<L1, 4, mp_less>, mp_at_c<L2, 4>>));\r\n        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_nth_element_c<L1, 5, mp_less>, mp_at_c<L2, 5>>));\r\n        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_nth_element_c<L1, 6, mp_less>, mp_at_c<L2, 6>>));\r\n\r\n        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_nth_element<L1, mp_size_t<0>, mp_less>, mp_at_c<L2, 0>>));\r\n        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_nth_element<L1, mp_size_t<1>, mp_less>, mp_at_c<L2, 1>>));\r\n        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_nth_element<L1, mp_size_t<2>, mp_less>, mp_at_c<L2, 2>>));\r\n        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_nth_element<L1, mp_size_t<3>, mp_less>, mp_at_c<L2, 3>>));\r\n        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_nth_element<L1, mp_size_t<4>, mp_less>, mp_at_c<L2, 4>>));\r\n        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_nth_element<L1, mp_size_t<5>, mp_less>, mp_at_c<L2, 5>>));\r\n        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_nth_element<L1, mp_size_t<6>, mp_less>, mp_at_c<L2, 6>>));\r\n    }\r\n\r\n    {\r\n        using L1 = mp_rename<mp_list_c<int, 7, 1, 11, 3, 2, 2, 4>, std::tuple>;\r\n        using L2 = mp_sort<L1, mp_less>;\r\n\r\n        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_nth_element_c<L1, 0, mp_less>, mp_at_c<L2, 0>>));\r\n        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_nth_element_c<L1, 1, mp_less>, mp_at_c<L2, 1>>));\r\n        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_nth_element_c<L1, 2, mp_less>, mp_at_c<L2, 2>>));\r\n        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_nth_element_c<L1, 3, mp_less>, mp_at_c<L2, 3>>));\r\n        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_nth_element_c<L1, 4, mp_less>, mp_at_c<L2, 4>>));\r\n        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_nth_element_c<L1, 5, mp_less>, mp_at_c<L2, 5>>));\r\n        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_nth_element_c<L1, 6, mp_less>, mp_at_c<L2, 6>>));\r\n\r\n        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_nth_element<L1, mp_size_t<0>, mp_less>, mp_at_c<L2, 0>>));\r\n        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_nth_element<L1, mp_size_t<1>, mp_less>, mp_at_c<L2, 1>>));\r\n        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_nth_element<L1, mp_size_t<2>, mp_less>, mp_at_c<L2, 2>>));\r\n        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_nth_element<L1, mp_size_t<3>, mp_less>, mp_at_c<L2, 3>>));\r\n        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_nth_element<L1, mp_size_t<4>, mp_less>, mp_at_c<L2, 4>>));\r\n        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_nth_element<L1, mp_size_t<5>, mp_less>, mp_at_c<L2, 5>>));\r\n        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_nth_element<L1, mp_size_t<6>, mp_less>, mp_at_c<L2, 6>>));\r\n    }\r\n\r\n    return boost::report_errors();\r\n}\r\n", "meta": {"hexsha": "747f3a4c7334f193325789b96cdca223cec63d38", "size": 3913, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/mp11/test/mp_nth_element.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": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/mp11/test/mp_nth_element.cpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-03-04T11:21:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-24T01:36:31.000Z", "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/mp11/test/mp_nth_element.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 53.602739726, "max_line_length": 106, "alphanum_fraction": 0.6718630207, "num_tokens": 1317, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059775, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.4793117852976843}}
{"text": "#ifndef BUSV_CREATE_ALPHA_SHAPE_HPP\n#define BUSV_CREATE_ALPHA_SHAPE_HPP\n\n#include \"cgal_typedefs.hpp\"\n#include \"point_transform_function.hpp\"\n#include \"init_edge_data.hpp\"\n#include \"process_cells.hpp\"\n#include \"weight_func_obj_default.hpp\"\n#include \"alpha_shape_container.hpp\"\n\n#include <boost/iterator/counting_iterator.hpp>\n#include <boost/iterator/transform_iterator.hpp>\n\nnamespace busv{\n\ntemplate <typename T, typename U>\nAlphaShapeContainer<T,U> create_alpha_shape(\n\tU numPoints, T alpha, \n\tconst T* points, const T* radii\n)\n{\n\ttypedef typename cgal_typedefs<T,U>::Triangulation_3 Triangulation_3;\n\ttypedef typename cgal_typedefs<T,U>::Fixed_alpha_shape_3 Fixed_alpha_shape_3;\n\n\tPointTransformFunction<Triangulation_3, VertexData<T, U>, T> tfunc(points, radii);\n\t//T (&coords)[numPoints][3] = (T (&)[numPoints][3])points;\n\n\t//build one alpha_shape with alpha=0\n\tFixed_alpha_shape_3* as_ptr = new Fixed_alpha_shape_3(\n\t\tboost::make_transform_iterator(boost::counting_iterator<U>(0), tfunc), \n\t\tboost::make_transform_iterator(boost::counting_iterator<U>(numPoints), tfunc), \n\t\talpha\n\t);\n\n\t//process edges and setup cell edge pointers\n\tEdgeData<T>* edgeData = init_edge_data<T>(*as_ptr);\n\n\t//process tetrahedra\n\tprocess_cells<T>(*as_ptr, weight_func_obj_default<T,U>());\n\n\treturn AlphaShapeContainer<T,U>(as_ptr, edgeData);\n}\n\n} //namespace busv\n\n#endif\n\n", "meta": {"hexsha": "b6eeb43e0cac2fabbbc9e2486156f13147ab51ec", "size": 1358, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/alpha_shapes/create_alpha_shape.hpp", "max_stars_repo_name": "academicRobot/mmstructlib", "max_stars_repo_head_hexsha": "76949620c9e9ca26faf10ff1a21c6fda1a564f5c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/alpha_shapes/create_alpha_shape.hpp", "max_issues_repo_name": "academicRobot/mmstructlib", "max_issues_repo_head_hexsha": "76949620c9e9ca26faf10ff1a21c6fda1a564f5c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/alpha_shapes/create_alpha_shape.hpp", "max_forks_repo_name": "academicRobot/mmstructlib", "max_forks_repo_head_hexsha": "76949620c9e9ca26faf10ff1a21c6fda1a564f5c", "max_forks_repo_licenses": ["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.2916666667, "max_line_length": 83, "alphanum_fraction": 0.7790868925, "num_tokens": 355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.727975460709318, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.4793117833104688}}
{"text": "/* test_poisson_distribution.cpp\n *\n * Copyright Steven Watanabe 2010\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: test_poisson_distribution.cpp 71018 2011-04-05 21:27:52Z steven_watanabe $\n *\n */\n\n#include <boost/random/poisson_distribution.hpp>\n\n#include <limits>\n\n#define BOOST_RANDOM_DISTRIBUTION boost::random::poisson_distribution<>\n#define BOOST_RANDOM_ARG1 mean\n#define BOOST_RANDOM_ARG1_DEFAULT 1.0\n#define BOOST_RANDOM_ARG1_VALUE 7.5\n\n#define BOOST_RANDOM_DIST0_MIN 0\n#define BOOST_RANDOM_DIST0_MAX (std::numeric_limits<int>::max)()\n#define BOOST_RANDOM_DIST1_MIN 0\n#define BOOST_RANDOM_DIST1_MAX (std::numeric_limits<int>::max)()\n\n#define BOOST_RANDOM_TEST1_PARAMS\n#define BOOST_RANDOM_TEST1_MIN 0.0\n#define BOOST_RANDOM_TEST1_MAX 10.0\n\n#define BOOST_RANDOM_TEST2_PARAMS (1000.0)\n#define BOOST_RANDOM_TEST2_MIN 10.0\n\n#include \"test_distribution.ipp\"\n", "meta": {"hexsha": "c8fd4421c984556f8d5393bdbfcc5a1734b39e66", "size": 983, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/random/test/test_poisson_distribution.cpp", "max_stars_repo_name": "ai-nikolaev/repo-cppboost", "max_stars_repo_head_hexsha": "218c4a977c6d8cd6f2864cdcea1b6ab53160d203", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2016-04-12T16:29:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-28T11:01:57.000Z", "max_issues_repo_path": "libs/random/test/test_poisson_distribution.cpp", "max_issues_repo_name": "ai-nikolaev/repo-cppboost", "max_issues_repo_head_hexsha": "218c4a977c6d8cd6f2864cdcea1b6ab53160d203", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-10-31T19:35:14.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-04T17:11:27.000Z", "max_forks_repo_path": "libs/random/test/test_poisson_distribution.cpp", "max_forks_repo_name": "ai-nikolaev/repo-cppboost", "max_forks_repo_head_hexsha": "218c4a977c6d8cd6f2864cdcea1b6ab53160d203", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-09-09T02:38:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-30T00:24:24.000Z", "avg_line_length": 28.9117647059, "max_line_length": 82, "alphanum_fraction": 0.8046795524, "num_tokens": 264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.4793117804183135}}
{"text": "// (C) Copyright Jeremy Siek 2001. Permission to copy, use, modify,\r\n// sell and distribute this software is granted provided this\r\n// copyright notice appears in all copies. This software is provided\r\n// \"as is\" without express or implied warranty, and with no claim as\r\n// to its suitability for any purpose.\r\n//\r\n// Sample output:\r\n//  mask =      101010101010\r\n//  Enter a 12-bit bitset in binary: 100110101101\r\n//  x =        100110101101\r\n//  As ulong:  2477\r\n//  And with mask: 100010101000\r\n//  Or with mask:  101110101111\r\n\r\n\r\n#include <iostream>\r\n#include <boost/dynamic_bitset.hpp>\r\n\r\nint main(int, char*[]) {\r\n  const boost::dynamic_bitset<> mask(12, 2730ul); \r\n  std::cout << \"mask = \" << mask << std::endl;\r\n\r\n  boost::dynamic_bitset<> x(12);\r\n  std::cout << \"x.size()=\" << x.size() << std::endl;\r\n\r\n  std::cout << \"Enter a 12-bit bitset in binary: \" << std::flush;\r\n  if (std::cin >> x) {\r\n    std::cout << \"input number:     \" << x << std::endl;\r\n    std::cout << \"As unsigned long: \" << x.to_ulong() << std::endl;\r\n    std::cout << \"And with mask:    \" << (x & mask) << std::endl;\r\n    std::cout << \"Or with mask:     \" << (x | mask) << std::endl;\r\n    std::cout << \"Shifted left:     \" << (x << 1) << std::endl;\r\n    std::cout << \"Shifted right:    \" << (x >> 1) << std::endl;\r\n  }\r\n  return EXIT_SUCCESS;\r\n}\r\n", "meta": {"hexsha": "3778cdd13673c8e02e3244deeb10d8c51c01813a", "size": 1328, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sdk/boost_1_30_0/libs/dynamic_bitset/example3.cpp", "max_stars_repo_name": "acidicMercury8/xray-1.0", "max_stars_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-01-30T12:51:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-31T08:36:49.000Z", "max_issues_repo_path": "sdk/boost_1_30_0/libs/dynamic_bitset/example3.cpp", "max_issues_repo_name": "acidicMercury8/xray-1.0", "max_issues_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_issues_repo_licenses": ["Linux-OpenIB"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sdk/boost_1_30_0/libs/dynamic_bitset/example3.cpp", "max_forks_repo_name": "acidicMercury8/xray-1.0", "max_forks_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.8918918919, "max_line_length": 69, "alphanum_fraction": 0.5828313253, "num_tokens": 407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754371026367, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.47931177752615794}}
{"text": "// SPDX-License-Identifier: Apache-2.0\n// \n// Copyright 2015 Conrad Sanderson (http://conradsanderson.id.au)\n// Copyright 2015 National ICT Australia (NICTA)\n// \n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n// http://www.apache.org/licenses/LICENSE-2.0\n// \n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS 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 <armadillo>\n#include \"catch.hpp\"\n\nusing namespace arma;\n\n\nTEST_CASE(\"fn_conj_1\")\n  {\n  vec re =   linspace<vec>(1,5,6);\n  vec im = 2*linspace<vec>(1,5,6);\n  \n  cx_vec a = cx_vec(re,im);\n  cx_vec b = conj(a);\n  \n  REQUIRE( accu(abs(real(b) - ( re))) == Approx(0.0).margin(0.001) );\n  REQUIRE( accu(abs(imag(b) - (-im))) == Approx(0.0).margin(0.001) );\n  }\n\n\n\nTEST_CASE(\"fn_conj2\")\n  {\n  cx_mat A = randu<cx_mat>(5,6);\n  \n  cx_mat B = conj(A);\n  \n  REQUIRE( all(vectorise(real(B) ==  real(A))) == true );\n  REQUIRE( all(vectorise(imag(B) == -imag(A))) == true );\n  }\n", "meta": {"hexsha": "20f79960548dee34a603f9a55be5b30466aa46dc", "size": 1363, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests2/fn_conj.cpp", "max_stars_repo_name": "getfiit/armadillo-code", "max_stars_repo_head_hexsha": "3a896deca12a0f596b52d84185ebfad65df650b7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests2/fn_conj.cpp", "max_issues_repo_name": "getfiit/armadillo-code", "max_issues_repo_head_hexsha": "3a896deca12a0f596b52d84185ebfad65df650b7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests2/fn_conj.cpp", "max_forks_repo_name": "getfiit/armadillo-code", "max_forks_repo_head_hexsha": "3a896deca12a0f596b52d84185ebfad65df650b7", "max_forks_repo_licenses": ["Apache-2.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.3958333333, "max_line_length": 75, "alphanum_fraction": 0.6324284666, "num_tokens": 377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6584175005616829, "lm_q2_score": 0.7279754489059775, "lm_q1q2_score": 0.47931177553894283}}
{"text": "#include \"CubicInterpolation/CubicSplines.h\"\n#include \"CubicInterpolation/InterpolantBuilder.h\"\n\n#include <boost/math/differentiation/finite_difference.hpp>\n#include <boost/math/interpolators/cardinal_cubic_b_spline.hpp>\n#include <boost/serialization/access.hpp>\n#include <vector>\n\nnamespace cubic_splines {\n\n/**\n * @brief Storage class to write and load the interpolation tables from  disk.\n * After reading and writing the object will be destructed.\n */\ntemplate <typename T> struct CubicSplines<T>::StorageData {\n  std::vector<T> y;\n  T lower_lim_derivate;\n  T upper_lim_derivate;\n\n  friend class boost::serialization::access;\n  template <class Archive> void serialize(Archive &ar, const unsigned int) {\n    ar &y;\n    ar &lower_lim_derivate;\n    ar &upper_lim_derivate;\n  };\n\npublic:\n  StorageData() = default;\n\n  template <typename T1>\n  StorageData(T1 const &_y, T _lower_lim_derivate, T _upper_lim_derivate)\n      : y(_y.begin(), _y.end()), lower_lim_derivate(_lower_lim_derivate),\n        upper_lim_derivate(_upper_lim_derivate){};\n\n  auto to_runtime_data() const {\n    return RuntimeData(y, lower_lim_derivate, upper_lim_derivate);\n  }\n};\n\ntemplate <typename T>\nstruct CubicSplines<T>::RuntimeData : public CubicSplines<T>::StorageData {\n\n  boost::math::interpolators::cardinal_cubic_b_spline<T> spline;\n\n  RuntimeData() = default;\n\n  template <typename T1>\n  RuntimeData(T1 _data, T _lower_lim_derivate, T _upper_lim_derivate)\n      : StorageData(_data, _lower_lim_derivate, _upper_lim_derivate),\n        spline(_data.data(), _data.size(), 0, 1, _lower_lim_derivate,\n               _upper_lim_derivate) {}\n\n  auto to_storage_data() const { return StorageData(*this); };\n};\n\ntemplate <typename T>\nCubicSplines<T>::CubicSplines(CubicSplines::RuntimeData _data)\n    : data(::std::make_unique<CubicSplines::RuntimeData>(_data)) {}\n\ntemplate <typename T>\nCubicSplines<T>::CubicSplines(Definition const &def, std::string path,\n                              std::string filename) {\n  try {\n    auto storage_data = load<CubicSplines>(path, filename);\n    *this = CubicSplines(storage_data.to_runtime_data());\n  } catch (std::system_error const &ex) {\n    if (ex.code().value() != ENOENT)\n      throw(ex);\n    *this = CubicSplines(def);\n    save(data->to_storage_data(), path, filename);\n  }\n}\n\ntemplate <typename T>\nCubicSplines<T>::CubicSplines(Definition const &def)\n    : data(::std::make_unique<CubicSplines::RuntimeData>()) {\n  using boost::math::differentiation::finite_difference_derivative;\n  auto func = [&def](T x) {\n    auto fx = def.f(x);\n    if (def.f_trafo)\n      fx = def.f_trafo->transform(fx);\n    return fx;\n  };\n  auto y = std::vector<T>(def.axis->required_nodes());\n  for (size_t n = 0; n < y.size(); ++n)\n    y[n] = func(def.axis->back_transform(n));\n  auto f_derivate = [func, axis = def.axis.get()](T t) {\n    return func(axis->back_transform(t));\n  };\n  auto diff_low = finite_difference_derivative(f_derivate, static_cast<T>(0));\n  auto diff_up = finite_difference_derivative(f_derivate, static_cast<T>(y.size() - 1));\n  data = ::std::make_unique<CubicSplines::RuntimeData>(y, diff_low, diff_up);\n}\n\ntemplate <typename T> T CubicSplines<T>::evaluate(T x) const { return data->spline(x); };\n\ntemplate <typename T> T CubicSplines<T>::prime(T x) const {\n  return data->spline.prime(x);\n};\n\ntemplate <typename T> T CubicSplines<T>::double_prime(T x) const {\n  return data->spline.double_prime(x);\n};\n} // namespace cubic_splines\n\ntemplate class cubic_splines::CubicSplines<float>;\ntemplate class cubic_splines::CubicSplines<double>;\n", "meta": {"hexsha": "f5d896b0684cf09d484ca8cf6c6b327ce9cd534b", "size": 3556, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/detail/CubicSplines.cxx", "max_stars_repo_name": "maxnoe/cubic_interpolation", "max_stars_repo_head_hexsha": "5e272ed3b2697a72bdbc4978b7eb7494c333bd5f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-01-07T15:35:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-14T06:59:47.000Z", "max_issues_repo_path": "src/detail/CubicSplines.cxx", "max_issues_repo_name": "maxnoe/cubic_interpolation", "max_issues_repo_head_hexsha": "5e272ed3b2697a72bdbc4978b7eb7494c333bd5f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2021-02-12T11:46:11.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-31T09:03:01.000Z", "max_forks_repo_path": "src/detail/CubicSplines.cxx", "max_forks_repo_name": "maxnoe/cubic_interpolation", "max_forks_repo_head_hexsha": "5e272ed3b2697a72bdbc4978b7eb7494c333bd5f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-02-12T14:34:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-19T13:33:52.000Z", "avg_line_length": 32.9259259259, "max_line_length": 89, "alphanum_fraction": 0.7103487064, "num_tokens": 956, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.47931177553894283}}
{"text": "#ifndef INCLUDED_scheme_nest_maps_ScaleMap_HH\n#define INCLUDED_scheme_nest_maps_ScaleMap_HH\n\n#include \"scheme/util/template_loop.hh\"\n#include \"scheme/util/SimpleArray.hh\"\n#include <boost/function.hpp>\n#include <boost/type_traits/make_signed.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/bind.hpp>\n#include <boost/static_assert.hpp>\n#include <iostream>\n#include <vector>\n\nnamespace scheme {\nnamespace nest {\nnamespace pmap {\n\n\t///@brief Parameter Mapping Policy for cartesian grids\n\t///@tparam DIM the dimension number of the input parameter space\n\t///@tparam Value the output value type, default\n\t///@tparam Index index type, default size_t\n\t///@tparam Float float type, default double\n\t///@note NEST num_cells MUST agree with cell_sizes_\n\t///@note bounds and cell indices are represented as SimpleArrays (like params) NOT Value Types\n\ttemplate<\n\t\tint DIM,\n\t\tclass Value = util::SimpleArray<DIM,double>,\n\t\tclass Index = uint64_t,\n\t\tclass Float = typename Value::Scalar\n\t>\n\tstruct ScaleMap {\n\t\tstatic int const DIMENSION = DIM;\n\t\ttypedef ScaleMap<DIM,Value,Index,Float> ThisType;\n\t\ttypedef Value ValueType ;\n\t\ttypedef Float FloatType ;\n\t\ttypedef Index IndexType ;\n\t\ttypedef typename boost::make_signed<Index>::type SignedIndex;\n\t\ttypedef util::SimpleArray<DIM,Index> Indices;\n\t\ttypedef util::SimpleArray<DIM,SignedIndex> SignedIndices;\n\t\ttypedef util::SimpleArray<DIM,Float> Params;\n\t\tBOOST_STATIC_ASSERT_MSG(DIM>0,\"ScaleMap DIM must be > 0\");\n\t private:\n\t\t///@brief lower bound on value space\n\t\tParams lower_bound_;\n\t\t///@brief upper bound on value space base size 1\n\t\tParams upper_bound_;\n\t\t///@brief distributes cell_index accross dimensions\n\t\tParams cell_width_;\n\t\tIndices cell_sizes_;\n\t\tIndices cell_sizes_pref_sum_;\n\t\tIndex num_cells_;\n\t public:\n\n\t \tParams const & lower_bound() const { return lower_bound_; }\n\t \tParams const & upper_bound() const { return upper_bound_; }\n\t \tParams const &  cell_width() const { return cell_width_; }\n\t \tIndices const & cell_sizes() const { return cell_sizes_; }\n\n\t\tstatic std::string pmap_name() { return \"ScaleMap<\"+boost::lexical_cast<std::string>(DIM)+\">\"; }\n\n\t\t///@brief construct with default lb, ub, bs\n\t\tScaleMap(){\tcell_sizes_.fill(1); lower_bound_.fill(0); upper_bound_.fill(1); init(); }\n\t\t///@brief construct with default lb, ub\n\t\ttemplate< class I >\n\t\tScaleMap(I const & bs) :\n\t\t\tcell_sizes_(bs) { lower_bound_.fill(0); upper_bound_.fill(1); init(); }\n\t\t///@brief construct with default bs\n\t\ttemplate< class P >\n\t\tScaleMap(P const & lb, P const & ub) :\n\t\t\tlower_bound_(lb), upper_bound_(ub) { cell_sizes_.fill(1); init(); }\n\t\t///@brief construct with specified lb, ub and bs\n\t\ttemplate< class P, class I >\n\t\tScaleMap(P const & lb, P const & ub, I const & bs) :\n\t\t\tlower_bound_(lb), upper_bound_(ub), cell_sizes_(bs) { init(); }\n\n\t\ttemplate< class I >\n\t\tvoid init(I const & bs){\n\t\t\tcell_sizes_ = bs;\n\t\t\tlower_bound_.fill(0);\n\t\t\tupper_bound_.fill(1);\n\t\t\tinit();\n\t\t}\n\n\t\ttemplate< class P >\n\t\tvoid init(P const & lb, P const & ub){\n\t\t\tlower_bound_ = lb;\n\t\t\tupper_bound_ = ub;\n\t\t\tcell_sizes_.fill(1);\n\t\t\tinit();\n\t\t}\n\n\t\ttemplate< class P, class I >\n\t\tvoid init(P const & lb, P const & ub, I const & bs){\n\t\t\tlower_bound_ = lb;\n\t\t\tupper_bound_ = ub;\n\t\t\tcell_sizes_  = bs;\n\t\t\tinit();\n\t\t}\n\n\t\t///@brief sets up cell_size_pref_sum\n\t\tvoid init(){\n\t\t\tnum_cells_ = cell_sizes_.prod();\n\t\t\tfor(size_t i = 0; i < DIM; ++i){\n\t\t\t\tcell_sizes_pref_sum_[i] = cell_sizes_.prod(i);\n\t\t\t\tcell_width_[i] = (upper_bound_[i]-lower_bound_[i])/(Float)cell_sizes_[i];\n\t\t\t\tassert(upper_bound_[i] > lower_bound_[i]);\n\t\t\t}\n\t\t}\n\n\t\t///@brief sets value based on cell_index and parameters using geometric bounds\n\t\t///@return false iff invalid parameters\n\t\tbool params_to_value(\n\t\t\tParams const & params,\n\t\t\tIndex cell_index,\n\t\t\tIndex resl,\n\t\t\tValue & value\n\t\t) const {\n\t\t\tfor(size_t i = 0; i < DIM; ++i){\n\t\t\t\tassert(cell_sizes_[i] > 0);\n\t\t\t\tassert(cell_sizes_[i] < 100000);\n\t\t\t\tassert(lower_bound_[i] < upper_bound_[i]);\n\t\t\t\tFloat bi = ( cell_index / cell_sizes_pref_sum_[i] ) % cell_sizes_[i];\n\t\t\t\tvalue[i] = lower_bound_[i] + cell_width_[i] * (bi + params[i]);\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\t///@brief sets params/cell_index from value\n\t\tbool value_to_params(\n\t\t\tValue const & value,\n\t\t\tIndex resl,\n\t\t\tParams & params,\n\t\t\tIndex & cell_index\n\t\t) const {\n\t\t\tvalue_to_params_for_cell(value,resl,params,0);\n\t\t\tcell_index = 0;\n\t\t\tfor(size_t i = 0; i < DIM; ++i){\n\t\t\t\tassert(cell_sizes_[i] > 0);\n\t\t\t\tassert(cell_sizes_[i] < 100000);\n\t\t\t\tassert(lower_bound_[i] < upper_bound_[i]);\n\t\t\t\t// Index cell_size_pref_sum = cell_sizes_.head(i).prod();\n\t\t\t\tFloat ci = (Index)params[i];\n\t\t\t\tcell_index += cell_sizes_pref_sum_[i] * ci;\n\t\t\t\tparams[i] -= (Float)ci;\n\t\t\t\tassert( 0.0 <= params[i] && params[i] <= 1.0);\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\t///@brief sets params/cell_index from value\n\t\tvoid value_to_params_for_cell(\n\t\t\tValue const & value,\n\t\t\tIndex resl,\n\t\t\tParams & params,\n\t\t\tIndex cell_index\n\t\t) const {\n\t\t\tIndices cell_indices = cellindex_to_indices(cell_index);\n\t\t\t// std::cout << \"CIDX \" << cell_indices.transpose() << std::endl;\n\t\t\tfor(size_t i = 0; i < DIM; ++i){\n\t\t\t\tassert(cell_sizes_[i] > 0);\n\t\t\t\tassert(cell_sizes_[i] < 100000);\n\t\t\t\tassert(lower_bound_[i] < upper_bound_[i]);\n\t\t\t\t// Index cell_size_pref_sum = cell_sizes_.head(i).prod();\n\t\t\t\tparams[i] = ( value[i] - lower_bound_[i] ) / cell_width_[i];\n\t\t\t\tparams[i] -= (Float)cell_indices[i];\n\t\t\t}\n\t\t}\n\n\t\tIndex indices_to_cellindex(Indices const & indices) const {\n\t\t\tIndex index = 0;\n\t\t\tfor(size_t i = 0; i < DIM; ++i){\n\t\t\t\tassert(indices[i] < cell_sizes_[i]);\n\t\t\t\tindex += indices[i]*cell_sizes_pref_sum_[i];\n\t\t\t}\n\t\t\treturn index;\n\t\t}\n\n\t\tIndices cellindex_to_indices(Index index) const {\n\t\t\tIndices indices;\n\t\t\tfor(size_t i = 0; i < DIM; ++i){\n\t\t\t\tindices[i] = ( index / cell_sizes_pref_sum_[i] ) % cell_sizes_[i];\n\t\t\t\tassert(indices[i] < cell_sizes_[i]);\n\t\t\t}\n\t\t\treturn indices;\n\t\t}\n\n\t\ttemplate<class OutIter>\n\t\tvoid push_cell_index(SignedIndices const & indices, OutIter out) const {\n\t\t\t*(out++) = indices_to_cellindex(indices.template cast<size_t>());\n\t\t}\n\n\t\t// template<class OutIter>\n\t\t// void get_neighbors(Indices const & indices, Index cell_index, Index resl, OutIter out)  {\n\t\t// \t// std::cout << indices.transpose() << std::endl;\n\t\t// \tSignedIndices lb = ((indices.template cast<int>()-1).max(     0     ));\n\t\t// \tSignedIndices ub = ((indices.template cast<int>()+1).min((1<<resl)-1));\n\t\t// \t// std::cout << \"IX \" << indices.transpose() << \" cell \" << cell_index << std::endl;\n\t\t// \t// std::cout << \"LB \" << lb.transpose() << std::endl;\n\t\t// \t// std::cout << \"UB \" << ub.transpose() << std::endl;\n\t\t// \tboost::function<void(SignedIndices)> functor;\n\t\t// \tfunctor = boost::bind( & ThisType::template push_index<OutIter>, this, _1, cell_index, resl, out );\n\t\t// \tutil::NESTED_FOR<DIM>(lb,ub,functor);\n\t\t// }\n\n\t\t///@brief return the cell_index of neighboring cells within delta of value\n\t\t///@note delta parameter is in \"Parameter Space\"\n\t\ttemplate<class OutIter>\n\t\tvoid get_neighboring_cells(\n\t\t\tValue const & value,\n\t\t\tIndex resl,\n\t\t\tFloat param_delta,\n\t\t\tOutIter out\n\t\t) const {\n\t\t\t// Float param_delta = 1.0 / (Float)(1<<resl);\n\t\t\tassert( param_delta > 0);\n\t\t\t// convert to value space, decided against this\n\t\t\t// Params delta_param;\n\t\t\t// for(size_t i = 0; i < DIM; ++i) delta_param[i] = delta / cell_width_[i];\n\t\t\tParams params;\n\t\t\tvalue_to_params_for_cell(value,resl,params,0);\n\t\t\tSignedIndex const BIG = 12345678;\n\t\t\tSignedIndices lb = (params-param_delta+(Float)BIG).max((Float)BIG).template cast<SignedIndex>() - BIG ;\n\t\t\tSignedIndices ub = (params+param_delta).template cast<Index>().min(cell_sizes_-(Index)1).template cast<SignedIndex>();\n\t\t\t// std::cout << \"PM \" << params.transpose() << std::endl;\n\t\t\t// std::cout << \"DL \" << delta_param.transpose() << std::endl;\n\t\t\t// std::cout << \"LB \" << lb.transpose() << std::endl;\n\t\t\t// std::cout << \"UB \" << ub.transpose() << std::endl;\n\t\t\tboost::function<void(SignedIndices)> functor;\n\t\t\tfunctor = boost::bind( & ThisType::template push_cell_index<OutIter>, this, _1, out );\n\t\t\tutil::NESTED_FOR<DIM>(lb,ub,functor);\n\t\t}\n\n\t\t///@brief aka covering radius max distance from bin center to any value within bin\n\t\tFloat bin_circumradius(Index resl) const {\n\t\t\tParams width = (upper_bound_-lower_bound_) / cell_sizes_.template cast<Float>();\n\t\t\treturn 0.5/(Float)(1<<resl) * sqrt((width*width).sum()); // squaredNorm\n\t\t}\n\n\t\t///@brief maximum distance from the bin center which must be within the bin\n\t\tFloat bin_inradius(Index resl) const {\n\t\t\tParams width = (upper_bound_-lower_bound_) / cell_sizes_.template cast<Float>();\n\t\t\treturn 1.5/(Float)(1<<resl) * width.minCoeff(); // norm\n\t\t}\n\n\t\t///@brief cell size\n\t\tIndex num_cells() const { return num_cells_; }\n\t \tvirtual ~ScaleMap(){}\n\t};\n\n\ttemplate<\n\t\tint DIM,\n\t\tclass Value,\n\t\tclass Index,\n\t\tclass Float\n\t>\n\tstd::ostream & operator << ( std::ostream & out, ScaleMap<DIM,Value,Index,Float> const & sm ){\n\t\tout << \"ScaleMap cell_sizes = \" << sm.cell_sizes() << \" cell_widths = \" << sm.cell_width();\n\t\treturn out;\n\t}\n\n}\n}\n}\n\n#endif\n", "meta": {"hexsha": "5507ceb66f1dfb3c7391671edf262eeb9d41e036", "size": 9008, "ext": "hh", "lang": "C++", "max_stars_repo_path": "schemelib/scheme/nest/pmap/ScaleMap.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/nest/pmap/ScaleMap.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/nest/pmap/ScaleMap.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": 33.8646616541, "max_line_length": 121, "alphanum_fraction": 0.6686278863, "num_tokens": 2647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.47931177553894283}}
{"text": "// Copyright 2015-2018 Hans Dembinski\n//\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n//[ guide_histogram_serialization\n\n#include <boost/archive/text_iarchive.hpp>\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/histogram.hpp>\n#include <boost/histogram/serialization.hpp> // includes serialization code\n#include <cassert>\n#include <sstream>\n\nint main() {\n  using namespace boost::histogram;\n\n  auto a = make_histogram(axis::regular<>(3, -1.0, 1.0, \"axis 0\"),\n                          axis::integer<>(0, 2, \"axis 1\"));\n  a(0.5, 1);\n\n  std::string buf; // to hold persistent representation\n\n  // store histogram\n  {\n    std::ostringstream os;\n    boost::archive::text_oarchive oa(os);\n    oa << a;\n    buf = os.str();\n  }\n\n  auto b = decltype(a)(); // create a default-constructed second histogram\n\n  assert(b != a); // b is empty, a is not\n\n  // load histogram\n  {\n    std::istringstream is(buf);\n    boost::archive::text_iarchive ia(is);\n    ia >> b;\n  }\n\n  assert(b == a); // now b is equal to a\n}\n\n//]\n", "meta": {"hexsha": "c00ef3cd608e7e7169476b27e240b2a1324a5e36", "size": 1128, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/histogram/examples/guide_histogram_serialization.cpp", "max_stars_repo_name": "cpp-pm/boost", "max_stars_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "libs/histogram/examples/guide_histogram_serialization.cpp", "max_issues_repo_name": "cpp-pm/boost", "max_issues_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "libs/histogram/examples/guide_histogram_serialization.cpp", "max_forks_repo_name": "cpp-pm/boost", "max_forks_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 23.5, "max_line_length": 75, "alphanum_fraction": 0.6524822695, "num_tokens": 303, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.727975443004307, "lm_q1q2_score": 0.4793117716531798}}
{"text": "/*    This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.\n *    See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.\n *    Author(s):       Clement Jamin\n *\n *    Copyright (C) 2016 Inria\n *\n *    Modification(s):\n *      - YYYY/MM Author: Description of the modification\n */\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE Tangential_complex - test tangential complex\n#include <boost/test/unit_test.hpp>\n\n#include <gudhi/Tangential_complex.h>\n#include <gudhi/sparsify_point_set.h>\n\n#include <CGAL/Epick_d.h>\n#include <CGAL/Random.h>\n\n#include <array>\n#include <vector>\n\nnamespace tc = Gudhi::tangential_complex;\n\nBOOST_AUTO_TEST_CASE(test_Spatial_tree_data_structure) {\n  typedef CGAL::Epick_d<CGAL::Dynamic_dimension_tag> Kernel;\n  typedef Kernel::Point_d Point;\n  typedef tc::Tangential_complex<\n      Kernel, CGAL::Dynamic_dimension_tag,\n      CGAL::Parallel_tag> TC;\n\n  const int INTRINSIC_DIM = 2;\n  const int AMBIENT_DIM = 3;\n  const int NUM_POINTS = 50;\n\n  Kernel k;\n\n  // Generate points on a 2-sphere\n  CGAL::Random_points_on_sphere_d<Point> generator(AMBIENT_DIM, 3.);\n  std::vector<Point> points;\n  points.reserve(NUM_POINTS);\n  for (int i = 0; i < NUM_POINTS; ++i)\n    points.push_back(*generator++);\n\n  // Compute the TC\n  TC tc(points, INTRINSIC_DIM, k);\n  tc.compute_tangential_complex();\n\n  // Try to fix inconsistencies. Give it 60 seconds to succeed\n  auto perturb_ret = tc.fix_inconsistencies_using_perturbation(0.01, 60);\n\n  BOOST_CHECK(perturb_ret.success);\n\n  // Export the TC into a Simplex_tree\n  Gudhi::Simplex_tree<> stree;\n  tc.create_complex(stree);\n}\n\nBOOST_AUTO_TEST_CASE(test_mini_tangential) {\n  typedef CGAL::Epick_d<CGAL::Dynamic_dimension_tag> Kernel;\n  typedef Kernel::Point_d Point;\n  typedef tc::Tangential_complex<Kernel, CGAL::Dynamic_dimension_tag, CGAL::Parallel_tag> TC;\n\n\n  const int INTRINSIC_DIM = 1;\n\n  // Generate points on a 2-sphere\n  std::vector<Point> points;\n  // [[0, 0], [1, 0], [0, 1], [1, 1]]\n  std::vector<double> point = {0.0, 0.0};\n  points.push_back(Point(point.size(), point.begin(), point.end()));\n  point = {1.0, 0.0};\n  points.push_back(Point(point.size(), point.begin(), point.end()));\n  point = {0.0, 1.0};\n  points.push_back(Point(point.size(), point.begin(), point.end()));\n  point = {1.0, 1.0};\n  points.push_back(Point(point.size(), point.begin(), point.end()));\n  std::clog << \"points = \" << points.size() << std::endl;\n  Kernel k;\n\n  // Compute the TC\n  TC tc(points, INTRINSIC_DIM, k);\n  tc.compute_tangential_complex();\n  TC::Num_inconsistencies num_inc = tc.number_of_inconsistent_simplices();\n  std::clog << \"TC vertices = \" << tc.number_of_vertices() << \" - simplices = \" << num_inc.num_simplices <<\n               \" - inc simplices = \" << num_inc.num_inconsistent_simplices <<\n               \" - inc stars = \" << num_inc.num_inconsistent_stars << std::endl;\n\n  BOOST_CHECK(tc.number_of_vertices() == 4);\n  BOOST_CHECK(num_inc.num_simplices == 4);\n  BOOST_CHECK(num_inc.num_inconsistent_simplices == 0);\n  BOOST_CHECK(num_inc.num_inconsistent_stars == 0);\n\n  // Export the TC into a Simplex_tree\n  Gudhi::Simplex_tree<> stree;\n  tc.create_complex(stree);\n  std::clog << \"ST vertices = \" << stree.num_vertices() << \" - simplices = \" << stree.num_simplices() << std::endl;\n\n  BOOST_CHECK(stree.num_vertices() == 4);\n  BOOST_CHECK(stree.num_simplices() == 6);\n\n  tc.fix_inconsistencies_using_perturbation(0.01, 30.0);\n\n  BOOST_CHECK(tc.number_of_vertices() == 4);\n  BOOST_CHECK(num_inc.num_simplices == 4);\n  BOOST_CHECK(num_inc.num_inconsistent_simplices == 0);\n  BOOST_CHECK(num_inc.num_inconsistent_stars == 0);\n\n  // Export the TC into a Simplex_tree\n  tc.create_complex(stree);\n  std::clog << \"ST vertices = \" << stree.num_vertices() << \" - simplices = \" << stree.num_simplices() << std::endl;\n\n  BOOST_CHECK(stree.num_vertices() == 4);\n  BOOST_CHECK(stree.num_simplices() == 6);\n}\n\n#ifdef GUDHI_DEBUG\nBOOST_AUTO_TEST_CASE(test_basic_example_throw) {\n  typedef CGAL::Epick_d<CGAL::Dynamic_dimension_tag> Kernel;\n  typedef Kernel::FT FT;\n  typedef Kernel::Point_d Point;\n  typedef Kernel::Vector_d Vector;\n  typedef tc::Tangential_complex<Kernel, CGAL::Dynamic_dimension_tag,CGAL::Parallel_tag> TC;\n\n  const int INTRINSIC_DIM = 2;\n  const int AMBIENT_DIM = 3;\n  const int NUM_POINTS = 1000;\n\n  Kernel k;\n\n  // Generate points on a 2-sphere\n  CGAL::Random_points_on_sphere_d<Point> generator(AMBIENT_DIM, 3.);\n  std::vector<Point> points;\n  points.reserve(NUM_POINTS);\n  for (int i = 0; i < NUM_POINTS; ++i)\n    points.push_back(*generator++);\n\n  // Compute the TC\n  TC tc(points, INTRINSIC_DIM, k);\n  tc.set_max_squared_edge_length(0.01);\n  std::clog << \"test_basic_example_throw - set_max_squared_edge_length(0.01) to make GUDHI_CHECK fail\" << std::endl;\n  BOOST_CHECK_THROW(tc.compute_tangential_complex(), std::invalid_argument);\n\n}\n#endif\n", "meta": {"hexsha": "023c1e1a284b026b62cd0c8dfceb3cc1e6038712", "size": 4907, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Tangential_complex/test/test_tangential_complex.cpp", "max_stars_repo_name": "m0baxter/gudhi-devel", "max_stars_repo_head_hexsha": "6e14ef1f31e09f3875316440303450ff870d9881", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 146.0, "max_stars_repo_stars_event_min_datetime": "2019-03-15T14:10:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T21:14:52.000Z", "max_issues_repo_path": "src/Tangential_complex/test/test_tangential_complex.cpp", "max_issues_repo_name": "m0baxter/gudhi-devel", "max_issues_repo_head_hexsha": "6e14ef1f31e09f3875316440303450ff870d9881", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 398.0, "max_issues_repo_issues_event_min_datetime": "2019-03-07T14:55:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T14:50:40.000Z", "max_forks_repo_path": "src/Tangential_complex/test/test_tangential_complex.cpp", "max_forks_repo_name": "m0baxter/gudhi-devel", "max_forks_repo_head_hexsha": "6e14ef1f31e09f3875316440303450ff870d9881", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 51.0, "max_forks_repo_forks_event_min_datetime": "2019-03-08T15:58:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T10:23:23.000Z", "avg_line_length": 33.380952381, "max_line_length": 116, "alphanum_fraction": 0.7067454657, "num_tokens": 1416, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.4793117706595721}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2014 Roshan <thisisroshansmail@gmail.com>\n//\n// Distributed under the Boost Software License, Version 1.0\n// See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt\n//\n// See http://boostorg.github.com/compute for more information.\n//---------------------------------------------------------------------------//\n\n#ifndef BOOST_COMPUTE_RANDOM_DISCRETE_DISTRIBUTION_HPP\n#define BOOST_COMPUTE_RANDOM_DISCRETE_DISTRIBUTION_HPP\n\n#include <numeric>\n\n#include <boost/config.hpp>\n#include <boost/type_traits.hpp>\n#include <boost/static_assert.hpp>\n\n#include <boost/compute/command_queue.hpp>\n#include <boost/compute/function.hpp>\n#include <boost/compute/algorithm/accumulate.hpp>\n#include <boost/compute/algorithm/copy.hpp>\n#include <boost/compute/algorithm/transform.hpp>\n#include <boost/compute/detail/literal.hpp>\n#include <boost/compute/types/fundamental.hpp>\n\nnamespace boost\n{\n    namespace compute\n    {\n\n        /// \\class discrete_distribution\n        /// \\brief Produces random integers on the interval [0, n), where\n        /// probability of each integer is given by the weight of the ith\n        /// integer divided by the sum of all weights.\n        ///\n        /// The following example shows how to setup a discrete distribution to\n        /// produce 0 and 1 with equal probability\n        ///\n        /// \\snippet test/test_discrete_distribution.cpp generate\n        ///\n        template <class IntType = uint_>\n        class discrete_distribution\n        {\n        public:\n            typedef IntType result_type;\n\n            /// Creates a new discrete distribution with a single weight p = { 1 }.\n            /// This distribution produces only zeroes.\n            discrete_distribution()\n                : m_probabilities(1, double(1)),\n                  m_scanned_probabilities(1, double(1))\n            {\n            }\n\n            /// Creates a new discrete distribution with weights given by\n            /// the range [\\p first, \\p last).\n            template <class InputIterator>\n            discrete_distribution(InputIterator first, InputIterator last)\n                : m_probabilities(first, last),\n                  m_scanned_probabilities(std::distance(first, last))\n            {\n                if (first != last)\n                {\n                    // after this m_scanned_probabilities.back() is a sum of all\n                    // weights from the range [first, last)\n                    std::partial_sum(first, last, m_scanned_probabilities.begin());\n\n                    std::vector<double, mi_stl_allocator<double>>::iterator i = m_probabilities.begin();\n                    std::vector<double, mi_stl_allocator<double>>::iterator j = m_scanned_probabilities.begin();\n                    for (; i != m_probabilities.end(); ++i, ++j)\n                    {\n                        // dividing each weight by sum of all weights to\n                        // get probabilities\n                        *i = *i / m_scanned_probabilities.back();\n                        // dividing each partial sum of weights by sum of\n                        // all weights to get partial sums of probabilities\n                        *j = *j / m_scanned_probabilities.back();\n                    }\n                }\n                else\n                {\n                    m_probabilities.push_back(double(1));\n                    m_scanned_probabilities.push_back(double(1));\n                }\n            }\n\n            /// Destroys the discrete_distribution object.\n            ~discrete_distribution()\n            {\n            }\n\n            /// Returns the probabilities\n            ::std::vector<double, mi_stl_allocator<double>> probabilities() const\n            {\n                return m_probabilities;\n            }\n\n            /// Returns the minimum potentially generated value.\n            result_type min BOOST_PREVENT_MACRO_SUBSTITUTION() const\n            {\n                return result_type(0);\n            }\n\n            /// Returns the maximum potentially generated value.\n            result_type max BOOST_PREVENT_MACRO_SUBSTITUTION() const\n            {\n                size_t type_max = static_cast<size_t>(\n                    (std::numeric_limits<result_type>::max)());\n                if (m_probabilities.size() - 1 > type_max)\n                {\n                    return (std::numeric_limits<result_type>::max)();\n                }\n                return static_cast<result_type>(m_probabilities.size() - 1);\n            }\n\n            /// Generates uniformly distributed integers and stores\n            /// them to the range [\\p first, \\p last).\n            template <class OutputIterator, class Generator>\n            void generate(OutputIterator first,\n                          OutputIterator last,\n                          Generator &generator,\n                          command_queue &queue)\n            {\n                std::string source = \"inline IntType scale_random(uint x)\\n\";\n\n                source = source +\n                         \"{\\n\" +\n                         \"float rno = convert_float(x) / UINT_MAX;\\n\";\n                for (size_t i = 0; i < m_scanned_probabilities.size() - 1; i++)\n                {\n                    source = source +\n                             \"if(rno <= \" + detail::make_literal<float>(m_scanned_probabilities[i]) + \")\\n\" +\n                             \"   return \" + detail::make_literal(i) + \";\\n\";\n                }\n\n                source = source +\n                         \"return \" + detail::make_literal(m_scanned_probabilities.size() - 1) + \";\\n\" +\n                         \"}\\n\";\n\n                BOOST_COMPUTE_FUNCTION(IntType, scale_random, (const uint_ x), {});\n\n                scale_random.set_source(source);\n                scale_random.define(\"IntType\", type_name<IntType>());\n\n                generator.generate(first, last, scale_random, queue);\n            }\n\n        private:\n            ::std::vector<double, mi_stl_allocator<double>> m_probabilities;\n            ::std::vector<double, mi_stl_allocator<double>> m_scanned_probabilities;\n\n            BOOST_STATIC_ASSERT_MSG(\n                boost::is_integral<IntType>::value,\n                \"Template argument must be integral\");\n        };\n\n    } // namespace compute\n} // namespace boost\n\n#endif // BOOST_COMPUTE_RANDOM_UNIFORM_INT_DISTRIBUTION_HPP\n", "meta": {"hexsha": "00eb6b89d9e76de4a6a7e220028ece4e63e2dd12", "size": 6455, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "compute/include/boost/compute/random/discrete_distribution.hpp", "max_stars_repo_name": "atksh/mimalloc-lgb", "max_stars_repo_head_hexsha": "add692a5ef9a91cad0bc78fa18a051d43a8c930e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "compute/include/boost/compute/random/discrete_distribution.hpp", "max_issues_repo_name": "atksh/mimalloc-lgb", "max_issues_repo_head_hexsha": "add692a5ef9a91cad0bc78fa18a051d43a8c930e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "compute/include/boost/compute/random/discrete_distribution.hpp", "max_forks_repo_name": "atksh/mimalloc-lgb", "max_forks_repo_head_hexsha": "add692a5ef9a91cad0bc78fa18a051d43a8c930e", "max_forks_repo_licenses": ["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.6012269939, "max_line_length": 112, "alphanum_fraction": 0.5388071263, "num_tokens": 1220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754371026368, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.4793117677674168}}
{"text": "#include <vector>\n#include <boost/math/distributions/uniform.hpp>\n#include \"uniform_dist.h\"\n\nstochastic::UniformDistribution::UniformDistribution(double lower, double upper)\n  : Distribution(),\n    lower_bound_{lower},\n    upper_bound_{upper},\n    distribution_{lower, upper}\n{}\n\nstd::vector<double> stochastic::UniformDistribution::cumulative_dist_func(\n    const std::vector<double>& locations) const {\n  std::vector<double> evaluations(locations.size());\n\n  for (unsigned int i = 0; i < locations.size(); ++i) {\n    evaluations[i] = cdf(distribution_, locations[i]);\n  }\n\n  return evaluations;\n}\n\nstd::vector<double> stochastic::UniformDistribution::inv_cumulative_dist_func(\n    const std::vector<double>& probabilities) const {\n  std::vector<double> evaluations(probabilities.size());\n\n  for (unsigned int i = 0; i < probabilities.size(); ++i) {\n    evaluations[i] = quantile(distribution_, probabilities[i]);\n  }\n\n  return evaluations;\n}\n", "meta": {"hexsha": "2f51a063adf977a823d7878e9ae2c2bacc83cdc7", "size": 944, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/uniform_dist.cc", "max_stars_repo_name": "fmckenna/smelt", "max_stars_repo_head_hexsha": "4e8a786fc415fc99bd79ada885e8312ed0eb36e0", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-05-07T03:14:27.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-19T07:10:52.000Z", "max_issues_repo_path": "src/uniform_dist.cc", "max_issues_repo_name": "fmckenna/smelt", "max_issues_repo_head_hexsha": "4e8a786fc415fc99bd79ada885e8312ed0eb36e0", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-04-11T19:29:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-11T19:29:47.000Z", "max_forks_repo_path": "src/uniform_dist.cc", "max_forks_repo_name": "fmckenna/smelt", "max_forks_repo_head_hexsha": "4e8a786fc415fc99bd79ada885e8312ed0eb36e0", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-03-25T20:08:22.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-04T13:02:31.000Z", "avg_line_length": 28.6060606061, "max_line_length": 80, "alphanum_fraction": 0.7224576271, "num_tokens": 210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754371026368, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.4793117628880461}}
{"text": "/* \n * Author: Johannes M Dieterich\n */\n\n#ifndef WANGGOVINDCARTER_HPP\n#define WANGGOVINDCARTER_HPP\n\n#include <armadillo>\n#include <array>\n#include <memory>\n#include \"KEDF.hpp\"\n#include \"IntKernelODE.hpp\"\nusing namespace std;\nusing namespace arma;\n\n#include \"TayloredWangGovindCarter.hpp\"\n\nclass WangGovindCarterODE : public ODEKernel {\n    \npublic:\n    WangGovindCarterODE(const double beta, const double gamma);\n    ~WangGovindCarterODE();\n    void evaluate(const double t, double y[], double yp[]) override;\n    \nprivate:\n    double _beta;\n    double _gamma;\n};\n\nclass AnalyticalWangGovindCarterKernel {\n    \npublic:\n    AnalyticalWangGovindCarterKernel(const double alpha, const double beta, const double gamma, const size_t numTermsAB = 100);\n    ~AnalyticalWangGovindCarterKernel();\n    \n    void fillWGCKernel(unique_ptr<cx_cube>& kernel, unique_ptr<cx_cube>& betaKernel, const cube* gNorms);\n    \nprivate:\n    \n    void elementWGC(const double eta, array<int,3>& w);\n    \n    void fillAB();\n    \n    size_t _numTermsAB;\n    double _pea;\n    double _cue;\n    double _ell;\n    double _cOne;\n    double _cTwo;\n    double _aM1;\n    vector<double> _an;\n    vector<double> _bn;\n};\n\nclass NumericalWangGovindCarterKernel {\n    \npublic:\n    NumericalWangGovindCarterKernel(const double alpha, const double beta, const double gamma, const double rhoS);\n    ~NumericalWangGovindCarterKernel();\n    \n    void fillWGCKernel(cube* kernel0th, const cube* gNorms);\n    \n    void fillWGCKernel(cube* kernel0th, cube* kernel1st, const cube* gNorms);\n    \n    void fillWGCKernel(cube* kernel0th, cube* kernel1st, cube* kernel2nd, const cube* gNorms);\n    \n    void fillWGCKernel(cube* kernel0th, cube* kernel1st, cube* kernel2nd, cube* kernel3rd, const cube* gNorms);\n    \nprivate:\n    double _tkFStar;\n    double _alpha;\n    double _beta;\n    double _gamma;\n    double _rhoS;\n    \n    unique_ptr<mat> _w;\n    shared_ptr<vec> _eta;\n    int _nVals;\n    double *_nls_wpp;\n    double *_nls_w1pp;\n    double *_nls_w2pp;\n};\n\nclass NumericalRealSpaceWangGovindCarterKernel {\n    \npublic:\n    NumericalRealSpaceWangGovindCarterKernel();\n    ~NumericalRealSpaceWangGovindCarterKernel();\n    \nprivate:\n    double _tkFStar;\n    double _alpha;\n    double _beta;\n    double _gamma;\n    double _rhoS;\n    \n    unique_ptr<mat> _w;\n    shared_ptr<vec> _eta;\n    int _nVals;\n    shared_ptr<vec> _nls_wpp;\n    shared_ptr<vec> _nls_w1pp;\n    shared_ptr<vec> _nls_w2pp;\n};\n\n#endif /* WANGGOVINDCARTER_HPP */\n\n", "meta": {"hexsha": "fb856085aca4e6e1509966b496b45076743d234a", "size": 2479, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/WangGovindCarter.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/WangGovindCarter.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/WangGovindCarter.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": 23.1682242991, "max_line_length": 127, "alphanum_fraction": 0.7027027027, "num_tokens": 730, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835411997897, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4792988673682786}}
{"text": "#include <iostream>\n#include <vector>\n#include <cmath>\n#include <string>\n#include <fstream>\n#include <limits>\n\n#include <boost/program_options.hpp>\n\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/math/special_functions/digamma.hpp>\n\n#include <dlib/optimization.h>\n\n#include \"misc.hpp\"\n#include \"NBModel.hpp\"\n\n\nnamespace po = boost::program_options;\n\n// This would optimize a mixture of two three densities; We shall derive the \n// parameters in the p,r format. Later we can convert them to the m,r format\n// as required.\n\n// A. one Dirac point mass and two negative binomials\n// B. One Dirac point mass and one negative binomials\n// C. A single negative binomial\n// D. Hurdle distributions ?\n\ntypedef dlib::matrix<double,0,1> column_vector;\nusing namespace std::placeholders;\n\ntypedef std::numeric_limits< double > dbl;\n\nclass MixtureModelC {\n\n    private:\n\n        po::options_description desc;\n        std::string infile_str;\n        std::string outdir_str;\n        std::string prefix_str;\n        int density_count;\n        long sample_count;\n        std::vector<long> sample_vec;\n        double* mem_prob_mat; \n\n        // For our model with one zero density + two NB density; the r_val[0]\n        // would be undefined. \n        //std::vector<double> prior_vec;\n        double prior_vec[3];\n        double p_vec[3];\n        double r_vec[3];\n        double mean_vec[3];\n\n        double CD_LL_value_k(int density_ind, double r_val);\n        double CD_LL_gradient_k(int density_ind, double r_val);\n\n    public:\n       \n        MixtureModelC();\n        void print_help();\n        bool parse_args(int argc, char* argv[]);\n        void read_infile();\n        void allocate_resources();\n        void initialize();\n        void main_func();\n        void free_vars();\n        double get_mem_prob(int density_ind, int sample_ind);\n        void set_mem_prob(double mem_prob, int density_ind, int sample_ind);\n\n        std::vector<long> get_sub_vec(std::vector<long>& lvec, \n            int start_p, int end_p);\n        double CD_LL_value_comp1(const column_vector& m);\n        double CD_LL_value_comp2(const column_vector& m);\n\n        const column_vector CD_LL_gradient_comp1(const column_vector& m);\n        const column_vector CD_LL_gradient_comp2(const column_vector& m);\n\n        double get_NB_density(long xi_val, double p_val, double r_val);\n\n        void init_EM_params();\n        void do_E_step();\n        void do_M_step();\n        void update_p_val(int k);\n        void update_prior_val(int k);\n        double get_LL();\n        \n};\n\ndouble MixtureModelC::get_NB_density(long xi_val, double p_val, double r_val) {\n\n    double lval1 = lgamma(xi_val + r_val) -lgamma(xi_val + 1) -lgamma(r_val) + \n            xi_val * log (p_val) + r_val * log(1 - p_val);\n    double lval2 = exp(lval1);\n\n    return (lval2);\n\n}\n\ndouble MixtureModelC::CD_LL_value_k(int density_ind, double r_val) {\n    \n    if (!(density_ind == 1 || density_ind == 2)) {\n        std::string err_str = \"Density index and function mismathch.\";\n        throw std::runtime_error(err_str);\n    }\n\n    double lpval = p_vec[density_ind];\n    double lprior_val = prior_vec[density_ind];\n    double lprior_ln = log(lprior_val);\n\n    double total_ll = 0;\n\n    for (int j_ind = 0; j_ind < sample_vec.size(); j_ind++) {\n        long xi_val = sample_vec[j_ind];\n\n        double lval1 = lgamma(xi_val + r_val) -lgamma(xi_val + 1) \n            - lgamma(r_val) + xi_val * log (lpval) + r_val * log(1 - lpval);\n        double lval2 = lprior_ln + lval1;\n        double lmem_prob = get_mem_prob(density_ind, j_ind);\n        double LL_xi = lmem_prob * lval2;\n        total_ll += LL_xi;\n    }         \n\n    return total_ll;\n}\n\ndouble MixtureModelC::CD_LL_gradient_k(int density_ind, double r_val) {\n    \n    if (!(density_ind == 1 || density_ind == 2)) {\n        std::string err_str = \"Density index and function mismathch.\";\n        throw std::runtime_error(err_str);\n    }\n\n    double lpval = p_vec[density_ind];\n\n    double total_gradient = 0;\n\n    for (int j_ind = 0; j_ind < sample_vec.size(); j_ind++) {\n        long xi_val = sample_vec[j_ind];\n\n        double lval1 = boost::math::digamma(xi_val + r_val) - \n            boost::math::digamma(r_val) + log(1 - lpval);\n        double lmem_prob = get_mem_prob(density_ind, j_ind);\n        double gradient_xi = lmem_prob * lval1;\n        total_gradient += gradient_xi;\n    }         \n\n    return total_gradient;\n}\n\ndouble MixtureModelC::CD_LL_value_comp1(const column_vector& m) {\n    const double r_val = m(0);\n    double lval1 = CD_LL_value_k(1, r_val); \n    return (lval1);\n}\n\ndouble MixtureModelC::CD_LL_value_comp2(const column_vector& m) {\n    const double r_val = m(0);\n    double lval1 = CD_LL_value_k(2, r_val); \n    return (lval1);\n}\n\nconst column_vector MixtureModelC::CD_LL_gradient_comp1(const column_vector& m) {\n    const double r_val = m(0);\n    double lval1 = CD_LL_gradient_k(1, r_val);\n    column_vector lval2 = {lval1};\n    return (lval2);\n}\n\nconst column_vector MixtureModelC::CD_LL_gradient_comp2(const column_vector& m) {\n    const double r_val = m(0);\n    double lval1 = CD_LL_gradient_k(2, r_val);\n    column_vector lval2 = {lval1};\n    return (lval2);\n}\n\nMixtureModelC::MixtureModelC() { \n}\n\nvoid MixtureModelC::free_vars() {\n    // Release the resources allocated by new\n    delete[]  mem_prob_mat;\n}\n\nvoid MixtureModelC::allocate_resources() {\n\n    if (density_count == 0 || sample_count == 0) {\n        std::string err_msg = \"Invalid value(s); density_count: \" + \n            std::to_string(density_count) + \", sample_count: \" + \n            std::to_string(sample_count);\n        throw std::runtime_error(err_msg);\n    }\n\n    mem_prob_mat = new double[density_count * sample_count];\n}\n\nvoid MixtureModelC::initialize() {\n    read_infile();\n    allocate_resources();\n}\n\nvoid MixtureModelC::read_infile() {\n\n    std::ifstream inf(infile_str);\n    std::string line1;     \n    long temp_num1;   \n    while (std::getline(inf, line1)) {\n\n        std::vector<std::string> lparts = split(line1, '\\t');\n        std::string gap_str = lparts[2];\n        temp_num1 = std::stol(gap_str);\n        sample_vec.push_back(temp_num1);\n    } \n    \n    sample_count = sample_vec.size();\n    std::cout << \"sample_count: \" << std::to_string(sample_count) << \"\\n\";\n}\n\ndouble MixtureModelC::get_mem_prob(int density_ind, int sample_ind) {\n    size_t actual_pos = density_ind * sample_count + sample_ind;\n    double lmem_prob = mem_prob_mat[actual_pos];\n    return (lmem_prob);\n}\n\nvoid MixtureModelC::set_mem_prob(double mem_prob, int density_ind, \n    int sample_ind) {\n    size_t actual_pos = density_ind * sample_count + sample_ind;\n    mem_prob_mat[actual_pos] = mem_prob;\n}\n\nvoid MixtureModelC::print_help() {\n    std::cout << desc << \"\\n\";\n    std::cout << \"Usage: MixtureModel --infile <txt> --outdir <outdir>\"\n        \" --prefix <prefix>  --density_c <density count>\"\n        \"\\n\\n\";\n}\n\nstd::vector<long> MixtureModelC::get_sub_vec(std::vector<long>& lvec, \n        int start_p, int end_p) {\n\n    auto first = lvec.cbegin() + start_p;\n    auto last = lvec.cbegin() + end_p + 1;\n    std::vector<long> new_v(first, last);\n    return new_v;\n\n}\n \nvoid MixtureModelC::init_EM_params() {\n\n    // Take the data and make a rough estimate from sample_vec;\n\n    // 1. Get the count of 0\n    // 2. Get the count of less than 500\n\n    int zero_count = 0;\n    int less_500_count = 0;\n    for (long lval1 : sample_vec) {\n        if (0 == lval1) {\n            zero_count++;\n        }\n\n        if (lval1 < 500) {\n            less_500_count++;\n        }\n    }\n\n    double zero_frac_m0 = 0.9;\n    int m0_count  = (int) floor(zero_count * zero_frac_m0);\n    int m1_count = less_500_count - m0_count;\n    int m2_count = sample_vec.size() - (m0_count + m1_count);\n\n    std::cout << \"model0_count: \" << m0_count << \"\\n\";\n    std::cout << \"model1_count: \" << m1_count << \"\\n\";\n    std::cout << \"model2_count: \" << m2_count << \"\\n\";\n    std::cout << \".................\\n\";\n\n    std::vector<long> sample_vec_s = sample_vec;\n    std::sort(sample_vec_s.begin(), sample_vec_s.end());\n\n    int m0_s = 0; \n    int m0_e = m0_count -1;\n    std::vector<long> sample_model0 =  get_sub_vec(sample_vec_s, m0_s, m0_e);\n\n    \n    int m1_s = m0_count;\n    int m1_e = m0_count + m1_count -1;\n    std::vector<long> sample_model1 =  get_sub_vec(sample_vec_s, m1_s, m1_e);\n\n    int m2_s = m0_count + m1_count;\n    int m2_e = sample_vec_s.size() -1;\n    std::vector<long> sample_model2 =  get_sub_vec(sample_vec_s, m2_s, m2_e);\n\n    int sample_vec_s_size = sample_vec_s.size();\n    std::cout << \"sample_vec_s_size: \" << sample_vec_s_size << \"\\n\";\n\n    prior_vec[0] = (double) m0_count / sample_vec_s_size;\n    prior_vec[1] = (double) m1_count / sample_vec_s_size;\n    prior_vec[2] = (double) m2_count / sample_vec_s_size;\n\n    std::cout << \"Reached here.\" << \"\\n\";\n    std::cout << \"model0_prior: \" << prior_vec[0] << \"\\n\";\n    std::cout << \"model1_prior: \" << prior_vec[1] << \"\\n\";\n    std::cout << \"model2_prior: \" << prior_vec[2] << \"\\n\";\n    std::cout << \".................\\n\";\n\n    // We shall get the p_val and r_val for model_1 and model_2 by doing\n    // another EM?\n    \n    std::cout << \"sample_model1: \" << sample_model1.size() << \"\\n\";\n\n    NBModelC model1(sample_model1);\n    r_vec[1] = model1.find_r_val();\n    p_vec[1] = model1.find_p_val();\n    std::cout << \"model1_r_val: \" << r_vec[1] << \"\\n\";\n    std::cout << \"model1_p_val: \" << p_vec[1] << \"\\n\";\n    std::cout << \"model1_mean_val: \" << model1.find_mean_val() << \"\\n\"; \n    std::cout << \".................\\n\";\n\n    NBModelC model2(sample_model2);\n    r_vec[2] = model2.find_r_val();\n    p_vec[2] = model2.find_p_val(); \n\n    std::cout << \"model2_r_val: \" << r_vec[2] << \"\\n\";\n    std::cout << \"model2_p_val: \" << p_vec[2] << \"\\n\";\n    std::cout << \"model2_mean_val: \" << model2.find_mean_val() << \"\\n\"; \n    std::cout << \".................\\n\";\n}\n\nvoid MixtureModelC::do_E_step() {\n\n    for (int n = 0; n < sample_count; n++) {\n\n        long xn_val = sample_vec[n];\n        double comp_0_L = 0;\n\n        // The component is a point mass concentrated at zero; so it has\n        // LL of 1 at 0 and LL of 0 at other points.\n        if (xn_val == 0) {\n            comp_0_L = 1;\n        } else {\n            comp_0_L = 0;\n        }\n\n        double comp_0_u = prior_vec[0] * comp_0_L;\n\n        double comp_1_L = get_NB_density(xn_val, p_vec[1], r_vec[1]); \n        double comp_1_u = prior_vec[1] * comp_1_L;\n\n        double comp_2_L = get_NB_density(xn_val, p_vec[2], r_vec[2]);\n        double comp_2_u = prior_vec[2] * comp_2_L; \n       \n        double total_d = comp_0_u + comp_1_u + comp_2_u;\n\n        double comp_0_n = comp_0_u / total_d;\n        double comp_1_n = comp_1_u / total_d;\n        double comp_2_n = comp_2_u / total_d; \n    \n        set_mem_prob(comp_0_n, 0, n);    \n        set_mem_prob(comp_1_n, 1, n);    \n        set_mem_prob(comp_2_n, 2, n);    \n    } \n}\n\n\nvoid MixtureModelC::update_prior_val(int k) {\n\n    double N_k = 0;\n    for (int n = 0; n < sample_vec.size(); n++) {\n        N_k += get_mem_prob(k, n);\n    }\n\n    int N = sample_vec.size();\n    prior_vec[k] = N_k / N;\n}\n\n\n// Works only for NB components (comp 1 and comp 2)\nvoid MixtureModelC::update_p_val(int k) {\n    \n    double N_k = 0;\n    for (int n = 0; n < sample_vec.size(); n++) {\n        N_k += get_mem_prob(k, n);\n    }\n\n    double lval1 = 0;\n\n    for (int n = 0; n < sample_vec.size(); n++) {\n        double xn_val = sample_vec[n];\n        double x_mem_prob = get_mem_prob(k, n);\n        lval1 += ( xn_val * x_mem_prob);\n    }\n\n    double mean_k = lval1 / N_k;\n    double r_val_k = r_vec[k];\n    \n    p_vec[k] = mean_k / (mean_k + r_val_k);\n}\n\nvoid MixtureModelC::do_M_step() {\n\n    // Estimate the parameters using the BFGS in dlib\n    auto value_comp1 = std::bind(&MixtureModelC::CD_LL_value_comp1, this, _1);\n    auto gradient_comp1 = std::bind(&MixtureModelC::CD_LL_gradient_comp1, this, _1);\n\n    // Get updated r_val for component 1\n    \n    const column_vector x_lower1 = {0.00001};\n    const column_vector x_upper1 = {10000};\n\n    column_vector starting_point1 = {r_vec[1]};\n    find_max_box_constrained(dlib::bfgs_search_strategy(),\n                                     dlib::objective_delta_stop_strategy(1e-6),\n                                     value_comp1, gradient_comp1,\n                                    starting_point1,\n                                    x_lower1, x_upper1);\n    r_vec[1] = starting_point1(0);\n    // update p_val for component 1\n    update_p_val(1);\n    \n\n    // Similarly update r_val for component 2\n    \n    auto value_comp2 = std::bind(&MixtureModelC::CD_LL_value_comp2, this, _1);\n    auto gradient_comp2 = std::bind(&MixtureModelC::CD_LL_gradient_comp2, this, _1);\n    const column_vector x_lower2 = {0.00001};\n    const column_vector x_upper2 = {10000};\n    column_vector starting_point2 = {r_vec[2]};\n    find_max_box_constrained(dlib::bfgs_search_strategy(),\n                                     dlib::objective_delta_stop_strategy(1e-6),\n                                     value_comp2, gradient_comp2,\n                                    starting_point2,\n                                    x_lower1, x_upper1);\n    r_vec[2] = starting_point2(0);\n    // update p_val for component2\n    update_p_val(2);\n\n\n    // calculate the prior_val for all three component\n    update_prior_val(0);\n    update_prior_val(1);\n    update_prior_val(2);\n\n}\n\ndouble MixtureModelC::get_LL() {\n    double ll = 0;\n\n    for (int n = 0; n < sample_count; n++) {\n\n        long xn_val = sample_vec[n];\n        double comp_0_L = 0;\n\n        if (xn_val == 0) {\n            comp_0_L = 1;\n        } else {\n            comp_0_L = 0;\n        }\n\n        double comp_0_u = prior_vec[0] * comp_0_L;\n\n        double comp_1_L = get_NB_density(xn_val, p_vec[1], r_vec[1]); \n        double comp_1_u = prior_vec[1] * comp_1_L;\n\n        double comp_2_L = get_NB_density(xn_val, p_vec[2], r_vec[2]);\n        double comp_2_u = prior_vec[2] * comp_2_L; \n       \n        double l_n = comp_0_u + comp_1_u + comp_2_u;\n        double ll_n = log(l_n);\n        ll += ll_n;\n    }\n\n    return (ll);\n}\n\n\nvoid MixtureModelC::main_func() {\n\n    // Here would be the four main steps.\n\n    //double target_ll_change = 1e-9;\n    double target_ll_change = 1e-6;\n    double ll_change = 0;\n    // 1. initialize the parameters\n    init_EM_params();\n\n    double old_ll = get_LL();\n\n    std::cout << \"It 0, LL val: \" << old_ll << \"\\n\";\n\n    // 2. do ... while not converged in terms of likelihood\n    int it_count = 0;\n    do {\n        it_count++;\n\n        // 3a. E step\n        do_E_step(); \n\n        // 3b. M step\n        do_M_step();\n\n        //4. Calculate the log linklihood\n        double new_ll = get_LL();\n\n        ll_change = abs(new_ll - old_ll);\n\n        double mean_1 = (p_vec[1] * r_vec[1])/(1 - p_vec[1]);\n        double mean_2 = (p_vec[2] * r_vec[2])/(1 - p_vec[2]);\n    \n    \n        std::cout.precision(dbl::max_digits10);\n        std::cout << \"It \" << it_count << \", LL val \" << new_ll << \"\\n\";\n        std::cout << \"prior_0: \" << prior_vec[0] << \", prior_1: \" << \n        prior_vec[1] << \", prior_2: \" << prior_vec[2] << \"\\n\";\n        std::cout << \"p_val_1: \" << p_vec[1] << \", p_val_2: \" << p_vec[2] << \n            \", r_val_1: \" << r_vec[1]  << \", r_val_2: \" << r_vec[2] << \n            \", mean_1: \" << mean_1 << \", mean_2: \" << mean_2 << \"\\n\";\n        std::cout << \"ll_change: \" << ll_change << \"\\n\";\n        std::cout << \"................\\n\";\n   \n\n        old_ll = new_ll;\n\n    } while(ll_change > target_ll_change);\n\n    std::cout << \">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\\n\";\n    double mean_1 = (p_vec[1] * r_vec[1])/(1 - p_vec[1]);\n    double mean_2 = (p_vec[2] * r_vec[2])/(1 - p_vec[2]);\n    std::cout.precision(dbl::max_digits10);\n    std::cout << \"prior_0: \" << prior_vec[0] << \", prior_1: \" << \n        prior_vec[1] << \", prior_2: \" << prior_vec[2] << \"\\n\";\n    std::cout << \"p_val_1: \" << p_vec[1] << \", p_val_2: \" << p_vec[2] << \n        \", r_val_1: \" << r_vec[1]  << \", r_val_2: \" << r_vec[2] << \n        \", mean_1: \" << mean_1 << \", mean_2: \" << mean_2 << \"\\n\";\n    std::cout << \"................\\n\";\n\n    for (int n = 0; n < sample_vec.size(); n++) {\n        if (sample_vec[n] > 200 && sample_vec[n] < 2000) {\n        std::cout << sample_vec[n] << \", g_0: \" << get_mem_prob(0, n) <<\n            \", g_1: \" << get_mem_prob(1, n) << \", g_2: \" << \n            get_mem_prob(2, n) << \"\\n\";\n        }\n    }\n}\n\n\nbool MixtureModelC::parse_args(int argc, char* argv[]) {\n\n    bool all_set = true;\n\n    desc.add_options()\n        (\"help,h\", \"produce help message\")\n        (\"infile,i\", po::value<std::string>(&infile_str), \"Infile for the gap data.\")\n        (\"outdir,o\", po::value<std::string>(&outdir_str), \"Output dir.\")\n        (\"prefix,p\", po::value<std::string>(&prefix_str), \"Prefix str.\")\n        (\"density_c,d\", po::value(&density_count), \"Density count.\")\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        return 0;\n    } else {\n    }\n\n    if (vm.count(\"infile\")) {\n        std::cout << \"Infile is set to: \" << infile_str << \"\\n\";\n    } else {\n        all_set = false;\n        std::cout << \"Error: infile is not set.\\n\";\n    }\n\n    if (vm.count(\"outdir\")) {\n        std::cout << \"Outdir is set to \" << outdir_str << \"\\n\";\n    } else {\n        all_set = false;\n        std::cout << \"Error: outdir is not set.\\n\";\n    }\n\n    if (vm.count(\"prefix\")) {\n        std::cout << \"Prefix is set to: \" << prefix_str << \"\\n\";\n    } else {\n        all_set = false;\n        std::cout << \"Error: Prefix is not set.\\n\";\n    }\n\n    if (vm.count(\"density_c\")) {\n        std::cout << \"Density_c is set to: \" << density_count << \"\\n\";\n    } else {\n        all_set = false;\n        std::cout << \"Error: Density_c is not set.\\n\";\n    }\n\n    return all_set;\n}\n\n\nint main(int argc, char** argv) {\n    MixtureModelC nbemo;\n    bool all_set = true;\n\n    try {\n        all_set = nbemo.parse_args(argc, argv);\n    } catch(std::exception& e) {\n        std::cerr << \"error: \" << e.what() << \"\\n\";\n        return 1;\n    } catch(...) {\n        return 0;\n    } \n\n    if (!all_set) {\n        nbemo.print_help();\n        return 0;\n    }\n\n    try {\n        nbemo.initialize();\n        nbemo.main_func();\n        nbemo.free_vars();\n\n    } catch(const std::runtime_error& e) {\n\n        std::cerr << \"error: \"  << e.what() << \"\\n\";\n        return 1;\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "30ba5e1a53964abef704efb5102b234e5bbceb12", "size": 18497, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "MixtureModel.cpp", "max_stars_repo_name": "nirmalya-broad/NB_EM", "max_stars_repo_head_hexsha": "de1bc4d1ee905c62b7427b00b5d9f6e513edbca2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MixtureModel.cpp", "max_issues_repo_name": "nirmalya-broad/NB_EM", "max_issues_repo_head_hexsha": "de1bc4d1ee905c62b7427b00b5d9f6e513edbca2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MixtureModel.cpp", "max_forks_repo_name": "nirmalya-broad/NB_EM", "max_forks_repo_head_hexsha": "de1bc4d1ee905c62b7427b00b5d9f6e513edbca2", "max_forks_repo_licenses": ["BSD-3-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.3137876387, "max_line_length": 85, "alphanum_fraction": 0.5805265719, "num_tokens": 5388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.4792988650182895}}
{"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 \"PoissonSolver.h\"\n#include \"PoissonSolverDetail.h\"\n#include \"RegularNumberField.h\"\n#include \"./Math.h\"\n#include \"Vector.h\"\n#include \"../ConsoleRig/Log.h\"\n#include \"../Utility/PtrUtils.h\"\n#include <vector>\n#include <assert.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:4505)       // 'SceneEngine::CalculateIncompleteCholesky' : unreferenced local function has been removed\n\nnamespace XLEMath\n{\n    using namespace PoissonSolverInternal;\n\n///////////////////////////////////////////////////////////////////////////////////////////////////\n\n    static void RunSOR(ScalarField1D& xv, const AMat& A, const ScalarField1D& b, float relaxationFactor)\n    {\n        const auto width = GetWidth(A);\n        const auto height = GetHeight(A);\n\n            // Note that \"SOR\" can't work correctly with wrapping borders\n            // Jacobi relaxation could work; but because SOR is done in-place,\n            // the results won't be correct if we attempt to read from a border\n            // wrapped around\n\n        if (A._dimensionality==2) {\n            const UInt2 bor(1,1);   // can't fill in the edges using this method\n            for (unsigned y=bor[1]; y<height-bor[1]; ++y) {\n                for (unsigned x=bor[0]; x<width-bor[0]; ++x) {\n                    const unsigned i = y*width+x;\n                    auto v = b[i];\n\n                    v -= A._a1 * xv[i-1];\n                    v -= A._a1 * xv[i+1];\n                    v -= A._a1 * xv[i-width];\n                    v -= A._a1 * xv[i+width];\n\n                    xv[i] = (1.f-relaxationFactor) * xv[i] + relaxationFactor * v / A._a0;\n                }\n            }\n        } else {\n            const UInt3 bor(1,1,1);\n            const auto depth = GetDepth(A);\n            for (unsigned z=bor[2]; z<depth-bor[2]; ++z) {\n                for (unsigned y=bor[1]; y<height-bor[1]; ++y) {\n                    for (unsigned x=bor[0]; x<width-bor[0]; ++x) {\n                        const unsigned i = (z*height+y)*width+x;\n                        auto v = b[i];\n\n                        v -= A._a1 * xv[i-width*height];\n                        v -= A._a1 * xv[i-width];\n                        v -= A._a1 * xv[i-1];\n                        v -= A._a1 * xv[i+1];\n                        v -= A._a1 * xv[i+width];\n                        v -= A._a1 * xv[i+width*height];\n\n                        xv[i] = (1.f-relaxationFactor) * xv[i] + relaxationFactor * v / A._a0;\n                    }\n                }\n            }\n        }\n    }\n\n    static void RunSOR(ScalarField1D& xv, std::function<float(unsigned, unsigned)>& A, const ScalarField1D& b, unsigned N, float relaxationFactor)\n    {\n        for (unsigned i = 0; i < N; ++i) {\n            auto v = b[i];\n\n                // these loops work oddly simply in this situation\n                // (but of course we can simplify because our matrix is sparse)\n            for (unsigned j = 0; j < i; ++j)\n                v -= A(i, j) * xv[j];\n            for (unsigned j = i+1; j < N; ++j)\n                v -= A(i, j) * xv[j];\n\n            xv[i] = (1.f-relaxationFactor) * xv[i] + relaxationFactor * v / A(i, i);\n        }\n    }\n\n///////////////////////////////////////////////////////////////////////////////////////////////////\n    \n    using VectorX = Eigen::VectorXf;\n    using MatrixX = Eigen::MatrixXf;\n    static ScalarField1D AsScalarField1D(VectorX& v) { return ScalarField1D { v.data(), (unsigned)v.size() }; }\n\n    // template<typename Vec>\n    //     static void ZeroBorder(Vec&x, const AMat& a)\n    // {\n    //     if (a._dimensionality==2)   ZeroBorder2D(x, Truncate(a._dims), GetMarginFlags(a));\n    //     else                        ZeroBorder3D(x, a._dims);\n    // }\n\n    template<typename Vec>\n        static void CopyBorder(Vec&dst, const Vec&src, const AMat& a)\n    {\n        if (a._dimensionality==2)   CopyBorder2D(dst, src, Truncate(a._dims), GetMarginFlags(a));\n        else                        CopyBorder3D(dst, src, a._dims);\n    }\n\n    class Solver_PlainCG\n    {\n    public:\n        template<typename Mat>\n            unsigned Execute(ScalarField1D& x, const Mat& A, const ScalarField1D& b);\n\n        Solver_PlainCG(unsigned N);\n        ~Solver_PlainCG();\n\n    protected:\n        VectorX _r, _d, _q;\n        unsigned _N;\n    };\n\n    template<typename Mat>\n        unsigned Solver_PlainCG::Execute(ScalarField1D& x, const Mat& A, const ScalarField1D& b)\n    {\n            // This is the basic \"conjugate gradient\" method; with no special thrills\n            // returns the number of iterations\n            // todo -- we need a better way to calculate \"rhoThreshold\"\n            //          ... perhaps it should scale with N? (or the initial error?)\n            //          a fixed number like this will result in a different quality\n            //          of result for different sized grids (and different operations\n            //          probably have varying levels of accuracy required)\n        const auto rhoThreshold = 1e-10f;\n        const auto maxIterations = 13u;\n\n        // const UInt3 bor = GetBorders(A);\n        // const auto& dims = A._dims;\n        // #define FOR_EACH_CELL                                               \\\n        //     for (unsigned qz=bor[2]; qz<dims[2]-bor[2]; ++qz)               \\\n        //         for (unsigned qy=bor[1]; qy<dims[1]-bor[1]; ++qy)           \\\n        //             for (unsigned qx=bor[0]; qx<dims[0]-bor[0]; ++qx) {     \\\n        //                 auto i = (qz*dims[1]+qy)*dims[0]+qx;                \\\n        //     /**/\n        const auto N = GetN(A);\n        assert(N == _N);\n        #define FOR_EACH_CELL                   \\\n            for (unsigned i=0; i<N; ++i) {      \\\n            /**/\n        #define FOR_EACH_CELL_END }\n\n        auto rAsField = AsScalarField1D(_r);\n        Multiply(rAsField, A, x, _N);\n        for (unsigned c=0; c<b._count; ++c) {\n            _r[c] =  b[c] - _r[c];\n            _d[c] = _r[c];\n        }\n        auto rho = 0.f; // _r.dot(_r);\n        FOR_EACH_CELL\n            rho += _r[i] * _r[i];\n        FOR_EACH_CELL_END\n\n        unsigned k=0;\n        if (XlAbs(rho) > rhoThreshold) {\n            for (; k<maxIterations; ++k) {\n            \n                Multiply(_q, A, _d, _N);\n                auto dDotQ = 0.f; // _d.dot(_q);\n                FOR_EACH_CELL\n                    dDotQ += _d[i] * _q[i];\n                FOR_EACH_CELL_END\n\n                auto alpha = rho / dDotQ;\n                assert(isfinite(alpha) && !isnan(alpha));\n                FOR_EACH_CELL\n                     x[i] += alpha * _d[i];\n                        // _r should be an estimate the of the current error\n                        // Every few iterations, we can improve this estimate\n                        // by recalculating _r = b - A * x\n                    _r[i] -= alpha * _q[i]; \n                FOR_EACH_CELL_END\n            \n                auto rhoOld = rho;\n                rho = 0.f; // _r.dot(_r);\n                FOR_EACH_CELL\n                    rho += _r[i] * _r[i];\n                FOR_EACH_CELL_END\n\n                if (XlAbs(rho) < rhoThreshold) break;\n                auto beta = rho / rhoOld;\n                assert(isfinite(beta) && !isnan(beta));\n            \n                    // we can skip the border for the following...\n                    // (but that requires different cases for 2D/3D)\n                FOR_EACH_CELL\n                    _d[i] = _r[i] + beta * _d[i];\n                FOR_EACH_CELL_END\n\n            }\n        }\n\n        #undef FOR_EACH_CELL\n        #undef FOR_EACH_CELL_END\n\n        return k;\n    }\n\n    Solver_PlainCG::Solver_PlainCG(unsigned N)\n    : _r(N), _d(N), _q(N)\n    {\n        _N = N;\n    }\n\n    Solver_PlainCG::~Solver_PlainCG() {}\n\n///////////////////////////////////////////////////////////////////////////////////////////////////\n\n    class Solver_PreconCG\n    {\n    public:\n        template<typename Mat, typename PreCon>\n            unsigned Execute(ScalarField1D& x, const Mat& A, const ScalarField1D& b, const PreCon& precon);\n\n        Solver_PreconCG(unsigned N);\n        ~Solver_PreconCG();\n\n    protected:\n        VectorX _r, _d, _q;\n        VectorX _s;\n        unsigned _N;\n    };\n\n    template<typename Mat, typename PreCon>\n        unsigned Solver_PreconCG::Execute(ScalarField1D& x, const Mat& A, const ScalarField1D& b, const PreCon& precon)\n    {\n            // This is the conjugate gradient method with a preconditioner.\n            //\n            // Note that for our CFD operations, the preconditioner often comes out very similar\n            // to \"A\" -- so it's not clear whether it will help in any significant way.\n            //\n            // See http://www.cs.cmu.edu/~quake-papers/painless-conjugate-gradient.pdf \n            // for for detailed description of conjugate gradient methods!\n            // \n            // see also reference at http://math.nist.gov/iml++/\n        const auto rhoThreshold = 1e-10f;\n        const auto maxIterations = 13u;\n\n        auto rAsField = AsScalarField1D(_r);\n        Multiply(rAsField, A, x, _N);    // r = AMat * x\n        for (unsigned c=0; c<b._count; ++c)\n            _r[c] = b[c] - _r[c];\n            \n        SolveLowerTriangular(_d, precon, _r, _N);\n            \n        // #if defined(_DEBUG)\n        //     {\n        //             // testing \"SolveLowerTriangular\"\n        //         VectorX t(_N);\n        //         Multiply(t, precon, _d, _N);\n        //         for (unsigned c=0; c<_N; ++c) {\n        //             auto z = t(c), y = _r(c);\n        //             assert(Equivalent(z, y, 1e-1f));\n        //         }\n        //     }\n        // #endif\n\n        // const UInt3 bor = GetBorders(A);\n        // const auto& dims = A._dims;\n        // #define FOR_EACH_CELL                                               \\\n        //     for (unsigned qz=bor[2]; qz<dims[2]-bor[2]; ++qz)               \\\n        //         for (unsigned qy=bor[1]; qy<dims[1]-bor[1]; ++qy)           \\\n        //             for (unsigned qx=bor[0]; qx<dims[0]-bor[0]; ++qx) {     \\\n        //                 auto i = (qz*dims[1]+qy)*dims[0]+qx;                \\\n        //     /**/\n        const auto N = GetN(A);\n        assert(N == _N);\n        #define FOR_EACH_CELL                           \\\n            for (unsigned i=0; i<N; ++i) {              \\\n            /**/\n        #define FOR_EACH_CELL_END }\n            \n        auto rho = 0.f;\n        FOR_EACH_CELL\n            rho += _r[i] * _d[i];       // calculating: auto rho = _r.dot(_d);\n        FOR_EACH_CELL_END\n        // auto rho0 = rho;\n            \n        unsigned k=0;\n        if (XlAbs(rho) > rhoThreshold) {\n            for (; k<maxIterations; ++k) {\n            \n                    // Note that all of the vectors and matrices\n                    // used here are quite sparse! So we need to\n                    // simplify the operation here to take advantage \n                    // of that sparseness.\n                    // Multiply by AMat can be replaced with a specialized\n                    // operation. Unfortunately the dot products can't be\n                    // simplified, because the vectors already have only one\n                    // element per cell.\n            \n                Multiply(_q, A, _d, _N);\n                auto dDotQ = 0.f; // _d.dot(_q);\n                FOR_EACH_CELL\n                    dDotQ += _d[i] * _q[i];\n                FOR_EACH_CELL_END\n\n                auto alpha = rho / dDotQ;\n                assert(isfinite(alpha) && !isnan(alpha));\n                FOR_EACH_CELL\n                     x[i] += alpha * _d[i];\n                    _r[i] -= alpha * _q[i];\n                FOR_EACH_CELL_END\n            \n                SolveLowerTriangular(_s, precon, _r, _N);\n                auto rhoOld = rho;\n                rho = 0.f; // _r.dot(_s);\n                FOR_EACH_CELL\n                    rho += _r[i] * _s[i];\n                FOR_EACH_CELL_END\n                if (XlAbs(rho) < rhoThreshold) break;\n                // assert(rho < rhoOld);\n\n                auto beta = rho / rhoOld;\n                assert(isfinite(beta) && !isnan(beta));\n            \n                FOR_EACH_CELL\n                    _d[i] = _s[i] + beta * _d[i];\n                FOR_EACH_CELL_END\n            }\n        }\n\n        #undef FOR_EACH_CELL\n        #undef FOR_EACH_CELL_END\n\n        return k;\n    }\n\n    Solver_PreconCG::Solver_PreconCG(unsigned N)\n    : _r(N), _d(N), _q(N), _s(N)\n    {\n        _N = N;\n    }\n\n    Solver_PreconCG::~Solver_PreconCG() {}\n\n///////////////////////////////////////////////////////////////////////////////////////////////////\n\n    class Solver_Multigrid\n    {\n    public:\n        template<typename Mat>\n            unsigned Execute(ScalarField1D& x, const Mat& A, const ScalarField1D& b);\n\n        Solver_Multigrid(UInt3 dims, unsigned dimensionality, unsigned levels);\n        ~Solver_Multigrid();\n\n    protected:\n        std::vector<VectorX> _subResidual;\n        std::vector<VectorX> _subB;\n        std::vector<UInt3> _subDims;\n        unsigned _N;\n        unsigned _dimensionality;\n    };\n\n    static AMat ChangeResolution(AMat i, unsigned layer)\n    {\n            // 'a' values are proportion to the square of N\n            // N quarters with every layer (width and height half)\n        auto scale = std::pow(4.f, float(layer));\n        auto result = i;\n        result._a0      /= scale;\n        result._a1      /= scale;\n        result._a0c     /= scale;\n        result._a0ex    /= scale;\n        result._a0ey    /= scale;\n        result._a1e     /= scale;\n        result._a1rx    /= scale;\n        result._a1ry    /= scale;\n        return result;\n    }\n\n    static void Restrict2D(ScalarField1D& dst, const ScalarField1D& src, UInt2 dstDims, UInt2 srcDims)\n    {\n            // This is the \"restrict\" operator\n            // There are many possible methods for this\n            // We're going to start with a simple method that\n            // assumes that the sample values are at the corners\n            // of the grid. This way we can just use the box\n            // mipmap operator; as so...\n            // If we have more complex boundary conditions, we\n            // might want to move the sames to the center of the \n            // grid cells; which would mean that we should \n            // use a more complex operator here\n        for (unsigned y=1; y<dstDims[1]-1; ++y) {\n            for (unsigned x=1; x<dstDims[0]-1; ++x) {\n                unsigned sx = (x-1)*2+1, sy = (y-1)*2+1;\n                dst[y*dstDims[0]+x]\n                    = .25f * src[(sy+0)*srcDims[0]+(sx+0)]\n                    + .25f * src[(sy+0)*srcDims[0]+(sx+1)]\n                    + .25f * src[(sy+1)*srcDims[0]+(sx+0)]\n                    + .25f * src[(sy+1)*srcDims[0]+(sx+1)]\n                    ;\n            }\n        }\n    }\n\n    static void Restrict3D(ScalarField1D& dst, const ScalarField1D& src, UInt3 dstDims, UInt3 srcDims)\n    {\n        for (unsigned z=1; z<dstDims[2]-1; ++z) {\n            for (unsigned y=1; y<dstDims[1]-1; ++y) {\n                for (unsigned x=1; x<dstDims[0]-1; ++x) {\n                    unsigned sx = (x-1)*2+1, sy = (y-1)*2+1, sz = (z-1)*2+1;\n                    dst[(z*dstDims[1]+y)*dstDims[0]+x]\n                        = .125f * src[((sz+0)*srcDims[1]+(sy+0))*srcDims[0]+(sx+0)]\n                        + .125f * src[((sz+0)*srcDims[1]+(sy+0))*srcDims[0]+(sx+1)]\n                        + .125f * src[((sz+0)*srcDims[1]+(sy+1))*srcDims[0]+(sx+0)]\n                        + .125f * src[((sz+0)*srcDims[1]+(sy+1))*srcDims[0]+(sx+1)]\n                        + .125f * src[((sz+1)*srcDims[1]+(sy+0))*srcDims[0]+(sx+0)]\n                        + .125f * src[((sz+1)*srcDims[1]+(sy+0))*srcDims[0]+(sx+1)]\n                        + .125f * src[((sz+1)*srcDims[1]+(sy+1))*srcDims[0]+(sx+0)]\n                        + .125f * src[((sz+1)*srcDims[1]+(sy+1))*srcDims[0]+(sx+1)]\n                        ;\n                }\n            }\n        }\n    }\n\n    static void Prolongate2D(ScalarField1D& dst, const ScalarField1D& src, UInt2 dstDims, UInt2 srcDims)\n    {\n            // This is the \"prolongate\" operator.\n            // As with the restrict operator, we're going\n            // to use a simple bilinear sample, as if each\n            // layer was a mipmap.\n\n        for (unsigned y=1; y<dstDims[1]-1; ++y) {\n            for (unsigned x=1; x<dstDims[0]-1; ++x) {\n                auto sx = (x-1)/2.f + 1.f;\n                auto sy = (y-1)/2.f + 1.f;\n                auto sx0 = XlFloor(sx), sy0 = XlFloor(sy);\n                auto a = sx - sx0, b = sy - sy0;\n                decltype(a) weights[] = {\n                    (1.0f - a) * (1.0f - b),\n                    a * (1.0f - b),\n                    (1.0f - a) * b,\n                    a * b\n                };\n                dst[y*dstDims[0]+x]\n                    = weights[0] * src[(unsigned(sy0)+0)*srcDims[0]+unsigned(sx0)]\n                    + weights[1] * src[(unsigned(sy0)+0)*srcDims[0]+unsigned(sx0)+1]\n                    + weights[2] * src[(unsigned(sy0)+1)*srcDims[0]+unsigned(sx0)]\n                    + weights[3] * src[(unsigned(sy0)+1)*srcDims[0]+unsigned(sx0)+1]\n                    ;\n            }\n        }\n    }\n\n    static void Prolongate3D(ScalarField1D& dst, const ScalarField1D& src, UInt3 dstDims, UInt3 srcDims)\n    {\n        for (unsigned z=1; z<dstDims[2]-1; ++z) {\n            for (unsigned y=1; y<dstDims[1]-1; ++y) {\n                for (unsigned x=1; x<dstDims[0]-1; ++x) {\n                    auto sx = (x-1)/2.f + 1.f;\n                    auto sy = (y-1)/2.f + 1.f;\n                    auto sz = (z-1)/2.f + 1.f;\n                    auto sx0 = XlFloor(sx), sy0 = XlFloor(sy), sz0 = XlFloor(sz);\n                    auto a = sx - sx0, b = sy - sy0, c = sz - sz0;\n                    decltype(a) weights[] = {\n                        (1.0f - a) * (1.0f - b) * (1.0f - c),\n                        a * (1.0f - b) * (1.0f - c),\n                        (1.0f - a) * b * (1.0f - c),\n                        a * b * (1.0f - c),\n                        (1.0f - a) * (1.0f - b) * c,\n                        a * (1.0f - b) * c,\n                        (1.0f - a) * b * c,\n                        a * b * c\n                    };\n                    dst[(z*dstDims[1]+y)*dstDims[0]+x]\n                        = weights[0] * src[((unsigned(sz0)+0)*srcDims[1]+(unsigned(sy0)+0))*srcDims[0]+unsigned(sx0)+0]\n                        + weights[1] * src[((unsigned(sz0)+0)*srcDims[1]+(unsigned(sy0)+0))*srcDims[0]+unsigned(sx0)+1]\n                        + weights[2] * src[((unsigned(sz0)+0)*srcDims[1]+(unsigned(sy0)+1))*srcDims[0]+unsigned(sx0)+0]\n                        + weights[3] * src[((unsigned(sz0)+0)*srcDims[1]+(unsigned(sy0)+1))*srcDims[0]+unsigned(sx0)+1]\n                        + weights[4] * src[((unsigned(sz0)+1)*srcDims[1]+(unsigned(sy0)+0))*srcDims[0]+unsigned(sx0)+0]\n                        + weights[5] * src[((unsigned(sz0)+1)*srcDims[1]+(unsigned(sy0)+0))*srcDims[0]+unsigned(sx0)+1]\n                        + weights[6] * src[((unsigned(sz0)+1)*srcDims[1]+(unsigned(sy0)+1))*srcDims[0]+unsigned(sx0)+0]\n                        + weights[7] * src[((unsigned(sz0)+1)*srcDims[1]+(unsigned(sy0)+1))*srcDims[0]+unsigned(sx0)+1]\n                        ;\n                }\n            }\n        }\n    }\n\n    template<typename Mat>\n        unsigned Solver_Multigrid::Execute(ScalarField1D& x, const Mat& A, const ScalarField1D& b)\n    {\n        //\n        // Here is our basic V-cycle:\n        //  * start with the finest grid\n        //  * perform pre-smoothing\n        //  * iteratively reduce down:\n        //      * \"restrict\" onto next more coarse grid\n        //      * smooth result\n        //  * iteratively expand upwards:\n        //      * \"prolongonate\" up to next more fine grid\n        //      * smooth result\n        //  * do post-smoothing\n        //\n        //      Note that this is often done in parallel, by dividing the fine\n        //      grids across multiple processors.\n        //\n\n        float gamma = 1.25f;                // relaxation factor\n        const auto preSmoothIterations = 3u;\n        const auto postSmoothIterations = 3u;\n        const auto stepSmoothIterations = 1u;\n        auto iterations = 0u;\n\n            // pre-smoothing (SOR method -- can be done in place)\n        if (x._u != b._u) CopyBorder(x, b, A);\n        for (unsigned k = 0; k<preSmoothIterations; ++k)\n            RunSOR(x, A, b, gamma);\n        iterations += preSmoothIterations;\n\n            // ---------- step down ----------\n        auto activeDims = A._dims;\n        ScalarField1D prevLayer = x;\n        ScalarField1D prevB = b;\n        auto gridCount = unsigned(_subResidual.size());\n        for (unsigned g=0; g<gridCount; ++g) {\n            auto prevDims = activeDims;\n            activeDims = _subDims[g];\n            auto dst = AsScalarField1D(_subResidual[g]);\n            auto dstB = AsScalarField1D(_subB[g]);\n\n            if (_dimensionality==2) {\n                Restrict2D(dst, prevLayer, Truncate(activeDims), Truncate(prevDims));\n                Restrict2D(dstB, prevB, Truncate(activeDims), Truncate(prevDims));   // is it better to downsample B from the top most level each time?\n            } else {\n                Restrict3D(dst, prevLayer, activeDims, prevDims);\n                Restrict3D(dstB, prevB, activeDims, prevDims);   // is it better to downsample B from the top most level each time?\n            }\n\n            auto SA = ChangeResolution(A, g+1);\n            SA._dims = activeDims;\n            for (unsigned k = 0; k<stepSmoothIterations; ++k)\n                RunSOR(dst, SA, dstB, gamma);\n            iterations += stepSmoothIterations;\n\n            prevLayer = dst;\n            prevB = dstB;\n        }\n\n            // ---------- step up ----------\n        for (unsigned g=gridCount-1; g>0; --g) {\n            auto src = AsScalarField1D(_subResidual[g]);\n            auto dst = AsScalarField1D(_subResidual[g-1]);\n            auto dstB = AsScalarField1D(_subB[g-1]);\n            auto srcDims = _subDims[g];\n            auto dstDims = _subDims[g-1];\n\n            if (_dimensionality==2) {\n                Prolongate2D(dst, src, Truncate(dstDims), Truncate(srcDims));\n            } else {\n                Prolongate3D(dst, src, dstDims, srcDims);\n            }\n\n            auto SA = ChangeResolution(A, g-1+1);\n            SA._dims = dstDims;\n            for (unsigned k = 0; k<stepSmoothIterations; ++k)\n                RunSOR(dst, SA, dstB, gamma);\n            iterations += stepSmoothIterations;\n        }\n\n            // finally, step back onto 'x'\n        if (_dimensionality==2) {\n            Prolongate2D(x, AsScalarField1D(_subResidual[0]), Truncate(A._dims), Truncate(_subDims[0]));\n        } else {\n            Prolongate3D(x, AsScalarField1D(_subResidual[0]), A._dims, _subDims[0]);\n        }\n\n            // post-smoothing (SOR method -- can be done in place)\n        for (unsigned k = 0; k<postSmoothIterations; ++k)\n            RunSOR(x, A, b, gamma);\n        iterations += postSmoothIterations;\n\n        return iterations;\n    }\n\n    Solver_Multigrid::Solver_Multigrid(UInt3 dims, unsigned dimensionality, unsigned levels)\n    {\n        _dimensionality = dimensionality;\n        _N = dims[0]*dims[1]*dims[2];\n        for (unsigned c=0; c<levels; c++) {\n            dims[0] = (unsigned)std::max(1, ((int(dims[0])-2) >> 1)) + 2u;\n            dims[1] = (unsigned)std::max(1, ((int(dims[1])-2) >> 1)) + 2u;\n            dims[2] = (unsigned)std::max(1, ((int(dims[2])-2) >> 1));\n            if (dims[2] > 1) dims[2] += 2;\n\n            unsigned n = dims[0]*dims[1]*dims[2];\n            VectorX subr(n); subr.fill(0.f);\n            _subResidual.push_back(std::move(subr));\n            VectorX subb(n); subb.fill(0.f);\n            _subB.push_back(std::move(subb));\n            _subDims.push_back(dims);\n        }\n    }\n\n    Solver_Multigrid::~Solver_Multigrid() {}\n\n///////////////////////////////////////////////////////////////////////////////////////////////////\n\n    class PoissonSolver::Pimpl\n    {\n    public:\n        VectorX _tempBuffer;\n        UInt3 _dimensionsWithBorders;\n        UInt3 _borders;\n        unsigned _dimensionality;\n\n        std::unique_ptr<Solver_PlainCG> _plainCGSolver;\n        std::unique_ptr<Solver_PreconCG> _preconCGSolver;\n        std::unique_ptr<Solver_Multigrid> _multigridSolver;\n    };\n\n    class PoissonSolver::PreparedMatrix\n    {\n    public:\n        AMat _amat;\n        std::vector<int> _bands;\n        SparseBandedMatrix<MatrixX> _bandedPrecon;\n    };\n\n    static AMat EstimateInverse(const AMat& A, float estimationFactor)\n    {\n            // This is a simple estimation of the inverse, assuming that\n            // the input matrix is prepared as a \"diffusion matrix\" type\n            // A cheap inverse estimation like this allows us to calculate\n            // a good starting estimate for iterative methods.\n        bool wrapX = A._a1rx > 0.f;\n        bool wrapY = A._a1ry > 0.f;\n        auto diffusionAmount = -estimationFactor * A._a1;\n        const auto a0 = 1.f + 4.f * diffusionAmount;\n        const auto a1 = -diffusionAmount;\n\n        unsigned cornerInfl = 2u + unsigned(wrapX) + unsigned(wrapY);\n        const auto a0c = 1.f + cornerInfl * diffusionAmount;\n\n        const auto a0ex = 1.f + (3u + unsigned(wrapX)) * diffusionAmount;\n        const auto a0ey = 1.f + (3u + unsigned(wrapY)) * diffusionAmount;\n\n        const auto a1e = -diffusionAmount;\n        const auto a1rx = wrapX?-diffusionAmount:0.f;\n        const auto a1ry = wrapY?-diffusionAmount:0.f;\n        return AMat { \n            A._dims, A._dimensionality, A._marginFlags, \n            a0, a1, a0c, a0ex, a0ey, a1e, a1rx, a1ry \n        };\n    }\n\n    unsigned PoissonSolver::Solve(\n        ScalarField1D x, const PreparedMatrix& A, const ScalarField1D& b, \n        Method solver, Flags::BitField flags) const\n    {\n        //\n        // Here is our basic solver for Poisson equations (such as the heat equation).\n        // It's a complex partial differential equation, so the solution is complex.\n        //\n        // There are many methods to solve this equation. We want a method that\n        // is:\n        //  * stable\n        //  * parallelizable\n        //  * sparse in memory usage\n        // \n        // Some methods (including the methods below) produce oscillation at high\n        // time steps (or large distances between cells). We need to be careful to\n        // to avoid that type of oscillation.\n        //\n        // As suggested in Jos Stam's Stable Fluids, we'll use an integration scheme\n        // based on an implicit euler method. There are a number of variations on this\n        // basic method (such as the Crank-Nicolson method).\n        //\n        // Note that when we want a periodic boundary condition (such as wrapping around\n        // on the edges), then we can consider solutions other than the ones provided\n        // here.\n        //\n        // These methods produce a system of linear equations. In 1D, this system is\n        // tridiagonal, and can be solved with the tridiagonal matrix algorithm.\n        //\n        // But in 2D, we must use more complex methods. There are many options here:\n        //  * Jacobi relaxation (or sucessive over-relaxation, or similar)\n        //      -   this type of method is very convenient because the implementation is\n        //          simple with our type of banded matrix. But it is not as efficient \n        //          or accurate as other methods.\n        //  * Conjugate Gradient methods\n        //  * Multi-grid methods\n        //  * Parallel methods\n        //      -   (such as dividing the matrix into many smaller parts).\n        //  * conjugate gradient methods with complex preconditioners\n        //      - (such as using a parallel multi-grid as a preconditioner for\n        //          the conjugate gradient method)\n        //\n        // See: https://www.math.ucla.edu/~jteran/papers/MST10.pdf for a method that\n        // uses a multigrid preconditioner for the conjugate gradient method (which\n        // can be parallelized) with complex boundary conditions support.\n        //\n        // We must also consider the boundary conditions in this step.\n        //\n        // Note -- rules for the border of region of the input:\n        //      * this function will not modify the border region (but it will read from there)\n        //      * if x is not an alias of b, the border region will be copied from b into x\n        // \n\n            // maybe we could adapt this based on the amount of noise in the system? \n            // In low noise systems, explicit euler seems very close to correct\n        static float estimateFactor = .75f; \n        const auto& matA = A._amat;\n        const auto N = GetN(matA);\n\n        assert(x._count == N);\n        assert(b._count == N);\n\n            // if b is an alias of x, we need to copy the data into\n            // a safe place\n        ScalarField1D workingB = b;\n        if (workingB._u == x._u) {\n            for (unsigned i=0; i<N; ++i)\n                _pimpl->_tempBuffer[i] = b._u[i];\n            workingB._u = _pimpl->_tempBuffer.data();\n        }\n\n        if (solver == Method::PlainCG || solver == Method::PreconCG || solver == Method::Multigrid) {\n\n                // Set an initial estimate using\n                // explicit euler. We'll march forward part of\n                // the timestep, and then refine the estimate\n                // from there using the iterative implicit method.\n            if (!(flags & Flags::XContainsEstimate))\n                Multiply(x, EstimateInverse(matA, estimateFactor), workingB, GetN(matA));\n\n            auto iterations = 0u;\n            if (solver == Method::PlainCG) {\n                if (!_pimpl->_plainCGSolver)\n                    _pimpl->_plainCGSolver = std::make_unique<Solver_PlainCG>(N);\n                iterations = _pimpl->_plainCGSolver->Execute(x, matA, workingB);\n            } else if (solver == Method::PreconCG) {\n                if (!_pimpl->_preconCGSolver)\n                    _pimpl->_preconCGSolver = std::make_unique<Solver_PreconCG>(N);\n                iterations = _pimpl->_preconCGSolver->Execute(x, matA, workingB, A._bandedPrecon);\n            } else if (solver == Method::Multigrid) {\n                if (!_pimpl->_multigridSolver)\n                    _pimpl->_multigridSolver = std::make_unique<Solver_Multigrid>(_pimpl->_dimensionsWithBorders, _pimpl->_dimensionality, 2);\n                iterations = _pimpl->_multigridSolver->Execute(x, matA, workingB);\n            }\n\n            return iterations;\n\n        } else if (solver == Method::ForwardEuler) {\n        \n                // This is the simpliest integration. We just\n                // move forward a single timestep...\n            Multiply(x, EstimateInverse(matA, 1.f), workingB, GetN(matA));\n            return 1;\n\n        } else if (solver == Method::SOR) {\n\n                // This is successive over relaxation. It's a iterative method similar\n                // to Gauss-Seidel. But we have an extra factor, the relaxation factor, \n                // that can be used to adjust the way in which the system converges. \n                //\n                // The choice of relaxation factor has an effect on the rate of convergence.\n                // However, it's not clear how we should pick the relaxation factor.\n                //\n                // An advantage of this method is it can be done in-place... It doesn't\n                // require any extra space.\n                //\n                // One possibility is that we should allow the relaxation factor to evolve\n                // over several frames. That is, we increase or decrease the factor every\n                // frame (within the range of 0 to 2) to improve the convergence of the \n                // next frame.\n                //\n                // We can calculate the ideal relaxation factor for a (positive definite)\n                // tridiagonal matrix. Even though our matrix doesn't meet this restriction\n                // the relaxation factor many be close to ideal for us. To calculate that,\n                // we need the spectral radius of the associated Jacobi matrix.\n\n                // We should start with an approximate result. We can just start with the\n                // previous frame's result -- but maybe there is a better starting point?\n                // (maybe stepping forward 3/4 of a timestep would be a good starting point?)\n\n            float gamma = 1.25f;    // relaxation factor\n            const auto iterations = 15u;\n\n                // If no estimate already exists in 'x', we must set some reasonable\n                // starting estimate\n            if (!(flags & Flags::XContainsEstimate))\n                Multiply(x, EstimateInverse(matA, estimateFactor), workingB, GetN(matA));\n\n            for (unsigned k = 0; k<iterations; ++k)\n                RunSOR(x, matA, workingB, gamma);\n\n            return iterations;\n\n        }\n\n        return 0;\n    }\n\n///////////////////////////////////////////////////////////////////////////////////////////////////\n\n    static MatrixX CalculateIncompleteCholesky(std::function<float(unsigned, unsigned)>& mat, unsigned N)\n    {\n        MatrixX result(N, N);\n        result.fill(0.f);\n            \n        for (unsigned i=0; i<N; ++i) {\n            float a = mat(i, i);\n            for (unsigned k=0; k<i; ++k) {\n                float l = result(i, k);\n                a -= l*l;\n            }\n            a = XlSqrt(a);\n            result(i,i) = a;\n\n            if (i != 0) {\n                for (unsigned j=i+1; j<N; ++j) {\n                    float aij = mat(i, j);\n                    for (unsigned k=0; k<i; ++k) {\n                        aij -= result(i, k) * result(j, k);\n                    }\n                    result(j, i) = aij / a;\n                }\n            }\n        }\n\n        return result * result.transpose();\n    }\n\n    class TempFactorization\n    {\n    public:\n        class Accessor\n        {\n        public:\n            float& operator[](unsigned j) \n            {\n                auto offset = int(j) - int(_row);\n                auto b = std::lower_bound(_parent->_bands.cbegin(), _parent->_bands.cend(), offset);\n                if (b == _parent->_bands.cend() || *b != offset) {\n                    assert(_parent->_dummy == 0.f);\n                    return _parent->_dummy;\n                }\n                auto bandIndex = std::distance(_parent->_bands.cbegin(), b);\n                return _parent->_data[_row*_parent->_bands.size()+bandIndex];\n            }\n\n            Accessor(TempFactorization& parent, unsigned row) : _parent(&parent), _row(row) {}\n        private:\n            TempFactorization* _parent;\n            unsigned _row;\n        };\n        Accessor operator[](unsigned i) { return Accessor(*this, i); }\n\n        unsigned BandCount() const { return (unsigned)_bands.size(); }\n        float BandedValue(unsigned i, unsigned b) const { return _data[i*_bands.size()+b]; }\n\n        TempFactorization(unsigned width, unsigned height, unsigned depth, unsigned dimensionality, unsigned bandOptimization);\n        ~TempFactorization();\n\n    private:\n        std::vector<int> _bands;\n        std::vector<float> _data;\n        float _dummy;\n    };\n\n    TempFactorization::TempFactorization(unsigned width, unsigned height, unsigned depth, unsigned dimensionality, unsigned bandOptimization)\n    {\n        _dummy = 0.f;\n        assert(bandOptimization < width);\n\n            // calculate the bands we're going to store (everything off-band is assumed to be zero)\n        int kband0Start = -int(width)-int(bandOptimization);\n        int kband0End   = -int(width)+int(bandOptimization);\n        int kband1Start = -1-int(bandOptimization);\n        int kband1End   = 0;\n\n        if (dimensionality>=3) {\n            auto kband3Start =  -int(width*height)-int(bandOptimization);\n            auto kband3End   =  -int(width*height)+int(bandOptimization);\n            for (int k=kband3Start; k<=kband3End; ++k) _bands.push_back(k);\n        }\n        \n        for (int k=kband0Start; k<=kband0End; ++k) _bands.push_back(k);\n        for (int k=kband1Start; k<=kband1End; ++k) _bands.push_back(k);\n\n        _data.resize(width*height*depth*_bands.size(), 0.f);\n    }\n\n    TempFactorization::~TempFactorization() {}\n\n    static MatrixX CalculateIncompleteCholesky(const AMat& mat, unsigned N, unsigned bandOptimization)\n    {\n            //\n            //  The final matrix we build will only hold values in\n            //  the places where the input matrix also holds values.\n            //  However, while building the matrix, we need to store\n            //  and calculate values at every address. This means\n            //  allocating a very large temporary matrix.\n            //  We will return a compressed matrix with the unneeded\n            //  bands removed\n            //\n            \n        const auto width = GetWidth(mat);\n        const auto height = GetHeight(mat);\n        const unsigned thirdTest = (mat._dimensionality==2)?0:(width*height);\n        \n        if (bandOptimization == 0) {\n\n            MatrixX factorization(N, N);\n            factorization.fill(0.f);\n\n            for (unsigned i=0; i<N; ++i) {\n                float a = mat._a0;\n                for (unsigned k=0; k<i; ++k) {\n                    float l = factorization(i,k);\n                    a -= l*l;\n                }\n                a = XlSqrt(a);\n                factorization(i,i) = a;\n\n                if (i != 0) {\n                    for (unsigned j=i+1; j<N; ++j) {\n                        float aij = ((j==i+1)||(j==i+width)||(j==i+thirdTest)) ? mat._a1 : 0.f;\n                        for (unsigned k=0; k<i; ++k)\n                            aij -= factorization(i,k) * factorization(j,k);\n                        factorization(j,i) = aij / a;\n                    }\n                }\n            }\n\n                // \n                //  Our preconditioner matrix is \"factorization\" multiplied by\n                //  it's transpose\n                //\n\n            int bands2D[] = { -int(width), -1, 1, width, 0 };\n            int bands3D[] = { -int(width*height), -int(width), -1, 1, width, width*height, 0 };\n            unsigned bandCount; int* bands;\n            if (mat._dimensionality == 2) {\n                bandCount = dimof(bands2D);\n                bands = bands2D;\n            } else {\n                bandCount = dimof(bands3D);\n                bands = bands3D;\n            }\n            MatrixX sparseMatrix(N, bandCount);\n            for (unsigned i=0; i<N; ++i)\n                for (unsigned j=0; j<bandCount; ++j) {\n                    int j2 = int(i) + bands[j];\n                    if (j2 >= 0 && j2 < int(N)) {\n\n                            // Here, calculate M(i, j), where M\n                            // is the factorization multiplied by its transpose\n                        float A = 0.f;\n                        for (unsigned k=0; k<N; ++k)\n                            A += factorization(i,k) * factorization(j2,k);\n\n                        sparseMatrix(i, j) = A;\n                    } else {\n                        sparseMatrix(i, j) = 0.f;\n                    }\n                }\n            return std::move(sparseMatrix);\n\n        } else {\n\n            // Generating the Cholesky factorization is actually really expensive!\n            // But we can optimise it because the input matrix is banded.\n            // We will assume the values in the factorization fall off to zero \n            // within a certain number of cells from the bands. This happens naturally,\n            // and we can adjust the number of cells to adjust the accuracy we want.\n            // (also note that some of the small details in the matrix will be lost\n            // when we generate the preconditioner matrix -- because all off-band cells\n            // in the final matrix are zero, anyway).\n            //\n            // Actually, it seems like the values off the main bands may not have any\n            // effect on the final preconditioner matrix we generate? (given that the\n            // final matrix is sparse, and has zeroes off the main bands).\n\n            assert(bandOptimization < width);   // if \"bandOptimisation\" is very big, the math will be incorrect (and anyway, it will run slowly)\n\n                // this factorization matrix can end up begin huge!\n                // We need a better way to generate this factorization\n                // that won't blow up like this (or, at least, precalculate it and store on disk)\n            TempFactorization factorization(width, height, GetDepth(mat), mat._dimensionality, bandOptimization);\n            const int magicOffset0 = width; // +2;\n            const int magicOffset1 = width; // -2;\n\n            for (unsigned i=0; i<N; ++i) {\n                float a = mat._a0;\n                for (unsigned k=0; k<factorization.BandCount()-1; ++k) {\n                    float l = factorization.BandedValue(i, k);\n                    a -= l*l;\n                }\n                a = XlSqrt(a);\n                factorization[i][i] = a;\n\n                if (i != 0) {\n\n                    int kband0Start, kband0End;\n                    if (mat._dimensionality==2) {\n                        kband0Start = kband0End = 0;\n                    } else {\n                        kband0Start = std::max(0,   int(i)-int(width*height)-int(bandOptimization));\n                        kband0End =                 int(i)-int(width*height)+int(bandOptimization)+1;\n                    }\n                    \n                    int kband1Start = std::max(0,   int(i)-magicOffset0-int(bandOptimization));\n                    int kband1End =                 int(i)-magicOffset0+int(bandOptimization)+1;\n                    \n                    int kband2Start = std::max(0,   int(i)-1-int(bandOptimization));\n\n                    for (unsigned j=i+1; j<std::min(i+1+bandOptimization+1, N); ++j) {\n                        float aij = ((j==i+1)||(j==i+width)||(j==i+thirdTest)) ? mat._a1 : 0.f;\n\n                            // there are only some cases of \"k\" that can possibly have data\n                            // it must be within the widened bands of both i and k. It's awkward\n                            // to find an overlap, so let's just check the bands of i\n                        for (int k=kband0Start; k<kband0End; ++k)\n                            aij -= factorization[i][k] * factorization[j][k];\n                        for (int k=kband1Start; k<kband1End; ++k)\n                            aij -= factorization[i][k] * factorization[j][k];\n                        for (int k=kband2Start; k<int(i); ++k)\n                            aij -= factorization[i][k] * factorization[j][k];\n\n                        factorization[j][i] = aij / a;\n                    }\n                    \n                    for (unsigned j=i+magicOffset1-bandOptimization; j<std::min(i+magicOffset1+bandOptimization+1, N); ++j) {\n                        float aij = ((j==i+1)||(j==i+width)||(j==i+thirdTest)) ? mat._a1 : 0.f;\n                        for (int k=kband0Start; k<kband0End; ++k)\n                            aij -= factorization[i][k] * factorization[j][k];\n                        for (int k=kband1Start; k<kband1End; ++k)\n                            aij -= factorization[i][k] * factorization[j][k];\n                        for (int k=kband2Start; k<int(i); ++k)\n                            aij -= factorization[i][k] * factorization[j][k];\n                        factorization[j][i] = aij / a;\n                    }\n\n                    if (mat._dimensionality!=2) {\n                        for (unsigned j=i+width*height-bandOptimization; j<std::min(i+width*height+bandOptimization+1, N); ++j) {\n                            float aij = ((j==i+1)||(j==i+width)||(j==i+thirdTest)) ? mat._a1 : 0.f;\n                            for (int k=kband0Start; k<kband0End; ++k)\n                                aij -= factorization[i][k] * factorization[j][k];\n                            for (int k=kband1Start; k<kband1End; ++k)\n                                aij -= factorization[i][k] * factorization[j][k];\n                            for (int k=kband2Start; k<int(i); ++k)\n                                aij -= factorization[i][k] * factorization[j][k];\n                            factorization[j][i] = aij / a;\n                        }\n                    }\n                }\n            }\n\n                // \n                //  Our preconditioner matrix is \"factorization\" multiplied by\n                //  it's transpose\n                //\n\n            int bands2D[] = { -int(width), -1, 1, width, 0 };\n            int bands3D[] = { -int(width*height), -int(width), -1, 1, width, width*height, 0 };\n            unsigned bandCount; int* bands;\n            if (mat._dimensionality == 2) {\n                bandCount = dimof(bands2D);\n                bands = bands2D;\n            } else {\n                bandCount = dimof(bands3D);\n                bands = bands3D;\n            }\n            MatrixX sparseMatrix(N, bandCount);\n            for (unsigned i=0; i<N; ++i) {\n\n                int kband0Start = std::max(0,       int(i)-magicOffset0-int(bandOptimization));\n                int kband0End   = std::max(0,       int(i)-magicOffset0+int(bandOptimization)+1);\n                int kband1Start = std::max(0,       int(i)-1-int(bandOptimization));\n                int kband1End   = std::min(int(N),  int(i)+1+int(bandOptimization)+1);\n                int kband2Start = std::min(int(N),  int(i)+magicOffset1-int(bandOptimization));\n                int kband2End   = std::min(int(N),  int(i)+magicOffset1+int(bandOptimization)+1);\n\n                int kband3Start, kband3End, kband4Start, kband4End;\n                if (mat._dimensionality==2) {\n                    kband3Start =  kband3End =  kband4Start = kband4End = 0;\n                } else {\n                    kband3Start =  std::max(0,      int(i)-int(width*height)-int(bandOptimization));\n                    kband3End   =  std::max(0,      int(i)-int(width*height)+int(bandOptimization)+1);\n                    kband4Start =  std::min(int(N), int(i)+int(width*height)-int(bandOptimization));\n                    kband4End   =  std::min(int(N), int(i)+int(width*height)+int(bandOptimization)+1);\n                }\n\n                for (unsigned j=0; j<bandCount; ++j) {\n                    int j2 = int(i) + bands[j];\n                    if (j2 >= 0 && j2 < int(N)) {\n\n                            // Here, calculate M(i, j), where M\n                            // is the factorization multiplied by its transpose\n                        float A = 0.f;\n                        for (int k=kband0Start; k<kband0End; ++k)\n                            A += factorization[i][k] * factorization[j2][k];\n                        for (int k=kband1Start; k<kband1End; ++k)\n                            A += factorization[i][k] * factorization[j2][k];\n                        for (int k=kband2Start; k<kband2End; ++k)\n                            A += factorization[i][k] * factorization[j2][k];\n                        for (int k=kband3Start; k<kband3End; ++k)\n                            A += factorization[i][k] * factorization[j2][k];\n                        for (int k=kband4Start; k<kband4End; ++k)\n                            A += factorization[i][k] * factorization[j2][k];\n\n                        sparseMatrix(i, j) = A;\n                    } else {\n                        sparseMatrix(i, j) = 0.f;\n                    }\n                }\n            }\n\n            return std::move(sparseMatrix);\n\n        }\n        \n    }\n\n    static float Sq(float i) { return i*i; }\n\n    static bool IsOnBand(UInt2 coord, const AMat& mat)\n    {\n        const auto width = GetWidth(mat);\n        const auto height = GetHeight(mat);\n        return  coord[0] > coord[1]\n            &&  (\n                        (coord[0]-1) == coord[1]\n                    ||  (coord[0]-int(width)) == coord[1]\n                    ||  (coord[0]-int(width*height)) == coord[1]\n                );\n    }\n    \n    static float CalculateOffDiag(UInt2 coord, const float diagonals[], const AMat& mat)\n    {\n        // Calculate the value in the cholesky decomposition at the given coordinate (for an off-diagonal)\n        // this is an unusual method to calculate this, but it suits us because of the way our\n        // matrix is banded.\n        const auto width = GetWidth(mat); (void)width;\n        const auto height = GetHeight(mat); (void)height;\n        const auto i = coord[1], j = coord[0]; // flipped around in this case\n        assert(i < j); (void)j;\n        assert(((j-1)==i) || ((j-int(width))==i) || ((j-int(width*height))==i));  // expecting a coordinate on a band\n\n        float A = mat._a1;  // assuming the request is on a band (we can consider it zero, otherwise)\n\n            // We need to subtract the dot product of the 'i' row with the 'j' row (up to 'i')\n            // but only entries on the bands have values... so we should only need to find the cases\n            // where they overlap.\n            //      doesn't seem to have a big effect..\n        // auto bc0 = j-int(width);\n        // if (bc0 >= 0 && bc0 < i) {\n        //     if (IsOnBand(UInt2(i, bc0), mat)) {\n        //         A -=    CalculateOffDiag(UInt2(i, bc0), diagonals, mat)\n        //             *   CalculateOffDiag(UInt2(j, bc0), diagonals, mat);\n        //     }\n        // }\n        // \n        // auto bc1 = j-int(width*height);\n        // if (bc1 >= 0 && bc1 < i) {\n        //     if (IsOnBand(UInt2(i, bc1), mat)) {\n        //         A -=    CalculateOffDiag(UInt2(i, bc1), diagonals, mat)\n        //             *   CalculateOffDiag(UInt2(j, bc1), diagonals, mat);\n        //     }\n        // }\n\n        return A / diagonals[i];\n    }\n\n    static MatrixX CalculateIncompleteCholeskyFast(const AMat& mat, unsigned N)\n    {\n        VectorX diagonalFactor(N);  // diagonal factorization\n        diagonalFactor.fill(0.f);\n        \n        const auto width = GetWidth(mat);\n        const auto height = GetHeight(mat);\n        // const unsigned thirdTest = (mat._dimensionality==2)?0:(width*height);\n\n        int band0 = -1;\n        int band1 = -int(width);\n        int band2 = INT_MIN;\n        if (mat._dimensionality >= 3) band2 = -int(width*height);\n\n        diagonalFactor[0] = XlSqrt(mat._a0);\n        for (unsigned i=1; i<N; ++i) {\n            float a = mat._a0;\n\n                // We're assuming that only values directly on our\n                // bands have values. Those values should be mat._a1 \n                // divided by the 'a' for that row. \n                // Note that we're avoiding part of the algorithm that\n                // subtracts small amount from the off-diagonal elements\n            {\n                int k = int(i)+band2;\n                if (k >= 0) a -= Sq(CalculateOffDiag(UInt2(i, k), diagonalFactor.data(), mat));\n            }\n            {\n                int k = int(i)+band1;\n                if (k >= 0) a -= Sq(CalculateOffDiag(UInt2(i, k), diagonalFactor.data(), mat));\n            }\n            {\n                int k = int(i)+band0;\n                if (k >= 0) a -= Sq(CalculateOffDiag(UInt2(i, k), diagonalFactor.data(), mat));\n            }\n\n            a = XlSqrt(a);\n            diagonalFactor[i] = a;\n        }\n\n            // \n            //  Our preconditioner matrix is \"factorization\" multiplied by\n            //  it's transpose\n            //\n\n        int bands2D[] = { -int(width), -1, 1, width, 0 };\n        int bands3D[] = { -int(width*height), -int(width), -1, 1, width, width*height, 0 };\n        unsigned bandCount; int* bands;\n        if (mat._dimensionality == 2) {\n            bandCount = dimof(bands2D);\n            bands = bands2D;\n        } else {\n            bandCount = dimof(bands3D);\n            bands = bands3D;\n        }\n        VectorX a(N), b(N); \n        MatrixX sparseMatrix(N, bandCount);\n        for (unsigned i=0; i<N; ++i) {\n            a.fill(0.f);\n            a(i) = diagonalFactor[i];\n            {\n                int k = int(i)+band2;\n                if (k >= 0) a(k) = CalculateOffDiag(UInt2(i, k), diagonalFactor.data(), mat);\n            }\n            {\n                int k = int(i)+band1;\n                if (k >= 0) a(k) = CalculateOffDiag(UInt2(i, k), diagonalFactor.data(), mat);\n            }\n            {\n                int k = int(i)+band0;\n                if (k >= 0) a(k) = CalculateOffDiag(UInt2(i, k), diagonalFactor.data(), mat);\n            }\n\n            for (unsigned j=0; j<bandCount; ++j) {\n                int j2 = int(i) + bands[j];\n                if (j2 >= 0 && j2 < int(N)) {\n\n                        // Here, calculate M(i, j), where M\n                        // is the factorization multiplied by its transpose\n                    b.fill(0.f);\n                    b[j2] = diagonalFactor[j2];\n                    {\n                        int k = int(j2)+band2;\n                        if (k >= 0) b(k) = CalculateOffDiag(UInt2(j2, k), diagonalFactor.data(), mat);\n                    }\n                    {\n                        int k = int(j2)+band1;\n                        if (k >= 0) b(k) = CalculateOffDiag(UInt2(j2, k), diagonalFactor.data(), mat);\n                    }\n                    {\n                        int k = int(j2)+band0;\n                        if (k >= 0) b(k) = CalculateOffDiag(UInt2(j2, k), diagonalFactor.data(), mat);\n                    }\n\n                    sparseMatrix(i, j) = a.dot(b);\n                } else {\n                    sparseMatrix(i, j) = 0.f;\n                }\n            }\n        }\n\n        return std::move(sparseMatrix);\n    }\n\n///////////////////////////////////////////////////////////////////////////////////////////////////\n\n    PoissonSolver::PoissonSolver(unsigned dimensionality, unsigned dimensions[])\n    {\n        assert(dimensionality==2 || dimensionality == 3);\n        dimensionality = std::min(dimensionality, 3u);\n        _pimpl = std::make_unique<Pimpl>();\n        _pimpl->_dimensionsWithBorders = UInt3(1,1,1);\n        _pimpl->_dimensionality = dimensionality;\n        for (unsigned c=0; c<_pimpl->_dimensionality; ++c)\n            _pimpl->_dimensionsWithBorders[c] = dimensions[c];\n\n        const auto N = \n              _pimpl->_dimensionsWithBorders[0]\n            * _pimpl->_dimensionsWithBorders[1]\n            * _pimpl->_dimensionsWithBorders[2];\n        \n        _pimpl->_tempBuffer = VectorX(N);\n        _pimpl->_tempBuffer.fill(0.f);\n\n        #if defined(_DEBUG)\n            {\n                const auto diffusion = 0.1f;\n                const auto a0 = 1.f + 6.f * diffusion;\n                const auto a1 = -diffusion;\n                AMat A = { \n                    UInt3(16, 16, 8), \n                    3, ~0u,\n                    a0, a1 };\n                auto precon0 = CalculateIncompleteCholeskyFast(A, 8*8*8);\n                auto precon1 = CalculateIncompleteCholesky(A, 8*8*8, 0);\n\n                const auto rows = (unsigned)precon0.rows();\n                for (unsigned i=0; i<rows; ++i) {\n                    LogInfo << \"[\" << i << \"] \" \n                        << precon0(i, 0) << \", \"\n                        << precon0(i, 1) << \", \"\n                        << precon0(i, 2) << \", \"\n                        << precon0(i, 3) << \", \"\n                        << precon0(i, 4) << \", \"\n                        << precon0(i, 5) << \", \"\n                        << precon0(i, 6) << \" (\"\n                        << precon1(i, 0) << \", \"\n                        << precon1(i, 1) << \", \"\n                        << precon1(i, 2) << \", \"\n                        << precon1(i, 3) << \", \"\n                        << precon1(i, 4) << \", \"\n                        << precon1(i, 5) << \", \"\n                        << precon1(i, 6) << \")\";\n                }\n\n                (void)precon1;\n            }\n        #endif\n    }\n\n    auto PoissonSolver::PrepareDiffusionMatrix(\n        float diffusionAmount, Method method, unsigned wrapEdgesFlags) const \n            -> std::shared_ptr<PreparedMatrix>\n    {\n            // Note that with some methods (multigrid, SOR) we require an \n            // extra margin area. We have to consider how we set the margin\n            // flags value in the matrix.\n        float a0, a1;\n        float a0c;\n        float a0ex, a0ey;\n        float a1e, a1rx, a1ry;\n\n        const bool wrapX = !!(wrapEdgesFlags & (1<<0));\n        const bool wrapY = !!(wrapEdgesFlags & (1<<1));\n        const bool wrapZ = !!(wrapEdgesFlags & (1<<2));\n\n        if (_pimpl->_dimensionality==2) {\n            a0 = 1.f + 4.f * diffusionAmount;\n            a1 = -diffusionAmount;\n\n            unsigned cornerInfl = 2u + unsigned(wrapX) + unsigned(wrapY);\n            a0c = 1.f + cornerInfl * diffusionAmount;\n\n            a0ex = 1.f + (3u + unsigned(wrapX)) * diffusionAmount;\n            a0ey = 1.f + (3u + unsigned(wrapY)) * diffusionAmount;\n\n            a1e = -diffusionAmount;\n            a1rx = wrapX?-diffusionAmount:0.f;\n            a1ry = wrapY?-diffusionAmount:0.f;\n        } else {\n            a0 = 1.f + 6.f * diffusionAmount;\n            a1 = -diffusionAmount;\n\n            unsigned cornerInfl = 2u + unsigned(wrapX) + unsigned(wrapY) + unsigned(wrapZ);\n            a0c = 1.f + cornerInfl * diffusionAmount;\n\n            a0ex = 1.f + (4u + unsigned(wrapX) + unsigned(wrapY)) * diffusionAmount;\n            a0ey = 1.f + (4u + unsigned(wrapX) + unsigned(wrapY)) * diffusionAmount;\n\n            a1e = -diffusionAmount;\n            a1rx = wrapX?-diffusionAmount:0.f;\n            a1ry = wrapY?-diffusionAmount:0.f;\n        }\n\n        // if (!wrapEdges) {   // getting better results if we just keep the edges and corners at constant values\n        //     a0e = a0c = 1.f;\n        //     a1e = a1r = 0.f;\n        // }\n\n        const unsigned marginFlags = 0u;\n        AMat A = {\n            _pimpl->_dimensionsWithBorders, _pimpl->_dimensionality, marginFlags, \n            a0, a1, a0c, a0ex, a0ey, a1e, a1rx, a1ry\n        };\n        const auto N = \n              _pimpl->_dimensionsWithBorders[0] \n            * _pimpl->_dimensionsWithBorders[1] \n            * _pimpl->_dimensionsWithBorders[2];\n\n        auto result = std::make_shared<PreparedMatrix>();\n        result->_amat = A;\n\n        const bool needPrecon = method == Method::PreconCG;\n        if (needPrecon) {\n            auto precon = CalculateIncompleteCholeskyFast(A, N);\n            const auto width = _pimpl->_dimensionsWithBorders[0];\n            const auto height = _pimpl->_dimensionsWithBorders[1];\n\n            if (_pimpl->_dimensionality==2) {\n                    // ----- 2D case -----\n                result->_bands.resize(5);\n                result->_bands[0] =  -int(width);\n                result->_bands[1] =  -1;\n                result->_bands[2] =   1;\n                result->_bands[3] =   width;\n                result->_bands[4] =   0;\n            } else {\n                    // ----- 3D case -----\n                result->_bands.resize(7);\n                result->_bands[0] =  -int(width*height);\n                result->_bands[1] =  -int(width);\n                result->_bands[2] =  -1;\n                result->_bands[3] =   1;\n                result->_bands[4] =   width;\n                result->_bands[5] =   width*height;\n                result->_bands[6] =   0;\n            }\n\n            result->_bandedPrecon = SparseBandedMatrix<MatrixX>(\n                std::move(precon), \n                AsPointer(result->_bands.cbegin()), (unsigned)result->_bands.size());\n        }\n\n        return std::move(result);\n    }\n\n    auto PoissonSolver::PrepareDivergenceMatrix(Method method, unsigned wrapEdgesFlags) const -> std::shared_ptr<PreparedMatrix>\n    {\n        float a0, a1;\n        float a0c;\n        float a0ex, a0ey;\n        float a1e, a1rx, a1ry;\n\n        const bool wrapX = !!(wrapEdgesFlags & (1<<0));\n        const bool wrapY = !!(wrapEdgesFlags & (1<<1));\n        const bool wrapZ = !!(wrapEdgesFlags & (1<<2));\n        if (_pimpl->_dimensionality==2) {\n            a0 = 4.f;\n            a1 = -1.f;\n            \n            unsigned cornerInfl = 2u + unsigned(wrapX) + unsigned(wrapY);\n            a0c = float(cornerInfl);\n\n            a0ex = float(3u + unsigned(wrapX));\n            a0ey = float(3u + unsigned(wrapY));\n            \n            a1e = -1.f;\n            a1rx = wrapX?-1.f:0.f;\n            a1ry = wrapY?-1.f:0.f;\n        } else {\n            a0 = 6.f;\n            a1 = -1.f;\n\n            unsigned cornerInfl = 2u + unsigned(wrapX) + unsigned(wrapY) + unsigned(wrapZ);\n            a0c = float(cornerInfl);\n\n            a0ex = float(4u + unsigned(wrapX) + unsigned(wrapY));\n            a0ey = float(4u + unsigned(wrapX) + unsigned(wrapY));\n            \n            a1e = -1.f;\n            a1rx = wrapX?-1.f:0.f;\n            a1ry = wrapY?-1.f:0.f;\n        }\n        // if (!wrapEdges) {   // getting better results if we just keep the edges and corners at constant values\n        //     a0e = a0c = 1.f;\n        //     a1e = a1r = 0.f;\n        // }\n\n        const unsigned marginFlags = 0u;\n        AMat A = {\n            _pimpl->_dimensionsWithBorders, _pimpl->_dimensionality, marginFlags, \n            a0, a1, a0c, a0ex, a0ey, a1e, a1rx, a1ry\n        };\n        const auto N = \n              _pimpl->_dimensionsWithBorders[0] \n            * _pimpl->_dimensionsWithBorders[1] \n            * _pimpl->_dimensionsWithBorders[2];\n\n        auto result = std::make_shared<PreparedMatrix>();\n        result->_amat = A;\n\n        const bool needPrecon = method == Method::PreconCG;\n        if (needPrecon) {\n            auto precon = CalculateIncompleteCholeskyFast(A, N);\n            const auto width = _pimpl->_dimensionsWithBorders[0];\n            const auto height = _pimpl->_dimensionsWithBorders[1];\n\n            if (_pimpl->_dimensionality==2) {\n                    // ----- 2D case -----\n                result->_bands.resize(5);\n                result->_bands[0] =  -int(width);\n                result->_bands[1] =  -1;\n                result->_bands[2] =   1;\n                result->_bands[3] =   width;\n                result->_bands[4] =   0;\n            } else {\n                    // ----- 3D case -----\n                result->_bands.resize(7);\n                result->_bands[0] =  -int(width*height);\n                result->_bands[1] =  -int(width);\n                result->_bands[2] =  -1;\n                result->_bands[3] =   1;\n                result->_bands[4] =   width;\n                result->_bands[5] =   width*height;\n                result->_bands[6] =   0;\n            }\n\n            result->_bandedPrecon = SparseBandedMatrix<MatrixX>(\n                std::move(precon), \n                AsPointer(result->_bands.cbegin()), (unsigned)result->_bands.size());\n        }\n\n        return std::move(result);\n    }\n\n    PoissonSolver::PoissonSolver(PoissonSolver&& moveFrom)\n    : _pimpl(std::move(moveFrom._pimpl)) {}\n\n    PoissonSolver& PoissonSolver::operator=(PoissonSolver&& moveFrom)\n    {\n        _pimpl = std::move(moveFrom._pimpl);\n        return *this;\n    }\n\n    PoissonSolver::PoissonSolver() {}\n    PoissonSolver::~PoissonSolver() {}\n}\n\n", "meta": {"hexsha": "a379856dfff3b5a37b4a97d6a6f1b7a5dc211b10", "size": 63478, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Math/PoissonSolver.cpp", "max_stars_repo_name": "alexgithubber/XLE-Another-Fork", "max_stars_repo_head_hexsha": "cdd8682367d9e9fdbdda9f79d72bb5b1499cec46", "max_stars_repo_licenses": ["MIT"], "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/PoissonSolver.cpp", "max_issues_repo_name": "alexgithubber/XLE-Another-Fork", "max_issues_repo_head_hexsha": "cdd8682367d9e9fdbdda9f79d72bb5b1499cec46", "max_issues_repo_licenses": ["MIT"], "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/PoissonSolver.cpp", "max_forks_repo_name": "alexgithubber/XLE-Another-Fork", "max_forks_repo_head_hexsha": "cdd8682367d9e9fdbdda9f79d72bb5b1499cec46", "max_forks_repo_licenses": ["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.1660181582, "max_line_length": 151, "alphanum_fraction": 0.4876650178, "num_tokens": 16216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4792988603183108}}
{"text": "/**\n * \\ file UniversalFixedDelayLineFilter.cpp\n */\n\n#include <ATK/Delay/UniversalFixedDelayLineFilter.h>\n\n#include <ATK/Core/InPointerFilter.h>\n#include <ATK/Core/OutPointerFilter.h>\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_NO_MAIN\n#include <boost/test/unit_test.hpp>\n\n#include <boost/math/constants/constants.hpp>\n#include <boost/scoped_array.hpp>\n\n#define PROCESSSIZE (1024*64)\n\nBOOST_AUTO_TEST_CASE( UniversalFixedDelayLineFilter_sinus_line100_delay50_test )\n{\n  boost::scoped_array<float> data(new float[PROCESSSIZE]);\n  for(int64_t i = 0; i < PROCESSSIZE; ++i)\n  {\n    data[i] = std::sin(2 * boost::math::constants::pi<float>() * (i+1.)/48000 * 1000);\n  }\n\n  ATK::InPointerFilter<float> generator(data.get(), 1, PROCESSSIZE, false);\n  generator.set_output_sampling_rate(48000);\n\n  boost::scoped_array<float> outdata(new float[PROCESSSIZE]);\n\n  ATK::UniversalFixedDelayLineFilter<float> filter(100);\n  filter.set_input_sampling_rate(48000);\n  filter.set_input_port(0, &generator, 0);\n  filter.set_delay(50);\n\n  ATK::OutPointerFilter<float> output(outdata.get(), 1, PROCESSSIZE, false);\n  output.set_input_sampling_rate(48000);\n  output.set_input_port(0, &filter, 0);\n\n  output.process(49);\n  output.process(1);\n  output.process(51);\n  output.process(PROCESSSIZE - 1 - 49 -51);\n  \n  for(int64_t i = 0; i < 50; ++i)\n  {\n    BOOST_REQUIRE_EQUAL(0, outdata[i]);\n  }\n  \n  for(int64_t i = 50; i < PROCESSSIZE; ++i)\n  {\n    BOOST_REQUIRE_EQUAL(data[i - 50], outdata[i]);\n  }\n}\n\nBOOST_AUTO_TEST_CASE( UniversalFixedDelayLineFilter_sinus_line25_delay24_blend_1_feedforward_1_feedback_0_test )\n{\n  boost::scoped_array<float> data(new float[PROCESSSIZE]);\n  for(int64_t i = 0; i < PROCESSSIZE; ++i)\n  {\n    data[i] = std::sin(2 * boost::math::constants::pi<float>() * (i+1.)/48000 * 1000);\n  }\n\n  ATK::InPointerFilter<float> generator(data.get(), 1, PROCESSSIZE, false);\n  generator.set_output_sampling_rate(48000);\n\n  boost::scoped_array<float> outdata(new float[PROCESSSIZE]);\n\n  ATK::UniversalFixedDelayLineFilter<float> filter(25);\n  filter.set_input_sampling_rate(48000);\n  filter.set_input_port(0, &generator, 0);\n  filter.set_delay(24);\n  filter.set_blend(1);\n  filter.set_feedback(0);\n  filter.set_feedforward(1);\n\n  ATK::OutPointerFilter<float> output(outdata.get(), 1, PROCESSSIZE, false);\n  output.set_input_sampling_rate(48000);\n  output.set_input_port(0, &filter, 0);\n\n  output.process(49);\n  output.process(1);\n  output.process(51);\n  output.process(PROCESSSIZE - 1 - 49 -51);\n\n  for(int64_t i = 24; i < PROCESSSIZE; ++i)\n  {\n    BOOST_REQUIRE_SMALL(outdata[i], 0.0001f);\n  }\n}\n\nBOOST_AUTO_TEST_CASE( UniversalFixedDelayLineFilter_sinus_line25_delay24_blend_0_feedforward_0_feedback_1_test )\n{\n  boost::scoped_array<float> data(new float[PROCESSSIZE]);\n  for(int64_t i = 0; i < PROCESSSIZE; ++i)\n  {\n    data[i] = std::sin(2 * boost::math::constants::pi<float>() * (i+1.)/48000 * 1000);\n  }\n\n  ATK::InPointerFilter<float> generator(data.get(), 1, PROCESSSIZE, false);\n  generator.set_output_sampling_rate(48000);\n\n  boost::scoped_array<float> outdata(new float[PROCESSSIZE]);\n\n  ATK::UniversalFixedDelayLineFilter<float> filter(25);\n  filter.set_input_sampling_rate(48000);\n  filter.set_input_port(0, &generator, 0);\n  filter.set_delay(24);\n  filter.set_blend(0);\n  filter.set_feedback(1);\n  filter.set_feedforward(0);\n\n  ATK::OutPointerFilter<float> output(outdata.get(), 1, PROCESSSIZE, false);\n  output.set_input_sampling_rate(48000);\n  output.set_input_port(0, &filter, 0);\n\n  output.process(49);\n  output.process(1);\n  output.process(51);\n  output.process(PROCESSSIZE - 1 - 49 -51);\n\n  for(int64_t i = 24; i < PROCESSSIZE; ++i)\n  {\n    BOOST_REQUIRE_SMALL(outdata[i], 0.0001f);\n  }\n}\n", "meta": {"hexsha": "1b1699a1b310bf0a91004022208f5afb03b6a711", "size": 3704, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/Delay/UniversalFixedDelayLineFilter.cpp", "max_stars_repo_name": "apohl79/AudioTK", "max_stars_repo_head_hexsha": "05ac241b0bc6a8f841d93257b4d81e5961b1f627", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-05-17T15:29:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T22:26:08.000Z", "max_issues_repo_path": "tests/Delay/UniversalFixedDelayLineFilter.cpp", "max_issues_repo_name": "apohl79/AudioTK", "max_issues_repo_head_hexsha": "05ac241b0bc6a8f841d93257b4d81e5961b1f627", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/Delay/UniversalFixedDelayLineFilter.cpp", "max_forks_repo_name": "apohl79/AudioTK", "max_forks_repo_head_hexsha": "05ac241b0bc6a8f841d93257b4d81e5961b1f627", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-04-21T13:43:57.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-28T19:10:14.000Z", "avg_line_length": 28.9375, "max_line_length": 112, "alphanum_fraction": 0.7213822894, "num_tokens": 1077, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4792970488641266}}
{"text": "//          Copyright Gavin Band 2008 - 2012.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef INTEGRATION_MODIFIED_CHOLESKY_HPP\n#define INTEGRATION_MODIFIED_CHOLESKY_HPP\n\n#include <iostream>\n#include <boost/noncopyable.hpp>\n#include <Eigen/Core>\n#include <Eigen/Cholesky>\n#include <Eigen/Eigenvalues>\n\n// #define DEBUG_MODIFIED_CHOLESKY 1\n\nnamespace integration {\n\t//\n\t// Implements the 'MC' algorithm from Gill & Murray, Practical Optimisation.\n\t// Also expressed as Algorithm 6.5, \"Modified Cholesky algorithm\" in\n\t// Nocedal & Wright, \"Numerical Optimisation\".\n\t//\n\t// I have borrowed a little bit from Eigen's LDLT.h here to get the permutations and types right.\n\t//\n\t// This algorithm only touches the lower-diagonal of the matrix.\n\t// As described in the above references, we use the lower-diagonal of the matrix\n\t// to store the non-unity entries of L, and the diagonal to store the entries of D.\n\t// The auxiliary variables c_ij are stored in the lower diagonal too until they\n\t// are overwritten by entries of L and D.\n\t//\n\t// At step j the matrix looks like:\n\t//\n\t//    0 . . j . .\n\t// 0  d\n\t// .  l d\n\t// .  l l d\n\t// j  c c c c\n\t// .  c c c a c\n\t// .  c c c a a c\n\t//\n\t// Where a refers to an entry of the original matrix (after the possible permutations) and l refers to an entry of\n\t// the computed matrix L, d refers to an entry of D, and c to one of the auxiliary c_ijs.\n\t//\n\t// At the jth step we update this to become\n\t// 1: d\n\t// .  l d\n\t// .  l l d\n\t// j: l l l d\n\t// .  c c c c c\n\t// .  c c c c a c\n\t//\n\t// i.e. we compute the jth row of L, the jth entry of D, and the c's in\n\t// the jth column and on the diagonal below j.\n\ttemplate< typename Matrix >\n\tstruct ModifiedCholesky {\n\tpublic:\n\t    enum {\n\t      RowsAtCompileTime = Matrix::RowsAtCompileTime,\n\t      ColsAtCompileTime = Matrix::ColsAtCompileTime,\n\t      Options = Matrix::Options & ~Eigen::RowMajorBit, // these are the options for the TmpMatrixType, we need a ColMajor matrix here!\n\t      MaxRowsAtCompileTime = Matrix::MaxRowsAtCompileTime,\n\t      MaxColsAtCompileTime = Matrix::MaxColsAtCompileTime,\n\t      UpLo = Eigen::Lower\n\t    } ;\n\t    typedef typename Matrix::Scalar Scalar;\n\t    typedef typename Eigen::NumTraits<typename Matrix::Scalar>::Real RealScalar;\n\t    typedef typename Matrix::Index Index;\n\n\t    typedef Eigen::Transpositions<RowsAtCompileTime, MaxRowsAtCompileTime> Transpositions;\n\t    typedef Eigen::PermutationMatrix<RowsAtCompileTime, MaxRowsAtCompileTime> Permutations;\n\t    typedef Eigen::TriangularView< Matrix const, Eigen::UnitLower > const MatrixL ;\n\t\ttypedef Eigen::Diagonal< Matrix const > Diagonal ;\n\n\tpublic:\n\t\tModifiedCholesky() {}\n\n\t\tModifiedCholesky( ModifiedCholesky const& other ):\n\t\t\tm_matrix( other.m_matrix ),\n\t\t\tm_transpositions( other.m_transpositions )\n\t\t{}\n\n\t\tModifiedCholesky& operator=( ModifiedCholesky const& other ) {\n\t\t\tm_matrix = other.m_matrix ;\n\t\t\tm_transpositions = other.m_transpositions ;\n\t\t\treturn *this ;\n\t\t}\n\t\t\n\t\tModifiedCholesky& compute( Matrix const& matrix ) {\n\t\t\tm_matrix = matrix ;\n\t\t\tcompute_inplace( m_matrix ) ;\n\t\t\treturn *this ;\n\t\t}\n\t\t\n\t\tMatrixL matrixL() const {\n\t\t\treturn m_matrix ;\n\t\t}\n\t\t\n\t    Diagonal vectorD() const {\n\t\t\treturn m_matrix.diagonal();\n\t\t}\n\n\t\tTranspositions const matrixP() const {\n\t\t\treturn m_transpositions ;\n\t\t}\n\t\t\n\t\tMatrix solve( Matrix const& rhs ) const\n\t    {\n\t\t\tMatrix result = rhs ;\n\t\t\tassert( result.rows() == m_matrix.rows() ) ;\n\t\t    // result = P rhs\n\t\t    result = m_transpositions * result ;\n\t\t    // result = L^-1 (P rhs)\n\t\t    matrixL().solveInPlace( result );\n\t\t    // result = D^-1 (L^-1 P rhs)\n\t\t\tfor( Index i = 0; i < m_matrix.rows(); ++i ) {\n\t\t\t\tresult.row(i) /= m_matrix(i,i) ;\n\t\t\t}\n\t\t    // result = L^-T (D^-1 L^-1 P rhs)\n\t\t    matrixL().transpose().solveInPlace( result ) ;\n\t\t    // result = P^-1 L^-T (D^-1 L^-1 P rhs)\n\t\t\tresult = m_transpositions.transpose() * result ;\n\t\t\treturn result ;\n\t    }\n\t\t\n\tprivate:\n\t    Matrix m_matrix ;\n\t    Transpositions m_transpositions;\n\t\t\n\tprivate:\n\t\t\n\t\tvoid compute_inplace( Matrix& matrix ) {\n\t\t\tassert( matrix.rows() == matrix.cols() ) ;\n\t\t\tm_transpositions.resize( matrix.rows() ) ;\n\t\t\tIndex const size = matrix.rows() ;\n\t\t\t\n#if DEBUG_MODIFIED_CHOLESKY\n\t\t\tstd::cerr << \"ModifiedCholesky::compute_inplace(): computing with matrix:\\n\" << matrix << \".\\n\" ;\n#endif\n\t\t\t\n\t\t\tScalar biggestOnDiagonal ;\n\t\t\tRealScalar beta ;\n\t\t\tRealScalar betaSquared ;\n\t\t\tRealScalar delta ;\n\n\t\t\tfor( Index j = 0; j < size; ++j ) {\n\t\t        // Find largest diagonal element\n\t\t        Index indexOfBiggestOnDiagonal ;\n\t\t        biggestOnDiagonal = matrix.diagonal().tail( size - j ).cwiseAbs().maxCoeff( &indexOfBiggestOnDiagonal ) ;\n\t\t\t\tindexOfBiggestOnDiagonal += j ;\n\n\t\t\t\t// Initialise beta and delta if we are starting.\n\t\t        if( j == 0 ) {\n\t\t\t\t\tScalar biggestOffDiagonal = 0.0 ;\n\t\t\t\t\tfor( Index i = 0; i < size; ++i ) {\n\t\t\t\t\t\tfor( Index j = i+1; j < size; ++j ) {\n\t\t\t\t\t\t\tbiggestOffDiagonal = std::max( biggestOffDiagonal, std::abs( matrix( i, j )) ) ;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tdelta = std::numeric_limits< Scalar >::epsilon() * std::max( biggestOnDiagonal + biggestOffDiagonal, Scalar( 1 ) ) ;\n\t\t\t\t\tbeta = std::max(\n\t\t\t\t\t\tstd::numeric_limits< Scalar >::epsilon(),\n\t\t\t\t\t\tstd::max( biggestOnDiagonal, biggestOffDiagonal / std::sqrt( ( size * size ) - 1 ) )\n\t\t\t\t\t) ;\n\t\t\t\t\tbetaSquared = beta * beta ;\n\t\t\t\t\t\n#if DEBUG_MODIFIED_CHOLESKY\n\t\t\t\t\tstd::cerr << \"ModifiedCholesky::compute_inplace(): initialised with delta = \"\n\t\t\t\t\t\t<< delta << \", beta^2 = \" << betaSquared << \".\\n\" ;\n#endif\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\t\n#if DEBUG_MODIFIED_CHOLESKY\n\t\t\t\tstd::cerr << \"ModifiedCholesky::compute_inplace(): at iteration \"\n\t\t\t\t\t<< j\n\t\t\t\t\t\t<< \": largest entry on diagonal = \" << biggestOnDiagonal\n\t\t\t\t\t<< \" at index \" << indexOfBiggestOnDiagonal << \".\\n\" ;\n#endif\n\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t// Swap rows and columns corresponding to the jth and largest diagonal element.\n\t\t        m_transpositions.coeffRef( j ) = indexOfBiggestOnDiagonal ;\n\t\t\t\tIndex const tailSize = size - indexOfBiggestOnDiagonal - 1 ;\n\t\t        if( j != indexOfBiggestOnDiagonal ) {\n\t\t\t\t\t// indexOfbiggestOnDiagonal is always >= j by construction\n\t\t\t\t\t// we only touch the lower triangular part of the matrix.\n\t\t\t\t\tmatrix.row( j ).head( j ).swap( matrix.row( indexOfBiggestOnDiagonal ).head( j ) ) ;\n\t\t\t\t\tmatrix.col( j ).tail( tailSize ).swap( matrix.col( indexOfBiggestOnDiagonal ).tail( tailSize ) ) ;\n\t\t\t\t\tstd::swap( matrix.coeffRef(j,j), matrix.coeffRef( indexOfBiggestOnDiagonal, indexOfBiggestOnDiagonal ) );\n\t\t\t\t\tfor( int i = j+1; i < indexOfBiggestOnDiagonal; ++i ) {\n\t\t\t\t\t\tstd::swap( matrix.coeffRef( i, j ), matrix.coeffRef( indexOfBiggestOnDiagonal, i ) ) ;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t// We first compute the jth row of L to produce:\n\t\t\t\t// 1: d\n\t\t\t\t// .  l d\n\t\t\t\t// .  l l d\n\t\t\t\t// j: l l l c\n\t\t\t\t// .  c c c a c\n\t\t\t\t// .  c c c a a c\n\t\t\t\t//\n\t\t\t\t// by formula: l_js = c_js / d_s for s = 0,...,j-1.\n\t\t        matrix.row( j ).head( j ).array() /= matrix.diagonal().head( j ).array() ;\n#if DEBUG_MODIFIED_CHOLESKY\n\t\t\t\tstd::cerr << \"ModifiedCholesky::compute_inplace(): after computing ls, matrix =\\n\"\n\t\t\t\t\t<< matrix << \".\\n\" ;\n#endif\n\t\t\t\t// We next compute jth column of c_ijs to get:\n\t\t\t\t// 1: d\n\t\t\t\t// .  l d\n\t\t\t\t// .  l l d\n\t\t\t\t// j: l l l c\n\t\t\t\t// .  c c c c c\n\t\t\t\t// .  c c c c a c\n\t\t\t\t//\n\t\t\t\t// by formula c_ij = a_ij - sum_s l_ks c_is for s=j+1...n\n\t\t\t\tfor( Index i = j+1; i < size; ++i ) {\n\t\t\t\t\tmatrix(i,j) -= ( matrix.row( j ).head( j ) * matrix.row( i ).head( j ).transpose() ) ;\n\t\t\t\t}\n\t\t\t\tScalar const theta = ( (j+1) == size ) ? 0.0 : ( matrix.col( j ).tail( tailSize ).maxCoeff() ) ;\n#if DEBUG_MODIFIED_CHOLESKY\n\t\t\t\tstd::cerr << \"ModifiedCholesky::compute_inplace(): after computing cs, matrix =\\n\"\n\t\t\t\t\t<< matrix << \",\\n\"\n\t\t\t\t\t<< \"theta = \" << theta << \".\\n\" ;\n#endif\n\n\t\t\t\t// compute d_jj to produce\n\t\t\t\t// 1: d\n\t\t\t\t// .  l d\n\t\t\t\t// .  l l d\n\t\t\t\t// j: l l l d\n\t\t\t\t// .  c c c c c\n\t\t\t\t// .  c c c c a c\n\t\t\t\tdouble new_dj = std::max( delta, std::abs( matrix(j,j) ) ) ;\n\t\t\t\tnew_dj = std::max( new_dj, (theta*theta) / betaSquared ) ;\n\t\t\t\tmatrix(j,j) = new_dj ;\n\t\t\t\t//\n\t\t\t\t// Finally update the c_ii's\n\t\t\t\tmatrix.diagonal().tail( tailSize ).array() -= ( matrix.col(j).tail( tailSize ).array().square() ) / matrix(j,j) ;\n\t\t\t\t\n#if DEBUG_MODIFIED_CHOLESKY\n\t\t\t\tstd::cerr << \"ModifiedCholesky::compute_inplace(): after iteration \" << j << \", matrix is:\\n\"\n\t\t\t\t\t<< matrix << \".\\n\" ;\n#endif\n\t\t\t}\n\t\t}\n\t} ;\n}\n\n#endif\n", "meta": {"hexsha": "41474469e13180068e93ea01d58123583bf38274", "size": 8497, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "integration/include/integration/ModifiedCholesky.hpp", "max_stars_repo_name": "gavinband/bingwa", "max_stars_repo_head_hexsha": "d52e166b3bb6bc32cd32ba63bf8a4a147275eca1", "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": "integration/include/integration/ModifiedCholesky.hpp", "max_issues_repo_name": "gavinband/bingwa", "max_issues_repo_head_hexsha": "d52e166b3bb6bc32cd32ba63bf8a4a147275eca1", "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": "integration/include/integration/ModifiedCholesky.hpp", "max_forks_repo_name": "gavinband/bingwa", "max_forks_repo_head_hexsha": "d52e166b3bb6bc32cd32ba63bf8a4a147275eca1", "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.8525896414, "max_line_length": 135, "alphanum_fraction": 0.6237495587, "num_tokens": 2538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4792970488641266}}
{"text": "//////////////////////////////////////////////////////////////////////////////\n//\n// (C) Copyright Ion Gaztanaga 2014-2015. 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// See http://www.boost.org/libs/container for documentation.\n//\n//////////////////////////////////////////////////////////////////////////////\n#ifndef BOOST_CONTAINER_DETAIL_NEXT_CAPACITY_HPP\n#define BOOST_CONTAINER_DETAIL_NEXT_CAPACITY_HPP\n\n#ifndef BOOST_CONFIG_HPP\n#  include <boost/config.hpp>\n#endif\n\n#if defined(BOOST_HAS_PRAGMA_ONCE)\n#  pragma once\n#endif\n\n// container\n#include <boost/container/throw_exception.hpp>\n// container/detail\n#include <boost/container/detail/min_max.hpp>\n\n#include <boost/static_assert.hpp>\n\nnamespace lslboost {\nnamespace container {\nnamespace dtl {\n\ntemplate<unsigned Minimum, unsigned Numerator, unsigned Denominator>\nstruct grow_factor_ratio\n{\n   BOOST_STATIC_ASSERT(Numerator > Denominator);\n   BOOST_STATIC_ASSERT(Numerator   < 100);\n   BOOST_STATIC_ASSERT(Denominator < 100);\n   BOOST_STATIC_ASSERT(Denominator == 1 || (0 != Numerator % Denominator));\n\n   template<class SizeType>\n   SizeType operator()(const SizeType cur_cap, const SizeType add_min_cap, const SizeType max_cap) const\n   {\n      const SizeType overflow_limit  = ((SizeType)-1) / Numerator;\n\n      SizeType new_cap = 0;\n\n      if(cur_cap <= overflow_limit){\n         new_cap = cur_cap * Numerator / Denominator;\n      }\n      else if(Denominator == 1 || (SizeType(new_cap = cur_cap) / Denominator) > overflow_limit){\n         new_cap = (SizeType)-1;\n      }\n      else{\n         new_cap *= Numerator;\n      }\n      return max_value(SizeType(Minimum), max_value(cur_cap+add_min_cap, min_value(max_cap, new_cap)));\n   }\n};\n\n}  //namespace dtl {\n\nstruct growth_factor_50\n   : dtl::grow_factor_ratio<0, 3, 2>\n{};\n\nstruct growth_factor_60\n   : dtl::grow_factor_ratio<0, 8, 5>\n{};\n\nstruct growth_factor_100\n   : dtl::grow_factor_ratio<0, 2, 1>\n{};\n\n}  //namespace container {\n}  //namespace lslboost {\n\n#endif   //#ifndef BOOST_CONTAINER_DETAIL_NEXT_CAPACITY_HPP\n", "meta": {"hexsha": "f5ccfd4adbd2ab4b662f407c4ac48cd4ed5ab16b", "size": 2146, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lslboost/boost/container/detail/next_capacity.hpp", "max_stars_repo_name": "samuelpowell/liblsl", "max_stars_repo_head_hexsha": "92f0e2f4870cd9b505cd35c89f70c7a9d3b191a3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-11-19T00:57:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-13T23:24:51.000Z", "max_issues_repo_path": "lslboost/boost/container/detail/next_capacity.hpp", "max_issues_repo_name": "samuelpowell/liblsl", "max_issues_repo_head_hexsha": "92f0e2f4870cd9b505cd35c89f70c7a9d3b191a3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lslboost/boost/container/detail/next_capacity.hpp", "max_forks_repo_name": "samuelpowell/liblsl", "max_forks_repo_head_hexsha": "92f0e2f4870cd9b505cd35c89f70c7a9d3b191a3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-19T23:31:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-19T23:31:13.000Z", "avg_line_length": 27.5128205128, "max_line_length": 104, "alphanum_fraction": 0.6668219944, "num_tokens": 510, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4792970424243505}}
{"text": "#include <Eigen/Core>\n#include <Eigen/Dense>\n\n#include <glog/logging.h>\n#include <gtest/gtest.h>\n#include <maplab-common/pose_types.h>\n#include <maplab-common/quaternion-math.h>\n#include <maplab-common/test/testing-entrypoint.h>\n#include <maplab-common/test/testing-predicates.h>\n\n#include \"ceres-error-terms/parameterization/quaternion-param-eigen.h\"\n\nTEST(QuaternionEigenParametrization, TestQuaternionEigenCeresParametrization) {\n  // Initial state values.\n  Eigen::Quaterniond q(Eigen::Quaterniond::Identity().slerp(\n      0.10, Eigen::Quaterniond::FromTwoVectors(\n                Eigen::Vector3d(1, 0, 0), Eigen::Vector3d(0, 0, 1))));\n\n  Eigen::Quaterniond p(Eigen::Quaterniond::Identity().slerp(\n      0.20, Eigen::Quaterniond::FromTwoVectors(\n                Eigen::Vector3d(1, 0, 0), Eigen::Vector3d(0, 0, 1))));\n\n  Eigen::Vector3d theta(0.2, 0.3, -0.1);\n\n  // Check: (q boxplus u)\n  Eigen::Quaterniond q_rot;\n  Eigen::Quaterniond q_rot_ceres;\n  Eigen::Vector3d u_new;\n  common::eigen_quaternion_helpers::Plus(q.coeffs(), theta, &q_rot);\n\n  ceres_error_terms::EigenQuaternionParameterization\n      ceres_quaternion_eigen_param;\n\n  ceres_quaternion_eigen_param.Plus(\n      q.coeffs().data(), theta.data(), q_rot_ceres.coeffs().data());\n\n  pose::Quaternion q_rot_(q_rot);\n  pose::Quaternion q_rot_ceres_(q_rot_ceres);\n  EXPECT_NEAR_KINDR_QUATERNION(q_rot_, q_rot_ceres_, 1e-5);\n\n  // Check: p boxminus q\n  Eigen::Vector3d theta_ceres_interface;\n  common::eigen_quaternion_helpers::Minus(p, q, &theta);\n  ceres_quaternion_eigen_param.Minus(\n      p.coeffs().data(), q.coeffs().data(), theta_ceres_interface.data());\n\n  EXPECT_NEAR_EIGEN(theta, theta_ceres_interface, 1e-5);\n}\n\nTEST(QuaternionEigenParametrization, TestQuaternionEigen) {\n  // Initial state values.\n  Eigen::Quaterniond q(Eigen::Quaterniond::Identity().slerp(\n      0.10, Eigen::Quaterniond::FromTwoVectors(\n                Eigen::Vector3d(1, 0, 0), Eigen::Vector3d(0, 0, 1))));\n\n  Eigen::Quaterniond p(Eigen::Quaterniond::Identity().slerp(\n      0.20, Eigen::Quaterniond::FromTwoVectors(\n                Eigen::Vector3d(1, 0, 0), Eigen::Vector3d(0, 0, 1))));\n\n  Eigen::Vector3d theata(0.2, 0.3, -0.1);\n\n  // Check: (q boxplus theata) boxminus q = theata\n  Eigen::Quaterniond q_rot;\n  Eigen::Vector3d theta_new;\n  common::eigen_quaternion_helpers::Plus(q.coeffs(), theata, &q_rot);\n  common::eigen_quaternion_helpers::Minus(q_rot, q, &theta_new);\n\n  EXPECT_NEAR_EIGEN(theata, theta_new, 1e-5);\n\n  // Check: (q boxplus theata) boxplus -theata = q\n  Eigen::Quaterniond q_orig;\n  Eigen::Vector3d theta_neg = -theata;\n  common::eigen_quaternion_helpers::Plus(q_rot.coeffs(), theta_neg, &q_orig);\n\n  pose::Quaternion q_(q);\n  pose::Quaternion q_orig_(q_orig);\n  EXPECT_NEAR_KINDR_QUATERNION(q_, q_orig_, 1e-5);\n\n  // Check: q boxplus (p boxminus q) = p\n  Eigen::Vector3d theta_temp;\n  Eigen::Quaterniond p_orig;\n  common::eigen_quaternion_helpers::Minus(p, q, &theta_temp);\n  common::eigen_quaternion_helpers::Plus(q.coeffs(), theta_temp, &p_orig);\n\n  pose::Quaternion p_(p);\n  pose::Quaternion p_orig_(p_orig);\n  EXPECT_NEAR_KINDR_QUATERNION(p_, p_orig_, 1e-5);\n}\n\nMAPLAB_UNITTEST_ENTRYPOINT\n", "meta": {"hexsha": "7a26694304f8e87396f7b66365cfc95ca6f61c59", "size": 3158, "ext": "cc", "lang": "C++", "max_stars_repo_path": "algorithms/ceres-error-terms/test/test_quaternion_eigen_parameterization.cc", "max_stars_repo_name": "AdronTech/maplab", "max_stars_repo_head_hexsha": "1340e01466fc1c02994860723b8117daf9ad226d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1936.0, "max_stars_repo_stars_event_min_datetime": "2017-11-27T23:11:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T14:24:14.000Z", "max_issues_repo_path": "algorithms/ceres-error-terms/test/test_quaternion_eigen_parameterization.cc", "max_issues_repo_name": "AdronTech/maplab", "max_issues_repo_head_hexsha": "1340e01466fc1c02994860723b8117daf9ad226d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 353.0, "max_issues_repo_issues_event_min_datetime": "2017-11-29T18:40:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T15:53:46.000Z", "max_forks_repo_path": "algorithms/ceres-error-terms/test/test_quaternion_eigen_parameterization.cc", "max_forks_repo_name": "AdronTech/maplab", "max_forks_repo_head_hexsha": "1340e01466fc1c02994860723b8117daf9ad226d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 661.0, "max_forks_repo_forks_event_min_datetime": "2017-11-28T07:20:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T08:06:29.000Z", "avg_line_length": 34.7032967033, "max_line_length": 79, "alphanum_fraction": 0.7162761241, "num_tokens": 977, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.47929704242435045}}
{"text": "#include <iostream>\n#include <Eigen/Core>\n#include <sys/time.h>\n\n#include \"celerite.h\"\n\nusing namespace Eigen;\n\ndouble get_timestamp () {\n  struct timeval now;\n  gettimeofday (&now, NULL);\n  return double(now.tv_usec) * 1.0e-6 + double(now.tv_sec);\n}\n\ntemplate <typename T, int J_comp>\nvoid run_benchmark (int J, int N) {\n  const auto Options = J_comp == 1 ? ColMajor : RowMajor;\n  typedef Matrix<T, Dynamic, J_comp, Options> matrix;\n  typedef Matrix<T, Dynamic, 1> vector;\n\n  // Random matrices\n  srand(1234);\n  vector A(N), Y = vector::Random(N), Z, bA(N), bD(N), bY(N), bZ(N);\n  matrix U = matrix::Random(N, J), bU(N, J),\n         V0 = matrix::Random(N, J), V(N, J), bV(N, J), bW(N, J),\n         P = matrix::Random(N-1, J), bP(N-1, J);\n  Matrix<T, J_comp, J_comp, Options> S(J, J), bS(J, J);\n  Matrix<T, J_comp, 1> F(J), G(J), bF(J), bG(J);\n  S.setZero();\n\n  // Likelihood time\n  double strt, end, count = 0.0;\n\n  strt = get_timestamp();\n  do {\n    V << V0;\n    A.setConstant(10*J);\n    int flag = celerite::factor(U, P, A, V, S);\n    T ll = log(A.array()).sum();\n\n    Z = Y;\n    celerite::solve(U, P, A, V, Z, F, G);\n    ll += Y.transpose() * Z;\n\n    end = get_timestamp();\n    count += 1.0;\n  } while ((end - strt < 0.7) || (count < 3.0));\n  std::cout << sizeof(T) << \",\" << J_comp << \",\" << J << \",\" << N << \",\";\n  std::cout << ((end - strt) / count) << \",\";\n\n  // Grad time\n  strt = get_timestamp();\n  count = 0.0;\n  do {\n    bZ = Y;\n    bY = Z;\n    bD.array() = 1.0 / A.array();\n\n    bF.setZero();\n    bG.setZero();\n\n    bU.setZero();\n    bP.setZero();\n\n    celerite::solve_grad(U, P, A, V, Z, F, G, bZ, bF, bG, bU, bP, bD, bW, bY);\n\n    bS.setZero();\n    celerite::factor_grad(U, P, A, V, S, bS, bU, bP, bD, bW);\n\n    end = get_timestamp();\n    count += 1.0;\n  } while ((end - strt < 0.7) || (count < 3.0));\n\n  std::cout << ((end - strt) / count);\n  std::cout << std::endl;\n}\n\n#define RUN_BENCHMARK(J, N)      \\\n  run_benchmark<double, J>(J, N);      \\\n  run_benchmark<double, Dynamic>(J, N);\n\n#define RUN_BENCHMARKS(J)        \\\nRUN_BENCHMARK(J, 64    )         \\\nRUN_BENCHMARK(J, 128   )         \\\nRUN_BENCHMARK(J, 256   )         \\\nRUN_BENCHMARK(J, 512   )         \\\nRUN_BENCHMARK(J, 1024  )         \\\nRUN_BENCHMARK(J, 2048  )         \\\nRUN_BENCHMARK(J, 4096  )         \\\nRUN_BENCHMARK(J, 8192  )         \\\nRUN_BENCHMARK(J, 16384 )         \\\nRUN_BENCHMARK(J, 32768 )         \\\nRUN_BENCHMARK(J, 65536 )         \\\nRUN_BENCHMARK(J, 131072)         \\\nRUN_BENCHMARK(J, 262144)\n\n\nint main ()\n{\n  std::cout << \"size,J_comp,J,N,time,grad_time\\n\";\n  //RUN_BENCHMARKS(1);\n  RUN_BENCHMARKS(2);\n  RUN_BENCHMARKS(4);\n  RUN_BENCHMARKS(8);\n  RUN_BENCHMARKS(16);\n  RUN_BENCHMARKS(32);\n  RUN_BENCHMARKS(64);\n  RUN_BENCHMARKS(128);\n\n  return 0;\n}\n", "meta": {"hexsha": "0fc48cb44bc689e6601aacd0a341c5eb7c5359a5", "size": 2740, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/benchmark.cc", "max_stars_repo_name": "dfm/celerite-grad", "max_stars_repo_head_hexsha": "5c7e8aa38ba33a37d9a9ef9ea66e54bd24dd119b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-09-27T22:46:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-03T10:00:55.000Z", "max_issues_repo_path": "src/benchmark.cc", "max_issues_repo_name": "dfm/celerite-grad", "max_issues_repo_head_hexsha": "5c7e8aa38ba33a37d9a9ef9ea66e54bd24dd119b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/benchmark.cc", "max_forks_repo_name": "dfm/celerite-grad", "max_forks_repo_head_hexsha": "5c7e8aa38ba33a37d9a9ef9ea66e54bd24dd119b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-01-26T02:54:24.000Z", "max_forks_repo_forks_event_max_datetime": "2018-05-19T15:35:55.000Z", "avg_line_length": 24.4642857143, "max_line_length": 78, "alphanum_fraction": 0.5525547445, "num_tokens": 964, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4792622659212648}}
{"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_ISQRT_HPP_INCLUDED\n#define BOOST_SIMD_TOOLBOX_ARITHMETIC_FUNCTIONS_SIMD_COMMON_ISQRT_HPP_INCLUDED\n\n#include <boost/simd/toolbox/arithmetic/functions/isqrt.hpp>\n#include <boost/simd/include/functions/simd/sqrt.hpp>\n#include <boost/simd/include/functions/simd/toint.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::isqrt_, tag::cpu_,\n                       (A0)(X),\n                       ((simd_< floating_<A0>, X >))\n                      )\n  {\n    typedef typename dispatch::meta::as_integer<A0>::type result_type;\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(1)\n    {\n      return boost::simd::itrunc(boost::simd::sqrt(a0));\n    }\n  };\n} } }\n\n#endif\n", "meta": {"hexsha": "03d5b15a6f2b8ebea4a8ecb5bfb11973d638af63", "size": 1314, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/arithmetic/include/boost/simd/toolbox/arithmetic/functions/simd/common/isqrt.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/isqrt.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/isqrt.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.8181818182, "max_line_length": 80, "alphanum_fraction": 0.5905631659, "num_tokens": 297, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4792622659212648}}
{"text": "// Copyright (c) 2017, Lawrence Livermore National Security, LLC and\n// UT-Battelle, LLC.\n// Produced at the Lawrence Livermore National Laboratory and the Oak Ridge\n// National Laboratory.\n// LLNL-CODE-743438\n// All rights reserved.\n// This file is part of MGmol. For details, see https://github.com/llnl/mgmol.\n// Please also read this link https://github.com/llnl/mgmol/LICENSE\n\n#include \"random.h\"\n\n#include <algorithm>\n#include <cstdlib>\n#include <iostream>\n#include <vector>\n\n#include <boost/random/linear_congruential.hpp>\n#include <boost/random/uniform_real.hpp>\n#include <boost/random/variate_generator.hpp>\n\n/* Generate random numbers between (a, b] */\ndouble generate_rand(const int a, const int b)\n{\n    double val = (b - a) * (double)rand() / (double)RAND_MAX + a;\n    return val;\n}\n\n/* Generate random numbers between (0, 1] */\ndouble generate_rand_num()\n{\n    double val = (double)rand() / (double)RAND_MAX;\n    return val;\n}\n\n/* Generate a vector of random numbers between (a, b] */\nstd::vector<double> generate_rand(const int n, const int a, const int b)\n{\n    std::vector<double> vec(n);\n    for (int i = 0; i < n; i++)\n        vec[i] = generate_rand(a, b);\n\n    return vec;\n}\nstd::vector<double> generate_rand(const int n)\n{\n    std::vector<double> vec(n);\n    std::generate(vec.begin(), vec.end(), &generate_rand_num);\n\n    return vec;\n}\n\ntemplate <typename DataType>\nvoid generateRandomData(\n    std::vector<DataType>& data, const DataType minv, const DataType maxv)\n{\n    typedef boost::minstd_rand rng_type;\n    typedef boost::uniform_real<> distribution_type;\n\n    int seed = 113;\n    rng_type rng(seed);\n    distribution_type nd(minv, maxv);\n    boost::variate_generator<rng_type, distribution_type> gen(rng, nd);\n\n    for (auto& d : data)\n        d = gen();\n}\n\ntemplate void generateRandomData(\n    std::vector<double>& data, const double minv, const double maxv);\ntemplate void generateRandomData(\n    std::vector<float>& data, const float minv, const float maxv);\n", "meta": {"hexsha": "21fe8fdf94fc6379d2bcbcbed4662201e3c36de0", "size": 1992, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/tools/random.cc", "max_stars_repo_name": "jeanlucf22/mgmol", "max_stars_repo_head_hexsha": "4e79bc32c14c8a47ae18ad0659ea740719c8b77f", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL", "FSFAP"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2018-12-29T03:33:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-08T12:52:27.000Z", "max_issues_repo_path": "src/tools/random.cc", "max_issues_repo_name": "jeanlucf22/mgmol", "max_issues_repo_head_hexsha": "4e79bc32c14c8a47ae18ad0659ea740719c8b77f", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL", "FSFAP"], "max_issues_count": 121.0, "max_issues_repo_issues_event_min_datetime": "2018-12-19T02:38:21.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-20T16:29:24.000Z", "max_forks_repo_path": "src/tools/random.cc", "max_forks_repo_name": "jeanlucf22/mgmol", "max_forks_repo_head_hexsha": "4e79bc32c14c8a47ae18ad0659ea740719c8b77f", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL", "FSFAP"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2019-02-17T05:28:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T05:24:11.000Z", "avg_line_length": 27.6666666667, "max_line_length": 78, "alphanum_fraction": 0.6957831325, "num_tokens": 511, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191460821871, "lm_q2_score": 0.6757645944891558, "lm_q1q2_score": 0.4791300357372767}}
{"text": "#include \"jacobiantest.hpp\"\n#include <kinfam_io.hpp>\n#include <Eigen/Core>\n\nCPPUNIT_TEST_SUITE_REGISTRATION(JacobianTest);\n\nusing namespace KDL;\n\nvoid JacobianTest::setUp(){}\nvoid JacobianTest::tearDown(){}\n\nvoid JacobianTest::TestChangeRefPoint(){\n    //Create a random jacobian\n    Jacobian j1(5);\n    j1.data.setRandom();\n    //Create a random Vector\n    Vector p;\n    random(p);\n    \n    Jacobian j2(5);\n    CPPUNIT_ASSERT(changeRefPoint(j1,p,j2));\n    CPPUNIT_ASSERT(j1!=j2);\n    Jacobian j3(4);\n    CPPUNIT_ASSERT(!changeRefPoint(j1,p,j3));\n    j3.resize(5);\n    CPPUNIT_ASSERT(changeRefPoint(j2,-p,j3));\n    CPPUNIT_ASSERT_EQUAL(j1,j3);\n\n}\n\nvoid JacobianTest::TestChangeRefFrame(){\n    //Create a random jacobian\n    Jacobian j1(5);\n    j1.data.setRandom();\n    //Create a random frame\n    Frame f;\n    random(f);\n    \n    Jacobian j2(5);\n    CPPUNIT_ASSERT(changeRefFrame(j1,f,j2));\n    CPPUNIT_ASSERT(j1!=j2);\n    Jacobian j3(4);\n    CPPUNIT_ASSERT(!changeRefFrame(j1,f,j3));\n    j3.resize(5);\n    CPPUNIT_ASSERT(changeRefFrame(j2,f.Inverse(),j3));\n    CPPUNIT_ASSERT_EQUAL(j1,j3);\n}\n\nvoid JacobianTest::TestChangeBase(){\n    //Create a random jacobian\n    Jacobian j1(5);\n    j1.data.setRandom();\n    //Create a random rotation\n    Rotation r;\n    random(r);\n    \n    Jacobian j2(5);\n    CPPUNIT_ASSERT(changeBase(j1,r,j2));\n    CPPUNIT_ASSERT(j1!=j2);\n    Jacobian j3(4);\n    CPPUNIT_ASSERT(!changeBase(j1,r,j3));\n    j3.resize(5);\n    CPPUNIT_ASSERT(changeBase(j2,r.Inverse(),j3));\n    CPPUNIT_ASSERT_EQUAL(j1,j3);\n}\n\nvoid JacobianTest::TestConstructor(){\n    //Create an empty Jacobian\n    Jacobian j1(2);\n    //Get size\n    CPPUNIT_ASSERT_EQUAL(j1.rows(),(unsigned int)6);\n    CPPUNIT_ASSERT_EQUAL(j1.columns(),(unsigned int)2);\n    //Create a second Jacobian from empty\n    Jacobian j2(j1);\n    //Get size\n    CPPUNIT_ASSERT_EQUAL(j2.rows(),(unsigned int)6);\n    CPPUNIT_ASSERT_EQUAL(j2.columns(),(unsigned int)2);\n    Jacobian j3=j1;\n    //Get size\n    CPPUNIT_ASSERT_EQUAL(j3.rows(),(unsigned int)6);\n    CPPUNIT_ASSERT_EQUAL(j3.columns(),(unsigned int)2);\n\n    //Test resize\n    j1.resize(5);\n    //Get size\n    CPPUNIT_ASSERT_EQUAL(j1.rows(),(unsigned int)6);\n    CPPUNIT_ASSERT_EQUAL(j1.columns(),(unsigned int)5);\n\n    j2=j1;\n    //Get size\n    CPPUNIT_ASSERT_EQUAL(j2.rows(),(unsigned int)6);\n    CPPUNIT_ASSERT_EQUAL(j2.columns(),(unsigned int)5);\n}\n\nvoid JacobianTest::TestGetSetColumn(){}\n\n\n", "meta": {"hexsha": "bf58d38d2311418e1c5a64e4e698b9ddb7ffb78b", "size": 2416, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/orocos_kinematics_dynamics/orocos_kdl/tests/jacobiantest.cpp", "max_stars_repo_name": "matchRos/simulation_multirobots", "max_stars_repo_head_hexsha": "286c5add84d521ad371b2c8961dea872c34e7da2", "max_stars_repo_licenses": ["BSD-2-Clause"], "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": "src/orocos_kinematics_dynamics/orocos_kdl/tests/jacobiantest.cpp", "max_issues_repo_name": "matchRos/simulation_multirobots", "max_issues_repo_head_hexsha": "286c5add84d521ad371b2c8961dea872c34e7da2", "max_issues_repo_licenses": ["BSD-2-Clause"], "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": "src/orocos_kinematics_dynamics/orocos_kdl/tests/jacobiantest.cpp", "max_forks_repo_name": "matchRos/simulation_multirobots", "max_forks_repo_head_hexsha": "286c5add84d521ad371b2c8961dea872c34e7da2", "max_forks_repo_licenses": ["BSD-2-Clause"], "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": 24.6530612245, "max_line_length": 55, "alphanum_fraction": 0.6713576159, "num_tokens": 682, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.4791300320571542}}
{"text": "\n#include <iostream>\n#include <algorithm>\n#include <cmath>        // abs() for float, and fabs()\n#include <math.h>       // pow()\n#include <random>\n#include <climits>\n\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/lu.hpp> // row(), column()\n\nusing namespace boost::numeric::ublas;\n\n#define print(var) \\\n  std::cout<<#var\" = \"<<(var)<<std::endl;\n#define printstr(str) \\\n  std::cout<<str<<std::endl;\n#define printLine() \\\n  std::cout<<\"============================\"<<std::endl;\n", "meta": {"hexsha": "c2f63014573ec0f6e7dc22dc97eb7b5ca1148cc3", "size": 582, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/pso.hpp", "max_stars_repo_name": "keit0222/various-pso-examples", "max_stars_repo_head_hexsha": "2a680ae8c66c0c4fb92e96cbc0e131231aa343ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-02-19T09:39:47.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-19T09:39:47.000Z", "max_issues_repo_path": "boost/pso.hpp", "max_issues_repo_name": "keit0222/various-pso-examples", "max_issues_repo_head_hexsha": "2a680ae8c66c0c4fb92e96cbc0e131231aa343ae", "max_issues_repo_licenses": ["MIT"], "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/pso.hpp", "max_forks_repo_name": "keit0222/various-pso-examples", "max_forks_repo_head_hexsha": "2a680ae8c66c0c4fb92e96cbc0e131231aa343ae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-02T14:38:08.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-02T14:38:08.000Z", "avg_line_length": 26.4545454545, "max_line_length": 56, "alphanum_fraction": 0.6254295533, "num_tokens": 157, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191214879992, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.47913002374721336}}
{"text": "#include \"testsuite.h\"\n#include <blitz/array.h>\n\n\nBZ_USING_NAMESPACE(blitz)\n\nint main() {\n  Array<int, 2> A(4);\n  Array<int, 1> B(4), C(4);\n\n  firstIndex i;\n  secondIndex j;\n\n  A = i+j;\n\n  B = max(A,j);\n\n  C = 3, 4, 5, 6;\n  BZTEST(count(B == C) == 4);\n\n  return 0;\n}\n\n\n", "meta": {"hexsha": "429e36cd8bf493364de30dc5a11d3dbaf42ce91d", "size": 269, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depspawn-blitz-0.10/testsuite/derrick-bass-3.cpp", "max_stars_repo_name": "fraguela/depspawn", "max_stars_repo_head_hexsha": "b5760f4c0d38a1b245ee5274e2ccc5c5fe2d3d45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-04-12T11:05:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T11:10:27.000Z", "max_issues_repo_path": "ibtk/third_party/blitz-0.10/testsuite/derrick-bass-3.cpp", "max_issues_repo_name": "MSV-Project/IBAMR", "max_issues_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ibtk/third_party/blitz-0.10/testsuite/derrick-bass-3.cpp", "max_forks_repo_name": "MSV-Project/IBAMR", "max_forks_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 10.76, "max_line_length": 29, "alphanum_fraction": 0.5464684015, "num_tokens": 108, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7090191214879991, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.4791300237472133}}
{"text": "#pragma once\n//standard include\n#include <math.h>\n#include <iostream>\n\n//opencv include\n#include \"opencv2/imgproc/imgproc.hpp\"\n#include \"opencv2/core/core.hpp\"\n#include <boost/circular_buffer.hpp>\n\n#include \"track3d.hpp\"\n\nstruct DepthInfo\n{\n\tfloat depth;\n\tbool  error;\n};\n\n//this contains all the info we need to decide between goals once we are certain if it is a goal\nstruct GoalInfo\n{\n\tcv::Point3f pos;\n\tfloat confidence;\n\tfloat distance;\n\tfloat angle;\n\tcv::Rect rect;\n\tsize_t contour_index;\n\tbool depth_error;\n\tcv::Point com;\n\tcv::Rect br;\n\tcv::RotatedRect rtRect;\n\tcv::Point2f lineStart;\n\tcv::Point2f lineEnd;\n};\n\n//This contains all the necessary info for a goal\nstruct GoalFound\n{\n\tcv::Point3f pos;\n\tcv::Point3f left_pos;\n\tcv::Point3f right_pos;\n\tfloat distance;\n\tfloat angle;\n\tfloat confidence;\n\tsize_t left_contour_index;\n\tsize_t right_contour_index;\n\tcv::Rect left_rect;\n\tcv::Rect right_rect;\n\tcv::RotatedRect left_rotated_rect;\n\tcv::RotatedRect right_rotated_rect;\n};\n\n\nclass GoalDetector\n{\n\tpublic:\n\t\tGoalDetector(const cv::Point2f &fov_size, const cv::Size &frame_size, bool gui = false);\n\n\t\tstd::vector< GoalFound > return_found(void) const;\n\n\t\tvoid drawOnFrame(cv::Mat &image,const std::vector< std::vector< cv::Point>> &contours) const;\n\n\t\t//These are the three functions to call to run GoalDetector\n\t\t//they fill in _contours, _infos, _depth_mins, etc\n\t\tvoid clear(void);\n\n\t\t//If your objectypes have the same width it's safe to run\n\t\t//getContours and computeConfidences with different types\n\t\tvoid findBoilers(const cv::Mat& image, const cv::Mat& depth);\n\t\tconst std::vector< std::vector< cv::Point > > getContours(const cv::Mat& image);\n\n\t\tbool Valid(void) const;\n\t\tvoid setCameraAngle(double camera_angle);\n\t\tvoid setBlueScale(double blue_scale);\n\t\tvoid setRedScale(double red_scale);\n\t\tvoid setOtsuThreshold(int otsu_threshold);\n\t\tvoid setMinConfidence(double min_valid_confidence);\n\n\tprivate:\n\n\t\tcv::Point2f _fov_size;\n\t\tcv::Size    _frame_size;\n\n\t\t// Save detection info\n\t\tbool        _isValid;\n\t\tstd::vector< GoalFound > _return_found;\n\t\tfloat       _min_valid_confidence;\n\n\t\tint         _otsu_threshold;\n\t\tint         _blue_scale;\n\t\tint         _red_scale;\n\n\t\tint         _camera_angle;\n\n\t\tfloat createConfidence(float expectedVal, float expectedStddev, float actualVal);\n\t\tfloat distanceUsingFOV(ObjectType _goal_shape, const cv::Rect &rect) const;\n\t\tfloat distanceUsingFixedHeight(const cv::Rect &rect,const cv::Point &center, float expected_delta_height) const;\n\t\tbool generateThresholdAddSubtract(const cv::Mat& imageIn, cv::Mat& imageOut);\n\t\tvoid isValid();\n\t\tconst std::vector<DepthInfo> getDepths(const cv::Mat &depth, const std::vector< std::vector< cv::Point > > &contours, const ObjectNum &objtype, float expected_height);\n\t\tconst std::vector< GoalInfo > getInfo(const std::vector< std::vector< cv::Point > > &contours, const std::vector<DepthInfo> &depth_maxs, ObjectNum objtype);\n};\n\n", "meta": {"hexsha": "52bf4340718f7d1699ac724f5bb2ef6a222e99a0", "size": 2922, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "common/GoalDetector.hpp", "max_stars_repo_name": "mattwalstra/2019RobotCode", "max_stars_repo_head_hexsha": "44f2543876b95428a68dc84820f931571244e49d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-01-15T16:37:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-15T16:39:31.000Z", "max_issues_repo_path": "common/GoalDetector.hpp", "max_issues_repo_name": "mattwalstra/2019RobotCode", "max_issues_repo_head_hexsha": "44f2543876b95428a68dc84820f931571244e49d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-08-30T00:06:15.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-29T17:02:18.000Z", "max_forks_repo_path": "common/GoalDetector.hpp", "max_forks_repo_name": "mattwalstra/2019RobotCode", "max_forks_repo_head_hexsha": "44f2543876b95428a68dc84820f931571244e49d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-10-29T01:13:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T21:53:06.000Z", "avg_line_length": 28.0961538462, "max_line_length": 169, "alphanum_fraction": 0.7378507871, "num_tokens": 773, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186787341014, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.47906241827737733}}
{"text": "/**\n * @file tests/mean_shift_test.cpp\n * @author Shangtong Zhang\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\n#include <mlpack/core.hpp>\n\n#include <mlpack/methods/mean_shift/mean_shift.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n\nusing namespace mlpack;\nusing namespace mlpack::meanshift;\nusing namespace mlpack::distribution;\n\nBOOST_AUTO_TEST_SUITE(MeanShiftTest);\n\n// Generate dataset; written transposed because it's easier to read.\narma::mat meanShiftData(\"  0.0   0.0;\" // Class 1.\n                     \"  0.3   0.4;\"\n                     \"  0.1   0.0;\"\n                     \"  0.1   0.3;\"\n                     \" -0.2  -0.2;\"\n                     \" -0.1   0.3;\"\n                     \" -0.4   0.1;\"\n                     \"  0.2  -0.1;\"\n                     \"  0.3   0.0;\"\n                     \" -0.3  -0.3;\"\n                     \"  0.1  -0.1;\"\n                     \"  0.2  -0.3;\"\n                     \" -0.3   0.2;\"\n                     \" 10.0  10.0;\" // Class 2.\n                     \" 10.1   9.9;\"\n                     \"  9.9  10.0;\"\n                     \" 10.2   9.7;\"\n                     \" 10.2   9.8;\"\n                     \"  9.7  10.3;\"\n                     \"  9.9  10.1;\"\n                     \"-10.0   5.0;\" // Class 3.\n                     \" -9.8   5.1;\"\n                     \" -9.9   4.9;\"\n                     \"-10.0   4.9;\"\n                     \"-10.2   5.2;\"\n                     \"-10.1   5.1;\"\n                     \"-10.3   5.3;\"\n                     \"-10.0   4.8;\"\n                     \" -9.6   5.0;\"\n                     \" -9.8   5.1;\");\n\n\n/**\n * 30-point 3-class test case for Mean Shift.\n */\nBOOST_AUTO_TEST_CASE(MeanShiftSimpleTest)\n{\n  MeanShift<> meanShift;\n\n  arma::Row<size_t> assignments;\n  arma::mat centroids;\n  meanShift.Cluster((arma::mat) trans(meanShiftData), assignments, centroids);\n\n  // Now make sure we got it all right.  There is no restriction on how the\n  // clusters are ordered, so we have to be careful about that.\n  size_t firstClass = assignments(0);\n\n  for (size_t i = 1; i < 13; ++i)\n    BOOST_REQUIRE_EQUAL(assignments(i), firstClass);\n\n  size_t secondClass = assignments(13);\n\n  // To ensure that class 1 != class 2.\n  BOOST_REQUIRE_NE(firstClass, secondClass);\n\n  for (size_t i = 13; i < 20; ++i)\n    BOOST_REQUIRE_EQUAL(assignments(i), secondClass);\n\n  size_t thirdClass = assignments(20);\n\n  // To ensure that this is the third class which we haven't seen yet.\n  BOOST_REQUIRE_NE(firstClass, thirdClass);\n  BOOST_REQUIRE_NE(secondClass, thirdClass);\n\n  for (size_t i = 20; i < 30; ++i)\n    BOOST_REQUIRE_EQUAL(assignments(i), thirdClass);\n}\n\n// Generate samples from four Gaussians, and make sure mean shift nearly\n// recovers those four centers.\nBOOST_AUTO_TEST_CASE(GaussianClustering)\n{\n  GaussianDistribution g1(\"0.0 0.0 0.0\", arma::eye<arma::mat>(3, 3));\n  GaussianDistribution g2(\"5.0 5.0 5.0\", 2 * arma::eye<arma::mat>(3, 3));\n  GaussianDistribution g3(\"-3.0 3.0 -1.0\", arma::eye<arma::mat>(3, 3));\n  GaussianDistribution g4(\"6.0 -2.0 -2.0\", 3 * arma::eye<arma::mat>(3, 3));\n\n  // We may need to run this multiple times, because sometimes it may converge\n  // to the wrong number of clusters.\n  bool success = false;\n  for (size_t trial = 0; trial < 4; ++trial)\n  {\n    arma::mat dataset(3, 4000);\n    for (size_t i = 0; i < 1000; ++i)\n      dataset.col(i) = g1.Random();\n    for (size_t i = 1000; i < 2000; ++i)\n      dataset.col(i) = g2.Random();\n    for (size_t i = 2000; i < 3000; ++i)\n      dataset.col(i) = g3.Random();\n    for (size_t i = 3000; i < 4000; ++i)\n      dataset.col(i) = g4.Random();\n\n    // Now that the dataset is generated, run mean shift.  Pre-set radius.\n    MeanShift<> meanShift(2.9);\n\n    arma::Row<size_t> assignments;\n    arma::mat centroids;\n    meanShift.Cluster(dataset, assignments, centroids);\n\n    success = (centroids.n_cols == 4);\n    if (!success)\n      continue;\n    success = (centroids.n_rows == 3);\n    if (!success)\n      continue;\n\n    // Check that each centroid is close to only one mean.\n    arma::vec centroidDistances(4);\n    arma::uvec minIndices(4);\n    for (size_t i = 0; i < 4; ++i)\n    {\n      centroidDistances(0) = metric::EuclideanDistance::Evaluate(g1.Mean(),\n          centroids.col(i));\n      centroidDistances(1) = metric::EuclideanDistance::Evaluate(g2.Mean(),\n          centroids.col(i));\n      centroidDistances(2) = metric::EuclideanDistance::Evaluate(g3.Mean(),\n          centroids.col(i));\n      centroidDistances(3) = metric::EuclideanDistance::Evaluate(g4.Mean(),\n          centroids.col(i));\n\n      // Are we near a centroid of a Gaussian?\n      const double minVal = centroidDistances.min(minIndices[i]);\n      success = (std::abs(minVal) <= 0.65);\n      if (!success)\n        break;\n    }\n\n    // Ensure each centroid corresponds to a different Gaussian.\n    bool innerSuccess = true;\n    for (size_t i = 0; i < 4; ++i)\n      for (size_t j = i + 1; j < 4; ++j)\n        innerSuccess &= (minIndices[i] != minIndices[j]);\n\n    if (innerSuccess)\n      success = true;\n\n    if (success)\n      break;\n  }\n\n  BOOST_REQUIRE_EQUAL(success, true);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "818602f632bfbd95fb81262b9d0e955433da807e", "size": 5376, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/mean_shift_test.cpp", "max_stars_repo_name": "tejasvi/mlpack", "max_stars_repo_head_hexsha": "9bc159c52d13139834cc89e8669fe65fc97fa107", "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/tests/mean_shift_test.cpp", "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/tests/mean_shift_test.cpp", "max_forks_repo_name": "R-Aravind/mlpack", "max_forks_repo_head_hexsha": "99d11a9b4d379885cf7f8160d8c71fb792fa1bbc", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-09-17T21:33:59.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-17T21:33:59.000Z", "avg_line_length": 31.8106508876, "max_line_length": 78, "alphanum_fraction": 0.5563616071, "num_tokens": 1587, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186787341014, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.47906241827737733}}
{"text": "//Author: Dr. Shantanu Shahane\n#include <stdio.h>\n#include <math.h>\n#include <stdlib.h>\n#include <time.h>\n#include <float.h>\n#include <string.h>\n#include <iostream>\n#include <vector>\n#include <Eigen/Dense>\n#include <unsupported/Eigen/SparseExtra>\n#include <Eigen/SparseLU>\n#include <Eigen/OrderingMethods>\n#include <Eigen/Core>\n#include \"_hypre_utilities.h\"\n#include \"HYPRE_krylov.h\"\n#include \"HYPRE.h\"\n#include \"HYPRE_parcsr_ls.h\"\n#include \"general_functions.hpp\"\n#include \"class.hpp\"\n\nSEMI_IMPLICIT_SPLIT_SOLVER::SEMI_IMPLICIT_SPLIT_SOLVER(POINTS &points, CLOUD &cloud, PARAMETERS &parameters, vector<bool> &u_dirichlet_flag1, vector<bool> &v_dirichlet_flag1, vector<bool> &p_dirichlet_flag1, int n_outer_iter1, double iterative_tolerance1, int precond_freq_it1)\n{\n    u_dirichlet_flag = u_dirichlet_flag1, v_dirichlet_flag = v_dirichlet_flag1, p_dirichlet_flag = p_dirichlet_flag1;\n    n_outer_iter = n_outer_iter1, iterative_tolerance = iterative_tolerance1, precond_freq_it = precond_freq_it1;\n    check_bc(points, parameters);\n    clock_t clock_t1 = clock(), clock_t2 = clock();\n    solver_p.init(points, cloud, parameters, p_dirichlet_flag, 0.0, 0.0, 1.0, true); //BC for p_prime is identical to BC of p_new\n    parameters.factoring_timer = ((double)(clock() - clock_t1)) / CLOCKS_PER_SEC;\n\n    zero_vector = Eigen::VectorXd::Zero(points.nv);\n    zero_vector_1 = Eigen::VectorXd::Zero(points.nv + 1);\n    p_bc_full_neumann = true;\n    for (int iv = 0; iv < points.nv; iv++)\n        if (points.boundary_flag[iv] && p_dirichlet_flag[iv])\n        { //boundary point found with dirichlet BC\n            p_bc_full_neumann = false;\n            break;\n        }\n\n    if (p_bc_full_neumann)\n        p_source = zero_vector_1, p_prime = zero_vector_1; //this is full Neumann for pressure\n    else\n        p_source = zero_vector, p_prime = zero_vector;\n    u_source = zero_vector, v_source = zero_vector;\n    u_old_old = zero_vector, v_old_old = zero_vector;\n    u_prime = zero_vector, v_prime = zero_vector;\n    u_iter_old = zero_vector, v_iter_old = zero_vector;\n    normal_mom_x = zero_vector, normal_mom_y = zero_vector;\n}\n\nvoid SEMI_IMPLICIT_SPLIT_SOLVER::check_bc(POINTS &points, PARAMETERS &parameters)\n{\n    int u_dirichlet_flag_sum = accumulate(u_dirichlet_flag.begin(), u_dirichlet_flag.end(), 0);\n    if (u_dirichlet_flag_sum == 0)\n    {\n        printf(\"\\n\\nERROR from SEMI_IMPLICIT_SPLIT_SOLVER::check_bc Setting u_dirichlet_flag to full Neumann BC is not permitted; sum of u_dirichlet_flag: %i\\n\\n\", u_dirichlet_flag_sum);\n        throw bad_exception();\n    }\n    int v_dirichlet_flag_sum = accumulate(v_dirichlet_flag.begin(), v_dirichlet_flag.end(), 0);\n    if (v_dirichlet_flag_sum == 0)\n    {\n        printf(\"\\n\\nERROR from FRACTIONASEMI_IMPLICIT_SPLIT_SOLVERL_STEP_1::check_bc Setting v_dirichlet_flag to full Neumann BC is not permitted; sum of v_dirichlet_flag: %i\\n\\n\", v_dirichlet_flag_sum);\n        throw bad_exception();\n    }\n    if (parameters.rho < 0 || parameters.mu < 0)\n    {\n        printf(\"\\n\\nERROR from SEMI_IMPLICIT_SPLIT_SOLVER::check_bc Some parameters are not set; parameters.rho: %g, parameters.mu: %g\\n\\n\", parameters.rho, parameters.mu);\n        throw bad_exception();\n    }\n}\n\nvoid SEMI_IMPLICIT_SPLIT_SOLVER::calc_vel(POINTS &points, PARAMETERS &parameters, Eigen::VectorXd &u_new, Eigen::VectorXd &v_new, Eigen::VectorXd &p_new, Eigen::VectorXd &u_old, Eigen::VectorXd &v_old, Eigen::VectorXd &p_old, Eigen::VectorXd &body_force_x, Eigen::VectorXd &body_force_y)\n{\n    if (it == 0)\n    { //BDF1: implicit Euler\n        u_source = ((parameters.rho / parameters.dt) * u_old) - (points.grad_x_matrix_EIGEN_internal * p_new.head(points.nv)) + body_force_x;\n        v_source = ((parameters.rho / parameters.dt) * v_old) - (points.grad_y_matrix_EIGEN_internal * p_new.head(points.nv)) + body_force_y;\n    }\n    else\n    { //BDF2\n        u_source = -((bdf2_alpha_2 * parameters.rho / parameters.dt) * u_old) - ((bdf2_alpha_3 * parameters.rho / parameters.dt) * u_old_old) - (points.grad_x_matrix_EIGEN_internal * p_new.head(points.nv)) + body_force_x;\n        v_source = -((bdf2_alpha_2 * parameters.rho / parameters.dt) * v_old) - ((bdf2_alpha_3 * parameters.rho / parameters.dt) * v_old_old) - (points.grad_y_matrix_EIGEN_internal * p_new.head(points.nv)) + body_force_y;\n    }\n\n    for (int iv = 0; iv < points.nv; iv++)\n        if (points.boundary_flag[iv])\n        { //retain boundary condition from \"_old\"\n            if (u_dirichlet_flag[iv])\n                u_source[iv] = u_old[iv];\n            else\n                u_source[iv] = 0.0;\n            if (v_dirichlet_flag[iv])\n                v_source[iv] = v_old[iv];\n            else\n                v_source[iv] = 0.0;\n        }\n    u_new = solver_eigen_u.solveWithGuess(u_source, u_new);\n    v_new = solver_eigen_v.solveWithGuess(v_source, v_new);\n}\n\nvoid SEMI_IMPLICIT_SPLIT_SOLVER::calc_vel(POINTS &points, PARAMETERS &parameters, Eigen::VectorXd &u_new, Eigen::VectorXd &v_new, Eigen::VectorXd &p_new, Eigen::VectorXd &u_old, Eigen::VectorXd &v_old, Eigen::VectorXd &p_old)\n{\n    if (it == 0)\n    { //BDF1: implicit Euler\n        u_source = ((parameters.rho / parameters.dt) * u_old) - (points.grad_x_matrix_EIGEN_internal * p_new.head(points.nv));\n        v_source = ((parameters.rho / parameters.dt) * v_old) - (points.grad_y_matrix_EIGEN_internal * p_new.head(points.nv));\n    }\n    else\n    { //BDF2\n        u_source = -((bdf2_alpha_2 * parameters.rho / parameters.dt) * u_old) - ((bdf2_alpha_3 * parameters.rho / parameters.dt) * u_old_old) - (points.grad_x_matrix_EIGEN_internal * p_new.head(points.nv));\n        v_source = -((bdf2_alpha_2 * parameters.rho / parameters.dt) * v_old) - ((bdf2_alpha_3 * parameters.rho / parameters.dt) * v_old_old) - (points.grad_y_matrix_EIGEN_internal * p_new.head(points.nv));\n    }\n\n    for (int iv = 0; iv < points.nv; iv++)\n        if (points.boundary_flag[iv])\n        { //retain boundary condition from \"_old\"\n            if (u_dirichlet_flag[iv])\n                u_source[iv] = u_old[iv];\n            else\n                u_source[iv] = 0.0;\n            if (v_dirichlet_flag[iv])\n                v_source[iv] = v_old[iv];\n            else\n                v_source[iv] = 0.0;\n        }\n    u_new = solver_eigen_u.solveWithGuess(u_source, u_new);\n    v_new = solver_eigen_v.solveWithGuess(v_source, v_new);\n}\n\nvoid SEMI_IMPLICIT_SPLIT_SOLVER::calc_pressure(POINTS &points, CLOUD &cloud, PARAMETERS &parameters, Eigen::VectorXd &u_new, Eigen::VectorXd &v_new, Eigen::VectorXd &p_new, Eigen::VectorXd &u_old, Eigen::VectorXd &v_old, Eigen::VectorXd &p_old)\n{\n    if (p_bc_full_neumann)\n        p_source = zero_vector_1; //this is full Neumann for pressure\n    else\n        p_source = zero_vector;\n    if (it == 0) //BDF1: implicit Euler\n        p_source.head(points.nv) = ((points.grad_x_matrix_EIGEN_internal * u_new) + (points.grad_y_matrix_EIGEN_internal * v_new)) * (parameters.rho / parameters.dt);\n    else\n        p_source.head(points.nv) = ((points.grad_x_matrix_EIGEN_internal * u_new) + (points.grad_y_matrix_EIGEN_internal * v_new)) * (bdf2_alpha_1 * parameters.rho / parameters.dt);\n    //BC for p_prime is identical to BC of p_new\n    //p_source of p_prime is zero for both dirichlet and neumann for p_new\n    if (p_bc_full_neumann) //this is full Neumann for pressure\n        solver_p.general_solve(points, parameters, p_prime, zero_vector_1, p_source);\n    else\n        solver_p.general_solve(points, parameters, p_prime, zero_vector, p_source);\n    p_new = p_new + p_prime;\n\n    normal_mom_x = zero_vector, normal_mom_y = zero_vector;\n    if (it == 0)\n    { //BDF1: implicit Euler\n        normal_mom_x = -parameters.rho * (u_new.cwiseProduct(points.grad_x_matrix_EIGEN_boundary * u_new) + v_new.cwiseProduct(points.grad_y_matrix_EIGEN_boundary * u_new)) + parameters.mu * (points.laplacian_matrix_EIGEN_boundary * u_new) - (parameters.rho / parameters.dt) * (u_new - u_old);\n        normal_mom_y = -parameters.rho * (u_new.cwiseProduct(points.grad_x_matrix_EIGEN_boundary * v_new) + v_new.cwiseProduct(points.grad_y_matrix_EIGEN_boundary * v_new)) + parameters.mu * (points.laplacian_matrix_EIGEN_boundary * v_new) - (parameters.rho / parameters.dt) * (v_new - v_old);\n    }\n    else\n    {\n        normal_mom_x = -parameters.rho * (u_new.cwiseProduct(points.grad_x_matrix_EIGEN_boundary * u_new) + v_new.cwiseProduct(points.grad_y_matrix_EIGEN_boundary * u_new)) + parameters.mu * (points.laplacian_matrix_EIGEN_boundary * u_new) - (parameters.rho / parameters.dt) * ((bdf2_alpha_1 * u_new) + (bdf2_alpha_2 * u_old) + (bdf2_alpha_3 * u_old_old));\n        normal_mom_y = -parameters.rho * (u_new.cwiseProduct(points.grad_x_matrix_EIGEN_boundary * v_new) + v_new.cwiseProduct(points.grad_y_matrix_EIGEN_boundary * v_new)) + parameters.mu * (points.laplacian_matrix_EIGEN_boundary * v_new) - (parameters.rho / parameters.dt) * ((bdf2_alpha_1 * v_new) + (bdf2_alpha_2 * v_old) + (bdf2_alpha_3 * v_old_old));\n    }\n\n    double rhs, diag_coeff, off_diag_coeff;\n    int dim = parameters.dimension, ivnb;\n\n    for (int iv = 0; iv < points.nv; iv++)\n    { //set boundary condition\n        if (points.boundary_flag[iv])\n        {\n            if (!p_dirichlet_flag[iv]) //p_new for dirichlet BC is retained when p_prime is added (p_prime is zero at dirichlet BC)\n            {                          //p_new for neumann BC has to be set explicitly\n                rhs = (normal_mom_x[iv] * points.normal[dim * iv]) + (normal_mom_y[iv] * points.normal[dim * iv + 1]);\n                for (int i1 = cloud.nb_points_row[iv]; i1 < cloud.nb_points_row[iv + 1]; i1++)\n                {\n                    ivnb = cloud.nb_points_col[i1];\n                    if (ivnb == iv)\n                        diag_coeff = (cloud.grad_x_coeff[i1] * points.normal[dim * iv]) + (cloud.grad_y_coeff[i1] * points.normal[dim * iv + 1]);\n                    else\n                    {\n                        off_diag_coeff = (cloud.grad_x_coeff[i1] * points.normal[dim * iv]) + (cloud.grad_y_coeff[i1] * points.normal[dim * iv + 1]);\n                        rhs = rhs - (off_diag_coeff * p_new[ivnb]);\n                    }\n                }\n                p_new[iv] = rhs / diag_coeff;\n            }\n        }\n    }\n}\n\nvoid SEMI_IMPLICIT_SPLIT_SOLVER::calc_vel_corr(POINTS &points, CLOUD &cloud, PARAMETERS &parameters, Eigen::VectorXd &u_new, Eigen::VectorXd &v_new)\n{\n    if (it == 0)\n    { //BDF1: implicit Euler\n        u_prime = ((points.grad_x_matrix_EIGEN_internal * p_prime.head(points.nv)) * (parameters.dt / parameters.rho));\n        v_prime = ((points.grad_y_matrix_EIGEN_internal * p_prime.head(points.nv)) * (parameters.dt / parameters.rho));\n    }\n    else\n    {\n        u_prime = ((points.grad_x_matrix_EIGEN_internal * p_prime.head(points.nv)) * (parameters.dt / (bdf2_alpha_1 * parameters.rho)));\n        v_prime = ((points.grad_y_matrix_EIGEN_internal * p_prime.head(points.nv)) * (parameters.dt / (bdf2_alpha_1 * parameters.rho)));\n    }\n\n    u_new = u_new - u_prime;\n    v_new = v_new - v_prime;\n    //internal points are set above; boundary values are obtained implicitly in the solver (for both dirichlet and neumann); u_prime and v_prime are zero at all boundaries\n}\n\nvoid SEMI_IMPLICIT_SPLIT_SOLVER::extras(POINTS &points, PARAMETERS &parameters, Eigen::VectorXd &u_new, Eigen::VectorXd &v_new, Eigen::VectorXd &p_new, Eigen::VectorXd &u_old, Eigen::VectorXd &v_old, Eigen::VectorXd &p_old)\n{\n    // double total_steady_err, max_err, l1_err;\n    // calc_max_l1_error(u_old, u_new, max_err, l1_err);\n    // total_steady_err = l1_err / parameters.dt;\n    // calc_max_l1_error(v_old, v_new, max_err, l1_err);\n    // total_steady_err += l1_err / parameters.dt;\n    // parameters.steady_error_log.push_back(total_steady_err);\n    u_old_old = u_old, v_old_old = v_old;\n    // return total_steady_err;\n}\n\nvoid SEMI_IMPLICIT_SPLIT_SOLVER::modify_vel_matrix(POINTS &points, CLOUD &cloud, PARAMETERS &parameters, Eigen::VectorXd &u_new, Eigen::VectorXd &v_new)\n{\n    int ivnb, dim = parameters.dimension, index;\n    double value, unsteady_factor;\n    if (it == 0)\n        unsteady_factor = 1.0; //BDF1: implicit Euler\n    else\n        unsteady_factor = bdf2_alpha_1;\n    for (int iv = 0; iv < points.nv; iv++)\n        if (!points.boundary_flag[iv])\n        { //coefficients of boundary points never updated for velocities\n            for (int i1 = cloud.nb_points_row[iv]; i1 < cloud.nb_points_row[iv + 1]; i1++)\n            {\n                ivnb = cloud.nb_points_col[i1];\n                value = -parameters.mu * cloud.laplacian_coeff[i1];                    //diffusion\n                value = value + (u_new[iv] * parameters.rho * cloud.grad_x_coeff[i1]); //convection\n                value = value + (v_new[iv] * parameters.rho * cloud.grad_y_coeff[i1]); //convection\n                if (ivnb == iv)\n                    value = value + (unsteady_factor * parameters.rho / parameters.dt); //diagonal term\n                index = nb_points_col_matrix_u[i1];\n                matrix_u.valuePtr()[index] = value;\n                index = nb_points_col_matrix_v[i1];\n                matrix_v.valuePtr()[index] = value;\n            }\n        }\n}\n\nvoid SEMI_IMPLICIT_SPLIT_SOLVER::set_vel_matrix(POINTS &points, CLOUD &cloud, PARAMETERS &parameters, Eigen::VectorXd &u_new, Eigen::VectorXd &v_new)\n{\n    matrix_u.resize(0, 0), matrix_v.resize(0, 0);\n    vector<Eigen::Triplet<double>> triplet;\n    int ivnb, dim = parameters.dimension;\n    double value, unsteady_factor;\n    if (it == 0)\n        unsteady_factor = 1.0; //BDF1: implicit Euler\n    else\n        unsteady_factor = bdf2_alpha_1;\n    for (int iv = 0; iv < points.nv; iv++)\n    {\n        if (points.boundary_flag[iv])\n        {\n            if (u_dirichlet_flag[iv])\n                triplet.push_back(Eigen::Triplet<double>(iv, iv, 1.0));\n            else\n            {\n                for (int i1 = cloud.nb_points_row[iv]; i1 < cloud.nb_points_row[iv + 1]; i1++)\n                {\n                    ivnb = cloud.nb_points_col[i1];\n                    value = points.normal[dim * iv] * cloud.grad_x_coeff[i1] + points.normal[dim * iv + 1] * cloud.grad_y_coeff[i1];\n                    triplet.push_back(Eigen::Triplet<double>(iv, ivnb, value));\n                }\n            }\n        }\n        else\n        {\n            for (int i1 = cloud.nb_points_row[iv]; i1 < cloud.nb_points_row[iv + 1]; i1++)\n            {\n                ivnb = cloud.nb_points_col[i1];\n                value = -parameters.mu * cloud.laplacian_coeff[i1];                    //diffusion\n                value = value + (u_new[iv] * parameters.rho * cloud.grad_x_coeff[i1]); //convection\n                value = value + (v_new[iv] * parameters.rho * cloud.grad_y_coeff[i1]); //convection\n                if (ivnb == iv)\n                    value = value + (unsteady_factor * parameters.rho / parameters.dt); //diagonal term\n                triplet.push_back(Eigen::Triplet<double>(iv, ivnb, value));\n            }\n        }\n    }\n    matrix_u.resize(points.nv, points.nv);\n    matrix_u.setFromTriplets(triplet.begin(), triplet.end());\n    matrix_u.makeCompressed();\n    triplet.clear();\n\n    for (int iv = 0; iv < points.nv; iv++)\n    {\n        if (points.boundary_flag[iv])\n        {\n            if (v_dirichlet_flag[iv])\n                triplet.push_back(Eigen::Triplet<double>(iv, iv, 1.0));\n            else\n            {\n                for (int i1 = cloud.nb_points_row[iv]; i1 < cloud.nb_points_row[iv + 1]; i1++)\n                {\n                    ivnb = cloud.nb_points_col[i1];\n                    value = points.normal[dim * iv] * cloud.grad_x_coeff[i1] + points.normal[dim * iv + 1] * cloud.grad_y_coeff[i1];\n                    triplet.push_back(Eigen::Triplet<double>(iv, ivnb, value));\n                }\n            }\n        }\n        else\n        {\n            for (int i1 = cloud.nb_points_row[iv]; i1 < cloud.nb_points_row[iv + 1]; i1++)\n            {\n                ivnb = cloud.nb_points_col[i1];\n                value = -parameters.mu * cloud.laplacian_coeff[i1];                    //diffusion\n                value = value + (u_new[iv] * parameters.rho * cloud.grad_x_coeff[i1]); //convection\n                value = value + (v_new[iv] * parameters.rho * cloud.grad_y_coeff[i1]); //convection\n                if (ivnb == iv)\n                    value = value + (parameters.rho / parameters.dt); //diagonal term\n                triplet.push_back(Eigen::Triplet<double>(iv, ivnb, value));\n            }\n        }\n    }\n    matrix_v.resize(points.nv, points.nv);\n    matrix_v.setFromTriplets(triplet.begin(), triplet.end());\n    matrix_v.makeCompressed();\n    triplet.clear();\n}\n\nvoid SEMI_IMPLICIT_SPLIT_SOLVER::calc_nb_points_col_matrix(POINTS &points, CLOUD &cloud, PARAMETERS &parameters)\n{\n    int ivnb, index;\n    nb_points_col_matrix_u.clear(), nb_points_col_matrix_v.clear();\n    for (int i1 = 0; i1 < cloud.nb_points_col.size(); i1++) //initialize to -1\n        nb_points_col_matrix_u.push_back(-1), nb_points_col_matrix_v.push_back(-1);\n    for (int iv = 0; iv < points.nv; iv++)\n        if (!points.boundary_flag[iv])\n        { //coefficients of boundary points never updated for velocities; nb_points_col_matrix ahas value of [-1] at bounday points\n            for (int i1 = cloud.nb_points_row[iv]; i1 < cloud.nb_points_row[iv + 1]; i1++)\n            {\n                index = -1;\n                ivnb = cloud.nb_points_col[i1];\n                for (int i2 = matrix_u.outerIndexPtr()[iv]; i2 < matrix_u.outerIndexPtr()[iv + 1]; i2++)\n                    if (matrix_u.innerIndexPtr()[i2] == ivnb)\n                    {\n                        index = i2;\n                        break;\n                    }\n                if (index < 0)\n                {\n                    cout << \"\\n\\nError from SEMI_IMPLICIT_SPLIT_SOLVER::calc_nb_points_col_matrix in matrix_u, unable to find ivnb: \" << ivnb << \" for iv: \" << iv << \", points.boundary_flag[iv]: \" << points.boundary_flag[iv] << \"\\n\\n\";\n                    throw bad_exception();\n                }\n                nb_points_col_matrix_u[i1] = index;\n            }\n        }\n    for (int iv = 0; iv < points.nv; iv++)\n        if (!points.boundary_flag[iv])\n        { //coefficients of boundary points never updated for velocities; nb_points_col_matrix ahas value of [-1] at bounday points\n            for (int i1 = cloud.nb_points_row[iv]; i1 < cloud.nb_points_row[iv + 1]; i1++)\n            {\n                index = -1;\n                ivnb = cloud.nb_points_col[i1];\n                for (int i2 = matrix_v.outerIndexPtr()[iv]; i2 < matrix_v.outerIndexPtr()[iv + 1]; i2++)\n                    if (matrix_v.innerIndexPtr()[i2] == ivnb)\n                    {\n                        index = i2;\n                        break;\n                    }\n                if (index < 0)\n                {\n                    cout << \"\\n\\nError from SEMI_IMPLICIT_SPLIT_SOLVER::calc_nb_points_col_matrix in matrix_v, unable to find ivnb: \" << ivnb << \" for iv: \" << iv << \", points.boundary_flag[iv]: \" << points.boundary_flag[iv] << \"\\n\\n\";\n                    throw bad_exception();\n                }\n                nb_points_col_matrix_v[i1] = index;\n            }\n        }\n}\n\nvoid SEMI_IMPLICIT_SPLIT_SOLVER::single_timestep_2d(POINTS &points, CLOUD &cloud, PARAMETERS &parameters, Eigen::VectorXd &u_new, Eigen::VectorXd &v_new, Eigen::VectorXd &p_new, Eigen::VectorXd &u_old, Eigen::VectorXd &v_old, Eigen::VectorXd &p_old, int it1, vector<int> &n_outer_iter_log, vector<double> &iterative_l1_err_log, vector<double> &iterative_max_err_log)\n{\n    it = it1;\n    if (p_source.size() != p_new.size())\n        p_new = Eigen::VectorXd::Zero(p_source.size());\n    if (p_source.size() != p_old.size())\n        p_old = Eigen::VectorXd::Zero(p_source.size());\n    double total_steady_err;\n    u_new = u_old, v_new = v_old, p_new = p_old; //initialize\n    if (it % precond_freq_it == 0 || it == 0 || it == 1)\n    {\n        set_vel_matrix(points, cloud, parameters, u_new, v_new);\n        solver_eigen_u.setTolerance(parameters.solver_tolerance); //default is machine precision (https://eigen.tuxfamily.org/dox/classEigen_1_1IterativeSolverBase.html#ac160a444af8998f93da9aa30e858470d)\n        solver_eigen_u.setMaxIterations(parameters.n_iter);       //default is twice number of columns (https://eigen.tuxfamily.org/dox/classEigen_1_1IterativeSolverBase.html#af83de7a7d31d9d4bd1fef6222b07335b)\n        solver_eigen_u.preconditioner().setDroptol(parameters.precond_droptol);\n        solver_eigen_u.compute(matrix_u);\n        solver_eigen_v.setTolerance(parameters.solver_tolerance); //default is machine precision (https://eigen.tuxfamily.org/dox/classEigen_1_1IterativeSolverBase.html#ac160a444af8998f93da9aa30e858470d)\n        solver_eigen_v.setMaxIterations(parameters.n_iter);       //default is twice number of columns (https://eigen.tuxfamily.org/dox/classEigen_1_1IterativeSolverBase.html#af83de7a7d31d9d4bd1fef6222b07335b)\n        solver_eigen_v.preconditioner().setDroptol(parameters.precond_droptol);\n        solver_eigen_v.compute(matrix_v);\n        calc_nb_points_col_matrix(points, cloud, parameters);\n    }\n    for (outer_iter = 0; outer_iter < n_outer_iter; outer_iter++)\n    {\n        u_iter_old = u_new, v_iter_old = v_new;\n        modify_vel_matrix(points, cloud, parameters, u_new, v_new);\n        calc_vel(points, parameters, u_new, v_new, p_new, u_old, v_old, p_old);\n        calc_pressure(points, cloud, parameters, u_new, v_new, p_new, u_old, v_old, p_old);\n        calc_vel_corr(points, cloud, parameters, u_new, v_new);\n        iterative_l1_err = (u_new - u_iter_old).lpNorm<1>() / (parameters.dimension * u_new.size());\n        iterative_l1_err += ((v_new - v_iter_old).lpNorm<1>() / (parameters.dimension * v_new.size()));\n        iterative_max_err = (u_new - u_iter_old).lpNorm<Eigen::Infinity>() / parameters.dimension;\n        iterative_max_err += ((v_new - v_iter_old).lpNorm<Eigen::Infinity>() / parameters.dimension);\n        if ((outer_iter == n_outer_iter - 1) || (iterative_l1_err <= iterative_tolerance))\n        {\n            iterative_max_err_log.push_back(iterative_max_err);\n            iterative_l1_err_log.push_back(iterative_l1_err);\n            n_outer_iter_log.push_back(outer_iter + 1);\n            // printf(\"    SEMI_IMPLICIT_SPLIT_SOLVER::single_timestep_2d outer_iter: %i, iterative l1_err: %g, max_err: %g, tolerance: %g\\n\", outer_iter, iterative_l1_err, iterative_max_err, iterative_tolerance);\n        }\n        if (iterative_l1_err <= iterative_tolerance)\n            break;\n    }\n    extras(points, parameters, u_new, v_new, p_new, u_old, v_old, p_old);\n    // return total_steady_err;\n}\n\nvoid SEMI_IMPLICIT_SPLIT_SOLVER::single_timestep_2d(POINTS &points, CLOUD &cloud, PARAMETERS &parameters, Eigen::VectorXd &u_new, Eigen::VectorXd &v_new, Eigen::VectorXd &p_new, Eigen::VectorXd &u_old, Eigen::VectorXd &v_old, Eigen::VectorXd &p_old, Eigen::VectorXd &body_force_x, Eigen::VectorXd &body_force_y, int it1, vector<int> &n_outer_iter_log, vector<double> &iterative_l1_err_log, vector<double> &iterative_max_err_log)\n{\n    it = it1;\n    if (p_source.size() != p_new.size())\n        p_new = Eigen::VectorXd::Zero(p_source.size());\n    if (p_source.size() != p_old.size())\n        p_old = Eigen::VectorXd::Zero(p_source.size());\n    double total_steady_err;\n    u_new = u_old, v_new = v_old, p_new = p_old; //initialize\n    if (it % precond_freq_it == 0 || it == 0 || it == 1)\n    {\n        set_vel_matrix(points, cloud, parameters, u_new, v_new);\n        solver_eigen_u.setTolerance(parameters.solver_tolerance); //default is machine precision (https://eigen.tuxfamily.org/dox/classEigen_1_1IterativeSolverBase.html#ac160a444af8998f93da9aa30e858470d)\n        solver_eigen_u.setMaxIterations(parameters.n_iter);       //default is twice number of columns (https://eigen.tuxfamily.org/dox/classEigen_1_1IterativeSolverBase.html#af83de7a7d31d9d4bd1fef6222b07335b)\n        solver_eigen_u.preconditioner().setDroptol(parameters.precond_droptol);\n        solver_eigen_u.compute(matrix_u);\n        solver_eigen_v.setTolerance(parameters.solver_tolerance); //default is machine precision (https://eigen.tuxfamily.org/dox/classEigen_1_1IterativeSolverBase.html#ac160a444af8998f93da9aa30e858470d)\n        solver_eigen_v.setMaxIterations(parameters.n_iter);       //default is twice number of columns (https://eigen.tuxfamily.org/dox/classEigen_1_1IterativeSolverBase.html#af83de7a7d31d9d4bd1fef6222b07335b)\n        solver_eigen_v.preconditioner().setDroptol(parameters.precond_droptol);\n        solver_eigen_v.compute(matrix_v);\n        calc_nb_points_col_matrix(points, cloud, parameters);\n    }\n    for (outer_iter = 0; outer_iter < n_outer_iter; outer_iter++)\n    {\n        u_iter_old = u_new, v_iter_old = v_new;\n        modify_vel_matrix(points, cloud, parameters, u_new, v_new);\n        calc_vel(points, parameters, u_new, v_new, p_new, u_old, v_old, p_old, body_force_x, body_force_y);\n        calc_pressure(points, cloud, parameters, u_new, v_new, p_new, u_old, v_old, p_old);\n        calc_vel_corr(points, cloud, parameters, u_new, v_new);\n        iterative_l1_err = (u_new - u_iter_old).lpNorm<1>() / (parameters.dimension * u_new.size());\n        iterative_l1_err += ((v_new - v_iter_old).lpNorm<1>() / (parameters.dimension * v_new.size()));\n        iterative_max_err = (u_new - u_iter_old).lpNorm<Eigen::Infinity>() / parameters.dimension;\n        iterative_max_err += ((v_new - v_iter_old).lpNorm<Eigen::Infinity>() / parameters.dimension);\n        if ((outer_iter == n_outer_iter - 1) || (iterative_l1_err <= iterative_tolerance))\n        {\n            iterative_max_err_log.push_back(iterative_max_err);\n            iterative_l1_err_log.push_back(iterative_l1_err);\n            n_outer_iter_log.push_back(outer_iter + 1);\n            // printf(\"    SEMI_IMPLICIT_SPLIT_SOLVER::single_timestep_2d outer_iter: %i, iterative l1_err: %g, max_err: %g, tolerance: %g\\n\", outer_iter, iterative_l1_err, iterative_max_err, iterative_tolerance);\n        }\n        if (iterative_l1_err <= iterative_tolerance)\n            break;\n    }\n    extras(points, parameters, u_new, v_new, p_new, u_old, v_old, p_old);\n    // return total_steady_err;\n}", "meta": {"hexsha": "9f137d5ddcaf3156606384aa22bafdd01ce0b679", "size": 26245, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "header_files/semi_implicit_split_solver.cpp", "max_stars_repo_name": "shahaneshantanu/memphys", "max_stars_repo_head_hexsha": "1b95afa505808f302d2dd4689faa45bb6480e8d8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "header_files/semi_implicit_split_solver.cpp", "max_issues_repo_name": "shahaneshantanu/memphys", "max_issues_repo_head_hexsha": "1b95afa505808f302d2dd4689faa45bb6480e8d8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "header_files/semi_implicit_split_solver.cpp", "max_forks_repo_name": "shahaneshantanu/memphys", "max_forks_repo_head_hexsha": "1b95afa505808f302d2dd4689faa45bb6480e8d8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-07T00:32:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T00:32:37.000Z", "avg_line_length": 56.0790598291, "max_line_length": 428, "alphanum_fraction": 0.6488473995, "num_tokens": 7133, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.47906241251473314}}
{"text": "#include \"gate_matrix.hpp\"\n// Turn off Eigen warnings\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wsuggest-override\"\n#pragma GCC diagnostic ignored \"-Wdeprecated-copy\"\n#pragma GCC diagnostic ignored \"-Wunused-function\"\n#include <Eigen/Dense>\n#pragma GCC diagnostic pop\n#include <cassert>\n#include <iostream>\n#include <unordered_map>\n\nnamespace {\nusing namespace qcor::utils;\nusing namespace std::complex_literals;\nEigen::Matrix2cd getGateMat(const qop_t &in_op) {\n  static const Eigen::Matrix2cd X_mat = []() {\n    Eigen::Matrix2cd result = Eigen::MatrixXcd::Zero(2, 2);\n    result << 0.0, 1.0, 1.0, 0.0;\n    return result;\n  }();\n  static const Eigen::Matrix2cd Y_mat = []() {\n    Eigen::Matrix2cd result = Eigen::MatrixXcd::Zero(2, 2);\n    result << 0.0, -1i, 1i, 0.0;\n    return result;\n  }();\n  static const Eigen::Matrix2cd Z_mat = []() {\n    Eigen::Matrix2cd result = Eigen::MatrixXcd::Zero(2, 2);\n    result << 1.0, 0.0, 0.0, -1.0;\n    return result;\n  }();\n  static const Eigen::Matrix2cd H_mat = []() {\n    Eigen::Matrix2cd result = Eigen::MatrixXcd::Zero(2, 2);\n    result << M_SQRT1_2, M_SQRT1_2, M_SQRT1_2, -M_SQRT1_2;\n    return result;\n  }();\n\n  static const auto rx_mat = [](const std::vector<double> &in_params) {\n    assert(in_params.size() == 1);\n    auto theta = in_params[0];\n    Eigen::Matrix2cd result = Eigen::MatrixXcd::Zero(2, 2);\n    result << std::cos(0.5 * theta),\n        std::complex<double>(0, -1) * std::sin(0.5 * theta),\n        std::complex<double>(0, -1) * std::sin(0.5 * theta),\n        std::cos(0.5 * theta);\n    return result;\n  };\n\n  static const auto ry_mat = [](const std::vector<double> &in_params) {\n    assert(in_params.size() == 1);\n    auto theta = in_params[0];\n    Eigen::Matrix2cd result = Eigen::MatrixXcd::Zero(2, 2);\n    result << std::cos(0.5 * theta), -std::sin(0.5 * theta),\n        std::sin(0.5 * theta), std::cos(0.5 * theta);\n    return result;\n  };\n\n  static const auto rz_mat = [](const std::vector<double> &in_params) {\n    assert(in_params.size() == 1);\n    auto theta = in_params[0];\n    Eigen::Matrix2cd result = Eigen::MatrixXcd::Zero(2, 2);\n    result << std::exp(std::complex<double>(0, -0.5 * theta)), 0.0, 0.0,\n        std::exp(std::complex<double>(0, 0.5 * theta));\n    return result;\n  };\n\n  static const auto p_mat = [](const std::vector<double> &in_params) {\n    assert(in_params.size() == 1);\n    auto theta = in_params[0];\n    Eigen::Matrix2cd result = Eigen::MatrixXcd::Zero(2, 2);\n    result << 1.0, 0.0, 0.0, std::exp(std::complex<double>(0, theta));\n    return result;\n  };\n\n  static const std::unordered_map<std::string, Eigen::Matrix2cd>\n      GateMatrixCache = {{\"x\", X_mat},           {\"y\", Y_mat},\n                         {\"z\", Z_mat},           {\"h\", H_mat},\n                         {\"t\", p_mat({M_PI_4})}, {\"tdg\", p_mat({-M_PI_4})},\n                         {\"s\", p_mat({M_PI_2})}, {\"sdg\", p_mat({-M_PI_2})}};\n  const auto &gateName = in_op.first;\n  const auto &gateParams = in_op.second;\n  const auto it = GateMatrixCache.find(gateName);\n  if (it != GateMatrixCache.end()) {\n    return it->second;\n  }\n  if (gateName == \"rx\") {\n    return rx_mat(gateParams);\n  }\n  if (gateName == \"ry\") {\n    return ry_mat(gateParams);\n  }\n  if (gateName == \"rz\") {\n    return rz_mat(gateParams);\n  }\n  throw std::runtime_error(\"Unknown single qubit gate: \" + gateName);\n  return Eigen::MatrixXcd::Zero(2, 2);\n}\n\n// If the matrix is finite: no NaN elements\ntemplate <typename Derived>\ninline bool isFinite(const Eigen::MatrixBase<Derived> &x) {\n  return ((x - x).array() == (x - x).array()).all();\n}\n\n// Default tolerace for validation\nconstexpr double TOLERANCE = 1e-6;\n\ntemplate <typename Derived>\nbool allClose(const Eigen::MatrixBase<Derived> &in_mat1,\n              const Eigen::MatrixBase<Derived> &in_mat2,\n              double in_tol = TOLERANCE) {\n  if (!isFinite(in_mat1) || !isFinite(in_mat2)) {\n    return false;\n  }\n\n  if (in_mat1.rows() == in_mat2.rows() && in_mat1.cols() == in_mat2.cols()) {\n    for (int i = 0; i < in_mat1.rows(); ++i) {\n      for (int j = 0; j < in_mat1.cols(); ++j) {\n        if (std::abs(in_mat1(i, j) - in_mat2(i, j)) > in_tol) {\n          return false;\n        }\n      }\n    }\n\n    return true;\n  }\n  return false;\n}\n\n// Use Z-Y decomposition of Nielsen and Chuang (Theorem 4.1).\n// An arbitrary one qubit gate matrix can be writen as\n// U = [ exp(j*(a-b/2-d/2))*cos(c/2), -exp(j*(a-b/2+d/2))*sin(c/2)\n//       exp(j*(a+b/2-d/2))*sin(c/2), exp(j*(a+b/2+d/2))*cos(c/2)]\n// where a,b,c,d are real numbers.\n// Then U = exp(j*a) Rz(b) Ry(c) Rz(d).\nstd::tuple<double, double, double, double>\nsingleQubitGateDecompose(const Eigen::Matrix2cd &matrix) {\n  static const Eigen::Matrix2cd ID_MAT = Eigen::Matrix2cd::Identity();\n  if (allClose(matrix, ID_MAT)) {\n    return std::make_tuple(0.0, 0.0, 0.0, 0.0);\n  }\n  const auto checkParams = [&matrix](double a, double bHalf, double cHalf,\n                                     double dHalf) {\n    Eigen::Matrix2cd U;\n    U << std::exp(1i * (a - bHalf - dHalf)) * std::cos(cHalf),\n        -std::exp(1i * (a - bHalf + dHalf)) * std::sin(cHalf),\n        std::exp(1i * (a + bHalf - dHalf)) * std::sin(cHalf),\n        std::exp(1i * (a + bHalf + dHalf)) * std::cos(cHalf);\n\n    return allClose(U, matrix);\n  };\n\n  double a, bHalf, cHalf, dHalf;\n  const double TOLERANCE = 1e-9;\n  if (std::abs(matrix(0, 1)) < TOLERANCE) {\n    auto two_a = fmod(std::arg(matrix(0, 0) * matrix(1, 1)), 2 * M_PI);\n    a = (std::abs(two_a) < TOLERANCE || std::abs(two_a) > 2 * M_PI - TOLERANCE)\n            ? 0\n            : two_a / 2.0;\n    auto dHalf = 0.0;\n    auto b = std::arg(matrix(1, 1)) - std::arg(matrix(0, 0));\n    std::vector<double> possibleBhalf{fmod(b / 2.0, 2 * M_PI),\n                                      fmod(b / 2.0 + M_PI, 2.0 * M_PI)};\n    std::vector<double> possibleChalf{0.0, M_PI};\n    bool found = false;\n    for (size_t i = 0; i < possibleBhalf.size(); ++i) {\n      for (size_t j = 0; j < possibleChalf.size(); ++j) {\n        bHalf = possibleBhalf[i];\n        cHalf = possibleChalf[j];\n        if (checkParams(a, bHalf, cHalf, dHalf)) {\n          found = true;\n          break;\n        }\n      }\n      if (found) {\n        break;\n      }\n    }\n    assert(found);\n  } else if (std::abs(matrix(0, 0)) < TOLERANCE) {\n    auto two_a = fmod(std::arg(-matrix(0, 1) * matrix(1, 0)), 2 * M_PI);\n    a = (std::abs(two_a) < TOLERANCE || std::abs(two_a) > 2 * M_PI - TOLERANCE)\n            ? 0\n            : two_a / 2.0;\n    dHalf = 0;\n    auto b = std::arg(matrix(1, 0)) - std::arg(matrix(0, 1)) + M_PI;\n    std::vector<double> possibleBhalf{fmod(b / 2., 2 * M_PI),\n                                      fmod(b / 2. + M_PI, 2 * M_PI)};\n    std::vector<double> possibleChalf{M_PI / 2., 3. / 2. * M_PI};\n    bool found = false;\n    for (size_t i = 0; i < possibleBhalf.size(); ++i) {\n      for (size_t j = 0; j < possibleChalf.size(); ++j) {\n        bHalf = possibleBhalf[i];\n        cHalf = possibleChalf[j];\n        if (checkParams(a, bHalf, cHalf, dHalf)) {\n          found = true;\n          break;\n        }\n      }\n      if (found) {\n        break;\n      }\n    }\n    assert(found);\n  } else {\n    auto two_a = fmod(std::arg(matrix(0, 0) * matrix(1, 1)), 2 * M_PI);\n    a = (std::abs(two_a) < TOLERANCE || std::abs(two_a) > 2 * M_PI - TOLERANCE)\n            ? 0\n            : two_a / 2.0;\n    auto two_d = 2. * std::arg(matrix(0, 1)) - 2. * std::arg(matrix(0, 0));\n    std::vector<double> possibleDhalf{\n        fmod(two_d / 4., 2 * M_PI), fmod(two_d / 4. + M_PI / 2., 2 * M_PI),\n        fmod(two_d / 4. + M_PI, 2 * M_PI),\n        fmod(two_d / 4. + 3. / 2. * M_PI, 2 * M_PI)};\n    auto two_b = 2. * std::arg(matrix(1, 0)) - 2. * std::arg(matrix(0, 0));\n    std::vector<double> possibleBhalf{\n        fmod(two_b / 4., 2 * M_PI), fmod(two_b / 4. + M_PI / 2., 2 * M_PI),\n        fmod(two_b / 4. + M_PI, 2 * M_PI),\n        fmod(two_b / 4. + 3. / 2. * M_PI, 2 * M_PI)};\n    auto tmp = std::acos(std::abs(matrix(1, 1)));\n    std::vector<double> possibleChalf{\n        fmod(tmp, 2 * M_PI), fmod(tmp + M_PI, 2 * M_PI),\n        fmod(-1. * tmp, 2 * M_PI), fmod(-1. * tmp + M_PI, 2 * M_PI)};\n    bool found = false;\n    for (size_t i = 0; i < possibleBhalf.size(); ++i) {\n      for (size_t j = 0; j < possibleChalf.size(); ++j) {\n        for (size_t k = 0; k < possibleDhalf.size(); ++k) {\n          bHalf = possibleBhalf[i];\n          cHalf = possibleChalf[j];\n          dHalf = possibleDhalf[k];\n          if (checkParams(a, bHalf, cHalf, dHalf)) {\n            found = true;\n            break;\n          }\n        }\n        if (found) {\n          break;\n        }\n      }\n      if (found) {\n        break;\n      }\n    }\n    assert(found);\n  }\n\n  // Final check:\n  assert(checkParams(a, bHalf, cHalf, dHalf));\n  return std::make_tuple(a, bHalf, cHalf, dHalf);\n};\n\nstd::vector<pauli_decomp_t>\nsimplifySingleQubitSeq(double zAngleBefore, double yAngle, double zAngleAfter) {\n  auto zExpBefore = zAngleBefore / M_PI - 0.5;\n  auto middleExp = yAngle / M_PI;\n  std::string middlePauli = \"rx\";\n  auto zExpAfter = zAngleAfter / M_PI + 0.5;\n\n  // Helper functions:\n  const auto isNearZeroMod = [](double a, double period) -> bool {\n    const auto halfPeriod = period / 2;\n    const double TOL = 1e-8;\n    return std::abs(fmod(a + halfPeriod, period) - halfPeriod) < TOL;\n  };\n\n  const auto toQuarterTurns = [](double in_exp) -> int {\n    return static_cast<int>(round(2 * in_exp)) % 4;\n  };\n\n  const auto isCliffordRotation = [&](double in_exp) -> bool {\n    return isNearZeroMod(in_exp, 0.5);\n  };\n\n  const auto isQuarterTurn = [&](double in_exp) -> bool {\n    return (isCliffordRotation(in_exp) && toQuarterTurns(in_exp) % 2 == 1);\n  };\n\n  const auto isHalfTurn = [&](double in_exp) -> bool {\n    return (isCliffordRotation(in_exp) && toQuarterTurns(in_exp) == 2);\n  };\n\n  const auto isNoTurn = [&](double in_exp) -> bool {\n    return (isCliffordRotation(in_exp) && toQuarterTurns(in_exp) == 0);\n  };\n\n  // Clean up angles\n  if (isCliffordRotation(zExpBefore)) {\n    if ((isQuarterTurn(zExpBefore) || isQuarterTurn(zExpAfter)) !=\n        (isHalfTurn(middleExp) && isNoTurn(zExpBefore - zExpAfter))) {\n      zExpBefore += 0.5;\n      zExpAfter -= 0.5;\n      middlePauli = \"ry\";\n    }\n    if (isHalfTurn(zExpBefore) || isHalfTurn(zExpAfter)) {\n      zExpBefore -= 1;\n      zExpAfter += 1;\n      middleExp = -middleExp;\n    }\n  }\n  if (isNoTurn(middleExp)) {\n    zExpBefore += zExpAfter;\n    zExpAfter = 0;\n  } else if (isHalfTurn(middleExp)) {\n    zExpAfter -= zExpBefore;\n    zExpBefore = 0;\n  }\n\n  std::vector<pauli_decomp_t> composite;\n  if (!isNoTurn(zExpBefore)) {\n    composite.emplace_back(std::make_pair(\"rz\", zExpBefore * M_PI));\n  }\n  if (!isNoTurn(middleExp)) {\n    composite.emplace_back(std::make_pair(middlePauli, middleExp * M_PI));\n  }\n  if (!isNoTurn(zExpAfter)) {\n    composite.emplace_back(std::make_pair(\"rz\", zExpAfter * M_PI));\n  }\n  return composite;\n}\n\n} // namespace\nnamespace qcor {\nnamespace utils {\nstd::vector<pauli_decomp_t>\ndecompose_gate_sequence(const std::vector<qop_t> &op_list) {\n  Eigen::Matrix2cd totalU = Eigen::MatrixXcd::Identity(2, 2);\n  for (const auto &op : op_list) {\n    // std::cout << \"Gate: \" << op.first << \": \" << op.second.size() << \"\\n\";\n    totalU = getGateMat(op) * totalU;\n  }\n\n  // std::cout << \"Total U = \" << totalU << \"\\n\";\n  auto [a, bHalf, cHalf, dHalf] = singleQubitGateDecompose(totalU);\n\n  // Validate U = exp(j*a) Rz(b) Ry(c) Rz(d).\n  const auto validate = [](const Eigen::Matrix2cd &in_mat, double a, double b,\n                           double c, double d) {\n    Eigen::Matrix2cd Rz_b, Ry_c, Rz_d;\n    Rz_b << std::exp(-1i * b / 2.0), 0, 0, std::exp(1i * b / 2.0);\n    Rz_d << std::exp(-1i * d / 2.0), 0, 0, std::exp(1i * d / 2.0);\n    Ry_c << std::cos(c / 2), -std::sin(c / 2), std::sin(c / 2), std::cos(c / 2);\n    Eigen::Matrix2cd mat = std::exp(1i * a) * Rz_b * Ry_c * Rz_d;\n    return allClose(in_mat, mat);\n  };\n  // Validate the *raw* decomposition\n  assert(validate(totalU, a, 2 * bHalf, 2 * cHalf, 2 * dHalf));\n  return simplifySingleQubitSeq(2 * dHalf, 2 * cHalf, 2 * bHalf);\n}\n} // namespace utils\n} // namespace qcor\n", "meta": {"hexsha": "041b082bfdde93817aba4907697cfc4896ccb88d", "size": 12138, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mlir/transforms/optimizations/utils/gate_matrix.cpp", "max_stars_repo_name": "ahayashi/qcor", "max_stars_repo_head_hexsha": "929988b92cfec52d321c48e6cc01545e46edc024", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mlir/transforms/optimizations/utils/gate_matrix.cpp", "max_issues_repo_name": "ahayashi/qcor", "max_issues_repo_head_hexsha": "929988b92cfec52d321c48e6cc01545e46edc024", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mlir/transforms/optimizations/utils/gate_matrix.cpp", "max_forks_repo_name": "ahayashi/qcor", "max_forks_repo_head_hexsha": "929988b92cfec52d321c48e6cc01545e46edc024", "max_forks_repo_licenses": ["BSD-3-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.5811965812, "max_line_length": 80, "alphanum_fraction": 0.5731586752, "num_tokens": 4074, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186768138228, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4790624067520887}}
{"text": "#include <boost/numeric/odeint/stepper/runge_kutta4_classic.hpp>\n", "meta": {"hexsha": "b4430ffc5473ca211ca401ee14120b75a64ab5dc", "size": 65, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_numeric_odeint_stepper_runge_kutta4_classic.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_numeric_odeint_stepper_runge_kutta4_classic.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_numeric_odeint_stepper_runge_kutta4_classic.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 32.5, "max_line_length": 64, "alphanum_fraction": 0.8461538462, "num_tokens": 20, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186768138228, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4790624067520887}}
{"text": "#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <iostream>\n#include <mimkl/data_structures.hpp>\n#include <mimkl/definitions.hpp>\n#include <mimkl/kernels.hpp>\n#include <mimkl/linear_algebra.hpp>\n#include <stdexcept>\n\nusing mimkl::data_structures::DataFrame;\nusing mimkl::data_structures::indexing_from_vector;\nusing mimkl::data_structures::range;\nusing mimkl::definitions::Indexing;\n\nint main(int argc, char **argv)\n{\n    try\n    {\n        Eigen::Matrix<double, 2, 3> X;\n        X << 1., 2., 3., 4., 5., 6.;\n\n        Eigen::MatrixXd Y(4, 3);\n        Y << 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12.;\n\n        // check range()\n        std::vector<int> vec = range(X.cols()); //\n        std::cout << \"a range:\\n\";\n        for (std::vector<int>::const_iterator i = vec.begin(); i != vec.end();\n             ++i)\n            std::cout << *i << \" \";\n        std::cout << std::endl;\n        // check indexing_from_vector()\n        Indexing an_indexing = indexing_from_vector(vec);\n        std::cout << \"first element of an Indexing\\n\"\n                  << an_indexing.begin()->second << std::endl;\n\n        // test constructors\n        DataFrame df;       // default\n        DataFrame df1 = df; // trivial\n        DataFrame dfY = Y;  // assignment\n        df = Y;\n        DataFrame dfX = X;\n\n        DataFrame df_copy(X);              // copy\n        std::cout << df_copy << std::endl; // operator<<\n\n        DataFrame df_copy_withindex(X, indexing_from_vector(range(X.rows())),\n                                    indexing_from_vector(range(X.cols()))); // copy\n\n        // construct from given vector of strings\n        std::vector<std::string> labels;\n        labels.push_back(\"patient_1\");\n        labels.push_back(\"patient_2\");\n        labels.push_back(\"patient_3\");\n        labels.push_back(\"patient_3\");\n        Indexing another_indexing;\n        Index i = 0;\n        for (const auto &element : labels)\n        {\n            another_indexing.emplace(element, i++);\n        }\n        std::cout << \"first key of an Indexing\\n\"\n                  << another_indexing.begin()->first << std::endl;\n        DataFrame df_ylabels(Y, another_indexing, an_indexing); // copy\n        std::cout << \"duplicate row labels df\\n\" << df_ylabels << std::endl;\n\n        //// slicing\n        // no such index found\n        try\n        {\n            df_copy[\"no_way_jos\u00e9\"];\n        }\n        catch (...)\n        {\n            std::cout << \"it's ok jos\u00e9\" << std::endl;\n        }\n\n        DataFrame col_slice = df_copy[\"1\"]; // 2nd col\n        std::cout << \"col slice\\n\" << col_slice << std::endl;\n        DataFrame row_slice = df_copy.loc(\"1\"); // 2nd row\n\n        Eigen::MatrixXd row_mat(1, 3);\n        row_mat << 4., 5., 6.;\n        DataFrame df_row_mat(row_mat);\n        row_slice = row_slice - df_row_mat; // some df operation\n        std::cout << \"row slice with substraction\\n\" << row_slice << std::endl;\n        std::cout << \".norm()\\n\" << row_slice.norm() << std::endl;\n\n        std::cout << df_ylabels << std::endl;\n        DataFrame labeled_row = df_ylabels.loc(\"patient_2\"); // 2nd row\n        std::cout << \"a labeled row:\\n\" << labeled_row << std::endl;\n        // duplicate label\n        DataFrame duplicate_row = df_ylabels.loc(\"patient_3\"); // 2nd row\n        std::cout << \"two rows with same label:\\n\"\n                  << duplicate_row << std::endl;\n\n        // chained\n        DataFrame an_element = (df_ylabels.loc(\"patient_2\"))[\"0\"]; // row and col\n        std::cout << \"chained, an element:\\n\" << an_element << std::endl;\n\n        std::vector<std::string> col_vec(2);\n        col_vec.push_back(\"0\");\n        col_vec.push_back(\"2\");\n        DataFrame two_element =\n        df_ylabels.loc(\"patient_2\")[col_vec]; // row and col\n        std::cout << \"chained, a row two elements:\\n\"\n                  << two_element << std::endl;\n\n        Eigen::MatrixXd row_ref(1, 2);\n        row_ref << 4., 6.;\n        std::cout << \"matrix row :\\n\" << row_ref << std::endl;\n\n        DataFrame ref = row_ref;\n        std::cout << \"df row :\\n\" << ref << std::endl;\n\n        Eigen::MatrixXd m;\n        m = ref.matrix(); // protected constructor\n        std::cout << \"get plain matrix back :\\n\"\n                  << m << std::endl; // no indexing\n        assert((ref.norm() == row_ref.norm()) && \" norm on df \");\n\n        assert(((two_element - row_ref).norm() == 0.0) &&\n               \"matrix operation on DF and matrix\");\n        assert(((two_element - ref).norm() == 0.0) &&\n               \"matrix operation on DFs\");\n\n        // multiplication, lin. kernel\n        Eigen::Matrix<double, 2, 2> K_lin_ref;\n        K_lin_ref << 1., 4., 4., 16.;\n        Eigen::SparseMatrix<double> L(3, 3);\n        L.insert(0, 0) = 1.;\n        assert(\n        (((dfX * L.selfadjointView<Eigen::Lower>() * dfX.adjoint()) - K_lin_ref)\n         .norm() == 0.0) &&\n        \"df multiplication / linear kernel directly\");\n\n        return EXIT_SUCCESS;\n    }\n    catch (const std::exception &e)\n    {\n        std::cerr << e.what();\n        return EXIT_FAILURE;\n    }\n}\n", "meta": {"hexsha": "44c6a296d427048cd6e409f735120e572b1f5665", "size": 5037, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/data_frame/main.cpp", "max_stars_repo_name": "vishalbelsare/mimkl", "max_stars_repo_head_hexsha": "53a5a9db5aa09c6e8808ba5b845601c5768d23e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2019-05-28T23:18:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T20:00:03.000Z", "max_issues_repo_path": "test/data_frame/main.cpp", "max_issues_repo_name": "vishalbelsare/mimkl", "max_issues_repo_head_hexsha": "53a5a9db5aa09c6e8808ba5b845601c5768d23e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2019-05-18T13:21:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T22:20:55.000Z", "max_forks_repo_path": "test/data_frame/main.cpp", "max_forks_repo_name": "vishalbelsare/mimkl", "max_forks_repo_head_hexsha": "53a5a9db5aa09c6e8808ba5b845601c5768d23e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2019-07-24T09:39:41.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-29T14:40:27.000Z", "avg_line_length": 34.7379310345, "max_line_length": 83, "alphanum_fraction": 0.5372245384, "num_tokens": 1327, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867681382279, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4790624067520886}}
{"text": "/* Copyright (c) 2016, the Cap authors.\n *\n * This file is subject to the Modified BSD License and may not be distributed\n * without copyright and license information. Please refer to the file LICENSE\n * for the text and further information on this license.\n */\n\n#define BOOST_TEST_MODULE DistributedEnergyStorage\n\n#include \"main.cc\"\n\n#include <cap/energy_storage_device.h>\n#include <cap/mp_values.h>\n#include <deal.II/base/types.h>\n#include <deal.II/grid/grid_generator.h>\n#include <deal.II/dofs/dof_handler.h>\n#include <boost/test/unit_test.hpp>\n#include <boost/format.hpp>\n#include <boost/property_tree/ptree.hpp>\n#include <boost/property_tree/info_parser.hpp>\n#include <cmath>\n#include <iostream>\n#include <fstream>\n#include <numeric>\n\nnamespace cap\n{\n\nvoid distributed_problem(std::shared_ptr<cap::EnergyStorageDevice> dev)\n{\n  double const charge_current = 5e-3;\n  // This is the values computed using one processor\n  double const exact_voltage = 0.24307431815;\n  double const time_step = 1e-2;\n  double const percent_tolerance = 1e-2;\n  double computed_voltage;\n  double computed_current;\n  for (unsigned int i = 0; i < 3; ++i)\n    dev->evolve_one_time_step_constant_current(time_step, charge_current);\n  dev->get_current(computed_current);\n  dev->get_voltage(computed_voltage);\n\n  BOOST_CHECK_CLOSE(computed_voltage, exact_voltage, percent_tolerance);\n  BOOST_CHECK_CLOSE(computed_current, charge_current, percent_tolerance);\n}\n}\n\nBOOST_AUTO_TEST_CASE(test_distributed_energy_storage)\n{\n  // Parse input file\n  boost::property_tree::ptree device_database;\n  boost::property_tree::info_parser::read_info(\"super_capacitor.info\",\n                                               device_database);\n  boost::property_tree::ptree geometry_database;\n  boost::property_tree::info_parser::read_info(\"generate_mesh.info\",\n                                               geometry_database);\n  device_database.put_child(\"geometry\", geometry_database);\n\n  std::shared_ptr<cap::EnergyStorageDevice> device =\n      cap::EnergyStorageDevice::build(device_database,\n                                      boost::mpi::communicator());\n\n  cap::distributed_problem(device);\n}\n", "meta": {"hexsha": "c4e8c1c6e972d8d5640b694dfb065c76196f66c2", "size": 2160, "ext": "cc", "lang": "C++", "max_stars_repo_path": "cpp/test/test_distributed_energy_storage.cc", "max_stars_repo_name": "iiscsahoo/EnergyData", "max_stars_repo_head_hexsha": "6230145b5df6b126eab11aea58a5cfaa11ad5ba1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2016-05-15T11:42:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-27T19:33:04.000Z", "max_issues_repo_path": "cpp/test/test_distributed_energy_storage.cc", "max_issues_repo_name": "iiscsahoo/EnergyData", "max_issues_repo_head_hexsha": "6230145b5df6b126eab11aea58a5cfaa11ad5ba1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 198.0, "max_issues_repo_issues_event_min_datetime": "2016-01-27T16:46:59.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-11T06:31:37.000Z", "max_forks_repo_path": "cpp/test/test_distributed_energy_storage.cc", "max_forks_repo_name": "iiscsahoo/EnergyData", "max_forks_repo_head_hexsha": "6230145b5df6b126eab11aea58a5cfaa11ad5ba1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2016-01-27T15:17:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-15T02:06:50.000Z", "avg_line_length": 33.2307692308, "max_line_length": 78, "alphanum_fraction": 0.7314814815, "num_tokens": 474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125848754471, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.4790551847666439}}
{"text": "/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n#include <lagrange/testing/common.h>\n\n#include <lagrange/utils/geometry2d.h>\n#include <Eigen/Core>\n\nTEST_CASE(\"utils-geometry2d\")\n{\n    using namespace lagrange;\n    using Vec2 = Eigen::Vector2d;\n\n\n    REQUIRE(sqr_minimum_distance(Vec2(0, 0), Vec2(0, 1), Vec2(0, 0)) == 0.0);\n    REQUIRE(sqr_minimum_distance(Vec2(0, 0), Vec2(0, 1), Vec2(0, 1)) == 0.0);\n    REQUIRE(sqr_minimum_distance(Vec2(0, 0), Vec2(0, 1), Vec2(0, .5)) == 0.0);\n\n    REQUIRE(sqr_minimum_distance(Vec2(0, 0), Vec2(0, 1), Vec2(1, 0)) == (1 * 1));\n    REQUIRE(sqr_minimum_distance(Vec2(0, 0), Vec2(0, 1), Vec2(1, .2)) == (1 * 1));\n\n    REQUIRE(sqr_minimum_distance(Vec2(0, 0), Vec2(0, 1), Vec2(0, -1)) == (1 * 1));\n    REQUIRE(sqr_minimum_distance(Vec2(0, 0), Vec2(0, 1), Vec2(0, 2)) == (1 * 1));\n    REQUIRE(sqr_minimum_distance(Vec2(0, 0), Vec2(0, 1), Vec2(0, 3)) == (2 * 2));\n\n    REQUIRE(sqr_minimum_distance(Vec2(0, 0), Vec2(1, 1), Vec2(0, 1)) == .5);\n}\n", "meta": {"hexsha": "49f3fddbdd141ded42e7f1a74db4dda54c32dbdf", "size": 1547, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/core/tests/test_utils_geometry2d.cpp", "max_stars_repo_name": "LaudateCorpus1/lagrange", "max_stars_repo_head_hexsha": "2a49d3ee93c1f1e712c93c5c87ea25b9a83c8f40", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 156.0, "max_stars_repo_stars_event_min_datetime": "2021-01-08T19:53:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T18:32:52.000Z", "max_issues_repo_path": "modules/core/tests/test_utils_geometry2d.cpp", "max_issues_repo_name": "LaudateCorpus1/lagrange", "max_issues_repo_head_hexsha": "2a49d3ee93c1f1e712c93c5c87ea25b9a83c8f40", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-01-11T20:18:07.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-04T15:53:57.000Z", "max_forks_repo_path": "modules/core/tests/test_utils_geometry2d.cpp", "max_forks_repo_name": "LaudateCorpus1/lagrange", "max_forks_repo_head_hexsha": "2a49d3ee93c1f1e712c93c5c87ea25b9a83c8f40", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2021-01-11T21:03:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-24T06:27:44.000Z", "avg_line_length": 42.9722222222, "max_line_length": 89, "alphanum_fraction": 0.6703296703, "num_tokens": 514, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125848754471, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.4790551847666439}}
{"text": "#include<iostream>\n#include <armadillo>\n\nusing namespace std;\nusing namespace arma;\n\nvoid testing_armadillo(void);\n\nint main(int argc, char* argv[])\n{\n\n\n\n\ttesting_armadillo();\n\n\n\n\treturn 0;\n}\n\n\nvoid testing_armadillo(void)\n{\n\tcout<<endl<<\"Testing armadillo::mat\"<<endl<<endl;\n\n\tmat A(4, 5, fill::randu);\n\tmat B(4, 5, fill::randn);\n\n\tcout<<\"A = \"<<A<<endl;\n\tcout<<\"B = \"<<B<<endl;\n\n\tcout<<\"A*B.t() = \"<<A*B.t()<<endl;\n\n}\n\n", "meta": {"hexsha": "0104463b2631ddbfc86f31f356d88ea477ffc007", "size": 421, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/cmake_arma/testing_armadillo.cpp", "max_stars_repo_name": "fit087/displacement_method_of_analysis", "max_stars_repo_head_hexsha": "37e35c7387ddedbb0a4f3ba3f5a4bcfa3af2d215", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-02-28T22:57:25.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-28T22:57:25.000Z", "max_issues_repo_path": "test/cmake_arma/testing_armadillo.cpp", "max_issues_repo_name": "fit087/displacement_method_of_analysis", "max_issues_repo_head_hexsha": "37e35c7387ddedbb0a4f3ba3f5a4bcfa3af2d215", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T00:16:20.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-22T09:23:32.000Z", "max_forks_repo_path": "test/cmake_arma/testing_armadillo.cpp", "max_forks_repo_name": "fit087/displacement_method_of_analysis", "max_forks_repo_head_hexsha": "37e35c7387ddedbb0a4f3ba3f5a4bcfa3af2d215", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 11.6944444444, "max_line_length": 50, "alphanum_fraction": 0.6199524941, "num_tokens": 128, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7520125848754472, "lm_q2_score": 0.6370308013713524, "lm_q1q2_score": 0.4790551795845483}}
{"text": "#include <walrus_stair_detector/walrus_stair_detector.h>\n#include <pcl/io/io.h>\n#include <pcl/io/pcd_io.h>\n#include <gtest/gtest.h>\n#include \"yaml-cpp/yaml.h\"\n#include <boost/filesystem.hpp>\n\nstd::string pcd_file;\nstd::string config_file;\n\nnamespace YAML {\ntemplate<>\nstruct convert<Eigen::Vector3f> {\n  static bool decode(const YAML::Node& node, Eigen::Vector3f& rhs) {\n    if(!node.IsSequence() || node.size() != 3) {\n      return false;\n    }\n\n    rhs[0] = node[0].as<double>();\n    rhs[1] = node[1].as<double>();\n    rhs[2] = node[2].as<double>();\n    return true;\n  }\n};\n}\n\n#define EXPECT_VECTOR_ANGLE_LE(val1, val2, max_angle)\t\t\t\\\n  do {\t\t\t\t\t\t\t\t\t\\\n    Eigen::Vector3f val1_norm = val1.normalized();\t\t\t\\\n    Eigen::Vector3f val2_norm = val2.normalized();\t\t\t\\\n    if(val1_norm != val2_norm) {\t\t\t\t\t\\\n      double angle = acos(val1_norm.dot(val2_norm));\t\t\t\\\n      EXPECT_LE(fabs(angle), max_angle)\t\t\t\t\t\\\n\t<< \"Expected angle between \"\t\t\t\t\t\\\n\t<< \"[\" << val1[0] << \", \" << val1[1] << \", \" << val1[2] << \"]\"\t\\\n\t<< \" and [\" << val2[0] << \", \" << val2[1] << \", \" << val2[2] << \"]\" \\\n\t<< \" <= \" << max_angle << \", but was \" << angle;\t\t\\\n    }\t\t\t\t\t\t\t\t\t\\\n  } while(0)\n\n#define EXPECT_VECTOR_NEAR(val1, val2, abs_error)\t\t\t\\\n  do {\t\t\t\t\t\t\t\t\t\\\n    double error = (val1 - val2).norm();\t\t\t\t\\\n    EXPECT_LE(error, abs_error)\t\t\t\t\t\t\\\n      << \"Expected error between \"\t\t\t\t\t\\\n      << \"[\" << val1[0] << \", \" << val1[1] << \", \" << val1[2] << \"]\"\t\\\n      << \" and [\" << val2[0] << \", \" << val2[1] << \", \" << val2[2] << \"]\" \\\n      << \" <= \" << abs_error << \", but was \" << error;\t\t\t\\\n  } while(0)\n\nstruct StairDetectorTestData {\n  StairDetectorTestData(std::string pcd_file, std::string config_file) : pcd_file(pcd_file), config_file(config_file) {}\n  std::string pcd_file;\n  std::string config_file;\n};\nvoid PrintTo(const StairDetectorTestData& data, ::std::ostream* os) {\n  *os << \"PCD File: \" << data.pcd_file << \", Config File: \" << data.config_file;\n}\n\nclass StairDetectorTest : public ::testing::TestWithParam<StairDetectorTestData> {};\n\n\nTEST_P(StairDetectorTest, detectStairs) {\n  pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>);\n  pcl::io::loadPCDFile(GetParam().pcd_file, *cloud);\n\n  YAML::Node config = YAML::LoadFile(GetParam().config_file);\n  YAML::Node sensor_config = config[\"sensor\"];\n  YAML::Node stairs_config = config[\"stairs\"];\n\n  Eigen::Vector3f vertical_estimate = sensor_config[\"vertical\"].as<Eigen::Vector3f>();\n\n  walrus_stair_detector::WalrusStairDetector detector;\n  std::vector<walrus_stair_detector::StairModel> stairs;\n  detector.detect(cloud, vertical_estimate, &stairs);\n\n  ASSERT_EQ(stairs_config.size(), stairs.size());\n\n  for(int i = 0; i < stairs.size(); ++i) {\n    YAML::Node stair_config = stairs_config[i];\n    walrus_stair_detector::StairModel& stair = stairs[i];\n    EXPECT_NEAR(stair_config[\"rise\"].as<double>(), stair.rise, 0.012);\n    EXPECT_NEAR(stair_config[\"run\"].as<double>(), stair.run, 0.008);\n\n    EXPECT_VECTOR_ANGLE_LE(stair_config[\"direction\"].as<Eigen::Vector3f>(), stair.direction, 0.05);\n\n    Eigen::Vector3f expected_origin = stair_config[\"origin\"].as<Eigen::Vector3f>();\n\n    double expected_x = expected_origin.dot(stair.horizontal);\n    double expected_y = expected_origin.dot(stair.vertical);\n    double expected_z = expected_origin.dot(stair.direction);\n\n    double actual_x = stair.origin.dot(stair.horizontal);\n    double actual_y = stair.origin.dot(stair.vertical);\n    double actual_z = stair.origin.dot(stair.direction);\n\n    // Expect the horizontal component to be less accurate\n    EXPECT_NEAR(expected_x, actual_x, 0.14);\n\n    double max_origin_center_error = 0.045;\n    Eigen::Vector3f expected_origin_center(0, expected_y, expected_z);\n    Eigen::Vector3f origin_center(0, actual_y, actual_z);\n    if(stair_config[\"can_miss_first_stair\"].IsDefined() && stair_config[\"can_miss_first_stair\"].as<bool>()){\n      Eigen::Vector3f upper_origin_center(0, actual_y - stair.rise, actual_z - stair.run);\n      if((expected_origin_center - upper_origin_center).norm() <= max_origin_center_error)\n\tEXPECT_VECTOR_NEAR(expected_origin_center, upper_origin_center, max_origin_center_error);\n      else\n\tEXPECT_VECTOR_NEAR(expected_origin_center, origin_center, max_origin_center_error);\n    }\n    else {\n      EXPECT_VECTOR_NEAR(expected_origin_center, origin_center, max_origin_center_error);\n    }\n\n    EXPECT_GE(stair_config[\"width\"].as<double>(), stair.width);\n    EXPECT_LE(stair_config[\"width\"].as<double>()-0.17, stair.width);\n\n    if(stair_config[\"num_stairs\"].IsScalar()) {\n      EXPECT_EQ(stair_config[\"num_stairs\"].as<int>(), stair.num_stairs);\n    }\n    else {\n      EXPECT_LE(stair_config[\"num_stairs\"][0].as<int>(), stair.num_stairs);\n      EXPECT_GE(stair_config[\"num_stairs\"][1].as<int>(), stair.num_stairs);\n    }\n  }\n}\n\nstd::string find_package(const std::string& package, const std::string& path) {\n  std::stringstream command;\n  command << \"catkin_find \" << package << \" \" << path;\n\n  char buf[1000];\n  FILE *fp = popen(command.str().c_str(), \"r\");\n  if (fp == NULL) {\n    return \"\";\n  }\n\n  std::string result;\n  while (fgets(buf, sizeof(buf), fp) != NULL) {\n    result = buf;\n    break;\n  }\n\n  if(result.size() > 0 && result[result.size()-1] == '\\n')\n    result = result.substr(0, result.size()-1);\n\n  pclose(fp);\n  return result;\n}\n\nstd::vector<StairDetectorTestData> GenerateStairDetectorParameterList() {\n  std::vector<StairDetectorTestData> data;\n  std::string testdata_root_string = find_package(\"walrus_testdata\", \"kinectv2/stairs\");\n\n  if(testdata_root_string.size() > 0) {\n    boost::filesystem::path testdata_root (testdata_root_string);\n    std::cout << \"Searching for test data in: \" << testdata_root << std::endl;\n    if(!boost::filesystem::is_directory(testdata_root))\n      throw new std::runtime_error(\"Test data path is not a directory\");\n\n    boost::filesystem::directory_iterator end;\n    for(boost::filesystem::directory_iterator itr(testdata_root); itr != end; ++itr) {\n      boost::filesystem::path test_collection = itr->path();\n      std::cout << \"\\tFound test collection: \" << test_collection.filename() << std::endl;\n\n      boost::filesystem::path test_collection_description = test_collection;\n      test_collection_description/=\"description.yaml\";\n      if(boost::filesystem::exists(test_collection_description)){\n\tfor(boost::filesystem::directory_iterator itr2(test_collection); itr2 != end; ++itr2) {\n\t  if(itr2->path().extension() == \".pcd\") {\n\t    std::cout << \"\\t\\tFound test: \" << itr2->path().filename() << std::endl;\n\t    data.push_back(StairDetectorTestData(itr2->path().native(), test_collection_description.native()));\n\t  }\n\t}\n      }\n      else\n\tstd::cout << \"Did not find test description: \" << test_collection_description << std::endl;\n    }\n\n  }\n  else\n    throw new std::runtime_error(\"Could not find test data folder in walrus_testdata\");\n  return data;\n}\nINSTANTIATE_TEST_CASE_P(\n\t\t\tStairTestData,\n\t\t\tStairDetectorTest,\n\t\t\ttesting::ValuesIn(GenerateStairDetectorParameterList()));\n\nint main(int argc, char** argv)\n{\n  testing::InitGoogleTest(&argc, argv);\n\n  return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "d3fe51096a18597802064c6db3a71b4e4c53b712", "size": 7121, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "walrus_stair_detector/test/stair_detector_test.cpp", "max_stars_repo_name": "RIVeR-Lab/walrus", "max_stars_repo_head_hexsha": "28d285cec8e181e9300fdd9a82a299c7c025f32e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2015-03-04T22:48:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-18T11:57:53.000Z", "max_issues_repo_path": "walrus_stair_detector/test/stair_detector_test.cpp", "max_issues_repo_name": "RIVeR-Lab/walrus", "max_issues_repo_head_hexsha": "28d285cec8e181e9300fdd9a82a299c7c025f32e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 52.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T05:50:10.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-23T20:34:50.000Z", "max_forks_repo_path": "walrus_stair_detector/test/stair_detector_test.cpp", "max_forks_repo_name": "RIVeR-Lab/walrus", "max_forks_repo_head_hexsha": "28d285cec8e181e9300fdd9a82a299c7c025f32e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2015-08-24T10:05:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-18T11:58:03.000Z", "avg_line_length": 36.5179487179, "max_line_length": 120, "alphanum_fraction": 0.6670411459, "num_tokens": 1921, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.4790551776856325}}
{"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.\r\n *\r\n *    References\r\n *    Hameduddin, I. Rotate vector(s) about axis, rodrigues_rot.m, available at\r\n *        http://www.mathworks.com/matlabcentral/fileexchange/34426-rotate-vectors-about-axis,\r\n *        2012, last accessed: 11th January, 2014.\r\n *    Murray, G. Rotation Matrices and Formulas java script, RotationMatrix.java available at\r\n *        https://sites.google.com/site/glennmurray/Home/rotation-matrices-and-formulas, 2011.\r\n *        last accessed: 20th January, 2014.\r\n *\r\n */\r\n\r\n#define BOOST_TEST_MAIN\r\n\r\n#include <boost/test/floating_point_comparison.hpp>\r\n#include <boost/test/unit_test.hpp>\r\n\r\n#include <Eigen/Core>\r\n\r\n#include \"Tudat/Basics/testMacros.h\"\r\n#include \"Tudat/Mathematics/BasicMathematics/mathematicalConstants.h\"\r\n\r\n#include \"Tudat/Mathematics/BasicMathematics/rotationAboutArbitraryAxis.h\"\r\n\r\nnamespace tudat\r\n{\r\nnamespace unit_tests\r\n{\r\n\r\n//! Test suite for rotations about about arbitrary axes.\r\nBOOST_AUTO_TEST_SUITE( test_RotationAboutArbitraryAxis )\r\n\r\nBOOST_AUTO_TEST_CASE( test_RotationAboutArbitraryAxis_PointRotationWithCommonOrigin )\r\n{\r\n\r\n    //Benchmark data is obtained using Matlab Script (Hameduddin, 2012).\r\n\r\n    //Set expected rotated vector.\r\n    const Eigen::Vector3d expectedRotatedPosition = Eigen::Vector3d( 0.0, 1.414213562373095, 1.0 );\r\n\r\n    //Set origin of rotation.\r\n    const Eigen::Vector3d originOfRotation = Eigen::Vector3d( 0.0, 0.0, 0.0 );\r\n\r\n    //Set angle of rotation [rad].\r\n    const double angleOfRotation = mathematical_constants::PI / 4.0;\r\n\r\n    //Set axis of rotation.\r\n    const Eigen::Vector3d axisOfRotation = Eigen::Vector3d( 0.0, 0.0, 1.0 );\r\n\r\n    //Set initial position of point.\r\n    const Eigen::Vector3d initialPositionOfPoint = Eigen::Vector3d( 1.0, 1.0, 1.0 );\r\n\r\n    //Compute rotated position.\r\n    const Eigen::Vector3d computedRotatedPosition = basic_mathematics::\r\n        computeRotationOfPointAboutArbitraryAxis( originOfRotation, angleOfRotation,\r\n                                                  axisOfRotation, initialPositionOfPoint );\r\n\r\n    // Compare computed and expected vectors.\r\n    BOOST_CHECK_SMALL( computedRotatedPosition.x( ), std::numeric_limits< double >::epsilon( ) );\r\n\r\n    TUDAT_CHECK_MATRIX_CLOSE_FRACTION( computedRotatedPosition.segment( 1, 2 ),\r\n                                       expectedRotatedPosition.segment( 1, 2),\r\n                                       std::numeric_limits< double >::epsilon( ) );\r\n\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE( test_RotationAboutArbitraryAxis_PointRotationWithDifferentOrigins )\r\n{\r\n\r\n    //Benchmark data is obtained using java script (Murray, 2013).\r\n\r\n    //Set expected rotated vector.\r\n    const Eigen::Vector3d expectedRotatedPosition = Eigen::Vector3d( 3.156561876696307,\r\n                                                                     -5.97145870839039,\r\n                                                                     -4.418680390057799 );\r\n    //Set origin of rotation.\r\n    const Eigen::Vector3d originOfRotation = Eigen::Vector3d( 4.0, 1.0, -1.0 );\r\n\r\n    //Set angle of rotation [rad]\r\n    const double angleOfRotation = 7.0;\r\n\r\n    //Set axis of rotation.\r\n    const Eigen::Vector3d axisOfRotation = Eigen::Vector3d( 2.0, -2.0, 3.0 );\r\n\r\n    //Set initial position of point.\r\n    const Eigen::Vector3d initialPositionOfPoint = Eigen::Vector3d( -1.0, -5.0, -1.0 );\r\n\r\n    //Compute rotated position.\r\n    const Eigen::Vector3d computedRotatedPosition = basic_mathematics::\r\n        computeRotationOfPointAboutArbitraryAxis( originOfRotation,  angleOfRotation,\r\n                                                  axisOfRotation, initialPositionOfPoint );\r\n\r\n    // Compare computed and expected radiation pressure acceleration vectors.\r\n    TUDAT_CHECK_MATRIX_CLOSE_FRACTION( computedRotatedPosition,\r\n                                       expectedRotatedPosition,\r\n                                       std::numeric_limits<double>::epsilon( ) );\r\n\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE( test_RotationAboutArbitraryAxis_PointRotationWithDifferentOrigins2 )\r\n{\r\n\r\n    //Benchmark data is obtained using java script (Murray, 2013).\r\n\r\n    //Set expected rotated vector.\r\n    const Eigen::Vector3d expectedRotatedPosition = Eigen::Vector3d( 15.71267522236938,\r\n                                                                     -0.9723168350942417,\r\n                                                                      9.449538267504582 );\r\n    //Set origin of rotation.\r\n    const Eigen::Vector3d originOfRotation = Eigen::Vector3d( 1.5, 3.8, 12.0 );\r\n\r\n    //Set angle of rotation [rad]\r\n    const double angleOfRotation = 3.0;\r\n\r\n    //Set axis of rotation.\r\n    const Eigen::Vector3d axisOfRotation = Eigen::Vector3d( -4.6, 6.75, 7.7 );\r\n\r\n    //Set initial position of point.\r\n    const Eigen::Vector3d initialPositionOfPoint = Eigen::Vector3d( -4.3, -5.2, 1.2 );\r\n\r\n    //Compute rotated position.\r\n    const Eigen::Vector3d computedRotatedPosition = basic_mathematics::\r\n        computeRotationOfPointAboutArbitraryAxis( originOfRotation, angleOfRotation,\r\n                                                  axisOfRotation, initialPositionOfPoint );\r\n\r\n    // Compare computed and expected radiation pressure acceleration vectors.\r\n    TUDAT_CHECK_MATRIX_CLOSE_FRACTION( computedRotatedPosition, expectedRotatedPosition, 1.0e-14 );\r\n\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE( test_RotationAboutArbitraryAxis_VectorRotationWithCommonOrigin )\r\n{\r\n\r\n    //Benchmark data is obtained using Matlab Script (Hameduddin, 2012).\r\n\r\n    //Set expected rotated vector.\r\n    const Eigen::Vector3d expectedRotatedVector = Eigen::Vector3d( -5.480598288892924,\r\n                                                                    0.532794739754852,\r\n                                                                    6.138336269794405 );\r\n    //Set origin of rotation.\r\n    const Eigen::Vector3d originOfRotation = Eigen::Vector3d( 0.0, 0.0, 0.0 );\r\n\r\n    //Set angle of rotation [rad].\r\n    const double angleOfRotation = 12.0;\r\n\r\n    //Set axis of rotation.\r\n    const Eigen::Vector3d axisOfRotation = Eigen::Vector3d( -1.0, -2.0, -3.0 );\r\n\r\n    //Set initial position of vector tail.\r\n    const Eigen::Vector3d initialPositionOfVectorTail = Eigen::Vector3d( 1.0, 3.0, 5.0 );\r\n\r\n    //Set initial vector.\r\n    const Eigen::Vector3d initialVector = Eigen::Vector3d( -6.0, 4.0, 4.0 );\r\n\r\n    //Compute rotated position.\r\n    const Eigen::Vector3d computedRotatedVector = basic_mathematics::\r\n        computeRotationOfVectorAboutArbitraryAxis( originOfRotation, angleOfRotation,\r\n                                                   axisOfRotation, initialPositionOfVectorTail,\r\n                                                   initialVector );\r\n\r\n    // Compare computed and expected radiation pressure acceleration vectors\r\n    TUDAT_CHECK_MATRIX_CLOSE_FRACTION( computedRotatedVector, expectedRotatedVector, 1.0e-14 );\r\n\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE( test_RotationAboutArbitraryAxis_VectorRotationWithDifferentOrigins )\r\n{\r\n\r\n    //Benchmark data is obtained using java script (Murray, 2013).\r\n\r\n    //Set expected rotated vector.\r\n    const Eigen::Vector3d expectedRotatedVector = Eigen::Vector3d( -7.15233485964669,\r\n                                                                   -2.4444137866784175,\r\n                                                                    8.308967883857736 );\r\n    //Set origin of rotation.\r\n    const Eigen::Vector3d originOfRotation = Eigen::Vector3d( 1.5, 3.8, 12.0 );\r\n\r\n    //Set angle of rotation [rad].\r\n    const double angleOfRotation = 3.0;\r\n\r\n    //Set axis of rotation.\r\n    const Eigen::Vector3d axisOfRotation = Eigen::Vector3d( -4.6, 6.75, 7.7 );\r\n\r\n    //Set initial position of vector tail.\r\n    const Eigen::Vector3d initialPositionOfVectorTail = Eigen::Vector3d( -4.3, -5.2, 1.2 );\r\n\r\n    //Set initial vector.\r\n    const Eigen::Vector3d initialVector = Eigen::Vector3d( 0.3, 11.2, 0.8 );\r\n\r\n    //Compute rotated position.\r\n    const Eigen::Vector3d computedRotatedVector = basic_mathematics::\r\n        computeRotationOfVectorAboutArbitraryAxis( originOfRotation, angleOfRotation,\r\n                                                   axisOfRotation, initialPositionOfVectorTail,\r\n                                                   initialVector );\r\n\r\n  // Compare computed and expected rotated vectors.\r\n  TUDAT_CHECK_MATRIX_CLOSE_FRACTION( computedRotatedVector, expectedRotatedVector, 1.0e-14 );\r\n\r\n}\r\n\r\nBOOST_AUTO_TEST_SUITE_END( )\r\n\r\n} // namespace unit_tests\r\n} // namespace tudat\r\n", "meta": {"hexsha": "0c42dfae051cff87fe30e04d85cdbf3ee96563a4", "size": 8920, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Mathematics/BasicMathematics/UnitTests/unitTestRotationAboutArbitraryAxis.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/Mathematics/BasicMathematics/UnitTests/unitTestRotationAboutArbitraryAxis.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/Mathematics/BasicMathematics/UnitTests/unitTestRotationAboutArbitraryAxis.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": 42.0754716981, "max_line_length": 100, "alphanum_fraction": 0.6381165919, "num_tokens": 2124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125848754471, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.4790551744024527}}
{"text": "#include <iostream>\n#include <cmath>\n#include <vector>\n#include <chrono>\n#include <memory>\n#include <thread>\n#include <random>\n#include <limits>\n#include <boost/range/irange.hpp>\n#include <Eigen/Dense>\n#include \"GPs.h\"\n\n// Retrieve aliases from GP namescope\nusing Matrix = GP::Matrix;\nusing Vector = GP::Vector;\n\n\n// Compute pairwise distance between lists of points\nvoid GP::pdist(Matrix & Dv, Matrix & X1, Matrix & X2)\n{\n  auto n = static_cast<int>(X1.rows());\n  auto entryCount = static_cast<int>( (n*(n-1))/2);\n  Dv.resize(entryCount, 1);\n\n  // Get thread count\n  int threadCount = Eigen::nbThreads( );\n      \n  // Get problem dimension d per thread\n  auto d = static_cast<int>(n/threadCount);\n  \n  std::vector<int> startVals;\n  for ( auto i : boost::irange(0,threadCount) )\n    startVals.emplace_back(i*d);\n\n  std::vector<int> endVals;\n  for ( auto i : boost::irange(1,threadCount) )\n    endVals.emplace_back(i*d);\n  endVals.emplace_back(n-1);\n\n  // Define lambda function specifying each threads solver task\n  auto lambda = [&Dv,&X1,&X2,n](int startInd, int endInd) {\n                  for ( auto i : boost::irange(startInd, endInd) )\n                    {      \n                      for ( auto j : boost::irange(i+1,n) )\n                        Dv(static_cast<int>(i*n-(i*(i+1))/2+j-i-1), 0) = (static_cast<Vector>(X1.row(i)-X2.row(j))).squaredNorm();\n                    }\n                };\n\n  // Initialize thread list\n  std::vector<std::thread> threadList;\n\n  // Assign tasks to threads\n  for ( auto i : boost::irange(0,threadCount) )\n    threadList.emplace_back(lambda,startVals[i],endVals[i]);\n\n  // Join threads\n  for ( auto & thread : threadList )\n    thread.join();\n\n  \n}\n\n// Re-assemble pairwise distances into a dense matrix\nvoid GP::squareForm(Matrix & D, Matrix & Dv, int n, double diagVal)\n{\n  D.resize(n,n);\n\n  // Get thread count\n  int threadCount = Eigen::nbThreads( );\n      \n  // Get problem dimension d per thread\n  auto d = static_cast<int>(n/threadCount);\n  \n  std::vector<int> startVals;\n  for ( auto i : boost::irange(0,threadCount) )\n    startVals.emplace_back(i*d);\n\n  std::vector<int> endVals;\n  for ( auto i : boost::irange(1,threadCount) )\n    endVals.emplace_back(i*d);\n  endVals.emplace_back(n-1);\n\n  // Define lambda function specifying each threads solver task\n  auto lambda = [&D,&Dv,n](int startInd, int endInd) {\n                  for ( auto i : boost::irange(startInd,endInd) )\n                    {\n                      for ( auto j : boost::irange(i+1, n) )\n                       D(i,j) = D(j,i) = Dv(static_cast<int>(i*n-(i*(i+1))/2+j-i-1), 0);\n                    }\n                };\n\n  // Initialize thread list\n  std::vector<std::thread> threadList;\n\n  // Assign tasks to threads\n  for ( auto i : boost::irange(0,threadCount) )\n    threadList.emplace_back(lambda,startVals[i],endVals[i]);\n\n  // Join threads\n  for ( auto & thread : threadList )\n    thread.join();\n\n  \n  // Add diagonal values to distance matrix\n  D.diagonal() = diagVal * Eigen::MatrixXd::Ones(n,1);\n}\n\n\n// Parse kernel parameter vector, separating noise from the kernel hyperparameters\nvoid GP::Kernel::parseParams(const Vector & params, Vector & kernelParams, std::vector<double> & nonKernelParams)\n{\n  if ( !fixedNoise )\n    {\n      // Noise = params(0)\n      nonKernelParams.emplace_back(params(0));\n      if ( !fixedScaling )\n        nonKernelParams.emplace_back(params(1));\n      else\n        nonKernelParams.emplace_back(scalingLevel);\n    }\n  else\n    {\n      // Scaling = params(0)\n      nonKernelParams.emplace_back(noiseLevel);\n      if ( !fixedScaling )\n        nonKernelParams.emplace_back(params(0));\n      else\n        nonKernelParams.emplace_back(scalingLevel);\n    }\n\n  // Trim kernel parameter vector\n  kernelParams = params.tail(paramCount);\n\n}\n\n// Compute covariance matrix (and gradients) from a vector of squared pairwise distances Dv\nvoid GP::RBF::computeCov(Matrix & K, Matrix & obsX, Vector & params, std::vector<Matrix> & gradList, double jitter, bool evalGrad)\n{\n  auto n = static_cast<int>(K.rows());\n\n  // Separate noise and scaling parameters from kernel hyperparameters\n  Vector kernelParams;\n  std::vector<double> noiseAndScaling;\n  parseParams(params, kernelParams, noiseAndScaling);\n  double noise = noiseAndScaling[0];\n  double scaling = noiseAndScaling[1];\n  \n  // Compute distance matrix for each call\n  Matrix Dv;\n  pdist(Dv, obsX, obsX);\n\n  // Evaluate covariance kernel on pairwise distance vector\n  Matrix Kv;\n  Kv.noalias() = scaling * ( (-0.5 / std::pow(kernelParams(0),2)) * Dv ).array().exp().matrix();\n\n  // Make sure not to scale the jitter and noise terms\n  squareForm(K, Kv, n, scaling*1.0 + jitter + noise);\n\n  // Compute gradients w.r.t. kernel hyperparameters\n  if ( evalGrad )\n    {\n      // Prepend gradient list with scaling term\n      //int index = 0;\n      //if (!fixedScaling)\n      //  {\n      //    Matrix dK_scaling;\n      //    squareForm(dK_scaling, Kv, n, -noise);\n      //    gradList[index++] = dK_scaling;\n      //  }\n      \n      Matrix dK_i;\n      Matrix dK_iv;\n      dK_iv.noalias() = 1/std::pow(kernelParams(0),2) * ( Dv.array() * Kv.array() ).matrix();\n      squareForm(dK_i, dK_iv, n); // Note: diagVal = 0.0\n      gradList[0] = dK_i.eval();\n      //gradList[index] = dK_i.eval();\n    }\n\n};\n\n\n// Define distance kernel function for RBF\n// [ Note: Optimize w.r.t. theta = log(l) for stability  ==>   / l^2  instead of  / l^3 ]\ndouble GP::RBF::evalDistKernel(double d, Vector & params, int n)\n{\n  switch (n)\n    {\n    case 0: return std::exp( -d / (2.0*std::pow(params(0),2)));\n    case 1: return d / std::pow(params(0),2) * std::exp( -d / (2.0*std::pow(params(0),2)));\n    default: std::cout << \"\\n[*] UNDEFINED DERIVATIVE\\n\"; return 0.0;\n    }\n};\n\n\n// Compute cross covariance between two input vectors using kernel parameters params\nvoid GP::RBF::computeCrossCov(Matrix & K, Matrix & X1, Matrix & X2, Vector & params)\n{\n  // Get prediction count\n  auto m = static_cast<int>(X2.rows());\n\n   // Define lambda function to create unary operator (by clamping kernelParams argument)      \n  auto lambda = [=,&params](double d)->double { return evalDistKernel(d, params, 0); };\n  for ( auto j : boost::irange(0,m) )\n    {\n      K.col(j) = ((X1.rowwise() - X2.row(j)).rowwise().squaredNorm()).unaryExpr(lambda);          \n    }\n  \n};\n\n\n// Evaluate NLML for specified kernel hyperparameters p\ndouble GP::GaussianProcess::evalNLML(const Vector & p, Vector & g, bool evalGrad)\n{\n  time EVAL_start = high_resolution_clock::now();\n  \n  // Get matrix input observation count\n  auto n = static_cast<int>(obsX.rows());\n\n  // ASSUME OPTIMIZATION OVER LOG VALUES\n  auto params = static_cast<Vector>(p);\n  params = params.array().exp().matrix();\n\n  // Compute covariance matrix and store Cholesky factor\n  Matrix K(n,n);\n  time start = high_resolution_clock::now();\n  (*kernel).computeCov(K, obsX, params, gradList, jitter, evalGrad);\n  time end = high_resolution_clock::now();\n  time_computecov += getTime(start, end);\n\n\n  start = high_resolution_clock::now();\n  Eigen::LLT<Matrix> _cholesky(n);\n  _cholesky = K.llt();\n  end = high_resolution_clock::now();\n  time_cholesky_llt += getTime(start, end);\n\n  start = high_resolution_clock::now();\n  Matrix _alpha = _cholesky.solve(obsY);\n  end = high_resolution_clock::now();\n  time_alpha += getTime(start, end);\n  \n  // Compute NLML value\n  start = high_resolution_clock::now();\n  double NLML_value = (obsY.transpose()*_alpha)(0);\n  NLML_value += n*std::log(2*PI);\n  NLML_value *= 0.5;\n  NLML_value += _cholesky.matrixLLT().diagonal().array().log().sum();\n  end = high_resolution_clock::now();\n  time_NLML += getTime(start, end);\n\n  if ( evalGrad )\n    {\n\n      //\n      // Precompute the multiplicative term in derivative expressions\n      //\n      // [ THIS APPEARS TO BE A COMPUTATIONAL BOTTLE-NECK ]\n      //\n\n      \n      start = high_resolution_clock::now();\n      \n      // Direct Implementation\n      //Matrix term(n,n);\n      //term.noalias() = _cholesky.solve(Matrix::Identity(n,n));\n      //term.noalias() -= _alpha*_alpha.transpose();\n\n      // Using Solve In Place\n      //Matrix term = Matrix::Identity(n,n);\n      //_cholesky.solveInPlace(term);\n      //term.noalias() -= _alpha*_alpha.transpose();\n\n      \n      //\n      //  MULTI-THREADED IMPLEMENTATION\n      //\n      Matrix term = Matrix::Identity(n,n);\n\n      // Get thread count\n      int threadCount = Eigen::nbThreads( );\n      \n      // Get problem dimension d per thread\n      auto d = static_cast<int>(n/threadCount);\n\n      // Construct partitioned list of block terms for solver\n      std::vector<Matrix> termList;      \n      for ( auto i : boost::irange(0,threadCount-1) )\n        termList.emplace_back(term.block(0,i*d,n,d));\n\n      // Ensure the final block extends to column n (i.e. account for index roundoff)\n      termList.emplace_back(term.block(0, (threadCount-1)*d, n, n - (threadCount-1)*d) );\n\n      // Define lambda function specifying each threads solver task\n      auto lambda = [&termList,&_cholesky](int i) { _cholesky.solveInPlace(termList[i]); };\n\n      // Initialize thread list\n      std::vector<std::thread> threadList;\n\n      // Assign tasks to threads\n      for ( auto i : boost::irange(0,threadCount) )\n        threadList.emplace_back(lambda,i);\n\n      // Join threads\n      for ( auto & thread : threadList )\n        thread.join();\n\n      // Reassemble blocks from solver threads back into original matrix\n      for ( auto i : boost::irange(0,threadCount-1) )\n        term.block(0,i*d,n,d) = termList[i];\n      term.block(0, (threadCount-1)*d, n, n - (threadCount-1)*d) = termList[threadCount-1];\n      \n      // Compute final multiplicative term:  K^-1 - alpha*alpha^T\n      term.noalias() -= _alpha*_alpha.transpose();\n\n      \n      end = high_resolution_clock::now();\n      time_term += getTime(start, end);\n\n\n      start = high_resolution_clock::now();      \n      // Compute gradient for noise term if 'fixedNoise=false'\n      int index = 0;\n      double noise;\n      if (!fixedNoise)\n        {\n          // Specify gradient of white noise kernel  [ dK_i = params(0)*Matrix::Identity(n,n) ]\n          //g(index++) = 0.5 * (term * params(0)).trace() ;\n          noise = params(0);\n          g(index) = term.trace();\n          g(index++) *= 0.5 * noise;\n          //g(index++) *= 0.5 * params(0);\n        }\n      else\n        noise = noiseLevel;\n\n      \n      if (!fixedScaling)\n        {\n          if (!fixedNoise)\n            {\n              double trace = 0.0;\n              for ( auto j : boost::irange(0, n) )\n                trace -= _alpha(j)*obsY(j);\n              trace += n;\n              trace *= 0.5;\n              // Add  1/2 * trace[(noise * term)]  (i.e. the noise gradient)\n              trace -= g(index-1);\n              g(index++) = trace;\n            }\n          else\n            {\n              double trace = 0.0;\n              Matrix dK = K - noise*Matrix::Identity(n,n);\n              for ( auto j : boost::irange(0, n) )\n                trace += term.row(j)*dK.col(j);\n              g(index++) = 0.5*trace;\n            }\n          //  \n          //  NOTE: The following implementation does not account for noise term (!)\n          //\n          //  Ah, it's so close though...\n          //\n          //  The adjusted covariance matrix is:  K'  =  s * K  +  noise * I  \n          //\n          //  But if we had   K' = s*K   and set   t = log(s) ~ s = exp(t) :\n          //\n          //  ( so that  dK'/dt  =  d/dt[ s*K ]  =  d/ds[ s*K ] * ds/dt  =  s * K  =  K'  )\n          //\n          //  then it would give us the reduction:\n          //\n          //  d/dt -log p(y|X,t)  =  -1/2 * trace[ ( (K'^-1 y)(K'^-1 y)^T - K'^-1 ) dK'/dt  ]\n          //\n          //   =  -1/2 * trace[ ( K'^-1 y y^T K'^-1 - K'^-1 ) dK'/dt  ]\n          //\n          //   =  -1/2 * trace[ ( K'^-1 y y^T K'^1 - K'^-1 ) K'  ]\n          //\n          //   =  -1/2 * trace[  (K'^-1 y) y^T - I  ]\n          //\n          //   =  -1/2 * trace[  alpha * y^T - I  ]\n          //\n          //\n          //  but...    we do have:\n          //  \n          //   dK'/dt  =  d/dt[s*K]  =  s * K  =  K' - noise * I\n          //\n          //  so that the (corected) calculation above still yields:\n          //\n          //   =  -1/2 * trace[  (alpha * y^T - I)  -  noise * term  ]\n          //\n          //  and the trace of \"term\" has already been calculated...\n          //\n          //\n          //double trace = 0.0;\n          //for ( auto i : boost::irange(0,n) )\n          //  trace -= _alpha(i)*obsY(i);\n          //trace += n;\n          //g(index++) = 0.5 * trace;\n        }\n\n      // Specify gradient w.r.t. the kernel scaling parameter\n      //if (!fixedScaling)\n      //  gradList.insert(gradList.begin(), K - noise*Matrix::Identity(n,n));\n      \n      // Compute gradients with respect to kernel hyperparameters\n      for (auto dK_i = gradList.begin(); dK_i != gradList.end(); ++dK_i) \n        {\n          // Compute trace of full matrix\n          //g(index++) = 0.5 * (term * (*dK_i) ).trace() ;\n\n          // POSSIBLE MULTI-THREADED IMPLEMENTATION\n          // Construct zero initialized vector of partial trace values\n          Matrix traceVals = Eigen::MatrixXd::Zero(threadCount,1);\n\n          std::vector<int> startVals;\n          for ( auto i : boost::irange(0,threadCount) )\n            startVals.emplace_back(i*d);\n\n          std::vector<int> endVals;\n          for ( auto i : boost::irange(1,threadCount) )\n            endVals.emplace_back(i*d);\n          endVals.emplace_back(n);\n\n          // Define lambda function specifying each threads solver task\n          auto lambda = [&term,&dK_i,&traceVals](int i, int startInd, int endInd) {\n                          for ( auto j : boost::irange(startInd, endInd) )\n                            traceVals(i) += term.row(j)*(*dK_i).col(j);\n                        };\n\n          // Initialize thread list\n          std::vector<std::thread> traceThreadList;\n\n          // Assign tasks to threads\n          for ( auto i : boost::irange(0,threadCount) )\n            traceThreadList.emplace_back(lambda,i,startVals[i],endVals[i]);\n\n          // Join threads\n          for ( auto & thread : traceThreadList )\n            thread.join();\n\n          // Compute final trace value for derivative calculation\n          g(index++) = 0.5*(traceVals.sum());\n          \n        }\n      end = high_resolution_clock::now();\n      time_grad += getTime(start, end);\n\n      // Update gradient evaluation count\n      gradientEvals += 1;\n\n    }\n  \n  time EVAL_end = high_resolution_clock::now();\n  time_evaluation += getTime(EVAL_start, EVAL_end);\n  return NLML_value;\n  \n}\n\n\n// Define simplified interface for evaluating NLML without gradient calculation\ndouble GP::GaussianProcess::evalNLML(const Vector & p)\n{\n  Vector nullGrad(0);\n  return evalNLML(p,nullGrad,false);\n}\n\n\nint GP::GaussianProcess::getAugParamCount(int count)\n{\n  if (!fixedNoise)\n    {\n      if (!fixedScaling)\n        return count + 2;\n      else\n        return count + 1;\n    }\n  else\n    {\n      if (!fixedScaling)\n        return count + 1;\n      else\n        return count;\n    }\n}\n\n// Fit model hyperparameters\nvoid GP::GaussianProcess::fitModel()\n{\n\n  // Get combined parameter/noise vector size\n  paramCount = (*kernel).getParamCount();\n  //augParamCount = (fixedNoise) ? static_cast<int>(paramCount) : static_cast<int>(paramCount) + 1 ;\n  augParamCount = getAugParamCount(paramCount);\n\n  // Pass noise level to kernel when 'fixedNoise=true'\n  if ( fixedNoise )\n    (*kernel).setNoise(noiseLevel);\n  if ( fixedScaling )\n    (*kernel).setScaling(scalingLevel);\n\n  // Declare vector for storing gradient calculations\n  Vector g(augParamCount);\n\n  // Initialize gradient list with identity matrices\n  //for ( auto i : boost::irange(0,augParamCount) )\n  //int gradientCount = paramCount;\n  //if (!fixedScaling)\n  //  gradientCount += 1;\n  //for ( auto i : boost::irange(0,gradientCount) )\n\n  for ( auto i : boost::irange(0,paramCount) )\n    {\n      // Avoid compiler warning for unused variable\n      (void)i;\n      gradList.push_back(Matrix::Identity(static_cast<int>(obsY.size()),static_cast<int>(obsY.size())));\n    }\n\n\n  // Convert hyperparameter bounds to log-scale\n  Vector lbs, ubs;\n  parseBounds(lbs, ubs, augParamCount);\n\n  // Initialize optimal hyperparamter values\n  Vector optParams = Eigen::MatrixXd::Zero(augParamCount,1);\n\n  // Define restart count for optimizer\n  int restartCount = solverRestarts;\n\n  // Declare variables to store optimization loop results\n  double currentVal;\n  double optVal = 1e9;\n  Vector theta(augParamCount);\n\n  // Define low-precision solver for restart loop\n  LBFGSpp::LBFGSParam<double> param;\n  param.linesearch  = LBFGSpp::LBFGS_LINESEARCH_BACKTRACKING_STRONG_WOLFE;\n  param.m = 10;\n  param.epsilon = 1e-6;\n  param.max_iterations = 10;\n  param.max_linesearch = 5;\n  param.delta = 1e-4;\n\n  int niter;\n  \n  // Evaluate optimizer with various different initializations\n  for ( auto i : boost::irange(0,restartCount) )\n    {\n      if ( i == 0 )\n        {\n          // Set initial guess (should make this user specifiable...)\n          theta = Eigen::MatrixXd::Zero(augParamCount,1);\n        }\n      else\n        {\n          // Sample initial hyperparameter vector\n          theta = sampleUnifVector(lbs, ubs);\n        }\n\n      // Create solver and function object\n      LBFGSpp::LBFGSSolver<double> solver(param);\n      niter = solver.minimize(*this, theta, currentVal);\n      \n      // Compute current NLML and store parameters if optimal\n      if ( currentVal < optVal ) { optVal = currentVal; optParams = theta; }\n      \n    }\n\n  // Perform one last optimization starting from best parameters so far\n  //if ( restartCount == 0 ) \n  //  optParams = sampleUnifVector(lbs, ubs);\n    \n\n  LBFGSpp::LBFGSParam<double> finalparam;\n\n  // Line Search Options\n  //param.linesearch  = LBFGSpp::LBFGS_LINESEARCH_BACKTRACKING_ARMIJO;\n  //param.linesearch  = LBFGSpp::LBFGS_LINESEARCH_BACKTRACKING_WOLFE;\n  //param.linesearch  = LBFGSpp::LBFGS_LINESEARCH_BACKTRACKING_STRONG_WOLFE;\n\n  // TRY MODELLING SCIPY fmin_l_bfgs_b PARAMETERS\n  finalparam.m = 10;\n  finalparam.epsilon = 1e-5;\n  finalparam.max_linesearch = 20;\n  double eps = 2.220446049250313e-16;\n  double factr = solverPrecision;\n  finalparam.past = 1;\n  //finalparam.ftol = factr*eps;\n  finalparam.delta = factr*eps;\n  finalparam.max_iterations = 100;\n  \n  // Create solver and function object\n  LBFGSpp::LBFGSSolver<double> finalsolver(finalparam);\n  niter = finalsolver.minimize(*this, optParams, optVal);\n\n  if ( VERBOSE )\n    {\n      std::cout << \"\\n[*] Solver Iterations = \" << niter <<std::endl;\n      std::cout << \"\\n[*] Function Evaluations = \" << gradientEvals <<std::endl;\n    }\n  \n  // ASSUME OPTIMIZATION OVER LOG VALUES\n  optParams = optParams.array().exp().matrix();\n\n  ///* [ This is included in the SciKit Learn model.fit() call as well ]\n\n  // Recompute covariance and Cholesky factor\n  auto n = static_cast<int>(obsX.rows());\n  Matrix K(n,n);\n  (*kernel).computeCov(K, obsX, optParams, gradList, jitter, false);\n  cholesky = K.llt();\n  alpha.noalias() = cholesky.solve(obsY);\n\n  // Assign tuned parameters to model\n  if (!fixedNoise)\n    {\n      noiseLevel = optParams[0];\n      if (!fixedScaling)\n          scalingLevel = optParams[1];\n    }\n  else\n    {\n      if (!fixedScaling)\n        scalingLevel = optParams[0];\n    }\n\n  optParams = static_cast<Vector>(optParams.tail(paramCount));\n  (*kernel).setParams(optParams);\n\n\n  // DISPLAY TIMING INFORMATION\n  if ( VERBOSE )\n    {\n      std::cout << \"\\n Time Diagnostics |\\n\";\n      std::cout << \"------------------\\n\";\n      std::cout << \"computeCov():\\t  \" << time_computecov/gradientEvals  << std::endl;\n      std::cout << \"cholesky.llt():\\t  \" << time_cholesky_llt/gradientEvals  << std::endl;\n      std::cout << \"_alpha term:\\t  \" << time_alpha/gradientEvals  << std::endl;\n      std::cout << \"NLML:\\t  \\t  \" << time_NLML/gradientEvals  << std::endl;\n      std::cout << \"Grad term:\\t  \" << time_term/gradientEvals  << std::endl;\n      std::cout << \"Gradient:\\t  \" << time_grad/gradientEvals  << std::endl;\n      std::cout << \"\\nEvaluation:\\t  \" << time_evaluation/gradientEvals  << std::endl;\n    }\n    \n};\n\n\n// Compute predicted values\nvoid GP::GaussianProcess::predict()\n{\n  // Get matrix input observation count\n  auto n = static_cast<int>(obsX.rows());\n  auto m = static_cast<int>(predX.rows());\n  \n  // Get optimized kernel hyperparameters\n  Vector params = (*kernel).getParams();\n\n  // Compute cross covariance for test points\n  Matrix kstar_and_v;\n  kstar_and_v.resize(n,m);\n  (*kernel).computeCrossCov(kstar_and_v, obsX, predX, params);\n  kstar_and_v *= scalingLevel;\n    \n  // Compute covariance matrix for test points\n  Matrix kstarmat;\n  kstarmat.resize(m,m);\n  (*kernel).computeCrossCov(kstarmat, predX, predX, params);\n  kstarmat *= scalingLevel;\n\n  // Set predictive means/variances and compute negative log marginal likelihood\n  Matrix cholMat(cholesky.matrixL());\n  //predMean.noalias() = kstar_and_v.transpose() * _alpha;\n  predMean.noalias() = kstar_and_v.transpose() * alpha;\n  cholMat.triangularView<Eigen::Lower>().solveInPlace(kstar_and_v);  // kstar_and_v is now 'v'\n  predCov.noalias() = kstarmat - kstar_and_v.transpose() * kstar_and_v;\n\n}\n\n\n// Draw sample paths from posterior distribution\nMatrix GP::GaussianProcess::getSamples(int count)\n{\n  // Get number of target points\n  auto n = static_cast<int>(predX.rows());\n  \n  // Construct simple random generator engine from a time-based seed\n  unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();\n  std::default_random_engine generator (seed);\n  std::normal_distribution<double> normal (0.0,1.0);\n\n  // Assign i.i.d. random normal values to uVals\n  Matrix uVals(n,count);\n  for (auto i : boost::irange(0,n))\n    {\n      for (auto j : boost::irange(0,count))\n          uVals(i,j) = normal(generator);\n    }\n\n  // Compute Cholesky factor L\n  Matrix L = ( predCov + (noiseLevel+jitter)*Matrix::Identity(static_cast<int>(predCov.cols()), static_cast<int>(predCov.cols())) ).llt().matrixL();\n\n  // Draw samples using the formula:  y = m + L*u\n  Matrix samples = predMean.replicate(1,count) + L*uVals;\n  \n  return samples;\n}\n\n\n// Evaluate NLML [public interface]\ndouble GP::GaussianProcess::computeNLML(const Vector & p)\n{\n  // Compute log-hyperparameters\n  Vector logparams(augParamCount);\n\n  int index = 0;\n  logparams(index++) = std::log(noiseLevel);\n  logparams(index++) = std::log(scalingLevel);\n  for ( auto i : boost::irange(index,augParamCount) )\n    logparams(i) = std::log(p(i-index));\n\n  // Evaluate NLML using log-hyperparameters\n  return evalNLML(logparams);\n}\n\n\n// Evaluate NLML with default noise level [public interface]\ndouble GP::GaussianProcess::computeNLML()\n{\n  auto params = (*kernel).getParams();\n  return computeNLML(params);\n}\n\n\n\n// Define function for uniform sampling\nMatrix GP::sampleUnif(double a, double b, int N, int dim)\n{\n  //return (b-a)*(Eigen::MatrixXd::Random(N,1) * 0.5 + 0.5*Eigen::MatrixXd::Ones(N,1)) + a*Eigen::MatrixXd::Ones(N,1);\n  return (b-a)*(Eigen::MatrixXd::Random(N,dim) * 0.5 + 0.5*Eigen::MatrixXd::Ones(N,dim) ) + a*Eigen::MatrixXd::Ones(N,dim);\n}\n\n\n// Define function for uniform sampling [Vectors]\nVector GP::sampleUnifVector(Vector lbs, Vector ubs)\n{\n  auto n = static_cast<int>(lbs.rows());\n\n  Vector sampleVector = ((ubs-lbs).array()*( 0.5*Eigen::MatrixXd::Random(n,1) + 0.5*Eigen::MatrixXd::Ones(n,1) ).array()).matrix() + (lbs.array()*Eigen::MatrixXd::Ones(n,1).array()).matrix();\n  \n  return sampleVector;\n}\n\n\n// Define function for sampling from standard normal distribution\nMatrix GP::sampleNormal(int N)\n{\n  // Note: Boost random is currently throwing deprecated header warnings...\n  //boost::random::mt19937 rng;\n  //boost::random::normal_distribution<> normalDist;\n\n  /*\n  // [ NOTE: .noalias() is 100% necessary with \"std::default_random_engine\" ]\n  std::default_random_engine rng;\n  std::normal_distribution<double> normalDist(0.0,1.0);\n  Matrix sampleVals(N,1);\n  for ( auto i : boost::irange(0,N) )\n    sampleVals(i) = normalDist(rng);\n  */\n\n  \n  //\n  //          Crude implementation of Box-Muller Transform\n  // ( see https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform )\n  //\n  static const double epsilon = std::numeric_limits<double>::min();\n  Matrix U1(N,1);\n  Matrix U2(N,1);\n\n  // Ensure log operand is not too small\n  double scaledLimit = 2.0*epsilon - 1.0;\n  do\n    {\n      U1 = Eigen::MatrixXd::Random(N,1);\n      U2 = Eigen::MatrixXd::Random(N,1);\n    }\n  while ( U1.minCoeff() <= scaledLimit );\n\n  // Rescale and shift Unif(-1,1) values to the interval [0,1]\n  U1 =  0.5*(U1 + Eigen::MatrixXd::Ones(N,1));\n  U2 =  0.5*(U2 + Eigen::MatrixXd::Ones(N,1));\n\n  // Compute transformed values with .noalias() to ensure evaluation\n  Matrix sampleVals;\n  sampleVals.noalias() = ((-2.0*(U1.array().log()).matrix()).array().sqrt() * (2*PI*U2).array().cos()).matrix();\n\n  return sampleVals;\n}\n\n\n// Generate equally spaced points on an interval or square region\nMatrix GP::linspace(double a, double b, int N, int dim)\n{\n\n  Matrix linspaceVals;\n  if ( dim == 1 )\n    {\n      linspaceVals.resize(N,1);\n      linspaceVals = Eigen::Array<double, Eigen::Dynamic, 1>::LinSpaced(N, a, b);\n    }\n  else if ( dim == 2 )\n    {\n      linspaceVals.resize(N*N,2);\n      Matrix linspaceVals1D = Eigen::Array<double, Eigen::Dynamic, 1>::LinSpaced(N, a, b);\n      int k = 0;\n      for ( auto i : boost::irange(0,N) )\n        {\n          for ( auto j : boost::irange(0,N) )\n            {\n              linspaceVals(k,0) = linspaceVals1D(i);\n              linspaceVals(k,1) = linspaceVals1D(j);\n              k++;\n            }\n        }\n    }\n  else\n      std::cout << \"[*] GP::linspace has not been implemented for dim > 2\\n\";\n  \n  return linspaceVals;\n}\n\n// Define function for retrieving time from chrono\nfloat GP::getTime(std::chrono::high_resolution_clock::time_point start, std::chrono::high_resolution_clock::time_point end)\n{\n  return static_cast<float>(std::chrono::duration_cast<std::chrono::microseconds>( end - start ).count() / 1000000.0);\n};\n\n\n\n\n// Define utility function for formatting hyperparameter bounds\nvoid GP::GaussianProcess::parseBounds(Vector & lbs, Vector & ubs, int augParamCount)\n{\n  lbs.resize(augParamCount);\n  ubs.resize(augParamCount);\n\n  double defaultLowerBound = 0.01;\n  double defaultUpperBound = 2.0;\n  \n  if ( fixedBounds )\n    {\n      // Check if bounds for noise parameter were provided\n      if ( lowerBounds.size() < augParamCount )\n        {\n          // Set noise bounds to defaults\n          lbs(0) = std::log( defaultLowerBound );\n          ubs(0) = std::log( defaultUpperBound );\n\n          // Convert specified bounds to log-scale\n          for ( auto bi : boost::irange(1,augParamCount) )\n            {\n              lbs(bi) = std::log(lowerBounds(bi-1));\n              ubs(bi) = std::log(upperBounds(bi-1));\n            }\n        }\n      else\n        {\n          // Convert specified bounds to log-scale\n          lbs = (lowerBounds.array().log()).matrix();\n          ubs = (upperBounds.array().log()).matrix();\n        }\n    }\n  else\n    {\n      // Set noise and hyperparameter bounds to defaults\n      lbs = ( defaultLowerBound * Eigen::MatrixXd::Ones(augParamCount,1) ).array().log().matrix();\n      ubs = ( defaultUpperBound * Eigen::MatrixXd::Ones(augParamCount,1) ).array().log().matrix();\n    }\n\n}\n\n\n\n\n/*\n//  POSSIBLY UNNEEDED POINTWISE KERNEL DEFINITIONS\n\n// Define kernel function for RBF\ndouble GP::RBF::evalKernel(Matrix & x, Matrix & y, Vector & params, int n)\n{\n  switch (n)\n    {\n    case 0: return std::exp( -(x-y).squaredNorm() / (2.0*std::pow(params(0),2)));\n    case 1: return (x-y).squaredNorm() / std::pow(params(0),3) * std::exp( -(x-y).squaredNorm() / (2.0*std::pow(params(0),2)));\n    default: std::cout << \"\\n[*] UNDEFINED DERIVATIVE\\n\"; return 0.0;\n    }\n};\n\n*/\n\n\n\n\n\n/*\n// POTENTIAL PARALLEL IMPLEMENTATION OF SQUARE FORM; SPEED-UP APPEARS NEGLIGIBLE\n// Re-assemble pairwise distances into a dense matrix\nvoid GP::squareFormParallel(Matrix & D, Matrix & Dv, int n, double diagVal)\n{\n\n  D.resize(n,n);\n  int i;\n  int j;\n#pragma omp parallel for private(i,j) shared(D,Dv,n)\n  for ( i = 0 ; i<n-1; i++ )\n    {\n      for ( j = i+1 ; j<n ; j++ )\n        {\n          D(i,j) = D(j,i) = Dv( static_cast<int>(i*n - (i*(i+1))/2 + j - i -1) ,0);\n        }\n    }\n  D.diagonal() = diagVal * Eigen::MatrixXd::Ones(n,1);\n}\n*/\n\n\n\n\n\n\n//\n//   SECOND MINIMIZATION IMPLEMENTATION USING CPPOPTLIB\n//\n\n// Fit model hyperparameters\n//void GP::GaussianProcess::fitModel()\n\n// Initialize gradient vector size\n//cppOptLibgrad.resize(augParamCount);\n\n/*\nthis->setLowerBound(lbs);\nthis->setUpperBound(ubs);\ncppoptlib::LbfgsbSolver<GaussianProcess> solver;\n\n// Specify stopping criteria\ncppoptlib::Criteria<double> crit = cppoptlib::Criteria<double>::defaults();\n//crit.iterations = 10; //!< Maximum number of iterations\ncrit.gradNorm = 1e-6;   //!< Minimum norm of gradient vector\n//crit.fDelta = 7.5e-5;   //!< Minimum [relative] change in cost function\ncrit.iterations = solverIterations;\ncrit.fDelta = solverPrecision;\nsolver.setStopCriteria(crit);\nsolver.setHistorySize(10);\n\nsolver.minimize(*this, optParams);\n\n*/\n\n// Display final solver criteria values\n/*\nstd::cout << \"\\nSolver Criteria |\";\nstd::cout << \"\\n----------------\\n\" << solver.criteria() << std::endl;\nstd::cout << \"gradEvals =\\t\" << gradientEvals <<std::endl;\n*/\n\n\n\n\n\n\n//\n//   ORIGINAL MINIMIZATION IMPLEMENTATION USING RASMUSSEN'S CODE\n//\n\n//\n//    NOTE:\n//\n//    Remember to include \"utils/minimize.h\" and derive the\n//   'GaussianProcess' class from the 'GradientObj' class:\n//\n//    i.e.  class GaussianProcess : public minimize::GradientObj\n//\n\n/*\nvoid minimize(...)\n{\n\n\n  //\n  // Specify the parameters for the minimization algorithm\n  //\n  \n  //   HIGH ACCURACY SETTINGS   //\n  // max of MAX function evaluations per line search\n  //int MAX = 30;\n  // max number of line searches = length\n  //int length = 20;\n  // don't reevaluate within INT of the limit of the current bracket\n  //double INT = 0.00001;\n  // SIG is a constant controlling the Wolfe-Powell conditions\n  //double SIG = 0.9;\n  // extrapolate maximum EXT times the current step-size\n  //double EXT = 5.0;\n\n  //  EFFICIENT SETTINGS  //\n\n\n  int MAX = 15;\n  int length = 10;\n  double INT = 0.00001;\n  double SIG = 0.9;\n  double EXT = 5.0;\n\n  // Define number of exploratory NLML evaluations for specifying\n  // a reasonable initial value for the optimization algorithm\n  int initParamSearchCount = 30;\n    \n  // Define restart count for optimizer\n  int restartCount = 0;\n  \n  // Convert hyperparameter bounds to log-scale\n  Vector lbs, ubs;\n  parseBounds(lbs, ubs, augParamCount);\n\n  // Declare variables to store optimization loop results\n  double currentVal;\n  double optVal = 1e9;\n  Vector theta(augParamCount);\n  Vector optParams(augParamCount);\n\n  //time start = high_resolution_clock::now();\n  // First explore hyperparameter space to get a reasonable initializer for optimization\n  for ( auto i : boost::irange(0,initParamSearchCount) )\n    {\n      if ( i == 0 )\n          theta = Eigen::MatrixXd::Zero(augParamCount,1);\n      else\n          theta = sampleUnifVector(lbs, ubs);\n\n      // Compute current NLML and store parameters if optimal\n      currentVal = evalNLML(theta);\n      if ( currentVal < optVal )\n        {\n          optVal = currentVal;\n          optParams = theta;\n        }\n      //std::cout << \"Theta Search:  \" << theta.transpose() << \"  [ NLML = \" << currentVal << \" ]\"<< std::endl;\n    }\n  //time end = high_resolution_clock::now();\n  //time_paramsearch += getTime(start, end);\n\n\n  // NOTE: THIS NEEDS TO BE RE-WRITTEN TO USE THE PRELIMINARY PARAMETER SEARCH RESULTS\n  // Evaluate optimizer with various different initializations\n  for ( auto i : boost::irange(0,restartCount) )\n    {\n      // Avoid compiler warning for unused variable\n      //(void)i;\n\n      if ( i == 0 )\n        {\n          // Set initial guess (should make this user specifiable...)\n          theta = Eigen::MatrixXd::Zero(augParamCount,1);\n        }\n      else\n        {\n          // Sample initial hyperparameter vector\n          theta = sampleUnifVector(lbs, ubs);\n        }\n\n      // Optimize hyperparameters\n      minimize::cg_minimize(theta, this, g, length, SIG, EXT, INT, MAX);\n      \n      // Compute current NLML and store parameters if optimal\n      currentVal = evalNLML(theta);\n      if ( currentVal < optVal )\n        {\n          optVal = currentVal;\n          optParams = theta;\n        }\n    }\n\n  // Perform one last optimization starting from best parameters so far\n  if ( ( initParamSearchCount == 0 ) && ( restartCount == 0 ) )\n    optParams = sampleUnifVector(lbs, ubs);\n  //std::cout << \"\\n[*] FINAL - Initial Values (log):  \" << optParams.transpose() << std::endl;\n  //std::cout << \"[*] FINAL - Initial Values (std):  \" << optParams.transpose().array().exp().matrix() << std::endl;\n  //start = high_resolution_clock::now();\n  minimize::cg_minimize(optParams, this, g, length, SIG, EXT, INT, MAX);\n  //end = high_resolution_clock::now();\n  //time_minimize += getTime(start, end);\n\n}\n*/\n", "meta": {"hexsha": "fdad22ccca5470e4581f9d590d67b37dc181be34", "size": 33133, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "GPs.cpp", "max_stars_repo_name": "nw2190/CppGPs", "max_stars_repo_head_hexsha": "eb707e54dff274596238310a654a715930d62214", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2019-06-14T02:16:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-11T16:22:49.000Z", "max_issues_repo_path": "GPs.cpp", "max_issues_repo_name": "nw2190/CppGPs", "max_issues_repo_head_hexsha": "eb707e54dff274596238310a654a715930d62214", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-05-10T07:40:50.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-10T07:40:50.000Z", "max_forks_repo_path": "GPs.cpp", "max_forks_repo_name": "nw2190/CppGPs", "max_forks_repo_head_hexsha": "eb707e54dff274596238310a654a715930d62214", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-08-12T15:07:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-07T12:44:46.000Z", "avg_line_length": 30.3138151876, "max_line_length": 191, "alphanum_fraction": 0.6144931036, "num_tokens": 9091, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125848754471, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.4790551744024527}}
{"text": "/**\n * @file stabrk3_main.cc\n * @brief NPDE homework StabRK3 code\n * @author Oliver Rietmann, Philippe Peter\n * @date 13.04.2021\n * @copyright Developed at ETH Zurich\n */\n\n#include <Eigen/Core>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\n#include \"stabrk3.h\"\n\nconst static Eigen::IOFormat CSVFormat(Eigen::FullPrecision,\n                                       Eigen::DontAlignCols, \", \", \"\\n\");\n\nint main() {\n  // aproximate reference solution used in the convergence study\n  double T = 1.0;\n  Eigen::Vector2d y0(100.0, T);\n  Eigen::Vector2d yT_reference = StabRK3::PredPrey(y0, T, std::pow(2, 14));\n  std::cout << \"Solution Computed by PredPrey(): \"\n            << yT_reference.transpose().format(CSVFormat) << std::endl;\n\n  // Convergence study\n  StabRK3::SimulatePredPrey();\n\n  return 0;\n}\n", "meta": {"hexsha": "aae0409d6883a5244e5bb9faf8d3d4682b39d3c5", "size": 807, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/StabRK3/templates/stabrk3_main.cc", "max_stars_repo_name": "yiluchen1066/NPDECODES", "max_stars_repo_head_hexsha": "f7b1d96555bace59aba2b65f3ef1e95fa7a9017c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/StabRK3/templates/stabrk3_main.cc", "max_issues_repo_name": "yiluchen1066/NPDECODES", "max_issues_repo_head_hexsha": "f7b1d96555bace59aba2b65f3ef1e95fa7a9017c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/StabRK3/templates/stabrk3_main.cc", "max_forks_repo_name": "yiluchen1066/NPDECODES", "max_forks_repo_head_hexsha": "f7b1d96555bace59aba2b65f3ef1e95fa7a9017c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 25.21875, "max_line_length": 75, "alphanum_fraction": 0.6505576208, "num_tokens": 232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.7520125848754471, "lm_q1q2_score": 0.4790551744024527}}
{"text": "/*****************************************************************************\n*\n* Rokko: Integrated Interface for libraries of eigenvalue decomposition\n*\n* Copyright (C) 2012-2013 by Tatsuya Sakashita <t-sakashita@issp.u-tokyo.ac.jp>,\n*                            Synge Todo <wistaria@comp-phys.org>\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#include <iostream>\n#include <fstream>\n#include <vector>\n#include <boost/tuple/tuple.hpp>\n\n#include <rokko/utility/xyz_hamiltonian.hpp>\n#include <rokko/localized_matrix.hpp>\n#include <rokko/localized_vector.hpp>\n\nint main(int argc, char *argv[])\n{\n  if (argc <= 1) {\n    std::cerr << \"error: \" << argv[0] << \" xyz.ip\" << std::endl;\n    exit(1);\n  }\n\n  std::ifstream ifs(argv[1]);\n  if (!ifs) {\n    std::cout << \"can't open file\" << std::endl;\n    exit(2);\n  }\n\n  int L, num_bonds;\n  std::vector<std::pair<int, int> > lattice;\n  std::vector<boost::tuple<double, double, double> > coupling;\n  ifs >> L >> num_bonds;\n  for (int i=0; i<num_bonds; ++i) {\n    int j, k;\n    ifs >> j >> k;\n    lattice.push_back(std::make_pair(j, k));\n  }\n  \n  for (int i=0; i<num_bonds; ++i) {\n    double jx, jy, jz;\n    ifs >> jx >> jy >> jz;\n    coupling.push_back(boost::make_tuple(jx, jy, jz));\n  }\n  \n  std::cout << \"L=\" << L << \" num_bonds=\" << num_bonds << std::endl;\n  for (int i=0; i<num_bonds; ++i) {\n    std::cout << lattice[i].first << \" \" << lattice[i].second << \" \" << coupling[i].get<0>() << \" \" << coupling[i].get<1>() << \" \" << coupling[i].get<2>() << std::endl;\n  }\n  int dim = 1 << L;\n  int N = dim;\n  std::cout << \"dim=\" << dim << std::endl;\n\n  rokko::localized_matrix<rokko::matrix_col_major> mat1(N, N);\n  std::cout << \"multiply:\" << std::endl;\n  for (int i=0; i<N; ++i) {\n    std::vector<double> v, w;\n    v.assign(N, 0);\n    v[i] = 1;\n    w.assign(N, 0);\n    rokko::xyz_hamiltonian::multiply(L, lattice, coupling, v, w);\n    for (int j=0; j<N; ++j) {\n      mat1(j,i) = w[j];\n      std::cout << w[j] << \" \";\n    }\n    std::cout << std::endl;\n  }\n\n  std::cout << \"fill_diagonal:\" << std::endl;\n  rokko::localized_vector diagonal(N);\n  std::vector<double> v(N);\n  rokko::xyz_hamiltonian::fill_diagonal(L, lattice, coupling, v);\n  for (int j=0; j<N; ++j) {\n    diagonal(j) = v[j];\n    std::cout << v[j] << \" \";\n  }\n  std::cout << std::endl;\n\n  std::cout << \"fill_matrix:\" << std::endl;\n  rokko::localized_matrix<rokko::matrix_col_major> mat2(N, N);\n  rokko::xyz_hamiltonian::generate(L, lattice, coupling, mat2);\n  for (int i=0; i<N; ++i) {\n    for (int j=0; j<N; ++j) {\n      std::cout << mat2(i,j) << \" \";\n    }\n    std::cout << std::endl;\n  }\n\n  if (mat1 == mat2) {\n    std::cout << \"OK: matrix by 'multiply' equals to a matrix by 'generate'.\" << std::endl;\n  } else {\n    std::cout << \"ERROR: matrix by 'multiply' is differnet from a matrix by 'generate'.\"<< std::endl;\n    exit(1);\n  }\n\n  if (diagonal == mat2.diagonal()) {\n    std::cout << \"OK: diagonal by 'fill_diagonal' equals to diagonal elementas of a matrix by 'genertate'.\"<< std::endl;\n  } else {\n    std::cout << \"ERROR: diagonal by 'fill_diagonal' is differnet from diagonal elementas of a matrix by 'genertate'.\"<< std::endl;\n    exit(1);\n  }\n\n}\n\n\n", "meta": {"hexsha": "18f86f5f3f5e8774e9661fe42953c57f8aa6059c", "size": 3348, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/generate_matrix/xyz_file.cpp", "max_stars_repo_name": "wistaria/rokko", "max_stars_repo_head_hexsha": "7cd9d5155e82f038039a46c1dc8f382b3fe7e2b7", "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": "test/generate_matrix/xyz_file.cpp", "max_issues_repo_name": "wistaria/rokko", "max_issues_repo_head_hexsha": "7cd9d5155e82f038039a46c1dc8f382b3fe7e2b7", "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/generate_matrix/xyz_file.cpp", "max_forks_repo_name": "wistaria/rokko", "max_forks_repo_head_hexsha": "7cd9d5155e82f038039a46c1dc8f382b3fe7e2b7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1621621622, "max_line_length": 168, "alphanum_fraction": 0.5537634409, "num_tokens": 1071, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.6370308013713525, "lm_q1q2_score": 0.47905517250353696}}
{"text": "#include <iostream>\n#include <algorithm>\n#include <iterator>\n#include <cmath>\n#include <fstream>\n#include <valarray>\n#include <sstream>\n#include <string>\n#include <utility>\n\nusing namespace std::string_literals;\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/math/constants/constants.hpp>\n\n#include \"vlasovpp/field.h\"\n#include \"vlasovpp/complex_field.h\"\n#include \"vlasovpp/weno.h\"\n#include \"vlasovpp/fft.h\"\n#include \"vlasovpp/array_view.h\"\n#include \"vlasovpp/poisson.h\"\n#include \"vlasovpp/splitting.h\"\n#include \"vlasovpp/lagrange5.h\"\n#include \"vlasovpp/config.h\"\n#include \"vlasovpp/signal_handler.h\"\n#include \"vlasovpp/iteration.h\"\n\nnamespace math = boost::math::constants;\nconst std::complex<double> & I = std::complex<double>(0.,1.);\n\n#define SQ(X) ((X)*(X))\n#define Xi(i) (i*fh.step.dx+fh.range.x_min)\n#define Vk(k) (k*fh.step.dv+fh.range.v_min)\n\nauto\nmaxwellian ( double rho , double u , double T ) {\n  return [=](double x,double v){ return rho/(std::sqrt(2.*math::pi<double>()*T))*std::exp( -0.5*SQ(v-u)/T ); };\n}\n\nauto\nerror_H ( std::size_t Nx , std::size_t Nv , double dt )\n{\n  const double Tf = 6.5;\n\n  field<double,1> fh(boost::extents[Nv][Nx]);\n  complex_field<double,1> hfh(boost::extents[Nv][Nx]);\n\n  const double Kx = 0.5;\n  fh.range.v_min = -12.; fh.range.v_max = 12.;\n  fh.range.x_min =  0.; fh.range.x_max = 2./Kx*math::pi<double>();\n  fh.compute_steps();\n\n  ublas::vector<double> v(Nv,0.);\n  std::generate( v.begin() , v.end() , [&,k=0]() mutable {return (k++)*fh.step.dv+fh.range.v_min;} );\n\n  ublas::vector<double> kx(Nx); // beware, Nx need to be odd\n  {\n    double l = fh.range.len_x();\n    for ( auto i=0 ; i<Nx/2 ; ++i ) { kx[i]    = 2.*math::pi<double>()*i/l; }\n    for ( int i=-Nx/2 ; i<0 ; ++i ) { kx[Nx+i] = 2.*math::pi<double>()*i/l; }\n  }\n\n  const double alpha = 0.2 , ui = 3.4;\n  auto tb_M1 = maxwellian( 0.5*alpha , ui , 1. ) , tb_M2 = maxwellian( 0.5*alpha , -ui , 1. );\n  for (field<double,2>::size_type k=0 ; k<fh.size(0) ; ++k ) {\n    for (field<double,2>::size_type i=0 ; i<fh.size(1) ; ++i ) {\n      hfh[k][i] = 0.;\n      fh[k][i] = ( tb_M1(Xi(i),Vk(k)) + tb_M2(Xi(i),Vk(k)) )*(1. + 0.01*std::cos(Kx*Xi(i)));\n    }\n    fft::fft(fh[k].begin(),fh[k].end(),hfh[k].begin());\n  }\n\n  std::size_t iter = 0;\n  double current_time = 0.;\n\n  ublas::vector<double> uc(Nx,0.);\n  ublas::vector<double> E (Nx,0.);\n\n  std::vector<double> H;\n  std::vector<double> ee;\n  std::vector<double> t;\n\n  const double rho_c = 1.-alpha;\n  const double sqrt_rho_c = std::sqrt(rho_c);\n\n  // init E with Poisson solver, init also ee, Emax, H and times\n  {\n    poisson<double> poisson_solver(Nx,fh.range.len_x());\n    ublas::vector<double> rho(Nx,0.); rho = fh.density(); // compute density from init hot data\n    for ( auto i=0 ; i<Nx ; ++i ) { rho[i] += (1.-alpha); } // add (1-alpha) for cold particules\n    E = poisson_solver(rho);\n\n    double total_energy = energy(fh,E);\n    total_energy += 0.; // sum(rho_c*u_c*u_c) = 0 because u_c = 0 at time 0\n    H.push_back( total_energy );\n  }\n  t.push_back(current_time);\n\n  // initialize memory for all temporary variables\n  splitting<double,1> Lie( fh , fh.range.len_x() , rho_c );\n\n  ublas::vector<double> uc1(Nx) , uc2(Nx) , uc3(Nx) , uc4(Nx) , ucn(Nx),\n                        E1 (Nx) , E2 (Nx) , E3 (Nx) , E4 (Nx) , En (Nx);\n  complex_field<double,1> hfh1(boost::extents[Nv][Nx]) , hfh2(boost::extents[Nv][Nx]) ,\n                          hfh3(boost::extents[Nv][Nx]) , hfh4(boost::extents[Nv][Nx]) ,\n                          hfhn(boost::extents[Nv][Nx]) ;\n\n  const double alpha1=1./(4.-std::cbrt(4.)), alpha2=alpha1, alpha3=1./(1.-SQ(std::cbrt(4.)));\n\n  const double g1 = alpha1, g2 = alpha1+alpha2;\n  const double w1 = (g2*(1.-g2))/(g1*(g1-1.)-g2*(g2-1.)) , w2 = 1.-w1 , w3 = w2 , w4 = w1;\n\n  while (  current_time < Tf ) {\n  /*std::cout << *std::max_element( hfh[100].begin() , hfh[100].end() , [](auto a,auto b){\n    return std::abs(a) < std::abs(b);\n  }) << \" \" << std::endl;*/\n\n///////////////////////////////////////////////////////////////////////////////\n// Suzuki /////////////////////////////////////////////////////////////////////\n\n    /*    \n    Lie.phi_a(0.5*dt,uc,E,hfh);\n    Lie.phi_c(0.5*dt,uc,E,hfh);\n    Lie.phi_b(dt,uc,E,hfh);\n    Lie.phi_c(0.5*dt,uc,E,hfh);\n    Lie.phi_a(0.5*dt,uc,E,hfh);\n    */\n\n    // Strang alpha1\n    Lie.phi_a(alpha1*0.5*dt,uc,E,hfh);\n    Lie.phi_c(alpha1*0.5*dt,uc,E,hfh);\n    Lie.phi_b(alpha1*dt,uc,E,hfh);\n    Lie.phi_c(alpha1*0.5*dt,uc,E,hfh);\n    Lie.phi_a(alpha1*0.5*dt,uc,E,hfh);\n\n    // Strang alpha2\n    Lie.phi_a(alpha2*0.5*dt,uc,E,hfh);\n    Lie.phi_c(alpha2*0.5*dt,uc,E,hfh);\n    Lie.phi_b(alpha2*dt,uc,E,hfh);\n    Lie.phi_c(alpha2*0.5*dt,uc,E,hfh);\n    Lie.phi_a(alpha2*0.5*dt,uc,E,hfh);\n\n    // Strang alpha3\n    Lie.phi_a(alpha3*0.5*dt,uc,E,hfh);\n    Lie.phi_c(alpha3*0.5*dt,uc,E,hfh);\n    Lie.phi_b(alpha3*dt,uc,E,hfh);\n    Lie.phi_c(alpha3*0.5*dt,uc,E,hfh);\n    Lie.phi_a(alpha3*0.5*dt,uc,E,hfh);\n\n    // Strang alpha2\n    Lie.phi_a(alpha2*0.5*dt,uc,E,hfh);\n    Lie.phi_c(alpha2*0.5*dt,uc,E,hfh);\n    Lie.phi_b(alpha2*dt,uc,E,hfh);\n    Lie.phi_c(alpha2*0.5*dt,uc,E,hfh);\n    Lie.phi_a(alpha2*0.5*dt,uc,E,hfh);\n\n    // Strang alpha1\n    Lie.phi_a(alpha1*0.5*dt,uc,E,hfh);\n    Lie.phi_c(alpha1*0.5*dt,uc,E,hfh);\n    Lie.phi_b(alpha1*dt,uc,E,hfh);\n    Lie.phi_c(alpha1*0.5*dt,uc,E,hfh);\n    Lie.phi_a(alpha1*0.5*dt,uc,E,hfh);\n\n\n///////////////////////////////////////////////////////////////////////////////\n// MONITORING /////////////////////////////////////////////////////////////////\n\n    for ( auto k=0 ; k<Nv ; ++k ) {\n      fft::ifft(hfh[k].begin(),hfh[k].end(),fh[k].begin());\n    }\n\n    double total_energy = kinetic_energy(fh);\n    for ( const auto ei : E ) {\n      total_energy += ei*ei*fh.step.dx;\n    }\n    {\n      auto rhoh = fh.density();\n      fft::spectrum_ hrhoh(Nx); hrhoh.fft(&rhoh[0]);\n      fft::spectrum_ hE(Nx); hE.fft(&E[0]);\n      fft::spectrum_ hrhoc(Nx);\n      hrhoc[0] = I*kx[0]*hE[0] - hrhoh[0] + 1.;\n      for ( auto i=1 ; i<Nx ; ++i ) {\n        hrhoc[i] = I*kx[i]*hE[i] - hrhoh[i];\n      }\n      ublas::vector<double> rhoc (Nx,0.); hrhoc.ifft(&rhoc[0]);\n\n      for ( auto i=0 ; i<Nx ; ++i ) {\n        total_energy += rhoc[i]*uc[i]*uc[i]*fh.step.dx;\n      }\n    }\n    H.push_back( total_energy );\n\n    double electric_energy = 0.;\n    for ( const auto & ei : E ) { electric_energy += ei*ei*fh.step.dx; }\n    ee.push_back( std::sqrt(electric_energy) );\n\n    // increment time\n    current_time += dt;\n    t.push_back(current_time);\n\n\n    ++iter;\n    //if ( current_time+dt > Tf ) { dt = Tf - current_time; }\n  } // while (  current_time < Tf ) // end of time loop\n\n  std::ofstream of(\"H.dat\");\n  std::transform( H.cbegin() , H.cend() , std::ostream_iterator<std::string>(of,\"\\n\") ,\n    [&,count=0] ( const double h ) mutable {\n      std::stringstream ss;\n      ss << t[count++] << \" \" << h << \" \" << std::abs(H[0]-h)/std::abs(H[0]);\n      return ss.str();\n  });\n  of.close();\n\n  of.open(\"ee.dat\");\n  std::transform( ee.cbegin() , ee.cend() , std::ostream_iterator<std::string>(of,\"\\n\") ,\n    [&,count=0] ( const double e ) mutable {\n      std::stringstream ss;\n      ss << t[count++] << \" \" << e;\n      return ss.str();\n  });\n  of.close();\n\n  for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) { fft::ifft(hfh[k].begin(),hfh[k].end(),fh[k].begin()); }\n  fh.write(\"vp.dat\");\n  \n  double h_max = std::abs(*std::max_element( H.begin() , H.end() ,\n    [&] ( double a , double b ) {\n      return std::abs(a-H[0])/std::abs(H[0]) < std::abs(b-H[0])/std::abs(H[0]);\n    }\n  ));\n  \n  double h_last = H.back();\n  //return std::make_pair(std::abs(H[0]-h_last)/std::abs(H[0]),std::abs(H[0]-h_max)/std::abs(H[0]));\n  double h = std::abs(*std::max_element( H.begin() , H.end() , [&](double a,double b){return ( std::abs((a-H[0])/std::abs(H[0])) < std::abs((b-H[0])/std::abs(H[0])) );} ));\n  return std::abs((h-H[0])/std::abs(H[0]));\n}\n\nint\nmain ( int argc , char const * argv[] )\n{\n  const std::size_t Nx = 75 , Nv = 1024;\n  const double dt_max = 1.;//3.*16./Nv;\n\n  for ( auto i=1 ; i<10 ; ++i ) {\n    double dt = dt_max/double(i);\n    std::cout << dt << \" \" << std::flush;\n    double h = error_H(Nx,Nv,dt);\n    std::cout << h << std::endl;\n  }\n  return 0;\n}\n", "meta": {"hexsha": "e02874cda3d274f6cb91435cd2d9fbc8491ce0ae", "size": 8233, "ext": "cc", "lang": "C++", "max_stars_repo_path": "code/order_H_suzuki.cc", "max_stars_repo_name": "kivvix/vlasovpp", "max_stars_repo_head_hexsha": "123072d42ddcceef9278e0cd3ac18d5b3fa4b3c0", "max_stars_repo_licenses": ["MIT"], "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/order_H_suzuki.cc", "max_issues_repo_name": "kivvix/vlasovpp", "max_issues_repo_head_hexsha": "123072d42ddcceef9278e0cd3ac18d5b3fa4b3c0", "max_issues_repo_licenses": ["MIT"], "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/order_H_suzuki.cc", "max_forks_repo_name": "kivvix/vlasovpp", "max_forks_repo_head_hexsha": "123072d42ddcceef9278e0cd3ac18d5b3fa4b3c0", "max_forks_repo_licenses": ["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.4133858268, "max_line_length": 172, "alphanum_fraction": 0.5539900401, "num_tokens": 2874, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.6370308013713524, "lm_q1q2_score": 0.47905517250353685}}
{"text": "#include <cassert>\n#include <cmath>\n#include <cstdint>\n#include <chrono>\n#include <iostream>\n#include <tuple>\n\n#include <boost/optional.hpp>\n\n\n#define MEASURE(CODE_TO_MEASURE) \\\n    { \\\n    auto start = std::chrono::system_clock::now(); \\\n    CODE_TO_MEASURE \\\n    auto end = std::chrono::system_clock::now(); \\\n    std::chrono::duration<double> difference = end - start; \\\n    std::cout << difference.count(); \\\n    }\n\n\nenum class ECode : uint64_t {\n    OK = 0xFFF0'0000'0000'0001,\n    ERROR,\n    INPUT_IS_NAN,\n    INPUT_IS_INFINITE,\n    INPUT_IS_NEGATIVE,\n};\n\nunion Result_or_code\n{\n    double result;\n    ECode code;\n    Result_or_code(double x) {result = x;}\n    Result_or_code(const ECode& c) {code = c;}\n    operator double() {return result;}\n    operator ECode() {return code;}\n};\n\nResult_or_code sqrt_or_not(double x) {\n    if (std::isnan(x))\n        return ECode::INPUT_IS_NAN;\n    if (std::isinf(x))\n        return ECode::INPUT_IS_INFINITE;\n    if(x < 0)\n        return ECode::INPUT_IS_NEGATIVE;\n    return std::sqrt(x);\n}\n\nboost::optional<double> optional_sqrt(double x) {\n    if (std::isnan(x) || std::isinf(x) || x < 0)\n        return boost::optional<double>();\n    return boost::optional<double>(std::sqrt(x));\n}\n\ndouble sqrt_or_throw(double x) {\n    if (std::isnan(x))\n        throw std::invalid_argument(\"\");\n    if (std::isinf(x))\n        throw std::invalid_argument(\"\");\n    if(x < 0)\n        throw std::domain_error(\"\");\n    return std::sqrt(x);\n}\n\nusing CodeAndResult = std::tuple<ECode, double>;\nCodeAndResult code_and_sqrt(double x) {\n    if (std::isnan(x))\n        return std::make_tuple(ECode::INPUT_IS_NAN, 0.);\n    if (std::isinf(x))\n        return std::make_tuple(ECode::INPUT_IS_INFINITE, 0.);\n    if(x < 0)\n        return std::make_tuple(ECode::INPUT_IS_NEGATIVE, 0.);\n    return std::make_tuple(ECode::OK, std::sqrt(x));\n}\n\nvoid measure_3_comparisons() {\n    size_t errors = 0;\n    size_t results = 0;\n    double total = 0.;\n    std::cout << \"3 comparisons: \";\n    MEASURE(\n        for(double x = -1024.; x <= 1024.; x += 1./65536.) {\n            auto root = sqrt_or_not(x);\n            if(root == ECode::INPUT_IS_NAN || root == ECode::INPUT_IS_INFINITE || root == ECode::INPUT_IS_NEGATIVE)\n                ++errors;\n            else {\n                ++results;\n                total += root;\n            }\n        }\n    );\n    std::cout << \"\\nsize of union: \" << sizeof(Result_or_code);\n    std::cout << \"\\nsanity check: \" << ((errors == results - 1) == 1. ? \"passed\" : \"not passed!\") << \"; sum: \" << total << \"\\n\" << std::endl;\n}\n\nvoid measure_isnan() {\n    size_t errors = 0;\n    size_t results = 0;\n    double total = 0.;\n    std::cout << \"is nan: \";\n    MEASURE(\n        for(double x = -1024.; x <= 1024.; x += 1./65536.) {\n            auto root = sqrt_or_not(x);\n            if(std::isnan(root))\n                ++errors;\n            else {\n                ++results;\n                total += root;\n            }\n        }\n    );\n    std::cout << \"\\nsanity check: \" << ((errors == results - 1) == 1. ? \"passed\" : \"not passed!\") << \"; sum: \" << total << \"\\n\" << std::endl;\n}\n\nvoid measure_non_less_than_error() {\n    size_t errors = 0;\n    size_t results = 0;\n    double total = 0.;\n    std::cout << \"no less than error: \";\n    MEASURE(\n        for(double x = -1024.; x <= 1024.; x += 1./65536.) {\n            auto root = sqrt_or_not(x);\n            if(root >= ECode::ERROR)\n                ++errors;\n            else {\n                ++results;\n                total += root;\n            }\n        }\n    );\n    std::cout << \"\\nsanity check: \" << ((errors == results - 1) == 1. ? \"passed\" : \"not passed!\") << \"; sum: \" << total << \"\\n\" << std::endl;\n}\n\nvoid measure_non_less_than_error_storing() {\n    size_t errors = 0;\n    size_t results = 0;\n    double total = 0.;\n    std::cout << \"no less than error: \";\n    MEASURE(\n        std::vector<Result_or_code> results_or_codes;\n        for(double x = -1024.; x <= 1024.; x += 1./65536.) {\n            results_or_codes.push_back(sqrt_or_not(x));\n            if(results_or_codes.back() >= ECode::ERROR)\n                ++errors;\n            else {\n                ++results;\n                total += results_or_codes.back();\n            }\n        }\n    );\n    std::cout << \"\\nsanity check: \" << ((errors == results - 1) == 1. ? \"passed\" : \"not passed!\") << \"; sum: \" << total << \"\\n\" << std::endl;\n}\n\nvoid measure_tuple() {\n    size_t errors = 0;\n    size_t results = 0;\n    double total = 0.;\n    std::cout << \"tuple: \";\n    MEASURE(\n        for(double x = -1024.; x <= 1024.; x += 1./65536.) {\n            auto code_and_root = code_and_sqrt(x);\n            if(std::get<0>(code_and_root) != ECode::OK)\n                ++errors;\n            else {\n                ++results;\n                total += std::get<1>(code_and_root);\n            }\n        }\n    );\n    std::cout << \"\\nsize of tuple: \" << sizeof(std::tuple<ECode, double>);\n    std::cout << \"\\nsanity check: \" << ((errors == results - 1) == 1. ? \"passed\" : \"not passed!\") << \"; sum: \" << total << \"\\n\" << std::endl;\n}\n\nvoid measure_tuple_storing() {\n    size_t errors = 0;\n    size_t results = 0;\n    double total = 0.;\n    std::cout << \"tuple: \";\n    MEASURE(\n        std::vector<CodeAndResult> results_and_codes;\n        for(double x = -1024.; x <= 1024.; x += 1./65536.) {\n            results_and_codes.push_back(code_and_sqrt(x));\n            if(std::get<0>(results_and_codes.back()) != ECode::OK)\n                ++errors;\n            else {\n                ++results;\n                total += std::get<1>(results_and_codes.back());\n            }\n        }\n    );\n    std::cout << \"\\nsize of tuple: \" << sizeof(std::tuple<ECode, double>);\n    std::cout << \"\\nsanity check: \" << ((errors == results - 1) == 1. ? \"passed\" : \"not passed!\") << \"; sum: \" << total << \"\\n\" << std::endl;\n}\n\nvoid measure_optional() {\n    size_t errors = 0;\n    size_t results = 0;\n    double total = 0.;\n    std::cout << \"optional: \";\n    MEASURE(\n        for(double x = -1024.; x <= 1024.; x += 1./65536.) {\n            auto optional_root = optional_sqrt(x);\n            if(!optional_root)\n                ++errors;\n            else {\n                ++results;\n                total += *optional_root;\n            }\n        }\n    );\n    std::cout << \"\\nsize of optional: \" << sizeof(boost::optional<double>);\n    std::cout << \"\\nsanity check: \" << ((errors == results - 1) == 1. ? \"passed\" : \"not passed!\") << \"; sum: \" << total << \"\\n\" << std::endl;\n}\n\nvoid measure_optional_storing() {\n    size_t errors = 0;\n    size_t results = 0;\n    double total = 0.;\n    std::cout << \"optional: \";\n    MEASURE(\n        std::vector<boost::optional<double>> optional_results;\n        for(double x = -1024.; x <= 1024.; x += 1./65536.) {\n            optional_results.push_back(optional_sqrt(x));\n            if(!optional_results.back())\n                ++errors;\n            else {\n                ++results;\n                total += *optional_results.back();\n            }\n        }\n    );\n    std::cout << \"\\nsize of optional: \" << sizeof(boost::optional<double>);\n    std::cout << \"\\nsanity check: \" << ((errors == results - 1) == 1. ? \"passed\" : \"not passed!\") << \"; sum: \" << total << \"\\n\" << std::endl;\n}\n\nvoid measure_throw() {\n    size_t errors = 0;\n    size_t results = 0;\n    double total = 0.;\n    std::cout << \"throw (512 less experiments!): \";\n    MEASURE(\n        for(double x = -2.; x <= 2.; x += 1./65536.) {\n            try {\n                auto root = sqrt_or_throw(x);\n                total += root;\n                ++results;\n            } catch (const std::logic_error& e) {\n                ++errors;\n            }\n        }\n    );\n    std::cout << \"\\nsanity check: \" << ((errors == results - 1) == 1. ? \"passed\" : \"not passed!\") << \"; sum: \" << total << \"\\n\" << std::endl;\n}\n\n\nint main(void) {\n    measure_3_comparisons();\n    measure_isnan();\n    measure_non_less_than_error();\n    measure_non_less_than_error_storing();\n    measure_tuple();\n    measure_tuple_storing();\n    measure_optional();\n    measure_optional_storing();\n    measure_throw();\n}\n", "meta": {"hexsha": "3eea72a19f288413c17e50aa3f57f05f61217d36", "size": 8088, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "exp/nan_code/measurements.cpp", "max_stars_repo_name": "NMinhNguyen/wordsandbuttons", "max_stars_repo_head_hexsha": "beba7f73c46f40790ad2482c2c0c04cfa5f626a4", "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": "exp/nan_code/measurements.cpp", "max_issues_repo_name": "NMinhNguyen/wordsandbuttons", "max_issues_repo_head_hexsha": "beba7f73c46f40790ad2482c2c0c04cfa5f626a4", "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": "exp/nan_code/measurements.cpp", "max_forks_repo_name": "NMinhNguyen/wordsandbuttons", "max_forks_repo_head_hexsha": "beba7f73c46f40790ad2482c2c0c04cfa5f626a4", "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.2921348315, "max_line_length": 141, "alphanum_fraction": 0.5129821958, "num_tokens": 2205, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125626441471, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.47905517060462083}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   tstLinLinLinUnitBaseInterpolatedPartiallyTabularBasicBivariateDistribution.cpp\n//! \\author Alex Robinson\n//! \\brief  The interpolated partially tabular two-dimensional dist. unit tests\n//!         (LinLinLin Unit-base interpolation)\n//!\n//---------------------------------------------------------------------------//\n\n// Std Lib Includes\n#include <iostream>\n#include <sstream>\n#include <memory>\n\n// Boost Includes\n#include <boost/units/systems/cgs.hpp>\n#include <boost/units/io.hpp>\n\n// FRENSIE Includes\n#include \"Utility_InterpolatedPartiallyTabularBasicBivariateDistribution.hpp\"\n#include \"Utility_DeltaDistribution.hpp\"\n#include \"Utility_UniformDistribution.hpp\"\n#include \"Utility_ExponentialDistribution.hpp\"\n#include \"Utility_ElectronVoltUnit.hpp\"\n#include \"Utility_BarnUnit.hpp\"\n#include \"Utility_UnitTestHarnessWithMain.hpp\"\n#include \"ArchiveTestHelpers.hpp\"\n\n//---------------------------------------------------------------------------//\n// Testing Types\n//---------------------------------------------------------------------------//\n\nusing boost::units::quantity;\nusing Utility::Units::MegaElectronVolt;\nusing Utility::Units::MeV;\nusing Utility::Units::Barn;\nusing Utility::Units::barn;\nusing Utility::Units::barns;\nnamespace cgs = boost::units::cgs;\n\ntypedef TestArchiveHelper::TestArchives TestArchives;\n\n//---------------------------------------------------------------------------//\n// Testing Variables\n//---------------------------------------------------------------------------//\nstd::shared_ptr<Utility::UnitAwarePartiallyTabularBasicBivariateDistribution<MegaElectronVolt,cgs::length,Barn> >\n  unit_aware_distribution;\n\nstd::shared_ptr<Utility::PartiallyTabularBasicBivariateDistribution> distribution;\n\n//---------------------------------------------------------------------------//\n// Tests.\n//---------------------------------------------------------------------------//\n// Check that the distribution is tabular in the primary dimension\nFRENSIE_UNIT_TEST( InterpolatedPartiallyTabularBasicBivariateDistribution,\n                   isPrimaryDimensionTabular )\n{\n  FRENSIE_CHECK( distribution->isPrimaryDimensionTabular() );\n}\n\n//---------------------------------------------------------------------------//\n// Check that the unit-aware distribution is tabular in the primary dimension\nFRENSIE_UNIT_TEST( UnitAwareInterpolatedPartiallyTabularBasicBivariateDistribution,\n                   isPrimaryDimensionTabular )\n{\n  FRENSIE_CHECK( unit_aware_distribution->isPrimaryDimensionTabular() );\n}\n\n//---------------------------------------------------------------------------//\n// Check that the distribution is continuous in the primary dimension\nFRENSIE_UNIT_TEST( InterpolatedPartiallyTabularBasicBivariateDistribution,\n                   isPrimaryDimensionContinuous )\n{\n  FRENSIE_CHECK( distribution->isPrimaryDimensionContinuous() );\n}\n\n//---------------------------------------------------------------------------//\n// Check that the unit-aware distribution is continuous in the primary dim.\nFRENSIE_UNIT_TEST( UnitAwareInterpolatedPartiallyTabularBasicBivariateDistribution,\n                   isPrimaryDimensionContinuous )\n{\n  FRENSIE_CHECK( unit_aware_distribution->isPrimaryDimensionTabular() );\n}\n\n//---------------------------------------------------------------------------//\n// Check that the distribution's primary dimension lower bound can be returned\nFRENSIE_UNIT_TEST( InterpolatedPartiallyTabularBasicBivariateDistribution,\n                   getLowerBoundOfPrimaryIndepVar )\n{\n  FRENSIE_CHECK_EQUAL( distribution->getLowerBoundOfPrimaryIndepVar(), 0.0 );\n}\n\n//---------------------------------------------------------------------------//\n// Check that the unit-aware distribution's primary dimension lower bound can\n// be returned\nFRENSIE_UNIT_TEST( UnitAwareInterpolatedPartiallyTabularBasicBivariateDistribution,\n                   getLowerBoundOfPrimaryIndepVar )\n{\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->getLowerBoundOfPrimaryIndepVar(), 0.0*MeV );\n}\n\n//---------------------------------------------------------------------------//\n// Check that the distribution's primary dimension upper bound can be returned\nFRENSIE_UNIT_TEST( InterpolatedPartiallyTabularBasicBivariateDistribution,\n                   getUpperBoundOfPrimaryIndepVar )\n{\n  FRENSIE_CHECK_EQUAL( distribution->getUpperBoundOfPrimaryIndepVar(), 2.0 );\n}\n\n//---------------------------------------------------------------------------//\n// Check that the unit-aware distribution's primary dimension upper bound can\n// be returned\nFRENSIE_UNIT_TEST( UnitAwareInterpolatedPartiallyTabularBasicBivariateDistribution,\n                   getUpperBoundOfPrimaryIndepVar )\n{\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->getUpperBoundOfPrimaryIndepVar(), 2.0*MeV );\n}\n\n//---------------------------------------------------------------------------//\n// Check that the lower bound of the conditional distribution can be returned\nFRENSIE_UNIT_TEST( InterpolatedPartiallyTabularBasicBivariateDistribution,\n                   getLowerBoundOfSecondaryConditionalIndepVar )\n{\n  // Before the first bin - no extension\n  FRENSIE_CHECK_EQUAL( distribution->getLowerBoundOfSecondaryConditionalIndepVar(-1.0),\n                       0.0 );\n\n  // Before the first bin - with extension\n  distribution->extendBeyondPrimaryIndepLimits();\n\n  FRENSIE_CHECK_EQUAL( distribution->getLowerBoundOfSecondaryConditionalIndepVar(-1.0),\n                       0.0 );\n\n  distribution->limitToPrimaryIndepLimits();\n\n  // On the second bin boundary\n  FRENSIE_CHECK_EQUAL( distribution->getLowerBoundOfSecondaryConditionalIndepVar( 0.0 ),\n                       0.0 );\n\n  // In the second bin\n  FRENSIE_CHECK_EQUAL( distribution->getLowerBoundOfSecondaryConditionalIndepVar( 0.5 ),\n                       1.25 );\n\n  // On the third bin boundary\n  FRENSIE_CHECK_EQUAL( distribution->getLowerBoundOfSecondaryConditionalIndepVar( 1.0 ),\n                       2.5 );\n\n  // In the third bin\n  FRENSIE_CHECK_EQUAL( distribution->getLowerBoundOfSecondaryConditionalIndepVar( 1.5 ),\n                       1.25 );\n\n  // On the upper bin boundary\n  FRENSIE_CHECK_EQUAL( distribution->getLowerBoundOfSecondaryConditionalIndepVar( 2.0 ),\n                       0.0 );\n\n  // Beyond the third bin - no extension\n  FRENSIE_CHECK_EQUAL( distribution->getLowerBoundOfSecondaryConditionalIndepVar( 3.0 ),\n                       0.0 );\n\n  // Beyond the third bin - with extension\n  distribution->extendBeyondPrimaryIndepLimits();\n\n  FRENSIE_CHECK_EQUAL( distribution->getLowerBoundOfSecondaryConditionalIndepVar( 3.0 ),\n                       0.0 );\n\n  distribution->limitToPrimaryIndepLimits();\n}\n\n//---------------------------------------------------------------------------//\n// Check that the lower bound of the unit-aware conditional distribution can be\n// returned\nFRENSIE_UNIT_TEST( UnitAwareInterpolatedPartiallyTabularBasicBivariateDistribution,\n                   getLowerBoundOfSecondaryConditionalIndepVar )\n{\n  // Before the first bin - no extension\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->getLowerBoundOfSecondaryConditionalIndepVar( -1.0*MeV ),\n                       0.0*cgs::centimeter );\n\n  // Before the first bin - with extension\n  unit_aware_distribution->extendBeyondPrimaryIndepLimits();\n\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->getLowerBoundOfSecondaryConditionalIndepVar( -1.0*MeV ),\n                       0.0*cgs::centimeter );\n\n  unit_aware_distribution->limitToPrimaryIndepLimits();\n\n  // On the second bin boundary\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->getLowerBoundOfSecondaryConditionalIndepVar( 0.0*MeV ),\n                       0.0*cgs::centimeter );\n\n  // In the second bin\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->getLowerBoundOfSecondaryConditionalIndepVar( 0.5*MeV ),\n                       1.25*cgs::centimeter );\n\n  // On the third bin boundary\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->getLowerBoundOfSecondaryConditionalIndepVar( 1.0*MeV ),\n                       2.5*cgs::centimeter );\n\n  // In the third bin\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->getLowerBoundOfSecondaryConditionalIndepVar( 1.5*MeV ),\n                       1.25*cgs::centimeter );\n\n  // On the upper bin boundary\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->getLowerBoundOfSecondaryConditionalIndepVar( 2.0*MeV ),\n                       0.0*cgs::centimeter );\n\n  // Beyond the third bin - no extension\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->getLowerBoundOfSecondaryConditionalIndepVar( 3.0*MeV ),\n                       0.0*cgs::centimeter );\n\n  // Beyond the third bin - with extension\n  unit_aware_distribution->extendBeyondPrimaryIndepLimits();\n\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->getLowerBoundOfSecondaryConditionalIndepVar( 3.0*MeV ),\n                       0.0*cgs::centimeter );\n\n  unit_aware_distribution->limitToPrimaryIndepLimits();\n}\n\n//---------------------------------------------------------------------------//\n// Check that the upper bound of the conditional distribution can be returned\nFRENSIE_UNIT_TEST( InterpolatedPartiallyTabularBasicBivariateDistribution,\n                   getUpperBoundOfSecondaryConditionalIndepVar )\n{\n  // Before the first bin - no extension\n  FRENSIE_CHECK_EQUAL( distribution->getUpperBoundOfSecondaryConditionalIndepVar(-1.0),\n                       0.0 );\n\n  // Before the first bin - with extension\n  distribution->extendBeyondPrimaryIndepLimits();\n\n  FRENSIE_CHECK_EQUAL( distribution->getUpperBoundOfSecondaryConditionalIndepVar(-1.0),\n                       10.0 );\n\n  distribution->limitToPrimaryIndepLimits();\n\n  // On the second bin boundary\n  FRENSIE_CHECK_EQUAL( distribution->getUpperBoundOfSecondaryConditionalIndepVar( 0.0 ),\n                       10.0 );\n\n  // In the second bin\n  FRENSIE_CHECK_EQUAL( distribution->getUpperBoundOfSecondaryConditionalIndepVar( 0.5 ),\n                       8.75 );\n\n  // On the third bin boundary\n  FRENSIE_CHECK_EQUAL( distribution->getUpperBoundOfSecondaryConditionalIndepVar( 1.0 ),\n                       7.5 );\n\n  // In the third bin\n  FRENSIE_CHECK_EQUAL( distribution->getUpperBoundOfSecondaryConditionalIndepVar( 1.5 ),\n                       8.75 );\n\n  // On the upper bin boundary\n  FRENSIE_CHECK_EQUAL( distribution->getUpperBoundOfSecondaryConditionalIndepVar( 2.0 ),\n                       10.0 );\n\n  // Beyond the third bin - no extension\n  FRENSIE_CHECK_EQUAL( distribution->getUpperBoundOfSecondaryConditionalIndepVar( 3.0 ),\n                       0.0 );\n\n  // Beyond the third bin - with extension\n  distribution->extendBeyondPrimaryIndepLimits();\n\n  FRENSIE_CHECK_EQUAL( distribution->getUpperBoundOfSecondaryConditionalIndepVar( 3.0 ),\n                       10.0 );\n\n  distribution->limitToPrimaryIndepLimits();\n}\n\n//---------------------------------------------------------------------------//\n// Check that the upper bound of the unit-aware conditional distribution can be\n// returned\nFRENSIE_UNIT_TEST( UnitAwareInterpolatedPartiallyTabularBasicBivariateDistribution,\n                   getUpperBoundOfSecondaryConditionalIndepVar )\n{\n  // Before the first bin - no extension\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->getUpperBoundOfSecondaryConditionalIndepVar( -1.0*MeV ),\n                       0.0*cgs::centimeter );\n\n  // Before the first bin - with extension\n  unit_aware_distribution->extendBeyondPrimaryIndepLimits();\n\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->getUpperBoundOfSecondaryConditionalIndepVar( -1.0*MeV ),\n                       10.0*cgs::centimeter );\n\n  unit_aware_distribution->limitToPrimaryIndepLimits();\n\n  // On the second bin boundary\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->getUpperBoundOfSecondaryConditionalIndepVar( 0.0*MeV ),\n                       10.0*cgs::centimeter );\n\n  // In the second bin\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->getUpperBoundOfSecondaryConditionalIndepVar( 0.5*MeV ),\n                       8.75*cgs::centimeter );\n\n  // On the third bin boundary\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->getUpperBoundOfSecondaryConditionalIndepVar( 1.0*MeV ),\n                       7.5*cgs::centimeter );\n\n  // In the third bin\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->getUpperBoundOfSecondaryConditionalIndepVar( 1.5*MeV ),\n                       8.75*cgs::centimeter );\n\n  // On the upper bin boundary\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->getUpperBoundOfSecondaryConditionalIndepVar( 2.0*MeV ),\n                       10.0*cgs::centimeter );\n\n  // Beyond the third bin - no extension\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->getUpperBoundOfSecondaryConditionalIndepVar( 3.0*MeV ),\n                       0.0*cgs::centimeter );\n\n  // Beyond the third bin - with extension\n  unit_aware_distribution->extendBeyondPrimaryIndepLimits();\n\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->getUpperBoundOfSecondaryConditionalIndepVar( 3.0*MeV ),\n                       10.0*cgs::centimeter );\n\n  unit_aware_distribution->limitToPrimaryIndepLimits();\n}\n\n//---------------------------------------------------------------------------//\n// Check that the bounds of two distributions can be compared\nFRENSIE_UNIT_TEST( InterpolatedPartiallyTabularBasicBivariateDistribution,\n                   hasSamePrimaryBounds )\n{\n  // Self test\n  FRENSIE_CHECK( distribution->hasSamePrimaryBounds( *distribution ) );\n\n  // Create a test distribution with same lower bound, different upper bound\n  std::shared_ptr<Utility::PartiallyTabularBasicBivariateDistribution> test_dist;\n\n  {\n    std::vector<double> primary_grid( 2 );\n    std::vector<std::shared_ptr<const Utility::UnivariateDistribution> >\n      secondary_dists( 2 );\n\n    // Create the secondary distribution in the first bin\n    primary_grid[0] = 0.0;\n    secondary_dists[0].reset( new Utility::UniformDistribution( 0.0, 10.0, 0.1 ) );\n\n    // Create the secondary distribution in the second bin\n    primary_grid[1] = 1.0;\n    secondary_dists[1].reset( new Utility::ExponentialDistribution( 1.0, 1.0, 0.0, 10.0 ) );\n\n    test_dist.reset( new Utility::InterpolatedPartiallyTabularBasicBivariateDistribution<Utility::UnitBase<Utility::LinLinLin> >(\n                                                           primary_grid,\n                                                           secondary_dists ) );\n  }\n\n  FRENSIE_CHECK( !distribution->hasSamePrimaryBounds( *test_dist ) );\n\n  // Create a test distribution with different lower bound, same upper bound\n  {\n    std::vector<double> primary_grid( 2 );\n    std::vector<std::shared_ptr<const Utility::UnivariateDistribution> >\n      secondary_dists( 2 );\n\n    // Create the secondary distribution in the first bin\n    primary_grid[0] = 1.0;\n    secondary_dists[0].reset( new Utility::UniformDistribution( 0.0, 10.0, 0.1 ) );\n\n    // Create the secondary distribution in the second bin\n    primary_grid[1] = 2.0;\n    secondary_dists[1].reset( new Utility::ExponentialDistribution( 1.0, 1.0, 0.0, 10.0 ) );\n\n    test_dist.reset( new Utility::InterpolatedPartiallyTabularBasicBivariateDistribution<Utility::UnitBase<Utility::LinLinLin> >(\n                                                           primary_grid,\n                                                           secondary_dists ) );\n  }\n\n  FRENSIE_CHECK( !distribution->hasSamePrimaryBounds( *test_dist ) );\n\n  // Create a test distribution with different bounds\n  {\n    std::vector<double> primary_grid( 2 );\n    std::vector<std::shared_ptr<const Utility::UnivariateDistribution> >\n      secondary_dists( 2 );\n\n    // Create the secondary distribution in the first bin\n    primary_grid[0] = 0.5;\n    secondary_dists[0].reset( new Utility::UniformDistribution( 0.0, 10.0, 0.1 ) );\n\n    // Create the secondary distribution in the second bin\n    primary_grid[1] = 1.5;\n    secondary_dists[1].reset( new Utility::ExponentialDistribution( 1.0, 1.0, 0.0, 10.0 ) );\n\n    test_dist.reset( new Utility::InterpolatedPartiallyTabularBasicBivariateDistribution<Utility::UnitBase<Utility::LinLinLin> >(\n                                                           primary_grid,\n                                                           secondary_dists ) );\n  }\n\n  FRENSIE_CHECK( !distribution->hasSamePrimaryBounds( *test_dist ) );\n}\n\n//---------------------------------------------------------------------------//\n// Check that the distribution can be evaluated\nFRENSIE_UNIT_TEST( InterpolatedPartiallyTabularBasicBivariateDistribution, evaluate )\n{\n  // Before the first bin - no extension\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( -1.0, -1.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( -1.0, 0.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( -1.0, 5.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( -1.0, 10.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( -1.0, 11.0 ), 0.0 );\n\n  // Before the first bin - with extension\n  distribution->extendBeyondPrimaryIndepLimits();\n\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( -1.0, -1.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( -1.0, 0.0 ), 0.1 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( -1.0, 5.0 ), 0.1 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( -1.0, 10.0 ), 0.1 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( -1.0, 11.0 ), 0.0 );\n\n  distribution->limitToPrimaryIndepLimits();\n\n  // On the second bin boundary\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( 0.0, -1.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( 0.0, 0.0 ), 1.0 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( 0.0, 10.0 ), exp( -10.0 ) );\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( 0.0, 11.0 ), 0.0 );\n\n  // In the second bin\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( 0.5, 1.0 ), 0.0 );\n  FRENSIE_CHECK_FLOATING_EQUALITY( distribution->evaluate( 0.5, 1.25 ),\n                          1.0,\n                          1e-15 );\n  FRENSIE_CHECK_FLOATING_EQUALITY( distribution->evaluate( 0.5, 5.0 ),\n                          0.33782529799939026,\n                          1e-15 );\n  FRENSIE_CHECK_FLOATING_EQUALITY( distribution->evaluate( 0.5, 8.75 ),\n                          0.33336359995317505,\n                          1e-15 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( 0.5, 9.0 ), 0.0 );\n\n  // On the third bin boundary\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( 1.0, 2.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( 1.0, 2.5 ), 1.0 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( 1.0, 5.0 ), 1.0 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( 1.0, 7.5 ), 1.0 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( 1.0, 8.0 ), 0.0 );\n\n  // In the third bin\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( 1.5, 1.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( 1.5, 1.25 ), 0.4 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( 1.5, 5.0 ), 0.4 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( 1.5, 8.75 ), 0.4 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( 1.5, 9.0 ), 0.0 );\n\n  // On the upper bin boundary\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( 2.0, -1.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( 2.0, 0.0 ), 0.1 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( 2.0, 5.0 ), 0.1 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( 2.0, 10.0 ), 0.1 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( 2.0, 11.0 ), 0.0 );\n\n  // After the third bin - no extension\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( 3.0, -1.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( 3.0, 0.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( 3.0, 5.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( 3.0, 10.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( 3.0, 11.0 ), 0.0 );\n\n  // After the third bin - with extension\n  distribution->extendBeyondPrimaryIndepLimits();\n\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( 3.0, -1.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( 3.0, 0.0 ), 0.1 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( 3.0, 5.0 ), 0.1 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( 3.0, 10.0 ), 0.1 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( 3.0, 11.0 ), 0.0 );\n\n  distribution->limitToPrimaryIndepLimits();\n}\n\n//---------------------------------------------------------------------------//\n// Check that the unit-aware distribution can be evaluated\nFRENSIE_UNIT_TEST( UnitAwareInterpolatedPartiallyTabularBasicBivariateDistribution,\n                   evaluate )\n{\n  // Before the first bin - no extension\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( -1.0*MeV, -1.0*cgs::centimeter ), 0.0*barn );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( -1.0*MeV, 0.0*cgs::centimeter ), 0.0*barn );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( -1.0*MeV, 5.0*cgs::centimeter ), 0.0*barn );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( -1.0*MeV, 10.0*cgs::centimeter ), 0.0*barn );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( -1.0*MeV, 11.0*cgs::centimeter ), 0.0*barn );\n\n  // Before the first bin - with extension\n  unit_aware_distribution->extendBeyondPrimaryIndepLimits();\n\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( -1.0*MeV, -1.0*cgs::centimeter ), 0.0*barn );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( -1.0*MeV, 0.0*cgs::centimeter ), 0.1*barns );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( -1.0*MeV, 5.0*cgs::centimeter ), 0.1*barns );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( -1.0*MeV, 10.0*cgs::centimeter ), 0.1*barns );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( -1.0*MeV, 11.0*cgs::centimeter ), 0.0*barn );\n\n  unit_aware_distribution->limitToPrimaryIndepLimits();\n\n  // On the second bin boundary\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( 0.0*MeV, -1.0*cgs::centimeter ), 0.0*barn );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( 0.0*MeV, 0.0*cgs::centimeter ), 1.0*barns );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( 0.0*MeV, 10.0*cgs::centimeter ), exp( -10.0 )*barns );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( 0.0*MeV, 11.0*cgs::centimeter ), 0.0*barn );\n\n  // In the second bin\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( 0.5*MeV, 1.0*cgs::centimeter ), 0.0*barn );\n  FRENSIE_CHECK_FLOATING_EQUALITY( unit_aware_distribution->evaluate( 0.5*MeV, 1.25*cgs::centimeter ),\n                          1.0*barns,\n                          1e-15 );\n  FRENSIE_CHECK_FLOATING_EQUALITY( unit_aware_distribution->evaluate( 0.5*MeV, 5.0*cgs::centimeter ),\n                          0.33782529799939026*barns,\n                          1e-15 );\n  FRENSIE_CHECK_FLOATING_EQUALITY( unit_aware_distribution->evaluate( 0.5*MeV, 8.75*cgs::centimeter ),\n                          0.33336359995317505*barns,\n                          1e-15 );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( 0.5*MeV, 9.0*cgs::centimeter ), 0.0*barn );\n\n  // On the third bin boundary\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( 1.0*MeV, 2.0*cgs::centimeter ), 0.0*barn );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( 1.0*MeV, 2.5*cgs::centimeter ), 1.0*barn );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( 1.0*MeV, 5.0*cgs::centimeter ), 1.0*barn );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( 1.0*MeV, 7.5*cgs::centimeter ), 1.0*barn );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( 1.0*MeV, 8.0*cgs::centimeter ), 0.0*barn );\n\n  // In the third bin\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( 1.5*MeV, 1.0*cgs::centimeter ), 0.0*barn );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( 1.5*MeV, 1.25*cgs::centimeter ), 0.4*barns );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( 1.5*MeV, 5.0*cgs::centimeter ), 0.4*barns );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( 1.5*MeV, 8.75*cgs::centimeter ), 0.4*barns );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( 1.5*MeV, 9.0*cgs::centimeter ), 0.0*barn );\n\n  // On the upper bin boundary\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( 2.0*MeV, -1.0*cgs::centimeter ), 0.0*barn );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( 2.0*MeV, 0.0*cgs::centimeter ), 0.1*barns );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( 2.0*MeV, 5.0*cgs::centimeter ), 0.1*barns );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( 2.0*MeV, 10.0*cgs::centimeter ), 0.1*barns );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( 2.0*MeV, 11.0*cgs::centimeter ), 0.0*barn );\n\n  // After the third bin - no extension\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( 3.0*MeV, -1.0*cgs::centimeter ), 0.0*barn );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( 3.0*MeV, 0.0*cgs::centimeter ), 0.0*barn );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( 3.0*MeV, 5.0*cgs::centimeter ), 0.0*barn );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( 3.0*MeV, 10.0*cgs::centimeter ), 0.0*barn );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( 3.0*MeV, 11.0*cgs::centimeter ), 0.0*barn );\n\n  // After the third bin - with extension\n  unit_aware_distribution->extendBeyondPrimaryIndepLimits();\n\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( 3.0*MeV, -1.0*cgs::centimeter ), 0.0*barn );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( 3.0*MeV, 0.0*cgs::centimeter ), 0.1*barns );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( 3.0*MeV, 5.0*cgs::centimeter ), 0.1*barns );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( 3.0*MeV, 10.0*cgs::centimeter ), 0.1*barns );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( 3.0*MeV, 11.0*cgs::centimeter ), 0.0*barn );\n\n  unit_aware_distribution->limitToPrimaryIndepLimits();\n}\n\n//---------------------------------------------------------------------------//\n// Check that the secondary conditional PDF can be evaluated\nFRENSIE_UNIT_TEST( InterpolatedPartiallyTabularBasicBivariateDistribution,\n                   evaluateSecondaryConditionalPDF )\n{\n  // Before the first bin - no extension\n  FRENSIE_CHECK_EQUAL( distribution->evaluateSecondaryConditionalPDF( -1.0, -1.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluateSecondaryConditionalPDF( -1.0, 0.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluateSecondaryConditionalPDF( -1.0, 5.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluateSecondaryConditionalPDF( -1.0, 10.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluateSecondaryConditionalPDF( -1.0, 11.0 ), 0.0 );\n\n  // Before the first bin - with extension\n  distribution->extendBeyondPrimaryIndepLimits();\n\n  FRENSIE_CHECK_EQUAL( distribution->evaluateSecondaryConditionalPDF( -1.0, -1.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluateSecondaryConditionalPDF( -1.0, 0.0 ), 0.1 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluateSecondaryConditionalPDF( -1.0, 5.0 ), 0.1 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluateSecondaryConditionalPDF( -1.0, 10.0 ), 0.1 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluateSecondaryConditionalPDF( -1.0, 11.0 ), 0.0 );\n\n  distribution->limitToPrimaryIndepLimits();\n\n  // On the second bin boundary\n  FRENSIE_CHECK_EQUAL( distribution->evaluateSecondaryConditionalPDF( 0.0, -1.0 ), 0.0 );\n  FRENSIE_CHECK_FLOATING_EQUALITY( distribution->evaluateSecondaryConditionalPDF( 0.0, 0.0 ),\n                          1.0000454019910097,\n                          1e-15 );\n  FRENSIE_CHECK_FLOATING_EQUALITY( distribution->evaluateSecondaryConditionalPDF( 0.0, 10.0 ),\n                          4.540199100968777e-05,\n                          1e-15 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluateSecondaryConditionalPDF( 0.0, 11.0 ), 0.0 );\n\n  // In the second bin\n  FRENSIE_CHECK_EQUAL( distribution->evaluateSecondaryConditionalPDF( 0.5, 1.0 ), 0.0 );\n  FRENSIE_CHECK_FLOATING_EQUALITY( distribution->evaluateSecondaryConditionalPDF( 0.5, 1.25 ),\n                          0.7333636013273398,\n                          1e-15 );\n  FRENSIE_CHECK_FLOATING_EQUALITY( distribution->evaluateSecondaryConditionalPDF( 0.5, 5.0 ),\n                          0.07115883527686304,\n                          1e-15 );\n  FRENSIE_CHECK_FLOATING_EQUALITY( distribution->evaluateSecondaryConditionalPDF( 0.5, 8.75 ),\n                          0.06669693466067313,\n                          1e-15 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluateSecondaryConditionalPDF( 0.5, 9.0 ), 0.0 );\n\n  // On the third bin boundary\n  FRENSIE_CHECK_EQUAL( distribution->evaluateSecondaryConditionalPDF( 1.0, 2.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluateSecondaryConditionalPDF( 1.0, 2.5 ), 0.2 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluateSecondaryConditionalPDF( 1.0, 5.0 ), 0.2 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluateSecondaryConditionalPDF( 1.0, 7.5 ), 0.2 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluateSecondaryConditionalPDF( 1.0, 8.0 ), 0.0 );\n\n  // In the third bin\n  FRENSIE_CHECK_EQUAL( distribution->evaluateSecondaryConditionalPDF( 1.5, 1.0 ), 0.0 );\n  FRENSIE_CHECK_FLOATING_EQUALITY( distribution->evaluateSecondaryConditionalPDF( 1.5, 1.25 ),\n                          0.13333333333333333,\n                          1e-15 );\n  FRENSIE_CHECK_FLOATING_EQUALITY( distribution->evaluateSecondaryConditionalPDF( 1.5, 5.0 ),\n                          0.13333333333333333,\n                          1e-15 );\n  FRENSIE_CHECK_FLOATING_EQUALITY( distribution->evaluateSecondaryConditionalPDF( 1.5, 8.75 ),\n                          0.13333333333333333,\n                          1e-15 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluateSecondaryConditionalPDF( 1.5, 9.0 ), 0.0 );\n\n  // On the upper bin boundary\n  FRENSIE_CHECK_EQUAL( distribution->evaluateSecondaryConditionalPDF( 2.0, -1.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluateSecondaryConditionalPDF( 2.0, 0.0 ), 0.1 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluateSecondaryConditionalPDF( 2.0, 5.0 ), 0.1 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluateSecondaryConditionalPDF( 2.0, 10.0 ), 0.1 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluateSecondaryConditionalPDF( 2.0, 11.0 ), 0.0 );\n\n  // After the third bin - no extension\n  FRENSIE_CHECK_EQUAL( distribution->evaluateSecondaryConditionalPDF( 3.0, -1.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluateSecondaryConditionalPDF( 3.0, 0.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluateSecondaryConditionalPDF( 3.0, 5.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluateSecondaryConditionalPDF( 3.0, 10.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluateSecondaryConditionalPDF( 3.0, 11.0 ), 0.0 );\n\n  // After the third bin - with extension\n  distribution->extendBeyondPrimaryIndepLimits();\n\n  FRENSIE_CHECK_EQUAL( distribution->evaluateSecondaryConditionalPDF( 3.0, -1.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluateSecondaryConditionalPDF( 3.0, 0.0 ), 0.1 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluateSecondaryConditionalPDF( 3.0, 5.0 ), 0.1 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluateSecondaryConditionalPDF( 3.0, 10.0 ), 0.1 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluateSecondaryConditionalPDF( 3.0, 11.0 ), 0.0 );\n\n  distribution->limitToPrimaryIndepLimits();\n}\n\n//---------------------------------------------------------------------------//\n// Check that the unit-aware secondary conditional PDF can be evaluated\nFRENSIE_UNIT_TEST( UnitAwareInterpolatedPartiallyTabularBasicBivariateDistribution,\n                   evaluateSecondaryConditionalPDF )\n{\n  // Before the first bin - no extension\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluateSecondaryConditionalPDF( -1.0*MeV, -1.0*cgs::centimeter ), 0.0/cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluateSecondaryConditionalPDF( -1.0*MeV, 0.0*cgs::centimeter ), 0.0/cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluateSecondaryConditionalPDF( -1.0*MeV, 5.0*cgs::centimeter ), 0.0/cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluateSecondaryConditionalPDF( -1.0*MeV, 10.0*cgs::centimeter ), 0.0/cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluateSecondaryConditionalPDF( -1.0*MeV, 11.0*cgs::centimeter ), 0.0/cgs::centimeter );\n\n  // Before the first bin - with extension\n  unit_aware_distribution->extendBeyondPrimaryIndepLimits();\n\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluateSecondaryConditionalPDF( -1.0*MeV, -1.0*cgs::centimeter ), 0.0/cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluateSecondaryConditionalPDF( -1.0*MeV, 0.0*cgs::centimeter ), 0.1/cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluateSecondaryConditionalPDF( -1.0*MeV, 5.0*cgs::centimeter ), 0.1/cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluateSecondaryConditionalPDF( -1.0*MeV, 10.0*cgs::centimeter ), 0.1/cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluateSecondaryConditionalPDF( -1.0*MeV, 11.0*cgs::centimeter ), 0.0/cgs::centimeter );\n\n  unit_aware_distribution->limitToPrimaryIndepLimits();\n\n  // On the second bin boundary\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluateSecondaryConditionalPDF( 0.0*MeV, -1.0*cgs::centimeter ), 0.0/cgs::centimeter );\n  FRENSIE_CHECK_FLOATING_EQUALITY( unit_aware_distribution->evaluateSecondaryConditionalPDF( 0.0*MeV, 0.0*cgs::centimeter ),\n                          1.0000454019910097/cgs::centimeter,\n                          1e-15 );\n  FRENSIE_CHECK_FLOATING_EQUALITY( unit_aware_distribution->evaluateSecondaryConditionalPDF( 0.0*MeV, 10.0*cgs::centimeter ),\n                          4.540199100968777e-05/cgs::centimeter,\n                          1e-15 );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluateSecondaryConditionalPDF( 0.0*MeV, 11.0*cgs::centimeter ), 0.0/cgs::centimeter );\n\n  // In the second bin\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluateSecondaryConditionalPDF( 0.5*MeV, 1.0*cgs::centimeter ), 0.0/cgs::centimeter );\n  FRENSIE_CHECK_FLOATING_EQUALITY( unit_aware_distribution->evaluateSecondaryConditionalPDF( 0.5*MeV, 1.25*cgs::centimeter ),\n                          0.7333636013273398/cgs::centimeter,\n                          1e-15 );\n  FRENSIE_CHECK_FLOATING_EQUALITY( unit_aware_distribution->evaluateSecondaryConditionalPDF( 0.5*MeV, 5.0*cgs::centimeter ),\n                          0.07115883527686304/cgs::centimeter,\n                          1e-15 );\n  FRENSIE_CHECK_FLOATING_EQUALITY( unit_aware_distribution->evaluateSecondaryConditionalPDF( 0.5*MeV, 8.75*cgs::centimeter ),\n                          0.06669693466067313/cgs::centimeter,\n                          1e-15 );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluateSecondaryConditionalPDF( 0.5*MeV, 9.0*cgs::centimeter ), 0.0/cgs::centimeter );\n\n  // On the third bin boundary\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluateSecondaryConditionalPDF( 1.0*MeV, 2.0*cgs::centimeter ), 0.0/cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluateSecondaryConditionalPDF( 1.0*MeV, 2.5*cgs::centimeter ), 0.2/cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluateSecondaryConditionalPDF( 1.0*MeV, 5.0*cgs::centimeter ), 0.2/cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluateSecondaryConditionalPDF( 1.0*MeV, 7.5*cgs::centimeter ), 0.2/cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluateSecondaryConditionalPDF( 1.0*MeV, 8.0*cgs::centimeter ), 0.0/cgs::centimeter );\n\n  // In the third bin\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluateSecondaryConditionalPDF( 1.5*MeV, 1.0*cgs::centimeter ), 0.0/cgs::centimeter );\n  FRENSIE_CHECK_FLOATING_EQUALITY( unit_aware_distribution->evaluateSecondaryConditionalPDF( 1.5*MeV, 1.25*cgs::centimeter ),\n                          0.13333333333333333/cgs::centimeter,\n                          1e-15 );\n  FRENSIE_CHECK_FLOATING_EQUALITY( unit_aware_distribution->evaluateSecondaryConditionalPDF( 1.5*MeV, 5.0*cgs::centimeter ),\n                          0.13333333333333333/cgs::centimeter,\n                          1e-15 );\n  FRENSIE_CHECK_FLOATING_EQUALITY( unit_aware_distribution->evaluateSecondaryConditionalPDF( 1.5*MeV, 8.75*cgs::centimeter ),\n                          0.13333333333333333/cgs::centimeter,\n                          1e-15 );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluateSecondaryConditionalPDF( 1.5*MeV, 9.0*cgs::centimeter ), 0.0/cgs::centimeter );\n\n  // On the upper bin boundary\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluateSecondaryConditionalPDF( 2.0*MeV, -1.0*cgs::centimeter ), 0.0/cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluateSecondaryConditionalPDF( 2.0*MeV, 0.0*cgs::centimeter ), 0.1/cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluateSecondaryConditionalPDF( 2.0*MeV, 5.0*cgs::centimeter ), 0.1/cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluateSecondaryConditionalPDF( 2.0*MeV, 10.0*cgs::centimeter ), 0.1/cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluateSecondaryConditionalPDF( 2.0*MeV, 11.0*cgs::centimeter ), 0.0/cgs::centimeter );\n\n  // After the third bin - no extension\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluateSecondaryConditionalPDF( 3.0*MeV, -1.0*cgs::centimeter ), 0.0/cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluateSecondaryConditionalPDF( 3.0*MeV, 0.0*cgs::centimeter ), 0.0/cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluateSecondaryConditionalPDF( 3.0*MeV, 5.0*cgs::centimeter ), 0.0/cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluateSecondaryConditionalPDF( 3.0*MeV, 10.0*cgs::centimeter ), 0.0/cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluateSecondaryConditionalPDF( 3.0*MeV, 11.0*cgs::centimeter ), 0.0/cgs::centimeter );\n\n  // After the third bin - with extension\n  unit_aware_distribution->extendBeyondPrimaryIndepLimits();\n\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluateSecondaryConditionalPDF( 3.0*MeV, -1.0*cgs::centimeter ), 0.0/cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluateSecondaryConditionalPDF( 3.0*MeV, 0.0*cgs::centimeter ), 0.1/cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluateSecondaryConditionalPDF( 3.0*MeV, 5.0*cgs::centimeter ), 0.1/cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluateSecondaryConditionalPDF( 3.0*MeV, 10.0*cgs::centimeter ), 0.1/cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluateSecondaryConditionalPDF( 3.0*MeV, 11.0*cgs::centimeter ), 0.0/cgs::centimeter );\n\n  unit_aware_distribution->limitToPrimaryIndepLimits();\n}\n\n//---------------------------------------------------------------------------//\n// Check that a secondary conditional PDF can be sampled\nFRENSIE_UNIT_TEST( InterpolatedPartiallyTabularBasicBivariateDistribution,\n                   sampleSecondaryConditional )\n{\n  // Before the first bin - no extension\n  FRENSIE_CHECK_THROW( distribution->sampleSecondaryConditional( -1.0 ),\n              std::logic_error );\n\n  // Before the first bin - with extension\n  distribution->extendBeyondPrimaryIndepLimits();\n\n  std::vector<double> fake_stream( 3 );\n  fake_stream[0] = 0.0;\n  fake_stream[1] = 0.5;\n  fake_stream[2] = 1.0-1e-15;\n\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  double sample = distribution->sampleSecondaryConditional( -1.0 );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0 );\n\n  sample = distribution->sampleSecondaryConditional( -1.0 );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0 );\n\n  sample = distribution->sampleSecondaryConditional( -1.0 );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0, 1e-12 );\n\n  distribution->limitToPrimaryIndepLimits();\n\n  // On the second bin\n  fake_stream.resize( 6 );\n  fake_stream[0] = 0.0;\n  fake_stream[1] = 0.0;\n  fake_stream[2] = 0.0;\n  fake_stream[3] = 0.5;\n  fake_stream[4] = 0.0;\n  fake_stream[5] = 1.0-1e-15;\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  sample = distribution->sampleSecondaryConditional( 0.0 );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0 );\n\n  sample = distribution->sampleSecondaryConditional( 0.0 );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 0.6931017816607284, 1e-15 );\n\n  sample = distribution->sampleSecondaryConditional( 0.0 );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0, 1e-9 );\n\n  // In the second bin\n  fake_stream.resize( 12 );\n  fake_stream[0] = 0.5; // use lower bin boundary\n  fake_stream[1] = 0.0;\n  fake_stream[2] = 0.5; // use lower bin boundary\n  fake_stream[3] = 0.5;\n  fake_stream[4] = 0.5; // use lower bin boundary\n  fake_stream[5] = 1.0-1e-15;\n  fake_stream[6] = 0.49; // use upper bin boundary\n  fake_stream[7] = 0.0;\n  fake_stream[8] = 0.49; // use upper bin boundary\n  fake_stream[9] = 0.5;\n  fake_stream[10] = 0.49; // use upper bin boundary\n  fake_stream[11] = 1.0-1e-15;\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  // Samples from lower boundary of second bin\n  sample = distribution->sampleSecondaryConditional( 0.5 );\n\n  FRENSIE_CHECK_EQUAL( sample, 1.25 );\n\n  sample = distribution->sampleSecondaryConditional( 0.5 );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 1.7698263362455464, 1e-15 );\n\n  sample = distribution->sampleSecondaryConditional( 0.5 );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 8.75, 1e-9 );\n\n  // Samples from upper boundary of second bin\n  sample = distribution->sampleSecondaryConditional( 0.5 );\n\n  FRENSIE_CHECK_EQUAL( sample, 1.25 );\n\n  sample = distribution->sampleSecondaryConditional( 0.5 );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0 );\n\n  sample = distribution->sampleSecondaryConditional( 0.5 );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 8.75, 1e-14 );\n\n  // On the third bin\n  fake_stream.resize( 6 );\n  fake_stream[0] = 0.0;\n  fake_stream[1] = 0.0;\n  fake_stream[2] = 0.0;\n  fake_stream[3] = 0.5;\n  fake_stream[4] = 0.0;\n  fake_stream[5] = 1.0-1e-15;\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  sample = distribution->sampleSecondaryConditional( 1.0 );\n\n  FRENSIE_CHECK_EQUAL( sample, 2.5 );\n\n  sample = distribution->sampleSecondaryConditional( 1.0 );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0 );\n\n  sample = distribution->sampleSecondaryConditional( 1.0 );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 7.5, 1e-14 );\n\n  // In the third bin\n  fake_stream.resize( 12 );\n  fake_stream[0] = 0.5; // use lower bin boundary\n  fake_stream[1] = 0.0;\n  fake_stream[2] = 0.5; // use lower bin boundary\n  fake_stream[3] = 0.5;\n  fake_stream[4] = 0.5; // use lower bin boundary\n  fake_stream[5] = 1.0-1e-15;\n  fake_stream[6] = 0.49; // use upper bin boundary\n  fake_stream[7] = 0.0;\n  fake_stream[8] = 0.49; // use upper bin boundary\n  fake_stream[9] = 0.5;\n  fake_stream[10] = 0.49; // use upper bin boundary\n  fake_stream[11] = 1.0-1e-15;\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  // Samples from lower boundary of third bin\n  sample = distribution->sampleSecondaryConditional( 1.5 );\n\n  FRENSIE_CHECK_EQUAL( sample, 1.25 );\n\n  sample = distribution->sampleSecondaryConditional( 1.5 );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0 );\n\n  sample = distribution->sampleSecondaryConditional( 1.5 );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 8.75, 1e-14 );\n\n  // Samples from upper boundary of third bin\n  sample = distribution->sampleSecondaryConditional( 1.5 );\n\n  FRENSIE_CHECK_EQUAL( sample, 1.25 );\n\n  sample = distribution->sampleSecondaryConditional( 1.5 );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0 );\n\n  sample = distribution->sampleSecondaryConditional( 1.5 );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 8.75, 1e-14 );\n\n  // On the upper bin boundary\n  fake_stream.resize( 6 );\n  fake_stream[0] = 0.0;\n  fake_stream[1] = 0.0;\n  fake_stream[2] = 0.0;\n  fake_stream[3] = 0.5;\n  fake_stream[4] = 0.0;\n  fake_stream[5] = 1.0-1e-15;\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  sample = distribution->sampleSecondaryConditional( 2.0 );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0 );\n\n  sample = distribution->sampleSecondaryConditional( 2.0 );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0 );\n\n  sample = distribution->sampleSecondaryConditional( 2.0 );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0, 1e-14 );\n\n  // After the third bin - no extension\n  FRENSIE_CHECK_THROW( distribution->sampleSecondaryConditional( 3.0 ),\n              std::logic_error );\n\n  // After the third bin - with extension\n  distribution->extendBeyondPrimaryIndepLimits();\n\n  fake_stream.resize( 3 );\n  fake_stream[0] = 0.0;\n  fake_stream[1] = 0.5;\n  fake_stream[2] = 1.0-1e-15;\n\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  sample = distribution->sampleSecondaryConditional( 3.0 );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0 );\n\n  sample = distribution->sampleSecondaryConditional( 3.0 );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0 );\n\n  sample = distribution->sampleSecondaryConditional( 3.0 );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0, 1e-14 );\n\n  distribution->limitToPrimaryIndepLimits();\n\n  Utility::RandomNumberGenerator::unsetFakeStream();\n}\n\n//---------------------------------------------------------------------------//\n// Check that a unit-aware secondary conditional PDF can be sampled\nFRENSIE_UNIT_TEST( UnitAwareInterpolatedPartiallyTabularBasicBivariateDistribution,\n                   sampleSecondaryConditional )\n{\n   // Before the first bin - no extension\n  FRENSIE_CHECK_THROW( unit_aware_distribution->sampleSecondaryConditional( -1.0*MeV ),\n              std::logic_error );\n\n  // Before the first bin - with extension\n  unit_aware_distribution->extendBeyondPrimaryIndepLimits();\n\n  std::vector<double> fake_stream( 3 );\n  fake_stream[0] = 0.0;\n  fake_stream[1] = 0.5;\n  fake_stream[2] = 1.0-1e-15;\n\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  quantity<cgs::length> sample =\n    unit_aware_distribution->sampleSecondaryConditional( -1.0*MeV );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter );\n\n  sample = unit_aware_distribution->sampleSecondaryConditional( -1.0*MeV );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0*cgs::centimeter );\n\n  sample = unit_aware_distribution->sampleSecondaryConditional( -1.0*MeV );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0*cgs::centimeter, 1e-12 );\n\n  unit_aware_distribution->limitToPrimaryIndepLimits();\n\n  // On the second bin\n  fake_stream.resize( 6 );\n  fake_stream[0] = 0.0;\n  fake_stream[1] = 0.0;\n  fake_stream[2] = 0.0;\n  fake_stream[3] = 0.5;\n  fake_stream[4] = 0.0;\n  fake_stream[5] = 1.0-1e-15;\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  sample = unit_aware_distribution->sampleSecondaryConditional( 0.0*MeV );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter );\n\n  sample = unit_aware_distribution->sampleSecondaryConditional( 0.0*MeV );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 0.6931017816607284*cgs::centimeter, 1e-15 );\n\n  sample = unit_aware_distribution->sampleSecondaryConditional( 0.0*MeV );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0*cgs::centimeter, 1e-9 );\n\n  // In the second bin\n  fake_stream.resize( 12 );\n  fake_stream[0] = 0.5; // use lower bin boundary\n  fake_stream[1] = 0.0;\n  fake_stream[2] = 0.5; // use lower bin boundary\n  fake_stream[3] = 0.5;\n  fake_stream[4] = 0.5; // use lower bin boundary\n  fake_stream[5] = 1.0-1e-15;\n  fake_stream[6] = 0.49; // use upper bin boundary\n  fake_stream[7] = 0.0;\n  fake_stream[8] = 0.49; // use upper bin boundary\n  fake_stream[9] = 0.5;\n  fake_stream[10] = 0.49; // use upper bin boundary\n  fake_stream[11] = 1.0-1e-15;\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  // Samples from lower boundary of second bin\n  sample = unit_aware_distribution->sampleSecondaryConditional( 0.5*MeV );\n\n  FRENSIE_CHECK_EQUAL( sample, 1.25*cgs::centimeter );\n\n  sample = unit_aware_distribution->sampleSecondaryConditional( 0.5*MeV );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 1.7698263362455464*cgs::centimeter, 1e-15 );\n\n  sample = unit_aware_distribution->sampleSecondaryConditional( 0.5*MeV );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 8.75*cgs::centimeter, 1e-9 );\n\n  // Samples from upper boundary of second bin\n  sample = unit_aware_distribution->sampleSecondaryConditional( 0.5*MeV );\n\n  FRENSIE_CHECK_EQUAL( sample, 1.25*cgs::centimeter );\n\n  sample = unit_aware_distribution->sampleSecondaryConditional( 0.5*MeV );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0*cgs::centimeter );\n\n  sample = unit_aware_distribution->sampleSecondaryConditional( 0.5*MeV );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 8.75*cgs::centimeter, 1e-14 );\n\n  // On the third bin\n  fake_stream.resize( 6 );\n  fake_stream[0] = 0.0;\n  fake_stream[1] = 0.0;\n  fake_stream[2] = 0.0;\n  fake_stream[3] = 0.5;\n  fake_stream[4] = 0.0;\n  fake_stream[5] = 1.0-1e-15;\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  sample = unit_aware_distribution->sampleSecondaryConditional( 1.0*MeV );\n\n  FRENSIE_CHECK_EQUAL( sample, 2.5*cgs::centimeter );\n\n  sample = unit_aware_distribution->sampleSecondaryConditional( 1.0*MeV );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0*cgs::centimeter );\n\n  sample = unit_aware_distribution->sampleSecondaryConditional( 1.0*MeV );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 7.5*cgs::centimeter, 1e-14 );\n\n  // In the third bin\n  fake_stream.resize( 12 );\n  fake_stream[0] = 0.5; // use lower bin boundary\n  fake_stream[1] = 0.0;\n  fake_stream[2] = 0.5; // use lower bin boundary\n  fake_stream[3] = 0.5;\n  fake_stream[4] = 0.5; // use lower bin boundary\n  fake_stream[5] = 1.0-1e-15;\n  fake_stream[6] = 0.49; // use upper bin boundary\n  fake_stream[7] = 0.0;\n  fake_stream[8] = 0.49; // use upper bin boundary\n  fake_stream[9] = 0.5;\n  fake_stream[10] = 0.49; // use upper bin boundary\n  fake_stream[11] = 1.0-1e-15;\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  // Samples from lower boundary of third bin\n  sample = unit_aware_distribution->sampleSecondaryConditional( 1.5*MeV );\n\n  FRENSIE_CHECK_EQUAL( sample, 1.25*cgs::centimeter );\n\n  sample = unit_aware_distribution->sampleSecondaryConditional( 1.5*MeV );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0*cgs::centimeter );\n\n  sample = unit_aware_distribution->sampleSecondaryConditional( 1.5*MeV );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 8.75*cgs::centimeter, 1e-14 );\n\n  // Samples from upper boundary of third bin\n  sample = unit_aware_distribution->sampleSecondaryConditional( 1.5*MeV );\n\n  FRENSIE_CHECK_EQUAL( sample, 1.25*cgs::centimeter );\n\n  sample = unit_aware_distribution->sampleSecondaryConditional( 1.5*MeV );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0*cgs::centimeter );\n\n  sample = unit_aware_distribution->sampleSecondaryConditional( 1.5*MeV );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 8.75*cgs::centimeter, 1e-14 );\n\n  // On the upper bin boundary\n  fake_stream.resize( 6 );\n  fake_stream[0] = 0.0;\n  fake_stream[1] = 0.0;\n  fake_stream[2] = 0.0;\n  fake_stream[3] = 0.5;\n  fake_stream[4] = 0.0;\n  fake_stream[5] = 1.0-1e-15;\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  sample = unit_aware_distribution->sampleSecondaryConditional( 2.0*MeV );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter );\n\n  sample = unit_aware_distribution->sampleSecondaryConditional( 2.0*MeV );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0*cgs::centimeter );\n\n  sample = unit_aware_distribution->sampleSecondaryConditional( 2.0*MeV );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0*cgs::centimeter, 1e-14 );\n\n  // After the third bin - no extension\n  FRENSIE_CHECK_THROW( unit_aware_distribution->sampleSecondaryConditional( 3.0*MeV ),\n              std::logic_error );\n\n  // After the third bin - with extension\n  unit_aware_distribution->extendBeyondPrimaryIndepLimits();\n\n  fake_stream.resize( 3 );\n  fake_stream[0] = 0.0;\n  fake_stream[1] = 0.5;\n  fake_stream[2] = 1.0-1e-15;\n\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  sample = unit_aware_distribution->sampleSecondaryConditional( 3.0*MeV );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter );\n\n  sample = unit_aware_distribution->sampleSecondaryConditional( 3.0*MeV );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0*cgs::centimeter );\n\n  sample = unit_aware_distribution->sampleSecondaryConditional( 3.0*MeV );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0*cgs::centimeter, 1e-14 );\n\n  unit_aware_distribution->limitToPrimaryIndepLimits();\n\n  Utility::RandomNumberGenerator::unsetFakeStream();\n}\n\n//---------------------------------------------------------------------------//\n// Check that a secondary conditional PDF can be sampled\nFRENSIE_UNIT_TEST( InterpolatedPartiallyTabularBasicBivariateDistribution,\n                   sampleSecondaryConditionalAndRecordTrials )\n{\n  Utility::DistributionTraits::Counter trials = 0u;\n\n  // Before the first bin - no extension\n  FRENSIE_CHECK_THROW( distribution->sampleSecondaryConditionalAndRecordTrials( -1.0, trials ),\n              std::logic_error );\n  FRENSIE_CHECK_EQUAL( trials, 0u );\n\n  // Before the first bin - with extension\n  distribution->extendBeyondPrimaryIndepLimits();\n\n  std::vector<double> fake_stream( 3 );\n  fake_stream[0] = 0.0;\n  fake_stream[1] = 0.5;\n  fake_stream[2] = 1.0-1e-15;\n\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  double sample = distribution->sampleSecondaryConditionalAndRecordTrials( -1.0, trials );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0 );\n  FRENSIE_CHECK_EQUAL( trials, 1u );\n\n  sample = distribution->sampleSecondaryConditionalAndRecordTrials( -1.0, trials );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0 );\n  FRENSIE_CHECK_EQUAL( trials, 2u );\n\n  sample = distribution->sampleSecondaryConditionalAndRecordTrials( -1.0, trials );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0, 1e-12 );\n  FRENSIE_CHECK_EQUAL( trials, 3u );\n\n  distribution->limitToPrimaryIndepLimits();\n\n  // On the second bin\n  fake_stream.resize( 6 );\n  fake_stream[0] = 0.0;\n  fake_stream[1] = 0.0;\n  fake_stream[2] = 0.0;\n  fake_stream[3] = 0.5;\n  fake_stream[4] = 0.0;\n  fake_stream[5] = 1.0-1e-15;\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  trials = 0u;\n\n  sample = distribution->sampleSecondaryConditionalAndRecordTrials( 0.0, trials );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0 );\n  FRENSIE_CHECK_EQUAL( trials, 1u );\n\n  sample = distribution->sampleSecondaryConditionalAndRecordTrials( 0.0, trials );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 0.6931017816607284, 1e-15 );\n  FRENSIE_CHECK_EQUAL( trials, 2u );\n\n  sample = distribution->sampleSecondaryConditionalAndRecordTrials( 0.0, trials );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0, 1e-9 );\n  FRENSIE_CHECK_EQUAL( trials, 3u );\n\n  // In the second bin\n  fake_stream.resize( 12 );\n  fake_stream[0] = 0.5; // use lower bin boundary\n  fake_stream[1] = 0.0;\n  fake_stream[2] = 0.5; // use lower bin boundary\n  fake_stream[3] = 0.5;\n  fake_stream[4] = 0.5; // use lower bin boundary\n  fake_stream[5] = 1.0-1e-15;\n  fake_stream[6] = 0.49; // use upper bin boundary\n  fake_stream[7] = 0.0;\n  fake_stream[8] = 0.49; // use upper bin boundary\n  fake_stream[9] = 0.5;\n  fake_stream[10] = 0.49; // use upper bin boundary\n  fake_stream[11] = 1.0-1e-15;\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  trials = 0u;\n\n  // Samples from lower boundary of second bin\n  sample = distribution->sampleSecondaryConditionalAndRecordTrials( 0.5, trials );\n\n  FRENSIE_CHECK_EQUAL( sample, 1.25 );\n  FRENSIE_CHECK_EQUAL( trials, 1u );\n\n  sample = distribution->sampleSecondaryConditionalAndRecordTrials( 0.5, trials );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 1.7698263362455464, 1e-15 );\n  FRENSIE_CHECK_EQUAL( trials, 2u );\n\n  sample = distribution->sampleSecondaryConditionalAndRecordTrials( 0.5, trials );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 8.75, 1e-9 );\n  FRENSIE_CHECK_EQUAL( trials, 3u );\n\n  // Samples from upper boundary of second bin\n  sample = distribution->sampleSecondaryConditionalAndRecordTrials( 0.5, trials );\n\n  FRENSIE_CHECK_EQUAL( sample, 1.25 );\n  FRENSIE_CHECK_EQUAL( trials, 4u );\n\n  sample = distribution->sampleSecondaryConditionalAndRecordTrials( 0.5, trials );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0 );\n  FRENSIE_CHECK_EQUAL( trials, 5u );\n\n  sample = distribution->sampleSecondaryConditionalAndRecordTrials( 0.5, trials );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 8.75, 1e-14 );\n  FRENSIE_CHECK_EQUAL( trials, 6u );\n\n  // On the third bin\n  fake_stream.resize( 6 );\n  fake_stream[0] = 0.0;\n  fake_stream[1] = 0.0;\n  fake_stream[2] = 0.0;\n  fake_stream[3] = 0.5;\n  fake_stream[4] = 0.0;\n  fake_stream[5] = 1.0-1e-15;\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  trials = 0u;\n\n  sample = distribution->sampleSecondaryConditionalAndRecordTrials( 1.0, trials );\n\n  FRENSIE_CHECK_EQUAL( sample, 2.5 );\n  FRENSIE_CHECK_EQUAL( trials, 1u );\n\n  sample = distribution->sampleSecondaryConditionalAndRecordTrials( 1.0, trials );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0 );\n  FRENSIE_CHECK_EQUAL( trials, 2u );\n\n  sample = distribution->sampleSecondaryConditionalAndRecordTrials( 1.0, trials );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 7.5, 1e-14 );\n  FRENSIE_CHECK_EQUAL( trials, 3u );\n\n  // In the third bin\n  fake_stream.resize( 12 );\n  fake_stream[0] = 0.5; // use lower bin boundary\n  fake_stream[1] = 0.0;\n  fake_stream[2] = 0.5; // use lower bin boundary\n  fake_stream[3] = 0.5;\n  fake_stream[4] = 0.5; // use lower bin boundary\n  fake_stream[5] = 1.0-1e-15;\n  fake_stream[6] = 0.49; // use upper bin boundary\n  fake_stream[7] = 0.0;\n  fake_stream[8] = 0.49; // use upper bin boundary\n  fake_stream[9] = 0.5;\n  fake_stream[10] = 0.49; // use upper bin boundary\n  fake_stream[11] = 1.0-1e-15;\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  trials = 0u;\n\n  // Samples from lower boundary of third bin\n  sample = distribution->sampleSecondaryConditionalAndRecordTrials( 1.5, trials );\n\n  FRENSIE_CHECK_EQUAL( sample, 1.25 );\n  FRENSIE_CHECK_EQUAL( trials, 1u );\n\n  sample = distribution->sampleSecondaryConditionalAndRecordTrials( 1.5, trials );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0 );\n  FRENSIE_CHECK_EQUAL( trials, 2u );\n\n  sample = distribution->sampleSecondaryConditionalAndRecordTrials( 1.5, trials );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 8.75, 1e-14 );\n  FRENSIE_CHECK_EQUAL( trials, 3u );\n\n  // Samples from upper boundary of third bin\n  sample = distribution->sampleSecondaryConditionalAndRecordTrials( 1.5, trials );\n\n  FRENSIE_CHECK_EQUAL( sample, 1.25 );\n  FRENSIE_CHECK_EQUAL( trials, 4u );\n\n  sample = distribution->sampleSecondaryConditionalAndRecordTrials( 1.5, trials );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0 );\n  FRENSIE_CHECK_EQUAL( trials, 5u );\n\n  sample = distribution->sampleSecondaryConditionalAndRecordTrials( 1.5, trials );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 8.75, 1e-14 );\n  FRENSIE_CHECK_EQUAL( trials, 6u );\n\n  // On the upper bin boundary\n  fake_stream.resize( 6 );\n  fake_stream[0] = 0.0;\n  fake_stream[1] = 0.0;\n  fake_stream[2] = 0.0;\n  fake_stream[3] = 0.5;\n  fake_stream[4] = 0.0;\n  fake_stream[5] = 1.0-1e-15;\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  trials = 0u;\n\n  sample = distribution->sampleSecondaryConditionalAndRecordTrials( 2.0, trials );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0 );\n  FRENSIE_CHECK_EQUAL( trials, 1u );\n\n  sample = distribution->sampleSecondaryConditionalAndRecordTrials( 2.0, trials );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0 );\n  FRENSIE_CHECK_EQUAL( trials, 2u );\n\n  sample = distribution->sampleSecondaryConditionalAndRecordTrials( 2.0, trials );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0, 1e-14 );\n  FRENSIE_CHECK_EQUAL( trials, 3u );\n\n  // After the third bin - no extension\n  FRENSIE_CHECK_THROW( distribution->sampleSecondaryConditionalAndRecordTrials( 3.0, trials ),\n              std::logic_error );\n\n  // After the third bin - with extension\n  distribution->extendBeyondPrimaryIndepLimits();\n\n  fake_stream.resize( 3 );\n  fake_stream[0] = 0.0;\n  fake_stream[1] = 0.5;\n  fake_stream[2] = 1.0-1e-15;\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  trials = 0u;\n\n  sample = distribution->sampleSecondaryConditionalAndRecordTrials( 3.0, trials );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0 );\n  FRENSIE_CHECK_EQUAL( trials, 1u );\n\n  sample = distribution->sampleSecondaryConditionalAndRecordTrials( 3.0, trials );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0 );\n  FRENSIE_CHECK_EQUAL( trials, 2u );\n\n  sample = distribution->sampleSecondaryConditionalAndRecordTrials( 3.0, trials );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0, 1e-14 );\n  FRENSIE_CHECK_EQUAL( trials, 3u );\n\n  distribution->limitToPrimaryIndepLimits();\n\n  Utility::RandomNumberGenerator::unsetFakeStream();\n}\n\n//---------------------------------------------------------------------------//\n// Check that a unit-aware secondary conditional PDF can be sampled\nFRENSIE_UNIT_TEST( UnitAwareInterpolatedPartiallyTabularBasicBivariateDistribution,\n                   sampleSecondaryConditionalAndRecordTrials )\n{\n  Utility::DistributionTraits::Counter trials = 0u;\n\n  // Before the first bin - no extension\n  FRENSIE_CHECK_THROW( unit_aware_distribution->sampleSecondaryConditionalAndRecordTrials( -1.0*MeV, trials ),\n              std::logic_error );\n  FRENSIE_CHECK_EQUAL( trials, 0u );\n\n  // Before the first bin - with extension\n  unit_aware_distribution->extendBeyondPrimaryIndepLimits();\n\n  std::vector<double> fake_stream( 3 );\n  fake_stream[0] = 0.0;\n  fake_stream[1] = 0.5;\n  fake_stream[2] = 1.0-1e-15;\n\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  quantity<cgs::length> sample = unit_aware_distribution->sampleSecondaryConditionalAndRecordTrials( -1.0*MeV, trials );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( trials, 1u );\n\n  sample = unit_aware_distribution->sampleSecondaryConditionalAndRecordTrials( -1.0*MeV, trials );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( trials, 2u );\n\n  sample = unit_aware_distribution->sampleSecondaryConditionalAndRecordTrials( -1.0*MeV, trials );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0*cgs::centimeter, 1e-12 );\n  FRENSIE_CHECK_EQUAL( trials, 3u );\n\n  unit_aware_distribution->limitToPrimaryIndepLimits();\n\n  // On the second bin\n  fake_stream.resize( 6 );\n  fake_stream[0] = 0.0;\n  fake_stream[1] = 0.0;\n  fake_stream[2] = 0.0;\n  fake_stream[3] = 0.5;\n  fake_stream[4] = 0.0;\n  fake_stream[5] = 1.0-1e-15;\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  trials = 0u;\n\n  sample = unit_aware_distribution->sampleSecondaryConditionalAndRecordTrials( 0.0*MeV, trials );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( trials, 1u );\n\n  sample = unit_aware_distribution->sampleSecondaryConditionalAndRecordTrials( 0.0*MeV, trials );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 0.6931017816607284*cgs::centimeter, 1e-15 );\n  FRENSIE_CHECK_EQUAL( trials, 2u );\n\n  sample = unit_aware_distribution->sampleSecondaryConditionalAndRecordTrials( 0.0*MeV, trials );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0*cgs::centimeter, 1e-9 );\n  FRENSIE_CHECK_EQUAL( trials, 3u );\n\n  // In the second bin\n  fake_stream.resize( 12 );\n  fake_stream[0] = 0.5; // use lower bin boundary\n  fake_stream[1] = 0.0;\n  fake_stream[2] = 0.5; // use lower bin boundary\n  fake_stream[3] = 0.5;\n  fake_stream[4] = 0.5; // use lower bin boundary\n  fake_stream[5] = 1.0-1e-15;\n  fake_stream[6] = 0.49; // use upper bin boundary\n  fake_stream[7] = 0.0;\n  fake_stream[8] = 0.49; // use upper bin boundary\n  fake_stream[9] = 0.5;\n  fake_stream[10] = 0.49; // use upper bin boundary\n  fake_stream[11] = 1.0-1e-15;\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  trials = 0u;\n\n  // Samples from lower boundary of second bin\n  sample = unit_aware_distribution->sampleSecondaryConditionalAndRecordTrials( 0.5*MeV, trials );\n\n  FRENSIE_CHECK_EQUAL( sample, 1.25*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( trials, 1u );\n\n  sample = unit_aware_distribution->sampleSecondaryConditionalAndRecordTrials( 0.5*MeV, trials );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 1.7698263362455464*cgs::centimeter, 1e-15 );\n  FRENSIE_CHECK_EQUAL( trials, 2u );\n\n  sample = unit_aware_distribution->sampleSecondaryConditionalAndRecordTrials( 0.5*MeV, trials );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 8.75*cgs::centimeter, 1e-9 );\n  FRENSIE_CHECK_EQUAL( trials, 3u );\n\n  // Samples from upper boundary of second bin\n  sample = unit_aware_distribution->sampleSecondaryConditionalAndRecordTrials( 0.5*MeV, trials );\n\n  FRENSIE_CHECK_EQUAL( sample, 1.25*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( trials, 4u );\n\n  sample = unit_aware_distribution->sampleSecondaryConditionalAndRecordTrials( 0.5*MeV, trials );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( trials, 5u );\n\n  sample = unit_aware_distribution->sampleSecondaryConditionalAndRecordTrials( 0.5*MeV, trials );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 8.75*cgs::centimeter, 1e-14 );\n  FRENSIE_CHECK_EQUAL( trials, 6u );\n\n  // On the third bin\n  fake_stream.resize( 6 );\n  fake_stream[0] = 0.0;\n  fake_stream[1] = 0.0;\n  fake_stream[2] = 0.0;\n  fake_stream[3] = 0.5;\n  fake_stream[4] = 0.0;\n  fake_stream[5] = 1.0-1e-15;\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  trials = 0u;\n\n  sample = unit_aware_distribution->sampleSecondaryConditionalAndRecordTrials( 1.0*MeV, trials );\n\n  FRENSIE_CHECK_EQUAL( sample, 2.5*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( trials, 1u );\n\n  sample = unit_aware_distribution->sampleSecondaryConditionalAndRecordTrials( 1.0*MeV, trials );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( trials, 2u );\n\n  sample = unit_aware_distribution->sampleSecondaryConditionalAndRecordTrials( 1.0*MeV, trials );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 7.5*cgs::centimeter, 1e-14 );\n  FRENSIE_CHECK_EQUAL( trials, 3u );\n\n  // In the third bin\n  fake_stream.resize( 12 );\n  fake_stream[0] = 0.5; // use lower bin boundary\n  fake_stream[1] = 0.0;\n  fake_stream[2] = 0.5; // use lower bin boundary\n  fake_stream[3] = 0.5;\n  fake_stream[4] = 0.5; // use lower bin boundary\n  fake_stream[5] = 1.0-1e-15;\n  fake_stream[6] = 0.49; // use upper bin boundary\n  fake_stream[7] = 0.0;\n  fake_stream[8] = 0.49; // use upper bin boundary\n  fake_stream[9] = 0.5;\n  fake_stream[10] = 0.49; // use upper bin boundary\n  fake_stream[11] = 1.0-1e-15;\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  trials = 0u;\n\n  // Samples from lower boundary of third bin\n  sample = unit_aware_distribution->sampleSecondaryConditionalAndRecordTrials( 1.5*MeV, trials );\n\n  FRENSIE_CHECK_EQUAL( sample, 1.25*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( trials, 1u );\n\n  sample = unit_aware_distribution->sampleSecondaryConditionalAndRecordTrials( 1.5*MeV, trials );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( trials, 2u );\n\n  sample = unit_aware_distribution->sampleSecondaryConditionalAndRecordTrials( 1.5*MeV, trials );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 8.75*cgs::centimeter, 1e-14 );\n  FRENSIE_CHECK_EQUAL( trials, 3u );\n\n  // Samples from upper boundary of third bin\n  sample = unit_aware_distribution->sampleSecondaryConditionalAndRecordTrials( 1.5*MeV, trials );\n\n  FRENSIE_CHECK_EQUAL( sample, 1.25*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( trials, 4u );\n\n  sample = unit_aware_distribution->sampleSecondaryConditionalAndRecordTrials( 1.5*MeV, trials );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( trials, 5u );\n\n  sample = unit_aware_distribution->sampleSecondaryConditionalAndRecordTrials( 1.5*MeV, trials );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 8.75*cgs::centimeter, 1e-14 );\n  FRENSIE_CHECK_EQUAL( trials, 6u );\n\n  // On the upper bin boundary\n  fake_stream.resize( 6 );\n  fake_stream[0] = 0.0;\n  fake_stream[1] = 0.0;\n  fake_stream[2] = 0.0;\n  fake_stream[3] = 0.5;\n  fake_stream[4] = 0.0;\n  fake_stream[5] = 1.0-1e-15;\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  trials = 0u;\n\n  sample = unit_aware_distribution->sampleSecondaryConditionalAndRecordTrials( 2.0*MeV, trials );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( trials, 1u );\n\n  sample = unit_aware_distribution->sampleSecondaryConditionalAndRecordTrials( 2.0*MeV, trials );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( trials, 2u );\n\n  sample = unit_aware_distribution->sampleSecondaryConditionalAndRecordTrials( 2.0*MeV, trials );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0*cgs::centimeter, 1e-14 );\n  FRENSIE_CHECK_EQUAL( trials, 3u );\n\n  // After the third bin - no extension\n  FRENSIE_CHECK_THROW( unit_aware_distribution->sampleSecondaryConditionalAndRecordTrials( 3.0*MeV, trials ),\n              std::logic_error );\n\n  // After the third bin - with extension\n  unit_aware_distribution->extendBeyondPrimaryIndepLimits();\n\n  fake_stream.resize( 3 );\n  fake_stream[0] = 0.0;\n  fake_stream[1] = 0.5;\n  fake_stream[2] = 1.0-1e-15;\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  trials = 0u;\n\n  sample = unit_aware_distribution->sampleSecondaryConditionalAndRecordTrials( 3.0*MeV, trials );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( trials, 1u );\n\n  sample = unit_aware_distribution->sampleSecondaryConditionalAndRecordTrials( 3.0*MeV, trials );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( trials, 2u );\n\n  sample = unit_aware_distribution->sampleSecondaryConditionalAndRecordTrials( 3.0*MeV, trials );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0*cgs::centimeter, 1e-14 );\n  FRENSIE_CHECK_EQUAL( trials, 3u );\n\n  unit_aware_distribution->limitToPrimaryIndepLimits();\n\n  Utility::RandomNumberGenerator::unsetFakeStream();\n}\n\n//---------------------------------------------------------------------------//\n// Check that the distribution can be archived\nFRENSIE_UNIT_TEST_TEMPLATE_EXPAND( InterpolatedPartiallyTabularBasicBivariateDistribution,\n                                   archive,\n                                   TestArchives )\n{\n  FETCH_TEMPLATE_PARAM( 0, RawOArchive );\n  FETCH_TEMPLATE_PARAM( 1, RawIArchive );\n\n  typedef typename std::remove_pointer<RawOArchive>::type OArchive;\n  typedef typename std::remove_pointer<RawIArchive>::type IArchive;\n  \n  std::string archive_base_name( \"test_LinLinLin_unit_base_interpolated_partially_tabular_basic_bivariate_dist\" );\n  std::ostringstream archive_ostream;\n\n  // Create and archive some distributions\n  {\n    std::unique_ptr<OArchive> oarchive;\n\n    createOArchive( archive_base_name, archive_ostream, oarchive );\n\n    auto concrete_dist = std::dynamic_pointer_cast<Utility::InterpolatedPartiallyTabularBasicBivariateDistribution<Utility::UnitBase<Utility::LinLinLin> > >( distribution );\n\n    FRENSIE_REQUIRE_NO_THROW( (*oarchive) << BOOST_SERIALIZATION_NVP( concrete_dist ) );\n    FRENSIE_REQUIRE_NO_THROW( (*oarchive) << boost::serialization::make_nvp( \"base_dist\", distribution ) );\n  }\n\n  // Copy the archive ostream to an istream\n  std::istringstream archive_istream( archive_ostream.str() );\n\n  // Load the archived distributions\n  std::unique_ptr<IArchive> iarchive;\n\n  createIArchive( archive_istream, iarchive );\n\n  std::shared_ptr<Utility::InterpolatedPartiallyTabularBasicBivariateDistribution<Utility::UnitBase<Utility::LinLinLin> > > concrete_dist;\n\n  FRENSIE_REQUIRE_NO_THROW( (*iarchive) >> BOOST_SERIALIZATION_NVP( concrete_dist ) );\n  \n  concrete_dist->extendBeyondPrimaryIndepLimits();\n\n  FRENSIE_CHECK_EQUAL( concrete_dist->evaluate( -1.0, -1.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( concrete_dist->evaluate( -1.0, 0.0 ), 0.1 );\n  FRENSIE_CHECK_EQUAL( concrete_dist->evaluate( -1.0, 5.0 ), 0.1 );\n  FRENSIE_CHECK_EQUAL( concrete_dist->evaluate( -1.0, 10.0 ), 0.1 );\n  FRENSIE_CHECK_EQUAL( concrete_dist->evaluate( -1.0, 11.0 ), 0.0 );\n\n  FRENSIE_CHECK_EQUAL( concrete_dist->evaluate( 0.0, -1.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( concrete_dist->evaluate( 0.0, 0.0 ), 1.0 );\n  FRENSIE_CHECK_EQUAL( concrete_dist->evaluate( 0.0, 10.0 ), exp( -10.0 ) );\n  FRENSIE_CHECK_EQUAL( concrete_dist->evaluate( 0.0, 11.0 ), 0.0 );\n\n  FRENSIE_CHECK_EQUAL( concrete_dist->evaluate( 0.5, 1.0 ), 0.0 );\n  FRENSIE_CHECK_FLOATING_EQUALITY( concrete_dist->evaluate( 0.5, 1.25 ),\n                          1.0,\n                          1e-15 );\n  FRENSIE_CHECK_FLOATING_EQUALITY( concrete_dist->evaluate( 0.5, 5.0 ),\n                          0.33782529799939026,\n                          1e-15 );\n  FRENSIE_CHECK_FLOATING_EQUALITY( concrete_dist->evaluate( 0.5, 8.75 ),\n                          0.33336359995317505,\n                          1e-15 );\n  FRENSIE_CHECK_EQUAL( concrete_dist->evaluate( 0.5, 9.0 ), 0.0 );\n\n  FRENSIE_CHECK_EQUAL( concrete_dist->evaluate( 1.0, 2.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( concrete_dist->evaluate( 1.0, 2.5 ), 1.0 );\n  FRENSIE_CHECK_EQUAL( concrete_dist->evaluate( 1.0, 5.0 ), 1.0 );\n  FRENSIE_CHECK_EQUAL( concrete_dist->evaluate( 1.0, 7.5 ), 1.0 );\n  FRENSIE_CHECK_EQUAL( concrete_dist->evaluate( 1.0, 8.0 ), 0.0 );\n\n  FRENSIE_CHECK_EQUAL( concrete_dist->evaluate( 1.5, 1.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( concrete_dist->evaluate( 1.5, 1.25 ), 0.4 );\n  FRENSIE_CHECK_EQUAL( concrete_dist->evaluate( 1.5, 5.0 ), 0.4 );\n  FRENSIE_CHECK_EQUAL( concrete_dist->evaluate( 1.5, 8.75 ), 0.4 );\n  FRENSIE_CHECK_EQUAL( concrete_dist->evaluate( 1.5, 9.0 ), 0.0 );\n\n  FRENSIE_CHECK_EQUAL( concrete_dist->evaluate( 2.0, -1.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( concrete_dist->evaluate( 2.0, 0.0 ), 0.1 );\n  FRENSIE_CHECK_EQUAL( concrete_dist->evaluate( 2.0, 5.0 ), 0.1 );\n  FRENSIE_CHECK_EQUAL( concrete_dist->evaluate( 2.0, 10.0 ), 0.1 );\n  FRENSIE_CHECK_EQUAL( concrete_dist->evaluate( 2.0, 11.0 ), 0.0 );\n\n  FRENSIE_CHECK_EQUAL( concrete_dist->evaluate( 3.0, -1.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( concrete_dist->evaluate( 3.0, 0.0 ), 0.1 );\n  FRENSIE_CHECK_EQUAL( concrete_dist->evaluate( 3.0, 5.0 ), 0.1 );\n  FRENSIE_CHECK_EQUAL( concrete_dist->evaluate( 3.0, 10.0 ), 0.1 );\n  FRENSIE_CHECK_EQUAL( concrete_dist->evaluate( 3.0, 11.0 ), 0.0 );\n\n  std::shared_ptr<Utility::PartiallyTabularBasicBivariateDistribution>\n    base_dist;\n\n  FRENSIE_REQUIRE_NO_THROW( (*iarchive) >> BOOST_SERIALIZATION_NVP( base_dist ) );\n\n  base_dist->extendBeyondPrimaryIndepLimits();\n\n  FRENSIE_CHECK_EQUAL( base_dist->evaluate( -1.0, -1.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( base_dist->evaluate( -1.0, 0.0 ), 0.1 );\n  FRENSIE_CHECK_EQUAL( base_dist->evaluate( -1.0, 5.0 ), 0.1 );\n  FRENSIE_CHECK_EQUAL( base_dist->evaluate( -1.0, 10.0 ), 0.1 );\n  FRENSIE_CHECK_EQUAL( base_dist->evaluate( -1.0, 11.0 ), 0.0 );\n\n  FRENSIE_CHECK_EQUAL( base_dist->evaluate( 0.0, -1.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( base_dist->evaluate( 0.0, 0.0 ), 1.0 );\n  FRENSIE_CHECK_EQUAL( base_dist->evaluate( 0.0, 10.0 ), exp( -10.0 ) );\n  FRENSIE_CHECK_EQUAL( base_dist->evaluate( 0.0, 11.0 ), 0.0 );\n\n  FRENSIE_CHECK_EQUAL( base_dist->evaluate( 0.5, 1.0 ), 0.0 );\n  FRENSIE_CHECK_FLOATING_EQUALITY( base_dist->evaluate( 0.5, 1.25 ),\n                          1.0,\n                          1e-15 );\n  FRENSIE_CHECK_FLOATING_EQUALITY( base_dist->evaluate( 0.5, 5.0 ),\n                          0.33782529799939026,\n                          1e-15 );\n  FRENSIE_CHECK_FLOATING_EQUALITY( base_dist->evaluate( 0.5, 8.75 ),\n                          0.33336359995317505,\n                          1e-15 );\n  FRENSIE_CHECK_EQUAL( base_dist->evaluate( 0.5, 9.0 ), 0.0 );\n\n  FRENSIE_CHECK_EQUAL( base_dist->evaluate( 1.0, 2.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( base_dist->evaluate( 1.0, 2.5 ), 1.0 );\n  FRENSIE_CHECK_EQUAL( base_dist->evaluate( 1.0, 5.0 ), 1.0 );\n  FRENSIE_CHECK_EQUAL( base_dist->evaluate( 1.0, 7.5 ), 1.0 );\n  FRENSIE_CHECK_EQUAL( base_dist->evaluate( 1.0, 8.0 ), 0.0 );\n\n  FRENSIE_CHECK_EQUAL( base_dist->evaluate( 1.5, 1.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( base_dist->evaluate( 1.5, 1.25 ), 0.4 );\n  FRENSIE_CHECK_EQUAL( base_dist->evaluate( 1.5, 5.0 ), 0.4 );\n  FRENSIE_CHECK_EQUAL( base_dist->evaluate( 1.5, 8.75 ), 0.4 );\n  FRENSIE_CHECK_EQUAL( base_dist->evaluate( 1.5, 9.0 ), 0.0 );\n\n  FRENSIE_CHECK_EQUAL( base_dist->evaluate( 2.0, -1.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( base_dist->evaluate( 2.0, 0.0 ), 0.1 );\n  FRENSIE_CHECK_EQUAL( base_dist->evaluate( 2.0, 5.0 ), 0.1 );\n  FRENSIE_CHECK_EQUAL( base_dist->evaluate( 2.0, 10.0 ), 0.1 );\n  FRENSIE_CHECK_EQUAL( base_dist->evaluate( 2.0, 11.0 ), 0.0 );\n\n  FRENSIE_CHECK_EQUAL( base_dist->evaluate( 3.0, -1.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( base_dist->evaluate( 3.0, 0.0 ), 0.1 );\n  FRENSIE_CHECK_EQUAL( base_dist->evaluate( 3.0, 5.0 ), 0.1 );\n  FRENSIE_CHECK_EQUAL( base_dist->evaluate( 3.0, 10.0 ), 0.1 );\n  FRENSIE_CHECK_EQUAL( base_dist->evaluate( 3.0, 11.0 ), 0.0 );\n}\n\n//---------------------------------------------------------------------------//\n// Check that the distribution can be archived\nFRENSIE_UNIT_TEST_TEMPLATE_EXPAND( UnitAwareInterpolatedPartiallyTabularBasicBivariateDistribution,\n                                   archive,\n                                   TestArchives )\n{\n  FETCH_TEMPLATE_PARAM( 0, RawOArchive );\n  FETCH_TEMPLATE_PARAM( 1, RawIArchive );\n\n  typedef typename std::remove_pointer<RawOArchive>::type OArchive;\n  typedef typename std::remove_pointer<RawIArchive>::type IArchive;\n  \n  std::string archive_base_name( \"test_LinLinLin_unit_base_unit_aware_interpolated_partially_tabular_basic_bivariate_dist\" );\n  std::ostringstream archive_ostream;\n\n  // Create and archive some distributions\n  {\n    std::unique_ptr<OArchive> oarchive;\n\n    createOArchive( archive_base_name, archive_ostream, oarchive );\n\n    auto concrete_dist = std::dynamic_pointer_cast<Utility::UnitAwareInterpolatedPartiallyTabularBasicBivariateDistribution<Utility::UnitBase<Utility::LinLinLin>,MegaElectronVolt,cgs::length,Barn> >( unit_aware_distribution );\n\n    FRENSIE_REQUIRE_NO_THROW( (*oarchive) << BOOST_SERIALIZATION_NVP( concrete_dist ) );\n    FRENSIE_REQUIRE_NO_THROW( (*oarchive) << boost::serialization::make_nvp( \"base_dist\", unit_aware_distribution ) );\n  }\n\n  // Copy the archive ostream to an istream\n  std::istringstream archive_istream( archive_ostream.str() );\n\n  // Load the archived distributions\n  std::unique_ptr<IArchive> iarchive;\n\n  createIArchive( archive_istream, iarchive );\n\n  std::shared_ptr<Utility::UnitAwareInterpolatedPartiallyTabularBasicBivariateDistribution<Utility::UnitBase<Utility::LinLinLin>,MegaElectronVolt,cgs::length,Barn> > concrete_dist;\n\n  FRENSIE_REQUIRE_NO_THROW( (*iarchive) >> BOOST_SERIALIZATION_NVP( concrete_dist ) );\n\n  concrete_dist->extendBeyondPrimaryIndepLimits();\n\n  FRENSIE_CHECK_EQUAL( concrete_dist->evaluate( -1.0*MeV, -1.0*cgs::centimeter ), 0.0*barn );\n  FRENSIE_CHECK_EQUAL( concrete_dist->evaluate( -1.0*MeV, 0.0*cgs::centimeter ), 0.1*barns );\n  FRENSIE_CHECK_EQUAL( concrete_dist->evaluate( -1.0*MeV, 5.0*cgs::centimeter ), 0.1*barns );\n  FRENSIE_CHECK_EQUAL( concrete_dist->evaluate( -1.0*MeV, 10.0*cgs::centimeter ), 0.1*barns );\n  FRENSIE_CHECK_EQUAL( concrete_dist->evaluate( -1.0*MeV, 11.0*cgs::centimeter ), 0.0*barn );\n\n  FRENSIE_CHECK_EQUAL( concrete_dist->evaluate( 0.0*MeV, -1.0*cgs::centimeter ), 0.0*barn );\n  FRENSIE_CHECK_EQUAL( concrete_dist->evaluate( 0.0*MeV, 0.0*cgs::centimeter ), 1.0*barns );\n  FRENSIE_CHECK_EQUAL( concrete_dist->evaluate( 0.0*MeV, 10.0*cgs::centimeter ), exp( -10.0 )*barns );\n  FRENSIE_CHECK_EQUAL( concrete_dist->evaluate( 0.0*MeV, 11.0*cgs::centimeter ), 0.0*barn );\n\n  FRENSIE_CHECK_EQUAL( concrete_dist->evaluate( 0.5*MeV, 1.0*cgs::centimeter ), 0.0*barn );\n  FRENSIE_CHECK_FLOATING_EQUALITY( concrete_dist->evaluate( 0.5*MeV, 1.25*cgs::centimeter ),\n                          1.0*barns,\n                          1e-15 );\n  FRENSIE_CHECK_FLOATING_EQUALITY( concrete_dist->evaluate( 0.5*MeV, 5.0*cgs::centimeter ),\n                          0.33782529799939026*barns,\n                          1e-15 );\n  FRENSIE_CHECK_FLOATING_EQUALITY( concrete_dist->evaluate( 0.5*MeV, 8.75*cgs::centimeter ),\n                          0.33336359995317505*barns,\n                          1e-15 );\n  FRENSIE_CHECK_EQUAL( concrete_dist->evaluate( 0.5*MeV, 9.0*cgs::centimeter ), 0.0*barn );\n\n  FRENSIE_CHECK_EQUAL( concrete_dist->evaluate( 1.0*MeV, 2.0*cgs::centimeter ), 0.0*barn );\n  FRENSIE_CHECK_EQUAL( concrete_dist->evaluate( 1.0*MeV, 2.5*cgs::centimeter ), 1.0*barn );\n  FRENSIE_CHECK_EQUAL( concrete_dist->evaluate( 1.0*MeV, 5.0*cgs::centimeter ), 1.0*barn );\n  FRENSIE_CHECK_EQUAL( concrete_dist->evaluate( 1.0*MeV, 7.5*cgs::centimeter ), 1.0*barn );\n  FRENSIE_CHECK_EQUAL( concrete_dist->evaluate( 1.0*MeV, 8.0*cgs::centimeter ), 0.0*barn );\n\n  FRENSIE_CHECK_EQUAL( concrete_dist->evaluate( 1.5*MeV, 1.0*cgs::centimeter ), 0.0*barn );\n  FRENSIE_CHECK_EQUAL( concrete_dist->evaluate( 1.5*MeV, 1.25*cgs::centimeter ), 0.4*barns );\n  FRENSIE_CHECK_EQUAL( concrete_dist->evaluate( 1.5*MeV, 5.0*cgs::centimeter ), 0.4*barns );\n  FRENSIE_CHECK_EQUAL( concrete_dist->evaluate( 1.5*MeV, 8.75*cgs::centimeter ), 0.4*barns );\n  FRENSIE_CHECK_EQUAL( concrete_dist->evaluate( 1.5*MeV, 9.0*cgs::centimeter ), 0.0*barn );\n\n  FRENSIE_CHECK_EQUAL( concrete_dist->evaluate( 2.0*MeV, -1.0*cgs::centimeter ), 0.0*barn );\n  FRENSIE_CHECK_EQUAL( concrete_dist->evaluate( 2.0*MeV, 0.0*cgs::centimeter ), 0.1*barns );\n  FRENSIE_CHECK_EQUAL( concrete_dist->evaluate( 2.0*MeV, 5.0*cgs::centimeter ), 0.1*barns );\n  FRENSIE_CHECK_EQUAL( concrete_dist->evaluate( 2.0*MeV, 10.0*cgs::centimeter ), 0.1*barns );\n  FRENSIE_CHECK_EQUAL( concrete_dist->evaluate( 2.0*MeV, 11.0*cgs::centimeter ), 0.0*barn );\n\n  FRENSIE_CHECK_EQUAL( concrete_dist->evaluate( 3.0*MeV, -1.0*cgs::centimeter ), 0.0*barn );\n  FRENSIE_CHECK_EQUAL( concrete_dist->evaluate( 3.0*MeV, 0.0*cgs::centimeter ), 0.1*barns );\n  FRENSIE_CHECK_EQUAL( concrete_dist->evaluate( 3.0*MeV, 5.0*cgs::centimeter ), 0.1*barns );\n  FRENSIE_CHECK_EQUAL( concrete_dist->evaluate( 3.0*MeV, 10.0*cgs::centimeter ), 0.1*barns );\n  FRENSIE_CHECK_EQUAL( concrete_dist->evaluate( 3.0*MeV, 11.0*cgs::centimeter ), 0.0*barn );\n\n  std::shared_ptr<Utility::UnitAwarePartiallyTabularBasicBivariateDistribution<MegaElectronVolt,cgs::length,Barn> >\n    base_dist;\n\n  FRENSIE_REQUIRE_NO_THROW( (*iarchive) >> BOOST_SERIALIZATION_NVP( base_dist ) );\n\n  base_dist->extendBeyondPrimaryIndepLimits();\n\n  FRENSIE_CHECK_EQUAL( base_dist->evaluate( -1.0*MeV, -1.0*cgs::centimeter ), 0.0*barn );\n  FRENSIE_CHECK_EQUAL( base_dist->evaluate( -1.0*MeV, 0.0*cgs::centimeter ), 0.1*barns );\n  FRENSIE_CHECK_EQUAL( base_dist->evaluate( -1.0*MeV, 5.0*cgs::centimeter ), 0.1*barns );\n  FRENSIE_CHECK_EQUAL( base_dist->evaluate( -1.0*MeV, 10.0*cgs::centimeter ), 0.1*barns );\n  FRENSIE_CHECK_EQUAL( base_dist->evaluate( -1.0*MeV, 11.0*cgs::centimeter ), 0.0*barn );\n\n  FRENSIE_CHECK_EQUAL( base_dist->evaluate( 0.0*MeV, -1.0*cgs::centimeter ), 0.0*barn );\n  FRENSIE_CHECK_EQUAL( base_dist->evaluate( 0.0*MeV, 0.0*cgs::centimeter ), 1.0*barns );\n  FRENSIE_CHECK_EQUAL( base_dist->evaluate( 0.0*MeV, 10.0*cgs::centimeter ), exp( -10.0 )*barns );\n  FRENSIE_CHECK_EQUAL( base_dist->evaluate( 0.0*MeV, 11.0*cgs::centimeter ), 0.0*barn );\n\n  FRENSIE_CHECK_EQUAL( base_dist->evaluate( 0.5*MeV, 1.0*cgs::centimeter ), 0.0*barn );\n  FRENSIE_CHECK_FLOATING_EQUALITY( base_dist->evaluate( 0.5*MeV, 1.25*cgs::centimeter ),\n                          1.0*barns,\n                          1e-15 );\n  FRENSIE_CHECK_FLOATING_EQUALITY( base_dist->evaluate( 0.5*MeV, 5.0*cgs::centimeter ),\n                          0.33782529799939026*barns,\n                          1e-15 );\n  FRENSIE_CHECK_FLOATING_EQUALITY( base_dist->evaluate( 0.5*MeV, 8.75*cgs::centimeter ),\n                          0.33336359995317505*barns,\n                          1e-15 );\n  FRENSIE_CHECK_EQUAL( base_dist->evaluate( 0.5*MeV, 9.0*cgs::centimeter ), 0.0*barn );\n\n  FRENSIE_CHECK_EQUAL( base_dist->evaluate( 1.0*MeV, 2.0*cgs::centimeter ), 0.0*barn );\n  FRENSIE_CHECK_EQUAL( base_dist->evaluate( 1.0*MeV, 2.5*cgs::centimeter ), 1.0*barn );\n  FRENSIE_CHECK_EQUAL( base_dist->evaluate( 1.0*MeV, 5.0*cgs::centimeter ), 1.0*barn );\n  FRENSIE_CHECK_EQUAL( base_dist->evaluate( 1.0*MeV, 7.5*cgs::centimeter ), 1.0*barn );\n  FRENSIE_CHECK_EQUAL( base_dist->evaluate( 1.0*MeV, 8.0*cgs::centimeter ), 0.0*barn );\n\n  FRENSIE_CHECK_EQUAL( base_dist->evaluate( 1.5*MeV, 1.0*cgs::centimeter ), 0.0*barn );\n  FRENSIE_CHECK_EQUAL( base_dist->evaluate( 1.5*MeV, 1.25*cgs::centimeter ), 0.4*barns );\n  FRENSIE_CHECK_EQUAL( base_dist->evaluate( 1.5*MeV, 5.0*cgs::centimeter ), 0.4*barns );\n  FRENSIE_CHECK_EQUAL( base_dist->evaluate( 1.5*MeV, 8.75*cgs::centimeter ), 0.4*barns );\n  FRENSIE_CHECK_EQUAL( base_dist->evaluate( 1.5*MeV, 9.0*cgs::centimeter ), 0.0*barn );\n\n  FRENSIE_CHECK_EQUAL( base_dist->evaluate( 2.0*MeV, -1.0*cgs::centimeter ), 0.0*barn );\n  FRENSIE_CHECK_EQUAL( base_dist->evaluate( 2.0*MeV, 0.0*cgs::centimeter ), 0.1*barns );\n  FRENSIE_CHECK_EQUAL( base_dist->evaluate( 2.0*MeV, 5.0*cgs::centimeter ), 0.1*barns );\n  FRENSIE_CHECK_EQUAL( base_dist->evaluate( 2.0*MeV, 10.0*cgs::centimeter ), 0.1*barns );\n  FRENSIE_CHECK_EQUAL( base_dist->evaluate( 2.0*MeV, 11.0*cgs::centimeter ), 0.0*barn );\n\n  FRENSIE_CHECK_EQUAL( base_dist->evaluate( 3.0*MeV, -1.0*cgs::centimeter ), 0.0*barn );\n  FRENSIE_CHECK_EQUAL( base_dist->evaluate( 3.0*MeV, 0.0*cgs::centimeter ), 0.1*barns );\n  FRENSIE_CHECK_EQUAL( base_dist->evaluate( 3.0*MeV, 5.0*cgs::centimeter ), 0.1*barns );\n  FRENSIE_CHECK_EQUAL( base_dist->evaluate( 3.0*MeV, 10.0*cgs::centimeter ), 0.1*barns );\n  FRENSIE_CHECK_EQUAL( base_dist->evaluate( 3.0*MeV, 11.0*cgs::centimeter ), 0.0*barn );\n}\n\n//---------------------------------------------------------------------------//\n// Custom setup\n//---------------------------------------------------------------------------//\nFRENSIE_CUSTOM_UNIT_TEST_SETUP_BEGIN();\n\nFRENSIE_CUSTOM_UNIT_TEST_INIT()\n{\n  // Create the two-dimensional distribution\n  {\n    std::vector<double> primary_grid( 4 );\n    std::vector<std::shared_ptr<const Utility::UnivariateDistribution> >\n      secondary_dists( 4 );\n\n    // Create the secondary distribution in the first bin\n    primary_grid[0] = 0.0;\n    secondary_dists[0].reset( new Utility::UniformDistribution( 0.0, 10.0, 0.1 ) );\n\n    // Create the secondary distribution in the second bin\n    primary_grid[1] = 0.0;\n    secondary_dists[1].reset( new Utility::ExponentialDistribution( 1.0, 1.0, 0.0, 10.0 ) );\n\n    // Create the secondary distribution in the third bin\n    primary_grid[2] = 1.0;\n    secondary_dists[2].reset( new Utility::UniformDistribution( 2.5, 7.5, 1.0 ) );\n\n    // Create the secondary distribution beyond the third bin\n    primary_grid[3] = 2.0;\n    secondary_dists[3] = secondary_dists[0];\n    \n    distribution.reset( new Utility::InterpolatedPartiallyTabularBasicBivariateDistribution<Utility::UnitBase<Utility::LinLinLin> >(\n                                             primary_grid, secondary_dists ) );\n  }\n\n  // Create the unit-aware two-dimensional distribution\n  {\n    std::vector<quantity<MegaElectronVolt> > primary_bins( 4 );\n\n    std::vector<std::shared_ptr<const Utility::UnitAwareUnivariateDistribution<cgs::length,Barn> > > secondary_dists( 4 );\n\n    // Create the secondary distribution in the first bin\n    primary_bins[0] = 0.0*MeV;\n    secondary_dists[0].reset( new Utility::UnitAwareUniformDistribution<cgs::length,Barn>( 0.0*cgs::centimeter, 10.0*cgs::centimeter, 0.1*barn ) );\n\n    // Create the secondary distribution in the second bin\n    primary_bins[1] = 0.0*MeV;\n    secondary_dists[1].reset( new Utility::UnitAwareExponentialDistribution<cgs::length,Barn>( 1.0*barn, 1.0/cgs::centimeter, 0.0*cgs::centimeter, 10.0*cgs::centimeter ) );\n\n    // Create the secondary distribution in the third bin\n    primary_bins[2] = 1.0*MeV;\n    secondary_dists[2].reset( new Utility::UnitAwareUniformDistribution<cgs::length,Barn>( 2.5*cgs::centimeter, 7.5*cgs::centimeter, 1.0*barn ) );\n\n    // Create the secondary distribution beyond the third bin\n    primary_bins[3] = 2.0*MeV;\n    secondary_dists[3] = secondary_dists[0];\n    \n    unit_aware_distribution.reset( new Utility::UnitAwareInterpolatedPartiallyTabularBasicBivariateDistribution<Utility::UnitBase<Utility::LinLinLin>,MegaElectronVolt,cgs::length,Barn>( primary_bins, secondary_dists ) );\n  }\n\n  // Initialize the random number generator\n  Utility::RandomNumberGenerator::createStreams();\n}\n\nFRENSIE_CUSTOM_UNIT_TEST_SETUP_END();\n\n//---------------------------------------------------------------------------//\n// end tstLinLinLinUnitBaseInterpolatedPartiallyTabularBasicBivariateDistribution.cpp\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "78d874d36b8927a167119926279d564bfefd8715", "size": 88708, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "packages/utility/distribution/test/tstLinLinLinUnitBaseInterpolatedPartiallyTabularBasicBivariateDistribution.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/utility/distribution/test/tstLinLinLinUnitBaseInterpolatedPartiallyTabularBasicBivariateDistribution.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/utility/distribution/test/tstLinLinLinUnitBaseInterpolatedPartiallyTabularBasicBivariateDistribution.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": 43.6125860374, "max_line_length": 226, "alphanum_fraction": 0.6952924201, "num_tokens": 26835, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.47905516732144143}}
{"text": "// system includes -----------------------------------------------\n#include <boost/math/constants/constants.hpp>\n#include <boost/program_options.hpp>\n#include <iostream>\n// own includes --------------------------------------------------\n#include <base/eigen2hdf.hpp>\n#include <base/init.hpp>\n#include <fft/fft2.hpp>\n#include <fft/ft_grid_helpers.hpp>\n#include <fft/shift.hpp>\n#include <ridgelet/ridgelet_frame.hpp>\n#include <ridgelet/rt.hpp>\n\nusing namespace std;\n\nEigen::VectorXd fft_freq(int n)\n{\n  Eigen::VectorXd x(n);\n\n  for (int i = 0; i < n / 2 + n % 2; ++i) {\n    x[i] = i;\n  }\n  for (int i = n / 2 + n % 2, j = 0; i < n; ++i, ++j) {\n    x[i] = -n / 2 + j;\n  }\n\n  return x;\n}\n\n/// even/odd test\nvoid test1()\n{\n  Eigen::VectorXd x5(5);\n  Eigen::VectorXd x4(4);\n\n  fftshift(x5, fft_freq(5), 0);\n  fftshift(x4, fft_freq(4), 0);\n\n  cout << \"x5:\\n\" << x5.transpose() << \"\\n\";\n  cout << \"x4:\\n\" << x4.transpose() << \"\\n\";\n\n  cout << \"ftcut(x5, 4, 1):\"\n       << \"\\n\";\n  cout << ftcut(x5, 4, 1).transpose() << endl;\n\n  // cout << \"fft_freq(4):\\n\"  << fft_freq(4) << \"\\n\";\n  // cout << \"fft_freq(5):\\n\"  << fft_freq(5) << \"\\n\";\n}\n\n/// n vs n/2 test\nvoid test2()\n{\n  Eigen::VectorXd x8(8);\n  Eigen::VectorXd x4(4);\n\n  fftshift(x8, fft_freq(8), 0);\n  fftshift(x4, fft_freq(4), 0);\n\n  cout << \"x8:\\n\" << x8.transpose() << \"\\n\";\n  cout << \"x4:\\n\" << x4.transpose() << \"\\n\";\n\n  cout << \"ftcut(x5, 4, 1):\"\n       << \"\\n\";\n  cout << ftcut(x8, 4, 1).transpose() << endl;\n}\n\nint main(int argc, char *argv[])\n{\n  cout << \"---------- test1() ----------\"\n       << \"\\n\";\n  test1();\n\n  cout << \"---------- test2() ----------\"\n       << \"\\n\";\n  test2();\n\n  return 0;\n}\n", "meta": {"hexsha": "eced04689102fc8128052ce4aa9bcf9e1b39c152", "size": 1655, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/main_test_ftcut.cpp", "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": "test/main_test_ftcut.cpp", "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": "test/main_test_ftcut.cpp", "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": 20.9493670886, "max_line_length": 66, "alphanum_fraction": 0.4900302115, "num_tokens": 564, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.47905516732144143}}
{"text": "// The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt\r\n/*\r\n    This is an example illustrating the use of the deep learning tools from the\r\n    dlib C++ Library.  I'm assuming you have already read the introductory\r\n    dnn_introduction_ex.cpp and dnn_introduction2_ex.cpp examples.  In this\r\n    example we are going to show how to create inception networks. \r\n\r\n    An inception network is composed of inception blocks of the form:\r\n\r\n               input from SUBNET\r\n              /        |        \\\r\n             /         |         \\\r\n          block1    block2  ... blockN \r\n             \\         |         /\r\n              \\        |        /\r\n          concatenate tensors from blocks\r\n                       |\r\n                    output\r\n                 \r\n    That is, an inception blocks runs a number of smaller networks (e.g. block1,\r\n    block2) and then concatenates their results.  For further reading refer to:\r\n    Szegedy, Christian, et al. \"Going deeper with convolutions.\" Proceedings of\r\n    the IEEE Conference on Computer Vision and Pattern Recognition. 2015.\r\n*/\r\n\r\n#include <dlib/dnn.h>\r\n#include <iostream>\r\n#include <dlib/data_io.h>\r\n\r\nusing namespace std;\r\nusing namespace dlib;\r\n\r\n// Inception layer has some different convolutions inside.  Here we define\r\n// blocks as convolutions with different kernel size that we will use in\r\n// inception layer block.\r\ntemplate <typename SUBNET> using block_a1 = relu<con<10,1,1,1,1,SUBNET>>;\r\ntemplate <typename SUBNET> using block_a2 = relu<con<10,3,3,1,1,relu<con<16,1,1,1,1,SUBNET>>>>;\r\ntemplate <typename SUBNET> using block_a3 = relu<con<10,5,5,1,1,relu<con<16,1,1,1,1,SUBNET>>>>;\r\ntemplate <typename SUBNET> using block_a4 = relu<con<10,1,1,1,1,max_pool<3,3,1,1,SUBNET>>>;\r\n\r\n// Here is inception layer definition. It uses different blocks to process input\r\n// and returns combined output.  Dlib includes a number of these inceptionN\r\n// layer types which are themselves created using concat layers.  \r\ntemplate <typename SUBNET> using incept_a = inception4<block_a1,block_a2,block_a3,block_a4, SUBNET>;\r\n\r\n// Network can have inception layers of different structure.  It will work\r\n// properly so long as all the sub-blocks inside a particular inception block\r\n// output tensors with the same number of rows and columns.\r\ntemplate <typename SUBNET> using block_b1 = relu<con<4,1,1,1,1,SUBNET>>;\r\ntemplate <typename SUBNET> using block_b2 = relu<con<4,3,3,1,1,SUBNET>>;\r\ntemplate <typename SUBNET> using block_b3 = relu<con<4,1,1,1,1,max_pool<3,3,1,1,SUBNET>>>;\r\ntemplate <typename SUBNET> using incept_b = inception3<block_b1,block_b2,block_b3,SUBNET>;\r\n\r\n// Now we can define a simple network for classifying MNIST digits.  We will\r\n// train and test this network in the code below.\r\nusing net_type = loss_multiclass_log<\r\n        fc<10,\r\n        relu<fc<32,\r\n        max_pool<2,2,2,2,incept_b<\r\n        max_pool<2,2,2,2,incept_a<\r\n        input<matrix<unsigned char>>\r\n        >>>>>>>>;\r\n\r\nint main(int argc, char** argv) try\r\n{\r\n    // This example is going to run on the MNIST dataset.\r\n    if (argc != 2)\r\n    {\r\n        cout << \"This example needs the MNIST dataset to run!\" << endl;\r\n        cout << \"You can get MNIST from http://yann.lecun.com/exdb/mnist/\" << endl;\r\n        cout << \"Download the 4 files that comprise the dataset, decompress them, and\" << endl;\r\n        cout << \"put them in a folder.  Then give that folder as input to this program.\" << endl;\r\n        return 1;\r\n    }\r\n\r\n\r\n    std::vector<matrix<unsigned char>> training_images;\r\n    std::vector<unsigned long>         training_labels;\r\n    std::vector<matrix<unsigned char>> testing_images;\r\n    std::vector<unsigned long>         testing_labels;\r\n    load_mnist_dataset(argv[1], training_images, training_labels, testing_images, testing_labels);\r\n\r\n\r\n    // Make an instance of our inception network.\r\n    net_type net;\r\n    cout << \"The net has \" << net.num_layers << \" layers in it.\" << endl;\r\n    cout << net << endl;\r\n\r\n\r\n    cout << \"Traning NN...\" << endl;\r\n    dnn_trainer<net_type> trainer(net);\r\n    trainer.set_learning_rate(0.01);\r\n    trainer.set_min_learning_rate(0.00001);\r\n    trainer.set_mini_batch_size(128);\r\n    trainer.be_verbose();\r\n    trainer.set_synchronization_file(\"inception_sync\", std::chrono::seconds(20));\r\n    // Train the network.  This might take a few minutes...\r\n    trainer.train(training_images, training_labels);\r\n\r\n    // At this point our net object should have learned how to classify MNIST images.  But\r\n    // before we try it out let's save it to disk.  Note that, since the trainer has been\r\n    // running images through the network, net will have a bunch of state in it related to\r\n    // the last batch of images it processed (e.g. outputs from each layer).  Since we\r\n    // don't care about saving that kind of stuff to disk we can tell the network to forget\r\n    // about that kind of transient data so that our file will be smaller.  We do this by\r\n    // \"cleaning\" the network before saving it.\r\n    net.clean();\r\n    serialize(\"mnist_network_inception.dat\") << net;\r\n    // Now if we later wanted to recall the network from disk we can simply say:\r\n    // deserialize(\"mnist_network_inception.dat\") >> net;\r\n\r\n\r\n    // Now let's run the training images through the network.  This statement runs all the\r\n    // images through it and asks the loss layer to convert the network's raw output into\r\n    // labels.  In our case, these labels are the numbers between 0 and 9.\r\n    std::vector<unsigned long> predicted_labels = net(training_images);\r\n    int num_right = 0;\r\n    int num_wrong = 0;\r\n    // And then let's see if it classified them correctly.\r\n    for (size_t i = 0; i < training_images.size(); ++i)\r\n    {\r\n        if (predicted_labels[i] == training_labels[i])\r\n            ++num_right;\r\n        else\r\n            ++num_wrong;\r\n        \r\n    }\r\n    cout << \"training num_right: \" << num_right << endl;\r\n    cout << \"training num_wrong: \" << num_wrong << endl;\r\n    cout << \"training accuracy:  \" << num_right/(double)(num_right+num_wrong) << endl;\r\n\r\n    // Let's also see if the network can correctly classify the testing images.\r\n    // Since MNIST is an easy dataset, we should see 99% accuracy.\r\n    predicted_labels = net(testing_images);\r\n    num_right = 0;\r\n    num_wrong = 0;\r\n    for (size_t i = 0; i < testing_images.size(); ++i)\r\n    {\r\n        if (predicted_labels[i] == testing_labels[i])\r\n            ++num_right;\r\n        else\r\n            ++num_wrong;\r\n        \r\n    }\r\n    cout << \"testing num_right: \" << num_right << endl;\r\n    cout << \"testing num_wrong: \" << num_wrong << endl;\r\n    cout << \"testing accuracy:  \" << num_right/(double)(num_right+num_wrong) << endl;\r\n\r\n}\r\ncatch(std::exception& e)\r\n{\r\n    cout << e.what() << endl;\r\n}\r\n\r\n", "meta": {"hexsha": "812a1edb40c67beff2ebbcfb92d3eeb72f1cf0ed", "size": 6822, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/dnn_inception_ex.cpp", "max_stars_repo_name": "ytobah/dlib-mod", "max_stars_repo_head_hexsha": "f1ddeb506b59c8b49f744323301b7f22fd3a25e0", "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/dnn_inception_ex.cpp", "max_issues_repo_name": "ytobah/dlib-mod", "max_issues_repo_head_hexsha": "f1ddeb506b59c8b49f744323301b7f22fd3a25e0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/dnn_inception_ex.cpp", "max_forks_repo_name": "ytobah/dlib-mod", "max_forks_repo_head_hexsha": "f1ddeb506b59c8b49f744323301b7f22fd3a25e0", "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.0129032258, "max_line_length": 101, "alphanum_fraction": 0.648783348, "num_tokens": 1718, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.752012562644147, "lm_q2_score": 0.6370308013713525, "lm_q1q2_score": 0.47905516542252535}}
{"text": "// ---------------------------------------------------------------------\n//\n// Copyright (c) 2018 - 2020 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/boundary_info.h>\n#include <libmesh/boundary_mesh.h>\n#include <libmesh/equation_systems.h>\n#include <libmesh/exodusII_io.h>\n#include <libmesh/explicit_system.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/IBFEMethod.h>\n#include <ibamr/INSCollocatedHierarchyIntegrator.h>\n#include <ibamr/INSStaggeredHierarchyIntegrator.h>\n\n#include <ibtk/AppInitializer.h>\n#include <ibtk/IBTKInit.h>\n#include <ibtk/LEInteractor.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\n// Elasticity model data.\nnamespace ModelData\n{\n// Tether (penalty) force functions.\nstatic double kappa_s = 1.0e6;\nstatic double eta_s = 0.0;\nSystem *x_solid_system, *u_solid_system;\nvoid\ntether_force_function(VectorValue<double>& F,\n                      const TensorValue<double>& /*FF*/,\n                      const libMesh::Point& x_bndry, // x_bndry gives current   coordinates on the boundary mesh\n                      const libMesh::Point& X_bndry, // X_bndry gives reference coordinates on the boundary mesh\n                      Elem* const elem,\n                      const vector<const vector<double>*>& var_data,\n                      const vector<const vector<VectorValue<double> >*>& /*grad_var_data*/,\n                      double /*time*/,\n                      void* /*ctx*/)\n{\n    // tether_force_function() is called on elements of the boundary mesh.  Here\n    // we look up the element in the solid mesh that the current boundary\n    // element was extracted from.\n    const Elem* const interior_parent = elem->interior_parent();\n\n    // We define \"arbitrary\" velocity and displacement fields on the solid mesh.\n    // Here we look up their values.\n    std::vector<double> x_solid(NDIM, 0.0), u_solid(NDIM, 0.0);\n    for (unsigned int d = 0; d < NDIM; ++d)\n    {\n        x_solid[d] = x_solid_system->point_value(d, X_bndry, interior_parent);\n        u_solid[d] = u_solid_system->point_value(d, X_bndry, interior_parent);\n    }\n\n    // Look up the velocity of the boundary mesh.\n    const std::vector<double>& u_bndry = *var_data[0];\n\n    // The tether force is proportional to the mismatch between the positions\n    // and velocities.\n    for (unsigned int d = 0; d < NDIM; ++d)\n    {\n        F(d) = kappa_s * (x_solid[d] - x_bndry(d)) + eta_s * (u_solid[d] - u_bndry[d]);\n    }\n    return;\n} // tether_force_function\n} // namespace ModelData\nusing namespace ModelData;\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        // 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_solid_filename = \"solid_output.ex2\"; // app_initializer->getExodusIIFilename();\n        const string exodus_bndry_filename = \"bndry_output.ex2\"; // 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        const double R = 0.5;\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\n        BoundaryMesh bndry_mesh(solid_mesh.comm(), solid_mesh.mesh_dimension() - 1);\n        solid_mesh.boundary_info->sync(bndry_mesh);\n        bndry_mesh.prepare_for_use();\n\n        kappa_s = input_db->getDouble(\"KAPPA_S\");\n        eta_s = input_db->getDouble(\"ETA_S\");\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;\n        const string solver_type = app_initializer->getComponentDatabase(\"Main\")->getString(\"solver_type\");\n        if (solver_type == \"STAGGERED\")\n        {\n            navier_stokes_integrator = new INSStaggeredHierarchyIntegrator(\n                \"INSStaggeredHierarchyIntegrator\",\n                app_initializer->getComponentDatabase(\"INSStaggeredHierarchyIntegrator\"));\n        }\n        else if (solver_type == \"COLLOCATED\")\n        {\n            navier_stokes_integrator = new INSCollocatedHierarchyIntegrator(\n                \"INSCollocatedHierarchyIntegrator\",\n                app_initializer->getComponentDatabase(\"INSCollocatedHierarchyIntegrator\"));\n        }\n        else\n        {\n            TBOX_ERROR(\"Unsupported solver type: \" << solver_type << \"\\n\"\n                                                   << \"Valid options are: COLLOCATED, STAGGERED\");\n        }\n        Pointer<IBFEMethod> ib_method_ops =\n            new IBFEMethod(\"IBFEMethod\",\n                           app_initializer->getComponentDatabase(\"IBFEMethod\"),\n                           &bndry_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        // Configure the IBFE solver.\n        ib_method_ops->initializeFEEquationSystems();\n        std::vector<int> vars(NDIM);\n        for (unsigned int d = 0; d < NDIM; ++d) vars[d] = d;\n        vector<SystemData> sys_data(1, SystemData(IBFEMethod::VELOCITY_SYSTEM_NAME, vars));\n        IBFEMethod::LagBodyForceFcnData body_fcn_data(tether_force_function, sys_data);\n        ib_method_ops->registerLagBodyForceFunction(body_fcn_data);\n        EquationSystems* bndry_equation_systems = ib_method_ops->getFEDataManager()->getEquationSystems();\n\n        // Setup solid systems.\n        std::unique_ptr<EquationSystems> solid_equation_systems(new EquationSystems(solid_mesh));\n        x_solid_system = &solid_equation_systems->add_system<ExplicitSystem>(\"position\");\n        u_solid_system = &solid_equation_systems->add_system<ExplicitSystem>(\"velocity\");\n        Order order = SECOND;\n        FEFamily family = LAGRANGE;\n        for (int d = 0; d < NDIM; ++d)\n        {\n            x_solid_system->add_variable(\"X_\" + std::to_string(d), order, family);\n        }\n        for (int d = 0; d < NDIM; ++d)\n        {\n            u_solid_system->add_variable(\"U_\" + std::to_string(d), order, family);\n        }\n        solid_equation_systems->init();\n\n        // Set up the position vector.\n        //\n        // \\todo There needs to be an API so that this can be handled by the IBFEMethod class implementation.\n        {\n            MeshBase& mesh = solid_equation_systems->get_mesh();\n            System& X_system = solid_equation_systems->get_system(\"position\");\n            const unsigned int X_sys_num = X_system.number();\n            NumericVector<double>& X_coords = *X_system.solution;\n            for (MeshBase::node_iterator it = mesh.local_nodes_begin(); it != mesh.local_nodes_end(); ++it)\n            {\n                Node* n = *it;\n                if (n->n_vars(X_sys_num))\n                {\n                    TBOX_ASSERT(n->n_vars(X_sys_num) == NDIM);\n                    const libMesh::Point& X = *n;\n                    libMesh::Point x = X;\n                    for (unsigned int d = 0; d < NDIM; ++d)\n                    {\n                        const int dof_index = n->dof_number(X_sys_num, d, 0);\n                        X_coords.set(dof_index, x(d));\n                    }\n                }\n            }\n            X_coords.close();\n            X_system.get_dof_map().enforce_constraints_exactly(X_system, &X_coords);\n            copy_and_synch(*X_system.solution, *X_system.current_local_solution);\n        }\n\n        x_solid_system->assemble_before_solve = false;\n        x_solid_system->assemble();\n\n        u_solid_system->assemble_before_solve = false;\n        u_solid_system->assemble();\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_solid_io(uses_exodus ? new ExodusII_IO(solid_mesh) : NULL);\n        std::unique_ptr<ExodusII_IO> exodus_bndry_io(uses_exodus ? new ExodusII_IO(bndry_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_solid_io->append(from_restart);\n            exodus_bndry_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_solid_io->write_timestep(\n                    exodus_solid_filename, *solid_equation_systems, iteration_num / viz_dump_interval + 1, loop_time);\n                exodus_bndry_io->write_timestep(\n                    exodus_bndry_filename, *bndry_equation_systems, iteration_num / viz_dump_interval + 1, loop_time);\n            }\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            // Setup the position and velocity vector.\n            //\n            // \\todo There needs to be an API so that this can be handled by the IBFEMethod class implementation.\n            {\n                DenseVector<double> U(NDIM);\n                U(1) = -1.0;\n                MeshBase& mesh = solid_equation_systems->get_mesh();\n                System& X_system = solid_equation_systems->get_system(\"position\");\n                const unsigned int X_sys_num = X_system.number();\n                NumericVector<double>& X_coords = *X_system.solution;\n                System& U_system = solid_equation_systems->get_system(\"velocity\");\n                const unsigned int U_sys_num = U_system.number();\n                NumericVector<double>& U_coords = *U_system.solution;\n                for (MeshBase::node_iterator it = mesh.local_nodes_begin(); it != mesh.local_nodes_end(); ++it)\n                {\n                    Node* n = *it;\n                    if (n->n_vars(X_sys_num))\n                    {\n                        TBOX_ASSERT(n->n_vars(X_sys_num) == NDIM);\n                        const libMesh::Point& X = *n;\n                        for (unsigned int d = 0; d < NDIM; ++d)\n                        {\n                            const int dof_index = n->dof_number(U_sys_num, d, 0);\n                            X_coords.set(dof_index, X(d) + loop_time * U(d));\n                            U_coords.set(dof_index, U(d));\n                        }\n                    }\n                }\n                X_coords.close();\n                X_system.get_dof_map().enforce_constraints_exactly(X_system, &X_coords);\n                copy_and_synch(X_coords, *X_system.current_local_solution);\n                U_coords.close();\n                U_system.get_dof_map().enforce_constraints_exactly(U_system, &U_coords);\n                copy_and_synch(U_coords, *U_system.current_local_solution);\n            }\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_solid_io->write_timestep(exodus_solid_filename,\n                                                    *solid_equation_systems,\n                                                    iteration_num / viz_dump_interval + 1,\n                                                    loop_time);\n                    exodus_bndry_io->write_timestep(exodus_bndry_filename,\n                                                    *bndry_equation_systems,\n                                                    iteration_num / viz_dump_interval + 1,\n                                                    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        }\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", "meta": {"hexsha": "6a1b67515afb1887ddd421adea6dd445e1c78c45", "size": 25230, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/IBFE/explicit/ex9/example.cpp", "max_stars_repo_name": "kkeonho/IBAMR", "max_stars_repo_head_hexsha": "50d5c37d8f2952abc21f05ab224f22003d23d6e7", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/ex9/example.cpp", "max_issues_repo_name": "kkeonho/IBAMR", "max_issues_repo_head_hexsha": "50d5c37d8f2952abc21f05ab224f22003d23d6e7", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/IBFE/explicit/ex9/example.cpp", "max_forks_repo_name": "kkeonho/IBAMR", "max_forks_repo_head_hexsha": "50d5c37d8f2952abc21f05ab224f22003d23d6e7", "max_forks_repo_licenses": ["BSD-3-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.5141242938, "max_line_length": 118, "alphanum_fraction": 0.5859294491, "num_tokens": 5394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.6370307806984445, "lm_q1q2_score": 0.47905515695725026}}
{"text": "#include <pybind11/pybind11.h>\n#include <pybind11/stl.h>\n#include <pybind11/numpy.h>\n#include <vector>\n#include<list>\n\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <boost/property_map/property_map.hpp>\nusing namespace boost;\nnamespace py = pybind11;\n\n// supports DELOCX and DELOCY without copying matrix A\n// \"Serializes\" a map. That means, giving an index for every pixel.\n// For example: [0123]\n// \t\t\t\t[4567]\n#define LOC(y,x,Arows) ((y)*(Arows+1)+(x))\n// Deserialising. Returns the x or y coordinate for a given index.\n#define DELOCY(i,Arows) ((i)/(Arows+1))\n#define DELOCX(i,Arows) ((i)%(Arows+1))\n\n\n// Typedefs for graph_t, vertex_descriptor, edge_descriptor, Edge,\n// and out_edge_iterator.\ntypedef adjacency_list < listS, vecS, directedS,\n    no_property, property < edge_weight_t, double > > graph_t;\ntypedef graph_traits < graph_t >::vertex_descriptor vertex_descriptor;\ntypedef graph_traits < graph_t >::edge_descriptor edge_descriptor;\ntypedef std::pair<int, int> Edge;\ntypedef graph_traits < graph_t >::out_edge_iterator out_edge_iterator;\n\n\n/*\n  Global state, needs mlock!\n*/\n\n\nstruct tState\n{\n    graph_t g;\t\t\t\t\t\t                        // the graph\n    property_map<graph_t, edge_weight_t>::type weightmap;   // the weights\n    std::vector<vertex_descriptor> p;\t\t                // predecessor map\n    std::vector<double> d;\t\t\t\t                    // distance map\n    vertex_descriptor global_s;\t\t\t\t      // cache the start of dijkstra\n    int Arows;\n} ;\n\n// The graph\n\nstd::vector<tState> gState; \n\nint py_graphFromBitmap(py::array_t<uint8_t> pyo_image, uint8_t walkable=0)\n{\n    auto A  = pyo_image.mutable_unchecked<2>(); \n    tState state;\n\n\t// Create a matrix from the bitmap and store the number of rows for LOC/DELOC\n    state.Arows = A.shape(0);\n    std::cout << \"Rows:\" << state.Arows << \", Columns: \" << A.shape(1) << \"\\n\";\n    \n    // prepare the graph and search\n    // This is the full graph. All points are vertices\n    // hence, some vertices are disconnected and make their\n    // own connected component, e.g., black pixels\n    graph_t _g(A.shape(0)*A.shape(1));\n    state.g = _g;\n    // Define macro to check, whether an edge can be added from\n    // i,j to i+k, j+l\n    auto CHECK_EDGE = [&](int i,int j,int k,int l) { return (\n\ti+k >= 0 && i+k < A.shape(0) && \n\tj+l >= 0 && j+l < A.shape(1) &&\n\tA(i,j) == walkable &&\n\tA(i+k,j+l) == walkable );};\n\n\t// Iterate through the map and add edges, if possible\n    int e=0;\n    for (int i=0; i< A.shape(0); i++) {\n        for (int j=0; j< A.shape(1); j++) {\n            // NOTE!!!\n            // left      0 -1\n            // right     0  1\n            // up       -1  0\n            // down      1  0\n            if (CHECK_EDGE(i,j,-1,0))\n                add_edge(LOC(i,j,state.Arows),LOC(i-1,j,state.Arows),1,state.g);\n            if (CHECK_EDGE(i,j,+1,0))\n                add_edge(LOC(i,j,state.Arows),LOC(i+1,j,state.Arows),1,state.g);\n            if (CHECK_EDGE(i,j,0,-1))\n                add_edge(LOC(i,j,state.Arows),LOC(i,j-1,state.Arows),1,state.g);\n            if (CHECK_EDGE(i,j,0,1))\n                add_edge(LOC(i,j,state.Arows),LOC(i,j+1,state.Arows),1,state.g);\n            // DIAGONALS\n            if (CHECK_EDGE(i,j,-1,-1))\n                add_edge(LOC(i,j,state.Arows),LOC(i-1,j-1,state.Arows),sqrt(2),state.g);\n            if (CHECK_EDGE(i,j,-1,1))\n                add_edge(LOC(i,j,state.Arows),LOC(i-1,j+1,state.Arows),sqrt(2),state.g);\n            if (CHECK_EDGE(i,j,1,-1))\n                add_edge(LOC(i,j,state.Arows),LOC(i+1,j-1,state.Arows),sqrt(2),state.g);\n            if (CHECK_EDGE(i,j,1,1))\n                add_edge(LOC(i,j,state.Arows),LOC(i+1,j+1,state.Arows),sqrt(2),state.g);\n        }\n    }\n    \n    std::cout << \"Added \" << num_vertices(state.g) << \" vertices and \"\n\t\t\t\t  << num_edges(state.g)<<\" edges.\\n\";\n\t\t\t\t  \t\n\t// Store the state\n    gState.push_back(state);\n    int index = gState.size()-1;\n    std::cout << \"State is \" << index << std::endl;\n    return index;\n\n}\n\n\n\n\n\n// -------------\n// pure C++ code\n// -------------\n\nstd::vector<int> multiply(const std::vector<double>& input)\n{\n  std::vector<int> output(input.size());\n\n  for ( size_t i = 0 ; i < input.size() ; ++i )\n    output[i] = 10*static_cast<int>(input[i]);\n\n  return output;\n}\n\n// ----------------\n// Python interface\n// ----------------\n\n\nstruct predicate_violated {};\n/*This function actually performs our homotopy test*/\nbool py_empty(py::array_t<uint8_t> pyo_image, py::array_t<double> pyo_points, uint8_t allowed=0)\n{\n    auto image  = pyo_image.mutable_unchecked<2>(); \n    auto points = pyo_points.unchecked<2>();\n\n    const int polyCorners = points.shape(0);\n    std::vector<double> nodeX;\n    nodeX.reserve(polyCorners);\n    try {\n    for (size_t pixelY=0; pixelY < image.shape(1); pixelY++)\n    {\n\tint i,j;\n    \n    auto polyX = [&](int row) {return points(row,0);};\n    auto polyY = [&](int row) {return points(row,1);};\n    \n\tnodeX.clear(); j=polyCorners-1;\n\tfor (i=0; i<polyCorners; i++)\n\t{\n\t    if (polyY(i)<(double) pixelY && polyY(j)>=(double) pixelY\n\t\t||  polyY(j)<(double) pixelY && polyY(i)>=(double) pixelY)\n\t    {\n\t\tnodeX.push_back( (polyX(i)+(pixelY-polyY(i))/(polyY(j)-polyY(i))*(polyX(j)-polyX(i))));\n\t   }\n\t  j=i;\n    } // for i ranging polyCorners\n    std::sort(nodeX.begin(), nodeX.end());\n\n    const auto IMAGE_LEFT=0;\n    const auto IMAGE_RIGHT = image.shape(1);\n    \n     for (i=0; i<nodeX.size(); i+=2) {\n\tif   (nodeX[i  ]>=IMAGE_RIGHT) break;\n\t\n\tif   (nodeX[i+1]> IMAGE_LEFT ) {\n\t  if (nodeX[i  ]< IMAGE_LEFT ) nodeX[i  ]=IMAGE_LEFT ;\n\t  if (nodeX[i+1]> IMAGE_RIGHT) nodeX[i+1]=IMAGE_RIGHT;\n\t  for (auto pixelX=(int)nodeX[i]; pixelX<=(int) (nodeX[i+1]+0.5); pixelX++)\n\t      if (image(pixelX,pixelY) != allowed)\n\t         throw(predicate_violated());\n\t  }\n\t  }\n   } // for y\n   }catch(predicate_violated v)\n    {\n    return false;\n\n   }\n   return true;\n\n }\n\n\nvoid py_dijkstra(int handle, py::array_t<uint32_t> pyo_p)\n{\n    tState *state = &gState[handle];  // @TODO: bound check? else crash\n    auto p = pyo_p.unchecked<1>();\n    \n    vertex_descriptor s = LOC(p(0),p(1),state->Arows);\n    state->global_s = s;\n    \n    std::cout << \"Search: \" << s << \"\\n\"; \n    std::cout << \"Using \" << num_vertices(state->g) << \" vertices and \"\n\t\t\t\t  << num_edges(state->g) << \" edges.\\n\";\n    state->weightmap = get(edge_weight, state->g);\t// weightmap\n    state->p.resize(num_vertices(state->g));\t\t// predecessor\n    state->d.resize(num_vertices(state->g));\t\t// distances\n\n\t// Perform dijkstra\n    dijkstra_shortest_paths(state->g, s,\n\t\tpredecessor_map(boost::make_iterator_property_map(state->p.begin(), get(boost::vertex_index, state->g))).\n\t\tdistance_map(boost::make_iterator_property_map(state->d.begin(), get(boost::vertex_index, state->g))));\n    std::cout << \"Did it \" << std::endl;\n}\n\n\npy::array_t<uint32_t> py_getpath(int handle, py::array_t<uint32_t> pyo_p, double penalty=1.0)\n{\n    tState *state = &gState[handle];  // @TODO: bound check? else crash\n    auto p = pyo_p.unchecked<1>();\n    \n    vertex_descriptor e = LOC(p(0),p(1),state->Arows);\n    if (state->p[e] == e) { // no path found\n\t  return (py::array_t<uint32_t>(0));\n    }\n    // Get the shortest path from s to e\n\n\n    std::list<vertex_descriptor> shortest_path;\n    for(vertex_descriptor v = e;;v=state->p[v] ) {\n        shortest_path.push_front(v);\n        if ( penalty != 1) {\n\t\t\tedge_descriptor e1; bool found;\n\t\t\ttie(e1, found) = edge(state->p[v], v, state->g);\n\t\t\tif(found) {\n//\t\t\t\toctave_stdout << e1 << \" : \" << get(state->weightmap, e1);\n\t\t\t\tput(state->weightmap, e1, get(state->weightmap, e1)*2);\n//\t\t\t\toctave_stdout << \" -> \" << get(state->weightmap, e1) << \"\\n\";\n\t\t\t}\n\t\t}\n        if(state->p[v] == v)\n            break;\n    }    \n// allocate py::array (to pass the result of the C++ function to Python)\n  // correctly transfer with a capsule\n  uint32_t *result_ptr = new uint32_t[shortest_path.size()*2];\n  uint32_t *ptr = result_ptr;\n  for(const auto pt:shortest_path) {\n        *ptr++ =  DELOCY(pt,state->Arows);\n        *ptr++  = DELOCX(pt,state->Arows);\n    }\n\n      py::capsule free_when_done(result_ptr, [](void *f) {\n            uint32_t *foo = reinterpret_cast<uint32_t *>(f);\n            //std::cerr << \"Element [0] = \" << foo[0] << \"\\n\";\n            //std::cerr << \"freeing memory @ \" << f << \"\\n\";\n            delete[] foo;\n        });\n\n   return py::array_t<uint32_t>(\n            shortest_path.size()*2, result_ptr,free_when_done); // numpy array references this parent\n }\n\n\n \n\nvoid py_getweights(int handle, py::array_t<double> pyo_image)\n{\n    auto weights  = pyo_image.mutable_unchecked<2>(); \n    tState *state = &gState[handle];  // @TODO: bound check? else crash\n    \n    for (auto r =0; r < weights.shape(0); r++)\n      for (auto c = 0; c < weights.shape(1); c++)\n      {\n\t  vertex_descriptor v = LOC(r,c,state->Arows);\n\t  out_edge_iterator out_i, out_end;\n\t  edge_descriptor e;\n\t  double sum = 0;\n\t  double N = 0;\n\t  for (tie(out_i, out_end) = out_edges(v, state->g); out_i != out_end; ++out_i)\n\t  {\n\t\t\tsum += get(state->weightmap, *out_i);\n\t\t\tN++;\n\t  }\n\t  weights(r,c) = (N==0)?0:sum/N;\n      }\n}\n/*This function is for debugging, but it is not needed*/\n\n\nvoid py_fill(py::array_t<uint8_t> pyo_image, py::array_t<double> pyo_points)\n{\n    auto image  = pyo_image.mutable_unchecked<2>(); \n    auto points = pyo_points.unchecked<2>();\n\n    const int polyCorners = points.shape(0);\n    std::vector<double> nodeX;\n    nodeX.reserve(polyCorners);\n    \n    for (size_t pixelY=0; pixelY < image.shape(1); pixelY++)\n    {\n//\tstd::cout << \"scanning \" << pixelY << std::endl;\n    int nodes = 0; int i,j;\n\n    \n    auto polyX = [&](int row) {return points(row,0);};\n    auto polyY = [&](int row) {return points(row,1);};\n    \n\tnodeX.clear(); j=polyCorners-1;\n\tfor (i=0; i<polyCorners; i++)\n\t{\n\t    if (polyY(i)<(double) pixelY && polyY(j)>=(double) pixelY\n\t\t||  polyY(j)<(double) pixelY && polyY(i)>=(double) pixelY)\n\t    {\n\t\tnodeX.push_back( (polyX(i)+(pixelY-polyY(i))/(polyY(j)-polyY(i))*(polyX(j)-polyX(i))));\n\t   }\n\t  j=i;\n\t  // now we have the X of the scanline\n    } // for i ranging polyCorners\n    std::sort(nodeX.begin(), nodeX.end());\n    //std::cout << \"On Scanline \" << pixelY << \" we have \" << std::endl;\n  //  Fill the pixels between node pairs.\n\n    const auto IMAGE_LEFT=0;\n    const auto IMAGE_RIGHT = image.shape(1);\n    \n    \n     for (i=0; i<nodeX.size(); i+=2) {\n\tif   (nodeX[i  ]>=IMAGE_RIGHT) break;\n\t\n\tif   (nodeX[i+1]> IMAGE_LEFT ) {\n\t  if (nodeX[i  ]< IMAGE_LEFT ) nodeX[i  ]=IMAGE_LEFT ;\n\t  if (nodeX[i+1]> IMAGE_RIGHT) nodeX[i+1]=IMAGE_RIGHT;\n\t  for (auto pixelX=(int)nodeX[i]; pixelX<=(int) (nodeX[i+1]+0.5); pixelX++)\n\t      image(pixelX,pixelY) = 1;\n\t  }\n\t  }\n\n\n\n    \n    } // for y\n\n\n    \n}\n\n\n\n/*// wrap C++ function with NumPy array IO\npy::array_t<int> py_multiply(py::array_t<double, py::array::c_style | py::array::forcecast> array)\n{\n  // allocate std::vector (to pass to the C++ function)\n  std::vector<double> array_vec(array.size());\n\n  // copy py::array -> std::vector\n  std::memcpy(array_vec.data(),array.data(),array.size()*sizeof(double));\n\n  // call pure C++ function\n  std::vector<int> result_vec = multiply(array_vec);\n\n  // allocate py::array (to pass the result of the C++ function to Python)\n  auto result        = py::array_t<int>(array.size());\n  auto result_buffer = result.request();\n  int *result_ptr    = (int *) result_buffer.ptr;\n\n  // copy std::vector -> py::array\n  std::memcpy(result_ptr,result_vec.data(),result_vec.size()*sizeof(int));\n\n  return result;\n  }\n  */ \n\n// wrap as Python module\nPYBIND11_MODULE(cfsrouting,m)\n{\n  m.doc() = \"pybind11 example plugin\";\n\n//  m.def(\"multiply\", &py_multiply, \"Convert all entries of an 1-D NumPy-array to int and multiply by 10\");\n//  m.def(\"test\", &py_multiply, \"Convert all entries of an 1-D NumPy-array to int and multiply by 10\");\n  m.def (\"fill\", &py_fill,py::arg().noconvert(), py::arg().none());\n  m.def(\"empty\", &py_empty);\n  m.def(\"graphFromBitmap\", &py_graphFromBitmap);\n  m.def(\"dijkstra\", &py_dijkstra);\n  m.def(\"getpath\", &py_getpath);\n  m.def(\"getweights\", &py_getweights, py::arg().noconvert(),py::arg().noconvert());\n}\n\n\n/*template<typename vtype>\npy::array wrap(vtype v)\n{\n   return py::array(v.size(),v.data()); // does a copy\n}\n\n\nPYBIND11_MODULE(spatialfacet,m) {\n    py::class_<SpatialFacetMiner>(m, \"SpatialFacetMiner\")\n    .def(py::init<>())\n    .def(\"add_database\", &SpatialFacetMiner::add_database)\n    .def(\"query\", [](SpatialFacetMiner &m,std::string query_string, int first, int max, int check_at_least){return m.query(query_string,first,max,check_at_least, false);})\n    .def(\"query_with_data\", [](SpatialFacetMiner &m,std::string query_string, int first, int max, int check_at_least){return m.query(query_string,first,max,check_at_least, true);})\n    .def(\"getSpyData\", [](SpatialFacetMiner &m){\n\tauto &spy = m.getSpy();\n\treturn py::make_tuple(\n\t    wrap(spy.coords[0]),\n\t    wrap(spy.coords[1]),\n\t    wrap(spy.docids),\n\t    wrap(spy.weights)\n\t );\n\t })\n   .def(\"getSpyStringData\",[](SpatialFacetMiner &m){\n      auto &spy = m.getSpy();\n      return py::make_tuple(spy.value1, spy.values);\n\n      })\n\n    .def (\"augment\",[](SpatialFacetMiner &m, std::string query_string,\n\t\t       py::array_t<double, py::array::c_style | py::array::forcecast> documents,\n\t\t       int n_terms)\n    {\n\t    std::vector<int> stl_documents;\n\t    auto r = documents.unchecked<1>();\n\t    for (py::ssize_t i =0; i < r.shape(0); i++)\n\t      stl_documents.push_back(r(i));\n\t    \n\t    std::vector<string> terms; std::vector<double> weights; std::string query_out;\t    \n//    void augment_query_from_documents(std::string query_string, std::vector<int> documents, int n_terms,\n//\t\t\t\t      std::vector<std::string> &terms, std::vector<double> &weights, std::string &query_out)\n\t    \n\t    m.augment_query_from_documents(query_string, stl_documents,n_terms, terms, weights, query_out);\n\t   return py::make_tuple(terms, weights, query_out);\n\t    \n    });\n\n\n\n      ;\n    \n}\n*/\n", "meta": {"hexsha": "5c2d2a075cc666e927d2dca720a9012f4a410caa", "size": 14068, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/module.cpp", "max_stars_repo_name": "tumbgd/cfsrouting", "max_stars_repo_head_hexsha": "94416947c744f81af3e23cba336ecae22bb6090a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/module.cpp", "max_issues_repo_name": "tumbgd/cfsrouting", "max_issues_repo_head_hexsha": "94416947c744f81af3e23cba336ecae22bb6090a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/module.cpp", "max_forks_repo_name": "tumbgd/cfsrouting", "max_forks_repo_head_hexsha": "94416947c744f81af3e23cba336ecae22bb6090a", "max_forks_repo_licenses": ["Apache-2.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.8280542986, "max_line_length": 180, "alphanum_fraction": 0.6077622974, "num_tokens": 4189, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125626441471, "lm_q2_score": 0.6370307875894138, "lm_q1q2_score": 0.47905515505833435}}
{"text": "#if defined (_MSC_VER) && !defined (_WIN64)\n#pragma warning(disable:4244) // boost::number_distance::distance()\n                              // converts 64 to 32 bits integers\n#endif\n\n#include <cstdlib>\n#include <fstream>\n#include <iostream>\n#include <string>\n\n#include <boost/function_output_iterator.hpp>\n\n#include <CGAL/Simple_cartesian.h>\n#include <CGAL/Classification.h>\n#include <CGAL/Point_set_3.h>\n#include <CGAL/Point_set_3/IO.h>\n#include <CGAL/jet_estimate_normals.h>\n#include <CGAL/Shape_detection/Region_growing.h>\n#include <CGAL/Real_timer.h>\n\n#ifdef CGAL_LINKED_WITH_TBB\ntypedef CGAL::Parallel_tag   Concurrency_tag;\n#else\ntypedef CGAL::Sequential_tag Concurrency_tag;\n#endif\n\ntypedef CGAL::Simple_cartesian<double> Kernel;\ntypedef Kernel::Point_3                Point;\ntypedef Kernel::Iso_cuboid_3           Iso_cuboid_3;\n\ntypedef CGAL::Point_set_3<Point> Point_set;\n\ntypedef Point_set::Point_map                   Pmap;\ntypedef Point_set::Vector_map                  Vmap;\ntypedef Point_set::Property_map<int>           Imap;\ntypedef Point_set::Property_map<unsigned char> UCmap;\n\n\ntypedef CGAL::Shape_detection::Point_set::Sphere_neighbor_query<Kernel, Point_set, Pmap>                Neighbor_query;\ntypedef CGAL::Shape_detection::Point_set::Least_squares_plane_fit_region<Kernel, Point_set, Pmap, Vmap> Region_type;\ntypedef CGAL::Shape_detection::Region_growing<Point_set, Neighbor_query, Region_type>                   Region_growing;\n\nnamespace Classification = CGAL::Classification;\n\ntypedef Classification::Label_handle   Label_handle;\ntypedef Classification::Feature_handle Feature_handle;\ntypedef Classification::Label_set      Label_set;\ntypedef Classification::Feature_set    Feature_set;\n\ntypedef Classification::Local_eigen_analysis                                 Local_eigen_analysis;\ntypedef Classification::Point_set_feature_generator<Kernel, Point_set, Pmap> Feature_generator;\ntypedef Classification::Cluster<Point_set, Pmap>                             Cluster;\n\nint main (int argc, char** argv)\n{\n  std::string filename        = \"data/b9.ply\";\n  std::string filename_config = \"data/b9_clusters_config.gz\";\n  \n  if (argc > 1)\n    filename = argv[1];\n  if (argc > 2)\n    filename_config = argv[2];\n\n  std::ifstream in (filename.c_str(), std::ios::binary);\n  Point_set pts;\n\n  std::cerr << \"Reading input\" << std::endl;\n  in >> pts;\n\n  std::cerr << \"Estimating normals\" << std::endl;\n  CGAL::Real_timer t;\n  t.start();\n  pts.add_normal_map();\n  CGAL::jet_estimate_normals<Concurrency_tag> (pts, 12);\n  t.stop();\n  std::cerr << \"Done in \" << t.time() << \" second(s)\" << std::endl;\n  t.reset();\n\n  Feature_set pointwise_features;\n  \n  std::cerr << \"Generating pointwise features\" << std::endl;\n  t.start();\n  Feature_generator generator (pts, pts.point_map(), 5); // using 5 scales\n  \n#ifdef CGAL_LINKED_WITH_TBB\n  pointwise_features.begin_parallel_additions();\n#endif\n  \n  generator.generate_point_based_features (pointwise_features);\n  generator.generate_normal_based_features (pointwise_features, pts.normal_map());\n\n#ifdef CGAL_LINKED_WITH_TBB\n  pointwise_features.end_parallel_additions();\n#endif\n  \n  t.stop();\n  std::cerr << \"Done in \" << t.time() << \" second(s)\" << std::endl;\n\n  ///////////////////////////////////////////////////////////////////\n  //! [Cluster]\n  \n  std::cerr << \"Detecting planes and creating clusters\" << std::endl;\n  t.start();\n  \n  const double search_sphere_radius  = 1.0;\n  const double max_distance_to_plane = 1.0;\n  const double max_accepted_angle    = 25.0;\n  const std::size_t min_region_size  = 10;\n\n  Neighbor_query neighbor_query (\n    pts, \n    search_sphere_radius, \n    pts.point_map());\n  Region_type region_type (\n    pts, \n    max_distance_to_plane, max_accepted_angle, min_region_size,\n    pts.point_map(), pts.normal_map());\n  Region_growing region_growing (\n    pts, neighbor_query, region_type);\n\n  std::vector<Cluster> clusters;\n  region_growing.detect\n    (boost::make_function_output_iterator\n     ([&](const std::vector<std::size_t>& region) -> void {\n        \n        // Create a new cluster.\n        Classification::Cluster<Point_set, Pmap> cluster (pts, pts.point_map());\n        for (const std::size_t idx : region) \n          cluster.insert(idx);\n        clusters.push_back(cluster);\n      }));\n\n  t.stop();\n  std::cerr << clusters.size() << \" clusters created in \"\n            << t.time() << \" second(s)\" << std::endl;\n  t.reset();\n\n  //! [Cluster]\n  ///////////////////////////////////////////////////////////////////\n  \n  std::cerr << \"Computing cluster features\" << std::endl;\n  \n  ///////////////////////////////////////////////////////////////////\n  //! [Eigen]\n  \n  Local_eigen_analysis eigen = Local_eigen_analysis::create_from_point_clusters (clusters);\n\n  //! [Eigen]\n  ///////////////////////////////////////////////////////////////////\n\n  t.start();\n  \n  ///////////////////////////////////////////////////////////////////\n  //! [Features]\n  \n  Feature_set features;\n  \n#ifdef CGAL_LINKED_WITH_TBB\n  features.begin_parallel_additions();\n#endif\n\n  // First, compute means of features.\n  for (std::size_t i = 0; i < pointwise_features.size(); ++ i)\n    features.add<Classification::Feature::Cluster_mean_of_feature> (clusters, pointwise_features[i]);\n\n#ifdef CGAL_LINKED_WITH_TBB\n  features.end_parallel_additions();\n  features.begin_parallel_additions();\n#endif\n\n  // Then, compute variances of features (and remaining cluster features).\n  for (std::size_t i = 0; i < pointwise_features.size(); ++ i)\n    features.add<Classification::Feature::Cluster_variance_of_feature> (clusters,\n                                                                        pointwise_features[i], // i^th feature\n                                                                        features[i]);          // mean of i^th feature\n\n  features.add<Classification::Feature::Cluster_size> (clusters);\n  features.add<Classification::Feature::Cluster_vertical_extent> (clusters);\n  \n  for (std::size_t i = 0; i < 3; ++ i)\n    features.add<Classification::Feature::Eigenvalue> (clusters, eigen, (unsigned int)(i));\n  \n#ifdef CGAL_LINKED_WITH_TBB\n  features.end_parallel_additions();\n#endif\n  \n  //! [Features]\n  ///////////////////////////////////////////////////////////////////\n  \n  t.stop();\n  \n  // Add types.\n  Label_set labels;\n  Label_handle ground     = labels.add (\"ground\");\n  Label_handle vegetation = labels.add (\"vegetation\");\n  Label_handle roof       = labels.add (\"roof\");\n\n  std::vector<int> label_indices(clusters.size(), -1);\n  \n  std::cerr << \"Using ETHZ Random Forest Classifier\" << std::endl;\n  Classification::ETHZ_random_forest_classifier classifier (labels, features);\n  \n  std::cerr << \"Loading configuration\" << std::endl;\n  std::ifstream in_config (filename_config, std::ios_base::in | std::ios_base::binary);\n  classifier.load_configuration (in_config);\n\n  std::cerr << \"Classifying\" << std::endl;\n  t.reset();\n  t.start();\n  Classification::classify<Concurrency_tag> (clusters, labels, classifier, label_indices);\n  t.stop();\n  \n  std::cerr << \"Classification done in \" << t.time() << \" second(s)\" << std::endl;\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "e4ff944803a31aeebcdec9cdc42011c7948b1f6e", "size": 7146, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CoreSystem/lib/CGAL/examples/Classification/example_cluster_classification.cpp", "max_stars_repo_name": "josuehfa/DAASystem", "max_stars_repo_head_hexsha": "a1fe61ffc19f0781eeeddcd589137eefde078a45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-17T01:13:02.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-17T01:13:02.000Z", "max_issues_repo_path": "CoreSystem/lib/CGAL/examples/Classification/example_cluster_classification.cpp", "max_issues_repo_name": "josuehfa/DAASystem", "max_issues_repo_head_hexsha": "a1fe61ffc19f0781eeeddcd589137eefde078a45", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CoreSystem/lib/CGAL/examples/Classification/example_cluster_classification.cpp", "max_forks_repo_name": "josuehfa/DAASystem", "max_forks_repo_head_hexsha": "a1fe61ffc19f0781eeeddcd589137eefde078a45", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-02T11:11:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-02T11:11:36.000Z", "avg_line_length": 33.0833333333, "max_line_length": 119, "alphanum_fraction": 0.6397984887, "num_tokens": 1638, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795402, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.47903947997842444}}
{"text": "/*\n * Copyright 2012-2019 CNRS-UM LIRMM, CNRS-AIST JRL\n */\n\n// associated header\n#include \"Tasks/QPContacts.h\"\n\n// includes\n// std\n#include <stdexcept>\n\n// Eigen\n#include <Eigen/Geometry>\n\n// boost\n#include <boost/math/constants/constants.hpp>\n\nnamespace tasks\n{\n\nnamespace qp\n{\n\n/// @throw std::domain_error if points is not a valid points index.\nvoid checkRange(int point, const std::vector<Eigen::Vector3d> & points)\n{\n  if(point < 0 || point >= static_cast<int>(points.size()))\n  {\n    std::ostringstream str;\n    str << \"invalid point index: must be in the range [0,\" << points.size() << \"[\";\n    throw std::domain_error(str.str());\n  }\n}\n\n/**\n *\t\t\t\t\t\t\t\t\t\t\t\t\tFrictionCone\n */\n\nFrictionCone::FrictionCone(const Eigen::Matrix3d & frame, int nrGen, double mu, double dir) : generators(nrGen)\n{\n  Eigen::Vector3d normal(frame.row(2));\n  Eigen::Vector3d tan(dir * frame.row(0));\n  double angle = std::atan(mu);\n\n  Eigen::Vector3d gen = Eigen::AngleAxisd(angle, tan) * normal;\n  double step = (boost::math::constants::pi<double>() * 2.) / nrGen;\n\n  for(int i = 0; i < nrGen; ++i)\n  {\n    generators[i] = Eigen::AngleAxisd(dir * step * i, normal) * gen;\n  }\n}\n\n/**\n *\t\t\t\t\t\t\t\t\t\t\t\t\tContactId\n */\n\nContactId::ContactId() : r1Index(-1), r2Index(-1), r1BodyName(\"\"), r2BodyName(\"\"), ambiguityId(-1) {}\n\nContactId::ContactId(int r1I, int r2I, const std::string & r1BName, const std::string & r2BName, int ambId)\n: r1Index(r1I), r2Index(r2I), r1BodyName(r1BName), r2BodyName(r2BName), ambiguityId(ambId)\n{\n}\n\nbool ContactId::operator==(const ContactId & cId) const\n{\n  return r1Index == cId.r1Index && r2Index == cId.r2Index && r1BodyName == cId.r1BodyName\n         && r2BodyName == cId.r2BodyName && ambiguityId == cId.ambiguityId;\n}\n\nbool ContactId::operator!=(const ContactId & cId) const\n{\n  return !((*this) == cId);\n}\n\nbool ContactId::operator<(const ContactId & cId) const\n{\n  return r1Index < cId.r1Index || (r1Index == cId.r1Index && r1BodyName < cId.r1BodyName)\n         || (r1Index == cId.r1Index && r1BodyName == cId.r1BodyName && r2Index < cId.r2Index)\n         || (r1Index == cId.r1Index && r1BodyName == cId.r1BodyName && r2Index == cId.r2Index\n             && r2BodyName < cId.r2BodyName)\n         || (r1Index == cId.r1Index && r1BodyName == cId.r1BodyName && r2Index == cId.r2Index\n             && r2BodyName == cId.r2BodyName && ambiguityId < cId.ambiguityId);\n}\n\n/**\n *\t\t\t\t\t\t\t\t\t\t\t\t\tUnilateralContact\n */\n\nUnilateralContact::UnilateralContact(int r1I,\n                                     int r2I,\n                                     const std::string & r1BName,\n                                     const std::string & r2BName,\n                                     std::vector<Eigen::Vector3d> r1P,\n                                     const Eigen::Matrix3d & r1Frame,\n                                     const sva::PTransformd & Xbb,\n                                     int nrGen,\n                                     double mu,\n                                     const sva::PTransformd & Xbcf)\n: contactId(r1I, r2I, r1BName, r2BName), r1Points(std::move(r1P)), r2Points(), r1Cone(r1Frame, nrGen, mu), r2Cone(),\n  X_b1_b2(Xbb), X_b1_cf(Xbcf)\n{\n  construct(r1Frame, nrGen, mu);\n}\n\nUnilateralContact::UnilateralContact(int r1I,\n                                     int r2I,\n                                     const std::string & r1BName,\n                                     const std::string & r2BName,\n                                     int ambId,\n                                     std::vector<Eigen::Vector3d> r1P,\n                                     const Eigen::Matrix3d & r1Frame,\n                                     const sva::PTransformd & Xbb,\n                                     int nrGen,\n                                     double mu,\n                                     const sva::PTransformd & Xbcf)\n: contactId(r1I, r2I, r1BName, r2BName, ambId), r1Points(std::move(r1P)), r2Points(), r1Cone(r1Frame, nrGen, mu),\n  r2Cone(), X_b1_b2(Xbb), X_b1_cf(Xbcf)\n{\n  construct(r1Frame, nrGen, mu);\n}\n\nUnilateralContact::UnilateralContact(const ContactId & cId,\n                                     std::vector<Eigen::Vector3d> r1P,\n                                     const Eigen::Matrix3d & r1Frame,\n                                     const sva::PTransformd & Xbb,\n                                     int nrGen,\n                                     double mu,\n                                     const sva::PTransformd & Xbcf)\n: contactId(cId), r1Points(std::move(r1P)), r2Points(), r1Cone(r1Frame, nrGen, mu), r2Cone(), X_b1_b2(Xbb),\n  X_b1_cf(Xbcf)\n{\n  construct(r1Frame, nrGen, mu);\n}\n\nEigen::Vector3d UnilateralContact::force(const Eigen::VectorXd & lambda,\n                                         int /* point */,\n                                         const FrictionCone & cone) const\n{\n  Eigen::Vector3d F(Eigen::Vector3d::Zero());\n\n  for(std::size_t i = 0; i < cone.generators.size(); ++i)\n  {\n    F += cone.generators[i] * lambda(i);\n  }\n\n  return F;\n}\n\nEigen::Vector3d UnilateralContact::force(const Eigen::VectorXd & lambda, const FrictionCone & cone) const\n{\n  Eigen::Vector3d F(Eigen::Vector3d::Zero());\n  int pos = 0;\n\n  for(int i = 0; i < int(r1Points.size()); ++i)\n  {\n    F += force(lambda.segment(pos, nrLambda(i)), i, cone);\n    pos += nrLambda(i);\n  }\n\n  return F;\n}\n\nsva::ForceVecd UnilateralContact::force(const Eigen::VectorXd & lambda,\n                                        const std::vector<Eigen::Vector3d> & p,\n                                        const FrictionCone & c) const\n{\n  sva::ForceVecd F_b(Eigen::Vector6d::Zero());\n  int pos = 0;\n\n  for(int i = 0; i < int(p.size()); ++i)\n  {\n    // force at point p in frame b\n    sva::ForceVecd F_p_b(Eigen::Vector3d::Zero(), force(lambda.segment(pos, nrLambda(i)), i, c));\n    // F_b += xlt(r_b_p)^T F_p_b\n    F_b += sva::PTransformd(p[i]).transMul(F_p_b);\n    pos += nrLambda(i);\n  }\n\n  return F_b;\n}\n\nint UnilateralContact::nrLambda(int /* point */) const\n{\n  return static_cast<int>(r1Cone.generators.size());\n}\n\nint UnilateralContact::nrLambda() const\n{\n  int totalLambda = 0;\n  for(int i = 0; i < int(r1Points.size()); ++i)\n  {\n    totalLambda += nrLambda(i);\n  }\n  return totalLambda;\n}\n\nEigen::Vector3d UnilateralContact::sForce(const Eigen::VectorXd & lambda, int point, const FrictionCone & cone) const\n{\n  checkRange(point, r1Points);\n  if(static_cast<int>(lambda.rows()) != nrLambda(point))\n  {\n    std::ostringstream str;\n    str << \"number of lambda and generator mismatch: expected (\" << nrLambda(point) << \") gived (\" << lambda.rows()\n        << \")\";\n    throw std::domain_error(str.str());\n  }\n\n  return force(lambda, point, cone);\n}\n\nEigen::Vector3d UnilateralContact::sForce(const Eigen::VectorXd & lambda, const FrictionCone & cone) const\n{\n  int totalLambda = nrLambda();\n\n  if(static_cast<int>(lambda.rows()) != totalLambda)\n  {\n    std::ostringstream str;\n    str << \"number of lambda and generator mismatch: expected (\" << totalLambda << \") gived (\" << lambda.rows() << \")\";\n    throw std::domain_error(str.str());\n  }\n\n  return force(lambda, cone);\n}\n\nsva::ForceVecd UnilateralContact::sForce(const Eigen::VectorXd & lambda,\n                                         const std::vector<Eigen::Vector3d> & r_b_pi,\n                                         const FrictionCone & c_b) const\n{\n  int totalLambda = nrLambda();\n\n  if(static_cast<int>(lambda.rows()) != totalLambda)\n  {\n    std::ostringstream str;\n    str << \"number of lambda and generator mismatch: expected (\" << totalLambda << \") gived (\" << lambda.rows() << \")\";\n    throw std::domain_error(str.str());\n  }\n\n  return force(lambda, r_b_pi, c_b);\n}\n\nint UnilateralContact::sNrLambda(int point) const\n{\n  checkRange(point, r1Points);\n  return nrLambda(point);\n}\n\nvoid UnilateralContact::construct(const Eigen::MatrixXd & r1Frame, int nrGen, double mu)\n{\n  // compute points in b2 coordinate\n  r2Points.reserve(r1Points.size());\n  for(const Eigen::Vector3d & p : r1Points)\n  {\n    r2Points.push_back((sva::PTransformd(p) * X_b1_b2.inv()).translation());\n  }\n\n  // compute points frame in b2 coordinate\n  // Eigen::Matrix3d r2Frame = (X_b1_b2*sva::PTransformd(Eigen::Matrix3d(r1Frame))).rotation();\n  Eigen::Matrix3d r2Frame = (sva::PTransformd(Eigen::Matrix3d(r1Frame)) * X_b1_b2.inv()).rotation();\n\n  // create the b2 cone\n  // We take the oppostie frame because force are opposed\n  r2Cone = FrictionCone(-r2Frame, nrGen, mu, -1.);\n}\n\n/**\n *\t\t\t\t\t\t\t\t\t\t\t\t\tBilateralContact\n */\n\nBilateralContact::BilateralContact(int r1I,\n                                   int r2I,\n                                   const std::string & r1BName,\n                                   const std::string & r2BName,\n                                   std::vector<Eigen::Vector3d> r1P,\n                                   const std::vector<Eigen::Matrix3d> & r1Frames,\n                                   const sva::PTransformd & Xbb,\n                                   int nrGen,\n                                   double mu,\n                                   const sva::PTransformd & Xbcf)\n: contactId(r1I, r2I, r1BName, r2BName), r1Points(std::move(r1P)), r2Points(), r1Cones(r1Points.size()),\n  r2Cones(r1Points.size()), X_b1_b2(Xbb), X_b1_cf(Xbcf)\n{\n  construct(r1Frames, nrGen, mu);\n}\n\nBilateralContact::BilateralContact(int r1I,\n                                   int r2I,\n                                   const std::string & r1BName,\n                                   const std::string & r2BName,\n                                   int ambId,\n                                   std::vector<Eigen::Vector3d> r1P,\n                                   const std::vector<Eigen::Matrix3d> & r1Frames,\n                                   const sva::PTransformd & Xbb,\n                                   int nrGen,\n                                   double mu,\n                                   const sva::PTransformd & Xbcf)\n: contactId(r1I, r2I, r1BName, r2BName, ambId), r1Points(std::move(r1P)), r2Points(), r1Cones(r1Points.size()),\n  r2Cones(r1Points.size()), X_b1_b2(Xbb), X_b1_cf(Xbcf)\n{\n  construct(r1Frames, nrGen, mu);\n}\n\nBilateralContact::BilateralContact(const ContactId & cId,\n                                   std::vector<Eigen::Vector3d> r1P,\n                                   const std::vector<Eigen::Matrix3d> & r1Frames,\n                                   const sva::PTransformd & Xbb,\n                                   int nrGen,\n                                   double mu,\n                                   const sva::PTransformd & Xbcf)\n: contactId(cId), r1Points(std::move(r1P)), r2Points(), r1Cones(r1Points.size()), r2Cones(r1Points.size()),\n  X_b1_b2(Xbb), X_b1_cf(Xbcf)\n{\n  construct(r1Frames, nrGen, mu);\n}\n\nBilateralContact::BilateralContact(const UnilateralContact & c)\n: contactId(c.contactId), r1Points(c.r1Points), r2Points(c.r2Points), r1Cones(c.r1Points.size(), c.r1Cone),\n  r2Cones(c.r1Points.size(), c.r2Cone), X_b1_b2(c.X_b1_b2), X_b1_cf(c.X_b1_cf)\n{\n}\n\nEigen::Vector3d BilateralContact::force(const Eigen::VectorXd & lambda,\n                                        int point,\n                                        const std::vector<FrictionCone> & cones) const\n{\n  Eigen::Vector3d F(Eigen::Vector3d::Zero());\n\n  for(std::size_t i = 0; i < cones[point].generators.size(); ++i)\n  {\n    F += cones[point].generators[i] * lambda(i);\n  }\n\n  return F;\n}\n\nEigen::Vector3d BilateralContact::force(const Eigen::VectorXd & lambda, const std::vector<FrictionCone> & cones) const\n{\n  Eigen::Vector3d F(Eigen::Vector3d::Zero());\n  int pos = 0;\n\n  for(int i = 0; i < int(r1Points.size()); ++i)\n  {\n    F += force(lambda.segment(pos, nrLambda(i)), i, cones);\n    pos += nrLambda(i);\n  }\n\n  return F;\n}\n\nsva::ForceVecd BilateralContact::force(const Eigen::VectorXd & lambda,\n                                       const std::vector<Eigen::Vector3d> & p,\n                                       const std::vector<FrictionCone> & c) const\n{\n  sva::ForceVecd F_b(Eigen::Vector6d::Zero());\n  int pos = 0;\n\n  for(int i = 0; i < int(p.size()); ++i)\n  {\n    // force at point p in frame b\n    sva::ForceVecd F_p_b(Eigen::Vector3d::Zero(), force(lambda.segment(pos, nrLambda(i)), i, c));\n    // F_b += xlt(r_b_p)^T F_p_b\n    F_b += sva::PTransformd(p[i]).transMul(F_p_b);\n    pos += nrLambda(i);\n  }\n\n  return F_b;\n}\n\nint BilateralContact::nrLambda(int point) const\n{\n  return static_cast<int>(r1Cones[point].generators.size());\n}\n\nint BilateralContact::nrLambda() const\n{\n  int totalLambda = 0;\n  for(int i = 0; i < int(r1Points.size()); ++i)\n  {\n    totalLambda += nrLambda(i);\n  }\n  return totalLambda;\n}\n\nEigen::Vector3d BilateralContact::sForce(const Eigen::VectorXd & lambda,\n                                         int point,\n                                         const std::vector<FrictionCone> & cones) const\n{\n  checkRange(point, r1Points);\n  if(static_cast<int>(lambda.rows()) != nrLambda(point))\n  {\n    std::ostringstream str;\n    str << \"number of lambda and generator mismatch: expected (\" << nrLambda(point) << \") gived (\" << lambda.rows()\n        << \")\";\n    throw std::domain_error(str.str());\n  }\n\n  return force(lambda, point, cones);\n}\n\nEigen::Vector3d BilateralContact::sForce(const Eigen::VectorXd & lambda, const std::vector<FrictionCone> & cones) const\n{\n  int totalLambda = nrLambda();\n\n  if(static_cast<int>(lambda.rows()) != totalLambda)\n  {\n    std::ostringstream str;\n    str << \"number of lambda and generator mismatch: expected (\" << totalLambda << \") gived (\" << lambda.rows() << \")\";\n    throw std::domain_error(str.str());\n  }\n\n  return force(lambda, cones);\n}\n\nsva::ForceVecd BilateralContact::sForce(const Eigen::VectorXd & lambda,\n                                        const std::vector<Eigen::Vector3d> & r_b_pi,\n                                        const std::vector<FrictionCone> & c_pi_b) const\n{\n  int totalLambda = nrLambda();\n\n  if(static_cast<int>(lambda.rows()) != totalLambda)\n  {\n    std::ostringstream str;\n    str << \"number of lambda and generator mismatch: expected (\" << totalLambda << \") gived (\" << lambda.rows() << \")\";\n    throw std::domain_error(str.str());\n  }\n\n  return force(lambda, r_b_pi, c_pi_b);\n}\n\nint BilateralContact::sNrLambda(int point) const\n{\n  checkRange(point, r1Points);\n  return nrLambda(point);\n}\n\nvoid BilateralContact::construct(const std::vector<Eigen::Matrix3d> & r1Frames, int nrGen, double mu)\n{\n  assert(r1Points.size() == r1Frames.size());\n\n  r2Points.reserve(r1Points.size());\n  sva::PTransformd X_b2_b1(X_b1_b2.inv());\n  for(std::size_t i = 0; i < r1Points.size(); ++i)\n  {\n    // compute point i in b2 coordinate\n    sva::PTransformd X_b1_p(r1Frames[i], r1Points[i]);\n    sva::PTransformd X_b2_p = X_b1_p * X_b2_b1;\n    r2Points.push_back(X_b2_p.translation());\n\n    // construct r1 cone\n    r1Cones[i] = FrictionCone(r1Frames[i], nrGen, mu);\n    // create the b2 cone\n    // We take the oppostie frame because force are opposed\n    r2Cones[i] = FrictionCone(-X_b2_p.rotation(), nrGen, mu, -1.);\n  }\n}\n\n} // namespace qp\n\n} // namespace tasks\n", "meta": {"hexsha": "060a66d006782a25b343c12d556501bfc87e5ebd", "size": 15041, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/QPContacts.cpp", "max_stars_repo_name": "SaeidSamadi/Tasks", "max_stars_repo_head_hexsha": "cb3f29a5545a96df83a7d49730799c90bfb0b6f7", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 60.0, "max_stars_repo_stars_event_min_datetime": "2016-04-08T05:48:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T16:54:31.000Z", "max_issues_repo_path": "src/QPContacts.cpp", "max_issues_repo_name": "SaeidSamadi/Tasks", "max_issues_repo_head_hexsha": "cb3f29a5545a96df83a7d49730799c90bfb0b6f7", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 48.0, "max_issues_repo_issues_event_min_datetime": "2016-04-01T09:50:12.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-05T02:12:27.000Z", "max_forks_repo_path": "src/QPContacts.cpp", "max_forks_repo_name": "SaeidSamadi/Tasks", "max_forks_repo_head_hexsha": "cb3f29a5545a96df83a7d49730799c90bfb0b6f7", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 21.0, "max_forks_repo_forks_event_min_datetime": "2017-01-10T16:23:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-18T08:40:20.000Z", "avg_line_length": 32.697826087, "max_line_length": 119, "alphanum_fraction": 0.5661857589, "num_tokens": 4102, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795402, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.47903947997842433}}
{"text": "#include <CGAL/algorithm.h>\n#include <CGAL/function_objects.h>\n#include <vector>\n#include <iostream>\n#include <boost/functional.hpp>\n\n\nint main()\n{\n  std::vector< int > v;\n  v.push_back(3);\n  v.push_back(5);\n  v.push_back(2);\n  std::cout << \"min_odd = \"\n            << *CGAL::min_element_if(v.begin(),\n                                     v.end(),\n                                     [](int i){ return (i%2) > 0; })\n            << std::endl;\n  return 0;\n}\n", "meta": {"hexsha": "32e43c1abfb4b492fe36e17b3977507b574b27e2", "size": 457, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "STL_Extension/examples/STL_Extension/min_element_if_example.cpp", "max_stars_repo_name": "ffteja/cgal", "max_stars_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 3227.0, "max_stars_repo_stars_event_min_datetime": "2015-03-05T00:19:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:20:35.000Z", "max_issues_repo_path": "STL_Extension/examples/STL_Extension/min_element_if_example.cpp", "max_issues_repo_name": "ffteja/cgal", "max_issues_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 5574.0, "max_issues_repo_issues_event_min_datetime": "2015-03-05T00:01:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:08:11.000Z", "max_forks_repo_path": "STL_Extension/examples/STL_Extension/min_element_if_example.cpp", "max_forks_repo_name": "ffteja/cgal", "max_forks_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1274.0, "max_forks_repo_forks_event_min_datetime": "2015-03-05T00:01:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:47:56.000Z", "avg_line_length": 21.7619047619, "max_line_length": 68, "alphanum_fraction": 0.4901531729, "num_tokens": 119, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.4790394687384761}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2017 Adam Wulkiewicz, Lodz, Poland.\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_GEOGRAPHIC_AREA_HPP\n#define BOOST_GEOMETRY_STRATEGIES_GEOGRAPHIC_AREA_HPP\n\n\n#include <boost/geometry/srs/spheroid.hpp>\n\n#include <boost/geometry/formulas/area_formulas.hpp>\n#include <boost/geometry/formulas/authalic_radius_sqr.hpp>\n#include <boost/geometry/formulas/eccentricity_sqr.hpp>\n\n#include <boost/geometry/strategies/area.hpp>\n#include <boost/geometry/strategies/geographic/parameters.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\nnamespace strategy { namespace area\n{\n\n/*!\n\\brief Geographic area calculation\n\\ingroup strategies\n\\details Geographic area calculation by trapezoidal rule plus integral\n         approximation that gives the ellipsoidal correction\n\\tparam FormulaPolicy Formula used to calculate azimuths\n\\tparam SeriesOrder The order of approximation of the geodesic integral\n\\tparam Spheroid The spheroid model\n\\tparam CalculationType \\tparam_calculation\n\\author See\n- Danielsen JS, The area under the geodesic. Surv Rev 30(232): 61\u201366, 1989\n- Charles F.F Karney, Algorithms for geodesics, 2011 https://arxiv.org/pdf/1109.4448.pdf\n\n\\qbk{\n[heading See also]\n\\* [link geometry.reference.algorithms.area.area_2_with_strategy area (with strategy)]\n\\* [link geometry.reference.srs.srs_spheroid srs::spheroid]\n}\n*/\ntemplate\n<\n    typename FormulaPolicy = strategy::andoyer,\n    std::size_t SeriesOrder = strategy::default_order<FormulaPolicy>::value,\n    typename Spheroid = srs::spheroid<double>,\n    typename CalculationType = void\n>\nclass geographic\n{\n    // Switch between two kinds of approximation(series in eps and n v.s.series in k ^ 2 and e'^2)\n    static const bool ExpandEpsN = true;\n    // LongSegment Enables special handling of long segments\n    static const bool LongSegment = false;\n\n    //Select default types in case they are not set\n\npublic:\n    template <typename Geometry>\n    struct result_type\n        : strategy::area::detail::result_type\n            <\n                Geometry,\n                CalculationType\n            >\n    {};\n\nprotected :\n    struct spheroid_constants\n    {\n        typedef typename boost::mpl::if_c\n            <\n                boost::is_void<CalculationType>::value,\n                typename geometry::radius_type<Spheroid>::type,\n                CalculationType\n            >::type calc_t;\n\n        Spheroid m_spheroid;\n        calc_t const m_a2;  // squared equatorial radius\n        calc_t const m_e2;  // squared eccentricity\n        calc_t const m_ep2; // squared second eccentricity\n        calc_t const m_ep;  // second eccentricity\n        calc_t const m_c2;  // squared authalic radius\n\n        inline spheroid_constants(Spheroid const& spheroid)\n            : m_spheroid(spheroid)\n            , m_a2(math::sqr(get_radius<0>(spheroid)))\n            , m_e2(formula::eccentricity_sqr<calc_t>(spheroid))\n            , m_ep2(m_e2 / (calc_t(1.0) - m_e2))\n            , m_ep(math::sqrt(m_ep2))\n            , m_c2(formula_dispatch::authalic_radius_sqr\n                    <\n                        calc_t, Spheroid, srs_spheroid_tag\n                    >::apply(m_a2, m_e2))\n        {}\n    };\n\npublic:\n    template <typename Geometry>\n    class state\n    {\n        friend class geographic;\n\n        typedef typename result_type<Geometry>::type return_type;\n\n    public:\n        inline state()\n            : m_excess_sum(0)\n            , m_correction_sum(0)\n            , m_crosses_prime_meridian(0)\n        {}\n\n    private:\n        inline return_type area(spheroid_constants const& spheroid_const) const\n        {\n            return_type result;\n\n            return_type sum = spheroid_const.m_c2 * m_excess_sum\n                   + spheroid_const.m_e2 * spheroid_const.m_a2 * m_correction_sum;\n\n            // If encircles some pole\n            if (m_crosses_prime_meridian % 2 == 1)\n            {\n                std::size_t times_crosses_prime_meridian\n                        = 1 + (m_crosses_prime_meridian / 2);\n\n                result = return_type(2.0)\n                         * geometry::math::pi<return_type>()\n                         * spheroid_const.m_c2\n                         * return_type(times_crosses_prime_meridian)\n                         - geometry::math::abs(sum);\n\n                if (geometry::math::sign<return_type>(sum) == 1)\n                {\n                    result = - result;\n                }\n\n            }\n            else\n            {\n                result = sum;\n            }\n\n            return result;\n        }\n\n        return_type m_excess_sum;\n        return_type m_correction_sum;\n\n        // Keep track if encircles some pole\n        std::size_t m_crosses_prime_meridian;\n    };\n\npublic :\n    explicit inline geographic(Spheroid const& spheroid = Spheroid())\n        : m_spheroid_constants(spheroid)\n    {}\n\n    template <typename PointOfSegment, typename Geometry>\n    inline void apply(PointOfSegment const& p1,\n                      PointOfSegment const& p2,\n                      state<Geometry>& st) const\n    {\n        if (! geometry::math::equals(get<0>(p1), get<0>(p2)))\n        {\n            typedef geometry::formula::area_formulas\n                <\n                    typename result_type<Geometry>::type,\n                    SeriesOrder, ExpandEpsN\n                > area_formulas;\n\n            typename area_formulas::return_type_ellipsoidal result =\n                     area_formulas::template ellipsoidal<FormulaPolicy::template inverse>\n                                             (p1, p2, m_spheroid_constants);\n\n            st.m_excess_sum += result.spherical_term;\n            st.m_correction_sum += result.ellipsoidal_term;\n\n            // Keep track whenever a segment crosses the prime meridian\n            if (area_formulas::crosses_prime_meridian(p1, p2))\n            {\n                st.m_crosses_prime_meridian++;\n            }\n        }\n    }\n\n    template <typename Geometry>\n    inline typename result_type<Geometry>::type\n        result(state<Geometry> const& st) const\n    {\n        return st.area(m_spheroid_constants);\n    }\n\nprivate:\n    spheroid_constants m_spheroid_constants;\n\n};\n\n#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\n\nnamespace services\n{\n\n\ntemplate <>\nstruct default_strategy<geographic_tag>\n{\n    typedef strategy::area::geographic<> type;\n};\n\n#endif // DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\n\n}\n\n}} // namespace strategy::area\n\n\n\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_STRATEGIES_GEOGRAPHIC_AREA_HPP\n", "meta": {"hexsha": "d40a30cf22bf18dab3bca57602f368d05cf00926", "size": 6931, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/geometry/strategies/geographic/area.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/geographic/area.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/geographic/area.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": 29.7467811159, "max_line_length": 98, "alphanum_fraction": 0.6328091185, "num_tokens": 1618, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.47903946873847597}}
{"text": "#define BOOST_TEST_MODULE pcraster model_engine fopointarray\n#include <boost/test/unit_test.hpp>\n#include \"com_math.h\"\n#include \"calc_foarrayimplmanual.h\"\n#include \"calc_fopointarray.h\"\n#include \"calc_fopointimpl.h\"\n\n\nBOOST_AUTO_TEST_CASE(test1)\n{\n  using namespace calc;\n\n#include \"calc_fopointarrayimpl.inc\"\n\n{\n INT4  l[3]={1,2,3};\n float  r[3];\n pcr::setMV(l[1]);\n foAr_c_4_2_s_4.f(r, l,3);\n BOOST_CHECK(r[0]==1);\n BOOST_CHECK(pcr::isMV(r[1]));\n BOOST_CHECK(r[2]==3);\n}\n {\n  float l[4] = { 10, 4, 8, 0 };\n  float r[4] = { 4, 10, 0, 9 };\n  pcr::setMV(l[3]);\n  pcr::setMV(r[2]);\n  UINT1 res[4];\n  foAr_gt_f.ss(res,l,r,4);\n  BOOST_CHECK(res[0]==1);\n  BOOST_CHECK(res[1]==0);\n  BOOST_CHECK(res[2]==MV_UINT1);\n  BOOST_CHECK(res[3]==MV_UINT1);\n }\n{\n  float l[4] = { 10, 4, 8, 0 };\n  float r[1] = { 4 };\n  pcr::setMV(l[3]);\n  UINT1 res[4];\n  foAr_gt_f.sn(res,l,r,4);\n  BOOST_CHECK(res[0]==1);\n  BOOST_CHECK(res[1]==0);\n  BOOST_CHECK(res[2]==1);\n  BOOST_CHECK(res[3]==MV_UINT1);\n }\n{\n  float l[1] = { 4 };\n  float r[4] = { 10, 4, 2, 0 };\n  pcr::setMV(r[3]);\n  UINT1 res[4];\n  foAr_gt_f.ns(res,l,r,4);\n  BOOST_CHECK(res[0]==0);\n  BOOST_CHECK(res[1]==0);\n  BOOST_CHECK(res[2]==1);\n  BOOST_CHECK(res[3]==MV_UINT1);\n }\n{\n {\n  float l[2] = { 10, 4 };\n  float r[2] = { 4,  0 };\n  foAr_mod_f.ss(l,r,2);\n  BOOST_CHECK(l[0]==2);\n  BOOST_CHECK(pcr::isMV(l[1]));\n  BOOST_CHECK(r[0]==4);\n  BOOST_CHECK(r[1]==0);\n }\n {\n  float l[1] = { 10 };\n  float r[2] = { 4,  0 };\n  foAr_mod_f.ns(l,r,2);\n  BOOST_CHECK(l[0]==10);\n  BOOST_CHECK(r[0]==2);\n  BOOST_CHECK(pcr::isMV(r[1]));\n }\n {\n  float l[2] = { 10, 4 };\n  float r[1] = {  0 };\n  bool catched(false);\n  try {\n    foAr_mod_f.sn(l,r,2);\n  } catch(const DomainError& ) {\n    catched=true;\n  }\n  BOOST_CHECK(catched);\n }\n}\n{\n {\n  float l[3]={-1,2,4};\n  float r[3]={-1,2,4};\n  pcr::setMV(r[1]);\n  foAr_badd_f.ss( l,r,3);\n  BOOST_CHECK(l[0]==-2);\n  BOOST_CHECK(r[0]==-1);\n  BOOST_CHECK(pcr::isMV(l[1]));\n  BOOST_CHECK(pcr::isMV(r[1]));\n  BOOST_CHECK(l[2]==8);\n  BOOST_CHECK(r[2]==4);\n }\n {\n  float l[1]={10};\n  float r[3]={1,2,4};\n  pcr::setMV(r[1]);\n  foAr_badd_f.ns( l,r,3);\n  BOOST_CHECK(l[0]==10);\n  BOOST_CHECK(r[0]==11);\n  BOOST_CHECK(pcr::isMV(r[1]));\n  BOOST_CHECK(r[2]==14);\n }\n {\n  float l[1]={10};\n  float r[3]={1,2,4};\n  pcr::setMV(r[1]);\n  foAr_badd_f.sn(r,l,3);  // swap as above\n  BOOST_CHECK(l[0]==10);\n  BOOST_CHECK(r[0]==11);\n  BOOST_CHECK(pcr::isMV(r[1]));\n  BOOST_CHECK(r[2]==14);\n }\n}\n{\n float l[3]={-1,2,4};\n pcr::setMV(l[1]);\n foAr_sqrt_f.f( l,3);\n BOOST_CHECK(pcr::isMV(l[1]));\n BOOST_CHECK(l[2]==2);\n BOOST_CHECK(pcr::isMV(l[0]));\n}\n{\n float l[3]={1,2,3};\n foAr_umin_f.f( l,3);\n BOOST_CHECK(l[0]==-1);\n BOOST_CHECK(l[1]==-2);\n BOOST_CHECK(l[2]==-3);\n}\n{\n INT4 l[3]={5,0,MV_INT4};\n UINT1 r[3];\n foAr_c_4_2_b_4.f(r, l,3);\n BOOST_CHECK(r[0]==1);\n BOOST_CHECK(r[1]==0);\n BOOST_CHECK(r[2]==MV_UINT1);\n BOOST_CHECK(l[0]==5);\n BOOST_CHECK(l[1]==0);\n BOOST_CHECK(l[2]==MV_INT4);\n}\n{ // pcrcalc337a\n    REAL4 r= -0.047F;\n    REAL4 l= 1.5F;\n    BOOST_CHECK(special::pow_domainIll(r,l));\n}\n}\n\nBOOST_AUTO_TEST_CASE(testAggregate)\n{\n  using namespace calc;\n\n {\n  UINT1 r,i[4]={MV_UINT1,4,0,3};\n  AggregateArray< MapTotal<UINT1> > f;\n  f.fImpl(&r,i,4);\n  BOOST_CHECK(r==7);\n }\n {\n  INT4 r,i[4]={MV_INT4,4,0,3};\n  AggregateArray< MapMaximum<INT4> > f;\n  f.fImpl(&r,i,4);\n  BOOST_CHECK(r == 4);\n }\n}\n", "meta": {"hexsha": "d271f2246f334ed32ce8c3441f129125265c4ed2", "size": 3335, "ext": "cc", "lang": "C++", "max_stars_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcraster_model_engine/calc_fopointarraytest.cc", "max_stars_repo_name": "quanpands/wflow", "max_stars_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcraster_model_engine/calc_fopointarraytest.cc", "max_issues_repo_name": "quanpands/wflow", "max_issues_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcraster_model_engine/calc_fopointarraytest.cc", "max_forks_repo_name": "quanpands/wflow", "max_forks_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.3895348837, "max_line_length": 60, "alphanum_fraction": 0.5823088456, "num_tokens": 1348, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289836, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.47903847299587216}}
{"text": "#ifndef TENSOR_HH\n#define TENSOR_HH\n\n#include <type_traits>\n#include <Eigen/Dense>\n#include \"../ElasticityTensor.hh\"\n#include \"../Flattening.hh\"\n#include \"../SymmetricMatrix.hh\"\n#include \"../Types.hh\"\n#include \"EnergyTraits.hh\"\n\ntemplate<typename _Real,\n         size_t t_N,\n         typename _Storage_t,\n         typename _ConstStorageRef_t,\n         typename _Derived>\n_Real\ndoubleContract(const ConstSymmetricMatrixBase<_Real, t_N, _Storage_t, _ConstStorageRef_t>& lhs,\n               const Eigen::MatrixBase<_Derived>& rhs)\n{\n    // Note: Some template metaprogramming should be used to test that the\n    // one scalar is convertible into the other and make the return type\n    // the type that is greater for the convertible relation.\n    static_assert(std::is_same<_Real, typename _Derived::Scalar>::value,\n                  \"Different scalar types between the operand is not supported\");\n\n    static_assert(_Derived::RowsAtCompileTime == _Derived::ColsAtCompileTime &&\n                    _Derived::RowsAtCompileTime == t_N,\n                  \"\");\n\n    // Note: This can be optimized by using the fact that lhs is symmetric\n    _Real e = 0;\n    for (size_t i = 0; i < t_N; ++i) {\n        for (size_t j = 0; j < t_N; ++j) {\n            e += lhs(i, j) * rhs(i, j);\n        }\n    }\n\n    return e;\n}\n\ntemplate<typename _Real,\n         size_t t_N,\n         typename _Storage_t,\n         typename _ConstStorageRef_t,\n         typename _Derived>\n_Real\ndoubleContract(const Eigen::MatrixBase<_Derived>& lhs,\n               const ConstSymmetricMatrixBase<_Real, t_N, _Storage_t, _ConstStorageRef_t>& rhs)\n{\n    return doubleContract(rhs, lhs);\n}\n\ntemplate<typename _Derived>\nvoid symmetrize(Eigen::MatrixBase<_Derived>& m) {\n    static_assert(_Derived::RowsAtCompileTime == _Derived::ColsAtCompileTime,\n                  \"Symmetrization only makes sense for square matrices\");\n    m = 0.5 * (m + m.transpose()).eval();\n}\n\ntemplate<typename EigenType>\nusing SMVType = SymmetricMatrixValue<typename EigenType::Scalar,\n                                     EigenType::RowsAtCompileTime>;\n\ntemplate<typename _Derived>\nSMVType<_Derived>\nsymmetrized(const Eigen::MatrixBase<_Derived> &A) {\n    static_assert(_Derived::RowsAtCompileTime == _Derived::ColsAtCompileTime,\n                  \"Symmetrization only makes sense for square matrices\");\n    return SMVType<_Derived>(0.5 * (A + A.transpose()), typename SMVType<_Derived>::skip_validation());\n}\n\ntemplate<typename _Derived>\nSMVType<_Derived>\nsymmetrized_x2(const Eigen::MatrixBase<_Derived> &A) {\n    static_assert(_Derived::RowsAtCompileTime == _Derived::ColsAtCompileTime,\n                  \"Symmetrization only makes sense for square matrices\");\n    return SMVType<_Derived>(A + A.transpose(), typename SMVType<_Derived>::skip_validation());\n}\n\ntemplate<typename _Derived>\nbool isSymmetric(const Eigen::MatrixBase<_Derived>& matrix) {\n    static_assert(_Derived::RowsAtCompileTime == _Derived::ColsAtCompileTime,\n                  \"Symmetry check only makes sense for square matrices\");\n\n    for (size_t col = 0; col < _Derived::ColsAtCompileTime; ++col) {\n        for (size_t row = 0; row <= col; ++row) {\n            if (std::abs(matrix(row, col) - matrix(col, row)) > 1e-13)\n                return false;\n        }\n    }\n    return true;\n}\n\n// Compute the scalar product of two matrices A : B\ntemplate<typename _Derived1, typename _Derived2>\ntypename _Derived1::Scalar doubleContract(const Eigen::MatrixBase<_Derived1>& A, const Eigen::MatrixBase<_Derived2>& B)\n{\n    static_assert((int(_Derived1::RowsAtCompileTime) == int(_Derived2::RowsAtCompileTime)) &&\n                  (int(_Derived1::ColsAtCompileTime) == int(_Derived2::ColsAtCompileTime)), \"Dimensions of A and B must match to compute A : B\");\n    return (A.transpose() * B).trace();\n}\n\ntemplate<typename _Real, size_t _Dim, typename Derived>\nSymmetricMatrixValue<_Real, _Dim>\ndoubleContract(const ElasticityTensor<_Real, _Dim>& A, const Eigen::MatrixBase<Derived>& B)\n{\n    SymmetricMatrixValue<_Real, _Dim> result;\n    for (size_t i = 0; i < _Dim; ++i)\n        for (size_t j = i; j < _Dim; ++j)\n            for (size_t k = 0; k < _Dim; ++k)\n                for (size_t l = 0; l < _Dim; ++l)\n                    result(i, j) += A(i, j, k, l) * B(k, l);\n\n    return result;\n}\n\n/**\n *  Puts in the given matrix zeros everywhere except in (\\a row, \\a col).\n */\ntemplate<typename Derived>\nvoid\nsetUnitMatrix(size_t row, size_t col, Eigen::MatrixBase<Derived>& out)\n{\n    out.setZero();\n    out(row, col) = 1.;\n}\n\n// Note: This could be factored by having a function that returnes the major index and another\n// function that returnes the non-major index.\n/**\n *  Matrix indices manipulation helper\n */\ntemplate<size_t _Dimension, size_t _StoragePolicy = Eigen::ColMajor>\nstruct Indices;\n\ntemplate<size_t _Dimension>\nstruct Indices<_Dimension, Eigen::ColMajor>\n{\n    static std::tuple<size_t, size_t> getNext(size_t row, size_t col)\n    {\n        ++row;\n        if (row == _Dimension)\n        {\n            return std::make_tuple(0, col + 1);\n        }\n        return std::make_tuple(row, col);\n    }\n\n    static std::tuple<size_t, size_t> getUpperTriangleNext(size_t row, size_t col)\n    {\n        ++row;\n        if (row > col)\n        {\n            return std::make_tuple(0, col + 1);\n        }\n        return std::make_tuple(row, col);\n    }\n\n    static bool arePastEnd(size_t /* row */, size_t col) { return col >= _Dimension; }\n};\n\ntemplate<size_t _Dimension>\nstruct Indices<_Dimension, Eigen::RowMajor>\n{\n    static std::tuple<size_t, size_t> getNext(size_t row, size_t col)\n    {\n        ++col;\n        if (col == _Dimension)\n        {\n            return std::make_tuple(row + 1, 0);\n        }\n        return std::make_tuple(row, col);\n    }\n\n    static std::tuple<size_t, size_t> getUpperTriangleNext(size_t row, size_t col)\n    {\n        ++col;\n        if (col > row)\n        {\n            return std::make_tuple(row + 1, 0);\n        }\n        return std::make_tuple(row, col);\n    }\n\n    static bool arePastEnd(size_t row, size_t /* col */) { return row >= _Dimension; }\n};\n\ntemplate<size_t _Dimension, size_t _StoragePolicy = Eigen::ColMajor>\nstd::tuple<size_t, size_t> getNextIndices(size_t row, size_t col) {\n    return Indices<_Dimension, _StoragePolicy>::getNext(row, col);\n}\n\ntemplate<size_t _Dimension, size_t _StoragePolicy = Eigen::ColMajor>\nstd::tuple<size_t, size_t> getUpperTriangleNextIndices(size_t row, size_t col) {\n    return Indices<_Dimension, _StoragePolicy>::getUpperTriangleNext(row, col);\n}\n\ntemplate<size_t _Dimension, size_t _StoragePolicy = Eigen::ColMajor>\nbool arePastEndIndices(size_t row, size_t col) {\n    return Indices<_Dimension, _StoragePolicy>::arePastEnd(row, col);\n}\n\n////////////////////////////////////////////////////////////////////////////////\n// Support for accelerating calculations involving Jacobians of vector-valued\n// shape functions\n////////////////////////////////////////////////////////////////////////////////\n\n// The vectorized shape functions are of the form\n//      e_c phi_n\n// and their Jacobians look like:\n//      e_c \\otimes grad phi_n\n// where e_c is a canonical basis vector for R^D (the output space dimension)\n// and grad phi_n is a vector in R^N (the input space dimension).\n// This class provides a compact representation for these Jacobians which\n// will also allow more efficient contraction operations.\ntemplate<int D, class GradType>\nstruct VectorizedShapeFunctionJacobian {\n    static constexpr int N = GradType::RowsAtCompileTime;\n\n    // Emulate part of Eigen's interface.\n    // This also allows VectorizedShapeFunctionJacobian to\n    // masquerade as a DxN matrix in metaprogramming type checks (e.g., isMatrixOfSize).\n    static constexpr int RowsAtCompileTime = D;\n    static constexpr int ColsAtCompileTime = N;\n    using Scalar     = typename GradType::Scalar;\n    using MatrixType = Eigen::Matrix<Scalar, D, N>;\n    using ColVec     = Eigen::Matrix<Scalar, D, 1>;\n    using Derived    = MatrixType;\n\n    int c;\n    GradType g;\n\n    VectorizedShapeFunctionJacobian(int cc, Eigen::Ref<const GradType> gg)\n        : c(cc), g(gg) { }\n\n    MatrixType toMatrix() const {\n        MatrixType result(MatrixType::Zero());\n        result.row(c) = g.transpose();\n        return result;\n    }\n\n    // Note: it doesn't seem possible to actually use this explicit cast operator\n    // except by directly calling `.operator MatrixType()`--this is because Eigen's\n    // converting constructor is preferred when issuing a\n    // `static_cast<MatrixType()` or `MatrixType()`.\n    explicit operator MatrixType() const { // Allow conversion to underlying matrix type when necessary.\n        return toMatrix();\n    }\n\n    // Note: this method provides the same conversion interface as Eigen::DenseBase::matrix();\n    // this allows generic code to call `.matrix()` on VSFJ or Eigen types.\n    MatrixType matrix() const { return toMatrix(); }\n\n    template<class Derived>\n    friend auto operator*(const VectorizedShapeFunctionJacobian &A, const Eigen::MatrixBase<Derived> &B) {\n        using ResultType = VectorizedShapeFunctionJacobian<D, Eigen::Matrix<Scalar, Derived::ColsAtCompileTime, 1>>;\n        return ResultType(A.c, B.template cast<Scalar>().transpose() * A.g);\n    }\n\n    template<class Derived>\n    friend auto operator*(const Eigen::MatrixBase<Derived> &A, const VectorizedShapeFunctionJacobian &B) {\n        return A.col(B.c).template cast<Scalar>() * B.g.transpose();\n    }\n\n    template<typename Real2, class Enable = std::enable_if_t<std::is_arithmetic<Real2>::value>>\n    friend VectorizedShapeFunctionJacobian operator*(const Real2 &s, const VectorizedShapeFunctionJacobian &B) {\n        return VectorizedShapeFunctionJacobian(B.c, s * B.g);\n    }\n\n    template<typename Real2, class Enable = std::enable_if_t<std::is_arithmetic<Real2>::value>>\n    friend VectorizedShapeFunctionJacobian operator*(const VectorizedShapeFunctionJacobian &B, const Real2 &s) {\n        return VectorizedShapeFunctionJacobian(B.c, s * B.g);\n    }\n\n    template<class Derived>\n    friend MatrixType operator+(const VectorizedShapeFunctionJacobian &A, const Eigen::MatrixBase<Derived> &B) {\n        static_assert((RowsAtCompileTime == Derived::RowsAtCompileTime) &&\n                      (ColsAtCompileTime == Derived::ColsAtCompileTime), \"Size mismatch\");\n        MatrixType result(B);\n        result.row(A.c) += A.g.transpose();\n        return result;\n    }\n\n    template<class Derived>\n    friend ColVec colCross(const VectorizedShapeFunctionJacobian &A, int j, const Eigen::MatrixBase<Derived> &v) {\n        // g[j] * e_c.cross(v)\n        ColVec result;\n        result[ A.c         ] = 0.0;\n        result[(A.c + 2) % D] =  A.g[j] * v[(A.c + 1) % D];\n        result[(A.c + 1) % D] = -A.g[j] * v[(A.c + 2) % D];\n        return result;\n    }\n\n    template<class Derived>\n    friend MatrixType operator+(const Eigen::MatrixBase<Derived> &A, const VectorizedShapeFunctionJacobian &B) {\n        return B + A;\n    }\n};\n\n// A : (B.c otimes B.g)\ntemplate<class Derived, int D, class GradType>\ntypename Derived::Scalar doubleContract(const Eigen::MatrixBase<Derived> &A,\n                      const VectorizedShapeFunctionJacobian<D, GradType> &B) {\n    return A.row(B.c).dot(B.g);\n}\n\ntemplate<class Derived, int D, class GradType>\nauto doubleContract(const VectorizedShapeFunctionJacobian<D, GradType> &A,\n                      const Eigen::MatrixBase<Derived> &B) { return doubleContract(B, A); }\n\ntemplate<class T>\nstruct IsVectorizedShapeFunctionJacobian { static constexpr bool value = false; };\ntemplate<int D, class GradType>\nstruct IsVectorizedShapeFunctionJacobian<VectorizedShapeFunctionJacobian<D, GradType>> {\n    static constexpr bool value = true;\n};\n\n// Some operations that can be accelerated with VectorizedShapeFunctionJacobian types.\ntemplate<class AType, class BType, typename =\n    std::enable_if_t<!IsVectorizedShapeFunctionJacobian<AType>::value ||\n                     !IsVectorizedShapeFunctionJacobian<BType>::value, void>>\nbool AtBKnownZero(const AType &, const BType &) { return false; }\n\ntemplate<int D, class GradType>\nbool AtBKnownZero(const VectorizedShapeFunctionJacobian<D, GradType> &A,\n                  const VectorizedShapeFunctionJacobian<D, GradType> &B) {\n    return A.c != B.c;\n}\n\ntemplate<class AType, class BType, typename =\n    std::enable_if_t<!IsVectorizedShapeFunctionJacobian<AType>::value ||\n                     !IsVectorizedShapeFunctionJacobian<BType>::value, void>>\nauto computeAtB(const AType &A, const BType &B) {\n    return A.transpose() * B;\n}\n\ntemplate<int D, class GradType>\nauto computeAtB(const VectorizedShapeFunctionJacobian<D, GradType> &A,\n                const VectorizedShapeFunctionJacobian<D, GradType> &B) {\n    using VSFJ = VectorizedShapeFunctionJacobian<D, GradType>;\n    using Scalar = typename VSFJ::Scalar;\n    using Result = Eigen::Matrix<Scalar, VSFJ::N, VSFJ::N>;\n\n    if (A.c == B.c)\n        return Result(A.g * B.g.transpose());\n    return Result(Result::Zero());\n}\n\ntemplate<class Derived1, class Derived2>\nEigen::Matrix<typename Derived1::Scalar, 3, 1>\ncolCross(const Eigen::MatrixBase<Derived1> &A, int j, const Eigen::MatrixBase<Derived2> &v) {\n    static_assert((Derived1::RowsAtCompileTime == 3) && (Derived2::RowsAtCompileTime == 3) && (Derived2::ColsAtCompileTime == 1),\n                  \"Unexpected sizes for colCross\");\n    return A.col(j).cross(v);\n}\n\ntemplate<int D, class GradType>\nSMVType<VectorizedShapeFunctionJacobian<D, GradType>>\nsymmetrized(const VectorizedShapeFunctionJacobian<D, GradType> &A) {\n    SMVType<VectorizedShapeFunctionJacobian<D, GradType>> result; // zero-initializes\n    for (int i = 0; i < int(D); ++i)\n        result(A.c, i) = ((i == A.c) ? 1.0 : 0.5) * A.g[i];\n    return result;\n}\n\n// Note: C better be symmetric!\ntemplate<class Mat_>\nEigen::Matrix<typename Mat_::Scalar,\n              Mat_::RowsAtCompileTime,\n              Mat_::ColsAtCompileTime>\nspdMatrixSqrt(const Mat_ &C) {\n    constexpr static int N = Mat_::RowsAtCompileTime;\n    static_assert((N == 2) || (N == 3), \"Unexpected matrix size\");\n    using MNd = Eigen::Matrix<typename Mat_::Scalar, N, N>;\n    return Eigen::SelfAdjointEigenSolver<MNd>(C).operatorSqrt();\n}\n\n// Compute the double contraction `C : e` for fourth order tensor `C` and matrix `e`.\n// Assumes that C has been flattened with the same ordering as e's storage storage order!\ntemplate<class FlattenedTensorDerived, class Derived>\nstd::enable_if_t<(FlattenedTensorDerived::RowsAtCompileTime == FlattenedTensorDerived::ColsAtCompileTime)\n                && (FlattenedTensorDerived::ColsAtCompileTime == (Derived::RowsAtCompileTime * Derived::ColsAtCompileTime)),\nEigen::Matrix<typename Derived::Scalar, Derived::RowsAtCompileTime, Derived::ColsAtCompileTime>>\napplyFlattened4thOrderTensor(const Eigen::MatrixBase<FlattenedTensorDerived> &C, const Eigen::MatrixBase<Derived> &e) {\n    using Scalar = typename Derived::Scalar;\n    constexpr int M = Derived::RowsAtCompileTime,\n                  N = Derived::ColsAtCompileTime;\n    using FlatMatrix = Eigen::Matrix<Scalar, M * N, 1>;\n    Eigen::Matrix<Scalar, M, N, Derived::Options> result;\n    Eigen::Map<FlatMatrix>(result.data()) = C * Eigen::Map<const FlatMatrix>(e.derived().data()).eval();\n    return result;\n}\n\n// Compute the double contraction `C : e` for fourth order tensor `C` and matrix `e`.\n// Assumes that C has been flattened **in column major order**\ntemplate<class FlattenedTensorDerived, int D, class GradType>\nstd::enable_if_t<(FlattenedTensorDerived::RowsAtCompileTime == FlattenedTensorDerived::RowsAtCompileTime)\n                && (FlattenedTensorDerived::ColsAtCompileTime == (D * GradType::RowsAtCompileTime)),\nEigen::Matrix<typename FlattenedTensorDerived::Scalar, D, GradType::RowsAtCompileTime>>\napplyFlattened4thOrderTensor(const Eigen::MatrixBase<FlattenedTensorDerived> &C,\n                             const VectorizedShapeFunctionJacobian<D, GradType> &e) {\n    using Scalar = typename FlattenedTensorDerived::Scalar;\n    constexpr int M = D,\n                  N = GradType::RowsAtCompileTime;\n    using FlatMatrix = Eigen::Matrix<Scalar, M * N, 1>;\n    // \"e\" consists of a single nonzero row at index \"e.c\" with values \"e.g\"\n    // We assume column major ordering, so the flattened version of \"e\" has\n    // nonzero values at indices `e.c + D * i`.\n    FlatMatrix flatResult = C.col(e.c) * e.g[0];\n    for (int i = 1; i < N; ++i)\n        flatResult += C.col(e.c + D * i) * e.g[i];\n    return Eigen::Map<Eigen::Matrix<Scalar, M, N>>(flatResult.data());\n}\n\n#endif\n", "meta": {"hexsha": "54c15e0bad1ce24c39e807732599feb9827a5a2d", "size": 16566, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/lib/MeshFEM/EnergyDensities/Tensor.hh", "max_stars_repo_name": "MeshFEM/MeshFEM", "max_stars_repo_head_hexsha": "9b3619fa450d83722879bfd0f5a3fe69d927bd63", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2020-10-21T10:05:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T13:41:50.000Z", "max_issues_repo_path": "src/lib/MeshFEM/EnergyDensities/Tensor.hh", "max_issues_repo_name": "MeshFEM/MeshFEM", "max_issues_repo_head_hexsha": "9b3619fa450d83722879bfd0f5a3fe69d927bd63", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-01-01T15:58:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-19T03:31:09.000Z", "max_forks_repo_path": "src/lib/MeshFEM/EnergyDensities/Tensor.hh", "max_forks_repo_name": "MeshFEM/MeshFEM", "max_forks_repo_head_hexsha": "9b3619fa450d83722879bfd0f5a3fe69d927bd63", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-10-05T09:01:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-11T03:02:39.000Z", "avg_line_length": 39.726618705, "max_line_length": 145, "alphanum_fraction": 0.671012918, "num_tokens": 4181, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289836, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.47903847299587216}}
{"text": "// Copyright Louis Dionne 2013-2017\r\n// Distributed under the Boost Software License, Version 1.0.\r\n// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef BOOST_HANA_EXAMPLE_CPPCON_2014_MATRIX_DET_HPP\r\n#define BOOST_HANA_EXAMPLE_CPPCON_2014_MATRIX_DET_HPP\r\n\r\n#include <boost/hana/equal.hpp>\r\n#include <boost/hana/eval_if.hpp>\r\n#include <boost/hana/front.hpp>\r\n#include <boost/hana/functional/always.hpp>\r\n#include <boost/hana/functional/fix.hpp>\r\n#include <boost/hana/functional/flip.hpp>\r\n#include <boost/hana/functional/on.hpp>\r\n#include <boost/hana/functional/partial.hpp>\r\n#include <boost/hana/integral_constant.hpp>\r\n#include <boost/hana/plus.hpp>\r\n#include <boost/hana/power.hpp>\r\n#include <boost/hana/range.hpp>\r\n#include <boost/hana/remove_at.hpp>\r\n#include <boost/hana/transform.hpp>\r\n#include <boost/hana/tuple.hpp>\r\n#include <boost/hana/unpack.hpp>\r\n\r\n#include <utility>\r\n\r\n#include \"matrix.hpp\"\r\n\r\n\r\nnamespace cppcon {\r\n    namespace hana = boost::hana;\r\n    auto det = hana::fix([](auto det, auto&& m) -> decltype(auto) {\r\n        auto matrix_minor = [=](auto&& m, auto i, auto j) -> decltype(auto) {\r\n            return det(hana::unpack(\r\n                hana::transform(\r\n                    hana::remove_at(rows(std::forward<decltype(m)>(m)), i),\r\n                    hana::partial(hana::flip(hana::remove_at), j)\r\n                ),\r\n                matrix\r\n            ));\r\n        };\r\n\r\n        auto cofactor = [=](auto&& m, auto i, auto j) {\r\n            return hana::power(hana::int_c<-1>, hana::plus(i, j)) *\r\n                    matrix_minor(std::forward<decltype(m)>(m), i, j);\r\n        };\r\n\r\n        return hana::eval_if(m.size() == hana::size_c<1>,\r\n            hana::always(m.at(hana::size_c<0>, hana::size_c<0>)),\r\n            [=](auto _) {\r\n                auto cofactors_1st_row = hana::unpack(_(hana::make_range)(hana::size_c<0>, m.ncolumns()),\r\n                    hana::on(hana::make_tuple, hana::partial(cofactor, m, hana::size_c<0>))\r\n                );\r\n                return detail::tuple_scalar_product(hana::front(rows(m)), cofactors_1st_row);\r\n            }\r\n        );\r\n    });\r\n} // end namespace cppcon\r\n\r\n#endif // !BOOST_HANA_EXAMPLE_CPPCON_2014_MATRIX_DET_HPP\r\n", "meta": {"hexsha": "44c71e68e977576d39038ec0e01473ab78ba0e60", "size": 2246, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/hana/example/cppcon_2014/matrix/det.hpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/hana/example/cppcon_2014/matrix/det.hpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-03-04T11:21:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-24T01:36:31.000Z", "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/hana/example/cppcon_2014/matrix/det.hpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 36.8196721311, "max_line_length": 106, "alphanum_fraction": 0.6086375779, "num_tokens": 578, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289836, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.47903847299587216}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2013   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2012   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_LINALG_FUNCTIONS_SCALAR_DET_HPP_INCLUDED\n#define NT2_LINALG_FUNCTIONS_SCALAR_DET_HPP_INCLUDED\n\n#include <nt2/linalg/functions/det.hpp>\n#include <nt2/include/functions/getrf.hpp>\n#include <nt2/include/functions/numel.hpp>\n#include <nt2/include/functions/diag_of.hpp>\n#include <nt2/include/functions/issquare.hpp>\n#include <nt2/include/functions/globalprod.hpp>\n#include <nt2/core/container/table/table.hpp>\n#include <boost/core/ignore_unused.hpp>\n\nnamespace nt2{ namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT  ( det_, tag::cpu_\n                            , (A0)\n                            , ((ast_<A0, nt2::container::domain>))\n                            )\n  {\n    typedef typename A0::value_type                 type_t;\n    typedef typename boost::dispatch::meta::as_floating<type_t>\n                                          ::type  result_type;\n\n    BOOST_FORCEINLINE result_type operator()(A0 const& a0) const\n    {\n      BOOST_ASSERT_MSG( issquare(a0)\n                      , \"DET: Argument must be a square matrix\"\n                      );\n\n      nt2::container::table<typename A0::value_type>  lu(a0);\n      nt2::container::table<nt2_la_int>               ip;\n\n      // Factorize A as L/U\n      nt2_la_int  info = nt2::getrf(boost::proto::value(lu),boost::proto::value(ip));\n      boost::ignore_unused(info);\n\n      // DET(A) is the product of LU(A) diagonal by -1 at the power of\n      // the number of non-permutations done in LU(A)\n      std::size_t n     = nt2::numel(ip);\n      result_type sign  = One<result_type>();\n\n      // TODO: Parallelize this somehow ?\n      for(std::size_t i = 1;i <= n;++i)\n        sign  *= (ip(i) != nt2_la_int(i)) ? 1 : -1;\n\n      return nt2::globalprod(nt2::diag_of(lu))*sign;\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  ( det_, tag::cpu_\n                            , (A0)\n                            , (scalar_< unspecified_<A0> >)\n                            )\n  {\n    typedef typename boost::dispatch::meta::as_floating<A0>\n                                          ::type  result_type;\n    BOOST_FORCEINLINE result_type operator()(A0 const& a0) const\n    {\n      return a0;\n    }\n  };\n} }\n\n#endif\n", "meta": {"hexsha": "fd5a7f9e7f2c2840dbf17e6ca24ca7acb8886a66", "size": 2708, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/linalg/include/nt2/linalg/functions/scalar/det.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/scalar/det.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/scalar/det.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.5945945946, "max_line_length": 85, "alphanum_fraction": 0.5435745938, "num_tokens": 645, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289836, "lm_q2_score": 0.6297746004557471, "lm_q1q2_score": 0.4790384677103645}}
{"text": "#include \"ros/ros.h\"\n#include \"tr3_msgs/InverseIK.h\"\n#include <Eigen/Geometry>\n#include <moveit/robot_model_loader/robot_model_loader.h>\n#include <moveit/robot_model/robot_model.h>\n#include <moveit/robot_state/robot_state.h>\n\nbool inverse_ik(tr3_msgs::InverseIK::Request &req, tr3_msgs::InverseIK::Response &res)\n{\n\trobot_model_loader::RobotModelLoader robot_model_loader(\"robot_description\");\n\trobot_model::RobotModelPtr kinematic_model = robot_model_loader.getModel();\n\tROS_INFO(\"Model frame: %s\", kinematic_model->getModelFrame().c_str());\n\n\trobot_state::RobotStatePtr kinematic_state(new robot_state::RobotState(kinematic_model));\n\tkinematic_state->setToDefaultValues();\n\tconst robot_state::JointModelGroup* joint_model_group = kinematic_model->getJointModelGroup(\"tr3_arm\");\n\n\tconst std::vector<std::string>& joint_names = joint_model_group->getVariableNames();\n\n\tconst geometry_msgs::Pose &m = req.pose;\n\tconst Eigen::Isometry3d& end_effector_state = Eigen::Translation3d(m.position.x, m.position.y, m.position.z)\n\t\t* Eigen::Quaterniond(m.orientation.w, m.orientation.x, m.orientation.y, m.orientation.z);\n\n\tstd::vector<double> joint_values;\n\n\tdouble timeout = 0.2;\n\tbool found_ik = kinematic_state->setFromIK(joint_model_group, end_effector_state, timeout);\n\n\tif (found_ik)\n\t{\n\t\tkinematic_state->copyJointGroupPositions(joint_model_group, joint_values);\n\t\tfor (std::size_t i = 0; i < joint_names.size(); ++i)\n\t\t{\n\t\t\tres.state.name.push_back(joint_names[i]);\n\t\t\tres.state.position.push_back(joint_values[i]);\n\t\t\tres.state.effort.push_back(0);\n\t\t\tres.state.velocity.push_back(0);\n\t\t}\n\t\tROS_INFO(\"Found solution\");\n\t\treturn true;\n\t}\n\telse\n\t{\n\t\tROS_INFO(\"Could not find IK solution\");\n\t\treturn false;\n\t}\n}\n\nint main(int argc, char **argv)\n{\n\tros::init(argc, argv, \"inverse_ik_server\");\n\tros::NodeHandle n;\n\n\tros::ServiceServer service = n.advertiseService(\"inverse_ik\", inverse_ik);\n\tROS_INFO(\"Ready.\");\n\tros::spin();\n\n\treturn 0;\n}\n", "meta": {"hexsha": "5677e9b7746dc6d35f5031a1816df57ce3bfd3dc", "size": 1935, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tr3_moveit/src/inverse_ik_server.cpp", "max_stars_repo_name": "SlateRobotics/tr3_essentials", "max_stars_repo_head_hexsha": "c8608f04a83a5ca53f25ce0e5f6bce217e378c6f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-01-22T05:52:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-09T18:11:20.000Z", "max_issues_repo_path": "tr3_moveit/src/inverse_ik_server.cpp", "max_issues_repo_name": "SlateRobotics/tr3_essentials", "max_issues_repo_head_hexsha": "c8608f04a83a5ca53f25ce0e5f6bce217e378c6f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-08-07T08:47:52.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-07T08:47:52.000Z", "max_forks_repo_path": "tr3_moveit/src/inverse_ik_server.cpp", "max_forks_repo_name": "SlateRobotics/tr3_essentials", "max_forks_repo_head_hexsha": "c8608f04a83a5ca53f25ce0e5f6bce217e378c6f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-08-03T17:42:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-06T14:23:35.000Z", "avg_line_length": 32.25, "max_line_length": 109, "alphanum_fraction": 0.757622739, "num_tokens": 515, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.47903846616175}}
{"text": "#include <g2o/core/base_vertex.h>\n#include <g2o/core/base_binary_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/core/robust_kernel_impl.h>\n#include <g2o/types/slam3d/se3quat.h>\n#include <g2o/types/slam3d/vertex_pointxyz.h>\n#include <g2o/types/sba/types_six_dof_expmap.h>\n#include <iostream>\n\n#include \"common.h\"\n#include <sophus/se3.hpp>\n#include <sophus/so3.hpp>\n#include <Eigen/Dense>\n\nusing namespace Sophus;\nusing namespace Eigen;\nusing namespace std;\n\nstruct Camera\n{\n    Camera() {}\n\n    Camera(double* data)\n    {\n        Rt = g2o::SE3Quat::exp(Eigen::Map<Eigen::Matrix<double, 6, 1>>(data));\n\n        f = data[6];\n        k1 = data[7];\n        k2 = data[8];\n    }\n\n    void set_to(double* data) const\n    {\n        Eigen::Matrix<double, 6, 1> rt = Rt.log();\n        \n        for (int i = 0; i < 6; ++i)\n            data[i] = rt[i];\n        \n\n        data[6] = f;\n        data[7] = k1;\n        data[8] = k2;\n    }\n\n    g2o::SE3Quat Rt; // g2o::SE3Quat is stored as rotation first and then translation\n    double f = 0.0, k1 = 0.0, k2 = 0.0;\n};\n\nclass VertexCamera: public g2o::BaseVertex<6, Camera>\n{\n    public:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n\n    virtual void setToOriginImpl() override {\n        \n        _estimate = Camera();\n        // _estimate = g2o::SE3Quat();\n    }\n\n    virtual void oplusImpl(const double *update) override {\n        // _estimate = g2o::SE3Quat::exp(Eigen::Map<const Eigen::Matrix<double, 6, 1>>(update)) * _estimate;\n        _estimate.Rt = g2o::SE3Quat::exp(Eigen::Map<const Eigen::Matrix<double, 6, 1>>(update)) * _estimate.Rt;\n\n    }\n\n    virtual bool read(std::istream&) override {}\n    virtual bool write(std::ostream&) const override {}\n};\n\nclass VertexLandmark: public g2o::BaseVertex<3, Eigen::Vector3d>\n{\n    public:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n\n    virtual void setToOriginImpl() override {\n        _estimate = Eigen::Vector3d::Zero();       \n    }\n\n    virtual void oplusImpl(const double *update) override {\n        _estimate += Eigen::Map<const Eigen::Vector3d>(update);\n    }\n\n    virtual bool read(std::istream&) override {}\n    virtual bool write(std::ostream&) const override {}\n};\n\n\nclass EdgeReprojection: public g2o::BaseBinaryEdge<2, Eigen::Vector2d, VertexLandmark, VertexCamera>\n{\n  public:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n\n    EdgeReprojection(double f, double k1, double k2) : f_(f), k1_(k1), k2_(k2) { }\n\n    virtual void computeError() override {\n        const VertexCamera* v_cam = static_cast<VertexCamera*>(_vertices[1]);\n        const VertexLandmark* v_point = static_cast<VertexLandmark*>(_vertices[0]);\n        auto cam = v_cam->estimate();\n        Eigen::Vector3d X = v_point->estimate();\n        Eigen::Vector3d X_cam = cam.Rt * X;\n        X_cam /= X_cam.z();\n\n        // auto p2 = X_cam.x() * X_cam.x() + X_cam.y() * X_cam.y();\n        // auto r = 1.0 + p2 * (k1_ + (p2 * k2_));\n\n        Eigen::Vector2d uv = -X_cam.head<2>() *  f_ ; // minus because of the dataset projection\n        _error = _measurement - uv;\n    }\n\n\n    virtual void linearizeOplus() override {\n        const VertexCamera *v_cam = static_cast<VertexCamera*>(_vertices[1]);\n        const VertexLandmark *v_landmark = static_cast<VertexLandmark*>(_vertices[0]);\n        Eigen::Vector3d X = v_landmark->estimate();\n        auto cam = v_cam->estimate();\n        Eigen::Vector3d Xc = cam.Rt * X;\n\n        double x = Xc.x();\n        double y = Xc.y();\n        double z = Xc.z();\n        double z_2 = z * z;\n        \n        Eigen::Matrix<double, 2, 3> dedXc;\n        dedXc << -f_ / z, 0.0, f_ * x / z_2,   // -f_ is because of the dataset projection function (not standard)\n                0.0, -f_ / z, f_ * y / z_2;\n        Eigen::Matrix3d dXcdR;\n        dXcdR << 0.0, -z, y,\n                 z, 0.0, -x,\n                 -y, x, 0.0;\n        Eigen::Matrix3d dXcdt = Eigen::Matrix3d::Identity();\n        _jacobianOplusXj.block<2, 3>(0, 0) = dedXc * -dXcdR; // -dXcdR <=> -Xc^\n        _jacobianOplusXj.block<2, 3>(0, 3) = dedXc * dXcdt;\n        \n        _jacobianOplusXi = dedXc * cam.Rt.rotation().matrix();\n\n         _jacobianOplusXi *= -1; // take the negative jacobian because the error is defined as (measurement - projection)\n         _jacobianOplusXj *= -1;\n\n\n    }\n\n    virtual bool read(std::istream&) override {}\n    virtual bool write(std::ostream&) const override {}\n    private:\n        double f_, k1_, k2_;\n\n};\n\n\nint main(int argc, char **argv) {\n\n    if (argc != 2) {\n        cout << \"usage: bundle_adjustment_g2o bal_data.txt\" << endl;\n        return 1;\n    }\n\n    BALProblem dataset(argv[1]);\n    dataset.Normalize();\n    // dataset.Perturb(0.1, 0.5, 0.5);\n    dataset.WriteToPLYFile(\"initial_pc.ply\");\n\n    std::cout << \"\\n\";\n    std::cout << \"nb cameras: \" << dataset.num_cameras() << std::endl;\n    std::cout << \"nb landmarks: \" << dataset.num_points() << std::endl;\n    std::cout << \"nb observations: \" << dataset.num_observations() << std::endl;\n    std::cout << \"nb parameters: \" << dataset.num_parameters() << std::endl;\n    std::cout << \"check: \" << dataset.num_cameras() * 9 + dataset.num_points()*3 << std::endl;\n\n\n    // pose dimension 9, landmark is 3\n    typedef g2o::BlockSolver<g2o::BlockSolverTraits<6, 3>> BlockSolverType;\n    typedef g2o::LinearSolverCSparse<BlockSolverType::PoseMatrixType> LinearSolverType;\n\n    auto solver = new g2o::OptimizationAlgorithmLevenberg(\n        g2o::make_unique<BlockSolverType>(g2o::make_unique<LinearSolverType>())\n    );\n    g2o::SparseOptimizer optimizer;\n    optimizer.setAlgorithm(solver);\n    optimizer.setVerbose(true);\n\n\n    auto* cameras = dataset.mutable_cameras();\n    std::vector<VertexCamera*> camera_vertices;\n    for (int i = 0; i < dataset.num_cameras(); ++i)\n    {\n        auto *c = new VertexCamera();\n        c->setId(i);\n        c->setEstimate(Camera(cameras + (i*dataset.camera_block_size())));\n        optimizer.addVertex(c);\n        camera_vertices.push_back(c);\n    }\n    \n    auto* landmarks = dataset.mutable_points();\n    std::vector<VertexLandmark*> landmark_vertices;\n    for (int i = 0; i < dataset.num_points(); ++i)\n    {\n        auto* l = new VertexLandmark();\n        l->setId(dataset.num_cameras() + i);\n        l->setEstimate(Eigen::Map<Eigen::Vector3d>(landmarks + i*dataset.point_block_size()));\n        l->setMarginalized(true);\n        optimizer.addVertex(l);\n        landmark_vertices.push_back(l);\n    }\n\n    auto* observations = dataset.observations();\n    auto* cam_indices = dataset.camera_index();\n    auto* landmark_indices = dataset.point_index();\n    for (int i = 0; i < dataset.num_observations(); ++i)\n    {\n        auto c = Camera(cameras + (cam_indices[i]*dataset.camera_block_size()));\n        auto* e = new EdgeReprojection(c.f, c.k1, c.k2);\n        e->setVertex(1, camera_vertices[cam_indices[i]]);\n        e->setVertex(0, landmark_vertices[landmark_indices[i]]);\n        e->setMeasurement(Eigen::Map<const Eigen::Vector2d>(observations + i*2));\n        e->setInformation(Eigen::Matrix2d::Identity());\n        optimizer.addEdge(e);\n    }\n\n    optimizer.initializeOptimization();\n    optimizer.optimize(40);\n\n\n    for (int i = 0; i < dataset.num_cameras(); ++i)\n    {\n        camera_vertices[i]->estimate().set_to(cameras + (i * dataset.camera_block_size()));\n        // auto v = camera_vertices[i]->estimate().log();\n        // double* pt = cameras + (i * dataset.camera_block_size());\n        // for (int j = 0; j < 6; ++j)\n        // {\n        //     pt[j] = v[j];\n        // }\n    }\n    for (int i = 0; i < dataset.num_points(); ++i)\n    {\n        Eigen::Vector3d X = landmark_vertices[i]->estimate();\n        landmarks[i*3] = X.x();\n        landmarks[i*3+1] = X.y();\n        landmarks[i*3+2] = X.z();\n    }\n\n    dataset.WriteToPLYFile(\"after_ba_g2o.ply\");\n\n    return 0;\n}\n", "meta": {"hexsha": "b970bf50c586a875cd0bd9b2a93db09c0934036d", "size": 7877, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch9/bundle_adjustment_g2o_custom_analytical_no_intrinsics.cpp", "max_stars_repo_name": "zinsmatt/slambook2", "max_stars_repo_head_hexsha": "3648caff838241553d9f3de332068eb0d501a7dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ch9/bundle_adjustment_g2o_custom_analytical_no_intrinsics.cpp", "max_issues_repo_name": "zinsmatt/slambook2", "max_issues_repo_head_hexsha": "3648caff838241553d9f3de332068eb0d501a7dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch9/bundle_adjustment_g2o_custom_analytical_no_intrinsics.cpp", "max_forks_repo_name": "zinsmatt/slambook2", "max_forks_repo_head_hexsha": "3648caff838241553d9f3de332068eb0d501a7dc", "max_forks_repo_licenses": ["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.8906882591, "max_line_length": 121, "alphanum_fraction": 0.6067030595, "num_tokens": 2272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645723, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.47898193734432243}}
{"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_RANDOM_STRATEGIES_AGNOSTIC_UNIFORM_LINEAR_HPP\n#define BOOST_GEOMETRY_EXTENSIONS_RANDOM_STRATEGIES_AGNOSTIC_UNIFORM_LINEAR_HPP\n\n#include <random>\n#include <iterator>\n#include <algorithm>\n\n#include <boost/geometry/algorithms/equals.hpp>\n#include <boost/geometry/algorithms/transform.hpp>\n#include <boost/geometry/algorithms/within.hpp>\n#include <boost/geometry/geometries/box.hpp>\n#include <boost/geometry/core/point_type.hpp>\n\n#include <boost/geometry/extensions/random/strategies/uniform_point_distribution.hpp>\n#include <boost/geometry/extensions/random/strategies/cartesian/uniform_point_distribution_segment.hpp>\n#include <boost/geometry/extensions/random/strategies/spherical/edwilliams_avform_intermediate.hpp>\n\nnamespace boost { namespace geometry\n{\n\nnamespace strategy { namespace uniform_point_distribution {\n\ntemplate\n<\n    typename Point,\n    typename DomainGeometry,\n    typename SegmentStrategy = services::default_strategy\n        <\n            typename point_type<DomainGeometry>::type,\n            model::segment<typename point_type<DomainGeometry>::type>\n        >\n>\nclass uniform_linear\n{\nprivate:\n    typedef typename default_length_result<DomainGeometry>::type length_type;\n    typedef typename point_type<DomainGeometry>::type domain_point_type;\n    std::vector<std::size_t> skip_list;\n    std::vector<domain_point_type> point_cache;\n    std::vector<length_type> accumulated_lengths;\npublic:\n    uniform_linear(DomainGeometry const& g)\n    {\n        std::size_t i = 0;\n        point_cache.push_back(*segments_begin(g)->first);\n        accumulated_lengths.push_back(0);\n        for (auto it = segments_begin(g) ; it != segments_end(g) ; ++it)\n        {\n            accumulated_lengths.push_back(\n                accumulated_lengths.back() + length(*it));\n            if (!boost::geometry::equals(point_cache.back(), *it->first))\n            {\n                point_cache.push_back(*it->first);\n                skip_list.push_back(i);\n            }\n            point_cache.push_back(*it->second);\n            ++i;\n        }\n    }\n    bool equals(DomainGeometry const& l_domain,\n                DomainGeometry const& r_domain,\n                uniform_linear const& r_strategy) const\n    {\n        if(r_strategy.skip_list.size() != skip_list.size()\n            || r_strategy.point_cache.size() != point_cache.size())\n            return false;\n        for (std::size_t i = 0; i < skip_list.size(); ++i)\n        {\n            if (skip_list[i] != r_strategy.skip_list[i]) return false;\n        }\n        for (std::size_t i = 0; i < point_cache.size(); ++i)\n        {\n            if (!boost::geometry::equals(point_cache[i], r_strategy.point_cache[i])) return false;\n        }\n        return true;\n    }\n    template<typename Gen>\n    Point apply(Gen& g, DomainGeometry const& d)\n    {\n        typedef typename select_most_precise\n            <\n                double,\n                typename coordinate_type<Point>::type\n            >::type sample_type;\n        std::uniform_real_distribution<sample_type> dist(0, accumulated_lengths.back());\n        sample_type r = dist(g);\n        std::size_t i = std::distance(\n            accumulated_lengths.begin(),\n            std::lower_bound(accumulated_lengths.begin(),\n                             accumulated_lengths.end(),\n                             r));\n        std::size_t offset = std::distance(\n            skip_list.begin(),\n            std::lower_bound(skip_list.begin(), skip_list.end(), i));\n\n        return SegmentStrategy::template map\n            <\n                sample_type,\n                domain_point_type\n            >(point_cache[ i + offset - 1 ], point_cache[ i + offset ],\n                ( r - accumulated_lengths[ i - 1 ]) /\n                ( accumulated_lengths[ i ] - accumulated_lengths[ i - 1 ] ));\n    }\n    void reset(DomainGeometry const&) {};\n};\n\nnamespace services {\n\ntemplate\n<\n    typename Point,\n    typename DomainGeometry,\n    typename MultiOrSingle,\n    int Dim,\n    typename CsTag\n>\nstruct default_strategy\n<\n    Point,\n    DomainGeometry,\n    linear_tag,\n    MultiOrSingle,\n    Dim,\n    CsTag\n> : public uniform_linear<Point, DomainGeometry> {\n    typedef uniform_linear<Point, DomainGeometry> base;\n    using base::base;\n};\n\n} // namespace services\n\n}} // namespace strategy::uniform_point_distribution\n\n}} // namespace boost::geometry\n\n#endif //  BOOST_GEOMETRY_EXTENSIONS_RANDOM_STRATEGIES_AGNOSTIC_UNIFORM_LINEAR_HPP\n", "meta": {"hexsha": "c869a685b9264113f6fa1ac78adf7b825b19da41", "size": 4757, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/geometry/extensions/random/strategies/agnostic/uniform_linear.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/random/strategies/agnostic/uniform_linear.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/random/strategies/agnostic/uniform_linear.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": 32.8068965517, "max_line_length": 103, "alphanum_fraction": 0.6535631701, "num_tokens": 1014, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.47898193143759116}}
{"text": "#include <antgame/FoodSource.h>\n#include <antgame/Food.h>\n#include <antgame/World.h>\n\n#include <easyloggingpp/easylogging++.h>\n\n#include <boost/geometry.hpp>\n\n#include <random>\n\nvoid FoodSource::Update(const WorldTree& world) {\n    static std::default_random_engine generator;\n    static size_t totalFoodCounter = 0;\n    static constexpr auto kFoodValue = 20;\n    static constexpr auto kMaxFood = 500;\n\n    int numberOfFood = m_poissonDist(generator);\n    m_numFood += numberOfFood;\n\n    if (m_numFood > kMaxFood) {\n        return;\n    }\n\n    for (size_t i = 0; i < numberOfFood; ++i) {\n        auto x = m_uniformDistX(generator);\n        auto y = m_uniformDistY(generator);\n        Point point(x, y);\n        auto newObj = std::make_shared<Food>(point, \"Food_\" + std::to_string(totalFoodCounter), kFoodValue, this);\n        m_world->AddObject(std::move(newObj));\n    }\n}\n", "meta": {"hexsha": "04f9c89dd1d5e5a21e6e48a6dcc40525356f38a6", "size": 872, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/FoodSource.cpp", "max_stars_repo_name": "maxnoka/AntGame", "max_stars_repo_head_hexsha": "2ac4cb075158832ca7ebabad5e08be4839b99948", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/FoodSource.cpp", "max_issues_repo_name": "maxnoka/AntGame", "max_issues_repo_head_hexsha": "2ac4cb075158832ca7ebabad5e08be4839b99948", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 25.0, "max_issues_repo_issues_event_min_datetime": "2021-05-27T22:26:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-19T21:36:52.000Z", "max_forks_repo_path": "src/FoodSource.cpp", "max_forks_repo_name": "maxnoka/AntGame", "max_forks_repo_head_hexsha": "2ac4cb075158832ca7ebabad5e08be4839b99948", "max_forks_repo_licenses": ["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.25, "max_line_length": 114, "alphanum_fraction": 0.6708715596, "num_tokens": 230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4789819314375911}}
{"text": "/*    Copyright (c) 2010-2018, Delft University of Technology\n *    All rigths reserved\n *\n *    This file is part of the Tudat. Redistribution and use in source and\n *    binary forms, with or without modification, are permitted exclusively\n *    under the terms of the Modified BSD license. You should have received\n *    a copy of the license with this file. If not, please or visit:\n *    http://tudat.tudelft.nl/LICENSE.\n *\n *    References\n *      Press W.H., et al. Numerical Recipes in C++: The Art of Scientific Computing. Cambridge\n *          University Press, February 2002.\n *\n */\n\n#define BOOST_TEST_MAIN\n\n#include <map>\n\n#include <boost/test/unit_test.hpp>\n\n#include <Eigen/Core>\n\n#include \"Tudat/Mathematics/BasicMathematics/nearestNeighbourSearch.h\"\n\nnamespace tudat\n{\nnamespace unit_tests\n{\n\n//! Define Boost test suite.\nBOOST_AUTO_TEST_SUITE( test_basic_functions )\n\n//! Test if search for nearest left neighbor using binary search works correctly.\nBOOST_AUTO_TEST_CASE( testNearestLeftNeighborUsingBinarySearch )\n{\n    using namespace basic_mathematics;\n\n    // Case 1: test Eigen-interface.\n    {\n        // Populate vector of 10 sorted elements.\n        Eigen::VectorXd vectorOfSortedData( 10 );\n        vectorOfSortedData << 1.0, 4.5, 10.6, 14.98, 54.65, 88.9, 101.31, 144.63, 180.01, 201.94;\n\n        // Declare vector of target values.\n        Eigen::VectorXd vectorOfTargetValues( 5 );\n        vectorOfTargetValues << 1.1, 4.6, 10.5, 54.55, 181.63;\n\n        // Declare vector of expected indices.\n        Eigen::VectorXi vectorOfExpectedIndices( 5 );\n        vectorOfExpectedIndices << 0, 1, 1, 3, 8;\n\n        // Compute nearest left neighbors and check if they match expectations.\n        for ( int i = 0; i < vectorOfTargetValues.rows( ); i++ )\n        {\n            BOOST_CHECK_EQUAL(\n                        vectorOfExpectedIndices[ i ],\n                        computeNearestLeftNeighborUsingBinarySearch(\n                            vectorOfSortedData, vectorOfTargetValues[ i ] ) );\n        }\n    }\n\n    // Case 2: test map-interface with VectorXd.\n    {\n        // Populate map of 10 sorted elements.\n        std::map< double, Eigen::VectorXd > mapOfSortedData;\n\n        Eigen::VectorXd vectorOfData( 1 );\n        vectorOfData << 1.0;\n\n        mapOfSortedData[ 0.3 ] = vectorOfData;\n        mapOfSortedData[ 3.65 ] = vectorOfData;\n        mapOfSortedData[ 43.12 ] = vectorOfData;\n        mapOfSortedData[ 2.23 ] = vectorOfData;\n        mapOfSortedData[ 1.233 ] = vectorOfData;\n        mapOfSortedData[ 6.78 ] = vectorOfData;\n        mapOfSortedData[ 0.21 ] = vectorOfData;\n        mapOfSortedData[ -1.23 ] = vectorOfData;\n        mapOfSortedData[ -931.12 ] = vectorOfData;\n        mapOfSortedData[ 124.52 ] = vectorOfData;\n\n        // Declare vector of target values.\n        Eigen::VectorXd vectorOfTargetValues( 5 );\n        vectorOfTargetValues << -1.22, 3.66, -931.11, 43.12, 0.4;\n\n        // Declare vector of expected indices.\n        Eigen::VectorXi vectorOfExpectedIndices( 5 );\n        vectorOfExpectedIndices << 1, 6, 0, 8, 3;\n\n        // Compute nearest left neighbors and check if they match expectations.\n        for ( int i = 0; i < vectorOfTargetValues.rows( ); i++ )\n        {\n            BOOST_CHECK_EQUAL(\n                        vectorOfExpectedIndices[ i ],\n                        computeNearestLeftNeighborUsingBinarySearch(\n                            mapOfSortedData, vectorOfTargetValues[ i ] ) );\n        }\n    }\n\n    // Case 3: test templated STL vector-interface.\n    {\n        // Populate vector of 10 sorted elements.\n        std::vector< double > vectorOfSortedData( 10 );\n        vectorOfSortedData[ 0 ] = 1.0;\n        vectorOfSortedData[ 1 ] = 4.5;\n        vectorOfSortedData[ 2 ] = 10.6;\n        vectorOfSortedData[ 3 ] = 14.98;\n        vectorOfSortedData[ 4 ] = 54.65;\n        vectorOfSortedData[ 5 ] = 88.9;\n        vectorOfSortedData[ 6 ] = 101.31;\n        vectorOfSortedData[ 7 ] = 144.63;\n        vectorOfSortedData[ 8 ] = 180.01;\n        vectorOfSortedData[ 9 ] = 201.94;\n\n        // Declare vector of target values.\n        std::vector< double > vectorOfTargetValues( 5 );\n        vectorOfTargetValues[ 0 ] = 1.1;\n        vectorOfTargetValues[ 1 ] = 4.6;\n        vectorOfTargetValues[ 2 ] = 10.5;\n        vectorOfTargetValues[ 3 ] = 54.55;\n        vectorOfTargetValues[ 4 ] = 181.63;\n\n        // Declare vector of expected indices.\n        std::vector< double > vectorOfExpectedIndices( 5 );\n        vectorOfExpectedIndices[ 0 ] = 0;\n        vectorOfExpectedIndices[ 1 ] = 1;\n        vectorOfExpectedIndices[ 2 ] = 1;\n        vectorOfExpectedIndices[ 3 ] = 3;\n        vectorOfExpectedIndices[ 4 ] = 8;\n\n        // Compute nearest left neighbors and check if they match expectations.\n        for ( int i = 0; i < 5; i++ )\n        {\n            BOOST_CHECK_EQUAL( vectorOfExpectedIndices[ i ],\n             computeNearestLeftNeighborUsingBinarySearch< double >(\n                            vectorOfSortedData, vectorOfTargetValues[ i ] ) );\n        }\n    }\n\n    // Case 4: test templated hunting algorithm ( with STL vector-interface ).\n    {\n        // Populate vector of 10 sorted elements.\n        std::vector< double > vectorOfSortedData( 10 );\n        vectorOfSortedData[ 0 ] = 1.0;\n        vectorOfSortedData[ 1 ] = 4.5;\n        vectorOfSortedData[ 2 ] = 10.6;\n        vectorOfSortedData[ 3 ] = 14.98;\n        vectorOfSortedData[ 4 ] = 54.65;\n        vectorOfSortedData[ 5 ] = 88.9;\n        vectorOfSortedData[ 6 ] = 101.31;\n        vectorOfSortedData[ 7 ] = 144.63;\n        vectorOfSortedData[ 8 ] = 180.01;\n        vectorOfSortedData[ 9 ] = 201.94;\n\n        // Declare vector of target values.\n        std::vector< double > vectorOfTargetValues( 5 );\n        vectorOfTargetValues[ 0 ] = 1.1;\n        vectorOfTargetValues[ 1 ] = 4.6;\n        vectorOfTargetValues[ 2 ] = 10.5;\n        vectorOfTargetValues[ 3 ] = 54.55;\n        vectorOfTargetValues[ 4 ] = 181.63;\n\n        // Declare vector of expected indices.\n        std::vector< double > vectorOfExpectedIndices( 5 );\n        vectorOfExpectedIndices[ 0 ] = 0;\n        vectorOfExpectedIndices[ 1 ] = 1;\n        vectorOfExpectedIndices[ 2 ] = 1;\n        vectorOfExpectedIndices[ 3 ] = 3;\n        vectorOfExpectedIndices[ 4 ] = 8;\n\n        // Compute nearest left neighbors and check if they match expectations.\n        for ( int i = 0; i < 5; i++ )\n        {\n            // Check whether each initial guess yields correct result.\n            for( int j = 0; j < 9; j++ )\n            {\n                BOOST_CHECK_EQUAL( vectorOfExpectedIndices[ i ],\n                    findNearestLeftNeighbourUsingHuntingAlgorithm< double >(\n                    vectorOfTargetValues[ i ], j, vectorOfSortedData ) );\n            }\n        }\n    }\n\n    // Case 5: test Eigen-interface of NearestNeighbourSearch.\n    {\n        // Populate vector of 10 sorted elements.\n        Eigen::VectorXd vectorOfSortedData( 10 );\n        vectorOfSortedData << 1.0, 4.5, 10.6, 14.98, 54.65, 88.9, 101.31, 144.63, 180.01, 201.94;\n\n        // Declare vector of target values.\n        Eigen::VectorXd vectorOfTargetValues( 10 );\n        vectorOfTargetValues << 1.1, 2.74, 2.75, 2.76, 4.6, 10.5, 54.55, 181.63, 200.0, 205.0;\n\n        // Declare vector of expected indices.\n        Eigen::VectorXi vectorOfExpectedIndices( 10 );\n        vectorOfExpectedIndices << 0, 0, 0, 1, 1, 2, 4, 8, 9, 9;\n\n        // Compute nearest left neighbors and check if they match expectations.\n        for ( int i = 0; i < vectorOfTargetValues.rows( ); i++ )\n        {\n            BOOST_CHECK_EQUAL(\n                        vectorOfExpectedIndices[ i ],\n                        computeNearestNeighborUsingBinarySearch(\n                            vectorOfSortedData, vectorOfTargetValues[ i ] ) );\n        }\n    }\n\n}\n\n//! Close Boost test suite.\nBOOST_AUTO_TEST_SUITE_END( )\n\n} // namespace unit_tests\n} // namespace tudat\n", "meta": {"hexsha": "2bbfaa1539e228ca9e9bda1e9175cb3c30b97160", "size": 7900, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Mathematics/BasicMathematics/UnitTests/unitTestNearestNeighbourSearch.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/Mathematics/BasicMathematics/UnitTests/unitTestNearestNeighbourSearch.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/Mathematics/BasicMathematics/UnitTests/unitTestNearestNeighbourSearch.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": 36.7441860465, "max_line_length": 97, "alphanum_fraction": 0.603164557, "num_tokens": 2179, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4789819314375911}}
{"text": "//==================================================================================================\n/*!\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#include <boost/simd/function/scalar/fnma.hpp>\n#include <scalar_test.hpp>\n#include <boost/simd/detail/dispatch/meta/as_integer.hpp>\n\nSTF_CASE_TPL(\" fnma\",  STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  using bs::fnma;\n\n\n  STF_EXPR_IS(fnma(T(),T(),T()), T);\n\n  STF_EQUAL(fnma(T(4),T(2),T(2)) , T(-10));\n  STF_EQUAL(fnma(T(4),T(-2),T(2)), T(6));\n  STF_EQUAL(fnma(T(4),T(2),T(-2)), T(-6));\n  STF_EQUAL(fnma(T(4),T(-2),T(-2)), T(10));\n}\n\n\n", "meta": {"hexsha": "0735979f8ffb04ae9b319c20cafabe506f686f78", "size": 822, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/scalar/fnma.cpp", "max_stars_repo_name": "nickporubsky/boost-simd-clone", "max_stars_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_stars_repo_licenses": ["BSL-1.0"], "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": "test/function/scalar/fnma.cpp", "max_issues_repo_name": "timblechmann/boost.simd", "max_issues_repo_head_hexsha": "2217f1d0102193799469b533e3a7118bf4a77dde", "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/function/scalar/fnma.cpp", "max_forks_repo_name": "timblechmann/boost.simd", "max_forks_repo_head_hexsha": "2217f1d0102193799469b533e3a7118bf4a77dde", "max_forks_repo_licenses": ["BSL-1.0"], "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": 28.3448275862, "max_line_length": 100, "alphanum_fraction": 0.4927007299, "num_tokens": 222, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.47898193143759105}}
{"text": "#pragma once\n\n#include <polyfem/Mesh2D.hpp>\n#include <polyfem/ElementBases.hpp>\n#include <polyfem/ElementAssemblyValues.hpp>\n#include <polyfem/InterfaceData.hpp>\n#include <polyfem/LocalBoundary.hpp>\n\n#include <Eigen/Dense>\n#include <vector>\n#include <map>\n\n\nnamespace polyfem\n{\n\n\tclass MVPolygonalBasis2d\n\t{\n\tpublic:\n\t\tstatic int build_bases(\n\t\t\tconst std::string &assembler_name,\n\t\t\tconst Mesh2D &mesh,\n\t\t\tconst int n_bases,\n\t\t\tconst int quadrature_order,\n\t\t\tstd::vector< ElementBases > &bases,\n\t\t\tconst std::vector< ElementBases > &gbases,\n\t\t\tconst  std::map<int, InterfaceData> &poly_edge_to_data,\n\t\t\tstd::vector<LocalBoundary> &local_boundary,\n\t\t\tstd::map<int, Eigen::MatrixXd> &mapped_boundary);\n\n\t\tstatic void meanvalue(const Eigen::MatrixXd &polygon, const Eigen::RowVector2d &point, Eigen::MatrixXd &b, const double tol);\n\t\tstatic void meanvalue_derivative(const Eigen::MatrixXd &polygon, const Eigen::RowVector2d &point, Eigen::MatrixXd &derivatives, const double tol);\n\t};\n}\n\n", "meta": {"hexsha": "53da3c9cb05fbebbec3cb41aed7c750cf35207ea", "size": 986, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/basis/MVPolygonalBasis2d.hpp", "max_stars_repo_name": "ldXiao/polyfem", "max_stars_repo_head_hexsha": "d4103af16979ff67d461a9ebe46a14bbc4dc8c7c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 228.0, "max_stars_repo_stars_event_min_datetime": "2018-11-23T19:32:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T10:30:51.000Z", "max_issues_repo_path": "src/basis/MVPolygonalBasis2d.hpp", "max_issues_repo_name": "ldXiao/polyfem", "max_issues_repo_head_hexsha": "d4103af16979ff67d461a9ebe46a14bbc4dc8c7c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2019-03-11T22:44:14.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T14:50:35.000Z", "max_forks_repo_path": "src/basis/MVPolygonalBasis2d.hpp", "max_forks_repo_name": "ldXiao/polyfem", "max_forks_repo_head_hexsha": "d4103af16979ff67d461a9ebe46a14bbc4dc8c7c", "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": 27.3888888889, "max_line_length": 148, "alphanum_fraction": 0.7494929006, "num_tokens": 264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.47898193143759105}}
{"text": "#ifndef BLUB_PROCEDURAL_VOXEL_EDIT_NOISE_HPP\n#define BLUB_PROCEDURAL_VOXEL_EDIT_NOISE_HPP\n\n#include \"blub/core/vector.hpp\"\n#include \"blub/math/axisAlignedBox.hpp\"\n#include \"blub/procedural/log/global.hpp\"\n#include \"blub/procedural/voxel/edit/base.hpp\"\n\n#include <boost/function/function2.hpp>\n\n#include <numeric>\n\n\nnamespace blub\n{\nnamespace procedural\n{\nnamespace voxel\n{\nnamespace edit\n{\n\n\n/**\n * @brief The noise class generates a random terrain using simplex noise http://en.wikipedia.org/wiki/Simplex_noise .\n * Original code http://webstaff.itn.liu.se/~stegu/simplexnoise/SimplexNoise.java\n */\ntemplate <class configType>\nclass noise : public base<configType>\n{\npublic:\n    typedef boost::function<bool (vector3, real&)> t_callbackInterpolation;\n\n    typedef configType t_config;\n    typedef base<t_config> t_base;\n    typedef sharedPointer<noise> pointer;\n    typedef typename t_config::t_data t_voxel;\n\n    /**\n     * @brief creates an instance of the class and returns it as shared_ptr<>\n     * @param desc Defines the size in which the terrain should get generated.\n     * @param scale Gets used to scale the voxel-position before calculating the interpolation\n     * @param seed Used before calling std::random_shuffle\n     * @param callbackInterpolation Callback for the generated interpolation.\n     * @return An instance of the class as shared_ptr<>\n     */\n    static pointer create(const blub::axisAlignedBox& desc,\n                          const vector3& scale,\n                          const uint32& seed = 0,\n                          const t_callbackInterpolation& callbackInterpolation = [] (const vector3&, real& value) {value*=1024;return true;})\n    {\n        return pointer(new noise(desc, scale, seed, callbackInterpolation));\n    }\n    /**\n     * @brief ~noise destructor\n     */\n    virtual ~noise()\n    {\n        ;\n    }\n\n    /**\n     * @brief getAxisAlignedBoundingBox returns transformed aab of the to generate voxel\n     * @param trans Transform\n     * @return\n     */\n    blub::axisAlignedBox getAxisAlignedBoundingBox(const transform& trans) const override\n    {\n        return blub::axisAlignedBox(m_aab.getMinimum() + trans.position,\n                                    m_aab.getMaximum() + trans.position);\n    }\n\nprotected:\n    static real fade(const real &t)\n    {\n        return t * t * t * (t * (t * 6 - 15) + 10);\n    }\n    static real lerp(const real& t, const real& a, const real& b)\n    {\n        return a + t * (b - a);\n    }\n    static real grad(const int32& hash, const real& x, const real& y, const real& z) {\n        const int32 h = hash & 15;                      // CONVERT LO 4 BITS OF HASH CODE\n        const real u = h < 8 ? x : y,                   // INTO 12 GRADIENT DIRECTIONS.\n                   v = h < 4 ? y : h == 12 || h == 14 ? x : z;\n        return ((h & 1) == 0 ? u : -u) + ((h & 2) == 0 ? v : -v);\n    }\n    int32 permutation(const int32 index) const\n    {\n        BASSERT(index >= 0);\n        BASSERT(index < 512);\n        return m_permutation[index%256];\n    }\n\n    /**\n     * @brief calculateOneVoxel scales pos by scale set in constructor and calculates the noise.\n     * @param pos absolute voxel-position\n     * @param resultVoxel gets set if interpolation larger -127\n     * @return Returns true if interpolation larger -127\n     */\n    bool calculateOneVoxel(const vector3& pos, t_voxel* resultVoxel) const override\n    {\n        real x(pos.x*m_scale.x);\n        real y(pos.y*m_scale.y);\n        real z(pos.z*m_scale.z);\n\n        const int32 X = static_cast<int32>(math::floor(x)) & 255;                  // FIND UNIT CUBE THAT\n        const int32 Y = static_cast<int32>(math::floor(y)) & 255;                  // CONTAINS POINT.\n        const int32 Z = static_cast<int32>(math::floor(z)) & 255;\n        x -= static_cast<int32>(math::floor(x));                                // FIND RELATIVE X,Y,Z\n        y -= static_cast<int32>(math::floor(y));                                // OF POINT IN CUBE.\n        z -= static_cast<int32>(math::floor(z));\n        const real u = fade(x);                                // COMPUTE FADE CURVES\n        const real v = fade(y);                                // FOR EACH OF X,Y,Z.\n        const real w = fade(z);\n        const int32 A =  permutation(X  )+Y;\n        const int32 AA = permutation(A)+Z;\n        const int32 AB = permutation(A+1)+Z;      // HASH COORDINATES OF\n        const int32 B =  permutation(X+1)+Y;\n        const int32 BA = permutation(B)+Z;\n        const int32 BB = permutation(B+1)+Z;      // THE 8 CUBE CORNERS,\n\n        real resultInterpolation =   lerp(w, lerp(v, lerp(u, grad(permutation(AA  ), x  , y  , z   ),  // AND ADD\n                                                             grad(permutation(BA  ), x-1, y  , z   )), // BLENDED\n                                                     lerp(u, grad(permutation(AB  ), x  , y-1, z   ),  // RESULTS\n                                                             grad(permutation(BB  ), x-1, y-1, z   ))),// FROM  8\n                                             lerp(v, lerp(u, grad(permutation(AA+1), x  , y  , z-1 ),  // CORNERS\n                                                             grad(permutation(BA+1), x-1, y  , z-1 )), // OF CUBE\n                                                     lerp(u, grad(permutation(AB+1), x  , y-1, z-1 ),\n                                                             grad(permutation(BB+1), x-1, y-1, z-1 ))));\n        if (!m_callbackInterpolation(pos, resultInterpolation))\n        {\n            return false;\n        }\n        const int8 resultCasted(static_cast<int8>(math::clamp<real>(resultInterpolation, -127., 127.)));\n\n        resultVoxel->setInterpolation(resultCasted);\n\n        return true;\n    }\n\n\n    /**\n     * @brief noise Contructor - same as create()\n     */\n    noise(const blub::axisAlignedBox& desc, const vector3& scale, const uint32& seed, const t_callbackInterpolation &callbackInterpolation)\n        : m_aab(desc)\n        , m_scale(scale)\n        , m_callbackInterpolation(callbackInterpolation)\n        , m_permutation(256)\n    {\n        std::srand(seed);\n        std::iota(m_permutation.begin(), m_permutation.end(), 0);\n        std::random_shuffle(m_permutation.begin(), m_permutation.end());\n    }\n\nprotected:\n    const blub::axisAlignedBox m_aab;\n    const vector3 m_scale;\n    const t_callbackInterpolation m_callbackInterpolation;\n\n    vector<uint8_t> m_permutation;\n\n};\n\n\n}\n}\n}\n}\n\n\n#endif // BLUB_PROCEDURAL_VOXEL_EDIT_NOISE_HPP\n", "meta": {"hexsha": "11d2761642b6e9f592a8ddbdc24c9f89f38a6ee7", "size": 6494, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/procedural/source/blub/procedural/voxel/edit/noise.hpp", "max_stars_repo_name": "qwertzui11/voxelTerrain", "max_stars_repo_head_hexsha": "05038fb261893dd044ae82fab96b7708ea5ed623", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 96.0, "max_stars_repo_stars_event_min_datetime": "2015-02-02T20:01:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T20:33:29.000Z", "max_issues_repo_path": "modules/procedural/source/blub/procedural/voxel/edit/noise.hpp", "max_issues_repo_name": "qwertzui11/voxelTerrain", "max_issues_repo_head_hexsha": "05038fb261893dd044ae82fab96b7708ea5ed623", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2016-06-04T15:45:30.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-04T11:10:51.000Z", "max_forks_repo_path": "modules/procedural/source/blub/procedural/voxel/edit/noise.hpp", "max_forks_repo_name": "qwertzui11/voxelTerrain", "max_forks_repo_head_hexsha": "05038fb261893dd044ae82fab96b7708ea5ed623", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19.0, "max_forks_repo_forks_event_min_datetime": "2015-09-22T01:21:45.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-30T09:52:27.000Z", "avg_line_length": 37.3218390805, "max_line_length": 141, "alphanum_fraction": 0.5677548506, "num_tokens": 1611, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.47898193143759105}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   DataGen_FreeGasElasticMarginalAlphaFunction.hpp\n//! \\author Alex Robinson\n//! \\brief  Free gas elastic marginal alpha function definition.\n//!\n//---------------------------------------------------------------------------//\n\n// Boost Includes\n#include <boost/function.hpp>\n#include <boost/bind.hpp>\n\n// FRENSIE Includes\n#include \"DataGen_FreeGasElasticMarginalAlphaFunction.hpp\"\n#include \"Utility_SearchAlgorithms.hpp\"\n#include \"MonteCarlo_KinematicHelpers.hpp\"\n#include \"Utility_DesignByContract.hpp\"\n\nnamespace DataGen{\n\n// Constructor\nFreeGasElasticMarginalAlphaFunction::FreeGasElasticMarginalAlphaFunction(\n          const std::shared_ptr<Utility::UnivariateDistribution>&\n          zero_temp_elastic_cross_section,\n          const std::shared_ptr<MonteCarlo::NuclearScatteringAngularDistribution>&\n          cm_scattering_distribution,\n          const double A,\n          const double kT,\n          const double beta,\n          const double E )\n  : d_gkq_set( 1e-4 ),\n    d_sab_function( zero_temp_elastic_cross_section,\n                    cm_scattering_distribution,\n                    A,\n                    kT ),\n    d_beta( beta ),\n    d_E( E ),\n    d_alpha_min( 0.0 ),\n    d_alpha_max( 0.0 ),\n    d_norm_constant( 1.0 ),\n    d_cached_cdf_values()\n{\n  // Make sure the values are valid\n  testPrecondition( A > 0.0 );\n  testPrecondition( kT > 0.0 );\n  testPrecondition( E > 0.0 );\n  testPrecondition( beta > MonteCarlo::calculateBetaMin( E, kT ) );\n\n  updateCachedValues();\n}\n\n// Set the beta and energy values\nvoid FreeGasElasticMarginalAlphaFunction::setIndependentVariables(\n                                                             const double beta,\n                                                             const double E )\n{\n  // Make sure beta is valid\n  remember( double kT = d_sab_function.getTemperature() );\n  testPrecondition( beta > MonteCarlo::calculateBetaMin( E, kT ) );\n\n  d_beta = beta;\n  d_E = E;\n\n  updateCachedValues();\n}\n\n// Get the lower alpha limit\ndouble FreeGasElasticMarginalAlphaFunction::getAlphaMin() const\n{\n  return d_alpha_min;\n}\n\n// Get the upper alpha limit\ndouble FreeGasElasticMarginalAlphaFunction::getAlphaMax() const\n{\n  return d_alpha_max;\n}\n\n// Get the normalization constant\ndouble FreeGasElasticMarginalAlphaFunction::getNormalizationConstant() const\n{\n  return d_norm_constant;\n}\n\n// Evaluate the marginal PDF\ndouble FreeGasElasticMarginalAlphaFunction::operator()( const double alpha )\n{\n  // Make sure the alpha value is valid\n  testPrecondition( alpha >= d_alpha_min );\n  testPrecondition( alpha <= d_alpha_max );\n\n  return d_sab_function( alpha, d_beta, d_E )/d_norm_constant;\n}\n\n// Evaluate the marginal CDF\ndouble FreeGasElasticMarginalAlphaFunction::evaluateCDF( const double alpha )\n{\n  // Make sure the alpha value is valid\n  testPrecondition( alpha >= d_alpha_min );\n  testPrecondition( alpha <= d_alpha_max );\n\n  // Find nearest cached evaluation of cdf\n  std::list<std::pair<double,double> >::iterator lower_cdf_point =\n    d_cached_cdf_values.begin();\n\n  lower_cdf_point = Utility::Search::binaryLowerBound<Utility::FIRST>(\n                                                     lower_cdf_point,\n                                                     d_cached_cdf_values.end(),\n                                                     alpha );\n\n  // Calculate the cdf value\n  double cdf_value, cdf_value_error;\n\n  d_gkq_set.integrateAdaptively<15>( *this,\n                                    lower_cdf_point->first,\n                                    alpha,\n                                    cdf_value,\n                                    cdf_value_error );\n\n  cdf_value += lower_cdf_point->second;\n\n  // Cache the new cdf value\n  std::pair<double,double> new_cdf_point(alpha, cdf_value );\n\n  d_cached_cdf_values.insert( ++lower_cdf_point, new_cdf_point );\n\n  // Return the calculated cdf value\n  return cdf_value;\n}\n\n// Update cached values\nvoid FreeGasElasticMarginalAlphaFunction::updateCachedValues()\n{\n  // Calculate the alpha limits\n  double A = d_sab_function.getAtomicWeightRatio();\n  double kT = d_sab_function.getTemperature();\n\n  d_alpha_min = MonteCarlo::calculateAlphaMin( d_E, d_beta, A, kT );\n\n  d_alpha_max = MonteCarlo::calculateAlphaMax( d_E, d_beta, A, kT );\n\n  // Calculate the norm constant\n  double norm_constant_error;\n\n  boost::function<double (double alpha)> sab_function_wrapper =\n    boost::bind<double>( d_sab_function, _1, d_beta, d_E );\n\n  d_gkq_set.integrateAdaptively<15>( sab_function_wrapper,\n                                    d_alpha_min,\n                                    d_alpha_max,\n                                    d_norm_constant,\n                                    norm_constant_error );\n\n  // Reset the cached cdf values\n  d_cached_cdf_values.clear();\n\n  // Add cdf point at alpha min\n  d_cached_cdf_values.push_back( std::make_pair(d_alpha_min, 0.0) );\n\n  // Add cdf point at alpha max\n  d_cached_cdf_values.push_back( std::make_pair(d_alpha_max, 1.0) );\n}\n\n} // end DataGen namespace\n\n//---------------------------------------------------------------------------//\n// end DataGen_FreeGasElasticMarginalAlphaFunction.cpp\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "5e9458f7b20a4718ffefef3e1f5c0d7251b50c4e", "size": 5318, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "packages/data_gen/free_gas_sab/src/DataGen_FreeGasElasticMarginalAlphaFunction.cpp", "max_stars_repo_name": "bam241/FRENSIE", "max_stars_repo_head_hexsha": "e1760cd792928699c84f2bdce70ff54228e88094", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2019-11-14T19:58:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-04T17:44:09.000Z", "max_issues_repo_path": "packages/data_gen/free_gas_sab/src/DataGen_FreeGasElasticMarginalAlphaFunction.cpp", "max_issues_repo_name": "bam241/FRENSIE", "max_issues_repo_head_hexsha": "e1760cd792928699c84f2bdce70ff54228e88094", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 43.0, "max_issues_repo_issues_event_min_datetime": "2020-03-03T19:59:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-08T03:36:08.000Z", "max_forks_repo_path": "packages/data_gen/free_gas_sab/src/DataGen_FreeGasElasticMarginalAlphaFunction.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": 31.4674556213, "max_line_length": 82, "alphanum_fraction": 0.6130124107, "num_tokens": 1179, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683105, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.4789478451303961}}
{"text": "\n#include <iostream>\n#include <Eigen/Dense>\n#include <Eigen/LU>\n#include <Eigen/QR>\n#include <manifold/SO3.h>\n\nstd::vector<Eigen::Matrix3f> Gs_;\nfloat tau_R_;\nEigen::Matrix3f Sigma_t_;\n\nstruct Stats {\n  uint32_t N;\n  Eigen::Vector3f sum;\n  Eigen::Matrix3f outer;\n  void reset(double regularize) {\n    N = 0;\n    sum.fill(0.);\n    outer = Eigen::Matrix3f::Identity()*regularize;\n  }\n  void add(const Eigen::Vector3f& x) {\n    ++N;\n    sum += x;\n    outer += x*x.transpose();\n  }\n};\n\nEigen::Matrix<float,6,1> OdomJacobian(\n  const Eigen::Vector3f& t, const Eigen::Vector3f& t_prev,\n  const Eigen::Matrix3f& R, const Eigen::Matrix3f& R_prev) {\n\n  Eigen::Matrix<float,6,1> J;\n  J.topRows<3>() = Sigma_t_.ldlt().solve(t-t_prev);\n  for (uint32_t l=0; l<3; ++l)\n    J(l+3) = -tau_R_*(R_prev.transpose()*Gs_[l]*R).trace();\n  return J;\n}\n\nEigen::Matrix<float,6,6> OdomHessian(\n  const Eigen::Vector3f& t, const Eigen::Vector3f& t_prev,\n  const Eigen::Matrix3f& R, const Eigen::Matrix3f& R_prev) {\n  Eigen::Matrix<float,6,6> H = Eigen::Matrix<float,6,6>::Zero();\n  H.topLeftCorner<3,3>() = Sigma_t_.inverse();\n  for (uint32_t l=0; l<3; ++l) for (uint32_t m=0; m<3; ++m) {\n    Eigen::Matrix3f Glmml = (Gs_[l]*Gs_[m] + Gs_[m]*Gs_[l]);\n    H(l+3,m+3) = -0.5*tau_R_*(R_prev.transpose()*Glmml*R).trace();\n  }\n  return H;\n};\n\nvoid AddObsHessian(\n  const Eigen::Vector3f& x,\n  const Eigen::Vector3f& y,\n  const Eigen::Matrix3f& covInv,\n  double w,\n  Eigen::Matrix<float,6,6>& H) {\n\n  H.topLeftCorner<3,3>() += w*covInv;\n\n  for (uint32_t m=0; m<3; ++m) {\n    H.block<3,1>(0,m+3) += w*covInv*Gs_[m]*y;\n  }\n\n  for (uint32_t l=0; l<3; ++l) for (uint32_t m=0; m<3; ++m) {\n    Eigen::Matrix3f Glmml = (Gs_[l]*Gs_[m] + Gs_[m]*Gs_[l]);\n    H(l+3,m+3) += w*(-y.dot(Gs_[l]*covInv*Gs_[m]*y)\n//        + 2.*y.dot(covInv*Glmml*y) \n        +0.5*x.dot(covInv*Glmml*y));\n  }\n  H.bottomLeftCorner<3,3>() = H.topRightCorner<3,3>().transpose();\n}\n\nvoid AddClusterHessian(\n    const Stats& ss,\n    const Eigen::Matrix3f& R,\n    const Eigen::Matrix3f& covInv,\n    const Eigen::LDLT<Eigen::Matrix3f>& covLdlt,\n    const Eigen::Vector3f& a,\n    Eigen::Matrix<float,6,6>& H) {\n\n  H.topLeftCorner<3,3>() += ss.N*covInv;\n  for (uint32_t m=0; m<3; ++m) {\n    H.block<3,1>(0,m+3) += covLdlt.solve(Gs_[m]*R*ss.sum);\n  }\n  Eigen::Matrix3f Hw;\n  for (uint32_t l=0; l<3; ++l) for (uint32_t m=0; m<3; ++m) {\n    Eigen::Matrix3f Glmml = (Gs_[l]*Gs_[m]+Gs_[m]*Gs_[l]);\n//    H(l+3,m+3) += \n    Hw(l,m) = 0.5*(R*ss.outer*R.transpose()*(covLdlt.solve(Glmml)\n          -2.*Gs_[l]*covLdlt.solve(Gs_[m]))).trace()\n      +0.5*a.dot(covLdlt.solve(Glmml*R*ss.sum));\n  }\n//  std::cout << Hw << std::endl;\n  H.bottomRightCorner<3,3>() += Hw;\n  H.bottomLeftCorner<3,3>() = H.topRightCorner<3,3>().transpose();\n}\n\nvoid AddObsJacobian( const Eigen::Vector3f& x, const Eigen::Vector3f&\n    y, const Eigen::Matrix3f& covInv, float w,\n    Eigen::Matrix<float,6,1>& J) {\n  J.topRows<3>() += w*covInv*x;\n  for (uint32_t l=0; l<3; ++l)\n    J(l+3) += w*x.dot(covInv*Gs_[l]*y);\n}\nvoid AddClusterJacobian(\n    const Stats& ss,\n    const Eigen::Matrix3f& R,\n    const Eigen::LDLT<Eigen::Matrix3f>& covLdlt,\n    const Eigen::Vector3f& a,\n    Eigen::Matrix<float,6,1>& J) {\n\n  J.topRows<3>() += covLdlt.solve(R*ss.sum + ss.N*a);\n  for (uint32_t l=0; l<3; ++l)\n    J(l+3) += (R*ss.outer*R.transpose()*covLdlt.solve(Gs_[l])).trace()\n      + a.dot(covLdlt.solve(Gs_[l]*R*ss.sum));\n}\n\nint main (int argc, char** argv) {\n\n  Gs_ = std::vector<Eigen::Matrix3f>(3,Eigen::Matrix3f::Zero());\n  // so(3) generators\n  Gs_[0](1,2) = -1;\n  Gs_[0](2,1) = 1;\n  Gs_[1](0,2) = 1;\n  Gs_[1](2,0) = -1;\n  Gs_[2](0,1) = -1;\n  Gs_[2](1,0) = 1;\n  // Basically ignore priors\n  tau_R_ = 0.00001;\n  Sigma_t_ = 10000.*Eigen::Matrix3f::Identity();\n\n  uint32_t K = 4;\n  uint32_t N = 40;\n  \n  double theta0 = 0.*M_PI/180.;\n  Eigen::Matrix3f Rmu;\n  Rmu << 1, 0, 0,\n         0, cos(theta0), sin(theta0),\n         0, -sin(theta0), cos(theta0);\n  Eigen::Matrix3f R = Rmu;\n  Eigen::Matrix3f covInv = 0.01*Eigen::Matrix3f::Identity(); \n\n  Eigen::Vector3f t(0,0,0.);\n  Eigen::Vector3f t_prev(0,0,0);\n\n  std::vector<Eigen::Vector3f> mus; \n  mus.push_back(Eigen::Vector3f(1.,0.,0.));\n  mus.push_back(Eigen::Vector3f(0.,1.,0.));\n  mus.push_back(Eigen::Vector3f(0.,0.,1.));\n  mus.push_back(Eigen::Vector3f(0.3,0.3,0.3));\n\n  double theta = 15.*M_PI/180.;\n  double phi = 25*M_PI/180.;\n  std::vector<Eigen::Vector3f> ps; \n  std::vector<uint32_t> zs;\n  Eigen::Vector3f t_true = Eigen::Vector3f(0.1,.1,0.1);\n  Eigen::Matrix3f R_true;\n  R_true << 1, 0, 0,\n            0,  cos(theta), sin(theta),\n            0, -sin(theta), cos(theta);\n  Eigen::Matrix3f R2;\n  R2     << cos(phi),  0,  sin(phi),\n            0,           1., 0,\n            -sin(phi), 0,  cos(phi);\n  R_true *= R2;\n//  R_true << sin(theta)*cos(phi), cos(theta)*cos(phi), -sin(phi),\n//            sin(theta)*sin(phi), cos(theta)*sin(phi), cos(phi),\n//            cos(theta), -sin(theta), 0.;\n\n  for (uint32_t i=0; i<N/K; ++i) {\n    ps.push_back(Eigen::Vector3f(1.,0,0));\n    ps.back() = R_true*ps.back() + t_true;\n    ps.push_back(Eigen::Vector3f(0,1.,0.));\n    ps.back() = R_true*ps.back() + t_true;\n    ps.push_back(Eigen::Vector3f(0,0.,1.));\n    ps.back() = R_true*ps.back() + t_true;\n    ps.push_back(Eigen::Vector3f(0.3,0.3,0.3));\n    ps.back() = R_true*ps.back() + t_true;\n    zs.push_back(0);\n    zs.push_back(1);\n    zs.push_back(2);\n    zs.push_back(3);\n  }\n\n  std::vector<Stats> ss(K);\n  for (uint32_t k=0; k<K; ++k) ss[k].reset(0.);\n  for (uint32_t i=0; i<N; ++i) {\n    ss[zs[i]].add(ps[i]); \n  }\n  for (uint32_t k=0; k<K; ++k) {\n    std::cout << k <<  std::endl;\n    std::cout << ss[k].N << std::endl;\n    std::cout << ss[k].sum.transpose() << std::endl;\n    std::cout << ss[k].outer << std::endl;\n  }\n  Eigen::LDLT<Eigen::Matrix3f> covLdlt(covInv.inverse());\n\n  std::cout << \"Using SO(3) formulation first order -------------------\" \n    << std::endl;\n\n  R = Rmu;\n  t.fill(0);\n  float delta = 1.;\n  float f_prev = 1e99;\n  float f = -tau_R_*(Rmu.transpose()*R).trace()\n    + 0.5*(t - t_prev).dot(Sigma_t_.ldlt().solve(t-t_prev));\n  for (uint32_t i=0; i<N; ++i) {\n    const Eigen::Vector3f x = R*ps[i]+t-mus[zs[i]];\n    f += 0.5*x.dot(covInv*x);\n  }\n  std::cout << \"f=\" << f << std::endl;\n  for (uint32_t it=0; it<100000; ++it) {\n    Eigen::Matrix<float,6,1> J = OdomJacobian(t, t_prev, R, Rmu);\n    for (uint32_t i=0; i<N; ++i) {\n      const Eigen::Vector3f y = R*ps[i];\n      const Eigen::Vector3f x = y+t-mus[zs[i]];\n      AddObsJacobian(x,y,covInv,1.,J);\n    }\n    J = -delta*J;\n\n    t = t + J.topRows<3>();\n    Eigen::Vector3f Jw = J.bottomRows<3>();\n    SO3f R_(R);\n    R = (R_ + Jw).matrix();\n\n    f_prev = f;\n    f = -tau_R_*(Rmu.transpose()*R).trace()\n      + 0.5*(t - t_prev).dot(Sigma_t_.ldlt().solve(t-t_prev));\n    for (uint32_t i=0; i<N; ++i) {\n      const Eigen::Vector3f x = R*ps[i]+t-mus[zs[i]];\n      f += 0.5*x.dot(covInv*x);\n    }\n    if (it%100==0)\n      std::cout << \"@\" << it << \": f=\" << f << \" df/f=\" << (f_prev - f)/fabs(f) << std::endl;\n    if ((f_prev - f)/fabs(f) < 1e-9) \n      break;\n  }\n\n  std::cout << \" -- d angle \" << acos(((R*R_true).trace()-1)*0.5)*180./M_PI \n            << \" |dt| \" << (t_true - (-R.transpose()*t)).sum() << std::endl;\n  std::cout << std::endl << R << std::endl;\n  std::cout << \"t \" << std::endl << t.transpose() << std::endl;\n  std::cout << acos(R.matrix()(1,1))*180/M_PI << std::endl;\n  std::cout << \"inverses\" << std::endl;\n  std::cout << R.transpose() << std::endl;\n  std::cout << \"t \" << (-R.transpose()*t).transpose() << std::endl;\n  std::cout << \"true\" << std::endl;\n  std::cout << R_true << std::endl;\n  std::cout << \"t \" << t_true.transpose() << std::endl;\n\n  std::cout << \"Using SO(3) formulation first order SS -------------------\" \n    << std::endl;\n\n  R = Rmu;\n  t.fill(0);\n  delta = 1.;\n  f_prev = 1e99;\n  f = -tau_R_*(Rmu.transpose()*R).trace()\n    + 0.5*(t - t_prev).dot(Sigma_t_.ldlt().solve(t-t_prev));\n  for (uint32_t i=0; i<N; ++i) {\n    const Eigen::Vector3f x = R*ps[i]+t-mus[zs[i]];\n    f += 0.5*x.dot(covInv*x);\n  }\n  std::cout << \"f=\" << f << std::endl;\n  for (uint32_t it=0; it<100000; ++it) {\n    Eigen::Matrix<float,6,1> J = OdomJacobian(t, t_prev, R, Rmu);\n    for (uint32_t k=0; k<K; ++k) {\n      const Eigen::Vector3f a = t-mus[k];\n      AddClusterJacobian(ss[k],R,covLdlt,a,J);\n    }\n    J = -delta*J;\n\n    t = t + J.topRows<3>();\n    Eigen::Vector3f Jw = J.bottomRows<3>();\n    SO3f R_(R);\n    R = (R_ + Jw).matrix();\n\n    f_prev = f;\n    f = -tau_R_*(Rmu.transpose()*R).trace()\n      + 0.5*(t - t_prev).dot(Sigma_t_.ldlt().solve(t-t_prev));\n    for (uint32_t i=0; i<N; ++i) {\n      const Eigen::Vector3f x = R*ps[i]+t-mus[zs[i]];\n      f += 0.5*x.dot(covInv*x);\n    }\n    if (it%100==0)\n      std::cout << \"@\" << it << \": f=\" << f << \" df/f=\" << (f_prev - f)/fabs(f) << std::endl;\n    if ((f_prev - f)/fabs(f) < 1e-9) \n      break;\n  }\n\n  std::cout << \" -- d angle \" << acos(((R*R_true).trace()-1)*0.5)*180./M_PI \n            << \" |dt| \" << (t_true - (-R.transpose()*t)).sum() << std::endl;\n  std::cout << std::endl << R << std::endl;\n  std::cout << \"t \" << std::endl << t.transpose() << std::endl;\n  std::cout << acos(R.matrix()(1,1))*180/M_PI << std::endl;\n  std::cout << \"inverses\" << std::endl;\n  std::cout << R.transpose() << std::endl;\n  std::cout << \"t \" << (-R.transpose()*t).transpose() << std::endl;\n  std::cout << \"true\" << std::endl;\n  std::cout << R_true << std::endl;\n  std::cout << \"t \" << t_true.transpose() << std::endl;\n\n  std::cout << \"Using SO(3) formulation second order -------------------\"\n    << std::endl;\n  R = Rmu;\n  t.fill(0);\n  delta = 0.5;\n  f_prev = 1e99;\n  f = -tau_R_*(Rmu.transpose()*R).trace()\n    + 0.5*(t - t_prev).dot(Sigma_t_.ldlt().solve(t-t_prev));\n  for (uint32_t i=0; i<N; ++i) {\n    const Eigen::Vector3f x = R*ps[i]+t-mus[zs[i]];\n    f += 0.5*x.dot(covInv*x);\n  }\n  std::cout << \"f=\" << f << std::endl;\n  Eigen::Vector3f tPrev = t;\n  Eigen::Matrix3f RPrev = R;\n  for (uint32_t it=0; it<2000; ++it) {\n    Eigen::Matrix<float,6,1> J = OdomJacobian(t, t_prev, R, Rmu);\n    Eigen::Matrix<float,6,6> H = OdomHessian(t, t_prev, R, Rmu);\n    for (uint32_t i=0; i<N; ++i) {\n      const Eigen::Vector3f y = R*ps[i];\n      const Eigen::Vector3f x = y+t-mus[zs[i]];\n      AddObsJacobian(x,y,covInv,1.,J);\n      AddObsHessian(x,y,covInv,1.,H);\n    }\n    if(it < 10) {\n      std::cout << J.transpose() << std::endl;\n      std::cout << H << std::endl;\n      std::cout << - H.ldlt().solve(J).transpose() << std::endl;\n    }\n//    std::cout << H << std::endl;\n//    std::cout << \"J \" << J.transpose() << std::endl;\n    J = - delta*H.ldlt().solve(J);\n//    std::cout << \"dx \" << J.transpose() << std::endl;\n\n    RPrev = R;\n    tPrev = t;\n\n    t = t + J.topRows<3>();\n    Eigen::Vector3f Jw = J.bottomRows<3>();\n    SO3f R_(R);\n    R = (R_ + Jw).matrix();\n    \n    f_prev = f;\n    f = -tau_R_*(Rmu.transpose()*R).trace()\n      + 0.5*(t - t_prev).dot(Sigma_t_.ldlt().solve(t-t_prev));\n    for (uint32_t i=0; i<N; ++i) {\n      const Eigen::Vector3f x = R*ps[i]+t-mus[zs[i]];\n      f += 0.5*x.dot(covInv*x);\n    }\n    if (it%100==0) \n      std::cout << \"@\" << it << \": f=\" << f << \" df/f=\" << (f_prev - f)/fabs(f) << std::endl;\n    if ((f_prev - f)/fabs(f) < 1e-9) {\n      std::cout << \"@\" << it << \": f=\" << f << \" f_prev=\" << f_prev << \" df/f=\" << (f_prev - f)/fabs(f) << std::endl;\n      break;\n    }\n  }\n  if (f_prev < f) {\n    R = RPrev; \n    t = tPrev;\n  }\n  std::cout << \" -- d angle \" << acos(((R*R_true).trace()-1)*0.5)*180./M_PI \n            << \" |dt| \" << (t_true - (-R.transpose()*t)).sum() << std::endl;\n  std::cout << std::endl << R << std::endl;\n  std::cout << \"t \" << t.transpose() << std::endl;\n  std::cout << acos(R.matrix()(1,1))*180/M_PI << std::endl;\n\n  std::cout << \"inverses\" << std::endl;\n  std::cout << R.transpose() << std::endl;\n  std::cout << \"t \" << (-R.transpose()*t).transpose() << std::endl;\n  std::cout << \"true\" << std::endl;\n  std::cout << R_true << std::endl;\n  std::cout << \"t \" << t_true.transpose() << std::endl;\n\n  std::cout << \"Using SO(3) formulation second order using SS -------------------\" \n    << std::endl;\n  R = Rmu;\n  t.fill(0);\n  delta = 0.5;\n  f_prev = 1e99;\n  f = -tau_R_*(Rmu.transpose()*R).trace()\n    + 0.5*(t - t_prev).dot(Sigma_t_.ldlt().solve(t-t_prev));\n  for (uint32_t i=0; i<N; ++i) {\n    const Eigen::Vector3f x = R*ps[i]+t-mus[zs[i]];\n    f += 0.5*x.dot(covInv*x);\n  }\n  std::cout << \"f=\" << f << std::endl;\n  tPrev = t;\n  RPrev = R;\n  std::cout << \" -- d angle \" << acos(((R*R_true).trace()-1)*0.5)*180./M_PI \n    << \" |dt| \" << (t_true - (-R.transpose()*t)).sum() << std::endl;\n  for (uint32_t it=0; it<2000; ++it) {\n    Eigen::Matrix<float,6,1> J = OdomJacobian(t, t_prev, R, Rmu);\n    Eigen::Matrix<float,6,6> H = OdomHessian(t, t_prev, R, Rmu);\n    for (uint32_t k=0; k<K; ++k) {\n      const Eigen::Vector3f a = t-mus[k];\n      AddClusterJacobian(ss[k],R,covLdlt,a,J);\n      AddClusterHessian(ss[k],R,covInv,covLdlt,a,H);\n    }\n    if(it < 10) {\n      std::cout << J.transpose() << std::endl;\n      std::cout << H << std::endl;\n      std::cout << - H.ldlt().solve(J).transpose() << std::endl;\n    }\n//    std::cout << H << std::endl;\n//    std::cout << \"J \" << J.transpose() << std::endl;\n    J = - delta*H.ldlt().solve(J);\n//    std::cout << \"dx \" << J.transpose() << std::endl;\n\n    RPrev = R;\n    tPrev = t;\n\n    t = t + J.topRows<3>();\n    Eigen::Vector3f Jw = J.bottomRows<3>();\n    SO3f R_(R);\n    R = (R_ + Jw).matrix();\n    \n    f_prev = f;\n    f = -tau_R_*(Rmu.transpose()*R).trace()\n      + 0.5*(t - t_prev).dot(Sigma_t_.ldlt().solve(t-t_prev));\n    for (uint32_t i=0; i<N; ++i) {\n      const Eigen::Vector3f x = R*ps[i]+t-mus[zs[i]];\n      f += 0.5*x.dot(covInv*x);\n    }\n    if (it%1==0) {\n      std::cout << \"@\" << it << \": f=\" << f << \" df/f=\" << (f_prev - f)/fabs(f) << std::endl;\n      std::cout << \" -- d angle \" << acos(std::min(1.,((R*R_true).trace()-1)*0.5))*180./M_PI \n        << \" |dt| \" << (t_true - (-R.transpose()*t)).sum() << std::endl;\n    }\n    if ((f_prev - f)/fabs(f) < 1e-9) {\n      std::cout << \"@\" << it << \": f=\" << f << \" f_prev=\" << f_prev << \" df/f=\" << (f_prev - f)/fabs(f) << std::endl;\n      break;\n    }\n  }\n  if (f_prev < f) {\n    R = RPrev; \n    t = tPrev;\n  }\n  std::cout << \" -- d angle \" << acos(((R*R_true).trace()-1)*0.5)*180./M_PI \n            << \" |dt| \" << (t_true - (-R.transpose()*t)).sum() << std::endl;\n  std::cout << std::endl << R << std::endl;\n  std::cout << \"t \" << t.transpose() << std::endl;\n  std::cout << acos(R.matrix()(1,1))*180/M_PI << std::endl;\n\n  std::cout << \"inverses\" << std::endl;\n  std::cout << R.transpose() << std::endl;\n  std::cout << \"t \" << (-R.transpose()*t).transpose() << std::endl;\n  std::cout << \"true\" << std::endl;\n  std::cout << R_true << std::endl;\n  std::cout << \"t \" << t_true.transpose() << std::endl;\n\n}\n", "meta": {"hexsha": "25663caf1f4d4e97b00f1c89b47c1421108d6676", "size": 14828, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/SO3_gmm.cpp", "max_stars_repo_name": "jstraub/tdp", "max_stars_repo_head_hexsha": "dcab53662be5b88db1538cf831707b07ab96e387", "max_stars_repo_licenses": ["MIT-feh"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-10-17T19:25:47.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-17T19:25:47.000Z", "max_issues_repo_path": "test/SO3_gmm.cpp", "max_issues_repo_name": "jstraub/tdp", "max_issues_repo_head_hexsha": "dcab53662be5b88db1538cf831707b07ab96e387", "max_issues_repo_licenses": ["MIT-feh"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-05-02T06:04:06.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-02T06:04:06.000Z", "max_forks_repo_path": "test/SO3_gmm.cpp", "max_forks_repo_name": "jstraub/tdp", "max_forks_repo_head_hexsha": "dcab53662be5b88db1538cf831707b07ab96e387", "max_forks_repo_licenses": ["MIT-feh"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2017-09-17T18:46:20.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-11T12:52:57.000Z", "avg_line_length": 32.6607929515, "max_line_length": 117, "alphanum_fraction": 0.5289317507, "num_tokens": 5681, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4789478409040162}}
{"text": "#include <Eigen/Core>\n\n#include <igl/readOBJ.h>\n#include <igl/point_mesh_squared_distance.h>\n\nextern \"C\" {\n\nEigen::MatrixXd V1, V2;\nEigen::MatrixXi F1, F2;\nvoid LoadObj(const char* filename, int mesh_id) {\n    if (mesh_id == 1)\n        igl::readOBJ(filename, V1, F1);\n    else\n        igl::readOBJ(filename, V2, F2);\n}\n\ndouble OneWayChamferDistance(const Eigen::MatrixXd& V1,\n    const Eigen::MatrixXi& F1,\n    const Eigen::MatrixXd& V2,\n    const Eigen::MatrixXi& F2,\n    int resample_points) {\n    Eigen::VectorXd sqrD;\n    Eigen::VectorXi I;\n    Eigen::MatrixXd C;\n    if (resample_points) {\n        \n        std::vector<double> areas(F1.rows() + 1, 0);\n        double total_area = 0;\n        for (int i = 0; i < F1.rows(); ++i) {\n            const Eigen::Vector3d& v1 = V1.row(F1(i, 0));\n            const Eigen::Vector3d& v2 = V1.row(F1(i, 1));\n            const Eigen::Vector3d& v3 = V1.row(F1(i, 2));\n            double area = ((v2 - v1).cross(v3 - v1)).norm();\n            areas[i + 1] = area;\n            total_area += area;\n        }\n        for (int i = 1; i < areas.size(); ++i)\n            areas[i] += areas[i - 1];\n        \n        Eigen::MatrixXd NV(resample_points, 3);\n        for (int i = 0; i < resample_points; ++i) {\n            double r = rand() / (double)RAND_MAX * areas.back();\n            auto lower = std::lower_bound(areas.begin(), areas.end(), r) - 1;\n            int tri_idx = lower - areas.begin();\n            if (tri_idx < 0) {\n                tri_idx = 0;\n            }\n            double u = rand() / (double)RAND_MAX;\n            double v = rand() / (double)RAND_MAX;\n            if (u + v > 1) {\n                u = 1 - u;\n                v = 1 - v;\n            }\n            auto v1 = V1.row(F1(tri_idx, 0));\n            auto v2 = V1.row(F1(tri_idx, 1));\n            auto v3 = V1.row(F1(tri_idx, 2));\n\n            NV.row(i) = u * (v2 - v1) + v * (v3 - v1) + v1;\n        }\n        igl::point_mesh_squared_distance(NV,V2,F2,sqrD,I,C);\n    } else {\n        igl::point_mesh_squared_distance(V1,V2,F2,sqrD,I,C);\n    }\n    double distance = 0;\n    for (int i = 0; i < sqrD.size(); ++i) {\n        distance += sqrt(sqrD[i]);\n    }\n    double ans = distance / sqrD.size();\n    return ans;\n}\n\ndouble OneWayChamfer(int src_id, int resample_points = 0) {\n    if (src_id == 1) {\n        return OneWayChamferDistance(V1, F1, V2, F2, resample_points);\n    }\n    return OneWayChamferDistance(V2, F2, V1, F1, resample_points);\n}\n\ndouble TwoWayChamfer(int resample_points = 0) {\n    double distance1 = OneWayChamferDistance(V1, F1, V2, F2, resample_points);\n    double distance2 = OneWayChamferDistance(V2, F2, V1, F1, resample_points);\n    \n    return distance1 + distance2;\n}\n\nvoid SetMesh(double* vertices, int* faces, int num_V, int num_F, int id) {\n    auto &V = (id == 1) ? V1 : V2;\n    auto &F = (id == 1) ? F1 : F2;\n\n    V = Eigen::MatrixXd(num_V, 3);\n    for (int i = 0; i < num_V; ++i) {\n        V.row(i) = Eigen::Vector3d(vertices[i * 3],vertices[i * 3 + 1],vertices[i * 3 + 2]);\n    }\n\n    F = Eigen::MatrixXi(num_F, 3);\n    for (int i = 0; i < num_F; ++i) {\n        F.row(i) = Eigen::Vector3i(faces[i * 3], faces[i * 3 + 1], faces[i * 3 + 2]);\n    }\n}\n\ndouble AreaRatio(const char* f1, const char* f2) {\n    LoadObj(f1, 2);\n    LoadObj(f2, 1);\n    {\n        Eigen::MatrixXd V2_buf(V2.rows() * 2, 3);\n        Eigen::MatrixXi F2_buf(F2.rows() * 2, 3);\n        for (int i = 0; i < V2.rows(); ++i) {\n            V2_buf.row(i) = V2.row(i);\n            V2_buf.row(i + V2.rows()) = V2.row(i);\n            V2_buf(i + V2.rows(), 0) = -V2_buf(i + V2.rows(), 0);\n        }\n        for (int i = 0; i < F2.rows(); ++i) {\n            F2_buf.row(i) = F2.row(i);\n            F2_buf.row(i + F2.rows()) = F2.row(i);\n            for (int j = 0; j < 3; ++j)\n                F2_buf(i + F2.rows(), j) += V2.rows();\n        }\n        F2 = F2_buf;\n        V2 = V2_buf;\n    }        \n    {\n        Eigen::VectorXd sqrD;\n        Eigen::VectorXi I;\n        Eigen::MatrixXd C;\n        std::vector<double> areas(F1.rows() + 1, 0);\n        double total_area = 0;\n        for (int i = 0; i < F1.rows(); ++i) {\n            const Eigen::Vector3d& v1 = V1.row(F1(i, 0));\n            const Eigen::Vector3d& v2 = V1.row(F1(i, 1));\n            const Eigen::Vector3d& v3 = V1.row(F1(i, 2));\n            double area = ((v2 - v1).cross(v3 - v1)).norm();\n            areas[i + 1] = area;\n            total_area += area;\n        }\n        for (int i = 1; i < areas.size(); ++i)\n            areas[i] += areas[i - 1];\n        \n        int resample_points = 100000;\n        Eigen::MatrixXd NV(resample_points, 3);\n        for (int i = 0; i < resample_points; ++i) {\n            double r = rand() / (double)RAND_MAX * areas.back();\n            auto lower = std::lower_bound(areas.begin(), areas.end(), r) - 1;\n            int tri_idx = lower - areas.begin();\n            if (tri_idx < 0) {\n                tri_idx = 0;\n            }\n            double u = rand() / (double)RAND_MAX;\n            double v = rand() / (double)RAND_MAX;\n            if (u + v > 1) {\n                u = 1 - u;\n                v = 1 - v;\n            }\n            auto v1 = V1.row(F1(tri_idx, 0));\n            auto v2 = V1.row(F1(tri_idx, 1));\n            auto v3 = V1.row(F1(tri_idx, 2));\n\n            NV.row(i) = u * (v2 - v1) + v * (v3 - v1) + v1;\n        }\n\n        igl::point_mesh_squared_distance(NV,V2,F2,sqrD,I,C);\n        int inliers = 0;\n        for (int i = 0; i < sqrD.size(); ++i) {\n            double dis = sqrt(sqrD[i]);\n            if (dis < 0.03)\n                inliers += 1;\n        }\n        return (double)inliers / sqrD.size();\n    }\n}\n\n};", "meta": {"hexsha": "a92b0ae541b4e18972267dbcf56fdd8101bc9126", "size": 5626, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tools/evaluation/distances.cc", "max_stars_repo_name": "mikacuy/deformation_aware_embedding", "max_stars_repo_head_hexsha": "7a2cef54328c51d2bfc582fdd5b119a24e19a9ca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 40.0, "max_stars_repo_stars_event_min_datetime": "2020-09-11T01:17:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T23:22:45.000Z", "max_issues_repo_path": "tools/evaluation/distances.cc", "max_issues_repo_name": "star-cold/deformation_aware_embedding", "max_issues_repo_head_hexsha": "d5982209f072015bdc16abf281cb0f045b928720", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-02-16T21:41:00.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-25T04:06:59.000Z", "max_forks_repo_path": "tools/evaluation/distances.cc", "max_forks_repo_name": "star-cold/deformation_aware_embedding", "max_forks_repo_head_hexsha": "d5982209f072015bdc16abf281cb0f045b928720", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2020-09-26T08:42:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-12T09:29:03.000Z", "avg_line_length": 32.9005847953, "max_line_length": 92, "alphanum_fraction": 0.4866690366, "num_tokens": 1832, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182187, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.47891508383578485}}
{"text": "#include <boost/math/distributions/normal.hpp>\n", "meta": {"hexsha": "2db877bf5367306565fb975d03af246aa902f9f3", "size": 47, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_distributions_normal.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_distributions_normal.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_distributions_normal.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 23.5, "max_line_length": 46, "alphanum_fraction": 0.8085106383, "num_tokens": 10, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672320414786, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.47891445894831947}}
{"text": "// Filename: imf_example.cpp (part of MTL4)\n\n#include <boost/numeric/mtl/mtl.hpp>\n#include <boost/numeric/itl/itl.hpp>\n\nint main(int, char** argv)\n{\n    typedef double value_type;\n  \n    std::string program_dir= mtl::io::directory_name(argv[0]),\n  \t        matrix_file= mtl::io::join(program_dir, \"../../mtl/test/matrix_market/square3.mtx\");\n    //define and read element structure\n    mtl::mat::element_structure<value_type> A;\n    read_el_matrix(matrix_file, A);\n    \n    int size= int( num_cols(A) );\n    mtl::dense_vector<value_type>    x(size, 1), b( A * x );\n    \n    //assemble sparse matrix from element structure (unnecessary)\n    mtl::compressed2D<value_type> B;\n    assemble_compressed(A, B);\n    \n    //create imf preconditioner with 3 levels of fill-in\n    itl::pc::imf_preconditioner<value_type> precond(A, 3);\n    \n    itl::cyclic_iteration<value_type>    iterA(b, size, 1.e-8, 0.0, 5),\n\t\t\t\t\t  iterB(b, size, 1.e-8, 0.0, 5);\n    x= 0;\n    bicgstab(A, x, b, precond, iterA);  //solve A*x=b  with element_structure A\n    x= 0;\n    bicgstab(B, x, b, precond, iterB);  //solve A*x=b  with assembled sparse matrix B\n    \n    return 0;\n}\n", "meta": {"hexsha": "e7ed238ff942247f5bde69f2bcbd4d15d80572bf", "size": 1147, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/examples/imf_example.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/imf_example.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/imf_example.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 32.7714285714, "max_line_length": 95, "alphanum_fraction": 0.6451612903, "num_tokens": 368, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672320414786, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.47891445894831947}}
{"text": "//=============================================================================\n//\n//  CLASS ConeConstraint\n//\n//=============================================================================\n\n\n#ifndef COMISO_CONECONSTRAINT_HH\n#define COMISO_CONECONSTRAINT_HH\n\n\n//== INCLUDES =================================================================\n\n#include <CoMISo/Config/CoMISoDefines.hh>\n#include \"NConstraintInterface.hh\"\n#include <Eigen/StdVector>\n\n\n//== FORWARDDECLARATIONS ======================================================\n\n//== NAMESPACES ===============================================================\n\nnamespace COMISO {\n\n//== CLASS DEFINITION =========================================================\n\n\t      \nclass COMISODLLEXPORT ConeConstraint : public NConstraintInterface\n{\npublic:\n\n  // sparse vector type\n  typedef NConstraintInterface::SVectorNC SVectorNC;\n  typedef NConstraintInterface::SMatrixNC SMatrixNC;\n\n  /// Default constructor\n  ConeConstraint();\n\n  // cone constraint of the form -> 0.5*(c_ * x(i_)^2 - x^T Q_ x) >= 0\n  ConeConstraint(const double _c, const int _i, const SMatrixNC& _Q);\n\n  virtual int n_unknowns();\n\n  // resize coefficient vector = #unknowns\n  void  resize(const unsigned int _n);\n\n  // clear to zero constraint 0 =_type 0\n  void  clear();\n\n  const double&    c() const;\n        double&    c();\n\n  const int&       i() const;\n        int&       i();\n\n  const SMatrixNC& Q() const;\n        SMatrixNC& Q();\n\n\n  virtual double eval_constraint ( const double* _x );\n  \n  virtual void eval_gradient( const double* _x, SVectorNC& _g      );\n\n  virtual void eval_hessian    ( const double* _x, SMatrixNC& _h      );\n\n  virtual bool   is_linear()         const { return false;}\n  virtual bool   constant_gradient() const { return false;}\n  virtual bool   constant_hessian () const { return true;}\n\nprivate:\n\n  // cone constraint of the form -> 0.5*(c_ * x(i_)^2 - x^T Q_ x) >= 0\n  double    c_;\n  int       i_;\n  SMatrixNC Q_;\n};\n\n\n//=============================================================================\n} // namespace COMISO\n//=============================================================================\n// support std vectors\nEIGEN_DEFINE_STL_VECTOR_SPECIALIZATION(COMISO::ConeConstraint);\n//=============================================================================\n#endif // ACG_CONECONSTRAINT_HH defined\n//=============================================================================\n\n", "meta": {"hexsha": "c747713f072e2cbce402d53cb6298ed9a608b19c", "size": 2441, "ext": "hh", "lang": "C++", "max_stars_repo_path": "ACAP_linux/3rd/CoMISo/NSolver/ConeConstraint.hh", "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/NSolver/ConeConstraint.hh", "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/NSolver/ConeConstraint.hh", "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.7386363636, "max_line_length": 79, "alphanum_fraction": 0.475624744, "num_tokens": 499, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971212, "lm_q2_score": 0.5926665999540697, "lm_q1q2_score": 0.4789144534694975}}
{"text": "// // [[Rcpp::depends(cgal4h)]]\n// #include <Rcpp.h>\n// \t\n// #include <CGAL/Cartesian.h>\n// #include <CGAL/MP_Float.h>\n// #include <CGAL/Quotient.h>\n// #include <CGAL/Arr_linear_traits_2.h>\n// #include <CGAL/Arr_segment_traits_2.h>\n// #include <CGAL/Arrangement_2.h>\n// // typedef CGAL::Quotient<CGAL::MP_Float> Number_type;\n// // typedef CGAL::Cartesian<Number_type> Kernel;\n// // // typedef CGAL::Arr_segment_traits_2<Kernel> Traits_2;\n// // typedef CGAL::Arr_linear_traits_2<Kernel> Traits_2;\n// // typedef Traits_2::Point_2 Point_2;\n// // typedef Traits_2::X_monotone_curve_2 Segment_2;\n// // typedef CGAL::Arrangement_2<Traits_2> Arrangement_2;\n// // #include <CGAL/Cartesian.h>\n// #include <CGAL/Exact_rational.h>\n// #include <CGAL/Arr_segment_traits_2.h>\n// #include <CGAL/Arr_extended_dcel.h>\n// #include <CGAL/Arrangement_2.h>\n// #include <CGAL/graph_traits_dual_arrangement_2.h>\n// #include <CGAL/Arr_face_index_map.h>\n// #include <climits>\n// #include <boost/graph/breadth_first_search.hpp>\n// #include <boost/graph/visitors.hpp>\n// \n// // A property map that reads/writes the information to/from the extended\n// // face.\n// template <typename Arrangement, class Type> class Extended_face_property_map {\n// public:\n//   typedef typename Arrangement::Face_handle       Face_handle;\n//   // Boost property type definitions.\n//   typedef boost::read_write_property_map_tag      category;\n//   typedef Type                                    value_type;\n//   typedef value_type&                             reference;\n//   typedef Face_handle                             key_type;\n//   // The get function is required by the property map concept.\n//   friend reference get(const Extended_face_property_map& /* map */,\n//                        key_type key)\n//   { return key->data(); }\n//   // The put function is required by the property map concept.\n//   friend void put(Extended_face_property_map /* map */,\n//                   key_type key, value_type val)\n//   { key->set_data(val); }\n// };\n// \n// \n// \n// typedef CGAL::Cartesian<CGAL::Exact_rational>                Kernel;\n// typedef CGAL::Arr_segment_traits_2<Kernel>                   Traits_2;\n// typedef CGAL::Arr_face_extended_dcel<Traits_2, unsigned int> Dcel;\n// typedef CGAL::Arrangement_2<Traits_2, Dcel>                  Ex_arrangement;\n// typedef CGAL::Dual<Ex_arrangement>                           Dual_arrangement;\n// typedef CGAL::Arr_face_index_map<Ex_arrangement>             Face_index_map;\n// typedef Extended_face_property_map<Ex_arrangement,unsigned int>\n//                                                              Face_property_map;\n// typedef Kernel::Point_2                                      Point_2;\n// typedef Kernel::Segment_2                                    Segment_2;\n// \n// \n// \n// // void print_ccb (Arrangement_2::Ccb_halfedge_const_circulator circ) {\n// //   Arrangement_2::Ccb_halfedge_const_circulator curr = circ;\n// //   Rcpp::Rcout << \"(\" << curr->source()->point() << \")\";\n// //   do {\n// //     Arrangement_2::Halfedge_const_handle he = curr->handle();\n// //     Rcpp::Rcout << \" [\" << he->curve() << \"] \"\n// //               << \"(\" << he->target()->point() << \")\";\n// //   } while (++curr != circ);\n// //   Rcpp::Rcout << std::endl;\n// // }\n// \n//  \n// // void print_face (Arrangement_2::Face_const_handle f) {\n// //   // Print the outer boundary.\n// //   if (f->is_unbounded())\n// //     Rcpp::Rcout << \"Unbounded face. \" << std::endl;\n// //   // else {\n// //   //   Rcpp::Rcout << \"Outer boundary: \";\n// //   //   print_ccb (f->outer_ccb());\n// //   // }\n// //   // Print the boundary of each of the holes.\n// //   // Arrangement_2::Hole_const_iterator hi;\n// //   int index = 1;\n// //   // for (hi = f->holes_begin(); hi != f->holes_end(); ++hi, ++index) {\n// //   //   Rcpp::Rcout << \" Hole #\" << index << \": \";\n// //   //   print_ccb (*hi);\n// //   // }\n// //   // Print the isolated vertices.\n// //   Arrangement_2::Isolated_vertex_const_iterator iv;\n// //   for (iv = f->isolated_vertices_begin(), index = 1;\n// //        iv != f->isolated_vertices_end(); ++iv, ++index){\n// //     Rcpp::Rcout << \" Isolated vertex #\" << index << \": \"\n// //               << \"(\" << iv->point() << \")\" << std::endl;\n// //   }\n// // }\n// \n// \n//   \n// // [[Rcpp::export]]\n// Rcpp::NumericVector construct_arrangement(Rcpp::NumericVector x) {\n// // \tArrangement_2 arr;\n// //   Segment_2 cv[3];\n// //   Point_2 p1 (0, 0), p2 (0, 4), p3 (4, 0);\n// //   cv[0] = Segment_2 (p1, p2);\n// //   cv[1] = Segment_2 (p2, p3);\n// //   cv[2] = Segment_2 (p3, p1);\n// //   CGAL::insert (arr, &cv[0], &cv[3]);\n// //   // ArrangementDcel::Face_const_iterator fit;\n// //   Rcpp::Rcout << arr.number_of_faces() << \" faces:\" << std::endl;\n// //   for (auto fit = arr.faces_begin(); fit != arr.faces_end(); ++fit)\n// //     print_face (fit);\n// //   return x * 2;\n// // Construct an arrangement of seven intersecting line segments.\n//   Point_2 p1(1, 1), p2(1, 4), p3(2, 2), p4(3, 7), p5(4, 4), p6(7, 1), p7(9, 3);\n//   Ex_arrangement  arr;\n//   insert(arr, Segment_2(p1, p6));\n//   insert(arr, Segment_2(p1, p4));  insert(arr, Segment_2(p2, p6));\n//   insert(arr, Segment_2(p3, p7));  insert(arr, Segment_2(p3, p5));\n//   insert(arr, Segment_2(p6, p7));  insert(arr, Segment_2(p4, p7));\n//   // Create a mapping of the arrangement faces to indices.\n//   Face_index_map  index_map(arr);\n//   // Perform breadth-first search from the unbounded face, using the event\n//   // visitor to associate each arrangement face with its discover time.\n//   unsigned int    time = 0;\n//   boost::breadth_first_search(Dual_arrangement(arr), arr.unbounded_face(),\n//                               boost::vertex_index_map(index_map).visitor\n//                               (boost::make_bfs_visitor\n//                                (stamp_times(Face_property_map(), time,\n//                                             boost::on_discover_vertex()))));\n//   // Print the discover time of each arrangement face.\n//   Ex_arrangement::Face_iterator  fit;\n//   for (fit = arr.faces_begin(); fit != arr.faces_end(); ++fit) {\n//     std::cout << \"Discover time \" << fit->data() << \" for \";\n//     if (fit != arr.unbounded_face()) {\n//       std::cout << \"face \";\n//       // print_ccb<Ex_arrangement>(fit->outer_ccb());\n//     }\n//     else std::cout << \"the unbounded face.\" << std::endl;\n//   }\n// \t//arr.unbounded_faces_begin() \n// }\n// \n// \n// /*** R\n// construct_arrangement(42)\n// */\n", "meta": {"hexsha": "b797c6ccc646136a9c37c76e3a4f1af09284c47f", "size": 6452, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ignore/cgal_arrangement.cpp", "max_stars_repo_name": "corybrunson/dart", "max_stars_repo_head_hexsha": "b51ff967998c99ffae370e502927af83404b8374", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ignore/cgal_arrangement.cpp", "max_issues_repo_name": "corybrunson/dart", "max_issues_repo_head_hexsha": "b51ff967998c99ffae370e502927af83404b8374", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ignore/cgal_arrangement.cpp", "max_forks_repo_name": "corybrunson/dart", "max_forks_repo_head_hexsha": "b51ff967998c99ffae370e502927af83404b8374", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-07-21T16:15:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-21T16:15:16.000Z", "avg_line_length": 43.3020134228, "max_line_length": 82, "alphanum_fraction": 0.5753254805, "num_tokens": 1843, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.808067204308405, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.478914442511853}}
{"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_ASINPI_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_ASINPI_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 inverse sine in \\f$\\pi\\f$ multiples.\n\n    @par Header <boost/simd/function/asinpi.hpp>\n\n    @see asin, asind, sinpi\n\n    @par Example:\n\n      @snippet asinpi.cpp asinpi\n\n    @par Possible output:\n\n      @snippet asinpi.txt asinpi\n\n  **/\n  IEEEValue asinpi(IEEEValue const & x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/asinpi.hpp>\n#include <boost/simd/function/simd/asinpi.hpp>\n\n#endif\n", "meta": {"hexsha": "3e757154d17cc06463b79cc12b21583c522537bd", "size": 1023, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/asinpi.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/asinpi.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/asinpi.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 23.7906976744, "max_line_length": 100, "alphanum_fraction": 0.5806451613, "num_tokens": 227, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080671950640463, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.47891443703303044}}
{"text": "#include <pybind11/pybind11.h>\n#include <pybind11/numpy.h>\n#include <pybind11/eigen.h>\n\nnamespace py = pybind11;\nusing namespace std;\n\n#include <Eigen/Dense>\n\n// https://pybind11.readthedocs.io/en/stable/advanced/cast/eigen.html\n\nclass MyClass\n{\nprivate:\n    Eigen::MatrixXd ary;\n\npublic:\n    Eigen::MatrixXd &ones(int, int);\n};\n\nEigen::MatrixXd &MyClass::ones(int ny, int nx)\n{\n    ary = Eigen::MatrixXd::Zero(ny, nx);\n\n    for (int y = 0; y < ny; ++y)\n    {\n        for (int x = 0; x < nx; ++x)\n        {\n            ary(y, x) = 1;\n        }\n    }\n\n    return ary;\n}\n\npy::array_t<int> ones(int ny, int nx)\n{\n    vector<int> arraysize{ny, nx};\n    py::array_t<int> ary{arraysize};\n\n    for (int y = 0; y < ny; ++y)\n    {\n        for (int x = 0; x < nx; ++x)\n        {\n            *ary.mutable_data(y, x) = 1;\n        }\n    }\n\n    return ary;\n}\n\npy::tuple oneses(int ny0, int nx0, int ny1, int nx1)\n{\n\n    return py::make_tuple(ones(ny0, nx0), ones(ny1, nx1));\n}\n\nPYBIND11_MODULE(numpytest, m)\n{\n    m.doc() = \"pybind11 example plugin\";\n    m.def(\"ones\", &ones, \"A function which returns ones array\");\n    m.def(\"oneses\", &oneses, \"A function which returns ones array x2\");\n\n    py::class_<MyClass>(m, \"MyClass\")\n        .def(py::init<>())\n        .def(\"ones\", &MyClass::ones, py::return_value_policy::reference_internal); // reference\n    //        .def(\"ones\", &MyClass::ones); //copy\n}", "meta": {"hexsha": "75a9b31ec8c16e2474e865d5f1dd84dd3ab44a0e", "size": 1388, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libraries/pybind11/numpytest.cpp", "max_stars_repo_name": "ashitani/cmake_example", "max_stars_repo_head_hexsha": "3631d8eabf7bde256181640df156127d58ce03d4", "max_stars_repo_licenses": ["MIT"], "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/pybind11/numpytest.cpp", "max_issues_repo_name": "ashitani/cmake_example", "max_issues_repo_head_hexsha": "3631d8eabf7bde256181640df156127d58ce03d4", "max_issues_repo_licenses": ["MIT"], "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/pybind11/numpytest.cpp", "max_forks_repo_name": "ashitani/cmake_example", "max_forks_repo_head_hexsha": "3631d8eabf7bde256181640df156127d58ce03d4", "max_forks_repo_licenses": ["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.4117647059, "max_line_length": 95, "alphanum_fraction": 0.5713256484, "num_tokens": 439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723317123102956, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.4788562922053589}}
{"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#include <boost/simd/arithmetic/include/functions/tenpower.hpp>\n#include <boost/simd/sdk/simd/native.hpp>\n#include <boost/dispatch/functor/meta/call.hpp>\n#include <nt2/sdk/unit/tests/ulp.hpp>\n#include <nt2/sdk/unit/tests/type_expr.hpp>\n#include <nt2/sdk/unit/module.hpp>\n#include <boost/simd/include/constants/one.hpp>\n#include <boost/simd/include/constants/oneo_10.hpp>\n#include <boost/simd/include/constants/zero.hpp>\n#include <boost/simd/include/constants/mone.hpp>\n#include <boost/simd/include/constants/two.hpp>\n#include <boost/simd/include/constants/three.hpp>\n#include <boost/simd/include/constants/hundred.hpp>\n#include <boost/simd/include/functions/sqr.hpp>\n#include <boost/simd/include/functions/splat.hpp>\n\n\nNT2_TEST_CASE_TPL ( tenpower_unsigned_int, BOOST_SIMD_SIMD_UINT_CONVERT_TYPES)\n{\n\n  using boost::simd::tenpower;\n  using boost::simd::tag::tenpower_;\n  using boost::simd::native;\n  typedef BOOST_SIMD_DEFAULT_EXTENSION  ext_t;\n  typedef native<T,ext_t>                  vT;\n  typedef typename boost::dispatch::meta::call<tenpower_(vT)>::type r_t;\n\n  // specific values tests\n  NT2_TEST_ULP_EQUAL(tenpower(boost::simd::One<vT>()), boost::simd::Ten<r_t>(), 0.5);\n  NT2_TEST_ULP_EQUAL(tenpower(boost::simd::Two<vT>()), boost::simd::Hundred<r_t>(), 0.5);\n  NT2_TEST_ULP_EQUAL(tenpower(boost::simd::Zero<vT>()), boost::simd::One<r_t>(), 0.5);\n} // end of test for unsigned_int_\n\nNT2_TEST_CASE_TPL ( tenpower_signed_int,  BOOST_SIMD_SIMD_INT_CONVERT_TYPES)\n{\n\n  using boost::simd::tenpower;\n  using boost::simd::tag::tenpower_;\n  using boost::simd::native;\n  typedef BOOST_SIMD_DEFAULT_EXTENSION  ext_t;\n  typedef native<T,ext_t>                  vT;\n  typedef typename boost::dispatch::meta::call<tenpower_(vT)>::type r_t;\n  // specific values tests\n  NT2_TEST_ULP_EQUAL(tenpower(boost::simd::Mone<vT>()), boost::simd::Oneo_10<r_t>(), 0.5);\n  NT2_TEST_ULP_EQUAL(tenpower(boost::simd::One<vT>()), boost::simd::Ten<r_t>(), 0.5);\n  NT2_TEST_ULP_EQUAL(tenpower(boost::simd::Two<vT>()), boost::simd::Hundred<r_t>(), 0.5);\n  NT2_TEST_ULP_EQUAL(tenpower(boost::simd::Three<vT>()),boost::simd::splat<r_t>(1000.0), 0.5);\n  NT2_TEST_ULP_EQUAL(tenpower(boost::simd::Mtwo<vT>()), boost::simd::sqr(boost::simd::Oneo_10<r_t>()), 0.5);\n  NT2_TEST_ULP_EQUAL(tenpower(boost::simd::Zero<vT>()), boost::simd::One<r_t>(), 0.5);\n} // end of test for signed_int_\n", "meta": {"hexsha": "73f74982d43232d7a566cfd93391d4bf08fc4d81", "size": 2754, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/base/unit/arithmetic/simd/tenpower.cpp", "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/unit/arithmetic/simd/tenpower.cpp", "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/unit/arithmetic/simd/tenpower.cpp", "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": 47.4827586207, "max_line_length": 108, "alphanum_fraction": 0.6721132898, "num_tokens": 760, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321964553657, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.4788562828530311}}
{"text": "#define BOOST_TEST_MODULE pcraster com statistics\n#include <boost/test/unit_test.hpp>\n#include \"stddefx.h\"\n#include <cmath>\n#include \"com_algorithm.h\"\n#include \"com_statistics.h\"\n\n\n// KDJ, 20150928: Some tests used to be excluded on certain platforms:\n\n// #ifndef __x86_64__\n//   // bugzilla #80\n//   suite->add(BOOST_CLASS_TEST_CASE(&StatisticsTest::testVariance1, instance));\n//   suite->add(BOOST_CLASS_TEST_CASE(&StatisticsTest::testVariance2, instance));\n//   suite->add(BOOST_CLASS_TEST_CASE(&StatisticsTest::testStandardDeviation, instance));\n//   suite->add(BOOST_CLASS_TEST_CASE(&StatisticsTest::testPercentile, instance));\n// #else\n//   suite->add(BOOST_CLASS_TEST_CASE(&StatisticsTest::testSuse, instance));\n// #endif\n\n\nnamespace com {\n namespace statisticsTest {\n    struct Reverse {\n      bool operator()(const double& e1, const double& e2) const\n      {\n        return e1>e2;\n      }\n    };\n }\n}\n\n\nBOOST_AUTO_TEST_CASE(sum)\n{\n  using namespace com;\n\n  int values[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };\n  const size_t nrValues = ARRAY_SIZE(values);\n\n  Sum<int> sum = std::for_each(values, values + nrValues, Sum<int>());\n\n  BOOST_CHECK(sum == 55);\n  BOOST_CHECK(sum.sum() == 55);\n}\n\n\nBOOST_AUTO_TEST_CASE(sum_nr)\n{\n  using namespace com;\n\n  int values[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };\n  const size_t nrValues = ARRAY_SIZE(values);\n  SumNr<int> sum = std::for_each(values, values + nrValues, SumNr<int>());\n\n  BOOST_CHECK(sum.sum() == 55);\n  BOOST_CHECK(sum.nr() ==  nrValues);\n}\n\n\nBOOST_AUTO_TEST_CASE(average)\n{\n  using namespace com;\n\n  double values[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };\n  const size_t nrValues = ARRAY_SIZE(values);\n  Average<> a = std::for_each(values, values + nrValues,\n      Average<>());\n\n  BOOST_CHECK(a.sum() == 55);\n  BOOST_CHECK(a.nr() ==  nrValues);\n  BOOST_CHECK(a.average() ==  5.5);\n\n  Average<double> empty;\n  BOOST_CHECK(empty.nr()==0);\n  BOOST_CHECK(empty.average(-1)==-1);\n}\n\n\nBOOST_AUTO_TEST_CASE(average_min_max)\n{\n  using namespace com;\n\n  {\n    double values[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };\n    const size_t nrValues = ARRAY_SIZE(values);\n    AverageMinMax<double> a = std::for_each(values, values + nrValues,\n        AverageMinMax<double>());\n\n    BOOST_CHECK(a.sum() == 55);\n    BOOST_CHECK(a.nr() ==  nrValues);\n    BOOST_CHECK(a.average() ==  5.5);\n    BOOST_CHECK(a.minimum() ==  1);\n    BOOST_CHECK(a.maximum() ==  10);\n  }\n  {\n    double values[] = { 6, 2, 10, 4, 5, 1, 7, 8, 9, 3 };\n    const size_t nrValues = ARRAY_SIZE(values);\n    AverageMinMax<double> a = std::for_each(values, values + nrValues,\n        AverageMinMax<double>());\n\n    BOOST_CHECK(a.sum() == 55);\n    BOOST_CHECK(a.nr() ==  nrValues);\n    BOOST_CHECK(a.average() ==  5.5);\n    BOOST_CHECK(a.minimum() ==  1);\n    BOOST_CHECK(a.maximum() ==  10);\n  }\n}\n\n\nBOOST_AUTO_TEST_CASE(variance_1)\n{\n  using namespace com;\n\n  // Empty collection.\n  {\n    double *values = 0;\n    const size_t nrValues = 0u;  // ARRAY_SIZE requires non-empty array.\n    Variance1<double> variance = std::for_each(values, values + nrValues,\n                   Variance1<double>(0.0));\n    BOOST_CHECK(variance == 0.0);\n  }\n\n  // Collection with equal values.\n  {\n    double values[] = { 3, 3, 3, 3, 3, 3, 3, 3 };\n    const size_t nrValues = ARRAY_SIZE(values);\n    Variance1<double> variance = std::for_each(values, values + nrValues,\n                   Variance1<double>(3.0));\n    BOOST_CHECK(variance == 0.0);\n  }\n\n  // Collection with different values.\n  {\n    double values[] = { 2, 2, 2, 2, 2.5, 3, 3, 3, 3 };\n    const size_t nrValues = ARRAY_SIZE(values);\n    Variance1<double> variance = std::for_each(values, values + nrValues,\n                   Variance1<double>(2.5));\n    BOOST_CHECK(variance == 0.25);\n  }\n}\n\n\nBOOST_AUTO_TEST_CASE(variance_2)\n{\n  using namespace com;\n\n  // Empty collection.\n  {\n    double *values = 0;\n    const size_t nrValues = 0u;  // ARRAY_SIZE requires non-empty array.\n    Variance2<double> variance = std::for_each(values, values + nrValues,\n                   Variance2<double>());\n    BOOST_CHECK(variance == 0.0);\n  }\n\n  // Collection with equal values.\n  {\n    double values[] = { 3, 3, 3, 3, 3, 3, 3, 3 };\n    const size_t nrValues = ARRAY_SIZE(values);\n    Variance2<double> variance = std::for_each(values, values + nrValues,\n                   Variance2<double>());\n    BOOST_CHECK(variance == 0.0);\n  }\n\n  // Collection with different values.\n  {\n    double values[] = { 2, 2, 2, 2, 2.5, 3, 3, 3, 3 };\n    const size_t nrValues = ARRAY_SIZE(values);\n    Variance2<double> variance = std::for_each(values, values + nrValues,\n                   Variance2<double>());\n    BOOST_CHECK(variance == 0.25);\n  }\n}\n\n\nBOOST_AUTO_TEST_CASE(standard_deviation)\n{\n  using namespace com;\n\n  // Empty collection.\n  {\n    double *values = 0;\n    const size_t nrValues = 0u;  // ARRAY_SIZE requires non-empty array.\n    StandardDeviation<double> stdDev = std::for_each(values,\n                   values + nrValues, StandardDeviation<double>());\n    BOOST_CHECK(stdDev == 0.0);\n  }\n\n  // Collection with equal values.\n  {\n    double values[] = { 3, 3, 3, 3, 3, 3, 3, 3 };\n    const size_t nrValues = ARRAY_SIZE(values);\n    StandardDeviation<double> stdDev = std::for_each(values, values + nrValues,\n                   StandardDeviation<double>());\n    BOOST_CHECK(stdDev == 0.0);\n  }\n\n  // Collection with different values.\n  {\n    double values[] = { 2, 2, 2, 2, 2.5, 3, 3, 3, 3 };\n    const size_t nrValues = ARRAY_SIZE(values);\n    StandardDeviation<double> stdDev = std::for_each(values, values + nrValues,\n                   StandardDeviation<double>());\n    BOOST_CHECK(stdDev == 0.5);\n  }\n}\n\n\nBOOST_AUTO_TEST_CASE(average_sd_min_max)\n{\n  using namespace com;\n\n  // Collection with different values.\n  {\n    double values[] = { 2, 2, 2, 2, 2.5, 3, 3, 3, 3 };\n    const size_t nrValues = ARRAY_SIZE(values);\n    AverageSdMinMax<double> asmm = std::for_each(values, values + nrValues,\n                   AverageSdMinMax<double>());\n    BOOST_CHECK(asmm.sd() == 0.5);\n    BOOST_CHECK(asmm.average() == 2.5);\n    BOOST_CHECK(asmm.minimum() == 2.0);\n    BOOST_CHECK(asmm.maximum() == 3.0);\n  }\n\n  // Empty collection.\n  {\n\n    double values[1] = { 99999 };\n    AverageSdMinMax<double> asmm = std::for_each(values, values+0,\n                   AverageSdMinMax<double>());\n    BOOST_CHECK(asmm.sd() == 0.0);\n    BOOST_CHECK(asmm.nr() == 0);\n    BOOST_CHECK(asmm.average(5) == 5);\n   }\n\n  // Collection with equal values.\n  {\n    double values[] = { 3, 3, 3, 3, 3, 3, 3, 3 };\n    const size_t nrValues = ARRAY_SIZE(values);\n    AverageSdMinMax<double> asmm = std::for_each(values, values + nrValues,\n                   AverageSdMinMax<double>());\n    BOOST_CHECK(asmm.sd() == 0.0);\n    BOOST_CHECK(asmm.average() == 3);\n    BOOST_CHECK(asmm.minimum() == 3);\n    BOOST_CHECK(asmm.maximum() == 3);\n  }\n}\n\n\nBOOST_AUTO_TEST_CASE(percentile_)\n{\n#ifndef __x86_64__\n  using namespace com;\n\n  typedef std::vector<double> T;\n  typedef T::iterator         I;\n {\n  double data[]={1,3,2,5,4,9,8,0,6,7};\n  T val;\n  std::copy(data,data+ARRAY_SIZE(data),std::back_inserter(val));\n\n  // out of range\n  BOOST_CHECK(percentile<I>(val.begin(),val.end(),5) == val.end());\n  BOOST_CHECK(percentile<I>(val.begin(),val.end(),-123) == val.end());\n\n  BOOST_CHECK(*percentile<I>(val.begin(),val.end(),0) == 0);\n  BOOST_CHECK( percentile<I>(val.begin(),val.end(),0) == val.begin());\n  BOOST_CHECK(*percentile<I>(val.begin(),val.end(),0.005) == 0);\n  BOOST_CHECK( percentile<I>(val.begin(),val.end(),0.005) == val.begin());\n\n  BOOST_CHECK(*percentile<I>(val.begin(),val.end(),1) == val.size()-1);\n  BOOST_CHECK( percentile<I>(val.begin(),val.end(),1) == val.end()-1);\n  BOOST_CHECK(*percentile<I>(val.begin(),val.end(),0.9994) == val.size()-1);\n  BOOST_CHECK( percentile<I>(val.begin(),val.end(),0.9994) == val.end()-1);\n\n#ifdef _MSC_VER\n  // bugzilla #80\n  BOOST_WARN(*percentile<I>(val.begin(),val.end(),0.6)  == 5);\n#else\n  BOOST_CHECK(*percentile<I>(val.begin(),val.end(),0.6)  == 5);\n#endif\n\n  BOOST_CHECK(*percentile<I>(val.begin(),val.end(),0.47) == 4);\n\n  BOOST_CHECK(*percentile<I>(val.begin(),val.end(),0,\n                         statisticsTest::Reverse())  == 9);\n  BOOST_CHECK(*percentile<I>(val.begin(),val.end(),1,\n                         statisticsTest::Reverse())  == 0);\n\n#ifdef _MSC_VER\n  // bugzilla #80\n  BOOST_WARN(*percentile<I>(val.begin(),val.end(),0.6,\n                         statisticsTest::Reverse())  == 4);\n#else\n  BOOST_CHECK(*percentile<I>(val.begin(),val.end(),0.6,\n                         statisticsTest::Reverse())  == 4);\n#endif\n }\n {\n  T e;\n  BOOST_CHECK( percentile<I>(e.begin(),e.end(),0)      == e.end());\n  BOOST_CHECK( percentile<I>(e.begin(),e.end(),0.005)  == e.end());\n  BOOST_CHECK( percentile<I>(e.begin(),e.end(),1)      == e.end());\n  BOOST_CHECK( percentile<I>(e.begin(),e.end(),0.9994) == e.end());\n }\n {\n  T e;\n  e.push_back(4);\n  BOOST_CHECK( percentile<I>(e.begin(),e.end(),0)      == e.begin());\n  BOOST_CHECK( percentile<I>(e.begin(),e.end(),0.005)  == e.begin());\n  BOOST_CHECK( percentile<I>(e.begin(),e.end(),0.5)    == e.begin());\n  BOOST_CHECK( percentile<I>(e.begin(),e.end(),1)      == e.begin());\n  BOOST_CHECK( percentile<I>(e.begin(),e.end(),0.9994) == e.begin());\n  BOOST_CHECK(*percentile<I>(e.begin(),e.end(),0)      == 4);\n  BOOST_CHECK(*percentile<I>(e.begin(),e.end(),0.005)  == 4);\n  BOOST_CHECK(*percentile<I>(e.begin(),e.end(),1)      == 4);\n  BOOST_CHECK(*percentile<I>(e.begin(),e.end(),0.9994) == 4);\n }\n#endif\n}\n\n\nBOOST_AUTO_TEST_CASE(suse)\n{\n  using namespace com;\n\n  bool suse64FailsALot=false;\n  BOOST_WARN(suse64FailsALot);\n}\n", "meta": {"hexsha": "f1a1f5a10f7117a4025fd1075e02d803d974b85b", "size": 9634, "ext": "cc", "lang": "C++", "max_stars_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcrcom/com_statisticstest.cc", "max_stars_repo_name": "quanpands/wflow", "max_stars_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcrcom/com_statisticstest.cc", "max_issues_repo_name": "quanpands/wflow", "max_issues_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcrcom/com_statisticstest.cc", "max_forks_repo_name": "quanpands/wflow", "max_forks_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.1057401813, "max_line_length": 89, "alphanum_fraction": 0.6148017438, "num_tokens": 2891, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321720225278, "lm_q2_score": 0.6723317123102956, "lm_q1q2_score": 0.47885627577838713}}
{"text": "// This program tests the functionality of my_vector_tools (parallel\n// and serial projection on FE spaces).\n\n// Deal.ii MPI\n#include <deal.II/base/conditional_ostream.h>\n#include <deal.II/base/function.h>\n#include <deal.II/base/index_set.h>\n#include <deal.II/base/logstream.h>\n#include <deal.II/base/mpi.h>\n#include <deal.II/base/numbers.h>\n#include <deal.II/base/tensor.h>\n#include <deal.II/base/tensor_function.h>\n#include <deal.II/base/utilities.h>\n#include <deal.II/distributed/tria.h>\n#include <deal.II/dofs/dof_handler.h>\n#include <deal.II/dofs/dof_tools.h>\n#include <deal.II/fe/fe_nedelec.h>\n#include <deal.II/grid/grid_generator.h>\n#include <deal.II/lac/affine_constraints.h>\n#include <deal.II/lac/vector.h>\n\n// C++ STL\n#include <iostream>\n\n// My library\n#include <vector_tools/my_vector_tools.h>\n#include <vector_tools/my_vector_tools.tpp>\n\nusing namespace dealii;\n\n///////////////////////////////////\n///////////////////////////////////\ntemplate <int dim>\nclass MyVectorFunction : public TensorFunction<1, dim>\n{\npublic:\n  MyVectorFunction()\n    : TensorFunction<1, dim>(){};\n\n  void\n    value_list(const std::vector<Point<dim>> &points,\n               std::vector<Tensor<1, dim>> &  values) const override;\n};\n\ntemplate <int dim>\nvoid\n  MyVectorFunction<dim>::value_list(const std::vector<Point<dim>> &points,\n                                    std::vector<Tensor<1, dim>> &  values) const\n{\n  Assert(points.size() == values.size(),\n         ExcDimensionMismatch(points.size(), values.size()));\n\n  for (unsigned int i = 0; i < values.size(); ++i)\n    {\n      values[i].clear();\n      for (unsigned int d = 0; d < dim; ++d)\n        values[i][d] = d + 1.0;\n    }\n}\n///////////////////////////////////\n///////////////////////////////////\n\n///////////////////////////////////\n///////////////////////////////////\nint\n  main(int argc, char *argv[])\n{\n  dealii::Utilities::MPI::MPI_InitFinalize mpi_initialization(\n    argc, argv, dealii::numbers::invalid_unsigned_int);\n\n  MPI_Comm mpi_communicator(MPI_COMM_WORLD);\n\n  const int dim = 3, degree = 0, n_refine = 3;\n\n  ConditionalOStream pcout(std::cout,\n                           (Utilities::MPI::this_mpi_process(MPI_COMM_WORLD) ==\n                            0));\n\n  parallel::distributed::Triangulation<dim> triangulation(\n    mpi_communicator,\n    typename Triangulation<dim>::MeshSmoothing(\n      Triangulation<dim>::smoothing_on_refinement |\n      Triangulation<dim>::smoothing_on_coarsening));\n\n  GridGenerator::hyper_cube(triangulation, 0.0, 1.0, true);\n  triangulation.refine_global(n_refine);\n\n  FE_Nedelec<dim> fe(degree);\n\n  DoFHandler<dim> dof_handler(triangulation);\n  dof_handler.distribute_dofs(fe);\n\n  AffineConstraints<double> constraints;\n  constraints.clear();\n  DoFTools::make_hanging_node_constraints(dof_handler, constraints);\n  constraints.close();\n\n  // Quadrature used for projection\n  QGauss<dim> quad_rule(/* order = */ 3);\n\n  // Setup function\n  MyVectorFunction<dim> my_vector_function;\n\n  TrilinosWrappers::MPI::Vector projected_function;\n\n  IndexSet locally_owned_dofs;\n  locally_owned_dofs = dof_handler.locally_owned_dofs();\n  projected_function.reinit(locally_owned_dofs, mpi_communicator);\n\n  try\n    {\n      MyVectorTools::project_on_fe_space(dof_handler,\n                                         constraints,\n                                         quad_rule,\n                                         my_vector_function,\n                                         projected_function,\n                                         mpi_communicator);\n\n      // Write only for process 0\n      if (Utilities::MPI::this_mpi_process(mpi_communicator) == 0)\n        {\n          IndexSet::ElementIterator local_index = locally_owned_dofs.begin(),\n                                    local_index_end = locally_owned_dofs.end();\n\n          std::cout << \"Values of the projected vector in MPI process 0:\"\n                    << std::endl;\n\n          for (; local_index != local_index_end; ++local_index)\n            {\n              std::cout << \"   \" << projected_function[*local_index]\n                        << std::endl;\n            }\n\n          std::cout << \"Projection test succeeded.\" << std::endl;\n        }\n\n      constraints.clear();\n      dof_handler.clear();\n    }\n  catch (...)\n    {\n      //      if (Utilities::MPI::this_mpi_process(mpi_communicator) == 0)\n      std::cout << \"Projection test failed.\" << std::endl;\n    }\n}\n///////////////////////////////////\n///////////////////////////////////\n", "meta": {"hexsha": "171009c9ea732e948e697597242e48a91aa2d095", "size": 4489, "ext": "cc", "lang": "C++", "max_stars_repo_path": "NonFEEC-C++/test/test_fe_projection_nedelec_mpi.cc", "max_stars_repo_name": "konsim83/StabilityPreservation", "max_stars_repo_head_hexsha": "2d480dc400cc0087b4ffb1423cbd16591a839bf7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "NonFEEC-C++/test/test_fe_projection_nedelec_mpi.cc", "max_issues_repo_name": "konsim83/StabilityPreservation", "max_issues_repo_head_hexsha": "2d480dc400cc0087b4ffb1423cbd16591a839bf7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NonFEEC-C++/test/test_fe_projection_nedelec_mpi.cc", "max_forks_repo_name": "konsim83/StabilityPreservation", "max_forks_repo_head_hexsha": "2d480dc400cc0087b4ffb1423cbd16591a839bf7", "max_forks_repo_licenses": ["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.3310810811, "max_line_length": 80, "alphanum_fraction": 0.5905546892, "num_tokens": 1024, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.47885627463954544}}
{"text": "#include \"testsuite.h\"\n#include <blitz/array.h>\n\n\nBZ_USING_NAMESPACE(blitz)\n\nint main()\n{\nArray<float,2> test(8,8), test2(5,5) ;\n\ntest = 5;\n\nRange I(2,6) ;\nRange J(3,7) ;\n\n// Koenig lookup hack\n#if defined(__GNUC__) && (__GNUC__ < 3)\ntest2 = where(blitz::operator> (test(I,J), test(I-1,J)), 0, test(I,J));\n#else\ntest2 = where(test(I,J) > test(I-1,J), 0, test(I,J));\n#endif\n\nBZTEST(test2(3,3) == 5);\n\ncout << test2 << endl ;\n\n}\n\n\n", "meta": {"hexsha": "d6e15e2e2fbfd4ba7f3125b3f711d1d10c6abc51", "size": 429, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depspawn-blitz-0.10/testsuite/chris-jeffery-3.cpp", "max_stars_repo_name": "fraguela/depspawn", "max_stars_repo_head_hexsha": "b5760f4c0d38a1b245ee5274e2ccc5c5fe2d3d45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-04-12T11:05:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T11:10:27.000Z", "max_issues_repo_path": "ibtk/third_party/blitz-0.10/testsuite/chris-jeffery-3.cpp", "max_issues_repo_name": "MSV-Project/IBAMR", "max_issues_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ibtk/third_party/blitz-0.10/testsuite/chris-jeffery-3.cpp", "max_forks_repo_name": "MSV-Project/IBAMR", "max_forks_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.3, "max_line_length": 71, "alphanum_fraction": 0.6083916084, "num_tokens": 160, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7122321720225278, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.4788562617498959}}
{"text": "#include <boost/multiprecision/gmp.hpp>\n#include <iostream>\n#include <stdio.h>\n#include <string.h>\n\nvoid findy(mpf_t y, long unsigned int nn, int precision)\n{\n\tmpz_t n,n1,y1,y2;\n\tmpz_inits(n,n1,y1,y2,NULL);\n\n\tmpz_set_ui( n,  nn);\n\tmpz_set_ui(n1,nn+1);\n\n\tmpz_pow_ui(y1,n1,nn+1);\n\tmpz_pow_ui(y2,n ,nn+1);\n\t\n\tmpf_t y3,y4;\n\tmpf_init2(y3,precision);\n\tmpf_init2(y4,precision);\n\tmpf_set_z(y3,y1);\n\tmpf_set_z(y4,y2);\n\t\n\tmpf_div(y,y3,y4);\t\n\t\n\tmpz_clear(n);\n\tmpz_clear(n1);\n\tmpz_clear(y1);\n\tmpz_clear(y2);\n\tmpf_clear(y3);\n\tmpf_clear(y4);\n}\n\n\nvoid findx(mpf_t x, long unsigned int nn, int precision)\n{\n\tmpz_t n,n1,x1,x2;\n\tmpz_inits(n,n1,x1,x2,NULL);\n\n\tmpz_set_ui( n,  nn);\n\tmpz_set_ui(n1,nn+1);\n\n\tmpz_pow_ui(x1,n1,nn);\n\tmpz_pow_ui(x2,n ,nn);\n\t\n\t/*\n\tstd::cout << \"X1 = \"; \n\tmpz_out_str(stdout, 10, x1);\n\tstd::cout << std::endl;\n\t\n\tstd::cout << \"X2 = \";\n\tmpz_out_str(stdout, 10, x2);\n\tstd::cout << std::endl;\n\t*/\n\tmpf_t x3,x4;\n\tmpf_init2(x3,precision);\n\tmpf_init2(x4,precision);\n\tmpf_set_z(x3,x1);\n\tmpf_set_z(x4,x2);\n\t\n\tmpf_div(x,x3,x4);\t\n\t\n\tmpz_clear(n);\n\tmpz_clear(n1);\n\tmpz_clear(x1);\n\tmpz_clear(x2);\n\tmpf_clear(x3);\n\tmpf_clear(x4);\n}\n\nint getsizef(mpf_t x)\n{\n\tmp_exp_t exponent; \n\tchar* c = mpf_get_str(NULL,&exponent,10,0,x);\n\t\n\treturn strlen(c);\n}\n\nint main()\n{\n\tusing namespace boost::multiprecision;\n\t\n\tint precision = 262144;\n\tchar* c;\n\n\tmpf_t x,y;\n\tmpf_init2(x,precision);\n\tmpf_init2(y,precision);\n\tmp_exp_t exponent;\n\t\n\tfor(long unsigned int nn = 1; nn<=5000; nn++)\n\t{\n\t\tfindx(x,nn,precision);\n\t\tfindy(y,nn,precision);\n\t\t\n\t\t//std::cout << \"X = \";\n\t\t//mpf_out_str(stdout, 10, 10, x);\n\t\t//std::cout << std::endl;\n\t\t//int sz = getsizef(x);\n\t\tc = mpf_get_str(NULL,&exponent,10,0,x);\n\t\tint sz = strlen(c); \n\t\tif(sz < 78911)//315651)\t//<precision/3.33\n\t\t{\n\t\t\tstd::cout << \"N = \" << nn << \"\\t\" << \"# of digits of X = \" << sz << \" : \";// << std::endl;\n\t\t\tif(sz > 7) for(int i=0; i<10; i++) std::cout << c[sz-10+i];\n\t\t\tstd::cout << \"\\t\";\n\t\t\t\n\t\t\tbool ok = true;\n\t\t\tfor (int i=sz-8; i<sz; i++) \n\t\t\t\tfor (int j= i+1; j<sz; j++) \n\t\t\t\t\tif(c[i] == c[j]) ok = false;\n\n\t\t\tif(ok) std::cout << \"OK!!!!!\";\n\t\t\telse std::cout << \"NO\";\n\t\t\tstd::cout << std::endl;\n\t\t}\n\t\t\n\t\tc = mpf_get_str(NULL,&exponent,10,0,y);\n\t\tsz = strlen(c); \n\t\tif(sz < 78911)\n\t\t{\n\t\t\tstd::cout << \"N = \" << nn << \"\\t\" << \"# of digits of Y = \" << sz << \" : \";// << std::endl;\n\t\t\tif(sz > 7) for(int i=0; i<10; i++) std::cout << c[sz-10+i];\n\t\t\tstd::cout << \"\\t\";\n\t\t\t\n\t\t\tbool ok = true;\n\t\t\tfor (int i=sz-8; i<sz; i++) \n\t\t\t\tfor (int j= i+1; j<sz; j++) \n\t\t\t\t\tif(c[i] == c[j]) ok = false;\n\n\t\t\tif(ok) std::cout << \"OK!!!!!\";\n\t\t\telse std::cout << \"NO\";\n\t\t\tstd::cout << std::endl;\n\t\t}\n\n\t}\n\t\n\t\n\tmpf_clear(x);\n\t\n\treturn 0;\n}\n", "meta": {"hexsha": "3bb4c288fb8c16b5f9cf52295d8dd869fb73b947", "size": 2659, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gen2017/divide.cpp", "max_stars_repo_name": "ale93111/PonderThisIBM", "max_stars_repo_head_hexsha": "5ab8da31e1e69ea333473e55937f02a826c7e166", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gen2017/divide.cpp", "max_issues_repo_name": "ale93111/PonderThisIBM", "max_issues_repo_head_hexsha": "5ab8da31e1e69ea333473e55937f02a826c7e166", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gen2017/divide.cpp", "max_forks_repo_name": "ale93111/PonderThisIBM", "max_forks_repo_head_hexsha": "5ab8da31e1e69ea333473e55937f02a826c7e166", "max_forks_repo_licenses": ["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.7253521127, "max_line_length": 93, "alphanum_fraction": 0.5675065814, "num_tokens": 1039, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4788190948288067}}
{"text": "#include <iostream>\n#include <vector>\n#include <string>\n#include <Eigen/Dense>\n#include <boost/python.hpp>\n#include <math.h>\n#include <chrono>\n#include <boost/python/numpy.hpp>\n\n\nusing namespace std;\nusing namespace boost::python;\nusing namespace Eigen;\nnamespace np = boost::python::numpy;\n\ntypedef vector<double> vec;\ntypedef vector<vec> mat;\n\n#define PI 3.14159265\n\nclass Arm {\npublic:\n  int numDOF;\n  boost::python::list displacements;\n  boost::python::list axes;\n  boost::python::list rotOffsets;\n  boost::python::tuple dispOffset;\n  boost::python::list velocity_limits;\n  boost::python::list joint_limits;\n  char* name;\n  Matrix3d rotX;\n  Matrix3d rotY;\n  Matrix3d rotZ;\n\n\n  Arm(boost::python::list axes, boost::python::list displacements,\n    boost::python::list rotOffsets, boost::python::tuple dispOffset, char* name) {\n    Py_Initialize();\n    np::initialize();\n    this->axes = axes;\n    this->displacements = displacements;\n    this->rotOffsets = rotOffsets;\n    this->dispOffset = dispOffset;\n    this->numDOF = len(displacements);\n    this->name = name;\n\n    this->rotX = MatrixXd::Zero(3,3);\n    this->rotY = MatrixXd::Zero(3,3);\n    this->rotZ = MatrixXd::Zero(3,3);\n\n    this->rotX(0,0) = 1.0;\n    this->rotY(1,1) = 1.0;\n    this->rotZ(2,2) = 1.0;\n  }\n\n  Matrix3d& rot3(char axis, double s, double c) {\n    if (axis == 'z' || axis == 'Z') {\n      this->rotZ(0,0) = c;\n      this->rotZ(0,1) = -s;\n      this->rotZ(1,0) = s;\n      this->rotZ(1,1) = c;\n      return this->rotZ;\n    }\n    else if(axis == 'y' || axis == 'Y') {\n      this->rotY(0,0) = c;\n      this->rotY(0,2) = s;\n      this->rotY(2,0) = -s;\n      this->rotY(2,2) = c;\n      return this->rotY;\n    }\n    else if(axis == 'x' || axis == 'X') {\n      this->rotX(1,1) = c;\n      this->rotX(1,2) = -s;\n      this->rotX(2,1) = s;\n      this->rotX(2,2) = c;\n      return this->rotX;\n    }\n    else {\n      cout << \"ERROR: not a valid axis label\";\n    }\n  }\n\n  boost::python::list getFrames(boost::python::list state) {\n    boost::python::list ret;\n    boost::python::list pts;\n    Vector3d pt = this->array(this->dispOffset);\n    pts.append(this->tolist(pt));\n    boost::python::list frames;\n    Matrix3d rot = MatrixXd::Zero(3,3);\n    rot(0,0) = 1.0;\n    rot(1,1) = 1.0;\n    rot(2,2) = 1.0;\n    frames.append(np::array(this->tolist(rot)));\n\n    for(int i = 0; i < this->numDOF; i++) {\n      double s = sin(extract<double>(state[i]));\n      double c = cos(extract<double>(state[i]));\n\n      //TODO: do rotation offsets\n\n      char curr_axis = extract<char>(this->axes[i]);\n\n      Matrix3d rmat = this->rot3(curr_axis,s,c);\n      rot = rot*rmat;\n      Vector3d disp;\n      disp(0) = extract<double>((this->displacements[i])[0]);\n      disp(1) = extract<double>((this->displacements[i])[1]);\n      disp(2) = extract<double>((this->displacements[i])[2]);\n      // cout << rot(1,1);\n      // cout << \"\\n\";\n      // high_resolution_clock::time_point t1 = high_resolution_clock::now();\n      pt = (rot*disp) + pt;\n      // high_resolution_clock::time_point t2 = high_resolution_clock::now();\n      // duration<double> time_span = duration_cast<duration<double>>(t2 - t1);\n      // std::cout << \"It took me \" << time_span.count() << \" seconds.\\n\";\n\n      pts.append(np::array(this->tolist(pt)));\n      frames.append(np::array(this->tolist(rot)));\n    }\n\n    ret.append(pts);\n    ret.append(frames);\n    return ret;\n  }\n\nprivate:\n\n  Vector3d array(boost::python::list input) {\n    Vector3d v;\n    v(0) = extract<double>(input[0]);\n    v(1) = extract<double>(input[1]);\n    v(2) = extract<double>(input[2]);\n    return v;\n  }\n\n  Vector3d array(boost::python::tuple input) {\n    Vector3d v;\n    v(0) = extract<double>(input[0]);\n    v(1) = extract<double>(input[1]);\n    v(2) = extract<double>(input[2]);\n    return v;\n  }\n\n  boost::python::list tolist(Vector3d v) {\n    boost::python::list l;\n    l.append(v(0));\n    l.append(v(1));\n    l.append(v(2));\n    return l;\n  }\n\n  mat tomat(Vector3d v) {\n    mat ret;\n    vec ve;\n    ve.push_back(v(0));\n    ve.push_back(v(1));\n    ve.push_back(v(2));\n    ret.push_back(ve);\n    return ret;\n  }\n\n  mat tomat(Matrix3d m) {\n    mat ret;\n    vec row1;\n    vec row2;\n    vec row3;\n\n    row1.push_back(m(0,0));\n    row1.push_back(m(0,1));\n    row1.push_back(m(0,2));\n\n    row2.push_back(m(1,0));\n    row2.push_back(m(1,1));\n    row2.push_back(m(1,2));\n\n    row3.push_back(m(2,0));\n    row3.push_back(m(2,1));\n    row3.push_back(m(2,2));\n\n    ret.push_back(row1);\n    ret.push_back(row2);\n    ret.push_back(row3);\n\n    return ret;\n  }\n\n  boost::python::list tolist(Matrix3d m) {\n    boost::python::list ret;\n    boost::python::list row1;\n    boost::python::list row2;\n    boost::python::list row3;\n\n    row1.append(m(0,0));\n    row1.append(m(0,1));\n    row1.append(m(0,2));\n\n    row2.append(m(1,0));\n    row2.append(m(1,1));\n    row2.append(m(1,2));\n\n    row3.append(m(2,0));\n    row3.append(m(2,1));\n    row3.append(m(2,2));\n\n    ret.append(row1);\n    ret.append(row2);\n    ret.append(row3);\n\n    return ret;\n  }\n\n  np::ndarray convert_to_numpy(mat const & input) {\n    u_int n_rows = input.size();\n    u_int n_cols = input[0].size();\n    boost::python::tuple shape = boost::python::make_tuple(n_rows, n_cols);\n    boost::python::tuple stride = boost::python::make_tuple(sizeof(double));\n    np::dtype dtype = np::dtype::get_builtin<double>();\n    boost::python::object own;\n    np::ndarray converted = np::zeros(shape, dtype);\n\n    for (u_int i = 0; i < n_rows; i++)\n    {\n        shape = boost::python::make_tuple(n_cols);\n        converted[i] = np::from_data(input[i].data(), dtype, shape, stride, own);\n    }\n    return converted;\n  }\n\n};\n\n\nBOOST_PYTHON_MODULE(Arm_ext) {\n    class_<Arm>(\"Arm\", init<boost::python::list, boost::python::list,\n    boost::python::list, boost::python::tuple, char*>())\n        .def(\"getFrames\", &Arm::getFrames)\n        .def_readwrite(\"numDOF\", &Arm::numDOF)\n        .def_readwrite(\"name\", &Arm::name)\n        .def_readwrite(\"velocity_limits\", &Arm::velocity_limits)\n        .def_readwrite(\"rotOffsets\", &Arm::rotOffsets)\n        .def_readwrite(\"dispOffset\", &Arm::dispOffset)\n        .def_readwrite(\"joint_limits\", &Arm::joint_limits)\n        .def_readwrite(\"displacements\", &Arm::displacements)\n        .def_readwrite(\"axes\", &Arm::axes)\n    ;\n}\n", "meta": {"hexsha": "42afce904bf6aeb09fd237218bd789a4c4469b2b", "size": 6284, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/RelaxedIK/Spacetime/boost/Arm.cpp", "max_stars_repo_name": "ajay5447/relaxed_ik", "max_stars_repo_head_hexsha": "e92cba393c4a0c405e8f2ebd6d1e76bcbf4f1ca6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 133.0, "max_stars_repo_stars_event_min_datetime": "2018-06-09T04:33:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T11:20:52.000Z", "max_issues_repo_path": "src/RelaxedIK/Spacetime/boost/Arm.cpp", "max_issues_repo_name": "ajay5447/relaxed_ik", "max_issues_repo_head_hexsha": "e92cba393c4a0c405e8f2ebd6d1e76bcbf4f1ca6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 29.0, "max_issues_repo_issues_event_min_datetime": "2018-08-02T16:27:54.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T02:52:33.000Z", "max_forks_repo_path": "src/RelaxedIK/Spacetime/boost/Arm.cpp", "max_forks_repo_name": "ajay5447/relaxed_ik", "max_forks_repo_head_hexsha": "e92cba393c4a0c405e8f2ebd6d1e76bcbf4f1ca6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2018-06-06T18:15:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T05:55:45.000Z", "avg_line_length": 25.5447154472, "max_line_length": 82, "alphanum_fraction": 0.5916613622, "num_tokens": 1955, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.78793120560257, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.4787967740067096}}
{"text": "/*\n * \n * Copyright (c) Kresimir Fresl 2002 \n *\n * Permission to copy, modify, use and distribute this software \n * for any non-commercial or commercial purpose is granted provided \n * that this license appear on all copies of the software source code.\n *\n * Author assumes no responsibility whatsoever for its use and makes \n * no guarantees about its quality, correctness or reliability.\n *\n * Author acknowledges the support of the Faculty of Civil Engineering, \n * University of Zagreb, Croatia.\n *\n */\n\n#ifndef BOOST_NUMERIC_BINDINGS_CBLAS3_OVERLOADS_HPP\n#define BOOST_NUMERIC_BINDINGS_CBLAS3_OVERLOADS_HPP\n\n#include <complex> \n#include <boost/numeric/bindings/atlas/cblas_inc.hpp>\n#include <boost/numeric/bindings/traits/type.hpp>\n\n\nnamespace boost { namespace numeric { namespace bindings { \n\n  namespace atlas { namespace detail {\n\n    // C <- alpha * op (A) * op (B) + beta * C \n  \n    inline \n    void gemm (CBLAS_ORDER const Order, \n               CBLAS_TRANSPOSE const TransA, CBLAS_TRANSPOSE const TransB, \n               int const M, int const N, int const K, \n               float const alpha, float const* A, int const lda,\n               float const* B, int const ldb, \n               float const beta, float* C, int const ldc) \n    {\n      cblas_sgemm (Order, TransA, TransB, M, N, K, \n                   alpha, A, lda, \n                   B, ldb,\n                   beta, C, ldc); \n    }\n\n    inline \n    void gemm (CBLAS_ORDER const Order, \n               CBLAS_TRANSPOSE const TransA, CBLAS_TRANSPOSE const TransB, \n               int const M, int const N, int const K, \n               double const alpha, double const* A, int const lda,\n               double const* B, int const ldb, \n               double const beta, double* C, int const ldc) \n    {\n      cblas_dgemm (Order, TransA, TransB, M, N, K, \n                   alpha, A, lda, \n                   B, ldb,\n                   beta, C, ldc); \n    }\n\n    inline \n    void gemm (CBLAS_ORDER const Order, \n               CBLAS_TRANSPOSE const TransA, CBLAS_TRANSPOSE const TransB, \n               int const M, int const N, int const K, \n               traits::complex_f const& alpha, \n               traits::complex_f const* A, int const lda,\n               traits::complex_f const* B, int const ldb, \n               traits::complex_f const& beta, \n               traits::complex_f* C, int const ldc) \n    {\n      cblas_cgemm (Order, TransA, TransB, M, N, K, \n                   static_cast<void const*> (&alpha), \n                   static_cast<void const*> (A), lda, \n                   static_cast<void const*> (B), ldb,\n                   static_cast<void const*> (&beta), \n                   static_cast<void*> (C), ldc); \n    }\n    \n    inline \n    void gemm (CBLAS_ORDER const Order, \n               CBLAS_TRANSPOSE const TransA, CBLAS_TRANSPOSE const TransB, \n               int const M, int const N, int const K, \n               traits::complex_d const& alpha, \n               traits::complex_d const* A, int const lda,\n               traits::complex_d const* B, int const ldb, \n               traits::complex_d const& beta, \n               traits::complex_d* C, int const ldc) \n    {\n      cblas_zgemm (Order, TransA, TransB, M, N, K, \n                   static_cast<void const*> (&alpha), \n                   static_cast<void const*> (A), lda, \n                   static_cast<void const*> (B), ldb,\n                   static_cast<void const*> (&beta), \n                   static_cast<void*> (C), ldc); \n    }\n\n    \n    // C <- alpha * A * B + beta * C \n    // C <- alpha * B * A + beta * C \n    // A == A^T\n\n    inline \n    void symm (CBLAS_ORDER const Order, CBLAS_SIDE const Side,\n               CBLAS_UPLO const Uplo, int const M, int const N, \n               float const alpha, float const* A, int const lda,\n               float const* B, int const ldb, \n               float const beta, float* C, int const ldc) \n    {\n      cblas_ssymm (Order, Side, Uplo, M, N, \n                   alpha, A, lda, \n                   B, ldb,\n                   beta, C, ldc); \n    }\n  \n    inline \n    void symm (CBLAS_ORDER const Order, CBLAS_SIDE const Side,\n               CBLAS_UPLO const Uplo, int const M, int const N, \n               double const alpha, double const* A, int const lda,\n               double const* B, int const ldb, \n               double const beta, double* C, int const ldc) \n    {\n      cblas_dsymm (Order, Side, Uplo, M, N, \n                   alpha, A, lda, \n                   B, ldb,\n                   beta, C, ldc); \n    }\n  \n    inline \n    void symm (CBLAS_ORDER const Order, CBLAS_SIDE const Side,\n               CBLAS_UPLO const Uplo, int const M, int const N, \n               traits::complex_f const& alpha, \n               traits::complex_f const* A, int const lda,\n               traits::complex_f const* B, int const ldb, \n               traits::complex_f const& beta, \n               traits::complex_f* C, int const ldc) \n    {\n      cblas_csymm (Order, Side, Uplo, M, N, \n                   static_cast<void const*> (&alpha), \n                   static_cast<void const*> (A), lda, \n                   static_cast<void const*> (B), ldb,\n                   static_cast<void const*> (&beta), \n                   static_cast<void*> (C), ldc); \n    }\n  \n    inline \n    void symm (CBLAS_ORDER const Order, CBLAS_SIDE const Side,\n               CBLAS_UPLO const Uplo, int const M, int const N, \n               traits::complex_d const& alpha, \n               traits::complex_d const* A, int const lda,\n               traits::complex_d const* B, int const ldb, \n               traits::complex_d const& beta, \n               traits::complex_d* C, int const ldc) \n    {\n      cblas_zsymm (Order, Side, Uplo, M, N, \n                   static_cast<void const*> (&alpha), \n                   static_cast<void const*> (A), lda, \n                   static_cast<void const*> (B), ldb,\n                   static_cast<void const*> (&beta), \n                   static_cast<void*> (C), ldc); \n    }\n  \n\n    // C <- alpha * A * B + beta * C \n    // C <- alpha * B * A + beta * C \n    // A == A^H\n  \n    inline \n    void hemm (CBLAS_ORDER const Order, CBLAS_SIDE const Side,\n               CBLAS_UPLO const Uplo, int const M, int const N, \n               traits::complex_f const& alpha, \n               traits::complex_f const* A, int const lda,\n               traits::complex_f const* B, int const ldb, \n               traits::complex_f const& beta, \n               traits::complex_f* C, int const ldc) \n    {\n      cblas_chemm (Order, Side, Uplo, M, N, \n                   static_cast<void const*> (&alpha), \n                   static_cast<void const*> (A), lda, \n                   static_cast<void const*> (B), ldb,\n                   static_cast<void const*> (&beta), \n                   static_cast<void*> (C), ldc); \n    }\n  \n    inline \n    void hemm (CBLAS_ORDER const Order, CBLAS_SIDE const Side,\n               CBLAS_UPLO const Uplo, int const M, int const N, \n               traits::complex_d const& alpha, \n               traits::complex_d const* A, int const lda,\n               traits::complex_d const* B, int const ldb, \n               traits::complex_d const& beta, \n               traits::complex_d* C, int const ldc) \n    {\n      cblas_zhemm (Order, Side, Uplo, M, N, \n                   static_cast<void const*> (&alpha), \n                   static_cast<void const*> (A), lda, \n                   static_cast<void const*> (B), ldb,\n                   static_cast<void const*> (&beta), \n                   static_cast<void*> (C), ldc); \n    }\n\n\n    // C <- alpha * A * A^T + beta * C\n    // C <- alpha * A^T * A + beta * C\n    // C == C^T\n\n    inline\n    void syrk (CBLAS_ORDER const Order, CBLAS_UPLO const Uplo,\n               CBLAS_TRANSPOSE const Trans, int const N, int const K,\n               float const alpha, float const* A, int const lda,\n               float const beta, float* C, int const ldc) \n    {\n      cblas_ssyrk (Order, Uplo, Trans, N, K, alpha, A, lda, beta, C, ldc); \n    }\n\n    inline\n    void syrk (CBLAS_ORDER const Order, CBLAS_UPLO const Uplo,\n               CBLAS_TRANSPOSE const Trans, int const N, int const K,\n               double const alpha, double const* A, int const lda,\n               double const beta, double* C, int const ldc) \n    {\n      cblas_dsyrk (Order, Uplo, Trans, N, K, alpha, A, lda, beta, C, ldc); \n    }\n\n    inline\n    void syrk (CBLAS_ORDER const Order, CBLAS_UPLO const Uplo,\n               CBLAS_TRANSPOSE const Trans, int const N, int const K,\n               traits::complex_f const& alpha, \n               traits::complex_f const* A, int const lda,\n               traits::complex_f const& beta, \n               traits::complex_f* C, int const ldc) \n    {\n      cblas_csyrk (Order, Uplo, Trans, N, K, \n                   static_cast<void const*> (&alpha), \n                   static_cast<void const*> (A), lda, \n                   static_cast<void const*> (&beta), \n                   static_cast<void*> (C), ldc); \n    }\n\n    inline\n    void syrk (CBLAS_ORDER const Order, CBLAS_UPLO const Uplo,\n               CBLAS_TRANSPOSE const Trans, int const N, int const K,\n               traits::complex_d const& alpha, \n               traits::complex_d const* A, int const lda,\n               traits::complex_d const& beta, \n               traits::complex_d* C, int const ldc) \n    {\n      cblas_zsyrk (Order, Uplo, Trans, N, K, \n                   static_cast<void const*> (&alpha), \n                   static_cast<void const*> (A), lda, \n                   static_cast<void const*> (&beta), \n                   static_cast<void*> (C), ldc); \n    }\n\n\n    // C <- alpha * A * B^T + conj(alpha) * B * A^T + beta * C\n    // C <- alpha * A^T * B + conj(alpha) * B^T * A + beta * C\n    // C == C^T\n\n    inline\n    void syr2k (CBLAS_ORDER const Order, CBLAS_UPLO const Uplo,\n                CBLAS_TRANSPOSE const Trans, int const N, int const K,\n                float const alpha, float const* A, int const lda,\n                float const* B, int const ldb,\n                float const beta, float* C, int const ldc) \n    {\n      cblas_ssyr2k (Order, Uplo, Trans, N, K, \n                    alpha, A, lda, B, ldb, beta, C, ldc); \n    }\n\n    inline\n    void syr2k (CBLAS_ORDER const Order, CBLAS_UPLO const Uplo,\n                CBLAS_TRANSPOSE const Trans, int const N, int const K,\n                double const alpha, double const* A, int const lda,\n                double const* B, int const ldb,\n                double const beta, double* C, int const ldc) \n    {\n      cblas_dsyr2k (Order, Uplo, Trans, N, K, \n                    alpha, A, lda, B, ldb, beta, C, ldc); \n    }\n\n    inline\n    void syr2k (CBLAS_ORDER const Order, CBLAS_UPLO const Uplo,\n                CBLAS_TRANSPOSE const Trans, int const N, int const K,\n                traits::complex_f const& alpha, \n                traits::complex_f const* A, int const lda,\n                traits::complex_f const* B, int const ldb,\n                traits::complex_f const& beta, \n                traits::complex_f* C, int const ldc) \n    {\n      cblas_csyr2k (Order, Uplo, Trans, N, K, \n                    static_cast<void const*> (&alpha), \n                    static_cast<void const*> (A), lda, \n                    static_cast<void const*> (B), ldb, \n                    static_cast<void const*> (&beta), \n                    static_cast<void*> (C), ldc); \n    }\n\n    inline\n    void syr2k (CBLAS_ORDER const Order, CBLAS_UPLO const Uplo,\n                CBLAS_TRANSPOSE const Trans, int const N, int const K,\n                traits::complex_d const& alpha, \n                traits::complex_d const* A, int const lda,\n                traits::complex_d const* B, int const ldb,\n                traits::complex_d const& beta, \n                traits::complex_d* C, int const ldc) \n    {\n      cblas_zsyr2k (Order, Uplo, Trans, N, K, \n                    static_cast<void const*> (&alpha), \n                    static_cast<void const*> (A), lda, \n                    static_cast<void const*> (B), ldb, \n                    static_cast<void const*> (&beta), \n                    static_cast<void*> (C), ldc); \n    }\n\n\n    // C <- alpha * A * A^H + beta * C\n    // C <- alpha * A^H * A + beta * C\n    // C == C^H\n\n    inline\n    void herk (CBLAS_ORDER const Order, CBLAS_UPLO const Uplo,\n               CBLAS_TRANSPOSE const Trans, int const N, int const K,\n               float alpha, traits::complex_f const* A, int const lda,\n               float beta, traits::complex_f* C, int const ldc) \n    {\n      cblas_cherk (Order, Uplo, Trans, N, K, \n                   alpha, static_cast<void const*> (A), lda, \n                   beta, static_cast<void*> (C), ldc); \n    }\n\n    inline\n    void herk (CBLAS_ORDER const Order, CBLAS_UPLO const Uplo,\n               CBLAS_TRANSPOSE const Trans, int const N, int const K,\n               double alpha, traits::complex_d const* A, int const lda,\n               double beta, traits::complex_d* C, int const ldc) \n    {\n      cblas_zherk (Order, Uplo, Trans, N, K, \n                   alpha, static_cast<void const*> (A), lda, \n                   beta, static_cast<void*> (C), ldc); \n    }\n\n\n    // C <- alpha * A * B^H + conj(alpha) * B * A^H + beta * C\n    // C <- alpha * A^H * B + conj(alpha) * B^H * A + beta * C\n    // C == C^H\n\n    inline\n    void her2k (CBLAS_ORDER const Order, CBLAS_UPLO const Uplo,\n                CBLAS_TRANSPOSE const Trans, int const N, int const K,\n                traits::complex_f const& alpha, \n                traits::complex_f const* A, int const lda,\n                traits::complex_f const* B, int const ldb,\n                float beta, traits::complex_f* C, int const ldc) \n    {\n      cblas_cher2k (Order, Uplo, Trans, N, K, \n                    static_cast<void const*> (&alpha), \n                    static_cast<void const*> (A), lda, \n                    static_cast<void const*> (B), ldb, \n                    beta, static_cast<void*> (C), ldc); \n    }\n\n    inline\n    void her2k (CBLAS_ORDER const Order, CBLAS_UPLO const Uplo,\n                CBLAS_TRANSPOSE const Trans, int const N, int const K,\n                traits::complex_d const& alpha, \n                traits::complex_d const* A, int const lda,\n                traits::complex_d const* B, int const ldb,\n                double beta, traits::complex_d* C, int const ldc) \n    {\n      cblas_zher2k (Order, Uplo, Trans, N, K, \n                    static_cast<void const*> (&alpha), \n                    static_cast<void const*> (A), lda, \n                    static_cast<void const*> (B), ldb, \n                    beta, static_cast<void*> (C), ldc); \n    }\n\n  \n  }} // namepaces detail & atlas\n\n}}} \n\n\n#endif // BOOST_NUMERIC_BINDINGS_CBLAS3_OVERLOADS_HPP\n", "meta": {"hexsha": "fcec436f61b99559692c3c01f66c345671b0852d", "size": 14729, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "applications/mkl_solvers_application/external_includes/boost/numeric/bindings/atlas/cblas3_overloads.hpp", "max_stars_repo_name": "jiaqiwang969/Kratos-test", "max_stars_repo_head_hexsha": "ed082abc163e7b627f110a1ae1da465f52f48348", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "applications/mkl_solvers_application/external_includes/boost/numeric/bindings/atlas/cblas3_overloads.hpp", "max_issues_repo_name": "jiaqiwang969/Kratos-test", "max_issues_repo_head_hexsha": "ed082abc163e7b627f110a1ae1da465f52f48348", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "applications/mkl_solvers_application/external_includes/boost/numeric/bindings/atlas/cblas3_overloads.hpp", "max_forks_repo_name": "jiaqiwang969/Kratos-test", "max_forks_repo_head_hexsha": "ed082abc163e7b627f110a1ae1da465f52f48348", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.557591623, "max_line_length": 75, "alphanum_fraction": 0.5264444294, "num_tokens": 3818, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.78793120560257, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.4787967740067096}}
{"text": "/*\n * van_der_pol_stiff.cpp\n *  \n * Created on: Dec 12, 2011\n *\n * Copyright 2011 Rajeev Singh\n *\n * Distributed under the Boost Software License, Version 1.0.\n * (See accompanying file LICENSE_1_0.txt or\n * copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#include <iostream>\n#include <fstream>\n#include <utility>\n\n#include <boost/numeric/odeint.hpp>\n\n#include <boost/phoenix/core.hpp>\n#include <boost/phoenix/operator.hpp>\n\nusing namespace std;\nusing namespace boost::numeric::odeint;\nnamespace phoenix = boost::phoenix;\n\nconst double mu = 1000.0;\n\n\ntypedef boost::numeric::ublas::vector< double > vector_type;\ntypedef boost::numeric::ublas::matrix< double > matrix_type;\n\nstruct vdp_stiff\n{\n    void operator()( const vector_type &x , vector_type &dxdt , double t )\n    {\n        dxdt[0] = x[1];\n        dxdt[1] = -x[0] - mu * x[1] * (x[0]*x[0]-1.0);\n    }\n};\n\nstruct vdp_stiff_jacobi\n{\n    void operator()( const vector_type &x , matrix_type &J , const double &t , vector_type &dfdt )\n    {\n        J(0, 0) = 0.0;\n        J(0, 1) = 1.0;\n        J(1, 0) = -1.0 - 2.0*mu * x[0] * x[1];\n        J(1, 1) = -mu * ( x[0] * x[0] - 1.0);\n\n        dfdt[0] = 0.0;\n        dfdt[1] = 0.0;\n    }\n};\n\n\nint main( int argc , char **argv )\n{\n    //[ integrate_stiff_system\n    vector_type x( 2 );\n    /* initialize random seed: */\n    srand ( time(NULL) );\n\n    // initial conditions\n    for (int i=0; i<2; i++)\n        x[i] = 1.0; //(1.0 * rand()) / RAND_MAX;\n\n    size_t num_of_steps = integrate_const( make_dense_output< rosenbrock4< double > >( 1.0e-6 , 1.0e-6 ) ,\n            make_pair( vdp_stiff() , vdp_stiff_jacobi() ) ,\n            x , 0.0 , 1000.0 , 1.0\n            , cout << phoenix::arg_names::arg2 << \" \" << phoenix::arg_names::arg1[0] << \" \" << phoenix::arg_names::arg1[1] << \"\\n\"\n            );\n    //]\n    clog << num_of_steps << endl;\n\n\n\n    //[ integrate_stiff_system_alternative\n\n    vector_type x2( 2 );\n    // initial conditions\n    for (int i=0; i<2; i++)\n        x2[i] = 1.0; //(1.0 * rand()) / RAND_MAX;\n\n    size_t num_of_steps2 = integrate_const( make_dense_output< runge_kutta_dopri5< vector_type > >( 1.0e-6 , 1.0e-6 ) ,\n            vdp_stiff() , x2 , 0.0 , 1000.0 , 1.0\n            , cout << phoenix::arg_names::arg2 << \" \" << phoenix::arg_names::arg1[0] << \" \" << phoenix::arg_names::arg1[1] << \"\\n\"\n            );\n    //]\n    clog << num_of_steps2 << endl;\n\n\n    return 0;\n}\n", "meta": {"hexsha": "4b433b24f604e5fdcabdcdac8bd0680b9d780fd3", "size": 2395, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Modules/ego_planner/ego-planner-swarm/src/uav_simulator/so3_quadrotor_simulator/include/ode/libs/numeric/odeint/examples/van_der_pol_stiff.cpp", "max_stars_repo_name": "473867143/Prometheus", "max_stars_repo_head_hexsha": "df1e1b0d861490223ac8b94d8cc4796537172292", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1217.0, "max_stars_repo_stars_event_min_datetime": "2020-07-02T13:15:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T06:17:44.000Z", "max_issues_repo_path": "Modules/ego_planner/ego-planner-swarm/src/uav_simulator/so3_quadrotor_simulator/include/ode/libs/numeric/odeint/examples/van_der_pol_stiff.cpp", "max_issues_repo_name": "473867143/Prometheus", "max_issues_repo_head_hexsha": "df1e1b0d861490223ac8b94d8cc4796537172292", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 167.0, "max_issues_repo_issues_event_min_datetime": "2020-07-12T15:35:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T11:57:40.000Z", "max_forks_repo_path": "Modules/ego_planner/ego-planner-swarm/src/uav_simulator/so3_quadrotor_simulator/include/ode/libs/numeric/odeint/examples/van_der_pol_stiff.cpp", "max_forks_repo_name": "473867143/Prometheus", "max_forks_repo_head_hexsha": "df1e1b0d861490223ac8b94d8cc4796537172292", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 270.0, "max_forks_repo_forks_event_min_datetime": "2020-07-02T13:28:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T05:43:08.000Z", "avg_line_length": 25.4787234043, "max_line_length": 130, "alphanum_fraction": 0.569519833, "num_tokens": 815, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.4787967679545817}}
{"text": "#include <string>\n#include <algorithm>\n#include <vector>\n#include <array>\n#include <memory>\n#include <map>\n#include <cassert>\n#include <fstream>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_real_distribution.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp> \n#include \"DatasetAR.h\"\n#include \"GaussSeq.h\"\n#include \"ZeroSeq.h\"\n#include \"utils.h\"\nusing utils::my_float;\nusing boost::random::uniform_real_distribution;\n\n\n/*\n *  Member variables\n */\nboost::random::mt19937 DatasetAR::gen {};\n\n\n/*\n *  Helper functions\n *\n *  All \"noise setters\" require the target sequence be defined.\n */\nvoid DatasetAR::noise_zero() {\n    for (auto i = 0; i < utils::FEAT_COUNT; i++) {\n        feats.push_back(std::make_unique<ZeroSeq>());\n    }\n    feats[utils::SALIENT_IND] = std::make_unique<ARSeq>(this->target);\n}\nvoid DatasetAR::noise_one() {\n    for (auto i = 0; i < utils::FEAT_COUNT; i++) {\n        feats.push_back(std::make_unique<GaussSeq>());\n    }\n    feats[utils::SALIENT_IND] = std::make_unique<ARSeq>(this->target);\n}\nvoid DatasetAR::noise_two() {\n    uniform_real_distribution<my_float> u_mean(-10, 10);\n    uniform_real_distribution<my_float> u_std(0.1, 5);\n\n    for (auto i = 0; i < utils::FEAT_COUNT; i++) {\n        feats.push_back(std::make_unique<GaussSeq>(u_mean(gen), u_std(gen)));\n    }\n    feats[utils::SALIENT_IND] = std::make_unique<ARSeq>(this->target);\n}\nvoid DatasetAR::noise_three() {\n    uniform_real_distribution<my_float> u_const(0, 1);\n    uniform_real_distribution<my_float> u_coeff(-0.9, 0.9);\n    uniform_real_distribution<my_float> u_seed(-1, 1);\n    std::vector<my_float> seed_vect {u_seed(gen),};\n    std::map<int, my_float> coeff_map {\n        {1, u_coeff(gen)},\n    };\n\n    for (auto i = 0; i < utils::FEAT_COUNT; i++) {\n        // prep seq backing\n        coeff_map[1] = u_coeff(gen);\n        seed_vect[0] = u_seed(gen);\n\n        ARSeq in_seq(coeff_map, u_const(gen));\n        in_seq.seed_prev_vals(seed_vect);\n\n        feats.push_back(std::make_unique<ARSeq>(in_seq));\n    }\n    feats[utils::SALIENT_IND] = std::make_unique<ARSeq>(this->target);\n}\nvoid DatasetAR::noise_four() {\n    uniform_real_distribution<my_float> u_const(-1000000, -999999);\n    uniform_real_distribution<my_float> u_coeff(1.1, 2);\n    uniform_real_distribution<my_float> u_seed(0, 0.0000001);\n    std::vector<my_float> seed_vect {u_seed(gen),};\n    std::map<int, my_float> coeff_map {\n        {1, u_coeff(gen)},\n    };\n\n    for (auto i = 0; i < utils::FEAT_COUNT; i++) {\n        // prep seq backing\n        coeff_map[1] = u_coeff(gen);\n        seed_vect[0] = u_seed(gen);\n\n        ARSeq in_seq(coeff_map, u_const(gen));\n        in_seq.seed_prev_vals(seed_vect);\n\n        feats.push_back(std::make_unique<ARSeq>(in_seq));\n    }\n    feats[utils::SALIENT_IND] = std::make_unique<ARSeq>(this->target);\n}\n\n\n/*\n *  Constructors and destructors\n */\nDatasetAR::DatasetAR(std::string file_name, ARSeq target_seq):\n    fname{file_name.append(\".csv\")},\n    target{target_seq}\n    {};\n\nDatasetAR::DatasetAR(std::string file_name, ARSeq target_seq, unsigned char type):\n    fname{file_name.append(\".csv\")},\n    noise_type{type},\n    target{target_seq} {\n    set_noise(type);\n}\n\n\n/*\n *  Member functions\n */\nvoid DatasetAR::set_noise(unsigned char type) {\n    this->noise_type = type;\n\n    switch (type) {\n        case 0: this->noise_zero();\n                break;\n        case 1: this->noise_one();\n                break;\n        case 2: this->noise_two();\n                break;\n        case 3: this->noise_three();\n                break;\n        case 4: this->noise_four();\n                break;\n    }\n    this->prev_targ_val = feats[utils::SALIENT_IND]->next();\n}\nstd::array<std::array<my_float, utils::FEAT_COUNT + 1>, utils::TIME_STEP>\n    DatasetAR::generate_normalized_dat() {\n    namespace mp = boost::multiprecision;\n    constexpr int T = utils::TIME_STEP;\n    constexpr int F = utils::FEAT_COUNT;\n    // observe storage[feat][time] indexing\n    std::array<std::array<my_float, T + 1>, F> storage {};  \n    std::array<my_float, T + 1> targ_storage {};            // storage for target\n\n    /*\n     *  Prepare progress bar\n     */\n\n    // offset used to determine when to update progress bar\n    int offset_mod = static_cast<int>(F / 10);\n    int offset_counter {0};\n    // print initial progress bar\n    std::cout << \"[\";\n    for (auto i = 0; i < 10; i++) {\n        std::cout << \" \";\n    }\n    std::cout << \"]\\r\";\n\n\n    /*\n     *  Store non-normalized values\n     */\n\n    // Store time-delayed values\n    // If noise type 3 or 4, then there is one previous value as a ARSeq.\n    // Otherwise, simply invoke next()\n    if (this->noise_type == 3 || this->noise_type == 4) {\n        for (auto f = 0; f < F; f++) {\n            if (f == utils::SALIENT_IND) \n                targ_storage[0] = this->prev_targ_val;\n            else \n                storage[f][0] = dynamic_cast<ARSeq*>(feats[f].get())->get_prev_val()[0];\n        }\n    } else {\n        for (auto f = 0; f < F; f++) {\n            if (f == utils::SALIENT_IND) \n                targ_storage[0] = this->prev_targ_val;\n            else \n                storage[f][0] = feats[f]->next();\n        }\n    }\n\n    // Store current values (those non-negative)\n    for (auto f = 0; f < F; f++) {\n        // print progress bar\n        if ((f - 1) % offset_mod == 0) {\n            offset_counter++;\n\n            std::cout << \"[\";\n            for (auto i = 0; i < offset_counter; i++) {\n                std::cout << \"X\";\n            }\n            for (auto i = 0; i < 10 - offset_counter; i++) {\n                std::cout << \" \";\n            }\n            std::cout << \"]\\r\";\n        }\n\n        // write and record sequences\n        for (int t = 1; t < T + 1; t++) {\n            if (f != utils::SALIENT_IND) \n                storage[f][t] = feats[f]->next();\n            else {\n                // target column\n                this->prev_targ_val = feats[utils::SALIENT_IND]->next();\n                targ_storage[t] = this->prev_targ_val;\n            }\n        }\n    }\n\n    /*\n     *  Normalize array values according to utils::NORM_VAL via min-max norm\n     */\n    my_float feat_min {0};\n    my_float feat_max {0};\n    // observe normalized_feats[time][feat] indexing\n    std::array<std::array<my_float, F + 1>, T> normalized_feats {};\n\n    // set normalized non-targ vals\n    for (auto f = 0; f < F; f++) {\n        if (f != utils::SALIENT_IND) {\n            // if we have zero values, no need to rescale\n            if (this->noise_type == 0) {\n                for (auto t = 0; t < T; t++) {\n                    normalized_feats[t][f] = storage[f][t];\n                }\n            } else {\n                feat_min = *std::min_element(storage[f].begin(), storage[f].end());\n                feat_max = *std::max_element(storage[f].begin(), storage[f].end());\n                \n                for (auto t = 0; t < T; t++) {\n                    if (feat_max - feat_min == 0) \n                        normalized_feats[t][f] = (utils::NORM_VAL * 2 * (storage[f][t] - feat_min)) - \n                            utils::NORM_VAL;\n                    else\n                        normalized_feats[t][f] = (utils::NORM_VAL * 2 * ((storage[f][t] - feat_min) / \n                            (feat_max - feat_min))) - utils::NORM_VAL;\n                }\n            }\n        } else {\n            feat_min = *std::min_element(targ_storage.begin(), targ_storage.end());\n            feat_max = *std::max_element(targ_storage.begin(), targ_storage.end());\n\n            for (auto t = 0; t < T; t++) {\n                if (feat_max - feat_min == 0) {\n                    normalized_feats[t][utils::SALIENT_IND] = (utils::NORM_VAL * 2 * (targ_storage[t] - feat_min)) - \n                        utils::NORM_VAL;\n                    normalized_feats[t][F] = (utils::NORM_VAL * 2 * (targ_storage[t + 1] - feat_min)) - \n                        utils::NORM_VAL;\n                } else {\n                    normalized_feats[t][utils::SALIENT_IND] = (utils::NORM_VAL * 2 * ((targ_storage[t] - feat_min) / \n                        (feat_max - feat_min))) - utils::NORM_VAL;\n                    normalized_feats[t][F] = (utils::NORM_VAL * 2 * ((targ_storage[t + 1] - feat_min) / \n                        (feat_max - feat_min))) - utils::NORM_VAL;\n                }\n            }\n        }\n    }\n\n    return normalized_feats;\n} \n\nvoid DatasetAR::write_csv() {\n    // was the noise value assigned?\n    assert(this->noise_type != 10);\n\n\n    // storage for normalize values\n    constexpr int T = utils::TIME_STEP;\n    constexpr int F = utils::FEAT_COUNT;\n    std::array<std::array<my_float, F + 1>, T> storage = generate_normalized_dat();\n\n\n    // initialize csv\n    std::ofstream synth_data {this->fname};\n    synth_data << std::setprecision(25);\n    \n    // prepare labels\n    for (auto i = 0; i < utils::FEAT_COUNT + 2; i++) {\n        if (i == 0)\n            synth_data << \"Time,\";\n        else if (i == utils::FEAT_COUNT + 1)\n            synth_data << \"Target\\n\";\n        else \n            synth_data << \"Feature_\" << i << \",\";\n    }\n\n    // write values to csv\n    for (auto t = 0; t < T; t++) {\n        for (auto f = 0; f < F + 2; f++) {\n            // time column\n            if (f == 0)\n                synth_data << t << \",\";\n            // target column\n            else if (f == utils::FEAT_COUNT + 1)\n                synth_data << storage[t][f - 1] << \"\\n\";\n            // data column\n            else \n                synth_data << storage[t][f - 1] << \",\";\n        }\n    }\n    std::cout << \"\\nFinished writing \" << this->fname << \"!\\n\";\n    synth_data.close();\n}\n", "meta": {"hexsha": "b76768c7952a2bb7c5a824bedf3ceaa69f072a08", "size": 9621, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gen-data/lib/DatasetAR.cpp", "max_stars_repo_name": "kvathupo/Synthetic-Time-Series-Generator", "max_stars_repo_head_hexsha": "ac133d2b0beff7f93f686742ce59401bc3cd1b90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gen-data/lib/DatasetAR.cpp", "max_issues_repo_name": "kvathupo/Synthetic-Time-Series-Generator", "max_issues_repo_head_hexsha": "ac133d2b0beff7f93f686742ce59401bc3cd1b90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gen-data/lib/DatasetAR.cpp", "max_forks_repo_name": "kvathupo/Synthetic-Time-Series-Generator", "max_forks_repo_head_hexsha": "ac133d2b0beff7f93f686742ce59401bc3cd1b90", "max_forks_repo_licenses": ["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.9634551495, "max_line_length": 117, "alphanum_fraction": 0.5394449641, "num_tokens": 2592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.47879676795458165}}
{"text": "//\n// Created by jk on 2020/3/8.\n//\n// #define R_BUILD\n#ifdef R_BUILD\n#include <Rcpp.h>\n#include <RcppEigen.h>\n// [[Rcpp::depends(RcppEigen)]]\nusing namespace Rcpp;\n#else\n#include <Eigen/Eigen>\n#include \"List.h\"\n#endif\n#include <algorithm>\n#include <vector>\n#include <iostream>\n\nusing namespace std;\n\nvoid Normalize(Eigen::MatrixXd &X, Eigen::VectorXd &y, Eigen::VectorXd &weights, Eigen::VectorXd &meanx, double &meany, Eigen::VectorXd &normx)\n{\n    int n = X.rows();\n    int p = X.cols();\n    Eigen::VectorXd tmp(n);\n    for (int i = 0; i < p; i++)\n    {\n        meanx(i) = weights.dot(X.col(i)) / double(n);\n    }\n    meany = (y.dot(weights)) / double(n);\n    for (int i = 0; i < p; i++)\n    {\n        X.col(i) = X.col(i).array() - meanx(i);\n    }\n    y = y.array() - meany;\n\n    for (int i = 0; i < p; i++)\n    {\n        tmp = X.col(i);\n        tmp = tmp.array().square();\n        normx(i) = sqrt(weights.dot(tmp));\n    }\n    for (int i = 0; i < p; i++)\n    {\n        X.col(i) = sqrt(double(n)) * X.col(i) / normx(i);\n    }\n}\n\nvoid Normalize(Eigen::MatrixXd &X, Eigen::MatrixXd &y, Eigen::VectorXd &weights, Eigen::VectorXd &meanx, Eigen::VectorXd &meany, Eigen::VectorXd &normx)\n{\n    // cout << \"multigaussian normal\" << endl;\n    int n = X.rows();\n    int p = X.cols();\n    Eigen::VectorXd tmp(n);\n    for (int i = 0; i < p; i++)\n    {\n        meanx(i) = weights.dot(X.col(i)) / double(n);\n    }\n    meany = y.transpose() * weights / double(n);\n    // cout << \"meany: \" << meany << endl;\n    for (int i = 0; i < p; i++)\n    {\n        X.col(i) = X.col(i).array() - meanx(i);\n    }\n\n    for (int i = 0; i < n; i++)\n    {\n        y.row(i) = y.row(i) - meany;\n    }\n    // y = y.array() - meany;\n\n    for (int i = 0; i < p; i++)\n    {\n        tmp = X.col(i);\n        tmp = tmp.array().square();\n        normx(i) = sqrt(weights.dot(tmp));\n    }\n    for (int i = 0; i < p; i++)\n    {\n        X.col(i) = sqrt(double(n)) * X.col(i) / normx(i);\n    }\n}\n\nvoid Normalize3(Eigen::MatrixXd &X, Eigen::VectorXd &weights, Eigen::VectorXd &meanx, Eigen::VectorXd &normx)\n{\n    int n = X.rows();\n    int p = X.cols();\n    Eigen::VectorXd tmp(n);\n    for (int i = 0; i < p; i++)\n    {\n        meanx(i) = weights.dot(X.col(i)) / double(n);\n    }\n    for (int i = 0; i < p; i++)\n    {\n        X.col(i) = X.col(i).array() - meanx(i);\n    }\n    for (int i = 0; i < p; i++)\n    {\n        tmp = X.col(i);\n        tmp = tmp.array().square();\n        normx(i) = sqrt(weights.dot(tmp));\n    }\n    for (int i = 0; i < p; i++)\n    {\n        X.col(i) = sqrt(double(n)) * X.col(i) / normx(i);\n    }\n}\n\nvoid Normalize4(Eigen::MatrixXd &X, Eigen::VectorXd &weights, Eigen::VectorXd &normx)\n{\n    int n = X.rows();\n    int p = X.cols();\n    Eigen::VectorXd tmp(n);\n    for (int i = 0; i < p; i++)\n    {\n        tmp = X.col(i);\n        tmp = tmp.array().square();\n        normx(i) = sqrt(weights.dot(tmp));\n    }\n    for (int i = 0; i < p; i++)\n    {\n        X.col(i) = sqrt(double(n)) * X.col(i) / normx(i);\n    }\n}\n\nvoid Normalize(Eigen::SparseMatrix<double> &X, Eigen::VectorXd &y, Eigen::VectorXd &weights, Eigen::VectorXd &meanx, double &meany, Eigen::VectorXd &normx) { return; }\nvoid Normalize(Eigen::SparseMatrix<double> &X, Eigen::MatrixXd &y, Eigen::VectorXd &weights, Eigen::VectorXd &meanx, Eigen::VectorXd &meany, Eigen::VectorXd &normx) { return; }\nvoid Normalize3(Eigen::SparseMatrix<double> &X, Eigen::VectorXd &y, Eigen::VectorXd &meanx, Eigen::VectorXd &normx) { return; }\nvoid Normalize4(Eigen::SparseMatrix<double> &X, Eigen::VectorXd &y, Eigen::VectorXd &normx) { return; }", "meta": {"hexsha": "a64164982c12635d144cb0651e384af568a88853", "size": 3566, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/normalize.cpp", "max_stars_repo_name": "adaizjx/abess", "max_stars_repo_head_hexsha": "a4374abaa56573c5ebf6ca51b641a1e8548fd554", "max_stars_repo_licenses": ["CNRI-Python", "CECILL-B"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-06T08:06:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T08:06:13.000Z", "max_issues_repo_path": "src/normalize.cpp", "max_issues_repo_name": "adaizjx/abess", "max_issues_repo_head_hexsha": "a4374abaa56573c5ebf6ca51b641a1e8548fd554", "max_issues_repo_licenses": ["CNRI-Python", "CECILL-B"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/normalize.cpp", "max_forks_repo_name": "adaizjx/abess", "max_forks_repo_head_hexsha": "a4374abaa56573c5ebf6ca51b641a1e8548fd554", "max_forks_repo_licenses": ["CNRI-Python", "CECILL-B"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.859375, "max_line_length": 176, "alphanum_fraction": 0.531688166, "num_tokens": 1133, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.47879676795458165}}
{"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\u00e4nkt), 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_FSM_INCLUDE\n#define ITL_FSM_INCLUDE\n\n#include <boost/numeric/mtl/operation/two_norm.hpp>\n\nnamespace itl {\n\n/// Folded spectrum method\n/** Computed and named as in http://en.wikipedia.org/wiki/Folded_spectrum_method **/\ntemplate < typename LinearOperator, typename VectorSpace, typename EigenValue, \n\t   typename Damping, typename Iteration >\nint fsm(const LinearOperator& H, VectorSpace& phi, EigenValue eps, Damping alpha, Iteration& iter)\n{\n    VectorSpace v1(H * phi - eps * phi);\n    for (; !iter.finished(v1); ++iter) {\n\tVectorSpace v2(H * v1 - eps * v1);\n\tphi-= alpha * v2;\n\tphi/= two_norm(phi);\n\tv1= H * phi - eps * phi;\n    }\n    return iter;\n}\n\n\n} // namespace itl\n\n#endif // ITL_FSM_INCLUDE\n", "meta": {"hexsha": "e398bcef1dbf113fcf6fbe4a1c67389430e08c75", "size": 1159, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/itl/krylov/fsm.hpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "lib/mtl4/boost/numeric/itl/krylov/fsm.hpp", "max_issues_repo_name": "spraetor/amdis2", "max_issues_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "lib/mtl4/boost/numeric/itl/krylov/fsm.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": 28.975, "max_line_length": 98, "alphanum_fraction": 0.7006039689, "num_tokens": 306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311856832191, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.4787967619024537}}
{"text": "/*\n@copyright Louis Dionne 2014\nDistributed under the Boost Software License, Version 1.0.\n(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n */\n\n#include <boost/hana/detail/assert.hpp>\n#include <boost/hana/detail/constexpr.hpp>\n#include <boost/hana/integral.hpp>\n#include <boost/hana/list/instance.hpp>\n#include <boost/hana/range.hpp>\nusing namespace boost::hana;\nusing namespace literals;\n\n\nint main() {\n    //! [main]\n    BOOST_HANA_CONSTEXPR_LAMBDA auto negative = [](auto x) {\n        return x < int_<0>;\n    };\n\n    BOOST_HANA_CONSTANT_ASSERT(\n        drop_while(negative, range(int_<-3>, int_<6>)) == range(int_<0>, int_<6>)\n    );\n\n    BOOST_HANA_CONSTANT_ASSERT(\n        drop_while(negative, list(1_c, -2_c, 4_c, 5_c)) == list(1_c, -2_c, 4_c, 5_c)\n    );\n    //! [main]\n}\n", "meta": {"hexsha": "914c9c25e4f23b6cdf851cf8dc266fbda2eb6371", "size": 810, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/iterable/drop_while.cpp", "max_stars_repo_name": "rbock/hana", "max_stars_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-05-07T14:29:13.000Z", "max_stars_repo_stars_event_max_datetime": "2015-07-04T10:59:46.000Z", "max_issues_repo_path": "example/iterable/drop_while.cpp", "max_issues_repo_name": "rbock/hana", "max_issues_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/iterable/drop_while.cpp", "max_forks_repo_name": "rbock/hana", "max_forks_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.1290322581, "max_line_length": 84, "alphanum_fraction": 0.675308642, "num_tokens": 230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.47876749963830384}}
{"text": "/**\n * @file seg_maths.cpp\n * @author M. Jorge Cardoso\n * @date 01/01/2014\n *\n * Copyright (c) 2014, University College London. All rights reserved.\n * Centre for Medical Image Computing (CMIC)\n * See the LICENSE.txt file in the nifty_seg root folder\n *\n */\n\n#include <iostream>\n#include <time.h>\n#include \"_seg_common.h\"\n#include \"_seg_tools.h\"\n#include <Eigen/Core>\n#include <Eigen/LU>\n#include <Eigen/Cholesky>\n#include <cfloat>\n\nusing namespace std;\n#define SegPrecisionTYPE float\n\nvoid Usage(char *exec)\n{\n    printf(\"* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\\n\");\n    printf(\"\\nMath tools:\\nUsage:\\t%s <input> <operation> <output>.\\n\\n\",exec);\n    printf(\"\\t* * Operations on 3-D and 4-D images* *\\n\");\n    printf(\"\\t-mul\\t<float/file>\\tMultiply image <float> value or by other image.\\n\");\n    printf(\"\\t-div\\t<float/file>\\tDivide image by <float> or by other image.\\n\");\n    printf(\"\\t-add\\t<float/file>\\tAdd image by <float> or by other image.\\n\");\n    printf(\"\\t-sub\\t<float/file>\\tSubtract image by <float> or by other image.\\n\");\n    printf(\"\\t-pow\\t<float>\\t\\tImage to the power of <float>.\\n\");\n    printf(\"\\t-thr\\t<float>\\t\\tThreshold the image below <float>.\\n\");\n    printf(\"\\t-uthr\\t<float>\\t\\tThreshold image above <float>.\\n\");\n    printf(\"\\t-smo\\t<float>\\t\\tGaussian smoothing by std <float> (in voxels and up to 4-D).\\n\");\n    printf(\"\\t-equal\\t<int>\\t\\tGet voxels equal to <int>\\n\");\n    printf(\"\\t-replace <int1> <int2>\\tReplaces voxels equal to <int1> with <int2>\\n\");\n    printf(\"\\t-sqrt \\t\\t\\tSquare root of the image.\\n\");\n    printf(\"\\t-exp \\t\\t\\tExponential root of the image.\\n\");\n    printf(\"\\t-log \\t\\t\\tLog of the image.\\n\");\n    printf(\"\\t-recip \\t\\t\\tReciprocal (1/I) of the image.\\n\");\n    printf(\"\\t-abs \\t\\t\\tAbsolute value of the image.\\n\");\n    printf(\"\\t-bin \\t\\t\\tBinarise the image.\\n\");\n    printf(\"\\t-otsu \\t\\t\\tOtsu thresholding of the current image.\\n\");\n    printf(\"\\t-edge\\t<float>\\t\\tCalculate the edges of the image using a threshold <float>.\\n\");\n    printf(\"\\t-sobel3\\t<float>\\t\\tCalculate the edges of all timepoints using a Sobel filter with a 3x3x3 kernel and applying <float> gaussian smoothing.\\n\");\n    printf(\"\\t-sobel5\\t<float>\\t\\tCalculate the edges of all timepoints using a Sobel filter with a 5x5x5 kernel and applying <float> gaussian smoothing.\\n\");\n    printf(\"\\t-min\\t<file>\\t\\tGet the min per voxel between <current> and <file>.\\n\");\n    printf(\"\\n\\t* * Operations on 3-D images * *\\n\");\n    printf(\"\\t-smol\\t<float>\\t\\tGaussian smoothing of a 3D label image.\\n\");\n    printf(\"\\t-dil\\t<int>\\t\\tDilate the image <int> times (in voxels).\\n\");\n    printf(\"\\t-ero\\t<int>\\t\\tErode the image <int> times (in voxels).\\n\");\n    printf(\"\\t-pad\\t<int>\\t\\tPad <int> voxels with NaN value around each 3D volume.\\n\");\n    printf(\"\\t-crop\\t<int>\\t\\tCrop <int> voxels around each 3D volume.\\n\");    \n    printf(\"\\n\\t* * Operations binary 3-D images * *\\n\");\n    printf(\"\\t-lconcomp\\t\\tTake the largest connected component\\n\");\n    printf(\"\\t-concomp6\\t\\tLabel the different connected components with a 6NN kernel\\n\");\n    printf(\"\\t-concomp26\\t\\tLabel the different connected components with a 26NN kernel\\n\");\n    printf(\"\\t-fill\\t\\t\\tFill holes in binary object (e.g. fill ventricle in brain mask).\\n\");\n    printf(\"\\t-euc\\t\\t\\tEuclidean distance trasnform\\n\");\n    printf(\"\\t-geo <float/file>\\tGeodesic distance according to the speed function <float/file>\\n\");\n    printf(\"\\n\\t* * Dimensionality reduction operations: from 4-D to 3-D * *\\n\");\n    printf(\"\\t-tp <int>\\t\\tExtract time point <int>\\n\");\n    printf(\"\\t-tpmax\\t\\t\\tGet the time point with the highest value (binarise 4D probabilities)\\n\");\n    printf(\"\\t-tmean\\t\\t\\tMean value of all time points.\\n\");\n    printf(\"\\t-tmax\\t\\t\\tMax value of all time points.\\n\");\n    printf(\"\\t-tmin\\t\\t\\tMean value of all time points.\\n\");\n    printf(\"\\n\\t* * Dimensionality increase operations: from 3-D to 4-D * *\\n\");\n    printf(\"\\t-merge\\t<i> <d> <files>\\tMerge <i> images and the working image in the <d> dimension \\n\");\n    printf(\"\\t-splitlab\\t\\tSplit the integer labels into multiple timepoints\\n\");\n    printf(\"\\t-splitinter <x/y/z>\\t\\tSplit interleaved slices in direction <x/y/z> into separate time points\\n\");\n    printf(\"\\n\\t* * Image similarity: Local metrics * *\\n\");\n    printf(\"\\t-lncc\\t<file> <std>\\tLocal CC between current img and <file> on a kernel with <std>\\n\");\n    printf(\"\\t-lssd\\t<file> <std>\\tLocal SSD between current img and <file> on a kernel with <std>\\n\");\n    printf(\"\\n\\t* * Normalisation * *\\n\");\n    printf(\"\\t-llsnorm\\t<file_norm>\\t\\t Linear LS normalisation between current and <file_norm>\\n\");\n    printf(\"\\t-lltsnorm\\t<file_norm> <float>\\t Linear LTS normalisation assuming <float> percent outliers\\n\");\n    printf(\"\\t-qlsnorm\\t<order> <file_norm>\\t LS normalisation of <order> between current and <file_norm>\\n\");\n    printf(\"\\n\\t* * NaN handling * *\\n\");\n    printf(\"\\t-removenan\\t\\tRemove all NaNs and replace then with 0\\n\");\n    printf(\"\\t-isnan\\t\\t\\tBinary image equal to 1 if the value is NaN and 0 otherwise\\n\");\n    printf(\"\\t-masknan <file_norm>\\tAssign everything outside the mask (mask==0) with NaNs \\n\");\n    printf(\"\\n\\t* * Sampling * *\\n\");\n    printf(\"\\t-subsamp2\\t\\tSubsample the image by 2 using NN sampling (qform and sform scaled) \\n\");\n    printf(\"\\n\\t* * Image header operations * *\\n\");\n    printf(\"\\t-hdr_copy <file> \\tCopy header from working image to <file> and save in <output>.\\n\");\n    printf(\"\\t-scl\\t\\t\\tReset scale and slope info.\\n\");\n    printf(\"\\t-4to5\\t\\t\\tFlip the 4th and 5th dimension.\\n\");\n    printf(\"\\n\\t* * Output * *\\n\");\n    printf(\"\\t-odt <datatype> \\tSet output <datatype> (char, short, int, uchar, ushort, uint, float, double).\\n\");\n    printf(\"\\t-range\\t\\t\\tReset the image range to the min max\\n\");\n    printf(\"\\t-v\\t\\t\\tVerbose.\\n\");\n#if defined (_OPENMP)\n    printf(\"\\t-omp <int>\\t\\tNumber of openmp threads [%d]\\n\",omp_get_max_threads());\n#endif\n#ifdef _GIT_HASH\n    printf(\"\\t--version\\t\\tPrint current source code git hash key and exit\\n\\t\\t\\t\\t(%s)\\n\",_GIT_HASH);\n#endif\n    printf(\"\\n\\t* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\\n\");\n    return;\n}\n\nbool isEdge(float a,float b,double treshold) {\n    float max=a>b?a:b;\n    return (fabs(a-b)/max>treshold);\n}\n\nint isNumeric (const char *s)\n{\n    if(s==NULL || *s=='\\0' || isspace(*s))\n        return 0;\n    char * p;\n    strtod (s, &p);\n    return *p == '\\0';\n}\n\nvoid no_memory ()\n{\n    cout << \"Failed to allocate memory!\\n\";\n    exit (1);\n}\n\nint main(int argc, char **argv)\n{\n    try\n    {\n        set_new_handler(no_memory);\n        if (argc <= 2)\n        {\n            Usage(argv[0]);\n            return 0;\n        }\n        if(strcmp(argv[1], \"-help\")==0 || strcmp(argv[1], \"-Help\")==0 ||\n                strcmp(argv[1], \"-HELP\")==0 || strcmp(argv[1], \"-h\")==0 ||\n                strcmp(argv[1], \"--h\")==0 || strcmp(argv[1], \"--help\")==0)\n        {\n            Usage(argv[0]);\n            return 0;\n        }\n\n\n        char * filename_in=argv[1];\n        nifti_image * InputImage=nifti_image_read(filename_in,true);\n        if(InputImage == NULL)\n        {\n            fprintf(stderr,\"* Error when reading the input image\\n\");\n            return 1;\n        }\n        if(InputImage->datatype!=NIFTI_TYPE_FLOAT32)\n        {\n            seg_changeDatatype<SegPrecisionTYPE>(InputImage);\n        }\n        SegPrecisionTYPE * InputImagePtr = static_cast<SegPrecisionTYPE *>(InputImage->data);\n        ImageSize * CurrSize = new ImageSize [1]();\n        CurrSize->numel=(long)(InputImage->nx*InputImage->ny*InputImage->nz);\n        CurrSize->xsize=InputImage->nx;\n        CurrSize->ysize=InputImage->ny;\n        CurrSize->zsize=InputImage->nz;\n        CurrSize->usize=(InputImage->nu>1)?InputImage->nu:1;\n        CurrSize->tsize=(InputImage->nt>1)?InputImage->nt:1;\n        float Scalling[4]= { 1.0f, 1.0f, 1.0f, 1.0f };\n        bool verbose=0;\n        int datatypeoutput=NIFTI_TYPE_FLOAT32;\n\n        SegPrecisionTYPE ** bufferImages = new SegPrecisionTYPE * [2];\n        bufferImages[0] = new SegPrecisionTYPE [CurrSize->xsize*CurrSize->ysize*CurrSize->zsize*CurrSize->tsize*CurrSize->usize];\n        bufferImages[1] = new SegPrecisionTYPE [CurrSize->xsize*CurrSize->ysize*CurrSize->zsize*CurrSize->tsize*CurrSize->usize];\n        for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize*CurrSize->tsize*CurrSize->usize); i++)\n        {\n            bufferImages[0][i]=InputImagePtr[i];\n        }\n        int current_buffer=0;\n\n        for(long i=2; i<(argc-1); i++)\n        {\n            if(strcmp(argv[i], \"-help\")==0 || strcmp(argv[i], \"-Help\")==0 ||\n                    strcmp(argv[i], \"-HELP\")==0 || strcmp(argv[i], \"-h\")==0 ||\n                    strcmp(argv[i], \"--h\")==0 || strcmp(argv[i], \"--help\")==0)\n            {\n                Usage(argv[0]);\n                return 0;\n            }\n#if defined (_OPENMP)\n            else if(strcmp(argv[i], \"-omp\")==0 || strcmp(argv[i], \"--omp\")==0)\n            {\n                omp_set_num_threads(atoi(argv[++i]));\n            }\n#endif\n            // *********************  MUTIPLY  *************************\n            else if(strcmp(argv[i], \"-mul\") == 0)\n            {\n                string parser=argv[++i];\n                if(parser.find_first_not_of(\"1234567890.-+\")== string::npos)\n                {\n                    double multfactor=strtod(parser.c_str(),NULL);\n                    for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize*CurrSize->tsize*CurrSize->usize); i++)\n                    {\n                        bufferImages[current_buffer?0:1][i]=bufferImages[current_buffer][i]*multfactor;\n                    }\n                    current_buffer=current_buffer?0:1;\n                }\n                else\n                {\n                    nifti_image * NewImage=nifti_image_read(parser.c_str(),true);\n                    NewImage->nu=(NewImage->nu>1)?NewImage->nu:1;\n                    NewImage->nt=(NewImage->nt>1)?NewImage->nt:1;\n                    if(NewImage->datatype!=DT_FLOAT32)\n                    {\n                        seg_changeDatatype<SegPrecisionTYPE>(NewImage);\n                    }\n                    SegPrecisionTYPE * NewImagePtr = static_cast<SegPrecisionTYPE *>(NewImage->data);\n                    if(NewImage->nx==CurrSize->xsize&&NewImage->ny==CurrSize->ysize&&NewImage->nz==CurrSize->zsize&&NewImage->nt==CurrSize->tsize&&NewImage->nu==CurrSize->usize)\n                    {\n                        for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize*CurrSize->tsize*CurrSize->usize); i++)\n                            bufferImages[current_buffer?0:1][i]=bufferImages[current_buffer][i]*NewImagePtr[i];\n                        current_buffer=current_buffer?0:1;\n                    }\n                    else\n                    {\n                        nifti_image * NewImage=nifti_image_read(parser.c_str(),true);\n                        NewImage->nu=(NewImage->nu>1)?NewImage->nu:1;\n                        NewImage->nt=(NewImage->nt>1)?NewImage->nt:1;\n                        if(NewImage->datatype!=DT_FLOAT32)\n                        {\n                            seg_changeDatatype<SegPrecisionTYPE>(NewImage);\n                        }\n                        SegPrecisionTYPE * NewImagePtr = static_cast<SegPrecisionTYPE *>(NewImage->data);\n                        if(NewImage->nx==CurrSize->xsize&&NewImage->ny==CurrSize->ysize&&NewImage->nz==CurrSize->zsize&&NewImage->nt==CurrSize->tsize&&NewImage->nu==CurrSize->usize)\n                        {\n                            for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize*CurrSize->tsize*CurrSize->usize); i++)\n                                bufferImages[current_buffer?0:1][i]=bufferImages[current_buffer][i]*NewImagePtr[i];\n                            current_buffer=current_buffer?0:1;\n                        }\n                        else\n                        {\n                            cout << \"ERROR: Image \"<< parser << \" is the wrong size  -  original = ( \"<<CurrSize->xsize<<\",\"\n                                 <<CurrSize->ysize<<\",\"<<CurrSize->zsize<<\",\"<<CurrSize->tsize<<\",\"<<CurrSize->usize<<\" ) New image = ( \"\n                                <<NewImage->nx<<\",\"<<NewImage->ny<<\",\"<<NewImage->nz<<\",\"<<NewImage->nt<<\",\"<<NewImage->nu<<\" )\"<<endl;\n                            i=argc;\n                        }\n                        nifti_image_free(NewImage);\n                    }\n                }\n            }\n            // *********************  ADD  *************************\n            else if( strcmp(argv[i], \"-add\") == 0)\n            {\n                string parser=argv[++i];\n                if(parser.find_first_not_of(\"1234567890.-+\")== string::npos)\n                {\n                    double addfactor=strtod(parser.c_str(),NULL);\n                    for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize*CurrSize->tsize*CurrSize->usize); i++)\n                        bufferImages[current_buffer?0:1][i]=bufferImages[current_buffer][i]+addfactor;\n                    current_buffer=current_buffer?0:1;\n                }\n                else\n                {\n                    nifti_image * NewImage=nifti_image_read(parser.c_str(),true);\n                    NewImage->nu=(NewImage->nu>1)?NewImage->nu:1;\n                    NewImage->nt=(NewImage->nt>1)?NewImage->nt:1;\n                    if(NewImage->datatype!=DT_FLOAT32)\n                    {\n                        seg_changeDatatype<SegPrecisionTYPE>(NewImage);\n                    }\n                    SegPrecisionTYPE * NewImagePtr = static_cast<SegPrecisionTYPE *>(NewImage->data);\n                    if(NewImage->nx==CurrSize->xsize&&NewImage->ny==CurrSize->ysize&&NewImage->nz==CurrSize->zsize&&NewImage->nt==CurrSize->tsize&&NewImage->nu==CurrSize->usize)\n                    {\n                        for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize*CurrSize->tsize*CurrSize->usize); i++)\n                            bufferImages[current_buffer?0:1][i]=bufferImages[current_buffer][i]+NewImagePtr[i];\n                        current_buffer=current_buffer?0:1;\n                    }\n                    else\n                    {\n                        cout << \"ERROR: Image \"<< parser << \" is the wrong size  -  original = ( \"<<CurrSize->xsize<<\",\"\n                             <<CurrSize->ysize<<\",\"<<CurrSize->zsize<<\",\"<<CurrSize->tsize<<\",\"<<CurrSize->usize<<\" )  New image = ( \"<<NewImage->nx<<\",\"\n                            <<NewImage->ny<<\",\"<<NewImage->nz<<\",\"<<NewImage->nt<<\",\"<<NewImage->nu<<\" )\"<<endl;\n                        i=argc;\n                    }\n                    nifti_image_free(NewImage);\n                }\n            }\n            // *********************  SUBTRACT  *************************\n            else if(strcmp(argv[i], \"-sub\") == 0)\n            {\n                string parser=argv[++i];\n                if(parser.find_first_not_of(\"1234567890.-+\")== string::npos)\n                {\n                    double factor=strtod(parser.c_str(),NULL);\n                    for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize*CurrSize->tsize*CurrSize->usize); i++)\n                        bufferImages[current_buffer?0:1][i]=bufferImages[current_buffer][i]-factor;\n                    current_buffer=current_buffer?0:1;\n                }\n                else\n                {\n                    nifti_image * NewImage=nifti_image_read(parser.c_str(),true);\n                    NewImage->nu=(NewImage->nu>1)?NewImage->nu:1;\n                    NewImage->nt=(NewImage->nt>1)?NewImage->nt:1;\n                    if(NewImage->datatype!=DT_FLOAT32)\n                    {\n                        seg_changeDatatype<SegPrecisionTYPE>(NewImage);\n                    }\n                    SegPrecisionTYPE * NewImagePtr = static_cast<SegPrecisionTYPE *>(NewImage->data);\n                    if(NewImage->nx==CurrSize->xsize&&NewImage->ny==CurrSize->ysize&&NewImage->nz==CurrSize->zsize&&NewImage->nt==CurrSize->tsize&&NewImage->nu==CurrSize->usize)\n                    {\n                        for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize*CurrSize->tsize*CurrSize->usize); i++)\n                            bufferImages[current_buffer?0:1][i]=bufferImages[current_buffer][i]-NewImagePtr[i];\n                        current_buffer=current_buffer?0:1;\n                    }\n                    else\n                    {\n                        cout << \"ERROR: Image \"<< parser << \" is the wrong size  -  original = ( \"<<CurrSize->xsize<<\",\"\n                             <<CurrSize->ysize<<\",\"<<CurrSize->zsize<<\",\"<<CurrSize->tsize<<\",\"<<CurrSize->usize<<\" )  New image = ( \"<<NewImage->nx<<\",\"\n                            <<NewImage->ny<<\",\"<<NewImage->nz<<\",\"<<NewImage->nt<<\",\"<<NewImage->nu<<\" )\"<<endl;\n                        i=argc;\n                    }\n                    nifti_image_free(NewImage);\n                }\n            }\n            // *********************  mask  *************************\n            else if(strcmp(argv[i], \"-masknan\") == 0)\n            {\n                string parser=argv[++i];\n\n                nifti_image * NewImage=nifti_image_read(parser.c_str(),true);\n                NewImage->nu=(NewImage->nu>1)?NewImage->nu:1;\n                NewImage->nt=(NewImage->nt>1)?NewImage->nt:1;\n                if(NewImage->datatype!=DT_FLOAT32)\n                {\n                    seg_changeDatatype<SegPrecisionTYPE>(NewImage);\n                }\n                SegPrecisionTYPE * NewImagePtr = static_cast<SegPrecisionTYPE *>(NewImage->data);\n                if(NewImage->nx==CurrSize->xsize&&NewImage->ny==CurrSize->ysize&&NewImage->nz==CurrSize->zsize&&NewImage->nt==CurrSize->tsize&&NewImage->nu==CurrSize->usize)\n                {\n                    for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize*CurrSize->tsize*CurrSize->usize); i++)\n                        bufferImages[current_buffer?0:1][i]=(NewImagePtr[i]>0)?bufferImages[current_buffer][i]:std::numeric_limits<float>::quiet_NaN();\n                    current_buffer=current_buffer?0:1;\n                }\n                else\n                {\n                    cout << \"ERROR: Image \"<< parser << \" is the wrong size  -  original = ( \"<<CurrSize->xsize<<\",\"\n                         <<CurrSize->ysize<<\",\"<<CurrSize->zsize<<\",\"<<CurrSize->tsize<<\",\"<<CurrSize->usize<<\" )  New image = ( \"<<NewImage->nx<<\",\"\n                        <<NewImage->ny<<\",\"<<NewImage->nz<<\",\"<<NewImage->nt<<\",\"<<NewImage->nu<<\" )\"<<endl;\n                    i=argc;\n                }\n                nifti_image_free(NewImage);\n\n            }\n            // *********************  mask  *************************\n            else if(strcmp(argv[i], \"-removenan\") == 0)\n            {\n\n                for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize*CurrSize->tsize*CurrSize->usize); i++)\n                    bufferImages[current_buffer?0:1][i]=isnan(bufferImages[current_buffer][i])==1?0:bufferImages[current_buffer][i];\n                current_buffer=current_buffer?0:1;\n\n            }\n\t    // *********************  pad voxels  *************************\n            else if(strcmp(argv[i], \"-pad\") == 0)\n            {\n                string parser=argv[++i];\n\n                if(parser.find_first_not_of(\"1234567890-+\")== string::npos)\n                {\n                    int padding=(int)strtod(parser.c_str(),NULL)*2;\n\t\t    long new_size=((CurrSize->xsize+padding)*(CurrSize->ysize+padding)*(CurrSize->zsize+padding)*CurrSize->tsize*CurrSize->usize);\n\t\t    bufferImages[current_buffer?0:1]=new SegPrecisionTYPE [new_size];\n\t\t           \n\t\t    for(long ii=0; ii<new_size; ii++)\n                        bufferImages[current_buffer?0:1][ii]=std::numeric_limits<double>::quiet_NaN();\n\n\t\t    long old_volume=CurrSize->xsize*CurrSize->ysize*CurrSize->zsize;\n\t\t    long new_volume=(CurrSize->xsize+padding)*(CurrSize->ysize+padding)*(CurrSize->zsize+padding);\n\t\t    for (long t=0;t<CurrSize->tsize*CurrSize->usize;t++) {\n\t\t\t    for(long z=0; z<CurrSize->zsize; z++) {\n\t\t\t\tfor(long y=0; y<CurrSize->ysize; y++) {\n\t\t\t\t\tfor(long x=0; x<CurrSize->xsize; x++) {\n\t\t\t\t\t\tlong big=t*new_volume+x+(padding/2)+(y+(padding/2))*(CurrSize->xsize+padding)+(z+(padding/2))*(CurrSize->xsize+padding)*(CurrSize->ysize+padding);\n\t\t\t\t\t\tlong small=t*old_volume+x+y*CurrSize->xsize+z*(CurrSize->xsize*CurrSize->ysize);\n        \t                \t\tbufferImages[current_buffer?0:1][big]=bufferImages[current_buffer][small];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t    }\n\t\t    }\n                    current_buffer=current_buffer?0:1;\n\t\t    bufferImages[current_buffer?0:1]=new SegPrecisionTYPE [new_size];\n\t\t    for(long ii=0; ii<new_size; ii++)\n                        bufferImages[current_buffer?0:1][ii]=0;\n\t\t    CurrSize->xsize+=padding;\n\t\t    CurrSize->ysize+=padding;\n\t\t    CurrSize->zsize+=padding;\n    \t\t    CurrSize->numel=CurrSize->xsize*CurrSize->ysize*CurrSize->zsize;\n                }\n\t\telse\n                {\n                    cout << \"ERROR: \"<< parser << \" is not a valid number\"<<endl;\n                    i=argc;\n                }\n            }\n\t    // *********************  crop voxels  *************************\n            else if(strcmp(argv[i], \"-crop\") == 0)\n            {\n                string parser=argv[++i];\n\n                if(parser.find_first_not_of(\"1234567890-+\")== string::npos)\n                {\n                    int cropping=(int)strtod(parser.c_str(),NULL)*2;\n\t\t    long new_size=((CurrSize->xsize-cropping)*(CurrSize->ysize-cropping)*(CurrSize->zsize-cropping)*CurrSize->tsize*CurrSize->usize);\n\t\t    bufferImages[current_buffer?0:1]=new SegPrecisionTYPE [new_size];\n\t\t           \n\t\t    for(long ii=0; ii<new_size; ii++)\n                        bufferImages[current_buffer?0:1][ii]=0;\n\t\t\n\t\t    long old_volume=CurrSize->xsize*CurrSize->ysize*CurrSize->zsize;\n\t\t    long new_volume=(CurrSize->xsize-cropping)*(CurrSize->ysize-cropping)*(CurrSize->zsize-cropping);\n\t\t    for (long t=0;t<CurrSize->tsize*CurrSize->usize;t++) {\n                    \tfor(long x=cropping/2; x<CurrSize->xsize-cropping/2; x++) {\n\t\t\t\tfor(long y=cropping/2; y<CurrSize->ysize-cropping/2; y++) {\n\t\t\t\t\tfor(long z=cropping/2; z<CurrSize->zsize-cropping/2; z++) {\n\t\t\t\t\t\tlong small=t*new_volume+x-(cropping/2)+(y-(cropping/2))*(CurrSize->xsize-cropping)+(z-(cropping/2))*((CurrSize->xsize-cropping)*(CurrSize->ysize-cropping));\n\t\t\t\t\t\tlong big=t*old_volume+x+y*CurrSize->xsize+z*(CurrSize->xsize*CurrSize->ysize);\n                    \t\t    \t\tbufferImages[current_buffer?0:1][small]=bufferImages[current_buffer][big];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t    \t}\n\t\t    }\n                    current_buffer=current_buffer?0:1;\n\t\t    bufferImages[current_buffer?0:1]=new SegPrecisionTYPE [new_size];\n\t\t    for(long ii=0; ii<new_size; ii++)\n                        bufferImages[current_buffer?0:1][ii]=0;\n\t\t    CurrSize->xsize-=cropping;\n\t\t    CurrSize->ysize-=cropping;\n\t\t    CurrSize->zsize-=cropping;\n\t\t    CurrSize->numel=CurrSize->xsize*CurrSize->ysize*CurrSize->zsize;\n                }\n\t\telse\n                {\n                    cout << \"ERROR: \"<< parser << \" is not a valid number\"<<endl;\n                    i=argc;\n                }\n            }\n\t    //  *********************  mask edge  *************************\n            else if(strcmp(argv[i], \"-edge\") == 0)\n            {\n                string parser=argv[++i];\n                if(((strtod(parser.c_str(),NULL)!=0) || (parser.length()==1 && parser.find(\"0\")!=string::npos)))\n                {\n                    double treshold=strtod(parser.c_str(),NULL);;\n                    float * Img1prt = bufferImages[current_buffer];\n                    for(int index=0; index<CurrSize->xsize*CurrSize->ysize*CurrSize->zsize; index++)\n                    {\n                        bool edge=false;\n                        if((index+1)<CurrSize->xsize*CurrSize->ysize*CurrSize->zsize) {\n                            if(isEdge(Img1prt[index],Img1prt[index+1],treshold)) edge=true;\n                        }\n                        if((index-1)>0) {\n                            if(isEdge(Img1prt[index],Img1prt[index-1],treshold)) edge=true;\n                        }\n                        if((index+CurrSize->xsize)<CurrSize->xsize*CurrSize->ysize*CurrSize->zsize) {\n                            if(isEdge(Img1prt[index],Img1prt[index+CurrSize->xsize],treshold)) edge=true;\n                        }\n                        if((index-CurrSize->xsize)>0) {\n                            if(isEdge(Img1prt[index],Img1prt[index-CurrSize->xsize],treshold)) edge=true;\n                        }\n                        if((index+CurrSize->xsize*CurrSize->ysize)<CurrSize->xsize*CurrSize->ysize*CurrSize->zsize) {\n                            if(isEdge(Img1prt[index],Img1prt[index+CurrSize->xsize*CurrSize->ysize],treshold)) edge=true;\n                        }\n                        if((index-CurrSize->xsize*CurrSize->ysize)>0) {\n                            if(isEdge(Img1prt[index],Img1prt[index-CurrSize->xsize*CurrSize->ysize],treshold)) edge=true;\n                        }\n                        if(edge)\n                        {\n                            bufferImages[current_buffer?0:1][index]=bufferImages[current_buffer][index];\n                        }\n                        else {\n                            bufferImages[current_buffer?0:1][index]=0;\n                        }\n                    }\n                    current_buffer=current_buffer?0:1;\n                }\n                else\n                {\n                    cout << \"ERROR: \"<< parser << \" is not a valid number\"<<endl;\n                    i=argc;\n                }\n            }\n\t    else if(strcmp(argv[i], \"-sobel3\") == 0)\n            {\n                string parser=argv[++i];\n                if(((strtod(parser.c_str(),NULL)!=0) || (parser.length()==1 && parser.find(\"0\")!=string::npos)))\n                {\n                    double factor=strtod(parser.c_str(),NULL);\n                    float * Img1prt = bufferImages[current_buffer];\n                    long tp=0;\n                    #ifdef _OPENMP\n                    #pragma omp parallel for \\\n                        private(tp)\\\n                        shared(CurrSize,bufferImages,Img1prt,factor,InputImage)\n                    #endif\n                    for(tp=0; tp<(long)(CurrSize->tsize*CurrSize->usize); tp++){\n                        //create dummy nii\n                        nifti_image * TMPnii = nifti_copy_nim_info(InputImage);\n                        TMPnii->dim[1]=CurrSize->xsize;\n                        TMPnii->dim[2]=CurrSize->ysize;\n                        TMPnii->dim[3]=CurrSize->zsize;\n                        TMPnii->dim[4]=TMPnii->nt=1;\n                        TMPnii->dim[5]=TMPnii->nu=1;\n                        nifti_update_dims_from_array(TMPnii);\n                        //copy pointer, run gaussian, and set to null\n                        TMPnii->data=static_cast<void*>(&Img1prt[CurrSize->xsize*CurrSize->ysize*CurrSize->zsize*tp]);\n                        if(factor>0) GaussianSmoothing5D_nifti(TMPnii,NULL,factor);\n                        TMPnii->data=NULL;\n                        //As TMPnii->data=NULL, the free will not cause any harm\n                        nifti_image_free(TMPnii);\n\n                        float *imgsort=new float [CurrSize->xsize*CurrSize->ysize*CurrSize->zsize];\n                        for(long i=0; i<CurrSize->xsize*CurrSize->ysize*CurrSize->zsize; i++) {\n                            imgsort[i]=Img1prt[i+tp*CurrSize->xsize*CurrSize->ysize*CurrSize->zsize];\n                        }\n                        HeapSort(imgsort,CurrSize->xsize*CurrSize->ysize*CurrSize->zsize-1);\n                        float max=imgsort[(int)(round((1-0.02)*(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize-1)))];\n                        float min=imgsort[(int)(round(0.02*(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize-1)))];\n                        float newMax=1,newMin=0;\n                        for(long i=0; i<CurrSize->xsize*CurrSize->ysize*CurrSize->zsize; i++) {\n                            if(min>Img1prt[i+tp*CurrSize->xsize*CurrSize->ysize*CurrSize->zsize]) Img1prt[i+tp*CurrSize->xsize*CurrSize->ysize*CurrSize->zsize]=min;\n                            if(max<Img1prt[i+tp*CurrSize->xsize*CurrSize->ysize*CurrSize->zsize]) Img1prt[i+tp*CurrSize->xsize*CurrSize->ysize*CurrSize->zsize]=max;\n                            Img1prt[i+tp*CurrSize->xsize*CurrSize->ysize*CurrSize->zsize]=newMin+(Img1prt[i+tp*CurrSize->xsize*CurrSize->ysize*CurrSize->zsize]-min)*(newMax-newMin)/(max-min);\n                        }\n                        int inz=0;\n                        float xkernel[3][3][3]={\n                                            {{-1,-2,-1},{-2,-4,-2},{-1,-2,-1}},\n                                            {{ 0, 0, 0},{ 0, 0, 0},{ 0, 0, 0}},\n                                            {{ 1, 2, 1},{ 2, 4, 2},{ 1, 2, 1}}\n                                         };\n                        float ykernel[3][3][3]={\n                                            {{ 1, 2, 1},{ 0, 0, 0},{-1,-2,-1}},\n                                            {{ 2, 4, 2},{ 0, 0, 0},{-2,-4,-2}},\n                                            {{ 1, 2, 1},{ 0, 0, 0},{-1,-2,-1}}\n                                         };\n                        float zkernel[3][3][3]={\n                                            {{-1, 0, 1},{-2, 0, 2},{-1, 0, 1}},\n                                            {{-2, 0, 2},{-4, 0, 4},{-2, 0, 2}},\n                                            {{-1, 0, 1},{-2, 0, 2},{-1, 0, 1}}\n                                         };\n                        #ifdef _OPENMP\n                        #pragma omp parallel for \\\n                            private(inz)\\\n                            shared(CurrSize,bufferImages,Img1prt,xkernel,ykernel,zkernel)\n                        #endif\n                        for(inz=0; inz<CurrSize->zsize; inz++) {\n                            for(int iny=0; iny<CurrSize->ysize; iny++) {\n                                for(int inx=0; inx<CurrSize->xsize; inx++) {\n                                    float sumx=0,sumy=0,sumz=0;\n                                    for(int i=-1;i<=1;i++) {\n                                        for(int j=-1;j<=1;j++) {\n                                            for(int k=-1;k<=1;k++) {\n                                                if(inx+k>=0 && iny+j>=0 && inz+i>=0 &&\n                                                        inx+k<CurrSize->xsize && iny+j<CurrSize->ysize && inz+i<CurrSize->zsize) {\n                                                    int index=(inx+k)+(iny+j)*CurrSize->xsize+(inz+i)*(CurrSize->xsize*CurrSize->ysize);\n                                                    sumx+=xkernel[k+1][j+1][i+1]*Img1prt[index+tp*CurrSize->xsize*CurrSize->ysize*CurrSize->zsize];\n                                                    sumy+=ykernel[j+1][k+1][i+1]*Img1prt[index+tp*CurrSize->xsize*CurrSize->ysize*CurrSize->zsize];\n                                                    sumz+=zkernel[i+1][k+1][j+1]*Img1prt[index+tp*CurrSize->xsize*CurrSize->ysize*CurrSize->zsize];\n                                                }\n                                            }\n                                        }\n                                    }\n\n                                    int index=inx+iny*CurrSize->xsize+inz*(CurrSize->xsize*CurrSize->ysize);\n                                    float val=sqrt(sumx*sumx+sumy*sumy+sumz*sumz);\n                                    bufferImages[current_buffer?0:1][index+tp*CurrSize->xsize*CurrSize->ysize*CurrSize->zsize]=val;\n                                }\n                            }\n                        }\n                        for(long i=0; i<CurrSize->xsize*CurrSize->ysize*CurrSize->zsize; i++) {\n                            imgsort[i]=bufferImages[current_buffer?0:1][i+tp*CurrSize->xsize*CurrSize->ysize*CurrSize->zsize];\n                        }\n                        HeapSort(imgsort,CurrSize->xsize*CurrSize->ysize*CurrSize->zsize-1);\n                        max=imgsort[(int)(round((1-0.02)*(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize-1)))];\n                        min=imgsort[(int)(round(0.02*(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize-1)))];\n                        for(long i=0; i<CurrSize->xsize*CurrSize->ysize*CurrSize->zsize; i++) {\n                            if(min>bufferImages[current_buffer?0:1][i+tp*CurrSize->xsize*CurrSize->ysize*CurrSize->zsize]) bufferImages[current_buffer?0:1][i+tp*CurrSize->xsize*CurrSize->ysize*CurrSize->zsize]=min;\n                            if(max<bufferImages[current_buffer?0:1][i+tp*CurrSize->xsize*CurrSize->ysize*CurrSize->zsize]) bufferImages[current_buffer?0:1][i+tp*CurrSize->xsize*CurrSize->ysize*CurrSize->zsize]=max;\n                            bufferImages[current_buffer?0:1][i+tp*CurrSize->xsize*CurrSize->ysize*CurrSize->zsize]=newMin+(bufferImages[current_buffer?0:1][i+tp*CurrSize->xsize*CurrSize->ysize*CurrSize->zsize]-min)*(newMax-newMin)/(max-min);\n                        }\n                    }\n                }\n                else {\n                    cout << \"ERROR: \"<< parser << \" is not a valid number\"<<endl;\n                    i=argc;\n                }\n                current_buffer=current_buffer?0:1;\n            }\n            else if(strcmp(argv[i], \"-sobel5\") == 0)\n            {\n                string parser=argv[++i];\n                if(((strtod(parser.c_str(),NULL)!=0) || (parser.length()==1 && parser.find(\"0\")!=string::npos)))\n                {\n                    double factor=strtod(parser.c_str(),NULL);\n                    float * Img1prt = bufferImages[current_buffer];\n                    long tp=0;\n                    #ifdef _OPENMP\n                    #pragma omp parallel for \\\n                        private(tp)\\\n                        shared(CurrSize,bufferImages,Img1prt,factor,InputImage)\n                    #endif\n                    for(tp=0; tp<(long)(CurrSize->tsize*CurrSize->usize); tp++){\n                        //create dummy nii\n                        nifti_image * TMPnii = nifti_copy_nim_info(InputImage);\n                        TMPnii->dim[1]=CurrSize->xsize;\n                        TMPnii->dim[2]=CurrSize->ysize;\n                        TMPnii->dim[3]=CurrSize->zsize;\n                        TMPnii->dim[4]=TMPnii->nt=1;\n                        TMPnii->dim[5]=TMPnii->nu=1;\n                        nifti_update_dims_from_array(TMPnii);\n                        //copy pointer, run gaussian, and set to null\n                        TMPnii->data=static_cast<void*>(&Img1prt[CurrSize->xsize*CurrSize->ysize*CurrSize->zsize*tp]);\n                        if(factor>0) GaussianSmoothing5D_nifti(TMPnii,NULL,factor);\n                        TMPnii->data=NULL;\n                        //As TMPnii->data=NULL, the free will not cause any harm\n                        nifti_image_free(TMPnii);\n\n                        float *imgsort=new float [CurrSize->xsize*CurrSize->ysize*CurrSize->zsize];\n                        for(long i=0; i<CurrSize->xsize*CurrSize->ysize*CurrSize->zsize; i++) {\n                            imgsort[i]=Img1prt[i+tp*CurrSize->xsize*CurrSize->ysize*CurrSize->zsize];\n                        }\n                        HeapSort(imgsort,CurrSize->xsize*CurrSize->ysize*CurrSize->zsize-1);\n                        float max=imgsort[(int)(round((1-0.02)*(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize-1)))];\n                        float min=imgsort[(int)(round(0.02*(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize-1)))];\n                        float newMax=1,newMin=0;\n                        for(long i=0; i<CurrSize->xsize*CurrSize->ysize*CurrSize->zsize; i++) {\n                            if(min>Img1prt[i+tp*CurrSize->xsize*CurrSize->ysize*CurrSize->zsize]) Img1prt[i+tp*CurrSize->xsize*CurrSize->ysize*CurrSize->zsize]=min;\n                            if(max<Img1prt[i+tp*CurrSize->xsize*CurrSize->ysize*CurrSize->zsize]) Img1prt[i+tp*CurrSize->xsize*CurrSize->ysize*CurrSize->zsize]=max;\n                            Img1prt[i+tp*CurrSize->xsize*CurrSize->ysize*CurrSize->zsize]=newMin+(Img1prt[i+tp*CurrSize->xsize*CurrSize->ysize*CurrSize->zsize]-min)*(newMax-newMin)/(max-min);\n                        }\n                        float xkernel[5][5][5]={\n                                            {{-1,-4, -6,-4,-1},{-2, -8,-12, -8,-2},{-4,-16,-24,-16,-4},{-2, -8,-12, -8,-2},{-1,-4, -6,-4,-1}},\n                                            {{-2,-8,-12,-8,-2},{-4,-16,-24,-16,-4},{-8,-32,-48,-32,-8},{-4,-16,-24,-16,-4},{-2,-8,-12,-8,-2}},\n                                            {{ 0, 0,  0, 0, 0},{ 0,  0,  0,  0, 0},{ 0,  0,  0,  0, 0},{ 0,  0,  0,  0, 0},{ 0, 0,  0, 0, 0}},\n                                            {{ 2, 8, 12, 8, 2},{ 4, 16, 24, 16, 4},{ 8, 32, 48, 32, 8},{ 4, 16, 24, 16, 4},{ 2, 8, 12, 8, 2}},\n                                            {{ 1, 4,  6, 4, 1},{ 2,  8, 12,  8, 2},{ 4, 16, 24, 16, 4},{ 2,  8, 12,  8, 2},{ 1, 4,  6, 4, 1}}\n                                         };\n                        float ykernel[5][5][5]={\n                                            {{ 1,  4,  6,  4, 1},{ 2,  8, 12,  8, 2},{ 0, 0, 0, 0, 0},{-2, -8,-12, -8,-2},{-1, -4, -6, -4,-1}},\n                                            {{ 2,  8, 12,  8, 2},{ 4, 16, 24, 16, 4},{ 0, 0, 0, 0, 0},{-4,-16,-24,-16,-4},{-2, -8,-12, -8,-2}},\n                                            {{ 4, 16, 24, 16, 4},{ 8, 32, 48, 32, 8},{ 0, 0, 0, 0, 0},{-8,-32,-48,-32,-8},{-4,-16,-24,-16,-4}},\n                                            {{ 2,  8, 12,  8, 2},{ 4, 16, 24, 16, 4},{ 0, 0, 0, 0, 0},{-4,-16,-24,-16,-4},{-2, -8,-12, -8,-2}},\n                                            {{ 1,  4,  6,  4, 1},{ 2,  8, 12,  8, 2},{ 0, 0, 0, 0, 0},{-2, -8,-12, -8,-2},{-1, -4, -6, -4,-1}}\n                                         };\n                        float zkernel[5][5][5]={\n                                            {{-1, -2,  0,  2, 1},{ -2, -4, 0,  4,  2},{ -4, -8, 0,  8,  4},{ -2, -4, 0,  4,  2},{-1, -2,  0,  2, 1}},\n                                            {{-4, -8,  0,  8, 4},{ -8,-16, 0, 16,  8},{-16,-32, 0, 32, 16},{ -8,-16, 0, 16,  8},{-4, -8,  0,  8, 4}},\n                                            {{-6,-12,  0, 12, 6},{-12,-24, 0, 24, 12},{-24,-48, 0, 48, 24},{-12,-24, 0, 24, 12},{-6,-12,  0, 12, 6}},\n                                            {{-4, -8,  0,  8, 4},{ -8,-16, 0, 16,  8},{-16,-32, 0, 32, 16},{ -8,-16, 0, 16,  8},{-4, -8,  0,  8, 4}},\n                                            {{-1, -2,  0,  2, 1},{- 2, -4, 0,  4,  2},{ -4,  8, 0,  8,  4},{ -2, -4, 0,  4,  2},{-1, -2,  0,  2, 1}}\n                                         };\n                        int inz=0;\n                        #ifdef _OPENMP\n                        #pragma omp parallel for \\\n                            private(inz)\\\n                            shared(CurrSize,bufferImages,Img1prt,xkernel,ykernel,zkernel)\n                        #endif\n                        for(inz=0; inz<CurrSize->zsize; inz++) {\n                            for(int iny=0; iny<CurrSize->ysize; iny++) {\n                                for(int inx=0; inx<CurrSize->xsize; inx++) {\n                                    float sumx=0,sumy=0,sumz=0;\n                                    for(int i=-2;i<=2;i++) {\n                                        for(int j=-2;j<=2;j++) {\n                                            for(int k=-2;k<=2;k++) {\n                                                if(inx+k>=0 && iny+j>=0 && inz+i>=0 &&\n                                                        inx+k<CurrSize->xsize && iny+j<CurrSize->ysize && inz+i<CurrSize->zsize) {\n                                                    int index=(inx+k)+(iny+j)*CurrSize->xsize+(inz+i)*(CurrSize->xsize*CurrSize->ysize);\n                                                    sumx+=xkernel[k+2][j+2][i+2]*Img1prt[index+tp*CurrSize->xsize*CurrSize->ysize*CurrSize->zsize];\n                                                    sumy+=ykernel[j+2][k+2][i+2]*Img1prt[index+tp*CurrSize->xsize*CurrSize->ysize*CurrSize->zsize];\n                                                    sumz+=zkernel[i+2][k+2][j+2]*Img1prt[index+tp*CurrSize->xsize*CurrSize->ysize*CurrSize->zsize];\n                                                }\n                                            }\n                                        }\n                                    }\n                                    int index=inx+iny*CurrSize->xsize+inz*(CurrSize->xsize*CurrSize->ysize);\n                                    float val=sqrt(sumx*sumx+sumy*sumy+sumz*sumz);\n                                    bufferImages[current_buffer?0:1][index+tp*CurrSize->xsize*CurrSize->ysize*CurrSize->zsize]=val;\n                                }\n                            }\n                        }\n                        for(long i=0; i<CurrSize->xsize*CurrSize->ysize*CurrSize->zsize; i++) {\n                            imgsort[i]=bufferImages[current_buffer?0:1][i+tp*CurrSize->xsize*CurrSize->ysize*CurrSize->zsize];\n                        }\n                        HeapSort(imgsort,CurrSize->xsize*CurrSize->ysize*CurrSize->zsize-1);\n                        max=imgsort[(int)(round((1-0.02)*(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize-1)))];\n                        min=imgsort[(int)(round(0.02*(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize-1)))];\n                        for(long i=0; i<CurrSize->xsize*CurrSize->ysize*CurrSize->zsize; i++) {\n                            if(min>bufferImages[current_buffer?0:1][i+tp*CurrSize->xsize*CurrSize->ysize*CurrSize->zsize]) bufferImages[current_buffer?0:1][i+tp*CurrSize->xsize*CurrSize->ysize*CurrSize->zsize]=min;\n                            if(max<bufferImages[current_buffer?0:1][i+tp*CurrSize->xsize*CurrSize->ysize*CurrSize->zsize]) bufferImages[current_buffer?0:1][i+tp*CurrSize->xsize*CurrSize->ysize*CurrSize->zsize]=max;\n                            bufferImages[current_buffer?0:1][i+tp*CurrSize->xsize*CurrSize->ysize*CurrSize->zsize]=newMin+(bufferImages[current_buffer?0:1][i+tp*CurrSize->xsize*CurrSize->ysize*CurrSize->zsize]-min)*(newMax-newMin)/(max-min);\n                        }\n                    }\n                }\n                else {\n                    cout << \"ERROR: \"<< parser << \" is not a valid number\"<<endl;\n                    i=argc;\n                }\n                current_buffer=current_buffer?0:1;\n            }\n\t    \n            // *********************  ADD  *************************\n            else if( strcmp(argv[i], \"-div\") == 0)\n            {\n                string parser=argv[++i];\n                if(parser.find_first_not_of(\"1234567890.-+\")== string::npos)\n                {\n                    double divfactor=strtod(parser.c_str(),NULL);\n                    for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize*CurrSize->tsize*CurrSize->usize); i++)\n                        bufferImages[current_buffer?0:1][i]=bufferImages[current_buffer][i]/divfactor;\n                    current_buffer=current_buffer?0:1;\n                }\n                else\n                {\n                    nifti_image * NewImage=nifti_image_read(parser.c_str(),true);\n                    NewImage->nu=(NewImage->nu>1)?NewImage->nu:1;\n                    NewImage->nt=(NewImage->nt>1)?NewImage->nt:1;\n                    if(NewImage->datatype!=DT_FLOAT32)\n                    {\n                        seg_changeDatatype<SegPrecisionTYPE>(NewImage);\n                    }\n                    SegPrecisionTYPE * NewImagePtr = static_cast<SegPrecisionTYPE *>(NewImage->data);\n                    if(NewImage->nx==CurrSize->xsize&&NewImage->ny==CurrSize->ysize&&NewImage->nz==CurrSize->zsize&&NewImage->nt==CurrSize->tsize&&NewImage->nu==CurrSize->usize)\n                    {\n                        for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize*CurrSize->tsize*CurrSize->usize); i++)\n                            bufferImages[current_buffer?0:1][i]=bufferImages[current_buffer][i]/NewImagePtr[i];\n                        current_buffer=current_buffer?0:1;\n                    }\n                    else\n                    {\n                        cout << \"ERROR: Image \"<< parser << \" is the wrong size  -  original = ( \"<<CurrSize->xsize<<\",\"\n                             <<CurrSize->ysize<<\",\"<<CurrSize->zsize<<\",\"<<CurrSize->tsize<<\",\"<<CurrSize->usize<<\" )  New image = ( \"<<NewImage->nx<<\",\"\n                            <<NewImage->ny<<\",\"<<NewImage->nz<<\",\"<<NewImage->nt<<\",\"<<NewImage->nu<<\" )\"<<endl;\n                        i=argc;\n                    }\n                    nifti_image_free(NewImage);\n                }\n            }\n            // *********************  POWER  *************************\n            else if(strcmp(argv[i], \"-pow\") == 0)\n            {\n                string parser=argv[++i];\n                if(((strtod(parser.c_str(),NULL)!=0) || (parser.length()==1 && parser.find(\"0\")!=string::npos)))\n                {\n                    float factor=strtof(parser.c_str(),NULL);\n                    for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize*CurrSize->tsize*CurrSize->usize); i++)\n                        bufferImages[current_buffer?0:1][i]=powf(bufferImages[current_buffer][i],factor);\n                    current_buffer=current_buffer?0:1;\n                }\n                else\n                {\n                    cout << \"ERROR: \"<< parser << \" is not a valid number\"<<endl;\n                    i=argc;\n                }\n            }\n            // *********************  Is NAN  *************************\n            else if(strcmp(argv[i], \"-isnan\") == 0)\n            {\n\n                for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize*CurrSize->tsize*CurrSize->usize); i++)\n                    bufferImages[current_buffer?0:1][i]=isnan(bufferImages[current_buffer][i]);\n                current_buffer=current_buffer?0:1;\n            }\n            // *********************  square_root  *************************\n            else if(strcmp(argv[i], \"-sqrt\") == 0)\n            {\n                for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize*CurrSize->tsize*CurrSize->usize); i++)\n                    bufferImages[current_buffer?0:1][i]=sqrtf(bufferImages[current_buffer][i]);\n                current_buffer=current_buffer?0:1;\n            }\n            // *********************  Exponential  *************************\n            else if(strcmp(argv[i], \"-exp\") == 0)\n            {\n                for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize*CurrSize->tsize*CurrSize->usize); i++)\n                    bufferImages[current_buffer?0:1][i]=expf(bufferImages[current_buffer][i]);\n                current_buffer=current_buffer?0:1;\n            }\n            // *********************  Exponential  *************************\n            else if(strcmp(argv[i], \"-log\") == 0)\n            {\n                for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize*CurrSize->tsize*CurrSize->usize); i++)\n                    bufferImages[current_buffer?0:1][i]=logf(bufferImages[current_buffer][i]);\n                current_buffer=current_buffer?0:1;\n            }\n            // *********************  reciprocal  *************************\n            else if(strcmp(argv[i], \"-recip\") == 0)\n            {\n                for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize*CurrSize->tsize*CurrSize->usize); i++)\n                    bufferImages[current_buffer?0:1][i]=1/(bufferImages[current_buffer][i]);\n                current_buffer=current_buffer?0:1;\n            }\n            // *********************  absolute value  *************************\n            else if(strcmp(argv[i], \"-abs\") == 0)\n            {\n                for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize*CurrSize->tsize*CurrSize->usize); i++)\n                    bufferImages[current_buffer?0:1][i]=fabs(bufferImages[current_buffer][i]);\n                current_buffer=current_buffer?0:1;\n\n            }\n            // *********************  bin value  *************************\n            else if(strcmp(argv[i], \"-bin\") == 0)\n            {\n                for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize*CurrSize->tsize*CurrSize->usize); i++)\n                    bufferImages[current_buffer?0:1][i]=(bufferImages[current_buffer][i]>0?1.0f:0.0f);\n                current_buffer=current_buffer?0:1;\n            }\n            // *********************  THRESHOLD below  *************************\n            else if(strcmp(argv[i], \"-thr\") == 0)\n            {\n                string parser=argv[++i];\n                if(((strtod(parser.c_str(),NULL)!=0 ) || (parser.length()==1 && parser.find(\"0\")!=string::npos)))\n                {\n                    double factor=strtod(parser.c_str(),NULL);\n                    for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize*CurrSize->tsize*CurrSize->usize); i++)\n                        bufferImages[current_buffer?0:1][i]=(bufferImages[current_buffer][i]>factor)?bufferImages[current_buffer][i]:0;\n                    current_buffer=current_buffer?0:1;\n                }\n                else\n                {\n                    cout << \"ERROR: \"<< parser << \" is not a valid number\"<<endl;\n                    i=argc;\n                }\n            }\n            // *********************  THRESHOLD below  *************************\n            else if(strcmp(argv[i], \"-equal\") == 0)\n            {\n                string parser=argv[++i];\n                if(((strtod(parser.c_str(),NULL)!=0 ) || (parser.length()==1 && parser.find(\"0\")!=string::npos)))\n                {\n                    double factor=strtod(parser.c_str(),NULL);\n                    for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize*CurrSize->tsize*CurrSize->usize); i++)\n                        bufferImages[current_buffer?0:1][i]=(bufferImages[current_buffer][i]==factor)?1:0;\n                    current_buffer=current_buffer?0:1;\n                }\n                else\n                {\n                    cout << \"ERROR: \"<< parser << \" is not a valid number\"<<endl;\n                    i=argc;\n                }\n            }\n            // *********************  Replace below  *************************\n            else if(strcmp(argv[i], \"-replace\") == 0)\n            {\n                string parser=argv[++i];\n                string parser2=argv[++i];\n                if(((strtod(parser.c_str(),NULL)!=0 ) || (parser.length()==1 && parser.find(\"0\")!=string::npos)))\n                {\n                    double factor=strtod(parser.c_str(),NULL);\n                    double factor2=strtod(parser2.c_str(),NULL);\n                    for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize*CurrSize->tsize*CurrSize->usize); i++)\n                        bufferImages[current_buffer?0:1][i]=(bufferImages[current_buffer][i]==factor)?factor2:bufferImages[current_buffer][i];\n                    current_buffer=current_buffer?0:1;\n                }\n                else\n                {\n                    cout << \"ERROR: \"<< parser << \" is not a valid number\"<<endl;\n                    i=argc;\n                }\n            }\n            // *********************  THRESHOLD ABOVE  *************************\n            else if(strcmp(argv[i], \"-uthr\") == 0)\n            {\n                string parser=argv[++i];\n                if(((strtod(parser.c_str(),NULL)!=0) || (parser.length()==1 && parser.find(\"0\")!=string::npos)))\n                {\n                    double factor=strtod(parser.c_str(),NULL);\n                    for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize*CurrSize->tsize*CurrSize->usize); i++)\n                        bufferImages[current_buffer?0:1][i]=(bufferImages[current_buffer][i]<factor)?bufferImages[current_buffer][i]:0;\n                    current_buffer=current_buffer?0:1;\n                }\n                else\n                {\n                    cout << \"ERROR: \"<< parser << \" is not a valid number\"<<endl;\n                    i=argc;\n                }\n            }\n            // *********************  Dilate   *************************\n            else if(strcmp(argv[i], \"-dil\") == 0)\n            {\n                string parser=argv[++i];\n                if(parser.find_first_not_of(\"1234567890.-+\")== string::npos)\n                {\n                    double factor=strtod(parser.c_str(),NULL);\n                    Dillate(bufferImages[current_buffer],(int)round(factor),CurrSize);\n                    for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize*CurrSize->tsize*CurrSize->usize); i++)\n                        bufferImages[current_buffer?0:1][i]=bufferImages[current_buffer][i];\n                    current_buffer=current_buffer?0:1;\n                }\n                else\n                {\n                    cout << \"ERROR: \"<< parser << \" has to be an integer > 0\"<<endl;\n                    i=argc;\n                }\n            }\n            // *********************  Erosion   *************************\n            else if(strcmp(argv[i], \"-ero\") == 0)\n            {\n                string parser=argv[++i];\n                if(parser.find_first_not_of(\"1234567890.-+\")== string::npos)\n                {\n                    double factor=strtod(parser.c_str(),NULL);\n                    Erosion(bufferImages[current_buffer],(int)round(factor),CurrSize);\n                    for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize*CurrSize->tsize*CurrSize->usize); i++)\n                        bufferImages[current_buffer?0:1][i]=bufferImages[current_buffer][i];\n                    current_buffer=current_buffer?0:1;\n                }\n                else\n                {\n                    cout << \"ERROR: \"<< parser << \" has to be an integer > 0\"<<endl;\n                    i=argc;\n                }\n            }\n//            // *********************  Erosion   *************************\n//            else if(strcmp(argv[i], \"-eroT\") == 0)\n//            {\n//                string parser=argv[++i];\n//                if(parser.find_first_not_of(\"1234567890.-+\")== string::npos)\n//                {\n//                    double factor=strtod(parser.c_str(),NULL);\n//                    //TopologicalErosion(bufferImages[current_buffer],(int)round(factor),CurrSize);\n//                    for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize*CurrSize->tsize*CurrSize->usize); i++)\n//                        bufferImages[current_buffer?0:1][i]=bufferImages[current_buffer][i];\n//                    current_buffer=current_buffer?0:1;\n//                }\n//                else\n//                {\n//                    cout << \"ERROR: \"<< parser << \" has to be an integer > 0\"<<endl;\n//                    i=argc;\n//                }\n//            }\n            // *********************  Erosion   *************************\n            else if(strcmp(argv[i], \"-erot\") == 0)\n            {\n                string parser=argv[++i];\n                if(parser.find_first_not_of(\"1234567890.-+\")== string::npos)\n                {\n                    double factor=strtod(parser.c_str(),NULL);\n                    Erosion(bufferImages[current_buffer],(int)round(factor),CurrSize);\n                    for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize*CurrSize->tsize*CurrSize->usize); i++)\n                        bufferImages[current_buffer?0:1][i]=bufferImages[current_buffer][i];\n                    current_buffer=current_buffer?0:1;\n                }\n                else\n                {\n                    cout << \"ERROR: \"<< parser << \" has to be an integer > 0\"<<endl;\n                    i=argc;\n                }\n            }\n\n            // *********************  Smooth Label   *************************\n            else if(strcmp(argv[i], \"-smol\") == 0)\n            {\n                string parser=argv[++i];\n                if(parser.find_first_not_of(\"1234567890.-+\")== string::npos)\n                {\n                    double factor=strtod(parser.c_str(),NULL);\n                    SmoothLab(bufferImages[current_buffer],factor,CurrSize);\n                    for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize*CurrSize->tsize*CurrSize->usize); i++)\n                        bufferImages[current_buffer?0:1][i]=bufferImages[current_buffer][i];\n                    current_buffer=current_buffer?0:1;\n                }\n                else\n                {\n                    cout << \"ERROR: \"<< parser << \" has to be an integer > 0\"<<endl;\n                    i=argc;\n                }\n            }\n            // *********************  Euclidean Distance Transform   *************************\n            else if(strcmp(argv[i], \"-euc\") == 0)\n            {\n\n                bool * Lable= new bool [CurrSize->numel];\n                float * Speed= new float [CurrSize->numel];\n                for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize*CurrSize->tsize*CurrSize->usize); i++)\n                {\n                    Lable[i]=bufferImages[current_buffer][i];\n                    Speed[i]=1.0f;\n                }\n                float * Distance = DoubleEuclideanDistance_3D(Lable,Speed,CurrSize);\n\n                for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize*CurrSize->tsize*CurrSize->usize); i++)\n                    bufferImages[current_buffer?0:1][i]=Distance[i];\n                current_buffer=current_buffer?0:1;\n                delete [] Distance;\n                delete [] Lable;\n                delete [] Speed;\n\n            }\n            // *********************  Geodesic Distance Transform   *************************\n            else if(strcmp(argv[i], \"-geo\") == 0)\n            {\n\n\n                string parser=argv[++i];\n                if(parser.find_first_not_of(\"1234567890.-+\")== string::npos)\n                {\n                    if(strtod(parser.c_str(),NULL)<=0)\n                    {\n                        cout<< \"ERROR: -geo speed should be larger than zero\"<<endl;\n                        return 1;\n                    }\n                    bool * Lable= new bool [CurrSize->numel];\n                    float * Speed= new float [CurrSize->numel];\n                    for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize*CurrSize->tsize*CurrSize->usize); i++)\n                    {\n                        Lable[i]=bufferImages[current_buffer][i];\n                        Speed[i]=strtod(parser.c_str(),NULL);\n                    }\n                    float * Distance = DoubleEuclideanDistance_3D(Lable,Speed,CurrSize);\n                    for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize*CurrSize->tsize*CurrSize->usize); i++)\n                        bufferImages[current_buffer?0:1][i]=Distance[i];\n                    current_buffer=current_buffer?0:1;\n                    delete [] Distance;\n                    delete [] Lable;\n                    delete [] Speed;\n                }\n                else\n                {\n\n                    if(   (strtod(parser.c_str(),NULL)!=0 && (parser.find(\".nii\")==string::npos ||parser.find(\".img\")==string::npos ||parser.find(\".hdr\")==string::npos )) ||(parser.length()==1 && parser.find(\"0\")!=string::npos))\n                    {\n                        cerr<<\"ERROR: \"<<argv[i]<<\"  has to be an image\"<<endl;\n                        exit(1);\n                    }\n\n                    bool * Lable= new bool [CurrSize->numel];\n                    float * Speed= new float [CurrSize->numel];\n                    nifti_image * SpeedImage=nifti_image_read(parser.c_str(),true);\n                    SpeedImage->nu=(SpeedImage->nu>1)?SpeedImage->nu:1;\n                    SpeedImage->nt=(SpeedImage->nt>1)?SpeedImage->nt:1;\n                    if(SpeedImage->datatype!=DT_FLOAT32)\n                    {\n                        seg_changeDatatype<float>(SpeedImage);\n                    }\n                    float * SpeedImagePtr = static_cast<float *>(SpeedImage->data);\n\n                    for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize*CurrSize->tsize*CurrSize->usize); i++)\n                    {\n                        Lable[i]=bufferImages[current_buffer][i];\n                        Speed[i]=SpeedImagePtr[i]>0.0001?SpeedImagePtr[i]:0.0001;\n                    }\n                    float * Distance = DoubleEuclideanDistance_3D(Lable,Speed,CurrSize);\n                    for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize*CurrSize->tsize*CurrSize->usize); i++)\n                        bufferImages[current_buffer?0:1][i]=Distance[i];\n                    current_buffer=current_buffer?0:1;\n                    delete [] Distance;\n                    delete [] Lable;\n                    delete [] Speed;\n                    nifti_image_free(SpeedImage);\n                }\n            }\n\n            // *********************  linear LS Normlise  *************************\n            else if(strcmp(argv[i], \"-llsnorm\") == 0)\n            {\n                string parser=argv[++i];\n                if(   (strtod(parser.c_str(),NULL)!=0 && (parser.find(\".nii\")==string::npos ||parser.find(\".img\")==string::npos ||parser.find(\".hdr\")==string::npos ))\n                      ||(parser.length()==1 && parser.find(\"0\")!=string::npos))\n                {\n                    cerr<<\"ERROR: \"<<argv[i]<<\"  has to be an image\"<<endl;\n                    exit(1);\n                }\n                else\n                {\n                    nifti_image * NewImage=nifti_image_read(parser.c_str(),true);\n                    NewImage->nu=(NewImage->nu>1)?NewImage->nu:1;\n                    NewImage->nt=(NewImage->nt>1)?NewImage->nt:1;\n                    if(NewImage->datatype!=DT_FLOAT32)\n                    {\n                        seg_changeDatatype<float>(NewImage);\n                    }\n                    float * NewImagePtr = static_cast<float *>(NewImage->data);\n\n                    // Y=a*X+b\n                    float a=0;\n                    float b=0;\n\n\n                    if(NewImage->nx==CurrSize->xsize&&NewImage->ny==CurrSize->ysize&&NewImage->nz==CurrSize->zsize&&NewImage->nt==CurrSize->tsize&&NewImage->nu==CurrSize->usize)\n                    {\n\n                        LS_Vecs(bufferImages[current_buffer],NewImagePtr,NULL, (CurrSize->xsize*CurrSize->ysize*CurrSize->zsize),&a, &b);\n                        for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize*CurrSize->tsize*CurrSize->usize); i++)\n                            bufferImages[current_buffer?0:1][i]=a*NewImagePtr[i]+b;\n                        current_buffer=current_buffer?0:1;\n                    }\n                    else\n                    {\n                        cout << \"ERROR: Image \"<< parser << \" is the wrong size  -  original = ( \"<<CurrSize->xsize<<\",\"\n                             <<CurrSize->ysize<<\",\"<<CurrSize->zsize<<\",\"<<CurrSize->tsize<<\",\"<<CurrSize->usize<<\" ) New image = ( \"\n                            <<NewImage->nx<<\",\"<<NewImage->ny<<\",\"<<NewImage->nz<<\",\"<<NewImage->nt<<\",\"<<NewImage->nu<<\" )\"<<endl;\n                        i=argc;\n                    }\n                    nifti_image_free(NewImage);\n                }\n            }\n\n            // ********************* linear LTS Normlise  *************************\n            else if(strcmp(argv[i], \"-lltsnorm\") == 0)\n            {\n                string parser=argv[++i];\n\n                string parserout=argv[++i];\n                float percent_outlier=strtod(parserout.c_str(),NULL);\n                percent_outlier=percent_outlier>0.5?0.5:(percent_outlier<0?0:percent_outlier);\n                if(   (strtod(parser.c_str(),NULL)!=0 && (parser.find(\".nii\")==string::npos ||parser.find(\".img\")==string::npos ||parser.find(\".hdr\")==string::npos ))\n                      ||(parser.length()==1 && parser.find(\"0\")!=string::npos))\n                {\n                    cerr<<\"ERROR: \"<<argv[i]<<\"  has to be an image\"<<endl;\n                    exit(1);\n                }\n                else\n                {\n                    nifti_image * NewImage=nifti_image_read(parser.c_str(),true);\n                    NewImage->nu=(NewImage->nu>1)?NewImage->nu:1;\n                    NewImage->nt=(NewImage->nt>1)?NewImage->nt:1;\n                    if(NewImage->datatype!=DT_FLOAT32)\n                    {\n                        seg_changeDatatype<float>(NewImage);\n                    }\n                    float * NewImagePtr = static_cast<float *>(NewImage->data);\n\n                    // Y=a*X+b\n                    float a=0;\n                    float b=0;\n\n\n                    if(NewImage->nx==CurrSize->xsize&&NewImage->ny==CurrSize->ysize&&NewImage->nz==CurrSize->zsize&&NewImage->nt==CurrSize->tsize&&NewImage->nu==CurrSize->usize)\n                    {\n\n                        LTS_Vecs(bufferImages[current_buffer],NewImagePtr,NULL,percent_outlier,20, 0.001, (CurrSize->xsize*CurrSize->ysize*CurrSize->zsize),&a, &b);\n\n                        for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize*CurrSize->tsize*CurrSize->usize); i++)\n                            bufferImages[current_buffer?0:1][i]=a*NewImagePtr[i]+b;\n                        current_buffer=current_buffer?0:1;\n                    }\n                    else\n                    {\n                        cout << \"ERROR: Image \"<< parser << \" is the wrong size  -  original = ( \"<<CurrSize->xsize<<\",\"\n                             <<CurrSize->ysize<<\",\"<<CurrSize->zsize<<\",\"<<CurrSize->tsize<<\",\"<<CurrSize->usize<<\" ) New image = ( \"\n                            <<NewImage->nx<<\",\"<<NewImage->ny<<\",\"<<NewImage->nz<<\",\"<<NewImage->nt<<\",\"<<NewImage->nu<<\" )\"<<endl;\n                        i=argc;\n                    }\n                    nifti_image_free(NewImage);\n                }\n            }\n\n            // *********************  QuadraticLS Normlise  *************************\n            else if(strcmp(argv[i], \"-qlsnorm\") == 0)\n            {\n\n                string order_str=argv[++i];\n                int order=(int)round(strtod(order_str.c_str(),NULL));\n\n                if(order>4){\n                    cout << \"ERROR: Order is too high... using order 5\"<<endl;\n                    order=4;\n                }\n                if(order<1){\n                    cout << \"ERROR: Order is too low... using order 1\"<<endl;\n                    order=1;\n                }\n\n                string parser=argv[++i];\n                nifti_image * NewImage=nifti_image_read(parser.c_str(),true);\n                NewImage->nu=(NewImage->nu>1)?NewImage->nu:1;\n                NewImage->nt=(NewImage->nt>1)?NewImage->nt:1;\n                if(NewImage->datatype!=DT_FLOAT32)\n                {\n                    seg_changeDatatype<float>(NewImage);\n                }\n                float * NewImagePtr = static_cast<float *>(NewImage->data);\n\n\n                const long nvox=CurrSize->xsize*CurrSize->ysize*CurrSize->zsize;\n\n                Eigen::MatrixXf Img1(nvox,order+1);\n                Eigen::VectorXf Img2(nvox,1);\n\n                for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize); i++)\n                    Img2(i)=bufferImages[current_buffer][i];\n\n                for(int j=0; j<(order+1); j++)\n                    for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize); i++)\n                        Img1(i,j)=pow(NewImagePtr[i],j);\n\n                Eigen::MatrixXf Img1TransImg1=Img1.transpose()*Img1;\n                Eigen::VectorXf Img1TransImg2=Img1.transpose()*Img2;\n\n                Eigen::VectorXf x;\n                x=Img1TransImg1.lu().solve(Img1TransImg2); // using a LU factorization\n\n                cout<<x;\n\n                for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize); i++){\n                    bufferImages[current_buffer?0:1][i]=x(0);\n                }\n                for(int j=1; j<(order+1); j++){\n                    for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize); i++){\n                        bufferImages[current_buffer?0:1][i]+=x(j)*pow(NewImagePtr[i],j);\n                    }\n                }\n\n                current_buffer=current_buffer?0:1;\n                nifti_image_free(NewImage);\n\n            }\n\n            else if(strcmp(argv[i], \"-qlsnorm_mask\") == 0)\n            {\n\n                string order_str=argv[++i];\n                int order=(int)round(strtod(order_str.c_str(),NULL));\n\n                if(order>4){\n                    cout << \"ERROR: Order is too high... using order 5\"<<endl;\n                    order=4;\n                }\n                if(order<1){\n                    cout << \"ERROR: Order is too low... using order 1\"<<endl;\n                    order=1;\n                }\n\n                string parser=argv[++i];\n                nifti_image * NewImage=nifti_image_read(parser.c_str(),true);\n                NewImage->nu=(NewImage->nu>1)?NewImage->nu:1;\n                NewImage->nt=(NewImage->nt>1)?NewImage->nt:1;\n                if(NewImage->datatype!=DT_FLOAT32)\n                {\n                    seg_changeDatatype<float>(NewImage);\n                }\n                float * NewImagePtr = static_cast<float *>(NewImage->data);\n\n                parser=argv[++i];\n                nifti_image * MaskImage=nifti_image_read(parser.c_str(),true);\n                MaskImage->nu=(MaskImage->nu>1)?MaskImage->nu:1;\n                MaskImage->nt=(MaskImage->nt>1)?MaskImage->nt:1;\n                if(MaskImage->datatype!=DT_FLOAT32)\n                {\n                    seg_changeDatatype<float>(MaskImage);\n                }\n                float * MaskImagePtr = static_cast<float *>(MaskImage->data);\n\n                size_t nvoxmax=0;\n                for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize); i++){\n                    if(MaskImagePtr[i]>0 && isnan(bufferImages[current_buffer][i])==0 && isnan(NewImagePtr[i])==0)\n                    {\n                        nvoxmax++;\n                    }\n                }\n\n                Eigen::MatrixXf Img1(nvoxmax+1,order+1);\n                Eigen::VectorXf Img2(nvoxmax+1);\n\n                size_t nvox=0;\n                for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize); i++)\n                {\n                    if(MaskImagePtr[i]>0 && isnan(bufferImages[current_buffer][i])==0 && isnan(NewImagePtr[i])==0)\n                    {\n                        Img2(nvox)=bufferImages[current_buffer][i];\n                        nvox++;\n                    }\n                }\n\n                nvox=0;\n                for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize); i++){\n                    if(MaskImagePtr[i]>0 && isnan(bufferImages[current_buffer][i])==0 && isnan(NewImagePtr[i])==0)\n                    {\n                        for(int j=0; j<(order+1); j++){\n                            Img1(nvox,j)= (j==0)? 1 : pow(NewImagePtr[i],j) ;\n                        }\n                        nvox++;\n                    }\n                }\n                cout<<nvox<<endl;\n\n\n                Eigen::MatrixXf Img1TransImg1=Img1.transpose()*Img1;\n                Eigen::VectorXf Img1TransImg2=Img1.transpose()*Img2;\n\n                Eigen::VectorXf x;\n                x=Img1TransImg1.lu().solve(Img1TransImg2); // using a LU factorization\n\n                cout<<x<<endl;\n\n                cout <<\"ui\\n\"<<x(0)<<endl;\n                for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize); i++){\n                    bufferImages[current_buffer?0:1][i]=x(0);\n                }\n                for(int j=1; j<(order+1); j++){\n                    cout <<x(j)<<endl;\n                    for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize); i++){\n                        bufferImages[current_buffer?0:1][i]+=x(j)*pow(NewImagePtr[i],j);\n                    }\n                }\n\n                current_buffer=current_buffer?0:1;\n                nifti_image_free(NewImage);\n                nifti_image_free(MaskImage);\n\n            }\n            else if(strcmp(argv[i], \"-qlsnorm2_mask\") == 0)\n            {\n\n                string order_str=argv[++i];\n                int order=(int)round(strtod(order_str.c_str(),NULL));\n\n                if(order>4){\n                    cout << \"ERROR: Order is too high... using order 5\"<<endl;\n                    order=4;\n                }\n                if(order<1){\n                    cout << \"ERROR: Order is too low... using order 1\"<<endl;\n                    order=1;\n                }\n\n                string parser=argv[++i];\n                nifti_image * NewImage=nifti_image_read(parser.c_str(),true);\n                NewImage->nu=(NewImage->nu>1)?NewImage->nu:1;\n                NewImage->nt=(NewImage->nt>1)?NewImage->nt:1;\n                if(NewImage->datatype!=DT_FLOAT32)\n                {\n                    seg_changeDatatype<float>(NewImage);\n                }\n                float * NewImagePtr = static_cast<float *>(NewImage->data);\n\n                parser=argv[++i];\n                nifti_image * MaskImage=nifti_image_read(parser.c_str(),true);\n                MaskImage->nu=(MaskImage->nu>1)?MaskImage->nu:1;\n                MaskImage->nt=(MaskImage->nt>1)?MaskImage->nt:1;\n                if(MaskImage->datatype!=DT_FLOAT32)\n                {\n                    seg_changeDatatype<float>(MaskImage);\n                }\n                float * MaskImagePtr = static_cast<float *>(MaskImage->data);\n\n                size_t nvoxmax=0;\n                for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize); i++){\n                    if(MaskImagePtr[i]>0 && isnan(bufferImages[current_buffer][i])==0 && isnan(NewImagePtr[i])==0)\n                    {\n                        nvoxmax++;\n                    }\n                }\n\n                Eigen::MatrixXf Img1(nvoxmax+1,order);\n                Eigen::VectorXf Img2(nvoxmax+1);\n\n                size_t nvox=0;\n                for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize); i++)\n                {\n                    if(MaskImagePtr[i]>0 && isnan(bufferImages[current_buffer][i])==0 && isnan(NewImagePtr[i])==0)\n                    {\n                        Img2(nvox)=bufferImages[current_buffer][i];\n                        nvox++;\n                    }\n                }\n\n                nvox=0;\n                for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize); i++){\n                    if(MaskImagePtr[i]>0 && isnan(bufferImages[current_buffer][i])==0 && isnan(NewImagePtr[i])==0)\n                    {\n                        for(int j=1; j<(order+1); j++){\n                            Img1(nvox,j-1)= pow(NewImagePtr[i],j) ;\n                        }\n                        nvox++;\n                    }\n                }\n\n\n                Eigen::MatrixXf Img1TransImg1=Img1.transpose()*Img1;\n                Eigen::VectorXf Img1TransImg2=Img1.transpose()*Img2;\n\n                Eigen::VectorXf x;\n                x=Img1TransImg1.lu().solve(Img1TransImg2); // using a LU factorization\n\n                cout<<x<<endl;\n\n                for(int j=1; j<(order+1); j++){\n                    for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize); i++){\n                        bufferImages[current_buffer?0:1][i]+=x(j-1)*pow(NewImagePtr[i],j);\n                    }\n                }\n\n                current_buffer=current_buffer?0:1;\n                nifti_image_free(NewImage);\n                nifti_image_free(MaskImage);\n\n            }\n\n            // *********************  QuadraticLS Normlise  *************************\n            else if(strcmp(argv[i], \"-qlshnorm\") == 0)\n            {\n\n                string order_str=argv[++i];\n                int order=(int)round(strtod(order_str.c_str(),NULL));\n\n                if(order>5){\n                    cout << \"ERROR: Order is too high... using order 5\"<<endl;\n                    order=4;\n                }\n                if(order<1){\n                    cout << \"ERROR: Order is too low... using order 1\"<<endl;\n                    order=1;\n                }\n\n                string parser=argv[++i];\n                nifti_image * NewImage=nifti_image_read(parser.c_str(),true);\n                NewImage->nu=(NewImage->nu>1)?NewImage->nu:1;\n                NewImage->nt=(NewImage->nt>1)?NewImage->nt:1;\n                if(NewImage->datatype!=DT_FLOAT32)\n                {\n                    seg_changeDatatype<float>(NewImage);\n                }\n                float * NewImagePtr = static_cast<float *>(NewImage->data);\n\n\n\n                // copy image, sort and fill vector\n                size_t img3Dsize=(NewImage->nx*NewImage->ny*NewImage->nz);\n                size_t countnan=0;\n                for(size_t index=0; index<img3Dsize; index++)\n                    countnan+=isnan(NewImagePtr[index])?0:1;\n                float * imgsort=new float [countnan];\n                size_t countindex=0;\n                for(size_t index=0; index<countnan; index++)\n                    if(isnan(NewImagePtr[index])==0){\n                        imgsort[countindex]=NewImagePtr[index];\n                        countindex++;\n                    }\n                HeapSort(imgsort,countnan-1);\n                Eigen::VectorXf Img2(1000,1);\n                for(int percentile=0; percentile<1000; percentile++)\n                    Img2(percentile)=imgsort[(long)(floor(( (float)(percentile) / 1000.0f ) * (float)( countnan-1 )))];\n                delete [] imgsort;\n\n\n                // copy image, sort and fill vector\n                img3Dsize=(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize);\n                countnan=0;\n                for(size_t index=0; index<img3Dsize; index++)\n                    countnan+=isnan(bufferImages[current_buffer][index])?0:1;\n                imgsort=new float [countnan];\n                countindex=0;\n                for(size_t index=0; index<countnan; index++)\n                    if(isnan(bufferImages[current_buffer][index])==0){\n                        imgsort[countindex]=bufferImages[current_buffer][index];\n                        countindex++;\n                    }\n                HeapSort(imgsort,countnan-1);\n                Eigen::MatrixXf Img1(1000,order+1);\n                for(int j=0; j<(order+1); j++)\n                    for(int percentile=0; percentile<1000; percentile++){\n                        Img1(percentile,j)=pow(imgsort[(long)(floor(( (float)(percentile) / 1000.0f ) * (float)( countnan-1 )))] , j );\n                    }\n                delete [] imgsort;\n\n                Eigen::MatrixXf Img1TransImg1=Img1.transpose()*Img1;\n                Eigen::VectorXf Img1TransImg2=Img1.transpose()*Img2;\n\n                Eigen::VectorXf x;\n                x=Img1TransImg1.lu().solve(Img1TransImg2); // using a LU factorization\n\n                cout<<x<<endl;\n\n                for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize); i++){\n                    bufferImages[current_buffer?0:1][i]=x(0);\n                }\n                for(int j=1; j<(order+1); j++)\n                    for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize); i++){\n                        bufferImages[current_buffer?0:1][i]+=x(j)*pow(bufferImages[current_buffer][i],j);\n                    }\n\n                current_buffer=current_buffer?0:1;\n                nifti_image_free(NewImage);\n\n            }\n\n            else if(strcmp(argv[i], \"-qlshnorm_mask\") == 0)\n            {\n\n                string order_str=argv[++i];\n                int order=(int)round(strtod(order_str.c_str(),NULL));\n\n                if(order>4){\n                    cout << \"ERROR: Order is too high... using order 5\"<<endl;\n                    order=4;\n                }\n                if(order<1){\n                    cout << \"ERROR: Order is too low... using order 1\"<<endl;\n                    order=1;\n                }\n\n                string parser=argv[++i];\n                nifti_image * NewImage=nifti_image_read(parser.c_str(),true);\n                NewImage->nu=(NewImage->nu>1)?NewImage->nu:1;\n                NewImage->nt=(NewImage->nt>1)?NewImage->nt:1;\n                if(NewImage->datatype!=DT_FLOAT32)\n                {\n                    seg_changeDatatype<float>(NewImage);\n                }\n                float * NewImagePtr = static_cast<float *>(NewImage->data);\n\n                parser=argv[++i];\n                nifti_image * MaskImage=nifti_image_read(parser.c_str(),true);\n                MaskImage->nu=(MaskImage->nu>1)?MaskImage->nu:1;\n                MaskImage->nt=(MaskImage->nt>1)?MaskImage->nt:1;\n                if(MaskImage->datatype!=DT_FLOAT32)\n                {\n                    seg_changeDatatype<float>(MaskImage);\n                }\n                float * MaskImagePtr = static_cast<float *>(MaskImage->data);\n\n\n\n\n                // copy image, sort and fill vector\n                size_t img3Dsize=(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize);\n                size_t countnan=0;\n                size_t numbsamples=1000;\n\n                for(size_t index=0; index<img3Dsize; index++){\n                    if(isnan(NewImagePtr[index])==0&&isnan(bufferImages[current_buffer][index])==0&&MaskImagePtr[index]>0){\n                        countnan++;\n                    }\n                }\n                float * imgsort=new float [countnan];\n                size_t countindex=0;\n                for(size_t index=0; index<img3Dsize; index++){\n                    if(isnan(NewImagePtr[index])==0&&isnan(bufferImages[current_buffer][index])==0&&MaskImagePtr[index]>0){\n                        imgsort[countindex]=NewImagePtr[index];\n                        countindex++;\n                    }\n                }\n                //cout<<countnan<<endl;\n                //cout<<countindex<<endl;\n                HeapSort(imgsort,countnan-1);\n                Eigen::VectorXf Img2(numbsamples,1);\n                for(size_t percentile=0; percentile<numbsamples; percentile++){\n                    Img2(percentile)=imgsort[(long)(floor(( (float)(percentile) / (float)(numbsamples) ) * (float)( countnan-1 )))];\n                    // cout<<percentile<<\" - \"<<Img2(percentile)<<endl;\n                }\n\n\n                // copy image, sort and fill vector\n\n                countindex=0;\n                for(size_t index=0; index<img3Dsize; index++){\n                    if(isnan(NewImagePtr[index])==0&&isnan(bufferImages[current_buffer][index])==0&&MaskImagePtr[index]>0){\n                        imgsort[countindex]=bufferImages[current_buffer][index];\n                        countindex++;\n                    }\n                }\n                //cout<<countnan<<endl;\n                //cout<<countindex<<endl;\n                HeapSort(imgsort,countnan-1);\n                Eigen::MatrixXf Img1(numbsamples,order+1);\n                for(size_t percentile=0; percentile<numbsamples; percentile++){\n                    for(int j=0; j<(order+1); j++){\n                        Img1(percentile,j)=pow(imgsort[(long)(floor(( (float)(percentile) / (float)(numbsamples) ) * (float)( countnan-1 )))] , j );\n\n                    }\n                    // cout<<percentile<<\" - \"<<Img1(percentile,1)<<endl;\n                }\n                delete [] imgsort;\n\n\n\n\n                Eigen::MatrixXf Img1TransImg1=Img1.transpose()*Img1;\n                Eigen::VectorXf Img1TransImg2=Img1.transpose()*Img2;\n\n                Eigen::VectorXf x;\n                x=Img1TransImg1.lu().solve(Img1TransImg2); // using a LU factorization\n\n                cout<<x<<endl;\n                for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize); i++){\n                    bufferImages[current_buffer?0:1][i]=x(0);\n                }\n                for(int j=1; j<(order+1); j++){\n                    for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize); i++){\n                        bufferImages[current_buffer?0:1][i]+=x(j)*pow(bufferImages[current_buffer][i],j);\n                    }\n                }\n\n                current_buffer=current_buffer?0:1;\n                nifti_image_free(NewImage);\n                nifti_image_free(MaskImage);\n\n            }\n            // *********************  GAUSSIAN SMOTHING *************************\n            else if(strcmp(argv[i], \"-smo\") == 0)\n            {\n                string parser=argv[++i];\n                if((strtod(parser.c_str(),NULL)!=0 ))\n                {\n                    float factor=strtof(parser.c_str(),NULL);\n                    for(long tp=0; tp<(long)(CurrSize->tsize*CurrSize->usize); tp++){\n                        //create dummy nii\n                        nifti_image * TMPnii = nifti_copy_nim_info(InputImage);\n                        TMPnii->dim[1]=CurrSize->xsize;\n                        TMPnii->dim[2]=CurrSize->ysize;\n                        TMPnii->dim[3]=CurrSize->zsize;\n                        TMPnii->dim[4]=TMPnii->nt=1;\n                        TMPnii->dim[5]=TMPnii->nu=1;\n                        nifti_update_dims_from_array(TMPnii);\n                        //copy pointer, run gaussian, and set to null\n                        TMPnii->data=static_cast<void*>(&bufferImages[current_buffer][CurrSize->xsize*CurrSize->ysize*CurrSize->zsize*tp]);\n                        GaussianSmoothing5D_nifti(TMPnii,NULL,factor);\n                        TMPnii->data=NULL;\n                        //As TMPnii->data=NULL, the free will not cause any harm\n                        nifti_image_free(TMPnii);\n                    }\n\n\n                    //current_buffer=current_buffer?0:1;\n                }\n                else\n                {\n                    cout << \"ERROR: \"<< parser << \" has to be a number > 0\"<<endl;\n                    i=argc;\n                }\n            }\n            // *********************  GAUSSIAN SMOTHING *************************\n            else if(strcmp(argv[i], \"-smoNaN\") == 0)\n            {\n                string filename=argv[++i];\n                nifti_image * MaskImage=nifti_image_read(filename.c_str(),true);\n                MaskImage->nu=(MaskImage->nu>1)?MaskImage->nu:1;\n                MaskImage->nt=(MaskImage->nt>1)?MaskImage->nt:1;\n                if(MaskImage->datatype!=DT_FLOAT32)\n                {\n                    seg_changeDatatype<SegPrecisionTYPE>(MaskImage);\n                }\n\n\n                for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize*CurrSize->tsize*CurrSize->usize); i++)\n                    bufferImages[current_buffer][i]=(bufferImages[current_buffer][i])?\n                                bufferImages[current_buffer][i]:\n                                std::numeric_limits<float>::quiet_NaN();\n\n                for(long tp=0; tp<(long)(CurrSize->tsize*CurrSize->usize); tp++){\n\n\n                    //create dummy nii\n                    nifti_image * TMPnii = nifti_copy_nim_info(InputImage);\n                    TMPnii->dim[1]=CurrSize->xsize;\n                    TMPnii->dim[2]=CurrSize->ysize;\n                    TMPnii->dim[3]=CurrSize->zsize;\n                    TMPnii->dim[4]=TMPnii->nt=1;\n                    TMPnii->dim[5]=TMPnii->nu=1;\n                    nifti_update_dims_from_array(TMPnii);\n                    //copy pointer, run gaussian, and set to null\n                    TMPnii->data=static_cast<void*>(&bufferImages[current_buffer][CurrSize->xsize*CurrSize->ysize*CurrSize->zsize*tp]);\n                    GaussianSmoothing4D_Nan_nifti(TMPnii,MaskImage);\n                    TMPnii->data=NULL;\n                    //As TMPnii->data=NULL, the free will not cause any harm\n                    nifti_image_free(TMPnii);\n\n                    nifti_image_free(MaskImage);\n                }\n\n                    //current_buffer=current_buffer?0:1;\n\n            }\n            // *********************  GAUSSIAN sharpening  (NOT WORKING) *************************\n            else if(strcmp(argv[i], \"-sharp\") == 0)\n            {\n                string parser=argv[++i];\n                if((strtod(parser.c_str(),NULL)!=0 ))\n                {\n                    float factor=strtof(parser.c_str(),NULL);\n                    for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize*CurrSize->tsize*CurrSize->usize); i++)\n                        bufferImages[current_buffer?0:1][i]=bufferImages[current_buffer][i];\n\n                    GaussianFilter4D_cArray(&bufferImages[current_buffer][0], factor, CurrSize);\n                    for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize*CurrSize->tsize*CurrSize->usize); i++)\n                        bufferImages[current_buffer?0:1][i]=(bufferImages[current_buffer?0:1][i]-bufferImages[current_buffer][i]);\n\n                    current_buffer=current_buffer?0:1;\n                }\n                else\n                {\n                    cout << \"ERROR: \"<< parser << \" has to be a number > 0\"<<endl;\n                    i=argc;\n                }\n            }\n            // *********************  Min  *************************\n            else if(strcmp(argv[i], \"-min\") == 0)\n            {\n                string parser=argv[++i];\n                if(!(parser.find_first_not_of(\"1234567890.-+\")== string::npos))\n                {\n\n                    nifti_image * NewImage=nifti_image_read(parser.c_str(),true);\n                    NewImage->nu=(NewImage->nu>1)?NewImage->nu:1;\n                    NewImage->nt=(NewImage->nt>1)?NewImage->nt:1;\n                    if(NewImage->datatype!=DT_FLOAT32)\n                    {\n                        seg_changeDatatype<SegPrecisionTYPE>(NewImage);\n                    }\n                    SegPrecisionTYPE * NewImagePtr = static_cast<SegPrecisionTYPE *>(NewImage->data);\n                    if(NewImage->nx==CurrSize->xsize&&NewImage->ny==CurrSize->ysize&&NewImage->nz==CurrSize->zsize&&NewImage->nt==CurrSize->tsize&&NewImage->nu==CurrSize->usize)\n                    {\n                        for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize*CurrSize->tsize*CurrSize->usize); i++)\n                            bufferImages[current_buffer?0:1][i]=min(bufferImages[current_buffer][i],NewImagePtr[i]);\n                        current_buffer=current_buffer?0:1;\n                    }\n                }\n            }\n\n            // *********************  Otsu thresholding *************************\n            else if(strcmp(argv[i], \"-otsu\") == 0)\n            {\n\n                otsu(bufferImages[current_buffer],NULL,CurrSize);\n                for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize*CurrSize->tsize*CurrSize->usize); i++)\n                    bufferImages[current_buffer?0:1][i]=bufferImages[current_buffer][i];\n\n                current_buffer=current_buffer?0:1;\n            }\n\n            // *********************  Fill  *************************\n            else if(strcmp(argv[i], \"-fill\") == 0)\n            {\n                if(CurrSize->tsize==1)\n                {\n                    Close_Forground_ConnectComp<float,float>(static_cast<void*>(bufferImages[current_buffer]),static_cast<void*>(bufferImages[current_buffer?0:1]),CurrSize);\n                    current_buffer=current_buffer?0:1;\n                }\n                else\n                {\n                    cout << \"ERROR: Image to -fill is not 3D\"<<endl;\n                    i=argc;\n                }\n            }\n            // *********************  Largest Connected Component  *************************\n            else if(strcmp(argv[i], \"-lconcomp\") == 0)\n            {\n                if(CurrSize->tsize==1)\n                {\n                    Largest_ConnectComp<float,float>(static_cast<void*>(bufferImages[current_buffer]),static_cast<void*>(bufferImages[current_buffer?0:1]),CurrSize);\n                    current_buffer=current_buffer?0:1;\n                }\n                else\n                {\n                    cout << \"ERROR: Image to -lconcomp is not 3D\"<<endl;\n                    i=argc;\n                }\n            }\n            // *********************  Connected Components 6NN  *************************\n            else if(strcmp(argv[i], \"-concomp6\") == 0)\n            {\n                if(CurrSize->tsize==1)\n                {\n                    ConnectComp6NN<float,float>(static_cast<void*>(bufferImages[current_buffer]),static_cast<void*>(bufferImages[current_buffer?0:1]),CurrSize);\n                    current_buffer=current_buffer?0:1;\n                }\n                else\n                {\n                    cout << \"ERROR: Image to -concomp6 is not 3D\"<<endl;\n                    i=argc;\n                }\n            }\n\n            // *********************  Connected Components 6NN  *************************\n            else if(strcmp(argv[i], \"-concomp26\") == 0)\n            {\n                if(CurrSize->tsize==1)\n                {\n                    ConnectComp26NN<float,float>(static_cast<void*>(bufferImages[current_buffer]),static_cast<void*>(bufferImages[current_buffer?0:1]),CurrSize);\n                    current_buffer=current_buffer?0:1;\n                }\n                else\n                {\n                    cout << \"ERROR: Image to -concomp26 is not 3D\"<<endl;\n                    i=argc;\n                }\n            }\n\n            // *********************  Range  *************************\n            else if(strcmp(argv[i], \"-range\") == 0)\n            {\n                float min=FLT_MAX;\n                float max=-FLT_MAX;\n                for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize*CurrSize->tsize*CurrSize->usize); i++)\n                {\n                    max=bufferImages[current_buffer][i]>max?bufferImages[current_buffer][i]:max;\n                    min=bufferImages[current_buffer][i]<min?bufferImages[current_buffer][i]:min;\n                }\n                InputImage->cal_max=max;\n                InputImage->cal_min=min;\n            }\n            // *********************  Extract time point  *************************\n            else if(strcmp(argv[i], \"-tp\") == 0)\n            {\n                string parser=argv[++i];\n                if(((strtod(parser.c_str(),NULL)!=0) || (parser.length()==1 && parser.find(\"0\")!=string::npos && parser.find(\"0\")!=string::npos) )&& strtod(parser.c_str(),NULL)<=CurrSize->tsize )\n                {\n                    float factor=strtof(parser.c_str(),NULL);\n                    InputImage->dim[4]=InputImage->nt=CurrSize->tsize=1;\n                    InputImage->dim[0]=3;\n                    InputImage->dim[5]=InputImage->nu=CurrSize->usize=1;\n                    for(long i=0; i<CurrSize->numel; i++)\n                        bufferImages[current_buffer?0:1][i]=bufferImages[current_buffer][i+(int)round(factor)*CurrSize->numel];\n\n                    current_buffer=current_buffer?0:1;\n                }\n                else\n                {\n                    cout << \"ERROR: \"<< parser << \" is not an integer\"<<endl;\n                    i=argc;\n                }\n            }\n\n            // *********************  Split Lables  *************************\n            else if(strcmp(argv[i], \"-splitlab\") == 0)\n            {\n                int maxlab=0;\n                for(long index=0; index<(CurrSize->numel*(CurrSize->tsize*CurrSize->usize)); index++)\n                    maxlab=(round(bufferImages[current_buffer][index])>maxlab)?(int)round(bufferImages[current_buffer][index]):maxlab;\n                maxlab=maxlab+1;\n                if(maxlab>0 && CurrSize->tsize<=1&& CurrSize->usize<=1)\n                {\n                    CurrSize->tsize=maxlab;\n                    CurrSize->usize=1;\n\n                    delete [] bufferImages[current_buffer?0:1];\n                    bufferImages[current_buffer?0:1]= new SegPrecisionTYPE [CurrSize->numel*maxlab];\n                    for(long index=0; index<(CurrSize->numel*maxlab); index++)\n                        bufferImages[current_buffer?0:1][index]=0.0f;\n                    for(long index=0; index<(CurrSize->numel); index++)\n                        bufferImages[current_buffer?0:1][index+(int)round(bufferImages[current_buffer][index])*CurrSize->numel]=1.0f;\n                    delete [] bufferImages[current_buffer];\n                    bufferImages[current_buffer]= new SegPrecisionTYPE [CurrSize->numel*maxlab];\n                    for(long index=0; index<(CurrSize->numel*maxlab); index++)\n                        bufferImages[current_buffer][index]=0;\n                    current_buffer=current_buffer?0:1;\n                }\n                else\n                {\n                    if(CurrSize->tsize<=1&& CurrSize->usize<=1)\n                    {\n                        cout << \"ERROR: Working image is not 3D\"<<endl;\n                    }\n                    else\n                    {\n                        cout << \"ERROR: Found only \"<< maxlab << \" labels\"<<endl;\n                    }\n                    i=argc;\n                }\n            }\n            // *********************  Split Lables  *************************\n            else if(strcmp(argv[i], \"-splitinter\") == 0)\n            {\n                string direction=argv[++i];\n                if(CurrSize->tsize<=1&& CurrSize->usize<=1){\n                    CurrSize->tsize=2;\n                    CurrSize->usize=1;\n                    int oldxsize=CurrSize->xsize;\n                    int oldysize=CurrSize->ysize;\n                    int xincrement=1;\n                    int yincrement=1;\n                    int zincrement=1;\n\n                    if(direction==string(\"x\")){\n                        CurrSize->xsize=round(CurrSize->xsize/2);\n                        xincrement=2;\n                        Scalling[0]= 0.5f;\n                    }\n                    else if(direction==string(\"y\")){\n                        CurrSize->ysize=round(CurrSize->ysize/2);\n                        yincrement=2;\n                        Scalling[1]= 0.5f;\n                    }\n                    else if(direction==string(\"z\")){\n                        CurrSize->zsize=round(CurrSize->zsize/2);\n                        zincrement=2;\n                        Scalling[2]= 0.5f;\n                    }\n                    else{\n                        cout << \"ERROR: Direction \"<< direction << \" is not x, y or z\"<<endl;\n                        exit(1);\n                    }\n\n                    CurrSize->numel=(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize);\n                    for(long indexZ=0, indexZold=0; indexZ<CurrSize->zsize; indexZ++, indexZold+=zincrement){\n                        for(long indexY=0, indexYold=0; indexY<CurrSize->ysize; indexY++, indexYold+=yincrement){\n                            for(long indexX=0, indexXold=0; indexX<CurrSize->xsize; indexX++, indexXold+=xincrement){\n                                bufferImages[current_buffer?0:1][indexX+indexY*CurrSize->xsize+indexZ*CurrSize->ysize*CurrSize->xsize]=\n                                        bufferImages[current_buffer][indexXold+indexYold*oldxsize+indexZold*oldysize*oldxsize];\n                                bufferImages[current_buffer?0:1][indexX+indexY*CurrSize->xsize+indexZ*CurrSize->ysize*CurrSize->xsize+CurrSize->numel]=\n                                        bufferImages[current_buffer][(indexXold+xincrement-1)+(indexYold+yincrement-1)*oldxsize+(indexZold+zincrement-1)*oldysize*oldxsize];\n                            }\n                        }\n                    }\n                    current_buffer=current_buffer?0:1;\n\n                }\n\n            }\n            // *********************  Split Lables  *************************\n            else if(strcmp(argv[i], \"-splitnorm\") == 0)\n            {\n                string direction=argv[++i];\n                if(CurrSize->tsize<=1&& CurrSize->usize<=1){\n                    CurrSize->tsize=1;\n                    CurrSize->usize=1;\n                    int xincrement=1;\n                    int yincrement=1;\n                    int zincrement=1;\n                    //bool isdirectionsizeodd=0;\n                    if(direction==string(\"x\") || direction==string(\"1\")){\n                        xincrement=2;\n                        //isdirectionsizeodd=(CurrSize->xsize%2)==0;\n                    }\n                    else if(direction==string(\"y\") || direction==string(\"2\")){\n                        yincrement=2;\n                        //isdirectionsizeodd=(CurrSize->ysize%2)==0;\n                    }\n                    else if(direction==string(\"z\") || direction==string(\"3\")){\n                        zincrement=2;\n                        //isdirectionsizeodd=(CurrSize->zsize%2)==0;\n                    }\n                    else{\n                        cout << \"ERROR: Direction \"<< direction << \" is not x, y or z\"<<endl;\n                        exit(1);\n                    }\n\n                    //double regul=5.0f;\n                    std::vector<float> sortedimg;\n                    for(long indexZ=0; indexZ<(CurrSize->zsize); indexZ+=zincrement){\n                        for(long indexY=0; indexY<(CurrSize->ysize); indexY+=yincrement){\n                            for(long indexX=0; indexX<(CurrSize->xsize); indexX+=xincrement){\n                                sortedimg.push_back(bufferImages[current_buffer][indexX+indexY*CurrSize->xsize+indexZ*CurrSize->ysize*CurrSize->xsize]);\n                            }\n                        }\n                    }\n                    std::sort(sortedimg.begin(), sortedimg.end());\n                    float thresh=0.5f*sortedimg.at(round(sortedimg.size()*0.5f)); // Find a rough background threshold to ignore non-brain tissues\n                    sortedimg.clear();\n\n                    std::vector<float> sortedvec;\n                    CurrSize->numel=(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize);\n                    for(long indexZ=(zincrement-1); indexZ<(CurrSize->zsize-(zincrement-1)); indexZ++){\n                        for(long indexY=(yincrement-1); indexY<(CurrSize->ysize-(yincrement-1)); indexY++){\n                            for(long indexX=(xincrement-1); indexX<(CurrSize->xsize-(xincrement-1)); indexX++){\n\n                                double previous_next_mean_val=(bufferImages[current_buffer][(indexX+xincrement-1)+(indexY+yincrement-1)*CurrSize->xsize+(indexZ+zincrement-1)*CurrSize->ysize*CurrSize->xsize]+\n                                        bufferImages[current_buffer][(indexX-xincrement+1)+(indexY-yincrement+1)*CurrSize->xsize+(indexZ-zincrement+1)*CurrSize->ysize*CurrSize->xsize])/(2.0f);\n                                double current_val=bufferImages[current_buffer][indexX+indexY*CurrSize->xsize+indexZ*CurrSize->ysize*CurrSize->xsize];\n\n                                bool oddeven=(xincrement>1?indexX%2==0:(yincrement>1?indexY%2==0:(zincrement>1?indexZ%2==0:0)));\n\n                                float curRat=(current_val*previous_next_mean_val)/(oddeven?(current_val*current_val):(previous_next_mean_val*previous_next_mean_val));\n                                if(!(curRat!=curRat) && current_val>thresh){\n                                    sortedvec.push_back(curRat);\n                                }\n                            }\n                        }\n                    }\n                    std::sort(sortedvec.begin(), sortedvec.end());\n                    double compensation_ratio=sortedvec.at(round(sortedvec.size()/2.0f)); // Get the median ratio\n                    cout<<compensation_ratio<<endl;\n\n                    sortedvec.clear();\n                    for(long indexZ=0; indexZ<(CurrSize->zsize); indexZ+=zincrement){\n                        for(long indexY=0; indexY<(CurrSize->ysize); indexY+=yincrement){\n                            for(long indexX=0; indexX<(CurrSize->xsize); indexX+=xincrement){\n                                bufferImages[current_buffer?0:1][indexX+indexY*CurrSize->xsize+indexZ*CurrSize->ysize*CurrSize->xsize]=\n                                        compensation_ratio*bufferImages[current_buffer][indexX+indexY*CurrSize->xsize+indexZ*CurrSize->ysize*CurrSize->xsize];\n                                if((indexX+xincrement-1)<CurrSize->xsize && (indexY+yincrement-1)<CurrSize->ysize && (indexZ+zincrement-1)<CurrSize->zsize)\n                                {\n                                    bufferImages[current_buffer?0:1][(indexX+xincrement-1)+(indexY+yincrement-1)*CurrSize->xsize+(indexZ+zincrement-1)*CurrSize->ysize*CurrSize->xsize]=\n                                            bufferImages[current_buffer][(indexX+xincrement-1)+(indexY+yincrement-1)*CurrSize->xsize+(indexZ+zincrement-1)*CurrSize->ysize*CurrSize->xsize];\n                                }\n                            }\n                        }\n                    }\n                    current_buffer=current_buffer?0:1;\n\n                }\n\n            }\n//            // *********************  Split Lables  *************************\n//            else if(strcmp(argv[i], \"-splitnorm2\") == 0)\n//            {\n//                string direction=argv[++i];\n//                if(CurrSize->tsize<=1&& CurrSize->usize<=1){\n//                    int cur_dims[8]={3,CurrSize->xsize,CurrSize->ysize,CurrSize->zsize,1,1,1,1};\n//                    nifti_image * NewImage1=nifti_copy_nim_info(InputImage);\n//                    NewImage1->data= (void *) calloc(InputImage->nvox, sizeof(float));\n\n//                    nifti_image * NewImage2=nifti_copy_nim_info(InputImage);\n//                    NewImage2->data=(void *) calloc(InputImage->nvox, sizeof(float));\n\n//                    float* NewImage1_ptr=static_cast<SegPrecisionTYPE *>(NewImage1->data);\n//                    float* NewImage2_ptr=static_cast<SegPrecisionTYPE *>(NewImage2->data);\n\n//                    int xincrement=1;\n//                    int yincrement=1;\n//                    int zincrement=1;\n\n//                    if(direction==string(\"x\")){\n//                        xincrement=2;\n//                    }\n//                    else if(direction==string(\"y\")){\n//                        yincrement=2;\n//                    }\n//                    else if(direction==string(\"z\")){\n//                        zincrement=2;\n//                    }\n//                    else{\n//                        cout << \"ERROR: Direction \"<< direction << \" is not x, y or z\"<<endl;\n//                        exit(1);\n//                    }\n////                    double regul=1.0e-15f;\n\n//                    CurrSize->numel=(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize);\n//                    for(long indexZ=(zincrement-1); indexZ<(CurrSize->zsize-(zincrement-1)); indexZ++){\n//                        for(long indexY=(yincrement-1); indexY<(CurrSize->ysize-(yincrement-1)); indexY++){\n//                            for(long indexX=(xincrement-1); indexX<(CurrSize->xsize-(xincrement-1)); indexX++){\n\n//                                if(xincrement>1?indexX%2==0:(yincrement>1?indexY%2==0:(zincrement>1?indexZ%2==0:0))){\n//                                    NewImage1_ptr[indexX+indexY*CurrSize->xsize+indexZ*CurrSize->ysize*CurrSize->xsize]=\n//                                            (bufferImages[current_buffer][(indexX+xincrement-1)+(indexY+yincrement-1)*CurrSize->xsize+(indexZ+zincrement-1)*CurrSize->ysize*CurrSize->xsize]+\n//                                            bufferImages[current_buffer][(indexX-xincrement+1)+(indexY-yincrement+1)*CurrSize->xsize+(indexZ-zincrement+1)*CurrSize->ysize*CurrSize->xsize])/(2.0f);\n//                                    NewImage2_ptr[indexX+indexY*CurrSize->xsize+indexZ*CurrSize->ysize*CurrSize->xsize]=\n//                                            bufferImages[current_buffer][indexX+indexY*CurrSize->xsize+indexZ*CurrSize->ysize*CurrSize->xsize];\n//                                }\n//                                else{\n//                                    NewImage2_ptr[indexX+indexY*CurrSize->xsize+indexZ*CurrSize->ysize*CurrSize->xsize]=\n//                                            (bufferImages[current_buffer][(indexX+xincrement-1)+(indexY+yincrement-1)*CurrSize->xsize+(indexZ+zincrement-1)*CurrSize->ysize*CurrSize->xsize]+\n//                                            bufferImages[current_buffer][(indexX-xincrement+1)+(indexY-yincrement+1)*CurrSize->xsize+(indexZ-zincrement+1)*CurrSize->ysize*CurrSize->xsize])/(2.0f);\n//                                    NewImage1_ptr[indexX+indexY*CurrSize->xsize+indexZ*CurrSize->ysize*CurrSize->xsize]=\n//                                            bufferImages[current_buffer][indexX+indexY*CurrSize->xsize+indexZ*CurrSize->ysize*CurrSize->xsize];\n//                                }\n\n//                            }\n//                        }\n//                    }\n//                    nifti_set_filenames(NewImage1,\"img1.nii.gz\",0,0);\n//                    nifti_image_write(NewImage1);\n//                    nifti_set_filenames(NewImage2,\"img2.nii.gz\",0,0);\n//                    nifti_image_write(NewImage2);\n//                    // Y=a*X+b\n//                    float a=0;\n//                    float b=0;\n//                    LS_Vecs(NewImage1_ptr,NewImage2_ptr,NULL, (CurrSize->xsize*CurrSize->ysize*CurrSize->zsize),&a, &b);\n//                    cout<<a<<\"  \"<<b<<endl;\n\n//                    for(long indexZ=0; indexZ<(CurrSize->zsize); indexZ+=zincrement){\n//                        for(long indexY=0; indexY<(CurrSize->ysize); indexY+=yincrement){\n//                            for(long indexX=0; indexX<(CurrSize->xsize); indexX+=xincrement){\n//                                bufferImages[current_buffer?0:1][indexX+indexY*CurrSize->xsize+indexZ*CurrSize->ysize*CurrSize->xsize]=\n//                                        a*bufferImages[current_buffer][indexX+indexY*CurrSize->xsize+indexZ*CurrSize->ysize*CurrSize->xsize];\n//                                if((indexX+xincrement-1)<CurrSize->xsize && (indexY+yincrement-1)<CurrSize->ysize && (indexZ+zincrement-1)<CurrSize->zsize)\n//                                {\n//                                    bufferImages[current_buffer?0:1][(indexX+xincrement-1)+(indexY+yincrement-1)*CurrSize->xsize+(indexZ+zincrement-1)*CurrSize->ysize*CurrSize->xsize]=\n//                                            bufferImages[current_buffer][(indexX+xincrement-1)+(indexY+yincrement-1)*CurrSize->xsize+(indexZ+zincrement-1)*CurrSize->ysize*CurrSize->xsize];\n//                                }\n//                            }\n//                        }\n//                    }\n//                    current_buffer=current_buffer?0:1;\n//                }\n//            }\n            // *********************  Split Lables  *************************\n            else if(strcmp(argv[i], \"-joininter\") == 0)\n            {\n                string direction=argv[++i];\n                if(CurrSize->tsize==2&& CurrSize->usize<=1){\n                    CurrSize->tsize=1;\n                    CurrSize->usize=1;\n                    int oldxsize=CurrSize->xsize;\n                    int oldysize=CurrSize->ysize;\n                    int oldzsize=CurrSize->zsize;\n                    int xincrement=1;\n                    int yincrement=1;\n                    int zincrement=1;\n\n                    if(direction==string(\"x\")){\n                        CurrSize->xsize=round(CurrSize->xsize*2);\n                        xincrement=2;\n                        Scalling[0]= 2.0f;\n                    }\n                    else if(direction==string(\"y\")){\n                        CurrSize->ysize=round(CurrSize->ysize*2);\n                        yincrement=2;\n                        Scalling[1]= 2.0f;\n                    }\n                    else if(direction==string(\"z\")){\n                        CurrSize->zsize=round(CurrSize->zsize*2);\n                        zincrement=2;\n                        Scalling[2]= 2.0f;\n                    }\n                    else{\n                        cout << \"ERROR: Direction \"<< direction << \" is not x, y or z\"<<endl;\n                        exit(1);\n                    }\n\n                    CurrSize->numel=(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize);\n                    long oldnumel=(long)(oldxsize*oldysize*oldzsize);\n                    for(long indexZ=0, indexZold=0; indexZ<CurrSize->zsize; indexZ+=zincrement, indexZold++){\n                        for(long indexY=0, indexYold=0; indexY<CurrSize->ysize; indexY+=yincrement, indexYold++){\n                            for(long indexX=0, indexXold=0; indexX<CurrSize->xsize; indexX+=xincrement, indexXold++){\n                                bufferImages[current_buffer?0:1][(indexX)+(indexY)*CurrSize->xsize+(indexZ)*CurrSize->ysize*CurrSize->xsize]=\n                                        bufferImages[current_buffer][indexXold+indexYold*oldxsize+indexZold*oldysize*oldxsize];\n                                bufferImages[current_buffer?0:1][(indexX+xincrement-1)+(indexY+yincrement-1)*CurrSize->xsize+(indexZ+zincrement-1)*CurrSize->ysize*CurrSize->xsize]=\n                                        bufferImages[current_buffer][indexXold+indexYold*oldxsize+indexZold*oldysize*oldxsize+oldnumel];\n                            }\n                        }\n                    }\n                    current_buffer=current_buffer?0:1;\n\n                }\n                else{\n                    cout << \"ERROR: Number of time points is not 2\"<<endl;\n                    exit(1);\n                }\n\n            }\n            // *********************  merge time points  *************************\n            else if(strcmp(argv[i], \"-merge\") == 0)\n            {\n                string parser=argv[++i];\n                string parsertp=argv[++i];\n                if(strtod(parser.c_str(),NULL) && (strtod(parser.c_str(),NULL)!=0 ))\n                {\n                    long numberof_new_images=(int)strtof(parser.c_str(),NULL);\n                    long dim=(int)strtof(parsertp.c_str(),NULL);\n\n                    long old_tsize=CurrSize->tsize;\n                    long old_usize=CurrSize->usize;\n\n                    long new_tsize=CurrSize->tsize;\n                    long new_usize=CurrSize->usize;\n                    if(dim==4)\n                    {\n                        new_tsize=CurrSize->tsize+(int)numberof_new_images;\n                    }\n                    else if(dim==5)\n                    {\n                        new_usize=CurrSize->usize+(int)numberof_new_images;\n                    }\n                    else{\n                        cout<< \"ERROR: dim has to be 4 or 5\"<<endl;\n                        return 1;\n                    }\n\n\n                    delete [] bufferImages[current_buffer?0:1];\n                    bufferImages[current_buffer?0:1]= new SegPrecisionTYPE [CurrSize->numel*(new_tsize*new_usize)];\n\n                    for(long index=0; index<(CurrSize->numel*(old_tsize*old_usize)); index++)\n                        bufferImages[current_buffer?0:1][index]=bufferImages[current_buffer][index];\n\n                    delete [] bufferImages[current_buffer];\n                    bufferImages[current_buffer]= new SegPrecisionTYPE [CurrSize->numel*(new_tsize*new_usize)];\n\n                    for(long index=0; index<(CurrSize->numel*(old_tsize*old_usize)); index++)\n                        bufferImages[current_buffer][index]=bufferImages[current_buffer?0:1][index];\n\n                    current_buffer=current_buffer?0:1;\n\n                    CurrSize->usize=new_usize;\n                    CurrSize->tsize=new_tsize;\n\n                    for(long tp=0; tp<(long)numberof_new_images; tp++)\n                    {\n                        string parser_image_name=argv[++i];\n                        if(parser_image_name.find(string(\".nii\"))>0 || parser_image_name.find(string(\".img\")) ||parser_image_name.find(string(\".hdr\"))>0)\n                        {\n                            nifti_image * NewImage=nifti_image_read(parser_image_name.c_str(),true);\n                            if(NewImage == NULL)\n                            {\n                                cout<< \"ERROR: When reading the image\"<<parser_image_name<<endl;\n                                return 1;\n                            }\n                            if(dim==4){\n                                if(NewImage->nx==InputImage->nx&&NewImage->ny==InputImage->ny&&NewImage->nz==InputImage->nz && NewImage->nt<=1)\n                                {\n                                    if(NewImage->datatype!=DT_FLOAT32)\n                                    {\n                                        seg_changeDatatype<SegPrecisionTYPE>(NewImage);\n                                    }\n                                    SegPrecisionTYPE * NewImagePtr = static_cast<SegPrecisionTYPE *>(NewImage->data);\n                                    for(long index=0; index<(long)CurrSize->numel; index++)\n                                        bufferImages[current_buffer?0:1][index+(old_tsize+tp)*CurrSize->numel]=NewImagePtr[index];\n                                }\n                                else\n                                {\n                                    cout<< \"ERROR: Image \"<<parser_image_name<<\" [nx,ny,nz] do not match or nt>1\"<<endl;\n                                    return 1;\n                                }\n                            }\n                            else if(dim==5){\n                                if(NewImage->nx==InputImage->nx&&NewImage->ny==InputImage->ny&&NewImage->nz==InputImage->nz&&NewImage->nt==InputImage->nt && NewImage->nu<=1)\n                                {\n                                    if(NewImage->datatype!=DT_FLOAT32)\n                                    {\n                                        seg_changeDatatype<SegPrecisionTYPE>(NewImage);\n                                    }\n                                    SegPrecisionTYPE * NewImagePtr = static_cast<SegPrecisionTYPE *>(NewImage->data);\n                                    for(long index=0; index<(long)CurrSize->numel*old_tsize; index++)\n                                        bufferImages[current_buffer?0:1][index+(old_tsize+old_tsize*tp)*CurrSize->numel]=NewImagePtr[index];\n                                }\n                                else\n                                {\n                                    cout<< \"ERROR: Image \"<<parser_image_name<<\" [nx,ny,nz,nt] do not match or nu>1\"<<endl;\n                                    return 1;\n                                }\n                            }\n\n                        }\n                    }\n                    current_buffer=current_buffer?0:1;\n                }\n                else\n                {\n                    cout << \"ERROR: \"<< parser << \" has to be an integer > 0\"<<endl;\n                    i=argc;\n                }\n            }\n            // *********************  merge time points  *************************\n            else if(strcmp(argv[i], \"-subsamp2\") == 0)\n            {\n\n                int newx=(int)floor(CurrSize->xsize/2.0f);\n                int newy=(int)floor(CurrSize->ysize/2.0f);\n                int newz=(int)floor(CurrSize->zsize/2.0f);\n                int newnumel=newx*newy*newz;\n\n\n                for(long tp=0; tp<(long)(CurrSize->tsize*CurrSize->usize); tp++){\n                    //create dummy nii\n                    nifti_image * TMPnii = nifti_copy_nim_info(InputImage);\n                    TMPnii->dim[1]=CurrSize->xsize;\n                    TMPnii->dim[2]=CurrSize->ysize;\n                    TMPnii->dim[3]=CurrSize->zsize;\n                    TMPnii->dim[4]=TMPnii->nt=1;\n                    TMPnii->dim[5]=TMPnii->nu=1;\n                    nifti_update_dims_from_array(TMPnii);\n                    //copy pointer, run gaussian, and set to null\n                    TMPnii->data=static_cast<void*>(&bufferImages[current_buffer][CurrSize->xsize*CurrSize->ysize*CurrSize->zsize*tp]);\n                    GaussianSmoothing5D_nifti(TMPnii,NULL,0.5);\n                    TMPnii->data=NULL;\n                    //As TMPnii->data=NULL, the free will not cause any harm\n                    nifti_image_free(TMPnii);\n                }\n\n                delete [] bufferImages[current_buffer?0:1];\n                bufferImages[current_buffer?0:1]= new SegPrecisionTYPE [newnumel*CurrSize->tsize];\n                Scalling[0]=0.5;\n                Scalling[1]=0.5;\n                Scalling[2]=0.5;\n\n                for(long indexT=0; indexT<CurrSize->tsize; indexT++)\n                    for(long indexZ=0; indexZ<newz; indexZ++)\n                        for(long indexY=0; indexY<newy; indexY++)\n                            for(long indexX=0; indexX<newx; indexX++)\n                                bufferImages[current_buffer?0:1][indexX+indexY*newx+indexZ*newy*newx+indexT*newnumel]=bufferImages[current_buffer][indexX*2+indexY*2*CurrSize->xsize+indexZ*2*CurrSize->xsize*CurrSize->ysize+indexT*CurrSize->numel];\n\n\n\n\n                delete [] bufferImages[current_buffer];\n                bufferImages[current_buffer]= new SegPrecisionTYPE [newnumel*CurrSize->tsize];\n                current_buffer=current_buffer?0:1;\n                CurrSize->xsize=newx;\n                CurrSize->ysize=newy;\n                CurrSize->zsize=newz;\n                CurrSize->numel=newnumel;\n            }\n            // *********************  merge time points  *************************\n            else if(strcmp(argv[i], \"-subsamp2xy\") == 0)\n            {\n\n                int newx=(int)floor(static_cast<float>(CurrSize->xsize)/2.0f);\n                int newy=(int)floor(static_cast<float>(CurrSize->ysize)/2.0f);\n                int newz=(int)floor(static_cast<float>(CurrSize->zsize));\n                int newnumel=newx*newy*newz;\n\n\n                delete [] bufferImages[current_buffer?0:1];\n                bufferImages[current_buffer?0:1]= new SegPrecisionTYPE [newnumel*CurrSize->tsize];\n                Scalling[0]=0.5;\n                Scalling[1]=0.5;\n                Scalling[2]=1;\n\n                for(long indexT=0; indexT<CurrSize->tsize; indexT++)\n                    for(long indexZ=0; indexZ<newz; indexZ++)\n                        for(long indexY=0; indexY<newy; indexY++)\n                            for(long indexX=0; indexX<newx; indexX++)\n                                bufferImages[current_buffer?0:1][indexX+indexY*newx+indexZ*newy*newx+indexT*newnumel]=bufferImages[current_buffer][indexX*2+indexY*2*CurrSize->xsize+indexZ*CurrSize->xsize*CurrSize->ysize+indexT*CurrSize->numel];\n\n\n\n\n                delete [] bufferImages[current_buffer];\n                bufferImages[current_buffer]= new SegPrecisionTYPE [newnumel*CurrSize->tsize];\n                current_buffer=current_buffer?0:1;\n                CurrSize->xsize=newx;\n                CurrSize->ysize=newy;\n                CurrSize->zsize=newz;\n                CurrSize->numel=newnumel;\n            }\n            // *********************  Get max TP  *************************\n            else if(strcmp(argv[i], \"-tmax\") == 0)\n            {\n                for(long i=0; i<CurrSize->numel; i++)\n                {\n                    float tmax=(float)-FLT_MAX;\n                    for(long tp=0; tp<(long)CurrSize->tsize; tp++)\n                    {\n                        if(tmax<bufferImages[current_buffer][i+(long)(tp)*(long)CurrSize->numel])\n                            tmax=bufferImages[current_buffer][i+(long)(tp)*(long)CurrSize->numel];\n                    }\n                    bufferImages[current_buffer?0:1][i]=tmax;\n                }\n                CurrSize->tsize=1;\n                current_buffer=current_buffer?0:1;\n            }\n            // *********************  Get TP with maxval  *************************\n            else if(strcmp(argv[i], \"-tpmax\") == 0)\n            {\n                for(long i=0; i<CurrSize->numel; i++)\n                {\n                    float tmax=(float)-FLT_MAX;\n                    float tmaxindex=-1;\n                    for(long tp=0; tp<(long)CurrSize->tsize; tp++)\n                    {\n                        if(bufferImages[current_buffer][i+(long)(tp)*(long)CurrSize->numel]>tmax)\n                        {\n                            tmax=bufferImages[current_buffer][i+(long)(tp)*(long)CurrSize->numel];\n                            tmaxindex=(float)tp;\n                        }\n                    }\n                    bufferImages[current_buffer?0:1][i]=(float)tmaxindex;\n                }\n                InputImage->cal_max=CurrSize->tsize;\n                CurrSize->tsize=1;\n\n                current_buffer=current_buffer?0:1;\n            }\n            // *********************  Get mean TP  *************************\n            else if(strcmp(argv[i], \"-tmean\") == 0)\n            {\n                for(long i=0; i<CurrSize->numel; i++)\n                {\n                    float tmean=0;\n                    for(long tp=0; tp<(long)CurrSize->tsize; tp++)\n                    {\n                        tmean+=bufferImages[current_buffer][i+(long)(tp)*CurrSize->numel];\n                    }\n                    bufferImages[current_buffer?0:1][i]=tmean/CurrSize->tsize;\n                }\n                CurrSize->tsize=1;\n                current_buffer=current_buffer?0:1;\n            }\n            // *********************  Get min TP  *************************\n            else if(strcmp(argv[i], \"-tmin\") == 0)\n            {\n                for(long i=0; i<CurrSize->numel; i++)\n                {\n                    float tmin=(float)FLT_MAX;\n                    for(long tp=0; tp<CurrSize->tsize; tp++)\n                    {\n                        if(tmin>bufferImages[current_buffer][i+(int)(tp)*CurrSize->numel])\n                            tmin=bufferImages[current_buffer][i+(int)(tp)*CurrSize->numel];\n                    }\n                    bufferImages[current_buffer?0:1][i]=tmin;\n                }\n                CurrSize->tsize=1;\n                current_buffer=current_buffer?0:1;\n            }\n            // *********************  Reset SCL  *************************\n            else if(strcmp(argv[i], \"-scl\") == 0)\n            {\n                InputImage->scl_inter=0;\n                InputImage->scl_slope=1;\n\n            }\n            // *********************  Copy Header  *************************\n            else if(strcmp(argv[i], \"-hdr_copy\") == 0)\n            {\n                string parser=argv[++i];\n\n                nifti_image * NewImage=nifti_image_read(parser.c_str(),true);\n                if(NewImage->datatype!=DT_FLOAT32)\n                {\n                    seg_changeDatatype<SegPrecisionTYPE>(NewImage);\n                }\n                NewImage->nu=(NewImage->nu>1)?NewImage->nu:1;\n                NewImage->nt=(NewImage->nt>1)?NewImage->nt:1;\n                if(NewImage->nu<1)\n                    NewImage->dim[5]=1;\n                if(NewImage->nt<1)\n                    NewImage->dim[4]=1;\n                nifti_update_dims_from_array(NewImage);\n                SegPrecisionTYPE * NewImagePtr = static_cast<SegPrecisionTYPE *>(NewImage->data);\n                if(NewImage->nx==CurrSize->xsize&&NewImage->ny==CurrSize->ysize&&NewImage->nz==CurrSize->zsize&&NewImage->nt==CurrSize->tsize&&NewImage->nu==CurrSize->usize)\n                {\n                    for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize*CurrSize->tsize*CurrSize->usize); i++)\n                        bufferImages[current_buffer?0:1][i]=NewImagePtr[i];\n                    current_buffer=current_buffer?0:1;\n                }\n                else\n                {\n                    cout << \"ERROR: Image \"<< parser << \" is the wrong size  -  original = ( \"<<CurrSize->xsize<<\",\"\n                         <<CurrSize->ysize<<\",\"<<CurrSize->zsize<<\",\"<<CurrSize->tsize<<\",\"<<CurrSize->usize<<\" )  New image = ( \"<<NewImage->nx<<\",\"\n                        <<NewImage->ny<<\",\"<<NewImage->nz<<\",\"<<NewImage->nt<<\",\"<<NewImage->nu<<\" )\"<<endl;\n                    exit(1);\n                    i=argc;\n                }\n                nifti_image_free(NewImage);\n\n            }\n            // *********************  Copy Header  *************************\n            else if(strcmp(argv[i], \"-4to5\") == 0)\n            {\n\n                int tempT=CurrSize->tsize;\n                int tempU=CurrSize->usize;\n\n                 InputImage->dim[4]=InputImage->nt=CurrSize->tsize=tempU;\n                 InputImage->dim[5]=InputImage->nu=CurrSize->usize=tempT;\n\n\n            }\n            // *********************  Get LSSD  *************************\n            else if(strcmp(argv[i], \"-lssd\") == 0)\n            {\n                string parser=argv[++i];\n                nifti_image * NewImage=nifti_image_read(parser.c_str(),true);\n                NewImage->nu=(NewImage->nu>1)?NewImage->nu:1;\n                NewImage->nt=(NewImage->nt>1)?NewImage->nt:1;\n                if(NewImage->datatype!=DT_FLOAT32)\n                {\n                    seg_changeDatatype<SegPrecisionTYPE>(NewImage);\n                }\n                SegPrecisionTYPE * NewImagePtr = static_cast<SegPrecisionTYPE *>(NewImage->data);\n\n                string parserstd=argv[++i];\n                if(strtod(parserstd.c_str(),NULL)>0)\n                {\n                    if(NewImage->nt<2&&NewImage->nx==InputImage->nx&&NewImage->ny==InputImage->ny&&NewImage->nz==InputImage->nz)\n                    {\n                        float * NewImageMean=new float [NewImage->nx*NewImage->ny*NewImage->nz];\n                        float * NewImageStd=new float [NewImage->nx*NewImage->ny*NewImage->nz];\n                        float * InputImageMean=new float [InputImage->nx*InputImage->ny*InputImage->nz];\n                        float * InputImageStd=new float [InputImage->nx*InputImage->ny*InputImage->nz];\n                        float allmeanNew=0;\n                        float allmeanInput=0;\n                        float allstdNew=0;\n                        float allstdInput=0;\n                        for(long index=0; index<InputImage->nx*InputImage->ny*InputImage->nz; index++)\n                        {\n                            allmeanNew+=NewImagePtr[index];\n                            allmeanInput+=bufferImages[current_buffer][index];\n                            NewImageMean[index]=NewImagePtr[index];\n                            NewImageStd[index]=NewImagePtr[index]*NewImagePtr[index];\n                            InputImageMean[index]=bufferImages[current_buffer][index];\n                            InputImageStd[index]=bufferImages[current_buffer][index]*bufferImages[current_buffer][index];\n                        }\n                        allmeanNew=allmeanNew/(InputImage->nx*InputImage->ny*InputImage->nz);\n                        allmeanInput=allmeanInput/(InputImage->nx*InputImage->ny*InputImage->nz);\n\n                        GaussianFilter4D_cArray(NewImageMean,strtod(parserstd.c_str(),NULL),CurrSize);\n                        GaussianFilter4D_cArray(NewImageStd,strtod(parserstd.c_str(),NULL),CurrSize);\n                        GaussianFilter4D_cArray(InputImageMean,strtod(parserstd.c_str(),NULL),CurrSize);\n                        GaussianFilter4D_cArray(InputImageStd,strtod(parserstd.c_str(),NULL),CurrSize);\n                        for(long index=0; index<InputImage->nx*InputImage->ny*InputImage->nz; index++)\n                        {\n                            allstdNew+=(NewImagePtr[index]-allmeanNew)*(NewImagePtr[index]-allmeanNew);\n                            allstdInput+=(bufferImages[current_buffer][index]-allmeanInput)*(bufferImages[current_buffer][index]-allmeanInput);\n                        }\n                        allstdNew=allstdNew/(InputImage->nx*InputImage->ny*InputImage->nz);\n                        allstdInput=allstdInput/(InputImage->nx*InputImage->ny*InputImage->nz);\n                        for(long index=0; index<InputImage->nx*InputImage->ny*InputImage->nz; index++)\n                        {\n                            NewImageStd[index]=NewImageStd[index]-NewImageMean[index]*NewImageMean[index];\n                            InputImageStd[index]=InputImageStd[index]-InputImageMean[index]*InputImageMean[index];\n                            bufferImages[current_buffer?0:1][index]=(bufferImages[current_buffer][index]-InputImageMean[index])/(sqrt(InputImageStd[index]+0.01*allstdInput))-(NewImagePtr[index]-NewImageMean[index])/(sqrt(NewImageStd[index]+0.01*allstdNew));\n                        }\n                        GaussianFilter4D_cArray(bufferImages[current_buffer?0:1],strtod(parserstd.c_str(),NULL),CurrSize);\n                        for(long index=0; index<InputImage->nx*InputImage->ny*InputImage->nz; index++)\n                        {\n                            bufferImages[current_buffer?0:1][index]=bufferImages[current_buffer?0:1][index]*bufferImages[current_buffer?0:1][index];\n                        }\n\n                        current_buffer=current_buffer?0:1;\n                        delete [] NewImageMean;\n                        delete [] NewImageStd;\n                        delete [] InputImageMean;\n                        delete [] InputImageStd;\n                    }\n                    else\n                    {\n                        cout << \"ERROR: Image \"<< parser << \" is the wrong size  -  original = ( \"<<CurrSize->xsize<<\",\"\n                             <<CurrSize->ysize<<\",\"<<CurrSize->zsize<<\",\"<<CurrSize->tsize<<\",\"<<CurrSize->usize<<\" )  New image = ( \"<<NewImage->nx<<\",\"\n                            <<NewImage->ny<<\",\"<<NewImage->nz<<\",\"<<NewImage->nt<<\",\"<<NewImage->nu<<\" )\"<<endl;\n                        i=argc;\n                    }\n                }\n            }\n            // *********************  Get LNCC  *************************\n            else if(strcmp(argv[i], \"-lncc\") == 0)\n            {\n                string parser=argv[++i];\n                nifti_image * NewImage=nifti_image_read(parser.c_str(),true);\n                NewImage->nu=(NewImage->nu>1)?NewImage->nu:1;\n                NewImage->nt=(NewImage->nt>1)?NewImage->nt:1;\n                if(NewImage->datatype!=DT_FLOAT32)\n                {\n                    seg_changeDatatype<float>(NewImage);\n                }\n                SegPrecisionTYPE * NewImagePtr = static_cast<SegPrecisionTYPE *>(NewImage->data);\n\n                string parserstd=argv[++i];\n                if(strtod(parserstd.c_str(),NULL))\n                {\n                    if(NewImage->nt<2&&NewImage->nx==InputImage->nx&&NewImage->ny==InputImage->ny&&NewImage->nz==InputImage->nz)\n                    {\n                        float * NewImageMean=new float [NewImage->nx*NewImage->ny*NewImage->nz];\n                        float * NewImageStd=new float [NewImage->nx*NewImage->ny*NewImage->nz];\n                        float * InputImageMean=new float [InputImage->nx*InputImage->ny*InputImage->nz];\n                        float * InputImageStd=new float [InputImage->nx*InputImage->ny*InputImage->nz];\n                        float allmeanNew=0;\n                        float allmeanInput=0;\n                        float allstdNew=0;\n                        float allstdInput=0;\n                        for(long index=0; index<InputImage->nx*InputImage->ny*InputImage->nz; index++)\n                        {\n                            if(!isnan(NewImagePtr[index]) && !isnan(bufferImages[current_buffer][index])){\n                            allmeanNew+=NewImagePtr[index];\n                            NewImageMean[index]=NewImagePtr[index];\n                            NewImageStd[index]=NewImagePtr[index]*NewImagePtr[index];\n                            allmeanInput+=bufferImages[current_buffer][index];\n                            InputImageMean[index]=bufferImages[current_buffer][index];\n                            InputImageStd[index]=bufferImages[current_buffer][index]*bufferImages[current_buffer][index];\n                            }\n                        }\n                        allmeanNew=allmeanNew/(InputImage->nx*InputImage->ny*InputImage->nz);\n                        allmeanInput=allmeanInput/(InputImage->nx*InputImage->ny*InputImage->nz);\n                        for(long index=0; index<InputImage->nx*InputImage->ny*InputImage->nz; index++)\n                        {\n                            if(!isnan(NewImagePtr[index]) && !isnan(bufferImages[current_buffer][index])){\n                            allstdNew+=(NewImagePtr[index]-allmeanNew)*(NewImagePtr[index]-allmeanNew);\n                            allstdInput+=(bufferImages[current_buffer][index]-allmeanInput)*(bufferImages[current_buffer][index]-allmeanInput);\n                            bufferImages[current_buffer][index]=NewImagePtr[index]*bufferImages[current_buffer][index];\n                            }\n                        }\n                        allstdNew=allstdNew/(InputImage->nx*InputImage->ny*InputImage->nz);\n                        allstdInput=allstdInput/(InputImage->nx*InputImage->ny*InputImage->nz);\n                        cout << allstdInput <<\"  \"<< allstdNew<<endl;\n                        GaussianFilter4D_cArray(bufferImages[current_buffer],strtod(parserstd.c_str(),NULL),CurrSize);\n                        GaussianFilter4D_cArray(NewImageMean,strtod(parserstd.c_str(),NULL),CurrSize);\n                        GaussianFilter4D_cArray(NewImageStd,strtod(parserstd.c_str(),NULL),CurrSize);\n                        GaussianFilter4D_cArray(InputImageMean,strtod(parserstd.c_str(),NULL),CurrSize);\n                        GaussianFilter4D_cArray(InputImageStd,strtod(parserstd.c_str(),NULL),CurrSize);\n                        for(long index=0; index<InputImage->nx*InputImage->ny*InputImage->nz; index++)\n                        {\n                            if(!isnan(NewImagePtr[index]) && !isnan(bufferImages[current_buffer][index])){\n                            NewImageStd[index]=NewImageStd[index]-NewImageMean[index]*NewImageMean[index];\n                            InputImageStd[index]=InputImageStd[index]-InputImageMean[index]*InputImageMean[index];\n                            bufferImages[current_buffer?0:1][index]=(bufferImages[current_buffer][index]-InputImageMean[index]*NewImageMean[index])/(sqrt(NewImageStd[index]*InputImageStd[index])+sqrt(0.01*(allstdNew+allstdInput)));\n                            }\n                            else{\n                                bufferImages[current_buffer?0:1][index]=std::numeric_limits<float>::quiet_NaN();\n                            }\n                        }\n                        current_buffer=current_buffer?0:1;\n                        delete [] NewImageMean;\n                        delete [] NewImageStd;\n                        delete [] InputImageMean;\n                        delete [] InputImageStd;\n                    }\n                    else\n                    {\n                        cout << \"ERROR: Image \"<< parser << \" is the wrong size  -  original = ( \"<<CurrSize->xsize<<\",\"\n                             <<CurrSize->ysize<<\",\"<<CurrSize->zsize<<\",\"<<CurrSize->tsize<<\",\"<<CurrSize->usize<<\" )  New image = ( \"<<NewImage->nx<<\",\"\n                            <<NewImage->ny<<\",\"<<NewImage->nz<<\",\"<<NewImage->nt<<\",\"<<NewImage->nu<<\" )\"<<endl;\n                        i=argc;\n                    }\n                }\n                else\n                {\n                    cout << \"ERROR: \"<< string() << \" is not a float\"<<endl;\n                    i=argc;\n                }\n                nifti_image_free(NewImage);\n            }\n            // ********************* z score ****************************\n\n            else if(strcmp(argv[i], \"-z\") == 0)\n            {\n                for (long tup=0; tup<(CurrSize->tsize*CurrSize->usize); tup++)\n                {\n                    float mean=0;\n                    int img3Dsize=(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize);\n                    for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize); i++)\n                    {\n                        mean+=bufferImages[current_buffer][i+img3Dsize*tup];\n                    }\n                    mean/=(float)(img3Dsize);\n                    float std=0;\n                    for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize); i++)\n                    {\n                        std+=powf((bufferImages[current_buffer][i+img3Dsize*tup]-mean),2);\n                    }\n                    std/=(float)img3Dsize;\n                    std=sqrt(std);\n                    for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize); i++)\n                    {\n                        bufferImages[current_buffer?0:1][i]=(bufferImages[current_buffer][i+img3Dsize*tup]-mean)/std;\n                    }\n                    current_buffer=current_buffer?0:1;\n                }\n            }\n\n            // ********************* z score ****************************\n\n            else if(strcmp(argv[i], \"-zr\") == 0)\n            {\n                string parser=argv[i+1];\n                if(strtod(parser.c_str(),NULL)==0 )\n                {\n                    cout<<\"ERROR: The <float> range in option -P is not a number or is not within the range.\"<<endl;\n                    return 0;\n                }\n                float percentile = atof(argv[++i])/100.0f;\n                percentile=percentile>1?1:percentile;\n                percentile=percentile<0?0:percentile;\n\n\n                for (long tup=0; tup<(CurrSize->tsize*CurrSize->usize); tup++)\n                {\n\n                    long img3Dsize=(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize);\n\n                    float * imgsort=new float [img3Dsize];\n                    long curindex=0;\n                    for(long index=0; index<img3Dsize; index++)\n                    {\n                        imgsort[curindex]=bufferImages[current_buffer][index+img3Dsize*tup];\n                        curindex++;\n                    }\n                    HeapSort(imgsort,img3Dsize-1);\n                    float lowThresh=imgsort[(long)(round(percentile*(img3Dsize-1)))];\n                    float highThresh=imgsort[(long)(round((1-percentile)*(img3Dsize-1)))];\n                    delete [] imgsort;\n\n\n                    float mean=0;\n                    long count=0;\n                    for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize); i++)\n                    {\n                        if(bufferImages[current_buffer][i+img3Dsize*tup]<highThresh && bufferImages[current_buffer][i+img3Dsize*tup]>lowThresh)\n                        {\n                            mean+=bufferImages[current_buffer][i+img3Dsize*tup];\n                            count++;\n                        }\n                    }\n                    mean/=(float)(count);\n                    float std=0;\n                    for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize); i++)\n                    {\n                        if(bufferImages[current_buffer][i+img3Dsize*tup]<highThresh && bufferImages[current_buffer][i+img3Dsize*tup]>lowThresh)\n                        {\n                            std+=powf((bufferImages[current_buffer][i+img3Dsize*tup]-mean),2);\n                        }\n                    }\n                    std/=(float)(count);\n                    std=sqrt(std);\n                    for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize); i++)\n                    {\n                        bufferImages[current_buffer?0:1][i]=(bufferImages[current_buffer][i+img3Dsize*tup]-mean)/std;\n                    }\n                    current_buffer=current_buffer?0:1;\n                }\n            }\n\n            else if(strcmp(argv[i], \"-flipNM\") == 0) // Neuromorphometric Lab Flip for version 3\n            {\n                for(long i=0; i<(long)(CurrSize->xsize*CurrSize->ysize*CurrSize->zsize); i++)\n                {\n                    switch((int)floor(bufferImages[current_buffer][i])){\n                    case 0: bufferImages[current_buffer?0:1][i]=0; break; break; // Background and skull\n                    case 1: bufferImages[current_buffer?0:1][i]=1; break; // NonBrain Low\n                    case 2: bufferImages[current_buffer?0:1][i]=2; break; // NonBrain Mid\n                    case 3: bufferImages[current_buffer?0:1][i]=3; break; // NonBrain High\n                    case 4: bufferImages[current_buffer?0:1][i]=4; break; // Non-ventricular CSF\n                    case 5: bufferImages[current_buffer?0:1][i]=5; break; // 3rd Ventricle\n                    case 12: bufferImages[current_buffer?0:1][i]=12; break; // 4th Ventricle\n                    case 16: bufferImages[current_buffer?0:1][i]=16; break; // 5th Ventricle\n                    case 24: bufferImages[current_buffer?0:1][i]=31; break; // Right to Left Accumbens Area\n                    case 31: bufferImages[current_buffer?0:1][i]=24; break; // Left to Right Accumbens Area\n                    case 32: bufferImages[current_buffer?0:1][i]=33; break; // Right to Left Amygdala\n                    case 33: bufferImages[current_buffer?0:1][i]=32; break; // Left to Right Amygdala\n                    case 35: bufferImages[current_buffer?0:1][i]=35; break; // Pons\n                    case 36: bufferImages[current_buffer?0:1][i]=36; break; // Brain Stem\n                    case 37: bufferImages[current_buffer?0:1][i]=38; break; // Right to Left Caudate\n                    case 38: bufferImages[current_buffer?0:1][i]=37; break; // Left to Right Caudate\n                    case 39: bufferImages[current_buffer?0:1][i]=40; break; // Right to Left Cerebellum Exterior\n                    case 40: bufferImages[current_buffer?0:1][i]=39; break; // Left to Right Cerebellum Exterior\n                    case 41: bufferImages[current_buffer?0:1][i]=42; break; // Right to Left Cerebellum White Matter\n                    case 42: bufferImages[current_buffer?0:1][i]=41; break; // Left to Right Cerebellum White Matter\n                    case 43: bufferImages[current_buffer?0:1][i]=44; break; // Right to Left Cerebral Exterior\n                    case 44: bufferImages[current_buffer?0:1][i]=43; break; // Left to Right Cerebral Exterior\n\n                    case 47: bufferImages[current_buffer?0:1][i]=47; break; // 3rd Ventricle (Posterior part)\n                    case 48: bufferImages[current_buffer?0:1][i]=49; break; // Right to Left Hippocampus\n                    case 49: bufferImages[current_buffer?0:1][i]=48; break; // Left to Right Hippocampus\n                    case 50: bufferImages[current_buffer?0:1][i]=51; break; // Right to Left Inf Lat Vent\n                    case 51: bufferImages[current_buffer?0:1][i]=50; break; // Left to Right Inf Lat Vent\n                    case 52: bufferImages[current_buffer?0:1][i]=53; break; // Right to Left Lateral Ventricle\n                    case 53: bufferImages[current_buffer?0:1][i]=52; break; // Left to Right Lateral Ventricle\n\n                    case 54: bufferImages[current_buffer?0:1][i]=55; break; // Right to Left Lesion\n                    case 55: bufferImages[current_buffer?0:1][i]=54; break; // Left to Right Lesion\n\n                    case 56: bufferImages[current_buffer?0:1][i]=57; break; // Right to Left Pallidum\n                    case 57: bufferImages[current_buffer?0:1][i]=56; break; // Left to Right Pallidum\n                    case 58: bufferImages[current_buffer?0:1][i]=59; break; // Right to Left Putamen\n                    case 59: bufferImages[current_buffer?0:1][i]=58; break; // Left to Right Putamen\n                    case 60: bufferImages[current_buffer?0:1][i]=61; break; // Right to Left Thalamus Proper\n                    case 61: bufferImages[current_buffer?0:1][i]=60; break; // Left to Right Thalamus Proper\n                    case 62: bufferImages[current_buffer?0:1][i]=63; break; // Right to Left Ventral DC\n                    case 63: bufferImages[current_buffer?0:1][i]=62; break; // Left to Right Ventral DC\n                    case 64: bufferImages[current_buffer?0:1][i]=65; break; // Right to Left vessel\n                    case 65: bufferImages[current_buffer?0:1][i]=64; break; // Left to Right vessel\n\n                    case 66: bufferImages[current_buffer?0:1][i]=67; break; // Right to Left Ventricular Lining\n                    case 67: bufferImages[current_buffer?0:1][i]=66; break; // Left to Right Ventricular Lining\n\n                    case 70: bufferImages[current_buffer?0:1][i]=70; break; // Optic Chiasm\n                    case 72: bufferImages[current_buffer?0:1][i]=72; break; // Cerebellar Vermal Lobules I-V\n                    case 73: bufferImages[current_buffer?0:1][i]=73; break; // Cerebellar Vermal Lobules VI-VII\n                    case 74: bufferImages[current_buffer?0:1][i]=74; break; // Cerebellar Vermal Lobules VIII-X\n                    case 77: bufferImages[current_buffer?0:1][i]=76; break; // Right to Left Basal Forebrain\n                    case 76: bufferImages[current_buffer?0:1][i]=77; break; // Left to Right Basal Forebrain\n\n                    case 81: bufferImages[current_buffer?0:1][i]=89; break; // WM region flips\n                    case 82: bufferImages[current_buffer?0:1][i]=90; break;\n                    case 83: bufferImages[current_buffer?0:1][i]=91; break;\n                    case 84: bufferImages[current_buffer?0:1][i]=92; break;\n                    case 85: bufferImages[current_buffer?0:1][i]=93; break;\n                    case 86: bufferImages[current_buffer?0:1][i]=94; break;\n\n                    case 87: bufferImages[current_buffer?0:1][i]=87; break;\n\n                    case 89: bufferImages[current_buffer?0:1][i]=81; break;\n                    case 90: bufferImages[current_buffer?0:1][i]=82; break;\n                    case 91: bufferImages[current_buffer?0:1][i]=83; break;\n                    case 92: bufferImages[current_buffer?0:1][i]=84; break;\n                    case 93: bufferImages[current_buffer?0:1][i]=85; break;\n                    case 94: bufferImages[current_buffer?0:1][i]=86; break;\n\n                    case 96: bufferImages[current_buffer?0:1][i]=97; break; // Right to Left claustrum\n                    case 97: bufferImages[current_buffer?0:1][i]=96; break; // Left to Right claustrum\n\n                    case 101: bufferImages[current_buffer?0:1][i]=102; break; // Right to Left ACgG anterior cingulate gyrus\n                    case 102: bufferImages[current_buffer?0:1][i]=101; break; // Left to Right ACgG anterior cingulate gyrus\n                    case 103: bufferImages[current_buffer?0:1][i]=104; break; // Right to Left AIns anterior insula\n                    case 104: bufferImages[current_buffer?0:1][i]=103; break; // Left to Right AIns anterior insula\n                    case 105: bufferImages[current_buffer?0:1][i]=106; break; // Right to Left AOrG anterior orbital gyrus\n                    case 106: bufferImages[current_buffer?0:1][i]=105; break; // Left to Right AOrG anterior orbital gyrus\n                    case 107: bufferImages[current_buffer?0:1][i]=108; break; // Right to Left AnG angular gyrus\n                    case 108: bufferImages[current_buffer?0:1][i]=107; break; // Left to Right AnG angular gyrus\n                    case 109: bufferImages[current_buffer?0:1][i]=110; break; // Right to Left Calc calcarine cortex\n                    case 110: bufferImages[current_buffer?0:1][i]=109; break; // Left to Right Calc calcarine cortex\n                    case 113: bufferImages[current_buffer?0:1][i]=114; break; // Right to Left CO central operculum\n                    case 114: bufferImages[current_buffer?0:1][i]=113; break; // Left to Right CO central operculum\n                    case 115: bufferImages[current_buffer?0:1][i]=116; break; // Right to Left Cun cuneus\n                    case 116: bufferImages[current_buffer?0:1][i]=115; break; // Left to Right Cun cuneus\n                    case 117: bufferImages[current_buffer?0:1][i]=118; break; // Right to Left Ent entorhinal area\n                    case 118: bufferImages[current_buffer?0:1][i]=117; break; // Left to Right Ent entorhinal area\n                    case 119: bufferImages[current_buffer?0:1][i]=120; break; // Right to Left FO frontal operculum\n                    case 120: bufferImages[current_buffer?0:1][i]=119; break; // Left to Right FO frontal operculum\n                    case 121: bufferImages[current_buffer?0:1][i]=122; break; // Right to Left FRP frontal pole\n                    case 122: bufferImages[current_buffer?0:1][i]=121; break; // Left to Right FRP frontal pole\n                    case 123: bufferImages[current_buffer?0:1][i]=124; break; // Right to Left FuG fusiform gyrus\n                    case 124: bufferImages[current_buffer?0:1][i]=123; break; // Left to Right FuG fusiform gyrus\n                    case 125: bufferImages[current_buffer?0:1][i]=126; break; // Right to Left GRe gyrus rectus\n                    case 126: bufferImages[current_buffer?0:1][i]=125; break; // Left to Right GRe gyrus rectus\n                    case 129: bufferImages[current_buffer?0:1][i]=130; break; // Right to Left IOG inferior occipital gyrus\n                    case 130: bufferImages[current_buffer?0:1][i]=129; break; // Left to Right IOG inferior occipital gyrus\n                    case 133: bufferImages[current_buffer?0:1][i]=134; break; // Right to Left ITG inferior temporal gyrus\n                    case 134: bufferImages[current_buffer?0:1][i]=133; break; // Left to Right ITG inferior temporal gyrus\n                    case 135: bufferImages[current_buffer?0:1][i]=136; break; // Right to Left LiG lingual gyrus\n                    case 136: bufferImages[current_buffer?0:1][i]=135; break; // Left to Right LiG lingual gyrus\n                    case 137: bufferImages[current_buffer?0:1][i]=138; break; // Right to Left LOrG lateral orbital gyrus\n                    case 138: bufferImages[current_buffer?0:1][i]=137; break; // Left to Right LOrG lateral orbital gyrus\n                    case 139: bufferImages[current_buffer?0:1][i]=140; break; // Right to Left MCgG middle cingulate gyrus\n                    case 140: bufferImages[current_buffer?0:1][i]=139; break; // Left to Right MCgG middle cingulate gyrus\n                    case 141: bufferImages[current_buffer?0:1][i]=142; break; // Right to Left MFC medial frontal cortex\n                    case 142: bufferImages[current_buffer?0:1][i]=141; break; // Left to Right MFC medial frontal cortex\n                    case 143: bufferImages[current_buffer?0:1][i]=144; break; // Right to Left MFG middle frontal gyrus\n                    case 144: bufferImages[current_buffer?0:1][i]=143; break; // Left to Right MFG middle frontal gyrus\n                    case 145: bufferImages[current_buffer?0:1][i]=146; break; // Right to Left MOG middle occipital gyrus\n                    case 146: bufferImages[current_buffer?0:1][i]=145; break; // Left to Right MOG middle occipital gyrus\n                    case 147: bufferImages[current_buffer?0:1][i]=148; break; // Right to Left MOrG medial orbital gyrus\n                    case 148: bufferImages[current_buffer?0:1][i]=147; break; // Left to Right MOrG medial orbital gyrus\n                    case 149: bufferImages[current_buffer?0:1][i]=150; break; // Right to Left MPoG postcentral gyrus medial segment\n                    case 150: bufferImages[current_buffer?0:1][i]=149; break; // Left to Right MPoG postcentral gyrus medial segment\n                    case 151: bufferImages[current_buffer?0:1][i]=152; break; // Right to Left MPrG precentral gyrus medial segment\n                    case 152: bufferImages[current_buffer?0:1][i]=151; break; // Left to Right MPrG precentral gyrus medial segment\n                    case 153: bufferImages[current_buffer?0:1][i]=154; break; // Right to Left MSFG superior frontal gyrus medial segment\n                    case 154: bufferImages[current_buffer?0:1][i]=153; break; // Left to Right MSFG superior frontal gyrus medial segment\n                    case 155: bufferImages[current_buffer?0:1][i]=156; break; // Right to Left MTG middle temporal gyrus\n                    case 156: bufferImages[current_buffer?0:1][i]=155; break; // Left to Right MTG middle temporal gyrus\n                    case 157: bufferImages[current_buffer?0:1][i]=158; break; // Right to Left OCP occipital pole\n                    case 158: bufferImages[current_buffer?0:1][i]=157; break; // Left to Right OCP occipital pole\n                    case 161: bufferImages[current_buffer?0:1][i]=162; break; // Right to Left OFuG occipital fusiform gyrus\n                    case 162: bufferImages[current_buffer?0:1][i]=161; break; // Left to Right OFuG occipital fusiform gyrus\n                    case 163: bufferImages[current_buffer?0:1][i]=164; break; // Right to Left OpIFG opercular part of the inferior frontal gyrus\n                    case 164: bufferImages[current_buffer?0:1][i]=163; break; // Left to Right OpIFG opercular part of the inferior frontal gyrus\n                    case 165: bufferImages[current_buffer?0:1][i]=166; break; // Right to Left OrIFG orbital part of the inferior frontal gyrus\n                    case 166: bufferImages[current_buffer?0:1][i]=165; break; // Left to Right OrIFG orbital part of the inferior frontal gyrus\n                    case 167: bufferImages[current_buffer?0:1][i]=168; break; // Right to Left PCgG posterior cingulate gyrus\n                    case 168: bufferImages[current_buffer?0:1][i]=167; break; // Left to Right PCgG posterior cingulate gyrus\n                    case 169: bufferImages[current_buffer?0:1][i]=170; break; // Right to Left PCu precuneus\n                    case 170: bufferImages[current_buffer?0:1][i]=169; break; // Left to Right PCu precuneus\n                    case 171: bufferImages[current_buffer?0:1][i]=172; break; // Right to Left PHG parahippocampal gyrus\n                    case 172: bufferImages[current_buffer?0:1][i]=171; break; // Left to Right PHG parahippocampal gyrus\n                    case 173: bufferImages[current_buffer?0:1][i]=174; break; // Right to Left PIns posterior insula\n                    case 174: bufferImages[current_buffer?0:1][i]=173; break; // Left to Right PIns posterior insula\n                    case 175: bufferImages[current_buffer?0:1][i]=176; break; // Right to Left PO parietal operculum\n                    case 176: bufferImages[current_buffer?0:1][i]=175; break; // Left to Right PO parietal operculum\n                    case 177: bufferImages[current_buffer?0:1][i]=178; break; // Right to Left PoG postcentral gyrus\n                    case 178: bufferImages[current_buffer?0:1][i]=177; break; // Left to Right PoG postcentral gyrus\n                    case 179: bufferImages[current_buffer?0:1][i]=180; break; // Right to Left POrG posterior orbital gyrus\n                    case 180: bufferImages[current_buffer?0:1][i]=179; break; // Left to Right POrG posterior orbital gyrus\n                    case 181: bufferImages[current_buffer?0:1][i]=182; break; // Right to Left PP planum polare\n                    case 182: bufferImages[current_buffer?0:1][i]=181; break; // Left to Right PP planum polare\n                    case 183: bufferImages[current_buffer?0:1][i]=184; break; // Right to Left PrG precentral gyrus\n                    case 184: bufferImages[current_buffer?0:1][i]=183; break; // Left to Right PrG precentral gyrus\n                    case 185: bufferImages[current_buffer?0:1][i]=186; break; // Right to Left PT planum temporale\n                    case 186: bufferImages[current_buffer?0:1][i]=185; break; // Left to Right PT planum temporale\n                    case 187: bufferImages[current_buffer?0:1][i]=188; break; // Right to Left SCA subcallosal area\n                    case 188: bufferImages[current_buffer?0:1][i]=187; break; // Left to Right SCA subcallosal area\n                    case 191: bufferImages[current_buffer?0:1][i]=192; break; // Right to Left SFG superior frontal gyrus\n                    case 192: bufferImages[current_buffer?0:1][i]=191; break; // Left to Right SFG superior frontal gyrus\n                    case 193: bufferImages[current_buffer?0:1][i]=194; break; // Right to Left SMC supplementary motor cortex\n                    case 194: bufferImages[current_buffer?0:1][i]=193; break; // Left to Right SMC supplementary motor cortex\n                    case 195: bufferImages[current_buffer?0:1][i]=196; break; // Right to Left SMG supramarginal gyrus\n                    case 196: bufferImages[current_buffer?0:1][i]=195; break; // Left to Right SMG supramarginal gyrus\n                    case 197: bufferImages[current_buffer?0:1][i]=198; break; // Right to Left SOG superior occipital gyrus\n                    case 198: bufferImages[current_buffer?0:1][i]=197; break; // Left to Right SOG superior occipital gyrus\n                    case 199: bufferImages[current_buffer?0:1][i]=200; break; // Right to Left SPL superior parietal lobule\n                    case 200: bufferImages[current_buffer?0:1][i]=199; break; // Left to Right SPL superior parietal lobule\n                    case 201: bufferImages[current_buffer?0:1][i]=202; break; // Right to Left STG superior temporal gyrus\n                    case 202: bufferImages[current_buffer?0:1][i]=201; break; // Left to Right STG superior temporal gyrus\n                    case 203: bufferImages[current_buffer?0:1][i]=204; break; // Right to Left TMP temporal pole\n                    case 204: bufferImages[current_buffer?0:1][i]=203; break; // Left to Right TMP temporal pole\n                    case 205: bufferImages[current_buffer?0:1][i]=206; break; // Right to Left TrIFG triangular part of the inferior frontal gyrus\n                    case 206: bufferImages[current_buffer?0:1][i]=205; break; // Left to Right TrIFG triangular part of the inferior frontal gyrus\n                    case 207: bufferImages[current_buffer?0:1][i]=208; break; // Right to Left TTG transverse temporal gyrus\n                    case 208: bufferImages[current_buffer?0:1][i]=207; break; // Left to Right TTG transverse temporal gyrus\n\n                    }\n                }\n\n                current_buffer=current_buffer?0:1;\n                for(long indexZ=0; indexZ<CurrSize->zsize; indexZ++)\n                    for(long indexY=0; indexY<CurrSize->ysize; indexY++)\n                        for(long indexX=0; indexX<CurrSize->xsize; indexX++)\n                            bufferImages[current_buffer?0:1][((CurrSize->xsize-1-indexX)+indexY*CurrSize->xsize+indexZ*CurrSize->ysize*CurrSize->xsize)]=bufferImages[current_buffer][indexX+indexY*CurrSize->xsize+indexZ*CurrSize->ysize*CurrSize->xsize];\n\n                current_buffer=current_buffer?0:1;\n\n\n            }\n\n            else if(strcmp(argv[i], \"-fliplab\") == 0)\n            {\n                for(long indexZ=1; indexZ<(CurrSize->zsize-1); indexZ++){\n                    for(long indexY=1; indexY<(CurrSize->ysize-1); indexY++){\n                        for(long indexX=1; indexX<(CurrSize->xsize-1); indexX++){\n                            int indexcur=indexX+indexY*CurrSize->xsize+indexZ*CurrSize->ysize*CurrSize->xsize;\n                            float curval=bufferImages[current_buffer][indexcur];\n                            if(     curval!= 52 &&\n                                    curval!= 53 &&\n                                    curval!= 47 &&\n                                    curval!= 50 &&\n                                    curval!= 51 &&\n                                    curval!= 46 &&\n                                    curval!= 45){\n                                int shiftrealsize=1;\n                                int shiftspacing=1;\n\n                                int stop=0;\n                                for(int shiftz=-shiftrealsize; shiftz<=shiftrealsize; shiftz+=shiftspacing){\n                                    for(int shifty=-shiftrealsize; shifty<=shiftrealsize; shifty+=shiftspacing){\n                                        for(int shiftx=-shiftrealsize; shiftx<=shiftrealsize; shiftx+=shiftspacing){\n                                            int index1=(indexX+shiftx)+CurrSize->xsize*(indexY+shifty)+CurrSize->xsize*CurrSize->ysize*(indexZ+shiftz);\n                                            int index2=(indexX-shiftx)+CurrSize->xsize*(indexY-shifty)+CurrSize->xsize*CurrSize->ysize*(indexZ-shiftz);\n                                            float curval1=bufferImages[current_buffer][index1];\n                                            float curval2=bufferImages[current_buffer][index2];\n                                            if(stop==0 && (fabs(shiftx)+fabs(shifty)+fabs(shiftz))<2 ){\n                                                if(curval1==46){\n                                                    if(curval2==47|| curval2==51|| curval2==53){\n                                                        bufferImages[current_buffer?0:1][indexcur]=46;\n                                                        stop=1;\n                                                    }\n                                                    else{\n                                                        bufferImages[current_buffer?0:1][indexcur]=bufferImages[current_buffer][indexcur];\n\n                                                    }\n\n                                                }\n                                                else if(curval1==45 ){\n                                                    if(curval2==52 || curval2==50 || curval2==47 ){\n                                                        bufferImages[current_buffer?0:1][indexcur]=45;\n                                                        stop=1;\n                                                    }\n                                                    else{\n                                                        bufferImages[current_buffer?0:1][indexcur]=bufferImages[current_buffer][indexcur];\n\n                                                    }\n\n                                                }\n                                                else  if(curval1==47|| curval1==51|| curval1==53){\n                                                    if(curval2==46 ){\n                                                        bufferImages[current_buffer?0:1][indexcur]=46;\n                                                        stop=1;\n                                                    }\n                                                    else{\n                                                        bufferImages[current_buffer?0:1][indexcur]=bufferImages[current_buffer][indexcur];\n\n                                                    }\n\n                                                }\n                                                else if(curval1==52 || curval1==50 || curval1==47 ){\n                                                    if(curval2==45 ){\n                                                        bufferImages[current_buffer?0:1][indexcur]=45;\n                                                        stop=1;\n                                                    }\n                                                    else{\n                                                        bufferImages[current_buffer?0:1][indexcur]=bufferImages[current_buffer][indexcur];\n                                                    }\n\n                                                }\n                                                else{\n                                                    bufferImages[current_buffer?0:1][indexcur]=bufferImages[current_buffer][indexcur];\n\n                                                }\n                                            }\n\n                                        }\n                                    }\n                                }\n\n                            }\n                            else{\n                                bufferImages[current_buffer?0:1][indexX+indexY*CurrSize->xsize+indexZ*CurrSize->ysize*CurrSize->xsize]=bufferImages[current_buffer][indexX+indexY*CurrSize->xsize+indexZ*CurrSize->ysize*CurrSize->xsize];\n\n                            }\n                        }\n                    }\n                }\n\n                current_buffer=current_buffer?0:1;\n\n            }\n            else if(strcmp(argv[i], \"-fliplab2\") == 0)\n              {\n                for(long indexZ=1; indexZ<(CurrSize->zsize-1); indexZ++){\n                    for(long indexY=1; indexY<(CurrSize->ysize-1); indexY++){\n                        for(long indexX=1; indexX<(CurrSize->xsize-1); indexX++){\n                            int indexcur=indexX+indexY*CurrSize->xsize+indexZ*CurrSize->ysize*CurrSize->xsize;\n                            float curval=bufferImages[current_buffer][indexcur];\n                            if( curval==46 || curval== 45){\n                                int shiftrealsize=1;\n                                int shiftspacing=1;\n\n                                int stop=0;\n                                for(int shiftz=-shiftrealsize; shiftz<=shiftrealsize; shiftz+=shiftspacing){\n                                    for(int shifty=-shiftrealsize; shifty<=shiftrealsize; shifty+=shiftspacing){\n                                        for(int shiftx=-shiftrealsize; shiftx<=shiftrealsize; shiftx+=shiftspacing){\n                                            if( stop==0 && (fabs(shiftz)+fabs(shifty)+fabs(shiftx))<2 ){\n\n                                                int index2=(indexX-shiftx)+CurrSize->xsize*(indexY-shifty)+CurrSize->xsize*CurrSize->ysize*(indexZ-shiftz);\n                                                float curval2=bufferImages[current_buffer][index2];\n\n                                                    if(curval2==47|| curval2==51|| curval2==53){\n                                                        bufferImages[current_buffer?0:1][indexcur]=67;\n                                                        stop=1;\n                                                        //cout<<\"hit\"<<endl;\n                                                    }\n                                                    else if(curval2==52 || curval2==50 || curval2==47 ){\n                                                        bufferImages[current_buffer?0:1][indexcur]=66;\n                                                        stop=1;\n                                                        //cout<<\"hat\"<<endl;\n                                                    }\n                                                    else{\n                                                        bufferImages[current_buffer?0:1][indexcur]=bufferImages[current_buffer][indexcur];\n                                                    }\n                                            }\n                                        }\n                                    }\n                                }\n                            }\n\n                            else{\n                                bufferImages[current_buffer?0:1][indexcur]=bufferImages[current_buffer][indexcur];\n\n                            }\n                        }\n                    }\n                }\n\n                  current_buffer=current_buffer?0:1;\n\n              }\n            else if(strcmp(argv[i], \"-flipimgx\") == 0) // X flip image\n            {\n\n                for(long indexZ=0; indexZ<CurrSize->zsize; indexZ++)\n                    for(long indexY=0; indexY<CurrSize->ysize; indexY++)\n                        for(long indexX=1; indexX<(CurrSize->xsize-1); indexX++)\n                            bufferImages[current_buffer?0:1][((CurrSize->xsize-1-indexX)+indexY*CurrSize->xsize+indexZ*CurrSize->ysize*CurrSize->xsize)]=bufferImages[current_buffer][indexX+indexY*CurrSize->xsize+indexZ*CurrSize->ysize*CurrSize->xsize];\n\n                current_buffer=current_buffer?0:1;\n\n            }\n            else if(strcmp(argv[i], \"-flipimgy\") == 0) // Y flip image\n            {\n\n                for(long indexZ=0; indexZ<CurrSize->zsize; indexZ++)\n                    for(long indexY=0; indexY<CurrSize->ysize; indexY++)\n                        for(long indexX=1; indexX<(CurrSize->xsize-1); indexX++)\n                            bufferImages[current_buffer?0:1][((indexX)+(CurrSize->ysize-1-indexY)*CurrSize->xsize+indexZ*CurrSize->ysize*CurrSize->xsize)]=bufferImages[current_buffer][indexX+indexY*CurrSize->xsize+indexZ*CurrSize->ysize*CurrSize->xsize];\n\n                current_buffer=current_buffer?0:1;\n\n            }\n            else if(strcmp(argv[i], \"-flipimgz\") == 0) // Z flip image\n            {\n\n                for(long indexZ=0; indexZ<CurrSize->zsize; indexZ++)\n                    for(long indexY=0; indexY<CurrSize->ysize; indexY++)\n                        for(long indexX=1; indexX<(CurrSize->xsize-1); indexX++)\n                            bufferImages[current_buffer?0:1][((indexX)+indexY*CurrSize->xsize+(CurrSize->zsize-1-indexZ)*CurrSize->ysize*CurrSize->xsize)]=bufferImages[current_buffer][indexX+indexY*CurrSize->xsize+indexZ*CurrSize->ysize*CurrSize->xsize];\n\n                current_buffer=current_buffer?0:1;\n\n            }\n            // *********************  output data type  *************************\n            else if(strcmp(argv[i], \"-v\") == 0)\n            {\n                verbose=1;\n            }\n            else if(strcmp(argv[i], \"-odt\") == 0)\n            {\n                string parser=argv[++i];\n                if(parser.find(\"uchar\")!=string::npos)\n                {\n                    datatypeoutput=NIFTI_TYPE_UINT8;\n                }\n                else if(parser.find(\"ushort\")!=string::npos)\n                {\n                    datatypeoutput=NIFTI_TYPE_UINT16;\n                }\n                else if(parser.find(\"uint\")!=string::npos)\n                {\n                    datatypeoutput=NIFTI_TYPE_UINT32;\n                }\n                else if(parser.find(\"char\")!=string::npos)\n                {\n                    datatypeoutput=NIFTI_TYPE_INT8;\n                }\n                else if(parser.find(\"short\")!=string::npos)\n                {\n                    datatypeoutput=NIFTI_TYPE_INT16;\n                }\n                else if(parser.find(\"int\")!=string::npos)\n                {\n                    datatypeoutput=NIFTI_TYPE_INT32;\n                }\n                else if(parser.find(\"float\")!=string::npos)\n                {\n                    datatypeoutput=NIFTI_TYPE_FLOAT32;\n                }\n                else if(parser.find(\"double\")!=string::npos)\n                {\n                    datatypeoutput=NIFTI_TYPE_FLOAT64;\n                }\n                else\n                {\n                    cout << \"ERROR: Datatype \"<< parser << \" is unknown\"<<endl;\n                    i=argc;\n                }\n            }\n#ifdef _GIT_HASH\n            else if( strcmp(argv[i], \"--version\")==0)\n            {\n                printf(\"%s\\n\",_GIT_HASH);\n                return 0;\n            }\n#endif\n            else\n            {\n                cout << \"Option \"<< string(argv[i]) << \" unkown\"<<endl;\n                i=argc;\n                return 0;\n            }\n\n        }\n        string parser=argv[argc-1];\n        if(parser.find(string(\".nii\"))>0 || parser.find(string(\".img\")) ||parser.find(string(\".hdr\"))>0)\n        {\n            // saving output\n            char * filename_out=argv[argc-1];\n            nifti_image * OutputImage = nifti_copy_nim_info(InputImage);\n            OutputImage->datatype=datatypeoutput;\n            nifti_set_filenames(OutputImage,filename_out,0,0);\n            OutputImage->dim[1]=OutputImage->nx=CurrSize->xsize;\n            OutputImage->dim[2]=OutputImage->ny=CurrSize->ysize;\n            OutputImage->dim[3]=OutputImage->nz=CurrSize->zsize;\n            OutputImage->dim[4]=OutputImage->nt=CurrSize->tsize;\n            OutputImage->dim[5]=OutputImage->nu=CurrSize->usize;\n            OutputImage->dim[6]=OutputImage->nv=1;\n            OutputImage->dim[7]=OutputImage->nw=1;\n            OutputImage->dim[0]=2;\n            OutputImage->dim[0]=(OutputImage->dim[3]>1?3:OutputImage->dim[0]);\n            OutputImage->dim[0]=(OutputImage->dim[4]>1?4:OutputImage->dim[0]);\n            OutputImage->dim[0]=(OutputImage->dim[5]>1?5:OutputImage->dim[0]);\n            OutputImage->dim[0]=(OutputImage->dim[6]>1?6:OutputImage->dim[0]);\n            OutputImage->dim[0]=(OutputImage->dim[7]>1?7:OutputImage->dim[0]);\n\n            //mat44 *affineTransformation = (mat44 *)calloc(1,sizeof(mat44));\n            bool scalingdiff=false;\n            for(long i=0; i<4; i++)\n            {\n                OutputImage->sto_xyz.m[i][i]/=Scalling[i];\n                OutputImage->pixdim[i+1]/=Scalling[i];\n                if(Scalling[i]!=1)\n                {\n                    scalingdiff=true;\n                }\n            }\n            if(scalingdiff)\n            {\n\n                cout << \"A scaling factor is present. Removing Sform\"<<endl;\n                OutputImage->sform_code=0;\n            }\n            //        OutputImage->qoffset_x=translation[0];\n            //        OutputImage->qoffset_y=translation[1];\n            //        OutputImage->qoffset_z=translation[2];\n\n\n            if(verbose)\n            {\n                cout << \"Output Dim = [ \";\n                for(long i=0; i<8; i++)\n                {\n                    cout<<(float)OutputImage->dim[i];\n                    if(i<7)\n                    {\n                        cout<<\" , \";\n                    }\n                }\n                cout<<\" ] \"<<endl;\n                flush(cout);\n            }\n            nifti_update_dims_from_array(OutputImage);\n            nifti_datatype_sizes(OutputImage->datatype,&OutputImage->nbyper,&OutputImage->swapsize);\n            if(datatypeoutput==NIFTI_TYPE_UINT8)\n            {\n                OutputImage->data = (void *) calloc(CurrSize->numel*CurrSize->tsize*CurrSize->usize, sizeof(unsigned char));\n                unsigned char * OutputImagePtr = static_cast<unsigned char *>(OutputImage->data);\n                for(long i=0; i<(long)(CurrSize->numel*CurrSize->tsize*CurrSize->usize); i++)\n                {\n                    OutputImagePtr[i]=(unsigned char)round(bufferImages[current_buffer][i]);\n                }\n            }\n            else if(datatypeoutput==NIFTI_TYPE_UINT16)\n            {\n                OutputImage->data = (void *) calloc(OutputImage->nvox, sizeof(unsigned short));\n                unsigned short * OutputImagePtr = static_cast<unsigned short *>(OutputImage->data);\n                for(long i=0; i<(long)(CurrSize->numel*CurrSize->tsize*CurrSize->usize); i++)\n                {\n                    OutputImagePtr[i]=(unsigned short)round(bufferImages[current_buffer][i]);\n                }\n            }\n            else if(datatypeoutput==NIFTI_TYPE_UINT32)\n            {\n                OutputImage->data = (void *) calloc(CurrSize->numel*CurrSize->tsize*CurrSize->usize, sizeof(unsigned int));\n                unsigned int * OutputImagePtr = static_cast<unsigned int *>(OutputImage->data);\n                for(long i=0; i<(long)(CurrSize->numel*CurrSize->tsize*CurrSize->usize); i++)\n                {\n                    OutputImagePtr[i]=(unsigned int)round(bufferImages[current_buffer][i]);\n                }\n            }\n            else if(datatypeoutput==NIFTI_TYPE_INT8)\n            {\n                OutputImage->data = (void *) calloc(CurrSize->numel*CurrSize->tsize*CurrSize->usize, sizeof(char));\n                char * OutputImagePtr = static_cast<char *>(OutputImage->data);\n                for(long i=0; i<(long)(CurrSize->numel*CurrSize->tsize*CurrSize->usize); i++)\n                {\n                    OutputImagePtr[i]=(char)round(bufferImages[current_buffer][i]);\n                }\n            }\n            else if(datatypeoutput==NIFTI_TYPE_INT16)\n            {\n                OutputImage->data = (void *) calloc(CurrSize->numel*CurrSize->tsize*CurrSize->usize, sizeof(short));\n                short * OutputImagePtr = static_cast<short *>(OutputImage->data);\n                for(long i=0; i<(long)(CurrSize->numel*CurrSize->tsize*CurrSize->usize); i++)\n                {\n                    OutputImagePtr[i]=(short)round(bufferImages[current_buffer][i]);\n                }\n            }\n            else if(datatypeoutput==NIFTI_TYPE_INT32)\n            {\n                OutputImage->data = (void *) calloc(CurrSize->numel*CurrSize->tsize*CurrSize->usize, sizeof(int));\n                int * OutputImagePtr = static_cast<int *>(OutputImage->data);\n                for(long i=0; i<(long)(CurrSize->numel*CurrSize->tsize*CurrSize->usize); i++)\n                {\n                    OutputImagePtr[i]=(int)round(bufferImages[current_buffer][i]);\n                }\n            }\n            else if(datatypeoutput==NIFTI_TYPE_FLOAT32)\n            {\n                OutputImage->data = (void *) calloc(CurrSize->numel*CurrSize->tsize*CurrSize->usize, sizeof(float));\n                float * OutputImagePtr = static_cast<float *>(OutputImage->data);\n                for(long i=0; i<(long)(CurrSize->numel*CurrSize->tsize*CurrSize->usize); i++)\n                {\n                    OutputImagePtr[i]=(float)bufferImages[current_buffer][i];\n                }\n            }\n            else if(datatypeoutput==NIFTI_TYPE_FLOAT64)\n            {\n                OutputImage->data = (void *) calloc(CurrSize->numel*CurrSize->tsize*CurrSize->usize, sizeof(double));\n                double * OutputImagePtr = static_cast<double *>(OutputImage->data);\n                for(long i=0; i<(long)(CurrSize->numel*CurrSize->tsize*CurrSize->usize); i++)\n                {\n                    OutputImagePtr[i]=(double)round(bufferImages[current_buffer][i]);\n                }\n            }\n            nifti_image_write(OutputImage);\n            nifti_image_free(OutputImage);\n        }\n\n        delete [] bufferImages[0];\n        delete [] bufferImages[1];\n        delete [] bufferImages;\n        delete [] CurrSize;\n\n    }\n\n    catch(std::exception & e)\n    {\n        std::cerr << \"Standard exception: \" << e.what() << std::endl;\n    }\n\n    catch(...)\n    {\n        std::cerr << \"Unhandled Exception: Something went wrong! Please report the error to mjorgecardoso\"<<(char) 64<<\"gmail.com\" << std::endl;\n    }\n    return 0;\n}\n\n", "meta": {"hexsha": "1bd8b341cd38114edd8fb826ccead5f8f9ba25f1", "size": 183021, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "seg-apps/seg_maths.cpp", "max_stars_repo_name": "0rC0/niftyseg", "max_stars_repo_head_hexsha": "40c5061188d0601b9b8d0f7494f6bf0022aa7abd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "seg-apps/seg_maths.cpp", "max_issues_repo_name": "0rC0/niftyseg", "max_issues_repo_head_hexsha": "40c5061188d0601b9b8d0f7494f6bf0022aa7abd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "seg-apps/seg_maths.cpp", "max_forks_repo_name": "0rC0/niftyseg", "max_forks_repo_head_hexsha": "40c5061188d0601b9b8d0f7494f6bf0022aa7abd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 56.0039779682, "max_line_length": 257, "alphanum_fraction": 0.4778194852, "num_tokens": 43094, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.478767489485639}}
{"text": "#include \"global_variables.h\"\n#include \"domain_geometry.h\"\n#include <boost/algorithm/string/replace.hpp>\n#include <boost/filesystem.hpp>\n#include <sstream>\n\nusing namespace boost::filesystem;\nusing namespace std;\n\nglobal_variables::global_variables()\n{\n    //ctor\n}\n\nglobal_variables::~global_variables()\n{\n    //dtor\n}\n\nvoid global_variables::initialise(domain_geometry domain,initial_conditions initial_conds){\n    //tau = 0.5 + viscosity / dt/ gamma\n    // viscosity = MA/root(3) /Re\n     std::ostringstream s;\n     visc =  max_velocity * domain.ref_length/reynolds_number;\n\n     tau = 3*visc/domain.dt + 0.5;  // non-dimensional dt is 1 here\n//    tau = 0.5 + initial_conds.average_rho*max_velocity*3/reynolds_number *\n//                domain.Y/domain.dt*pre_conditioned_gamma;\n    knudsen_number = max_velocity *sqrt(3) / reynolds_number;\n\n\tif (testcase == 8) {\n\t\ttau = 0.5;\n\t\tvisc = 0.0;\n\t}\n\n\n    s << \"RE_\" << reynolds_number << \" N_CELLS_Y\" << domain.Y << \" N_CELLS_x\" << domain.X <<\n                    \" MA_\" << max_velocity *sqrt(3)/scale << \" dt_\" << domain.dt\n                    << \" DT_\" << time_marching_step << \" wom_ \" << womersley_no;\n    simulation_name = s.str();\n    boost::replace_all(simulation_name,\".\",\"_\");\n    output_file = create_output_directory();\n    simulation_length = simulation_length *scale;\n    ref_rho = initial_conds.average_rho;\n\n    if( preconditioning == \"true\"){\n\t\tpreconditioning_active = true;\n\t\tif (fabs(pre_conditioned_gamma - 1) < 0.00001) {\n\t\t\tpre_conditioned_gamma = max_velocity * 2.0 *sqrt(3);\n\t\t}\n\n        \n\t}\n\telse {\n\t\tpreconditioning_active = false;\n\n\t}\n\n\tif (time_stepping == \"local\") {\n\t\tgpu_time_stepping = 1;\n\t}\n\telse if (time_stepping == \"constant\") {\n\t\tgpu_time_stepping = 2;\n\t}\n\telse if (time_stepping == \"min\") {\n\t\tgpu_time_stepping = 3;\n\t}\n\n\n\n}\nvoid global_variables::update_visc(double y){\n\n    visc =  max_velocity * y/reynolds_number;\n}\nvoid global_variables::update_coarse_tau(){\n\n    tau = tau/2.0;\n}\n\nvoid global_variables::update_fine_tau(){\n\n    tau = tau*2.0;\n}\n\nvoid global_variables::update_tau( domain_geometry domain){\n     tau = 0.5 + max_velocity/reynolds_number * ceil(domain.Y /domain.dt) *pre_conditioned_gamma;\n\n}\nvoid global_variables::magnify_time_step( ){\n     time_marching_step = time_marching_step * 2;\n\n}\n\nvoid global_variables::reduce_time_step( ){\n     time_marching_step = time_marching_step / 2;\n\n}\nstd::string global_variables::create_output_directory(){\n\n    std::string output_file,plt,ux,vy,max_u, object;\n    std::string folder;\n    std::ostringstream s ,s1,s2,s3,s4,s5;\n    //output_file = \"C:/Users/brendan/Dropbox/PhD/Test Cases/Poiseuille Flow/\";\n\n    output_file = output_file_dir;\n\n    if( simulation_name ==  \"default\"){\n        s << \"tol \" << tolerance << \" RE \" << reynolds_number\n         << \" t \" << time_marching_step << \" gamma \" << pre_conditioned_gamma << \" tau \"\n         << tau << \" wom \" << womersley_no;\n         folder = s.str();\n\n    }else{\n\n        folder = simulation_name;\n\n    }\n\n    //folder.replace(folder.begin(),folder.end(), \".\",  \"_\");\n    boost::system::error_code ec;\n    boost::replace_all(folder, \".\" , \"_\");\n    output_file = output_file + folder;\n\n    boost::filesystem::path dir(output_file);\n    boost::filesystem::create_directories(dir);\n\n    // create plt, uy, vx folders\n    s1 << \"/plt\";\n    plt = output_file + s1.str();\n    boost::filesystem::path dir1(plt);\n    boost::filesystem::create_directories(dir1);\n\n\ts5<< \"/plt/object\";\n\tobject = output_file + s5.str();\n\tboost::filesystem::path dir5(object);\n\tboost::filesystem::create_directories(dir5);\n\n    s1 << \"/grid\";\n    plt = output_file + s1.str();\n    boost::filesystem::path dir4(plt);\n    boost::filesystem::create_directories(dir4);\n\n    // create plt, uy, vx folders\n    s2 << \"/uy\";\n    ux = output_file + s2.str();\n    boost::filesystem::path dir2(ux);\n    boost::filesystem::create_directories(dir2);\n\n    // create plt, uy, vx folders\n    s3 << \"/vx\";\n    vy = output_file + s3.str();\n    boost::filesystem::path dir3(vy);\n    boost::filesystem::create_directories(dir3);\n\n    output_file = output_file;\n    return output_file;\n\n}\n", "meta": {"hexsha": "5c5a25c151ef129bd6c4611f0d69ae2eb71dd743", "size": 4141, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "global_variables.cpp", "max_stars_repo_name": "CHRG-Developer/LBFS-IBM-ADE-SP", "max_stars_repo_head_hexsha": "6a214c48aef26f2c7c865183a3d612d1c8174257", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-07-27T13:14:12.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-27T13:14:12.000Z", "max_issues_repo_path": "global_variables.cpp", "max_issues_repo_name": "CHRG-Developer/LBFS-IBM-ADE-SP", "max_issues_repo_head_hexsha": "6a214c48aef26f2c7c865183a3d612d1c8174257", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "global_variables.cpp", "max_forks_repo_name": "CHRG-Developer/LBFS-IBM-ADE-SP", "max_forks_repo_head_hexsha": "6a214c48aef26f2c7c865183a3d612d1c8174257", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-17T12:48:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T12:48:36.000Z", "avg_line_length": 25.88125, "max_line_length": 97, "alphanum_fraction": 0.6505674958, "num_tokens": 1122, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431679972357831, "lm_q2_score": 0.6442251133170357, "lm_q1q2_score": 0.4787674872328168}}
{"text": "// Author(s): Jan Friso Groote\n// Copyright: see the accompanying file COPYING or copy at\n// https://github.com/mCRL2org/mCRL2/blob/master/COPYING\n//\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//\n/// \\file timed_linearization_test.cpp\n/// \\brief Add your file description here.\n\n#define BOOST_TEST_MODULE timed_linearization_test\n#include <boost/test/included/unit_test.hpp>\n\n#ifndef MCRL2_SKIP_LONG_TESTS\n\n#include \"mcrl2/data/detail/rewrite_strategies.h\"\n#include \"mcrl2/lps/linearise.h\"\n\nusing namespace mcrl2;\nusing namespace mcrl2::lps;\n\ntypedef data::rewriter::strategy rewrite_strategy;\ntypedef std::vector<rewrite_strategy> rewrite_strategy_vector;\n\ndata::data_expression ultimate_delay(const stochastic_action_summand_vector& l)\n{\n  data::data_expression result=data::sort_real::real_(\"0\");\n  for(const stochastic_action_summand& s: l)\n  {\n    if (s.condition()!=data::sort_bool::false_() && s.has_time())\n    {\n      result=data::sort_real::maximum(result, s.multi_action().time());\n    }\n  }\n  return result;\n}\n\ndata::data_expression ultimate_delay(const deadlock_summand_vector& l)\n{\n  data::data_expression result=data::sort_real::real_(\"0\");\n  for(const deadlock_summand& s: l)\n  {\n    BOOST_CHECK(s.has_time());\n    if (s.condition()!=data::sort_bool::false_())\n    {\n      result=data::sort_real::maximum(result, s.deadlock().time());\n    }\n  }\n  return result;\n}\n\nvoid run_linearisation_instance(const std::string& spec,\n                                const t_lin_options& options,\n                                const bool expect_success,\n                                const data::data_expression max_expected_action_ultimate_delay,\n                                const bool check_max_expected_deadlock_ultimate_delay,\n                                const data::data_expression max_expected_deadlock_ultimate_delay)\n{\n  if (expect_success)\n  {\n    lps::stochastic_specification s=linearise(spec, options);\n    data::rewriter r(s.data());\n    data::data_expression max_action_ultimate_delay=r(ultimate_delay(s.process().action_summands()));\n    if (r(data::equal_to(ultimate_delay(s.process().action_summands()),max_expected_action_ultimate_delay))!=data::sort_bool::true_())\n    {\n      std::clog << \"Expected action time does not match:\\n\";\n      std::clog << \"Action time \" << max_action_ultimate_delay << \"\\n\";\n      std::clog << \"Expected maximum delay \" << max_expected_action_ultimate_delay << \"\\n\";\n      BOOST_CHECK(r(data::equal_to(ultimate_delay(s.process().action_summands()),max_expected_action_ultimate_delay))==data::sort_bool::true_());\n    }\n    if (check_max_expected_deadlock_ultimate_delay)\n    {\n      data::data_expression max_deadlock_ultimate_delay=r(ultimate_delay(s.process().deadlock_summands()));\n      if (r(data::equal_to(ultimate_delay(s.process().deadlock_summands()),max_expected_deadlock_ultimate_delay))!=data::sort_bool::true_())\n      {\n        std::clog << \"Expected deadlock time does not match:\\n\";\n        std::clog << \"Deadlock time \" << ultimate_delay(s.process().deadlock_summands()) << \"\\n\";\n        std::clog << \"Expected maximum delay \" << max_expected_deadlock_ultimate_delay << \"\\n\";\n        BOOST_CHECK(r(data::equal_to(ultimate_delay(s.process().deadlock_summands()),max_expected_deadlock_ultimate_delay))==data::sort_bool::true_());\n      }\n    }\n  }\n  else\n  {\n    BOOST_CHECK_THROW(linearise(spec, options), mcrl2::runtime_error);\n  }\n}\n\n// The ultimate delays are the maximum of the ultimate delays over all actions resp. deadlocks\n// not looking at the conditions of the actions or deadlocks.\nvoid run_linearisation_test_case(const std::string& spec,\n                                 const bool expect_success,\n                                 const std::size_t max_expected_action_ultimate_delay_,\n                                 const bool check_max_expected_deadlock_ultimate_delay,\n                                 const std::size_t max_expected_deadlock_ultimate_delay_)\n{\n  // Set various rewrite strategies\n  rewrite_strategy_vector rewrite_strategies = data::detail::get_test_rewrite_strategies(false);\n  const data::data_expression max_expected_action_ultimate_delay=data::sort_real::real_(max_expected_action_ultimate_delay_);\n  const data::data_expression max_expected_deadlock_ultimate_delay=data::sort_real::real_(max_expected_deadlock_ultimate_delay_);\n\n  for (rewrite_strategy_vector::const_iterator i = rewrite_strategies.begin(); i != rewrite_strategies.end(); ++i)\n  {\n    std::clog << std::endl << \"Testing with rewrite strategy \" << *i << std::endl;\n    std::clog << spec << \"\\n\";\n\n    t_lin_options options;\n    options.ignore_time=false;  // Do not ignore time.\n\n    options.rewrite_strategy=*i;\n\n    std::clog << \"  Default options\" << std::endl;\n    run_linearisation_instance(spec, options, expect_success,max_expected_action_ultimate_delay,check_max_expected_deadlock_ultimate_delay,max_expected_deadlock_ultimate_delay);\n\n    std::clog << \"  Linearisation method regular2\" << std::endl;\n    options.lin_method=lmRegular2;\n    run_linearisation_instance(spec, options, expect_success,max_expected_action_ultimate_delay,check_max_expected_deadlock_ultimate_delay,max_expected_deadlock_ultimate_delay);\n\n    std::clog << \"  Linearisation method stack\" << std::endl;\n    options.lin_method=lmStack;\n    run_linearisation_instance(spec, options, expect_success,max_expected_action_ultimate_delay,check_max_expected_deadlock_ultimate_delay,max_expected_deadlock_ultimate_delay);\n\n    std::clog << \"  Linearisation method stack; binary enabled\" << std::endl;\n    options.binary=true;\n    run_linearisation_instance(spec, options, expect_success,max_expected_action_ultimate_delay,check_max_expected_deadlock_ultimate_delay,max_expected_deadlock_ultimate_delay);\n\n    std::clog << \"  Linearisation method regular; binary enabled\" << std::endl;\n    options.lin_method=lmRegular;\n    run_linearisation_instance(spec, options, expect_success,max_expected_action_ultimate_delay,check_max_expected_deadlock_ultimate_delay,max_expected_deadlock_ultimate_delay);\n\n    std::clog << \"  Linearisation method regular; no intermediate clustering\" << std::endl;\n    options.binary=false; // reset binary\n    options.no_intermediate_cluster=true;\n    run_linearisation_instance(spec, options, expect_success,max_expected_action_ultimate_delay,check_max_expected_deadlock_ultimate_delay,max_expected_deadlock_ultimate_delay);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(Check_single_timed_process)\n{\n  const std::string spec =\n    \"act a;\\n\"\n    \"init a@2.delta@10;\\n\"\n    ;\n\n  run_linearisation_test_case(spec,true,2,true,10);\n}\n\nBOOST_AUTO_TEST_CASE(Check_parallel_timed_processes)\n{\n  const std::string spec =\n    \"act a;\\n\"\n    \"init a@2.delta@10 || a@4.delta@10;\\n\"\n    ;\n\n  run_linearisation_test_case(spec,true,4,true,10);\n}\n\nBOOST_AUTO_TEST_CASE(Check_parallel_timed_processes_with_the_same_time)\n{\n  const std::string spec =\n    \"act a;\\n\"\n    \"init a@2.delta@10 || a@2.delta@10;\\n\"\n    ;\n\n  run_linearisation_test_case(spec,true,2,true,10);\n}\n\nBOOST_AUTO_TEST_CASE(Check_parallel_timed_processes_reversed)\n{\n  const std::string spec =\n   \"act a;\\n\"\n   \"init a@5.delta@10 || a@3.delta@10;\\n\"\n   ;\n\n  run_linearisation_test_case(spec,true,5,true,10);\n}\n\nBOOST_AUTO_TEST_CASE(Check_parallel_deltas)\n{\n  const std::string spec =\n    \"init delta@2 || delta@4;\\n\"\n    ;\n\n  run_linearisation_test_case(spec,true,0,true,2);\n}\n\nBOOST_AUTO_TEST_CASE(Check_parallel_deltas_with_the_same_time)\n{\n  const std::string spec =\n    \"init delta@2 || delta@2;\\n\"\n    ;\n\n  run_linearisation_test_case(spec,true,0,true,2);\n}\n\nBOOST_AUTO_TEST_CASE(Check_parallel_action_and_delta_with_the_same_time)\n{\n  const std::string spec =\n    \"act a;\\n\"\n    \"init a@3.delta@10 || delta@3;\";\n    ;\n\n  run_linearisation_test_case(spec,true,0,true,3);\n}\n\nBOOST_AUTO_TEST_CASE(Check_parallel_action_and_delta_with_different_time1)\n{\n  const std::string spec =\n    \"act a;\\n\"\n    \"init a@3.delta@10 || delta@4;\";\n    ;\n\n  run_linearisation_test_case(spec,true,3,true,4);\n}\n\nBOOST_AUTO_TEST_CASE(Check_parallel_action_and_delta_with_different_time2)\n{\n  const std::string spec =\n    \"act a;\\n\"\n    \"init a@4.delta@10 || delta@3;\";\n    ;\n\n  run_linearisation_test_case(spec,true,0,true,3);\n}\n\nBOOST_AUTO_TEST_CASE(Check_terminate)\n{\n  const std::string spec =\n    \"act a;\\n\"\n    \"init a@2;\";\n    ;\n\n  run_linearisation_test_case(spec,true,2,false,0);\n}\n\nBOOST_AUTO_TEST_CASE(Check_terminate_and_parallelism)\n{\n  const std::string spec =\n    \"act a;\\n\"\n    \"init a@2||a@3;\";\n    ;\n\n  run_linearisation_test_case(spec,true,3,false,0);\n}\n\nBOOST_AUTO_TEST_CASE(Check_terminate_and_synchrony)\n{\n  const std::string spec =\n    \"act a;\\n\"\n    \"init a@2||a@2;\";\n    ;\n\n  run_linearisation_test_case(spec,true,2,false,0);\n}\n\nBOOST_AUTO_TEST_CASE(Check_terminate_and_parallelism_deadlock1)\n{\n  const std::string spec =\n    \"act a;\\n\"\n    \"init a@2||delta@3;\";\n    ;\n\n  run_linearisation_test_case(spec,true,2,false,0);  // As it stands, cannot check the the deadlock. Should be \"true,3\".\n}\n\nBOOST_AUTO_TEST_CASE(Check_terminate_and_parallelism_deadlock2)\n{\n  const std::string spec =\n    \"act a;\\n\"\n    \"init a@4||delta@3;\";\n    ;\n\n  run_linearisation_test_case(spec,true,0,false,0);\n}\n\nBOOST_AUTO_TEST_CASE(Check_terminate_and_synchrony_and_deadlock)\n{\n  const std::string spec =\n    \"act a;\\n\"\n    \"init a@2||delta@2;\";\n    ;\n\n  run_linearisation_test_case(spec,true,0,false,0);\n}\n\n#else // ndef MCRL2_SKIP_LONG_TESTS\n\nBOOST_AUTO_TEST_CASE(skip_test)\n{\n}\n\n#endif // ndef MCRL2_SKIP_LONG_TESTS\n\n", "meta": {"hexsha": "4314758f928945ea5fdd88796f2c963dc7fa0883", "size": 9638, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libraries/lps/test/timed_linearization_test.cpp", "max_stars_repo_name": "sdrees/mCRL2", "max_stars_repo_head_hexsha": "bbda4c85022bc21cfa3eab3aafd07e60e89dee2d", "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": "libraries/lps/test/timed_linearization_test.cpp", "max_issues_repo_name": "sdrees/mCRL2", "max_issues_repo_head_hexsha": "bbda4c85022bc21cfa3eab3aafd07e60e89dee2d", "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": "libraries/lps/test/timed_linearization_test.cpp", "max_forks_repo_name": "sdrees/mCRL2", "max_forks_repo_head_hexsha": "bbda4c85022bc21cfa3eab3aafd07e60e89dee2d", "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.6711864407, "max_line_length": 177, "alphanum_fraction": 0.7232828388, "num_tokens": 2384, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743167997235783, "lm_q2_score": 0.6442251133170357, "lm_q1q2_score": 0.47876748723281676}}
{"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 *      130115    R.C.A. Boon       Creation of code (in progress).\n *      130124    R.C.A. Boon       Removed retrograde factor unit test (function no longer exists).\n *      130131    R.C.A. Boon       Improved Kepler to MEE and back test cases, added Cartesian to\n *                                  MEE and back test cases.\n *      130225    D. Dirkx          Added tests for functions that determine retrogradeness for\n *                                  Keplerian to MEE conversions.\n *      130227    D. Dirkx          Replaced ../180.0*PI by convertDegreeToRadians(), added case 7\n *                                  (200 deg inclination) in Kepler to MEE test case.\n *      130301    R.C.A. Boon       Set tolerance from 1e-14 to 2e-14 for MEE to Cartesian tests\n *                                  (due to triple conversions)\n *      130305    R.C.A. Boon       Added validated data for prograde cases in Kepler to MEE (none\n *                                  available for retrograde cases), added e=0 & i=0 case to all\n *                                  conversions, replaced Eigen::VectorXd by basic_mathema-\n *                                  tics::Vector6d.\n *      140221    H.P. Gijsen       added include statements to accomodate the change in location of\n *                                  the indices enum.\n *\n *    References\n *      B. R\u02c6mgens, \"Verified Interval Propagation\" (2011). MSc thesis,\n *          Delft University of Technology.\n *\n *    Notes\n *\n */\n\n#define BOOST_TEST_MAIN\n\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/unit_test.hpp>\n\n#include <Eigen/Core>\n\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/orbitalElementConversions.h\"\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/unitConversions.h\"\n#include \"Tudat/Basics/testMacros.h\"\n#include \"Tudat/Mathematics/BasicMathematics/mathematicalConstants.h\"\n#include \"Tudat/Mathematics/BasicMathematics/basicMathematicsFunctions.h\"\n\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/modifiedEquinoctialElementConversions.h\"\n#include \"Tudat/Mathematics/BasicMathematics/linearAlgebraTypes.h\"\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/stateVectorIndices.h\"\n\nnamespace tudat\n{\nnamespace unit_tests\n{\n\n//! Show the functionality of the unit tests.\nBOOST_AUTO_TEST_SUITE( test_orbital_element_conversions )\n\n//! Unit test for conversion Keplerian orbital elements to modified equinoctial elements.\nBOOST_AUTO_TEST_CASE( testConvertKeplerianToModifiedEquinoctialElements )\n{\n    using namespace orbital_element_conversions;\n    using namespace unit_conversions;\n    using mathematical_constants::PI;\n\n    // Setting fraction tolerance for correctness evaluation\n    double tolerance = 1.0E-14;\n\n    // Initializing default Keplerian orbit\n    basic_mathematics::Vector6d keplerianElements = Eigen::VectorXd::Zero( 6 );\n    keplerianElements( semiMajorAxisIndex ) = 1.0e7;\n    keplerianElements( eccentricityIndex ) = 0.1;\n    keplerianElements( inclinationIndex ) = convertDegreesToRadians( 50.0 );\n    bool avoidSingularity = false;\n    keplerianElements( argumentOfPeriapsisIndex ) = convertDegreesToRadians( 350.0 );\n    keplerianElements( longitudeOfAscendingNodeIndex ) = convertDegreesToRadians( 15.0 );\n    keplerianElements( trueAnomalyIndex ) = convertDegreesToRadians( 10.0 );\n    // Modified equinoctial element vector declaration\n    basic_mathematics::Vector6d expectedModifiedEquinoctialElements\n            = Eigen::VectorXd::Zero( 6 );\n    basic_mathematics::Vector6d computedModifiedEquinoctialElements\n            = Eigen::VectorXd::Zero( 6 );\n\n    // Case 1: Elliptical prograde orbit (default case).\n    {\n        // Default case, so no modification necessary.\n\n        // Expected modified equinoctial elements [m,-,-,-,-,rad].\n        // (Results obtained using code archive B. R\u02c6mgens (2011)).\n        expectedModifiedEquinoctialElements( semiLatusRectumIndex ) = 9900000.0;\n        expectedModifiedEquinoctialElements( fElementIndex ) = 0.09961946980917456;\n        expectedModifiedEquinoctialElements( gElementIndex ) = 0.008715574274765783;\n        expectedModifiedEquinoctialElements( hElementIndex ) = 0.4504186100082874;\n        expectedModifiedEquinoctialElements( kElementIndex ) = 0.1206893028076694;\n        expectedModifiedEquinoctialElements( trueLongitudeIndex ) =\n                basic_mathematics::computeModulo( 6.544984694978736, 2.0 * PI );\n\n        // Compute modified equinoctial elements.\n        basic_mathematics::Vector6d computedModifiedEquinoctialElements =\n                convertKeplerianToModifiedEquinoctialElements( keplerianElements,\n                                                               avoidSingularity );\n\n        // Check if computed modified equinoctial elements match the expected values.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedModifiedEquinoctialElements,\n                                           computedModifiedEquinoctialElements, tolerance );\n\n        // Compute modified equinoctial elements using direct function.\n        computedModifiedEquinoctialElements =\n                convertKeplerianToModifiedEquinoctialElements( keplerianElements );\n\n        // Check if computed modified equinoctial elements match the expected values.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedModifiedEquinoctialElements,\n                                           computedModifiedEquinoctialElements, tolerance );\n    }\n\n    // Case 2: Hyperbolic retrograde orbit.\n    {\n        // Modify Keplerian elements [m,-,rad,rad,rad,rad].\n        keplerianElements( semiMajorAxisIndex ) = -1.0e7;\n        keplerianElements( eccentricityIndex ) = 2.0;\n        keplerianElements( inclinationIndex ) = convertDegreesToRadians( 170.0 );\n        avoidSingularity = true;\n        keplerianElements( trueAnomalyIndex ) = convertDegreesToRadians( 10.0 );\n\n        // Set expected modified equinoctial elements [m,-,-,-,-,rad]. (Results were calculated by\n        // hand).\n        expectedModifiedEquinoctialElements( semiLatusRectumIndex ) = 3.0e7;\n        expectedModifiedEquinoctialElements( fElementIndex )\n                = 1.8126155740732999264851053135086;\n        expectedModifiedEquinoctialElements( gElementIndex )\n                = -0.84523652348139887237395697929546;\n        expectedModifiedEquinoctialElements( hElementIndex )\n                = 0.0845075596072044152327702959491; //Minor error?\n        expectedModifiedEquinoctialElements( kElementIndex )\n                = 0.02264373235107538825570191377426;\n        expectedModifiedEquinoctialElements( trueLongitudeIndex )\n                = 6.0213859193804370403867331512857;\n\n        // Compute modified equinoctial elements.\n        basic_mathematics::Vector6d computedModifiedEquinoctialElements =\n                convertKeplerianToModifiedEquinoctialElements( keplerianElements,\n                                                               avoidSingularity );\n\n        // Check if computed modified equinoctial elements match the expected values.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedModifiedEquinoctialElements,\n                                           computedModifiedEquinoctialElements, tolerance );\n\n        // Compute modified equinoctial elements using direct function.\n        computedModifiedEquinoctialElements =\n                convertKeplerianToModifiedEquinoctialElements( keplerianElements );\n\n        // Check if computed modified equinoctial elements match the expected values.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedModifiedEquinoctialElements,\n                                           computedModifiedEquinoctialElements, tolerance );\n    }\n\n    // Case 3: Parabolic retrograde orbit.\n    {\n        // Set Keplerian elements [m,-,rad,rad,rad,rad].\n        keplerianElements( semiMajorAxisIndex ) = 1.0e7;\n        keplerianElements( eccentricityIndex ) = 1.0;\n        keplerianElements( inclinationIndex ) = convertDegreesToRadians( 170.0 );\n        avoidSingularity = true;\n        keplerianElements( trueAnomalyIndex ) = convertDegreesToRadians( 170.0 );\n\n        // Set expected modified equinoctial elements [m,-,-,-,-,rad]. (Results were calculated by\n        // hand)\n        expectedModifiedEquinoctialElements( semiLatusRectumIndex ) = 1.0e7;\n        expectedModifiedEquinoctialElements( fElementIndex )\n                = 0.90630778703664996324255265675432;\n        expectedModifiedEquinoctialElements( gElementIndex )\n                = -0.42261826174069943618697848964773;\n        expectedModifiedEquinoctialElements( hElementIndex )\n                = 0.0845075596072044152327702959491;\n        expectedModifiedEquinoctialElements( kElementIndex )\n                = 0.02264373235107538825570191377426;\n        expectedModifiedEquinoctialElements( trueLongitudeIndex )\n                = 2.5307274153917778865393516143085;\n\n        // Compute modified equinoctial elements.\n        computedModifiedEquinoctialElements =\n                convertKeplerianToModifiedEquinoctialElements( keplerianElements,\n                                                               avoidSingularity );\n\n        // Check if computed modified equinoctial elements match the expected values.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedModifiedEquinoctialElements,\n                                           computedModifiedEquinoctialElements, tolerance );\n\n        // Compute modified equinoctial elements using direct function.\n        convertKeplerianToModifiedEquinoctialElements( keplerianElements );\n\n        // Check if computed modified equinoctial elements match the expected values.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedModifiedEquinoctialElements,\n                                           computedModifiedEquinoctialElements, tolerance );\n    }\n\n    // Case 4: Circular prograde orbit.\n    {\n        // Set Keplerian elements [m,-,rad,rad,rad,rad].\n        keplerianElements( eccentricityIndex ) = 0.0;\n        keplerianElements( inclinationIndex ) = convertDegreesToRadians( 50.0 );\n        avoidSingularity = false;\n\n        // Expected modified equinoctial elements [m,-,-,-,-,rad].\n        // (Results obtained using code archive B. R\u02c6mgens (2011)).\n        expectedModifiedEquinoctialElements( semiLatusRectumIndex ) = 10000000;\n        expectedModifiedEquinoctialElements( fElementIndex ) = 0;\n        expectedModifiedEquinoctialElements( gElementIndex ) = 0;\n        expectedModifiedEquinoctialElements( hElementIndex ) = 0.4504186100082874;\n        expectedModifiedEquinoctialElements( kElementIndex ) = 0.1206893028076694;\n        expectedModifiedEquinoctialElements( trueLongitudeIndex ) =\n                basic_mathematics::computeModulo( 9.337511498169663, 2.0 * PI );\n\n        // Compute modified equinoctial elements.\n        computedModifiedEquinoctialElements =\n                convertKeplerianToModifiedEquinoctialElements( keplerianElements,\n                                                               avoidSingularity );\n\n        // Check if computed modified equinoctial elements match the expected values.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedModifiedEquinoctialElements,\n                                           computedModifiedEquinoctialElements, tolerance );\n\n        // Compute modified equinoctial elements using direct function.\n        computedModifiedEquinoctialElements =\n                convertKeplerianToModifiedEquinoctialElements( keplerianElements );\n\n        // Check if computed modified equinoctial elements match the expected values.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedModifiedEquinoctialElements,\n                                           computedModifiedEquinoctialElements, tolerance );\n    }\n\n    // Case 5: 0 inclination orbit.\n    {\n        // Set Keplerian elements [m,-,rad,rad,rad,rad].\n        keplerianElements( eccentricityIndex ) = 0.1;\n        keplerianElements( inclinationIndex ) = 0.0;\n        avoidSingularity = false;\n\n        // Expected modified equinoctial elements [m,-,-,-,-,rad].\n        // (Results obtained using code archive B. R\u02c6mgens (2011)).\n        expectedModifiedEquinoctialElements( semiLatusRectumIndex ) = 9900000;\n        expectedModifiedEquinoctialElements( fElementIndex ) = 0.09961946980917456;\n        expectedModifiedEquinoctialElements( gElementIndex ) = 0.008715574274765783;\n        expectedModifiedEquinoctialElements( hElementIndex ) = 0;\n        expectedModifiedEquinoctialElements( kElementIndex ) = 0;\n        expectedModifiedEquinoctialElements( trueLongitudeIndex ) =\n                basic_mathematics::computeModulo( 9.337511498169663, 2.0 * PI );\n\n        // Compute modified equinoctial elements.\n        computedModifiedEquinoctialElements =\n                convertKeplerianToModifiedEquinoctialElements( keplerianElements,\n                                                               avoidSingularity );\n\n        // Check if computed modified equinoctial elements match the expected values.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedModifiedEquinoctialElements,\n                                           computedModifiedEquinoctialElements, tolerance );\n\n        // Compute modified equinoctial elements using direct function.\n        computedModifiedEquinoctialElements =\n                convertKeplerianToModifiedEquinoctialElements( keplerianElements );\n\n        // Check if computed modified equinoctial elements match the expected values.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedModifiedEquinoctialElements,\n                                           computedModifiedEquinoctialElements, tolerance );\n    }\n\n    // Case 6: 180 inclination orbit.\n    {\n        // Set Keplerian elements [m,-,rad,rad,rad,rad].\n        keplerianElements( inclinationIndex ) = PI; // = 180 deg\n        avoidSingularity = true;\n\n        // Set expected modified equinoctial elements [m,-,-,-,-,rad]. (Results were calculated by\n        // hand).\n        expectedModifiedEquinoctialElements( semiLatusRectumIndex ) = 9.9e6;\n        expectedModifiedEquinoctialElements( fElementIndex )\n                = 0.09063077870366499632425526567543;\n        expectedModifiedEquinoctialElements( gElementIndex )\n                = -0.04226182617406994361869784896477;\n        expectedModifiedEquinoctialElements( hElementIndex ) = 0.0;\n        expectedModifiedEquinoctialElements( kElementIndex ) = 0.0;\n        expectedModifiedEquinoctialElements( trueLongitudeIndex )\n                = 2.5307274153917778865393516143085;\n\n        // Compute modified equinoctial elements.\n        computedModifiedEquinoctialElements =\n                convertKeplerianToModifiedEquinoctialElements( keplerianElements,\n                                                               avoidSingularity );\n\n        // Check if computed elements match the expected values.\n        // Because two elements are near-zero, a close fraction/percentage check will fail.\n        // Therefore, 1.0 is added to the elements to avoid this\n        basic_mathematics::Vector6d vectorToAdd\n                = ( basic_mathematics::Vector6d( ) << 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 ).finished( );\n        basic_mathematics::Vector6d expectedModifiedEquinoctialElementsPlusOne =\n                expectedModifiedEquinoctialElements + vectorToAdd;\n        basic_mathematics::Vector6d computedModifiedEquinoctialElementsPlusOne =\n                computedModifiedEquinoctialElements + vectorToAdd;\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedModifiedEquinoctialElementsPlusOne,\n                                           computedModifiedEquinoctialElementsPlusOne, tolerance );\n\n        // Compute modified equinoctial elements using direct function.\n        computedModifiedEquinoctialElements =\n                convertKeplerianToModifiedEquinoctialElements( keplerianElements );\n\n        // Check if computed elements match the expected values.\n        // Because two elements are near-zero, a close fraction/percentage check will fail.\n        // Therefore, 1.0 is added to the elements to avoid this\n        expectedModifiedEquinoctialElementsPlusOne =\n                expectedModifiedEquinoctialElements + vectorToAdd;\n        computedModifiedEquinoctialElementsPlusOne =\n                computedModifiedEquinoctialElements + vectorToAdd;\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedModifiedEquinoctialElementsPlusOne,\n                                           computedModifiedEquinoctialElementsPlusOne, tolerance );\n    }\n\n    // Case 7: 0 eccentricity and inclination orbit.\n    {\n        // Set Keplerian elements [m,-,rad,rad,rad,rad].\n        keplerianElements( eccentricityIndex ) = 0.0;\n        keplerianElements( inclinationIndex ) = 0.0;\n        avoidSingularity = false;\n\n        // Expected modified equinoctial elements [m,-,-,-,-,rad].\n        // (Results obtained using code archive B. R\u02c6mgens (2011)).\n        expectedModifiedEquinoctialElements( semiLatusRectumIndex ) = 10000000;\n        expectedModifiedEquinoctialElements( fElementIndex ) = 0;\n        expectedModifiedEquinoctialElements( gElementIndex ) = 0;\n        expectedModifiedEquinoctialElements( hElementIndex ) = 0;\n        expectedModifiedEquinoctialElements( kElementIndex ) = 0;\n        expectedModifiedEquinoctialElements( trueLongitudeIndex ) =\n                basic_mathematics::computeModulo( 9.337511498169663, 2.0 * PI );\n\n        // Compute modified equinoctial elements.\n        computedModifiedEquinoctialElements =\n                convertKeplerianToModifiedEquinoctialElements( keplerianElements,\n                                                               avoidSingularity );\n\n        // Check if computed elements match the expected values.\n        // Because two elements are near-zero, a close fraction/percentage check will fail.\n        // Therefore, 1.0 is added to the elements to avoid this\n        basic_mathematics::Vector6d vectorToAdd\n                = ( basic_mathematics::Vector6d( ) << 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 ).finished( );\n        basic_mathematics::Vector6d expectedModifiedEquinoctialElementsPlusOne =\n                expectedModifiedEquinoctialElements + vectorToAdd;\n        basic_mathematics::Vector6d computedModifiedEquinoctialElementsPlusOne =\n                computedModifiedEquinoctialElements + vectorToAdd;\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedModifiedEquinoctialElementsPlusOne,\n                                           computedModifiedEquinoctialElementsPlusOne, tolerance );\n\n        // Compute modified equinoctial elements using direct function.\n        computedModifiedEquinoctialElements =\n                convertKeplerianToModifiedEquinoctialElements( keplerianElements );\n\n        // Check if computed elements match the expected values.\n        // Because two elements are near-zero, a close fraction/percentage check will fail.\n        // Therefore, 1.0 is added to the elements to avoid this\n        expectedModifiedEquinoctialElementsPlusOne =\n                expectedModifiedEquinoctialElements + vectorToAdd;\n        computedModifiedEquinoctialElementsPlusOne =\n                computedModifiedEquinoctialElements + vectorToAdd;\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedModifiedEquinoctialElementsPlusOne,\n                                           computedModifiedEquinoctialElementsPlusOne, tolerance );\n    }\n\n    // Case 8: 200 degree inclination orbit, test for error.\n    {\n        keplerianElements( inclinationIndex ) = convertDegreesToRadians( 200.0 );\n        bool isExceptionFound = false;\n\n        // Try to calculate retrogradeness\n        try\n        {\n            computedModifiedEquinoctialElements = convertKeplerianToModifiedEquinoctialElements\n                    ( keplerianElements, avoidSingularity );\n        }\n        // Catch the expected runtime error, and set the boolean flag to true.\n        catch ( std::runtime_error )\n        {\n            isExceptionFound = true;\n        }\n\n        // Check value of flag.\n        BOOST_CHECK( isExceptionFound );\n    }\n}\n\n//! Unit test for conversion modified equinoctial elements to Keplerian orbital elements\nBOOST_AUTO_TEST_CASE( testConvertModifiedEquinoctialToKeplerianElements )\n{\n    /* Used procedure:\n      Because the Kepler to modified equinoctial elements are verified, a subsequent conversion back\n      to Keplerian elements should yield the same outcome as the input Keplerian state. This\n      principle is used for verification.\n     */\n\n    using namespace orbital_element_conversions;\n    using namespace unit_conversions;\n    using mathematical_constants::PI;\n\n    // Setting fraction tolerance for correctness evaluation\n    double tolerance = 1.0E-14;\n\n    // Initializing default Keplerian orbit\n    basic_mathematics::Vector6d expectedKeplerianElements = Eigen::VectorXd::Zero( 6 );\n    expectedKeplerianElements( semiMajorAxisIndex ) = 1.0e7;\n    expectedKeplerianElements( eccentricityIndex ) = 0.1;\n    expectedKeplerianElements( inclinationIndex ) = convertDegreesToRadians( 50.0 );\n    bool avoidSingularity = false;\n    expectedKeplerianElements( argumentOfPeriapsisIndex ) = convertDegreesToRadians( 350.0 );\n    expectedKeplerianElements( longitudeOfAscendingNodeIndex ) = convertDegreesToRadians( 15.0 );\n    expectedKeplerianElements( trueAnomalyIndex ) = convertDegreesToRadians( 170.0 );\n\n    // Declaring computed output vector.\n    basic_mathematics::Vector6d computedKeplerianElements = Eigen::VectorXd::Zero( 6 );\n\n    // Case 1: Elliptical prograde orbit (default case).\n    {\n        // Default case, so no modification necessary.\n\n        // Convert to modified equinoctial elements and back.\n        computedKeplerianElements = convertModifiedEquinoctialToKeplerianElements(\n                    convertKeplerianToModifiedEquinoctialElements( expectedKeplerianElements,\n                                                                   avoidSingularity ),\n                    avoidSingularity );\n\n        // Check if computed Keplerian elements match the expected values.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedKeplerianElements,\n                                           computedKeplerianElements, tolerance );\n    }\n\n    // Case 2: Hyperbolic retrograde orbit.\n    {\n        // Modify Keplerian elements [m,-,rad,rad,rad,rad].\n        expectedKeplerianElements( semiMajorAxisIndex ) = -1.0e7;\n        expectedKeplerianElements( eccentricityIndex ) = 2.0;\n        expectedKeplerianElements( inclinationIndex ) = convertDegreesToRadians( 160.0 );\n        avoidSingularity = true;\n        expectedKeplerianElements( trueAnomalyIndex )\n                = convertDegreesToRadians( 10.0 ); // 170 is above limit\n\n        // Convert to modified equinoctial elements and back.\n        computedKeplerianElements = convertModifiedEquinoctialToKeplerianElements(\n                    convertKeplerianToModifiedEquinoctialElements( expectedKeplerianElements,\n                                                                   avoidSingularity ),\n                    avoidSingularity );\n\n        // Check if computed Keplerian elements match the expected values.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedKeplerianElements,\n                                           computedKeplerianElements, tolerance );\n    }\n\n    // Case 3: Parabolic retrograde orbit.\n    {\n        // Set Keplerian elements [m,-,rad,rad,rad,rad].\n        expectedKeplerianElements( semiMajorAxisIndex ) = 3.678e7;\n        expectedKeplerianElements( eccentricityIndex ) = 1.0;\n        expectedKeplerianElements( inclinationIndex ) = convertDegreesToRadians( 90.0 );\n        avoidSingularity = true;\n\n        // Convert to modified equinoctial elements and back.\n        computedKeplerianElements = convertModifiedEquinoctialToKeplerianElements(\n                    convertKeplerianToModifiedEquinoctialElements( expectedKeplerianElements,\n                                                                   avoidSingularity ),\n                    avoidSingularity );\n\n        // Check if computed Keplerian elements match the expected values.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedKeplerianElements,\n                                           computedKeplerianElements, tolerance );\n    }\n\n    // Case 4: Circular prograde orbit.\n    {\n        // Set Keplerian elements [m,-,rad,rad,rad,rad].\n        expectedKeplerianElements( eccentricityIndex ) = 0.0;\n        expectedKeplerianElements( inclinationIndex ) = convertDegreesToRadians( 70.0 );\n        avoidSingularity = false;\n        expectedKeplerianElements( argumentOfPeriapsisIndex ) = 0.0; // For e = 0, undefined.\n\n        // Convert to modified equinoctial elements and back.\n        computedKeplerianElements = convertModifiedEquinoctialToKeplerianElements(\n                    convertKeplerianToModifiedEquinoctialElements( expectedKeplerianElements,\n                                                                   avoidSingularity ),\n                    avoidSingularity );\n\n        // Check if computed Keplerian elements match the expected values.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedKeplerianElements,\n                                           computedKeplerianElements, tolerance );\n    }\n\n    // Case 5: 0 inclination orbit,\n    {\n        // Set Keplerian elements [m,-,rad,rad,rad,rad].\n        expectedKeplerianElements( eccentricityIndex ) = 0.3;\n        expectedKeplerianElements( inclinationIndex ) = 0.0;\n        avoidSingularity = false;\n        expectedKeplerianElements( longitudeOfAscendingNodeIndex ) = 0.0; // Set to zero as for\n        // non-inclined orbit planes, this parameter is undefined\n\n        // Convert to modified equinoctial elements and back.\n        computedKeplerianElements = convertModifiedEquinoctialToKeplerianElements(\n                    convertKeplerianToModifiedEquinoctialElements( expectedKeplerianElements,\n                                                                   avoidSingularity ),\n                    avoidSingularity );\n\n        // Check if computed Keplerian elements match the expected values.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedKeplerianElements,\n                                           computedKeplerianElements, tolerance );\n    }\n\n    // Case 6: 180 inclination orbit.\n    {\n        // Set Keplerian elements [m,-,rad,rad,rad,rad].\n        expectedKeplerianElements( semiMajorAxisIndex ) = 1.0e10;\n        expectedKeplerianElements( inclinationIndex ) = PI;\n        avoidSingularity = true;\n        expectedKeplerianElements( trueAnomalyIndex ) = convertDegreesToRadians( 240.0 );\n\n        // Convert to modified equinoctial elements and back.\n        computedKeplerianElements = convertModifiedEquinoctialToKeplerianElements(\n                    convertKeplerianToModifiedEquinoctialElements( expectedKeplerianElements,\n                                                                   avoidSingularity ),\n                    avoidSingularity );\n\n        // Check if computed Keplerian elements match the expected values.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedKeplerianElements,\n                                           computedKeplerianElements, tolerance );\n    }\n\n    // Case 7: 0 eccentricity and inclination orbit.\n    {\n        // Set Keplerian elements [m,-,rad,rad,rad,rad].\n        expectedKeplerianElements( eccentricityIndex ) = 0.0;\n        expectedKeplerianElements( inclinationIndex ) = 0.0;\n        avoidSingularity = false;\n\n        // Convert to modified equinoctial elements and back\n        computedKeplerianElements = convertModifiedEquinoctialToKeplerianElements(\n                    convertKeplerianToModifiedEquinoctialElements( expectedKeplerianElements,\n                                                                   avoidSingularity ),\n                    avoidSingularity );\n\n        // Check if computed Keplerian elements match the expected values.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedKeplerianElements,\n                                           computedKeplerianElements, tolerance );\n    }\n}\n\n//! Unit test for conversion of Cartesian to modified equinoctial elements.\nBOOST_AUTO_TEST_CASE( testConvertCartesianElementsToModifiedEquinoctialElements )\n{\n    using namespace orbital_element_conversions;\n    using namespace unit_conversions;\n    using mathematical_constants::PI;\n\n    double tolerance = 1.0E-14;\n\n    basic_mathematics::Vector6d testMEE = Eigen::VectorXd::Zero( 6 );\n    basic_mathematics::Vector6d computedMEE = Eigen::VectorXd::Zero( 6 );\n    basic_mathematics::Vector6d testCartesianElements = Eigen::VectorXd::Zero( 6 );\n\n    // Set default Keplerian elements [m,-,rad,rad,rad,rad].\n    basic_mathematics::Vector6d testKepler = Eigen::VectorXd::Zero( 6 );\n    testKepler( semiMajorAxisIndex ) = 1.0e7;\n    testKepler( eccentricityIndex ) = 0.1;\n    testKepler( inclinationIndex ) = convertDegreesToRadians( 50.0 );\n    bool avoidSingularity = false;\n    testKepler( argumentOfPeriapsisIndex ) = convertDegreesToRadians( 350.0 );\n    testKepler( longitudeOfAscendingNodeIndex ) = convertDegreesToRadians( 15.0 );\n    testKepler( trueAnomalyIndex ) = convertDegreesToRadians( 170.0 );\n\n    double gravitationalParameter = 398600.44e9; // Earth's, but any parameter would do.\n\n    // Case 1: Elliptical prograde orbit.\n    {\n        // Default, so no modification necessary\n\n        // Set expected modified equinoctial elements [m,-,-,-,-,rad]. (Results were calculated by\n        // hand)\n        testMEE( semiLatusRectumIndex ) = 9.9e6;\n        testMEE( fElementIndex )\n                = 0.09961946980917455322950104024739;\n        testMEE( gElementIndex )\n                = 0.00871557427476581735580642708375;\n        testMEE( hElementIndex )\n                = 0.45041861000828740764931177254188;\n        testMEE( kElementIndex )\n                = 0.12068930280766941437578622043344;\n        testMEE( trueLongitudeIndex )\n                = 3.0543261909900767596164588448551;\n\n        // Create starting Cartesian vector through the verified Kepler to Cartesian routine.\n        testCartesianElements = convertKeplerianToCartesianElements( testKepler,\n                                                                     gravitationalParameter );\n\n        // Convert to modified equinoctial elements.\n        computedMEE = convertCartesianToModifiedEquinoctialElements( testCartesianElements,\n                                                                     gravitationalParameter,\n                                                                     avoidSingularity );\n\n        // Compare, because element 2 is quite small, tolerance is less stringent than usual.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( testMEE, computedMEE, 1.0E-13 );\n\n        // Convert to modified equinoctial elements using direct function.\n        computedMEE = convertCartesianToModifiedEquinoctialElements( testCartesianElements,\n                                                                     gravitationalParameter );\n\n        // Compare, because element 2 is quite small, tolerance is less stringent than usual.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( testMEE, computedMEE, 1.0E-13 );\n    }\n\n    // Case 2: Hyperbolic retrograde orbit.\n    {\n        // Set Keplerian elements [m,-,rad,rad,rad,rad].\n        testKepler( semiMajorAxisIndex ) = -1.0e7;\n        testKepler( eccentricityIndex ) = 2.0;\n        testKepler( inclinationIndex ) = convertDegreesToRadians( 170.0 );\n        avoidSingularity = true;\n        testKepler( trueAnomalyIndex ) = convertDegreesToRadians( 10.0 );\n\n        // Set expected modified equinoctial elements [m,-,-,-,-,rad]. (Results were calculated by\n        // hand)\n        testMEE( semiLatusRectumIndex ) = 3.0e7;\n        testMEE( fElementIndex )\n                = 1.8126155740732999264851053135086;\n        testMEE( gElementIndex )\n                = -0.84523652348139887237395697929546;\n        testMEE( hElementIndex )\n                = 0.0845075596072044152327702959491;\n        testMEE( kElementIndex )\n                = 0.02264373235107538825570191377426;\n        testMEE( trueLongitudeIndex )\n                = 6.0213859193804370403867331512857;\n\n        // Create starting Cartesian vector through the verified Kepler to Cartesian routine.\n        testCartesianElements = convertKeplerianToCartesianElements( testKepler,\n                                                                     gravitationalParameter );\n\n        // Convert to modified equinoctial elements.\n        computedMEE = convertCartesianToModifiedEquinoctialElements( testCartesianElements,\n                                                                     gravitationalParameter,\n                                                                     avoidSingularity );\n\n        // Compare.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( testMEE, computedMEE, tolerance );\n\n        // Convert to modified equinoctial elements using direct function.\n        computedMEE = convertCartesianToModifiedEquinoctialElements( testCartesianElements,\n                                                                     gravitationalParameter );\n\n        // Compare.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( testMEE, computedMEE, tolerance );\n    }\n\n    // Case 3: Parabolic retrograde orbit.\n    {\n        // Set Keplerian elements [m,-,rad,rad,rad,rad].\n        testKepler( semiMajorAxisIndex ) = 1.0e7;\n        testKepler( eccentricityIndex ) = 1.0;\n        avoidSingularity = true;\n        testKepler( trueAnomalyIndex ) = convertDegreesToRadians( 170.0 );\n\n        // Set expected modified equinoctial elements [m,-,-,-,-,rad]. (Results were calculated by\n        // hand).\n        testMEE( semiLatusRectumIndex ) = 1.0e7;\n        testMEE( fElementIndex )\n                = 0.90630778703664996324255265675432;\n        testMEE( gElementIndex )\n                = -0.42261826174069943618697848964773;\n        testMEE( hElementIndex )\n                = 0.0845075596072044152327702959491;\n        testMEE( kElementIndex )\n                = 0.02264373235107538825570191377426;\n        testMEE( trueLongitudeIndex )\n                = 2.5307274153917778865393516143085;\n\n        // Create starting Cartesian vector through the verified Kepler to Cartesian routine.\n        testCartesianElements = convertKeplerianToCartesianElements( testKepler,\n                                                                     gravitationalParameter );\n\n        // Convert to modified equinoctial elements.\n        computedMEE = convertCartesianToModifiedEquinoctialElements( testCartesianElements,\n                                                                     gravitationalParameter,\n                                                                     avoidSingularity );\n\n        // Compare.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( testMEE, computedMEE, tolerance );\n\n        // Convert to modified equinoctial elements using direct function.\n        computedMEE = convertCartesianToModifiedEquinoctialElements( testCartesianElements,\n                                                                     gravitationalParameter );\n\n        // Compare.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( testMEE, computedMEE, tolerance );\n    }\n\n    // Case 4: Circular prograde orbit.\n    {\n        // Set Keplerian elements [m,-,rad,rad,rad,rad].\n        testKepler ( eccentricityIndex ) = 0.0;\n        testKepler ( inclinationIndex ) = convertDegreesToRadians( 50.0 );\n        avoidSingularity = false;\n        testKepler ( argumentOfPeriapsisIndex ) = 0.0; // e = 0, so actually undefined\n\n        // Set expected modified equinoctial elements [m,-,-,-,-,rad]. (Results were calculated by\n        // hand).\n        testMEE ( semiLatusRectumIndex ) = 1.0e7;\n        testMEE ( fElementIndex ) = 0.0;\n        testMEE ( gElementIndex ) = 0.0;\n        testMEE ( hElementIndex )\n                = 0.45041861000828740764931177254188;\n        testMEE ( kElementIndex )\n                = 0.12068930280766941437578622043344;\n        testMEE ( trueLongitudeIndex )\n                = 3.2288591161895097173088279217039;\n\n        // Create starting Cartesian vector through the verified Kepler to Cartesian routine.\n        testCartesianElements = convertKeplerianToCartesianElements( testKepler,\n                                                                     gravitationalParameter );\n\n        // Convert to modified equinoctial elements.\n        computedMEE = convertCartesianToModifiedEquinoctialElements( testCartesianElements,\n                                                                     gravitationalParameter,\n                                                                     avoidSingularity );\n\n        // Check if computed elements match the expected values.\n        // Because two elements are near-zero, a close fraction/percentage check will fail.\n        // Therefore, 1.0 is added to the elements to avoid this\n        basic_mathematics::Vector6d vectorToAdd\n                = ( basic_mathematics::Vector6d( ) << 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 ).finished( );\n        basic_mathematics::Vector6d computedMeePlusOne = computedMEE + vectorToAdd;\n        basic_mathematics::Vector6d testMeePlusOne = testMEE + vectorToAdd;\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( computedMeePlusOne, testMeePlusOne, tolerance );\n\n        // Convert to modified equinoctial elements using direct function\n        computedMEE = convertCartesianToModifiedEquinoctialElements( testCartesianElements,\n                                                                     gravitationalParameter );\n\n        // Check if computed elements match the expected values.\n        // Because two elements are near-zero, a close fraction/percentage check will fail.\n        // Therefore, 1.0 is added to the elements to avoid this.\n        computedMeePlusOne = computedMEE + vectorToAdd;\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( computedMeePlusOne, testMeePlusOne, tolerance );\n    }\n\n    // Case 5: 0 inclination orbit.\n    {\n        // Set Keplerian elements [m,-,rad,rad,rad,rad].\n        testKepler ( eccentricityIndex ) = 0.1;\n        testKepler ( inclinationIndex ) = 0.0;\n        avoidSingularity = false;\n        testKepler ( argumentOfPeriapsisIndex ) = convertDegreesToRadians( 260.0 );\n        testKepler ( longitudeOfAscendingNodeIndex ) = convertDegreesToRadians( 0.0 );\n\n        // Set expected modified equinoctial elements [m,-,-,-,-,rad]. (Results were calculated by\n        // hand).\n        testMEE( semiLatusRectumIndex ) = 9.9e6;\n        testMEE( fElementIndex )\n                = -0.01736481776669303488517166267693;\n        testMEE( gElementIndex )\n                = -0.09848077530122080593667430245895;\n        testMEE( hElementIndex ) = 0.0;\n        testMEE( kElementIndex ) = 0.0;\n        testMEE( trueLongitudeIndex )\n                = 1.221730476396030703846583537942;\n\n        // Create starting Cartesian vector through the verified Kepler to Cartesian routine.\n        testCartesianElements = convertKeplerianToCartesianElements( testKepler,\n                                                                     gravitationalParameter );\n\n        // Convert to modified equinoctial elements.\n        computedMEE = convertCartesianToModifiedEquinoctialElements( testCartesianElements,\n                                                                     gravitationalParameter,\n                                                                     avoidSingularity );\n\n        // Check if computed elements match the expected values.\n        // Because two elements are near-zero, a close fraction/percentage check will fail.\n        // Therefore, 1.0 is added to the elements to avoid this.\n        basic_mathematics::Vector6d vectorToAdd\n                = ( basic_mathematics::Vector6d( ) << 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 ).finished( );\n        basic_mathematics::Vector6d computedMeePlusOne = computedMEE + vectorToAdd;\n        basic_mathematics::Vector6d testMeePlusOne = testMEE + vectorToAdd;\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( computedMeePlusOne, testMeePlusOne, tolerance );\n\n        // Convert to modified equinoctial elements using direct function.\n        computedMEE = convertCartesianToModifiedEquinoctialElements( testCartesianElements,\n                                                                     gravitationalParameter );\n\n        // Check if computed elements match the expected values.\n        // Because two elements are near-zero, a close fraction/percentage check will fail.\n        // Therefore, 1.0 is added to the elements to avoid this.\n        computedMeePlusOne = computedMEE + vectorToAdd;\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( computedMeePlusOne, testMeePlusOne, tolerance );\n    }\n\n    // Case 6: 180 inclination orbit.\n    {\n        // Set Keplerian elements [m,-,rad,rad,rad,rad].\n        testKepler( eccentricityIndex ) = 0.1;\n        testKepler( inclinationIndex ) = PI; // = 180 deg\n        avoidSingularity = true;\n        testKepler( argumentOfPeriapsisIndex ) = convertDegreesToRadians( 12.0 );\n        testKepler( trueAnomalyIndex ) = convertDegreesToRadians( 190.0 );\n\n        // Set expected modified equinoctial elements [m,-,-,-,-,rad]. (Results were calculated by\n        // hand).\n        testMEE ( semiLatusRectumIndex ) = 9.9e6;\n        testMEE ( fElementIndex )\n                = 0.09781476007338056379285667478696;\n        testMEE ( gElementIndex )\n                = 0.02079116908177593371017422844051;\n        testMEE ( hElementIndex )\n                = 0.0;\n        testMEE ( kElementIndex )\n                = 0.0;\n        testMEE ( trueLongitudeIndex )\n                = 3.525565089028545745385855352347;\n\n        // Create starting Cartesian vector through the verified Kepler to Cartesian routine.\n        testCartesianElements = convertKeplerianToCartesianElements( testKepler,\n                                                                     gravitationalParameter );\n\n        // Convert to modified equinoctial elements.\n        computedMEE = convertCartesianToModifiedEquinoctialElements( testCartesianElements,\n                                                                     gravitationalParameter,\n                                                                     avoidSingularity );\n\n        // Check if computed elements match the expected values.\n        // Because two elements are near-zero, a close fraction/percentage check will fail.\n        // Therefore, 1.0 is added to the elements to avoid this.\n        basic_mathematics::Vector6d vectorToAdd\n                = ( basic_mathematics::Vector6d( ) << 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 ).finished( );\n        basic_mathematics::Vector6d computedMeePlusOne = computedMEE + vectorToAdd;\n        basic_mathematics::Vector6d testMeePlusOne = testMEE + vectorToAdd;\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( computedMeePlusOne, testMeePlusOne, tolerance );\n\n        // Convert to modified equinoctial elements using direct function.\n        computedMEE = convertCartesianToModifiedEquinoctialElements( testCartesianElements,\n                                                                     gravitationalParameter );\n\n        // Check if computed elements match the expected values.\n        // Because two elements are near-zero, a close fraction/percentage check will fail.\n        // Therefore, 1.0 is added to the elements to avoid this.\n        computedMeePlusOne = computedMEE + vectorToAdd;\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( computedMeePlusOne, testMeePlusOne, tolerance );\n    }\n\n    // Case 7: 0 eccentricity and inclination orbit.\n    {\n        // Set Keplerian elements [m,-,rad,rad,rad,rad].\n        testKepler( eccentricityIndex ) = 0.0;\n        testKepler( inclinationIndex ) = 0.0;\n        avoidSingularity = false;\n\n        // Set expected modified equinoctial elements [m,-,-,-,-,rad]. (Results were calculated by\n        // hand).\n        testMEE ( semiLatusRectumIndex ) = 1.0e7; // Circular\n        testMEE ( fElementIndex ) = 0.0;\n        testMEE ( gElementIndex ) = 0.0;\n        testMEE ( hElementIndex ) = 0.0;\n        testMEE ( kElementIndex ) = 0.0;\n        testMEE ( trueLongitudeIndex )\n                = 3.525565089028545745385855352347;\n\n        // Create starting Cartesian vector through the verified Kepler to Cartesian routine.\n        testCartesianElements = convertKeplerianToCartesianElements( testKepler,\n                                                                     gravitationalParameter );\n\n        // Convert to modified equinoctial elements.\n        computedMEE = convertCartesianToModifiedEquinoctialElements( testCartesianElements,\n                                                                     gravitationalParameter,\n                                                                     avoidSingularity );\n\n        // Check if computed elements match the expected values.\n        // Because two elements are near-zero, a close fraction/percentage check will fail.\n        // Therefore, 1.0 is added to the elements to avoid this.\n        basic_mathematics::Vector6d vectorToAdd\n                = ( basic_mathematics::Vector6d( ) << 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 ).finished( );\n        basic_mathematics::Vector6d computedMeePlusOne = computedMEE + vectorToAdd;\n        basic_mathematics::Vector6d testMeePlusOne = testMEE + vectorToAdd;\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( computedMeePlusOne, testMeePlusOne, tolerance );\n\n        // Convert to modified equinoctial elements using direct function.\n        computedMEE = convertCartesianToModifiedEquinoctialElements( testCartesianElements,\n                                                                     gravitationalParameter );\n\n        // Check if computed elements match the expected values.\n        // Because two elements are near-zero, a close fraction/percentage check will fail.\n        // Therefore, 1.0 is added to the elements to avoid this.\n        computedMeePlusOne = computedMEE + vectorToAdd;\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( computedMeePlusOne, testMeePlusOne, tolerance );\n    }\n}\n\n//! Unit test for conversion of modified equinoctial elements to Cartesian.\nBOOST_AUTO_TEST_CASE( testConvertModifiedEquinoctialToCartesianElements )\n{\n    /* Used procedure:\n      The Cartesian expected outcome is computed from the verified Kepler to Cartesian conversion.\n      Subsequently, the Kepler state is converted to modified equinoctial elements and then\n      converted back to Cartesian elements. Outcomes are compared.\n     */\n\n    using namespace orbital_element_conversions;\n    using namespace unit_conversions;\n    using mathematical_constants::PI;\n\n    // Tolerance precision: two orders higher than machine due to three conversions being applied\n    // (accumulation of error) in order to save on manual labor.\n    double tolerance = 2.0E-14;\n\n    basic_mathematics::Vector6d intermediateModifiedEquinoctialElements\n            = Eigen::VectorXd::Zero( 6 );\n    basic_mathematics::Vector6d expectedCartesianElements = Eigen::VectorXd::Zero( 6 );\n    basic_mathematics::Vector6d computedCartesianElements = Eigen::VectorXd::Zero( 6 );\n\n    // Set default Keplerian elements [m,-,rad,rad,rad,rad].\n    basic_mathematics::Vector6d testKepler = Eigen::VectorXd::Zero( 6 );\n    testKepler( semiMajorAxisIndex ) = 1.0e7;\n    testKepler( eccentricityIndex ) = 0.1;\n    testKepler( inclinationIndex ) = convertDegreesToRadians( 50.0 );\n    bool avoidSingularity = false;\n    testKepler( argumentOfPeriapsisIndex ) = convertDegreesToRadians( 350.0 );\n    testKepler( longitudeOfAscendingNodeIndex ) = convertDegreesToRadians( 15.0 );\n    testKepler( trueAnomalyIndex ) = convertDegreesToRadians( 170.0 );\n\n    double gravitationalParameter = 398600.44e9; // Earth's, but any parameter would do.\n\n    // Case 1: Elliptical prograde orbit.\n    {\n        // Default, so no modification necessary.\n\n        // Create expected Cartesian vector through the verified Kepler to Cartesian routine.\n        expectedCartesianElements = convertKeplerianToCartesianElements( testKepler,\n                                                                         gravitationalParameter );\n\n        // Convert to modified equinoctial elements, then that to Cartesian.\n        intermediateModifiedEquinoctialElements =\n                convertKeplerianToModifiedEquinoctialElements( testKepler, avoidSingularity );\n        computedCartesianElements = convertModifiedEquinoctialToCartesianElements(\n                    intermediateModifiedEquinoctialElements, gravitationalParameter,\n                    avoidSingularity );\n\n        // Compare.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedCartesianElements, computedCartesianElements,\n                                           tolerance );\n    }\n\n    // Case 2: Hyperbolic retrograde orbit.\n    {\n        // Set Keplerian elements [m,-,rad,rad,rad,rad].\n        testKepler( semiMajorAxisIndex ) = -1.0e7;\n        testKepler( eccentricityIndex ) = 2.0;\n        testKepler( inclinationIndex )\n                = convertDegreesToRadians( 170.0 ); // Between 90 and 180 is retrograde\n        avoidSingularity = true;\n        testKepler( trueAnomalyIndex ) = convertDegreesToRadians( 10.0 );\n\n        // Create starting Cartesian vector through the verified Kepler to Cartesian routine.\n        expectedCartesianElements = convertKeplerianToCartesianElements( testKepler,\n                                                                         gravitationalParameter );\n\n        // Convert to modified equinoctial elements, then to Cartesian.\n        intermediateModifiedEquinoctialElements =\n                convertKeplerianToModifiedEquinoctialElements( testKepler, avoidSingularity );\n        computedCartesianElements = convertModifiedEquinoctialToCartesianElements(\n                    intermediateModifiedEquinoctialElements, gravitationalParameter,\n                    avoidSingularity );\n\n        // Check if computed elements match the expected values.\n        // Because element z is ~10^16 smaller than the other elements, it is only checked whether\n        // its value is 'sufficiently' close to zero.\n        BOOST_CHECK_SMALL( expectedCartesianElements( 2 ), 1.0E-9 );\n        BOOST_CHECK_SMALL( computedCartesianElements( 2 ), 1.0E-9 );\n        expectedCartesianElements( 2 ) = 0.0;\n        computedCartesianElements( 2 ) = 0.0;\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedCartesianElements, computedCartesianElements,\n                                           tolerance );\n    }\n\n    // Case 3: Parabolic retrograde orbit.\n    {\n        // Set Keplerian elements [m,-,rad,rad,rad,rad].\n        testKepler( semiMajorAxisIndex ) = 1.0e7;\n        testKepler( eccentricityIndex ) = 1.0;\n        avoidSingularity = true;\n        testKepler( trueAnomalyIndex ) = convertDegreesToRadians( 170.0 );\n\n        // Create starting Cartesian vector through the verified Kepler to Cartesian routine.\n        expectedCartesianElements = convertKeplerianToCartesianElements( testKepler,\n                                                                         gravitationalParameter );\n\n        // Convert to modified equinoctial elements, then to Cartesian.\n        intermediateModifiedEquinoctialElements =\n                convertKeplerianToModifiedEquinoctialElements( testKepler, avoidSingularity );\n        computedCartesianElements = convertModifiedEquinoctialToCartesianElements(\n                    intermediateModifiedEquinoctialElements, gravitationalParameter,\n                    avoidSingularity );\n\n        // Compare.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedCartesianElements, computedCartesianElements,\n                                           tolerance );\n    }\n\n    // Case 4: Circular prograde orbit.\n    {\n        // Set Keplerian elements [m,-,rad,rad,rad,rad].\n        testKepler ( eccentricityIndex ) = 0.0;\n        testKepler ( inclinationIndex ) = convertDegreesToRadians( 50.0 );\n        avoidSingularity = false;\n        testKepler ( argumentOfPeriapsisIndex ) = 0.0; // e = 0, so actually undefined.\n\n        // Create starting Cartesian vector through the verified Kepler to Cartesian routine.\n        expectedCartesianElements = convertKeplerianToCartesianElements( testKepler,\n                                                                         gravitationalParameter );\n\n        // Convert to modified equinoctial elements, then to Cartesian.\n        intermediateModifiedEquinoctialElements =\n                convertKeplerianToModifiedEquinoctialElements( testKepler, avoidSingularity );\n        computedCartesianElements = convertModifiedEquinoctialToCartesianElements(\n                    intermediateModifiedEquinoctialElements, gravitationalParameter,\n                    avoidSingularity );\n\n        // Compare.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedCartesianElements, computedCartesianElements,\n                                           1.0E-13 );\n    }\n\n    // Case 5: 0 inclination orbit.\n    {\n        // Set Keplerian elements [m,-,rad,rad,rad,rad].\n        testKepler ( eccentricityIndex ) = 0.1;\n        testKepler ( inclinationIndex ) = 0.0;\n        avoidSingularity = false;\n        testKepler ( argumentOfPeriapsisIndex ) = convertDegreesToRadians( 260.0 );\n        testKepler ( longitudeOfAscendingNodeIndex ) = convertDegreesToRadians( 0.0 );\n\n        // Create starting Cartesian vector through the verified Kepler to Cartesian routine.\n        expectedCartesianElements = convertKeplerianToCartesianElements( testKepler,\n                                                                         gravitationalParameter );\n\n        // Convert to modified equinoctial elements, then to Cartesian.\n        intermediateModifiedEquinoctialElements =\n                convertKeplerianToModifiedEquinoctialElements( testKepler, avoidSingularity );\n        computedCartesianElements = convertModifiedEquinoctialToCartesianElements(\n                    intermediateModifiedEquinoctialElements, gravitationalParameter,\n                    avoidSingularity );\n\n        // Compare.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedCartesianElements, computedCartesianElements,\n                                           tolerance );\n    }\n\n    // Case 6: 180 inclination orbit.\n    {\n        // Set Keplerian elements [m,-,rad,rad,rad,rad].\n        testKepler( eccentricityIndex ) = 0.1;\n        testKepler( inclinationIndex ) = PI; // = 180 deg\n        avoidSingularity = true;\n        testKepler( argumentOfPeriapsisIndex ) = convertDegreesToRadians( 12.0 );\n        testKepler( trueAnomalyIndex ) = convertDegreesToRadians( 190.0 );\n\n        // Create starting Cartesian vector through the verified Kepler to Cartesian routine.\n        expectedCartesianElements = convertKeplerianToCartesianElements( testKepler,\n                                                                         gravitationalParameter );\n\n        // Convert to modified equinoctial elements, then to Cartesian.\n        intermediateModifiedEquinoctialElements =\n                convertKeplerianToModifiedEquinoctialElements( testKepler, avoidSingularity );\n        computedCartesianElements = convertModifiedEquinoctialToCartesianElements(\n                    intermediateModifiedEquinoctialElements, gravitationalParameter,\n                    avoidSingularity );\n\n        // Compare.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedCartesianElements, computedCartesianElements,\n                                           tolerance );\n    }\n\n    // Case 7: 0 eccentricity and inclination.\n    {\n        // Set Keplerian elements [m,-,rad,rad,rad,rad].\n        testKepler( eccentricityIndex ) = 0.0;\n        testKepler( inclinationIndex ) = 0.0;\n        avoidSingularity = false;\n\n        // Create starting Cartesian vector through the verified Kepler to Cartesian routine.\n        expectedCartesianElements = convertKeplerianToCartesianElements( testKepler,\n                                                                         gravitationalParameter );\n\n        // Convert to modified equinoctial elements, then to Cartesian.\n        intermediateModifiedEquinoctialElements =\n                convertKeplerianToModifiedEquinoctialElements( testKepler, avoidSingularity );\n        computedCartesianElements = convertModifiedEquinoctialToCartesianElements(\n                    intermediateModifiedEquinoctialElements, gravitationalParameter,\n                    avoidSingularity );\n\n        // Compare.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedCartesianElements, computedCartesianElements,\n                                           tolerance );\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END( )\n\n} // namespace unit_tests\n} // namespace tudat\n", "meta": {"hexsha": "39eeda817c09617a1be8ba5642f540069e652d34", "size": 58419, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/BasicAstrodynamics/UnitTests/unitTestModifiedEquinoctialElementConversions.cpp", "max_stars_repo_name": "JPelamatti/ThesisTUDAT", "max_stars_repo_head_hexsha": "b94ce35fb7c8fa44ae83238e296a979dfa3adfe8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tudat/Astrodynamics/BasicAstrodynamics/UnitTests/unitTestModifiedEquinoctialElementConversions.cpp", "max_issues_repo_name": "JPelamatti/ThesisTUDAT", "max_issues_repo_head_hexsha": "b94ce35fb7c8fa44ae83238e296a979dfa3adfe8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tudat/Astrodynamics/BasicAstrodynamics/UnitTests/unitTestModifiedEquinoctialElementConversions.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": 51.928, "max_line_length": 100, "alphanum_fraction": 0.6530409627, "num_tokens": 12949, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.47876748582106166}}
{"text": "#include \"probability.h\"\n\n#include \"plugin_factory.h\"\n\n#include \"logger.h\"\n#include \"fetcher.h\"\n#include \"writer.h\"\n\n#include \"ensemble.h\"\n#include \"lagged_ensemble.h\"\n#include \"util.h\"\n\n#include <boost/thread.hpp>\n\n#include <algorithm>\n#include <exception>\n#include <iostream>\n\n#include \"radon.h\"\n#include <math.h>\n\nnamespace himan\n{\nnamespace plugin\n{\nstatic std::mutex singleFileWriteMutex;\n\nstatic const std::string kClassName = \"himan::plugin::probability\";\n\n/// @brief Used for calculating wind vector magnitude\nstatic inline double Magnitude(double u, double v) { return sqrt(u * u + v * v); }\nprobability::probability()\n{\n\titsCudaEnabledCalculation = false;\n\titsLogger = logger(\"probability\");\n\n\titsEnsembleSize = 0;\n\titsMaximumMissingForecasts = 0;\n\titsUseNormalizedResult = false;\n\titsUseLaggedEnsemble = false;\n\titsLag = 0;\n\titsLaggedSteps = 0;\n}\n\nprobability::~probability() {}\n/// @brief Configuration reading\n/// @param outParamConfig is modified to have information about the threshold value and input parameters\n/// @returns param to be pushed in the calculatedParams vector in Process()\nstatic param GetConfigurationParameter(const std::string& name, const std::shared_ptr<const plugin_configuration> conf,\n                                       param_configuration* outParamConfig)\n{\n\tif (conf->ParameterExists(name))\n\t{\n\t\tconst auto paramOpts = conf->GetParameterOptions(name);\n\n\t\tparam param1;\n\t\tparam param2;\n\n\t\t// NOTE These are plugin dependent\n\t\tfor (auto&& p : paramOpts)\n\t\t{\n\t\t\tif (p.first == \"threshold\")\n\t\t\t{\n\t\t\t\toutParamConfig->gridThreshold = std::stod(p.second);\n\t\t\t}\n\t\t\telse if (p.first == \"input_param1\")\n\t\t\t{\n\t\t\t\tparam1.Name(p.second);\n\t\t\t}\n\t\t\telse if (p.first == \"input_param2\")\n\t\t\t{\n\t\t\t\tparam2.Name(p.second);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tauto elems = util::Split(p.first, \"_\", false);\n\t\t\t\tif (elems.size() == 2 && elems[0] == \"threshold\")\n\t\t\t\t{\n\t\t\t\t\toutParamConfig->stationThreshold[std::stoi(elems[1])] = std::stod(p.second);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (param1.Name() == \"XX-X\")\n\t\t{\n\t\t\tthrow std::runtime_error(\"probability : configuration error:: input parameter not specified for '\" + name +\n\t\t\t                         \"'\");\n\t\t}\n\t\toutParamConfig->parameter = param1;\n\n\t\t// NOTE param2 is used only with wind calculation at the moment\n\t\tif (param2.Name() != \"XX-X\")\n\t\t{\n\t\t\toutParamConfig->parameter2 = param2;\n\t\t}\n\t}\n\telse\n\t{\n\t\tthrow std::runtime_error(\n\t\t    \"probability : configuration error:: requested parameter doesn't exist in the configuration file '\" + name +\n\t\t    \"'\");\n\t}\n\n\treturn param(name);\n}\n\nvoid probability::Process(const std::shared_ptr<const plugin_configuration> conf)\n{\n\tInit(conf);\n\n\t//\n\t// 1. Parse json configuration specific to this plugin\n\t//\n\n\t// Most of the plugin operates by the configuration in the json file.\n\t// Here we collect all the parameters we want to calculate, and the parameters that are used for the calculation.\n\t// If the configuration is invalid we will bail out asap!\n\n\t// Get the number of forecasts this ensemble has from plugin configuration\n\tif (itsConfiguration->Exists(\"ensemble_size\"))\n\t{\n\t\tconst int ensembleSize = std::stoi(itsConfiguration->GetValue(\"ensemble_size\"));\n\t\tif (ensembleSize <= 0)\n\t\t{\n\t\t\tthrow std::runtime_error(ClassName() + \" invalid ensemble_size in plugin configuration\");\n\t\t}\n\t\titsEnsembleSize = ensembleSize;\n\t}\n\telse\n\t{\n\t\tthrow std::runtime_error(ClassName() + \" ensemble_size not specified in plugin configuration\");\n\t}\n\n\t// Find out whether we want probabilities in [0,1] range or [0,100] range\n\tif (itsConfiguration->Exists(\"normalized_results\"))\n\t{\n\t\tconst std::string useNormalized = itsConfiguration->GetValue(\"normalized_results\");\n\n\t\titsUseNormalizedResult = (useNormalized == \"true\") ? true : false;\n\t}\n\telse\n\t{\n\t\t// default to [0,100] for compatibility\n\t\titsUseNormalizedResult = false;\n\t\titsLogger.Info(\n\t\t    \"'normalized_results' not found from the configuration, results will be written in [0,100] range\");\n\t}\n\n\t// Maximum number of missing forecasts for an ensemble\n\tif (itsConfiguration->Exists(\"max_missing_forecasts\"))\n\t{\n\t\tconst int maxMissingForecasts = std::stoi(itsConfiguration->GetValue(\"max_missing_forecasts\"));\n\t\tif (maxMissingForecasts < 0)\n\t\t{\n\t\t\tthrow std::runtime_error(ClassName() +\n\t\t\t                         \" invalid max_missing_forecasts value specified in plugin configuration\");\n\t\t}\n\t\titsMaximumMissingForecasts = maxMissingForecasts;\n\t}\n\n\t// Are we using lagged ensemble?\n\t// NOTE 'lag' needs to be specified first\n\tif (itsConfiguration->Exists(\"lag\"))\n\t{\n\t\tint lag = std::stoi(itsConfiguration->GetValue(\"lag\"));\n\t\tif (lag == 0)\n\t\t{\n\t\t\tthrow std::runtime_error(ClassName() + \": specify lag < 0\");\n\t\t}\n\t\telse if (lag > 0)\n\t\t{\n\t\t\titsLogger.Warning(\"negating lag value \" + std::to_string(-lag));\n\t\t\tlag = -lag;\n\t\t}\n\n\t\titsLag = lag;\n\t\titsUseLaggedEnsemble = true;\n\t}\n\telse\n\t{\n\t\titsUseLaggedEnsemble = false;\n\t}\n\n\t// How many lagged steps to include in the calculation\n\tif (itsUseLaggedEnsemble)\n\t{\n\t\tif (itsConfiguration->Exists(\"lagged_steps\"))\n\t\t{\n\t\t\tconst int steps = std::stoi(itsConfiguration->GetValue(\"lagged_steps\"));\n\t\t\tif (steps <= 0)\n\t\t\t{\n\t\t\t\tthrow std::runtime_error(ClassName() + \": invalid lagged_steps value. Allowed range >= 0\");\n\t\t\t}\n\t\t\titsLaggedSteps = steps;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tthrow std::runtime_error(ClassName() + \": specify lagged_steps when using time lagging ('lag')\");\n\t\t}\n\t}\n\n\t//\n\t// 2. Setup input and output parameters from the json configuration.\n\t//    `calculatedParams' will hold the output parameter, it's inputs,\n\t//    and the 'threshold' value.\n\t//\n\tparams calculatedParams;\n\n\tint targetInfoIndex = 0;\n\tconst auto& names = conf->GetParameterNames();\n\tfor (const std::string& name : names)\n\t{\n\t\tparam_configuration config;\n\n\t\tconfig.targetInfoIndex = targetInfoIndex;\n\t\tconfig.output.Name(name);\n\n\t\tparam p = GetConfigurationParameter(name, conf, &config);\n\n\t\tif (p.Name() == \"\")\n\t\t{\n\t\t\tthrow std::runtime_error(ClassName() + \"Misconfigured parameter definition in JSON\");\n\t\t}\n\n\t\titsParamConfigurations.push_back(config);\n\t\tcalculatedParams.push_back(p);\n\t\ttargetInfoIndex++;\n\t}\n\n\tSetParams(calculatedParams);\n\n\t// Make sure that limit exists for all stations (if source data is stations)\n\tauto tempInfo = std::make_shared<himan::info>(*conf->Info());\n\ttempInfo->First();\n\n\tif (tempInfo->Grid()->Type() == kPointList)\n\t{\n\t\tauto r = GET_PLUGIN(radon);\n\t\tfor (tempInfo->ResetLocation(); tempInfo->NextLocation();)\n\t\t{\n\t\t\tconst auto st = tempInfo->Station();\n\n\t\t\tfor (auto& pc : itsParamConfigurations)\n\t\t\t{\n\t\t\t\tauto it = pc.stationThreshold.find(st.Id());\n\n\t\t\t\tif (it == pc.stationThreshold.end())\n\t\t\t\t{\n\t\t\t\t\titsLogger.Trace(\"Fetching threshold for param \" + pc.output.Name() + \", station \" +\n\t\t\t\t\t                std::to_string(st.Id()) + \" from radon\");\n\t\t\t\t\tdouble limit = r->RadonDB().GetProbabilityLimitForStation(st.Id(), pc.output.Name());\n\n\t\t\t\t\tif (limit == kFloatMissing)\n\t\t\t\t\t{\n\t\t\t\t\t\titsLogger.Fatal(\"Threshold not found for param \" + pc.output.Name() + \", station \" +\n\t\t\t\t\t\t                std::to_string(st.Id()));\n\t\t\t\t\t\tabort();\n\t\t\t\t\t}\n\n\t\t\t\t\tpc.stationThreshold[st.Id()] = limit;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// NOTE\n\t// NOTE We circumvent the usual Himan Start => Run => RunAll / RunTimeDimension - control flow structure\n\t// NOTE\n\n\t//\n\t// 3. Process parameters in LIFO order by spawning threads for each parameter.\n\t//\t  (We don't divide timesteps between threads)\n\t//\n\tboost::thread_group g;\n\tauto paramConfigurations = itsParamConfigurations;\n\n\t// Set iterators at this stage to avoid invalid indexing when loading from auxiliary files\n\titsInfo->First();\n\n\tint threadIdx = 0;\n\n\tfor (const auto& pc : paramConfigurations)\n\t{\n\t\tg.add_thread(new boost::thread(&himan::plugin::probability::Calculate, this, threadIdx, boost::ref(pc)));\n\n\t\tif (threadIdx == itsThreadCount)\n\t\t{\n\t\t\tg.join_all();\n\t\t\tthreadIdx = 0;\n\t\t}\n\n\t\tthreadIdx++;\n\t}\n\n\tg.join_all();\n\n\tFinish();\n}\n\nstatic void CalculateNormal(std::shared_ptr<info> targetInfo, uint16_t threadIndex,\n                            const param_configuration& paramConf, int infoIndex, bool normalized,\n                            std::unique_ptr<ensemble>& ens);\n\nstatic void CalculateNegative(std::shared_ptr<info> targetInfo, uint16_t threadIndex,\n                              const param_configuration& paramConf, const int infoIndex, const bool normalized,\n                              std::unique_ptr<ensemble>& ens);\n\nstatic void CalculateWind(const logger& log, std::shared_ptr<info> targetInfo, uint16_t threadIndex,\n                          const param_configuration& paramConf, int infoIndex, bool normalized,\n                          std::unique_ptr<ensemble>& ens1, std::unique_ptr<ensemble>& ens2);\n\nvoid probability::Calculate(uint16_t threadIndex, const param_configuration& pc)\n{\n\tinfo myTargetInfo = *itsInfo;\n\n\tauto threadedLogger = logger(\"probabilityThread # \" + std::to_string(threadIndex));\n\tconst std::string deviceType = \"CPU\";\n\n\tconst double threshold = pc.gridThreshold;\n\tconst int infoIndex = pc.targetInfoIndex;\n\tconst int ensembleSize = itsEnsembleSize;\n\tconst bool normalized = itsUseNormalizedResult;\n\n\tmyTargetInfo.First();\n\n\tstd::unique_ptr<ensemble> ens1;\n\tstd::unique_ptr<ensemble> ens2;  // used with wind calculation\n\n\tif (itsUseLaggedEnsemble)\n\t{\n\t\tthreadedLogger.Info(\"Using lagged ensemble for ensemble #1\");\n\t\tens1 = std::unique_ptr<ensemble>(\n\t\t    new lagged_ensemble(pc.parameter, ensembleSize, kHourResolution, itsLag, itsLaggedSteps + 1));\n\t}\n\telse\n\t{\n\t\tens1 = std::unique_ptr<ensemble>(new ensemble(pc.parameter, ensembleSize));\n\t}\n\tens1->MaximumMissingForecasts(itsMaximumMissingForecasts);\n\n\tif (pc.parameter.Name() == \"U-MS\" || pc.parameter.Name() == \"V-MS\")\n\t{\n\t\t// Wind\n\t\tif (itsUseLaggedEnsemble)\n\t\t{\n\t\t\tthreadedLogger.Info(\"Using lagged ensemble for ensemble #2\");\n\t\t\tens2 = std::unique_ptr<ensemble>(\n\t\t\t    new lagged_ensemble(pc.parameter2, ensembleSize, kHourResolution, itsLag, itsLaggedSteps + 1));\n\t\t}\n\t\telse\n\t\t{\n\t\t\tens2 = std::unique_ptr<ensemble>(new ensemble(pc.parameter2, ensembleSize));\n\t\t}\n\t\tens2->MaximumMissingForecasts(itsMaximumMissingForecasts);\n\t}\n\n\t// NOTE we only loop through the time steps here\n\tdo\n\t{\n\t\tthreadedLogger.Info(\"Calculating \" + pc.output.Name() + \" time \" +\n\t\t                    static_cast<std::string>(myTargetInfo.Time().ValidDateTime()) + \" threshold '\" +\n\t\t                    std::to_string(threshold) + \"' infoIndex \" + std::to_string(infoIndex));\n\n\t\t//\n\t\t// Setup input data, data fetching\n\t\t//\n\n\t\ttry\n\t\t{\n\t\t\tens1->Fetch(itsConfiguration, myTargetInfo.Time(), myTargetInfo.Level());\n\n\t\t\tif (pc.parameter.Name() == \"U-MS\" || pc.parameter.Name() == \"V-MS\")\n\t\t\t{\n\t\t\t\tens2->Fetch(itsConfiguration, myTargetInfo.Time(), myTargetInfo.Level());\n\t\t\t}\n\t\t}\n\t\tcatch (const HPExceptionType& e)\n\t\t{\n\t\t\tif (e == kFileDataNotFound)\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\titsLogger.Fatal(\"Received error code \" + std::to_string(e));\n\t\t\t\tabort();\n\t\t\t}\n\t\t}\n\n\t\t// Output memory\n\t\tif (itsConfiguration->UseDynamicMemoryAllocation())\n\t\t{\n\t\t\tAllocateMemory(myTargetInfo);\n\t\t}\n\t\tassert(myTargetInfo.Data().Size() > 0);\n\n\t\t//\n\t\t// Choose the correct calculation function for this parameter and do the actual calculation\n\t\t//\n\t\t// Unfortunately we use both the input parameter name and output parameter name for doing this.\n\t\t//\n\t\tif (pc.parameter.Name() == \"U-MS\" || pc.parameter.Name() == \"V-MS\")\n\t\t{\n\t\t\tCalculateWind(threadedLogger, std::make_shared<info>(myTargetInfo), threadIndex, pc, infoIndex, normalized,\n\t\t\t              ens1, ens2);\n\t\t}\n\t\telse if (pc.output.Name() == \"PROB-TC-0\" || pc.output.Name() == \"PROB-TC-1\" ||\n\t\t         pc.output.Name() == \"PROB-TC-2\" || pc.output.Name() == \"PROB-TC-3\" ||\n\t\t         pc.output.Name() == \"PROB-TC-4\" || pc.output.Name() == \"PROB-WATLEV-LOW-1\")\n\t\t{\n\t\t\tCalculateNegative(std::make_shared<info>(myTargetInfo), threadIndex, pc, infoIndex, normalized, ens1);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tCalculateNormal(std::make_shared<info>(myTargetInfo), threadIndex, pc, infoIndex, normalized, ens1);\n\t\t}\n\n\t\tif (itsConfiguration->StatisticsEnabled())\n\t\t{\n\t\t\titsConfiguration->Statistics()->AddToMissingCount(myTargetInfo.Data().MissingCount());\n\t\t\titsConfiguration->Statistics()->AddToValueCount(myTargetInfo.Data().Size());\n\t\t}\n\n\t\t// Finally write this parameter out\n\t\tWriteToFile(myTargetInfo, pc.targetInfoIndex);\n\n\t} while (myTargetInfo.NextTime());\n\n\tthreadedLogger.Info(\"[\" + deviceType + \"] Missing values: \" + std::to_string(myTargetInfo.Data().MissingCount()) +\n\t                    \"/\" + std::to_string(myTargetInfo.Data().Size()));\n}\n\n// Usually himan writes all the parameters out on a call to WriteToFile, but probability calculates\n// each parameter separately in separate threads so this makes no sense (writing all out if we've only\n// calculated one parameter)\nvoid probability::WriteToFile(const info& targetInfo, size_t targetInfoIndex, write_options opts)\n{\n\tauto writer = GET_PLUGIN(writer);\n\n\twriter->WriteOptions(opts);\n\n\tauto info = targetInfo;\n\n\tinfo.ResetParam();\n\tinfo.ParamIndex(targetInfoIndex);\n\n\tif (itsConfiguration->FileWriteOption() == kDatabase || itsConfiguration->FileWriteOption() == kMultipleFiles)\n\t{\n\t\twriter->ToFile(info, itsConfiguration);\n\t}\n\telse\n\t{\n\t\tstd::lock_guard<std::mutex> lock(singleFileWriteMutex);\n\n\t\twriter->ToFile(info, itsConfiguration, itsConfiguration->ConfigurationFile());\n\t}\n\n\tif (itsConfiguration->UseDynamicMemoryAllocation())\n\t{\n\t\tDeallocateMemory(info);\n\t}\n}\n\ndouble GetThreshold(std::shared_ptr<info>& targetInfo, const param_configuration& paramConf, bool isGrid)\n{\n\tif (isGrid)\n\t{\n\t\treturn paramConf.gridThreshold;\n\t}\n\telse\n\t{\n\t\tconst int stationId = targetInfo->Station().Id();\n\t\tconst auto iter = paramConf.stationThreshold.find(stationId);\n\n\t\tif (iter == paramConf.stationThreshold.end())\n\t\t{\n\t\t\tthrow std::runtime_error(\"Threshold for station \" + std::to_string(stationId) + \" not found\");\n\t\t}\n\n\t\treturn iter->second;\n\t}\n}\n\nvoid CalculateWind(const logger& log, std::shared_ptr<info> targetInfo, uint16_t threadIndex,\n                   const param_configuration& paramConf, int infoIndex, bool normalized,\n                   std::unique_ptr<ensemble>& ens1, std::unique_ptr<ensemble>& ens2)\n{\n\ttargetInfo->ParamIndex(infoIndex);\n\ttargetInfo->ResetLocation();\n\tens1->ResetLocation();\n\tens2->ResetLocation();\n\n\tconst size_t ensembleSize = ens1->Size();\n\tif (ensembleSize != ens2->Size())\n\t{\n\t\tlog.Fatal(\" CalculateWind(): U and V ensembles are of different size, aborting\");\n\t\tabort();\n\t}\n\n\tconst double invN =\n\t    normalized ? 1.0 / static_cast<double>(ensembleSize) : 100.0 / static_cast<double>(ensembleSize);\n\n\tconst bool isGrid = (targetInfo->Grid()->Type() != kPointList);\n\n\twhile (targetInfo->NextLocation() && ens1->NextLocation() && ens2->NextLocation())\n\t{\n\t\tdouble probability = 0.0;\n\t\tconst double threshold = GetThreshold(targetInfo, paramConf, isGrid);\n\n\t\tfor (size_t i = 0; i < ensembleSize; i++)\n\t\t{\n\t\t\tconst auto u = ens1->Value(i);\n\t\t\tconst auto v = ens2->Value(i);\n\n\t\t\tif ((u == kFloatMissing) || (v == kFloatMissing))\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (Magnitude(u, v) >= threshold)\n\t\t\t{\n\t\t\t\tprobability += invN;\n\t\t\t}\n\t\t}\n\t\ttargetInfo->Value(probability);\n\t}\n}\n\nvoid CalculateNegative(std::shared_ptr<info> targetInfo, uint16_t threadIndex, const param_configuration& paramConf,\n                       int infoIndex, bool normalized, std::unique_ptr<ensemble>& ens)\n{\n\ttargetInfo->ParamIndex(infoIndex);\n\ttargetInfo->ResetLocation();\n\tens->ResetLocation();\n\n\tconst size_t ensembleSize = ens->Size();\n\tconst double invN =\n\t    normalized ? 1.0 / static_cast<double>(ensembleSize) : 100.0 / static_cast<double>(ensembleSize);\n\n\tconst bool isGrid = (targetInfo->Grid()->Type() != kPointList);\n\n\twhile (targetInfo->NextLocation() && ens->NextLocation())\n\t{\n\t\tdouble probability = 0.0;\n\t\tconst double threshold = GetThreshold(targetInfo, paramConf, isGrid);\n\n\t\tfor (size_t i = 0; i < ensembleSize; i++)\n\t\t{\n\t\t\tconst auto x = ens->Value(i);\n\t\t\tif ((x != kFloatMissing) && (x <= threshold))\n\t\t\t{\n\t\t\t\tprobability += invN;\n\t\t\t}\n\t\t}\n\t\ttargetInfo->Value(probability);\n\t}\n}\n\nvoid CalculateNormal(std::shared_ptr<info> targetInfo, uint16_t threadIndex, const param_configuration& paramConf,\n                     int infoIndex, bool normalized, std::unique_ptr<ensemble>& ens)\n{\n\ttargetInfo->ParamIndex(infoIndex);\n\ttargetInfo->ResetLocation();\n\tens->ResetLocation();\n\n\tconst size_t ensembleSize = ens->Size();\n\tconst double invN =\n\t    normalized ? 1.0 / static_cast<double>(ensembleSize) : 100.0 / static_cast<double>(ensembleSize);\n\n\tconst bool isGrid = (targetInfo->Grid()->Type() != kPointList);\n\n\twhile (targetInfo->NextLocation() && ens->NextLocation())\n\t{\n\t\tdouble probability = 0.0;\n\t\tconst double threshold = GetThreshold(targetInfo, paramConf, isGrid);\n\n\t\tfor (size_t i = 0; i < ensembleSize; i++)\n\t\t{\n\t\t\tconst auto x = ens->Value(i);\n\t\t\tif ((x != kFloatMissing) && (x >= threshold))\n\t\t\t{\n\t\t\t\tprobability += invN;\n\t\t\t}\n\t\t}\n\t\ttargetInfo->Value(probability);\n\t}\n}\n\n}  // plugin\n\n}  // namespace\n", "meta": {"hexsha": "01ac3cc84eb2ee11578eb84e6c12f56fdaf2306c", "size": 16913, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "himan-plugins/source/probability.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/probability.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/probability.cpp", "max_forks_repo_name": "jrintala/fmi-data", "max_forks_repo_head_hexsha": "625f0a44919e6406440349425ee0b3f1a64a923d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5692567568, "max_line_length": 119, "alphanum_fraction": 0.6791225684, "num_tokens": 4375, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431679972357831, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.4787674821564844}}
{"text": "/* Generate an MCMC estimate of the edge appearance probabilities of a graph \n * in the directed spanning tree polytope by sampling random spanning trees\n *\n * Author : Rahul G. Krishnan\n * Inst.  : NYU\n */\n#include <iostream>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/graph_concepts.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <vector>\n#include <fstream>\n#include <cstdlib>\n#include <boost/graph/random_spanning_tree.hpp>\n#include <boost/graph/iteration_macros.hpp>\n#include <boost/graph/named_function_params.hpp>\n#include <boost/array.hpp>\n#include <string>\n#include <boost/foreach.hpp>\n#include <boost/unordered_map.hpp>\n#include <boost/tuple/tuple.hpp> \n#include <boost/tuple/tuple_io.hpp> \n#include <boost/random/uniform_int_distribution.hpp>\n#include <boost/graph/iteration_macros.hpp>\n#ifdef DEBUG\n#define DEBUG_MSG(str) do { std::cout << str << std::endl; } while( false )\n#else\n#define DEBUG_MSG(str) do { } while ( false )\n#endif\n\n//Parameters for the MC algorithm\nint WEIGHTED = 0;\nint MAXITS  = 10000;\n\n\n//Defining types\ntypedef boost::property<boost::edge_weight_t, double> EdgeWeightProperty;\ntypedef boost::adjacency_list < \n    boost::vecS, boost::vecS, boost::directedS,\n    boost::no_property,EdgeWeightProperty > digraph_t;\ntypedef boost::unordered_map<std::string,double> unordered_map;\nboost::random::mt19937 rng;\n#define getKey(v1,v2) std::to_string((long long unsigned int)v1)+\"->\"+std::to_string((long long unsigned int)v2)\n\nvoid initializeGraph(std::vector<boost::tuple<int,int,double> > edgeList, \n                    digraph_t* g,\n                    unordered_map* map) \n{   \n    int v1,v2;\n    double wt;\n    boost::tuple<int,int,double> t;\n    BOOST_FOREACH ( t, edgeList)\n    {\n        v1 = boost::get<0>(t);\n        v2 = boost::get<1>(t);\n        wt = boost::get<2>(t);\n        DEBUG_MSG(\"Loading: \"<<v1<<\"->\"<<v2<<\" : \"<<wt);\n\t\t//TODO: Investigate why \n\t\t//you have to use this hack. Likely assumption\n\t\t//in BOOST library\n        add_edge(v1,v2,100/wt,*g);\n        map->insert(unordered_map::value_type(getKey(v1,v2),0));\n    }\n}\n\n\n/*\nGiven an edgeList, run the test case\n*/\nvoid runTest(int n_vertices,\n\tstd::vector<boost::tuple<int,int,double> > edgeList,\n\tunordered_map* edgeProb,\n\tstd::vector<double>* root_prob)\n{\n    digraph_t g;\n\n    initializeGraph(edgeList,&g,edgeProb);\n    for (unordered_map::iterator it = edgeProb->begin(); it != edgeProb->end(); ++it) \n        DEBUG_MSG(it->first << \", \" << it->second);\n    \n  \t#ifdef DEBUG\n    BGL_FORALL_EDGES(e, g, digraph_t) \n    {\n        std::cout<<e<<\" W=\"<<get(boost::edge_weight, g, e)<<std::endl;\n    }\n\tfor(int v=0;v<n_vertices;v++)\n\t{\n\t\tdouble weight_sum = 0;\n\t\tBGL_FORALL_OUTEDGES(v, e, g, digraph_t) {std::cout<<e<<\", \";weight_sum += get(get(boost::edge_weight,g), e);}\n\t\tstd::cout<<v<<\"->\"<<weight_sum<<std::endl;\n\t}\n    #endif\n    std::vector<int> predecessors (n_vertices);\n\tstd::vector<double> edgeMap (edgeList.size());\n    \n    for(int i=0;i<n_vertices;i++)\n    {\n        predecessors[i]=0;\n        (*root_prob)[i] = 0;\n    }\n    int root;\n    boost::random::uniform_int_distribution<> dist(0, n_vertices-1);\n    for(int i=1;i<=MAXITS;i++)\n    {\n\t\tstd::cout<<\".\";\n\t\tstd::fill(predecessors.begin(),predecessors.end(),0);\n\t\tif(i%500==0)\n\t\t{\n\t\t\tstd::cout<<std::endl;\n\t\t}\n        //Sample root uniformly \n        root = dist(rng);\n        #ifdef DEBUG_L2 //Since the DEBUG_MSG macro prints newline\n            std::cout<<i<<\"|\"<<root<<\"|,\"<<std::flush;\n        #endif\n\t\tif(WEIGHTED==1)\n\t\t{\n        boost::random_spanning_tree(g,rng,\n            boost::predecessor_map(\n                boost::make_iterator_property_map(\n                    predecessors.begin(), get(boost::vertex_index, g)))\n            .root_vertex(root)\n\t\t\t.weight_map(get(boost::edge_weight,g))\n\t\t\t\t\t\t\t\t);\n\t\t}\n\t\telse\n\t\t{\n        boost::random_spanning_tree(g,rng,\n            boost::predecessor_map(\n                boost::make_iterator_property_map(\n                    predecessors.begin(), get(boost::vertex_index, g)))\n            .root_vertex(root));\n\t\t}\n#ifdef DEBUG\n\t\tstd::cout<<\"Printing spanning tree rooted at \"<<root<<std::endl;\n#endif\n        //Update counts\n        (*root_prob)[root]+=1;\n        for(int i=0;i<n_vertices;i++)\n        {\n            if(predecessors[i]!=-1)\n            {\n                edgeProb->at(getKey(predecessors[i],i)) +=1;\n#ifdef DEBUG\n\t\t\t\tstd::cout<<predecessors[i]<<\"--\"<<i<<\" Key: \"<<getKey(predecessors[i],i)<<std::endl;\n#endif\n            }\n            else\n            {\n                if(root!=i)\n                    std::cout<<\"Error. root=\"<<root<<\" i=\"<<i<<std::endl;\n            }\n            \n        }\n\n    }\n    DEBUG_MSG(\"\");\n\n}\n\nint MCMC_spanning_tree(std::string fileIN,std::string fileOUT)\n{\n\t//Read graph structure from fileIN\n\tint v1,v2,n_vertices,n_edges = 0;\n\tstd::vector< boost::tuple<int,int,double> > edgeList;\n\tstd::string line;\n\tdouble weight;\n\tstd::ifstream inputf (fileIN.c_str());\n\tif(inputf.is_open())\n\t{\n\t\tgetline(inputf,line);\n\t\tsscanf(line.c_str(),\"%d\",&n_vertices);\n\t\twhile(getline(inputf,line))\n\t\t{\n\t\t\tsscanf (line.c_str(),\"%d,%d,%lf\",&v1,&v2,&weight);\n\t\t\t//Assumes vertices start from 0...N-1\n\t\t\tedgeList.push_back(boost::make_tuple(v1,v2,weight));\n\t\t\tn_edges++;\n\t\t}\n\t\tinputf.close();\n\t}\n\telse\n\t{\n\t\tstd::cerr<<\"Input file not found. Cannot be opened\\n\";\n\t\treturn EXIT_FAILURE;\n\t}\n\n\tstd::vector<double> root_prob (n_vertices);\n    unordered_map edgeProb;\n    runTest(n_vertices,edgeList, &edgeProb, &root_prob);\n    DEBUG_MSG(\"---RESULT---\");\n\n    \n    std::ofstream outputf (fileOUT.c_str());\n\n    //Normalize root and edge probabilities\n    for (int i=0;i<n_vertices;i++)\n    {\n    \toutputf<<(root_prob[i]/MAXITS);\n    \toutputf<<\" \";\n        DEBUG_MSG(\"Node \"<<i<<\" : \" << (root_prob[i]/MAXITS));\n    }\n    outputf<<\"\\n\";\n    boost::tuple<int,int,double> t;\n    BOOST_FOREACH(t,edgeList)\n    {\n    \tline = getKey(boost::get<0>(t),boost::get<1>(t));\n    \tDEBUG_MSG(boost::get<0>(t)<<\"->\"<<\n    \t    \t  boost::get<1>(t)<<\" : \"<<(edgeProb.at(line)/MAXITS));\n    \toutputf<<(edgeProb.at(line)/MAXITS);\n    \toutputf<<\" \";\n    }\n\n\treturn EXIT_SUCCESS;\n}\n\nstd::string PNAME = \"MCMC_spanning_tree\";\nint main(int argc,char* argv[])\n{\n\tif (argc < 3)\n\t{\n\t\tstd::cerr << \"Usage (* indicates optional): \" << PNAME\n\t\t\t << \" <input file name> <output file name> <Weighted=0>* <MAXIT=10K>*\\n\";\n\t\treturn EXIT_FAILURE;\n\t}\n\t//Modify global constants if specified\n\tif (argc>=4)\n\t{\n\t\tWEIGHTED = atoi(argv[3]);\n\t\tstd::cout<<\"Modifying WEIGHTED to \"<<WEIGHTED<<std::endl;\n\t\tif(WEIGHTED!=0 && WEIGHTED!=1)\n\t\t{\n\t\t\tstd::cerr <<\"WEIGHTED must be 1/0\"<<std::endl;\n\t\t\treturn EXIT_FAILURE;\n\t\t}\n\t}\n\tif (argc==5)\n\t{\n\t\tMAXITS = atoi(argv[4]);\n\t\tstd::cout<<\"Modifying MAXITS to \"<<MAXITS<<std::endl;\n\t}\n\tDEBUG_MSG(\"---Calling <MCMC_spanning_tree>---\\nINPUT FILE: \"<<argv[1]<<\"\\nOUTPUT FILE: \"<<argv[2]);\n\treturn MCMC_spanning_tree(argv[1],argv[2]);\n\t\n}\n", "meta": {"hexsha": "3a11d716d463c6b8895cd74c7ebc45a427510aad", "size": 6941, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "MCMC_spanning_tree.cpp", "max_stars_repo_name": "rahulk90/mcmc_directed_spanning_tree", "max_stars_repo_head_hexsha": "c6622e82107ca8377118893ce01571a2d0f9561b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MCMC_spanning_tree.cpp", "max_issues_repo_name": "rahulk90/mcmc_directed_spanning_tree", "max_issues_repo_head_hexsha": "c6622e82107ca8377118893ce01571a2d0f9561b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MCMC_spanning_tree.cpp", "max_forks_repo_name": "rahulk90/mcmc_directed_spanning_tree", "max_forks_repo_head_hexsha": "c6622e82107ca8377118893ce01571a2d0f9561b", "max_forks_repo_licenses": ["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.1012145749, "max_line_length": 112, "alphanum_fraction": 0.6156173462, "num_tokens": 1963, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743167997235783, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.47876748215648435}}
{"text": "//============================================================================\n// Name        : benchmark_main.cc\n// Author      : Giovanni Azua (bravegag@hotmail.com)\n// Since       : 25.07.2013\n// Description : Main application for benchmarking Eigen with MAGMA and MKL\n//============================================================================\n\n#include <assert.h>\n#include <iostream>\n#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string>\n#include <vector>\n\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/mean.hpp>\n#include <boost/accumulators/statistics/variance.hpp>\n\n#include <boost/program_options/cmdline.hpp>\n#include <boost/program_options/config.hpp>\n#include <boost/program_options/environment_iterator.hpp>\n#include <boost/program_options/eof_iterator.hpp>\n#include <boost/program_options/errors.hpp>\n#include <boost/program_options/option.hpp>\n#include <boost/program_options/options_description.hpp>\n#include <boost/program_options/parsers.hpp>\n#include <boost/program_options/positional_options.hpp>\n#include <boost/program_options/value_semantic.hpp>\n#include <boost/program_options/variables_map.hpp>\n#include <boost/program_options/version.hpp>\n\n#include <boost/chrono.hpp>\n\n#include <boost/tokenizer.hpp>\n\n#include <Eigen/Dense>\n\n/**\n * Define reusable Eigen vector and matrix types.\n */\ntemplate<typename T>\nstruct BenchType {\n\ttypedef Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor> MatrixX;\n\ttypedef Eigen::Matrix<T, Eigen::Dynamic, 1, Eigen::ColMajor> VectorX;\n};\n\ntypedef BenchType<double>::MatrixX MatrixXd;\ntypedef BenchType<double>::VectorX VectorXd;\n\nusing namespace std;\nusing namespace boost::accumulators;\nusing namespace boost::chrono;\nnamespace po = boost::program_options;\n\ntypedef double (*workload_type)(long);\n\ntypedef accumulator_set<double, stats<tag::mean, tag::variance> > bench_accumulator;\nstatic bench_accumulator real_time_acc, gflops_acc;\n\n// reusable vector and matrices. Note we need to use pointers to make sure\n// that the memory is deallocated *before* MAGMA/CUDA shutdown takes place.\nMatrixXd *pA = new MatrixXd(), *pB = new MatrixXd(), *pC = new MatrixXd(), *pL = new MatrixXd();\nVectorXd *pa = new VectorXd(), *pb = new VectorXd(), *pc = new VectorXd();\nEigen::ColPivHouseholderQR<MatrixXd> *pAqr = new Eigen::ColPivHouseholderQR<MatrixXd>();\n\n// continue using them as before\nMatrixXd &A = *pA, &B = *pB, &C = *pC, &L = *pL;\nVectorXd &a = *pa, &b = *pb, &c = *pc;\nEigen::ColPivHouseholderQR<MatrixXd>& Aqr = *pAqr;\n\n/// Generic benchmarking\n/**\n * Generic benchmarking, implement the different workload types according to the expected signature.\n */\nstatic void run_benchmark(long N, int warm_ups, int num_runs, workload_type workload) {\n\t// warm up runs\n\tfor (int i = 0; i < warm_ups; ++i) {\n\t\t// invoke workload\n\t\t(*workload)(N);\n\n\t\tfprintf(stderr, \".\");\n\t\tfflush (stderr);\n\t}\n\n\t// actual measurements\n\tfor (int i = 0; i < num_runs; ++i) {\n\t\tdouble real_time, cpu_time, gflops;\n\t\tdouble flop_count;\n\t\tsystem_clock::time_point start;\n\n\t\t// benchmark using high-resolution timer\n\t\tstart = system_clock::now();\n\n\t\t// invoke workload\n\t\tflop_count = (*workload)(N);\n\n\t\t// use high-resolution timer\n\t\tduration<double> sec = system_clock::now() - start;\n\t\treal_time = sec.count();\n\t\tgflops = flop_count / (1e9 * real_time);\n\n\t\t// feed the accumulators\n\t\treal_time_acc(real_time);\n\t\tgflops_acc(gflops);\n\n\t\tfprintf(stderr, \".\");\n\t\tfflush (stderr);\n\t}\n}\n\nEIGEN_DONT_INLINE\nstatic double dgemm(long N) {\n\tC = A * B;\n\t// flops see http://www.netlib.org/lapack/lawnspdf/lawn41.pdf page 120\n\treturn 2 * N * N * N;\n}\n\nEIGEN_DONT_INLINE\nstatic double dgeqp3(long N) {\n\tEigen::ColPivHouseholderQR<MatrixXd> qr = A.colPivHouseholderQr();\n\t// flops see http://www.netlib.org/lapack/lawnspdf/lawn41.pdf page 121\n\treturn N * N * N - (2 / 3) * N * N * N + N * N + N * N + (14 / 3) * N;\n}\n\nEIGEN_DONT_INLINE\nstatic double dgeqrf(long N) {\n\tEigen::HouseholderQR<MatrixXd> qr = A.householderQr();\n\t// flops see http://www.netlib.org/lapack/lawnspdf/lawn41.pdf page 121\n\treturn 2 * N * N * N - (2 / 3) * N * N * N + 3 * N * N - N * N + (14 / 3) * N;\n}\n\nEIGEN_DONT_INLINE\nstatic double dgemv(long N) {\n\tC = A * b;\n\treturn 2 * N * N - N;\n}\n\nEIGEN_DONT_INLINE\nstatic double dtrsm(long N) {\n\tC = Aqr.solve(B);\n\treturn N * N * N;\n}\n\nEIGEN_DONT_INLINE\nstatic double dpotrf(long N) {\n\tEigen::LLT<MatrixXd> lltOfA(A);\n\tL = lltOfA.matrixL();\n\treturn N * N * N / 3.0 + N * N / 2.0 + N / 6.0;\n}\n\nEIGEN_DONT_INLINE\nstatic double dgesvd(long N) {\n\tEigen::JacobiSVD<MatrixXd> svd(A, Eigen::ComputeThinU | Eigen::ComputeThinV);\n\treturn 22 * N * N * N;\n}\n\nint main(int argc, char** argv) {\n#if !defined(NDEBUG) || defined(DEBUG)\n\tcerr << \"Warning: you are running in debug mode - assertions are enabled.\" << endl;\n#endif\n\n\ttry {\n\t\t// program arguments\n\t\tstring function;\n\t\tstring range;\n\t\tint warm_ups, num_runs, device_id = 0;\n\n\t\tpo::options_description desc(\"Benchmark main options\");\n\t\tdesc.add_options()(\"help\", \"produce help message\")\n\t\t\t(\"warm-up-runs\", po::value<int>(&warm_ups)->default_value(1), \"warm up runs e.g. 1\")\n\t\t\t(\"num-runs\", po::value<int>(&num_runs)->default_value(10), \"number of runs e.g. 10\")\n\t\t\t(\"function\", po::value < string > (&function)->default_value(\"dgemm\"), \"Function to test e.g. dgemm, dgeqp3\")\n\t\t\t(\"range\", po::value < string > (&range)->default_value(\"1024:10240:1024\"), \"N range i.e. start:stop:step\")\n\t\t\t(\"device-id\", po::value<int>(&device_id)->default_value(0), \"device id e.g. 0\");\n\n\t\tpo::variables_map vm;\n\t\tpo::store(po::parse_command_line(argc, argv, desc), vm);\n\t\tpo::notify(vm);\n\n#if defined(EIGEN_USE_MAGMA_ALL)\n\t\tcudaSetDevice(device_id);\n\t\tmagma_init();\n#endif\n\t\tif (vm.count(\"help\")) {\n\t\t\tcout << desc << \"\\n\";\n\t\t\treturn EXIT_FAILURE;\n\n\t\t} else {\n\t\t\tstring temp = range;\n\t\t\tboost::tokenizer<> tok(temp);\n\t\t\tvector<long> range_values;\n\t\t\tfor (boost::tokenizer<>::iterator current = tok.begin(); current != tok.end(); ++current) {\n\t\t\t\trange_values.push_back(boost::lexical_cast<long>(*current));\n\t\t\t}\n\n\t\t\tif (range_values.size() != 3) {\n\t\t\t\tthrow std::runtime_error(\"Illegal range input: '\" + range + \"'\");\n\t\t\t}\n\n\t\t\tworkload_type workload;\n\t\t\tif (function == \"dgemm\") {\n\t\t\t\tworkload = dgemm;\n\t\t\t} else if (function == \"dgeqp3\") {\n\t\t\t\tworkload = dgeqp3;\n\t\t\t} else if (function == \"dgeqrf\") {\n\t\t\t\tworkload = dgeqrf;\n\t\t\t} else if (function == \"dgemv\") {\n\t\t\t\tworkload = dgemv;\n\t\t\t} else if (function == \"dtrsm\") {\n\t\t\t\tworkload = dtrsm;\n\t\t\t} else if (function == \"dpotrf\") {\n\t\t\t\tworkload = dpotrf;\n\t\t\t} else if (function == \"dgesvd\") {\n\t\t\t\tworkload = dgesvd;\n\t\t\t} else {\n\t\t\t\tthrow std::runtime_error(\"Sorry, the function '\" + function + \"' is not yet implemented.\");\n\t\t\t}\n\n\t\t\tfor (long N = range_values[0]; N <= range_values[1]; N += range_values[2]) {\n\t\t\t\t// prepare the input data\n\t\t\t\tA = MatrixXd::Random(N, N);\n\t\t\t\tB = MatrixXd::Random(N, N);\n\t\t\t\tb = VectorXd::Random(N);\n\n\t\t\t\t// function-specific input data\n\t\t\t\tif (function == \"dtrsm\") {\n\t\t\t\t\tAqr = A.colPivHouseholderQr();\n\t\t\t\t} else if (function == \"dpotrf\") {\n\t\t\t\t\t// make sure A is SPD\n\t\t\t\t\tA = A.adjoint() * A;\n\t\t\t\t}\n\n\t\t\t\treal_time_acc = bench_accumulator();\n\t\t\t\tgflops_acc = bench_accumulator();\n\n\t\t\t\t// run the benchmark\n\t\t\t\trun_benchmark(N, warm_ups, num_runs, workload);\n\n\t\t\t\tfprintf(stdout, \"%d\\t%e\\t%e\\n\", N, mean(real_time_acc), mean(gflops_acc));\n\t\t\t\tfflush (stdout);\n\t\t\t\tfprintf(stderr, \"%d,%e,%e\\n\", N, mean(real_time_acc), mean(gflops_acc));\n\t\t\t\tfflush (stderr);\n\t\t\t}\n\t\t}\n\t\t\n\t\t// now is safe to clean up\n\t\tdelete pa;\n\t\tdelete pb;\n\t\tdelete pc;\n\n\t\tdelete pA;\n\t\tdelete pB;\n\t\tdelete pC;\n\t\tdelete pL;\n\n\t\tdelete pAqr;\n\n#if defined(EIGEN_USE_MAGMA_ALL)\n\t\tmagma_finalize();\n#endif\n\t}\n\tcatch (std::exception& e) {\n\t\tcerr << \"Exception: \" << e.what() << \"\\n\";\n\t\treturn EXIT_FAILURE;\n\t}\n\tcatch (...) {\n\t\tcerr << \"Exception of unknown type!\\n\";\n\t\treturn EXIT_FAILURE;\n\t}\n\n\treturn EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "cac927c61702dea2a875d71b1633caf97c4257d6", "size": 7950, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/main/cpp/benchmark_main.cc", "max_stars_repo_name": "bravegag/eigen-magma-benchmark", "max_stars_repo_head_hexsha": "a75d21cbf26a6cf69fc318f87fc12b649731b294", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2016-07-19T11:57:51.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-20T07:18:58.000Z", "max_issues_repo_path": "src/main/cpp/benchmark_main.cc", "max_issues_repo_name": "bravegag/eigen-magma-benchmark", "max_issues_repo_head_hexsha": "a75d21cbf26a6cf69fc318f87fc12b649731b294", "max_issues_repo_licenses": ["Apache-2.0"], "max_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/benchmark_main.cc", "max_forks_repo_name": "bravegag/eigen-magma-benchmark", "max_forks_repo_head_hexsha": "a75d21cbf26a6cf69fc318f87fc12b649731b294", "max_forks_repo_licenses": ["Apache-2.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.9090909091, "max_line_length": 112, "alphanum_fraction": 0.6597484277, "num_tokens": 2317, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.4787664196139861}}
{"text": "//\r\n//  Copyright (c) 2000-2002\r\n//  Joerg Walter, Mathias Koch\r\n//\r\n//  Distributed under the Boost Software License, Version 1.0. (See\r\n//  accompanying file LICENSE_1_0.txt or copy at\r\n//  http://www.boost.org/LICENSE_1_0.txt)\r\n//\r\n//  The authors gratefully acknowledge the support of\r\n//  GeNeSys mbH & Co. KG in producing this work.\r\n//\r\n\r\n#ifndef _BOOST_UBLAS_OPERATION_\r\n#define _BOOST_UBLAS_OPERATION_\r\n\r\n#include <boost/numeric/ublas/matrix_proxy.hpp>\r\n\r\n/** \\file operation.hpp\r\n *  \\brief This file contains some specialized products.\r\n */\r\n\r\n// axpy-based products\r\n// Alexei Novakov had a lot of ideas to improve these. Thanks.\r\n// Hendrik Kueck proposed some new kernel. Thanks again.\r\n\r\nnamespace boost { namespace numeric { namespace ublas {\r\n\r\n    template<class V, class T1, class L1, class IA1, class TA1, class E2>\r\n    BOOST_UBLAS_INLINE\r\n    V &\r\n    axpy_prod (const compressed_matrix<T1, L1, 0, IA1, TA1> &e1,\r\n               const vector_expression<E2> &e2,\r\n               V &v, row_major_tag) {\r\n        typedef typename V::size_type size_type;\r\n        typedef typename V::value_type value_type;\r\n\r\n        for (size_type i = 0; i < e1.filled1 () -1; ++ i) {\r\n            size_type begin = e1.index1_data () [i];\r\n            size_type end = e1.index1_data () [i + 1];\r\n            value_type t (v (i));\r\n            for (size_type j = begin; j < end; ++ j)\r\n                t += e1.value_data () [j] * e2 () (e1.index2_data () [j]);\r\n            v (i) = t;\r\n        }\r\n        return v;\r\n    }\r\n\r\n    template<class V, class T1, class L1, class IA1, class TA1, class E2>\r\n    BOOST_UBLAS_INLINE\r\n    V &\r\n    axpy_prod (const compressed_matrix<T1, L1, 0, IA1, TA1> &e1,\r\n               const vector_expression<E2> &e2,\r\n               V &v, column_major_tag) {\r\n        typedef typename V::size_type size_type;\r\n\r\n        for (size_type j = 0; j < e1.filled1 () -1; ++ j) {\r\n            size_type begin = e1.index1_data () [j];\r\n            size_type end = e1.index1_data () [j + 1];\r\n            for (size_type i = begin; i < end; ++ i)\r\n                v (e1.index2_data () [i]) += e1.value_data () [i] * e2 () (j);\r\n        }\r\n        return v;\r\n    }\r\n\r\n    // Dispatcher\r\n    template<class V, class T1, class L1, class IA1, class TA1, class E2>\r\n    BOOST_UBLAS_INLINE\r\n    V &\r\n    axpy_prod (const compressed_matrix<T1, L1, 0, IA1, TA1> &e1,\r\n               const vector_expression<E2> &e2,\r\n               V &v, bool init = true) {\r\n        typedef typename V::value_type value_type;\r\n        typedef typename L1::orientation_category orientation_category;\r\n\r\n        if (init)\r\n            v.assign (zero_vector<value_type> (e1.size1 ()));\r\n#if BOOST_UBLAS_TYPE_CHECK\r\n        vector<value_type> cv (v);\r\n        typedef typename type_traits<value_type>::real_type real_type;\r\n        real_type verrorbound (norm_1 (v) + norm_1 (e1) * norm_1 (e2));\r\n        indexing_vector_assign<scalar_plus_assign> (cv, prod (e1, e2));\r\n#endif\r\n        axpy_prod (e1, e2, v, orientation_category ());\r\n#if BOOST_UBLAS_TYPE_CHECK\r\n        BOOST_UBLAS_CHECK (norm_1 (v - cv) <= 2 * std::numeric_limits<real_type>::epsilon () * verrorbound, internal_logic ());\r\n#endif\r\n        return v;\r\n    }\r\n    template<class V, class T1, class L1, class IA1, class TA1, class E2>\r\n    BOOST_UBLAS_INLINE\r\n    V\r\n    axpy_prod (const compressed_matrix<T1, L1, 0, IA1, TA1> &e1,\r\n               const vector_expression<E2> &e2) {\r\n        typedef V vector_type;\r\n\r\n        vector_type v (e1.size1 ());\r\n        return axpy_prod (e1, e2, v, true);\r\n    }\r\n\r\n    template<class V, class T1, class L1, class IA1, class TA1, class E2>\r\n    BOOST_UBLAS_INLINE\r\n    V &\r\n    axpy_prod (const coordinate_matrix<T1, L1, 0, IA1, TA1> &e1,\r\n               const vector_expression<E2> &e2,\r\n               V &v, bool init = true) {\r\n        typedef typename V::size_type size_type;\r\n        typedef typename V::value_type value_type;\r\n        typedef L1 layout_type;\r\n\r\n        size_type size1 = e1.size1();\r\n        size_type size2 = e1.size2();\r\n\r\n        if (init) {\r\n            noalias(v) = zero_vector<value_type>(size1);\r\n        }\r\n\r\n        for (size_type i = 0; i < e1.nnz(); ++i) {\r\n            size_type row_index = layout_type::index_M( e1.index1_data () [i], e1.index2_data () [i] );\r\n            size_type col_index = layout_type::index_m( e1.index1_data () [i], e1.index2_data () [i] );\r\n            v( row_index ) += e1.value_data () [i] * e2 () (col_index);\r\n        }\r\n        return v;\r\n    }\r\n\r\n    template<class V, class E1, class E2>\r\n    BOOST_UBLAS_INLINE\r\n    V &\r\n    axpy_prod (const matrix_expression<E1> &e1,\r\n               const vector_expression<E2> &e2,\r\n               V &v, packed_random_access_iterator_tag, row_major_tag) {\r\n        typedef const E1 expression1_type;\r\n        typedef typename V::size_type size_type;\r\n\r\n        typename expression1_type::const_iterator1 it1 (e1 ().begin1 ());\r\n        typename expression1_type::const_iterator1 it1_end (e1 ().end1 ());\r\n        while (it1 != it1_end) {\r\n            size_type index1 (it1.index1 ());\r\n#ifndef BOOST_UBLAS_NO_NESTED_CLASS_RELATION\r\n            typename expression1_type::const_iterator2 it2 (it1.begin ());\r\n            typename expression1_type::const_iterator2 it2_end (it1.end ());\r\n#else\r\n            typename expression1_type::const_iterator2 it2 (boost::numeric::ublas::begin (it1, iterator1_tag ()));\r\n            typename expression1_type::const_iterator2 it2_end (boost::numeric::ublas::end (it1, iterator1_tag ()));\r\n#endif\r\n            while (it2 != it2_end) {\r\n                v (index1) += *it2 * e2 () (it2.index2 ());\r\n                ++ it2;\r\n            }\r\n            ++ it1;\r\n        }\r\n        return v;\r\n    }\r\n\r\n    template<class V, class E1, class E2>\r\n    BOOST_UBLAS_INLINE\r\n    V &\r\n    axpy_prod (const matrix_expression<E1> &e1,\r\n               const vector_expression<E2> &e2,\r\n               V &v, packed_random_access_iterator_tag, column_major_tag) {\r\n        typedef const E1 expression1_type;\r\n        typedef typename V::size_type size_type;\r\n\r\n        typename expression1_type::const_iterator2 it2 (e1 ().begin2 ());\r\n        typename expression1_type::const_iterator2 it2_end (e1 ().end2 ());\r\n        while (it2 != it2_end) {\r\n            size_type index2 (it2.index2 ());\r\n#ifndef BOOST_UBLAS_NO_NESTED_CLASS_RELATION\r\n            typename expression1_type::const_iterator1 it1 (it2.begin ());\r\n            typename expression1_type::const_iterator1 it1_end (it2.end ());\r\n#else\r\n            typename expression1_type::const_iterator1 it1 (boost::numeric::ublas::begin (it2, iterator2_tag ()));\r\n            typename expression1_type::const_iterator1 it1_end (boost::numeric::ublas::end (it2, iterator2_tag ()));\r\n#endif\r\n            while (it1 != it1_end) {\r\n                v (it1.index1 ()) += *it1 * e2 () (index2);\r\n                ++ it1;\r\n            }\r\n            ++ it2;\r\n        }\r\n        return v;\r\n    }\r\n\r\n    template<class V, class E1, class E2>\r\n    BOOST_UBLAS_INLINE\r\n    V &\r\n    axpy_prod (const matrix_expression<E1> &e1,\r\n               const vector_expression<E2> &e2,\r\n               V &v, sparse_bidirectional_iterator_tag) {\r\n        typedef const E2 expression2_type;\r\n\r\n        typename expression2_type::const_iterator it (e2 ().begin ());\r\n        typename expression2_type::const_iterator it_end (e2 ().end ());\r\n        while (it != it_end) {\r\n            v.plus_assign (column (e1 (), it.index ()) * *it);\r\n            ++ it;\r\n        }\r\n        return v;\r\n    }\r\n\r\n    // Dispatcher\r\n    template<class V, class E1, class E2>\r\n    BOOST_UBLAS_INLINE\r\n    V &\r\n    axpy_prod (const matrix_expression<E1> &e1,\r\n               const vector_expression<E2> &e2,\r\n               V &v, packed_random_access_iterator_tag) {\r\n        typedef typename E1::orientation_category orientation_category;\r\n        return axpy_prod (e1, e2, v, packed_random_access_iterator_tag (), orientation_category ());\r\n    }\r\n\r\n\r\n  /** \\brief computes <tt>v += A x</tt> or <tt>v = A x</tt> in an\r\n          optimized fashion.\r\n\r\n          \\param e1 the matrix expression \\c A\r\n          \\param e2 the vector expression \\c x\r\n          \\param v  the result vector \\c v\r\n          \\param init a boolean parameter\r\n\r\n          <tt>axpy_prod(A, x, v, init)</tt> implements the well known\r\n          axpy-product.  Setting \\a init to \\c true is equivalent to call\r\n          <tt>v.clear()</tt> before <tt>axpy_prod</tt>. Currently \\a init\r\n          defaults to \\c true, but this may change in the future.\r\n\r\n          Up to now there are some specialisation for compressed\r\n          matrices that give a large speed up compared to prod.\r\n          \r\n          \\ingroup blas2\r\n\r\n          \\internal\r\n          \r\n          template parameters:\r\n          \\param V type of the result vector \\c v\r\n          \\param E1 type of a matrix expression \\c A\r\n          \\param E2 type of a vector expression \\c x\r\n  */\r\n    template<class V, class E1, class E2>\r\n    BOOST_UBLAS_INLINE\r\n    V &\r\n    axpy_prod (const matrix_expression<E1> &e1,\r\n               const vector_expression<E2> &e2,\r\n               V &v, bool init = true) {\r\n        typedef typename V::value_type value_type;\r\n        typedef typename E2::const_iterator::iterator_category iterator_category;\r\n\r\n        if (init)\r\n            v.assign (zero_vector<value_type> (e1 ().size1 ()));\r\n#if BOOST_UBLAS_TYPE_CHECK\r\n        vector<value_type> cv (v);\r\n        typedef typename type_traits<value_type>::real_type real_type;\r\n        real_type verrorbound (norm_1 (v) + norm_1 (e1) * norm_1 (e2));\r\n        indexing_vector_assign<scalar_plus_assign> (cv, prod (e1, e2));\r\n#endif\r\n        axpy_prod (e1, e2, v, iterator_category ());\r\n#if BOOST_UBLAS_TYPE_CHECK\r\n        BOOST_UBLAS_CHECK (norm_1 (v - cv) <= 2 * std::numeric_limits<real_type>::epsilon () * verrorbound, internal_logic ());\r\n#endif\r\n        return v;\r\n    }\r\n    template<class V, class E1, class E2>\r\n    BOOST_UBLAS_INLINE\r\n    V\r\n    axpy_prod (const matrix_expression<E1> &e1,\r\n               const vector_expression<E2> &e2) {\r\n        typedef V vector_type;\r\n\r\n        vector_type v (e1 ().size1 ());\r\n        return axpy_prod (e1, e2, v, true);\r\n    }\r\n\r\n    template<class V, class E1, class T2, class IA2, class TA2>\r\n    BOOST_UBLAS_INLINE\r\n    V &\r\n    axpy_prod (const vector_expression<E1> &e1,\r\n               const compressed_matrix<T2, column_major, 0, IA2, TA2> &e2,\r\n               V &v, column_major_tag) {\r\n        typedef typename V::size_type size_type;\r\n        typedef typename V::value_type value_type;\r\n\r\n        for (size_type j = 0; j < e2.filled1 () -1; ++ j) {\r\n            size_type begin = e2.index1_data () [j];\r\n            size_type end = e2.index1_data () [j + 1];\r\n            value_type t (v (j));\r\n            for (size_type i = begin; i < end; ++ i)\r\n                t += e2.value_data () [i] * e1 () (e2.index2_data () [i]);\r\n            v (j) = t;\r\n        }\r\n        return v;\r\n    }\r\n\r\n    template<class V, class E1, class T2, class IA2, class TA2>\r\n    BOOST_UBLAS_INLINE\r\n    V &\r\n    axpy_prod (const vector_expression<E1> &e1,\r\n               const compressed_matrix<T2, row_major, 0, IA2, TA2> &e2,\r\n               V &v, row_major_tag) {\r\n        typedef typename V::size_type size_type;\r\n\r\n        for (size_type i = 0; i < e2.filled1 () -1; ++ i) {\r\n            size_type begin = e2.index1_data () [i];\r\n            size_type end = e2.index1_data () [i + 1];\r\n            for (size_type j = begin; j < end; ++ j)\r\n                v (e2.index2_data () [j]) += e2.value_data () [j] * e1 () (i);\r\n        }\r\n        return v;\r\n    }\r\n\r\n    // Dispatcher\r\n    template<class V, class E1, class T2, class L2, class IA2, class TA2>\r\n    BOOST_UBLAS_INLINE\r\n    V &\r\n    axpy_prod (const vector_expression<E1> &e1,\r\n               const compressed_matrix<T2, L2, 0, IA2, TA2> &e2,\r\n               V &v, bool init = true) {\r\n        typedef typename V::value_type value_type;\r\n        typedef typename L2::orientation_category orientation_category;\r\n\r\n        if (init)\r\n            v.assign (zero_vector<value_type> (e2.size2 ()));\r\n#if BOOST_UBLAS_TYPE_CHECK\r\n        vector<value_type> cv (v);\r\n        typedef typename type_traits<value_type>::real_type real_type;\r\n        real_type verrorbound (norm_1 (v) + norm_1 (e1) * norm_1 (e2));\r\n        indexing_vector_assign<scalar_plus_assign> (cv, prod (e1, e2));\r\n#endif\r\n        axpy_prod (e1, e2, v, orientation_category ());\r\n#if BOOST_UBLAS_TYPE_CHECK\r\n        BOOST_UBLAS_CHECK (norm_1 (v - cv) <= 2 * std::numeric_limits<real_type>::epsilon () * verrorbound, internal_logic ());\r\n#endif\r\n        return v;\r\n    }\r\n    template<class V, class E1, class T2, class L2, class IA2, class TA2>\r\n    BOOST_UBLAS_INLINE\r\n    V\r\n    axpy_prod (const vector_expression<E1> &e1,\r\n               const compressed_matrix<T2, L2, 0, IA2, TA2> &e2) {\r\n        typedef V vector_type;\r\n\r\n        vector_type v (e2.size2 ());\r\n        return axpy_prod (e1, e2, v, true);\r\n    }\r\n\r\n    template<class V, class E1, class E2>\r\n    BOOST_UBLAS_INLINE\r\n    V &\r\n    axpy_prod (const vector_expression<E1> &e1,\r\n               const matrix_expression<E2> &e2,\r\n               V &v, packed_random_access_iterator_tag, column_major_tag) {\r\n        typedef const E2 expression2_type;\r\n        typedef typename V::size_type size_type;\r\n\r\n        typename expression2_type::const_iterator2 it2 (e2 ().begin2 ());\r\n        typename expression2_type::const_iterator2 it2_end (e2 ().end2 ());\r\n        while (it2 != it2_end) {\r\n            size_type index2 (it2.index2 ());\r\n#ifndef BOOST_UBLAS_NO_NESTED_CLASS_RELATION\r\n            typename expression2_type::const_iterator1 it1 (it2.begin ());\r\n            typename expression2_type::const_iterator1 it1_end (it2.end ());\r\n#else\r\n            typename expression2_type::const_iterator1 it1 (boost::numeric::ublas::begin (it2, iterator2_tag ()));\r\n            typename expression2_type::const_iterator1 it1_end (boost::numeric::ublas::end (it2, iterator2_tag ()));\r\n#endif\r\n            while (it1 != it1_end) {\r\n                v (index2) += *it1 * e1 () (it1.index1 ());\r\n                ++ it1;\r\n            }\r\n            ++ it2;\r\n        }\r\n        return v;\r\n    }\r\n\r\n    template<class V, class E1, class E2>\r\n    BOOST_UBLAS_INLINE\r\n    V &\r\n    axpy_prod (const vector_expression<E1> &e1,\r\n               const matrix_expression<E2> &e2,\r\n               V &v, packed_random_access_iterator_tag, row_major_tag) {\r\n        typedef const E2 expression2_type;\r\n        typedef typename V::size_type size_type;\r\n\r\n        typename expression2_type::const_iterator1 it1 (e2 ().begin1 ());\r\n        typename expression2_type::const_iterator1 it1_end (e2 ().end1 ());\r\n        while (it1 != it1_end) {\r\n            size_type index1 (it1.index1 ());\r\n#ifndef BOOST_UBLAS_NO_NESTED_CLASS_RELATION\r\n            typename expression2_type::const_iterator2 it2 (it1.begin ());\r\n            typename expression2_type::const_iterator2 it2_end (it1.end ());\r\n#else\r\n            typename expression2_type::const_iterator2 it2 (boost::numeric::ublas::begin (it1, iterator1_tag ()));\r\n            typename expression2_type::const_iterator2 it2_end (boost::numeric::ublas::end (it1, iterator1_tag ()));\r\n#endif\r\n            while (it2 != it2_end) {\r\n                v (it2.index2 ()) += *it2 * e1 () (index1);\r\n                ++ it2;\r\n            }\r\n            ++ it1;\r\n        }\r\n        return v;\r\n    }\r\n\r\n    template<class V, class E1, class E2>\r\n    BOOST_UBLAS_INLINE\r\n    V &\r\n    axpy_prod (const vector_expression<E1> &e1,\r\n               const matrix_expression<E2> &e2,\r\n               V &v, sparse_bidirectional_iterator_tag) {\r\n        typedef const E1 expression1_type;\r\n\r\n        typename expression1_type::const_iterator it (e1 ().begin ());\r\n        typename expression1_type::const_iterator it_end (e1 ().end ());\r\n        while (it != it_end) {\r\n            v.plus_assign (*it * row (e2 (), it.index ()));\r\n            ++ it;\r\n        }\r\n        return v;\r\n    }\r\n\r\n    // Dispatcher\r\n    template<class V, class E1, class E2>\r\n    BOOST_UBLAS_INLINE\r\n    V &\r\n    axpy_prod (const vector_expression<E1> &e1,\r\n               const matrix_expression<E2> &e2,\r\n               V &v, packed_random_access_iterator_tag) {\r\n        typedef typename E2::orientation_category orientation_category;\r\n        return axpy_prod (e1, e2, v, packed_random_access_iterator_tag (), orientation_category ());\r\n    }\r\n\r\n\r\n  /** \\brief computes <tt>v += A<sup>T</sup> x</tt> or <tt>v = A<sup>T</sup> x</tt> in an\r\n          optimized fashion.\r\n\r\n          \\param e1 the vector expression \\c x\r\n          \\param e2 the matrix expression \\c A\r\n          \\param v  the result vector \\c v\r\n          \\param init a boolean parameter\r\n\r\n          <tt>axpy_prod(x, A, v, init)</tt> implements the well known\r\n          axpy-product.  Setting \\a init to \\c true is equivalent to call\r\n          <tt>v.clear()</tt> before <tt>axpy_prod</tt>. Currently \\a init\r\n          defaults to \\c true, but this may change in the future.\r\n\r\n          Up to now there are some specialisation for compressed\r\n          matrices that give a large speed up compared to prod.\r\n          \r\n          \\ingroup blas2\r\n\r\n          \\internal\r\n          \r\n          template parameters:\r\n          \\param V type of the result vector \\c v\r\n          \\param E1 type of a vector expression \\c x\r\n          \\param E2 type of a matrix expression \\c A\r\n  */\r\n    template<class V, class E1, class E2>\r\n    BOOST_UBLAS_INLINE\r\n    V &\r\n    axpy_prod (const vector_expression<E1> &e1,\r\n               const matrix_expression<E2> &e2,\r\n               V &v, bool init = true) {\r\n        typedef typename V::value_type value_type;\r\n        typedef typename E1::const_iterator::iterator_category iterator_category;\r\n\r\n        if (init)\r\n            v.assign (zero_vector<value_type> (e2 ().size2 ()));\r\n#if BOOST_UBLAS_TYPE_CHECK\r\n        vector<value_type> cv (v);\r\n        typedef typename type_traits<value_type>::real_type real_type;\r\n        real_type verrorbound (norm_1 (v) + norm_1 (e1) * norm_1 (e2));\r\n        indexing_vector_assign<scalar_plus_assign> (cv, prod (e1, e2));\r\n#endif\r\n        axpy_prod (e1, e2, v, iterator_category ());\r\n#if BOOST_UBLAS_TYPE_CHECK\r\n        BOOST_UBLAS_CHECK (norm_1 (v - cv) <= 2 * std::numeric_limits<real_type>::epsilon () * verrorbound, internal_logic ());\r\n#endif\r\n        return v;\r\n    }\r\n    template<class V, class E1, class E2>\r\n    BOOST_UBLAS_INLINE\r\n    V\r\n    axpy_prod (const vector_expression<E1> &e1,\r\n               const matrix_expression<E2> &e2) {\r\n        typedef V vector_type;\r\n\r\n        vector_type v (e2 ().size2 ());\r\n        return axpy_prod (e1, e2, v, true);\r\n    }\r\n\r\n    template<class M, class E1, class E2, class TRI>\r\n    BOOST_UBLAS_INLINE\r\n    M &\r\n    axpy_prod (const matrix_expression<E1> &e1,\r\n               const matrix_expression<E2> &e2,\r\n               M &m, TRI,\r\n               dense_proxy_tag, row_major_tag) {\r\n\r\n        typedef typename M::size_type size_type;\r\n\r\n#if BOOST_UBLAS_TYPE_CHECK\r\n        typedef typename M::value_type value_type;\r\n        matrix<value_type, row_major> cm (m);\r\n        typedef typename type_traits<value_type>::real_type real_type;\r\n        real_type merrorbound (norm_1 (m) + norm_1 (e1) * norm_1 (e2));\r\n        indexing_matrix_assign<scalar_plus_assign> (cm, prod (e1, e2), row_major_tag ());\r\n#endif\r\n        size_type size1 (e1 ().size1 ());\r\n        size_type size2 (e1 ().size2 ());\r\n        for (size_type i = 0; i < size1; ++ i)\r\n            for (size_type j = 0; j < size2; ++ j)\r\n                row (m, i).plus_assign (e1 () (i, j) * row (e2 (), j));\r\n#if BOOST_UBLAS_TYPE_CHECK\r\n        BOOST_UBLAS_CHECK (norm_1 (m - cm) <= 2 * std::numeric_limits<real_type>::epsilon () * merrorbound, internal_logic ());\r\n#endif\r\n        return m;\r\n    }\r\n    template<class M, class E1, class E2, class TRI>\r\n    BOOST_UBLAS_INLINE\r\n    M &\r\n    axpy_prod (const matrix_expression<E1> &e1,\r\n               const matrix_expression<E2> &e2,\r\n               M &m, TRI,\r\n               sparse_proxy_tag, row_major_tag) {\r\n\r\n        typedef TRI triangular_restriction;\r\n        typedef const E1 expression1_type;\r\n        typedef const E2 expression2_type;\r\n\r\n#if BOOST_UBLAS_TYPE_CHECK\r\n        typedef typename M::value_type value_type;\r\n        matrix<value_type, row_major> cm (m);\r\n        typedef typename type_traits<value_type>::real_type real_type;\r\n        real_type merrorbound (norm_1 (m) + norm_1 (e1) * norm_1 (e2));\r\n        indexing_matrix_assign<scalar_plus_assign> (cm, prod (e1, e2), row_major_tag ());\r\n#endif\r\n        typename expression1_type::const_iterator1 it1 (e1 ().begin1 ());\r\n        typename expression1_type::const_iterator1 it1_end (e1 ().end1 ());\r\n        while (it1 != it1_end) {\r\n#ifndef BOOST_UBLAS_NO_NESTED_CLASS_RELATION\r\n            typename expression1_type::const_iterator2 it2 (it1.begin ());\r\n            typename expression1_type::const_iterator2 it2_end (it1.end ());\r\n#else\r\n            typename expression1_type::const_iterator2 it2 (boost::numeric::ublas::begin (it1, iterator1_tag ()));\r\n            typename expression1_type::const_iterator2 it2_end (boost::numeric::ublas::end (it1, iterator1_tag ()));\r\n#endif\r\n            while (it2 != it2_end) {\r\n                // row (m, it1.index1 ()).plus_assign (*it2 * row (e2 (), it2.index2 ()));\r\n                matrix_row<expression2_type> mr (e2 (), it2.index2 ());\r\n                typename matrix_row<expression2_type>::const_iterator itr (mr.begin ());\r\n                typename matrix_row<expression2_type>::const_iterator itr_end (mr.end ());\r\n                while (itr != itr_end) {\r\n                    if (triangular_restriction::other (it1.index1 (), itr.index ()))\r\n                        m (it1.index1 (), itr.index ()) += *it2 * *itr;\r\n                    ++ itr;\r\n                }\r\n                ++ it2;\r\n            }\r\n            ++ it1;\r\n        }\r\n#if BOOST_UBLAS_TYPE_CHECK\r\n        BOOST_UBLAS_CHECK (norm_1 (m - cm) <= 2 * std::numeric_limits<real_type>::epsilon () * merrorbound, internal_logic ());\r\n#endif\r\n        return m;\r\n    }\r\n\r\n    template<class M, class E1, class E2, class TRI>\r\n    BOOST_UBLAS_INLINE\r\n    M &\r\n    axpy_prod (const matrix_expression<E1> &e1,\r\n               const matrix_expression<E2> &e2,\r\n               M &m, TRI,\r\n               dense_proxy_tag, column_major_tag) {\r\n        typedef typename M::size_type size_type;\r\n\r\n#if BOOST_UBLAS_TYPE_CHECK\r\n        typedef typename M::value_type value_type;\r\n        matrix<value_type, column_major> cm (m);\r\n        typedef typename type_traits<value_type>::real_type real_type;\r\n        real_type merrorbound (norm_1 (m) + norm_1 (e1) * norm_1 (e2));\r\n        indexing_matrix_assign<scalar_plus_assign> (cm, prod (e1, e2), column_major_tag ());\r\n#endif\r\n        size_type size1 (e2 ().size1 ());\r\n        size_type size2 (e2 ().size2 ());\r\n        for (size_type j = 0; j < size2; ++ j)\r\n            for (size_type i = 0; i < size1; ++ i)\r\n                column (m, j).plus_assign (e2 () (i, j) * column (e1 (), i));\r\n#if BOOST_UBLAS_TYPE_CHECK\r\n        BOOST_UBLAS_CHECK (norm_1 (m - cm) <= 2 * std::numeric_limits<real_type>::epsilon () * merrorbound, internal_logic ());\r\n#endif\r\n        return m;\r\n    }\r\n    template<class M, class E1, class E2, class TRI>\r\n    BOOST_UBLAS_INLINE\r\n    M &\r\n    axpy_prod (const matrix_expression<E1> &e1,\r\n               const matrix_expression<E2> &e2,\r\n               M &m, TRI,\r\n               sparse_proxy_tag, column_major_tag) {\r\n        typedef TRI triangular_restriction;\r\n        typedef const E1 expression1_type;\r\n        typedef const E2 expression2_type;\r\n\r\n\r\n#if BOOST_UBLAS_TYPE_CHECK\r\n        typedef typename M::value_type value_type;\r\n        matrix<value_type, column_major> cm (m);\r\n        typedef typename type_traits<value_type>::real_type real_type;\r\n        real_type merrorbound (norm_1 (m) + norm_1 (e1) * norm_1 (e2));\r\n        indexing_matrix_assign<scalar_plus_assign> (cm, prod (e1, e2), column_major_tag ());\r\n#endif\r\n        typename expression2_type::const_iterator2 it2 (e2 ().begin2 ());\r\n        typename expression2_type::const_iterator2 it2_end (e2 ().end2 ());\r\n        while (it2 != it2_end) {\r\n#ifndef BOOST_UBLAS_NO_NESTED_CLASS_RELATION\r\n            typename expression2_type::const_iterator1 it1 (it2.begin ());\r\n            typename expression2_type::const_iterator1 it1_end (it2.end ());\r\n#else\r\n            typename expression2_type::const_iterator1 it1 (boost::numeric::ublas::begin (it2, iterator2_tag ()));\r\n            typename expression2_type::const_iterator1 it1_end (boost::numeric::ublas::end (it2, iterator2_tag ()));\r\n#endif\r\n            while (it1 != it1_end) {\r\n                // column (m, it2.index2 ()).plus_assign (*it1 * column (e1 (), it1.index1 ()));\r\n                matrix_column<expression1_type> mc (e1 (), it1.index1 ());\r\n                typename matrix_column<expression1_type>::const_iterator itc (mc.begin ());\r\n                typename matrix_column<expression1_type>::const_iterator itc_end (mc.end ());\r\n                while (itc != itc_end) {\r\n                    if(triangular_restriction::other (itc.index (), it2.index2 ()))\r\n                       m (itc.index (), it2.index2 ()) += *it1 * *itc;\r\n                    ++ itc;\r\n                }\r\n                ++ it1;\r\n            }\r\n            ++ it2;\r\n        }\r\n#if BOOST_UBLAS_TYPE_CHECK\r\n        BOOST_UBLAS_CHECK (norm_1 (m - cm) <= 2 * std::numeric_limits<real_type>::epsilon () * merrorbound, internal_logic ());\r\n#endif\r\n        return m;\r\n    }\r\n\r\n    // Dispatcher\r\n    template<class M, class E1, class E2, class TRI>\r\n    BOOST_UBLAS_INLINE\r\n    M &\r\n    axpy_prod (const matrix_expression<E1> &e1,\r\n               const matrix_expression<E2> &e2,\r\n               M &m, TRI, bool init = true) {\r\n        typedef typename M::value_type value_type;\r\n        typedef typename M::storage_category storage_category;\r\n        typedef typename M::orientation_category orientation_category;\r\n        typedef TRI triangular_restriction;\r\n\r\n        if (init)\r\n            m.assign (zero_matrix<value_type> (e1 ().size1 (), e2 ().size2 ()));\r\n        return axpy_prod (e1, e2, m, triangular_restriction (), storage_category (), orientation_category ());\r\n    }\r\n    template<class M, class E1, class E2, class TRI>\r\n    BOOST_UBLAS_INLINE\r\n    M\r\n    axpy_prod (const matrix_expression<E1> &e1,\r\n               const matrix_expression<E2> &e2,\r\n               TRI) {\r\n        typedef M matrix_type;\r\n        typedef TRI triangular_restriction;\r\n\r\n        matrix_type m (e1 ().size1 (), e2 ().size2 ());\r\n        return axpy_prod (e1, e2, m, triangular_restriction (), true);\r\n    }\r\n\r\n  /** \\brief computes <tt>M += A X</tt> or <tt>M = A X</tt> in an\r\n          optimized fashion.\r\n\r\n          \\param e1 the matrix expression \\c A\r\n          \\param e2 the matrix expression \\c X\r\n          \\param m  the result matrix \\c M\r\n          \\param init a boolean parameter\r\n\r\n          <tt>axpy_prod(A, X, M, init)</tt> implements the well known\r\n          axpy-product.  Setting \\a init to \\c true is equivalent to call\r\n          <tt>M.clear()</tt> before <tt>axpy_prod</tt>. Currently \\a init\r\n          defaults to \\c true, but this may change in the future.\r\n\r\n          Up to now there are no specialisations.\r\n          \r\n          \\ingroup blas3\r\n\r\n          \\internal\r\n          \r\n          template parameters:\r\n          \\param M type of the result matrix \\c M\r\n          \\param E1 type of a matrix expression \\c A\r\n          \\param E2 type of a matrix expression \\c X\r\n  */\r\n    template<class M, class E1, class E2>\r\n    BOOST_UBLAS_INLINE\r\n    M &\r\n    axpy_prod (const matrix_expression<E1> &e1,\r\n               const matrix_expression<E2> &e2,\r\n               M &m, bool init = true) {\r\n        typedef typename M::value_type value_type;\r\n        typedef typename M::storage_category storage_category;\r\n        typedef typename M::orientation_category orientation_category;\r\n\r\n        if (init)\r\n            m.assign (zero_matrix<value_type> (e1 ().size1 (), e2 ().size2 ()));\r\n        return axpy_prod (e1, e2, m, full (), storage_category (), orientation_category ());\r\n    }\r\n    template<class M, class E1, class E2>\r\n    BOOST_UBLAS_INLINE\r\n    M\r\n    axpy_prod (const matrix_expression<E1> &e1,\r\n               const matrix_expression<E2> &e2) {\r\n        typedef M matrix_type;\r\n\r\n        matrix_type m (e1 ().size1 (), e2 ().size2 ());\r\n        return axpy_prod (e1, e2, m, full (), true);\r\n    }\r\n\r\n\r\n    template<class M, class E1, class E2>\r\n    BOOST_UBLAS_INLINE\r\n    M &\r\n    opb_prod (const matrix_expression<E1> &e1,\r\n              const matrix_expression<E2> &e2,\r\n              M &m,\r\n              dense_proxy_tag, row_major_tag) {\r\n        typedef typename M::size_type size_type;\r\n        typedef typename M::value_type value_type;\r\n\r\n#if BOOST_UBLAS_TYPE_CHECK\r\n        matrix<value_type, row_major> cm (m);\r\n        typedef typename type_traits<value_type>::real_type real_type;\r\n        real_type merrorbound (norm_1 (m) + norm_1 (e1) * norm_1 (e2));\r\n        indexing_matrix_assign<scalar_plus_assign> (cm, prod (e1, e2), row_major_tag ());\r\n#endif\r\n        size_type size (BOOST_UBLAS_SAME (e1 ().size2 (), e2 ().size1 ()));\r\n        for (size_type k = 0; k < size; ++ k) {\r\n            vector<value_type> ce1 (column (e1 (), k));\r\n            vector<value_type> re2 (row (e2 (), k));\r\n            m.plus_assign (outer_prod (ce1, re2));\r\n        }\r\n#if BOOST_UBLAS_TYPE_CHECK\r\n        BOOST_UBLAS_CHECK (norm_1 (m - cm) <= 2 * std::numeric_limits<real_type>::epsilon () * merrorbound, internal_logic ());\r\n#endif\r\n        return m;\r\n    }\r\n\r\n    template<class M, class E1, class E2>\r\n    BOOST_UBLAS_INLINE\r\n    M &\r\n    opb_prod (const matrix_expression<E1> &e1,\r\n              const matrix_expression<E2> &e2,\r\n              M &m,\r\n              dense_proxy_tag, column_major_tag) {\r\n        typedef typename M::size_type size_type;\r\n        typedef typename M::value_type value_type;\r\n\r\n#if BOOST_UBLAS_TYPE_CHECK\r\n        matrix<value_type, column_major> cm (m);\r\n        typedef typename type_traits<value_type>::real_type real_type;\r\n        real_type merrorbound (norm_1 (m) + norm_1 (e1) * norm_1 (e2));\r\n        indexing_matrix_assign<scalar_plus_assign> (cm, prod (e1, e2), column_major_tag ());\r\n#endif\r\n        size_type size (BOOST_UBLAS_SAME (e1 ().size2 (), e2 ().size1 ()));\r\n        for (size_type k = 0; k < size; ++ k) {\r\n            vector<value_type> ce1 (column (e1 (), k));\r\n            vector<value_type> re2 (row (e2 (), k));\r\n            m.plus_assign (outer_prod (ce1, re2));\r\n        }\r\n#if BOOST_UBLAS_TYPE_CHECK\r\n        BOOST_UBLAS_CHECK (norm_1 (m - cm) <= 2 * std::numeric_limits<real_type>::epsilon () * merrorbound, internal_logic ());\r\n#endif\r\n        return m;\r\n    }\r\n\r\n    // Dispatcher\r\n\r\n  /** \\brief computes <tt>M += A X</tt> or <tt>M = A X</tt> in an\r\n          optimized fashion.\r\n\r\n          \\param e1 the matrix expression \\c A\r\n          \\param e2 the matrix expression \\c X\r\n          \\param m  the result matrix \\c M\r\n          \\param init a boolean parameter\r\n\r\n          <tt>opb_prod(A, X, M, init)</tt> implements the well known\r\n          axpy-product. Setting \\a init to \\c true is equivalent to call\r\n          <tt>M.clear()</tt> before <tt>opb_prod</tt>. Currently \\a init\r\n          defaults to \\c true, but this may change in the future.\r\n\r\n          This function may give a speedup if \\c A has less columns than\r\n          rows, because the product is computed as a sum of outer\r\n          products.\r\n          \r\n          \\ingroup blas3\r\n\r\n          \\internal\r\n          \r\n          template parameters:\r\n          \\param M type of the result matrix \\c M\r\n          \\param E1 type of a matrix expression \\c A\r\n          \\param E2 type of a matrix expression \\c X\r\n  */\r\n    template<class M, class E1, class E2>\r\n    BOOST_UBLAS_INLINE\r\n    M &\r\n    opb_prod (const matrix_expression<E1> &e1,\r\n              const matrix_expression<E2> &e2,\r\n              M &m, bool init = true) {\r\n        typedef typename M::value_type value_type;\r\n        typedef typename M::storage_category storage_category;\r\n        typedef typename M::orientation_category orientation_category;\r\n\r\n        if (init)\r\n            m.assign (zero_matrix<value_type> (e1 ().size1 (), e2 ().size2 ()));\r\n        return opb_prod (e1, e2, m, storage_category (), orientation_category ());\r\n    }\r\n    template<class M, class E1, class E2>\r\n    BOOST_UBLAS_INLINE\r\n    M\r\n    opb_prod (const matrix_expression<E1> &e1,\r\n              const matrix_expression<E2> &e2) {\r\n        typedef M matrix_type;\r\n\r\n        matrix_type m (e1 ().size1 (), e2 ().size2 ());\r\n        return opb_prod (e1, e2, m, true);\r\n    }\r\n\r\n}}}\r\n\r\n#endif\r\n", "meta": {"hexsha": "81438db74884f79eaf5bad5f74e64a7cff19b2e8", "size": 32940, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ios/Pods/boost-for-react-native/boost/numeric/ublas/operation.hpp", "max_stars_repo_name": "rudylee/expo", "max_stars_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_stars_repo_licenses": ["Apache-2.0", "MIT"], "max_stars_count": 8805.0, "max_stars_repo_stars_event_min_datetime": "2015-11-03T00:52:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T22:30:03.000Z", "max_issues_repo_path": "ios/Pods/boost-for-react-native/boost/numeric/ublas/operation.hpp", "max_issues_repo_name": "rudylee/expo", "max_issues_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_issues_repo_licenses": ["Apache-2.0", "MIT"], "max_issues_count": 14694.0, "max_issues_repo_issues_event_min_datetime": "2015-02-24T15:13:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T13:16:45.000Z", "max_forks_repo_path": "ios/Pods/boost-for-react-native/boost/numeric/ublas/operation.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.6389891697, "max_line_length": 128, "alphanum_fraction": 0.5854887675, "num_tokens": 8674, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585903489892, "lm_q2_score": 0.6548947290421276, "lm_q1q2_score": 0.4787664174405211}}
{"text": "/* boost random/mersenne_twister.hpp header file\n *\n * Copyright Jens Maurer 2000-2001\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: mersenne_twister.hpp,v 1.20 2005/07/21 22:04:31 jmaurer Exp $\n *\n * Revision history\n *  2001-02-18  moved to individual header files\n */\n\n#ifndef BOOST_RANDOM_MERSENNE_TWISTER_HPP\n#define BOOST_RANDOM_MERSENNE_TWISTER_HPP\n\n#include <iostream>\n#include <algorithm>     // std::copy\n#include <stdexcept>\n#include <boost/config.hpp>\n#include <boost/limits.hpp>\n#include <boost/static_assert.hpp>\n#include <boost/integer_traits.hpp>\n#include <boost/cstdint.hpp>\n#include <boost/random/linear_congruential.hpp>\n#include <boost/detail/workaround.hpp>\n#include <boost/random/detail/ptr_helper.hpp>\n\nnamespace boost {\nnamespace random {\n\n// http://www.math.keio.ac.jp/matumoto/emt.html\ntemplate<class UIntType, int w, int n, int m, int r, UIntType a, int u,\n  int s, UIntType b, int t, UIntType c, int l, UIntType val>\nclass mersenne_twister\n{\npublic:\n  typedef UIntType result_type;\n  BOOST_STATIC_CONSTANT(int, word_size = w);\n  BOOST_STATIC_CONSTANT(int, state_size = n);\n  BOOST_STATIC_CONSTANT(int, shift_size = m);\n  BOOST_STATIC_CONSTANT(int, mask_bits = r);\n  BOOST_STATIC_CONSTANT(UIntType, parameter_a = a);\n  BOOST_STATIC_CONSTANT(int, output_u = u);\n  BOOST_STATIC_CONSTANT(int, output_s = s);\n  BOOST_STATIC_CONSTANT(UIntType, output_b = b);\n  BOOST_STATIC_CONSTANT(int, output_t = t);\n  BOOST_STATIC_CONSTANT(UIntType, output_c = c);\n  BOOST_STATIC_CONSTANT(int, output_l = l);\n\n  BOOST_STATIC_CONSTANT(bool, has_fixed_range = false);\n  \n  mersenne_twister() { seed(); }\n\n#if defined(__SUNPRO_CC) && (__SUNPRO_CC <= 0x520)\n  // Work around overload resolution problem (Gennadiy E. Rozental)\n  explicit mersenne_twister(const UIntType& value)\n#else\n  explicit mersenne_twister(UIntType value)\n#endif\n  { seed(value); }\n  template<class It> mersenne_twister(It& first, It last) { seed(first,last); }\n\n  template<class Generator>\n  explicit mersenne_twister(Generator & gen) { seed(gen); }\n\n  // compiler-generated copy ctor and assignment operator are fine\n\n  void seed() { seed(UIntType(5489)); }\n\n#if defined(__SUNPRO_CC) && (__SUNPRO_CC <= 0x520)\n  // Work around overload resolution problem (Gennadiy E. Rozental)\n  void seed(const UIntType& value)\n#else\n  void seed(UIntType value)\n#endif\n  {\n    // New seeding algorithm from \n    // http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/emt19937ar.html\n    // In the previous versions, MSBs of the seed affected only MSBs of the\n    // state x[].\n    const UIntType mask = ~0u;\n    x[0] = value & mask;\n    for (i = 1; i < n; i++) {\n      // See Knuth \"The Art of Computer Programming\" Vol. 2, 3rd ed., page 106\n      x[i] = (1812433253UL * (x[i-1] ^ (x[i-1] >> (w-2))) + i) & mask;\n    }\n  }\n\n  // For GCC, moving this function out-of-line prevents inlining, which may\n  // reduce overall object code size.  However, MSVC does not grok\n  // out-of-line definitions of member function templates.\n  template<class Generator>\n  void seed(Generator & gen)\n  {\n#ifndef BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS\n    BOOST_STATIC_ASSERT(!std::numeric_limits<result_type>::is_signed);\n#endif\n    // I could have used std::generate_n, but it takes \"gen\" by value\n    for(int j = 0; j < n; j++)\n      x[j] = gen();\n    i = n;\n  }\n\n  template<class It>\n  void seed(It& first, It last)\n  {\n    int j;\n    for(j = 0; j < n && first != last; ++j, ++first)\n      x[j] = *first;\n    i = n;\n    if(first == last && j < n)\n      throw std::invalid_argument(\"mersenne_twister::seed\");\n  }\n  \n  result_type min BOOST_PREVENT_MACRO_SUBSTITUTION () const { return 0; }\n  result_type max BOOST_PREVENT_MACRO_SUBSTITUTION () const\n  {\n    // avoid \"left shift count >= with of type\" warning\n    result_type res = 0;\n    for(int i = 0; i < w; ++i)\n      res |= (1u << i);\n    return res;\n  }\n\n  result_type operator()();\n  static bool validation(result_type v) { return val == v; }\n\n#ifndef BOOST_NO_OPERATORS_IN_NAMESPACE\n\n#ifndef BOOST_NO_MEMBER_TEMPLATE_FRIENDS\n  template<class CharT, class Traits>\n  friend std::basic_ostream<CharT,Traits>&\n  operator<<(std::basic_ostream<CharT,Traits>& os, const mersenne_twister& mt)\n  {\n    for(int j = 0; j < mt.state_size; ++j)\n      os << mt.compute(j) << \" \";\n    return os;\n  }\n\n  template<class CharT, class Traits>\n  friend std::basic_istream<CharT,Traits>&\n  operator>>(std::basic_istream<CharT,Traits>& is, mersenne_twister& mt)\n  {\n    for(int j = 0; j < mt.state_size; ++j)\n      is >> mt.x[j] >> std::ws;\n    // MSVC (up to 7.1) and Borland (up to 5.64) don't handle the template\n    // value parameter \"n\" available from the class template scope, so use\n    // the static constant with the same value\n    mt.i = mt.state_size;\n    return is;\n  }\n#endif\n\n  friend bool operator==(const mersenne_twister& x, const mersenne_twister& y)\n  {\n    for(int j = 0; j < state_size; ++j)\n      if(x.compute(j) != y.compute(j))\n        return false;\n    return true;\n  }\n\n  friend bool operator!=(const mersenne_twister& x, const mersenne_twister& y)\n  { return !(x == y); }\n#else\n  // Use a member function; Streamable concept not supported.\n  bool operator==(const mersenne_twister& rhs) const\n  {\n    for(int j = 0; j < state_size; ++j)\n      if(compute(j) != rhs.compute(j))\n        return false;\n    return true;\n  }\n\n  bool operator!=(const mersenne_twister& rhs) const\n  { return !(*this == rhs); }\n#endif\n\nprivate:\n  // returns x(i-n+index), where index is in 0..n-1\n  UIntType compute(unsigned int index) const\n  {\n    // equivalent to (i-n+index) % 2n, but doesn't produce negative numbers\n    return x[ (i + n + index) % (2*n) ];\n  }\n  void twist(int block);\n\n  // state representation: next output is o(x(i))\n  //   x[0]  ... x[k] x[k+1] ... x[n-1]     x[n]     ... x[2*n-1]   represents\n  //  x(i-k) ... x(i) x(i+1) ... x(i-k+n-1) x(i-k-n) ... x[i(i-k-1)]\n  // The goal is to always have x(i-n) ... x(i-1) available for\n  // operator== and save/restore.\n\n  UIntType x[2*n]; \n  int i;\n};\n\n#ifndef BOOST_NO_INCLASS_MEMBER_INITIALIZATION\n//  A definition is required even for integral static constants\ntemplate<class UIntType, int w, int n, int m, int r, UIntType a, int u,\n  int s, UIntType b, int t, UIntType c, int l, UIntType val>\nconst bool mersenne_twister<UIntType,w,n,m,r,a,u,s,b,t,c,l,val>::has_fixed_range;\ntemplate<class UIntType, int w, int n, int m, int r, UIntType a, int u,\n  int s, UIntType b, int t, UIntType c, int l, UIntType val>\nconst int mersenne_twister<UIntType,w,n,m,r,a,u,s,b,t,c,l,val>::state_size;\ntemplate<class UIntType, int w, int n, int m, int r, UIntType a, int u,\n  int s, UIntType b, int t, UIntType c, int l, UIntType val>\nconst int mersenne_twister<UIntType,w,n,m,r,a,u,s,b,t,c,l,val>::shift_size;\ntemplate<class UIntType, int w, int n, int m, int r, UIntType a, int u,\n  int s, UIntType b, int t, UIntType c, int l, UIntType val>\nconst int mersenne_twister<UIntType,w,n,m,r,a,u,s,b,t,c,l,val>::mask_bits;\ntemplate<class UIntType, int w, int n, int m, int r, UIntType a, int u,\n  int s, UIntType b, int t, UIntType c, int l, UIntType val>\nconst UIntType mersenne_twister<UIntType,w,n,m,r,a,u,s,b,t,c,l,val>::parameter_a;\ntemplate<class UIntType, int w, int n, int m, int r, UIntType a, int u,\n  int s, UIntType b, int t, UIntType c, int l, UIntType val>\nconst int mersenne_twister<UIntType,w,n,m,r,a,u,s,b,t,c,l,val>::output_u;\ntemplate<class UIntType, int w, int n, int m, int r, UIntType a, int u,\n  int s, UIntType b, int t, UIntType c, int l, UIntType val>\nconst int mersenne_twister<UIntType,w,n,m,r,a,u,s,b,t,c,l,val>::output_s;\ntemplate<class UIntType, int w, int n, int m, int r, UIntType a, int u,\n  int s, UIntType b, int t, UIntType c, int l, UIntType val>\nconst UIntType mersenne_twister<UIntType,w,n,m,r,a,u,s,b,t,c,l,val>::output_b;\ntemplate<class UIntType, int w, int n, int m, int r, UIntType a, int u,\n  int s, UIntType b, int t, UIntType c, int l, UIntType val>\nconst int mersenne_twister<UIntType,w,n,m,r,a,u,s,b,t,c,l,val>::output_t;\ntemplate<class UIntType, int w, int n, int m, int r, UIntType a, int u,\n  int s, UIntType b, int t, UIntType c, int l, UIntType val>\nconst UIntType mersenne_twister<UIntType,w,n,m,r,a,u,s,b,t,c,l,val>::output_c;\ntemplate<class UIntType, int w, int n, int m, int r, UIntType a, int u,\n  int s, UIntType b, int t, UIntType c, int l, UIntType val>\nconst int mersenne_twister<UIntType,w,n,m,r,a,u,s,b,t,c,l,val>::output_l;\n#endif\n\ntemplate<class UIntType, int w, int n, int m, int r, UIntType a, int u,\n  int s, UIntType b, int t, UIntType c, int l, UIntType val>\nvoid mersenne_twister<UIntType,w,n,m,r,a,u,s,b,t,c,l,val>::twist(int block)\n{\n  const UIntType upper_mask = (~0u) << r;\n  const UIntType lower_mask = ~upper_mask;\n\n  if(block == 0) {\n    for(int j = n; j < 2*n; j++) {\n      UIntType y = (x[j-n] & upper_mask) | (x[j-(n-1)] & lower_mask);\n      x[j] = x[j-(n-m)] ^ (y >> 1) ^ (y&1 ? a : 0);\n    }\n  } else if (block == 1) {\n    // split loop to avoid costly modulo operations\n    {  // extra scope for MSVC brokenness w.r.t. for scope\n      for(int j = 0; j < n-m; j++) {\n        UIntType y = (x[j+n] & upper_mask) | (x[j+n+1] & lower_mask);\n        x[j] = x[j+n+m] ^ (y >> 1) ^ (y&1 ? a : 0);\n      }\n    }\n    \n    for(int j = n-m; j < n-1; j++) {\n      UIntType y = (x[j+n] & upper_mask) | (x[j+n+1] & lower_mask);\n      x[j] = x[j-(n-m)] ^ (y >> 1) ^ (y&1 ? a : 0);\n    }\n    // last iteration\n    UIntType y = (x[2*n-1] & upper_mask) | (x[0] & lower_mask);\n    x[n-1] = x[m-1] ^ (y >> 1) ^ (y&1 ? a : 0);\n    i = 0;\n  }\n}\n\ntemplate<class UIntType, int w, int n, int m, int r, UIntType a, int u,\n  int s, UIntType b, int t, UIntType c, int l, UIntType val>\ninline typename mersenne_twister<UIntType,w,n,m,r,a,u,s,b,t,c,l,val>::result_type\nmersenne_twister<UIntType,w,n,m,r,a,u,s,b,t,c,l,val>::operator()()\n{\n  if(i == n)\n    twist(0);\n  else if(i >= 2*n)\n    twist(1);\n  // Step 4\n  UIntType z = x[i];\n  ++i;\n  z ^= (z >> u);\n  z ^= ((z << s) & b);\n  z ^= ((z << t) & c);\n  z ^= (z >> l);\n  return z;\n}\n\n} // namespace random\n\n\ntypedef random::mersenne_twister<uint32_t,32,351,175,19,0xccab8ee7,11,\n  7,0x31b6ab00,15,0xffe50000,17, 0xa37d3c92> mt11213b;\n\n// validation by experiment from mt19937.c\ntypedef random::mersenne_twister<uint32_t,32,624,397,31,0x9908b0df,11,\n  7,0x9d2c5680,15,0xefc60000,18, 3346425566U> mt19937;\n\n} // namespace boost\n\nBOOST_RANDOM_PTR_HELPER_SPEC(boost::mt19937)\n\n#endif // BOOST_RANDOM_MERSENNE_TWISTER_HPP\n", "meta": {"hexsha": "cdada35ab03baeff943da01be8534f8afd016f38", "size": 10664, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Source/boost_1_33_1/boost/random/mersenne_twister.hpp", "max_stars_repo_name": "spxuw/RFIM", "max_stars_repo_head_hexsha": "32b78fbb90c7008b1106b0cff4f8023ae83c9b6d", "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": "Source/boost_1_33_1/boost/random/mersenne_twister.hpp", "max_issues_repo_name": "spxuw/RFIM", "max_issues_repo_head_hexsha": "32b78fbb90c7008b1106b0cff4f8023ae83c9b6d", "max_issues_repo_licenses": ["MIT"], "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/boost_1_33_1/boost/random/mersenne_twister.hpp", "max_forks_repo_name": "spxuw/RFIM", "max_forks_repo_head_hexsha": "32b78fbb90c7008b1106b0cff4f8023ae83c9b6d", "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": 35.1947194719, "max_line_length": 81, "alphanum_fraction": 0.6600712678, "num_tokens": 3433, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300048, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.47876640484173677}}
{"text": "#define BOOST_NO_RTTI\n#include <boost/math/tools/roots.hpp>\n\n#include <boost/math/quadrature/gauss_kronrod.hpp>\n#include <sstream>\n\nconstexpr long double Q_E = 1.6021766208e-19;\n\nstruct PotLoopBase {\n    Float\n        phi_t, g_A, psi_a, psi_b, n_i,\n        N_A, eps_si, phi_ms, Q_0, g_t, cox;\n    std::vector<Float> psi_t{}, N_t{};\n\n    unsigned tol_bits{31}; //result will be exact to 2^(1-tol_bits)\n    unsigned long max_iter{2000};\n\n    inline Float exp_phi_t(Float x) const {\n        return std::exp(x / phi_t);\n    }\n\n    inline Float fs_ea(Float psi_s, Float v_ch) const {\n        return 1./(1. + g_A * exp_phi_t(psi_a - psi_s + v_ch));\n    }\n\n    inline Float fb_ea() const {\n        return 1./(1. + g_A * exp_phi_t(psi_a - psi_b));\n    }\n\n    inline Float fs_Et(Float psi_t, Float psi_s, Float v_ch) const {\n        return 1. / (1. + g_t * exp_phi_t(+psi_t - psi_s + v_ch));\n    }\n\n    Float Q_it(Float psi_s, Float v_ch) const {\n        Float ret = 0;\n\n        for(size_t i=0; i < psi_t.size(); ++i) {\n            if(g_t == 0)\n                ret += (-Q_E) * N_t[i];\n            else\n                ret += (-Q_E) * N_t[i] * fs_Et(psi_t[i], psi_s, v_ch);\n        }\n        return ret;\n    }\n\n    Float v_fb(Float psi_s, Float v_ch) const {\n        return phi_ms + (Q_0 - Q_it(psi_s, v_ch)) / cox;\n    }\n};\n\n\nstruct PotLoop : public PotLoopBase {\n    inline Float Es_x(Float psi_s, Float v_ch, Float fb_ea_) const {\n        auto fs_ea_ = fs_ea(psi_s, v_ch);\n\n        auto fac1 = 2. * Q_E / eps_si;\n        auto fac2 = exp_phi_t(psi_s - v_ch) + exp_phi_t(-psi_s) - exp_phi_t(psi_b - v_ch) - exp_phi_t(-psi_b);\n        auto fac3 = psi_s - psi_b - phi_t * std::log(fs_ea_ / fb_ea_);\n        auto es2 = n_i * phi_t * fac1 * fac2 + fac1 * N_A * fac3;\n        if(psi_s >= psi_b)\n            return std::sqrt(es2);\n        else\n            return -std::sqrt(es2);\n    }\n\n    Float Es(Float psi_s, Float v_ch) const {\n        auto fb_ea_ = fb_ea();\n        return Es_x(psi_s, v_ch, fb_ea_);\n    }\n\n    std::pair<Float, Float> psi_s_x(Float v_ch, Float v_gb, boost::uintmax_t& iter, Float start=1.0) const {\n        using boost::math::tools::bracket_and_solve_root;\n        using boost::math::tools::eps_tolerance;\n\n        const Float fb_ea_ = fb_ea();  //precalculate\n\n        auto rootfun = [=](Float psi_s) {\n            psi_s -= 1.;\n            return v_fb(psi_s, v_ch) + eps_si * Es_x(psi_s, v_ch, fb_ea_) / cox + psi_s - psi_b - v_gb;\n        };\n\n        //TOMS748 instead?\n        return bracket_and_solve_root(rootfun, start, 1.2, true, eps_tolerance<Float>(tol_bits), iter);\n    }\n};\n\n// fermi-dirac solution\nstruct PotLoopFD : public PotLoopBase {\n    // TODO: are these really necessary?\n    Float E_i, E_v, E_c, N_c, N_v;\n\n    inline Float fdint(Float e) const {\n        // return fdk(k=0.5, phi=E / (k * T))\n        static fdint_method<> fd1h(\"fd1h\");\n        return fd1h(e / (Q_E * phi_t));\n    }\n\n    inline Float Es(Float psi_s, Float v_ch) const {\n        using boost::math::quadrature::gauss_kronrod;\n        gauss_kronrod<double, 15> integrator;\n\n        auto fac = 2. * Q_E / eps_si;\n\n        const auto S2PI = 2. * boost::math::constants::one_div_root_pi<Float>();\n\n        auto int_fun = [&](Float psi) {\n            auto n_fd = N_c * S2PI * fdint(Q_E * (psi - v_ch) + E_i - E_c);\n            auto p_fd = N_v * S2PI * fdint(E_v - Q_E * psi - E_i);\n            auto na_min = N_A / (1. + g_A * exp_phi_t(psi_a - psi + v_ch));\n            return n_fd - p_fd + na_min;\n        };\n\n        Float error, ret;\n        try {\n            if(psi_s >= psi_b)\n                ret = sqrt(fac * integrator.integrate(int_fun, psi_b, psi_s, 5, 1e-18, &error));\n            else\n                ret = -sqrt(-fac * integrator.integrate(int_fun, psi_s, psi_b, 5, 1e-18, &error));\n        } catch(std::domain_error const& ex) {\n            std::stringstream msg;\n            msg << ex.what() << \" psi_s = \" << psi_s;\n            throw std::domain_error(msg.str());\n        }\n\n        return ret;\n    }\n\n    std::pair<Float, Float> psi_s_x(Float v_ch, Float v_gb, boost::uintmax_t& iter, Float start=1.0) const {\n        using boost::math::tools::bracket_and_solve_root;\n        using boost::math::tools::eps_tolerance;\n\n        auto rootfun = [=](Float psi_s) {\n            psi_s -= 1.;\n            return v_fb(psi_s, v_ch) + eps_si * Es(psi_s, v_ch) / cox + psi_s - psi_b - v_gb;\n        };\n\n        //TOMS748 instead?\n        return bracket_and_solve_root(rootfun, start, 1.2, true, eps_tolerance<Float>(tol_bits), iter);\n    }\n};\n\nstruct PotLoopGildenblat : public PotLoopBase {\n    Float lam_bulk, bulk_n, bulk_p;\n\n    inline Float Es(Float psi_s, Float v_ch) const {\n        auto k_0 = std::exp(-v_ch / phi_t);\n        auto phi_s = psi_s - psi_b;\n        auto u = phi_s / phi_t;\n        auto g_fun = 1. / lam_bulk * std::log(1. + lam_bulk * (std::exp(u) - 1));\n        auto h2 = std::exp(-u) - 1 + g_fun + bulk_n / bulk_p * k_0 * (std::exp(u) - 1. - g_fun);\n\n        auto es2 = 2 * Q_E * bulk_p * phi_t / eps_si * h2;\n\n        if(psi_s >= psi_b)\n            return std::sqrt(es2);\n        else\n            return -std::sqrt(es2);\n    }\n\n    std::pair<Float, Float> psi_s_x(Float v_ch, Float v_gb, boost::uintmax_t& iter, Float start=1.0) const {\n        using boost::math::tools::bracket_and_solve_root;\n        using boost::math::tools::eps_tolerance;\n\n        const Float fb_ea_ = fb_ea();  //precalculate\n\n        auto rootfun = [=](Float psi_s) {\n            psi_s -= 1.;\n            return v_fb(psi_s, v_ch) + eps_si * Es(psi_s, v_ch) / cox + psi_s - psi_b - v_gb;\n        };\n\n        //TOMS748 instead?\n        return bracket_and_solve_root(rootfun, start, 1.2, true, eps_tolerance<Float>(tol_bits), iter);\n    }\n};\n\ntemplate<class L>\nFloat psi_s(L& l, Float v_ch, Float v_gb) {\n    static Float last_root = 1.0;\n\n    boost::uintmax_t iter = l.max_iter;\n    auto root = l.psi_s_x(v_ch, v_gb, iter, last_root);\n\n    if(iter == l.max_iter)\n        throw std::runtime_error(\"no solution found in max_iter iterations\");\n\n    if(root.first + root.second < 1e-6)\n        throw std::runtime_error(\"ran into psi_s < -1.0\");\n\n    if(!isfinite(root.first) || !isfinite(root.second))\n        throw std::runtime_error(\"no solution found (nan or inf)\");\n\n    last_root = (root.first + root.second) / 2;\n    return last_root - 1.;\n}\n\ntemplate<class L>\npy::tuple psi_s2(const L& l, Float v_ch, Float v_gb) {\n    boost::uintmax_t iter = l.max_iter;\n    auto root = l.psi_s_x(v_ch, v_gb, iter);\n    return py::make_tuple(root.first, root.second, iter);\n}\n", "meta": {"hexsha": "ce23200c27e15f7296bf076a26fcf010541e513a", "size": 6551, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "CryMOS/cpp/PotLoop.hpp", "max_stars_repo_name": "michi7x7/pm-mos-model", "max_stars_repo_head_hexsha": "394d752b1165f5afd96520f1b6e2dbecc27fdc4b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-26T08:40:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-26T08:40:40.000Z", "max_issues_repo_path": "CryMOS/cpp/PotLoop.hpp", "max_issues_repo_name": "michi7x7/pm-mos-model", "max_issues_repo_head_hexsha": "394d752b1165f5afd96520f1b6e2dbecc27fdc4b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CryMOS/cpp/PotLoop.hpp", "max_forks_repo_name": "michi7x7/pm-mos-model", "max_forks_repo_head_hexsha": "394d752b1165f5afd96520f1b6e2dbecc27fdc4b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-12-06T21:56:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-08T09:58:24.000Z", "avg_line_length": 32.4306930693, "max_line_length": 110, "alphanum_fraction": 0.5760952526, "num_tokens": 2018, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391617003942, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.47872515132311083}}
{"text": "// standard includes and external libraries\n#include <iostream>\n#include <random>\n#include <Eigen/Dense>\n#include <cmath>\n#include <fstream>\n#include <nlohmann/json.hpp>\n#include <ctime>\n// project includes\n#include \"abstractclasses.h\"\n#include \"bandit.h\"\n#include \"oful.h\"\n#include \"leader.h\"\n#include \"regbalancing.h\"\n#include \"adversarial_master.h\"\n#include \"finitelinrep.h\"\n#include \"utils.h\"\n#include \"gzip.h\"\n\nusing json = nlohmann::json;\nusing namespace std;\nusing namespace Eigen;\n\nsize_t PREC = 4;   // for saving numbers are rounded to PREC decimals\nsize_t EVERY = 1;  // save EVERY round\n\nint main()\n{\n    std::time_t t = std::time(nullptr);\n    char MY_TIME[100];\n    std::strftime(MY_TIME, sizeof(MY_TIME), \"%Y%m%d%H%M%S\", std::localtime(&t));\n    std::cout << MY_TIME << '\\n';\n\n    typedef std::vector<std::vector<double>> vec2double;\n\n    int seed = time(NULL);\n    // seed= 1611835201;\n    seed=1611836268;\n    srand (seed);\n    cout << \"seed: \" << seed << endl;\n    // rng.seed(10000); // warm it up\n    int n_runs = 5, T = 10000;\n    double delta = 0.01;\n    double reg_val = 1.;\n    double noise_std = 0.3;\n    double bonus_scale = 1.;\n    bool adaptive_ci = true;\n    //double cor_gamma = 1./T, cor_beta = exp(1./log(T)), cor_lr0 = 20. / sqrt(T);\n\n    std::vector<long> seeds(n_runs);\n    std::generate(seeds.begin(), seeds.end(), [] ()\n    {\n        return rand();\n    });\n\n    // FiniteLinearRepresentation rep = make_random(20, 5, 6, true, noise_std, seed);\n    // rep.save(\"linrep.json\"); // save current model\n\n    FiniteLinearRepresentation rep = flr_loadjson(\"linrep3.json\", noise_std, seed);\n    int dim = rep.features_dim();\n    cout << \"Dimension: \" << dim << endl;\n\n    std::vector<FiniteLinearRepresentation> reps;\n    double MMM = rep.features_bound();\n    for(int i = 1; i < dim; ++i)\n    {\n        FiniteLinearRepresentation rr = derank_hls(rep, i, false, true, true);\n        // cout << i << \": \" << rr.features_bound() << \", \" << rr.param_bound() << std::endl;\n        rr.normalize_features(MMM);\n        // cout << i << \": \" << rr.features_bound() << \", \" << rr.param_bound() << std::endl;\n        reps.push_back(rr);\n        bool flag = rr.is_equal(rep);\n        if (!flag) {\n            std::cout << \"Error: non realizable representation\" << std::endl;\n            exit(1);\n        }\n    }\n    assert(rep.is_equal(rep));\n    reps.push_back(rep);\n    // cout << dim << \": \" << rep.features_bound() << \", \" << rep.param_bound() << std::endl;\n    assert(reps.size() == dim);\n\n\n    // //LEADER\n    // vec2double regrets(n_runs), pseudo_regrets(n_runs);\n    // #pragma omp parallel for\n    // for (int i = 0; i < n_runs; ++i)\n    // {\n    //     std::vector<std::shared_ptr<ContRepresentation<int>>> lreps;\n    //     for(auto& ll : reps)\n    //     {\n    //         auto tmp = std::make_shared<FiniteLinearRepresentation>(ll.copy(seeds[i]));\n    //         lreps.push_back(tmp);\n    //     }\n    //     LEADER<int> localg(lreps, reg_val, noise_std, bonus_scale, delta/lreps.size(), adaptive_ci);\n    //     ContBanditProblem<int> prb(*lreps[0], localg);\n    //     prb.reset();\n    //     prb.run(T);\n    //     regrets[i] = prb.instant_regret;\n    //     pseudo_regrets[i] = prb.exp_instant_regret;\n    //     // delete localg;\n    // }\n    // // save_vector_csv(regrets, \"LEADER_regrets.csv\", EVERY, PREC);\n    // save_vector_csv_gzip(regrets, \"LEADER_regrets.csv.gz\", EVERY, PREC);\n    // // save_vector_csv(pseudo_regrets, \"LEADER_pseudoregrets.csv\", EVERY, PREC);\n    // save_vector_csv_gzip(pseudo_regrets, \"LEADER_pseudoregrets.csv.gz\", EVERY, PREC);\n\n\n    //just OFUL\n    for(int j = 0; j < reps.size(); ++j)\n    {\n        vec2double regrets(n_runs), pseudo_regrets(n_runs);\n\n        #pragma omp parallel for\n        for (int i = 0; i < n_runs; ++i)\n        {\n            FiniteLinearRepresentation lrep = reps[j].copy(seeds[i]);\n            OFUL<int> localg(lrep, reg_val, noise_std, bonus_scale, delta, adaptive_ci);\n            ContBanditProblem<int> prb(lrep, localg);\n            prb.reset();\n            prb.run(T);\n            regrets[i] = prb.instant_regret;\n            pseudo_regrets[i] = prb.exp_instant_regret;\n        }\n        // save_vector_csv(regrets, \"OFUL-rep\"+std::to_string(j)+\"_regrets.csv\", EVERY, PREC);\n        save_vector_csv_gzip(regrets, \"OFUL-rep\"+std::to_string(j)+\"_regrets.csv.gz\", EVERY, PREC);\n        // save_vector_csv(pseudo_regrets, \"OFUL-rep\"+std::to_string(j)+\"_pseudoregrets.csv\", EVERY, PREC);\n        save_vector_csv_gzip(pseudo_regrets, \"OFUL-rep\"+std::to_string(j)+\"_pseudoregrets.csv.gz\", EVERY, PREC);\n\n#if 0\n        #pragma omp parallel for\n        for (int i = 0; i < n_runs; ++i)\n        {\n            std::vector<FiniteLinearRepresentation> llr{reps[j].copy(seeds[i])};\n            LEADER ddd(llr, reg_val, 1, delta/llr.size(), adaptive_ci);\n            LinBanditProblem prb(llr[0], ddd);\n            prb.run(T);\n            regrets[i] = prb.instant_regret;\n            pseudo_regrets[i] = prb.exp_instant_regret;\n        }\n        save_vector_csv(regrets, \"LEADER-rep\"+std::to_string(j)+\"_regrets.txt\");\n        save_vector_csv(pseudo_regrets, \"LEADER-rep\"+std::to_string(j)+\"_pseudoregrets.txt\");\n#endif\n    }\n    return 0;\n}\n", "meta": {"hexsha": "bdadf6ae43c3a46d71304d1909673c8f2325f05e", "size": 5223, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/multirep.cpp", "max_stars_repo_name": "T3p/hidden-features", "max_stars_repo_head_hexsha": "7d3c27ab513e5a4c6a10c7550dc6363bd7735266", "max_stars_repo_licenses": ["MIT"], "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/multirep.cpp", "max_issues_repo_name": "T3p/hidden-features", "max_issues_repo_head_hexsha": "7d3c27ab513e5a4c6a10c7550dc6363bd7735266", "max_issues_repo_licenses": ["MIT"], "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/multirep.cpp", "max_forks_repo_name": "T3p/hidden-features", "max_forks_repo_head_hexsha": "7d3c27ab513e5a4c6a10c7550dc6363bd7735266", "max_forks_repo_licenses": ["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.5306122449, "max_line_length": 112, "alphanum_fraction": 0.6011870572, "num_tokens": 1494, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.6224593452091672, "lm_q1q2_score": 0.4787211873694224}}
{"text": "// Copyright Louis Dionne 2013-2017\r\n// Distributed under the Boost Software License, Version 1.0.\r\n// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\r\n\r\n#include <boost/hana/functional/partial.hpp>\r\n#include <boost/hana/plus.hpp>\r\nnamespace hana = boost::hana;\r\n\r\n\r\nconstexpr auto increment = hana::partial(hana::plus, 1);\r\nstatic_assert(increment(2) == 3, \"\");\r\n\r\nint main() { }\r\n", "meta": {"hexsha": "a83dee11060cd6175e4ba4a4160a5fd7e43d2be4", "size": 413, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/hana/example/functional/partial.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": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/hana/example/functional/partial.cpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-03-04T11:21:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-24T01:36:31.000Z", "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/hana/example/functional/partial.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 29.5, "max_line_length": 82, "alphanum_fraction": 0.7070217918, "num_tokens": 109, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4787211700076092}}
{"text": "#include <iostream>\n#include <fstream>\nusing namespace std;\n\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n\n#include <octomap/octomap.h>    // for octomap \n\n#include <Eigen/Geometry> \n#include <boost/format.hpp>  // for formating strings\n#include <boost/timer/timer.hpp>\n#include <cstdio>\nint main( int argc, char** argv )\n{\n\tboost::timer timer;\n\tfreopen(\"octomap_output.txt\",\"w\", stdout);\n\n    vector<cv::Mat> colorImgs, depthImgs;    // color image and depth image\n    vector<Eigen::Isometry3d> poses;         // camera pose\n    \n    ifstream fin(\"./data/pose.txt\");\n    if (!fin)\n    {\n        cerr<<\"cannot find pose file\"<<endl;\n        return 1;\n    }\n    \n    for ( int i=0; i<5; i++ )\n    {\n        boost::format fmt( \"./data/%s/%d.%s\" ); //image file format\n        colorImgs.push_back( cv::imread( (fmt%\"color\"%(i+1)%\"png\").str() ));\n        depthImgs.push_back( cv::imread( (fmt%\"depth\"%(i+1)%\"pgm\").str(), -1 )); // \u4f7f\u7528-1\u8bfb\u53d6\u539f\u59cb\u56fe\u50cf\n        \n        double data[7] = {0};\n        for ( int i=0; i<7; i++ )\n        {\n            fin>>data[i];\n        }\n        Eigen::Quaterniond q( data[6], data[3], data[4], data[5] );\n        Eigen::Isometry3d T(q);\n        T.pretranslate( Eigen::Vector3d( data[0], data[1], data[2] ));\n        poses.push_back( T );\n    }\n    \n    // join point cloud\n    // camera intrinsic\n    double cx = 325.5;\n    double cy = 253.5;\n    double fx = 518.0;\n    double fy = 519.0;\n    double depthScale = 1000.0;\n    \n    cout<<\"convert image to Octomap ...\"<<endl;\n    \n    // octomap tree \n    octomap::OcTree tree( 0.05 ); //  paramter is resolution\n    \n    for ( int i=0; i<5; i++ )\n    {\n        cout<<\"converting image: \"<<i+1<<endl; \n        cv::Mat color = colorImgs[i]; \n        cv::Mat depth = depthImgs[i];\n        Eigen::Isometry3d T = poses[i];\n        \n        octomap::Pointcloud cloud;  // the point cloud in octomap \n        \n        for ( int v=0; v<color.rows; v++ )\n            for ( int u=0; u<color.cols; u++ )\n            {\n                unsigned int d = depth.ptr<unsigned short> ( v )[u]; // depth value\n                if ( d==0 ) continue; // detect nothing\n                if ( d >= 7000 ) continue; // depth too big, erase\n                Eigen::Vector3d point; \n                point[2] = double(d)/depthScale; \n                point[0] = (u-cx)*point[2]/fx;\n                point[1] = (v-cy)*point[2]/fy; \n                Eigen::Vector3d pointWorld = T*point;\n                // put word coordinate into point cloud\n                cloud.push_back( pointWorld[0], pointWorld[1], pointWorld[2] ); \n            }\n        // insert pointcloud into octomap, set original in order to calculate projection line\n        tree.insertPointCloud( cloud, octomap::point3d( T(0,3), T(1,3), T(2,3) ) );     \n    }\n    \n    // update middle node and write \n    tree.updateInnerOccupancy();\n    cout<<\"saving octomap ... \"<<endl;\n    tree.writeBinary( \"octomap_output.bt\" );\n    cout<<\" used time \"<<timer.elapsed()<<endl;\n    return 0;\n}\n", "meta": {"hexsha": "a6802345a1426f60bcc1d23cdb2d9d1eef40a40b", "size": 3012, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "densemap/octomap_mapping.cpp", "max_stars_repo_name": "AmosLewis/RGBD_SLAM", "max_stars_repo_head_hexsha": "f4a5817936d917f59da967e8b9a6acd98fd1f06a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-05-18T08:46:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T07:10:15.000Z", "max_issues_repo_path": "densemap/octomap_mapping.cpp", "max_issues_repo_name": "AmosLewis/RGBD_SLAM", "max_issues_repo_head_hexsha": "f4a5817936d917f59da967e8b9a6acd98fd1f06a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "densemap/octomap_mapping.cpp", "max_forks_repo_name": "AmosLewis/RGBD_SLAM", "max_forks_repo_head_hexsha": "f4a5817936d917f59da967e8b9a6acd98fd1f06a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-05-21T09:33:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-14T09:03:57.000Z", "avg_line_length": 32.3870967742, "max_line_length": 94, "alphanum_fraction": 0.5391766268, "num_tokens": 867, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851919, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.4787211634185433}}
{"text": "#include <test_common.h>\n#include <iostream>\n#include <Eigen/Dense>\n\n#include <igl/copyleft/cgal/peel_outer_hull_layers.h>\n#include <igl/copyleft/cgal/remesh_self_intersections.h>\n#include <igl/copyleft/cgal/RemeshSelfIntersectionsParam.h>\n#include <igl/per_face_normals.h>\n#include <igl/remove_unreferenced.h>\n#include <igl/writeOBJ.h>\n\n#include <CGAL/Exact_predicates_exact_constructions_kernel.h>\n\nTEST_CASE(\"copyleft_cgal_peel_outer_hull_layers: TwoCubes\", \"[igl/copyleft/cgal]\")\n{\n    Eigen::MatrixXd V;\n    Eigen::MatrixXi F;\n    igl::read_triangle_mesh(test_common::data_path(\"two-boxes-bad-self-union.ply\"), V, F);\n    REQUIRE (V.rows() == 486);\n    REQUIRE (F.rows() == 708);\n\n    typedef CGAL::Exact_predicates_exact_constructions_kernel K;\n    typedef K::FT Scalar;\n    typedef Eigen::Matrix<Scalar,\n            Eigen::Dynamic,\n            Eigen::Dynamic> MatrixXe;\n\n    MatrixXe Vs;\n    Eigen::MatrixXi Fs, IF;\n    Eigen::VectorXi J, IM;\n    igl::copyleft::cgal::RemeshSelfIntersectionsParam param;\n    igl::copyleft::cgal::remesh_self_intersections(V, F, param, Vs, Fs, IF, J, IM);\n\n    std::for_each(Fs.data(),Fs.data()+Fs.size(),\n            [&IM](int & a){ a=IM(a); });\n    MatrixXe Vt;\n    Eigen::MatrixXi Ft;\n    igl::remove_unreferenced(Vs,Fs,Vt,Ft,IM);\n    const size_t num_faces = Ft.rows();\n\n    Eigen::VectorXi I, flipped;\n    size_t num_peels = igl::copyleft::cgal::peel_outer_hull_layers(Vt, Ft, I, flipped);\n\n    Eigen::MatrixXd vertices(Vt.rows(), Vt.cols());\n    std::transform(Vt.data(), Vt.data() + Vt.rows() * Vt.cols(),\n            vertices.data(), [](Scalar v) { return CGAL::to_double(v); });\n    igl::writeOBJ(\"debug.obj\", vertices, Ft);\n\n    REQUIRE (I.rows() == num_faces);\n    REQUIRE (I.minCoeff() == 0);\n    REQUIRE (I.maxCoeff() == 1);\n}\n\nTEST_CASE(\"PeelOuterHullLayers: CubeWithFold\", \"[igl/copyleft/cgal]\")\n{\n    Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> V;\n    Eigen::MatrixXi F;\n    igl::read_triangle_mesh(test_common::data_path(\"cube_with_fold.ply\"), V, F);\n\n    typedef CGAL::Exact_predicates_exact_constructions_kernel K;\n    typedef K::FT Scalar;\n    typedef Eigen::Matrix<Scalar,\n            Eigen::Dynamic,\n            Eigen::Dynamic> MatrixXe;\n\n    MatrixXe Vs;\n    Eigen::MatrixXi Fs, IF;\n    Eigen::VectorXi J, IM;\n    igl::copyleft::cgal::RemeshSelfIntersectionsParam param;\n    igl::copyleft::cgal::remesh_self_intersections(V, F, param, Vs, Fs, IF, J, IM);\n\n    std::for_each(Fs.data(),Fs.data()+Fs.size(),\n            [&IM](int & a){ a=IM(a); });\n    MatrixXe Vt;\n    Eigen::MatrixXi Ft;\n    igl::remove_unreferenced(Vs,Fs,Vt,Ft,IM);\n\n    Eigen::VectorXi I, flipped;\n    size_t num_peels = igl::copyleft::cgal::peel_outer_hull_layers(Vt, Ft, I, flipped);\n}\n", "meta": {"hexsha": "086de5328fd77d9bd71f348990b2e39fc271699e", "size": 2745, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "external/libigl/tests/include/igl/copyleft/cgal/peel_outer_hull_layers.cpp", "max_stars_repo_name": "V-Sekai/godot-tri", "max_stars_repo_head_hexsha": "8f1c1529b26ebec5928800c7f87da72a0fd03748", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-01-25T04:26:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-30T14:16:34.000Z", "max_issues_repo_path": "external/libigl/tests/include/igl/copyleft/cgal/peel_outer_hull_layers.cpp", "max_issues_repo_name": "V-Sekai/godot-tri", "max_issues_repo_head_hexsha": "8f1c1529b26ebec5928800c7f87da72a0fd03748", "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": "external/libigl/tests/include/igl/copyleft/cgal/peel_outer_hull_layers.cpp", "max_forks_repo_name": "V-Sekai/godot-tri", "max_forks_repo_head_hexsha": "8f1c1529b26ebec5928800c7f87da72a0fd03748", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-11-05T01:11:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-05T01:12:03.000Z", "avg_line_length": 33.8888888889, "max_line_length": 90, "alphanum_fraction": 0.6666666667, "num_tokens": 808, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.6224593171945417, "lm_q1q2_score": 0.4787211592348618}}
{"text": "#include <iostream>\n#include <boost/numeric/mtl/mtl.hpp>\n\nint main()\n{\n  const int size = 3, N = size * size;\n  mtl::compressed2D<double>          A(N, N);\n \n  laplacian_setup(A, size, size);\n  std::cout<< \"Laplacian_setup=\\n\" << A << \"\\n\";\n  \n  diagonal_setup(A, 2.0);\n  std::cout<< \"diagonal_setup=\\n\" << A << \"\\n\";\n  \n  mtl::dense2D<double>\t\t     B(N, N);   //to expensive for sparse Matrix\n  hessian_setup(B, 4.0);\n  std::cout<< \"hessian_setup=\\n\" << B << \"\\n\";\n    \n  return 0;\n}\n", "meta": {"hexsha": "69497034fe8adcfc98ac920a939bea43c2dc0b45", "size": 485, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/examples/setups_example.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/setups_example.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/setups_example.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 23.0952380952, "max_line_length": 72, "alphanum_fraction": 0.5711340206, "num_tokens": 171, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388167733099, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.47870832470919733}}
{"text": "#include <basix/e-lagrange.h>\n#include <basix/quadrature.h>\n#include <boost/program_options.hpp>\n#include <cmath>\n#include <dolfinx.h>\n#include <dolfinx/io/XDMFFile.h>\n#include <iostream>\n\n#include <cublas_v2.h>\n#include <cuda_profiler_api.h>\n\n// Helper functions\n#include <cuda/allocator.hpp>\n#include <cuda/array.hpp>\n#include <cuda/la.hpp>\n#include <cuda/mass.hpp>\n#include <cuda/scatter.hpp>\n#include <cuda/transform.hpp>\n#include <cuda/utils.hpp>\n#include <operators.hpp>\n\nusing namespace dolfinx;\nnamespace po = boost::program_options;\n\nvoid assert_cublas(cudaError_t e) {\n  if (e != cudaSuccess)\n    throw std::runtime_error(\" Unable to allocate memoy - cublas error\");\n}\nint main(int argc, char* argv[]) {\n\n  po::options_description desc(\"Allowed options\");\n  desc.add_options()(\"help,h\", \"print usage message\")(\n      \"size\", po::value<std::size_t>()->default_value(32))(\n      \"degree\", po::value<int>()->default_value(1))(\n      \"check\", po::value<bool>()->default_value(false));\n\n  po::variables_map vm;\n  po::store(po::command_line_parser(argc, argv).options(desc).allow_unregistered().run(),\n            vm);\n  po::notify(vm);\n\n  if (vm.count(\"help\")) {\n    std::cout << desc << \"\\n\";\n    return 0;\n  }\n\n  const std::size_t Nx = vm[\"size\"].as<std::size_t>();\n  const int degree = vm[\"degree\"].as<int>();\n  const bool check = vm[\"check\"].as<bool>();\n\n  common::subsystem::init_logging(argc, argv);\n  common::subsystem::init_mpi(argc, argv);\n  {\n    // MPI\n    MPI_Comm mpi_comm{MPI_COMM_WORLD};\n    int rank = utils::set_device(mpi_comm);\n\n    // Create cublas handle\n    cublasHandle_t handle;\n    cublasCreate(&handle);\n\n    // Read mesh and mesh tags\n    std::array<std::array<double, 3>, 2> p = {{{0.0, 0.0, 0.0}, {1.0, 1.0, 1.0}}};\n    std::array<std::size_t, 3> n = {Nx, Nx, Nx};\n    auto mesh = std::make_shared<mesh::Mesh>(mesh::create_box(\n        mpi_comm, p, n, mesh::CellType::hexahedron, mesh::GhostMode::none));\n\n    // Create a Basix continuous Lagrange element of given degree\n    basix::FiniteElement e = basix::element::create_lagrange(\n        mesh::cell_type_to_basix_type(mesh::CellType::hexahedron), degree,\n        basix::element::lagrange_variant::gll_warped, false);\n\n    // Create a scalar function space\n    std::shared_ptr<fem::FunctionSpace> V\n        = std::make_shared<fem::FunctionSpace>(fem::create_functionspace(mesh, e, 1));\n    auto idxmap = V->dofmap()->index_map;\n\n    int ncells = mesh->topology().index_map(3)->size_local();\n    int ndofs = e.dim();\n\n    fem::Function<double> u(V);\n    // Interpolate sin(2 \\pi x[0]) in the scalar Lagrange finite element space\n    constexpr double PI = xt::numeric_constants<double>::PI;\n    u.interpolate([PI](auto&& x) { return PI * xt::row(x, 0); });\n\n    CUDA::allocator<double> allocator{};\n    la::Vector<double, decltype(allocator)> x(idxmap, 1, allocator);\n    la::Vector<double, decltype(allocator)> y(idxmap, 1, allocator);\n    std::fill(x.mutable_array().begin(), x.mutable_array().end(), 1);\n\n    linalg::prefetch(0, x);\n    linalg::prefetch(0, y);\n\n    auto quad = basix::quadrature::type::gll;\n    int qdegree = (degree > 1) ? degree + 1 : degree;\n    MassOperator<double> op(V, e, quad, qdegree);\n\n    double t = MPI_Wtime();\n    op.apply(x, y);\n    t = MPI_Wtime() - t;\n\n    if (check) {\n      la::Vector<double> x(idxmap, 1);\n      la::Vector<double> y1(idxmap, 1);\n      std::fill(x.mutable_array().begin(), x.mutable_array().end(), 1);\n      MassOperatorCPU<double> cpu_op(V, degree);\n      double t = MPI_Wtime();\n      cpu_op(x, y1);\n      t = MPI_Wtime() - t;\n      std::cout << \"Y norm: \" << y1.norm() << std::endl;\n\n      for (int i = 0; i < x.array().size(); i++) {\n        double err = y1.array()[i] - y.array()[i];\n        if (std::abs(err) > 1e-8)\n          std::cout << y1.array()[i] - y.array()[i] << \" \";\n      }\n      std::cout << \"\\n#Elapsed Time: \" << t << std::endl;\n    }\n\n    std::cout << \"X norm: \" << x.norm() << std::endl;\n    std::cout << \"Y norm: \" << y.norm() << std::endl;\n    std::cout << \"Number of cells: \" << op.num_cells();\n    std::cout << \"\\nNumber of dofs: \" << op.num_dofs();\n    std::cout << \"\\nNumber of quads: \" << op.num_quads();\n    std::cout << \"\\n#Elapsed Time: \" << t;\n    std::cout << \"\\nDOF/s: \" << V->dofmap()->index_map->size_local() / t;\n    std::cout << std::endl;\n  }\n\n  common::subsystem::finalize_mpi();\n  return 0;\n}\n", "meta": {"hexsha": "b4c95e653f683ca8ea757631874e19274fda8acf", "size": 4376, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "demo/gpu_operator_monolithic/main.cpp", "max_stars_repo_name": "Excalibur-SLE/wave-fenics", "max_stars_repo_head_hexsha": "2d3345c4cffecbe382acd1005a9dcc2bbc62ad1c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-27T23:36:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-27T23:36:14.000Z", "max_issues_repo_path": "demo/gpu_operator_monolithic/main.cpp", "max_issues_repo_name": "Excalibur-SLE/wave-fenics", "max_issues_repo_head_hexsha": "2d3345c4cffecbe382acd1005a9dcc2bbc62ad1c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2022-02-23T13:22:29.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-01T12:40:10.000Z", "max_forks_repo_path": "demo/gpu_operator_monolithic/main.cpp", "max_forks_repo_name": "Excalibur-SLE/wave-fenics", "max_forks_repo_head_hexsha": "2d3345c4cffecbe382acd1005a9dcc2bbc62ad1c", "max_forks_repo_licenses": ["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.9022556391, "max_line_length": 89, "alphanum_fraction": 0.6154021938, "num_tokens": 1310, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214155, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4787083198282675}}
{"text": "#ifndef _TAG_HPP\n#define _TAG_HPP\n\n#include <boost/math/quaternion.hpp>\n\nclass Tag\n{\nprivate:\n   int _id;\n   double _x;\n   double _y;\n   double _z;\n   boost::math::quaternion<double> _orientation;\n\n   static constexpr double CAMERA_HEIGHT = 0.195;\n   static constexpr double CAMERA_OFFSET = -0.023;\npublic:\n   const static int NEST_TAG_ID = 256;\n   const static int CUBE_TAG_ID = 0;\n\n   Tag(int id, double x, double y, double z, boost::math::quaternion<double> orientation);\n   ~Tag() {}\n   \n   double Alignment() const;\n   double Distance() const;\n   double HorizontalDistance() const;\n   double GetX() const { return _x; }\n   double GetY() const { return _y; }\n   double GetZ() const { return _z; }\n   boost::math::quaternion<double> GetOrientation() const { return _orientation; }\n   double GetYaw()   const;\n   double GetPitch() const;\n   int    GetId()    const { return _id; }\n   bool   IsCube()   const;\n   bool   IsNest()   const;\n\n   friend std::ostream& operator<<(std::ostream& os, const Tag& tag);\n};\n\n#endif // _TAG_HPP\n", "meta": {"hexsha": "677110dca315017d33826b8ae45c8f7fa5ad18cd", "size": 1033, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/behaviours/include/Tag.hpp", "max_stars_repo_name": "BCLab-UNM/SwarmBaseCode-Modular-Public", "max_stars_repo_head_hexsha": "2061796570baf65deeb74f29444fcaf3b6464aa1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/behaviours/include/Tag.hpp", "max_issues_repo_name": "BCLab-UNM/SwarmBaseCode-Modular-Public", "max_issues_repo_head_hexsha": "2061796570baf65deeb74f29444fcaf3b6464aa1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/behaviours/include/Tag.hpp", "max_forks_repo_name": "BCLab-UNM/SwarmBaseCode-Modular-Public", "max_forks_repo_head_hexsha": "2061796570baf65deeb74f29444fcaf3b6464aa1", "max_forks_repo_licenses": ["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.1951219512, "max_line_length": 90, "alphanum_fraction": 0.6679574056, "num_tokens": 284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.4787083198282675}}
{"text": "/*\n*  ERD2.cpp\n*\n*      Author: gstoszek\n*/\n\n#include \"ERD2.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 <armadillo>\n\nnamespace NetworKit {\n\n  ERD2::ERD2(const Graph &G): Centrality(G, true) {\n        n=G.upperNodeIdBound();\n        /* EffectiveResistanceDistance-Matrix*/\n        ERD.resize(n);\n        /*Laplacian*/\n        L.set_size(n,n);\n        L.zeros();\n        /* */\n        vList.resize(n);\n        vAdj_List.resize(n);\n\n        G.forNodes([&](node v){\n            ERD[v].resize(n);\n            ERD[v][v]=0.;\n            vAdj_List[v].resize(0);\n            vList[v]=v;\n            G.forNodes([&](node w){\n              if(G.hasEdge(v,w)){\n                /*instead of 1 one should use a function for weighted edges*/\n                L(v,w)=-1.;\n                L(v,v)+=1.;\n                vAdj_List[v].push_back(w);\n              }\n            });\n            nEdges+=L(v,v);\n        });\n      }\n    /**************************************************************************/\n    std::vector<std::vector<double>> ERD2::getERDMatrix() {\n        return ERD;\n    }\n    /**************************************************************************/\n    void ERD2::run(){\n      /**Set LEVEL here**/\n      upperLevelIdBound =1;\n      count current_Level;\n      current_Level=0;\n      coarsed_List.resize(0);\n      auto start = std::chrono::high_resolution_clock::now();\n      while(current_Level<upperLevelIdBound){\n        coarse_L(current_Level);\n        current_Level+=1;\n      }\n      auto end = std::chrono::high_resolution_clock::now();\n      std::chrono::duration<double> diff = end-start;\n      std::cout<< \"Coarsening finished in: \" << diff.count() << \"(s)\" << \"\\n\";\n      /*invert*/\n      start = std::chrono::high_resolution_clock::now();\n      L=arma::pinv(L, 0.01);\n      end = std::chrono::high_resolution_clock::now();\n      diff = end-start;\n      std::cout<< \"Pinv() calculated in: \" << diff.count() << \"(s)\" << \"\\n\";\n      /*calculate initial ERD Matrix*/\n      for(count i=0;i<vList.size();i++){\n        for(count j=i+1;j<vList.size();j++){\n          ERD[vList[i]][vList[j]]=L(i,i)+L(j,j)-2.*L(i,j);\n          ERD[vList[j]][vList[i]]=ERD[vList[i]][vList[j]];\n        }\n      }\n      for(count i=0;i<coarsed_List.size();i++){\n        for(count j=0;j<ERD.size();j++){\n          ERD[coarsed_List[i].first][j]=ERD[vAdj_List[coarsed_List[i].first][0]][j]+1.;\n          ERD[j][coarsed_List[i].first]=ERD[coarsed_List[i].first][j];\n        }\n      }\n    }\n    /***************************************************************************/\n    void uncoarse_L(){\n\n    }\n\n\n    /***************************************************************************/\n    void ERD2::coarse_L(count current_Level){\n      std::vector<node> coarse_List;\n      coarse_List.resize(0);\n      for(count i=0;i<L.n_rows;i++){\n        if(L(i,i)==current_Level+1){\n          coarse_List.push_back(i);\n        }\n      }\n      for(count i=0;i<coarse_List.size();i++){\n        for(count j=1;j<vAdj_List[coarse_List[i]].size();j++){\n          if(L(vAdj_List[coarse_List[i]][0],vAdj_List[coarse_List[i]][j])!=-1){\n            L(vAdj_List[coarse_List[i]][0],vAdj_List[coarse_List[i]][j])=-1.;\n            L(vAdj_List[coarse_List[i]][j],vAdj_List[coarse_List[i]][0])=-1.;\n            tM[vList[i]][vAdj_List[coarse_List[i]][j]];\n            tM[vAdj_List[coarse_List[i]][j]][vList[i]];\n            /*Diagonal*/\n            L(vAdj_List[coarse_List[i]][0],vAdj_List[coarse_List[i]][0])+=1.;\n          }\n        }\n        L(vAdj_List[coarse_List[i]][0],vAdj_List[coarse_List[i]][0])-=1.;\n        coarsed_List.push_back(std::make_pair(vList[coarse_List[i]],current_Level));\n      }\n      arma::uvec indices(vList.size()-coarse_List.size());\n      count k;\n      count j;\n      k=0;\n      j=0;\n      for(count i=0;i<vList.size();i++){\n        if(coarse_List[k]==i){\n          k++;\n        }\n        else{\n          indices(j)=i;\n          j++;\n        }\n      }\n      for(count i=0;i<coarse_List.size();i++){\n        vList.erase(vList.begin()+coarse_List[i]-i);\n      }\n      L=L.submat(indices, indices);\n    }\n    /**************************************************************************/\n    /*\n    void ERD2::sort_Level_List(std::vector<node> vLevel_List,count LevelId){\n      std::vector<std::vector<node>> bucket_List;\n      bucket_List.resize(upperLevelIdBound)\n      bucket_List.resize(0);\n      count k,\n      k=0;\n      while(k!=vLevel_List.size()){\n        if(nAdj_List[vLevel_List[k]].second<upperNodeIdBound){\n          bucket_List[nAdj_List[vLevel_List[k]].second-1].push_back vLevel_List[k];\n        }\n        else{\n          bucket_List[upperNodeIdBound].push_back vLevel_List[k];\n        }\n        k++;\n      }\n      for(count i=0;i<bucket_List.size();i++){\n        for(count j=0;j<bucket_List[i].size();j++){\n          vLevel_List=bucket_List[i][j];\n        }\n      }\n    }\n    */\n    /**************************************************************************/\n    /*\n    void ERD2::coarse(count samplesize, count LevelID){\n      if(LevelID==3){\n      }\n      else{\n        std::pair<node,node> coarsed_edge;\n        std::vector<std::pair<bool,double>> Absorber_Edge_List;\n        std::vector<std::pair<bool,double>> Submitter_Edge_List;\n        Absorber_Edge_List.resize(Adj.size());\n        Submitter_Edge_List.resize(Adj.size());\n        coarsed_edge=select_edge();\n        //coarsed_edge=random_edge();\n        Absorber_Edge_List=Adj[coarsed_edge.first];\n        Submitter_Edge_List=Adj[coarsed_edge.second];\n        coarsening(coarsed_edge);\n        coarse(1);\n        uncoarsening(Absorber_Edge_List,Submitter_Edge_List,coarsed_edge);\n      }\n    }\n    */\n    /**************************************************************************/\n    /*\n    std::pair<node,node> ERD2::select_edge(){\n      return make_pair(Matching_List[vLevel_List[0]].second,vLevel_List[0])\n    }\n    */\n    /**************************************************************************/\n    /*\n    std::pair<node,node> ERD2::random_edge(){\n      count Random_Edge;\n      count i;\n      count a;\n      count b;\n\n      a=1;\n      b=nAdj_List.size()-1;\n\n      i=a+(b-a)*0.5;\n      Random_Edge= (std::rand() % nEdges)+1;\n      while(!((Random_Edge>nAdj_List[i-1].second)&&(Random_Edge<=nAdj_List[i].second))){\n        if(Random_Edge<=nAdj_List[i-1].second){\n          b=i;\n        }\n        else{\n          a=i;\n        }\n        i=a+(b-a)*0.5;\n      }\n      count k=0;\n      count j=0;\n      while(k<Random_Edge-nAdj_List[i-1].second){\n        if(Adj[nAdj_List[i].first][j].first){\n            k++;\n        }\n        j++;\n      }\n      j--;\n      if(j>=G.upperNodeIdBound()){\n        std::cout<<\"<\"<<nAdj_List[i].first<<\",\"<<j<<\"> mit \"<<Random_Edge<<\"\\n\";\n        std::cout<<\"No. of Edges=\"<<nEdges<<\"\\n\";\n        std::cout<<\"i-1=\"<<i+1<<\"-->\"<<\"v=\"<<nAdj_List[i-1].first<<\" No.=\"<< nAdj_List[i-1].second<<\"\\n\";\n        std::cout<<\"i=\"<<i<<\"-->\"<<\"v=\"<<nAdj_List[i].first<<\" No.=\"<< nAdj_List[i].second<<\"\\n\";\n        std::cout<<\"i+1=\"<<i+1<<\"-->\"<<\"v=\"<<nAdj_List[i+1].first<<\" No.=\"<< nAdj_List[i+1].second<<\"\\n\";\n        count p;\n        for(count k=0;k<Adj.size();k++){\n          if(Adj[nAdj_List[i].first][k].first){\n            p++;\n          }\n        }\n        std::cout<<\"p=\"<<p<<\"\\n\";\n      }\n      return std::make_pair(nAdj_List[i].first,j);\n    }\n    */\n    /**************************************************************************/\n    /*\n    void ERD2::coarsening_2(std::pair<node,node> coarsed_edge){\n      std::cout << \"coarsening! <a,s>=<\" << coarsed_edge.first << \",\" << coarsed_edge.second <<\">\"<<\"\\n\";\n      vLevel_List.erase (vLevel_List.begin());\n      Adj[coarsed_edge.first][coarsed_edge.second].first=false;\n      Adj[coarsed_edge.second][coarsed_edge.first].first=false;\n    }\n    */\n    /**************************************************************************/\n    /**************************************************************************/\n    /*void ERD2::coarsening(std::pair<node,node> coarsed_edge){\n      count x;\n      count y;\n      std::vector<int> transfered_Edges;\n      transfered_Edges.resize(Adj.size()+1);\n      transfered_Edges[0]=0;\n      for(count i=1;i<nAdj_List.size();i++){\n        x=nAdj_List[i].first;\n        if(Adj[coarsed_edge.second][x].first==true){\n          if(Adj[coarsed_edge.first][x].first==false){\n            Adj[coarsed_edge.first][x]=std::make_pair(true,Adj[coarsed_edge.second][x].second);\n            Adj[x][coarsed_edge.first]=std::make_pair(true,Adj[coarsed_edge.second][x].second);\n            transfered_Edges[x+1]++;\n            transfered_Edges[coarsed_edge.first+1]++;\n          }\n          Adj[coarsed_edge.second][x]=std::make_pair(false,0.);\n          Adj[x][coarsed_edge.second]=std::make_pair(false,0.);\n          transfered_Edges[x+1]--;\n          transfered_Edges[coarsed_edge.second+1]--;\n        }\n      }\n      Adj[coarsed_edge.first][coarsed_edge.first]=std::make_pair(false,0);\n      transfered_Edges[coarsed_edge.first+1]-=2;\n      y=1;\n      nAdj_List[1].second+=transfered_Edges[nAdj_List[1].first+1];\n      for(count i=2;i<nAdj_List.size();i++){\n          transfered_Edges[nAdj_List[i].first+1]+=transfered_Edges[nAdj_List[i-1].first+1];\n          nAdj_List[i].second+=transfered_Edges[nAdj_List[i].first+1];\n          if(nAdj_List[i].first==coarsed_edge.second){\n            y=i;\n          }\n      }\n      nAdj_List.erase(nAdj_List.begin()+y);\n      nEdges=nAdj_List[nAdj_List.size()-1].second;\n    }\n    */\n    /**************************************************************************/\n    /*\n    void ERD2::uncoarsening(std::vector<std::pair<bool,double>> Absorber_Edge_List,\n      std::vector<std::pair<bool,double>> Submitter_Edge_List,\n      std::pair<node,node> coarsed_edge){\n        count x;\n\n        first_join(coarsed_edge);\n        nAdj_List.push_back(std::make_pair(coarsed_edge.second,1));\n        for(count i=1; i<nAdj_List.size();i++){\n          x=nAdj_List[i].first;\n          if((Submitter_Edge_List[x].first) && (x!=coarsed_edge.first)){\n            if(Absorber_Edge_List[x].first){\n              edge_fire(std::make_pair(x,coarsed_edge.second));\n            }\n            else{\n              ERD[coarsed_edge.second][x]=ERD[coarsed_edge.first]\n            }\n          }\n          if((Adj[coarsed_edge.first][x].first)&&(Absorber_Edge_List[x].first!=true)){\n            non_bridge_delete(std::make_pair(x,coarsed_edge.first));\n          }\n        }\n      }\n      */\n    /**************************************************************************/\n    /*\n    void ERD2::first_join(std::pair<node,node> coarsed_edge){\n      for(count i=1;i<nAdj_List.size();i++){\n        ERD[nAdj_List[i].first][coarsed_edge.second]=ERD[nAdj_List[i].first][coarsed_edge.first]+1.;\n        ERD[coarsed_edge.second][nAdj_List[i].first]=ERD[nAdj_List[i].first][coarsed_edge.second];\n      }\n      Adj[coarsed_edge.first][coarsed_edge.second]=std::make_pair(true,1.);\n      Adj[coarsed_edge.second][coarsed_edge.first]=std::make_pair(true,1.);\n    }\n    */\n    /**************************************************************************/\n    /*\n    void ERD2::edge_fire(std::pair<node,node> coarsed_edge){\n      std::vector<std::vector<double>> ERD2;\n      ERD2.resize(ERD.size());\n      G.forNodes([&](node v){\n        ERD2[v].resize(ERD.size());\n      });\n      count x;\n      count y;\n\n      for(count i=1;i<nAdj_List.size();i++){\n        x=nAdj_List[i].first;\n        for(count j=i+1;j<nAdj_List.size();j++){\n          y=nAdj_List[j].first;\n          ERD2[x][y]=ERD[x][coarsed_edge.second]-ERD[x][coarsed_edge.first];\n          ERD2[x][y]-=ERD[coarsed_edge.second][y]-ERD[coarsed_edge.first][y];\n          ERD2[x][y]*=ERD2[x][y];\n          ERD2[x][y]/=4.*(1.+ERD[coarsed_edge.first][coarsed_edge.second]);\n          ERD2[x][y]=ERD[x][y]-ERD2[x][y];\n          ERD2[y][x]=ERD2[x][y];\n        }\n      }\n      ERD=ERD2;\n      Adj[coarsed_edge.first][coarsed_edge.second]=std::make_pair(true,1.);\n      Adj[coarsed_edge.second][coarsed_edge.first]=std::make_pair(true,1.);\n    }\n    */\n    /**************************************************************************/\n    /*\n    void ERD2::non_bridge_delete(std::pair<node,node> coarsed_edge){\n      std::vector<std::vector<double>> ERD2;\n      ERD2.resize(ERD.size());\n      G.forNodes([&](node v){\n        ERD2[v].resize(ERD.size());\n      });\n      count x;\n      count y;\n\n      for(count i=1;i<nAdj_List.size();i++){\n        x=nAdj_List[i].first;\n        for(count j=i+1;j<nAdj_List.size();j++){\n          y=nAdj_List[j].first;\n          ERD2[x][y]=ERD[x][coarsed_edge.second]-ERD[x][coarsed_edge.first];\n          ERD2[x][y]-=ERD[coarsed_edge.second][y]-ERD[coarsed_edge.first][y];\n          ERD2[x][y]*=ERD2[x][y];\n          ERD2[x][y]/=4.*(1.-ERD[coarsed_edge.first][coarsed_edge.second]);\n          ERD2[x][y]=ERD[x][y]+ERD2[x][y];\n          ERD2[y][x]=ERD2[x][y];\n        }\n      }\n      ERD=ERD2;\n      Adj[coarsed_edge.first][coarsed_edge.second]=std::make_pair(false,0.);\n      Adj[coarsed_edge.second][coarsed_edge.first]=std::make_pair(false,0.);\n    }\n    */\n    /**************************************************************************/\n} /* namespace NetworKit*/\n", "meta": {"hexsha": "28bc8830d1e3aee78727b32978a843be9efc3f07", "size": 13345, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "networkit/cpp/centrality/ERD2.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/ERD2.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/ERD2.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": 35.7774798928, "max_line_length": 105, "alphanum_fraction": 0.4996627951, "num_tokens": 3581, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4787083149473375}}
{"text": "// Copyright (c) 2016 Matt Overby\n// \n// MPM-OPTIMIZATION Uses the BSD 2-Clause License (http://www.opensource.org/licenses/BSD-2-Clause)\n// Redistribution and use in source and binary forms, with or without modification, are\n// permitted provided that the following conditions are met:  \n// 1. Redistributions of source code must retain the above copyright notice, this list of\n// conditions and the following disclaimer.  \n// 2. Redistributions in binary form must reproduce the above copyright notice, this list\n// of conditions and the following disclaimer in the documentation and/or other materials\n// provided with the distribution.  \n// THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR  A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL THE UNIVERSITY OF MINNESOTA, DULUTH OR CONTRIBUTORS BE \n// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,\n// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER\n// IN CONTRACT, STRICT 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 SUCH DAMAGE.\n\n#ifndef INTERP_HPP\n#define INTERP_HPP 1\n\n#include <Eigen/Dense>\n#include <vector>\n\nnamespace mpm\n{\n\n\t// Cubic B-spline\n\tstatic inline double cspline(double x)\n\t{\n\t\tif (x==0.0) { x=1e-12; }\n\t\tx = fabs(x);\n\t\tif (x < 1.0) { return x*x*(x*0.5 - 1.0) + 2.0/3.0; }\n\t\telse if (x < 2.0) { return x*(x*(-x/6.0 + 1.0) - 2.0) + 4.0/3.0; }\n\t\treturn 0.0;\n\t}\n\n\t// Slope of cubic spline\n\tstatic inline double d_cspline(double x)\n\t{\n\t\tif (x==0.0) { x=1e-12; }\n\t\tdouble abs_x = fabs(x);\n\t\tif (abs_x < 1.0) { return 1.5*x*abs_x - 2.0*x; }\n\t\telse if (x < 2.0) { return -x*abs_x*0.5 + 2.0*x - 2.0*x/abs_x; }\n\t\treturn 0.0;\n\t}\n\n\t// Quadratic spline\n\tstatic inline double qspline( double x )\n\t{\n\t\tdouble fx = fabs(x);\n\t\tif (fx < 0.5) { return ( 0.75 - x*x ); }\n\t\telse if (fx < 1.5) { return ( 0.5*x*x - 1.5*fx + 9.0/8.0 ); }\n\t\treturn 0.0;\n\t}\n\n\t// Slope of quadratic spline\n\tstatic inline double d_qspline( double x )\n\t{\n\t\tdouble fx = fabs(x);\n\t\tif (fx < 0.5) { return ( -2.0 * x ); }\n\t\telse if (fx < 1.5)\n\t\t{\n\t\t\tif (x < 0.0) { return fabs( fx - 1.5 ); }\n\t\t\telse { return (fx - 1.5); }\n\t\t}\n\t\treturn 0.0;\n\t}\n\n\tstatic inline bool isreal(double n)\n\t{\n\t\treturn !std::isnan(n) && !std::isinf(n);\n\t}\n\n} // end namespace mpm\n\n#endif\n", "meta": {"hexsha": "4269055c7361f3d0b5a813e55dab817967271dbe", "size": 2600, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Interp.hpp", "max_stars_repo_name": "NTForked/mpm-optimization", "max_stars_repo_head_hexsha": "883b1ca2ed57ebea936922855af2eee4c6997897", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2017-07-21T10:00:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-29T18:08:00.000Z", "max_issues_repo_path": "src/Interp.hpp", "max_issues_repo_name": "NTForked/mpm-optimization", "max_issues_repo_head_hexsha": "883b1ca2ed57ebea936922855af2eee4c6997897", "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/Interp.hpp", "max_forks_repo_name": "NTForked/mpm-optimization", "max_forks_repo_head_hexsha": "883b1ca2ed57ebea936922855af2eee4c6997897", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-08-07T18:32:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-07T08:15:10.000Z", "avg_line_length": 32.9113924051, "max_line_length": 99, "alphanum_fraction": 0.6726923077, "num_tokens": 815, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042768, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4786887335702307}}
{"text": "#include <pluginlib/class_list_macros.h>\n#include <kdl_parser/kdl_parser.hpp>\n#include <math.h>\n#include <Eigen/LU>\n\n#include <utils/pseudo_inversion.h>\n#include <utils/skew_symmetric.h>\n#include <lwr_controllers/multi_task_priority_inverse_kinematics.h>\n\nnamespace lwr_controllers \n{\n\tMultiTaskPriorityInverseKinematics::MultiTaskPriorityInverseKinematics() {}\n\tMultiTaskPriorityInverseKinematics::~MultiTaskPriorityInverseKinematics() {}\n\n\tbool MultiTaskPriorityInverseKinematics::init(hardware_interface::EffortJointInterface *robot, ros::NodeHandle &n)\n\t{\n        KinematicChainControllerBase<hardware_interface::EffortJointInterface>::init(robot, n);\n\n\t\tjnt_to_jac_solver_.reset(new KDL::ChainJntToJacSolver(kdl_chain_));\n\t\tid_solver_.reset(new KDL::ChainDynParam(kdl_chain_,gravity_));\n\t\tfk_pos_solver_.reset(new KDL::ChainFkSolverPos_recursive(kdl_chain_));\n\t\ttau_cmd_.resize(kdl_chain_.getNrOfJoints());\n\t\tJ_.resize(kdl_chain_.getNrOfJoints());\n\t\tJ_star_.resize(kdl_chain_.getNrOfJoints());\n\n\t\tsub_command_ = nh_.subscribe(\"command\", 1, &MultiTaskPriorityInverseKinematics::command, this);\n\n\t\tpub_error_ = nh_.advertise<std_msgs::Float64MultiArray>(\"error\", 1000);\n\t\tpub_marker_ = nh_.advertise<visualization_msgs::MarkerArray>(\"marker\",1000);\n\n\t\treturn true;\n\t}\n\n\tvoid MultiTaskPriorityInverseKinematics::starting(const ros::Time& time)\n\t{\n\t\t// get joint positions\n  \t\tfor(int i=0; i < joint_handles_.size(); i++) \n  \t\t{\n    \t\tjoint_msr_states_.q(i) = joint_handles_[i].getPosition();\n    \t\tjoint_msr_states_.qdot(i) = joint_handles_[i].getVelocity();\n    \t\tjoint_des_states_.q(i) = joint_msr_states_.q(i);\n    \t\tjoint_des_states_.qdot(i) = joint_msr_states_.qdot(i);\n    \t}\n\n    \tI_ = Eigen::Matrix<double,7,7>::Identity(7,7);\n    \te_dot_ = Eigen::Matrix<double,6,1>::Zero();\n\n    \tcmd_flag_ = 0;\n\t}\n\n\tvoid MultiTaskPriorityInverseKinematics::update(const ros::Time& time, const ros::Duration& period)\n\t{\n\t\t// get joint positions\n  \t\tfor(int i=0; i < joint_handles_.size(); i++) \n  \t\t{\n    \t\tjoint_msr_states_.q(i) = joint_handles_[i].getPosition();\n    \t\tjoint_msr_states_.qdot(i) = joint_handles_[i].getVelocity();\n    \t}\n    \t\n    \t// clearing error msg before publishing\n    \tmsg_err_.data.clear();\n\n    \tif (cmd_flag_)\n    \t{\n    \t\t// resetting P and qdot(t=0) for the highest priority task\n    \t\tP_ = I_;\t\n    \t\tSetToZero(joint_des_states_.qdot);\n\n    \t\tfor (int index = 0; index < ntasks_; index++)\n    \t\t{\n\t\t    \t// computing Jacobian\n\t\t    \tjnt_to_jac_solver_->JntToJac(joint_msr_states_.q,J_,links_index_[index]);\n\n\t\t    \t// computing forward kinematics\n\t\t    \tfk_pos_solver_->JntToCart(joint_msr_states_.q,x_,links_index_[index]);\n\n\t\t    \t// setting marker parameters\n\t\t    \tset_marker(x_,index,msg_id_);\n\n\t\t    \t// computing end-effector position/orientation error w.r.t. desired frame\n\t\t    \tx_err_ = diff(x_,x_des_[index]);\n\n\t\t    \tfor(int i = 0; i < e_dot_.size(); i++)\n\t\t    \t{\n\t\t    \t\te_dot_(i) = x_err_(i);\n\t    \t\t\tmsg_err_.data.push_back(e_dot_(i));\n\t\t    \t}\n\n\t\t    \t// computing (J[i]*P[i-1])^pinv\n\t\t    \tJ_star_.data = J_.data*P_;\n\t\t    \tpseudo_inverse(J_star_.data,J_pinv_);\n\n\t\t    \t// computing q_dot (qdot(i) = qdot[i-1] + (J[i]*P[i-1])^pinv*(x_err[i] - J[i]*qdot[i-1]))\n\t\t    \tjoint_des_states_.qdot.data = joint_des_states_.qdot.data + J_pinv_*(e_dot_ - J_.data*joint_des_states_.qdot.data);\n\n\t\t    \t// stop condition\n\t\t    \tif (!on_target_flag_[index])\n\t\t    \t{\n\t\t\t    \tif (Equal(x_,x_des_[index],0.01))\n\t\t\t    \t{\n\t\t\t    \t\tROS_INFO(\"Task %d on target\",index);\n\t\t\t    \t\ton_target_flag_[index] = true;\n\t\t\t    \t\tif (index == (ntasks_ - 1))\n\t\t\t    \t\t\tcmd_flag_ = 0;\n\t\t\t    \t}\n\t\t\t    }\n\n\t\t    \t// updating P_ (it mustn't make use of the damped pseudo inverse)\n\t\t    \tpseudo_inverse(J_star_.data,J_pinv_,false);\n\t\t    \tP_ = P_ - J_pinv_*J_star_.data;\n\t\t    }\n\n\t\t    // integrating q_dot -> getting q (Euler method)\n\t\t    for (int i = 0; i < joint_handles_.size(); i++)\n\t\t    \tjoint_des_states_.q(i) += period.toSec()*joint_des_states_.qdot(i);\t\t\t\n    \t}\n\n    \t// set controls for joints\n    \tfor (int i = 0; i < joint_handles_.size(); i++)\n    \t{\n    \t\ttau_cmd_(i) = PIDs_[i].computeCommand(joint_des_states_.q(i) - joint_msr_states_.q(i),joint_des_states_.qdot(i) - joint_msr_states_.qdot(i),period);\n    \t\tjoint_handles_[i].setCommand(tau_cmd_(i));\n    \t}\n\n    \t// publishing markers for visualization in rviz\n    \tpub_marker_.publish(msg_marker_);\n    \tmsg_id_++;\n\n\t    // publishing error for all tasks as an array of ntasks*6\n\t    pub_error_.publish(msg_err_);\n\t    ros::spinOnce();\n\n\t}\n\n\tvoid MultiTaskPriorityInverseKinematics::command(const lwr_controllers::MultiPriorityTask::ConstPtr &msg)\n\t{\n\t\tif (msg->links.size() == msg->tasks.size()/6)\n\t\t{\n\t\t\tntasks_ = msg->links.size();\n\t\t\tROS_INFO(\"Number of tasks: %d\",ntasks_);\n\t\t\t// Dynamically resize desired postures and links index when a message arrives\n\t\t\tx_des_.resize(ntasks_);\n\t\t\tlinks_index_.resize(ntasks_);\n\t\t\ton_target_flag_.resize(ntasks_);\n\t\t\tmsg_marker_.markers.resize(ntasks_);\n\t\t\tmsg_id_ = 0;\n\n\t\t\tfor (int i = 0; i < ntasks_; i++)\n\t\t\t{\n\t\t\t\t\tif (msg->links[i] == -1)\t// adjust index\n\t\t\t\t\t\tlinks_index_[i] = msg->links[i];\n\t\t\t\t\telse if (msg->links[i] >= 1 && msg->links[i] <=joint_handles_.size())\n\t\t\t\t\t\tlinks_index_[i] = msg->links[i] + 1;\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tROS_INFO(\"Links index must be within 1 and %ld. (-1 is end-effector)\",joint_handles_.size());\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tx_des_[i] = KDL::Frame(\n\t\t\t\t\t\t\t\t\tKDL::Rotation::RPY(msg->tasks[i*6 + 3],\n\t\t\t\t\t\t\t\t\t\t\t\t\t   msg->tasks[i*6 + 4],\n\t\t\t\t\t\t\t\t\t\t\t\t\t   msg->tasks[i*6 + 5]),\n\t\t\t\t\t\t\t\t\tKDL::Vector(msg->tasks[i*6],\n\t\t\t\t\t\t\t\t\t\t\t\tmsg->tasks[i*6 + 1],\n\t\t\t\t\t\t\t\t\t\t\t\tmsg->tasks[i*6 + 2]));\n\n\t\t\t\t\ton_target_flag_[i] = false;\n\t\t\t}\n\n\t\t\tcmd_flag_ = 1;\n\t\t}\t\n\t\telse\n\t\t{\n\t\t\tROS_INFO(\"The number of links index and tasks must be the same\");\n\t\t\tROS_INFO(\"Tasks parameters are [x,y,x,roll,pitch,yaw]\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t}\n\n\tvoid MultiTaskPriorityInverseKinematics::set_marker(KDL::Frame x, int index, int id)\n\t{\t\t\t\n\t\t\t\tsstr_.str(\"\");\n\t\t\t\tsstr_.clear();\n\n\t\t\t\tif (links_index_[index] == -1)\n\t\t\t\t\tsstr_<<\"end_effector\";\t\t\n\t\t\t\telse\n\t\t\t\t\tsstr_<<\"link_\"<<(links_index_[index]-1);\n\n\n\t\t\t\tmsg_marker_.markers[index].header.frame_id = \"world\";\n\t\t\t\tmsg_marker_.markers[index].header.stamp = ros::Time();\n\t\t\t\tmsg_marker_.markers[index].ns = sstr_.str();\n\t\t\t\tmsg_marker_.markers[index].id = id;\n\t\t\t\tmsg_marker_.markers[index].type = visualization_msgs::Marker::SPHERE;\n\t\t\t\tmsg_marker_.markers[index].action = visualization_msgs::Marker::ADD;\n\t\t\t\tmsg_marker_.markers[index].pose.position.x = x.p(0);\n\t\t\t\tmsg_marker_.markers[index].pose.position.y = x.p(1);\n\t\t\t\tmsg_marker_.markers[index].pose.position.z = x.p(2);\n\t\t\t\tmsg_marker_.markers[index].pose.orientation.x = 0.0;\n\t\t\t\tmsg_marker_.markers[index].pose.orientation.y = 0.0;\n\t\t\t\tmsg_marker_.markers[index].pose.orientation.z = 0.0;\n\t\t\t\tmsg_marker_.markers[index].pose.orientation.w = 1.0;\n\t\t\t\tmsg_marker_.markers[index].scale.x = 0.01;\n\t\t\t\tmsg_marker_.markers[index].scale.y = 0.01;\n\t\t\t\tmsg_marker_.markers[index].scale.z = 0.01;\n\t\t\t\tmsg_marker_.markers[index].color.a = 1.0;\n\t\t\t\tmsg_marker_.markers[index].color.r = 0.0;\n\t\t\t\tmsg_marker_.markers[index].color.g = 1.0;\n\t\t\t\tmsg_marker_.markers[index].color.b = 0.0;\t\n\t}\n}\n\nPLUGINLIB_EXPORT_CLASS(lwr_controllers::MultiTaskPriorityInverseKinematics, controller_interface::ControllerBase)\n", "meta": {"hexsha": "13a1d038951bf851fb8f7023d61707fc87e4f171", "size": 7320, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lwr_controllers/src/multi_task_priority_inverse_kinematics.cpp", "max_stars_repo_name": "tecnalia-advancedmanufacturing-robotics/kuka-lwr", "max_stars_repo_head_hexsha": "6ee3eecc7df70beda20dbdd41e4f409d56bb88a5", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 106.0, "max_stars_repo_stars_event_min_datetime": "2015-01-20T12:45:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T11:27:28.000Z", "max_issues_repo_path": "lwr_controllers/src/multi_task_priority_inverse_kinematics.cpp", "max_issues_repo_name": "tecnalia-advancedmanufacturing-robotics/kuka-lwr", "max_issues_repo_head_hexsha": "6ee3eecc7df70beda20dbdd41e4f409d56bb88a5", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 92.0, "max_issues_repo_issues_event_min_datetime": "2015-01-26T09:08:37.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-13T09:31:41.000Z", "max_forks_repo_path": "lwr_controllers/src/multi_task_priority_inverse_kinematics.cpp", "max_forks_repo_name": "tecnalia-advancedmanufacturing-robotics/kuka-lwr", "max_forks_repo_head_hexsha": "6ee3eecc7df70beda20dbdd41e4f409d56bb88a5", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 93.0, "max_forks_repo_forks_event_min_datetime": "2015-01-23T16:39:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-09T09:24:39.000Z", "avg_line_length": 33.732718894, "max_line_length": 154, "alphanum_fraction": 0.6614754098, "num_tokens": 2148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4786887282309476}}
{"text": "#pragma once\n\n#include <cmath>\n#include <map>\n\n#include <Eigen/SparseLU>\n\n#include \"OpenABF/Exceptions.hpp\"\n#include \"OpenABF/HalfEdgeMesh.hpp\"\n#include \"OpenABF/Math.hpp\"\n\nnamespace OpenABF\n{\n\n/**\n * @brief Compute parameterized mesh using Angle-based LSCM\n *\n * Computes a least-squares conformal parameterization of a mesh. Unlike the\n * original LSCM algorithm, this class ignores the 3D vertex positions and\n * instead uses the angle associated with the mesh's edge trait\n * (MeshType::EdgeTraits::alpha) to calculate the initial per-triangle edge\n * lengths. Without previously modifying the angles of the provided mesh, this\n * class produces the same result as a vertex-based LSCM implementation.\n * However, by first processing the mesh with a parameterized angle optimizer,\n * such as ABFPlusPlus, the parameterization can be improved, sometimes\n * significantly.\n *\n * Implements the angle-based variant of \"Least squares conformal maps for\n * automatic texture atlas generation\" by L\u00e9vy _et al._ (2002)\n * \\cite levy2002lscm.\n *\n * @tparam T Floating-point type\n * @tparam MeshType HalfEdgeMesh type which implements the default mesh traits\n * @tparam Solver A solver implementing the\n * [Eigen Sparse solver\n * concept](https://eigen.tuxfamily.org/dox-devel/group__TopicSparseSystems.html)\n * and templated on Eigen::SparseMatrix<T>\n */\ntemplate <\n    typename T,\n    class MeshType = HalfEdgeMesh<T>,\n    class Solver =\n        Eigen::SparseLU<Eigen::SparseMatrix<T>, Eigen::COLAMDOrdering<int>>,\n    std::enable_if_t<std::is_floating_point<T>::value, bool> = true>\nclass AngleBasedLSCM\n{\npublic:\n    /** @brief Mesh type alias */\n    using Mesh = MeshType;\n\n    /** @copydoc AngleBasedLSCM::Compute */\n    void compute(typename Mesh::Pointer& mesh) const { Compute(mesh); }\n\n    /**\n     * @brief Compute the parameterized mesh\n     *\n     * @throws MeshException If pinned vertex is not on boundary.\n     * @throws SolverException If matrix cannot be decomposed or if solver fails\n     * to find a solution.\n     */\n    static void Compute(typename Mesh::Pointer& mesh)\n    {\n        using Triplet = Eigen::Triplet<T>;\n        using SparseMatrix = Eigen::SparseMatrix<T>;\n        using DenseMatrix = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>;\n\n        // Pinned vertex selection\n        // Get the end points of a boundary edge\n        auto p0 = mesh->vertices_boundary()[0];\n        auto e = p0->edge;\n        do {\n            if (not e->pair) {\n                break;\n            }\n            e = e->pair->next;\n        } while (e != p0->edge);\n        if (e == p0->edge and e->pair) {\n            throw MeshException(\"Pinned vertex not on boundary\");\n        }\n        auto p1 = e->next->vertex;\n\n        // Map selected edge to closest XY axis\n        // Use sign to select direction\n        auto pinVec = p1->pos - p0->pos;\n        auto dist = norm(pinVec);\n        pinVec /= dist;\n        p0->pos = {T(0), T(0), T(0)};\n        auto maxElem = std::max_element(pinVec.begin(), pinVec.end());\n        auto maxAxis = std::distance(pinVec.begin(), maxElem);\n        dist = std::copysign(dist, *maxElem);\n        if (maxAxis == 0) {\n            p1->pos = {dist, T(0), T(0)};\n        } else {\n            p1->pos = {T(0), dist, T(0)};\n        }\n\n        // For convenience\n        auto numFaces = mesh->num_faces();\n        auto numVerts = mesh->num_vertices();\n        auto numFixed = 2;\n        auto numFree = numVerts - numFixed;\n\n        // Permutation for free vertices\n        // This helps us find a vert's row in the solution matrix\n        std::map<std::size_t, std::size_t> freeIdxTable;\n        for (const auto& v : mesh->vertices()) {\n            if (v == p0 or v == p1) {\n                continue;\n            }\n            auto newIdx = freeIdxTable.size();\n            freeIdxTable[v->idx] = newIdx;\n        }\n\n        // Setup pinned bFixed\n        std::vector<Triplet> tripletsB;\n        tripletsB.emplace_back(0, 0, p0->pos[0]);\n        tripletsB.emplace_back(1, 0, p0->pos[1]);\n        tripletsB.emplace_back(2, 0, p1->pos[0]);\n        tripletsB.emplace_back(3, 0, p1->pos[1]);\n        SparseMatrix bFixed(2 * numFixed, 1);\n        bFixed.reserve(tripletsB.size());\n        bFixed.setFromTriplets(tripletsB.begin(), tripletsB.end());\n\n        // Setup variables matrix\n        // Are only solving for free vertices, so push pins in special matrix\n        std::vector<Triplet> tripletsA;\n        tripletsB.clear();\n        for (const auto& f : mesh->faces()) {\n            auto e0 = f->head;\n            auto e1 = e0->next;\n            auto e2 = e1->next;\n            auto sin0 = std::sin(e0->alpha);\n            auto sin1 = std::sin(e1->alpha);\n            auto sin2 = std::sin(e2->alpha);\n\n            // Find the max sin idx\n            std::vector<T> sins{sin0, sin1, sin2};\n            auto sinMaxElem = std::max_element(sins.begin(), sins.end());\n            auto sinMaxIdx = std::distance(sins.begin(), sinMaxElem);\n\n            // Rotate the edge order of the face so last angle is largest\n            if (sinMaxIdx == 0) {\n                auto temp = e0;\n                e0 = e1;\n                e1 = e2;\n                e2 = temp;\n                sin0 = sins[1];\n                sin1 = sins[2];\n                sin2 = sins[0];\n            } else if (sinMaxIdx == 1) {\n                auto temp = e2;\n                e2 = e1;\n                e1 = e0;\n                e0 = temp;\n                sin0 = sins[2];\n                sin1 = sins[0];\n                sin2 = sins[1];\n            }\n\n            auto ratio = (sin2 == T(0)) ? T(1) : sin1 / sin2;\n            auto cosine = std::cos(e0->alpha) * ratio;\n            auto sine = sin0 * ratio;\n\n            // If pin0 or pin1, put in fixedB matrix, else put in A\n            auto row = 2 * f->idx;\n            if (e0->vertex == p0) {\n                tripletsB.emplace_back(row, 0, cosine - T(1));\n                tripletsB.emplace_back(row, 1, -sine);\n                tripletsB.emplace_back(row + 1, 0, sine);\n                tripletsB.emplace_back(row + 1, 1, cosine - T(1));\n            } else if (e0->vertex == p1) {\n                tripletsB.emplace_back(row, 2, cosine - T(1));\n                tripletsB.emplace_back(row, 3, -sine);\n                tripletsB.emplace_back(row + 1, 2, sine);\n                tripletsB.emplace_back(row + 1, 3, cosine - T(1));\n            } else {\n                auto freeIdx = freeIdxTable.at(e0->vertex->idx);\n                tripletsA.emplace_back(row, 2 * freeIdx, cosine - T(1));\n                tripletsA.emplace_back(row, 2 * freeIdx + 1, -sine);\n                tripletsA.emplace_back(row + 1, 2 * freeIdx, sine);\n                tripletsA.emplace_back(row + 1, 2 * freeIdx + 1, cosine - T(1));\n            }\n\n            if (e1->vertex == p0) {\n                tripletsB.emplace_back(row, 0, -cosine);\n                tripletsB.emplace_back(row, 1, sine);\n                tripletsB.emplace_back(row + 1, 0, -sine);\n                tripletsB.emplace_back(row + 1, 1, -cosine);\n            } else if (e1->vertex == p1) {\n                tripletsB.emplace_back(row, 2, -cosine);\n                tripletsB.emplace_back(row, 3, sine);\n                tripletsB.emplace_back(row + 1, 2, -sine);\n                tripletsB.emplace_back(row + 1, 3, -cosine);\n            } else {\n                auto freeIdx = freeIdxTable.at(e1->vertex->idx);\n                tripletsA.emplace_back(row, 2 * freeIdx, -cosine);\n                tripletsA.emplace_back(row, 2 * freeIdx + 1, sine);\n                tripletsA.emplace_back(row + 1, 2 * freeIdx, -sine);\n                tripletsA.emplace_back(row + 1, 2 * freeIdx + 1, -cosine);\n            }\n\n            if (e2->vertex == p0) {\n                tripletsB.emplace_back(row, 0, T(1));\n                tripletsB.emplace_back(row + 1, 1, T(1));\n            } else if (e2->vertex == p1) {\n                tripletsB.emplace_back(row, 2, T(1));\n                tripletsB.emplace_back(row + 1, 3, T(1));\n            } else {\n                auto freeIdx = freeIdxTable.at(e2->vertex->idx);\n                tripletsA.emplace_back(row, 2 * freeIdx, T(1));\n                tripletsA.emplace_back(row + 1, 2 * freeIdx + 1, T(1));\n            }\n        }\n        SparseMatrix A(2 * numFaces, 2 * numFree);\n        A.reserve(tripletsA.size());\n        A.setFromTriplets(tripletsA.begin(), tripletsA.end());\n\n        SparseMatrix bFree(2 * numFaces, 2 * numFixed);\n        bFree.reserve(tripletsB.size());\n        bFree.setFromTriplets(tripletsB.begin(), tripletsB.end());\n\n        // Calculate rhs from free and fixed matrices\n        SparseMatrix b = bFree * bFixed * -1;\n\n        // Setup AtA and solver\n        SparseMatrix AtA = A.transpose() * A;\n        AtA.makeCompressed();\n        Solver solver;\n        solver.compute(AtA);\n        if (solver.info() != Eigen::ComputationInfo::Success) {\n            throw SolverException(solver.lastErrorMessage());\n        }\n\n        // Setup Atb\n        SparseMatrix Atb = A.transpose() * b;\n\n        // Solve AtAx = AtAb\n        DenseMatrix x = solver.solve(Atb);\n\n        // Assign solution to UV coordinates\n        // Pins are already updated, so these are free vertices\n        for (const auto& v : mesh->vertices()) {\n            if (v == p0 or v == p1) {\n                continue;\n            }\n            auto newIdx = 2 * freeIdxTable.at(v->idx);\n            v->pos[0] = x(newIdx, 0);\n            v->pos[1] = x(newIdx + 1, 0);\n            v->pos[2] = T(0);\n        }\n    }\n};\n\n}  // namespace OpenABF", "meta": {"hexsha": "7670227c655bec6f60d554ee3c79b6156e15ee66", "size": 9525, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/OpenABF/AngleBasedLSCM.hpp", "max_stars_repo_name": "educelab/OpenABF", "max_stars_repo_head_hexsha": "8b8c7cfc23e7bef21979f54099f19d28eba0e682", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2021-03-12T17:39:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T03:58:32.000Z", "max_issues_repo_path": "include/OpenABF/AngleBasedLSCM.hpp", "max_issues_repo_name": "educelab/OpenABF", "max_issues_repo_head_hexsha": "8b8c7cfc23e7bef21979f54099f19d28eba0e682", "max_issues_repo_licenses": ["Apache-2.0"], "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/OpenABF/AngleBasedLSCM.hpp", "max_forks_repo_name": "educelab/OpenABF", "max_forks_repo_head_hexsha": "8b8c7cfc23e7bef21979f54099f19d28eba0e682", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-03-12T17:39:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-04T13:30:08.000Z", "avg_line_length": 37.5, "max_line_length": 81, "alphanum_fraction": 0.5478215223, "num_tokens": 2524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4786887228916645}}
{"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_LDLT_HPP__\n#define __OPTIMISATION2_BA_LDLT_HPP__\n\n#include \"../container/container.hpp\"\n#include \"tuple_to_mat.hpp\"\n#include \"../omp/omp.hpp\"\n#include \"isdiagonal1f.hpp\"\n#include \"mat.hpp\"\n#include \"make_type.hpp\"\n#include <libv/lma/version.hpp>\n#include <boost/mpl/for_each.hpp>\n#include <boost/fusion/include/front.hpp>\n#include <libv/lma/time/tictoc.hpp>\n\nnamespace lma\n{  \n  template<class Delta, class X> struct AssignDelta\n  {\n    Delta& delta;\n    const X& x;\n    int& cpt;\n\n    AssignDelta(Delta& delta_, const X& x_, int& cpt_):delta(delta_),x(x_),cpt(cpt_){}\n\n    template<class Key> void operator()(ttt::wrap<Key>)\n    {\n      auto& refa = boost::fusion::at_key<Key>(delta);\n//       #pragma omp parallel for if(use_omp())\n      for(auto i = refa.first() ; i < refa.size() ; ++i)\n      {\n        for(size_t k = 0 ; k < refa.I ; ++k)\n          refa(i)[k] = x[cpt++];\n      }\n    }\n  };\n\n  template<class Delta, class X> AssignDelta<Delta,X> assign_delta(Delta& delta, const X& x, int& cpt)\n  {\n    return AssignDelta<Delta,X>(delta,x,cpt);\n  }\n\n  namespace internal\n  {\n    template<bool IsDiagonal1F> struct LDLT\n    {\n      template<class Tag, class Container, class Delta>\n      static void compute(const Container& container, Delta& delta)\n      {\n        auto a = to_mat<Tag,typename Container::OptimizeKeys,typename Container::Hessian>(container.A(),size_tuple<mpl::size<typename Container::OptimizeKeys>::value>(delta));\n//         auto a = to_sparse<typename Container::OptimizeKeys,typename Container::Hessian>(container.A(),size_tuple<mpl::size<typename Container::OptimizeKeys>::value>(delta));\n        auto b = to_matv<Tag>(container.B());\n\n        typename ContainerOption<Tag,0,0>::MatrixD1 x(b.size());\n\n        ldlt_solve(x,a,b);\n\n#ifndef NDEBUG\n        if (is_invalid(x)) throw NAN_ERROR(\"Ldlt : delta contains nan\");\n#endif\n        int cpt = 0;\n        mpl::for_each<typename Container::OptimizeKeys,ttt::wrap<mpl::_1>>(assign_delta(delta,x,cpt));\n      }\n    };\n    \n    template<> struct LDLT<true>\n    {\n      template<class Float, class Container, class Delta>\n      static void compute(const Container& container, Delta& delta)\n      {\n        auto& h = bf::front(container.A()).second;\n        auto& jte = bf::front(container.B()).second;\n        auto& d = bf::front(delta).second;\n        \n        if (h.size() == h.v.size()) // matrice diagonale par block\n      \t{\n      \t  for(auto i = h.first() ; i < h.size() ; ++i)\n      \t    d(i) = h(i).llt().solve(jte(i));\n      \t}\n      \telse\n      \t{\n      \t  LDLT<false>::compute(container,delta);\n      \t}\n      }\n    };\n  }\n  \n  struct LDLT\n  {\n    template<class Config>\n    LDLT(Config){}\n\n    template<class MatrixTag, class Container, class Delta, size_t TotalFParams = 1>\n    void operator()(const Container& container, Delta& delta, const MatrixTag&) const\n    {\n      internal::LDLT< IsDiagonal<Container>::value >::template compute<MatrixTag>(container,delta);\n    }\n  };\n\n}\n\nnamespace ttt\n{\n  template<> struct Name<lma::LDLT> { static std::string name(){ return \"LDLT\"; } };\n}\n#endif\n", "meta": {"hexsha": "3e25a30cf906068ea05cdc70cfc02b3288988510", "size": 3576, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/libv/lma/lm/ba/ldlt.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/ldlt.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/ldlt.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": 29.8, "max_line_length": 177, "alphanum_fraction": 0.5967561521, "num_tokens": 926, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4786887228916645}}
{"text": "/**\t\\file TestPerpTangentPoints.cpp\n*\t\\brief \n*/\n\n/****************************************************************************/\n/*\tTestPerpTangentPoints.cpp\t\t\t\t\t\t\t\t\t\t\t\t*/\n/****************************************************************************/\n/*                                                                          */\n/*  Copyright 2008 - 2010 Paul Kohut                                        */\n/*  Licensed under the Apache License, Version 2.0 (the \"License\"); you may */\n/*  not use this file except in compliance with the License. You may obtain */\n/*  a copy of the License at                                                */\n/*                                                                          */\n/*  http://www.apache.org/licenses/LICENSE-2.0                              */\n/*                                                                          */\n/*  Unless required by applicable law or agreed to in writing, software     */\n/*  distributed under the License is distributed on an \"AS IS\" BASIS,       */\n/*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or         */\n/*  implied. See the License for the specific language governing            */\n/*  permissions and limitations under the License.                          */\n/*                                                                          */\n/****************************************************************************/\n\n//#include \"stdafx.h\"\n#include <string>\n#include <fstream>\n#include \"LatLongConversions.h\"\n#include \"..\\GeoFormulas\\Conversions.h\"\n#include \"..\\GeoFormulas\\GeoFormulas.h\"\n#include <boost/regex.hpp>\n\nusing namespace boost;\nusing namespace GeoCalcs;\nusing namespace std;\n\nbool ParseTestPerpTangentPoints(string sString)\n{\n\tbool bPassed = false;\n\tTrimWhitespace(sString);\n\tstring sTestId, sGeoStartLat, sGeoStartLon, sGeoAzimuth;\n\tstring sArcCenterLat, sArcCenterLon, sArcRadius;\n\tstring sIntPt1Lat, sIntPt1Lon, sIntPt2Lat, sIntPt2Lon;\n\tstring sTanPt1Lat, sTanPt1Lon, sTanPt2Lat, sTanPt2Lon;\n\ttry\n\t{\n\t\tregex_constants::syntax_option_type flags =  regex_constants::icase | regex_constants::perl;\n\n\t\tstring sRxPat = \"([a-z]+|[A-Z]+\\\\d+)[,]\";\n\t\tsRxPat += \"([0-9]*[:][0-9]*[:][0-9]*[.][0-9]*[NS])[,]([0-9]*[:][0-9]*[:][0-9]*[.][0-9]*[WE])[,]\";\n\t\tsRxPat += \"([-+]?[0-9]*[.]?[0-9]+)[,]\";\n\t\tsRxPat += \"([0-9]*[:][0-9]*[:][0-9]*[.][0-9]*[NS])[,]([0-9]*[:][0-9]*[:][0-9]*[.][0-9]*[WE])[,]\";\n\t\tsRxPat += \"([-+]?[0-9]*[.]?[0-9]+)[,]\";\n\t\tsRxPat += \"([N/A]+|[0-9]*[:][0-9]*[:][0-9]*[.][0-9]*[NS])[,]([N/A]+|[0-9]*[:][0-9]*[:][0-9]*[.][0-9]*[WE])[,]\";\n\t\tsRxPat += \"([N/A]+|[0-9]*[:][0-9]*[:][0-9]*[.][0-9]*[NS])[,]([N/A]+|[0-9]*[:][0-9]*[:][0-9]*[.][0-9]*[WE])[,]\";\n\t\tsRxPat += \"([N/A]+|[0-9]*[:][0-9]*[:][0-9]*[.][0-9]*[NS])[,]([N/A]+|[0-9]*[:][0-9]*[:][0-9]*[.][0-9]*[WE])[,]\";\n\t\tsRxPat += \"([N/A]+|[0-9]*[:][0-9]*[:][0-9]*[.][0-9]*[NS])[,]([N/A]+|[0-9]*[:][0-9]*[:][0-9]*[.][0-9]*[WE])\";\n\n\t\tregex pat(sRxPat, flags);\n\n\t\tint const sub_matches[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, };\n\t\tsregex_token_iterator it(sString.begin(), sString.end(), pat, sub_matches);\n\t\tif(it != sregex_token_iterator())\n\t\t{\n\t\t\tsTestId = *it++;\n\t\t\tsGeoStartLat = *it++;\n\t\t\tsGeoStartLon = *it++;\n\t\t\tsGeoAzimuth = *it++;\n\t\t\tsArcCenterLat = *it++;\n\t\t\tsArcCenterLon = *it++;\n\t\t\tsArcRadius = *it++;\n\t\t\tsIntPt1Lat = *it++;\n\t\t\tsIntPt1Lon = *it++;\n\t\t\tsIntPt2Lat = *it++;\n\t\t\tsIntPt2Lon = *it++;\n\t\t\tsTanPt1Lat = *it++;\n\t\t\tsTanPt1Lon = *it++;\n\t\t\tsTanPt2Lat = *it++;\n\t\t\tsTanPt2Lon = *it++;\n\t\t\tbPassed = true;\n\t\t}\n\t}\n\tcatch(regex_error & e)\n\t{\n\t\tcout << \"\\n\" << e.what();\n\t\treturn false;\n\t}\n\n\tLLPoint geoPt(Deg2Rad(ParseLatitude(sGeoStartLat)), Deg2Rad(ParseLongitude(sGeoStartLon)));\n\tdouble geoAzimuth = Deg2Rad(atof(sGeoAzimuth.c_str()));\n\n\tLLPoint arc(Deg2Rad(ParseLatitude(sArcCenterLat)), Deg2Rad(ParseLongitude(sArcCenterLon)));\n\tdouble radius = NmToMeters(atof(sArcRadius.c_str()));\n\n\tLLPoint llIntPt1(Deg2Rad(ParseLatitude(sIntPt1Lat)), Deg2Rad(ParseLongitude(sIntPt1Lon)));\n\tLLPoint llIntPt2(Deg2Rad(ParseLatitude(sIntPt2Lat)), Deg2Rad(ParseLongitude(sIntPt2Lon)));\n\n\tLLPoint tangentPt1(Deg2Rad(ParseLatitude(sTanPt1Lat)), Deg2Rad(ParseLongitude(sTanPt1Lon)));\n\tLLPoint tangentPt2(Deg2Rad(ParseLatitude(sTanPt2Lat)), Deg2Rad(ParseLongitude(sTanPt2Lon)));\n\n\t\n\tLLPoint linePts[2];\n\tLLPoint tanPts[2];\n\tPerpTangentPoints(geoPt, geoAzimuth, arc, radius, linePts, tanPts, 1e-9);\n\n\n\t\tstring sInt1Lat = ConvertLatitudeDdToDms(Rad2Deg(linePts[0].latitude));\n\t\tstring sInt1Lon = ConvertLongitudeDdToDms(Rad2Deg(linePts[0].longitude));\n\t\tstring sInt2Lat = ConvertLatitudeDdToDms(Rad2Deg(linePts[1].latitude));\n\t\tstring sInt2Lon = ConvertLongitudeDdToDms(Rad2Deg(linePts[1].longitude));\n\t\tstring sTan1Lat = ConvertLatitudeDdToDms(Rad2Deg(tanPts[0].latitude));\n\t\tstring sTan1Lon = ConvertLongitudeDdToDms(Rad2Deg(tanPts[0].longitude));\n\t\tstring sTan2Lat = ConvertLatitudeDdToDms(Rad2Deg(tanPts[1].latitude));\n\t\tstring sTan2Lon = ConvertLongitudeDdToDms(Rad2Deg(tanPts[1].longitude));\n\n\t\tdouble dTol = 1e-10;\n\n\t\tif(sInt1Lat.compare(sIntPt1Lat) != 0)\n\t\t{\n\t\t\tdouble dLat = Deg2Rad(ParseLatitude(sIntPt1Lat));\n\t\t\tif(IsApprox(dLat, linePts[0].latitude, dTol))\n\t\t\t{\n\t\t\t\tcout << \"\\n\" << sTestId << \" within rounding tolerance of \" << dTol << \": Input Intercept pt 1 latitude: \" << sIntPt1Lat << \"  calced: \" << sInt1Lat;\n\t\t\t} else {\n\t\t\t\tcout << \"\\n\" << sTestId << \" failed: Expected Intercept pt 1 latitude: \" << sIntPt1Lat << \"  calced: \" << sInt1Lat;\n\t\t\t\tbPassed = false;\n\t\t\t}\n\t\t}\n\n\t\tif(sInt1Lon.compare(sIntPt1Lon) != 0)\n\t\t{\n\t\t\tdouble dLon = Deg2Rad(ParseLongitude(sIntPt1Lon));\n\t\t\tif(IsApprox(dLon, linePts[0].longitude, dTol))\n\t\t\t{\n\t\t\t\tcout << \"\\n\" << sTestId << \" within rounding tolerance of \" << dTol << \": Input Intercept pt 1 longitude: \" << sIntPt1Lon << \"  calced: \" << sInt1Lon;\n\t\t\t} else {\n\t\t\t\tcout << \"\\n\" << sTestId << \" failed: Expected Intercept pt 1 longitude: \" << sIntPt1Lon << \"  calced: \" << sInt1Lon;\n\t\t\t\tbPassed = false;\n\t\t\t}\n\t\t}\n\n\t\tif(sInt2Lat.compare(sIntPt2Lat) != 0)\n\t\t{\n\t\t\tdouble dLat = Deg2Rad(ParseLatitude(sIntPt2Lat));\n\t\t\tif(IsApprox(dLat, linePts[1].latitude, dTol))\n\t\t\t{\n\t\t\t\tcout << \"\\n\" << sTestId << \" within rounding tolerance of \" << dTol << \": Input Intercept pt 2 latitude: \" << sIntPt2Lat << \"  calced: \" << sInt2Lat;\n\t\t\t} else {\n\t\t\t\tcout << \"\\n\" << sTestId << \" failed: Expected Intercept pt 2 latitude: \" << sIntPt2Lat << \"  calced: \" << sInt2Lat;\n\t\t\t\tbPassed = false;\n\t\t\t}\n\t\t}\n\n\t\tif(sInt2Lon.compare(sIntPt2Lon) != 0)\n\t\t{\n\t\t\tdouble dLon = Deg2Rad(ParseLongitude(sIntPt2Lon));\n\t\t\tif(IsApprox(dLon, linePts[1].longitude, dTol))\n\t\t\t{\n\t\t\t\tcout << \"\\n\" << sTestId << \" within rounding tolerance of \" << dTol << \": Input Intercept pt 2 longitude: \" << sIntPt2Lon << \"  calced: \" << sInt2Lon;\n\t\t\t} else {\n\t\t\t\tcout << \"\\n\" << sTestId << \" failed: Expected Intercept pt 2 longitude: \" << sIntPt2Lon << \"  calced: \" << sInt2Lon;\n\t\t\t\tbPassed = false;\n\t\t\t}\n\t\t}\n\n\n\n\n\t\tif(sTan1Lat.compare(sTanPt1Lat) != 0)\n\t\t{\n\t\t\tdouble dLat = Deg2Rad(ParseLatitude(sTanPt1Lat));\n\t\t\tif(IsApprox(dLat, tanPts[0].latitude, dTol))\n\t\t\t{\n\t\t\t\tcout << \"\\n\" << sTestId << \" within rounding tolerance of \" << dTol << \": Input Tangent pt 1 latitude: \" << sTanPt1Lat << \"  calced: \" << sTan1Lat;\n\t\t\t} else {\n\t\t\t\tcout << \"\\n\" << sTestId << \" failed: Expected Tangent pt 1 latitude: \" << sTanPt1Lat << \"  calced: \" << sTan1Lat;\n\t\t\t\tbPassed = false;\n\t\t\t}\n\t\t}\n\n\t\tif(sTan1Lon.compare(sTanPt1Lon) != 0)\n\t\t{\n\t\t\tdouble dLon = Deg2Rad(ParseLongitude(sTanPt1Lon));\n\t\t\tif(IsApprox(dLon, tanPts[0].longitude, dTol))\n\t\t\t{\n\t\t\t\tcout << \"\\n\" << sTestId << \" within rounding tolerance of \" << dTol << \": Input Tangent pt 1 longitude: \" << sTanPt1Lon << \"  calced: \" << sTan1Lon;\n\t\t\t} else {\n\t\t\t\tcout << \"\\n\" << sTestId << \" failed: Expected Tangent pt 1 longitude: \" << sTanPt1Lon << \"  calced: \" << sTan1Lon;\n\t\t\t\tbPassed = false;\n\t\t\t}\n\t\t}\n\n\t\tif(sTan2Lat.compare(sTanPt2Lat) != 0)\n\t\t{\n\t\t\tdouble dLat = Deg2Rad(ParseLatitude(sTanPt2Lat));\n\t\t\tif(IsApprox(dLat, tanPts[1].latitude, dTol))\n\t\t\t{\n\t\t\t\tcout << \"\\n\" << sTestId << \" within rounding tolerance of \" << dTol << \": Input Tangent pt 2 latitude: \" << sTanPt2Lat << \"  calced: \" << sTan2Lat;\n\t\t\t} else {\n\t\t\t\tcout << \"\\n\" << sTestId << \" failed: Expected Tangent pt 2 latitude: \" << sTanPt2Lat << \"  calced: \" << sTan2Lat;\n\t\t\t\tbPassed = false;\n\t\t\t}\n\t\t}\n\n\t\tif(sTan2Lon.compare(sTanPt2Lon) != 0)\n\t\t{\n\t\t\tdouble dLon = Deg2Rad(ParseLongitude(sTanPt2Lon));\n\t\t\tif(IsApprox(dLon, tanPts[1].longitude, dTol))\n\t\t\t{\n\t\t\t\tcout << \"\\n\" << sTestId << \" within rounding tolerance of \" << dTol << \": Input Tangent pt 2 longitude: \" << sTanPt2Lon << \"  calced: \" << sTan2Lon;\n\t\t\t} else {\n\t\t\t\tcout << \"\\n\" << sTestId << \" failed: Expected Tangent pt 2 longitude: \" << sTanPt2Lon << \"  calced: \" << sTan2Lon;\n\t\t\t\tbPassed = false;\n\t\t\t}\n\t\t}\n\n\n\n\n\n\n\treturn bPassed;\t\n}\n\nint TestPerpTangentPoints(const string & sFilePath)\n{\n\tifstream infile;\n\tinfile.exceptions(ifstream::eofbit | ifstream::failbit | ifstream::badbit);\n\tint nCount = 0;\n\tint nCommentCount = 0;\n\tbool bPassed = true;\n\ttry\n\t{\n\t\tstring sLine;\n\t\tinfile.open(sFilePath.c_str(), ifstream::in);\n\n\t\twhile(!infile.eof())\n\t\t{\n\t\t\tgetline(infile, sLine);\t\t\t\n\t\t\tif(sLine.at(0) == '#')\n\t\t\t{\n\t\t\t\tnCommentCount++;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif(!ParseTestPerpTangentPoints(sLine))\n\t\t\t\t\tbPassed = false;\n\t\t\t\tnCount++;\n\t\t\t}\n\t\t}\n\t\tinfile.close();\n\t\treturn bPassed;\n\t}\n\n\tcatch(ifstream::failure e)\n\t{\n\t\tint nError = -99;\n\t\t// Per C++ standards for ifstream::failbit with global function getline\n\t\t// No characters were extracted because the end was prematurely found.Notice\n\t\t// that some eofbit cases will also set failbit.\n\t\t// In this case the end of the file is read and causes both flags to be raised,\n\t\t// so this presumably means all the data has been read correctly.\n\t\tif((infile.rdstate() & ifstream::failbit) && (infile.rdstate() & ifstream::eofbit) != 0)\n\t\t\tnError = bPassed;\n\t\telse if((infile.rdstate() & ifstream::failbit) != 0)\n\t\t\tnError = -1;\n\t\telse if((infile.rdstate() & ifstream::badbit) != 0)\n\t\t\tnError = -2;\n\t\telse if((infile.rdstate() & ifstream::eofbit) != 0)\n\t\t\tnError = -3;\n\t\tif(infile.is_open())\n\t\t\tinfile.close();\n\t\treturn nError;\n\t}\n}", "meta": {"hexsha": "73c192ec6521e561b0545dc791c1b23552097f1f", "size": 10111, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "TerpsTest/TestPerpTangentPoints.cpp", "max_stars_repo_name": "buffetboy2001/GeoFormulas", "max_stars_repo_head_hexsha": "d439b8941a84965d12078fad80307bc66444e46b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "TerpsTest/TestPerpTangentPoints.cpp", "max_issues_repo_name": "buffetboy2001/GeoFormulas", "max_issues_repo_head_hexsha": "d439b8941a84965d12078fad80307bc66444e46b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TerpsTest/TestPerpTangentPoints.cpp", "max_forks_repo_name": "buffetboy2001/GeoFormulas", "max_forks_repo_head_hexsha": "d439b8941a84965d12078fad80307bc66444e46b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.901459854, "max_line_length": 154, "alphanum_fraction": 0.5797646128, "num_tokens": 3318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239836484143, "lm_q2_score": 0.6688802735722128, "lm_q1q2_score": 0.4785329899028737}}
{"text": "/* vim: set tabstop=4 expandtab shiftwidth=4 softtabstop=4: */\n\n/**\n * \\file boost/numeric/ublasx/operation/realmax.hpp\n *\n * \\brief Largest positive normalized floating-point number.\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n *\n * <hr/>\n *\n * Copyright (c) 2010, Marco Guazzone\n *\n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#ifndef BOOST_NUMERIC_UBLASX_OPERATION_REALMAX_HPP\n#define BOOST_NUMERIC_UBLASX_OPERATION_REALMAX_HPP\n\n\n#include <boost/numeric/ublas/traits.hpp>\n#include <limits>\n\n\nnamespace boost { namespace numeric { namespace ublasx {\n\nusing namespace boost::numeric::ublas;\n\n/// Return the largest positive normalized floating-point number.\ntemplate <typename RealT>\nBOOST_UBLAS_INLINE\ntypename type_traits<RealT>::real_type realmax()\n{\n    return ::std::numeric_limits<typename type_traits<RealT>::real_type>::max();\n}\n\n}}} // Namespace boost::numeric::ublasx\n\n#endif // BOOST_NUMERIC_UBLASX_OPERATION_REALMAX_HPP\n", "meta": {"hexsha": "6b72f5046a9d59596ced48316a41fc1a7b5015ba", "size": 1061, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/ublasx/operation/realmax.hpp", "max_stars_repo_name": "sguazt/boost-ublasx", "max_stars_repo_head_hexsha": "21c9b393d33a6ec2a8071ba8d48680073d766409", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2016-05-14T11:08:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-05T14:22:20.000Z", "max_issues_repo_path": "boost/numeric/ublasx/operation/realmax.hpp", "max_issues_repo_name": "sguazt/boost-ublasx", "max_issues_repo_head_hexsha": "21c9b393d33a6ec2a8071ba8d48680073d766409", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-12-28T18:36:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-06T11:28:51.000Z", "max_forks_repo_path": "boost/numeric/ublasx/operation/realmax.hpp", "max_forks_repo_name": "sguazt/boost-ublasx", "max_forks_repo_head_hexsha": "21c9b393d33a6ec2a8071ba8d48680073d766409", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-12-23T02:53:27.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-23T02:53:27.000Z", "avg_line_length": 25.2619047619, "max_line_length": 80, "alphanum_fraction": 0.7596606975, "num_tokens": 270, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.47853298857531695}}
{"text": "\n#include \"stdafx.h\"\n#include <boost/test/unit_test.hpp>\n#include \"BirthdayChocolate.h\"\n\nusing namespace HackerRank;\n\nBirthdayChocolate* bc;\n\nvoid assertCountPartitions(vector<int> s, int day, int month, int expectedCount) {\n\tBOOST_TEST(expectedCount == bc->CountPossiblePartitions(s, day, month));\n}\n\nBOOST_AUTO_TEST_SUITE(BirthdayChocolateTests)\n\nBOOST_AUTO_TEST_CASE(GivenReqdInputs_WhenCountPossiblePartitions_ThenReturnPartitionsCount) {\n\tbc = new BirthdayChocolate;\n\n\tassertCountPartitions({ 1 }, 1, 1, 1);\n\tassertCountPartitions({ 1 }, 2, 1, 0);\n\tassertCountPartitions({ 2 }, 2, 1, 1);\n\tassertCountPartitions({ 1 }, 1, 2, 0);\n\tassertCountPartitions({ 1, 1 }, 1, 1, 2);\n\tassertCountPartitions({ 1, 1 }, 1, 3, 0);\n\tassertCountPartitions({ 1, 1 }, 2, 1, 0);\n\tassertCountPartitions({ 1, 1 }, 2, 2, 1);\n\tassertCountPartitions({ 1, 2, 1, 3, 2 }, 3, 2, 2);\n\tassertCountPartitions({ 1, 1, 1, 1, 1, 1 }, 3, 2, 0);\n\tassertCountPartitions({ 4, 1 }, 4, 1, 1);\n}\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "8412ac9cf0ee1f05df0e57b78606d109add2ebd9", "size": 985, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "HackerRank-C++/HackerRank/HackerRankTest/BirthdayChocolateTest.cpp", "max_stars_repo_name": "domEnriquez/Algorithms", "max_stars_repo_head_hexsha": "ec156f04f83463bcb320f55dc7234b558454c418", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "HackerRank-C++/HackerRank/HackerRankTest/BirthdayChocolateTest.cpp", "max_issues_repo_name": "domEnriquez/Algorithms", "max_issues_repo_head_hexsha": "ec156f04f83463bcb320f55dc7234b558454c418", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HackerRank-C++/HackerRank/HackerRankTest/BirthdayChocolateTest.cpp", "max_forks_repo_name": "domEnriquez/Algorithms", "max_forks_repo_head_hexsha": "ec156f04f83463bcb320f55dc7234b558454c418", "max_forks_repo_licenses": ["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.78125, "max_line_length": 93, "alphanum_fraction": 0.7106598985, "num_tokens": 344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.7154239897159438, "lm_q1q2_score": 0.4785329845168662}}
{"text": "#ifdef STAND_ALONE\n#   define BOOST_TEST_MODULE DemoTests\n#endif\n\n#include <boost/test/unit_test.hpp>\n#include <stdexcept>\n#include \"../src/shared/Calculator.hpp\"\n\n// Scenariusze danych:\n\n// add\n// 1,1\n// 3,1\n// 1,3\n// -1,-3\n// -3,-1\n// 'a','b'\n// 1.5,2.5\n// min int i max int\n\n\n// min\n\n// mult\n\n// div \n\n\n\n\nBOOST_AUTO_TEST_SUITE(calculator_suite)\n\n    BOOST_AUTO_TEST_CASE(add_test_1_1)\n    {\n        Calculator calculator(1,1);\n        BOOST_CHECK_EQUAL(calculator.add(), 2);\n    }\n\n    BOOST_AUTO_TEST_CASE(add_test_3_1)\n    {\n        Calculator calculator(3,1);\n        BOOST_CHECK_EQUAL(calculator.add(), 4);\n    }\n\n    BOOST_AUTO_TEST_CASE(add_test_1_3)\n    {\n        Calculator calculator(1,3);\n        BOOST_CHECK_EQUAL(calculator.add(), 4);\n    }\n\n    BOOST_AUTO_TEST_CASE(add_test_minus_1_minus_3)\n    {\n        Calculator calculator(-1,-3);\n        BOOST_CHECK_EQUAL(calculator.add(), -4);\n    }\n\n    BOOST_AUTO_TEST_CASE(add_test_minus_3_minus_1)\n    {\n        Calculator calculator(-3,-1);\n        BOOST_CHECK_EQUAL(calculator.add(), -4);\n    }\n\n    BOOST_AUTO_TEST_CASE(add_test_a_b)\n    {\n        Calculator calculator('a','b');  // 'a' in ascii table: 97, 'b' in ascii table: 98 !!!\n        BOOST_CHECK_EQUAL(calculator.add(), 195);\n    }\n\n    BOOST_AUTO_TEST_CASE(add_test_1_5_2_5)\n    {\n        Calculator calculator(1.5,2.5);  // !!!\n        BOOST_CHECK_EQUAL(calculator.add(), 4.0);\n    }\n\n    BOOST_AUTO_TEST_CASE(add_test_min_value)\n    {\n        Calculator calculator(5,std::numeric_limits<int>::min()); // min value for int is -2147483648\n        BOOST_CHECK_EQUAL(calculator.add(), -2147483643);\n    }\n\n    BOOST_AUTO_TEST_CASE(add_test_max_value)\n    {\n        Calculator calculator(5,std::numeric_limits<int>::max()); // max value for int is 2147483647\n        BOOST_CHECK_EQUAL(calculator.add(), -2147483644);  // !!!\n    }\n\n    BOOST_AUTO_TEST_CASE(div_test_1_0)\n    {\n        Calculator calculator(1,0);\n        BOOST_CHECK_THROW(calculator.div(), std::exception);\n    }\n\nBOOST_AUTO_TEST_SUITE_END()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "306afaa89eaaf8032636d4b9319fc9baa6b6b2b4", "size": 2049, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_Calculator.cpp", "max_stars_repo_name": "wkusmirek/cmake-boost-demo", "max_stars_repo_head_hexsha": "c1d8528415448d1911ed238965a56cf474bc3781", "max_stars_repo_licenses": ["MIT"], "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_Calculator.cpp", "max_issues_repo_name": "wkusmirek/cmake-boost-demo", "max_issues_repo_head_hexsha": "c1d8528415448d1911ed238965a56cf474bc3781", "max_issues_repo_licenses": ["MIT"], "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_Calculator.cpp", "max_forks_repo_name": "wkusmirek/cmake-boost-demo", "max_forks_repo_head_hexsha": "c1d8528415448d1911ed238965a56cf474bc3781", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-05-09T06:21:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-10T17:46:35.000Z", "avg_line_length": 18.1327433628, "max_line_length": 101, "alphanum_fraction": 0.6329917033, "num_tokens": 555, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834734, "lm_q2_score": 0.6688802537704064, "lm_q1q2_score": 0.47853298385308785}}
{"text": "// Copyright 2015-2018 Hans Dembinski\n//\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include <boost/core/lightweight_test.hpp>\n#include <boost/histogram/accumulators/mean.hpp>\n#include <boost/histogram/accumulators/ostream.hpp>\n#include <boost/histogram/accumulators/sum.hpp>\n#include <boost/histogram/accumulators/thread_safe.hpp>\n#include <boost/histogram/accumulators/weighted_mean.hpp>\n#include <boost/histogram/accumulators/weighted_sum.hpp>\n#include <boost/histogram/detail/throw_exception.hpp>\n#include <sstream>\n#include \"is_close.hpp\"\n\nusing namespace boost::histogram;\nusing namespace std::literals;\n\ntemplate <class T>\nauto str(const T& t) {\n  std::ostringstream os;\n  os << t;\n  return os.str();\n}\n\nint main() {\n  {\n    using w_t = accumulators::weighted_sum<double>;\n    w_t w;\n    BOOST_TEST_EQ(str(w), \"weighted_sum(0, 0)\"s);\n\n    BOOST_TEST_EQ(w, w_t(0));\n    BOOST_TEST_NE(w, w_t(1));\n    w = w_t(1);\n    BOOST_TEST_EQ(w.value(), 1);\n    BOOST_TEST_EQ(w.variance(), 1);\n    BOOST_TEST_EQ(w, 1);\n    BOOST_TEST_NE(w, 2);\n\n    w += 2;\n    BOOST_TEST_EQ(w.value(), 3);\n    BOOST_TEST_EQ(w.variance(), 5);\n    BOOST_TEST_EQ(w, w_t(3, 5));\n    BOOST_TEST_NE(w, w_t(3));\n\n    w += w_t(1, 2);\n    BOOST_TEST_EQ(w.value(), 4);\n    BOOST_TEST_EQ(w.variance(), 7);\n\n    // consistency: a weighted counter increased by weight 1 multiplied\n    // by 2 must be the same as a weighted counter increased by weight 2\n    w_t u(0);\n    ++u;\n    u *= 2;\n    BOOST_TEST_EQ(u, w_t(2, 4));\n\n    w_t v(0);\n    v += 2;\n    BOOST_TEST_EQ(u, v);\n\n    // conversion to RealType\n    w_t y(1, 2);\n    BOOST_TEST_NE(y, 1);\n    BOOST_TEST_EQ(static_cast<double>(y), 1);\n  }\n\n  {\n    using m_t = accumulators::mean<double>;\n    m_t a;\n    BOOST_TEST_EQ(a.count(), 0);\n\n    a(4);\n    a(7);\n    a(13);\n    a(16);\n\n    BOOST_TEST_EQ(a.count(), 4);\n    BOOST_TEST_EQ(a.value(), 10);\n    BOOST_TEST_EQ(a.variance(), 30);\n\n    BOOST_TEST_EQ(str(a), \"mean(4, 10, 30)\"s);\n\n    m_t b;\n    b(1e8 + 4);\n    b(1e8 + 7);\n    b(1e8 + 13);\n    b(1e8 + 16);\n\n    BOOST_TEST_EQ(b.count(), 4);\n    BOOST_TEST_EQ(b.value(), 1e8 + 10);\n    BOOST_TEST_EQ(b.variance(), 30);\n\n    auto c = a;\n    c += a; // same as feeding all samples twice\n\n    BOOST_TEST_EQ(c.count(), 8);\n    BOOST_TEST_EQ(c.value(), 10);\n    BOOST_TEST_IS_CLOSE(c.variance(), 25.714, 1e-3);\n  }\n\n  {\n    using m_t = accumulators::weighted_mean<double>;\n    m_t a;\n    BOOST_TEST_EQ(a.sum_of_weights(), 0);\n\n    a(0.5, 1);\n    a(1.0, 2);\n    a(0.5, 3);\n\n    BOOST_TEST_EQ(a.sum_of_weights(), 2);\n    BOOST_TEST_EQ(a.value(), 2);\n    BOOST_TEST_IS_CLOSE(a.variance(), 0.8, 1e-3);\n\n    BOOST_TEST_EQ(str(a), \"weighted_mean(2, 2, 0.8)\"s);\n\n    auto b = a;\n    b += a; // same as feeding all samples twice\n\n    BOOST_TEST_EQ(b.sum_of_weights(), 4);\n    BOOST_TEST_EQ(b.value(), 2);\n    BOOST_TEST_IS_CLOSE(b.variance(), 0.615, 1e-3);\n  }\n\n  {\n    double bad_sum = 0;\n    bad_sum += 1;\n    bad_sum += 1e100;\n    bad_sum += 1;\n    bad_sum += -1e100;\n    BOOST_TEST_EQ(bad_sum, 0); // instead of 2\n\n    accumulators::sum<double> sum;\n    ++sum;\n    BOOST_TEST_EQ(sum.large(), 1);\n    BOOST_TEST_EQ(sum.small(), 0);\n    BOOST_TEST_EQ(str(sum), \"sum(1 + 0)\"s);\n    sum += 1e100;\n    BOOST_TEST_EQ(str(sum), \"sum(1e+100 + 1)\"s);\n    ++sum;\n    BOOST_TEST_EQ(str(sum), \"sum(1e+100 + 2)\"s);\n    sum += -1e100;\n    BOOST_TEST_EQ(str(sum), \"sum(0 + 2)\"s);\n    BOOST_TEST_EQ(sum, 2); // correct answer\n    BOOST_TEST_EQ(sum.large(), 0);\n    BOOST_TEST_EQ(sum.small(), 2);\n\n    accumulators::sum<double> a(3), b(2), c(3);\n    BOOST_TEST_LT(b, c);\n    BOOST_TEST_LE(b, c);\n    BOOST_TEST_LE(a, c);\n    BOOST_TEST_GT(a, b);\n    BOOST_TEST_GE(a, b);\n    BOOST_TEST_GE(a, c);\n  }\n\n  {\n    accumulators::weighted_sum<accumulators::sum<double>> w;\n\n    ++w;\n    w += 1e100;\n    ++w;\n    w += -1e100;\n\n    BOOST_TEST_EQ(w.value(), 2);\n    BOOST_TEST_EQ(w.variance(), 2e200);\n  }\n\n  {\n    accumulators::thread_safe<int> i;\n    ++i;\n    i += 1000;\n\n    BOOST_TEST_EQ(i, 1001);\n    BOOST_TEST_EQ(str(i), \"1001\"s);\n  }\n\n  return boost::report_errors();\n}\n", "meta": {"hexsha": "c028c8aa7ccc34b7c51d879fd9450964d66fdf5b", "size": 4176, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/internal_accumulators_test.cpp", "max_stars_repo_name": "glenfe/boost.histogram", "max_stars_repo_head_hexsha": "376ddeadc40e4de6dffb9ad87668b3efa52b08b5", "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": "test/internal_accumulators_test.cpp", "max_issues_repo_name": "glenfe/boost.histogram", "max_issues_repo_head_hexsha": "376ddeadc40e4de6dffb9ad87668b3efa52b08b5", "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/internal_accumulators_test.cpp", "max_forks_repo_name": "glenfe/boost.histogram", "max_forks_repo_head_hexsha": "376ddeadc40e4de6dffb9ad87668b3efa52b08b5", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.0718232044, "max_line_length": 72, "alphanum_fraction": 0.6120689655, "num_tokens": 1363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834732, "lm_q2_score": 0.6688802537704064, "lm_q1q2_score": 0.4785329838530877}}
{"text": "#ifndef MHTLP_HPP_\n#define MHTLP_HPP_\n\n#include <NTL/ZZ.h>\n#include <assert.h>\n#include <openssl/sha.h>\n#include <vector>\n#include <sstream>\n\n#include \"Puzzle.hpp\"\n#include \"HTLP.hpp\"\n\n#ifndef RSA_\n#define RSA_\ntypedef struct RSA\n{\n    NTL::ZZ p;\n    NTL::ZZ q;\n} RSA;\n#endif\n\nclass MHTLP : public HTLP\n{\n\nprivate:\n    NTL::ZZ chi_;\n\npublic:\n    MHTLP(const long modulus_len, const long T, const long kappa);\n    MHTLP(const NTL::ZZ &n, const NTL::ZZ &g, const NTL::ZZ &h, const NTL::ZZ &chi, const long T, const long kappa);\n    MHTLP(const long modulus_len, const long T, const long kappa, bool cheeting_mode);\n\n    NTL::ZZ chi()\n    {\n        return chi_;\n    }\n\n    MPuzzle GeneratePuzzle(const NTL::ZZ &s);\n    MPuzzle GeneratePuzzle(const NTL::ZZ &s, const NTL::ZZ &r, const NTL::ZZ &r_prime);\n    NTL::ZZ SolvePuzzle(const MPuzzle &Z);\n    NTL::ZZ QuickSolvePuzzle(const MPuzzle &Z);\n\n    std::tuple<std::vector<NTL::ZZ>, std::vector<NTL::ZZ>, std::vector<NTL::ZZ>, std::vector<NTL::ZZ>> GenerateMValidProof(const MPuzzle &Z, const NTL::ZZ &s, const NTL::ZZ &r, const NTL::ZZ &r_prime);\n    bool VerifyMValidProof(const MPuzzle &Z, const std::tuple<std::vector<NTL::ZZ>, std::vector<NTL::ZZ>, std::vector<NTL::ZZ>, std::vector<NTL::ZZ>> &proof);\n\n    std::tuple<NTL::ZZ, NTL::ZZ, NTL::ZZ, NTL::ZZ, NTL::ZZ> SolvePuzzleWithProof(const long k, const long gamma, const MPuzzle &Z);\n    std::tuple<NTL::ZZ, NTL::ZZ, NTL::ZZ, NTL::ZZ, NTL::ZZ> QuickSolvePuzzleWithProof(const MPuzzle &Z);\n\n    int VerifyProofOfSol(const MPuzzle Z, const std::tuple<NTL::ZZ, NTL::ZZ, NTL::ZZ, NTL::ZZ, NTL::ZZ> &proof);\n};\n\n#endif", "meta": {"hexsha": "cf44c95c98a9a8e0fae4edd8fc1365e6c3bde8f8", "size": 1615, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/MHTLP.hpp", "max_stars_repo_name": "liu-yi/HTLP", "max_stars_repo_head_hexsha": "c66a0c8b126c52e6ac74dbba9b7be0828bb8ef45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/MHTLP.hpp", "max_issues_repo_name": "liu-yi/HTLP", "max_issues_repo_head_hexsha": "c66a0c8b126c52e6ac74dbba9b7be0828bb8ef45", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/MHTLP.hpp", "max_forks_repo_name": "liu-yi/HTLP", "max_forks_repo_head_hexsha": "c66a0c8b126c52e6ac74dbba9b7be0828bb8ef45", "max_forks_repo_licenses": ["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.0576923077, "max_line_length": 201, "alphanum_fraction": 0.6681114551, "num_tokens": 544, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.5698526514141572, "lm_q1q2_score": 0.47852463253170996}}
{"text": "#include \"Derivatives.hpp\"\n\n#include <fmt/format.h>\n#include <spdlog/spdlog.h>\n#include <boost/range/adaptor/indexed.hpp>\n#include <boost/range/combine.hpp>\n#include <boost/range/irange.hpp>\n\n#include <FeltElements/internal/Format.hpp>\n#include \"Body.hpp\"\n\nnamespace\n{\nusing namespace FeltElements;\n\ntemplate <typename T>\nint sgn(T val)\n{\n\treturn (T(0) < val) - (val < T(0));\n}\nauto constexpr delta = [](auto const i, auto const j) { return i == j; };\n\nElement::Elasticity const c_lambda = ([]() {  // NOLINT(cert-err58-cpp)\n\tstd::size_t constexpr N = 3;\n\tElement::Elasticity c{};\n\tfor (std::size_t i = 0; i < N; i++)\n\t\tfor (std::size_t j = 0; j < N; j++)\n\t\t\tfor (std::size_t k = 0; k < N; k++)\n\t\t\t\tfor (std::size_t l = 0; l < N; l++) c(i, j, k, l) = delta(i, j) * delta(k, l);\n\n\treturn c;\n}());\n\n// TODO: constexpr - requires constexpr std::copy (C++20)\nElement::Elasticity const c_mu = ([]() {  // NOLINT(cert-err58-cpp)\n\tstd::size_t constexpr N = 3;\n\tElement::Elasticity c{};\n\tfor (std::size_t i = 0; i < N; i++)\n\t\tfor (std::size_t j = 0; j < N; j++)\n\t\t\tfor (std::size_t k = 0; k < N; k++)\n\t\t\t\tfor (std::size_t l = 0; l < N; l++)\n\t\t\t\t\tc(i, j, k, l) = delta(i, k) * delta(j, l) + delta(i, l) * delta(j, k);\n\n\treturn c;\n}());\n\n// TODO: constexpr - requries simd_vector_type to satisfy literal type requirements\nTensor::Matrix<3> const I = ([]() {\t // NOLINT(cert-err58-cpp)\n\tTensor::Matrix<3> mat{};\n\tmat.eye2();\n\treturn mat;\n}());\n}  // namespace\n\nnamespace FeltElements::ex\n{\nusing namespace Tensor;\n\nconstexpr auto dX_by_dL = [](auto const & X) {\n\treturn Func::einsum<Idxs<k, i>, Idxs<k, j>>(X, Derivatives::dN_by_dL);\n};\n\nconstexpr auto dL_by_dX = [](auto const & dX_by_dL_) { return Func::inv(dX_by_dL_); };\n\nconstexpr auto dX_by_dS = [](auto const & X) {\n\treturn Func::einsum<Idxs<k, i>, Idxs<k, j>>(X, Derivatives::dN_by_dS);\n};\n\nconstexpr auto dN_by_dX = [](auto const & dL_by_dX_) {\n\t// dN/dX^T = dX/dL^(-T) * dN/dL^T => dN/dX = dN/dL * dX/dL^(-1) = dN/dL * dL/dX\n\treturn Func::einsum<Idxs<i, k>, Idxs<k, j>>(Derivatives::dN_by_dL, dL_by_dX_);\n};\n\nconstexpr auto dx_by_dX = [](auto const & x, auto const & dN_by_dX_) {\n\treturn Func::einsum<Idxs<k, i>, Idxs<k, j>>(x, dN_by_dX_);\n};\n\nconstexpr auto finger = [](auto const & F) { return Func::einsum<Idxs<i, k>, Idxs<j, k>>(F, F); };\n\nconstexpr auto sigma = [](Scalar const J, auto const & b, Scalar const lambda, Scalar const mu) {\n\treturn (mu / J) * (b - I) + (lambda / J) * log(J) * I;\n};\n\nconstexpr auto T = [](auto const & dN_by_dx, auto const & sigma_) {\n\t// T = v * sigma * dN/dx^T\n\treturn Func::einsum<Idxs<a, k>, Idxs<i, k>>(dN_by_dx, sigma_);\n};\n\nconstexpr auto c = [](Scalar J, Scalar lambda, Scalar mu) {\n\tScalar const lambda_prime = lambda / J;\n\tScalar const mu_prime = (mu - lambda * std::log(J)) / J;\n\n\treturn lambda_prime * c_lambda + mu_prime * c_mu;\n};\n\nconstexpr auto Kc = [](auto const & dN_by_dx, auto const & c_) {\n\t// Kc_ij = v * dN_a/dx_k * c_ikjl * dN_b/dx_l\n\treturn Func::einsum<Idxs<a, k>, Idxs<i, k, j, l>, Idxs<b, l>, Order<a, i, b, j>>(\n\t\tdN_by_dx, c_, dN_by_dx);\n};\n\nconstexpr auto Ks = [](auto const & dN_by_dx, auto const & s) {\n\t// Ks_ij = v * dN_a/dx_k * sigma_kl * dN_b/dx_l * delta_ij\n\treturn Func::einsum<Idxs<a, k>, Idxs<k, l>, Idxs<b, l>, Idxs<i, j>, Order<a, i, b, j>>(\n\t\tdN_by_dx, s, dN_by_dx, I);\n};\n}  // namespace FeltElements::ex\n\nnamespace FeltElements::Derivatives\n{\nElement::StiffnessResidual KR(\n\tElement::NodePositions const & x,\n\tElement::BoundaryVtxhIdxs const & boundary_faces_idxs,\n\tElement::BoundaryNodePositions const & boundary_faces_x,\n\tElement::ShapeDerivative const & dN_by_dX,\n\tBody::Material const & material,\n\tBody::Forces const & forces)\n{\n\tusing Tensor::Func::all;\n\n\tElement::Gradient const dx_by_dX = ex::dx_by_dX(x, dN_by_dX);\n\tauto const b = ex::finger(dx_by_dX);\n\tScalar const J = Derivatives::det_dx_by_dX(dx_by_dX);\n\tif (J < 0)\n\t{\n\t\tstd::string const msg =\n\t\t\tfmt::format(\"Error: J < 0:\\nJ = {}\\nF = {}\\nb = {}\", J, dx_by_dX, b);\n\t\tspdlog::error(msg);\n\t\tthrow std::invalid_argument{msg};\n\t}\n\tScalar const v = Derivatives::v(x);\t // TODO: but also v = J*V\n\n\tauto const & dx_by_dL = ex::dX_by_dL(x);\n\tauto const & dL_by_dx = ex::dL_by_dX(dx_by_dL);\n\tElement::ShapeDerivative const dN_by_dx = ex::dN_by_dX(dL_by_dx);\n\n\tElement::Stress const sigma = ex::sigma(J, b, material.lambda, material.mu);\n\n\tauto const & c = ex::c(J, material.lambda, material.mu);\n\t// Elasticity component.\n\tauto const & Kc = ex::Kc(dN_by_dx, c);\n\t// Initial stress component.\n\tauto const & Ks = ex::Ks(dN_by_dx, sigma);\n\t// Constitutive (traction) component.\n\tauto const & Kp = Derivatives::Kp(boundary_faces_x, boundary_faces_idxs, forces.p);\n\n\t// Tangent stiffness matrix.\n\tElement::Stiffness K = v * (Kc + Ks) + Kp;\n\n\t// Internal forces.\n\tauto const & T_by_v = ex::T(dN_by_dx, sigma);\n\n\t// Residual\n\tElement::Forces R = v * T_by_v;\n\n\t// Body force.\n\tauto const & F_by_V = forces.F_by_m * material.rho;\n\tauto const & F_by_v = F_by_V / J;\n\tauto const & F_by_v_per_node = (1.0 / Element::num_nodes) * F_by_v;\n\tNode::Force const F_per_node = v * F_by_v_per_node;\n\n\tfor (const auto node_idx : boost::irange(Element::num_nodes)) R(node_idx, all) -= F_per_node;\n\n\t// Traction force.\n\tfor (const auto & [s, idxs] : boost::range::combine(boundary_faces_x, boundary_faces_idxs))\n\t{\n\t\tconst Node::Force & t =\n\t\t\t(1.0 / BoundaryElement::num_nodes) * Derivatives::t(forces.p, Derivatives::dX_by_dS(s));\n\t\tfor (Tensor::Index const node_idx : idxs) R(node_idx, all) -= t;\n\t}\n\t/*\n\t\tif (!Tensor::Func::all_of(R == R))\t// Assert no NaNs\n\t\t{\n\t\t\tstd::string const & msg = fmt::format(\n\t\t\t\t\"Residual is NaN because: v={}; T_by_v={}; dN_by_dx={}; sigma={}; J={}; b={}; \"\n\t\t\t\t\"dx_by_dX={}.  Where J={}; dx_by_dX=\\n{}\",\n\t\t\t\tstd::isnan(v),\n\t\t\t\t!Tensor::Func::all_of(T_by_v == T_by_v),\n\t\t\t\t!Tensor::Func::all_of(dN_by_dx == dN_by_dx),\n\t\t\t\t!Tensor::Func::all_of(sigma == sigma),\n\t\t\t\tstd::isnan(J),\n\t\t\t\t!Tensor::Func::all_of(b == b),\n\t\t\t\t!Tensor::Func::all_of(dx_by_dX == dx_by_dX),\n\t\t\t\tJ,\n\t\t\t\tdx_by_dX);\n\n\t\t\tspdlog::error(msg);\n\n\t\t\tthrow std::logic_error{msg};\n\t\t};\n\t*/\n\treturn {K, R};\n}\n\nElement::Stiffness Kc(\n\tElement::ShapeDerivative const & dN_by_dx, Scalar const v, Element::Elasticity const & c)\n{\n\treturn v * ex::Kc(dN_by_dx, c);\n}\n\nElement::Stiffness Ks(\n\tElement::ShapeDerivative const & dN_by_dx, Scalar const v, Element::Stress const & s)\n{\n\treturn v * ex::Ks(dN_by_dx, s);\n}\n\nElement::SurfaceShapeDerivative const dN_by_dS =  // NOLINT(cert-err58-cpp)\n\tFastor::evaluate(Fastor::inv(Tensor::Matrix<3, 3>{\n\t\t{1, 1, 1},\n\t\t{0, 1, 0},\n\t\t{0, 0, 1},\n\t}))(Fastor::all, Fastor::fseq<1, 3>());\n// clang-format on\n\nnamespace\n{\nauto const [KpLHS, KpRHS] = ([]() {\t // NOLINT(cert-err58-cpp)\n\tusing Tensor::Func::all;\n\tTensor::Matrix<3> KpLHS_, KpRHS_;\n\tfor (auto const a : boost::irange(BoundaryElement::num_nodes))\n\t\tfor (auto const b : boost::irange(BoundaryElement::num_nodes))\n\t\t{\n\t\t\t// Assuming single-point integral, i.e. sample at centre where Na = Nb = 1/3.\n\t\t\tKpLHS_(a, b) = dN_by_dS(a, 1) * (1.0 / 3.0) - dN_by_dS(b, 1) * (1.0 / 3.0);\n\t\t\tKpRHS_(a, b) = dN_by_dS(a, 0) * (1.0 / 3.0) - dN_by_dS(b, 0) * (1.0 / 3.0);\n\t\t}\n\n\treturn std::tuple{KpLHS_, KpRHS_};\n}());\n}\n\nElement::Stiffness Kp(\n\tElement::BoundaryNodePositions const & xs,\n\tconst Element::BoundaryVtxhIdxs & S_to_Vs,\n\tScalar const p)\n{\n\tusing Tensor::Idxs;\n\tusing Tensor::Order;\n\tusing Tensor::Func::all;\n\tusing Tensor::Func::einsum;\n\tenum\n\t{\n\t\ti,\n\t\tj,\n\t\tk,\n\t\ta,\n\t\tb\n\t};\n\tElement::Stiffness K = 0;\n\tfor (auto const & [x, S_to_V] : boost::range::combine(xs, S_to_Vs))\n\t{\n\t\tauto const & dx_by_dS = Derivatives::dX_by_dS(x);\n\t\tScalar const A = Derivatives::A(x);\n\n\t\tTensor::Vector<3> const & dx_by_dS1 = dx_by_dS(all, 0);\n\t\tTensor::Vector<3> const & dx_by_dS2 = dx_by_dS(all, 1);\n\n\t\tBoundaryElement::Stiffness const & K_face = 0.5 * A * p *\n\t\t\t(einsum<Idxs<i, j, k>, Idxs<k>, Idxs<a, b>, Order<a, i, b, j>>(\n\t\t\t\t levi_civita, dx_by_dS1, KpLHS) -\n\t\t\t einsum<Idxs<i, j, k>, Idxs<k>, Idxs<a, b>, Order<a, i, b, j>>(\n\t\t\t\t levi_civita, dx_by_dS2, KpRHS));\n\n\t\tfor (auto const & [face_idx_a, cell_idx_a] : boost::adaptors::index(S_to_V))\n\t\t\tfor (auto const & [face_idx_b, cell_idx_b] : boost::adaptors::index(S_to_V))\n\t\t\t\tK(cell_idx_a, all, cell_idx_b, all) += K_face(face_idx_a, all, face_idx_b, all);\n\t}\n\n\treturn K;\n}\n\nElement::Elasticity c(Scalar J, Scalar lambda, Scalar mu)\n{\n\treturn ex::c(J, lambda, mu);\n}\n\nNode::Force t(Scalar const p, Element::SurfaceGradient const & dX_by_dS)\n{\n\tusing Tensor::Func::all;\n\tusing Tensor::Func::fix;\n\tNode::Force const & dX1_by_dS = dX_by_dS(all, fix<0>);\n\tNode::Force const & dX2_by_dS = dX_by_dS(all, fix<1>);\n\treturn (1.0 / 2.0) * p * cross(dX1_by_dS, dX2_by_dS);\n}\n\nElement::Forces T(\n\tElement::ShapeDerivative const & dN_by_dx, Scalar const v, Element::Stress const & sigma)\n{\n\treturn v * ex::T(dN_by_dx, sigma);\n}\n\nElement::Stress sigma(\n\tScalar const J, Element::Gradient const & b, Scalar const lambda, Scalar const mu)\n{\n\treturn ex::sigma(J, b, lambda, mu);\n}\n\nScalar det_dx_by_dX(Element::Gradient const & dx_by_dX)\n{\n\treturn Fastor::det(dx_by_dX);\n}\n\nElement::Gradient b(Element::Gradient const & F)\n{\n\treturn ex::finger(F);\n}\n\nElement::Gradient dx_by_dX(\n\tElement::NodePositions const & x, Element::ShapeDerivative const & dN_by_dX)\n{\n\treturn ex::dx_by_dX(x, dN_by_dX);\n}\n\nElement::Gradient dx_by_dX(Element::Gradient const & dx_by_dL, Element::Gradient const & dL_by_dX)\n{\n\tusing namespace Tensor;\n\treturn Func::einsum<Idxs<k, i>, Idxs<j, k>>(dx_by_dL, dL_by_dX);\n}\n\nElement::ShapeDerivative dN_by_dX(Element::Gradient const & dL_by_dx)\n{\n\treturn ex::dN_by_dX(dL_by_dx);\n}\n\nElement::ShapeDerivative dN_by_dX(Element::NodePositions const & X)\n{\n\tauto const & dX_by_dL = ex::dX_by_dL(X);\n\tauto const & dL_by_dX = ex::dL_by_dX(dX_by_dL);\n\treturn ex::dN_by_dX(dL_by_dX);\n}\n\nElement::CartesianDerivative dx_by_dN(Element::ShapeCartesianTransform const & N_to_x)\n{\n\tusing namespace Tensor::Func;\n\treturn N_to_x(fseq<1, last>{}, all);\n}\n\nElement::Gradient dL_by_dX(Element::Gradient const & dX_by_dL)\n{\n\treturn ex::dL_by_dX(dX_by_dL);\n}\n\nElement::Gradient dX_by_dL(Element::NodePositions const & X)\n{\n\treturn ex::dX_by_dL(X);\n}\n\nElement::SurfaceGradient dX_by_dS(BoundaryElement::NodePositions const & X)\n{\n\treturn ex::dX_by_dS(X);\n}\n\nElement::ShapeDerivative dN_by_dX(Element::ShapeCartesianTransform const & N_to_x)\n{\n\tusing namespace Tensor::Func;\n\t// Interpolation: (1, x, y, z)^T = N_to_x * N, where N is 4x natural coordinates (corners).\n\t// Invert then strip constant terms, leaving just coefficients, i.e. the derivative.\n\treturn evaluate(inv(N_to_x))(all, fseq<1, last>{});\n}\n\nElement::ShapeCartesianTransform N_to_x(Element::NodePositions const & X)\n{\n\tElement::ShapeCartesianTransform mat;\n\tmat(Fastor::ffirst, Fastor::all) = 1.0;\n\tmat(Fastor::fseq<1, Fastor::last>{}, Fastor::all) = Fastor::transpose(X);\n\treturn mat;\n}\n\nScalar V(Element::NodePositions const & x)\n{\n\tusing namespace Tensor::Func;\n\tauto const & start_3x3 = x(fseq<0, 3>{}, all);\n\t//\tstd::clog << x(fix<3>, all).self().size() << \"\\n\";\n\tTensor::Vector<3> end_1x3 = x(fix<3>, all);\n\tTensor::Matrix<3> end_3x3;\n\tend_3x3(fix<0>, all) = end_1x3;\n\tend_3x3(fix<1>, all) = end_1x3;\n\tend_3x3(fix<2>, all) = end_1x3;\n\tauto const & delta = start_3x3 - end_3x3;\n\treturn std::abs(Fastor::det(delta) / 6.0);\n}\n\nScalar v(Element::NodePositions const & x)\n{\n\t// Volume in local coords (constant)\n\tconstexpr Scalar v_wrt_L = 1.0 / 6.0;\n\treturn v_wrt_L * det_dx_by_dL(x);\n}\n\nScalar A(BoundaryElement::NodePositions const & s)\n{\n\tusing Tensor::Func::all;\n\tusing Tensor::Func::cross;\n\tusing Tensor::Func::norm;\n\tTensor::Vector<3> const & v1 = s(0, all) - s(2, all);\n\tTensor::Vector<3> const & v2 = s(1, all) - s(2, all);\n\treturn 0.5 * norm(cross(v1, v2));\n}\n\nScalar det_dx_by_dL(Element::NodePositions const & x)\n{\n\tusing namespace Tensor;\n\tusing Func::all;\n\tusing Func::einsum;\n\tusing Func::fix;\n\n\t//\tScalar det_ = 0;\n\t//\tfor (Index i = 0; i < Element::count; i++)\n\t//\t\tfor (Index j = 0; j < Element::count; j++)\n\t//\t\t\tfor (Index k = 0; k < Element::count; k++)\n\t//\t\t\t\tdet_ += det_dN_by_dL(i, j, k) * x(i, 0) * x(j, 1) * x(k, 2);\n\t//\n\t//\treturn det_;\n\n\t//\tElement::ShapeDerivativeDeterminant xs = ([&x](){\n\t//\t\tusing Tensor::Index;\n\t//\t\tusing Tensor::Func::all;\n\t//\t\tElement::ShapeDerivativeDeterminant xs_;\n\t//\t\tfor (Index i = 0; i < Element::count; i++)\n\t//\t\t\tfor (Index j = 0; j < Element::count; j++)\n\t//\t\t\t\tfor (Index k = 0; k < Element::count; k++)\n\t//\t\t\t\t\txs_(i, j, k) = x(i, 0) * x(j, 1) * x(k, 2);\n\t//\t\treturn xs_;\n\t//\t}());\n\t//\tTensor::Vector<1> sum = einsum<Idxs<i, j, k>, Idxs<i, j, k>>(\n\t//\t\tdet_dN_by_dL, xs);\n\n\t// \"Consideration of Body Forces within Finite Element Analysis\", Glenk et al., 2018\n\tTensor::Vector<4> x0 = x(all, fix<0>);\n\tTensor::Vector<4> x1 = x(all, fix<1>);\n\tTensor::Vector<4> x2 = x(all, fix<2>);\n\tTensor::Vector<1> sum =\n\t\teinsum<Idxs<i, j, k>, Idxs<i>, Idxs<j>, Idxs<k>>(Derivatives::det_dN_by_dL, x0, x1, x2);\n\n\treturn sum(0);\n}\n\n// clang-format off\nElement::IsoCoordDerivative const dL_by_dN = // NOLINT(cert-err58-cpp)\n\tTensor::Matrix<4, 4>{\n\t\t{1, 1, 1, 1},\n\t\t{0, 1, 0, 0},\n\t\t{0, 0, 1, 0},\n\t\t{0, 0, 0, 1}}(Fastor::fseq<1, 4>(), Fastor::all);\n\nElement::ShapeDerivative const dN_by_dL = // NOLINT(cert-err58-cpp)\n\tFastor::evaluate(Fastor::inv(Tensor::Matrix<4, 4>{\n\t\t{1, 1, 1, 1},\n\t\t{0, 1, 0, 0},\n\t\t{0, 0, 1, 0},\n\t\t{0, 0, 0, 1}}))(Fastor::all, Fastor::fseq<1, 4>());\n\nElement::ShapeDerivativeDeterminant const det_dN_by_dL = ([]() {  // NOLINT(cert-err58-cpp)\n\tusing Tensor::Index;\n\tusing Tensor::Func::all;\n\tusing Tensor::Func::det;\n\tElement::ShapeDerivativeDeterminant det_dN_by_dL_;\n\tfor (Index i = 0; i < Element::num_nodes; i++)\n\t\tfor (Index j = 0; j < Element::num_nodes; j++)\n\t\t\tfor (Index k = 0; k < Element::num_nodes; k++)\n\t\t\t{\n\t\t\t\tTensor::Matrix<3> dN_by_dL_ijk;\n\t\t\t\tdN_by_dL_ijk(0, all) = dN_by_dL(i, all);\n\t\t\t\tdN_by_dL_ijk(1, all) = dN_by_dL(j, all);\n\t\t\t\tdN_by_dL_ijk(2, all) = dN_by_dL(k, all);\n\t\t\t\tdet_dN_by_dL_(i, j, k) = det(dN_by_dL_ijk);\n\t\t\t}\n\treturn det_dN_by_dL_;\n}());\n\nTensor::Multi<Node::dim, Node::dim, Node::dim> const levi_civita =\t// NOLINT(cert-err58-cpp)\n\t([]() {\n\t\tusing LeviCivita = Tensor::Multi<Node::dim, Node::dim, Node::dim>;\n\t\tLeviCivita E;\n\t\tint constexpr const count = static_cast<int>(Node::dim);\n\t\tfor (int i = 0; i < count; i++)\n\t\t\tfor (int j = 0; j < count; j++)\n\t\t\t\tfor (int k = 0; k < count; k++) E(i, j, k) = sgn(j - i) * sgn(k - i) * sgn(k - j);\n\t\treturn E;\n\t}());\n}  // namespace FeltElements::Derivatives\n", "meta": {"hexsha": "461457acc2fef555c889b85e41269d2a7b3d3b65", "size": 14434, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/lib/FeltElements/Derivatives.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/Derivatives.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/Derivatives.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": 29.9460580913, "max_line_length": 98, "alphanum_fraction": 0.6451434114, "num_tokens": 5216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.47852463253170985}}
{"text": "#include <iostream>\n#include <algorithm>\n#include <iterator>\n#include <cmath>\n#include <fstream>\n#include <valarray>\n#include <sstream>\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/math/constants/constants.hpp>\n\n#include \"miMaS/field.h\"\n#include \"miMaS/weno.h\"\n#include \"miMaS/fft.h\"\n#include \"miMaS/array_view.h\"\n#include \"miMaS/poisson.h\"\n#include \"miMaS/rk.h\"\n\n#ifndef SIGMA\n#define SIGMA (1.0)\n#endif\n#define E_MAX (2.0)\n\n/*\ntemplate <unsigned int i>\nstruct phi\n{\n  static std::complex<double>\n  operator () ( std::complex<double> const & z ) {\n    static std::valarray<std::complex<double>> coeff(i);\n    coeff[0] = 1.;\n\n    for ( unsigned int k=1 ; k<coeff.size() ; ++k ) {\n      coeff[k] = coeff[k-1] * z / (double(k));\n    }\n\n    return (std::exp(z) - std::accumulate( std::begin(coeff) , std::end(coeff) , std::complex<double>(0.,0.) ))/(std::pow(z,i));\n  }\n};\n*/\ntemplate <unsigned int i>\nstd::complex<double>\nphi ( std::complex<double> const & _z )\n{\n  std::valarray<std::complex<double>> coeff(i);\n  coeff[0] = 1.;\n\n  std::complex<double> z = _z;\n  if ( _z == 0. ) { z = std::complex<double>(1.,0.); }\n\n  for ( unsigned int k=1 ; k<coeff.size() ; ++k ) {\n    coeff[k] = coeff[k-1] * z / (double(k));\n  }\n  //std::copy(std::begin(coeff),std::end(coeff),std::ostream_iterator<std::complex<double>>(std::cout,\" . \"));\n  //std::cout << std::endl;\n\n  if ( z != 0. ) {\n    return (std::exp(z) - std::accumulate( std::begin(coeff) , std::end(coeff) , std::complex<double>(0.,0.) ))/(std::pow(z,i));  \n  }\n  return coeff[i-1];\n}\n\nnamespace o2 {\n  template < typename _T , std::size_t NumDimsV >\n  auto\n  trp_v ( field<_T,NumDimsV> const & u , ublas::vector<_T> const& E )\n  {\n    field<_T,NumDimsV> trp(tools::array_view<const std::size_t>(u.shape(),NumDimsV+1));\n\n    { auto k=0, km1=trp.size(0)-1;\n      for ( auto i=0 ; i<trp.size(1) ; ++i ) {\n        trp[k][i] = ( E(i)*(u[k+1][i]-u[km1][i])/(2.*u.step.dv) );\n      }\n    }\n    for ( auto k=1 ; k<trp.size(0)-1 ; ++k ) {\n      for ( auto i=0 ; i<trp.size(1) ; ++i ) {\n        trp[k][i] = ( E(i)*(u[k+1][i]-u[k-1][i])/(2.*u.step.dv) );\n      }\n    }\n    { auto k=trp.size(0)-1, kp1=0;\n      for ( auto i=0 ; i<trp.size(1) ; ++i ) {\n        trp[k][i] = ( E(i)*(u[kp1][i]-u[k-1][i])/(2.*u.step.dv) );\n      }\n    }\n\n    return trp;\n  }\n}\n\n\nnamespace math = boost::math::constants;\nconst std::complex<double> & I = std::complex<double>(0.,1.);\n\n#define SQ(X) ((X)*(X))\n#define Xi(i) (i*f.step.dx+f.range.x_min)\n#define Vk(k) (k*f.step.dv+f.range.v_min)\n\nauto\nmaxwellian ( double rho , double u , double T ) {\n  //std::cout << rho << \" \" << u << \" \" << T << std::endl;\n  //std::cout << rho/(std::sqrt(2.*math::pi<double>()*T)) << std::endl;\n  return [=](double x,double v){ return rho/(std::sqrt(2.*math::pi<double>()*T))*std::exp( -0.5*SQ(v-u)/T ); };\n}\n\nint main(int,char**)\n{\n\tstd::size_t Nx = 135, Nv = 256 , Nb_iter=10;\n\tfield<double,1> f(boost::extents[Nv][Nx]);\n\n\tf.range.v_min = -8.; f.range.v_max = 8.;\n\tf.step.dv = (f.range.v_max-f.range.v_min)/Nv;\n\n  const double Kx = 0.5;\n\t//f.range.x_min = 0.; f.range.x_max = 20.*math::pi<double>();\n  f.range.x_min = 0.; f.range.x_max = 2./Kx*math::pi<double>(); //10.0*math::pi<double>();\n  //f.range.x_min = -8.; f.range.x_max = 8.;\n\tf.step.dx = (f.range.x_max-f.range.x_min)/Nx;\n\n  //field<double,1> f_sol = f;\n  //field<double,1> f_ini = f;\n\t\n\tublas::vector<double> v (Nv,0.);\n  ublas::vector<double> E (Nx,0.),rho(Nx);\n  for ( std::size_t k=0 ; k<Nv ; ++k ) { v[k] = Vk(k); }\n  //for ( std::size_t i=0 ; i<Nx ; ++i ) { E[i] = -Xi(i); }\n\n\tconst double l = f.range.x_max-f.range.x_min;\n\tublas::vector<double> kx(Nx);\n\t//for ( auto i=0 ; i<Nx/2+1 ; ++i )   { kx[i] = 2.*math::pi<double>()*i/l; }\n\t//for ( auto i=0 ; i<((Nx/2)) ; ++i ) { kx[i+Nx/2+1] = -kx[Nx/2-i]; }\n  for ( auto i=0 ; i<Nx/2 ; ++i ) { kx[i]    = 2.*math::pi<double>()*i/l; }\n  for ( int i=-Nx/2 ; i<0 ; ++i ) { kx[Nx+i] = 2.*math::pi<double>()*i/l; }\n\t\n  double np = 0.9 , nb = 0.2 , ui = 4.5;\n  double alpha = 0.1;\n  double Tc = 0.01; //, u = 4.5;\n  //auto Mmu = maxwellian(1.,-u,1.) , Mpu = maxwellian(1.,u,1.) , M0c = maxwellian(1.,0.,Tc);\n\n  ui = 2.;\n  alpha = 0.2;\n  Tc = 0.01;\n  auto landau_M = maxwellian(1.,0.,1.);\n  auto db_M1 = maxwellian(0.5,-ui,1.) , db_M2 = maxwellian(0.5,ui,1.);\n  auto bot_M1 = maxwellian(1.-alpha,0.,1.) , bot_M2 = maxwellian(alpha,ui,0.25);\n  auto tb_MC = maxwellian(1.-alpha,0.,Tc) , tb_M1 = maxwellian(0.5*alpha,ui,1.) , tb_M2 = maxwellian(0.5*alpha,-ui,1.);\n  auto v10_MC = maxwellian(1.-alpha,0,Tc) , v10_Mh = maxwellian(alpha,0.,1.);\n\n  for (field<double,2>::size_type k=0 ; k<f.size(0) ; ++k ) {\n    for (field<double,2>::size_type i=0 ; i<f.size(1) ; ++i ) {\n      //f[k][i] = ((1.-alpha)*M0c(Xi(i),Vk(k)) + 0.5*alpha*( Mpu(Xi(i),Vk(k)) + Mmu(Xi(i),Vk(k)) ))*(1.+0.01*std::cos(0.5*Xi(i)));\n\n      //// landau damping : Kx=0.5\n      //f[k][i] = landau_M(Xi(i),Vk(k))*(1.+0.001*std::cos(Kx*Xi(i)));\n      //// double beam Kx=0.2, ui=2.4 ou Kx=0.2, ui=4.5\n      //f[k][i] = (db_M1(Xi(i),Vk(k))+db_M2(Xi(i),Vk(k)))*(1.+0.001*std::cos(Kx*Xi(i)));\n      //// bot Kx=0.5 , alpha=0.2 , ui=4.5\n      //f[k][i] = (bot_M1(Xi(i),Vk(k)) + bot_M2(Xi(i),Vk(k)))*(1.+0.01*std::cos(Kx*Xi(i)));\n      //// tb Kx=0.5 , ui=4. , alpha=0.2 , Tc=0.01\n      f[k][i] = tb_MC(Xi(i),Vk(k)) + (tb_M1(Xi(i),Vk(k)) + tb_M2(Xi(i),Vk(k)) )*(1. + 0.01*std::cos(Kx*Xi(i)));\n      //// v10 Kx=0.5 , alpha=0.2\n      //f[k][i] = v10_MC(Xi(i),Vk(k)) + ( std::pow(Vk(k),10)*v10_Mh(Xi(i),Vk(k))/945. )*(1. + 0.01*std::cos(Kx*Xi(i)));\n    }\n  }\n  f.write(\"vphl/kin/init_tb.dat\");\n\n  poisson<double> poisson_solver(Nx,l);\n  rho = f.density();\n  E = poisson_solver(rho);\n  \n\n  //double Tf = 60.;//2*math::pi<double>();\n  const double Tf = 200.;\n  int i_t=0;\n\n  double current_time = 0.;\n  // SIGMA is the CFL number\n  double dt = f.step.dv;//std::min( 0.1 , SIGMA*f.step.dv/std::abs(*std::max_element( E.begin() , E.end() , [](double a,double b){return (std::abs(a) < std::abs(b));} )) );\n\n  std::cout << \"Nx: \" << Nx << \"\\n\";\n  std::cout << \"Nv: \" << Nv << \"\\n\";\n  std::cout << \"v_min: \" << f.range.v_min << \"\\n\";\n  std::cout << \"v_max: \" << f.range.v_max << \"\\n\";\n  std::cout << \"x_min: \" << f.range.x_min << \"\\n\";\n  std::cout << \"x_max: \" << f.range.x_max << \"\\n\";\n  std::cout << \"dt: \" << dt << \"\\n\";\n  std::cout << \"dx: \" << f.step.dx << \"\\n\";\n  std::cout << \"dv: \" << f.step.dv << \"\\n\";\n  std::cout << \"Tf: \" << Tf << \"\\n\";\n  std::cout << \"f_0: \" << \"\\\"tb\\\"\" << \"\\n\";\n  std::cout << std::endl;\n\n  std::ofstream info(\"info.yaml\");\n\n  info << \"Nx: \" << Nx << \"\\n\";\n  info << \"Nv: \" << Nv << \"\\n\";\n  info << \"v_min: \" << f.range.v_min << \"\\n\";\n  info << \"v_max: \" << f.range.v_max << \"\\n\";\n  info << \"x_min: \" << f.range.x_min << \"\\n\";\n  info << \"x_max: \" << f.range.x_max << \"\\n\";\n  info << \"dt: \" << dt << \"\\n\";\n  info << \"dx: \" << f.step.dx << \"\\n\";\n  info << \"dv: \" << f.step.dv << \"\\n\";\n  info << \"Tf: \" << Tf << \"\\n\";\n  info << \"f_0: \" << \"\\\"tb\\\"\" << \"\\n\";\n  info << std::endl;\n  info.close();\n\n  std::vector<double> ee;   ee.reserve(int(std::ceil(Tf/dt))+1);\n  std::vector<double> Emax; Emax.reserve(int(std::ceil(Tf/dt))+1);\n  std::vector<double> H;    H.reserve(int(std::ceil(Tf/dt))+1);\n\n  std::vector<double> times; times.reserve(int(std::ceil(Tf/dt))+1);\n\n  // space scheme\n  auto weno = [&](field<double,1>const& f , ublas::vector<double> const& E )->field<double,1> { return weno::trp_v(f,E); };\n  auto cd2 = [&](field<double,1>const& f , ublas::vector<double> const& E )->field<double,1> { return o2::trp_v(f,E); };\n\n  // time scheme init\n  lawson::RK33<poisson<double>> rk(Nx,Nv,l,f.shape(),v,kx,weno);\n\n  rk.E = rk.poisson_solver(f.density());\n  Emax.push_back( std::abs(*std::max_element( rk.E.begin() , rk.E.end() , [](double a,double b){return (std::abs(a) < std::abs(b));} )) );\n  double electric_energy = 0.;\n  for ( const auto & ei : rk.E ) { electric_energy += ei*ei*f.step.dx; }\n  ee.push_back( std::sqrt(electric_energy) );\n  H.push_back( energy(f,rk.E) );\n  times.push_back( 0. );\n\n  while (  current_time < Tf ) {\n    std::cout<<\" [\"<<std::setw(5)<<i_t<<\"] \"<< current_time <<\"\\r\"<<std::flush;\n    \n    f = rk(f,dt);\n\n    // end of time loop\n\n    // MONITORING\n    rk.E = rk.poisson_solver(f.density());\n    Emax.push_back( std::abs(*std::max_element( rk.E.begin() , rk.E.end() , [](double a,double b){return (std::abs(a) < std::abs(b));} )) );\n    electric_energy = 0.;\n    for ( const auto & ei : rk.E ) { electric_energy += ei*ei*f.step.dx; }\n    ee.push_back( std::sqrt(electric_energy) );\n    H.push_back( energy(f,rk.E) );\n\n    dt = std::min( 0.1 , SIGMA*f.step.dv/Emax[i_t] );\n\n    // increment time\n    ++i_t;\n    current_time += dt;\n    times.push_back( current_time );\n\t} // while (  i_t*dt < Tf )\n\n\n//#define FOLDER \"lukas/landau/\"\n#define FOLDER \"vphl/kin/\"\n#define SPACE_SCHEME \"weno\"\n\n  std::cout<<\" [\"<<std::setw(5)<<i_t<<\"] \"<<i_t*dt <<std::endl;\n\n  std::stringstream ss; ss << FOLDER << \"vp_\" << rk.label << \"_\" << SPACE_SCHEME << \".dat\";\n  f.write(\"vphl/kin/vp_tb.dat\");\n\n  ss.str(std::string());\n  std::ofstream of;\n  std::size_t count = 0;\n  auto dt_y = [&,count=0](auto const& y) mutable { std::stringstream ss; ss<<times[count++]<<\" \"<<y; return ss.str(); };\n  //ss << FOLDER << \"ee_\" << rk.label << \"_\" << SPACE_SCHEME << \".dat\";\n  of.open(\"vphl/kin/ee_tb.dat\"); ss.str(std::string());\n  for ( auto i=0; i<ee.size() ; ++i ) {\n    of << times[i] <<\" \" << ee[i] << \"\\n\";\n  }\n  of.close();\n  //ss << FOLDER << \"H_\" << rk.label << \"_\" << SPACE_SCHEME << \".dat\";\n  of.open(\"vphl/kin/H_tb.dat\"); ss.str(std::string());\n  for ( auto i=0; i<H.size() ; ++i ) {\n    of << times[i] <<\" \" << (H[i]-H[0])/std::abs(H[0]) << \"\\n\";\n  }\n\n  //double h = std::abs(*std::max_element( H.begin() , H.end() , [&](double a,double b){return ( std::abs((a-H[0])/std::abs(H[0])) < std::abs((b-H[0])/std::abs(H[0])) );} ));\n  //std::cout << dt << \" \" << std::abs((h-H[0])/std::abs(H[0])) << \"\\n\";\n\n  of.close();\n  //ss << FOLDER << \"Emax_\" << rk.label << \"_\" << SPACE_SCHEME << \".dat\";\n  of.open(\"vphl/kin/Emax_tb.dat\"); ss.str(std::string());\n  std::transform( Emax.begin() , Emax.end() , std::ostream_iterator<std::string>(of,\"\\n\") , dt_y );\n  of.close();\n\n\treturn 0;\n}\n", "meta": {"hexsha": "6ce0d6a0918898ff7c0b02d8f4a7ca77a7b024fe", "size": 10220, "ext": "cc", "lang": "C++", "max_stars_repo_path": "code/tb.cc", "max_stars_repo_name": "kivvix/vlasovpp", "max_stars_repo_head_hexsha": "123072d42ddcceef9278e0cd3ac18d5b3fa4b3c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-01-03T22:31:03.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-29T06:12:07.000Z", "max_issues_repo_path": "code/tb.cc", "max_issues_repo_name": "kivvix/vlasovpp", "max_issues_repo_head_hexsha": "123072d42ddcceef9278e0cd3ac18d5b3fa4b3c0", "max_issues_repo_licenses": ["MIT"], "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/tb.cc", "max_forks_repo_name": "kivvix/vlasovpp", "max_forks_repo_head_hexsha": "123072d42ddcceef9278e0cd3ac18d5b3fa4b3c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-11-20T12:36:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-29T06:17:16.000Z", "avg_line_length": 35.2413793103, "max_line_length": 174, "alphanum_fraction": 0.538258317, "num_tokens": 3873, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.47852463253170985}}
{"text": "/*\n * LibHEOM: Copyright (c) Tatsushi Ikeda\n * This library is distributed under BSD 3-Clause License.\n * See LINCENSE.txt for licence.\n *------------------------------------------------------------------------*/\n\n// Note: In order to avoid compile errors caused by the two phase name\n//       lookup rule regarding template class, all class variables in\n//       this source have this-> modifier.\n\n#include \"redfield.h\"\n\n#include <Eigen/SparseLU>\n\n#include \"const.h\"\n// #include \"mkl_wrapper.h\"\n\nnamespace libheom\n{\n\n// calculate Fourier-Laplace transform of quantum correlation function.\n// The exponent is +1j*omega*t.\ntemplate<typename T>\ninline T correlation\n/**/(redfield<T>& rf,\n     int u,\n     real_t<T> omega)\n{\n  if (rf.use_corr_func && rf.use_corr_func[u]) {\n    return rf.corr_func[u](omega);\n  } else {\n    \n    Eigen::SparseMatrix<T, Eigen::RowMajor> I(rf.len_gamma[u],rf.len_gamma[u]);\n    I.setIdentity();\n    Eigen::SparseLU<Eigen::SparseMatrix<T, Eigen::RowMajor>> solver;\n    solver.compute(rf.gamma[u] - i_unit<T>()*omega*I);\n    if (solver.info() != Eigen::Success) {\n      std::cerr << \"[Error] LU decomposition failed. \" << std::endl;\n      std::exit(1);\n      return zero<T>();\n    }\n    return static_cast<T>(rf.sigma[u].transpose()*(rf.s[u] + i_unit<T>()*rf.a[u])*solver.solve(rf.phi_0[u])) + rf.S_delta[u];\n    \n  }\n}\n\n\ntemplate<typename T>\nvoid redfield<T>::init_aux_vars\n/**/()\n{\n  qme<T>::init_aux_vars();\n  \n  this->Lambda.reset(new lil_matrix<T>[this->n_noise]);\n  for (int s = 0; s < this->n_noise; ++s) {\n    this->Lambda[s].set_shape(this->n_state, this->n_state);\n    for (auto& V_ijv : this->V[s].data) {\n      int i = V_ijv.first;\n      for (auto& V_jv: V_ijv.second) {\n        int j = V_jv.first;\n        T val = V_jv.second;\n        if (val != zero<T>()) {\n          real_t<T> omega_ji;\n          try {\n            omega_ji = std::real(this->H.data[j][j] - this->H.data[i][i]);\n          } catch (std::out_of_range&) {\n            continue;\n          }\n          T corr = correlation(*this, s, omega_ji);\n          this->Lambda[s].data[i][j] += val*corr;\n        }\n      }\n    }\n  }\n}\n\n\n//========================================================================\n// redfield Module (Hilbert space expression)\n//========================================================================\n\n\ntemplate<typename T,\n         template <typename, int> class matrix_type,\n         int num_state>\nvoid redfield_h<T, matrix_type, num_state>::init_aux_vars\n/**/()\n{\n  redfield<T>::init_aux_vars();\n\n  if (this->secular) {\n    std::cerr << \"[Error] Secular approximation is supported only in Liouville space.\" << std::endl;\n    std::exit(1);\n  }\n\n  this->H.template dump<num_state>(this->H_impl);\n  matrix_type<T, num_state> H_c_impl;\n  this->H_c.template dump<num_state>(H_c_impl);\n  this->H_impl += H_c_impl;\n  \n  this->V_impl.reset(new matrix_hilb[this->n_noise]);\n  this->Lambda_impl.reset(new matrix_hilb[this->n_noise]);\n  this->Lambda_dagger_impl.reset(new matrix_hilb[this->n_noise]);\n  \n  for (int s = 0; s < this->n_noise; ++s) {\n    this->V[s].template dump<num_state>(this->V_impl[s]);\n    this->Lambda[s].template dump<num_state>(this->Lambda_impl[s]);\n    auto tmp = this->Lambda[s].hermite_conjugate();\n    tmp.template dump<num_state>(this->Lambda_dagger_impl[s]);\n  }\n}\n\n\n// template<typename T, template <typename> class matrix_type>\n// void redfield_h<T, matrix_type>::ConstructCommutator(\n//     lil_matrix<T>& x,\n//     T coef_l,\n//     T coef_r,\n//     std::function<void(int)> callback,\n//     int interval_callback) {\n//   this->X_impl = static_cast<matrix_type<T>>(this->x);\n//   this->coef_l_X = coef_l;\n//   this->coef_r_X = coef_r;\n// }\n\n\ntemplate<typename T,\n         template <typename, int> class matrix_type,\n         int num_state>\nvoid redfield_h<T, matrix_type, num_state>::calc_diff\n/**/(ref<dense_vector<T,Eigen::Dynamic>>              drho_dt_raw,\n     const ref<const dense_vector<T,Eigen::Dynamic>>& rho_raw,\n     real_t<T> alpha,\n     real_t<T> beta)\n{\n  auto n_state = this->n_state;\n  \n  auto rho     = Eigen::Map<const dense_matrix<T,num_state>>(rho_raw.data(),n_state,n_state);\n  auto drho_dt = Eigen::Map<dense_matrix<T,num_state>>(drho_dt_raw.data(),n_state,n_state);\n  dense_matrix<T,num_state> tmp(n_state,n_state);\n\n  drho_dt *= beta;\n  drho_dt.noalias() += -alpha*i_unit<T>()*this->H_impl*rho;\n  drho_dt.noalias() += +alpha*i_unit<T>()*rho*this->H_impl;\n  \n  for (int s = 0; s < this->n_noise; ++s) {\n    tmp.noalias()  = +i_unit<T>()*this->Lambda_impl[s]*rho;\n    tmp.noalias() += -i_unit<T>()*rho*this->Lambda_dagger_impl[s];\n    drho_dt.noalias() += alpha*i_unit<T>()*this->V_impl[s]*tmp;\n    drho_dt.noalias() -= alpha*i_unit<T>()*tmp*this->V_impl[s];\n  }\n}\n\n\n// template<typename T, template <typename, int> class matrix_type, int num_state>\n// void redfield_h<T, matrix_type, num_state>::ApplyCommutator(T* rho_raw) {\n//   DenseMatrixWrapper<T> rho(this->n_state, this->n_state, rho_raw);\n//   DenseMatrixWrapper<T> sub(this->n_state, this->n_state, this->sub_vector.data());\n  \n//   gemm(this->coef_l_X, this->X_impl, rho, zero<T>(), sub);\n//   gemm(this->coef_r_X, rho, this->X_impl, one <T>(), sub);\n// }\n\n\n//========================================================================\n// redfield Module (Liouville space expression)\n//========================================================================\n\n\ntemplate<typename T,\n         template <typename, int> class matrix_type,\n         int num_state>\nvoid redfield_l<T, matrix_type, num_state>::init_aux_vars\n/**/()\n{\n  redfield<T>::init_aux_vars();\n  \n  this->n_state_liou = this->n_state*this->n_state;\n  \n  this->L.set_shape(this->n_state_liou, this->n_state_liou);\n  kron_identity_right(+i_unit<T>(), this->H, zero<T>(), this->L);\n  kron_identity_left (-i_unit<T>(), this->H, one<T>(), this->L);\n  \n  this->Phi.  reset(new lil_matrix<T>[this->n_noise]);\n  this->Theta.reset(new lil_matrix<T>[this->n_noise]);\n  \n  for (int s = 0; s < this->n_noise; ++s){\n    this->Phi[s].set_shape(this->n_state_liou, this->n_state_liou);\n    kron_identity_right(+i_unit<T>(), this->V[s], zero<T>(), this->Phi[s]);\n    kron_identity_left (-i_unit<T>(), this->V[s], one<T>(),  this->Phi[s]);\n\n    this->Theta[s].set_shape(this->n_state_liou, this->n_state_liou);\n    kron_identity_right(+i_unit<T>(), this->Lambda[s],\n                        zero<T>(), this->Theta[s]);\n    kron_identity_left (-i_unit<T>(), this->Lambda[s].hermite_conjugate(),\n                        one<T>(),  this->Theta[s]);\n  }\n\n  this->R_redfield.set_shape(this->n_state_liou, this->n_state_liou);\n  kron_identity_right(+i_unit<T>(), this->H_c, zero<T>(), this->R_redfield);\n  kron_identity_left (-i_unit<T>(), this->H_c, one<T>(),  this->R_redfield);\n  for (int s = 0; s < this->n_noise; ++s) {\n    gemm(-one<T>(), this->Phi[s], this->Theta[s], one<T>(), this->R_redfield);\n  }\n  if (this->secular) {\n    dense_matrix<T,num_state_liou> i_omega;\n    this->L.optimize();\n    this->L.template dump<num_state_liou>(i_omega);\n    this->R_redfield.optimize();\n    for (auto& ijv : this->R_redfield.data) {\n      int i = ijv.first;\n      for (auto& jv: ijv.second) {\n        int j = jv.first;\n        if (abs(i_omega(i,i) - i_omega(j,j))\n            >= std::numeric_limits<typename T::value_type>::epsilon()) {\n          jv.second = zero<T>();\n        }\n      }\n    }\n    this->R_redfield.optimize();\n  }\n  axpy(one<T>(), this->L, this->R_redfield);\n  this->R_redfield.optimize();\n\n  R_redfield.template dump<num_state_liou>(this->R_redfield_impl);\n}\n\n\n// template<typename T, template <typename> class matrix_type>\n// void redfield_l<T, matrix_type>::ConstructCommutator(\n//     lil_matrix<T>& x,\n//     T coef_l,\n//     T coef_r,\n//     std::function<void(int)> callback,\n//     int interval_callback) {\n//   this->X_impl = static_cast<matrix_type<T>>(this->x);\n//   this->coef_l_X = coef_l;\n//   this->coef_r_X = coef_r;\n// }\n\n\ntemplate<typename T,\n         template <typename, int> class matrix_type,\n         int num_state>\nvoid redfield_l<T, matrix_type, num_state>::calc_diff\n/**/(ref<dense_vector<T,Eigen::Dynamic>>              drho_dt_raw,\n     const ref<const dense_vector<T,Eigen::Dynamic>>& rho_raw,\n     real_t<T> alpha,\n     real_t<T> beta)\n{\n  auto n_state_liou   = this->n_state_liou;\n  auto rho     = blk<T,num_state_liou,1>::value(rho_raw,    0,0,n_state_liou,1);\n  auto drho_dt = blk<T,num_state_liou,1>::value(drho_dt_raw,0,0,n_state_liou,1);\n\n  drho_dt *= beta;\n  drho_dt.noalias() += -alpha*this->R_redfield_impl*rho;\n}\n\n\n// template<typename T, template <typename, int> class matrix_type, int num_state>\n// void redfield_l<T, matrix_type, num_state>::ApplyCommutator(T* rho_raw) {\n//   DenseMatrixWrapper<T> rho(this->n_state, this->n_state, rho_raw);\n//   DenseMatrixWrapper<T> sub(this->n_state, this->n_state, this->sub_vector.data());\n  \n//   gemm(this->coef_l_X, this->X_impl, rho, zero<T>(), sub);\n//   gemm(this->coef_r_X, rho, this->X_impl, one <T>(), sub);\n// }\n\n\n}\n\n\n// Explicit instantiations\nnamespace libheom\n{\n\n#define DECLARE_EXPLICIT_INSTANTIATIONS(qme_type, T, matrix_type, num_state) \\\n  template void qme_type<T, matrix_type, num_state>::init_aux_vars();        \\\n  template void qme_type<T, matrix_type, num_state>::calc_diff(              \\\n      ref<dense_vector<T, Eigen::Dynamic>> drho_dt,                          \\\n      const ref<const dense_vector<T, Eigen::Dynamic>>& rho,                 \\\n      real_t<T> alpha, real_t<T> beta);\n// template void qme_type<T, matrix_type>::ConstructCommutator(            \\\n//     lil_matrix<T>& x,                                                  \\\n//     T coef_l,                                                         \\\n//     T coef_r,                                                         \\\n//     std::function<void(int)> callback,                                \\\n//     int interval_callback);                                           \\\n// template void qme_type<T, matrix_type>::ApplyCommutator(ref<dense_vector<T>> rho);\n\nDECLARE_EXPLICIT_INSTANTIATIONS(redfield_h, complex64,  dense_matrix, Eigen::Dynamic);\nDECLARE_EXPLICIT_INSTANTIATIONS(redfield_h, complex64,  csr_matrix,   Eigen::Dynamic);\nDECLARE_EXPLICIT_INSTANTIATIONS(redfield_h, complex128, dense_matrix, Eigen::Dynamic);\nDECLARE_EXPLICIT_INSTANTIATIONS(redfield_h, complex128, csr_matrix,   Eigen::Dynamic);\n\nDECLARE_EXPLICIT_INSTANTIATIONS(redfield_l, complex64,  dense_matrix, Eigen::Dynamic);\nDECLARE_EXPLICIT_INSTANTIATIONS(redfield_l, complex64,  csr_matrix,   Eigen::Dynamic);\nDECLARE_EXPLICIT_INSTANTIATIONS(redfield_l, complex128, dense_matrix, Eigen::Dynamic);\nDECLARE_EXPLICIT_INSTANTIATIONS(redfield_l, complex128, csr_matrix,   Eigen::Dynamic);\n\nDECLARE_EXPLICIT_INSTANTIATIONS(redfield_h, complex64,  dense_matrix, 2);\nDECLARE_EXPLICIT_INSTANTIATIONS(redfield_h, complex64,  csr_matrix,   2);\nDECLARE_EXPLICIT_INSTANTIATIONS(redfield_h, complex128, dense_matrix, 2);\nDECLARE_EXPLICIT_INSTANTIATIONS(redfield_h, complex128, csr_matrix,   2);\n\nDECLARE_EXPLICIT_INSTANTIATIONS(redfield_l, complex64,  dense_matrix, 2);\nDECLARE_EXPLICIT_INSTANTIATIONS(redfield_l, complex64,  csr_matrix,   2);\nDECLARE_EXPLICIT_INSTANTIATIONS(redfield_l, complex128, dense_matrix, 2);\nDECLARE_EXPLICIT_INSTANTIATIONS(redfield_l, complex128, csr_matrix,   2);\n\nDECLARE_EXPLICIT_INSTANTIATIONS(redfield_h, complex64,  dense_matrix, 3);\nDECLARE_EXPLICIT_INSTANTIATIONS(redfield_h, complex64,  csr_matrix,   3);\nDECLARE_EXPLICIT_INSTANTIATIONS(redfield_h, complex128, dense_matrix, 3);\nDECLARE_EXPLICIT_INSTANTIATIONS(redfield_h, complex128, csr_matrix,   3);\n\nDECLARE_EXPLICIT_INSTANTIATIONS(redfield_l, complex64,  dense_matrix, 3);\nDECLARE_EXPLICIT_INSTANTIATIONS(redfield_l, complex64,  csr_matrix,   3);\nDECLARE_EXPLICIT_INSTANTIATIONS(redfield_l, complex128, dense_matrix, 3);\nDECLARE_EXPLICIT_INSTANTIATIONS(redfield_l, complex128, csr_matrix,   3);\n\n}\n", "meta": {"hexsha": "3d0ec87bcf5a3185418b7c140cb10b1c867f7514", "size": 11905, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/redfield.cc", "max_stars_repo_name": "tatsushi-ikeda/libheom", "max_stars_repo_head_hexsha": "786072f15fe680af6c4f676bb549deb620d7fa84", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-06-22T09:58:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T06:25:10.000Z", "max_issues_repo_path": "src/redfield.cc", "max_issues_repo_name": "tatsushi-ikeda/libheom", "max_issues_repo_head_hexsha": "786072f15fe680af6c4f676bb549deb620d7fa84", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/redfield.cc", "max_forks_repo_name": "tatsushi-ikeda/libheom", "max_forks_repo_head_hexsha": "786072f15fe680af6c4f676bb549deb620d7fa84", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-11-15T01:09:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-15T01:09:06.000Z", "avg_line_length": 36.9720496894, "max_line_length": 125, "alphanum_fraction": 0.6352792944, "num_tokens": 3218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339516289534, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4785246188182466}}
{"text": "/* \n\n   Recon Code for Cartesian and Non-Cartesian Data\n   (in process of reorganizing for template + 4D recons)\n\n\n */\n\n#include \"ArrayTemplates.cpp\"\n#include \"tictoc.hpp\"\n#include <omp.h>\n#include <armadillo>\n#include <cmath>\n\nusing namespace std;\nusing namespace NDarray;\n\nint dideal_recon_2D_CG( \n\tArray< float,2 >&kx, \n\tArray< float,2 >&ky, \n\tArray< complex<float>,2 >&kdata,\n\tArray< float,3 >&fieldmap,\n\tArray< float,2 >&ktimes,\n\tfloat *freqs, \n\tint Ns, \n\tfloat lambda_space,\n\tfloat lambda_time,\n\tint max_iter);\n\nint dideal_recon_2D_Gradient( \n\tArray< float,2 >&kx, \n\tArray< float,2 >&ky, \n\tArray< complex<float>,2 >&kdata,\n\tArray< float,3 >&fieldmap,\n\tArray< float,2 >&ktimes,\n\tfloat *freqs, \n\tint Ns, \n\tfloat lambda_space,\n\tfloat lambda_time,\n\tfloat lambda_lowrank,\n\tint max_iter);\n\nvoid lowrank_thresh( Array< complex<float>, 4> &image, float thresh);\n\nint main( int argc, char **argv){\n\n\t// Hard Coded\n\tint Nt = 20;\n\tint Nr = 6692*2;\n\tint Ny = 128;\n\tint Nx = 128;\n\tint Ns = 3;\n\tint max_iter = 50;\n\tfloat lambda_space= 0.000;\n\tfloat lambda_time = 0.000;\n\tfloat lambda_lowrank = 0.000;\n\tfloat *freqs = new float[16];\n\tfreqs[0]=-42;\n\tfreqs[1]=-653;\n\tfreqs[2]=-462;\n\tfreqs[3]=-302;\n\t\n#define float_flag(name,val)    }else if(strcmp(name,argv[pos]) == 0){ pos++; val = atof(argv[pos]);\n#define int_flag(name,val)    }else if(strcmp(name,argv[pos]) == 0){ pos++; val = atoi(argv[pos]);\n\tfor(int pos=0; pos < argc; pos++){\n\t\tif (strcmp(\"-h\", argv[pos] ) == 0) {\n\n\t\t\tint_flag(\"-Nt\",Nt);\n\t\t\tint_flag(\"-Nr\",Nr);\n\t\t\tint_flag(\"-Ny\",Ny);\n\t\t\tint_flag(\"-Nx\",Nx);\n\t\t\tint_flag(\"-Ns\",Ns);\n\t\t\tint_flag(\"-max_iter\",max_iter);\n\t\t\tfloat_flag(\"-lambda_space\",lambda_space);\n\t\t\tfloat_flag(\"-lambda_time\",lambda_time);\n\t\t\tfloat_flag(\"-lambda_lowrank\",lambda_lowrank);\n\t\t\tfloat_flag(\"-f0\",freqs[0]);\n\t\t\tfloat_flag(\"-f1\",freqs[1]);\n\t\t\tfloat_flag(\"-f2\",freqs[2]);\n\t\t\tfloat_flag(\"-f3\",freqs[3]);\n\t\t\tfloat_flag(\"-f4\",freqs[4]);\n\t\t\tfloat_flag(\"-f5\",freqs[5]);\n\t\t\tfloat_flag(\"-f6\",freqs[6]);\n\t\t}\n\t}\n\t\n\tcout << \"Imaging Parameters\" << endl;\n\tcout << \"  Nx = \" << Nx << endl;\n\tcout << \"  Ny = \" << Ny << endl;\n\tcout << \"  Nt = \" << Nt << endl;\n\tcout << \"  Ns = \" << Ns << endl;\n\tcout << \"  Nr = \" << Nr << endl;\n\tcout << \"Recon Parameters\" << endl;\n\tfor(int sp = 0; sp <Ns; sp++){\n\tcout << \"  f\" << sp << \" = \" << freqs[sp] << endl;\n\t}\n\tcout << \"  lambda_space = \" << lambda_space << endl;\n\tcout << \"  lambda_time = \" << lambda_time << endl;\n\tcout << \"  lambda_lowrank = \" << lambda_lowrank << endl;\n\tcout << \"  max_iter = \" << max_iter << endl;\n\t\n\t// Allocate Memory and Copy Values\n\tcout << \"Kx\" << endl << flush;\n\tArray< float,2>kx(Nr,Nt,ColumnMajorArray<2>());\n\tArrayRead(kx,\"Kx.dat\");\n\tkx*=(float)1.0 / (float)Nx;\n\n\tcout << \"Ky\" << endl << flush;\n\tArray< float,2>ky(Nr,Nt,ColumnMajorArray<2>());\n\tArrayRead(ky,\"Ky.dat\");\n\tky*=(float)1.0 / (float)Ny;\n\t\n\tcout << \"Kt\" << endl << flush;\n\tArray< float,2>kt(Nr,Nt,ColumnMajorArray<2>());\n\tArrayRead(kt,\"Kt.dat\");\n\t\n\tcout << \"Kdata\" << endl << flush;\n\tArray< complex<float> ,2>kdata(Nr,Nt,ColumnMajorArray<2>());\n\tArrayRead(kdata,\"Kdata.dat\");\n\t\n\t\n\tcout << \"Fieldmap\" << endl << flush;\n\tArray< float,3>fieldmap(Nx,Ny,Nt,ColumnMajorArray<3>());\n\tArrayRead(fieldmap,\"FieldMap.dat\");\n\n\tif(lambda_lowrank == 0){\n\t\tdideal_recon_2D_CG( kx, ky, kdata, fieldmap, kt, freqs, Ns,lambda_space,lambda_time,max_iter);\n\t}else{\n\t\tdideal_recon_2D_Gradient( kx, ky, kdata, fieldmap, kt, freqs, Ns,lambda_space,lambda_time,lambda_lowrank,max_iter);\n\t}\n\n\treturn(0);\n}\n\n// Generate Images from Kdata\nvoid transpose_dideal(\n\tconst Array< complex<float>,2 > &diff_data,\n\tArray< complex<float>,4 > &X,\n\tconst Array< float, 2 > &kx,\n\tconst Array< float, 2 > &ky,\n\tconst Array< float, 2 > &kt,\n\tconst Array< float, 3 > &fieldmap,\n\tfloat *freqs){\n\n\tint Ns = X.length(fourthDim);\n\tint Nt = diff_data.length(secondDim); // Time Frame\n\tint Nr = diff_data.length(firstDim);  // Readout position\n\n\t// Spatial Coordinates\n\tint Nx = fieldmap.length(firstDim);\n\tint Ny = fieldmap.length(secondDim);\n\tfloat cx = (float)Ny/2.0;\n\tfloat cy = (float)Nx/2.0;\n\tconst float pic=-6.28318530718;\n\n\tX = 0;\n\n\tfloat fov = (float)(Nx*Nx)/(4.0);\n\t// Loop Kx/Ky\t\n\ttictoc T;\n\tT.tic();\n\n#pragma omp parallel for schedule(static,1)\n\tfor(int j=0; j<Ny; j++){\n\n\t\t// cout << \",\" << j << flush;\n\t\tfloat y = (float)j - cy;\n\n\t\tfor(int i=0; i<Nx; i++){\n\t\t\tfloat x = (float)i - cx;\n\t\t\tfloat rad = x*x + y*y;\n\t\t\tif( rad > fov) continue;\n\n\t\t\tfor(int species=0; species< Ns; species++){\n\t\t\t\tfor(int t=0; t< Nt; t++){\n\t\t\t\t\tfloat Pf = freqs[species]+fieldmap(i,j,t);\n\t\t\t\t\tcomplex<float>temp(0.0,0.0);\n\t\t\t\t\tfor(int rpos=0; rpos< Nr; rpos++){\n\t\t\t\t\t\t// Loop over image\n\t\t\t\t\t\tcomplex<float>basis = polar<float>((float)1.0, pic*(kx(rpos,t)*x + ky(rpos,t)*y + kt(rpos,t)*Pf));\n\t\t\t\t\t\ttemp+= ( diff_data(rpos,t)*basis);\n\t\t\t\t\t}\n\t\t\t\t\tX(i,j,t,species)=temp;\t// This takes all the time\n\t\t\t\t}// Nt\n\t\t\t}\n\t\t}\n\t}//Image Loop\n\tcout << \"Transpose Took = \" << T << endl;\n}\n\n\n\n// Generate Images from Kdata\nvoid forward_dideal(\n\tArray< complex<float>,2 > &diff_data,\n\tconst Array< complex<float>,4 > &X,\n\tconst Array< float, 2 > &kx,\n\tconst Array< float, 2 > &ky,\n\tconst Array< float, 2 > &kt,\n\tconst Array< float, 3 > &fieldmap,\n\tfloat *freqs){\n\n\tint Ns = X.length(fourthDim);\n\tint Nt = diff_data.length(secondDim); // Time Frame\n\tint Nr = diff_data.length(firstDim);  // Readout position\n\n\t// Spatial Coordinates\n\tint Nx = fieldmap.length(firstDim);\n\tint Ny = fieldmap.length(secondDim);\n\tfloat cx = (float)Ny/2.0;\n\tfloat cy = (float)Nx/2.0;\n\tconst float pic= 6.28318530718;\n\n\tdiff_data = 0;\n\n\tfloat fov = (float)(Nx*Nx)/(4.0);\n\t// Loop Kx/Ky\t\n\t\n\ttictoc T;\n\tT.tic();\n\n#pragma omp parallel for \n\tfor(int rpos=0; rpos< Nr; rpos++){\n\t\tfor(int t=0; t< Nt; t++){\n\n\n\t\t\t// Position in k-t space\n\t\t\tfloat Kx = kx(rpos,t);\n\t\t\tfloat Ky = ky(rpos,t);\n\t\t\tfloat Kt = kt(rpos,t);\n\n\t\t\t// Loop over image\n\t\t\tfor(int j=0; j<Ny; j++){\n\t\t\t\tfloat y = ((float)j - cy);\n\t\t\t\tfloat Py = y*Ky;\n\t\t\t\tfor(int i=0; i<Nx; i++){\n\t\t\t\t\tfloat x =((float)i - cx);\n\t\t\t\t\tfloat Px = x*Kx;\n\n\t\t\t\t\tfloat rad = x*x + y*y;\n\t\t\t\t\tif( rad > fov) continue;\n\t\t\t\t\tfor(int species=0; species< Ns; species++){\n\t\t\t\t\t\tcomplex<float>basis = polar<float>((float)1.0, pic*(Px + Py + Kt*( freqs[species]+fieldmap(i,j,t) )));\n\t\t\t\t\t\tdiff_data(rpos,t) += (X(i,j,t,species)*basis);\n\t\t\t\t\t}\n\t\t\t}}//Image Loop\n\n\t}}// K-t  + Species Looop\n\tcout << \"Forward Took = \" << T << endl;\n}\n\n\nint dideal_recon_2D_CG( \n\tArray< float,2 >&kx, \n\tArray< float,2 >&ky, \n\tArray< complex<float>,2 >&kdata,\n\tArray< float,3 >&fieldmap,\n\tArray< float,2 >&ktimes,\n\tfloat *freqs, \n\tint Ns, \n\tfloat lambda_space,\n\tfloat lambda_time,\n\tint max_iter){\n\n\t// Inputs\n\t//   kx      \t[Nr,Nt ]          = Matrix with Nt readouts of length Nr \n\t//   ky      \t[Nr,Nt ]          = Matrix with Nt readouts of length Nr \n\t//   kdata   \t[Nr,Nt ]   \t\t  = Matrix with Nt readouts of length Nr x Coils\n\t//   fieldmap\t[ResX,ResY,Nt]    = Fieldmap\n\t//   kt      \t[Nr,Nt]           = Readout times\n\t//   freqs   \t[Ns x 1]          = Offsets for Species\n\t//   max_iter   [scalar]     \t\tmaximum iterations\n\n\t\n\t// Dimensions of Problem\n\tint Nr = ky.length(firstDim);\n\tint Nt = ky.length(secondDim);\n\tint Ny = fieldmap.length(firstDim);\n\tint Nx = fieldmap.length(secondDim);\n\tcout << \"Array Size = \" << Nx << \" x \" << Ny << \" x \" << Nt << \" x \" << Ns << endl;\n\n\t// ------------------------------------\n\t// Iterative Soft Thresholding  x(n+1)=  thresh(   x(n) - E*(Ex(n) - d)  )\n\t//  Designed to not use memory\n\t// Uses gradient descent x(n+1) = x(n) - ( R'R ) / ( R'E'E R) * Grad  [ R = E'(Ex-d)]\n\t// ------------------------------------\n\n\t// Final Image Solution\n\tArray< complex<float>,4 >X(Nx,Ny,Nt,Ns,ColumnMajorArray<4>());\n\tX = 0;\n\n\t// Residue \t\n\tArray< complex<float>,4 >R(Nx,Ny,Nt,Ns,ColumnMajorArray<4>());\n\tR = 0;;\n\n\t// Residue \t\n\tArray< complex<float>,4 >Reg(Nx,Ny,Nt,Ns,ColumnMajorArray<4>());\n\tReg = 0;\n\n\t// Temp variable for E'ER \n\tArray< complex<float>,4 >P(Nx,Ny,Nt,Ns,ColumnMajorArray<4>());\n\tP = 0;;\n\n\t// Temp variable for E'ER \n\tArray< complex<float>,2 >diff_data(Nr,Nt,ColumnMajorArray<2>());\n\tdiff_data = 0;\n\t\n\n\n\t// RHS (CG)\n\tArray< complex<float>,4 >LHS(Nx,Ny,Nt,Ns,ColumnMajorArray<4>());\n\t\n\tcout << \"Init CG\" << endl;\n\t\n\tLHS= complex<float>(0,0);\n\tR= complex<float>(0,0);\n\tP= complex<float>(0,0);\n\t\n\ttranspose_dideal(kdata,R,kx,ky,ktimes,fieldmap,freqs);\n\tR = -R;\n\tP = R;\n\n\t// Conjugate Gradient\n\tfloat error0=0.0;\n\tfloat reg_scale2=0.0; \n\tfor(int iteration =0; iteration< max_iter; iteration++){\n\t\t\n\t\tcout << \"\\nIteration = \" << iteration << endl;\n\t\t\n\t\tdiff_data = complex<float>(0,0);\n\t\tforward_dideal(diff_data,P,kx,ky,ktimes,fieldmap,freqs);\n\t\t\n\t\tLHS = complex<float>(0,0);\n\t\ttranspose_dideal(diff_data,LHS,kx,ky,ktimes,fieldmap,freqs);\n\n\t\t// Convolve with TV\n\t\tReg = complex<float>(0.0,0.0);\n\t\tfor(int sp=0; sp<Ns; sp++){\n\t\t\tfor(int t=0;t<Nt;t++){\n\t\t\t\tfor(int j=0;j<Ny;j++){\n\t\t\t\t\tfor(int i=0;i<Nx;i++){\n\t\t\t\t\t\t\n\t\t\t\t\t\t// Space\n\t\t\t\t\t\tReg(i,j,t,sp)=complex<float>(4.0,0)*P(i,j,t,sp);\n\t\t\t\t\t\tReg(i,j,t,sp)-=P( (i+1+Nx)%Nx,j,t,sp);\n\t\t\t\t\t\tReg(i,j,t,sp)-=P( (i-1+Nx)%Nx,j,t,sp);\n\t\t\t\t\t\tReg(i,j,t,sp)-=P( i,(j+1+Ny)%Ny,t,sp);\n\t\t\t\t\t\tReg(i,j,t,sp)-=P( i,(j-1+Ny)%Ny,t,sp);\n\t\t\t\t\t\t\n\t\t\t\t\t\t//Time\n\t\t\t\t\t\tReg(i,j,t,sp) +=lambda_time*complex<float>(2.0,0)*P(i,j,t,sp);\n\t\t\t\t\t\tReg(i,j,t,sp) -=lambda_time*P(i,j,(Nt+t-1)%Nt,sp);\n\t\t\t\t\t\tReg(i,j,t,sp) -=lambda_time*P(i,j,(Nt+t+1)%Nt,sp);\n\t\t}}}}\t\t\t\n\n\t\tif(iteration==0){\n\t\t\terror0 = ArrayEnergy(R);\n\t\t\treg_scale2 = lambda_space*sqrt( error0 );\n\t\t}\n\t\tReg *= reg_scale2;\n\t\tLHS += Reg; \n\n\t\tcomplex< float> sum_R0_R0(0.0,0.0);\n\t\tcomplex< float> sum_R_R(0.0,0.0);\n\t\tcomplex< float> sum_P_LHS(0.0,0.0);\n\t\t\n\t\t// Calc R'R and P'*LHS\n\t\tfor(int sp=0; sp<Ns; sp++){\n\t\t\tfor(int t=0;t<Nt;t++){\n\t\t\t\tfor(int j=0;j<Ny;j++){\n\t\t\t\t\tfor(int i=0;i<Nx;i++){\t\t\t\n\t\t\t\t\t\tsum_R0_R0 += norm( R(i,j,t,sp));\n\t\t\t\t\t\tsum_P_LHS += conj( P(i,j,t,sp))*LHS(i,j,t,sp);\n\t\t}}}}\n\t\tcomplex< float> scale = sum_R0_R0 / sum_P_LHS; \n\n\n\t\t// Calc R'R and P'*LHS\n\t\tfor(int sp=0; sp<Ns; sp++){\n\t\t\tfor(int t=0;t<Nt;t++){\n\t\t\t\tfor(int j=0;j<Ny;j++){\n\t\t\t\t\tfor(int i=0;i<Nx;i++){\t\t\t\n\t\t\t\t\t\tX(i,j,t,sp) += ( scale*P(i,j,t,sp) );\n\t\t\t\t\t\tR(i,j,t,sp) -= ( scale*LHS(i,j,t,sp) );\n\t\t\t\t\t\tsum_R_R += norm( R(i,j,t,sp) );\n\t\t}}}}\n\t\t\n\t\tcout << \"Sum R'R = \" << sum_R_R << endl;\n\t\tcomplex< float> scale2 = sum_R_R / sum_R0_R0; \n\n\t\t// Take step size\n\t\tfor(int sp=0; sp<Ns; sp++){\n\t\t\tfor(int t=0;t<Nt;t++){\n\t\t\t\tfor(int j=0;j<Ny;j++){\n\t\t\t\t\tfor(int i=0;i<Nx;i++){\t\t\t\n\t\t\t\t\t\tP(i,j,t,sp) = R(i,j,t,sp) + scale2*P(i,j,t,sp);\n\t\t}}}}\n\n\t\tchar fname[80];\n\t\tfor(int sp=0; sp<Ns; sp++){\n\t\t\tsprintf(fname,\"Species_%d.dat\",sp);\n\t\t\tArray< complex<float>,3> TempS = X( Range::all(),Range::all(),Range::all(),sp);\n\t\t\tArrayWrite( TempS,fname);\n\t\t}\n\t}\n\n\n\treturn(0);\n}\n\nint dideal_recon_2D_Gradient( \n\tArray< float,2 >&kx, \n\tArray< float,2 >&ky, \n\tArray< complex<float>,2 >&kdata,\n\tArray< float,3 >&fieldmap,\n\tArray< float,2 >&ktimes,\n\tfloat *freqs, \n\tint Ns, \n\tfloat lambda_space,\n\tfloat lambda_time,\n\tfloat lambda_lowrank,\n\tint max_iter){\n\n\t// Inputs\n\t//   kx      \t[Nr,Nt ]          = Matrix with Nt readouts of length Nr \n\t//   ky      \t[Nr,Nt ]          = Matrix with Nt readouts of length Nr \n\t//   kdata   \t[Nr,Nt ]   \t\t  = Matrix with Nt readouts of length Nr x Coils\n\t//   fieldmap\t[ResX,ResY,Nt]    = Fieldmap\n\t//   kt      \t[Nr,Nt]           = Readout times\n\t//   freqs   \t[Ns x 1]          = Offsets for Species\n\t//   max_iter   [scalar]     \t\tmaximum iterations\n\n\t\n\t// Dimensions of Problem\n\tint Nr = ky.length(firstDim);\n\tint Nt = ky.length(secondDim);\n\tint Ny = fieldmap.length(firstDim);\n\tint Nx = fieldmap.length(secondDim);\n\tcout << \"Array Size = \" << Nx << \" x \" << Ny << \" x \" << Nt << \" x \" << Ns << endl;\n\n\t// ------------------------------------\n\t// Iterative Soft Thresholding  x(n+1)=  thresh(   x(n) - E*(Ex(n) - d)  )\n\t//  Designed to not use memory\n\t// Uses gradient descent x(n+1) = x(n) - ( R'R ) / ( R'E'E R) * Grad  [ R = E'(Ex-d)]\n\t// ------------------------------------\n\n\t// Final Image Solution\n\tArray< complex<float>,4 >X(Nx,Ny,Nt,Ns,ColumnMajorArray<4>());\n\tArray< complex<float>,4 >R(Nx,Ny,Nt,Ns,ColumnMajorArray<4>());\n\tArray< complex<float>,4 >Reg(Nx,Ny,Nt,Ns,ColumnMajorArray<4>());\n\tArray< complex<float>,2 >diff_data(Nr,Nt,ColumnMajorArray<2>());\n\tArray< complex<float>,4 >P(Nx,Ny,Nt,Ns,ColumnMajorArray<4>());\n\t\n\n\tR= complex<float>(0,0);\n\tX= complex<float>(0,0);\n\t\n\t\n\t// Conjugate Gradient\n\tfloat error0=0.0;\n\tfloat reg_scale2=0.0; \n\tfor(int iteration =0; iteration< max_iter; iteration++){\n\t\t\n\t\tcout << \"Iteration = \" << iteration << endl;\n\t\t\n\t\t// Get data\n\t\tdiff_data = complex<float>(0,0);\n\t\tforward_dideal(diff_data,X,kx,ky,ktimes,fieldmap,freqs);\n\t\t\n\t\t// Difference\n\t\tdiff_data -= kdata;\n\t\t\t\t\n\t\t// Get Residue\n\t\tR= complex<float>(0,0);\n\t\ttranspose_dideal(diff_data,R,kx,ky,ktimes,fieldmap,freqs);\n\n\t\t// Convolve with TV\n\t\tReg = complex<float>(0.0,0.0);\n\t\tfor(int sp=0; sp<Ns; sp++){\n\t\t\tfor(int t=0;t<Nt;t++){\n\t\t\t\tfor(int j=0;j<Ny;j++){\n\t\t\t\t\tfor(int i=0;i<Nx;i++){\n\t\t\t\t\t\t\n\t\t\t\t\t\t// Space\n\t\t\t\t\t\tReg(i,j,t,sp)=lambda_space*complex<float>(4.0,0)*X(i,j,t,sp);\n\t\t\t\t\t\tReg(i,j,t,sp)-=lambda_space*X( (i+1+Nx)%Nx,j,t,sp);\n\t\t\t\t\t\tReg(i,j,t,sp)-=lambda_space*X( (i-1+Nx)%Nx,j,t,sp);\n\t\t\t\t\t\tReg(i,j,t,sp)-=lambda_space*X( i,(j+1+Ny)%Ny,t,sp);\n\t\t\t\t\t\tReg(i,j,t,sp)-=lambda_space*X( i,(j-1+Ny)%Ny,t,sp);\n\t\t\t\t\t\t\n\t\t\t\t\t\t//Time\n\t\t\t\t\t\tReg(i,j,t,sp) +=lambda_time*complex<float>(2.0,0)*X(i,j,t,sp);\n\t\t\t\t\t\tReg(i,j,t,sp) -=lambda_time*X(i,j,(Nt+t-1)%Nt,sp);\n\t\t\t\t\t\tReg(i,j,t,sp) -=lambda_time*X(i,j,(Nt+t+1)%Nt,sp);\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t}}}}\t\t\t\n\n\t\tif(iteration==0){\n\t\t\terror0 = ArrayEnergy(R);\n\t\t\treg_scale2 = sqrt( error0 );\n\t\t}\n\t\tReg *= reg_scale2;\n\t\tR += Reg; \n\t\t\n\t\t\n\t\t// Now get Scale\n\t\tdiff_data = complex<float>(0,0);\n\t\tforward_dideal(diff_data,R,kx,ky,ktimes,fieldmap,freqs);\n\t\tP = complex<float>(0,0);\n\t\ttranspose_dideal(diff_data,P,kx,ky,ktimes,fieldmap,freqs);\n\t\t\n\t\tcout << \"Energy = \" << ArrayEnergy(R)/error0 << endl;\n\t\t\n\t\tP *= conj(R);\n\t\tcout << \"RhR = \" << ArrayEnergy(R) << endl;\n\t\tcout << \"RhP = \" << sum(P) << endl;\n\t\t\n\t\t\n\t\tcomplex<float>scale = ArrayEnergy(R)/sum(P);\n\t\tcout << \"Scale = \" << scale << endl;\n\t\t\n\t\tR *= scale;\n\t\tX -= R;\n\t\t\n\t\t\n\t\t{\n\t\t\tchar fname[80];\n\t\t\tfor(int sp=0; sp<Ns; sp++){\n\t\t\t\tsprintf(fname,\"Species_%d.dat.slice\",sp);\n\t\t\t\tArray< complex<float>,2> TempS = X( Range::all(),Range::all(),(int)(Nt/2),sp);\t\n\t\t\t\tArrayWriteMagAppend(TempS,fname);\n\t\t\t}\n\t\t}\n\t\t\n\t\tif(lambda_lowrank > 0){\n\t\t\tlowrank_thresh(X,lambda_lowrank);\n\t\t}\n\t\t\t\n\t\t{\n\t\t\tchar fname[80];\n\t\t\tfor(int sp=0; sp<Ns; sp++){\n\t\t\t\tsprintf(fname,\"Species_%d.dat.slice\",sp);\n\t\t\t\tArray< complex<float>,2> TempS = X( Range::all(),Range::all(),(int)(Nt/2),sp);\t\n\t\t\t\tArrayWriteMagAppend(TempS,fname);\n\t\t\t}\n\t\t}\n\t}\n\n\tchar fname[80];\n\tfor(int sp=0; sp<Ns; sp++){\n\t\tsprintf(fname,\"Species_%d.dat\",sp);\n\t\tArray< complex<float>,3> TempS = X( Range::all(),Range::all(),Range::all(),sp);\n\t\tArrayWrite( TempS,fname);\n\t}\n\n\treturn(0);\n}\n\nvoid lowrank_thresh( Array< complex<float>,4> &image, float thresh){\n\n\tint Nx = image.length(firstDim);\n\tint Ny = image.length(secondDim);\n\tint Nt = image.length(thirdDim);\n\tint Ns = image.length(fourthDim);\n\tint Np = Nx*Ny*Ns;\n\t\n\t// Copy image into matrix\n\tarma::cx_mat A;\n\tA.zeros(Nx*Ny*Ns,Nt);\n\t\n\tfor(int t =0; t < Nt; t++){\n\t\tint count = 0;\n\n\t\tfor(int s =0; s<Ns; s++){\n\t\tfor(int j =0; j<Ny; j++){\n\t\tfor(int i =0; i<Nx; i++){\n\t\t\tA(count,t) = image(i,j,t,s);\t\n\t\t\tcount++;\n\t\t}}}\n\t}\n\t\n\t// SVD\n\tcout << \"Svd\" << endl;\n\tarma::cx_mat U;\n\tarma::vec s;\n\tarma::cx_mat V;\n\tarma::svd(U,s,V,A);\n\t\n\tarma::mat S;\n\tS.zeros(Np,Nt); // Pixels x Coils\n\t\n\tcout << \"Thresh with \" << thresh << endl;\n\tfloat smax = thresh*max(s);\n\tfor(int pos =0; pos< min(Nt,Np); pos++){\n\t\tS(pos,pos)=   max( s(pos) - smax, 0.0 );\n\t}\n\t\n\tA = U*S*V.t(); \n\t\n\tfor(int t =0; t < Nt; t++){\n\t\tint count = 0;\n\n\t\tfor(int s =0; s<Ns; s++){\n\t\tfor(int j =0; j<Ny; j++){\n\t\tfor(int i =0; i<Nx; i++){\n\t\t\timage(i,j,t,s) = A(count,t);\t\n\t\t\tcount++;\n\t\t}}}\n\t}\n}\n\n", "meta": {"hexsha": "636ce3b9625ac572723c583802ae5c022e3de6e4", "size": 15825, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "recon.cxx", "max_stars_repo_name": "kmjohnson3/c13_spiral_recon", "max_stars_repo_head_hexsha": "2e515de3f40cc0911552da2c3a4da6f7d9f4f5ab", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "recon.cxx", "max_issues_repo_name": "kmjohnson3/c13_spiral_recon", "max_issues_repo_head_hexsha": "2e515de3f40cc0911552da2c3a4da6f7d9f4f5ab", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "recon.cxx", "max_forks_repo_name": "kmjohnson3/c13_spiral_recon", "max_forks_repo_head_hexsha": "2e515de3f40cc0911552da2c3a4da6f7d9f4f5ab", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.8156606852, "max_line_length": 117, "alphanum_fraction": 0.5778830964, "num_tokens": 5603, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.782662489091802, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.47850573700425786}}
{"text": "//\n// Copyright 2016 MIT Lincoln Laboratory, Massachusetts Institute of Technology\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use these files except in compliance with\n// the License.\n//\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on\n// an \"AS IS\" BASIS, WITHOUT WARRANTIES OR 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\n// MFCCs\n\n// Refactored from LLSpeech 2.2.10 code & BC Speech Tools:\n// filtbank.cc, mfb_to_cep.cc, mfb_to_cep_subs.cc, mfb_utils.cc, pcm_to_feat.cc, pcm_to_mfb_subs.cc, vec_utils.cc\n\n// Written by BC 10/18/10\n#include \"stdafx.h\"\n#include <stdio.h>\n#include <math.h>\n#include \"speech_tools.h\"\n#include <boost/property_tree/ptree.hpp>\n#include <boost/property_tree/json_parser.hpp>\nusing boost::property_tree::ptree;\nusing boost::property_tree::read_json;\n\n#define PI 3.141592653589793\n\ntypedef float* flt_ptr;\nstatic float warp (float freq, float alpha, float sfreq);\n\n//\n// Main processing routine\n//\nvoid MFCC_Features::process (Signal &x, string &config_str) \n{\n\n\t// MFCC configuration\n\tconfig(x, config_str);\n\t\n\t// Set up storage\n\tFrame f(win_len, win_inc);\n\tmag_fft m(win_len);\n\tvec<REAL_FEAT> x_frame(win_len);\n\tvec<REAL_FFT> x_mag(n2_fft+1);\n\tvec<REAL_FFT> x_fb(num_filt_bl);\n\tvec<REAL_FEAT> x_cep(num_features);\n\tREAL_FEAT *feat_ptr;\n\n\t// Allocate space for features\n\tnum_vectors = f.get_num_frames(x);\n\tfeat_ptr = feat = new REAL_FEAT[num_vectors*num_features];\n\tenergy = new REAL_FEAT[num_vectors];\n\n\t// Loop across frames\n\tint i, j;\n\tfor (i=0; i<num_vectors; i++) {\n\n\t\t// Frame based pre-processing\n\t\tf.get_frame(x, i);\n\t\tf.dither(dither);\n\t\tf.rm_dc();\n\t\tf.hamming_window();\n\t\tenergy[i] = f.energy();\n\n\t\t// FFT magnitudes -- FFT not quite the same as LLSpeech\n\t\tx_frame = f.vector();\n\t\tx_mag = m.calc(x_frame);\n\n\t\t// Pre-emphasis\n\t\tx_mag.scale(*preemp_filt);\n\n\t\t// Calculate filterbanks with bandlimiting\n\t\tx_fb = calc_fb(x_mag);\n\n\t\tif (fb_only) {\n\t\t\tfor (j=0; j<num_features; j++, feat_ptr++)\n\t\t\t\t*feat_ptr = x_fb.data[j];\n\t\t} else {\n\t\t\t// Cepstral coefficients\n\t\t\tx_cep = icostrans(x_fb);\n\t\t\tfor (j=0; j<num_features; j++, feat_ptr++)\n\t\t\t\t*feat_ptr = x_cep.data[j];\n\t\t}\n\n\t}\n\n\tfeatures_available = true;\n\tenergy_available = true;\n\n}\n\nMFCC_Features::MFCC_Features () \n{\n\tfilt_beg = 0;\n\tfilt_end = 0;\n\tfilt = 0;\n\tfc = 0;\n\tpreemp_filt = 0;\n\ticos_matrix = 0;\n}\n\nMFCC_Features::~MFCC_Features () \n{\n\tdelete[] filt_beg;\n\tdelete[] filt_end;\n\tdelete[] fc;\n\tif (filt!=0) {\n\t\tfor (int i=0; i<num_filt; i++)\n\t\t\tdelete[] (filt[i]);\n\t}\n\tdelete[] filt;\n\tdelete preemp_filt;\n\tdelete[] icos_matrix;\n}\n\nvoid MFCC_Features::config (Signal &x, string &config) \n{\n   bool linear = false;\n   int tgt_num_filt = -1;\n\n   istringstream is(config);\n   ptree pt;\n\n   try {\n      read_json(is, pt);\n      alpha = pt.get<float>(\"alpha\");\n      dither = pt.get<float>(\"dither\");\n      fb_low = pt.get<float>(\"fb_low\");\n      fb_hi = pt.get<float>(\"fb_hi\");\n\t\tkeep_c0 = pt.get<bool>(\"keep_c0\");\n      linear = pt.get<bool>(\"linear\");\n      num_cep = pt.get<int>(\"num_cep\");\n      win_inc_ms = pt.get<float>(\"win_inc_ms\");\n      win_len_ms = pt.get<float>(\"win_len_ms\");\n\t\tif (pt.find(\"fb_only\")==pt.not_found())\n\t\t\tfb_only = false;\n\t\telse\n\t\t\tfb_only = pt.get<bool>(\"fb_only\");\n      if (pt.find(\"tgt_num_filt\")!=pt.not_found())\n         tgt_num_filt = pt.get<int>(\"tgt_num_filt\");\n   } catch (exception &e) {\n      throw ST_exception(string(\"MFCC_Features::config:  error in config string, \")+e.what());\n   }\n\n\t// Sanity check\n\tfloat f_max = x.sampling_freq()/2.0f;\n\tif ((fb_low<0) || (fb_hi<fb_low) || (fb_hi>f_max))\n      throw ST_exception(\"MFCC_Features::process -- filterbank parameters don't make sense.\");\n\tsampling_freq = x.sampling_freq();\n\n\t// Find window parameters\n\twin_inc = (int) ((x.sampling_freq()*win_inc_ms)/1000);\n\twin_len = (int) ((x.sampling_freq()*win_len_ms)/1000);\n\tif ((win_len % 2) != 0)\n\t\twin_len++;\n\tif (win_inc<=0 || win_len<=0)\n\t\tthrow ST_exception(\"MFCC_Features::process -- Window increment or length is <= 0.\");\n\n\t// Initialize filterbank\n\tfor (n_fft=1; n_fft<win_len; n_fft*= 2);\n\tn2_fft = n_fft/2;\n\tinit_filtbank(f_max, n2_fft+1, linear, tgt_num_filt);\n\tif (fb_low==0 && fb_hi==f_max) { // Use full band\n\t\tfb_index_low = 0;\n\t\tfb_index_hi = num_filt-1;\n\t} else {\n\t\tfb_index_low = filtbank_get_filt_num(fb_low);\n\t\tfb_index_hi = filtbank_get_filt_num(fb_hi);\n\t}\n   num_filt_bl = fb_index_hi-fb_index_low+1;\n\n\t// Initialize cepstral processing\n\tif ((num_cep <= 0) || (num_cep>(num_filt_bl-1)))\n\t\tthrow ST_exception(\"Number of cepstral coefficients larger than number of filters.\");\n\n\tnum_features = 0;\n\tif (fb_only) {\n\t\tnum_features = num_filt_bl;\n\t} else {\n\t\tif (keep_c0)\n\t\t\tnum_features = 1;\n\t\tnum_features += num_cep;\n\t}\n\tnum_base_features = num_features;\n\tinit_icostrans();\n\n\t// Initialize pre-emphasis\n\tpreemp_filt = new vec<REAL_FFT> (n2_fft+1);\n\tfloat finc = (float) (f_max/(n2_fft+1.0));\n\tfloat f = 0;\n\tfor (int j=0; j<=n2_fft; f += finc, j++)\n\t\tpreemp_filt->data[j] = (REAL_FEAT) (1.0 + f*f/2.5e5);\n\n}\n\nvec<REAL_FFT> MFCC_Features::calc_fb (vec<REAL_FFT> &mag)\n{\n\tint i, j, k, l;\n\tvec<REAL_FFT> x_fb(num_filt_bl);\n\tREAL_FFT val;\n\n\tfor (i=fb_index_low, l=0; i<=fb_index_hi; i++, l++) {\n\t\tval = 0;\n\t\tfor (j=filt_beg[i], k=0; j<filt_end[i]; j++, k++)\n\t\t\tval += mag.data[j]*filt[i][k];\n\t\tval = (REAL_FFT) (10.0*log10(val + 1e-20)-40.0);\n\t\tx_fb.data[l] = val;\n\t}\n\treturn x_fb;\n\n}\n\nint MFCC_Features::filtbank_get_filt_num (float freq) \n{\n  int i;\n  for (i=1; i<=num_filt && fc[i]<=freq; i++);\n  i--;\n  if(i < 1) \n\t  return 0;\n  if (i==num_filt) \n\t  return num_filt-1;\n  if ((fc[i+1]-freq) < (freq-fc[i])) \n\t  i++; // move to closest center freq\n  return i-1;\n\n}\n\nvec<REAL_FEAT> MFCC_Features::icostrans (vec<REAL_FFT> &x)\n{\n\tvec<REAL_FEAT> out(num_features);\n\tint i, j, k;\n\tREAL_FFT val;\n\n\t// Matrix vector multiply -- should use BLAS\n\ti = keep_c0 ? 0 : 1;\n\tfor (k=0; k<num_features; k++, i++) {\n\t\tval = 0;\n\t\tfor (j=0; j<num_filt_bl; j++)\n\t\t\tval += icos_matrix[i*num_filt_bl+j]*x.data[j];\n\t\tout.data[k] = (REAL_FEAT) val;\n\t}\n\n\treturn out;\n\n} \n\nvoid MFCC_Features::init_icostrans () \n{\n\tfloat tmp, W;\n\tint i, j;\n\n\ttmp = (float) (1.0/num_filt_bl);\n\tW = (float) (PI*tmp);\n\ticos_matrix = new REAL_FFT[(num_cep+1)*num_filt_bl];\n\n\tfor (i=0; i < (num_cep+1); i++) {\n\t\tfor (j=0; j < num_filt_bl; j++) {\n\t\t\ticos_matrix[i*num_filt_bl+j] = (float) (cos((double) i*(j+0.5)*W)*tmp);\n\t\t}\n\t}\n\n}\n\nvoid MFCC_Features::init_filtbank (const float fmax, const int num_dft, bool linear, int tgt_num_filt)\n{\n  float f, *Fptr, area;\n  float finc, delta_f;\n  int i, j, nf, init_len, final_len;\n\n  finc = fmax/(num_dft-1);\n\n  if (linear) {\n     if (tgt_num_filt<=0)\n        delta_f = 100;\n     else\n        delta_f = fmax/(tgt_num_filt+1);\n     for (nf=0, f=-delta_f; f<fmax; nf++)\n        f += delta_f;\n     fc = new float[nf];\n     for (nf=0, f=-delta_f; f<fmax; nf++)\n        fc[nf] = warp(f+=delta_f, alpha, fmax);\n     nf -= 2;\n     if ((fc[nf]+fc[nf+1])/2 > fmax)\n        nf--;\n     init_len = (int) ((fc[2]-fc[0])/finc + 1);\n  } else {\n     // Determine length of fc\n     for (nf=11, f=1000; f<fmax; nf++)\n        f *= 1.1f;\n     fc = new float[nf];\n\n     // Center frequencies\n     for (i=0; i<=10; i++) // 100 Hz\n        fc[i] = (float) warp((float) i*100, alpha, fmax);\n     for (nf=11, f=1000; f<fmax; nf++) { // 10% spacing \n        f *= 1.1f;\n        fc[nf] = warp(f, alpha, fmax);\n     }\n     nf -= 2;\n     if ((fc[nf]+fc[nf+1])/2 > fmax) \n        nf--;\n\n     // Determine maximum initial length\n     init_len = 0;\n     for (i = 1; i < nf + 1; i++) {\n        int x = (int) ((fc[i+1]-fc[i-1])/finc + 1);\n        init_len = x > init_len ? x : init_len;\n     }\n  }\n\n  filt_beg = new int[nf];\n  filt_end = new int[nf];\n  filt = new flt_ptr[nf];\n  float *tmp_filt = new float[init_len];\n\n  for (i=1; i<=nf; ++i) {\n\t  area = 0.0;\n\t  Fptr = tmp_filt;\n\t  filt_beg[i-1] = 0;\n\t  filt_end[i-1] = 0;\n\t  for (j=0, f=0.0; (f<fmax) && (j<num_dft); f+=finc, j++) {\n\t\t  if ((f <= fc[i-1]) || (f >= fc[i+1])) \n\t\t\t  continue;\n\t\t  if (f < fc[i]) {\n\t\t\t  if (filt_beg[i-1] == 0) \n\t\t\t\t  filt_beg[i-1] = j;\n\t\t\t  *Fptr = (f-fc[i-1])/(fc[i]-fc[i-1]);\n\t\t\t  area += (*Fptr++);\n\t\t  } else {\n\t\t\t  *Fptr = (fc[i+1]-f)/(fc[i+1]-fc[i]);\n\t\t\t  filt_end[i-1] = j+1;\n\t\t\t  area += (*Fptr++);\n\t\t  } \n\t  } \n\n\t  //  Single DFT sample in filter passband, happens with very small windows (e.g., 5ms)\n\t  if ((filt_end[i-1]==0) && (filt_beg[i-1]!=0)) \n\t\t  filt_end[i-1] = filt_beg[i-1]+1;\n\t  else if ((filt_end[i-1]!=0) && (filt_beg[i-1]==0)) \n\t\t  filt_beg[i-1] = filt_end[i-1]-1;\n\t  \n\t  final_len = filt_end[i-1] - filt_beg[i-1];\n\t  filt[i-1] = new float[final_len]; \n\t  for (j=0; j<final_len; j++)\n\t\t  filt[i-1][j] = tmp_filt[j]/area;\n\n  } // next i\n\n  delete[] tmp_filt;\n  num_filt = nf;\n\n} // init_filterbank\n\nfloat MFCC_Features::duration(void)\n{\n   return (float) (((float) num_vectors)*(0.001*win_inc_ms));\n}\n\nfloat MFCC_Features::get_win_inc_ms (void)\n{\n   return win_inc_ms;\n}\n\n//\n// Local functions\n//\nstatic float warp (float freq, float alpha, float sfreq)\n{\n  float ret;\n  float fr = (float) (freq * PI / sfreq);\n  ret = (float) (fr + 2.0f * atan((double)(1.0 - alpha) * sin((double)fr) / (1.0 - (1.0 - alpha) * cos((double)fr))));\n  ret *= (float) (sfreq/PI);\n  return ret;\n}\n\n\n", "meta": {"hexsha": "e7939ef19dac859bb900a875d352d014de31dcdc", "size": 9497, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "slgr_engine/feat_mfcc.cpp", "max_stars_repo_name": "nathandouglas/pyslgr", "max_stars_repo_head_hexsha": "89076bbb432ff9b8159b84e1894bb7883ea59617", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-03-22T14:34:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-26T03:05:22.000Z", "max_issues_repo_path": "slgr_engine/feat_mfcc.cpp", "max_issues_repo_name": "nathandouglas/pyslgr", "max_issues_repo_head_hexsha": "89076bbb432ff9b8159b84e1894bb7883ea59617", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-10-15T23:18:45.000Z", "max_issues_repo_issues_event_max_datetime": "2017-10-30T23:08:03.000Z", "max_forks_repo_path": "slgr_engine/feat_mfcc.cpp", "max_forks_repo_name": "nathandouglas/pyslgr", "max_forks_repo_head_hexsha": "89076bbb432ff9b8159b84e1894bb7883ea59617", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2016-12-21T18:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-09T14:09:55.000Z", "avg_line_length": 24.8612565445, "max_line_length": 120, "alphanum_fraction": 0.6176687375, "num_tokens": 3214, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.782662489091802, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.47850573700425786}}
{"text": "#pragma once\n#ifndef KERNEL_H\n#define KERNEL_H\n\n#include <vector>\n#include <Eigen/Core>\n\nnamespace Kernel\n{\n    double dot(const std::vector<Eigen::Vector3d> & v1, const std::vector<Eigen::Vector3d> & v2);\n\n    void run_eigen_solver(const std::vector<Eigen::Matrix3f> &m);\n}\n\n#endif", "meta": {"hexsha": "a0068fcde95e0b22eae80e2cc053f6220ec4d931", "size": 282, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/kernel.hpp", "max_stars_repo_name": "Robslhc/eigen-cuda", "max_stars_repo_head_hexsha": "31c4b1488730d2ea4d5612e6d0769369a2b376b9", "max_stars_repo_licenses": ["MIT"], "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/kernel.hpp", "max_issues_repo_name": "Robslhc/eigen-cuda", "max_issues_repo_head_hexsha": "31c4b1488730d2ea4d5612e6d0769369a2b376b9", "max_issues_repo_licenses": ["MIT"], "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/kernel.hpp", "max_forks_repo_name": "Robslhc/eigen-cuda", "max_forks_repo_head_hexsha": "31c4b1488730d2ea4d5612e6d0769369a2b376b9", "max_forks_repo_licenses": ["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.8, "max_line_length": 97, "alphanum_fraction": 0.7163120567, "num_tokens": 79, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.47850573080553893}}
{"text": "/*\n * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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#define BOOST_TEST_MAIN\n#define BOOST_TEST_MODULE davidson_test\n\n// Standard includes\n#include <iostream>\n\n// Third party includes\n#include <boost/test/unit_test.hpp>\n\n// Local VOTCA includes\n#include \"votca/xtp/bseoperator_btda.h\"\n#include \"votca/xtp/davidsonsolver.h\"\n#include \"votca/xtp/eigen.h\"\n#include \"votca/xtp/matrixfreeoperator.h\"\n\nusing namespace votca::xtp;\nusing namespace votca;\n\nEigen::MatrixXd symm_matrix(Index N, double eps) {\n  Eigen::MatrixXd matrix;\n  matrix = eps * Eigen::MatrixXd::Random(N, N);\n  Eigen::MatrixXd tmat = matrix.transpose();\n  matrix = matrix + tmat;\n  return matrix;\n}\n\nEigen::MatrixXd init_matrix(Index N, double eps) {\n  Eigen::MatrixXd matrix = Eigen::MatrixXd::Zero(N, N);\n  for (Index i = 0; i < N; i++) {\n    for (Index j = i; j < N; j++) {\n      if (i == j) {\n        matrix(i, i) = std::sqrt(static_cast<double>(1 + i));\n      } else {\n        matrix(i, j) = eps / std::pow(static_cast<double>(j - i), 2);\n        matrix(j, i) = eps / std::pow(static_cast<double>(j - i), 2);\n      }\n    }\n  }\n  return matrix;\n}\n\nBOOST_AUTO_TEST_SUITE(davidson_test)\n\nBOOST_AUTO_TEST_CASE(davidson_full_matrix) {\n\n  Index size = 100;\n  Index neigen = 10;\n  double eps = 0.01;\n  Eigen::MatrixXd A = init_matrix(size, eps);\n  Logger log;\n  DavidsonSolver DS(log);\n  DS.solve(A, neigen);\n  Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(A);\n\n  auto lambda = DS.eigenvalues();\n  auto lambda_ref = es.eigenvalues().head(neigen);\n  bool check_eigenvalues = lambda.isApprox(lambda_ref, 1E-6);\n  if (!check_eigenvalues) {\n    std::cout << \"ref\" << std::endl;\n    std::cout << es.eigenvalues().head(neigen).transpose() << std::endl;\n    std::cout << \"result\" << std::endl;\n    std::cout << DS.eigenvalues().transpose() << std::endl;\n  }\n\n  BOOST_CHECK_EQUAL(check_eigenvalues, 1);\n}\n\nBOOST_AUTO_TEST_CASE(davidson_full_matrix_large) {\n\n  Index size = 400;\n  Index neigen = 10;\n  double eps = 0.01;\n  Eigen::MatrixXd A = init_matrix(size, eps);\n  Logger log;\n  DavidsonSolver DS(log);\n  DS.solve(A, neigen);\n  Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(A);\n\n  auto lambda = DS.eigenvalues();\n  auto lambda_ref = es.eigenvalues().head(neigen);\n  bool check_eigenvalues = lambda.isApprox(lambda_ref, 1E-6);\n  if (!check_eigenvalues) {\n    std::cout << \"ref\" << std::endl;\n    std::cout << es.eigenvalues().head(neigen).transpose() << std::endl;\n    std::cout << \"result\" << std::endl;\n    std::cout << DS.eigenvalues().transpose() << std::endl;\n  }\n\n  BOOST_CHECK_EQUAL(check_eigenvalues, 1);\n}\n\nBOOST_AUTO_TEST_CASE(davidson_full_matrix_fail) {\n\n  Index size = 100;\n  Index neigen = 10;\n  double eps = 0.01;\n  Eigen::MatrixXd A = init_matrix(size, eps);\n\n  Logger log;\n  DavidsonSolver DS(log);\n  DS.set_iter_max(1);\n  DS.solve(A, neigen);\n  Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(A);\n\n  auto lambda = DS.eigenvalues();\n  auto lambda_ref = es.eigenvalues().head(neigen);\n  bool check_eigenvalues = lambda.isApprox(lambda_ref, 1E-6);\n\n  BOOST_CHECK_EQUAL(check_eigenvalues, 0);\n}\n\nclass TestOperator : public MatrixFreeOperator {\n public:\n  TestOperator() = default;\n  Eigen::RowVectorXd OperatorRow(Index index) const override;\n\n private:\n};\n\n//  get a col of the operator\nEigen::RowVectorXd TestOperator::OperatorRow(Index index) const {\n  Index lsize = this->size();\n  Eigen::RowVectorXd row_out = Eigen::RowVectorXd::Zero(lsize);\n  for (Index j = 0; j < lsize; j++) {\n    if (j == index) {\n      row_out(j) = std::sqrt(static_cast<double>(index + 1));\n    } else {\n      row_out(j) = 0.01 / std::pow(static_cast<double>(j - index), 2);\n    }\n  }\n  return row_out;\n}\n\nBOOST_AUTO_TEST_CASE(davidson_matrix_free) {\n\n  Index size = 100;\n  Index neigen = 10;\n\n  // Create Operator\n  TestOperator Aop;\n  Aop.set_size(size);\n\n  Logger log;\n  DavidsonSolver DS(log);\n  DS.set_tolerance(\"normal\");\n  DS.set_size_update(\"safe\");\n  DS.solve(Aop, neigen);\n\n  Eigen::MatrixXd A = Aop.get_full_matrix();\n  Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(A);\n\n  auto lambda = DS.eigenvalues();\n  auto lambda_ref = es.eigenvalues().head(neigen);\n  bool check_eigenvalues = lambda.isApprox(lambda_ref, 1E-6);\n\n  BOOST_CHECK_EQUAL(check_eigenvalues, 1);\n  if (!check_eigenvalues) {\n    std::cout << \"ref\" << std::endl;\n    std::cout << es.eigenvalues().head(neigen).transpose() << std::endl;\n    std::cout << \"result\" << std::endl;\n    std::cout << DS.eigenvalues().transpose() << std::endl;\n  }\n}\n\nBOOST_AUTO_TEST_CASE(davidson_matrix_free_large) {\n\n  Index size = 400;\n  Index neigen = 10;\n\n  // Create Operator\n  TestOperator Aop;\n  Aop.set_size(size);\n\n  Logger log;\n  DavidsonSolver DS(log);\n  DS.set_tolerance(\"normal\");\n  DS.set_size_update(\"safe\");\n  DS.solve(Aop, neigen);\n  std::cout << log << std::endl;\n  Eigen::MatrixXd A = Aop.get_full_matrix();\n  Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(A);\n\n  auto lambda = DS.eigenvalues();\n  auto lambda_ref = es.eigenvalues().head(neigen);\n  bool check_eigenvalues = lambda.isApprox(lambda_ref, 1E-6);\n\n  BOOST_CHECK_EQUAL(check_eigenvalues, 1);\n  if (!check_eigenvalues) {\n    std::cout << \"ref\" << std::endl;\n    std::cout << es.eigenvalues().head(neigen).transpose() << std::endl;\n    std::cout << \"result\" << std::endl;\n    std::cout << DS.eigenvalues().transpose() << std::endl;\n  }\n}\n\nclass BlockOperator : public MatrixFreeOperator {\n public:\n  BlockOperator() = default;\n  Eigen::MatrixXd OperatorBlock(Index row, Index col) const override;\n\n  bool useRow() const override { return false; }\n  bool useBlock() const override { return true; }\n  Index getBlocksize() const override { return size() / 10; }\n\n private:\n};\n\n//  get a block of the operator\nEigen::MatrixXd BlockOperator::OperatorBlock(Index row, Index col) const {\n  Index blocksize = getBlocksize();\n  Eigen::MatrixXd block = Eigen::MatrixXd::Zero(blocksize, blocksize);\n  Index blocdisttodiagonal = std::abs(row - col) * blocksize;\n  for (Index i_col = 0; i_col < blocksize; i_col++) {\n    for (Index i_row = 0; i_row < blocksize; i_row++) {\n      block(i_row, i_col) =\n          0.01 / std::pow(static_cast<double>(std::abs(i_row - i_col) +\n                                              blocdisttodiagonal),\n                          2);\n    }\n  }\n  if (blocdisttodiagonal == 0) {\n    for (Index i = 0; i < blocksize; i++) {\n      block(i, i) = std::sqrt(static_cast<double>(row * blocksize + i + 1));\n    }\n  }\n\n  return block;\n}\n\nBOOST_AUTO_TEST_CASE(davidson_matrix_free_block) {\n\n  Index size = 100;\n  Index neigen = 10;\n\n  // Create Operator\n  BlockOperator Aop;\n  Aop.set_size(size);\n\n  Logger log;\n  DavidsonSolver DS(log);\n  DS.set_tolerance(\"normal\");\n  DS.set_size_update(\"safe\");\n\n  Eigen::MatrixXd A = Aop.get_full_matrix();\n  Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(A);\n  DS.solve(Aop, neigen);\n  auto lambda = DS.eigenvalues();\n  auto lambda_ref = es.eigenvalues().head(neigen);\n  bool check_eigenvalues = lambda.isApprox(lambda_ref, 1E-6);\n\n  BOOST_CHECK_EQUAL(check_eigenvalues, 1);\n  if (!check_eigenvalues) {\n    std::cout << \"ref\" << std::endl;\n    std::cout << es.eigenvalues().head(neigen).transpose() << std::endl;\n    std::cout << \"result\" << std::endl;\n    std::cout << DS.eigenvalues().transpose() << std::endl;\n  }\n}\n\nBOOST_AUTO_TEST_CASE(davidson_matrix_free_block_large) {\n\n  Index size = 400;\n  Index neigen = 10;\n\n  // Create Operator\n  BlockOperator Aop;\n  Aop.set_size(size);\n\n  Logger log;\n  DavidsonSolver DS(log);\n  DS.set_tolerance(\"normal\");\n  DS.set_size_update(\"safe\");\n\n  Eigen::MatrixXd A = Aop.get_full_matrix();\n  Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(A);\n  DS.solve(Aop, neigen);\n  auto lambda = DS.eigenvalues();\n  auto lambda_ref = es.eigenvalues().head(neigen);\n  bool check_eigenvalues = lambda.isApprox(lambda_ref, 1E-6);\n\n  BOOST_CHECK_EQUAL(check_eigenvalues, 1);\n  if (!check_eigenvalues) {\n    std::cout << \"ref\" << std::endl;\n    std::cout << es.eigenvalues().head(neigen).transpose() << std::endl;\n    std::cout << \"result\" << std::endl;\n    std::cout << DS.eigenvalues().transpose() << std::endl;\n  }\n}\n\nEigen::ArrayXi index_eval(Eigen::VectorXd ev, Index neigen) {\n\n  Index nev = ev.rows();\n  Index npos = nev / 2;\n\n  Eigen::ArrayXi idx = Eigen::ArrayXi::Zero(npos);\n  Index nstored = 0;\n\n  // get only positives\n  for (Index i = 0; i < nev; i++) {\n    if (ev(i) > 0) {\n      idx(nstored) = int(i);\n      nstored++;\n    }\n  }\n\n  // sort the epos eigenvalues\n  std::sort(idx.data(), idx.data() + idx.size(),\n            [&](Index i1, Index i2) { return ev[i1] < ev[i2]; });\n  return idx.head(neigen);\n}\n\nEigen::MatrixXd extract_eigenvectors(const Eigen::MatrixXd &V,\n                                     const Eigen::ArrayXi &idx) {\n  Eigen::MatrixXd W = Eigen::MatrixXd::Zero(V.rows(), idx.size());\n  for (Index i = 0; i < idx.size(); i++) {\n    W.col(i) = V.col(idx(i));\n  }\n  return W;\n}\n\nclass HermitianBlockOperator : public MatrixFreeOperator {\n public:\n  HermitianBlockOperator() = default;\n\n  void attach_matrix(const Eigen::MatrixXd &mat);\n  Eigen::RowVectorXd OperatorRow(Index index) const override;\n  void set_diag(Index diag);\n  Eigen::VectorXd diag_el;\n\n private:\n  Eigen::MatrixXd _mat;\n};\n\nvoid HermitianBlockOperator::attach_matrix(const Eigen::MatrixXd &mat) {\n  _mat = mat;\n}\n\n//  get a col of the operator\nEigen::RowVectorXd HermitianBlockOperator::OperatorRow(Index index) const {\n  return _mat.row(index);\n}\n\nBOOST_AUTO_TEST_CASE(davidson_hamiltonian_matrix_free) {\n\n  Index size = 60;\n  Index neigen = 5;\n  Logger log;\n\n  // Create Operator\n  HermitianBlockOperator Rop;\n  Rop.set_size(size);\n  Eigen::MatrixXd rmat = init_matrix(size, 0.01);\n  Rop.attach_matrix(rmat);\n\n  HermitianBlockOperator Cop;\n  Cop.set_size(size);\n  Eigen::MatrixXd cmat = symm_matrix(size, 0.01);\n  Cop.attach_matrix(cmat);\n\n  // create Hamiltonian operator\n  HamiltonianOperator<HermitianBlockOperator, HermitianBlockOperator> Hop(Rop,\n                                                                          Cop);\n\n  DavidsonSolver DS(log);\n  DS.set_tolerance(\"normal\");\n  DS.set_size_update(\"max\");\n  DS.set_matrix_type(\"HAM\");\n  DS.solve(Hop, neigen);\n  auto lambda = DS.eigenvalues().real();\n  std::sort(lambda.data(), lambda.data() + lambda.size());\n  Eigen::MatrixXd H = Hop.get_full_matrix();\n\n  Eigen::EigenSolver<Eigen::MatrixXd> es(H);\n  Eigen::ArrayXi idx = index_eval(es.eigenvalues().real(), neigen);\n  Eigen::VectorXd lambda_ref = idx.unaryExpr(es.eigenvalues().real());\n\n  bool check_eigenvalues = lambda.isApprox(lambda_ref.head(neigen), 1E-6);\n  if (!check_eigenvalues) {\n    std::cout << \"Davidson not converged after \" << DS.num_iterations()\n              << \" iterations\" << std::endl;\n    std::cout << \"Reference eigenvalues\" << std::endl;\n    std::cout << lambda_ref.head(neigen) << std::endl;\n    std::cout << \"Davidson eigenvalues\" << std::endl;\n    std::cout << lambda << std::endl;\n    std::cout << \"Residue norms\" << std::endl;\n    std::cout << DS.residues() << std::endl;\n  }\n  BOOST_CHECK_EQUAL(check_eigenvalues, 1);\n\n  Eigen::MatrixXd evect_dav = DS.eigenvectors().real();\n  Eigen::MatrixXd evect = es.eigenvectors().real();\n  Eigen::MatrixXd evect_ref = extract_eigenvectors(evect, idx);\n\n  bool check_eigenvectors =\n      evect_ref.cwiseAbs2().isApprox(evect_dav.cwiseAbs2(), 0.001);\n  BOOST_CHECK_EQUAL(check_eigenvectors, 1);\n}\n\nBOOST_AUTO_TEST_CASE(davidson_hamiltonian_matrix_free_large) {\n\n  Index size = 120;\n  Index neigen = 5;\n  Logger log;\n  // log.setReportLevel(TLogLevel::logDEBUG);\n\n  // Create Operator\n  HermitianBlockOperator Rop;\n  Rop.set_size(size);\n  Eigen::MatrixXd rmat = init_matrix(size, 0.01);\n  Rop.attach_matrix(rmat);\n\n  HermitianBlockOperator Cop;\n  Cop.set_size(size);\n  Eigen::MatrixXd cmat = symm_matrix(size, 0.01);\n  Cop.attach_matrix(cmat);\n\n  // create Hamiltonian operator\n  HamiltonianOperator<HermitianBlockOperator, HermitianBlockOperator> Hop(Rop,\n                                                                          Cop);\n\n  DavidsonSolver DS(log);\n  DS.set_tolerance(\"normal\");\n  DS.set_size_update(\"safe\");\n  DS.set_max_search_space(50);\n  DS.set_matrix_type(\"HAM\");\n  DS.solve(Hop, neigen);\n  std::cout << log;\n  auto lambda = DS.eigenvalues().real();\n  std::sort(lambda.data(), lambda.data() + lambda.size());\n  Eigen::MatrixXd H = Hop.get_full_matrix();\n\n  Eigen::EigenSolver<Eigen::MatrixXd> es(H);\n  Eigen::ArrayXi idx = index_eval(es.eigenvalues().real(), neigen);\n  Eigen::VectorXd lambda_ref = idx.unaryExpr(es.eigenvalues().real());\n\n  bool check_eigenvalues = lambda.isApprox(lambda_ref.head(neigen), 1E-6);\n  if (!check_eigenvalues) {\n    std::cout << \"Davidson not converged after \" << DS.num_iterations()\n              << \" iterations\" << std::endl;\n    std::cout << \"Reference eigenvalues\" << std::endl;\n    std::cout << lambda_ref.head(neigen) << std::endl;\n    std::cout << \"Davidson eigenvalues\" << std::endl;\n    std::cout << lambda << std::endl;\n    std::cout << \"Residue norms\" << std::endl;\n    std::cout << DS.residues() << std::endl;\n  }\n  BOOST_CHECK_EQUAL(check_eigenvalues, 1);\n\n  Eigen::MatrixXd evect_dav = DS.eigenvectors().real();\n  Eigen::MatrixXd evect = es.eigenvectors().real();\n  Eigen::MatrixXd evect_ref = extract_eigenvectors(evect, idx);\n\n  bool check_eigenvectors =\n      evect_ref.cwiseAbs2().isApprox(evect_dav.cwiseAbs2(), 0.001);\n  BOOST_CHECK_EQUAL(check_eigenvectors, 1);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "5b28c8e6f0d2f73b573de8614e399c43c017d01a", "size": 13970, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/tests/test_davidson.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/tests/test_davidson.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/tests/test_davidson.cc", "max_forks_repo_name": "fossabot/xtp", "max_forks_repo_head_hexsha": "e82cc53f23e213d09da15da80ada6e32ac031a07", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4725738397, "max_line_length": 79, "alphanum_fraction": 0.6665712241, "num_tokens": 3905, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.47850573080553893}}
{"text": "#ifndef __TRIANGULATE_HPP\n/**\n * Triangulate\n *\n * Takes a list of polylines and separates them into complex polygons such that\n * no two overlap.  This is equivalent to the 2D arrangement of the input line\n * segments.  Each complex polygon is represented as a list of triangles and a\n * list of poly-lines forming the boundary.  The input polygons can be\n * self-intersecting.\n *\n * The result is computed using the constrained Delaunay triangulation (CDT).\n * To reject the extra triangles created by the CDT, the arrangement of all the\n * input is computed.  Triangles not bounded by this arrangement are rejected.\n * To associate output polygons with input polylines, the arrangement of each\n * input polyline is computed.\n *\n * Input: Polylines as list of points, one polyline per line, separated by\n * whitespace, with an arbitrary ID as the first token, e.g.\n *     0 x1 y1 x2 y2 x3 y3\n *     1 x1 y1 x2 y2 x3 y3 x4 y4 x5 y5\n *     2 x1 y1 x2 y2 x3 y3 x4 y4\n * The id can be anything as long a it does not contain whitespace.  The input\n * may be terminated either with \"END\" on one line or by ending the file.  Any\n * text after \"END\" is ignored.\n *\n * Output: Flattened whitespace-separated list of vertices, triangles, and\n * lines separated by \"|\".  Each complex polygon is on its own line.  The first\n * group on each line is the IDs of the input polygons that contain it, or\n * nothing.\n * Triangles and lines are indices into the list of vertices e.g.\n *     0 | x0 y0 x1 y1 x2 y2 | v0 v1 v2 | v0 v1 v0 v2 v1 v2\n *     1 2 | x0 y0 x1 y1 x2 y2 x3 y3 | v0 v1 v2 v0 v2 v3 | v0 v1 v1 v2 v2 v3 v3 v0\n */\n\n#include <stdexcept>\n#include <iostream>\n#include <fstream>\n#include <boost/algorithm/string.hpp>\n\n#include <CGAL/Exact_predicates_exact_constructions_kernel.h>\n#include <CGAL/intersections.h>\n#include <CGAL/Polygon_2.h>\n\n#include <CGAL/Arr_segment_traits_2.h>\n#include <CGAL/Arr_polyline_traits_2.h>\n#include <CGAL/Arrangement_2.h>\n#include <CGAL/Arr_naive_point_location.h>\n\n#include <CGAL/Constrained_Delaunay_triangulation_2.h>\n#include <CGAL/Constrained_triangulation_plus_2.h>\n\n#include <CGAL/squared_distance_2.h>\n\nusing std::cout;\nusing std::cerr;\nusing std::cin;\nusing std::string;\nusing std::endl;\nusing std::vector;\n\n// Kernel\ntypedef CGAL::Exact_predicates_exact_constructions_kernel K;\ntypedef CGAL::Polygon_2<K> Polygon_2;\n\n// Arrangement\ntypedef CGAL::Arr_segment_traits_2<K>                      Segment_traits_2;\ntypedef CGAL::Arr_polyline_traits_2<Segment_traits_2>      Traits_2;\ntypedef Traits_2::Point_2                                  Point_2;\ntypedef Traits_2::Curve_2                                  Polyline_2;\ntypedef CGAL::Arrangement_2<Traits_2>                      Arrangement_2;\ntypedef CGAL::Arr_naive_point_location<Arrangement_2>      Point_location_2;\ntypedef Arrangement_2::Face_const_handle                   Arr_face_handle_2;\n\n// Triangulations\ntypedef CGAL::Triangulation_vertex_base_2<K>                     Vb;\ntypedef CGAL::Constrained_triangulation_face_base_2<K>           Fb;\ntypedef CGAL::Triangulation_data_structure_2<Vb,Fb>              TDS;\ntypedef CGAL::Exact_intersections_tag                            Itag;\ntypedef CGAL::Constrained_Delaunay_triangulation_2<K, TDS, Itag> CDT_parent;\ntypedef CGAL::Constrained_triangulation_plus_2<CDT_parent>       CDT;\n\n\n// Wrapper class to hold variables\nclass Triangulate {\n\tpublic:\n\t\tvoid load_polylines(std::istream &input);\n\t\tvoid build_triangulation();\n\t\tvoid build_out_triangle_components();\n\t\tvoid print_out_triangle_components();\n\n\tprivate:\n\n\t\t/// INPUT\n\n\t\t// storage for polygon points\n\t\tvector<vector<Point_2> > polyline_points;\n\n\t\t// poly-lines submitted by user\n\t\tvector<Polyline_2> polylines;\n\n\t\t// arrangement of each input polygon (to handle self-intersecting inputs)\n\t\tvector<std::pair<string, Arrangement_2> > poly_arr;\n\n\t\t// arrangement of all polylines\n\t\tArrangement_2 arr;\n\n\t\t// constrained delaunay triangulation (CDT) of all input polyglines\n\t\tCDT cdt;\n\n\t\t// triangles in the CDT\n\t\tvector<CDT::Face_handle> tris;\n\n\t\t// map faces to their index in the list\n\t\tstd::map<CDT::Face_handle, size_t> tri2index;\n\n\t\t// triangle midpoints\n\t\tvector<Point_2> tri_midpoints;\n\n\t\t// output polygons (connected component of triangles) as a list of\n\t\t// triangle indices\n\t\tvector<vector<size_t> > out_triangle_components;\n};\n\ninline bool\narrangement_contains(const Arrangement_2 &arr, const Point_2 &p) {\n\tPoint_location_2 pl(arr);\n\tCGAL::Object obj = pl.locate(p);\n\tArr_face_handle_2 f;\n\treturn (CGAL::assign(f, obj) && !f->is_unbounded());\n}\n\n#define __TRIANGULATE_HPP\n#endif /* __TRIANGULATE_HPP */\n", "meta": {"hexsha": "3ce2793b69d5b7f619631db62d96f55f4355f05f", "size": 4616, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "triangulate/include/triangulate.hpp", "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": "triangulate/include/triangulate.hpp", "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": "triangulate/include/triangulate.hpp", "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": 34.447761194, "max_line_length": 82, "alphanum_fraction": 0.7250866551, "num_tokens": 1286, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.47850573080553893}}
{"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 <ros/ros.h>\n#include <nodelet/nodelet.h>\n#include <message_filters/subscriber.h>\n#include <message_filters/cache.h>\n#include <nav_msgs/Odometry.h>\n#include <pluginlib/class_list_macros.h>\n#include <sensor_msgs/Imu.h>\n#include <Eigen/Dense>\n#include <tuple>\n\nnamespace sdd_vio {\n\nclass ImuIntegrationNodelet : public nodelet::Nodelet\n{\n   private:\n    void onInit(void);\n\n    bool has_received_first_vio_;\n    bool new_odom_available_;  // if true, then a new odom has been received and IMU should re-integrate from that point.\n    ros::Time vio_odom_timestamp_;  // The timestamp of new odom, same as image timestamp\n    double vio_odom_seq_;\n\n    /* the odom from vio, these are with respect to the initial IMU frame */\n    Eigen::Vector3f p_vio_;\n    Eigen::Isometry3f T_vio_;\n    Eigen::Quaternionf q_vio_;\n    Eigen::Vector3f v_vio_;\n\n    /* the actual current state (still relative to the initial IMU frame) that needs to be published */\n    Eigen::Vector3f p_;\n    Eigen::Isometry3f T_;\n    Eigen::Quaternionf q_;\n    Eigen::Vector3f v_;\n\n\n    /* fixed params */\n    Eigen::Isometry3f T_world_imu_;  // transformation between world frame and imu body frame\n    Eigen::Vector3f b_w_;  // gyro bias\n    Eigen::Vector3f b_a_;  // accelerometer bias\n    Eigen::Vector3f g_;  // gravity in initial IMU frame\n\n    ros::Time last_timestamp_;\n\n\n    /* publisher to publish high rate odometry */\n    ros::Publisher pub_odom_;\n    /* subscriber to tightly-coupled vio odometry low frequency output */\n    message_filters::Subscriber<nav_msgs::Odometry> sub_odom_;\n    /* subscriber to IMU messages */\n    message_filters::Subscriber<sensor_msgs::Imu> sub_imu_;\n    /* IMU cache linked to subscriber */\n    message_filters::Cache<sensor_msgs::Imu>* imu_cache_;\n\n    /* publish odom at IMU rate */\n    void imu_callback(const sensor_msgs::Imu::ConstPtr& imu);\n    /* set flag for incoming vio odometry to trigger IMU re-integration */\n    void vio_callback(const nav_msgs::Odometry::ConstPtr& odom);\n    /* integrate IMU from last image pose to current */\n    std::tuple<Eigen::Vector3f, Eigen::Vector3f, Eigen::Quaternionf> imuIntegrate(const std::vector<sensor_msgs::Imu::ConstPtr> &imu_vector) const;\n\n\n};\n\n\nvoid ImuIntegrationNodelet::onInit(void)\n{\n  ros::NodeHandle nh = getPrivateNodeHandle();\n\n  /* initialization */\n  p_vio_.setZero(3);\n  T_vio_.setIdentity();\n  q_vio_.setIdentity();\n  v_vio_.setZero(3);\n\n  p_.setZero(3);\n  T_.setIdentity();\n  q_.setIdentity();\n  v_.setZero(3);\n\n  b_w_.setZero(3);  // imu biases\n  b_a_.setZero(3);\n  g_ << 0,0,9.8;  // gravity\n  T_world_imu_.setIdentity();\n  Eigen::Matrix3f R_world_imu;\n  R_world_imu << 1,0,0,\n                0,-1,0,\n                0,0,-1;\n  T_world_imu_.linear() = R_world_imu;\n\n  //std::cout<<\"isometry T_: \"<<T_.matrix()<<\"\\n\";\n  //std::cout<<\"isometry T_world_imu_: \"<<T_world_imu_.matrix()<<\"\\n\";\n\n  last_timestamp_ = ros::Time::now();\n\n  new_odom_available_ = false;\n  has_received_first_vio_ = false;\n\n  /* initialize publisher */\n  pub_odom_ = nh.advertise<nav_msgs::Odometry>(\"odom\", 100);\n  /* initialize vio odom subscriber */\n  sub_odom_.subscribe(nh, \"odom_topic\", 100, ros::TransportHints().tcpNoDelay());\n  sub_odom_.registerCallback(boost::bind(&ImuIntegrationNodelet::vio_callback, this, _1));\n  /* initialize imu subscriber and cache callback */\n  sub_imu_.subscribe(nh, \"imu_topic\", 500, ros::TransportHints().tcpNoDelay());\n  imu_cache_ = new message_filters::Cache<sensor_msgs::Imu>(sub_imu_,500);\n  imu_cache_->registerCallback(boost::bind(&ImuIntegrationNodelet::imu_callback, this, _1));\n\n}\n\n\n/* upon receiving an odom message, save the timestamp and odom info, set flag */\nvoid ImuIntegrationNodelet::vio_callback(const nav_msgs::Odometry::ConstPtr &odom)\n{\n\n    new_odom_available_ = true;\n    has_received_first_vio_ = true;\n    vio_odom_timestamp_ = odom->header.stamp;\n    vio_odom_seq_ = odom->header.seq;\n\n    p_vio_(0) = odom->pose.pose.position.x;\n    p_vio_(1) = odom->pose.pose.position.y;\n    p_vio_(2) = odom->pose.pose.position.z;\n\n    q_vio_.x() = odom->pose.pose.orientation.x;\n    q_vio_.y() = odom->pose.pose.orientation.y;\n    q_vio_.z() = odom->pose.pose.orientation.z;\n    q_vio_.w() = odom->pose.pose.orientation.w;\n\n    T_vio_.linear() = q_vio_.toRotationMatrix();\n    T_vio_.translation() = p_vio_;\n\n    v_vio_(0) = odom->twist.twist.linear.x;\n    v_vio_(1) = odom->twist.twist.linear.y;\n    v_vio_(2) = odom->twist.twist.linear.z;\n\n}\n\nvoid ImuIntegrationNodelet::imu_callback(const sensor_msgs::Imu::ConstPtr &imu)\n{\n\n    ros::Time current_timestamp = imu->header.stamp;\n\n\n    /* raw observation */\n    Eigen::Vector3f w, a;\n    w(0) = imu->angular_velocity.x;\n    w(1) = imu->angular_velocity.y;\n    w(2) = imu->angular_velocity.z;\n    a(0) = imu->linear_acceleration.x;\n    a(1) = imu->linear_acceleration.y;\n    a(2) = imu->linear_acceleration.z;\n\n    /* Calibration of IMU */\n    static const int total_num = 300;\n    static int data_i = 0;  // the number of data processed\n    static float w1 = 0, w2 = 0, w3 = 0, a1 = 0, a2 = 0, a3 = 0;\n    if (data_i < total_num)  // take first 300 data - for calibration on bias\n    {\n        ROS_INFO(\"ImuIntegration nodelet - Imu Seq: [%d]\", imu->header.seq);\n        w1 += w(0);\n        w2 += w(1);\n        w3 += w(2);\n        a1 += a(0) + g_(0);\n        a2 += a(1) + g_(1);\n        a3 += a(2) + g_(2);\n\n        if (data_i == total_num-1)  // the last date collected for calibration\n        {\n            Eigen::Vector3f w_b(w1/total_num, w2/total_num, w3/total_num), a_b(a1/total_num, a2/total_num, a3/total_num);\n            b_w_ = w_b;\n            //b_a_ = a_b;\n            std::cout<<\"calibrated gyro bias: \\n\"<<w_b<<\"\\n\";\n            std::cout<<\"calibrated accel bias: \\n\"<<a_b<<\"\\n\";\n//            throw std::runtime_error(\"Calibration done!\");\n        }\n        data_i++;\n    }\n\n\n    if (new_odom_available_)\n    {\n        //std::cout<<\"Received new odom from VIO! Getting imu data vector from buffer: \\n\";\n        //std::cout<<\"vio_odom_timestamp: \"<<vio_odom_timestamp_<<\"\\n\";\n        //std::cout<<\"current_timestamp: \"<<current_timestamp<<\"\\n\";\n        std::vector<sensor_msgs::Imu::ConstPtr> imu_vector = imu_cache_->getInterval(vio_odom_timestamp_, current_timestamp);\n        if (imu_vector.size() == 0)\n          ROS_WARN_STREAM(\"Fail to retrieve IMU data between current frame and last frame.\");\n        std::tie(p_, v_, q_) = imuIntegrate(imu_vector);\n        new_odom_available_ = false;\n\n    }\n\n    if (data_i != 1 && has_received_first_vio_)  // if not the first IMU data\n    {\n      /* getting current odometry in initial IMU frame */\n      Eigen::Vector3f w_mBias = w - b_w_;\n      Eigen::Vector3f a_mBias = a - b_a_;\n      float delta_t = (current_timestamp - last_timestamp_).toSec();\n\n      /* increment T_pub by one IMU measurement */\n      Eigen::AngleAxisf aa_inc(w_mBias.norm() * delta_t, w_mBias.normalized());\n      p_ = p_ + v_*delta_t + 0.5*g_*delta_t*delta_t + 0.5*q_.toRotationMatrix()*(a_mBias*delta_t*delta_t);\n      v_ = v_ + g_*delta_t + q_.toRotationMatrix()*(a_mBias*delta_t);\n      q_ = q_ * aa_inc;\n\n      T_.linear() = q_.toRotationMatrix();\n      T_.translation() = p_;\n    }\n\n    last_timestamp_ = current_timestamp;\n\n\n    /* transform to world frame */\n    Eigen::Isometry3f T_pub = T_world_imu_ * T_ * T_world_imu_.inverse();\n    Eigen::Vector3f v_pub = T_world_imu_ * v_;\n    Eigen::Quaternionf q_pub(T_pub.rotation());\n    Eigen::Vector3f p_pub = T_pub.translation();\n\n    /* publish odometry */\n    nav_msgs::Odometry odom;\n    std_msgs::Header header_msg;\n    header_msg.frame_id = \"world\";\n    header_msg.stamp = imu->header.stamp;  // use original imu message's header\n    header_msg.seq = imu->header.seq;\n    /* prepare cam msg to publish */\n    odom.header = header_msg;\n    odom.pose.pose.position.x = p_pub(0);\n    odom.pose.pose.position.y = p_pub(1);\n    odom.pose.pose.position.z = p_pub(2);\n    odom.pose.pose.orientation.x = q_pub.x();\n    odom.pose.pose.orientation.y = q_pub.y();\n    odom.pose.pose.orientation.z = q_pub.z();\n    odom.pose.pose.orientation.w = q_pub.w();\n    odom.twist.twist.linear.x = v_pub(0);\n    odom.twist.twist.linear.y = v_pub(1);\n    odom.twist.twist.linear.z = v_pub(2);\n    pub_odom_.publish(odom);\n\n\n}\n\n\nstd::tuple<Eigen::Vector3f, Eigen::Vector3f, Eigen::Quaternionf> ImuIntegrationNodelet::imuIntegrate(const std::vector<sensor_msgs::Imu::ConstPtr>& imu_vector) const\n{\n\n    int num_measurement = imu_vector.size();\n    Eigen::Vector3f v_proc = v_vio_;  // states during integration process\n    Eigen::Vector3f p_proc = p_vio_;\n    Eigen::Quaternionf q_proc = q_vio_;\n\n    // not to use the last element\n    for (int i=0;i<num_measurement-1;i++)\n    {\n        //std::cout<<\"measurement \"<<i<<\": \\n\";\n        Eigen::Vector3f w(imu_vector[i]->angular_velocity.x,\n                          imu_vector[i]->angular_velocity.y,\n                          imu_vector[i]->angular_velocity.z);  // angular velocity\n        Eigen::Vector3f a(imu_vector[i]->linear_acceleration.x,\n                          imu_vector[i]->linear_acceleration.y,\n                          imu_vector[i]->linear_acceleration.z);  // linear acceleration\n        /* remove bias */\n        w = w - b_w_;\n        a = a - b_a_;\n        /* obtain delta t */\n        const float delta_t = (imu_vector[i+1]->header.stamp - imu_vector[i]->header.stamp).toSec();\n\n        /* update state */\n        const Eigen::AngleAxisf aa_inc(w.norm() * delta_t, w.normalized());\n        const Eigen::Quaternionf q_inc(aa_inc);\n        p_proc = p_proc + v_proc*delta_t + 0.5*g_*delta_t*delta_t + 0.5*q_proc.toRotationMatrix()*(a*delta_t*delta_t);\n        v_proc = v_proc + g_*delta_t + q_proc.toRotationMatrix()*(a*delta_t);\n        q_proc = q_proc * q_inc;\n    }\n\n    return std::make_tuple(p_proc, v_proc, q_proc);\n}\n\n\n\n}\n\nPLUGINLIB_EXPORT_CLASS(sdd_vio::ImuIntegrationNodelet, nodelet::Nodelet);\n", "meta": {"hexsha": "00cb41b4835a6da9cacf861e55052ac407eeae05", "size": 10617, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/imu_integration_nodelet.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/imu_integration_nodelet.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/imu_integration_nodelet.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": 35.508361204, "max_line_length": 165, "alphanum_fraction": 0.6543279646, "num_tokens": 2952, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.47850573080553893}}
{"text": "//\n// Copyright 2013 Krzysztof Czainski\n// Copyright 2020 Mateusz Loskot <mateusz at loskot dot net>\n//\n// Distributed under the Boost Software License, Version 1.0\n// See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt\n//\n#include <boost/gil.hpp>\n#include <boost/gil/extension/numeric/resample.hpp>\n#include <boost/gil/extension/numeric/sampler.hpp>\n\n#include <boost/core/lightweight_test.hpp>\n\n#include <cmath>\n\nnamespace gil = boost::gil;\n\n// FIXME: Remove when https://github.com/boostorg/core/issues/38 happens\n#define BOOST_GIL_TEST_IS_CLOSE(a, b, epsilon) BOOST_TEST(std::abs((a) - (b)) < (epsilon))\n\ntemplate <class F, class I>\nstruct test_map_fn\n{\n    using point_t = gil::point<F>;\n    using result_type = point_t;\n    result_type operator()(gil::point<I> const &src) const\n    {\n        F x = static_cast<F>(src.x) - 0.5;\n        F y = static_cast<F>(src.y) - 0.5;\n        return {x, y};\n    }\n};\n\nnamespace boost { namespace gil {\n\n// NOTE: I suggest this could be the default behavior:\n\ntemplate <typename T>\nstruct mapping_traits;\n\ntemplate <class F, class I>\nstruct mapping_traits<test_map_fn<F, I>>\n{\n    using result_type = typename test_map_fn<F, I>::result_type;\n};\n\ntemplate <class F, class I>\ninline point<F> transform(test_map_fn<F, I> const &mf, point<I> const &src)\n{\n    return mf(src);\n}\n\n}} // namespace boost::gil\n\nvoid test_bilinear_sampler_test()\n{\n    // R G B\n    // G W R\n    // B R G\n    gil::rgb8_image_t img(3, 3);\n    gil::rgb8_view_t v = view(img);\n    v(0, 0) = v(1, 2) = v(2, 1) = gil::rgb8_pixel_t(128, 0, 0);\n    v(0, 1) = v(1, 0) = v(2, 2) = gil::rgb8_pixel_t(0, 128, 0);\n    v(0, 2) = v(2, 0) = gil::rgb8_pixel_t(0, 0, 128);\n    v(1, 1) = gil::rgb8_pixel_t(128, 128, 128);\n\n    gil::rgb8_image_t dims(4, 4);\n    gil::rgb8c_view_t dv = gil::const_view(dims);\n\n    test_map_fn<double, gil::rgb8_image_t::coord_t> mf;\n\n    gil::resample_pixels(gil::const_view(img), gil::view(dims), mf, gil::bilinear_sampler());\n\n    BOOST_TEST(gil::rgb8_pixel_t(128, 0, 0) == dv(0, 0));\n    BOOST_TEST(gil::rgb8_pixel_t(64, 64, 0) == dv(0, 1));\n    BOOST_TEST(gil::rgb8_pixel_t(0, 64, 64) == dv(0, 2));\n    BOOST_TEST(gil::rgb8_pixel_t(0, 0, 128) == dv(0, 3));\n\n    BOOST_TEST(gil::rgb8_pixel_t(64, 64, 0) == dv(1, 0));\n    BOOST_TEST(gil::rgb8_pixel_t(64, 96, 32) == dv(1, 1));\n    BOOST_TEST(gil::rgb8_pixel_t(64, 64, 64) == dv(1, 2));\n    BOOST_TEST(gil::rgb8_pixel_t(64, 0, 64) == dv(1, 3));\n\n    BOOST_TEST(gil::rgb8_pixel_t(0, 64, 64) == dv(2, 0));\n    BOOST_TEST(gil::rgb8_pixel_t(64, 64, 64) == dv(2, 1));\n    BOOST_TEST(gil::rgb8_pixel_t(96, 64, 32) == dv(2, 2));\n    BOOST_TEST(gil::rgb8_pixel_t(64, 64, 0) == dv(2, 3));\n\n    BOOST_TEST(gil::rgb8_pixel_t(0, 0, 128) == dv(3, 0));\n    BOOST_TEST(gil::rgb8_pixel_t(64, 0, 64) == dv(3, 1));\n    BOOST_TEST(gil::rgb8_pixel_t(64, 64, 0) == dv(3, 2));\n    BOOST_TEST(gil::rgb8_pixel_t(0, 128, 0) == dv(3, 3));\n}\n\nint main()\n{\n    test_bilinear_sampler_test();\n\n    return ::boost::report_errors();\n}\n", "meta": {"hexsha": "db1dac9c7e7ee08d713d9844329faa8172826fe1", "size": 3017, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/extension/numeric/resample.cpp", "max_stars_repo_name": "martin-carrasco/gil", "max_stars_repo_head_hexsha": "fc7900f40201080cf8081128df74299b80c2c227", "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": "test/extension/numeric/resample.cpp", "max_issues_repo_name": "martin-carrasco/gil", "max_issues_repo_head_hexsha": "fc7900f40201080cf8081128df74299b80c2c227", "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/extension/numeric/resample.cpp", "max_forks_repo_name": "martin-carrasco/gil", "max_forks_repo_head_hexsha": "fc7900f40201080cf8081128df74299b80c2c227", "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.5784313725, "max_line_length": 93, "alphanum_fraction": 0.6360623136, "num_tokens": 1115, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529376, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.47850573080553893}}
{"text": "//\n//  GPUTSDFVolume.hpp\n//  A GPU Based TSDF\n//\n//  Created by Dave on 11/03/2016.\n//  Copyright \u00a9 2016 Sindesso. All rights reserved.\n//\n\n#ifndef TSDFVolumeCPU_hpp\n#define TSDFVolumeCPU_hpp\n\n#include \"Camera.hpp\"\n\n//#include <Eigen/Core>\n\n#include <cstdint>\n#include <iostream>\n#include <string>\n#include <cmath>\n\n\ntypedef struct {\n    float m11, m21, m31, m41;\n    float m12, m22, m32, m42;\n    float m13, m23, m33, m43;\n    float m14, m24, m34, m44;\n} Mat44CPU;\n\ntypedef struct {\n    float m11, m21, m31;\n    float m12, m22, m32;\n    float m13, m23, m33;\n} Mat33CPU;\n\nstruct float3cpu {\n    float x, y, z;\n};\n\nstruct int3cpu {\n    int x, y, z;\n};\n\nstruct dim3cpu {\n    unsigned int x, y, z;\n};\n\nstruct uchar3cpu {\n    unsigned char x, y, z;\n};\n\ninline float f3_dot(const float3cpu& f1, const float3cpu& f2) {\n    return f1.x * f2.x + f1.y * f2.y + f1.z * f2.z;\n}\n\n/**\n * Subtract one float3 from another\n * @param f1 First float3\n * @param f2 Second float3\n * @return f1 - f2\n */\ninline float3cpu f3_sub( const float3cpu& f1, const float3cpu& f2 ) {\n    float3cpu f{f1.x-f2.x, f1.y-f2.y, f1.z-f2.z};\n    return f;\n}\n\n/**\n * Add one float3 to another\n * @param f1 First float3\n * @param f2 Second float3\n * @return f1 + f2\n */\ninline float3cpu f3_add( const float3cpu& f1, const float3cpu& f2 ) {\n    float3cpu f{f2.x+f1.x, f2.y+f1.y, f2.z+f1.z};\n    return f;\n}\n\n/**\n * Multiply a float3 by a scalar value\n * @param s The scalar\n * @param vec The float3\n */\ninline float3cpu f3_mul_scalar( const float& scalar, const float3cpu& vec ) {\n    float3cpu f{vec.x * scalar, vec.y * scalar, vec.z * scalar};\n    return f;\n}\n\n\n/**\n * Perform per element division of f1 by v2\n * @param f1 the first float3 (numerators)\n * @param f2 The second float3 (denominators)\n * @return f1 ./ f2\n */\ninline float3cpu f3_div_elem(const float3cpu& f1, const float3cpu& f2 ) {\n    float3cpu f{f1.x/f2.x, f1.y/f2.y, f1.z/f2.z};\n    return f;\n}\n\n/**\n * Perform per element division of f1 by v2\n * @param f1 the first float3 (numerators)\n * @param i2 The second float3 (denominators)\n * @return f1 ./ f2\n */\ninline float3cpu f3_div_elem( const float3cpu& f, const dim3cpu& i ) {\n    float3cpu ff{f.x/i.x, f.y/i.y, f.z/i.z};\n    return ff;\n}\n\n/**\n * Normalise a float3\n * @param vec The float3 vector\n */\ninline float3cpu f3_normalise(float3cpu vec) {\n    float l = sqrt( vec.x*vec.x+vec.y*vec.y+vec.z*vec.z);\n    vec.x /= l;\n    vec.y /= l;\n    vec.z /= l;\n    return vec;\n}\n\n/**\n * Normalise a float3\n * @param vec The float3 vector\n */\ninline float f3_norm( float3cpu vec ) {\n    return sqrt(vec.x*vec.x+vec.y*vec.y+vec.z*vec.z);\n}\n\n/**\n * Perform a matrix multiplication\n * @param mat33 The matrix\n * @param vec3 The vector\n * @return an output vector\n */\ninline float3cpu m3_f3_mul( const Mat33CPU& mat, const float3cpu& vec ) {\n    float3cpu result;\n    result.x = mat.m11 * vec.x + mat.m12 * vec.y + mat.m13 * vec.z;\n    result.y = mat.m21 * vec.x + mat.m22 * vec.y + mat.m23 * vec.z;\n    result.z = mat.m31 * vec.x + mat.m32 * vec.y + mat.m33 * vec.z;\n    return result;\n}\n\n/**\n * Perform a matrix multiplication\n * @param mat33 The matrix\n * @param vec3 The vector\n * @return an output vector\n */\ninline float3cpu m3_i3_mul( const Mat33CPU& mat, const int3cpu& vec ) {\n    float3cpu result;\n    result.x = mat.m11 * vec.x + mat.m12 * vec.y + mat.m13 * vec.z;\n    result.y = mat.m21 * vec.x + mat.m22 * vec.y + mat.m23 * vec.z;\n    result.z = mat.m31 * vec.x + mat.m32 * vec.y + mat.m33 * vec.z;\n    return result;\n}\n\n/**\n * Project down into pixel coordinates\n * given the inv_pose and K matrices\n * plus a point in world coords\n */\ninline int3cpu world_to_pixel( const Mat44CPU & inv_pose, const Mat33CPU& k, const float3cpu& point ) {\n    float3cpu cam_point;\n    cam_point.x = inv_pose.m11 * point.x + inv_pose.m12 * point.y + inv_pose.m13 * point.z + inv_pose.m14;\n    cam_point.y = inv_pose.m21 * point.x + inv_pose.m22 * point.y + inv_pose.m23 * point.z + inv_pose.m24;\n    cam_point.z = inv_pose.m31 * point.x + inv_pose.m32 * point.y + inv_pose.m33 * point.z + inv_pose.m34;\n    float w = inv_pose.m41 * point.x + inv_pose.m42 * point.y + inv_pose.m43 * point.z + inv_pose.m44;\n    cam_point.x /= w;\n    cam_point.y /= w;\n    cam_point.z /= w;\n\n    float3cpu image_point {cam_point.x / cam_point.z, cam_point.y / cam_point.z, 1.0f};\n    int3cpu pixel;\n    pixel.x = static_cast<uint>( round( k.m11 * image_point.y + k.m12 * image_point.z + k.m13 ) );\n    pixel.y = static_cast<uint>( round( k.m21 * image_point.y + k.m22 * image_point.z + k.m23 ) );\n    pixel.z = static_cast<uint>( round( k.m31 * image_point.y + k.m32 * image_point.z + k.m33 ) ); // Should be 1\n\n    return pixel;\n}\n\nclass TSDFVolumeCPU {\npublic:\n    struct DeformationNode {\n        float3cpu  translation;\n        float3cpu  rotation;\n    };\n\n    struct Float3 {\n        float x;\n        float y;\n        float z;\n        inline Float3( const float3cpu& rhs ) {\n            x = rhs.x;\n            y = rhs.y;\n            z = rhs.z;\n        }\n        inline Float3( float fx=0.0f, float fy=0.0f, float fz=0.0f ) {\n            x = fx;\n            y = fy;\n            z = fz;\n        }\n        inline operator float3cpu() const {return float3cpu{x, y, z}; }\n\n        inline Float3 operator -( const Float3& rhs ) const {\n            return float3cpu{x - rhs.x, y - rhs.y, z - rhs.z};\n        }\n        inline Float3 operator +( const Float3& rhs ) const {\n            return float3cpu{x + rhs.x, y + rhs.y, z + rhs.z};\n        }\n        inline Float3 operator /( const float scalar ) const {\n            return float3cpu{x / scalar, y / scalar, z / scalar};\n        }\n        inline Float3 operator *( const Float3& rhs ) const {\n            return float3cpu{x * rhs.x, y * rhs.y, z * rhs.z};\n        }\n        inline float norm( ) const {\n            return std::sqrt( x*x + y*y + z*z );\n        }\n\n    };\n\n    struct Int3 {\n        int16_t x;\n        int16_t y;\n        int16_t z;\n    };\n\n    struct  UInt3 {\n        unsigned int x;\n        unsigned int y;\n        unsigned int z;\n\n        inline UInt3( const dim3cpu& rhs ) : x{rhs.x}, y{rhs.y}, z{rhs.z} {};\n        inline UInt3( uint32_t x, uint32_t y, uint32_t z ) : x{x}, y{y}, z{z} {};\n        inline operator dim3cpu() const {return dim3cpu{x, y, z}; }\n    };\n\n    ~TSDFVolumeCPU();\n\n    /**\n    * Make a TSDFVolume with the given dimensions (voxels) and physcial dimensions\n    * @param size The number of voxels in each X,Y and Z dimension\n    * @param physical_size The size ( in mm ) of the space contained in the volume\n    */\n    TSDFVolumeCPU( const UInt3& size = UInt3{64, 64, 64},\n                const Float3& physical_size = Float3 { 3000.0f, 3000.0f, 3000.0f} );\n\n\n    /**\n     * Make a TSDFVolume with the given dimensins and physical dimensions\n     * @param volume_x X dimension in voxels\n     * @param volume_y Y dimension in voxels\n     * @param volume_z Z dimension in voxels\n     * @param psize_x Physical size in X dimension in mm\n     * @param psize_y Physical size in Y dimension in mm\n     * @param psize_z Physical size in Z dimension in mm\n     */\n    TSDFVolumeCPU( uint16_t volume_x, uint16_t volume_y, uint16_t volume_z, float psize_x, float psize_y, float psize_z );\n\n    /**\n     * Load a TSDFVolume from the specified file. The volume must previously have been saved\n     */\n    TSDFVolumeCPU( const std::string& file_name );\n\n    /**\n     * Set the size of the volume. This will delete any existing values and resize the volume, clearing it when done.\n     * Volume offset is maintained\n     * @param volume_x X dimension in voxels\n     * @param volume_y Y dimension in voxels\n     * @param volume_z Z dimension in voxels\n     * @param psize_x Physical size in X dimension in mm\n     * @param psize_y Physical size in Y dimension in mm\n     * @param psize_z Physical size in Z dimension in mm\n     */\n    void set_size( uint16_t volume_x, uint16_t volume_y, uint16_t volume_z, float psize_x, float psize_y, float psize_z);\n\n    void set_truncation_distance(float d);\n\n    /**\n     * @return the size of this space in voxels.\n     */\n    inline UInt3 size( ) const { return (UInt3) m_size; }\n\n    /**\n     * @return the dimensions of each voxel in mm\n     */\n    inline Float3 voxel_size( ) const { return (Float3) m_voxel_size; }\n\n    /**\n     * @return the physical size of the volume in world coords (mm)\n     */\n    inline Float3 physical_size( ) const { return (Float3) m_physical_size; }\n\n    /**\n     * @return the truncation distance (mm)\n     */\n    inline float truncation_distance( ) const { return m_truncation_distance; }\n\n    /**\n     * Offset the TSDF volume in space by the given offset. By default, the bottom, left, front corner of\n     * voxel (0,0,0) is at world coordinate (0,0,0). This moves that point to the new world coordinate by a\n     * @param ox X offset in mm\n     * @param oy Y offset in mm\n     * @param oz Z offset in mm\n     */\n    inline void offset( float ox, float oy, float oz ) {\n        m_offset.x = ox;\n        m_offset.y = oy;\n        m_offset.z = oz;\n    }\n\n    /**\n     * @return the offset f the TSDF volume in space\n     */\n    inline Float3 offset( ) const { return (Float3) m_offset; }\n\n    /**\n     * Clear the voxel and weight data\n     */\n    void clear( );\n\n#pragma mark - Data access\n\n /**\n     *\n     */\n    inline size_t index( int x, int y, int z ) const {\n        return x + (y * m_size.x) + (z * m_size.x * m_size.y);\n    };\n\n    /**\n     * @return pointer to translation data\n     */\n    inline DeformationNode *  deformation() const {\n        return m_deformation_nodes;\n    }\n\n    /**\n     * Set the deformation data for this space\n     * @param data Data in host memory space; Assumed to be vx*vy*vz DeformationNode\n     */\n    void set_deformation( DeformationNode *deformation);\n\n    /**\n     * Return pointer to distance data\n     * @return Pointer to distance data\n     */\n    inline const float * distance_data() const {\n        return m_distances;\n    }\n\n    /**\n     * Set the distance data for the TSDF in one call\n     * @param distance_data Pointer to enough floats to populate the TSFD\n     */\n    void set_distance_data(float * distance_data);\n\n\n    /**\n     * Return pointer to weight data\n     * @return Pointer to weight data\n     */\n    inline const float * weight_data() const {\n        return m_weights;\n    }\n\n    /**\n     * Set the weight data for the TSDF in one call\n     * @param weight_data Pointer to enough floats to populate the TSFD\n     */\n    void set_weight_data( const float * weight_data );\n\n\n    /**\n     * @return the global rotation of the TSDF deformation \n     * as a vector of 3 Euler angles (X then Y then Z - also Tait-Bryan angles)\n     */\n    inline float3cpu global_rotation( ) const {\n        return m_global_rotation;\n    }\n\n    /**\n     * @return the global translation of the TSDF deformation \n     */\n    inline float3cpu global_translation( ) const {\n        return m_global_translation;\n    }\n\n\n#pragma mark - Deform a set of points\n    /**\n     * Apply the volume's deformation field t the given set of points, modifying them in place\n     */\n    void deform_mesh( const int num_points, float3cpu * points ) const;\n\n#pragma mark - Integrate new depth data\n    /**\n     * Integrate a range map into the TSDF\n     * @param depth_map Pointer to width*height depth values where 0 is an invalid depth and positive values are expressed in mm\n     * @param width The horiontal dimension of the depth_map\n     * @param height The height of the depth_map\n     * @param camera The camera from which the depth_map was taken\n     */\n    void integrate( const uint16_t * depth_map, uint32_t width, uint32_t height, const Camera & camera );\n\n#pragma mark - Import/Export\n\n    /**\n     * Save the TSDF to file\n     * @param The filename\n     * @return true if the file saved OK otherwise false.\n     */\n    bool save_to_file( const std::string & file_name) const;\n\n    /**\n     * Load the given TSDF file\n     * @param The filename\n     * @return true if the file saved OK otherwise false.\n     */\n    bool load_from_file( const std::string & file_name);\n\n#pragma mark - Rendering\n    void raycast( uint16_t width, uint16_t height, const Camera& camera, Eigen::Matrix<float, 3, Eigen::Dynamic>& vertices, Eigen::Matrix<float, 3, Eigen::Dynamic>& normals ) const ;\n\nprivate:\n    /**\n     * Deallocate storage for this TSDF\n     */\n    void deallocate( );\n\n    // Size of voxel grid\n    dim3cpu                    m_size;\n\n    // Physical size of space represented in mm\n    float3cpu                  m_physical_size;\n\n    // Offset of physical grid in world coordinates\n    float3cpu                  m_offset;\n\n    // Size of a voxel\n    float3cpu m_voxel_size;\n\n    //  Truncation distance\n    float m_truncation_distance;\n\n    // Max weight for a voxel\n    float m_max_weight;\n\n    // Per grid point data\n    float                   *m_distances;\n\n    // Colour data, RGB as 3xuchar\n    uchar3cpu                  *m_colours;\n\n    //  Confidence weight for distance and colour\n    float                   *m_weights;\n\n    // Deformation field\n    DeformationNode         *m_deformation_nodes;\n\n    // Global translation\n    float3cpu                  m_global_translation;\n\n    // Global rotation\n    float3cpu                  m_global_rotation;\n};\n#endif /* TSDFVolumeCPU_hpp */\n", "meta": {"hexsha": "b7eaa0094f2be1622a455764790eb0bc20066011", "size": 13334, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/TSDFVolumeCPU.hpp", "max_stars_repo_name": "justanhduc/ray-casting", "max_stars_repo_head_hexsha": "25ea97f3ff10d2b0cb3c9e935f1adb9201e42908", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-08T22:38:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-08T22:38:06.000Z", "max_issues_repo_path": "include/TSDFVolumeCPU.hpp", "max_issues_repo_name": "justanhduc/ray-casting", "max_issues_repo_head_hexsha": "25ea97f3ff10d2b0cb3c9e935f1adb9201e42908", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-04-12T02:19:00.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-26T02:46:41.000Z", "max_forks_repo_path": "include/TSDFVolumeCPU.hpp", "max_forks_repo_name": "justanhduc/ray-casting", "max_forks_repo_head_hexsha": "25ea97f3ff10d2b0cb3c9e935f1adb9201e42908", "max_forks_repo_licenses": ["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.4307036247, "max_line_length": 182, "alphanum_fraction": 0.6205939703, "num_tokens": 3745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.47850573080553893}}
{"text": "/*\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\nCopyright (c) 2019 Panda Team\n*/\n#ifndef _METRIC_DISTANCE_K_RANDOM_VOI_CPP\n#define _METRIC_DISTANCE_K_RANDOM_VOI_CPP\n\n#include <algorithm>\n#include <cmath>\n#include <iostream>\n#include <random>\n#include <unordered_set>\n#include <vector>\n\n#include <boost/functional/hash.hpp>\n\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/special_functions/digamma.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n\n#include \"../../space/tree.hpp\"\n#include \"VOI.hpp\"\n\nnamespace metric {\n\nnamespace {\n    template <typename T>\n    void add_noise(std::vector<std::vector<T>>& data)\n    {\n        std::random_device rd;\n        std::mt19937 gen(rd());\n        std::normal_distribution<T> dis(0, 1);\n        double c = 1e-10;\n        for (auto& v : data) {\n            std::transform(v.begin(), v.end(), v.begin(), [&gen, c, &dis](T e) {\n                auto g = dis(gen);\n                auto k = e + c * g;\n                return k;\n            });\n        }\n    }\n\n    template <typename T1, typename T2>\n    T1 log(T1 logbase, T2 x)\n    {\n        return std::log(x) / std::log(logbase);\n    }\n\n    template <typename T>\n    void print_vec(const std::vector<T>& v)\n    {\n        std::cout << \"[\";\n        for (auto d : v) {\n            std::cout << d << \", \";\n        }\n        std::cout << \"]\";\n    }\n\n    template <typename Node_ptr, typename Distance>\n    void print(const std::vector<std::pair<Node_ptr, Distance>>& data)\n    {\n        std::cout << \"[\";\n        for (auto& v : data) {\n            print_vec(v.first->data);\n            std::cout << \" dist=\" << v.second << \"]\";\n        }\n        std::cout << \"]\" << std::endl;\n    }\n    template <typename T>\n    void combine(\n        const std::vector<std::vector<T>>& X, const std::vector<std::vector<T>>& Y, std::vector<std::vector<T>>& XY)\n    {\n        std::size_t N = X.size();\n        std::size_t dx = X[0].size();\n        std::size_t dy = Y[0].size();\n        XY.resize(N);\n        for (std::size_t i = 0; i < N; i++) {\n            XY[i].resize(dx + dy);\n            std::size_t k = 0;\n            for (std::size_t j = 0; j < dx; j++, k++) {\n                XY[i][k] = X[i][j];\n            }\n            for (std::size_t j = 0; j < dy; j++, k++) {\n                XY[i][k] = Y[i][j];\n            }\n        }\n    }\n    template <typename T>\n    std::vector<T> unique(const std::vector<T>& data)\n    {\n        std::unordered_set<std::size_t> hashes;\n        std::vector<T> result;\n        result.reserve(data.size());\n        std::copy_if(data.begin(), data.end(), std::back_inserter(result),\n            [&hashes](const T& i) { return hashes.insert(boost::hash_value(i)).second; });\n        return result;\n    }\n\n}  // namespace\n\ntemplate <typename T, typename Metric, typename L>\ntypename std::enable_if<!std::is_integral<T>::value, T>::type entropy(\n    std::vector<std::vector<T>> data, std::size_t k, L logbase, Metric metric)\n{\n    if (data.empty() || data[0].empty()) {\n        return 0;\n    }\n    if (data.size() < k + 1)\n        throw std::invalid_argument(\"number of points in dataset must be larger than k\");\n\n    T p = 1;\n    T N = data.size();\n    T d = data[0].size();\n    T two = 2.0;  // this is in order to make types match the log template function\n    T cb = d * log(logbase, two);\n\n    if constexpr (!std::is_same<Metric, typename metric::Chebyshev<T>>::value) {\n        if constexpr (std::is_same<Metric, typename metric::Euclidian<T>>::value) {\n            p = 2;\n        } else if constexpr (std::is_same<Metric, typename metric::P_norm<T>>::value) {\n            p = metric.p;\n        }\n        cb = cb + d * log(logbase, std::tgamma(1 + 1 / p)) - log(logbase, std::tgamma(1 + d / p));\n    }\n\n    add_noise(data);\n    metric::Tree<std::vector<T>, Metric> tree(data, -1, metric);\n    T entropyEstimate = boost::math::digamma(N) - boost::math::digamma(k) + cb + d * log(logbase, two);\n    for (std::size_t i = 0; i < N; i++) {\n        auto res = tree.knn(data[i], k + 1);\n        entropyEstimate += d / N * log(logbase, res.back().second);\n    }\n    return entropyEstimate;\n}\n\n// Kozachenko-Leonenko estimator based on https://hal.archives-ouvertes.fr/hal-00331300/document (Shannon diff. entropy,\n// q = 1)\n\ntemplate <typename T, typename Metric = metric::Euclidian<T>, typename L = T>  // TODO check if L = T is correct\ntypename std::enable_if<!std::is_integral<T>::value, T>::type entropy_kl(\n    std::vector<std::vector<T>> data, std::size_t k = 3, L logbase = 2, Metric metric = Metric())\n{\n    if (data.empty() || data[0].empty())\n        return 0;\n    if (data.size() < k + 1)\n        throw std::invalid_argument(\"number of points in dataset must be larger than k\");\n    if constexpr (!std::is_same<Metric, typename metric::Euclidian<T>>::value)\n        throw std::logic_error(\"entropy function is now implemented only for Euclidean distance\");\n\n    metric::Tree<std::vector<T>, Metric> tree(data, -1, metric);\n\n    size_t N = data.size();\n    size_t m = data[0].size();\n    T two = 2.0;  // this is in order to make types match the log template function\n    T sum = 0;\n    auto Pi = boost::math::constants::pi<T>();\n    T half_m = m / two;\n    auto coeff = (N - 1) * exp(-boost::math::digamma(k + 1)) * std::pow(Pi, half_m) / boost::math::tgamma(half_m + 1);\n\n    for (std::size_t i = 0; i < N; i++) {\n        auto neighbors = tree.knn(data[i], k + 1);\n        auto ro = neighbors.back().second;\n        sum = sum + log(logbase, coeff * std::pow(ro, m));\n    }\n\n    return sum;\n}\n\ntemplate <typename T>\nstd::pair<std::vector<double>, std::vector<std::vector<T>>> pluginEstimator(const std::vector<std::vector<T>>& Y)\n{\n    std::vector<std::vector<T>> uniqueVal = unique(Y);\n    std::vector<double> counts(uniqueVal.size());\n    for (std::size_t i = 0; i < counts.size(); i++) {\n        for (std::size_t j = 0; j < Y.size(); j++) {\n            if (Y[j] == uniqueVal[i])\n                counts[i]++;\n        }\n    }\n    std::size_t length = Y.size() * Y[0].size();\n    std::transform(counts.begin(), counts.end(), counts.begin(), [&length](auto& i) { return i / length; });\n\n    return std::make_pair(counts, uniqueVal);\n}\n\ntemplate <typename T, typename Metric>\ntypename std::enable_if<!std::is_integral<T>::value, T>::type mutualInformation(\n    const std::vector<std::vector<T>>& Xc, const std::vector<std::vector<T>>& Yc, int k, Metric metric, int version)\n{\n    T N = Xc.size();\n\n    if (N < k + 1 || Yc.size() < k + 1)\n        throw std::invalid_argument(\"number of points in dataset must be larger than k\");\n\n    auto X = Xc;\n    auto Y = Yc;\n    add_noise(X);\n    add_noise(Y);\n    std::vector<std::vector<T>> XY;\n    combine(X, Y, XY);\n    metric::Tree<std::vector<T>, Metric> tree(XY, -1, metric);\n    auto entropyEstimate = boost::math::digamma(k) + boost::math::digamma(N);\n    if (version == 2) {\n        entropyEstimate -= 1 / static_cast<double>(k);\n    }\n\n    metric::Tree<std::vector<T>, Metric> xTree(X, -1, metric);\n\n    for (std::size_t i = 0; i < N; i++) {\n        auto res = tree.knn(XY[i], k + 1);\n        auto neighbor = res.back().first;\n        auto dist = res.back().second;\n        std::size_t nx = 0;\n        if (version == 1) {\n            auto dist_eps = std::nextafter(\n                dist, std::numeric_limits<decltype(dist)>::max());  // this is instead of replacing < with <= in Tree //\n                // added by Max F in order to match Julia code logic\n                // without updating Tree\n            nx = xTree.rnn(X[i], dist_eps).size();  // we include points that lay on the sphere\n        } else if (version == 2) {\n            auto ex = metric(X[neighbor->ID], X[i]);\n            auto ex_eps = std::nextafter(\n                ex, std::numeric_limits<decltype(ex)>::max());  // this it to include the most distant point into the\n                // sphere // added by Max F in order to match Julia code\n                // logic without updating Tree\n            auto rnn_set = xTree.rnn(X[i], ex_eps);\n            nx = rnn_set.size();  // replaced ex by ex_eps by Max F\n        } else {\n            throw std::runtime_error(\"this version not allowed\");\n        }\n        entropyEstimate -= 1.0 / N * boost::math::digamma(static_cast<double>(nx));\n    }\n    return entropyEstimate;\n}\n\ntemplate <typename T>\ntypename std::enable_if<std::is_integral<T>::value, T>::type mutualInformation(\n    const std::vector<std::vector<T>>& Xc, const std::vector<std::vector<T>>& Yc, T logbase)\n{\n    std::vector<std::vector<T>> XY;\n    combine(Xc, Yc, XY);\n    return entropy<T>(Xc, logbase)\n        + entropy<T>(Yc,\n            logbase)  // entropy overload for integers is not implemented yet\n        - entropy<T>(XY, logbase);\n}\n\ntemplate <typename T, typename Metric>\ntypename std::enable_if<!std::is_integral<T>::value, T>::type variationOfInformation(\n    const std::vector<std::vector<T>>& Xc, const std::vector<std::vector<T>>& Yc, int k, T logbase)\n{\n    return entropy<T, Metric>(Xc, k, logbase, Metric()) + entropy<T, Metric>(Yc, k, logbase, Metric())\n        - 2 * mutualInformation<T>(Xc, Yc, k);\n}\n\ntemplate <typename T>\ntypename std::enable_if<!std::is_integral<T>::value, T>::type variationOfInformation_normalized(\n    const std::vector<std::vector<T>>& Xc, const std::vector<std::vector<T>>& Yc, int k, T logbase)\n{\n    using Cheb = metric::Chebyshev<T>;\n    auto mi = mutualInformation<T>(Xc, Yc, k);\n    return 1 - (mi / (entropy<T, Cheb>(Xc, k, logbase, Cheb()) + entropy<T, Cheb>(Yc, k, logbase, Cheb()) - mi));\n}\n\ntemplate <typename V>\ntemplate <template <class, class> class Container, class Allocator_inner, class Allocator_outer, class El>\ntypename std::enable_if<!std::is_integral<El>::value, V>::type VOI<V>::operator()(\n    const Container<Container<El, Allocator_inner>, Allocator_outer>& a,\n    const Container<Container<El, Allocator_inner>, Allocator_outer>& b) const\n{\n    using Cheb = metric::Chebyshev<El>;\n    return entropy<El, Cheb>(a, k, logbase, Cheb()) + entropy<El, Cheb>(b, k, logbase, Cheb())\n        - 2 * mutualInformation<El>(a, b, k);\n}\n\ntemplate <typename V>\ntemplate <template <class, class> class Container, class Allocator_inner, class Allocator_outer, class El>\ntypename std::enable_if<!std::is_integral<El>::value, V>::type VOI_normalized<V>::operator()(\n    const Container<Container<El, Allocator_inner>, Allocator_outer>& a,\n    const Container<Container<El, Allocator_inner>, Allocator_outer>& b) const\n{\n    using Cheb = metric::Chebyshev<El>;\n    auto mi = mutualInformation<El>(a, b, this->k);\n    return 1\n        - (mi\n            / (entropy<El, Cheb>(a, this->k, this->logbase, Cheb())\n                + entropy<El, Cheb>(b, this->k, this->logbase, Cheb()) - mi));\n}\n\n// VOI based on Kozachenko-Leonenko entropy estimator\n\ntemplate <typename V>\ntemplate <template <class, class> class Container, class Allocator_inner, class Allocator_outer, class El>\ntypename std::enable_if<!std::is_integral<El>::value, V>::type VOI_kl<V>::operator()(\n    const Container<Container<El, Allocator_inner>, Allocator_outer>& a,\n    const Container<Container<El, Allocator_inner>, Allocator_outer>& b) const\n{\n    std::vector<std::vector<El>> ab;\n    combine(a, b, ab);\n    return 2 * entropy_kl(ab) - entropy_kl(a) - entropy_kl(b);\n}\n\ntemplate <typename V>\ntemplate <template <class, class> class Container, class Allocator_inner, class Allocator_outer, class El>\ntypename std::enable_if<!std::is_integral<El>::value, V>::type VOI_normalized_kl<V>::operator()(\n    const Container<Container<El, Allocator_inner>, Allocator_outer>& a,\n    const Container<Container<El, Allocator_inner>, Allocator_outer>& b) const\n{\n    auto entropy_a = entropy_kl(a);\n    auto entropy_b = entropy_kl(b);\n    std::vector<std::vector<El>> ab;\n    combine(a, b, ab);\n    auto joint_entropy = entropy_kl(ab);\n    auto mi = entropy_a + entropy_b - joint_entropy;\n    return 1 - (mi / (entropy_a + entropy_b - mi));\n}\n\n}  // namespace metric\n#endif\n", "meta": {"hexsha": "f7117c8a93e7c5ce3ab34eaae536e637a71a6f52", "size": 12097, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "metric/modules/distance/k-random/VOI.cpp", "max_stars_repo_name": "Stepka/telegram_clustering_contest", "max_stars_repo_head_hexsha": "52a012af2ce821410caa98cba840364710eb4256", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-12-03T17:08:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-25T05:06:29.000Z", "max_issues_repo_path": "metric/modules/distance/k-random/VOI.cpp", "max_issues_repo_name": "Stepka/telegram_clustering_contest", "max_issues_repo_head_hexsha": "52a012af2ce821410caa98cba840364710eb4256", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-09-02T02:25:51.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-02T02:25:51.000Z", "max_forks_repo_path": "metric/modules/distance/k-random/VOI.cpp", "max_forks_repo_name": "Stepka/telegram_clustering_contest", "max_forks_repo_head_hexsha": "52a012af2ce821410caa98cba840364710eb4256", "max_forks_repo_licenses": ["Apache-2.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.4520123839, "max_line_length": 120, "alphanum_fraction": 0.6008101182, "num_tokens": 3366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.4785057308055389}}
{"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_TRIGONOMETRIC_FUNCTIONS_SIMD_COMMON_REM_2PI_HPP_INCLUDED\n#define NT2_TOOLBOX_TRIGONOMETRIC_FUNCTIONS_SIMD_COMMON_REM_2PI_HPP_INCLUDED\n\n#include <nt2/toolbox/trigonometric/functions/rem_2pi.hpp>\n#include <nt2/toolbox/trigonometric/functions/scalar/impl/trigo/selection_tags.hpp>\n#include <nt2/include/functions/simd/rem_pio2.hpp>\n#include <nt2/include/functions/simd/rem_pio2_medium.hpp>\n#include <nt2/include/functions/simd/round.hpp>\n#include <nt2/include/functions/simd/tofloat.hpp>\n#include <nt2/include/functions/simd/if_else.hpp>\n#include <nt2/include/functions/simd/is_greater.hpp>\n#include <nt2/include/constants/inv2pi.hpp>\n#include <nt2/include/constants/pix2_1.hpp>\n#include <nt2/include/constants/pix2_2.hpp>\n#include <nt2/include/constants/pix2_3.hpp>\n#include <nt2/sdk/meta/scalar_of.hpp>\n#include <nt2/sdk/meta/as_integer.hpp>\n#include <boost/simd/sdk/memory/aligned_type.hpp>\n#include <boost/fusion/tuple.hpp>\n\n/////////////////////////////////////////////////////////////////////////////\n// reference based Implementation\n/////////////////////////////////////////////////////////////////////////////\nnamespace nt2 { namespace ext\n{\n  NT2_FUNCTOR_IMPLEMENTATION(nt2::tag::rem_2pi_, boost::simd::tag::simd_,\n                      (A0)(X),\n                      ((simd_ < floating_<A0>,X > ))\n                    )\n  {\n    typedef boost::fusion::tuple<A0,A0>        result_type;\n\n    inline result_type operator()(A0 const& a0) const\n      {\n        result_type res;\n        nt2::rem_2pi(a0,\n                     boost::fusion::at_c<0>(res),\n                     boost::fusion::at_c<1>(res)\n                     );\n        return res;\n      }\n  };\n\n  NT2_FUNCTOR_IMPLEMENTATION(  nt2::tag::rem_2pi_, boost::simd::tag::simd_,(A0)(X)\n                            , ((simd_<floating_<A0>,X>))\n                              ((simd_<floating_<A0>,X>))\n                              ((simd_<floating_<A0>,X>))\n                            )\n  {\n    typedef void result_type;\n    inline result_type operator()(A0 const& a0,A0 & xr,A0 & xc) const\n    {\n      typedef typename meta::as_integer<A0>::type i_type;\n      A0 n = tofloat(rem_pio2(a0, xr, xc));\n      xr = xr+n*Pio_2<A0>();\n      xr =  if_else(gt(xr, Pi<A0>()), xr-Twopi<A0>(), xr);\n    }\n  };\n\n  NT2_FUNCTOR_IMPLEMENTATION(nt2::tag::rem_2pi_, tag::cpu_,\n                             (A0)(A1)(X),\n                             ((simd_ <floating_<A0>,X  > ))\n                             ((simd_ <floating_<A0>,X  > ))\n                             ((simd_ <floating_<A0>,X  > ))\n                             ((target_ <unspecified_<A1> >))\n                 )\n  {\n    typedef void result_type;\n    inline result_type operator()(A0 const& a0, A0 & xr, A0& xc, A1 const&) const\n    {\n      typedef typename A1::type selector;\n      rem2pi<selector, void>::rem(a0, xr, xc);\n    }\n  private:\n    template < class T, class dummy = void> struct rem2pi\n    {\n      static inline result_type rem(A0 const& x, A0 & xr, A0& xc)\n      {\n        BOOST_ASSERT_MSG(false, \"wrong target for rem_2pi\");\n      }\n    };\n    template < class dummy> struct rem2pi < big_, dummy>\n    {\n      static inline result_type rem(A0 const& x, A0 & xr, A0& xc)\n      {\n        nt2::rem_2pi(x, xr, xc);\n      }\n    };\n    template < class dummy> struct rem2pi < very_small_, dummy > // |a0| <2*pi\n    {\n      static inline result_type rem(A0 const& x, A0 & xr, A0& xc)\n      {\n        xr = if_else(gt(x, Pi<A0>()), x-Twopi<A0>(),\n                     if_else(lt(x, -Pi<A0>()), x+Twopi<A0>(), x));\n        xc = Zero<A0>();\n      }\n    };\n    template < class dummy> struct rem2pi < small_, dummy >// |a0| <= 20*pi\n    {\n      static inline result_type rem(A0 const& x, A0 & xr, A0& xc)\n      {\n        A0 xi =  nt2::round(x*Inv2pi<A0>());\n        xr = x-xi*Pix2_1<A0>();\n        xr -= xi*Pix2_2<A0>();\n        xr -= xi*Pix2_3<A0>();\n        xc = Zero<A0>();\n       }\n    };\n\n    template < class dummy> struct rem2pi < medium_, dummy >\n    {\n      static inline result_type rem(A0 const& x, A0 & xr, A0& xc)\n      {\n        typedef typename meta::as_integer<A0>::type i_type;\n        A0 n = tofloat(rem_pio2_medium(x, xr, xc));\n        xr = xr+n*Pio_2<A0>();\n        xr = if_else(gt(xr, Pi<A0>()), xr-Twopi<A0>(), xr);\n      }\n    };\n  };\n\n} }\n#endif\n", "meta": {"hexsha": "8965681b2f6882695d954d09403529c0b75f2eea", "size": 4803, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/trigonometric/include/nt2/toolbox/trigonometric/functions/simd/common/rem_2pi.hpp", "max_stars_repo_name": "timblechmann/nt2", "max_stars_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-09-14T00:23:53.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-14T12:51:18.000Z", "max_issues_repo_path": "modules/core/trigonometric/include/nt2/toolbox/trigonometric/functions/simd/common/rem_2pi.hpp", "max_issues_repo_name": "timblechmann/nt2", "max_issues_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/core/trigonometric/include/nt2/toolbox/trigonometric/functions/simd/common/rem_2pi.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": 36.3863636364, "max_line_length": 83, "alphanum_fraction": 0.5288361441, "num_tokens": 1296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4785057246068197}}
{"text": "#ifndef MATHTOOLBOX_LOG_DETERMINANT_HPP\n#define MATHTOOLBOX_LOG_DETERMINANT_HPP\n\n#include <Eigen/Cholesky>\n#include <Eigen/Core>\n\nnamespace mathtoolbox\n{\n    double CalcLogDetOfSymmetricPositiveDefiniteMatrix(const Eigen::MatrixXd& matrix);\n    double CalcLogDetOfSymmetricPositiveDefiniteMatrix(const Eigen::LLT<Eigen::MatrixXd>& matrix_llt);\n} // namespace mathtoolbox\n\n#endif // MATHTOOLBOX_LOG_DETERMINANT_HPP\n", "meta": {"hexsha": "497de97f024636665113c0ab5bfdcca99c65af2d", "size": 414, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mathtoolbox/log-determinant.hpp", "max_stars_repo_name": "yuki-koyama/mathtoolbox", "max_stars_repo_head_hexsha": "eb7449c3c489f465849a74405e72aff016a296f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 195.0, "max_stars_repo_stars_event_min_datetime": "2018-04-28T16:12:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T03:52:56.000Z", "max_issues_repo_path": "include/mathtoolbox/log-determinant.hpp", "max_issues_repo_name": "amazing89/mathtoolbox", "max_issues_repo_head_hexsha": "8904bb06ced2ac501594f9574ef1ba3454b8e38e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 52.0, "max_issues_repo_issues_event_min_datetime": "2018-04-15T01:24:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-02T09:14:23.000Z", "max_forks_repo_path": "include/mathtoolbox/log-determinant.hpp", "max_forks_repo_name": "amazing89/mathtoolbox", "max_forks_repo_head_hexsha": "8904bb06ced2ac501594f9574ef1ba3454b8e38e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 21.0, "max_forks_repo_forks_event_min_datetime": "2018-06-05T04:11:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T13:28:12.000Z", "avg_line_length": 29.5714285714, "max_line_length": 102, "alphanum_fraction": 0.8309178744, "num_tokens": 113, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.47850572460681967}}
{"text": "#ifndef TEST_UNIT_TORSTEN_FRIEBERG_KARLSSON_TEST_FIXTURE\n#define TEST_UNIT_TORSTEN_FRIEBERG_KARLSSON_TEST_FIXTURE\n\n#include <stan/math/rev/core/recover_memory.hpp>\n#include <gtest/gtest.h>\n#include <boost/numeric/odeint.hpp>\n#include <stan/math/torsten/test/unit/test_fixture_model.hpp>\n#include <stan/math/torsten/pmx_ode_model.hpp>\n#include <iostream>\n#include <sstream>\n#include <vector>\n#include <string>\n\nstruct FribergKarlssonFunc {\n   // parms contains both the PK and the PD parameters.\n   // x contains both the PK and the PD states.\n  template <typename T0, typename T1, typename T2>\n  Eigen::Matrix<typename stan::return_type_t<T0, T1, T2>, -1, 1>\n  operator()(const T0& t,\n             const Eigen::Matrix<T1, -1, 1>& x,\n             std::ostream* pstream__,\n             const std::vector<T2>& parms,\n             const std::vector<double>& x_r,\n             const std::vector<int>& x_i) const {\n    using scalar = typename stan::return_type_t<T0, T1, T2>;\n\n    // PK variables\n    T2\n      CL = parms[0],\n      Q = parms[1],\n      VC = parms[2],\n      VP = parms[3],\n      ka = parms[4],\n      k10 = CL / VC,\n      k12 = Q / VC,\n      k21 = Q / VP;\n\n    // PD variables\n    T2\n      MTT = parms[5],\n      circ0 = parms[6],\n      gamma = parms[7],\n      alpha = parms[8],\n      ktr = 4 / MTT;\n    typename stan::return_type_t<T1, T2>\n      prol = x[3] + circ0,\n      transit1 = x[4] + circ0,\n      transit2 = x[5] + circ0,\n      transit3 = x[6] + circ0,\n      circ = stan::math::fmax(stan::math::machine_precision(), x[7] + circ0);\n\n    Eigen::Matrix<scalar, -1, 1> dxdt(8);\n    dxdt[0] = -ka * x[0];\n    dxdt[1] = ka * x[0] - (k10 + k12) * x[1] + k21 * x[2];\n    dxdt[2] = k12 * x[1] - k21 * x[2];\n\n    scalar conc = x[1] / VC;\n    scalar Edrug = alpha * conc;\n\n    dxdt[3] = ktr * prol * (((1 - Edrug) * pow((circ0 / circ), gamma)) - 1);\n    dxdt[4] = ktr * (prol - transit1);\n    dxdt[5] = ktr * (transit1 - transit2);\n    dxdt[6] = ktr * (transit2 - transit3);\n    dxdt[7] = ktr * (transit3 - circ);\n\n    return dxdt;\n  }\n};\n\ntemplate<typename T>\nstruct test_fk : public TorstenPMXTest<test_fk<T> > {\n  test_fk() {\n    this -> ncmt = 8;\n\n    this -> reset_events(10);\n\n    this -> theta.resize(1);\n\n    // CL , Q , Vc , Vp , ka , MTT , Circ0 , alpha , gamma\n    this -> theta[0] = {10, 15, 35, 105, 2.0, 125, 5, 0.17, 3e-4};\n\n    this -> biovar.resize(1);\n    this -> biovar[0] = {1, 1, 1, 1, 1, 1, 1, 1};\n    this -> tlag.resize(1);\n    this -> tlag[0] = {0, 0, 0, 0, 0, 0, 0, 0};\n\n    for(int i = 0; i < this -> nt; i++) {\n      this -> time[i] = i * 1.25; \n    }\n\n    this -> amt[0] = 80000.0;\n    this -> cmt[0] = 1;\n    this -> evid[0] = 1;\n    this -> ii[0] = 12;\n    this -> addl[0] = 14;\n  }\n};\n\n#endif\n", "meta": {"hexsha": "099beefa7cc229907bd8e9a5b8e790c6de421034", "size": 2728, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/unit/test_fixture_friberg_karlsson.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": "test/unit/test_fixture_friberg_karlsson.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": "test/unit/test_fixture_friberg_karlsson.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": 27.28, "max_line_length": 77, "alphanum_fraction": 0.5527859238, "num_tokens": 990, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.47838242611123133}}
{"text": "/**\n * @file Tools/Math/RotationMatrix.hpp\n * Delcaration of class RotationMatrix\n * @author <a href=\"mailto:martin.kallnik@gmx.de\">Martin Kallnik</a>\n * @author <a href=\"mailto:thomas.kindler@gmx.de\">Thomas Kindler</a>\n * @author Max Risler\n * @author <a href=\"mailto:alexists@tzi.de\">Alexis Tsogias</a>\n */\n\n#pragma once\n\n#include <Eigen/Dense>\n\nusing namespace Eigen;\n\n/**\n * Representation for 3x3 RotationMatrices\n */\nclass RotationMatrix : public Matrix3f\n{\npublic:\n  RotationMatrix() : Matrix3f(Matrix3f::Identity()) {}\n  RotationMatrix(const Matrix3f& other) : Matrix3f(other) {}\n  RotationMatrix(const AngleAxisf& angleAxis) : Matrix3f(angleAxis.toRotationMatrix()) {}\n  RotationMatrix(const Quaternionf& quat) : Matrix3f(quat.toRotationMatrix()) {}\n\n  RotationMatrix& operator=(const Matrix3f& other)\n  {\n    Matrix3f::operator=(other);\n    return *this;\n  }\n\n  RotationMatrix& operator=(const AngleAxisf& angleAxis)\n  {\n    Matrix3f::operator=(angleAxis.toRotationMatrix());\n    return *this;\n  }\n\n  RotationMatrix& operator=(const Quaternionf& quat)\n  {\n    Matrix3f::operator=(quat.toRotationMatrix());\n    return *this;\n  }\n\n  /**\n   * Multiplication of this matrix by vector.\n   * @param  vector  The vector this one is multiplied by\n   * @return         A new vector containing the result\n   */\n  Vector3f operator*(const Vector3f& vector) const\n  {\n    return Matrix3f::operator*(vector);\n  }\n\n  /**\n   * Multiplication of this rotation matrix by another rotation matrix.\n   * @param  other  The other matrix this one is multiplied by\n   * @return        A new matrix containing the result\n   *                of the calculation.\n   */\n  RotationMatrix operator*(const RotationMatrix& other) const\n  {\n    return RotationMatrix(Base::operator*(other));\n  }\n\n  RotationMatrix& operator*=(const AngleAxisf& rot)\n  {\n    Matrix3f::operator*=(rot.toRotationMatrix());\n    return *this;\n  }\n\n  RotationMatrix& operator*=(const Quaternionf& rot)\n  {\n    Matrix3f::operator*=(rot.toRotationMatrix());\n    return *this;\n  }\n\n  RotationMatrix& operator*=(const RotationMatrix& rot)\n  {\n    Matrix3f::operator*=(rot);\n    return *this;\n  }\n\n  /**\n   * Invert the matrix.\n   *\n   * @note: Inverted rotation matrix is transposed matrix.\n   */\n  RotationMatrix& invert()\n  {\n    transposeInPlace();\n    return *this;\n  }\n\n  RotationMatrix inverse() const\n  {\n    return RotationMatrix(transpose());\n  }\n\n  void normalize()\n  {\n    *this = Quaternionf(*this).normalized();\n  }\n\n  RotationMatrix normalized() const\n  {\n    return Quaternionf(*this).normalized();\n  }\n\n  /**\n   * Converts the rotation matrix into an angleAxis.\n   * @return The rotation matrix as angleAxis.\n   */\n  AngleAxisf getAngleAxis() const;\n\n  /**\n   * Converts the rotation matrix into an angleAxis in single vector format.\n   * @return The rotation matrix as angleAxis.\n   */\n  // Vector3f getPackedAngleAxis() const;\n\n  /**\n   * Rotation around the x-axis.\n   *\n   * @param   angle  The angle this pose will be rotated by\n   * @return  A reference to this object after the calculation.\n   */\n  RotationMatrix& rotateX(const float angle);\n\n  /**\n   * Rotation around the y-axis.\n   *\n   * @param   angle  The angle this pose will be rotated by\n   * @return  A reference to this object after the calculation.\n   */\n  RotationMatrix& rotateY(const float angle);\n\n  /**\n   * Rotation around the z-axis.\n   *\n   * @param   angle  The angle this pose will be rotated by\n   * @return  A reference to this object after the calculation.\n   */\n  RotationMatrix& rotateZ(const float angle);\n\n  /**\n   * Get the x-angle of a RotationMatrix.\n   *\n   * @return  The angle around the x-axis between the original\n   *          and the rotated z-axis projected on the y-z-plane\n   */\n  float getXAngle() const;\n\n  /**\n   * Get the y-angle of a RotationMatrix.\n   *\n   * @return  The angle around the y-axis between the original\n   *          and the rotated x-axis projected on the x-z-plane\n   */\n  float getYAngle() const;\n\n  /**\n   * Get the z-angle of a RotationMatrix.\n   *\n   * @return  The angle around the z-axis between the original\n   *          and the rotated x-axis projected on the x-y-plane\n   */\n  float getZAngle() const;\n\n  /**\n   * Create and return a RotationMatrix, rotated around x-axis\n   *\n   * @param   angle\n   * @return  rotated RotationMatrix\n   */\n  static RotationMatrix aroundX(const float angle);\n\n  /**\n   * Create and return a RotationMatrix, rotated around y-axis\n   *\n   * @param   angle\n   * @return  rotated RotationMatrix\n   */\n  static RotationMatrix aroundY(const float angle);\n\n  /**\n   * Create and return a RotationMatrix, rotated around z-axis\n   *\n   * @param   angle\n   * @return  rotated RotationMatrix\n   */\n  static RotationMatrix aroundZ(const float angle);\n\n  /**\n   * Creates a RotationMatrix rotated around z, y and x (in this order!).\n   * Equivalent to fromRotationZ(z).rotateY(y).rotateX(x);\n   */\n  static RotationMatrix fromEulerAngles(const float x, const float y, const float z);\n\n  /**\n   * Creates a RotationMatrix rotatied around the z, y and x components of the Vector3 (in this order!).\n   * Equivalent to fromRotationZ(rotation.z).rotateY(rotation.y).rotateX(rotation.x);\n   */\n  static RotationMatrix fromEulerAngles(const Vector3f rotation);\n\nprivate:\n  // The following is a hack in order to keep the kicks from the Kickengine working...\n  friend class KickViewWidget;\n  friend class KickEngineData;\n  friend class StableKickEngineData;\n  friend class RotationMatrix_getPackedAngleAxisFaulty_Test;\n\n  Vector3f getPackedAngleAxisFaulty() const;\n\n  static void reg();\n};\n", "meta": {"hexsha": "587a1e497b474291d0aaac90cc8a1a8a21411368", "size": 5601, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "nao_ik/include/nao_ik/bhuman/RotationMatrix.hpp", "max_stars_repo_name": "ijnek/nao_ik", "max_stars_repo_head_hexsha": "f417ce46092d2375fca6bdedba38bf90a8458f5d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "nao_ik/include/nao_ik/bhuman/RotationMatrix.hpp", "max_issues_repo_name": "ijnek/nao_ik", "max_issues_repo_head_hexsha": "f417ce46092d2375fca6bdedba38bf90a8458f5d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nao_ik/include/nao_ik/bhuman/RotationMatrix.hpp", "max_forks_repo_name": "ijnek/nao_ik", "max_forks_repo_head_hexsha": "f417ce46092d2375fca6bdedba38bf90a8458f5d", "max_forks_repo_licenses": ["Apache-2.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.8110599078, "max_line_length": 104, "alphanum_fraction": 0.6784502767, "num_tokens": 1407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834649, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4783637748694477}}
{"text": "#include <cmath>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <Eigen/LU>\n#include <limits>\n#include \"rose499/spline.hpp\"\n\nusing namespace Eigen;\n\nconstexpr int Spline::PolyOrder;\nconstexpr int Spline::CoeffCount;\n\nnamespace\n{\n    constexpr int ResampleCount = 9;\n\n    using ValueType = Spline::ValueType;\n    using MatrixXT = SimulatorTypes::MatrixXT;\n    using VectorXT = SimulatorTypes::VectorXT;\n    using PolySpace = Array<ValueType, 1, Spline::CoeffCount>;\n\n    PolySpace polydiff_power(PolySpace poly, int order)\n    {\n        PolySpace prevPoly = poly;\n        PolySpace dpoly = PolySpace::Constant(0);\n        PolySpace powerCoeff = PolySpace::Constant(1);\n        for(auto i = 0; i < order; i++)\n        {\n            Array<ValueType, 1, Dynamic> power(1, Spline::CoeffCount - i);\n            power.setLinSpaced(0, Spline::PolyOrder - i);\n            powerCoeff.tail(Spline::CoeffCount - i) = powerCoeff.tail(Spline::CoeffCount - i) * power;\n        }\n        dpoly.tail(Spline::CoeffCount - order) = poly.head(Spline::CoeffCount - order);\n        dpoly = dpoly * powerCoeff;\n        return dpoly;\n    }\n\n    PolySpace polydiffshift(PolySpace poly)\n    {\n        PolySpace dpoly = PolySpace::Constant(0);\n        dpoly.head(Spline::CoeffCount - 1) = poly.tail(Spline::CoeffCount - 1);\n        dpoly.head(Spline::CoeffCount - 1) *= Array<ValueType, Spline::CoeffCount - 1, 1>::LinSpaced(1, Spline::PolyOrder);\n        return dpoly;\n    }\n\n    /**\n        Builds an equality matrix that only provides end point guarantees and\n        C^2 continuity everywhere.\n    **/\n    void\n    polyBuildSoftEqualityMatrix(    MatrixXT& Aeq,\n                                    VectorXT& beq,\n                                    Matrix<ValueType, 2, Dynamic> const & waypoints,\n                                    double direction = std::numeric_limits<double>::infinity() )\n    {\n        constexpr size_t DirectionConstraintCount = 1;\n        constexpr auto CoeffCount = Spline::CoeffCount;\n\n        auto const waypointCount = waypoints.cols();\n        auto const segmentCount = waypointCount - 1;\n\n        bool const supportDirection = std::isfinite(direction);\n\n        Aeq.resize( 4*(waypointCount-2)                                         // Differential Constraints\n                        + 2*waypointCount                                       // Equality Constraints\n                        + (supportDirection ? DirectionConstraintCount : 0)     // Direction Constraint\n                    , 2*CoeffCount*segmentCount );\n        beq.resize(Aeq.rows(), 1);\n\n        Aeq.setZero();\n        beq.setZero();\n\n        PolySpace powers = PolySpace::LinSpaced(0, Spline::PolyOrder);\n        auto row = 0;\n        for(auto indSeg = 0; indSeg < segmentCount; ++indSeg)\n        {\n            auto col = 2*CoeffCount*indSeg;\n\n            ValueType leftLambda = (indSeg * 1.0) / segmentCount;\n            ValueType rightLambda = ((indSeg + 1.0) * 1.0) / segmentCount;\n\n            PolySpace leftTerms = PolySpace::Constant(leftLambda);\n            PolySpace rightTerms = PolySpace::Constant(rightLambda);\n            leftTerms = pow(leftTerms, powers);\n            rightTerms = pow(rightTerms, powers);\n\n            PolySpace dLeftTerms = polydiff_power(leftTerms, 1);\n            PolySpace ddLeftTerms = polydiff_power(leftTerms, 2);\n\n            PolySpace dRightTerms = polydiff_power(rightTerms, 1);\n            PolySpace ddRightTerms = polydiff_power(rightTerms, 2);\n\n\n            if( indSeg < segmentCount - 1 )\n            {\n                // Right Equality (C0)\n                Aeq.block<1, CoeffCount>(row + 0, col) = rightTerms;\n                Aeq.block<1, CoeffCount>(row + 0, col + 2 * CoeffCount) = -rightTerms;\n                Aeq.block<1, CoeffCount>(row + 1, col + CoeffCount) = rightTerms;\n                Aeq.block<1, CoeffCount>(row + 1, col + 3 * CoeffCount) = -rightTerms;\n                row += 2;\n\n                // Right Differential Continuity (C1)\n                Aeq.block<1, CoeffCount>(row + 0, col) = dRightTerms;\n                Aeq.block<1, CoeffCount>(row + 0, col + 2 * CoeffCount) = -dRightTerms;\n                Aeq.block<1, CoeffCount>(row + 1, col + CoeffCount) = dRightTerms;\n                Aeq.block<1, CoeffCount>(row + 1, col + 3 * CoeffCount) = -dRightTerms;\n                row += 2;\n\n                // Right Differential Continuity (C2)\n                Aeq.block<1, CoeffCount>(row + 0, col) = ddRightTerms;\n                Aeq.block<1, CoeffCount>(row + 0, col + 2 * CoeffCount) = -ddRightTerms;\n                Aeq.block<1, CoeffCount>(row + 1, col + CoeffCount) = ddRightTerms;\n                Aeq.block<1, CoeffCount>(row + 1, col + 3 * CoeffCount) = -ddRightTerms;\n                row += 2;\n            }\n            else\n            {\n                // Hard Right Equality\n                Aeq.block<1, CoeffCount>(row + 0, col) = rightTerms;\n                Aeq.block<1, CoeffCount>(row + 1, col + CoeffCount) = rightTerms;\n                beq.block<2, 1>(row, 0) = waypoints.block<2, 1>(0, indSeg + 1);\n                row += 2;\n            }\n\n            if( indSeg == 0 )\n            {\n                // Left Equality (C0)\n                Aeq.block<1, CoeffCount>(row + 0, col) = leftTerms;\n                Aeq.block<1, CoeffCount>(row + 1, col + CoeffCount) = leftTerms;\n                beq.block<2, 1>(row, 0) = waypoints.block<2, 1>(0, indSeg);\n                row += 2;\n\n                if( supportDirection )\n                {\n                    while(direction > M_PI) direction -= 2*M_PI;\n                    while(direction < -M_PI) direction += 2*M_PI;\n\n                    if( std::abs(direction) <= std::atan2(1.0, 1.0)\n                     || std::abs(direction - M_PI) <= std::atan2(1.0, 1.0)\n                     || std::abs(direction + M_PI) <= std::atan2(1.0, 1.0) )\n                    {\n                        // Small tangent.\n                        Aeq.bottomRows(DirectionConstraintCount).block<1, CoeffCount>(0, col) = std::tan(direction)*dLeftTerms;\n                        Aeq.bottomRows(DirectionConstraintCount).block<1, CoeffCount>(0, col + CoeffCount) = -dLeftTerms;\n                    }\n                    else\n                    {\n                        // Large tangent\n                        Aeq.bottomRows(DirectionConstraintCount).block<1, CoeffCount>(0, col) = -dLeftTerms;\n                        Aeq.bottomRows(DirectionConstraintCount).block<1, CoeffCount>(0, col + CoeffCount) = dLeftTerms / std::tan(direction);\n                    }\n                }\n            }\n        }\n    }\n\n    /**\n        Builds the equality matrix that is used in least squares to achieve\n        C0, C1, and C2 equality at waypoints.\n\n    **/\n    void\n    polyBuildEqualityMatrix( MatrixXT& Aeq,\n                             VectorXT& beq,\n                             Matrix<ValueType, 2, Dynamic> const & waypoints,\n                             double direction = std::numeric_limits<double>::infinity() )\n    {\n        constexpr size_t DirectionConstraintCount = 2;\n        constexpr auto CoeffCount = Spline::CoeffCount;\n\n        auto const waypointCount = waypoints.cols();\n        auto const segmentCount = waypointCount - 1;\n\n        bool const supportDirection = std::isfinite(direction);\n\n        Aeq.resize( 4*(segmentCount-1)                                          // Differential Constraints\n                        + 4*(segmentCount)                                      // Equality Constraints\n                        + (supportDirection ? DirectionConstraintCount : 0)     // Direction Constraint\n                    , 2*CoeffCount*segmentCount );\n        beq.resize(Aeq.rows(), 1);\n\n        Aeq.setZero();\n        beq.setZero();\n\n        PolySpace powers = PolySpace::LinSpaced(0, Spline::PolyOrder);\n        auto row = 0;\n        for(auto indSeg = 0; indSeg < segmentCount; ++indSeg)\n        {\n            auto col = 2*CoeffCount*indSeg;\n\n            ValueType leftLambda = (indSeg * 1.0) / segmentCount;\n            ValueType rightLambda = ((indSeg + 1.0) * 1.0) / segmentCount;\n\n            PolySpace leftTerms = PolySpace::Constant(leftLambda);\n            PolySpace rightTerms = PolySpace::Constant(rightLambda);\n            leftTerms = pow(leftTerms, powers);\n            rightTerms = pow(rightTerms, powers);\n\n            PolySpace dLeftTerms = polydiff_power(leftTerms, 1);\n            PolySpace ddLeftTerms = polydiff_power(leftTerms, 2);\n\n            PolySpace dRightTerms = polydiff_power(rightTerms, 1);\n            PolySpace ddRightTerms = polydiff_power(rightTerms, 2);\n\n            // Left Equality (C0)\n            Aeq.block<1, CoeffCount>(row + 0, col) = leftTerms;\n            Aeq.block<1, CoeffCount>(row + 1, col + CoeffCount) = leftTerms;\n            beq.block<2, 1>(row, 0) = waypoints.block<2, 1>(0, indSeg);\n            row += 2;\n\n            // Right Equality (C0)\n            Aeq.block<1, CoeffCount>(row + 0, col) = rightTerms;\n            Aeq.block<1, CoeffCount>(row + 1, col + CoeffCount) = rightTerms;\n            beq.block<2, 1>(row, 0) = waypoints.block<2, 1>(0, indSeg + 1);\n            row += 2;\n\n            if( (indSeg == 0) && supportDirection )\n            {\n                Aeq.bottomRows(DirectionConstraintCount).block<1, CoeffCount>(0, col) = dLeftTerms;\n                Aeq.bottomRows(DirectionConstraintCount).block<1, CoeffCount>(1, col + CoeffCount) = dLeftTerms;\n\n                Matrix<ValueType, 2, 1> vec;\n                vec(0) = std::cos(direction);\n                vec(1) = std::sin(direction);\n\n                beq.tail(DirectionConstraintCount) = vec;\n            }\n\n            if( indSeg < segmentCount - 1 )\n            {\n                // Right Differential Continuity (C1)\n                Aeq.block<1, CoeffCount>(row + 0, col) = dRightTerms;\n                Aeq.block<1, CoeffCount>(row + 0, col + 2 * CoeffCount) = -dRightTerms;\n                Aeq.block<1, CoeffCount>(row + 1, col + CoeffCount) = dRightTerms;\n                Aeq.block<1, CoeffCount>(row + 1, col + 3 * CoeffCount) = -dRightTerms;\n                row += 2;\n\n                // Right Differential Continuity (C2)\n                Aeq.block<1, CoeffCount>(row + 0, col) = ddRightTerms;\n                Aeq.block<1, CoeffCount>(row + 0, col + 2 * CoeffCount) = -ddRightTerms;\n                Aeq.block<1, CoeffCount>(row + 1, col + CoeffCount) = ddRightTerms;\n                Aeq.block<1, CoeffCount>(row + 1, col + 3 * CoeffCount) = -ddRightTerms;\n                row += 2;\n            }\n        }\n    }\n\n\n    void\n    polyBuildLSQMatrix( MatrixXT& A,\n                        VectorXT& b,\n                        Matrix<ValueType, 2, Dynamic> const & waypoints )\n    {\n        constexpr auto CoeffCount = Spline::CoeffCount;\n        constexpr auto IntermediateSampleCount = 9;\n        const auto waypointCount = waypoints.cols();\n        const auto segmentCount = waypointCount - 1;\n        const auto sampleCount = segmentCount * IntermediateSampleCount;\n        using SampleRow = Matrix<ValueType, 1, IntermediateSampleCount>;\n\n        A.resize(2*sampleCount, 2*CoeffCount*segmentCount);\n        b.resize(A.rows());\n\n        A.setZero();\n        b.setZero();\n\n        PolySpace powers = PolySpace::LinSpaced(0, Spline::PolyOrder);\n        size_t row = 0;\n        size_t colX = 0, colY = CoeffCount;\n        for(auto si = 0; si < segmentCount; ++si)\n        {\n            SampleRow sampleX = Matrix<ValueType, 1, IntermediateSampleCount+2>::LinSpaced(waypoints(0, si), waypoints(0, si+1)).middleCols(1, IntermediateSampleCount);\n            SampleRow sampleY = Matrix<ValueType, 1, IntermediateSampleCount+2>::LinSpaced(waypoints(1, si), waypoints(1, si+1)).middleCols(1, IntermediateSampleCount);\n            SampleRow sampleLambda = Matrix<ValueType, 1, IntermediateSampleCount+2>::LinSpaced(si * 1.0 / segmentCount, (si+1) * 1.0 / segmentCount).middleCols(1, IntermediateSampleCount);\n\n            for(auto i = 0; i < sampleLambda.cols(); ++i)\n            {\n                PolySpace terms = PolySpace::Constant(sampleLambda(i));\n                terms = pow(terms, powers);\n\n                // Equality at the lambda\n                A.block<1, CoeffCount>(row + 0, colX) = terms;\n                A.block<1, CoeffCount>(row + 1, colY) = terms;\n                b(row + 0) = sampleX(i);\n                b(row + 1) = sampleY(i);\n\n                row += 2;\n            }\n\n            colX += 2 * CoeffCount;\n            colY += 2 * CoeffCount;\n        }\n    }\n\n    /**\n     * Splines a 5th order polynomial through the waypoints that ensures C2\n     * conditions are met as well as a direction requirement at lambda=0\n     *\n     * The system is normally underdetermined so polyfit normally calculates the\n     * right pseduo-inverse and performs a full pivot LU decomposition in order to\n     * solve for the coefficients.\n     *\n     * Implements https://stanford.edu/class/ee103/lectures/constrained-least-squares/constrained-least-squares_slides.pdf\n     */\n    Matrix<ValueType, Dynamic, Spline::CoeffCount>\n    polyfit(Matrix<ValueType, 2, Dynamic> waypoints, double direction = std::numeric_limits<double>::infinity() )\n    {\n        constexpr auto CoeffCount = Spline::CoeffCount;\n\n        auto const waypointCount = waypoints.cols();\n        auto const segmentCount = waypointCount - 1;\n\n        MatrixXT Aeq, A;\n        VectorXT beq, b;\n\n        polyBuildSoftEqualityMatrix(Aeq, beq, waypoints, direction);\n        polyBuildLSQMatrix(A, b, waypoints);\n\n        // Moore-Penrose (Right) Pseudo-Inverse\n        //c = Aeq.transpose() * (Aeq * Aeq.transpose()).fullPivLu().solve(beq);\n\n        // Build full solution matrix F * (x, z)' = (2A'b, beq)'\n        MatrixXT F( A.cols() + Aeq.rows(),\n                    A.cols() + Aeq.rows() );\n        VectorXT v( F.rows() );\n\n        F.setZero();\n        v.setZero();\n\n        F.block(0, 0, A.cols(), A.cols()) = 2 * A.transpose() * A;\n        F.block(0, A.cols(), Aeq.cols(), Aeq.rows()) = Aeq.transpose();\n        F.block(A.cols(), 0, Aeq.rows(), Aeq.cols()) = Aeq;\n\n        v.head(A.cols()) = 2 * A.transpose() * b;\n        v.tail(beq.rows()) = beq;\n\n        VectorXT d(F.rows(), 1);\n        if( F.rows() > 100 )\n        {\n            SparseMatrix<ValueType, ColMajor> Fs;\n            Fs = F.sparseView();\n\n            SparseLU< SparseMatrix<ValueType, ColMajor> > solver;\n            solver.analyzePattern(Fs);\n            solver.factorize(Fs);\n            d = solver.solve(v);\n        }\n        else\n        {\n            d = F.fullPivHouseholderQr().solve(v);\n        }\n        VectorXT c = d.head(Aeq.cols());\n        /*\n        MatrixXT c(Aeq.cols(), 1);\n\n        // Moore-Penrose (Right) Pseudo-Inverse\n        c = Aeq.transpose() * (Aeq * Aeq.transpose()).fullPivLu().solve(beq);\n        */\n        // Map the resulting coefficient vector into our matrix form of the polynomial\n        // spline!\n        Matrix<ValueType, Dynamic, CoeffCount> result(2 * segmentCount, CoeffCount);\n        result = Map< Matrix<ValueType, Dynamic, CoeffCount, RowMajor> >(c.data(), result.rows(), result.cols());\n\n        return result;\n    }\n}\n\nSpline::Spline(Matrix<Spline::ValueType, 2, Dynamic> points)\n  : mSplineCount(points.cols() - 1),\n    mPoly(2 * mSplineCount, CoeffCount),\n    mDPoly(2 * mSplineCount, CoeffCount),\n    mDDPoly(2 * mSplineCount, CoeffCount)\n{\n    mPoly = ::polyfit(points);\n    for( auto i = 0; i < mPoly.rows(); ++i )\n    {\n        mDPoly.row(i) = ::polydiffshift(mPoly.row(i));\n    }\n    for( auto i = 0; i < mPoly.rows(); ++i )\n    {\n        mDDPoly.row(i) = ::polydiffshift(mDPoly.row(i));\n    }\n    approximateSelf();\n}\n\nSpline::Spline(Eigen::Matrix<Spline::ValueType, 2, Eigen::Dynamic> points, double direction)\n  : mSplineCount(points.cols() - 1),\n    mPoly(2 * mSplineCount, CoeffCount),\n    mDPoly(2 * mSplineCount, CoeffCount),\n    mDDPoly(2 * mSplineCount, CoeffCount)\n{\n    mPoly = ::polyfit(points, direction);\n    for( auto i = 0; i < mPoly.rows(); ++i )\n    {\n        mDPoly.row(i) = ::polydiffshift(mPoly.row(i));\n    }\n    for( auto i = 0; i < mPoly.rows(); ++i )\n    {\n        mDDPoly.row(i) = ::polydiffshift(mDPoly.row(i));\n    }\n    approximateSelf();\n}\n\n\nSpline::Spline()\n  : mSplineCount(1),\n    mPoly(2 * mSplineCount, CoeffCount),\n    mDPoly(2 * mSplineCount, CoeffCount),\n    mDDPoly(2 * mSplineCount, CoeffCount)\n{\n    mPoly.setZero();\n    mDPoly.setZero();\n    mDDPoly.setZero();\n}\n\nMatrix<Spline::ValueType, 2, 2> Spline::frame(ValueType parameter, uint32_t derivative) const\n{\n    // Min ops, 89 froats\n\n    Matrix<ValueType, 2, 2> basis;\n    Matrix<ValueType, 2, 1> tangent = (*this)(parameter, 1);\n    ValueType speed = tangent.norm();\n\n    if(derivative >= 0)\n    {\n        basis.col(0) = tangent / speed;\n\n        // Rotate the first column by 90 degrees (right handed frame) to form the\n        // full basis for R^2\n        basis.col(1) = basis.col(0).reverse();\n        basis(0, 1) = -basis(0, 1);\n    }\n\n    if(derivative >= 1)\n    {\n        Matrix<ValueType, 2, 1> accel = (*this)(parameter, 2);\n        basis.col(0) = ( accel - accel.dot(basis.col(0)) * basis.col(0) ) / speed;\n    }\n\n    if(derivative >= 2)\n        throw InvalidParameterException();\n\n    // Rotate the first column by 90 degrees (right handed frame) to form the\n    // full basis for R^2\n    basis.col(1) = basis.col(0).reverse();\n    basis(0, 1) = -basis(0, 1);\n    return basis;\n}\n\nSpline::ValueType Spline::nearestPoint(Matrix<ValueType, 2, 1> point, ValueType lambdaStar) const\n{\n    auto error =\n        [point, this](ValueType l) -> ValueType {\n            return (point - this->operator()(l)).squaredNorm();\n        };\n    auto gradient =\n        [point, this](ValueType l) -> ValueType {\n            Matrix<ValueType, 2, 1> verr = point - this->operator()(l);\n            return -2*verr.dot(this->operator()(l, 1));\n        };\n\n    ValueType lambda = lambdaStar;\n    ValueType alpha = static_cast<ValueType>(1.0);\n    alpha = std::min(alpha, alpha / speed(lambda));\n\n    ValueType improvement = 1;\n    int i = 500;\n    while(std::abs(gradient(lambda)) > 1e-6 && (i > 0))\n    {\n        ValueType estimate = lambda - alpha * gradient(lambda);\n        improvement = error(estimate) - error(lambda);\n        if( improvement < 0 )\n        {\n            lambda = estimate;\n            alpha *= 1.2;\n        }\n        else\n            alpha *= 0.7;\n        --i;\n    }\n\n    return std::max(std::min(lambda, static_cast<ValueType>(1.0)), static_cast<ValueType>(0.0));\n}\n\nint Spline::splineIndexUsed(ValueType parameter) const\n{\n    return std::max(0, std::min(mSplineCount - 1, (int)std::floor(mSplineCount * parameter)));\n}\n\nSpline::ValueType Spline::speed(ValueType parameter) const\n{\n    return (*this)(parameter, 1).norm();\n}\n\nMatrix<Spline::ValueType, 2, 1> Spline::operator() (ValueType parameter, uint32_t derivative) const\n{\n    using Vector = Matrix<Spline::ValueType, 2, 1>;\n    using PolySpace = Array<Spline::ValueType, CoeffCount, 1>;\n\n    // Identically zero derivative\n    if( derivative > PolyOrder )\n        return Vector::Zero();\n\n    // Calculate x^0, x^1, ..., x^5\n    PolySpace value = PolySpace::Constant(parameter);\n    PolySpace powers = PolySpace::LinSpaced(0, PolyOrder);\n    value = pow(value, powers);\n\n    // Choose spline based on parameter value.\n    int indSpline = splineIndexUsed(parameter);\n\n    // And evaluate!\n    switch(derivative)\n    {\n    case 0:\n        return mPoly.block<2, CoeffCount>(2 * indSpline, 0) * value.matrix();\n\n    case 1:\n        return mDPoly.block<2, CoeffCount>(2 * indSpline, 0) * value.matrix();\n\n    case 2:\n        return mDDPoly.block<2, CoeffCount>(2 * indSpline, 0) * value.matrix();\n\n    default:\n        throw InvalidParameterException();\n    };\n}\n\nvoid Spline::approximateSelf()\n{\n    Spline& self = *this;\n\n    const double maxDelta = 1.0 / (2.0 * mSplineCount);\n    double startLambda = 0;\n    double endLambda = maxDelta;\n\n    mApproximation.clear();\n    do\n    {\n        Spline::Line currentSegment;\n        Matrix<ValueType, 2, 1> start = self(startLambda);\n        Matrix<ValueType, 2, 1> end = self(endLambda);\n\n        double normedIntegral = 0.0;\n        do\n        {\n            normedIntegral = 0.0;\n            endLambda = startLambda / 2.0 + endLambda / 2.0;\n            end = self(endLambda);\n\n            Matrix<ValueType, 2, 1> midpoint = self(startLambda / 2.0 + endLambda / 2.0);\n\n            // Integrate numerically\n            for(int i = 0; (i < 1000) && (normedIntegral <= 0.1); ++i)\n            {\n                Matrix<ValueType, 3, 1> dError = Matrix<ValueType, 3, 1>::Constant(0);\n                Matrix<ValueType, 3, 1> dLine = Matrix<ValueType, 3, 1>::Constant(0);\n                dError.head(2) = self(startLambda + i * (endLambda - startLambda) / 1000)\n                               - (start + i * (end - start) / 1000);\n                dLine.head(2)  = (end - start) / 1000;\n                normedIntegral += dError.cross(dLine).norm();\n            }\n        } while( normedIntegral > 0.1 );\n\n        geom::set<0, 0>(currentSegment, start[0]);\n        geom::set<0, 1>(currentSegment, start[1]);\n        geom::set<1, 0>(currentSegment, end[0]);\n        geom::set<1, 1>(currentSegment, end[1]);\n\n        startLambda = endLambda;\n        endLambda = std::min(endLambda + maxDelta, 1.0);\n\n        mApproximation.push_back(currentSegment);\n    } while( startLambda < 1.0 );\n\n    mArcLength = 0;\n    for(auto&& line : mApproximation)\n    {\n        mArcLength += geom::length(line);\n    }\n}\n\nMatrix<Spline::ValueType, Dynamic, Spline::CoeffCount> Spline::poly() const { return mPoly; }\nMatrix<Spline::ValueType, Dynamic, Spline::CoeffCount> Spline::dpoly() const{ return mDPoly; }\nMatrix<Spline::ValueType, Dynamic, Spline::CoeffCount> Spline::ddpoly() const{ return mDDPoly; }\nSpline::ApproximateSpline const & Spline::approximation() const { return mApproximation; }\nSpline::ValueType Spline::arclength() const { return mArcLength; }\n", "meta": {"hexsha": "5a4767a40693cf36806356d75c4e182dd69fd989", "size": 21952, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "simulator/src/spline.cpp", "max_stars_repo_name": "rollends/SE499", "max_stars_repo_head_hexsha": "949b9cc85abe558b84289d906b730605c2f32c3b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "simulator/src/spline.cpp", "max_issues_repo_name": "rollends/SE499", "max_issues_repo_head_hexsha": "949b9cc85abe558b84289d906b730605c2f32c3b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "simulator/src/spline.cpp", "max_forks_repo_name": "rollends/SE499", "max_forks_repo_head_hexsha": "949b9cc85abe558b84289d906b730605c2f32c3b", "max_forks_repo_licenses": ["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.2699490662, "max_line_length": 189, "alphanum_fraction": 0.5633655248, "num_tokens": 5891, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.47836376966800304}}
{"text": "//******************************************************************************\r\n//                            INTEL CONFIDENTIAL\r\n//  Copyright(C) 2008-2010 Intel Corporation. All Rights Reserved.\r\n//  The source code contained  or  described herein and all documents related to\r\n//  the source code (\"Material\") are owned by Intel Corporation or its suppliers\r\n//  or licensors.  Title to the  Material remains with  Intel Corporation or its\r\n//  suppliers and licensors. The Material contains trade secrets and proprietary\r\n//  and  confidential  information of  Intel or its suppliers and licensors. The\r\n//  Material  is  protected  by  worldwide  copyright  and trade secret laws and\r\n//  treaty  provisions. No part of the Material may be used, copied, reproduced,\r\n//  modified, published, uploaded, posted, transmitted, distributed or disclosed\r\n//  in any way without Intel's prior express written permission.\r\n//  No license  under any  patent, copyright, trade secret or other intellectual\r\n//  property right is granted to or conferred upon you by disclosure or delivery\r\n//  of the Materials,  either expressly, by implication, inducement, estoppel or\r\n//  otherwise.  Any  license  under  such  intellectual property  rights must be\r\n//  express and approved by Intel in writing.\r\n//\r\n//******************************************************************************\r\n// Content:\r\n//     Intel(R) Math Kernel Library (MKL) overloaded Boost/uBLAS prod()\r\n//******************************************************************************\r\n\r\n#ifndef _MKL_BOOST_UBLAS_MATRIX_PROD_\r\n#define _MKL_BOOST_UBLAS_MATRIX_PROD_\r\n\r\n#ifdef NDEBUG\r\n\r\n#include <boost/version.hpp>\r\n#if defined (BOOST_VERSION) && \\\r\n\t  ((BOOST_VERSION == 103401) \\\r\n\t|| (BOOST_VERSION == 103500) \\\r\n\t|| (BOOST_VERSION == 103600) \\\r\n\t|| (BOOST_VERSION == 103700) \\\r\n\t|| (BOOST_VERSION == 103800) \\\r\n\t|| (BOOST_VERSION == 103900) \\\r\n\t|| (BOOST_VERSION == 104000) \\\r\n\t|| (BOOST_VERSION == 104100))\r\n\r\n#include <boost/numeric/ublas/matrix.hpp>\r\n\r\n#include \"mkl_boost_ublas_gemm.hpp\"\r\n\r\nnamespace boost { namespace numeric { namespace ublas {\r\n\r\n    template<class T, class F, class A>\r\n    MKL_BOOST_UBLAS_INLINE\r\n    matrix<T,F,A>    // prod( m1, m2 )\r\n    prod(const matrix<T,F,A> &m1,\r\n         const matrix<T,F,A> &m2)\r\n    {\r\n        matrix<T,F,A> temporary(m1.size1(),m2.size2());\r\n        mkl::gemm(CblasNoTrans, CblasNoTrans, m1, m2, temporary);\r\n        return temporary;\r\n    }\r\n    template<class T, class F, class A>\r\n    MKL_BOOST_UBLAS_INLINE\r\n    matrix<T,F,A>    // prod( trans(m1), m2 )\r\n    prod(const matrix_unary2<matrix<T,F,A>,scalar_identity<T> > &m1,\r\n         const matrix<T,F,A> &m2)\r\n    {\r\n        matrix<T,F,A> temporary(m1.size1(),m2.size2());\r\n        mkl::gemm(CblasTrans, CblasNoTrans, m1, m2, temporary);\r\n        return temporary;\r\n    }\r\n    template<class T, class F, class A>\r\n    MKL_BOOST_UBLAS_INLINE\r\n    matrix<T,F,A>    // prod( trans(conj(m1)), m2 )\r\n    prod(const matrix_unary2<matrix_unary1<matrix<T,F,A>,scalar_conj<T> > const ,scalar_identity<T> > &m1,\r\n         const matrix<T,F,A> &m2)\r\n    {\r\n        matrix<T,F,A> temporary(m1.size1(),m2.size2());\r\n        mkl::gemm(CblasConjTrans, CblasNoTrans, m1, m2, temporary);\r\n        return temporary;\r\n    }\r\n    template<class T, class F, class A>\r\n    MKL_BOOST_UBLAS_INLINE\r\n    matrix<T,F,A>    // prod( conj(trans(m1)), m2 )\r\n    prod(const matrix_unary1<matrix_unary2<matrix<T,F,A>,scalar_identity<T> >,scalar_conj<T> > &m1,\r\n         const matrix<T,F,A> &m2)\r\n    {\r\n        matrix<T,F,A> temporary(m1.size1(),m2.size2());\r\n        mkl::gemm(CblasConjTrans, CblasNoTrans, m1, m2, temporary);\r\n        return temporary;\r\n    }\r\n    template<class T, class F, class A>\r\n    MKL_BOOST_UBLAS_INLINE\r\n    matrix<T,F,A>    // prod( m1, trans(m2) )\r\n    prod(const matrix<T,F,A> &m1,\r\n         const matrix_unary2<matrix<T,F,A>,scalar_identity<T> > &m2)\r\n    {\r\n        matrix<T,F,A> temporary(m1.size1(),m2.size2());\r\n        mkl::gemm(CblasNoTrans, CblasTrans, m1, m2, temporary);\r\n        return temporary;\r\n    }\r\n    template<class T, class F, class A>\r\n    MKL_BOOST_UBLAS_INLINE\r\n    matrix<T,F,A>    // prod( trans(m1), trans(m2) )\r\n    prod(const matrix_unary2<matrix<T,F,A>,scalar_identity<T> > &m1,\r\n         const matrix_unary2<matrix<T,F,A>,scalar_identity<T> > &m2)\r\n    {\r\n        matrix<T,F,A> temporary(m1.size1(),m2.size2());\r\n        mkl::gemm(CblasTrans, CblasTrans, m1, m2, temporary);\r\n        return temporary;\r\n    }\r\n    template<class T, class F, class A>\r\n    MKL_BOOST_UBLAS_INLINE\r\n    matrix<T,F,A>    // prod( trans(conj(m1)), trans(m2) )\r\n    prod(const matrix_unary2<matrix_unary1<matrix<T,F,A>,scalar_conj<T> > const ,scalar_identity<T> > &m1,\r\n         const matrix_unary2<matrix<T,F,A>,scalar_identity<T> > &m2)\r\n    {\r\n        matrix<T,F,A> temporary(m1.size1(),m2.size2());\r\n        mkl::gemm(CblasConjTrans, CblasTrans, m1, m2, temporary);\r\n        return temporary;\r\n    }\r\n    template<class T, class F, class A>\r\n    MKL_BOOST_UBLAS_INLINE\r\n    matrix<T,F,A>    // prod( conj(trans(m1)), trans(m2) )\r\n    prod(const matrix_unary1<matrix_unary2<matrix<T,F,A>,scalar_identity<T> >,scalar_conj<T> > &m1,\r\n         const matrix_unary2<matrix<T,F,A>,scalar_identity<T> > &m2)\r\n    {\r\n        matrix<T,F,A> temporary(m1.size1(),m2.size2());\r\n        mkl::gemm(CblasConjTrans, CblasTrans, m1, m2, temporary);\r\n        return temporary;\r\n    }\r\n    template<class T, class F, class A>\r\n    MKL_BOOST_UBLAS_INLINE\r\n    matrix<T,F,A>    // prod( m1, trans(conj(m2)) )\r\n    prod(const matrix<T,F,A> &m1,\r\n         const matrix_unary2<matrix_unary1<matrix<T,F,A>,scalar_conj<T> > const ,scalar_identity<T> > &m2)\r\n    {\r\n        matrix<T,F,A> temporary(m1.size1(),m2.size2());\r\n        mkl::gemm(CblasNoTrans, CblasConjTrans, m1, m2, temporary);\r\n        return temporary;\r\n    }\r\n    template<class T, class F, class A>\r\n    MKL_BOOST_UBLAS_INLINE\r\n    matrix<T,F,A>    // prod( trans(m1), trans(conj(m2)) )\r\n    prod(const matrix_unary2<matrix<T,F,A>,scalar_identity<T> > &m1,\r\n         const matrix_unary2<matrix_unary1<matrix<T,F,A>,scalar_conj<T> > const ,scalar_identity<T> > &m2)\r\n    {\r\n        matrix<T,F,A> temporary(m1.size1(),m2.size2());\r\n        mkl::gemm(CblasTrans, CblasConjTrans, m1, m2, temporary);\r\n        return temporary;\r\n    }\r\n    template<class T, class F, class A>\r\n    MKL_BOOST_UBLAS_INLINE\r\n    matrix<T,F,A>    // prod( trans(conj(m1)), trans(conj(m2)) )\r\n    prod(const matrix_unary2<matrix_unary1<matrix<T,F,A>,scalar_conj<T> > const ,scalar_identity<T> > &m1,\r\n         const matrix_unary2<matrix_unary1<matrix<T,F,A>,scalar_conj<T> > const ,scalar_identity<T> > &m2)\r\n    {\r\n        matrix<T,F,A> temporary(m1.size1(),m2.size2());\r\n        mkl::gemm(CblasConjTrans, CblasConjTrans, m1, m2, temporary);\r\n        return temporary;\r\n    }\r\n    template<class T, class F, class A>\r\n    MKL_BOOST_UBLAS_INLINE\r\n    matrix<T,F,A>    // prod( conj(trans(m1)), trans(conj(m2)) )\r\n    prod(const matrix_unary1<matrix_unary2<matrix<T,F,A>,scalar_identity<T> >,scalar_conj<T> > &m1,\r\n         const matrix_unary2<matrix_unary1<matrix<T,F,A>,scalar_conj<T> > const ,scalar_identity<T> > &m2)\r\n    {\r\n        matrix<T,F,A> temporary(m1.size1(),m2.size2());\r\n        mkl::gemm(CblasConjTrans, CblasConjTrans, m1, m2, temporary);\r\n        return temporary;\r\n    }\r\n    template<class T, class F, class A>\r\n    MKL_BOOST_UBLAS_INLINE\r\n    matrix<T,F,A>    // prod( m1, conj(trans(m2)) )\r\n    prod(const matrix<T,F,A> &m1,\r\n         const matrix_unary1<matrix_unary2<matrix<T,F,A>,scalar_identity<T> >,scalar_conj<T> > &m2)\r\n    {\r\n        matrix<T,F,A> temporary(m1.size1(),m2.size2());\r\n        mkl::gemm(CblasNoTrans, CblasConjTrans, m1, m2, temporary);\r\n        return temporary;\r\n    }\r\n    template<class T, class F, class A>\r\n    MKL_BOOST_UBLAS_INLINE\r\n    matrix<T,F,A>    // prod( trans(m1), conj(trans(m2)) )\r\n    prod(const matrix_unary2<matrix<T,F,A>,scalar_identity<T> > &m1,\r\n         const matrix_unary1<matrix_unary2<matrix<T,F,A>,scalar_identity<T> >,scalar_conj<T> > &m2)\r\n    {\r\n        matrix<T,F,A> temporary(m1.size1(),m2.size2());\r\n        mkl::gemm(CblasTrans, CblasConjTrans, m1, m2, temporary);\r\n        return temporary;\r\n    }\r\n    template<class T, class F, class A>\r\n    MKL_BOOST_UBLAS_INLINE\r\n    matrix<T,F,A>    // prod( trans(conj(m1)), conj(trans(m2)) )\r\n    prod(const matrix_unary2<matrix_unary1<matrix<T,F,A>,scalar_conj<T> > const ,scalar_identity<T> > &m1,\r\n         const matrix_unary1<matrix_unary2<matrix<T,F,A>,scalar_identity<T> >,scalar_conj<T> > &m2)\r\n    {\r\n        matrix<T,F,A> temporary(m1.size1(),m2.size2());\r\n        mkl::gemm(CblasConjTrans, CblasConjTrans, m1, m2, temporary);\r\n        return temporary;\r\n    }\r\n    template<class T, class F, class A>\r\n    MKL_BOOST_UBLAS_INLINE\r\n    matrix<T,F,A>    // prod( conj(trans(m1)), conj(trans(m2)) )\r\n    prod(const matrix_unary1<matrix_unary2<matrix<T,F,A>,scalar_identity<T> >,scalar_conj<T> > &m1,\r\n         const matrix_unary1<matrix_unary2<matrix<T,F,A>,scalar_identity<T> >,scalar_conj<T> > &m2)\r\n    {\r\n        matrix<T,F,A> temporary(m1.size1(),m2.size2());\r\n        mkl::gemm(CblasConjTrans, CblasConjTrans, m1, m2, temporary);\r\n        return temporary;\r\n    }\r\n\r\n}}}\r\n#endif  // BOOST_VERSION\r\n#endif  // NDEBUG\r\n#endif  // _MKL_BOOST_UBLAS_MATRIX_PROD_\r\n", "meta": {"hexsha": "4016f0eed6eec57c92a84f8768f74035cd5b78b7", "size": 9392, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "QR_benchmark/mkl_boost_ublas_matrix_prod.hpp", "max_stars_repo_name": "Lcrypto/QR-decomposition-Benchmark", "max_stars_repo_head_hexsha": "720733ebf1781a1b4152abef2d98103a4eab4975", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "QR_benchmark/mkl_boost_ublas_matrix_prod.hpp", "max_issues_repo_name": "Lcrypto/QR-decomposition-Benchmark", "max_issues_repo_head_hexsha": "720733ebf1781a1b4152abef2d98103a4eab4975", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "QR_benchmark/mkl_boost_ublas_matrix_prod.hpp", "max_forks_repo_name": "Lcrypto/QR-decomposition-Benchmark", "max_forks_repo_head_hexsha": "720733ebf1781a1b4152abef2d98103a4eab4975", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-11-24T01:56:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T06:14:12.000Z", "avg_line_length": 44.5118483412, "max_line_length": 107, "alphanum_fraction": 0.6185051107, "num_tokens": 2733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744717487329, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4783637670672806}}
{"text": "#pragma once\n#include <autoppl/util/var_expr_traits.hpp>\n#include <autoppl/variable.hpp>\n#include <autoppl/math/math.hpp>\n#include <iostream>\n#include <boost/uuid/uuid.hpp>\n#include <boost/uuid/uuid_generators.hpp>\n#include <boost/uuid/uuid_io.hpp>\n#include <autoppl/program_analysis/UncertainIntervals/IntervalAnalysis.hpp>\n#include <autoppl/global_data.hpp>\n\nnamespace ppl {\nnamespace expr {\n\n#if __cplusplus <= 201703L\ntemplate <class BinaryOp, class LHSVarExprType, class RHSVarExprType>\n#else\ntemplate <class BinaryOp, util::var_expr LHSVarExprType, util::var_expr RHSVarExprType>\n#endif\nstruct BinaryOpNode : \n    util::VarExpr<BinaryOpNode<BinaryOp, LHSVarExprType, RHSVarExprType>>\n{\n#if __cplusplus <= 201703L\n\tstatic_assert(util::assert_is_var_expr_v<LHSVarExprType>);\n\tstatic_assert(util::assert_is_var_expr_v<RHSVarExprType>);\n#endif\n\n\tusing value_t = std::common_type_t<\n\t\ttypename util::var_expr_traits<LHSVarExprType>::value_t,\n\t\ttypename util::var_expr_traits<RHSVarExprType>::value_t\n\t\t\t>;\n\n\tBinaryOpNode(const LHSVarExprType& lhs, const RHSVarExprType& rhs)\n\t\t: lhs_{lhs}, rhs_{rhs}\n\t{ assert(lhs.size() == rhs.size() || lhs.size() == 1 || rhs.size() == 1); }\n\n    value_t get_value(size_t i = 0) const {\n        auto lhs_value = lhs_.get_value(i);\n        auto rhs_value = rhs_.get_value(i);\n        return BinaryOp::evaluate(lhs_value, rhs_value);\n    }\n\n    size_t size() const { return std::max(lhs_.size(), rhs_.size()); }\n\n    /**\n     * Returns ad expression of the binary operation.\n     */\n    template <class VecRefType, class VecADVarType>\n    auto get_ad(const VecRefType& keys,\n                const VecADVarType& vars,\n                size_t idx = 0) const\n    {  \n        return BinaryOp::evaluate(lhs_.get_ad(keys, vars, idx),\n                                  rhs_.get_ad(keys, vars, idx));\n    }\n\n\n    std::set<boost::uuids::uuid> getDeps(){\n\tstd::set<boost::uuids::uuid> used_vars; \n\tstd::set<boost::uuids::uuid> lhs_used_vars = lhs_.getDeps(); //runtime polymorphism: whatever class mean_ is should have it's own getDeps() function\n\tused_vars.insert(lhs_used_vars.begin(),lhs_used_vars.end());\n\tstd::set<boost::uuids::uuid> rhs_used_vars = rhs_.getDeps();\n\tused_vars.insert(rhs_used_vars.begin(),rhs_used_vars.end());\n\treturn used_vars;\n    }\n\n\n   DeterministicInterval getInterval(){\n        return BinaryOp::getInterval(lhs_, rhs_);\n   }\n\nprivate:\n\tLHSVarExprType lhs_;\n\tRHSVarExprType rhs_;\n\n};\n\nstruct AddOp {\n\t\n\ttemplate <class LHSValueType, class RHSValueType>\n\tstatic auto evaluate(LHSValueType x, RHSValueType y)\n\t{\n\t\treturn x + y;\n\t}\n\n\ttemplate <class LHSValueType, class RHSValueType>\n\tstatic auto getInterval(LHSValueType x, RHSValueType y)\n\t{\n\t\treturn add(x.getInterval(),y.getInterval());\n\t}\n\n\n};\n\nstruct SubOp {\n\t\n\ttemplate <class LHSValueType, class RHSValueType>\n\tstatic auto evaluate(LHSValueType x, RHSValueType y)\n\t{\n\t\treturn x - y;\n\t}\n\n\ttemplate <class LHSValueType, class RHSValueType>\n\tstatic auto getInterval(LHSValueType x, RHSValueType y)\n\t{\n\t\treturn sub(x.getInterval(),y.getInterval());\n\t}\n\n\n\n};\n\nstruct MultOp {\n\t\n\ttemplate <class LHSValueType, class RHSValueType>\n\tstatic auto evaluate(LHSValueType x, RHSValueType y)\n\t{\n\t\treturn x * y;\n\t}\n\n\n\ttemplate <class LHSValueType, class RHSValueType>\n\tstatic auto getInterval(LHSValueType x, RHSValueType y)\n\t{\n\t\treturn mult(x.getInterval(),y.getInterval());\n\t}\n\n\n};\n\nstruct DivOp {\n\t\n\ttemplate <class LHSValueType, class RHSValueType>\n\tstatic auto evaluate(LHSValueType x, RHSValueType y)\n\t{\n\t\treturn x / y;\n\t}\n\n};\n\nstruct MaxOp {\n\t\n\ttemplate <class LHSValueType, class RHSValueType>\n\tstatic auto evaluate(LHSValueType x, RHSValueType y)\n\t{\n\t\treturn (x >= y) ? x : y;\n\t}\n\n\n\ttemplate <class LHSValueType, class RHSValueType>\n\tstatic auto getInterval(LHSValueType x, RHSValueType y)\n\t{\n\t\treturn max(x.getInterval(),y.getInterval());\n\t}\n\n};\n\nstruct MinOp {\n\t\n\ttemplate <class LHSValueType, class RHSValueType>\n\tstatic auto evaluate(LHSValueType x, RHSValueType y)\n\t{\n\t\treturn (x <= y) ? x : y;\n\t}\n\n\n\ttemplate <class LHSValueType, class RHSValueType>\n\tstatic auto getInterval(LHSValueType x, RHSValueType y)\n\t{\n\t\treturn min(x.getInterval(),y.getInterval());\n\t}\n\n\n};\n\n\n\nstruct GTEOp {\n\t\n\ttemplate <class LHSValueType, class RHSValueType>\n\tstatic auto evaluate(LHSValueType x, RHSValueType y)\n\t{\n\t\treturn (x >= y) ? LHSValueType(1.) : LHSValueType(0.);\n\t}\n\n\n\ttemplate <class LHSValueType, class RHSValueType>\n\tstatic auto getInterval(LHSValueType x, RHSValueType y)\n\t{\n\t\treturn DeterministicInterval(0.,1.);\n\t}\n\n\n\n};\n\n\nstruct LTEOp {\n\t\n\ttemplate <class LHSValueType, class RHSValueType>\n\tstatic auto evaluate(LHSValueType x, RHSValueType y)\n\t{\n\t\treturn (x <= y) ? LHSValueType(1.) : LHSValueType(0.);\n\t}\n\n\ttemplate <class LHSValueType, class RHSValueType>\n\tstatic auto getInterval(LHSValueType x, RHSValueType y)\n\t{\n\t\treturn DeterministicInterval(0.,1.);\n\t}\n\n\n};\n\n\nstruct GTOp {\n\n\ttemplate <class LHSValueType, class RHSValueType>\n\tstatic auto evaluate(LHSValueType x, RHSValueType y)\n\t{\n\t\treturn (x > y) ? LHSValueType(1.) : LHSValueType(0.);\n\t}\n\n\ttemplate <class LHSValueType, class RHSValueType>\n\tstatic auto getInterval(LHSValueType x, RHSValueType y)\n\t{\n\t\treturn DeterministicInterval(0.,1.);\n\t}\n\n\n};\n\n\n\nstruct LTOp {\n\n\ttemplate <class LHSValueType, class RHSValueType>\n\tstatic auto evaluate(LHSValueType x, RHSValueType y)\n\t{\n\t\treturn (x < y) ? LHSValueType(1.) : LHSValueType(0.);\n\t}\n\n\ttemplate <class LHSValueType, class RHSValueType>\n\tstatic auto getInterval(LHSValueType x, RHSValueType y)\n\t{\n\t\treturn DeterministicInterval(0,1);\n\t}\n\n\n};\n\nstruct EQOp {\n\t\n\ttemplate <class LHSValueType, class RHSValueType>\n\tstatic auto evaluate(LHSValueType x, RHSValueType y)\n\t{\n\t\treturn (x == y) ? LHSValueType(1.) : LHSValueType(0.);\n\t}\n\n\ttemplate <class LHSValueType, class RHSValueType>\n\tstatic auto getInterval(LHSValueType x, RHSValueType y)\n\t{\n\t\treturn DeterministicInterval(0,1);\n\t}\n\n};\n\n\nstruct SqrtOp {\n\t\n\ttemplate <class LHSValueType, class RHSValueType>\n\tstatic auto evaluate(LHSValueType x, RHSValueType y)\n\t{\n\t\treturn ppl::math::sqrt(x*y);\n\t}\n\n\ttemplate <class LHSValueType, class RHSValueType>\n\tstatic auto getInterval(LHSValueType x, RHSValueType y)\n\t{\n\t\treturn sqrt_prod(x.getInterval(),y.getInterval());\n\t}\n\n\n};\n\n\nstruct BooleanSwitchOp {\n\t//left value is a boolean switch\n\ttemplate <class BooleanSwitchType, class RHSValueType>\n\tstatic auto evaluate(BooleanSwitchType x, RHSValueType y)\n\t{\n\t\treturn x*y;\n\t}\n\n\ttemplate <class BooleanSwitchType, class RHSValueType>\n\tstatic auto getInterval(BooleanSwitchType x, RHSValueType y)\n\t{\n\t\treturn y.getInterval();\n\t}\n\n};\n\n\n\nstruct MixtureMaxOp {\n\t\n\ttemplate <class LHSValueType, class RHSValueType>\n\tstatic auto evaluate(LHSValueType x, RHSValueType y)\n\t{\n\t\treturn (x >= y) ? x : y;\n\t}\n\n\n\ttemplate <class LHSValueType, class RHSValueType>\n\tstatic auto getInterval(LHSValueType x, RHSValueType y)\n\t{\n\t\treturn union_(x.getInterval(),y.getInterval());\n\t}\n\n};\n\n\n\n} // namespace expr\n} // namespace ppl\n", "meta": {"hexsha": "34a77568c4d6f280a1f9630346f5004746c41315", "size": 6956, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "autoppl/expression/variable/binop.hpp", "max_stars_repo_name": "uiuc-arc/Statheros", "max_stars_repo_head_hexsha": "ca4d3057030a594550ba1d238be695b6a04b0d8f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "autoppl/expression/variable/binop.hpp", "max_issues_repo_name": "uiuc-arc/Statheros", "max_issues_repo_head_hexsha": "ca4d3057030a594550ba1d238be695b6a04b0d8f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "autoppl/expression/variable/binop.hpp", "max_forks_repo_name": "uiuc-arc/Statheros", "max_forks_repo_head_hexsha": "ca4d3057030a594550ba1d238be695b6a04b0d8f", "max_forks_repo_licenses": ["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.3374233129, "max_line_length": 149, "alphanum_fraction": 0.7162162162, "num_tokens": 1813, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.47836376446655826}}
{"text": "// Copyright (c) 2018-2019 FRC Team 3512. All Rights Reserved.\n\n#pragma once\n\n#include <Eigen/Core>\n#include <frc/controller/StateSpaceLoop.h>\n\n#include \"Constants.hpp\"\n#include \"control/ElevatorCoeffs.hpp\"\n#include \"control/TrapezoidalMotionProfile.hpp\"\n\nclass ElevatorController {\npublic:\n    // State tolerances in meters and meters/sec respectively.\n    static constexpr double kPositionTolerance = 0.05;\n    static constexpr double kVelocityTolerance = 2.0;\n\n    ElevatorController();\n\n    ElevatorController(const ElevatorController&) = delete;\n    ElevatorController& operator=(const ElevatorController&) = delete;\n\n    void Enable();\n    void Disable();\n\n    void SetGoal(double goal);\n\n    /**\n     * Sets the references.\n     *\n     * @param position Position of the carriage in meters.\n     * @param velocity Velocity of the carriage in meters per second.\n     */\n    void SetReferences(units::meter_t position,\n                       units::meters_per_second_t velocity);\n\n    bool AtReferences() const;\n\n    /**\n     * Sets the current encoder measurement.\n     *\n     * @param measuredPosition Position of the carriage in meters.\n     */\n    void SetMeasuredPosition(double measuredPosition);\n\n    /**\n     * Returns the control loop calculated voltage.\n     */\n    double ControllerVoltage() const;\n\n    /**\n     * Returns the estimated position.\n     */\n    double EstimatedPosition() const;\n\n    /**\n     * Returns the estimated velocity.\n     */\n    double EstimatedVelocity() const;\n\n    /**\n     * Returns the error between the position reference and the position\n     * estimate.\n     */\n    double PositionError() const;\n\n    /**\n     * Returns the error between the velocity reference and the velocity\n     * estimate.\n     */\n    double VelocityError() const;\n\n    /**\n     * Returns the current reference set by the profile\n     */\n    double PositionReference();\n\n    /**\n     * Executes the control loop for a cycle.\n     */\n    void Update(void);\n\n    /**\n     * Resets any internal state.\n     */\n    void Reset(void);\n\nprivate:\n    // The current sensor measurement.\n    Eigen::Matrix<double, 1, 1> m_Y;\n    double m_estimatedPosition = 0.0;\n    TrapezoidalMotionProfile::State m_goal;\n\n    TrapezoidalMotionProfile::Constraints constraints{kElevatorMaxV,\n                                                      kElevatorMaxA};\n    TrapezoidalMotionProfile m_positionProfile{constraints, {0_m, 0_mps}};\n\n    TrapezoidalMotionProfile::State m_profiledReference;\n\n    // The control loop.\n    frc::StateSpaceLoop<2, 1, 1> m_loop{MakeElevatorLoop()};\n\n    bool m_atReferences = false;\n};\n", "meta": {"hexsha": "87c4e917f8edb95812b84b67429797f8824c351e", "size": 2613, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/main/include/control/ElevatorController.hpp", "max_stars_repo_name": "Team3512/Robot-2018.1", "max_stars_repo_head_hexsha": "67486bad03d3bb49cea2b36d764bf8b4bf131df9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-05-19T07:54:41.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-19T07:54:41.000Z", "max_issues_repo_path": "src/main/include/control/ElevatorController.hpp", "max_issues_repo_name": "Team3512/Robot-2018.1", "max_issues_repo_head_hexsha": "67486bad03d3bb49cea2b36d764bf8b4bf131df9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/include/control/ElevatorController.hpp", "max_forks_repo_name": "Team3512/Robot-2018.1", "max_forks_repo_head_hexsha": "67486bad03d3bb49cea2b36d764bf8b4bf131df9", "max_forks_repo_licenses": ["BSD-3-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.8857142857, "max_line_length": 74, "alphanum_fraction": 0.6578645235, "num_tokens": 572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744584140003, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4783637592651132}}
{"text": "#include <stan/math/prim/mat.hpp>\n#include <gtest/gtest.h>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/math/distributions.hpp>\n\nTEST(ProbDistributionsLkjCov, testIdentity) {\n  boost::random::mt19937 rng;\n  unsigned int K = 4;\n  Eigen::MatrixXd Sigma(K, K);\n  Sigma.setZero();\n  Sigma.diagonal().setOnes();\n  double mu = 0;\n  Eigen::VectorXd muV = Eigen::VectorXd::Zero(K);\n  double sd = 1;\n  Eigen::VectorXd sdV = Eigen::VectorXd::Ones(K);\n  double eta = stan::math::uniform_rng(0.5, 1.5, rng);\n  double f = stan::math::do_lkj_constant(eta, K)\n             + K * stan::math::lognormal_lpdf(1, 0, 1);\n  EXPECT_FLOAT_EQ(f, stan::math::lkj_cov_lpdf(Sigma, mu, sd, eta));\n  EXPECT_FLOAT_EQ(f, stan::math::lkj_cov_lpdf(Sigma, muV, sdV, eta));\n  eta = 1.0;\n  f = stan::math::do_lkj_constant(eta, K)\n      + K * stan::math::lognormal_lpdf(1, 0, 1);\n  EXPECT_FLOAT_EQ(f, stan::math::lkj_cov_lpdf(Sigma, mu, sd, eta));\n  EXPECT_FLOAT_EQ(f, stan::math::lkj_cov_lpdf(Sigma, muV, sdV, eta));\n}\n\nTEST(ProbDistributionsLkjCov, testHalf) {\n  boost::random::mt19937 rng;\n  unsigned int K = 4;\n  Eigen::MatrixXd Sigma(K, K);\n  Sigma.setConstant(0.5);\n  Sigma.diagonal().setOnes();\n  double mu = 0;\n  Eigen::VectorXd muV = Eigen::VectorXd::Zero(K);\n  double sd = 1;\n  Eigen::VectorXd sdV = Eigen::VectorXd::Ones(K);\n  double eta = stan::math::uniform_rng(0.5, 1.5, rng);\n  double f = stan::math::do_lkj_constant(eta, K)\n             + K * stan::math::lognormal_lpdf(1, 0, 1)\n             + (eta - 1.0) * log(0.3125);\n  EXPECT_FLOAT_EQ(f, stan::math::lkj_cov_lpdf(Sigma, mu, sd, eta));\n  EXPECT_FLOAT_EQ(f, stan::math::lkj_cov_lpdf(Sigma, muV, sdV, eta));\n  eta = 1.0;\n  f = stan::math::do_lkj_constant(eta, K)\n      + K * stan::math::lognormal_lpdf(1, 0, 1);\n  EXPECT_FLOAT_EQ(f, stan::math::lkj_cov_lpdf(Sigma, mu, sd, eta));\n  EXPECT_FLOAT_EQ(f, stan::math::lkj_cov_lpdf(Sigma, muV, sdV, eta));\n}\n\nTEST(ProbDistributionsLkjCov, ErrorChecks) {\n  boost::random::mt19937 rng;\n  unsigned int K = 4;\n  Eigen::MatrixXd Sigma(K, K);\n  Sigma.setZero();\n  Sigma.diagonal().setOnes();\n  double mu = 0;\n  Eigen::VectorXd muV = Eigen::VectorXd::Zero(K);\n  double sd = 1;\n  Eigen::VectorXd sdV = Eigen::VectorXd::Ones(K);\n  double eta = stan::math::uniform_rng(0.5, 1.5, rng);\n  EXPECT_NO_THROW(stan::math::lkj_cov_lpdf(Sigma, mu, sd, eta));\n\n  // Error checks for non vectorized version.\n\n  EXPECT_NO_THROW(stan::math::lkj_cov_lpdf(Sigma, -1, sd, eta));\n  EXPECT_THROW(\n      stan::math::lkj_cov_lpdf(Sigma, stan::math::NOT_A_NUMBER, sd, eta),\n      std::domain_error);\n  EXPECT_THROW(stan::math::lkj_cov_lpdf(Sigma, stan::math::INFTY, sd, eta),\n               std::domain_error);\n  EXPECT_THROW(\n      stan::math::lkj_cov_lpdf(Sigma, stan::math::NEGATIVE_INFTY, sd, eta),\n      std::domain_error);\n\n  EXPECT_THROW(stan::math::lkj_cov_lpdf(Sigma, mu, -1, eta), std::domain_error);\n  EXPECT_THROW(\n      stan::math::lkj_cov_lpdf(Sigma, mu, stan::math::NOT_A_NUMBER, eta),\n      std::domain_error);\n  EXPECT_THROW(stan::math::lkj_cov_lpdf(Sigma, mu, stan::math::INFTY, eta),\n               std::domain_error);\n  EXPECT_THROW(\n      stan::math::lkj_cov_lpdf(Sigma, mu, stan::math::NEGATIVE_INFTY, eta),\n      std::domain_error);\n\n  EXPECT_THROW(stan::math::lkj_cov_lpdf(Sigma, mu, sd, -1), std::domain_error);\n  EXPECT_THROW(\n      stan::math::lkj_cov_lpdf(Sigma, muV, sd, stan::math::NOT_A_NUMBER),\n      std::domain_error);\n  EXPECT_NO_THROW(stan::math::lkj_cov_lpdf(Sigma, mu, sd, stan::math::INFTY));\n  EXPECT_THROW(\n      stan::math::lkj_cov_lpdf(Sigma, mu, sd, stan::math::NEGATIVE_INFTY),\n      std::domain_error);\n\n  // Vectorized.\n\n  Eigen::VectorXd muV1 = -muV;\n  EXPECT_NO_THROW(stan::math::lkj_cov_lpdf(Sigma, muV1, sdV, eta));\n  muV1 = stan::math::NOT_A_NUMBER * muV;\n  EXPECT_THROW(stan::math::lkj_cov_lpdf(Sigma, muV1, sdV, eta),\n               std::domain_error);\n  muV1 = stan::math::INFTY * muV;\n  EXPECT_THROW(stan::math::lkj_cov_lpdf(Sigma, muV1, sdV, eta),\n               std::domain_error);\n  muV1 = stan::math::NEGATIVE_INFTY * muV;\n  EXPECT_THROW(stan::math::lkj_cov_lpdf(Sigma, muV1, sdV, eta),\n               std::domain_error);\n\n  Eigen::VectorXd sdV1 = -sdV;\n  EXPECT_THROW(stan::math::lkj_cov_lpdf(Sigma, muV, sdV1, eta),\n               std::domain_error);\n  sdV1 = stan::math::NOT_A_NUMBER * sdV;\n  EXPECT_THROW(stan::math::lkj_cov_lpdf(Sigma, muV, sdV1, eta),\n               std::domain_error);\n  sdV1 = stan::math::INFTY * sdV;\n  EXPECT_THROW(stan::math::lkj_cov_lpdf(Sigma, muV, sdV1, eta),\n               std::domain_error);\n  sdV1 = stan::math::NEGATIVE_INFTY * sdV;\n  EXPECT_THROW(stan::math::lkj_cov_lpdf(Sigma, muV, sdV1, eta),\n               std::domain_error);\n\n  EXPECT_THROW(stan::math::lkj_cov_lpdf(Sigma, muV, sdV, -1),\n               std::domain_error);\n  EXPECT_THROW(\n      stan::math::lkj_cov_lpdf(Sigma, muV, sdV, stan::math::NOT_A_NUMBER),\n      std::domain_error);\n  EXPECT_NO_THROW(stan::math::lkj_cov_lpdf(Sigma, muV, sdV, stan::math::INFTY));\n  EXPECT_THROW(\n      stan::math::lkj_cov_lpdf(Sigma, muV, sdV, stan::math::NEGATIVE_INFTY),\n      std::domain_error);\n}\n", "meta": {"hexsha": "646194aa37972cc47abcaf075125bb24cba5c89a", "size": 5104, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/prim/mat/prob/lkj_cov_test.cpp", "max_stars_repo_name": "peterwicksstringfield/math", "max_stars_repo_head_hexsha": "5ce0718ea64f2cca8b2f1e4eeac27a2dc2bd246e", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/unit/math/prim/mat/prob/lkj_cov_test.cpp", "max_issues_repo_name": "peterwicksstringfield/math", "max_issues_repo_head_hexsha": "5ce0718ea64f2cca8b2f1e4eeac27a2dc2bd246e", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/unit/math/prim/mat/prob/lkj_cov_test.cpp", "max_forks_repo_name": "peterwicksstringfield/math", "max_forks_repo_head_hexsha": "5ce0718ea64f2cca8b2f1e4eeac27a2dc2bd246e", "max_forks_repo_licenses": ["BSD-3-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.6666666667, "max_line_length": 80, "alphanum_fraction": 0.6586990596, "num_tokens": 1722, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195385342971, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.47817233267071335}}
{"text": "// g++ cdf.cpp  -lboost_unit_test_framework\n\n#include <cmath>\n#include <boost/random.hpp>\n#include <boost/test/unit_test.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/accumulators/numeric/functional/vector.hpp>\n#include <boost/accumulators/numeric/functional/complex.hpp>\n#include <boost/accumulators/numeric/functional/valarray.hpp>\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/p_square_cumul_dist.hpp>\n\n#include <vector>\n#include <utility>\n\nusing namespace boost;\nusing namespace boost::accumulators;\n//using namespace unit_test;\n\ntypedef iterator_range<std::vector<std::pair<double, double> >::iterator > histogram_type;\n\nstd::vector<std::pair<double, int> mapdata(histogram_type& h)\n{\n  const double mapToBlackPct = 0.2;\n  const int otherSteps = 15;\n  const double stepSizePct = (1-mapToBlackPct) / otherSteps;\n  std::cout << \"stepSizePct = \" << stepSizePct << std::endl;\n\n  std::vector<std::pair<double, int> mapping;\n\n  for (std::size_t i = 0; i < h.size(); ++i)\n    {\n      int step = -1;\n      if(h[i].second < mapToBlackPct)\n\tstep = 0;\n      else\n\tstep = std::min(otherSteps, ceil((h[i].second - mapToBlackPct) / stepSizePct));\n      std::cout << \"[\" << h[i].first << \",\" << h[i].second << \"]\"  << \" ==> \" << step << std::endl;\n\n      // NOTE: Using -1 here so that the searches are easier later\n      mapping.push_back(std::make_pair(h[i].first, step-1));\n    }\n\n  return mapping;\n}\n\nint main(void)\n{\n\n  // tolerance in %\n  double epsilon = 3;\n\n  typedef accumulator_set<double, stats<tag::p_square_cumulative_distribution> > accumulator_t;\n\n  accumulator_t acc(tag::p_square_cumulative_distribution::num_cells = 100);\n\n  // two random number generators\n  boost::lagged_fibonacci607 rng;\n  boost::normal_distribution<> mean_sigma(0,1);\n  boost::variate_generator<boost::lagged_fibonacci607&, boost::normal_distribution<> > normal(rng, mean_sigma);\n\n  for (std::size_t i=0; i<100000; ++i)\n    {\n      acc(normal());\n    }\n\n  histogram_type histogram = p_square_cumulative_distribution(acc);\n  //histogram_type histogram;\n\n  for (std::size_t i = 0; i < histogram.size(); ++i)\n    {\n      std::cout << \"[\" << histogram[i].first << \",\" << histogram[i].second << \"]\" << std::endl;\n\n      /*\n      // problem with small results: epsilon is relative (in percent), not absolute!\n      if ( histogram[i].second > 0.001 )\n        BOOST_CHECK_CLOSE( 0.5 * (1.0 + erf( histogram[i].first / sqrt(2.0) )), histogram[i].second, epsilon );\n      */\n    }\n\n  std::cout << \"*************************\" << std::endl;\n  std::vector<std::pair<double, int> mapping (mapdata(histogram));\n\n  std::vector<double> vals;\n  vals.push_back(-0.75);\n  vals.push_back(-0.25);\n  vals.push_back(0);\n  vals.push_back(0.5);\n  vals.push_back(2);\n  //vals.push_back(4.2);\n\n  for(std::vector<double>::const_iterator iter; iter!=vals.end(); ++iter)\n    {\n       \n    }\n\n  return 0;\n}\n", "meta": {"hexsha": "6a22253ce1317fb893a702c0f96215506d5688b1", "size": 2973, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/cdf.cpp", "max_stars_repo_name": "klaricmn/snippets", "max_stars_repo_head_hexsha": "a1ae04c13a2209dee013284358d2d987bb0fb4fc", "max_stars_repo_licenses": ["MIT"], "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/cdf.cpp", "max_issues_repo_name": "klaricmn/snippets", "max_issues_repo_head_hexsha": "a1ae04c13a2209dee013284358d2d987bb0fb4fc", "max_issues_repo_licenses": ["MIT"], "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/cdf.cpp", "max_forks_repo_name": "klaricmn/snippets", "max_forks_repo_head_hexsha": "a1ae04c13a2209dee013284358d2d987bb0fb4fc", "max_forks_repo_licenses": ["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.73, "max_line_length": 111, "alphanum_fraction": 0.6646485032, "num_tokens": 809, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195152660687, "lm_q2_score": 0.6513548714339145, "lm_q1q2_score": 0.47817232248325775}}
{"text": "/*\n * Copyright (c) 2013-2014 Masahide Kashiwagi (kashi@waseda.jp)\n */\n\n#ifndef RK_HPP\n#define RK_HPP\n\n// Runge-Kutta\n\n#include <iostream>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n\nnamespace kv {\n\nnamespace ub = boost::numeric::ublas;\n\ntemplate <class T, class F>\nvoid\nrk(F f, ub::vector<T>& init, T start, T end) {\n\n\tub::vector<T> x, dx1, dx2, dx3, dx4, x1, x2, x3;\n\n\tT t = start;\n\tT dt = end - start;\n\n\tx = init;\n\tdx1 = f(x, t) * dt;\n\tx1 = x + dx1 / 2.;\n\tdx2 = f(x1, t + dt/2.) * dt;\n\tx2 = x + dx2 / 2.;\n\tdx3 = f(x2, t + dt/2.) * dt;\n\tx3 = x + dx3;\n\tdx4 = f(x3, t + dt) * dt;\n\n\tinit = x + dx1 / 6. + dx2 / 3. + dx3 / 3. + dx4 / 6.;\n}\n\n} // namespace kv\n\n#endif // RK_HPP\n", "meta": {"hexsha": "22562d34c6605f849f67a9f676c08a9fe79860ae", "size": 716, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "kv/rk.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/rk.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/rk.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": 17.0476190476, "max_line_length": 63, "alphanum_fraction": 0.5726256983, "num_tokens": 285, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.47817232012435823}}
{"text": "#define BOOST_TEST_MODULE SplineTest\n/*\n * ########################################################################\n * The contents of this file is free and unencumbered software released into the\n * public domain. For more information, please refer to <http://unlicense.org/>\n * ########################################################################\n */\n\n#include <okruz/bspline/interpolation/interpolation.h>\n#include <okruz/bspline/support/Support.h>\n\n#include <boost/test/included/unit_test.hpp>\n#include <boost/test/tools/floating_point_comparison.hpp>\n\n#ifdef OKRUZ_BSPLINE_INTERPOLATION_USE_EIGEN\ntemplate <typename T, size_t order>\nvoid testInterpolationEigen(T tol) {\n  using Spline = okruz::bspline::Spline<T, order>;\n  using Support = okruz::bspline::support::Support<T>;\n  using Grid = okruz::bspline::support::Grid<T>;\n  using Construction = okruz::bspline::support::Construction;\n\n  const Grid grid(std::vector<T>{-3.0l, -2.5l, -1.5l, -1.0l, 0.0l, 0.5l, 1.5l,\n                                 2.5l, 3.5l, 4.0l, 5.0l});\n  const Support x(grid, Construction::WHOLE_GRID);\n  const std::vector<T> y{-3.0l, -2.5l, -1.5l, -1.0l, 0.0l, -0.5l,\n                         -1.5l, -2.5l, -3.5l, -4.0l, 3.0l};\n  Spline s =\n      okruz::bspline::interpolation::interpolate_using_eigen<T, order>(x, y);\n  for (size_t i = 0; i < x.size(); i++) {\n    BOOST_CHECK_SMALL(s(x[i]) - y[i], tol);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(TestInterpolationEigen) {\n  testInterpolationEigen<double, 1>(2.0e-14);\n  testInterpolationEigen<double, 2>(2.0e-14);\n  testInterpolationEigen<double, 3>(2.0e-14);\n  testInterpolationEigen<double, 4>(2.0e-14);\n\n  if constexpr (sizeof(long double) != sizeof(double)) {\n    testInterpolationEigen<long double, 1>(1.0e-17l);\n    testInterpolationEigen<long double, 2>(1.0e-17l);\n    testInterpolationEigen<long double, 3>(1.0e-17l);\n    testInterpolationEigen<long double, 4>(1.0e-17l);\n  }\n}\n#endif\n\n#ifdef OKRUZ_BSPLINE_INTERPOLATION_USE_ARMADILLO\ntemplate <size_t order>\nvoid testInterpolationArmadillo(double tol) {\n  using Spline = okruz::bspline::Spline<double, order>;\n  using Support = okruz::bspline::support::Support<double>;\n  using Grid = okruz::bspline::support::Grid<double>;\n  using Construction = okruz::bspline::support::Construction;\n\n  const Grid grid(std::vector<double>{-3.0l, -2.5l, -1.5l, -1.0l, 0.0l, 0.5l,\n                                      1.5l, 2.5l, 3.5l, 4.0l, 5.0l});\n  const Support x(grid, Construction::WHOLE_GRID);\n  const std::vector<double> y{-3.0l, -2.5l, -1.5l, -1.0l, 0.0l, -0.5l,\n                              -1.5l, -2.5l, -3.5l, -4.0l, 3.0l};\n  Spline s =\n      okruz::bspline::interpolation::interpolate_using_armadillo<order>(x, y);\n  for (size_t i = 0; i < x.size(); i++) {\n    BOOST_CHECK_SMALL(s(x[i]) - y[i], tol);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(TestInterpolationArmadillo) {\n  testInterpolationArmadillo<1>(2.0e-14);\n  testInterpolationArmadillo<2>(2.0e-14);\n  testInterpolationArmadillo<3>(2.0e-14);\n  testInterpolationArmadillo<4>(2.0e-14);\n}\n#endif\n", "meta": {"hexsha": "56f405e15208d9ce33f99cfc339f015208105b34", "size": 3015, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/okruz/bspline/interpolation/interpolation-test.cpp", "max_stars_repo_name": "okruz/BSplinebasis", "max_stars_repo_head_hexsha": "2dd31b9e48730966d3097035b5bed2f7dbbbe46b", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-29T17:30:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T17:30:17.000Z", "max_issues_repo_path": "tests/okruz/bspline/interpolation/interpolation-test.cpp", "max_issues_repo_name": "okruz/BSplinebasis", "max_issues_repo_head_hexsha": "2dd31b9e48730966d3097035b5bed2f7dbbbe46b", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2021-11-15T20:50:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-31T20:32:44.000Z", "max_forks_repo_path": "tests/okruz/bspline/interpolation/interpolation-test.cpp", "max_forks_repo_name": "okruz/BSplinebasis", "max_forks_repo_head_hexsha": "2dd31b9e48730966d3097035b5bed2f7dbbbe46b", "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": 39.1558441558, "max_line_length": 80, "alphanum_fraction": 0.6371475954, "num_tokens": 995, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.734119526900183, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.4781723201243581}}
{"text": "/*    Copyright (c) 2010-2015, Delft University of Technology\r\n *    All rights reserved.\r\n *\r\n *    Redistribution and use in source and binary forms, with or without modification, are\r\n *    permitted provided that the following conditions are met:\r\n *      - Redistributions of source code must retain the above copyright notice, this list of\r\n *        conditions and the following disclaimer.\r\n *      - Redistributions in binary form must reproduce the above copyright notice, this list of\r\n *        conditions and the following disclaimer in the documentation and/or other materials\r\n *        provided with the distribution.\r\n *      - Neither the name of the Delft University of Technology nor the names of its contributors\r\n *        may be used to endorse or promote products derived from this software without specific\r\n *        prior written permission.\r\n *\r\n *    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS\r\n *    OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\r\n *    MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\r\n *    COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\r\n *    EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\r\n *    GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\r\n *    AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\r\n *    NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\r\n *    OF THE POSSIBILITY OF SUCH DAMAGE.\r\n *\r\n *    Changelog\r\n *      YYMMDD    Author            Comment\r\n *      140219    E. Brandon        File copied from Newton-Raphson unit test.\r\n *      150417    D. Dirkx          Made modifications for templated root finding.\r\n *\r\n *    References\r\n *\r\n *    Notes\r\n *\r\n */\r\n\r\n#include <boost/bind.hpp>\r\n#include <boost/make_shared.hpp>\r\n#include <boost/test/floating_point_comparison.hpp>\r\n#include <boost/test/unit_test.hpp>\r\n\r\n#include \"Tudat/Mathematics/RootFinders/secantRootFinder.h\"\r\n#include \"Tudat/Mathematics/RootFinders/UnitTests/testFunction1.h\"\r\n#include \"Tudat/Mathematics/RootFinders/UnitTests/testFunction2.h\"\r\n#include \"Tudat/Mathematics/RootFinders/UnitTests/testFunction3.h\"\r\n#include \"Tudat/Mathematics/RootFinders/UnitTests/testFunctionWithLargeRootDifference.h\"\r\n#include \"Tudat/Mathematics/RootFinders/UnitTests/testFunctionWithZeroRoot.h\"\r\n\r\nnamespace tudat\r\n{\r\nnamespace unit_tests\r\n{\r\n\r\nBOOST_AUTO_TEST_SUITE( testsuite_rootfinders )\r\n\r\nusing namespace tudat;\r\nusing namespace root_finders;\r\nusing namespace root_finders::termination_conditions;\r\n\r\n//! Check if Secant method converges on test function #1 (TestFunction1).\r\nBOOST_AUTO_TEST_CASE( test_secantRootFinder_testFunction1 )\r\n{\r\n    // Create object containing the test functions.\r\n    boost::shared_ptr< TestFunction1 > testFunction = boost::make_shared< TestFunction1 >( 0 );\r\n\r\n    // The termination condition.\r\n    SecantRootFinder::TerminationFunction terminationConditionFunction =\r\n            boost::bind(\r\n                &RootAbsoluteToleranceTerminationCondition< double >::checkTerminationCondition,\r\n                boost::make_shared< RootAbsoluteToleranceTerminationCondition< double > >(\r\n                    testFunction->getTrueRootAccuracy( ) ), _1, _2, _3, _4, _5 );\r\n\r\n    // Test Secant object. Use the default value of the first initial guess.\r\n    SecantRootFinder secantRootFinder( terminationConditionFunction );\r\n\r\n    // Let the Secant method search for the root.\r\n    const double root = secantRootFinder.execute( testFunction, testFunction->getInitialGuess( ) );\r\n\r\n    // Check if the result is within the requested accuracy.\r\n    BOOST_CHECK_CLOSE_FRACTION( root, testFunction->getTrueRootLocation( ), 1.0e-15 );\r\n    BOOST_CHECK_LT( testFunction->evaluate( root ), testFunction->getTrueRootAccuracy( ) );\r\n}\r\n\r\n//! Check if Secant method converges on test function #2 (TestFunction2).\r\nBOOST_AUTO_TEST_CASE( test_secantRootFinder_testFunction2 )\r\n{\r\n    // Create object containing the test functions.\r\n    boost::shared_ptr< TestFunction2 > testFunction = boost::make_shared< TestFunction2 >( 0 );\r\n\r\n    // The termination condition.\r\n    SecantRootFinder::TerminationFunction terminationConditionFunction =\r\n            boost::bind(\r\n                &RootAbsoluteToleranceTerminationCondition< double >::checkTerminationCondition,\r\n                boost::make_shared< RootAbsoluteToleranceTerminationCondition< double > >(\r\n                    testFunction->getTrueRootAccuracy( ) ), _1, _2, _3, _4, _5 );\r\n\r\n    // Test Secant object. Use the default value of the first initial guess.\r\n    SecantRootFinder secantRootFinder( terminationConditionFunction );\r\n\r\n    // Let the Secant method search for the root.\r\n    const double root = secantRootFinder.execute( testFunction, testFunction->getInitialGuess( ) );\r\n\r\n    // Check if the result is within the requested accuracy.\r\n    BOOST_CHECK_CLOSE_FRACTION( root, testFunction->getTrueRootLocation( ), 1.0e-15 );\r\n    BOOST_CHECK_LT( testFunction->evaluate( root ), testFunction->getTrueRootAccuracy( ) );\r\n}\r\n\r\n//! Check if Secant method converges on test function #3 (TestFunction3).\r\nBOOST_AUTO_TEST_CASE( test_secantRootFinder_testFunction3 )\r\n{\r\n    // Create object containing the test functions.\r\n    boost::shared_ptr< TestFunction3 > testFunction = boost::make_shared< TestFunction3 >( 0 );\r\n\r\n    // The termination condition.\r\n    SecantRootFinder::TerminationFunction terminationConditionFunction =\r\n            boost::bind(\r\n                &RootAbsoluteToleranceTerminationCondition< double >::checkTerminationCondition,\r\n                boost::make_shared< RootAbsoluteToleranceTerminationCondition< double > >(\r\n                    testFunction->getTrueRootAccuracy( ) ), _1, _2, _3, _4, _5 );\r\n\r\n    // Test Secant object. Use the default value of the first initial guess.\r\n    SecantRootFinder secantRootFinder( terminationConditionFunction );\r\n\r\n    // Let the Secant method search for the root.\r\n    const double root = secantRootFinder.execute( testFunction, testFunction->getInitialGuess( ) );\r\n\r\n    // Check if the result is within the requested accuracy.\r\n    BOOST_CHECK_CLOSE_FRACTION( root, testFunction->getTrueRootLocation( ), 1.0e-15 );\r\n    BOOST_CHECK_LT( testFunction->evaluate( root ), testFunction->getTrueRootAccuracy( ) );\r\n}\r\n\r\n//! Check if Secant method converges on function with large root difference\r\n//! (testFunctionWithLargeRootDifference).\r\n// Not the best test case. Inheritance from old code.\r\nBOOST_AUTO_TEST_CASE( test_secantRootFinder_testFunctionWithLargeRootDifference )\r\n{\r\n    // Declare tolerance.\r\n    const double tolerance = 1.0e-10;\r\n\r\n    // Declare expected roots.\r\n    const double expectedRootLowCase = 1.00000000793634;\r\n    const double expectedRootHighCase = 7937.3386333591;\r\n\r\n    // Create objects containing the test functions. Values were obtained during a limit case\r\n    // gravity assist calculation (while evaluating Cassini-1 trajectory).\r\n    boost::shared_ptr< TestFunctionWithLargeRootDifference > testFunctionLowCase =\r\n            boost::make_shared< TestFunctionWithLargeRootDifference >\r\n            ( 0, -3.24859999867635e18, -3248600.0, 1.5707963267949 );\r\n    boost::shared_ptr< TestFunctionWithLargeRootDifference > testFunctionHighCase =\r\n            boost::make_shared< TestFunctionWithLargeRootDifference >\r\n            ( 0, -3248600.0, -3.24859999867635e18, 1.5707963267949 );\r\n\r\n    // The termination condition.\r\n    SecantRootFinder::TerminationFunction terminationConditionFunction\r\n            = boost::bind( &RootRelativeToleranceTerminationCondition< >::checkTerminationCondition,\r\n                           boost::make_shared< RootRelativeToleranceTerminationCondition< > >(\r\n                               1.0e-10 ), _1, _2, _3, _4, _5 );\r\n\r\n    // Test Secant object, per case.\r\n    SecantRootFinder secantLowCase( terminationConditionFunction, 1.0 );\r\n    SecantRootFinder secantHighCase( terminationConditionFunction, 1.0 );\r\n\r\n    // Let the Secant method search for the root.\r\n    const double rootLowCase = secantLowCase.execute( testFunctionLowCase, 1.0 + 8.0e-9 );\r\n    const double rootHighCase = secantHighCase.execute( testFunctionHighCase, 10000.0 );\r\n\r\n    // Check if the result is within the requested accuracy.\r\n    BOOST_CHECK_CLOSE_FRACTION( rootLowCase, expectedRootLowCase, tolerance );\r\n    BOOST_CHECK_CLOSE_FRACTION( rootHighCase, expectedRootHighCase, tolerance );\r\n}\r\n\r\n//! Check if Secant method converges on function with zero root (testFunctionWithZeroRoot).\r\n// Not the best test case. Inheritance from old code. Not really relevant anymore. The basic\r\n// idea is that Newton-Raphson should work for both a function that becomes zero, as well as for a\r\n// function that does not become zero. A better case should be written.\r\nBOOST_AUTO_TEST_CASE( test_secantRootFinder_testFunctionWithZeroRoot )\r\n{\r\n    // Create object containing the test functions.\r\n    boost::shared_ptr< TestFunctionWithZeroRoot > testFunction =\r\n            boost::make_shared< TestFunctionWithZeroRoot >( 0 );\r\n\r\n    // The termination condition.\r\n    SecantRootFinder::TerminationFunction terminationConditionFunction =\r\n            boost::bind(\r\n                &RootAbsoluteToleranceTerminationCondition< double >::checkTerminationCondition,\r\n                boost::make_shared< RootAbsoluteToleranceTerminationCondition< double > >(\r\n                    1.0e-150 ), _1, _2, _3, _4, _5 );\r\n\r\n    // Test Secant object. Use the default value of the first initial guess.\r\n    SecantRootFinder secantRootFinder( terminationConditionFunction );\r\n\r\n    // Let the Secant method search for the root.\r\n    const double root = secantRootFinder.execute( testFunction, testFunction->getInitialGuess( ) );\r\n\r\n    // Check if the result is within the requested accuracy.\r\n    BOOST_CHECK_SMALL( root, 1.0e-100 );\r\n    BOOST_CHECK_SMALL( testFunction->evaluate( root ), 1.0e-200 );\r\n}\r\n\r\nBOOST_AUTO_TEST_SUITE_END( ) // testsuite_rootfinders\r\n\r\n} // namespace unit_tests\r\n} // namespace tudat\r\n", "meta": {"hexsha": "32523be7f7916f4595adcbd8fc4b29ef4044b5c8", "size": 10260, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Mathematics/RootFinders/UnitTests/unitTestSecantRootFinder.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/RootFinders/UnitTests/unitTestSecantRootFinder.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/RootFinders/UnitTests/unitTestSecantRootFinder.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": 50.5418719212, "max_line_length": 101, "alphanum_fraction": 0.7221247563, "num_tokens": 2307, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548646660543, "lm_q2_score": 0.7341195152660687, "lm_q1q2_score": 0.4781723175148395}}
{"text": "// This file is part of Eigen, a lightweight C++ template library\n// for linear algebra.\n//\n// Copyright (C) 2012 Desire Nuentsa <desire.nuentsa_wakam@inria.fr>\n// Copyright (C) 2012 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 <iostream>\n#include <fstream>\n#include <iomanip>\n\n#include \"main.h\"\n#include <Eigen/LevenbergMarquardt>\nusing namespace std;\nusing namespace Eigen;\n\ntemplate<typename Scalar>\nstruct DenseLM : DenseFunctor<Scalar>\n{\n  typedef DenseFunctor<Scalar> Base;\n  typedef typename Base::JacobianType JacobianType;\n  typedef Matrix<Scalar,Dynamic,1> VectorType;\n  \n  DenseLM(int n, int m) : DenseFunctor<Scalar>(n,m) \n  { }\n \n  VectorType model(const VectorType& uv, VectorType& x)\n  {\n    VectorType y; // Should change to use expression template\n    int m = Base::values(); \n    int n = Base::inputs();\n    eigen_assert(uv.size()%2 == 0);\n    eigen_assert(uv.size() == n);\n    eigen_assert(x.size() == m);\n    y.setZero(m);\n    int half = n/2;\n    VectorBlock<const VectorType> u(uv, 0, half);\n    VectorBlock<const VectorType> v(uv, half, half);\n    for (int j = 0; j < m; j++)\n    {\n      for (int i = 0; i < half; i++)\n        y(j) += u(i)*std::exp(-(x(j)-i)*(x(j)-i)/(v(i)*v(i)));\n    }\n    return y;\n    \n  }\n  void initPoints(VectorType& uv_ref, VectorType& x)\n  {\n    m_x = x;\n    m_y = this->model(uv_ref, x);\n  }\n  \n  int operator()(const VectorType& uv, VectorType& fvec)\n  {\n    \n    int m = Base::values(); \n    int n = Base::inputs();\n    eigen_assert(uv.size()%2 == 0);\n    eigen_assert(uv.size() == n);\n    eigen_assert(fvec.size() == m);\n    int half = n/2;\n    VectorBlock<const VectorType> u(uv, 0, half);\n    VectorBlock<const VectorType> v(uv, half, half);\n    for (int j = 0; j < m; j++)\n    {\n      fvec(j) = m_y(j);\n      for (int i = 0; i < half; i++)\n      {\n        fvec(j) -= u(i) *std::exp(-(m_x(j)-i)*(m_x(j)-i)/(v(i)*v(i)));\n      }\n    }\n    \n    return 0;\n  }\n  int df(const VectorType& uv, JacobianType& fjac)\n  {\n    int m = Base::values(); \n    int n = Base::inputs();\n    eigen_assert(n == uv.size());\n    eigen_assert(fjac.rows() == m);\n    eigen_assert(fjac.cols() == n);\n    int half = n/2;\n    VectorBlock<const VectorType> u(uv, 0, half);\n    VectorBlock<const VectorType> v(uv, half, half);\n    for (int j = 0; j < m; j++)\n    {\n      for (int i = 0; i < half; i++)\n      {\n        fjac.coeffRef(j,i) = -std::exp(-(m_x(j)-i)*(m_x(j)-i)/(v(i)*v(i)));\n        fjac.coeffRef(j,i+half) = -2.*u(i)*(m_x(j)-i)*(m_x(j)-i)/(std::pow(v(i),3)) * std::exp(-(m_x(j)-i)*(m_x(j)-i)/(v(i)*v(i)));\n      }\n    }\n    return 0;\n  }\n  VectorType m_x, m_y; //Data Points\n};\n\ntemplate<typename FunctorType, typename VectorType>\nint test_minimizeLM(FunctorType& functor, VectorType& uv)\n{\n  LevenbergMarquardt<FunctorType> lm(functor);\n  LevenbergMarquardtSpace::Status info; \n  \n  info = lm.minimize(uv);\n  \n  VERIFY_IS_EQUAL(info, 1);\n  //FIXME Check other parameters\n  return info;\n}\n\ntemplate<typename FunctorType, typename VectorType>\nint test_lmder(FunctorType& functor, VectorType& uv)\n{\n  typedef typename VectorType::Scalar Scalar;\n  LevenbergMarquardtSpace::Status info; \n  LevenbergMarquardt<FunctorType> lm(functor);\n  info = lm.lmder1(uv);\n  \n  VERIFY_IS_EQUAL(info, 1);\n  //FIXME Check other parameters\n  return info;\n}\n\ntemplate<typename FunctorType, typename VectorType>\nint test_minimizeSteps(FunctorType& functor, VectorType& uv)\n{\n  LevenbergMarquardtSpace::Status info;   \n  LevenbergMarquardt<FunctorType> lm(functor);\n  info = lm.minimizeInit(uv);\n  if (info==LevenbergMarquardtSpace::ImproperInputParameters)\n      return info;\n  do \n  {\n    info = lm.minimizeOneStep(uv);\n  } while (info==LevenbergMarquardtSpace::Running);\n  \n  VERIFY_IS_EQUAL(info, 1);\n  //FIXME Check other parameters\n  return info;\n}\n\ntemplate<typename T>\nvoid test_denseLM_T()\n{\n  typedef Matrix<T,Dynamic,1> VectorType;\n  \n  int inputs = 10; \n  int values = 1000; \n  DenseLM<T> dense_gaussian(inputs, values);\n  VectorType uv(inputs),uv_ref(inputs);\n  VectorType x(values);\n  \n  // Generate the reference solution \n  uv_ref << -2, 1, 4 ,8, 6, 1.8, 1.2, 1.1, 1.9 , 3;\n  \n  //Generate the reference data points\n  x.setRandom();\n  x = 10*x;\n  x.array() += 10;\n  dense_gaussian.initPoints(uv_ref, x);\n  \n  // Generate the initial parameters \n  VectorBlock<VectorType> u(uv, 0, inputs/2); \n  VectorBlock<VectorType> v(uv, inputs/2, inputs/2);\n  \n  // Solve the optimization problem\n  \n  //Solve in one go\n  u.setOnes(); v.setOnes();\n  test_minimizeLM(dense_gaussian, uv);\n  \n  //Solve until the machine precision\n  u.setOnes(); v.setOnes();\n  test_lmder(dense_gaussian, uv); \n  \n  // Solve step by step\n  v.setOnes(); u.setOnes();\n  test_minimizeSteps(dense_gaussian, uv);\n  \n}\n\nvoid test_denseLM()\n{\n  CALL_SUBTEST_2(test_denseLM_T<double>());\n  \n  // CALL_SUBTEST_2(test_sparseLM_T<std::complex<double>());\n}\n", "meta": {"hexsha": "0aa736ea3fbe199eefb42c2d84e4fb48125776db", "size": 5054, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Eigen-3.3/test/denseLM.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/test/denseLM.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/test/denseLM.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": 26.4607329843, "max_line_length": 131, "alphanum_fraction": 0.6394934705, "num_tokens": 1587, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195152660687, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.47817231751483946}}
{"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 <Eigen/Core>\n#include <Eigen/SparseCore>\n#include <Eigen/SparseLU>\n#include <algorithm>\n#include <ceres/rotation.h>\n#include <glog/logging.h>\n#include <memory>\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n\n#include \"spectra/include/SymEigsShiftSolver.h\"\n\n#include \"theia/math/graph/triplet_extractor.h\"\n#include \"theia/math/matrix/spectra_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_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\nstd::vector<ViewIdTriplet> GetLargetConnectedTripletGraph(\n    const std::unordered_map<ViewIdPair, TwoViewInfo>& view_pairs) {\n  static const int kLargestCCIndex = 0;\n\n  // Get a list of all edges in the view graph.\n  std::unordered_set<ViewIdPair> view_id_pairs;\n  view_id_pairs.reserve(view_pairs.size());\n  for (const auto& view_pair : view_pairs) {\n    view_id_pairs.insert(view_pair.first);\n  }\n\n  // Extract connected triplets.\n  TripletExtractor<ViewId> extractor;\n  std::vector<std::vector<ViewIdTriplet> > triplets;\n  CHECK(extractor.ExtractTriplets(view_id_pairs, &triplets));\n  CHECK_GT(triplets.size(), 0);\n  return triplets[kLargestCCIndex];\n}\n\n// Adds the constraint from the triplet to the symmetric matrix. Our standard\n// constraint matrix A is a 3M x 3N matrix with M triplet constraints and N\n// cameras. We seek to construct A^t * A directly. For each triplet constraint\n// in our matrix A (i.e. a 3-row block), we can compute the corresponding\n// entries in A^t * A with the following summation:\n//\n//   A^t * A += Row(i)^t * Row(i)\n//\n// for each triplet constraint i.\nvoid AddTripletConstraintToSymmetricMatrix(\n    const std::vector<Matrix3d>& constraints,\n    const std::vector<int>& view_indices,\n    std::unordered_map<std::pair<int, int>, double>* sparse_matrix_entries) {\n  // Construct Row(i)^t * Row(i). If we denote the row as a block matrix:\n  //\n  //   Row(i) = [A | B | C]\n  //\n  // then we have:\n  //\n  //   Row(i)^t * Row(i) = [A | B | C]^t * [A | B | C]\n  //                     = [ A^t * A  |  A^t * B  |  A^t * C]\n  //                       [ B^t * A  |  B^t * B  |  B^t * C]\n  //                       [ C^t * A  |  C^t * B  |  C^t * C]\n  //\n  // Since A^t * A is symmetric, we only store the upper triangular portion.\n  for (int i = 0; i < 3; i++) {\n    for (int j = 0; j < 3; j++) {\n      // Skip any block entries that correspond to the lower triangular portion\n      // of the matrix.\n      if (view_indices[i] > view_indices[j]) {\n        continue;\n      }\n\n      // Compute the A^t * B, etc. matrix.\n      const Eigen::Matrix3d symmetric_constraint =\n          constraints[i].transpose() * constraints[j];\n\n      // Add to the 3x3 block corresponding to (i, j)\n      for (int r = 0; r < 3; r++) {\n        for (int c = 0; c < 3; c++) {\n          const std::pair<int, int> row_col(view_indices[i] + r,\n                                            view_indices[j] + c);\n          (*sparse_matrix_entries)[row_col] += symmetric_constraint(r, c);\n        }\n      }\n    }\n  }\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// 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, 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  view_pairs_ = &view_pairs;\n  orientations_ = &orientations;\n\n  // Extract triplets from the view pairs. As of now, we only consider the\n  // largest connected triplet in the viewing graph.\n  VLOG(2) << \"Extracting triplets from the viewing graph.\";\n  triplets_ = GetLargetConnectedTripletGraph(view_pairs);\n\n  VLOG(2) << \"Determining baseline ratios within each triplet...\";\n  // Baselines where (x, y, z) corresponds to the baseline of the first,\n  // second, and third view pair in the triplet.\n  std::unique_ptr<ThreadPool> pool(new ThreadPool(options_.num_threads));\n  baselines_.resize(triplets_.size());\n  for (size_t i = 0; i < triplets_.size(); i++) {\n    AddTripletConstraint(triplets_[i]);\n    pool->Add(&LinearPositionEstimator::ComputeBaselineRatioForTriplet,\n              this,\n              triplets_[i],\n              &baselines_[i]);\n  }\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(&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(constraint_matrix);\n  Spectra::\n      SymEigsShiftSolver<double, Spectra::LARGEST_MAGN, SparseSymShiftSolveLLT>\n          eigs(&op, 1, 6, 0.0);\n  eigs.init();\n  eigs.compute();\n\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(positions);\n\n  return true;\n}\n\n// An alternative interface is to instead add triplets one by one to linear\n// estimator. This allows for adding redundant observations of triplets, which\n// may be useful if there are multiple estimates of the data.\nvoid LinearPositionEstimator::AddTripletConstraint(\n    const ViewIdTriplet& view_triplet) {\n  num_triplets_for_view_[std::get<0>(view_triplet)] += 1;\n  num_triplets_for_view_[std::get<1>(view_triplet)] += 1;\n  num_triplets_for_view_[std::get<2>(view_triplet)] += 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                     std::get<0>(view_triplet),\n                     linear_system_index_.size() - 1);\n  InsertIfNotPresent(&linear_system_index_,\n                     std::get<1>(view_triplet),\n                     linear_system_index_.size() - 1);\n  InsertIfNotPresent(&linear_system_index_,\n                     std::get<2>(view_triplet),\n                     linear_system_index_.size() - 1);\n}\n\nvoid LinearPositionEstimator::ComputeBaselineRatioForTriplet(\n    const ViewIdTriplet& triplet, Vector3d* baseline) {\n  baseline->setZero();\n\n  const View& view1 = *reconstruction_.View(std::get<0>(triplet));\n  const View& view2 = *reconstruction_.View(std::get<1>(triplet));\n  const View& view3 = *reconstruction_.View(std::get<2>(triplet));\n\n  // Find common tracks.\n  const std::vector<ViewId> triplet_view_ids = {\n      std::get<0>(triplet), std::get<1>(triplet), std::get<2>(triplet)};\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).point_);\n    feature2.emplace_back(GetNormalizedFeature(view2, track_id).point_);\n    feature3.emplace_back(GetNormalizedFeature(view3, track_id).point_);\n  }\n\n  // Get the baseline ratios.\n  ViewTriplet view_triplet;\n  view_triplet.view_ids[0] = std::get<0>(triplet);\n  view_triplet.view_ids[1] = std::get<1>(triplet);\n  view_triplet.view_ids[2] = std::get<2>(triplet);\n  view_triplet.info_one_two = FindOrDieNoPrint(\n      *view_pairs_,\n      ViewIdPair(view_triplet.view_ids[0], view_triplet.view_ids[1]));\n  view_triplet.info_one_three = FindOrDieNoPrint(\n      *view_pairs_,\n      ViewIdPair(view_triplet.view_ids[0], view_triplet.view_ids[2]));\n  view_triplet.info_two_three = FindOrDieNoPrint(\n      *view_pairs_,\n      ViewIdPair(view_triplet.view_ids[1], view_triplet.view_ids[2]));\n\n  ComputeTripletBaselineRatios(\n      view_triplet, feature1, feature2, feature3, baseline);\n}\n\n// Sets up the linear system with the constraints that each triplet adds.\nvoid LinearPositionEstimator::CreateLinearSystem(\n    Eigen::SparseMatrix<double>* constraint_matrix) {\n  const int num_views = num_triplets_for_view_.size();\n\n  std::unordered_map<std::pair<int, int>, double> sparse_matrix_entries;\n  sparse_matrix_entries.reserve(27 * num_triplets_for_view_.size());\n  for (int i = 0; i < triplets_.size(); i++) {\n    const ViewId& view_id1 = std::get<0>(triplets_[i]);\n    const ViewId& view_id2 = std::get<1>(triplets_[i]);\n    const ViewId& view_id3 = std::get<2>(triplets_[i]);\n    AddTripletConstraintToSparseMatrix(\n        view_id1, view_id2, view_id3, baselines_[i], &sparse_matrix_entries);\n  }\n\n  // Set the sparse matrix from the container of the accumulated entries.\n  std::vector<Eigen::Triplet<double> > triplet_list;\n  triplet_list.reserve(sparse_matrix_entries.size());\n  for (const auto& sparse_matrix_entry : sparse_matrix_entries) {\n    // Skip this entry if the indices are invalid. This only occurs when we\n    // encounter a constraint with the constant camera (which has a view index\n    // of -1).\n    if (sparse_matrix_entry.first.first < 0 ||\n        sparse_matrix_entry.first.second < 0) {\n      continue;\n    }\n    triplet_list.emplace_back(sparse_matrix_entry.first.first,\n                              sparse_matrix_entry.first.second,\n                              sparse_matrix_entry.second);\n  }\n\n  // We construct the constraint matrix A^t * A directly, which is an\n  // N - 1 x N - 1 matrix where N is the number of cameras (and 3 entries per\n  // camera, corresponding to the camera position entries).\n  constraint_matrix->resize((num_views - 1) * 3, (num_views - 1) * 3);\n  constraint_matrix->setFromTriplets(triplet_list.begin(), triplet_list.end());\n}\n\nvoid LinearPositionEstimator::ComputeRotatedRelativeTranslationRotations(\n    const ViewId view_id0,\n    const ViewId view_id1,\n    const ViewId view_id2,\n    Eigen::Matrix3d* r012,\n    Eigen::Matrix3d* r201,\n    Eigen::Matrix3d* r120) {\n  // Relative camera positions.\n  const Eigen::Vector3d& orientation0_aa =\n      FindOrDieNoPrint(*orientations_, view_id0);\n  const Eigen::Vector3d& orientation1_aa =\n      FindOrDieNoPrint(*orientations_, view_id1);\n  const Matrix3d orientation0 = AngleAxisToRotationMatrix(orientation0_aa);\n  const Matrix3d orientation1 = AngleAxisToRotationMatrix(orientation1_aa);\n  const Vector3d t01 =\n      -orientation0.transpose() *\n      FindOrDieNoPrint(*view_pairs_, ViewIdPair(view_id0, view_id1)).position_2;\n  const Vector3d t02 =\n      -orientation0.transpose() *\n      FindOrDieNoPrint(*view_pairs_, ViewIdPair(view_id0, view_id2)).position_2;\n  const Vector3d t12 =\n      -orientation1.transpose() *\n      FindOrDieNoPrint(*view_pairs_, ViewIdPair(view_id1, view_id2)).position_2;\n\n  // Rotations between the translation vectors.\n  *r012 = Eigen::Quaterniond::FromTwoVectors(t12, -t01).toRotationMatrix();\n  *r201 = Eigen::Quaterniond::FromTwoVectors(t01, t02).toRotationMatrix();\n  *r120 = Eigen::Quaterniond::FromTwoVectors(-t02, -t12).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 LinearPositionEstimator::AddTripletConstraintToSparseMatrix(\n    const ViewId view_id0,\n    const ViewId view_id1,\n    const ViewId view_id2,\n    const Eigen::Vector3d& baselines,\n    std::unordered_map<std::pair<int, int>, double>* sparse_matrix_entries) {\n  // Weight each term by the inverse of the # of triplet that the nodes\n  // participate in.\n  const double w =\n      1.0 / std::sqrt(std::min({num_triplets_for_view_[view_id0],\n                                num_triplets_for_view_[view_id1],\n                                num_triplets_for_view_[view_id2]}));\n\n  // Get the index of each camera in the sparse matrix.\n  const std::vector<int> view_indices = {\n      static_cast<int>(3 * FindOrDie(linear_system_index_, view_id0)),\n      static_cast<int>(3 * FindOrDie(linear_system_index_, view_id1)),\n      static_cast<int>(3 * FindOrDie(linear_system_index_, view_id2))};\n\n  // Compute the rotations between relative translations.\n  Eigen::Matrix3d r012, r201, r120;\n  ComputeRotatedRelativeTranslationRotations(\n      view_id0, view_id1, view_id2, &r012, &r201, &r120);\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  std::vector<Eigen::Matrix3d> constraints(3);\n  constraints[0] =\n      (-s_201 * r201 + r012.transpose() / s_012 + Matrix3d::Identity()) * w;\n  constraints[1] =\n      (s_201 * r201 - r012.transpose() / s_012 + Matrix3d::Identity()) * w;\n  constraints[2] = -2.0 * w * Matrix3d::Identity();\n  AddTripletConstraintToSymmetricMatrix(\n      constraints, view_indices, sparse_matrix_entries);\n\n  // Assume t02 is perfect and solve for c1.\n  constraints[0] =\n      (-r201.transpose() / s_201 + s_120 * r120 + Matrix3d::Identity()) * w;\n  constraints[1] = -2.0 * w * Matrix3d::Identity();\n  constraints[2] =\n      (r201.transpose() / s_201 - s_120 * r120 + Matrix3d::Identity()) * w;\n  AddTripletConstraintToSymmetricMatrix(\n      constraints, view_indices, sparse_matrix_entries);\n\n  // Assume t12 is perfect and solve for c0.\n  constraints[0] = -2.0 * w * Matrix3d::Identity();\n  constraints[1] =\n      (-s_012 * r012 + r120.transpose() / s_120 + Matrix3d::Identity()) * w;\n  constraints[2] =\n      (s_012 * r012 - r120.transpose() / s_120 + Matrix3d::Identity()) * w;\n  AddTripletConstraintToSymmetricMatrix(\n      constraints, view_indices, sparse_matrix_entries);\n}\n\nFeature LinearPositionEstimator::GetNormalizedFeature(const View& view,\n                                                      const TrackId track_id) {\n  Feature feature = *view.GetFeature(track_id);\n  const Camera& camera = view.Camera();\n  Eigen::Vector3d ray = camera.PixelToNormalizedCoordinates(feature.point_);\n  Feature normalized_Feature(ray.hnormalized());\n  // todo normalized covariance?\n  return normalized_Feature;\n}\n\nvoid LinearPositionEstimator::FlipSignOfPositionsIfNecessary(\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  for (const auto& view_pair : *view_pairs_) {\n    // Only count the votes for edges where both positions were successfully\n    // estimated.\n    const Vector3d* position1 = FindOrNull(*positions, view_pair.first.first);\n    const Vector3d* position2 = FindOrNull(*positions, view_pair.first.second);\n    if (position1 == nullptr || position2 == nullptr) {\n      continue;\n    }\n\n    // Check the relative translation of views 1 and 2 in the triplet.\n    if (VectorsAreSameDirection(\n            *position1,\n            *position2,\n            FindOrDieNoPrint(*orientations_, view_pair.first.first),\n            view_pair.second.position_2)) {\n      correct_sign_votes += 1;\n    } else {\n      correct_sign_votes -= 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        (view_pairs_->size() + correct_sign_votes) / 2;\n    VLOG(2) << \"Sign of the positions was incorrect: \" << num_correct_votes\n            << \" of \" << view_pairs_->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\nstd::unordered_map<ViewId, Eigen::Vector3d>\nLinearPositionEstimator::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": "8af74214ff084204229dd6113db9b09ef36ee36a", "size": 19860, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/sfm/global_pose_estimation/linear_position_estimator.cc", "max_stars_repo_name": "urbste/TheiaSfM", "max_stars_repo_head_hexsha": "a92fa27e90b6182e2a2511a46d24283afad1a995", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T03:01:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-04T08:08:45.000Z", "max_issues_repo_path": "src/theia/sfm/global_pose_estimation/linear_position_estimator.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/global_pose_estimation/linear_position_estimator.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": 41.1180124224, "max_line_length": 80, "alphanum_fraction": 0.6966263847, "num_tokens": 5034, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.4781709008861777}}
{"text": "#include <array>\n#include <vector>\n#include \"plane3d.hpp\"\n#include \"mesh_components.hpp\"\n#include <Eigen/Dense>\n\nusing namespace Eigen;\nusing namespace std;\n\n#ifndef FOUND_PATH_HPP\n#define FOUND_PATH_HPP\n\nclass FoundPath{\n    unsigned long int planeId;\n    Vector3d pt0;\n    Vector3d pt1;\n    double lowerBound;\n    double upperBound;\n  public:\n    FoundPath(unsigned long int _planeId, Vector3d _pt0, Vector3d _pt1, double _lowerBound, double _upperBound);\n    unsigned long int PlaneId();\n    double UpperBound();\n    double LowerBound();\n    array<Vector3d, 2> Points();\n};\n\n#endif\n\n", "meta": {"hexsha": "9021ebee1b1506315c090e023c5e1ea56de0a3d4", "size": 586, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/found_path.hpp", "max_stars_repo_name": "myociss/pathfinder", "max_stars_repo_head_hexsha": "4c0b14e074cfc8f0e41836abc056989f2d465c12", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/found_path.hpp", "max_issues_repo_name": "myociss/pathfinder", "max_issues_repo_head_hexsha": "4c0b14e074cfc8f0e41836abc056989f2d465c12", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/found_path.hpp", "max_forks_repo_name": "myociss/pathfinder", "max_forks_repo_head_hexsha": "4c0b14e074cfc8f0e41836abc056989f2d465c12", "max_forks_repo_licenses": ["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.2068965517, "max_line_length": 112, "alphanum_fraction": 0.7252559727, "num_tokens": 148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.4781709008861777}}
{"text": "/******************************************************************************\n * Copyright 2017 Baidu Robotic Vision Authors. 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 __DEVELOPMENT_DEBUG_MODE__\n#define __FEATURE_UTILS_NO_DEBUG__\n#endif\n#include \"feature_utils.h\"\n#include \"patch_score.h\"\n\n#include \"cameras/PinholeCamera.hpp\"\n#include \"cameras/RadialTangentialDistortion.hpp\"\n#include \"cameras/RadialTangentialDistortion8.hpp\"\n\n#include <boost/lexical_cast.hpp>\n#ifndef __FEATURE_UTILS_NO_DEBUG__\n#include <opencv2/highgui.hpp>\n#endif\n\n// define this MACROS to enable profing and verifying align2D_NEON\n#undef _ALIGN2D_TIMING_AND_VERIFYING\n#ifdef _ALIGN2D_TIMING_AND_VERIFYING\n#include <vio/timing/ProfilingTimer.hpp>\nusing vio::timing::MicrosecondStopwatch;\nMicrosecondStopwatch timer_align2d(\"align2d\", 0);\nMicrosecondStopwatch timer_align2d_neon(\"align2d neon\", 0);\nfloat align2d_total_time = 0.f;\nfloat align2d_total_time_neon = 0.f;\n#endif\n\nnamespace XP {\n\nusing Eigen::Vector2i;\nusing Eigen::Vector2f;\nusing Eigen::Vector3f;\nusing Eigen::Matrix2f;\nusing Eigen::Matrix3f;\nusing Eigen::Matrix4f;\n\n// The triangulated point at the current frame coordinate can be represented as:\n// R_cur_ref * f_ref * d_ref + t_cur_ref =  f_cur * d_cur,\n// where d_ref and d_cur are scales, respetively\n// We can organize the equation into a linear system to solve d in the form of\n// Ax = b:\n// [R_cur_ref * f_ref  f_cur] * [d_ref; - d_cur] = - t_cur_ref\n//   A = [R_cur_ref * f_ref f_cur],  3 x 2\n//   x = [d_ref; -d_cur],  2 x 1\n//   b = - t_cur_ref,  3 x 1\n// x = (AtA)^-1 * At * b\n//\n// The returned depth is based on the reference frame\nbool depthFromTriangulation(const Matrix3f& R_cur_ref,\n                            const Vector3f& t_cur_ref, const Vector3f& f_ref,\n                            const Vector3f& f_cur, float* depth) {\n  Eigen::Matrix<float, 3, 2> A;\n  A << R_cur_ref * f_ref, f_cur;\n  const Matrix2f AtA = A.transpose() * A;\n  if (AtA.determinant() < 1e-6) {\n    // TODO(mingyu): figure the right threshold for float\n    *depth = 1000;  // a very far point\n    return false;\n  }\n  const Vector2f depth2 = -AtA.inverse() * A.transpose() * t_cur_ref;\n  *depth = fabs(depth2[0]);\n  return true;\n}\n\nvoid DirectMatcher::createPatchFromPatchWithBorder() {\n  uint8_t* ref_patch_ptr = patch_;\n  for (int y = 1; y < patch_size_ + 1; ++y, ref_patch_ptr += patch_size_) {\n    uint8_t* ref_patch_border_ptr =\n        patch_with_border_ + y * (patch_size_ + 2) + 1;\n    memcpy(ref_patch_ptr, ref_patch_border_ptr, patch_size_);\n    /*\n    for (int x = 0; x < patch_size_; ++x) {\n      ref_patch_ptr[x] = ref_patch_border_ptr[x];\n    }\n    */\n  }\n}\n\nbool DirectMatcher::findMatchDirect(\n    const vio::cameras::CameraBase& cam_ref,\n    const vio::cameras::CameraBase& cam_cur, const Vector2f& px_ref,\n    const Vector3f& f_ref, const Matrix3f& R_cur_ref, const Vector3f& t_cur_ref,\n    const int level_ref, const float depth_ref,\n    const std::vector<cv::Mat>& pyrs_ref, const std::vector<cv::Mat>& pyrs_cur,\n    const bool edgelet_feature, Vector2f* px_cur) {\n  CHECK_NEAR(f_ref[2], 1.f, 1e-6);\n  CHECK_EQ(pyrs_ref.size(), pyrs_cur.size());\n\n  // TODO(mingyu): check return boolean of getWarpMatrixAffine\n  // warp affine\n  warp::getWarpMatrixAffine(cam_ref, cam_cur, px_ref, f_ref, depth_ref,\n                            R_cur_ref, t_cur_ref, level_ref, &A_cur_ref_);\n  const int max_level = pyrs_ref.size() - 1;\n  const int search_level = warp::getBestSearchLevel(A_cur_ref_, max_level);\n\n  // TODO(mingyu): check return boolean of warpAffine\n  warp::warpAffine(A_cur_ref_, pyrs_ref[level_ref], px_ref, level_ref,\n                   search_level, halfpatch_size_ + 1, patch_with_border_);\n  createPatchFromPatchWithBorder();\n\n  // px_cur should be set\n  Vector2f px_scaled = *px_cur / (1 << search_level);\n\n  bool success = false;\n  if (edgelet_feature) {\n    // TODO(mingyu): currently not used until we further refine the feature type\n    //               with gradient direction.\n    //               Fast features do contain edgelet features.\n    /*\n    Vector2f dir_cur(A_cur_ref_ * ref_ftr_->grad);\n    dir_cur.normalize();\n    success = align::align1D(pyrs_cur[search_level],\n                             dir_cur,\n                             patch_with_border_,\n                             patch_,\n                             options_.max_iter,\n                             &px_scaled,\n                             &h_inv_);\n    */\n    LOG(ERROR) << \"findMatchDirect for edgelet feature is NOT rimplemented yet\";\n    success = false;\n  } else {\n#ifndef _ALIGN2D_TIMING_AND_VERIFYING\n#ifndef __ARM_NEON__\n    success = align::align2D(pyrs_cur[search_level], patch_with_border_, patch_,\n                             options_.max_iter, &px_scaled);\n#else\n    success = align::align2D_NEON(pyrs_cur[search_level], patch_with_border_,\n                                  patch_, options_.max_iter, &px_scaled);\n#endif  // __ARM_NEON__\n#else\n// timing and verifying code.\n#ifdef __ARM_NEON__\n    Vector2f px_scaled_neon = px_scaled;\n#endif  // __ARM_NEON__\n    timer_align2d.start();\n    success = align::align2D(pyrs_cur[search_level], patch_with_border_, patch_,\n                             options_.max_iter, &px_scaled);\n    timer_align2d.stop();\n    align2d_total_time = timer_align2d.stop();\n\n#ifdef __ARM_NEON__\n    timer_align2d_neon.start();\n    bool success_neon =\n        align::align2D_NEON(pyrs_cur[search_level], patch_with_border_, patch_,\n                            options_.max_iter, &px_scaled_neon);\n    timer_align2d_neon.stop();\n    align2d_total_time_neon = timer_align2d_neon.elapse_ms();\n    CHECK_EQ(success, success_neon);\n    if (success_neon) {\n      CHECK_NEAR(px_scaled[0], px_scaled_neon[0], 0.05);\n      CHECK_NEAR(px_scaled[1], px_scaled_neon[1], 0.05);\n      std::cout << \"[NEON : NON-NEON --->\"\n                << \"[\" << align2d_total_time_neon << \" : \" << align2d_total_time\n                << \"]\" << std::endl;\n    }\n#endif  // __ARM_NEON__\n#endif  // _ALIGN2D_TIMING_AND_VERIFYING\n  }\n  *px_cur = px_scaled * (1 << search_level);\n  return success;\n}\n\nbool DirectMatcher::findEpipolarMatchDirect(\n    const vio::cameras::CameraBase& cam_ref,\n    const vio::cameras::CameraBase& cam_cur, const Vector2f& px_ref,\n    const Vector3f& f_ref, const Matrix3f& R_cur_ref, const Vector3f& t_cur_ref,\n    const int level_ref, const float d_estimate, const float d_min,\n    const float d_max, const std::vector<cv::Mat>& pyrs_ref,\n    const std::vector<cv::Mat>& pyrs_cur, const cv::Mat_<uchar>& mask_cur,\n    const bool edgelet_feature, Vector2f* px_cur, float* depth, int* level_cur,\n    cv::Mat* dbg_cur) {\n  CHECK_NEAR(f_ref[2], 1.f, 1e-6);\n  CHECK_EQ(pyrs_ref.size(), pyrs_cur.size());\n\n  // Compute start and end of epipolar line in old_kf for match search, on unit\n  // plane!\n  // i.e., A & B are the first two elements of unit rays.\n  // We will search from far to near\n  Vector3f ray_A, ray_B;\n  Vector2f px_A, px_B;\n  ray_B = R_cur_ref * (f_ref * d_max) + t_cur_ref;  // far\n  ray_B /= ray_B(2);\n  if (vio::cameras::CameraBase::ProjectionStatus::Successful !=\n      cam_cur.project(ray_B, &px_B)) {\n#ifndef __FEATURE_UTILS_NO_DEBUG__\n    VLOG(2) << \"ray_A (far) cannot be reprojected in cam_cur\";\n#endif\n    return false;\n  }\n\n  bool invalid_ray_A = true;\n  for (float d = d_min; d < d_estimate; d *= 10) {\n    ray_A = R_cur_ref * (f_ref * d) + t_cur_ref;  // near\n    ray_A /= ray_A(2);\n    if (vio::cameras::CameraBase::ProjectionStatus::Successful ==\n        cam_cur.project(ray_A, &px_A)) {\n      invalid_ray_A = false;\n      break;\n    }\n  }\n  if (invalid_ray_A) {\n#ifndef __FEATURE_UTILS_NO_DEBUG__\n    VLOG(2) << \"ray_B (near) cannot be reprojected in cam_cur \"\n            << \" d_min = \" << d_min << \" d_estimate = \" << d_estimate;\n#endif\n    return false;\n  }\n\n  // Compute warp affine matrix\n  if (!warp::getWarpMatrixAffine(cam_ref, cam_cur, px_ref, f_ref, d_estimate,\n                                 R_cur_ref, t_cur_ref, level_ref,\n                                 &A_cur_ref_)) {\n    LOG(WARNING) << \"warp::getWarpMatrixAffine fails\";\n    return false;\n  }\n#ifndef __FEATURE_UTILS_NO_DEBUG__\n  VLOG(2) << \"A_cur_ref_ =\\n\" << A_cur_ref_;\n#endif\n\n  const int max_level = pyrs_ref.size() - 1;\n  const int search_level = warp::getBestSearchLevel(A_cur_ref_, max_level);\n  epi_dir_ = ray_A.head<2>() - ray_B.head<2>();  // far to near, B to A\n  epi_length_ = (px_A - px_B).norm() / (1 << search_level);\n\n  // feature pre-selection\n  if (edgelet_feature) {\n    /*\n    const Vector2f grad_cur = (A_cur_ref_ * ref_ftr.grad).normalized();\n    const float cosangle = fabs(grad_cur.dot(epi_dir_.normalized()));\n    if (cosangle < options_.epi_search_edgelet_max_angle) {\n      return false;\n    }\n    */\n    LOG(ERROR)\n        << \"findEpipolarMatchDirect for edgelet feature is NOT implemented yet\";\n    return false;\n  }\n\n  if (!warp::warpAffine(A_cur_ref_, pyrs_ref[level_ref], px_ref, level_ref,\n                        search_level, halfpatch_size_ + 1,\n                        patch_with_border_)) {\n    return false;\n  }\n  createPatchFromPatchWithBorder();\n#ifndef __FEATURE_UTILS_NO_DEBUG__\n  VLOG(2) << \" search_level = \" << search_level\n          << \" epi_length_ = \" << epi_length_;\n#endif\n  if (epi_length_ < options_.max_epi_length_optim) {\n    // The epipolar search line is short enough (< 2 pixels)\n    // to perform direct alignment\n    *px_cur = (px_A + px_B) * 0.5f;\n    Vector2f px_scaled(*px_cur / (1 << search_level));\n    bool success;\n    if (options_.align_1d) {\n      Vector2f direction = (px_A - px_B).normalized();\n      success =\n          align::align1D(pyrs_cur[search_level], direction, patch_with_border_,\n                         patch_, options_.max_iter, &px_scaled, &h_inv_);\n    } else {\n#ifndef _ALIGN2D_TIMING_AND_VERIFYING\n#ifndef __ARM_NEON__\n      success = align::align2D(pyrs_cur[search_level], patch_with_border_,\n                               patch_, options_.max_iter, &px_scaled);\n#else\n      success = align::align2D_NEON(pyrs_cur[search_level], patch_with_border_,\n                                    patch_, options_.max_iter, &px_scaled);\n#endif  // __ARM_NEON__\n#else\n// verifying and timing code\n#ifdef __ARM_NEON__\n      Vector2f px_scaled_neon = px_scaled;\n#endif  // __ARM_NEON__\n      timer_align2d.start();\n      success = align::align2D(pyrs_cur[search_level], patch_with_border_,\n                               patch_, options_.max_iter, &px_scaled);\n      timer_align2d.stop();\n      align2d_total_time = timer_align2d.elapse_ms();\n#ifdef __ARM_NEON__\n      timer_align2d_neon.start();\n      bool success_neon =\n          align::align2D_NEON(pyrs_cur[search_level], patch_with_border_,\n                              patch_, options_.max_iter, &px_scaled_neon);\n      timer_align2d_neon.stop();\n      align2d_total_time_neon = timer_align2d_neon.elapse_ms();\n      CHECK_EQ(success, success_neon);\n      if (success_neon) {\n        CHECK_NEAR(px_scaled[0], px_scaled_neon[0], 0.05);\n        CHECK_NEAR(px_scaled[1], px_scaled_neon[1], 0.05);\n        std::cout << \"[NEON : NON-NEON --->\"\n                  << \"[\" << align2d_total_time_neon << \" : \"\n                  << align2d_total_time << \"]\" << std::endl;\n      }\n#endif  // __ARM_NEON__\n#endif  // _ALIGN2D_TIMING_AND_VERIFYING\n    }\n\n    if (success) {\n      *px_cur = px_scaled * (1 << search_level);\n      Vector3f f_cur;\n      if (cam_cur.backProject(*px_cur, &f_cur)) {\n        CHECK_NEAR(f_cur[2], 1.f, 1e-6);\n        if (!depthFromTriangulation(R_cur_ref, t_cur_ref, f_ref, f_cur,\n                                    depth)) {\n          LOG(WARNING) << \"depthFromTriangulation fails, set depth to d_max\";\n          *depth = d_max;\n        }\n      }\n    }\n\n    if (dbg_cur != nullptr) {\n      if (success) {\n        // green: subpix alignment is good\n        cv::circle(*dbg_cur, cv::Point2f((*px_cur)(0), (*px_cur)(1)), 2,\n                   cv::Scalar(0, 255, 0));\n      } else {\n        // red: subpix alignment fails\n        cv::circle(*dbg_cur, cv::Point2f((*px_cur)(0), (*px_cur)(1)), 2,\n                   cv::Scalar(0, 0, 255));\n      }\n    }\n    return success;\n  }\n\n  // Determine the steps to Search along the epipolar line\n  // [NOTE] The epipolar line can be curvy, so we slightly increase it\n  //        to roughly have one step per pixel (heuristically).\n  size_t n_steps = epi_length_ / 0.7;\n  Vector3f step;\n  step << epi_dir_ / n_steps, 0;\n  if (n_steps > options_.max_epi_search_steps) {\n    LOG(ERROR) << \"Skip epipolar search: evaluations = \" << n_steps\n               << \"epi length (px) = \" << epi_length_;\n    return false;\n  }\n\n  // Search along the epipolar line (on unit plane) with patch matching\n  // for matching, precompute sum and sum2 of warped reference patch\n  // [heuristic] The ssd from patch mean difference can be up to 50% of the\n  // resulting ssd.\n  //  ssd = zmssd + N * (a_bar - b_bar)^2\n  typedef patch_score::ZMSSD<halfpatch_size_> PatchScore;\n  PatchScore patch_score(patch_);\n  int zmssd_best = PatchScore::threshold();\n  int ssd_corr = PatchScore::threshold() * 2;\n  Vector3f ray_best;\n  Vector3f ray = ray_B;\n  Eigen::Vector2i last_checked_pxi(0, 0);\n  const int search_img_rows = pyrs_cur[search_level].rows;\n  const int search_img_cols = pyrs_cur[search_level].cols;\n  ++n_steps;\n  for (size_t i = 0; i < n_steps; ++i, ray += step) {\n    Vector2f px;\n    if (vio::cameras::CameraBase::ProjectionStatus::Successful !=\n        cam_cur.project(ray, &px)) {\n      // We have already checked the valid projection of starting and ending\n      // rays.  However,\n      // under very rare circumstance, cam_cur.project may still fail:\n      // close to zero denominator for radial tangential 8 distortion:\n      // 1 + k4 * r^2 + k5 * r^4 + k6 * r^6 < 1e-6\n      continue;\n    }\n    Vector2i pxi(px[0] / (1 << search_level) + 0.5,\n                 px[1] / (1 << search_level) + 0.5);  // round to closest int\n    if (pxi == last_checked_pxi) {\n      continue;\n    }\n    last_checked_pxi = pxi;\n\n    // check if the patch is full within the new frame\n    if (pxi[0] >= halfpatch_size_ &&\n        pxi[0] < search_img_cols - halfpatch_size_ &&\n        pxi[1] >= halfpatch_size_ &&\n        pxi[1] < search_img_rows - halfpatch_size_ &&\n        mask_cur(pxi(1), pxi(0)) > 0) {\n      // TODO(mingyu): Interpolation instead?\n      uint8_t* cur_patch_ptr = pyrs_cur[search_level].data +\n                               (pxi[1] - halfpatch_size_) * search_img_cols +\n                               (pxi[0] - halfpatch_size_);\n      int ssd, zmssd;\n      patch_score.computeScore(cur_patch_ptr, search_img_cols, &zmssd, &ssd);\n      if (zmssd < zmssd_best) {\n        // We store the best zmssd and its corresponding ssd score.  Usually,\n        // zmssd and ssd have good correlation if the *matching* is reasonable.\n        zmssd_best = zmssd;\n        ssd_corr = ssd;\n        ray_best = ray;\n      }\n#ifndef __FEATURE_UTILS_NO_DEBUG__\n      VLOG(2) << \"search pxi=[\" << pxi[0] << \", \" << pxi[1]\n              << \"] zmssd = \" << zmssd << \" ssd = \" << ssd;\n#endif\n      if (dbg_cur != nullptr) {\n        dbg_cur->at<cv::Vec3b>(pxi[1], pxi[0]) = cv::Vec3b(255, 0, 0);\n      }\n    } else {\n      // The patch contains out of bound pixels\n      continue;\n    }\n  }\n\n  VLOG(2) << \"zmssd_best = \" << zmssd_best << \" ssd_corr = \" << ssd_corr\n          << \" zmssd / ssd = \" << static_cast<float>(zmssd_best) / ssd_corr;\n  if (zmssd_best < PatchScore::threshold()) {\n    cam_cur.project(ray_best, px_cur);\n    if (options_.subpix_refinement) {\n      Vector2f px_scaled(*px_cur / (1 << search_level));\n      bool success;\n      if (options_.align_1d) {\n        Vector2f direction = (px_A - px_B).normalized();\n        success = align::align1D(pyrs_cur[search_level], direction,\n                                 patch_with_border_, patch_, options_.max_iter,\n                                 &px_scaled, &h_inv_);\n      } else {\n#ifndef _ALIGN2D_TIMING_AND_VERIFYING\n#ifndef __ARM_NEON__\n        success = align::align2D(pyrs_cur[search_level], patch_with_border_,\n                                 patch_, options_.max_iter, &px_scaled);\n#else\n        success =\n            align::align2D_NEON(pyrs_cur[search_level], patch_with_border_,\n                                patch_, options_.max_iter, &px_scaled);\n#endif  // __ARM_NEON__\n#else\n#ifdef __ARM_NEON__\n        Vector2f px_scaled_neon = px_scaled;\n#endif  // __ARM_NEON__\n        timer_align2d.start();\n        success = align::align2D(pyrs_cur[search_level], patch_with_border_,\n                                 patch_, options_.max_iter, &px_scaled);\n        timer_align2d.stop();\n        align2d_total_time = timer_align2d.elapse_ms();\n#ifdef __ARM_NEON__\n        timer_align2d_neon.start();\n        bool success_neon =\n            align::align2D_NEON(pyrs_cur[search_level], patch_with_border_,\n                                patch_, options_.max_iter, &px_scaled_neon);\n        timer_align2d_neon.stop();\n        align2d_total_time_neon = timer_align2d_neon.elapse_ms();\n        CHECK_EQ(success, success_neon);\n        if (success_neon) {\n          CHECK_NEAR(px_scaled[0], px_scaled_neon[0], 0.05);\n          CHECK_NEAR(px_scaled[1], px_scaled_neon[1], 0.05);\n          std::cout << \"[NEON : NON-NEON --->\"\n                    << \"[\" << align2d_total_time_neon << \" : \"\n                    << align2d_total_time << \"]\" << std::endl;\n        }\n#endif  // __ARM_NEON__\n#endif  // _ALIGN2D_TIMING_AND_VERIFYING\n      }\n\n      if (success) {\n        *px_cur = px_scaled * (1 << search_level);\n        Vector3f f_cur;\n        if (cam_cur.backProject(*px_cur, &f_cur)) {\n          CHECK_NEAR(f_cur[2], 1.f, 1e-6);\n          if (!depthFromTriangulation(R_cur_ref, t_cur_ref, f_ref, f_cur,\n                                      depth)) {\n            LOG(WARNING) << \"depthFromTriangulation fails, set depth to d_max\";\n            *depth = d_max;\n          }\n        }\n      }\n\n      if (dbg_cur != nullptr) {\n        if (success) {\n          // green: subpix alignment is good\n          cv::circle(*dbg_cur, cv::Point2f((*px_cur)(0), (*px_cur)(1)), 2,\n                     cv::Scalar(0, 255, 0));\n        } else {\n          // red: subpix alignment fails\n          cv::circle(*dbg_cur, cv::Point2f((*px_cur)(0), (*px_cur)(1)), 2,\n                     cv::Scalar(0, 0, 255));\n        }\n      }\n      return success;\n    } else {\n      // No subpix refinement\n      CHECK_NEAR(ray_best[2], 1.f, 1e-6);\n      if (!depthFromTriangulation(R_cur_ref, t_cur_ref, f_ref, ray_best,\n                                  depth)) {\n        LOG(WARNING) << \"depthFromTriangulation fails, set depth to d_max\";\n        *depth = d_max;\n      }\n      return true;\n    }\n  }\n\n// No patch qualifiess a match\n#ifndef __FEATURE_UTILS_NO_DEBUG__\n  VLOG(1) << \"No matching patch found for this feature\";\n#endif\n  return false;\n}\n\n// Prepare all the shared variabls for the whole tracking pipeline\nImgFeaturePropagator::ImgFeaturePropagator(\n    const Eigen::Matrix3f& cur_camK, const Eigen::Matrix3f& ref_camK,\n    const cv::Mat_<float>& cur_cv_dist_coeff,\n    const cv::Mat_<float>& ref_cv_dist_coeff, const cv::Mat_<uchar>& cur_mask,\n    int feat_det_pyramid_level, float min_feature_distance_over_baseline_ratio,\n    float max_feature_distance_over_baseline_ratio)\n    : mask_cur_(cur_mask),\n      min_feature_distance_over_baseline_ratio_(\n          min_feature_distance_over_baseline_ratio),\n      max_feature_distance_over_baseline_ratio_(\n          max_feature_distance_over_baseline_ratio),\n      feat_det_pyramid_level_(feat_det_pyramid_level) {\n  CHECK_GT(mask_cur_.rows, 0);\n  CHECK_GT(mask_cur_.cols, 0);\n  if (cur_cv_dist_coeff.rows == 8) {\n    cam_cur_.reset(new vio::cameras::PinholeCamera<\n                   vio::cameras::RadialTangentialDistortion8>(\n        mask_cur_.cols, mask_cur_.rows, cur_camK(0, 0),  // focalLength[0],\n        cur_camK(1, 1),                                  // focalLength[1],\n        cur_camK(0, 2),                                  // principalPoint[0],\n        cur_camK(1, 2),                                  // principalPoint[1],\n        vio::cameras::RadialTangentialDistortion8(\n            cur_cv_dist_coeff(0), cur_cv_dist_coeff(1), cur_cv_dist_coeff(2),\n            cur_cv_dist_coeff(3), cur_cv_dist_coeff(4), cur_cv_dist_coeff(5),\n            cur_cv_dist_coeff(6), cur_cv_dist_coeff(7))));\n  } else if (cur_cv_dist_coeff.rows == 4) {\n    cam_cur_.reset(new vio::cameras::PinholeCamera<\n                   vio::cameras::RadialTangentialDistortion>(\n        mask_cur_.cols, mask_cur_.rows, cur_camK(0, 0),  // focalLength[0],\n        cur_camK(1, 1),                                  // focalLength[1],\n        cur_camK(0, 2),                                  // principalPoint[0],\n        cur_camK(1, 2),                                  // principalPoint[1],\n        vio::cameras::RadialTangentialDistortion(\n            cur_cv_dist_coeff(0), cur_cv_dist_coeff(1), cur_cv_dist_coeff(2),\n            cur_cv_dist_coeff(3))));\n  } else {\n    LOG(FATAL) << \"Dist model unsupported for cam_cur_\";\n  }\n  if (ref_cv_dist_coeff.rows == 8) {\n    cam_ref_.reset(new vio::cameras::PinholeCamera<\n                   vio::cameras::RadialTangentialDistortion8>(\n        mask_cur_.cols, mask_cur_.rows, ref_camK(0, 0),  // focalLength[0],\n        ref_camK(1, 1),                                  // focalLength[1],\n        ref_camK(0, 2),                                  // principalPoint[0],\n        ref_camK(1, 2),                                  // principalPoint[1],\n        vio::cameras::RadialTangentialDistortion8(\n            ref_cv_dist_coeff(0), ref_cv_dist_coeff(1), ref_cv_dist_coeff(2),\n            ref_cv_dist_coeff(3), ref_cv_dist_coeff(4), ref_cv_dist_coeff(5),\n            ref_cv_dist_coeff(6), ref_cv_dist_coeff(7))));\n  } else if (ref_cv_dist_coeff.rows == 4) {\n    cam_ref_.reset(new vio::cameras::PinholeCamera<\n                   vio::cameras::RadialTangentialDistortion>(\n        mask_cur_.cols, mask_cur_.rows, ref_camK(0, 0),  // focalLength[0],\n        ref_camK(1, 1),                                  // focalLength[1],\n        ref_camK(0, 2),                                  // principalPoint[0],\n        ref_camK(1, 2),                                  // principalPoint[1],\n        vio::cameras::RadialTangentialDistortion(\n            ref_cv_dist_coeff(0), ref_cv_dist_coeff(1), ref_cv_dist_coeff(2),\n            ref_cv_dist_coeff(3))));\n  } else {\n    LOG(FATAL) << \"Dist model unsupported for cam_ref_\";\n  }\n}\n\nbool ImgFeaturePropagator::PropagateFeatures(\n    const cv::Mat& cur_img,\n    const cv::Mat& ref_img,  // TODO(mingyu): store image pyramids\n    const std::vector<cv::KeyPoint>& ref_keypoints, const Matrix4f& T_ref_cur,\n    std::vector<cv::KeyPoint>* cur_keypoints, cv::Mat* cur_orb_features,\n    const bool draw_debug) {\n  cur_keypoints->clear();\n  cur_keypoints->reserve(ref_keypoints.size());\n\n  R_cur_ref_ = T_ref_cur.topLeftCorner<3, 3>().transpose();\n  t_cur_ref_ = -R_cur_ref_ * T_ref_cur.topRightCorner<3, 1>();\n\n  // TODO(mingyu): Make shared variables of DirectMatcher into member variables\n  //               instead of passing as input arguments\n\n  // Heuristically determine the d_max, d_min, and d_estimate based on the\n  // baseline,\n  // d_min = baseline x 3\n  // d_max = baseline x 3000\n  // inv_d_estimate is the average of inv_d_min and inv_d_max\n  const float baseline = t_cur_ref_.norm();\n  const float d_min = baseline * min_feature_distance_over_baseline_ratio_;\n  const float d_max = baseline * max_feature_distance_over_baseline_ratio_;\n  const float d_estimate = 2.f / (1.f / d_min + 1.f / d_max);\n\n  // TODO(mingyu): feed the backend results back for d_estimate if available\n  // TODO(mingyu): feed the pyramids in directly\n  std::vector<cv::Mat> pyrs_cur(feat_det_pyramid_level_);\n  std::vector<cv::Mat> pyrs_ref(feat_det_pyramid_level_);\n  pyrs_cur[0] = cur_img;\n  pyrs_ref[0] = ref_img;\n  for (int pyr_lv = 1; pyr_lv < feat_det_pyramid_level_; ++pyr_lv) {\n    pyrs_cur[pyr_lv] = fast_pyra_down(pyrs_cur[pyr_lv - 1]);\n    pyrs_ref[pyr_lv] = fast_pyra_down(pyrs_ref[pyr_lv - 1]);\n  }\n\n  for (const cv::KeyPoint& ref_kp : ref_keypoints) {\n    int level_cur = 0;\n    float depth = -1.f;\n    Vector2f px_cur, px_ref(ref_kp.pt.x, ref_kp.pt.y);\n    Vector3f f_ref;\n    if (!cam_ref_->backProject(px_ref, &f_ref)) {\n      continue;\n    }\n\n    // Visualization (re-draw for every keypoint)\n    if (draw_debug) {\n      dbg_img_.create(mask_cur_.rows * 2, mask_cur_.cols, CV_8UC3);\n      dbg_ref_ = dbg_img_(cv::Rect(0, 0, mask_cur_.cols, mask_cur_.rows));\n      dbg_cur_ =\n          dbg_img_(cv::Rect(0, mask_cur_.rows, mask_cur_.cols, mask_cur_.rows));\n      dbg_cur_ptr_ = &dbg_cur_;\n      cv::cvtColor(ref_img, dbg_ref_, CV_GRAY2RGB);\n      cv::cvtColor(cur_img, dbg_cur_, CV_GRAY2RGB);\n      cv::circle(dbg_ref_, ref_kp.pt, 2, cv::Scalar(0, 255, 0));\n      cv::putText(dbg_ref_, boost::lexical_cast<std::string>(ref_kp.class_id),\n                  ref_kp.pt, cv::FONT_HERSHEY_SIMPLEX, 0.5,\n                  cv::Scalar(0, 255, 0), 1);\n      for (int i = 0; i < mask_cur_.rows; ++i) {\n        for (int j = 0; j < mask_cur_.cols; ++j) {\n          if (mask_cur_(i, j) == 0x00) {\n            dbg_cur_.at<cv::Vec3b>(i, j)[0] = 0;\n            dbg_cur_.at<cv::Vec3b>(i, j)[1] = 0;\n          }\n        }\n      }\n    }\n#ifndef __FEATURE_UTILS_NO_DEBUG__\n    VLOG(1) << \"findEpipolarMatchDirect for of_id = \" << ref_kp.class_id;\n#endif\n    if (!direct_matcher_.findEpipolarMatchDirect(\n            *cam_ref_, *cam_cur_, px_ref, f_ref, R_cur_ref_, t_cur_ref_,\n            ref_kp.octave,  // double check here\n            d_estimate, d_min, d_max, pyrs_ref, pyrs_cur, mask_cur_,\n            false, /*edgelet_feature, not supported yet*/\n            &px_cur, &depth, &level_cur, dbg_cur_ptr_)) {\n#ifndef __FEATURE_UTILS_NO_DEBUG__\n      if (draw_debug) {\n        cv::imwrite(\"/tmp/per_feat_dbg/det_\" +\n                        boost::lexical_cast<std::string>(ref_kp.class_id) +\n                        \".png\",\n                    dbg_img_);\n      }\n      VLOG(1) << \"findEpipolarMatchDirect fails for of_id: \" << ref_kp.class_id;\n#endif\n      continue;\n    }\n#ifndef __FEATURE_UTILS_NO_DEBUG__\n    if (draw_debug) {\n      cv::imwrite(\"/tmp/per_feat_dbg/det_\" +\n                      boost::lexical_cast<std::string>(ref_kp.class_id) +\n                      \".png\",\n                  dbg_img_);\n      VLOG(1) << \"findEpipolarMatchDirect succeeds for of_id: \"\n              << ref_kp.class_id;\n    }\n#endif\n\n    // check boundary condition (set to 20 pixels for computing ORB features)\n    // [NOTE] Returned px_cur should be within mask_cur_ already\n    const int orb_desc_margin = 20;\n    if (px_cur(0) < orb_desc_margin ||\n        px_cur(0) > mask_cur_.cols - orb_desc_margin ||\n        px_cur(1) < orb_desc_margin ||\n        px_cur(1) > mask_cur_.rows - orb_desc_margin) {\n      continue;\n    }\n\n    cv::KeyPoint cur_kp = ref_kp;\n    cur_kp.octave = level_cur;\n    cur_kp.pt.x = px_cur(0);\n    cur_kp.pt.y = px_cur(1);\n    cur_keypoints->push_back(cur_kp);\n  }\n\n  if (cur_orb_features != nullptr && cur_keypoints->size() > 0) {\n    cur_orb_features->create(cur_keypoints->size(), 32, CV_8U);\n#ifdef __ARM_NEON__\n    ORBextractor::computeDescriptorsN512(cur_img, *cur_keypoints,\n                                         cur_orb_features);\n#else\n    ORBextractor::computeDescriptors(cur_img, *cur_keypoints, cur_orb_features);\n#endif\n  }\n  return true;\n}\n\n}  // namespace XP\n", "meta": {"hexsha": "4fe926078d05128f5fe7779e1b7b8665a12720ff", "size": 28119, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Frontend/feature_utils_direct_matcher.cc", "max_stars_repo_name": "TongLing916/ICE-BA", "max_stars_repo_head_hexsha": "b8febd35af821e3bbb5909c66a485b9e234a80fe", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Frontend/feature_utils_direct_matcher.cc", "max_issues_repo_name": "TongLing916/ICE-BA", "max_issues_repo_head_hexsha": "b8febd35af821e3bbb5909c66a485b9e234a80fe", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Frontend/feature_utils_direct_matcher.cc", "max_forks_repo_name": "TongLing916/ICE-BA", "max_forks_repo_head_hexsha": "b8febd35af821e3bbb5909c66a485b9e234a80fe", "max_forks_repo_licenses": ["Apache-2.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.9417613636, "max_line_length": 80, "alphanum_fraction": 0.6211102813, "num_tokens": 7839, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.47817090088617764}}
{"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_IEEE_FUNCTIONS_NEXTPOW2_HPP_INCLUDED\n#define BOOST_SIMD_IEEE_FUNCTIONS_NEXTPOW2_HPP_INCLUDED\n#include <boost/simd/include/functor.hpp>\n#include <boost/dispatch/include/functor.hpp>\n\n\nnamespace boost { namespace simd { namespace tag\n  {\n   /*!\n     @brief nextpow2 generic tag\n\n     Represents the nextpow2 function in generic contexts.\n\n     @par Models:\n        Hierarchy\n   **/\n    struct nextpow2_ : ext::elementwise_<nextpow2_>\n    {\n      /// @brief Parent hierarchy\n      typedef ext::elementwise_<nextpow2_> parent;\n      template<class... Args>\n      static BOOST_FORCEINLINE BOOST_AUTO_DECLTYPE dispatch(Args&&... args)\n      BOOST_AUTO_DECLTYPE_BODY( dispatching_nextpow2_( ext::adl_helper(), static_cast<Args&&>(args)... ) )\n    };\n  }\n  namespace ext\n  {\n   template<class Site>\n   BOOST_FORCEINLINE generic_dispatcher<tag::nextpow2_, Site> dispatching_nextpow2_(adl_helper, boost::dispatch::meta::unknown_<Site>, ...)\n   {\n     return generic_dispatcher<tag::nextpow2_, Site>();\n   }\n   template<class... Args>\n   struct impl_nextpow2_;\n  }\n  /*!\n    Returns the least n such that abs(x) is less or equal to \\f$2^n\\f$\n\n    @par Semantic:\n\n    @code\n    T r = nextpow2(a0);\n    @endcode\n\n    is similar to:\n\n    @code\n    T n = ceil(log2(abs(x)x));\n    @endcode\n\n    @param a0\n\n    @return a value of same type as the input\n  **/\n  BOOST_DISPATCH_FUNCTION_IMPLEMENTATION(tag::nextpow2_, nextpow2, 1)\n} }\n\n#endif\n", "meta": {"hexsha": "4c36115a4f773668374397a85b429773913c7f80", "size": 1951, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/base/include/boost/simd/ieee/functions/nextpow2.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/ieee/functions/nextpow2.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/ieee/functions/nextpow2.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.1194029851, "max_line_length": 139, "alphanum_fraction": 0.612506407, "num_tokens": 480, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.63341027059799, "lm_q1q2_score": 0.47817089912508376}}
{"text": "#include <blitz/array.h>\n#include <iostream>\n#include <vector>\n#include <math.h>\n\n// Mapping preexisting data the const way\nclass Test {\n    public:\n        std::vector<double> v;\n        void mapBlitz() const;\n};\n\nvoid Test::mapBlitz() const{\n    using namespace blitz;\n    const Array<double,1> vecArray(const_cast<double*>(&v[0]), shape(v.size()), neverDeleteData);\n}\nvoid testConst(){\n    Test t = Test();\n    t.v = std::vector<double>(10,3.2);\n    t.mapBlitz();\n}\n\n\n// Blitz++ has built-in stride support\ntemplate<unsigned int dimension>\nvoid strideT(unsigned int size){\n    using namespace blitz;\n    TinyVector<unsigned int, dimension> v =size;\n    Array<double,dimension> data(v);\n    data = 1;\n    \n    TinyVector<int, dimension> low = fromStart;\n    TinyVector<int, dimension> high = toEnd;\n    TinyVector<int, dimension> stride = 2;\n    StridedDomain<dimension> sd(low, high, stride);\n    Array<double,dimension> strided = data(sd);\n    std::cout << strided;\n}\nvoid stride(unsigned int size){\n    using namespace blitz;\n\n    Array<double,1> vecArray(shape(size));\n    vecArray = tensor::i;\n\n    // Variant 1, form depends on dimension\n    Array<double,1> strided = vecArray(Range(fromStart, toEnd, 2));\n    std::cout << strided; // outputs 0 2 4 ...\n    \n    // Variant 2, extensible to n dimensions\n    StridedDomain<1> sd (shape(fromStart), shape(toEnd), 2);\n    Array<double,1> strided2 = vecArray(sd);\n    std::cout << strided2;\n\n    // Variant 3 = variant 2 extended to n dimensions\n    strideT<3>(size);\n}\n\n// Assigning a matrix to a formula depending on itself\n// using tensor\nvoid operatorDiv(unsigned int size){\n    using namespace blitz;\n    Array<double,2> matrix1(shape(size, size));\n    matrix1 = 1.0;\n    matrix1 /= 2 * 4;\n    std::cout << matrix1; // outputs 2 2 ...\n}\n\n\n// Assigning a matrix to a formula depending on itself\n// using tensor\nvoid tensorSelf(unsigned int size){\n    using namespace blitz;\n    Array<double,2> matrix1(shape(size, size));\n    matrix1 = 1;\n    matrix1 = matrix1(tensor::i, tensor::j) + matrix1(tensor::i, tensor::j);\n    std::cout << matrix1; // outputs 2 2 ...\n}\n\n// Combining tensor::i with range\n// the tensor::i starts at 0, no matter what the range\nvoid tensorRange(unsigned int size){\n    using namespace blitz;\n    Array<double,2> matrix1(shape(size, size));\n    matrix1 = 1;\n    Array<double,2> matrix2(shape(size, size));\n    matrix2 = 2;\n\n    matrix2(Range(size/2, size-1), Range::all()) =\n            tensor::i;  // Fills with 0, 1, 2, ...\n\n    std::cout << matrix2;\n}\n\n\n\n// Speeed test of tensor notation\nvoid speedTest(unsigned int size){\n    using namespace blitz;\n    Array<double,2> matrix(shape(size, size));\n    double dKX = 1.1;\n    double dKY = 1.2;\n    double deltaZ = 0.02;\n    double energyTerm = 1;\n\n    matrix = exp(- sqrt(tensor::i * dKX * tensor::i * dKX + tensor::j *dKY * tensor::j * dKY - energyTerm) * deltaZ);\n    std::cout << \"Finished\\n\";\n    std::cout << matrix(2,3);\n}\n\n// Calculate with tensor indices inside parameter, i.e. A(tensor::i * 2)\n// This is forbidden.\nvoid indexCalc(unsigned int size){\n    using namespace blitz;\n    Array<double,1> vecarray(shape(size));\n    Array<double,1> vec2array(shape(size*2));\n    vec2array = tensor::i;\n//  vecarray = vec2array( (tensor::i) * 2);\n    std::cout << vecarray;\n}\n\n// Fill Array with tensor notation plus questionmark operator\n// This does *not* work.\nvoid fillArrayAdvanced(unsigned int size){\n    using namespace blitz;\n    Array<double,1> vecarray(shape(size));\n    //vecarray = (tensor::i % 2 == 0) ? (tensor::i * tensor::i) : (0);\n    std::cout << vecarray;\n}\n\n// Fill Array with tensor notation\nvoid fillArray(unsigned int size){\n    using namespace blitz;\n    Array<double,1> vecArray(shape(size));\n    vecArray = tensor::i * tensor::i;\n    std::cout << vecArray;\n}\n\n\n// Resizing array - works.\n// Note: If array deletes data when done you get an error because of \n// double free (from vector and Array)\nvoid resizeArray(unsigned int size) {\n    using namespace blitz;\n    \n    std::vector<double> vec(size,3.4);\n    \n    Array<double,1> vecArray(&vec[0], shape(size), neverDeleteData);\n   \n    vecArray(1) = 100; \n    vecArray(0) = 70; \n    cout << vecArray << endl;\n    vecArray.resizeAndPreserve(shape(size+1));\n    cout << vecArray << endl;\n}\n\n// Partially mapping a vector works as well.\nvoid doubleReuseVector(unsigned int size) {\n    using namespace blitz;\n    \n    std::vector<double> vec(size,3.4);\n    \n    Array<double,1> vecArray(&vec[0], shape(size), neverDeleteData);\n    Array<double,1> vecArray2(&vec[size/2], shape(size/2), neverDeleteData);\n    vecArray2(1) = 20;\n    vec[7]=100;\n    cout << vecArray;\n}\n\n\n// This works perfectly. The Array reuses the vector. \nvoid reuseVector(unsigned int size) {\n    using namespace blitz;\n    \n    std::vector<double> vec(size,3.4);\n    Array<double,1> vecArray(&vec[0], shape(size), neverDeleteData);\n    vec[7]=100;\n\n    cout << vecArray;\n}\n\nvoid reuseArray(){\n   using namespace::blitz; \n   using namespace tensor;\n    double data[] = {1,2,3,4,5,6,7,8,9,10,11,12};    \n    Array<double,3> dataArray(data, shape(3,2,2), neverDeleteData);\n    cout << dataArray;\n    std::cout << dataArray(0,0,1);\n    cout << dataArray(0,1,0);\n    cout << dataArray(1,0,0);\n\n//    Array<double,1> reduced(sum(dataArray(j,i),j));\n//    cout << reduced;\n}\n\nvoid reduceTensor() {\n    using namespace blitz;\n    Array<float,2> A(3,3);\n    Array<float,1> B(3);\n    A = 0, 1, 2,\n    3, 4, 5,\n    6, 7, 8;\n\n    cout << A;\n    B= sum(A(tensor::i,tensor::j),tensor::j);\n    cout << B;\n    \n    cout << sum(A) << endl          // 36\n         << min(A) << endl          // 0\n         << count(A >= 4) << endl;  // 5\n}\n\n// When partially reducing a multidimensional array,\n// the storage order is correctly as indicated by the indices.\nvoid reduceOrder() {\n    using namespace blitz;\n    Array<float,3> A(2,2,2);\n    A = 0, 1, 2, 3, 4, 5, 6, 7;\n    std::vector<float> vA; vA.assign(A.begin(), A.end());\n    std::vector<float>::const_iterator beginA = vA.begin(), endA = vA.end();\n\n    cout << \"Storage order in data: \";\n    while(beginA != endA){\n        std::cout << *beginA<< \" \";\n        ++beginA;\n    }\n    cout << endl;\n\n    // Fastest direction should be z, then y, then x\n\n    cout << A;\n    //Array<float,2> B(2,2);\n    Array<float,2> B;// = Array<float,2>();\n    //Array<float,2> B(sum(A(tensor::i,tensor::k, tensor::j),tensor::k),\n            //RowMajorArray<2>);\n//    B = sum(A(tensor::i,tensor::k, tensor::j),tensor::k);\n    firstIndex i; secondIndex j; thirdIndex k;\n    B = blitz::sum(A, k);\n\n\n    // Since y is reduced, this should yield \n    // x/z  1     2\n    // 1   0+2    1+3\n    // 2   4+6    5+7\n    cout << B;\n    std::vector<float> v; v.assign(B.begin(), B.end());\n    std::vector<float>::const_iterator begin = v.begin(), end = v.end();\n\n    cout << \"Storage order in data: \";\n    while(begin != end){\n        std::cout << *begin << \" \";\n        ++begin;\n    }\n    cout << endl;\n    \n}\n\nvoid testManual(){\n    using namespace blitz;\n    Array<float,3> A(2,2);   // ...\n    A = 0, 1, 2, 3;\n    Array<float,1> B;   // ...\n    firstIndex i;\n    secondIndex j;\n    thirdIndex k;\n\n    // Reduce over dimension 2 of a 3-D array?\n    B = sum(A(i,j), j);\n    cout << B;\n}\n\nint main() {\n    unsigned int size = 20;\n//  doubleReuseVector(size);\n//  reuseArray();\n//  fillArrayAdvanced(size);\n//  resizeArray(size);\n//  speedTest(270);\n//  indexCalc(size);\n//  tensorRange(size);\n//  tensorSelf(size);\n//  operatorDiv(size);\n//  stride(size);\n//  reduceOrder();\n    testManual();\n    return 0;\n}\n", "meta": {"hexsha": "2e4bbb70ae264300ae8a25559d1ece4b4219ace1", "size": 7589, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/blitz.cpp", "max_stars_repo_name": "ltalirz/util-programs", "max_stars_repo_head_hexsha": "93c76cb8f52543b55afdd968f6d8374997031a27", "max_stars_repo_licenses": ["MIT"], "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/blitz.cpp", "max_issues_repo_name": "ltalirz/util-programs", "max_issues_repo_head_hexsha": "93c76cb8f52543b55afdd968f6d8374997031a27", "max_issues_repo_licenses": ["MIT"], "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/blitz.cpp", "max_forks_repo_name": "ltalirz/util-programs", "max_forks_repo_head_hexsha": "93c76cb8f52543b55afdd968f6d8374997031a27", "max_forks_repo_licenses": ["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.4425087108, "max_line_length": 117, "alphanum_fraction": 0.6087758598, "num_tokens": 2234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6334102567576901, "lm_q1q2_score": 0.4781708956620527}}
{"text": "#include <boost/test/unit_test.hpp>\n#include <chipmunk.hpp>\n\nusing namespace cp;\n\nBOOST_AUTO_TEST_CASE(BBTest) {\n\tBB bb = BB::forCircle(Vect(30, 100), 5);\n\tBOOST_CHECK(bb.contains(Vect(30, 100)));\n\tBOOST_CHECK(bb.contains(Vect(34, 100)));\n\tBOOST_CHECK(bb.contains(Vect(26, 102)));\n\tBOOST_CHECK(!bb.contains(Vect(36, 100)));\n\tBOOST_CHECK(!bb.contains(Vect(30, 94)));\n\tBOOST_CHECK(!bb.contains(Vect(20, 106)));\n}", "meta": {"hexsha": "d7ceefeaf013057faf7d6afe4bdaed3dbb208ff6", "size": 410, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_test/bb.cpp", "max_stars_repo_name": "amiani/chipmunkpp", "max_stars_repo_head_hexsha": "4ffd0c9ae269dcdec2e693c439f28bf1bd63bff8", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 30.0, "max_stars_repo_stars_event_min_datetime": "2015-04-06T21:43:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-06T10:06:39.000Z", "max_issues_repo_path": "unit_test/bb.cpp", "max_issues_repo_name": "amiani/chipmunkpp", "max_issues_repo_head_hexsha": "4ffd0c9ae269dcdec2e693c439f28bf1bd63bff8", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2015-04-22T08:13:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-03T20:22:03.000Z", "max_forks_repo_path": "unit_test/bb.cpp", "max_forks_repo_name": "amiani/chipmunkpp", "max_forks_repo_head_hexsha": "4ffd0c9ae269dcdec2e693c439f28bf1bd63bff8", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-25T19:15:17.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-25T19:15:17.000Z", "avg_line_length": 29.2857142857, "max_line_length": 42, "alphanum_fraction": 0.712195122, "num_tokens": 123, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6334102567576901, "lm_q1q2_score": 0.4781708956620527}}
{"text": "\ufeff#include <boost/test/unit_test.hpp>\n\n#include \"logs.h\"\n#include \"route.h\"\n#include \"track.h\"\n\nusing namespace GPS;\n\nBOOST_AUTO_TEST_SUITE( Route_minLongitude )\n\nconst bool isFileName = true;\n\n\n// The function i have chose is Route::minLongitude(). The function should find the minimum longitude in the points in a gpx files.\n// The test cases will consist of finding the longitude on a positve and negative stationary points where both longitude and latitude points are static\n// and doesnt not change. Then the gpx will be a horizontal and vertical line where either the longitude or latitude will not change and we will see\n// if the function will still run and return the minimum longitude. There will be another test to see if the function can return the minimum longitude\n// where the points will be unsorted and finally, there will a test case to see if it can detect small minuscule changes in the millionth and bigger numbers.\n// These tests will ensure that the function is functionable and that can find the minimum longitude without having to worry about the order or the points,\n// repeated points and with little or large changes.\n\n// RouteStationaryPoints has 5 points all stationary and positive\n// This test case is to find out if it can still return the minimum longitude\n\nBOOST_AUTO_TEST_CASE( CheckPostiveStationaryPoints )\n{\n        Route route = Route(Logfiles::GPXRoutesDir + \"RouteStationaryPoints.gpx\", isFileName);\n        BOOST_CHECK_EQUAL( route.minLongitude(), -1.45248);\n}\n\n// RouteStationaryNegativePoints has 5 points all stationary and negative\n// This will find out if the test can still return the minimum longitude even when its negative\n\nBOOST_AUTO_TEST_CASE( CheckNegativeStationaryPoints )\n{\n        Route route = Route(Logfiles::GPXRoutesDir + \"RouteStationaryNegativePoints.gpx\", isFileName);\n        BOOST_CHECK_EQUAL( route.minLongitude(), -0.207456);\n}\n\n// In CliftonStraightVerticalLine gpx file, the points are going vertical therefore, the longitude\n// should be the same throughout the points\n\nBOOST_AUTO_TEST_CASE( CheckLongitudeVerticalLine )\n{\n        Route route = Route(Logfiles::GPXRoutesDir + \"CliftonStraightVerticalLine.gpx\", isFileName);\n        BOOST_CHECK_EQUAL( route.minLongitude(), -1.19);\n}\n\n// In CliftonStraightLineIncreasingLong gpx file, the latitude points are static and only the longitude\n// has changed.\n\nBOOST_AUTO_TEST_CASE( CheckLongitudeVerticalLine )\n{\n        Route route = Route(Logfiles::GPXRoutesDir + \"CliftonStraightLineIncreasingLong.gpx\", isFileName);\n        BOOST_CHECK_EQUAL( route.minLongitude(), -1.19);\n}\n\n// In RouteChangingLongitude gpx file, the points are going horizontal and the longitude\n// are all negative, the test case should return the minimum longitude\n\nBOOST_AUTO_TEST_CASE( CheckLongitudeHorizontalLine )\n{\n        Route route = Route(Logfiles::GPXRoutesDir + \"RouteChangingLongitude.gpx\", isFileName);\n        BOOST_CHECK_EQUAL( route.minLongitude(), -1.45248);\n}\n\n// In Route_Different_Longitudes_Log gpx file, the longitude points are not in order, the test\n// should return the minimum longitude if the function is working as intended\nBOOST_AUTO_TEST_CASE( CheckLongitudeUnsorted )\n{\n        Route route = Route(Logfiles::GPXRoutesDir + \"Route_Different_Longitudes_Log.gpx\", isFileName);\n        BOOST_CHECK_EQUAL( route.minLongitude(), 7.12765439876543);\n}\n\n// The gpx has the longitude change by 50 each time\n// This test is to try and find out if it can still return the minimum longitude.\n\nBOOST_AUTO_TEST_CASE( CheckLongitudeWithBigChange)\n{\n        Route route = Route(Logfiles::GPXRoutesDir + \"LongitudeChangeOf50.gpx\", isFileName);\n        BOOST_CHECK_EQUAL( route.minLongitude(), 1);\n}\n\n// The gpx has the longitude change by 0.0000001 each time\n// This test is to try and find out if it can still return the minimum longitude even with a minuscule change.\n\nBOOST_AUTO_TEST_CASE( CheckLongitudeWithMinusculeChange)\n{\n        Route route = Route(Logfiles::GPXRoutesDir + \"LongitudeChangeOf0000001.gpx\", isFileName);\n        BOOST_CHECK_EQUAL( route.minLongitude(), 1.0000000);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "ebdb4f4410a236a01df2a2afe1ce28825cc241a8", "size": 4126, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/gpx-tests/minLongitude_N0671080.cpp", "max_stars_repo_name": "EdwinLangley/GPX-Route-and-Track", "max_stars_repo_head_hexsha": "e4de303c62c7e9dc92724e8f257f7960ff77c992", "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/gpx-tests/minLongitude_N0671080.cpp", "max_issues_repo_name": "EdwinLangley/GPX-Route-and-Track", "max_issues_repo_head_hexsha": "e4de303c62c7e9dc92724e8f257f7960ff77c992", "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/gpx-tests/minLongitude_N0671080.cpp", "max_forks_repo_name": "EdwinLangley/GPX-Route-and-Track", "max_forks_repo_head_hexsha": "e4de303c62c7e9dc92724e8f257f7960ff77c992", "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": 43.8936170213, "max_line_length": 157, "alphanum_fraction": 0.7719340766, "num_tokens": 925, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102498375401, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.47817089043792776}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   tstHistogramFullyTabularBasicBivariateDistribution.cpp\n//! \\author Alex Robinson\n//! \\brief  The histogram fully tabular two-dimensional dist. unit tests\n//!\n//---------------------------------------------------------------------------//\n\n// Std Lib Includes\n#include <iostream>\n#include <memory>\n\n// Boost Includes\n#include <boost/units/systems/cgs.hpp>\n#include <boost/units/io.hpp>\n\n// FRENSIE Includes\n#include \"Utility_HistogramFullyTabularBasicBivariateDistribution.hpp\"\n#include \"Utility_DeltaDistribution.hpp\"\n#include \"Utility_UniformDistribution.hpp\"\n#include \"Utility_ElectronVoltUnit.hpp\"\n#include \"Utility_BarnUnit.hpp\"\n#include \"Utility_UnitTestHarnessWithMain.hpp\"\n#include \"ArchiveTestHelpers.hpp\"\n\n//---------------------------------------------------------------------------//\n// Testing Types\n//---------------------------------------------------------------------------//\n\nusing boost::units::quantity;\nusing Utility::Units::MegaElectronVolt;\nusing Utility::Units::MeV;\nusing Utility::Units::Barn;\nusing Utility::Units::barn;\nusing Utility::Units::barns;\nnamespace cgs = boost::units::cgs;\n\ntypedef TestArchiveHelper::TestArchives TestArchives;\n\n//---------------------------------------------------------------------------//\n// Testing Variables\n//---------------------------------------------------------------------------//\nstd::shared_ptr<Utility::UnitAwareBasicBivariateDistribution<MegaElectronVolt,cgs::length,Barn> >\n  unit_aware_distribution;\n\nstd::shared_ptr<Utility::UnitAwareFullyTabularBasicBivariateDistribution<MegaElectronVolt,cgs::length,Barn> >\n  unit_aware_tab_distribution;\n\nstd::shared_ptr<Utility::BasicBivariateDistribution> distribution;\n\nstd::shared_ptr<Utility::FullyTabularBasicBivariateDistribution> tab_distribution;\n\n//---------------------------------------------------------------------------//\n// Tests.\n//---------------------------------------------------------------------------//\n// Check that the upper bound of the distribution primary independent variable\n// can be returned\nFRENSIE_UNIT_TEST( HistogramFullyTabularBasicBivariateDistribution,\n                   getUpperBoundOfPrimaryIndepVar )\n{\n  FRENSIE_CHECK_EQUAL( distribution->getUpperBoundOfPrimaryIndepVar(), 2.0 );\n}\n\n//---------------------------------------------------------------------------//\n// Check that the upper bound of the unit-aware distribution primary\n// independent variable can be returned\nFRENSIE_UNIT_TEST( UnitAwareHistogramFullyTabularBasicBivariateDistribution,\n                   getUpperBoundOfPrimaryIndepVar )\n{\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->getUpperBoundOfPrimaryIndepVar(), 2.0*MeV );\n}\n\n//---------------------------------------------------------------------------//\n// Check that the lower bound of the distribution primary independent variable\n// can be returned\nFRENSIE_UNIT_TEST( HistogramFullyTabularBasicBivariateDistribution,\n                   getLowerBoundOfPrimaryIndepVar )\n{\n  FRENSIE_CHECK_EQUAL( distribution->getLowerBoundOfPrimaryIndepVar(), 0.0 );\n}\n\n//---------------------------------------------------------------------------//\n// Check that the lower bound of the unit-aware distribution primary\n// independent variable can be returned\nFRENSIE_UNIT_TEST( UnitAwareHistogramFullyTabularBasicBivariateDistribution,\n                   getLowerBoundOfPrimaryIndepVar )\n{\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->getLowerBoundOfPrimaryIndepVar(), 0.0*MeV );\n}\n\n//---------------------------------------------------------------------------//\n// Check that the upper bound of the conditional distribution independent\n// variable can be returned\nFRENSIE_UNIT_TEST( HistogramFullyTabularBasicBivariateDistribution,\n                   getUpperBoundOfSecondaryConditionalIndepVar )\n{\n  // Before the first bin - no extension\n  FRENSIE_CHECK_EQUAL(\n                 distribution->getUpperBoundOfSecondaryConditionalIndepVar(-1.0), 0.0 );\n\n  // Before the first bin - with extension\n  tab_distribution->extendBeyondPrimaryIndepLimits();\n\n  FRENSIE_CHECK_EQUAL(\n                 distribution->getUpperBoundOfSecondaryConditionalIndepVar(-1.0), 0.0 );\n\n  tab_distribution->limitToPrimaryIndepLimits();\n\n  // On the second bin (first bin boundary = second bin boundary)\n  FRENSIE_CHECK_EQUAL(\n                 distribution->getUpperBoundOfSecondaryConditionalIndepVar(0.0), 10.0 );\n\n\n  // In the second bin\n  FRENSIE_CHECK_EQUAL(\n                 distribution->getUpperBoundOfSecondaryConditionalIndepVar(0.5), 10.0 );\n\n  // On the third bin\n  FRENSIE_CHECK_EQUAL(\n                 distribution->getUpperBoundOfSecondaryConditionalIndepVar(1.0), 10.0 );\n\n  // In the third bin\n  FRENSIE_CHECK_EQUAL(\n                 distribution->getUpperBoundOfSecondaryConditionalIndepVar(1.5), 10.0 );\n\n  // On the upper bin boundary - this should be treated as part of the third\n  // bin (special case)\n  FRENSIE_CHECK_EQUAL(\n                 distribution->getUpperBoundOfSecondaryConditionalIndepVar(2.0), 10.0 );\n\n  // After the third bin - no extension\n  FRENSIE_CHECK_EQUAL(\n                  distribution->getUpperBoundOfSecondaryConditionalIndepVar(3.0), 0.0 );\n\n  // After the third bin - with extension\n  tab_distribution->extendBeyondPrimaryIndepLimits();\n\n  FRENSIE_CHECK_EQUAL(\n                  distribution->getUpperBoundOfSecondaryConditionalIndepVar(3.0), 0.0 );\n\n  tab_distribution->limitToPrimaryIndepLimits();\n}\n\n//---------------------------------------------------------------------------//\n// Check that the upper bound of the unit-aware conditional distribution\n// independent variable can be returned\nFRENSIE_UNIT_TEST( UnitAwareHistogramFullyTabularBasicBivariateDistribution,\n                   getUpperBoundOfSecondaryConditionalIndepVar )\n{\n  // Before the first bin - no extension\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->getUpperBoundOfSecondaryConditionalIndepVar(-1.0*MeV), 0.0*cgs::centimeter );\n\n  // Before the first bin - with extension\n  unit_aware_tab_distribution->extendBeyondPrimaryIndepLimits();\n\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->getUpperBoundOfSecondaryConditionalIndepVar(-1.0*MeV), 0.0*cgs::centimeter );\n\n  unit_aware_tab_distribution->limitToPrimaryIndepLimits();\n\n  // On the second bin (first bin boundary = second bin boundary)\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->getUpperBoundOfSecondaryConditionalIndepVar(0.0*MeV), 10.0*cgs::centimeter );\n\n  // In the second bin\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->getUpperBoundOfSecondaryConditionalIndepVar(0.5*MeV), 10.0*cgs::centimeter );\n\n  // On the third bin\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->getUpperBoundOfSecondaryConditionalIndepVar(1.0*MeV), 10.0*cgs::centimeter );\n\n  // In the third bin\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->getUpperBoundOfSecondaryConditionalIndepVar(1.5*MeV), 10.0*cgs::centimeter );\n\n  // On the upper bin boundary - this should be treated as part of the third\n  // bin (special case)\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->getUpperBoundOfSecondaryConditionalIndepVar(2.0*MeV), 10.0*cgs::centimeter );\n\n  // After the third bin - no extension\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->getUpperBoundOfSecondaryConditionalIndepVar(3.0*MeV), 0.0*cgs::centimeter );\n\n  // After the third bin - with extension\n  unit_aware_tab_distribution->extendBeyondPrimaryIndepLimits();\n\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->getUpperBoundOfSecondaryConditionalIndepVar(3.0*MeV), 0.0*cgs::centimeter );\n\n  unit_aware_tab_distribution->limitToPrimaryIndepLimits();\n}\n\n//---------------------------------------------------------------------------//\n// Check that the lower bound of the conditional distribution independent\n// variable can be returned\nFRENSIE_UNIT_TEST( HistogramFullyTabularBasicBivariateDistribution,\n                   getLowerBoundOfSecondaryConditionalIndepVar )\n{\n  // Before the first bin - no extension\n  FRENSIE_CHECK_EQUAL(\n                 distribution->getLowerBoundOfSecondaryConditionalIndepVar(-1.0), 0.0 );\n\n  // Before the first bin - with extension\n  tab_distribution->extendBeyondPrimaryIndepLimits();\n\n  FRENSIE_CHECK_EQUAL(\n                 distribution->getLowerBoundOfSecondaryConditionalIndepVar(-1.0), 0.0 );\n\n  tab_distribution->limitToPrimaryIndepLimits();\n\n  // On the second bin (first bin boundary = second bin boundary)\n  FRENSIE_CHECK_EQUAL(\n                  distribution->getLowerBoundOfSecondaryConditionalIndepVar(0.0), 0.0 );\n\n\n  // In the second bin\n  FRENSIE_CHECK_EQUAL(\n                  distribution->getLowerBoundOfSecondaryConditionalIndepVar(0.5), 0.0 );\n\n  // On the third bin\n  FRENSIE_CHECK_EQUAL(\n                  distribution->getLowerBoundOfSecondaryConditionalIndepVar(1.0), 0.0 );\n\n  // In the third bin\n  FRENSIE_CHECK_EQUAL(\n                  distribution->getLowerBoundOfSecondaryConditionalIndepVar(1.5), 0.0 );\n\n  // On the upper bin boundary - this should be treated as part of the third\n  // bin (special case)\n  FRENSIE_CHECK_EQUAL(\n                  distribution->getLowerBoundOfSecondaryConditionalIndepVar(2.0), 0.0 );\n\n  // After the third bin - no extension\n  FRENSIE_CHECK_EQUAL(\n                  distribution->getLowerBoundOfSecondaryConditionalIndepVar(3.0), 0.0 );\n\n  // After the third bin - with extension\n  tab_distribution->extendBeyondPrimaryIndepLimits();\n\n  FRENSIE_CHECK_EQUAL(\n                  distribution->getLowerBoundOfSecondaryConditionalIndepVar(3.0), 0.0 );\n\n  tab_distribution->limitToPrimaryIndepLimits();\n}\n\n//---------------------------------------------------------------------------//\n// Check that the lower bound of the unit-aware conditional distribution\n// independent variable can be returned\nFRENSIE_UNIT_TEST( UnitAwareHistogramFullyTabularBasicBivariateDistribution,\n                   getLowerBoundOfSecondaryConditionalIndepVar )\n{\n  // Before the first bin - no extension\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->getLowerBoundOfSecondaryConditionalIndepVar(-1.0*MeV), 0.0*cgs::centimeter );\n\n  // Before the first bin - with extension\n  unit_aware_tab_distribution->extendBeyondPrimaryIndepLimits();\n\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->getLowerBoundOfSecondaryConditionalIndepVar(-1.0*MeV), 0.0*cgs::centimeter );\n\n  unit_aware_tab_distribution->limitToPrimaryIndepLimits();\n\n  // On the second bin (first bin boundary = second bin boundary)\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->getLowerBoundOfSecondaryConditionalIndepVar(0.0*MeV), 0.0*cgs::centimeter );\n\n  // In the second bin\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->getLowerBoundOfSecondaryConditionalIndepVar(0.5*MeV), 0.0*cgs::centimeter );\n\n  // On the third bin\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->getLowerBoundOfSecondaryConditionalIndepVar(1.0*MeV), 0.0*cgs::centimeter );\n\n  // In the third bin\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->getLowerBoundOfSecondaryConditionalIndepVar(1.5*MeV), 0.0*cgs::centimeter );\n\n  // On the upper bin boundary - this should be treated as part of the third\n  // bin (special case)\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->getLowerBoundOfSecondaryConditionalIndepVar(2.0*MeV), 0.0*cgs::centimeter );\n\n  // After the third bin - no extension\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->getLowerBoundOfSecondaryConditionalIndepVar(3.0*MeV), 0.0*cgs::centimeter );\n\n  // After the third bin - with extension\n  unit_aware_tab_distribution->extendBeyondPrimaryIndepLimits();\n\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->getLowerBoundOfSecondaryConditionalIndepVar(3.0*MeV), 0.0*cgs::centimeter );\n\n  unit_aware_tab_distribution->limitToPrimaryIndepLimits();\n}\n\n//---------------------------------------------------------------------------//\n// Check if the distribution is tabular in the primary dimension\nFRENSIE_UNIT_TEST( HistogramFullyTabularBasicBivariateDistribution,\n                   isPrimaryDimensionTabular )\n{\n  FRENSIE_CHECK( distribution->isPrimaryDimensionTabular() );\n}\n\n//---------------------------------------------------------------------------//\n// Check if the unit-aware distribution is tabular in the primary dimension\nFRENSIE_UNIT_TEST( UnitAwareHistogramFullyTabularBasicBivariateDistribution,\n                   isPrimaryDimensionTabular )\n{\n  FRENSIE_CHECK( unit_aware_distribution->isPrimaryDimensionTabular() );\n}\n\n//---------------------------------------------------------------------------//\n// Check if the distribution is continuous in the primary dimension\nFRENSIE_UNIT_TEST( HistogramFullyTabularBasicBivariateDistribution,\n                   isPrimaryDimensionContinuous )\n{\n  FRENSIE_CHECK( distribution->isPrimaryDimensionContinuous() );\n}\n\n//---------------------------------------------------------------------------//\n// Check if the unit-aware distribution is continuous in the primary dimension\nFRENSIE_UNIT_TEST( UnitAwareHistogramFullyTabularBasicBivariateDistribution,\n                   isPrimaryDimensionContinuous )\n{\n  FRENSIE_CHECK( unit_aware_distribution->isPrimaryDimensionContinuous() );\n}\n\n//---------------------------------------------------------------------------//\n// Check if the distribution has the same bounds as another distribution\nFRENSIE_UNIT_TEST( HistogramFullyTabularBasicBivariateDistribution,\n                   hasSamePrimaryBounds )\n{\n  std::shared_ptr<Utility::BasicBivariateDistribution> other_distribution;\n\n  {\n    std::vector<double> primary_grid( 2 );\n    std::vector<std::shared_ptr<const Utility::TabularUnivariateDistribution> >\n      secondary_dists( 2 );\n\n    primary_grid[0] = 0.0;\n    secondary_dists[0].reset( new Utility::DeltaDistribution( 0.0 ) );\n\n    primary_grid[1] = 2.0;\n    secondary_dists[1].reset( new Utility::DeltaDistribution( 1.0 ) );\n\n    other_distribution.reset(\n                  new Utility::HistogramFullyTabularBasicBivariateDistribution(\n                                             primary_grid, secondary_dists ) );\n  }\n\n  FRENSIE_CHECK( distribution->hasSamePrimaryBounds( *other_distribution ) );\n\n  {\n    std::vector<double> primary_grid( 2 );\n    std::vector<std::shared_ptr<const Utility::TabularUnivariateDistribution> >\n      secondary_dists( 2 );\n\n    primary_grid[0] = -1.0;\n    secondary_dists[0].reset( new Utility::DeltaDistribution( 0.0 ) );\n\n    primary_grid[1] = 2.0;\n    secondary_dists[1].reset( new Utility::DeltaDistribution( 1.0 ) );\n\n    other_distribution.reset(\n                  new Utility::HistogramFullyTabularBasicBivariateDistribution(\n                                             primary_grid, secondary_dists ) );\n  }\n\n  FRENSIE_CHECK( !distribution->hasSamePrimaryBounds( *other_distribution ) );\n\n  {\n    std::vector<double> primary_grid( 2 );\n    std::vector<std::shared_ptr<const Utility::TabularUnivariateDistribution> >\n      secondary_dists( 2 );\n\n    primary_grid[0] = 0.0;\n    secondary_dists[0].reset( new Utility::DeltaDistribution( 0.0 ) );\n\n    primary_grid[1] = 3.0;\n    secondary_dists[1].reset( new Utility::DeltaDistribution( 1.0 ) );\n\n    other_distribution.reset(\n                  new Utility::HistogramFullyTabularBasicBivariateDistribution(\n                                             primary_grid, secondary_dists ) );\n  }\n\n  FRENSIE_CHECK( !distribution->hasSamePrimaryBounds( *other_distribution ) );\n\n  {\n    std::vector<double> primary_grid( 2 );\n    std::vector<std::shared_ptr<const Utility::TabularUnivariateDistribution> >\n      secondary_dists( 2 );\n\n    primary_grid[0] = -1.0;\n    secondary_dists[0].reset( new Utility::DeltaDistribution( 0.0 ) );\n\n    primary_grid[1] = 3.0;\n    secondary_dists[1].reset( new Utility::DeltaDistribution( 1.0 ) );\n\n    other_distribution.reset(\n                  new Utility::HistogramFullyTabularBasicBivariateDistribution(\n                                             primary_grid, secondary_dists ) );\n  }\n\n  FRENSIE_CHECK( !distribution->hasSamePrimaryBounds( *other_distribution ) );\n}\n\n//---------------------------------------------------------------------------//\n// Check if the unit-aware distribution has the same bounds as another\n// distribution\nFRENSIE_UNIT_TEST( UnitAwareHistogramFullyTabularBasicBivariateDistribution,\n                   hasSamePrimaryBounds )\n{\n  std::shared_ptr<Utility::UnitAwareBasicBivariateDistribution<MegaElectronVolt,cgs::length,Barn> > other_distribution;\n\n  {\n    std::vector<quantity<MegaElectronVolt> > primary_grid( 2 );\n    std::vector<std::shared_ptr<const Utility::UnitAwareTabularUnivariateDistribution<cgs::length,Barn> > > secondary_dists( 2 );\n\n    primary_grid[0] = 0.0*MeV;\n    secondary_dists[0].reset( new Utility::UnitAwareDeltaDistribution<cgs::length,Barn>( 0.0*cgs::centimeter ) );\n\n    primary_grid[1] = 2.0*MeV;\n    secondary_dists[1].reset( new Utility::UnitAwareDeltaDistribution<cgs::length,Barn>( 1.0*cgs::centimeter ) );\n\n    other_distribution.reset(\n                       new Utility::UnitAwareHistogramFullyTabularBasicBivariateDistribution<MegaElectronVolt,cgs::length,Barn>(\n                                             primary_grid, secondary_dists ) );\n  }\n\n  FRENSIE_CHECK( unit_aware_distribution->hasSamePrimaryBounds( *other_distribution ) );\n\n  {\n    std::vector<quantity<MegaElectronVolt> > primary_grid( 2 );\n    std::vector<std::shared_ptr<const Utility::UnitAwareTabularUnivariateDistribution<cgs::length,Barn> > > secondary_dists( 2 );\n\n    primary_grid[0] = -1.0*MeV;\n    secondary_dists[0].reset( new Utility::UnitAwareDeltaDistribution<cgs::length,Barn>( 0.0*cgs::centimeter ) );\n\n    primary_grid[1] = 2.0*MeV;\n    secondary_dists[1].reset( new Utility::UnitAwareDeltaDistribution<cgs::length,Barn>( 1.0*cgs::centimeter ) );\n\n    other_distribution.reset(\n                       new Utility::UnitAwareHistogramFullyTabularBasicBivariateDistribution<MegaElectronVolt,cgs::length,Barn>(\n                                             primary_grid, secondary_dists ) );\n  }\n\n  FRENSIE_CHECK( !unit_aware_distribution->hasSamePrimaryBounds( *other_distribution ) );\n\n  {\n    std::vector<quantity<MegaElectronVolt> > primary_grid( 2 );\n    std::vector<std::shared_ptr<const Utility::UnitAwareTabularUnivariateDistribution<cgs::length,Barn> > > secondary_dists( 2 );\n\n    primary_grid[0] = 0.0*MeV;\n    secondary_dists[0].reset( new Utility::UnitAwareDeltaDistribution<cgs::length,Barn>( 0.0*cgs::centimeter ) );\n\n    primary_grid[1] = 3.0*MeV;\n    secondary_dists[1].reset( new Utility::UnitAwareDeltaDistribution<cgs::length,Barn>( 1.0*cgs::centimeter ) );\n\n    other_distribution.reset(\n                       new Utility::UnitAwareHistogramFullyTabularBasicBivariateDistribution<MegaElectronVolt,cgs::length,Barn>(\n                                             primary_grid, secondary_dists ) );\n  }\n\n  FRENSIE_CHECK( !unit_aware_distribution->hasSamePrimaryBounds( *other_distribution ) );\n\n  {\n    std::vector<quantity<MegaElectronVolt> > primary_grid( 2 );\n    std::vector<std::shared_ptr<const Utility::UnitAwareTabularUnivariateDistribution<cgs::length,Barn> > > secondary_dists( 2 );\n\n    primary_grid[0] = -1.0*MeV;\n    secondary_dists[0].reset( new Utility::UnitAwareDeltaDistribution<cgs::length,Barn>( 0.0*cgs::centimeter ) );\n\n    primary_grid[1] = 3.0*MeV;\n    secondary_dists[1].reset( new Utility::UnitAwareDeltaDistribution<cgs::length,Barn>( 1.0*cgs::centimeter ) );\n\n    other_distribution.reset(\n                       new Utility::UnitAwareHistogramFullyTabularBasicBivariateDistribution<MegaElectronVolt,cgs::length,Barn>(\n                                             primary_grid, secondary_dists ) );\n  }\n\n  FRENSIE_CHECK( !unit_aware_distribution->hasSamePrimaryBounds( *other_distribution ) );\n}\n\n//---------------------------------------------------------------------------//\n// Check that the distribution can be evaluated\nFRENSIE_UNIT_TEST( HistogramFullyTabularBasicBivariateDistribution, evaluate )\n{\n  // Before the first bin - no extension\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( -1.0, -1.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( -1.0, 0.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( -1.0, 1.0 ), 0.0 );\n\n  // Before the first bin - with extension\n  tab_distribution->extendBeyondPrimaryIndepLimits();\n\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( -1.0, -1.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( -1.0, 0.0 ), 1.0 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( -1.0, 1.0 ), 0.0 );\n\n  tab_distribution->limitToPrimaryIndepLimits();\n\n  // On the second bin (first bin boundary = second bin boundary)\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( 0.0, -1.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( 0.0, 0.0 ), 2.0 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( 0.0, 1.0 ), 2.0 );\n\n  // In the second bin\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( 0.5, -1.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( 0.5, 0.0 ), 2.0 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( 0.5, 1.0 ), 2.0 );\n\n  // On the third bin\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( 1.0, -1.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( 1.0, 0.0 ), 1.0 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( 1.0, 1.0 ), 1.0 );\n\n  // In the third bin\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( 1.5, -1.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( 1.5, 0.0 ), 1.0 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( 1.5, 1.0 ), 1.0 );\n\n  // On the upper bin boundary - this should be treated as part of the third\n  // bin (special case)\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( 2.0, -1.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( 2.0, 0.0 ), 1.0 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( 2.0, 1.0 ), 1.0 );\n\n  // After the third bin - no extension\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( 3.0, -1.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( 3.0, 0.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( 3.0, 1.0 ), 0.0 );\n\n  // After the third bin - with extension\n  tab_distribution->extendBeyondPrimaryIndepLimits();\n\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( 3.0, -1.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( 3.0, 0.0 ), 1.0 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( 3.0, 1.0 ), 0.0 );\n\n  tab_distribution->limitToPrimaryIndepLimits();\n}\n\n//---------------------------------------------------------------------------//\n// Check that the unit-aware distribution can be evaluated\nFRENSIE_UNIT_TEST( UnitAwareHistogramFullyTabularBasicBivariateDistribution, evaluate )\n{\n  // Before the first bin - no extension\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( -1.0*MeV, -1.0*cgs::centimeter ), 0.0*barn );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( -1.0*MeV, 0.0*cgs::centimeter ), 0.0*barn );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( -1.0*MeV, 1.0*cgs::centimeter ), 0.0*barn );\n\n  // Before the first bin - with extension\n  unit_aware_tab_distribution->extendBeyondPrimaryIndepLimits();\n\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( -1.0*MeV, -1.0*cgs::centimeter ), 0.0*barn );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( -1.0*MeV, 0.0*cgs::centimeter ), 1.0*barn );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( -1.0*MeV, 1.0*cgs::centimeter ), 0.0*barn );\n\n  unit_aware_tab_distribution->limitToPrimaryIndepLimits();\n\n  // On the second bin (first bin boundary = second bin boundary)\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( 0.0*MeV, -1.0*cgs::centimeter ), 0.0*barn );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( 0.0*MeV, 0.0*cgs::centimeter ), 2.0*barns );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( 0.0*MeV, 1.0*cgs::centimeter ), 2.0*barns );\n\n  // In the second bin\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( 0.5*MeV, -1.0*cgs::centimeter ), 0.0*barn );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( 0.5*MeV, 0.0*cgs::centimeter ), 2.0*barns );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( 0.5*MeV, 1.0*cgs::centimeter ), 2.0*barns );\n\n  // On the third bin\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( 1.0*MeV, -1.0*cgs::centimeter ), 0.0*barn );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( 1.0*MeV, 0.0*cgs::centimeter ), 1.0*barn );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( 1.0*MeV, 1.0*cgs::centimeter ), 1.0*barn );\n\n  // In the third bin\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( 1.5*MeV, -1.0*cgs::centimeter ), 0.0*barn );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( 1.5*MeV, 0.0*cgs::centimeter ), 1.0*barn );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( 1.5*MeV, 1.0*cgs::centimeter ), 1.0*barn );\n\n  // On the upper bin boundary - this should be treated as part of the third\n  // bin (special case)\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( 2.0*MeV, -1.0*cgs::centimeter ), 0.0*barn );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( 2.0*MeV, 0.0*cgs::centimeter ), 1.0*barn );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( 2.0*MeV, 1.0*cgs::centimeter ), 1.0*barn );\n\n  // After the third bin - no extension\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( 3.0*MeV, -1.0*cgs::centimeter ), 0.0*barn );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( 3.0*MeV, 0.0*cgs::centimeter ), 0.0*barn );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( 3.0*MeV, 1.0*cgs::centimeter ), 0.0*barn );\n\n  // After the third bin - with extension\n  unit_aware_tab_distribution->extendBeyondPrimaryIndepLimits();\n\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( 3.0*MeV, -1.0*cgs::centimeter ), 0.0*barn );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( 3.0*MeV, 0.0*cgs::centimeter ), 1.0*barn );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( 3.0*MeV, 1.0*cgs::centimeter ), 0.0*barn );\n\n  unit_aware_tab_distribution->limitToPrimaryIndepLimits();\n}\n\n//---------------------------------------------------------------------------//\n// Check that the secondary conditional PDF can be evaluated\nFRENSIE_UNIT_TEST( HistogramFullyTabularBasicBivariateDistribution,\n                   evaluateSecondaryConditionalPDF )\n{\n  // Before the first bin - no extension\n  FRENSIE_CHECK_EQUAL( distribution->evaluateSecondaryConditionalPDF( -1.0, -1.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluateSecondaryConditionalPDF( -1.0, 0.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluateSecondaryConditionalPDF( -1.0, 1.0 ), 0.0 );\n\n  // Before the first bin - with extension\n  tab_distribution->extendBeyondPrimaryIndepLimits();\n\n  FRENSIE_CHECK_EQUAL( distribution->evaluateSecondaryConditionalPDF( -1.0, -1.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluateSecondaryConditionalPDF( -1.0, 0.0 ), 1.0 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluateSecondaryConditionalPDF( -1.0, 1.0 ), 0.0 );\n\n  tab_distribution->limitToPrimaryIndepLimits();\n\n  // On the second bin (first bin boundary = second bin boundary)\n  FRENSIE_CHECK_EQUAL( distribution->evaluateSecondaryConditionalPDF( 0.0, -1.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluateSecondaryConditionalPDF( 0.0, 0.0 ), 0.1 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluateSecondaryConditionalPDF( 0.0, 1.0 ), 0.1 );\n\n  // In the second bin\n  FRENSIE_CHECK_EQUAL( distribution->evaluateSecondaryConditionalPDF( 0.5, -1.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluateSecondaryConditionalPDF( 0.5, 0.0 ), 0.1 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluateSecondaryConditionalPDF( 0.5, 1.0 ), 0.1 );\n\n  // On the third bin\n  FRENSIE_CHECK_EQUAL( distribution->evaluateSecondaryConditionalPDF( 1.0, -1.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluateSecondaryConditionalPDF( 1.0, 0.0 ), 0.1 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluateSecondaryConditionalPDF( 1.0, 1.0 ), 0.1 );\n\n  // In the third bin\n  FRENSIE_CHECK_EQUAL( distribution->evaluateSecondaryConditionalPDF( 1.5, -1.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluateSecondaryConditionalPDF( 1.5, 0.0 ), 0.1 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluateSecondaryConditionalPDF( 1.5, 1.0 ), 0.1 );\n\n  // On the upper bin boundary - this should be treated as part of the third\n  // bin (special case)\n  FRENSIE_CHECK_EQUAL( distribution->evaluateSecondaryConditionalPDF( 2.0, -1.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluateSecondaryConditionalPDF( 2.0, 0.0 ), 0.1 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluateSecondaryConditionalPDF( 2.0, 1.0 ), 0.1 );\n\n  // After the third bin - no extension\n  FRENSIE_CHECK_EQUAL( distribution->evaluateSecondaryConditionalPDF( 3.0, -1.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluateSecondaryConditionalPDF( 3.0, 0.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluateSecondaryConditionalPDF( 3.0, 1.0 ), 0.0 );\n\n  // After the third bin - with extension\n  tab_distribution->extendBeyondPrimaryIndepLimits();\n\n  FRENSIE_CHECK_EQUAL( distribution->evaluateSecondaryConditionalPDF( 3.0, -1.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluateSecondaryConditionalPDF( 3.0, 0.0 ), 1.0 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluateSecondaryConditionalPDF( 3.0, 1.0 ), 0.0 );\n\n  tab_distribution->limitToPrimaryIndepLimits();\n}\n\n//---------------------------------------------------------------------------//\n// Check that the unit-aware secondary conditional PDF can be evaluated\nFRENSIE_UNIT_TEST( UnitAwareHistogramFullyTabularBasicBivariateDistribution,\n                   evaluateSecondaryConditionalPDF )\n{\n  // Before the first bin - no extension\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluateSecondaryConditionalPDF( -1.0*MeV, -1.0*cgs::centimeter ), 0.0/cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluateSecondaryConditionalPDF( -1.0*MeV, 0.0*cgs::centimeter ), 0.0/cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluateSecondaryConditionalPDF( -1.0*MeV, 1.0*cgs::centimeter ), 0.0/cgs::centimeter );\n\n  // Before the first bin - with extension\n  unit_aware_tab_distribution->extendBeyondPrimaryIndepLimits();\n\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluateSecondaryConditionalPDF( -1.0*MeV, -1.0*cgs::centimeter ), 0.0/cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluateSecondaryConditionalPDF( -1.0*MeV, 0.0*cgs::centimeter ), 1.0/cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluateSecondaryConditionalPDF( -1.0*MeV, 1.0*cgs::centimeter ), 0.0/cgs::centimeter );\n\n  unit_aware_tab_distribution->limitToPrimaryIndepLimits();\n\n  // On the second bin (first bin boundary = second bin boundary)\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluateSecondaryConditionalPDF( 0.0*MeV, -1.0*cgs::centimeter ), 0.0/cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluateSecondaryConditionalPDF( 0.0*MeV, 0.0*cgs::centimeter ), 0.1/cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluateSecondaryConditionalPDF( 0.0*MeV, 1.0*cgs::centimeter ), 0.1/cgs::centimeter );\n\n  // In the second bin\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluateSecondaryConditionalPDF( 0.5*MeV, -1.0*cgs::centimeter ), 0.0/cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluateSecondaryConditionalPDF( 0.5*MeV, 0.0*cgs::centimeter ), 0.1/cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluateSecondaryConditionalPDF( 0.5*MeV, 1.0*cgs::centimeter ), 0.1/cgs::centimeter );\n\n  // On the third bin\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluateSecondaryConditionalPDF( 1.0*MeV, -1.0*cgs::centimeter ), 0.0/cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluateSecondaryConditionalPDF( 1.0*MeV, 0.0*cgs::centimeter ), 0.1/cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluateSecondaryConditionalPDF( 1.0*MeV, 1.0*cgs::centimeter ), 0.1/cgs::centimeter );\n\n  // In the third bin\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluateSecondaryConditionalPDF( 1.5*MeV, -1.0*cgs::centimeter ), 0.0/cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluateSecondaryConditionalPDF( 1.5*MeV, 0.0*cgs::centimeter ), 0.1/cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluateSecondaryConditionalPDF( 1.5*MeV, 1.0*cgs::centimeter ), 0.1/cgs::centimeter );\n\n  // On the upper bin boundary - this should be treated as part of the third\n  // bin (special case)\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluateSecondaryConditionalPDF( 2.0*MeV, -1.0*cgs::centimeter ), 0.0/cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluateSecondaryConditionalPDF( 2.0*MeV, 0.0*cgs::centimeter ), 0.1/cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluateSecondaryConditionalPDF( 2.0*MeV, 1.0*cgs::centimeter ), 0.1/cgs::centimeter );\n\n  // After the third bin - no extension\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluateSecondaryConditionalPDF( 3.0*MeV, -1.0*cgs::centimeter ), 0.0/cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluateSecondaryConditionalPDF( 3.0*MeV, 0.0*cgs::centimeter ), 0.0/cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluateSecondaryConditionalPDF( 3.0*MeV, 1.0*cgs::centimeter ), 0.0/cgs::centimeter );\n\n  // After the third bin - with extension\n  unit_aware_tab_distribution->extendBeyondPrimaryIndepLimits();\n\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluateSecondaryConditionalPDF( 3.0*MeV, -1.0*cgs::centimeter ), 0.0/cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluateSecondaryConditionalPDF( 3.0*MeV, 0.0*cgs::centimeter ), 1.0/cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluateSecondaryConditionalPDF( 3.0*MeV, 1.0*cgs::centimeter ), 0.0/cgs::centimeter );\n\n  unit_aware_tab_distribution->limitToPrimaryIndepLimits();\n}\n\n//---------------------------------------------------------------------------//\n// Check that the secondary conditional CDF can be evaluated\nFRENSIE_UNIT_TEST( HistogramFullyTabularBasicBivariateDistribution,\n                   evaluateSecondaryConditionalCDF )\n{\n  // Before the first bin - no extension\n  FRENSIE_CHECK_EQUAL( tab_distribution->evaluateSecondaryConditionalCDF( -1.0, -1.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( tab_distribution->evaluateSecondaryConditionalCDF( -1.0, 0.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( tab_distribution->evaluateSecondaryConditionalCDF( -1.0, 1.0 ), 0.0 );\n\n  // Before the first bin - with extension\n  tab_distribution->extendBeyondPrimaryIndepLimits();\n\n  FRENSIE_CHECK_EQUAL( tab_distribution->evaluateSecondaryConditionalCDF( -1.0, -1.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( tab_distribution->evaluateSecondaryConditionalCDF( -1.0, 0.0 ), 1.0 );\n  FRENSIE_CHECK_EQUAL( tab_distribution->evaluateSecondaryConditionalCDF( -1.0, 1.0 ), 1.0 );\n\n  tab_distribution->limitToPrimaryIndepLimits();\n\n  // On the second bin (first bin boundary = second bin boundary)\n  FRENSIE_CHECK_EQUAL( tab_distribution->evaluateSecondaryConditionalCDF( 0.0, -1.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( tab_distribution->evaluateSecondaryConditionalCDF( 0.0, 0.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( tab_distribution->evaluateSecondaryConditionalCDF( 0.0, 1.0 ), 0.1 );\n\n  // In the second bin\n  FRENSIE_CHECK_EQUAL( tab_distribution->evaluateSecondaryConditionalCDF( 0.5, -1.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( tab_distribution->evaluateSecondaryConditionalCDF( 0.5, 0.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( tab_distribution->evaluateSecondaryConditionalCDF( 0.5, 1.0 ), 0.1 );\n\n  // On the third bin\n  FRENSIE_CHECK_EQUAL( tab_distribution->evaluateSecondaryConditionalCDF( 1.0, -1.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( tab_distribution->evaluateSecondaryConditionalCDF( 1.0, 0.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( tab_distribution->evaluateSecondaryConditionalCDF( 1.0, 1.0 ), 0.1 );\n\n  // In the third bin\n  FRENSIE_CHECK_EQUAL( tab_distribution->evaluateSecondaryConditionalCDF( 1.5, -1.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( tab_distribution->evaluateSecondaryConditionalCDF( 1.5, 0.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( tab_distribution->evaluateSecondaryConditionalCDF( 1.5, 1.0 ), 0.1 );\n\n  // On the upper bin boundary - this should be treated as part of the third\n  // bin (special case)\n  FRENSIE_CHECK_EQUAL( tab_distribution->evaluateSecondaryConditionalCDF( 2.0, -1.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( tab_distribution->evaluateSecondaryConditionalCDF( 2.0, 0.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( tab_distribution->evaluateSecondaryConditionalCDF( 2.0, 1.0 ), 0.1 );\n\n  // After the third bin - no extension\n  FRENSIE_CHECK_EQUAL( tab_distribution->evaluateSecondaryConditionalCDF( 3.0, -1.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( tab_distribution->evaluateSecondaryConditionalCDF( 3.0, 0.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( tab_distribution->evaluateSecondaryConditionalCDF( 3.0, 1.0 ), 0.0 );\n\n  // After the third bin - with extension\n  tab_distribution->extendBeyondPrimaryIndepLimits();\n\n  FRENSIE_CHECK_EQUAL( tab_distribution->evaluateSecondaryConditionalCDF( 3.0, -1.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( tab_distribution->evaluateSecondaryConditionalCDF( 3.0, 0.0 ), 1.0 );\n  FRENSIE_CHECK_EQUAL( tab_distribution->evaluateSecondaryConditionalCDF( 3.0, 1.0 ), 1.0 );\n\n  tab_distribution->limitToPrimaryIndepLimits();\n}\n\n//---------------------------------------------------------------------------//\n// Check that the unit-aware secondary conditional CDF can be evaluated\nFRENSIE_UNIT_TEST( UnitAwareHistogramFullyTabularBasicBivariateDistribution,\n                   evaluateSecondaryConditionalCDF )\n{\n  // Before the first bin - no extension\n  FRENSIE_CHECK_EQUAL( unit_aware_tab_distribution->evaluateSecondaryConditionalCDF( -1.0*MeV, -1.0*cgs::centimeter ), 0.0 );\n  FRENSIE_CHECK_EQUAL( unit_aware_tab_distribution->evaluateSecondaryConditionalCDF( -1.0*MeV, 0.0*cgs::centimeter ), 0.0 );\n  FRENSIE_CHECK_EQUAL( unit_aware_tab_distribution->evaluateSecondaryConditionalCDF( -1.0*MeV, 1.0*cgs::centimeter ), 0.0 );\n\n  // Before the first bin - with extension\n  unit_aware_tab_distribution->extendBeyondPrimaryIndepLimits();\n\n  FRENSIE_CHECK_EQUAL( unit_aware_tab_distribution->evaluateSecondaryConditionalCDF( -1.0*MeV, -1.0*cgs::centimeter ), 0.0 );\n  FRENSIE_CHECK_EQUAL( unit_aware_tab_distribution->evaluateSecondaryConditionalCDF( -1.0*MeV, 0.0*cgs::centimeter ), 1.0 );\n  FRENSIE_CHECK_EQUAL( unit_aware_tab_distribution->evaluateSecondaryConditionalCDF( -1.0*MeV, 1.0*cgs::centimeter ), 1.0 );\n\n  unit_aware_tab_distribution->limitToPrimaryIndepLimits();\n\n  // On the second bin (first bin boundary = second bin boundary)\n  FRENSIE_CHECK_EQUAL( unit_aware_tab_distribution->evaluateSecondaryConditionalCDF( 0.0*MeV, -1.0*cgs::centimeter ), 0.0 );\n  FRENSIE_CHECK_EQUAL( unit_aware_tab_distribution->evaluateSecondaryConditionalCDF( 0.0*MeV, 0.0*cgs::centimeter ), 0.0 );\n  FRENSIE_CHECK_EQUAL( unit_aware_tab_distribution->evaluateSecondaryConditionalCDF( 0.0*MeV, 1.0*cgs::centimeter ), 0.1 );\n\n  // In the second bin\n  FRENSIE_CHECK_EQUAL( unit_aware_tab_distribution->evaluateSecondaryConditionalCDF( 0.5*MeV, -1.0*cgs::centimeter ), 0.0 );\n  FRENSIE_CHECK_EQUAL( unit_aware_tab_distribution->evaluateSecondaryConditionalCDF( 0.5*MeV, 0.0*cgs::centimeter ), 0.0 );\n  FRENSIE_CHECK_EQUAL( unit_aware_tab_distribution->evaluateSecondaryConditionalCDF( 0.5*MeV, 1.0*cgs::centimeter ), 0.1 );\n\n  // On the third bin\n  FRENSIE_CHECK_EQUAL( unit_aware_tab_distribution->evaluateSecondaryConditionalCDF( 1.0*MeV, -1.0*cgs::centimeter ), 0.0 );\n  FRENSIE_CHECK_EQUAL( unit_aware_tab_distribution->evaluateSecondaryConditionalCDF( 1.0*MeV, 0.0*cgs::centimeter ), 0.0 );\n  FRENSIE_CHECK_EQUAL( unit_aware_tab_distribution->evaluateSecondaryConditionalCDF( 1.0*MeV, 1.0*cgs::centimeter ), 0.1 );\n\n  // In the third bin\n  FRENSIE_CHECK_EQUAL( unit_aware_tab_distribution->evaluateSecondaryConditionalCDF( 1.5*MeV, -1.0*cgs::centimeter ), 0.0 );\n  FRENSIE_CHECK_EQUAL( unit_aware_tab_distribution->evaluateSecondaryConditionalCDF( 1.5*MeV, 0.0*cgs::centimeter ), 0.0 );\n  FRENSIE_CHECK_EQUAL( unit_aware_tab_distribution->evaluateSecondaryConditionalCDF( 1.5*MeV, 1.0*cgs::centimeter ), 0.1 );\n\n  // On the upper bin boundary - this should be treated as part of the third\n  // bin (special case)\n  FRENSIE_CHECK_EQUAL( unit_aware_tab_distribution->evaluateSecondaryConditionalCDF( 2.0*MeV, -1.0*cgs::centimeter ), 0.0 );\n  FRENSIE_CHECK_EQUAL( unit_aware_tab_distribution->evaluateSecondaryConditionalCDF( 2.0*MeV, 0.0*cgs::centimeter ), 0.0 );\n  FRENSIE_CHECK_EQUAL( unit_aware_tab_distribution->evaluateSecondaryConditionalCDF( 2.0*MeV, 1.0*cgs::centimeter ), 0.1 );\n\n  // After the third bin - no extension\n  FRENSIE_CHECK_EQUAL( unit_aware_tab_distribution->evaluateSecondaryConditionalCDF( 3.0*MeV, -1.0*cgs::centimeter ), 0.0 );\n  FRENSIE_CHECK_EQUAL( unit_aware_tab_distribution->evaluateSecondaryConditionalCDF( 3.0*MeV, 0.0*cgs::centimeter ), 0.0 );\n  FRENSIE_CHECK_EQUAL( unit_aware_tab_distribution->evaluateSecondaryConditionalCDF( 3.0*MeV, 1.0*cgs::centimeter ), 0.0 );\n\n  // After the third bin - with extension\n  unit_aware_tab_distribution->extendBeyondPrimaryIndepLimits();\n\n  FRENSIE_CHECK_EQUAL( unit_aware_tab_distribution->evaluateSecondaryConditionalCDF( 3.0*MeV, -1.0*cgs::centimeter ), 0.0 );\n  FRENSIE_CHECK_EQUAL( unit_aware_tab_distribution->evaluateSecondaryConditionalCDF( 3.0*MeV, 0.0*cgs::centimeter ), 1.0 );\n  FRENSIE_CHECK_EQUAL( unit_aware_tab_distribution->evaluateSecondaryConditionalCDF( 3.0*MeV, 1.0*cgs::centimeter ), 1.0 );\n\n  unit_aware_tab_distribution->limitToPrimaryIndepLimits();\n}\n\n//---------------------------------------------------------------------------//\n// Check that a secondary conditional PDF can be sampled\nFRENSIE_UNIT_TEST( HistogramFullyTabularBasicBivariateDistribution,\n                   sampleSecondaryConditional )\n{\n  // Before the first bin - no extension\n  FRENSIE_CHECK_THROW( distribution->sampleSecondaryConditional( -1.0 ),\n              std::logic_error );\n\n  // Before the first bin - with extension\n  tab_distribution->extendBeyondPrimaryIndepLimits();\n\n  double sample = distribution->sampleSecondaryConditional( -1.0 );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0 );\n\n  tab_distribution->limitToPrimaryIndepLimits();\n\n  // On the second bin (first bin boundary = second bin boundary)\n  std::vector<double> fake_stream( 3 );\n  fake_stream[0] = 0.0;\n  fake_stream[1] = 0.5;\n  fake_stream[2] = 1.0 - 1e-15;\n\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  sample = distribution->sampleSecondaryConditional( 0.0 );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0 );\n\n  sample = distribution->sampleSecondaryConditional( 0.0 );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0 );\n\n  sample = distribution->sampleSecondaryConditional( 0.0 );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0, 1e-9 );\n\n  // In the second bin\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  sample = distribution->sampleSecondaryConditional( 0.5 );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0 );\n\n  sample = distribution->sampleSecondaryConditional( 0.5 );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0 );\n\n  sample = distribution->sampleSecondaryConditional( 0.5 );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0, 1e-9 );\n\n  // On the third bin\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  sample = distribution->sampleSecondaryConditional( 1.0 );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0 );\n\n  sample = distribution->sampleSecondaryConditional( 1.0 );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0 );\n\n  sample = distribution->sampleSecondaryConditional( 1.0 );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0, 1e-9 );\n\n  // In the third bin\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  sample = distribution->sampleSecondaryConditional( 1.5 );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0 );\n\n  sample = distribution->sampleSecondaryConditional( 1.5 );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0 );\n\n  sample = distribution->sampleSecondaryConditional( 1.5 );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0, 1e-9 );\n\n  // On the upper bin boundary - this should be treated as part of the third\n  // bin (special case)\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  sample = distribution->sampleSecondaryConditional( 2.0 );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0 );\n\n  sample = distribution->sampleSecondaryConditional( 2.0 );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0 );\n\n  sample = distribution->sampleSecondaryConditional( 2.0 );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0, 1e-9 );\n\n  // After the third bin - no extension\n  Utility::RandomNumberGenerator::unsetFakeStream();\n\n  FRENSIE_CHECK_THROW( distribution->sampleSecondaryConditional( 3.0 ),\n              std::logic_error );\n\n  // After the third bin - with extension\n  tab_distribution->extendBeyondPrimaryIndepLimits();\n\n  sample = distribution->sampleSecondaryConditional( 3.0 );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0 );\n\n  tab_distribution->limitToPrimaryIndepLimits();\n}\n\n//---------------------------------------------------------------------------//\n// Check that a unit-aware secondary conditional PDF can be sampled\nFRENSIE_UNIT_TEST( UnitAwareHistogramFullyTabularBasicBivariateDistribution,\n                   sampleSecondaryConditional )\n{\n  // Before the first bin - no extension\n  FRENSIE_CHECK_THROW( unit_aware_distribution->sampleSecondaryConditional( -1.0*MeV ),\n              std::logic_error );\n\n  // Before the first bin - with extension\n  unit_aware_tab_distribution->extendBeyondPrimaryIndepLimits();\n\n  quantity<cgs::length> sample =\n    unit_aware_distribution->sampleSecondaryConditional( -1.0*MeV );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter );\n\n  unit_aware_tab_distribution->limitToPrimaryIndepLimits();\n\n  // On the second bin (first bin boundary = second bin boundary)\n  std::vector<double> fake_stream( 3 );\n  fake_stream[0] = 0.0;\n  fake_stream[1] = 0.5;\n  fake_stream[2] = 1.0 - 1e-15;\n\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  sample = unit_aware_distribution->sampleSecondaryConditional( 0.0*MeV );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter );\n\n  sample = unit_aware_distribution->sampleSecondaryConditional( 0.0*MeV );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0*cgs::centimeter );\n\n  sample = unit_aware_distribution->sampleSecondaryConditional( 0.0*MeV );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0*cgs::centimeter, 1e-9 );\n\n  // In the second bin\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  sample = unit_aware_distribution->sampleSecondaryConditional( 0.5*MeV );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter );\n\n  sample = unit_aware_distribution->sampleSecondaryConditional( 0.5*MeV );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0*cgs::centimeter );\n\n  sample = unit_aware_distribution->sampleSecondaryConditional( 0.5*MeV );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0*cgs::centimeter, 1e-9 );\n\n  // On the third bin\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  sample = unit_aware_distribution->sampleSecondaryConditional( 1.0*MeV );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter );\n\n  sample = unit_aware_distribution->sampleSecondaryConditional( 1.0*MeV );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0*cgs::centimeter );\n\n  sample = unit_aware_distribution->sampleSecondaryConditional( 1.0*MeV );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0*cgs::centimeter, 1e-9 );\n\n  // In the third bin\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  sample = unit_aware_distribution->sampleSecondaryConditional( 1.5*MeV );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter );\n\n  sample = unit_aware_distribution->sampleSecondaryConditional( 1.5*MeV );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0*cgs::centimeter );\n\n  sample = unit_aware_distribution->sampleSecondaryConditional( 1.5*MeV );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0*cgs::centimeter, 1e-9 );\n\n  // On the upper bin boundary - this should be treated as part of the third\n  // bin (special case)\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  sample = unit_aware_distribution->sampleSecondaryConditional( 2.0*MeV );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter );\n\n  sample = unit_aware_distribution->sampleSecondaryConditional( 2.0*MeV );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0*cgs::centimeter );\n\n  sample = unit_aware_distribution->sampleSecondaryConditional( 2.0*MeV );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0*cgs::centimeter, 1e-9 );\n\n  // After the third bin - no extension\n  Utility::RandomNumberGenerator::unsetFakeStream();\n\n  FRENSIE_CHECK_THROW( unit_aware_distribution->sampleSecondaryConditional( 3.0*MeV ),\n              std::logic_error );\n\n  // After the third bin - with extension\n  unit_aware_tab_distribution->extendBeyondPrimaryIndepLimits();\n\n  sample = unit_aware_distribution->sampleSecondaryConditional( 3.0*MeV );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter );\n\n  unit_aware_tab_distribution->limitToPrimaryIndepLimits();\n}\n\n//---------------------------------------------------------------------------//\n// Check that a secondary conditional PDF can be sampled\nFRENSIE_UNIT_TEST( HistogramFullyTabularBasicBivariateDistribution,\n                   sampleSecondaryConditionalAndRecordTrials )\n{\n  Utility::DistributionTraits::Counter trials = 0u;\n\n  // Before the first bin - no extension\n  FRENSIE_CHECK_THROW( distribution->sampleSecondaryConditionalAndRecordTrials( -1.0, trials ),\n              std::logic_error );\n  FRENSIE_CHECK_EQUAL( trials, 0u );\n\n  // Before the first bin - with extension\n  tab_distribution->extendBeyondPrimaryIndepLimits();\n\n  double sample = distribution->sampleSecondaryConditionalAndRecordTrials( -1.0, trials );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0 );\n  FRENSIE_CHECK_EQUAL( trials, 1u );\n\n  tab_distribution->limitToPrimaryIndepLimits();\n\n  // On the second bin (first bin boundary = second bin boundary)\n  std::vector<double> fake_stream( 3 );\n  fake_stream[0] = 0.0;\n  fake_stream[1] = 0.5;\n  fake_stream[2] = 1.0 - 1e-15;\n\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  sample = distribution->sampleSecondaryConditionalAndRecordTrials( 0.0, trials );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0 );\n  FRENSIE_CHECK_EQUAL( trials, 2u );\n\n  sample = distribution->sampleSecondaryConditionalAndRecordTrials( 0.0, trials );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0 );\n  FRENSIE_CHECK_EQUAL( trials, 3u );\n\n  sample = distribution->sampleSecondaryConditionalAndRecordTrials( 0.0, trials );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0, 1e-9 );\n  FRENSIE_CHECK_EQUAL( trials, 4u );\n\n  // In the second bin\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  sample = distribution->sampleSecondaryConditionalAndRecordTrials( 0.5, trials );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0 );\n  FRENSIE_CHECK_EQUAL( trials, 5u );\n\n  sample = distribution->sampleSecondaryConditionalAndRecordTrials( 0.5, trials );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0 );\n  FRENSIE_CHECK_EQUAL( trials, 6u );\n\n  sample = distribution->sampleSecondaryConditionalAndRecordTrials( 0.5, trials );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0, 1e-9 );\n  FRENSIE_CHECK_EQUAL( trials, 7u );\n\n  // On the third bin\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  sample = distribution->sampleSecondaryConditionalAndRecordTrials( 1.0, trials );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0 );\n  FRENSIE_CHECK_EQUAL( trials, 8u );\n\n  sample = distribution->sampleSecondaryConditionalAndRecordTrials( 1.0, trials );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0 );\n  FRENSIE_CHECK_EQUAL( trials, 9u );\n\n  sample = distribution->sampleSecondaryConditionalAndRecordTrials( 1.0, trials );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0, 1e-9 );\n  FRENSIE_CHECK_EQUAL( trials, 10u );\n\n  // In the third bin\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  sample = distribution->sampleSecondaryConditionalAndRecordTrials( 1.5, trials );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0 );\n  FRENSIE_CHECK_EQUAL( trials, 11u );\n\n  sample = distribution->sampleSecondaryConditionalAndRecordTrials( 1.5, trials );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0 );\n  FRENSIE_CHECK_EQUAL( trials, 12u );\n\n  sample = distribution->sampleSecondaryConditionalAndRecordTrials( 1.5, trials );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0, 1e-9 );\n  FRENSIE_CHECK_EQUAL( trials, 13u );\n\n  // On the upper bin boundary - this should be treated as part of the third\n  // bin (special case)\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  sample = distribution->sampleSecondaryConditionalAndRecordTrials( 2.0, trials );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0 );\n  FRENSIE_CHECK_EQUAL( trials, 14u );\n\n  sample = distribution->sampleSecondaryConditionalAndRecordTrials( 2.0, trials );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0 );\n  FRENSIE_CHECK_EQUAL( trials, 15u );\n\n  sample = distribution->sampleSecondaryConditionalAndRecordTrials( 2.0, trials );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0, 1e-9 );\n  FRENSIE_CHECK_EQUAL( trials, 16u );\n\n  // After the third bin - no extension\n  Utility::RandomNumberGenerator::unsetFakeStream();\n\n  FRENSIE_CHECK_THROW( distribution->sampleSecondaryConditionalAndRecordTrials( 3.0, trials ),\n              std::logic_error );\n\n  // After the third bin - with extension\n  tab_distribution->extendBeyondPrimaryIndepLimits();\n\n  sample = distribution->sampleSecondaryConditionalAndRecordTrials( 3.0, trials );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0 );\n  FRENSIE_CHECK_EQUAL( trials, 17u );\n\n  tab_distribution->limitToPrimaryIndepLimits();\n}\n\n//---------------------------------------------------------------------------//\n// Check that a unit-aware secondary conditional PDF can be sampled\nFRENSIE_UNIT_TEST( UnitAwareHistogramFullyTabularBasicBivariateDistribution,\n                   sampleSecondaryConditionalAndRecordTrials )\n{\n  Utility::DistributionTraits::Counter trials = 0u;\n\n  // Before the first bin - no extension\n  FRENSIE_CHECK_THROW( unit_aware_distribution->sampleSecondaryConditionalAndRecordTrials( -1.0*MeV, trials ),\n              std::logic_error );\n  FRENSIE_CHECK_EQUAL( trials, 0u );\n\n  // Before the first bin - with extension\n  unit_aware_tab_distribution->extendBeyondPrimaryIndepLimits();\n\n  quantity<cgs::length> sample =\n    unit_aware_distribution->sampleSecondaryConditionalAndRecordTrials( -1.0*MeV, trials );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( trials, 1u );\n\n  unit_aware_tab_distribution->limitToPrimaryIndepLimits();\n\n  // On the second bin (first bin boundary = second bin boundary)\n  std::vector<double> fake_stream( 3 );\n  fake_stream[0] = 0.0;\n  fake_stream[1] = 0.5;\n  fake_stream[2] = 1.0 - 1e-15;\n\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  sample = unit_aware_distribution->sampleSecondaryConditionalAndRecordTrials( 0.0*MeV, trials );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( trials, 2u );\n\n  sample = unit_aware_distribution->sampleSecondaryConditionalAndRecordTrials( 0.0*MeV, trials );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( trials, 3u );\n\n  sample = unit_aware_distribution->sampleSecondaryConditionalAndRecordTrials( 0.0*MeV, trials );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0*cgs::centimeter, 1e-9 );\n  FRENSIE_CHECK_EQUAL( trials, 4u );\n\n  // In the second bin\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  sample = unit_aware_distribution->sampleSecondaryConditionalAndRecordTrials( 0.5*MeV, trials );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( trials, 5u );\n\n  sample = unit_aware_distribution->sampleSecondaryConditionalAndRecordTrials( 0.5*MeV, trials );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( trials, 6u );\n\n  sample = unit_aware_distribution->sampleSecondaryConditionalAndRecordTrials( 0.5*MeV, trials );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0*cgs::centimeter, 1e-9 );\n  FRENSIE_CHECK_EQUAL( trials, 7u );\n\n  // On the third bin\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  sample = unit_aware_distribution->sampleSecondaryConditionalAndRecordTrials( 1.0*MeV, trials );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( trials, 8u );\n\n  sample = unit_aware_distribution->sampleSecondaryConditionalAndRecordTrials( 1.0*MeV, trials );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( trials, 9u );\n\n  sample = unit_aware_distribution->sampleSecondaryConditionalAndRecordTrials( 1.0*MeV, trials );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0*cgs::centimeter, 1e-9 );\n  FRENSIE_CHECK_EQUAL( trials, 10u );\n\n  // In the third bin\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  sample = unit_aware_distribution->sampleSecondaryConditionalAndRecordTrials( 1.5*MeV, trials );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( trials, 11u );\n\n  sample = unit_aware_distribution->sampleSecondaryConditionalAndRecordTrials( 1.5*MeV, trials );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( trials, 12u );\n\n  sample = unit_aware_distribution->sampleSecondaryConditionalAndRecordTrials( 1.5*MeV, trials );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0*cgs::centimeter, 1e-9 );\n  FRENSIE_CHECK_EQUAL( trials, 13u );\n\n  // On the upper bin boundary - this should be treated as part of the third\n  // bin (special case)\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  sample = unit_aware_distribution->sampleSecondaryConditionalAndRecordTrials( 2.0*MeV, trials );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( trials, 14u );\n\n  sample = unit_aware_distribution->sampleSecondaryConditionalAndRecordTrials( 2.0*MeV, trials );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( trials, 15u );\n\n  sample = unit_aware_distribution->sampleSecondaryConditionalAndRecordTrials( 2.0*MeV, trials );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0*cgs::centimeter, 1e-9 );\n  FRENSIE_CHECK_EQUAL( trials, 16u );\n\n  // After the third bin - no extension\n  Utility::RandomNumberGenerator::unsetFakeStream();\n\n  FRENSIE_CHECK_THROW( unit_aware_distribution->sampleSecondaryConditionalAndRecordTrials( 3.0*MeV, trials ),\n              std::logic_error );\n\n  // After the third bin - with extension\n  unit_aware_tab_distribution->extendBeyondPrimaryIndepLimits();\n\n  sample = unit_aware_distribution->sampleSecondaryConditionalAndRecordTrials( 3.0*MeV, trials );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( trials, 17u );\n\n  unit_aware_tab_distribution->limitToPrimaryIndepLimits();\n}\n\n//---------------------------------------------------------------------------//\n// Check that a secondary conditional PDF can be sampled\nFRENSIE_UNIT_TEST( HistogramFullyTabularBasicBivariateDistribution,\n                   sampleSecondaryConditionalAndRecordBinIndices )\n{\n  size_t primary_bin_index = 0, secondary_bin_index = 0;\n\n  // Before the first bin - no extension\n  FRENSIE_CHECK_THROW( tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( -1.0, primary_bin_index, secondary_bin_index ),\n                       std::logic_error );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 0u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  // Before the first bin - with extension\n  tab_distribution->extendBeyondPrimaryIndepLimits();\n\n  double sample = tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( -1.0, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0 );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 0u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  tab_distribution->limitToPrimaryIndepLimits();\n\n  // On the second bin (first bin boundary = second bin boundary)\n  std::vector<double> fake_stream( 3 );\n  fake_stream[0] = 0.0;\n  fake_stream[1] = 0.5;\n  fake_stream[2] = 1.0 - 1e-15;\n\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  sample = tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 0.0, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0 );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 1u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  sample = tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 0.0, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0 );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 1u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  sample = tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 0.0, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0, 1e-9 );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 1u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  // In the second bin\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  sample = tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 0.5, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0 );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 1u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  sample = tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 0.5, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0 );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 1u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  sample = tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 0.5, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0, 1e-9 );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 1u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  // On the third bin\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  sample = tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 1.0, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0 );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 2u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  sample = tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 1.0, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0 );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 2u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  sample = tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 1.0, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0, 1e-9 );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 2u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  // In the third bin\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  sample = tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 1.5, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0 );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 2u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  sample = tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 1.5, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0 );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 2u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  sample = tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 1.5, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0, 1e-9 );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 2u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  // On the upper bin boundary - this should be treated as part of the third\n  // bin (special case)\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  sample = tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 2.0, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0 );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 2u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  sample = tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 2.0, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0 );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 2u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  sample = tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 2.0, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0, 1e-9 );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 2u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  // After the third bin - no extension\n  Utility::RandomNumberGenerator::unsetFakeStream();\n\n  FRENSIE_CHECK_THROW( tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 3.0, primary_bin_index, secondary_bin_index ),\n              std::logic_error );\n\n  // After the third bin - with extension\n  tab_distribution->extendBeyondPrimaryIndepLimits();\n\n  sample = tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 3.0, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0 );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 3u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  tab_distribution->limitToPrimaryIndepLimits();\n}\n\n//---------------------------------------------------------------------------//\n// Check that a unit-aware secondary conditional PDF can be sampled\nFRENSIE_UNIT_TEST( UnitAwareHistogramFullyTabularBasicBivariateDistribution,\n                   sampleSecondaryConditionalAndRecordBinIndices )\n{\n  size_t primary_bin_index = 0u, secondary_bin_index = 0u;\n\n  // Before the first bin - no extension\n  FRENSIE_CHECK_THROW( unit_aware_tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( -1.0*MeV, primary_bin_index, secondary_bin_index ),\n              std::logic_error );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 0u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  // Before the first bin - with extension\n  unit_aware_tab_distribution->extendBeyondPrimaryIndepLimits();\n\n  quantity<cgs::length> sample = unit_aware_tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( -1.0*MeV, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 0u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  unit_aware_tab_distribution->limitToPrimaryIndepLimits();\n\n  // On the second bin (first bin boundary = second bin boundary)\n  std::vector<double> fake_stream( 3 );\n  fake_stream[0] = 0.0;\n  fake_stream[1] = 0.5;\n  fake_stream[2] = 1.0 - 1e-15;\n\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 0.0*MeV, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 1u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 0.0*MeV, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 1u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 0.0*MeV, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0*cgs::centimeter, 1e-9 );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 1u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  // In the second bin\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 0.5*MeV, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 1u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 0.5*MeV, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 1u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 0.5*MeV, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0*cgs::centimeter, 1e-9 );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 1u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  // On the third bin\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 1.0*MeV, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 2u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 1.0*MeV, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 2u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 1.0*MeV, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0*cgs::centimeter, 1e-9 );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 2u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  // In the third bin\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 1.5*MeV, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 2u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 1.5*MeV, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 2u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 1.5*MeV, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0*cgs::centimeter, 1e-9 );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 2u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  // On the upper bin boundary - this should be treated as part of the third\n  // bin (special case)\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 2.0*MeV, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 2u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 2.0*MeV, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 2u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 2.0*MeV, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0*cgs::centimeter, 1e-9 );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 2u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  // After the third bin - no extension\n  Utility::RandomNumberGenerator::unsetFakeStream();\n\n  FRENSIE_CHECK_THROW( unit_aware_tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 3.0*MeV, primary_bin_index, secondary_bin_index ),\n              std::logic_error );\n\n  // After the third bin - with extension\n  unit_aware_tab_distribution->extendBeyondPrimaryIndepLimits();\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 3.0*MeV, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 3u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  unit_aware_tab_distribution->limitToPrimaryIndepLimits();\n}\n\n//---------------------------------------------------------------------------//\n// Check that a secondary conditional PDF can be sampled\nFRENSIE_UNIT_TEST( HistogramFullyTabularBasicBivariateDistribution,\n                   sampleSecondaryConditionalAndRecordBinIndices_with_raw )\n{\n  size_t primary_bin_index = 0u, secondary_bin_index = 0u;\n  double raw_sample;\n\n  // Before the first bin - no extension\n  FRENSIE_CHECK_THROW( tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( -1.0, raw_sample, primary_bin_index, secondary_bin_index ),\n              std::logic_error );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 0u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  // Before the first bin - with extension\n  tab_distribution->extendBeyondPrimaryIndepLimits();\n\n  double sample = tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( -1.0, raw_sample, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0 );\n  FRENSIE_CHECK_EQUAL( raw_sample, 0.0 );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 0u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  tab_distribution->limitToPrimaryIndepLimits();\n\n  // On the second bin (first bin boundary = second bin boundary)\n  std::vector<double> fake_stream( 3 );\n  fake_stream[0] = 0.0;\n  fake_stream[1] = 0.5;\n  fake_stream[2] = 1.0 - 1e-15;\n\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  sample = tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 0.0, raw_sample, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0 );\n  FRENSIE_CHECK_EQUAL( raw_sample, 0.0 );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 1u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  sample = tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 0.0, raw_sample, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0 );\n  FRENSIE_CHECK_EQUAL( raw_sample, 5.0 );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 1u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  sample = tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 0.0, raw_sample, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0, 1e-9 );\n  FRENSIE_CHECK_FLOATING_EQUALITY( raw_sample, 10.0, 1e-9 );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 1u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  // In the second bin\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  sample = tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 0.5, raw_sample, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0 );\n  FRENSIE_CHECK_EQUAL( raw_sample, 0.0 );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 1u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  sample = tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 0.5, raw_sample, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0 );\n  FRENSIE_CHECK_EQUAL( raw_sample, 5.0 );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 1u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  sample = tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 0.5, raw_sample, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0, 1e-9 );\n  FRENSIE_CHECK_FLOATING_EQUALITY( raw_sample, 10.0, 1e-9 );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 1u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  // On the third bin\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  sample = tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 1.0, raw_sample, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0 );\n  FRENSIE_CHECK_EQUAL( raw_sample, 0.0 );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 2u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  sample = tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 1.0, raw_sample, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0 );\n  FRENSIE_CHECK_EQUAL( raw_sample, 5.0 );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 2u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  sample = tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 1.0, raw_sample, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0, 1e-9 );\n  FRENSIE_CHECK_FLOATING_EQUALITY( raw_sample, 10.0, 1e-9 );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 2u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  // In the third bin\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  sample = tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 1.5, raw_sample, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0 );\n  FRENSIE_CHECK_EQUAL( raw_sample, 0.0 );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 2u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  sample = tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 1.5, raw_sample, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0 );\n  FRENSIE_CHECK_EQUAL( raw_sample, 5.0 );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 2u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  sample = tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 1.5, raw_sample, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0, 1e-9 );\n  FRENSIE_CHECK_FLOATING_EQUALITY( raw_sample, 10.0, 1e-9 );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 2u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  // On the upper bin boundary - this should be treated as part of the third\n  // bin (special case)\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  sample = tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 2.0, raw_sample, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0 );\n  FRENSIE_CHECK_EQUAL( raw_sample, 0.0 );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 2u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  sample = tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 2.0, raw_sample, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0 );\n  FRENSIE_CHECK_EQUAL( raw_sample, 5.0 );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 2u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  sample = tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 2.0, raw_sample, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0, 1e-9 );\n  FRENSIE_CHECK_FLOATING_EQUALITY( raw_sample, 10.0, 1e-9 );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 2u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  // After the third bin - no extension\n  Utility::RandomNumberGenerator::unsetFakeStream();\n\n  FRENSIE_CHECK_THROW( tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 3.0, raw_sample, primary_bin_index, secondary_bin_index ),\n              std::logic_error );\n\n  // After the third bin - with extension\n  tab_distribution->extendBeyondPrimaryIndepLimits();\n\n  sample = tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 3.0, raw_sample, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0 );\n  FRENSIE_CHECK_EQUAL( raw_sample, 0.0 );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 3u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  tab_distribution->limitToPrimaryIndepLimits();\n}\n\n//---------------------------------------------------------------------------//\n// Check that a unit-aware secondary conditional PDF can be sampled\nFRENSIE_UNIT_TEST( UnitAwareHistogramFullyTabularBasicBivariateDistribution,\n                   sampleSecondaryConditionalAndRecordBinIndices_with_raw )\n{\n  size_t primary_bin_index = 0u, secondary_bin_index = 0u;\n  quantity<cgs::length> raw_sample;\n\n  // Before the first bin - no extension\n  FRENSIE_CHECK_THROW( unit_aware_tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( -1.0*MeV, raw_sample, primary_bin_index, secondary_bin_index ),\n              std::logic_error );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 0u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  // Before the first bin - with extension\n  unit_aware_tab_distribution->extendBeyondPrimaryIndepLimits();\n\n  quantity<cgs::length> sample = unit_aware_tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( -1.0*MeV, raw_sample, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 0u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  unit_aware_tab_distribution->limitToPrimaryIndepLimits();\n\n  // On the second bin (first bin boundary = second bin boundary)\n  std::vector<double> fake_stream( 3 );\n  fake_stream[0] = 0.0;\n  fake_stream[1] = 0.5;\n  fake_stream[2] = 1.0 - 1e-15;\n\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 0.0*MeV, raw_sample, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( raw_sample, 0.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 1u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 0.0*MeV, raw_sample, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( raw_sample, 5.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 1u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 0.0*MeV, raw_sample, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0*cgs::centimeter, 1e-9 );\n  FRENSIE_CHECK_FLOATING_EQUALITY( raw_sample, 10.0*cgs::centimeter, 1e-9 );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 1u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  // In the second bin\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 0.5*MeV, raw_sample, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( raw_sample, 0.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 1u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 0.5*MeV, raw_sample, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( raw_sample, 5.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 1u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 0.5*MeV, raw_sample, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0*cgs::centimeter, 1e-9 );\n  FRENSIE_CHECK_FLOATING_EQUALITY( raw_sample, 10.0*cgs::centimeter, 1e-9 );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 1u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  // On the third bin\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 1.0*MeV, raw_sample, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( raw_sample, 0.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 2u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 1.0*MeV, raw_sample, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( raw_sample, 5.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 2u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 1.0*MeV, raw_sample, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0*cgs::centimeter, 1e-9 );\n  FRENSIE_CHECK_FLOATING_EQUALITY( raw_sample, 10.0*cgs::centimeter, 1e-9 );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 2u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  // In the third bin\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 1.5*MeV, raw_sample, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( raw_sample, 0.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 2u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 1.5*MeV, raw_sample, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( raw_sample, 5.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 2u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 1.5*MeV, raw_sample, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0*cgs::centimeter, 1e-9 );\n  FRENSIE_CHECK_FLOATING_EQUALITY( raw_sample, 10.0*cgs::centimeter, 1e-9 );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 2u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  // On the upper bin boundary - this should be treated as part of the third\n  // bin (special case)\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 2.0*MeV, raw_sample, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( raw_sample, 0.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 2u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 2.0*MeV, raw_sample, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( raw_sample, 5.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 2u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 2.0*MeV, raw_sample, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0*cgs::centimeter, 1e-9 );\n  FRENSIE_CHECK_FLOATING_EQUALITY( raw_sample, 10.0*cgs::centimeter, 1e-9 );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 2u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  // After the third bin - no extension\n  Utility::RandomNumberGenerator::unsetFakeStream();\n\n  FRENSIE_CHECK_THROW( unit_aware_tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 3.0*MeV, raw_sample, primary_bin_index, secondary_bin_index ),\n              std::logic_error );\n\n  // After the third bin - with extension\n  unit_aware_tab_distribution->extendBeyondPrimaryIndepLimits();\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalAndRecordBinIndices( 3.0*MeV, raw_sample, primary_bin_index, secondary_bin_index );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( raw_sample, 0.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( primary_bin_index, 3u );\n  FRENSIE_CHECK_EQUAL( secondary_bin_index, 0u );\n\n  unit_aware_tab_distribution->limitToPrimaryIndepLimits();\n}\n\n//---------------------------------------------------------------------------//\n// Check that the secondary conditional PDF can be sampled\nFRENSIE_UNIT_TEST( HistogramFullyTabularBasicBivariateDistribution,\n                   sampleSecondaryConditionalWithRandomNumber )\n{\n  // Before the first bin - no extension\n  FRENSIE_CHECK_THROW( tab_distribution->sampleSecondaryConditionalWithRandomNumber( -1.0, 0.0 ),\n              std::logic_error );\n\n  // Before the first bin - with extension\n  tab_distribution->extendBeyondPrimaryIndepLimits();\n\n  double sample = tab_distribution->sampleSecondaryConditionalWithRandomNumber( -1.0, 0.0 );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0 );\n\n  tab_distribution->limitToPrimaryIndepLimits();\n\n  // On the second bin (first bin boundary = second bin boundary)\n  sample = tab_distribution->sampleSecondaryConditionalWithRandomNumber( 0.0, 0.0 );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0 );\n\n  sample = tab_distribution->sampleSecondaryConditionalWithRandomNumber( 0.0, 0.5 );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0 );\n\n  sample = tab_distribution->sampleSecondaryConditionalWithRandomNumber( 0.0, 1.0-1e-15 );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0, 1e-9 );\n\n  // In the second bin\n  sample = tab_distribution->sampleSecondaryConditionalWithRandomNumber( 0.5, 0.0 );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0 );\n\n  sample = tab_distribution->sampleSecondaryConditionalWithRandomNumber( 0.5, 0.5 );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0 );\n\n  sample = tab_distribution->sampleSecondaryConditionalWithRandomNumber( 0.5, 1.0-1e-15 );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0, 1e-9 );\n\n  // On the third bin\n  sample = tab_distribution->sampleSecondaryConditionalWithRandomNumber( 1.0, 0.0 );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0 );\n\n  sample = tab_distribution->sampleSecondaryConditionalWithRandomNumber( 1.0, 0.5 );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0 );\n\n  sample = tab_distribution->sampleSecondaryConditionalWithRandomNumber( 1.0, 1.0-1e-15 );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0, 1e-9 );\n\n  // In the third bin\n  sample = tab_distribution->sampleSecondaryConditionalWithRandomNumber( 1.5, 0.0 );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0 );\n\n  sample = tab_distribution->sampleSecondaryConditionalWithRandomNumber( 1.5, 0.5 );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0 );\n\n  sample = tab_distribution->sampleSecondaryConditionalWithRandomNumber( 1.5, 1.0-1e-15 );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0, 1e-9 );\n\n  // On the upper bin boundary - this should be treated as part of the third\n  // bin (special case)\n  sample = tab_distribution->sampleSecondaryConditionalWithRandomNumber( 2.0, 0.0 );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0 );\n\n  sample = tab_distribution->sampleSecondaryConditionalWithRandomNumber( 2.0, 0.5 );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0 );\n\n  sample = tab_distribution->sampleSecondaryConditionalWithRandomNumber( 2.0, 1.0-1e-15 );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0, 1e-9 );\n\n  // After the third bin - no extension\n  FRENSIE_CHECK_THROW( tab_distribution->sampleSecondaryConditionalWithRandomNumber( 3.0, 0.5 ),\n              std::logic_error );\n\n  // After the third bin - with extension\n  tab_distribution->extendBeyondPrimaryIndepLimits();\n\n  sample = tab_distribution->sampleSecondaryConditionalWithRandomNumber( 3.0, 0.5 );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0 );\n\n  tab_distribution->limitToPrimaryIndepLimits();\n}\n\n//---------------------------------------------------------------------------//\n// Check that the unit-aware secondary conditional PDF can be sampled\nFRENSIE_UNIT_TEST( UnitAwareHistogramFullyTabularBasicBivariateDistribution,\n                   sampleSecondaryConditionalWithRandomNumber )\n{\n  // Before the first bin - no extension\n  FRENSIE_CHECK_THROW( unit_aware_tab_distribution->sampleSecondaryConditionalWithRandomNumber( -1.0*MeV, 0.0 ),\n              std::logic_error );\n\n  // Before the first bin - with extension\n  unit_aware_tab_distribution->extendBeyondPrimaryIndepLimits();\n\n  quantity<cgs::length> sample = unit_aware_tab_distribution->sampleSecondaryConditionalWithRandomNumber( -1.0*MeV, 0.0 );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter );\n\n  unit_aware_tab_distribution->limitToPrimaryIndepLimits();\n\n  // On the second bin (first bin boundary = second bin boundary)\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalWithRandomNumber( 0.0*MeV, 0.0 );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalWithRandomNumber( 0.0*MeV, 0.5 );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0*cgs::centimeter );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalWithRandomNumber( 0.0*MeV, 1.0-1e-15 );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0*cgs::centimeter, 1e-9 );\n\n  // In the second bin\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalWithRandomNumber( 0.5*MeV, 0.0 );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalWithRandomNumber( 0.5*MeV, 0.5 );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0*cgs::centimeter );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalWithRandomNumber( 0.5*MeV, 1.0-1e-15 );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0*cgs::centimeter, 1e-9 );\n\n  // On the third bin\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalWithRandomNumber( 1.0*MeV, 0.0 );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalWithRandomNumber( 1.0*MeV, 0.5 );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0*cgs::centimeter );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalWithRandomNumber( 1.0*MeV, 1.0-1e-15 );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0*cgs::centimeter, 1e-9 );\n\n  // In the third bin\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalWithRandomNumber( 1.5*MeV, 0.0 );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalWithRandomNumber( 1.5*MeV, 0.5 );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0*cgs::centimeter );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalWithRandomNumber( 1.5*MeV, 1.0-1e-15 );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0*cgs::centimeter, 1e-9 );\n\n  // On the upper bin boundary - this should be treated as part of the third\n  // bin (special case)\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalWithRandomNumber( 2.0*MeV, 0.0 );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalWithRandomNumber( 2.0*MeV, 0.5 );\n\n  FRENSIE_CHECK_EQUAL( sample, 5.0*cgs::centimeter );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalWithRandomNumber( 2.0*MeV, 1.0-1e-15 );\n\n  // After the third bin - no extension\n  FRENSIE_CHECK_THROW( unit_aware_tab_distribution->sampleSecondaryConditionalWithRandomNumber( 3.0*MeV, 0.5 ),\n              std::logic_error );\n\n  // After the third bin - with extension\n  unit_aware_tab_distribution->extendBeyondPrimaryIndepLimits();\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalWithRandomNumber( 3.0*MeV, 0.5 );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter );\n\n  unit_aware_tab_distribution->limitToPrimaryIndepLimits();\n}\n\n//---------------------------------------------------------------------------//\n// Check that a secondary conditional PDF can be sampled\nFRENSIE_UNIT_TEST( HistogramFullyTabularBasicBivariateDistribution,\n                   sampleSecondaryConditionalInSubrange )\n{\n  // Before the first bin - no extension\n  FRENSIE_CHECK_THROW( tab_distribution->sampleSecondaryConditionalInSubrange( -1.0, 1.0 ),\n              std::logic_error );\n\n  // Before the first bin - with extension\n  tab_distribution->extendBeyondPrimaryIndepLimits();\n\n  double sample = tab_distribution->sampleSecondaryConditionalInSubrange( -1.0, 1.0 );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0 );\n\n  tab_distribution->limitToPrimaryIndepLimits();\n\n  // On the second bin (first bin boundary = second bin boundary)\n  std::vector<double> fake_stream( 3 );\n  fake_stream[0] = 0.0;\n  fake_stream[1] = 0.5;\n  fake_stream[2] = 1.0 - 1e-15;\n\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  sample = tab_distribution->sampleSecondaryConditionalInSubrange( 0.0, 5.0 );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0 );\n\n  sample = tab_distribution->sampleSecondaryConditionalInSubrange( 0.0, 5.0 );\n\n  FRENSIE_CHECK_EQUAL( sample, 2.5 );\n\n  sample = tab_distribution->sampleSecondaryConditionalInSubrange( 0.0, 5.0 );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 5.0, 1e-9 );\n\n  // In the second bin\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  sample = tab_distribution->sampleSecondaryConditionalInSubrange( 0.5, 5.0 );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0 );\n\n  sample = tab_distribution->sampleSecondaryConditionalInSubrange( 0.5, 5.0 );\n\n  FRENSIE_CHECK_EQUAL( sample, 2.5 );\n\n  sample = tab_distribution->sampleSecondaryConditionalInSubrange( 0.5, 5.0 );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 5.0, 1e-9 );\n\n  // On the third bin\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  sample = tab_distribution->sampleSecondaryConditionalInSubrange( 1.0, 5.0 );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0 );\n\n  sample = tab_distribution->sampleSecondaryConditionalInSubrange( 1.0, 5.0 );\n\n  FRENSIE_CHECK_EQUAL( sample, 2.5 );\n\n  sample = tab_distribution->sampleSecondaryConditionalInSubrange( 1.0, 5.0 );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 5.0, 1e-9 );\n\n  // In the third bin\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  sample = tab_distribution->sampleSecondaryConditionalInSubrange( 1.5, 5.0 );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0 );\n\n  sample = tab_distribution->sampleSecondaryConditionalInSubrange( 1.5, 5.0 );\n\n  FRENSIE_CHECK_EQUAL( sample, 2.5 );\n\n  sample = tab_distribution->sampleSecondaryConditionalInSubrange( 1.5, 5.0 );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 5.0, 1e-9 );\n\n  // On the upper bin boundary - this should be treated as part of the third\n  // bin (special case)\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  sample = tab_distribution->sampleSecondaryConditionalInSubrange( 2.0, 5.0 );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0 );\n\n  sample = tab_distribution->sampleSecondaryConditionalInSubrange( 2.0, 5.0 );\n\n  FRENSIE_CHECK_EQUAL( sample, 2.5 );\n\n  sample = tab_distribution->sampleSecondaryConditionalInSubrange( 2.0, 5.0 );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 5.0, 1e-9 );\n\n  // After the third bin - no extension\n  Utility::RandomNumberGenerator::unsetFakeStream();\n\n  FRENSIE_CHECK_THROW( tab_distribution->sampleSecondaryConditionalInSubrange( 3.0, 1.0 ),\n              std::logic_error );\n\n  // After the third bin - with extension\n  tab_distribution->extendBeyondPrimaryIndepLimits();\n\n  sample = tab_distribution->sampleSecondaryConditionalInSubrange( 3.0, 1.0 );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0 );\n\n  tab_distribution->limitToPrimaryIndepLimits();\n}\n\n//---------------------------------------------------------------------------//\n// Check that a unit-aware secondary conditional PDF can be sampled\nFRENSIE_UNIT_TEST( UnitAwareHistogramFullyTabularBasicBivariateDistribution,\n                   sampleSecondaryConditionalInSubrange )\n{\n  // Before the first bin - no extension\n  FRENSIE_CHECK_THROW( unit_aware_tab_distribution->sampleSecondaryConditionalInSubrange( -1.0*MeV, 1.0*cgs::centimeter ),\n              std::logic_error );\n\n  // Before the second bin - with extension\n  unit_aware_tab_distribution->extendBeyondPrimaryIndepLimits();\n\n  quantity<cgs::length> sample = unit_aware_tab_distribution->sampleSecondaryConditionalInSubrange( -1.0*MeV, 1.0*cgs::centimeter );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter );\n\n  unit_aware_tab_distribution->limitToPrimaryIndepLimits();\n\n  // On the second bin (first bin boundary = second bin boundary)\n  std::vector<double> fake_stream( 3 );\n  fake_stream[0] = 0.0;\n  fake_stream[1] = 0.5;\n  fake_stream[2] = 1.0 - 1e-15;\n\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalInSubrange( 0.0*MeV, 5.0*cgs::centimeter );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalInSubrange( 0.0*MeV, 5.0*cgs::centimeter );\n\n  FRENSIE_CHECK_EQUAL( sample, 2.5*cgs::centimeter );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalInSubrange( 0.0*MeV, 5.0*cgs::centimeter );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 5.0*cgs::centimeter, 1e-9 );\n\n  // In the second bin\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalInSubrange( 0.5*MeV, 5.0*cgs::centimeter );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalInSubrange( 0.5*MeV, 5.0*cgs::centimeter );\n\n  FRENSIE_CHECK_EQUAL( sample, 2.5*cgs::centimeter );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalInSubrange( 0.5*MeV, 5.0*cgs::centimeter );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 5.0*cgs::centimeter, 1e-9 );\n\n  // On the third bin\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalInSubrange( 1.0*MeV, 5.0*cgs::centimeter );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalInSubrange( 1.0*MeV, 5.0*cgs::centimeter );\n\n  FRENSIE_CHECK_EQUAL( sample, 2.5*cgs::centimeter );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalInSubrange( 1.0*MeV, 5.0*cgs::centimeter );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 5.0*cgs::centimeter, 1e-9 );\n\n  // In the third bin\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalInSubrange( 1.5*MeV, 5.0*cgs::centimeter );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalInSubrange( 1.5*MeV, 5.0*cgs::centimeter );\n\n  FRENSIE_CHECK_EQUAL( sample, 2.5*cgs::centimeter );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalInSubrange( 1.5*MeV, 5.0*cgs::centimeter );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 5.0*cgs::centimeter, 1e-9 );\n\n  // On the upper bin boundary - this should be treated as part of the third\n  // bin (special case)\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalInSubrange( 2.0*MeV, 5.0*cgs::centimeter );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalInSubrange( 2.0*MeV, 5.0*cgs::centimeter );\n\n  FRENSIE_CHECK_EQUAL( sample, 2.5*cgs::centimeter );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalInSubrange( 2.0*MeV, 5.0*cgs::centimeter );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 5.0*cgs::centimeter, 1e-9 );\n\n  // After the third bin - no extension\n  Utility::RandomNumberGenerator::unsetFakeStream();\n\n  FRENSIE_CHECK_THROW( unit_aware_tab_distribution->sampleSecondaryConditionalInSubrange( 3.0*MeV, 1.0*cgs::centimeter ),\n              std::logic_error );\n\n  // After the third bin - with extension\n  unit_aware_tab_distribution->extendBeyondPrimaryIndepLimits();\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalInSubrange( 3.0*MeV, 1.0*cgs::centimeter );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter );\n\n  unit_aware_tab_distribution->limitToPrimaryIndepLimits();\n}\n\n//---------------------------------------------------------------------------//\n// Check that a secondary conditional PDF can be sampled\nFRENSIE_UNIT_TEST( HistogramFullyTabularBasicBivariateDistribution,\n                   sampleSecondaryConditionalWithRandomNumberInSubrange )\n{\n  // Before the first bin - no extension\n  FRENSIE_CHECK_THROW( tab_distribution->sampleSecondaryConditionalWithRandomNumberInSubrange( -1.0, 0.0, 1.0 ),\n              std::logic_error );\n\n  // Before the first bin - with extension\n  tab_distribution->extendBeyondPrimaryIndepLimits();\n\n  double sample = tab_distribution->sampleSecondaryConditionalWithRandomNumberInSubrange( -1.0, 0.0, 1.0 );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0 );\n\n  tab_distribution->limitToPrimaryIndepLimits();\n\n  // On the second bin (first bin boundary = second bin boundary)\n  sample = tab_distribution->sampleSecondaryConditionalWithRandomNumberInSubrange( 0.0, 0.0, 5.0 );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0 );\n\n  sample = tab_distribution->sampleSecondaryConditionalWithRandomNumberInSubrange( 0.0, 0.5, 5.0 );\n\n  FRENSIE_CHECK_EQUAL( sample, 2.5 );\n\n  sample = tab_distribution->sampleSecondaryConditionalWithRandomNumberInSubrange( 0.0, 1.0-1e-15, 5.0 );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 5.0, 1e-9 );\n\n  // In the second bin\n  sample = tab_distribution->sampleSecondaryConditionalWithRandomNumberInSubrange( 0.5, 0.0, 5.0 );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0 );\n\n  sample = tab_distribution->sampleSecondaryConditionalWithRandomNumberInSubrange( 0.5, 0.5, 5.0 );\n\n  FRENSIE_CHECK_EQUAL( sample, 2.5 );\n\n  sample = tab_distribution->sampleSecondaryConditionalWithRandomNumberInSubrange( 0.5, 1.0-1e-15, 5.0 );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 5.0, 1e-9 );\n\n  // On the third bin\n  sample = tab_distribution->sampleSecondaryConditionalWithRandomNumberInSubrange( 1.0, 0.0, 5.0 );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0 );\n\n  sample = tab_distribution->sampleSecondaryConditionalWithRandomNumberInSubrange( 1.0, 0.5, 5.0 );\n\n  FRENSIE_CHECK_EQUAL( sample, 2.5 );\n\n  sample = tab_distribution->sampleSecondaryConditionalWithRandomNumberInSubrange( 1.0, 1.0-1e-15, 5.0 );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 5.0, 1e-9 );\n\n  // In the third bin\n  sample = tab_distribution->sampleSecondaryConditionalWithRandomNumberInSubrange( 1.5, 0.0, 5.0 );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0 );\n\n  sample = tab_distribution->sampleSecondaryConditionalWithRandomNumberInSubrange( 1.5, 0.5, 5.0 );\n\n  FRENSIE_CHECK_EQUAL( sample, 2.5 );\n\n  sample = tab_distribution->sampleSecondaryConditionalWithRandomNumberInSubrange( 1.5, 1.0-1e-15, 5.0 );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 5.0, 1e-9 );\n\n  // On the upper bin boundary - this should be treated as part of the third\n  // bin (special case)\n  sample = tab_distribution->sampleSecondaryConditionalWithRandomNumberInSubrange( 2.0, 0.0, 5.0 );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0 );\n\n  sample = tab_distribution->sampleSecondaryConditionalWithRandomNumberInSubrange( 2.0, 0.5, 5.0 );\n\n  FRENSIE_CHECK_EQUAL( sample, 2.5 );\n\n  sample = tab_distribution->sampleSecondaryConditionalWithRandomNumberInSubrange( 2.0, 1.0-1e-15, 5.0 );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 5.0, 1e-9 );\n\n  // After the third bin - no extension\n  FRENSIE_CHECK_THROW( tab_distribution->sampleSecondaryConditionalWithRandomNumberInSubrange( 3.0, 0.5, 1.0 ),\n              std::logic_error );\n\n  // After the third bin - with extension\n  tab_distribution->extendBeyondPrimaryIndepLimits();\n\n  sample = tab_distribution->sampleSecondaryConditionalWithRandomNumberInSubrange( 3.0, 0.5, 1.0 );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0 );\n\n  tab_distribution->limitToPrimaryIndepLimits();\n}\n\n//---------------------------------------------------------------------------//\n// Check that a unit-aware secondary conditional PDF can be sampled\nFRENSIE_UNIT_TEST( UnitAwareHistogramFullyTabularBasicBivariateDistribution,\n                   sampleSecondaryConditionalWithRandomNumberInSubrange )\n{\n  // Before the first bin - no extension\n  FRENSIE_CHECK_THROW( unit_aware_tab_distribution->sampleSecondaryConditionalWithRandomNumberInSubrange( -1.0*MeV, 0.0, 1.0*cgs::centimeter ),\n              std::logic_error );\n\n  // Before the first bin - with extension\n  unit_aware_tab_distribution->extendBeyondPrimaryIndepLimits();\n\n  quantity<cgs::length> sample = unit_aware_tab_distribution->sampleSecondaryConditionalWithRandomNumberInSubrange( -1.0*MeV, 0.0, 1.0*cgs::centimeter );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter );\n\n  unit_aware_tab_distribution->limitToPrimaryIndepLimits();\n\n  // On the second bin (first bin boundary = second bin boundary)\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalWithRandomNumberInSubrange( 0.0*MeV, 0.0, 5.0*cgs::centimeter );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalWithRandomNumberInSubrange( 0.0*MeV, 0.5, 5.0*cgs::centimeter );\n\n  FRENSIE_CHECK_EQUAL( sample, 2.5*cgs::centimeter );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalWithRandomNumberInSubrange( 0.0*MeV, 1.0-1e-15, 5.0*cgs::centimeter );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 5.0*cgs::centimeter, 1e-9 );\n\n  // In the second bin\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalWithRandomNumberInSubrange( 0.5*MeV, 0.0, 5.0*cgs::centimeter );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalWithRandomNumberInSubrange( 0.5*MeV, 0.5, 5.0*cgs::centimeter );\n\n  FRENSIE_CHECK_EQUAL( sample, 2.5*cgs::centimeter );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalWithRandomNumberInSubrange( 0.5*MeV, 1.0-1e-15, 5.0*cgs::centimeter );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 5.0*cgs::centimeter, 1e-9 );\n\n  // On the third bin\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalWithRandomNumberInSubrange( 1.0*MeV, 0.0, 5.0*cgs::centimeter );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalWithRandomNumberInSubrange( 1.0*MeV, 0.5, 5.0*cgs::centimeter );\n\n  FRENSIE_CHECK_EQUAL( sample, 2.5*cgs::centimeter );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalWithRandomNumberInSubrange( 1.0*MeV, 1.0-1e-15, 5.0*cgs::centimeter );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 5.0*cgs::centimeter, 1e-9 );\n\n  // In the third bin\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalWithRandomNumberInSubrange( 1.5*MeV, 0.0, 5.0*cgs::centimeter );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalWithRandomNumberInSubrange( 1.5*MeV, 0.5, 5.0*cgs::centimeter );\n\n  FRENSIE_CHECK_EQUAL( sample, 2.5*cgs::centimeter );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalWithRandomNumberInSubrange( 1.5*MeV, 1.0-1e-15, 5.0*cgs::centimeter );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 5.0*cgs::centimeter, 1e-9 );\n\n  // On the upper bin boundary - this should be treated as part of the third\n  // bin (special case)\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalWithRandomNumberInSubrange( 2.0*MeV, 0.0, 5.0*cgs::centimeter );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalWithRandomNumberInSubrange( 2.0*MeV, 0.5, 5.0*cgs::centimeter );\n\n  FRENSIE_CHECK_EQUAL( sample, 2.5*cgs::centimeter );\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalWithRandomNumberInSubrange( 2.0*MeV, 1.0-1e-15, 5.0*cgs::centimeter );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 5.0*cgs::centimeter, 1e-9 );\n\n  // After the third bin - no extension\n  FRENSIE_CHECK_THROW( unit_aware_tab_distribution->sampleSecondaryConditionalWithRandomNumberInSubrange( 3.0*MeV, 0.5, 1.0*cgs::centimeter ),\n              std::logic_error );\n\n  // After the third bin - with extension\n  unit_aware_tab_distribution->extendBeyondPrimaryIndepLimits();\n\n  sample = unit_aware_tab_distribution->sampleSecondaryConditionalWithRandomNumberInSubrange( 3.0*MeV, 0.5, 1.0*cgs::centimeter );\n\n  FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter );\n\n  unit_aware_tab_distribution->limitToPrimaryIndepLimits();\n}\n\n//---------------------------------------------------------------------------//\n// Check that the distribution can be placed in a stream\nFRENSIE_UNIT_TEST( HistogramFullyTabularBasicBivariateDistribution,\n                   ostream_operator )\n{\n  std::ostringstream oss;\n\n  oss << *distribution;\n\n  Utility::VariantMap dist_data =\n    Utility::fromString<Utility::VariantMap>( oss.str() );\n\n  FRENSIE_CHECK_EQUAL( dist_data[\"type\"].toString(),\n                       \"HistogramFullyTabularBasicBivariateDistribution\",\n                       SHOW_LHS );\n  FRENSIE_CHECK_EQUAL( dist_data[\"primary independent unit\"].toString(),\n                       \"void\",\n                       SHOW_LHS );\n  FRENSIE_CHECK_EQUAL( dist_data[\"secondary independent unit\"].toString(),\n                       \"void\",\n                       SHOW_LHS );\n  FRENSIE_CHECK_EQUAL( dist_data[\"dependent unit\"].toString(),\n                       \"void\",\n                       SHOW_LHS );\n  FRENSIE_CHECK_EQUAL( dist_data[\"primary grid\"].toType<std::vector<double> >(),\n                       std::vector<double>( {0.0, 0.0, 1.0, 2.0} ),\n                       SHOW_LHS );\n\n  Utility::VariantVector secondary_dists =\n    dist_data[\"secondary dists\"].toVector();\n\n  FRENSIE_REQUIRE_EQUAL( secondary_dists.size(), 4, SHOW_LHS );\n\n  Utility::VariantMap secondary_dist_data = secondary_dists[0].toMap();\n\n  FRENSIE_CHECK_EQUAL( secondary_dist_data[\"type\"].toString(),\n                       \"Delta Distribution\",\n                       SHOW_LHS );\n\n  secondary_dist_data = secondary_dists[1].toMap();\n\n  FRENSIE_CHECK_EQUAL( secondary_dist_data[\"type\"].toString(),\n                       \"Uniform Distribution\",\n                       SHOW_LHS );\n\n  secondary_dist_data = secondary_dists[2].toMap();\n\n  FRENSIE_CHECK_EQUAL( secondary_dist_data[\"type\"].toString(),\n                       \"Uniform Distribution\",\n                       SHOW_LHS );\n\n  FRENSIE_CHECK_EQUAL( secondary_dists[0].toMap(),\n                       secondary_dists[3].toMap(),\n                       SHOW_BOTH );\n}\n\n//---------------------------------------------------------------------------//\n// Check that the unit-aware distribution can be placed in a stream\nFRENSIE_UNIT_TEST( UnitAwareHistogramFullyTabularBasicBivariateDistribution,\n                   ostream_operator )\n{\n  std::ostringstream oss;\n\n  oss << *unit_aware_distribution;\n\n  Utility::VariantMap dist_data =\n    Utility::fromString<Utility::VariantMap>( oss.str() );\n\n  FRENSIE_CHECK_EQUAL( dist_data[\"type\"].toString(),\n                       \"HistogramFullyTabularBasicBivariateDistribution\",\n                       SHOW_LHS );\n  FRENSIE_CHECK_EQUAL( dist_data[\"primary independent unit\"].toString(),\n                       Utility::UnitTraits<MegaElectronVolt>::name(),\n                       SHOW_LHS );\n  FRENSIE_CHECK_EQUAL( dist_data[\"secondary independent unit\"].toString(),\n                       Utility::UnitTraits<cgs::length>::name(),\n                       SHOW_LHS );\n  FRENSIE_CHECK_EQUAL( dist_data[\"dependent unit\"].toString(),\n                       Utility::UnitTraits<Barn>::name(),\n                       SHOW_LHS );\n  FRENSIE_CHECK_EQUAL( dist_data[\"primary grid\"].toType<std::vector<quantity<MegaElectronVolt> > >(),\n                       std::vector<quantity<MegaElectronVolt> >( {0.0*MeV, 0.0*MeV, 1.0*MeV, 2.0*MeV} ),\n                       SHOW_LHS );\n\n  Utility::VariantVector secondary_dists =\n    dist_data[\"secondary dists\"].toVector();\n\n  FRENSIE_REQUIRE_EQUAL( secondary_dists.size(), 4, SHOW_LHS );\n\n  Utility::VariantMap secondary_dist_data = secondary_dists[0].toMap();\n\n  FRENSIE_CHECK_EQUAL( secondary_dist_data[\"type\"].toString(),\n                       \"Delta Distribution\",\n                       SHOW_LHS );\n\n  secondary_dist_data = secondary_dists[1].toMap();\n\n  FRENSIE_CHECK_EQUAL( secondary_dist_data[\"type\"].toString(),\n                       \"Uniform Distribution\",\n                       SHOW_LHS );\n\n  secondary_dist_data = secondary_dists[2].toMap();\n\n  FRENSIE_CHECK_EQUAL( secondary_dist_data[\"type\"].toString(),\n                       \"Uniform Distribution\",\n                       SHOW_LHS );\n\n  FRENSIE_CHECK_EQUAL( secondary_dists[0].toMap(),\n                       secondary_dists[3].toMap(),\n                       SHOW_BOTH );\n}\n\n//---------------------------------------------------------------------------//\n// Check that the distribution can be archived\nFRENSIE_UNIT_TEST_TEMPLATE_EXPAND( HistogramFullyTabularBasicBivariateDistribution,\n                                   archive,\n                                   TestArchives )\n{\n  FETCH_TEMPLATE_PARAM( 0, RawOArchive );\n  FETCH_TEMPLATE_PARAM( 1, RawIArchive );\n\n  typedef typename std::remove_pointer<RawOArchive>::type OArchive;\n  typedef typename std::remove_pointer<RawIArchive>::type IArchive;\n\n  std::string archive_base_name( \"test_histogram_fully_tabular_basic_bivariate_dist\" );\n  std::ostringstream archive_ostream;\n\n  // Create and archive some distributions\n  {\n    std::unique_ptr<OArchive> oarchive;\n\n    createOArchive( archive_base_name, archive_ostream, oarchive );\n\n    std::shared_ptr<Utility::HistogramFullyTabularBasicBivariateDistribution>\n      concrete_distribution = std::dynamic_pointer_cast<Utility::HistogramFullyTabularBasicBivariateDistribution>( distribution );\n\n    FRENSIE_REQUIRE_NO_THROW( (*oarchive) << BOOST_SERIALIZATION_NVP( concrete_distribution ) );\n    FRENSIE_REQUIRE_NO_THROW( (*oarchive) << BOOST_SERIALIZATION_NVP( tab_distribution ) );\n    FRENSIE_REQUIRE_NO_THROW( (*oarchive) << BOOST_SERIALIZATION_NVP( distribution ) );\n  }\n\n  // Copy the archive ostream to an istream\n  std::istringstream archive_istream( archive_ostream.str() );\n\n  // Load the archived distributions\n  std::unique_ptr<IArchive> iarchive;\n\n  createIArchive( archive_istream, iarchive );\n\n  std::shared_ptr<Utility::HistogramFullyTabularBasicBivariateDistribution>\n    concrete_distribution;\n\n  FRENSIE_REQUIRE_NO_THROW( (*iarchive) >> BOOST_SERIALIZATION_NVP( concrete_distribution ) );\n  FRENSIE_CHECK_EQUAL( Utility::toString( *concrete_distribution ),\n                       Utility::toString( *distribution ),\n                       SHOW_BOTH );\n\n  std::shared_ptr<Utility::FullyTabularBasicBivariateDistribution>\n    local_tab_dist;\n\n  FRENSIE_REQUIRE_NO_THROW( (*iarchive) >> boost::serialization::make_nvp( \"tab_distribution\", local_tab_dist ) );\n  FRENSIE_CHECK_EQUAL( Utility::toString( *local_tab_dist ),\n                       Utility::toString( *tab_distribution ),\n                       SHOW_BOTH );\n\n  std::shared_ptr<Utility::BasicBivariateDistribution> local_dist;\n\n  FRENSIE_REQUIRE_NO_THROW( (*iarchive) >> boost::serialization::make_nvp( \"distribution\", local_dist ) );\n  FRENSIE_CHECK_EQUAL( Utility::toString( *local_dist ),\n                       Utility::toString( *distribution ),\n                       SHOW_BOTH );\n}\n\n//---------------------------------------------------------------------------//\n// Check that the unit-aware distribution can be archived\nFRENSIE_UNIT_TEST_TEMPLATE_EXPAND( UnitAwareHistogramFullyTabularBasicBivariateDistribution,\n                                   archive,\n                                   TestArchives )\n{\n  FETCH_TEMPLATE_PARAM( 0, RawOArchive );\n  FETCH_TEMPLATE_PARAM( 1, RawIArchive );\n\n  typedef typename std::remove_pointer<RawOArchive>::type OArchive;\n  typedef typename std::remove_pointer<RawIArchive>::type IArchive;\n\n  std::string archive_base_name( \"test_unit_aware_histogram_fully_tabular_basic_bivariate_dist\" );\n  std::ostringstream archive_ostream;\n\n  // Create and archive some distributions\n  {\n    std::unique_ptr<OArchive> oarchive;\n\n    createOArchive( archive_base_name, archive_ostream, oarchive );\n\n    std::shared_ptr<Utility::UnitAwareHistogramFullyTabularBasicBivariateDistribution<MegaElectronVolt,cgs::length,Barn> >\n      concrete_distribution = std::dynamic_pointer_cast<Utility::UnitAwareHistogramFullyTabularBasicBivariateDistribution<MegaElectronVolt,cgs::length,Barn> >( unit_aware_distribution );\n\n    FRENSIE_REQUIRE_NO_THROW( (*oarchive) << BOOST_SERIALIZATION_NVP( concrete_distribution ) );\n    FRENSIE_REQUIRE_NO_THROW( (*oarchive) << boost::serialization::make_nvp( \"tab_distribution\", unit_aware_tab_distribution ) );\n    FRENSIE_REQUIRE_NO_THROW( (*oarchive) << boost::serialization::make_nvp( \"distribution\", unit_aware_distribution ) );\n  }\n\n  // Copy the archive ostream to an istream\n  std::istringstream archive_istream( archive_ostream.str() );\n\n  // Load the archived distributions\n  std::unique_ptr<IArchive> iarchive;\n\n  createIArchive( archive_istream, iarchive );\n\n  std::shared_ptr<Utility::UnitAwareHistogramFullyTabularBasicBivariateDistribution<MegaElectronVolt,cgs::length,Barn> >\n    concrete_distribution;\n\n  FRENSIE_REQUIRE_NO_THROW( (*iarchive) >> BOOST_SERIALIZATION_NVP( concrete_distribution ) );\n  FRENSIE_CHECK_EQUAL( Utility::toString( *concrete_distribution ),\n                       Utility::toString( *unit_aware_distribution ),\n                       SHOW_BOTH );\n\n  std::shared_ptr<Utility::UnitAwareFullyTabularBasicBivariateDistribution<MegaElectronVolt,cgs::length,Barn> >\n    local_tab_dist;\n\n  FRENSIE_REQUIRE_NO_THROW( (*iarchive) >> boost::serialization::make_nvp( \"tab_distribution\", local_tab_dist ) );\n  FRENSIE_CHECK_EQUAL( Utility::toString( *local_tab_dist ),\n                       Utility::toString( *unit_aware_tab_distribution ),\n                       SHOW_BOTH );\n\n  std::shared_ptr<Utility::UnitAwareBasicBivariateDistribution<MegaElectronVolt,cgs::length,Barn> > local_dist;\n\n  FRENSIE_REQUIRE_NO_THROW( (*iarchive) >> boost::serialization::make_nvp( \"distribution\", local_dist ) );\n  FRENSIE_CHECK_EQUAL( Utility::toString( *local_dist ),\n                       Utility::toString( *unit_aware_distribution ),\n                       SHOW_BOTH );\n}\n\n//---------------------------------------------------------------------------//\n// Custom setup\n//---------------------------------------------------------------------------//\nFRENSIE_CUSTOM_UNIT_TEST_SETUP_BEGIN();\n\nFRENSIE_CUSTOM_UNIT_TEST_INIT()\n{\n  // Create the two-dimensional distribution\n  {\n    std::vector<double> primary_grid( 4 );\n    std::vector<std::shared_ptr<const Utility::TabularUnivariateDistribution> >\n      secondary_dists( 4 );\n\n    // Create the secondary distribution in the first bin\n    primary_grid[0] = 0.0;\n    secondary_dists[0].reset( new Utility::DeltaDistribution( 0.0 ) );\n\n\n    // Create the secondary distribution in the second bin\n    primary_grid[1] = 0.0;\n    secondary_dists[1].reset( new Utility::UniformDistribution( 0.0, 10.0, 2.0 ) );\n\n    // Create the secondary distribution in the third bin\n    primary_grid[2] = 1.0;\n    secondary_dists[2].reset( new Utility::UniformDistribution( 0.0, 10.0, 1.0 ) );\n\n    // Create the secondary distribution beyond the third bin\n    primary_grid[3] = 2.0;\n    secondary_dists[3] = secondary_dists[0];\n\n    tab_distribution.reset( new Utility::HistogramFullyTabularBasicBivariateDistribution(\n                                             primary_grid, secondary_dists ) );\n\n    distribution = tab_distribution;\n  }\n\n  // Create the unit-aware two-dimensional distribution\n  {\n    std::vector<quantity<MegaElectronVolt> > primary_bins( 4 );\n\n    std::vector<std::shared_ptr<const Utility::UnitAwareTabularUnivariateDistribution<cgs::length,Barn> > > secondary_dists( 4 );\n\n    // Create the secondary distribution in the first bin\n    primary_bins[0] = 0.0*MeV;\n    secondary_dists[0].reset( new Utility::UnitAwareDeltaDistribution<cgs::length,Barn>( 0.0*cgs::centimeter ) );\n\n    // Create the secondary distribution in the second bin\n    primary_bins[1] = 0.0*MeV;\n    secondary_dists[1].reset( new Utility::UnitAwareUniformDistribution<cgs::length,Barn>( 0.0*cgs::centimeter, 10.0*cgs::centimeter, 2.0*barn ) );\n\n    // Create the secondary distribution in the third bin\n    primary_bins[2] = 1.0*MeV;\n    secondary_dists[2].reset( new Utility::UnitAwareUniformDistribution<cgs::length,Barn>( 0.0*cgs::centimeter, 10.0*cgs::centimeter, 1.0*barn ) );\n\n    // Create the secondary distribution beyond the third bin\n    primary_bins[3] = 2.0*MeV;\n    secondary_dists[3] = secondary_dists[0];\n\n    unit_aware_tab_distribution.reset( new Utility::UnitAwareHistogramFullyTabularBasicBivariateDistribution<MegaElectronVolt,cgs::length,Barn>( primary_bins, secondary_dists ) );\n\n    unit_aware_distribution = unit_aware_tab_distribution;\n  }\n\n  // Initialize the random number generator\n  Utility::RandomNumberGenerator::createStreams();\n}\n\nFRENSIE_CUSTOM_UNIT_TEST_SETUP_END();\n\n//---------------------------------------------------------------------------//\n// end tstHistogramFullyTabularBasicBivariateDistribution.hpp\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "da70d2d76be82cd8d5f36af8ebf2df2ac8f61ef0", "size": 125193, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "packages/utility/distribution/test/tstHistogramFullyTabularBasicBivariateDistribution.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/utility/distribution/test/tstHistogramFullyTabularBasicBivariateDistribution.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/utility/distribution/test/tstHistogramFullyTabularBasicBivariateDistribution.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": 43.0808671714, "max_line_length": 186, "alphanum_fraction": 0.7338269712, "num_tokens": 34007, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.47816029627290074}}
{"text": "//\n// \tCopyright (c) 2018, Cem Bassoy, cem.bassoy@gmail.com\n// \tCopyright (c) 2019, Amit Singh, amitsingh19975@gmail.com\n//\n//  Distributed under the Boost Software License, Version 1.0. (See\n//  accompanying file LICENSE_1_0.txt or copy at\n//  http://www.boost.org/LICENSE_1_0.txt)\n//\n//  The authors gratefully acknowledge the support of\n//  Google and Fraunhofer IOSB, Ettlingen, Germany\n//\n\n#include <boost/numeric/ublas/tensor/extents.hpp>\n#include <boost/test/unit_test.hpp>\n#include <vector>\n#include \"utility.hpp\"\n\nBOOST_AUTO_TEST_SUITE(test_static_extents)\n\n\nstruct fixture\n{\n  template<std::size_t ... e>\n  using extents = boost::numeric::ublas::extents<e...>;\n\n  extents<>                 e0      {};\n  extents<1>                e1      {};\n  extents<1, 1>             e11     {};\n  extents<2, 1>             e21     {};\n  extents<1, 2>             e12     {};\n  extents<2, 3>             e23     {};\n  extents<2, 1, 1>          e211    {};\n  extents<2, 3, 1>          e231    {};\n  extents<1, 2, 3>          e123    {};\n  extents<4, 2, 3>          e423    {};\n  extents<1, 2, 3, 4>       e1234   {};\n  extents<4, 2, 1, 3>       e4213   {};\n  extents<1, 2, 3, 4, 1>    e12341  {};\n  extents<4, 2, 1, 3, 1>    e42131  {};\n  extents<1, 4, 2, 1, 3, 1> e142131 {};\n};\n\nBOOST_FIXTURE_TEST_CASE(test_extents_static_ctor, fixture,\n                        *boost::unit_test::label(\"extents_static\") *boost::unit_test::label(\"ctor\"))\n{\n\n  namespace ublas = boost::numeric::ublas;\n\n  BOOST_CHECK(  ublas::empty(     e0));\n  BOOST_CHECK(! ublas::empty(     e1));\n  BOOST_CHECK(! ublas::empty(    e11));\n  BOOST_CHECK(! ublas::empty(    e12));\n  BOOST_CHECK(! ublas::empty(    e21));\n  BOOST_CHECK(! ublas::empty(    e23));\n  BOOST_CHECK(! ublas::empty(   e211));\n  BOOST_CHECK(! ublas::empty(   e123));\n  BOOST_CHECK(! ublas::empty(   e423));\n  BOOST_CHECK(! ublas::empty(  e1234));\n  BOOST_CHECK(! ublas::empty(  e4213));\n  BOOST_CHECK(! ublas::empty(e142131));\n\n  BOOST_CHECK_EQUAL( ublas::size(     e0),0);\n  BOOST_CHECK_EQUAL( ublas::size(     e1),1);\n  BOOST_CHECK_EQUAL( ublas::size(    e11),2);\n  BOOST_CHECK_EQUAL( ublas::size(    e12),2);\n  BOOST_CHECK_EQUAL( ublas::size(    e21),2);\n  BOOST_CHECK_EQUAL( ublas::size(    e23),2);\n  BOOST_CHECK_EQUAL( ublas::size(   e211),3);\n  BOOST_CHECK_EQUAL( ublas::size(   e123),3);\n  BOOST_CHECK_EQUAL( ublas::size(   e423),3);\n  BOOST_CHECK_EQUAL( ublas::size(  e1234),4);\n  BOOST_CHECK_EQUAL( ublas::size(  e4213),4);\n  BOOST_CHECK_EQUAL( ublas::size(e142131),6);\n\n\n  BOOST_CHECK_EQUAL( ublas::size_v<decltype(     e0)>,0);\n  BOOST_CHECK_EQUAL( ublas::size_v<decltype(     e1)>,1);\n  BOOST_CHECK_EQUAL( ublas::size_v<decltype(    e11)>,2);\n  BOOST_CHECK_EQUAL( ublas::size_v<decltype(    e12)>,2);\n  BOOST_CHECK_EQUAL( ublas::size_v<decltype(    e21)>,2);\n  BOOST_CHECK_EQUAL( ublas::size_v<decltype(    e23)>,2);\n  BOOST_CHECK_EQUAL( ublas::size_v<decltype(   e211)>,3);\n  BOOST_CHECK_EQUAL( ublas::size_v<decltype(   e123)>,3);\n  BOOST_CHECK_EQUAL( ublas::size_v<decltype(   e423)>,3);\n  BOOST_CHECK_EQUAL( ublas::size_v<decltype(  e1234)>,4);\n  BOOST_CHECK_EQUAL( ublas::size_v<decltype(  e4213)>,4);\n  BOOST_CHECK_EQUAL( ublas::size_v<decltype(e142131)>,6);\n\n}\n\nBOOST_FIXTURE_TEST_CASE(test_extents_static_product, fixture,\n                        *boost::unit_test::label(\"extents_static\") *boost::unit_test::label(\"product\"))\n{\n  \n  namespace ublas = boost::numeric::ublas;\n\n  BOOST_CHECK_EQUAL(ublas::product(     e0),  0);\n  //FIXME:  BOOST_CHECK_EQUAL(ublas::product(     e1),  1);\n  BOOST_CHECK_EQUAL(ublas::product(    e11),  1);\n  BOOST_CHECK_EQUAL(ublas::product(    e12),  2);\n  BOOST_CHECK_EQUAL(ublas::product(    e21),  2);\n  BOOST_CHECK_EQUAL(ublas::product(    e23),  6);\n  BOOST_CHECK_EQUAL(ublas::product(   e211),  2);\n  BOOST_CHECK_EQUAL(ublas::product(   e123),  6);\n  BOOST_CHECK_EQUAL(ublas::product(   e423), 24);\n  BOOST_CHECK_EQUAL(ublas::product(  e1234), 24);\n  BOOST_CHECK_EQUAL(ublas::product(  e4213), 24);\n  BOOST_CHECK_EQUAL(ublas::product(e142131), 24);\n\n\n  BOOST_CHECK_EQUAL(ublas::product_v<decltype(     e0)>,  0);\n  BOOST_CHECK_EQUAL(ublas::product_v<decltype(     e1)>,  1);\n  BOOST_CHECK_EQUAL(ublas::product_v<decltype(    e11)>,  1);\n  BOOST_CHECK_EQUAL(ublas::product_v<decltype(    e12)>,  2);\n  BOOST_CHECK_EQUAL(ublas::product_v<decltype(    e21)>,  2);\n  BOOST_CHECK_EQUAL(ublas::product_v<decltype(    e23)>,  6);\n  BOOST_CHECK_EQUAL(ublas::product_v<decltype(   e211)>,  2);\n  BOOST_CHECK_EQUAL(ublas::product_v<decltype(   e123)>,  6);\n  BOOST_CHECK_EQUAL(ublas::product_v<decltype(   e423)>, 24);\n  BOOST_CHECK_EQUAL(ublas::product_v<decltype(  e1234)>, 24);\n  BOOST_CHECK_EQUAL(ublas::product_v<decltype(  e4213)>, 24);\n  BOOST_CHECK_EQUAL(ublas::product_v<decltype(e142131)>, 24);\n}\n\nBOOST_FIXTURE_TEST_CASE(test_static_extents_access, fixture,\n                        *boost::unit_test::label(\"extents_static\") *boost::unit_test::label(\"access\"))\n{\n  namespace ublas = boost::numeric::ublas;\n\n  BOOST_REQUIRE_EQUAL( ublas::size_v<decltype(     e0)>,0);\n  BOOST_REQUIRE_EQUAL( ublas::size_v<decltype(     e1)>,1);\n  BOOST_REQUIRE_EQUAL( ublas::size_v<decltype(    e11)>,2);\n  BOOST_REQUIRE_EQUAL( ublas::size_v<decltype(    e12)>,2);\n  BOOST_REQUIRE_EQUAL( ublas::size_v<decltype(    e21)>,2);\n  BOOST_REQUIRE_EQUAL( ublas::size_v<decltype(    e23)>,2);\n  BOOST_REQUIRE_EQUAL( ublas::size_v<decltype(   e211)>,3);\n  BOOST_REQUIRE_EQUAL( ublas::size_v<decltype(   e123)>,3);\n  BOOST_REQUIRE_EQUAL( ublas::size_v<decltype(   e423)>,3);\n  BOOST_REQUIRE_EQUAL( ublas::size_v<decltype(  e1234)>,4);\n  BOOST_REQUIRE_EQUAL( ublas::size_v<decltype(  e4213)>,4);\n  BOOST_REQUIRE_EQUAL( ublas::size_v<decltype(e142131)>,6);\n\n\n  BOOST_CHECK_EQUAL((ublas::get_v<decltype(e1),0>), 1);\n\n  BOOST_CHECK_EQUAL((ublas::get_v<decltype(e11),0>), 1);\n  BOOST_CHECK_EQUAL((ublas::get_v<decltype(e11),1>), 1);\n\n  BOOST_CHECK_EQUAL((ublas::get_v<decltype(e12),0>), 1);\n  BOOST_CHECK_EQUAL((ublas::get_v<decltype(e12),1>), 2);\n\n  BOOST_CHECK_EQUAL((ublas::get_v<decltype(e21),0>), 2);\n  BOOST_CHECK_EQUAL((ublas::get_v<decltype(e21),1>), 1);\n\n  BOOST_CHECK_EQUAL((ublas::get_v<decltype(e23),0>), 2);\n  BOOST_CHECK_EQUAL((ublas::get_v<decltype(e23),1>), 3);\n\n  BOOST_CHECK_EQUAL((ublas::get_v<decltype(e211),0>), 2);\n  BOOST_CHECK_EQUAL((ublas::get_v<decltype(e211),1>), 1);\n  BOOST_CHECK_EQUAL((ublas::get_v<decltype(e211),2>), 1);\n\n  BOOST_CHECK_EQUAL((ublas::get_v<decltype(e123),0>), 1);\n  BOOST_CHECK_EQUAL((ublas::get_v<decltype(e123),1>), 2);\n  BOOST_CHECK_EQUAL((ublas::get_v<decltype(e123),2>), 3);\n\n  BOOST_CHECK_EQUAL((ublas::get_v<decltype(e423),0>), 4);\n  BOOST_CHECK_EQUAL((ublas::get_v<decltype(e423),1>), 2);\n  BOOST_CHECK_EQUAL((ublas::get_v<decltype(e423),2>), 3);\n\n  BOOST_CHECK_EQUAL((ublas::get_v<decltype(e1234),0>), 1);\n  BOOST_CHECK_EQUAL((ublas::get_v<decltype(e1234),1>), 2);\n  BOOST_CHECK_EQUAL((ublas::get_v<decltype(e1234),2>), 3);\n  BOOST_CHECK_EQUAL((ublas::get_v<decltype(e1234),3>), 4);\n\n  BOOST_CHECK_EQUAL((ublas::get_v<decltype(e4213),0>), 4);\n  BOOST_CHECK_EQUAL((ublas::get_v<decltype(e4213),1>), 2);\n  BOOST_CHECK_EQUAL((ublas::get_v<decltype(e4213),2>), 1);\n  BOOST_CHECK_EQUAL((ublas::get_v<decltype(e4213),3>), 3);\n\n  //FIXME:  BOOST_CHECK_EQUAL(e1 [0], 1);\n\n  BOOST_CHECK_EQUAL(e11[0], 1);\n  BOOST_CHECK_EQUAL(e11[1], 1);\n\n  BOOST_CHECK_EQUAL(e12[0], 1);\n  BOOST_CHECK_EQUAL(e12[1], 2);\n\n  BOOST_CHECK_EQUAL(e21[0], 2);\n  BOOST_CHECK_EQUAL(e21[1], 1);\n\n  BOOST_CHECK_EQUAL(e23[0], 2);\n  BOOST_CHECK_EQUAL(e23[1], 3);\n\n  BOOST_CHECK_EQUAL(e211[0], 2);\n  BOOST_CHECK_EQUAL(e211[1], 1);\n  BOOST_CHECK_EQUAL(e211[2], 1);\n\n  BOOST_CHECK_EQUAL(e123[0], 1);\n  BOOST_CHECK_EQUAL(e123[1], 2);\n  BOOST_CHECK_EQUAL(e123[2], 3);\n\n  BOOST_CHECK_EQUAL(e423[0], 4);\n  BOOST_CHECK_EQUAL(e423[1], 2);\n  BOOST_CHECK_EQUAL(e423[2], 3);\n\n  BOOST_CHECK_EQUAL(e1234[0], 1);\n  BOOST_CHECK_EQUAL(e1234[1], 2);\n  BOOST_CHECK_EQUAL(e1234[2], 3);\n  BOOST_CHECK_EQUAL(e1234[3], 4);\n\n  BOOST_CHECK_EQUAL(e4213[0], 4);\n  BOOST_CHECK_EQUAL(e4213[1], 2);\n  BOOST_CHECK_EQUAL(e4213[2], 1);\n  BOOST_CHECK_EQUAL(e4213[3], 3);\n}\n\nstruct fixture_second\n{\n  template<std::size_t ... e>\n  using extents = boost::numeric::ublas::extents<e...>;\n\n  std::tuple<\n    extents<>\n    > empty;\n\n  std::tuple<\n    //FIXME:    extents<1>,\n    extents<1,1>,\n    extents<1,1,1>,\n    extents<1,1,1,1>\n    > scalars;\n\n  std::tuple<\n    extents<1,2>,\n    extents<2,1>,\n    extents<1,2,1>,\n    extents<2,1,1>,\n    extents<1,4,1,1>,\n    extents<5,1,1,1,1>\n    > vectors;\n\n  std::tuple<\n    extents<2,3>,\n    extents<3,2,1>,\n    extents<4,4,1,1>,\n    extents<6,6,1,1,1,1>\n    > matrices;\n\n  std::tuple<\n    extents<1,2,3>,\n    extents<1,2,3>,\n    extents<1,2,3,1>,\n    extents<4,2,3>,\n    extents<4,2,3,1>,\n    extents<4,2,3,1,1>,\n    extents<6,6,6,1,1,1>,\n    extents<6,6,1,1,1,6>\n    > tensors;\n};\n\n\nBOOST_FIXTURE_TEST_CASE(test_static_extents, fixture_second,\n                        *boost::unit_test::label(\"extents_static\") *boost::unit_test::label(\"is_scalar_vector_matrix_tensor\")) {\n\n  namespace ublas = boost::numeric::ublas;\n\n  for_each_in_tuple(scalars,[](auto const& /*unused*/, auto const& e){\n    BOOST_CHECK(  ublas::is_scalar(e) );\n    BOOST_CHECK(  ublas::is_vector(e) );\n    BOOST_CHECK(  ublas::is_matrix(e) );\n    BOOST_CHECK( !ublas::is_tensor(e) );\n\n    BOOST_CHECK(  ublas::is_scalar_v<decltype(e)>);\n    BOOST_CHECK(  ublas::is_vector_v<decltype(e)>);\n    BOOST_CHECK(  ublas::is_matrix_v<decltype(e)>);\n    BOOST_CHECK( !ublas::is_tensor_v<decltype(e)>);\n\n  });\n\n  for_each_in_tuple(vectors,[](auto const& /*unused*/, auto& e){\n    BOOST_CHECK( !ublas::is_scalar(e) );\n    BOOST_CHECK(  ublas::is_vector(e) );\n    BOOST_CHECK(  ublas::is_matrix(e) );\n    BOOST_CHECK( !ublas::is_tensor(e) );\n\n    BOOST_CHECK( !ublas::is_scalar_v<decltype(e)>);\n    BOOST_CHECK(  ublas::is_vector_v<decltype(e)>);\n    BOOST_CHECK(  ublas::is_matrix_v<decltype(e)>);\n    BOOST_CHECK( !ublas::is_tensor_v<decltype(e)>);\n  });\n\n  for_each_in_tuple(matrices,[](auto const& /*unused*/, auto& e){\n    BOOST_CHECK( !ublas::is_scalar(e) );\n    BOOST_CHECK( !ublas::is_vector(e) );\n    BOOST_CHECK(  ublas::is_matrix(e) );\n    BOOST_CHECK( !ublas::is_tensor(e) );\n\n    BOOST_CHECK( !ublas::is_scalar_v<decltype(e)>);\n    BOOST_CHECK( !ublas::is_vector_v<decltype(e)>);\n    BOOST_CHECK(  ublas::is_matrix_v<decltype(e)>);\n    BOOST_CHECK( !ublas::is_tensor_v<decltype(e)>);\n  });\n\n  for_each_in_tuple(tensors,[](auto const& /*unused*/, auto& e){\n    BOOST_CHECK( !ublas::is_scalar(e) );\n    BOOST_CHECK( !ublas::is_vector(e) );\n    BOOST_CHECK( !ublas::is_matrix(e) );\n    BOOST_CHECK(  ublas::is_tensor(e) );\n\n    BOOST_CHECK( !ublas::is_scalar_v<decltype(e)>);\n    BOOST_CHECK( !ublas::is_vector_v<decltype(e)>);\n    BOOST_CHECK( !ublas::is_matrix_v<decltype(e)>);\n    BOOST_CHECK(  ublas::is_tensor_v<decltype(e)>);\n  });\n\n}\n\nBOOST_FIXTURE_TEST_CASE(test_static_extents_valid, fixture_second,\n                        *boost::unit_test::label(\"extents_extents\") *boost::unit_test::label(\"valid\"))\n{\n  namespace ublas = boost::numeric::ublas;\n\n//FIXME:  BOOST_CHECK(!ublas::is_valid (extents<0>{}) );\n//FIXME:  BOOST_CHECK( ublas::is_valid (extents<2>{}) );\n//FIXME:  BOOST_CHECK( ublas::is_valid (extents<3>{}) );\n\n  BOOST_CHECK(!ublas::is_valid_v<extents<0>> );\n  BOOST_CHECK( ublas::is_valid_v<extents<2>> );\n  BOOST_CHECK( ublas::is_valid_v<extents<3>> );\n\n\n  for_each_in_tuple(scalars  ,[](auto const& /*unused*/, auto& e){ BOOST_CHECK(  ublas::is_valid (e) ); });\n  for_each_in_tuple(vectors  ,[](auto const& /*unused*/, auto& e){ BOOST_CHECK(  ublas::is_valid (e) ); });\n  for_each_in_tuple(matrices ,[](auto const& /*unused*/, auto& e){ BOOST_CHECK(  ublas::is_valid (e) ); });\n  for_each_in_tuple(tensors  ,[](auto const& /*unused*/, auto& e){ BOOST_CHECK(  ublas::is_valid (e) ); });\n\n\n  for_each_in_tuple(scalars  ,[](auto const& /*unused*/, auto& e){ BOOST_CHECK(  ublas::is_valid_v<decltype(e)> ); });\n  for_each_in_tuple(vectors  ,[](auto const& /*unused*/, auto& e){ BOOST_CHECK(  ublas::is_valid_v<decltype(e)> ); });\n  for_each_in_tuple(matrices ,[](auto const& /*unused*/, auto& e){ BOOST_CHECK(  ublas::is_valid_v<decltype(e)> ); });\n  for_each_in_tuple(tensors  ,[](auto const& /*unused*/, auto& e){ BOOST_CHECK(  ublas::is_valid_v<decltype(e)> ); });\n}\n\n\nBOOST_FIXTURE_TEST_CASE(test_static_extents_comparsion_operator, fixture,\n                        *boost::unit_test::label(\"extents_static\") *boost::unit_test::label(\"equals\"))\n{\n  namespace ublas = boost::numeric::ublas;\n\n  BOOST_CHECK(      e0 == e0      );\n  BOOST_CHECK(      e1 == e1      );\n  BOOST_CHECK(     e11 == e11     );\n  BOOST_CHECK(     e21 == e21     );\n  BOOST_CHECK(     e12 == e12     );\n  BOOST_CHECK(     e23 == e23     );\n  BOOST_CHECK(    e231 == e231    );\n  BOOST_CHECK(    e211 == e211    );\n  BOOST_CHECK(    e123 == e123    );\n  BOOST_CHECK(    e423 == e423    );\n  BOOST_CHECK(   e1234 == e1234   );\n  BOOST_CHECK(   e4213 == e4213   );\n  BOOST_CHECK( e142131 == e142131 );\n\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "c92794886c8038c5cd8dceb0d52cc8d89196c73a", "size": 13079, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/tensor/test_static_extents.cpp", "max_stars_repo_name": "samd2/ublas", "max_stars_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 96.0, "max_stars_repo_stars_event_min_datetime": "2015-01-23T10:15:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T18:31:02.000Z", "max_issues_repo_path": "test/tensor/test_static_extents.cpp", "max_issues_repo_name": "samd2/ublas", "max_issues_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 105.0, "max_issues_repo_issues_event_min_datetime": "2015-01-14T09:01:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-05T06:10:39.000Z", "max_forks_repo_path": "test/tensor/test_static_extents.cpp", "max_forks_repo_name": "samd2/ublas", "max_forks_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 157.0, "max_forks_repo_forks_event_min_datetime": "2015-01-26T13:35:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T11:12:27.000Z", "avg_line_length": 35.6376021798, "max_line_length": 128, "alphanum_fraction": 0.652114076, "num_tokens": 4269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708562, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.47816029150490513}}
{"text": "#include <igl/colon.h>\r\n#include <igl/directed_edge_orientations.h>\r\n#include <igl/directed_edge_parents.h>\r\n#include <igl/forward_kinematics.h>\r\n#include <igl/PI.h>\r\n#include <igl/lbs_matrix.h>\r\n#include <igl/deform_skeleton.h>\r\n#include <igl/dqs.h>\r\n#include <igl/readDMAT.h>\r\n#include <igl/readOFF.h>\r\n#include <igl/arap.h>\r\n#include <igl/opengl/glfw/Viewer.h>\r\n\r\n#include <Eigen/Geometry>\r\n#include <Eigen/StdVector>\r\n#include <vector>\r\n#include <algorithm>\r\n#include <iostream>\r\n\r\n#include \"tutorial_shared_path.h\"\r\n\r\ntypedef \r\n  std::vector<Eigen::Quaterniond,Eigen::aligned_allocator<Eigen::Quaterniond> >\r\n  RotationList;\r\n\r\nconst Eigen::RowVector3d sea_green(70./255.,252./255.,167./255.);\r\nEigen::MatrixXd V,U;\r\nEigen::MatrixXi F;\r\nEigen::VectorXi S,b;\r\nEigen::RowVector3d mid;\r\ndouble anim_t = 0.0;\r\ndouble anim_t_dir = 0.03;\r\nigl::ARAPData arap_data;\r\n\r\nbool pre_draw(igl::opengl::glfw::Viewer & viewer)\r\n{\r\n  using namespace Eigen;\r\n  using namespace std;\r\n    MatrixXd bc(b.size(),V.cols());\r\n    for(int i = 0;i<b.size();i++)\r\n    {\r\n      bc.row(i) = V.row(b(i));\r\n      switch(S(b(i)))\r\n      {\r\n        case 0:\r\n        {\r\n          const double r = mid(0)*0.25;\r\n          bc(i,0) += r*sin(0.5*anim_t*2.*igl::PI);\r\n          bc(i,1) -= r+r*cos(igl::PI+0.5*anim_t*2.*igl::PI);\r\n          break;\r\n        }\r\n        case 1:\r\n        {\r\n          const double r = mid(1)*0.15;\r\n          bc(i,1) += r+r*cos(igl::PI+0.15*anim_t*2.*igl::PI);\r\n          bc(i,2) -= r*sin(0.15*anim_t*2.*igl::PI);\r\n          break;\r\n        }\r\n        case 2:\r\n        {\r\n          const double r = mid(1)*0.15;\r\n          bc(i,2) += r+r*cos(igl::PI+0.35*anim_t*2.*igl::PI);\r\n          bc(i,0) += r*sin(0.35*anim_t*2.*igl::PI);\r\n          break;\r\n        }\r\n        default:\r\n          break;\r\n      }\r\n    }\r\n    igl::arap_solve(bc,arap_data,U);\r\n    viewer.data().set_vertices(U);\r\n    viewer.data().compute_normals();\r\n  if(viewer.core().is_animating)\r\n  {\r\n    anim_t += anim_t_dir;\r\n  }\r\n  return false;\r\n}\r\n\r\nbool key_down(igl::opengl::glfw::Viewer &viewer, unsigned char key, int mods)\r\n{\r\n  switch(key)\r\n  {\r\n    case ' ':\r\n      viewer.core().is_animating = !viewer.core().is_animating;\r\n      return true;\r\n  }\r\n  return false;\r\n}\r\n\r\nint main(int argc, char *argv[])\r\n{\r\n  using namespace Eigen;\r\n  using namespace std;\r\n  igl::readOFF(TUTORIAL_SHARED_PATH \"/decimated-knight.off\",V,F);\r\n  U=V;\r\n  igl::readDMAT(TUTORIAL_SHARED_PATH \"/decimated-knight-selection.dmat\",S);\r\n\r\n  // vertices in selection\r\n  igl::colon<int>(0,V.rows()-1,b);\r\n  b.conservativeResize(stable_partition( b.data(), b.data()+b.size(), \r\n   [](int i)->bool{return S(i)>=0;})-b.data());\r\n  // Centroid\r\n  mid = 0.5*(V.colwise().maxCoeff() + V.colwise().minCoeff());\r\n  // Precomputation\r\n  arap_data.max_iter = 100;\r\n  igl::arap_precomputation(V,F,V.cols(),b,arap_data);\r\n\r\n  // Set color based on selection\r\n  MatrixXd C(F.rows(),3);\r\n  RowVector3d purple(80.0/255.0,64.0/255.0,255.0/255.0);\r\n  RowVector3d gold(255.0/255.0,228.0/255.0,58.0/255.0);\r\n  for(int f = 0;f<F.rows();f++)\r\n  {\r\n    if( S(F(f,0))>=0 && S(F(f,1))>=0 && S(F(f,2))>=0)\r\n    {\r\n      C.row(f) = purple;\r\n    }else\r\n    {\r\n      C.row(f) = gold;\r\n    }\r\n  }\r\n\r\n  // Plot the mesh with pseudocolors\r\n  igl::opengl::glfw::Viewer viewer;\r\n  viewer.data().set_mesh(U, F);\r\n  viewer.data().set_colors(C);\r\n  viewer.callback_pre_draw = &pre_draw;\r\n  viewer.callback_key_down = &key_down;\r\n  viewer.core().is_animating = false;\r\n  viewer.core().animation_max_fps = 30.;\r\n  cout<<\r\n    \"Press [space] to toggle animation\"<<endl;\r\n  viewer.launch();\r\n}\r\n", "meta": {"hexsha": "55d37c657727abd08ee733cf6b0b9d1678b6e4a0", "size": 3594, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sdf-net/lib/submodules/libigl/tutorial/405_AsRigidAsPossible/main.cpp", "max_stars_repo_name": "hardikk13/nglod", "max_stars_repo_head_hexsha": "6c6c66ce1b39c5a3515cafc290ec903ae90b506e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sdf-net/lib/submodules/libigl/tutorial/405_AsRigidAsPossible/main.cpp", "max_issues_repo_name": "hardikk13/nglod", "max_issues_repo_head_hexsha": "6c6c66ce1b39c5a3515cafc290ec903ae90b506e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sdf-net/lib/submodules/libigl/tutorial/405_AsRigidAsPossible/main.cpp", "max_forks_repo_name": "hardikk13/nglod", "max_forks_repo_head_hexsha": "6c6c66ce1b39c5a3515cafc290ec903ae90b506e", "max_forks_repo_licenses": ["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.4264705882, "max_line_length": 80, "alphanum_fraction": 0.5831942126, "num_tokens": 1133, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943805178139, "lm_q2_score": 0.6654105587468141, "lm_q1q2_score": 0.47816028825267926}}
{"text": "//////////////////////////////////////////////////////////////////////////////////\n// survival::models::exponential::scalar::detail::lpdf_rt.hpp                   //\n//                                                                              //\n//  Copyright 2009 Erwann Rogard. Distributed under the Boost                   //\n//  Software License, Version 1.0. (See accompanying file                       //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)            //\n//////////////////////////////////////////////////////////////////////////////////\n#ifndef BOOST_STATISTICS_DETAIL_DISTRIBUTION_SURVIVAL_MODELS_EXPONENTIAL_SCALAR_DETAIL_LPDF_RT_HPP_ER_2009\n#define BOOST_STATISTICS_DETAIL_DISTRIBUTION_SURVIVAL_MODELS_EXPONENTIAL_SCALAR_DETAIL_LPDF_RT_HPP_ER_2009\n#include <stdexcept>\n#include <string>\n#include <cmath>\n#include <boost/operators.hpp>\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/archive/text_iarchive.hpp>\n#include <boost/statistics/detail/distribution/survival/response/types/right_truncated/event.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n\nnamespace boost{\nnamespace statistics{\nnamespace detail{\nnamespace distribution{\nnamespace survival{\nnamespace exponential_model_{\n\n    template<typename T,typename B>\n    T lpdf_rt(\n        const T& log_rate,\n        const response::event<T,B>& e\n    ){\n    \n        typedef std::string str_;\n        static const str_ msg \n            = \"exponential<T,right_truncated> : log_unnormalized_pdf\";\n        \n        typedef T val_;\n        \n        val_ result = log_rate;\n        result = exp( result );\n        result *= (- e.time());\n        try{\n            if( boost::math::isinf(result) ){\n                throw std::runtime_error(\" isinf(result)\");\n            }\n            if( boost::math::isnan(result) ){\n                throw std::runtime_error(\" isnan(result)\");\n            }\n        }catch(std::exception ex){\n            str_ str = msg;\n            str += ex.what();\n            throw std::runtime_error(str);\n        }\n        if(e.failure()){\n            result += log_rate;\n        }\n        return result;\n    }\n\n}// exponential_model_\n}// survival\n}// distribution\n}// detail\n}// statistics\n}// boost\n\n#endif", "meta": {"hexsha": "9e393a6dcaea301b99611c768f6c9e26175b331d", "size": 2248, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "distribution_survival/boost/statistics/detail/distribution/survival/models/exponential/scalar/detail/lpdf_rt.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_survival/boost/statistics/detail/distribution/survival/models/exponential/scalar/detail/lpdf_rt.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_survival/boost/statistics/detail/distribution/survival/models/exponential/scalar/detail/lpdf_rt.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": 34.0606060606, "max_line_length": 106, "alphanum_fraction": 0.5600533808, "num_tokens": 443, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.478107704702877}}
{"text": "#define PY_SSIZE_T_CLEAN\n#include \"Python.h\"\n//#include \"math.h\"\n#include \"numpy/ndarraytypes.h\"\n#include \"numpy/ufuncobject.h\"\n#include \"numpy/halffloat.h\"\n#include \"approx_class.h\"\n#include <Eigen/Core>\n\nusing Eigen::VectorXd;\n\n/*\n * approx_class.h\n *\n * Each function of the form type_cdf defines the\n * CDF function for a different numpy dtype.\n *\n * Details explaining the Python-C API can be found under\n * 'Extending and Embedding' and 'Python/C API' at\n * docs.python.org .\n *\n */\n\nstatic PyMethodDef CDFUfuncMethods[] = {\n        {NULL, NULL, 0, NULL}\n};\n\n/* The loop definitions must precede the PyMODINIT_FUNC. */\n\nstatic void double_cdf(char **args, npy_intp *dimensions,\n                       npy_intp* steps, void* data)\n{\n    npy_intp i;\n    npy_intp j;\n    npy_intp n = dimensions[1];  // x size\n    npy_intp m = dimensions[2];  // alphas size\n\n    char *x = args[0];  // x\n    char *alpha = args[1];\n    char *beta = args[2];\n    char *alphas = args[3];\n    char *out = args[4];\n    npy_intp in_step = steps[5], alpha_step = steps[6], out_step = steps[7];\n\n    double loc = *(double *) alpha;\n    double scale = *(double *) beta;\n\n    VectorXd param(m);\n    for (j = 0; j < m; j++) {\n        param[j] = *(double *)alphas;\n        alphas += alpha_step;\n    }\n\n    Distribution<double> distribution(loc, scale, param);\n\n    double tmp;\n#pragma omp parallel for firstprivate(distribution)\n    for (i = 0; i < n; i++) {\n        /*BEGIN main ufunc computation*/\n        tmp = *(double *)(x + i * in_step);\n        *(( double *)(out + out_step * i)) = distribution.cdf(tmp);\n        /*END main ufunc computation*/\n    }\n}\n\n/*This gives pointers to the above functions*/\nPyUFuncGenericFunction funcs[1] = {reinterpret_cast<PyUFuncGenericFunction>(&double_cdf)};\n\nstatic char types[5] = {NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE};\nstatic void *data[1] = {NULL};\n\nstatic struct PyModuleDef moduledef = {\n        PyModuleDef_HEAD_INIT,\n        \"cdf_ufunc\",\n        NULL,\n        -1,\n        CDFUfuncMethods,\n        NULL,\n        NULL,\n        NULL,\n        NULL\n};\n\nPyMODINIT_FUNC PyInit_cdf_ufunc(void)\n{\n    PyObject *m, *cdf, *d;\n\n    m = PyModule_Create(&moduledef);\n    if (!m) {\n        return NULL;\n    }\n\n    import_array();\n    import_umath();\n\n    cdf = PyUFunc_FromFuncAndDataAndSignature(funcs, data, types, 1, 4, 1,\n                                              PyUFunc_None, \"cdf\",\n                                              \"cdf_docstring\", 0, \"(n),(),(),(m)->(n)\");\n\n    d = PyModule_GetDict(m);\n\n    PyDict_SetItemString(d, \"cdf\", cdf);\n    Py_DECREF(cdf);\n\n    return m;\n}\n", "meta": {"hexsha": "b930f6d64954f08390956609755c67182da1fa8a", "size": 2621, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "nychka/distribution/cdf_ufunc.cpp", "max_stars_repo_name": "ainmukh/project", "max_stars_repo_head_hexsha": "c5a7481414bd2baa2b38b8c64c593348846b6660", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "nychka/distribution/cdf_ufunc.cpp", "max_issues_repo_name": "ainmukh/project", "max_issues_repo_head_hexsha": "c5a7481414bd2baa2b38b8c64c593348846b6660", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nychka/distribution/cdf_ufunc.cpp", "max_forks_repo_name": "ainmukh/project", "max_forks_repo_head_hexsha": "c5a7481414bd2baa2b38b8c64c593348846b6660", "max_forks_repo_licenses": ["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.4953271028, "max_line_length": 90, "alphanum_fraction": 0.594429607, "num_tokens": 734, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.478107704702877}}
{"text": "#include \"cplex.h\"\n#include <cassert>\n#include <string>\n#include <vector>\n#include <iostream>\n#include <fstream>\n#include <boost/algorithm/string.hpp>\n#include <numeric>\n\nusing namespace std;\n\n\nint ReadSolution(string solfile,\n        vector<double> &solution,\n        vector<string> &names,\n        double &objval);\n\n\nint main(int argc, char* argv[])\n{\n    int status = 0;\n\n    CPXENVptr env = CPXopenCPLEX(&status);\n    assert(!status);\n\n    cout << \"CPLEX version: \" <<  CPXversion(env) << endl;\n\n    status = CPXsetintparam(env, CPXPARAM_ScreenOutput, CPX_ON);\n    assert(!status);\n\n    CPXLPptr problem = CPXcreateprob(env, &status, \"Test problem\");\n    assert(!status);\n\n    status = CPXreadcopyprob(env, \n        problem, \n        argv[1], \n        NULL);\n    assert(!status);\n\n\n    vector<double> solution;\n    vector<string> names;\n    double objectivevalue;\n\n    status = ReadSolution(argv[2],\n            solution,\n            names,\n            objectivevalue);\n    assert(!status);\n\n    // We sort the solution, according to index in problem\n    vector<double> sortedsolution(CPXgetnumcols(env, problem));\n\n    for(int i = 0; i < solution.size(); ++i)\n    {\n        int idx;\n        status = CPXgetcolindex(env, \n                problem, \n                names[i].c_str(),\n                &idx);\n        if(&idx != NULL)\n        {\n            sortedsolution[idx] =solution[i];\n            if(idx >= sortedsolution.size())\n            {\n                cout << \"Variable index out of bounds!!\" <<  endl;\n                exit(1);\n            }\n        }\n        else\n        {\n            cerr << \"Error. Name not found\" << endl;\n            exit(1);\n        }\n    }\n\n    vector<int> indices;\n    int beg = 0;\n    int effortlevel = CPX_MIPSTART_CHECKFEAS;\n    for(int i = 0; i < CPXgetnumcols(env, problem); ++i)\n        indices.push_back(i);\n\n    status = CPXaddmipstarts(env,\n            problem,\n            1,\n            CPXgetnumcols(env, problem),\n            &beg,\n            &(indices[0]),\n            &(sortedsolution[0]),\n            &(effortlevel),\n            NULL);\n    assert(!status);\n\n    status = CPXsetdblparam(env, CPXPARAM_TimeLimit, 10.0);\n    assert(!status);\n\n    status = CPXmipopt(env, problem);\n\n    status = CPXfreeprob(env, &problem);\n    assert(!status);\n\n    status = CPXcloseCPLEX(&env);\n    assert(!status);\n\n\n}\n\nint ReadSolution(string solfile,\n        vector<double> &solution,\n        vector<string> &names,\n        double &objval)\n{\n    int status;\n\n    ifstream infile(solfile.c_str());\n\n    string line;\n    vector<string> tokens;\n\n    while(getline(infile, line))\n    {\n        if(line == \"\")\n            continue;\n        boost::algorithm::split(tokens, \n                line, \n                boost::algorithm::is_space(), \n                boost::token_compress_on);\n        if(tokens[0] == \"=obj=\")\n        {\n            objval = atof(tokens[1].c_str());\n        }\n        else if(tokens[0] != \"#\")\n        {\n            solution.push_back(atof(tokens[1].c_str()));\n            names.push_back(tokens[0].c_str());\n            //cout << \"Variable \" << tokens[0] << \"= \" << atof(tokens[1].c_str()) << endl;\n        }\n    }\n\n    infile.close();\n\n    return 0;\n}\n", "meta": {"hexsha": "8613d93f4e0fb6db1ae194350148e5e83dfc115d", "size": 3214, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example.cpp", "max_stars_repo_name": "rocarvaj/mipstart-example", "max_stars_repo_head_hexsha": "4d949b1706435dba1c99715c4ce6776ed35c1016", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-06-30T12:27:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-30T12:27:26.000Z", "max_issues_repo_path": "example.cpp", "max_issues_repo_name": "rocarvaj/mipstart-example", "max_issues_repo_head_hexsha": "4d949b1706435dba1c99715c4ce6776ed35c1016", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example.cpp", "max_forks_repo_name": "rocarvaj/mipstart-example", "max_forks_repo_head_hexsha": "4d949b1706435dba1c99715c4ce6776ed35c1016", "max_forks_repo_licenses": ["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.3194444444, "max_line_length": 90, "alphanum_fraction": 0.5273802116, "num_tokens": 793, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.478107704702877}}
{"text": "#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/erdos_renyi_generator.hpp>\n#include <boost/random/linear_congruential.hpp>\n#include <boost/graph/graphml.hpp>\n#include <boost/property_map/dynamic_property_map.hpp>\n#include <iostream>\n#include <stdlib.h>     /* atoi */\n//#include \"include_and_types.cpp\"\n\ntypedef boost::adjacency_list <boost::setS, boost::vecS, boost::directedS, boost::no_property, boost::disallow_parallel_edge_tag> G;\ntypedef boost::erdos_renyi_iterator<boost::minstd_rand, G> ERGen;\n\nusing namespace std;\n\nint main(int argc,char* argv[])\n{\n    boost::dynamic_properties dp;\n    boost::minstd_rand gen;\n    // Create graph with 100 nodes and edges with probability 0.05\n    float n, p;\n    if (argc <= 1){\n        n= 20;\n        p= 0.05;\n    } else if( argc == 3){\n        n = atof(argv[1]);\n        p = atof(argv[2]);\n    } else return 1;\n\n    G g(ERGen(gen, n, p), ERGen(), n);\n    boost::write_graphml(cout, g, dp, true);\n\n    return 0;\n}", "meta": {"hexsha": "42332c61400255e29dbfe03b59c340aff7578a87", "size": 976, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "generate_graph.cpp", "max_stars_repo_name": "phisco/advance_algorithms_project", "max_stars_repo_head_hexsha": "2961959cf6036ed4c85d479dd14389315df55ee1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-07-04T13:46:31.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-28T16:42:31.000Z", "max_issues_repo_path": "generate_graph.cpp", "max_issues_repo_name": "phisco/advance_algorithms_project", "max_issues_repo_head_hexsha": "2961959cf6036ed4c85d479dd14389315df55ee1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "generate_graph.cpp", "max_forks_repo_name": "phisco/advance_algorithms_project", "max_forks_repo_head_hexsha": "2961959cf6036ed4c85d479dd14389315df55ee1", "max_forks_repo_licenses": ["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.5757575758, "max_line_length": 132, "alphanum_fraction": 0.6741803279, "num_tokens": 278, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.47810770470287695}}
{"text": "/*\n * This file is part of the Interpolated Polyline (https://github.com/fzi-forschungszentrum-informatik/P3IV),\n * copyright by FZI Forschungszentrum Informatik, licensed under the BSD-3 license (see LICENSE file in main directory)\n */\n\n#pragma once\n#include <iostream>\n#include <Eigen/Core>\n\nnamespace util_probability {\n\n\ntemplate <typename T, int DistributionDim>\nstruct NormalDistributionSequence {\n    using Mean = Eigen::Matrix<T, Eigen::Dynamic, DistributionDim>;\n    using Covariance = Eigen::Matrix<T, Eigen::Dynamic, DistributionDim>;\n\n\n    NormalDistributionSequence() = default;\n\n    NormalDistributionSequence(const Eigen::Ref<const Mean>& mean_, const Eigen::Ref<const Covariance>& covariance_)\n            : _mean{mean_}, _covariance{covariance_} {\n    }\n\n    NormalDistributionSequence(const Eigen::Ref<const Mean>& mean_, Eigen::Matrix<T, Eigen::Dynamic, 1>& variance_)\n            : _mean{mean_}, _covariance{Covariance::Zero()} {\n\n        for (size_t i = 0; i < variance_.size(); i++) {\n            _covariance(i, i) = variance_(i);\n        }\n    }\n\n    NormalDistributionSequence(std::vector<T> mean_, std::vector<T> covariance_) {\n        _mean = Eigen::Map<Mean, Eigen::Unaligned>(mean_.data(), mean_.size() / DistributionDim, DistributionDim);\n        _covariance = Eigen::Map<Covariance, Eigen::Unaligned>(\n            covariance_.data(), covariance_.size() / DistributionDim, DistributionDim);\n    };\n\n    size_t dimension() const {\n        return static_cast<size_t>(_mean.size() / DistributionDim);\n    }\n\n    void setMean(std::vector<T> mean_) {\n        _mean = Eigen::Map<Mean, Eigen::Unaligned>(mean_.data(), mean_.size() / DistributionDim, DistributionDim);\n    }\n\n    void setCovariance(std::vector<T> covariance_) {\n        _covariance = Eigen::Map<Mean, Eigen::Unaligned>(\n            covariance_.data(), covariance_.size() / DistributionDim, DistributionDim);\n    }\n\n    Mean mean() const {\n        return _mean;\n    }\n\n    Covariance covariance() const {\n        return _covariance;\n    }\n\n    std::vector<T> meanVec() {\n        std::vector<T> mean(_mean.data(), _mean.data() + _mean.rows() * _mean.cols());\n        return mean;\n    }\n\n    T covariance(size_t r, size_t c) const {\n        return _covariance(r, c);\n    }\n\n\nprotected:\n    Mean _mean;\n    Covariance _covariance;\n};\n\n\ntemplate <typename T>\nstruct UnivariateNormalDistributionSequence : NormalDistributionSequence<T, 1> {\n    using Mean = Eigen::Matrix<T, Eigen::Dynamic, 1>;\n    using Covariance = Eigen::Matrix<T, Eigen::Dynamic, 1>;\n\n    using NormalDistributionSequence<T, 1>::NormalDistributionSequence;\n\n    using NormalDistributionSequence<T, 1>::mean;\n    using NormalDistributionSequence<T, 1>::covariance;\n\n    T mean(size_t e) const {\n        return this->_mean(e, 0);\n    }\n\n    T covariance(size_t e) const {\n        return this->_covariance(e, 0);\n    }\n};\n\n\ntemplate <typename T>\nstruct BivariateNormalDistributionSequence : NormalDistributionSequence<T, 2> {\n    using Mean = Eigen::Matrix<T, Eigen::Dynamic, 2>;\n    using Covariance = Eigen::Matrix<T, Eigen::Dynamic, 4>;\n\n    using NormalDistributionSequence<T, 2>::NormalDistributionSequence;\n\n    BivariateNormalDistributionSequence(const Eigen::Ref<const Mean>& mean_,\n                                        Eigen::Matrix<T, Eigen::Dynamic, 1>& variance_)\n            : NormalDistributionSequence<T, 2>(mean_, Covariance::Zero()) {\n\n        for (size_t i = 0; i < this->dimension(); i++) {\n            this->_covariance(i, 0) = variance_(i);\n            this->_covariance(i, 3) = variance_(i);\n        }\n    }\n\n    using NormalDistributionSequence<T, 2>::mean;\n    using NormalDistributionSequence<T, 2>::covariance;\n\n    T mean(size_t e, size_t c) const {\n        return this->_mean(e, c);\n    }\n\n    T covariance(size_t e, size_t c) const {\n        return this->_covariance(e, c);\n    }\n\n    virtual Eigen::Matrix<T, Eigen::Dynamic, 2> variance() const {\n        Eigen::Matrix<T, Eigen::Dynamic, 2> variance;\n        for (size_t i = 0; i < this->dimension(); i++) {\n            variance(i, 0) = this->_covariance(i, 0);\n            variance(i, 1) = this->_covariance(i, 3);\n        }\n        return variance;\n    }\n};\n\n\n} // namespace util_probability", "meta": {"hexsha": "97fbbaf2318a613482766290705b90149fde78fc", "size": 4226, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "p3iv_utils_probability/include/p3iv_utils_probability/sequence_distribution.hpp", "max_stars_repo_name": "fzi-forschungszentrum-informatik/P3IV", "max_stars_repo_head_hexsha": "51784e6dc03dcaa0ad58a5078475fa4daec774bd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-07-27T06:56:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T11:21:30.000Z", "max_issues_repo_path": "p3iv_utils_probability/include/p3iv_utils_probability/sequence_distribution.hpp", "max_issues_repo_name": "fzi-forschungszentrum-informatik/P3IV", "max_issues_repo_head_hexsha": "51784e6dc03dcaa0ad58a5078475fa4daec774bd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "p3iv_utils_probability/include/p3iv_utils_probability/sequence_distribution.hpp", "max_forks_repo_name": "fzi-forschungszentrum-informatik/P3IV", "max_forks_repo_head_hexsha": "51784e6dc03dcaa0ad58a5078475fa4daec774bd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-10-10T01:56:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-10T01:56:44.000Z", "avg_line_length": 31.3037037037, "max_line_length": 119, "alphanum_fraction": 0.6441079035, "num_tokens": 1047, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.47806032672960863}}
{"text": "//\n// This file is part of\n//\n// CTBignum \t\n//\n// C++ Library for Compile-Time and Run-Time Multi-Precision and Modular Arithmetic\n// \n//\n// This file is distributed under the Apache License, Version 2.0. See the LICENSE\n// file for details.\n\n#include <NTL/ZZ.h>\n#include <NTL/ZZ_p.h>\n#include <benchmark/benchmark.h>\n#include <random>\n\n#include <ctbignum/ctbignum.hpp>\n#include <ctbignum/bigint.hpp>\n#include <ctbignum/mult.hpp>\n#include <ctbignum/mod_exp.hpp>\n#include <gmp.h>\n\n\ntemplate <size_t Len>\nstatic void mul_gmp(benchmark::State &state) {\n\n  using namespace cbn;\n\n  size_t total_sz = 2 * Len  * 1000;\n\n  std::vector<uint64_t> data(total_sz);\n  std::default_random_engine generator;\n  std::uniform_int_distribution<uint64_t> distribution(0);\n  for (auto& limb : data)\n    limb = distribution(generator);\n\n  size_t i = 0;\n  auto base_ptr = reinterpret_cast<mp_limb_t*>(data.data());\n\n    \n  mp_limb_t result[2*Len];\n\n  for (auto _ : state) {\n\n    mpn_mul(result, base_ptr + i, Len, base_ptr + i + Len, Len);\n    benchmark::DoNotOptimize(result);\n\n    i += 2 * Len;\n    if (i == total_sz)\n     i = 0;\n  }\n}\n\n\n\n\ntemplate <size_t Len>\nstatic void mul_cbn(benchmark::State &state) {\n\n  using namespace cbn;\n\n  size_t total_sz = 2* Len  * 1000;\n\n  std::vector<uint64_t> data(total_sz);\n  std::default_random_engine generator;\n  std::uniform_int_distribution<uint64_t> distribution(0);\n  for (auto& limb : data)\n    limb = distribution(generator);\n\n  size_t i = 0;\n  auto base_ptr = data.data();\n\n\n  for (auto _ : state) {\n\n    auto x = reinterpret_cast<big_int<Len>*>(base_ptr + i);\n    auto y = reinterpret_cast<big_int<Len>*>(base_ptr + i + Len);\n    auto j = cbn::mul(*x, *y);\n    benchmark::DoNotOptimize(j);\n\n    i += 2 * Len;\n    if (i == total_sz)\n     i = 0;\n  }\n}\n\n/*\ntemplate <size_t Len>\nstatic void mul_cbn(benchmark::State &state) {\n\n  using namespace cbn;\n  std::default_random_engine generator;\n  std::uniform_int_distribution<uint64_t> distribution(0);\n\n  big_int<Len> x;\n  big_int<Len> y;\n  for (int i = 0; i < Len; ++i) {\n    x[i] = distribution(generator);\n    y[i] = distribution(generator);\n  }\n\n  for (auto _ : state) {\n    auto k = cbn::mul(x, y);\n    benchmark::DoNotOptimize(k);\n  }\n}\n*/\n\ntemplate <size_t Len>\nstatic void mul_ntl(benchmark::State &state) {\n\n  using NTL::ZZ;\n  using NTL::ZZ_p;\n  using NTL::conv;\n\n  auto x = NTL::RandomBits_ZZ(Len*64);\n  auto y = NTL::RandomBits_ZZ(Len*64);\n  ZZ z;\n\n  for (auto _ : state) {\n    mul(z, x, y);\n    benchmark::DoNotOptimize(z);\n  }\n}\n\n\nBENCHMARK_TEMPLATE(mul_cbn, 2);\nBENCHMARK_TEMPLATE(mul_ntl, 2);\nBENCHMARK_TEMPLATE(mul_gmp, 2);\n\nBENCHMARK_TEMPLATE(mul_cbn, 3);\nBENCHMARK_TEMPLATE(mul_ntl, 3);\nBENCHMARK_TEMPLATE(mul_gmp, 3);\n\nBENCHMARK_TEMPLATE(mul_cbn, 4);\nBENCHMARK_TEMPLATE(mul_ntl, 4);\nBENCHMARK_TEMPLATE(mul_gmp, 4);\n\nBENCHMARK_TEMPLATE(mul_cbn, 5);\nBENCHMARK_TEMPLATE(mul_ntl, 5);\nBENCHMARK_TEMPLATE(mul_gmp, 5);\n\nBENCHMARK_TEMPLATE(mul_cbn, 6);\nBENCHMARK_TEMPLATE(mul_ntl, 6);\nBENCHMARK_TEMPLATE(mul_gmp, 6);\n\nBENCHMARK_TEMPLATE(mul_cbn, 7);\nBENCHMARK_TEMPLATE(mul_ntl, 7);\nBENCHMARK_TEMPLATE(mul_gmp, 7);\n\nBENCHMARK_TEMPLATE(mul_cbn, 8);\nBENCHMARK_TEMPLATE(mul_ntl, 8);\nBENCHMARK_TEMPLATE(mul_gmp, 8);\n\n\nBENCHMARK_MAIN();\n", "meta": {"hexsha": "7acd8062dddfd5eda565b6066f75e056f7225b36", "size": 3213, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "benchmarks/src/bench-mul.cpp", "max_stars_repo_name": "itzmeanjan/ctbignum", "max_stars_repo_head_hexsha": "c4a0ff43a8e6f1c9fecdba69e98f954d36c1d29e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 92.0, "max_stars_repo_stars_event_min_datetime": "2018-04-23T07:50:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T19:08:50.000Z", "max_issues_repo_path": "benchmarks/src/bench-mul.cpp", "max_issues_repo_name": "itzmeanjan/ctbignum", "max_issues_repo_head_hexsha": "c4a0ff43a8e6f1c9fecdba69e98f954d36c1d29e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2018-04-11T20:01:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-29T09:40:22.000Z", "max_forks_repo_path": "benchmarks/src/bench-mul.cpp", "max_forks_repo_name": "itzmeanjan/ctbignum", "max_forks_repo_head_hexsha": "c4a0ff43a8e6f1c9fecdba69e98f954d36c1d29e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2018-06-28T06:39:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-22T15:52:03.000Z", "avg_line_length": 20.4649681529, "max_line_length": 83, "alphanum_fraction": 0.6850295674, "num_tokens": 998, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.4780356432825999}}
{"text": "#ifndef STAN_MATH_PRIM_SCAL_PROB_EXPONENTIAL_RNG_HPP\n#define STAN_MATH_PRIM_SCAL_PROB_EXPONENTIAL_RNG_HPP\n\n#include <stan/math/prim/scal/err/check_consistent_sizes.hpp>\n#include <stan/math/prim/scal/err/check_nonnegative.hpp>\n#include <stan/math/prim/scal/err/check_not_nan.hpp>\n#include <stan/math/prim/scal/err/check_positive_finite.hpp>\n#include <stan/math/prim/scal/fun/value_of.hpp>\n#include <stan/math/prim/scal/meta/length.hpp>\n#include <stan/math/prim/scal/meta/VectorBuilder.hpp>\n#include <stan/math/prim/scal/meta/return_type.hpp>\n#include <stan/math/prim/scal/fun/constants.hpp>\n#include <stan/math/prim/scal/meta/include_summand.hpp>\n#include <boost/random/exponential_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n\nnamespace stan {\n  namespace math {\n\n    template <class RNG>\n    inline double\n    exponential_rng(double beta,\n                    RNG& rng) {\n      using boost::variate_generator;\n      using boost::exponential_distribution;\n\n      static const char* function(\"exponential_rng\");\n\n      check_positive_finite(function, \"Inverse scale parameter\", beta);\n\n      variate_generator<RNG&, exponential_distribution<> >\n        exp_rng(rng, exponential_distribution<>(beta));\n      return exp_rng();\n    }\n\n  }\n}\n#endif\n", "meta": {"hexsha": "cd2fce6ded115af7bbb8949b9f0c451fc8883b76", "size": 1262, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/scal/prob/exponential_rng.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/prim/scal/prob/exponential_rng.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/prim/scal/prob/exponential_rng.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": 32.358974359, "max_line_length": 71, "alphanum_fraction": 0.7527733756, "num_tokens": 299, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.4780356432825999}}
{"text": "#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE COMPUTE\n\n#include <boost/test/unit_test.hpp>\n\n#include \"api/umo.hpp\"\n\n#include <cmath>\n#include <vector>\n#include <algorithm>\n\nusing namespace umo;\n\nBOOST_AUTO_TEST_CASE(FloatCompute) {\n    Model model;\n    FloatExpression dec1 = model.floatVar(0.0, 10.0);\n    FloatExpression dec2 = model.floatVar(0.0, 10.0);\n    FloatExpression x01 = dec1 + dec2;\n    FloatExpression x02 = dec1 - dec2;\n    FloatExpression x03 = dec1 * dec2;\n    FloatExpression x04 = dec1 / dec2;\n    FloatExpression x05 = -dec1;\n    for (double val1 : {5.0, -4.0, 2.5}) {\n        for (double val2 : {-7.0, 2.0, 1.3}) {\n            dec1.setValue(val1);\n            dec2.setValue(val2);\n            BOOST_CHECK_EQUAL(x01.getValue(), val1 + val2);\n            BOOST_CHECK_EQUAL(x02.getValue(), val1 - val2);\n            BOOST_CHECK_EQUAL(x03.getValue(), val1 * val2);\n            BOOST_CHECK_EQUAL(x04.getValue(), val1 / val2);\n            BOOST_CHECK_EQUAL(x05.getValue(), -val1);\n        }\n    }\n    model.check();\n}\n\nBOOST_AUTO_TEST_CASE(IntCompute) {\n    Model model;\n    IntExpression dec1 = model.intVar(0, 10);\n    IntExpression dec2 = model.intVar(0, 10);\n    IntExpression x01 = dec1 + dec2;\n    IntExpression x02 = dec1 - dec2;\n    IntExpression x03 = dec1 * dec2;\n    IntExpression x04 = dec1 / dec2;\n    IntExpression x05 = dec1 % dec2;\n    IntExpression x06 = -dec1;\n    for (long long val1 : {5, -4, 0}) {\n        for (long long val2 : {-7, 2}) {\n            dec1.setValue(val1);\n            dec2.setValue(val2);\n            BOOST_CHECK_EQUAL(x01.getValue(), val1 + val2);\n            BOOST_CHECK_EQUAL(x02.getValue(), val1 - val2);\n            BOOST_CHECK_EQUAL(x03.getValue(), val1 * val2);\n            BOOST_CHECK_EQUAL(x04.getValue(), val1 / val2);\n            BOOST_CHECK_EQUAL(x05.getValue(), val1 % val2);\n            BOOST_CHECK_EQUAL(x06.getValue(), -val1);\n        }\n    }\n    model.check();\n}\n\nBOOST_AUTO_TEST_CASE(BoolCompute) {\n    Model model;\n    BoolExpression dec1 = model.boolVar();\n    BoolExpression dec2 = model.boolVar();\n    BoolExpression x01 = dec1 && dec2;\n    BoolExpression x02 = dec1 || dec2;\n    BoolExpression x03 = dec1 && !dec2;\n    BoolExpression x04 = !dec1 || dec2;\n    BoolExpression x05 = !(dec1 || dec2);\n    BoolExpression x06 = !(dec1 && dec2);\n    BoolExpression x07 = !dec1;\n    for (bool val1 : {false, true}) {\n        for (bool val2 : {false, true}) {\n            dec1.setValue(val1);\n            dec2.setValue(val2);\n            BOOST_CHECK_EQUAL(x01.getValue(), val1 && val2);\n            BOOST_CHECK_EQUAL(x02.getValue(), val1 || val2);\n            BOOST_CHECK_EQUAL(x03.getValue(), val1 && !val2);\n            BOOST_CHECK_EQUAL(x04.getValue(), !val1 || val2);\n            BOOST_CHECK_EQUAL(x05.getValue(), !(val1 || val2));\n            BOOST_CHECK_EQUAL(x06.getValue(), !(val1 && val2));\n            BOOST_CHECK_EQUAL(x07.getValue(), !val1);\n        }\n    }\n    model.check();\n}\n\nBOOST_AUTO_TEST_CASE(Operations) {\n    Model model;\n    FloatExpression dec = model.floatVar(-10.0, 10.0);\n    FloatExpression x01 = umo::exp(dec);\n    FloatExpression x02 = umo::cos(dec);\n    FloatExpression x03 = umo::atan(dec);\n    for (double val : {5.0, -4.0, 2.5}) {\n        dec.setValue(val);\n        BOOST_CHECK_EQUAL(x01.getValue(), std::exp(val));\n        BOOST_CHECK_EQUAL(x02.getValue(), std::cos(val));\n        BOOST_CHECK_EQUAL(x03.getValue(), std::atan(val));\n    }\n    model.check();\n}\n\nBOOST_AUTO_TEST_CASE(Comparisons) {\n    Model model;\n    FloatExpression dec1 = model.floatVar(0.0, 10.0);\n    FloatExpression dec2 = model.floatVar(0.0, 10.0);\n    BoolExpression x01 = dec1 == dec2;\n    BoolExpression x02 = dec1 != dec2;\n    BoolExpression x03 = dec1 <= dec2;\n    BoolExpression x04 = dec1 >= dec2;\n    BoolExpression x05 = dec1 < dec2;\n    BoolExpression x06 = dec1 > dec2;\n\n    // Should compare equal\n    dec1.setValue(1.0 - 1e-7);\n    dec2.setValue(1.0);\n    BOOST_CHECK_EQUAL(x01.getValue(), true);  // ==\n    BOOST_CHECK_EQUAL(x02.getValue(), false); // !=\n    BOOST_CHECK_EQUAL(x03.getValue(), true);  // <=\n    BOOST_CHECK_EQUAL(x04.getValue(), true);  // >=\n    BOOST_CHECK_EQUAL(x05.getValue(), false); // <\n    BOOST_CHECK_EQUAL(x06.getValue(), false); // >\n\n    // Should compare different\n    dec1.setValue(1.0 - 1e-5);\n    dec2.setValue(1.0);\n    BOOST_CHECK_EQUAL(x01.getValue(), false); // ==\n    BOOST_CHECK_EQUAL(x02.getValue(), true);  // !=\n    BOOST_CHECK_EQUAL(x03.getValue(), true);  // <=\n    BOOST_CHECK_EQUAL(x04.getValue(), false); // >=\n    BOOST_CHECK_EQUAL(x05.getValue(), true);  // <\n    BOOST_CHECK_EQUAL(x06.getValue(), false); // >\n\n    // Should compare equal\n    dec1.setValue(1e-9);\n    dec2.setValue(0.0);\n    BOOST_CHECK_EQUAL(x01.getValue(), true);  // ==\n    BOOST_CHECK_EQUAL(x02.getValue(), false); // !=\n    BOOST_CHECK_EQUAL(x03.getValue(), true);  // <=\n    BOOST_CHECK_EQUAL(x04.getValue(), true);  // >=\n    BOOST_CHECK_EQUAL(x05.getValue(), false); // <\n    BOOST_CHECK_EQUAL(x06.getValue(), false); // >\n\n    // Should compare different\n    dec1.setValue(1e-7);\n    dec2.setValue(0.0);\n    BOOST_CHECK_EQUAL(x01.getValue(), false); // ==\n    BOOST_CHECK_EQUAL(x02.getValue(), true);  // !=\n    BOOST_CHECK_EQUAL(x03.getValue(), false); // <=\n    BOOST_CHECK_EQUAL(x04.getValue(), true);  // >=\n    BOOST_CHECK_EQUAL(x05.getValue(), false); // <\n    BOOST_CHECK_EQUAL(x06.getValue(), true);  // >\n\n    // Should compare different\n    dec1.setValue(1e-5);\n    dec2.setValue(0.0);\n    BOOST_CHECK_EQUAL(x01.getValue(), false); // ==\n    BOOST_CHECK_EQUAL(x02.getValue(), true);  // !=\n    BOOST_CHECK_EQUAL(x03.getValue(), false); // <=\n    BOOST_CHECK_EQUAL(x04.getValue(), true);  // >=\n    BOOST_CHECK_EQUAL(x05.getValue(), false); // <\n    BOOST_CHECK_EQUAL(x06.getValue(), true);  // >\n\n    // Just for directions\n    dec1.setValue(1.0);\n    dec2.setValue(2.0);\n    BOOST_CHECK_EQUAL(x03.getValue(), true);  // <=\n    BOOST_CHECK_EQUAL(x04.getValue(), false); // >=\n    BOOST_CHECK_EQUAL(x05.getValue(), true);  // <\n    BOOST_CHECK_EQUAL(x06.getValue(), false); // >\n    dec1.setValue(2.0);\n    dec2.setValue(1.0);\n    BOOST_CHECK_EQUAL(x03.getValue(), false); // <=\n    BOOST_CHECK_EQUAL(x04.getValue(), true);  // >=\n    BOOST_CHECK_EQUAL(x05.getValue(), false); // <\n    BOOST_CHECK_EQUAL(x06.getValue(), true);  // >\n\n    model.check();\n}\n\nBOOST_AUTO_TEST_CASE(ModelStatus) {\n    Model model;\n    BoolExpression dec = model.boolVar();\n    constraint(dec);\n    dec.setValue(false);\n    BOOST_CHECK(model.getStatus() == Status::Invalid);\n    dec.setValue(true);\n    BOOST_CHECK(model.getStatus() == Status::Valid);\n}\n\nBOOST_AUTO_TEST_CASE(IntNary) {\n    Model model;\n    IntExpression dec1 = model.intVar();\n    IntExpression dec2 = model.intVar();\n    IntExpression dec3 = model.intVar();\n    std::vector<IntExpression> vec{dec1, dec2, dec3};\n    IntExpression x01 = sum(vec);\n    IntExpression x02 = prod(vec);\n    IntExpression x03 = min(vec);\n    IntExpression x04 = max(vec);\n    for (long long val1 : {5, -4, 0}) {\n        for (long long val2 : {-7, 2, 8}) {\n            for (long long val3 : {-17, -5, 0, 4}) {\n                dec1.setValue(val1);\n                dec2.setValue(val2);\n                dec3.setValue(val3);\n                std::vector<long long> vals{val1, val2, val3};\n                BOOST_CHECK_EQUAL(x01.getValue(), val1 + val2 + val3);\n                BOOST_CHECK_EQUAL(x02.getValue(), val1 * val2 * val3);\n                BOOST_CHECK_EQUAL(x03.getValue(), *std::min_element(vals.begin(), vals.end()));\n                BOOST_CHECK_EQUAL(x04.getValue(), *std::max_element(vals.begin(), vals.end()));\n            }\n        }\n    }\n    model.check();\n}\n\nBOOST_AUTO_TEST_CASE(BoolNary) {\n    Model model;\n    BoolExpression dec1 = model.boolVar();\n    BoolExpression dec2 = model.boolVar();\n    BoolExpression dec3 = model.boolVar();\n    std::vector<BoolExpression> vec{dec1, dec2, dec3};\n    BoolExpression x01 = logical_or(vec);\n    BoolExpression x02 = logical_and(vec);\n    BoolExpression x03 = logical_xor(vec);\n    for (long long val1 : {false, true}) {\n        for (long long val2 : {false, true}) {\n            for (long long val3 : {false, true}) {\n                dec1.setValue(val1);\n                dec2.setValue(val2);\n                dec3.setValue(val3);\n                BOOST_CHECK_EQUAL(x01.getValue(), val1 || val2 || val3);\n                BOOST_CHECK_EQUAL(x02.getValue(), val1 && val2 && val3);\n                BOOST_CHECK_EQUAL(x03.getValue(), val1 ^ val2 ^ val3);\n            }\n        }\n    }\n    model.check();\n}\n", "meta": {"hexsha": "8a60af9cab65612675477cc4cc8f2a42a941a370", "size": 8603, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/compute.cpp", "max_stars_repo_name": "Coloquinte/umo", "max_stars_repo_head_hexsha": "1f39c316d6584bbed22913aabaa4bfb5ee02d72b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-24T20:56:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-24T20:56:25.000Z", "max_issues_repo_path": "test/compute.cpp", "max_issues_repo_name": "Coloquinte/umo", "max_issues_repo_head_hexsha": "1f39c316d6584bbed22913aabaa4bfb5ee02d72b", "max_issues_repo_licenses": ["MIT"], "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/compute.cpp", "max_forks_repo_name": "Coloquinte/umo", "max_forks_repo_head_hexsha": "1f39c316d6584bbed22913aabaa4bfb5ee02d72b", "max_forks_repo_licenses": ["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.5495867769, "max_line_length": 95, "alphanum_fraction": 0.6068813205, "num_tokens": 2294, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.4780356432825999}}
{"text": "#include <boost/math/distributions/poisson.hpp>\r\n#include <iostream>\r\n\r\n// C++17 allows us to omit tail template parameters.\r\ntemplate<template<class>class T, typename... U>\r\nauto f(double q, U&&... params) {\r\n    T<double> dist(params...);\r\n    return boost::math::quantile(dist, q);\r\n}\r\n\r\n// C++14 requires all explicit template parameters.\r\ntemplate<template<class,class>class T, typename... U>\r\nauto g(double q, U&&... params) {\r\n    T<double, boost::math::policies::policy<>> dist(params...);\r\n    return boost::math::quantile(dist, q);\r\n}\r\n\r\nvoid compilationError(void) {\r\n//  This may cause error message which is hard to understand.\r\n//  int policy = 0;\r\n    using namespace boost::math::policies;\r\n//  This \"policy\" is namespace boost::math::policies::policy, not a local variable.\r\n    boost::math::poisson_distribution<double, policy<discrete_quantile<integer_round_up>>> dist;\r\n}\r\n\r\nint main(int argc, char* argv[]) {\r\n    using namespace boost::math;\r\n    std::cout << f<boost::math::poisson_distribution>(0.9, 2.5) << \"\\n\";\r\n    std::cout << g<boost::math::poisson_distribution>(0.9, 2.5) << \"\\n\";\r\n    return 0;\r\n}\r\n\r\n/*\r\nLocal Variables:\r\nmode: c++\r\ncoding: utf-8-dos\r\ntab-width: nil\r\nc-file-style: \"stroustrup\"\r\nEnd:\r\n*/\r\n", "meta": {"hexsha": "01bc7dcb075e3f846df733e9fdf0866b8cbd0339", "size": 1239, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "template_params/template_params.cpp", "max_stars_repo_name": "zettsu-t/cPlusPlusFriend", "max_stars_repo_head_hexsha": "5399065abe2c0eda2b9aec26e6435d8c27cda9cd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2017-04-15T00:05:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-10T05:11:14.000Z", "max_issues_repo_path": "template_params/template_params.cpp", "max_issues_repo_name": "zettsu-t/cPlusPlusFriend", "max_issues_repo_head_hexsha": "5399065abe2c0eda2b9aec26e6435d8c27cda9cd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "template_params/template_params.cpp", "max_forks_repo_name": "zettsu-t/cPlusPlusFriend", "max_forks_repo_head_hexsha": "5399065abe2c0eda2b9aec26e6435d8c27cda9cd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-02-23T22:47:08.000Z", "max_forks_repo_forks_event_max_datetime": "2018-02-23T22:47:08.000Z", "avg_line_length": 30.2195121951, "max_line_length": 97, "alphanum_fraction": 0.6569814366, "num_tokens": 330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.6261241702517975, "lm_q1q2_score": 0.47803563795615084}}
{"text": "// Copyright (c) 2021 Stig Rune Sellevag\n//\n// This file is distributed under the MIT License. See the accompanying file\n// LICENSE.txt or http://www.opensource.org/licenses/mit-license.php for terms\n// and conditions.\n\n#ifdef _MSC_VER\n#pragma warning(push)\n#pragma warning(disable : 4305)\n#pragma warning(disable : 5054)\n#endif\n\n#include <scilib/mdarray.h>\n#include <scilib/linalg.h>\n#include <chrono>\n#include <iostream>\n#include <Eigen/Dense>\n\nusing Timer = std::chrono::duration<double, std::milli>;\n\nvoid print(int n, const Timer& t_eigen, const Timer& t_sci)\n{\n    std::cout << \"Eigenvalues for symmetric matrix:\\n\"\n              << \"---------------------------------\\n\"\n              << \"size =      \" << n << \" x \" << n << '\\n'\n              << \"sci/eigen = \" << t_sci.count() / t_eigen.count() << \"\\n\\n\";\n}\n\nvoid benchmark(int n)\n{\n    using namespace Sci;\n    using namespace Sci::Linalg;\n\n    Eigen::MatrixXd a1 = Eigen::MatrixXd::Random(n, n);\n    Eigen::MatrixXd a2 = a1 + a1.transpose();\n    Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es;\n    auto t1 = std::chrono::high_resolution_clock::now();\n    es.compute(a2);\n    auto t2 = std::chrono::high_resolution_clock::now();\n    Timer t_eigen = t2 - t1;\n\n    Matrix<double> b1 = randu<Matrix<double>>(n, n);\n    Matrix<double> b1_t = b1;\n    Matrix<double> b2(n, n);\n    matrix_product(transposed(b1_t.view()), b1.view(), b2.view());\n    Vector<double> wr(n);\n    t1 = std::chrono::high_resolution_clock::now();\n    eigs(b2.view(), wr.view());\n    t2 = std::chrono::high_resolution_clock::now();\n    Timer t_sci = t2 - t1;\n\n    print(n, t_eigen, t_sci);\n}\n\nint main()\n{\n    int n = 10;\n    benchmark(n);\n\n    n = 100;\n    benchmark(n);\n\n    n = 500;\n    benchmark(n);\n}\n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n", "meta": {"hexsha": "a2157bfe786473c2d8458a056b0162c055d64d81", "size": 1781, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bench/bench_eigs.cpp", "max_stars_repo_name": "stigrs/scilib", "max_stars_repo_head_hexsha": "c49f1f882bf2031a4de537e0f5701b2648af181f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bench/bench_eigs.cpp", "max_issues_repo_name": "stigrs/scilib", "max_issues_repo_head_hexsha": "c49f1f882bf2031a4de537e0f5701b2648af181f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bench/bench_eigs.cpp", "max_forks_repo_name": "stigrs/scilib", "max_forks_repo_head_hexsha": "c49f1f882bf2031a4de537e0f5701b2648af181f", "max_forks_repo_licenses": ["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.4428571429, "max_line_length": 78, "alphanum_fraction": 0.6148231331, "num_tokens": 496, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911057, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.47803562589061055}}
{"text": "#include <boost/test/minimal.hpp>\n#include <ctime>\n\n#include \"./suffix_array.hpp\"\n#include \"./utils.hpp\"\n\nusing namespace std;\n\n// SuffixArray O(nlogn^2)\n#define REP(i,n) for(int i=0; i<(int)(n) ; i++)\nstruct SAComp{\n\tint h;\n\tconst vector<int> &g;\n\tSAComp(int h, vector<int> &g):h(h),g(g){}\n\tbool operator()(int a,int b){\n\t\treturn a == b ? false : g[a] != g[b] ? g[a] < g[b] : g[a + h] < g[b + h];\n\t}\n};\n\nvector<int> SuffixArray(const string &str){\n\tint n = str.size();\n\tvector<int> sa(n+1),g(n+1),b(n+1);\n\tREP(i,n+1)sa[i] = i,g[i] = str[i];\n\tb[0] = b[n] = 0;\n\tSAComp comp(0,g);\n\tsort(sa.begin(),sa.end(),comp);\n\tfor(comp.h = 1; b[n] != n; comp.h *= 2) {\n\t\tsort(sa.begin(),sa.end(),comp);\n\t\tREP(i,n)b[i+1] = b[i] + comp(sa[i], sa[i+1]);\n\t\tREP(i,n+1)g[sa[i]] = b[i];\n\t}\n\treturn sa;\n}\n// HeightArray O(n)\nvector<int> HeightArray(const string &str, const vector<int> &sa){\n\tint n = str.size(),h = 0;\n\tvector<int> ha(n+1),b(n+1);\n\tREP(i,n+1)b[sa[i]] = i;\n\tREP(i,n+1){\n\t\tif (b[i]){\n\t\t\tfor (int j=sa[b[i]-1]; j+h<n && i+h<n && str[j+h]==str[i+h]; ++h);\n\t\t\tha[b[i]] = h;\n\t\t}else ha[b[i]] = -1;\n\t\tif(h>0)--h;\n\t}\n\treturn ha;\n}\n\nvector<int> create_vector(int arr[], int len){\n    return vector<int>(arr, arr+len);\n}\n\nvoid test_create_suffix_array_from_string(){\n    string data[] = {\"mmiissiissippi\", \"abracadabra\"};\n    vector<int> expected[] = {\n          create_vector((int[]){14,13,2,6,10,3,7,1,0,12,11,5,9,4,8}, 15)\n        , create_vector((int[]){11,10,7,0,3,5,8,1,4,6,9,2}, 12)\n    };\n    for(int i=0 ; i<2 ; i++){\n        vector<int> actual = sasa::create_suffix_array_from_string(data[i]);\n        BOOST_CHECK(actual.size() == expected[i].size());\n        for(int j=0 ; j<(int)actual.size() ; j++){\n            BOOST_CHECK(actual[j] == expected[i][j]);\n        }\n    }\n}\n\nvoid test_construction_speed(){\n    int n = 5000000;\n    string str = \"\";\n    for(int i=0 ; i<n ; i++){\n        str += rand() % 2 ? 'a' : 'b';\n    }\n    clock_t start,end;\n    start = clock();\n    sasa::create_suffix_array_from_string(str);\n    end = clock();\n\n    double sais_time = (double)(end - start)/CLOCKS_PER_SEC;\n\n    start = clock();\n    SuffixArray(str);\n    end = clock();\n\n    double ls_time = (double)(end - start)/CLOCKS_PER_SEC;\n\n    cout << \"sais time: \" << sais_time << \" [s]\" << endl;\n    cout << \"ls time: \" << ls_time << \" [s]\" << endl;\n}\n\nint test_main(int argc, char* argv[]){\n    test_create_suffix_array_from_string();\n    test_construction_speed();\n    return 0;\n}\n", "meta": {"hexsha": "4efe44725e357042c30dab2ccc5e8e7a067ee4be", "size": 2462, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test.cpp", "max_stars_repo_name": "nel215/sasa", "max_stars_repo_head_hexsha": "37074f07dfec4f91e6f89ed79d9f9a52f61ce3dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-07-07T15:00:59.000Z", "max_stars_repo_stars_event_max_datetime": "2016-07-07T15:00:59.000Z", "max_issues_repo_path": "test.cpp", "max_issues_repo_name": "nel215/sasa", "max_issues_repo_head_hexsha": "37074f07dfec4f91e6f89ed79d9f9a52f61ce3dc", "max_issues_repo_licenses": ["MIT"], "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.cpp", "max_forks_repo_name": "nel215/sasa", "max_forks_repo_head_hexsha": "37074f07dfec4f91e6f89ed79d9f9a52f61ce3dc", "max_forks_repo_licenses": ["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.6458333333, "max_line_length": 76, "alphanum_fraction": 0.5560519903, "num_tokens": 839, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.4780034039818082}}
{"text": "#include <boost/integer/common_factor_rt.hpp>\n", "meta": {"hexsha": "db42167251803e464bc0a35ed6da19913747da3a", "size": 46, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_integer_common_factor_rt.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_integer_common_factor_rt.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_integer_common_factor_rt.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 23.0, "max_line_length": 45, "alphanum_fraction": 0.8260869565, "num_tokens": 10, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.4780034039818082}}
{"text": "#include <boost/timer/timer.hpp>\n#include <Eigen/Core>\n#include <iostream>\n#include <memory>\n\n#include <bayesclassifier.h>\n#include <knnclassifier.h>\n#include <naivebayesclassifier.h>\n\n#include \"tsv.h\"\n\nusing Eigen::MatrixXd;\nusing std::cout;\nusing std::make_unique;\nusing std::string;\nusing std::vector;\n\nvoid print(const Eigen::VectorXd& v) {\n    for (int i = 0; i < v.size(); ++i) {\n        if (i)\n            cout << \", \";\n        cout << v(i);\n    }\n}\n\nint main(int argc, char * argv[]) {\n    // parse arguments\n    if (argc != 3) {\n        cout << \"Usage: \" << argv[0] << \" file algorithm\\n\"\n             << \"Algorithm can be b, k or n:\\n\"\n             << \"    b -- Full Bayes classifier\\n\"\n             << \"    n -- Naive Bayes classifier\\n\"\n             << \"    k -- K Nearest Neighbors classifier with k=5\\n\";\n        return 1;\n    }\n    string filename = argv[1];\n    char algorithm = argv[2][0];\n\n    // load input data\n    ClassificationDataset tr = load_tsv(filename);\n    ClassificationDataset te;\n    unsigned n = tr.x.size();\n\n    // split into training and test data\n    unsigned n_tr = (unsigned)std::round(0.7 * (double)n);\n    unsigned n_te = n - n_tr;\n    te.x.insert(te.x.cbegin(), tr.x.cbegin() + n_tr, tr.x.cend());\n    te.y.insert(te.y.cbegin(), tr.y.cbegin() + n_tr, tr.y.cend());\n    tr.x.erase(tr.x.cbegin() + n_tr, tr.x.cend());\n    tr.y.erase(tr.y.cbegin() + n_tr, tr.y.cend());\n    cout << n << \" instances (\" << n_tr << \" training, \" << n_te << \" test)\\n\";\n\n    // train classifier\n    std::unique_ptr<Classifier> c;\n    if (algorithm == 'b') {\n        cout << \"Training Bayes classifier...\\n\";\n        boost::timer::auto_cpu_timer t;\n        c = make_unique<BayesClassifier>(tr.x, tr.y);\n    } else if (algorithm == 'k') {\n        cout << \"Training K Nearest Neighbors classifier...\\n\";\n        boost::timer::auto_cpu_timer t;\n        c = make_unique<KnnClassifier>(std::move(tr.x), std::move(tr.y), 5);\n    } else {\n        cout << \"Training Naive Bayes classifier...\\n\";\n        boost::timer::auto_cpu_timer t;\n        c = make_unique<NaiveBayesClassifier>(tr.x, tr.y);\n    }\n\n    // apply classifier to test data\n    Eigen::MatrixXd m = Eigen::MatrixXd::Zero(2,2);\n    {\n        cout << \"Predicting class labels...\\n\";\n        boost::timer::auto_cpu_timer t;\n        auto xi = te.x.cbegin();\n        auto yi = te.y.cbegin();\n        for (; xi != te.x.cend(); ++xi, ++yi)\n            ++m(c->predict(*xi), *yi);\n    }\n\n    double true_positive  = m(1,1);\n    double false_positive = m(1,0);\n    double true_negative  = m(0,0);\n    double false_negative = m(0,1);\n\n    double accuracy  = (true_positive + true_negative) /  (double)n_te;\n    double precision = true_positive / (true_positive + false_positive);\n    double recall    = true_positive / (true_positive + false_negative);\n\n    cout << \"Results:\\n\"\n         << \"    True positives:  \" << true_positive << \"\\n\"\n         << \"    False positives: \" << false_positive << \"\\n\"\n         << \"    True negatives:  \" << true_negative << \"\\n\"\n         << \"    False negatives: \" << false_negative << \"\\n\"\n         << \"    Accuracy:        \" << accuracy << \"\\n\"\n         << \"    Precision:       \" << precision << \"\\n\"\n         << \"    Recall:          \" << recall << \"\\n\";\n\n    return 0;\n}\n", "meta": {"hexsha": "934620b2509c0883d412403c7789f6050ce710ec", "size": 3273, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "classification/main.cpp", "max_stars_repo_name": "lfritz/data-mining-and-analysis", "max_stars_repo_head_hexsha": "f92aba784f2a8a0e8c02f6b8d3adf5bdf884fed7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "classification/main.cpp", "max_issues_repo_name": "lfritz/data-mining-and-analysis", "max_issues_repo_head_hexsha": "f92aba784f2a8a0e8c02f6b8d3adf5bdf884fed7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "classification/main.cpp", "max_forks_repo_name": "lfritz/data-mining-and-analysis", "max_forks_repo_head_hexsha": "f92aba784f2a8a0e8c02f6b8d3adf5bdf884fed7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-06T19:20:37.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-06T19:20:37.000Z", "avg_line_length": 32.73, "max_line_length": 79, "alphanum_fraction": 0.5493431103, "num_tokens": 898, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.4780034018683596}}
{"text": "#include \"benchmark.h\"\n\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n#include <chrono>\n#include <iostream>\n#include <cstdlib>\n#include <assert.h>\n\nvoid benchmark_Eigen(\n    const std::vector<std::string>& parameterNames,\n    const Json::Array& parameters,\n    const std::vector<std::string>& returnNames,\n    Json::Array& returnValues)\n{\n    //number of runs for time measures\n    const int runs = 10;\n\tconst int subruns = 2;\n\n    int numConfigs = parameters.Size();\n    for (int config = 0; config < numConfigs; ++config)\n    {\n        //Input\n        int gridSize = parameters[config][0].AsInt32();\n        double totalTime = 0;\n        std::cout << \"  Grid Size: \" << gridSize << std::flush;\n\t\tint matrixSize = gridSize * gridSize;\n\n\t\t//Create matrix\n#define IDX(x, y) ((y) + (x)*gridSize)\n\t\tEigen::SparseMatrix<float, Eigen::RowMajor> matrix(matrixSize, matrixSize);\n\t\tmatrix.reserve(Eigen::VectorXi::Constant(matrixSize, 5));\n\t\tfor (int x=0; x<gridSize; ++x) for (int y=0; y<gridSize; ++y)\n\t\t{\n\t\t\tint row = IDX(x, y);\n\t\t\tif (x > 0) matrix.insert(row, IDX(x - 1, y)) = -1;\n\t\t\tif (y > 0) matrix.insert(row, IDX(x, y - 1)) = -1;\n\t\t\tmatrix.insert(row, row) = 4;\n\t\t\tif (y < gridSize - 1) matrix.insert(row, IDX(x, y + 1)) = -1;\n\t\t\tif (x < gridSize - 1) matrix.insert(row, IDX(x + 1, y)) = -1;\n\t\t}\n\t\tmatrix.makeCompressed();\n\n\t\t//Create vector\n\t\tEigen::VectorXf x = Eigen::VectorXf::Random(matrixSize);\n\t\tEigen::VectorXf r(matrixSize);\n\n        //Run it multiple times\n        for (int run = 0; run < runs; ++run)\n        {\n            //Main logic\n            auto start = std::chrono::steady_clock::now();\n\n            //csrmv\n\t\t\tfor (int i = 0; i < subruns; ++i) {\n\t\t\t\tr.noalias() = matrix * x;\n\t\t\t}\n\n            auto finish = std::chrono::steady_clock::now();\n            double elapsed = std::chrono::duration_cast<\n                std::chrono::duration<double> >(finish - start).count() * 1000 / subruns;\n            totalTime += elapsed;\n        }\n\n        //Result\n        Json::Array result;\n        double finalTime = totalTime / runs;\n        result.PushBack(finalTime);\n        returnValues.PushBack(result);\n        std::cout << \" -> \" << finalTime << \"ms\" << std::endl;\n    }\n}\n", "meta": {"hexsha": "dccf8abfb366675d47825e9f71022aa62577fd43", "size": 2192, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "benchmarks/csrmv/Implementation_Eigen.cpp", "max_stars_repo_name": "chrismile/cuMat", "max_stars_repo_head_hexsha": "8bfe48393cc93aa4555c7b81b5b4f44c142b4ebb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2020-03-08T18:28:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T20:32:56.000Z", "max_issues_repo_path": "benchmarks/csrmv/Implementation_Eigen.cpp", "max_issues_repo_name": "chrismile/cuMat", "max_issues_repo_head_hexsha": "8bfe48393cc93aa4555c7b81b5b4f44c142b4ebb", "max_issues_repo_licenses": ["MIT"], "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/csrmv/Implementation_Eigen.cpp", "max_forks_repo_name": "chrismile/cuMat", "max_forks_repo_head_hexsha": "8bfe48393cc93aa4555c7b81b5b4f44c142b4ebb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-03-26T01:54:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-18T13:32:46.000Z", "avg_line_length": 30.0273972603, "max_line_length": 89, "alphanum_fraction": 0.5821167883, "num_tokens": 630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.47800339886244625}}
{"text": "\n#pragma once\n\n#include <Eigen/Dense>\n#include <pcl/point_types.h>\n#include <pcl/visualization/cloud_viewer.h>\n\n#include <string>\n\nusing namespace Eigen;\nusing namespace std;\n\nbool updateCosy(const boost::shared_ptr<pcl::visualization::PCLVisualizer>& viewer\n    ,const Matrix3f& R, string prefix=\"cosy\", float scale=1.0f);\n\nvoid addCosy(const boost::shared_ptr<pcl::visualization::PCLVisualizer>& viewer,\n    const Matrix3f& R, string prefix=\"cosy\", float scale=1.0f, int viewport=0);\n\n", "meta": {"hexsha": "0d79ad47f118e9d1a8c56fc4cdaa261e661d09fc", "size": 487, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/deprecated/pcl_helpers.hpp", "max_stars_repo_name": "jstraub/rtmf", "max_stars_repo_head_hexsha": "eb348987959f118e0a9056eb0eede6435eef8842", "max_stars_repo_licenses": ["MIT-feh"], "max_stars_count": 33.0, "max_stars_repo_stars_event_min_datetime": "2015-10-07T14:33:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T13:45:16.000Z", "max_issues_repo_path": "include/deprecated/pcl_helpers.hpp", "max_issues_repo_name": "jstraub/rtmf", "max_issues_repo_head_hexsha": "eb348987959f118e0a9056eb0eede6435eef8842", "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/deprecated/pcl_helpers.hpp", "max_forks_repo_name": "jstraub/rtmf", "max_forks_repo_head_hexsha": "eb348987959f118e0a9056eb0eede6435eef8842", "max_forks_repo_licenses": ["MIT-feh"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2015-10-19T20:44:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T08:30:12.000Z", "avg_line_length": 25.6315789474, "max_line_length": 82, "alphanum_fraction": 0.7535934292, "num_tokens": 129, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.478003391629636}}
{"text": "//=======================================================================\r\n// Copyright 1997, 1998, 1999, 2000 University of Notre Dame.\r\n// Authors: Andrew Lumsdaine, Lie-Quan Lee, Jeremy G. Siek\r\n//\r\n// Distributed under the Boost Software License, Version 1.0. (See\r\n// accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n//=======================================================================\r\n\r\n#include <boost/config.hpp>\r\n#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n#include <utility>\r\n#include <boost/graph/adjacency_list.hpp>\r\n#include <boost/graph/connected_components.hpp>\r\n\r\n/*\r\n\r\n  This example demonstrates the usage of the connected_components\r\n  algorithm on a undirected graph. The example graphs come from\r\n  \"Introduction to Algorithms\", Cormen, Leiserson, and Rivest p. 87\r\n  (though we number the vertices from zero instead of one).\r\n\r\n  Sample output:\r\n\r\n  Total number of components: 3\r\n  Vertex 0 is in component 0\r\n  Vertex 1 is in component 0\r\n  Vertex 2 is in component 1\r\n  Vertex 3 is in component 2\r\n  Vertex 4 is in component 0\r\n  Vertex 5 is in component 1\r\n\r\n */\r\n\r\nusing namespace std;\r\n\r\nint main(int , char* []) \r\n{\r\n  using namespace boost;\r\n  {\r\n    typedef adjacency_list <vecS, vecS, undirectedS> Graph;\r\n\r\n    Graph G;\r\n    add_edge(0, 1, G);\r\n    add_edge(1, 4, G);\r\n    add_edge(4, 0, G);\r\n    add_edge(2, 5, G);\r\n    \r\n    std::vector<int> component(num_vertices(G));\r\n    int num = connected_components(G, &component[0]);\r\n    \r\n    std::vector<int>::size_type i;\r\n    cout << \"Total number of components: \" << num << endl;\r\n    for (i = 0; i != component.size(); ++i)\r\n      cout << \"Vertex \" << i <<\" is in component \" << component[i] << endl;\r\n    cout << endl;\r\n  }\r\n  return 0;\r\n}\r\n\r\n", "meta": {"hexsha": "10626ff15b1cd9d82e00bdac65d20cb6a3a7db41", "size": 1790, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/graph/example/connected_components.cpp", "max_stars_repo_name": "zyiacas/boost-doc-zh", "max_stars_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 198.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T05:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:46:46.000Z", "max_issues_repo_path": "libs/graph/example/connected_components.cpp", "max_issues_repo_name": "sdfict/boost-doc-zh", "max_issues_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/graph/example/connected_components.cpp", "max_forks_repo_name": "sdfict/boost-doc-zh", "max_forks_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 28.4126984127, "max_line_length": 76, "alphanum_fraction": 0.5977653631, "num_tokens": 455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.478003391629636}}
{"text": "// Copyright Louis Dionne 2013-2016\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#include <boost/hana/and.hpp>\n#include <boost/hana/assert.hpp>\n#include <boost/hana/comparing.hpp>\n#include <boost/hana/div.hpp>\n#include <boost/hana/equal.hpp>\n#include <boost/hana/eval_if.hpp>\n#include <boost/hana/greater.hpp>\n#include <boost/hana/greater_equal.hpp>\n#include <boost/hana/if.hpp>\n#include <boost/hana/less.hpp>\n#include <boost/hana/less_equal.hpp>\n#include <boost/hana/max.hpp>\n#include <boost/hana/min.hpp>\n#include <boost/hana/minus.hpp>\n#include <boost/hana/mod.hpp>\n#include <boost/hana/mult.hpp>\n#include <boost/hana/negate.hpp>\n#include <boost/hana/not.hpp>\n#include <boost/hana/not_equal.hpp>\n#include <boost/hana/one.hpp>\n#include <boost/hana/or.hpp>\n#include <boost/hana/ordering.hpp>\n#include <boost/hana/plus.hpp>\n#include <boost/hana/power.hpp>\n#include <boost/hana/tuple.hpp>\n#include <boost/hana/while.hpp>\n#include <boost/hana/zero.hpp>\n\n#include <laws/base.hpp>\n#include <laws/comparable.hpp>\n#include <laws/euclidean_ring.hpp>\n#include <laws/group.hpp>\n#include <laws/logical.hpp>\n#include <laws/monoid.hpp>\n#include <laws/orderable.hpp>\n#include <support/cnumeric.hpp>\n#include <support/numeric.hpp>\n\n#include <cstdlib>\n#include <vector>\nnamespace hana = boost::hana;\n\n\nstruct invalid {\n    template <typename T>\n    operator T const() { std::abort(); }\n};\n\nint main() {\n    //////////////////////////////////////////////////////////////////////////\n    // Comparable\n    //////////////////////////////////////////////////////////////////////////\n    {\n        hana::test::_injection<0> f{};\n        auto x = numeric(1);\n        auto y = numeric(2);\n\n        // equal\n        {\n            BOOST_HANA_CONSTEXPR_CHECK(hana::equal(x, x));\n            BOOST_HANA_CONSTEXPR_CHECK(hana::not_(hana::equal(x, y)));\n        }\n\n        // not_equal\n        {\n            BOOST_HANA_CONSTEXPR_CHECK(hana::not_equal(x, y));\n            BOOST_HANA_CONSTEXPR_CHECK(hana::not_(hana::not_equal(x, x)));\n        }\n\n        // comparing\n        {\n            BOOST_HANA_CONSTEXPR_CHECK(hana::equal(\n                hana::comparing(f)(x, x),\n                hana::equal(f(x), f(x))\n            ));\n\n            BOOST_HANA_CONSTEXPR_CHECK(hana::equal(\n                hana::comparing(f)(x, y),\n                hana::equal(f(x), f(y))\n            ));\n        }\n    }\n\n    //////////////////////////////////////////////////////////////////////////\n    // Orderable\n    //////////////////////////////////////////////////////////////////////////\n    {\n        auto ord = numeric;\n\n        // _injection is also monotonic\n        hana::test::_injection<0> f{};\n\n        // less\n        {\n            BOOST_HANA_CONSTEXPR_CHECK(hana::less(ord(0), ord(1)));\n            BOOST_HANA_CONSTEXPR_CHECK(hana::not_(hana::less(ord(0), ord(0))));\n            BOOST_HANA_CONSTEXPR_CHECK(hana::not_(hana::less(ord(1), ord(0))));\n        }\n\n        // less_equal\n        {\n            BOOST_HANA_CONSTEXPR_CHECK(hana::less_equal(ord(0), ord(1)));\n            BOOST_HANA_CONSTEXPR_CHECK(hana::less_equal(ord(0), ord(0)));\n            BOOST_HANA_CONSTEXPR_CHECK(hana::not_(hana::less_equal(ord(1), ord(0))));\n        }\n\n        // greater_equal\n        {\n            BOOST_HANA_CONSTEXPR_CHECK(hana::greater_equal(ord(1), ord(0)));\n            BOOST_HANA_CONSTEXPR_CHECK(hana::greater_equal(ord(0), ord(0)));\n            BOOST_HANA_CONSTEXPR_CHECK(hana::not_(hana::greater_equal(ord(0), ord(1))));\n        }\n\n        // greater\n        {\n            BOOST_HANA_CONSTEXPR_CHECK(hana::greater(ord(1), ord(0)));\n            BOOST_HANA_CONSTEXPR_CHECK(hana::not_(hana::greater(ord(0), ord(0))));\n            BOOST_HANA_CONSTEXPR_CHECK(hana::not_(hana::greater(ord(0), ord(1))));\n        }\n\n        // max\n        {\n            BOOST_HANA_CONSTEXPR_CHECK(hana::equal(\n                hana::max(ord(0), ord(0)), ord(0)\n            ));\n            BOOST_HANA_CONSTEXPR_CHECK(hana::equal(\n                hana::max(ord(1), ord(0)), ord(1)\n            ));\n            BOOST_HANA_CONSTEXPR_CHECK(hana::equal(\n                hana::max(ord(0), ord(1)), ord(1)\n            ));\n        }\n\n        // min\n        {\n            BOOST_HANA_CONSTEXPR_CHECK(hana::equal(\n                hana::min(ord(0), ord(0)),\n                ord(0)\n            ));\n            BOOST_HANA_CONSTEXPR_CHECK(hana::equal(\n                hana::min(ord(1), ord(0)),\n                ord(0)\n            ));\n            BOOST_HANA_CONSTEXPR_CHECK(hana::equal(\n                hana::min(ord(0), ord(1)),\n                ord(0)\n            ));\n        }\n\n        // ordering\n        {\n            BOOST_HANA_CONSTEXPR_CHECK(hana::equal(\n                hana::ordering(f)(ord(1), ord(0)),\n                hana::less(f(ord(1)), f(ord(0)))\n            ));\n\n            BOOST_HANA_CONSTEXPR_CHECK(hana::equal(\n                hana::ordering(f)(ord(0), ord(1)),\n                hana::less(f(ord(0)), f(ord(1)))\n            ));\n\n            BOOST_HANA_CONSTEXPR_CHECK(hana::equal(\n                hana::ordering(f)(ord(0), ord(0)),\n                hana::less(f(ord(0)), f(ord(0)))\n            ));\n        }\n    }\n\n    //////////////////////////////////////////////////////////////////////////\n    // Monoid\n    //////////////////////////////////////////////////////////////////////////\n    {\n        constexpr int x = 2, y = 3;\n\n        // zero\n        {\n            BOOST_HANA_CONSTEXPR_CHECK(hana::equal(\n                hana::zero<Numeric>(), numeric(0)\n            ));\n        }\n\n        // plus\n        {\n            BOOST_HANA_CONSTEXPR_CHECK(hana::equal(\n                hana::plus(numeric(x), numeric(y)),\n                numeric(x + y)\n            ));\n        }\n    }\n\n    //////////////////////////////////////////////////////////////////////////\n    // Group\n    //////////////////////////////////////////////////////////////////////////\n    {\n        constexpr int x = 2, y = 3;\n\n        // minus\n        {\n            BOOST_HANA_CONSTEXPR_CHECK(hana::equal(\n                hana::minus(numeric(x), numeric(y)),\n                numeric(x - y)\n            ));\n        }\n\n        // negate\n        {\n            BOOST_HANA_CONSTEXPR_CHECK(hana::equal(\n                hana::negate(numeric(x)),\n                numeric(-x)\n            ));\n        }\n    }\n\n    //////////////////////////////////////////////////////////////////////////\n    // Ring\n    //////////////////////////////////////////////////////////////////////////\n    {\n        constexpr int x = 2, y = 3;\n\n        // one\n        {\n            BOOST_HANA_CONSTEXPR_CHECK(hana::equal(\n                hana::one<Numeric>(),\n                numeric(1)\n            ));\n        }\n\n        // mult\n        {\n            BOOST_HANA_CONSTEXPR_CHECK(hana::equal(\n                hana::mult(numeric(x), numeric(y)),\n                numeric(x * y)\n            ));\n        }\n\n        // power\n        {\n            BOOST_HANA_CONSTEXPR_CHECK(hana::equal(\n                hana::power(numeric(x), hana::zero<CNumeric<int>>()),\n                hana::one<Numeric>()\n            ));\n\n            BOOST_HANA_CONSTEXPR_CHECK(hana::equal(\n                hana::power(numeric(x), hana::one<CNumeric<int>>()),\n                numeric(x)\n            ));\n\n            BOOST_HANA_CONSTEXPR_CHECK(hana::equal(\n                hana::power(numeric(x), cnumeric<int, 2>),\n                hana::mult(numeric(x), numeric(x))\n            ));\n\n            BOOST_HANA_CONSTEXPR_CHECK(hana::equal(\n                hana::power(numeric(x), cnumeric<int, 3>),\n                hana::mult(hana::mult(numeric(x), numeric(x)), numeric(x))\n            ));\n        }\n    }\n\n    //////////////////////////////////////////////////////////////////////////\n    // EuclideanRing\n    //////////////////////////////////////////////////////////////////////////\n    {\n        constexpr int x = 6, y = 3, z = 4;\n\n        // div\n        {\n            BOOST_HANA_CONSTEXPR_CHECK(hana::equal(\n                hana::div(numeric(x), numeric(y)),\n                numeric(x / y)\n            ));\n\n            BOOST_HANA_CONSTEXPR_CHECK(hana::equal(\n                hana::div(numeric(x), numeric(z)),\n                 numeric(x/ z)\n            ));\n        }\n\n        // mod\n        {\n            BOOST_HANA_CONSTEXPR_CHECK(hana::equal(\n                hana::mod(numeric(x), numeric(y)),\n                numeric(x % y)\n            ));\n\n            BOOST_HANA_CONSTEXPR_CHECK(hana::equal(\n                hana::mod(numeric(x), numeric(z)),\n                numeric(x % z)\n            ));\n        }\n    }\n\n    //////////////////////////////////////////////////////////////////////////\n    // Logical\n    //////////////////////////////////////////////////////////////////////////\n    {\n        auto logical = numeric;\n        auto comparable = numeric;\n\n        // not_\n        {\n            BOOST_HANA_CONSTEXPR_CHECK(hana::equal(\n                hana::not_(logical(true)),\n                logical(false)\n            ));\n        }\n\n        // and_\n        {\n            BOOST_HANA_CONSTEXPR_CHECK(hana::equal(\n                hana::and_(logical(true)),\n                logical(true)\n            ));\n            BOOST_HANA_CONSTEXPR_CHECK(hana::equal(\n                hana::and_(logical(false)),\n                logical(false)\n            ));\n\n            BOOST_HANA_CONSTEXPR_CHECK(hana::equal(\n                hana::and_(logical(true), logical(true)),\n                logical(true)\n            ));\n            BOOST_HANA_CONSTEXPR_CHECK(hana::equal(\n                hana::and_(logical(true), logical(false)),\n                logical(false)\n            ));\n            BOOST_HANA_CONSTEXPR_CHECK(hana::equal(\n                hana::and_(logical(false), invalid{}),\n                logical(false)\n            ));\n\n            BOOST_HANA_CONSTEXPR_CHECK(hana::equal(\n                hana::and_(logical(true), logical(true), logical(true)),\n                logical(true)\n            ));\n            BOOST_HANA_CONSTEXPR_CHECK(hana::equal(\n                hana::and_(logical(true), logical(true), logical(false)),\n                logical(false)\n            ));\n            BOOST_HANA_CONSTEXPR_CHECK(hana::equal(\n                hana::and_(logical(true), logical(false), invalid{}),\n                logical(false)\n            ));\n            BOOST_HANA_CONSTEXPR_CHECK(hana::equal(\n                hana::and_(logical(false), invalid{}, invalid{}),\n                logical(false)\n            ));\n        }\n\n        // or_\n        {\n            BOOST_HANA_CONSTEXPR_CHECK(hana::equal(\n                hana::or_(logical(true)),\n                logical(true)\n            ));\n            BOOST_HANA_CONSTEXPR_CHECK(hana::equal(\n                hana::or_(logical(false)),\n                logical(false)\n            ));\n\n            BOOST_HANA_CONSTEXPR_CHECK(hana::equal(\n                hana::or_(logical(false), logical(false)),\n                logical(false)\n            ));\n            BOOST_HANA_CONSTEXPR_CHECK(hana::equal(\n                hana::or_(logical(false), logical(true)),\n                logical(true)\n            ));\n            BOOST_HANA_CONSTEXPR_CHECK(hana::equal(\n                hana::or_(logical(true), invalid{}),\n                logical(true)\n            ));\n\n            BOOST_HANA_CONSTEXPR_CHECK(hana::equal(\n                hana::or_(logical(false), logical(false), logical(false)),\n                logical(false)\n            ));\n            BOOST_HANA_CONSTEXPR_CHECK(hana::equal(\n                hana::or_(logical(false), logical(false), logical(true)),\n                logical(true)\n            ));\n            BOOST_HANA_CONSTEXPR_CHECK(hana::equal(\n                hana::or_(logical(false), logical(true), invalid{}),\n                logical(true)\n            ));\n            BOOST_HANA_CONSTEXPR_CHECK(hana::equal(\n                hana::or_(logical(true), invalid{}, invalid{}),\n                logical(true)\n            ));\n        }\n\n        // if_\n        {\n            BOOST_HANA_CONSTEXPR_CHECK(hana::equal(\n                hana::if_(logical(true), comparable(0), comparable(1)),\n                comparable(0)\n            ));\n\n            BOOST_HANA_CONSTEXPR_CHECK(hana::equal(\n                hana::if_(logical(false), comparable(0), comparable(1)),\n                comparable(1)\n            ));\n        }\n\n        // eval_if\n        {\n            auto t = [=](auto) { return comparable(0); };\n            auto e = [=](auto) { return comparable(1); };\n\n            BOOST_HANA_CONSTEXPR_CHECK(hana::equal(\n                hana::eval_if(logical(true), t, e),\n                comparable(0)\n            ));\n\n            BOOST_HANA_CONSTEXPR_CHECK(hana::equal(\n                hana::eval_if(logical(false), t, e),\n                comparable(1)\n            ));\n        }\n\n        // while_\n        {\n            auto smaller_than = [](auto n) {\n                return [n](auto v) { return v.size() < n; };\n            };\n            auto f = [](auto v) {\n                v.push_back(v.size());\n                return v;\n            };\n\n            BOOST_HANA_RUNTIME_CHECK(hana::equal(\n                hana::while_(smaller_than(0u), std::vector<int>{}, f),\n                std::vector<int>{}\n            ));\n\n            BOOST_HANA_RUNTIME_CHECK(hana::equal(\n                hana::while_(smaller_than(1u), std::vector<int>{}, f),\n                std::vector<int>{0}\n            ));\n\n            BOOST_HANA_RUNTIME_CHECK(hana::equal(\n                hana::while_(smaller_than(2u), std::vector<int>{}, f),\n                std::vector<int>{0, 1}\n            ));\n\n            BOOST_HANA_RUNTIME_CHECK(hana::equal(\n                hana::while_(smaller_than(3u), std::vector<int>{}, f),\n                std::vector<int>{0, 1, 2}\n            ));\n\n            BOOST_HANA_RUNTIME_CHECK(hana::equal(\n                hana::while_(smaller_than(4u), std::vector<int>{}, f),\n                std::vector<int>{0, 1, 2, 3}\n            ));\n\n            // Make sure it can be called with an lvalue state:\n            std::vector<int> v{};\n            BOOST_HANA_RUNTIME_CHECK(hana::equal(\n                hana::while_(smaller_than(4u), v, f),\n                std::vector<int>{0, 1, 2, 3}\n            ));\n        }\n\n        // while_\n        {\n            auto less_than = [](auto n) {\n                return [n](auto v) { return v.size() < n; };\n            };\n            auto f = [](auto v) {\n                v.push_back(v.size());\n                return v;\n            };\n\n            BOOST_HANA_RUNTIME_CHECK(hana::equal(\n                hana::while_(less_than(0u), std::vector<int>{}, f),\n                std::vector<int>{}\n            ));\n\n            BOOST_HANA_RUNTIME_CHECK(hana::equal(\n                hana::while_(less_than(1u), std::vector<int>{}, f),\n                std::vector<int>{0}\n            ));\n\n            BOOST_HANA_RUNTIME_CHECK(hana::equal(\n                hana::while_(less_than(2u), std::vector<int>{}, f),\n                std::vector<int>{0, 1}\n            ));\n\n            BOOST_HANA_RUNTIME_CHECK(hana::equal(\n                hana::while_(less_than(3u), std::vector<int>{}, f),\n                std::vector<int>{0, 1, 2}\n            ));\n\n            BOOST_HANA_RUNTIME_CHECK(hana::equal(\n                hana::while_(less_than(4u), std::vector<int>{}, f),\n                std::vector<int>{0, 1, 2, 3}\n            ));\n\n            // Make sure it can be called with an lvalue state:\n            std::vector<int> v{};\n            BOOST_HANA_RUNTIME_CHECK(hana::equal(\n                hana::while_(less_than(4u), v, f),\n                std::vector<int>{0, 1, 2, 3}\n            ));\n        }\n    }\n}\n", "meta": {"hexsha": "e39f88dd1a2096860988b787056778e702bb73d3", "size": 15668, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/hana/test/numeric/main.hpp", "max_stars_repo_name": "metux/boost", "max_stars_repo_head_hexsha": "e0157afdd519a2b14356cea62fcdac81829324cc", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-06-01T15:17:22.000Z", "max_stars_repo_stars_event_max_datetime": "2015-06-01T16:06:53.000Z", "max_issues_repo_path": "libs/hana/test/numeric/main.hpp", "max_issues_repo_name": "metux/boost", "max_issues_repo_head_hexsha": "e0157afdd519a2b14356cea62fcdac81829324cc", "max_issues_repo_licenses": ["BSL-1.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": "libs/hana/test/numeric/main.hpp", "max_forks_repo_name": "metux/boost", "max_forks_repo_head_hexsha": "e0157afdd519a2b14356cea62fcdac81829324cc", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-03-19T07:18:18.000Z", "max_forks_repo_forks_event_max_datetime": "2017-03-19T07:18:18.000Z", "avg_line_length": 30.6015625, "max_line_length": 88, "alphanum_fraction": 0.4477916773, "num_tokens": 3464, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.47800338862372227}}
{"text": "// Boost.Geometry Index\r\n// Unit Test\r\n\r\n// Copyright (c) 2011-2013 Adam Wulkiewicz, Lodz, Poland.\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#include <algorithm>\r\n\r\n#include <geometry_index_test_common.hpp>\r\n\r\n#include <boost/geometry/index/detail/algorithms/minmaxdist.hpp>\r\n\r\n#include <boost/geometry/geometries/point_xy.hpp>\r\n#include <boost/geometry/geometries/point.hpp>\r\n#include <boost/geometry/geometries/box.hpp>\r\n\r\n#define BOOST_GEOMETRY_TEST_DEBUG\r\n\r\ntemplate <typename Point, typename Indexable>\r\nvoid test(Point const& pt, Indexable const& indexable,\r\n    typename bg::default_distance_result<Point, Indexable>::type expected_value)\r\n{\r\n    typename bg::default_distance_result<Point, Indexable>::type value = bgi::detail::minmaxdist(pt, indexable);\r\n\r\n#ifdef BOOST_GEOMETRY_TEST_DEBUG\r\n    std::ostringstream out;\r\n    out << typeid(typename bg::coordinate_type<Point>::type).name()\r\n        << \" \"\r\n        << typeid(typename bg::coordinate_type<Indexable>::type).name()\r\n        << \" \"\r\n        << typeid(bg::default_distance_result<Point, Indexable>::type).name()\r\n        << \" \"\r\n        << \"minmaxdist : \" << value\r\n        << std::endl;\r\n    std::cout << out.str();\r\n#endif\r\n\r\n    BOOST_CHECK_CLOSE(value, expected_value, 0.0001);\r\n}\r\n\r\ntemplate <typename Indexable, typename Point>\r\nvoid test_indexable(Point const& pt, std::string const& wkt,\r\n    typename bg::default_distance_result<Point, Indexable>::type expected_value)\r\n{\r\n    Indexable indexable;\r\n    bg::read_wkt(wkt, indexable);\r\n    test(pt, indexable, expected_value);\r\n}\r\n\r\nvoid test_large_integers()\r\n{\r\n    typedef bg::model::point<int, 2, bg::cs::cartesian> int_point_type;\r\n    typedef bg::model::point<double, 2, bg::cs::cartesian> double_point_type;\r\n\r\n    int_point_type int_pt(0, 0);\r\n    double_point_type double_pt(0, 0);\r\n\r\n    bg::model::box<int_point_type> int_box;\r\n    bg::model::box<double_point_type> double_box;\r\n\r\n    std::string const box_li = \"POLYGON((1536119 192000, 1872000 528000))\";\r\n    bg::read_wkt(box_li, int_box);\r\n    bg::read_wkt(box_li, double_box);\r\n    \r\n    BOOST_CHECK(bgi::detail::minmaxdist(int_pt, int_box) == bgi::detail::minmaxdist(double_pt, double_box));\r\n}\r\n\r\nint test_main(int, char* [])\r\n{\r\n    typedef bg::model::point<int, 2, bg::cs::cartesian> P2ic;\r\n    typedef bg::model::point<float, 2, bg::cs::cartesian> P2fc;\r\n    typedef bg::model::point<double, 2, bg::cs::cartesian> P2dc;\r\n\r\n    typedef bg::model::point<int, 3, bg::cs::cartesian> P3ic;\r\n    typedef bg::model::point<float, 3, bg::cs::cartesian> P3fc;\r\n    typedef bg::model::point<double, 3, bg::cs::cartesian> P3dc;\r\n\r\n    test_indexable<bg::model::box<P2ic> >(P2ic(1, 2), \"POLYGON((0 1,2 4))\", 5.0);\r\n    test_indexable<bg::model::box<P2fc> >(P2fc(1, 2), \"POLYGON((0 1,2 4))\", 5.0);\r\n    test_indexable<bg::model::box<P2dc> >(P2dc(1, 2), \"POLYGON((0 1,2 4))\", 5.0);\r\n    test_indexable<bg::model::box<P3ic> >(P3ic(1, 2, 3), \"POLYGON((0 1 2,2 4 6))\", 14.0);\r\n    test_indexable<bg::model::box<P3fc> >(P3fc(1, 2, 3), \"POLYGON((0 1 2,2 4 6))\", 14.0);\r\n    test_indexable<bg::model::box<P3dc> >(P3dc(1, 2, 3), \"POLYGON((0 1 2,2 4 6))\", 14.0);\r\n\r\n    test_indexable<bg::model::box<P2ic> >(P2ic(1, 2), \"POLYGON((1 2,3 5))\", 4.0);\r\n    \r\n#ifdef HAVE_TTMATH\r\n    typedef bg::model::point<ttmath_big, 2, bg::cs::cartesian> P2ttmc;\r\n    typedef bg::model::point<ttmath_big, 3, bg::cs::cartesian> P3ttmc;\r\n\r\n    test_indexable<bg::model::box<P2ttmc> >(P2ttmc(1, 2), \"POLYGON((0 1,2 4))\", 5.0);\r\n    test_indexable<bg::model::box<P3ttmc> >(P3ttmc(1, 2, 3), \"POLYGON((0 1 2,2 4 6))\", 14.0);\r\n#endif\r\n\r\n    test_large_integers();\r\n\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "fd781223d8e81f9b2dc1e7d5d4351ed637246fbe", "size": 3788, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/geometry/index/test/algorithms/minmaxdist.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": 85.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T20:36:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T20:38:31.000Z", "max_issues_repo_path": "libs/boost/libs/geometry/index/test/algorithms/minmaxdist.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/index/test/algorithms/minmaxdist.cpp", "max_forks_repo_name": "flingone/frameworks_base_cmds_remoted", "max_forks_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2015-01-28T16:33:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-12T05:04:39.000Z", "avg_line_length": 37.137254902, "max_line_length": 113, "alphanum_fraction": 0.6554910243, "num_tokens": 1229, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389817407017, "lm_q2_score": 0.6406358479787609, "lm_q1q2_score": 0.47800337927746367}}
{"text": "// An example showing TEASER++ registration with the Stanford bunny model\n#include <chrono>\n#include <iostream>\n#include <random>\n#include <fstream>\n#include <Eigen/Core>\n\n#include <teaser/ply_io.h>\n#include <teaser/registration.h>\n\n\nint main(int argc, char* argv[]) {\n\n  // argv[1:]: \"path_to_src_cloud\", \"path_to_out_cloud\", \"float_noise_bound\", \"float.cbar2\", \"bool_estimate_scaling\",\n  //            \"int_rotation_max_iterations\", \"float_rotation_gnc_factor\", \"float_rotation_cost_threshold\",\n  //            \"path_to_correspondences_file\"\n\n  // Load the .ply file\n  teaser::PLYReader reader;\n  teaser::PointCloud src_cloud, tgt_cloud;\n  auto status = reader.read(argv[1], src_cloud);\n  status = reader.read(argv[2], tgt_cloud);\n  std::vector<std::pair<int, int>> correspondences;\n  std::ifstream corr_file(argv[9]);\n\n  int x, y;\n  while(corr_file >> x >> y)\n  {\n      correspondences.push_back(std::make_pair(x, y));\n  }\n\n  int N_src = src_cloud.size();\n  int N_tgt = tgt_cloud.size();\n\n\n  // Convert the point clouds to Eigen\n  Eigen::Matrix<double, 3, Eigen::Dynamic> src(3, N_src);\n  for (size_t i = 0; i < N_src; ++i) {\n    src.col(i) << src_cloud[i].x, src_cloud[i].y, src_cloud[i].z;\n  }\n  Eigen::Matrix<double, 3, Eigen::Dynamic> tgt(3, N_tgt);\n  for (size_t i = 0; i < N_tgt; ++i) {\n    tgt.col(i) << tgt_cloud[i].x, tgt_cloud[i].y, tgt_cloud[i].z;\n  }\n\n  // Run TEASER++ registration\n  // Prepare solver parameters\n  teaser::RobustRegistrationSolver::Params params;\n  params.noise_bound = std::stof(argv[3]);\n  params.cbar2 = std::stof(argv[4]);\n  params.estimate_scaling = std::stoi(argv[5]);\n  params.rotation_max_iterations = std::stoi(argv[6]);\n  params.rotation_gnc_factor = std::stof(argv[7]);\n  params.rotation_estimation_algorithm =\n      teaser::RobustRegistrationSolver::ROTATION_ESTIMATION_ALGORITHM::GNC_TLS;\n  params.rotation_cost_threshold = std::stof(argv[8]);\n\n  // Solve with TEASER++\n  teaser::RobustRegistrationSolver solver(params);\n  std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now();\n  solver.solve(src_cloud, tgt_cloud, correspondences);\n  std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();\n\n  auto solution = solver.getSolution();\n\n  // Compare results\n  std::cout << \"=====================================\" << std::endl;\n  std::cout << \"          TEASER++ Results           \" << std::endl;\n  std::cout << \"=====================================\" << std::endl;\n    std::cout << \"Estimated rotation: \" << std::endl;\n  std::cout << solution.rotation << std::endl;\n  std::cout << \"Estimated translation: \" << std::endl;\n  std::cout << solution.translation << std::endl;\n  std::cout << \"Estimated scale: \" << std::endl;\n  std::cout << solution.scale << std::endl;\n  std::cout << std::endl;\n\n  std::cout << \"Time taken (s): \"\n            << std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count() /\n                   1000000.0\n            << std::endl;\n}\n", "meta": {"hexsha": "6041e946e4ad97f2127160dca0777e51bde6462a", "size": 2963, "ext": "cc", "lang": "C++", "max_stars_repo_path": "GUI/teaser.cc", "max_stars_repo_name": "superkirill/TEASER-GUI", "max_stars_repo_head_hexsha": "8a71b07eac8d2c2fd89b13c22e1f64f4b21abc95", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "GUI/teaser.cc", "max_issues_repo_name": "superkirill/TEASER-GUI", "max_issues_repo_head_hexsha": "8a71b07eac8d2c2fd89b13c22e1f64f4b21abc95", "max_issues_repo_licenses": ["MIT"], "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/teaser.cc", "max_forks_repo_name": "superkirill/TEASER-GUI", "max_forks_repo_head_hexsha": "8a71b07eac8d2c2fd89b13c22e1f64f4b21abc95", "max_forks_repo_licenses": ["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.6987951807, "max_line_length": 117, "alphanum_fraction": 0.6432669592, "num_tokens": 801, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891479496523, "lm_q2_score": 0.5813030906443134, "lm_q1q2_score": 0.47794109279734753}}
{"text": "#include \"DarkART/Wavefunctions_Initial.hpp\"\n\n#include <cmath>\n#include <complex>\n#include <fstream>\n#include <stdlib.h>\n\n#include <boost/math/quadrature/gauss_kronrod.hpp>\n\n#include \"libphysica/Integration.hpp\"\n#include \"libphysica/Natural_Units.hpp\"\n#include \"libphysica/Utilities.hpp\"\n\n#include \"DarkART/Special_Functions.hpp\"\n#include \"DarkART/version.hpp\"\n\nnamespace DarkART\n{\nusing namespace std::complex_literals;\nusing namespace libphysica::natural_units;\nusing namespace boost::math::quadrature;\nusing boost::math::factorial;\n\ndouble a0 = Bohr_Radius;\ndouble au = 27.211386245988 * eV;\n\n// 1. Initial state: Roothaan-Hartree-Fock Ground-State Atomic Wave Functions\n\nvoid Initial_Electron_State::Import_RHF_Coefficients()\n{\n\tstd::string filepath = TOP_LEVEL_DIR \"data/\" + Orbital_Name() + \".txt\";\n\tif(libphysica::File_Exists(filepath) == false)\n\t{\n\t\tstd::cerr << \"Error in Initial_Electron_State::Import_RHF_Coefficients(): Coefficient table for \" << Orbital_Name() << \" does not exist.\" << std::endl;\n\t\tstd::exit(EXIT_FAILURE);\n\t}\n\n\tstd::ifstream f;\n\tf.open(filepath);\n\tif(f.is_open())\n\t{\n\t\tf >> binding_energy;\n\t\tbinding_energy *= au;\n\t\tdouble C, Z;\n\t\tunsigned int nin;\n\t\twhile(f >> nin >> Z >> C)\n\t\t{\n\t\t\tn_lj.push_back(nin);\n\t\t\tZ_lj.push_back(Z);\n\t\t\tC_nlj.push_back(C);\n\t\t}\n\t\tf.close();\n\t}\n\tZ_eff = sqrt(-2.0 * binding_energy / au) * n;\n}\n\nvoid Initial_Electron_State::Check_Normalization()\n{\n\tdouble norm = Normalization();\n\tif(std::fabs(1.0 - norm) > 1.0e-4)\n\t{\n\t\tstd::cout << \"Error in Initial_Electron_State(): Normalization of \" << element_name << \" = \" << norm << \" != 1.0\" << std::endl;\n\t\tstd::exit(EXIT_FAILURE);\n\t}\n}\n\nInitial_Electron_State::Initial_Electron_State()\n: element_name(\"none\"), n(0), l(0), binding_energy(0.0), Z_eff(0.0)\n{\n}\n\nInitial_Electron_State::Initial_Electron_State(const std::string& element, int N, int L)\n: element_name(element), n(N), l(L)\n{\n\tImport_RHF_Coefficients();\n\tCheck_Normalization();\n}\n\nInitial_Electron_State::Initial_Electron_State(const std::string& element, std::string shell_name)\n: element_name(element)\n{\n\tn = shell_name[0] - '0';\n\tfor(l = 0; l < l_orbital_names.size(); l++)\n\t\tif(shell_name[1] == l_orbital_names[l][0])\n\t\t\tbreak;\n\tImport_RHF_Coefficients();\n\tCheck_Normalization();\n}\n\nstd::string Initial_Electron_State::Orbital_Name() const\n{\n\treturn element_name + \"_\" + std::to_string(n) + l_orbital_names[l];\n}\n\ndouble Initial_Electron_State::Radial_Wavefunction(double r) const\n{\n\tdouble R_nl = 0.0;\n\tfor(unsigned int j = 0; j < C_nlj.size(); j++)\n\t\tR_nl += C_nlj[j] * std::pow(2.0 * Z_lj[j], n_lj[j] + 0.5) / sqrt(factorial<double>(2.0 * n_lj[j])) * std::pow(r / a0, n_lj[j] - 1.0) * std::exp(-Z_lj[j] * r / a0);\n\n\treturn std::pow(a0, -1.5) * R_nl;\n}\n\ndouble Initial_Electron_State::Radial_Wavefunction_Derivative(double r) const\n{\n\tdouble dR_dr = 0.0;\n\tfor(unsigned int j = 0; j < C_nlj.size(); j++)\n\t\tdR_dr += C_nlj[j] * std::pow(2.0 * Z_lj[j], n_lj[j] + 0.5) / sqrt(factorial<double>(2.0 * n_lj[j])) * ((n_lj[j] - 1.0) / a0 * std::pow(r / a0, n_lj[j] - 2.0) - Z_lj[j] / a0 * std::pow(r / a0, n_lj[j] - 1.0)) * std::exp(-Z_lj[j] * r / a0);\n\n\treturn std::pow(a0, -1.5) * dR_dr;\n}\n\ndouble Initial_Electron_State::Normalization() const\n{\n\tstd::function<double(double)> integrand = [this](double r) {\n\t\tdouble R = Radial_Wavefunction(r);\n\t\treturn r * r * R * R;\n\t};\n\t// Integrate with Gauss Legendre\n\treturn libphysica::Integrate_Gauss_Legendre(integrand, 0.0, 50.0 * Bohr_Radius, 1000);\n}\n\ndouble Initial_Electron_State::Radial_Integral(double r) const\n{\n\tstd::function<double(double)> integrand = [this](double rprime) {\n\t\tdouble R = Radial_Wavefunction(rprime);\n\t\treturn rprime * rprime * R * R;\n\t};\n\treturn gauss_kronrod<double, 31>::integrate(integrand, 0.0, r, 5, 1e-9);\n}\n\nvoid Initial_Electron_State::Print_Summary(unsigned int mpi_rank) const\n{\n\tif(mpi_rank == 0)\n\t{\n\t\tstd::cout << SEPARATOR\n\t\t\t\t  << Orbital_Name() << \" - Summary\" << std::endl\n\t\t\t\t  << std::endl\n\t\t\t\t  << \"Binding energy [eV]:\\t\" << In_Units(binding_energy, eV) << std::endl\n\t\t\t\t  << \"Z_effective:\\t\\t\" << Z_eff << std::endl\n\t\t\t\t  << std::endl\n\t\t\t\t  << \"n_lj\\tZ_lj\\tC_nlj\" << std::endl;\n\t\tfor(unsigned int i = 0; i < C_nlj.size(); i++)\n\t\t\tstd::cout << n_lj[i] << \"\\t\" << Z_lj[i] << \"\\t\" << C_nlj[i] << std::endl;\n\t}\n}\n\n}\t// namespace DarkART", "meta": {"hexsha": "9c743ffc2d490a3a6a55a9819ba04ff471d901c5", "size": 4285, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Wavefunctions_Initial.cpp", "max_stars_repo_name": "temken/DarkART", "max_stars_repo_head_hexsha": "7bf3b03e4bf89ec83edd5ca2c9e8e7ce5ee16081", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-15T13:58:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T13:58:28.000Z", "max_issues_repo_path": "src/Wavefunctions_Initial.cpp", "max_issues_repo_name": "temken/DarkART", "max_issues_repo_head_hexsha": "7bf3b03e4bf89ec83edd5ca2c9e8e7ce5ee16081", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Wavefunctions_Initial.cpp", "max_forks_repo_name": "temken/DarkART", "max_forks_repo_head_hexsha": "7bf3b03e4bf89ec83edd5ca2c9e8e7ce5ee16081", "max_forks_repo_licenses": ["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.9527027027, "max_line_length": 240, "alphanum_fraction": 0.6709451575, "num_tokens": 1395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891218080991, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.47794107760118176}}
{"text": "#include <boost/math/distributions/normal.hpp>\n\n#include <iostream>\n\nnamespace bmath = boost::math;\n\ninline double normal_cdf(const double x, const double mean, const double sd) {\n    if (sd == 0.0) {return 0.0;}\n    return bmath::cdf(bmath::normal(mean, sd), x);\n}\n\ninline double normal_ccdf(const double x, const double mean, const double sd) {\n    if (sd == 0.0) {return 0.0;}\n    return bmath::cdf(bmath::complement(bmath::normal(mean, sd), x));\n}\n\nint main() {\n    std::cout << normal_cdf(0.0, 0.0, 1.0) << std::endl;\n    std::cout << normal_cdf(0.0, 0.0, 1.0) << std::endl;\n    return 0;\n}\n", "meta": {"hexsha": "37f77ee17477d55df9b6cae2ed32d35ee87d1133", "size": 596, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cxx/boost_math.cpp", "max_stars_repo_name": "heavywatal/scribble", "max_stars_repo_head_hexsha": "48fa1ade110ca57a47314b2c0346ee4f71ea23a5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cxx/boost_math.cpp", "max_issues_repo_name": "heavywatal/scribble", "max_issues_repo_head_hexsha": "48fa1ade110ca57a47314b2c0346ee4f71ea23a5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cxx/boost_math.cpp", "max_forks_repo_name": "heavywatal/scribble", "max_forks_repo_head_hexsha": "48fa1ade110ca57a47314b2c0346ee4f71ea23a5", "max_forks_repo_licenses": ["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.0909090909, "max_line_length": 79, "alphanum_fraction": 0.6409395973, "num_tokens": 197, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.874077222043951, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.47789136507215474}}
{"text": "#include <iostream>\n#include <algorithm>\n#include <iterator>\n#include <cmath>\n#include <fstream>\n#include <valarray>\n#include <sstream>\n#include <filesystem>\n#include <string>\n\nusing namespace std::string_literals;\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/math/constants/constants.hpp>\n\n#include \"miMaS/field.h\"\n#include \"miMaS/complex_field.h\"\n#include \"miMaS/weno.h\"\n#include \"miMaS/fft.h\"\n#include \"miMaS/array_view.h\"\n#include \"miMaS/poisson.h\"\n#include \"miMaS/rk.h\"\n#include \"miMaS/config.h\"\n#include \"miMaS/signal_handler.h\"\n#include \"miMaS/iteration.h\"\n\nnamespace o2 {\n  template < typename _T , std::size_t NumDimsV >\n  auto\n  trp_v ( field<_T,NumDimsV> const & u , ublas::vector<_T> const& E )\n  {\n    field<_T,NumDimsV> trp(tools::array_view<const std::size_t>(u.shape(),NumDimsV+1));\n\n    { auto k=0, km1=trp.size(0)-1;\n      for ( auto i=0 ; i<trp.size(1) ; ++i ) {\n        trp[k][i] = ( E(i)*(u[k+1][i]-u[km1][i])/(2.*u.step.dv) );\n      }\n    }\n    for ( auto k=1 ; k<trp.size(0)-1 ; ++k ) {\n      for ( auto i=0 ; i<trp.size(1) ; ++i ) {\n        trp[k][i] = ( E(i)*(u[k+1][i]-u[k-1][i])/(2.*u.step.dv) );\n      }\n    }\n    { auto k=trp.size(0)-1, kp1=0;\n      for ( auto i=0 ; i<trp.size(1) ; ++i ) {\n        trp[k][i] = ( E(i)*(u[kp1][i]-u[k-1][i])/(2.*u.step.dv) );\n      }\n    }\n\n    return trp;\n  }\n}\n\nstruct iter_s {\n  std::size_t iter;\n  double dt;\n  double current_time;\n  double Lhfh;\n  double LE;\n};\n\n#define save(data,dir,suffix,x_y) {\\\n  std::stringstream filename; filename << #data << \"_\" << suffix << \".dat\"; \\\n  std::ofstream of( dir / filename.str() );\\\n  std::transform( data.begin() , data.end() , std::ostream_iterator<std::string>(of,\"\\n\") , x_y );\\\n  of.close();\\\n}\n\nnamespace math = boost::math::constants;\nconst std::complex<double> & I = std::complex<double>(0.,1.);\n\n#define SQ(X) ((X)*(X))\n#define Xi(i) (i*fh.step.dx+fh.range.x_min)\n#define Vk(k) (k*fh.step.dv+fh.range.v_min)\n\n\nauto\nmaxwellian ( double rho , double u , double T ) {\n  return [=](double x,double v){ return rho/(std::sqrt(2.*math::pi<double>()*T))*std::exp( -0.5*SQ(v-u)/T ); };\n}\n\nint\nmain(int argc, char const *argv[])\n{\n  const double sigma = 1.733;\n\n  std::filesystem::path p(\"config.init\");\n  if ( argc > 1 ) {\n    p = argv[1];\n  }\n  auto c = config(p);\n  c.name = \"vhll\";\n\n  std::filesystem::create_directories(c.output_dir);\n  std::cout << c << std::endl;\n  std::ofstream oconfig( c.output_dir / \"config.init\" );\n  oconfig << c << std::endl;\n  oconfig.close();\n\n/* --------------------------------------------------------------- */\n  field<double,1> fh(boost::extents[c.Nv][c.Nx]);\n  complex_field<double,1> hfh(boost::extents[c.Nv][c.Nx]);\n\n  fh.range.v_min = -8.; fh.range.v_max = 8.;\n  fh.step.dv = (fh.range.v_max-fh.range.v_min)/c.Nv;\n\n  double Kx = 0.5;\n  fh.range.x_min = 0.; fh.range.x_max = 2./Kx*math::pi<double>();\n  fh.step.dx = (fh.range.x_max-fh.range.x_min)/c.Nx;\n\n  ublas::vector<double> v (c.Nv,0.);\n  for ( std::size_t k=0 ; k<c.Nv ; ++k ) { v[k] = Vk(k); }\n\n  ublas::vector<double> kx(c.Nx);\n  {\n    double l = fh.range.len_x();\n    for ( auto i=0 ; i<c.Nx/2 ; ++i ) { kx[i]      = 2.*math::pi<double>()*i/l; }\n    for ( int i=-c.Nx/2 ; i<0 ; ++i ) { kx[c.Nx+i] = 2.*math::pi<double>()*i/l; }\n  }\n\n  auto tb_M1    = maxwellian( 0.5*c.alpha ,  c.ui , 1.   ) , tb_M2  = maxwellian( 0.5*c.alpha , -c.ui , 1.  );\n\n  for (field<double,2>::size_type k=0 ; k<fh.size(0) ; ++k ) {\n    for (field<double,2>::size_type i=0 ; i<fh.size(1) ; ++i ) {\n      // tb\n      fh[k][i] = ( tb_M1(Xi(i),Vk(k)) + tb_M2(Xi(i),Vk(k)) )*(1. + 0.01*std::cos(Kx*Xi(i)));\n      //fh[k][i] = ( tb_M1(Xi(i),Vk(k)) + tb_M2(Xi(i),Vk(k)) )*(1.);\n    }\n    fft::fft(&(fh[k][0]),&(fh[k][c.Nx-1])+1,&(hfh[k][0]));\n  }\n  fh.write( c.output_dir / \"init_vhll.dat\" );\n\n  iteration::iteration<double> iter;\n  iter.iter = 0;\n  iter.current_time = 0.;\n  iter.dt = 0.5*fh.step.dv;\n\n  ublas::vector<double> uc(c.Nx,0.);\n  ublas::vector<double> E (c.Nx,0.);\n\n  std::vector<double> ee;   ee.reserve(int(std::ceil(c.Tf/iter.dt))+1);\n  std::vector<double> Emax; Emax.reserve(int(std::ceil(c.Tf/iter.dt))+1);\n  std::vector<double> H;    H.reserve(int(std::ceil(c.Tf/iter.dt))+1);\n\n  std::vector<double> times; times.reserve(int(std::ceil(c.Tf/iter.dt))+1);\n  std::vector<iteration::iteration<double>> iterations;         iterations.reserve(int(std::ceil(c.Tf/iter.dt))+1);\n  std::vector<iteration::iteration<double>> success_iterations; success_iterations.reserve(int(std::ceil(c.Tf/iter.dt))+1);\n\n  auto save_data = [&] ( std::string && suffix ) {\n    suffix = c.name + suffix;\n\n    // save iterations informations\n    auto writer_iter = [] ( auto const & it ) {\n      std::stringstream ss; ss << it;\n      return ss.str();\n    };\n    c << monitoring::data( \"iterations_\"+suffix+\".dat\"         , iterations         , writer_iter );\n    c << monitoring::data( \"success_iterations_\"+suffix+\".dat\" , success_iterations , writer_iter );\n\n    // save temporel data\n    auto dt_y = [&,count=0] (auto const& y) mutable {\n      std::stringstream ss; ss<<times[count++]<<\" \"<<y;\n      return ss.str();\n    };\n    c << monitoring::data( \"ee_\"+suffix+\".dat\"   , ee   , dt_y );\n    c << monitoring::data( \"Emax_\"+suffix+\".dat\" , Emax , dt_y );\n    c << monitoring::data( \"H_\"+suffix+\".dat\"    , H    , dt_y );\n\n    // save distribution function\n    for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) { fft::ifft(hfh[k].begin(),hfh[k].end(),fh[k].begin()); }\n    fh.write( c.output_dir / (\"vp_\"+suffix+\".dat\") );\n\n  };\n\n  signal_handler::signal_handler<SIGINT,SIGILL>::handler( [&]( int signal ) -> void {\n    std::cerr << \"\\n\\033[41;97m ** End of execution after signal \" << signal << \" ** \\033[0m\\n\";\n    std::cerr << \"\\033[36msave data...\\033[0m\\n\";\n\n    save_data(\"_SIGINT\");\n  });\n\n  const double rho_c = 1.-c.alpha;\n  const double sqrt_rho_c = std::sqrt(rho_c);\n  {\n    poisson<double> poisson_solver(c.Nx,fh.range.len_x());\n    ublas::vector<double> rho(c.Nx,0.);\n    rho = fh.density(); // compute density from init data\n    for ( auto i=0 ; i<c.Nx ; ++i ) { rho[i] += (1.-c.alpha); } // add (1-alpha) for cold particules\n    E = poisson_solver(rho);\n\n    Emax.push_back( std::abs(*std::max_element( E.begin() , E.end() , [](double a,double b){return (std::abs(a) < std::abs(b));} )) );\n    double electric_energy = 0.;\n    for ( const auto & ei : E ) { electric_energy += ei*ei*fh.step.dx; }\n    ee.push_back( std::sqrt(electric_energy) );\n\n    double total_energy = energy(fh,E);\n    total_energy += 0.; // sum(rho_c*u_c*u_c) = 0 because u_c = 0 at time 0\n    H.push_back( total_energy );\n    times.push_back( 0. );\n  }\n\n\n  // initialize memory for all temporary variables\n  ublas::vector<double> J(c.Nx);\n  fft::spectrum_ d(c.Nx);\n  field<double,1> Edvf(tools::array_view<const std::size_t>(fh.shape(),2));\n  ublas::vector<double> uc1(c.Nx) , uc2(c.Nx) , uc3(c.Nx) , uc4(c.Nx) , uc5(c.Nx) , uc6(c.Nx) , uc7(c.Nx),\n                        E1(c.Nx)  , E2(c.Nx)  , E3(c.Nx)  , E4(c.Nx)  , E5(c.Nx)  , E6(c.Nx)  , E7(c.Nx);\n  complex_field<double,1> hfh1(boost::extents[c.Nv][c.Nx]),hfh2(boost::extents[c.Nv][c.Nx]),hfh3(boost::extents[c.Nv][c.Nx]),hfh4(boost::extents[c.Nv][c.Nx]),hfh5(boost::extents[c.Nv][c.Nx]),hfh6(boost::extents[c.Nv][c.Nx]),hfh7(boost::extents[c.Nv][c.Nx]);\n\n  while (  iter.current_time < c.Tf ) {\n    std::cout << \"\\r\" << iteration::time(iter) << std::flush;\n    \n\n/////////////////////////////////////////////////////////////////////\n/**\n/////////////////////////////////////////////////////////////////////\n    // RK(3,3) classical\n\n    // STAGE 1\n    {\n      for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) { fft::ifft(hfh[k].begin(),hfh[k].end(),fh[k].begin()); }\n      J = fh.courant();\n      Edvf = weno::trp_v(fh,E);\n\n      double c1 = std::cos(dt*sqrt_rho_c), s1 = std::sin(dt*sqrt_rho_c);\n      for ( auto i=0 ; i<c.Nx ; ++i ) {\n        uc1[i] =  uc[i]*c1 + E[i]*s1/sqrt_rho_c - dt*J[i]*s1/sqrt_rho_c;\n        E1[i]  = -uc[i]*s1*sqrt_rho_c + E[i]*c1 - dt*J[i]*c1;\n      }\n      for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) {\n        d.fft(&(Edvf[k][0]));\n        for ( auto i=0 ; i<c.Nx ; ++i ) {\n          hfh1[k][i] = hfh[k][i]*std::exp(-I*kx[i]*Vk(k)*dt) - dt*d[i]*std::exp(-I*kx[i]*Vk(k)*dt);\n        }\n      }\n    } // end stage 1\n\n    // STAGE 2\n    {\n      for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) { fft::ifft(hfh1[k].begin(),hfh1[k].end(),fh[k].begin()); }\n      J = fh.courant();\n      Edvf = weno::trp_v(fh,E1);\n\n      double c2 = std::cos(0.5*dt*sqrt_rho_c), s2 = std::sin(0.5*dt*sqrt_rho_c);\n      for ( auto i=0 ; i<c.Nx ; ++i ) {\n        uc2[i] =  0.75*uc[i]*c2 + 0.75*E[i]*s2/sqrt_rho_c + 0.25*uc1[i]*c2 - 0.25*E1[i]*s2/sqrt_rho_c + 0.25*dt*J[i]*s2/sqrt_rho_c;\n        E2[i]  = -0.75*uc[i]*s2*sqrt_rho_c + 0.75*E[i]*c2 + 0.25*uc1[i]*s2*sqrt_rho_c + 0.25*E1[i]*c2 - 0.25*dt*J[i]*c2;\n      }\n      for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) {\n        d.fft(&(Edvf[k][0]));\n        for ( auto i=0 ; i<c.Nx ; ++i ) {\n          hfh2[k][i] = 0.75*hfh[k][i]*std::exp(-I*kx[i]*Vk(k)*0.5*dt) + 0.25*hfh1[k][i]*std::exp(I*kx[i]*Vk(k)*0.5*dt) - 0.25*dt*d[i]*std::exp(I*kx[i]*Vk(k)*0.5*dt);\n        }\n      }\n    } // end stage 2\n\n    // STAGE 3\n    {\n      for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) { fft::ifft(hfh2[k].begin(),hfh2[k].end(),fh[k].begin()); }\n      J = fh.courant();\n      Edvf = weno::trp_v(fh,E2);\n\n      double c1 = std::cos(dt*sqrt_rho_c), s1 = std::sin(dt*sqrt_rho_c);\n      double c2 = std::cos(0.5*dt*sqrt_rho_c), s2 = std::sin(0.5*dt*sqrt_rho_c);\n      for ( auto i=0 ; i<c.Nx ; ++i ) {\n        double tmp_uc =  (1./3.)*uc[i]*c1 + (1./3.)*E[i]*s1/sqrt_rho_c + (2./3.)*uc2[i]*c2 + (2./3.)*E2[i]*s2/sqrt_rho_c - (2./3.)*dt*J[i]*s2/sqrt_rho_c;\n        E[i]          = -(1./3.)*uc[i]*s1*sqrt_rho_c + (1./3.)*E[i]*c1 - (2./3.)*uc2[i]*s2*sqrt_rho_c + (2./3.)*E2[i]*c2 - (2./3.)*dt*J[i]*c2;\n        uc[i] = tmp_uc;\n      }\n      for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) {\n        d.fft(&(Edvf[k][0]));\n        for ( auto i=0 ; i<c.Nx ; ++i ) {\n          hfh[k][i] = (1./3.)*hfh[k][i]*std::exp(-I*kx[i]*Vk(k)*dt) + (2./3.)*hfh2[k][i]*std::exp(-I*kx[i]*Vk(k)*0.5*dt) - (2./3.)*dt*d[i]*std::exp(-I*kx[i]*Vk(k)*0.5*dt);\n        }\n      }\n    } // end stage 3\n\n\n/////////////////////////////////////////////////////////////////////\n**\n/////////////////////////////////////////////////////////////////////\n    // RK(3,3) NSSP\n\n    // STAGE 1\n    {\n      for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) { fft::ifft(hfh[k].begin(),hfh[k].end(),fh[k].begin()); }\n      J = fh.courant();\n      Edvf = weno::trp_v(fh,E);\n\n      double c49 = std::cos((4./9.)*dt*sqrt_rho_c), s49 = std::sin((4./9.)*dt*sqrt_rho_c);\n      for ( auto i=0 ; i<c.Nx ; ++i ) {\n        uc1[i] =  uc[i]*c49 - E[i]*s49/sqrt_rho_c - (4./9.)*dt*J[i]*s49/sqrt_rho_c;\n        E1[i]  =  uc[i]*s49*sqrt_rho_c + E[i]*c49 + (4./9.)*dt*J[i]*c49;\n      }\n      for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) {\n        d.fft(&(Edvf[k][0]));\n        for ( auto i=0 ; i<c.Nx ; ++i ) {\n          hfh1[k][i] = hfh[k][i]*std::exp((4./9.)*I*kx[i]*Vk(k)*dt) + (4./9.)*dt*d[i]*std::exp((4./9.)*I*kx[i]*Vk(k)*dt);\n        }\n      }\n    } // end stage 1\n\n    // STAGE 2\n    {\n      for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) { fft::ifft(hfh1[k].begin(),hfh1[k].end(),fh[k].begin()); }\n      J = fh.courant();\n      Edvf = weno::trp_v(fh,E1);\n\n      double c23  = std::cos((2./3.)*dt*sqrt_rho_c)  , s23  = std::sin((2./3.)*dt*sqrt_rho_c) ,\n             c109 = std::cos((10./9.)*dt*sqrt_rho_c) , s109 = std::sin((10./9.)*dt*sqrt_rho_c);\n      for ( auto i=0 ; i<c.Nx ; ++i ) {\n        uc2[i] = (29./8.)*(  uc[i]*c23 + E[i]*s23/sqrt_rho_c ) - (21./8.)*(  uc1[i]*c109 + E1[i]*s109/sqrt_rho_c ) + 0.5*dt*J[i]*s109/sqrt_rho_c;\n        E2[i]  = (29./8.)*( -uc[i]*s23*sqrt_rho_c + E[i]*c23 ) - (21./8.)*( -uc1[i]*s109*sqrt_rho_c + E1[i]*c109 ) + 0.5*dt*J[i]*c109;\n      }\n      for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) {\n        d.fft(&(Edvf[k][0]));\n        for ( auto i=0 ; i<c.Nx ; ++i ) {\n          hfh2[k][i] = (29./8.)*hfh[k][i]*std::exp(-(2./3.)*I*kx[i]*Vk(k)*dt) - (21./8.)*hfh1[k][i]*std::exp(-(10./9.)*I*kx[i]*Vk(k)*dt) + 0.5*dt*d[i]*std::exp(-(10./9.)*I*kx[i]*Vk(k)*dt);\n        }\n      }\n    } // end stage 2\n\n    // STAGE 3\n    {\n      for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) { fft::ifft(hfh2[k].begin(),hfh2[k].end(),fh[k].begin()); }\n      J = fh.courant();\n      Edvf = weno::trp_v(fh,E2);\n\n      double c1   = std::cos(dt*sqrt_rho_c)          , s1   = std::sin(dt*sqrt_rho_c)         ,\n             c13  = std::cos((1./3.)*dt*sqrt_rho_c)  , s13  = std::sin((1./3.)*dt*sqrt_rho_c) ,\n             c139 = std::cos((13./9.)*dt*sqrt_rho_c) , s139 = std::sin((13./9.)*dt*sqrt_rho_c);\n      for ( auto i=0 ; i<c.Nx ; ++i ) {\n        double tmp_uc =  (25./16.)*(  uc[i]*c1 + E[i]*s1/sqrt_rho_c ) - (9./16.)*(  uc1[i]*c139 + E1[i]*s139/sqrt_rho_c ) - (3./4.)*dt*J[i]*s13/sqrt_rho_c;\n        E[i]          =  (25./16.)*( -uc[i]*s1*sqrt_rho_c + E[i]*c1 ) - (9./16.)*( -uc1[i]*s139*sqrt_rho_c + E1[i]*c139 ) - (3./4.)*dt*J[i]*c13;\n        uc[i] = tmp_uc;\n      }\n      for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) {\n        d.fft(&(Edvf[k][0]));\n        for ( auto i=0 ; i<c.Nx ; ++i ) {\n          hfh[k][i] = (25./16.)*hfh[k][i]*std::exp(-I*kx[i]*Vk(k)*dt) - (9./16.)*hfh1[k][i]*std::exp(-(13./9.)*I*kx[i]*Vk(k)*dt) - (3./4.)*dt*d[i]*std::exp(-(1./3.)*I*kx[i]*Vk(k)*dt);\n        }\n      }\n    } // end stage 3\n\n/////////////////////////////////////////////////////////////////////\n**/\n/////////////////////////////////////////////////////////////////////\n\n    // DP4(3)\n    // STAGE 1\n    {\n      for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) { fft::ifft(hfh[k].begin(),hfh[k].end(),fh[k].begin()); }\n      J = fh.courant();\n      Edvf = weno::trp_v(fh,E);\n\n      double c05 = std::cos(0.5*iter.dt*sqrt_rho_c), s05 = std::sin(0.5*iter.dt*sqrt_rho_c);\n      for ( auto i=0 ; i<c.Nx ; ++i ) {\n        uc1[i] =  uc[i]*c05 + E[i]*s05/sqrt_rho_c - 0.5*iter.dt*J[i]*s05/sqrt_rho_c;\n        E1[i]  = -uc[i]*s05*sqrt_rho_c + E[i]*c05 - 0.5*iter.dt*J[i]*c05;\n      }\n      for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) {\n        d.fft(&(Edvf[k][0]));\n        for ( auto i=0 ; i<c.Nx ; ++i ) {\n          hfh1[k][i] = hfh[k][i]*std::exp(-0.5*I*kx[i]*Vk(k)*iter.dt) - 0.5*iter.dt*d[i]*std::exp(-0.5*I*kx[i]*Vk(k)*iter.dt);\n        }\n      }\n    } // end stage 1\n\n    // STAGE 2\n    {\n      for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) { fft::ifft(hfh1[k].begin(),hfh1[k].end(),fh[k].begin()); }\n      J = fh.courant();\n      Edvf = weno::trp_v(fh,E1);\n\n      double c05 = std::cos(0.5*iter.dt*sqrt_rho_c), s05 = std::sin(0.5*iter.dt*sqrt_rho_c);\n      for ( auto i=0 ; i<c.Nx ; ++i ) {\n        uc2[i] =  uc[i]*c05 + E[i]*s05/sqrt_rho_c;\n        E2[i]  = -uc[i]*s05*sqrt_rho_c + E[i]*c05 - 0.5*iter.dt*J[i];\n      }\n      for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) {\n        d.fft(&(Edvf[k][0]));\n        for ( auto i=0 ; i<c.Nx ; ++i ) {\n          hfh2[k][i] = hfh[k][i]*std::exp(-0.5*I*kx[i]*Vk(k)*iter.dt) - 0.5*iter.dt*d[i];\n        }\n      }\n    } // end stage 2\n\n    // STAGE 3\n    {\n      for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) { fft::ifft(hfh2[k].begin(),hfh2[k].end(),fh[k].begin()); }\n      J = fh.courant();\n      Edvf = weno::trp_v(fh,E2);\n\n      double c1  = std::cos(iter.dt*sqrt_rho_c)     , s1  = std::sin(iter.dt*sqrt_rho_c)    ,\n             c05 = std::cos(0.5*iter.dt*sqrt_rho_c) , s05 = std::sin(0.5*iter.dt*sqrt_rho_c);\n      for ( auto i=0 ; i<c.Nx ; ++i ) {\n        uc3[i] =  uc[i]*c1 + E[i]*s1/sqrt_rho_c - iter.dt*J[i]*s05/sqrt_rho_c;\n        E3[i]  = -uc[i]*s1*sqrt_rho_c + E[i]*c1 - iter.dt*J[i]*c05;\n      }\n      for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) {\n        d.fft(&(Edvf[k][0]));\n        for ( auto i=0 ; i<c.Nx ; ++i ) {\n          hfh3[k][i] = hfh[k][i]*std::exp(-I*kx[i]*Vk(k)*iter.dt) - iter.dt*d[i]*std::exp(-0.5*I*kx[i]*Vk(k)*iter.dt);\n        }\n      }\n    } // end stage 3\n\n    // STAGE 4\n    {\n      for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) { fft::ifft(hfh3[k].begin(),hfh3[k].end(),fh[k].begin()); }\n      J = fh.courant();\n      Edvf = weno::trp_v(fh,E3);\n\n      double c1  = std::cos(iter.dt*sqrt_rho_c)     , s1  = std::sin(iter.dt*sqrt_rho_c)    ,\n             c05 = std::cos(0.5*iter.dt*sqrt_rho_c) , s05 = std::sin(0.5*iter.dt*sqrt_rho_c);\n      for ( auto i=0 ; i<c.Nx ; ++i ) {\n        uc4[i] = -(1./3.)*(  uc[i]*c1 + E[i]*s1/sqrt_rho_c ) + (1./3.)*(  uc1[i]*c05 + E1[i]*s05/sqrt_rho_c ) + (2./3.)*(  uc2[i]*c05 + E2[i]*s05/sqrt_rho_c ) + uc3[i]/3.;\n        E4[i]  = -(1./3.)*( -uc[i]*s1*sqrt_rho_c + E[i]*c1 ) + (1./3.)*( -uc1[i]*s05*sqrt_rho_c + E1[i]*c05 ) + (2./3.)*( -uc2[i]*s05*sqrt_rho_c + E2[i]*c05 ) + E3[i]/3. - (1./6.)*iter.dt*J[i];\n      }\n      for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) {\n        d.fft(&(Edvf[k][0]));\n        for ( auto i=0 ; i<c.Nx ; ++i ) {\n          hfh4[k][i] = -(1./3.)*hfh[k][i]*std::exp(-I*kx[i]*Vk(k)*iter.dt) + (1./3.)*hfh1[k][i]*std::exp(-0.5*I*kx[i]*Vk(k)*iter.dt) + (2./3.)*hfh2[k][i]*std::exp(-0.5*I*kx[i]*Vk(k)*iter.dt) + hfh3[k][i]/3. - (1./6.)*iter.dt*d[i];\n        }\n      }\n    } // end stage 4\n\n/*\n    // STAGE 5\n    {\n      for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) { fft::ifft(hfh4[k].begin(),hfh4[k].end(),fh[k].begin()); }\n      J = fh.courant();\n      Edvf = weno::trp_v(fh,E4);\n\n      double c1  = std::cos(iter.dt*sqrt_rho_c)     , s1  = std::sin(iter.dt*sqrt_rho_c)    ,\n             c05 = std::cos(0.5*iter.dt*sqrt_rho_c) , s05 = std::sin(0.5*iter.dt*sqrt_rho_c);\n      for ( auto i=0 ; i<c.Nx ; ++i ) {\n        uc5[i] = -(1./5.)*(  uc[i]*c1 + E[i]*s1/sqrt_rho_c ) + (1./5.)*(  uc1[i]*c05 + E1[i]*s05/sqrt_rho_c ) + (2./5.)*(  uc2[i]*c05 + E2[i]*s05/sqrt_rho_c ) + uc3[i]/5. + (2./5.)*uc4[i];\n        E5[i]  = -(1./5.)*( -uc[i]*s1*sqrt_rho_c + E[i]*c1 ) + (1./5.)*( -uc1[i]*s05*sqrt_rho_c + E1[i]*c05 ) + (2./5.)*( -uc2[i]*s05*sqrt_rho_c + E2[i]*c05 ) + E3[i]/5. + (2./5.)*E4[i] - (1./10.)*iter.dt*J[i];\n      }\n      for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) {\n        d.fft(&(Edvf[k][0]));\n        for ( auto i=0 ; i<c.Nx ; ++i ) {\n          hfh5[k][i] = -(1./5.)*hfh[k][i]*std::exp(-I*kx[i]*Vk(k)*iter.dt) + (1./5.)*hfh1[k][i]*std::exp(-0.5*I*kx[i]*Vk(k)*iter.dt) + (2./5.)*hfh2[k][i]*std::exp(-0.5*I*kx[i]*Vk(k)*iter.dt) + hfh3[k][i]/5. + (2./5.)*hfh4[k][i] - 0.1*iter.dt*d[i];\n        }\n      }\n    } // end stage 5\n*/\n\n/////////////////////////////////////////////////////////////////////\n/**\n/////////////////////////////////////////////////////////////////////\n\n    //DP5\n    // STAGE 1\n    {\n      for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) { fft::ifft(hfh[k].begin(),hfh[k].end(),fh[k].begin()); }\n      J = fh.courant();\n      Edvf = weno::trp_v(fh,E);\n\n      double c02 = std::cos(0.2*dt*sqrt_rho_c) , s02 = std::sin(0.2*dt*sqrt_rho_c);\n      for ( auto i=0 ; i<c.Nx ; ++i ) {\n        uc1[i] =  uc[i]*c02 + E[i]*s02/sqrt_rho_c - 0.2*dt*J[i]*s02/sqrt_rho_c;\n        E1[i]  = -uc[i]*s02*sqrt_rho_c + E[i]*c02 - 0.2*dt*J[i]*c02;\n      }\n      for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) {\n        d.fft(&(Edvf[k][0]));\n        for ( auto i=0 ; i<c.Nx ; ++i ) {\n          hfh1[k][i] = hfh[k][i]*std::exp(-0.2*I*kx[i]*Vk(k)*dt) - 0.2*dt*d[i]*std::exp(-0.2*I*kx[i]*Vk(k)*dt);\n        }\n      }\n    } // end stage 1\n\n    // STAGE 2\n    {\n      for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) { fft::ifft(hfh1[k].begin(),hfh1[k].end(),fh[k].begin()); }\n      J = fh.courant();\n      Edvf = weno::trp_v(fh,E1);\n\n      double c01 = std::cos(0.1*sqrt_rho_c*dt) , s01 = std::sin(0.1*sqrt_rho_c*dt),\n             c03 = std::cos(0.3*sqrt_rho_c*dt) , s03 = std::sin(0.3*sqrt_rho_c*dt);\n      for ( auto i=0 ; i<c.Nx ; ++i ) {\n        uc2[i] = 0.625*(  uc[i]*c03 + E[i]*s03/sqrt_rho_c ) + 0.375*(  uc1[i]*c01 + E1[i]*s01/sqrt_rho_c ) - 0.225*dt*J[i]*s01/sqrt_rho_c;\n        E2[i]  = 0.625*( -uc[i]*s03*sqrt_rho_c + E[i]*c03 ) + 0.375*( -uc1[i]*sqrt_rho_c*s01 + E1[i]*c01 ) - 0.225*dt*J[i]*c01;\n      }\n      for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) {\n        d.fft(&(Edvf[k][0]));\n        for ( auto i=0 ; i<c.Nx ; ++i ) {\n          hfh2[k][i] = 0.625*hfh[k][i]*std::exp(-0.3*I*kx[i]*Vk(k)*dt) + 0.375*hfh1[k][i]*std::exp(-0.1*I*kx[i]*Vk(k)*dt) - 0.225*dt*d[i]*std::exp(-0.1*I*kx[i]*Vk(k));\n        }\n      }\n    } // end stage 2\n\n    // STAGE 3\n    {\n      for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) { fft::ifft(hfh2[k].begin(),hfh2[k].end(),fh[k].begin()); }\n      J = fh.courant();\n      Edvf = weno::trp_v(fh,E2);\n\n      double c08 = std::cos(0.8*dt*sqrt_rho_c) , s08 = std::sin(0.8*dt*sqrt_rho_c) ,\n             c06 = std::cos(0.6*dt*sqrt_rho_c) , s06 = std::sin(0.6*dt*sqrt_rho_c) ,\n             c05 = std::cos(0.5*dt*sqrt_rho_c) , s05 = std::sin(0.5*dt*sqrt_rho_c) ;\n      for ( auto i=0 ; i<c.Nx ; ++i ) {\n        uc3[i] = (175./27.)*(  uc[i]*c08 + E[i]*s08/sqrt_rho_c ) + (100./9.)*(  uc1[i]*c06 + E1[i]*s06/sqrt_rho_c ) - (448./27.)*(  uc2[i]*c05 + E2[i]*s05/sqrt_rho_c ) - (32./9.)*dt*J[i]*s05/sqrt_rho_c;\n        E3[i]  = (175./27.)*( -uc[i]*s08*sqrt_rho_c + E[i]*c08 ) + (100./9.)*( -uc1[i]*s06*sqrt_rho_c + E1[i]*c06 ) - (448./27.)*( -uc2[i]*s05*sqrt_rho_c + E2[i]*c05 ) - (32./9.)*dt*J[i]*c05;\n      }\n      for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) {\n        d.fft(&(Edvf[k][0]));\n        for ( auto i=0 ; i<c.Nx ; ++i ) {\n          hfh3[k][i] = (175./27.)*hfh[k][i]*std::exp(-0.8*I*kx[i]*Vk(k)*dt) + (100./9.)*hfh1[k][i]*std::exp(-0.6*I*kx[i]*Vk(k)*dt) - (448./27.)*hfh2[k][i]*std::exp(-0.5*I*kx[i]*Vk(k)*dt) - (32./9.)*dt*d[i]*std::exp(-0.5*I*kx[i]*Vk(k));\n        }\n      }\n    } // end stage 3\n\n    // STAGE 4\n    {\n      for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) { fft::ifft(hfh3[k].begin(),hfh3[k].end(),fh[k].begin()); }\n      J = fh.courant();\n      Edvf = weno::trp_v(fh,E3);\n\n      double c89    = std::cos((8./9.)*sqrt_rho_c*dt)    , s89    = std::sin((8./9.)*sqrt_rho_c*dt)    ,\n             c3145  = std::cos((31./45.)*sqrt_rho_c*dt)  , s3145  = std::sin((31./45.)*sqrt_rho_c*dt)  ,\n             c5390  = std::cos((53./90.)*sqrt_rho_c*dt)  , s5390  = std::sin((53./90.)*sqrt_rho_c*dt)  ,\n             c44827 = std::cos((448./27.)*sqrt_rho_c*dt) , s44827 = std::sin((448./27.)*sqrt_rho_c*dt) ,\n             c445   = std::cos((4./45.)*sqrt_rho_c*dt)   , s445   = std::sin((4./45.)*sqrt_rho_c*dt)   ;\n      for ( auto i=0 ; i<c.Nx ; ++i ) {\n        uc4[i] = (3551./6561.)*(  uc[i]*c89 + E[i]*s89/sqrt_rho_c ) + (7420./2187.)*(  uc1[i]*c3145 + E1[i]*s3145/sqrt_rho_c ) - (37376./6561.)*(  uc2[i]*c5390 + E2[i]*s5390/sqrt_rho_c ) + (2014./729.)*(  uc3[i]*c445 + E3[i]*s445/sqrt_rho_c ) + (212./729.)*dt*J[i]*s445/sqrt_rho_c;\n        E4[i]  = (3551./6561.)*( -uc[i]*s89*sqrt_rho_c + E[i]*c89 ) + (7420./2187.)*( -uc1[i]*s3145*sqrt_rho_c + E1[i]*c3145 ) - (37376./6561.)*( -uc2[i]*s5390*sqrt_rho_c + E2[i]*c5390 ) + (2014./729.)*( -uc3[i]*s445*sqrt_rho_c + E3[i]*c445 ) + (212./729.)*dt*J[i]*c445;\n      }\n      for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) {\n        d.fft(&(Edvf[k][0]));\n        for ( auto i=0 ; i<c.Nx ; ++i ) {\n          hfh4[k][i] = (3551./6561.)*hfh[k][i]*std::exp(-(8./9.)*I*kx[i]*Vk(k)*dt) + (7420./2187.)*hfh1[k][i]*std::exp(-(31./45.)*I*kx[i]*Vk(k)*dt) - (37376./6561.)*hfh2[k][i]*std::exp(-(53./90.)*I*kx[i]*Vk(k)*dt) + (2014./729.)*hfh3[k][i]*std::exp(-(4./45.)*I*kx[i]*Vk(k)*dt) + (212./729.)*dt*d[i]*std::exp(-(4./45.)*kx[i]*Vk(k)*dt);\n        }\n      }\n    } // end stage 4\n\n    // STAGE 5\n    {\n      for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) { fft::ifft(hfh4[k].begin(),hfh4[k].end(),fh[k].begin()); }\n      J = fh.courant();\n      Edvf = weno::trp_v(fh,E4);\n\n      double c1  = std::cos(sqrt_rho_c*dt)         , s1  = std::sin(sqrt_rho_c*dt)         ,\n             c08 = std::cos(0.8*sqrt_rho_c*dt)     , s08 = std::sin(0.8*sqrt_rho_c*dt)     ,\n             c07 = std::cos(0.7*sqrt_rho_c*dt)     , s07 = std::sin(0.7*sqrt_rho_c*dt)     ,\n             c02 = std::cos(0.2*sqrt_rho_c*dt)     , s02 = std::sin(0.2*sqrt_rho_c*dt)     ,\n             c19 = std::cos((1./9.)*sqrt_rho_c*dt) , s19 = std::sin((1./9.)*sqrt_rho_c*dt) ;\n      for ( auto i=0 ; i<c.Nx ; ++i ) {\n        uc5[i] = (313397./335808.)*(  uc[i]*c1 + E[i]*s1/sqrt_rho_c ) + (424025./55968.)*(  uc1[i]*c08 + E1[i]*s08/sqrt_rho_c ) - (61400./5247.)*(  uc2[i]*c07 + E2[i]*s07/sqrt_rho_c ) + (96075./18656.)*(  uc3[i]*c02 + E3[i]*s02/sqrt_rho_c ) - (35721./37312.)*(  uc4[i]*c19 + E4[i]*s19/sqrt_rho_c ) + (5103./18656.)*dt*J[i]*s19/sqrt_rho_c;\n        E5[i]  = (313397./335808.)*( -uc[i]*s1*sqrt_rho_c + E[i]*c1 ) + (424025./55968.)*( -uc1[i]*s08*sqrt_rho_c + E1[i]*c08 ) - (61400./5247.)*( -uc2[i]*s07*sqrt_rho_c + E2[i]*c07 ) + (96075./18656.)*( -uc3[i]*s02*sqrt_rho_c + E3[i]*c02 ) - (35721./37312.)*( -uc4[i]*s19*sqrt_rho_c + E4[i]*c19 ) + (5103./18656.)*dt*J[i]*c19;\n      }\n      for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) {\n        d.fft(&(Edvf[k][0]));\n        for ( auto i=0 ; i<c.Nx ; ++i ) {\n          hfh5[k][i] = (313397./335808.)*hfh[k][i]*std::exp(-I*kx[i]*Vk(k)*dt) + (424025./55968.)*hfh1[k][i]*std::exp(-0.8*I*kx[i]*Vk(k)*dt) - (61400./5247.)*hfh2[k][i]*std::exp(-0.7*I*kx[i]*Vk(k)*dt) + (96075./18656.)*hfh3[k][i]*std::exp(-0.2*I*kx[i]*Vk(k)*dt) - (35721./37312.)*hfh4[k][i]*std::exp(-(1./9.)*I*kx[i]*Vk(k)*dt) + (5103./18656.)*dt*d[i]*std::exp(-(1./9.)*I*kx[i]*Vk(k)*dt);\n        }\n      }\n    } // end stage 5\n\n    // STAGE 6\n    {\n      for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) { fft::ifft(hfh5[k].begin(),hfh5[k].end(),fh[k].begin()); }\n      J = fh.courant();\n      Edvf = weno::trp_v(fh,E5);\n\n      double c1  = std::cos(sqrt_rho_c*dt)         , s1  = std::sin(sqrt_rho_c*dt)         ,\n             c08 = std::cos(0.8*sqrt_rho_c*dt)     , s08 = std::sin(0.8*sqrt_rho_c*dt)     ,\n             c07 = std::cos(0.7*sqrt_rho_c*dt)     , s07 = std::sin(0.7*sqrt_rho_c*dt)     ,\n             c02 = std::cos(0.2*sqrt_rho_c*dt)     , s02 = std::sin(0.2*sqrt_rho_c*dt)     ,\n             c19 = std::cos((1./9.)*sqrt_rho_c*dt) , s19 = std::sin((1./9.)*sqrt_rho_c*dt) ;\n      for ( auto i=0 ; i<c.Nx ; ++i ) {\n        uc6[i] = -(563./3456.)*(  uc[i]*c1 + E[i]*s1/sqrt_rho_c ) - (575./252.)*(  uc1[i]*c08 + E1[i]*s08/sqrt_rho_c ) + (31400./10017.)*(  uc2[i]*c07 + E2[i]*s07/sqrt_rho_c ) + (325./1344.)*(  uc3[i]*c02 + E3[i]*s02/sqrt_rho_c ) - (7533./6784.)*(  uc4[i]*c19 + E4[i]*s19/sqrt_rho_c ) + (33./28.)*uc5[i];\n        E6[i]  = -(563./3456.)*( -uc[i]*s1*sqrt_rho_c + E[i]*c1 ) - (575./252.)*( -uc1[i]*s08*sqrt_rho_c + E1[i]*c08 ) + (31400./10017.)*( -uc2[i]*s07*sqrt_rho_c + E2[i]*c07 ) + (325./1344.)*( -uc3[i]*s02*sqrt_rho_c + E3[i]*c02 ) - (7533./6784.)*( -uc4[i]*s19*sqrt_rho_c + E4[i]*c19 ) + (33./28.)*E5[i] - (11./84.)*dt*J[i];\n      }\n      for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) {\n        d.fft(&(Edvf[k][0]));\n        for ( auto i=0 ; i<c.Nx ; ++i ) {\n          hfh6[k][i] = -(563./3456.)*hfh[k][i]*std::exp(-I*kx[i]*Vk(k)*dt) - (575./252.)*hfh1[k][i]*std::exp(-0.8*I*kx[i]*Vk(k)*dt) + (31400./10017.)*hfh2[k][i]*std::exp(-0.7*I*kx[i]*Vk(k)*dt) + (325./1344.)*hfh3[k][i]*std::exp(-0.2*I*kx[i]*Vk(k)*dt) - (7533./6784.)*hfh4[k][i]*std::exp(-(1./9.)*I*kx[i]*Vk(k)*dt) + (33./28.)*hfh5[k][i] - (11./84.)*dt*d[i];\n        }\n      }\n    } // end stage 6\n\n    // STAGE 7\n    {\n      for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) { fft::ifft(hfh6[k].begin(),hfh6[k].end(),fh[k].begin()); }\n      J = fh.courant();\n      Edvf = weno::trp_v(fh,E6);\n\n      double c1  = std::cos(sqrt_rho_c*dt)         , s1  = std::sin(sqrt_rho_c*dt)         ,\n             c08 = std::cos(0.8*sqrt_rho_c*dt)     , s08 = std::sin(0.8*sqrt_rho_c*dt)     ,\n             c07 = std::cos(0.7*sqrt_rho_c*dt)     , s07 = std::sin(0.7*sqrt_rho_c*dt)     ,\n             c02 = std::cos(0.2*sqrt_rho_c*dt)     , s02 = std::sin(0.2*sqrt_rho_c*dt)     ,\n             c19 = std::cos((1./9.)*sqrt_rho_c*dt) , s19 = std::sin((1./9.)*sqrt_rho_c*dt) ;\n      for ( auto i=0 ; i<c.Nx ; ++i ) {\n        uc7[i] = (8813./172800.)*(  uc[i]*c1 + E[i]*s1/sqrt_rho_c ) + (41./180.)*(  uc1[i]*c08 + E1[i]*s08/sqrt_rho_c ) - (4294./10017.)*(  uc2[i]*c07 + E2[i]*s07/sqrt_rho_c ) + (263./384.)*(  uc3[i]*c02 + E3[i]*s02/sqrt_rho_c ) - (137781./339200.)*(  uc4[i]*c19 + E4[i]*s19/sqrt_rho_c ) + (803./4200)*uc5[i] + (17./25.)*uc6[i];\n        E7[i]  = (8813./172800.)*( -uc[i]*s1*sqrt_rho_c + E[i]*c1 ) + (41./180.)*( -uc1[i]*s08*sqrt_rho_c + E1[i]*c08 ) - (4294./10017.)*( -uc2[i]*s07*sqrt_rho_c + E2[i]*c07 ) + (263./384.)*( -uc3[i]*s02*sqrt_rho_c + E3[i]*c02 ) - (137781./339200.)*( -uc4[i]*s19*sqrt_rho_c + E4[i]*c19 ) + (803./4200)*E5[i] + (17./25.)*E6[i] - (1./40.)*dt*J[i];\n      }\n      for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) {\n        d.fft(&(Edvf[k][0]));\n        for ( auto i=0 ; i<c.Nx ; ++i ) {\n          hfh7[k][i] = (8813./172800.)*hfh[k][i]*std::exp(-I*kx[i]*Vk(k)*dt) + (41./180.)*hfh1[k][i]*std::exp(-0.8*I*kx[i]*Vk(k)*dt) - (4294./10017.)*hfh2[k][i]*std::exp(-0.7*I*kx[i]*Vk(k)*dt) + (263./384.)*hfh3[k][i]*std::exp(-0.2*I*kx[i]*Vk(k)*dt) - (137781./339200.)*hfh4[k][i]*std::exp(-(1./9.)*I*kx[i]*Vk(k)*dt) + (803./4200)*hfh5[k][i] + (17./25.)*hfh6[k][i] - (1./40.)*dt*d[i];\n        }\n      }\n    } // end stage 7\n/////////////////////////////////////////////////////////////////////\n/**/\n/////////////////////////////////////////////////////////////////////\n    // end of time loop\n\n    // CHECK local error for compute next time step\n    iter.E_error(E5,E4,fh.step.dx);\n    iter.hfh_error(hfh5,hfh4,fh.step.dx*fh.step.dv);\n    std::cout << \" -- \" << iteration::error(iter) << std::flush;\n\n    iter.success = std::abs(iter.error() - c.tol) <= c.tol;\n    //if ( iter.success ) // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n    {\n      iter.success = true;\n      // SAVE TIME STEP\n      std::copy( uc4.begin()  , uc4.end()  , uc.begin()  );\n      std::copy( E4.begin()   , E4.end()   , E.begin()   );\n      std::copy( hfh4.begin() , hfh4.end() , hfh.begin() );\n\n      // MONITORING\n\n      Emax.push_back( std::abs(*std::max_element( E.begin() , E.end() , [](double a,double b){return (std::abs(a) < std::abs(b));} )) );\n      double electric_energy = std::sqrt(std::accumulate(\n        E.begin() , E.end() , 0. ,\n        [&] ( double partial_sum , double ei ) {\n          return partial_sum + ei*ei*fh.step.dx;\n        }\n      ));\n      ee.push_back( electric_energy );\n\n      for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) { fft::ifft(hfh[k].begin(),hfh[k].end(),fh[k].begin()); }\n      double total_energy = energy(fh,E);\n      {\n        auto rhoh = fh.density();\n        fft::spectrum_ hrhoh(c.Nx); hrhoh.fft(&rhoh[0]);\n        fft::spectrum_ hE(c.Nx); hE.fft(&E[0]);\n        fft::spectrum_ hrhoc(c.Nx);\n        hrhoc[0] = I*kx[0]*hE[0] - hrhoh[0] + 1.;\n        for ( auto i=1 ; i<c.Nx ; ++i ) {\n          hrhoc[i] = I*kx[i]*hE[i] - hrhoh[i];\n        }\n        ublas::vector<double> rhoc (c.Nx,0.); hrhoc.ifft(&rhoc[0]);\n\n        for ( auto i=0 ; i<c.Nx ; ++i ) {\n          total_energy += rhoc[i]*uc[i]*uc[i];\n        }\n      }\n      H.push_back( total_energy );\n\n      // increment time\n      iter.current_time += iter.dt;\n      times.push_back( iter.current_time );\n      success_iterations.push_back( iter );\n    }\n    iterations.push_back( iter );\n\n    ++iter.iter;\n\n    //iter.dt = std::pow( c.tol/iter.Lhfh , 0.25 )*iter.dt;// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n    if ( iter.current_time+iter.dt > c.Tf ) { iter.dt = c.Tf - iter.current_time; }\n  } // while (  i_t*dt < Tf )\n  std::cout << \"\\r\" << time(iter) << std::endl;\n\n  save_data(\"\");\n\n  auto dx_y = [&,count=0](auto const& y) mutable {\n    std::stringstream ss; ss<< fh.step.dx*(count++) <<\" \"<<y;\n    return ss.str();\n  };\n  c << monitoring::data( \"E_\"+c.name+\".dat\" , E , dx_y );\n\n  ublas::vector<double> rho  (c.Nx,0.);\n  ublas::vector<double> rhoc (c.Nx,0.);\n  {\n    auto rhoh = fh.density();\n    fft::spectrum_ hrhoh(c.Nx); hrhoh.fft(&rhoh[0]);\n    fft::spectrum_ hE(c.Nx); hE.fft(&E[0]);\n    fft::spectrum_ hrhoc(c.Nx);\n    hrhoc[0] = I*kx[0]*hE[0] - hrhoh[0] + 1.;\n    for ( auto i=1 ; i<c.Nx ; ++i ) {\n      hrhoc[i] = I*kx[i]*hE[i] - hrhoh[i];\n    }\n    hrhoc.ifft(&rhoc[0]);\n    rho = rhoc + rhoh;\n  }\n\n  c << monitoring::data( \"rho_\"+c.name+\".dat\" , rho , dx_y );\n  c << monitoring::data( \"uc_\"+c.name+\".dat\"  , uc  , dx_y );\n\n  auto Jh = fh.courant();\n  ublas::vector<double> Jc (c.Nx,0.), Jtot (c.Nx,0.);\n  for ( auto i=0 ; i<c.Nx ; ++i ) {\n    Jc[i] = rhoc[i]*uc[i];\n  }\n  Jtot = Jc + Jh;\n  c << monitoring::data( \"J_\"+c.name+\".dat\" , Jtot , dx_y );\n\n  return 0;\n}\n", "meta": {"hexsha": "82ccb9ac0a6cbfe2662971d4cfc03f9260f5e2c8", "size": 32339, "ext": "cc", "lang": "C++", "max_stars_repo_path": "code/cmp_vhll.cc", "max_stars_repo_name": "Kivvix/miMaS", "max_stars_repo_head_hexsha": "ad3894522e64f21827ba3b8f8d1a48c3dc9216e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-01-03T22:31:03.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-29T06:12:07.000Z", "max_issues_repo_path": "code/cmp_vhll.cc", "max_issues_repo_name": "Kivvix/miMaS", "max_issues_repo_head_hexsha": "ad3894522e64f21827ba3b8f8d1a48c3dc9216e3", "max_issues_repo_licenses": ["MIT"], "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/cmp_vhll.cc", "max_forks_repo_name": "Kivvix/miMaS", "max_forks_repo_head_hexsha": "ad3894522e64f21827ba3b8f8d1a48c3dc9216e3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-11-20T12:36:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-29T06:17:16.000Z", "avg_line_length": 45.7411598303, "max_line_length": 388, "alphanum_fraction": 0.4860076069, "num_tokens": 13012, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711870587667, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.4778338277944457}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_COMMON_DETAIL_SCALAR_F_INVTRIG_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_DETAIL_SCALAR_F_INVTRIG_HPP_INCLUDED\n\n#include <boost/simd/function/horn.hpp>\n#include <boost/simd/constant/constant.hpp>\n#include <boost/simd/constant/half.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/mhalf.hpp>\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/constant/pio_2.hpp>\n#include <boost/simd/detail/constant/pio_2lo.hpp>\n#include <boost/simd/constant/pio_3.hpp>\n#include <boost/simd/constant/pio_4.hpp>\n#include <boost/simd/detail/constant/pio_4lo.hpp>\n#include <boost/simd/constant/tan_3pio_8.hpp>\n#include <boost/simd/constant/tanpio_8.hpp>\n#include <boost/simd/constant/two.hpp>\n#include <boost/simd/constant/twopio_3.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/fma.hpp>\n#include <boost/simd/function/is_eqz.hpp>\n#include <boost/simd/function/dec.hpp>\n#include <boost/simd/function/oneminus.hpp>\n#include <boost/simd/function/inc.hpp>\n#include <boost/simd/function/rec.hpp>\n#include <boost/simd/function/sqr.hpp>\n#include <boost/simd/function/sqrt.hpp>\n#include <boost/simd/detail/dispatch/meta/scalar_of.hpp>\n\nnamespace boost { namespace simd\n{\n  namespace detail\n  {\n    namespace bd =  boost::dispatch;\n    namespace bs =  boost::simd;\n\n   template < class A0,\n             class unit_tag,\n             class style,\n             class base_A0 = bd::scalar_of_t<A0>\n  >\n  struct invtrig_base{};\n\n  template < class A0 >\n  struct invtrig_base<A0,tag::radian_tag,tag::not_simd_type, float>\n  {\n    static BOOST_FORCEINLINE A0 asin(A0 a0) BOOST_NOEXCEPT\n    {\n      A0 sign, x, z;\n      x = bs::abs(a0);\n      sign = bitofsign(a0);\n      if ((x < Constant<A0,0x38d1b717>())) return a0; //1.0e-4\n      if ((x >  One<A0>())) return Nan<A0>();\n      auto bx_larger_05    = (x > Half<A0>());\n      if (bx_larger_05)\n      {\n        z = Half<A0>()*oneminus(x);\n        x =  sqrt(z);\n      }\n      else\n      {\n        z = sqr(x);\n      }\n      A0 z1 = horn<A0,\n        0x3e2aaae4,\n        0x3d9980f6,\n        0x3d3a3ec7,\n        0x3cc617e3,\n        0x3d2cb352\n        > (z);\n      z1 = fma(z1, z*x, x);\n      if(bx_larger_05)\n      {\n        z1 = z1+z1;\n        z1 = Pio_2<A0>()-z1;\n      }\n      return bitwise_xor(z1, sign);\n    }\n\n    static BOOST_FORCEINLINE A0 acos(const  A0& a0) BOOST_NOEXCEPT\n    {\n      if (a0 < Mhalf<A0>())\n        return Pi<A0>()-asin( sqrt(inc(a0)*Half<A0>()))*Two<A0>();\n      else if (a0 > Half<A0>())\n        return asin( sqrt(oneminus(a0)*Half<A0>()))*Two<A0>();\n      return (Pio_2<A0>()-asin(a0));\n    }\n\n    static BOOST_FORCEINLINE A0 atan(A0 a0) BOOST_NOEXCEPT\n    {\n      A0 x  = abs(a0);\n      return bitwise_xor(kernel_atan(x, rec(x)), bitofsign(a0));\n    }\n\n    static BOOST_FORCEINLINE A0 acot(A0 a0) BOOST_NOEXCEPT\n    {\n      A0 x  = abs(a0);\n      return bitwise_xor(kernel_atan(rec(x), x), bitofsign(a0));\n    }\n\n    static BOOST_FORCEINLINE A0 kernel_atan(A0 x, A0 recx) BOOST_NOEXCEPT\n    {\n      if (is_eqz(x))  return Zero<A0>();\n      if (x == Inf<A0>())  return Pio_2<A0>();\n      A0 y = 0.0;\n      A0 more = Zero<A0>();\n      if( x > Tan_3pio_8<A0>())\n      {\n        y = Pio_2<A0>();\n        more = Pio_2lo<A0>();\n        x = -recx;\n      }\n      else if( x > Tanpio_8<A0>())\n      {\n        y = Pio_4<A0>();\n        more =  Pio_4lo<A0>();\n        x = dec(x)/inc(x);\n      }\n      A0 z = sqr(x);\n      A0 z1 = horn<A0\n        , 0xbeaaaa2aul  // -3.3333293e-01\n        , 0x3e4c925ful  //  1.9991724e-01\n        , 0xbe0e1b85ul  // -1.4031009e-01\n        , 0x3da4f0d1ul  //  8.5460119e-02\n        > (z);\n    z1 = fma(x, z1*z, x);\n\n      return y+(z1+more);\n    }\n  };\n}\n} }\n#endif\n", "meta": {"hexsha": "0d6b29b4cb1c766fd44d9361a1dbd6d6ebfec37d", "size": 4312, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/detail/scalar/f_invtrig.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/detail/scalar/f_invtrig.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/scalar/f_invtrig.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": 28.9395973154, "max_line_length": 100, "alphanum_fraction": 0.5865027829, "num_tokens": 1357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583695, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4778338256579516}}
{"text": "/**\n * \\copyright\n * Copyright (c) 2012-2017, OpenGeoSys Community (http://www.opengeosys.org)\n *            Distributed under a Modified BSD License.\n *              See accompanying file LICENSE.txt or\n *              http://www.opengeosys.org/project/license\n *\n */\n\n#include <cmath>\n#include <memory>\n\n#include <gtest/gtest.h>\n\n#include <Eigen/Eigen>\n\n#include \"MeshLib/Elements/Line.h\"\n#include \"MeshLib/Mesh.h\"\n\n#include \"ProcessLib/LIE/Common/Utils.h\"\n\n\nnamespace\n{\n\nstd::unique_ptr<MeshLib::Mesh> createLine(\n    std::array<double, 3> const& a, std::array<double, 3> const& b)\n{\n    MeshLib::Node** nodes = new MeshLib::Node*[2];\n    nodes[0] = new MeshLib::Node(a);\n    nodes[1] = new MeshLib::Node(b);\n    MeshLib::Element* e = new MeshLib::Line(nodes);\n\n    return std::unique_ptr<MeshLib::Mesh>(\n                new MeshLib::Mesh(\"\",\n                                  std::vector<MeshLib::Node*>{nodes[0], nodes[1]},\n                                  std::vector<MeshLib::Element*>{e})\n                );\n}\n\nstd::unique_ptr<MeshLib::Mesh> createX()\n{\n    return createLine({{-1.0, 0.0, 0.0}}, {{1.0,  0.0, 0.0}});\n}\n\nstd::unique_ptr<MeshLib::Mesh> createY()\n{\n    return createLine({{0.0, -1.0, 0.0}}, {{0.0,  1.0, 0.0}});\n}\n\nstd::unique_ptr<MeshLib::Mesh> createXY()\n{\n    // 45degree inclined\n    return createLine({{0.0, 0.0, 0.0}}, {{2./sqrt(2), 2./sqrt(2), 0.0}});\n}\n\nconst double eps = std::numeric_limits<double>::epsilon();\n\n}\n\nTEST(LIE, rotationMatrixX)\n{\n    auto msh(createX());\n    auto e(msh->getElement(0));\n    Eigen::Vector3d nv;\n    ProcessLib::LIE::computeNormalVector(*e, nv);\n    ASSERT_EQ(0., nv[0]);\n    ASSERT_EQ(1., nv[1]);\n    ASSERT_EQ(0., nv[2]);\n\n    Eigen::MatrixXd R(2,2);\n    ProcessLib::LIE::computeRotationMatrix(nv, 2, R);\n\n    ASSERT_NEAR(1., R(0,0), eps);\n    ASSERT_NEAR(0., R(0,1), eps);\n    ASSERT_NEAR(0., R(1,0), eps);\n    ASSERT_NEAR(1., R(1,1), eps);\n}\n\nTEST(LIE, rotationMatrixY)\n{\n    auto msh(createY());\n    auto e(msh->getElement(0));\n    Eigen::Vector3d nv;\n    ProcessLib::LIE::computeNormalVector(*e, nv);\n    ASSERT_EQ(-1., nv[0]);\n    ASSERT_EQ(0., nv[1]);\n    ASSERT_EQ(0., nv[2]);\n\n    Eigen::MatrixXd R(2,2);\n    ProcessLib::LIE::computeRotationMatrix(nv, 2, R);\n\n    ASSERT_NEAR(0., R(0,0), eps);\n    ASSERT_NEAR(1., R(0,1), eps);\n    ASSERT_NEAR(-1., R(1,0), eps);\n    ASSERT_NEAR(0., R(1,1), eps);\n}\n\nTEST(LIE, rotationMatrixXY)\n{\n    auto msh(createXY());\n    auto e(msh->getElement(0));\n    Eigen::Vector3d nv;\n    ProcessLib::LIE::computeNormalVector(*e, nv);\n    ASSERT_NEAR(-1./sqrt(2), nv[0], eps);\n    ASSERT_NEAR(1./sqrt(2), nv[1], eps);\n    ASSERT_EQ(0., nv[2]);\n\n    Eigen::MatrixXd R(2,2);\n    ProcessLib::LIE::computeRotationMatrix(nv, 2, R);\n\n    ASSERT_NEAR(1./sqrt(2), R(0,0), eps);\n    ASSERT_NEAR(1./sqrt(2), R(0,1), eps);\n    ASSERT_NEAR(-1./sqrt(2), R(1,0), eps);\n    ASSERT_NEAR(1./sqrt(2), R(1,1), eps);\n}\n", "meta": {"hexsha": "c2ed9fa3de8b4a6fd2de17f8b8399b888be75d88", "size": 2898, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tests/ProcessLib/TestLIE.cpp", "max_stars_repo_name": "HaibingShao/ogs6_ufz", "max_stars_repo_head_hexsha": "d4acfe7132eaa2010157122da67c7a4579b2ebae", "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": "Tests/ProcessLib/TestLIE.cpp", "max_issues_repo_name": "HaibingShao/ogs6_ufz", "max_issues_repo_head_hexsha": "d4acfe7132eaa2010157122da67c7a4579b2ebae", "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": "Tests/ProcessLib/TestLIE.cpp", "max_forks_repo_name": "HaibingShao/ogs6_ufz", "max_forks_repo_head_hexsha": "d4acfe7132eaa2010157122da67c7a4579b2ebae", "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": 24.7692307692, "max_line_length": 82, "alphanum_fraction": 0.5845410628, "num_tokens": 956, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432182679956, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.4777383514746265}}
{"text": "/*=============================================================================\nCopyright 2020 Syed Ali Hasan <alihasan9922@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#define BOOST_TEST_MODULE ecliptic_coord_test\n\n#include <iostream>\n#include <boost/units/io.hpp>\n#include <boost/units/systems/angle/degrees.hpp>\n#include <boost/astronomy/coordinate/coord_sys/ecliptic_coord.hpp>\n\n#include <boost/test/unit_test.hpp>\n\nusing namespace boost::units;\nusing namespace boost::units::si;\nusing namespace boost::astronomy::coordinate;\n\nnamespace bud = boost::units::degree;\n\nBOOST_AUTO_TEST_SUITE(ecliptic_coord_constructors)\n\nBOOST_AUTO_TEST_CASE(ecliptic_coord_default_constructor) {\n    ecliptic_coord<\n            double,\n            quantity<bud::plane_angle>,\n            quantity<bud::plane_angle>>\n            ec;\n\n    //Check set_lat_lon\n        ec.set_lat_lon(45.0 * bud::degrees, 18.0 * bud::degrees);\n\n    //Check values\n    BOOST_CHECK_CLOSE(ec.get_lat().value(), 45.0, 0.001);\n    BOOST_CHECK_CLOSE(ec.get_lon().value(), 18.0, 0.001);\n\n    //Quantities stored as expected?\n    BOOST_TEST((std::is_same<decltype(ec.get_lat()), quantity<bud::plane_angle>>::value));\n    BOOST_TEST((std::is_same<decltype(ec.get_lon()), quantity<bud::plane_angle>>::value));\n}\n\nBOOST_AUTO_TEST_CASE(ecliptic_coord_quantities_constructor) {\n    //Make Ecliptic Coordinate Check\n    auto ec1 = make_ecliptic_coord\n            (15.0 * bud::degrees, 39.0 * bud::degrees);\n\n    //Check values\n    BOOST_CHECK_CLOSE(ec1.get_lat().value(), 15.0, 0.001);\n    BOOST_CHECK_CLOSE(ec1.get_lon().value(), 39.0, 0.001);\n\n    //Quantities stored as expected?\n    BOOST_TEST((std::is_same<decltype(ec1.get_lat()), quantity<bud::plane_angle>>::value));\n    BOOST_TEST((std::is_same<decltype(ec1.get_lon()), quantity<bud::plane_angle>>::value));\n\n    //Ecliptic Coordinate constructor\n    ecliptic_coord<double, quantity<bud::plane_angle>, quantity<bud::plane_angle>>\n            ec2(1.5 * bud::degrees, 9.0 * bud::degrees);\n\n    //Check values\n    BOOST_CHECK_CLOSE(ec2.get_lat().value(), 1.5, 0.001);\n    BOOST_CHECK_CLOSE(ec2.get_lon().value(), 9.0, 0.001);\n\n    //Quantities stored as expected?\n    BOOST_TEST((std::is_same<decltype(ec2.get_lat()), quantity<bud::plane_angle>>::value));\n    BOOST_TEST((std::is_same<decltype(ec2.get_lon()), quantity<bud::plane_angle>>::value));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "c61243af181dba4bdbc036f4ce0831f87cceed2e", "size": 2577, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/coordinate/ecliptic_coord.cpp", "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": "test/coordinate/ecliptic_coord.cpp", "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": "test/coordinate/ecliptic_coord.cpp", "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": 36.2957746479, "max_line_length": 91, "alphanum_fraction": 0.664338378, "num_tokens": 647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432182679957, "lm_q2_score": 0.6619228758499941, "lm_q1q2_score": 0.4777383466611817}}
{"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\u00e4nkt), www.simunova.com. \n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include <iostream>\n#include <string>\n#include <boost/numeric/mtl/mtl.hpp>\n\n\nusing namespace std;\n\n// Function is instantiated 108 times\ntemplate <typename T, typename U>\nvoid inline test3(string type1, T x, string type2, U y)\n{\n    cout << type1 << \" @ \" << type2 << '\\n';\n    // cout << \"As typeid: \" << typeid(x).name() << \" @ \" << typeid(y).name() << '\\n';\n    // cout << x << \" @ \" << y << '\\n';\n\n    cout << x << \" + \" << y << \" = \" << x + y << '\\n';  \n    MTL_THROW_IF(x + y != 8, mtl::runtime_error(\"Result of addition must be 8.\"));  // Integer numbers less then 17 should not have rounding errors\n\n    cout << x << \" - \" << y << \" = \" << x - y << '\\n';\n    MTL_THROW_IF(x - y != 4, mtl::runtime_error(\"Result of subtraction must be 4.\"));\n\n    cout << x << \" * \" << y << \" = \" << x * y << '\\n';\n    MTL_THROW_IF(x * y != 12, mtl::runtime_error(\"Result of subtraction must be 12.\"));\n\n    cout << x << \" / \" << y << \" = \" << x / y << '\\n';\n    MTL_THROW_IF(x / y != 3, mtl::runtime_error(\"Result of subtraction must be 3.\"));\n\n    cout << '\\n';\n}\n\ntemplate <typename T, typename U>\nvoid inline test2(const char* type1, T x, const char* type2, U y)\n{\n    cout << type1 << \" @ \" << type2 << '\\n';\n    cout << \"different_non_complex<T, U> is \" << (mtl::traits::different_non_complex<T, U>::value ? \"true (use my extension)\\n \" : \"false (use standard)\\n\") << \"----\\n\";\n    string ctype1(string(\"complex<\") + type1 + \">\"), ctype2(string(\"complex<\") + type2 + \">\");\n    std::complex<T> cx(x);\n    std::complex<U> cy(y);\n\n    test3(type1, x, ctype2, cy);\n    test3(ctype1, cx, type2, y);\n    test3(ctype1, cx, ctype2, cy);\n}\n\ntemplate <typename T>\nvoid inline test(const char* type1, T x)\n{\n#ifdef ___clang__\n    test2(type1, x, \"int\", 2);\n    test2(type1, x, \"long\", 2l);\n#  if 0 // causes warnings in visual studion and g++ with -pedantic\n    test2(type1, x, \"unsigned\", 2u);\n#  endif\n\n#else\n    std::cerr << \"Warning complex<int> not supported on certain clang compilers.\\n\";\n#endif\n\n    test2(type1, x, \"float\", 2.f);\n    test2(type1, x, \"double\", 2.);\n    test2(type1, x, \"long double\", 2.l);\n}\n\n\nint main(int, char**)\n{\n    using namespace mtl;\n\n    test(\"int\", 6);\n    test(\"long\", 6l);\n#if 0// causes warnings in visual studion and g++ with -pedantic\n    test(\"unsigned\", 6u);\n#endif\n    test(\"float\", 6.f);\n    test(\"double\", 6.);\n    test(\"long double\", 6.l);\n\n    return 0;\n}\n", "meta": {"hexsha": "5503743df5ae4c8f692f6a826dacd566ef2626c1", "size": 2835, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/mixed_complex_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/mixed_complex_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/mixed_complex_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": 30.8152173913, "max_line_length": 169, "alphanum_fraction": 0.580952381, "num_tokens": 888, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975978, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.4777383435511463}}
{"text": "//==================================================================================================\n/*!\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#include <boost/simd/function/scalar/sind.hpp>\n#include <scalar_test.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/minf.hpp>\n#include <boost/simd/constant/nan.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/mone.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/constant/mzero.hpp>\n#include <boost/simd/constant/sqrt_2o_2.hpp>\n\nSTF_CASE_TPL (\" sind\",  STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::sind;\n\n  using r_t = decltype(sind(T()));\n\n  // return type conformity test\n  STF_TYPE_IS(r_t, T);\n\n  // specific values tests\n#ifndef BOOST_SIMD_NO_INVALIDS\n  STF_ULP_EQUAL(sind(bs::Inf<T>()), bs::Nan<r_t>(), 0.5);\n  STF_ULP_EQUAL(sind(bs::Minf<T>()), bs::Nan<r_t>(), 0.5);\n  STF_ULP_EQUAL(sind(bs::Nan<T>()), bs::Nan<r_t>(), 0.5);\n#endif\n  STF_ULP_EQUAL(sind(-T(180)), bs::Zero<r_t>(), 0.5);\n  STF_ULP_EQUAL(sind(-T(45)), -bs::Sqrt_2o_2<r_t>(), 0.5);\n  STF_ULP_EQUAL(sind(-T(90)), -bs::One<r_t>(), 0.5);\n  STF_ULP_EQUAL(sind(bs::Zero<T>()), bs::Zero<r_t>(), 0.5);\n  STF_ULP_EQUAL(sind(T(180)), bs::Zero<r_t>(), 0.5);\n  STF_ULP_EQUAL(sind(T(45)), bs::Sqrt_2o_2<r_t>(), 0.5);\n  STF_ULP_EQUAL(sind(T(90)), bs::One<r_t>(), 0.5);\n}\n", "meta": {"hexsha": "c279f026759e1f1dda051dc8c6dd8f7de457adc2", "size": 1628, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/scalar/sind.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": "test/function/scalar/sind.cpp", "max_issues_repo_name": "remymuller/boost.simd", "max_issues_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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/function/scalar/sind.cpp", "max_forks_repo_name": "remymuller/boost.simd", "max_forks_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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": 35.3913043478, "max_line_length": 100, "alphanum_fraction": 0.5964373464, "num_tokens": 507, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.721743206297598, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.4777383387377017}}
{"text": "/***************************************************************************\n/* Javier Juan Albarracin - jajuaal1@ibime.upv.es                          */\n/* Universidad Politecnica de Valencia, Spain                              */\n/*                                                                         */\n/* Copyright (C) 2014 Javier Juan Albarracin                               */\n/*                                                                         */\n/***************************************************************************\n* Eigen Utils                                                              *\n***************************************************************************/\n\n#ifndef EIGENUTILS_HPP\n#define EIGENUTILS_HPP\n\n#include <Eigen/Dense>\n\nusing namespace Eigen;\n\nclass EigenUtils\n{\npublic:\n\ttemplate <typename Derived>\n\tinline static void removeRow(DenseBase<Derived> &matrix, size_t rowToRemove);\n\ttemplate <typename Derived>\n\tinline static void removeColumn(DenseBase<Derived> &matrix, size_t colToRemove);\n};\n\ntemplate <typename Derived>\nvoid EigenUtils::removeRow(DenseBase<Derived> &matrix, size_t rowToRemove)\n{\n    size_t numRows = matrix.rows() - 1;\n    size_t numCols = matrix.cols();\n\n    if (rowToRemove < numRows)\n        matrix.block(rowToRemove, 0, numRows - rowToRemove, numCols) = matrix.block(rowToRemove + 1, 0, numRows - rowToRemove, numCols);\n\n    matrix.derived().conservativeResize(numRows, numCols);\n}\n\ntemplate <typename Derived>\nvoid EigenUtils::removeColumn(DenseBase<Derived> &matrix, size_t colToRemove)\n{\n    size_t numRows = matrix.rows();\n    size_t numCols = matrix.cols() - 1;\n\n    if (colToRemove < numCols)\n        matrix.block(0, colToRemove, numRows, numCols - colToRemove) = matrix.block(0, colToRemove + 1, numRows, numCols - colToRemove);\n\n    matrix.derived().conservativeResize(numRows, numCols);\n}\n\n#endif", "meta": {"hexsha": "b9485e32d351ffb48452e62b4c3b8708aa1b9220", "size": 1879, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "EigenUtils.hpp", "max_stars_repo_name": "javierjuan/tools", "max_stars_repo_head_hexsha": "fd51855d3babccabc2cf95e9d7ac00c0a390f7fc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "EigenUtils.hpp", "max_issues_repo_name": "javierjuan/tools", "max_issues_repo_head_hexsha": "fd51855d3babccabc2cf95e9d7ac00c0a390f7fc", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "EigenUtils.hpp", "max_forks_repo_name": "javierjuan/tools", "max_forks_repo_head_hexsha": "fd51855d3babccabc2cf95e9d7ac00c0a390f7fc", "max_forks_repo_licenses": ["Apache-2.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.8431372549, "max_line_length": 136, "alphanum_fraction": 0.5263437999, "num_tokens": 356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.47773833873770166}}
{"text": "// Copyright Paul A. Bristow 2015\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//! \\file\n//!\\brief Basic tests for fixed_point.\n\n#include <iomanip>\n#include <sstream>\n#include <string>\n\n#define BOOST_TEST_MODULE test_negatable_basic_basic_ops\n#define BOOST_LIB_DIAGNOSTIC\n\n#include <boost/fixed_point/fixed_point.hpp>\n#include <boost/test/included/unit_test.hpp>\n\nBOOST_AUTO_TEST_CASE(test_negatable_basic_basic_ops)\n{\n  {\n    // Plain fixed-point\n    typedef boost::fixed_point::negatable<32, -16> fixed_point_type;\n\n    const fixed_point_type x = fixed_point_type(-100) / 100;\n\n    std::ostringstream os;\n\n    os << std::setprecision(std::numeric_limits<fixed_point_type>::digits10)\n       << std::fixed\n       << x;\n\n    const std::string reference_string =\n        std::string(\"-1.\")\n      + std::string(std::string::size_type(std::numeric_limits<fixed_point_type>::digits10), char('0'));\n\n    BOOST_CHECK_EQUAL(os.str(), reference_string);\n  }\n\n  {\n    // Plain fixed-point\n    typedef boost::fixed_point::negatable<2, -13> fixed_point_type;\n\n    const fixed_point_type x = fixed_point_type(-1) / 3;\n\n    std::ostringstream os;\n\n    os << std::setprecision(std::numeric_limits<fixed_point_type>::digits10)\n       << std::fixed\n       << x;\n\n    const std::string reference_string =\n        std::string(\"-0.\")\n      + std::string(std::string::size_type(std::numeric_limits<fixed_point_type>::digits10), char('3'));\n\n    BOOST_CHECK_EQUAL(os.str(), reference_string);\n  }\n\n  {\n    // fastest round\n    typedef boost::fixed_point::negatable<13, -2> fixed_point_type_fastest_round;\n\n    const fixed_point_type_fastest_round x = fixed_point_type_fastest_round(-1.26);\n\n    std::ostringstream os;\n\n    os << std::setprecision(std::numeric_limits<fixed_point_type_fastest_round>::digits10)\n       << std::fixed\n       << x;\n\n    const std::string reference_string =\n        std::string(\"-1.25\")\n      + std::string(std::string::size_type(std::numeric_limits<fixed_point_type_fastest_round>::digits10 - int(std::string(\"25\").size())), char('0'));\n\n    BOOST_CHECK_EQUAL(os.str(), reference_string);\n  }\n}\n", "meta": {"hexsha": "f133c6276f5f9200bfa32ed907feb074e0e08bc0", "size": 2250, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_negatable_basic_basic_ops.cpp", "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": "test/test_negatable_basic_basic_ops.cpp", "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": "test/test_negatable_basic_basic_ops.cpp", "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": 28.125, "max_line_length": 150, "alphanum_fraction": 0.6951111111, "num_tokens": 562, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217431943271999, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.47773833562766604}}
{"text": "#include \"electronthresholds.h\"\n#include \"python/pyreader.h\"\n\n#include <algorithm>\n#include <cmath>\n#include <random>\n\n#include <Eigen/Dense>\n#include <unsupported/Eigen/LevenbergMarquardt>\n\nnamespace stempy {\n\ntemplate <typename T>\ndouble calculateMean(std::vector<T>& values)\n{\n  return std::accumulate(values.begin(), values.end(), 0.0) / values.size();\n}\n\ntemplate <typename T>\ndouble calculateVariance(std::vector<T>& values, double mean)\n{\n  double v1 = 0;\n  double sigma2;\n\n  for (size_t i = 0; i < values.size(); i++) {\n    v1 += pow(values[i] - mean, 2.0);\n  }\n  sigma2 = v1 / (values.size() - 1.0);\n\n  return sigma2;\n}\n\nstruct GaussianErrorFunctor : Eigen::DenseFunctor<double>\n{\n\n  GaussianErrorFunctor(const Eigen::VectorXd& bins,\n                       const Eigen::VectorXd& histogram)\n    : Eigen::DenseFunctor<double>(3, bins.rows()), m_bins(bins),\n      m_histogram(histogram)\n  {}\n\n  int operator()(const InputType& x, ValueType& fvec)\n  {\n    auto num = -(m_bins - ValueType::Constant(values(), x[1])).array().square();\n    auto variance = pow(x[2], 2);\n\n    fvec = x[0] * (num / (2 * variance)).exp() - m_histogram.array();\n\n    return 0;\n  }\n\n  int df(const InputType& x, JacobianType& jacobian)\n  {\n    auto means = ValueType::Constant(values(), x[1]);\n    auto tmp = (m_bins - means).array();\n    auto num = -tmp.square();\n    auto variance = pow(x[2], 2);\n    auto den = 2 * variance;\n\n    auto j0 = (num / den).exp();\n    auto j1 = x[0] * tmp * j0 / variance;\n\n    jacobian.col(0) = j0;\n    jacobian.col(1) = j1;\n    jacobian.col(2) = tmp * j1 / x[2];\n\n    return 0;\n  }\n\n  Eigen::VectorXd m_bins;\n  Eigen::VectorXd m_histogram;\n};\n\ntemplate <typename BlockType, typename FrameType, bool dark>\nCalculateThresholdsResults<FrameType> calculateThresholds(\n  std::vector<BlockType>& blocks, const float darkReference[],\n  int numberOfSamples, double backgroundThresholdNSigma,\n  double xRayThresholdNSigma, const float gain[])\n{\n  auto frameDimensions = blocks[0].header.frameDimensions;\n  auto numberOfPixels = frameDimensions.first * frameDimensions.second;\n\n  // Setup random number engine\n  std::random_device randomDevice;\n  std::default_random_engine randomEngine(randomDevice());\n\n  int numberSamplePixels =\n    frameDimensions.first * frameDimensions.second * numberOfSamples;\n  std::vector<FrameType> samples(numberSamplePixels, 0);\n  for (int i = 0; i < numberOfSamples; i++) {\n    std::uniform_int_distribution<int> randomBlockDist(0, blocks.size() - 1);\n    auto randomBlockIndex = randomBlockDist(randomEngine);\n    auto randomBlock = blocks[randomBlockIndex];\n    std::uniform_int_distribution<int> randomFrameDist(\n      0, randomBlock.header.imagesInBlock - 1);\n    auto randomFrameIndex = randomFrameDist(randomEngine);\n    auto blockData = randomBlock.data.get();\n\n    for (unsigned j = 0; j < numberOfPixels; j++) {\n      // For now just use the index, the image number don't seem to work, in the\n      // current data set. In the future we should be using the image number.\n\n      // This will be evaluated a compile time.\n      if (std::is_integral<FrameType>::value) {\n        auto value = blockData[randomFrameIndex * numberOfPixels + j];\n        static_if<dark>(\n          [&]() { value -= static_cast<int16_t>(darkReference[j]); })();\n        samples[i * numberOfPixels + j] = value;\n      }\n      // if not integral type then we know we have gain and need to multiple\n      else {\n        auto value = blockData[randomFrameIndex * numberOfPixels + j] * gain[j];\n        static_if<dark>(\n          [&]() { value -= static_cast<float>(darkReference[j]); })();\n        samples[i * numberOfPixels + j] = value;\n      }\n    }\n  }\n\n  // Calculate stats\n  auto mean = calculateMean(samples);\n  auto variance = calculateVariance(samples, mean);\n  auto stdDev = sqrt(variance);\n  auto xrayThreshold = mean + xRayThresholdNSigma * stdDev;\n\n  // Now generate a histograms\n  auto minMax = std::minmax_element(samples.begin(), samples.end());\n  auto minSample = *minMax.first;\n  auto maxSample = static_cast<FrameType>(std::ceil(*minMax.second));\n  auto maxBin = std::min(static_cast<int>(maxSample),\n                         static_cast<int>(mean + xrayThreshold * stdDev));\n  auto minBin = std::max(static_cast<int>(minSample),\n                         static_cast<int>(mean - xrayThreshold * stdDev));\n\n  auto numberOfBins = maxBin - minBin;\n  std::vector<double> histogram(numberOfBins, 0.0);\n  std::vector<double> bins(numberOfBins);\n\n  auto binEdge = minBin;\n  for (int i = 0; i < numberOfBins; i++) {\n    bins[i] = binEdge++;\n  }\n\n  // Bin the values\n  for (int i = 0; i < numberSamplePixels; i++) {\n    auto binIndex = static_cast<int>(samples[i] - minBin);\n    // Skip values outside range\n    if (binIndex >= numberOfBins) {\n      continue;\n    }\n    histogram[binIndex] += 1;\n  }\n\n  auto b = Eigen::Map<Eigen::VectorXd>(bins.data(), bins.size());\n  auto h = Eigen::Map<Eigen::VectorXd>(histogram.data(), histogram.size());\n\n  GaussianErrorFunctor gef(b, h);\n  Eigen::VectorXd state(3);\n  auto indexOfMaxElement =\n    std::max_element(histogram.begin(), histogram.end()) - histogram.begin();\n  state << static_cast<double>(histogram[indexOfMaxElement]), mean, stdDev;\n\n  Eigen::LevenbergMarquardt<GaussianErrorFunctor> solver(gef);\n  solver.minimize(state);\n\n  if (solver.info() != Eigen::ComputationInfo::Success) {\n    throw std::runtime_error(\"Optimization did not converge\");\n  }\n\n  auto optimizedMean = state[1];\n  auto optimizedStdDev = fabs(state[2]);\n\n  auto backgroundThreshold =\n    optimizedMean + optimizedStdDev * backgroundThresholdNSigma;\n\n  CalculateThresholdsResults<FrameType> ret;\n  ret.numberOfSamples = numberOfSamples;\n  ret.minSample = minSample;\n  ret.maxSample = maxSample;\n  ret.mean = mean;\n  ret.variance = variance;\n  ret.stdDev = stdDev;\n  ret.numberOfBins = numberOfBins;\n  ret.xRayThresholdNSigma = xRayThresholdNSigma;\n  ret.backgroundThresholdNSigma = backgroundThresholdNSigma;\n  ret.xRayThreshold = xrayThreshold;\n  ret.backgroundThreshold = backgroundThreshold;\n  ret.optimizedMean = optimizedMean;\n  ret.optimizedStdDev = optimizedStdDev;\n\n  return ret;\n}\n\n// Without gain\ntemplate <typename BlockType>\nCalculateThresholdsResults<uint16_t> calculateThresholds(\n  std::vector<BlockType>& blocks, Image<float>& darkreference,\n  int numberOfSamples, double backgroundThresholdNSigma,\n  double xRayThresholdNSigma)\n{\n  return calculateThresholds<BlockType, uint16_t>(\n    blocks, darkreference.data.get(), numberOfSamples,\n    backgroundThresholdNSigma, xRayThresholdNSigma, nullptr);\n}\n\ntemplate <typename BlockType>\nCalculateThresholdsResults<uint16_t> calculateThresholds(\n  std::vector<BlockType>& blocks, const float darkreference[],\n  int numberOfSamples, double backgroundThresholdNSigma,\n  double xRayThresholdNSigma)\n{\n  return calculateThresholds<BlockType, uint16_t>(\n    blocks, darkreference, numberOfSamples, backgroundThresholdNSigma,\n    xRayThresholdNSigma, nullptr);\n}\n\n// With gain\ntemplate <typename BlockType>\nCalculateThresholdsResults<float> calculateThresholds(\n  std::vector<BlockType>& blocks, Image<float>& darkreference,\n  int numberOfSamples, double backgroundThresholdNSigma,\n  double xRayThresholdNSigma, const float gain[])\n{\n  return calculateThresholds<BlockType, float>(\n    blocks, darkreference.data.get(), numberOfSamples,\n    backgroundThresholdNSigma, xRayThresholdNSigma, gain);\n}\n\n// Without gain, without darkreference\ntemplate <typename BlockType>\nCalculateThresholdsResults<uint16_t> calculateThresholds(\n  std::vector<BlockType>& blocks, int numberOfSamples,\n  double backgroundThresholdNSigma, double xRayThresholdNSigma)\n{\n  return calculateThresholds<BlockType, uint16_t, false>(\n    blocks, nullptr, numberOfSamples, backgroundThresholdNSigma,\n    xRayThresholdNSigma, nullptr);\n}\n\n// With gain\ntemplate CalculateThresholdsResults<float> calculateThresholds<Block>(\n  std::vector<Block>& blocks, Image<float>& darkReference, int numberOfSamples,\n  double backgroundThresholdNSigma, double xRayThresholdNSigma,\n  const float gain[]);\ntemplate CalculateThresholdsResults<float> calculateThresholds<PyBlock>(\n  std::vector<PyBlock>& blocks, Image<float>& darkReference,\n  int numberOfSamples, double backgroundThresholdNSigma,\n  double xRayThresholdNSigma, const float gain[]);\ntemplate CalculateThresholdsResults<float> calculateThresholds<Block, float, true>(\n  std::vector<Block>& blocks, const float darkReference[], int numberOfSamples,\n  double backgroundThresholdNSigma, double xRayThresholdNSigma,\n  const float gain[]);\ntemplate CalculateThresholdsResults<uint16_t> calculateThresholds<Block>(\n  std::vector<Block>& blocks, const float darkReference[], int numberOfSamples,\n  double backgroundThresholdNSigma, double xRayThresholdNSigma,\n  const float gain[]);\ntemplate CalculateThresholdsResults<float> calculateThresholds<PyBlock, float, true>(\n  std::vector<PyBlock>& blocks, const float darkReference[],\n  int numberOfSamples, double backgroundThresholdNSigma,\n  double xRayThresholdNSigma, const float gain[]);\n\n// No gain\ntemplate CalculateThresholdsResults<uint16_t> calculateThresholds<Block>(\n  std::vector<Block>& blocks, Image<float>& darkReference, int numberOfSamples,\n  double backgroundThresholdNSigma, double xRayThresholdNSigma);\ntemplate CalculateThresholdsResults<uint16_t> calculateThresholds<PyBlock>(\n  std::vector<PyBlock>& blocks, Image<float>& darkReference,\n  int numberOfSamples, double backgroundThresholdNSigma,\n  double xRayThresholdNSigma);\ntemplate CalculateThresholdsResults<uint16_t> calculateThresholds<Block>(\n  std::vector<Block>& blocks, const float darkReference[], int numberOfSamples,\n  double backgroundThresholdNSigma, double xRayThresholdNSigma);\ntemplate CalculateThresholdsResults<uint16_t> calculateThresholds<PyBlock>(\n  std::vector<PyBlock>& blocks, const float darkReference[],\n  int numberOfSamples, double backgroundThresholdNSigma,\n  double xRayThresholdNSigma);\n\ntemplate CalculateThresholdsResults<uint16_t>\ncalculateThresholds<Block, uint16_t, false>(std::vector<Block>& blocks,\n                                            const float darkReference[],\n                                            int numberOfSamples,\n                                            double backgroundThresholdNSigma,\n                                            double xRayThresholdNSigma,\n                                            const float gain[]);\ntemplate CalculateThresholdsResults<uint16_t>\ncalculateThresholds<PyBlock, uint16_t, false>(std::vector<PyBlock>& blocks,\n                                              const float darkReference[],\n                                              int numberOfSamples,\n                                              double backgroundThresholdNSigma,\n                                              double xRayThresholdNSigma,\n                                              const float gain[]);\n\ntemplate CalculateThresholdsResults<float>\ncalculateThresholds<Block, float, false>(std::vector<Block>& blocks,\n                                         const float darkReference[],\n                                         int numberOfSamples,\n                                         double backgroundThresholdNSigma,\n                                         double xRayThresholdNSigma,\n                                         const float gain[]);\ntemplate CalculateThresholdsResults<float>\ncalculateThresholds<PyBlock, float, false>(std::vector<PyBlock>& blocks,\n                                           const float darkReference[],\n                                           int numberOfSamples,\n                                           double backgroundThresholdNSigma,\n                                           double xRayThresholdNSigma,\n                                           const float gain[]);\n\n// No gain or dark reference\ntemplate CalculateThresholdsResults<uint16_t> calculateThresholds(\n  std::vector<Block>& blocks, int numberOfSamples,\n  double backgroundThresholdNSigma, double xRayThresholdNSigma);\n\ntemplate CalculateThresholdsResults<uint16_t> calculateThresholds(\n  std::vector<PyBlock>& blocks, int numberOfSamples,\n  double backgroundThresholdNSigma, double xRayThresholdNSigma);\n}\n", "meta": {"hexsha": "81a7bf8bdfe594317866b5d260cdb9c9edfe1c48", "size": 12223, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "stempy/electronthresholds.cpp", "max_stars_repo_name": "jerenner/stempy", "max_stars_repo_head_hexsha": "815136092a86b4a61ff9dc1c0cdd98389c196b5c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2019-11-08T11:13:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T19:58:25.000Z", "max_issues_repo_path": "stempy/electronthresholds.cpp", "max_issues_repo_name": "jerenner/stempy", "max_issues_repo_head_hexsha": "815136092a86b4a61ff9dc1c0cdd98389c196b5c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 146.0, "max_issues_repo_issues_event_min_datetime": "2018-12-27T16:00:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T23:06:04.000Z", "max_forks_repo_path": "stempy/electronthresholds.cpp", "max_forks_repo_name": "jerenner/stempy", "max_forks_repo_head_hexsha": "815136092a86b4a61ff9dc1c0cdd98389c196b5c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2019-04-08T11:16:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-25T21:59:24.000Z", "avg_line_length": 38.5583596215, "max_line_length": 85, "alphanum_fraction": 0.6895197578, "num_tokens": 2736, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382200964035, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.47769749747803175}}
{"text": "#include <stdio.h>\n#include <FileLoop.h>\n#include <FileWvOut.h>\n#include <Fir.h>\n#include <string.h>\n#include <math.h>\n#include <vector>\n#include <Eigen/Eigen>\n#include <Eigen/Dense>\n\n#include \"kiss_fftr.h\"\n#include \"FIRFilterCode.h\"\n#include \"eigen_to_image.h\"\n\n#include \"ChunkStats.h\"\n#include \"Chunk.h\"\n\nusing namespace stk;\n\nusing Eigen::MatrixXf;\nusing Eigen::MatrixXi;\nusing std::list;\n\n//main test\nvoid process_song(std::string fn_in, std::string fn_out);\n\n//thing with fourier transform\nMatrixXf TFD_extract(FileWvIn input, int nfft, int total_slices, int samples_per_slice, int channels);\nvoid TFDI_extract(kiss_fft_cpx* fft_input, int nfft, int samples_per_slice, StkFrames output);\n\n\n//filtering methods\n//using stk\nvoid make_fir_bandpass_filter(double* coefs, int taps, int freq_center, int freq_margin,  int max_freq);\nstk::Fir create_fir_from_coefs(double* coefs, int len);\nstk::Fir create_1d_gaussian_filter(int length, double amplitude, double center, double stddev);\n//using eigen\nMatrixXf create_1d_gaussian_filter_col(int length, double amplitude, double stddev);\nMatrixXf create_1d_gaussian_filter_row(int length, double amplitude, double stddev);\nMatrixXf one_d_convolve(MatrixXf mat, MatrixXf kern);\nMatrixXf dog(MatrixXf full, MatrixXf gauss);\n\n//chunking functions\ndouble snaz(MatrixXf filt, int snazr);\nMatrixXi chunkify(MatrixXf tfd, int vert_range, int horz_range);\n//list(Chunk) cull_chunks(MatrixXi chunk_ids, ChunkStats stats)\nlist<Chunk> cull_chunks(ChunkStats stats);\n\nint main() {\n  std::string file_in = \"./sound/tsu.wav\";\n  std::string file_out = \"./pet.wav\";\n\n  process_song(file_in, file_out);\n\n  return 0;\n}\n\n\nvoid process_song(std::string fn_in, std::string fn_out) {\n  FileRead song;\n  FileWvIn input;\n  FileWvOut output;\n  fn_in = \"./sound/tsu.wav\";\n  fn_out = \"pet.wav\";\n  song.open(fn_in, 2);\n  input.openFile(fn_in);\n  output.openFile(fn_out, 2, FileWrite::FILE_WAV, Stk::STK_SINT16);\n\n  int channels = input.channelsOut();\n  long samples = song.fileSize();\n  long samples_length = samples / channels;\n  double file_rate = input.getFileRate();\n  double len_in_sec = samples_length / file_rate;\n   \n  \n  \n  int samples_per_slice = 1024;\n  double slices_per_second = file_rate / samples_per_slice;\n  int total_slices = ceil(samples_length / samples_per_slice);\n\n  int max_freq = file_rate / 2;\n  //kiss_fft mentions that the fftr only populates nfft/2 + 1 things \n  //guessing that means I initialize with nfft, then only look at nfft/2 + 1 results?\n  //actualyl nfft should just be length of sample. is also the resulting frequency resolution.\n\n\n  bool filter_test = false;\n  if (filter_test) {\n    FileWvOut filteredOut;\n    filteredOut.openFile(\"hi.wav\", 2, FileWrite::FILE_WAV, Stk::STK_SINT16);\n  \n    StkFrames slice(samples_per_slice, channels);\n    int taps = 60;\n    double coefs[taps];\n    make_fir_bandpass_filter(coefs, taps, max_freq / 2, max_freq / 64, max_freq);\n    stk::Fir bp = create_fir_from_coefs(coefs, taps);\n    input.reset();\n\n    for (int slice_i = 0; slice_i < total_slices; slice_i++) {\n      input.tick(slice);\n      for (int chan_i = 0; chan_i < channels; chan_i++) {\n\tbp.tick(slice, chan_i);\n      }\n      filteredOut.tick( slice );\n    }\n    input.reset();\n  }\n\n\n  int nfft = samples_per_slice;\n\n  //generate time-frequency distribution\n  MatrixXf tfd = TFD_extract(input, nfft, total_slices, samples_per_slice, channels);\n  \n  write_eigen_to_file(\"some_spectogram.png\", tfd);\n  //test out convolution code\n  MatrixXf guass_col = create_1d_gaussian_filter_col(16, 1, 1);\n  MatrixXf guass_row = create_1d_gaussian_filter_row(16, 1, 1);\n  MatrixXf sobel_x (1,3);\n  MatrixXf sobel_y (3,1);\n  //3x3 sobels but I only implemented 1d convolution :(\n  //sobel_x << -1, 0, 1, -3, 0, 3, -1, 0, 1;\n  //sobel_y << -1, -3, -1, 0, 0, 0, 1, 3, 1;\n  sobel_x << -1, 0, 1;\n  sobel_y << -1, 0, 1;\n\n  MatrixXf tfd_y = one_d_convolve(tfd, sobel_y);\n  MatrixXf tfd_x = one_d_convolve(tfd, sobel_x);\n\n  write_eigen_to_file(\"y_sobel_spectogram.png\", tfd_y);\n  write_eigen_to_file(\"x_sobel_spectogram.png\", tfd_x);\n  \n  \n  MatrixXf sobel = one_d_convolve(tfd, sobel_y);\n  sobel = one_d_convolve(sobel, sobel_x);\n  write_eigen_to_file(\"abs_sobel_spectogram.png\", sobel);\n  \n  //chunkify(sobel, 1,2);\n\n  MatrixXf result = one_d_convolve(tfd, guass_col);\n  result = one_d_convolve(result, guass_row);\n  write_eigen_to_file(\"gauss_spectogram.png\", result);\n  MatrixXf dogg = dog(tfd, result);\n  write_eigen_to_file(\"dog_spectogram.png\", dogg);\n\n  MatrixXf x_sobeled_dog = one_d_convolve(dogg, sobel_x);\n  MatrixXf y_sobeled_dog = one_d_convolve(dogg, sobel_y);\n  \n  write_eigen_to_file(\"x_sobel_dog_spectogram.png\", x_sobeled_dog * 100);\n  write_eigen_to_file(\"y_sobel_dog_spectogram.png\", y_sobeled_dog * 100);\n  int vert = 1;\n  int horz = 2;\n  MatrixXi chunk_ids = chunkify(y_sobeled_dog, vert,horz);\n  //MatrixXi stats = chunk_stats(chunk_ids);\n  ChunkStats stats = ChunkStats(chunk_ids);\n  list<Chunk> y_imps = cull_chunks(stats);\n  chunk_ids = chunkify(x_sobeled_dog, vert,horz);\n  stats = ChunkStats(chunk_ids);\n  list<Chunk> x_imps = cull_chunks(stats);\n  list<Chunk> all_imps;\n  all_imps.insert(all_imps.begin(), x_imps.begin(), x_imps.end());\n  all_imps.insert(all_imps.begin(), y_imps.begin(), y_imps.end());\n  std::cout << \"length of joined list is \" << all_imps.size() << \"\\n\";\n\t\t\t\t\t\t    \n    /// close files\n  song.close();\n  input.closeFile();\n  output.closeFile();\n}\n\n//extract the time-frequency distribution of a song\n//going to have it return eigen \nMatrixXf TFD_extract(FileWvIn input, int nfft, int total_slices, int samples_per_slice, int channels) {\n  bool is_inverse = false;\n  //numbe of binds fft puts things into. apparently it's the same as nfft.\n  //since nothing is placed in the upper half, divide by 2\n  //though if you want to play around with inverse fft, just set to nfft I think?\n  int freq_chunks = nfft / 2;\n  kiss_fftr_cfg cfg = kiss_fftr_alloc( nfft ,is_inverse,0,0 );\n  size_t input_size = sizeof(kiss_fft_scalar) * samples_per_slice;\n  size_t output_size = sizeof(kiss_fft_cpx) * freq_chunks;\n  kiss_fft_scalar* fft_input =(kiss_fft_scalar*)KISS_FFT_MALLOC(input_size);\n  kiss_fft_cpx* fft_output =(kiss_fft_cpx*)KISS_FFT_MALLOC(output_size);\n  bool print = false;\n  StkFrames slice(samples_per_slice, channels);\n  StkFrames single_chan(samples_per_slice, 1);\n\n  MatrixXf tfd = MatrixXf(freq_chunks, total_slices); \n  tfd.setZero();\n  for (int slice_i = 0; slice_i < total_slices; slice_i++) {\n    input.tick(slice);\n    for (int i = 0; i < channels; i++) {\n      slice.getChannel(i, single_chan, 0);\n      for (int i = 0; i < samples_per_slice; i++) {\n\tfft_input[i] = single_chan[i];\n      }\n      kiss_fftr(cfg, fft_input, fft_output);\n      for (int freq_i = 0; freq_i < freq_chunks; freq_i++) {\n\tkiss_fft_cpx a = fft_output[freq_i];\n\tdouble modulus =  pow(a.r, 2) + pow(a.i, 2);\n\tif (print) {\n\t  std::cout << modulus << \" \";\n\t}\n\t//plus equals to get both channels\n\ttfd(freq_i, slice_i) += modulus;\n      }\n      if (print) {\n\tstd::cout << \"\\n\";\n      }\n    }\n  }\n  std::cout << tfd(tfd.rows() / 4, tfd.cols() - 1) << \"\\n\";\n  kiss_fftr_free(cfg);\n  return tfd;\n}\n\n//do the inverse of the TFD, which I guess just returns the original input amplitudes?\n//call this inside the regular TFD extract, hand in cpx, output some scalar value into some passed in stk-frame output, then in tfd, tick that to some output file\nvoid TFDI_extract(kiss_fft_cpx* fft_input, int nfft, int samples_per_slice, StkFrames output) {\n  bool print = true;\n  bool is_inverse = true;\n  int freq_chunks = nfft / 2 + 1;\n  kiss_fftr_cfg cfg = kiss_fftr_alloc( nfft ,is_inverse,0,0 );\n  //just swapped the input/output sizes \n  //actually don't even need the input size since data is handed in\n  //size_t input_size = sizeof(kiss_fft_cpx) * freq_chunks;\n  size_t output_size = sizeof(kiss_fft_scalar) * samples_per_slice;\n\n  kiss_fft_scalar* fft_output =(kiss_fft_scalar*)KISS_FFT_MALLOC(output_size);\n\n  \n  //kiss_fftri(cfg, fft_input, fft_output);\n  //output is a bunch of scalars, put into some stack frame\n  for (int freq_i = 0; freq_i < samples_per_slice; freq_i++) {\n    kiss_fft_scalar a = fft_output[freq_i];\n    if (print) {\n      std::cout << a << \" \";\n    }\n    output[freq_i] = a;\n  }\n  if (print) {\n    std::cout << \"\\n\";\n  }\n  kiss_fftr_free(cfg);\n}\n\n//creates a 1-dimensional gaussian filter, as an stk finite impulse response filter\n//  int filter_size = 20;\n//  Fir gaussian_filt = create_1d_gaussian_filter(20, 1, filter_size / 2, 1);\nstk::Fir create_1d_gaussian_filter(int length, double amplitude, double center, double stddev) {\n  std::vector<StkFloat> kernel(0);\n  StkFloat val = 0;\n  double exp = 0;\n  for (int i = 0; i < length; i++) {\n    exp = -1 * pow(i - center, 2) / stddev;\n    val = amplitude * pow(M_E, exp);\n    kernel.insert(kernel.begin(), val);\n  }\n  Fir ret (kernel);\n  return ret;\n}\n\nMatrixXf create_1d_gaussian_filter_col(int length, double amplitude, double stddev) {\n  MatrixXf kern (1, length);\n  float val = 0;\n  double exp = 0;\n  double center = (double)length / 2;\n  for (int i = 0; i < length; i++) {\n    exp = -1 * pow(i - center, 2) / stddev;\n    val = amplitude * pow(M_E, exp);\n    kern(0,i) = val;\n  }\n  return kern;;\n}\n\nMatrixXf create_1d_gaussian_filter_row(int length, double amplitude, double stddev) {\n  return create_1d_gaussian_filter_col(length, amplitude, stddev).transpose();\n}\n\n\nvoid make_fir_bandpass_filter(double* coefs, int taps, int freq_center, int freq_margin,  int max_freq) {\n  double rel_center = (double)freq_center / max_freq;\n  double rel_margin = (double)freq_margin / max_freq;\n  TFIRPassTypes band = firBPF;\n  TWindowType wt = wtSINC;\n  double some_window_param = 10;\n  RectWinFIR(coefs, taps, band, rel_center, rel_margin);\n  FIRFilterWindow(coefs, taps, wt, some_window_param);\n}\n\nstk::Fir create_fir_from_coefs(double* coefs, int len) {\n  std::vector<StkFloat> kernel(0);\n  StkFloat val = 0;\n  for (int i = 0; i < len; i++) {\n    val = coefs[i];\n    kernel.insert(kernel.begin(), val);\n  }\n  Fir ret (kernel);\n  return ret;\n}\n\nMatrixXf one_d_convolve(MatrixXf mat, MatrixXf kern) {\n  //perform valid 1d convolution on matrix\n  //or cross-corelation, planning on using symetric kernels so doesn't matter\n  int res_dim;\n  int kern_dim = -1;\n  MatrixXf temp, result;\n  int d_start, d_end, d_width;\n  \n  if (kern.rows() == 1) {\n    result = MatrixXf(mat.rows(), mat.cols() - (kern.cols() - 1));\n    result.setZero();\n    res_dim = result.cols();\n    d_width = mat.rows();\n    kern_dim = kern.cols();\n    for (int i = 0; i < kern_dim; i++) {\n      d_start = i;\n      d_end = res_dim;\n      temp = mat.block(0,d_start, d_width, d_end);\n      result += temp * kern(0,i);\n    }\n  }\n  else if (kern.cols() == 1) {\n    result = MatrixXf(mat.rows() - (kern.rows() - 1), mat.cols());\n    result.setZero();\n    res_dim = result.rows();\n    d_width = mat.cols();\n    kern_dim = kern.rows();\n    for (int i = 0; i < kern_dim; i++) {\n      d_start = i;\n      d_end = res_dim;\n      temp = mat.block(d_start, 0, d_end, d_width);\n      result += temp * kern(i, 0);\n    }\n  }\n  else {\n    //error, kernel is not 1d\n  }\n  if (kern_dim % 2 == 0) {\n    //kernel has even dim and doesn't have a perfect center index, funky stuff may happen\n  }\n  return result;\n}\n\n\nMatrixXf dog(MatrixXf full, MatrixXf gauss) {\n  int f_rows = full.rows();\n  int f_cols = full.cols();\n  int g_rows = gauss.rows();\n  int g_cols = gauss.cols();\n  if (f_rows == g_rows && f_cols == g_cols) {\n    return full - gauss;\n  }\n  else {\n    MatrixXf temp = full.block((f_rows - g_rows) / 2, (f_cols - g_cols) / 2, g_rows, g_cols);\n    temp = temp - gauss;\n    return temp.cwiseAbs();\n  }\n}\n\n//stands for sub nonzero-average zeroing\n//take average of all non-zero elements, zero anything below average\n//takes matrix and rounds to apply snaz, zeros values in matrix\n//returns average of penultimate round\n//having snazr as anything above 1 is typically excessive, consider at most using 2\ndouble snaz(MatrixXf filt, int snazr) {\n  int freq_range = filt.rows();\n  int time_range = filt.cols();\n  double nz_tot = 0;\n  double nz_avg = 0;\n  int nz_count = 0;\n  float val = 0;\n  for (int i = 0; i <= snazr; i++) {\n    nz_tot = 0;\n    nz_count = 0;\n    //don't want to include zeros in average, can't use builtin sum methods, have to traverse :(\n    //combined two tasks in one, do the sub_average zeroing then compute new average\n    //need to to 1 final loop after outermost for loop finishes to do final sub_average zeroing\n    //accomplished by using i <= snazr and only recomputing nz_avg if i < snazr\n    for (int freq_i = 0; freq_i < freq_range; freq_i++) {\n      for (int time_i = 0; time_i < time_range; time_i++) {\n\tval = filt(freq_i, time_i);\n\tif (val < nz_avg) {\n\t  filt(freq_i, time_i) = 0.0;\n\t}\n\telse {\n\t  if (i < snazr) {\n\t    nz_tot += val;\n\t    nz_count++;\n\t  }\n\t}\n      }\n    }\n    if (i < snazr) {\n      nz_avg = nz_tot / nz_count;\n      std::cout << \"non-zero average for round \" << i << \" is \" << nz_avg << \"\\n\";\n    }\n  }\n  return nz_avg;\n}\n\nMatrixXi chunkify(MatrixXf tfd, int vert_range, int horz_range) {\n  //chunkify the input matrix\n  //defining chunkify as assign groups of sound in tfd that are signifigant together\n  //do this by locally grouping cells within proximity in matrix\n  //output is a new matrix, same dimensions, values are positive intergers\n  //zero indicated cell wasn't assigned a chunk\n  //positive integer represents some group id to which the cell got assigned to\n  int chunk_id = 0;\n  int freq_range = tfd.rows();\n  int time_range = tfd.cols();\n  int temp_i = -1;\n  int temp = 0;\n  float nz_avg = 0;\n  MatrixXf filt (freq_range, time_range);\n  MatrixXi chunk_ids (freq_range, time_range);\n  filt << tfd;\n  chunk_ids.setZero( );\n  //threshold values < average to zero\n  //do this to not care about very minor sounds\n  //sub-nonzero-average-zeroing rounds\n  nz_avg = snaz(filt, 1);\n  \n  //isn't a perfect grouping algorithim, since the local grouping is kind of naive\n  //hoping further culling methods down the line will get rid of bad groups\n  //but loop could be improved by having a more robust/expensive joining loop(s)\n  for (int time_i = 0; time_i < time_range; time_i++) {\n    for (int freq_i = 0; freq_i < freq_range; freq_i++) {\n      if (filt(freq_i, time_i) > nz_avg) {\n\t//check if you want to join it vertically\n\tfor (int freq_off = 1; freq_off <= vert_range; freq_off++) {\n\t  //group into chunks within freq_off indexes below current cell \n\t  temp_i = freq_i - freq_off;\n\t  if (temp_i >= 0) {\n\t    temp = chunk_ids(temp_i, time_i);\n\t    if (temp != 0) {\n\t      chunk_ids(freq_i, time_i) = temp;\n\t      break;\n\t    }\n\t  }\n\t  else {\n\t    break;\n\t  }\n\t}\n\t//check if you want to join it horizontally, potentially overwriting vertical joins\n\tfor (int time_off = 1; time_off <= horz_range; time_off++) {\n\t  temp_i = time_i - time_off;\n\t  if (temp_i >= 0) {\n\t    temp = chunk_ids(freq_i, temp_i);\n\t    if (temp != 0) {\n\t      chunk_ids(freq_i, time_i) = temp;\n\t      break;\n\t    }\n\t  }\n\t  else {\n\t    break;\n\t  }\n\t}\n\t//else assigning to a new group\n\tif (chunk_ids(freq_i, time_i) == 0) {\n\t  chunk_ids(freq_i, time_i) = ++chunk_id;\n\t}\n      }\n    }\n  }\n  //basic error checking, making sure sufficiently low values aren't being assigned chunk_ids\n  for (int time_i = 0; time_i < time_range; time_i++) {\n    for (int freq_i = 0; freq_i < freq_range; freq_i++) {\n      if (chunk_ids(freq_i, time_i) != 00 && filt(freq_i, time_i) < nz_avg) {\n\tstd::cout << filt(freq_i, time_i) <<  \"bad! \";\n      }\n    }\n  }\n  return chunk_ids;\n}\n\nlist<Chunk> cull_chunks(ChunkStats stats) {\n  //wait I don't even need the chunkids anymore \n  \n  //thinking of returning a linked list of chunk objects\n  //because working with matrixes will probably be annoying past this point\n\n\n  list<Chunk> chunk_list;\n  MatrixXi sizes = stats.get_size();\n  int chunks = sizes.rows();\n  //ignoring chunk_id 0\n  sizes = stats.get_size().block(1,0, chunks - 1,1);\n  chunks = sizes.rows();\n\n  double average_size = (float)sizes.sum() / sizes.sum();\n  MatrixXi minf = stats.get_min_freq();\n  MatrixXi maxf = stats.get_max_freq();\n  MatrixXi mint = stats.get_min_time();\n  MatrixXi maxt = stats.get_max_time();\n  int chunk_count = 0;\n  for (int i = 0; i < chunks; i++) {\n    if (sizes(i) > average_size) {\n      //gather min, max, delta of time and frequency, construct a chunk\n      //find a better name for chunks to many things have chunk in the name\n      chunk_count++;\n      Chunk temp = Chunk(minf(i), maxf(i), mint(i), maxt(i));\n      chunk_list.insert(chunk_list.begin(), temp);\n    }\n  }\n  std::cout << \"original size was \" << chunks << \" culled size is \" << chunk_count << \"\\n\";\n  return chunk_list; \n}\n", "meta": {"hexsha": "3eb9043ec7a34892fffbcc2258736412e3b7cb73", "size": 16711, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test.cpp", "max_stars_repo_name": "nudon/ubiquitous-chainsaw", "max_stars_repo_head_hexsha": "e1de3d426665925a8c8fe449a0cc0a4cd1604939", "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/test.cpp", "max_issues_repo_name": "nudon/ubiquitous-chainsaw", "max_issues_repo_head_hexsha": "e1de3d426665925a8c8fe449a0cc0a4cd1604939", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-12T08:57:29.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-18T13:31:01.000Z", "max_forks_repo_path": "src/test.cpp", "max_forks_repo_name": "nudon/ubiquitous-chainsaw", "max_forks_repo_head_hexsha": "e1de3d426665925a8c8fe449a0cc0a4cd1604939", "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.8310412574, "max_line_length": 162, "alphanum_fraction": 0.6797917539, "num_tokens": 5011, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412809, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.47769749550682133}}
{"text": "#include <cstdlib>\n#include <iostream>\n#include <boost/lexical_cast.hpp>\n\n#include \"model.h\"\n#include \"param.h\"\n\nusing namespace std;\nusing namespace boost;\nusing namespace boost::random;\n\nnamespace nplm\n{\n\n    void model::resize(int ngram_size,\n        int input_vocab_size,\n        int output_vocab_size,\n        int input_embedding_dimension,\n        int num_hidden,\n        int output_embedding_dimension)\n{\n    input_layer.resize(input_vocab_size, input_embedding_dimension, ngram_size-1);\n    first_hidden_linear.resize(num_hidden, input_embedding_dimension*(ngram_size-1));\n    first_hidden_activation.resize(num_hidden);\n    second_hidden_linear.resize(output_embedding_dimension, num_hidden);\n    second_hidden_activation.resize(output_embedding_dimension);\n    output_layer.resize(output_vocab_size, output_embedding_dimension);\n    this->ngram_size = ngram_size;\n    this->input_vocab_size = input_vocab_size;\n    this->output_vocab_size = output_vocab_size;\n    this->input_embedding_dimension = input_embedding_dimension;\n    this->num_hidden = num_hidden;\n    this->output_embedding_dimension = output_embedding_dimension;\n    premultiplied = false;\n}\n  \nvoid model::initialize(mt19937 &init_engine, bool init_normal, double init_range, double init_bias)\n{\n    input_layer.initialize(init_engine, init_normal, init_range);\n    output_layer.initialize(init_engine, init_normal, init_range, init_bias);\n    first_hidden_linear.initialize(init_engine, init_normal, init_range);\n    second_hidden_linear.initialize(init_engine, init_normal, init_range);\n}\n\nvoid model::premultiply()\n{\n    // Since input and first_hidden_linear are both linear,\n    // we can multiply them into a single linear layer *if* we are not training\n    int context_size = ngram_size-1;\n    Matrix<double,Dynamic,Dynamic> U = first_hidden_linear.U;\n    first_hidden_linear.U.resize(num_hidden, input_vocab_size * context_size);\n    for (int i=0; i<context_size; i++)\n        first_hidden_linear.U.middleCols(i*input_vocab_size, input_vocab_size) = U.middleCols(i*input_embedding_dimension, input_embedding_dimension) * input_layer.W->transpose();\n    input_layer.W->resize(1,1); // try to save some memory\n    premultiplied = true;\n}\n\nvoid model::readConfig(ifstream &config_file)\n{\n    string line;\n    vector<string> fields;\n    int ngram_size, vocab_size, input_embedding_dimension, num_hidden, output_embedding_dimension;\n    activation_function_type activation_function = this->activation_function;\n    while (getline(config_file, line) && line != \"\")\n    {\n        splitBySpace(line, fields);\n\tif (fields[0] == \"ngram_size\")\n\t    ngram_size = lexical_cast<int>(fields[1]);\n\telse if (fields[0] == \"vocab_size\")\n\t    input_vocab_size = output_vocab_size = lexical_cast<int>(fields[1]);\n\telse if (fields[0] == \"input_vocab_size\")\n\t    input_vocab_size = lexical_cast<int>(fields[1]);\n\telse if (fields[0] == \"output_vocab_size\")\n\t    output_vocab_size = lexical_cast<int>(fields[1]);\n\telse if (fields[0] == \"input_embedding_dimension\")\n\t    input_embedding_dimension = lexical_cast<int>(fields[1]);\n\telse if (fields[0] == \"num_hidden\")\n\t    num_hidden = lexical_cast<int>(fields[1]);\n\telse if (fields[0] == \"output_embedding_dimension\")\n\t    output_embedding_dimension = lexical_cast<int>(fields[1]);\n\telse if (fields[0] == \"activation_function\")\n\t    activation_function = string_to_activation_function(fields[1]);\n\telse if (fields[0] == \"version\")\n\t{\n\t    int version = lexical_cast<int>(fields[1]);\n\t    if (version != 1)\n\t    {\n\t\tcerr << \"error: file format mismatch (expected 1, found \" << version << \")\" << endl;\n\t\texit(1);\n\t    }\n\t}\n\telse\n\t    cerr << \"warning: unrecognized field in config: \" << fields[0] << endl;\n    }\n    resize(ngram_size,\n        input_vocab_size,\n        output_vocab_size,\n        input_embedding_dimension,\n        num_hidden,\n        output_embedding_dimension);\n    set_activation_function(activation_function);\n}\n\nvoid model::readConfig(const string &filename)\n{\n    ifstream config_file(filename.c_str());\n    if (!config_file)\n    {\n        cerr << \"error: could not open config file \" << filename << endl;\n\texit(1);\n    }\n    readConfig(config_file);\n    config_file.close();\n}\n \nvoid model::read(const string &filename)\n{\n    vector<string> input_words;\n    vector<string> output_words;\n    read(filename, input_words, output_words);\n}\n\nvoid model::read(const string &filename, vector<string> &input_words, vector<string> &output_words)\n{\n    ifstream file(filename.c_str());\n    if (!file) throw runtime_error(\"Could not open file \" + filename);\n    \n    param myParam;\n    string line;\n    \n    while (getline(file, line))\n    {\n\tif (line == \"\\\\config\")\n\t{\n\t    readConfig(file);\n\t}\n\n\telse if (line == \"\\\\vocab\")\n\t{\n\t    input_words.clear();\n\t    readWordsFile(file, input_words);\n\t    output_words = input_words;\n\t}\n\n\telse if (line == \"\\\\input_vocab\")\n\t{\n\t    input_words.clear();\n\t    readWordsFile(file, input_words);\n\t}\n\n\telse if (line == \"\\\\output_vocab\")\n\t{\n\t    output_words.clear();\n\t    readWordsFile(file, output_words);\n\t}\n\n\telse if (line == \"\\\\input_embeddings\")\n\t    input_layer.read(file);\n\telse if (line == \"\\\\hidden_weights 1\")\n\t    first_hidden_linear.read(file);\n\telse if (line == \"\\\\hidden_weights 2\")\n\t    second_hidden_linear.read(file);\n\telse if (line == \"\\\\output_weights\")\n\t    output_layer.read_weights(file);\n\telse if (line == \"\\\\output_biases\")\n\t    output_layer.read_biases(file);\n\telse if (line == \"\\\\end\")\n\t    break;\n\telse if (line == \"\")\n\t    continue;\n\telse\n\t{\n\t    cerr << \"warning: unrecognized section: \" << line << endl;\n\t    // skip over section\n\t    while (getline(file, line) && line != \"\") { }\n\t}\n    }\n    file.close();\n}\n\n    void model::write(const string &filename, const vector<string> &input_words, const vector<string> &output_words)\n{ \n    write(filename, &input_words, &output_words);\n}\n\nvoid model::write(const string &filename) \n{ \n    write(filename, NULL, NULL);\n}\n\n    void model::write(const string &filename, const vector<string> *input_pwords, const vector<string> *output_pwords)\n{\n    ofstream file(filename.c_str());\n    if (!file) throw runtime_error(\"Could not open file \" + filename);\n    \n    file << \"\\\\config\" << endl;\n    file << \"version 1\" << endl;\n    file << \"ngram_size \" << ngram_size << endl;\n    file << \"input_vocab_size \" << input_vocab_size << endl;\n    file << \"output_vocab_size \" << output_vocab_size << endl;\n    file << \"input_embedding_dimension \" << input_embedding_dimension << endl;\n    file << \"num_hidden \" << num_hidden << endl;\n    file << \"output_embedding_dimension \" << output_embedding_dimension << endl;\n    file << \"activation_function \" << activation_function_to_string(activation_function) << endl;\n    file << endl;\n    \n    if (input_pwords)\n    {\n        file << \"\\\\input_vocab\" << endl;\n\twriteWordsFile(*input_pwords, file);\n\tfile << endl;\n    }\n\n    if (output_pwords)\n    {\n        file << \"\\\\output_vocab\" << endl;\n\twriteWordsFile(*output_pwords, file);\n\tfile << endl;\n    }\n\n    file << \"\\\\input_embeddings\" << endl;\n    input_layer.write(file);\n    file << endl;\n    \n    file << \"\\\\hidden_weights 1\" << endl;\n    first_hidden_linear.write(file);\n    file << endl;\n    \n    file << \"\\\\hidden_weights 2\" << endl;\n    second_hidden_linear.write(file);\n    file << endl;\n    \n    file << \"\\\\output_weights\" << endl;\n    output_layer.write_weights(file);\n    file << endl;\n    \n    file << \"\\\\output_biases\" << endl;\n    output_layer.write_biases(file);\n    file << endl;\n    \n    file << \"\\\\end\" << endl;\n    file.close();\n}\n\n\n} // namespace nplm\n", "meta": {"hexsha": "361197554e02fcc28d196ea172466c86979e8af7", "size": 7582, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/model.cpp", "max_stars_repo_name": "gonzaloiglesiasiglesias/nplm", "max_stars_repo_head_hexsha": "a4a69b83e6ed03e031625a5d3b2e1ab3ad2909ca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-02-21T10:44:02.000Z", "max_stars_repo_stars_event_max_datetime": "2015-02-21T10:44:02.000Z", "max_issues_repo_path": "nplm/src/model.cpp", "max_issues_repo_name": "zaycev/nnsmt", "max_issues_repo_head_hexsha": "a030e51a6679a22b7fdcd03bf2161ee0d08281a7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nplm/src/model.cpp", "max_forks_repo_name": "zaycev/nnsmt", "max_forks_repo_head_hexsha": "a030e51a6679a22b7fdcd03bf2161ee0d08281a7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-09-04T13:20:40.000Z", "max_forks_repo_forks_event_max_datetime": "2015-09-04T13:20:40.000Z", "avg_line_length": 30.6963562753, "max_line_length": 179, "alphanum_fraction": 0.679240306, "num_tokens": 1772, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310355, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.4776974915644003}}
{"text": "#pragma once\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include \"ADNConstants.hpp\"\n#include \"ADNVectorMath.hpp\"\n#include \"ADNLogger.hpp\"\n\n\nusing LatticeType = ADNConstants::LatticeType;\n\nnamespace ublas = boost::numeric::ublas;\n\nstruct LatticeCell {\n  double x_;\n  double y_;\n};\n\nclass DASLattice \n{\npublic:\n  DASLattice() = default;\n  DASLattice(LatticeType type, double edgeDistance, int maxRows, int maxCols);\n  ~DASLattice() = default;\n\n  LatticeCell GetLatticeCell(unsigned int row, unsigned int column);\n\n  size_t GetNumberRows();\n  size_t GetNumberCols();\n\nprivate:\n  ublas::matrix<LatticeCell> mat_;\n\n  void CreateSquareLattice(int maxRows, int maxCols);\n  void CreateHoneycombLattice(int maxRows, int maxCols);\n\n  double edgeDistance_;\n};", "meta": {"hexsha": "e249fe65f8b60da0783332401462eb669bbf3aa8", "size": 748, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "AdenitaCoreSE/modules/DAS/includes/DASLattices.hpp", "max_stars_repo_name": "edellano/Adenita-SAMSON-Edition-Win-", "max_stars_repo_head_hexsha": "6df8d21572ef40fe3fc49165dfaa1d4318352a69", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-09-07T20:48:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-03T05:49:59.000Z", "max_issues_repo_path": "AdenitaCoreSE/modules/DAS/includes/DASLattices.hpp", "max_issues_repo_name": "edellano/Adenita-SAMSON-Edition-Linux", "max_issues_repo_head_hexsha": "a7e267e5dd37e0073f4d1e3e603c5fb1c69a350a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-04-05T18:39:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-11T14:28:55.000Z", "max_forks_repo_path": "AdenitaCoreSE/modules/DAS/includes/DASLattices.hpp", "max_forks_repo_name": "edellano/Adenita-SAMSON-Edition-Linux", "max_forks_repo_head_hexsha": "a7e267e5dd37e0073f4d1e3e603c5fb1c69a350a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-07-13T12:58:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-11T13:52:00.000Z", "avg_line_length": 20.2162162162, "max_line_length": 78, "alphanum_fraction": 0.7526737968, "num_tokens": 204, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951182587158, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.47766027869593913}}
{"text": "// gcc -O2 -march=native -DNDEBUG -o sfact sfact.cpp -std=c++11 -lstdc++ -lm -I../.. -I/usr/include/QtGui/ ../../libs/spacegroups/spacegroup.cpp ../../libs/spacegroups/crystalsys.cpp ../../libs/globals.cpp ../../libs/formfactors/formfact.cpp ../../tlibs/log/log.cpp -DNO_QT -lboost_system -lboost_filesystem -lboost_iostreams\n/**\n * generates structure factors\n * @author Tobias Weber <tobias.weber@tum.de>\n * @date nov-2015\n * @license GPLv2\n */\n\n#include <vector>\n#include <unordered_map>\n#include <tuple>\n#include <algorithm>\n#include <sstream>\n#include \"tlibs/math/linalg_ops.h\"\n#include \"tlibs/phys/atoms.h\"\n#include \"tlibs/phys/mag.h\"\n#include \"tlibs/phys/lattice.h\"\n#include \"tlibs/phys/neutrons.h\"\n#include \"tlibs/string/string.h\"\n#include \"tlibs/file/prop.h\"\n#include \"libs/spacegroups/spacegroup.h\"\n#include \"libs/formfactors/formfact.h\"\n#include \"libs/globals.h\"\n\nnamespace ublas = tl::ublas;\n\nusing t_real = t_real_glob;\ntypedef ublas::vector<t_real> t_vec;\ntypedef ublas::matrix<t_real> t_mat;\n\nconst std::string g_strXmlRoot(\"taz/\");\n\n\n\n// --------------------------------------------------------------------------------------------\n// Lattice\n// --------------------------------------------------------------------------------------------\nstatic inline tl::Lattice<t_real> enter_lattice()\n{\n\tstd::cout << \"\\n----------------------------------------------------------------------\\n\" << std::endl;\n\tt_real a,b,c, alpha,beta,gamma;\n\tstd::cout << \"Enter unit cell lattice constants [a b c (in A)]: \";\n\tstd::cin >> a >> b >> c;\n\tstd::cout << \"Enter unit cell angles [alpha beta gamma (in deg)]: \";\n\tstd::cin >> alpha >> beta >> gamma;\n\n\talpha = tl::d2r(alpha);\n\tbeta = tl::d2r(beta);\n\tgamma = tl::d2r(gamma);\n\n\treturn tl::Lattice<t_real>(a,b,c, alpha,beta,gamma);\n}\n\n\nstatic tl::Lattice<t_real> load_lattice(const tl::Prop<>& file)\n{\n\tt_real a = file.Query<t_real>((g_strXmlRoot + \"sample/a\").c_str(), 0.);\n\tt_real b = file.Query<t_real>((g_strXmlRoot + \"sample/b\").c_str(), 0.);\n\tt_real c = file.Query<t_real>((g_strXmlRoot + \"sample/c\").c_str(), 0.);\n\tt_real alpha = file.Query<t_real>((g_strXmlRoot + \"sample/alpha\").c_str(), 0.);\n\tt_real beta = file.Query<t_real>((g_strXmlRoot + \"sample/beta\").c_str(), 0.);\n\tt_real gamma = file.Query<t_real>((g_strXmlRoot + \"sample/gamma\").c_str(), 0.);\n\n\talpha = tl::d2r(alpha);\n\tbeta = tl::d2r(beta);\n\tgamma = tl::d2r(gamma);\n\n\treturn tl::Lattice<t_real>(a,b,c, alpha,beta,gamma);\n}\n// --------------------------------------------------------------------------------------------\n\n\n\n// --------------------------------------------------------------------------------------------\n// Space group\n// --------------------------------------------------------------------------------------------\nstatic inline std::string enter_spacegroup()\n{\n\tstd::cout << \"\\n----------------------------------------------------------------------\\n\" << std::endl;\n\tstd::string strSg;\n\tstd::cout << \"Enter spacegroup: \";\n\tstd::cin.ignore();\n\tstd::getline(std::cin, strSg);\n\n\treturn strSg;\n}\n\n\nstatic std::string load_spacegroup(const tl::Prop<>& file)\n{\n\tstd::string strSG = file.Query<std::string>((g_strXmlRoot + \"sample/spacegroup\").c_str(), \"\");\n\ttl::trim(strSG);\n\n\treturn strSG;\n}\n// --------------------------------------------------------------------------------------------\n\n\n\n\n// --------------------------------------------------------------------------------------------\n// Atom positions\n// --------------------------------------------------------------------------------------------\nstatic inline\nstd::tuple<std::vector<std::string>, std::vector<t_vec>, std::unordered_map<std::string, t_real>>\nenter_atoms()\n{\n\tstd::cout << \"\\n----------------------------------------------------------------------\\n\" << std::endl;\n\tint iAtom=0;\n\tstd::vector<std::string> vecElems;\n\tstd::vector<t_vec> vecAtoms;\n\tstd::unordered_map<std::string, t_real> mapMag;\n\n\twhile(1)\n\t{\n\t\tstd::cout << \"Enter element name \" << (++iAtom) << \" name (or <Enter> to finish): \";\n\t\tstd::string strElem;\n\t\tstd::getline(std::cin, strElem);\n\t\ttl::trim(strElem);\n\t\tif(strElem == \"\")\n\t\t\tbreak;\n\n\t\tstd::cout << \"Enter atom position \" << (iAtom) << \" [x y z (in frac. units)]: \";\n\t\tstd::string strAtom;\n\t\tstd::getline(std::cin, strAtom);\n\t\ttl::trim(strAtom);\n\t\tif(strAtom == \"\")\n\t\t\tbreak;\n\n\t\tstd::cout << \"Enter atom \" << (iAtom) << \" effective magnetic moment [muB]: \";\n\t\tstd::string strMag;\n\t\tstd::getline(std::cin, strMag);\n\t\ttl::trim(strMag);\n\t\tif(strMag == \"\")\n\t\t\tstrMag = \"0\";\n\n\n\t\tvecElems.push_back(strElem);\n\n\t\tt_vec vec(4);\n\t\tstd::istringstream istrAtom(strAtom);\n\t\tistrAtom >> vec[0] >> vec[1] >> vec[2];\n\t\tvec[3] = 1.;\n\t\tvecAtoms.push_back(vec);\n\n\t\tt_real dMag;\n\t\tstd::istringstream istrMag(strMag);\n\t\tistrMag >> dMag;\n\t\tdMag = tl::mag_scatlen_eff(dMag);\n\t\tmapMag[strElem] = dMag;\n\t}\n\n\treturn std::make_tuple(vecElems, vecAtoms, mapMag);\n}\n\n\nstatic inline\nstd::tuple<std::vector<std::string>, std::vector<t_vec>, std::unordered_map<std::string, t_real>>\nload_atoms(const tl::Prop<>& file)\n{\n\tstd::vector<std::string> vecElems;\n\tstd::vector<t_vec> vecAtoms;\n\tstd::unordered_map<std::string, t_real> mapMag;\n\n\tstd::size_t iNumAtoms = file.Query<std::size_t>((g_strXmlRoot + \"sample/atoms/num\").c_str(), 0);\n\tvecElems.reserve(iNumAtoms);\n\tvecAtoms.reserve(iNumAtoms);\n\n\tfor(std::size_t iAtom=0; iAtom<iNumAtoms; ++iAtom)\n\t{\n\t\tstd::string strNr = tl::var_to_str(iAtom);\n\n\t\tstd::string strAtomName =\n\t\t\tfile.Query<std::string>((g_strXmlRoot + \"sample/atoms/\" + strNr + \"/name\").c_str(), \"\");\n\n\t\tt_vec vec(4);\n\t\tvec[0] = file.Query<t_real>((g_strXmlRoot + \"sample/atoms/\" + strNr + \"/x\").c_str(), 0.);\n\t\tvec[1] = file.Query<t_real>((g_strXmlRoot + \"sample/atoms/\" + strNr + \"/y\").c_str(), 0.);\n\t\tvec[2] = file.Query<t_real>((g_strXmlRoot + \"sample/atoms/\" + strNr + \"/z\").c_str(), 0.);\n\t\tvec[3] = 1.;\n\n\t\tvecElems.push_back(strAtomName);\n\t\tvecAtoms.push_back(vec);\n\t}\n\n\treturn std::make_tuple(vecElems, vecAtoms, mapMag);\n}\n// --------------------------------------------------------------------------------------------\n\n\n\nvoid gen_atoms_sfact(const char *pcFile = nullptr)\n{\n\tbool bHasFile = (pcFile != nullptr);\n\ttl::Prop<> file;\n\tif(bHasFile)\n\t{\n\t\tbHasFile = file.Load(pcFile, tl::PropType::XML);\n\t\tif(!bHasFile)\n\t\t\tstd::cerr << \"Error: Invalid file \\\"\" << pcFile << \"\\\".\" << std::endl;\n\t}\n\n\t// --------------------------------------------------------------------------------------------\n\t// Tables\n\t// --------------------------------------------------------------------------------------------\n\tstd::shared_ptr<const xtl::ScatlenList<t_real>> lst = xtl::ScatlenList<t_real>::GetInstance();\n\tstd::shared_ptr<const xtl::FormfactList<t_real>> lstff = xtl::FormfactList<t_real>::GetInstance();\n\tstd::shared_ptr<const xtl::MagFormfactList<t_real>> lstmff = xtl::MagFormfactList<t_real>::GetInstance();\n\tstd::shared_ptr<const xtl::SpaceGroups<t_real>> sgs = xtl::SpaceGroups<t_real>::GetInstance();\n\t// --------------------------------------------------------------------------------------------\n\n\n\t// --------------------------------------------------------------------------------------------\n\t// Lattice\n\t// --------------------------------------------------------------------------------------------\n\ttl::Lattice<t_real> lattice;\n\tif(bHasFile)\n\t\tlattice = load_lattice(file);\n\telse\n\t\tlattice = enter_lattice();\n\n\tconst t_real dVol = lattice.GetVol();\n\tconst t_mat matA = lattice.GetBaseMatrixCov();\n\tconst t_mat matB = lattice.GetRecip().GetBaseMatrixCov();\n\tstd::cout << \"Unit cell volume: \" << dVol << \" A^3\" << std::endl;\n\tstd::cout << \"A = \" << matA << std::endl;\n\tstd::cout << \"B = \" << matB << std::endl;\n\t// --------------------------------------------------------------------------------------------\n\n\n\n\t// --------------------------------------------------------------------------------------------\n\t// Space group\n\t// --------------------------------------------------------------------------------------------\n\tstd::string strSg;\n\tif(bHasFile)\n\t\tstrSg = load_spacegroup(file);\n\telse\n\t\tstrSg = enter_spacegroup();\n\n\tconst auto pSg = sgs->Find(strSg);\n\tif(!pSg)\n\t{\n\t\tstd::cerr << \"Error: Unknown spacegroup.\" << std::endl;\n\t\treturn;\n\t}\n\tstd::cout << \"Spacegroup \" << pSg->GetNr() << \": \" << pSg->GetName() << \".\" << std::endl;\n\n\tconst std::vector<t_mat>& vecTrafos = pSg->GetTrafos();\n\tstd::cout << vecTrafos.size() << \" symmetry operations in spacegroup.\" << std::endl;\n\t// --------------------------------------------------------------------------------------------\n\n\n\n\t// --------------------------------------------------------------------------------------------\n\t// Atom positions\n\t// --------------------------------------------------------------------------------------------\n\tint iAtom=0;\n\tstd::vector<std::string> vecElems;\n\tstd::vector<t_vec> vecAtoms;\n\tstd::unordered_map<std::string, t_real> mapMag;\n\n\tif(bHasFile)\n\t\tstd::tie(vecElems, vecAtoms, mapMag) = load_atoms(file);\n\telse\n\t\tstd::tie(vecElems, vecAtoms, mapMag) = enter_atoms();\n\t// --------------------------------------------------------------------------------------------\n\n\n\n\t// --------------------------------------------------------------------------------------------\n\t// Unit cell & Scattering lengths (assuming magnetic unit cell is the same as structural one)\n\t// --------------------------------------------------------------------------------------------\n\tstd::vector<unsigned int> vecNumAtoms;\n\tstd::vector<t_vec> vecAllAtoms;\n\tstd::vector<std::complex<t_real>> vecScatlens;\n\tstd::vector<std::complex<t_real>> vecMagScatlens;\n\tstd::vector<int> vecAtomIndices;\n\n\tt_real dsigCoh = 0.;\n\tt_real dsigInc = 0.;\n\tt_real dsigScat = 0.;\n\tt_real dsigAbs = 0.;\n\n\tt_real dSigAbs = 0.;\n\tt_real dSigScat = 0.;\n\n\tfor(int iAtom=0; iAtom<int(vecAtoms.size()); ++iAtom)\n\t{\n\t\t// generate symmetry-equivalent atom positions\n\t\tconst t_vec& vecAtom = vecAtoms[iAtom];\n\t\tstd::vector<t_vec> vecPos = tl::generate_atoms<t_mat, t_vec, std::vector>(vecTrafos, vecAtom);\n\t\tvecNumAtoms.push_back(vecPos.size());\n\t\tstd::cout << \"Generated \" << vecPos.size() << \" \" << vecElems[iAtom] << \" atoms.\" << std::endl;\n\t\tfor(const t_vec& vec : vecPos)\n\t\t\tstd::cout << vec << std::endl;\n\n\n\t\t// get scattering lengths\n\t\tconst xtl::ScatlenList<t_real>::elem_type* pElem = lst->Find(vecElems[iAtom]);\n\t\tif(pElem == nullptr)\n\t\t{\n\t\t\tstd::cerr << \"Error: cannot get scattering length for \"\n\t\t\t\t<< vecElems[iAtom] << \".\" << std::endl;\n\t\t\treturn;\n\t\t}\n\t\tstd::complex<t_real> b = pElem->GetCoherent();\n\n\n\t\t// microscopic cross-sections\n\t\tdsigCoh += pElem->GetXSecCoherent().real()*vecNumAtoms[iAtom];\n\t\tdsigInc += pElem->GetXSecIncoherent().real()*vecNumAtoms[iAtom];\n\t\tdsigScat += pElem->GetXSecScatter().real()*vecNumAtoms[iAtom];\n\t\tdsigAbs += pElem->GetXSecAbsorption().real()*vecNumAtoms[iAtom];\n\n\n\t\t// get magnetic scattering lengths\n\t\tstd::complex<t_real> p(0.);\n\t\tauto iterMag = mapMag.find(vecElems[iAtom]);\n\t\tif(iterMag == mapMag.end())\n\t\t{\n\t\t\tstd::cerr << \"Warning: cannot get effective magnetic scattering length for \"\n\t\t\t\t<< vecElems[iAtom] << \".\" << std::endl;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tp = iterMag->second;\n\t\t}\n\n\n\t\t// macroscopic cross-sections\n\t\tdSigScat += tl::macro_xsect(pElem->GetXSecScatter().real()*tl::get_one_femtometer<t_real>()*tl::get_one_femtometer<t_real>(),\n\t\t\tvecNumAtoms[iAtom],\n\t\t\tdVol*tl::get_one_angstrom<t_real>()*tl::get_one_angstrom<t_real>()*tl::get_one_angstrom<t_real>()) * tl::get_one_centimeter<t_real>();\n\n\t\tdSigAbs += tl::macro_xsect(pElem->GetXSecAbsorption().real()*tl::get_one_femtometer<t_real>()*tl::get_one_femtometer<t_real>(),\n\t\t\tvecNumAtoms[iAtom],\n\t\t\tdVol*tl::get_one_angstrom<t_real>()*tl::get_one_angstrom<t_real>()*tl::get_one_angstrom<t_real>()) * tl::get_one_centimeter<t_real>();\n\n\n\t\t// store calculations\n\t\tfor(t_vec vecThisAtom : vecPos)\n\t\t{\n\t\t\tvecThisAtom.resize(3,1);\n\t\t\tvecAllAtoms.push_back(tl::mult<t_mat, t_vec>(matA, vecThisAtom));\n\t\t\tvecScatlens.push_back(b);\n\t\t\tvecMagScatlens.push_back(p);\n\t\t\tvecAtomIndices.push_back(iAtom);\n\t\t}\n\t}\n\n\tstd::cout << \"\\nMicroscopic coherent cross-section: \" << dsigCoh << \" fm^2.\" << std::endl;\n\tstd::cout << \"Microscopic incoherent cross-section: \" << dsigInc << \" fm^2.\" << std::endl;\n\tstd::cout << \"Microscopic total scattering cross-section: \" << dsigScat << \" fm^2.\" << std::endl;\n\tstd::cout << \"Microscopic absorption cross-section: \" << dsigAbs << \" fm^2.\" << std::endl;\n\n\tconst t_real dLam0 = 1.8;\t// thermal\n\tconst t_real dLam = 4.5;\n\tstd::cout << \"\\nMacroscopic total scattering cross-section for lambda = 4.5 A: \"\n\t\t<< dSigScat*dLam/dLam0 << \" / cm.\" << std::endl;\n\tstd::cout << \"Macroscopic absorption cross-section for lambda = 4.5 A: \"\n\t\t<< dSigAbs*dLam/dLam0 << \" / cm.\" << std::endl;\n\n\t//for(const t_vec& vecAt : vecAllAtoms) std::cout << vecAt << std::endl;\n\t//for(const std::complex<t_real>& cb : vecScatlens) std::cout << cb << std::endl;\n\t// --------------------------------------------------------------------------------------------\n\n\n\n\t// --------------------------------------------------------------------------------------------\n\t// Bragg peaks\n\t// --------------------------------------------------------------------------------------------\n\tstd::vector<t_real> vecFormfacts;\n\tstd::vector<t_real> vecMagFormfacts;\n\n\twhile(1)\n\t{\n\t\tstd::cout << \"\\n----------------------------------------------------------------------\\n\" << std::endl;\n\n\t\tt_real h=0., k=0., l=0.;\n\t\tstd::cout << \"Enter h k l [rlu]: \";\n\t\tstd::cin >> h >> k >> l;\n\n\t\tt_vec vecG = tl::mult<t_mat, t_vec>(matB, tl::make_vec({h,k,l}));\n\t\tt_real dG = ublas::norm_2(vecG);\n\t\tstd::cout << \"G = \" << dG << \" / A\" << std::endl;\n\n\n\t\tvecFormfacts.clear();\n\t\tvecMagFormfacts.clear();\n\t\tfor(unsigned int iAtom=0; iAtom<vecAllAtoms.size(); ++iAtom)\n\t\t{\n\t\t\t//const t_vec& vecAtom = vecAllAtoms[iAtom];\n\t\t\tconst xtl::FormfactList<t_real>::elem_type* pElemff = lstff->Find(vecElems[vecAtomIndices[iAtom]]);\n\t\t\tconst xtl::MagFormfactList<t_real>::elem_type* pElemMff = lstmff->Find(vecElems[vecAtomIndices[iAtom]]);\n\n\t\t\tif(pElemff == nullptr)\n\t\t\t{\n\t\t\t\tstd::cerr << \"Error: cannot get form factor for \"\n\t\t\t\t\t<< vecElems[vecAtomIndices[iAtom]] << \".\" << std::endl;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t/*if(pElemMff == nullptr)\n\t\t\t{\n\t\t\t\tstd::cerr << \"Warning: cannot get magnetic form factor for \"\n\t\t\t\t\t<< vecElems[vecAtomIndices[iAtom]] << \".\" << std::endl;\n\t\t\t}*/\n\n\t\t\tt_real dFF = pElemff ? pElemff->GetFormfact(dG) : 0.;\n\t\t\tvecFormfacts.push_back(dFF);\n\n\t\t\tt_real dMFF = pElemMff ? pElemMff->GetFormfact(dG) : 0.;\n\t\t\tvecMagFormfacts.push_back(dMFF);\n\t\t}\n\n\n\t\tstd::vector<std::complex<t_real>> vecMag(vecMagScatlens.size());\n\t\tif(vecMagScatlens.size() != vecMagFormfacts.size())\n\t\t{\n\t\t\tstd::cerr << \"Size mismatch in magnetic scattering lengths and form factors.\"\n\t\t\t\t<< std::endl;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstd::transform(vecMagScatlens.begin(), vecMagScatlens.end(), vecMagFormfacts.begin(),\n\t\t\t\tvecMag.begin(), [](const std::complex<t_real>& c, t_real d) -> std::complex<t_real>\n\t\t\t{\n\t\t\t\t// multiply eff. mag. scattering lengths with respective form factors\n\t\t\t\treturn c * d;\n\t\t\t});\n\t\t}\n\n\n\t\tstd::complex<t_real> F = tl::structfact<t_real, std::complex<t_real>, ublas::vector<t_real>, std::vector>\n\t\t\t(vecAllAtoms, vecG, vecScatlens);\n\t\t\tstd::complex<t_real> Fm = tl::structfact<t_real, std::complex<t_real>, ublas::vector<t_real>, std::vector>\n\t\t\t(vecAllAtoms, vecG, vecMag);\n\t\tstd::complex<t_real> Fx = tl::structfact<t_real, t_real, ublas::vector<t_real>, std::vector>\n\t\t\t(vecAllAtoms, vecG, vecFormfacts);\n\n\t\tstd::cout << std::endl;\n\t\tstd::cout << \"Neutron nuclear structure factor: \" << std::endl;\n\t\tt_real dFsq = (std::conj(F)*F).real();\n\t\tstd::cout << \"F = \" << F << \" fm\" << std::endl;\n\t\tstd::cout << \"|F| = \" << std::sqrt(dFsq) << \" fm\" << std::endl;\n\t\tstd::cout << \"|F|^2 = \" << dFsq << \" fm^2\" << std::endl;\n\n\t\tstd::cout << std::endl;\n\t\tstd::cout << \"Neutron magnetic structure factor: \" << std::endl;\n\t\tt_real dFmsq = (std::conj(Fm)*Fm).real();\n\t\tstd::cout << \"Fm = \" << Fm << \" fm\" << std::endl;\n\t\tstd::cout << \"|Fm| = \" << std::sqrt(dFmsq) << \" fm\" << std::endl;\n\t\tstd::cout << \"|Fm|^2 = \" << dFmsq << \" fm^2\" << std::endl;\n\n\t\tstd::cout << std::endl;\n\t\tstd::cout << \"X-ray atomic structure factor: \" << std::endl;\n\t\tt_real dFxsq = (std::conj(Fx)*Fx).real();\n\t\tstd::cout << \"Fx = \" << Fx << std::endl;\n\t\tstd::cout << \"|Fx| = \" << std::sqrt(dFxsq) << std::endl;\n\t\tstd::cout << \"|Fx|^2 = \" << dFxsq << std::endl;\n\t}\n\t// --------------------------------------------------------------------------------------------\n}\n\n\n#include \"libs/version.h\"\n#include <boost/filesystem.hpp>\nnamespace fs = boost::filesystem;\n\nint main(int argc, char** argv)\n{\n#ifdef NO_TERM_CMDS\n\ttl::Log::SetUseTermCmds(0);\n#endif\n\n\t// plain C locale\n\t/*std::*/setlocale(LC_ALL, \"C\");\n\tstd::locale::global(std::locale::classic());\n\n\n\t// Header\n\ttl::log_info(\"Libcrystal structure factor calculator.\");\n\ttl::log_info(\"Written by Tobias Weber <tobias.weber@tum.de>, 2014-2017.\");\n\ttl::log_info(\"License: GPLv2.\");\n\n\n\t// possible resource paths\n\tconst char* pcProg = argv[0];\n\tfs::path path(pcProg);\n\tpath.remove_filename();\n\ttl::log_info(\"Program path: \", path.string());\n\n\tadd_resource_path(path.string());\n\tadd_resource_path((path / \"..\").string());\n\tadd_resource_path((path / \"resources\").string());\n\tadd_resource_path((path / \"Resources\").string());\n\tadd_resource_path((path / \"..\" / \"resources\").string());\n\tadd_resource_path((path / \"..\" / \"Resources\").string());\n\n\n\t// load a taz file if given\n\tconst char *pcFile = nullptr;\n\tif(argc >= 2)\n\t{\n\t\tpcFile = argv[1];\n\t\tstd::cout << \"Using crystal file \\\"\" << pcFile << \"\\\".\" << std::endl;\n\t}\n\n\ttry\n\t{\n\t\tgen_atoms_sfact(pcFile);\n\t}\n\tcatch(const std::exception& err)\n\t{\n\t\tstd::cerr << err.what() << std::endl;\n\t}\n\n\treturn 0;\n}\n", "meta": {"hexsha": "2d7c4b412858fa3c9f02b15dd4365795d3f4d9c7", "size": 17651, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tools/sggen/sfact.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/sggen/sfact.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/sggen/sfact.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": 33.9442307692, "max_line_length": 325, "alphanum_fraction": 0.5438218798, "num_tokens": 4850, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.47766027425151264}}
{"text": "#include \"singular.h\"\n\n#include <boost/random/poisson_distribution.hpp>\n#include <boost/random/binomial_distribution.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/gamma_distribution.hpp>\n#include <boost/random/beta_distribution.hpp>\n#include <boost/random/uniform_int_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <boost/math/special_functions/erf.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/math/special_functions/beta.hpp>\n\nnamespace statiskit\n{\n    SingularDistribution::~SingularDistribution()\n    {}\n    \n    double SingularDistribution::loglikelihood(const MultivariateData& data) const\n    {\n        double llh = 0.;\n        std::unique_ptr< MultivariateData::Generator > generator = data.generator();\n        while(generator->is_valid() && boost::math::isfinite(llh))\n        { \n            double weight = generator->weight();\n            if(weight > 0.)\n            { llh += weight * probability(generator->event(), true); }\n            ++(*generator);\n        }\n        return llh;\n    }\n\n    MultinomialSingularDistribution::MultinomialSingularDistribution(const Eigen::VectorXd& pi)\n    {\n        _pi = Eigen::VectorXd::Zero(pi.size());\n        set_pi(pi);\n    }\n\n    MultinomialSingularDistribution::MultinomialSingularDistribution(const MultinomialSingularDistribution& splitting)\n    { _pi = splitting._pi; }\n\n    MultinomialSingularDistribution::~MultinomialSingularDistribution()\n    {}\n\n    Index MultinomialSingularDistribution::get_nb_components() const\n    { return _pi.size(); }\n\n    unsigned int MultinomialSingularDistribution::get_nb_parameters() const\n    { return _pi.size() - 1; }\n\n    double MultinomialSingularDistribution::probability(const MultivariateEvent* event, const bool& logarithm) const\n    {\n        double p;\n        if(event && event->size() == get_nb_components())\n        {\n            try\n            {\n                p = 0.;\n                int sum = 0;\n                for(Index component = 0, max_component = get_nb_components(); component < max_component; ++component)\n                {\n                    const UnivariateEvent* uevent = event->get(component);\n                    if(uevent)\n                    {\n                        if(uevent->get_outcome() == DISCRETE && uevent->get_event() == ELEMENTARY)\n                        {\n                            int value = static_cast< const DiscreteElementaryEvent* >(uevent)->get_value();\n                            if(!(_pi[component] <= 0. && value == 0))\n                            {\n                                p += value * log(_pi[component]) - boost::math::lgamma(value + 1);\n                                sum += value;\n                            }\n                        }\n                        else\n                        { throw std::exception(); }\n                    }\n                }\n                p += boost::math::lgamma(sum + 1);\n            }\n            catch(const std::exception& error)\n            { p = log(0.); }\n        }\n        else\n        { p = log(0.); }\n        if(!logarithm)\n        { p = exp(p); }\n        return p;\n    }\n\n    std::unique_ptr< MultivariateEvent > MultinomialSingularDistribution::simulate(unsigned int sum) const\n    {\n        double pi = 0.;\n        Index component = 0, max_component = get_nb_components() - 1;\n        std::unique_ptr< VectorEvent > event = std::make_unique< VectorEvent >(max_component + 1);\n        while(component < max_component && sum > 0)\n        {\n            boost::binomial_distribution<> dist(sum, _pi[component] / (1 - pi));\n            boost::variate_generator<boost::mt19937&, boost::binomial_distribution<> > simulator(__impl::get_random_generator(), dist);\n            int value = simulator();\n            pi += _pi[component];\n            event->set(component, DiscreteElementaryEvent(value));\n            sum -= value;\n            ++component;\n        }\n        for(; component < max_component; ++component)\n        { event->set(component, DiscreteElementaryEvent(0)); }\n        event->set(max_component, DiscreteElementaryEvent(sum));\n        return std::move(event);\n    }\n\n    const Eigen::VectorXd& MultinomialSingularDistribution::get_pi() const\n    { return _pi; }\n\n    void MultinomialSingularDistribution::set_pi(const Eigen::VectorXd& pi)\n    {\n        if(pi.rows() == _pi.size() - 1)\n        {\n            Index j = 0; \n            while(j < pi.rows() && pi[j] >= 0.)\n            { ++j; }\n            if(j < pi.rows())\n            { throw parameter_error(\"pi\", \"contains negative values\"); } \n            double sum = pi.sum();\n            if(sum < 1)\n            {\n                _pi.block(0, 0, _pi.size() - 1, 1) = pi / sum;\n                _pi[_pi.size()-1] = 1 - sum;\n            }\n            else\n            { throw parameter_error(\"pi\", \"last category values\"); }                \n        }\n        else if(pi.rows() == _pi.size())\n        {\n            Index j = 0; \n            while(j < pi.rows() && pi[j] >= 0.)\n            { ++j; }\n            if(j < pi.rows())\n            { throw parameter_error(\"pi\", \"contains negative values\"); } \n            _pi = pi / pi.sum();\n        }\n        else\n        { throw parameter_error(\"pi\", \"number of parameters\"); }\n    }\n\n    DirichletMultinomialSingularDistribution::DirichletMultinomialSingularDistribution(const Eigen::VectorXd& alpha)\n    {\n        _alpha = Eigen::VectorXd::Zero(alpha.size());\n        set_alpha(alpha);\n    }\n\n    DirichletMultinomialSingularDistribution::DirichletMultinomialSingularDistribution(const DirichletMultinomialSingularDistribution& splitting)\n    { _alpha = splitting._alpha; }\n\n    DirichletMultinomialSingularDistribution::~DirichletMultinomialSingularDistribution()\n    {}\n\n    Index DirichletMultinomialSingularDistribution::get_nb_components() const\n    { return _alpha.size(); }\n\n\n    unsigned int DirichletMultinomialSingularDistribution::get_nb_parameters() const\n    { return _alpha.size(); }\n\n    double DirichletMultinomialSingularDistribution::probability(const MultivariateEvent* event, const bool& logarithm) const\n    {\n        double p;\n        if(event && event->size() == get_nb_components())\n        {\n            try\n            {\n                p = 0.;\n                int sum = 0;\n                for(Index component = 0, max_component = get_nb_components(); component < max_component; ++component)\n                {\n                    const UnivariateEvent* uevent = event->get(component);\n                    if(uevent)\n                    {\n                        if(uevent->get_outcome() == DISCRETE && uevent->get_event() == ELEMENTARY)\n                        {\n                            int value = static_cast< const DiscreteElementaryEvent* >(uevent)->get_value();\n                            if(!(_alpha[component] <= 0. && value == 0))\n                            {\n                                p += boost::math::lgamma(_alpha[component] + value);\n                                p -= boost::math::lgamma(_alpha[component]) + boost::math::lgamma(value + 1);\n                                sum += value;\n                            }\n                        }\n                        else\n                        { throw std::exception(); }\n                    }\n                }\n                double alpha = _alpha.sum();\n                p += boost::math::lgamma(sum + 1) + boost::math::lgamma(alpha) - boost::math::lgamma(alpha + sum);\n            }\n            catch(const std::exception& error)\n            { p = log(0.); }\n        }\n        else\n        { p = log(0.); }\n        if(!logarithm)\n        { p = exp(p); }\n        return p;\n    }\n\n    std::unique_ptr< MultivariateEvent > DirichletMultinomialSingularDistribution::simulate(unsigned int sum) const\n    {\n        Eigen::VectorXd _pi = Eigen::VectorXd::Zero(get_nb_components());\n        for(Index component = 0, max_component = get_nb_components(); component < max_component; ++component)\n        {\n            boost::random::gamma_distribution<> dist(_alpha(component), 1.);\n            boost::variate_generator<boost::mt19937&, boost::random::gamma_distribution<> > simulator(__impl::get_random_generator(), dist);\n            _pi(component) = simulator(); \n        }\n        _pi /= _pi.sum();\n        double pi = 0.;\n        Index component = 0, max_component = get_nb_components() - 1;\n        std::unique_ptr< VectorEvent > event = std::make_unique< VectorEvent >(max_component + 1);\n        while(component < max_component && sum > 0)\n        {\n            boost::binomial_distribution<> dist(sum, _pi[component] / (1 - pi));\n            boost::variate_generator<boost::mt19937&, boost::binomial_distribution<> > simulator(__impl::get_random_generator(), dist);\n            int value = simulator();\n            pi += _pi[component];\n            event->set(component, DiscreteElementaryEvent(value));\n            sum -= value;\n            ++component;\n        }\n        for(; component < max_component; ++component)\n        { event->set(component, DiscreteElementaryEvent(0)); }\n        event->set(max_component, DiscreteElementaryEvent(sum));\n        return std::move(event);\n    }\n\n    const Eigen::VectorXd& DirichletMultinomialSingularDistribution::get_alpha() const\n    { return _alpha; }\n\n    void DirichletMultinomialSingularDistribution::set_alpha(const Eigen::VectorXd& alpha)\n    {\n        if(alpha.rows() == _alpha.size())\n        {\n            Index j = 0; \n            while(j < alpha.rows() && alpha[j] >= 0.)\n            { ++j; }\n            if(j < alpha.rows())\n            { throw parameter_error(\"alpha\", \"contains negative values\"); } \n            _alpha = alpha;\n        }\n        else\n        { throw parameter_error(\"alpha\", \"number of parameters\"); }\n    }\n}", "meta": {"hexsha": "16582d3eb512944609fd09f34f29752f5ea93b1c", "size": 9793, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cpp/singular.cpp", "max_stars_repo_name": "StatisKit/Core", "max_stars_repo_head_hexsha": "79d8ec07c203eb7973a6cf482852ddb2e8e1e93e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cpp/singular.cpp", "max_issues_repo_name": "StatisKit/Core", "max_issues_repo_head_hexsha": "79d8ec07c203eb7973a6cf482852ddb2e8e1e93e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2018-03-20T14:23:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-09T11:57:57.000Z", "max_forks_repo_path": "src/cpp/singular.cpp", "max_forks_repo_name": "StatisKit/Core", "max_forks_repo_head_hexsha": "79d8ec07c203eb7973a6cf482852ddb2e8e1e93e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-04-28T07:41:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-15T18:17:20.000Z", "avg_line_length": 39.015936255, "max_line_length": 145, "alphanum_fraction": 0.5496783417, "num_tokens": 2176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6187804478040616, "lm_q1q2_score": 0.4776016652275159}}
{"text": "#pragma once\n#include <Eigen/Dense>\n#include <unsupported/Eigen/KroneckerProduct>\n\n#include <vector>\n\n#include \"../utils.hpp\"\n\nnamespace yavque\n{\nenum class Pauli : char\n{\n\tX = 'X',\n\tY = 'Y',\n\tZ = 'Z'\n};\n\nnamespace detail\n{\n\tclass CompressedPauliString\n\t{\n\tprivate:\n\t\tconst std::vector<Pauli> pstring_;\n\t\tEigen::MatrixXcd mat_;\n\t\tmutable bool diagonalized_ = false;\n\t\tmutable Eigen::MatrixXcd evecs_;\n\t\tmutable Eigen::MatrixXcd evals_;\n\n\t\tstatic std::vector<Pauli> construct_pauli(const std::string& str)\n\t\t{\n\t\t\tstd::vector<Pauli> res;\n\t\t\tfor(auto c : str)\n\t\t\t{\n\t\t\t\tres.emplace_back(Pauli(c));\n\t\t\t}\n\t\t\treturn res;\n\t\t}\n\n\t\tstatic Eigen::MatrixXcd get_pauli(Pauli p)\n\t\t{\n\t\t\tswitch(p)\n\t\t\t{\n\t\t\tcase Pauli::X:\n\t\t\t\treturn pauli_x().cast<cx_double>();\n\t\t\tcase Pauli::Y:\n\t\t\t\treturn pauli_y();\n\t\t\tcase Pauli::Z:\n\t\t\t\treturn pauli_z().cast<cx_double>();\n\t\t\t}\n\t\t\t__builtin_unreachable();\n\t\t\treturn Eigen::MatrixXcd();\n\t\t}\n\n\t\tvoid diagonalize() const\n\t\t{\n\t\t\tif(!diagonalized_)\n\t\t\t{\n\t\t\t\tEigen::SelfAdjointEigenSolver<Eigen::MatrixXcd> es(mat_);\n\t\t\t\tevecs_ = es.eigenvectors();\n\t\t\t\tevals_ = es.eigenvalues();\n\t\t\t\tdiagonalized_ = true;\n\t\t\t}\n\t\t}\n\n\t\tstatic uint32_t change_bits(const std::vector<uint32_t>& indices,\n\t\t                            uint32_t bitstring, uint32_t bits_to_change)\n\t\t{\n\t\t\tfor(uint32_t n = 0; n < indices.size(); ++n)\n\t\t\t{\n\t\t\t\tuint32_t b = (bits_to_change >> n) & 1U;\n\t\t\t\tbitstring = (bitstring & (~(1U << indices[n]))) | (b << indices[n]);\n\t\t\t}\n\t\t\treturn bitstring;\n\t\t}\n\n\t\tstatic uint32_t bits(const std::vector<uint32_t>& indices, uint32_t bitstring)\n\t\t{\n\t\t\tuint32_t b = 0U;\n\n\t\t\tfor(uint32_t k = 0; k < indices.size(); ++k)\n\t\t\t{\n\t\t\t\tb |= ((bitstring >> indices[k]) & 1U) << k;\n\t\t\t}\n\t\t\treturn b;\n\t\t}\n\n\t\tvoid construct_matrix()\n\t\t{\n\t\t\tmat_ = Eigen::MatrixXcd::Ones(1, 1);\n\t\t\tfor(auto iter = pstring_.rbegin(); iter != pstring_.rend(); ++iter)\n\t\t\t{\n\t\t\t\tmat_ = Eigen::kroneckerProduct(mat_, get_pauli(*iter)).eval();\n\t\t\t}\n\t\t}\n\n\tpublic:\n\t\texplicit CompressedPauliString(const std::string& str)\n\t\t\t: pstring_{construct_pauli(str)}\n\t\t{\n\t\t\tconstruct_matrix();\n\t\t}\n\n\t\texplicit CompressedPauliString(std::vector<Pauli> pvec)\n\t\t\t: pstring_{std::move(pvec)}\n\t\t{\n\t\t\tconstruct_matrix();\n\t\t}\n\n\t\tPauli at(uint32_t idx) const { return pstring_[idx]; }\n\n\t\tEigen::VectorXcd apply(const std::vector<uint32_t>& indices,\n\t\t                       const Eigen::VectorXcd& vec) const\n\t\t{\n\t\t\tassert(pstring_.size() == indices.size());\n\t\t\tuint32_t dim = 1U << pstring_.size();\n\t\t\tEigen::VectorXcd res = Eigen::VectorXcd::Zero(vec.size());\n\n\t\t\tif(indices.size() == 1)\n\t\t\t{\n\t\t\t\treturn apply_single_qubit(vec, mat_, indices[0]);\n\t\t\t}\n\t\t\tif(indices.size() == 2)\n\t\t\t{\n\t\t\t\treturn apply_two_qubit(vec, mat_, {indices[0], indices[1]});\n\t\t\t}\n\t\t\tif(indices.size() == 3)\n\t\t\t{\n\t\t\t\treturn apply_three_qubit(vec, mat_, {indices[0], indices[1], indices[2]});\n\t\t\t}\n\n\t\t\tfor(uint32_t k = 0; k < vec.size(); ++k)\n\t\t\t{\n\t\t\t\tcx_double v = 0.0;\n\t\t\t\tuint32_t row = bits(indices, k);\n\t\t\t\tfor(uint32_t col = 0; col < dim; ++col)\n\t\t\t\t{\n\t\t\t\t\tuint32_t l = change_bits(indices, k, col);\n\t\t\t\t\tv += mat_(row, col) * vec(l);\n\t\t\t\t}\n\t\t\t\tres(k) = v;\n\t\t\t}\n\t\t\treturn res;\n\t\t}\n\n\t\t/* return exp(t*P) applied to indices */\n\t\tEigen::VectorXcd apply_exp(cx_double t, const std::vector<uint32_t>& indices,\n\t\t                           const Eigen::VectorXcd& vec) const\n\t\t{\n\t\t\tassert(pstring_.size() == indices.size());\n\t\t\tuint32_t dim = 1U << pstring_.size();\n\t\t\tEigen::VectorXcd res = Eigen::VectorXcd::Zero(vec.size());\n\n\t\t\tif(!diagonalized_)\n\t\t\t{\n\t\t\t\tdiagonalize();\n\t\t\t}\n\n\t\t\tEigen::VectorXcd p = (t * evals_.array()).exp();\n\t\t\tEigen::MatrixXcd exp_mat = evecs_ * p.asDiagonal() * evecs_.adjoint();\n\n\t\t\tif(indices.size() == 1)\n\t\t\t{\n\t\t\t\treturn apply_single_qubit(vec, exp_mat, indices[0]);\n\t\t\t}\n\t\t\tif(indices.size() == 2)\n\t\t\t{\n\t\t\t\treturn apply_two_qubit(vec, exp_mat, {indices[0], indices[1]});\n\t\t\t}\n\t\t\tif(indices.size() == 3)\n\t\t\t{\n\t\t\t\treturn apply_three_qubit(vec, exp_mat,\n\t\t\t\t                         {indices[0], indices[1], indices[2]});\n\t\t\t}\n\n\t\t\tfor(uint32_t k = 0; k < vec.size(); ++k)\n\t\t\t{\n\t\t\t\tcx_double v = 0.0;\n\t\t\t\tuint32_t row = bits(indices, k);\n\t\t\t\tfor(uint32_t col = 0; col < dim; ++col)\n\t\t\t\t{\n\t\t\t\t\tuint32_t l = change_bits(indices, k, col);\n\t\t\t\t\tv += exp_mat(row, col) * vec(l);\n\t\t\t\t}\n\t\t\t\tres(k) = v;\n\t\t\t}\n\t\t\treturn res;\n\t\t}\n\t};\n} // namespace detail\n\nclass CPSFactory\n{\nprivate:\n\tstd::map<std::string, std::weak_ptr<detail::CompressedPauliString>> map_;\n\n\tCPSFactory() = default;\n\npublic:\n\tCPSFactory(const CPSFactory&) = delete;\n\tCPSFactory& operator=(const CPSFactory&) = delete;\n\n\tCPSFactory(CPSFactory&&) = delete;\n\tCPSFactory& operator=(CPSFactory&&) = delete;\n\t~CPSFactory() = default;\n\n\tstd::shared_ptr<detail::CompressedPauliString>\n\tget_pauli_string_for(const std::string& pstr)\n\t{\n\t\tauto iter = map_.find(pstr);\n\t\tif((iter == map_.end()) || iter->second.expired())\n\t\t{\n\t\t\tauto p = std::make_shared<detail::CompressedPauliString>(pstr);\n\t\t\tmap_[pstr] = p;\n\t\t\treturn p;\n\t\t}\n\t\treturn std::shared_ptr<detail::CompressedPauliString>(map_[pstr]);\n\t}\n\n\tstatic CPSFactory& get_instance()\n\t{\n\t\tstatic CPSFactory instance;\n\t\treturn instance;\n\t}\n};\n} // namespace yavque\n", "meta": {"hexsha": "2f85882e92bbbc02be17b410a00d8de72bf1e53e", "size": 5125, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/yavque/Operators/CompressedPauliString.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/CompressedPauliString.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/CompressedPauliString.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": 22.6769911504, "max_line_length": 80, "alphanum_fraction": 0.6140487805, "num_tokens": 1639, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435083355187, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4776016608702272}}
{"text": "//==================================================================================================\n/**\n  EVE - Expressive Vector Engine\n  Copyright : EVE Contributors & Maintainers\n  SPDX-License-Identifier: MIT\n**/\n//==================================================================================================\n#include <eve/function/jacobi_zeta.hpp>\n#include <boost/math/special_functions/jacobi_zeta.hpp>\n#include <eve/function/next.hpp>\n#include <eve/function/prev.hpp>\n#include <eve/function/is_denormal.hpp>\n#include <eve/constant/nan.hpp>\n#include <eve/constant/inf.hpp>\n#include <eve/constant/minf.hpp>\n#include <eve/constant/minlog.hpp>\n#include <eve/platform.hpp>\n\n#include <cmath>\n\nTTS_CASE_TPL(\"Check eve::jacobi_zeta return type\", EVE_TYPE)\n{\n  TTS_EXPR_IS(eve::jacobi_zeta(T(0), T(0)), T);\n}\n\n\nTTS_CASE_TPL(\"Check eve::jacobi_zeta behavior two parameter\", EVE_TYPE)\n{\n  using v_t = eve::element_type_t<T>;\n  using eve::as;\n  if constexpr( eve::platform::supports_invalids )\n  {\n   TTS_IEEE_EQUAL(eve::jacobi_zeta(eve::pio_4(as<T>()), eve::nan(eve::as<T>())) , eve::nan(eve::as<T>()) );\n   TTS_ULP_EQUAL(eve::jacobi_zeta(eve::pio_2(as<T>()), T(1)) , eve::zero(eve::as<T>()), 0.5);\n   TTS_ULP_EQUAL(eve::jacobi_zeta(eve::pio_2(as<T>()), T(-1)), eve::zero(eve::as<T>()), 0.5);\n  }\n\n  TTS_ULP_EQUAL( eve::jacobi_zeta(eve::pio_2(as<T>()), T( 0.)),  eve::zero(eve::as<T>()), 0.5);\n  TTS_ULP_EQUAL( eve::jacobi_zeta(eve::pio_2(as<T>()), T( 0.5)), eve::zero(eve::as<T>()), 4);\n  TTS_ULP_EQUAL( eve::jacobi_zeta(eve::pio_2(as<T>()), T( 0.9)), eve::zero(eve::as<T>()), 4.55);\n\n  TTS_ULP_EQUAL( eve::jacobi_zeta(eve::pio_4(as<T>()), T( 0.)),  T(boost::math::jacobi_zeta(v_t(0)  , eve::pio_4(as<v_t>()))), 0.5);\n  TTS_ULP_EQUAL( eve::jacobi_zeta(eve::pio_4(as<T>()), T( 0.5)), T(boost::math::jacobi_zeta(v_t(0.5), eve::pio_4(as<v_t>()))), 1.0);\n  TTS_ULP_EQUAL( eve::jacobi_zeta(eve::pio_4(as<T>()), T( 0.9)), T(boost::math::jacobi_zeta(v_t(0.9), eve::pio_4(as<v_t>()))), 1.0);\n  TTS_ULP_EQUAL( eve::jacobi_zeta(3*eve::pio_4(as<T>()), T( 0.)),  T(boost::math::jacobi_zeta(v_t(0)  , 3*eve::pio_4(as<v_t>()))), 0.5);\n  TTS_ULP_EQUAL( eve::jacobi_zeta(T(100), T( 0.)),  T(boost::math::jacobi_zeta(v_t(0)  , v_t(100))), 0.5);\n  TTS_ULP_EQUAL( eve::jacobi_zeta(T(1.5), T(1)),    T(boost::math::jacobi_zeta(v_t(1)  , v_t(1.5))), 1.0);\n  TTS_ULP_EQUAL( eve::jacobi_zeta(3*eve::pio_4(as<T>()), T( 0.5)), T(boost::math::jacobi_zeta(v_t(0.5), 3*eve::pio_4(as<v_t>()))), 0.5);\n  TTS_ULP_EQUAL( eve::jacobi_zeta(3*eve::pio_4(as<T>()), T( 0.9)), T(boost::math::jacobi_zeta(v_t(0.9), 3*eve::pio_4(as<v_t>()))), 0.5);\n  TTS_ULP_EQUAL( eve::jacobi_zeta(T(100), T( 0.5)), T(boost::math::jacobi_zeta(v_t(0.5), v_t(100))), 1.0);\n  TTS_ULP_EQUAL( eve::jacobi_zeta(T(100), T( 0.9)), T(boost::math::jacobi_zeta(v_t(0.9), v_t(100))), 1.0);\n}\n", "meta": {"hexsha": "a74d5557b71f6b0830360012404847d1b46d5394", "size": 2828, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/unit/module/real/elliptic/jacobi_zeta/regular/jacobi_zeta.hpp", "max_stars_repo_name": "orao/eve", "max_stars_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_stars_repo_licenses": ["MIT"], "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/unit/module/real/elliptic/jacobi_zeta/regular/jacobi_zeta.hpp", "max_issues_repo_name": "orao/eve", "max_issues_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_issues_repo_licenses": ["MIT"], "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/unit/module/real/elliptic/jacobi_zeta/regular/jacobi_zeta.hpp", "max_forks_repo_name": "orao/eve", "max_forks_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 53.358490566, "max_line_length": 136, "alphanum_fraction": 0.5979490806, "num_tokens": 1078, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.47760165437523305}}
{"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_LOG1P_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_LOG1P_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n    @ingroup group-exponential\n    This function object computes \\f$\\log(1+x)\\f$ with good accuracy even for small\n    \\f$x\\f$ values.\n\n    @par Header <boost/simd/function/log1p.hpp>\n\n    @par Decorators\n\n      - std_ for floating entries calls @c std::log1p\n\n    @see log, exp, expm1\n\n    @par Example:\n\n      @snippet log1p.cpp log1p\n\n    @par Possible output:\n\n      @snippet log1p.txt log1p\n\n  **/\n  IEEEValue log1p(IEEEValue const& x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/log1p.hpp>\n#include <boost/simd/function/simd/log1p.hpp>\n\n#endif\n", "meta": {"hexsha": "cb557c5d935f8dd7abdf7c896d1f18141e10b832", "size": 1113, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/log1p.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/log1p.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/log1p.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 23.1875, "max_line_length": 100, "alphanum_fraction": 0.5786163522, "num_tokens": 260, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.47760165437523305}}
{"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_FUNCTION_DIVROUND_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_DIVROUND_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-arithmetic\n    Function object implementing divround capabilities\n\n    Computes the round of the division.\n\n    @par semantic:\n    For any given value @c x,  @c y of type @c T:\n\n    @code\n    T r = divround(x, y);\n    @endcode\n\n    The code is similar to:\n\n    @code\n    T r = round(x/y);\n    @endcode\n\n    for integral types, if y is null, it returns @ref Valmax or @ref Valmin\n    if x is positive (resp. negative) and 0 if x is null.\n    Take also care that dividing @ref Valmin by -1 for signed integral types has\n    undefined behaviour.\n\n    @see  divides, rec, divs, divfloor,\n    divceil, divround2even, divfix\n\n  **/\n  const boost::dispatch::functor<tag::divround_> divround = {};\n} }\n#endif\n\n#include <boost/simd/function/scalar/divround.hpp>\n#include <boost/simd/function/simd/divround.hpp>\n\n#endif\n", "meta": {"hexsha": "217fc660c420297994e5fff08944bdc0ff153614", "size": 1422, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/divround.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/function/divround.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/function/divround.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": 25.3928571429, "max_line_length": 100, "alphanum_fraction": 0.6026722925, "num_tokens": 332, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.47760165437523305}}
{"text": "// ds THIS CODE WAS CREATED BASED ON: http://kitti.is.tue.mpg.de/kitti/devkit_odometry.zip\n// ds minimally modified to avoid C++11 warnings and provided a brief result dump to stdout\n\n#include <Eigen/Geometry>\n#include <fstream>\n#include <iostream>\n#include <limits>\n#include <set>\n#include <srrg_system_utils/system_utils.h>\n#include <vector>\n\n// ds readability\ntypedef Eigen::Matrix<float, 4, 4> Matrix4f;\ntypedef std::vector<Matrix4f, Eigen::aligned_allocator<Matrix4f>> Matrix4fVector;\n\n// static parameter\nfloat lengths_small[] = {5, 10, 25, 50, 75, 100, 150, 200};\nfloat lengths_large[] = {100, 200, 300, 400, 500, 600, 700, 800};\nfloat* lengths        = lengths_large;\nint32_t num_lengths   = 8;\n\nconstexpr size_t minimum_number_of_samples_per_length = 3;\n\nstruct errors {\n  int32_t first_frame;\n  float r_err;\n  float t_err;\n  float len;\n  float speed;\n  errors(int32_t first_frame, float r_err, float t_err, float len, float speed) :\n    first_frame(first_frame),\n    r_err(r_err),\n    t_err(t_err),\n    len(len),\n    speed(speed) {\n  }\n};\n\nMatrix4fVector loadPoses(std::string file_name) {\n  Matrix4fVector poses;\n\n  // ds going modern\n  std::ifstream pose_file(file_name, std::ifstream::in);\n\n  // ds grab a line from the ground truth\n  std::string buffer_line;\n  while (std::getline(pose_file, buffer_line)) {\n    // ds get it to a std::stringstream\n    std::istringstream buffer_stream(buffer_line);\n\n    // ds information fields (KITTI format)\n    Matrix4f pose(Matrix4f::Identity());\n    for (uint8_t u = 0; u < 3; ++u) {\n      for (uint8_t v = 0; v < 4; ++v) {\n        buffer_stream >> pose(u, v);\n      }\n    }\n    poses.push_back(pose);\n  }\n\n  pose_file.close();\n  return poses;\n}\n\nstd::vector<float> trajectoryDistances(Matrix4fVector& poses) {\n  std::vector<float> dist;\n  dist.push_back(0);\n  for (std::size_t i = 1; i < poses.size(); i++) {\n    Matrix4f P1 = poses[i - 1];\n    Matrix4f P2 = poses[i];\n    float dx    = P1(0, 3) - P2(0, 3);\n    float dy    = P1(1, 3) - P2(1, 3);\n    float dz    = P1(2, 3) - P2(2, 3);\n    dist.push_back(dist[i - 1] + std::sqrt(dx * dx + dy * dy + dz * dz));\n  }\n  return dist;\n}\n\nint32_t lastFrameFromSegmentLength(std::vector<float>& dist, int32_t first_frame, float len) {\n  for (std::size_t i = first_frame; i < dist.size(); i++)\n    if (dist[i] > dist[first_frame] + len)\n      return i;\n  return -1;\n}\n\ninline float rotationError(Matrix4f& pose_error) {\n  float a = pose_error(0, 0);\n  float b = pose_error(1, 1);\n  float c = pose_error(2, 2);\n  float d = 0.5 * (a + b + c - 1.0);\n  return std::acos(std::max(std::min(d, 1.0f), -1.0f));\n}\n\ninline float translationError(Matrix4f& pose_error) {\n  float dx = pose_error(0, 3);\n  float dy = pose_error(1, 3);\n  float dz = pose_error(2, 3);\n  return std::sqrt(dx * dx + dy * dy + dz * dz);\n}\n\nstd::vector<errors> calcSequenceErrors(Matrix4fVector& poses_gt, Matrix4fVector& poses_result) {\n  // error std::vector\n  std::vector<errors> error_statistics;\n\n  // parameters\n  int32_t step_size = 10; // every second\n\n  // pre-compute distances (from ground truth as reference)\n  std::vector<float> dist = trajectoryDistances(poses_gt);\n\n  // for all start positions do\n  std::multiset<size_t> evaluated_lengths;\n  for (std::size_t first_frame = 0; first_frame < poses_gt.size(); first_frame += step_size) {\n    // for all segment lengths do\n    for (int32_t i = 0; i < num_lengths; i++) {\n      // current length\n      float len = lengths[i];\n\n      // compute last frame\n      int32_t last_frame = lastFrameFromSegmentLength(dist, first_frame, len);\n\n      // continue, if sequence not long enough\n      if (last_frame == -1) {\n        continue;\n      } else {\n        evaluated_lengths.insert(len);\n      }\n\n      // compute rotational and translational errors\n      Matrix4f pose_delta_gt     = poses_gt[first_frame].inverse() * poses_gt[last_frame];\n      Matrix4f pose_delta_result = poses_result[first_frame].inverse() * poses_result[last_frame];\n      Matrix4f pose_error        = pose_delta_result.inverse() * pose_delta_gt;\n      float r_err                = rotationError(pose_error);\n      float t_err                = translationError(pose_error);\n\n      // compute speed\n      float num_frames = (float) (last_frame - first_frame + 1);\n      float speed      = len / (0.1 * num_frames);\n\n      // write to file\n      error_statistics.push_back(errors(first_frame, r_err / len, t_err / len, len, speed));\n    }\n  }\n\n  // ds check sample distribution\n  size_t number_of_valid_lengths = 0;\n  for (size_t i = 0; i < static_cast<size_t>(num_lengths); ++i) {\n    if (evaluated_lengths.count(static_cast<size_t>(lengths[i])) > 6) {\n      std::cerr << lengths[i] << \" : \" << evaluated_lengths.count(static_cast<size_t>(lengths[i]))\n                << std::endl;\n      ++number_of_valid_lengths;\n    }\n  }\n\n  // ds if we did not manage to sample enough lengths and are not running on small samples already\n  if (number_of_valid_lengths < 3 && lengths != lengths_small) {\n    std::cerr << \"calcSequenceErrors|not enough samples, switching to smaller intervals\"\n              << std::endl;\n    lengths = lengths_small;\n    return calcSequenceErrors(poses_gt, poses_result);\n  } else {\n    return error_statistics;\n  }\n}\n\nvoid saveSequenceErrors(std::vector<errors>& err, std::string file_name) {\n  // open file\n  FILE* fp;\n  fp = fopen(file_name.c_str(), \"w\");\n\n  // write to file\n  for (std::vector<errors>::iterator it = err.begin(); it != err.end(); it++)\n    fprintf(fp, \"%d %f %f %f %f\\n\", it->first_frame, it->r_err, it->t_err, it->len, it->speed);\n\n  // close file\n  fclose(fp);\n  std::cerr << \"saveSequenceErrors|wrote to: '\" << file_name << \"'\" << std::endl;\n}\n\nvoid savePathPlot(Matrix4fVector& poses_gt, Matrix4fVector& poses_result, std::string file_name) {\n  // parameters\n  int32_t step_size = 3;\n\n  // open file\n  FILE* fp = fopen(file_name.c_str(), \"w\");\n\n  // save x/z coordinates of all frames to file\n  for (std::size_t i = 0; i < poses_gt.size(); i += step_size)\n    fprintf(fp,\n            \"%f %f %f %f\\n\",\n            poses_gt[i](0, 3),\n            poses_gt[i](2, 3),\n            poses_result[i](0, 3),\n            poses_result[i](2, 3));\n\n  // close file\n  fclose(fp);\n  std::cerr << \"savePathPlot|wrote to: '\" << file_name << \"'\" << std::endl;\n}\n\nstd::vector<int32_t> computeRoi(Matrix4fVector& poses_gt, Matrix4fVector& poses_result) {\n  float x_min = std::numeric_limits<int32_t>::max();\n  float x_max = std::numeric_limits<int32_t>::min();\n  float z_min = std::numeric_limits<int32_t>::max();\n  float z_max = std::numeric_limits<int32_t>::min();\n\n  for (Matrix4fVector::iterator it = poses_gt.begin(); it != poses_gt.end(); it++) {\n    float x = (*it)(0, 3);\n    float z = (*it)(2, 3);\n    if (x < x_min)\n      x_min = x;\n    if (x > x_max)\n      x_max = x;\n    if (z < z_min)\n      z_min = z;\n    if (z > z_max)\n      z_max = z;\n  }\n\n  for (Matrix4fVector::iterator it = poses_result.begin(); it != poses_result.end(); it++) {\n    float x = (*it)(0, 3);\n    float z = (*it)(2, 3);\n    if (x < x_min)\n      x_min = x;\n    if (x > x_max)\n      x_max = x;\n    if (z < z_min)\n      z_min = z;\n    if (z > z_max)\n      z_max = z;\n  }\n\n  float dx = 1.1 * (x_max - x_min);\n  float dz = 1.1 * (z_max - z_min);\n  float mx = 0.5 * (x_max + x_min);\n  float mz = 0.5 * (z_max + z_min);\n  float r  = 0.5 * std::max(dx, dz);\n\n  std::vector<int32_t> roi;\n  roi.push_back((int32_t)(mx - r));\n  roi.push_back((int32_t)(mx + r));\n  roi.push_back((int32_t)(mz - r));\n  roi.push_back((int32_t)(mz + r));\n  return roi;\n}\n\nint32_t plotPathPlot(std::string dir, std::vector<int32_t>& roi, int32_t idx) {\n  // gnuplot file name\n  char command[1024];\n  char file_name[256];\n  sprintf(file_name, \"%02d.gp\", idx);\n  std::string full_name = dir + \"/\" + file_name;\n\n  // ds system calls\n  int32_t result = 0;\n\n  // create png + eps\n  for (int32_t i = 0; i < 1 /*PNG only*/; i++) {\n    // open file\n    FILE* fp = fopen(full_name.c_str(), \"w\");\n\n    // save gnuplot instructions\n    if (i == 0) {\n      fprintf(fp, \"set term png size 900,900\\n\");\n      fprintf(fp, \"set output \\\"%02d.png\\\"\\n\", idx);\n    } else {\n      fprintf(fp, \"set term postscript eps enhanced color\\n\");\n      fprintf(fp, \"set output \\\"%02d.eps\\\"\\n\", idx);\n    }\n\n    fprintf(fp, \"set size ratio -1\\n\");\n    fprintf(fp, \"set xrange [%d:%d]\\n\", roi[0], roi[1]);\n    fprintf(fp, \"set yrange [%d:%d]\\n\", roi[2], roi[3]);\n    fprintf(fp, \"set xlabel \\\"x [m]\\\"\\n\");\n    fprintf(fp, \"set ylabel \\\"z [m]\\\"\\n\");\n    fprintf(\n      fp, \"plot \\\"%02d.txt\\\" using 1:2 lc rgb \\\"#FF0000\\\" title 'Ground Truth' w lines,\", idx);\n    fprintf(fp, \"\\\"%02d.txt\\\" using 3:4 lc rgb \\\"#0000FF\\\" title 'Visual Odometry' w lines,\", idx);\n    fprintf(fp,\n            \"\\\"< head -1 %02d.txt\\\" using 1:2 lc rgb \\\"#000000\\\" pt 4 ps 1 lw 2 title 'Sequence \"\n            \"Start' w points\\n\",\n            idx);\n\n    // close file\n    fclose(fp);\n    std::cerr << \"plotPathPlot|wrote to: '\" << full_name << \"'\" << std::endl;\n\n    // run gnuplot => create png + eps\n    sprintf(command, \"cd %s; gnuplot %s\", dir.c_str(), file_name);\n    result = system(command);\n    std::cerr << \"plotPathPlot|wrote to: '\" << file_name << \"'\" << std::endl;\n  }\n\n  // create pdf and crop TODO re-enable\n  //  sprintf(command, \"cd %s; ps2pdf %02d.eps %02d_large.pdf\", dir.c_str(), idx, idx);\n  //  result = system(command);\n  //  sprintf(command, \"cd %s; pdfcrop %02d_large.pdf %02d.pdf\", dir.c_str(), idx, idx);\n  //  result = system(command);\n  //  sprintf(command, \"cd %s; rm %02d_large.pdf\", dir.c_str(), idx);\n  //  result = system(command);\n  return result;\n}\n\nvoid saveErrorPlots(std::vector<errors>& seq_err, std::string plot_error_dir, const char* prefix) {\n  // file names\n  char file_name_tl[1024];\n  sprintf(file_name_tl, \"%s/%s_tl.txt\", plot_error_dir.c_str(), prefix);\n  char file_name_rl[1024];\n  sprintf(file_name_rl, \"%s/%s_rl.txt\", plot_error_dir.c_str(), prefix);\n  //  char file_name_ts[1024];\n  //  sprintf(file_name_ts, \"%s/%s_ts.txt\", plot_error_dir.c_str(), prefix);\n  //  char file_name_rs[1024];\n  //  sprintf(file_name_rs, \"%s/%s_rs.txt\", plot_error_dir.c_str(), prefix);\n\n  // open files\n  FILE* fp_tl = fopen(file_name_tl, \"w\");\n  FILE* fp_rl = fopen(file_name_rl, \"w\");\n  //  FILE* fp_ts = fopen(file_name_ts, \"w\");\n  //  FILE* fp_rs = fopen(file_name_rs, \"w\");\n\n  // for each segment length do\n  std::cerr << \"---------------------------- ERROR STATISTICS ----------------------------\"\n            << std::endl;\n  float total_error_rotation    = 0;\n  float total_error_translation = 0;\n  uint32_t number_of_lengths    = 0;\n  for (int32_t i = 0; i < num_lengths; i++) {\n    float t_err = 0;\n    float r_err = 0;\n    float num   = 0;\n\n    // for all errors do\n    for (std::vector<errors>::iterator it = seq_err.begin(); it != seq_err.end(); it++) {\n      if (fabs(it->len - lengths[i]) < 1.0) {\n        t_err += it->t_err;\n        r_err += it->r_err;\n        num++;\n      }\n    }\n\n    // ds we require at least 2 lengths to be evaluated\n    if (num > 1) {\n      fprintf(fp_tl, \"%f %f\\n\", lengths[i], t_err / num);\n      fprintf(fp_rl, \"%f %f\\n\", lengths[i], r_err / num);\n      total_error_rotation += r_err / num * (180 / M_PI) * 100;\n      total_error_translation += t_err / num * 100;\n      ++number_of_lengths;\n\n      // ds info\n      std::printf(\"length: %f error rotation (deg/100m): %9.6f error translation (%%): %9.6f\\n\",\n                  lengths[i],\n                  r_err / num * (180 / M_PI) * 100,\n                  t_err / num * 100);\n    }\n  }\n  std::cerr << \"---------------------------- ---------------- ----------------------------\"\n            << std::endl;\n  std::printf(\"average error rotation (deg/100m): %9.6f error translation (%%): %9.6f\\n\",\n              total_error_rotation / number_of_lengths,\n              total_error_translation / number_of_lengths);\n  std::cerr << \"---------------------------- ---------------- ----------------------------\"\n            << std::endl;\n\n  //  // for each driving speed do (in m/s)\n  //  for (float speed = 2; speed < 25; speed += 2) {\n  //    float t_err = 0;\n  //    float r_err = 0;\n  //    float num   = 0;\n  //\n  //    // for all errors do\n  //    for (std::vector<errors>::iterator it = seq_err.begin(); it != seq_err.end(); it++) {\n  //      if (fabs(it->speed - speed) < 2.0) {\n  //        t_err += it->t_err;\n  //        r_err += it->r_err;\n  //        num++;\n  //      }\n  //    }\n  //\n  //    // ds we require at least 2 lengths to be evaluated\n  //    if (num > 1) {\n  //      fprintf(fp_ts, \"%f %f\\n\", speed, t_err / num);\n  //      fprintf(fp_rs, \"%f %f\\n\", speed, r_err / num);\n  //    }\n  //  }\n\n  // close files\n  fclose(fp_tl);\n  fclose(fp_rl);\n  //  fclose(fp_ts);\n  //  fclose(fp_rs);\n}\n\nint32_t plotErrorPlots(std::string dir, const char* prefix) {\n  char command[1024];\n\n  // ds system calls\n  int32_t result = 0;\n\n  // for all four error plots do\n  for (int32_t i = 0; i < 2; i++) {\n    // create suffix\n    char suffix[16];\n    switch (i) {\n      case 0:\n        sprintf(suffix, \"tl\");\n        break;\n      case 1:\n        sprintf(suffix, \"rl\");\n        break;\n      case 2:\n        sprintf(suffix, \"ts\");\n        break;\n      case 3:\n        sprintf(suffix, \"rs\");\n        break;\n    }\n\n    // gnuplot file name\n    char file_name[1024];\n    char full_name[1024];\n    sprintf(file_name, \"%s_%s.gp\", prefix, suffix);\n    sprintf(full_name, \"%s/%s\", dir.c_str(), file_name);\n\n    // create png + eps\n    for (int32_t j = 0; j < 1 /*PNG only*/; j++) {\n      // open file\n      FILE* fp = fopen(full_name, \"w\");\n\n      // save gnuplot instructions\n      if (j == 0) {\n        fprintf(fp, \"set term png size 500,250 font \\\"Helvetica\\\" 11\\n\");\n        fprintf(fp, \"set output \\\"%s_%s.png\\\"\\n\", prefix, suffix);\n      } else {\n        fprintf(fp, \"set term postscript eps enhanced color\\n\");\n        fprintf(fp, \"set output \\\"%s_%s.eps\\\"\\n\", prefix, suffix);\n      }\n\n      // start plot at 0\n      fprintf(fp, \"set size ratio 0.5\\n\");\n      fprintf(fp, \"set yrange [0:*]\\n\");\n\n      // x label\n      if (i <= 1)\n        fprintf(fp, \"set xlabel \\\"Path Length [m]\\\"\\n\");\n      else\n        fprintf(fp, \"set xlabel \\\"Speed [km/h]\\\"\\n\");\n\n      // y label\n      if (i == 0 || i == 2)\n        fprintf(fp, \"set ylabel \\\"Translation Error [%%]\\\"\\n\");\n      else\n        fprintf(fp, \"set ylabel \\\"Rotation Error [deg/m]\\\"\\n\");\n\n      // plot error curve\n      fprintf(fp, \"plot \\\"%s_%s.txt\\\" using \", prefix, suffix);\n      switch (i) {\n        case 0:\n          fprintf(fp, \"1:($2*100) title 'Translation Error'\");\n          break;\n        case 1:\n          fprintf(fp, \"1:($2*57.3) title 'Rotation Error'\");\n          break;\n        case 2:\n          fprintf(fp, \"($1*3.6):($2*100) title 'Translation Error'\");\n          break;\n        case 3:\n          fprintf(fp, \"($1*3.6):($2*57.3) title 'Rotation Error'\");\n          break;\n      }\n      fprintf(fp, \" lc rgb \\\"#0000FF\\\" pt 4 w linespoints\\n\");\n\n      // close file\n      fclose(fp);\n\n      // run gnuplot => create png + eps\n      sprintf(command, \"cd %s; gnuplot %s\", dir.c_str(), file_name);\n      result = system(command);\n      std::cerr << \"plotErrorPlots|wrote to: '\" << dir + \"/\" + file_name << \"'\" << std::endl;\n    }\n\n    // create pdf and crop TODO re-enable\n    //    sprintf(command,\n    //            \"cd %s; ps2pdf %s_%s.eps %s_%s_large.pdf\",\n    //            dir.c_str(),\n    //            prefix,\n    //            suffix,\n    //            prefix,\n    //            suffix);\n    //    result = system(command);\n    //    sprintf(command,\n    //            \"cd %s; pdfcrop %s_%s_large.pdf %s_%s.pdf\",\n    //            dir.c_str(),\n    //            prefix,\n    //            suffix,\n    //            prefix,\n    //            suffix);\n    //    result = system(command);\n    //    sprintf(command, \"cd %s; rm %s_%s_large.pdf\", dir.c_str(), prefix, suffix);\n    //    result = system(command);\n  }\n\n  return result;\n}\n\nvoid saveStats(std::vector<errors> err, std::string dir) {\n  float t_err = 0;\n  float r_err = 0;\n\n  // for all errors do => compute sum of t_err, r_err\n  for (std::vector<errors>::iterator it = err.begin(); it != err.end(); it++) {\n    t_err += it->t_err;\n    r_err += it->r_err;\n  }\n\n  // open file\n  FILE* fp = fopen((dir + \"/stats.txt\").c_str(), \"w\");\n\n  // save errors\n  float num = err.size();\n  fprintf(fp, \"%f %f\\n\", t_err / num, r_err / num);\n\n  // close file\n  fclose(fp);\n  std::cerr << \"saveStats|wrote to '\" << dir + \"/stats.txt\"\n            << \"'\" << std::endl;\n}\n\nint eval(const std::string& file_trajectory_test_,\n         const std::string& file_trajectory_ground_truth_,\n         const std::string& file_sequence_) {\n  // ground truth and result directories\n  const std::string result_dir     = \"results\";\n  const std::string error_dir      = result_dir + \"/errors\";\n  const std::string plot_path_dir  = result_dir + \"/plot_path\";\n  const std::string plot_error_dir = result_dir + \"/plot_error\";\n\n  // create output directories TODO evil evil\n  int32_t result = system((\"mkdir -p \" + result_dir).c_str());\n  result         = system((\"mkdir -p \" + error_dir).c_str());\n  result         = system((\"mkdir -p \" + plot_path_dir).c_str());\n  result         = system((\"mkdir -p \" + plot_error_dir).c_str());\n  if (result < 0) {\n    std::cerr << \"eval|ERROR: system io error\" << std::endl;\n    return -1;\n  }\n\n  // read ground truth and result poses\n  Matrix4fVector poses_gt     = loadPoses(file_trajectory_ground_truth_);\n  Matrix4fVector poses_result = loadPoses(file_trajectory_test_);\n\n  // ds parse sequence number\n  const std::string sequence_number_literal = file_sequence_.substr(0, 2);\n  const uint32_t sequence_number            = std::stoi(sequence_number_literal);\n\n  // plot status\n  printf(\"Processing: %s (sequence: %i), poses: %lu/%lu\\n\",\n         file_sequence_.c_str(),\n         sequence_number,\n         poses_result.size(),\n         poses_gt.size());\n\n  // check for errors\n  if (poses_gt.size() == 0 || poses_result.size() != poses_gt.size()) {\n    std::cerr << \"eval|ERROR: Couldn't read (all) poses of: \" << file_sequence_ << std::endl;\n    return -1;\n  }\n\n  // compute sequence errors\n  std::vector<errors> seq_err = calcSequenceErrors(poses_gt, poses_result);\n  saveSequenceErrors(seq_err, error_dir + \"/\" + file_sequence_);\n\n  // for first half => plot trajectory and compute individual stats\n  // save + plot bird's eye view trajectories\n  savePathPlot(poses_gt, poses_result, plot_path_dir + \"/\" + file_sequence_);\n  std::vector<int32_t> roi = computeRoi(poses_gt, poses_result);\n  result                   = plotPathPlot(plot_path_dir, roi, sequence_number);\n  if (result != 0) {\n    std::cerr << \"eval|ERROR: unable to plot path\" << std::endl;\n    return -1;\n  }\n\n  // save + plot individual errors\n  saveErrorPlots(seq_err, plot_error_dir, sequence_number_literal.c_str());\n  result = plotErrorPlots(plot_error_dir, sequence_number_literal.c_str());\n  if (result != 0) {\n    std::cerr << \"eval|ERROR: unable to plot error statistics\" << std::endl;\n    return -1;\n  }\n\n  return result;\n}\n\nconst std::string banner =\n  \"\\n\\nUsage: ./srrg_kitti_evaluate_odometry_app -gt <string> -odom <string> -seq <string>\\n\"\n  \"Example: ./srrg_kitti_evaluate_odometry_app -gt 00.txt -odom tracker_output.txt -seq 00.txt\\n\"\n  \"Options:\\n\"\n  \"------------------------------------------\\n\"\n  \"-gt <string>                path to ground_truth file\\n\"\n  \"-odom <string>              path to tracker odometry path\\n\"\n  \"-seq <string>               sequence number, e.g. '00.txt' if not set, then seq=gt\\n\"\n  \"-h                          this help\\n\";\n\n// ds parameters\nstd::string file_tracked_odometry = \"\";\nstd::string file_ground_truth     = \"\";\nstd::string file_sequence         = \"\";\n\n// ds parse parameters\nint c = 1;\n\nint32_t main(int32_t argc, char** argv) {\n  // ds always expects 6 arguments\n  if (argc != 7) {\n    std::cerr << banner << std::endl;\n    return -1;\n  }\n\n  // ds parameters\n  std::string file_tracked_odometry = \"\";\n  std::string file_ground_truth     = \"\";\n  std::string file_sequence         = \"\";\n\n  // ds parse parameters\n  int c = 1;\n  while (c < argc) {\n    if (!strcmp(argv[c], \"-h\")) {\n      std::cerr << banner << std::endl;\n      return -1;\n    } else if (!strcmp(argv[c], \"-gt\")) {\n      c++;\n      file_ground_truth = argv[c];\n    } else if (!strcmp(argv[c], \"-odom\")) {\n      c++;\n      file_tracked_odometry = argv[c];\n    } else if (!strcmp(argv[c], \"-seq\")) {\n      c++;\n      file_sequence = argv[c];\n    }\n    c++;\n  }\n\n  // ds input validation\n  if (file_sequence.empty())\n    file_sequence = file_ground_truth;\n\n  if (file_sequence.find(\".txt\") == std::string::npos) {\n    std::cerr << \"ERROR: missing file ending (e.g. txt) in provided sequence file: \"\n              << file_sequence << std::endl;\n    return -1;\n  }\n\n  // ds configuration\n  std::cerr << \"file_ground_truth: \" << file_ground_truth << std::endl;\n  std::cerr << \"file_tracked_odometry: \" << file_tracked_odometry << std::endl;\n  std::cerr << \"file_sequence: \" << file_sequence << std::endl;\n\n  // run evaluation\n  return eval(file_tracked_odometry, file_ground_truth, file_sequence);\n}\n", "meta": {"hexsha": "468e73ba9a292d3123ca8724be1e877c0f5c7307", "size": 21138, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "catkin_ws/src/srrg2_core/srrg2_core/apps/geigerzaehler.cpp", "max_stars_repo_name": "laaners/progetto-labiagi_pick_e_delivery", "max_stars_repo_head_hexsha": "3453bfbc1dd7562c78ba06c0f79b069b0a952c0e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-03-11T14:36:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-09T09:01:15.000Z", "max_issues_repo_path": "catkin_ws/src/srrg2_core/srrg2_core/apps/geigerzaehler.cpp", "max_issues_repo_name": "laaners/progetto-labiagi_pick_e_delivery", "max_issues_repo_head_hexsha": "3453bfbc1dd7562c78ba06c0f79b069b0a952c0e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-06-07T17:25:04.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-15T07:36:10.000Z", "max_forks_repo_path": "catkin_ws/src/srrg2_core/srrg2_core/apps/geigerzaehler.cpp", "max_forks_repo_name": "laaners/progetto-labiagi_pick_e_delivery", "max_forks_repo_head_hexsha": "3453bfbc1dd7562c78ba06c0f79b069b0a952c0e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-11-30T08:17:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-19T05:07:07.000Z", "avg_line_length": 32.0272727273, "max_line_length": 99, "alphanum_fraction": 0.5819850506, "num_tokens": 6163, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.47760165437523305}}
{"text": "#include <cstring>\n#include <numeric>\n#include <vector>\n#include <array>\n#include <random>\n\n#include <boost/test/unit_test.hpp>\n\n#include <cereal/cereal.hpp>\n#include <cereal/types/bitset.hpp>\n#include <cereal/archives/xml.hpp>\n#include <cereal/archives/binary.hpp>\n#include <cereal/archives/portable_binary.hpp>\n\n#include <sstream>\n\n#include \"rfr/data_containers/default_data_container.hpp\"\n#include \"rfr/splits/binary_split_one_feature_rss_loss.hpp\"\n\ntypedef double num_t;\ntypedef unsigned int index_t;\ntypedef std::default_random_engine rng_type;\n\ntypedef rfr::data_containers::default_container<num_t, num_t, index_t> data_container_type;\ntypedef rfr::splits::binary_split_one_feature_rss_loss<num_t, num_t, index_t,rng_type,128> split_type;\ntypedef rfr::splits::data_info_t<num_t, num_t, index_t> info_t;\n\n\ntemplate <class T>\nvoid print_vector (T v){\n\tfor (auto e : v)\n\t\tstd::cout<<e<<\", \";\n\tstd::cout<<\"\\b\\b\\n\";\n}\n\n\nvoid print_pcs (std::vector<std::vector<num_t> > pcs){\n\tfor (auto i: pcs){\n\t\tprint_vector(i);\n\t}\n}\n\n\ndata_container_type load_toy_data(){\n\tdata_container_type data(2);\n\t\n    std::string feature_file, response_file;\n    \n    feature_file  = std::string(boost::unit_test::framework::master_test_suite().argv[1]) + \"toy_data_set_features.csv\";\n    response_file = std::string(boost::unit_test::framework::master_test_suite().argv[1]) + \"toy_data_set_responses.csv\";\n\n    data.import_csv_files(feature_file, response_file);\n\t\n\tdata.set_type_of_feature(1,10);\n\n\tBOOST_REQUIRE_EQUAL(data.get_type_of_feature(1), 10);\n\t\n    return(data);\n}\n\n\n\n\n\nBOOST_AUTO_TEST_CASE(binary_split_one_feature_rss_loss_continuous_split_test){\n\t\n\tauto data = load_toy_data();\n\t\n    std::vector<info_t > data_info(data.num_data_points());\n\t\n\tfor (auto i=0u; i<data.num_data_points(); ++i){\n\t\tdata_info[i].index=i;\n\t\tdata_info[i].response = data.response(i);\n\t\tdata_info[i].weight = 1;\n\n\t}\n\n\tstd::array<std::vector<info_t>::iterator, 3> infos_split_it;\n\tstd::vector<index_t> features_to_try(1,0);\n\n\trng_type rng;\n\n\tsplit_type split1;\n\tnum_t loss = split1.find_best_split(data, features_to_try,data_info.begin(), data_info.end(),infos_split_it,1, 1, rng);\n\n\t// actual loss independently computed in python\n\tBOOST_REQUIRE_CLOSE(loss, 23.33333333, 1e-4);\n\t\n\t// split criterion has to be in [59, 60) -> see python reference\n\tnum_t split_val = split1.get_num_split_value();\n\n\tBOOST_REQUIRE(split_val >=59);\n\tBOOST_REQUIRE(split_val < 60);\n\t\n\t// test the () operator for the trainings data\n\tstd::vector<index_t> operator_test = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1};\n\t\n\tfor (size_t i=0; i<operator_test.size(); i++){\n\t\tstd::vector<num_t> tmp_feature_vector ({data.feature(0,i), data.feature(1,i)});\n\t\tBOOST_REQUIRE(split1(tmp_feature_vector) == operator_test[i]);\n\t}\n\t\n\tstd::vector<std::vector<num_t> > pcs = { {-1000, 1000}, {0,1,2,3,4,5,6,7,8,9}};\n\t\n\tauto pcss = split1.compute_subspaces(pcs);\n\t\n\tBOOST_REQUIRE(std::find(pcss[0][1].begin(), pcss[0][1].end(), 0) != pcss[0][1].end());\n\n\n\tBOOST_CHECK_EQUAL(pcss[0][0][0], pcs[0][0]);\n\tBOOST_CHECK_EQUAL(pcss[0][0][1], split_val);\n\tBOOST_CHECK_EQUAL(pcss[1][0][0], split_val);\n\tBOOST_CHECK_EQUAL(pcss[1][0][1], pcs[0][1]);\n\n\n\t// make sure that x2 has not been altered\n\tBOOST_CHECK_EQUAL_COLLECTIONS( pcss[0][1].begin(), pcss[0][1].end(),\n\t\t\t\t\t\t\t\t\tpcs[1].begin(), pcs[1].end());\n\t\n\tBOOST_CHECK_EQUAL_COLLECTIONS( pcss[1][1].begin(), pcss[1][1].end(),\n\t\t\t\t\t\t\t\t\tpcs[1].begin(), pcs[1].end());\n\n\n\tsplit1.print_info();\n\t\n}\n\n\nBOOST_AUTO_TEST_CASE(binary_split_one_feature_rss_loss_categorical_split_test){\n\t\n\tauto data = load_toy_data();\n\t\n    \n    std::vector<info_t > data_info(data.num_data_points());\n\t\n\tfor (auto i=0u; i<data.num_data_points(); ++i){\n\t\tdata_info[i].index=i;\n\t\tdata_info[i].response = data.response(i);\n\t\tdata_info[i].weight = 1;\n\n\t}\n\n\tstd::array<std::vector<info_t>::iterator, 3> infos_split_it;\n\tstd::vector<index_t> features_to_try(1,1);\n\n\trng_type rng;\n\n\tsplit_type split2;\n\tnum_t loss = split2.find_best_split(data, features_to_try,data_info.begin(), data_info.end(),infos_split_it, 1, 1, rng);\n\n    num_t total_weight = 0;\n    for (auto it = infos_split_it[0]; it!=infos_split_it[1]; ++it)\n        total_weight += (*it).weight;\n    for (auto it = infos_split_it[1]; it!=infos_split_it[2]; ++it)\n        total_weight += (*it).weight;\n    BOOST_REQUIRE_CLOSE(total_weight, data.num_data_points(), 1e-4);    \n    \n\t// actual best split and loss independently computed in python\n\tBOOST_REQUIRE_CLOSE(loss, 88.57142857, 1e-6);\n\tauto split_set = split2.get_cat_split_set();\n\tstd::cout<< split2.get_num_split_value()<<std::endl;\n\tstd::cout<< split_set<<std::endl;\n\tBOOST_REQUIRE(split_set[0]);\n\tBOOST_REQUIRE(split_set[1]);\n\tBOOST_REQUIRE(!split_set[2]);\n\t\n\t\n\t// test the () operator for the trainings data\n\tstd::vector<index_t> operator_test = {0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1};\n\t\n\n\t// test the pcs splitting\n\tfor (size_t i=0; i<operator_test.size(); i++){\n\t\tstd::vector<num_t> tmp_feature_vector ({data.feature(0,i), data.feature(1,i)});\n\t\tBOOST_CHECK_MESSAGE(split2(tmp_feature_vector) == operator_test[i],split2(tmp_feature_vector) << \"!=\" <<  operator_test[i]<<\" (index \"<<i<<\")\\n\");\n\t}\n\t\n\tstd::vector<std::vector<num_t> > pcs = { {-1000, 1000}, {0,1,2,3,4,5,6,7,8,9}};\n\t\n\tauto pcss = split2.compute_subspaces(pcs);\n\t\n\tBOOST_REQUIRE( pcss[0][0][0] == pcs[0][0]);BOOST_REQUIRE( pcss[0][0][1] == pcs[0][1]);\n\tBOOST_REQUIRE( pcss[1][0][0] == pcs[0][0]);BOOST_REQUIRE( pcss[0][0][1] == pcs[0][1]);\n\t\n\tBOOST_REQUIRE(std::find(pcss[0][1].begin(), pcss[0][1].end(), 0) != pcss[0][1].end());\n\tBOOST_REQUIRE(std::find(pcss[0][1].begin(), pcss[0][1].end(), 1) != pcss[0][1].end());\n\tBOOST_REQUIRE(std::find(pcss[0][1].begin(), pcss[0][1].end(), 2) == pcss[0][1].end());\n\t\n\tBOOST_REQUIRE(std::find(pcss[1][1].begin(), pcss[1][1].end(), 0) == pcss[1][1].end());\n\tBOOST_REQUIRE(std::find(pcss[1][1].begin(), pcss[1][1].end(), 1) == pcss[1][1].end());\n\tBOOST_REQUIRE(std::find(pcss[1][1].begin(), pcss[1][1].end(), 2) != pcss[1][1].end());\n\n\n\t// test the can_be_split_function\n\t\n\tstd::vector<num_t> eevee (data.num_features(), 0);\n\n\tBOOST_REQUIRE(split2.can_be_split(eevee));\n\n\teevee[split2.get_feature_index()] = NAN;\n\n\tBOOST_REQUIRE(!split2.can_be_split(eevee));\n\n\tsplit2.print_info();\n\t\n}\n\n\n// check if it finds the best split out of the two above\nBOOST_AUTO_TEST_CASE(binary_split_one_feature_rss_loss_find_best_split_test){\n\n\tauto data = load_toy_data();\n\n    std::vector<info_t > data_info(data.num_data_points());    \n\tfor (auto i=0u; i<data.num_data_points(); ++i){\n\t\tdata_info[i].index=i;\n\t\tdata_info[i].response = data.response(i);\n\t\tdata_info[i].weight = 1;\n\t}\n\n\tstd::array<std::vector<info_t>::iterator, 3> infos_split_it;\n\tstd::vector<index_t> features_to_try({0,1});\n\n\trng_type rng;\n\n\tsplit_type split3;\n\tnum_t loss = split3.find_best_split(data, features_to_try,data_info.begin(), data_info.end(),infos_split_it, 1, 1, rng);\n\tBOOST_REQUIRE_CLOSE(loss, 23.33333333, 1e-4);\n    \n    num_t total_weight = 0;\n    for (auto it = infos_split_it[0]; it!=infos_split_it[1]; ++it)\n        total_weight += (*it).weight;\n    for (auto it = infos_split_it[1]; it!=infos_split_it[2]; ++it)\n        total_weight += (*it).weight;\n    BOOST_REQUIRE_CLOSE(total_weight, data.num_data_points(), 1e-4);\n    \n    \n\n\t\n\tnum_t split_val = split3.get_num_split_value();\n\n\tBOOST_REQUIRE(split_val >=59);\n\tBOOST_REQUIRE(split_val < 60);\n}\n\n\n\n// test serialization\nBOOST_AUTO_TEST_CASE(binary_split_one_feature_rss_loss_serialization){\n\n    auto data = load_toy_data();\n    \n\tstd::vector<info_t > data_info(data.num_data_points());\n\t\n\tfor (auto i=0u; i<data.num_data_points(); ++i){\n\t\tdata_info[i].index=i;\n\t\tdata_info[i].response = data.response(i);\n\t\tdata_info[i].weight = 1;\n\n\t}\n\n\tstd::array<std::vector<info_t>::iterator, 3> infos_split_it;\n\tstd::vector<index_t> features_to_try({0,1});\n\n\trng_type rng;\n\n\n\tsplit_type split4;\n\tnum_t loss = split4.find_best_split(data, features_to_try,data_info.begin(), data_info.end(),infos_split_it, 1, 1, rng);\n\n    num_t total_weight = 0;\n    for (auto it = infos_split_it[0]; it!=infos_split_it[1]; ++it)\n        total_weight += (*it).weight;\n    for (auto it = infos_split_it[1]; it!=infos_split_it[2]; ++it)\n        total_weight += (*it).weight;\n    BOOST_REQUIRE_CLOSE(total_weight, data.num_data_points(), 1e-4);\n    \n\tindex_t index4 = split4.get_feature_index();\n\tauto split_val = split4.get_num_split_value();\n\tauto split_bits= split4.get_cat_split_set();\n\tstd::ostringstream oss;\n\t{\n\t\tcereal::XMLOutputArchive oarchive(oss);\n\t\toarchive(split4);\n\t}\n\t\n\t\t\n\tsplit_type split5;\n\t{\n\t\tstd::istringstream iss(oss.str());\n\t\tcereal::XMLInputArchive iarchive(iss);\n\t\tiarchive(split5);\n\t}\n\t\n\tBOOST_REQUIRE(index4     == split5.get_feature_index());\n\tBOOST_REQUIRE(split_val  == split5.get_num_split_value());\n\tBOOST_REQUIRE(split_bits == split5.get_cat_split_set());\n\t\n}\n\n\n// test binary serialization\nBOOST_AUTO_TEST_CASE(binary_split_one_feature_rss_loss_binary_serialization){\n\t\n\tauto data = load_toy_data();\n\n\tstd::vector<info_t > data_info(data.num_data_points());\n\t\n\tfor (auto i=0u; i<data.num_data_points(); ++i){\n\t\tdata_info[i].index=i;\n\t\tdata_info[i].response = data.response(i);\n\t\tdata_info[i].weight = 1;\n\n\t}\n\n\tstd::array<std::vector<info_t>::iterator, 3> infos_split_it;\n\tstd::vector<index_t> features_to_try({0,1});\n\n\trng_type rng;\n\n\n\tsplit_type split4;\n\tnum_t loss = split4.find_best_split(data, features_to_try,data_info.begin(), data_info.end(),infos_split_it, 1, 1, rng);\n\n    num_t total_weight = 0;\n    for (auto it = infos_split_it[0]; it!=infos_split_it[1]; ++it)\n        total_weight += (*it).weight;\n    for (auto it = infos_split_it[1]; it!=infos_split_it[2]; ++it)\n        total_weight += (*it).weight;\n    BOOST_REQUIRE_CLOSE(total_weight, data.num_data_points(), 1e-4);\n    \n\t\n\tindex_t index4 = split4.get_feature_index();\n\tauto split_val = split4.get_num_split_value();\n\tauto split_bits= split4.get_cat_split_set();\n\n\tstd::ostringstream oss;\n\t{\n\t\tcereal::PortableBinaryOutputArchive oarchive(oss);\n\t\toarchive(split4);\n\t}\n\t\n\t\t\n\tsplit_type split5;\n\t{\n\t\tstd::istringstream iss(oss.str());\n\t\tcereal::PortableBinaryInputArchive iarchive(iss);\n\t\tiarchive(split5);\n\t}\n\t\n\tBOOST_REQUIRE_EQUAL(index4,    split5.get_feature_index());\n\tBOOST_REQUIRE_EQUAL(split_val, split5.get_num_split_value());\n\tBOOST_REQUIRE_EQUAL(split_bits,split5.get_cat_split_set());\n\t\n}\n\n", "meta": {"hexsha": "c5b8ab215f85132ec819a2c6e78ebb43efe87580", "size": 10679, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/unit_test_binary_splits.cpp", "max_stars_repo_name": "sslavian812/random_forest_run", "max_stars_repo_head_hexsha": "a533f2b8fa3d81fbf358cd211317a61af9651de8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/unit_test_binary_splits.cpp", "max_issues_repo_name": "sslavian812/random_forest_run", "max_issues_repo_head_hexsha": "a533f2b8fa3d81fbf358cd211317a61af9651de8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2021-02-12T22:47:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-19T23:33:47.000Z", "max_forks_repo_path": "tests/unit_test_binary_splits.cpp", "max_forks_repo_name": "franchuterivera/test_bots", "max_forks_repo_head_hexsha": "7d682f96fa9d29c3c625201aac2ea0dfee8467a5", "max_forks_repo_licenses": ["BSD-3-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.9131652661, "max_line_length": 240, "alphanum_fraction": 0.691918719, "num_tokens": 3394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.47760165437523305}}
{"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\n#include <Eigen/Dense>\n\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/math/distributions/inverse_gamma.hpp>\n\n#include <boost/random/chi_squared_distribution.hpp>\n#include <boost/random/normal_distribution.hpp>\n\n#include <dpMM/basemeasure.hpp>\n#include <dpMM/distribution.hpp>\n#include <dpMM/normalSphere.hpp>\n#include <dpMM/iw.hpp>\n#include <dpMM/sphere.hpp>\n#include <dpMM/karcherMean.hpp>\n\nusing namespace Eigen;\nusing std::endl;\nusing std::cout;\n\n/* Actually just places an IW prior on covariances in the tangent\n * plane. \n *\n * The point of tangentcy has to be set \"manually\". This makes the\n * clase usefull for models that externaly update the point of tangency\n * such as the Manhattan Frame \n */\ntemplate<typename T>\nclass IwTangent : public BaseMeasure<T>\n{\npublic:\n\n  IW<T> iw0_; // IW prior on the covariance of the normal in T_\\muS^D\n  Sphere<T> S_;\n  NormalSphere<T> normalS_; // normal on sphere\n\n  IwTangent(const IW<T>& iw, boost::mt19937* pRndGen);\n  ~IwTangent();\n\n  virtual BaseMeasure<T>* copy();\n  virtual IwTangent<T>* copyNative();\n\n  virtual baseMeasureType getBaseMeasureType() const {return(NIW_TANGENT); }\n\n  /* for any point on the sphere; maps into T_muS and rotates north first */\n  virtual T logLikelihood(const Matrix<T,Dynamic,1>& x) const ;\n  virtual T logLikelihood(const Matrix<T,Dynamic,Dynamic>& x, uint32_t i) const \n    {return logLikelihood(x.col(i));};\n  // right now this does not support actual scatter!  it supports\n  // weighted directional data though.  count is the weight\n  // [counts,karcherMean,scatter around KarcherMean] \n  virtual T logLikelihoodFromSS(const Matrix<T,Dynamic,1>& x) const;\n  /* assumes x is already in T_northS */\n  virtual T logLikelihoodNorth(const Matrix<T,Dynamic,1>& x) const ;\n\n  void posterior(const Matrix<T,Dynamic,Dynamic>& x, const VectorXu& z, \n    uint32_t k);\n  void posterior(const shared_ptr<ClGMMData<T> >& cldp, uint32_t k);\n  /* assumes the x are already in T_northS correctly */\n  void posteriorFromPtsInTpS(const Matrix<T,Dynamic,Dynamic>& x, \n    const VectorXu& z, uint32_t k);\n  // right now this does not support actual scatter!  it supports\n  // weighted directional data though.  count is the weight\n  // [counts,karcherMean,scatter around KarcherMean] \n  void posteriorFromSS(const vector<Matrix<T,Dynamic,1> >&x, const\n      VectorXu& z, uint32_t k);\n  void posteriorFromSS(const Matrix<T,Dynamic,1> &x);\n\n  void sample();\n\n  T logPdfUnderPrior() const;\n  T logPdfUnderPriorMarginalized() const;\n//  T logPdfUnderPriorMarginalizedMerged(const shared_ptr<IwTangent<T> >& other) const;\n\n  void print() const;\n  virtual uint32_t getDim() const {return(uint32_t(normalS_.D_));}; \n\n//  virtual IwTangent<T>* merge(const IwTangent<T>& other);\n//  void fromMerge(const IwTangent<T>& niwA, const IwTangent<T>& niwB);\n\n  const Matrix<T,Dynamic,Dynamic>& scatter() const {return iw0_.scatter();};\n  Matrix<T,Dynamic,Dynamic>& scatter() {return iw0_.scatter();};\n  T count() const {return iw0_.count();};\n  T& count() {return iw0_.count();};\n\n  const Matrix<T,Dynamic,Dynamic>& Sigma() const {return normalS_.Sigma();};\n\n  const Matrix<T,Dynamic,1>& getMean() const {return normalS_.getMean();};\n  void setMean(const Matrix<T,Dynamic,1>& mean) {return normalS_.setMean(mean);};\n\nprivate:\n\n//  void computeMergedSS( const IwTangent<T>& niwA, \n//    const IwTangent<T>& niwB, Matrix<T,Dynamic,Dynamic>& scatterM, \n//    Matrix<T,Dynamic,1>& muM, T& countM) const;\n\n\n};\n\ntypedef IwTangent<double> IwTangentd;\ntypedef IwTangent<float> IwTangentf;\n\n", "meta": {"hexsha": "3cb025a0c4ee48f304836d737f6d256e6cc61aae", "size": 3734, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/dpMM/iwTangent.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/iwTangent.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/iwTangent.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": 34.8971962617, "max_line_length": 87, "alphanum_fraction": 0.7198714515, "num_tokens": 1048, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390746, "lm_q2_score": 0.6187804337438502, "lm_q1q2_score": 0.47760165437523305}}
{"text": "//Copyright (C) 2011 Pierre Moulon\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#ifndef LIBS_SVD_H_\n#define LIBS_SVD_H_\n\n#include <Eigen/Core>\n#include <Eigen/SVD>\n#include \"extras/libNumerics/matrix.h\"\n#include \"third_party/svd/matConversion.hpp\"\n#include \"third_party/svd/eigenWrapper.hpp\"\n\nnamespace SVDWrapper {\n\n  typedef libNumerics::matrix<double> Mat;\n  typedef libNumerics::vector<double> Vec;\n  typedef Eigen::MatrixXd MatEigen;\n\n  /// Solve the linear system Ax = 0 with ||x|| = 1.0 via SVD.\n  /// Return true if the ratio of singular values SV(0)/SV(N-2) < dRatio.\n  /// The return value indicates whether the solution is unique.\n  static bool Nullspace(const Mat & A, Vec *nullspace, double dRatio=1e-5)\n  {\n    typedef Eigen::MatrixXd MatEigen;\n    MatEigen AEigen, null;\n    EigenWrapper::MatToEigen(A, AEigen);\n    bool bOk = EigenWrapper::Nullspace(&AEigen, &null, dRatio);\n    (*nullspace).read( null.data() );\n    return bOk;\n  }\n\n  /// Inverse of norm-2 condition value (ratio of extreme singular values)\n  inline double InvCond(const Mat& A) {\n    Eigen::MatrixXd AEigen, sing;\n    EigenWrapper::MatToEigen(A, AEigen);\n    EigenWrapper::SingularValues(&AEigen, &sing);\n    return sing(A.nrow()-1)/sing(0);\n  }\n\n  /// Make rank<=2.\n  inline void EnforceRank2_3x3(const Mat& A, Mat *ARank)\n  {\n    Eigen::MatrixXd MEigen, MRank2Eigen;\n    EigenWrapper::MatToEigen(A, MEigen);\n    EigenWrapper::EnforceRank2_3x3(MEigen, &MRank2Eigen);\n    EigenWrapper::EigenToMat(MRank2Eigen, *ARank);\n  }\n\n  /// Save the two last nullspace vector as 3x3 matrices.\n  /// It uses Eigen to compute the SVD decomposition.\n  inline void Nullspace2_Remap33(const Mat &A, Mat& f1, Mat& f2) {\n      using Eigen::Map;\n      using namespace EigenWrapper;\n\n      MatEigen f1E, f2E;\n      MatEigen AEigen;\n      MatToEigen(A, AEigen);\n      Nullspace2(&AEigen, &f1E, &f2E);\n\n      typedef Eigen::Matrix<double, 3, 3> Mat3;\n      typedef Eigen::Matrix<double, 3, 3, Eigen::RowMajor> RMat3;\n      // Update f1 and f2\n      EigenToMat(Map<RMat3>(f1E.data()), f1);\n      EigenToMat(Map<RMat3>(f2E.data()), f2);\n  }\n\n} // namespace SVDWrapper\n\n\n#endif // LIBS_SVD_H_\n", "meta": {"hexsha": "83a65cc7c1b5a4e957fa317cb2b8056cfbd52449", "size": 2748, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "OrsaHomography/third_party/svd/svd.hpp", "max_stars_repo_name": "alicevision/KVLD", "max_stars_repo_head_hexsha": "3323458197cb29223f3a09a7906c92aab0b3916b", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 36.0, "max_stars_repo_stars_event_min_datetime": "2015-06-01T12:14:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-25T02:27:26.000Z", "max_issues_repo_path": "OrsaHomography/third_party/svd/svd.hpp", "max_issues_repo_name": "Zhe-LIU-Imagine/MRMS_online", "max_issues_repo_head_hexsha": "fe406cc3aea20aa186e57c03e809773e922978aa", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2017-05-09T07:20:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-20T04:59:39.000Z", "max_forks_repo_path": "OrsaHomography/third_party/svd/svd.hpp", "max_forks_repo_name": "Zhe-LIU-Imagine/KVLD", "max_forks_repo_head_hexsha": "77eb60c50a911c2c4bd9dc770ba8cce1cf33f6f2", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2016-01-14T15:40:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-04T16:01:01.000Z", "avg_line_length": 33.1084337349, "max_line_length": 74, "alphanum_fraction": 0.7019650655, "num_tokens": 772, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390746, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.47760165437523294}}
{"text": "// Loba2d library\n\n// Copyright (c) 2015 Andrii Sydorchuk\n\n// Use, modification and distribution is subject to the MIT License (MIT).\n\n#include <ctime>\n#include <iostream>\n#include <random>\n#include <vector>\n\n#include <boost/polygon/voronoi_builder.hpp>\n\n#include \"loba2d/delaunay_graph.hpp\"\n\nconst int RANDOM_SEED = 27;\nconst int NUM_POINTS = 1000000;\n\n\nint main() {\n  std::mt19937 gen(RANDOM_SEED);\n  boost::polygon::voronoi_builder<int> vb;\n  loba2d::delaunay_graph dg;\n  std::vector< std::pair<int, int> > input;\n\n  for (int i = 0; i < NUM_POINTS; ++i) {\n    int x = gen() & ((1 << 30) - 1);\n    int y = gen() & ((1 << 30) - 1);\n    input.push_back(std::make_pair(x, y));\n    vb.insert_point(x, y);\n  }\n\n  double t = clock();\n  vb.construct(&dg);\n  double elapsed = (clock() - t) / 1E6;\n\n  std::cout << \"Delaunay index constructed in: \" << elapsed << \"(secs)\" << std::endl;\n  std::cout << \"Num. vertices: \" << dg.vertices().size() << std::endl;\n  std::cout << \"Num. triangles: \" << dg.triangles().size() << std::endl;\n  std::cout << \"Num. half-edges: \" << dg.edges().size() << std::endl;\n\n  if (dg.num_triangles() <= 10) {\n    std::cout << \"Triangles coordinates:\" << std::endl;\n    for (loba2d::delaunay_graph::const_triangle_iterator it = dg.triangles().begin();\n         it != dg.triangles().end(); ++it) {\n      const loba2d::delaunay_graph::edge_type* e = it->incident_edge();\n      std::cout << \"[\";\n      for (int i = 0; i < 3; ++i) {\n        std::size_t idx = e->vertex0()->source_index();\n        std::cout << \" (\" << input[idx].first << \", \" << input[idx].second << \")\";\n        e = e->next();\n      }\n      std::cout << \" ]\" << std::endl;\n    }\n  }\n}\n", "meta": {"hexsha": "1d339e1c5852325e8cee59a6ef717b01c7e7fd6f", "size": 1666, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/delaunay_graph_example.cpp", "max_stars_repo_name": "asydorchuk/loba2d", "max_stars_repo_head_hexsha": "ec173529f81fc2465c87392797d7c583ea2fb25e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-07-27T18:19:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-28T18:45:07.000Z", "max_issues_repo_path": "example/delaunay_graph_example.cpp", "max_issues_repo_name": "asydorchuk/loba2d", "max_issues_repo_head_hexsha": "ec173529f81fc2465c87392797d7c583ea2fb25e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/delaunay_graph_example.cpp", "max_forks_repo_name": "asydorchuk/loba2d", "max_forks_repo_head_hexsha": "ec173529f81fc2465c87392797d7c583ea2fb25e", "max_forks_repo_licenses": ["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.2280701754, "max_line_length": 85, "alphanum_fraction": 0.5804321729, "num_tokens": 531, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390746, "lm_q2_score": 0.6187804267137442, "lm_q1q2_score": 0.47760164894909146}}
{"text": "#include \"ouster/lidar_scan.h\"\n\n#include <Eigen/Eigen>\n#include <cmath>\n#include <vector>\n\nnamespace ouster {\n\nconstexpr int LidarScan::N_FIELDS;\n\nXYZLut make_xyz_lut(size_t w, size_t h, double range_unit,\n                    double lidar_origin_to_beam_origin_mm,\n                    const mat4d& transform,\n                    const std::vector<double>& azimuth_angles_deg,\n                    const std::vector<double>& altitude_angles_deg) {\n    if (w <= 0 || h <= 0)\n        throw std::invalid_argument(\"lut dimensions must be greater than zero\");\n    if (azimuth_angles_deg.size() != h || altitude_angles_deg.size() != h)\n        throw std::invalid_argument(\"unexpected scan dimensions\");\n\n    Eigen::ArrayXd encoder(w * h);   // theta_e\n    Eigen::ArrayXd azimuth(w * h);   // theta_a\n    Eigen::ArrayXd altitude(w * h);  // phi\n\n    const double azimuth_radians = M_PI * 2.0 / w;\n\n    // populate angles for each pixel\n    for (size_t v = 0; v < w; v++) {\n        for (size_t u = 0; u < h; u++) {\n            size_t i = u * w + v;\n            encoder(i) = 2.0 * M_PI - (v * azimuth_radians);\n            azimuth(i) = -azimuth_angles_deg[u] * M_PI / 180.0;\n            altitude(i) = altitude_angles_deg[u] * M_PI / 180.0;\n        }\n    }\n\n    XYZLut lut;\n\n    // unit vectors for each pixel\n    lut.direction = LidarScan::Points{w * h, 3};\n    lut.direction.col(0) = (encoder + azimuth).cos() * altitude.cos();\n    lut.direction.col(1) = (encoder + azimuth).sin() * altitude.cos();\n    lut.direction.col(2) = altitude.sin();\n\n    // offsets due to beam origin\n    lut.offset = LidarScan::Points{w * h, 3};\n    lut.offset.col(0) = encoder.cos() - lut.direction.col(0);\n    lut.offset.col(1) = encoder.sin() - lut.direction.col(1);\n    lut.offset.col(2) = -lut.direction.col(2);\n    lut.offset *= lidar_origin_to_beam_origin_mm;\n\n    // apply the supplied transform\n    auto rot = transform.topLeftCorner(3, 3).transpose();\n    auto trans = transform.topRightCorner(3, 1).transpose();\n    lut.direction.matrix() *= rot;\n    lut.offset.matrix() *= rot;\n    lut.offset.matrix() += trans.replicate(w * h, 1);\n\n    // apply scaling factor\n    lut.direction *= range_unit;\n    lut.offset *= range_unit;\n\n    return lut;\n}\n\nLidarScan::Points cartesian(const LidarScan& scan, const XYZLut& lut) {\n    if (scan.w * scan.h != lut.direction.rows())\n        throw std::invalid_argument(\"unexpected scan dimensions\");\n\n    auto reshaped = Eigen::Map<const Eigen::Array<LidarScan::raw_t, -1, 1>>(\n        scan.field(LidarScan::RANGE).data(), scan.h * scan.w);\n    auto nooffset = lut.direction.colwise() * reshaped.cast<double>();\n    return (nooffset.array() == 0.0).select(nooffset, nooffset + lut.offset);\n}\n\nScanBatcher::ScanBatcher(size_t w, const sensor::packet_format& pf)\n    : w(w), h(pf.pixels_per_column), next_m_id(0), ls_write(w, h), pf(pf) {}\n\nbool ScanBatcher::operator()(const uint8_t* packet_buf, LidarScan& ls) {\n    using row_view_t =\n        Eigen::Map<Eigen::Array<LidarScan::raw_t, Eigen::Dynamic,\n                                Eigen::Dynamic, Eigen::RowMajor>>;\n\n    if (ls.w != w || ls.h != h)\n        throw std::invalid_argument(\"unexpected scan dimensions\");\n\n    bool swapped = false;\n\n    for (int icol = 0; icol < pf.columns_per_packet; icol++) {\n        const uint8_t* col_buf = pf.nth_col(icol, packet_buf);\n        const uint16_t m_id = pf.col_measurement_id(col_buf);\n        const uint16_t f_id = pf.col_frame_id(col_buf);\n        const std::chrono::nanoseconds ts(pf.col_timestamp(col_buf));\n        const uint32_t encoder = pf.col_encoder(col_buf);\n        const uint32_t status = pf.col_status(col_buf);\n        const bool valid = (status == 0xffffffff);\n\n        // drop invalid / out-of-bounds data in case of misconfiguration\n        if (!valid || m_id >= w || f_id + 1 == ls_write.frame_id) continue;\n\n        if (ls_write.frame_id != f_id) {\n            // if not initializing with first packet\n            if (ls_write.frame_id != -1) {\n                // zero out remaining missing columns\n                auto rows = h * LidarScan::N_FIELDS;\n                row_view_t{ls_write.data.data(), rows, w}\n                    .block(0, next_m_id, rows, w - next_m_id)\n                    .setZero();\n\n                // finish the scan and notify callback\n                std::swap(ls, ls_write);\n                swapped = true;\n            }\n\n            // start new frame\n            next_m_id = 0;\n            ls_write.frame_id = f_id;\n        }\n\n        // zero out missing columns if we jumped forward\n        if (m_id >= next_m_id) {\n            auto rows = h * LidarScan::N_FIELDS;\n            row_view_t{ls_write.data.data(), rows, w}\n                .block(0, next_m_id, rows, m_id - next_m_id)\n                .setZero();\n            next_m_id = m_id + 1;\n        }\n\n        ls_write.header(m_id) = {ts, encoder, status};\n        for (uint8_t ipx = 0; ipx < h; ipx++) {\n            const uint8_t* px_buf = pf.nth_px(ipx, col_buf);\n\n            ls_write.block(m_id).row(ipx)\n                << static_cast<LidarScan::raw_t>(pf.px_range(px_buf)),\n                static_cast<LidarScan::raw_t>(pf.px_signal(px_buf)),\n                static_cast<LidarScan::raw_t>(pf.px_ambient(px_buf)),\n                static_cast<LidarScan::raw_t>(pf.px_reflectivity(px_buf));\n        }\n    }\n    return swapped;\n}\n\n}  // namespace ouster\n", "meta": {"hexsha": "c83745f0f15ffee19fd5671f534d933ca9bf67e6", "size": 5365, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ouster_client/src/lidar_scan.cpp", "max_stars_repo_name": "tu-darmstadt-ros-pkg/ouster_example", "max_stars_repo_head_hexsha": "2b49e6a2f3dbd0462c557974a3f428915067fd2f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-02-12T13:02:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-12T13:02:45.000Z", "max_issues_repo_path": "ouster_client/src/lidar_scan.cpp", "max_issues_repo_name": "tu-darmstadt-ros-pkg/ouster_example", "max_issues_repo_head_hexsha": "2b49e6a2f3dbd0462c557974a3f428915067fd2f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ouster_client/src/lidar_scan.cpp", "max_forks_repo_name": "tu-darmstadt-ros-pkg/ouster_example", "max_forks_repo_head_hexsha": "2b49e6a2f3dbd0462c557974a3f428915067fd2f", "max_forks_repo_licenses": ["BSD-3-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.2569444444, "max_line_length": 80, "alphanum_fraction": 0.5912395154, "num_tokens": 1400, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.47755924999901217}}
{"text": "/*\n * Software License Agreement (BSD License)\n *\n *  Copyright (c) 2020, Clearpath Robotics\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions\n *  are met:\n *\n *   * Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *   * Redistributions in binary form must reproduce the above\n *     copyright notice, this list of conditions and the following\n *     disclaimer in the documentation and/or other materials provided\n *     with the distribution.\n *   * Neither the name of the copyright holder 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 (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#include <fuse_constraints/normal_delta_pose_2d.h>\n#include <fuse_core/util.h>\n\n#include <Eigen/Core>\n#include <glog/logging.h>\n\n\nnamespace fuse_constraints\n{\n\nNormalDeltaPose2D::NormalDeltaPose2D(const fuse_core::MatrixXd& A, const fuse_core::Vector3d& b) :\n  A_(A),\n  b_(b)\n{\n  CHECK_GT(A_.rows(), 0);\n  CHECK_EQ(A_.cols(), 3);\n  set_num_residuals(A_.rows());\n}\n\nbool NormalDeltaPose2D::Evaluate(\n  double const* const* parameters,\n  double* residuals,\n  double** jacobians) const\n{\n  const fuse_core::Matrix2d R1_transpose = fuse_core::rotationMatrix2D(parameters[1][0]).transpose();  // orientation1\n  const fuse_core::Vector2d position_delta =\n      R1_transpose * fuse_core::Vector2d(parameters[2][0] - parameters[0][0],   // position2.x - position1.x\n                                         parameters[2][1] - parameters[0][1]);  // position2.y - position1.y\n\n  const fuse_core::Vector3d full_residuals_vector(\n      position_delta[0] - b_[0], position_delta[1] - b_[1],\n      fuse_core::wrapAngle2D(parameters[3][0] - parameters[1][0] - b_[2]));  // orientation2 - orientation1\n\n  // Scale the residuals by the square root information matrix to account for the measurement uncertainty.\n  Eigen::Map<fuse_core::VectorXd> residuals_vector(residuals, num_residuals());\n  residuals_vector = A_ * full_residuals_vector;\n\n  if (jacobians != nullptr)\n  {\n    // Jacobian wrt position1\n    if (jacobians[0] != nullptr)\n    {\n      Eigen::Map<fuse_core::MatrixXd>(jacobians[0], num_residuals(), 2) = -A_.leftCols<2>() * R1_transpose;\n    }\n\n    // Jacobian wrt orientation1\n    if (jacobians[1] != nullptr)\n    {\n      Eigen::Map<fuse_core::VectorXd>(jacobians[1], num_residuals()) =\n          A_ * fuse_core::Vector3d(position_delta[1], -position_delta[0], -1);\n    }\n\n    // Jacobian wrt position2\n    if (jacobians[2] != nullptr)\n    {\n      Eigen::Map<fuse_core::MatrixXd>(jacobians[2], num_residuals(), 2) = A_.leftCols<2>() * R1_transpose;\n    }\n\n    // Jacobian wrt orientation2\n    if (jacobians[3] != nullptr)\n    {\n      Eigen::Map<fuse_core::VectorXd>(jacobians[3], num_residuals()) = A_.col(2);\n    }\n  }\n  return true;\n}\n\n}  // namespace fuse_constraints\n", "meta": {"hexsha": "1450b94434d8c920f93b08daf9f1c14a37410d5b", "size": 3837, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "fuse_constraints/src/normal_delta_pose_2d.cpp", "max_stars_repo_name": "mcx/fuse", "max_stars_repo_head_hexsha": "3825e489ceaba394fb07c87e0e52dce9485da19b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 383.0, "max_stars_repo_stars_event_min_datetime": "2018-07-02T07:20:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:51:06.000Z", "max_issues_repo_path": "fuse_constraints/src/normal_delta_pose_2d.cpp", "max_issues_repo_name": "mcx/fuse", "max_issues_repo_head_hexsha": "3825e489ceaba394fb07c87e0e52dce9485da19b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 117.0, "max_issues_repo_issues_event_min_datetime": "2018-07-16T10:32:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-02T20:15:16.000Z", "max_forks_repo_path": "fuse_constraints/src/normal_delta_pose_2d.cpp", "max_forks_repo_name": "mcx/fuse", "max_forks_repo_head_hexsha": "3825e489ceaba394fb07c87e0e52dce9485da19b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 74.0, "max_forks_repo_forks_event_min_datetime": "2018-10-01T10:10:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T04:48:22.000Z", "avg_line_length": 37.6176470588, "max_line_length": 118, "alphanum_fraction": 0.7028928851, "num_tokens": 982, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.47755924432575975}}
{"text": "#include <cassert>\n#include <cmath>\n#include <algorithm>\n#include <boost/functional/hash.hpp>\n\n#include \"fin.hh\"\n\nusing namespace std;\n\nFin::Fin( const Fin & other )\n  : Action( other ),\n    _lambda( other._lambda )\n{\n}\n\nFin::Fin( const RemyBuffers::Fin & dna )\n  : Action ( dna.domain() ), \n    _lambda( dna.lambda() )\n{\n}\n\nRemyBuffers::Fin Fin::DNA( void ) const\n{\n  RemyBuffers::Fin ret;\n\n  ret.set_lambda( _lambda );\n  ret.mutable_domain()->CopyFrom( _domain.DNA() );\n\n  return ret;\n}\n\nvector< Fin > Fin::next_generation( void ) const\n{\n  vector< Fin> ret;\n\n  auto lambda_alternatives = get_optimizer().lambda.alternatives( _lambda, true );\n  \n  printf(\"Alternatives: lambda %f to %f\\n\",\n         *(min_element(lambda_alternatives.begin(), lambda_alternatives.end())),\n         *(max_element(lambda_alternatives.begin(), lambda_alternatives.end()))\n  );\n\n  for ( const auto & alt_lambda : lambda_alternatives ) {\n        Fin new_fin{ *this };\n        new_fin._generation++;\n\n        new_fin._lambda = alt_lambda;\n        new_fin.round();\n\n        ret.push_back( new_fin );\n  }\n\n  return ret;\n}\n\nstring Fin::str( const unsigned int total ) const\n{\n  char tmp[ 256 ];\n  snprintf( tmp, 256, \"{%s} gen=%u usage=%.4f => (lambda=%f)\",\n            _domain.str().c_str(), _generation, double( _domain.count() ) / double( total ), _lambda );\n  return tmp;\n}\n\nvoid Fin::round( void )\n{\n  _lambda = (1.0/10000.0) * int( 10000 * _lambda );\n}\n\nsize_t hash_value( const Fin & fin )\n{\n  size_t seed = 0;\n  boost::hash_combine( seed, fin._lambda );\n  boost::hash_combine( seed, fin._domain );\n\n  return seed;\n}", "meta": {"hexsha": "77ddb456b8ba1478e401e2a494646609dd1785b4", "size": 1598, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/fin.cc", "max_stars_repo_name": "CN-TU/remy", "max_stars_repo_head_hexsha": "0c0887322b0cbf6e3497e3aeb95c979907f03623", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2020-03-19T04:16:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T15:41:39.000Z", "max_issues_repo_path": "src/fin.cc", "max_issues_repo_name": "CN-TU/remy", "max_issues_repo_head_hexsha": "0c0887322b0cbf6e3497e3aeb95c979907f03623", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-05-20T12:05:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-14T13:39:23.000Z", "max_forks_repo_path": "src/fin.cc", "max_forks_repo_name": "CN-TU/remy", "max_forks_repo_head_hexsha": "0c0887322b0cbf6e3497e3aeb95c979907f03623", "max_forks_repo_licenses": ["Apache-2.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.0263157895, "max_line_length": 103, "alphanum_fraction": 0.6376720901, "num_tokens": 434, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.47755924432575975}}
{"text": "#include \"geodb/trajectory.hpp\"\n\n#include <boost/geometry/geometries/box.hpp>\n#include <boost/geometry/geometries/point.hpp>\n#include <boost/geometry/geometries/segment.hpp>\n#include <boost/geometry/algorithms/intersects.hpp>\n\nnamespace geodb {\n\nbool trajectory_unit::intersects(const bounding_box& b) const {\n    namespace bg = boost::geometry;\n\n    // Using double for all coordinates.\n    using point_t = bg::model::point<double, 3, bg::cs::cartesian>;\n    using line_t = bg::model::segment<point_t>;\n    using box_t = bg::model::box<point_t>;\n\n    // Convert point to boost geometry type.\n    auto convert_point = [](const vector3& p) {\n        return point_t(p.x(), p.y(), p.t());\n    };\n\n    box_t box(convert_point(b.min()), convert_point(b.max()));\n    line_t line(convert_point(start), convert_point(end));\n    return bg::intersects(box, line);\n}\n\n} // namespace geodb\n", "meta": {"hexsha": "9b1e0ade36cc56d78417129f955a48339560bbab", "size": 878, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/geodb/trajectory.cpp", "max_stars_repo_name": "mbeckem/msc", "max_stars_repo_head_hexsha": "93e71ba163a7ffef4eec3e83934fa793f3f50ff6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/geodb/trajectory.cpp", "max_issues_repo_name": "mbeckem/msc", "max_issues_repo_head_hexsha": "93e71ba163a7ffef4eec3e83934fa793f3f50ff6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/geodb/trajectory.cpp", "max_forks_repo_name": "mbeckem/msc", "max_forks_repo_head_hexsha": "93e71ba163a7ffef4eec3e83934fa793f3f50ff6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.275862069, "max_line_length": 67, "alphanum_fraction": 0.6924829157, "num_tokens": 220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4775447354253605}}
{"text": "#include <algorithm>\n#include <boost/optional.hpp>\n#include <climits>\n#include <cmath>\n#include <cstdio>\n#include <cstring>\n#include <functional>\n#include <iostream>\n#include <limits>\n#include <list>\n#include <map>\n#include <numeric>\n#include <queue>\n#include <set>\n#include <sstream>\n#include <string>\n#include <tuple>\n#include <type_traits>\n#include <unordered_map>\n#include <unordered_set>\n#include <utility>\n#include <vector>\n\n#define REP(i, n) for(int i = 0, i##_MACRO = (n); i < i##_MACRO; i++)\n#define RANGE(i, a, b) for(int i = (a), i##_MACRO = (b); i < i##_MACRO; i++)\n#define EACH(e, a) for(auto&& e : a)\n#define ALL(a) std::begin(a), std::end(a)\n#define RALL(a) std::rbegin(a), std::rend(a)\n#define FILL(a, n) memset((a), n, sizeof(a))\n#define FILLZ(a) FILL(a, 0)\n#define INT(x) (static_cast<int>(x))\n\nusing namespace std;\n\nusing ll = long long;\nusing VI = vector<int>;\nusing VI2D = vector<vector<int>>;\n\nconstexpr int INF = 2e9;\nconstexpr double EPS = 1e-10;\nconstexpr double PI = acos(-1.0);\n\nconstexpr int dx[] = {-1, 0, 1, 0};\nconstexpr int dy[] = {0, -1, 0, 1};\n\ntemplate <typename T>\nconstexpr int sign(T x) {\n\treturn x < 0 ? -1 : x > 0 ? 1 : 0;\n}\n\ntemplate <>\nconstexpr int sign(double x) {\n\treturn x < -EPS ? -1 : x > EPS ? 1 : 0;\n}\n\ntemplate <typename T, typename U>\nconstexpr void chmax(T& m, U x) {\n\tm = max(m, x);\n}\n\ntemplate <typename T, typename U>\nconstexpr void chmin(T& m, U x) {\n\tm = min(m, x);\n}\n\ntemplate <typename T>\nconstexpr T square(T x) {\n\treturn x * x;\n}\n\nusing Weight = int;\n\n// \u8fba\nstruct Edge {\n\tsize_t from;\n\tsize_t to;\n\tWeight cost;\n\tEdge(size_t t, Weight c) : to(t), cost(c) {}\n\tEdge(size_t f, size_t t, Weight c) : from(f), to(t), cost(c) {}\n\tbool operator<(const Edge& rhs) const { return this->cost > rhs.cost; }\n};\n\n// \u30b0\u30e9\u30d5 G=(V,E)\nstruct Graph {\n\tsize_t node;\n\tstd::vector<std::vector<Edge>> edges;\n\n\tGraph(size_t n) : node(n), edges(n) {}\n};\n\n// \u6700\u77ed\u7d4c\u8def\u63a2\u7d22(\u975e\u8ca0\u9589\u8def)\nstd::vector<int> dijkstra(const Graph& graph, const size_t s) {\n\tsize_t n = graph.node;\n\tstd::vector<int> used(n, -1);\n\tstd::vector<Weight> distances(n, INF);\n\n\tdistances[s] = 0;\n\tstd::priority_queue<Edge> pq;\n\tpq.push(Edge(0, s, 0));\n\twhile(!pq.empty()) {\n\t\tEdge edge = pq.top();\n\t\tpq.pop();\n\t\tif(used[edge.to] != -1) {\n\t\t\tcontinue;\n\t\t}\n\t\tused[edge.to] = edge.from;\n\t\tfor(auto&& e : graph.edges[edge.to]) {\n\t\t\tWeight alt = edge.cost + e.cost;\n\t\t\tif(alt < distances[e.to]) {\n\t\t\t\tdistances[e.to] = alt;\n\t\t\t\tpq.push(Edge(edge.to, e.to, alt));\n\t\t\t}\n\t\t}\n\t}\n\treturn used;\n}\n\nint main() {\n\tint n, m;\n\tcin >> n >> m;\n\tVI a(m);\n\tVI b(m);\n\tGraph g(n);\n\tREP(i, m) {\n\t\tcin >> a[i] >> b[i];\n\t\tg.edges[a[i] - 1].push_back(Edge(a[i] - 1, b[i] - 1, 1));\n\t\tg.edges[b[i] - 1].push_back(Edge(b[i] - 1, a[i] - 1, 1));\n\t}\n\tvector<int> result = dijkstra(g, 0);\n\tbool is_enable = true;\n\tREP(i, n) {\n\t\tif(result[i] == -1) {\n\t\t\tis_enable = false;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif(is_enable) {\n\t\tcout << \"Yes\" << endl;\n\t\tRANGE(i, 1, n) { cout << result[i] + 1 << endl; }\n\t} else {\n\t\tcout << \"No\" << endl;\n\t}\n\treturn 0;\n}\n", "meta": {"hexsha": "36dc0ce053a40f41e9e5a8be17eb6e3da5ced17c", "size": 2989, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AtCoder/ABC168/D.cpp", "max_stars_repo_name": "arlechann/atcoder", "max_stars_repo_head_hexsha": "1af08efa6d3a0e8c75e4eaf13e1eda994820b9e2", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AtCoder/ABC168/D.cpp", "max_issues_repo_name": "arlechann/atcoder", "max_issues_repo_head_hexsha": "1af08efa6d3a0e8c75e4eaf13e1eda994820b9e2", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AtCoder/ABC168/D.cpp", "max_forks_repo_name": "arlechann/atcoder", "max_forks_repo_head_hexsha": "1af08efa6d3a0e8c75e4eaf13e1eda994820b9e2", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.6137931034, "max_line_length": 76, "alphanum_fraction": 0.5991970559, "num_tokens": 1021, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4775447296089965}}
{"text": "#ifndef STAN_MATH_PRIM_SCAL_PROB_SCALED_INV_CHI_SQUARE_RNG_HPP\n#define STAN_MATH_PRIM_SCAL_PROB_SCALED_INV_CHI_SQUARE_RNG_HPP\n\n#include <boost/random/chi_squared_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <stan/math/prim/scal/err/check_consistent_sizes.hpp>\n#include <stan/math/prim/scal/err/check_nonnegative.hpp>\n#include <stan/math/prim/scal/err/check_not_nan.hpp>\n#include <stan/math/prim/scal/err/check_positive_finite.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/gamma_q.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/square.hpp>\n#include <stan/math/prim/scal/meta/VectorBuilder.hpp>\n#include <stan/math/prim/scal/meta/length.hpp>\n#include <stan/math/prim/scal/meta/include_summand.hpp>\n#include <stan/math/prim/scal/fun/grad_reg_inc_gamma.hpp>\n\nnamespace stan {\n  namespace math {\n\n    template <class RNG>\n    inline double\n    scaled_inv_chi_square_rng(double nu,\n                              double s,\n                              RNG& rng) {\n      using boost::variate_generator;\n      using boost::random::chi_squared_distribution;\n\n      static const char* function(\"scaled_inv_chi_square_rng\");\n\n      check_positive_finite(function, \"Degrees of freedom parameter\", nu);\n      check_positive_finite(function, \"Scale parameter\", s);\n\n      variate_generator<RNG&, chi_squared_distribution<> >\n        chi_square_rng(rng, chi_squared_distribution<>(nu));\n      return nu * s / chi_square_rng();\n    }\n\n  }\n}\n#endif\n", "meta": {"hexsha": "6cdfc8d67264fcb033a798f8e861bfb1344a6cab", "size": 1635, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/scal/prob/scaled_inv_chi_square_rng.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/prim/scal/prob/scaled_inv_chi_square_rng.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/prim/scal/prob/scaled_inv_chi_square_rng.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": 36.3333333333, "max_line_length": 74, "alphanum_fraction": 0.7400611621, "num_tokens": 404, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4775447296089964}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#include \"Domain/FunctionsOfTime/QuaternionHelpers.hpp\"\n\n#include <boost/math/quaternion.hpp>\n\n#include \"DataStructures/DataVector.hpp\"\n#include \"Utilities/ErrorHandling/Assert.hpp\"\n#include \"Utilities/Gsl.hpp\"\n\nDataVector quaternion_to_datavector(\n    const boost::math::quaternion<double>& input) noexcept {\n  return DataVector{input.R_component_1(), input.R_component_2(),\n                    input.R_component_3(), input.R_component_4()};\n}\n\nboost::math::quaternion<double> datavector_to_quaternion(\n    const DataVector& input) noexcept {\n  ASSERT(input.size() == 3 or input.size() == 4,\n         \"To form a quaternion, a DataVector can either have 3 or 4 components \"\n         \"only. This DataVector has \"\n             << input.size() << \" components.\");\n  if (input.size() == 3) {\n    return boost::math::quaternion<double>(0.0, input[0], input[1], input[2]);\n  } else {\n    return boost::math::quaternion<double>(input[0], input[1], input[2],\n                                           input[3]);\n  }\n}\n\n// Normalize a `boost::math::quaternion`\nvoid normalize_quaternion(\n    const gsl::not_null<boost::math::quaternion<double>*> input) noexcept {\n  *input /= abs(*input);\n}\n", "meta": {"hexsha": "3ce37bd76c14eb407c0302adc3785e754c9ab08c", "size": 1254, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Domain/FunctionsOfTime/QuaternionHelpers.cpp", "max_stars_repo_name": "macedo22/spectre", "max_stars_repo_head_hexsha": "97b2b7ae356cf86830258cb5f689f1191fdb6ddd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Domain/FunctionsOfTime/QuaternionHelpers.cpp", "max_issues_repo_name": "macedo22/spectre", "max_issues_repo_head_hexsha": "97b2b7ae356cf86830258cb5f689f1191fdb6ddd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Domain/FunctionsOfTime/QuaternionHelpers.cpp", "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": 33.8918918919, "max_line_length": 80, "alphanum_fraction": 0.6618819777, "num_tokens": 305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4775447296089964}}
{"text": "#ifndef STAN_MATH_PRIM_MAT_FUN_QUAD_FORM_DIAG_HPP\n#define STAN_MATH_PRIM_MAT_FUN_QUAD_FORM_DIAG_HPP\n\n#include <stan/math/prim/mat/fun/Eigen.hpp>\n#include <boost/math/tools/promotion.hpp>\n#include <stan/math/prim/mat/err/check_square.hpp>\n#include <stan/math/prim/mat/err/check_vector.hpp>\n#include <stan/math/prim/scal/err/check_size_match.hpp>\n\nnamespace stan {\nnamespace math {\n\ntemplate <typename T1, typename T2, int R, int C>\ninline Eigen::Matrix<typename boost::math::tools::promote_args<T1, T2>::type,\n                     Eigen::Dynamic, Eigen::Dynamic>\nquad_form_diag(const Eigen::Matrix<T1, Eigen::Dynamic, Eigen::Dynamic>& mat,\n               const Eigen::Matrix<T2, R, C>& vec) {\n  using boost::math::tools::promote_args;\n  check_vector(\"quad_form_diag\", \"vec\", vec);\n  check_square(\"quad_form_diag\", \"mat\", mat);\n  int size = vec.size();\n  check_size_match(\"quad_form_diag\", \"rows of mat\", mat.rows(), \"size of vec\",\n                   size);\n  Eigen::Matrix<typename promote_args<T1, T2>::type, Eigen::Dynamic,\n                Eigen::Dynamic>\n      result(size, size);\n  for (int i = 0; i < size; i++) {\n    result(i, i) = vec(i) * vec(i) * mat(i, i);\n    for (int j = i + 1; j < size; ++j) {\n      typename promote_args<T1, T2>::type temp = vec(i) * vec(j);\n      result(j, i) = temp * mat(j, i);\n      result(i, j) = temp * mat(i, j);\n    }\n  }\n  return result;\n}\n\n}  // namespace math\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "4fa26f8215f42ae61336d1150499627f7bbe8515", "size": 1430, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/prim/mat/fun/quad_form_diag.hpp", "max_stars_repo_name": "jrmie/math", "max_stars_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "stan/math/prim/mat/fun/quad_form_diag.hpp", "max_issues_repo_name": "jrmie/math", "max_issues_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stan/math/prim/mat/fun/quad_form_diag.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": 34.8780487805, "max_line_length": 78, "alphanum_fraction": 0.6461538462, "num_tokens": 405, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.6477982315512488, "lm_q1q2_score": 0.477529754124429}}
{"text": "#include <iostream>\n#include <vector>\n#include <utility>\n#include <boost/random.hpp>\n\nclass ising\n{\nprivate:\n  std::vector<bool> configuration;\n  std::vector<std::vector<double>> connects;\n\n  double cost(const std::vector<bool>& state) const;\n  void incliment(std::vector<bool>& state) const;\npublic:\n  // constructors\n  ising(const unsigned int N, boost::mt19937& eng);\n  ising(const unsigned int N, const std::vector<std::vector<double>> Q);\n  ising(const std::vector<bool> spins, const std::vector<std::vector<double>> Q);\n  ising(const std::vector<bool> spins, boost::mt19937& eng);\n  \n  // destructor\n  ~ising();\n\n  // extract inner state/configuration\n  std::vector<bool> state() const;\n  \n  // objective/cost function\n  double cost() const;\n  double delta(const unsigned int site) const;\n\n  // flip procedure\n  void flip(const unsigned int site);\n\n  // all search\n  std::pair<double, std::vector<bool>> all_search() const;\n  \n  // output for debug\n  friend std::ostream& operator<<(std::ostream& os, const ising& obj);\n  void show_interaction(std::ostream& os) const;\n};\n", "meta": {"hexsha": "0e8e9726b796fb1fecd74cd2d58f2d8b53a286ad", "size": 1078, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ising.hpp", "max_stars_repo_name": "suzumoto/sa", "max_stars_repo_head_hexsha": "f007ef19272efdebc1dacba87d5f0af822abcecb", "max_stars_repo_licenses": ["MIT"], "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/ising.hpp", "max_issues_repo_name": "suzumoto/sa", "max_issues_repo_head_hexsha": "f007ef19272efdebc1dacba87d5f0af822abcecb", "max_issues_repo_licenses": ["MIT"], "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/ising.hpp", "max_forks_repo_name": "suzumoto/sa", "max_forks_repo_head_hexsha": "f007ef19272efdebc1dacba87d5f0af822abcecb", "max_forks_repo_licenses": ["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.2926829268, "max_line_length": 81, "alphanum_fraction": 0.6966604824, "num_tokens": 276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.737158174177441, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.47752975158097766}}
{"text": "#include <vector>\n#include <array>\n#include <string>\n#include <iostream>\n#include <fstream>\n#include <iomanip>\n\n#include <BlueLink/Host/AFU.hpp>\n#include <BlueLink/Host/WED.hpp>\n\n#include <boost/range/algorithm.hpp>\n\n#include <boost/random/mersenne_twister.hpp>\n\n#include <BlueLink/Host/aligned_allocator.hpp>\n\nusing namespace std;\n\nstruct MemLoadWED\n{\n\tconst uint64_t*\tpSrc=nullptr;\n\tuint64_t* \t\tpDst=nullptr;\n\tuint64_t\t\tsize=0;\n\n\tarray<uint64_t,13>\tpad;\n\n\tMemLoadWED(){ boost::fill(pad,0); }\n};\n\nint main(int argc,char **argv)\n{\n\t//// Source constants\n#ifdef SIM\n\tconst unsigned logNHL \t = 10;\t\t\t\t// 1024 512b half-lines\n\tconst unsigned timeout=1800;\n#else\n\tconst unsigned logNHL\t= 16;\t\t\t\t// 64k 512b half-lines\n\tconst unsigned timeout\t= 4;\n#endif\n\n\tconst unsigned logNBanks =  4;\t\t\t\t// 16 banks\n\n\n\n\t//// Derived constants\n\t\tconst unsigned Nl1024=1 << (logNHL+1);\t// # 1024b (128B) cache lines\n\t\tconst unsigned Nhl512=1 << (logNHL);\t// # 512b (64B) half-lines\n\t\tconst unsigned Nui64=1 << (logNHL+3);\t// # 64b (8B) words\n\t\tconst unsigned NB= 1 << (logNHL+6);\t\t// # 8b (1B) bytes\n\n\t\tconst unsigned logNui64 = logNHL+3;\n\t\tconst unsigned logNL = logNHL+1;\n\n\t\tconst unsigned NBanks = 1<<logNBanks;\n\n\t\tconst unsigned NWordsPerBank = (1 << (logNHL+3-logNBanks));\n\n\tBOOST_STATIC_ASSERT(logNL >= 6);\n\n\tStackWED<MemLoadWED,128,128> wed;\n\n\tvector<uint64_t,aligned_allocator<uint64_t,128>> src(Nui64,0),dst(Nui64,0);\n\n\tcout << \"Running with \" << NB << \" byte transfer (\" << Nl1024 << \" cache lines, \" << Nhl512 << \" half-lines, \" << Nui64 << \" 64b words)\" << endl;\n\n\t// set up WED\n\twed->pSrc = src.data();\n\twed->pDst = dst.data();\n\twed->size = NB;\n\n\t// fill source with random numbers\n\tboost::mt19937_64 rng;\n\tboost::generate(src, rng);\n\n\tofstream os(\"output.expected.hex\");\n\n\tfor(uint64_t i : src)\n\t\tos << setw(16) << hex << i << endl;\n\tos.close();\n\n\n\t// start accelerator\n\tAFU afu(\"/dev/cxl0.0d\");\n\tafu.start(wed);\n\tsleep(1);\n\n\n\t////// Do host-AFU copy\n\n\tcout << \"Waiting for host->AFU copy to finish\" << endl;\n\n\tuint64_t tsH2AStart = afu.mmio_read64(0x10);\n\tuint64_t tsH2ADone  = 0;\n\n\tunsigned i;\n\n\tfor(i=0;i<timeout && (tsH2ADone = afu.mmio_read64(0x18)) == 0; ++i)\n\t\tsleep(1);\n\n\tif (i==timeout)\n\t\tcout << \"TIMEOUT!\" << endl;\n\n\tcout << \"  Started at \" << tsH2AStart << \" and finished at \" << tsH2ADone << \" (duration \" << tsH2ADone-tsH2AStart << \")\" << endl;\n\n\n\n\t////// Check BRAM readback\n\n\tstd::vector<std::pair<uint8_t,uint32_t>> addrs{\n\t\tmake_pair(0,0),\n\t\tmake_pair(0,NWordsPerBank-1),\t\t\t\t\t\t// last element in bank 1\n\t\tmake_pair(1,NWordsPerBank-1),\n\t\tmake_pair(1,0),\n\t\tmake_pair(1,NWordsPerBank-1),\n\t\tmake_pair(NBanks-2,NWordsPerBank-1),\n\t\tmake_pair(NBanks-2,NWordsPerBank-2),\n\t\tmake_pair(NBanks-2,NWordsPerBank-3),\n\t\tmake_pair(NBanks-1,NWordsPerBank-1),\t\t\t\t// last element overall\n\t\tmake_pair(0,1),\n\t\tmake_pair(NBanks-1,1),\n\t\tmake_pair(NBanks-1,0)\t\t\t\t\t\t\t\t// last bank, elements 1 and 0\n\t};\n\n\tcout << \"Checking BRAM readback: \" << endl;\n\tfor(const auto p : addrs)\n\t{\n\n\t\tafu.mmio_write64(0x00,(p.first << 16) | p.second);\n\t\tcout << \" Bank \" << hex << (unsigned)p.first << \" offset \" << hex << p.second << ' ';\n#ifdef SIM\n\t\tsleep(1);\n#endif\n\n\t\tuint64_t expect = src[(p.first<<(logNui64-logNBanks)) | p.second];\n\t\tuint64_t actual = afu.mmio_read64(0x00);\n\n\t\tif (actual == expect)\n\t\t\tcout << \"OK (\" << hex << setw(16) << expect << \")\";\n\t\telse\n\t\t\tcout << \"Mismatch - expecting \" << hex << setw(16) << expect << \" received \" << hex << actual;\n\t\tcout << endl;\n\t}\n\n\n\n\t////// Do AFU->host copy\n\n\tcout << \"Starting AFU->host copy\" << endl;\n\n\tafu.mmio_write64(0x08,0);\n\n\tuint64_t tsA2HStart=afu.mmio_read64(0x20);\n\tuint64_t tsA2HDone =afu.mmio_read64(0x28);\n\n\tfor(unsigned i=0;i<timeout && (tsA2HDone = afu.mmio_read64(0x28)) == 0; ++i)\n\t{\n#ifdef SIM\n\t\tsleep(1);\n#endif\n\t}\n\n\tif (i==timeout)\n\t\tcout << \"TIMEOUT!\" << endl;\n\n\tcout << \"AFU->host transfer started at \" << tsA2HStart << \" and finished at \" << tsA2HDone << \" (duration \" << tsA2HDone-tsA2HStart << \")\" << endl;\n\n\n\n\t////// Check output\n\n\tcout << \"Output: \" << endl;\n\n\tos.open(\"output.actual.hex\");\n\n\tfor(uint64_t o : dst)\n\t\tos << setw(16) << hex << o << endl;\n\tos.close();\n\n\tfor(unsigned i=0;i<Nui64;++i)\n\t\tif (src[i] != dst[i])\n\t\t\tcout << \"Mismatch at byte offset \" << std::hex << setw(8) << 8*i << \": expected \" << setw(16) << std::hex << src[i] << \" and received \" << setw(16) << std::hex << dst[i] << endl;\n\n\tcout << \"Output check done\" << endl;\n\n\tafu.mmio_write64(0x10,0);\n\n\treturn 0;\n}\n", "meta": {"hexsha": "3ab63a43d53d075a55993fff9be3586dd83c16e3", "size": 4438, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Examples/MemLoad/MemLoadHost.cpp", "max_stars_repo_name": "vinayby/BlueLink", "max_stars_repo_head_hexsha": "69944e51df8358877b9a86d3749f220fa459c0da", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2015-09-29T10:16:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-04T22:04:50.000Z", "max_issues_repo_path": "Examples/MemLoad/MemLoadHost.cpp", "max_issues_repo_name": "vinayby/BlueLink", "max_issues_repo_head_hexsha": "69944e51df8358877b9a86d3749f220fa459c0da", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-09-14T22:35:10.000Z", "max_issues_repo_issues_event_max_datetime": "2015-09-14T22:35:10.000Z", "max_forks_repo_path": "Examples/MemLoad/MemLoadHost.cpp", "max_forks_repo_name": "vinayby/BlueLink", "max_forks_repo_head_hexsha": "69944e51df8358877b9a86d3749f220fa459c0da", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2015-08-25T18:09:17.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-01T14:36:05.000Z", "avg_line_length": 23.4814814815, "max_line_length": 181, "alphanum_fraction": 0.6309148265, "num_tokens": 1525, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.737158174177441, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.47752975158097766}}
{"text": "/*******************************************************************************\n *         Copyright 2003-2014 LASMEA UMR 6602 CNRS/U.B.P\n *         Copyright 2011-2014 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n *\n *          Distributed under the Boost Software License, Version 1.0.\n *                 See accompanying file LICENSE.txt or copy at\n *                     http://www.boost.org/LICENSE_1_0.txt\n ******************************************************************************/\n#ifndef NT2_CORE_FUNCTIONS_EXPR_GLOBALNORM_HPP_INCLUDED\n#define NT2_CORE_FUNCTIONS_EXPR_GLOBALNORM_HPP_INCLUDED\n\n#include <nt2/include/functions/globalnorm.hpp>\n#include <nt2/core/container/dsl.hpp>\n#include <nt2/sdk/meta/as_real.hpp>\n#include <nt2/include/functions/abs.hpp>\n#include <nt2/include/functions/globalmin.hpp>\n#include <nt2/include/functions/globalmax.hpp>\n#include <nt2/include/functions/globalasum1.hpp>\n#include <nt2/include/functions/globalnorm2.hpp>\n#include <nt2/include/functions/globalnormp.hpp>\n#include <nt2/include/constants/one.hpp>\n#include <nt2/include/constants/two.hpp>\n#include <nt2/include/constants/inf.hpp>\n#include <nt2/include/constants/minf.hpp>\n#include <nt2/tags.hpp>\n#include <boost/dispatch/functor/meta/make_functor.hpp>\n#include <boost/dispatch/attributes.hpp>\n#include <boost/assert.hpp>\n\nnamespace nt2 { namespace ext\n{\n  // Default globalnorm is globalnorm2\n  BOOST_DISPATCH_IMPLEMENT  ( globalnorm_, tag::cpu_\n                            , (A0)\n                            , ((ast_<A0, nt2::container::domain>))\n                            )\n  {\n    BOOST_DISPATCH_RETURNS( 1\n                          , (A0 const &a0)\n                          , nt2::globalnorm2(a0)\n                          );\n  };\n\n  // Selects globalnorm from dynamic norm value\n  BOOST_DISPATCH_IMPLEMENT  ( globalnorm_, tag::cpu_\n                            , (A0)(A1)\n                            , ((ast_<A0, nt2::container::domain>))\n                              (scalar_<arithmetic_<A1> > )\n                           )\n  {\n    typedef typename A0::value_type                   type_t;\n    typedef typename meta::as_real<type_t>::type result_type;\n\n    BOOST_FORCEINLINE result_type operator()(A0 const &a0, A1 a1) const\n    {\n      BOOST_ASSERT_MSG( (a1 > 0) || (a1 == Minf<A1>())\n                      , \"p must be strictly positive or infinite\"\n                      );\n\n      if(a1 == Two<A1>())  return nt2::globalnorm2(a0);\n      if(a1 == One<A1>())  return nt2::globalasum1(a0);\n      if(a1 == Inf<A1>())  return nt2::globalmax(nt2::abs(a0));\n      if(a1 == Minf<A1>()) return nt2::globalmin(nt2::abs(a0));\n\n      return nt2::globalnormp(a0, a1);\n    }\n  };\n\n  // Selects globalnorm from static norm value\n  BOOST_DISPATCH_IMPLEMENT  ( globalnorm_, tag::cpu_\n                            , (A0)(A1)\n                            , ((ast_<A0, nt2::container::domain>))\n                              (mpl_integral_< scalar_< fundamental_<A1> > >)\n                            )\n  {\n    typedef typename A0::value_type                   type_t;\n    typedef typename meta::as_real<type_t>::type result_type;\n\n    BOOST_FORCEINLINE result_type operator()(A0 const &a0, A1 const& a1) const\n    {\n      BOOST_ASSERT_MSG( (A1::value > 0), \"p must be strictly positive\" );\n      return eval(a0, a1);\n    }\n\n    template<int Value>\n    BOOST_FORCEINLINE result_type eval( A0 const &a0\n                                      , boost::mpl::int_<Value> const&\n                                      ) const\n    {\n      return nt2::globalnormp(a0, Value);\n    }\n\n    BOOST_FORCEINLINE result_type eval( A0 const &a0\n                                      , boost::mpl::int_<1> const&\n                                      ) const\n    {\n      return nt2::globalasum1(a0);\n    }\n\n    BOOST_FORCEINLINE result_type eval( A0 const &a0\n                                      , boost::mpl::int_<2> const&\n                                      ) const\n    {\n      return nt2::globalnorm2(a0);\n    }\n  };\n\n  // Selects globalnorm from static norm value tag\n  BOOST_DISPATCH_IMPLEMENT  ( globalnorm_, tag::cpu_\n                            , (A0)(A1)\n                            , ((ast_<A0, nt2::container::domain>))\n                              (target_<unspecified_<A1> >)\n                            )\n  {\n    typedef typename A0::value_type                   type_t;\n    typedef typename meta::as_real<type_t>::type result_type;\n\n    BOOST_FORCEINLINE result_type operator()(A0 const &a0, A1 const&) const\n    {\n      return eval(a0, typename A1::type());\n    }\n\n    BOOST_FORCEINLINE result_type eval(A0 const &a0, tag::Inf const&) const\n    {\n      return nt2::globalmax(nt2::abs(a0));\n    }\n\n    BOOST_FORCEINLINE result_type eval(A0 const &a0, tag::Minf const&) const\n    {\n      return nt2::globalmin(nt2::abs(a0));\n    }\n\n    BOOST_FORCEINLINE result_type eval(A0 const &a0, tag::One const&) const\n    {\n      return nt2::globalasum1(a0);\n    }\n\n    BOOST_FORCEINLINE result_type eval(A0 const &a0, tag::Two const&) const\n    {\n      return nt2::globalnorm2(a0);\n    }\n\n    BOOST_FORCEINLINE result_type eval(A0 const &a0, tag::inf_ const&) const\n    {\n      return nt2::globalmax(nt2::abs(a0));\n    }\n\n    BOOST_FORCEINLINE result_type eval(A0 const &a0, tag::minf_ const&) const\n    {\n      return nt2::globalmin(nt2::abs(a0));\n    }\n\n    BOOST_FORCEINLINE result_type eval(A0 const &a0, tag::one_ const&) const\n    {\n      return nt2::globalasum1(a0);\n    }\n\n    BOOST_FORCEINLINE result_type eval(A0 const &a0, tag::two_ const&) const\n    {\n      return nt2::globalnorm2(a0);\n    }\n\n    BOOST_FORCEINLINE result_type eval(A0 const &a0, tag::fro_ const&) const\n    {\n      return nt2::globalnorm2(a0);\n    }\n\n    template<typename Tag>\n    BOOST_FORCEINLINE result_type eval(A0 const &a0, Tag const&) const\n    {\n      // outside of Inf,  Minf,  One and Two we get back to the dynamic normp\n      typename boost::dispatch::make_functor<Tag,A0>::type callee;\n      type_t value = callee( nt2::meta::as_<type_t>() );\n\n      BOOST_ASSERT_MSG( value > 0, \"Norm value must be strictly positive\" );\n      return  globalnormp(a0, value);\n    }\n  };\n} }\n\n#endif\n\n\n", "meta": {"hexsha": "44fd442ce906689a5aa506d24b00b44729218e32", "size": 6158, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/reduction/include/nt2/core/functions/expr/globalnorm.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/reduction/include/nt2/core/functions/expr/globalnorm.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/reduction/include/nt2/core/functions/expr/globalnorm.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": 33.4673913043, "max_line_length": 80, "alphanum_fraction": 0.5612211757, "num_tokens": 1532, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286833, "lm_q2_score": 0.6477982247516796, "lm_q1q2_score": 0.47752974911207097}}
{"text": "#ifndef _DOUGLAS_PEUCKER_H_\n#define _DOUGLAS_PEUCKER_H_\n\n#include <Eigen/Eigen>\n#include <vector>\n\n/**\n * This class is used to simpified a curve containing numerous points,applying the\n * Ramer-Douglas-Peucker Algorithm.\n *\n * Usage : Create a instance of this class, then call the simplifiy() function\n * Input : Points of a curve, and epsilon\n * Output: Points of the simplified curve\n */\nclass RDPCurveSimplifier\n{\npublic:\n  RDPCurveSimplifier()\n  {\n  }\n\n  void simplify(std::vector<Eigen::Vector3d> &curve, float epsilon);\n\nprivate:\n  void getMostDistantPoint(std::vector<Eigen::Vector3d> segment, int &point_id, float &distance);\n\n  void breakSegment(std::vector<Eigen::Vector3d> segment, int point_id,\n                    std::vector<Eigen::Vector3d> &part1, std::vector<Eigen::Vector3d> &part2);\n\n  bool allSegmentSimplified(std::vector<std::vector<Eigen::Vector3d>> segments);\n\n  void getDistanceToLine(Eigen::Vector3d front, Eigen::Vector3d back, Eigen::Vector3d point,\n                         float &distance);\n};\n\nvoid RDPCurveSimplifier::simplify(std::vector<Eigen::Vector3d> &curve, float epsilon)\n{\n  // create a vector containing the simplified segments\n  std::vector<std::vector<Eigen::Vector3d>> segments;\n\n  // At the begining, there is only one segment\n  segments.push_back(curve);\n\n  // begin to simplify the curve, applying Ramer-Douglas-Peucker Algorithm\n  while(1)\n  {\n    // output the segment\n    std::cout << \"size:\" << std::endl;\n    for(int i= 0; i < segments.size(); i++)\n    {\n      std::cout << segments[i].size() << \",\";\n    }\n    std::cout << std::endl;\n\n    std::vector<std::vector<Eigen::Vector3d>> updated_segments;\n\n    // simplify each segment\n    for(int i= 0; i < segments.size(); i++)\n    {\n      // get one segment\n      std::vector<Eigen::Vector3d> sgm= segments[i];\n      if(sgm.size() == 2)\n      {\n        updated_segments.push_back(sgm);\n        continue;\n      }\n\n      // get the most distant point's id and distance in this segment\n      float dist= -1.0;\n      int pt_id= -1;\n      getMostDistantPoint(sgm, pt_id, dist);\n      // if distance larger than epsilon, break the segemnt into two parts\n      if(dist > epsilon)\n      {\n        std::vector<Eigen::Vector3d> part1, part2;\n        breakSegment(sgm, pt_id, part1, part2);\n        updated_segments.push_back(part1);\n        updated_segments.push_back(part2);\n      }\n      // distance small enough, only hold front and back point\n      else\n      {\n        std::vector<Eigen::Vector3d> front_back;\n        front_back.push_back(sgm.front());\n        front_back.push_back(sgm.back());\n        updated_segments.push_back(front_back);\n      }\n    }\n\n    // after one iteration, reset the segments\n    segments= updated_segments;\n    updated_segments.clear();\n\n    // if all segments are simplified, stop the iteration, else the iteration continue\n    if(allSegmentSimplified(segments))\n      break;\n  }\n\n  // finally reset points in curve\n  curve.clear();\n  for(int i= 0; i < segments.size(); i++)\n  {\n    curve.insert(curve.end(), segments[i].begin(), segments[i].end());\n  }\n}\n\nvoid RDPCurveSimplifier::getMostDistantPoint(std::vector<Eigen::Vector3d> segment, int &point_id,\n                                             float &distance)\n{\n  Eigen::Vector3d front= segment.front();\n  Eigen::Vector3d back= segment.back();\n\n  point_id= -1;\n  distance= -10.0;\n  for(int i= 1; i < segment.size() - 1; i++)\n  {\n    float dist= 0;\n    getDistanceToLine(front, back, segment[i], dist);\n    if(dist > distance)\n    {\n      distance= dist;\n      point_id= i;\n    }\n  }\n}\n\nvoid RDPCurveSimplifier::breakSegment(std::vector<Eigen::Vector3d> segment, int point_id,\n                                      std::vector<Eigen::Vector3d> &part1,\n                                      std::vector<Eigen::Vector3d> &part2)\n{\n  part1.insert(part1.begin(), segment.begin(), segment.begin() + point_id + 1);\n  part2.insert(part2.begin(), segment.begin() + point_id, segment.end());\n}\n\nbool RDPCurveSimplifier::allSegmentSimplified(std::vector<std::vector<Eigen::Vector3d>> segments)\n{\n  for(int i= 0; i < segments.size(); i++)\n  {\n    if(segments[i].size() != 2)\n    {\n      return false;\n    }\n  }\n\n  return true;\n}\n\nvoid RDPCurveSimplifier::getDistanceToLine(Eigen::Vector3d front, Eigen::Vector3d back,\n                                           Eigen::Vector3d point, float &distance)\n{\n  Eigen::Vector4d line_dir(back(0) - front(0), back(1) - front(1), back(2) - front(2), 0);\n  line_dir.normalize();\n  Eigen::Vector4d p2p(point(0) - front(0), point(1) - front(1), point(2) - front(2), 0);\n\n  distance= p2p.cross3(line_dir).squaredNorm();\n  distance= sqrt(distance);\n}\n\n#endif", "meta": {"hexsha": "d566b12c8035062ead6ebf58dbf74cf6ac2a6d32", "size": 4665, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "grad_traj_optimization/src/grad_traj_optimization/include/douglas_peucker.hpp", "max_stars_repo_name": "Sunshinehualong/motion_Planning", "max_stars_repo_head_hexsha": "ea127de8cd8f32e9994538416d0c74b99054214f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2019-08-24T08:28:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-28T05:23:42.000Z", "max_issues_repo_path": "grad_traj_optimization/src/grad_traj_optimization/include/douglas_peucker.hpp", "max_issues_repo_name": "lvhualong/motion_Planning", "max_issues_repo_head_hexsha": "ea127de8cd8f32e9994538416d0c74b99054214f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "grad_traj_optimization/src/grad_traj_optimization/include/douglas_peucker.hpp", "max_forks_repo_name": "lvhualong/motion_Planning", "max_forks_repo_head_hexsha": "ea127de8cd8f32e9994538416d0c74b99054214f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2019-08-24T08:28:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-19T12:47:20.000Z", "avg_line_length": 29.3396226415, "max_line_length": 97, "alphanum_fraction": 0.6342979636, "num_tokens": 1260, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581741774411, "lm_q2_score": 0.6477982111525411, "lm_q1q2_score": 0.4775297465686197}}
{"text": "/*******************************************************************************\n *         Copyright 2003 & onward LASMEA UMR 6602 CNRS/Univ. Clermont II\n *         Copyright 2009 & onward LRI    UMR 8623 CNRS/Univ Paris Sud XI\n *\n *          Distributed under the Boost Software License, Version 1.0.\n *                 See accompanying file LICENSE.txt or copy at\n *                     http://www.boost.org/LICENSE_1_0.txt\n ******************************************************************************/\n#ifndef NT2_SDK_MEMORY_META_ALIGN_ON_HPP_INCLUDED\n#define NT2_SDK_MEMORY_META_ALIGN_ON_HPP_INCLUDED\n\n#include <cstddef>\n#include <boost/mpl/size_t.hpp>\n#include <boost/mpl/integral_c.hpp>\n#include <nt2/sdk/memory/parameters.hpp>\n#include <nt2/sdk/error/static_assert.hpp>\n#include <nt2/sdk/memory/meta/is_power_of_2.hpp>\n\nnamespace nt2 { namespace meta\n{\n  //////////////////////////////////////////////////////////////////////////////\n  // Compute an aligned value of an integral constant on a power of 2 boundary.\n  // Documentation: align_on_c.rst\n  //////////////////////////////////////////////////////////////////////////////\n  template<std::size_t V, std::size_t N = NT2_CONFIG_ALIGNMENT>\n  struct align_on_c\n       : boost::mpl::integral_c< std::size_t\n                               , (V+N-1) & ~(N-1)\n                               >\n  {\n    NT2_STATIC_ASSERT ( (meta::is_power_of_2_c<N>::value)\n                      , INVALID_ALIGNMENT_VALUE\n                      , \"Alignment done on a non-power of two boundary.\"\n                      );\n  };\n\n  //////////////////////////////////////////////////////////////////////////////\n  // Compute an aligned value of an Integral Constant on a power of 2 boundary.\n  // Documentation: align_on.rst\n  //////////////////////////////////////////////////////////////////////////////\n  template<class V, class N = boost::mpl::size_t<NT2_CONFIG_ALIGNMENT> >\n  struct align_on\n       : boost::mpl::integral_c< typename V::value_type\n                               , align_on_c<V::value,N::value>::value\n                               >\n  {};\n} }\n\n#endif\n", "meta": {"hexsha": "ffb03227deec2e718088655bc8bac72f073cd72f", "size": 2109, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/sdk/include/nt2/sdk/memory/meta/align_on.hpp", "max_stars_repo_name": "brycelelbach/nt2", "max_stars_repo_head_hexsha": "73d7e8dd390fa4c8d251c6451acdae65def70e0b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-24T03:35:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T03:35:10.000Z", "max_issues_repo_path": "modules/sdk/include/nt2/sdk/memory/meta/align_on.hpp", "max_issues_repo_name": "brycelelbach/nt2", "max_issues_repo_head_hexsha": "73d7e8dd390fa4c8d251c6451acdae65def70e0b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/sdk/include/nt2/sdk/memory/meta/align_on.hpp", "max_forks_repo_name": "brycelelbach/nt2", "max_forks_repo_head_hexsha": "73d7e8dd390fa4c8d251c6451acdae65def70e0b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.18, "max_line_length": 80, "alphanum_fraction": 0.4770033191, "num_tokens": 415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.47752974409971305}}
{"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#include <boost/simd/function/ldexp.hpp>\n#include <boost/simd/function/std.hpp>\n#include <boost/simd/function/fast.hpp>\n#include <boost/simd/pack.hpp>\n#include <simd_test.hpp>\n#include <boost/simd/detail/dispatch/meta/as_integer.hpp>\n\nnamespace bs = boost::simd;\nnamespace bd = boost::dispatch;\n\ntemplate <typename T, std::size_t N, typename Env>\nvoid test(Env& $)\n{\n  using iT = bd::as_integer_t<T>;\n  using p_t = bs::pack<T, N>;\n  using pi_t = bs::pack<iT, N>;\n\n  T a1[N],  b[N], c[N], d[N];\n  iT a2[N];\n  for(std::size_t i = 0; i < N; ++i)\n  {\n    a1[i] = (i%2) ? T(i) : T(-1.*i);\n    a2[i] = i%(sizeof(T)*8-1);\n    b[i] = bs::ldexp(a1[i], a2[i]);\n    c[i] = bs::std_(bs::ldexp)(a1[i], a2[i]);\n    d[i] = bs::fast_(bs::ldexp)(a1[i], a2[i]);\n  }\n\n  p_t aa1(&a1[0], &a1[0]+N);\n  pi_t aa2(&a2[0], &a2[0]+N);\n  p_t bb(&b[0], &b[0]+N);\n  p_t cc(&c[0], &c[0]+N);\n  p_t dd(&d[0], &d[0]+N);\n\n  STF_IEEE_EQUAL(bs::ldexp(aa1, aa2)            , bb);\n  STF_IEEE_EQUAL(bs::std_(bs::ldexp)(aa1, aa2)  , cc);\n  STF_IEEE_EQUAL(bs::fast_(bs::ldexp)(aa1, aa2) , dd);\n}\n\nSTF_CASE_TPL(\"Check ldexp on pack\" , STF_NUMERIC_TYPES)\n{\n  static const std::size_t N = bs::pack<T>::static_size;\n  test<T, N>($);\n  test<T, N/2>($);\n  test<T, N*2>($);\n}\n\ntemplate <typename T, std::size_t N, typename Env>\nvoid tests(Env& $)\n{\n  using p_t = bs::pack<T, N>;\n\n  T a1[N],  b[N], c[N];\n  for(std::size_t i = 0; i < N; ++i)\n  {\n    a1[i] = (i%2) ? T(i) : T(-1.*i);\n    b[i] = bs::ldexp(a1[i], 2);\n    c[i] = bs::fast_(bs::ldexp)(a1[i], 2);\n  }\n\n  p_t aa1(&a1[0], &a1[0]+N);\n  p_t bb(&b[0], &b[0]+N);\n  p_t cc(&c[0], &c[0]+N);\n\n  STF_IEEE_EQUAL(bs::ldexp(aa1, 2)            , bb);\n  STF_IEEE_EQUAL(bs::fast_(bs::ldexp)(aa1, 2) , cc);\n}\n\nSTF_CASE_TPL(\"Check ldexp on pack/scalar\" , STF_NUMERIC_TYPES)\n{\n  static const std::size_t N = bs::pack<T>::static_size;\n  tests<T, N>($);\n  tests<T, N/2>($);\n  tests<T, N*2>($);\n}\n", "meta": {"hexsha": "c685d37f7caaab15ac75519f66c8506ebd271602", "size": 2277, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/simd/ldexp.cpp", "max_stars_repo_name": "timblechmann/boost.simd", "max_stars_repo_head_hexsha": "2217f1d0102193799469b533e3a7118bf4a77dde", "max_stars_repo_licenses": ["BSL-1.0"], "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": "test/function/simd/ldexp.cpp", "max_issues_repo_name": "timblechmann/boost.simd", "max_issues_repo_head_hexsha": "2217f1d0102193799469b533e3a7118bf4a77dde", "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/function/simd/ldexp.cpp", "max_forks_repo_name": "timblechmann/boost.simd", "max_forks_repo_head_hexsha": "2217f1d0102193799469b533e3a7118bf4a77dde", "max_forks_repo_licenses": ["BSL-1.0"], "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": 26.476744186, "max_line_length": 100, "alphanum_fraction": 0.519982433, "num_tokens": 839, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799253, "lm_q2_score": 0.6477982247516797, "lm_q1q2_score": 0.47752974163080614}}
{"text": "#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/compute_average_spacing.h>\n#include <CGAL/IO/read_points.h>\n\n#include <vector>\n#include <fstream>\n#include <boost/tuple/tuple.hpp>\n\n// Types\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel;\ntypedef Kernel::FT FT;\ntypedef Kernel::Point_3 Point;\n\n// Data type := index, followed by the point, followed by three integers that\n// define the Red Green Blue color of the point.\ntypedef boost::tuple<int, Point, int, int, int> IndexedPointWithColorTuple;\n\n// Concurrency\ntypedef CGAL::Parallel_if_available_tag Concurrency_tag;\n\nint main(int argc, char*argv[])\n{\n  const std::string fname = (argc>1)?argv[1]:CGAL::data_file_path(\"points_3/sphere_20k.xyz\");\n\n  // Reads a file in points.\n  // As the point is the second element of the tuple (that is with index 1)\n  // we use a property map that accesses the 1st element of the tuple.\n\n  std::vector<IndexedPointWithColorTuple> points;\n  if (!CGAL::IO::read_points(fname, std::back_inserter(points),\n                             CGAL::parameters::point_map(CGAL::Nth_of_tuple_property_map<1, IndexedPointWithColorTuple>())))\n  {\n    std::cerr << \"Error: cannot read file \" << fname << std::endl;\n    return EXIT_FAILURE;\n  }\n\n  // Initialize index and RGB color fields in tuple.\n  // As the index and RGB color are respectively the first and third-fifth elements\n  // of the tuple we use a get function from the property map that accesses the 0\n  // and 2-4th elements of the tuple.\n  for(unsigned int i = 0; i < points.size(); i++)\n  {\n    points[i].get<0>() = i; // set index value of tuple to i\n\n    points[i].get<2>() = 0; // set RGB color to black\n    points[i].get<3>() = 0;\n    points[i].get<4>() = 0;\n  }\n\n  // Computes average spacing.\n  const unsigned int nb_neighbors = 6; // 1 ring\n  FT average_spacing = CGAL::compute_average_spacing<Concurrency_tag>(\n                         points, nb_neighbors,\n                         CGAL::parameters::point_map(CGAL::Nth_of_tuple_property_map<1,IndexedPointWithColorTuple>()));\n\n  std::cout << \"Average spacing: \" << average_spacing << std::endl;\n\n  return EXIT_SUCCESS;\n}\n\n", "meta": {"hexsha": "60320cb67eeed29219838b8d5b40b0802f9fae2f", "size": 2168, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Point_set_processing_3/examples/Point_set_processing_3/average_spacing_example.cpp", "max_stars_repo_name": "ffteja/cgal", "max_stars_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 3227.0, "max_stars_repo_stars_event_min_datetime": "2015-03-05T00:19:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:20:35.000Z", "max_issues_repo_path": "Point_set_processing_3/examples/Point_set_processing_3/average_spacing_example.cpp", "max_issues_repo_name": "ffteja/cgal", "max_issues_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 5574.0, "max_issues_repo_issues_event_min_datetime": "2015-03-05T00:01:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:08:11.000Z", "max_forks_repo_path": "Point_set_processing_3/examples/Point_set_processing_3/average_spacing_example.cpp", "max_forks_repo_name": "ffteja/cgal", "max_forks_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1274.0, "max_forks_repo_forks_event_min_datetime": "2015-03-05T00:01:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:47:56.000Z", "avg_line_length": 35.5409836066, "max_line_length": 124, "alphanum_fraction": 0.6964944649, "num_tokens": 561, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799252, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.4775297366184481}}
{"text": "/*\n * Copyright Andrey Semashev 2020\n *\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/*!\n * \\file countr_zero.hpp\n *\n * This header defines \\c countr_zero algorithm, which counts the number of consecutive\n * least significant zero bits in an integer.\n */\n\n#ifndef BOOST_BIT_OPS_COUNTING_COUNTR_ZERO_HPP_INCLUDED_\n#define BOOST_BIT_OPS_COUNTING_COUNTR_ZERO_HPP_INCLUDED_\n\n#include <limits>\n#include <boost/bit_ops/detail/config.hpp>\n#include <boost/bit_ops/detail/int_sizes.hpp>\n#include <boost/bit_ops/detail/type_traits/enable_if.hpp>\n#include <boost/bit_ops/detail/type_traits/integral_constant.hpp>\n#include <boost/bit_ops/detail/type_traits/is_integral.hpp>\n#include <boost/bit_ops/detail/type_traits/is_unsigned.hpp>\n\n#if defined(_MSC_VER)\n#include <intrin.h>\n#endif\n\nnamespace boost {\nnamespace bit_ops {\n\nnamespace detail {\n\n#if defined(BOOST_BIT_OPS_DETAIL_HAS_BUILTIN_CTZ)\n\ntemplate< typename T, unsigned int N >\ninline typename bit_ops::detail::enable_if< N <= BOOST_BIT_OPS_DETAIL_SIZEOF_INT, unsigned int >::type countr_zero_nz(T value, bit_ops::detail::integral_constant< unsigned int, N >) BOOST_NOEXCEPT\n{\n    return static_cast< unsigned int >(__builtin_ctz(value));\n}\n\n#if BOOST_BIT_OPS_DETAIL_SIZEOF_LONG > BOOST_BIT_OPS_DETAIL_SIZEOF_INT\n\ntemplate< typename T, unsigned int N >\ninline typename bit_ops::detail::enable_if< N == BOOST_BIT_OPS_DETAIL_SIZEOF_LONG, unsigned int >::type countr_zero_nz(T value, bit_ops::detail::integral_constant< unsigned int, N >) BOOST_NOEXCEPT\n{\n    return static_cast< unsigned int >(__builtin_ctzl(value));\n}\n\n#endif // BOOST_BIT_OPS_DETAIL_SIZEOF_LONG > BOOST_BIT_OPS_DETAIL_SIZEOF_INT\n\n#if BOOST_BIT_OPS_DETAIL_SIZEOF_LLONG > BOOST_BIT_OPS_DETAIL_SIZEOF_LONG\n\ntemplate< typename T, unsigned int N >\ninline typename bit_ops::detail::enable_if< N == BOOST_BIT_OPS_DETAIL_SIZEOF_LLONG, unsigned int >::type countr_zero_nz(T value, bit_ops::detail::integral_constant< unsigned int, N >) BOOST_NOEXCEPT\n{\n    return static_cast< unsigned int >(__builtin_ctzll(value));\n}\n\n#endif // BOOST_BIT_OPS_DETAIL_SIZEOF_LLONG > BOOST_BIT_OPS_DETAIL_SIZEOF_LONG\n\n#elif defined(BOOST_BIT_OPS_DETAIL_HAS_BIT_SCAN_FORWARD)\n\ntemplate< typename T, unsigned int N >\ninline typename bit_ops::detail::enable_if< N <= BOOST_BIT_OPS_DETAIL_SIZEOF_LONG, unsigned int >::type countr_zero_nz(T value, bit_ops::detail::integral_constant< unsigned int, N >) BOOST_NOEXCEPT\n{\n    unsigned long pos;\n    _BitScanForward(&pos, value);\n    return static_cast< unsigned int >(pos);\n}\n\n#if BOOST_BIT_OPS_DETAIL_SIZEOF_LLONG > BOOST_BIT_OPS_DETAIL_SIZEOF_LONG\n\ntemplate< typename T, unsigned int N >\ninline typename bit_ops::detail::enable_if< N == BOOST_BIT_OPS_DETAIL_SIZEOF_LLONG, unsigned int >::type countr_zero_nz(T value, bit_ops::detail::integral_constant< unsigned int, N >) BOOST_NOEXCEPT\n{\n#if defined(_M_AMD64) || defined(_M_ARM64)\n    unsigned long pos;\n    _BitScanForward64(&pos, value);\n    return static_cast< unsigned int >(pos);\n#else\n    unsigned long pos;\n    if (!_BitScanForward(&pos, static_cast< unsigned int >(value)))\n        _BitScanForward(&pos, static_cast< unsigned int >(value >> 32u));\n    return static_cast< unsigned int >(pos);\n#endif\n}\n\n#endif // BOOST_BIT_OPS_DETAIL_SIZEOF_LLONG > BOOST_BIT_OPS_DETAIL_SIZEOF_LONG\n\n#else\n\ntemplate< typename T, unsigned int N >\ninline unsigned int countr_zero_nz(T value, bit_ops::detail::integral_constant< unsigned int, N >) BOOST_NOEXCEPT\n{\n    unsigned int count = 0u;\n    unsigned int digits = std::numeric_limits< T >::digits / 2u;\n    T mask = (static_cast< T >(1u) << digits) - 1u;\n    for (; digits > 0u; digits >>= 1u, mask >>= digits)\n    {\n        if ((value & mask) == 0u)\n        {\n            count += digits;\n            value >>= digits;\n        }\n    }\n\n    return count;\n}\n\n#endif\n\n#if defined(BOOST_BIT_OPS_DETAIL_HAS_TZCNT_U32)\n\n#if defined(BOOST_BIT_OPS_DETAIL_HAS_TZCNT_U16)\n\ntemplate< typename T, unsigned int N >\ninline typename bit_ops::detail::enable_if< N <= 2u, unsigned int >::type countr_zero(T value, bit_ops::detail::integral_constant< unsigned int, N >) BOOST_NOEXCEPT\n{\n    // Note: gcc provides the intrinsic with two double underscores\n    return static_cast< unsigned int >(__tzcnt_u16(value) - (16u - std::numeric_limits< T >::digits));\n}\n\ntemplate< typename T, unsigned int N >\ninline typename bit_ops::detail::enable_if< N == 4u, unsigned int >::type countr_zero(T value, bit_ops::detail::integral_constant< unsigned int, N >) BOOST_NOEXCEPT\n{\n    return static_cast< unsigned int >(_tzcnt_u32(value));\n}\n\n#else // defined(BOOST_BIT_OPS_DETAIL_HAS_TZCNT_U16)\n\ntemplate< typename T, unsigned int N >\ninline typename bit_ops::detail::enable_if< N <= 4u, unsigned int >::type countr_zero(T value, bit_ops::detail::integral_constant< unsigned int, N >) BOOST_NOEXCEPT\n{\n    return static_cast< unsigned int >(_tzcnt_u32(value) - (32u - std::numeric_limits< T >::digits));\n}\n\n#endif // defined(BOOST_BIT_OPS_DETAIL_HAS_TZCNT_U16)\n\ntemplate< typename T, unsigned int N >\ninline typename bit_ops::detail::enable_if< N == 8u, unsigned int >::type countr_zero(T value, bit_ops::detail::integral_constant< unsigned int, N >) BOOST_NOEXCEPT\n{\n#if defined(BOOST_BIT_OPS_DETAIL_HAS_TZCNT_U64)\n    return static_cast< unsigned int >(_tzcnt_u64(value));\n#else\n    unsigned int count = _tzcnt_u32(static_cast< unsigned int >(value));\n    if (count == 32u)\n        count += _tzcnt_u32(static_cast< unsigned int >(value >> 32u));\n    return count;\n#endif // defined(BOOST_BIT_OPS_DETAIL_HAS_TZCNT_U64)\n}\n\n#endif // defined(BOOST_BIT_OPS_DETAIL_HAS_TZCNT_U32)\n\n} // namespace detail\n\n/*!\n * \\brief Returns the number of consecutive least significant zero bits in \\a value\n *\n * \\pre \\a value must not be zero\n */\ntemplate< typename T >\ninline typename bit_ops::detail::enable_if<\n    bit_ops::detail::is_integral< T >::value && bit_ops::detail::is_unsigned< T >::value,\n    unsigned int\n>::type countr_zero_nz(T value) BOOST_NOEXCEPT\n{\n    return bit_ops::detail::countr_zero_nz(value, bit_ops::detail::integral_constant< unsigned int, sizeof(T) >());\n}\n\n//! Returns the number of consecutive least significant zero bits in \\a value\ntemplate< typename T >\ninline typename bit_ops::detail::enable_if<\n    bit_ops::detail::is_integral< T >::value && bit_ops::detail::is_unsigned< T >::value,\n    unsigned int\n>::type countr_zero(T value) BOOST_NOEXCEPT\n{\n#if defined(BOOST_BIT_OPS_DETAIL_HAS_TZCNT_U32)\n    return bit_ops::detail::countr_zero(value, bit_ops::detail::integral_constant< unsigned int, sizeof(T) >());\n#else\n    return value == 0u ? static_cast< unsigned int >(std::numeric_limits< T >::digits) : bit_ops::countr_zero_nz(value);\n#endif\n}\n\n} // namespace bit_ops\n} // namespace boost\n\n#endif // BOOST_BIT_OPS_COUNTING_COUNTR_ZERO_HPP_INCLUDED_\n", "meta": {"hexsha": "59cd484a403b306c36a5e2ecd2a63c3a71e0c661", "size": 6882, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/bit_ops/counting/countr_zero.hpp", "max_stars_repo_name": "Lastique/bit_ops", "max_stars_repo_head_hexsha": "c0f8d03687affe2d4426d0ff623d6e511d5c1a5b", "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/bit_ops/counting/countr_zero.hpp", "max_issues_repo_name": "Lastique/bit_ops", "max_issues_repo_head_hexsha": "c0f8d03687affe2d4426d0ff623d6e511d5c1a5b", "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/bit_ops/counting/countr_zero.hpp", "max_forks_repo_name": "Lastique/bit_ops", "max_forks_repo_head_hexsha": "c0f8d03687affe2d4426d0ff623d6e511d5c1a5b", "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.2210526316, "max_line_length": 198, "alphanum_fraction": 0.7505085731, "num_tokens": 1792, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.4775297340749969}}
{"text": "#include <glm/models/links/power_odds.hpp>\n\n#include <armadillo>\n\nusing namespace arma;\n\npower_odds_link::power_odds_link(float lambda)\n    : glm_link::glm_link( \"power_odds\" ),\n      m_lambda( lambda )\n{\n}\n\nvec\npower_odds_link::init_beta(const mat &X, const vec &y) const\n{\n    \n    return arma::vec( 0.0 );\n}\n\nvec\npower_odds_link::mu(const arma::vec &eta) const\n{\n    if( m_lambda == 0.0 )\n    {\n        return 1.0 / ( 1 + exp( -eta ) );\n    }\n    else\n    {\n        return 1.0 / ( 1 + pow( 1 + m_lambda * eta, -1 / m_lambda ) );\n    }\n}\n\nvec\npower_odds_link::eta(const arma::vec &mu) const\n{\n    if( m_lambda == 0.0 )\n    {\n        return log( mu / ( 1 - mu ) );\n    }\n    else\n    {\n        return ( pow( mu / ( 1 - mu ), m_lambda ) - 1 ) / m_lambda;\n    }\n}\n\nvec\npower_odds_link::mu_eta(const arma::vec &mu) const\n{\n    if( m_lambda == 0.0 )\n    {\n        return 1.0 / ( mu % ( 1 - mu ) );\n    }\n    else\n    {\n        return pow( mu / (1 - mu), m_lambda ) / ( mu % ( 1 - mu ) );\n    }\n}\n", "meta": {"hexsha": "6da359605b8d9cf6eb40891f220d90f685b83782", "size": 993, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/glm/models/links/power_odds.cpp", "max_stars_repo_name": "hoehleatsu/besiq", "max_stars_repo_head_hexsha": "94959e2819251805e19311ce377919e6bccb7bf9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-10-21T14:22:12.000Z", "max_stars_repo_stars_event_max_datetime": "2015-10-21T14:22:12.000Z", "max_issues_repo_path": "libs/glm/models/links/power_odds.cpp", "max_issues_repo_name": "hoehleatsu/besiq", "max_issues_repo_head_hexsha": "94959e2819251805e19311ce377919e6bccb7bf9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-05-26T20:52:31.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-28T16:19:49.000Z", "max_forks_repo_path": "libs/glm/models/links/power_odds.cpp", "max_forks_repo_name": "hoehleatsu/besiq", "max_forks_repo_head_hexsha": "94959e2819251805e19311ce377919e6bccb7bf9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2016-11-06T14:58:37.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-26T14:03:13.000Z", "avg_line_length": 17.1206896552, "max_line_length": 70, "alphanum_fraction": 0.5216515609, "num_tokens": 338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056322076481139, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4774713013202988}}
{"text": "// graph-tool -- a general graph modification and manipulation thingy\n//\n// Copyright (C) 2006-2018 Tiago de Paula Peixoto <tiago@skewed.de>\n//\n// This program is free software; you can redistribute it and/or\n// modify it under the terms of the GNU General Public License\n// as published by the Free Software Foundation; either version 3\n// of the License, or (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with this program. If not, see <http://www.gnu.org/licenses/>.\n\n#include \"graph_filtering.hh\"\n#include \"graph.hh\"\n#include \"graph_properties.hh\"\n\n#include <boost/bind.hpp>\n\n#ifndef __clang__\n#include <ext/numeric>\nusing __gnu_cxx::power;\n#else\ntemplate <class Value>\nValue power(Value value, int n)\n{\n    return pow(value, n);\n}\n#endif\n\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/math/special_functions/hypot.hpp>\n#include <boost/math/constants/constants.hpp>\n\n#include <boost/graph/fruchterman_reingold.hpp>\n\nusing namespace std;\nusing namespace boost;\nusing namespace graph_tool;\n\nnamespace graph_tool\n{\n// convert point types\ntemplate <class Val>\nstruct convert<vector<Val>, typename convex_topology<2>::point>\n{\n    vector<Val> operator()(const typename convex_topology<2>::point& p) const\n    {\n        vector<Val> v(2);\n        for (size_t i = 0; i < 2; ++i)\n            v[i] = p[i];\n        return v;\n    }\n};\n\ntemplate <class Val>\nstruct convert<typename convex_topology<2>::point, vector<Val> >\n{\n    typename convex_topology<2>::point operator()(const vector<Val>& v) const\n    {\n        typename convex_topology<2>::point p;\n        for (size_t i = 0; i < min(size_t(2), v.size()); ++i)\n            p[i] = v[i];\n        return p;\n    }\n};\n} // graph_tool namespace\n\ntemplate<class T>\nstruct anneal_cooling\n{\n    typedef T result_type;\n\n    anneal_cooling(T ti, T tf, std::size_t iterations)\n        : _ti(ti), _tf(tf), _iter(0), _n_iter(iterations) \n    {\n        _beta = (log(_tf) - log(_ti)) / _n_iter;\n    }\n\n    T operator()()\n    {\n        T temp = _ti * exp(T(_iter) * _beta);\n        ++_iter;\n        if (_iter == _n_iter)\n            temp = 0;\n        return temp;\n    }\n\nprivate:\n    T _ti, _tf;\n    size_t _iter;\n    size_t _n_iter;\n    T _beta;\n};\n\ntemplate <class Topology>\nstruct get_layout\n{\n    template <class WeightMap, class Value>\n    struct attr_force\n    {\n        attr_force(WeightMap w, Value a): _w(w), _a(a) {}\n        WeightMap _w;\n        Value _a;\n\n        template <class Graph, class Edge, class KVal, class DVal>\n        Value operator()(Edge e, KVal k, DVal dist, const Graph&) const\n        {\n            return _a * get(_w, e) * power(dist, 2) / k;\n        }\n    };\n\n    template <class Value>\n    struct rep_force\n    {\n        rep_force(Value r): _r(r){}\n        Value _r;\n\n        template <class Graph, class Vertex, class KVal, class DVal>\n        Value operator()(Vertex, Vertex, KVal k, DVal dist, const Graph&) const\n        {\n            return _r * power(k, 2) / dist;\n        }\n    };\n\n\n    template <class Graph, class PosMap, class WeightMap>\n    void operator()(Graph& g, PosMap pos, WeightMap weight,\n                    pair<double, double> f, double scale, bool grid,\n                    pair<double, double> temp, size_t n_iter) const\n    {\n        typedef typename property_traits<PosMap>::value_type::value_type pos_t;\n        anneal_cooling<pos_t> cool(temp.first, temp.second, n_iter);\n        attr_force<WeightMap, pos_t> af(weight, f.first);\n        rep_force<pos_t> rf(f.second);\n        Topology topology(scale);\n        ConvertedPropertyMap<PosMap, typename Topology::point_type> cpos(pos);\n        if (grid)\n            fruchterman_reingold_force_directed_layout\n                (g, cpos,\n                 topology,\n                 attractive_force(af).\n                 repulsive_force(rf).\n                 cooling(cool));\n        else\n            fruchterman_reingold_force_directed_layout\n                (g, cpos,\n                 topology,\n                 attractive_force(af).\n                 repulsive_force(rf).\n                 cooling(cool).\n                 force_pairs(all_force_pairs()));\n    }\n};\n\n\nvoid fruchterman_reingold_layout(GraphInterface& g, boost::any pos,\n                                 boost::any weight, double a, double r,\n                                 bool square, double scale, bool grid,\n                                 double ti, double tf, size_t max_iter)\n{\n    typedef UnityPropertyMap<int,GraphInterface::edge_t> weight_map_t;\n    typedef boost::mpl::push_back<edge_scalar_properties, weight_map_t>::type\n        edge_props_t;\n\n    if(weight.empty())\n        weight = weight_map_t();\n    if (square)\n        run_action<graph_tool::detail::never_directed>()\n            (g,\n             std::bind(get_layout<square_topology<> >(), std::placeholders::_1,\n                       std::placeholders::_2, std::placeholders::_3, make_pair(a, r), scale,\n                       grid, make_pair(ti, tf), max_iter),\n             vertex_floating_vector_properties(), edge_props_t())\n            (pos, weight);\n    else\n        run_action<graph_tool::detail::never_directed>()\n            (g,\n             std::bind(get_layout<circle_topology<> >(), std::placeholders::_1,\n                       std::placeholders::_2, std::placeholders::_3, make_pair(a, r),\n                       scale, grid, make_pair(ti, tf), max_iter),\n             vertex_floating_vector_properties(), edge_props_t()) (pos, weight);\n}\n\n#include <boost/python.hpp>\n\nvoid export_fruchterman_reingold()\n{\n    python::def(\"fruchterman_reingold_layout\", &fruchterman_reingold_layout);\n}\n", "meta": {"hexsha": "85fc88f4e9df91785f1f0916ace1325f012ff4e9", "size": 5910, "ext": "cc", "lang": "C++", "max_stars_repo_path": "graph-tool-2.27/src/graph/layout/graph_fruchterman_reingold.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_fruchterman_reingold.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_fruchterman_reingold.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": 30.3076923077, "max_line_length": 92, "alphanum_fraction": 0.6126903553, "num_tokens": 1441, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812554, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.47747129025707524}}
{"text": "/*\n\nCopyright (c) 2007-2016, Un Shyam, Arvid Norberg, Steven Siloti\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n    * Redistributions of source code must retain the above copyright\n      notice, this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above copyright\n      notice, this list of conditions and the following disclaimer in\n      the documentation and/or other materials provided with the distribution.\n    * Neither the name of the author 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\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 OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, 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\n#if !defined(TORRENT_DISABLE_ENCRYPTION) && !defined(TORRENT_DISABLE_EXTENSIONS)\n\n#include <cstdint>\n#include <algorithm>\n#include <random>\n\n#include \"libtorrent/aux_/disable_warnings_push.hpp\"\n\n#include <boost/multiprecision/integer.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n\n// for backwards compatibility with boost < 1.60 which was before export_bits\n// and import_bits were introduced\n#if BOOST_VERSION < 106000\n#include \"libtorrent/aux_/cppint_import_export.hpp\"\n#endif\n\n#include \"libtorrent/aux_/disable_warnings_pop.hpp\"\n\n#include \"libtorrent/random.hpp\"\n#include \"libtorrent/alloca.hpp\"\n#include \"libtorrent/pe_crypto.hpp\"\n#include \"libtorrent/hasher.hpp\"\n#include \"libtorrent/assert.hpp\"\n#include \"libtorrent/span.hpp\"\n\nnamespace libtorrent\n{\n\tnamespace mp = boost::multiprecision;\n\n\tnamespace {\n\t\t// TODO: it would be nice to get the literal working\n\t\tkey_t const dh_prime\n\t\t\t(\"0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A63A36210000000000090563\");\n\t}\n\n\tstd::array<char, 96> export_key(key_t const& k)\n\t{\n\t\tstd::array<char, 96> ret;\n\t\tstd::uint8_t* begin = reinterpret_cast<std::uint8_t*>(ret.data());\n\t\tstd::uint8_t* end = mp::export_bits(k, begin, 8);\n\n\t\t// TODO: it would be nice to be able to export to a fixed width field, so\n\t\t// we wouldn't have to shift it later\n\t\tif (end < begin + 96)\n\t\t{\n\t\t\tint const len = end - begin;\n\t\t\tstd::memmove(begin + 96 - len, begin, len);\n\t\t\tstd::memset(begin, 0, 96 - len);\n\t\t}\n\t\treturn ret;\n\t}\n\n\tvoid rc4_init(const unsigned char* in, unsigned long len, rc4 *state);\n\tunsigned long rc4_encrypt(unsigned char *out, unsigned long outlen, rc4 *state);\n\n\t// Set the prime P and the generator, generate local public key\n\tdh_key_exchange::dh_key_exchange()\n\t{\n\t\tstd::array<std::uint8_t, 96> random_key;\n\t\tfor (auto& i : random_key) i = random(0xff);\n\n\t\t// create local key (random)\n\t\tmp::import_bits(m_dh_local_secret, random_key.begin(), random_key.end());\n\n\t\t// key = (2 ^ secret) % prime\n\t\tm_dh_local_key = mp::powm(key_t(2), m_dh_local_secret, dh_prime);\n\t}\n\n\t// compute shared secret given remote public key\n\tvoid dh_key_exchange::compute_secret(std::uint8_t const* remote_pubkey)\n\t{\n\t\tTORRENT_ASSERT(remote_pubkey);\n\t\tkey_t key;\n\t\tmp::import_bits(key, remote_pubkey, remote_pubkey + 96);\n\t\tcompute_secret(key);\n\t}\n\n\tvoid dh_key_exchange::compute_secret(key_t const& remote_pubkey)\n\t{\n\t\t// shared_secret = (remote_pubkey ^ local_secret) % prime\n\t\tm_dh_shared_secret = mp::powm(remote_pubkey, m_dh_local_secret, dh_prime);\n\n\t\tstd::array<char, 96> buffer;\n\t\tmp::export_bits(m_dh_shared_secret, reinterpret_cast<std::uint8_t*>(buffer.data()), 8);\n\n\t\tstatic char const req3[4] = {'r', 'e', 'q', '3'};\n\t\t// calculate the xor mask for the obfuscated hash\n\t\tm_xor_mask = hasher(req3).update(buffer).final();\n\t}\n\n\tstd::tuple<int, span<span<char const>>>\n\tencryption_handler::encrypt(\n\t\tspan<span<char>> iovec)\n\t{\n\t\tTORRENT_ASSERT(!m_send_barriers.empty());\n\t\tTORRENT_ASSERT(m_send_barriers.front().enc_handler);\n\n\t\tint to_process = m_send_barriers.front().next;\n\n\t\tspan<char>* bufs;\n\t\tsize_t num_bufs;\n\t\tbool need_destruct = false;\n\t\tif (to_process != INT_MAX)\n\t\t{\n\t\t\tbufs = TORRENT_ALLOCA(span<char>, iovec.size());\n\t\t\tneed_destruct = true;\n\t\t\tnum_bufs = 0;\n\t\t\tfor (int i = 0; to_process > 0 && i < iovec.size(); ++i)\n\t\t\t{\n\t\t\t\t++num_bufs;\n\t\t\t\tint const size = int(iovec[i].size());\n\t\t\t\tif (to_process < size)\n\t\t\t\t{\n\t\t\t\t\tnew (&bufs[i]) span<char>(\n\t\t\t\t\t\tiovec[i].data(), to_process);\n\t\t\t\t\tto_process = 0;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tnew (&bufs[i]) span<char>(iovec[i]);\n\t\t\t\t\tto_process -= size;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tbufs = iovec.data();\n\t\t\tnum_bufs = iovec.size();\n\t\t}\n\n\t\tint next_barrier = 0;\n\t\tspan<span<char const>> out_iovec;\n\t\tif (num_bufs != 0)\n\t\t{\n\t\t\tstd::tie(next_barrier, out_iovec)\n\t\t\t\t= m_send_barriers.front().enc_handler->encrypt({bufs, size_t(num_bufs)});\n\t\t}\n\n\t\tif (m_send_barriers.front().next != INT_MAX)\n\t\t{\n\t\t\t// to_process holds the difference between the size of the buffers\n\t\t\t// and the bytes left to the next barrier\n\t\t\t// if it's zero then pop the barrier\n\t\t\t// otherwise update the number of bytes remaining to the next barrier\n\t\t\tif (to_process == 0)\n\t\t\t{\n\t\t\t\tif (m_send_barriers.size() == 1)\n\t\t\t\t{\n\t\t\t\t\t// transitioning back to plaintext\n\t\t\t\t\tnext_barrier = INT_MAX;\n\t\t\t\t}\n\t\t\t\tm_send_barriers.pop_front();\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tm_send_barriers.front().next = to_process;\n\t\t\t}\n\t\t}\n\n#if TORRENT_USE_ASSERTS\n\t\tif (next_barrier != INT_MAX && next_barrier != 0)\n\t\t{\n\t\t\tint payload = 0;\n\t\t\tfor (int i = 0; i < num_bufs; ++i)\n\t\t\t\tpayload += int(bufs[i].size());\n\n\t\t\tint overhead = 0;\n\t\t\tfor (auto buf : out_iovec)\n\t\t\t\toverhead += int(buf.size());\n\t\t\tTORRENT_ASSERT(overhead + payload == next_barrier);\n\t\t}\n#endif\n\t\tif (need_destruct)\n\t\t{\n\t\t\tfor (int i = 0; i < num_bufs; ++i)\n\t\t\t\tbufs[i].~span<char>();\n\t\t}\n\t\treturn std::make_tuple(next_barrier, out_iovec);\n\t}\n\n\tint encryption_handler::decrypt(crypto_receive_buffer& recv_buffer\n\t\t, std::size_t& bytes_transferred)\n\t{\n\t\tTORRENT_ASSERT(!is_recv_plaintext());\n\t\tint consume = 0;\n\t\tif (recv_buffer.crypto_packet_finished())\n\t\t{\n\t\t\tspan<char> wr_buf = recv_buffer.mutable_buffer(bytes_transferred);\n\t\t\tint produce = 0;\n\t\t\tint packet_size = 0;\n\t\t\tstd::tie(consume, produce, packet_size) = m_dec_handler->decrypt(wr_buf);\n\t\t\tTORRENT_ASSERT(packet_size || produce);\n\t\t\tTORRENT_ASSERT(packet_size >= 0);\n\t\t\tbytes_transferred = produce;\n\t\t\tif (packet_size)\n\t\t\t\trecv_buffer.crypto_cut(consume, packet_size);\n\t\t}\n\t\telse\n\t\t\tbytes_transferred = 0;\n\t\treturn consume;\n\t}\n\n\tbool encryption_handler::switch_send_crypto(std::shared_ptr<crypto_plugin> crypto\n\t\t, int pending_encryption)\n\t{\n\t\tbool place_barrier = false;\n\t\tif (!m_send_barriers.empty())\n\t\t{\n\t\t\tstd::list<barrier>::iterator end = m_send_barriers.end(); --end;\n\t\t\tfor (std::list<barrier>::iterator b = m_send_barriers.begin();\n\t\t\t\tb != end; ++b)\n\t\t\t\tpending_encryption -= b->next;\n\t\t\tTORRENT_ASSERT(pending_encryption >= 0);\n\t\t\tm_send_barriers.back().next = pending_encryption;\n\t\t}\n\t\telse if (crypto)\n\t\t\tplace_barrier = true;\n\n\t\tif (crypto)\n\t\t\tm_send_barriers.push_back(barrier(crypto, INT_MAX));\n\n\t\treturn place_barrier;\n\t}\n\n\tvoid encryption_handler::switch_recv_crypto(std::shared_ptr<crypto_plugin> crypto\n\t\t, crypto_receive_buffer& recv_buffer)\n\t{\n\t\tm_dec_handler = crypto;\n\t\tint packet_size = 0;\n\t\tif (crypto)\n\t\t{\n\t\t\tint consume = 0;\n\t\t\tint produce = 0;\n\t\t\tstd::vector<span<char>> wr_buf;\n\t\t\tstd::tie(consume, produce, packet_size) = crypto->decrypt(wr_buf);\n\t\t\tTORRENT_ASSERT(wr_buf.empty());\n\t\t\tTORRENT_ASSERT(consume == 0);\n\t\t\tTORRENT_ASSERT(produce == 0);\n\t\t}\n\t\trecv_buffer.crypto_reset(packet_size);\n\t}\n\n\trc4_handler::rc4_handler()\n\t\t: m_encrypt(false)\n\t\t, m_decrypt(false)\n\t{\n\t\tm_rc4_incoming.x = 0;\n\t\tm_rc4_incoming.y = 0;\n\t\tm_rc4_outgoing.x = 0;\n\t\tm_rc4_outgoing.y = 0;\n\t}\n\n\tvoid rc4_handler::set_incoming_key(span<char const> key)\n\t{\n\t\tm_decrypt = true;\n\t\trc4_init(reinterpret_cast<unsigned char const*>(key.data())\n\t\t\t, key.size(), &m_rc4_incoming);\n\t\t// Discard first 1024 bytes\n\t\tchar buf[1024];\n\t\tspan<char> vec(buf, sizeof(buf));\n\t\tdecrypt(vec);\n\t}\n\n\tvoid rc4_handler::set_outgoing_key(span<char const> key)\n\t{\n\t\tm_encrypt = true;\n\t\trc4_init(reinterpret_cast<unsigned char const*>(key.data())\n\t\t\t, key.size(), &m_rc4_outgoing);\n\t\t// Discard first 1024 bytes\n\t\tchar buf[1024];\n\t\tspan<char> vec(buf, sizeof(buf));\n\t\tencrypt(vec);\n\t}\n\n\tstd::tuple<int, span<span<char const>>>\n\trc4_handler::encrypt(span<span<char>> bufs)\n\t{\n\t\tspan<span<char const>> empty;\n\t\tif (!m_encrypt) return std::make_tuple(0, empty);\n\t\tif (bufs.size() == 0) return std::make_tuple(0, empty);\n\n\t\tint bytes_processed = 0;\n\t\tfor (auto& buf : bufs)\n\t\t{\n\t\t\tunsigned char* const pos = reinterpret_cast<unsigned char*>(buf.data());\n\t\t\tint const len = int(buf.size());\n\n\t\t\tTORRENT_ASSERT(len >= 0);\n\t\t\tTORRENT_ASSERT(pos);\n\n\t\t\tbytes_processed += len;\n\t\t\trc4_encrypt(pos, len, &m_rc4_outgoing);\n\t\t}\n\t\treturn std::make_tuple(bytes_processed, empty);\n\t}\n\n\tstd::tuple<int, int, int> rc4_handler::decrypt(span<span<char>> bufs)\n\t{\n\t\tif (!m_decrypt) std::make_tuple(0, 0, 0);\n\n\t\tint bytes_processed = 0;\n\t\tfor (auto& buf : bufs)\n\t\t{\n\t\t\tunsigned char* const pos = reinterpret_cast<unsigned char*>(buf.data());\n\t\t\tint const len = int(buf.size());\n\n\t\t\tTORRENT_ASSERT(len >= 0);\n\t\t\tTORRENT_ASSERT(pos);\n\n\t\t\tbytes_processed += len;\n\t\t\trc4_encrypt(pos, len, &m_rc4_incoming);\n\t\t}\n\t\treturn std::make_tuple(0, bytes_processed, 0);\n\t}\n\n// All this code is based on libTomCrypt (http://www.libtomcrypt.com/)\n// this library is public domain and has been specially\n// tailored for libtorrent by Arvid Norberg\n\nvoid rc4_init(const unsigned char* in, unsigned long len, rc4 *state)\n{\n\tsize_t const key_size = sizeof(state->buf);\n\tunsigned char key[key_size], tmp, *s;\n\tint keylen, x, y, j;\n\n\tTORRENT_ASSERT(state != nullptr);\n\tTORRENT_ASSERT(len <= key_size);\n\tif (len > key_size) len = key_size;\n\n\tstate->x = 0;\n\twhile (len--) {\n\t\tstate->buf[state->x++] = *in++;\n\t}\n\n\t/* extract the key */\n\ts = state->buf.data();\n\tstd::memcpy(key, s, key_size);\n\tkeylen = state->x;\n\n\t/* make RC4 perm and shuffle */\n\tfor (x = 0; x < key_size; ++x) {\n\t\ts[x] = x;\n\t}\n\n\tfor (j = x = y = 0; x < key_size; x++) {\n\t\ty = (y + state->buf[x] + key[j++]) & 255;\n\t\tif (j == keylen) {\n\t\t\tj = 0;\n\t\t}\n\t\ttmp = s[x]; s[x] = s[y]; s[y] = tmp;\n\t}\n\tstate->x = 0;\n\tstate->y = 0;\n}\n\nunsigned long rc4_encrypt(unsigned char *out, unsigned long outlen, rc4 *state)\n{\n\tunsigned char x, y, *s, tmp;\n\tunsigned long n;\n\n\tTORRENT_ASSERT(out != nullptr);\n\tTORRENT_ASSERT(state != nullptr);\n\n\tn = outlen;\n\tx = state->x;\n\ty = state->y;\n\ts = state->buf.data();\n\twhile (outlen--) {\n\t\tx = (x + 1) & 255;\n\t\ty = (y + s[x]) & 255;\n\t\ttmp = s[x]; s[x] = s[y]; s[y] = tmp;\n\t\ttmp = (s[x] + s[y]) & 255;\n\t\t*out++ ^= s[tmp];\n\t}\n\tstate->x = x;\n\tstate->y = y;\n\treturn n;\n}\n\n} // namespace libtorrent\n\n#endif // #if !defined(TORRENT_DISABLE_ENCRYPTION) && !defined(TORRENT_DISABLE_EXTENSIONS)\n", "meta": {"hexsha": "c6fa0a07b75dc2c8a6eacba350d052d5ebb74424", "size": 11543, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/pe_crypto.cpp", "max_stars_repo_name": "usertex/lib2", "max_stars_repo_head_hexsha": "c7eb76593cb328c25f762a976485abbfd38694bb", "max_stars_repo_licenses": ["BSL-1.0", "BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/pe_crypto.cpp", "max_issues_repo_name": "usertex/lib2", "max_issues_repo_head_hexsha": "c7eb76593cb328c25f762a976485abbfd38694bb", "max_issues_repo_licenses": ["BSL-1.0", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pe_crypto.cpp", "max_forks_repo_name": "usertex/lib2", "max_forks_repo_head_hexsha": "c7eb76593cb328c25f762a976485abbfd38694bb", "max_forks_repo_licenses": ["BSL-1.0", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7475961538, "max_line_length": 202, "alphanum_fraction": 0.6904617517, "num_tokens": 3411, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4774712902570752}}
{"text": "#include \"itkImage.h\"\n#include \"itkImageFileReader.h\"\n#include \"vnl/vnl_matrix_ref.h\"\n#include \"vnl/vnl_matrix.h\"\n#include \"tkdCmdParser.h\"\n#include \"flens.h\"\n#include <cmath>\n#include <boost/math/special_functions/fpclassify.hpp>\n\n// 26-12-2009\n// added to Kajo's clustercoefficient: nan-check! (for binary unconnected graphs).\n\nclass ClusterCoefficient\n{\npublic:\n\ttypedef float PixelType;\n\ttypedef itk::Image< PixelType, 2 > ImageType;\n\ttypedef vnl_matrix_ref< PixelType > DataMatrixType;\n\ttypedef float PrecisionType;\n\ttypedef flens::GeMatrix< flens::FullStorage< PrecisionType, flens::RowMajor > > MatrixType;\n\ttypedef vnl_vector< PrecisionType > VectorType;\n\n\t/**\n\t * Stam's algorithm ...\n\t */\n\tvoid RunStam( const std::string& filename )\n\t{\n\t\ttypedef itk::ImageFileReader< ImageType > ReaderType;\n\t\tReaderType::Pointer reader = ReaderType::New();\n\t\treader->SetFileName( filename.c_str() );\n\t\treader->Update();\n\n\t\tImageType::Pointer image = reader->GetOutput();\n\t\treader = 0;\n\n\t\tPixelType* buffer = image->GetPixelContainer()->GetBufferPointer();\n\t\tImageType::RegionType region = image->GetLargestPossibleRegion();\n\t\tImageType::SizeType size = region.GetSize();\n\t\tint rows = size[0];\n\t\tint cols = size[1];\n\t\tint nans = 0;\n\n\t\tDataMatrixType wIn( rows, cols, buffer );\n\n\t\tVectorType clusteringcoefficients( rows );\n\n\t\tPrecisionType sum = 0;\n\t\tfor ( int i = 0; i < rows; ++i )\n\t\t{\n\t\t\tPrecisionType numerator = 0;\n\t\t\tPrecisionType denominator = 0;\n\n\t\t\tfor ( int k = 0; k < rows; ++k )\n\t\t\t{\n\t\t\t\tif ( k == i )\n\t\t\t\t{\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tfor ( int l = 0; l < rows; ++l )\n\t\t\t\t{\n\t\t\t\t\tif ( l == k || l == i )\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\tnumerator += ( wIn( i, k ) * wIn( i, l ) * wIn( k, l ) );\n\t\t\t\t\tdenominator += ( wIn( i, k ) * wIn( i, l ) );\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tclusteringcoefficients( i ) = numerator / denominator;\n\n\t\t\tif ( !boost::math::isnan< PixelType >( clusteringcoefficients( i ) ) )\n\t\t\t{\n\t\t\t\t sum += clusteringcoefficients( i );\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tstd::cout << \"*** WARNING ***: nan detected!\" << std::endl;\n\t\t\t\tnans++;\n\t\t\t}\n\t\t}\n\n\t\tstd::cout << ( sum / static_cast< PrecisionType > ( rows - nans ) ) << std::endl;\n\t}\n\n\tvoid RunWeighted( const std::string& filename, PixelType threshold )\n\t{\n\t\ttypedef itk::ImageFileReader< ImageType > ReaderType;\n\t\tReaderType::Pointer reader = ReaderType::New();\n\t\treader->SetFileName( filename.c_str() );\n\t\treader->Update();\n\n\t\tImageType::Pointer image = reader->GetOutput();\n\t\treader = 0;\n\n\t\tPixelType* buffer = image->GetPixelContainer()->GetBufferPointer();\n\t\tImageType::RegionType region = image->GetLargestPossibleRegion();\n\t\tImageType::SizeType size = region.GetSize();\n\t\tint rows = size[0];\n\t\tint cols = size[1];\n\n\t\tDataMatrixType wIn( rows, cols, buffer );\n\n\t\tMatrixType A( rows, cols );\n\t\tMatrixType S( rows, cols );\n\t\tMatrixType B( rows, cols );\n\t\tMatrixType W( rows, cols );\n\n\t\tfor ( int i = 0; i < rows; ++i )\n\t\t{\n\t\t\tfor ( int j = 0; j < cols; ++j )\n\t\t\t{\n\t\t\t\tS( i + 1, j + 1 ) = 0;\n\n\t\t\t\tif ( wIn( i, j ) > threshold )\n\t\t\t\t{\n\t\t\t\t\tA( i + 1, j + 1 ) = 1;\n\t\t\t\t\tB( i + 1, j + 1 ) = vcl_pow( wIn( i, j ), 1. / 3. );\n\t\t\t\t\tW( i + 1, j + 1 ) = wIn( i, j );\n\t\t\t\t} else\n\t\t\t\t{\n\t\t\t\t\tA( i + 1, j + 1 ) = 0;\n\t\t\t\t\tB( i + 1, j + 1 ) = 0;\n\t\t\t\t\tW( i + 1, j + 1 ) = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor ( int i = 1; i <= rows; ++i )\n\t\t{\n\t\t\tfor ( int j = 1; j <= cols; ++j )\n\t\t\t{\n\t\t\t\tS( i, j ) = B( i, j ) + B( j, i );\n\t\t\t}\n\t\t}\n\n\t\tMatrixType p1( rows, cols );\n\t\tMatrixType p( rows, cols );\n\t\tMatrixType a( rows, cols );\n\t\tVectorType C( rows );\n\t\tVectorType K( rows );\n\n\t\tflens::copy( S * S, p1 );\n\t\tflens::copy( p1 * S, p );\n\t\tflens::copy( A * A, a );\n\n\t\tK.fill( 0 );\n\t\tfor ( int i = 0; i < rows; ++i )\n\t\t{\n\t\t\tfor ( int j = 0; j < cols; ++j )\n\t\t\t{\n\t\t\t\tK( i ) += ( A( i + 1, j + 1 ) + A( j + 1, i + 1 ) );\n\t\t\t}\n\n\t\t\tPrecisionType cyc = p( i + 1, i + 1 ) / 2.;\n\t\t\tif ( cyc == 0 )\n\t\t\t{\n\t\t\t\tK( i) = vcl_numeric_limits< PrecisionType>::max();\n\t\t\t}\n\n\t\t\tC( i ) = cyc / ( K( i ) * ( K( i ) - 1 ) - 2 * a( i + 1, i + 1) );\n\t\t}\n\n\t\tPrecisionType sum = 0;\n\t\tfor( int i = 0; i < rows; ++i )\n\t\t{\n\t\t\tsum += C( i );\n\t\t}\n\n\t\tsum /= static_cast< PrecisionType>( rows );\n\t\tstd::cout << sum << std::endl;\n\t}\n\n\tvoid Run( const std::string& filename, PixelType threshold )\n\t{\n\t\ttypedef itk::ImageFileReader< ImageType> ReaderType;\n\t\tReaderType::Pointer reader = ReaderType::New();\n\t\treader->SetFileName( filename.c_str() );\n\t\treader->Update();\n\n\t\tImageType::Pointer image = reader->GetOutput();\n\t\treader = 0;\n\n\t\tPixelType* buffer = image->GetPixelContainer()->GetBufferPointer();\n\t\tImageType::RegionType region = image->GetLargestPossibleRegion();\n\t\tImageType::SizeType size = region.GetSize();\n\t\tint rows = size[ 0 ];\n\t\tint cols = size[ 1 ];\n\n\t\tDataMatrixType data( rows, cols, buffer );\n\t\tfor( int i = 0; i < ( rows * cols ); ++i )\n\t\t{\n\t\t\tbuffer[ i ] *= ( buffer[ i ] < 0 ? -1. : 1. );\n\t\t}\n\n\t\tPixelType sum = 0;\n\t\t//\n\t\t\t\t\t\t//    std::vector< PixelType > t;\n\t\t\t\t\t\t//    for( int i = 0; i < rows; ++i )\n\t\t\t\t\t\t//      {\n\t\t\t\t\t\t//      for( int j = i + 1; j < cols; ++j )\n\t\t\t\t\t\t//        {\n\t\t\t\t\t\t//        if ( data( i, j ) > 0 )\n\t\t\t\t\t\t//          {\n\t\t\t\t\t\t//          t.push_back( data( i, j ) );\n\t\t\t\t\t\t//          }\n\t\t\t\t\t\t//        }\n\t\t\t\t\t\t//      }\n\t\t\t\t\t\t//\n\t\t\t\t\t\t//    std::sort( t.begin(), t.end() );\n\t\t\t\t\t\t//    int index = static_cast< int >( 0.8 * static_cast< float >( t.size() ) );\n\t\t\t\t\t\t//    std::cout << t[ index ] << std::endl;\n\t\t\t\t\t\t//    return;\n\n\t\t\t\t\t\tfor( int i = 0; i < rows; ++i )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// 1) determine k = number of edges to neighbors\n\t\t\t\t\t\t\tint k = 0;\n\t\t\t\t\t\t\tstd::vector< int> neighbors;\n\t\t\t\t\t\t\tfor( int j = 0; j < cols; ++j )\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif ( i == j )\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tif ( data( i, j ) < threshold )\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t++k;\n\t\t\t\t\t\t\t\tneighbors.push_back( j );\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// 2) determine connections among neighbors\n\t\t\t\t\t\t\tint connections = 0;\n\t\t\t\t\t\t\tstd::vector< int>::const_iterator end = neighbors.end();\n\t\t\t\t\t\t\tfor( std::vector< int>::const_iterator j = neighbors.begin(); j != end; ++j )\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tfor( std::vector< int>::const_iterator m = j; m != end; ++m )\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tif ( *j == *m || i == *j || *m == i )\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tif ( data( *j, *m ) < threshold )\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t++connections;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// k(k-1)*0.5 possible connections\n\t\t\t\t\t\t\tif ( k> 1 )\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tPixelType coefficient = static_cast< PixelType>( 2 * connections ) / static_cast< PixelType>( k * ( k - 1 ) );\n\t\t\t\t\t\t\t\tsum += coefficient;\n\t\t\t\t\t\t\t\t//        std::cout << i << \"\\t\" << coefficient << std::endl;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tPixelType average = sum / static_cast< PixelType>( rows );\n\n\t\t\t\t\t\tstd::cout << average << std::endl;\n\t\t\t\t\t}\n\t\t\t\t};\n\nint main( int argc, char ** argv )\n{\n\ttkd::CmdParser p( \"clustercoefficient\", \"Calculate voxel-wise cluster coefficients\" );\n\n\tstd::string inputFileName;\n\tfloat threshold;\n\tbool weightedGraph = false;\n\tbool stam = false;\n\n\tp.AddArgument( inputFileName, \"input\" ) ->AddAlias( \"i\" ) ->SetInput( \"filename\" ) ->SetDescription( \"Input 2D image: adjacency matrix\" ) ->SetRequired(\n\t\t\ttrue );\n\n\tp.AddArgument( threshold, \"threshold\" ) ->AddAlias( \"t\" ) ->SetInput( \"float\" ) ->SetDescription( \"Threshold\" ) ->SetRequired( true );\n\n\tp.AddArgument( weightedGraph, \"weighted\" ) ->AddAlias( \"w\" ) ->SetDescription( \"Calculated weighted cluster coefficients\" );\n\n\tp.AddArgument( stam, \"stam\" ) ->SetDescription(\n\t\t\t\"Calculated weighted cluster coefficients similar to Stam et al. in Brain 2009 (no threshold options!)\" );\n\n\tif ( !p.Parse( argc, argv ) )\n\t{\n\t\tp.PrintUsage( std::cout );\n\t\treturn -1;\n\t}\n\n\tClusterCoefficient cc;\n\n\tif ( stam )\n\t{\n\t\tcc.RunStam( inputFileName );\n\t\treturn 0;\n\t}\n\n\tif ( weightedGraph )\n\t{\n\t\tcc.RunWeighted( inputFileName, threshold );\n\t} else\n\t{\n\t\tcc.Run( inputFileName, threshold );\n\t}\n\n\treturn 0;\n}\n", "meta": {"hexsha": "2aa278d7ce084598bb9f15c87c3c0c1e418aba41", "size": 7852, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/graphs/clusteringcoefficient.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/graphs/clusteringcoefficient.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/graphs/clusteringcoefficient.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": 24.7697160883, "max_line_length": 153, "alphanum_fraction": 0.545084055, "num_tokens": 2514, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4774712902570752}}
{"text": "#ifndef STAN_MATH_PRIM_SCAL_PROB_EXP_MOD_NORMAL_LPDF_HPP\n#define STAN_MATH_PRIM_SCAL_PROB_EXP_MOD_NORMAL_LPDF_HPP\n\n#include <stan/math/prim/scal/meta/is_constant_struct.hpp>\n#include <stan/math/prim/scal/meta/partials_return_type.hpp>\n#include <stan/math/prim/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_finite.hpp>\n#include <stan/math/prim/scal/err/check_not_nan.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/erfc.hpp>\n#include <stan/math/prim/scal/fun/constants.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/value_of.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <cmath>\n\nnamespace stan {\nnamespace math {\n\ntemplate <bool propto, typename T_y, typename T_loc, typename T_scale,\n          typename T_inv_scale>\ntypename return_type<T_y, T_loc, T_scale, T_inv_scale>::type\nexp_mod_normal_lpdf(const T_y& y, const T_loc& mu, const T_scale& sigma,\n                    const T_inv_scale& lambda) {\n  static const char* function = \"exp_mod_normal_lpdf\";\n  typedef\n      typename stan::partials_return_type<T_y, T_loc, T_scale,\n                                          T_inv_scale>::type T_partials_return;\n\n  using std::log;\n\n  if (size_zero(y, mu, sigma, lambda))\n    return 0.0;\n\n  T_partials_return logp(0.0);\n\n  check_not_nan(function, \"Random variable\", y);\n  check_finite(function, \"Location parameter\", mu);\n  check_positive_finite(function, \"Inv_scale parameter\", lambda);\n  check_positive_finite(function, \"Scale parameter\", sigma);\n  check_consistent_sizes(function, \"Random variable\", y, \"Location parameter\",\n                         mu, \"Scale parameter\", sigma, \"Inv_scale paramter\",\n                         lambda);\n\n  if (!include_summand<propto, T_y, T_loc, T_scale, T_inv_scale>::value)\n    return 0.0;\n\n  using std::exp;\n  using std::log;\n  using std::sqrt;\n\n  operands_and_partials<T_y, T_loc, T_scale, T_inv_scale> ops_partials(\n      y, mu, sigma, lambda);\n\n  scalar_seq_view<T_y> y_vec(y);\n  scalar_seq_view<T_loc> mu_vec(mu);\n  scalar_seq_view<T_scale> sigma_vec(sigma);\n  scalar_seq_view<T_inv_scale> lambda_vec(lambda);\n  size_t N = max_size(y, mu, sigma, lambda);\n\n  for (size_t n = 0; n < N; n++) {\n    const T_partials_return y_dbl = value_of(y_vec[n]);\n    const T_partials_return mu_dbl = value_of(mu_vec[n]);\n    const T_partials_return sigma_dbl = value_of(sigma_vec[n]);\n    const T_partials_return lambda_dbl = value_of(lambda_vec[n]);\n\n    const T_partials_return pi_dbl = boost::math::constants::pi<double>();\n\n    if (include_summand<propto>::value)\n      logp -= log(2.0);\n    if (include_summand<propto, T_inv_scale>::value)\n      logp += log(lambda_dbl);\n    if (include_summand<propto, T_y, T_loc, T_scale, T_inv_scale>::value)\n      logp += lambda_dbl\n                  * (mu_dbl + 0.5 * lambda_dbl * sigma_dbl * sigma_dbl - y_dbl)\n              + log(erfc((mu_dbl + lambda_dbl * sigma_dbl * sigma_dbl - y_dbl)\n                         / (sqrt(2.0) * sigma_dbl)));\n\n    const T_partials_return deriv_logerfc\n        = -2.0 / sqrt(pi_dbl)\n          * exp(-(mu_dbl + lambda_dbl * sigma_dbl * sigma_dbl - y_dbl)\n                / (std::sqrt(2.0) * sigma_dbl)\n                * (mu_dbl + lambda_dbl * sigma_dbl * sigma_dbl - y_dbl)\n                / (sigma_dbl * std::sqrt(2.0)))\n          / erfc((mu_dbl + lambda_dbl * sigma_dbl * sigma_dbl - y_dbl)\n                 / (sigma_dbl * std::sqrt(2.0)));\n\n    if (!is_constant_struct<T_y>::value)\n      ops_partials.edge1_.partials_[n]\n          += -lambda_dbl + deriv_logerfc * -1.0 / (sigma_dbl * std::sqrt(2.0));\n    if (!is_constant_struct<T_loc>::value)\n      ops_partials.edge2_.partials_[n]\n          += lambda_dbl + deriv_logerfc / (sigma_dbl * std::sqrt(2.0));\n    if (!is_constant_struct<T_scale>::value)\n      ops_partials.edge3_.partials_[n]\n          += sigma_dbl * lambda_dbl * lambda_dbl\n             + deriv_logerfc\n                   * (-mu_dbl / (sigma_dbl * sigma_dbl * std::sqrt(2.0))\n                      + lambda_dbl / std::sqrt(2.0)\n                      + y_dbl / (sigma_dbl * sigma_dbl * std::sqrt(2.0)));\n    if (!is_constant_struct<T_inv_scale>::value)\n      ops_partials.edge4_.partials_[n]\n          += 1 / lambda_dbl + lambda_dbl * sigma_dbl * sigma_dbl + mu_dbl\n             - y_dbl + deriv_logerfc * sigma_dbl / std::sqrt(2.0);\n  }\n  return ops_partials.build(logp);\n}\n\ntemplate <typename T_y, typename T_loc, typename T_scale, typename T_inv_scale>\ninline typename return_type<T_y, T_loc, T_scale, T_inv_scale>::type\nexp_mod_normal_lpdf(const T_y& y, const T_loc& mu, const T_scale& sigma,\n                    const T_inv_scale& lambda) {\n  return exp_mod_normal_lpdf<false>(y, mu, sigma, lambda);\n}\n\n}  // namespace math\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "86f74b1efd1997bf3673f45be4ed03292e553f54", "size": 5032, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "venv/lib/python3.7/site-packages/pystan/stan/lib/stan_math/stan/math/prim/scal/prob/exp_mod_normal_lpdf.hpp", "max_stars_repo_name": "vchiapaikeo/prophet", "max_stars_repo_head_hexsha": "e8c250ca7bfffc280baa7dabc80a2c2d1f72c6a7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "venv/lib/python3.7/site-packages/pystan/stan/lib/stan_math/stan/math/prim/scal/prob/exp_mod_normal_lpdf.hpp", "max_issues_repo_name": "vchiapaikeo/prophet", "max_issues_repo_head_hexsha": "e8c250ca7bfffc280baa7dabc80a2c2d1f72c6a7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "venv/lib/python3.7/site-packages/pystan/stan/lib/stan_math/stan/math/prim/scal/prob/exp_mod_normal_lpdf.hpp", "max_forks_repo_name": "vchiapaikeo/prophet", "max_forks_repo_head_hexsha": "e8c250ca7bfffc280baa7dabc80a2c2d1f72c6a7", "max_forks_repo_licenses": ["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.9105691057, "max_line_length": 79, "alphanum_fraction": 0.6703100159, "num_tokens": 1415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.5926665999540697, "lm_q1q2_score": 0.47747129025707513}}
{"text": "#include <benchmark/benchmark.h>\n\n#include <tnt/core/core.hpp>\n#include <tnt/math/math.hpp>\n\n#include <opencv2/core.hpp>\n#include <benchmark/opencv_utils.hpp>\n\n#include <Eigen/Dense>\n\ntemplate <typename DataType>\nstatic void add_TNT(benchmark::State& state, int size)\n{\n    while (state.KeepRunning()) {\n        state.PauseTiming(); // We don't count tensor creation\n        tnt::Shape shape{size, size};\n\n        tnt::Tensor<DataType> left(shape, 1.f);\n        tnt::Tensor<DataType> right(shape, 2.f);\n\n        state.ResumeTiming();\n        tnt::add(left, right);\n    }\n}\n\ntemplate <typename DataType>\nstatic void add_OCV(benchmark::State& state, int size)\n{\n    while (state.KeepRunning()) {\n        state.PauseTiming();\n\n        cv::Mat left  = tnt::create_cv_mat<DataType>(size, size, cv::Scalar(1));\n        cv::Mat right = tnt::create_cv_mat<DataType>(size, size, cv::Scalar(2));\n\n        cv::Mat dst;\n\n        state.ResumeTiming();\n        cv::add(left, right, dst);\n    }\n}\n\ntemplate <typename DataType>\nstatic void add_EIG(benchmark::State& state, int size)\n{\n    using MatType = Eigen::Matrix<DataType, Eigen::Dynamic, Eigen::Dynamic>;\n\n    while (state.KeepRunning()) {\n        state.PauseTiming();\n\n        MatType left = MatType::Constant(size, size, 1);\n        MatType right = MatType::Constant(size, size, 2);\n\n        state.ResumeTiming();\n        MatType dst = left + right;\n    }\n}\n\n/*template <typename DataType>\nstatic void add_CUS(benchmark::State& state)\n{\n    while (state.KeepRunning()) {\n        state.PauseTiming();\n\n        cv::Mat left = create_cv_mat<DataType>(state.range(0), state.range(1), cv::Scalar(1));\n        cv::Mat right = create_cv_mat<DataType>(state.range(0), state.range(1), cv::Scalar(2));\n        cv::Mat dst(state.range(0), state.range(1), CV_32FC1);\n\n        const DataType* left_p = left.ptr<DataType>();\n        const DataType* right_p = right.ptr<DataType>();\n        DataType* dst_p = dst.ptr<DataType>();\n\n        int width = state.range(0);\n        int height = state.range(1);\n        int total = width * height;\n\n        state.ResumeTiming();\n        int x = 0;\n        for ( ; total--; x++)\n            dst_p[x] = left_p[x] + right_p[x];\n    }\n}*/\n\ntemplate <typename T>\nclass RegisterAddBenchmark\n{\npublic:\n    RegisterAddBenchmark(const std::string& type)\n    {\n        std::vector<int> sizes{4, 16, 64, 512, 2048};\n        for (int size : sizes) {\n            std::string suffix = type + \">[\" + std::to_string(size) + \"x\" + std::to_string(size) + \"]\";\n            benchmark::RegisterBenchmark((\"Add:TNT<\" + suffix).c_str(), add_TNT<T>, size);\n            benchmark::RegisterBenchmark((\"Add:OCV<\" + suffix).c_str(), add_OCV<T>, size);\n            benchmark::RegisterBenchmark((\"Add:EIG<\" + suffix).c_str(), add_EIG<T>, size);\n        }\n    }\n};\n\nstatic RegisterAddBenchmark<int> add_benchmark_int(\"int\");\nstatic RegisterAddBenchmark<float> add_benchmark_float(\"float\");\nstatic RegisterAddBenchmark<double> add_benchmark_double(\"double\");\n", "meta": {"hexsha": "a20e94354a2729fa3245812443f9fe0ab05b7cf3", "size": 2997, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "benchmark/src/math/add.cpp", "max_stars_repo_name": "JordanCheney/tnt", "max_stars_repo_head_hexsha": "a0fd378079d36b2bd39960c34e5c83f9633db0c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "benchmark/src/math/add.cpp", "max_issues_repo_name": "JordanCheney/tnt", "max_issues_repo_head_hexsha": "a0fd378079d36b2bd39960c34e5c83f9633db0c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-06-09T04:40:01.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-09T04:40:01.000Z", "max_forks_repo_path": "benchmark/src/math/add.cpp", "max_forks_repo_name": "JordanCheney/tnt", "max_forks_repo_head_hexsha": "a0fd378079d36b2bd39960c34e5c83f9633db0c0", "max_forks_repo_licenses": ["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.3823529412, "max_line_length": 103, "alphanum_fraction": 0.6216216216, "num_tokens": 773, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478255, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4774712847254631}}
{"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_SINHC_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_SINHC_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n\n    @ingroup group-hyperbolic\n    This function object returns the hyperbolic cardinal sine: \\f$\\sinh(x)/x\\f$.\n\n    @par Header <boost/simd/function/sinhc.hpp>\n\n    @see cosh, sinh\n\n    @par Example:\n\n      @snippet sinhc.cpp sinhc\n\n    @par Possible output:\n\n      @snippet sinhc.txt sinhc\n\n\n  **/\n  IEEEValue sinhc(IEEEValue const& x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/sinhc.hpp>\n#include <boost/simd/function/simd/sinhc.hpp>\n\n#endif\n", "meta": {"hexsha": "b67e3b2d5ff08f2e012a639e5c02573e54956bbd", "size": 1010, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/sinhc.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/sinhc.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/sinhc.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.4444444444, "max_line_length": 100, "alphanum_fraction": 0.5732673267, "num_tokens": 226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478255, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4774712847254631}}
{"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/testcase.h>\n#include <mitsuba/core/quad.h>\n#include <mitsuba/core/fstream.h>\n#include <mitsuba/core/plugin.h>\n#include <boost/bind.hpp>\n#include \"../bsdfs/rtrans.h\"\n\nMTS_NAMESPACE_BEGIN\n\nvoid transmittanceIntegrand(const BSDF *bsdf, const Vector &wi, size_t nPts, const Float *in, Float *out) {\n\tIntersection its;\n\n\tfor (size_t i=0; i<nPts; ++i) {\n\t\tBSDFSamplingRecord bRec(its, wi, Vector(), EImportance);\n\t\tbRec.typeMask = BSDF::ETransmission;\n\t\tout[i] = bsdf->sample(bRec, Point2(in[2*i], in[2*i+1]))[0];\n\t}\n}\n\nvoid diffTransmittanceIntegrand(Float *data, size_t resolution, size_t nPts, const Float *in, Float *out) {\n\tfor (size_t i=0; i<nPts; ++i)\n\t\tout[i] = 2 * in[i] * evalCubicInterp1D(in[i], data, resolution, 0, 1);\n}\n\nclass TestRoughTransmittance : public TestCase {\npublic:\n\tMTS_BEGIN_TESTCASE()\n\tMTS_DECLARE_TEST(test01_smoothTransmittance)\n\tMTS_DECLARE_TEST(test02_roughTransmittance)\n\tMTS_DECLARE_TEST(test03_roughTransmittanceFixedEta)\n\tMTS_DECLARE_TEST(test04_roughTransmittanceFixedEtaFixedAlpha)\n\tMTS_END_TESTCASE()\n\n\tFloat computeDiffuseTransmittance(const char *name, Float eta, Float alpha, size_t resolution = 100) {\n\t\tProperties bsdfProps(\"roughdielectric\");\n\t\tif (eta < 1) {\n\t\t\tbsdfProps.setFloat(\"intIOR\", 1.0f);\n\t\t\tbsdfProps.setFloat(\"extIOR\", 1.0f / eta);\n\t\t} else {\n\t\t\tbsdfProps.setFloat(\"extIOR\", 1.0f);\n\t\t\tbsdfProps.setFloat(\"intIOR\", eta);\n\t\t}\n\n\t\tbsdfProps.setFloat(\"alpha\", alpha);\n\t\tbsdfProps.setString(\"distribution\", name);\n\t\tref<BSDF> bsdf = static_cast<BSDF *>(\n\t\t\t\tPluginManager::getInstance()->createObject(bsdfProps));\n\n\t\tFloat *transmittances = new Float[resolution];\n\t\tFloat stepSize = 1.0f / (resolution-1);\n\t\tFloat error;\n\n\t\tNDIntegrator intTransmittance(1, 2, 50000, 0, 1e-6f);\n\t\tNDIntegrator intDiffTransmittance(1, 1, 50000, 0, 1e-6f);\n\n\t\tfor (size_t i=0; i<resolution; ++i) {\n\t\t\tFloat cosTheta = stepSize * i;\n\t\t\tVector wi(math::safe_sqrt(1-cosTheta*cosTheta), 0, cosTheta);\n\n\t\t\tFloat min[2] = {0, 0}, max[2] = {1, 1};\n\t\t\tintTransmittance.integrateVectorized(\n\t\t\t\tboost::bind(&transmittanceIntegrand, bsdf, wi, _1, _2, _3),\n\t\t\t\tmin, max, &transmittances[i], &error, NULL);\n\t\t}\n\n\t\tFloat Fdr;\n\t\tFloat min[1] = { 0 }, max[1] = { 1 };\n\t\tintDiffTransmittance.integrateVectorized(\n\t\t\tboost::bind(&diffTransmittanceIntegrand, transmittances, resolution, _1, _2, _3),\n\t\t\tmin, max, &Fdr, &error, NULL);\n\n\t\tdelete[] transmittances;\n\t\treturn Fdr;\n\t}\n\n\tFloat computeTransmittance(const char *name, Float eta, Float alpha, Float cosTheta) {\n\t\tProperties bsdfProps(\"roughdielectric\");\n\t\tif (cosTheta < 0) {\n\t\t\tcosTheta = -cosTheta;\n\t\t\teta = 1.0f / eta;\n\t\t}\n\t\tif (eta < 1) {\n\t\t\tbsdfProps.setFloat(\"intIOR\", 1.0f);\n\t\t\tbsdfProps.setFloat(\"extIOR\", 1.0f / eta);\n\t\t} else {\n\t\t\tbsdfProps.setFloat(\"extIOR\", 1.0f);\n\t\t\tbsdfProps.setFloat(\"intIOR\", eta);\n\t\t}\n\t\tbsdfProps.setFloat(\"alpha\", alpha);\n\t\tbsdfProps.setString(\"distribution\", name);\n\n\t\tref<BSDF> bsdf = static_cast<BSDF *>(\n\t\t\t\tPluginManager::getInstance()->createObject(bsdfProps));\n\n\t\tNDIntegrator intTransmittance(1, 2, 50000, 0, 1e-6f);\n\n\t\tVector wi(math::safe_sqrt(1-cosTheta*cosTheta), 0, cosTheta);\n\t\tFloat transmittance, error;\n\n\t\tFloat min[2] = {0, 0}, max[2] = {1, 1};\n\t\tintTransmittance.integrateVectorized(\n\t\t\tboost::bind(&transmittanceIntegrand, bsdf, wi, _1, _2, _3),\n\t\t\tmin, max, &transmittance, &error, NULL);\n\n\t\treturn transmittance;\n\t}\n\n\tvoid test01_smoothTransmittance() {\n\t\t/* Smooth diffuse transmittance - compare polynomial approximations to ground truth */\n\t\tfor (int i=0; i<=10; ++i) {\n\t\t\tFloat eta = 1 + i/10.0f;\n\n\t\t\tFloat f1 = fresnelDiffuseReflectance(eta, false);\n\t\t\tFloat f2 = fresnelDiffuseReflectance(eta, true);\n\t\t\tFloat f3 = fresnelDiffuseReflectance(1/eta, false);\n\t\t\tFloat f4 = fresnelDiffuseReflectance(1/eta, true);\n\n\t\t\tassertEqualsEpsilon(std::abs(f1-f2), (Float) 0, 1e-3f);\n\t\t\tassertEqualsEpsilon(std::abs(f3-f4), (Float) 0, 1e-3f);\n\t\t}\n\t}\n\n\tvoid test02_roughTransmittance() {\n\t\tRoughTransmittance rtr(MicrofacetDistribution::EBeckmann);\n\t\tref<Random> random = new Random();\n\n\t\tfor (int i=0; i<50; ++i) {\n\t\t\tFloat alpha = std::pow(random->nextFloat(), (Float) 4.0f)*4;\n\t\t\tFloat eta = 1 + std::pow(random->nextFloat(), (Float) 4.0f)*3;\n\t\t\tif (alpha < 1e-5)\n\t\t\t\talpha = 1e-5f;\n\t\t\tif (eta < 1+1e-5)\n\t\t\t\teta = 1+1e-5f;\n\t\t\t//eta = 1/eta;\n\n\t\t\tFloat refD = computeDiffuseTransmittance(\"beckmann\", eta, alpha);\n\t\t\tFloat datD = rtr.evalDiffuse(alpha, eta);\n\n\t\t\tcout << \"Testing \" << i << \"/50\" << endl;\n\t\t\tif (std::abs(refD-datD) > 1e-3f) {\n\t\t\t\tcout << endl;\n\t\t\t\tcout << \"eta = \" << eta << endl;\n\t\t\t\tcout << \"alpha = \" << alpha << endl;\n\t\t\t\tcout << \"diff=\" << datD-refD << \" (datD=\" << datD << \", ref=\" << refD << \")\" << endl;\n\t\t\t}\n\t\t}\n\n\t\tFloat avgErr = 0.0f;\n\t\tfor (int i=0; i<1000; ++i) {\n\t\t\tFloat cosTheta = random->nextFloat();\n\t\t\tFloat alpha = std::pow(random->nextFloat(), (Float) 4.0f)*4;\n\t\t\tFloat eta = 1 + std::pow(random->nextFloat(), (Float) 4.0f)*3;\n\t\t\tif (cosTheta < 1e-5)\n\t\t\t\tcosTheta = 1e-5f;\n\t\t\tif (alpha < 1e-5)\n\t\t\t\talpha = 1e-5f;\n\t\t\tif (eta < 1+1e-5)\n\t\t\t\teta = 1+1e-5f;\n\t\t\t//eta = 1/eta;\n\n\t\t\tFloat ref = computeTransmittance(\"beckmann\", eta, alpha, cosTheta);\n\t\t\tFloat dat = rtr.eval(cosTheta, alpha, eta);\n\n\t\t\tif (i % 20 == 0)\n\t\t\t\tcout << \"Testing \" << i << \"/1000\" << endl;\n\t\t\tif (std::abs(ref-dat) > 1e-3f) {\n\t\t\t\tcout << endl;\n\t\t\t\tcout << \"eta = \" << eta << endl;\n\t\t\t\tcout << \"alpha = \" << alpha << endl;\n\t\t\t\tcout << \"cosTheta = \" << cosTheta << endl;\n\t\t\t\tcout << \"diff=\" << dat-ref << \" (dat=\" << dat << \", ref=\" << ref << \")\" << endl;\n\t\t\t}\n\n\t\t\tavgErr += ref-dat;\n\t\t}\n\t\tavgErr /= 1000;\n\t\tcout << \"Avg error = \" << avgErr << endl;\n\t}\n\n\tvoid test03_roughTransmittanceFixedEta() {\n\t\tRoughTransmittance rtr(MicrofacetDistribution::EBeckmann);\n\n\t\tFloat eta = 1.5f;\n\t\trtr.setEta(eta);\n\n\t\tref<Random> random = new Random();\n\n\t\tfor (int i=0; i<50; ++i) {\n\t\t\tFloat alpha = std::pow(random->nextFloat(), (Float) 4.0f)*4;\n\t\t\tif (alpha < 1e-5)\n\t\t\t\talpha = 1e-5f;\n\n\t\t\tFloat refD = computeDiffuseTransmittance(\"beckmann\", eta, alpha);\n\t\t\tFloat datD = rtr.evalDiffuse(alpha, eta);\n\n\t\t\tcout << \"Testing \" << i << \"/50\" << endl;\n\t\t\tif (std::abs(refD-datD) > 1e-3f) {\n\t\t\t\tcout << endl;\n\t\t\t\tcout << \"alpha = \" << alpha << endl;\n\t\t\t\tcout << \"diff=\" << datD-refD << \" (datD=\" << datD << \", ref=\" << refD << \")\" << endl;\n\t\t\t}\n\t\t}\n\n\t\tFloat avgErr = 0.0f;\n\t\tfor (int i=0; i<1000; ++i) {\n\t\t\tFloat cosTheta = random->nextFloat();\n\t\t\tFloat alpha = std::pow(random->nextFloat(), (Float) 4.0f)*4;\n\t\t\tif (cosTheta < 1e-5)\n\t\t\t\tcosTheta = 1e-5f;\n\t\t\tif (alpha < 1e-5)\n\t\t\t\talpha = 1e-5f;\n\n\t\t\tFloat ref = computeTransmittance(\"beckmann\", eta, alpha, cosTheta);\n\t\t\tFloat dat = rtr.eval(cosTheta, alpha, eta);\n\n\t\t\tif (i % 20 == 0)\n\t\t\t\tcout << \"Testing \" << i << \"/1000\" << endl;\n\t\t\tif (std::abs(ref-dat) > 1e-3f) {\n\t\t\t\tcout << endl;\n\t\t\t\tcout << \"eta = \" << eta << endl;\n\t\t\t\tcout << \"alpha = \" << alpha << endl;\n\t\t\t\tcout << \"cosTheta = \" << cosTheta << endl;\n\t\t\t\tcout << \"diff=\" << dat-ref << \" (dat=\" << dat << \", ref=\" << ref << \")\" << endl;\n\t\t\t}\n\n\t\t\tavgErr += ref-dat;\n\t\t}\n\t\tavgErr /= 1000;\n\t\tcout << \"Avg error = \" << avgErr << endl;\n\t}\n\n\tvoid test04_roughTransmittanceFixedEtaFixedAlpha() {\n\t\tref<Timer> timer = new Timer();\n\t\tRoughTransmittance rtr(MicrofacetDistribution::EBeckmann);\n\t\tFloat eta = 1.5f;\n\t\tFloat alpha = 0.2f;\n\t\trtr.setEta(eta);\n\t\trtr.setAlpha(alpha);\n\t\tcout << \"Loading and projecting took \" << timer->getMilliseconds() << \" ms\" << endl;\n\n\t\tref<Random> random = new Random();\n\n\t\tFloat refD = computeDiffuseTransmittance(\"beckmann\", eta, alpha);\n\t\tFloat datD = rtr.evalDiffuse(alpha, eta);\n\n\t\tif (std::abs(refD-datD) > 1e-3f) {\n\t\t\tcout << endl;\n\t\t\tcout << \"alpha = \" << alpha << endl;\n\t\t\tcout << \"diff=\" << datD-refD << \" (datD=\" << datD << \", ref=\" << refD << \")\" << endl;\n\t\t}\n\n\t\tFloat avgErr = 0.0f;\n\t\tfor (int i=0; i<1000; ++i) {\n\t\t\tFloat cosTheta = random->nextFloat();\n\t\t\tif (cosTheta < 1e-5)\n\t\t\t\tcosTheta = 1e-5f;\n\n\t\t\tFloat ref = computeTransmittance(\"beckmann\", eta, alpha, cosTheta);\n\t\t\tFloat dat = rtr.eval(cosTheta, alpha, eta);\n\n\t\t\tif (i % 20 == 0)\n\t\t\t\tcout << \"Testing \" << i << \"/1000\" << endl;\n\t\t\tif (std::abs(ref-dat) > 1e-3f) {\n\t\t\t\tcout << endl;\n\t\t\t\tcout << \"eta = \" << eta << endl;\n\t\t\t\tcout << \"alpha = \" << alpha << endl;\n\t\t\t\tcout << \"cosTheta = \" << cosTheta << endl;\n\t\t\t\tcout << \"diff=\" << dat-ref << \" (dat=\" << dat << \", ref=\" << ref << \")\" << endl;\n\t\t\t}\n\n\t\t\tavgErr += ref-dat;\n\t\t}\n\t\tavgErr /= 1000;\n\t\tcout << \"Avg error = \" << avgErr << endl;\n\t}\n};\n\nMTS_EXPORT_TESTCASE(TestRoughTransmittance, \"Testcase for rough transmittance computations\")\nMTS_NAMESPACE_END\n", "meta": {"hexsha": "e9889b93d3e522b4dc158b439c008e8836f233d4", "size": 9242, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mitsuba-af602c6fd98a/src/tests/test_rtrans.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/tests/test_rtrans.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/tests/test_rtrans.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": 31.0134228188, "max_line_length": 107, "alphanum_fraction": 0.6273533867, "num_tokens": 3199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056295505783, "lm_q2_score": 0.6926419958239132, "lm_q1q2_score": 0.4774420269845715}}
{"text": "// preprocesses the edge list to ensure that it's rehashed and weighted using Jaccard coefficient\n// the rehashed weighted edgelist and the inverse maps are stored in the same directory\n\n#include <iostream>\n#include <fstream>\n#include <unordered_map>\n#include <unordered_set>\n#include <boost/graph/adjacency_list.hpp>\n\nusing namespace std;\nusing namespace boost;\n\n\ntypedef adjacency_list< listS,vecS, undirectedS > Graph;\ntypedef graph_traits < Graph> :: vertex_descriptor vertex_descriptor;\ntypedef graph_traits < Graph> :: edge_descriptor edge_descriptor;\ntypedef Graph :: vertex_iterator vertex_iterator;\ntypedef Graph :: edge_iterator edge_iterator;\ntypedef std::pair <int ,int> Edge;\ntypedef graph_traits < Graph> :: adjacency_iterator my_adjacency_iterator;\n\n\nvoid print_set(std::unordered_set<int> uset)\n{\n\tcout << endl;\n\tfor (auto item: uset)\n\t\tcout << item << \" \";\n\tcout << endl;\n}\n\nstd::unordered_set<int> union_(std::unordered_set<int> uset1, std::unordered_set<int> uset2)\n{\n\tstd::unordered_set<int> new_uset;\n\tif (uset1.size() > uset2.size())\n\t{\n\t\tnew_uset = uset1;\n\t\tfor (auto thing: uset2)\n\t\t\tnew_uset.insert(thing);\n\t}\n\t\n\telse\n\t{\n\t\tnew_uset = uset2;\n\t\tfor (auto thing: uset1)\n\t\t\tnew_uset.insert(thing);\n\t}\n\n\treturn new_uset;\n}\n\nstd::unordered_set<int> intersection(std::unordered_set<int> uset1, std::unordered_set<int> uset2)\n{\n\tstd::unordered_set<int> new_uset;\n\n\tif (uset1.size() > uset2.size())\n\t{\n\t\tfor (auto node: uset2)\n\t\t{\n\t\t\tif (uset1.find(node) != uset1.end())\n\t\t\t\tnew_uset.insert(node);\n\t\t}\n\t}\n\t\n\telse\n\t{\n\t\tfor (auto node: uset1)\n\t\t{\n\t\t\tif (uset2.find(node) != uset2.end())\n\t\t\t\tnew_uset.insert(node);\n\t\t}\n\t}\n\t\t\n\treturn new_uset;\n}\n\n\nvoid preprocesses(string input_filename)\n{\n\t// rehashes the edge list at input_filename \n\tGraph G;\n\tmy_adjacency_iterator start, end;\n\tedge_iterator e_start, e_end;\n\tedge_descriptor e;\n\tstd::unordered_map<int,int> ordered_labels;\n\tint u, v;\n\tint count = 0;\n\tfloat w;\n\n\tifstream fin(input_filename);\n\t\n\n\twhile (fin >> u >> v)\n\t{\n\t\tadd_edge(u, v, G);\n\n\t\tif (ordered_labels.find(u) == ordered_labels.end())\n\t\t{\n\t\t\tordered_labels[u] = count;\n\t\t\tcount += 1;\n\t\t}\n\n\t\tif (ordered_labels.find(v) == ordered_labels.end())\n\t\t{\n\t\t\tordered_labels[v] = count;\n\t\t\tcount += 1;\n\t\t}\n\t}\n\tfin.close();\n\n\tstring out_filename1 = \"rehashed_weighted_\" + input_filename;\n\tstring out_filename2 = \"rehashed_\" + input_filename;\n\n\tofstream fout1;\n\tfout1.open(out_filename1);\n\tofstream fout2;\n\tfout2.open(out_filename2);\n\n\tfor (tie(e_start, e_end) = edges(G); e_start != e_end; ++ e_start)\n\t{\n\t\tstd::unordered_set<int> u_neighbors, v_neighbors;\n\t\te = *e_start;\n\t\tu = source(e, G);\n\t\tv = target(e, G);\n\t\t\n\t\tfor (tie(start, end) = adjacent_vertices(u, G); start != end; ++ start)\n\t\t{\n\t\t\tint neighbor = *start;\n\t\t\tu_neighbors.insert(neighbor); \n\t\t}\n\t\t\n\t\tfor (tie(start, end) = adjacent_vertices(v, G); start != end; ++ start)\n\t\t{\n\t\t\tint neighbor = *start;\n\t\t\tv_neighbors.insert(neighbor); \n\t\t}\n\n\n\t\tfloat num = intersection(u_neighbors, v_neighbors).size();\n\t\tfloat denom = union_(u_neighbors, v_neighbors).size() - 2;\n\n\t\tif (denom == 0)\n\t\t\tw = 0;\n\t\telse\n\t\t\tw = num / denom;\n\n\t\tfout1 << ordered_labels[u] << \" \" << ordered_labels[v] << \" \" << w << endl;\n\t\tfout2 << ordered_labels[u] << \" \" << ordered_labels[v] << endl;\n\t}\n\tfout1.close();\n\tfout2.close();\n\n\tcout << \"\\nWeighted edgelist is at \" << out_filename1 << endl;\n\tcout << \"\\nRehashed unweighted edgelist is at \" << out_filename2 << endl;\n\t\n\n\tout_filename2 = input_filename + \"_inv_maps\";\n\tfout2.open(out_filename2);\n\n\tfor (auto item: ordered_labels)\n\t\tfout2 << item.first << \" \" << item.second << endl;\n\n\tfout2.close();\n\tcout << \"\\nThe inverse mapping is at \" << out_filename2 << endl;\n}\n\nint main(int argc, char const *argv[])\n{\n\tif (argc < 2)\n\t{\n\t\tcout << \"\\nEnter filename of the unweighted edge list to preprocesses\\n\";\n\t\treturn 0;\n\t}\n\n\tpreprocesses(argv[1]);\n\treturn 0;\n}", "meta": {"hexsha": "f926e938414eb6dd2f5244502cf7948e1359b4d6", "size": 3859, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pre_process.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": "pre_process.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": "pre_process.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": 21.9261363636, "max_line_length": 98, "alphanum_fraction": 0.675304483, "num_tokens": 1104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.6893056295505784, "lm_q1q2_score": 0.4774420182378504}}
{"text": "/*    This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.\n *    See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.\n *    Author(s):       Vincent Rouvreau\n *\n *    Copyright (C) 2015 Inria\n *\n *    Modification(s):\n *      - YYYY/MM Author: Description of the modification\n */\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE \"alpha_complex_3d\"\n#include <boost/test/unit_test.hpp>\n#include <boost/mpl/list.hpp>\n\n#include <cmath>  // float comparison\n#include <limits>\n#include <string>\n#include <vector>\n#include <random>\n#include <cstddef>  // for std::size_t\n\n#include <gudhi/Alpha_complex_3d.h>\n#include <gudhi/graph_simplicial_complex.h>\n#include <gudhi/Simplex_tree.h>\n#include <gudhi/Unitary_tests_utils.h>\n// to construct Alpha_complex from a OFF file of points\n#include <gudhi/Points_3D_off_io.h>\n\n#include <CGAL/Random.h>\n#include <CGAL/point_generators_3.h>\n\nusing Fast_weighted_alpha_complex_3d =\n    Gudhi::alpha_complex::Alpha_complex_3d<Gudhi::alpha_complex::complexity::FAST, true, false>;\nusing Safe_weighted_alpha_complex_3d =\n    Gudhi::alpha_complex::Alpha_complex_3d<Gudhi::alpha_complex::complexity::SAFE, true, false>;\nusing Exact_weighted_alpha_complex_3d =\n    Gudhi::alpha_complex::Alpha_complex_3d<Gudhi::alpha_complex::complexity::EXACT, true, false>;\n\ntypedef boost::mpl::list<Fast_weighted_alpha_complex_3d, Safe_weighted_alpha_complex_3d,\n                         Exact_weighted_alpha_complex_3d>\n    weighted_variants_type_list;\n\n#ifdef GUDHI_DEBUG\nBOOST_AUTO_TEST_CASE_TEMPLATE(Alpha_complex_weighted_throw, Weighted_alpha_complex_3d, weighted_variants_type_list) {\n  using Point_3 = typename Weighted_alpha_complex_3d::Point_3;\n  std::vector<Point_3> w_points;\n  w_points.push_back(Point_3(0.0, 0.0, 0.0));\n  w_points.push_back(Point_3(0.0, 0.0, 0.2));\n  w_points.push_back(Point_3(0.2, 0.0, 0.2));\n  // w_points.push_back(Point_3(0.6, 0.6, 0.0));\n  // w_points.push_back(Point_3(0.8, 0.8, 0.2));\n  // w_points.push_back(Point_3(0.2, 0.8, 0.6));\n\n  // weights size is different from w_points size to make weighted Alpha_complex_3d throw in debug mode\n  std::vector<double> weights = {0.01, 0.005, 0.006, 0.01, 0.009, 0.001};\n\n  std::cout << \"Check exception throw in debug mode\" << std::endl;\n  BOOST_CHECK_THROW(Weighted_alpha_complex_3d wac(w_points, weights), std::invalid_argument);\n}\n#endif\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(Alpha_complex_weighted, Weighted_alpha_complex_3d, weighted_variants_type_list) {\n  std::cout << \"Weighted alpha complex 3d from points and weights\" << std::endl;\n  using Point_3 = typename Weighted_alpha_complex_3d::Point_3;\n  std::vector<Point_3> w_points;\n  w_points.push_back(Point_3(0.0, 0.0, 0.0));\n  w_points.push_back(Point_3(0.0, 0.0, 0.2));\n  w_points.push_back(Point_3(0.2, 0.0, 0.2));\n  w_points.push_back(Point_3(0.6, 0.6, 0.0));\n  w_points.push_back(Point_3(0.8, 0.8, 0.2));\n  w_points.push_back(Point_3(0.2, 0.8, 0.6));\n\n  // weights size is different from w_points size to make weighted Alpha_complex_3d throw in debug mode\n  std::vector<double> weights = {0.01, 0.005, 0.006, 0.01, 0.009, 0.001};\n\n  Weighted_alpha_complex_3d alpha_complex_p_a_w(w_points, weights);\n  Gudhi::Simplex_tree<> stree;\n  alpha_complex_p_a_w.create_complex(stree);\n\n  std::cout << \"Weighted alpha complex 3d from weighted points\" << std::endl;\n  using Weighted_point_3 = typename Weighted_alpha_complex_3d::Weighted_point_3;\n\n  std::vector<Weighted_point_3> weighted_points;\n\n  for (std::size_t i = 0; i < w_points.size(); i++) {\n    weighted_points.push_back(Weighted_point_3(w_points[i], weights[i]));\n  }\n  Weighted_alpha_complex_3d alpha_complex_w_p(weighted_points);\n\n  Gudhi::Simplex_tree<> stree_bis;\n  alpha_complex_w_p.create_complex(stree_bis);\n\n  // ---------------------\n  // Compare both versions\n  // ---------------------\n  std::cout << \"Weighted alpha complex 3d is of dimension \" << stree_bis.dimension() << \" - versus \"\n            << stree.dimension() << std::endl;\n  BOOST_CHECK(stree_bis.dimension() == stree.dimension());\n  std::cout << \"Weighted alpha complex 3d num_simplices \" << stree_bis.num_simplices() << \" - versus \"\n            << stree.num_simplices() << std::endl;\n  BOOST_CHECK(stree_bis.num_simplices() == stree.num_simplices());\n  std::cout << \"Weighted alpha complex 3d num_vertices \" << stree_bis.num_vertices() << \" - versus \"\n            << stree.num_vertices() << std::endl;\n  BOOST_CHECK(stree_bis.num_vertices() == stree.num_vertices());\n\n  auto sh = stree.filtration_simplex_range().begin();\n  while (sh != stree.filtration_simplex_range().end()) {\n    std::vector<int> simplex;\n    std::vector<int> exact_simplex;\n#ifdef DEBUG_TRACES\n    std::cout << \" ( \";\n#endif\n    for (auto vertex : stree.simplex_vertex_range(*sh)) {\n      simplex.push_back(vertex);\n#ifdef DEBUG_TRACES\n      std::cout << vertex << \" \";\n#endif\n    }\n#ifdef DEBUG_TRACES\n    std::cout << \") -> \"\n              << \"[\" << stree.filtration(*sh) << \"] \";\n    std::cout << std::endl;\n#endif\n\n    // Find it in the exact structure\n    auto sh_exact = stree_bis.find(simplex);\n    BOOST_CHECK(sh_exact != stree_bis.null_simplex());\n\n    // Exact and non-exact version is not exactly the same due to float comparison\n    GUDHI_TEST_FLOAT_EQUALITY_CHECK(stree_bis.filtration(sh_exact), stree.filtration(*sh));\n\n    ++sh;\n  }\n}\n", "meta": {"hexsha": "44deb930b8920d1aa85e7b9873b43c5d92633228", "size": 5374, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Alpha_complex/test/Weighted_alpha_complex_3d_unit_test.cpp", "max_stars_repo_name": "jmarino/gudhi-devel", "max_stars_repo_head_hexsha": "b1824e4de6fd1d037af3c1341c3065731472ffc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-01-27T03:32:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-14T21:14:14.000Z", "max_issues_repo_path": "src/Alpha_complex/test/Weighted_alpha_complex_3d_unit_test.cpp", "max_issues_repo_name": "jmarino/gudhi-devel", "max_issues_repo_head_hexsha": "b1824e4de6fd1d037af3c1341c3065731472ffc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-08-25T16:03:23.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-28T07:36:21.000Z", "max_forks_repo_path": "src/Alpha_complex/test/Weighted_alpha_complex_3d_unit_test.cpp", "max_forks_repo_name": "jmarino/gudhi-devel", "max_forks_repo_head_hexsha": "b1824e4de6fd1d037af3c1341c3065731472ffc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-11-06T12:36:23.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-25T14:53:13.000Z", "avg_line_length": 39.5147058824, "max_line_length": 117, "alphanum_fraction": 0.7100855973, "num_tokens": 1619, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056040203135, "lm_q2_score": 0.6926419704455589, "lm_q1q2_score": 0.47744199180779606}}
{"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\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include <iostream>\n#include <cmath>\n#include <complex>\n\n\n#include <boost/numeric/mtl/mtl.hpp>\n\n\ntemplate <typename T>\ninline void check(const T& result, double exp)\n{\n    MTL_THROW_IF(std::abs(result - exp) > 0.0001, mtl::runtime_error(\"dot product wrong\"));\n}\n\n\ntemplate <typename VectorU, typename VectorV>\nvoid test(VectorU& u, VectorV& v, const char* name)\n{\n    //using mtl::dot;\n    typedef typename mtl::Collection<VectorU>::size_type  size_type;\n    for (size_type i= 0; i < size(v); i++)\n\tu[i]= i+1, v[i]= i+1;\n\n    \n    mtl::io::tout << name << \"\\n dot(u, v) = \" << dot(u, v) << \"\\n\"; mtl::io::tout.flush();\n    check(dot(u, v), 285.0);\n\n    mtl::io::tout << \" dot<2>(u, v) = \" << mtl::dot<2>(u, v) << \"\\n\"; mtl::io::tout.flush();\n    check(mtl::dot<2>(u, v), 285.0);\n\n    mtl::io::tout << \" dot<6>(u, v) = \" << mtl::dot<6>(u, v) << \"\\n\"; mtl::io::tout.flush();\n    check(mtl::dot<6>(u, v), 285.0);\n}\n \n\nint main(int ,char**)\n{\n    using mtl::vec::parameters;\n    const int size= 9;\n\n    mtl::dense_vector<float>   u(size), v(size), w(size);\n    mtl::dense_vector<double>  x(size), y(size), z(size);\n    mtl::dense_vector<std::complex<double> >  xc(size), yc(size), zc(size);\n\n    mtl::io::tout << \"Testing vector operations\\n\";\n\n    test(u, v, \"test float\");\n    test(x, y, \"test double\");\n    test(u, x, \"test float, double mixed\");\n    test(xc, yc, \"test complex<double>\");\n    test(x, yc, \"test complex<double>, double mixed\");\n\n    mtl::dense_vector<float, parameters<mtl::row_major> >   ur(size), vr(size), wr(size);\n    test(ur, vr, \"test float in row vector\");\n    \n    // test(ur, v, wr, \"test float in mixed vector (shouldn't work)\"); \n\n    return 0;\n}\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "c55b7fc5a68ebedb14066bfe9da4d348ce15c7d9", "size": 2134, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/dot_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/dot_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/dot_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": 24.5287356322, "max_line_length": 94, "alphanum_fraction": 0.6035613871, "num_tokens": 667, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056040203135, "lm_q2_score": 0.6926419704455588, "lm_q1q2_score": 0.477441991807796}}
{"text": "#include \"gtest/gtest.h\"\n\n#include <vector>\n#include <iostream>\n#include <doublefann.h>\n#include <fann_train.h>\n#include <fann.h>\n#include <boost/filesystem.hpp>\n\n#include \"MLP.hpp\"\n#include <bib/Utils.hpp>\n#include <bib/MetropolisHasting.hpp>\n#include <bib/Combinaison.hpp>\n\n#define NB_SOL_OPTIMIZATION 25\n\ndouble OR(double x1, double x2) {\n  if (x1 == 1.f || x2 == 1.f)\n    return 1.f;\n  return -1.f;\n}\n\ndouble AND(double x1, double x2) {\n  if (x1 == 1.f && x2 == 1.f)\n    return 1.f;\n  return -1.f;\n}\n\ndouble LECUNIZATION(double x){ \n  if(x == 1.f) \n    return 1.5f;\n  else\n    return -1.5f;\n}\n\ndouble sech(double x) {\n  return 2. / (exp(x) + exp(-x));\n}\n\nTEST(MLP, ConsistentActivationFunction) {\n  MLP nn(1, {1}, 0, 0.01f);\n\n  fann_set_weight(nn.getNeuralNet(), 0, 2, 1.f);\n  fann_set_weight(nn.getNeuralNet(), 1, 2, 0.f);\n  fann_set_weight(nn.getNeuralNet(), 2, 4, 1.f);\n  fann_set_weight(nn.getNeuralNet(), 3, 4, 0.f);\n\n  std::vector<double> sens(0);\n  std::vector<double> ac(1);\n  ac[0] = 1;\n\n  double lambda = 0.5;\n  fann_set_activation_steepness_output(nn.getNeuralNet(), lambda);\n  fann_set_activation_steepness(nn.getNeuralNet(), lambda, 1, 0);\n  EXPECT_DOUBLE_EQ(nn.computeOutVF(sens, ac), tanh(lambda * 1.) / 2.);\n\n  lambda = 0.8;\n  fann_set_activation_steepness(nn.getNeuralNet(), lambda, 1, 0);\n  EXPECT_DOUBLE_EQ(nn.computeOutVF(sens, ac), tanh(lambda * 1.) / 2.);\n\n  ac[0] = -1;\n  EXPECT_DOUBLE_EQ(nn.computeOutVF(sens, ac), tanh(lambda * -1.) / 2.);\n\n  lambda = 0.5;\n  fann_set_activation_steepness(nn.getNeuralNet(), lambda, 1, 0);\n  EXPECT_DOUBLE_EQ(nn.computeOutVF(sens, ac), tanh(lambda * -1.) / 2.);\n\n  fann_set_weight(nn.getNeuralNet(), 0, 2, 0.f);\n  fann_set_weight(nn.getNeuralNet(), 1, 2, 0.f);\n  fann_set_weight(nn.getNeuralNet(), 2, 4, 0.f);\n  fann_set_weight(nn.getNeuralNet(), 3, 4, 5.f);\n\n  EXPECT_DOUBLE_EQ(nn.computeOutVF(sens, ac), 5.f / 2.f);\n\n  fann_set_weight(nn.getNeuralNet(), 0, 2, 0.2f);\n  fann_set_weight(nn.getNeuralNet(), 1, 2, 0.4f);\n  fann_set_weight(nn.getNeuralNet(), 2, 4, 0.6f);\n  fann_set_weight(nn.getNeuralNet(), 3, 4, 0.8f);\n\n  EXPECT_DOUBLE_EQ(nn.computeOutVF(sens, ac), (tanh(lambda * (-1. * 0.2f + 0.4f)) * 0.6f + 0.8f) / 2.f);\n\n  fann_set_activation_steepness_output(nn.getNeuralNet(), 1.f);\n  EXPECT_DOUBLE_EQ(nn.computeOutVF(sens, ac),  tanh(lambda * (-1. * 0.2f + 0.4f)) * 0.6f + 0.8f);\n}\n\n\nTEST(MLP, LearnOpposite) {\n  MLP nn(1, {1}, 0, 0.5f);\n\n  fann_set_weight(nn.getNeuralNet(), 0, 2, -1.f);\n  fann_set_weight(nn.getNeuralNet(), 1, 2, 0.f);\n\n  fann_set_weight(nn.getNeuralNet(), 2, 4, 1. / tanh(0.5 * 1.));\n  fann_set_weight(nn.getNeuralNet(), 3, 4, 0.f);\n\n  // Test\n  for (uint n = 0; n < 100 ; n++) {\n    double x1 = bib::Utils::randBool() ? 1.f : -1.f;\n\n    double out = x1 == 1.f ? -1.f : 1.f;\n\n    std::vector<double> sens(0);\n    std::vector<double> ac(1);\n    ac[0] = x1;\n\n    EXPECT_DOUBLE_EQ(nn.computeOutVF(sens, ac), out);\n  }\n\n  // Learn\n  for (uint n = 0; n < 1000 ; n++) {\n    double x1 = bib::Utils::randBool() ? 1.f : -1.f;\n\n    double out = x1 == 1.f ? -1.f : 1.f;\n\n    std::vector<double> sens(0);\n    std::vector<double> ac(1);\n    ac[0] = x1;\n\n    nn.learn(sens, ac, out);\n  }\n\n  // Test\n  for (uint n = 0; n < 100 ; n++) {\n    double x1 = bib::Utils::randBool() ? 1.f : -1.f;\n\n    double out = x1 == 1.f ? -1.f : 1.f;\n\n    std::vector<double> sens(0);\n    std::vector<double> ac(1);\n    ac[0] = x1;\n\n    EXPECT_EQ(nn.computeOutVF(sens, ac), out);\n  }\n}\n\n\nTEST(MLP, LearnAndOr) {\n  MLP nn(3, {10}, 2, 0.5f);\n\n  // Learn\n  for (uint n = 0; n < 10000 ; n++) {\n    double x1 = bib::Utils::randBool() ? 1.f : -1.f;\n    double x2 = bib::Utils::randBool() ? 1.f : -1.f;\n    double x3 = bib::Utils::randBool() ? 1.f : -1.f;\n\n    double out = AND(OR(x1, x2), x3);\n\n    std::vector<double> sens(2);\n    sens[0] = x1;\n    sens[1] = x2;\n    std::vector<double> ac(1);\n    ac[0] = x3;\n\n    nn.learn(sens, ac, out);\n  }\n\n  // Test\n  for (uint n = 0; n < 100 ; n++) {\n    double x1 = bib::Utils::randBool() ? 1.f : -1.f;\n    double x2 = bib::Utils::randBool() ? 1.f : -1.f;\n    double x3 = bib::Utils::randBool() ? 1.f : -1.f;\n\n    double out = AND(OR(x1, x2), x3);\n\n    std::vector<double> sens(2);\n    sens[0] = x1;\n    sens[1] = x2;\n    std::vector<double> ac(1);\n    ac[0] = x3;\n\n    EXPECT_GT(nn.computeOutVF(sens, ac), out - 0.02);\n    EXPECT_LT(nn.computeOutVF(sens, ac), out + 0.02);\n  }\n}\n\n#ifndef NO_OPTPP\nTEST(MLP, MLPCheckOuput) {\n  MLP nn(1, {1}, 2, 0.5f);\n  std::vector<double> sens(0);\n\n  fann_set_weight(nn.getNeuralNet(), 0, 2, 1.f);\n  fann_set_weight(nn.getNeuralNet(), 1, 2, 0.f);\n  fann_set_weight(nn.getNeuralNet(), 2, 4, 1.f);\n  fann_set_weight(nn.getNeuralNet(), 3, 4, 0.f);\n\n  uint ndim = 1;\n  passdata d = {nn.getNeuralNet(), sens};\n  ColumnVector ac(ndim);\n  ac(1) = -1.f;\n  double fx = -1;\n  int result = 0;\n  ColumnVector gx(ndim);\n  SymmetricMatrix Hx(ndim);\n  hs65(NLPFunction, ndim, ac, fx, gx, Hx, result, &d);\n\n  EXPECT_DOUBLE_EQ(fx, tanh(0.5 * 1.));\n\n  fann_set_weight(nn.getNeuralNet(), 0, 2, 0.2f);\n  fann_set_weight(nn.getNeuralNet(), 1, 2, 0.4f);\n  fann_set_weight(nn.getNeuralNet(), 2, 4, 0.6f);\n  fann_set_weight(nn.getNeuralNet(), 3, 4, 0.8f);\n\n  hs65(NLPFunction, ndim, ac, fx, gx, Hx, result, &d);\n\n  EXPECT_DOUBLE_EQ(-fx, tanh(0.5 * (-1. * 0.2f + 0.4f)) * 0.6f + 0.8f);\n}\n\nTEST(MLP, MLPCheckDerivative) {\n  MLP nn(1, {1}, 2, 0.5f);\n  std::vector<double> sens(0);\n\n  fann_set_weight(nn.getNeuralNet(), 0, 2, 1.f);\n  fann_set_weight(nn.getNeuralNet(), 1, 2, 0.f);\n  fann_set_weight(nn.getNeuralNet(), 2, 4, 1.f);\n  fann_set_weight(nn.getNeuralNet(), 3, 4, 0.f);\n\n  uint ndim = 1;\n  passdata d = {nn.getNeuralNet(), sens};\n  ColumnVector ac(ndim);\n  double a = -1;\n  ac(1) = a;\n  double fx = -1;\n  int result = 0;\n\n  ColumnVector gx(ndim);\n\n  SymmetricMatrix Hx(ndim);\n\n  double h = 1e-10;\n  ac(1) = a - h;\n  hs65(NLPFunction, ndim, ac, fx, gx, Hx, result, &d);\n  double fx_base = fx;\n  ac(1) = a + h;\n  hs65(NLPFunction, ndim, ac, fx, gx, Hx, result, &d);\n  double fx_h = fx;\n  double derivative1 = (fx_h - fx_base) / (2.0 * h);\n\n  ac(1) = a;\n  hs65(NLPFunction, ndim, ac, fx, gx, Hx, result, &d);\n  double derivative2 = (fx_h - fx) / h;\n\n  hs65(NLPGradient, ndim, ac, fx, gx, Hx, result, &d);\n\n  EXPECT_GT(derivative1, gx(1) - 1e-5);\n  EXPECT_LT(derivative1, gx(1) + 1e-5);\n\n  EXPECT_GT(derivative2, gx(1) - 1e-5);\n  EXPECT_LT(derivative2, gx(1) + 1e-5);\n}\n\nTEST(MLP, MLPCheckAnalyticscFuncDerHess) {\n  MLP nn(1, {1}, 0, 0.5f);\n\n  fann_set_weight(nn.getNeuralNet(), 0, 2, -1.f);\n  fann_set_weight(nn.getNeuralNet(), 1, 2, 0.f);\n\n  fann_set_weight(nn.getNeuralNet(), 2, 4, 1. / tanh(0.5 * 1.));\n  fann_set_weight(nn.getNeuralNet(), 3, 4, 0.f);\n\n  uint ndim = 1;\n  std::vector<double> sens(0);\n  passdata d = {nn.getNeuralNet(), sens};\n  ColumnVector ac(ndim);\n  double a = -1;\n  ac(1) = a;\n  double fx = -1;\n  int result = 0;\n  ColumnVector gx(ndim);\n\n  SymmetricMatrix Hx(ndim);\n\n  double C = 1. / (2. * tanh(0.5)) ;\n\n  //exact computation\n  for (a = -1; a <= 1.0; a += 1e-2) {\n    ac(1) = a;\n    hs65(NLPFunction, ndim, ac, fx, gx, Hx, result, &d);\n    EXPECT_GT(- fx, tanh(-0.5 * a) / tanh(0.5)  - 1e-7);  //opposite taking to maximaze\n    EXPECT_LT(- fx, tanh(-0.5 * a) / tanh(0.5)  + 1e-7);\n\n    hs65(NLPGradient, ndim, ac, fx, gx, Hx, result, &d);\n    EXPECT_GT(- gx(1), - C * sech(0.5 * a) * sech(0.5 * a) - 1e-7);\n    EXPECT_LT(- gx(1), - C * sech(0.5 * a) * sech(0.5 * a) + 1e-7);\n\n    hs65(NLPHessian, ndim, ac, fx, gx, Hx, result, &d);\n    EXPECT_GT(- Hx(1, 1), C * tanh(0.5 * a) * sech(0.5 * a) * sech(0.5 * a) - 1e-7);\n    EXPECT_LT(- Hx(1, 1), C * tanh(0.5 * a) * sech(0.5 * a) * sech(0.5 * a) + 1e-7);\n  }\n}\n\nTEST(MLP, MLPCheckDerivativeHard) {\n  MLP nn(4, {10}, 3, 0.5f);\n  std::vector<double> sens(3);\n  sens[0] = bib::Utils::randin(-1, 1);\n  sens[1] = bib::Utils::randin(-1, 1);\n  sens[2] = bib::Utils::randin(-1, 1);\n\n  uint ndim = 1;\n  passdata d = {nn.getNeuralNet(), sens};\n  ColumnVector ac(ndim);\n  ColumnVector gx(ndim);\n  SymmetricMatrix Hx(ndim);\n  int result = 0;\n  double fx = -1;\n\n  for (double a = -1; a <= 1.0; a += 1e-2) {\n    ac(1) = a;\n\n    double h = 1e-10;\n    ac(1) = a - h;\n    hs65(NLPFunction, ndim, ac, fx, gx, Hx, result, &d);\n    double fx_base = fx;\n    ac(1) = a + h;\n    hs65(NLPFunction, ndim, ac, fx, gx, Hx, result, &d);\n    double fx_h = fx;\n    double derivative1 = (fx_h - fx_base) / (2.0 * h);\n\n    ac(1) = a;\n    hs65(NLPFunction, ndim, ac, fx, gx, Hx, result, &d);\n    double derivative2 = (fx_h - fx) / h;\n\n    hs65(NLPGradient, ndim, ac, fx, gx, Hx, result, &d);\n\n    EXPECT_GT(derivative1, gx(1) - 1e-5);\n    EXPECT_LT(derivative1, gx(1) + 1e-5);\n\n    EXPECT_GT(derivative2, gx(1) - 1e-5);\n    EXPECT_LT(derivative2, gx(1) + 1e-5);\n  }\n}\n\nTEST(MLP, MLPCheckHessian) {\n  MLP nn(4, {10}, 3, 0.5f);\n  std::vector<double> sens(3);\n  sens[0] = bib::Utils::randin(-1, 1);\n  sens[1] = bib::Utils::randin(-1, 1);\n  sens[2] = bib::Utils::randin(-1, 1);\n\n  uint ndim = 1;\n  passdata d = {nn.getNeuralNet(), sens};\n  ColumnVector ac(ndim);\n  ColumnVector gx(ndim);\n  SymmetricMatrix Hx(ndim);\n  int result = 0;\n  double fx = -1;\n\n  for (double a = -1; a <= 1.0; a += 1e-2) {\n    ac(1) = a;\n\n    double h = 1e-5;\n    ac(1) = a - h;\n    hs65(NLPFunction, ndim, ac, fx, gx, Hx, result, &d);\n    double fx_base = fx;\n    ac(1) = a + h;\n    hs65(NLPFunction, ndim, ac, fx, gx, Hx, result, &d);\n    double fx_h = fx;\n\n    ac(1) = a;\n    hs65(NLPFunction, ndim, ac, fx, gx, Hx, result, &d);\n    double snd_derivative = (fx_h - 2.0 * fx + fx_base) / (h * h);\n\n    hs65(NLPHessian, ndim, ac, fx, gx, Hx, result, &d);\n\n    EXPECT_GT(snd_derivative, Hx(1, 1) - 1e-5);\n    EXPECT_LT(snd_derivative, Hx(1, 1) + 1e-5);\n  }\n}\n\nTEST(MLP, OptimizeOpposite) {\n  MLP nn(1, {1}, 0, 0.5f);\n\n  fann_set_weight(nn.getNeuralNet(), 0, 2, -1.f);\n  fann_set_weight(nn.getNeuralNet(), 1, 2, 0.f);\n\n  fann_set_weight(nn.getNeuralNet(), 2, 4, 1. / tanh(0.5 * 1.));\n  fann_set_weight(nn.getNeuralNet(), 3, 4, 0.f);\n\n  // Test\n  std::vector<double> sens(0);\n  for (uint n = 0; n < 100 ; n++) {\n    double x1 = bib::Utils::randBool() ? 1.f : -1.f;\n\n    double out = x1 == 1.f ? -1.f : 1.f;\n\n    std::vector<double> ac(1);\n    ac[0] = x1;\n\n    EXPECT_DOUBLE_EQ(nn.computeOutVF(sens, ac), out);\n  }\n\n  std::vector<double>* ac = nn.optimized(sens);\n  EXPECT_GT(ac->at(0), -1. - 0.01);\n  EXPECT_LT(ac->at(0), -1. + 0.01);\n  delete ac;\n\n  fann_set_weight(nn.getNeuralNet(), 0, 2, 1.f);\n  ac = nn.optimized(sens);\n  EXPECT_GT(ac->at(0), 1. - 0.01);\n  EXPECT_LT(ac->at(0), 1. + 0.01);\n  delete ac;\n\n  // Learn\n  for (uint n = 0; n < 1000 ; n++) {\n    double x1 = bib::Utils::randBool() ? 1.f : -1.f;\n\n    double out = x1 == 1.f ? -1.f : 1.f;\n\n    std::vector<double> sens(0);\n    std::vector<double> acc(1);\n    acc[0] = x1;\n\n    nn.learn(sens, acc, out);\n  }\n\n  ac = nn.optimized(sens);\n  EXPECT_GT(ac->at(0), -1. - 0.01);\n  EXPECT_LT(ac->at(0), -1. + 0.01);\n\n//     LOG_DEBUG(nn.computeOut(sens, *ac));\n  ac->at(0) = -1;\n//     LOG_DEBUG(nn.computeOut(sens, *ac));\n  delete ac;\n}\n\n\nTEST(MLP, OptimizeAndOr) {\n  MLP nn(3, {10}, 2, 0.5f);\n\n  // Learn\n  for (uint n = 0; n < 10000 ; n++) {\n    double x1 = bib::Utils::randBool() ? 1.f : -1.f;\n    double x2 = bib::Utils::randBool() ? 1.f : -1.f;\n    double x3 = bib::Utils::randBool() ? 1.f : -1.f;\n\n    double out = AND(OR(x1, x2), x3);\n\n    std::vector<double> sens(2);\n    sens[0] = x1;\n    sens[1] = x2;\n    std::vector<double> ac(1);\n    ac[0] = x3;\n\n    nn.learn(sens, ac, out);\n  }\n\n\n\n  // Test\n  for (uint n = 0; n < 100 ; n++) {\n    double x1 = bib::Utils::randBool() ? 1.f : -1.f;\n    double x2 = bib::Utils::randBool() ? 1.f : -1.f;\n\n    std::vector<double> sens(2);\n    sens[0] = x1;\n    sens[1] = x2;\n\n    std::vector<double>* ac = nn.optimized(sens);\n    double his_sol = nn.computeOutVF(sens, *ac);\n\n    ac->at(0) = 1.f;\n    double my_sol = nn.computeOutVF(sens, *ac);\n\n    EXPECT_GE(his_sol, my_sol - 0.01);\n    delete ac;\n  }\n}\n\n\nTEST(MLP, OptimizeMultiDim) {\n  MLP nn(3, {20}, 0, 0.5f);\n\n  // Learn\n  for (uint n = 0; n < 10000 ; n++) {\n    double x1 = bib::Utils::randBool() ? 1.f : -1.f;\n    double x2 = bib::Utils::randBool() ? 1.f : -1.f;\n    double x3 = bib::Utils::randBool() ? 1.f : -1.f;\n\n    double out = AND(OR(x1, x2), x3);\n\n    std::vector<double> sens(0);\n    std::vector<double> ac(3);\n    ac[0] = x1;\n    ac[1] = x2;\n    ac[2] = x3;\n\n    nn.learn(sens, ac, out);\n  }\n\n  // Test\n  for (uint n = 0; n < 100 ; n++) {\n    std::vector<double> sens(0);\n    std::vector<double>* ac = nn.optimized(sens);\n    double his_sol = nn.computeOutVF(sens, *ac);\n    double my_sol = 1.;\n\n    EXPECT_GE(his_sol, my_sol - 0.01);\n    delete ac;\n  }\n}\n\nTEST(MLP, OptimizeNonExtremum) {\n  //learn x^2 - x\n  //root min ~0.474\n  //root max -1\n\n  double sensv = 1. ;\n  for (uint n = 0; n < 1 ; n++) {\n    MLP nn(1, {3}, 0, 0.2f);\n    std::vector<double> sens(0);\n    std::vector<double> ac(1);\n\n    // Learn\n    for (uint n = 0; n < 100000 ; n++) {\n      double x1 = (bib::Utils::rand01() * 2.) - 1;\n\n      double out = x1 * x1 - x1;\n      ac[0] = x1;\n\n      nn.learn(sens, ac, sensv * out);\n    }\n\n    //Test learned\n    for (uint n = 0; n < 1000 ; n++) {\n      double x1 = (bib::Utils::rand01() * 2.) - 1;\n\n      double out = x1 * x1 - x1;\n      ac[0] = x1;\n\n      double myout = nn.computeOutVF(sens, ac);\n      EXPECT_GT(myout, sensv * out - 0.1);\n      EXPECT_LT(myout, sensv * out + 0.1);\n      LOG_FILE(\"OptimizeNonExtremum.data\", x1 << \" \" << myout << \" \" << out);\n//     close all; X=load('OptimizeNonExtremum.data'); plot(X(:,1),X(:,2), '.'); hold on; plot(X(:,1),X(:,3), 'r.');\n    }\n\n    std::vector<double>* acopt = nn.optimized(sens, {}, NB_SOL_OPTIMIZATION);\n    if (sensv == -1.) {\n      EXPECT_GT(acopt->at(0), 0.46);\n      EXPECT_LT(acopt->at(0), 0.48);\n    } else {\n      EXPECT_LT(acopt->at(0), -0.99);\n      EXPECT_GT(acopt->at(0), -1.01);\n    }\n    delete acopt;\n    sensv *= -1;\n  }\n}\n\n\nTEST(MLP, Optimize2LocalMaxima) {\n  //learn - cos(5.*x1)/2.\n\n  MLP nn(1, {10}, 0, 0.1f);\n  std::vector<double> sens(0);\n  std::vector<double> ac(1);\n\n  fann_set_training_algorithm(nn.getNeuralNet(), FANN_TRAIN_RPROP); //adaptive algorithm without learning rate\n  fann_set_train_error_function(nn.getNeuralNet(), FANN_ERRORFUNC_TANH);\n\n  struct fann_train_data* data = fann_create_train(2500, 1, 1);\n\n  // Learn\n  for (uint n = 0; n < 2500 ; n++) {\n    double x1 = (bib::Utils::rand01() * 2.) - 1;\n\n    double out = - cos(5.*x1) / 2.;\n    ac[0] = x1;\n\n    data->input[n][0] = x1;\n    data->output[n][0] = out;\n  }\n\n  fann_train_on_data(nn.getNeuralNet(), data, 3000, 0, 0.0005);\n  fann_destroy_train(data);\n\n  //Test learned\n  for (uint n = 0; n < 1000 ; n++) {\n    double x1 = (bib::Utils::rand01() * 2.) - 1;\n\n    double out = - cos(5.*x1) / 2.;\n    ac[0] = x1;\n\n    double myout = nn.computeOutVF(sens, ac);\n    LOG_FILE(\"Optimize2LocalMaxima.data\", x1 << \" \" << myout << \" \" << out);\n//     close all; X=load('Optimize2LocalMaxima.data'); plot(X(:,1),X(:,2), '.'); hold on; plot(X(:,1),X(:,3), 'r.');\n  }\n\n  std::vector<double>* acopt = nn.optimized(sens, {}, NB_SOL_OPTIMIZATION);\n//     ac[0] = acopt->at(0);\n//     double my_sol = nn.computeOut(sens, ac);\n//     ac[0] = M_PI/5;\n//     double best_sol = nn.computeOut(sens, ac);\n//     LOG_DEBUG(\"my sol : \" << my_sol << \" | best : \" << best_sol << \" (\" << acopt->at(0) << \" vs \" << M_PI/5 << \") \");\n\n  double precision = 0.1;\n  if (acopt->at(0) > 0) {\n    EXPECT_GT(acopt->at(0), M_PI / 5. - precision);\n    EXPECT_LT(acopt->at(0), M_PI / 5. + precision);\n  } else {\n    EXPECT_GT(acopt->at(0), -M_PI / 5. - precision);\n    EXPECT_LT(acopt->at(0), -M_PI / 5 + precision);\n  }\n\n  delete acopt;\n}\n\n\nTEST(MLP, OptimizeTrapInEvilLocalOptimal) {\n  //learn sin(-3*x*x*x+2*x*x+x)\n  //local max ~0.6\n  //global max -0.7\n\n  MLP nn(1, {12}, 0, 0.1f);\n  std::vector<double> sens(0);\n  std::vector<double> ac(1);\n\n  fann_set_training_algorithm(nn.getNeuralNet(), FANN_TRAIN_RPROP); //adaptive algorithm without learning rate\n  fann_set_train_error_function(nn.getNeuralNet(), FANN_ERRORFUNC_TANH);\n\n  struct fann_train_data* data = fann_create_train(2500, 1, 1);\n\n  // Learn\n  for (uint n = 0; n < 2500 ; n++) {\n    double x1 = (bib::Utils::rand01() * 2.) - 1;\n\n    double out = sin(-3 * x1 * x1 * x1 + 2 * x1 * x1 + x1);\n    ac[0] = x1;\n\n    data->input[n][0] = x1;\n    data->output[n][0] = out;\n  }\n\n  fann_train_on_data(nn.getNeuralNet(), data, 10000, 0, 0.0005);\n  fann_destroy_train(data);\n\n  //Test learned\n  for (uint n = 0; n < 1000 ; n++) {\n    double x1 = (bib::Utils::rand01() * 2.) - 1;\n\n    double out = sin(-3 * x1 * x1 * x1 + 2 * x1 * x1 + x1);\n    ac[0] = x1;\n\n    double myout = nn.computeOutVF(sens, ac);\n    LOG_FILE(\"OptimizeTrapInEvilLocalOptimal.data\", x1 << \" \" << myout << \" \" << out);\n//     close all; X=load('OptimizeTrapInEvilLocalOptimal.data'); plot(X(:,1),X(:,2), '.'); hold on; plot(X(:,1),X(:,3), 'r.');\n  }\n\n  std::vector<double>* acopt = nn.optimized(sens, {}, NB_SOL_OPTIMIZATION+100);\n//     LOG_DEBUG(acopt->at(0));\n\n  double precision = 0.1;\n\n  if(acopt->at(0) < -0.7 - precision || acopt->at(0) > -0.7 + precision) {\n    LOG_DEBUG(nn.computeOutVF(sens, *acopt));\n    ac[0] = -0.7;\n    LOG_DEBUG(nn.computeOutVF(sens, ac));\n  }\n\n  EXPECT_GT(acopt->at(0), -0.7 - precision);\n  EXPECT_LT(acopt->at(0), -0.7 + precision);\n\n  delete acopt;\n}\n\n\n\nTEST(MLP, OptimizePlateau) {\n  //learn sin(-3*x*x*x+2*x*x+x)\n  //local max ~0.6\n  //global max -0.7\n\n  MLP nn(1, {2}, 0, 0.1f);\n  std::vector<double> sens(0);\n  std::vector<double> ac(1);\n\n  fann_set_training_algorithm(nn.getNeuralNet(), FANN_TRAIN_RPROP); //adaptive algorithm without learning rate\n  fann_set_train_error_function(nn.getNeuralNet(), FANN_ERRORFUNC_TANH);\n\n  struct fann_train_data* data = fann_create_train(5000, 1, 1);\n\n  // Learn\n  for (uint n = 0; n < 5000 ; n++) {\n    double x1 = n < 2000 ? (bib::Utils::rand01() * 2.) - 1 : bib::Utils::randin(0, 0.5);\n\n    double out = x1 >= 0.2 ? 1. : 0.2;\n    ac[0] = x1;\n\n    data->input[n][0] = x1;\n    data->output[n][0] = out;\n  }\n\n  fann_train_on_data(nn.getNeuralNet(), data, 10000, 0, 0.00001);\n  fann_destroy_train(data);\n\n  //Test learned\n  for (uint n = 0; n < 1000 ; n++) {\n    double x1 = (bib::Utils::rand01() * 2.) - 1;\n\n    double out = x1 >= 0.2 ? 1. : 0.2;\n    ac[0] = x1;\n\n    double myout = nn.computeOutVF(sens, ac);\n    LOG_FILE(\"OptimizePlateau.data\", x1 << \" \" << myout << \" \" << out);\n//     close all; X=load('OptimizePlateau.data'); plot(X(:,1),X(:,2), '.'); hold on; plot(X(:,1),X(:,3), 'r.');\n  }\n\n  std::vector<double>* acopt = nn.optimized(sens, {}, NB_SOL_OPTIMIZATION);\n//     LOG_DEBUG(acopt->at(0));\n\n  double precision = 0.01;\n\n  EXPECT_GT(acopt->at(0), 0.2 - precision);\n\n  delete acopt;\n}\n#endif //NO_OPTPP\n\nTEST(MLP, ConsistentActivationFunctionLecun) {\n  MLP nn(1, {1}, 0, 0.01f, true);\n\n  fann_set_weight(nn.getNeuralNet(), 0, 2, 1.f);\n  fann_set_weight(nn.getNeuralNet(), 1, 2, 0.f);\n  fann_set_weight(nn.getNeuralNet(), 2, 4, 1.f);\n  fann_set_weight(nn.getNeuralNet(), 3, 4, 0.f);\n  \n  std::vector<double> sens(0);\n  std::vector<double> ac(1);\n  ac[0] = 1.d;\n\n  double lambda = atanh(1.d/sqrt(3.d));\n  EXPECT_DOUBLE_EQ(nn.computeOutVF(sens, ac), sqrt(3.d)*tanh(lambda * 1.d));\n\n  ac[0] = 1.5d;\n  EXPECT_DOUBLE_EQ(nn.computeOutVF(sens, ac), sqrt(3.d)*tanh(lambda * 1.5d));//1.31\n  \n  fann_set_weight(nn.getNeuralNet(), 0, 2, 0.f);\n  fann_set_weight(nn.getNeuralNet(), 1, 2, 0.f);\n  fann_set_weight(nn.getNeuralNet(), 2, 4, 0.f);\n  fann_set_weight(nn.getNeuralNet(), 3, 4, 5.f);\n\n  EXPECT_DOUBLE_EQ(nn.computeOutVF(sens, ac), 5.f);\n\n  fann_set_weight(nn.getNeuralNet(), 0, 2, 0.2f);\n  fann_set_weight(nn.getNeuralNet(), 1, 2, 0.4f);\n  fann_set_weight(nn.getNeuralNet(), 2, 4, 0.6f);\n  fann_set_weight(nn.getNeuralNet(), 3, 4, 0.8f);\n\n  ac[0] = -1.d;\n  EXPECT_DOUBLE_EQ(nn.computeOutVF(sens, ac), (sqrt(3.d)*tanh(lambda * (-1. * 0.2f + 0.4f)) * 0.6f + 0.8f));\n}\n\nTEST(MLP, LearnAndOrLecun) {\n  MLP nn(3, {10}, 2, 0.05f, true);\n\n  // Learn\n  for (uint n = 0; n < 10000 ; n++) {\n    double x1 = bib::Utils::randBool() ? 1.f : -1.f;\n    double x2 = bib::Utils::randBool() ? 1.f : -1.f;\n    double x3 = bib::Utils::randBool() ? 1.f : -1.f;\n\n    double out = AND(OR(x1, x2), x3);\n\n    std::vector<double> sens(2);\n    sens[0] = x1;\n    sens[1] = x2;\n    std::vector<double> ac(1);\n    ac[0] = x3;\n    \n    nn.learn(sens, ac, out);\n  }\n\n  // Test\n  for (uint n = 0; n < 100 ; n++) {\n    double x1 = bib::Utils::randBool() ? 1.f : -1.f;\n    double x2 = bib::Utils::randBool() ? 1.f : -1.f;\n    double x3 = bib::Utils::randBool() ? 1.f : -1.f;\n\n    double out = AND(OR(x1, x2), x3);\n\n    std::vector<double> sens(2);\n    sens[0] = x1;\n    sens[1] = x2;\n    std::vector<double> ac(1);\n    ac[0] = x3;\n\n    EXPECT_GT(nn.computeOutVF(sens, ac), out - 0.02);\n    EXPECT_LT(nn.computeOutVF(sens, ac), out + 0.02);\n  }\n}\n\nTEST(MLP, LearnAndOrLecun2) {\n  MLP nn(3, {5}, 1, true);\n\n  struct fann_train_data* data = fann_create_train(2*2*2, 3, 1);\n   \n  uint n = 0;\n  auto iter = [&](const std::vector<double>& x) {\n    data->input[n][0]= x[0];\n    data->input[n][1]= x[1];\n    data->input[n][2]= x[2];\n    \n    double out = AND(OR(x[0], x[1]), x[2]);\n    data->output[n][0]= out;\n    n++;\n  };\n    \n  bib::Combinaison::continuous<>(iter, 3, -1, 1, 1);\n  \n  nn.learn_stoch(data, 20000, 0, 0.00000001);\n  \n  fann_destroy_train(data);\n\n  // Test\n  for (uint n = 0; n < 100 ; n++) {\n    double x1 = bib::Utils::randBool() ? 1.f : -1.f;\n    double x2 = bib::Utils::randBool() ? 1.f : -1.f;\n    double x3 = bib::Utils::randBool() ? 1.f : -1.f;\n\n    double out = AND(OR(x1, x2), x3);\n\n    std::vector<double> sens(2);\n    sens[0] = x1;\n    sens[1] = x2;\n    std::vector<double> ac(1);\n    ac[0] = x3;\n\n    EXPECT_GT(nn.computeOutVF(sens, ac), out - 0.02);\n    EXPECT_LT(nn.computeOutVF(sens, ac), out + 0.02);\n    \n    std::vector<double> in(3);\n    in[0] = x1;\n    in[1] = x2;\n    in[2] = x3;\n    std::vector<double>* outnn = nn.computeOut(in);\n    \n    EXPECT_GT(outnn->at(0), out - 0.05);\n    EXPECT_LT(outnn->at(0), out + 0.05);\n    \n    delete outnn;\n  }\n}\n\n\n// 1 0.2\n// 3 0.3\n// 5 0.3\n// \n// Result:  y = 0.025 x + 1.916666667\u00b710-1\n// \n// 2.166666667\u00b710-1 \t\t 1.666666667\u00b710-2 \n// 2.666666667\u00b710-1 \t\t 3.333333333\u00b710-2 \n// 3.166666667\u00b710-1 \t\t 1.666666667\u00b710-2 \nTEST(MLP, LearnLabelWeight) {\n  fann* lin_nn =fann_create_standard(2, 1, 1);\n  fann_set_activation_function_output(lin_nn, FANN_LINEAR);\n  fann_set_learning_momentum(lin_nn, 0.);\n  fann_set_training_algorithm(lin_nn, FANN_TRAIN_RPROP);\n\n  struct fann_train_data* data = fann_create_train(3, 1, 1);\n  fann_type lw [3];\n  \n  uint n = 0;\n  data->input[n][0]= 1.f;\n  data->output[n][0]= 2.f/10.f;\n  lw[n] = 1.f;\n  n++;\n  data->input[n][0]= 3.f;\n  data->output[n][0]= 3.f/10.f;\n  lw[n] = 0.5f;\n  n++;\n  data->input[n][0]= 5.f;\n  data->output[n][0]= 3.f/10.;\n  lw[n] = 1.f;\n  n++;\n  \n  for(int i=0;i<1000; i++)\n    fann_train_epoch(lin_nn, data);\n  \n  fann_type out_no_lw[3];\n  fann_type * out;\n  n=0;\n  out = fann_run(lin_nn, data->input[n]);\n  EXPECT_GT(out[0], 0.216 - 0.002);\n  EXPECT_LT(out[0], 0.216 + 0.002);\n  out_no_lw[n]=out[0];\n  n++;\n\n  out = fann_run(lin_nn, data->input[n]);\n  EXPECT_GT(out[0], 0.266 - 0.002);\n  EXPECT_LT(out[0], 0.266 + 0.002);\n  out_no_lw[n]=out[0];\n  n++;\n  \n  out = fann_run(lin_nn, data->input[n]);\n  EXPECT_GT(out[0], 0.316 - 0.002);\n  EXPECT_LT(out[0], 0.316 + 0.002);\n  out_no_lw[n]=out[0];\n  \n  for(int i=0;i<1000; i++)\n    fann_train_epoch_lw(lin_nn, data, lw);\n  \n  n=0;\n  out = fann_run(lin_nn, data->input[n]);\n  EXPECT_GT(out[0], 0.2);\n  EXPECT_LT(out[0], out_no_lw[n]);\n  out_no_lw[n]=out[0];\n  n++;\n\n  out = fann_run(lin_nn, data->input[n]);\n  EXPECT_GT(out[0], 0.25);\n  EXPECT_LT(out[0], out_no_lw[n]);\n  out_no_lw[n]=out[0];\n  n++;\n  \n  out = fann_run(lin_nn, data->input[n]);\n  EXPECT_GT(out[0], 0.3);\n  EXPECT_LT(out[0], out_no_lw[n]);\n  out_no_lw[n]=out[0];\n  \n  lw[1] = 0.05;\n  for(int i=0;i<1000; i++)\n    fann_train_epoch_lw(lin_nn, data, lw);\n    \n  n=0;\n  out = fann_run(lin_nn, data->input[n]);\n  EXPECT_GT(out[0], 0.2);\n  EXPECT_LT(out[0], out_no_lw[n]);\n  n++;\n\n  out = fann_run(lin_nn, data->input[n]);\n  EXPECT_GT(out[0], 0.25);\n  EXPECT_LT(out[0], out_no_lw[n]);\n  n++;\n  \n  out = fann_run(lin_nn, data->input[n]);\n  EXPECT_GT(out[0], 0.3);\n  EXPECT_LT(out[0], out_no_lw[n]);\n  \n  fann_destroy_train(data);\n}\n\nTEST(MLP, LearnNonLinearLabelWeight) {\n  MLP nn(1, {4}, 1, true);\n\n  struct fann_train_data* data = fann_create_train(11*2, 1, 1);\n  fann_type label_weight[11*2];\n  \n  uint n = 0;\n  auto iter = [&](const std::vector<double>& x) {\n    data->input[n][0]= x[0];\n    data->output[n][0]= x[0];\n    label_weight[n] = 1.f;\n    n++;\n  };\n  \n  auto iter2 = [&](const std::vector<double>& x) {\n    data->input[n][0]= x[0];\n    data->output[n][0]= x[0]*x[0];\n    label_weight[n] = 0.2f;\n    n++;\n  };\n  \n  bib::Combinaison::continuous<>(iter, 1, 0, 1, 10);\n  bib::Combinaison::continuous<>(iter2, 1, 0, 1, 10);\n  \n  nn.learn_stoch(data, 20000, 0, 0.00000001);\n  \n  // Test\n  for (uint n = 0; n < 100 ; n++) {\n    double x1 = bib::Utils::rand01();\n\n    double out = (x1 + x1*x1)/2.;\n\n    std::vector<double> sens(1);\n    sens[0] = x1;\n    std::vector<double> ac(0);\n    \n    double old_out1 = x1;\n    double old_out2 = x1*x1;\n\n    EXPECT_GT(nn.computeOutVF(sens, ac), out - 0.15);\n    EXPECT_LT(nn.computeOutVF(sens, ac), out + 0.15);\n    \n    if(x1 > 0.15 && x1 < 0.85){\n      EXPECT_GE(fabs(nn.computeOutVF(sens, ac) - old_out1), fabs(nn.computeOutVF(sens, ac) - out));\n      EXPECT_GE(fabs(nn.computeOutVF(sens, ac) - old_out2), fabs(nn.computeOutVF(sens, ac) - out));\n    }\n      \n  }\n  \n  nn.learn_stoch_lw(data, label_weight, 20000, 0, 0.00000001);\n  \n  // Test\n  for (uint n = 0; n < 100 ; n++) {\n    double x1 = bib::Utils::rand01();\n\n    double old_out = (x1 + x1*x1)/2.;\n    double out = (x1 + 0.2*x1*x1)/1.2;\n\n    std::vector<double> sens(1);\n    sens[0] = x1;\n    std::vector<double> ac(0);\n\n    EXPECT_GT(nn.computeOutVF(sens, ac), out - 0.1);\n    EXPECT_LT(nn.computeOutVF(sens, ac), out + 0.1);\n    \n    if(x1 > 0.15 && x1 < 0.85)\n      EXPECT_GE(fabs(nn.computeOutVF(sens, ac) - old_out), fabs(nn.computeOutVF(sens, ac) - out));\n  }\n  \n  fann_destroy_train(data);\n}\n\n\nTEST(MLP, LearnNonLinearLabelWeightWithNullImportance) {\n  MLP nn(1, {4}, 1, true);\n\n  struct fann_train_data* data = fann_create_train(11*2, 1, 1);\n  fann_type label_weight[11*2];\n  \n  uint n = 0;\n  auto iter = [&](const std::vector<double>& x) {\n    data->input[n][0]= x[0];\n    data->output[n][0]= x[0];\n    label_weight[n] = 0.0f;\n    n++;\n  };\n  \n  auto iter2 = [&](const std::vector<double>& x) {\n    data->input[n][0]= x[0];\n    data->output[n][0]= -x[0];\n    label_weight[n] = 0.8f;\n    n++;\n  };\n  \n  bib::Combinaison::continuous<>(iter, 1, 0, 1, 10);\n  bib::Combinaison::continuous<>(iter2, 1, 0, 1, 10);\n  \n  nn.learn_stoch_lw(data, label_weight, 20000, 0, 0.00000001);\n  \n  // Test\n  for (uint n = 0; n < 100 ; n++) {\n    double x1 = bib::Utils::rand01();\n\n    double out = (0.0*x1 - 0.8*x1)/(0.0+0.8);\n\n    std::vector<double> sens(1);\n    sens[0] = x1;\n    std::vector<double> ac(0);\n\n    EXPECT_GT(nn.computeOutVF(sens, ac), out - 0.15);\n    EXPECT_LT(nn.computeOutVF(sens, ac), out + 0.15);\n  }\n  \n  fann_destroy_train(data);\n}\n\n\ndouble derivative(double* s, double* a, int, void*){\n    return -(2*a[0] -s[0]*s[0]);\n}\n\n// try to learn a function pi that maximize another one : f(s, pi(a)) = a^2-(s^2)*a\nTEST(MLP, OptimizeNNTroughGradient) {\n  MLP nn(1, {4}, 1, 0.0, true);\n\n  struct fann_train_data* data = fann_create_train(200, 1, 1);\n  \n  uint n = 0;\n  auto iter = [&](const std::vector<double>& x) {\n    data->input[n][0]= x[0];\n//     data->output[n][0]= -x[0]*x[0];\n    data->output[n][0]= x[0];//don't care\n    n++;\n  };\n  \n  bib::Combinaison::continuous<>(iter, 1, -1, 1, 200);\n  \n  for(int i=0;i<10000; i++)\n    fann_train_epoch_irpropm_gradient(nn.getNeuralNet(), data, derivative, nullptr);\n  \n  // Test\n  for (uint n = 0; n < 100 ; n++) {\n    double x1 = bib::Utils::rand01()*2 -1;\n\n    double out = (x1 * x1)/2;\n\n    std::vector<double> sens(1);\n    sens[0] = x1;\n    std::vector<double> ac(0);\n\n    EXPECT_GT(nn.computeOutVF(sens, ac), out - 0.1);\n    EXPECT_LT(nn.computeOutVF(sens, ac), out + 0.1);\n    \n    LOG_FILE(\"OptimizeNNTroughGradient.data\", x1 << \" \" << nn.computeOutVF(sens, ac) << \" \" << out);\n  }\n  \n  fann_destroy_train(data);\n}\n\n\nclass my_weights {\n  typedef struct fann_connection sfn;\n\n public:\n  my_weights(NN neural_net, const double* sensors, const double* x, uint _m, uint _n) : m(_m), n(_n) {\n    _lambda = fann_get_activation_steepness(neural_net, 1, 0);\n\n    unsigned int number_connection = fann_get_total_connections(neural_net);\n    connections = reinterpret_cast<sfn*>(calloc(number_connection, sizeof(sfn)));\n\n    fann_get_connection_array(neural_net, connections);\n\n    uint number_layer = fann_get_num_layers(neural_net);\n    layers = reinterpret_cast<uint*>(calloc(number_layer, sizeof(sfn)));\n\n    fann_get_layer_array(neural_net, layers);\n    ASSERT(number_layer == 3, number_layer);\n\n    for (uint i = 0; i < h() * (m + n + 1); i++) {\n      _ASSERT_EQ(connections[i].from_neuron, i % (m + n + 1));\n      _ASSERT_EQ(connections[i].to_neuron, (m + n + 1) + i / (m + n + 1));\n    }\n\n    Ci.clear();\n    Ci.resize(h());\n    for (uint i = 0; i < h(); i++) {\n      Ci[i] = 0;\n      for (uint j = 0; j < m; j++)\n        Ci[i] += sensors[j] * w(j, i);\n\n      Ci[i] += connections[ i * (m + n + 1) + m + n].weight;\n      _ASSERT_EQ(connections[ i * (m + n + 1) + m + n].from_neuron, m + n);\n      _ASSERT_EQ(connections[ i * (m + n + 1) + m + n].to_neuron, m + n + 1 + i);\n    }\n\n    Di.clear();\n    Di.resize(h());\n    for (uint i = 0; i < h(); i++) {\n      Di[i] = Ci[i];\n      for (uint j = 0; j < n; j++)\n        Di[i] += x[j] * w(m + j, i);\n    }\n\n    ASSERT(number_connection == h() * (m + n + 1) + (h() + 1), \"\");\n  }\n\n  ~my_weights() {\n    free(connections);\n    free(layers);\n  }\n\n  double v(uint i) const {\n    sfn conn = connections[ h() * (m + n + 1) + i];\n\n    _ASSERT_EQS(conn.from_neuron, (m + n + 1) + i, \" i: \" << i  << \" m \" << m << \" n \" << n << \" h \" << h());\n    _ASSERT_EQS(conn.to_neuron, (m + n + 1) + (h() + 1), \" i: \" << i  << \" m \" << m << \" n \" << n << \" h \" << h());\n    return conn.weight;\n  }\n\n  double w(uint j, uint i) const {\n    sfn conn = connections[ i * (m + n + 1) + j];\n\n    _ASSERT_EQS(conn.from_neuron, j, \" i: \" << i << \" j : \" << j  << \" m \" << m << \" n \" << n << \" h \" << h());\n    _ASSERT_EQS(conn.to_neuron, (m + n + 1) + i, \" i: \" << i << \" j : \" << j  << \" m \" << m << \" n \" << n << \" h \" << h());\n    return conn.weight;\n  }\n\n  uint h() const {\n    return layers[1];\n  }\n\n  double C(uint i) const {\n    return Ci[i];\n  }\n\n  double D(uint i) const {\n    return Di[i];\n  }\n\n  double lambda() const {\n    return _lambda;\n  }\n\n private :\n  sfn* connections;\n  uint* layers;\n  std::vector<double> Ci;\n  std::vector<double> Di;\n  uint m, n;\n  double _lambda;\n};\n\n#define activation_function(x, lambda) tanh(lambda * x)\n\ndouble derivative2(double* input, double *neuron_value, int, void* data){\n    MLP* nn = (MLP*)data;\n    my_weights _w(nn->getNeuralNet(), input, neuron_value, 1, 1);\n    \n    std::vector<double> gx(1);\n    for (uint j = 0; j < 1; j++) {\n      gx[j] = 0;\n      for (uint i = 0; i < _w.h() ; i++) {\n        double der = activation_function(_w.D(i), _w.lambda());\n        gx[j] = gx[j] + _w.v(i) * _w.w(1 + j, i) * _w.lambda() * (1.0 - der * der);\n      }\n    }\n\n//     LOG_DEBUG((-(2*neuron_value[0] -input[0]*input[0])) << \" \" << gx[0]);\n    return gx[0];\n}\n\nTEST(MLP, OptimizeNNTroughGradientOfAnotherNN) {\n  MLP nn(2, {50}, 1, 0.0);\n  MLP actor(1, {4}, 1);\n\n  struct fann_train_data* data = fann_create_train(200*200, 2, 1);\n  \n  uint n = 0;\n  auto iter = [&](const std::vector<double>& x) {\n    data->input[n][0]= x[0];\n    data->input[n][1]= x[1];\n\n    data->output[n][0]= -(x[1]*x[1]-(x[0]*x[0])*x[1]);\n    n++;\n  };\n  \n  bib::Combinaison::continuous<>(iter, 2, -1, 1, 200);\n  \n  nn.learn_stoch(data, 500, 100, 0.0000001,200);\n  fann_destroy_train(data);\n  \n  data = fann_create_train(2000, 1, 1);\n  n = 0;\n  auto iter2 = [&](const std::vector<double>& x) {\n    data->input[n][0]= x[0];\n    data->output[n][0]= x[0];//don't care\n    n++;\n  };\n  bib::Combinaison::continuous<>(iter2, 1, -1, 1, 2000);\n  \n  //fann_type *error_begin = nn.getNeuralNet()->train_errors;\n  \n  for(int i=0;i<1000; i++)\n     fann_train_epoch_irpropm_gradient(actor.getNeuralNet(), data, derivative2, &nn);\n  \n  // Test\n  for (uint n = 0; n < 100 ; n++) {\n    double x1 = bib::Utils::rand01()*2 -1;\n\n    double out = (x1 * x1)/2;\n    double qout = -(out*out-(x1*x1)*out);\n\n    std::vector<double> sens(1);\n    sens[0] = x1;\n    std::vector<double> ac(1);\n    std::vector<double> ac_empty(0);\n    ac[0]= out;\n    \n    EXPECT_GT(nn.computeOutVF(sens, ac), qout - 0.15);\n    EXPECT_LT(nn.computeOutVF(sens, ac), qout + 0.15);\n\n    EXPECT_GT(actor.computeOutVF(sens, ac_empty), out - 0.2);\n    EXPECT_LT(actor.computeOutVF(sens, ac_empty), out + 0.2);\n    \n    LOG_FILE(\"OptimizeNNTroughGradientOfAnotherNN.data\", x1 << \" \" << actor.computeOutVF(sens, ac_empty) << \" \" << out);\n  }\n  \n  fann_destroy_train(data);\n}\n\nTEST(MLP, OptimizeNNTroughGradientOfAnotherNNFann) {\n  MLP nn(2, {50}, 1, 0.0, true);\n//   MLP nn(2, 1, 1, 0.0);\n  MLP actor(1, {8}, 1);\n  \n  MLP actor2(actor);\n  fann_set_activation_function_output(actor.getNeuralNet(), FANN_SIGMOID_SYMMETRIC);\n  fann_set_activation_function_output(actor2.getNeuralNet(), FANN_LINEAR);\n\n  struct fann_train_data* data;\n  if ( !boost::filesystem::exists( \"OptimizeNNTroughGradientOfAnotherNNFann.cache.data\" ) ){\n    data = fann_create_train(200*200, 2, 1);\n    \n    uint n = 0;\n    auto iter = [&](const std::vector<double>& x) {\n      data->input[n][0]= x[0];\n      data->input[n][1]= x[1];\n\n      data->output[n][0]= -(x[1]*x[1]-(x[0]*x[0])*x[1]);\n      n++;\n    };\n    \n    bib::Combinaison::continuous<>(iter, 2, -1, 1, 200);\n    \n    \n    nn.learn_stoch(data, 5800, 100, 0.0000001,500);\n    //nn.learn(data, 300, 0);\n    \n    fann_destroy_train(data);\n    nn.save(\"OptimizeNNTroughGradientOfAnotherNNFann.cache.data\");\n  } else \n    nn.load(\"OptimizeNNTroughGradientOfAnotherNNFann.cache.data\");\n  \n\n  \n  datann_derivative d = {&nn, 1, 1};\n  \n  for(int i=0;i<5000; i++){\n     data = fann_create_train(4000, 1, 1);\n     for (uint n = 0; n < 4000 ; n++){\n       data->input[n][0]= bib::Utils::rand01()*2-1.;\n       data->output[n][0]= 0;\n     }\n    \n    \n     fann_train_epoch_irpropm_gradient(actor.getNeuralNet(), data, derivative_nn, &d);\n\n     fann_train_epoch_irpropm_gradient(actor2.getNeuralNet(), data, derivative_nn_inverting, &d);\n     if(i%200 == 0)\n      LOG_DEBUG(actor.weight_l1_norm() << \" \" << actor2.weight_l1_norm());\n     \n     fann_destroy_train(data);\n  }\n  \n  // Test\n  double ac1_error = 0;\n  double ac2_error = 0;\n  for (uint n = 0; n < 100 ; n++) {\n    double x1 = bib::Utils::rand01()*2 -1;\n\n    double out = (x1 * x1)/2;\n    //out = x1 > 0 ? 0 : -1.f;\n    double qout = out*out-(x1*x1)*out;\n    qout = - qout;\n\n    std::vector<double> sens(1);\n    sens[0] = x1;\n    std::vector<double> ac(1);\n    std::vector<double> ac_empty(0);\n    ac[0]= out;\n    \n    EXPECT_GT(nn.computeOutVF(sens, ac), qout - 0.2);\n    EXPECT_LT(nn.computeOutVF(sens, ac), qout + 0.2);\n\n    EXPECT_GT(actor.computeOutVF(sens, ac_empty), out - 0.25);\n    EXPECT_LT(actor.computeOutVF(sens, ac_empty), out + 0.25);\n    \n    EXPECT_GT(actor2.computeOutVF(sens, ac_empty), out - 0.25);\n    EXPECT_LT(actor2.computeOutVF(sens, ac_empty), out + 0.25);\n    \n    LOG_FILE(\"OptimizeNNTroughGradientOfAnotherNNFann.data\", x1 << \" \" << actor.computeOutVF(sens, ac_empty) << \" \" <<\n                                                              actor2.computeOutVF(sens, ac_empty)<< \" \" << out);\n    //clear all; close all; X=load('OptimizeNNTroughGradientOfAnotherNNFann.data'); plot(X(:,1),X(:,2), '.'); hold on; plot(X(:,1),X(:,3), 'r.');plot(X(:,1),X(:,4), 'go');\n    ac1_error += fabs(out - actor.computeOutVF(sens, ac_empty));\n    ac2_error += fabs(out - actor2.computeOutVF(sens, ac_empty));\n  }\n  \n  ac1_error /= 100;\n  ac2_error /= 100;\n  \n  LOG_DEBUG(ac1_error << \" \" << ac2_error);\n}\n\nTEST(MLP, OptimizeNNTroughGradientOfAnotherNNFannMinDerivative) {\n  MLP nn(2, {50}, 1, 0.0, true);\n  MLP actor(1, {8}, 1);\n  \n  MLP actor2(actor);\n  fann_set_activation_function_output(actor.getNeuralNet(), FANN_SIGMOID_SYMMETRIC);\n  fann_set_activation_function_output(actor2.getNeuralNet(), FANN_LINEAR);\n\n  struct fann_train_data* data;\n  if ( !boost::filesystem::exists( \"OptimizeNNTroughGradientOfAnotherNNFannMinDerivative.cache.data\" ) ){\n    data = fann_create_train(200*200, 2, 1);\n    \n    \n    for(uint n = 0; n < 200*200 ;n++){\n      double x0 = bib::Utils::rand01()*2 -1;\n      double x1 = bib::Utils::rand01()*2 -1;\n      data->input[n][0]= x0;\n      data->input[n][1]= x1;\n\n      data->output[n][0]= x1*x1-(x0*x0)*x1;\n    }\n    \n    \n    nn.learn_stoch(data, 5800, 100, 0.0000001,1000);\n    //nn.learn(data, 300, 0);\n    \n    fann_destroy_train(data);\n    nn.save(\"OptimizeNNTroughGradientOfAnotherNNFannMinDerivative.cache.data\");\n  } else \n    nn.load(\"OptimizeNNTroughGradientOfAnotherNNFannMinDerivative.cache.data\");\n  \n\n  \n  datann_derivative d = {&nn, 1, 1};\n  \n  for(int i=0;i<1000; i++){\n     data = fann_create_train(400, 1, 1);\n//      uint n = 0;\n//      auto iter2 = [&](const std::vector<double>& x) {\n//         data->input[n][0]= x[0];\n//         data->output[n][0]= x[0];//don't care\n//        n++;\n//      };\n//      bib::Combinaison::continuous<>(iter2, 1, -1, 1, 200);\n     for (uint n = 0; n < 400 ; n++){\n       data->input[n][0]= bib::Utils::rand01()*2-1.;\n       data->output[n][0]= 0;\n     }\n    \n    \n     fann_train_epoch_irpropm_gradient(actor.getNeuralNet(), data, derivative_nn, &d);\n\n     fann_train_epoch_irpropm_gradient(actor2.getNeuralNet(), data, derivative_nn_inverting, &d);\n     if(i%100 == 0)\n      LOG_DEBUG(actor.weight_l1_norm() << \" \" << actor2.weight_l1_norm());\n     \n     fann_destroy_train(data);\n  }\n  \n  // Test\n  double ac1_error = 0;\n  double ac2_error = 0;\n  for (uint n = 0; n < 100 ; n++) {\n    double x1 = bib::Utils::rand01()*2 -1;\n\n    double out = -1.f; //not about derivative but constraints in [-1; 1]\n    double qout = out*out-(x1*x1)*out;\n\n    std::vector<double> sens(1);\n    sens[0] = x1;\n    std::vector<double> ac(1);\n    std::vector<double> ac_empty(0);\n    ac[0]= out;\n    \n    EXPECT_GT(nn.computeOutVF(sens, ac), qout - 0.25);\n    EXPECT_LT(nn.computeOutVF(sens, ac), qout + 0.25);\n\n    EXPECT_GT(actor.computeOutVF(sens, ac_empty), out - 0.2);\n    EXPECT_LT(actor.computeOutVF(sens, ac_empty), out + 0.2);\n    \n    EXPECT_GT(actor2.computeOutVF(sens, ac_empty), out - 0.2);\n    EXPECT_LT(actor2.computeOutVF(sens, ac_empty), out + 0.2);\n    \n    LOG_FILE(\"OptimizeNNTroughGradientOfAnotherNNFannMinDerivative.data\", x1 << \" \" << actor.computeOutVF(sens, ac_empty) << \" \" <<\n                                                              actor2.computeOutVF(sens, ac_empty)<< \" \" << out);\n    //clear all; close all; X=load('OptimizeNNTroughGradientOfAnotherNNFannMinDerivative.data'); plot(X(:,1),X(:,2), '.'); hold on; plot(X(:,1),X(:,3), 'r.');plot(X(:,1),X(:,4), 'go');\n    ac1_error += fabs(out - actor.computeOutVF(sens, ac_empty));\n    ac2_error += fabs(out - actor2.computeOutVF(sens, ac_empty));\n  }\n  \n  ac1_error /= 100;\n  ac2_error /= 100;\n  \n  LOG_DEBUG(ac1_error << \" \" << ac2_error);\n}\n", "meta": {"hexsha": "9f36f304755ab3cab4b04d91be4b1af515373dd6", "size": 39514, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "agent/old/qlearning-nn/src/test/MLPOptUtest.cpp", "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/old/qlearning-nn/src/test/MLPOptUtest.cpp", "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/old/qlearning-nn/src/test/MLPOptUtest.cpp", "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": 27.0643835616, "max_line_length": 184, "alphanum_fraction": 0.5743280862, "num_tokens": 15106, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4774264249701429}}
{"text": "/*\n * InnerMapTask.cpp\n *\n *  Created on: 25 Jul 2018\n *      Author: scsjd\n */\n\n#include <fstream>\n#include <sstream>\n#include <iterator>\n#include <chrono>\n#include <NTL/ZZ.h>\n#include <NTL/ZZ_p.h>\n#include <NTL/vec_ZZ.h>\n#include <jsoncpp/json/json.h>\n#include \"InnerMapTask.h\"\n#include \"HE1Array.h\"\n\n\nInnerMapTask::InnerMapTask(int numPerLine, const char* parametersPath, const char* inputPath){\n\tthis->inputPath = inputPath;\n\tthis->numPerLine = numPerLine;\n\tparseParameters(parametersPath);\n\ttotalSumTime=0;\n\tnumberAdditions=0;\n\ttotalProductTime=0;\n\tnumberMultiplications=0;\n\tHE1Array::create_device_handle();\n\tHE1Array::create_device_modulus(modulus);\n}\n\nInnerMapTask::~InnerMapTask(){\n\tHE1Array::delete_device_modulus();\n\tHE1Array::delete_device_handle();\n}\n\nvoid InnerMapTask::parseParameters(const char* parametersPath){\n\tNTL::ZZ mod;\n\tstd::ifstream ifs(parametersPath);\n\tif (ifs.is_open()){\n\t\tstd::string json;\n\t\tgetline(ifs,json);\n\t\tJson::Value root;   // will contains the root value after parsing.\n\t\tJson::Reader reader;\n\t\tbool parsingSuccessful = reader.parse(json,root);\n\t\tif (parsingSuccessful){\n\t\t\tmodulus = NTL::conv<NTL::ZZ>(root[\"modulus\"].asCString());\n\t\t}\n\t}\n}\n\nNTL::ZZ InnerMapTask::run(){\n\tstd::ifstream ifs(inputPath);\n\tif (!ifs.is_open()){\n\t\tthrow std::ios_base::failure(\"Could not open input file.\");\n\t}\n\tstd::string line;\n\n\tNTL::vec_ZZ v[numPerLine];\n\n\twhile(getline(ifs,line)){\n\t\tstd::istringstream iss(line);\n\t\tstd::vector<std::string> words((std::istream_iterator<std::string>(iss)),std::istream_iterator<std::string>());\n\t\tfor(int i = 0; i < words.size(); i++){\n\t\t\tNTL::ZZ z = NTL::conv<NTL::ZZ>(words[i].c_str());\n\t\t\tv[i].append(z);\n\t\t}\n\t}\n\tifs.close();\n\n\t//Do multiplication on device\n\tHE1Array prod(v[0]);\n\tnumberMultiplications = v[0].length();\n\tfor (int i=1; i < numPerLine; i++){\n\t\tHE1Array bn(v[i]);\n\t\tauto start = std::chrono::high_resolution_clock::now();\n\t\tprod*=bn;\n\t\tauto finish = std::chrono::high_resolution_clock::now();\n\t\ttotalProductTime += std::chrono::duration_cast<std::chrono::nanoseconds>(finish-start).count();\n\t}\n\n\t//Do prefix sum reduce on CPU because array reduction not supported by xmp\n\tNTL::vec_ZZ products = prod.to_ZZ_vector();\n\tNTL::ZZ_p::init(modulus);\n\tNTL::ZZ_p result;\n\tfor (int i = 0; i < products.length(); i++){\n\t\tauto start = std::chrono::high_resolution_clock::now();\n\t\tresult += NTL::conv<NTL::ZZ_p>(products.at(i));\n\t\tauto finish = std::chrono::high_resolution_clock::now();\n\t\ttotalSumTime += std::chrono::duration_cast<std::chrono::nanoseconds>(finish-start).count();\n\t\tnumberAdditions++;\n\t}\n\n\treturn NTL::rep(result);\n};\n\n\n", "meta": {"hexsha": "ac39d6f25b75f38260b4cf7a4815d0220dd9d4f3", "size": 2599, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/inner_product/inner/src/worker/InnerMapTask_GPU.cpp", "max_stars_repo_name": "TANGO-Project/cryptango", "max_stars_repo_head_hexsha": "be6a2d74d238bffd3f3e899ea0eea01966097ebe", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/inner_product/inner/src/worker/InnerMapTask_GPU.cpp", "max_issues_repo_name": "TANGO-Project/cryptango", "max_issues_repo_head_hexsha": "be6a2d74d238bffd3f3e899ea0eea01966097ebe", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/inner_product/inner/src/worker/InnerMapTask_GPU.cpp", "max_forks_repo_name": "TANGO-Project/cryptango", "max_forks_repo_head_hexsha": "be6a2d74d238bffd3f3e899ea0eea01966097ebe", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.5204081633, "max_line_length": 113, "alphanum_fraction": 0.6979607541, "num_tokens": 741, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.47742642497014287}}
{"text": "#include \"SparseSolverEigenLLT.h\"\n#include <Eigen/SparseCholesky>\n\nstd::vector<double> SparseSolverEigenLLT::solve_Ax_b(SparseMatrix<double> A, SparseVector<double> b, int numel, std::vector<int> & uidx, const std::vector<int> * labels, const std::vector<int> * seeds, int active_label)\n{\n\tSimplicialLLT<SparseMatrix<double> > solver;\n\n\t// Convert to dense format for solver compatibility - this might become a memory issue\n\tVectorXd b_dense = b;\n\n\t// LLT Decomposition\n\tsolver.compute(A);\n\n\t/*if(solver.info()!=true) {\n\t  std::cout << \"Decomposition failed!\\n\";\n\t}*/\n\n\t// Solve system with decomposition\n\tVectorXd x_dense = solver.solve(b_dense);\n\n\t/*if(solver.info()!=true) {\n\t\tstd::cout << \"Solver failed!\\n\";\n\t}*/\n\n\t// solve for another right hand side - good feature for multi-label setup\n\t//x1 = solver.solve(b1);\n\n\t// Holder for saving to external format\n\tstd::vector<double> xmat(numel);\n\n\tfor (int i=0; i<x_dense.rows(); i++)\n\t{\n\t\tdouble val = x_dense(i);\n\t\txmat[uidx[i]] = val;\n\t}\n\n\tfor (int i=0; i<seeds->size(); i++)\n\t{\n\t\tif((*labels)[i] == active_label)\n\t\t\txmat[(*seeds)[i]] = 1.0;\n\t\telse\n\t\t\txmat[(*seeds)[i]] = 0.0;\n\t}\n\n\treturn xmat;\n}", "meta": {"hexsha": "c0902a8ed44a50ba1a671d9a772223c06327e9f8", "size": 1149, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/ConfidenceMapCpp/SparseSolverEigenLLT.cpp", "max_stars_repo_name": "doublechenching/UltrasondConfienceMap", "max_stars_repo_head_hexsha": "e345b3fbf658817e3b4af57e32d5ecb4b7073595", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2019-03-12T08:47:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T18:07:30.000Z", "max_issues_repo_path": "cpp/ConfidenceMapCpp/SparseSolverEigenLLT.cpp", "max_issues_repo_name": "doublechenching/UltrasondConfienceMap", "max_issues_repo_head_hexsha": "e345b3fbf658817e3b4af57e32d5ecb4b7073595", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-06-16T14:29:30.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-16T14:29:30.000Z", "max_forks_repo_path": "cpp/ConfidenceMapCpp/SparseSolverEigenLLT.cpp", "max_forks_repo_name": "doublechenching/UltrasondConfienceMap", "max_forks_repo_head_hexsha": "e345b3fbf658817e3b4af57e32d5ecb4b7073595", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-04-25T03:06:47.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-02T02:59:55.000Z", "avg_line_length": 24.9782608696, "max_line_length": 219, "alphanum_fraction": 0.6684073107, "num_tokens": 349, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4774264249701428}}
{"text": "/* aHAFF.cpp \n   g++ -I/usr/local/include/eigen3 -o aHAF aHAF.cpp -O3\n*/\n\n#include <iostream>\n#include <cstdlib>\n#include <cmath>\n#include <fstream>\n#include <iomanip>\n#include <Eigen/Eigenvalues> \n\nusing namespace std;\nusing namespace Eigen;\n\nint *pl = NULL;\nint *rl = NULL;\nunsigned long int rsn;\ndouble *phi = NULL;\ndouble *phiOld = NULL;\ndouble *phiOlder = NULL;\ndouble *Hphi = NULL;\ndouble *A;\ndouble *B;\nMatrixXd Lanczos;\nSelfAdjointEigenSolver<MatrixXd> es;\nint L,Sztot;\nint maxlen;\ndouble g, oldnorm, norm;\nofstream ofs,ofs2;\n\nvoid initialize(int);\nvoid exit();\nint Sz(unsigned long int);\nint spin(unsigned long int, int);\nint INV(unsigned long int);\nunsigned long int flip(unsigned long int,int);\nbool flippable(unsigned long int,int);\n\nvoid initialize(int opt) {\n  A = new double[200];\n  B = new double[200];\n  pl = new int [L];           // watch zero start !\n  for (int i=0;i<L;i++) {\n    pl[i] = i+1;\n  }\n  pl[L-1] = 0;\n  // allocate memory\n  unsigned long int size=1;   // L!/(L/2)!(L/2)!\n  int L2 = L/2;               // L must be even\n  int j=1;\n  for (int i=L2+1;i<=L;i++) {\n    size = size*i/j;\n    j += 1;\n  }\n  cout << \"     \" <<  endl;\n  double d;\n  cout << \"double: \" << sizeof(d) << endl;\n  cout << \"int: \" << sizeof(j) << endl;\n  cout << \"ulint: \" << sizeof(size) << endl;\n  cout << \"basis size for Sztot=0: \" << size << endl;\n  if (!(phi  = new double[size+1] )) {   // rsn starts from 1 !!\n   cout << \"out of memory\" << endl;\n   exit(1);\n  }\n  if (!(phiOld  = new double[size+1] )) {\n   cout << \"out of memory\" << endl;\n   exit(1);\n  }\n  if (!(phiOlder  = new double[size+1] )) {\n   cout << \"out of memory\" << endl;\n   exit(1);\n  }\n  if (!(Hphi  = new double[size+1] )) {\n   cout << \"out of memory\" << endl;\n   exit(1);\n  }\n  if (!(rl = new int[size+1] )) {\n   cout << \"out of memory\" << endl;\n   exit(1);\n  }\n  // set up relabeled state codes\n  unsigned long int maxnum = 1 << L;   // a dirty trick to get 2^L (cpp does not support pow(int,int)!!\n  cout << \" 2^L = \" << maxnum << endl;\n  rsn = 1;\n  for (unsigned long int sn=0;sn<maxnum;sn++) {\n    if (Sz(sn) == Sztot) {\n      rl[rsn] = sn;\n      rsn++;\n    }\n  }\n  maxlen = rsn - 1;\n  cout << \" basis size for Sztot= \" << Sztot << \" : \" << maxlen << endl;\n  // initial state\n  if (opt == 1){                      // initial state = neel1 + neel2\n    int neel1 = maxnum/3;\n    int neel2 = 2*neel1;\n    for (rsn=1;rsn<=maxlen;rsn++) {\n       phi[rsn] = 0.0;\n    }  \n    phi[INV(neel1)] = 1.0/sqrt(2.0);\n    phi[INV(neel2)] = 1.0/sqrt(2.0);\n    oldnorm = 1.0;\n    if (L == 4) {\n      cout << \"neel1 \" << neel1 << \" inv \" << INV(neel1) << endl;\n      cout << \"neel2 \" << neel2 << \" inv \" << INV(neel2) << endl;\n    }\n  } else {                          // random start\n    int seed;\n    cout << \" enter the random seed \" << endl;\n    cin >> seed;\n    srand(seed);\n    oldnorm = 0.0;\n    for (rsn=1;rsn<=maxlen;rsn++) {\n     phi[rsn] = 2.0*( (double) rand()/RAND_MAX - 0.5);\n     oldnorm = oldnorm + phi[rsn]*phi[rsn];\n    }\n  }\n  // file miscellany\n  ofs2.open(\"aHAFab.dat\");\n  ofs.open(\"aHAFout.dat\");\n  ofs << \"# aHAF.cpp\" << endl;\n  ofs << \"# L = \" << L <<  endl;\n  ofs << \"# g = \" << g << endl;\n  ofs << \"# Sztot = \" << Sztot << endl;\n  if (opt == 1) {\n   ofs << \"# Neel start \" << endl;\n  } else {\n   ofs << \"# random start \" << endl;\n  }\n}\n\n\nvoid exit() {\n  delete [] phi;\n  delete [] phiOld;\n  delete [] phiOlder;\n  delete [] Hphi;\n  delete [] rl;\n  delete [] pl;\n  delete [] A;\n  delete [] B;\n  ofs.close();\n  ofs2.close();\n}\n\nint INV(unsigned long int sn) {\n  // find the state index, rsn, for a state, sn=rl(rsn)\n  unsigned long int mid;\n  unsigned long int low = 1;\n  unsigned long int high = maxlen;\n  st:  mid = (low + high)/2;\n  if (sn ==  rl[mid]) return mid;\n  if (sn <  rl[mid]) {\n    high = mid - 1;\n  } else {\n    low = mid + 1;\n  }\n  goto st;\n}\n\nint spin(unsigned long int sn, int bt) {\n  // return the bt'th bit in sn converted to +-\n  int S = -1;\n  int k = sn & 1 << bt;     \n  if (k != 0) S=1;\n  return S;\n}\n\nint Sz(unsigned long int sn) {\n // compute Sztot for a state sn\n int S=0;\n for (int b=0;b<L;b++) {\n  S += spin(sn,b);\n }\n return S;\n} \n\nint T(unsigned long int rsn) {\n  // compute H0 for a state rsn  (need to divide by 4)\n  int S=0;\n  unsigned long int sn = rl[rsn];\n  for (int bt=0;bt<L;bt++) {\n    S += spin(sn,bt)*spin(sn,pl[bt]);\n  }\n  return S;\n}\n\nunsigned long int flip(unsigned long int rsn, int i) {\n // flip bits i and i+1  using a nasty trick; return a relabeled statecode\n // will fail drastically if b(i) = b(i+1)\n unsigned long int sn = rl[rsn];\n sn ^= 1 << i;\n sn ^= 1 << pl[i];\n return INV(sn);\n}\n\nbool flippable(unsigned long int rsn, int bt) {\n // check if bit i != bit i+1\n bool f = false;\n int b0 = (rl[rsn] >> bt) & 1;\n int b1 = (rl[rsn] >> pl[bt]) & 1;\n if (b0 != b1) f = true;\n return f;\n}\n\n \n\nint main() {\n  int opt;\n  cout << \" enter L, Sztot, g \" << endl;\n  cin >> L >> Sztot >> g;\n  cout << \" enter 1 for Neel start, 2 for random \" << endl;\n  cin >> opt;\n\n  initialize(opt);\n\n  // H{phi}\n  for (rsn=1;rsn<=maxlen;rsn++) {\n   Hphi[rsn] = T(rsn)*phi[rsn]/4.0;\n  }\n  for (rsn=1;rsn<=maxlen;rsn++) {\n   for (int bt=0;bt<L;bt++) {\n    if (flippable(rsn,bt)) {\n     Hphi[flip(rsn,bt)] += g/2.0*phi[rsn];\n    }\n   }\n  }\n\n  double sum = 0.0;\n  for (rsn=1;rsn<=maxlen;rsn++) {\n    sum += phi[rsn]*Hphi[rsn];\n    phiOld[rsn] = phi[rsn];\n  }\n  A[0] = sum/oldnorm;\n  B[0] = 0.0;\n  cout << \" variational  e0 = \" << A[0]/L << endl;\n  ofs << \"0 A: \" << A[0] << endl;\n\n  for (int loop=1;loop<=4*L;loop++) {    // Lanzcos loop  :::::::::::::::::::::::::::\n   for (rsn=1;rsn<=maxlen;rsn++) {\n     phi[rsn] = Hphi[rsn] - A[loop-1]*phiOld[rsn] - B[loop-1]*phiOlder[rsn];\n   }\n   // H{phi}\n   for (rsn=1;rsn<=maxlen;rsn++) {\n    Hphi[rsn] = T(rsn)*phi[rsn]/4.0;\n   }\n   for (rsn=1;rsn<=maxlen;rsn++) {\n    for (int bt=0;bt<L;bt++) {\n     if (flippable(rsn,bt)) {\n      Hphi[flip(rsn,bt)] += g/2.0*phi[rsn];\n     }\n    }\n   }\n   double norm = 0.0;\n   for (rsn=1;rsn<=maxlen;rsn++) {\n     norm += phi[rsn]*phi[rsn];\n   }\n   double sum = 0.0;\n   for (rsn=1;rsn<=maxlen;rsn++) {\n     sum += phi[rsn]*Hphi[rsn];\n   }\n   A[loop] = sum/norm;\n   B[loop] = norm/oldnorm;\n   oldnorm = norm;\n   for (rsn=1;rsn<=maxlen;rsn++) {\n     phiOlder[rsn] = phiOld[rsn];\n     phiOld[rsn] = phi[rsn] ;\n   }\n \n   ofs2 << loop << setprecision(16) << std::fixed << \" A: \" << A[loop] << \" B: \" << B[loop] << endl;\n   // diagonalise\n   Lanczos.resize(loop+1,loop+1);\n   Lanczos.setZero();\n   for (int i=0;i<=loop;i++) {\n     Lanczos(i,i) = A[i];\n   }\n   for (int i=0;i<loop;i++) {\n     Lanczos(i,i+1) = sqrt(B[i+1]);\n     Lanczos(i+1,i) = Lanczos(i,i+1);\n   }\n   es.compute(Lanczos);\n   double lam0 = es.eigenvalues()[0];\n   double lam1 = es.eigenvalues()[1];\n   ofs << loop << setprecision(12) << std::fixed << \" \" << lam0 << \" \" << lam1;\n   if (loop > 3 ) {\n    double lam2 = es.eigenvalues()[2];\n    double lam3 = es.eigenvalues()[3];\n    ofs << \" \" << lam2 << \" \" << lam3;\n   }\n   ofs << endl;\n   cout << loop << setprecision(12) << std::fixed <<  \"\\t e0: \" << lam0/L << \"\\t e1: \" << lam1/L << \"\\t gap: \" << lam1-lam0 << endl;\n  }  // end of Lanczos iteration loop           :::::::::::::::::::::::::::::: \n\n  exit();\n  cout << endl << \" data in aHAFout.dat\" << endl;\n  cout << \" A,B in aHAFab.dat\" << endl << endl;\n  return 0;\n}\n", "meta": {"hexsha": "7f80609661bd187e9632c214cf0e714ea9417d2f", "size": 7319, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CH22/AHAFLANCZOS/aHAF.cpp", "max_stars_repo_name": "acastellanos95/AppCompPhys", "max_stars_repo_head_hexsha": "920a7ba707e92f1ef92fba9d97323863994f0b1a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CH22/AHAFLANCZOS/aHAF.cpp", "max_issues_repo_name": "acastellanos95/AppCompPhys", "max_issues_repo_head_hexsha": "920a7ba707e92f1ef92fba9d97323863994f0b1a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CH22/AHAFLANCZOS/aHAF.cpp", "max_forks_repo_name": "acastellanos95/AppCompPhys", "max_forks_repo_head_hexsha": "920a7ba707e92f1ef92fba9d97323863994f0b1a", "max_forks_repo_licenses": ["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.4782608696, "max_line_length": 132, "alphanum_fraction": 0.5219292253, "num_tokens": 2710, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4774264249701428}}
{"text": "#include <geometry.h>\n#include <tiny.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n\n#include <vector>\n\n\nBOOST_AUTO_TEST_SUITE(geometry);\n\nBOOST_AUTO_TEST_CASE(plane)\n{\n  typedef tiny::MathTypes<float> MT;\n  typedef MT::vector3_type       V;\n  typedef MT::real_type          T;\n  \n  {\n    V const p0 = V::make(1,0,2);\n    V const p1 = V::make(1,1,2);\n    V const p2 = V::make(0,1,2);\n    \n    geometry::Plane<V> P = geometry::make_plane( p0, p1, p2);\n    \n    BOOST_CHECK_CLOSE( P.n()(0), 0.0f, 0.01f );\n    BOOST_CHECK_CLOSE( P.n()(1), 0.0f, 0.01f );\n    BOOST_CHECK_CLOSE( P.n()(2), 1.0f, 0.01f );\n    BOOST_CHECK_CLOSE( P.w(),    2.0f, 0.01f );\n\n    V const q0  = V::make(0,0,4);\n    V const q1  = V::make(0,0,0);\n\n    T const d0 = geometry::get_signed_distance(q0, P);\n    BOOST_CHECK_CLOSE( d0,  2.0f, 0.01f );\n\n    T const d1 = geometry::get_signed_distance(q1, P);\n    BOOST_CHECK_CLOSE( d1,  -2.0f, 0.01f );\n\n    T const a0 = geometry::get_distance(q0, P);\n    BOOST_CHECK_CLOSE( a0,  2.0f, 0.01f );\n\n    T const a1 = geometry::get_distance(q1, P);\n    BOOST_CHECK_CLOSE( a1,  2.0f, 0.01f );\n  }\n  {\n    V const normal = V::make(0,0,1);\n    T const offset = 2.0;\n\n    geometry::Plane<V> P = geometry::make_plane( normal, offset);\n\n    BOOST_CHECK_CLOSE( P.n()(0), 0.0f, 0.01f );\n    BOOST_CHECK_CLOSE( P.n()(1), 0.0f, 0.01f );\n    BOOST_CHECK_CLOSE( P.n()(2), 1.0f, 0.01f );\n    BOOST_CHECK_CLOSE( P.w(),    2.0f, 0.01f );\n  }\n  {\n    V const p0 = V::make(1,0,2);\n    V const p1 = V::make(1,1,2);\n    V const p2 = V::make(0,1,2);\n\n    geometry::Triangle<V> triangle = geometry::make_triangle(p0, p1, p2);\n\n    geometry::Plane<V> P = geometry::make_plane( triangle );\n\n    BOOST_CHECK_CLOSE( P.n()(0), 0.0f, 0.01f );\n    BOOST_CHECK_CLOSE( P.n()(1), 0.0f, 0.01f );\n    BOOST_CHECK_CLOSE( P.n()(2), 1.0f, 0.01f );\n    BOOST_CHECK_CLOSE( P.w(),    2.0f, 0.01f );\n  }\n\n\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "086e3b6bd6cae5bb3d74cfe8baf2e5feeaf8fc91", "size": 2064, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/FOUNDATION/GEOMETRY/unit_tests/geometry_plane/geometry_plane.cpp", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-11-27T09:44:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-13T00:24:21.000Z", "max_issues_repo_path": "PROX/FOUNDATION/GEOMETRY/unit_tests/geometry_plane/geometry_plane.cpp", "max_issues_repo_name": "erleben/matchstick", "max_issues_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_issues_repo_licenses": ["MIT"], "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/FOUNDATION/GEOMETRY/unit_tests/geometry_plane/geometry_plane.cpp", "max_forks_repo_name": "erleben/matchstick", "max_forks_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_forks_repo_licenses": ["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.4615384615, "max_line_length": 73, "alphanum_fraction": 0.6085271318, "num_tokens": 757, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.47742641900929916}}
{"text": "//\n// Created by egrzrbr on 2019-04-26.\n//\n\n#include <stdlib.h>\n#include <stdint.h>\n#include <string.h>\n#include <stdio.h>\n\n#include <boost/numeric/ublas/matrix.hpp>\nusing namespace boost::numeric::ublas;\n\n/**********************************\n * Pseudo-random number generator *\n **********************************/\n\nstatic uint64_t mat_rng[2] = { 11ULL, 1181783497276652981ULL };\n\nstatic inline uint64_t xorshift128plus(uint64_t s[2])\n{\n\tuint64_t x, y;\n\tx = s[0], y = s[1];\n\ts[0] = y;\n\tx ^= x << 23;\n\ts[1] = x ^ y ^ (x >> 17) ^ (y >> 26);\n\ty += s[1];\n\treturn y;\n}\n\ndouble mat_drand(void)\n{\n\treturn (xorshift128plus(mat_rng)>>11) * (1.0/9007199254740992.0);\n}\n\nvoid mat_gen_random_ublas(matrix<float> &m)\n{\n\tsize_t i, j;\n\tfor (i = 0; i < m.size1(); ++i)\n\t\tfor (j = 0; j < m.size2(); ++j)\n\t\t\tm(i, j) = mat_drand();\n}\n\n/*****************\n * Main function *\n *****************/\n\n#include <unistd.h>\n#include <time.h>\n\nint main(int argc, char *argv[])\n{\n\tint c, n = 1000;\n\tclock_t t;\n\n\twhile ((c = getopt(argc, argv, \"n:h\")) >= 0) {\n\t\tif (c == 'n') n = atoi(optarg);\n\t\telse if (c == 'h') {\n\t\t\tfprintf(stderr, \"Usage: mat-eval [options]\\n\");\n\t\t\tfprintf(stderr, \"Options:\\n\");\n\t\t\tfprintf(stderr, \"  -n INT    size of the square matrix [%d]\\n\", n);\n\t\t\tfprintf(stderr, \"  -h        this help message\\n\");\n\t\t\treturn 1;\n\t\t}\n\t}\n\n\tmatrix<float> a(n, n), b(n, n), m(n, n);\n\tmat_gen_random_ublas(a);\n\tmat_gen_random_ublas(b);\n\n\tt = clock();\n\tm = prod(a, b);\n\tfprintf(stderr, \"CPU time: %g\\n\", (double)(clock() - t) / CLOCKS_PER_SEC);\n\tfprintf(stderr, \"Central cell: %g\\n\", m(n/2, n/2));\n\n\treturn 0;\n}\n", "meta": {"hexsha": "4b307d8e103d9ad6449fe22c6c76c593a76902c9", "size": 1586, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/boost/matmul_boost.cpp", "max_stars_repo_name": "robgrzel/Eigen_Boost_OpenMPI_GoogleTests_Examples", "max_stars_repo_head_hexsha": "40e5eb9385ae216529d39b314925106c5766a674", "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/boost/matmul_boost.cpp", "max_issues_repo_name": "robgrzel/Eigen_Boost_OpenMPI_GoogleTests_Examples", "max_issues_repo_head_hexsha": "40e5eb9385ae216529d39b314925106c5766a674", "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/boost/matmul_boost.cpp", "max_forks_repo_name": "robgrzel/Eigen_Boost_OpenMPI_GoogleTests_Examples", "max_forks_repo_head_hexsha": "40e5eb9385ae216529d39b314925106c5766a674", "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": 20.5974025974, "max_line_length": 75, "alphanum_fraction": 0.551702396, "num_tokens": 521, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4774264190092991}}
{"text": "#include <fstream>\n#include <sstream>\n#include <iostream>\n#include <iomanip>\n#include <fmt/format.h>\n#include <string>\n#include <iomanip>\n#include <boost/variant.hpp>\n#include <unordered_map>\n#include <cstdint>\n#include <vector>\nusing gint = std::int64_t;\nusing Coordinate = std::complex<gint>;\nenum Command {\n  TurnRight,\n  TurnLeft\n};\nclass Car\n{\n  std::vector<std::pair<std::complex<gint>, std::complex<gint>>> v_;\n  std::complex<gint> pos_{ 0, 0 };\n  std::complex<gint> direction_{ 1, 0 };\n  std::complex<gint> turn_[2]{\n    { 0, -1 },\n    { 0, 1 }\n  };\n  Coordinate interPoint_{ 0, 0 };\n\npublic:\n  constexpr gint distance() const noexcept\n  {\n    return std::abs(interPoint_.real()) + std::abs(interPoint_.imag());\n  }\n  bool inter(std::pair<Coordinate, Coordinate> l, std::pair<Coordinate, Coordinate> r)\n  {\n    auto linestart = l.first;\n    if (l.first.real() > l.second.real()) {\n      std::swap(l.first, l.second);\n    } else if (l.first.imag() > l.second.imag()) {\n      std::swap(l.first, l.second);\n    }\n    if (r.first.real() > r.second.real()) {\n      std::swap(r.first, r.second);\n    } else if (r.first.imag() > r.second.imag()) {\n      std::swap(r.first, r.second);\n    }\n    auto between = [](auto f, auto l, auto m) {\n      return (f <= m) && (m <= l);\n    };\n    if (l.first.imag() == l.second.imag() && r.first.real() == r.second.real() && between(l.first.real(), l.second.real(), r.first.real()) && between(r.first.imag(), r.second.imag(), l.first.imag())) {\n      interPoint_ = Coordinate(r.first.real(), l.first.imag());\n      if (interPoint_ != linestart) {\n        return true;\n      }\n    } else {\n      swap(l, r);\n      if (l.first.imag() == l.second.imag() && r.first.real() == r.second.real() && between(l.first.real(), l.second.real(), r.first.real()) && between(r.first.imag(), r.second.imag(), l.first.imag())) {\n        interPoint_ = Coordinate(r.first.real(), l.first.imag());\n        if (interPoint_ != linestart) {\n          return true;\n        }\n      }\n    }\n    return false;\n  }\n  bool findinter(std::pair<Coordinate, Coordinate> l)\n  {\n    for (auto r : v_) {\n      if (inter(l, r)) {\n\n        return true;\n      }\n    }\n    return false;\n  }\n\n\n  bool process(Command command, gint value) noexcept\n  {\n    direction_ *= turn_[command];\n\n    auto newpos = pos_ + direction_ * value;\n\n    auto road = std::make_pair(pos_, newpos);\n    if (findinter(road)) {\n      return true;\n    } else {\n      v_.push_back(std::make_pair(pos_, newpos));\n      pos_ = newpos;\n      return false;\n    }\n  }\n};\n\n\nint main(int argc, char **argv)\n{\n  if (argc > 1) {\n    std::ifstream ifs(argv[1]);\n    char c;\n    int forward;\n    Car car;\n    Command com[256];\n    com['L'] = Command::TurnLeft;\n    com['R'] = Command::TurnRight;\n    while (ifs >> c >> forward) {\n      auto r = car.process(com[c], forward);\n      if (r) {\n        fmt::print(\"d:{}\\n\", car.distance());\n        break;\n      }\n    }\n  }\n}", "meta": {"hexsha": "80b268a8a719094bc918214826d5fabcb8d6087c", "size": 2931, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "aoc2016/aoc160102.cpp", "max_stars_repo_name": "jiayuehua/adventOfCode", "max_stars_repo_head_hexsha": "fd47ddefd286fe94db204a9850110f8d1d74d15b", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "aoc2016/aoc160102.cpp", "max_issues_repo_name": "jiayuehua/adventOfCode", "max_issues_repo_head_hexsha": "fd47ddefd286fe94db204a9850110f8d1d74d15b", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "aoc2016/aoc160102.cpp", "max_forks_repo_name": "jiayuehua/adventOfCode", "max_forks_repo_head_hexsha": "fd47ddefd286fe94db204a9850110f8d1d74d15b", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7105263158, "max_line_length": 203, "alphanum_fraction": 0.5687478676, "num_tokens": 819, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4774222343514512}}
{"text": "/*  calculate CMB related observables, depends on Cosmology calculator(s).\n    \n    Shift parameter: R = (1+z*) * DA(z\ufffd6\ufffd5) * sqrt(Omegam) * H0 / c\n    acoustic scale: lA = (1+z*) * Pi * DA(z*) / rs(z*)\n\nwhere z* is the decoupling redshift\n*/\n\n#ifndef __CMB_DISTANCE_PRIOR__\n#define __CMB_DISTANCE_PRIOR__\n\n#include <vector>\n#include <string>\n#include <armadillo>\n#include <imcmc/imcmc.hpp>\n#include \"ParamList.hpp\"\n\nusing namespace imcmc;\n\nstruct Data_CMB_Dist {\n\n    DataInfo data_info;\n    bool use_Hu_fitting;\n    int format;                     // 0--WMAP; 1--Planck\n    arma::rowvec distance_prior;    // {lA,R,zdec}\n    arma::mat covmat_inv;           // inverse of the covariance matrix.\n    void Init( std::string& CMB_dist_prior_dataset );\n\n    Data_CMB_Dist();\n    ~Data_CMB_Dist();\n\n//  add Planck CMB distance prior\n    arma::rowvec distance_prior_plk;    // {R,lA,Omegabh2}\n    arma::mat covmat_inv_plk;           // this (inv-)covariance matrix is different from those from WMAP\n    double std_R, std_lA, std_Obh2;     // 1-sigma errors for {R,lA,Omegabh2}\n};\n\ntypedef Data_CMB_Dist CMB_Dist;\n\n//  likelihood function prototype:\ndouble Prior_CMB_Dist(  imcmc_double&   param,\n                        double&         lndet,\n                        double&         chisq,\n                        void*           model,\n                        void*           data,\n                        istate&         state );\n\n#endif  //  __CMB_DISTANCE_PRIOR__\n", "meta": {"hexsha": "2ba0c95d37578c92a7f78f46f5576c156259069c", "size": 1463, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/CMB.hpp", "max_stars_repo_name": "LBJ-Wade/ClassMC_DE_EoS", "max_stars_repo_head_hexsha": "eaf9e92fcf867377be622d7627ebdba514fe2bac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-04-26T07:17:53.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-31T02:41:06.000Z", "max_issues_repo_path": "include/CMB.hpp", "max_issues_repo_name": "xyh-cosmo/ClassMC", "max_issues_repo_head_hexsha": "eaf9e92fcf867377be622d7627ebdba514fe2bac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/CMB.hpp", "max_forks_repo_name": "xyh-cosmo/ClassMC", "max_forks_repo_head_hexsha": "eaf9e92fcf867377be622d7627ebdba514fe2bac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8571428571, "max_line_length": 105, "alphanum_fraction": 0.5987696514, "num_tokens": 401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4774222343514512}}
{"text": "/*\n * Metric.hpp\n *\n *  Created on: May 18, 2012\n *      Author: david\n */\n\n#ifndef DASP_METRIC_HPP_\n#define DASP_METRIC_HPP_\n\n#include \"Point.hpp\"\n#include <Danvil/Tools/MoreMath.h>\n#include <Danvil/Tools/FunctionCache.h>\n#include <Eigen/Dense>\n\nnamespace dasp\n{\n\n\tnamespace metric\n\t{\n\t\tinline int PixelDistanceSquared(const Point& a, const Point& b) {\n\t\t\tconst int dx = a.px - b.px;\n\t\t\tconst int dy = a.py - b.py;\n\t\t\treturn dx*dx + dy*dy;\n\t\t}\n\n\t\tinline float ImageDistanceRaw(const Point& x, const Point& y) {\n\t\t\treturn static_cast<float>(PixelDistanceSquared(x,y)) / (y.cluster_radius_px * y.cluster_radius_px);\n\t\t}\n\n\t\tinline float SpatialDistanceRaw(const Eigen::Vector3f& x, const Eigen::Vector3f& y) {\n\t\t\treturn (x - y).squaredNorm();\n\t\t}\n\n\t\tinline float SpatialDistanceRaw(const Point& x, const Point& y) {\n\t\t\treturn SpatialDistanceRaw(x.position, y.position);\n\t\t}\n\n\t\tinline float ColorDistanceRaw(const Eigen::Vector3f& u, const Eigen::Vector3f& v) {\n\t\t\treturn (u - v).squaredNorm();\n\t\t}\n\n\t\tinline float ColorDistanceRaw(const Point& u, const Point& v) {\n\t\t\treturn ColorDistanceRaw(u.color, v.color);\n\t\t}\n\n\t\tinline float NormalDistanceRaw(const Eigen::Vector3f& u, const Eigen::Vector3f& v) {\n\t\t\t// this is an approximation to the angle between the normals\n\t\t\treturn 1.0f - u.dot(v);\n\t\t}\n\n\t\tinline float NormalDistanceRaw(const Point& u, const Point& v) {\n\t\t\treturn NormalDistanceRaw(u.normal, v.normal);\n\t\t}\n\n\t\tinline float NormalDistanceWithDepth(const Point& u, const Point& v) {\n\t\t\tconst float q = NormalDistanceRaw(u.normal, v.normal);\n\t\t\treturn 2.0f * q / (u.position.z() + v.position.z());\n\t\t}\n\n\t}\n\n\t/** Computes the density-adaptive distance from a point to a center point\n\t * - uses pixel distance and color metric\n\t * - Takes the density at the center point\n\t */\n\tstruct DensityAdaptiveMetric_UxRGB\n\t{\n\t\tDensityAdaptiveMetric_UxRGB(float w_u, float w_c) {\n\t\t\tweights_ = {\n\t\t\t\tw_u,\n\t\t\t\tw_c };\n\t\t}\n\n\t\tfloat operator()(const Point& p, const Point& q) const {\n\t\t\treturn weights_.dot(\n\t\t\t\t\tEigen::Vector2f(\n\t\t\t\t\t\t\tmetric::ImageDistanceRaw(p, q),\n\t\t\t\t\t\t\tmetric::ColorDistanceRaw(p, q)));\n\t\t}\n\n\tprivate:\n\t\tEigen::Vector2f weights_;\n\t};\n\n\t/** Computes the density-adaptive distance from a point to a center point\n\t * - uses pixel distance, color metric and depth difference\n\t * - Takes the density at the center point\n\t */\n\tstruct DensityAdaptiveMetric_UxRGBxD\n\t{\n\t\tDensityAdaptiveMetric_UxRGBxD(float w_u, float w_c, float w_d) {\n\t\t\tweights_ = {\n\t\t\t\tw_u,\n\t\t\t\tw_c,\n\t\t\t\tw_d };\n\t\t}\n\n\t\tfloat operator()(const Point& p, const Point& q) const {\n\t\t\treturn weights_.dot(\n\t\t\t\t\tEigen::Vector3f(\n\t\t\t\t\t\t\tmetric::ImageDistanceRaw(p, q),\n\t\t\t\t\t\t\tmetric::ColorDistanceRaw(p, q),\n\t\t\t\t\t\t\tstd::abs(p.depth() - q.depth())));\n\t\t}\n\n\tprivate:\n\t\tEigen::Vector3f weights_;\n\t};\n\n\t/** Computes the depth-adaptive distance from a point to a center point\n\t * - Takes the density at the center point\n\t * - Uses 3D position instead of pixel position\n\t * - Additionally uses normals.\n\t */\n\tstruct DepthAdaptiveMetric\n\t{\n\t\tDepthAdaptiveMetric(float w_r, float w_c, float w_n, float R) {\n\t\t\tweights_ = {\n\t\t\t\tw_r / (R * R),\n\t\t\t\tw_c,\n\t\t\t\tw_n };\n\t\t}\n\n\t\tfloat operator()(const Point& p, const Point& q) const {\n\t\t\treturn weights_.dot(\n\t\t\t\t\tEigen::Vector3f(\n\t\t\t\t\t\t\tmetric::SpatialDistanceRaw(p, q),\n\t\t\t\t\t\t\tmetric::ColorDistanceRaw(p, q),\n\t\t\t\t\t\t\tmetric::NormalDistanceWithDepth(p, q)));\n\t\t}\n\n\tprivate:\n\t\tEigen::Vector3f weights_;\n\t};\n\n\ttemplate<bool SupressConvexEdges=true>\n\tstruct ClassicSpectralAffinity\n\t{\n\t\tClassicSpectralAffinity(unsigned int num_superpixels, float superpixel_radius, float w_spatial=1.0f, float w_color=1.0f, float w_normal=1.0f)\n\t\t: num_superpixels_(num_superpixels),\n\t\t  superpixel_radius_(superpixel_radius)\n\t\t{\n\t\t\tscl_spatial_ = w_spatial / (4.0f * superpixel_radius_ * superpixel_radius_);\n\t\t\tscl_color_ = w_color / (std::sqrt(static_cast<float>(num_superpixels_)) * cWeightRho);\n\t\t\tscl_normal_ = w_normal;\n\t\t}\n\n\t\tfloat operator()(const Point& x, const Point& y) const {\n\t\t\tconst Eigen::Vector3f& x_pos = x.position;\n\t\t\tconst Eigen::Vector3f& y_pos = y.position;\n\t\t\tconst Eigen::Vector3f& x_col = x.color;\n\t\t\tconst Eigen::Vector3f& y_col = y.color;\n\t\t\tconst Eigen::Vector3f& x_norm = x.normal;\n\t\t\tconst Eigen::Vector3f& y_norm = y.normal;\n\t\t\t// spatial distance\n\t\t\tfloat scl_d_spatial = metric::SpatialDistanceRaw(x_pos, y_pos) * scl_spatial_;\n\t\t\tscl_d_spatial = std::max(0.0f, scl_d_spatial - 1.2f); // distance of 1 indicates estimated distance\n\t\t\t// color distance\n\t\t\tfloat d_color = metric::ColorDistanceRaw(x_col, y_col);\n\t\t\t// normal distance\n\t\t\tfloat d_normal;\n\t\t\tif(SupressConvexEdges) {\n\t\t\t\t// only use concave edges\n\t\t\t\tEigen::Vector3f d = y_pos - x_pos;\n\t\t\t\td_normal = (x_norm - y_norm).dot(d) * Danvil::MoreMath::FastInverseSqrt(d.squaredNorm());\n\t\t\t\td_normal = std::max(0.0f, d_normal);\n\t\t\t}\n\t\t\telse {\n\t\t\t\td_normal = metric::NormalDistanceRaw(x_norm, y_norm);\n\t\t\t}\n\t\t\t// compute total edge connectivity\n\t\t\tfloat d_combined = scl_d_spatial + scl_color_*d_color + scl_normal_*d_normal;\n\t\t\treturn exp_cache_(d_combined);\n\t\t}\n\n\tprivate:\n\t\tstatic constexpr float cWeightRho = 0.01f; // 640x480 clusters would yield 0.1 which is used in gPb\n\t\tunsigned int num_superpixels_;\n\t\tfloat superpixel_radius_;\n\t\tfloat scl_spatial_;\n\t\tfloat scl_color_;\n\t\tfloat scl_normal_;\n\t\tDanvil::ExpNegFunctionCache<float> exp_cache_; // used for std::exp(-x)\n\t};\n\n\tstruct ImprovedSpectralAffinity\n\t{\n\t\tImprovedSpectralAffinity(float superpixel_radius,\n\t\t\tfloat w_spatial=1.0f, float w_color=1.0f, float w_normal=1.0f)\n\t\t: superpixel_radius_(superpixel_radius),\n\t\t  ww_(w_spatial), wc_(w_color), wn_(w_normal)\n\t\t{\n\t\t\tfloat w_total = ww_ + wc_ + wn_;\n\t\t\tww_ /= w_total;\n\t\t\twc_ /= w_total;\n\t\t\twn_ /= w_total;\n\t\t}\n\n\t\tfloat operator()(const Cluster& x, const Cluster& y) const {\n\t\t\tconst Eigen::Vector3f& x_pos = x.center.position;\n\t\t\tconst Eigen::Vector3f& y_pos = y.center.position;\n\t\t\tconst Eigen::Vector3f& x_col = x.center.color;\n\t\t\tconst Eigen::Vector3f& y_col = y.center.color;\n\t\t\tconst Eigen::Vector3f& x_norm = x.center.normal;\n\t\t\tconst Eigen::Vector3f& y_norm = y.center.normal;\n\t\t\t// spatial distance\n\t\t\tfloat dw = (x_pos - y_pos).squaredNorm() / (4.0f * superpixel_radius_ * superpixel_radius_);\n\t\t\tdw = std::max(0.0f, dw - 1.2f); // distance of 1 indicates estimated distance\n\t\t\t// color distance\n\t\t\tfloat dc = 3.2f * (x_col - y_col).squaredNorm();\n\t\t\t// normal distance (only use concave edges)\n\t\t\tEigen::Vector3f u = y_pos - x_pos;\n\t\t\tfloat dn = (x_norm - y_norm).dot(u) / u.norm();\n\t\t\tdn = std::max(0.0f, dn);\n\t\t\t// compute total edge connectivity\n\t\t\tfloat d = ww_*dw + wc_*dc + wn_*dn;\n\t\t\treturn exp_cache_(d);\n\t\t}\n\n\tprivate:\n\t\tfloat superpixel_radius_;\n\t\tfloat ww_, wc_, wn_;\n\t\tDanvil::ExpNegFunctionCache<float> exp_cache_; // used for std::exp(-x)\n\t};\t\n\n\tstruct ClassicSpectralAffinitySLIC\n\t{\n\t\tClassicSpectralAffinitySLIC(unsigned int num_superpixels, float w_color=1.0f)\n\t\t: num_superpixels_(num_superpixels),\n\t\t  w_color(w_color)\n\t\t{}\n\n\t\tfloat operator()(const Point& x, const Point& y) const {\n\t\t\tfloat w_maha_color = 4.0f * metric::ColorDistanceRaw(x, y) / (std::sqrt(static_cast<float>(num_superpixels_)) * cWeightRho);\n\t\t\treturn std::exp(-w_color*w_maha_color);\n\t\t}\n\n\tprivate:\n\t\tstatic constexpr float cWeightRho = 0.01f; // 640x480 clusters would yield 0.1 which is used in gPb\n\t\tunsigned int num_superpixels_;\n\t\tfloat w_color;\n\t};\n\n}\n\n#endif\n", "meta": {"hexsha": "c3d06c1ad1e334a6f45b5a100d5538b1bf3e45a3", "size": 7353, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib_dasp/lib_dasp/Metric.hpp", "max_stars_repo_name": "jbellis/superpixel-benchmark", "max_stars_repo_head_hexsha": "81a45649d426751d1ae450ef8ea0d2d9c7b3545f", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 344.0, "max_stars_repo_stars_event_min_datetime": "2016-12-16T10:11:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T06:08:14.000Z", "max_issues_repo_path": "lib_dasp/lib_dasp/Metric.hpp", "max_issues_repo_name": "jbellis/superpixel-benchmark", "max_issues_repo_head_hexsha": "81a45649d426751d1ae450ef8ea0d2d9c7b3545f", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2018-02-15T19:34:19.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-31T17:04:48.000Z", "max_forks_repo_path": "lib_dasp/lib_dasp/Metric.hpp", "max_forks_repo_name": "jbellis/superpixel-benchmark", "max_forks_repo_head_hexsha": "81a45649d426751d1ae450ef8ea0d2d9c7b3545f", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 111.0, "max_forks_repo_forks_event_min_datetime": "2016-12-08T07:19:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T06:08:16.000Z", "avg_line_length": 29.6491935484, "max_line_length": 143, "alphanum_fraction": 0.6920984632, "num_tokens": 2201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4774222294202612}}
{"text": "//==================================================================================================\n/*!\n  @file\n  @copyright 2015 NumScale SAS\n  @copyright 2015 J.T. Lapreste\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_COMMON_FUNCTION_SCALAR_GAMMA_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_FUNCTION_SCALAR_GAMMA_HPP_INCLUDED\n\n#include <boost/simd/function/std.hpp>\n#include <boost/config.hpp>\n#include <boost/simd/arch/common/detail/generic/gamma_kernel.hpp>\n#include <boost/simd/constant/half.hpp>\n#include <boost/simd/constant/inf.hpp>\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/constant/three.hpp>\n#include <boost/simd/constant/two.hpp>\n#include <boost/simd/function/scalar/abs.hpp>\n#include <boost/simd/function/scalar/copysign.hpp>\n#include <boost/simd/function/scalar/floor.hpp>\n#include <boost/simd/function/scalar/is_eqz.hpp>\n#include <boost/simd/function/scalar/is_even.hpp>\n#include <boost/simd/function/scalar/is_ltz.hpp>\n#include <boost/simd/function/scalar/sinpi.hpp>\n#include <boost/simd/function/scalar/stirling.hpp>\n\n#include <boost/dispatch/function/overload.hpp>\n#include <cmath>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  namespace bs = boost::simd;\n  using bs::std_tag;\n  BOOST_DISPATCH_OVERLOAD ( gamma_\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      if (is_eqz(a0)) return copysign(Inf<A0>(), a0);\n      #ifndef BOOST_SIMD_NO_INVALIDS\n      if( is_nan(a0) || (a0 == Minf<A0>()) ) return Nan<A0>();\n      if (a0 == Inf<A0>()) return a0;\n      #endif\n\n      A0 x = a0;\n      A0 q = bs::abs(x);\n      if(x < A0(-33.0))\n      {\n        return std::tgamma(a0);\n        A0 st = stirling(q);\n        A0 p =  floor(q);\n        auto iseven =  is_even((int32_t)p);\n        if (p == q) return Nan<A0>();\n        A0 z = q - p;\n        if( z > Half<A0>() )\n        {\n          p += One<A0>();\n          z = q - p;\n        }\n        z = q*sinpi(z);\n        if( is_eqz(z) ) return Nan<A0>();\n        st = Pi<A0>()/(bs::abs(z)*st);\n        return iseven  ? -st : st;\n      }\n      A0 z = One<A0>();\n      while( x >= Three<A0>() )\n      {\n        x -= One<A0>();\n        z *= x;\n      }\n      while( is_ltz(x) )\n      {\n        z /= x;\n        x += One<A0>();\n      }\n      while( x < Two<A0>() )\n      {\n        if( is_eqz(x)) return Nan<A0>();\n        z /= x;\n        x +=  One<A0>();\n      }\n      if( x == Two<A0>() ) return(z);\n      x -= Two<A0>();\n      return z*detail::gamma_kernel<A0>::gamma1(x);\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( gamma_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_< bd::floating_<A0> >\n                          , bs::std_tag\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() (A0 a0, std_tag const&) const BOOST_NOEXCEPT\n    {\n      return std::tgamma(a0);\n    }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "e480f52befdf1032e43a888dc2dc1c9de515627f", "size": 3386, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arch/common/scalar/function/gamma.hpp", "max_stars_repo_name": "yaeldarmon/boost.simd", "max_stars_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/simd/arch/common/scalar/function/gamma.hpp", "max_issues_repo_name": "yaeldarmon/boost.simd", "max_issues_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/arch/common/scalar/function/gamma.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": 29.701754386, "max_line_length": 100, "alphanum_fraction": 0.5245126994, "num_tokens": 887, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4774222294202612}}
{"text": "//\n//  GridRaycast.hpp\n//  PinkTopaz\n//\n//  Created by Andrew Fox on 11/18/17.\n//\n//\n\n#ifndef GridRaycast_hpp\n#define GridRaycast_hpp\n\n#include \"Ray.hpp\"\n#include <vector>\n#include <glm/vec3.hpp>\n#include <boost/coroutine2/all.hpp>\n\n\nnamespace GridRaycastRange {\n\n// Iterate over cells which fall within the specified frustum.\ninline void\nraycast(boost::coroutines2::coroutine<glm::vec3>::push_type &sink,\n        const Ray &ray,\n        size_t maxDepth)\n{\n    /* Implementation is based on:\n     * \"A Fast Voxel Traversal Algorithm for Ray Tracing\"\n     * John Amanatides, Andrew Woo\n     * http://www.cse.yorku.ca/~amana/research/grid.pdf\n     *\n     * See also: http://www.xnawiki.com/index.php?title=Voxel_traversal\n     */\n    \n    // NOTES:\n    // * This code assumes that the ray's position and direction are in 'cell coordinates', which means\n    //   that one unit equals one cell in all directions.\n    // * When the ray doesn't start within the voxel grid, calculate the first position at which the\n    //   ray could enter the grid. If it never enters the grid, there is nothing more to do here.\n    // * Also, it is important to test when the ray exits the voxel grid when the grid isn't infinite.\n    // * The Point3D structure is a simple structure having three integer fields (X, Y and Z).\n    \n    // The cell in which the ray starts.\n    int x = (int)ray.origin.x;\n    int y = (int)ray.origin.y;\n    int z = (int)ray.origin.z;\n    \n    // Determine which way we go.\n    int stepX = (ray.direction.x<0) ? -1 : (ray.direction.x==0) ? 0 : +1;\n    int stepY = (ray.direction.y<0) ? -1 : (ray.direction.y==0) ? 0 : +1;\n    int stepZ = (ray.direction.z<0) ? -1 : (ray.direction.z==0) ? 0 : +1;\n    \n    // Calculate cell boundaries. When the step (i.e. direction sign) is positive,\n    // the next boundary is AFTER our current position, meaning that we have to add 1.\n    // Otherwise, it is BEFORE our current position, in which case we add nothing.\n    glm::ivec3 cellBoundary(x + (stepX > 0 ? 1 : 0),\n                            y + (stepY > 0 ? 1 : 0),\n                            z + (stepZ > 0 ? 1 : 0));\n    \n    // NOTE: For the following calculations, the result will be Single.PositiveInfinity\n    // when ray.Direction.X, Y or Z equals zero, which is OK. However, when the left-hand\n    // value of the division also equals zero, the result is Single.NaN, which is not OK.\n    \n    // Determine how far we can travel along the ray before we hit a voxel boundary.\n    glm::vec3 tMax((cellBoundary.x - ray.origin.x) / ray.direction.x,    // Boundary is a plane on the YZ axis.\n                   (cellBoundary.y - ray.origin.y) / ray.direction.y,    // Boundary is a plane on the XZ axis.\n                   (cellBoundary.z - ray.origin.z) / ray.direction.z);   // Boundary is a plane on the XY axis.\n    if (isnan(tMax.x)) { tMax.x = +INFINITY; }\n    if (isnan(tMax.y)) { tMax.y = +INFINITY; }\n    if (isnan(tMax.z)) { tMax.z = +INFINITY; }\n    \n    // Determine how far we must travel along the ray before we have crossed a gridcell.\n    glm::vec3 tDelta(stepX / ray.direction.x,                    // Crossing the width of a cell.\n                     stepY / ray.direction.y,                    // Crossing the height of a cell.\n                     stepZ / ray.direction.z);                   // Crossing the depth of a cell.\n    if (isnan(tDelta.x)) { tDelta.x = +INFINITY; }\n    if (isnan(tDelta.y)) { tDelta.y = +INFINITY; }\n    if (isnan(tDelta.z)) { tDelta.z = +INFINITY; }\n    \n    // For each step, determine which distance to the next voxel boundary is lowest (i.e.\n    // which voxel boundary is nearest) and walk that way.\n    for (size_t i = 0; i < maxDepth; ++i) {\n        sink(glm::vec3(x, y, z));\n        \n        // Do the next step.\n        if (tMax.x < tMax.y && tMax.x < tMax.z) {\n            // tMax.X is the lowest, an YZ cell boundary plane is nearest.\n            x += stepX;\n            tMax.x += tDelta.x;\n        } else if (tMax.y < tMax.z) {\n            // tMax.Y is the lowest, an XZ cell boundary plane is nearest.\n            y += stepY;\n            tMax.y += tDelta.y;\n        } else {\n            // tMax.Z is the lowest, an XY cell boundary plane is nearest.\n            z += stepZ;\n            tMax.z += tDelta.z;\n        }\n    }\n}\n\n} // namespace GridRaycastRange\n\n\n// Return a range to iterate over grid cells which fall on the specified ray.\n// The ray is specified in world space coordinates.\ninline boost::coroutines2::coroutine<glm::vec3>::pull_type\nslice(const GridIndexer &grid,\n      const Ray &ray,\n      size_t maxDepth)\n{\n    if constexpr (EnableVerboseBoundsChecking) {\n        if (!grid.inbounds(ray.origin)) {\n            throw OutOfBoundsException(fmt::format(\"OutOfBoundsException -- grid.boundingBox={} ; ray.origin={}\",\n                                                   grid.boundingBox(),\n                                                   glm::to_string(ray.origin)));\n        }\n    }\n    \n#if 0\n    // TODO: Fix the conversion from world-space ray to cell-space direction.\n    // Convert the world-space ray direction to a cell-space direction.\n    const AABB box = grid.boundingBox();\n    const glm::vec3 mins = box.mins();\n    const glm::vec3 p = (ray.direction - mins) / (box.extent*2.0f);\n    const glm::ivec3 res = grid.gridResolution();\n    const glm::vec3 ccDir(glm::normalize(glm::vec3(p.x * res.x, p.y * res.y, p.z * res.z)));\n    \n    // Convert the world-space ray origin to cell-space.\n    const glm::ivec3 iccOrigin = grid.cellCoordsAtPoint(ray.origin);\n    const glm::vec3 ccOrigin(iccOrigin.x, iccOrigin.y, iccOrigin.z);\n    \n    return boost::coroutines2::coroutine<glm::vec3>::pull_type([&](boost::coroutines2::coroutine<glm::vec3>::push_type &sink){\n        GridRaycastRange::raycast(sink, Ray(ccOrigin, ccDir), maxDepth);\n    });\n#else\n    return boost::coroutines2::coroutine<glm::vec3>::pull_type([&](boost::coroutines2::coroutine<glm::vec3>::push_type &sink){\n        GridRaycastRange::raycast(sink, ray, maxDepth);\n    });\n#endif\n}\n\n\n#endif /* GridRaycast_hpp */\n", "meta": {"hexsha": "da0bcb7f7ec060989fed0ce4fe6ae2d8da0168ae", "size": 6069, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/include/Grid/GridRaycast.hpp", "max_stars_repo_name": "foxostro/PinkTopaz", "max_stars_repo_head_hexsha": "cd8275a93ea34a56f640f915d4b6c769e82e9dc2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-10-30T22:49:06.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-30T22:49:06.000Z", "max_issues_repo_path": "src/include/Grid/GridRaycast.hpp", "max_issues_repo_name": "foxostro/PinkTopaz", "max_issues_repo_head_hexsha": "cd8275a93ea34a56f640f915d4b6c769e82e9dc2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/include/Grid/GridRaycast.hpp", "max_forks_repo_name": "foxostro/PinkTopaz", "max_forks_repo_head_hexsha": "cd8275a93ea34a56f640f915d4b6c769e82e9dc2", "max_forks_repo_licenses": ["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.1458333333, "max_line_length": 126, "alphanum_fraction": 0.6076783655, "num_tokens": 1601, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.4774222294202611}}
{"text": "/*\n * File: pybind.cc\n * Created Date: 2019-09-11\n * Author: Lei Pan\n * Contact: <panlei7@gmail.com>\n *\n * Last Modified: Wednesday September 25th 2019 11:37:53 am\n *\n * MIT License\n *\n * Copyright (c) 2019 Lei Pan\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 * HISTORY:\n * Date      \t By\tComments\n * ----------\t---\n * ----------------------------------------------------------\n */\n\n#include \"fast_hankel_transform.hpp\"\n\n#include <Eigen/Dense>\n#include <pybind11/complex.h>\n#include <pybind11/eigen.h>\n#include <pybind11/pybind11.h>\n\nnamespace py = pybind11;\nusing namespace Eigen;\nusing CRefCMat = const Ref<const MatrixXd>;\n\nPYBIND11_MODULE(fhtcxx, m) {\n  py::class_<FastHankelTransform>(m, \"FastHankelTransform\")\n      .def(py::init<int, double, double>())\n      .def(\"sampling\", &FastHankelTransform::sampling)\n      .def(\"set_feval\", &FastHankelTransform::set_feval)\n      .def(\"calculate\", &FastHankelTransform::calculate);\n}", "meta": {"hexsha": "633512a2d62cf524aa015b15f09832f258935039", "size": 1971, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/pybind.cc", "max_stars_repo_name": "pan3rock/fast-hankel-transform", "max_stars_repo_head_hexsha": "c06edff4d0f42c250e5fda1a4eeb9c3800ab213c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-08-13T12:05:06.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-13T12:05:06.000Z", "max_issues_repo_path": "src/pybind.cc", "max_issues_repo_name": "pan3rock/fast-hankel-transform", "max_issues_repo_head_hexsha": "c06edff4d0f42c250e5fda1a4eeb9c3800ab213c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pybind.cc", "max_forks_repo_name": "pan3rock/fast-hankel-transform", "max_forks_repo_head_hexsha": "c06edff4d0f42c250e5fda1a4eeb9c3800ab213c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-06-16T09:56:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-09T00:43:38.000Z", "avg_line_length": 36.5, "max_line_length": 80, "alphanum_fraction": 0.7037037037, "num_tokens": 473, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081926, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.47739223809083303}}
{"text": "\n// BLAS level 1 (matrix rows and columns) \n\n//#define BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n\n#include <iostream>\n#include <boost/numeric/bindings/ublas/vector.hpp>\n#include <boost/numeric/bindings/ublas/matrix.hpp>\n#include <boost/numeric/bindings/ublas/matrix_proxy.hpp>\n#include <boost/numeric/bindings/ublas/vector_proxy.hpp>\n#include <boost/numeric/bindings/blas/level1.hpp>\n#include \"utils.h\"\n\nnamespace blas = boost::numeric::bindings::blas;\nnamespace bindings = boost::numeric::bindings;\nnamespace ublas = boost::numeric::ublas;\n\nusing std::cout;\nusing std::endl; \nusing std::size_t; \n\ntypedef ublas::vector<double> vct_t;\ntypedef ublas::matrix<double> matr_t;\ntypedef ublas::matrix_row<matr_t> mr_t;\ntypedef ublas::matrix_column<matr_t> mc_t;\ntypedef ublas::matrix_range<matr_t> mrng_t;\ntypedef ublas::matrix_slice<matr_t> msl_t;\ntypedef ublas::matrix_slice<matr_t const> cmsl_t;\n\nint main() {\n\n  cout << endl; \n\n  int r = 7; \n  int c = 8; \n  matr_t m (r, c);\n  init_m (m, times_plus<double> (10, 1, 1)); \n  print_m (m, \"m\"); \n  cout << endl; \n\n  vct_t v (10);\n  blas::set (0., v); \n  print_v (v, \"v\"); \n  cout << endl; \n\n  // m[2,.] <- 0.1 m[2,.]\n  mr_t mr2 (m, 2); \n  blas::scal (0.1, mr2);\n  print_m (m, \"0.1 m[2,.]\"); \n  cout << endl; \n  \n  // m[2,.] <-> m[4,.]\n  mr_t mr4 (m, 4);\n  blas::swap (mr2, mr4);\n  print_m (m, \"m[2,.] <-> m[4,.]\"); \n  cout << endl; \n\n  // m[4,.] <- m[2,.]\n  blas::copy (mr2, mr4);\n  print_m (m, \"m[4,.] <- m[2,.]\"); \n  cout << endl; \n\n  // v[2..6] <- 10 m[5,.][1..5]\n  mr_t mr5 (m, 5); \n  ublas::vector_range<vct_t> vr (v, ublas::range (2, 6)); \n  ublas::vector_range<mr_t> mr5r (mr5, ublas::range (1, 5)); \n  blas::axpy (10.0, mr5r, vr);\n  print_v (v, \"v[2..6] <- 10 m[5,.][1..5]\"); \n  cout << endl; \n\n  // ||m[.,3]||_1, ||m[.,3]||_2\n  mc_t mc3 (m, 3); \n  cout << \"||m[.,3]||_1 = \" << blas::asum (mc3) << endl; \n  cout << \"||m[.,3]||_2 = \" << blas::nrm2 (mc3) << endl; \n  cout << endl; \n  \n  // m[.,5] <- 0.01 m[.,3] + m[.,5]\n  mc_t mc5 (m, 5); \n  blas::axpy (0.01, mc3, mc5); \n  print_m (m, \"m[.,5] <- 0.01 m[.,3] + m[.,5]\"); \n  cout << endl; \n\n  // 0.1 m[.,5][1:2:3]\n  ublas::vector_slice<mc_t> mc5s (mc5, ublas::slice (1, 2, 3)); \n  blas::scal (0.1, mc5s); \n  print_m (m, \"0.1 m[.,5][1:2:3]\"); \n  cout << endl; \n\n  // 0.1 m[4,.][1:2:4][1..3]\n  ublas::vector_slice<mr_t> mr4s (mr4, ublas::slice (1, 2, 4));\n  ublas::vector_range<ublas::vector_slice<mr_t> >\n    mr4sr (mr4s, ublas::range (1, 3)); \n  blas::scal (0.1, mr4sr); \n  print_m (m, \"0.1 m[4,.][1:2:4][1..3]\"); \n  cout << endl; \n\n  // new initialization\n  init_m (m, times_plus<double> (10, 1, 1)); \n#ifndef F_USE_DETAIL\n  for (int i = 0; i < m.size1(); ++i) {\n    mr_t mri (m, i); \n    blas::scal (0.1, mri);\n  }\n#else\n  // cblas level 1 function applied to matrix\n  blas::detail::scal (traits::matrix_storage_size (m),\n                       0.1, traits::matrix_storage (m), 1); \n#endif \n  matr_t const cm (m); \n  print_m (cm, \"new m, cm == const m\"); \n  cout << endl; \n\n  // m[2..6][1..8]\n  mrng_t mrng (m, ublas::range (2, 6), ublas::range (1, 8)); \n  print_m (mrng, \"mrng = m[2..6][1..8]\"); \n  cout << endl; \n  \n  // mrng[1,.] <-> mrng[2,.]\n  ublas::matrix_row<mrng_t> mrngr1 (mrng, 1); \n  ublas::matrix_row<mrng_t> mrngr2 (mrng, 2); \n  blas::swap (mrngr1, mrngr2); \n  print_m (m, \"mrng[1,.] <-> mrng[2,.]\"); \n  cout << endl; \n\n  // mrng[2,.] <-> mrng[1,.]\n  blas::swap (mrngr2, mrngr1); \n  print_m (m, \"mrng[2,.] <-> mrng[1,.]\"); \n  cout << endl; \n\n  // mrng[.,3] <- 0.01 mrng[.,5] + mrng[.,3]\n  ublas::matrix_column<mrng_t> mrngc3 (mrng, 3);\n  ublas::matrix_column<mrng_t> const mrngc5 (mrng, 5);\n  blas::axpy (0.01, mrngc5, mrngc3); \n  print_m (m, \"mrng[.,3] <- 0.01 mrng[.,5] + mrng[.,3]\"); \n  cout << endl; \n\n  // cm[1:2:3][2:3:2] \n  cmsl_t msl (cm, ublas::slice (1, 2, 3), ublas::slice (2, 3, 2)); \n  print_m (msl, \"cmsl = cm[1:2:3][2:3:2]\"); \n  cout << endl; \n\n  // ||cmsl[.,0]||_1\n  ublas::matrix_column<cmsl_t> mslc0 (msl, 0); \n  cout << \"||cmsl[.,0]||_1 = \" << blas::asum (mslc0) << endl;\n  cout << endl; \n\n  // mrng[.,3][1..4] <= 0.0001 cmsl[.,0] + mrng[.,3][1..4]\n  ublas::vector_range<ublas::matrix_column<mrng_t> >\n    vrmrngc3 (mrngc3, ublas::range (1, 4));\n  blas::axpy (0.0001, mslc0, vrmrngc3); \n  print_m (m, \"mrng[.,3][1..4] <= 0.0001 cmsl[.,0] + mrng[.,3][1..4]\"); \n  cout << endl; \n\n}\n", "meta": {"hexsha": "cc14283c523dba86f218db0cba2bd14e96b2cabe", "size": 4309, "ext": "cc", "lang": "C++", "max_stars_repo_path": "externals/numeric_bindings/libs/numeric/bindings/atlas/ublas_matr1.cc", "max_stars_repo_name": "ljktest/siconos", "max_stars_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 137.0, "max_stars_repo_stars_event_min_datetime": "2015-06-16T15:55:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T06:01:59.000Z", "max_issues_repo_path": "externals/numeric_bindings/libs/numeric/bindings/atlas/ublas_matr1.cc", "max_issues_repo_name": "ljktest/siconos", "max_issues_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 381.0, "max_issues_repo_issues_event_min_datetime": "2015-09-22T15:31:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-14T09:05:23.000Z", "max_forks_repo_path": "externals/numeric_bindings/libs/numeric/bindings/atlas/ublas_matr1.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": 27.8, "max_line_length": 72, "alphanum_fraction": 0.5558134138, "num_tokens": 1886, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.47739223376511125}}
{"text": "// ---------------------------------------------------------------------\n//\n// Copyright (c) 2017 - 2019 by the IBAMR developers\n// All rights reserved.\n//\n// This file is part of IBAMR.\n//\n// IBAMR is free software and is distributed under the 3-clause BSD\n// license. The full text of the license can be found in the file\n// COPYRIGHT at the top level directory of IBAMR.\n//\n// ---------------------------------------------------------------------\n\n// Config files\n#include <IBAMR_config.h>\n#include <IBTK_config.h>\n\n#include <SAMRAI_config.h>\n\n// Headers for basic PETSc functions\n#include <petscsys.h>\n\n// Headers for basic SAMRAI objects\n#include <BergerRigoutsos.h>\n#include <CartesianGridGeometry.h>\n#include <LoadBalancer.h>\n#include <StandardTagAndInitialize.h>\n\n// Headers for basic libMesh objects\n#include <libmesh/boundary_info.h>\n#include <libmesh/boundary_mesh.h>\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/IBFEMethod.h>\n#include <ibamr/IBFESurfaceMethod.h>\n#include <ibamr/INSCollocatedHierarchyIntegrator.h>\n#include <ibamr/INSStaggeredHierarchyIntegrator.h>\n\n#include <ibtk/AppInitializer.h>\n#include <ibtk/LEInteractor.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\n// Elasticity model data.\nnamespace ModelData\n{\n// The tether penalty functions each require some data that is set in the\n// input file. This data is passed to each object through the void *ctx\n// context data pointer. Here we collect all relevant tether data in a struct:\nstruct TetherData\n{\n    const double c1_s;\n    const double kappa_s_body;\n    const double eta_s_body;\n    const double kappa_s_surface;\n    const double eta_s_surface;\n\n    TetherData(Pointer<Database> input_db)\n        : c1_s(input_db->getDouble(\"C1_S\")),\n          kappa_s_body(input_db->getDouble(\"KAPPA_S_BODY\")),\n          eta_s_body(input_db->getDouble(\"ETA_S_BODY\")),\n          kappa_s_surface(input_db->getDouble(\"KAPPA_S_SURFACE\")),\n          eta_s_surface(input_db->getDouble(\"ETA_S_SURFACE\"))\n    {\n    }\n};\n\n// Tether (penalty) stress function.\nvoid\nPK1_stress_function(TensorValue<double>& PP,\n                    const TensorValue<double>& FF,\n                    const libMesh::Point& /*x*/,\n                    const libMesh::Point& /*X*/,\n                    Elem* const /*elem*/,\n                    const vector<const vector<double>*>& /*var_data*/,\n                    const vector<const vector<VectorValue<double> >*>& /*grad_var_data*/,\n                    double /*time*/,\n                    void* ctx)\n{\n    const TetherData* const tether_data = reinterpret_cast<TetherData*>(ctx);\n\n    PP = 2.0 * tether_data->c1_s * (FF - tensor_inverse_transpose(FF, NDIM));\n    return;\n} // PK1_stress_function\n\n// Tether (penalty) force functions.\nvoid\ntether_force_function(VectorValue<double>& F,\n                      const TensorValue<double>& /*FF*/,\n                      const libMesh::Point& x,\n                      const libMesh::Point& X,\n                      Elem* const /*elem*/,\n                      const vector<const vector<double>*>& var_data,\n                      const vector<const vector<VectorValue<double> >*>& /*grad_var_data*/,\n                      double /*time*/,\n                      void* ctx)\n{\n    const TetherData* const tether_data = reinterpret_cast<TetherData*>(ctx);\n\n    const std::vector<double>& U = *var_data[0];\n    for (unsigned int d = 0; d < NDIM; ++d)\n    {\n        F(d) = tether_data->kappa_s_body * (X(d) - x(d)) - tether_data->eta_s_body * U[d];\n    }\n    return;\n} // tether_force_function\n\nvoid\ntether_force_function(VectorValue<double>& F,\n                      const VectorValue<double>& n,\n                      const VectorValue<double>& /*N*/,\n                      const TensorValue<double>& /*FF*/,\n                      const libMesh::Point& x,\n                      const libMesh::Point& X,\n                      Elem* const /*elem*/,\n                      const unsigned short /*side*/,\n                      const vector<const vector<double>*>& var_data,\n                      const vector<const vector<VectorValue<double> >*>& /*grad_var_data*/,\n                      double /*time*/,\n                      void* ctx)\n{\n    const TetherData* const tether_data = reinterpret_cast<TetherData*>(ctx);\n\n    VectorValue<double> D = X - x;\n    VectorValue<double> D_n = (D * n) * n;\n    VectorValue<double> U;\n    for (unsigned int d = 0; d < NDIM; ++d) U(d) = (*var_data[0])[d];\n    VectorValue<double> U_t = U - (U * n) * n;\n    F = tether_data->kappa_s_surface * D - tether_data->eta_s_surface * U;\n    return;\n} // tether_force_function\n} // namespace ModelData\nusing namespace ModelData;\n\n// Function prototypes\nstatic ofstream drag_stream, lift_stream, U_L1_norm_stream, U_L2_norm_stream, U_max_norm_stream;\nvoid postprocess_data(Pointer<Database> input_db,\n                      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 libMesh, PETSc, MPI, and SAMRAI.\n    LibMeshInit init(argc, argv);\n    SAMRAI_MPI::setCommunicator(PETSC_COMM_WORLD);\n    SAMRAI_MPI::setCallAbortInSerialInsteadOfExit();\n    SAMRAIManager::startup();\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        const double R = 0.5;\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\n        BoundaryMesh boundary_mesh(solid_mesh.comm(), solid_mesh.mesh_dimension() - 1);\n        solid_mesh.boundary_info->sync(boundary_mesh);\n        boundary_mesh.prepare_for_use();\n\n        bool use_boundary_mesh = input_db->getBoolWithDefault(\"USE_BOUNDARY_MESH\", false);\n        Mesh& mesh = use_boundary_mesh ? boundary_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;\n        const string solver_type = app_initializer->getComponentDatabase(\"Main\")->getString(\"solver_type\");\n        if (solver_type == \"STAGGERED\")\n        {\n            navier_stokes_integrator = new INSStaggeredHierarchyIntegrator(\n                \"INSStaggeredHierarchyIntegrator\",\n                app_initializer->getComponentDatabase(\"INSStaggeredHierarchyIntegrator\"));\n        }\n        else if (solver_type == \"COLLOCATED\")\n        {\n            navier_stokes_integrator = new INSCollocatedHierarchyIntegrator(\n                \"INSCollocatedHierarchyIntegrator\",\n                app_initializer->getComponentDatabase(\"INSCollocatedHierarchyIntegrator\"));\n        }\n        else\n        {\n            TBOX_ERROR(\"Unsupported solver type: \" << solver_type << \"\\n\"\n                                                   << \"Valid options are: COLLOCATED, STAGGERED\");\n        }\n        Pointer<IBStrategy> ib_ops;\n        if (use_boundary_mesh)\n        {\n            ib_ops = new IBFESurfaceMethod(\n                \"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        }\n        else\n        {\n            ib_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        }\n        Pointer<IBHierarchyIntegrator> time_integrator =\n            new IBExplicitHierarchyIntegrator(\"IBHierarchyIntegrator\",\n                                              app_initializer->getComponentDatabase(\"IBHierarchyIntegrator\"),\n                                              ib_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        // Configure the IBFE solver.\n        TetherData tether_data(input_db);\n        void* const tether_data_ptr = reinterpret_cast<void*>(&tether_data);\n        EquationSystems* equation_systems;\n        std::vector<int> vars(NDIM);\n        for (unsigned int d = 0; d < NDIM; ++d) vars[d] = d;\n        vector<SystemData> sys_data(1, SystemData(IBFEMethod::VELOCITY_SYSTEM_NAME, vars));\n        if (use_boundary_mesh)\n        {\n            Pointer<IBFESurfaceMethod> ibfe_ops = ib_ops;\n            ibfe_ops->initializeFEEquationSystems();\n            equation_systems = ibfe_ops->getFEDataManager()->getEquationSystems();\n            IBFESurfaceMethod::LagSurfaceForceFcnData surface_fcn_data(\n                tether_force_function, sys_data, tether_data_ptr);\n            ibfe_ops->registerLagSurfaceForceFunction(surface_fcn_data);\n        }\n        else\n        {\n            Pointer<IBFEMethod> ibfe_ops = ib_ops;\n            ibfe_ops->initializeFEEquationSystems();\n            equation_systems = ibfe_ops->getFEDataManager()->getEquationSystems();\n            IBFEMethod::PK1StressFcnData PK1_stress_data(\n                PK1_stress_function, std::vector<IBTK::SystemData>(), tether_data_ptr);\n            PK1_stress_data.quad_order =\n                Utility::string_to_enum<libMesh::Order>(input_db->getStringWithDefault(\"PK1_QUAD_ORDER\", \"THIRD\"));\n            ibfe_ops->registerPK1StressFunction(PK1_stress_data);\n\n            IBFEMethod::LagBodyForceFcnData body_fcn_data(tether_force_function, sys_data, tether_data_ptr);\n            ibfe_ops->registerLagBodyForceFunction(body_fcn_data);\n\n            IBFEMethod::LagSurfaceForceFcnData surface_fcn_data(tether_force_function, sys_data, tether_data_ptr);\n            ibfe_ops->registerLagSurfaceForceFunction(surface_fcn_data);\n\n            if (input_db->getBoolWithDefault(\"ELIMINATE_PRESSURE_JUMPS\", false))\n            {\n                ibfe_ops->registerStressNormalizationPart();\n            }\n        }\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        if (use_boundary_mesh)\n        {\n            Pointer<IBFESurfaceMethod> ibfe_ops = ib_ops;\n            ibfe_ops->initializeFEData();\n        }\n        else\n        {\n            Pointer<IBFEMethod> ibfe_ops = ib_ops;\n            ibfe_ops->initializeFEData();\n        }\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 and the norms of the\n        // velocity.\n        if (SAMRAI_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            U_L1_norm_stream.open(\"U_L1.curve\", ios_base::out | ios_base::trunc);\n            U_L2_norm_stream.open(\"U_L2.curve\", ios_base::out | ios_base::trunc);\n            U_max_norm_stream.open(\"U_max.curve\", ios_base::out | ios_base::trunc);\n\n            drag_stream.precision(10);\n            lift_stream.precision(10);\n            U_L1_norm_stream.precision(10);\n            U_L2_norm_stream.precision(10);\n            U_max_norm_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                if (use_boundary_mesh)\n                {\n                    dynamic_cast<IBFESurfaceMethod&>(*ib_ops).writeFEDataToRestartFile(restart_dump_dirname,\n                                                                                       iteration_num);\n                }\n                else\n                {\n                    dynamic_cast<IBFEMethod&>(*ib_ops).writeFEDataToRestartFile(restart_dump_dirname, iteration_num);\n                }\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(input_db,\n                                 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 (SAMRAI_MPI::getRank() == 0)\n        {\n            drag_stream.close();\n            lift_stream.close();\n            U_L1_norm_stream.close();\n            U_L2_norm_stream.close();\n            U_max_norm_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\n    SAMRAIManager::shutdown();\n} // main\n\nvoid\npostprocess_data(Pointer<Database> input_db,\n                 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    TetherData tether_data(input_db);\n    void* const tether_data_ptr = reinterpret_cast<void*>(&tether_data);\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& x_system = equation_systems->get_system(IBFEMethod::COORDS_SYSTEM_NAME);\n    System& U_system = equation_systems->get_system(IBFEMethod::VELOCITY_SYSTEM_NAME);\n    NumericVector<double>* x_vec = x_system.solution.get();\n    NumericVector<double>* x_ghost_vec = x_system.current_local_solution.get();\n    x_vec->localize(*x_ghost_vec);\n    NumericVector<double>* U_vec = U_system.solution.get();\n    NumericVector<double>* U_ghost_vec = U_system.current_local_solution.get();\n    U_vec->localize(*U_ghost_vec);\n    const DofMap& dof_map = x_system.get_dof_map();\n    std::vector<std::vector<unsigned int> > dof_indices(NDIM);\n\n    std::unique_ptr<FEBase> fe(FEBase::build(dim, dof_map.variable_type(0)));\n    std::unique_ptr<QBase> qrule = QBase::build(QGAUSS, dim, SEVENTH);\n    fe->attach_quadrature_rule(qrule.get());\n    const vector<double>& JxW = fe->get_JxW();\n    const vector<libMesh::Point>& q_point = fe->get_xyz();\n    const vector<vector<double> >& phi = fe->get_phi();\n    const vector<vector<VectorValue<double> > >& dphi = fe->get_dphi();\n\n    std::unique_ptr<FEBase> fe_face(FEBase::build(dim, dof_map.variable_type(0)));\n    std::unique_ptr<QBase> qrule_face = QBase::build(QGAUSS, dim - 1, SEVENTH);\n    fe_face->attach_quadrature_rule(qrule_face.get());\n    const vector<double>& JxW_face = fe_face->get_JxW();\n    const vector<libMesh::Point>& q_point_face = fe_face->get_xyz();\n    const vector<libMesh::Point>& normal_face = fe_face->get_normals();\n    const vector<vector<double> >& phi_face = fe_face->get_phi();\n    const vector<vector<VectorValue<double> > >& dphi_face = fe_face->get_dphi();\n\n    std::vector<double> U_qp_vec(NDIM);\n    std::vector<const std::vector<double>*> var_data(1);\n    var_data[0] = &U_qp_vec;\n    std::vector<const std::vector<libMesh::VectorValue<double> >*> grad_var_data;\n\n    TensorValue<double> FF, FF_inv_trans;\n    boost::multi_array<double, 2> x_node, U_node;\n    VectorValue<double> F, N, U, n, x;\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(x_node, *x_ghost_vec, dof_indices);\n        get_values_for_interpolation(U_node, *U_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(x, qp, x_node, phi);\n            jacobian(FF, qp, x_node, dphi);\n            interpolate(U, qp, U_node, phi);\n            for (unsigned int d = 0; d < NDIM; ++d)\n            {\n                U_qp_vec[d] = U(d);\n            }\n            tether_force_function(F, FF, x, q_point[qp], elem, var_data, grad_var_data, loop_time, tether_data_ptr);\n            for (int d = 0; d < NDIM; ++d)\n            {\n                F_integral[d] += F(d) * JxW[qp];\n            }\n        }\n        for (unsigned short int side = 0; side < elem->n_sides(); ++side)\n        {\n            if (elem->neighbor_ptr(side)) continue;\n            fe_face->reinit(elem, side);\n            const unsigned int n_qp_face = qrule_face->n_points();\n            for (unsigned int qp = 0; qp < n_qp_face; ++qp)\n            {\n                interpolate(x, qp, x_node, phi_face);\n                jacobian(FF, qp, x_node, dphi_face);\n                interpolate(U, qp, U_node, phi_face);\n                for (unsigned int d = 0; d < NDIM; ++d)\n                {\n                    U_qp_vec[d] = U(d);\n                }\n                N = normal_face[qp];\n                tensor_inverse_transpose(FF_inv_trans, FF, NDIM);\n                n = (FF_inv_trans * N).unit();\n\n                tether_force_function(\n                    F, n, N, FF, x, q_point_face[qp], elem, side, var_data, grad_var_data, loop_time, tether_data_ptr);\n                for (int d = 0; d < NDIM; ++d)\n                {\n                    F_integral[d] += F(d) * JxW_face[qp];\n                }\n            }\n        }\n    }\n    SAMRAI_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 = 1.0;\n    if (SAMRAI_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": "c83f557967cf2da1a3bbd41254c1584c8ae43400", "size": 34175, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/IBFE/explicit/ex5/example.cpp", "max_stars_repo_name": "syam-s/IBAMR", "max_stars_repo_head_hexsha": "b6502f2f818835961d103fd2a2827d9336e68640", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-03-03T12:29:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-15T06:54:20.000Z", "max_issues_repo_path": "examples/IBFE/explicit/ex5/example.cpp", "max_issues_repo_name": "syam-s/IBAMR", "max_issues_repo_head_hexsha": "b6502f2f818835961d103fd2a2827d9336e68640", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/IBFE/explicit/ex5/example.cpp", "max_forks_repo_name": "syam-s/IBAMR", "max_forks_repo_head_hexsha": "b6502f2f818835961d103fd2a2827d9336e68640", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.8490813648, "max_line_length": 120, "alphanum_fraction": 0.5888807608, "num_tokens": 7948, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494421679929, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.47739222915458907}}
{"text": "// libgp - Gaussian process library for Machine Learning\n// Copyright (c) 2013, Manuel Blum <mblum@informatik.uni-freiburg.de>\n// All rights reserved.\n\n#include \"abstract_gp.h\"\n#include \"gp.h\"\n#include \"gp_utils.h\"\n\n#include <Eigen/Dense>\n\nusing namespace libgp;\n\nint main (int argc, char const *argv[])\n{\n  int n=4000, m=1000;\n  double tss = 0, error, f, y;\n  // initialize Gaussian process for 2-D input using the squared exponential \n  // covariance function with additive white noise.\n  GaussianProcess gp(2, \"CovSum ( CovSEiso, CovNoise)\");\n  // initialize hyper parameter vector\n  Eigen::VectorXd params(gp.covf().get_param_dim());\n  params << 0.0, 0.0, -2.0;\n  // set parameters of covariance function\n  gp.covf().set_loghyper(params);\n\n  // add training patterns\n  for(int i = 0; i < n; ++i) {\n    double x[] = {drand48()*4-2, drand48()*4-2};\n    y = Utils::hill(x[0], x[1]) + Utils::randn() * 0.1;\n    gp.add_pattern(x, y);\n  }\n\n  // total squared error\n  for(int i = 0; i < m; ++i) {\n    double x[] = {drand48()*4-2, drand48()*4-2};\n    f = gp.f(x);\n    y = Utils::hill(x[0], x[1]);\n    error = f - y;\n    tss += error*error;\n  }\n  std::cout << \"mse = \" << tss/m << std::endl;\n\treturn EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "c1c06ac1310ab8e043adedaedc8cdf24ea6ea46d", "size": 1211, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/gp_example_dense.cc", "max_stars_repo_name": "simbartonels/libgp-1", "max_stars_repo_head_hexsha": "b276776bc9e50c2ef4cced0f8262911f29dd04dc", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/gp_example_dense.cc", "max_issues_repo_name": "simbartonels/libgp-1", "max_issues_repo_head_hexsha": "b276776bc9e50c2ef4cced0f8262911f29dd04dc", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/gp_example_dense.cc", "max_forks_repo_name": "simbartonels/libgp-1", "max_forks_repo_head_hexsha": "b276776bc9e50c2ef4cced0f8262911f29dd04dc", "max_forks_repo_licenses": ["BSD-3-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.5227272727, "max_line_length": 77, "alphanum_fraction": 0.6251032205, "num_tokens": 394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619979547273, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4773199662224855}}
{"text": "//===- types.hh -----------------------------------------------------------===//\n//\n//                       The CIM Hardware Simulator Project\n//\n// See LICENSE.TXT for details.\n//\n//===----------------------------------------------------------------------===//\n#pragma once\n#include <Eigen/Dense>\n\nnamespace cimHW {\n\n// basic element type\ntypedef unsigned int bitType;\ntypedef float numType;\n\n// matrix with bitType\ntypedef Eigen::Matrix<bitType, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> MatrixXuiRowMajor;\ntypedef Eigen::Matrix<bitType, 1, Eigen::Dynamic, Eigen::RowMajor> RowVectorXui;\ntypedef Eigen::Matrix<bitType, Eigen::Dynamic, 1> VectorXui;\n\n// matrix with numType\ntypedef Eigen::Matrix<numType, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> MatrixXfRowMajor;\ntypedef Eigen::Matrix<numType, 1, Eigen::Dynamic, Eigen::RowMajor> RowVectorXf;\ntypedef Eigen::Matrix<numType, Eigen::Dynamic, 1> VectorXnum;\n\n} //namespace cimHW\n", "meta": {"hexsha": "1bf0094745ea82273357e2a0f3311c8790fb0f89", "size": 944, "ext": "hh", "lang": "C++", "max_stars_repo_path": "skysim/onnc-cimHW/lib/hardware/types.hh", "max_stars_repo_name": "ONNC/ONNC-CIM", "max_stars_repo_head_hexsha": "dd15eae6b22b39dcd2bff179e14ad0eda40e4338", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-07-05T02:26:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-11T10:37:20.000Z", "max_issues_repo_path": "skysim/onnc-cimHW/lib/hardware/types.hh", "max_issues_repo_name": "ONNC/ONNC-CIM", "max_issues_repo_head_hexsha": "dd15eae6b22b39dcd2bff179e14ad0eda40e4338", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "skysim/onnc-cimHW/lib/hardware/types.hh", "max_forks_repo_name": "ONNC/ONNC-CIM", "max_forks_repo_head_hexsha": "dd15eae6b22b39dcd2bff179e14ad0eda40e4338", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-11T10:39:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-11T10:39:01.000Z", "avg_line_length": 33.7142857143, "max_line_length": 98, "alphanum_fraction": 0.6207627119, "num_tokens": 218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.837619963333289, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4773199569829038}}
{"text": "// #define EIGEN_TAUCS_SUPPORT\r\n// #define EIGEN_CHOLMOD_SUPPORT\r\n#include <iostream>\r\n#include <Eigen/Sparse>\r\n\r\n// g++ -DSIZE=10000 -DDENSITY=0.001  sparse_cholesky.cpp -I.. -DDENSEMATRI -O3 -g0 -DNDEBUG   -DNBTRIES=1 -I /home/gael/Coding/LinearAlgebra/taucs_full/src/ -I/home/gael/Coding/LinearAlgebra/taucs_full/build/linux/  -L/home/gael/Coding/LinearAlgebra/taucs_full/lib/linux/ -ltaucs /home/gael/Coding/LinearAlgebra/GotoBLAS/libgoto.a -lpthread -I /home/gael/Coding/LinearAlgebra/SuiteSparse/CHOLMOD/Include/ $CHOLLIB -I /home/gael/Coding/LinearAlgebra/SuiteSparse/UFconfig/ /home/gael/Coding/LinearAlgebra/SuiteSparse/CCOLAMD/Lib/libccolamd.a   /home/gael/Coding/LinearAlgebra/SuiteSparse/CHOLMOD/Lib/libcholmod.a -lmetis /home/gael/Coding/LinearAlgebra/SuiteSparse/AMD/Lib/libamd.a  /home/gael/Coding/LinearAlgebra/SuiteSparse/CAMD/Lib/libcamd.a   /home/gael/Coding/LinearAlgebra/SuiteSparse/CCOLAMD/Lib/libccolamd.a  /home/gael/Coding/LinearAlgebra/SuiteSparse/COLAMD/Lib/libcolamd.a -llapack && ./a.out\r\n\r\n#define NOGMM\r\n#define NOMTL\r\n\r\n#ifndef SIZE\r\n#define SIZE 10\r\n#endif\r\n\r\n#ifndef DENSITY\r\n#define DENSITY 0.01\r\n#endif\r\n\r\n#ifndef REPEAT\r\n#define REPEAT 1\r\n#endif\r\n\r\n#include \"BenchSparseUtil.h\"\r\n\r\n#ifndef MINDENSITY\r\n#define MINDENSITY 0.0004\r\n#endif\r\n\r\n#ifndef NBTRIES\r\n#define NBTRIES 10\r\n#endif\r\n\r\n#define BENCH(X) \\\r\n  timer.reset(); \\\r\n  for (int _j=0; _j<NBTRIES; ++_j) { \\\r\n    timer.start(); \\\r\n    for (int _k=0; _k<REPEAT; ++_k) { \\\r\n        X  \\\r\n  } timer.stop(); }\r\n\r\n// typedef SparseMatrix<Scalar,UpperTriangular> EigenSparseTriMatrix;\r\ntypedef SparseMatrix<Scalar,SelfAdjoint|LowerTriangular> EigenSparseSelfAdjointMatrix;\r\n\r\nvoid fillSpdMatrix(float density, int rows, int cols,  EigenSparseSelfAdjointMatrix& dst)\r\n{\r\n  dst.startFill(rows*cols*density);\r\n  for(int j = 0; j < cols; j++)\r\n  {\r\n    dst.fill(j,j) = internal::random<Scalar>(10,20);\r\n    for(int i = j+1; i < rows; i++)\r\n    {\r\n      Scalar v = (internal::random<float>(0,1) < density) ? internal::random<Scalar>() : 0;\r\n      if (v!=0)\r\n        dst.fill(i,j) = v;\r\n    }\r\n\r\n  }\r\n  dst.endFill();\r\n}\r\n\r\n#include <Eigen/Cholesky>\r\n\r\ntemplate<int Backend>\r\nvoid doEigen(const char* name, const EigenSparseSelfAdjointMatrix& sm1, int flags = 0)\r\n{\r\n  std::cout << name << \"...\" << std::flush;\r\n  BenchTimer timer;\r\n  timer.start();\r\n  SparseLLT<EigenSparseSelfAdjointMatrix,Backend> chol(sm1, flags);\r\n  timer.stop();\r\n  std::cout << \":\\t\" << timer.value() << endl;\r\n\r\n  std::cout << \"  nnz: \" << sm1.nonZeros() << \" => \" << chol.matrixL().nonZeros() << \"\\n\";\r\n//   std::cout << \"sparse\\n\" << chol.matrixL() << \"%\\n\";\r\n}\r\n\r\nint main(int argc, char *argv[])\r\n{\r\n  int rows = SIZE;\r\n  int cols = SIZE;\r\n  float density = DENSITY;\r\n  BenchTimer timer;\r\n\r\n  VectorXf b = VectorXf::Random(cols);\r\n  VectorXf x = VectorXf::Random(cols);\r\n\r\n  bool densedone = false;\r\n\r\n  //for (float density = DENSITY; density>=MINDENSITY; density*=0.5)\r\n//   float density = 0.5;\r\n  {\r\n    EigenSparseSelfAdjointMatrix sm1(rows, cols);\r\n    std::cout << \"Generate sparse matrix (might take a while)...\\n\";\r\n    fillSpdMatrix(density, rows, cols, sm1);\r\n    std::cout << \"DONE\\n\\n\";\r\n\r\n    // dense matrices\r\n    #ifdef DENSEMATRIX\r\n    if (!densedone)\r\n    {\r\n      densedone = true;\r\n      std::cout << \"Eigen Dense\\t\" << density*100 << \"%\\n\";\r\n      DenseMatrix m1(rows,cols);\r\n      eiToDense(sm1, m1);\r\n      m1 = (m1 + m1.transpose()).eval();\r\n      m1.diagonal() *= 0.5;\r\n\r\n//       BENCH(LLT<DenseMatrix> chol(m1);)\r\n//       std::cout << \"dense:\\t\" << timer.value() << endl;\r\n\r\n      BenchTimer timer;\r\n      timer.start();\r\n      LLT<DenseMatrix> chol(m1);\r\n      timer.stop();\r\n      std::cout << \"dense:\\t\" << timer.value() << endl;\r\n      int count = 0;\r\n      for (int j=0; j<cols; ++j)\r\n        for (int i=j; i<rows; ++i)\r\n          if (!internal::isMuchSmallerThan(internal::abs(chol.matrixL()(i,j)), 0.1))\r\n            count++;\r\n      std::cout << \"dense: \" << \"nnz = \" << count << \"\\n\";\r\n//       std::cout << \"dense:\\n\" << m1 << \"\\n\\n\" << chol.matrixL() << endl;\r\n    }\r\n    #endif\r\n\r\n    // eigen sparse matrices\r\n    doEigen<Eigen::DefaultBackend>(\"Eigen/Sparse\", sm1, Eigen::IncompleteFactorization);\r\n\r\n    #ifdef EIGEN_CHOLMOD_SUPPORT\r\n    doEigen<Eigen::Cholmod>(\"Eigen/Cholmod\", sm1, Eigen::IncompleteFactorization);\r\n    #endif\r\n\r\n    #ifdef EIGEN_TAUCS_SUPPORT\r\n    doEigen<Eigen::Taucs>(\"Eigen/Taucs\", sm1, Eigen::IncompleteFactorization);\r\n    #endif\r\n\r\n    #if 0\r\n    // TAUCS\r\n    {\r\n      taucs_ccs_matrix A = sm1.asTaucsMatrix();\r\n\r\n      //BENCH(taucs_ccs_matrix* chol = taucs_ccs_factor_llt(&A, 0, 0);)\r\n//       BENCH(taucs_supernodal_factor_to_ccs(taucs_ccs_factor_llt_ll(&A));)\r\n//       std::cout << \"taucs:\\t\" << timer.value() << endl;\r\n\r\n      taucs_ccs_matrix* chol = taucs_ccs_factor_llt(&A, 0, 0);\r\n\r\n      for (int j=0; j<cols; ++j)\r\n      {\r\n        for (int i=chol->colptr[j]; i<chol->colptr[j+1]; ++i)\r\n          std::cout << chol->values.d[i] << \" \";\r\n      }\r\n    }\r\n\r\n    // CHOLMOD\r\n    #ifdef EIGEN_CHOLMOD_SUPPORT\r\n    {\r\n      cholmod_common c;\r\n      cholmod_start (&c);\r\n      cholmod_sparse A;\r\n      cholmod_factor *L;\r\n\r\n      A = sm1.asCholmodMatrix();\r\n      BenchTimer timer;\r\n//       timer.reset();\r\n      timer.start();\r\n      std::vector<int> perm(cols);\r\n//       std::vector<int> set(ncols);\r\n      for (int i=0; i<cols; ++i)\r\n        perm[i] = i;\r\n//       c.nmethods = 1;\r\n//       c.method[0] = 1;\r\n\r\n      c.nmethods = 1;\r\n      c.method [0].ordering = CHOLMOD_NATURAL;\r\n      c.postorder = 0;\r\n      c.final_ll = 1;\r\n\r\n      L = cholmod_analyze_p(&A, &perm[0], &perm[0], cols, &c);\r\n      timer.stop();\r\n      std::cout << \"cholmod/analyze:\\t\" << timer.value() << endl;\r\n      timer.reset();\r\n      timer.start();\r\n      cholmod_factorize(&A, L, &c);\r\n      timer.stop();\r\n      std::cout << \"cholmod/factorize:\\t\" << timer.value() << endl;\r\n\r\n      cholmod_sparse* cholmat = cholmod_factor_to_sparse(L, &c);\r\n\r\n      cholmod_print_factor(L, \"Factors\", &c);\r\n\r\n      cholmod_print_sparse(cholmat, \"Chol\", &c);\r\n      cholmod_write_sparse(stdout, cholmat, 0, 0, &c);\r\n//\r\n//       cholmod_print_sparse(&A, \"A\", &c);\r\n//       cholmod_write_sparse(stdout, &A, 0, 0, &c);\r\n\r\n\r\n//       for (int j=0; j<cols; ++j)\r\n//       {\r\n//           for (int i=chol->colptr[j]; i<chol->colptr[j+1]; ++i)\r\n//             std::cout << chol->values.s[i] << \" \";\r\n//       }\r\n    }\r\n    #endif\r\n\r\n    #endif\r\n\r\n\r\n\r\n  }\r\n\r\n\r\n  return 0;\r\n}\r\n\r\n", "meta": {"hexsha": "9cff50545dd668bb87a57de7d018f6fc7a628cdf", "size": 6476, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "packages/eigen-eigen-323c052e1731/bench/sparse_cholesky.cpp", "max_stars_repo_name": "k4rth33k/dnnc-operators", "max_stars_repo_head_hexsha": "a7fe3f1240c12b3438558def71fbfcd4520446c3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-08-16T14:35:17.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-11T23:59:22.000Z", "max_issues_repo_path": "packages/eigen-eigen-323c052e1731/bench/sparse_cholesky.cpp", "max_issues_repo_name": "k4rth33k/dnnc-operators", "max_issues_repo_head_hexsha": "a7fe3f1240c12b3438558def71fbfcd4520446c3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-08-12T04:38:14.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T16:32:13.000Z", "max_forks_repo_path": "packages/eigen-eigen-323c052e1731/bench/sparse_cholesky.cpp", "max_forks_repo_name": "k4rth33k/dnnc-operators", "max_forks_repo_head_hexsha": "a7fe3f1240c12b3438558def71fbfcd4520446c3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-08-15T13:29:00.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-09T17:08:04.000Z", "avg_line_length": 29.8433179724, "max_line_length": 903, "alphanum_fraction": 0.593730698, "num_tokens": 2031, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544335934766, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.4772927145574819}}
{"text": "// The MIT License \n// (c) 2019 Daniel Williams\n\n#ifndef _INTERPOLATE_HPP_\n#define _INTERPOLATE_HPP_\n\n#include <Eigen/Geometry>\n\n#include \"geometry/cell_value.hpp\"\n#include \"geometry/sample.hpp\"\n\nnamespace terrain::geometry {\n\n/**\n * Performs the low-level interpolation between this node and another node, at the requested location\n *\n * @param {Point} the x,y coordinates to interpolate at.\n * @param {quadtree::Node} n2 the other node to interpolate\n * @return {cell_value_t} The resultant value\n */\ncell_value_t interpolate_linear( const Eigen::Vector2d& at, const Sample& s1, const Sample& s2);\n\n/**\n * Performs bilinear-interpolation: \n * http://en.wikipedia.org/wiki/Bilinear_Interpolation\n * \n * Warning: Undefined behavior, if interpolation happens outside of the rectangle defined by the 4 samples\n * \n * @param the x,y coordinates to interpolate at.\n * @param ne quadrant sample point\n * @param nw quadrant sample point\n * @param sw quadrant sample point\n * @param se quadrant sample point\n * @return resultant value\n */\ncell_value_t interpolate_bilinear( const Eigen::Vector2d& at, const Sample& ne, const Sample& nw, const Sample& sw, const Sample& se);\n\n} // namespace terrain::geometry\n\n#endif // #ifndef _INTERPOLATE_HPP_\n", "meta": {"hexsha": "a59cc28142b0946305b86bbc95642ce07ce8c189", "size": 1238, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/geometry/interpolate.hpp", "max_stars_repo_name": "teyrana/quadtree", "max_stars_repo_head_hexsha": "4172ad2f2e36414caebf80013a3d32e6df200945", "max_stars_repo_licenses": ["MIT"], "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/geometry/interpolate.hpp", "max_issues_repo_name": "teyrana/quadtree", "max_issues_repo_head_hexsha": "4172ad2f2e36414caebf80013a3d32e6df200945", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-08-24T17:31:50.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-24T17:31:50.000Z", "max_forks_repo_path": "include/geometry/interpolate.hpp", "max_forks_repo_name": "teyrana/quadtree", "max_forks_repo_head_hexsha": "4172ad2f2e36414caebf80013a3d32e6df200945", "max_forks_repo_licenses": ["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.1951219512, "max_line_length": 134, "alphanum_fraction": 0.7504038772, "num_tokens": 293, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6992544335934766, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.4772927145574819}}
{"text": "//\r\n// Copyright (c) 2015, J2 Innovations\r\n// Copyright (c) 2012 Brian Frank\r\n// Licensed under the Academic Free License version 3.0\n// History:\r\n//   19 Aug 2014  Radu Racariu<radur@2inn.com> Ported to C++\r\n//   06 Jun 2011  Brian Frank  Creation\r\n//\r\n#include \"coord.hpp\"\r\n#include <cstdio>\r\n#include <sstream>\r\n#include <stdexcept>\r\n\r\n#include <boost/lexical_cast.hpp>\r\n#include <boost/algorithm/string/predicate.hpp>\r\n\r\n////////////////////////////////////////////////\r\n// Coord\r\n////////////////////////////////////////////////\r\nusing namespace haystack;\r\n\r\n// private ctor\r\nCoord::Coord(int32_t lat, int32_t lng) : ulat(lat), ulng(lng) \r\n{\r\n    if (ulat < -90000000 || ulat > 90000000) throw std::runtime_error(\"Invalid lat > +/- 90\");\r\n    if (ulng < -180000000 || ulng > 180000000) throw std::runtime_error(\"Invalid lng > +/- 180\");\r\n}\r\n\r\nCoord::Coord(double lat, double lng) : ulat((int32_t)(lat * 1000000.0)), ulng((int32_t)(lng * 1000000.0)) \r\n{\r\n    if (ulat < -90000000 || ulat > 90000000) throw std::runtime_error(\"Invalid lat > +/- 90\");\r\n    if (ulng < -180000000 || ulng > 180000000) throw std::runtime_error(\"Invalid lng > +/- 180\");\r\n}\r\n\r\n////////////////////////////////////////////////\r\n// statics\r\n////////////////////////////////////////////////\r\n\r\n// Parse from string fomat \"C(lat,lng)\" or raise runtime exception\r\nCoord Coord::make(const std::string &s) \r\n{\r\n    if (!boost::starts_with(s, \"C(\")) throw std::runtime_error(\"Parse error\");\r\n    if (!boost::ends_with(s, \")\")) throw std::runtime_error(\"Parse error\");\r\n    size_t comma = s.find(',');\r\n    if (comma < 3) throw std::runtime_error(\"Parse error\");\r\n\r\n    std::string lat = s.substr(2, comma - 2);\r\n    std::string lng = s.substr(comma + 1, s.size() - comma - 2);\r\n\r\n    return Coord(boost::lexical_cast<double>(lat), boost::lexical_cast<double>(lng));\r\n}\r\n\r\n// Return if given latitude is legal value between -90.0 and +90.0 */\r\nbool Coord::is_lat(double lat) { return -90.0 <= lat && lat <= 90.0; }\r\n\r\n// Return if given is longtitude is legal value between -180.0 and +180.0\r\nbool Coord::is_lng(double lng) { return -180.0 <= lng && lng <= 180.0; }\r\n\r\nvoid u_to_str(std::stringstream &s, int ud)\r\n{\r\n    if (ud < 0) { s << '-'; ud = -ud; }\r\n    if (ud < 1000000.0)\r\n    {\r\n        double d = (ud / 1000000.0);\r\n        char buf[64];\r\n        sprintf(buf, \"%g\", d);\r\n        s << buf;\r\n        if (d == 0)\r\n            s << \".0\";\r\n        return;\r\n    }\r\n    std::string x = boost::lexical_cast<std::string>(ud);\r\n    size_t dot = x.size() - 6;\r\n    size_t end = x.size();\r\n\r\n    while (end > dot + 1 && x[end - 1] == '0') --end;\r\n\r\n    for (size_t i = 0; i < dot; ++i)\r\n        s << x[i];\r\n\r\n    s << '.';\r\n    for (size_t i = dot; i < end; ++i) s << x[i];\r\n}\r\n\r\n\r\n//////////////////////////////////////////////////////////////////////////\r\n// Access\r\n//////////////////////////////////////////////////////////////////////////\r\n\r\n// Latitude in decimal degrees\r\ndouble Coord::lat() const { return ulat / 1000000.0; }\r\n\r\n// Longtitude in decimal degrees\r\ndouble Coord::lng() const { return ulng / 1000000.0; }\r\n\r\n////////////////////////////////////////////////\r\n// to zinc\r\n////////////////////////////////////////////////\r\n\r\n// Encode using double quotes and back slash escapes\r\nconst std::string Coord::to_zinc() const\r\n{\r\n\tstd::stringstream os;\r\n\t\r\n    os << \"C(\";\r\n    u_to_str(os, ulat);\r\n    os << ',';\r\n    u_to_str(os, ulng);\r\n    os << \")\";\r\n\r\n\treturn os.str();\r\n}\r\n\r\n////////////////////////////////////////////////\r\n// Equal\r\n////////////////////////////////////////////////\r\nbool Coord::operator ==(const Coord &other) const\r\n{\r\n\treturn ulat == other.ulat && ulng == other.ulng;\r\n}\r\n\r\nbool Coord::operator==(const Val &other) const\r\n{\r\n    if (type() != other.type())\r\n        return false;\r\n    return static_cast<const Coord&>(other).operator==(*this);\r\n}\r\n\r\nbool Coord::operator < (const Val &other) const\r\n{\r\n    return type() == other.type() \r\n        && ulat < ((Coord&)other).ulat && ulng >((Coord&)other).ulng;\r\n}\r\n\r\nbool Coord::operator >(const Val &other) const\r\n{\r\n    return type() == other.type() \r\n        && ulat > ((Coord&)other).ulat && ulng > ((Coord&)other).ulng;\r\n}\r\n\r\nCoord::auto_ptr_t Coord::clone() const\r\n{\r\n    return auto_ptr_t(new Coord(*this));\r\n}", "meta": {"hexsha": "0e165a0be537bb8ab8f2a128258aff316f22bc94", "size": 4277, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/coord.cpp", "max_stars_repo_name": "kushaldalsania/haystack-cpp", "max_stars_repo_head_hexsha": "95997ae2bca9ea096dc7e61c000291f3ac08d9d7", "max_stars_repo_licenses": ["AFL-3.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/coord.cpp", "max_issues_repo_name": "kushaldalsania/haystack-cpp", "max_issues_repo_head_hexsha": "95997ae2bca9ea096dc7e61c000291f3ac08d9d7", "max_issues_repo_licenses": ["AFL-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/coord.cpp", "max_forks_repo_name": "kushaldalsania/haystack-cpp", "max_forks_repo_head_hexsha": "95997ae2bca9ea096dc7e61c000291f3ac08d9d7", "max_forks_repo_licenses": ["AFL-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7013888889, "max_line_length": 107, "alphanum_fraction": 0.5078325929, "num_tokens": 1131, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544335934766, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.47729270552706576}}
{"text": "//\n// Created by abakfja on 3/28/21.\n//\n\n#ifndef LA_VECTOR_HPP\n#define LA_VECTOR_HPP\n\n\n#include <boost/numeric/ublas/matrix/vector/vector_engine.hpp>\n#include <boost/numeric/ublas/matrix/vector/traits/engine_traits.hpp>\n\n\nnamespace boost::numeric::ublas::experimental {\n\ntemplate<class engine>\nclass vector {\npublic:\n    using scalar_type = typename engine::scalar_type;\n    using scalar_reference = scalar_type &;\n    using scalar_const_reference = const scalar_type &;\n\n    using storage_traits_type = typename engine::storage_traits_type;\n\n    using storage_type = typename storage_traits_type::storage_type;\n\n    using size_type = typename storage_traits_type::size_type;\n    using index_type = std::pair<size_type, size_type>;\n    using difference_type = typename storage_traits_type::difference_type;\n\n    using reference = typename storage_traits_type::reference;\n    using const_reference = typename storage_traits_type::const_reference;\n\n    using pointer = typename storage_traits_type::pointer;\n    using const_pointer = typename storage_traits_type::const_pointer;\n\n    using iterator = typename storage_traits_type::iterator;\n    using const_iterator = typename storage_traits_type::const_iterator;\n\n    using reverse_iterator = typename storage_traits_type::reverse_iterator;\n    using const_reverse_iterator = typename storage_traits_type::const_reverse_iterator;\n\n    using resizable_tag = typename storage_traits_type::resizable_tag;\n\n\n//    vector() = default;\n\n    template<typename E = engine,\n            typename = detail::enable_if_static<E>>\n    explicit vector(scalar_const_reference v): vector(resizable_tag{}) {\n        fill(v);\n    }\n\n    template<typename E = engine,\n            typename = detail::enable_if_dynamic<E>>\n    vector(std::initializer_list<scalar_type> l)\n            : vector(l.size(), resizable_tag{}) {\n        std::copy(l.begin(), l.end(), m_data.begin());\n    }\n\n    template<typename E = engine,\n            typename = detail::enable_if_dynamic<E>>\n    constexpr explicit\n    vector(size_type n, scalar_type v) :\n            vector(n, resizable_tag{}) {\n        fill(v);\n    }\n\n    [[nodiscard]] index_type size() const {\n        return this->n_ele;\n    }\n\n    [[nodiscard]] bool empty() const {\n        return m_data.empty();\n    }\n\n    constexpr auto begin() noexcept {\n        return m_data.begin();\n    }\n\n    constexpr auto end() noexcept {\n        return m_data.end();\n    }\n\n    constexpr auto begin() const noexcept {\n        return m_data.begin();\n    }\n\n    constexpr auto end() const noexcept {\n        return m_data.end();\n    }\n\n    constexpr auto at(size_type pos) const {\n        return m_data.at(pos);\n    }\n\n    constexpr auto at(size_type pos) {\n        return m_data.at(pos);\n    }\n\n    void fill(const_reference value) {\n        std::fill(begin(), end(), value);\n    }\n\n    constexpr const_reference operator[](size_type i) const {\n        return this->m_data[i];\n    }\n\n    constexpr reference operator[](size_type i) {\n        return this->m_data[i];\n    }\n\nprivate:\n\n    constexpr explicit vector(size_type n,\n                              storage_resizable_container_tag t\n    ) : n_ele{n}, m_data(n_ele) {\n    }\n\n    constexpr explicit vector(size_type n,\n                              storage_static_container_tag t\n    ) : n_ele{engine::n}, m_data(n_ele) {\n    }\n\n\n    constexpr explicit vector(storage_static_container_tag t) :\n            n_ele{engine::n} {\n    }\n\n\n    storage_type m_data;\n    size_type n_ele;\n};\n\n\n}\n\n\n#endif //LA_VECTOR_HPP\n", "meta": {"hexsha": "1c02fee96fa769ec40b707db35fda4b8253256c9", "size": 3522, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/matrix_old/vector/vector.hpp", "max_stars_repo_name": "abakfja/linear-algebra", "max_stars_repo_head_hexsha": "024974bc537f3c1aa86bd011e5821e6e4465aa49", "max_stars_repo_licenses": ["MIT"], "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/matrix_old/vector/vector.hpp", "max_issues_repo_name": "abakfja/linear-algebra", "max_issues_repo_head_hexsha": "024974bc537f3c1aa86bd011e5821e6e4465aa49", "max_issues_repo_licenses": ["MIT"], "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/matrix_old/vector/vector.hpp", "max_forks_repo_name": "abakfja/linear-algebra", "max_forks_repo_head_hexsha": "024974bc537f3c1aa86bd011e5821e6e4465aa49", "max_forks_repo_licenses": ["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.3381294964, "max_line_length": 88, "alphanum_fraction": 0.6666666667, "num_tokens": 740, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737473266735, "lm_q2_score": 0.6992544085240401, "lm_q1q2_score": 0.4772927019609507}}
{"text": "#pragma once\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <vector>\n\n#include <utils/eigen_ext.hpp>\n\nnamespace ipc::rigid {\n\ntemplate <typename T> class Pose;\ntemplate <typename T> using Poses = std::vector<Pose<T>>;\n\n/// @brief The position and rotation of an object.\ntemplate <typename T> class Pose {\npublic:\n    Pose();\n    Pose(const VectorMax3<T>& position, const VectorMax3<T>& rotation);\n    Pose(const VectorMax6<T>& dof);\n    Pose(const T& x, const T& y, const T& theta);\n    Pose(\n        const T& x,\n        const T& y,\n        const T& z,\n        const T& theta_x,\n        const T& theta_y,\n        const T& theta_z);\n\n    static Pose<T> Zero(int dim);\n\n    static Poses<T> dofs_to_poses(const VectorX<T>& dofs, int dim);\n    static VectorX<T> poses_to_dofs(const Poses<T>& poses);\n\n    static int dim_to_ndof(const int dim) { return dim == 2 ? 3 : 6; }\n    static int dim_to_pos_ndof(const int dim) { return dim; }\n    static int dim_to_rot_ndof(const int dim)\n    {\n        return dim_to_ndof(dim) - dim_to_pos_ndof(dim);\n    }\n    int dim() const { return position.size(); }\n    int pos_ndof() const { return position.size(); }\n    int rot_ndof() const { return rotation.size(); }\n    int ndof() const { return pos_ndof() + rot_ndof(); }\n\n    VectorMax6<T> dof() const;\n\n    /// @brief Replace a selected dof with the dof in other.\n    /// @param R Rotation this rotations coordinates to the dof in\n    ///          is_dof_selected.\n    void select_dof(\n        const VectorMax6b& is_dof_selected,\n        const Pose<T>& other,\n        const MatrixMax3d& R);\n    /// @brief Replace a selected dof with the dof in other.\n    void select_dof(const VectorMax6b& is_dof_selected, const Pose<T>& other)\n    {\n        select_dof(\n            is_dof_selected, other,\n            MatrixMax3d::Identity(rot_ndof(), rot_ndof()));\n    }\n    /// @brief Zero out the i-th dof if is_dof_zero(i) == true.\n    void zero_dof(const VectorMax6b& is_dof_zero, const MatrixMax3d& R);\n    /// @brief Zero out the i-th dof if is_dof_zero(i) == true.\n    void zero_dof(const VectorMax6b& is_dof_zero)\n    {\n        zero_dof(is_dof_zero, MatrixMax3d::Identity(rot_ndof(), rot_ndof()));\n    }\n\n    MatrixMax3<T> construct_rotation_matrix() const;\n\n    Eigen::Quaternion<T> construct_quaternion() const;\n\n    static Pose<T> interpolate(const Pose<T>& pose0, const Pose<T>& pose1, T t);\n\n    bool operator==(const Pose<T>& other) const;\n\n    friend Pose<T> operator*(const Pose<T>& pose, const T& x)\n    {\n        return Pose<T>(pose.position * x, pose.rotation * x);\n    }\n    friend Pose<T> operator*(const T& x, const Pose<T>& pose)\n    {\n        return Pose<T>(x * pose.position, x * pose.rotation);\n    }\n    inline Pose<T>& operator*=(const T& x);\n    Pose<T> operator/(const T& x) const;\n\n    template <typename T1> Pose<T1> cast() const\n    {\n        return Pose<T1>(\n            position.template cast<T1>(), rotation.template cast<T1>());\n    }\n\n    /// Position dof (either 2D or 3D)\n    VectorMax3<T> position;\n    /// Rotation dof (either 1D or 3D) expressed as a rotation vector\n    VectorMax3<T> rotation;\n};\n\ntypedef Pose<double> PoseD;\ntypedef Poses<double> PosesD;\n\ntemplate <typename T>\nPoses<T> interpolate(const Poses<T>& pose0, const Poses<T>& pose1, T t);\ntemplate <typename T> Poses<T> operator*(const Poses<T>& poses, const T& x);\n/// @brief Cast poses element-wise.\ntemplate <typename T, typename U> Poses<T> cast(const Poses<U>& poses);\n\ntemplate <typename T>\nMatrixMax3<T> construct_rotation_matrix(const VectorMax3<T>& r);\ntemplate <typename Derived, typename T = typename Derived::Scalar>\nEigen::Quaternion<T> construct_quaternion(const Eigen::MatrixBase<Derived>& r);\n\ntemplate <typename T> Matrix3<T> rotate_to_z(Vector3<T> n);\ntemplate <typename T> Matrix3<T> rotate_around_z(const T& theta);\ntemplate <typename T>\nvoid decompose_to_z_screwing(\n    const Pose<T>& pose_t0,\n    const Pose<T>& pose_t1,\n    Matrix3<T>& R0,\n    Matrix3<T>& P,\n    T& omega);\n\n} // namespace ipc::rigid\n\n#include \"pose.tpp\"\n", "meta": {"hexsha": "00b0a4535f79fd671d32546ea4f4b9524c2537cf", "size": 4036, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/physics/pose.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/physics/pose.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/physics/pose.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": 31.7795275591, "max_line_length": 80, "alphanum_fraction": 0.653617443, "num_tokens": 1098, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587586, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.47729270148640457}}
{"text": "#include <algorithm>\n#include <cfloat>\n#include <cmath>\n#include <cstddef>\n#include <cstdlib>\n#include <iterator>\n#include <iomanip>\n#include <iostream>\n#include <limits>\n#include <vector>\n\n#include <Eigen/Geometry>\n\n#include <nlohmann/json/json.hpp>\n\n#include \"geometry/polygon.hpp\"\n\nusing std::cerr;\nusing std::max;\nusing std::min;\nusing std::endl;\nusing std::ostream;\nusing std::string;\n\nusing Eigen::Vector2d;\n\nusing terrain::geometry::Polygon;\n\n//---------------------------------------------------------------\n// Constructor\n//\nPolygon::Polygon(){\n    set_default();\n}\n\nPolygon::Polygon(const size_t initial_capacity):\n    points(initial_capacity)\n{\n    points.resize(initial_capacity);\n}\n\nPolygon::Polygon(nlohmann::json doc){\n    load(doc);\n}\n\nPolygon::Polygon(std::vector<Vector2d>& init){\n    load(init);\n}\n\nPolygon::Polygon(std::initializer_list<Vector2d> init_list)\n{\n    std::vector<Vector2d> pts = init_list;\n\n    load(pts);\n}\n\nvoid Polygon::clear(){\n    points.clear();\n}\n\nvoid Polygon::complete(){\n    // cerr << \"====== ====== ====== \" << endl;\n    // write_yaml(cerr, \"    \");\n\n    enclose_polygon();\n    if(! is_right_handed()){\n        std::reverse(std::begin(points), std::end(points));\n    }\n}\n\nvoid Polygon::emplace(const double x, const double y){\n    points.emplace_back(x,y);\n}\n\nvoid Polygon::enclose_polygon(){\n    // ensure that polygon loops back\n    const auto& first_Vector2d = points[0];\n    const auto& last_Vector2d = points[points.size()-1];\n\n    if( ! first_Vector2d.isApprox(last_Vector2d)){\n        points.emplace_back(first_Vector2d);\n    }\n}\n\nbool Polygon::is_right_handed() const {\n    double sum = 0;\n\n    // NOTE THE RANGE!:\n    //   this needs to iterate over all doubles\n    for( uint i = 0; i < (points.size()-1); ++i ){\n        auto& p1 = points[i];\n        auto& p2 = points[i+1];\n        sum += (p1[0] * p2[1]) - (p1[1]*p2[0]);\n    }\n\n    // // The shoelace formula includes a divide-by-2 step; ... but we don't\n    // // care about the magnitude, just the sign.  So skip this step.\n    // sum /= 2;\n\n    if( 0 > sum ){\n        // left-handed / clockwise points\n        return false;\n    }else{\n        // right-handed / counter-clockwise points\n        return true;\n    }\n}\n\nbool Polygon::load(std::vector<Vector2d> source){\n    // if the new polygon contains insufficient points, abort and clear.\n    if(4 > source.size()){\n        return false;\n    }\n\n    points = std::move(source);\n    \n    complete();\n\n    return true;\n}\n\nbool Polygon::load(nlohmann::json doc){\n    if(doc.is_array() && doc[0].is_array() && (4 <= doc.size()) ){\n        clear();\n        points.resize(doc.size());\n\n        size_t pair_index = 0;\n        for( auto& pair : doc){\n            Vector2d p(pair[0].get<double>(), pair[1].get<double>());\n            points[pair_index] = p;\n            ++pair_index;\n        }\n\n        complete(); \n\n        return true;\n    }\n\n    return false;\n}\n\nterrain::geometry::Layout Polygon::make_layout(const double precision) const {\n    double min_x = DBL_MAX;\n    double max_x = DBL_MIN;\n    double min_y = DBL_MAX;\n    double max_y = DBL_MIN;\n\n    for( auto p : points ){\n        min_x = min(min_x, p.x());\n        max_x = max(max_x, p.x());\n        min_y = min(min_y, p.y());\n        max_y = max(max_y, p.y());\n    }\n\n    const double ctr_x = round( 0.5*( min_x + max_x ) );\n    const double ctr_y = round( 0.5*( min_y + max_y ) );\n    const double width = max(max_x - min_x, max_y - min_y);\n\n    return Layout(precision, ctr_x, ctr_y, width);\n}\n\nVector2d& Polygon::operator[](const size_t index){\n    return points[index];\n}\n\nconst Vector2d& Polygon::operator[](const size_t index) const {\n    return points[index];\n}\n\nvoid Polygon::push_back(const Vector2d p){\n    points.push_back(p);\n}\n\nsize_t Polygon::size() const {\n    return points.size();\n}\n\nvoid Polygon::set_default(){\n    points.clear();\n    points.emplace_back( 0, 0);\n    points.emplace_back( 1, 0);\n    points.emplace_back( 1, 1);\n    points.emplace_back( 0, 1);\n}\n\nvoid Polygon::write_yaml(std::ostream& sink, string indent) const {\n    sink << indent << \"points: \\n\";\n    for( uint i = 0; i < points.size(); ++i ){\n        auto& p = points[i];\n        sink << indent << \"    - \" << p[0] << \", \" << p[1] << '\\n';\n    }\n}\n", "meta": {"hexsha": "12e6922773bb51d0975f7ca5698e4a194cc4ec75", "size": 4251, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/geometry/polygon.cpp", "max_stars_repo_name": "teyrana/quadtree", "max_stars_repo_head_hexsha": "4172ad2f2e36414caebf80013a3d32e6df200945", "max_stars_repo_licenses": ["MIT"], "max_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/polygon.cpp", "max_issues_repo_name": "teyrana/quadtree", "max_issues_repo_head_hexsha": "4172ad2f2e36414caebf80013a3d32e6df200945", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-08-24T17:31:50.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-24T17:31:50.000Z", "max_forks_repo_path": "src/geometry/polygon.cpp", "max_forks_repo_name": "teyrana/quadtree", "max_forks_repo_head_hexsha": "4172ad2f2e36414caebf80013a3d32e6df200945", "max_forks_repo_licenses": ["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.0259067358, "max_line_length": 78, "alphanum_fraction": 0.5885673959, "num_tokens": 1117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.4772927014864045}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n//                                                                           //\n//                          *** Mesh.hpp ***                                 //\n//                                                                           //\n// Base class responsible for holding discretized mesh points and weights    //\n//                                                                           //\n// created November 26, 2017                                                 //\n// copyright Christopher N. Singh Binghamton University Physics              //\n//                                                                           //\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef Mesh_hpp\n#define Mesh_hpp\n\n#include <Eigen/Dense>\n#include <numeric>\n#include <fstream>\n#include <string>\n#include <sstream>\n#include <vector>\n\nclass Mesh \n{\npublic:\n\tMesh(std::string klist_file);\n\n\tEigen::Vector3d point(int index);\n\n\tint weight(int index);\n\tint size();\n\tint norm();\n\nprivate:\n\tstd::vector<Eigen::Vector3d> m_points;\n\tstd::vector<int> m_weights;\n};\n\n#endif /* Mesh_hpp */\n", "meta": {"hexsha": "5030b96d2b83eca0a98f050e5e80f6a8a5daa745", "size": 1198, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/Mesh.hpp", "max_stars_repo_name": "csingh5/SpinCorrelator2", "max_stars_repo_head_hexsha": "90fa4d2a0d427d28fa2694ac8587be5543336095", "max_stars_repo_licenses": ["MIT"], "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/Mesh.hpp", "max_issues_repo_name": "csingh5/SpinCorrelator2", "max_issues_repo_head_hexsha": "90fa4d2a0d427d28fa2694ac8587be5543336095", "max_issues_repo_licenses": ["MIT"], "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/Mesh.hpp", "max_forks_repo_name": "csingh5/SpinCorrelator2", "max_forks_repo_head_hexsha": "90fa4d2a0d427d28fa2694ac8587be5543336095", "max_forks_repo_licenses": ["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.7179487179, "max_line_length": 79, "alphanum_fraction": 0.3514190317, "num_tokens": 160, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.682573734412324, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.4772927014864044}}
{"text": "#ifndef LMHPP\n#define LMHPP\n/* -------------------------------------------------------\n   \n   Levenberg Marquardt algorithm\n   Coded by J. de la Cruz Rodriguez (ISP-SU, 2020)\n   \n   ------------------------------------------------------- */\n\n#include <vector>\n#include <iostream>\n#include <cmath>\n#include <algorithm>\n\n#include <Eigen/Dense>\n\n#include \"Milne.hpp\"\n\nnamespace lm{\n\n  // ***************************************** //\n\n  template<typename T>\n  struct Par{\n    bool isCyclic;\n    bool limited;\n    T scale;\n    T limits[2];\n\n    Par(): isCyclic(false), limited(false), scale(1.0), limits{0,0}{};\n    Par(bool const cyclic, bool const ilimited, T const scal, T const mi, T const ma):\n      isCyclic(cyclic), limited(ilimited), scale(scal), limits{mi,ma}{};\n\n    Par(Par<T> const& in): isCyclic(in.isCyclic) ,limited(in.limited), scale(in.scale), limits{in.limits[0], in.limits[1]}{};\n\n    Par<T> &operator=(Par<T> const& in)\n    {\n      isCyclic = in.isCyclic, limited = in.limited, scale=in.scale, limits[0]=in.limits[0], limits[1]=in.limits[1];\n      return *this;\n    }\n\n    inline void Normalize(T &val)const{val /= scale;};\n    \n    inline void Scale(T &val)const{val *= scale;};\n    \n    inline void Check(T &val)const{\n      if(!limited) return;\n      if(isCyclic){\n\tif(val > limits[1]) val -= 3.1415926f;\n\tif(val < limits[0]) val += 3.1416026f;\n      }\n      val = std::max<T>(std::min<T>(val, limits[1]),limits[0]);\n    }\n    \n    inline void CheckNormalized(T &val)const{\n      if(!limited) return;\n      Scale(val);\n      Check(val);\n      Normalize(val);\n    }\n    \n  };\n  \n  // ***************************************** //\n\n  template<typename T>\n  struct container{\n    int const nDat;\n    T const mu;\n    int Nreal;\n    const ml::Milne<T>& Me;\n    const T* __restrict__ d;\n    const T* __restrict__ sig;\n    const std::vector<Par<T>> &Pinfo;\n\n    container(int const nd, T const imu, ml::Milne<T> const& iMe, const T* __restrict__ din, const T* __restrict__ sigin, const std::vector<Par<T>> &Pi): nDat(nd), mu(imu), Nreal(1), Me(iMe), d(din), sig(sigin), Pinfo(Pi)\n    {\n      // --- only account for non-dummy points in the data array --- //\n      Nreal = 0;\n      for(int ii = 0; ii<nDat; ++ii)\n\tif(sig[ii] < 1.e20) Nreal += 1;\n      \n    }\n    \n  };\n\n  // ***************************************** //\n\n  template<typename T> constexpr inline T SQ(T const v){return v*v;}\n  \n  // ***************************************** //\n\n  template<typename T>\n  T getChi2(int const nDat, const T* __restrict__ r)\n  {\n    double sum = 0.0;\n    int const nDat4 = nDat/4;\n    \n    if(nDat4*4 == nDat){\n      double sumI = 0.0;\n      double sumQ = 0.0;\n      double sumU = 0.0;\n      double sumV = 0.0;\n      \n      for(int ii=0; ii<nDat4; ++ii){\n\tsumI += SQ(r[ii*4+0]);\n\tsumQ += SQ(r[ii*4+1]);\n\tsumU += SQ(r[ii*4+2]);\n\tsumV += SQ(r[ii*4+3]);\n      }\n      sum = sumI + (sumQ + sumU + sumV);\n    }else{\n\n      for(int ii=0; ii<nDat;++ii)\n\tsum += SQ(r[ii]);\n    }\n\n    return static_cast<T>(sum);\n  }\n\n  // ***************************************** //\n\n  template<typename T>\n  T fx(container<T> const& myData, int const nPar, const T* __restrict__ m_in, T* __restrict__ syn, T* __restrict__ r)\n  {\n\n\n    // --- Copy model --- //\n\n    T* __restrict__ m = new T [nPar]();\n    std::memcpy(m,m_in,nPar*sizeof(T));\n\n\n    // --- /// \n    \n    int const nDat = myData.nDat;\n    const T* __restrict__ dat = myData.d;\n    const T* __restrict__ sig = myData.sig;\n    \n    // --- Scale up model --- //\n\n    for(int ii=0; ii<nPar; ++ii){\n      myData.Pinfo[ii].Scale(m[ii]);\n    }\n\n    \n    // --- calculate spectrum --- //\n\n    myData.Me.synthesize(m, syn, myData.mu);\n    \n\n    // --- calculate residue --- //\n\n    T const scl = sqrt(T(myData.Nreal)); \n    for(int ii=0; ii<nDat; ++ii) r[ii] = (dat[ii] - syn[ii]) / (sig[ii] * scl);\n\n\n\n    delete [] m;\n    \n    // --- get Chi2 --- //\n    \n    return getChi2<T>(nDat, r);  \n  }\n    // ***************************************** //\n\n  template<typename T>\n  T fx_dx(container<T> const& myData, int const nPar, const T* __restrict__ m_in, T* __restrict__ syn, T* __restrict__ r, T* __restrict__ J)\n  {\n\n    // --- Copy model --- //\n\n    T* __restrict__ m = new T [nPar]();\n    std::memcpy(m,m_in,nPar*sizeof(T));\n    \n    int const nDat = myData.nDat;\n    const T* __restrict__ dat = myData.d;\n    const T* __restrict__ sig = myData.sig;\n    \n    // --- Scale up model --- //\n\n    for(int ii=0; ii<nPar; ++ii){\n      myData.Pinfo[ii].Scale(m[ii]);\n    }\n\n    \n    // --- calculate spectrum --- //\n\n    myData.Me.synthesize_rf(m, syn, J, myData.mu);\n    \n\n    \n    // --- calculate residue --- //\n\n    T const scl = sqrt(T(myData.Nreal)); \n    for(int ii=0; ii<nDat; ++ii) r[ii] = (dat[ii] - syn[ii]) / (sig[ii] * scl);\n\n\n    // --- scale J --- //\n\n    for(int ii = 0; ii<nPar; ++ii){\n\n      T const iScl = myData.Pinfo[ii].scale / scl;\n      \n      for(int ww = 0; ww<nDat; ++ww)\n\tJ[ii*nDat + ww] *=  iScl / sig[ww];\n    }\n    \n\n    // --- clean up model array --- //\n    delete [] m;\n\n    \n    // --- get Chi2 --- //\n    \n    return getChi2<T>(nDat, r);  \n  }\n\n  // **************************************** // \n  \n  template<typename T>\n  struct LevMar{\n    int nPar;\n    std::vector<T> diag;\n    std::vector<Par<T>> Pinfo;\n\n    void set(int const& iPar){\n      nPar = iPar;\n      diag = std::vector<T>(iPar,0.0);\n      Pinfo = std::vector<Par<T>>(iPar, Par<T>());\n    }\n    \n    LevMar(): nPar(0), diag(), Pinfo(){};\n    LevMar(int const &nPar_i):LevMar(){set(nPar_i);}\n\n    LevMar(LevMar<T> const& in): LevMar(){nPar = in.nPar, diag=in.diag, Pinfo = in.Pinfo;}\n    \n    LevMar<T> &operator=(LevMar<T> const& in){nPar = in.nPar, diag=in.diag(), Pinfo = in.Pinfo; return *this;}\n\n    static inline T checkLambda(T val, T const &mi, T const& ma){return std::max<T>(std::min<T>(ma, val), mi);}\n\n\n    // ------------------------------------------------------------------------------ //\n\n    T getCorrection(container<T> const& myData, T* __restrict__ m, const T* __restrict__ J, T* __restrict__ syn, T* __restrict__ r, T const iLam)const\n    {\n      \n      // --- Simplify the notation --- //\n      \n      using Mat = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;\n      using Vec = Eigen::Matrix<T, Eigen::Dynamic, 1>;\n      \n      using cVecMap = Eigen::Map<const Eigen::Matrix<T, Eigen::Dynamic, 1>>;\n      using cMatMap = Eigen::Map<const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>;\n\n\n      // --- Define some quantities --- //\n\n      int const nDat = myData.nDat;\n      int const cPar = nPar;\n\n      Mat A(cPar, cPar); A.setZero();\n      Vec B(cPar); B.setZero();\n      Vec dm(cPar); dm.setZero();\n      \n      \n      // --- get Hessian matrix --- //\n       \n      for(int jj = 0; jj<cPar; ++jj){\n\n\t// --- Compute left-hand side of the system --- //\n\t\n\tfor(int ii=0; ii<=jj; ++ii){\n\t  double sum = 0.0;\n\t  \n\t  for(int ww=0; ww<nDat; ++ww) sum += J[jj*nDat + ww]*J[ii*nDat + ww];\n\t  A(jj,ii) = A(ii,jj) = static_cast<T>(sum);\n\t}//ii\n\t\n\t\t\n\t// --- Compute right-hand side of the system --- //\n\t\n\tdouble sum = 0.0;\n\tfor(int ww = 0; ww<nDat; ww++) sum += J[jj*nDat+ww] * r[ww];\n\tB[jj] = static_cast<T>(sum); \n\t\n\t\n\tA(jj,jj) *= 1+iLam;\n      } // jj\n\n      \n      // --- Solve linear system to get solution --- //\n      \n      //Eigen::BDCSVD<Mat> sy(A, Eigen::ComputeThinU | Eigen::ComputeThinV);\n      Eigen::ColPivHouseholderQR<Mat> sy(A); // Also rank revealing but much faster than SVD\n      sy.setThreshold(1.e-14);\n      \n      dm = sy.solve(B);\n\n      \n      // --- add to model and check parameters --- //\n\n      for(int ii =0; ii<cPar; ++ii){\n\tm[ii] += dm[ii];\n\tPinfo[ii].CheckNormalized(m[ii]);\n      }   \n      \n      return fx<T>(myData, nPar, m, syn, r);\n    }\n    \n    // ------------------------------------------------------------------------------ //\n    \n    T getStep(container<T> const& myData, T* __restrict__ m, const T* __restrict__ J, T* __restrict__ syn, T* __restrict__ r, T &iLam, bool braket, T const maxLam, T const minLam)const{\n\n      // if(!braket){\n\treturn getCorrection(myData, m, J, syn, r, iLam);\n\t// }\n      \n      \n    }\n    \n    // ------------------------------------------------------------------------------ //\n\n    \n    T fitData(ml::Milne<T> const& Me,  int const nDat, const T* __restrict__ dat, T* __restrict__ syn, const T* __restrict__ sig, T* __restrict__ m, T const mu, int const max_iter = 20, T iLam = sqrt(10.0f), T const Chi2_thres = 1.0, T const fx_thres = 2.e-3, int const delay_braket = 2, bool verbose = true)const\n    {\n      static constexpr T const facLam = 3.1622776601683795;\n      static constexpr T const maxLam = 100*facLam;\n      static constexpr T const minLam = 1.e-4;\n      static constexpr int const max_n_reject = 6;\n      \n      // --- Init container --- //\n\n      container<T> myData(nDat, mu, Me, dat, sig, Pinfo);\n\n\n      \n      // --- Check initial Lambda value --- //\n      \n      iLam = checkLambda(iLam, minLam, maxLam);\n      \n\n      // --- Init temp arrays and values--- //\n      \n      int const cPar = nPar;\n      T bestChi2     = 1.e32;\n      T     Chi2     = 1.e32;\n      \n      T* __restrict__ bestModel  = new T [cPar]();\n      T* __restrict__ bestSyn    = new T [nDat]();      \n\n      T* __restrict__     J      = new T [cPar*nDat]();\n      T* __restrict__     r      = new T [nDat]();\n\n\n      \n      // --- Work with normalized quantities --- //\n\n      for(int ii =0; ii<cPar; ++ii){\n\tPinfo[ii].Check(m[ii]);\n\tPinfo[ii].Normalize(m[ii]);\n      }\n      \n      std::memcpy(bestModel,  m, cPar*sizeof(T));\n\n      \n      // --- get derivatives and init Chi2 --- //\n\n      bestChi2 = fx_dx<T>(myData, nPar, bestModel, bestSyn, r, J);\n\n      \n      // --- Init iteration --- //\n\n      if(verbose){\n\tfprintf(stderr, \"\\nLevDer::fitData: [Init] Chi2=%13.5f\\n\", bestChi2);\n      }\n\n\n      \n      // --- Iterate --- //\n\n      int iter = 0, n_rejected = 0;\n      bool quit = false, tooSmall = false;\n      T oLam = 0, dfx = 0;\n\n      while(iter < max_iter){\n\t\n\toLam = iLam;\n\tstd::memcpy(m, bestModel, nPar*sizeof(T));\n\n\t\n\t// --- Get model correction --- //\n\n\tChi2 = getStep(myData, m, J, syn, r, iLam, false, minLam, maxLam);\n\n\n\t// --- Did Chi2 improve? --- //\n\n\tif(Chi2 < bestChi2){\n\n\t  oLam = iLam;\n\t  dfx = (bestChi2 - Chi2) / bestChi2;\n\t  \n\t  bestChi2 = Chi2;\n\t  std::memcpy(bestModel,   m, cPar*sizeof(T));\n\t  std::memcpy(bestSyn  , syn, nDat*sizeof(T));\n\n\t  if(iLam > 1.0001*minLam)\n\t    iLam = checkLambda(iLam/facLam, minLam, maxLam);\n\t  else\n\t    iLam = 10*minLam;\n\t    \n\t  if(dfx < fx_thres){\n\t    if(tooSmall) quit = true;\n\t    else tooSmall = true;\n\t  }\n\t  \n\t  n_rejected = 0;\n\t}else{\n\t  \n\t  // --- Increase lambda and re-try --- //\n\t  \n\t  iLam = checkLambda(iLam*SQ<T>(facLam), minLam, maxLam);\n\t  n_rejected += 1;\n\t  if(verbose)\n\t    fprintf(stderr,\"LevMar::fitData: Chi2=%13.5f > %13.5f -> Increasing lambda %f -> %f\\n\", Chi2, bestChi2, oLam, iLam);\n\t  \n\t  if(n_rejected<max_n_reject) continue;\n\n\t}\n\t\n\t// --- Check what has happened with Chi2 --- //\n\t\n\tif(n_rejected >= max_n_reject){\n\t  if(verbose)\n\t    fprintf(stderr, \"LevMar::fitData: maximum number of rejected iterations reached, finishing inversion\");\n\t  break;\n\t}\n\n\tif(verbose)\n\t  fprintf(stderr, \"LevMar::fitData [%3d] Chi2=%13.5f, lambda=%e\\n\", iter, Chi2, oLam);\n\n\tif(bestChi2 < Chi2_thres){\n\t  if(verbose)\n\t    fprintf(stderr, \"LevMar::fitData: Chi2 (%f) < Chi2_threshold (%f), finishing inversion\", bestChi2, Chi2_thres);\n\t  break;\n\t}\n\n\tif(quit){\n\t  if(verbose)\n\t    fprintf(stderr, \"LevMar::fitData: Chi2 improvement too small for 2-iterations, finishing inversion\\n\");\n\t  break;\n\t}\n\t\n\titer++;\n\tif(iter >= max_iter){\n\t  break;\n\t}\n\n\t// --- compute gradient of the new model for next iteration --- //\n\n\tstd::memcpy(m, bestModel, cPar*sizeof(T));\n\tfx_dx<T>(myData, nPar, m, syn, r, J);\n      }\n      \n      std::memcpy(m, bestModel, cPar*sizeof(T));\n      std::memcpy(syn, bestSyn, nDat*sizeof(T));\n\n      for(int ii=0; ii<cPar; ++ii)\n\tPinfo[ii].Scale(m[ii]);\n      \n      \n      // --- Clean-up --- //\n\n      delete [] bestModel;\n      delete [] bestSyn;\n      delete [] r;\n      delete [] J;\n\n\n      return bestChi2;\n    }\n    \n  };\n  \n}\n\n\n#endif\n", "meta": {"hexsha": "3d7b6c5e7d1cc491aea74eb272f00fe93c240daf", "size": 12193, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/lm.hpp", "max_stars_repo_name": "HighwayStar/pyMilne", "max_stars_repo_head_hexsha": "630fa3715347584980f2a997f7848179bc3847e9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2020-06-16T08:37:22.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-17T23:48:54.000Z", "max_issues_repo_path": "src/lm.hpp", "max_issues_repo_name": "HighwayStar/pyMilne", "max_issues_repo_head_hexsha": "630fa3715347584980f2a997f7848179bc3847e9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lm.hpp", "max_forks_repo_name": "HighwayStar/pyMilne", "max_forks_repo_head_hexsha": "630fa3715347584980f2a997f7848179bc3847e9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-09-25T13:27:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-28T18:57:13.000Z", "avg_line_length": 24.8836734694, "max_line_length": 313, "alphanum_fraction": 0.5237431313, "num_tokens": 3671, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4772822254240681}}
{"text": "#ifndef ALEPH_GEOMETRY_DOWKER_COMPLEX_HH__\n#define ALEPH_GEOMETRY_DOWKER_COMPLEX_HH__\n\n#include <aleph/math/Combinations.hh>\n\n#include <aleph/topology/filtrations/Data.hh>\n\n#include <aleph/topology/Simplex.hh>\n#include <aleph/topology/SimplicialComplex.hh>\n\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/graph_traits.hpp>\n\n#include <boost/graph/floyd_warshall_shortest.hpp>\n#include <boost/graph/johnson_all_pairs_shortest.hpp>\n\n#include <algorithm>\n#include <iterator>\n#include <limits>\n#include <unordered_map>\n#include <vector>\n\nnamespace aleph\n{\n\nnamespace geometry\n{\n\nnamespace detail\n{\n\n// FIXME: the weight type of an edge should be configurable as an\n// additional template parameter\nusing EdgeWeightProperty = boost::property<boost::edge_weight_t, double>;\n\n// FIXME: the data type of the graph should be configurable as an\n// additional template parameter.\nusing Graph = boost::adjacency_list<\n  boost::vecS,\n  boost::vecS,\n  boost::directedS,\n  boost::no_property,\n  EdgeWeightProperty\n>;\n\nusing VertexDescriptor = boost::graph_traits<Graph>::vertex_descriptor;\n\ntemplate <class T, class I = std::size_t> struct Pair\n{\n  I p; // first index\n  I q; // second index\n  T w; // weight\n};\n\ntemplate <class D, class V> struct Vertex\n{\n  V p; // vertex index\n  D w; // weight\n};\n\ntemplate <class D, class V> void swap( Vertex<D, V>& first, Vertex<D, V>& second )\n{\n  std::swap( first.p, second.p );\n  std::swap( first.w, second.w );\n}\n\n} // namespace detail\n\n/**\n  Calculates a set of admissible pairs from a matrix of weights and\n  a given distance threshold. The matrix of weights does *not* have\n  to satisfy symmetry constraints.\n\n  @param W Weighted adjacency matrix\n  @param R Maximum weight\n*/\n\ntemplate <class Matrix, class T> std::vector< detail::Pair<T> > admissiblePairs( const Matrix& W, T R )\n{\n  using namespace detail;\n\n  // Convert matrix into a graph ---------------------------------------\n\n  auto n          = W.size();\n  using IndexType = decltype(n);\n\n  detail::Graph G( n );\n\n  for( IndexType i = 0; i < n; i++ )\n  {\n    for( IndexType j = 0; j < n; j++ )\n    {\n      if( W[i][j] > 0 )\n      {\n        EdgeWeightProperty weight = W[i][j];\n\n        boost::add_edge( VertexDescriptor(i), VertexDescriptor(j),\n                         weight,\n                         G );\n      }\n    }\n  }\n\n  double density\n    = static_cast<double>( boost::num_edges(G) ) / static_cast<double>( boost::num_vertices(G) * ( boost::num_vertices(G) - 1 ) );\n\n  // This 'pseudo-matrix' contains the completion of the weight function\n  // specified by the input matrix.\n  std::vector< std::vector<double> > D( boost::num_vertices(G),\n                                        std::vector<double>( boost::num_vertices(G) ) );\n\n  if( density >= 0.5 )\n    boost::floyd_warshall_all_pairs_shortest_paths( G, D );\n  else\n    boost::johnson_all_pairs_shortest_paths( G, D );\n\n  std::vector< Pair<T> > pairs;\n\n  // Create admissible pairs -------------------------------------------\n  //\n  // A pair is admissible if it satisfies a reachability property,\n  // meaning that the induced graph distance permits to reach both\n  // vertices under the specified distance threshold.\n\n  for( IndexType i = 0; i < n; i++ )\n  {\n    for( IndexType j = 0; j < n; j++ )\n    {\n      if( D[i][j] <= R )\n        pairs.push_back( {i, j, static_cast<T>( D[i][j] ) } );\n    }\n  }\n\n  return pairs;\n}\n\n/**\n  Creates a Dowker sink complex and a Dowker source complex from a given\n  set of admissible pairs. A *general* Dowker complex contains a simplex\n  if all of its vertices satisfy the admissibility condition.\n\n  @param pairs     Set of admissible pairs\n  @param dimension Maximum dimension for expansion. If set to zero, will\n                   expand the complex to its maximum dimension.\n*/\n\ntemplate <class V, class D, class T>\nstd::pair<\n  topology::SimplicialComplex< topology::Simplex<D, V> >,\n  topology::SimplicialComplex< topology::Simplex<D, V> >\n> buildDowkerSinkSourceComplexes( const std::vector<detail::Pair<T> >& pairs,\n                                  unsigned dimension = 0 )\n{\n  using namespace detail;\n\n  using Simplex           = topology::Simplex<D, V>;\n  using SimplicialComplex = topology::SimplicialComplex<Simplex>;\n\n  using VertexType     = V;\n  VertexType maxVertex = VertexType();\n\n  for( auto&& pair : pairs )\n  {\n    maxVertex = std::max(maxVertex, VertexType(pair.p) );\n    maxVertex = std::max(maxVertex, VertexType(pair.q) );\n  }\n\n  using Vertex = Vertex<D, V>;\n\n  // Keep track of the mapping induced by fixing either the source\n  // points or the sink points.\n  std::unordered_map< VertexType, std::vector<Vertex> > sourceBasePointMap;\n  std::unordered_map< VertexType, std::vector<Vertex> > sinkBasePointMap;\n\n  for( auto&& pair : pairs )\n  {\n    auto&& p = pair.p;\n    auto&& q = pair.q;\n\n    sourceBasePointMap[ VertexType(p) ].push_back( { VertexType(q), pair.w } );\n    sinkBasePointMap[ VertexType(q) ].push_back( { VertexType(p), pair.w } );\n  }\n\n  // Auxiliary weight calculation lambda function ----------------------\n  //\n  // This function calculates the *maximum* weight of a range of\n  // vertices. It is used to determine the weight of a simplex.\n\n  using Iterator = typename std::vector<Vertex>::const_iterator;\n  auto getWeight = [] ( Iterator begin, Iterator end )\n  {\n    using DataType  = D;\n    DataType weight = std::numeric_limits<DataType>::lowest();\n\n    for( auto it = begin; it != end; ++it )\n      weight = std::max( weight, it->w );\n\n    return weight;\n  };\n\n  auto makeSimplices = [&dimension, &getWeight] ( const std::unordered_map< VertexType, std::vector<Vertex> >& map )\n  {\n    std::vector<Simplex> simplices;\n    std::unordered_map<Simplex, D> simplex_to_weight;\n\n    for( auto&& pair : map )\n    {\n      auto vertices            = pair.second;\n      std::size_t maxDimension = 0;\n\n      if( dimension == 0 )\n        maxDimension = vertices.size();\n      else\n        maxDimension = dimension + 1;\n\n      using DifferenceType = typename decltype(vertices)::difference_type;\n\n      for( std::size_t d = std::min( vertices.size(), maxDimension ); d >= 1; d-- )\n      {\n        math::for_each_combination( vertices.begin(), vertices.begin() + DifferenceType(d), vertices.end(),\n          [&simplex_to_weight, &getWeight] ( Iterator first, Iterator last )\n          {\n            std::vector<V> vertices_;\n            vertices_.reserve( typename std::vector<V>::size_type( std::distance( first, last ) ) );\n\n            for( auto it = first; it != last; ++it )\n              vertices_.push_back( it->p );\n\n            Simplex s( vertices_.begin(), vertices_.end() );\n\n            if( simplex_to_weight.find(s) == simplex_to_weight.end() )\n              simplex_to_weight[s] = getWeight(first, last);\n            else\n              simplex_to_weight[s] = std::min( simplex_to_weight[s], getWeight(first, last) );\n\n            return false;\n          }\n        );\n      }\n    }\n\n    for( auto&& pair : simplex_to_weight )\n    {\n      auto s = pair.first;\n      s.setData( pair.second );\n\n      simplices.push_back( s );\n    }\n\n    return simplices;\n  };\n\n  auto sourceEdges = makeSimplices( sourceBasePointMap );\n  auto sinkEdges   = makeSimplices( sinkBasePointMap );\n\n  SimplicialComplex dowkerSourceComplex( sourceEdges.begin(), sourceEdges.end() );\n  SimplicialComplex dowkerSinkComplex  ( sinkEdges.begin()  , sinkEdges.end()   );\n\n  dowkerSourceComplex.sort( topology::filtrations::Data<Simplex>() );\n  dowkerSinkComplex.sort( topology::filtrations::Data<Simplex>() );\n\n  return std::make_pair( dowkerSourceComplex, dowkerSinkComplex );\n}\n\n/**\n  Given a matrix and a maximum radius, creates a Dowker source complex that\n  contains a simplex if all of its vertices are admissible.\n\n  @param matrix    Matrix of weighted adjacencies. The matrix is *not*\n                   assumed to be symmetric.\n\n  @param epsilon   Maximum radius for expansion. I refer to this as epsilon\n                   in order to show the connection to other simplicial complex\n                   creation algorithms.\n\n  @param dimension Maximum dimension for expansion. If set to zero, will\n                   expand the complex to its maximum dimension.\n*/\n\ntemplate\n<\n  class Matrix,\n  class VertexType,\n  class DataType\n> topology::SimplicialComplex< topology::Simplex<DataType, VertexType> >\n    buildDowkerSourceCompplex( const Matrix& matrix,\n                               DataType epsilon,\n                               unsigned dimension = 0 )\n{\n  using namespace detail;\n\n  auto pairs = admissiblePairs( matrix, epsilon );\n\n  using Simplex           = topology::Simplex<DataType, VertexType>;\n  using SimplicialComplex = topology::SimplicialComplex<Simplex>;\n\n  VertexType maxVertex = VertexType();\n\n  for( auto&& pair : pairs )\n  {\n    maxVertex = std::max(maxVertex, VertexType(pair.p) );\n    maxVertex = std::max(maxVertex, VertexType(pair.q) );\n  }\n\n  using Vertex = Vertex<DataType, VertexType>;\n\n  // Keep track of the mapping induced by fixing the source points. In\n  // essence, this is a adjacency list representation of a matrix that\n  // tracks the admissibility of vertices.\n  std::unordered_map< VertexType, std::vector<Vertex> > sourceBasePointMap;\n\n  for( auto&& pair : pairs )\n  {\n    auto&& p = pair.p;\n    auto&& q = pair.q;\n\n    sourceBasePointMap[ VertexType(p) ].push_back( { VertexType(q), pair.w } );\n  }\n\n  // Auxiliary weight calculation lambda function ----------------------\n  //\n  // This function calculates the *maximum* weight of a range of\n  // vertices. It is used to determine the weight of a simplex.\n\n  using Iterator = typename std::vector<Vertex>::const_iterator;\n  auto getWeight = [] ( Iterator begin, Iterator end )\n  {\n    DataType weight = std::numeric_limits<DataType>::lowest();\n\n    for( auto it = begin; it != end; ++it )\n      weight = std::max( weight, it->w );\n\n    return weight;\n  };\n\n  // Create all valid simplices ----------------------------------------\n  //\n  // All valid simplices with respect to the source point are created\n  // by generating all combinations of admissible pairs, with respect\n  // to the given source point.\n  //\n  std::vector<Simplex> simplices;\n\n  {\n    // The same simplex may occur multiple times because it is\n    // 'observed' by multiple source points. We need to obtain\n    // the *earliest* weight at which the simplex occurs!\n    std::unordered_map<Simplex, DataType> simplex_to_weight;\n\n    for( auto&& pair : sourceBasePointMap )\n    {\n      auto vertices            = pair.second;\n      std::size_t maxDimension = 0;\n\n      if( dimension == 0 )\n        maxDimension = vertices.size();\n      else\n        maxDimension = dimension + 1;\n\n      using DifferenceType = typename decltype(vertices)::difference_type;\n\n      for( std::size_t d = std::min( vertices.size(), maxDimension ); d >= 1; d-- )\n      {\n        math::for_each_combination( vertices.begin(), vertices.begin() + DifferenceType(d), vertices.end(),\n          [&simplex_to_weight, &getWeight] ( Iterator first, Iterator last )\n          {\n            std::vector<VertexType> vertices_;\n            vertices_.reserve( typename std::vector<VertexType>::size_type( std::distance( first, last ) ) );\n\n            for( auto it = first; it != last; ++it )\n              vertices_.push_back( it->p );\n\n            Simplex s( vertices_.begin(), vertices_.end() );\n\n            // Ensures that we do not take the default weight, which is\n            // zero, as the weight of the simplex---there does not seem\n            // to be a way to solve this more efficiently...\n            if( simplex_to_weight.find(s) == simplex_to_weight.end() )\n              simplex_to_weight[s] = getWeight(first, last);\n            else\n              simplex_to_weight[s] = std::min( simplex_to_weight[s], getWeight(first, last) );\n\n            return false;\n          }\n        );\n      }\n    }\n\n    // Set the weights of all simplices prior to inserting them into the\n    // simplicial complex.\n    for( auto&& pair : simplex_to_weight )\n    {\n      auto s = pair.first;\n      s.setData( pair.second );\n\n      simplices.push_back( s );\n    }\n  }\n\n  SimplicialComplex K( simplices.begin(), simplices.end() );\n  K.sort( topology::filtrations::Data<Simplex>() );\n\n  return K;\n}\n\n} // namespace geometry\n\n} // namespace aleph\n\n#endif\n", "meta": {"hexsha": "0825d4ffc84844af2ba1952eec39d40868b8dc93", "size": 12312, "ext": "hh", "lang": "C++", "max_stars_repo_path": "include/aleph/geometry/DowkerComplex.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/geometry/DowkerComplex.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/geometry/DowkerComplex.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": 29.9562043796, "max_line_length": 130, "alphanum_fraction": 0.6355588044, "num_tokens": 3010, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4772822254240681}}
{"text": "// Boost.Geometry\n\n// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.\n\n// This file was modified by Oracle on 2014.\n// Modifications copyright (c) 2014 Oracle and/or its affiliates.\n\n// Contributed and/or modified by 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_AGNOSTIC_SIDE_BY_AZIMUTH_HPP\n#define BOOST_GEOMETRY_STRATEGIES_AGNOSTIC_SIDE_BY_AZIMUTH_HPP\n\n#include <boost/mpl/if.hpp>\n#include <boost/type_traits.hpp>\n#include <boost/core/ignore_unused.hpp>\n\n#include <boost/geometry/core/cs.hpp>\n#include <boost/geometry/core/access.hpp>\n#include <boost/geometry/core/radian_access.hpp>\n\n#include <boost/geometry/algorithms/detail/azimuth.hpp>\n\n#include <boost/geometry/util/math.hpp>\n#include <boost/geometry/util/promote_floating_point.hpp>\n#include <boost/geometry/util/select_calculation_type.hpp>\n\n#include <boost/geometry/strategies/side.hpp>\n//#include <boost/geometry/strategies/concepts/side_concept.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\n\nnamespace strategy { namespace side\n{\n\n/*!\n\\brief Check at which side of a segment a point lies\n         left of segment (> 0), right of segment (< 0), on segment (0)\n\\ingroup strategies\n\\tparam Model Reference model of coordinate system.\n\\tparam CalculationType \\tparam_calculation\n */\ntemplate <typename Model, typename CalculationType = void>\nclass side_by_azimuth\n{\npublic:\n    side_by_azimuth(Model const& model = Model())\n        : m_model(model)\n    {}\n\n    template <typename P1, typename P2, typename P>\n    inline int apply(P1 const& p1, P2 const& p2, P const& p)\n    {\n        typedef typename promote_floating_point\n            <\n                typename select_calculation_type_alt\n                    <\n                        CalculationType,\n                        P1, P2, P\n                    >::type\n            >::type calc_t;\n\n        calc_t d1 = 0.001;\n        calc_t crs_AD = geometry::detail::azimuth<calc_t>(p1, p, m_model);\n        calc_t crs_AB = geometry::detail::azimuth<calc_t>(p1, p2, m_model);\n        calc_t XTD = asin(sin(d1) * sin(crs_AD - crs_AB));\n\n        return math::equals(XTD, 0) ? 0 : XTD < 0 ? 1 : -1;\n    }\n\nprivate:\n    Model m_model;\n};\n\n}} // namespace strategy::side\n\n\n}} // namespace boost::geometry\n\n\n#endif // BOOST_GEOMETRY_STRATEGIES_AGNOSTIC_SIDE_BY_AZIMUTH_HPP\n", "meta": {"hexsha": "14c69a0597c91b79ede868b9f996b7e2ffb02dc6", "size": 2509, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/cinder/include/boost/geometry/strategies/agnostic/side_by_azimuth.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": 113.0, "max_stars_repo_stars_event_min_datetime": "2018-07-12T07:49:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-16T12:41:53.000Z", "max_issues_repo_path": "deps/cinder/include/boost/geometry/strategies/agnostic/side_by_azimuth.hpp", "max_issues_repo_name": "multi-os-engine/cinder-natj-binding", "max_issues_repo_head_hexsha": "969b66fdd49e4ca63442baf61ce90ae385ab8178", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 81.0, "max_issues_repo_issues_event_min_datetime": "2018-03-01T18:05:41.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-15T18:47:31.000Z", "max_forks_repo_path": "deps/cinder/include/boost/geometry/strategies/agnostic/side_by_azimuth.hpp", "max_forks_repo_name": "multi-os-engine/cinder-natj-binding", "max_forks_repo_head_hexsha": "969b66fdd49e4ca63442baf61ce90ae385ab8178", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 51.0, "max_forks_repo_forks_event_min_datetime": "2018-07-16T06:09:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-01T13:18:36.000Z", "avg_line_length": 28.5113636364, "max_line_length": 79, "alphanum_fraction": 0.6978876046, "num_tokens": 632, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4772822200325273}}
{"text": "#include \"catch.hpp\"\n\n#include \"libirc/io.h\"\n\n#include \"config.h\"\n\n#ifdef HAVE_ARMA\n#include <armadillo>\nusing arma::mat;\nusing arma::vec;\nusing arma::vec3;\n#elif HAVE_EIGEN3\n#include <Eigen/Dense>\nusing vec3 = Eigen::Vector3d;\nusing vec = Eigen::VectorXd;\nusing mat = Eigen::MatrixXd;\n\n#else\n#error\n#endif\n\nTEST_CASE(\"File not found\") {\n  using irc::io::load_xyz;\n\n  REQUIRE_THROWS_AS(load_xyz<vec3>(irc::config::molecules_dir + \"ABC.xyz\"),\n                    std::runtime_error);\n\n  REQUIRE_NOTHROW(load_xyz<vec3>(irc::config::molecules_dir + \"caffeine.xyz\"));\n}\n\nTEST_CASE(\"Print molecule\") {\n  using namespace irc;\n  using namespace io;\n  using namespace connectivity;\n  using namespace molecule;\n  using namespace tools;\n\n  // Load toluene molecule\n  const auto mol = load_xyz<vec3>(config::molecules_dir + \"benzene_dimer.xyz\");\n\n  // Compute interatomic distance for formaldehyde molecule\n  const mat dd{distances<vec3, mat>(mol)};\n\n  // Build graph based on the adjacency matrix\n  const UGraph adj{adjacency_matrix(dd, mol)};\n\n  // Compute distance matrix and predecessor matrix\n  mat dist{distance_matrix<mat>(adj)};\n\n  // Compute bonds\n  const std::vector<Bond> B{bonds(dist, mol)};\n\n  // Print bonds to std::cout\n  print_bonds<vec3, vec>(to_cartesian<vec3, vec>(mol), B);\n\n  // Compute angles\n  const std::vector<Angle> A{angles(dist, mol)};\n\n  // Print angles to std::cout\n  print_angles<vec3, vec>(to_cartesian<vec3, vec>(mol), A);\n\n  // Compute dihedral angles\n  const std::vector<Dihedral> D{dihedrals(dist, mol)};\n\n  // Print dihedrals to std::cout\n  print_dihedrals<vec3, vec>(to_cartesian<vec3, vec>(mol), D);\n\n  // Compute out of plane bends\n  const std::vector<OutOfPlaneBend> OOPB{out_of_plane_bends(dist, mol)};\n\n  // Print dihedrals to std::cout\n  print_out_of_plane_bends<vec3, vec>(to_cartesian<vec3, vec>(mol), OOPB);\n}\n", "meta": {"hexsha": "42b0bf92b51c8ba9f08d541a99273b7b2bda3af9", "size": 1846, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/io_test.cpp", "max_stars_repo_name": "francesco-bosia/irc", "max_stars_repo_head_hexsha": "6d5c7c372d02ecdbd50f8981669c46ddae0638ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2018-01-30T16:12:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T00:20:23.000Z", "max_issues_repo_path": "src/test/io_test.cpp", "max_issues_repo_name": "francesco-bosia/irc", "max_issues_repo_head_hexsha": "6d5c7c372d02ecdbd50f8981669c46ddae0638ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 45.0, "max_issues_repo_issues_event_min_datetime": "2018-01-11T13:21:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-16T19:59:39.000Z", "max_forks_repo_path": "src/test/io_test.cpp", "max_forks_repo_name": "francesco-bosia/irc", "max_forks_repo_head_hexsha": "6d5c7c372d02ecdbd50f8981669c46ddae0638ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2019-04-11T15:46:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-22T10:00:16.000Z", "avg_line_length": 24.9459459459, "max_line_length": 79, "alphanum_fraction": 0.7091007584, "num_tokens": 542, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.47728222003252724}}
{"text": "#ifndef __BETA_H__\n#define __BETA_H__\n\n#include <armadillo>\n\n#include <vector>\n\n/**\n * Estimates parameters for the beta distribution using the\n * method of moments. The method of moments estimates will have\n * a higher variance than maximum likelihood, but is faster and\n * simpler.\n *\n * @param samples A list of samples to fit a beta distribution to.\n *\n * @return The estimated parameters, if they could not be estimated,\n *         the parameters 1,1 will be returned. \n */\narma::vec mom_beta(const arma::vec &samples);\n\n#endif /* End of __BETA_H__ */\n", "meta": {"hexsha": "05d483263c33c4521d5ffd0fd97bfc68eb25bf3e", "size": 557, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/besiq/stats/beta.hpp", "max_stars_repo_name": "hoehleatsu/besiq", "max_stars_repo_head_hexsha": "94959e2819251805e19311ce377919e6bccb7bf9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-10-21T14:22:12.000Z", "max_stars_repo_stars_event_max_datetime": "2015-10-21T14:22:12.000Z", "max_issues_repo_path": "libs/besiq/stats/beta.hpp", "max_issues_repo_name": "hoehleatsu/besiq", "max_issues_repo_head_hexsha": "94959e2819251805e19311ce377919e6bccb7bf9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-05-26T20:52:31.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-28T16:19:49.000Z", "max_forks_repo_path": "libs/besiq/stats/beta.hpp", "max_forks_repo_name": "hoehleatsu/besiq", "max_forks_repo_head_hexsha": "94959e2819251805e19311ce377919e6bccb7bf9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2016-11-06T14:58:37.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-26T14:03:13.000Z", "avg_line_length": 25.3181818182, "max_line_length": 68, "alphanum_fraction": 0.723518851, "num_tokens": 129, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7248702761768249, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.4772672851889175}}
{"text": "/*\n [auto_generated]\n libs/numeric/odeint/test/integrate_times.cpp\n\n [begin_description]\n This file tests the integrate_times function and its variants.\n [end_description]\n\n Copyright 2011-2012 Karsten Ahnert\n Copyright 2011-2012 Mario Mulansky\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#define BOOST_TEST_MODULE odeint_integrate_times\n\n#include <boost/test/unit_test.hpp>\n\n#include <utility>\n#include <iostream>\n#include <vector>\n\n#include <boost/ref.hpp>\n#include <boost/iterator/counting_iterator.hpp>\n\n#ifndef ODEINT_INTEGRATE_ITERATOR\n#include <boost/numeric/odeint/integrate/integrate_times.hpp>\n#include <boost/numeric/odeint/integrate/integrate_adaptive.hpp>\n#else\n#include <boost/numeric/odeint/iterator/integrate/integrate_times.hpp>\n#include <boost/numeric/odeint/iterator/integrate/integrate_adaptive.hpp>\n#endif\n#include <boost/numeric/odeint/stepper/runge_kutta4.hpp>\n#include <boost/numeric/odeint/stepper/runge_kutta_dopri5.hpp>\n#include <boost/numeric/odeint/stepper/runge_kutta_cash_karp54.hpp>\n#include <boost/numeric/odeint/stepper/controlled_runge_kutta.hpp>\n#include <boost/numeric/odeint/stepper/bulirsch_stoer.hpp>\n#include <boost/numeric/odeint/stepper/bulirsch_stoer_dense_out.hpp>\n#include <boost/numeric/odeint/stepper/dense_output_runge_kutta.hpp>\n\nusing namespace boost::unit_test;\nusing namespace boost::numeric::odeint;\n\ntypedef double value_type;\ntypedef std::vector< value_type > state_type;\n\n\nvoid lorenz( const state_type &x , state_type &dxdt , const value_type t )\n{\n    BOOST_CHECK( t >= 0.0 );\n\n    const value_type sigma( 10.0 );\n    const value_type R( 28.0 );\n    const value_type b( value_type( 8.0 ) / value_type( 3.0 ) );\n\n    dxdt[0] = sigma * ( x[1] - x[0] );\n    dxdt[1] = R * x[0] - x[1] - x[0] * x[2];\n    dxdt[2] = -b * x[2] + x[0] * x[1];\n}\n\nstruct push_back_time\n{\n    std::vector< double >& m_times;\n\n    push_back_time( std::vector< double > &times )\n    :  m_times( times ) { }\n\n    void operator()( const state_type &x , double t )\n    {\n        m_times.push_back( t );\n    }\n};\n\nBOOST_AUTO_TEST_SUITE( integrate_times_test )\n\nBOOST_AUTO_TEST_CASE( test_integrate_times )\n{\n\n    state_type x( 3 );\n    x[0] = x[1] = x[2] = 10.0;\n\n    const value_type dt = 0.03;\n\n    std::vector< double > times;\n\n    std::cout << \"test rk4 stepper\" << std::endl;\n\n    // simple stepper\n    integrate_times( runge_kutta4< state_type >() , lorenz , x , boost::counting_iterator<int>(0) , boost::counting_iterator<int>(10) ,\n                dt , push_back_time( times ) );\n\n    for( int i=0 ; i<10 ; ++i )\n        // check if observer was called at times 0,1,2,...\n        BOOST_CHECK_EQUAL( times[i] , static_cast<double>(i) );\n    times.clear();\n\n    std::cout << \"test dopri5 stepper\" << std::endl;\n\n    // controlled stepper\n    integrate_times( controlled_runge_kutta< runge_kutta_dopri5< state_type > >() , lorenz , x ,\n                boost::counting_iterator<int>(0) , boost::counting_iterator<int>(10) ,\n                dt , push_back_time( times ) );\n\n    for( int i=0 ; i<10 ; ++i )\n        // check if observer was called at times 0,1,2,...\n        BOOST_CHECK_EQUAL( times[i] , static_cast<double>(i) );\n    times.clear();\n\n    std::cout << \"test BS stepper\" << std::endl;\n\n    //another controlled stepper\n    integrate_times( bulirsch_stoer< state_type >() , lorenz , x ,\n                boost::counting_iterator<int>(0) , boost::counting_iterator<int>(10) ,\n                dt , push_back_time( times ) );\n\n    for( int i=0 ; i<10 ; ++i )\n        // check if observer was called at times 0,1,2,...\n        BOOST_CHECK_EQUAL( times[i] , static_cast<double>(i) );\n    times.clear();\n\n    std::cout << \"test dense_out stepper\" << std::endl;\n\n    // dense output stepper\n    integrate_times( dense_output_runge_kutta< controlled_runge_kutta< runge_kutta_dopri5< state_type > > >() ,\n                     lorenz , x ,\n                     boost::counting_iterator<int>(0) , boost::counting_iterator<int>(10) ,\n                     dt , push_back_time( times ) );\n\n    for( int i=0 ; i<10 ; ++i )\n        // check if observer was called at times 0,1,2,...\n        BOOST_CHECK_EQUAL( times[i] , static_cast<double>(i) );\n\n    std::cout << \"test BS_do stepper\" << std::endl;\n\n    integrate_times( bulirsch_stoer_dense_out< state_type >() , lorenz , x ,\n                boost::counting_iterator<int>(0) , boost::counting_iterator<int>(10) ,\n                dt , push_back_time( times ) );\n\n    for( int i=0 ; i<10 ; ++i )\n        // check if observer was called at times 0,1,2,...\n        BOOST_CHECK_EQUAL( times[i] , static_cast<double>(i) );\n\n}\n\n\nBOOST_AUTO_TEST_CASE( test_integrate_times_ranges )\n{\n\n    state_type x( 3 );\n    x[0] = x[1] = x[2] = 10.0;\n\n    const value_type dt = 0.03;\n\n    std::vector< double > times;\n\n    // simple stepper\n    integrate_times( runge_kutta4< state_type >() , lorenz , x ,\n                std::make_pair( boost::counting_iterator<int>(0) , boost::counting_iterator<int>(10) ) ,\n                dt , push_back_time( times ) );\n\n    for( int i=0 ; i<10 ; ++i )\n        // check if observer was called at times 0,1,2,...\n        BOOST_CHECK_EQUAL( times[i] , static_cast<double>(i) );\n    times.clear();\n\n    // controlled stepper\n    integrate_times( controlled_runge_kutta< runge_kutta_dopri5< state_type > >() , lorenz , x ,\n                std::make_pair( boost::counting_iterator<int>(0) , boost::counting_iterator<int>(10) ) ,\n                dt , push_back_time( times ) );\n\n    for( int i=0 ; i<10 ; ++i )\n        // check if observer was called at times 0,1,2,...\n        BOOST_CHECK_EQUAL( times[i] , static_cast<double>(i) );\n    times.clear();\n\n    //another controlled stepper\n    integrate_times( bulirsch_stoer< state_type >() , lorenz , x ,\n                std::make_pair( boost::counting_iterator<int>(0) , boost::counting_iterator<int>(10) ) ,\n                dt , push_back_time( times ) );\n\n    for( int i=0 ; i<10 ; ++i )\n        // check if observer was called at times 0,1,2,...\n        BOOST_CHECK_EQUAL( times[i] , static_cast<double>(i) );\n    times.clear();\n\n\n    // dense output stepper\n    integrate_times( bulirsch_stoer_dense_out< state_type >() , lorenz , x ,\n                std::make_pair( boost::counting_iterator<int>(0) , boost::counting_iterator<int>(10) ) ,\n                dt , push_back_time( times ) );\n\n    for( int i=0 ; i<10 ; ++i )\n        // check if observer was called at times 0,1,2,...\n        BOOST_CHECK_EQUAL( times[i] , static_cast<double>(i) );\n\n}\n\nBOOST_AUTO_TEST_CASE( test_integrate_times_overshoot )\n{\n    state_type x( 3 );\n    x[0] = x[1] = x[2] = 10.0;\n    double dt = -0.1;\n\n    std::vector<double> times( 10 );\n    for( int i=0 ; i<10 ; ++i )\n            times[i] = 1.0-i*1.0/9.0;\n\n    std::cout << \"test rk4 stepper\" << std::endl;\n    // simple stepper\n    std::vector<double> obs_times;\n    int steps = integrate_times( runge_kutta4< state_type >() , lorenz , x ,\n                                 times.begin() , times.end() ,\n                                 dt , push_back_time( obs_times ) );\n// different behavior for the iterator based integrate implementaton\n#ifndef ODEINT_INTEGRATE_ITERATOR\n    BOOST_CHECK_EQUAL( steps , 18 ); // we really need 18 steps because dt and\n                                     // the difference of the observation times\n                                     // are so out of sync\n#else\n    // iterator based implementation can only return the number of iteration steps\n    BOOST_CHECK_EQUAL( steps , 9 );\n#endif\n    for( int i=0 ; i<10 ; ++i )\n        BOOST_CHECK_EQUAL( times[i] , obs_times[i] );\n\n    std::cout << \"test rk_ck stepper\" << std::endl;\n    // controlled stepper\n    obs_times.clear();\n    integrate_times( controlled_runge_kutta< runge_kutta_cash_karp54< state_type > >() , lorenz , x ,\n                     times.begin() , times.end() ,\n                     dt , push_back_time( obs_times ) );\n    for( int i=0 ; i<10 ; ++i )\n        BOOST_CHECK_EQUAL( times[i] , obs_times[i] );\n\n    std::cout << \"test dopri5 stepper\" << std::endl;\n    // controlled stepper\n    obs_times.clear();\n    integrate_times( dense_output_runge_kutta< controlled_runge_kutta< runge_kutta_dopri5< state_type > > >() , lorenz , x ,\n                     times.begin() , times.end() ,\n                     dt , push_back_time( obs_times ) );\n    for( int i=0 ; i<10 ; ++i )\n        BOOST_CHECK_EQUAL( times[i] , obs_times[i] );\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "2837f09e38e14a1cf467df50abd0d4d8619383d6", "size": 8551, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/odeint/test/integrate_times.cpp", "max_stars_repo_name": "cpp-pm/boost", "max_stars_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "libs/numeric/odeint/test/integrate_times.cpp", "max_issues_repo_name": "cpp-pm/boost", "max_issues_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "libs/numeric/odeint/test/integrate_times.cpp", "max_forks_repo_name": "cpp-pm/boost", "max_forks_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_forks_repo_licenses": ["BSL-1.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.4798387097, "max_line_length": 135, "alphanum_fraction": 0.6249561455, "num_tokens": 2369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.7248702880639791, "lm_q1q2_score": 0.4772672832985123}}
{"text": "//  Boost pow_test.cpp test file\n//  Tests the pow function\n\n//  (C) Copyright Bruno Lalande 2008.\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 <cmath>\n#include <string>\n#include <iostream>\n\n#include <boost/math/concepts/real_concept.hpp>\n#include <boost/test/test_exec_monitor.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n\n#include <boost/typeof/typeof.hpp>\n#include <boost/type_traits/is_same.hpp>\n#include <boost/static_assert.hpp>\n\n#include <boost/math/special_functions/pow.hpp>\n\n#include BOOST_TYPEOF_INCREMENT_REGISTRATION_GROUP()\nBOOST_TYPEOF_REGISTER_TYPE(boost::math::concepts::real_concept)\n\nusing namespace boost;\nusing namespace boost::math;\n\ntemplate <int N, class T>\nvoid test_pow(T base)\n{\n    typedef typename tools::promote_args<T>::type result_type;\n\n    BOOST_MATH_STD_USING\n\n    if ((base == 0) && N < 0)\n    {\n       BOOST_CHECK_THROW(math::pow<N>(base), std::overflow_error);\n    }\n    else\n    {\n       BOOST_CHECK_CLOSE(math::pow<N>(base),\n              pow(static_cast<result_type>(base), static_cast<result_type>(N)),\n              boost::math::tools::epsilon<result_type>() * 100 * 400); // 400 eps as a %\n    }\n}\n\ntemplate <int N, class T>\nvoid test_with_big_bases()\n{\n    for (T base = T(); base < T(1000); ++base)\n        test_pow<N>(base);\n}\n\ntemplate <int N, class T>\nvoid test_with_small_bases()\n{\n    T base = 0.9f;\n    for (int i = 0; i < 10; ++i)\n    {\n        base += base/50;\n        test_pow<N>(base);\n    }\n}\n\ntemplate <class T, int Factor>\nvoid test_with_small_exponents()\n{\n    test_with_big_bases<0, T>();\n    test_with_big_bases<Factor*1, T>();\n    test_with_big_bases<Factor*2, T>();\n    test_with_big_bases<Factor*3, T>();\n    test_with_big_bases<Factor*5, T>();\n    test_with_big_bases<Factor*6, T>();\n    test_with_big_bases<Factor*7, T>();\n    test_with_big_bases<Factor*8, T>();\n    test_with_big_bases<Factor*9, T>();\n    test_with_big_bases<Factor*10, T>();\n    test_with_big_bases<Factor*11, T>();\n    test_with_big_bases<Factor*12, T>();\n}\n\ntemplate <class T, int Factor>\nvoid test_with_big_exponents()\n{\n    test_with_small_bases<Factor*50, T>();\n    test_with_small_bases<Factor*100, T>();\n    test_with_small_bases<Factor*150, T>();\n    test_with_small_bases<Factor*200, T>();\n    test_with_small_bases<Factor*250, T>();\n    test_with_small_bases<Factor*300, T>();\n    test_with_small_bases<Factor*350, T>();\n    test_with_small_bases<Factor*400, T>();\n    test_with_small_bases<Factor*450, T>();\n    test_with_small_bases<Factor*500, T>();\n}\n\n\nvoid test_return_types()\n{\n    BOOST_STATIC_ASSERT((is_same<BOOST_TYPEOF(pow<2>('\\1')), double>::value));\n    BOOST_STATIC_ASSERT((is_same<BOOST_TYPEOF(pow<2>(L'\\2')), double>::value));\n    BOOST_STATIC_ASSERT((is_same<BOOST_TYPEOF(pow<2>(3)), double>::value));\n    BOOST_STATIC_ASSERT((is_same<BOOST_TYPEOF(pow<2>(4u)), double>::value));\n    BOOST_STATIC_ASSERT((is_same<BOOST_TYPEOF(pow<2>(5ul)), double>::value));\n    BOOST_STATIC_ASSERT((is_same<BOOST_TYPEOF(pow<2>(6.0f)), float>::value));\n    BOOST_STATIC_ASSERT((is_same<BOOST_TYPEOF(pow<2>(7.0)), double>::value));\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n    BOOST_STATIC_ASSERT((is_same<BOOST_TYPEOF(pow<2>(7.0l)), long double>::value));\n#endif\n}\n\n\nnamespace boost { namespace math { namespace policies {\ntemplate <class T>\nT user_overflow_error(const char*, const char*, const T&)\n{ return T(123.45); }\n}}}\n\nnamespace boost { namespace math { namespace policies {\ntemplate <class T>\nT user_indeterminate_result_error(const char*, const char*, const T&)\n{ return T(456.78); }\n}}}\n\n\nvoid test_error_policy()\n{\n    using namespace policies;\n\n    BOOST_CHECK(pow<-2>(\n                    0.0,\n                    policy< ::boost::math::policies::overflow_error<user_error> >()\n                )\n                == 123.45);\n\n    BOOST_CHECK(pow<0>(\n                    0.0,\n                    policy< ::boost::math::policies::indeterminate_result_error<user_error> >()\n                )\n                == 456.78);\n}\n\nint test_main(int, char* [])\n{\n    using namespace std;\n\n    cout << \"Testing with integral bases and positive small exponents\" << endl;\n    test_with_small_exponents<int, 1>();\n    cout << \"Testing with integral bases and negative small exponents\" << endl;\n    test_with_small_exponents<int, -1>();\n\n    cout << \"Testing with float precision bases and positive small exponents\" << endl;\n    test_with_small_exponents<float, 1>();\n    cout << \"Testing with float precision bases and negative small exponents\" << endl;\n    test_with_small_exponents<float, -1>();\n\n    cout << \"Testing with float precision bases and positive big exponents\" << endl;\n    test_with_big_exponents<float, 1>();\n    cout << \"Testing with float precision bases and negative big exponents\" << endl;\n    test_with_big_exponents<float, -1>();\n\n     cout << \"Testing with double precision bases and positive small exponents\" << endl;\n    test_with_small_exponents<double, 1>();\n    cout << \"Testing with double precision bases and negative small exponents\" << endl;\n    test_with_small_exponents<double, -1>();\n\n    cout << \"Testing with double precision bases and positive big exponents\" << endl;\n    test_with_big_exponents<double, 1>();\n    cout << \"Testing with double precision bases and negative big exponents\" << endl;\n    test_with_big_exponents<double, -1>();\n\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n    cout << \"Testing with long double precision bases and positive small exponents\" << endl;\n    test_with_small_exponents<long double, 1>();\n    cout << \"Testing with long double precision bases and negative small exponents\" << endl;\n    test_with_small_exponents<long double, -1>();\n\n    cout << \"Testing with long double precision bases and positive big exponents\" << endl;\n    test_with_big_exponents<long double, 1>();\n    cout << \"Testing with long double precision bases and negative big exponents\" << endl;\n    test_with_big_exponents<long double, -1>();\n\n    cout << \"Testing with concepts::real_concept precision bases and positive small exponents\" << endl;\n    test_with_small_exponents<boost::math::concepts::real_concept, 1>();\n    cout << \"Testing with concepts::real_concept precision bases and negative small exponents\" << endl;\n    test_with_small_exponents<boost::math::concepts::real_concept, -1>();\n\n    cout << \"Testing with concepts::real_concept precision bases and positive big exponents\" << endl;\n    test_with_big_exponents<boost::math::concepts::real_concept, 1>();\n    cout << \"Testing with concepts::real_concept precision bases and negative big exponents\" << endl;\n    test_with_big_exponents<boost::math::concepts::real_concept, -1>();\n#endif\n\n    test_return_types();\n\n    test_error_policy();\n\n    return 0;\n}\n\n/*\n\n  Running 1 test case...\n  Testing with integral bases and positive small exponents\n  Testing with integral bases and negative small exponents\n  Testing with float precision bases and positive small exponents\n  Testing with float precision bases and negative small exponents\n  Testing with float precision bases and positive big exponents\n  Testing with float precision bases and negative big exponents\n  Testing with double precision bases and positive small exponents\n  Testing with double precision bases and negative small exponents\n  Testing with double precision bases and positive big exponents\n  Testing with double precision bases and negative big exponents\n  Testing with long double precision bases and positive small exponents\n  Testing with long double precision bases and negative small exponents\n  Testing with long double precision bases and positive big exponents\n  Testing with long double precision bases and negative big exponents\n  Testing with concepts::real_concept precision bases and positive small exponents\n  Testing with concepts::real_concept precision bases and negative small exponents\n  Testing with concepts::real_concept precision bases and positive big exponents\n  Testing with concepts::real_concept precision bases and negative big exponents\n  \n  *** No errors detected\n\n  */\n", "meta": {"hexsha": "29fb4fffa018373d78129c082d1d7c888bdf1131", "size": 8174, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/math/test/pow_test.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2016-04-12T16:29:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-28T11:01:57.000Z", "max_issues_repo_path": "boost/libs/math/test/pow_test.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-10-31T19:35:14.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-04T17:11:27.000Z", "max_forks_repo_path": "boost/libs/math/test/pow_test.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-09-09T02:38:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-30T00:24:24.000Z", "avg_line_length": 36.0088105727, "max_line_length": 103, "alphanum_fraction": 0.7101786151, "num_tokens": 1965, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702880639791, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.4772672832985123}}
{"text": "#include <fstream>\n#include <iostream>\n#include <memory>\n#include <pcl/common/common_headers.h>\n#include <pcl/console/parse.h>\n#include <pcl/io/pcd_io.h>\n#include <pcl/point_types.h>\n#include <boost/tokenizer.hpp>\n\nnamespace {\nusing ::pcl::PointCloud;\nusing ::pcl::PointXYZ;\n\n// Command usage help\nvoid printUsage (const char* progName)\n{\n  std::cout << \"\\n\\nUsage: \"<<progName<<\" [options] <data.txt> <outfile.pcd>\\n\\n\"\n            << \"Options:\\n\"\n            << \"-------------------------------------------\\n\"\n            << \"-h           this help text\\n\"\n            << \"\\n\\n\";\n}\n\nstd::unique_ptr<PointCloud<PointXYZ>> makeCloud() {\n\tauto cloud = std::make_unique<PointCloud<PointXYZ>>();\n\n\t// dimensions of the tof image\n\tcloud->width = 180;\n\tcloud->height = 240;\n\t// We may have NaN values in data set\n\tcloud->is_dense = false;\n\tcloud->points.resize(cloud->width * cloud->height);\n\n\t// Set sensor location to world coordinate center\n\tcloud->sensor_origin_.setZero();\n\tcloud->sensor_orientation_.w() = 0.0f;\n\tcloud->sensor_orientation_.x() = 1.0f;\n\tcloud->sensor_orientation_.y() = 0.0f;\n\tcloud->sensor_orientation_.z() = 0.0f;\n\treturn cloud;\n}\n\n// Use camera intrinsic parameters to transform points from u,v,depth\n// into real-world xyz coordinates. (Depth sensor is assumed at (0,0,0))\npcl::PointXYZ pointXYZFromDepth(float u, float v, float depth) {\n\n\tconst float bad_point = std::numeric_limits<float>::quiet_NaN (); \n\n\t// Camera intrinsic parameters\n\tconst float alph_x = 492.68967;\t\t// focal width / sensor width\n\tconst float alph_y = 492.6062;\t\t// focal height / sensor height\n\tconst float u0 = 323.59485;\t\t\t// image center \n\tconst float v0 = 234.65974;\t\t\t// image center\n\n\tpcl::PointXYZ point;\n\n\t// depth value of zero is invalid\n\tif (depth == 0) {\n\t\tpoint.x = point.y = point.z = bad_point;\n\t\treturn point;\n\t}\n\n\tpoint.x = depth * ((u - u0) / alph_x);\n\tpoint.y = depth * ((v - v0) / alph_y);\n\tpoint.z = depth;\n\treturn point;\n}\n\nint writePcd(const std::string& filename, const std::string& outfile) {\n\n\t// Open the raw file for reading\n\tstd::ifstream infile(filename);\n\tif (!infile) {\n\t\tthrow std::runtime_error(\"File not found.\");\n\t}\n\n\tstd::unique_ptr<PointCloud<PointXYZ>> cloud = makeCloud();\n\tint i = 0;\n\t// File format: u,v,depth,confidence\n\tstd::vector<float> data(4);\n\n\t// Read file and insert data into point cloud\n\tfor (std::string line; std::getline(infile, line) && i < cloud->points.size();) {\n     \tboost::tokenizer<boost::char_separator<char>> tok(line, boost::char_separator<char>(\",\"));\n     \tdata.clear();\n     \tfor (const auto& t: tok) {\n     \t\tdata.push_back(std::stof(t));\t\n     \t}\n     \tif (data.size() < 3) {\n     \t\tthrow std::runtime_error(\"Incorrect file format on line \" + std::to_string(i));\n     \t}\n\n     \t// Transform from u,v,d into x,y,z world coordinates\n     \tcloud->points[i] = pointXYZFromDepth(data[0], data[1], data[2]);\n\t\ti++;\n\t}\n\n\t// Write point cloud to file\n\tpcl::io::savePCDFileASCII (outfile, *cloud);\n\tstd::cerr << \"Saved \" << cloud->size() << \" data points to \" << outfile << std::endl;\n\n\treturn(0);\n\n}\n} // namespace\n\nint main (int argc, char** argv) {\n\n\t// Parse command-line arguments\n  \tif (pcl::console::find_argument (argc, argv, \"-h\") >= 0)\n  \t{\n    \tprintUsage(argv[0]);\n    \treturn 0;\n  \t}\n  \tif (argc != 3) {\n  \t\tstd::cout << \"Incorrect number of arguments.\";\n  \t\tprintUsage(argv[0]);\n  \t\treturn 0;\n  \t}\n  \tstd::string filename = std::string(argv[1]);\n  \tstd::string outfile = std::string(argv[2]);\n\n  \treturn writePcd(filename, outfile);\n}", "meta": {"hexsha": "1e97382db1db8ae1b0e4f02c4d5cfcb50c5db4d9", "size": 3507, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PclProcessing/pcd_write.cpp", "max_stars_repo_name": "ameliaholcomb/trees", "max_stars_repo_head_hexsha": "8a068417a92dd349255bda60795999579d2bb9aa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PclProcessing/pcd_write.cpp", "max_issues_repo_name": "ameliaholcomb/trees", "max_issues_repo_head_hexsha": "8a068417a92dd349255bda60795999579d2bb9aa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PclProcessing/pcd_write.cpp", "max_forks_repo_name": "ameliaholcomb/trees", "max_forks_repo_head_hexsha": "8a068417a92dd349255bda60795999579d2bb9aa", "max_forks_repo_licenses": ["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.2822580645, "max_line_length": 96, "alphanum_fraction": 0.6355859709, "num_tokens": 979, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.6584175072643415, "lm_q1q2_score": 0.4772672803303597}}
{"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 <Eigen/Core>\n#include <Eigen/Geometry>\n#include <glog/logging.h>\n\n#include \"gtest/gtest.h\"\n#include \"theia/math/util.h\"\n#include \"theia/sfm/transformation/align_point_clouds.h\"\n\nnamespace theia {\nusing Eigen::Matrix;\nusing Eigen::Matrix3d;\nusing Eigen::RowMajor;\nusing Eigen::Vector3d;\n\nnamespace {\ndouble kEpsilon = 1e-6;\n\nvoid UmeyamaSimpleTest() {\n  std::vector<Vector3d> left = {\n      Vector3d(0.4, -3.105, 2.147),\n      Vector3d(1.293, 7.1982, -.068),\n      Vector3d(-5.34, 0.708, -3.69),\n      Vector3d(-.345, 1.987, 0.936),\n      Vector3d(0.93, 1.45, 1.079),\n      Vector3d(-3.15, -4.73, 2.49),\n      Vector3d(2.401, -2.03, -1.87),\n      Vector3d(3.192, -.573, 0.1),\n      Vector3d(-2.53, 3.07, -5.19)};\n\n  const Matrix3d rotation_mat =\n      Eigen::AngleAxisd(DegToRad(15.0), Vector3d(1.0, -2.7, 1.9).normalized())\n          .toRotationMatrix();\n  const Vector3d translation_vec(0, 2, 2);\n  const double expected_scale = 1.5;\n\n  // Transform the points.\n  std::vector<Vector3d> right;\n  for (int i = 0; i < left.size(); i++) {\n    Vector3d transformed_point =\n        expected_scale * rotation_mat * left[i] + translation_vec;\n    right.emplace_back(transformed_point);\n  }\n\n  // Compute the similarity transformation.\n  Matrix3d rotation;\n  Vector3d translation;\n  double scale;\n  AlignPointCloudsUmeyama(left, right, &rotation, &translation, &scale);\n\n  // Ensure the calculated transformation is the same as the one we set.\n  for (int i = 0; i < 3; i++) {\n    for (int j = 0; j < 3; j++) {\n      ASSERT_LT(std::abs(rotation(i, j) - rotation_mat(i, j)), kEpsilon);\n    }\n    ASSERT_LT(std::abs(translation(i) - translation_vec(i)), kEpsilon);\n  }\n  ASSERT_LT(fabs(expected_scale - scale), kEpsilon);\n}\n\n}  // namespace\n\nTEST(AlignPointCloudsUmeyama, SimpleTest) {\n  UmeyamaSimpleTest();\n}\n\n}  // namespace theia\n", "meta": {"hexsha": "a96e4e5ea0e24c02f6b77ba9a78e473457574033", "size": 3631, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/sfm/transformation/align_point_clouds_test.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/transformation/align_point_clouds_test.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/transformation/align_point_clouds_test.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": 35.9504950495, "max_line_length": 78, "alphanum_fraction": 0.701459653, "num_tokens": 961, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768249, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.4772672803303597}}
{"text": "/**\n * @file upwindquadrature_test.cc\n * @brief NPDE homework UpwindQuadrature code\n * @author  Philippe Peter\n * @date June 2020\n * @copyright Developed at ETH Zurich\n */\n\n#include \"../upwindquadrature.h\"\n\n#include <gtest/gtest.h>\n#include <lf/geometry/geometry.h>\n#include <lf/mesh/hybrid2d/hybrid2d.h>\n#include <lf/mesh/mesh.h>\n\n#include <Eigen/Core>\n#include <memory>\n\nnamespace UpwindQuadrature::test {\n\nTEST(UpwindQuadrature, opposite_velocity_direction_1) {\n  Eigen::MatrixXd coords(2, 3);\n  coords << 0, 1, 0, 0, 0, 1;\n\n  Eigen::MatrixXd velocities(2, 3);\n  velocities << 1, 1, 1, 1, 1, 1;\n\n  auto res =\n      opposite_velocity_directions(lf::geometry::TriaO1(coords), velocities);\n  EXPECT_EQ(res[0], Direction::OUTWARDS);\n  EXPECT_EQ(res[1], Direction::OUTWARDS);\n  EXPECT_EQ(res[2], Direction::OUTWARDS);\n}\n\nTEST(UpwindQuadrature, opposite_velocity_direction_2) {\n  Eigen::MatrixXd coords(2, 3);\n  coords << -1, 2, 0, -1, -1, 2;\n\n  Eigen::MatrixXd velocities(2, 3);\n  velocities << -1, 1, 0, -1, -1, 1;\n\n  auto res =\n      opposite_velocity_directions(lf::geometry::TriaO1(coords), velocities);\n  EXPECT_EQ(res[0], Direction::INWARDS);\n  EXPECT_EQ(res[1], Direction::INWARDS);\n  EXPECT_EQ(res[2], Direction::INWARDS);\n}\n\nTEST(UpwindQuadrature, opposite_velocity_direction_3) {\n  Eigen::MatrixXd coords(2, 3);\n  coords << 1, 2, 1, 1, 1, 2;\n\n  Eigen::MatrixXd velocities(2, 3);\n  velocities << 0, 1, 0, -1, 0, 1;\n\n  auto res =\n      opposite_velocity_directions(lf::geometry::TriaO1(coords), velocities);\n  EXPECT_EQ(res[0], Direction::ALONG_EDGE);\n  EXPECT_EQ(res[1], Direction::ALONG_EDGE);\n  EXPECT_EQ(res[2], Direction::ALONG_EDGE);\n}\n\nTEST(UpwindQuadrature, initialize_masses) {\n  // construct a triangular tensor product mesh on the unit square\n  std::unique_ptr<lf::mesh::MeshFactory> mesh_factory_ptr =\n      std::make_unique<lf::mesh::hybrid2d::MeshFactory>(2);\n  lf::mesh::utils::TPTriagMeshBuilder builder(std::move(mesh_factory_ptr));\n  builder.setBottomLeftCorner(Eigen::Vector2d{0.0, 0.0})\n      .setTopRightCorner(Eigen::Vector2d{1.0, 1.0})\n      .setNumXCells(2)\n      .setNumYCells(2);\n  std::shared_ptr<lf::mesh::Mesh> mesh_p = builder.Build();\n\n  // a third of the area of each triangle.\n  double reference_mass = 1.0 / 24.0;\n\n  auto computed_masses = UpwindQuadrature::initializeMasses(mesh_p);\n  EXPECT_DOUBLE_EQ(computed_masses(*(mesh_p->EntityByIndex(2, 0))),\n                   2.0 * reference_mass);\n  EXPECT_DOUBLE_EQ(computed_masses(*(mesh_p->EntityByIndex(2, 1))),\n                   3.0 * reference_mass);\n  EXPECT_DOUBLE_EQ(computed_masses(*(mesh_p->EntityByIndex(2, 2))),\n                   1.0 * reference_mass);\n  EXPECT_DOUBLE_EQ(computed_masses(*(mesh_p->EntityByIndex(2, 3))),\n                   3.0 * reference_mass);\n  EXPECT_DOUBLE_EQ(computed_masses(*(mesh_p->EntityByIndex(2, 4))),\n                   6.0 * reference_mass);\n  EXPECT_DOUBLE_EQ(computed_masses(*(mesh_p->EntityByIndex(2, 5))),\n                   3.0 * reference_mass);\n  EXPECT_DOUBLE_EQ(computed_masses(*(mesh_p->EntityByIndex(2, 6))),\n                   1.0 * reference_mass);\n  EXPECT_DOUBLE_EQ(computed_masses(*(mesh_p->EntityByIndex(2, 7))),\n                   3.0 * reference_mass);\n  EXPECT_DOUBLE_EQ(computed_masses(*(mesh_p->EntityByIndex(2, 8))),\n                   2.0 * reference_mass);\n}\n\nTEST(UpwindQuadrature, upwind_convection_element_matrix_provider_1) {\n  // construct a triangular tensor product mesh on the unit square\n  std::unique_ptr<lf::mesh::MeshFactory> mesh_factory_ptr =\n      std::make_unique<lf::mesh::hybrid2d::MeshFactory>(2);\n  lf::mesh::utils::TPTriagMeshBuilder builder(std::move(mesh_factory_ptr));\n  builder.setBottomLeftCorner(Eigen::Vector2d{0.0, 0.0})\n      .setTopRightCorner(Eigen::Vector2d{1.0, 1.0})\n      .setNumXCells(2)\n      .setNumYCells(2);\n  std::shared_ptr<lf::mesh::Mesh> mesh_p = builder.Build();\n\n  // initialize masses and velocity field\n  auto masses = UpwindQuadrature::initializeMasses(mesh_p);\n  const auto v = [](const Eigen::Vector2d & /*x*/) {\n    return (Eigen::Vector2d() << 1, 2).finished();\n  };\n\n  // initialize already implemented reference provider and\n  // the upwind provider\n  ConvectionElementMatrixProvider reference(v);\n  UpwindConvectionElementMatrixProvider upwind(v, masses);\n\n  const lf::mesh::Entity &element_0 = *(mesh_p->EntityByIndex(0, 0));\n  const lf::mesh::Entity &element_1 = *(mesh_p->EntityByIndex(0, 1));\n\n  // element 0 is at nonoe of the corners the upwind triangle.\n  EXPECT_NEAR(upwind.Eval(element_0).norm(), 0.0, 1E-15);\n\n  // element 1 is the upwind triangle at corner 2.\n  Eigen::MatrixXd reference_eval = reference.Eval(element_1);\n  Eigen::MatrixXd upwind_eval = upwind.Eval(element_1);\n\n  EXPECT_NEAR(upwind_eval.row(0).norm(), 0.0, 1E-14);\n  EXPECT_NEAR(upwind_eval.row(1).norm(), 0.0, 1E-14);\n  EXPECT_NEAR((upwind_eval.row(2) - 6.0 * reference_eval.row(2)).norm(), 0.0,\n              1E-14);\n}\n\nTEST(UpwindQuadrature, upwind_convection_element_matrix_provider_2) {\n  // construct a triangular tensor product mesh on the unit square\n  std::unique_ptr<lf::mesh::MeshFactory> mesh_factory_ptr =\n      std::make_unique<lf::mesh::hybrid2d::MeshFactory>(2);\n  lf::mesh::utils::TPTriagMeshBuilder builder(std::move(mesh_factory_ptr));\n  builder.setBottomLeftCorner(Eigen::Vector2d{0.0, 0.0})\n      .setTopRightCorner(Eigen::Vector2d{1.0, 1.0})\n      .setNumXCells(2)\n      .setNumYCells(2);\n  std::shared_ptr<lf::mesh::Mesh> mesh_p = builder.Build();\n\n  // initialize masses and velocity field\n  auto masses = UpwindQuadrature::initializeMasses(mesh_p);\n  const auto v = [](const Eigen::Vector2d & /*x*/) {\n    return (Eigen::Vector2d() << -2, -1).finished();\n  };\n\n  // initialize already implemented reference provider and\n  // the upwind provider\n  ConvectionElementMatrixProvider reference(v);\n  UpwindConvectionElementMatrixProvider upwind(v, masses);\n\n  const lf::mesh::Entity &element_1 = *(mesh_p->EntityByIndex(0, 1));\n\n  // element 1 is the upwind triangle at corner 0.\n  Eigen::MatrixXd reference_eval = reference.Eval(element_1);\n  Eigen::MatrixXd upwind_eval = upwind.Eval(element_1);\n\n  EXPECT_NEAR((upwind_eval.row(0) - 2.0 * reference_eval.row(0)).norm(), 0.0,\n              1E-14);\n  EXPECT_NEAR(upwind_eval.row(1).norm(), 0.0, 1E-14);\n  EXPECT_NEAR(upwind_eval.row(2).norm(), 0.0, 1E-14);\n}\n\nTEST(UpwindQuadrature, upwind_convection_element_matrix_provider_3) {\n  // construct a triangular tensor product mesh on the unit square\n  std::unique_ptr<lf::mesh::MeshFactory> mesh_factory_ptr =\n      std::make_unique<lf::mesh::hybrid2d::MeshFactory>(2);\n  lf::mesh::utils::TPTriagMeshBuilder builder(std::move(mesh_factory_ptr));\n  builder.setBottomLeftCorner(Eigen::Vector2d{0.0, 0.0})\n      .setTopRightCorner(Eigen::Vector2d{1.0, 1.0})\n      .setNumXCells(2)\n      .setNumYCells(2);\n  std::shared_ptr<lf::mesh::Mesh> mesh_p = builder.Build();\n\n  // initialize masses and velocity field\n  auto masses = UpwindQuadrature::initializeMasses(mesh_p);\n  const auto v = [](const Eigen::Vector2d & /*x*/) {\n    return (Eigen::Vector2d() << 0, -1).finished();\n  };\n\n  // initialize already implemented reference provider and\n  // the upwind provider\n  ConvectionElementMatrixProvider reference(v);\n  UpwindConvectionElementMatrixProvider upwind(v, masses);\n\n  const lf::mesh::Entity &element_1 = *(mesh_p->EntityByIndex(0, 1));\n\n  // at corner 1 of element 1, -v(a^1) points along the edge\n  //--> contribution split between triangle sharing that edge.\n  Eigen::MatrixXd reference_eval = reference.Eval(element_1);\n  Eigen::MatrixXd upwind_eval = upwind.Eval(element_1);\n\n  EXPECT_NEAR(upwind_eval.row(0).norm(), 0.0, 1E-14);\n  EXPECT_NEAR((upwind_eval.row(1) - 1.5 * reference_eval.row(1)).norm(), 0.0,\n              1E-14);\n  EXPECT_NEAR(upwind_eval.row(2).norm(), 0.0, 1E-14);\n}\n\n}  // namespace UpwindQuadrature::test\n", "meta": {"hexsha": "e983fbf366c48fe4f905cda5bdc3cdd29a07c458", "size": 7842, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/UpwindQuadrature/templates/test/upwindquadrature_test.cc", "max_stars_repo_name": "kryo4096/NPDECODES", "max_stars_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/UpwindQuadrature/templates/test/upwindquadrature_test.cc", "max_issues_repo_name": "kryo4096/NPDECODES", "max_issues_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/UpwindQuadrature/templates/test/upwindquadrature_test.cc", "max_forks_repo_name": "kryo4096/NPDECODES", "max_forks_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 38.067961165, "max_line_length": 77, "alphanum_fraction": 0.6959959194, "num_tokens": 2379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.47726727547180187}}
{"text": "#include <stdio.h>\n#include <opencv2/opencv.hpp>\n#include <iostream>\n#include \"planner.h\"\n#include <boost/heap/binomial_heap.hpp>\n#include \"node2d.h\"\n\nusing namespace cv;\nusing namespace std;\nnav_msgs::OccupancyGridPtr grid;\nstruct CompareNodes1\n{\n    /// Sorting 3D nodes by increasing C value - the total estimated cost\n    bool operator()(const Node3D *lhs, const Node3D *rhs) const\n    {\n        return lhs->getG() > rhs->getG();\n    }\n    /// Sorting 2D nodes by increasing C value - the total estimated cost\n    bool operator()(const Node2D *lhs, const Node2D *rhs) const\n    {\n        return lhs->getG() > rhs->getG();\n    }\n};\nstruct CompareNodes\n{\n    /// Sorting 3D nodes by increasing C value - the total estimated cost\n    bool operator()(const Node3D *lhs, const Node3D *rhs) const\n    {\n        return lhs->getG() > rhs->getG();\n    }\n    /// Sorting 2D nodes by increasing C value - the total estimated cost\n    bool operator()(const Node2D *lhs, const Node2D *rhs) const\n    {\n        return lhs->getG() > rhs->getG();\n    }\n};\nfloat a1Star(Node2D &start,\n             Node2D &goal,\n             Node2D *nodes2D,\n             int width,\n             int height,\n             CollisionDetection &configurationSpace,\n             Visualize &visualization);\nfloat jjStar(Node2D &start,\n             Node2D &goal,\n             Node2D *nodes2D,\n             int width,\n             int height,\n             CollisionDetection &configurationSpace,\n             Visualize &visualization);\n\nvoid updateMap(const nav_msgs::OccupancyGrid::Ptr map)\n{\n    grid = map;\n}\nint main(int argc, char **argv)\n{\n    ros::init(argc, argv, \"jj_star\");\n    ros::NodeHandle n;\n    ros::Subscriber subMap;\n    subMap = n.subscribe(\"/map\", 1, updateMap);\n    ros::Duration(0.5).sleep();\n    ros::spinOnce();\n    ros::spinOnce();\n    ros::spinOnce();\n    int width = grid->info.width;\n    int height = grid->info.height;\n\n    Node2D *nodes2D = new Node2D[width * height]();\n    //Node2D start2d(61, 124, 0, 0, nullptr);\n    // create a 2d goal node\n    //Node2D goal2d(61, 77, 0, 0, nullptr);\n    Node2D start2d(1, 1, 0, 0, nullptr);\n    // create a 2d goal node\n    Node2D goal2d(100,105, 0, 0, nullptr);\n    goal2d.setIdx(width);\n    CollisionDetection configurationSpace;\n    configurationSpace.updateGrid(grid);\n    Visualize visualization;\n    ros::WallTime start_, end_;\n    visualization.clear();\n\n    std::cout << \"height : \" << height << std::endl;\n    std::cout << \"width : \" << width << std::endl;\n    start_ = ros::WallTime::now();\n    float astart_cost = a1Star(start2d, goal2d, nodes2D, width, height, configurationSpace, visualization);\n    end_ = ros::WallTime::now();\n    double execution_time = (end_ - start_).toNSec() * 1e-6;\n    ROS_INFO_STREAM(\"Astar time (ms): \" << execution_time);\n    \n    \n \n    \n    start_ = ros::WallTime::now();\n    jjStar(start2d, goal2d, nodes2D, width, height, configurationSpace, visualization);\n    end_ = ros::WallTime::now();\n    execution_time = (end_ - start_).toNSec() * 1e-6;\n    ROS_INFO_STREAM(\"jjStar time (ms): \" << execution_time);\n\n    float jjstar_cost = nodes2D[goal2d.getIdx()].getG();\n    std::cout << \"astar cost : \" << astart_cost << std::endl;\n    std::cout << \"jjstar cost : \" << jjstar_cost << std::endl;\n    Mat image;\n    image = imread(\"/home/ljj/code/APA/pathplannerOnGit/src/path_planner/maps/jj_map_parking.png\", -1);\n    if (!image.data)\n    {\n        printf(\"No image data \\n\");\n        return -1;\n    }\n\n    float Max_C = 0;\n    for(int i = 0; i < width * height ; i++){\n        if(nodes2D[i].getG() > Max_C){\n            Max_C = nodes2D[i].getG();\n        }\n    }\n    std::cout << \"Max cost : \" << Max_C << std::endl;\n    \n    int nodecount = 0;\n    for (int i = 0; i < width * height ; i++){\n        if(nodes2D[i].isClosed()){\n            int r = i / width;\n\n            int c = i % width;\n            //std::cout <<\"row : \"<<r<<\", col : \"<<c<<std::endl;\n            Vec3b &intensity = image.at<Vec3b>(124 - r, c);\n\n            intensity.val[0] = saturate_cast< uchar >(255 * nodes2D[i].getG() / Max_C);\n            intensity.val[1] = 1;\n            intensity.val[2] = saturate_cast< uchar >(255 * nodes2D[i].getG() / Max_C);\n            //intensity.val[0] = 1;\n            //intensity.val[1] = 2;\n            //intensity.val[2] = 3;\n            nodecount++;\n        }\n    }\n    //std::cout << \"total node number : \" << nodecount << std::endl;\n    namedWindow(\"Display Image\", WINDOW_AUTOSIZE);\n    imshow(\"Display Image\", image);\n    imwrite(\"/home/ljj/code/APA/pathplannerOnGit/src/path_planner/maps/jj_map_parking1.png\", image);\n    waitKey(0);\n\n    delete[] nodes2D;\n    return 0;\n}\n//###################################################\nfloat jjStar(Node2D &start,\n             Node2D &goal,\n             Node2D *nodes2D,\n             int width,\n             int height,\n             CollisionDetection &configurationSpace,\n             Visualize &visualization)\n{\n    // PREDECESSOR AND SUCCESSOR INDEX\n    int iPred, iSucc;\n    float newG;\n\n    // reset the open and closed list\n    for (int i = 0; i < width * height; ++i)\n    {\n        nodes2D[i].open();\n    }\n    boost::heap::binomial_heap<Node2D *,\n                               boost::heap::compare<CompareNodes1>>\n        O;\n    // update h value\n    start.updateH(goal);\n    // mark start as open\n    start.open();\n    // push on priority queue\n    O.push(&start);\n    iPred = start.setIdx(width);\n    nodes2D[iPred] = start;\n    int tt = nodes2D[iPred].isOpen() ? 1 : 0;\n    std::cout << \"node2D[iPred].isOpen : \"<< tt <<std::endl;\n    // NODE POINTER\n    Node2D *nPred;\n    Node2D *nSucc;\n    int node_count = 0;\n    while (!O.empty())\n    {\n        // pop node with lowest cost from priority queue\n        //std::cout << \"in while()\"<<std::endl;\n        nPred = O.top();\n        O.pop();\n        // set index\n        iPred = nPred->setIdx(width);\n\n        for (int i = 0; i < Node2D::dir; i++)\n        {\n            // create possible successor\n            nSucc = nPred->createSuccessor(i);\n            // set index of the successor\n            iSucc = nSucc->setIdx(width);\n            \n            int isongrid = nSucc->isOnGrid(width, height)? 1:0;\n            int isTrav = configurationSpace.isTraversable(nSucc)?1:0;\n            //std::cout << \"succ X : \"<< nSucc->getX()\n             //         << \"succ Y : \"<< nSucc->getY() <<std::endl;\n            //std::cout << \"isOnGrid(width, height) : \"<< isongrid <<std::endl;\n            //std::cout << \"isTraversable(nSucc) : \"<< isTrav <<std::endl;\n            if (nSucc->isOnGrid(width, height) && configurationSpace.isTraversable(nSucc))\n            {\n                // calculate new G value\n                nSucc->updateG();\n                newG = nSucc->getG();\n                //int isopen = nodes2D[iSucc].isOpen()?1:0;\n                //int lower = newG < nodes2D[iSucc].getG() ? 1:0;\n                //std::cout << \"nodes2D[iSucc].isOpen() : \"<< isopen <<std::endl;\n                //std::cout << \"newG < nodes2D[iSucc].getG() : \"<< lower <<std::endl;\n                if (nodes2D[iSucc].isOpen() || newG < nodes2D[iSucc].getG())\n                {\n                    nodes2D[iSucc] = *nSucc;\n                    nodes2D[iSucc].close();\n                    nodes2D[iSucc].setG(newG);\n                    O.push(&nodes2D[iSucc]);\n                    node_count ++ ;\n                    //std::cout << \"total node number : \"<<node_count<<std::endl;\n\n                }\n                else\n                {\n                    delete nSucc;\n                }\n            }\n            else\n            {\n                delete nSucc;\n            }\n        }\n        \n    }\n}\n//###################################################\nfloat a1Star(Node2D &start,\n             Node2D &goal,\n             Node2D *nodes2D,\n             int width,\n             int height,\n             CollisionDetection &configurationSpace,\n             Visualize &visualization)\n{\n\n    // PREDECESSOR AND SUCCESSOR INDEX\n    int iPred, iSucc;\n    float newG;\n\n    // reset the open and closed list\n    for (int i = 0; i < width * height; ++i)\n    {\n        nodes2D[i].reset();\n    }\n\n    // VISUALIZATION DELAY\n    ros::Duration d(0.001);\n\n    boost::heap::binomial_heap<Node2D *,\n                               boost::heap::compare<CompareNodes>>\n        O;\n    // update h value\n    start.updateH(goal);\n    // mark start as open\n    start.open();\n    // push on priority queue\n    O.push(&start);\n    iPred = start.setIdx(width);\n    nodes2D[iPred] = start;\n\n    // NODE POINTER\n    Node2D *nPred;\n    Node2D *nSucc;\n\n    // continue until O empty\n    while (!O.empty())\n    {\n        // pop node with lowest cost from priority queue\n        nPred = O.top();\n        // set index\n        iPred = nPred->setIdx(width);\n\n        // _____________________________\n        // LAZY DELETION of rewired node\n        // if there exists a pointer this node has already been expanded\n        if (nodes2D[iPred].isClosed())\n        {\n            // pop node from the open list and start with a fresh node\n            O.pop();\n            continue;\n        }\n        // _________________\n        // EXPANSION OF NODE\n        else if (nodes2D[iPred].isOpen())\n        {\n            // add node to closed list\n            nodes2D[iPred].close();\n            nodes2D[iPred].discover();\n\n            // RViz visualization\n            if (Constants::visualization2D)\n            {\n                visualization.publishNode2DPoses(*nPred);\n                visualization.publishNode2DPose(*nPred);\n                //        d.sleep();\n            }\n\n            // remove node from open list\n            O.pop();\n\n            // _________\n            // GOAL TEST\n            if (*nPred == goal)\n            {\n                return nPred->getG();\n            }\n            // ____________________\n            // CONTINUE WITH SEARCH\n            else\n            {\n                // _______________________________\n                // CREATE POSSIBLE SUCCESSOR NODES\n                for (int i = 0; i < Node2D::dir; i++)\n                {\n                    // create possible successor\n                    nSucc = nPred->createSuccessor(i);\n                    // set index of the successor\n                    iSucc = nSucc->setIdx(width);\n\n                    // ensure successor is on grid ROW MAJOR\n                    // ensure successor is not blocked by obstacle\n                    // ensure successor is not on closed list\n                    if (nSucc->isOnGrid(width, height) && configurationSpace.isTraversable(nSucc) && !nodes2D[iSucc].isClosed())\n                    {\n                        // calculate new G value\n                        nSucc->updateG();\n                        newG = nSucc->getG();\n\n                        // if successor not on open list or g value lower than before put it on open list\n                        if (!nodes2D[iSucc].isOpen() || newG < nodes2D[iSucc].getG())\n                        {\n                            // calculate the H value\n                            nSucc->updateH(goal);\n                            // put successor on open list\n                            nSucc->open();\n                            nodes2D[iSucc] = *nSucc;\n                            O.push(&nodes2D[iSucc]);\n                            delete nSucc;\n                        }\n                        else\n                        {\n                            delete nSucc;\n                        }\n                    }\n                    else\n                    {\n                        delete nSucc;\n                    }\n                }\n            }\n        }\n    }\n\n    // return large number to guide search away\n    return 1000;\n}", "meta": {"hexsha": "ca4428445fbc2cf1fc6746689a3f1f593bcb47b4", "size": 11744, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/astar_test/astar.cpp", "max_stars_repo_name": "ljjhome/motion_planning", "max_stars_repo_head_hexsha": "5a4a8b8b146e69a07b47d412cbf6d9e09d650111", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/astar_test/astar.cpp", "max_issues_repo_name": "ljjhome/motion_planning", "max_issues_repo_head_hexsha": "5a4a8b8b146e69a07b47d412cbf6d9e09d650111", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/astar_test/astar.cpp", "max_forks_repo_name": "ljjhome/motion_planning", "max_forks_repo_head_hexsha": "5a4a8b8b146e69a07b47d412cbf6d9e09d650111", "max_forks_repo_licenses": ["BSD-3-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.1753424658, "max_line_length": 128, "alphanum_fraction": 0.5022138965, "num_tokens": 2999, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768249, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.4772672657546861}}
{"text": "#include \"base/image.h\"\n#include \"base/pose.h\"\n#include \"base/reconstruction.h\"\n#include \"util/logging.h\"\n#include \"util/misc.h\"\n#include \"util/option_manager.h\"\n\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <string>\n\n#include <Eigen/Dense>\n\nusing namespace colmap;\n\n// Takes as input a reconstruction, extracts the global down vectors (+y) in the\n// local image coordinates for every image, and then saves these vectors as .txt\n// files in the images directory. This is useful for generating an artificial\n// ground truth dataset for testing gravity assisted SfM.\n\n// Note that the images themselves don't have to exist in the given output\n// directory, you can pass any path as long as the subdirectory structure from\n// the images directory exists.\n\nint main(int argc, char** argv) {\n  InitializeGlog(argv);\n\n  std::string reconstruction_path;\n  std::string images_path;\n\n  OptionManager options;\n  options.AddRequiredOption(\"reconstruction_path\", &reconstruction_path);\n  options.AddRequiredOption(\"images_path\", &images_path);\n  options.Parse(argc, argv);\n\n  Reconstruction reconstruction;\n  reconstruction.Read(reconstruction_path);\n\n  bool first_file = true;\n\n  for (const auto& ipair : reconstruction.Images()) {\n    const Image& image = ipair.second;\n    std::string root, ext;\n    SplitFileExtension(image.Name(), &root, &ext);\n    // might break if images_path is empty... \u00af\\_(\u30c4)_/\u00af\n    const std::string gravity_file_name =\n        EnsureTrailingSlash(images_path) + root + \".txt\";\n\n    if (first_file && ExistsFile(gravity_file_name)) {\n      // If gravity files exist but not for the first file then what are you\n      // even doing?\n\n      std::cout\n          << \"Warning: this will overwrite existing .txt files in the images \"\n             \"path. Confirm with 'y'.\\n\";\n      char confirm_char;\n      std::cin >> confirm_char;\n\n      if (confirm_char != 'y') {\n        return EXIT_FAILURE;\n      }\n    }\n    first_file = false;\n\n    const Eigen::Vector3d gravity =\n        QuaternionToEigenQuaternion(image.Qvec()) * Eigen::Vector3d(0, 1, 0);\n\n    std::ofstream of(gravity_file_name);\n    of << std::setprecision(9) << gravity.transpose() << '\\n';\n  }\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "ded7b5f6d9675568a3f53d8d548da561eb3ed70e", "size": 2216, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/tools/extract_gravity_vectors.cc", "max_stars_repo_name": "Pascal-So/colmap", "max_stars_repo_head_hexsha": "7c82a22a2ac97e54272d54a1c7276cb293bcdd2f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-10-08T11:01:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-05T09:00:33.000Z", "max_issues_repo_path": "src/tools/extract_gravity_vectors.cc", "max_issues_repo_name": "Pascal-So/colmap", "max_issues_repo_head_hexsha": "7c82a22a2ac97e54272d54a1c7276cb293bcdd2f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tools/extract_gravity_vectors.cc", "max_forks_repo_name": "Pascal-So/colmap", "max_forks_repo_head_hexsha": "7c82a22a2ac97e54272d54a1c7276cb293bcdd2f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5466666667, "max_line_length": 80, "alphanum_fraction": 0.6953971119, "num_tokens": 519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.477239652662761}}
{"text": "/*\n*   Copyright (c) 2010-2016, MIT Probabilistic Computing Project\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// Program to check the modified Bessel functions of the first (I_0)\n// and second (I_1) kinds against boost at points sampled randomly\n// from N(0, 1), N(15, 1), and U[-709, +709].  The edge cases are\n// zero, since I_0 is even and I_1 is odd; 15, where we switch from\n// one rational approximation to another; and +/- 709, which are about\n// where the values overflow the representable range of IEEE 754\n// double-precision floating-point numbers.\n//\n// Usage:\n//\n//      c++ -I../include/CrossCat -o bessamp bessamp.cpp ../src/RandomNumberGenerator.cpp ../src/numerics.cpp ../src/weakprng.cpp\n//      ./bessamp | head -n <nsamples>\n//\n// The output is\n//\n//      nu x boost local relerr\n//\n// where nu \\in {0, 1}, x \\in [-709, +709], boost is I_nu(x) evaluated\n// using boost, local is I_nu(x) evaluated using the local numerics\n// code, and relerr is the relative error of local from boost, or the\n// absolute magnitude of local if boost = 0.\n//\n// The invocation\n//\n//      ./bessamp | awk '$5 > 1e-14'\n//\n// will show points at which we disagree with boost by more than one\n// digit.  So far I have not seen it show any.\n\n#include <boost/math/special_functions/bessel.hpp>\n#include <cmath>\n#include <cstdio>\n#include <limits>\n\n#include \"RandomNumberGenerator.h\"\n#include \"numerics.h\"\n\nstatic double relerr(double expected, double actual) {\n    return fabs(expected == 0 ? actual : (actual - expected)/actual);\n}\n\nstatic double check(unsigned nu, double x) {\n    double expected, actual, error;\n\n    expected = boost::math::cyl_bessel_i(nu, x);\n    actual = nu == 0 ? numerics::i_0(x) : numerics::i_1(x);\n    error = relerr(expected, actual);\n    if (printf(\"%u %.17e %.17e %.17e %.17e\\n\", nu, x, expected, actual, error)\n        < 0)\n        abort();\n}\n\nint main(int argc, char **argv) {\n    const double epsilon = std::numeric_limits<double>::epsilon();\n    RandomNumberGenerator rng;\n    unsigned nu;\n\n    for (;;) {\n        for (nu = 0; nu < 2; nu++) {\n            check(nu, rng.stdnormal());\n            check(nu, 15 + rng.stdnormal());\n            check(nu, rng.nexti(+709 - -709) + -709);\n        }\n    }\n}\n", "meta": {"hexsha": "7045a84e9fc77dd3d3be4e5ded7738f88ae3a655", "size": 2755, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp_code/tests/bessamp.cpp", "max_stars_repo_name": "vishalbelsare/crosscat", "max_stars_repo_head_hexsha": "1f2ac5a43a50ebd7aaa89f0c5ac3815a170848c5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 207.0, "max_stars_repo_stars_event_min_datetime": "2015-09-23T08:35:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-24T23:05:55.000Z", "max_issues_repo_path": "cpp_code/tests/bessamp.cpp", "max_issues_repo_name": "vishalbelsare/crosscat", "max_issues_repo_head_hexsha": "1f2ac5a43a50ebd7aaa89f0c5ac3815a170848c5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 52.0, "max_issues_repo_issues_event_min_datetime": "2015-09-18T21:19:54.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-15T21:17:32.000Z", "max_forks_repo_path": "cpp_code/tests/bessamp.cpp", "max_forks_repo_name": "vishalbelsare/crosscat", "max_forks_repo_head_hexsha": "1f2ac5a43a50ebd7aaa89f0c5ac3815a170848c5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 33.0, "max_forks_repo_forks_event_min_datetime": "2015-10-30T22:50:30.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-01T00:29:55.000Z", "avg_line_length": 33.5975609756, "max_line_length": 129, "alphanum_fraction": 0.6617059891, "num_tokens": 751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145997, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.47723964902114885}}
{"text": "//  Copyright John Maddock 2017.\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// Basic sanity check that header <boost/math/tools/config.hpp>\n// #includes all the files that it needs to.\n//\n#include <boost/math/common_factor_ct.hpp>\n\ntemplate <boost::math::static_gcd_type a, boost::math::static_gcd_type b>\nstruct static_value_check;\n\ntemplate <boost::math::static_gcd_type a>\nstruct static_value_check<a, a>\n{\n   static const boost::math::static_gcd_type value = a;\n};\n\n\nvoid compile_and_link_test()\n{\n   typedef static_value_check<boost::math::static_gcd<42, 30>::value, 6> checked_type;\n   boost::math::static_gcd_type result = checked_type::value;\n   (void)result;\n   typedef static_value_check<boost::math::static_lcm<18, 30>::value, 90> checked_type_2;\n   boost::math::static_gcd_type result_2 = checked_type_2::value;\n   (void)result_2;\n}\n", "meta": {"hexsha": "723ba020114ea28ba310dc0d61e430d83bd056ea", "size": 996, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "deps/src/boost_1_65_1/libs/math/test/compile_test/common_factor_ct_inc_test.cpp", "max_stars_repo_name": "shreyasvj25/turicreate", "max_stars_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 918.0, "max_stars_repo_stars_event_min_datetime": "2016-12-22T02:53:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T06:21:35.000Z", "max_issues_repo_path": "deps/src/boost_1_65_1/libs/math/test/compile_test/common_factor_ct_inc_test.cpp", "max_issues_repo_name": "shreyasvj25/turicreate", "max_issues_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 203.0, "max_issues_repo_issues_event_min_datetime": "2016-12-27T12:09:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T20:46:55.000Z", "max_forks_repo_path": "deps/src/boost_1_65_1/libs/math/test/compile_test/common_factor_ct_inc_test.cpp", "max_forks_repo_name": "shreyasvj25/turicreate", "max_forks_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 122.0, "max_forks_repo_forks_event_min_datetime": "2016-12-22T17:38:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-22T14:25:49.000Z", "avg_line_length": 33.2, "max_line_length": 89, "alphanum_fraction": 0.7489959839, "num_tokens": 273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746407, "lm_q2_score": 0.6297746004557471, "lm_q1q2_score": 0.4772396473971009}}
{"text": "// Copyright John Maddock 2006.\n// Copyright Paul A. Bristow 2007, 2009\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include <boost/math/concepts/real_concept.hpp>\n#include <boost/math/special_functions/math_fwd.hpp>\n#define BOOST_TEST_MAIN\n#include <boost/test/unit_test.hpp>\n#include <boost/test/results_collector.hpp>\n#include <boost/test/unit_test.hpp>\n#include <boost/test/tools/floating_point_comparison.hpp>\n#include <boost/math/tools/stats.hpp>\n#include <boost/math/tools/test.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/type_traits/is_floating_point.hpp>\n#include <boost/array.hpp>\n#include \"functor.hpp\"\n\n#include \"handle_test_result.hpp\"\n#include \"table_type.hpp\"\n\n#ifndef SC_\n#define SC_(x) static_cast<typename table_type<T>::type>(BOOST_JOIN(x, L))\n#endif\n\n#define BOOST_CHECK_CLOSE_EX(a, b, prec, i) \\\n   {\\\n      unsigned int failures = boost::unit_test::results_collector.results( boost::unit_test::framework::current_test_case().p_id ).p_assertions_failed;\\\n      BOOST_CHECK_CLOSE(a, b, prec); \\\n      if(failures != boost::unit_test::results_collector.results( boost::unit_test::framework::current_test_case().p_id ).p_assertions_failed)\\\n      {\\\n         std::cerr << \"Failure was at row \" << i << std::endl;\\\n         std::cerr << std::setprecision(35); \\\n         std::cerr << \"{ \" << data[i][0] << \" , \" << data[i][1] << \" , \" << data[i][2];\\\n         std::cerr << \" , \" << data[i][3] << \" , \" << data[i][4] << \" , \" << data[i][5] << \" } \" << std::endl;\\\n      }\\\n   }\n\ntemplate <class Real, class T>\nvoid do_test_gamma_2(const T& data, const char* type_name, const char* test_name)\n{\n   //\n   // test gamma_p_inv(T, T) against data:\n   //\n   using namespace std;\n   typedef Real                   value_type;\n\n   std::cout << test_name << \" with type \" << type_name << std::endl;\n\n   //\n   // These sanity checks test for a round trip accuracy of one half\n   // of the bits in T, unless T is type float, in which case we check\n   // for just one decimal digit.  The problem here is the sensitivity\n   // of the functions, not their accuracy.  This test data was generated\n   // for the forward functions, which means that when it is used as\n   // the input to the inverses then it is necessarily inexact.  This rounding\n   // of the input is what makes the data unsuitable for use as an accuracy check,\n   // and also demonstrates that you can't in general round-trip these functions.\n   // It is however a useful sanity check.\n   //\n   value_type precision = static_cast<value_type>(ldexp(1.0, 1-boost::math::policies::digits<value_type, boost::math::policies::policy<> >()/2)) * 100;\n   if(boost::math::policies::digits<value_type, boost::math::policies::policy<> >() < 50)\n      precision = 1;   // 1% or two decimal digits, all we can hope for when the input is truncated to float\n\n   for(unsigned i = 0; i < data.size(); ++i)\n   {\n      //\n      // These inverse tests are thrown off if the output of the\n      // incomplete gamma is too close to 1: basically there is insuffient\n      // information left in the value we're using as input to the inverse\n      // to be able to get back to the original value.\n      //\n      if(Real(data[i][5]) == 0)\n         BOOST_CHECK_EQUAL(boost::math::gamma_p_inv(Real(data[i][0]), Real(data[i][5])), value_type(0));\n      else if((1 - Real(data[i][5]) > 0.001) \n         && (fabs(Real(data[i][5])) > 2 * boost::math::tools::min_value<value_type>()) \n         && (fabs(Real(data[i][5])) > 2 * boost::math::tools::min_value<double>()))\n      {\n         value_type inv = boost::math::gamma_p_inv(Real(data[i][0]), Real(data[i][5]));\n         BOOST_CHECK_CLOSE_EX(Real(data[i][1]), inv, precision, i);\n      }\n      else if(1 == Real(data[i][5]))\n         BOOST_CHECK_EQUAL(boost::math::gamma_p_inv(Real(data[i][0]), Real(data[i][5])), std::numeric_limits<value_type>::has_infinity ? std::numeric_limits<value_type>::infinity() : boost::math::tools::max_value<value_type>());\n      else\n      {\n         // not enough bits in our input to get back to x, but we should be in\n         // the same ball park:\n         value_type inv = boost::math::gamma_p_inv(Real(data[i][0]), Real(data[i][5]));\n         BOOST_CHECK_CLOSE_EX(Real(data[i][1]), inv, 100000, i);\n      }\n\n      if(Real(data[i][3]) == 0)\n         BOOST_CHECK_EQUAL(boost::math::gamma_q_inv(Real(data[i][0]), Real(data[i][3])), std::numeric_limits<value_type>::has_infinity ? std::numeric_limits<value_type>::infinity() : boost::math::tools::max_value<value_type>());\n      else if((1 - Real(data[i][3]) > 0.001) && (fabs(Real(data[i][3])) > 2 * boost::math::tools::min_value<value_type>()))\n      {\n         value_type inv = boost::math::gamma_q_inv(Real(data[i][0]), Real(data[i][3]));\n         BOOST_CHECK_CLOSE_EX(Real(data[i][1]), inv, precision, i);\n      }\n      else if(1 == Real(data[i][3]))\n         BOOST_CHECK_EQUAL(boost::math::gamma_q_inv(Real(data[i][0]), Real(data[i][3])), value_type(0));\n      else if(fabs(Real(data[i][3])) > 2 * boost::math::tools::min_value<value_type>())\n      {\n         // not enough bits in our input to get back to x, but we should be in\n         // the same ball park:\n         value_type inv = boost::math::gamma_q_inv(Real(data[i][0]), Real(data[i][3]));\n         BOOST_CHECK_CLOSE_EX(Real(data[i][1]), inv, 100, i);\n      }\n   }\n   std::cout << std::endl;\n}\n\ntemplate <class Real, class T>\nvoid do_test_gamma_inv(const T& data, const char* type_name, const char* test_name)\n{\n#if !(defined(ERROR_REPORTING_MODE) && !defined(GAMMAP_INV_FUNCTION_TO_TEST))\n   typedef Real                   value_type;\n\n   typedef value_type (*pg)(value_type, value_type);\n#ifdef GAMMAP_INV_FUNCTION_TO_TEST\n   pg funcp = GAMMAP_INV_FUNCTION_TO_TEST;\n#elif defined(BOOST_MATH_NO_DEDUCED_FUNCTION_POINTERS)\n   pg funcp = boost::math::gamma_p_inv<value_type, value_type>;\n#else\n   pg funcp = boost::math::gamma_p_inv;\n#endif\n\n   boost::math::tools::test_result<value_type> result;\n\n   std::cout << \"Testing \" << test_name << \" with type \" << type_name\n      << \"\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\";\n\n   //\n   // test gamma_p_inv(T, T) against data:\n   //\n   result = boost::math::tools::test_hetero<Real>(\n      data,\n      bind_func<Real>(funcp, 0, 1),\n      extract_result<Real>(2));\n   handle_test_result(result, data[result.worst()], result.worst(), type_name, \"gamma_p_inv\", test_name);\n   //\n   // test gamma_q_inv(T, T) against data:\n   //\n#ifdef GAMMAQ_INV_FUNCTION_TO_TEST\n   funcp = GAMMAQ_INV_FUNCTION_TO_TEST;\n#elif defined(BOOST_MATH_NO_DEDUCED_FUNCTION_POINTERS)\n   funcp = boost::math::gamma_q_inv<value_type, value_type>;\n#else\n   funcp = boost::math::gamma_q_inv;\n#endif\n   result = boost::math::tools::test_hetero<Real>(\n      data,\n      bind_func<Real>(funcp, 0, 1),\n      extract_result<Real>(3));\n   handle_test_result(result, data[result.worst()], result.worst(), type_name, \"gamma_q_inv\", test_name);\n#endif\n}\n\ntemplate <class T>\nvoid test_gamma(T, const char* name)\n{\n#if !defined(TEST_UDT) && !defined(ERROR_REPORTING_MODE)\n   //\n   // The actual test data is rather verbose, so it's in a separate file\n   //\n   // First the data for the incomplete gamma function, each\n   // row has the following 6 entries:\n   // Parameter a, parameter z,\n   // Expected tgamma(a, z), Expected gamma_q(a, z)\n   // Expected tgamma_lower(a, z), Expected gamma_p(a, z)\n   //\n#  include \"igamma_med_data.ipp\"\n\n   do_test_gamma_2<T>(igamma_med_data, name, \"Running round trip sanity checks on incomplete gamma medium sized values\");\n\n#  include \"igamma_small_data.ipp\"\n\n   do_test_gamma_2<T>(igamma_small_data, name, \"Running round trip sanity checks on incomplete gamma small values\");\n\n#  include \"igamma_big_data.ipp\"\n\n   do_test_gamma_2<T>(igamma_big_data, name, \"Running round trip sanity checks on incomplete gamma large values\");\n\n#endif\n\n#  include \"gamma_inv_data.ipp\"\n\n   do_test_gamma_inv<T>(gamma_inv_data, name, \"incomplete gamma inverse(a, z) medium values\");\n\n#  include \"gamma_inv_big_data.ipp\"\n\n   do_test_gamma_inv<T>(gamma_inv_big_data, name, \"incomplete gamma inverse(a, z) large values\");\n\n#  include \"gamma_inv_small_data.ipp\"\n\n   do_test_gamma_inv<T>(gamma_inv_small_data, name, \"incomplete gamma inverse(a, z) small values\");\n}\n\ntemplate <class T>\nvoid test_spots(T, const char* type_name)\n{\n   std::cout << \"Running spot checks for type \" << type_name << std::endl;\n   //\n   // basic sanity checks, tolerance is 150 epsilon expressed as a percentage:\n   //\n   T tolerance = boost::math::tools::epsilon<T>() * 15000;\n   if(tolerance < 1e-25f)\n      tolerance = 1e-25f;  // limit of test data?\n   BOOST_CHECK_CLOSE(::boost::math::gamma_q_inv(static_cast<T>(1)/100, static_cast<T>(1.0/128)), static_cast<T>(0.35767144525455121503672919307647515332256996883787L), tolerance);\n   BOOST_CHECK_CLOSE(::boost::math::gamma_q_inv(static_cast<T>(1)/100, static_cast<T>(0.5)), static_cast<T>(4.4655350189103486773248562646452806745879516124613e-31L), tolerance*10);\n   //\n   // We can't test in this region against Mathworld's data as the results produced\n   // by functions.wolfram.com appear to be in error, and do *not* round trip with\n   // their own version of gamma_q.  Using our output from the inverse as input to \n   // their version of gamma_q *does* round trip however.  It should be pointed out\n   // that the functions in this area are very sensitive with nearly infinite\n   // first derivatives, it's also questionable how useful these functions are\n   // in this part of the domain.\n   //\n   //BOOST_CHECK_CLOSE(::boost::math::gamma_q_inv(static_cast<T>(1e-2), static_cast<T>(1.0-1.0/128)), static_cast<T>(3.8106736649978161389878528903698068142257930575497e-181L), tolerance);\n   //\n   BOOST_CHECK_CLOSE(::boost::math::gamma_q_inv(static_cast<T>(0.5), static_cast<T>(1.0/128)), static_cast<T>(3.5379794687984498627918583429482809311448951189097L), tolerance);\n   BOOST_CHECK_CLOSE(::boost::math::gamma_q_inv(static_cast<T>(0.5), static_cast<T>(1.0/2)), static_cast<T>(0.22746821155978637597125832348982469815821055329511L), tolerance);\n   BOOST_CHECK_CLOSE(::boost::math::gamma_q_inv(static_cast<T>(0.5), static_cast<T>(1.0-1.0/128)), static_cast<T>(0.000047938431649305382237483273209405461203600840052182L), tolerance);\n   BOOST_CHECK_CLOSE(::boost::math::gamma_q_inv(static_cast<T>(10), static_cast<T>(1.0/128)), static_cast<T>(19.221865946801723949866005318845155649972164294057L), tolerance);\n   BOOST_CHECK_CLOSE(::boost::math::gamma_q_inv(static_cast<T>(10), static_cast<T>(1.0/2)), static_cast<T>(9.6687146147141311517500637401166726067778162022664L), tolerance);\n   BOOST_CHECK_CLOSE(::boost::math::gamma_q_inv(static_cast<T>(10), static_cast<T>(1.0-1.0/128)), static_cast<T>(3.9754602513640844712089002210120603689809432130520L), tolerance);\n   BOOST_CHECK_CLOSE(::boost::math::gamma_q_inv(static_cast<T>(10000), static_cast<T>(1.0/128)), static_cast<T>(10243.369973939134157953734588122880006091919872879L), tolerance);\n   BOOST_CHECK_CLOSE(::boost::math::gamma_q_inv(static_cast<T>(10000), static_cast<T>(1.0/2)), static_cast<T>(9999.6666686420474237369661574633153551436435884101L), tolerance);\n   BOOST_CHECK_CLOSE(::boost::math::gamma_q_inv(static_cast<T>(10000), static_cast<T>(1.0-1.0/128)), static_cast<T>(9759.8597223369324083191194574874497413261589080204L), tolerance);\n}\n\n", "meta": {"hexsha": "7330e918a7ed4d5ec80f2cfe20f2d09d5699cba6", "size": 11490, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/test_igamma_inv.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": "3rdparty/boost_1_73_0/libs/math/test/test_igamma_inv.hpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "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": "3rdparty/boost_1_73_0/libs/math/test/test_igamma_inv.hpp", "max_forks_repo_name": "qingkouwei/mediaones", "max_forks_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_forks_repo_licenses": ["MIT"], "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": 49.1025641026, "max_line_length": 228, "alphanum_fraction": 0.6867711053, "num_tokens": 3192, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.4772396421314405}}
{"text": "//\r\n//  Copyright (c) 2000-2002\r\n//  Joerg Walter, Mathias Koch\r\n//\r\n//  Distributed under the Boost Software License, Version 1.0. (See\r\n//  accompanying file LICENSE_1_0.txt or copy at\r\n//  http://www.boost.org/LICENSE_1_0.txt)\r\n//\r\n//  The authors gratefully acknowledge the support of\r\n//  GeNeSys mbH & Co. KG in producing this work.\r\n//\r\n\r\n#include <boost/numeric/ublas/vector.hpp>\r\n#include <boost/numeric/ublas/io.hpp>\r\n\r\nint main () {\r\n    using namespace boost::numeric::ublas;\r\n    vector<std::complex<double> > v (3);\r\n    for (unsigned i = 0; i < v.size (); ++ i)\r\n        v (i) = std::complex<double> (i, i);\r\n\r\n    std::cout << - v << std::endl;\r\n    std::cout << conj (v) << std::endl;\r\n    std::cout << real (v) << std::endl;\r\n    std::cout << imag (v) << std::endl;\r\n    std::cout << trans (v) << std::endl;\r\n    std::cout << herm (v) << std::endl;\r\n}\r\n\r\n", "meta": {"hexsha": "3d8f1687ec83ec28a271058fcf45dc8d2a337723", "size": 873, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/ublas/doc/samples/vector_unary.cpp", "max_stars_repo_name": "zyiacas/boost-doc-zh", "max_stars_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 198.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T05:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:46:46.000Z", "max_issues_repo_path": "libs/numeric/ublas/doc/samples/vector_unary.cpp", "max_issues_repo_name": "sdfict/boost-doc-zh", "max_issues_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/numeric/ublas/doc/samples/vector_unary.cpp", "max_forks_repo_name": "sdfict/boost-doc-zh", "max_forks_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 29.1, "max_line_length": 68, "alphanum_fraction": 0.5830469645, "num_tokens": 265, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.757794360334681, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.4772396352417319}}
{"text": "#include <boost/math/special_functions/beta.hpp>\n#include <deque>\n#include <random>\n#include <unordered_map>\n#include \"relles.h\"\n\n#include<iostream>\nstatic uint64_t beta_bsearch(std::unordered_map<uint64_t, long double>& memo, long double value, uint64_t n) {\n  uint64_t low = 0;\n  uint64_t high = n;\n\n  std::random_device rd;\n  std::mt19937_64 gen(rd());\n  std::uniform_real_distribution<> unif_dis(0.0, 1.0);\n\n  while (low < high - 1) {\n    uint64_t idx = low + (high - low) / 2;\n    if (memo.find(idx) == memo.end()) {\n      long double beta = boost::math::ibeta_inv(idx - low + 1, high - idx, unif_dis(gen), boost::math::policies::policy<boost::math::policies::digits2<25>>());\n      memo[idx] = memo[low] + (memo[high] - memo[low]) * beta;\n    }\n\n    if (memo[idx] < value) {\n      low = idx;\n    } else {\n      high = idx;\n    }\n  }\n\n  assert(low == high - 1);\n\n  return low;\n}\n\nstatic uint64_t beta_isearch(std::unordered_map<uint64_t, long double>& memo, std::deque<std::pair<uint64_t, long double>>& prev_points, long double value, uint64_t n) {\n  uint64_t low = 0;\n  while (prev_points.back().second < value) {\n    low = prev_points.back().first;\n    prev_points.pop_back();\n  }\n  long double low_val = memo[low];\n  uint64_t high = prev_points.back().first;\n  long double high_val = memo[high];\n\n  std::random_device rd;\n  std::mt19937_64 gen(rd());\n  std::uniform_real_distribution<> unif_dis(0.0, 1.0);\n\n  while (low < high - 2) {\n    uint64_t idx = round((value - low_val) / (high_val - low_val) * (high - low - 2)) + low + 1;\n    assert(idx >= 0);\n    if (memo.find(idx) == memo.end()) {\n      long double beta = boost::math::ibeta_inv(idx - low, high - idx + 1, unif_dis(gen), boost::math::policies::policy<boost::math::policies::digits2<25>>());\n      memo[idx] = memo[low] + (memo[high] - memo[low]) * beta;\n      prev_points.emplace_back(idx, memo[idx]);\n    }\n\n    if (memo[idx] < value) {\n      low = idx;\n      low_val = memo[idx];\n    } else {\n      high = idx;\n      high_val = memo[idx];\n    }\n  }\n\n  return low + 1;\n}\n\n/*\n * The O(k log n) algorithm for multinomial sampling.\n */\nstd::vector<uint64_t> relles(uint64_t n, const std::vector<long double>& dist) {\n  std::unordered_map<uint64_t, long double> memo;\n  std::vector<uint64_t> output(dist.size());\n\n  memo[0] = 0;\n  memo[n] = 1;\n\n  long double cum = 0;\n  uint64_t last = 0;\n\n  for (int i = 0; i < dist.size(); i ++) {\n    cum += dist[i];\n    uint64_t loc = beta_bsearch(memo, cum, n);\n    output[i] = loc - last - 1;\n    last = loc;\n  }\n\n  return output;\n}\n\n/*\n * The O(k log log n) algorithm for multinomial sampling.\n */\nstd::vector<uint64_t> relles_enhanced(uint64_t n, const std::vector<long double>& dist) {\n  std::unordered_map<uint64_t, long double> memo;\n  std::deque<std::pair<uint64_t, long double>> prev_points = { { n, 1 } };\n  std::vector<uint64_t> output(dist.size());\n\n  memo[0] = 0;\n  memo[n] = 1;\n\n  long double cum = 0;\n  uint64_t last = 0;\n\n  for (int i = 0; i < dist.size(); i ++) {\n    cum += dist[i];\n    if (cum >= 1) {\n      output[i] = n - last - 1;\n      break;\n    }\n    uint64_t loc = beta_isearch(memo, prev_points, cum, n);\n    output[i] = loc - last - 1;\n    last = loc;\n  }\n\n  return output;\n}\n\n", "meta": {"hexsha": "9467d9cee3eafca6a6b972efa1f0eda8bc322850", "size": 3210, "ext": "cc", "lang": "C++", "max_stars_repo_path": "relles.cc", "max_stars_repo_name": "colavitam/sampling", "max_stars_repo_head_hexsha": "5b1ce5a536661c57babd6e9c4b5b8c59592a5774", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "relles.cc", "max_issues_repo_name": "colavitam/sampling", "max_issues_repo_head_hexsha": "5b1ce5a536661c57babd6e9c4b5b8c59592a5774", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "relles.cc", "max_forks_repo_name": "colavitam/sampling", "max_forks_repo_head_hexsha": "5b1ce5a536661c57babd6e9c4b5b8c59592a5774", "max_forks_repo_licenses": ["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.5289256198, "max_line_length": 169, "alphanum_fraction": 0.6096573209, "num_tokens": 1010, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384736, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.47720309545264483}}
{"text": "#include \"teca_latitude_damper.h\"\n\n#include \"teca_variant_array.h\"\n#include \"teca_metadata.h\"\n#include \"teca_cartesian_mesh.h\"\n#include \"teca_string_util.h\"\n\n#include <iostream>\n#include <set>\n\n#if defined(TECA_HAS_BOOST)\n#include <boost/program_options.hpp>\n#endif\n\n#include <complex.h>\n\nusing std::cerr;\nusing std::endl;\n\n//#define TECA_DEBUG\nnamespace {\n\n// get the filter ready to be applied in the next steps\ntemplate <typename coord_t>\nvoid get_lat_filter(\n    coord_t *filter, const coord_t *lat, size_t n_lat_vals,\n    coord_t mu, coord_t sigma)\n{\n    coord_t two_sigma_sqr = 2.0*sigma*sigma;\n    for (size_t i = 0; i < n_lat_vals; ++i)\n    {\n        coord_t x_min_mu = lat[i] - mu;\n        coord_t neg_x_min_mu_sqr = -x_min_mu*x_min_mu;\n        filter[i] = coord_t(1) - exp(neg_x_min_mu_sqr/two_sigma_sqr);\n    }\n}\n\n// damp the input array using inverted gaussian\ntemplate <typename num_t, typename coord_t>\nvoid apply_lat_filter(\n    num_t *output, const num_t *input, const coord_t *filter,\n    size_t n_lat_vals, size_t n_lon_vals)\n{\n    for (size_t j = 0; j < n_lat_vals; ++j)\n    {\n        size_t jj = j * n_lon_vals;\n        for (size_t i = 0; i < n_lon_vals; ++i)\n        {\n            output[jj + i] = filter[j] * input[jj + i];\n        }\n    }\n}\n\n};\n\n// --------------------------------------------------------------------------\nteca_latitude_damper::teca_latitude_damper() :\n    center(std::numeric_limits<double>::quiet_NaN()),\n    half_width_at_half_max(std::numeric_limits<double>::quiet_NaN()),\n    variable_post_fix(\"\")\n{\n    this->set_number_of_input_connections(1);\n    this->set_number_of_output_ports(1);\n}\n\n// --------------------------------------------------------------------------\nteca_latitude_damper::~teca_latitude_damper()\n{}\n\n#if defined(TECA_HAS_BOOST)\n// --------------------------------------------------------------------------\nvoid teca_latitude_damper::get_properties_description(\n    const std::string &prefix, options_description &global_opts)\n{\n    options_description opts(\"Options for \"\n        + (prefix.empty()?\"teca_latitude_damper\":prefix));\n\n    opts.add_options()\n        TECA_POPTS_GET(double, prefix, center,\n            \"set the center (mu) for the gaussian filter\")\n        TECA_POPTS_GET(double, prefix, half_width_at_half_max,\n            \"set the value of the half width at half maximum (HWHM) \"\n            \"to calculate sigma from: sigma = HWHM/std::sqrt(2.0*std::log(2.0))\")\n        TECA_POPTS_MULTI_GET(std::vector<std::string>, prefix, damped_variables,\n            \"set the variables that will be damped by the inverted \"\n            \"gaussian filter\")\n        TECA_POPTS_GET(std::string, prefix, variable_post_fix,\n            \"set the post-fix that will be attached to the variables \"\n            \"that will be saved in the output\")\n        ;\n\n    this->teca_algorithm::get_properties_description(prefix, opts);\n\n    global_opts.add(opts);\n}\n// --------------------------------------------------------------------------\nvoid teca_latitude_damper::set_properties(const std::string &prefix,\n    variables_map &opts)\n{\n    this->teca_algorithm::set_properties(prefix, opts);\n\n    TECA_POPTS_SET(opts, double, prefix, center)\n    TECA_POPTS_SET(opts, double, prefix, half_width_at_half_max)\n    TECA_POPTS_SET(opts, std::vector<std::string>, prefix, damped_variables)\n    TECA_POPTS_SET(opts, std::string, prefix, variable_post_fix)\n}\n#endif\n\n// --------------------------------------------------------------------------\nint teca_latitude_damper::get_sigma(const teca_metadata &request, double &sigma)\n{\n    double hwhm = 0.0;\n    if (std::isnan(this->half_width_at_half_max))\n    {\n        if (request.has(\"half_width_at_half_max\"))\n            request.get(\"half_width_at_half_max\", hwhm);\n        else\n            return -1;\n    }\n    else\n    {\n        hwhm = this->half_width_at_half_max;\n    }\n\n    sigma = hwhm/std::sqrt(2.0*std::log(2.0));\n\n    return 0;\n}\n\n// --------------------------------------------------------------------------\nint teca_latitude_damper::get_mu(const teca_metadata &request, double &mu)\n{\n    if (std::isnan(this->center))\n    {\n        if (request.has(\"center\"))\n            request.get(\"center\", mu);\n        else\n            return -1;\n    }\n    else\n    {\n        mu = this->center;\n    }\n\n    return 0;\n}\n\n// --------------------------------------------------------------------------\nint teca_latitude_damper::get_damped_variables(std::vector<std::string> &vars)\n{\n    if (this->damped_variables.empty())\n        return -1;\n    else\n        vars = this->damped_variables;\n\n    return 0;\n}\n\n// --------------------------------------------------------------------------\nteca_metadata teca_latitude_damper::get_output_metadata(\n    unsigned int port,\n    const std::vector<teca_metadata> &input_md)\n{\n#ifdef TECA_DEBUG\n    cerr << teca_parallel_id()\n        << \"teca_latitude_damper::get_output_metadata\" << endl;\n#endif\n    (void)port;\n\n    // add in the array we will generate\n    teca_metadata out_md(input_md[0]);\n\n    const std::string &var_post_fix = this->variable_post_fix;\n    if (!var_post_fix.empty())\n    {\n        std::vector<std::string> &damped_vars = this->damped_variables;\n\n        size_t n_arrays = damped_vars.size();\n        for (size_t i = 0; i < n_arrays; ++i)\n        {\n            out_md.append(\"variables\", damped_vars[i] + var_post_fix);\n        }\n    }\n\n    return out_md;\n}\n\n// --------------------------------------------------------------------------\nstd::vector<teca_metadata> teca_latitude_damper::get_upstream_request(\n    unsigned int port,\n    const std::vector<teca_metadata> &input_md,\n    const teca_metadata &request)\n{\n#ifdef TECA_DEBUG\n    cerr << teca_parallel_id()\n        << \"teca_latitude_damper::get_upstream_request\" << endl;\n#endif\n    (void) port;\n    (void) input_md;\n\n    std::vector<teca_metadata> up_reqs;\n    teca_metadata req(request);\n\n    // get the name of the array to request\n    std::vector<std::string> damped_vars;\n    if (this->get_damped_variables(damped_vars))\n    {\n        TECA_FATAL_ERROR(\"No variables to damp specified\")\n        return up_reqs;\n    }\n\n    // pass the incoming request upstream, and\n    // add in what we need\n    std::set<std::string> arrays;\n    if (req.has(\"arrays\"))\n        req.get(\"arrays\", arrays);\n\n    arrays.insert(damped_vars.begin(), damped_vars.end());\n\n    // Cleaning off the postfix for arrays passed in the pipeline.\n    // For ex a down stream could request \"foo_damped\" then we'd\n    // need to request \"foo\". also remove \"foo_damped\" from the\n    // request.\n    const std::string &var_post_fix = this->variable_post_fix;\n    if (!var_post_fix.empty())\n    {\n        teca_string_util::remove_post_fix(arrays, var_post_fix);\n    }\n\n    req.set(\"arrays\", arrays);\n\n    // send up\n    up_reqs.push_back(req);\n    return up_reqs;\n}\n\n// --------------------------------------------------------------------------\nconst_p_teca_dataset teca_latitude_damper::execute(\n    unsigned int port,\n    const std::vector<const_p_teca_dataset> &input_data,\n    const teca_metadata &request)\n{\n#ifdef TECA_DEBUG\n    cerr << teca_parallel_id() << \"teca_latitude_damper::execute\" << endl;\n#endif\n\n    (void)port;\n\n    // get the input\n    const_p_teca_cartesian_mesh in_mesh =\n        std::dynamic_pointer_cast<const teca_cartesian_mesh>(input_data[0]);\n\n    if (!in_mesh)\n    {\n        TECA_FATAL_ERROR(\"empty input, or not a mesh\")\n        return nullptr;\n    }\n\n    // create output and copy metadata, coordinates, etc\n    p_teca_cartesian_mesh out_mesh =\n        std::dynamic_pointer_cast<teca_cartesian_mesh>(in_mesh->new_instance());\n\n    out_mesh->shallow_copy(\n        std::const_pointer_cast<teca_cartesian_mesh>(in_mesh));\n\n    // get the input array names\n    std::vector<std::string> damped_vars;\n    if (this->get_damped_variables(damped_vars))\n    {\n        TECA_FATAL_ERROR(\"No variable specified to damp\")\n        return nullptr;\n    }\n\n    // get Gaussian paramters. if none were provided, these are the defaults\n    // that will be used.\n    double mu = 0.0;\n    double sigma = 45.0;\n\n    this->get_mu(request, mu);\n    this->get_sigma(request, sigma);\n\n    // get the coordinate axes\n    const_p_teca_variant_array lat = in_mesh->get_y_coordinates();\n    const_p_teca_variant_array lon = in_mesh->get_x_coordinates();\n\n    size_t n_lat = lat->size();\n    size_t n_lon = lon->size();\n\n    p_teca_variant_array filter_array = lat->new_instance(n_lat);\n\n    // Get the gaussian filter\n    NESTED_TEMPLATE_DISPATCH_FP(teca_variant_array_impl,\n        filter_array.get(),\n        _COORD,\n\n        const NT_COORD *p_lat = static_cast<const TT_COORD*>(lat.get())->get();\n\n        NT_COORD *filter = (NT_COORD*)malloc(n_lat*sizeof(NT_COORD));\n        ::get_lat_filter<NT_COORD>(filter, p_lat, n_lat, mu, sigma);\n\n        size_t n_arrays = damped_vars.size();\n        for (size_t i = 0; i < n_arrays; ++i)\n        {\n            // get the input array\n            const_p_teca_variant_array input_array\n                = out_mesh->get_point_arrays()->get(damped_vars[i]);\n            if (!input_array)\n            {\n                TECA_FATAL_ERROR(\"damper variable \\\"\" << damped_vars[i]\n                    << \"\\\" is not in the input\")\n                return nullptr;\n            }\n\n            // apply the gaussian damper\n            size_t n_elem = input_array->size();\n            p_teca_variant_array damped_array = input_array->new_instance(n_elem);\n\n            NESTED_TEMPLATE_DISPATCH(teca_variant_array_impl,\n                damped_array.get(),\n                _DATA,\n\n                const NT_DATA *p_in = static_cast<const TT_DATA*>(input_array.get())->get();\n                NT_DATA *p_damped_array = static_cast<TT_DATA*>(damped_array.get())->get();\n\n                ::apply_lat_filter(p_damped_array, p_in, filter, n_lat, n_lon);\n            )\n\n            // set the damped array in the output\n            std::string out_var_name = damped_vars[i] + this->variable_post_fix;\n            out_mesh->get_point_arrays()->set(out_var_name, damped_array);\n        }\n\n        free(filter);\n    )\n\n    teca_metadata &omd = out_mesh->get_metadata();\n    omd.set(\"gaussian_filter_hwhm\", sigma);\n    omd.set(\"gaussian_filter_center_lat\", mu);\n\n    return out_mesh;\n}\n\n", "meta": {"hexsha": "225da059c44c033d66f96fa9246b1b2f61410d44", "size": 10269, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "alg/teca_latitude_damper.cxx", "max_stars_repo_name": "LBL-EESA/TECA", "max_stars_repo_head_hexsha": "63923b8a12914f3758dc9525239bc48cd8864b39", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-03-28T14:22:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T05:02:25.000Z", "max_issues_repo_path": "alg/teca_latitude_damper.cxx", "max_issues_repo_name": "LBL-EESA/TECA", "max_issues_repo_head_hexsha": "63923b8a12914f3758dc9525239bc48cd8864b39", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": 476.0, "max_issues_repo_issues_event_min_datetime": "2016-11-28T18:06:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-25T05:31:42.000Z", "max_forks_repo_path": "alg/teca_latitude_damper.cxx", "max_forks_repo_name": "LBL-EESA/TECA", "max_forks_repo_head_hexsha": "63923b8a12914f3758dc9525239bc48cd8864b39", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 19.0, "max_forks_repo_forks_event_min_datetime": "2017-04-25T18:15:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-28T18:16:05.000Z", "avg_line_length": 29.9387755102, "max_line_length": 92, "alphanum_fraction": 0.6012269939, "num_tokens": 2475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.6370308013713525, "lm_q1q2_score": 0.47719162766750794}}
{"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_SQR_ABS_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_SQR_ABS_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-arithmetic\n    Function object implementing sqr_abs capabilities\n\n    Computes the square of the absolute value of its parameter. For real entries it is the same as @ref sqr.\n\n    @par semantic:\n    For any given value @c x of type @c T:\n\n    @code\n    T r = sqr_abs(x);\n    @endcode\n\n    is equivalent to:\n\n    @code\n    T r = sqr(abs(x));\n    @endcode\n\n  **/\n  Value sqr_abs(Value const& x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/sqr_abs.hpp>\n#include <boost/simd/function/simd/sqr_abs.hpp>\n\n#endif\n", "meta": {"hexsha": "f052468f90874e3c65959f1051a7fcf0b7dc33af", "size": 1090, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/sqr_abs.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/sqr_abs.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/sqr_abs.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": 23.1914893617, "max_line_length": 108, "alphanum_fraction": 0.5779816514, "num_tokens": 234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.477191622505571}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// variance.hpp\n//\n//  Copyright 2005 Daniel Egloff, Eric Niebler. Distributed under the Boost\n//  Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_ACCUMULATORS_STATISTICS_VARIANCE_HPP_EAN_28_10_2005\n#define BOOST_ACCUMULATORS_STATISTICS_VARIANCE_HPP_EAN_28_10_2005\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/count.hpp>\n#include <boost/accumulators/statistics/sum.hpp>\n#include <boost/accumulators/statistics/mean.hpp>\n#include <boost/accumulators/statistics/moment.hpp>\n\nnamespace boost { namespace accumulators\n{\n\nnamespace impl\n{\n    //! Lazy calculation of variance.\n    /*!\n        Default sample variance implementation based on the second moment \\f$ M_n^{(2)} \\f$ moment<2>, mean and count.\n        \\f[\n            \\sigma_n^2 = M_n^{(2)} - \\mu_n^2.\n        \\f]\n        where\n        \\f[\n            \\mu_n = \\frac{1}{n} \\sum_{i = 1}^n x_i.\n        \\f]\n        is the estimate of the sample mean and \\f$n\\f$ is the number of samples.\n    */\n    template<typename Sample, typename MeanFeature>\n    struct lazy_variance_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        lazy_variance_impl(dont_care) {}\n\n        template<typename Args>\n        result_type result(Args const &args) const\n        {\n            extractor<MeanFeature> mean;\n            result_type tmp = mean(args);\n            return accumulators::moment<2>(args) - tmp * tmp;\n        }\n    };\n\n    //! Iterative calculation of variance.\n    /*!\n        Iterative calculation of sample variance \\f$\\sigma_n^2\\f$ according to the formula\n        \\f[\n            \\sigma_n^2 = \\frac{1}{n} \\sum_{i = 1}^n (x_i - \\mu_n)^2 = \\frac{n-1}{n} \\sigma_{n-1}^2 + \\frac{1}{n-1}(x_n - \\mu_n)^2.\n        \\f]\n        where\n        \\f[\n            \\mu_n = \\frac{1}{n} \\sum_{i = 1}^n x_i.\n        \\f]\n        is the estimate of the sample mean and \\f$n\\f$ is the number of samples.\n\n        Note that the sample variance is not defined for \\f$n <= 1\\f$.\n\n        A simplification can be obtained by the approximate recursion\n        \\f[\n            \\sigma_n^2 \\approx \\frac{n-1}{n} \\sigma_{n-1}^2 + \\frac{1}{n}(x_n - \\mu_n)^2.\n        \\f]\n        because the difference\n        \\f[\n            \\left(\\frac{1}{n-1} - \\frac{1}{n}\\right)(x_n - \\mu_n)^2 = \\frac{1}{n(n-1)}(x_n - \\mu_n)^2.\n        \\f]\n        converges to zero as \\f$n \\rightarrow \\infty\\f$. However, for small \\f$ n \\f$ the difference\n        can be non-negligible.\n    */\n    template<typename Sample, typename MeanFeature, typename Tag>\n    struct variance_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        variance_impl(Args const &args)\n          : variance(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            std::size_t cnt = count(args);\n\n            if(cnt > 1)\n            {\n                extractor<MeanFeature> mean;\n                result_type tmp = args[parameter::keyword<Tag>::get()] - mean(args);\n                this->variance =\n                    numeric::fdiv(this->variance * (cnt - 1), cnt)\n                  + numeric::fdiv(tmp * tmp, cnt - 1);\n            }\n        }\n\n        result_type result(dont_care) const\n        {\n            return this->variance;\n        }\n\n    private:\n        result_type variance;\n    };\n\n} // namespace impl\n\n///////////////////////////////////////////////////////////////////////////////\n// tag::variance\n// tag::immediate_variance\n//\nnamespace tag\n{\n    struct lazy_variance\n      : depends_on<moment<2>, mean>\n    {\n        /// INTERNAL ONLY\n        ///\n        typedef accumulators::impl::lazy_variance_impl<mpl::_1, mean> impl;\n    };\n\n    struct variance\n      : depends_on<count, immediate_mean>\n    {\n        /// INTERNAL ONLY\n        ///\n        typedef accumulators::impl::variance_impl<mpl::_1, mean, sample> impl;\n    };\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// extract::lazy_variance\n// extract::variance\n//\nnamespace extract\n{\n    extractor<tag::lazy_variance> const lazy_variance = {};\n    extractor<tag::variance> const variance = {};\n\n    BOOST_ACCUMULATORS_IGNORE_GLOBAL(lazy_variance)\n    BOOST_ACCUMULATORS_IGNORE_GLOBAL(variance)\n}\n\nusing extract::lazy_variance;\nusing extract::variance;\n\n// variance(lazy) -> lazy_variance\ntemplate<>\nstruct as_feature<tag::variance(lazy)>\n{\n    typedef tag::lazy_variance type;\n};\n\n// variance(immediate) -> variance\ntemplate<>\nstruct as_feature<tag::variance(immediate)>\n{\n    typedef tag::variance type;\n};\n\n// for the purposes of feature-based dependency resolution,\n// immediate_variance provides the same feature as variance\ntemplate<>\nstruct feature_of<tag::lazy_variance>\n  : feature_of<tag::variance>\n{\n};\n\n// So that variance can be automatically substituted with\n// weighted_variance when the weight parameter is non-void.\ntemplate<>\nstruct as_weighted_feature<tag::variance>\n{\n    typedef tag::weighted_variance type;\n};\n\n// for the purposes of feature-based dependency resolution,\n// weighted_variance provides the same feature as variance\ntemplate<>\nstruct feature_of<tag::weighted_variance>\n  : feature_of<tag::variance>\n{\n};\n\n// So that immediate_variance can be automatically substituted with\n// immediate_weighted_variance when the weight parameter is non-void.\ntemplate<>\nstruct as_weighted_feature<tag::lazy_variance>\n{\n    typedef tag::lazy_weighted_variance type;\n};\n\n// for the purposes of feature-based dependency resolution,\n// immediate_weighted_variance provides the same feature as immediate_variance\ntemplate<>\nstruct feature_of<tag::lazy_weighted_variance>\n  : feature_of<tag::lazy_variance>\n{\n};\n\n////////////////////////////////////////////////////////////////////////////\n//// droppable_accumulator<variance_impl>\n////  need to specialize droppable lazy variance to cache the result at the\n////  point the accumulator is dropped.\n///// INTERNAL ONLY\n/////\n//template<typename Sample, typename MeanFeature>\n//struct droppable_accumulator<impl::variance_impl<Sample, MeanFeature> >\n//  : droppable_accumulator_base<\n//        with_cached_result<impl::variance_impl<Sample, MeanFeature> >\n//    >\n//{\n//    template<typename Args>\n//    droppable_accumulator(Args const &args)\n//      : droppable_accumulator::base(args)\n//    {\n//    }\n//};\n\n}} // namespace boost::accumulators\n\n#endif\n", "meta": {"hexsha": "baac55696b332c88d1254e966d2cbe3a8799d4b1", "size": 7147, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/cinder/include/boost/accumulators/statistics/variance.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/variance.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/variance.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": 30.1561181435, "max_line_length": 130, "alphanum_fraction": 0.6262767595, "num_tokens": 1701, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.477191622505571}}
{"text": "/* Copyright (C) 5/23/18 Julian Stobbe - All Rights Reserved\n * You may use, distribute and modify this code under the\n * terms of the MIT license.\n *\n * You should have received a copy of the MIT license with\n * this file.\n */\n\n#ifndef STAT_ACC_HPP_\n#define STAT_ACC_HPP_\n\n#include <deque>\n\n#include <boost/accumulators/numeric/functional/vector.hpp>\n#include <boost/serialization/vector.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/variance.hpp>\n#include <boost/accumulators/statistics/density.hpp>\n#include <boost/accumulators/statistics/kurtosis.hpp>\n#include <boost/accumulators/statistics/skewness.hpp>\n#include <Eigen/Dense>\n\n#include <algorithm>\n#include <vector>\n\nnamespace MCUtil\n{\n\n\n    /*!\n     * @brief Statistic types to be collected\n     */\nenum class StatType : unsigned char {\n    MEAN = 0,\n    VARIANCE  = 1\n    //,SKEWNESS = 2,\n    //KURTOSIS = 3\n};\n\n//use cache with sfinae to only define caching vector if needed\n\n    /*!\n     * @brief               This class provides the low level accumulation functionality for statistical quantities of observables\n     * @tparam T            Type of quantity\n     * @tparam CACHE_SIZE   Cache for the last CACHE_SIZE samples. This can be used for quantities that depend on multiple samples\n     */\ntemplate<typename T, unsigned long CACHE_SIZE = 0>\nclass StatAcc\n{\n\n    using AccT = boost::accumulators::accumulator_set<T,\n            boost::accumulators::features<\n                    boost::accumulators::tag::mean,\n                    boost::accumulators::tag::variance\n                    //,boost::accumulators::tag::skewness\n                    //,boost::accumulators::tag::kurtosis\n            > >;\n\nprivate:\n    AccT acc;\n    //@TODO: switch to boost circular buffer to store full time series?\n    std::deque<T> cache;\n    unsigned long cache_used;\n\npublic:\n    /*StatAcc(): cache_used{0}\n    {\n        if(CACHE_SIZE)\n            cache.resize(CACHE_SIZE);\n    }\n     */\n\n    StatAcc &operator=(const StatAcc &) = delete;\n    //StatAcc(const StatAcc&) = delete;\n\n    /*!\n     * @brief\n     * @tparam ArgTypes     Argument types for the constructor of the quantity type to be accumulated\n     * @param args          Arguments for the constructor of the quantity type to be accumulated\n     */\n    template<typename... ArgTypes>\n    StatAcc(ArgTypes&&... args):\n            acc(T(std::forward<ArgTypes>(args)...)), cache_used{0} {\n        if(CACHE_SIZE)\n            cache.resize(CACHE_SIZE);\n    }\n\n    friend std::ostream &operator<<(std::ostream &stream, const StatAcc &sa) {\n        stream << \"This is the temporary output for StatAcc\";\n        return stream;\n    }\n\n    /*!\n     * @brief       Adds another sample to the accumulator\n     * @param val   Value of next sample\n     */\n    void operator()(T val) {\n        if(CACHE_SIZE) {\n            if(cache_used < CACHE_SIZE) {\n                cache.push_back(val);\n                cache_used += 1;\n            } else {\n                cache.pop_front();\n                cache.push_back(val);\n            }\n        }\n        acc(val);\n    }\n\n\n    /*!\n     * @brief       extracts statistic of accumulated quantity\n     * @param st    Stat Type\n     * @return      Value of statistic for quantity\n     */\n    T extract(const StatType st) {\n        T res;\n        switch(st) {\n            case StatType::MEAN:\n                res = boost::accumulators::mean(acc);\n                break;\n            case StatType::VARIANCE:\n                res = boost::accumulators::variance(acc);\n                break;\n                /* @TODO: template disable\n                 * case StatType::SKEWNESS:\n                    res = boost::accumulators::variance(acc);\n                    break;\n                case StatType::KURTOSIS:\n                    res = boost::accumulators::kurtosis(acc);\n                    break;\n                    */\n        }\n        return res;\n    }\n};\n\n// ===== Eigen::MatrixXd specialization\n\n    // TODO: do this as template specialization\n    template<typename T, unsigned long CACHE_SIZE = 0>\n    class StatAccEigen\n    {\n\n        using AccT = boost::accumulators::accumulator_set<std::vector<T>,\n                boost::accumulators::features<\n                        boost::accumulators::tag::mean,\n                        boost::accumulators::tag::variance\n                        //,boost::accumulators::tag::skewness\n                        //,boost::accumulators::tag::kurtosis\n                > >;\n\n    private:\n        AccT acc;\n        std::vector<T> mapped;\n        std::deque<std::vector<T>> cache;\n        int r;\n        int c;\n        unsigned long cache_used;\n\n    public:\n\n        StatAccEigen &operator=(const StatAccEigen &) = delete;\n\n        /*!\n         * @brief\n         * @param rows     Rows of matrices to be accumulated\n         * @param cols     Cols of matrices to be accumulated\n         */\n        StatAccEigen(int rows, int cols):\n                acc(std::vector<T>(rows*cols)), cache_used{0}, r(rows), c(cols)\n        {\n                mapped.resize(cols*rows);\n                if(CACHE_SIZE)\n                cache.resize(CACHE_SIZE);\n        }\n        /*!\n         * @brief       Adds another sample to the accumulator\n         * @param val   Value of next sample\n         */\n        void new_sample(const Eigen::Ref<const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>>& val) {\n            Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>::Map(&mapped[0], val.rows(), val.cols()) = val;\n            if(CACHE_SIZE) {\n                if(cache_used < CACHE_SIZE) {\n                    cache.push_back(mapped);\n                    cache_used += 1;\n                } else {\n                    cache.pop_front();\n                    cache.push_back(mapped);\n                }\n            }\n            acc(mapped);\n        }\n\n        /*!\n         * @brief       Adds another sample to the accumulator\n         * @param val   Value of next sample\n         */\n        void operator()(const Eigen::Ref<const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>>& val) {\n            Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>::Map(&mapped[0], val.rows(), val.cols()) = val;\n            if(CACHE_SIZE) {\n                if(cache_used < CACHE_SIZE) {\n                    cache.push_back(mapped);\n                    cache_used += 1;\n                } else {\n                    cache.pop_front();\n                    cache.push_back(mapped);\n                }\n            }\n            acc(mapped);\n        }\n\n\n        /*!\n         * @brief       extracts statistic of accumulated quantity\n         * @param st    Stat Type\n         * @return      Value of statistic for quantity\n         */\n        Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> extract(const StatType st) {\n            std::vector<T> res;\n            switch(st) {\n                case StatType::MEAN:\n                    res = boost::accumulators::mean(acc);\n                    break;\n                case StatType::VARIANCE:\n                    res = boost::accumulators::variance(acc);\n                    break;\n                    /* @TODO: template disable\n                     * case StatType::SKEWNESS:\n                        res = boost::accumulators::variance(acc);\n                        break;\n                    case StatType::KURTOSIS:\n                        res = boost::accumulators::kurtosis(acc);\n                        break;\n                        */\n            }\n            Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> out = \\\n                Eigen::Map<Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>>(&res[0], r, c);\n            return out;\n        }\n    };\n\n\n\n\n} // end namespace\n\n#endif\n", "meta": {"hexsha": "52efd23395ffa5a699da7691476e38be6dd12a61", "size": 7811, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/StatAcc.hpp", "max_stars_repo_name": "Atomtomate/sys_risk", "max_stars_repo_head_hexsha": "b47cd40a7fec1305dbe70fde9b94815b41939b5c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/StatAcc.hpp", "max_issues_repo_name": "Atomtomate/sys_risk", "max_issues_repo_head_hexsha": "b47cd40a7fec1305dbe70fde9b94815b41939b5c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/StatAcc.hpp", "max_forks_repo_name": "Atomtomate/sys_risk", "max_forks_repo_head_hexsha": "b47cd40a7fec1305dbe70fde9b94815b41939b5c", "max_forks_repo_licenses": ["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.1195219124, "max_line_length": 130, "alphanum_fraction": 0.5316860837, "num_tokens": 1690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.4771916225055709}}
{"text": "// -----------------------------------------------------------------------------\n// Fern \u00a9 Geoneric\n//\n// This file is part of Geoneric Fern which is available under the terms of\n// the GNU General Public License (GPL), version 2. If you do not want to\n// be bound by the terms of the GPL, you may purchase a proprietary license\n// from Geoneric (http://www.geoneric.eu/contact).\n// -----------------------------------------------------------------------------\n#define BOOST_TEST_MODULE fern algorithm algebra elementary add\n#include <boost/test/unit_test.hpp>\n#include \"fern/core/data_customization_point/scalar.h\"\n#include \"fern/algorithm/algebra/elementary/add.h\"\n\n\nnamespace fa = fern::algorithm;\n\n\ntemplate<\n    class Value1,\n    class Value2,\n    class Result>\nvoid verify_value(\n    Value1 const& value1,\n    Value2 const& value2,\n    Result const& result_we_want)\n{\n    fa::SequentialExecutionPolicy sequential;\n\n    Result result_we_get;\n    fa::algebra::add(sequential, value1, value2, result_we_get);\n    BOOST_CHECK_EQUAL(result_we_get, result_we_want);\n}\n\n\nBOOST_AUTO_TEST_CASE(d0_array_d0_array)\n{\n    verify_value<int8_t, int8_t, int8_t>(-5, 6, 1);\n    verify_value<int8_t, int8_t, int8_t>(-5, -5, -10);\n    verify_value<double, uint8_t, double>(-5.5, 5, -0.5);\n}\n", "meta": {"hexsha": "e4fa23070ee6ce50a1ee6e4058dc47286eb4642f", "size": 1279, "ext": "cc", "lang": "C++", "max_stars_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/fern/source/fern/algorithm/algebra/elementary/test/add_test.cc", "max_stars_repo_name": "quanpands/wflow", "max_stars_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/fern/source/fern/algorithm/algebra/elementary/test/add_test.cc", "max_issues_repo_name": "quanpands/wflow", "max_issues_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/fern/source/fern/algorithm/algebra/elementary/test/add_test.cc", "max_forks_repo_name": "quanpands/wflow", "max_forks_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.1951219512, "max_line_length": 80, "alphanum_fraction": 0.6379984363, "num_tokens": 311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300698514778, "lm_q2_score": 0.6791787121629465, "lm_q1q2_score": 0.4771434680974715}}
{"text": "/*-----------------------------------------------------------------------------+    \nCopyright (c) 2008-2009: Joachim Faulhaber\n+------------------------------------------------------------------------------+\n   Distributed under the Boost Software License, Version 1.0.\n      (See accompanying file LICENCE.txt or copy at\n           http://www.boost.org/LICENSE_1_0.txt)\n+-----------------------------------------------------------------------------*/\n#define BOOST_TEST_MODULE icl::test_doc_code unit test\n#include <libs/icl/test/disable_test_warnings.hpp>\n\n#include <limits>\n#include <complex>\n\n\n#include <string>\n#include <vector>\n#include <boost/mpl/list.hpp>\n#include \"../unit_test_unwarned.hpp\"\n\n\n// interval instance types\n#include \"../test_type_lists.hpp\"\n#include \"../test_value_maker.hpp\"\n\n#include <boost/type_traits/is_same.hpp>\n\n#include <boost/icl/rational.hpp>\n\n#include <boost/icl/detail/interval_morphism.hpp>\n#include <boost/icl/interval_map.hpp>\n#include \"../test_laws.hpp\"\n\nusing namespace std;\nusing namespace boost;\nusing namespace unit_test;\nusing namespace boost::icl;\n\nBOOST_AUTO_TEST_CASE(intro_sample_telecast)\n{\n    // Switch on my favorite telecasts using an interval_set\n    interval<int>::type news(2000, 2015);\n    interval<int>::type talk_show(2245, 2330);\n    interval_set<int> myTvProgram;\n    myTvProgram.add(news).add(talk_show);\n\n    // Iterating over elements (seconds) would be silly ...\n    for(interval_set<int>::iterator telecast = myTvProgram.begin(); \n        telecast != myTvProgram.end(); ++telecast)\n        //...so this iterates over intervals\n        //TV.switch_on(*telecast);\n        cout << *telecast;\n\n    cout << endl;\n}\n\nBOOST_AUTO_TEST_CASE(interface_sample_identifiers)\n{\n    typedef interval_set<std::string, less, continuous_interval<std::string> > IdentifiersT;\n    IdentifiersT identifiers, excluded;\n\n    // special identifiers shall be excluded\n    identifiers += continuous_interval<std::string>::right_open(\"a\", \"c\");\n    identifiers -= std::string(\"boost\");\n    cout << \"identifiers: \" << identifiers << endl;\n\n    excluded = IdentifiersT(icl::hull(identifiers)) - identifiers;\n    cout << \"excluded   : \" << excluded << endl;\n\n    if(icl::contains(identifiers, std::string(\"boost\")))\n        cout << \"error, identifiers.contains('boost')\\n\";\n}\n\nBOOST_AUTO_TEST_CASE(function_reference_element_iteration)\n{\n    // begin of doc code -------------------------------------------------------\n    interval_set<int> inter_set;\n    inter_set.add(interval<int>::right_open(0,3))\n             .add(interval<int>::right_open(7,9));\n\n    for(interval_set<int>::element_const_iterator creeper = elements_begin(inter_set); \n        creeper != elements_end(inter_set); ++creeper)\n        cout << *creeper << \" \";\n    cout << endl;\n    //Program output: 0 1 2 7 8\n\n    for(interval_set<int>::element_reverse_iterator repeerc = elements_rbegin(inter_set); \n        repeerc != elements_rend(inter_set); ++repeerc)\n        cout << *repeerc << \" \";\n    cout << endl;\n    //Program output: 8 7 2 1 0\n    // end of doc code ---------------------------------------------------------\n\n    // Testcode\n    std::stringstream result;\n    for(interval_set<int>::element_iterator creeper2 = elements_begin(inter_set); \n        creeper2 != elements_end(inter_set); ++creeper2)\n        result << *creeper2 << \" \";\n\n    BOOST_CHECK_EQUAL(result.str(), std::string(\"0 1 2 7 8 \"));\n\n    std::stringstream tluser;\n    for(interval_set<int>::element_const_reverse_iterator repeerc2 \n            = elements_rbegin(const_cast<const interval_set<int>&>(inter_set)); \n        repeerc2 != elements_rend(const_cast<const interval_set<int>&>(inter_set)); ++repeerc2)\n        tluser << *repeerc2 << \" \";\n\n    BOOST_CHECK_EQUAL(tluser.str(), std::string(\"8 7 2 1 0 \"));\n}\n\n", "meta": {"hexsha": "7339a5fc1ee2a1092279f49c30c52165bdc3dc2d", "size": 3797, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/icl/test/test_doc_code_/test_doc_code.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "boost/libs/icl/test/test_doc_code_/test_doc_code.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "boost/libs/icl/test/test_doc_code_/test_doc_code.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 34.5181818182, "max_line_length": 95, "alphanum_fraction": 0.621016592, "num_tokens": 872, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.4771434596374365}}
{"text": "/*\n * GraphBLAS Template Library (GBTL), Version 3.0\n *\n * Copyright 2020 Carnegie Mellon University, Battelle Memorial Institute, and\n * Authors.\n *\n * THIS MATERIAL WAS PREPARED AS AN ACCOUNT OF WORK SPONSORED BY AN AGENCY OF\n * THE UNITED STATES GOVERNMENT.  NEITHER THE UNITED STATES GOVERNMENT NOR THE\n * UNITED STATES DEPARTMENT OF ENERGY, NOR THE UNITED STATES DEPARTMENT OF\n * DEFENSE, NOR CARNEGIE MELLON UNIVERSITY, NOR BATTELLE, NOR ANY OF THEIR\n * EMPLOYEES, NOR ANY JURISDICTION OR ORGANIZATION THAT HAS COOPERATED IN THE\n * DEVELOPMENT OF THESE MATERIALS, MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR\n * ASSUMES ANY LEGAL LIABILITY OR RESPONSIBILITY FOR THE ACCURACY, COMPLETENESS,\n * OR USEFULNESS OR ANY INFORMATION, APPARATUS, PRODUCT, SOFTWARE, OR PROCESS\n * DISCLOSED, OR REPRESENTS THAT ITS USE WOULD NOT INFRINGE PRIVATELY OWNED\n * RIGHTS.\n *\n * Released under a BSD-style license, please see LICENSE file or contact\n * permission@sei.cmu.edu for full terms.\n *\n * [DISTRIBUTION STATEMENT A] This material has been approved for public release\n * and unlimited distribution.  Please see Copyright notice for non-US\n * Government use and distribution.\n *\n * This Software includes and/or makes use of the following Third-Party Software\n * subject to its own license:\n *\n * 1. Boost Unit Test Framework\n * (https://www.boost.org/doc/libs/1_45_0/libs/test/doc/html/utf.html)\n * Copyright 2001 Boost software license, Gennadiy Rozental.\n *\n * DM20-0442\n */\n\n#define GRAPHBLAS_LOGGING_LEVEL 0\n\n#include <graphblas/graphblas.hpp>\n\nusing namespace grb;\n\n#define BOOST_TEST_MAIN\n#define BOOST_TEST_MODULE ewiseadd_matrix_test_suite\n\n#include <boost/test/included/unit_test.hpp>\n\nBOOST_AUTO_TEST_SUITE(BOOST_TEST_MODULE)\n\n/// @todo add better tests with accumulate (only a few using Second)\n\n//****************************************************************************\n\nnamespace\n{\n    std::vector<std::vector<double> > m3x3_dense = {{12, 0, 7},\n                                                    {1,  0, 0},\n                                                    {3,  6, 9}};\n\n    std::vector<std::vector<double> > eye3x3_dense = {{1, 0, 0},\n                                                      {0, 1, 0},\n                                                      {0, 0, 1}};\n\n    std::vector<std::vector<double> > twos3x3_dense = {{2, 2, 2},\n                                                       {2, 2, 2},\n                                                       {2, 2, 2}};\n\n    std::vector<std::vector<double> > zero3x3_dense = {{0, 0, 0},\n                                                       {0, 0, 0},\n                                                       {0, 0, 0}};\n\n    std::vector<std::vector<double> > ans_twos3x3_dense = {{14,  2,  9},\n                                                           { 3,  2,  2},\n                                                           { 5,  8, 11}};\n\n    std::vector<std::vector<double> > ans_eye3x3_dense = {{13,  0,  7},\n                                                          { 1,  1,  0},\n                                                          { 3,  6, 10}};\n\n    std::vector<std::vector<double> > m3x4_dense = {{5, 0, 1, 2},\n                                                    {6, 7, 0, 0},\n                                                    {4, 5, 0, 1}};\n\n    std::vector<std::vector<double> > m4x3_dense = {{5, 6, 4},\n                                                    {0, 7, 5},\n                                                    {1, 0, 0},\n                                                    {2, 0, 1}};\n\n    std::vector<std::vector<double> > twos4x3_dense = {{2, 2, 2},\n                                                       {2, 2, 2},\n                                                       {2, 2, 2},\n                                                       {2, 2, 2}};\n\n    std::vector<std::vector<double> > twos3x4_dense = {{2, 2, 2, 2},\n                                                       {2, 2, 2, 2},\n                                                       {2, 2, 2, 2}};\n\n    std::vector<std::vector<double> > ans_twos4x3_dense = {{7, 8,  6},\n                                                           {2, 9,  7},\n                                                           {3, 2,  2},\n                                                           {4, 2,  3}};\n    std::vector<std::vector<double> > ans_twos3x4_dense = {{7, 2, 3, 4},\n                                                           {8, 9, 2, 2},\n                                                           {6, 7, 2, 3}};\n}\n\n//****************************************************************************\n// Tests without mask\n//****************************************************************************\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_ewiseadd_matrix_bad_dimensions)\n{\n    grb::Matrix<double, grb::DirectedMatrixTag> mA(m3x3_dense, 0.);\n    grb::Matrix<double, grb::DirectedMatrixTag> mB(m4x3_dense, 0.);\n\n    grb::Matrix<double, grb::DirectedMatrixTag> Result(3, 3);\n\n    // incompatible input dimensions\n    BOOST_CHECK_THROW(\n        (grb::eWiseAdd(Result,\n                             grb::NoMask(),\n                             grb::NoAccumulate(),\n                             grb::Plus<double>(), mA, mB)),\n        grb::DimensionException);\n\n    // incompatible output matrix dimensions\n    BOOST_CHECK_THROW(\n        (grb::eWiseAdd(Result,\n                             grb::NoMask(),\n                             grb::NoAccumulate(),\n                             grb::Plus<double>(), mB, mB)),\n        grb::DimensionException);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_ewiseadd_matrix_bad_dimensions2)\n{\n    IndexArrayType i_m1    = {0, 0, 1, 1, 2, 2, 3};\n    IndexArrayType j_m1    = {0, 1, 1, 2, 2, 3, 3};\n    std::vector<double> v_m1 = {1, 2, 2, 3, 3, 4, 4};\n    Matrix<double, DirectedMatrixTag> m1(4, 4);\n    m1.build(i_m1, j_m1, v_m1);\n\n    IndexArrayType i_m2    = {0, 0, 1, 1, 1, 2, 2};\n    IndexArrayType j_m2    = {0, 1, 0, 1, 2, 1, 2};\n    std::vector<double> v_m2 = {2, 2, 1, 4, 4, 4, 6};\n    Matrix<double, DirectedMatrixTag> m2(3, 4);\n    m2.build(i_m2, j_m2, v_m2);\n\n    Matrix<double, DirectedMatrixTag> m3(4, 4);\n\n    BOOST_CHECK_THROW(\n        eWiseAdd(m3, NoMask(), NoAccumulate(),\n                 Plus<double>(), m1, m2),\n        DimensionException);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_eWiseadd_matrix_normal)\n{\n    // Build some sparse matrices.\n    IndexArrayType i_mat    = {0, 0, 1, 1, 1, 2, 2, 2, 3, 3};\n    IndexArrayType j_mat    = {0, 1, 0, 1, 2, 1, 2, 3, 2, 3};\n    std::vector<double> v_mat = {1, 1, 1, 2, 2, 2, 3, 3, 3, 4};\n    Matrix<double, DirectedMatrixTag> mat(4, 4);\n    mat.build(i_mat, j_mat, v_mat);\n\n    Matrix<double, DirectedMatrixTag> m3(4, 4);\n\n    IndexArrayType i_answer    = {0, 0, 1, 1, 1, 2, 2, 2, 3, 3};\n    IndexArrayType j_answer    = {0, 1, 0, 1, 2, 1, 2, 3, 2, 3};\n    std::vector<double> v_answer = {2, 2, 2, 4, 4, 4, 6, 6, 6, 8};\n    Matrix<double, DirectedMatrixTag> answer(4, 4);\n    answer.build(i_answer, j_answer, v_answer);\n\n    // Now try simple's ewiseapply.\n    eWiseAdd(m3, NoMask(), NoAccumulate(), Plus<double>(), mat, mat);\n\n    BOOST_CHECK_EQUAL(m3, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_eWiseadd_matrix_semiring)\n{\n    // Build some sparse matrices.\n    IndexArrayType i_mat    = {0, 0, 1, 1, 1, 2, 2, 2, 3, 3};\n    IndexArrayType j_mat    = {0, 1, 0, 1, 2, 1, 2, 3, 2, 3};\n    std::vector<double> v_mat = {1, 1, 1, 2, 2, 2, 3, 3, 3, 4};\n    Matrix<double, DirectedMatrixTag> mat(4, 4);\n    mat.build(i_mat, j_mat, v_mat);\n\n    Matrix<double, DirectedMatrixTag> m3(4, 4);\n\n    IndexArrayType i_answer    = {0, 0, 1, 1, 1, 2, 2, 2, 3, 3};\n    IndexArrayType j_answer    = {0, 1, 0, 1, 2, 1, 2, 3, 2, 3};\n    std::vector<double> v_answer = {2, 2, 2, 4, 4, 4, 6, 6, 6, 8};\n    Matrix<double, DirectedMatrixTag> answer(4, 4);\n    answer.build(i_answer, j_answer, v_answer);\n\n    eWiseAdd(m3, NoMask(), NoAccumulate(),\n             add_monoid(ArithmeticSemiring<double>()),\n             mat, mat);\n\n    BOOST_CHECK_EQUAL(m3, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_ewiseadd_matrix_reg)\n{\n    grb::Matrix<double, grb::DirectedMatrixTag> A(m3x3_dense, 0.);\n\n    // ewise add with dense matrix\n    grb::Matrix<double, grb::DirectedMatrixTag> B(twos3x3_dense, 0.);\n    grb::Matrix<double, grb::DirectedMatrixTag> Ans(\n        ans_twos3x3_dense, 0.);\n\n    grb::Matrix<double, grb::DirectedMatrixTag> Result(3,3);\n\n    grb::eWiseAdd(Result,\n                        grb::NoMask(),\n                        grb::NoAccumulate(),\n                        grb::Plus<double>(), A, B);\n    BOOST_CHECK_EQUAL(Result, Ans);\n\n    // ewise add with sparse matrix\n    grb::Matrix<double, grb::DirectedMatrixTag> B2(eye3x3_dense, 0.);\n    grb::Matrix<double, grb::DirectedMatrixTag> Ans2(\n        ans_eye3x3_dense, 0.);\n    grb::eWiseAdd(Result,\n                        grb::NoMask(),\n                        grb::NoAccumulate(),\n                        grb::Plus<double>(), A, B2);\n    BOOST_CHECK_EQUAL(Result, Ans2);\n\n    // ewise add with empty matrix\n    grb::Matrix<double, grb::DirectedMatrixTag> B3(zero3x3_dense, 0.);\n    grb::Matrix<double, grb::DirectedMatrixTag> Ans3(\n        m3x3_dense, 0.);\n    grb::eWiseAdd(Result,\n                        grb::NoMask(),\n                        grb::NoAccumulate(),\n                        grb::Plus<double>(), A, B3);\n    BOOST_CHECK_EQUAL(Result, Ans3);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_ewiseadd_semiring_matrix_reg)\n{\n    grb::Matrix<double, grb::DirectedMatrixTag> A(m3x3_dense, 0.);\n\n    // ewise add with dense matrix\n    grb::Matrix<double, grb::DirectedMatrixTag> B(twos3x3_dense, 0.);\n    grb::Matrix<double, grb::DirectedMatrixTag> Ans(\n        ans_twos3x3_dense, 0.);\n\n    grb::Matrix<double, grb::DirectedMatrixTag> Result(3,3);\n\n    grb::eWiseAdd(Result,\n                        grb::NoMask(),\n                        grb::NoAccumulate(),\n                        add_monoid(grb::ArithmeticSemiring<double>()),\n                        A, B);\n    BOOST_CHECK_EQUAL(Result, Ans);\n\n    // ewise add with sparse matrix\n    grb::Matrix<double, grb::DirectedMatrixTag> B2(eye3x3_dense, 0.);\n    grb::Matrix<double, grb::DirectedMatrixTag> Ans2(\n        ans_eye3x3_dense, 0.);\n    grb::eWiseAdd(Result,\n                        grb::NoMask(),\n                        grb::NoAccumulate(),\n                        add_monoid(grb::ArithmeticSemiring<double>()),\n                        A, B2);\n    BOOST_CHECK_EQUAL(Result, Ans2);\n\n    // ewise add with empty matrix\n    grb::Matrix<double, grb::DirectedMatrixTag> B3(zero3x3_dense, 0.);\n    grb::Matrix<double, grb::DirectedMatrixTag> Ans3(\n        m3x3_dense, 0.);\n    grb::eWiseAdd(Result,\n                        grb::NoMask(),\n                        grb::NoAccumulate(),\n                        add_monoid(grb::ArithmeticSemiring<double>()),\n                        A, B3);\n    BOOST_CHECK_EQUAL(Result, Ans3);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_ewiseadd_matrix_stored_zero_result)\n{\n    grb::Matrix<double, grb::DirectedMatrixTag> A(m3x3_dense, 0.);\n\n    // Add a stored zero\n    A.setElement(1, 2, 0);\n    BOOST_CHECK_EQUAL(A.nvals(), 7);\n\n    grb::Matrix<double, grb::DirectedMatrixTag> B2(eye3x3_dense, 0.);\n    grb::Matrix<double, grb::DirectedMatrixTag> Ans2(\n        ans_eye3x3_dense, 0.);\n    // Add a stored zero\n    Ans2.setElement(1, 2, 0);\n\n    grb::Matrix<double, grb::DirectedMatrixTag> Result(3,3);\n\n    grb::eWiseAdd(Result,\n                        grb::NoMask(),\n                        grb::NoAccumulate(),\n                        grb::Plus<double>(), A, B2);\n    BOOST_CHECK_EQUAL(Result.nvals(), 8);\n    BOOST_CHECK_EQUAL(Result, Ans2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_a_transpose)\n{\n    grb::Matrix<double, grb::DirectedMatrixTag> A(m3x4_dense, 0.);\n    grb::Matrix<double, grb::DirectedMatrixTag> B(twos4x3_dense, 0.);\n    grb::Matrix<double, grb::DirectedMatrixTag> Ans(ans_twos4x3_dense, 0.);\n    grb::Matrix<double, grb::DirectedMatrixTag> Result(4,3);\n\n    grb::eWiseAdd(Result,\n                        grb::NoMask(),\n                        grb::NoAccumulate(),\n                        grb::Plus<double>(),\n                        transpose(A), B);\n    BOOST_CHECK_EQUAL(Result, Ans);\n\n    grb::Matrix<double, grb::DirectedMatrixTag> B2(m3x4_dense, 0.);\n    BOOST_CHECK_THROW(\n        (grb::eWiseAdd(Result,\n                             grb::NoMask(),\n                             grb::NoAccumulate(),\n                             grb::Plus<double>(),\n                             transpose(A), A)),\n        grb::DimensionException);\n\n    grb::Matrix<double, grb::DirectedMatrixTag> Result2(3,3);\n    BOOST_CHECK_THROW(\n        (grb::eWiseAdd(Result2,\n                             grb::NoMask(),\n                             grb::NoAccumulate(),\n                             grb::Plus<double>(),\n                             transpose(A), B)),\n        grb::DimensionException);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_b_transpose)\n{\n    grb::Matrix<double, grb::DirectedMatrixTag> A(m3x4_dense, 0.);\n    grb::Matrix<double, grb::DirectedMatrixTag> B(twos4x3_dense, 0.);\n    grb::Matrix<double, grb::DirectedMatrixTag> Ans(ans_twos3x4_dense, 0.);\n    grb::Matrix<double, grb::DirectedMatrixTag> Result(3, 4);\n\n\n    grb::eWiseAdd(Result,\n                        grb::NoMask(),\n                        grb::NoAccumulate(),\n                        grb::Plus<double>(),\n                        A, transpose(B));\n    BOOST_CHECK_EQUAL(Result, Ans);\n\n    grb::Matrix<double, grb::DirectedMatrixTag> B2(m3x4_dense, 0.);\n    BOOST_CHECK_THROW(\n        (grb::eWiseAdd(Result,\n                             grb::NoMask(),\n                             grb::NoAccumulate(),\n                             grb::Plus<double>(),\n                             B, transpose(B))),\n        grb::DimensionException);\n\n    grb::Matrix<double, grb::DirectedMatrixTag> Result2(3,3);\n    BOOST_CHECK_THROW(\n        (grb::eWiseAdd(Result2,\n                             grb::NoMask(),\n                             grb::NoAccumulate(),\n                             grb::Plus<double>(),\n                             A, transpose(B))),\n        grb::DimensionException);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_a_and_b_transpose)\n{\n    grb::Matrix<double, grb::DirectedMatrixTag> A(m4x3_dense, 0.);\n    grb::Matrix<double, grb::DirectedMatrixTag> B(twos4x3_dense, 0.);\n    grb::Matrix<double, grb::DirectedMatrixTag> Ans(ans_twos3x4_dense, 0.);\n    grb::Matrix<double, grb::DirectedMatrixTag> Result(3, 4);\n\n\n    grb::eWiseAdd(Result,\n                        grb::NoMask(),\n                        grb::NoAccumulate(),\n                        grb::Plus<double>(),\n                        transpose(A), transpose(B));\n    BOOST_CHECK_EQUAL(Result, Ans);\n\n    grb::Matrix<double, grb::DirectedMatrixTag> B2(m3x4_dense, 0.);\n    BOOST_CHECK_THROW(\n        (grb::eWiseAdd(Result,\n                             grb::NoMask(),\n                             grb::NoAccumulate(),\n                             grb::Plus<double>(),\n                             transpose(Ans), transpose(B))),\n        grb::DimensionException);\n\n    grb::Matrix<double, grb::DirectedMatrixTag> Result2(3,3);\n    BOOST_CHECK_THROW(\n        (grb::eWiseAdd(Result2,\n                             grb::NoMask(),\n                             grb::NoAccumulate(),\n                             grb::Plus<double>(),\n                             transpose(A), transpose(B))),\n        grb::DimensionException);\n}\n\n//****************************************************************************\n// Tests using a mask with REPLACE\n//****************************************************************************\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_ewiseadd_matrix_masked_replace_bad_dimensions)\n{\n    grb::Matrix<double, grb::DirectedMatrixTag> mA(twos4x3_dense, 0.);\n    grb::Matrix<double, grb::DirectedMatrixTag> mB(m4x3_dense, 0.);\n    grb::Matrix<double, grb::DirectedMatrixTag> Mask(twos3x3_dense, 0.);\n    grb::Matrix<double, grb::DirectedMatrixTag> Result(4, 3);\n\n    // incompatible Mask-Output dimensions\n    BOOST_CHECK_THROW(\n        (grb::eWiseAdd(Result,\n                             Mask,\n                             grb::NoAccumulate(),\n                             grb::Plus<double>(), mA, mB,\n                             REPLACE)),\n        grb::DimensionException);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_ewiseadd_matrix_masked_replace_reg)\n{\n    grb::Matrix<double, grb::DirectedMatrixTag> mA(twos4x3_dense, 0.);\n    grb::Matrix<double, grb::DirectedMatrixTag> mB(m4x3_dense, 0.);\n\n    std::vector<std::vector<double> > mask_dense = {{1, 1, 1},\n                                                    {0, 1, 1},\n                                                    {0, 0, 1},\n                                                    {0, 0, 0}};\n    grb::Matrix<double, grb::DirectedMatrixTag> Mask(mask_dense, 0.);\n\n    {\n        grb::Matrix<double, grb::DirectedMatrixTag> Result(twos4x3_dense, 0.);\n\n        std::vector<std::vector<double> > ans_dense = {{7, 8, 6},\n                                                       {0, 9, 7},\n                                                       {0, 0, 2},\n                                                       {0, 0, 0}};\n        grb::Matrix<double, grb::DirectedMatrixTag> Ans(ans_dense, 0.);\n\n        grb::eWiseAdd(Result,\n                            Mask,\n                            grb::NoAccumulate(),\n                            grb::Plus<double>(), mA, mB,\n                            REPLACE);\n\n        BOOST_CHECK_EQUAL(Result.nvals(), 6);\n        BOOST_CHECK_EQUAL(Result, Ans);\n    }\n\n    {\n        grb::Matrix<double, grb::DirectedMatrixTag> Result(twos4x3_dense, 0.);\n\n        std::vector<std::vector<double> > ans_dense = {{7, 8,  6},\n                                                       {0, 9,  7},\n                                                       {0, 0,  2},\n                                                       {0, 0,  0}};\n        grb::Matrix<double, grb::DirectedMatrixTag> Ans(ans_dense, 0.);\n\n        grb::eWiseAdd(Result,\n                            Mask,\n                            grb::Second<double>(),\n                            grb::Plus<double>(), mA, mB,\n                            REPLACE);\n\n        BOOST_CHECK_EQUAL(Result.nvals(), 6);\n        BOOST_CHECK_EQUAL(Result, Ans);\n    }\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_ewiseadd_matrix_masked_replace_reg_stored_zero)\n{\n    // tests a computed and stored zero\n    // tests a stored zero in the mask\n    grb::Matrix<double, grb::DirectedMatrixTag> mA(twos4x3_dense, 0.);\n    grb::Matrix<double, grb::DirectedMatrixTag> mB(m4x3_dense, 0.);\n\n    std::vector<std::vector<double> > mask_dense = {{1, 1, 1},\n                                                    {0, 1, 1},\n                                                    {0, 0, 1},\n                                                    {0, 0, 0}};\n    grb::Matrix<double, grb::DirectedMatrixTag> Mask(mask_dense); //, 0.);\n    BOOST_CHECK_EQUAL(Mask.nvals(), 12);\n\n    {\n        grb::Matrix<double, grb::DirectedMatrixTag> Result(twos4x3_dense, 0.);\n\n        std::vector<std::vector<double> > ans_dense = {{7, 8, 6},\n                                                       {0, 9, 7},\n                                                       {0, 0, 2},\n                                                       {0, 0, 0}};\n        grb::Matrix<double, grb::DirectedMatrixTag> Ans(ans_dense, 0.);\n\n        grb::eWiseAdd(Result,\n                            Mask,\n                            grb::NoAccumulate(),\n                            grb::Plus<double>(), mA, mB,\n                            REPLACE);\n\n        BOOST_CHECK_EQUAL(Result.nvals(), 6);\n        BOOST_CHECK_EQUAL(Result, Ans);\n    }\n\n    {\n        grb::Matrix<double, grb::DirectedMatrixTag> Result(twos4x3_dense, 0.);\n\n        std::vector<std::vector<double> > ans_dense = {{7,  8,  6},\n                                                       {0,  9,  7},\n                                                       {0,  0,  2},\n                                                       {0,  0,  0}};\n        grb::Matrix<double, grb::DirectedMatrixTag> Ans(ans_dense, 0.);\n\n        grb::eWiseAdd(Result,\n                            Mask,\n                            grb::Second<double>(),\n                            grb::Plus<double>(), mA, mB,\n                            REPLACE);\n\n        BOOST_CHECK_EQUAL(Result.nvals(), 6);\n        BOOST_CHECK_EQUAL(Result, Ans);\n    }\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_ewiseadd_matrix_masked_replace_a_transpose)\n{\n    grb::Matrix<double, grb::DirectedMatrixTag> mA(twos3x4_dense, 0.);\n    grb::Matrix<double, grb::DirectedMatrixTag> mB(m4x3_dense, 0.);\n\n    std::vector<std::vector<double> > mask_dense = {{1, 1, 1},\n                                                    {0, 1, 1},\n                                                    {0, 0, 1},\n                                                    {0, 0, 0}};\n    grb::Matrix<double, grb::DirectedMatrixTag> Mask(mask_dense, 0.);\n\n    grb::Matrix<double, grb::DirectedMatrixTag> Result(twos4x3_dense, 0.);\n\n    std::vector<std::vector<double> > ans_dense = {{7, 8, 6},\n                                                   {0, 9, 7},\n                                                   {0, 0, 2},\n                                                   {0, 0, 0}};\n    grb::Matrix<double, grb::DirectedMatrixTag> Ans(ans_dense, 0.);\n\n    grb::eWiseAdd(Result,\n                        Mask,\n                        grb::NoAccumulate(),\n                        grb::Plus<double>(), transpose(mA), mB,\n                        REPLACE);\n\n    BOOST_CHECK_EQUAL(Result.nvals(), 6);\n    BOOST_CHECK_EQUAL(Result, Ans);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_ewiseadd_matrix_masked_replace_b_transpose)\n{\n    grb::Matrix<double, grb::DirectedMatrixTag> mA(twos4x3_dense, 0.);\n    grb::Matrix<double, grb::DirectedMatrixTag> mB(m3x4_dense, 0.);\n\n    std::vector<std::vector<double> > mask_dense = {{1, 1, 1},\n                                                    {0, 1, 1},\n                                                    {0, 0, 1},\n                                                    {0, 0, 0}};\n    grb::Matrix<double, grb::DirectedMatrixTag> Mask(mask_dense, 0.);\n\n    grb::Matrix<double, grb::DirectedMatrixTag> Result(twos4x3_dense, 0.);\n\n    std::vector<std::vector<double> > ans_dense = {{7, 8, 6},\n                                                   {0, 9, 7},\n                                                   {0, 0, 2},\n                                                   {0, 0, 0}};\n    grb::Matrix<double, grb::DirectedMatrixTag> Ans(ans_dense, 0.);\n\n    grb::eWiseAdd(Result,\n                        Mask,\n                        grb::NoAccumulate(),\n                        grb::Plus<double>(), mA, transpose(mB),\n                        REPLACE);\n\n    BOOST_CHECK_EQUAL(Result.nvals(), 6);\n    BOOST_CHECK_EQUAL(Result, Ans);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_ewiseadd_matrix_masked_replace_a_and_b_transpose)\n{\n    grb::Matrix<double, grb::DirectedMatrixTag> mA(twos3x4_dense, 0.);\n    grb::Matrix<double, grb::DirectedMatrixTag> mB(m3x4_dense, 0.);\n\n    std::vector<std::vector<double> > mask_dense = {{1, 1, 1},\n                                                    {0, 1, 1},\n                                                    {0, 0, 1},\n                                                    {0, 0, 0}};\n    grb::Matrix<double, grb::DirectedMatrixTag> Mask(mask_dense, 0.);\n\n    grb::Matrix<double, grb::DirectedMatrixTag> Result(twos4x3_dense, 0.);\n\n    std::vector<std::vector<double> > ans_dense = {{7, 8, 6},\n                                                   {0, 9, 7},\n                                                   {0, 0, 2},\n                                                   {0, 0, 0}};\n    grb::Matrix<double, grb::DirectedMatrixTag> Ans(ans_dense, 0.);\n\n    grb::eWiseAdd(Result,\n                        Mask,\n                        grb::NoAccumulate(),\n                        grb::Plus<double>(), transpose(mA), transpose(mB),\n                        REPLACE);\n\n    BOOST_CHECK_EQUAL(Result.nvals(), 6);\n    BOOST_CHECK_EQUAL(Result, Ans);\n}\n\n//****************************************************************************\n// Tests using a mask with MERGE semantics\n//****************************************************************************\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_ewiseadd_matrix_masked_bad_dimensions)\n{\n    grb::Matrix<double, grb::DirectedMatrixTag> mA(twos4x3_dense, 0.);\n    grb::Matrix<double, grb::DirectedMatrixTag> mB(m4x3_dense, 0.);\n    grb::Matrix<double, grb::DirectedMatrixTag> Mask(twos3x3_dense, 0.);\n    grb::Matrix<double, grb::DirectedMatrixTag> Result(4, 3);\n\n    // incompatible Mask-Output dimensions\n    BOOST_CHECK_THROW(\n        (grb::eWiseAdd(Result,\n                             Mask,\n                             grb::NoAccumulate(),\n                             grb::Plus<double>(), mA, mB)),\n        grb::DimensionException);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_ewiseadd_matrix_masked_reg)\n{\n    grb::Matrix<double, grb::DirectedMatrixTag> mA(twos4x3_dense, 0.);\n    grb::Matrix<double, grb::DirectedMatrixTag> mB(m4x3_dense, 0.);\n\n    std::vector<std::vector<double> > mask_dense = {{1, 1, 1},\n                                                    {0, 1, 1},\n                                                    {0, 0, 1},\n                                                    {0, 0, 0}};\n    grb::Matrix<double, grb::DirectedMatrixTag> Mask(mask_dense, 0.);\n\n    {\n        grb::Matrix<double, grb::DirectedMatrixTag> Result(twos4x3_dense, 0.);\n\n        std::vector<std::vector<double> > ans_dense = {{7,  8,  6},\n                                                       {2,  9,  7},\n                                                       {2,  2,  2},\n                                                       {2,  2,  2}};\n        grb::Matrix<double, grb::DirectedMatrixTag> Ans(ans_dense, 0.);\n\n        grb::eWiseAdd(Result,\n                            Mask,\n                            grb::NoAccumulate(),\n                            grb::Plus<double>(), mA, mB);\n\n        BOOST_CHECK_EQUAL(Result.nvals(), 12);\n        BOOST_CHECK_EQUAL(Result, Ans);\n    }\n\n    {\n        grb::Matrix<double, grb::DirectedMatrixTag> Result(twos4x3_dense, 0.);\n\n        std::vector<std::vector<double> > ans_dense = {{7,  8,  6},\n                                                       {2,  9,  7},\n                                                       {2,  2,  2},\n                                                       {2,  2,  2}};\n        grb::Matrix<double, grb::DirectedMatrixTag> Ans(ans_dense, 0.);\n\n        grb::eWiseAdd(Result,\n                            Mask,\n                            grb::Second<double>(),\n                            grb::Plus<double>(), mA, mB);\n\n        BOOST_CHECK_EQUAL(Result.nvals(), 12);\n        BOOST_CHECK_EQUAL(Result, Ans);\n    }\n\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_ewiseadd_matrix_masked_reg_stored_zero)\n{\n    grb::Matrix<double, grb::DirectedMatrixTag> mA(twos4x3_dense, 0.);\n    grb::Matrix<double, grb::DirectedMatrixTag> mB(m4x3_dense, 0.);\n\n    std::vector<std::vector<double> > mask_dense = {{1, 1, 1},\n                                                    {0, 1, 1},\n                                                    {0, 0, 1},\n                                                    {0, 0, 0}};\n    grb::Matrix<double, grb::DirectedMatrixTag> Mask(mask_dense); //, 0.);\n\n    {\n        grb::Matrix<double, grb::DirectedMatrixTag> Result(twos4x3_dense, 0.);\n\n        std::vector<std::vector<double> > ans_dense = {{7,  8,  6},\n                                                       {2,  9,  7},\n                                                       {2,  2,  2},\n                                                       {2,  2,  2}};\n        grb::Matrix<double, grb::DirectedMatrixTag> Ans(ans_dense, 0.);\n\n        grb::eWiseAdd(Result,\n                            Mask,\n                            grb::NoAccumulate(),\n                            grb::Plus<double>(), mA, mB);\n\n        BOOST_CHECK_EQUAL(Result.nvals(), 12);\n        BOOST_CHECK_EQUAL(Result, Ans);\n    }\n\n    {\n        grb::Matrix<double, grb::DirectedMatrixTag> Result(twos4x3_dense, 0.);\n\n        std::vector<std::vector<double> > ans_dense = {{7,  8,  6},\n                                                       {2,  9,  7},\n                                                       {2,  2,  2},\n                                                       {2,  2,  2}};\n        grb::Matrix<double, grb::DirectedMatrixTag> Ans(ans_dense, 0.);\n\n        grb::eWiseAdd(Result,\n                            Mask,\n                            grb::Second<double>(),\n                            grb::Plus<double>(), mA, mB);\n\n        BOOST_CHECK_EQUAL(Result.nvals(), 12);\n        BOOST_CHECK_EQUAL(Result, Ans);\n    }\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_ewiseadd_matrix_masked_a_transpose)\n{\n    grb::Matrix<double, grb::DirectedMatrixTag> mA(twos3x4_dense, 0.);\n    grb::Matrix<double, grb::DirectedMatrixTag> mB(m4x3_dense, 0.);\n\n    std::vector<std::vector<double> > mask_dense = {{1, 1, 1},\n                                                    {0, 1, 1},\n                                                    {0, 0, 1},\n                                                    {0, 0, 0}};\n    grb::Matrix<double, grb::DirectedMatrixTag> Mask(mask_dense, 0.);\n\n    grb::Matrix<double, grb::DirectedMatrixTag> Result(twos4x3_dense, 0.);\n\n    std::vector<std::vector<double> > ans_dense = {{7,  8,  6},\n                                                   {2,  9,  7},\n                                                   {2,  2,  2},\n                                                   {2,  2,  2}};\n    grb::Matrix<double, grb::DirectedMatrixTag> Ans(ans_dense, 0.);\n\n    grb::eWiseAdd(Result,\n                        Mask,\n                        grb::NoAccumulate(),\n                        grb::Plus<double>(), transpose(mA), mB);\n\n    BOOST_CHECK_EQUAL(Result.nvals(), 12);\n    BOOST_CHECK_EQUAL(Result, Ans);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_ewiseadd_matrix_masked_b_transpose)\n{\n    grb::Matrix<double, grb::DirectedMatrixTag> mA(twos4x3_dense, 0.);\n    grb::Matrix<double, grb::DirectedMatrixTag> mB(m3x4_dense, 0.);\n\n    std::vector<std::vector<double> > mask_dense = {{1, 1, 1},\n                                                    {0, 1, 1},\n                                                    {0, 0, 1},\n                                                    {0, 0, 0}};\n    grb::Matrix<double, grb::DirectedMatrixTag> Mask(mask_dense, 0.);\n\n    grb::Matrix<double, grb::DirectedMatrixTag> Result(twos4x3_dense, 0.);\n\n    std::vector<std::vector<double> > ans_dense = {{7,  8,  6},\n                                                   {2,  9,  7},\n                                                   {2,  2,  2},\n                                                   {2,  2,  2}};\n    grb::Matrix<double, grb::DirectedMatrixTag> Ans(ans_dense, 0.);\n\n    grb::eWiseAdd(Result,\n                        Mask,\n                        grb::NoAccumulate(),\n                        grb::Plus<double>(), mA, transpose(mB));\n\n    BOOST_CHECK_EQUAL(Result.nvals(), 12);\n    BOOST_CHECK_EQUAL(Result, Ans);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_ewiseadd_matrix_masked_a_and_b_transpose)\n{\n    grb::Matrix<double, grb::DirectedMatrixTag> mA(twos3x4_dense, 0.);\n    grb::Matrix<double, grb::DirectedMatrixTag> mB(m3x4_dense, 0.);\n\n    std::vector<std::vector<double> > mask_dense = {{1, 1, 1},\n                                                    {0, 1, 1},\n                                                    {0, 0, 1},\n                                                    {0, 0, 0}};\n    grb::Matrix<double, grb::DirectedMatrixTag> Mask(mask_dense, 0.);\n\n    grb::Matrix<double, grb::DirectedMatrixTag> Result(twos4x3_dense, 0.);\n\n    std::vector<std::vector<double> > ans_dense = {{7,  8,  6},\n                                                   {2,  9,  7},\n                                                   {2,  2,  2},\n                                                   {2,  2,  2}};\n    grb::Matrix<double, grb::DirectedMatrixTag> Ans(ans_dense, 0.);\n\n    grb::eWiseAdd(Result,\n                        Mask,\n                        grb::NoAccumulate(),\n                        grb::Plus<double>(), transpose(mA), transpose(mB));\n\n    BOOST_CHECK_EQUAL(Result.nvals(), 12);\n    BOOST_CHECK_EQUAL(Result, Ans);\n}\n\n//****************************************************************************\n// Tests using a complemented mask with REPLACE semantics\n//****************************************************************************\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_ewiseadd_matrix_scmp_masked_replace_bad_dimensions)\n{\n    grb::Matrix<double, grb::DirectedMatrixTag> mA(twos4x3_dense, 0.);\n    grb::Matrix<double, grb::DirectedMatrixTag> mB(m4x3_dense, 0.);\n    grb::Matrix<double, grb::DirectedMatrixTag> Mask(twos3x3_dense, 0.);\n    grb::Matrix<double, grb::DirectedMatrixTag> Result(4, 3);\n\n    // incompatible Mask-Output dimensions\n    BOOST_CHECK_THROW(\n        (grb::eWiseAdd(Result,\n                             grb::complement(Mask),\n                             grb::NoAccumulate(),\n                             grb::Plus<double>(), mA, mB,\n                             REPLACE)),\n        grb::DimensionException);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_ewiseadd_matrix_scmp_masked_replace_reg)\n{\n    grb::Matrix<double, grb::DirectedMatrixTag> mA(twos4x3_dense, 0.);\n    grb::Matrix<double, grb::DirectedMatrixTag> mB(m4x3_dense, 0.);\n\n    std::vector<std::vector<double> > mask_dense = {{0, 0, 0},\n                                                    {1, 0, 0},\n                                                    {1, 1, 0},\n                                                    {1, 1, 1}};\n    grb::Matrix<double, grb::DirectedMatrixTag> Mask(mask_dense, 0.);\n\n    {\n        grb::Matrix<double, grb::DirectedMatrixTag> Result(twos4x3_dense, 0.);\n\n        std::vector<std::vector<double> > ans_dense = {{7, 8, 6},\n                                                       {0, 9, 7},\n                                                       {0, 0, 2},\n                                                       {0, 0, 0}};\n        grb::Matrix<double, grb::DirectedMatrixTag> Ans(ans_dense, 0.);\n\n        grb::eWiseAdd(Result,\n                            grb::complement(Mask),\n                            grb::NoAccumulate(),\n                            grb::Plus<double>(), mA, mB,\n                            REPLACE);\n\n        BOOST_CHECK_EQUAL(Result.nvals(), 6);\n        BOOST_CHECK_EQUAL(Result, Ans);\n    }\n\n    {\n        grb::Matrix<double, grb::DirectedMatrixTag> Result(twos4x3_dense, 0.);\n\n        std::vector<std::vector<double> > ans_dense = {{7, 8, 6},\n                                                       {0, 9, 7},\n                                                       {0, 0, 2},\n                                                       {0, 0, 0}};\n        grb::Matrix<double, grb::DirectedMatrixTag> Ans(ans_dense, 0.);\n\n        grb::eWiseAdd(Result,\n                            grb::complement(Mask),\n                            grb::Second<double>(),\n                            grb::Plus<double>(), mA, mB,\n                            REPLACE);\n\n        BOOST_CHECK_EQUAL(Result.nvals(), 6);\n        BOOST_CHECK_EQUAL(Result, Ans);\n    }\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_ewiseadd_matrix_scmp_masked_replace_reg_stored_zero)\n{\n    // tests a computed and stored zero\n    // tests a stored zero in the mask\n    grb::Matrix<double, grb::DirectedMatrixTag> mA(twos4x3_dense, 0.);\n    grb::Matrix<double, grb::DirectedMatrixTag> mB(m4x3_dense, 0.);\n\n    std::vector<std::vector<double> > mask_dense = {{0, 0, 0},\n                                                    {1, 0, 0},\n                                                    {1, 1, 0},\n                                                    {1, 1, 1}};\n    grb::Matrix<double, grb::DirectedMatrixTag> Mask(mask_dense); //, 0.);\n    BOOST_CHECK_EQUAL(Mask.nvals(), 12);\n\n    {\n        grb::Matrix<double, grb::DirectedMatrixTag> Result(twos4x3_dense, 0.);\n\n        std::vector<std::vector<double> > ans_dense = {{7, 8, 6},\n                                                       {0, 9, 7},\n                                                       {0, 0, 2},\n                                                       {0, 0, 0}};\n        grb::Matrix<double, grb::DirectedMatrixTag> Ans(ans_dense, 0.);\n\n        grb::eWiseAdd(Result,\n                            grb::complement(Mask),\n                            grb::NoAccumulate(),\n                            grb::Plus<double>(), mA, mB,\n                            REPLACE);\n\n        BOOST_CHECK_EQUAL(Result.nvals(), 6);\n        BOOST_CHECK_EQUAL(Result, Ans);\n    }\n\n    {\n        grb::Matrix<double, grb::DirectedMatrixTag> Result(twos4x3_dense, 0.);\n\n        std::vector<std::vector<double> > ans_dense = {{7, 8, 6},\n                                                       {0, 9, 7},\n                                                       {0, 0, 2},\n                                                       {0, 0, 0}};\n        grb::Matrix<double, grb::DirectedMatrixTag> Ans(ans_dense, 0.);\n\n        grb::eWiseAdd(Result,\n                            grb::complement(Mask),\n                            grb::Second<double>(),\n                            grb::Plus<double>(), mA, mB,\n                            REPLACE);\n\n        BOOST_CHECK_EQUAL(Result.nvals(), 6);\n        BOOST_CHECK_EQUAL(Result, Ans);\n    }\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_ewiseadd_matrix_scmp_masked_replace_a_transpose)\n{\n    grb::Matrix<double, grb::DirectedMatrixTag> mA(twos3x4_dense, 0.);\n    grb::Matrix<double, grb::DirectedMatrixTag> mB(m4x3_dense, 0.);\n\n    std::vector<std::vector<double> > mask_dense = {{0, 0, 0},\n                                                    {1, 0, 0},\n                                                    {1, 1, 0},\n                                                    {1, 1, 1}};\n    grb::Matrix<double, grb::DirectedMatrixTag> Mask(mask_dense, 0.);\n\n    grb::Matrix<double, grb::DirectedMatrixTag> Result(twos4x3_dense, 0.);\n\n    std::vector<std::vector<double> > ans_dense = {{7, 8, 6},\n                                                   {0, 9, 7},\n                                                   {0, 0, 2},\n                                                   {0, 0, 0}};\n    grb::Matrix<double, grb::DirectedMatrixTag> Ans(ans_dense, 0.);\n\n    grb::eWiseAdd(Result,\n                        grb::complement(Mask),\n                        grb::NoAccumulate(),\n                        grb::Plus<double>(), transpose(mA), mB,\n                        REPLACE);\n\n    BOOST_CHECK_EQUAL(Result.nvals(), 6);\n    BOOST_CHECK_EQUAL(Result, Ans);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_ewiseadd_matrix_scmp_masked_replace_b_transpose)\n{\n    grb::Matrix<double, grb::DirectedMatrixTag> mA(twos4x3_dense, 0.);\n    grb::Matrix<double, grb::DirectedMatrixTag> mB(m3x4_dense, 0.);\n\n    std::vector<std::vector<double> > mask_dense = {{0, 0, 0},\n                                                    {1, 0, 0},\n                                                    {1, 1, 0},\n                                                    {1, 1, 1}};\n    grb::Matrix<double, grb::DirectedMatrixTag> Mask(mask_dense, 0.);\n\n    grb::Matrix<double, grb::DirectedMatrixTag> Result(twos4x3_dense, 0.);\n\n    std::vector<std::vector<double> > ans_dense = {{7, 8, 6},\n                                                   {0, 9, 7},\n                                                   {0, 0, 2},\n                                                   {0, 0, 0}};\n    grb::Matrix<double, grb::DirectedMatrixTag> Ans(ans_dense, 0.);\n\n    grb::eWiseAdd(Result,\n                        grb::complement(Mask),\n                        grb::NoAccumulate(),\n                        grb::Plus<double>(), mA, transpose(mB),\n                        REPLACE);\n\n    BOOST_CHECK_EQUAL(Result.nvals(), 6);\n    BOOST_CHECK_EQUAL(Result, Ans);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_ewiseadd_matrix_scmp_masked_replace_a_and_b_transpose)\n{\n    grb::Matrix<double, grb::DirectedMatrixTag> mA(twos3x4_dense, 0.);\n    grb::Matrix<double, grb::DirectedMatrixTag> mB(m3x4_dense, 0.);\n\n    std::vector<std::vector<double> > mask_dense = {{0, 0, 0},\n                                                    {1, 0, 0},\n                                                    {1, 1, 0},\n                                                    {1, 1, 1}};\n    grb::Matrix<double, grb::DirectedMatrixTag> Mask(mask_dense, 0.);\n\n    grb::Matrix<double, grb::DirectedMatrixTag> Result(twos4x3_dense, 0.);\n\n    std::vector<std::vector<double> > ans_dense = {{7, 8, 6},\n                                                   {0, 9, 7},\n                                                   {0, 0, 2},\n                                                   {0, 0, 0}};\n    grb::Matrix<double, grb::DirectedMatrixTag> Ans(ans_dense, 0.);\n\n    grb::eWiseAdd(Result,\n                        grb::complement(Mask),\n                        grb::NoAccumulate(),\n                        grb::Plus<double>(), transpose(mA), transpose(mB),\n                        REPLACE);\n\n    BOOST_CHECK_EQUAL(Result.nvals(), 6);\n    BOOST_CHECK_EQUAL(Result, Ans);\n}\n\n//****************************************************************************\n// Tests using a complemented mask (with merge semantics)\n//****************************************************************************\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_ewiseadd_matrix_scmp_masked_bad_dimensions)\n{\n    grb::Matrix<double, grb::DirectedMatrixTag> mA(twos4x3_dense, 0.);\n    grb::Matrix<double, grb::DirectedMatrixTag> mB(m4x3_dense, 0.);\n    grb::Matrix<double, grb::DirectedMatrixTag> Mask(twos3x3_dense, 0.);\n    grb::Matrix<double, grb::DirectedMatrixTag> Result(4, 3);\n\n    // incompatible Mask-Output dimensions\n    BOOST_CHECK_THROW(\n        (grb::eWiseAdd(Result,\n                             grb::complement(Mask),\n                             grb::NoAccumulate(),\n                             grb::Plus<double>(), mA, mB)),\n        grb::DimensionException);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_ewiseadd_matrix_scmp_masked_reg)\n{\n    grb::Matrix<double, grb::DirectedMatrixTag> mA(twos4x3_dense, 0.);\n    grb::Matrix<double, grb::DirectedMatrixTag> mB(m4x3_dense, 0.);\n\n    std::vector<std::vector<double> > mask_dense = {{0, 0, 0},\n                                                    {1, 0, 0},\n                                                    {1, 1, 0},\n                                                    {1, 1, 1}};\n    grb::Matrix<double, grb::DirectedMatrixTag> Mask(mask_dense, 0.);\n\n    {\n        grb::Matrix<double, grb::DirectedMatrixTag> Result(twos4x3_dense, 0.);\n\n        std::vector<std::vector<double> > ans_dense = {{7,  8,  6},\n                                                       {2,  9,  7},\n                                                       {2,  2,  2},\n                                                       {2,  2,  2}};\n        grb::Matrix<double, grb::DirectedMatrixTag> Ans(ans_dense, 0.);\n\n        grb::eWiseAdd(Result,\n                            grb::complement(Mask),\n                            grb::NoAccumulate(),\n                            grb::Plus<double>(), mA, mB);\n\n        BOOST_CHECK_EQUAL(Result.nvals(), 12);\n        BOOST_CHECK_EQUAL(Result, Ans);\n    }\n\n    {\n        grb::Matrix<double, grb::DirectedMatrixTag> Result(twos4x3_dense, 0.);\n\n        std::vector<std::vector<double> > ans_dense = {{7,  8,  6},\n                                                       {2,  9,  7},\n                                                       {2,  2,  2},\n                                                       {2,  2,  2}};\n        grb::Matrix<double, grb::DirectedMatrixTag> Ans(ans_dense, 0.);\n\n        grb::eWiseAdd(Result,\n                            grb::complement(Mask),\n                            grb::Second<double>(),\n                            grb::Plus<double>(), mA, mB);\n\n        BOOST_CHECK_EQUAL(Result.nvals(), 12);\n        BOOST_CHECK_EQUAL(Result, Ans);\n    }\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_ewiseadd_matrix_scmp_masked_reg_stored_zero)\n{\n    grb::Matrix<double, grb::DirectedMatrixTag> mA(twos4x3_dense, 0.);\n    grb::Matrix<double, grb::DirectedMatrixTag> mB(m4x3_dense, 0.);\n\n    std::vector<std::vector<double> > mask_dense = {{0, 0, 0},\n                                                    {1, 0, 0},\n                                                    {1, 1, 0},\n                                                    {1, 1, 1}};\n    grb::Matrix<double, grb::DirectedMatrixTag> Mask(mask_dense);//, 0.);\n\n    {\n        grb::Matrix<double, grb::DirectedMatrixTag> Result(twos4x3_dense, 0.);\n\n        std::vector<std::vector<double> > ans_dense = {{7,  8,  6},\n                                                       {2,  9,  7},\n                                                       {2,  2,  2},\n                                                       {2,  2,  2}};\n        grb::Matrix<double, grb::DirectedMatrixTag> Ans(ans_dense, 0.);\n\n        grb::eWiseAdd(Result,\n                            grb::complement(Mask),\n                            grb::NoAccumulate(),\n                            grb::Plus<double>(), mA, mB);\n\n        BOOST_CHECK_EQUAL(Result.nvals(), 12);\n        BOOST_CHECK_EQUAL(Result, Ans);\n    }\n\n    {\n        grb::Matrix<double, grb::DirectedMatrixTag> Result(twos4x3_dense, 0.);\n\n        std::vector<std::vector<double> > ans_dense = {{7,  8,  6},\n                                                       {2,  9,  7},\n                                                       {2,  2,  2},\n                                                       {2,  2,  2}};\n        grb::Matrix<double, grb::DirectedMatrixTag> Ans(ans_dense, 0.);\n\n        grb::eWiseAdd(Result,\n                      grb::complement(Mask),\n                      grb::Second<double>(),\n                      grb::Plus<double>(), mA, mB);\n\n        BOOST_CHECK_EQUAL(Result.nvals(), 12);\n        BOOST_CHECK_EQUAL(Result, Ans);\n    }\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_ewiseadd_matrix_scmp_masked_a_transpose)\n{\n    grb::Matrix<double, grb::DirectedMatrixTag> mA(twos3x4_dense, 0.);\n    grb::Matrix<double, grb::DirectedMatrixTag> mB(m4x3_dense, 0.);\n\n    std::vector<std::vector<double> > mask_dense = {{0, 0, 0},\n                                                    {1, 0, 0},\n                                                    {1, 1, 0},\n                                                    {1, 1, 1}};\n    grb::Matrix<double, grb::DirectedMatrixTag> Mask(mask_dense, 0.);\n\n    grb::Matrix<double, grb::DirectedMatrixTag> Result(twos4x3_dense, 0.);\n\n    std::vector<std::vector<double> > ans_dense = {{7,  8,  6},\n                                                   {2,  9,  7},\n                                                   {2,  2,  2},\n                                                   {2,  2,  2}};\n    grb::Matrix<double, grb::DirectedMatrixTag> Ans(ans_dense, 0.);\n\n    grb::eWiseAdd(Result,\n                  grb::complement(Mask),\n                  grb::NoAccumulate(),\n                  grb::Plus<double>(), transpose(mA), mB);\n\n    BOOST_CHECK_EQUAL(Result.nvals(), 12);\n    BOOST_CHECK_EQUAL(Result, Ans);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_ewiseadd_matrix_scmp_masked_b_transpose)\n{\n    grb::Matrix<double, grb::DirectedMatrixTag> mA(twos4x3_dense, 0.);\n    grb::Matrix<double, grb::DirectedMatrixTag> mB(m3x4_dense, 0.);\n\n    std::vector<std::vector<double> > mask_dense = {{0, 0, 0},\n                                                    {1, 0, 0},\n                                                    {1, 1, 0},\n                                                    {1, 1, 1}};\n    grb::Matrix<double, grb::DirectedMatrixTag> Mask(mask_dense, 0.);\n\n    grb::Matrix<double, grb::DirectedMatrixTag> Result(twos4x3_dense, 0.);\n\n    std::vector<std::vector<double> > ans_dense = {{7,  8,  6},\n                                                   {2,  9,  7},\n                                                   {2,  2,  2},\n                                                   {2,  2,  2}};\n    grb::Matrix<double, grb::DirectedMatrixTag> Ans(ans_dense, 0.);\n\n    grb::eWiseAdd(Result,\n                        grb::complement(Mask),\n                        grb::NoAccumulate(),\n                        grb::Plus<double>(), mA, transpose(mB));\n\n    BOOST_CHECK_EQUAL(Result.nvals(), 12);\n    BOOST_CHECK_EQUAL(Result, Ans);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_ewiseadd_matrix_scmp_masked_a_and_b_transpose)\n{\n    grb::Matrix<double, grb::DirectedMatrixTag> mA(twos3x4_dense, 0.);\n    grb::Matrix<double, grb::DirectedMatrixTag> mB(m3x4_dense, 0.);\n\n    std::vector<std::vector<double> > mask_dense = {{0, 0, 0},\n                                                    {1, 0, 0},\n                                                    {1, 1, 0},\n                                                    {1, 1, 1}};\n    grb::Matrix<double, grb::DirectedMatrixTag> Mask(mask_dense, 0.);\n\n    grb::Matrix<double, grb::DirectedMatrixTag> Result(twos4x3_dense, 0.);\n\n    std::vector<std::vector<double> > ans_dense = {{7,  8,  6},\n                                                   {2,  9,  7},\n                                                   {2,  2,  2},\n                                                   {2,  2,  2}};\n    grb::Matrix<double, grb::DirectedMatrixTag> Ans(ans_dense, 0.);\n\n    grb::eWiseAdd(Result,\n                  grb::complement(Mask),\n                  grb::NoAccumulate(),\n                  grb::Plus<double>(), transpose(mA), transpose(mB));\n\n    BOOST_CHECK_EQUAL(Result.nvals(), 12);\n    BOOST_CHECK_EQUAL(Result, Ans);\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "b0c0e3d10a1395728d55629092b7dc3111ffd0b4", "size": 52147, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/test_ewiseadd_matrix.cpp", "max_stars_repo_name": "KIwabuchi/gbtl", "max_stars_repo_head_hexsha": "62c6b1e3262f3623359e793edb5ec4fa7bb471f0", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 112.0, "max_stars_repo_stars_event_min_datetime": "2016-04-26T05:54:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T05:56:16.000Z", "max_issues_repo_path": "src/test/test_ewiseadd_matrix.cpp", "max_issues_repo_name": "KIwabuchi/gbtl", "max_issues_repo_head_hexsha": "62c6b1e3262f3623359e793edb5ec4fa7bb471f0", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 21.0, "max_issues_repo_issues_event_min_datetime": "2016-03-22T19:06:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-07T15:40:18.000Z", "max_forks_repo_path": "src/test/test_ewiseadd_matrix.cpp", "max_forks_repo_name": "KIwabuchi/gbtl", "max_forks_repo_head_hexsha": "62c6b1e3262f3623359e793edb5ec4fa7bb471f0", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2016-04-26T05:54:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-21T03:33:20.000Z", "avg_line_length": 41.2229249012, "max_line_length": 80, "alphanum_fraction": 0.4334477535, "num_tokens": 12703, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.7025300698514778, "lm_q1q2_score": 0.47714345897332466}}
{"text": "/****************************************************************************\r\n**\r\n** Copyright (C) 2016 The Qt Company Ltd.\r\n** Contact: https://www.qt.io/licensing/\r\n**\r\n** This file is part of the Qt Charts module of the Qt Toolkit.\r\n**\r\n** $QT_BEGIN_LICENSE:GPL$\r\n** Commercial License Usage\r\n** Licensees holding valid commercial Qt licenses may use this file in\r\n** accordance with the commercial license agreement provided with the\r\n** Software or, alternatively, in accordance with the terms contained in\r\n** a written agreement between you and The Qt Company. For licensing terms\r\n** and conditions see https://www.qt.io/terms-conditions. For further\r\n** information use the contact form at https://www.qt.io/contact-us.\r\n**\r\n** GNU General Public License Usage\r\n** Alternatively, this file may be used under the terms of the GNU\r\n** General Public License version 3 or (at your option) any later version\r\n** approved by the KDE Free Qt Foundation. The licenses are as published by\r\n** the Free Software Foundation and appearing in the file LICENSE.GPL3\r\n** included in the packaging of this file. Please review the following\r\n** information to ensure the GNU General Public License requirements will\r\n** be met: https://www.gnu.org/licenses/gpl-3.0.html.\r\n**\r\n** $QT_END_LICENSE$\r\n**\r\n****************************************************************************/\r\n\r\n#include \"view.h\"\r\n#include <QtGui/QResizeEvent>\r\n#include <QtWidgets/QGraphicsScene>\r\n#include <QtCharts/QChart>\r\n#include <QtCharts/QLineSeries>\r\n#include <QtCharts/QSplineSeries>\r\n#include <QtWidgets/QGraphicsTextItem>\r\n#include \"callout.h\"\r\n#include <QtGui/QMouseEvent>\r\n#include <Eigen/Dense>\r\n#include \"kalman.h\"\r\n\r\nView::View(QWidget *parent)\r\n    : QGraphicsView(new QGraphicsScene, parent),\r\n      m_coordX(0),\r\n      m_coordY(0),\r\n      m_chart(0),\r\n      m_tooltip(0)\r\n{\r\n    int n = 9; // Number of states\r\n    int m = 3; // Number of measurements\r\n    unsigned int dt = 5.; // delta\r\n    unsigned int endTime = 60;\r\n    Eigen::MatrixXd A(n, n); // System dynamics matrix (Transformation Matrix)\r\n    Eigen::MatrixXd C(m, n); // Output matrix\r\n    Eigen::MatrixXd Q(n, n); // Process noise covariance\r\n    Eigen::MatrixXd R(m, m); // Measurement noise covariance\r\n    Eigen::MatrixXd P(n, n); // Estimate error covariance\r\n    // Discrete LTI projectile motion, measuring position only\r\n    double tt = 0.5 * dt * dt;\r\n    A << 1, 0, 0, dt,  0,  0, tt,  0,  0,\r\n         0, 1, 0,  0, dt,  0,  0, tt,  0,\r\n         0, 0, 1,  0,  0, dt,  0,  0, dt,\r\n         0, 0, 0,  1,  0,  0, dt,  0,  0,\r\n         0, 0, 0,  0,  1,  0,  0, dt,  0,\r\n         0, 0, 0,  0,  0,  1,  0,  0, dt,\r\n         0, 0, 0,  0,  0,  0,  1,  0,  0,\r\n         0, 0, 0,  0,  0,  0,  0,  1,  0,\r\n         0, 0, 0,  0,  0,  0,  0,  0,  1;\r\n    C << 1, 0, 0, 0, 0, 0, 0, 0, 0,\r\n         0, 1, 0, 0, 0, 0, 0, 0, 0,\r\n         0, 0, 1, 0, 0, 0, 0, 0, 0;\r\n    // Reasonable covariance matrices\r\n    Q << tt, .05, .05, .0, .0, .0, .0, .0, .0,\r\n         .05, tt, .05, .0, .0, .0, .0, .0, .0,\r\n         .05, .5, tt, .0, .0, .0, .0, .0, .0,\r\n         .0, .0, .0, .0, .0, .0, .0, .0, .0,\r\n         .0, .0, .0, .0, .0, .0, .0, .0, .0,\r\n         .0, .0, .0, .0, .0, .0, .0, .0, .0,\r\n         .0, .0, .0, .0, .0, .0, .0, .0, .0,\r\n         .0, .0, .0, .0, .0, .0, .0, .0, .0,\r\n         .0, .0, .0, .0, .0, .0, .0, .0, .0;\r\n    R << 5, 0, 0,\r\n         0, 5, 0,\r\n         0, 0, 5;\r\n    P << 1.3, 2, 3, 1, 1, 1, 1, 1, 1,\r\n         4, 1.5, 5, 1, 1, 1, 1, 1, 1,\r\n         6, 7, 9, 1, 1, 1, 1, 1, 1,\r\n         1, 1, 1, 1.6, 1, 1, 1, 1, 1,\r\n         1, 1, 1, 1, .9, 1, 1, 1, 1,\r\n         1, 1, 1, 1, 1, .2, 1, 1, 1,\r\n         1, 1, 1, 1, 1, 1, .1, 1, 1,\r\n         1, 1, 1, 1, 1, 1, 1, 1.54, 1,\r\n         1, 1, 1, 1, 1, 1, 1, 1, 1.2;\r\n    KalmanFilter k(dt, A, C, Q, R, P);\r\n    Eigen::VectorXd s0(n), y(m);\r\n    s0 <<  7.0,  8.0,  9.0, 1.0,  2.0,  3.0, 0.33, 0.66, 0.99;\r\n    //      px,   py,   pz,  vx,   vy,   vz,   ax,   ay,   az\r\n    k.init(0, s0);\r\n\r\n    setDragMode(QGraphicsView::NoDrag);\r\n    setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);\r\n    setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);\r\n\r\n    // chart\r\n    m_chart = new QChart;\r\n    m_chart->setMinimumSize(640, 480);\r\n    m_chart->setTitle(\"Distance to Origin (m) x Instant (s)\");\r\n    //m_chart->legend()->hide();\r\n    m_chart->legend()->setVisible(true);\r\n    m_chart->legend()->setAlignment(Qt::AlignBottom);\r\n\r\n\r\n    QLineSeries *series = new QLineSeries;\r\n    series->setName(\"Observed\");\r\n    QSplineSeries *series2 = new QSplineSeries;\r\n    series2->setName(\"Predicted\");\r\n    Eigen::MatrixXd B = Eigen::MatrixXd::Random(n, n);\r\n    for (unsigned int t = 0; t <= endTime; t += dt)\r\n    {\r\n        Eigen::VectorXd u = Eigen::VectorXd::Random(n);\r\n        Eigen::VectorXd y_ = A * s0 + B * u;\r\n        Eigen::Vector3d v;\r\n        v << y_[0], y_[1], y_[2];\r\n        k.update(v);\r\n        series->append(t, v.norm());// distance to origin\r\n        series2->append(t, k.state().norm()); // distance to origin\r\n        s0 = y_;\r\n    }\r\n    m_chart->addSeries(series);\r\n    m_chart->addSeries(series2);\r\n\r\n    m_chart->createDefaultAxes();\r\n    m_chart->setAcceptHoverEvents(true);\r\n\r\n    setRenderHint(QPainter::Antialiasing);\r\n    scene()->addItem(m_chart);\r\n\r\n    m_coordX = new QGraphicsSimpleTextItem(m_chart);\r\n    m_coordX->setPos(m_chart->size().width()/2 - 50, m_chart->size().height());\r\n    m_coordX->setText(\"X: \");\r\n    m_coordY = new QGraphicsSimpleTextItem(m_chart);\r\n    m_coordY->setPos(m_chart->size().width()/2 + 50, m_chart->size().height());\r\n    m_coordY->setText(\"Y: \");\r\n\r\n    connect(series, &QLineSeries::clicked, this, &View::keepCallout);\r\n    connect(series, &QLineSeries::hovered, this, &View::tooltip);\r\n\r\n    connect(series2, &QSplineSeries::clicked, this, &View::keepCallout);\r\n    connect(series2, &QSplineSeries::hovered, this, &View::tooltip);\r\n\r\n    this->setMouseTracking(true);\r\n}\r\n\r\nvoid View::resizeEvent(QResizeEvent *event)\r\n{\r\n    if (scene()) {\r\n        scene()->setSceneRect(QRect(QPoint(0, 0), event->size()));\r\n         m_chart->resize(event->size());\r\n         m_coordX->setPos(m_chart->size().width()/2 - 50, m_chart->size().height() - 20);\r\n         m_coordY->setPos(m_chart->size().width()/2 + 50, m_chart->size().height() - 20);\r\n         const auto callouts = m_callouts;\r\n         for (Callout *callout : callouts)\r\n             callout->updateGeometry();\r\n    }\r\n    QGraphicsView::resizeEvent(event);\r\n}\r\n\r\nvoid View::mouseMoveEvent(QMouseEvent *event)\r\n{\r\n    m_coordX->setText(QString(\"X: %1\").arg(m_chart->mapToValue(event->pos()).x()));\r\n    m_coordY->setText(QString(\"Y: %1\").arg(m_chart->mapToValue(event->pos()).y()));\r\n    QGraphicsView::mouseMoveEvent(event);\r\n}\r\n\r\nvoid View::keepCallout()\r\n{\r\n    m_callouts.append(m_tooltip);\r\n    m_tooltip = new Callout(m_chart);\r\n}\r\n\r\nvoid View::tooltip(QPointF point, bool state)\r\n{\r\n    if (m_tooltip == 0)\r\n        m_tooltip = new Callout(m_chart);\r\n\r\n    if (state) {\r\n        m_tooltip->setText(QString(\"X: %1 \\nY: %2 \").arg(point.x()).arg(point.y()));\r\n        m_tooltip->setAnchor(point);\r\n        m_tooltip->setZValue(11);\r\n        m_tooltip->updateGeometry();\r\n        m_tooltip->show();\r\n    } else {\r\n        m_tooltip->hide();\r\n    }\r\n}\r\n", "meta": {"hexsha": "26f08741f2f1e25eeb6d9c8c73d27a18d3cd8a70", "size": 7267, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "view.cpp", "max_stars_repo_name": "sergiosvieira/kalman_filter", "max_stars_repo_head_hexsha": "289af72f346ae334dcf71c447e05452b5696611e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "view.cpp", "max_issues_repo_name": "sergiosvieira/kalman_filter", "max_issues_repo_head_hexsha": "289af72f346ae334dcf71c447e05452b5696611e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "view.cpp", "max_forks_repo_name": "sergiosvieira/kalman_filter", "max_forks_repo_head_hexsha": "289af72f346ae334dcf71c447e05452b5696611e", "max_forks_repo_licenses": ["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.0765306122, "max_line_length": 90, "alphanum_fraction": 0.5511215082, "num_tokens": 2454, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.4771434505132897}}
{"text": "// A note to a potential future debugger, the -fno-use-cxa-atexit is needed solely for lli (the llvm interpreter) to work\n//   Actually compiling it works fine, and moreover, the one place atexit is used is nowhere near the enzyme code\n\n// RUN: %clang++ -fno-use-cxa-atexit -ffast-math -mllvm -force-vector-width=1 -ffast-math -fno-unroll-loops -fno-vectorize -fno-slp-vectorize -fno-exceptions -O3 %s -S -emit-llvm -o - | %opt - %loadEnzyme -enzyme -S | %lli - \n// RUN: %clang++ -fno-use-cxa-atexit -ffast-math -fno-unroll-loops -fno-vectorize -fno-slp-vectorize -fno-exceptions -O2 %s -S -emit-llvm -o - | %opt - %loadEnzyme -enzyme -S | %lli -\n// RUN: %clang++ -Xclang -new-struct-path-tbaa -fno-use-cxa-atexit -ffast-math -fno-unroll-loops -fno-vectorize -fno-slp-vectorize -fno-exceptions -O1 %s -S -emit-llvm -o - | %opt - %loadEnzyme -enzyme -S | %lli -\n//   note not doing O0 below as to ensure we get tbaa\n// RUN: %clang++ -Xclang -new-struct-path-tbaa -fno-use-cxa-atexit -ffast-math -fno-unroll-loops -fno-vectorize -fno-slp-vectorize -fno-exceptions -O1 -Xclang -disable-llvm-optzns %s -S -emit-llvm -o - | %opt - %loadEnzyme -enzyme -S | %lli - \n// RUN: %clang++ -fno-use-cxa-atexit -ffast-math -fno-unroll-loops -fno-vectorize -fno-slp-vectorize -fno-exceptions -O3 %s -S -emit-llvm -o - | %opt - %loadEnzyme -enzyme -enzyme-inline=1 -S | %lli - \n// RUN: %clang++ -fno-use-cxa-atexit -ffast-math -fno-unroll-loops -fno-vectorize -fno-slp-vectorize -fno-exceptions -O2 %s -S -emit-llvm -o - | %opt - %loadEnzyme -enzyme -enzyme-inline=1 -S | %lli -\n// Note the below ends up with a memcpy from undefined memory data for type analysis to handle\n// RUN: %clang++ -fno-use-cxa-atexit -ffast-math -fno-unroll-loops -fno-vectorize -fno-slp-vectorize -fno-exceptions -O1 %s -S -emit-llvm -o - | %opt - %loadEnzyme -enzyme -enzyme-inline=1 -S | %lli - \n// TODO: %clang++ -fno-use-cxa-atexit -ffast-math -fno-unroll-loops -fno-vectorize -fno-slp-vectorize -fno-exceptions -O0 %s -S -emit-llvm -o - | %opt - %loadEnzyme -enzyme -enzyme-inline=1 -S | %lli - \n\n#include \"test_utils.h\"\n\n#define BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n#define BOOST_NO_EXCEPTIONS\n#include <iostream>\n#include <boost/array.hpp>\n\n#include <boost/numeric/odeint.hpp>\n\n#include <boost/throw_exception.hpp>\nvoid boost::throw_exception(std::exception const & e){\n    //do nothing\n}\n\nusing namespace std;\nusing namespace boost::numeric::odeint;\n\n#include <stdio.h>\n\ntypedef boost::array< double , 1 > state_type;\n\nvoid lorenz( const state_type &x , state_type &dxdt , double t )\n{\n    const double a = 1.2;\n    dxdt[0] = -a * x[0];\n}\n\n    \ndouble foobar(double t=10.0) {\n    state_type x = { 1.0 }; // initial conditions\n\n    typedef controlled_runge_kutta< runge_kutta_dopri5< state_type , typename state_type::value_type , state_type , double > > stepper_type;\n    integrate_const( stepper_type(), lorenz , x , 0.0 , t, t/100 );\n    \n    //printf(\"final result t=%f x(t)=%f, exp(-1.2* t)=%f\\n\", t, x[0], exp(- 1.2 * t));\n    return x[0];\n}\n\nextern \"C\" {\nextern double __enzyme_autodiff(void*, double);\n}\n\nint main(int argc, char **argv)\n{\n    for(int i=1; i<=100; i++) {\n        double t=i/10.;\n        double res = __enzyme_autodiff((void*)foobar, t);\n        double realanswer = -1.2*exp(-1.2*t);\n        printf(\"t=%f d/dt(exp(-1.2*t))=%f, -1.2*exp(-1.2*t)=%f\\n\", t, res, realanswer);\n        // see if approximation is within 10%\n        APPROX_EQ(res, realanswer, max(fabs(realanswer)/10., 2.0e-5) );\n    }\n}\n", "meta": {"hexsha": "bcc819057037759e31b32fa7bd8cf98011fa8b2b", "size": 3493, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "enzyme/test/Integration/ReverseMode/integrateexp.cpp", "max_stars_repo_name": "anandijain/Enzyme", "max_stars_repo_head_hexsha": "fcaeb498a7fcb941be02ca407444fbb81e31c02e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 674.0, "max_stars_repo_stars_event_min_datetime": "2020-10-05T17:55:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T11:18:11.000Z", "max_issues_repo_path": "enzyme/test/Integration/ReverseMode/integrateexp.cpp", "max_issues_repo_name": "anandijain/Enzyme", "max_issues_repo_head_hexsha": "fcaeb498a7fcb941be02ca407444fbb81e31c02e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 119.0, "max_issues_repo_issues_event_min_datetime": "2020-10-07T00:47:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-06T16:46:58.000Z", "max_forks_repo_path": "enzyme/test/Integration/ReverseMode/integrateexp.cpp", "max_forks_repo_name": "anandijain/Enzyme", "max_forks_repo_head_hexsha": "fcaeb498a7fcb941be02ca407444fbb81e31c02e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 55.0, "max_forks_repo_forks_event_min_datetime": "2020-10-10T14:45:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-30T05:51:07.000Z", "avg_line_length": 51.3676470588, "max_line_length": 243, "alphanum_fraction": 0.6701975379, "num_tokens": 1198, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.4771434505132897}}
{"text": "<<<<<<< HEAD\r\n/*    Copyright (c) 2010-2018, Delft University of Technology\r\n=======\r\n/*    Copyright (c) 2010-2019, Delft University of Technology\r\n>>>>>>> origin/master\r\n *    All rigths reserved\r\n *\r\n *    This file is part of the Tudat. Redistribution and use in source and\r\n *    binary forms, with or without modification, are permitted exclusively\r\n *    under the terms of the Modified BSD license. You should have received\r\n *    a copy of the license with this file. If not, please or visit:\r\n *    http://tudat.tudelft.nl/LICENSE.\r\n *\r\n *    References\r\n *      Vallado, D.A. Fundamentals of Astrodynamics and Applications website.\r\n *        URL http://www.smad.com/vallado, 2001. Last accessed: 25-07-2012.\r\n *      Wakker, K.F. Astrodynamics I, reader of course AE4874 I. Delft University of Technology,\r\n *        2007.\r\n *\r\n */\r\n\r\n#define BOOST_TEST_MAIN\r\n\r\n#include <cmath>\r\n\r\n#include <boost/test/floating_point_comparison.hpp>\r\n#include <boost/test/unit_test.hpp>\r\n\r\n#include <Eigen/Core>\r\n\r\n#include \"Tudat/Basics/testMacros.h\"\r\n#include \"Tudat/Mathematics/BasicMathematics/mathematicalConstants.h\"\r\n\r\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/clohessyWiltshirePropagator.h\"\r\n\r\nnamespace tudat\r\n{\r\nnamespace unit_tests\r\n{\r\n\r\n//! Test suite for Clohessy-Wiltshire propagation.\r\nBOOST_AUTO_TEST_SUITE( test_clohessyWiltshirePropagation )\r\n\r\n// Testcase 1: propagation of full state in low-Earth orbit.\r\n// This test benchmarks the propagation of a full state against external data.\r\nBOOST_AUTO_TEST_CASE( test_ClohessyWiltshirePropagation_fullState )\r\n{\r\n    // Set central body gravitational parameter [m^3 s^-2].\r\n    // In this case: central body is Earth.\r\n    const double centralBodyGravitationalParameter1 = 3.986004418e14;\r\n\r\n    // Set propagation duration [s].\r\n    // In this case: propagation duration is 30 minutes.\r\n    const double propagationDuration1 = 1800.0;\r\n\r\n    // Set reference orbit radius [m].\r\n    // In this case: reference orbit is at 400 km altitude above Earth.\r\n    const double referenceOrbitRadius1 = 6.778137e6;\r\n\r\n    // Set initial state [m], [m], [m], [m/s], [m,s], [m/s].\r\n    // In this case: arbitrary non-zero distances and velocities.\r\n    const Eigen::Vector6d initialState1 =\r\n            ( Eigen::Vector6d( ) << 45.0, 37.0, 12.0, 0.08,\r\n              0.03, 0.01 ).finished( );\r\n\r\n    // Calculate final state according to Tudat function.\r\n    const Eigen::Vector6d computedFinalState1\r\n            = basic_astrodynamics::propagateClohessyWiltshire(\r\n                initialState1,\r\n                propagationDuration1,\r\n                centralBodyGravitationalParameter1,\r\n                referenceOrbitRadius1 );\r\n\r\n    // Set final state according to the MATLAB routine \"hillsr\" from Vallado [2001].\r\n    const Eigen::Vector6d expectedFinalState1 =\r\n            ( Eigen::Vector6d( ) << 3.806450080201250e2,\r\n              -5.437424675454679e2, 2.509547637285142,\r\n              1.541620605755606e-1, -7.294751390499470e-1,\r\n              -1.662099488431618e-2 ).finished( );\r\n\r\n    // Check if computed final state matches expected state.\r\n    TUDAT_CHECK_MATRIX_CLOSE_FRACTION( computedFinalState1, expectedFinalState1, 1.0e-14 );\r\n}\r\n\r\n// Testcase 2: pure harmonic relative motion in low-Earth orbit.\r\n//   According to Wakker [2007] pure harmonic relative motion occurs if two conditions are met:\r\n//   (1) initialRadialVelocity = 0.5 * meanAngularMotion * initialAlongTrackPosition.\r\n//   (2) initialAlongTrackVelocity = -2.0 * meanAngularMotion * initialRadialPosition.\r\n//   Therefore the final state after one orbital revolution must be exactly equal to the initial\r\n//   state. This testcase verifies this.\r\nBOOST_AUTO_TEST_CASE( test_ClohessyWiltshirePropagation_harmonicMotion )\r\n{\r\n    // Set central body gravitational parameter [m^3 s^-2].\r\n    // In this case: central body is Earth.\r\n    const double centralBodyGravitationalParameter2 = 3.986004418e14;\r\n\r\n    // Set reference orbit radius [m].\r\n    // In this case: reference orbit is at 400 km altitude above Earth.\r\n    const double referenceOrbitRadius2 = 6.778137e6;\r\n\r\n    // Calculate mean angular motion of reference orbit [rad].\r\n    const double meanAngularMotion =\r\n            std::sqrt( centralBodyGravitationalParameter2\r\n                       / ( referenceOrbitRadius2 * referenceOrbitRadius2\r\n                           * referenceOrbitRadius2 ) );\r\n\r\n    // Set propagation duration [s].\r\n    // In this case: orbital period of the reference orbit.\r\n    const double propagationDuration2 = 2.0 * mathematical_constants::PI\r\n            / meanAngularMotion;\r\n\r\n    // Set initial state [m], [m], [m], [m/s], [m,s], [m/s].\r\n    // In this case: arbitrary values for initial positions and initialCrossTrackVelocity. The\r\n    // initialRadialVelocity and initialAlongTrackVelocity are set to achieve harmonic motion.\r\n    const Eigen::Vector6d initialState2 =\r\n            ( Eigen::Vector6d( )\r\n              << 34.0, 49.0 , 17.0,\r\n              0.5 * meanAngularMotion * 49.0,\r\n              -2.0 * meanAngularMotion * 34.0, 0.04 ).finished( );\r\n\r\n    // Calculate final state according to Tudat function.\r\n    const Eigen::Vector6d computedFinalState2\r\n            = basic_astrodynamics::propagateClohessyWiltshire(\r\n                initialState2,\r\n                propagationDuration2,\r\n                centralBodyGravitationalParameter2,\r\n                referenceOrbitRadius2 );\r\n\r\n    // Check if computed final state matches the initial state.\r\n    TUDAT_CHECK_MATRIX_CLOSE_FRACTION( initialState2, computedFinalState2, 1.0e-14 );\r\n}\r\n\r\nBOOST_AUTO_TEST_SUITE_END( )\r\n\r\n} // namespace unit_tests\r\n} // namespace tudat\r\n", "meta": {"hexsha": "03f2ab30dc9fae074a47f8081f5819abdada340d", "size": 5679, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/BasicAstrodynamics/UnitTests/unitTestClohessyWiltshirePropagator.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/BasicAstrodynamics/UnitTests/unitTestClohessyWiltshirePropagator.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/BasicAstrodynamics/UnitTests/unitTestClohessyWiltshirePropagator.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": 41.4525547445, "max_line_length": 97, "alphanum_fraction": 0.676175383, "num_tokens": 1430, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952052, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.4771434459512162}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2014 Jose Aparicio\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n#ifndef quantlib_math_multidimintegrator_hpp\n#define quantlib_math_multidimintegrator_hpp\n\n#include <vector>\n\n#include <boost/function.hpp>\n#include <boost/bind.hpp>\n\n#include <ql/types.hpp>\n#include <ql/errors.hpp>\n#include <ql/math/integrals/integral.hpp>\n\nnamespace QuantLib {\n\n    /*! \\brief Integrates a vector or scalar function of vector domain. \n        \n        Uses a collection of arbitrary 1D integrators along each of the \n        dimensions. A template recursion along dimensions avoids calling depth \n        test or virtual functions.\\par\n        This class generalizes to an arbitrary number of dimensions the \n        functionality in class TwoDimensionalIntegral  \n    */\n    class MultidimIntegral {\n    public:\n        explicit MultidimIntegral(\n            const std::vector<boost::shared_ptr<Integrator> >& integrators);\n\n        // scalar variant:\n        /*!\n            @param f Integrand function.\n            @param a Lower integration limit domain for each dimension.\n            @param b Upper integration limit domain for each dimension.\n        */\n        Real operator()(\n            const boost::function<Real (const std::vector<Real>&)>& f,\n            const std::vector<Real>& a,\n            const std::vector<Real>& b) const \n        {\n            QL_REQUIRE((a.size()==b.size())&&(b.size()==integrators_.size()), \n                \"Incompatible integration problem dimensions\");\n            return integrationLevelEntries_[integrators_.size()-1](f, a, b);\n        }\n        // to do: write std::vector<Real> operator()(...) version\n\n    private:\n        static const Size maxDimensions_ = 15;\n\n        /* Here is the tradeoff; this is avoiding the dimension limits checks \n        during integration at the price of these asignments during construction.\n        Explicit template instantiation is of no use, an object is needed \n        (notice 'this' is needed for the asignment.)\n        If not all the dimensions up the maximum number are used the waste goes\n        into storage of the functions (in fact only one is used)\n        */\n        template<Size depth>\n        void spawnFcts() const;\n        // Splits the integration in cross-sections per dimension.\n        template<int T_N> \n        Real vectorBinder (\n            const boost::function<Real (const std::vector<Real>&)>& f,\n            Real z,\n            const std::vector<Real>& a,\n            const std::vector<Real>& b) const ;\n        // actual integration of dimension nT\n        template<int nT>\n        Real integrate(\n            const boost::function<Real (const std::vector<Real>&)>& f,\n            const std::vector<Real>& a,\n            const std::vector<Real>& b) const;\n    private:\n        const std::vector<boost::shared_ptr<Integrator> > integrators_;\n\n        /* typedef (const boost::function<Real \n            (const std::vector<Real>&arg1)>&arg2) integrableFunctType;\n        */\n\n        /* vector of, functions returning reals And taking as argument: \n        1.- a const ref to a function taking vectors \n        2.- a vector, 3. another vector. typedefs eventually...\n         at first sight this might look like mimicking a virtual table, it isnt \n         that. The reason is to be able to select the correct integration \n         dimension at run time, this can not be done before because of the \n         template argument restriction to be constant known at compilation.\n        */\n        mutable std::vector<boost::function<Real (//<- members: integrate<N>\n            // integrable function:\n            const boost::function<Real (const std::vector<Real>&)>&, \n            const std::vector<Real>&, //<- a\n            const std::vector<Real>&) //<- b\n            > > \n            integrationLevelEntries_;\n\n        /* One can avoid the passing around of the ct refs to a and b but the \n        price is to keep a copy of them (they are unknown at construction time)\n         On the other hand the vector integration variable has to be created.*/\n        mutable std::vector<Real> varBuffer_;\n\n    };\n\t\n    // spez last call/dimension\n    template<>\n    Real inline MultidimIntegral::vectorBinder<0> (\n        const boost::function<Real (const std::vector<Real>&)>& f, \n        Real z,\n        const std::vector<Real>& a,\n        const std::vector<Real>& b) const\n    {\n        varBuffer_[0] = z;\n        return f(varBuffer_);\n    }\n\t\n    template<>\n    void inline MultidimIntegral::spawnFcts<1>() const {\n        integrationLevelEntries_[0] = \n            boost::bind(&MultidimIntegral::integrate<0>, this, _1, _2, _3);\n    }\n\t\n\ttemplate<int nT>\n\tinline Real MultidimIntegral::integrate(\n        const boost::function<Real (const std::vector<Real>&)>& f,\n        const std::vector<Real>& a,\n        const std::vector<Real>& b) const \n    {\n        return \n            (*integrators_[nT])(\n                boost::bind(&MultidimIntegral::vectorBinder<nT>, this, f, \n                    _1, boost::cref(a), boost::cref(b)), a[nT], b[nT]);\n    }\n\n    template<int T_N> \n    inline Real MultidimIntegral::vectorBinder (\n        const boost::function<Real (const std::vector<Real>&)>& f,\n        Real z,\n        const std::vector<Real>& a,\n        const std::vector<Real>& b) const \n    {\n        varBuffer_[T_N] = z;\n        return integrate<T_N-1>(f, a, b);\n    }\n\t\t\n    template<Size depth>\n    void MultidimIntegral::spawnFcts() const {\n        integrationLevelEntries_[depth-1] =\n          boost::bind(&MultidimIntegral::integrate<depth-1>, this, \n            _1, _2, _3);\n        spawnFcts<depth-1>();\n    }\n\t\t\n}\n\n#endif\n", "meta": {"hexsha": "ba61f24e42129ba8e84fbd306fc70fade4cabed4", "size": 6361, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "QuantLib/ql/experimental/math/multidimintegrator.hpp", "max_stars_repo_name": "frannuca/quantlib", "max_stars_repo_head_hexsha": "63e66f5f767397e5b7c79fa78eaed4e3e0a6b7c6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "QuantLib/ql/experimental/math/multidimintegrator.hpp", "max_issues_repo_name": "frannuca/quantlib", "max_issues_repo_head_hexsha": "63e66f5f767397e5b7c79fa78eaed4e3e0a6b7c6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "QuantLib/ql/experimental/math/multidimintegrator.hpp", "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": 37.1988304094, "max_line_length": 80, "alphanum_fraction": 0.6274170728, "num_tokens": 1460, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.6791786861878392, "lm_q1q2_score": 0.47714344138914283}}
{"text": "//  (C) Copyright Raffi Enficiaud 2014.\n//  Distributed under the Boost Software License, Version 1.0.\n//  (See accompanying file LICENSE_1_0.txt or copy at\n//  http://www.boost.org/LICENSE_1_0.txt)\n//\n//  See http://www.boost.org/libs/test for the library home page.\n//\n//  snippets included in the dataset documentation\n// ***************************************************************************\n\n#define BOOST_TEST_MAIN\n#include <boost/test/included/unit_test.hpp>\n#include <boost/test/data/test_case.hpp>\n\n#include <boost/test/data/monomorphic.hpp>\n\n#include <boost/test/data/monomorphic/generators/xrange.hpp>\n#include <boost/test/data/monomorphic/zip.hpp>\n\n// generation of a sequence/range\nnamespace data=boost::unit_test::data;\n\n\n//[snippet_dataset1_1\nBOOST_DATA_TEST_CASE( test_case_arity1_implicit, data::xrange(5) )\n{\n  BOOST_TEST((sample <= 4 && sample >= 0));\n}\n//]\n\n//[snippet_dataset1_2\nBOOST_DATA_TEST_CASE( test_case_arity1, data::xrange(5), my_var )\n{\n  BOOST_TEST((my_var <= 4 && my_var >= 0));\n}\n//]\n\n//[snippet_dataset1_3\nBOOST_DATA_TEST_CASE( test_case_arity2, data::xrange(2) ^ data::xrange(5), apples, potatoes)\n{\n  BOOST_TEST((apples <= 1 && apples >= 0));\n  BOOST_TEST((potatoes <= 4 && potatoes >= 0));\n}\n//]\n\n\n\n\n//[snippet_dataset1_4\nstd::vector<int> generate()\n{\n  std::vector<int> out;\n  out.push_back(3);\n  out.push_back(1);\n  out.push_back(7);\n  return out;\n}\n\nconst std::vector<int> v = generate();\nBOOST_DATA_TEST_CASE( test_case_3, data::make(v), var1)\n{\n  BOOST_TEST_MESSAGE(var1);\n  BOOST_CHECK(true);\n}\n//]\n\n\n#include <vector>\n#include <map>\n\nstd::vector<int> generate_vector()\n{\n  std::vector<int> out;\n  out.push_back(3);\n  out.push_back(1);\n  out.push_back(7);\n  return out;\n}\n\ntypedef std::pair<const int, int> pair_int;\nBOOST_TEST_DONT_PRINT_LOG_VALUE( pair_int )\n\nconst std::vector<int> v = generate_vector();\nBOOST_DATA_TEST_CASE( test_case_1, data::make(v), var1)\n{\n  std::cout << var1 << std::endl;\n  BOOST_TEST(true);\n}\n\n\nstd::map<int, int> generate_map()\n{\n  std::vector<int> v = generate_vector();\n  std::map<int, int> out;\n  for(std::size_t i = 0; i < v.size(); i++)\n  {\n    out[v[i]] = (i * 7) % 19;\n  }\n  return out;\n}\n\nconst std::map<int, int> m = generate_map();\nBOOST_DATA_TEST_CASE( test_case_2, data::make(m), var1)\n{\n  std::cout << var1.first << \" -- \" << var1.second << std::endl;\n  BOOST_TEST(true);\n}\n", "meta": {"hexsha": "ba412a8c40918a1f50d123f9f2e665f065d1802e", "size": 2366, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "deps/boost/libs/test/doc/snippet/dataset_1/test_file.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/test/doc/snippet/dataset_1/test_file.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/test/doc/snippet/dataset_1/test_file.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": 21.9074074074, "max_line_length": 92, "alphanum_fraction": 0.6614539307, "num_tokens": 686, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6791786861878392, "lm_q2_score": 0.7025300573952052, "lm_q1q2_score": 0.4771434413891427}}
{"text": "#ifndef __FOLDING_ESTIMATION_ALGORITHM__\n#define __FOLDING_ESTIMATION_ALGORITHM__\n\n#include <ros/ros.h>\n#include <Eigen/Dense>\n#include <math.h>\n#include <pr2_algorithms/algorithm_base.hpp>\n#include <limits>\n#include <stdexcept>\n\nnamespace manipulation_algorithms{\n\n  /**\n    Class that implements the contact point estimator\n    used in the folding assembly problem.\n  **/\n  class FoldingAssemblyEstimator : public AlgorithmBase\n  {\n  public:\n    FoldingAssemblyEstimator();\n    ~FoldingAssemblyEstimator();\n\n    /**\n      Computes an estimate of the free vector that represents a rigidly grasped object.\n\n      Makes use of the process model \\f$\\dot{\\mathbf{r}} = \\mathbf{S}(\\boldsymbol{\\omega_1}}) \\mathbf{r}\\f$\n      and of the observation model \\f$\\boldsymbol{\\tau} = -\\mathbf{S}(\\mathbf{f})\\mathbf{r}\\f$.\n\n      @param omega The end-effector angular velocity.\n      @param force The measured contact force.\n      @param torque The measured torque at the end-effector wrist.\n      @param dt Elapsed time between calls (in seconds).\n      @return A free vector representing the estimate of the vector that connects the wrench measurement point to the contact point.\n    **/\n    Eigen::Vector3d estimate(const Eigen::Vector3d &omega, const Eigen::Vector3d &force, const Eigen::Vector3d &torque, const double dt);\n\n    /**\n      Initialize the estimator\n\n      @param r The initial virtual stick estimate.\n    **/\n    void initialize(const Eigen::Vector3d &r);\n\n    virtual bool getParams(const ros::NodeHandle &n);\n\n  private:\n    Eigen::Vector3d r_;\n    Eigen::Matrix3d P_, Q_, R_;\n  };\n}\n#endif\n", "meta": {"hexsha": "605058eb509c53b3f21e1c00638ebee65f1deea4", "size": 1600, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pr2_algorithms/include/pr2_algorithms/folding_assembly/folding_assembly_estimator.hpp", "max_stars_repo_name": "diogoalmeida/pr2_controller_framework", "max_stars_repo_head_hexsha": "852240638d8da439485d69fb1f627db5845c6820", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pr2_algorithms/include/pr2_algorithms/folding_assembly/folding_assembly_estimator.hpp", "max_issues_repo_name": "diogoalmeida/pr2_controller_framework", "max_issues_repo_head_hexsha": "852240638d8da439485d69fb1f627db5845c6820", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pr2_algorithms/include/pr2_algorithms/folding_assembly/folding_assembly_estimator.hpp", "max_forks_repo_name": "diogoalmeida/pr2_controller_framework", "max_forks_repo_head_hexsha": "852240638d8da439485d69fb1f627db5845c6820", "max_forks_repo_licenses": ["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.7692307692, "max_line_length": 137, "alphanum_fraction": 0.709375, "num_tokens": 392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152325073083131, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4769934809700881}}
{"text": "#include \"ParallelEigenvectorsEvaluator.hh\"\n\n#include <Eigen/Geometry>\n\n#include <boost/algorithm/cxx11/any_of.hpp>\n#include <boost/range/algorithm/min_element.hpp>\n#include <boost/range/algorithm/max_element.hpp>\n\n#include <vector>\n\nusing namespace cpp_utils;\n\nnamespace tl\n{\n\ntemplate <typename T, std::size_t... Degrees>\nusing TPBT = TensorProductBezierTriangle<T, double, Degrees...>;\n\nstd::array<TPBT<double, 1, 2>, 6>\nparallelEigenvectorsCoeffs(const TensorInterp& s,\n                           const TensorInterp& t,\n                           const Triangle& r)\n{\n    using Coords = TPBT<double, 1, 2>::Coords;\n\n    // (T * r) x r\n    auto eval_ev =\n            [&](const Coords& coords, const TensorInterp& t, int i) -> double {\n        auto rv = r(coords.tail<3>());\n        auto tv = t(coords.head<3>());\n        return (tv * rv).cross(rv)[i];\n    };\n\n    auto eval1 = [&](const Coords& coords) { return eval_ev(coords, s, 0); };\n    auto eval2 = [&](const Coords& coords) { return eval_ev(coords, s, 1); };\n    auto eval3 = [&](const Coords& coords) { return eval_ev(coords, s, 2); };\n\n    auto eval4 = [&](const Coords& coords) { return eval_ev(coords, t, 0); };\n    auto eval5 = [&](const Coords& coords) { return eval_ev(coords, t, 1); };\n    auto eval6 = [&](const Coords& coords) { return eval_ev(coords, t, 2); };\n\n    return {TPBT<double, 1, 2>{eval1},\n            TPBT<double, 1, 2>{eval2},\n            TPBT<double, 1, 2>{eval3},\n            TPBT<double, 1, 2>{eval4},\n            TPBT<double, 1, 2>{eval5},\n            TPBT<double, 1, 2>{eval6}};\n}\n\n\nusing PEVE = ParallelEigenvectorsEvaluator;\n\nPEVE::ParallelEigenvectorsEvaluator(const DoubleTri& tri,\n                                    const TensorInterp& s,\n                                    const TensorInterp& t,\n                                    const Options& opts)\n        : _tri(tri),\n          _target_funcs(parallelEigenvectorsCoeffs(s, t, tri.dir_tri)),\n          _opts(opts)\n{\n}\n\n\nstd::array<PEVE, 4> PEVE::split() const\n{\n    if(_last_split_dir)\n    {\n        return split<0>();\n    }\n    return split<1>();\n}\n\n\nResult PEVE::eval()\n{\n    // Check if any of the error components can not become zero in the\n    // current subdivision triangles\n    auto has_nonzero = boost::algorithm::any_of(\n            _target_funcs,\n            [](const auto& c) { return sameSign(c.coefficients()) != 0; });\n\n    // Discard triangles if no roots can occur inside\n    if(has_nonzero)\n    {\n        return Result::Discard;\n    }\n\n    // Compute upper bound for target function\n    auto max_error = abs_max_upper_bound(_target_funcs);\n\n    if(max_error < _opts.tolerance)\n    {\n        return Result::Accept;\n    }\n\n    return Result::Split;\n}\n\n\ndouble PEVE::error() const\n{\n    return upper_bound_norm(_target_funcs);\n}\n\n\ndouble PEVE::condition() const\n{\n    auto gradients = std::vector<Eigen::Vector4d>{};\n    gradients.reserve(_target_funcs.size());\n\n    auto min_cos = 0.;\n\n    auto center0 = (TensorProductDerivativeType_t<0, double, double, 1, 2>::\n                            Coords::Ones()\n                    / 3.).eval();\n    auto center1 = (TensorProductDerivativeType_t<1, double, double, 1, 2>::\n                            Coords::Ones()\n                    / 3.).eval();\n\n    for(const auto& poly: _target_funcs)\n    {\n        auto deriv0 = derivatives<0>(poly);\n        auto deriv1 = derivatives<1>(poly);\n        auto grad = Eigen::Vector4d(deriv0[0](center0),\n                                    deriv0[1](center0),\n                                    deriv1[0](center1),\n                                    deriv1[1](center1));\n        grad.normalize();\n        for(const auto& g: gradients)\n        {\n            min_cos = std::min(min_cos, std::abs(grad.dot(g)));\n        }\n        gradients.push_back(grad);\n    }\n\n    auto angle = std::acos(min_cos);\n    return min_cos / std::sin(angle);\n}\n\n\ndouble distance(const PEVE& t1, const PEVE& t2)\n{\n    return distance(t1.tris(), t2.tris());\n}\n\n\nbool operator==(const PEVE& t1, const PEVE& t2)\n{\n    return t1._tri == t2._tri && t1._target_funcs == t2._target_funcs\n           && t1._last_split_dir == t2._last_split_dir\n           && t1._split_level == t2._split_level && t1._opts == t2._opts;\n}\n\n\nbool operator!=(const PEVE& t1, const PEVE& t2)\n{\n    return !(t1 == t2);\n}\n\n}// namespace tl\n", "meta": {"hexsha": "f67fa18540d8947b9aead96bef6b06b083f3c43f", "size": 4335, "ext": "cc", "lang": "C++", "max_stars_repo_path": "cpp/src/ParallelEigenvectorsEvaluator.cc", "max_stars_repo_name": "timo-oster/tensor-lines", "max_stars_repo_head_hexsha": "b4f489452f3ce5b5f48042cc035e53d3fdaa675e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cpp/src/ParallelEigenvectorsEvaluator.cc", "max_issues_repo_name": "timo-oster/tensor-lines", "max_issues_repo_head_hexsha": "b4f489452f3ce5b5f48042cc035e53d3fdaa675e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp/src/ParallelEigenvectorsEvaluator.cc", "max_forks_repo_name": "timo-oster/tensor-lines", "max_forks_repo_head_hexsha": "b4f489452f3ce5b5f48042cc035e53d3fdaa675e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-13T00:08:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-13T00:08:09.000Z", "avg_line_length": 26.9254658385, "max_line_length": 79, "alphanum_fraction": 0.5688581315, "num_tokens": 1153, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324983301568, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.47699347571695844}}
{"text": "//  (C) Copyright Matt Borland 2021.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include <cmath>\n#include <cstdint>\n#include <limits>\n#include <type_traits>\n#include <boost/math/ccmath/abs.hpp>\n#include <boost/math/ccmath/fabs.hpp>\n#include <boost/math/tools/config.hpp>\n\n#ifdef BOOST_HAS_FLOAT128\n#include <boost/multiprecision/float128.hpp>\n#endif\n\ntemplate <typename T>\nvoid test()\n{\n    static_assert(boost::math::ccmath::abs(T(3)) == 3);\n    static_assert(boost::math::ccmath::abs(T(-3)) == 3);\n    static_assert(boost::math::ccmath::abs(T(-0)) == 0);\n    static_assert(boost::math::ccmath::abs(-std::numeric_limits<T>::infinity()) == std::numeric_limits<T>::infinity());\n\n    if constexpr (std::numeric_limits<T>::has_quiet_NaN)\n    {\n        static_assert(boost::math::ccmath::abs(-std::numeric_limits<T>::quiet_NaN()) != std::numeric_limits<T>::quiet_NaN());\n    }\n}\n\ntemplate <typename T>\nvoid gpp_test()\n{\n    static_assert(std::sin(T(0)) == 0);\n    \n    constexpr T sin_1 = boost::math::ccmath::abs(std::sin(T(-1)));\n    static_assert(sin_1 > 0);\n    static_assert(sin_1 == T(0.8414709848078965066525l));\n}\n\ntemplate <typename T>\nvoid fabs_test()\n{\n    static_assert(boost::math::ccmath::fabs(T(3)) == 3);\n    static_assert(boost::math::ccmath::fabs(T(-3)) == 3);\n    static_assert(boost::math::ccmath::fabs(T(-0)) == 0);\n    static_assert(boost::math::ccmath::fabs(-std::numeric_limits<T>::infinity()) == std::numeric_limits<T>::infinity());\n\n    if constexpr (std::numeric_limits<T>::has_quiet_NaN)\n    {\n        static_assert(boost::math::ccmath::fabs(-std::numeric_limits<T>::quiet_NaN()) != std::numeric_limits<T>::quiet_NaN());\n    }\n}\n\n// Only test on platforms that provide BOOST_MATH_IS_CONSTANT_EVALUATED\n#ifndef BOOST_MATH_NO_CONSTEXPR_DETECTION\nint main()\n{\n    test<float>();\n    test<double>();\n    \n    #ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n    test<long double>();\n    #endif\n\n    #if defined(BOOST_HAS_FLOAT128) && !defined(BOOST_MATH_USING_BUILTIN_CONSTANT_P)\n    test<boost::multiprecision::float128>();\n    #endif\n\n    test<int>();\n    test<long>();\n    test<long long>();\n    test<std::int32_t>();\n    test<std::int64_t>();\n\n    // Types that are convertible to int\n    test<short>();\n    test<char>();\n\n    // fabs\n    fabs_test<float>();\n    fabs_test<double>();\n\n    #ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n    fabs_test<long double>();\n    #endif\n\n    #if defined(BOOST_HAS_FLOAT128) && !defined(BOOST_MATH_USING_BUILTIN_CONSTANT_P)\n    fabs_test<boost::multiprecision::float128>();\n    #endif\n\n    // Tests using glibcxx extensions that allow for some constexpr cmath\n    #if __GNUC__ >= 10\n    gpp_test<float>();\n    gpp_test<double>();\n\n    #ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n    gpp_test<long double>();\n    #endif\n    \n    #endif // glibcxx tests\n\n    return 0;\n}\n#else\nint main()\n{\n    return 0;\n}\n#endif\n", "meta": {"hexsha": "76fe489e8a90dc73012790b37813d1507edc1967", "size": 3030, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/ccmath_abs_test.cpp", "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": "test/ccmath_abs_test.cpp", "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": "test/ccmath_abs_test.cpp", "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.0535714286, "max_line_length": 126, "alphanum_fraction": 0.6726072607, "num_tokens": 811, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.47699347046382856}}
{"text": "/*\n@copyright Louis Dionne 2015\nDistributed under the Boost Software License, Version 1.0.\n(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n */\n\n#include <boost/hana/integral_constant.hpp>\n\n#include <boost/hana/tuple.hpp>\n\n#include <laws/enumerable.hpp>\n#include <laws/group.hpp>\n#include <laws/integral_domain.hpp>\n#include <laws/monoid.hpp>\n#include <laws/ring.hpp>\nusing namespace boost::hana;\n\n\nint main() {\n    auto int_constants = tuple_c<int, -10, -2, 0, 1, 3, 4>;\n\n    //////////////////////////////////////////////////////////////////////////\n    // Enumerable, Monoid, Group, Ring, IntegralDomain\n    //////////////////////////////////////////////////////////////////////////\n    {\n        // operators\n        static_assert(has_operator<IntegralConstant<int>, decltype(plus)>{}, \"\");\n        static_assert(has_operator<IntegralConstant<int>, decltype(minus)>{}, \"\");\n        static_assert(has_operator<IntegralConstant<int>, decltype(negate)>{}, \"\");\n        static_assert(has_operator<IntegralConstant<int>, decltype(mult)>{}, \"\");\n        static_assert(has_operator<IntegralConstant<int>, decltype(quot)>{}, \"\");\n        static_assert(has_operator<IntegralConstant<int>, decltype(rem)>{}, \"\");\n\n        // laws\n        test::TestEnumerable<IntegralConstant<int>>{int_constants};\n        test::TestMonoid<IntegralConstant<int>>{int_constants};\n        test::TestGroup<IntegralConstant<int>>{int_constants};\n        test::TestRing<IntegralConstant<int>>{int_constants};\n        test::TestIntegralDomain<IntegralConstant<int>>{int_constants};\n    }\n}\n", "meta": {"hexsha": "f1d95c24febae7a03504cbc3b0b39be4229ef9d7", "size": 1591, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/integral_constant/integral_domain.cpp", "max_stars_repo_name": "josephwinston/hana", "max_stars_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/integral_constant/integral_domain.cpp", "max_issues_repo_name": "josephwinston/hana", "max_issues_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/integral_constant/integral_domain.cpp", "max_forks_repo_name": "josephwinston/hana", "max_forks_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.880952381, "max_line_length": 83, "alphanum_fraction": 0.6266499057, "num_tokens": 346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.47699347046382856}}
{"text": "/* Copyright (c) 2015, Julian Straub <jstraub@csail.mit.edu>, Randi Cabezas <rcabezas@csail.mit.edu>                    \n * Licensed under the MIT license. See the license file LICENSE.                \n */\n\n#pragma once\n\n#include <Eigen/Dense>\n\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/math/distributions/inverse_gamma.hpp>\n\n#include <boost/random/chi_squared_distribution.hpp>\n#include <boost/random/normal_distribution.hpp>\n\n#include <boost/math/special_functions/bessel.hpp>\n\n#include <dpMM/distribution.hpp>\n#include <dpMM/vmf.hpp>\n\nusing namespace Eigen;\nusing std::endl;\nusing std::cout;\nusing std::vector;\n\ntemplate<typename T>\nclass vMFpriorFull : public Distribution<T>\n{\npublic:\n  vMFpriorFull(const Matrix<T,Dynamic,1>& m0, T t0, T a0, T b0, boost::mt19937\n    *pRndGen);\n  vMFpriorFull(const vMFpriorFull<T>& vmfPriorFull);\n  ~vMFpriorFull();\n\n//  vMFpriorFull<T> posterior(const Matrix<T,Dynamic,Dynamic>& x, const\n//      VectorXu& z, uint32_t k); \n//  vMFpriorFull<T> posterior() const;  \n\n  void resetSufficientStatistics();\n  void getSufficientStatistics(const Matrix<T,Dynamic,Dynamic> &x, \n    const VectorXu& z, uint32_t k);\n\n  vMF<T> sample();\n  vMF<T> sampleFromPosterior(const vMF<T>& vmf);\n\n//  T logPdf(const vMF<T>& vmf) const;\n//  T logPdfMarginalized() const; // log pdf of SS under NIW prior\n//  T logPdfUnderPriorMarginalizedMerged(const NIW<T>& other) const;\n\n  vMF<T> vmf0_; // prior on the mean\n  T a0_;\n  T b0_;\n\n  uint32_t D_;\n  // sufficient statistics\n  Matrix<T,Dynamic,1> xSum_;\n  T count_;\n\n  boost::mt19937 *pRndGen_;\n\nprivate:\n  boost::uniform_01<> unif_;\n\n  T concentrationLogPdf(const T tau, const T a, const T b) const;\n  T sampleConcentration(const T a, const T b, const T TT=10);\n};\n// -----------------------------------------------------------------------\n\ntemplate<typename T> \nvMFpriorFull<T>::vMFpriorFull(const Matrix<T,Dynamic,1>& m0, T t0, T a0, T\n    b0, boost::mt19937 *pRndGen)\n: Distribution<T>(pRndGen), vmf0_(m0,t0,pRndGen), a0_(a0), b0_(b0), D_(m0.rows()),\nxSum_(Matrix<T,Dynamic,1>::Zero(m0.rows())), count_(0.), pRndGen_(pRndGen)\n{\n//cout<<m0<<endl; cout<<m0.rows()<<endl;cout<<uint32_t(m0.rows())<<endl;\n};\n\ntemplate<typename T> \nvMFpriorFull<T>::vMFpriorFull(const vMFpriorFull<T>& vmfPriorFull)\n: Distribution<T>(vmfPriorFull.pRndGen_), vmf0_(vmfPriorFull.vmf0_),\na0_(vmfPriorFull.a0_), b0_(vmfPriorFull.b0_), D_(vmfPriorFull.D_), \nxSum_(vmfPriorFull.xSum_), count_(vmfPriorFull.count_),\npRndGen_(vmfPriorFull.pRndGen_)\n{};\n\n\ntemplate<typename T> \nvMFpriorFull<T>::~vMFpriorFull()\n{\n};\n\n//template<typename T> \n//vMFpriorFull<T> vMFpriorFull<T>::posterior(const \n//    Matrix<T,Dynamic,Dynamic>& x, const VectorXu& z, uint32_t k)\n//{\n//  getSufficientStatistics(x,z,k);\n//  return posterior();\n//};\n//\n//template<typename T>\n//vMFpriorFull<T> vMFpriorFull<T>::posterior() const\n//{\n//  Matrix<T,Dynamic,1> xi = t0_*m0_ +;\n//  const T a = a0_ + count_;\n//  const T b = b0_ + \n//  return vMFpriorFull(xSum_, count_);\n//};\n\ntemplate<typename T>\nvoid vMFpriorFull<T>::resetSufficientStatistics()\n{\n  xSum_.setZero(D_);\n  count_ = 0;\n};\n\n\ntemplate<typename T>\nvoid vMFpriorFull<T>::getSufficientStatistics(const\n    Matrix<T,Dynamic,Dynamic> &x, const VectorXu& z, uint32_t k)\n{\n  this->resetSufficientStatistics();\n  // TODO: be carefull here when parallelizing since all are writing to the same \n  // location in memory\n#pragma omp parallel for\n  for (int32_t i=0; i<z.size(); ++i)\n  {\n    if(z(i) == k)\n    {      \n#pragma omp critical\n      {\n        xSum_ += x.col(i);\n        count_++;\n      }\n    }\n  }\n#ifndef NDEBUG\n  cout<<\" -- updating ss \"<<count_<<endl;\n  cout<<\"xSum=\"<<xSum_.transpose()<<endl;\n  posterior().print();\n#endif\n//  cout<<\"SS: \"<<count_<<\" \"<<xSum_.transpose()<<endl;\n};\n\ntemplate<typename T>\nvMF<T> vMFpriorFull<T>::sample()\n{\n  const T tau = sampleConcentration(a0_,b0_);\n  const Matrix<T,Dynamic,1> mu = vmf0_.sample();\n  return vMF<T>(mu, tau,pRndGen_);\n};\n\ntemplate<typename T>\nvMF<T> vMFpriorFull<T>::sampleFromPosterior(const vMF<T>& vmf)\n{\n  vMF<T> vmfPost (vmf);\n  vMF<T> vmfPostPrev (vmf);\n  T logPost = -FLT_MAX;\n  T logPostPrev = logPost;\n  // Gibbs sampler for concentration and mean\n  for(uint32_t j=0;j<10; ++j)\n  {\n    // posterior concentration prior parameters\n    const T a = a0_ + count_;\n    const T b = b0_ + vmfPost.mu().transpose()*xSum_;\n//    cout<<\"vMFpriorFull::sampleFromPosterior: a=\"<<a<<\" b=\"<<b<<endl;\n    // sample concentration form this posterior\n    const T tau = sampleConcentration(a,b);\n//    cout<<\"vMFpriorFull::sampleFromPosterior: tau=\"<<tau<<endl;\n    // posterior mean (m_N) and concentration (t_N) for vMF\n    Matrix<T,Dynamic,1> m_N = vmf0_.tau()*vmf0_.mu() + tau*xSum_;\n    T t_N = m_N.norm();\n    m_N /= t_N;\n//    cout<<\"vMFpriorFull::sampleFromPosterior: t_N=\"<<t_N<<\" m_N=\"<<m_N.transpose()<<endl;\n    // sample mean mu from posterior vMF\n    Matrix<T,Dynamic,1> mu = vMF<T>(m_N,t_N, pRndGen_).sample();\n//    cout<<\"vMFpriorFull::sampleFromPosterior: mu=\"<<mu.transpose()<<endl;\n    logPost = (tau*b + tau*mu.transpose()*xSum_ + vmf0_.tau()*vmf0_.mu().transpose()*mu);\n    cout<<\"@\"<<j<<\" cost \"<<logPost<<\" \"<<(logPost - logPostPrev)<<endl;\n    // return sampled posterior vMF\n    vmfPost = vMF<T>(mu, tau, pRndGen_);\n//    if((logPost - logPostPrev)<0. ) break;\n    logPostPrev = logPost;\n    vmfPostPrev = vmfPost;\n  }\n  return vmfPostPrev;\n};\n\n\ntemplate<typename T>\nT vMFpriorFull<T>::concentrationLogPdf(const T tau, const T a, const T b) const\n{\n  // modified bessel function of the first kind\n  // http://www.boost.org/doc/libs/1_35_0/libs/math/doc/sf_and_dist/html/math_toolkit/special/bessel/mbessel.html\n  const T DD = static_cast<T>(D_);\n//  cout<<\"vMFpriorFull:: bessel: D=\"<<DD<<\" \"<<(DD/2.-1.)<<\" tau=\"<<tau<<endl;\n  return a*((DD/2. -1.)*log(tau) \n    - (DD/2.)*log(2.*M_PI) \n    - logBesselI(DD/2. -1.,tau))\n    + tau*b;\n};\n\ntemplate<typename T>\nT vMFpriorFull<T>::sampleConcentration(const T a, const T b, const T TT)\n{\n  // slice sampler for concentration paramter tau\n  const T w = 0.1;  // width for expansions of search region\n  T tau = 0.11;      // arbitrary starting point\n  for(int32_t t=0; t<TT; ++t)\n  {\n    const T yMax = concentrationLogPdf(tau,a,b);\n    const T y = log(unif_(*pRndGen_)) + yMax; \n//    cout<<\"vMFpriorFull::sampleConcentration: yMax=\"<<yMax<<\" y=\"<<y<<endl;\n    T tauMin = tau-w; \n    T tauMax = tau+w; \n    while (tauMin >=0. && concentrationLogPdf(tauMin,a,b) >= y) tauMin -= w;\n    tauMin = max(0.0,tauMin); \n    while (concentrationLogPdf(tauMax,a,b) >= y) tauMax += w;\n    while(42){\n      T tauNew = unif_(*pRndGen_)*(tauMax-tauMin)+tauMin;\n//      cout<<\"vMFpriorFull::sampleConcentration: \"<<tauNew<<\" min: \"<<tauMin<<\" max: \"<<tauMax<<\" a=\"<<a<<\" b=\"<<b<<endl;\n      if(concentrationLogPdf(tauNew,a,b) >= y)\n      {\n        tau = tauNew; break;\n      }else{\n        if (tauNew < tau) tauMin = tauNew; else tauMax = tauNew;\n      }\n    };\n  }\n  return tau;\n};\n", "meta": {"hexsha": "43868fcaa83cb87b3b4db2a36f16d451992c8b1e", "size": 6983, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/dpMM/vmfPriorFull.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/vmfPriorFull.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/vmfPriorFull.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": 30.3608695652, "max_line_length": 122, "alphanum_fraction": 0.6517256194, "num_tokens": 2215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324893519999, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4769934704638285}}
{"text": "#include \"random_generator.hpp\"\n#include <memory>\n#include <time.h>\n#include <cmath>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <boost/random/uniform_real.hpp>\n#include <boost/random/uniform_int.hpp>\n\nRandomGenerator* RandomGenerator::instance = 0;\n\nRandomGenerator* RandomGenerator::getInstance() {\n  if (instance == 0) {\n      instance = new RandomGenerator();\n  }\n\n  return instance;\n}\n\nRandomGenerator::RandomGenerator() {\n  //pGenerator_ = std::make_shared<\n  //  boost::variate_generator<boost::mt19937, boost::normal_distribution<>>\n  //  >( boost::mt19937(time(0)), boost::normal_distribution<>() )\n  //;\n\n  pGenerator_ = std::make_shared<\n    boost::variate_generator<boost::mt19937, boost::uniform_real<>>\n    >( boost::mt19937(time(0)), boost::uniform_real<>(0,1) )\n  ;\n\n  pIntGenerator_ = std::make_shared<\n    boost::variate_generator<boost::mt19937, boost::uniform_int<>>\n    >( boost::mt19937(time(0)), boost::uniform_int<>(0, 999999) )\n    //>( boost::mt19937(time(0)), boost::uniform_int<>(0, 99) )\n  ;\n}\n\nint RandomGenerator::getInt() {\n  return (*pIntGenerator_)();\n}\n\nint RandomGenerator::getMaxInt() {\n  return pIntGenerator_->max();\n}\n\ndouble RandomGenerator::getDouble() {\n  return (*pGenerator_)();\n}\n\ndouble RandomGenerator::getMaxDouble() {\n  return pGenerator_->max();\n}\n", "meta": {"hexsha": "f169076e5d556937dac8b59dbce9b4ae973f3b1d", "size": 1403, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/random_generator.cpp", "max_stars_repo_name": "kfsun/genetic-algorithm-tsp", "max_stars_repo_head_hexsha": "457e52164bcfd59b26e6ebd958a959c8ddfbf1f5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/random_generator.cpp", "max_issues_repo_name": "kfsun/genetic-algorithm-tsp", "max_issues_repo_head_hexsha": "457e52164bcfd59b26e6ebd958a959c8ddfbf1f5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/random_generator.cpp", "max_forks_repo_name": "kfsun/genetic-algorithm-tsp", "max_forks_repo_head_hexsha": "457e52164bcfd59b26e6ebd958a959c8ddfbf1f5", "max_forks_repo_licenses": ["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.9814814815, "max_line_length": 76, "alphanum_fraction": 0.7042052744, "num_tokens": 366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6224593382055109, "lm_q1q2_score": 0.47698663394637647}}
{"text": "/* boost random/uniform_smallint.hpp header file\r\n *\r\n * Copyright Jens Maurer 2000-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 most recent version including documentation.\r\n *\r\n * $Id: uniform_smallint.hpp 60755 2010-03-22 00:45:06Z steven_watanabe $\r\n *\r\n * Revision history\r\n *  2001-04-08  added min<max assertion (N. Becker)\r\n *  2001-02-18  moved to individual header files\r\n */\r\n\r\n#ifndef BOOST_RANDOM_UNIFORM_SMALLINT_HPP\r\n#define BOOST_RANDOM_UNIFORM_SMALLINT_HPP\r\n\r\n#include <cassert>\r\n#include <iostream>\r\n#include <boost/config.hpp>\r\n#include <boost/limits.hpp>\r\n#include <boost/static_assert.hpp>\r\n#include <boost/random/detail/config.hpp>\r\n#include <boost/random/uniform_01.hpp>\r\n#include <boost/detail/workaround.hpp>\r\n\r\nnamespace boost {\r\n\r\n// uniform integer distribution on a small range [min, max]\r\n\r\n/**\r\n * The distribution function uniform_smallint models a \\random_distribution.\r\n * On each invocation, it returns a random integer value uniformly distributed\r\n * in the set of integer numbers {min, min+1, min+2, ..., max}. It assumes\r\n * that the desired range (max-min+1) is small compared to the range of the\r\n * underlying source of random numbers and thus makes no attempt to limit\r\n * quantization errors.\r\n *\r\n * Let r<sub>out</sub>=(max-min+1) the desired range of integer numbers, and\r\n * let r<sub>base</sub> be the range of the underlying source of random\r\n * numbers. Then, for the uniform distribution, the theoretical probability\r\n * for any number i in the range r<sub>out</sub> will be p<sub>out</sub>(i) =\r\n * 1/r<sub>out</sub>. Likewise, assume a uniform distribution on r<sub>base</sub> for\r\n * the underlying source of random numbers, i.e. p<sub>base</sub>(i) =\r\n * 1/r<sub>base</sub>. Let p<sub>out_s</sub>(i) denote the random\r\n * distribution generated by @c uniform_smallint. Then the sum over all\r\n * i in r<sub>out</sub> of (p<sub>out_s</sub>(i)/p<sub>out</sub>(i) - 1)<sup>2</sup>\r\n * shall not exceed r<sub>out</sub>/r<sub>base</sub><sup>2</sup>\r\n * (r<sub>base</sub> mod r<sub>out</sub>)(r<sub>out</sub> -\r\n * r<sub>base</sub> mod r<sub>out</sub>).\r\n *\r\n * The template parameter IntType shall denote an integer-like value type.\r\n *\r\n * Note: The property above is the square sum of the relative differences\r\n * in probabilities between the desired uniform distribution\r\n * p<sub>out</sub>(i) and the generated distribution p<sub>out_s</sub>(i).\r\n * The property can be fulfilled with the calculation\r\n * (base_rng mod r<sub>out</sub>), as follows: Let r = r<sub>base</sub> mod\r\n * r<sub>out</sub>. The base distribution on r<sub>base</sub> is folded onto the\r\n * range r<sub>out</sub>. The numbers i < r have assigned (r<sub>base</sub>\r\n * div r<sub>out</sub>)+1 numbers of the base distribution, the rest has\r\n * only (r<sub>base</sub> div r<sub>out</sub>). Therefore,\r\n * p<sub>out_s</sub>(i) = ((r<sub>base</sub> div r<sub>out</sub>)+1) /\r\n * r<sub>base</sub> for i < r and p<sub>out_s</sub>(i) = (r<sub>base</sub>\r\n * div r<sub>out</sub>)/r<sub>base</sub> otherwise. Substituting this in the\r\n * above sum formula leads to the desired result.\r\n *\r\n * Note: The upper bound for (r<sub>base</sub> mod r<sub>out</sub>)\r\n * (r<sub>out</sub> - r<sub>base</sub> mod r<sub>out</sub>) is\r\n * r<sub>out</sub><sup>2</sup>/4.  Regarding the upper bound for the\r\n * square sum of the relative quantization error of\r\n * r<sub>out</sub><sup>3</sup>/(4*r<sub>base</sub><sup>2</sup>), it\r\n * seems wise to either choose r<sub>base</sub> so that r<sub>base</sub> >\r\n * 10*r<sub>out</sub><sup>2</sup> or ensure that r<sub>base</sub> is\r\n * divisible by r<sub>out</sub>.\r\n */\r\ntemplate<class IntType = int>\r\nclass uniform_smallint\r\n{\r\npublic:\r\n  typedef IntType input_type;\r\n  typedef IntType result_type;\r\n\r\n  /**\r\n   * Constructs a @c uniform_smallint. @c min and @c max are the\r\n   * lower and upper bounds of the output range, respectively.\r\n   */\r\n  explicit uniform_smallint(IntType min_arg = 0, IntType max_arg = 9)\r\n    : _min(min_arg), _max(max_arg)\r\n  {\r\n#ifndef BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS\r\n    // MSVC fails BOOST_STATIC_ASSERT with std::numeric_limits at class scope\r\n    BOOST_STATIC_ASSERT(std::numeric_limits<IntType>::is_integer);\r\n#endif\r\n }\r\n\r\n  result_type min BOOST_PREVENT_MACRO_SUBSTITUTION () const { return _min; }\r\n  result_type max BOOST_PREVENT_MACRO_SUBSTITUTION () const { return _max; }\r\n  void reset() { }\r\n\r\n  template<class Engine>\r\n  result_type operator()(Engine& eng)\r\n  {\r\n    typedef typename Engine::result_type base_result;\r\n    base_result _range = static_cast<base_result>(_max-_min)+1;\r\n    base_result _factor = 1;\r\n    \r\n    // LCGs get bad when only taking the low bits.\r\n    // (probably put this logic into a partial template specialization)\r\n    // Check how many low bits we can ignore before we get too much\r\n    // quantization error.\r\n    base_result r_base = (eng.max)() - (eng.min)();\r\n    if(r_base == (std::numeric_limits<base_result>::max)()) {\r\n      _factor = 2;\r\n      r_base /= 2;\r\n    }\r\n    r_base += 1;\r\n    if(r_base % _range == 0) {\r\n      // No quantization effects, good\r\n      _factor = r_base / _range;\r\n    } else {\r\n      // carefully avoid overflow; pessimizing here\r\n      for( ; r_base/_range/32 >= _range; _factor *= 2)\r\n        r_base /= 2;\r\n    }\r\n\r\n    return static_cast<result_type>(((eng() - (eng.min)()) / _factor) % _range + _min);\r\n  }\r\n\r\n#ifndef BOOST_RANDOM_NO_STREAM_OPERATORS\r\n  template<class CharT, class Traits>\r\n  friend std::basic_ostream<CharT,Traits>&\r\n  operator<<(std::basic_ostream<CharT,Traits>& os, const uniform_smallint& ud)\r\n  {\r\n    os << ud._min << \" \" << ud._max;\r\n    return os;\r\n  }\r\n\r\n  template<class CharT, class Traits>\r\n  friend std::basic_istream<CharT,Traits>&\r\n  operator>>(std::basic_istream<CharT,Traits>& is, uniform_smallint& ud)\r\n  {\r\n    is >> std::ws >> ud._min >> std::ws >> ud._max;\r\n    return is;\r\n  }\r\n#endif\r\n\r\nprivate:\r\n\r\n  result_type _min;\r\n  result_type _max;\r\n};\r\n\r\n} // namespace boost\r\n\r\n#endif // BOOST_RANDOM_UNIFORM_SMALLINT_HPP\r\n", "meta": {"hexsha": "93c7b63dc4fadc9b737510d16f653cb53191642f", "size": 6178, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Compiler/boost/boost/random/uniform_smallint.hpp", "max_stars_repo_name": "davidov541/MiniC", "max_stars_repo_head_hexsha": "d3b16a1568b97a4d801880b110a8be04fe848adb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 33.0, "max_stars_repo_stars_event_min_datetime": "2015-04-15T16:58:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-06T13:58:14.000Z", "max_issues_repo_path": "LibsExternes/Includes/boost/random/uniform_smallint.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": 3.0, "max_issues_repo_issues_event_min_datetime": "2015-04-15T17:11:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-08T14:08:52.000Z", "max_forks_repo_path": "LibsExternes/Includes/boost/random/uniform_smallint.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": 6.0, "max_forks_repo_forks_event_min_datetime": "2015-05-07T14:41:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-27T12:19:58.000Z", "avg_line_length": 38.8553459119, "max_line_length": 88, "alphanum_fraction": 0.6765943671, "num_tokens": 1773, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.6224593452091673, "lm_q1q2_score": 0.4769866326688173}}
{"text": "#include <boost/test/unit_test.hpp>\n#include <gmp.h>\n\n#include \"runtime/header.h\"\n\nextern \"C\" {\nmpz_ptr hook_INT_tmod(mpz_t, mpz_t);\nmpz_ptr hook_INT_emod(mpz_t, mpz_t);\nmpz_ptr hook_INT_add(mpz_t, mpz_t);\nmpz_ptr hook_INT_and(mpz_t, mpz_t);\nmpz_ptr hook_INT_mul(mpz_t, mpz_t);\nmpz_ptr hook_INT_sub(mpz_t, mpz_t);\nmpz_ptr hook_INT_tdiv(mpz_t, mpz_t);\nmpz_ptr hook_INT_ediv(mpz_t, mpz_t);\nmpz_ptr hook_INT_shl(mpz_t, mpz_t);\nmpz_ptr hook_INT_shr(mpz_t, mpz_t);\nmpz_ptr hook_INT_pow(mpz_t, mpz_t);\nmpz_ptr hook_INT_xor(mpz_t, mpz_t);\nmpz_ptr hook_INT_or(mpz_t, mpz_t);\nmpz_ptr hook_INT_max(mpz_t, mpz_t);\nmpz_ptr hook_INT_min(mpz_t, mpz_t);\nmpz_ptr hook_INT_powmod(mpz_t, mpz_t, mpz_t);\nmpz_ptr hook_INT_bitRange(mpz_t, mpz_t, mpz_t);\nmpz_ptr hook_INT_signExtendBitRange(mpz_t, mpz_t, mpz_t);\nmpz_ptr hook_INT_not(mpz_t);\nmpz_ptr hook_INT_abs(mpz_t);\nmpz_ptr hook_INT_log2(mpz_t);\nmpz_ptr hook_INT_rand(mpz_t);\nbool hook_INT_le(mpz_t, mpz_t);\nbool hook_INT_lt(mpz_t, mpz_t);\nbool hook_INT_eq(mpz_t, mpz_t);\nbool hook_INT_ne(mpz_t, mpz_t);\nbool hook_INT_ge(mpz_t, mpz_t);\nbool hook_INT_gt(mpz_t, mpz_t);\nblock *hook_INT_srand(mpz_t);\n\nmpz_ptr move_int(mpz_t i) {\n  mpz_ptr result = (mpz_ptr)malloc(sizeof(__mpz_struct));\n  *result = *i;\n  return result;\n}\n\nvoid add_hash64(void *, uint64_t) { }\n\nuint32_t getTagForSymbolName(const char *) {\n  return 0;\n}\n\nvoid *koreAllocAlwaysGC(size_t size) {\n  return malloc(size);\n}\n}\n\nBOOST_AUTO_TEST_SUITE(IntTest)\n\nBOOST_AUTO_TEST_CASE(tmod) {\n  mpz_t a, b;\n  mpz_ptr result;\n  mpz_init_set_ui(a, 7);\n  mpz_init_set_ui(b, 3);\n  result = hook_INT_tmod(a, b);\n  BOOST_CHECK_EQUAL(mpz_cmp_ui(result, 1), 0);\n  mpz_set_si(a, -7);\n  mpz_clear(result);\n  free(result);\n  result = hook_INT_tmod(a, b);\n  BOOST_CHECK_EQUAL(mpz_cmp_si(result, -1), 0);\n  mpz_clear(result);\n  free(result);\n  mpz_set_si(b, 0);\n  BOOST_CHECK_THROW(hook_INT_tmod(a, b), std::invalid_argument);\n  mpz_clear(a);\n  mpz_clear(b);\n}\n\nBOOST_AUTO_TEST_CASE(emod) {\n  mpz_t a, b;\n  mpz_ptr result;\n  mpz_init_set_ui(a, 7);\n  mpz_init_set_ui(b, 3);\n  result = hook_INT_emod(a, b);\n  BOOST_CHECK_EQUAL(mpz_cmp_ui(result, 1), 0);\n  mpz_set_si(a, -7);\n  mpz_clear(result);\n  free(result);\n  result = hook_INT_emod(a, b);\n  BOOST_CHECK_EQUAL(mpz_cmp_si(result, 2), 0);\n  mpz_clear(result);\n  free(result);\n  mpz_set_si(b, 0);\n  BOOST_CHECK_THROW(hook_INT_emod(a, b), std::invalid_argument);\n  mpz_clear(a);\n  mpz_clear(b);\n}\n\nBOOST_AUTO_TEST_CASE(add) {\n  mpz_t a, b;\n  mpz_ptr result;\n  mpz_init_set_ui(a, 7);\n  mpz_init_set_ui(b, 3);\n  result = hook_INT_add(a, b);\n  BOOST_CHECK_EQUAL(mpz_cmp_ui(result, 10), 0);\n  mpz_clear(result);\n  free(result);\n  mpz_clear(a);\n  mpz_clear(b);\n}\n\nBOOST_AUTO_TEST_CASE(le) {\n  mpz_t a, b;\n  bool result;\n  mpz_init_set_ui(a, 2);\n  mpz_init_set_ui(b, 3);\n  result = hook_INT_le(a, b);\n  BOOST_CHECK(result);\n  result = false;\n  mpz_set_si(a, 3);\n  result = hook_INT_le(a, b);\n  BOOST_CHECK(result);\n  mpz_clear(a);\n  mpz_clear(b);\n}\n\nBOOST_AUTO_TEST_CASE(eq) {\n  mpz_t a, b;\n  bool result;\n  mpz_init_set_ui(a, 2);\n  mpz_init_set_ui(b, 3);\n  result = hook_INT_eq(a, b);\n  BOOST_CHECK(!result);\n  result = false;\n  mpz_set_si(a, 3);\n  result = hook_INT_eq(a, b);\n  BOOST_CHECK(result);\n  mpz_clear(a);\n  mpz_clear(b);\n}\n\nBOOST_AUTO_TEST_CASE(ne) {\n  mpz_t a, b;\n  bool result;\n  mpz_init_set_ui(a, 2);\n  mpz_init_set_ui(b, 3);\n  result = hook_INT_ne(a, b);\n  BOOST_CHECK(result);\n  result = true;\n  mpz_set_si(a, 3);\n  result = hook_INT_ne(a, b);\n  BOOST_CHECK(!result);\n  mpz_clear(a);\n  mpz_clear(b);\n}\n\nBOOST_AUTO_TEST_CASE(bitwise_and) {\n  mpz_t a, b;\n  mpz_ptr result;\n  mpz_init_set_ui(a, 13);\n  mpz_init_set_ui(b, 3);\n  result = hook_INT_and(a, b);\n  BOOST_CHECK_EQUAL(mpz_cmp_ui(result, 1), 0);\n  mpz_clear(result);\n  free(result);\n  mpz_clear(a);\n  mpz_clear(b);\n}\n\nBOOST_AUTO_TEST_CASE(mul) {\n  mpz_t a, b;\n  mpz_ptr result;\n  mpz_init_set_ui(a, 7);\n  mpz_init_set_ui(b, 3);\n  result = hook_INT_mul(a, b);\n  BOOST_CHECK_EQUAL(mpz_cmp_ui(result, 21), 0);\n  mpz_clear(result);\n  free(result);\n  mpz_clear(a);\n  mpz_clear(b);\n}\n\nBOOST_AUTO_TEST_CASE(sub) {\n  mpz_t a, b;\n  mpz_ptr result;\n  mpz_init_set_ui(a, 7);\n  mpz_init_set_ui(b, 3);\n  result = hook_INT_sub(a, b);\n  BOOST_CHECK_EQUAL(mpz_cmp_ui(result, 4), 0);\n  mpz_clear(result);\n  free(result);\n  mpz_clear(a);\n  mpz_clear(b);\n}\n\nBOOST_AUTO_TEST_CASE(tdiv) {\n  mpz_t a, b;\n  mpz_ptr result;\n  mpz_init_set_ui(a, 7);\n  mpz_init_set_ui(b, 3);\n  result = hook_INT_tdiv(a, b);\n  BOOST_CHECK_EQUAL(mpz_cmp_ui(result, 2), 0);\n  mpz_set_si(b, -3);\n  mpz_clear(result);\n  free(result);\n  result = hook_INT_tdiv(a, b);\n  BOOST_CHECK_EQUAL(mpz_cmp_si(result, -2), 0);\n  mpz_clear(result);\n  free(result);\n  mpz_set_si(b, 0);\n  BOOST_CHECK_THROW(hook_INT_tdiv(a, b), std::invalid_argument);\n  mpz_clear(a);\n  mpz_clear(b);\n}\n\nBOOST_AUTO_TEST_CASE(ediv) {\n  mpz_t a, b;\n  mpz_ptr result;\n  mpz_init_set_ui(a, 7);\n  mpz_init_set_ui(b, 3);\n  result = hook_INT_ediv(a, b);\n  BOOST_CHECK_EQUAL(mpz_cmp_ui(result, 2), 0);\n  mpz_set_si(a, -7);\n  mpz_set_si(b, -3);\n  mpz_clear(result);\n  free(result);\n  result = hook_INT_ediv(a, b);\n  BOOST_CHECK_EQUAL(mpz_cmp_si(result, 3), 0);\n  mpz_clear(result);\n  free(result);\n  mpz_set_si(b, 0);\n  BOOST_CHECK_THROW(hook_INT_ediv(a, b), std::invalid_argument);\n  mpz_clear(a);\n  mpz_clear(b);\n}\n\nBOOST_AUTO_TEST_CASE(shl) {\n  mpz_t a, b;\n  mpz_ptr result;\n  mpz_init_set_ui(a, 7);\n  mpz_init_set_ui(b, 3);\n  result = hook_INT_shl(a, b);\n  BOOST_CHECK_EQUAL(mpz_cmp_ui(result, 56), 0);\n  mpz_set_si(b, -3);\n  mpz_clear(result);\n  free(result);\n  BOOST_CHECK_THROW(hook_INT_shl(a, b), std::invalid_argument);\n  mpz_clear(a);\n  mpz_clear(b);\n}\n\nBOOST_AUTO_TEST_CASE(lt) {\n  mpz_t a, b;\n  bool result;\n  mpz_init_set_ui(a, 2);\n  mpz_init_set_ui(b, 3);\n  result = hook_INT_lt(a, b);\n  BOOST_CHECK(result);\n  result = true;\n  mpz_set_si(a, 3);\n  result = hook_INT_lt(a, b);\n  BOOST_CHECK(!result);\n  mpz_clear(a);\n  mpz_clear(b);\n}\n\nBOOST_AUTO_TEST_CASE(ge) {\n  mpz_t a, b;\n  bool result;\n  mpz_init_set_ui(a, 4);\n  mpz_init_set_ui(b, 3);\n  result = hook_INT_ge(a, b);\n  BOOST_CHECK(result);\n  result = false;\n  mpz_set_si(a, 3);\n  result = hook_INT_ge(a, b);\n  BOOST_CHECK(result);\n  mpz_clear(a);\n  mpz_clear(b);\n}\n\nBOOST_AUTO_TEST_CASE(shr) {\n  mpz_t a, b;\n  mpz_ptr result;\n  mpz_init_set_ui(a, 21);\n  mpz_init_set_ui(b, 3);\n  result = hook_INT_shr(a, b);\n  BOOST_CHECK_EQUAL(mpz_cmp_ui(result, 2), 0);\n  mpz_set_si(b, -3);\n  mpz_clear(result);\n  free(result);\n  BOOST_CHECK_THROW(hook_INT_shr(a, b), std::invalid_argument);\n  mpz_set_ui(b, 1);\n  mpz_mul_2exp(b, b, 64);\n  result = hook_INT_shr(a, b);\n  BOOST_CHECK_EQUAL(mpz_cmp_ui(result, 0), 0);\n  mpz_clear(result);\n  free(result);\n  mpz_set_si(a, -21);\n  result = hook_INT_shr(a, b);\n  BOOST_CHECK_EQUAL(mpz_cmp_si(result, -1), 0);\n  mpz_clear(result);\n  free(result);\n  mpz_clear(a);\n  mpz_clear(b);\n}\n\nBOOST_AUTO_TEST_CASE(gt) {\n  mpz_t a, b;\n  bool result;\n  mpz_init_set_ui(a, 4);\n  mpz_init_set_ui(b, 3);\n  result = hook_INT_gt(a, b);\n  BOOST_CHECK(result);\n  result = true;\n  mpz_set_si(a, 3);\n  result = hook_INT_gt(a, b);\n  BOOST_CHECK(!result);\n  mpz_clear(a);\n  mpz_clear(b);\n}\n\nBOOST_AUTO_TEST_CASE(pow) {\n  mpz_t a, b;\n  mpz_ptr result;\n  mpz_init_set_ui(a, 7);\n  mpz_init_set_ui(b, 3);\n  result = hook_INT_pow(a, b);\n  BOOST_CHECK_EQUAL(mpz_cmp_ui(result, 343), 0);\n  mpz_set_si(b, -3);\n  mpz_clear(result);\n  free(result);\n  BOOST_CHECK_THROW(hook_INT_pow(a, b), std::invalid_argument);\n  mpz_clear(a);\n  mpz_clear(b);\n}\n\nBOOST_AUTO_TEST_CASE(powmod) {\n  mpz_t a, b, mod;\n  mpz_ptr result;\n  mpz_init_set_ui(a, 5);\n  mpz_init_set_ui(b, 2);\n  mpz_init_set_ui(mod, 3);\n  result = hook_INT_powmod(a, b, mod);\n  BOOST_CHECK_EQUAL(mpz_cmp_ui(result, 1), 0);\n  mpz_set_si(b, -3);\n  mpz_clear(result);\n  free(result);\n  result = hook_INT_powmod(a, b, mod);\n  BOOST_CHECK_EQUAL(mpz_cmp_ui(result, 2), 0);\n  mpz_clear(result);\n  free(result);\n  mpz_set_si(mod, 5);\n  BOOST_CHECK_THROW(hook_INT_powmod(a, b, mod), std::invalid_argument);\n  mpz_clear(a);\n  mpz_clear(b);\n}\n\nBOOST_AUTO_TEST_CASE(bitwise_xor) {\n  mpz_t a, b;\n  mpz_ptr result;\n  mpz_init_set_ui(a, 13);\n  mpz_init_set_ui(b, 3);\n  result = hook_INT_xor(a, b);\n  BOOST_CHECK_EQUAL(mpz_cmp_ui(result, 14), 0);\n  mpz_clear(result);\n  free(result);\n  mpz_clear(a);\n  mpz_clear(b);\n}\n\nBOOST_AUTO_TEST_CASE(bitwise_or) {\n  mpz_t a, b;\n  mpz_ptr result;\n  mpz_init_set_ui(a, 13);\n  mpz_init_set_ui(b, 3);\n  result = hook_INT_or(a, b);\n  BOOST_CHECK_EQUAL(mpz_cmp_ui(result, 15), 0);\n  mpz_clear(result);\n  free(result);\n  mpz_clear(a);\n  mpz_clear(b);\n}\n\nBOOST_AUTO_TEST_CASE(bitwise_not) {\n  mpz_t a;\n  mpz_ptr result;\n  mpz_init_set_ui(a, 7);\n  result = hook_INT_not(a);\n  BOOST_CHECK_EQUAL(mpz_cmp_si(result, -8), 0);\n  mpz_clear(result);\n  free(result);\n  mpz_clear(a);\n}\n\nBOOST_AUTO_TEST_CASE(abs) {\n  mpz_t a;\n  mpz_ptr result;\n  mpz_init_set_si(a, -7);\n  result = hook_INT_abs(a);\n  BOOST_CHECK_EQUAL(mpz_cmp_si(result, 7), 0);\n  mpz_clear(result);\n  free(result);\n  mpz_clear(a);\n}\n\nBOOST_AUTO_TEST_CASE(max) {\n  mpz_t a, b;\n  mpz_ptr result;\n  mpz_init_set_ui(a, 2);\n  mpz_init_set_ui(b, 3);\n  result = hook_INT_max(a, b);\n  BOOST_CHECK_EQUAL(mpz_cmp_ui(result, 3), 0);\n  mpz_clear(result);\n  free(result);\n  mpz_set_si(b, 2);\n  result = hook_INT_max(a, b);\n  BOOST_CHECK_EQUAL(mpz_cmp_ui(result, 2), 0);\n  mpz_clear(result);\n  free(result);\n  mpz_clear(a);\n  mpz_clear(b);\n}\n\nBOOST_AUTO_TEST_CASE(min) {\n  mpz_t a, b;\n  mpz_ptr result;\n  mpz_init_set_ui(a, 2);\n  mpz_init_set_ui(b, 3);\n  result = hook_INT_min(a, b);\n  BOOST_CHECK_EQUAL(mpz_cmp_ui(result, 2), 0);\n  mpz_clear(result);\n  free(result);\n  mpz_set_si(a, 3);\n  result = hook_INT_min(a, b);\n  BOOST_CHECK_EQUAL(mpz_cmp_ui(result, 3), 0);\n  mpz_clear(result);\n  free(result);\n  mpz_clear(a);\n  mpz_clear(b);\n}\n\nBOOST_AUTO_TEST_CASE(log2) {\n  mpz_t a;\n  mpz_ptr result;\n  mpz_init_set_ui(a, 0);\n  BOOST_CHECK_THROW(hook_INT_log2(a), std::invalid_argument);\n  mpz_set_ui(a, 256);\n  result = hook_INT_log2(a);\n  BOOST_CHECK_EQUAL(mpz_cmp_ui(result, 8), 0);\n  mpz_set_ui(a, 255);\n  mpz_clear(result);\n  free(result);\n  result = hook_INT_log2(a);\n  BOOST_CHECK_EQUAL(mpz_cmp_ui(result, 7), 0);\n  mpz_clear(result);\n  free(result);\n  mpz_clear(a);\n}\n\nBOOST_AUTO_TEST_CASE(bitRange) {\n  mpz_t i, off, len;\n  mpz_ptr result;\n  mpz_init_set_ui(i, 127);\n  mpz_init_set_ui(off, 0);\n  mpz_init_set_ui(len, 8);\n  result = hook_INT_bitRange(i, off, len);\n  BOOST_CHECK_EQUAL(mpz_cmp_ui(result, 127), 0);\n  mpz_clear(result);\n  free(result);\n  mpz_set_ui(i, 255);\n  result = hook_INT_bitRange(i, off, len);\n  BOOST_CHECK_EQUAL(mpz_cmp_ui(result, 255), 0);\n  mpz_clear(result);\n  free(result);\n  mpz_set_ui(i, 128);\n  mpz_set_ui(off, 1);\n  mpz_set_ui(len, 7);\n  result = hook_INT_bitRange(i, off, len);\n  BOOST_CHECK_EQUAL(mpz_cmp_ui(result, 64), 0);\n  mpz_clear(result);\n  free(result);\n  mpz_set_ui(i, 129);\n  mpz_set_ui(len, 5);\n  result = hook_INT_bitRange(i, off, len);\n  BOOST_CHECK_EQUAL(mpz_cmp_ui(result, 0), 0);\n  mpz_clear(result);\n  free(result);\n  mpz_set_ui(i, 1);\n  mpz_mul_2exp(i, i, 256);\n  mpz_sub_ui(i, i, 1);\n  mpz_set_ui(off, 1);\n  mpz_mul_2exp(off, off, 64);\n  mpz_set_ui(len, 1);\n  result = hook_INT_bitRange(i, off, len);\n  BOOST_CHECK_EQUAL(mpz_cmp_ui(result, 0), 0);\n  mpz_clear(result);\n  free(result);\n  mpz_set_ui(i, 128);\n  mpz_set_ui(off, 0);\n  mpz_set_ui(len, 0);\n  result = hook_INT_bitRange(i, off, len);\n  BOOST_CHECK_EQUAL(mpz_cmp_ui(result, 0), 0);\n  mpz_clear(result);\n  free(result);\n  mpz_set_si(len, -1);\n  BOOST_CHECK_THROW(hook_INT_bitRange(i, off, len), std::invalid_argument);\n  mpz_set_ui(len, 8);\n  mpz_set_si(off, -1);\n  BOOST_CHECK_THROW(hook_INT_bitRange(i, off, len), std::invalid_argument);\n  mpz_set_ui(off, 1);\n  mpz_mul_2exp(off, off, 64);\n  result = hook_INT_bitRange(i, off, len);\n  BOOST_CHECK_EQUAL(mpz_cmp_ui(result, 0), 0);\n  mpz_clear(result);\n  free(result);\n  mpz_set_si(i, -128);\n  result = hook_INT_bitRange(i, off, len);\n  BOOST_CHECK_EQUAL(mpz_cmp_ui(result, 255), 0);\n  mpz_clear(result);\n  free(result);\n  mpz_set_ui(i, 0x8040201008040201);\n  mpz_set_ui(off, 256);\n  mpz_set_ui(len, 8);\n  result = hook_INT_bitRange(i, off, len);\n  BOOST_CHECK_EQUAL(mpz_cmp_ui(result, 0), 0);\n  mpz_clear(result);\n  free(result);\n  mpz_set_str(\n      i,\n      \"-71056704293871788966541103783220878172235088814392126358492723927577357\"\n      \"355120458894410533635294234972718488758941394468447352968280152612380545\"\n      \"3895275517072855048781056\",\n      10);\n  mpz_set_ui(off, 32);\n  mpz_set_ui(len, 8);\n  result = hook_INT_bitRange(i, off, len);\n  BOOST_CHECK_EQUAL(mpz_cmp_ui(result, 12), 0);\n  mpz_clear(result);\n  free(result);\n  mpz_set_str(\n      i,\n      \"697754608693466068295273213726275558775348389513141500672185545754018175\"\n      \"72291616476873517904722261084304426432566930777772989164244884679414200\"\n      \"0\",\n      10);\n  mpz_set_ui(off, 64);\n  mpz_set_ui(len, 8);\n  result = hook_INT_bitRange(i, off, len);\n  BOOST_CHECK_EQUAL(mpz_cmp_ui(result, 56), 0);\n  mpz_clear(result);\n  free(result);\n  mpz_clear(i);\n  mpz_clear(off);\n  mpz_clear(len);\n}\n\nBOOST_AUTO_TEST_CASE(signExtendBitRange) {\n  mpz_t i, off, len;\n  mpz_ptr result;\n  mpz_init_set_ui(i, 255);\n  mpz_init_set_ui(off, 0);\n  mpz_init_set_ui(len, 8);\n  result = hook_INT_signExtendBitRange(i, off, len);\n  BOOST_CHECK_EQUAL(mpz_cmp_si(result, -1), 0);\n  mpz_clear(result);\n  free(result);\n  mpz_set_ui(i, 127);\n  result = hook_INT_signExtendBitRange(i, off, len);\n  BOOST_CHECK_EQUAL(mpz_cmp_ui(result, 127), 0);\n  mpz_clear(result);\n  free(result);\n  mpz_set_ui(i, 128);\n  mpz_set_ui(off, 1);\n  mpz_set_ui(len, 7);\n  result = hook_INT_signExtendBitRange(i, off, len);\n  BOOST_CHECK_EQUAL(mpz_cmp_si(result, -64), 0);\n  mpz_clear(result);\n  free(result);\n  mpz_set_ui(i, 129);\n  mpz_set_ui(len, 5);\n  result = hook_INT_signExtendBitRange(i, off, len);\n  BOOST_CHECK_EQUAL(mpz_cmp_ui(result, 0), 0);\n  mpz_clear(result);\n  free(result);\n  mpz_set_ui(i, 1);\n  mpz_mul_2exp(i, i, 256);\n  mpz_sub_ui(i, i, 1);\n  mpz_set_ui(off, 1);\n  mpz_mul_2exp(off, off, 64);\n  mpz_set_ui(len, 1);\n  result = hook_INT_signExtendBitRange(i, off, len);\n  BOOST_CHECK_EQUAL(mpz_cmp_ui(result, -0), 0);\n  mpz_clear(result);\n  free(result);\n  mpz_set_ui(i, 128);\n  mpz_set_ui(off, 0);\n  mpz_set_ui(len, 0);\n  result = hook_INT_signExtendBitRange(i, off, len);\n  BOOST_CHECK_EQUAL(mpz_cmp_ui(result, 0), 0);\n  mpz_clear(result);\n  free(result);\n  mpz_set_si(len, -1);\n  BOOST_CHECK_THROW(\n      hook_INT_signExtendBitRange(i, off, len), std::invalid_argument);\n  mpz_set_ui(len, 8);\n  mpz_set_si(off, -1);\n  BOOST_CHECK_THROW(\n      hook_INT_signExtendBitRange(i, off, len), std::invalid_argument);\n  mpz_set_ui(off, 1);\n  mpz_mul_2exp(off, off, 64);\n  result = hook_INT_signExtendBitRange(i, off, len);\n  BOOST_CHECK_EQUAL(mpz_cmp_ui(result, 0), 0);\n  mpz_clear(result);\n  free(result);\n  mpz_set_si(i, -128);\n  result = hook_INT_signExtendBitRange(i, off, len);\n  BOOST_CHECK_EQUAL(mpz_cmp_si(result, -1), 0);\n  mpz_clear(result);\n  free(result);\n  mpz_clear(i);\n  mpz_clear(off);\n  mpz_clear(len);\n}\n\nBOOST_AUTO_TEST_CASE(rand) {\n  mpz_t seed;\n  mpz_init_set_ui(seed, 1);\n  mpz_t upperBound;\n  mpz_init_set_ui(upperBound, 100);\n  BOOST_CHECK_EQUAL((uintptr_t)hook_INT_srand(seed), 1);\n  mpz_ptr result = hook_INT_rand(upperBound);\n  BOOST_CHECK_EQUAL(mpz_cmp_ui(result, 59), 0);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "920a1543dbfd47e4961b45ac3331daf2ad166381", "size": 15414, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittests/runtime-arithmetic/inttest.cpp", "max_stars_repo_name": "Tarnyko/llvm-backend", "max_stars_repo_head_hexsha": "96a81b5909f925d286ceb64def3ff9b4bcc5a97e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2018-08-01T16:45:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-13T07:37:50.000Z", "max_issues_repo_path": "unittests/runtime-arithmetic/inttest.cpp", "max_issues_repo_name": "Tarnyko/llvm-backend", "max_issues_repo_head_hexsha": "96a81b5909f925d286ceb64def3ff9b4bcc5a97e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 165.0, "max_issues_repo_issues_event_min_datetime": "2018-07-26T19:55:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T16:39:32.000Z", "max_forks_repo_path": "unittests/runtime-arithmetic/inttest.cpp", "max_forks_repo_name": "runtimeverification/llvm-backend", "max_forks_repo_head_hexsha": "8243ca9e201f9be793b57ddfb54cc77043a14dd4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2018-08-18T06:00:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-13T00:19:46.000Z", "avg_line_length": 24.3123028391, "max_line_length": 80, "alphanum_fraction": 0.7015051252, "num_tokens": 5018, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859598, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.47698662857951923}}
{"text": "#include <vi/ea.h>\n\n#include <boost/lexical_cast.hpp>\n#include <boost/program_options.hpp>\n\n#include <cstdio>\n#include <iostream>\n#include <random>\n#include <string>\n\n// Merciful C++ gods, please absolve me of these sins\n\n#define BUILD_SYSTEM(PARENT_SELECTION, ADULT_SELECTION) \\\n    vi::ea::build_system( \\\n        std::default_random_engine{std::random_device{}()}, \\\n        vi::ea::dynamic_int_vector_creator{ \\\n            variables[\"L\"].as<unsigned>(), \\\n            variables[\"L\"].as<unsigned>(), \\\n            std::uniform_int_distribution<unsigned>{0U, variables[\"S\"].as<unsigned>() - 1U}}, \\\n        PARENT_SELECTION, \\\n        vi::ea::reproduction::sexual{ \\\n            variables[\"mutation_rate\"].as<double>(), \\\n            variables[\"crossover_rate\"].as<double>(), \\\n            variables[\"crossover_points\"].as<unsigned>()}, \\\n        ADULT_SELECTION, \\\n        variables[\"population_size\"].as<unsigned>(), \\\n        [=] (const auto& genotype) \\\n        { \\\n            unsigned collisions = 0; \\\n            const auto d_max = variables.count(\"local\") ? 0 : genotype.size() - 3; \\\n            for (int d = 0; d <= d_max; ++d) \\\n            { \\\n                collisions += evaluate_surprising_sequence_collisions(genotype, variables[\"S\"].as<unsigned>(), d); \\\n            } \\\n            return 1.0 / (1.0 + static_cast<double>(collisions)); \\\n        })\n\nnamespace po = boost::program_options;\npo::variables_map variables{};\n\nbool solution_found = false;\n\ntemplate <typename system_type>\nvoid run_system(system_type&& system)\n{\n    unsigned generation;\n    double fitness_mean, fitness_std_dev;\n    typename system_type::individual_type const* best_individual;\n\n    const auto early_stop = variables.count(\"stop\") > 0;\n\n    while (true)\n    {\n        std::tie(generation, fitness_mean, fitness_std_dev, best_individual) = system.stats();\n\n        std::printf(\"%d %f %f %f %s\\n\",\n                    generation,\n                    best_individual->fitness,\n                    fitness_mean,\n                    fitness_std_dev,\n                    boost::lexical_cast<std::string>(best_individual->genotype).c_str());\n\n        if (early_stop and best_individual->fitness == 1.0 or generation >= variables[\"generations\"].as<unsigned>())\n        {\n            break;\n        }\n\n        system.evolve();\n    }\n}\n\nstd::vector<bool> tags{};\n\nunsigned evaluate_surprising_sequence_collisions(\n    const std::vector<unsigned>& sentence, const unsigned s, const unsigned d)\n{\n    tags.resize(s * s);\n    std::fill(tags.begin(), tags.end(), false);\n\n    unsigned collisions = 0;\n\n    for (std::size_t i = 0; i != sentence.size() - d - 1; ++i)\n    {\n        const auto offset = s * sentence[i] + sentence[i + d + 1];\n        if (tags[offset])\n        {\n            ++collisions;\n        }\n        else\n        {\n            tags[offset] = true;\n        }\n    }\n\n    return collisions;\n}\n\nint main(int argc, char** argv)\n{\n    try\n    {\n        po::options_description description{\"Options\"};\n        description.add_options()\n            (\"L\", po::value<unsigned>()->default_value(40), \"Surprising string length\")\n            (\"S\", po::value<unsigned>()->default_value(40), \"Surprising string symbol set size\")\n            (\"adult_selection\", po::value<std::string>()->default_value(\"full\"), \"Adult selection (full/mixed/over)\")\n            (\"child_count\", po::value<unsigned>()->default_value(150), \"Child count used in mixed/over adult selection\")\n            (\"crossover_points\", po::value<unsigned>()->default_value(1), \"Crossover points\")\n            (\"crossover_rate\", po::value<double>()->default_value(1.0), \"Crossover rate\")\n            (\"epsilon\", po::value<double>()->default_value(0.1), \"Tournament probability of selecting random winner\")\n            (\"generations\", po::value<unsigned>()->default_value(1000), \"Generation count\")\n            (\"global\", \"Global surprising sequence\")\n            (\"group_size\", po::value<unsigned>()->default_value(10), \"Tournament group size\")\n            (\"local\", \"Local surprising sequence\")\n            (\"mutation_rate\", po::value<double>()->default_value(0.001), \"Mutation rate\")\n            (\"parent_selection\", po::value<std::string>()->default_value(\"proportionate\"), \"Parent selection (proportionate/rank/sigma/tournament)\")\n            (\"population_size\", po::value<unsigned>()->default_value(100), \"Population size\")\n            (\"rank_max\", po::value<double>()->default_value(1.5), \"Rank selection pressure ('max')\")\n            (\"stop\", \"Stop on first encountered solution\");\n\n        po::store(po::parse_command_line(argc, argv, description), variables);\n\n        if (variables.count(\"global\") == 0 and variables.count(\"local\") == 0)\n        {\n            std::cerr << \"error: use --global or --local switch\" << std::endl;\n            return EXIT_FAILURE;\n        }\n\n        const auto adult_selection  = variables[\"adult_selection\"].as<std::string>();\n        const auto parent_selection = variables[\"parent_selection\"].as<std::string>();\n\n        if (adult_selection == \"full\" and parent_selection == \"proportionate\")\n        {\n            run_system(BUILD_SYSTEM(\n                vi::ea::parent_selection::fitness_proportionate{},\n                vi::ea::adult_selection::full_generational_replacement{}));\n        }\n        else if (adult_selection == \"full\" and parent_selection == \"rank\")\n        {\n            run_system(BUILD_SYSTEM(\n                vi::ea::parent_selection::rank{variables[\"rank_max\"].as<double>()},\n                vi::ea::adult_selection::full_generational_replacement{}));\n        }\n        else if (adult_selection == \"full\" and parent_selection == \"sigma\")\n        {\n            run_system(BUILD_SYSTEM(\n                vi::ea::parent_selection::sigma{},\n                vi::ea::adult_selection::full_generational_replacement{}));\n        }\n        else if (adult_selection == \"full\" and parent_selection == \"tournament\")\n        {\n            auto parent_selection = vi::ea::parent_selection::tournament{\n                variables[\"group_size\"].as<unsigned>(),\n                variables[\"epsilon\"].as<double>()};\n\n            run_system(BUILD_SYSTEM(parent_selection, vi::ea::adult_selection::full_generational_replacement{}));\n        }\n        else if (adult_selection == \"mixed\" and parent_selection == \"proportionate\")\n        {\n            run_system(BUILD_SYSTEM(\n                vi::ea::parent_selection::fitness_proportionate{},\n                vi::ea::adult_selection::generational_mixing{variables[\"child_count\"].as<unsigned>()}));\n        }\n        else if (adult_selection == \"mixed\" and parent_selection == \"rank\")\n        {\n            run_system(BUILD_SYSTEM(\n                vi::ea::parent_selection::rank{variables[\"rank_max\"].as<double>()},\n                vi::ea::adult_selection::generational_mixing{variables[\"child_count\"].as<unsigned>()}));\n        }\n        else if (adult_selection == \"mixed\" and parent_selection == \"sigma\")\n        {\n            run_system(BUILD_SYSTEM(\n                vi::ea::parent_selection::sigma{},\n                vi::ea::adult_selection::generational_mixing{variables[\"child_count\"].as<unsigned>()}));\n        }\n        else if (adult_selection == \"mixed\" and parent_selection == \"tournament\")\n        {\n            auto parent_selection = vi::ea::parent_selection::tournament{\n                variables[\"group_size\"].as<unsigned>(),\n                variables[\"epsilon\"].as<double>()};\n\n            run_system(BUILD_SYSTEM(\n                parent_selection,\n                vi::ea::adult_selection::generational_mixing{variables[\"child_count\"].as<unsigned>()}));\n        }\n        else if (adult_selection == \"over\" and parent_selection == \"proportionate\")\n        {\n            run_system(BUILD_SYSTEM(\n                vi::ea::parent_selection::fitness_proportionate{},\n                vi::ea::adult_selection::overproduction{variables[\"child_count\"].as<unsigned>()}));\n        }\n        else if (adult_selection == \"over\" and parent_selection == \"rank\")\n        {\n            run_system(BUILD_SYSTEM(\n                vi::ea::parent_selection::rank{variables[\"rank_max\"].as<double>()},\n                vi::ea::adult_selection::overproduction{variables[\"child_count\"].as<unsigned>()}));\n        }\n        else if (adult_selection == \"over\" and parent_selection == \"sigma\")\n        {\n            run_system(BUILD_SYSTEM(\n                vi::ea::parent_selection::sigma{},\n                vi::ea::adult_selection::overproduction{variables[\"child_count\"].as<unsigned>()}));\n        }\n        else if (adult_selection == \"over\" and parent_selection == \"tournament\")\n        {\n            auto parent_selection = vi::ea::parent_selection::tournament{\n                variables[\"group_size\"].as<unsigned>(),\n                variables[\"epsilon\"].as<double>()};\n\n            run_system(BUILD_SYSTEM(\n                parent_selection,\n                vi::ea::adult_selection::overproduction{variables[\"child_count\"].as<unsigned>()}));\n        }\n    }\n    catch (const po::error& error)\n    {\n        std::cerr << \"error: \" << error.what() << std::endl;\n        return EXIT_FAILURE;\n    }\n\n    return solution_found ? 1 : 0;\n}\n\n", "meta": {"hexsha": "24e809512d3c1e3f5c9214270eaedf3015b58904", "size": 9171, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "project_2/program/surprising.cpp", "max_stars_repo_name": "pveierland/permve-ntnu-it3708", "max_stars_repo_head_hexsha": "1066d5c1af5c953dbaf129d7e05ce32f2d4292aa", "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": "project_2/program/surprising.cpp", "max_issues_repo_name": "pveierland/permve-ntnu-it3708", "max_issues_repo_head_hexsha": "1066d5c1af5c953dbaf129d7e05ce32f2d4292aa", "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": "project_2/program/surprising.cpp", "max_forks_repo_name": "pveierland/permve-ntnu-it3708", "max_forks_repo_head_hexsha": "1066d5c1af5c953dbaf129d7e05ce32f2d4292aa", "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": 40.9419642857, "max_line_length": 148, "alphanum_fraction": 0.5879402464, "num_tokens": 1972, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4769866285795191}}
{"text": "/*=============================================================================\nCopyright (c) 2016 Paul W. Bible\n\nDistributed under the Boost Software License, Version 1.0. (See accompanying\nfile LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n==============================================================================*/\n#ifndef ACCUMULATORS\n#define ACCUMULATORS\n\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics.hpp>\n#include <boost/accumulators/statistics/max.hpp>\n#include <boost/accumulators/statistics/min.hpp>\n#include <boost/accumulators/statistics/mean.hpp>\n#include <boost/accumulators/statistics/covariance.hpp>\n#include <boost/accumulators/statistics/variance.hpp>\n#include <boost/accumulators/statistics/variates/covariate.hpp>\n\n//! The Accumulators namespace provides min, max, and average accumulators to the broader code base.\n/*!\n\tThis namespace defines accumulator types from boost. Also provided are specific extactors\n\tthat will return the accumulator's current value.\n*/\nnamespace Accumulators{\n\n\t//to be able to call Accumulators::covariate1 instread of boost::accumulators::covariate1\n\tusing namespace boost::accumulators;\n\n\t//typedefs\n\t/*! MinAccumulator\n\t\\brief A helper type wrapping boost accumulators.\n\t*/\n\ttypedef boost::accumulators::accumulator_set< double,\n\t\tboost::accumulators::stats< boost::accumulators::tag::min >  > MinAccumulator;\n\n\t/*! MaxAccumulator\n\t\\brief A helper type wrapping boost accumulators.\n\t*/\n\ttypedef boost::accumulators::accumulator_set< double,\n\t\tboost::accumulators::stats< boost::accumulators::tag::max >  > MaxAccumulator;\n\n\t/*! MeanAccumulator\n\t\\brief A helper type wrapping boost accumulators.\n\t*/\n\ttypedef boost::accumulators::accumulator_set< double,\n\t\tboost::accumulators::stats<\tboost::accumulators::tag::mean > > MeanAccumulator;\n\n\t/*! MeanAccumulator\n\t\\brief A helper type wrapping boost accumulators.\n\t*/\n\ttypedef boost::accumulators::accumulator_set< double,\n\t\tboost::accumulators::stats<\tboost::accumulators::tag::mean > > MeanAccumulator;\n\n\t/*! SimpleAccumulator\n\t\\brief A helper type wrapping min, max, and mean accumulators.\n\t*/\n\ttypedef boost::accumulators::accumulator_set< double,\n\t\tboost::accumulators::stats<\n\t\t\tboost::accumulators::tag::max,\n\t\t\tboost::accumulators::tag::min,\n\t\t\tboost::accumulators::tag::mean > > SimpleAccumulator;\n\n\n\t/*! CovarianceAccumulator\n\t\\brief A helper type wrapping the covariance accumulator.\n\t*/\n\ttypedef boost::accumulators::accumulator_set< double,\n\t\tboost::accumulators::stats< \n\t\t    boost::accumulators::tag::covariance<double,\n\t\t\t  boost::accumulators::tag::covariate1> > > CovarianceAccumulator;\n\n\t/*! VarianceAccumulator\n\t\\brief A helper type wrapping the variance accumulator.\n\t*/\n\ttypedef boost::accumulators::accumulator_set< double,\n\t\tboost::accumulators::stats< \n\t\t    boost::accumulators::tag::variance> > VarianceAccumulator;\n\n\t//extractors\n\t/*! extractMin\n\t\\brief A helper helper function to extract the min.\n\t*/\n\tinline double extractMin(const MinAccumulator &acc){\n\t\treturn  boost::accumulators::min(acc);\n\t}\n\n\t/*! extractMax\n\t\\brief A helper helper function to extract the max.\n\t*/\n\tinline double extractMax(const MaxAccumulator &acc){\n\t\treturn  boost::accumulators::max(acc);\n\t}\n\n\t/*! extractMean\n\t\\brief A helper helper function to extract the mean.\n\t*/\n\tinline double extractMean(const MeanAccumulator &acc){\n\t\treturn  boost::accumulators::mean(acc);\n\t}\n\n\t/*! extractMin\n\t\\brief An overlaoded helper helper function to extract the min.\n\t*/\n\tinline double extractMin(const SimpleAccumulator &acc){\n\t\treturn  boost::accumulators::min(acc);\n\t}\n\n\t/*! extractMax\n\t\\brief An overlaoded helper helper function to extract the max.\n\t*/\n\tinline double extractMax(const SimpleAccumulator &acc){\n\t\treturn  boost::accumulators::max(acc);\n\t}\n\n\t/*! extractMean\n\t\\brief An overlaoded helper helper function to extract the mean.\n\t*/\n\tinline double extractMean(const SimpleAccumulator &acc){\n\t\treturn  boost::accumulators::mean(acc);\n\t}\n\n\t/*! extractCovariance\n\t\\brief A helper helper function to extract the covariance.\n\t*/\n\tinline double extractCovariance(const CovarianceAccumulator &acc){\n\t\treturn  boost::accumulators::covariance(acc);\n\t}\n\n\t/*! extractVariance\n\t\\brief A helper helper function to extract the variance.\n\t*/\n\tinline double extractVariance(const VarianceAccumulator &acc){\n\t\treturn  boost::accumulators::variance(acc);\n\t}\n\n\t/*! extractVariance\n\t\\brief A helper helper function to extract the variance.\n\t*/\n\tinline double extractSD(const VarianceAccumulator &acc){\n\t\treturn  sqrt(boost::accumulators::variance(acc));\n\t}\n\n};\n#endif\n", "meta": {"hexsha": "54792c4b41f9140a1e35b1c7c77501779b0ba34a", "size": 4619, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ggtk/Accumulators.hpp", "max_stars_repo_name": "paulbible/ggtk", "max_stars_repo_head_hexsha": "9cdfb1ecced55db7353683b312b250e7238f61da", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-09-11T04:32:51.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-27T20:51:59.000Z", "max_issues_repo_path": "ggtk/Accumulators.hpp", "max_issues_repo_name": "paulbible/ggtk", "max_issues_repo_head_hexsha": "9cdfb1ecced55db7353683b312b250e7238f61da", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-10-12T05:36:18.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-30T19:47:01.000Z", "max_forks_repo_path": "ggtk/Accumulators.hpp", "max_forks_repo_name": "paulbible/ggtk", "max_forks_repo_head_hexsha": "9cdfb1ecced55db7353683b312b250e7238f61da", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-08T21:30:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-08T21:30:32.000Z", "avg_line_length": 31.8551724138, "max_line_length": 100, "alphanum_fraction": 0.7319766183, "num_tokens": 1093, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.766293653760418, "lm_q2_score": 0.6224593171945417, "lm_q1q2_score": 0.4769866244902204}}
{"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// 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// Projection example 1, direct\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/extensions/algorithms/parse.hpp>\n\n#include <boost/geometry/extensions/gis/latlong/latlong.hpp>\n#include <boost/geometry/extensions/gis/projections/parameters.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/robin.hpp>\n\nint main()\n{\n    using namespace boost::geometry;\n\n    // Initialize projection parameters\n    projections::parameters par = projections::init(\"+ellps=WGS84 +units=m\");\n\n    // Construct a Robinson projection, using specified point types\n    // (This delivers a projection without virtual methods. Note that in p02 example\n    //  the projection is created using a factory, which delivers a projection with virtual methods)\n    typedef model::ll::point<degree> point_ll_deg;\n    typedef model::d2::point_xy<double> point_xy;\n    projections::robin_spheroid<point_ll_deg, point_xy> prj(par);\n\n    // Define Amsterdam / Barcelona in decimal degrees / degrees/minutes\n    point_ll_deg amsterdam = parse<point_ll_deg>(\"52.4N\", \"5.9E\");\n    point_ll_deg barcelona = parse<point_ll_deg>(\"41 23'N\", \"2 11'E\");\n\n    point_xy pa, pb;\n\n    // Now do the projection. \"Forward\" means from latlong to meters.\n    // (Note that a map projection might fail. This is not 'exceptional'.\n    // Therefore the forward function does not throw but returns false)\n    if (prj.forward(amsterdam, pa) && prj.forward(barcelona, pb))\n    {\n        std::cout << \"Amsterdam: \" << wkt(pa) << std::endl << \"Barcelona: \" << wkt(pb) << std::endl;\n\n        std::cout << \"Distance (unprojected):\" << distance(amsterdam, barcelona) / 1000.0 << \" km\" << std::endl;\n        std::cout << \"Distance (  projected):\" << distance(pa, pb) / 1000.0 << \" km\" << std::endl;\n\n        // Do the inverse projection. \"Inverse\" means from meters to latlong\n        // It also might fail or might not exist, not all projections\n        // have their inverse implemented\n        point_ll_deg a1;\n        if (prj.inverse(pa, a1))\n        {\n            std::cout << \"Amsterdam (original): \" << wkt(amsterdam)  << std::endl\n                << \"Amsterdam (projected, and back):\" << wkt(a1) << std::endl;\n            std::cout << \"Distance a-a': \" << distance(amsterdam, a1) << \" meter\" << std::endl;\n        }\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "1dbbfa0a4deb166286c1308a6835055f72b5661e", "size": 2721, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "extensions/example/gis/projections/p01_projection_example.cpp", "max_stars_repo_name": "jkerkela/geometry", "max_stars_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 326.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T13:47:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T02:13:59.000Z", "max_issues_repo_path": "extensions/example/gis/projections/p01_projection_example.cpp", "max_issues_repo_name": "jkerkela/geometry", "max_issues_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 623.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T23:45:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T11:15:23.000Z", "max_forks_repo_path": "extensions/example/gis/projections/p01_projection_example.cpp", "max_forks_repo_name": "jkerkela/geometry", "max_forks_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-01-14T15:50:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T03:58:36.000Z", "avg_line_length": 43.1904761905, "max_line_length": 112, "alphanum_fraction": 0.6714443219, "num_tokens": 707, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6224593241981982, "lm_q1q2_score": 0.4769866232126617}}
{"text": "#include <iostream>\n#include <boost/date_time/gregorian/gregorian.hpp>\n#include <cstdlib>\n\nint main( int argc , char* argv[ ] ) {\n   using namespace boost::gregorian ;\n\n   int year =  std::atoi( argv[ 1 ] ) ;\n   for ( int i = 1 ; i < 13 ; i++ ) {\n      try {\n\t date d( year , i , 1  ) ;\n\t d = d.end_of_month( ) ;\n\t day_iterator d_itr ( d ) ;\n\t while ( d_itr->day_of_week( ) != Sunday ) {\n\t    --d_itr ;\n\t }\n\t std::cout << to_simple_string ( *d_itr ) << std::endl ;\n      } catch ( bad_year by ) {\n\t  std::cout << \"Terminated because of \" << by.what( ) << \"\\n\" ;\n      }\n   }\n   return 0 ;\n}\n", "meta": {"hexsha": "6e33791ea05227d88d9db93ff64a142a8a9d9c0f", "size": 591, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lang/C++/find-the-last-sunday-of-each-month-2.cpp", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-01-29T20:08:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T06:16:05.000Z", "max_issues_repo_path": "lang/C++/find-the-last-sunday-of-each-month-2.cpp", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/C++/find-the-last-sunday-of-each-month-2.cpp", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-11-09T22:08:40.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-09T22:08:40.000Z", "avg_line_length": 24.625, "max_line_length": 64, "alphanum_fraction": 0.5414551607, "num_tokens": 191, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7662936324115012, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.47698662193510283}}
{"text": "/*\n * rng/uniform_rng.hpp --\n *\n * This file is part of nettcl2d application.\n *\n * Copyright (c) 2012 Andrey V. Nakin <andrey.nakin@gmail.com>\n * All rights reserved.\n *\n * See the file \"COPYING\" for information on usage and redistribution\n * of this file, and for a DISCLAIMER OF ALL WARRANTIES.\n *\n */\n\n#ifndef UNIFORM_RNG_HPP_\n#define UNIFORM_RNG_HPP_\n\n#include <boost/random/uniform_real.hpp>\n#include <boost/random/linear_congruential.hpp>\n#include \"../calc/abstract_rng.hpp\"\n\nnamespace rng {\n\n\tclass Uniform : public AbstractRng {\n\n\t\ttypedef boost::rand48 Generator;\n\n\t\tvirtual double doGenerate() {\n\t\t\treturn distr(generator);\n\t\t}\n\n\t\tvirtual void doSeed(long seedValue) {\n\t\t\tgenerator.seed(static_cast<uint64_t>(seedValue));\n\t\t}\n\n\t\tvirtual phlib::Cloneable* doClone() const {\n\t\t\treturn new Uniform(mean, range);\n\t\t}\n\n\tpublic:\n\n\t\tUniform(const double mean, const double range) :\n\t\t\tmean(mean), range(range),\n\t\t\tgenerator(static_cast<uint64_t>(12345L)),\n\t\t\tdistr(mean - 0.5 * range, range > 0.0 ? mean + 0.5 * range : mean + 1.0e-6) {}\n\n\tprivate:\n\n\t\tconst double mean;\n\t\tconst double range;\n\t\tGenerator generator;\n\t\tboost::uniform_real<double> distr;\n\n\t};\n\n}\n\n#endif /* UNIFORM_RNG_HPP_ */\n", "meta": {"hexsha": "d57966baebe935a4d3ebe9c2bb93d10fee26b98b", "size": 1196, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/nettcl2d/rng/uniform_rng.hpp", "max_stars_repo_name": "andrey-nakin/nettcl2d", "max_stars_repo_head_hexsha": "d35d9dee6d108e7a09345a06aa4a6349bef1c0fb", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/nettcl2d/rng/uniform_rng.hpp", "max_issues_repo_name": "andrey-nakin/nettcl2d", "max_issues_repo_head_hexsha": "d35d9dee6d108e7a09345a06aa4a6349bef1c0fb", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/nettcl2d/rng/uniform_rng.hpp", "max_forks_repo_name": "andrey-nakin/nettcl2d", "max_forks_repo_head_hexsha": "d35d9dee6d108e7a09345a06aa4a6349bef1c0fb", "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": 20.6206896552, "max_line_length": 81, "alphanum_fraction": 0.6998327759, "num_tokens": 319, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4769866219351028}}
{"text": "#include <boost/date_time/gregorian/gregorian.hpp> \n#include <iostream> \n\nint main() \n{ \n  boost::gregorian::date d1(2008, 1, 31); \n  boost::gregorian::date d2(2008, 8, 31); \n  boost::gregorian::date_duration dd = d2 - d1; \n  std::cout << dd.days() << std::endl; \n} ", "meta": {"hexsha": "da4db10067eb4eda662fa26d0198b47b58163830", "size": 266, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Boost/The Boost C++ Libraries/src/10.2.3/main.cpp", "max_stars_repo_name": "goodspeed24e/Programming", "max_stars_repo_head_hexsha": "ae73fad022396ea03105aad83293facaeea561ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-12T19:29:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-12T19:29:33.000Z", "max_issues_repo_path": "Boost/The Boost C++ Libraries/src/10.2.3/main.cpp", "max_issues_repo_name": "goodspeed24e/Programming", "max_issues_repo_head_hexsha": "ae73fad022396ea03105aad83293facaeea561ae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-03-13T01:36:12.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-13T01:36:12.000Z", "max_forks_repo_path": "Boost/The Boost C++ Libraries/src/10.2.3/main.cpp", "max_forks_repo_name": "goodspeed24e/Programming", "max_forks_repo_head_hexsha": "ae73fad022396ea03105aad83293facaeea561ae", "max_forks_repo_licenses": ["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.6, "max_line_length": 51, "alphanum_fraction": 0.6428571429, "num_tokens": 98, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.6224593241981982, "lm_q1q2_score": 0.4769866165682454}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\nCopyright (C) 2014 StatPro Italia srl\nCopyright (C) 2015 CompatibL\n\nThis file is part of QuantLib, a free-software/open-source library\nfor financial quantitative analysts and developers - http://quantlib.org/\n\nQuantLib is free software: you can redistribute it and/or modify it\nunder the terms of the QuantLib license.  You should have received a\ncopy of the license along with this program; if not, please email\n<quantlib-dev@lists.sf.net>. The license is also available online at\n<http://quantlib.org/license.shtml>.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT\nANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\nFOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n// Based on piecewisezerospreadedtermstructure.cpp from Quantlib/test-suite.\n\n\n#ifndef cl_adjoint_test_zero_spreaded_term_structure_impl_hpp\n#define cl_adjoint_test_zero_spreaded_term_structure_impl_hpp\n#pragma once\n\n#include \"adjointzerospreadedtermstructuretest.hpp\"\n#include \"utilities.hpp\"\n#include \"adjointtestutilities.hpp\"\n#include \"adjointtestbase.hpp\"\n#include <ql/termstructures/yield/piecewisezerospreadedtermstructure.hpp>\n#include <ql/termstructures/yield/zerocurve.hpp>\n#include <ql/indexes/iborindex.hpp>\n#include <ql/termstructures/yield/ratehelpers.hpp>\n#include <ql/time/daycounters/actual360.hpp>\n#include <ql/time/calendars/target.hpp>\n#include <ql/time/daycounters/thirty360.hpp>\n#include <ql/math/interpolations/all.hpp>\n#include <boost/make_shared.hpp>\n\nusing namespace QuantLib;\nusing namespace boost::unit_test_framework;\n\n#define OUTPUT_FOLDER_NAME \"AdjointPiecwZeroSprTermStruct\"\n\nnamespace\n{\n    enum\n    {\n#if defined CL_GRAPH_GEN\n        // Number of points for dependency plots.\n        pointNo = 100,\n        // Number of points for performance plot.\n        iterNo = 100,\n        // Step for portfolio size for performance testing .\n        step = 1,\n        // Defines performance accuracy. Its value is a minimum number\n        // of calling of O(1) complexity methods per one performance test.\n        iterNumFactor = 1000,\n#else\n        // Number of points for dependency plots.\n        pointNo = 10,\n        // Number of points for performance plot.\n        iterNo = 10,\n        // Step for portfolio size for performance testing .\n        step = 1,\n        // Defines performance accuracy. Its value is a minimum number\n        // of calling of O(1) complexity methods per one performance test.\n        iterNumFactor = 1\n#endif\n    };\n\n    std::vector<double> getDoubleVector(Size size)\n    {\n        std::vector<double> vec =\n        {\n            0.04, 0.09, 0.12, 0.06, 0.05, 0.19, 0.52, 0.66, 0.45, 0.82, 0.73, 0.33, 0.82\n            , 0.66, 0.39, 0.74, 0.58, 0.55, 0.36, 0.91, 0.11, 0.24, 0.5, 0.22, 0.43, 0.5\n            , 0.99, 0.64, 0.58, 0.35, 0.46, 0.86, 0.71, 0.23, 0.3, 0.07, 0.03, 0.82, 0.12\n            , 0.55, 0.82, 0.95, 0.11, 0.91, 0.16, 0.73, 0.24, 0.96, 0.31, 0.32, 0.46, 0.88\n            , 0.71, 0.03, 0.55, 0.58, 0.1, 0.63, 0.23, 0.02, 0.62, 0.7, 0.37, 0.21, 0.19\n            , 0.13, 0.2, 0.46, 0.41, 0.9, 0.99, 0.01, 0.73, 0.19, 0.2, 0.58, 0.59, 0.83\n            , 0.1, 0.85, 0.76, 0.9, 0.49, 0.01, 0.65, 0.99, 0.5, 0.63, 0.52, 0.43, 0.79\n            , 0.49, 0.69, 0.01, 0.44, 0.22, 0.64, 0.88, 0.83, 0.35, 0.54, 0.16, 0.91, 0.18\n            , 0.35, 0.45, 0.26, 0.48, 0.67, 0.94, 0.03, 0.22, 0.64, 0.88, 0.83, 0.35, 0.64\n        };\n        return std::vector<double>(vec.begin(), vec.begin() + size);\n    }\n\n    std::vector<Integer> getIntegerVector(Size size)\n    {\n        std::vector<Integer> vec = {\n            18, 51, 98, 120, 170, 201, 296, 297, 315, 383, 394, 460, 504, 588, 620, 691, 753\n            , 776, 781, 806, 904, 993, 1062, 1107, 1126, 1196, 1199, 1236, 1301, 1347, 1382\n            , 1475, 1486, 1539, 1576, 1664, 1740, 1793, 1799, 1837, 1906, 1942, 1982, 2070\n            , 2089, 2115, 2138, 2196, 2210, 2244, 2293, 2368, 2425, 2445, 2494, 2572, 2588, 2674\n            , 2770, 2790, 2792, 2802, 2810, 2903, 2973, 2990, 3032, 3108, 3193, 3196, 3289\n            , 3346, 3349, 3356, 3415, 3468, 3492, 3538, 3578, 3635, 3664, 3760, 3781, 3875\n            , 3930, 4025, 4047, 4072, 4150, 4216, 4295, 4388, 4441, 4521, 4572, 4594, 4615, 4692\n            , 4766, 4778, 4834, 4856, 4895, 4936, 4965, 4995, 5012, 5096, 5145, 5185, 5215, 5305\n        };\n        return std::vector<Integer>(vec.begin(), vec.begin() + size);\n    }\n\n    struct RateDependence\n    {\n        static std::deque<std::string > get_columns()\n        {\n            static std::deque<std::string > columns =\n            {\n                \"Rate\", \"\"\n            };\n\n            return columns;\n        }\n\n        template <typename stream_type>\n        friend inline stream_type&\n            operator << (stream_type& stm, RateDependence& v)\n        {\n                stm << v.inputRate_\n                    << \";\" << v.interpolatedZeroRate_ << std::endl;\n\n                return stm;\n            }\n\n        Real inputRate_;\n        Real interpolatedZeroRate_;\n    };\n\n    struct Interpol\n    {\n        Interpol() :\n        calendar_(TARGET())\n        , settlementDays_(2)\n        , today_(Date(9, June, 2009))\n        , compounding_(Continuous)\n        , dayCount_(Actual360())\n        , settlementDate_(calendar_.advance(today_, settlementDays_, Days))\n        {\n            Settings::instance().evaluationDate() = today_;\n        }\n\n        virtual Date setInterpolationDate() = 0;\n\n        virtual void setSpreads(std::vector<Handle<Quote> >& spreads, std::vector<Date>& spreadDates) = 0;\n\n        virtual boost::shared_ptr<ZeroYieldStructure> createSpreadedTermStructure(boost::shared_ptr<YieldTermStructure>& termStructure\n                                                                                  , std::vector<Handle<Quote> >& spreads, std::vector<Date>& spreadDates)\n                                                                                  = 0;\n        virtual std::string getName() = 0;\n\n        Calendar calendar_;\n        Natural settlementDays_;\n        DayCounter dayCount_;\n        Compounding compounding_;\n        Date today_;\n        Date settlementDate_;\n\n        SavedSettings backup_;\n\n    };\n\n    struct FlatInterpolLeft : Interpol\n    {\n        FlatInterpolLeft()\n        {\n        }\n\n        Date setInterpolationDate() { return calendar_.advance(today_, 6, Months); }\n\n        void setSpreads(std::vector<Handle<Quote> >& spreads, std::vector<Date>& spreadDates)\n        {\n            spreads.resize(2);\n            spreadDates.resize(2);\n            for (Size i = 0; i < 2; i++)\n            {\n                spreads[i] = Handle<Quote>(boost::make_shared<SimpleQuote>(0.01*i + 0.02));\n                spreadDates[i] = calendar_.advance(today_, 7 * i + 8, Months);\n            }\n        }\n\n        boost::shared_ptr<ZeroYieldStructure> createSpreadedTermStructure(boost::shared_ptr<YieldTermStructure>& termStructure\n                                                                          , std::vector<Handle<Quote> >& spreads, std::vector<Date>& spreadDates)\n        {\n            return boost::make_shared<PiecewiseZeroSpreadedTermStructure>(\n                Handle<YieldTermStructure>(termStructure),\n                spreads, spreadDates);\n        }\n\n        std::string getName() { return \"FlatInterpolationLeft\"; }\n\n    };\n\n    struct FlatInterpolRight : Interpol\n    {\n        FlatInterpolRight() {}\n\n        Date setInterpolationDate() { return calendar_.advance(today_, 6, Months); }\n\n        void setSpreads(std::vector<Handle<Quote> >& spreads, std::vector<Date>& spreadDates)\n        {\n            spreads.resize(2);\n            spreadDates.resize(2);\n            for (Size i = 0; i < 2; i++)\n            {\n                spreads[i] = Handle<Quote>(boost::make_shared<SimpleQuote>(0.01*i + 0.02));\n                spreadDates[i] = calendar_.advance(today_, 7 * i + 8, Months);\n            }\n        }\n\n        boost::shared_ptr<ZeroYieldStructure> createSpreadedTermStructure(boost::shared_ptr<YieldTermStructure>& termStructure\n                                                                          , std::vector<Handle<Quote> >& spreads, std::vector<Date>& spreadDates)\n        {\n            boost::shared_ptr<ZeroYieldStructure> sprTermStructure =\n                boost::make_shared<PiecewiseZeroSpreadedTermStructure>(\n                Handle<YieldTermStructure>(termStructure),\n                spreads, spreadDates);\n            sprTermStructure->enableExtrapolation();\n            return sprTermStructure;\n        }\n\n        std::string getName() { return \"FlatInterpolationRight\"; }\n    };\n\n    struct LinearInterpolMultipleSpreads : Interpol\n    {\n        LinearInterpolMultipleSpreads() {}\n\n        Date setInterpolationDate() { return  calendar_.advance(today_, 120, Days); }\n\n        void setSpreads(std::vector<Handle<Quote> >& spreads, std::vector<Date>& spreadDates)\n        {\n            spreads.resize(4);\n            spreadDates.resize(4);\n            for (Size i = 0; i < 4; i++)\n            {\n                spreads[i] = Handle<Quote>(boost::make_shared<SimpleQuote>(0.005*i + 0.02));\n            }\n            for (Size i = 0; i < 2; i++)\n            {\n                spreadDates[i] = calendar_.advance(today_, 3 * i + 3, Months);\n                spreadDates[i + 2] = calendar_.advance(today_, 10 * i + 30, Months);\n            }\n        }\n\n        boost::shared_ptr<ZeroYieldStructure> createSpreadedTermStructure(boost::shared_ptr<YieldTermStructure>& termStructure\n                                                                          , std::vector<Handle<Quote> >& spreads, std::vector<Date>& spreadDates)\n        {\n            return boost::make_shared<PiecewiseZeroSpreadedTermStructure>(\n                Handle<YieldTermStructure>(termStructure),\n                spreads, spreadDates);\n        }\n\n        std::string getName() { return \"LinearInterpolationMultipleSpreads\"; }\n    };\n\n    struct LinearInterpol : Interpol\n    {\n        LinearInterpol() {}\n\n        Date setInterpolationDate() { return  calendar_.advance(today_, 120, Days); }\n\n        void setSpreads(std::vector<Handle<Quote> >& spreads, std::vector<Date>& spreadDates)\n        {\n            spreads.resize(2);\n            spreadDates.resize(2);\n            for (Size i = 0; i < 2; i++)\n            {\n                spreads[i] = Handle<Quote>(boost::make_shared<SimpleQuote>(0.01*i + 0.02));\n                spreadDates[i] = calendar_.advance(today_, 50 * i + 100, Days);\n            }\n        }\n\n        boost::shared_ptr<ZeroYieldStructure> createSpreadedTermStructure(boost::shared_ptr<YieldTermStructure>& termStructure\n                                                                          , std::vector<Handle<Quote> >& spreads, std::vector<Date>& spreadDates)\n        {\n            return boost::make_shared<InterpolatedPiecewiseZeroSpreadedTermStructure<Linear> >(\n                Handle<YieldTermStructure>(termStructure),\n                spreads, spreadDates);\n        }\n\n        std::string getName() { return \"LinearInterpolation\"; }\n    };\n\n    struct ForwardFlatInterpol : Interpol\n    {\n        ForwardFlatInterpol() {}\n\n        Date setInterpolationDate() { return  calendar_.advance(today_, 100, Days); }\n\n        void setSpreads(std::vector<Handle<Quote> >& spreads, std::vector<Date>& spreadDates)\n        {\n            spreads.resize(2);\n            spreadDates.resize(2);\n            for (Size i = 0; i < 2; i++)\n            {\n                spreads[i] = Handle<Quote>(boost::make_shared<SimpleQuote>(0.01*i + 0.02));\n                spreadDates[i] = calendar_.advance(today_, 185 * i + 75, Days);\n            }\n        }\n\n        boost::shared_ptr<ZeroYieldStructure> createSpreadedTermStructure(boost::shared_ptr<YieldTermStructure>& termStructure\n                                                                          , std::vector<Handle<Quote> >& spreads, std::vector<Date>& spreadDates)\n        {\n            return boost::make_shared<InterpolatedPiecewiseZeroSpreadedTermStructure<ForwardFlat> >(\n                Handle<YieldTermStructure>(termStructure),\n                spreads, spreadDates);\n        }\n\n        std::string getName() { return \"ForwardFlatInterpolation\"; }\n    };\n\n    struct BackwardFlatInterpol : Interpol\n    {\n        BackwardFlatInterpol() {}\n\n        Date setInterpolationDate() { return  calendar_.advance(today_, 110, Days); }\n\n        void setSpreads(std::vector<Handle<Quote> >& spreads, std::vector<Date>& spreadDates)\n        {\n            spreads.resize(3);\n            spreadDates.resize(3);\n            for (Size i = 0; i < 3; i++)\n            {\n                spreads[i] = Handle<Quote>(boost::make_shared<SimpleQuote>(0.01*i + 0.02));\n                spreadDates[i] = calendar_.advance(today_, 100 * (i + 1), Days);\n            }\n        }\n\n        boost::shared_ptr<ZeroYieldStructure> createSpreadedTermStructure(boost::shared_ptr<YieldTermStructure>& termStructure\n                                                                          , std::vector<Handle<Quote> >& spreads, std::vector<Date>& spreadDates)\n        {\n            return boost::make_shared<InterpolatedPiecewiseZeroSpreadedTermStructure<BackwardFlat> >(\n                Handle<YieldTermStructure>(termStructure),\n                spreads, spreadDates);\n        }\n\n        std::string getName() { return \"BackwardFlatInterpolation\"; }\n    };\n\n    struct DefaultInterpol : Interpol\n    {\n        DefaultInterpol() {}\n\n        Date setInterpolationDate() { return  calendar_.advance(today_, 100, Days); }\n\n        void setSpreads(std::vector<Handle<Quote> >& spreads, std::vector<Date>& spreadDates)\n        {\n            spreads.resize(2, Handle<Quote>(boost::make_shared<SimpleQuote>(0.02)));\n            spreadDates.resize(2);\n            for (Size i = 0; i < 2; i++)\n            {\n                spreadDates[i] = calendar_.advance(today_, 75 * (i + 1), Days);\n            }\n        }\n\n        boost::shared_ptr<ZeroYieldStructure> createSpreadedTermStructure(boost::shared_ptr<YieldTermStructure>& termStructure\n                                                                          , std::vector<Handle<Quote> >& spreads, std::vector<Date>& spreadDates)\n        {\n            return boost::make_shared<PiecewiseZeroSpreadedTermStructure>(\n                Handle<YieldTermStructure>(termStructure),\n                spreads, spreadDates);\n        }\n\n        std::string getName() { return \"DefaultInterpolation\"; }\n    };\n\n    struct SetInterpolFactory : Interpol\n    {\n        SetInterpolFactory() {}\n\n        Date setInterpolationDate() { return  calendar_.advance(today_, 11, Months); }\n\n        void setSpreads(std::vector<Handle<Quote> >& spreads, std::vector<Date>& spreadDates)\n        {\n            spreads.resize(3);\n            spreadDates.resize(3);\n            for (Size i = 0; i < 3; i++)\n            {\n                spreads[i] = Handle<Quote>(boost::make_shared<SimpleQuote>(0.02 + i*pow(-1, i)*0.01));\n                spreadDates[i] = calendar_.advance(today_, 8 * (i + 1), Months);\n            }\n        }\n\n        boost::shared_ptr<ZeroYieldStructure> createSpreadedTermStructure(boost::shared_ptr<YieldTermStructure>& termStructure\n                                                                          , std::vector<Handle<Quote> >& spreads, std::vector<Date>& spreadDates)\n        {\n            Cubic factory = Cubic(CubicInterpolation::Spline, false);\n            return boost::make_shared<InterpolatedPiecewiseZeroSpreadedTermStructure<Cubic> >(\n                Handle<YieldTermStructure>(termStructure),\n                spreads, spreadDates, compounding_,\n                NoFrequency, dayCount_, factory);\n        }\n\n        std::string getName() { return \"SetInterpolationFactory\"; }\n    };\n\n    struct QuoteChanging : Interpol\n    {\n        QuoteChanging() {}\n\n        Date setInterpolationDate() { return  calendar_.advance(today_, 120, Days); }\n\n        void setSpreads(std::vector<Handle<Quote> >& spreads, std::vector<Date>& spreadDates)\n        {\n            spreads.resize(2);\n            spreadDates.resize(2);\n            for (Size i = 0; i < 2; i++)\n            {\n                spreads[i] = Handle<Quote>(boost::make_shared<SimpleQuote>(0.01*i + 0.02));\n                spreadDates[i] = calendar_.advance(today_, 50 * i + 100, Days);\n            }\n        }\n\n        boost::shared_ptr<ZeroYieldStructure> createSpreadedTermStructure(boost::shared_ptr<YieldTermStructure>& termStructure\n                                                                          , std::vector<Handle<Quote> >& spreads, std::vector<Date>& spreadDates)\n        {\n            return boost::make_shared<InterpolatedPiecewiseZeroSpreadedTermStructure<BackwardFlat> >(\n                Handle<YieldTermStructure>(termStructure),\n                spreads, spreadDates);\n        }\n\n        std::string getName() { return \"QuoteChanging\"; }\n    };\n\n    template <class InterpolationType>\n    struct TestData\n    {\n        struct Test\n        : cl::AdjointTest<Test>\n        {\n            explicit Test(Size size, TestData* data)\n            : AdjointTest()\n            , data_(data)\n            , size_(size)\n            , rates_(size)\n            , resRates_(1)\n            , spreads_()\n            , spreadDates_()\n            , interpolationDate_()\n            {\n                setLogger(&data_->outPerform_);\n                std::vector<double> ratesDouble_ = getDoubleVector(size_);\n\n                for (Size i = 0; i < size_; i++)\n                {\n                    rates_[i] = Real(ratesDouble_[i]);\n                }\n            }\n\n            Size indepVarNumber() { return size_; }\n\n            Size depVarNumber() { return 1; }\n\n            Size minPerfIteration() { return iterNumFactor; }\n\n            void recordTape()\n            {\n                cl::Independent(rates_);\n                calculateResRates(rates_, resRates_);\n                f_ = std::make_unique<cl::tape_function<double>>(rates_, resRates_);\n            }\n\n            void calculateResRates(std::vector<Real> rates, std::vector<Real>& resRates)\n            {\n                resRates.resize(1);\n                data_->type_.setSpreads(spreads_, spreadDates_);\n                interpolationDate_ = data_->type_.setInterpolationDate();\n                boost::shared_ptr<YieldTermStructure> termStructure = createTermStructure(rates);\n                boost::shared_ptr<ZeroYieldStructure> spreadedTermStructure =\n                    data_->type_.createSpreadedTermStructure(termStructure, spreads_, spreadDates_);\n\n                Time t = data_->type_.dayCount_.yearFraction(data_->type_.today_, interpolationDate_);\n\n                resRates[0] = spreadedTermStructure->zeroRate(t, data_->type_.compounding_);\n            }\n\n            void resetSpreads(std::vector<Real> rates, std::vector<Real>& resRates)\n            {\n                resRates.resize(1);\n                data_->type_.setSpreads(spreads_, spreadDates_);\n                interpolationDate_ = data_->type_.setInterpolationDate();\n                spreads_[1] = Handle<Quote>(boost::make_shared<SimpleQuote>(0.025));\n                boost::shared_ptr<YieldTermStructure> termStructure = createTermStructure(rates);\n                boost::shared_ptr<ZeroYieldStructure> spreadedTermStructure =\n                    data_->type_.createSpreadedTermStructure(termStructure, spreads_, spreadDates_);\n\n                Time t = data_->type_.dayCount_.yearFraction(data_->type_.today_, interpolationDate_);\n\n                resRates[0] = spreadedTermStructure->zeroRate(t, data_->type_.compounding_);\n            }\n\n\n            boost::shared_ptr<YieldTermStructure> createTermStructure(std::vector<Real>& rates)\n            {\n                std::vector<Integer> ts = getIntegerVector(size_ - 1);\n                std::vector<Date> dates(size_);\n                dates[0] = data_->type_.settlementDate_;\n                for (Size i = 0; i < size_ - 1; ++i)\n                {\n                    dates[i + 1] = data_->type_.calendar_.advance(data_->type_.today_, ts[i], Days);\n                }\n                return boost::make_shared<ZeroCurve>(dates, rates, data_->type_.dayCount_);\n            };\n\n            void calcAnalytical()\n            {\n                double h = 1e-4;\n                std::vector<Real> resRight(1), resLeft(1);\n                analyticalResults_.resize(size_);\n                for (Size i = 0; i < size_; i++)\n                {\n                    rates_[i] += h;\n                    calculateResRates(rates_, resRight);\n                    rates_[i] -= 2 * h;\n                    calculateResRates(rates_, resLeft);\n                    rates_[i] += h;\n                    analyticalResults_[i] = (resRight[0] - resLeft[0]) / (2 * h);\n                }\n            }\n\n            Size size_;\n            std::vector<cl::tape_double> rates_;\n            std::vector<cl::tape_double> resRates_;\n            std::vector<Handle<Quote> > spreads_;\n            std::vector<Date> spreadDates_;\n            Date interpolationDate_;\n            TestData* data_;\n\n        };\n\n        TestData() :\n            type_()\n            , outPerform_tilte_(\"Interpolated zero rate (by \" + type_.getName() + \") \\\\ndifferentiation performance with respect to yield rate\")\n            , outAdjoint_tilte_(\"Interpolated zero rate (by \" + type_.getName() + \") \\\\nadjoint differentiation performance with respect to yield rate\")\n            , out_tilte_(\"Zero Rate dependence on yield rate by\" + type_.getName())\n            , out_filename_(\"ZeroRateOnYieldRateBy\" + type_.getName())\n            , outPerform_(OUTPUT_FOLDER_NAME \"//\" + type_.getName()\n            , { { \"filename\", \"AdjointPerformance\" }\n        , { \"not_clear\", \"Not\" }\n        , { \"title\", outPerform_tilte_ }\n        , { \"ylabel\", \"Time (s)\" }\n        , { \"xlabel\", \"Number of yield rates\" }\n        , { \"smooth\", \"default\" }\n        , { \"line_box_width\", \"-5\" }\n        , { \"cleanlog\", \"true\" } })\n            , outAdjoint_(OUTPUT_FOLDER_NAME \"//\" + type_.getName()\n            , { { \"filename\", \"Adjoint\" }\n        , { \"not_clear\", \"Not\" }\n        , { \"title\", outAdjoint_tilte_ }\n        , { \"xlabel\", \"Number of yield rates\" }\n        , { \"smooth\", \"default\" }\n        , { \"ylabel\", \"Time (s)\" }\n        , { \"cleanlog\", \"false\" } })\n            , outSize_(OUTPUT_FOLDER_NAME \"//\" + type_.getName()\n            , { { \"filename\", \"TapeSize\" }\n        , { \"not_clear\", \"Not\" }\n        , { \"title\", \"Tape size dependence on number of yield rates\" }\n        , { \"xlabel\", \"Number of yield rates\" }\n        , { \"ylabel\", \"Memory(MB)\" }\n        , { \"cleanlog\", \"false\" } })\n            , out_(OUTPUT_FOLDER_NAME \"//\" + type_.getName() + \"//output\"\n            , { { \"filename\", out_filename_ }\n        , { \"not_clear\", \"Not\" }\n        , { \"title\", out_tilte_ }\n        , { \"xlabel\", \"Yield rates\" }\n        , { \"ylabel\", \"Zero Rate\" }\n        , { \"cleanlog\", \"false\" } })\n        {\n        }\n\n        bool makeOutput()\n        {\n            bool ok = true;\n            if (pointNo > 0)\n            {\n                ok &= recordDependencePlot();\n            }\n            ok &= cl::recordPerformance(*this, iterNo, step);\n            return ok;\n        }\n\n        std::shared_ptr<Test> getTest(size_t size)\n        {\n            return std::make_shared<Test>(10 + size, this);\n        }\n\n        // Makes plots for sensitivity dependence.\n        bool recordDependencePlot()\n        {\n            std::vector<RateDependence> outData(pointNo);\n            auto test = getTest(10);\n            std::vector<Real> rates = test->rates_;\n            std::vector<Real> result(1);\n            for (Size i = 0; i < pointNo; i++)\n            {\n                rates[5] = (i + 1)*0.01;\n                test->calculateResRates(rates, result);\n                outData[i] = { rates[5], result[0] };\n            }\n            out_ << outData;\n            return true;\n        }\n\n        InterpolationType type_;\n        std::string outPerform_tilte_;\n        std::string outAdjoint_tilte_;\n        std::string out_tilte_;\n        std::string out_filename_;\n        cl::tape_empty_test_output outPerform_;\n        cl::tape_empty_test_output outAdjoint_;\n        cl::tape_empty_test_output outSize_;\n        cl::tape_empty_test_output out_;\n\n    };\n}\n#endif", "meta": {"hexsha": "619cf595a5db4c9255ada28daa1d44bbc46f803d", "size": 24442, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test-suite-adjoint/adjointzerospreadedtermstructureimpl.hpp", "max_stars_repo_name": "fduffy/QuantLibAdjoint", "max_stars_repo_head_hexsha": "d9d355db4f46824bb5e607e28381943aef994ed4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 41.0, "max_stars_repo_stars_event_min_datetime": "2016-03-19T02:31:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T13:23:20.000Z", "max_issues_repo_path": "test-suite-adjoint/adjointzerospreadedtermstructureimpl.hpp", "max_issues_repo_name": "fduffy/QuantLibAdjoint", "max_issues_repo_head_hexsha": "d9d355db4f46824bb5e607e28381943aef994ed4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test-suite-adjoint/adjointzerospreadedtermstructureimpl.hpp", "max_forks_repo_name": "fduffy/QuantLibAdjoint", "max_forks_repo_head_hexsha": "d9d355db4f46824bb5e607e28381943aef994ed4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2016-03-17T14:14:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T10:33:19.000Z", "avg_line_length": 39.4862681745, "max_line_length": 153, "alphanum_fraction": 0.5565011047, "num_tokens": 6219, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.705785040214066, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.4769445507141705}}
{"text": "#include \"irrigation.h\"\n\n#include <boost/log/trivial.hpp>\n\nnamespace WorldEngine\n{\n\nstatic void IrrigationExecute(World& world);\n\nvoid IrrigationSimulation(World& world)\n{\n   BOOST_LOG_TRIVIAL(info) << \"Irrigation simulation start\";\n\n   IrrigationExecute(world);\n\n   BOOST_LOG_TRIVIAL(info) << \"Irrigation simulation finish\";\n}\n\nstatic void IrrigationExecute(World& world)\n{\n   const int32_t width  = world.width();\n   const int32_t height = world.height();\n   const int32_t radius = 10;\n\n   const WaterMapArrayType& watermap   = world.GetWaterMapData();\n   IrrigationArrayType&     irrigation = world.GetIrrigationData();\n   irrigation.resize(boost::extents[height][width]);\n\n   std::fill(\n      irrigation.data(), irrigation.data() + irrigation.num_elements(), 0.0f);\n\n   // Create array of pre-calculated values\n   boost::multi_array<float, 2> logs(\n      boost::extents[radius * 2 + 1][radius * 2 + 1]);\n   for (int32_t y = 0; y <= radius * 2; y++)\n   {\n      // Y distance to center: [-10, 10]\n      float dy = static_cast<float>(y - radius);\n\n      for (int32_t x = 0; x <= radius * 2; x++)\n      {\n         // X distance to center: [-10, 10]\n         float dx = static_cast<float>(x - radius);\n\n         // Calculate final matrix: ln(sqrt(x^2 + y^2) + 1) + 1\n         logs[y][x] = log1pf(sqrtf(dx * dx + dy * dy)) + 1;\n      }\n   }\n\n   for (int32_t y = 0; y < height; y++)\n   {\n      for (int32_t x = 0; x < width; x++)\n      {\n         if (world.IsOcean(x, y))\n         {\n            // Coordinates (top-left / bottom-right) used for the values slice\n            uint32_t tlXV = std::max(x - radius, 0);\n            uint32_t tlYV = std::max(y - radius, 0);\n            uint32_t brXV = std::min(x + radius, width - 1);\n            uint32_t brYV = std::min(y + radius, height - 1);\n\n            // Coordinates (top-left / bottom-right) used for the logs slice\n            uint32_t tlXL = std::max(radius - x, 0);\n            uint32_t tlYL = std::max(radius - y, 0);\n            uint32_t brXL = std::min(radius - x + width - 1, 2 * radius);\n            uint32_t brYL = std::min(radius - y + height - 1, 2 * radius);\n\n            // Values slice and logs slice should be the same size and\n            // dimensions\n\n            for (uint32_t vy = tlYV, ly = tlYL; //\n                 vy <= brYV && ly <= brYL;\n                 vy++, ly++)\n            {\n               for (uint32_t vx = tlXV, lx = tlXL; //\n                    vx <= brXV && lx <= brXL;\n                    vx++, lx++)\n               {\n                  irrigation[vy][vx] += watermap[y][x] / logs[ly][lx];\n               }\n            }\n         }\n      }\n   }\n}\n\n} // namespace WorldEngine\n", "meta": {"hexsha": "c7c6915eebbd6ee1047646b55de83f90122c47bc", "size": 2662, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "worldengine/source/simulations/irrigation.cpp", "max_stars_repo_name": "dpaulat/worldengine-cpp", "max_stars_repo_head_hexsha": "9f7961aaf62db2633fc9d44b6018384812a6704e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-06-09T12:44:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T21:52:10.000Z", "max_issues_repo_path": "worldengine/source/simulations/irrigation.cpp", "max_issues_repo_name": "dpaulat/worldengine-cpp", "max_issues_repo_head_hexsha": "9f7961aaf62db2633fc9d44b6018384812a6704e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-06-09T12:49:33.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-17T15:28:37.000Z", "max_forks_repo_path": "worldengine/source/simulations/irrigation.cpp", "max_forks_repo_name": "dpaulat/worldengine-cpp", "max_forks_repo_head_hexsha": "9f7961aaf62db2633fc9d44b6018384812a6704e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.25, "max_line_length": 78, "alphanum_fraction": 0.5379413974, "num_tokens": 744, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.779992900254107, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.4768735985127838}}
{"text": "#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#include <opencv2/calib3d/calib3d.hpp>\n#include <Eigen/Dense>\n#include <opencv2/core/eigen.hpp>\n#include <iostream>\n#include <cstdio>\n#include <cstring>\n\nint main()\n{\n    const int COLS = 2208, ROWS = 1242;\n\n    cv::Mat depth = cv::imread(\"../data/1_dpt.tiff\", cv::IMREAD_ANYDEPTH);\n    cv::Mat img = cv::imread(\"../data/1.jpg\");\n    cv::FileStorage reader(\"../data/data.yml\", cv::FileStorage::READ);\n    cv::Mat c_mat, p_mat;\n    Eigen::Matrix<double, 3, 3> C;\n    Eigen::Matrix<double, 4, 4> P;\n    reader[\"C\"] >> c_mat;\n    reader[\"D\"] >> p_mat;\n\n    // std::cout << c_mat << std::endl << p_mat << std::endl << depth << std::endl;\n    cv::cv2eigen(c_mat, C);\n    cv::cv2eigen(p_mat, P);\n\n    std::vector<cv::Point2f> pt_u;\n    std::vector<cv::Point2f> pt_c;\n\n\n    for (int i = 0; i < img.rows; i++)\n        for (int j = 0; j < img.cols; j++)\n            pt_u.push_back(cv::Point2f{j, i});\n    cv::undistortPoints(pt_u, pt_c, c_mat, cv::noArray());\n\n    pt_u.clear();\n\n    std::vector<cv::Point2f> pt_c2;\n    // std::cout << pt_c.size() << \" : \" << depth.rows * depth.cols << std::endl;\n    for (int i = 0; i < pt_c.size(); i++)\n    {\n        Eigen::Matrix<double, 4, 1> pt_w, tmp;\n        pt_w << pt_c[i].x, pt_c[i].y, 1, 1;\n        pt_w *= depth.at<float>(i / depth.cols, i % depth.cols);\n        pt_w(3, 0) = 1;\n        Eigen::Matrix<double, 3, 1> pt, result;\n        tmp = P * pt_w;\n        pt << tmp(0, 0) / tmp(2, 0), tmp(1, 0) / tmp(2, 0), 1;\n        result = C * pt;\n        // std::cout << i << \":\\n\" << result << std::endl;\n        pt_c2.push_back({result(0, 0) / result(2, 0), result(1, 0) / result(2, 0)});\n    }\n    cv::Mat result = cv::Mat::zeros(cv::Size(img.cols, img.rows), CV_8UC3);\n    for (int i = 0; i < depth.rows; i++)\n        for (int j = 0; j < depth.cols; j++)\n        {\n            cv::Point2f pt = pt_c2[i * img.cols + j];\n            int x = (int)pt.x, y = (int)pt.y;\n            if (x < 0 || x > result.cols - 1 || y < 0 || y > result.rows - 1)\n                continue;\n            result.at<cv::Vec3b>(y, x) = img.at<cv::Vec3b>(i, j);\n        }\n    cv::imwrite(\"../out.jpg\", result);\n    cv::namedWindow(\"result\", 0);\n    cv::imshow(\"result\", result);\n    cv::waitKey(0);\n    return 0;\n}", "meta": {"hexsha": "ad37412085d13dbd8705c95cc2d227d036c89255", "size": 2332, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "hw4/1/main.cpp", "max_stars_repo_name": "Lupin2019/rm2022_homework", "max_stars_repo_head_hexsha": "f1e4820a5fa03c4ff1342ea82bad14706c64d1b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hw4/1/main.cpp", "max_issues_repo_name": "Lupin2019/rm2022_homework", "max_issues_repo_head_hexsha": "f1e4820a5fa03c4ff1342ea82bad14706c64d1b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hw4/1/main.cpp", "max_forks_repo_name": "Lupin2019/rm2022_homework", "max_forks_repo_head_hexsha": "f1e4820a5fa03c4ff1342ea82bad14706c64d1b0", "max_forks_repo_licenses": ["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.7971014493, "max_line_length": 84, "alphanum_fraction": 0.5295883362, "num_tokens": 808, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4768735985127838}}
{"text": "#ifndef TCM_DIELECTRIC_FUNCTION_HPP\n#define TCM_DIELECTRIC_FUNCTION_HPP\n\n#include <cmath>\n#include <cassert>\n\n#include <iostream>\n#include <vector>\n#include <array>\n#include <fstream>\n#include <regex>\n#include <algorithm>\n\n#include <boost/core/demangle.hpp>\n\n#include <benchmark.hpp>\n#include <logging.hpp>\n\n#include <constants.hpp>\n#include <matrix.hpp>\n#include <blas.hpp>\n\n\n\n\nnamespace tcm {\n\ntemplate <class T> struct huge_val;\n\ntemplate <> \nstruct huge_val<float> { static constexpr float value = HUGE_VALF; };\n\ntemplate <> \nstruct huge_val<double> { static constexpr double value = HUGE_VAL; };\n\ntemplate <> \nstruct huge_val<long double> { static constexpr long double value = HUGE_VALL; };\n\nconstexpr float huge_val<float>::value;\n\n\n///////////////////////////////////////////////////////////////////////////////\n/// \\brief Computes \\f$ f(E) \\f$\n\n/// Calculates the Fermi-Dirac distribution:\n/// \\f[ f(E) := \\frac{1}{\\exp(\\frac{E - \\mu}{k_{\\text{B}}T}) + 1}. \\f]\n///\n/// In the calculation we use that p\n/// \\f[ \\begin{aligned}\n///         \\lim_{E\\to -\\infty} f(E) &= 1 //\n///         \\lim_{E\\to +\\infty} f(E) &= 0\n///     \\end{algned}\n/// \\f]\n/// If `std::exp` returns HUGE_VAL, HUGE_VALF or HUGE_VALL, 0 is returned.\n/// \\param     E       Energy, i.e. a real number. Thus `_F` must be floating\n///                    point: `std::is_floating_point<_F>::value == true`.\n/// \\param     mu      Chemical potential \\f$ \\mu \\f$. It has the dimensions\n///                    of energy \\f$\\implies\\f$ `_R` is also floating point.\n/// \\param     t       Temperature \\f$ T \\f$.\n/// \\param     kb      Boltzmann constant \\f$ k_\\text{B} \\f$.\n///\n/// \\return \\f$ f(E) \\f$.\n///////////////////////////////////////////////////////////////////////////////\ntemplate<class _F, class _R>\nauto fermi_dirac(_F const E, _R const t, _R const mu, _R const kb ) noexcept\n{\n\tstatic_assert(std::is_floating_point<_F>::value, \"Energy must be real.\");\n\tstatic_assert(std::is_floating_point<_R>::value, \"Chemical potential, \" \n\t\t\"temperature and Boltzmann's constant must be real.\");\n\n\tauto const x = std::exp((E - mu) / (kb * t));\n\n\tif (std::isinf(x)) return 0.0;\n\tif (x < std::numeric_limits<decltype(x)>::epsilon()) return 1.0;\n\treturn 1.0 / (x + 1.0); \n}\n\n\n///////////////////////////////////////////////////////////////////////////////\n/// \\brief Defines tools to calculate the \\f$ G(\\omega) \\f$ matrix.\n///////////////////////////////////////////////////////////////////////////////\nnamespace g_function {\n\n///////////////////////////////////////////////////////////////////////////////\n/// \\brief Computes \\f$G_{i, j}(\\omega)=\\frac{f_i-f_j}{E_i-E_j-\\omega}\\f$.\n\n/// \\tparam    _F      Represents a real/complex field.\n/// \\tparam    _R      Represents a real field.\n/// \\tparam    _Number Just some abstract field.\n/// \\param     i       Row of the matrix \\f$G(\\omega)\\f$.\n/// \\param     j       Column of the matrix \\f$G(\\omega)\\f$.\n/// \\param     E       Pointer into the array of energies. `_F` must be real,\n///                    and size of \\p E must be at least `max(i,j)`.\n/// \\param     f       Pointer into the array of occupational numbers. `_R`\n///                    must be real, and size of \\p f must be at least\n///                    `max(i,j)`.\n///\n/// \\return \\f$G_{i,j}(\\omega)\\f$.\n///////////////////////////////////////////////////////////////////////////////\ntemplate<class _F, class _R, class _Number>\nauto at( std::size_t const i, std::size_t const j\n       , _Number const omega\n       , _F const* E\n       , _R const* f ) noexcept\n{\n\tstatic_assert(std::is_floating_point<_F>::value, \"Energy must be real.\");\n\tstatic_assert(std::is_floating_point<_R>::value, \"Occupational numbers \" \n\t\t\"must be real.\");\n\treturn (f[i] - f[j]) / (E[i] - E[j] - omega);\n}\n\n\n///////////////////////////////////////////////////////////////////////////////\n/// \\brief Computes \\f$ G(\\omega) \\f$.\n\n/// \\f[ G_{i,j}(\\omega) = \\frac{f_i - f_j}{E_i - E_j - \\omega}. \\f]\n///\n/// \\param omega    Frequency \\f$\\omega\\f$ at which to calculate \\f$ G \\f$.\n///                 It may be either real or complex.\n/// \\param E        Energies of the system: \\f$1 \\times N\\f$ matrix (i.e. a \n///                 column vector). `_F` must be floating point.\n/// \\param cs       Constants map. This function requires the availability of\n///                 \\f$ T, \\mu, k_\\text{B}, \\hbar \\f$ to run. Checks are\n///                 performed at runtime, i.e. this function <b>may throw</b>!\n///                 `_R`, the type of constants in \\p cs must also be floating\n///                 point.\n/// \\param lg       The logger.\n/// \\return         \\f$G(\\omega)\\f$.\n/// \\exception      May throw.\n///////////////////////////////////////////////////////////////////////////////\ntemplate<class _Number, class _F, class _R, class _Logger>\nauto make( _Number const omega\n         , Matrix<_F> const& E\n         , std::map<std::string, _R> const& cs \n         , _Logger & lg )\n{\n\tstatic_assert(std::is_floating_point<_F>::value, \"Energy must be real.\");\n\tstatic_assert(std::is_floating_point<_R>::value, \"Physical constants \" \n\t\t\"such as chemical potential and temperature must be real.\");\n\tusing Real = decltype( fermi_dirac( std::declval<_F>()\n\t                                  , std::declval<_R>() \n\t                                  , std::declval<_R>()\n\t                                  , std::declval<_R>() ));\n\tusing Complex = decltype( at( std::declval<std::size_t>()\n\t                            , std::declval<std::size_t>()\n\t                            , std::declval<_Number>()\n\t                            , std::declval<_F const*>() \n\t                            , std::declval<_R const*>() ));\n\n\tTCM_MEASURE( \"g_function::make<\" + boost::core::demangle(\n\t\ttypeid(Complex).name()) + \">()\" );\n\tLOG(lg, debug) << \"Calculating G for omega = \" << omega << \"...\";\n\trequire(__PRETTY_FUNCTION__, cs, \"temperature\");\n\trequire(__PRETTY_FUNCTION__, cs, \"chemical-potential\");\n\trequire(__PRETTY_FUNCTION__, cs, \"boltzmann-constant\");\n\tassert( is_column(E) == 1 );\n\tconst auto t  = cs.at(\"temperature\");\n\tconst auto mu = cs.at(\"chemical-potential\");\n\tconst auto kb = cs.at(\"boltzmann-constant\");\n\tconst auto N  = E.height();\n\n\tMatrix<Real> f{N, 1};\n\tstd::transform( E.data(), E.data() + N, f.data()\n\t              , [t, mu, kb](auto Ei) noexcept\n\t                { return fermi_dirac(Ei, t, mu, kb); } );\n\tMatrix<Complex> G{N, N};\n\tfor (std::size_t j = 0; j < N; ++j) {\n\t\tfor (std::size_t i = 0; i < N; ++i) {\n\t\t\tG(i,j) = at(i, j, omega, E.data(), f.data());\n\t\t}\n\t}\n\n\tLOG(lg, debug) << \"Successfully calculated G.\";\n\treturn G;\n}\n\n\n} // namespace g_function\n\n\n\n\n\n///////////////////////////////////////////////////////////////////////////////\n/// Defines tools to compute \\f$ \\chi(\\omega) \\f$ matrix.\n///////////////////////////////////////////////////////////////////////////////\nnamespace chi_function {\n\n///////////////////////////////////////////////////////////////////////////////\n/// \\brief Calculates \\f$ \\chi_{a,b}(\\omega) \\f$.\n\n/// We compute \\f$ \\chi_{a,b}(\\omega) \\f$ as\n/// \\f[ \\begin{aligned}\n///         A &:= \\psi_a \\circ \\psi_b^*, \n///         \\text{ i.e. } A_i = \\psi_{i,a}\\cdot\\psi{i,b}^* \\\\ \\text{}\n///         \\chi_{a,b}(\\omega) &= A^\\dagger \\times G(\\omega) \\times A. \n///     \\end{aligned}\n/// \\f]\n/// \n/// Hadamard product \\f$ \\circ \\f$ is computed using `std::transform`, which\n/// can easily be parallelized using GNU parallel mode of the `stdlibc++`.\n/// Matrix-vector products are calculated by first calling `?GEMV` and then\n/// `?DOTC`. Intel MKL has a highly parallel implementation of both of this\n/// functions.\n///\n/// \\param a    Row of the matrix.\n/// \\param b    Column of the matrix.\n/// \\param Psi  Eigenstates of the system.\n/// \\param G    G function calculated by calling g_function::make().\n///\n/// \\returns    \\f$ \\chi_{a,b}(\\omega) \\f$.\n/// \\exception  May throw if memory allocations or LAPACK operations fail.\n///////////////////////////////////////////////////////////////////////////////\ntemplate <class _F, class _C>\nauto at( std::size_t const a, std::size_t const b\n       , Matrix<_F> const& Psi, Matrix<_C> const& G )\n{\n\tTCM_MEASURE( \"chi_function::at<\" + boost::core::demangle(\n\t\ttypeid(_F).name()) + \", \" + boost::core::demangle(\n\t\ttypeid(_C).name()) + \">()\" );\n\tusing Complex = std::common_type_t<_F, _C>;\n\n\tconst auto N = Psi.height();\n\tMatrix<Complex>    A{N, 1};\n\tMatrix<Complex> temp{N, 1};\n\n\tstd::transform( Psi.cbegin_row(a), Psi.cend_row(a)\n\t              , Psi.cbegin_row(b)\n\t              , A.data()\n\t              , [](auto x, auto y) { return x * std::conj(y); } );\n\tblas::gemv( blas::Operator::T\n\t          , Complex{1}, G, A\n\t          , Complex{0}, temp );\n\treturn Complex{2} * blas::dot(A, temp);\n}\n\nnamespace {\n// For the case that eigenstates are actually real.\ntemplate<class _Number, class _F, class _R, class _Logger>\nauto make_impl( _Number const omega\n              , Matrix<_F> const& E\n              , Matrix<_F> const& Psi\n              , std::map<std::string, _R> const& cs\n              , _Logger & lg )\n{\n\tstatic_assert(std::is_floating_point<_F>::value, \"Energy must be real.\");\n\tstatic_assert(std::is_floating_point<_R>::value, \"Physical constants \" \n\t\t\"such as chemical potential and temperature must be real.\");\n\tTCM_MEASURE( \"chi_function::make_impl<\" + boost::core::demangle(\n\t\ttypeid(_F).name()) + \">()\" );\n\tauto const N = E.height();\n\tauto const G = g_function::make(omega, E, cs, lg);\n\n\tusing T = decltype( at( std::declval<std::size_t>()\n\t                      , std::declval<std::size_t>()\n\t                      , std::declval<Matrix<_F>>()\n\t                      , std::declval<decltype(G)>() ));\n\tMatrix<T> Chi{N, N};\n\n\tauto const _total_points_ = static_cast<double>(N * (N - 1) / 2);\n\tauto _start_ = std::chrono::system_clock::now();\n\t// fill the diagonal\n\tfor (std::size_t i = 0; i < N; ++i) {\n\t\t\tif ((_start_ - std::chrono::system_clock::now()) >\n\t\t\t\tstd::chrono::minutes{5}) {\n\t\t\t\t\n\t\t\t\tLOG(lg, info) << \"at \" << std::round((i + 1) / _total_points_)\n\t\t\t\t              << \"% ...\" << std::flush;\n\t\t\t\t_start_ = std::chrono::system_clock::now();\n\t\t\t}\n\t\t\tChi(i, i) = at(i, i, Psi, G);\n\t}\n\t// calculate upper triangle\n\tfor (std::size_t j = 0; j < N; ++j) {\n\t\tfor (std::size_t i = 0; i < j; ++i) {\n\t\t\tif ((_start_ - std::chrono::system_clock::now()) >\n\t\t\t\tstd::chrono::minutes{5}) {\n\t\t\t\t\n\t\t\t\tLOG(lg, info) << \"at \" << std::round((N + (i + 1)* (j + 1)) \n\t\t\t\t\t/ _total_points_)\n\t\t\t\t              << \"% ...\" << std::flush;\n\t\t\t\t_start_ = std::chrono::system_clock::now();\n\t\t\t}\n\t\t\tChi(i, j) = at(i, j, Psi, G);\n\t\t\tChi(j, i) = Chi(i, j);\n\t\t}\n\t}\n\treturn Chi;\n}\n\n// For the case that eigenstates are complex.\ntemplate<class _Number, class _F, class _R, class _Logger>\nauto make_impl( _Number const omega\n              , Matrix<_F> const& E\n              , Matrix<std::complex<_F>> const& Psi\n              , std::map<std::string, _R> const& cs\n              , _Logger & lg )\n{\n\tstatic_assert(std::is_floating_point<_F>::value, \"Energy must be real.\");\n\tstatic_assert(std::is_floating_point<_R>::value, \"Physical constants \" \n\t\t\"such as chemical potential and temperature must be real.\");\n\tTCM_MEASURE( \"chi_function::make_impl<\" + boost::core::demangle(\n\t\ttypeid(std::complex<_F>).name()) + \">()\" );\n\tauto const N = E.height();\n\tauto const G = g_function::make(omega, E, cs, lg);\n\n\tusing T = decltype( at( std::declval<std::size_t>()\n\t                      , std::declval<std::size_t>()\n\t                      , std::declval<Matrix<std::complex<_F>>>()\n\t                      , std::declval<decltype(G)>() ));\n\tMatrix<T> Chi{N, N};\n\n\tauto const _total_points_ = static_cast<double>(N * N);\n\tauto _start_ = std::chrono::system_clock::now();\n\tfor (std::size_t j = 0; j < N; ++j) {\n\t\tfor (std::size_t i = 0; i < N; ++i) {\n\t\t\tif ((_start_ - std::chrono::system_clock::now()) >\n\t\t\t\tstd::chrono::minutes{5}) {\n\t\t\t\t\n\t\t\t\tLOG(lg, info) << \"at \" << std::round(((i + 1) * (j + 1)) / _total_points_)\n\t\t\t\t              << \"% ...\" << std::flush;\n\t\t\t\t_start_ = std::chrono::system_clock::now();\n\t\t\t}\n\t\t\tChi(i, j) = at(i, j, Psi, G);\n\t\t}\n\t}\n\treturn Chi;\n}\n} // end unnamed namespace\n\n\n///////////////////////////////////////////////////////////////////////////////\n/// \\brief Calculates \\f$ \\chi(\\omega) \\f$.\n\n/// First, calculates \\f$ G(\\omega) \\f$ by calling tcm::g_function::make and\n/// then computes each matrix element by calling at().\n/// \\tparam _Number   Some abstract field.\n/// \\tparam _F        Complex or real field.\n/// \\tparam _C        Complex field.\n/// \\tparam _F        Real field.\n/// \\tparam _Logger   Type of the logger. \n/// \\param omega      Frequency \\f$ \\omega \\f$ at which to calculate \n///                   \\f$\\chi\\f$.\n/// \\param E          Eigenenergies of the system.\n/// \\param Psi        Eigenstates of the system.\n/// \\param cs         Constants. \n/// \\param lg         Logger object.\n///\n/// \\returns \\f$ \\chi(\\omega) \\f$ as a Matrix<_C>.\n/// \\exception May throw.\n///////////////////////////////////////////////////////////////////////////////\ntemplate<class _Number, class _F, class _C, class _R, class _Logger>\nauto make( _Number const omega\n         , Matrix<_F> const& E\n         , Matrix<_C> const& Psi\n         , std::map<std::string, _R> const& cs\n         , _Logger & lg )\n{\n\tTCM_MEASURE( \"chi_function::make<\" + boost::core::demangle(\n\t\ttypeid(_C).name()) + \">()\" );\n\tLOG(lg, debug) << \"Calculating chi for omega = \" << omega << \"...\";\n\n\tconst auto N = E.height();\n\tassert( is_column(E) );\n\tassert( is_square(Psi) );\n\tassert( N == Psi.height() );\n\n\tauto const Chi = make_impl(omega, E, Psi, cs, lg);\n\tLOG(lg, debug) << \"Successfully calculating chi.\";\n\treturn Chi;\n}\n\n\n} // namespace chi_function\n\n\n\n///////////////////////////////////////////////////////////////////////////////\n/// \\brief Defines tools to calculate the Coulomb interaction potential.\n///////////////////////////////////////////////////////////////////////////////\nnamespace coulomb {\n\nnamespace {\n///////////////////////////////////////////////////////////////////////////////\n/// \\brief Computes the distance between two points in \\f$ F^3 \\f$.\n///////////////////////////////////////////////////////////////////////////////\ntemplate<class _F>\nauto distance(std::array<_F, 3> const& v, std::array<_F, 3> const& w)\n{\n\treturn std::sqrt( std::pow(std::abs(v[0] - w[0]), 2)\n\t                + std::pow(std::abs(v[1] - w[1]), 2)\n\t                + std::pow(std::abs(v[2] - w[2]), 2)\n\t                );\n}\n} // unnamed namespace\n\n\n///////////////////////////////////////////////////////////////////////////////\n/// \\brief Calculates \\f$ V_{i,j} \\f$.\n\n/// Potential is calculated as following\n/// \\f[ V_{i,j} = \\left\\{ \n///     \\begin{aligned}\n///         &\\frac{e}{4\\pi\\varepsilon_0|\\mathbf{r_i} - \\mathbf{r_j}|}\n///              , &\\text{if } i \\neq j, \\\\ \\text{}\n///         &V_0, &\\text{if } i = j.\n///     \\end{aligned}\n///     \\right.\n/// \\f]\n/// \n/// \\tparam _F        Real field.\n/// \\tparam _R        Another real field.\n/// \\param i          Index of the first atom, i.e. row of the matrix.\n/// \\param j          Index of the second atom,.i.e. column of the matrix.\n/// \\param positions  Positions of the atoms, in __meters__.\n/// \\param e          Elementary charge, in Coulombs.\n/// \\param pi         \\f$\\pi\\f$.\n/// \\param eps0       \\f$\\varepsilon_0\\f$.\n/// \\param v0         Self-interaction potential \\f$V_0\\f$, in eV.\n///\n/// \\returns Potential in eV.\n/// \\exceptions Should not throw.\n///////////////////////////////////////////////////////////////////////////////\ntemplate<class _F, class _R>\nauto at( std::size_t const i, std::size_t const j\n       , std::vector<std::array<_F, 3>> const& positions\n       , _R const e\n       , _R const pi\n       , _R const eps0\n       , _R const v0 ) noexcept\n{\n\treturn (i == j)\n\t\t? v0\n\t\t: e / (_R{4.0} * pi * eps0 * distance(positions[i], positions[j]));\n}\n\n\n\n///////////////////////////////////////////////////////////////////////////////\n/// \\brief Construct an Elemental-like matrix \\f$ V \\f$, representing the \n/// Coulomb potential.\n\n/// \\tparam _T       Element type of the output Matrix.\n/// \\tparam _F       Real field.\n/// \\tparam _R       Another real field.\n/// \\tparam _Logger  The logger type.\n/// \\param positions Array with positions of atoms.\n/// \\param cs        Constants. `elementary-charge`, `vacuum-permittivity`, \n///                  `pi` and `self-interaction-potential` are needed.\n/// \\param lg        The logger.\n///\n/// \\return Matrix describing the Coulomb interaction.\n/// \\exception May throw.\n///////////////////////////////////////////////////////////////////////////////\ntemplate<class _T, class _F, class _R, class _Logger>\nauto make( std::vector<std::array<_F, 3>> const& positions\n         , std::map<std::string, _R> const& cs \n         , _Logger & lg ) -> Matrix<_T>\n{\n\tTCM_MEASURE( \"coulomb::make<\" + boost::core::demangle(\n\t\ttypeid(_T).name()) + \">()\" );\n\tLOG(lg, debug) << \"Calculating V...\";\n\n\trequire(__PRETTY_FUNCTION__, cs, \"elementary-charge\");\n\trequire(__PRETTY_FUNCTION__, cs, \"pi\");\n\trequire(__PRETTY_FUNCTION__, cs, \"vacuum-permittivity\");\n\trequire(__PRETTY_FUNCTION__, cs, \"self-interaction-potential\");\n\n\tauto const N         = positions.size();\n\tauto const e         = cs.at(\"elementary-charge\");\n\tauto const pi        = cs.at(\"pi\");\n\tauto const eps0      = cs.at(\"vacuum-permittivity\");\n\tauto const v0        = cs.at(\"self-interaction-potential\");\n\n\tauto const V = build_matrix\n\t\t( N, N\n\t\t, [&positions, e, pi, eps0, v0] (auto i, auto j)\n\t\t  { return boost::numeric_cast<_T>(\n\t\t        at(i, j, positions, e, pi, eps0, v0)\n\t\t\t);\n\t\t  }\n\t\t);\n\n\tLOG(lg, debug) << \"Successfully calculated V.\";\n\treturn V;\n}\n\n\n} // namespace coulomb\n\n\n\n\n\n\n\n///////////////////////////////////////////////////////////////////////////////\n/// \\brief Defines tools to compute the dielectric function.\n///////////////////////////////////////////////////////////////////////////////\nnamespace dielectric_function {\n\n\n///////////////////////////////////////////////////////////////////////////////\n/// \\brief Calculates the dielectric function matrix \\f$\\epsilon(\\omega)\\f$.\n///////////////////////////////////////////////////////////////////////////////\ntemplate< class _Number, class _F, class _C, class _R, class _T, class _Logger>\nauto make( _Number const omega\n         , Matrix<_F> const& E\n         , Matrix<_C> const& Psi\n         , Matrix<_T> const& V\n         , std::map<std::string, _R> const& cs \n         , _Logger & lg )\n{\n\tTCM_MEASURE( \"dielectric_function::make<\" + boost::core::demangle(\n\t\ttypeid(_C).name()) + \">()\" );\n\tLOG(lg, debug) << \"Calculating epsilon for omega = \" << omega << \"...\";\n\n\tconst auto N = E.height();\n\tassert( is_column(E) );\n\tassert( is_square(Psi) );\n\tassert( is_square(V) );\n\tassert( Psi.height() == N );\n\tassert( V.height() == N );\n\n\tauto const Chi = chi_function::make(omega, E, Psi, cs, lg);\n\n\tstatic_assert(std::is_same<_T, typename decltype(Chi)::value_type>::value, \"\");\n\tMatrix<_T> epsilon{N, N};\n\tfor (std::size_t j = 0; j < N; ++j) {\n\t\tfor (std::size_t i = 0; i < N; ++i) {\n\t\t\tepsilon(i, j) = (i == j) ? 1.0 : 0.0;\n\t\t}\n\t}\n\n\tblas::gemm( blas::Operator::None, blas::Operator::None\n\t          , _T{-1.0}, V, Chi\n\t          , _T{ 1.0}, epsilon );\n\n\tLOG(lg, debug) << \"Successfully calculating epsilon.\";\n\treturn epsilon;\n}\n\n\n\n} // namespace dielectric function\n\n\n\n} // namespace tcm\n\n\n#endif // TCM_DIELECTRIC_FUNCTION_HPP\n", "meta": {"hexsha": "28bb72309854923bd41bf8d0cb47bd71f5bf3fad", "size": 19399, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/dielectric_function_v2.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/dielectric_function_v2.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/dielectric_function_v2.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": 35.0795660036, "max_line_length": 81, "alphanum_fraction": 0.5182225888, "num_tokens": 5158, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4768735985127838}}
{"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 gamma_oracle_example.cpp\n * @brief\n * @author Robert Rosolek\n * @version 1.0\n * @date 2014-6-6\n */\n\n#include \"paal/auctions/auction_components.hpp\"\n#include \"paal/data_structures/fraction.hpp\"\n\n#include <boost/optional/optional.hpp>\n#include <boost/range/algorithm/copy.hpp>\n\n#include <cassert>\n#include <iostream>\n#include <utility>\n#include <vector>\n\n//! [Gamma Oracle Auction Components Example]\n\nnamespace pa = paal::auctions;\nnamespace pds = paal::data_structures;\n\nusing Bidder = std::string;\nusing Item = std::string;\nusing Items = std::vector<Item>;\nusing Value = int;\nusing Frac = pds::fraction<Value, Value>;\n\nconst std::vector<Bidder> bidders {\"Pooh Bear\", \"Rabbit\"};\n\nconst Items items {\"honey\", \"baby carrot\", \"carrot\", \"jam\"};\n\nconst int gamma_val = 2;\n\nstruct gamma_oracle_func {\n      template <class GetPrice, class Threshold>\n      boost::optional<std::pair<Items, Frac>>\n      operator()(Bidder bidder, GetPrice get_price, Threshold z) const {\n\n          if (bidder == \"Pooh Bear\") {\n              const Value val = 10;\n              if (val <= z) return boost::none;\n              return std::make_pair(Items{\"honey\"}, Frac(get_price(\"honey\"), val - z));\n          }\n\n          assert(bidder == \"Rabbit\");\n\n          const Value baby_val = 2, val = 3;\n          auto const baby_price = get_price(\"baby carrot\");\n          auto const price = get_price(\"carrot\");\n          auto const baby_frac = Frac(baby_price, baby_val - z),\n          frac = Frac(price, val - z),\n          both_frac = Frac(baby_price + price, baby_val + val - z);\n\n          auto check = [=](Frac candidate, Frac other1, Frac other2) {\n            if (candidate.den <= 0) return false;\n            auto check_single = [=](Frac candidate, Frac other) {\n                 return other.den <= 0 || candidate <= gamma_val * other;\n            };\n            return check_single(candidate, other1) && check_single(candidate, other2);\n          };\n\n          if (check(baby_frac, frac, both_frac))\n              return std::make_pair(Items{\"baby carrot\"}, baby_frac);\n          if (check(frac, baby_frac, both_frac))\n              return std::make_pair(Items{\"carrot\"}, frac);\n          if (check(both_frac, baby_frac, frac))\n              return std::make_pair(Items{\"baby carrot\", \"carrot\"}, both_frac);\n          return boost::none;\n      }\n};\n\n//! [Gamma Oracle Auction Components Example]\n\nint main()\n{\n   //! [Gamma Oracle Auction Create Example]\n   auto const auction = pa::make_gamma_oracle_auction_components(\n      bidders, items, gamma_oracle_func(), gamma_val\n   );\n   //! [Gamma Oracle Auction Create Example]\n\n   //! [Gamma Oracle Auction Use Example]\n   auto get_price_func = [](Item item) { return item == \"honey\" ? 5 : 2; };\n\n   std::cout << \"pooh bear buys: \";\n   auto got_pooh_bear =\n      auction.call<pa::gamma_oracle>(\"Pooh Bear\", get_price_func, 10);\n   if (!got_pooh_bear)\n      std::cout << \"nothing\";\n   else\n      boost::copy(got_pooh_bear->first, std::ostream_iterator<Item>(std::cout, \", \"));\n   std::cout << std::endl;\n\n   std::cout << \"rabbit oracle buys: \";\n   auto got_rabbit = auction.call<pa::gamma_oracle>(\"Rabbit\", get_price_func, 1);\n   if (!got_rabbit)\n      std::cout << \"nothing\";\n   else\n      boost::copy(got_rabbit->first, std::ostream_iterator<Item>(std::cout, \", \"));\n   std::cout << std::endl;\n\n   //! [Gamma Oracle Auction Use Example]\n   return 0;\n}\n", "meta": {"hexsha": "013e2973431ee307f795e8c1b5696c8e7d6e1379", "size": 3719, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/auctions/gamma_oracle_example.cpp", "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": "examples/auctions/gamma_oracle_example.cpp", "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": "examples/auctions/gamma_oracle_example.cpp", "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.3391304348, "max_line_length": 87, "alphanum_fraction": 0.6006991127, "num_tokens": 937, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4768735985127838}}
{"text": "/*\n@copyright Louis Dionne 2014\nDistributed under the Boost Software License, Version 1.0.\n(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n */\n\n#include <boost/hana/detail/assert.hpp>\n#include <boost/hana/integral.hpp>\nusing namespace boost::hana;\n\n\nint main() {\n    //! [main]\n    BOOST_HANA_CONSTANT_ASSERT(less(int_<-3>, int_<3>));\n    BOOST_HANA_CONSTANT_ASSERT(max(int_<-3>, long_<2>) == long_<2>);\n    BOOST_HANA_CONSTANT_ASSERT(min(int_<-3>, long_<2>) == int_<-3>);\n    //! [main]\n}\n", "meta": {"hexsha": "706b706fc876b806211c4f1ce41826721b7ce172", "size": 521, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/integral/orderable.cpp", "max_stars_repo_name": "rbock/hana", "max_stars_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-05-07T14:29:13.000Z", "max_stars_repo_stars_event_max_datetime": "2015-07-04T10:59:46.000Z", "max_issues_repo_path": "example/integral/orderable.cpp", "max_issues_repo_name": "rbock/hana", "max_issues_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/integral/orderable.cpp", "max_forks_repo_name": "rbock/hana", "max_forks_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4210526316, "max_line_length": 78, "alphanum_fraction": 0.6928982726, "num_tokens": 145, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7401743735019594, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.4768389145877817}}
{"text": "/* boost random/geometric_distribution.hpp header file\n *\n * Copyright Jens Maurer 2000-2001\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: geometric_distribution.hpp 49314 2008-10-13 09:00:03Z johnmaddock $\n *\n * Revision history\n *  2001-02-18  moved to individual header files\n */\n\n#ifndef BOOST_RANDOM_GEOMETRIC_DISTRIBUTION_HPP\n#define BOOST_RANDOM_GEOMETRIC_DISTRIBUTION_HPP\n\n#include <boost/config/no_tr1/cmath.hpp>          // std::log\n#include <cassert>\n#include <iostream>\n#include <boost/random/uniform_01.hpp>\n\nnamespace boost {\n\n#if defined(__GNUC__) && (__GNUC__ < 3)\n// Special gcc workaround: gcc 2.95.x ignores using-declarations\n// in template classes (confirmed by gcc author Martin v. Loewis)\n  using std::log;\n#endif\n\n// geometric distribution: p(i) = (1-p) * pow(p, i-1)   (integer)\ntemplate<class IntType = int, class RealType = double>\nclass geometric_distribution\n{\npublic:\n  typedef RealType input_type;\n  typedef IntType result_type;\n\n  explicit geometric_distribution(const RealType& p_arg = RealType(0.5))\n    : _p(p_arg)\n  {\n    assert(RealType(0) < _p && _p < RealType(1));\n    init();\n  }\n\n  // compiler-generated copy ctor and assignment operator are fine\n\n  RealType p() const { return _p; }\n  void reset() { }\n\n  template<class Engine>\n  result_type operator()(Engine& eng)\n  {\n#ifndef BOOST_NO_STDC_NAMESPACE\n    using std::log;\n    using std::floor;\n#endif\n    return IntType(floor(log(RealType(1)-eng()) / _log_p)) + IntType(1);\n  }\n\n#if !defined(BOOST_NO_OPERATORS_IN_NAMESPACE) && !defined(BOOST_NO_MEMBER_TEMPLATE_FRIENDS)\n  template<class CharT, class Traits>\n  friend std::basic_ostream<CharT,Traits>&\n  operator<<(std::basic_ostream<CharT,Traits>& os, const geometric_distribution& gd)\n  {\n    os << gd._p;\n    return os;\n  }\n\n  template<class CharT, class Traits>\n  friend std::basic_istream<CharT,Traits>&\n  operator>>(std::basic_istream<CharT,Traits>& is, geometric_distribution& gd)\n  {\n    is >> std::ws >> gd._p;\n    gd.init();\n    return is;\n  }\n#endif\n\nprivate:\n  void init()\n  {\n#ifndef BOOST_NO_STDC_NAMESPACE\n    using std::log;\n#endif\n    _log_p = log(_p);\n  }\n\n  RealType _p;\n  RealType _log_p;\n};\n\n} // namespace boost\n\n#endif // BOOST_RANDOM_GEOMETRIC_DISTRIBUTION_HPP\n\n", "meta": {"hexsha": "e457de44d313e776128730672e9c44d13d733a3e", "size": 2429, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/random/geometric_distribution.hpp", "max_stars_repo_name": "mike-code/boost_1_38_0", "max_stars_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-12-06T00:55:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T03:05:51.000Z", "max_issues_repo_path": "boost/random/geometric_distribution.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/random/geometric_distribution.hpp", "max_forks_repo_name": "mike-code/boost_1_38_0", "max_forks_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.7857142857, "max_line_length": 91, "alphanum_fraction": 0.7114038699, "num_tokens": 664, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.6442251064863698, "lm_q1q2_score": 0.4768389072030661}}
{"text": "#ifndef SEQUENTIAL_LINE_SEARCH_PREFERENTIAL_BAYESIAN_OPTIMIZER_HPP\n#define SEQUENTIAL_LINE_SEARCH_PREFERENTIAL_BAYESIAN_OPTIMIZER_HPP\n\n#include <Eigen/Core>\n#include <memory>\n#include <sequential-line-search/acquisition-function.hpp>\n#include <sequential-line-search/current-best-selection-strategy.hpp>\n#include <sequential-line-search/kernel-type.hpp>\n#include <utility>\n#include <vector>\n\nnamespace sequential_line_search\n{\n    class PreferenceRegressor;\n    class PreferenceDataManager;\n\n    std::vector<Eigen::VectorXd> GenerateRandomPoints(const int num_dims);\n\n    /// \\brief Optimizer class for performing preferential Bayesian optimization with discrete choice.\n    ///\n    /// \\details This optimizer requests discrete choice queries. In the current implementation, the number of choices\n    /// for each query is fixed to two (i.e., pairwise comparison). This class assumes that the search space is [0,\n    /// 1]^{D}.\n    class PreferentialBayesianOptimizer\n    {\n    public:\n        /// \\brief Construct an optimizer instance.\n        ///\n        /// \\param use_map_hyperparams When this is set true, the optimizer always perform the MAP estimation for the\n        /// GPR kernel hyperparameters. When this is set false, the optimizer performs the MAP estimation only for\n        /// goodness values.\n        PreferentialBayesianOptimizer(\n            const int                 num_dims,\n            const bool                use_map_hyperparams   = true,\n            const KernelType          kernel_type           = KernelType::ArdMatern52Kernel,\n            const AcquisitionFuncType acquisition_func_type = AcquisitionFuncType::ExpectedImprovement,\n            const std::function<std::vector<Eigen::VectorXd>(const int)>& initial_query_generator =\n                GenerateRandomPoints,\n            const CurrentBestSelectionStrategy current_best_selection_strategy =\n                CurrentBestSelectionStrategy::LargestExpectValue);\n\n        /// \\brief Specify (kernel and other) hyperparameter values.\n        ///\n        /// \\details When the MAP estimation is enabled, the specified kernel hyperparameters will be used as the median\n        /// of the prior distribution and the initial solution of the estimation. When the MAP estimation is not\n        /// enabled, these values will be directly used.\n        void SetHyperparams(const double kernel_signal_var            = 0.500,\n                            const double kernel_length_scale          = 0.500,\n                            const double noise_level                  = 0.005,\n                            const double kernel_hyperparams_prior_var = 0.250,\n                            const double btl_scale                    = 0.010);\n\n        /// \\brief Submit the result of the user's selection and update the internal surrogate model.\n        ///\n        /// \\param num_map_estimation_iters The number of iterations for the MAP estimation. When a non-positive value\n        /// (e.g., 0) is specified, this is heuristically set.\n        void SubmitFeedbackData(const int option_index, const int num_map_estimation_iters = 0);\n\n        /// \\brief Determine the preferential query for the next iteration by using an acquisition function.\n        void DetermineNextQuery(const int num_global_search_iters = 0, const int num_local_search_iters = 0);\n\n        /// \\brief Get the current options.\n        const std::vector<Eigen::VectorXd>& GetCurrentOptions() const { return m_current_options; }\n\n        /// \\brief Get the point that has the highest value among the observed points.\n        Eigen::VectorXd GetMaximizer() const;\n\n        double GetPreferenceValueMean(const Eigen::VectorXd& point) const;\n        double GetPreferenceValueStdev(const Eigen::VectorXd& point) const;\n        double GetAcquisitionFuncValue(const Eigen::VectorXd& point) const;\n\n        const Eigen::MatrixXd& GetRawDataPoints() const;\n\n        void DampData(const std::string& directory_path) const;\n\n        /// \\brief Set the hyperparameter in the GP-UCB algorithm.\n        ///\n        /// \\details This hyperparameter controls the trade-off of exploration and exploitation. Specifically, this\n        /// hyperparameter corresponds to the square root of the beta in [Srinivas et al. ICML '10].\n        ///\n        /// If the acquisition function is not GP-UCB, this value will not be used.\n        void SetGaussianProcessUpperConfidenceBoundHyperparam(const double hyperparam)\n        {\n            m_gaussian_process_upper_confidence_bound_hyperparam = hyperparam;\n        }\n\n    private:\n        const bool m_use_map_hyperparams;\n\n        const CurrentBestSelectionStrategy m_current_best_selection_strategy;\n\n        std::shared_ptr<PreferenceRegressor>   m_regressor;\n        std::shared_ptr<PreferenceDataManager> m_data;\n\n        /// \\details In the case of using pairwise comparison, the number of options is always two.\n        std::vector<Eigen::VectorXd> m_current_options;\n\n        double m_kernel_signal_var;\n        double m_kernel_length_scale;\n        double m_noise_level;\n        double m_kernel_hyperparams_prior_var;\n        double m_btl_scale;\n\n        const KernelType          m_kernel_type;\n        const AcquisitionFuncType m_acquisition_func_type;\n\n        double m_gaussian_process_upper_confidence_bound_hyperparam;\n    };\n} // namespace sequential_line_search\n\n#endif // SEQUENTIAL_LINE_SEARCH_PREFERENTIAL_BAYESIAN_OPTIMIZER_HPP\n", "meta": {"hexsha": "1f47be3245f4ba24a0038540f5a8a11be811e1fc", "size": 5426, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/sequential-line-search/preferential-bayesian-optimizer.hpp", "max_stars_repo_name": "yuki-koyama/sequential-line-search", "max_stars_repo_head_hexsha": "7f68ce6f3ccb63eee4e921b867bd1014e3f947ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 26.0, "max_stars_repo_stars_event_min_datetime": "2018-03-12T13:18:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T20:28:04.000Z", "max_issues_repo_path": "include/sequential-line-search/preferential-bayesian-optimizer.hpp", "max_issues_repo_name": "yuki-koyama/sequential-line-search", "max_issues_repo_head_hexsha": "7f68ce6f3ccb63eee4e921b867bd1014e3f947ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 37.0, "max_issues_repo_issues_event_min_datetime": "2018-04-05T23:42:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-13T03:52:42.000Z", "max_forks_repo_path": "include/sequential-line-search/preferential-bayesian-optimizer.hpp", "max_forks_repo_name": "yuki-koyama/sequential-line-search", "max_forks_repo_head_hexsha": "7f68ce6f3ccb63eee4e921b867bd1014e3f947ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2018-06-12T17:50:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-17T11:13:03.000Z", "avg_line_length": 48.4464285714, "max_line_length": 120, "alphanum_fraction": 0.6913011426, "num_tokens": 1080, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.6442251133170357, "lm_q1q2_score": 0.4768389048742338}}
{"text": "\ufeff// created by Mark O. Brown\n#include \"stdafx.h\"\n#include \"PictureControl.h\"\n#include <algorithm>\n#include <numeric>\n#include <boost/lexical_cast.hpp>\n#include <qlayout.h>\n\n\nPictureControl::PictureControl(bool histogramOption, Qt::TransformationMode mode)\n\t: histOption(histogramOption), /*QWidget(), */transformationMode(mode)\n\t, slider(Qt::Vertical, RangeSlider::DoubleHandles)\n{\n\tactive = true;\n\tif ( histOption ){\n\t\thorData.resize ( 1 );\n\t\tvertData.resize ( 1 );\n\t\tupdatePlotData ( );\n\t}\n\trepaint ();\n}\n\nvoid PictureControl::updatePlotData ( ){\n\tif ( !histOption ){\n\t\treturn;\n\t}\n\thorData[ 0 ].resize ( mostRecentImage_m.getCols ( ) );\n\tvertData[ 0 ].resize ( mostRecentImage_m.getRows ( ) );\n\tunsigned count = 0;\n\n\tstd::vector<long> dataRow;\n\tfor ( auto& data : horData[ 0 ] ){\n\t\tdata.x = count;\n\t\t// integrate the column\n\t\tdouble p = 0.0;\n\t\tfor ( auto row : range ( mostRecentImage_m.getRows ( ) ) ){\n\t\t\tp += mostRecentImage_m ( row, count );\n\t\t}\n\t\tcount++;\n\t\tdataRow.push_back ( p );\n\t}\n\tcount = 0;\n\tauto avg = std::accumulate ( dataRow.begin ( ), dataRow.end ( ), 0.0 ) / dataRow.size ( );\n\tfor ( auto& data : horData[ 0 ] ){\n\t\tdata.y = dataRow[ count++ ] - avg;\n\t}\n\tcount = 0;\n\tstd::vector<long> dataCol;\n\tfor ( auto& data : vertData[ 0 ] ){\n\t\tdata.x = count;\n\t\t// integrate the row\n\t\tdouble p = 0.0;\n\t\tfor ( auto col : range ( mostRecentImage_m.getCols ( ) ) ){\n\t\t\tp += mostRecentImage_m ( count, col );\n\t\t}\n\t\tcount++;\n\t\tdataCol.push_back ( p );\n\t}\n\tcount = 0;\n\tauto avgCol = std::accumulate ( dataCol.begin ( ), dataCol.end ( ), 0.0 ) / dataCol.size ( );\n\tfor ( auto& data : vertData[ 0 ] ){\n\t\tdata.y = dataCol[ count++ ] - avgCol;\n\t}\n}\n\n/*\n* initialize all controls associated with single picture.\n*/\nvoid PictureControl::initialize(std::string name, int width, int height, IChimeraQtWindow* parent, int picScaleFactorIn){\n\tQVBoxLayout* layout = new QVBoxLayout(this);\n\tlayout->setContentsMargins(0, 0, 0, 0);\n\tpicScaleFactor = picScaleFactorIn;\n\tif ( width < 100 ){\n\t\tthrower ( \"Pictures must be greater than 100 in width because this is the size of the max/min\"\n\t\t\t\t\t\t\t\t\t \"controls.\" );\n\t}\n\tif ( height < 100 ){\n\t\tthrower ( \"Pictures must be greater than 100 in height because this is the minimum height \"\n\t\t\t\t\t\t\t\t\t \"of the max/min controls.\" );\n\t}\n\tQHBoxLayout* layout1 = new QHBoxLayout(this);\n\tlayout1->setContentsMargins(0, 0, 0, 0);\n\tcoordinatesText = new QLabel(\"Coordinates: \", this);\n\tcoordinatesDisp = new QLabel(\"\", this);\n\tvalueText = new QLabel(\"; Value: \", this);\n\tvalueDisp = new QLabel(\"\", this);\n\tlayout1->addWidget(new QLabel(qstr(name),this));\n\tlayout1->addWidget(coordinatesText);\n\tlayout1->addWidget(coordinatesDisp);\n\tlayout1->addWidget(valueText);\n\tlayout1->addWidget(valueDisp);\n\tlayout1->addStretch();\n\n\tmaxWidth = width;\n\tmaxHeight = height;\n\tQHBoxLayout* layout2 = new QHBoxLayout(this);\n\tlayout2->setContentsMargins(0, 0, 0, 0);\n\tpic.setStyle(plotStyle::DensityPlotWithHisto);\n\tpic.init(parent,\"\");\n\tpic.plot->setMinimumSize(400, 350);\n\tpictureObject = new ImageLabel (parent);\t\n\t//connect (pictureObject, &ImageLabel::mouseReleased, [this](QMouseEvent* event) {handleMouse (event); });\n\tstd::vector<unsigned char> data (20000);\n\tfor (auto& pt : data){\n\t\tpt = rand () % 255;\n\t}\n\tslider.setRange(0, 4096);\n\tslider.setMaximumWidth(80);\n\tslider.setMaxLength(800);\n\tparent->connect (&slider, &RangeSliderIntg::smlValueChanged, [this]() {redrawImage (); });\n\tparent->connect (&slider, &RangeSliderIntg::lrgValueChanged, [this]() {redrawImage (); });\n\tlayout2->addWidget(pic.plot, 1);\n\tlayout2->addWidget(&slider, 0);\n\n\tconnect(pic.plot, &QCustomPlot::mouseMove, [this](QMouseEvent* event) {\n\t\thandleMouse(event); });\n\n\n\tlayout->addLayout(layout1);\n\tlayout->addLayout(layout2);\n\tlayout->addStretch();\n}\n\n\n\nbool PictureControl::isActive(){\n\treturn active;\n}\n\n\nvoid PictureControl::setSliderPositions(unsigned min, unsigned max){\n\tslider.upperSpinBox()->setValue(max);\n\tslider.lowerSpinBox()->setValue(min);\n\t//sliderMin.setValue ( min );\n\t//sliderMax.setValue ( max );\n}\n\n/*\n * Used during initialization & when used when transitioning between 1 and >1 pictures per repetition. \n * Sets the unscaled background area and the scaled area.\n */\nvoid PictureControl::setPictureArea( QPoint loc, int width, int height ){\n\t//// this is important for the control to know where it should draw controls.\n\t//auto& sBA = scaledBackgroundArea;\n\t//auto& px = loc.rx (), & py = loc.ry ();\n\t//unscaledBackgroundArea = { px, py, px + width, py + height };\n\t//// reserve some area for the texts.\n\t//unscaledBackgroundArea.setRight (unscaledBackgroundArea.right () - 100);\n\t//sBA = unscaledBackgroundArea;\n\t///*\n\t//sBA.left *= width;\n\t//sBA.right *= width;\n\t//sBA.top *= height;\n\t//sBA.bottom *= height;*/\n\t//if ( horGraph ){\n\t//\t//horGraph->setControlLocation ( { scaledBackgroundArea.left, scaledBackgroundArea.bottom }, \n\t//\t//\t\t\t\t\t\t\t   scaledBackgroundArea.right - scaledBackgroundArea.left, 65 );\n\t//}\n\t//if ( vertGraph ){\n\t//\t//vertGraph->setControlLocation ( { scaledBackgroundArea.left - 65, scaledBackgroundArea.bottom },\n\t//\t//\t\t\t\t\t\t\t      65, scaledBackgroundArea.bottom - scaledBackgroundArea.top );\n\t//}\n\t//double widthPicScale;\n\t//double heightPicScale;\n\t//auto& uIP = unofficialImageParameters;\n\t//double w_to_h_ratio = double (uIP.width ()) / uIP.height ();\n\t//double sba_w = sBA.right () - sBA.left ();\n\t//double sba_h = sBA.bottom () - sBA.top ();\n\t//if (w_to_h_ratio > sba_w/sba_h){\n\t//\twidthPicScale = 1;\n\t//\theightPicScale = (1.0/ w_to_h_ratio) * (sba_w / sba_h);\n\t//}\n\t//else{\n\t//\theightPicScale = 1;\n\t//\twidthPicScale = w_to_h_ratio / (sba_w / sba_h);\n\t//}\n\n\t//unsigned long picWidth = unsigned long( (sBA.right () - sBA.left())*widthPicScale );\n\t//unsigned long picHeight = (sBA.bottom() - sBA.top())*heightPicScale;\n\t//QPoint mid = { (sBA.left () + sBA.right ()) / 2, (sBA.top () + sBA.bottom ()) / 2 };\n\t//pictureArea.setLeft(mid.x() - picWidth / 2);\n\t//pictureArea.setRight(mid.x() + picWidth / 2);\n\t//pictureArea.setTop(mid.y() - picHeight / 2);\n\t//pictureArea.setBottom(mid.y() + picHeight / 2);\n\t//\n\t//if (pictureObject){\n\t//\tpictureObject->setGeometry (px, py, width, height);\n\t//\tpictureObject->raise ();\n\t//}\n}\n\n\n/* used when transitioning between single and multiple pictures. It sets it based on the background size, so make \n * sure to change the background size before using this.\n * ********/\nvoid PictureControl::setSliderControlLocs (QPoint pos, int height){\n\t//sliderMin.reposition ( pos, height);\n\t//pos.rx() += 25;\n\t//sliderMax.reposition ( pos, height );\n}\n\n/* used when transitioning between single and multiple pictures. It sets it based on the background size, so make\n* sure to change the background size before using this.\n* ********/\n\n/*\n * change the colormap used for a given picture.\n */\nvoid PictureControl::updatePalette( QVector<QRgb> palette ){\n\timagePalette = palette;\n}\n\n\n/*\n * called when the user changes either the min or max edit.\n */\nvoid PictureControl::handleEditChange( int id ){\n\t//if ( id == sliderMax.getEditId() ){\n\t//\tsliderMax.handleEdit ( );\n\t//}\n\t//if ( id == sliderMin.getEditId() ){\n\t//\tsliderMin.handleEdit ( );\n\t//}\n}\n\n\nstd::pair<unsigned, unsigned> PictureControl::getSliderLocations(){\n\treturn { slider.getSilderSmlVal(), slider.getSilderLrgVal() };\n}\n\n\n\n\n\n/*\n * Recalculate the grid of pixels, which needs to be done e.g. when changing number of pictures or re-sizing the \n * picture. Does not draw the grid.\n */\nvoid PictureControl::recalculateGrid(imageParameters newParameters){\n\t// not strictly necessary.\n\tgrid.clear();\n\t// find the maximum dimension.\n\tunofficialImageParameters = newParameters;\n\tdouble widthPicScale;\n\tdouble heightPicScale;\n\t/*if (unofficialImageParameters.width ()> unofficialImageParameters.height())\n\t{\n\t\twidthPicScale = 1;\n\t\theightPicScale = double(unofficialImageParameters.height()) / unofficialImageParameters.width();\n\t}\n\telse\n\t{\n\t\theightPicScale = 1;\n\t\twidthPicScale = double(unofficialImageParameters.width()) / unofficialImageParameters.height();\n\t}*/\n\tauto& uIP = unofficialImageParameters;\n\tdouble w_to_h_ratio = double (uIP.width ()) / uIP.height ();\n\tauto& sBA = scaledBackgroundArea;\n\tdouble sba_w = sBA.right () - sBA.left ();\n\tdouble sba_h = sBA.bottom () - sBA.top ();\n\tif (w_to_h_ratio > sba_w / sba_h){\n\t\twidthPicScale = 1;\n\t\theightPicScale = (1.0 / w_to_h_ratio) * (sba_w / sba_h);\n\t}\n\telse{\n\t\theightPicScale = 1;\n\t\twidthPicScale = w_to_h_ratio / (sba_w / sba_h);\n\t}\n\n\tlong width = long((scaledBackgroundArea.right () - scaledBackgroundArea.left ())*widthPicScale);\n\tlong height = long((scaledBackgroundArea.bottom () - scaledBackgroundArea.top ())*heightPicScale);\n\tQPoint mid = { (scaledBackgroundArea.left () + scaledBackgroundArea.right ()) / 2,\n\t\t\t\t  (scaledBackgroundArea.top () + scaledBackgroundArea.bottom ()) / 2 };\n\tpictureArea.setLeft (mid.x () - width / 2);\n\tpictureArea.setRight (mid.x () + width / 2);\n\tpictureArea.setTop (mid.y () - height / 2);\n\tpictureArea.setBottom (mid.y () + height / 2);\n\n\tgrid.resize(newParameters.width());\n\tfor (unsigned colInc = 0; colInc < grid.size(); colInc++){\n\t\tgrid[colInc].resize(newParameters.height());\n\t\tfor (unsigned rowInc = 0; rowInc < grid[colInc].size(); rowInc++){\n\t\t\t// for all 4 pictures...\n\t\t\tgrid[colInc][rowInc].setLeft(int(pictureArea.left()\n\t\t\t\t\t\t\t\t\t\t\t + (double)(colInc+1) * (pictureArea.right () - pictureArea.left ())\n\t\t\t\t\t\t\t\t\t\t\t / (double)grid.size( ) + 2));\n\t\t\tgrid[colInc][rowInc].setRight(int(pictureArea.left()\n\t\t\t\t+ (double)(colInc + 2) * (pictureArea.right () - pictureArea.left ()) / (double)grid.size() + 2));\n\t\t\tgrid[colInc][rowInc].setTop(int(pictureArea.top ()\n\t\t\t\t+ (double)(rowInc)* (pictureArea.bottom () - pictureArea.top ()) / (double)grid[colInc].size()));\n\t\t\tgrid[colInc][rowInc].setBottom(int(pictureArea.top()\n\t\t\t\t+ (double)(rowInc + 1)* (pictureArea.bottom () - pictureArea.top ()) / (double)grid[colInc].size()));\n\t\t}\n\t}\n}\n\n/* \n * sets the state of the picture and changes visibility of controls depending on that state.\n */\nvoid PictureControl::setActive( bool activeState )\n{\n\tif (!coordinatesText || !coordinatesDisp)\t{\n\t\treturn;\n\t}\n\tactive = activeState;\n\tif (!active){\n\t\tthis->hide();\n\t\tslider.hide();\n\t\tcoordinatesText->hide();\n\t\tcoordinatesDisp->hide();\n\t\tvalueText->hide();\n\t\tvalueDisp->hide();\n\t}\n\telse{\n\t\tthis->show();\n\t\tslider.show();\n\t\tcoordinatesText->show();\n\t\tcoordinatesDisp->show();\n\t\tvalueText->show();\n\t\tvalueDisp->show();\n\t}\n}\n\n/*\n * redraws the background and image. \n */\nvoid PictureControl::redrawImage(){\n\tif ( active && mostRecentImage_m.size ( ) != 0 ){\n\t\tdrawBitmap (mostRecentImage_m, mostRecentAutoscaleInfo, mostRecentSpecialMinSetting,\n\t\t\tmostRecentSpecialMaxSetting, mostRecentGrids, mostRecentPicNum, true);\n\t}\n}\n\nvoid PictureControl::resetStorage(){\n\tmostRecentImage_m = Matrix<long>(0,0);\n}\n\nvoid PictureControl::setSoftwareAccumulationOption ( softwareAccumulationOption opt ){\n\tsaOption = opt;\n\taccumPicData.clear ( );\n\taccumNum = 0;\n}\n\n/* \n  Version of this from the Basler camera control Code. I will consolidate these shortly.\n*/\nvoid PictureControl::drawBitmap ( const Matrix<long>& picData, std::tuple<bool, int, int> autoScaleInfo, \n\t\t\t\t\t\t\t\t  bool specialMin, bool specialMax, std::vector<atomGrid> grids, unsigned pictureNumber,\n\t\t\t\t\t\t\t\t  bool includingAnalysisMarkers ){\n\tmostRecentImage_m = picData;\n\tmostRecentPicNum = pictureNumber;\n\tmostRecentGrids = grids;\n\n\tauto minColor = slider.getSilderSmlVal( );\n\tauto maxColor = slider.getSilderLrgVal( );\n\tmostRecentAutoscaleInfo = autoScaleInfo;\n\tint pixelsAreaWidth = pictureArea.right () - pictureArea.left () + 1;\n\tint pixelsAreaHeight = pictureArea.bottom () - pictureArea.top () + 1;\n\tint dataWidth = grid.size ( );\n\t// first element containst whether autoscaling or not.\n\t//long colorRange;\n\t//if ( std::get<0> ( autoScaleInfo ) ){\n\t//\t// third element contains max, second contains min.\n\t//\tcolorRange = std::get<2> ( autoScaleInfo ) - std::get<1> ( autoScaleInfo );\n\t//\tminColor = std::get<1> ( autoScaleInfo );\n\t//}\n\t//else{\n\t//\tcolorRange = maxColor - minColor;\n\t//\tminColor = minColor;\n\t//\t//colorRange = sliderMax.getValue ( ) - sliderMin.getValue ( );\n\t//\t//minColor = sliderMin.getValue ( );\n\t//}\n\t// assumes non-zero size...\n\tif ( grid.size ( ) == 0 ){\n\t\tthrower  ( \"Tried to draw bitmap without setting grid size!\" );\n\t}\n\tint dataHeight = grid[ 0 ].size ( );\n\tint totalGridSize = dataWidth * dataHeight;\n\tif ( picData.size ( ) != totalGridSize ){\n\t\tthrower  ( \"Picture data didn't match grid size!\" );\n\t}\n\t\n\tint width = picData.getCols();\n\tint height = picData.getRows();\n\tstd::vector<plotDataVec> ddvec(height);\n\tfor (size_t idx = 0; idx < height; idx++)\n\t{\n\t\tddvec[idx].reserve(width);\n\t\tfor (size_t idd = 0; idd < width; idd++)\n\t\t{\n\t\t\tddvec[idx].push_back(dataPoint{ 0,double(picData(idx,idd)),0 }); // x,y,err\n\t\t}\n\t}\n\tpic.setData(ddvec);\n\n\t//float yscale = ( 256.0f ) / (float) colorRange;\n\t//std::vector<uchar> dataArray2 ( dataWidth * dataHeight, 255 );\n\t//int iTemp;\n\t//double dTemp = 1;\n\t//const int picPaletteSize = 256;\n\t//for (int heightInc = 0; heightInc < dataHeight; heightInc++){\n\t//\tfor (int widthInc = 0; widthInc < dataWidth; widthInc++){\n\t//\t\tdTemp = ceil (yscale * double(picData (heightInc, widthInc) - minColor));\n\t//\t\tif (dTemp <= 0)\t{\n\t//\t\t\t// raise value to zero which is the floor of values this parameter can take.\n\t//\t\t\tiTemp = 1;\n\t//\t\t}\n\t//\t\telse if (dTemp >= picPaletteSize - 1)\t{\n\t//\t\t\t// round to maximum value.\n\t//\t\t\tiTemp = picPaletteSize - 2;\n\t//\t\t}\n\t//\t\telse{\n\t//\t\t\t// no rounding or flooring to min or max needed.\n\t//\t\t\tiTemp = (int)dTemp;\n\t//\t\t}\n\t//\t\t// store the value.\n\t//\t\tdataArray2[widthInc + heightInc * dataWidth] = (unsigned char)iTemp;\n\t//\t}\n\t//}\n\t//int sf = picScaleFactor;\n\t//QImage img (sf * dataWidth, sf * dataHeight, QImage::Format_Indexed8);\n\t//img.setColorTable (imagePalette);\n\t//img.fill (0);\n\t//for (auto rowInc : range(dataHeight)){\n\t//\tstd::vector<uchar> singleRow (sf * dataWidth);\n\t//\tfor (auto val : range (dataWidth)){\n\t//\t\tfor (auto rep : range (sf)) {\n\t//\t\t\tsingleRow[sf * val + rep] = dataArray2[rowInc * dataWidth + val];\n\t//\t\t}\n\t//\t}\n\t//\tfor (auto repRow : range (sf)){\n\t//\t\tmemcpy (img.scanLine (rowInc * sf + repRow), singleRow.data(), img.bytesPerLine ());\n\t//\t}\n\t//}\n\t// need to convert to an rgb format in order to draw on top. drawing on top using qpainter isn't supported with the \n\t// indexed format. \n\t//img = img.convertToFormat (QImage::Format_RGB888);\n\t//QPainter painter;\n\t//painter.begin (&img);\n\t//drawDongles (painter, grids, pictureNumber, includingAnalysisMarkers);\n\t//painter.end ();\t\n\t//// seems like this doesn't *quite* work for some reason, hence the extra number here to adjust\n\t//if (img.width () / img.height () > (pictureObject->width () / pictureObject->height ())-0.1)\t{\n\t//\tpictureObject->setPixmap (QPixmap::fromImage (img).scaledToWidth (pictureObject->width (), transformationMode));\n\t//}\n\t//else {\n\t//\tpictureObject->setPixmap (QPixmap::fromImage (img).scaledToHeight (pictureObject->height (), transformationMode));\n\t//}\n\t// //update this with the new picture.\n\t//setHoverValue ( );\n}\n\nvoid PictureControl::setHoverValue( ){\n\tint loc = (grid.size( ) - 1 - selectedLocation.column) * grid.size( ) + selectedLocation.row;\n\tif ( loc >= mostRecentImage_m.size( ) )\t{\n\t\treturn;\n\t}\n\tvalueDisp->setText( cstr( mostRecentImage_m.data[loc] ) );\n}\n\nvoid PictureControl::handleMouse (QMouseEvent* event){\n\tauto vec = pic.handleMousePosOnCMap(event);\n\tcoordinatesDisp->setText(\"( \" + qstr(int(vec[0])) + \" , \" + qstr(int(vec[1])) + \" )\");\n\tvalueDisp->setText(qstr(int(vec[2])));\n}\n\n/* \n * draw the grid which outlines where each pixel is.  Especially needs to be done when selecting pixels and no picture\n * is displayed. \n */\nvoid PictureControl::drawGrid(QPainter& painter){\n\tif (!active){\n\t\treturn;\n\t}\n\tif (grid.size() != 0){\n\t\t// hard set to 5000. Could easily change this to be able to see finer grids. Tested before and 5000 seems \n\t\t// reasonable.\n\t\tif (grid.size() * grid.front().size() > 5000){\n\t\t\treturn;\n\t\t}\n\t}\n\t// draw rectangles indicating where the pixels are.\n\tfor (unsigned columnInc = 0; columnInc < grid.size(); columnInc++){\n\t\tfor (unsigned rowInc = 0; rowInc < grid[columnInc].size(); rowInc++){\n\t\t\tunsigned pixelRow = picScaleFactor * grid[columnInc][rowInc].top();\n\t\t\tunsigned pixelColumn = picScaleFactor * grid[columnInc][rowInc].left();\n\t\t\tQRect rect = QRect (QPoint (pixelColumn, pixelRow),\n\t\t\t\t\t\t QPoint (pixelColumn + picScaleFactor - 2, pixelRow + picScaleFactor - 2));\n\t\t\tpainter.drawRect (rect);\n\t\t}\n\t}\n}\n\n/*\n * draws the circle which denotes the selected pixel that the user wants to know the counts for. \n */\nvoid PictureControl::drawCircle(coordinate selectedLocation, QPainter& painter){\n\tif (grid.size() == 0){\n\t\t// this hasn't been set yet, presumably this got called by the camera window as the camera window\n\t\t// was drawing itself before the control was initialized.\n\t\treturn;\n\t}\n\tif (!active){\n\t\t// don't draw anything if the window isn't active.\n\t\treturn;\n\t}\n\tQRect smallRect( selectedLocation.column * picScaleFactor, selectedLocation.row * picScaleFactor, \n\t\t\t\t\t picScaleFactor-1, picScaleFactor-1 );\n\tpainter.drawEllipse (smallRect);\n}\n\nvoid PictureControl::drawPicNum( unsigned picNum, QPainter& painter ){\n\tQFont font = painter.font ();\n\t// I think this is the font height in pixels on the pixmap basically. \n\tfont.setPointSize (20);\n\tpainter.setFont (font);\n\tpainter.setPen (Qt::white);\n\tpainter.drawText (QPoint ( int(picScaleFactor)/5, picScaleFactor), cstr (picNum));\n}\n\nvoid PictureControl::drawAnalysisMarkers( std::vector<atomGrid> gridInfo, QPainter& painter ){\n\tif ( !active ){\n\t\treturn;\n\t}\n\tpainter.setPen (Qt::white);\n\t//std::vector<COLORREF> colors = { RGB( 100, 100, 100 ), RGB( 0, 100, 0 ), RGB( 0, 0, 100), RGB( 100, 0, 0 ) };\n\tunsigned gridCount = 0;\n\tfor ( auto atomGrid : gridInfo ){\n\t\tif ( atomGrid.topLeftCorner == coordinate( 0, 0 ) ){\n\t\t\t// atom grid is empty, not to be used.\n\t\t\tunsigned count = 1;\n\t\t}\n\t\telse {\n\t\t\t// use the atom grid.\n\t\t\tunsigned count = 1;\n\t\t\tfor ( auto columnInc : range( atomGrid.width ) ){\n\t\t\t\tfor ( auto rowInc : range( atomGrid.height ) ){\n\t\t\t\t\tunsigned pixelRow = picScaleFactor*(atomGrid.topLeftCorner.row + rowInc * atomGrid.pixelSpacing);\n\t\t\t\t\tunsigned pixelColumn = picScaleFactor * (atomGrid.topLeftCorner.column \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t + columnInc * atomGrid.pixelSpacing);\n\t\t\t\t\tQRect rect = QRect (QPoint(pixelColumn, pixelRow), \n\t\t\t\t\t\t\t\t\t\tQPoint (pixelColumn+picScaleFactor-2, pixelRow + picScaleFactor - 2));\n\t\t\t\t\tpainter.drawRect (rect);\t\t\t\t\t\n\t\t\t\t\tpainter.drawText (rect, Qt::AlignCenter, cstr(count++));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tgridCount++;\n\t}\n}\n\nvoid PictureControl::drawDongles (QPainter& painter, std::vector<atomGrid> grids, unsigned pictureNumber, \n\tbool includingAnalysisMarkers){\n\tdrawPicNum (pictureNumber, painter);\n\tif (includingAnalysisMarkers) {\n\t\tdrawAnalysisMarkers (  grids, painter );\n\t}\n\tpainter.setPen (Qt::red);\n\tdrawCircle (selectedLocation, painter);\n}\n \n \nvoid PictureControl::setTransformationMode (Qt::TransformationMode mode) {\n\ttransformationMode = mode;\n}\n\nvoid PictureControl::setSliderSize(int size)\n{\n\tslider.setMaxLength(size);\n}\n\n", "meta": {"hexsha": "b7b1e549bcb009caab3e6306e5e1a369dfaeb16e", "size": 19088, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Chimera/Source/GeneralImaging/PictureControl.cpp", "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chimera/Source/GeneralImaging/PictureControl.cpp", "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chimera/Source/GeneralImaging/PictureControl.cpp", "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": ["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.3706293706, "max_line_length": 121, "alphanum_fraction": 0.6788034367, "num_tokens": 5308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743735019594, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.47683890447601374}}
{"text": "// Copyright Paul Bristow 2006, 2007.\n// Copyright John Maddock 2006, 2007.\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// test_triangular.cpp\n\n#include <pch.hpp>\n\n#ifdef _MSC_VER\n#  pragma warning(disable: 4127) // conditional expression is constant.\n#  pragma warning(disable: 4305) // truncation from 'long double' to 'float'\n#endif\n\n#include <boost/math/concepts/real_concept.hpp> // for real_concept\n#define BOOST_TEST_MAIN\n#include <boost/test/unit_test.hpp> // Boost.Test\n#include <boost/test/floating_point_comparison.hpp>\n\n#include <boost/math/distributions/triangular.hpp>\nusing boost::math::triangular_distribution;\n#include <boost/math/tools/test.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include \"test_out_of_range.hpp\"\n\n#include <iostream>\n#include <iomanip>\nusing std::cout;\nusing std::endl;\nusing std::scientific;\nusing std::fixed;\nusing std::left;\nusing std::right;\nusing std::setw;\nusing std::setprecision;\nusing std::showpos;\n#include <limits>\nusing std::numeric_limits;\n\ntemplate <class RealType>\nvoid check_triangular(RealType lower, RealType mode, RealType upper, RealType x, RealType p, RealType q, RealType tol)\n{\n  BOOST_CHECK_CLOSE_FRACTION(\n    ::boost::math::cdf(\n    triangular_distribution<RealType>(lower, mode, upper),   // distribution.\n    x),  // random variable.\n    p,    // probability.\n    tol);   // tolerance.\n  BOOST_CHECK_CLOSE_FRACTION(\n    ::boost::math::cdf(\n    complement(\n    triangular_distribution<RealType>(lower, mode, upper), // distribution.\n    x)),    // random variable.\n    q,    // probability complement.\n    tol);  // tolerance.\n  BOOST_CHECK_CLOSE_FRACTION(\n    ::boost::math::quantile(\n    triangular_distribution<RealType>(lower,mode, upper),  // distribution.\n    p),   // probability.\n    x,  // random variable.\n    tol);  // tolerance.\n  BOOST_CHECK_CLOSE_FRACTION(\n    ::boost::math::quantile(\n    complement(\n    triangular_distribution<RealType>(lower, mode, upper),  // distribution.\n    q)),     // probability complement.\n    x,                                             // random variable.\n    tol);  // tolerance.\n} // void check_triangular\n\ntemplate <class RealType>\nvoid test_spots(RealType)\n{\n  // Basic sanity checks:\n  //\n  // Some test values were generated for the triangular distribution\n  // using the online calculator at\n  // http://espse.ed.psu.edu/edpsych/faculty/rhale/hale/507Mat/statlets/free/pdist.htm\n  //\n  // Tolerance is just over 5 epsilon expressed as a fraction:\n  RealType tolerance = boost::math::tools::epsilon<RealType>() * 5; // 5 eps as a fraction.\n  RealType tol5eps = boost::math::tools::epsilon<RealType>() * 5; // 5 eps as a fraction.\n\n  cout << \"Tolerance for type \" << typeid(RealType).name()  << \" is \" << tolerance << \".\" << endl;\n\n  using namespace std; // for ADL of std::exp;\n\n  // Tests on construction\n  // Default should be 0, 0, 1\n  BOOST_CHECK_EQUAL(triangular_distribution<RealType>().lower(), -1);\n  BOOST_CHECK_EQUAL(triangular_distribution<RealType>().mode(), 0);\n  BOOST_CHECK_EQUAL(triangular_distribution<RealType>().upper(), 1);\n  BOOST_CHECK_EQUAL(support(triangular_distribution<RealType>()).first, triangular_distribution<RealType>().lower());\n  BOOST_CHECK_EQUAL(support(triangular_distribution<RealType>()).second, triangular_distribution<RealType>().upper());\n\n  if (std::numeric_limits<RealType>::has_quiet_NaN == true)\n  {\n  BOOST_CHECK_THROW( // duff parameter lower.\n    triangular_distribution<RealType>(static_cast<RealType>(std::numeric_limits<RealType>::quiet_NaN()), 0, 0),\n    std::domain_error);\n\n  BOOST_CHECK_THROW( // duff parameter mode.\n    triangular_distribution<RealType>(0, static_cast<RealType>(std::numeric_limits<RealType>::quiet_NaN()), 0),\n    std::domain_error);\n\n  BOOST_CHECK_THROW( // duff parameter upper.\n    triangular_distribution<RealType>(0, 0, static_cast<RealType>(std::numeric_limits<RealType>::quiet_NaN())),\n    std::domain_error);\n  } // quiet_NaN tests.\n\n  BOOST_CHECK_THROW( // duff parameters upper < lower.\n    triangular_distribution<RealType>(1, 0, -1),\n    std::domain_error);\n\n  BOOST_CHECK_THROW( // duff parameters upper == lower.\n    triangular_distribution<RealType>(0, 0, 0),\n    std::domain_error);\n  BOOST_CHECK_THROW( // duff parameters mode < lower.\n    triangular_distribution<RealType>(0, -1, 1),\n    std::domain_error);\n\n  BOOST_CHECK_THROW( // duff parameters mode > upper.\n    triangular_distribution<RealType>(0, 2, 1),\n    std::domain_error);\n\n  // Tests for PDF\n  // // triangular_distribution<RealType>() default is (0, 0, 1), mode == lower.\n  BOOST_CHECK_CLOSE_FRACTION( // x == lower == mode\n    pdf(triangular_distribution<RealType>(0, 0, 1), static_cast<RealType>(0)),\n    static_cast<RealType>(2),\n    tolerance);\n\n  BOOST_CHECK_CLOSE_FRACTION( // x == upper\n    pdf(triangular_distribution<RealType>(0, 0, 1), static_cast<RealType>(1)),\n    static_cast<RealType>(0),\n    tolerance);\n\n  BOOST_CHECK_CLOSE_FRACTION( // x > upper\n    pdf(triangular_distribution<RealType>(0, 0, 1), static_cast<RealType>(-1)),\n    static_cast<RealType>(0),\n    tolerance);\n  BOOST_CHECK_CLOSE_FRACTION( // x < lower\n    pdf(triangular_distribution<RealType>(0, 0, 1), static_cast<RealType>(2)),\n    static_cast<RealType>(0),\n    tolerance);\n\n  BOOST_CHECK_CLOSE_FRACTION( // x < lower\n    pdf(triangular_distribution<RealType>(0, 0, 1), static_cast<RealType>(2)),\n    static_cast<RealType>(0),\n    tolerance);\n\n  // triangular_distribution<RealType>() (0, 1, 1) mode == upper\n  BOOST_CHECK_CLOSE_FRACTION( // x == lower\n    pdf(triangular_distribution<RealType>(0, 1, 1), static_cast<RealType>(0)),\n    static_cast<RealType>(0),\n    tolerance);\n\n  BOOST_CHECK_CLOSE_FRACTION( // x == upper\n    pdf(triangular_distribution<RealType>(0, 1, 1), static_cast<RealType>(1)),\n    static_cast<RealType>(2),\n    tolerance);\n\n  BOOST_CHECK_CLOSE_FRACTION( // x > upper\n    pdf(triangular_distribution<RealType>(0, 1, 1), static_cast<RealType>(-1)),\n    static_cast<RealType>(0),\n    tolerance);\n  BOOST_CHECK_CLOSE_FRACTION( // x < lower\n    pdf(triangular_distribution<RealType>(0, 1, 1), static_cast<RealType>(2)),\n    static_cast<RealType>(0),\n    tolerance);\n\n  BOOST_CHECK_CLOSE_FRACTION( // x < middle so Wiki says special case pdf = 2 * x\n    pdf(triangular_distribution<RealType>(0, 1, 1), static_cast<RealType>(0.25)),\n    static_cast<RealType>(0.5),\n    tolerance);\n\n  BOOST_CHECK_CLOSE_FRACTION( // x < middle so Wiki says special case cdf = x * x\n    cdf(triangular_distribution<RealType>(0, 1, 1), static_cast<RealType>(0.25)),\n    static_cast<RealType>(0.25 * 0.25),\n    tolerance);\n\n  // triangular_distribution<RealType>() (0, 0.5, 1) mode == middle.\n  BOOST_CHECK_CLOSE_FRACTION( // x == lower\n    pdf(triangular_distribution<RealType>(0, 0.5, 1), static_cast<RealType>(0)),\n    static_cast<RealType>(0),\n    tolerance);\n\n  BOOST_CHECK_CLOSE_FRACTION( // x == upper\n    pdf(triangular_distribution<RealType>(0, 0.5, 1), static_cast<RealType>(1)),\n    static_cast<RealType>(0),\n    tolerance);\n\n  BOOST_CHECK_CLOSE_FRACTION( // x > upper\n    pdf(triangular_distribution<RealType>(0, 0.5, 1), static_cast<RealType>(-1)),\n    static_cast<RealType>(0),\n    tolerance);\n  BOOST_CHECK_CLOSE_FRACTION( // x < lower\n    pdf(triangular_distribution<RealType>(0, 0.5, 1), static_cast<RealType>(2)),\n    static_cast<RealType>(0),\n    tolerance);\n\n  BOOST_CHECK_CLOSE_FRACTION( // x == mode\n    pdf(triangular_distribution<RealType>(0, 0.5, 1), static_cast<RealType>(0.5)),\n    static_cast<RealType>(2),\n    tolerance);\n\n  BOOST_CHECK_CLOSE_FRACTION( // x == half mode\n    pdf(triangular_distribution<RealType>(0, 0.5, 1), static_cast<RealType>(0.25)),\n    static_cast<RealType>(1),\n    tolerance);\n  BOOST_CHECK_CLOSE_FRACTION( // x == half mode\n    pdf(triangular_distribution<RealType>(0, 0.5, 1), static_cast<RealType>(0.75)),\n    static_cast<RealType>(1),\n    tolerance);\n\n  if(std::numeric_limits<RealType>::has_infinity)\n  { // BOOST_CHECK tests for infinity using std::numeric_limits<>::infinity()\n    // Note that infinity is not implemented for real_concept, so these tests\n    // are only done for types, like built-in float, double.. that have infinity.\n    // Note that these assume that  BOOST_MATH_OVERFLOW_ERROR_POLICY is NOT throw_on_error.\n    // #define BOOST_MATH_OVERFLOW_ERROR_POLICY == throw_on_error would give a throw here.\n    // #define BOOST_MATH_DOMAIN_ERROR_POLICY == throw_on_error IS defined, so the throw path\n    // of error handling is tested below with BOOST_CHECK_THROW tests.\n\n    BOOST_CHECK_THROW( // x == infinity NOT OK.\n      pdf(triangular_distribution<RealType>(0, 0, 1), static_cast<RealType>(std::numeric_limits<RealType>::infinity())),\n      std::domain_error);\n\n    BOOST_CHECK_THROW( // x == minus infinity not OK too.\n      pdf(triangular_distribution<RealType>(0, 0, 1), static_cast<RealType>(-std::numeric_limits<RealType>::infinity())),\n      std::domain_error);\n  }\n  if(std::numeric_limits<RealType>::has_quiet_NaN)\n  { // BOOST_CHECK tests for NaN using std::numeric_limits<>::has_quiet_NaN() - should throw.\n    BOOST_CHECK_THROW(\n      pdf(triangular_distribution<RealType>(0, 0, 1), static_cast<RealType>(std::numeric_limits<RealType>::quiet_NaN())),\n      std::domain_error);\n    BOOST_CHECK_THROW(\n      pdf(triangular_distribution<RealType>(0, 0, 1), static_cast<RealType>(-std::numeric_limits<RealType>::quiet_NaN())),\n      std::domain_error);\n  } // test for x = NaN using std::numeric_limits<>::quiet_NaN()\n\n  // cdf\n  BOOST_CHECK_EQUAL( // x < lower\n    cdf(triangular_distribution<RealType>(0, 1, 1), static_cast<RealType>(-1)),\n    static_cast<RealType>(0) );\n  BOOST_CHECK_CLOSE_FRACTION( // x == lower\n    cdf(triangular_distribution<RealType>(0, 1, 1), static_cast<RealType>(0)),\n    static_cast<RealType>(0),\n    tolerance);\n  BOOST_CHECK_CLOSE_FRACTION( // x == upper\n    cdf(triangular_distribution<RealType>(0, 1, 1), static_cast<RealType>(1)),\n    static_cast<RealType>(1),\n    tolerance);\n   BOOST_CHECK_EQUAL( // x > upper\n    cdf(triangular_distribution<RealType>(0, 1, 1), static_cast<RealType>(2)),\n    static_cast<RealType>(1));\n\n  BOOST_CHECK_CLOSE_FRACTION( // x == mode\n    cdf(triangular_distribution<RealType>(-1, 0, 1), static_cast<RealType>(0)),\n    //static_cast<RealType>((mode - lower) / (upper - lower)),\n    static_cast<RealType>(0.5),    // (0 --1) / (1 -- 1) = 0.5\n    tolerance);\n  BOOST_CHECK_CLOSE_FRACTION(\n    cdf(triangular_distribution<RealType>(0, 1, 1), static_cast<RealType>(0.9L)),\n    static_cast<RealType>(0.81L),\n    tolerance);\n\n  BOOST_CHECK_CLOSE_FRACTION(\n    cdf(triangular_distribution<RealType>(-1, 0, 1), static_cast<RealType>(-1)),\n    static_cast<RealType>(0),\n    tolerance);\n  BOOST_CHECK_CLOSE_FRACTION(\n    cdf(triangular_distribution<RealType>(-1, 0, 1), static_cast<RealType>(-0.5L)),\n    static_cast<RealType>(0.125L),\n    tolerance);\n  BOOST_CHECK_CLOSE_FRACTION(\n    cdf(triangular_distribution<RealType>(-1, 0, 1), static_cast<RealType>(0)),\n    static_cast<RealType>(0.5),\n    tolerance);\n  BOOST_CHECK_CLOSE_FRACTION(\n    cdf(triangular_distribution<RealType>(-1, 0, 1), static_cast<RealType>(+0.5L)),\n    static_cast<RealType>(0.875L),\n    tolerance);\n  BOOST_CHECK_CLOSE_FRACTION(\n    cdf(triangular_distribution<RealType>(-1, 0, 1), static_cast<RealType>(1)),\n    static_cast<RealType>(1),\n    tolerance);\n\n   // cdf complement\n  BOOST_CHECK_EQUAL( // x < lower\n    cdf(complement(triangular_distribution<RealType>(0, 0, 1), static_cast<RealType>(-1))),\n    static_cast<RealType>(1));\n  BOOST_CHECK_EQUAL( // x == lower\n    cdf(complement(triangular_distribution<RealType>(0, 0, 1), static_cast<RealType>(0))),\n    static_cast<RealType>(1));\n\n  BOOST_CHECK_EQUAL( // x == mode\n    cdf(complement(triangular_distribution<RealType>(-1, 0, 1), static_cast<RealType>(0))),\n    static_cast<RealType>(0.5));\n\n  BOOST_CHECK_EQUAL( // x == mode\n    cdf(complement(triangular_distribution<RealType>(0, 0, 1), static_cast<RealType>(0))),\n    static_cast<RealType>(1));\n  BOOST_CHECK_EQUAL( // x == mode\n    cdf(complement(triangular_distribution<RealType>(0, 1, 1), static_cast<RealType>(1))),\n    static_cast<RealType>(0));\n\n  BOOST_CHECK_EQUAL( // x > upper\n    cdf(complement(triangular_distribution<RealType>(0, 0, 1), static_cast<RealType>(2))),\n    static_cast<RealType>(0));\n  BOOST_CHECK_EQUAL( // x == upper\n    cdf(complement(triangular_distribution<RealType>(0, 0, 1), static_cast<RealType>(1))),\n    static_cast<RealType>(0));\n\n  BOOST_CHECK_CLOSE_FRACTION( // x = -0.5\n    cdf(complement(triangular_distribution<RealType>(-1, 0, 1), static_cast<RealType>(-0.5))),\n    static_cast<RealType>(0.875L),\n    tolerance);\n\n  BOOST_CHECK_CLOSE_FRACTION( // x = +0.5\n    cdf(complement(triangular_distribution<RealType>(-1, 0, 1), static_cast<RealType>(0.5))),\n    static_cast<RealType>(0.125),\n    tolerance);\n\n  triangular_distribution<RealType> triang; // Using typedef == triangular_distribution<double> tristd;\n  triangular_distribution<RealType> tristd(0, 0.5, 1); // 'Standard' triangular distribution.\n\n  BOOST_CHECK_CLOSE_FRACTION( // median of Standard triangular is sqrt(mode/2) if c > 1/2 else 1 - sqrt((1-c)/2)\n    median(tristd),\n    static_cast<RealType>(0.5),\n    tolerance);\n  triangular_distribution<RealType> tri011(0, 1, 1); // Using default RealType double.\n  triangular_distribution<RealType> tri0q1(0, 0.25, 1); // mode is near bottom.\n  triangular_distribution<RealType> tri0h1(0, 0.5, 1); // Equilateral triangle - mode is the middle.\n  triangular_distribution<RealType> trim12(-1, -0.5, 2); // mode is negative.\n\n  BOOST_CHECK_CLOSE_FRACTION(cdf(tri0q1, 0.02L), static_cast<RealType>(0.0016L), tolerance);\n  BOOST_CHECK_CLOSE_FRACTION(cdf(tri0q1, 0.5L), static_cast<RealType>(0.66666666666666666666666666666666666666666666667L), tolerance);\n  BOOST_CHECK_CLOSE_FRACTION(cdf(tri0q1, 0.98L), static_cast<RealType>(0.9994666666666666666666666666666666666666666666L), tolerance);\n\n  // quantile\n  BOOST_CHECK_CLOSE_FRACTION(quantile(tri0q1, static_cast<RealType>(0.0016L)), static_cast<RealType>(0.02L), tol5eps);\n  BOOST_CHECK_CLOSE_FRACTION(quantile(tri0q1, static_cast<RealType>(0.66666666666666666666666666666666666666666666667L)), static_cast<RealType>(0.5), tol5eps);\n  BOOST_CHECK_CLOSE_FRACTION(quantile(complement(tri0q1, static_cast<RealType>(0.3333333333333333333333333333333333333333333333333L))), static_cast<RealType>(0.5), tol5eps);\n  BOOST_CHECK_CLOSE_FRACTION(quantile(tri0q1, static_cast<RealType>(0.999466666666666666666666666666666666666666666666666L)), static_cast<RealType>(98) / 100, 10 * tol5eps);\n\n  BOOST_CHECK_CLOSE_FRACTION(pdf(trim12, 0), static_cast<RealType>(0.533333333333333333333333333333333333333333333L), tol5eps);\n  BOOST_CHECK_CLOSE_FRACTION(cdf(trim12, 0), static_cast<RealType>(0.466666666666666666666666666666666666666666667L), tol5eps);\n  BOOST_CHECK_CLOSE_FRACTION(cdf(complement(trim12, 0)), static_cast<RealType>(1 - 0.466666666666666666666666666666666666666666667L), tol5eps);\n\n  BOOST_CHECK_CLOSE_FRACTION(quantile(complement(tri0q1, static_cast<RealType>(1 - 0.999466666666666666666666666666666666666666666666L))), static_cast<RealType>(0.98L), 10 * tol5eps);\n  BOOST_CHECK_CLOSE_FRACTION(quantile(complement(tri0h1, static_cast<RealType>(1))), static_cast<RealType>(0), tol5eps);\n  BOOST_CHECK_CLOSE_FRACTION(quantile(complement(tri0h1, static_cast<RealType>(0.5))), static_cast<RealType>(0.5), tol5eps); // OK\n  BOOST_CHECK_CLOSE_FRACTION(quantile(complement(tri0h1, static_cast<RealType>(1 - 0.02L))), static_cast<RealType>(0.1L), tol5eps);\n  BOOST_CHECK_CLOSE_FRACTION(quantile(complement(tri0h1, static_cast<RealType>(1 - 0.98L))), static_cast<RealType>(0.9L), tol5eps);\n  BOOST_CHECK_CLOSE_FRACTION(quantile(complement(tri0h1, 0)), static_cast<RealType>(1), tol5eps);\n\n  RealType xs [] = {0, 0.01L, 0.02L, 0.05L, 0.1L, 0.2L, 0.3L, 0.4L, 0.5L, 0.6L, 0.7L, 0.8L, 0.9L, 0.95L, 0.98L, 0.99L, 1};\n\n  const triangular_distribution<RealType>& distr = triang;\n  BOOST_CHECK_CLOSE_FRACTION(quantile(complement(distr, 1.)), static_cast<RealType>(-1), tol5eps);\n  const triangular_distribution<RealType>* distp = &triang;\n  BOOST_CHECK_CLOSE_FRACTION(quantile(complement(*distp, 1.)), static_cast<RealType>(-1), tol5eps);\n\n  const triangular_distribution<RealType>* dists [] = {&tristd, &tri011, &tri0q1, &tri0h1, &trim12};\n  BOOST_CHECK_CLOSE_FRACTION(quantile(complement(*dists[1], 1.)), static_cast<RealType>(0), tol5eps);\n\n   for (int i = 0; i < 5; i++)\n  {\n    const triangular_distribution<RealType>* const dist = dists[i];\n    // cout << \"Distribution \" << i << endl;\n    BOOST_CHECK_CLOSE_FRACTION(quantile(*dists[i], 0.5L), quantile(complement(*dist, 0.5L)),  tol5eps);\n    BOOST_CHECK_CLOSE_FRACTION(quantile(*dists[i], 0.98L), quantile(complement(*dist, 1.L - 0.98L)),tol5eps);\n    BOOST_CHECK_CLOSE_FRACTION(quantile(*dists[i], 0.98L), quantile(complement(*dist, 1.L - 0.98L)),tol5eps);\n  } // for i\n\n   // quantile complement\n  for (int i = 0; i < 5; i++)\n  {\n    const triangular_distribution<RealType>* const dist = dists[i];\n    //cout << \"Distribution \" << i << endl;\n    BOOST_CHECK_EQUAL(quantile(complement(*dists[i], 1.)), quantile(*dists[i], 0.));\n    for (unsigned j = 0; j < sizeof(xs) /sizeof(RealType); j++)\n    {\n      RealType x = xs[j];\n      BOOST_CHECK_CLOSE_FRACTION(quantile(*dists[i], x), quantile(complement(*dist, 1 - x)),  tol5eps);\n    } // for j\n  } // for i\n\n\n  check_triangular(\n    static_cast<RealType>(0),       // lower\n    static_cast<RealType>(0.5),     // mode\n    static_cast<RealType>(1),       // upper\n    static_cast<RealType>(0.5),     // x\n    static_cast<RealType>(0.5),     // p\n    static_cast<RealType>(1 - 0.5), // q\n    tolerance);\n\n  // Some Not-standard triangular tests.\n  check_triangular(\n    static_cast<RealType>(-1),    // lower\n    static_cast<RealType>(0),     // mode\n    static_cast<RealType>(1),     // upper\n    static_cast<RealType>(0),     // x\n    static_cast<RealType>(0.5),   // p\n    static_cast<RealType>(1 - 0.5), // q = 1 - p\n    tolerance);\n\n  check_triangular(\n    static_cast<RealType>(1),       // lower\n    static_cast<RealType>(1),       // mode\n    static_cast<RealType>(3),       // upper\n    static_cast<RealType>(2),    // x\n    static_cast<RealType>(0.75),     // p\n    static_cast<RealType>(1 - 0.75), // q = 1 - p\n    tolerance);\n\n  check_triangular(\n    static_cast<RealType>(-1),    // lower\n    static_cast<RealType>(1),       // mode\n    static_cast<RealType>(2),     // upper\n    static_cast<RealType>(1),     // x\n    static_cast<RealType>(0.66666666666666666666666666666666666666666667L),   // p\n    static_cast<RealType>(0.33333333333333333333333333333333333333333333L), // q = 1 - p\n    tolerance);\n  tolerance = (std::max)(\n    boost::math::tools::epsilon<RealType>(),\n    static_cast<RealType>(boost::math::tools::epsilon<double>())) * 10; // 10 eps as a fraction.\n  cout << \"Tolerance (as fraction) for type \" << typeid(RealType).name()  << \" is \" << tolerance << \".\" << endl;\n  triangular_distribution<RealType> tridef; // (-1, 0, 1) // default\n  RealType x = static_cast<RealType>(0.5);\n  using namespace std; // ADL of std names.\n  // mean:\n  BOOST_CHECK_CLOSE_FRACTION(\n    mean(tridef), static_cast<RealType>(0), tolerance);\n  // variance:\n  BOOST_CHECK_CLOSE_FRACTION(\n    variance(tridef), static_cast<RealType>(0.16666666666666666666666666666666666666666667L), tolerance);\n  // was 0.0833333333333333333333333333333333333333333L\n\n  // std deviation:\n  BOOST_CHECK_CLOSE_FRACTION(\n    standard_deviation(tridef), sqrt(variance(tridef)), tolerance);\n  // hazard:\n  BOOST_CHECK_CLOSE_FRACTION(\n    hazard(tridef, x), pdf(tridef, x) / cdf(complement(tridef, x)), tolerance);\n  // cumulative hazard:\n  BOOST_CHECK_CLOSE_FRACTION(\n    chf(tridef, x), -log(cdf(complement(tridef, x))), tolerance);\n  // coefficient_of_variation:\n  if (mean(tridef) != 0)\n  {\n  BOOST_CHECK_CLOSE_FRACTION(\n    coefficient_of_variation(tridef), standard_deviation(tridef) / mean(tridef), tolerance);\n  }\n  // mode:\n  BOOST_CHECK_CLOSE_FRACTION(\n    mode(tridef), static_cast<RealType>(0), tolerance);\n  // skewness:\n  BOOST_CHECK_CLOSE_FRACTION(\n    median(trim12), static_cast<RealType>(-0.13397459621556151), tolerance);\n  BOOST_CHECK_EQUAL(\n    skewness(tridef), static_cast<RealType>(0));\n  // kurtosis:\n  BOOST_CHECK_CLOSE_FRACTION(\n    kurtosis_excess(tridef), kurtosis(tridef) - static_cast<RealType>(3L), tolerance);\n  // kurtosis excess = kurtosis - 3;\n  BOOST_CHECK_CLOSE_FRACTION(\n    kurtosis_excess(tridef), static_cast<RealType>(-0.6), tolerance); // for all distributions.\n\n  if(std::numeric_limits<RealType>::has_infinity)\n  { // BOOST_CHECK tests for infinity using std::numeric_limits<>::infinity()\n    // Note that infinity is not implemented for real_concept, so these tests\n    // are only done for types, like built-in float, double.. that have infinity.\n    // Note that these assume that BOOST_MATH_OVERFLOW_ERROR_POLICY is NOT throw_on_error.\n    // #define BOOST_MATH_OVERFLOW_ERROR_POLICY == throw_on_error would give a throw here.\n    // #define BOOST_MATH_DOMAIN_ERROR_POLICY == throw_on_error IS defined, so the throw path\n    // of error handling is tested below with BOOST_CHECK_THROW tests.\n\n    using boost::math::policies::policy;\n    using boost::math::policies::domain_error;\n    using boost::math::policies::ignore_error;\n\n    // Define a (bad?) policy to ignore domain errors ('bad' arguments):\n    typedef policy<domain_error<ignore_error> > inf_policy; // domain error returns infinity.\n    triangular_distribution<RealType, inf_policy> tridef_inf(-1, 0., 1);\n    // But can't use BOOST_CHECK_EQUAL(?, quiet_NaN)\n    using boost::math::isnan;\n    BOOST_CHECK((isnan)(pdf(tridef_inf, std::numeric_limits<RealType>::infinity())));\n  } // test for infinity using std::numeric_limits<>::infinity()\n  else\n  { // real_concept case, does has_infinfity == false, so can't check it throws.\n    // cout << std::numeric_limits<RealType>::infinity() << ' '\n    // << (boost::math::fpclassify)(std::numeric_limits<RealType>::infinity()) << endl;\n    // value of std::numeric_limits<RealType>::infinity() is zero, so FPclassify is zero,\n    // so (boost::math::isfinite)(std::numeric_limits<RealType>::infinity()) does not detect infinity.\n    // so these tests would never throw.\n    //BOOST_CHECK_THROW(pdf(tridef, std::numeric_limits<RealType>::infinity()),  std::domain_error);\n    //BOOST_CHECK_THROW(pdf(tridef, std::numeric_limits<RealType>::quiet_NaN()),  std::domain_error);\n    // BOOST_CHECK_THROW(pdf(tridef, boost::math::tools::max_value<RealType>() * 2),  std::domain_error); // Doesn't throw.\n    BOOST_CHECK_EQUAL(pdf(tridef, boost::math::tools::max_value<RealType>()), 0);\n  }\n  // Special cases:\n  BOOST_CHECK(pdf(tridef, -1) == 0);\n  BOOST_CHECK(pdf(tridef, 1) == 0);\n  BOOST_CHECK(cdf(tridef, 0) == 0.5);\n  BOOST_CHECK(pdf(tridef, 1) == 0);\n  BOOST_CHECK(cdf(tridef, 1) == 1);\n  BOOST_CHECK(cdf(complement(tridef, -1)) == 1);\n  BOOST_CHECK(cdf(complement(tridef, 1)) == 0);\n  BOOST_CHECK(quantile(tridef, 1) == 1);\n  BOOST_CHECK(quantile(complement(tridef, 1)) == -1);\n\n  BOOST_CHECK_EQUAL(support(trim12).first, trim12.lower());\n  BOOST_CHECK_EQUAL(support(trim12).second, trim12.upper());\n\n  // Error checks:\n  if(std::numeric_limits<RealType>::has_quiet_NaN)\n  { // BOOST_CHECK tests for quiet_NaN (not for real_concept, for example - see notes above).\n    BOOST_CHECK_THROW(triangular_distribution<RealType>(0, std::numeric_limits<RealType>::quiet_NaN()), std::domain_error);\n    BOOST_CHECK_THROW(triangular_distribution<RealType>(0, -std::numeric_limits<RealType>::quiet_NaN()), std::domain_error);\n  }\n  BOOST_CHECK_THROW(triangular_distribution<RealType>(1, 0), std::domain_error); // lower > upper!\n\n  check_out_of_range<triangular_distribution<RealType> >(-1, 0, 1);\n} // template <class RealType>void test_spots(RealType)\n\nBOOST_AUTO_TEST_CASE( test_main )\n{\n  //  double toleps = std::numeric_limits<double>::epsilon(); // 5 eps as a fraction.\n  double tol5eps = std::numeric_limits<double>::epsilon() * 5; // 5 eps as a fraction.\n  // double tol50eps = std::numeric_limits<double>::epsilon() * 50; // 50 eps as a fraction.\n  double tol500eps = std::numeric_limits<double>::epsilon() * 500; // 500 eps as a fraction.\n\n  // Check that can construct triangular distribution using the two convenience methods:\n  using namespace boost::math;\n  triangular triang; // Using typedef\n  // == triangular_distribution<double> triang;\n\n  BOOST_CHECK_EQUAL(triang.lower(), -1); // Check default.\n  BOOST_CHECK_EQUAL(triang.mode(), 0);\n  BOOST_CHECK_EQUAL(triang.upper(), 1);\n\n  triangular tristd (0, 0.5, 1); // Using typedef\n\n  BOOST_CHECK_EQUAL(tristd.lower(), 0);\n  BOOST_CHECK_EQUAL(tristd.mode(), 0.5);\n  BOOST_CHECK_EQUAL(tristd.upper(), 1);\n\n  //cout << \"X range from \" << range(tristd).first << \" to \" << range(tristd).second << endl;\n  //cout << \"Supported from \"<< support(tristd).first << ' ' << support(tristd).second << endl;\n\n  BOOST_CHECK_EQUAL(support(tristd).first, tristd.lower());\n  BOOST_CHECK_EQUAL(support(tristd).second, tristd.upper());\n\n  triangular_distribution<> tri011(0, 1, 1); // Using default RealType double.\n  // mode is upper\n  BOOST_CHECK_EQUAL(tri011.lower(), 0); // Check defaults again.\n  BOOST_CHECK_EQUAL(tri011.mode(), 1); // Check defaults again.\n  BOOST_CHECK_EQUAL(tri011.upper(), 1);\n  BOOST_CHECK_EQUAL(mode(tri011), 1);\n\n  BOOST_CHECK_EQUAL(pdf(tri011, 0), 0);\n  BOOST_CHECK_EQUAL(pdf(tri011, 0.1), 0.2);\n  BOOST_CHECK_EQUAL(pdf(tri011, 0.5), 1);\n  BOOST_CHECK_EQUAL(pdf(tri011, 0.9), 1.8);\n  BOOST_CHECK_EQUAL(pdf(tri011, 1), 2);\n\n  BOOST_CHECK_EQUAL(cdf(tri011, 0), 0);\n  BOOST_CHECK_CLOSE_FRACTION(cdf(tri011, 0.1), 0.01, tol5eps);\n  BOOST_CHECK_EQUAL(cdf(tri011, 0.5), 0.25);\n  BOOST_CHECK_EQUAL(cdf(tri011, 0.9), 0.81);\n  BOOST_CHECK_EQUAL(cdf(tri011, 1), 1);\n  BOOST_CHECK_EQUAL(cdf(tri011, 9), 1);\n  BOOST_CHECK_EQUAL(mean(tri011), 0.666666666666666666666666666666666666666666666666667);\n  BOOST_CHECK_EQUAL(variance(tri011), 1./18.);\n\n  triangular tri0h1(0, 0.5, 1); // Equilateral triangle - mode is the middle.\n  BOOST_CHECK_EQUAL(tri0h1.lower(), 0);\n  BOOST_CHECK_EQUAL(tri0h1.mode(), 0.5);\n  BOOST_CHECK_EQUAL(tri0h1.upper(), 1);\n  BOOST_CHECK_EQUAL(mean(tri0h1), 0.5);\n  BOOST_CHECK_EQUAL(mode(tri0h1), 0.5);\n  BOOST_CHECK_EQUAL(pdf(tri0h1, -1), 0);\n  BOOST_CHECK_EQUAL(cdf(tri0h1, -1), 0);\n  BOOST_CHECK_EQUAL(pdf(tri0h1, 1), 0);\n  BOOST_CHECK_EQUAL(pdf(tri0h1, 999), 0);\n  BOOST_CHECK_EQUAL(cdf(tri0h1, 999), 1);\n  BOOST_CHECK_EQUAL(cdf(tri0h1, 1), 1);\n  BOOST_CHECK_CLOSE_FRACTION(cdf(tri0h1, 0.1), 0.02, tol5eps);\n  BOOST_CHECK_EQUAL(cdf(tri0h1, 0.5), 0.5);\n  BOOST_CHECK_CLOSE_FRACTION(cdf(tri0h1, 0.9), 0.98, tol5eps);\n\n  BOOST_CHECK_CLOSE_FRACTION(quantile(tri0h1, 0.), 0., tol5eps);\n  BOOST_CHECK_CLOSE_FRACTION(quantile(tri0h1, 0.02), 0.1, tol5eps);\n  BOOST_CHECK_CLOSE_FRACTION(quantile(tri0h1, 0.5), 0.5, tol5eps);\n  BOOST_CHECK_CLOSE_FRACTION(quantile(tri0h1, 0.98), 0.9, tol5eps);\n  BOOST_CHECK_CLOSE_FRACTION(quantile(tri0h1, 1.), 1., tol5eps);\n\n  triangular tri0q1(0, 0.25, 1); // mode is near bottom.\n  BOOST_CHECK_CLOSE_FRACTION(cdf(tri0q1, 0.02), 0.0016, tol5eps);\n  BOOST_CHECK_CLOSE_FRACTION(cdf(tri0q1, 0.5), 0.66666666666666666666666666666666666666666666667, tol5eps);\n  BOOST_CHECK_CLOSE_FRACTION(cdf(tri0q1, 0.98), 0.99946666666666661, tol5eps);\n\n  BOOST_CHECK_CLOSE_FRACTION(quantile(tri0q1, 0.0016), 0.02, tol5eps);\n  BOOST_CHECK_CLOSE_FRACTION(quantile(tri0q1, 0.66666666666666666666666666666666666666666666667), 0.5, tol5eps);\n  BOOST_CHECK_CLOSE_FRACTION(quantile(complement(tri0q1, 0.3333333333333333333333333333333333333333333333333)), 0.5, tol5eps);\n  BOOST_CHECK_CLOSE_FRACTION(quantile(tri0q1, 0.99946666666666661), 0.98, 10 * tol5eps);\n\n  triangular trim12(-1, -0.5, 2); // mode is negative.\n  BOOST_CHECK_CLOSE_FRACTION(pdf(trim12, 0), 0.533333333333333333333333333333333333333333333, tol5eps);\n  BOOST_CHECK_CLOSE_FRACTION(cdf(trim12, 0), 0.466666666666666666666666666666666666666666667, tol5eps);\n  BOOST_CHECK_CLOSE_FRACTION(cdf(complement(trim12, 0)), 1 - 0.466666666666666666666666666666666666666666667, tol5eps);\n\n  BOOST_CHECK_CLOSE_FRACTION(quantile(complement(tri0q1, 1 - 0.99946666666666661)), 0.98, 10 * tol5eps);\n  BOOST_CHECK_CLOSE_FRACTION(quantile(complement(tri0h1, 1.)), 0., tol5eps);\n  BOOST_CHECK_CLOSE_FRACTION(quantile(complement(tri0h1, 0.5)), 0.5, tol5eps); // OK\n  BOOST_CHECK_CLOSE_FRACTION(quantile(complement(tri0h1, 1. - 0.02)), 0.1, tol5eps);\n  BOOST_CHECK_CLOSE_FRACTION(quantile(complement(tri0h1, 1. - 0.98)), 0.9, tol5eps);\n  BOOST_CHECK_CLOSE_FRACTION(quantile(complement(tri0h1, 0)), 1., tol5eps);\n\n  double xs [] = {0., 0.01, 0.02, 0.05, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 0.95, 0.98, 0.99, 1.};\n\n  const triangular_distribution<double>& distr = tristd;\n  BOOST_CHECK_CLOSE_FRACTION(quantile(complement(distr, 1.)), 0., tol5eps);\n  const triangular_distribution<double>* distp = &tristd;\n  BOOST_CHECK_CLOSE_FRACTION(quantile(complement(*distp, 1.)), 0., tol5eps);\n\n  const triangular_distribution<double>* dists [] = {&tristd, &tri011, &tri0q1, &tri0h1, &trim12};\n  BOOST_CHECK_CLOSE_FRACTION(quantile(complement(*dists[1], 1.)), 0., tol5eps);\n\n  for (int i = 0; i < 5; i++)\n  {\n    const triangular_distribution<double>* const dist = dists[i];\n    cout << \"Distribution \" << i << endl;\n    BOOST_CHECK_EQUAL(quantile(complement(*dists[i], 1.)), quantile(*dists[i], 0.));\n    BOOST_CHECK_CLOSE_FRACTION(quantile(*dists[i], 0.5), quantile(complement(*dist, 0.5)),  tol5eps); // OK\n    BOOST_CHECK_CLOSE_FRACTION(quantile(*dists[i], 0.98), quantile(complement(*dist, 1. - 0.98)),tol5eps);\n    // cout << setprecision(17) <<  median(*dist) << endl;\n  }\n\n  cout << showpos << setprecision(2) << endl;\n\n  //triangular_distribution<double>& dist = trim12;\n  for (unsigned i = 0; i < sizeof(xs) /sizeof(double); i++)\n  {\n    double x = xs[i] * (trim12.upper() - trim12.lower()) + trim12.lower();\n    double dx = cdf(trim12, x);\n    double cx = cdf(complement(trim12, x));\n    //cout << fixed << showpos << setprecision(3)\n    //  << xs[i] << \", \" << x << \",  \" << pdf(trim12, x) << \",  \" << dx << \",  \" << cx << \",, \" ;\n\n    BOOST_CHECK_CLOSE_FRACTION(cx, 1 - dx, tol500eps); // cx == 1 - dx\n\n    // << setprecision(2) << scientific << cr - x << \", \" // difference x - quan(cdf)\n    // << setprecision(3) << fixed\n    // << quantile(trim12, dx) << \", \"\n    // << quantile(complement(trim12, 1 - dx)) << \", \"\n    // << quantile(complement(trim12, cx)) << \", \"\n    // << endl;\n    BOOST_CHECK_CLOSE_FRACTION(quantile(trim12, dx), quantile(complement(trim12, 1 - dx)), tol500eps);\n  }\n  cout << endl;\n  // Basic sanity-check spot values.\n  // (Parameter value, arbitrarily zero, only communicates the floating point type).\n  test_spots(0.0F); // Test float. OK at decdigits = 0 tolerance = 0.0001 %\n  test_spots(0.0); // Test double. OK at decdigits 7, tolerance = 1e07 %\n  #ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n    test_spots(0.0L); // Test long double.\n  #if !BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x0582))\n    test_spots(boost::math::concepts::real_concept(0.)); // Test real concept.\n  #endif\n  #else\n     std::cout << \"<note>The long double tests have been disabled on this platform \"\n        \"either because the long double overloads of the usual math functions are \"\n        \"not available at all, or because they are too inaccurate for these tests \"\n        \"to pass.</note>\" << std::cout;\n  #endif\n\n  \n} // BOOST_AUTO_TEST_CASE( test_main )\n\n/*\n\nOutput:\n\nAutorun \"i:\\boost-06-05-03-1300\\libs\\math\\test\\Math_test\\debug\\test_triangular.exe\"\nRunning 1 test case...\nDistribution 0\nDistribution 1\nDistribution 2\nDistribution 3\nDistribution 4\nTolerance for type float is 5.96046e-007.\nTolerance for type double is 1.11022e-015.\nTolerance for type long double is 1.11022e-015.\nTolerance for type class boost::math::concepts::real_concept is 1.11022e-015.\n*** No errors detected\n\n\n\n*/\n\n\n\n\n", "meta": {"hexsha": "4b0673b24139ecce9bb462ce98843e853d5ed748", "size": 32133, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/boost_1_56_0/libs/math/test/test_triangular.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": 5.0, "max_stars_repo_stars_event_min_datetime": "2015-11-07T10:32:49.000Z", "max_stars_repo_stars_event_max_datetime": "2016-06-24T06:44:25.000Z", "max_issues_repo_path": "boost/boost_1_56_0/libs/math/test/test_triangular.cpp", "max_issues_repo_name": "cooparation/caffe-android", "max_issues_repo_head_hexsha": "cd91078d1f298c74fca4c242531989d64a32ba03", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-11-18T21:24:03.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-11T12:39:57.000Z", "max_forks_repo_path": "boost/boost_1_56_0/libs/math/test/test_triangular.cpp", "max_forks_repo_name": "cooparation/caffe-android", "max_forks_repo_head_hexsha": "cd91078d1f298c74fca4c242531989d64a32ba03", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "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": 45.1306179775, "max_line_length": 183, "alphanum_fraction": 0.70675007, "num_tokens": 9762, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743735019594, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.47683890447601374}}
{"text": "#include <fstream>\n#include <iostream>\n#include <experimental/filesystem>\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 \"../tasks.hh\"\n#include \"../util/split.hh\"\n#include \"../classes/BinnedTypedMatrix.hh\"\n\nnamespace fs = std::experimental::filesystem;\n\nusing namespace EMC;\n\nusing namespace boost::numeric;\n\nint EMC::apply(bool forceOverwrite, std::string inputVectorFileName, std::string outputVectorFileName, std::string matrixFileName) {\n\n\tif (!forceOverwrite && fs::exists(outputVectorFileName)) {\n\t\tstd::cout << \"Output file already exists, use -f to force overwrite.\" << std::endl;\n\t\treturn 1;\n\t}\n\n\tstd::ifstream matFile(matrixFileName);\n\tBinnedTypedMatrix responseMatrix = BinnedTypedMatrix::readFromFile(matFile);\n\tmatFile.close();\n\n\tstd::vector<double> inputBinCenter;\n\tstd::vector<double> inputBinValue;\n\tstd::ifstream inputVectorFile(inputVectorFileName);\n\twhile (!inputVectorFile.eof()) {\n\t\tstd::string line;\n\t\tstd::getline(inputVectorFile, line );\n\n\t\tif (!line.empty()) {\n\t\t\ttry {\n\t\t\t\tauto splitLine = split(split(split(line, ';'), ','), ' ');\n\t\t\t\tdouble binCntr = std::stod(splitLine[0]);\n\t\t\t\tdouble binValue = std::stod(splitLine[1]);\n\t\t\t\tinputBinCenter.push_back(binCntr);\n\t\t\t\tinputBinValue.push_back(binValue);\n\t\t\t} catch(...) { }\n\t\t}\n\t}\n\tinputVectorFile.close();\n\n\tublas::vector<ValueError> inputVector(responseMatrix.columnCount);\n\tstd::vector<double> inputVectorBinWidth(responseMatrix.columnCount, 0);\n\n\tfor (unsigned int i = 0; i < inputBinCenter.size() && inputBinCenter[i] < responseMatrix.columnIndex.back() ; i++) {\n\t\tint fillPosition = -1;\n\t\twhile ( (inputBinCenter[i] > responseMatrix.columnIndex.at(fillPosition + 1)) ) {\n\t\t\tfillPosition++;\n\t\t}\n\n\t\t//std::cout << inputBinCenter[i] << \" --> [\" << responseMatrix.columnIndex.at(fillPosition) << \", \" << responseMatrix.columnIndex.at(fillPosition + 1) << \"]\" << std::endl;\n\n\t\tif (fillPosition >= 0) {\n\t\t\tinputVector[fillPosition].value += inputBinValue[i];\n\t\t\tif (i == 0) {\n\t\t\t\tinputVectorBinWidth[fillPosition] += inputBinCenter[i+1] - inputBinCenter[i];\n\t\t\t} else {\n\t\t\t\tinputVectorBinWidth[fillPosition] += inputBinCenter[i] - inputBinCenter[i-1];\n\t\t\t}\n\t\t}\n\t}\n\n\tfor (unsigned int i=0; i<responseMatrix.columnCount; i++) {\n\t\tinputVector[i].err_sq = inputVector[i].value;\n\t\tinputVector[i].value /= inputVectorBinWidth[i];\n\t\tinputVector[i].err_sq /= (inputVectorBinWidth[i]*inputVectorBinWidth[i]);\n\t\tstd::cout << \"inputVectorBinWidth[i] = \" << inputVectorBinWidth[i] << std::endl;\n\t}\n\n\tublas::vector<ValueError> outputVector = ublas::prod(responseMatrix.m, inputVector);\n\n    std::ofstream outputFstep(outputVectorFileName + \".step\");\n\n    for (unsigned int i=0; i<responseMatrix.rowCount; i++) {\n    \toutputFstep << responseMatrix.rowIndex[i]   << \" \" << outputVector[i].value << std::endl;\n    \toutputFstep << responseMatrix.rowIndex[i+1] << \" \" << outputVector[i].value << std::endl;\n\t}\n\n    outputFstep.close();\n\n    std::ofstream outputFcntr(outputVectorFileName + \".cntr\");\n\n    for (unsigned int i=0; i<responseMatrix.rowCount; i++) {\n    \toutputFcntr << (0.5*(responseMatrix.rowIndex[i] + responseMatrix.rowIndex[i+1]))   << \" \" << outputVector[i].value << \" \" << sqrt(outputVector[i].err_sq) << std::endl;\n\t}\n\n    outputFcntr.close();\n\n    return 0;\n}\n", "meta": {"hexsha": "43d734dab9d7326b851ba7f79c9aed8fb3aa02df", "size": 3324, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tasks/apply.cpp", "max_stars_repo_name": "pixel-toolbox/error-matrix-calculation", "max_stars_repo_head_hexsha": "29539c9950552f64648932747ab4c07a32004766", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/tasks/apply.cpp", "max_issues_repo_name": "pixel-toolbox/error-matrix-calculation", "max_issues_repo_head_hexsha": "29539c9950552f64648932747ab4c07a32004766", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tasks/apply.cpp", "max_forks_repo_name": "pixel-toolbox/error-matrix-calculation", "max_forks_repo_head_hexsha": "29539c9950552f64648932747ab4c07a32004766", "max_forks_repo_licenses": ["BSD-3-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.9183673469, "max_line_length": 173, "alphanum_fraction": 0.6916365824, "num_tokens": 888, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.47683889981835004}}
{"text": "#include \"drake/math/barycentric.h\"\n\n#include <cmath>\n#include <memory>\n#include <set>\n#include <vector>\n\n#include <Eigen/Dense>\n#include <gtest/gtest.h>\n\n#include \"drake/common/symbolic.h\"\n#include \"drake/common/test_utilities/eigen_matrix_compare.h\"\n\nnamespace drake {\nnamespace math {\nnamespace {\n\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\nusing Eigen::VectorXi;\nusing Eigen::Vector2d;\nusing Eigen::Vector3d;\nusing Eigen::Vector3i;\n\nGTEST_TEST(BarycentricTest, GetMeshPoints) {\n  // Create a mesh in 3 (input) dimensions, with the second dimension being a\n  // singleton.\n  const int kNumInputs = 3;\n  BarycentricMesh<double> bary{{{0.0, 1.0},  // BR\n                                {2.0},       // BR\n                                {3.0, 4.0}}};\n\n  EXPECT_EQ(bary.get_input_size(), kNumInputs);\n  EXPECT_EQ(*(bary.get_input_grid()[2].rbegin()), 4.0);\n  EXPECT_EQ(bary.get_num_mesh_points(), 4);\n\n  Vector3d point;\n  bary.get_mesh_point(0, &point);\n  EXPECT_TRUE(CompareMatrices(point, Vector3d{0, 2, 3}));\n  bary.get_mesh_point(1, &point);\n  EXPECT_TRUE(CompareMatrices(point, Vector3d{1, 2, 3}));\n  bary.get_mesh_point(2, &point);\n  EXPECT_TRUE(CompareMatrices(point, Vector3d{0, 2, 4}));\n  bary.get_mesh_point(3, &point);\n  EXPECT_TRUE(CompareMatrices(point, Vector3d{1, 2, 4}));\n\n  // Test the alternative call signature.\n  EXPECT_TRUE(CompareMatrices(bary.get_mesh_point(0), Vector3d{0, 2, 3}));\n\n  // Test the batch retrieval.\n  const MatrixXd points = bary.get_all_mesh_points();\n  EXPECT_EQ(points.cols(), 4);\n  EXPECT_TRUE(CompareMatrices(points.col(3), Vector3d{1, 2, 4}));\n}\n\nGTEST_TEST(BarycentricTest, EvalWeights) {\n  // Create a mesh in 3 (input) dimensions, with the second dimension being a\n  // singleton.\n  BarycentricMesh<double> bary{{{0.0, 1.0},  // BR\n                                {2.0},       // BR\n                                {3.0, 4.0}}};\n\n  VectorXi indices(3);\n  VectorXd weights(3);\n\n  Vector3d sample{1, 2, 3.1};\n  bary.EvalBarycentricWeights(sample, &indices, &weights);\n  EXPECT_TRUE(CompareMatrices(indices, Vector3i{3, 1, 0}));\n  EXPECT_TRUE(CompareMatrices(weights, Vector3d{.1, .9, 0}, 1e-8));\n\n  // Off the grid (in singleton dimension) should not change things.\n  sample[1] = 3.0;\n  bary.EvalBarycentricWeights(sample, &indices, &weights);\n  EXPECT_TRUE(CompareMatrices(indices, Vector3i{3, 1, 0}));\n  EXPECT_TRUE(CompareMatrices(weights, Vector3d{.1, .9, 0}, 1e-8));\n\n  // Off the grid to the right.\n  sample[0] = 1.5;\n  bary.EvalBarycentricWeights(sample, &indices, &weights);\n  EXPECT_TRUE(CompareMatrices(indices, Vector3i{3, 1, 1}));\n  EXPECT_TRUE(CompareMatrices(weights, Vector3d{.1, .9, 0}, 1e-8));\n\n  // Test a different face.\n  sample = Vector3d{0., 2.0, 3.4};\n  bary.EvalBarycentricWeights(sample, &indices, &weights);\n  EXPECT_TRUE(CompareMatrices(indices, Vector3i{2, 0, 0}));\n  EXPECT_TRUE(CompareMatrices(weights, Vector3d{.4, .6, 0.}, 1e-8));\n\n  // Off the grid to the left should not change things.\n  sample[0] = -1.5;\n  bary.EvalBarycentricWeights(sample, &indices, &weights);\n  EXPECT_TRUE(CompareMatrices(indices, Vector3i{2, 0, 0}));\n  EXPECT_TRUE(CompareMatrices(weights, Vector3d{.4, .6, 0}, 1e-8));\n\n  // Smack in the middle.\n  sample = Vector3d{.5, 2., 3.5};\n  bary.EvalBarycentricWeights(sample, &indices, &weights);\n  EXPECT_TRUE(CompareMatrices(indices, Vector3i{3, 2, 0}));\n  EXPECT_TRUE(CompareMatrices(weights, Vector3d{.5, 0, .5}, 1e-8));\n}\n\nGTEST_TEST(BarycentricTest, EvalTest) {\n  BarycentricMesh<double> bary{{{0.0, 1.0},  // BR\n                                {0.0, 1.0}}};\n\n  MatrixXd mesh = Eigen::RowVector4d{1., 2., 3., 4.};\n\n  Vector1d value;\n  double tol = 1e-8;\n  // Check grid points.\n  bary.Eval(mesh, Vector2d{0., 0.}, &value);\n  EXPECT_NEAR(value[0], 1., tol);\n  bary.Eval(mesh, Vector2d{1., 0.}, &value);\n  EXPECT_NEAR(value[0], 2., tol);\n  bary.Eval(mesh, Vector2d{0., 1.}, &value);\n  EXPECT_NEAR(value[0], 3., tol);\n  bary.Eval(mesh, Vector2d{1., 1.}, &value);\n  EXPECT_NEAR(value[0], 4., tol);\n\n  // Check the middle.\n  bary.Eval(mesh, Vector2d{.5, .5}, &value);\n  EXPECT_NEAR(value[0], 2.5, 1e-8);\n\n  // Check the two faces.\n  bary.Eval(mesh, Vector2d{.75, .25}, &value);\n  EXPECT_NEAR(value[0], 2.25, 1e-8);\n  bary.Eval(mesh, Vector2d{.25, .75}, &value);\n  EXPECT_NEAR(value[0], 2.75, 1e-8);\n\n  // Lift a corner and check again.\n  mesh(0, 2) = 10.;\n  bary.Eval(mesh, Vector2d{.25, .75}, &value);\n  EXPECT_NEAR(value[0], 6.25, 1e-8);\n\n  // Test the alternative call signature.\n  EXPECT_NEAR(bary.Eval(mesh, Vector2d{.25, .75})[0], 6.25, 1e-8);\n}\n\nGTEST_TEST(BarycentricTest, EvalSymbolicTest) {\n  BarycentricMesh<double> bary{{{0.0, 1.0},  // BR\n                                {0.0, 1.0}}};\n\n  using symbolic::Variable;\n  using symbolic::Expression;\n  Variable a{\"a\"}, b{\"b\"}, c{\"c\"}, d{\"d\"};\n  RowVector4<Expression> mesh;\n  mesh << a, b, c, d;\n\n  Vector1<Expression> value;\n  // Check grid points.\n  bary.EvalWithMixedScalars<Expression>(mesh, Vector2d{0., 0.}, &value);\n  EXPECT_TRUE(value[0].EqualTo(a));\n  bary.EvalWithMixedScalars<Expression>(mesh, Vector2d{1., 0.}, &value);\n  EXPECT_TRUE(value[0].EqualTo(b));\n  bary.EvalWithMixedScalars<Expression>(mesh, Vector2d{0., 1.}, &value);\n  EXPECT_TRUE(value[0].EqualTo(c));\n  bary.EvalWithMixedScalars<Expression>(mesh, Vector2d{1., 1.}, &value);\n  EXPECT_TRUE(value[0].EqualTo(d));\n\n  // Check the middle.\n  bary.EvalWithMixedScalars<Expression>(mesh, Vector2d{.5, .5}, &value);\n  EXPECT_TRUE(value[0].EqualTo(.5 * a + .5 * d));\n\n  // Test the alternative call signature.\n  EXPECT_TRUE(\n      bary.EvalWithMixedScalars<Expression>(mesh, Vector2d{0., 0.})[0].EqualTo(\n          a));\n}\n\nGTEST_TEST(BarycentricTest, MultidimensionalOutput) {\n  BarycentricMesh<double> bary{{{0.0, 1.0},  // BR\n                                {0.0, 1.0}}};\n\n  const int kNumOutputs = 2;\n  MatrixXd mesh(kNumOutputs, bary.get_num_mesh_points());\n  mesh << 1., 2., 3., 4.,  // BR\n      5., 6., 7., 8.;\n\n  Vector2d value;\n  // Check the two faces.\n  bary.Eval(mesh, Vector2d{.75, .25}, &value);\n  EXPECT_TRUE(CompareMatrices(value, Vector2d{2.25, 6.25}, 1e-8));\n  bary.Eval(mesh, Vector2d{.25, .75}, &value);\n  EXPECT_TRUE(CompareMatrices(value, Vector2d{2.75, 6.75}, 1e-8));\n}\n\nVector1d my_sine(const Eigen::Ref<const Vector1d>& x) {\n  return Vector1d(std::sin(x[0]));\n}\n\n// Build a BarycentricMesh from a function pointer.\nGTEST_TEST(BarycentricTest, FromVectorFunc) {\n  BarycentricMesh<double>::Coordinates x_values{0, .1, .2, 5, 204};\n\n  BarycentricMesh<double> bary({x_values});\n\n  MatrixXd mesh_values = bary.MeshValuesFrom(&my_sine);\n\n  // Check that it evaluates correctly on the grid (the interpolation is\n  // verified with the other tests).\n  Vector1d y_value;\n  for (const auto& x : x_values) {\n    bary.Eval(mesh_values, Vector1d(x), &y_value);\n    EXPECT_EQ(y_value[0], std::sin(x));\n  }\n}\n\n// Build a BarycentricMesh from a lambda expression.\nGTEST_TEST(BarycentricTest, FromLambda) {\n  BarycentricMesh<double>::Coordinates x_values{0, .1, .2, 5, 204};\n\n  BarycentricMesh<double> bary({x_values});\n\n  MatrixXd mesh_values = bary.MeshValuesFrom(\n      [](const auto& x) { return Vector1d(std::sin(x[0])); });\n\n  // Check that it evaluates correctly on the grid (the interpolation is\n  // verified with the other tests).\n  Vector1d y_value;\n  for (const auto& x : x_values) {\n    bary.Eval(mesh_values, Vector1d(x), &y_value);\n    EXPECT_EQ(y_value[0], std::sin(x));\n  }\n}\n\n}  // namespace\n}  // namespace math\n}  // namespace drake\n", "meta": {"hexsha": "f1dd2dc17f96d3fd9471244793300e2e2f995862", "size": 7483, "ext": "cc", "lang": "C++", "max_stars_repo_path": "math/test/barycentric_test.cc", "max_stars_repo_name": "RobotLocomotion/drake-python3.7", "max_stars_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-02-25T02:01:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-17T04:52:04.000Z", "max_issues_repo_path": "math/test/barycentric_test.cc", "max_issues_repo_name": "RobotLocomotion/drake-python3.7", "max_issues_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "math/test/barycentric_test.cc", "max_forks_repo_name": "RobotLocomotion/drake-python3.7", "max_forks_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-13T12:05:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-13T12:05:39.000Z", "avg_line_length": 32.6768558952, "max_line_length": 79, "alphanum_fraction": 0.6586930376, "num_tokens": 2509, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390162, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.4768388970912981}}
{"text": "#pragma once\n\n#include <iostream>\n\n#include <chrono>\n#include <functional>\n#include <memory>\n#include <optional>\n\n#include <boost/hana.hpp>\n\n#include \"SignalPt.hpp\"\n\nnamespace chrono = std::chrono;\nusing namespace std::chrono_literals;\n\ntemplate <typename Clock = chrono::steady_clock>\nstruct PIDState {\n  chrono::time_point<Clock> time;\n  double errSum;\n  double error;\n  double ctrlVal;\n};\n\ntemplate <typename Clock = chrono::steady_clock>\nauto pid_algebra(double kp, double ki, double kd) {\n  return [kp, ki, kd](PIDState<Clock> prev,\n                      SignalPt<double, Clock> errSigl) -> PIDState<Clock> {\n    const chrono::duration<double> deltaT =\n        errSigl.time - prev.time;\n    if (deltaT <= chrono::seconds{0}) return prev;\n    const auto errSum = prev.errSum + (errSigl.value * deltaT.count());\n    const auto dErr = (errSigl.value - prev.error) / deltaT.count();\n    const auto ctrlVal = kp * errSigl.value + ki * errSum + kd * dErr;\n\n    return {errSigl.time, errSum, errSigl.value, ctrlVal};\n  };\n}\n", "meta": {"hexsha": "dce89b7aa2775ee59ec1e4c6a911f9a106a33ced", "size": 1022, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/pid.hpp", "max_stars_repo_name": "timtro/pid-unfolding", "max_stars_repo_head_hexsha": "3e9aaa0c47785bb1fc7464235774de1c255a3b68", "max_stars_repo_licenses": ["MIT"], "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/pid.hpp", "max_issues_repo_name": "timtro/pid-unfolding", "max_issues_repo_head_hexsha": "3e9aaa0c47785bb1fc7464235774de1c255a3b68", "max_issues_repo_licenses": ["MIT"], "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/pid.hpp", "max_forks_repo_name": "timtro/pid-unfolding", "max_forks_repo_head_hexsha": "3e9aaa0c47785bb1fc7464235774de1c255a3b68", "max_forks_repo_licenses": ["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.2051282051, "max_line_length": 75, "alphanum_fraction": 0.6819960861, "num_tokens": 266, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583169, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.47680882006058434}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   DataGen_FreeGasElasticMarginalBetaFunction.hpp\n//! \\author Alex Robinson\n//! \\brief  Free gas elastic marginal beta function definition\n//!\n//---------------------------------------------------------------------------//\n\n// Boost Includes\n#include <boost/bind.hpp>\n\n// Trilinos Includes\n#include <Teuchos_Tuple.hpp>\n\n// FRENSIE Includes\n#include \"DataGen_FreeGasElasticMarginalBetaFunction.hpp\"\n#include \"Utility_SearchAlgorithms.hpp\"\n#include \"Utility_KinematicHelpers.hpp\"\n#include \"Utility_ComparePolicy.hpp\"\n#include \"Utility_ContractException.hpp\"\n\nnamespace DataGen{\n\n// Constructor\nFreeGasElasticMarginalBetaFunction::FreeGasElasticMarginalBetaFunction(\n\t  const Teuchos::RCP<Utility::OneDDistribution>& \n\t  zero_temp_elastic_cross_section,\n          const Teuchos::RCP<MonteCarlo::NuclearScatteringAngularDistribution>&\n\t  cm_scattering_distribution,\n\t  const double A,\n\t  const double kT,\n\t  const double E )\n  : d_alpha_gkq_set( 1e-4, 0.0, 10000 ),\n    d_beta_gkq_set( 1e-4, 0.0, 10000 ),\n    d_sab_function( zero_temp_elastic_cross_section,\n\t\t    cm_scattering_distribution,\n\t\t    A,\n\t\t    kT ),\n    d_E( E ),\n    d_A( A ),\n    d_kT( kT ),\n    d_beta_min( 0.0 ),\n    d_norm_constant( 1.0 ),\n    d_cached_cdf_values()\n{\n  // Make sure the values are valid\n  testPrecondition( A > 0.0 );\n  testPrecondition( kT > 0.0 );\n  testPrecondition( E > 0.0 );\n  \n  updateCachedValues();\n}\n\n// Set the beta and energy values\nvoid FreeGasElasticMarginalBetaFunction::setIndependentVariables( \n\t\t\t\t\t\t\t       const double E )\n{\n  // Make sure the energy is valid\n  testPrecondition( E > 0.0 );\n  \n  d_E = E;\n\n  updateCachedValues();\n}\n\n// Get the lower beta limit\ndouble FreeGasElasticMarginalBetaFunction::getBetaMin() const\n{\n  return d_beta_min;\n}\n  \n// Get the normalization constant\ndouble FreeGasElasticMarginalBetaFunction::getNormalizationConstant() const\n{\n  return d_norm_constant;\n}\n\n// Evaluate the marginal PDF\ndouble FreeGasElasticMarginalBetaFunction::operator()( const double beta )\n{\n  // Make sure the beta value is valid\n  testPrecondition( beta >= d_beta_min );\n\n  return integratedSAlphaBetaFunction( beta )/d_norm_constant;\n}\n\n// Evaluate the marginal CDF\ndouble FreeGasElasticMarginalBetaFunction::evaluateCDF( const double beta )\n{\n  // Make sure the beta value is valid\n  testPrecondition( beta >= d_beta_min );\n\n  // Find the nearest cached evaluation of cdf\n  std::list<Utility::Pair<double,double> >::iterator lower_cdf_point = \n    d_cached_cdf_values.begin();\n\n  lower_cdf_point = Utility::Search::binaryLowerBound<Utility::FIRST>(\n\t\t\t\t\t\t     lower_cdf_point,\n\t\t\t\t\t\t     d_cached_cdf_values.end(),\n\t\t\t\t\t\t     beta );\n\n  // Calculate the cdf value\n  double cdf_value, cdf_value_error;\n\n  d_beta_gkq_set.integrateAdaptively<15>( *this,\n\t\t\t\t\t lower_cdf_point->first,\n\t\t\t\t\t beta,\n\t\t\t\t\t cdf_value,\n\t\t\t\t\t cdf_value_error );\n\n  cdf_value += lower_cdf_point->second;\n\n  // Cache the new cdf value\n  Utility::Pair<double,double> new_cdf_point( beta, cdf_value );\n\n  d_cached_cdf_values.insert( ++lower_cdf_point, new_cdf_point );\n\n  // Return the calculated cdf value\n  return cdf_value;\n}\n\n// Update the cached values\nvoid FreeGasElasticMarginalBetaFunction::updateCachedValues()\n{\n  d_beta_min = Utility::calculateBetaMin( d_E, d_kT );\n  std::cout << \"beta min: \" << d_beta_min << std::endl;\n  // Calculate the norm constant\n  double norm_constant_error;\n\n  boost::function<double (double beta)> d_integrated_sab_function = \n    boost::bind<double>( &FreeGasElasticMarginalBetaFunction::integratedSAlphaBetaFunction, boost::ref( *this ), _1 );\n  \n  d_beta_gkq_set.integrateAdaptively<15>( d_integrated_sab_function,\n  \t\t\t\t\t 400.0,\n  \t\t\t\t\t 540.0,\n  \t\t\t\t\t d_norm_constant,\n  \t\t\t\t\t norm_constant_error );\n  \n  // Teuchos::Tuple<double,3> points_of_interest = \n  //   Teuchos::tuple( d_beta_min, 515.0, -d_beta_min );\n  \n  // d_beta_gkq_set.integrateAdaptivelyWynnEpsilon( d_integrated_sab_function,\n  // \t\t\t\t\t\tpoints_of_interest(),\n  // \t\t\t\t\t\td_norm_constant,\n  // \t\t\t\t\t\tnorm_constant_error );\n\n  // Make sure the norm constant is non-zero\n  testPostcondition( d_norm_constant > 0.0 );\n  \n  // Reset the cached cdf values\n  d_cached_cdf_values.clear();\n\n  Utility::Pair<double,double> cdf_point( d_beta_min, 0.0 );\n  d_cached_cdf_values.push_back( cdf_point );\n\n  cdf_point( std::numeric_limits<double>::infinity(), 1.0 );\n\n  d_cached_cdf_values.push_back( cdf_point );\n}\n\n// Function that represents the integral of S(alpha,beta) over all alpha\ndouble FreeGasElasticMarginalBetaFunction::integratedSAlphaBetaFunction(\n\t\t\t\t\t\t\t    const double beta )\n{\n  // Make sure beta is valid\n  testPrecondition( beta >= d_beta_min );\n  \n  double alpha_min = Utility::calculateAlphaMin( d_E, beta, d_A, d_kT );\n  double alpha_max = Utility::calculateAlphaMax( d_E, beta, d_A, d_kT );\n\n  double function_value, function_value_error;\n  \n  boost::function<double (double alpha)> sab_function_wrapper = \n    boost::bind<double>( boost::ref( d_sab_function ), _1, beta, d_E );\n  \n  // d_alpha_gkq_set.integrateAdaptively<15>( sab_function_wrapper,\n  // \t\t\t\t\t  alpha_min,\n  // \t\t\t\t\t  alpha_max,\n  // \t\t\t\t\t  function_value,\n  // \t\t\t\t\t  function_value_error );\n\n  if( beta < 0.0 && beta > d_beta_min )\n  {\n    Teuchos::Tuple<double,3> points_of_interest = \n      Teuchos::tuple( alpha_min, -beta, alpha_max );\n    std::cout << points_of_interest() << std::endl;\n    d_beta_gkq_set.integrateAdaptivelyWynnEpsilon( sab_function_wrapper,\n\t\t\t\t\t\t  points_of_interest(),\n\t\t\t\t\t\t  function_value,\n\t\t\t\t\t\t  function_value_error );\n  }\n  else\n  {\n    d_alpha_gkq_set.integrateAdaptively<15>( sab_function_wrapper,\n\t\t\t\t\t    alpha_min,\n\t\t\t\t\t    alpha_max,\n\t\t\t\t\t    function_value,\n\t\t\t\t\t    function_value_error );\n  }\n\n  std::cout << beta << \" \" << function_value << std::endl;\n\n  // Make sure the return value is valid\n  testPostcondition(!Teuchos::ScalarTraits<double>::isnaninf(function_value));\n\n  return function_value;\n}\n\n} // end DataGen namespace\n\n//---------------------------------------------------------------------------//\n// end DataGen_FreeGasElasticMarginalBetaFunction.cpp\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "821196c2a334034b40914adeaf17f066133512a0", "size": 6249, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "packages/data_gen/free_gas_sab/src/DataGen_FreeGasElasticMarginalBetaFunction.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/free_gas_sab/src/DataGen_FreeGasElasticMarginalBetaFunction.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/free_gas_sab/src/DataGen_FreeGasElasticMarginalBetaFunction.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": 29.2009345794, "max_line_length": 118, "alphanum_fraction": 0.6764282285, "num_tokens": 1599, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127492339909, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.4767625387044704}}
{"text": "\r\n///////////////////////////////////////////////////////////////////////////////\r\n//  Copyright 2013 Nikhar Agrawal\r\n//  Copyright 2013 Christopher Kormanyos\r\n//  Copyright 2013 John Maddock\r\n//  Copyright 2013 Paul Bristow\r\n//  Distributed under the Boost\r\n//  Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef _BOOST_BERNOULLI_2013_05_30_HPP_\r\n  #define _BOOST_BERNOULLI_2013_05_30_HPP_\r\n\r\n  #include <boost/array.hpp>\r\n  #include <boost/cstdint.hpp>\r\n  #include \"detail/bernoulli_b2n.hpp\"\r\n\r\n  namespace boost { namespace math {\r\n\r\n  template <class T, class Policy>\r\n  inline T bernoulli_b2n(const int i, const Policy &pol)\r\n  {\n    if(i<0)\n      policies::raise_domain_error<T>(\"boost::math::bernoulli<%1%>\", \"Index should be >= 0 but got %1%\", T(i), pol);\r\n    const int i_2 = 2 * i;\r\n\r\n    return boost::math::detail::bernoulli_number_imp<T,Policy>(i_2, pol);\r\n  }\r\n\r\n  template <class T>\r\n  inline T bernoulli_b2n(const int i)\r\n  {\r\n    return boost::math::bernoulli_b2n<T>(i, policies::policy<>());\r\n  }\r\n\r\n  template <class T, class OutputIterator, class Policy>\r\n  inline OutputIterator bernoulli_b2n(int start_index,\r\n                                      unsigned number_of_bernoullis_b2n,\r\n                                      OutputIterator out_it,\r\n                                      const Policy& pol)\r\n  {\r\n    return boost::math::detail::bernoulli_series_imp<T, OutputIterator, Policy>(start_index,\r\n                                                                                number_of_bernoullis_b2n,\r\n                                                                                out_it,\r\n                                                                                pol);\r\n  }\r\n\r\n  template <class T, class OutputIterator>\r\n  inline OutputIterator bernoulli_b2n(int start_index,\r\n                                      unsigned number_of_bernoullis_b2n,\r\n                                      OutputIterator out_it)\r\n  {\r\n    return boost::math::bernoulli_b2n<T, OutputIterator>(start_index,\r\n                                                         number_of_bernoullis_b2n,\r\n                                                         out_it,\r\n                                                         policies::policy<>());\r\n  }\r\n\r\n\r\n\r\n} } // namespace boost::math\r\n\r\n#endif // _BOOST_BERNOULLI_2013_05_30_HPP_\r\n", "meta": {"hexsha": "55ced45116fbdcb5fa7ed3a94f171fcee067f2db", "size": 2429, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "SigTM/external/boost_sub/math/special_functions/bernoulli.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/external/boost_sub/math/special_functions/bernoulli.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/external/boost_sub/math/special_functions/bernoulli.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": 37.953125, "max_line_length": 117, "alphanum_fraction": 0.5125566077, "num_tokens": 534, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059775, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.4767472843606013}}
{"text": "/* boost random/piecewise_linear_distribution.hpp header file\r\n *\r\n * Copyright Steven Watanabe 2011\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 most recent version including documentation.\r\n *\r\n * $Id: piecewise_linear_distribution.hpp 83381 2013-03-09 22:55:05Z eric_niebler $\r\n */\r\n\r\n#ifndef BOOST_RANDOM_PIECEWISE_LINEAR_DISTRIBUTION_HPP_INCLUDED\r\n#define BOOST_RANDOM_PIECEWISE_LINEAR_DISTRIBUTION_HPP_INCLUDED\r\n\r\n#include <vector>\r\n#include <algorithm>\r\n#include <cmath>\r\n#include <cstdlib>\r\n#include <boost/assert.hpp>\r\n#include <boost/random/uniform_real.hpp>\r\n#include <boost/random/discrete_distribution.hpp>\r\n#include <boost/random/detail/config.hpp>\r\n#include <boost/random/detail/operators.hpp>\r\n#include <boost/random/detail/vector_io.hpp>\r\n\r\n#ifndef BOOST_NO_CXX11_HDR_INITIALIZER_LIST\r\n#include <initializer_list>\r\n#endif\r\n\r\n#include <boost/range/begin.hpp>\r\n#include <boost/range/end.hpp>\r\n\r\nnamespace boost {\r\nnamespace random {\r\n\r\n/**\r\n * The class @c piecewise_linear_distribution models a \\random_distribution.\r\n */\r\ntemplate<class RealType = double>\r\nclass piecewise_linear_distribution {\r\npublic:\r\n    typedef std::size_t input_type;\r\n    typedef RealType result_type;\r\n\r\n    class param_type {\r\n    public:\r\n\r\n        typedef piecewise_linear_distribution distribution_type;\r\n\r\n        /**\r\n         * Constructs a @c param_type object, representing a distribution\r\n         * that produces values uniformly distributed in the range [0, 1).\r\n         */\r\n        param_type()\r\n        {\r\n            _weights.push_back(RealType(1));\r\n            _weights.push_back(RealType(1));\r\n            _intervals.push_back(RealType(0));\r\n            _intervals.push_back(RealType(1));\r\n        }\r\n        /**\r\n         * Constructs a @c param_type object from two iterator ranges\r\n         * containing the interval boundaries and weights at the boundaries.\r\n         * If there are fewer than two boundaries, then this is equivalent to\r\n         * the default constructor and the distribution will produce values\r\n         * uniformly distributed in the range [0, 1).\r\n         *\r\n         * The values of the interval boundaries must be strictly\r\n         * increasing, and the number of weights must be the same as\r\n         * the number of interval boundaries.  If there are extra\r\n         * weights, they are ignored.\r\n         */\r\n        template<class IntervalIter, class WeightIter>\r\n        param_type(IntervalIter intervals_first, IntervalIter intervals_last,\r\n                   WeightIter weight_first)\r\n          : _intervals(intervals_first, intervals_last)\r\n        {\r\n            if(_intervals.size() < 2) {\r\n                _intervals.clear();\r\n                _weights.push_back(RealType(1));\r\n                _weights.push_back(RealType(1));\r\n                _intervals.push_back(RealType(0));\r\n                _intervals.push_back(RealType(1));\r\n            } else {\r\n                _weights.reserve(_intervals.size());\r\n                for(std::size_t i = 0; i < _intervals.size(); ++i) {\r\n                    _weights.push_back(*weight_first++);\r\n                }\r\n            }\r\n        }\r\n#ifndef BOOST_NO_CXX11_HDR_INITIALIZER_LIST\r\n        /**\r\n         * Constructs a @c param_type object from an initializer_list\r\n         * containing the interval boundaries and a unary function\r\n         * specifying the weights at the boundaries.  Each weight is\r\n         * determined by calling the function at the corresponding point.\r\n         *\r\n         * If the initializer_list contains fewer than two elements,\r\n         * this is equivalent to the default constructor and the\r\n         * distribution will produce values uniformly distributed\r\n         * in the range [0, 1).\r\n         */\r\n        template<class T, class F>\r\n        param_type(const std::initializer_list<T>& il, F f)\r\n          : _intervals(il.begin(), il.end())\r\n        {\r\n            if(_intervals.size() < 2) {\r\n                _intervals.clear();\r\n                _weights.push_back(RealType(1));\r\n                _weights.push_back(RealType(1));\r\n                _intervals.push_back(RealType(0));\r\n                _intervals.push_back(RealType(1));\r\n            } else {\r\n                _weights.reserve(_intervals.size());\r\n                for(typename std::vector<RealType>::const_iterator\r\n                    iter = _intervals.begin(), end = _intervals.end();\r\n                    iter != end; ++iter)\r\n                {\r\n                    _weights.push_back(f(*iter));\r\n                }\r\n            }\r\n        }\r\n#endif\r\n        /**\r\n         * Constructs a @c param_type object from Boost.Range ranges holding\r\n         * the interval boundaries and the weights at the boundaries.  If\r\n         * there are fewer than two interval boundaries, this is equivalent\r\n         * to the default constructor and the distribution will produce\r\n         * values uniformly distributed in the range [0, 1).  The\r\n         * number of weights must be equal to the number of\r\n         * interval boundaries.\r\n         */\r\n        template<class IntervalRange, class WeightRange>\r\n        param_type(const IntervalRange& intervals_arg,\r\n                   const WeightRange& weights_arg)\r\n          : _intervals(boost::begin(intervals_arg), boost::end(intervals_arg)),\r\n            _weights(boost::begin(weights_arg), boost::end(weights_arg))\r\n        {\r\n            if(_intervals.size() < 2) {\r\n                _weights.clear();\r\n                _weights.push_back(RealType(1));\r\n                _weights.push_back(RealType(1));\r\n                _intervals.clear();\r\n                _intervals.push_back(RealType(0));\r\n                _intervals.push_back(RealType(1));\r\n            }\r\n        }\r\n\r\n        /**\r\n         * Constructs the parameters for a distribution that approximates a\r\n         * function.  The range of the distribution is [xmin, xmax).  This\r\n         * range is divided into nw equally sized intervals and the weights\r\n         * are found by calling the unary function f on the boundaries of the\r\n         * intervals.\r\n         */\r\n        template<class F>\r\n        param_type(std::size_t nw, RealType xmin, RealType xmax, F f)\r\n        {\r\n            std::size_t n = (nw == 0) ? 1 : nw;\r\n            double delta = (xmax - xmin) / n;\r\n            BOOST_ASSERT(delta > 0);\r\n            for(std::size_t k = 0; k < n; ++k) {\r\n                _weights.push_back(f(xmin + k*delta));\r\n                _intervals.push_back(xmin + k*delta);\r\n            }\r\n            _weights.push_back(f(xmax));\r\n            _intervals.push_back(xmax);\r\n        }\r\n\r\n        /**  Returns a vector containing the interval boundaries. */\r\n        std::vector<RealType> intervals() const { return _intervals; }\r\n\r\n        /**\r\n         * Returns a vector containing the probability densities\r\n         * at all the interval boundaries.\r\n         */\r\n        std::vector<RealType> densities() const\r\n        {\r\n            RealType sum = static_cast<RealType>(0);\r\n            for(std::size_t i = 0; i < _intervals.size() - 1; ++i) {\r\n                RealType width = _intervals[i + 1] - _intervals[i];\r\n                sum += (_weights[i] + _weights[i + 1]) * width / 2;\r\n            }\r\n            std::vector<RealType> result;\r\n            result.reserve(_weights.size());\r\n            for(typename std::vector<RealType>::const_iterator\r\n                iter = _weights.begin(), end = _weights.end();\r\n                iter != end; ++iter)\r\n            {\r\n                result.push_back(*iter / sum);\r\n            }\r\n            return result;\r\n        }\r\n\r\n        /** Writes the parameters to a @c std::ostream. */\r\n        BOOST_RANDOM_DETAIL_OSTREAM_OPERATOR(os, param_type, parm)\r\n        {\r\n            detail::print_vector(os, parm._intervals);\r\n            detail::print_vector(os, parm._weights);\r\n            return os;\r\n        }\r\n        \r\n        /** Reads the parameters from a @c std::istream. */\r\n        BOOST_RANDOM_DETAIL_ISTREAM_OPERATOR(is, param_type, parm)\r\n        {\r\n            std::vector<RealType> new_intervals;\r\n            std::vector<RealType> new_weights;\r\n            detail::read_vector(is, new_intervals);\r\n            detail::read_vector(is, new_weights);\r\n            if(is) {\r\n                parm._intervals.swap(new_intervals);\r\n                parm._weights.swap(new_weights);\r\n            }\r\n            return is;\r\n        }\r\n\r\n        /** Returns true if the two sets of parameters are the same. */\r\n        BOOST_RANDOM_DETAIL_EQUALITY_OPERATOR(param_type, lhs, rhs)\r\n        {\r\n            return lhs._intervals == rhs._intervals\r\n                && lhs._weights == rhs._weights;\r\n        }\r\n        /** Returns true if the two sets of parameters are different. */\r\n        BOOST_RANDOM_DETAIL_INEQUALITY_OPERATOR(param_type)\r\n\r\n    private:\r\n        friend class piecewise_linear_distribution;\r\n\r\n        std::vector<RealType> _intervals;\r\n        std::vector<RealType> _weights;\r\n    };\r\n\r\n    /**\r\n     * Creates a new @c piecewise_linear_distribution that\r\n     * produces values uniformly distributed in the range [0, 1).\r\n     */\r\n    piecewise_linear_distribution()\r\n    {\r\n        default_init();\r\n    }\r\n    /**\r\n     * Constructs a piecewise_linear_distribution from two iterator ranges\r\n     * containing the interval boundaries and the weights at the boundaries.\r\n     * If there are fewer than two boundaries, then this is equivalent to\r\n     * the default constructor and creates a distribution that\r\n     * produces values uniformly distributed in the range [0, 1).\r\n     *\r\n     * The values of the interval boundaries must be strictly\r\n     * increasing, and the number of weights must be equal to\r\n     * the number of interval boundaries.  If there are extra\r\n     * weights, they are ignored.\r\n     *\r\n     * For example,\r\n     *\r\n     * @code\r\n     * double intervals[] = { 0.0, 1.0, 2.0 };\r\n     * double weights[] = { 0.0, 1.0, 0.0 };\r\n     * piecewise_constant_distribution<> dist(\r\n     *     &intervals[0], &intervals[0] + 3, &weights[0]);\r\n     * @endcode\r\n     *\r\n     * produces a triangle distribution.\r\n     */\r\n    template<class IntervalIter, class WeightIter>\r\n    piecewise_linear_distribution(IntervalIter first_interval,\r\n                                  IntervalIter last_interval,\r\n                                  WeightIter first_weight)\r\n      : _intervals(first_interval, last_interval)\r\n    {\r\n        if(_intervals.size() < 2) {\r\n            default_init();\r\n        } else {\r\n            _weights.reserve(_intervals.size());\r\n            for(std::size_t i = 0; i < _intervals.size(); ++i) {\r\n                _weights.push_back(*first_weight++);\r\n            }\r\n            init();\r\n        }\r\n    }\r\n#ifndef BOOST_NO_CXX11_HDR_INITIALIZER_LIST\r\n    /**\r\n     * Constructs a piecewise_linear_distribution from an\r\n     * initializer_list containing the interval boundaries\r\n     * and a unary function specifying the weights.  Each\r\n     * weight is determined by calling the function at the\r\n     * corresponding interval boundary.\r\n     *\r\n     * If the initializer_list contains fewer than two elements,\r\n     * this is equivalent to the default constructor and the\r\n     * distribution will produce values uniformly distributed\r\n     * in the range [0, 1).\r\n     */\r\n    template<class T, class F>\r\n    piecewise_linear_distribution(std::initializer_list<T> il, F f)\r\n      : _intervals(il.begin(), il.end())\r\n    {\r\n        if(_intervals.size() < 2) {\r\n            default_init();\r\n        } else {\r\n            _weights.reserve(_intervals.size());\r\n            for(typename std::vector<RealType>::const_iterator\r\n                iter = _intervals.begin(), end = _intervals.end();\r\n                iter != end; ++iter)\r\n            {\r\n                _weights.push_back(f(*iter));\r\n            }\r\n            init();\r\n        }\r\n    }\r\n#endif\r\n    /**\r\n     * Constructs a piecewise_linear_distribution from Boost.Range\r\n     * ranges holding the interval boundaries and the weights.  If\r\n     * there are fewer than two interval boundaries, this is equivalent\r\n     * to the default constructor and the distribution will produce\r\n     * values uniformly distributed in the range [0, 1).  The\r\n     * number of weights must be equal to the number of\r\n     * interval boundaries.\r\n     */\r\n    template<class IntervalsRange, class WeightsRange>\r\n    piecewise_linear_distribution(const IntervalsRange& intervals_arg,\r\n                                  const WeightsRange& weights_arg)\r\n      : _intervals(boost::begin(intervals_arg), boost::end(intervals_arg)),\r\n        _weights(boost::begin(weights_arg), boost::end(weights_arg))\r\n    {\r\n        if(_intervals.size() < 2) {\r\n            default_init();\r\n        } else {\r\n            init();\r\n        }\r\n    }\r\n    /**\r\n     * Constructs a piecewise_linear_distribution that approximates a\r\n     * function.  The range of the distribution is [xmin, xmax).  This\r\n     * range is divided into nw equally sized intervals and the weights\r\n     * are found by calling the unary function f on the interval boundaries.\r\n     */\r\n    template<class F>\r\n    piecewise_linear_distribution(std::size_t nw,\r\n                                  RealType xmin,\r\n                                  RealType xmax,\r\n                                  F f)\r\n    {\r\n        if(nw == 0) { nw = 1; }\r\n        RealType delta = (xmax - xmin) / nw;\r\n        _intervals.reserve(nw + 1);\r\n        for(std::size_t i = 0; i < nw; ++i) {\r\n            RealType x = xmin + i * delta;\r\n            _intervals.push_back(x);\r\n            _weights.push_back(f(x));\r\n        }\r\n        _intervals.push_back(xmax);\r\n        _weights.push_back(f(xmax));\r\n        init();\r\n    }\r\n    /**\r\n     * Constructs a piecewise_linear_distribution from its parameters.\r\n     */\r\n    explicit piecewise_linear_distribution(const param_type& parm)\r\n      : _intervals(parm._intervals),\r\n        _weights(parm._weights)\r\n    {\r\n        init();\r\n    }\r\n\r\n    /**\r\n     * Returns a value distributed according to the parameters of the\r\n     * piecewise_linear_distribution.\r\n     */\r\n    template<class URNG>\r\n    RealType operator()(URNG& urng) const\r\n    {\r\n        std::size_t i = _bins(urng);\r\n        bool is_in_rectangle = (i % 2 == 0);\r\n        i = i / 2;\r\n        uniform_real<RealType> dist(_intervals[i], _intervals[i+1]);\r\n        if(is_in_rectangle) {\r\n            return dist(urng);\r\n        } else if(_weights[i] < _weights[i+1]) {\r\n            return (std::max)(dist(urng), dist(urng));\r\n        } else {\r\n            return (std::min)(dist(urng), dist(urng));\r\n        }\r\n    }\r\n    \r\n    /**\r\n     * Returns a value distributed according to the parameters\r\n     * specified by param.\r\n     */\r\n    template<class URNG>\r\n    RealType operator()(URNG& urng, const param_type& parm) const\r\n    {\r\n        return piecewise_linear_distribution(parm)(urng);\r\n    }\r\n    \r\n    /** Returns the smallest value that the distribution can produce. */\r\n    result_type min BOOST_PREVENT_MACRO_SUBSTITUTION () const\r\n    { return _intervals.front(); }\r\n    /** Returns the largest value that the distribution can produce. */\r\n    result_type max BOOST_PREVENT_MACRO_SUBSTITUTION () const\r\n    { return _intervals.back(); }\r\n\r\n    /**\r\n     * Returns a vector containing the probability densities\r\n     * at the interval boundaries.\r\n     */\r\n    std::vector<RealType> densities() const\r\n    {\r\n        RealType sum = static_cast<RealType>(0);\r\n        for(std::size_t i = 0; i < _intervals.size() - 1; ++i) {\r\n            RealType width = _intervals[i + 1] - _intervals[i];\r\n            sum += (_weights[i] + _weights[i + 1]) * width / 2;\r\n        }\r\n        std::vector<RealType> result;\r\n        result.reserve(_weights.size());\r\n        for(typename std::vector<RealType>::const_iterator\r\n            iter = _weights.begin(), end = _weights.end();\r\n            iter != end; ++iter)\r\n        {\r\n            result.push_back(*iter / sum);\r\n        }\r\n        return result;\r\n    }\r\n    /**  Returns a vector containing the interval boundaries. */\r\n    std::vector<RealType> intervals() const { return _intervals; }\r\n\r\n    /** Returns the parameters of the distribution. */\r\n    param_type param() const\r\n    {\r\n        return param_type(_intervals, _weights);\r\n    }\r\n    /** Sets the parameters of the distribution. */\r\n    void param(const param_type& parm)\r\n    {\r\n        std::vector<RealType> new_intervals(parm._intervals);\r\n        std::vector<RealType> new_weights(parm._weights);\r\n        init(new_intervals, new_weights);\r\n        _intervals.swap(new_intervals);\r\n        _weights.swap(new_weights);\r\n    }\r\n    \r\n    /**\r\n     * Effects: Subsequent uses of the distribution do not depend\r\n     * on values produced by any engine prior to invoking reset.\r\n     */\r\n    void reset() { _bins.reset(); }\r\n\r\n    /** Writes a distribution to a @c std::ostream. */\r\n    BOOST_RANDOM_DETAIL_OSTREAM_OPERATOR(\r\n        os, piecewise_linear_distribution, pld)\r\n    {\r\n        os << pld.param();\r\n        return os;\r\n    }\r\n\r\n    /** Reads a distribution from a @c std::istream */\r\n    BOOST_RANDOM_DETAIL_ISTREAM_OPERATOR(\r\n        is, piecewise_linear_distribution, pld)\r\n    {\r\n        param_type parm;\r\n        if(is >> parm) {\r\n            pld.param(parm);\r\n        }\r\n        return is;\r\n    }\r\n\r\n    /**\r\n     * Returns true if the two distributions will return the\r\n     * same sequence of values, when passed equal generators.\r\n     */\r\n    BOOST_RANDOM_DETAIL_EQUALITY_OPERATOR(\r\n        piecewise_linear_distribution, lhs,  rhs)\r\n    {\r\n        return lhs._intervals == rhs._intervals && lhs._weights == rhs._weights;\r\n    }\r\n    /**\r\n     * Returns true if the two distributions may return different\r\n     * sequences of values, when passed equal generators.\r\n     */\r\n    BOOST_RANDOM_DETAIL_INEQUALITY_OPERATOR(piecewise_linear_distribution)\r\n\r\nprivate:\r\n\r\n    /// @cond \\show_private\r\n\r\n    void init(const std::vector<RealType>& intervals_arg,\r\n              const std::vector<RealType>& weights_arg)\r\n    {\r\n        std::vector<RealType> bin_weights;\r\n        bin_weights.reserve((intervals_arg.size() - 1) * 2);\r\n        for(std::size_t i = 0; i < intervals_arg.size() - 1; ++i) {\r\n            RealType width = intervals_arg[i + 1] - intervals_arg[i];\r\n            RealType w1 = weights_arg[i];\r\n            RealType w2 = weights_arg[i + 1];\r\n            bin_weights.push_back((std::min)(w1, w2) * width);\r\n            bin_weights.push_back(std::abs(w1 - w2) * width / 2);\r\n        }\r\n        typedef discrete_distribution<std::size_t, RealType> bins_type;\r\n        typename bins_type::param_type bins_param(bin_weights);\r\n        _bins.param(bins_param);\r\n    }\r\n\r\n    void init()\r\n    {\r\n        init(_intervals, _weights);\r\n    }\r\n\r\n    void default_init()\r\n    {\r\n        _intervals.clear();\r\n        _intervals.push_back(RealType(0));\r\n        _intervals.push_back(RealType(1));\r\n        _weights.clear();\r\n        _weights.push_back(RealType(1));\r\n        _weights.push_back(RealType(1));\r\n        init();\r\n    }\r\n\r\n    discrete_distribution<std::size_t, RealType> _bins;\r\n    std::vector<RealType> _intervals;\r\n    std::vector<RealType> _weights;\r\n\r\n    /// @endcond\r\n};\r\n\r\n}\r\n}\r\n\r\n#endif\r\n", "meta": {"hexsha": "9c6edc2b72524c83db8ea795e789a49f714db4b6", "size": 19389, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/random/piecewise_linear_distribution.hpp", "max_stars_repo_name": "PXLVision/opengv", "max_stars_repo_head_hexsha": "e48f77da4db7b8cee36ec677ed4ff5c5354571bb", "max_stars_repo_licenses": ["BSD-3-Clause"], "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": "third_party/boost/random/piecewise_linear_distribution.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": "third_party/boost/random/piecewise_linear_distribution.hpp", "max_forks_repo_name": "PXLVision/opengv", "max_forks_repo_head_hexsha": "e48f77da4db7b8cee36ec677ed4ff5c5354571bb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2015-03-09T09:03:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-05T15:08:41.000Z", "avg_line_length": 36.5141242938, "max_line_length": 84, "alphanum_fraction": 0.5813605653, "num_tokens": 4186, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.47674728436060126}}
{"text": "/*\n * Software License Agreement (BSD License)\n *\n *  Copyright (c) 2014 Max-Planck-Institute for Intelligent Systems,\n *                     University of Southern California\n *    Jan Issac (jan.issac@gmail.com)\n *    Manuel Wuthrich (manuel.wuthrich@gmail.com)\n *\n *\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions\n *  are met:\n *\n *   * Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *   * Redistributions in binary form must reproduce the above\n *     copyright notice, this list of conditions and the following\n *     disclaimer in the documentation and/or other materials provided\n *     with the distribution.\n *   * Neither the name of Willow Garage, Inc. nor the names of its\n *     contributors may be used to endorse or promote products derived\n *     from this software without specific prior written permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n *  \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n *  POSSIBILITY OF SUCH DAMAGE.\n *\n */\n\n/**\n * @date 2014\n * @author Jan Issac (jan.issac@gmail.com)\n * Max-Planck-Institute for Intelligent Systems,\n * University of Southern California\n */\n\n#include <gtest/gtest.h>\n\n#include <memory>\n\n#include <Eigen/Dense>\n\n#include <fl/exception/exception.hpp>\n#include <fl/filter/gaussian/gaussian_filter.hpp>\n#include <fl/filter/gaussian/unscented_transform.hpp>\n\n#include \"gaussian_filter_stubs.hpp\"\n\n\ntemplate <typename FilteringAlgorithm>\nclass FilteringContext\n{\npublic:\n    typedef fl::FilterInterface<FilteringAlgorithm> Filter;\n\n    FilteringContext(const typename Filter::Ptr& filter)\n        : filter_(filter)\n    {\n\n    }\n\n    void predict()\n    {\n        filter_->predict(0.0, typename Filter::Input(), state_distr_, state_distr_);\n    }\n\n    void update()\n    {\n        filter_->update(typename Filter::Observation(), state_distr_, state_distr_);\n    }\n\n    typename Filter::Ptr filter()\n    {\n        return filter_;\n    }\n\n    typename Filter::Ptr filter_;\n    typename Filter::Observation y_;\n    typename Filter::StateDistribution state_distr_;\n};\n\nTEST(GaussianFilter, some_test)\n{\n    /* ===  Step 1: define vectorial types === */\n    typedef Eigen::Matrix<double, 11,  1> State;\n    typedef Eigen::Matrix<double, 100, 1> Obsrv;\n    typedef Eigen::Matrix<double, 3,   1> Input;\n    typedef Eigen::Matrix<double, 6,   1> StateNoise;\n    typedef Eigen::Matrix<double, 100, 1> ObsrvNoise;\n\n    /* == Step 2: define models == */\n    typedef ProcessModelStub<State, StateNoise, Input> ProcessModel;\n    typedef ObservationModelStub<State, Obsrv, ObsrvNoise> ObservationModel;\n\n    /* == Step 3: define the custom filter algorithm == */\n    typedef fl::GaussianFilter<\n                ProcessModel,\n                ObservationModel,\n                fl::UnscentedTransform\n            > UnscentedKalmanFilter;\n\n    typedef fl::FilterInterface<UnscentedKalmanFilter> Filter;\n\n    std::shared_ptr<Filter> filter =\n        std::make_shared<UnscentedKalmanFilter>(\n            std::make_shared<ProcessModel>(),\n            std::make_shared<ObservationModel>(),\n            std::make_shared<fl::UnscentedTransform>());\n\n    typename Filter::StateDistribution state_distr;\n\n    filter->predict(0.0, Input(), state_distr, state_distr);\n    filter->update(Obsrv(), state_distr, state_distr);\n    filter->predict_and_update(0., Input(), Obsrv(), state_distr, state_distr);\n}\n\n//TEST(GaussianFilter, context_test)\n//{\n//    /* ===  Step 1: define vectorial types === */\n//    typedef Eigen::Matrix<double, 7,  1> State;\n//    typedef Eigen::Matrix<double, 4, 1> Obsrv;\n//    typedef Eigen::Matrix<double, 3,   1> Input;\n//    typedef Eigen::Matrix<double, 6,   1> StateNoise;\n//    typedef Eigen::Matrix<double, 4, 1> ObsrvNoise;\n\n//    /* == Step 2: define models == */\n//    typedef ProcessModelStub<State, StateNoise, Input> ProcessModel;\n//    typedef ObservationModelStub<State, Obsrv, ObsrvNoise> ObservationModel;\n\n//    /* == Step 3: define filter algorithm == */\n//    typedef fl::GaussianFilter<\n//                ProcessModel,\n//                ObservationModel,\n//                fl::UnscentedTransform\n//            > UnscentedKalmanFilter;\n\n//    FilteringContext<UnscentedKalmanFilter> filter_context(\n//        std::make_shared<UnscentedKalmanFilter>(\n//            std::make_shared<ProcessModel>(),\n//            std::make_shared<ObservationModel>(),\n//            std::make_shared<fl::UnscentedTransform>()));\n\n//    filter_context.predict();\n//    filter_context.update();\n//}\n\n", "meta": {"hexsha": "027651c1b4ff5e483d1b123907519e185a5b8a0e", "size": 5321, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/gaussian_filter/gaussian_filter_test.cpp", "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": "test/gaussian_filter/gaussian_filter_test.cpp", "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": "test/gaussian_filter/gaussian_filter_test.cpp", "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": 33.8917197452, "max_line_length": 84, "alphanum_fraction": 0.6831422665, "num_tokens": 1259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.47674728436060126}}
{"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 *      120323    K. Kumar          Created based off of unit test for RKF45 integrator; test data\n *                                  taken from (The Mathworks, 2012).\n *      120328    K. Kumar          Moved (Burden and Faires, 2011) test class to its own file.\n *      120404    K. Kumar          Updated MATLAB unit test by adding discrete-event data file.\n *      130116    K. Kumar          Rewrote unit test to make use of testing code for numerical\n *                                  integrators migrated to Tudat Core.\n *      130909    K. Kumar          Updated error tolerances for MuPAD-based tests.\n *\n *    References\n *      Burden, R.L., Faires, J.D. Numerical Analysis, 7th Edition, Books/Cole, 2001.\n *      The Mathworks, Inc. RKF87, Symbolic Math Toolbox, 2012.\n *\n *    Notes\n *      All the test for this integrator are based on the data generated using the Symbolic Math\n *      Toolbox (MathWorks, 2012). Ideally, another source of data should be used to complete the\n *      testing.\n *\n *      The single step and full integration error tolerances were picked to be as small as\n *      possible, without causing the tests to fail. These values are not deemed to indicate any\n *      bugs in the code; however, it is important to take these discrepancies into account when\n *      using this numerical integrator.\n *\n */\n\n#define BOOST_TEST_MAIN\n\n#include <boost/make_shared.hpp>\n#include <boost/test/unit_test.hpp>\n\n#include \"Tudat/Mathematics/NumericalIntegrators/rungeKuttaVariableStepSizeIntegrator.h\"\n#include \"Tudat/Mathematics/NumericalIntegrators/rungeKuttaCoefficients.h\"\n#include \"Tudat/Mathematics/NumericalIntegrators/numericalIntegrator.h\"\n#include \"Tudat/Mathematics/NumericalIntegrators/reinitializableNumericalIntegrator.h\"\n#include \"Tudat/Mathematics/NumericalIntegrators/UnitTests/numericalIntegratorTests.h\"\n#include \"Tudat/Mathematics/NumericalIntegrators/UnitTests/numericalIntegratorTestFunctions.h\"\n\n#include \"Tudat/InputOutput/matrixTextFileReader.h\"\n#include \"Tudat/InputOutput/basicInputOutput.h\"\n#include \"Tudat/Mathematics/BasicMathematics/linearAlgebra.h\"\n\n#include <limits>\n#include <string>\n\n#include <Eigen/Core>\n\nnamespace tudat\n{\nnamespace unit_tests\n{\n\nBOOST_AUTO_TEST_SUITE( test_runge_kutta_fehlberg_78_integrator )\n\nusing linear_algebra::flipMatrixRows;\n\nusing numerical_integrators::NumericalIntegratorXdPointer;\nusing numerical_integrators::ReinitializableNumericalIntegratorXdPointer;\nusing numerical_integrators::RungeKuttaVariableStepSizeIntegratorXd;\nusing numerical_integrators::RungeKuttaCoefficients;\n\nusing numerical_integrator_test_functions::computeNonAutonomousModelStateDerivative;\nusing numerical_integrator_test_functions::computeFehlbergLogirithmicTestODEStateDerivative ;\nusing numerical_integrator_test_functions::computeAnalyticalStateFehlbergODE ;\n\n//! Test Runge-Kutta-Fehlberg 78 integrator using benchmark ODE of Fehlberg (1968)\nBOOST_AUTO_TEST_CASE( test_RungeKuttaFehlberg78_Integrator_Fehlberg_Benchmark )\n{\n    using namespace numerical_integrators;\n    RungeKuttaCoefficients coeff78 =\n            RungeKuttaCoefficients::get( RungeKuttaCoefficients::rungeKuttaFehlberg78 );\n\n    // Integrator settings\n    double minimumStepSize   = std::numeric_limits<double>::epsilon( );\n    double maximumStepSize   = std::numeric_limits<double>::infinity( );\n    double initialStepSize   = 1E-6; // Error: 0.0521 for initialStepSize = 1 ?\n    double relativeTolerance = 1E-16;\n    double absoluteTolerance = 1E-16;\n\n    // Initial conditions\n    double initialTime = 0.0;\n    double finalTime   = 5.0;\n    Eigen::Vector2d initialState( exp( 1.0 ), 1.0);\n\n    // Setup integrator\n    numerical_integrators::RungeKuttaVariableStepSizeIntegratorXd integrator78(\n                coeff78, computeFehlbergLogirithmicTestODEStateDerivative,\n                initialTime, initialState, minimumStepSize,\n                maximumStepSize, relativeTolerance, absoluteTolerance );\n\n\n    // Obtain numerical solution\n    Eigen::Vector2d numericalSolution = integrator78.integrateTo( finalTime, initialStepSize );\n\n    // Analytical solution\n    Eigen::Vector2d analyticalSolution = computeAnalyticalStateFehlbergODE( finalTime, initialState );\n\n    Eigen::Vector2d computedError = numericalSolution - analyticalSolution;\n    BOOST_CHECK_SMALL( std::fabs(computedError( 0 )), 1E-13 );\n    BOOST_CHECK_SMALL( std::fabs(computedError( 1 )), 1E-13 );\n}\n\n//! Test Runge-Kutta-Fehlberg 78 integrator using benchmark data from (The MathWorks, 2012).\nBOOST_AUTO_TEST_CASE( testRungeKuttaFehlberg78IntegratorUsingMatlabData )\n{\n    using namespace numerical_integrator_tests;\n\n    // Read in benchmark data (generated using Symbolic Math Toolbox in Matlab\n    // (The MathWorks, 2012)). This data is generated using the RKF87 numerical integrator.\n    const std::string pathToForwardIntegrationOutputFile = input_output::getTudatRootPath( )\n            + \"/Mathematics/NumericalIntegrators/UnitTests\"\n            + \"/matlabOutputRungeKuttaFehlberg78Forward.txt\";\n    const std::string pathToDiscreteEventIntegrationOutputFile = input_output::getTudatRootPath( )\n            + \"/Mathematics/NumericalIntegrators/UnitTests\"\n            + \"/matlabOutputRungeKuttaFehlberg78DiscreteEvent.txt\";\n\n    // Store benchmark data in matrix.\n    const Eigen::MatrixXd matlabForwardIntegrationData =\n            input_output::readMatrixFromFile( pathToForwardIntegrationOutputFile, \",\" );\n    Eigen::MatrixXd matlabBackwardIntegrationData = matlabForwardIntegrationData;\n    flipMatrixRows( matlabBackwardIntegrationData );\n    const Eigen::MatrixXd matlabDiscreteEventIntegrationData =\n            input_output::readMatrixFromFile( pathToDiscreteEventIntegrationOutputFile, \",\" );\n\n    // Set integrator parameters.\n\n    // All of the following parameters are set such that the input data is fully accepted by the\n    // integrator, to determine the steps to be taken.\n    const double zeroMinimumStepSize = std::numeric_limits< double >::epsilon( );\n    const double infiniteMaximumStepSize = std::numeric_limits< double >::infinity( );\n    const double infiniteRelativeErrorTolerance = std::numeric_limits< double >::infinity( );\n    const double infiniteAbsoluteErrorTolerance = std::numeric_limits< double >::infinity( );\n\n    // The following parameters set how the error control mechanism should work.\n    const double relativeErrorTolerance = 1.0e-15;\n    const double absoluteErrorTolerance = 1.0e-15;\n\n    // Case 1: Execute integrateTo() to integrate one step forward in time.\n    {\n        // Declare integrator with all necessary settings.\n        NumericalIntegratorXdPointer integrator\n                = boost::make_shared< RungeKuttaVariableStepSizeIntegratorXd >(\n                    RungeKuttaCoefficients::get( RungeKuttaCoefficients::rungeKuttaFehlberg78 ),\n                    &computeNonAutonomousModelStateDerivative,\n                    matlabForwardIntegrationData( FIRST_ROW, TIME_COLUMN_INDEX ),\n                    ( Eigen::VectorXd( 1 )\n                      << matlabForwardIntegrationData( FIRST_ROW,\n                                                       STATE_COLUMN_INDEX ) ).finished( ),\n                    zeroMinimumStepSize,\n                    infiniteMaximumStepSize,\n                    infiniteRelativeErrorTolerance,\n                    infiniteAbsoluteErrorTolerance );\n\n        executeOneIntegrateToStep( matlabForwardIntegrationData, 1.0e-15, integrator );\n    }\n\n    // Case 2: Execute performIntegrationStep() to perform multiple integration steps until final\n    //         time.\n    {\n        // Declare integrator with all necessary settings.\n        NumericalIntegratorXdPointer integrator\n                = boost::make_shared< RungeKuttaVariableStepSizeIntegratorXd >(\n                    RungeKuttaCoefficients::get( RungeKuttaCoefficients::rungeKuttaFehlberg78 ),\n                    &computeNonAutonomousModelStateDerivative,\n                    matlabForwardIntegrationData( FIRST_ROW, TIME_COLUMN_INDEX ),\n                    ( Eigen::VectorXd( 1 )\n                      << matlabForwardIntegrationData( FIRST_ROW,\n                                                       STATE_COLUMN_INDEX ) ).finished( ),\n                    zeroMinimumStepSize,\n                    infiniteMaximumStepSize,\n                    infiniteRelativeErrorTolerance,\n                    infiniteAbsoluteErrorTolerance );\n\n        performIntegrationStepToSpecifiedTime( matlabForwardIntegrationData,\n                                               1.0e-15, 1.0e-15, integrator );\n    }\n\n    // Case 3: Execute performIntegrationStep() to perform multiple integration steps until initial\n    //         time (backwards).\n    {\n        // Declare integrator with all necessary settings.\n        NumericalIntegratorXdPointer integrator\n                = boost::make_shared< RungeKuttaVariableStepSizeIntegratorXd >(\n                    RungeKuttaCoefficients::get( RungeKuttaCoefficients::rungeKuttaFehlberg78 ),\n                    &computeNonAutonomousModelStateDerivative,\n                    matlabBackwardIntegrationData( FIRST_ROW, TIME_COLUMN_INDEX ),\n                    ( Eigen::VectorXd( 1 )\n                      << matlabBackwardIntegrationData( FIRST_ROW,\n                                                        STATE_COLUMN_INDEX ) ).finished( ),\n                    zeroMinimumStepSize,\n                    infiniteMaximumStepSize,\n                    infiniteRelativeErrorTolerance,\n                    infiniteAbsoluteErrorTolerance );\n\n        performIntegrationStepToSpecifiedTime( matlabBackwardIntegrationData,\n                                               1.0e-15, 1.0e-14, integrator );\n    }\n\n    // Case 4: Execute integrateTo() to integrate to specified time in one step.\n    {\n        // Note that this test has a strange issue that the if the absolute error tolerance is set\n        // to 1.0e-15, the last step that the integrateTo() function takes does not result in the\n        // expected final time of 1.0. As a temporary solution, the absolute error tolerance has\n        // been multiplied by 10.0, which seems to solve the problem. This error indicated a\n        // possible problem with the implementation of the integrateTo() function, which needs to\n        // be investigated in future.\n\n        // Declare integrator with all necessary settings.\n        NumericalIntegratorXdPointer integrator\n                = boost::make_shared< RungeKuttaVariableStepSizeIntegratorXd >(\n                    RungeKuttaCoefficients::get( RungeKuttaCoefficients::rungeKuttaFehlberg78 ),\n                    &computeNonAutonomousModelStateDerivative,\n                    matlabForwardIntegrationData( FIRST_ROW, TIME_COLUMN_INDEX ),\n                    ( Eigen::VectorXd( 1 )\n                      << matlabForwardIntegrationData( FIRST_ROW,\n                                                       STATE_COLUMN_INDEX ) ).finished( ),\n                    zeroMinimumStepSize,\n                    infiniteMaximumStepSize,\n                    relativeErrorTolerance,\n                    absoluteErrorTolerance * 10.0 );\n\n        executeIntegrateToToSpecifiedTime( matlabForwardIntegrationData, 1.0e-13, integrator,\n                                           matlabForwardIntegrationData(\n                                               matlabForwardIntegrationData.rows( ) - 1,\n                                               TIME_COLUMN_INDEX ) );\n    }\n\n    // Case 5: Execute performIntegrationstep() to integrate to specified time in multiple steps,\n    //         including discrete events.\n    {\n        // Declare integrator with all necessary settings.\n        ReinitializableNumericalIntegratorXdPointer integrator\n                = boost::make_shared< RungeKuttaVariableStepSizeIntegratorXd >(\n                    RungeKuttaCoefficients::get( RungeKuttaCoefficients::rungeKuttaFehlberg78 ),\n                    &computeNonAutonomousModelStateDerivative,\n                    matlabForwardIntegrationData( FIRST_ROW, TIME_COLUMN_INDEX ),\n                    ( Eigen::VectorXd( 1 )\n                      << matlabForwardIntegrationData( FIRST_ROW,\n                                                       STATE_COLUMN_INDEX ) ).finished( ),\n                    zeroMinimumStepSize,\n                    infiniteMaximumStepSize,\n                    infiniteRelativeErrorTolerance,\n                    infiniteAbsoluteErrorTolerance );\n\n        performIntegrationStepToSpecifiedTimeWithEvents( matlabDiscreteEventIntegrationData,\n                                                         1.0e-15, 1.0e-13, integrator );\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END( )\n\n} // namespace unit_tests\n} // namespace tudat\n", "meta": {"hexsha": "c8e14b011ff74895f07166afb73982a56f361aee", "size": 14436, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Mathematics/NumericalIntegrators/UnitTests/unitTestRungeKuttaFehlberg78Integrator.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/NumericalIntegrators/UnitTests/unitTestRungeKuttaFehlberg78Integrator.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/NumericalIntegrators/UnitTests/unitTestRungeKuttaFehlberg78Integrator.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": 51.928057554, "max_line_length": 102, "alphanum_fraction": 0.6794125797, "num_tokens": 3099, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.47674728436060126}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n// Unit test\r\n\r\n// Copyright (c) 2015, Oracle and/or its affiliates.\r\n\r\n// Licensed under the Boost Software License version 1.0.\r\n// http://www.boost.org/users/license.html\r\n\r\n// Contributed and/or modified by Menelaos Karavelas, on behalf of Oracle\r\n\r\n#ifndef BOOST_TEST_MODULE\r\n#define BOOST_TEST_MODULE test_intersection_linear_linear_areal\r\n#endif\r\n\r\n#ifdef BOOST_GEOMETRY_TEST_DEBUG\r\n#define BOOST_GEOMETRY_DEBUG_TURNS\r\n#define BOOST_GEOMETRY_DEBUG_SEGMENT_IDENTIFIER\r\n#endif\r\n\r\n#include <boost/test/included/unit_test.hpp>\r\n\r\n#include <boost/range.hpp>\r\n\r\n#include <boost/geometry/geometries/linestring.hpp>\r\n#include <boost/geometry/geometries/multi_linestring.hpp>\r\n#include <boost/geometry/geometries/ring.hpp>\r\n#include <boost/geometry/geometries/polygon.hpp>\r\n#include <boost/geometry/geometries/multi_polygon.hpp>\r\n\r\n#include \"test_intersection_linear_linear.hpp\"\r\n\r\ntypedef bg::model::point<double,2,bg::cs::cartesian>  point_type;\r\ntypedef bg::model::multi_linestring\r\n    <\r\n        bg::model::linestring<point_type>\r\n    >  multi_linestring_type;\r\n\r\ntypedef bg::model::ring<point_type, true, false> open_ring_type;\r\ntypedef bg::model::polygon<point_type, true, false> open_polygon_type;\r\ntypedef bg::model::multi_polygon<open_polygon_type> open_multipolygon_type;\r\n\r\ntypedef bg::model::ring<point_type> closed_ring_type;\r\ntypedef bg::model::polygon<point_type> closed_polygon_type;\r\ntypedef bg::model::multi_polygon<closed_polygon_type> closed_multipolygon_type;\r\n\r\n\r\ntemplate\r\n<\r\n    typename OpenAreal1,\r\n    typename OpenAreal2,\r\n    typename ClosedAreal1,\r\n    typename ClosedAreal2,\r\n    typename MultiLinestring\r\n>\r\nstruct test_intersection_aal\r\n{\r\n    static inline void apply(std::string const& case_id,\r\n                             OpenAreal1 const& open_areal1,\r\n                             OpenAreal2 const& open_areal2,\r\n                             MultiLinestring const& expected1,\r\n                             MultiLinestring const& expected2)\r\n    {\r\n        typedef test_intersection_of_geometries\r\n            <\r\n                OpenAreal1, OpenAreal2, MultiLinestring\r\n            > tester;\r\n\r\n        tester::apply(open_areal1, open_areal2, expected1, expected2, case_id);\r\n\r\n        ClosedAreal1 closed_areal1;\r\n        ClosedAreal2 closed_areal2;\r\n        bg::convert(open_areal1, closed_areal1);\r\n        bg::convert(open_areal2, closed_areal2);\r\n\r\n        typedef test_intersection_of_geometries\r\n            <\r\n                ClosedAreal1, ClosedAreal2, MultiLinestring\r\n            > tester_of_closed;\r\n\r\n        std::string case_id_closed = case_id + \"-closed\";\r\n\r\n#ifdef BOOST_GEOMETRY_TEST_DEBUG\r\n        std::cout << \"testing closed areal geometries...\" << std::endl;\r\n#endif\r\n        tester_of_closed::apply(closed_areal1, closed_areal2,\r\n                                expected1, expected2, case_id_closed);\r\n    }\r\n\r\n    static inline void apply(std::string const& case_id,\r\n                             OpenAreal1 const& open_areal1,\r\n                             OpenAreal2 const& open_areal2,\r\n                             MultiLinestring const& expected)\r\n    {\r\n        apply(case_id, open_areal1, open_areal2, expected, expected);\r\n    }\r\n};\r\n\r\n\r\nBOOST_AUTO_TEST_CASE( test_intersection_ring_ring_linestring )\r\n{\r\n#ifdef BOOST_GEOMETRY_TEST_DEBUG\r\n    std::cout << std::endl << std::endl << std::endl;\r\n    std::cout << \"*** RING / RING / LINEAR INTERSECTION ***\" << std::endl;\r\n    std::cout << std::endl;\r\n#endif\r\n    typedef open_ring_type OG;\r\n    typedef closed_ring_type CG;\r\n    typedef multi_linestring_type ML;\r\n\r\n    typedef test_intersection_aal<OG, OG, CG, CG, ML> tester;\r\n\r\n    tester::apply\r\n        (\"r-r-01\",\r\n         from_wkt<OG>(\"POLYGON((0 0,0 2,2 2,2 0))\"),\r\n         from_wkt<OG>(\"POLYGON((2 1,2 4,4 4,4 0,1 0))\"),\r\n         from_wkt<ML>(\"MULTILINESTRING((2 1,2 2),(2 0,1 0),(2 1,2 1))\"),\r\n         from_wkt<ML>(\"MULTILINESTRING((2 2,2 1),(2 0,1 0),(2 1,2 1))\")\r\n         );\r\n\r\n    tester::apply\r\n        (\"r-r-02\",\r\n         from_wkt<OG>(\"POLYGON(())\"),\r\n         from_wkt<OG>(\"POLYGON((2 1,2 4,4 4,4 0,1 0))\"),\r\n         from_wkt<ML>(\"MULTILINESTRING()\")\r\n         );\r\n\r\n    tester::apply\r\n        (\"r-r-03\",\r\n         from_wkt<OG>(\"POLYGON((2 1,2 4,4 4,4 0,1 0))\"),\r\n         from_wkt<OG>(\"POLYGON(())\"),\r\n         from_wkt<ML>(\"MULTILINESTRING()\")\r\n         );\r\n\r\n    tester::apply\r\n        (\"r-r-04\",\r\n         from_wkt<OG>(\"POLYGON(())\"),\r\n         from_wkt<OG>(\"POLYGON(())\"),\r\n         from_wkt<ML>(\"MULTILINESTRING()\")\r\n         );\r\n}\r\n\r\n\r\nBOOST_AUTO_TEST_CASE( test_intersection_ring_polygon_linestring )\r\n{\r\n#ifdef BOOST_GEOMETRY_TEST_DEBUG\r\n    std::cout << std::endl << std::endl << std::endl;\r\n    std::cout << \"*** RING / POLYGON / LINEAR INTERSECTION ***\" << std::endl;\r\n    std::cout << std::endl;\r\n#endif\r\n    typedef open_ring_type OG1;\r\n    typedef open_polygon_type OG2;\r\n    typedef closed_ring_type CG1;\r\n    typedef closed_polygon_type CG2;\r\n    typedef multi_linestring_type ML;\r\n\r\n    typedef test_intersection_aal<OG1, OG2, CG1, CG2, ML> tester;\r\n\r\n    tester::apply\r\n        (\"r-pg-01\",\r\n         from_wkt<OG1>(\"POLYGON((0 0,0 2,2 2,2 0))\"),\r\n         from_wkt<OG2>(\"POLYGON((2 1,2 4,4 4,4 0,1 0))\"),\r\n         from_wkt<ML>(\"MULTILINESTRING((2 1,2 2),(2 0,1 0),(2 1,2 1))\"),\r\n         from_wkt<ML>(\"MULTILINESTRING((2 2,2 1),(2 0,1 0),(2 1,2 1))\")\r\n         );\r\n}\r\n\r\n\r\nBOOST_AUTO_TEST_CASE( test_intersection_ring_multipolygon_linestring )\r\n{\r\n#ifdef BOOST_GEOMETRY_TEST_DEBUG\r\n    std::cout << std::endl << std::endl << std::endl;\r\n    std::cout << \"*** RING / MULTIPOLYGON / LINEAR INTERSECTION ***\"\r\n              << std::endl;\r\n    std::cout << std::endl;\r\n#endif\r\n    typedef open_ring_type OG1;\r\n    typedef open_multipolygon_type OG2;\r\n    typedef closed_ring_type CG1;\r\n    typedef closed_multipolygon_type CG2;\r\n    typedef multi_linestring_type ML;\r\n\r\n    typedef test_intersection_aal<OG1, OG2, CG1, CG2, ML> tester;\r\n\r\n    tester::apply\r\n        (\"r-mpg-01\",\r\n         from_wkt<OG1>(\"POLYGON((0 0,0 2,2 2,2 0))\"),\r\n         from_wkt<OG2>(\"MULTIPOLYGON(((2 1,2 4,4 4,4 0,1 0)))\"),\r\n         from_wkt<ML>(\"MULTILINESTRING((2 1,2 2),(2 0,1 0),(2 1,2 1))\"),\r\n         from_wkt<ML>(\"MULTILINESTRING((2 2,2 1),(2 0,1 0),(2 1,2 1))\")\r\n         );\r\n}\r\n\r\n\r\nBOOST_AUTO_TEST_CASE( test_intersection_polygon_polygon_linestring )\r\n{\r\n#ifdef BOOST_GEOMETRY_TEST_DEBUG\r\n    std::cout << std::endl << std::endl << std::endl;\r\n    std::cout << \"*** POLYGON / POLYGON / LINEAR INTERSECTION ***\" << std::endl;\r\n    std::cout << std::endl;\r\n#endif\r\n    typedef open_polygon_type OG;\r\n    typedef closed_polygon_type CG;\r\n    typedef multi_linestring_type ML;\r\n\r\n    typedef test_intersection_aal<OG, OG, CG, CG, ML> tester;\r\n\r\n    tester::apply\r\n        (\"pg-pg-01\",\r\n         from_wkt<OG>(\"POLYGON((0 0,0 2,2 2,2 0))\"),\r\n         from_wkt<OG>(\"POLYGON((2 1,2 4,4 4,4 0,1 0))\"),\r\n         from_wkt<ML>(\"MULTILINESTRING((2 1,2 2),(2 0,1 0),(2 1,2 1))\"),\r\n         from_wkt<ML>(\"MULTILINESTRING((2 2,2 1),(2 0,1 0),(2 1,2 1))\")\r\n         );\r\n\r\n    tester::apply\r\n        (\"pg-pg-02\",\r\n         from_wkt<OG>(\"POLYGON((0 0,0 10,10 10,10 0),(2 2,7 2,7 7,2 7))\"),\r\n         from_wkt<OG>(\"POLYGON((2 2,2 7,7 7,7 2))\"),\r\n         from_wkt<ML>(\"MULTILINESTRING((2 2,2 2),(2 2,2 7,7 7,7 2,2 2),(2 2,2 2))\"),\r\n         from_wkt<ML>(\"MULTILINESTRING((2 2,2 2),(2 2,7 2,7 7,2 7,2 2),(2 2,2 2))\")\r\n         );\r\n\r\n    tester::apply\r\n        (\"pg-pg-03\",\r\n         from_wkt<OG>(\"POLYGON((0 0,0 10,10 10,10 0),(2 2,7 2,7 7,2 7))\"),\r\n         from_wkt<OG>(\"POLYGON((2 3,2 6,6 6,6 3))\"),\r\n         from_wkt<ML>(\"MULTILINESTRING((2 3,2 6),(2 3,2 3))\")\r\n         );\r\n\r\n    tester::apply\r\n        (\"pg-pg-04\",\r\n         from_wkt<OG>(\"POLYGON((0 0,0 10,10 10,10 0),(2 2,7 2,7 7,2 7))\"),\r\n         from_wkt<OG>(\"POLYGON((2 3,2 7,6 7,6 3))\"),\r\n         from_wkt<ML>(\"MULTILINESTRING((2 3,2 7,6 7),(2 3,2 3))\")\r\n         );\r\n\r\n    tester::apply\r\n        (\"pg-pg-05\",\r\n         from_wkt<OG>(\"POLYGON((0 0,0 10,10 10,10 0),(2 2,7 2,7 7,2 7))\"),\r\n         from_wkt<OG>(\"POLYGON((2 3,2 7,7 7,7 3))\"),\r\n         from_wkt<ML>(\"MULTILINESTRING((2 3,2 7,7 7,7 3),(2 3,2 3))\")\r\n         );\r\n\r\n    tester::apply\r\n        (\"pg-pg-06\",\r\n         from_wkt<OG>(\"POLYGON((0 0,0 10,10 10,10 0),(2 2,7 2,7 7,2 7))\"),\r\n         from_wkt<OG>(\"POLYGON((2 3,2 7,7 7,7 3))\"),\r\n         from_wkt<ML>(\"MULTILINESTRING((2 3,2 7,7 7,7 3),(2 3,2 3))\")\r\n         );\r\n\r\n    tester::apply\r\n        (\"pg-pg-07\",\r\n         from_wkt<OG>(\"POLYGON((0 0,0 10,10 10,10 0),(2 2,7 2,7 7,2 7))\"),\r\n         from_wkt<OG>(\"POLYGON((2 5,5 7,7 5,5 2))\"),\r\n         from_wkt<ML>(\"MULTILINESTRING((2 5,2 5),(5 7,5 7),(7 5,7 5),(5 2,5 2))\")\r\n         );\r\n\r\n    tester::apply\r\n        (\"pg-pg-08\",\r\n         from_wkt<OG>(\"POLYGON((0 0,0 10,10 10,10 0),(2 2,7 2,7 7,2 7))\"),\r\n         from_wkt<OG>(\"POLYGON((2 5,4 7,6 7,7 5,5 2))\"),\r\n         from_wkt<ML>(\"MULTILINESTRING((2 5,2 5),(4 7,6 7),(7 5,7 5),(5 2,5 2))\")\r\n         );\r\n\r\n    tester::apply\r\n        (\"pg-pg-09\",\r\n         from_wkt<OG>(\"POLYGON(())\"),\r\n         from_wkt<OG>(\"POLYGON((2 1,2 4,4 4,4 0,1 0))\"),\r\n         from_wkt<ML>(\"MULTILINESTRING()\")\r\n         );\r\n\r\n    tester::apply\r\n        (\"pg-pg-10\",\r\n         from_wkt<OG>(\"POLYGON((2 1,2 4,4 4,4 0,1 0))\"),\r\n         from_wkt<OG>(\"POLYGON(())\"),\r\n         from_wkt<ML>(\"MULTILINESTRING()\")\r\n         );\r\n\r\n    tester::apply\r\n        (\"pg-pg-11\",\r\n         from_wkt<OG>(\"POLYGON(())\"),\r\n         from_wkt<OG>(\"POLYGON(())\"),\r\n         from_wkt<ML>(\"MULTILINESTRING()\")\r\n         );\r\n\r\n    tester::apply\r\n        (\"pg-pg-12\",\r\n         from_wkt<OG>(\"POLYGON((),())\"),\r\n         from_wkt<OG>(\"POLYGON((),(),())\"),\r\n         from_wkt<ML>(\"MULTILINESTRING()\")\r\n         );\r\n\r\n    tester::apply\r\n        (\"pg-pg-13\",\r\n         from_wkt<OG>(\"POLYGON((2 1,2 4,4 4,4 0,1 0),())\"),\r\n         from_wkt<OG>(\"POLYGON(())\"),\r\n         from_wkt<ML>(\"MULTILINESTRING()\")\r\n         );\r\n}\r\n\r\n\r\nBOOST_AUTO_TEST_CASE( test_intersection_polygon_multipolygon_linestring )\r\n{\r\n#ifdef BOOST_GEOMETRY_TEST_DEBUG\r\n    std::cout << std::endl << std::endl << std::endl;\r\n    std::cout << \"*** POLYGON / MULTIPOLYGON / LINEAR INTERSECTION ***\"\r\n              << std::endl;\r\n    std::cout << std::endl;\r\n#endif\r\n    typedef open_polygon_type OG1;\r\n    typedef open_multipolygon_type OG2;\r\n    typedef closed_polygon_type CG1;\r\n    typedef closed_multipolygon_type CG2;\r\n    typedef multi_linestring_type ML;\r\n\r\n    typedef test_intersection_aal<OG1, OG2, CG1, CG2, ML> tester;\r\n\r\n    tester::apply\r\n        (\"pg-mpg-01\",\r\n         from_wkt<OG1>(\"POLYGON((0 0,0 2,2 2,2 0))\"),\r\n         from_wkt<OG2>(\"MULTIPOLYGON(((2 1,2 4,4 4,4 0,1 0)))\"),\r\n         from_wkt<ML>(\"MULTILINESTRING((2 1,2 2),(2 0,1 0),(2 1,2 1))\"),\r\n         from_wkt<ML>(\"MULTILINESTRING((2 2,2 1),(2 0,1 0),(2 1,2 1))\")\r\n         );\r\n}\r\n\r\n\r\nBOOST_AUTO_TEST_CASE( test_intersection_multipolygon_multipolygon_linestring )\r\n{\r\n#ifdef BOOST_GEOMETRY_TEST_DEBUG\r\n    std::cout << std::endl << std::endl << std::endl;\r\n    std::cout << \"*** MULTIPOLYGON / MULTIPOLYGON / LINEAR INTERSECTION ***\"\r\n              << std::endl;\r\n    std::cout << std::endl;\r\n#endif\r\n    typedef open_multipolygon_type OG;\r\n    typedef closed_multipolygon_type CG;\r\n    typedef multi_linestring_type ML;\r\n\r\n    typedef test_intersection_aal<OG, OG, CG, CG, ML> tester;\r\n\r\n    tester::apply\r\n        (\"mpg-mpg-01\",\r\n         from_wkt<OG>(\"MULTIPOLYGON(((0 0,0 2,2 2,2 0)))\"),\r\n         from_wkt<OG>(\"MULTIPOLYGON(((2 1,2 4,4 4,4 0,1 0)))\"),\r\n         from_wkt<ML>(\"MULTILINESTRING((2 1,2 2),(2 0,1 0),(2 1,2 1))\"),\r\n         from_wkt<ML>(\"MULTILINESTRING((2 2,2 1),(2 0,1 0),(2 1,2 1))\")\r\n         );\r\n\r\n    tester::apply\r\n        (\"mpg-mpg-02\",\r\n         from_wkt<OG>(\"MULTIPOLYGON(((0 0,0 10,10 10,10 0),(2 2,8 2,8 8,2 8)))\"),\r\n         from_wkt<OG>(\"MULTIPOLYGON(((2 4,2 6,8 6,8 4)))\"),\r\n         from_wkt<ML>(\"MULTILINESTRING((2 4,2 4),(2 4,2 6),(8 6,8 4))\")\r\n         );\r\n\r\n    tester::apply\r\n        (\"mpg-mpg-03\",\r\n         from_wkt<OG>(\"MULTIPOLYGON()\"),\r\n         from_wkt<OG>(\"MULTIPOLYGON(((2 1,2 4,4 4,4 0,1 0)))\"),\r\n         from_wkt<ML>(\"MULTILINESTRING()\")\r\n         );\r\n\r\n    tester::apply\r\n        (\"mpg-mpg-04\",\r\n         from_wkt<OG>(\"MULTIPOLYGON(((2 1,2 4,4 4,4 0,1 0)))\"),\r\n         from_wkt<OG>(\"MULTIPOLYGON()\"),\r\n         from_wkt<ML>(\"MULTILINESTRING()\")\r\n         );\r\n\r\n    tester::apply\r\n        (\"mpg-mpg-05\",\r\n         from_wkt<OG>(\"MULTIPOLYGON()\"),\r\n         from_wkt<OG>(\"MULTIPOLYGON()\"),\r\n         from_wkt<ML>(\"MULTILINESTRING()\")\r\n         );\r\n\r\n    tester::apply\r\n        (\"mpg-mpg-06\",\r\n         from_wkt<OG>(\"MULTIPOLYGON((()),((),()))\"),\r\n         from_wkt<OG>(\"MULTIPOLYGON()\"),\r\n         from_wkt<ML>(\"MULTILINESTRING()\")\r\n         );\r\n\r\n    tester::apply\r\n        (\"mpg-mpg-07\",\r\n         from_wkt<OG>(\"MULTIPOLYGON(((2 1,2 4,4 4,4 0,1 0),(),()))\"),\r\n         from_wkt<OG>(\"MULTIPOLYGON()\"),\r\n         from_wkt<ML>(\"MULTILINESTRING()\")\r\n         );\r\n}\r\n", "meta": {"hexsha": "106045a7ee1e408ca9a134e69d2c21ca3e886151", "size": 13012, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/geometry/test/algorithms/set_operations/intersection/intersection_areal_areal_linear.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": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/geometry/test/algorithms/set_operations/intersection/intersection_areal_areal_linear.cpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-03-04T11:21:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-24T01:36:31.000Z", "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/geometry/test/algorithms/set_operations/intersection/intersection_areal_areal_linear.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 33.193877551, "max_line_length": 85, "alphanum_fraction": 0.5608668921, "num_tokens": 4272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.47674728436060126}}
{"text": "#include <boost/test/unit_test.hpp>\n\n#include \"../math/math.h\"\n\nUSING_NAMESPACE(sway)\n\nBOOST_AUTO_TEST_SUITE(TColorTestSuite)\n\n/*!\n\u00a0* \u0423\u0431\u0435\u0436\u0434\u0430\u0435\u043c\u0441\u044f, \u0447\u0442\u043e \u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u043e\u0440 \u043f\u043e \u0443\u043c\u043e\u043b\u0447\u0430\u043d\u0438\u044e \u043f\u0440\u0438\u0432\u043e\u0434\u0438\u0442 \u0432\u0441\u0435 \u043a\u043e\u043c\u043f\u043e\u043d\u0435\u043d\u0442\u044b \u043a \u043d\u0443\u043b\u044e.\n */\nBOOST_AUTO_TEST_CASE(TColorTestCase_DefaultConstructor) {\n\tmath::TColor<f32> color;\n\n\tBOOST_CHECK_EQUAL(color.getR(), 0.0f);\n\tBOOST_CHECK_EQUAL(color.getG(), 0.0f);\n\tBOOST_CHECK_EQUAL(color.getB(), 0.0f);\n\tBOOST_CHECK_EQUAL(color.getA(), 1.0f);\n}\n\n/*!\n\u00a0* \u0423\u0431\u0435\u0436\u0434\u0430\u0435\u043c\u0441\u044f, \u0447\u0442\u043e \u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u043e\u0440 \u0443\u0441\u0442\u0430\u043d\u0430\u0432\u043b\u0438\u0432\u0430\u0435\u0442 \u0432\u0441\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f \u043a\u043e\u043c\u043f\u043e\u043d\u0435\u043d\u0442\u043e\u0432 \u0432 \u0442\u0435, \n * \u043a\u043e\u0442\u043e\u0440\u044b\u0435 \u0431\u044b\u043b\u0438 \u0437\u0430\u0434\u0430\u043d\u044b.\n */\nBOOST_AUTO_TEST_CASE(TColorTestCase_ComponentConstructor) {\n\tconst f32 r = 0.1f, g = 0.2f, b = 0.3f, a = 1.0f;\n\t\n\tmath::TColor<f32> color = math::TColor<f32>(r, g, b, a);\n\n\tBOOST_CHECK_EQUAL(color.getR(), r);\n\tBOOST_CHECK_EQUAL(color.getG(), g);\n\tBOOST_CHECK_EQUAL(color.getB(), b);\n\tBOOST_CHECK_EQUAL(color.getA(), a);\n}\n\n/*!\n\u00a0* \u0423\u0431\u0435\u0436\u0434\u0430\u0435\u043c\u0441\u044f, \u0447\u0442\u043e \u043f\u0440\u0435\u043e\u0431\u0440\u0430\u0437\u043e\u0432\u0430\u043d\u0438\u0435 \u0432 TVector4<type> \u043f\u0440\u043e\u0445\u043e\u0434\u0438\u0442 \u043f\u0440\u0430\u0432\u0438\u043b\u044c\u043d\u043e.\n */\nBOOST_AUTO_TEST_CASE(TColorTestCase_ConvertToVector4) {\n\tconst f32 r = 0.1f, g = 0.2f, b = 0.3f, a = 1.0f;\n\n\tmath::TColor<f32> color = math::TColor<f32>(r, g, b, a);\n\tmath::TVector4<f32> vec4 = color.toVec4();\n\n\tBOOST_CHECK_EQUAL(vec4.getX(), r);\n\tBOOST_CHECK_EQUAL(vec4.getY(), g);\n\tBOOST_CHECK_EQUAL(vec4.getZ(), b);\n\tBOOST_CHECK_EQUAL(vec4.getW(), a);\n}\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "7fd86e222261106da32261c07a9251229ec21c2f", "size": 1355, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tests/color.tests.cpp", "max_stars_repo_name": "timcogames/Sway.Framework", "max_stars_repo_head_hexsha": "e59c3ddaaafd849fa683e8d99ec0cd297c3806dc", "max_stars_repo_licenses": ["MIT"], "max_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/color.tests.cpp", "max_issues_repo_name": "timcogames/Sway.Framework", "max_issues_repo_head_hexsha": "e59c3ddaaafd849fa683e8d99ec0cd297c3806dc", "max_issues_repo_licenses": ["MIT"], "max_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/color.tests.cpp", "max_forks_repo_name": "timcogames/Sway.Framework", "max_forks_repo_head_hexsha": "e59c3ddaaafd849fa683e8d99ec0cd297c3806dc", "max_forks_repo_licenses": ["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.568627451, "max_line_length": 76, "alphanum_fraction": 0.7188191882, "num_tokens": 451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.727975460709318, "lm_q2_score": 0.6548947155710233, "lm_q1q2_score": 0.47674728228391344}}
{"text": "#pragma once\n\n#include <iostream>\n#include <Eigen/Dense>\n#include <Eigen/Core>\n\nnamespace EigenHelpers{\n    template <typename Derived>\n        void dumpt(const Eigen::EigenBase<Derived>& mat) { std::cout<<mat<<std::endl; }\n\n    inline void dump(const Eigen::MatrixXd& mat) { std::cout<<mat<<std::endl; }\n    inline void dump(const Eigen::VectorXd& mat) { std::cout<<mat<<std::endl; }\n    inline void dump(const Eigen::ArrayXd& mat)  { std::cout<<mat<<std::endl; }\n    inline void dump(const Eigen::ArrayXXd& mat) { std::cout<<mat<<std::endl; }\n\n    /* Won't work till C++17*/\n    /* inline Eigen::IOFormat numpy_format(Eigen::StreamPrecision, 0, \", \", \";\\n\", \"[\", \"]\", \"[\", \"]\"); */\n\n    inline Eigen::IOFormat setNumpyFormat() {\n        return Eigen::IOFormat(Eigen::StreamPrecision, 0, \", \", \";\\n\", \"[\", \"]\", \"[\", \"]\");\n    }\n}\n", "meta": {"hexsha": "a60cd7ff1fe9f6552ffc5de2a2bef19baab178c5", "size": 831, "ext": "hh", "lang": "C++", "max_stars_repo_path": "extra/EigenHelpers.hh", "max_stars_repo_name": "gnafit/gna", "max_stars_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-10-14T01:06:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-02T16:33:06.000Z", "max_issues_repo_path": "extra/EigenHelpers.hh", "max_issues_repo_name": "gnafit/gna", "max_issues_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "extra/EigenHelpers.hh", "max_forks_repo_name": "gnafit/gna", "max_forks_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_forks_repo_licenses": ["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.1304347826, "max_line_length": 106, "alphanum_fraction": 0.6089049338, "num_tokens": 236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059775, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.47674727945728484}}
{"text": "/**\n * @file\n * @author lkoppel\n */\n\n#ifndef WAVE_GEOMETRY_MATRIXMAP_HPP\n#define WAVE_GEOMETRY_MATRIXMAP_HPP\n\n#include <Eigen/Core>\n#include <boost/container/flat_map.hpp>\n\nnamespace wave {\n\n/**\n * Stores a collection of equal-height matrices in one contiguous matrix.\n *\n * Stores matrices of size n*m_1, n*m_2, ... n*m_p,  where n and\n * all m_i are known at construct time.\n *\n * Indexing is done through a corresponding set of keys k_1, k_2, ... k_p.\n *\n * MatrixMap is constructed with a map of keys k_i to widths m_i, and its size cannot not\n * change later. The matrix is initially resized but not initialized (holds garbage).\n *\n * @tparam Key the key type used for indexing\n * @tparam Scalar the scalar type of the matrix (e.g. double)\n */\ntemplate <typename Key, typename Scalar>\nclass MatrixMap {\n    struct IndexPair {\n        int col_index;\n        int col_width;\n    };\n\n    using IndexMap = boost::container::flat_map<Key, IndexPair>;\n\n public:\n    /** Constructs and resizes the matrix. (Doesn't initialize. It holds garbage).\n     *\n     * Variant for dynamic-height MatrixMap.\n     *\n     * @param begin, end a pair of iterators to a sequence of type <Key, int> holding\n     * the {key, column width} for each matrix. For best performance it should be sorted;\n     * duplicates allowed.\n     * @param number of rows\n     */\n    template <typename MapIt>\n    MatrixMap(const MapIt &begin, const MapIt &end, Eigen::Index rows) {\n        int col = 0;\n        index_map.reserve(std::distance(begin, end));\n        for (auto it = begin; it != end; ++it) {\n            const auto &key = it->first;\n            const auto &width = it->second;\n            index_map.emplace_hint(index_map.end(), key, IndexPair{col, width});\n            col += width;\n        }\n        storage.resize(rows, col);\n    }\n\n    /** Returns a block representing the matrix for the given key */\n    auto operator[](const Key &key) {\n        const auto &v = this->index_map[key];\n        return this->storage.block(0, v.col_index, storage.rows(), v.col_width);\n    }\n\n    /** Returns a const block representing the matrix for the given key */\n    auto operator[](const Key &key) const {\n        const auto &v = this->index_map[key];\n        return this->storage.block(0, v.col_index, storage.rows(), v.col_width);\n    }\n\n    /** Returns a block representing the matrix for the given key\n     * @throws out_of_range if key is not present\n     */\n    auto at(const Key &key) {\n        const auto &v = this->index_map.at(key);\n        return this->storage.block(0, v.col_index, storage.rows(), v.col_width);\n    }\n\n    /** Returns a const block representing the matrix for the given key\n     * @throws out_of_range if key is not present\n     */\n    auto at(const Key &key) const {\n        const auto &v = this->index_map.at(key);\n        return this->storage.block(0, v.col_index, storage.rows(), v.col_width);\n    }\n\n    /** Returns 1 if the key is present, 0 otherwise */\n    auto count(const Key &key) const {\n        return this->index_map.count(key);\n    }\n\n    /** Set all blocks to zero */\n    void setZero() {\n        this->storage.setZero();\n    }\n\n\n private:\n    Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic> storage;\n    // Map of key -> (column index, column width) index\n    IndexMap index_map;\n};\n\n}  // namespace wave\n\n#endif  // WAVE_GEOMETRY_MATRIXMAP_HPP\n", "meta": {"hexsha": "2f79ddf8c33f44891a53922d9b73031a5e20a26d", "size": 3364, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/wave/geometry/src/util/math/MatrixMap.hpp", "max_stars_repo_name": "wavelab/wave_geometry", "max_stars_repo_head_hexsha": "aabcad44a490fc6393b35e63db9ad8908cf46dec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 112.0, "max_stars_repo_stars_event_min_datetime": "2018-05-07T00:57:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T12:14:07.000Z", "max_issues_repo_path": "include/wave/geometry/src/util/math/MatrixMap.hpp", "max_issues_repo_name": "wavelab/wave_geometry", "max_issues_repo_head_hexsha": "aabcad44a490fc6393b35e63db9ad8908cf46dec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2018-08-02T20:10:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T17:45:29.000Z", "max_forks_repo_path": "include/wave/geometry/src/util/math/MatrixMap.hpp", "max_forks_repo_name": "wavelab/wave_geometry", "max_forks_repo_head_hexsha": "aabcad44a490fc6393b35e63db9ad8908cf46dec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2018-05-27T01:08:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T13:46:31.000Z", "avg_line_length": 31.1481481481, "max_line_length": 89, "alphanum_fraction": 0.6409036861, "num_tokens": 822, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754371026368, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.4767472766306557}}
{"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 <Eigen/Core>\n\n#include <igl/embree/ambient_occlusion.h>\n\nnamespace ork::meshutil {\n\n//////////////////////////////////////////////////////////////////////////////\nEigen::VectorXd IglMesh::ambientOcclusion(int numsamples) const {\n  Eigen::VectorXd AO;\n  Eigen::MatrixXd N = computeVertexNormals();\n  igl::embree::ambient_occlusion(_verts, _faces, _verts, N, numsamples, AO);\n  AO = 1.0 - AO.array();\n  return AO;\n}\n\n} // namespace ork::meshutil\n\n#endif", "meta": {"hexsha": "efa73e36eae4933b91b5ccf5de6ca5aca1f59583", "size": 998, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ork.lev2/src/gfx/meshutil/submesh_igl_ambientocclusion.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_ambientocclusion.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_ambientocclusion.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": 29.3529411765, "max_line_length": 79, "alphanum_fraction": 0.5761523046, "num_tokens": 242, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677737461006, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4767075559085029}}
{"text": "// Std includes\n#include <iostream> // cout, endl\n#include <vector>\n#include <memory> // shared_ptr\n#include <map>\n// Thirdparties includes\n#include <Eigen/Dense>\n// Lib includes\n#include \"m0sh/uniform.h\"\n#include \"m0sh/structured_sub.h\"\n#include \"fl0p/stationary.h\"\n\nconst unsigned int DIM = 3;\n\nusing TypeScalar = double;\nusing TypeVector = Eigen::Matrix<TypeScalar, DIM, 1>;\nusing TypeMatrix = Eigen::Matrix<TypeScalar, DIM, DIM>;\ntemplate<typename... Args>\nusing TypeRef = Eigen::Ref<Args...>;\n\ntemplate<typename ...Args>\nusing TypeContainer = std::vector<Args...>;\nusing TypeMesh = m0sh::Uniform<TypeVector, TypeRef, TypeContainer>;\nusing TypeMeshSub = m0sh::StructuredSub<TypeVector, TypeRef, TypeContainer>;\nusing TypeFlow = fl0w::fl0p::Stationary<TypeVector, TypeMatrix, TypeRef, TypeMesh, TypeContainer, TypeMeshSub, TypeContainer>;\n\nvoid print(const TypeFlow& flow, const TypeVector& x, const TypeScalar& t) {\n    std::cout << std::endl;\n    std::cout << \"flow.getVelocity(\" << x.transpose() << \", \" << t << \") = \\n\" << flow.getVelocity(x, t).transpose() << std::endl;\n    std::cout << \"flow.getJacobian(\" << x.transpose() << \", \" << t << \") = \\n\" << flow.getJacobian(x, t) << std::endl;\n    std::cout << \"flow.getVorticity(\" << x.transpose() << \", \" << t << \") = \\n\" << flow.getVorticity(x, t).transpose() << std::endl;\n    std::cout << \"flow.getAcceleration(\" << x.transpose() << \", \" << t << \") = \\n\" << flow.getAcceleration(x, t).transpose() << std::endl;\n    std::cout << std::endl;\n}\n\ndouble f(const double x, const double y) {\n    return x;\n}\n\nint main () { \n    // parameters\n    std::size_t n = 8;\n    // mesh\n    std::vector<std::size_t> dimensions({n, n, n});\n    std::vector<double> lengths({1.0, 1.0, 1.0});\n    TypeVector origin({-0.5, -0.5, -0.5});\n    // data\n    std::vector<std::vector<float>> velocity(3, std::vector<float>(std::pow(n, DIM)));\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                velocity[0][i + n*j + n*n*k] = (i + j + k)/3.0f;\n                velocity[1][i + n*j + n*n*k] = (i + j + k)/3.0f;\n                velocity[2][i + n*j + n*n*k] = (i + j + k)/3.0f;\n            }\n        }\n    }\n    // flow\n    TypeFlow flow(std::make_shared<TypeMesh>(dimensions, lengths, origin, TypeContainer<bool>(DIM, true)), velocity, 4);\n    // print\n    print(flow, TypeVector({0.0, 0.0, 0.0}), 0.0);\n}\n", "meta": {"hexsha": "e8f140c2a02a1bbc023775b24f6e2ec613b5e7ee", "size": 2435, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/stationary/main.cpp", "max_stars_repo_name": "C0PEP0D/fl0p", "max_stars_repo_head_hexsha": "d65b1babfaec8b996474e42362f6819580ad3538", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/stationary/main.cpp", "max_issues_repo_name": "C0PEP0D/fl0p", "max_issues_repo_head_hexsha": "d65b1babfaec8b996474e42362f6819580ad3538", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/stationary/main.cpp", "max_forks_repo_name": "C0PEP0D/fl0p", "max_forks_repo_head_hexsha": "d65b1babfaec8b996474e42362f6819580ad3538", "max_forks_repo_licenses": ["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.6507936508, "max_line_length": 138, "alphanum_fraction": 0.5934291581, "num_tokens": 754, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619634, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.4767075515886617}}
{"text": "\n#include \"vr/util/ops_int.h\"\n\n#include \"vr/data/NA.h\"\n#include \"vr/util/logging.h\"\n\n#include \"vr/test/utility.h\"\n\n#include <boost/math/special_functions/pow.hpp>\n\n//----------------------------------------------------------------------------\nnamespace vr\n{\nnamespace util\n{\n//............................................................................\n/*\n * note: this nlz() implementation has a defined behavior for zero input\n */\nTEST (ops_int_test, vr_nlz)\n{\n#define vr_nlz_TEST(r, type, test) \\\n    { \\\n        const type x_input = BOOST_PP_TUPLE_ELEM (2, 0, test); \\\n        const int32_t n_expected = BOOST_PP_TUPLE_ELEM (2, 1, test); \\\n        auto x = x_input; \\\n        const int32_t n = vr_nlz_##type (x); \\\n        EXPECT_EQ (n_expected, n) << \"x: \" << x; \\\n        ASSERT_EQ (x_input, x); /* catch ABI bugs */ \\\n    } \\\n    /* */\n\n    // 32 bits:\n\n#define vr_nlz_TESTCASES (0, 32)(1, 31)(3, 30)(4, 29)(-1, 0)\n\n    BOOST_PP_SEQ_FOR_EACH (vr_nlz_TEST, int32_t, VR_DOUBLE_PARENTHESIZE_2 (vr_nlz_TESTCASES))\n\n#undef vr_nlz_TESTCASES\n#define vr_nlz_TESTCASES (0, 64)(1, 63)(3, 62)(4, 61)(-1, 0)\n\n    // 64 bits:\n\n    BOOST_PP_SEQ_FOR_EACH (vr_nlz_TEST, int64_t, VR_DOUBLE_PARENTHESIZE_2 (vr_nlz_TESTCASES))\n\n#undef vr_nlz_TEST\n}\n//............................................................................\n\nusing supported_int_types   = gt::Types<int32_t, int64_t>;\n\ntemplate<typename T> struct ops_int_test: public gt::Test { };\nTYPED_TEST_CASE (ops_int_test, supported_int_types);\n\n//............................................................................\n//............................................................................\nnamespace\n{\n\ntemplate<typename T, int32_t ZERO_RETURN>\nvoid ilog10_floor_test ()\n{\n    using value_type    = T;\n\n    using zero_policy   = arg_policy<zero_arg_policy::return_special, ZERO_RETURN>;\n\n    using ops_fast      = ops_int<zero_policy, false>;\n    using ops_checked   = ops_int<zero_policy, true>;\n\n    // input validation:\n\n    EXPECT_NO_THROW (ops_fast::ilog10_floor (-2));\n    EXPECT_THROW (ops_checked::ilog10_floor (-2), invalid_input);\n\n    // test zero input:\n    {\n        value_type x = 0; // note: special value (return controlled by policy)\n        const int32_t l = ops_checked::ilog10_floor (x);\n        const int32_t l_expected = zero_policy::zero_return;\n        ASSERT_EQ (l, l_expected) << \"failed for zero input \";\n    }\n\n    {\n        value_type x = 9;\n        const int32_t l = ops_checked::ilog10_floor (x);\n        EXPECT_EQ (l, 0) << \"x: \" << x;\n    }\n    {\n        value_type x = 10;\n        const int32_t l = ops_checked::ilog10_floor (x);\n        EXPECT_EQ (l, 1) << \"x: \" << x;\n    }\n    {\n        value_type x = 11;\n        const int32_t l = ops_checked::ilog10_floor (x);\n        EXPECT_EQ (l, 1) << \"x: \" << x;\n    }\n\n    // test a large input:\n\n    constexpr int32_t max_pow10     = std::numeric_limits<value_type>::digits10;\n    const value_type x_big = boost::math::pow<max_pow10> (static_cast<value_type> (10));\n\n    LOG_trace1 << \"max pow10: \" << max_pow10 << \", x_big: \" << x_big;\n\n    {\n        value_type x = x_big - 1;\n        const int32_t l = ops_checked::ilog10_floor (x);\n        EXPECT_EQ (l, max_pow10 - 1) << \"x: \" << x;\n    }\n    {\n        value_type x = x_big;\n        const int32_t l = ops_checked::ilog10_floor (x);\n        EXPECT_EQ (l, max_pow10) << \"x: \" << x;\n    }\n    {\n        value_type x = x_big + 1;\n        const int32_t l = ops_checked::ilog10_floor (x);\n        EXPECT_EQ (l, max_pow10) << \"x: \" << x;\n    }\n\n    // test max input:\n\n    const value_type x_max = std::numeric_limits<value_type>::max ();\n\n    LOG_trace1 << \"x_max: \" << x_max;\n\n    {\n        value_type x = x_max;\n        const int32_t l = ops_checked::ilog10_floor (x);\n        EXPECT_EQ (l, max_pow10) << \"x: \" << x;\n    }\n}\n\n} // end of anonymous\n//............................................................................\n//............................................................................\n// TODO\n// - log2 tests\n\nTYPED_TEST (ops_int_test, ilog10_floor_zero_0)\n{\n    using value_type    = TypeParam; // test parameter\n\n    ilog10_floor_test<value_type, 0> ();\n}\n\nTYPED_TEST (ops_int_test, ilog10_floor_zero_m1)\n{\n    using value_type    = TypeParam; // test parameter\n\n    ilog10_floor_test<value_type, -1> ();\n}\n//............................................................................\n\nTYPED_TEST (ops_int_test, popcount)\n{\n    using value_type    = TypeParam; // test parameter\n\n    value_type const zero       = 0;\n    EXPECT_EQ (popcount (zero), 0);\n\n    value_type const all_ones   = -1;\n    EXPECT_EQ (popcount (all_ones), signed_cast (8 * sizeof (value_type)));\n}\n//............................................................................\n\nTYPED_TEST (ops_int_test, ls_zero_index)\n{\n    using value_type    = TypeParam; // test parameter\n\n    for (int32_t i = 0; i < signed_cast (sizeof (value_type)); ++ i)\n    {\n        value_type const x      = -1 & ~(static_cast<value_type> (0xFF) << (i * 8));\n        int32_t const lszix = ls_zero_index (x);\n\n        EXPECT_EQ (lszix, i);\n    }\n\n    // some edge cases:\n    {\n        // no zeros:\n        {\n            value_type const x  = -1;\n            int32_t const lszix = ls_zero_index (x);\n\n            EXPECT_EQ (lszix, signed_cast (sizeof (value_type)));\n        }\n\n        // several zeros:\n        {\n            value_type x        = 0; // all zeros\n            int32_t lszix = ls_zero_index (x);\n\n            EXPECT_EQ (lszix, 0);\n\n            x                   = 0xFF00FF; // all but 2 zeros\n            lszix = ls_zero_index (x);\n            EXPECT_EQ (lszix, 1);\n        }\n    }\n}\n//............................................................................\n\nTYPED_TEST (ops_int_test, net_int)\n{\n    using value_type    = TypeParam; // test parameter\n\n    const value_type inputs [] { std::numeric_limits<value_type>::min (), -1000, -1, 0, 1, 1000, std::numeric_limits<value_type>::max () };\n\n    {\n        using nint_type     = net_int<value_type, false>;\n\n        nint_type ni;\n\n        for (value_type i : inputs)\n        {\n            ni = i;\n            value_type const ii = ni;\n\n            ASSERT_EQ (ii, i) << \"failed for input \" << i;\n\n            // copy construction:\n            {\n                nint_type const ni_cc { ni };\n                value_type const ii_cc = ni_cc;\n\n                ASSERT_EQ (ii_cc, ii);\n            }\n            // copy assignment:\n            {\n                nint_type ni_ca; ni_ca = ni;\n                value_type const ii_ca = ni_ca;\n\n                ASSERT_EQ (ii_ca, ii);\n            }\n        }\n    }\n    {\n        using nint_type     = net_int<value_type, true>;\n\n        nint_type ni;\n\n        for (value_type i : inputs)\n        {\n            ni = i;\n            value_type const ii = ni;\n\n            ASSERT_EQ (ii, i) << \"failed for input \" << i;\n\n            // copy construction:\n            {\n                nint_type const ni_cc { ni };\n                value_type const ii_cc = ni_cc;\n\n                ASSERT_EQ (ii_cc, ii);\n            }\n            // copy assignment:\n            {\n                nint_type ni_ca; ni_ca = ni;\n                value_type const ii_ca = ni_ca;\n\n                ASSERT_EQ (ii_ca, ii);\n            }\n        }\n    }\n}\n//............................................................................\n\nTEST (ops_int_test, mux)\n{\n    EXPECT_TRUE (0          == mux (0));\n    EXPECT_TRUE (  0x0102FF == mux (0, 1, 2, 255));\n    EXPECT_TRUE (0x01020304 == mux (1, 2, 3, 4));\n}\n//............................................................................\n\nTEST (bit_cast, fp)\n{\n    {\n        auto const na = data::NA<float> ();\n        LOG_trace1 << \"bit image of float NA: \" << hex_string_cast (bit_cast (na));\n\n        auto const na_image = bit_cast (na);\n        EXPECT_EQ (signed_cast (na_image & 0xFFFF), VR_R_NA_MARKER);\n    }\n    {\n        auto const na = data::NA<double> ();\n        LOG_trace1 << \"bit image of double NA: \" << hex_string_cast (bit_cast (na));\n\n        auto const na_image = bit_cast (na);\n        EXPECT_EQ (signed_cast (na_image & 0xFFFF), VR_R_NA_MARKER);\n    }\n}\n\n} // end of 'util'\n} // end of namespace\n//----------------------------------------------------------------------------\n", "meta": {"hexsha": "141435c6a1f9003edefffe281c767f490ddbdced", "size": 8285, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "vr/vr_common/src/vr/util/ops_int_test.cpp", "max_stars_repo_name": "vladium/vrt", "max_stars_repo_head_hexsha": "57394a630c306b7529dbe4574036ea71420d00cf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-09-09T22:08:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-17T13:43:31.000Z", "max_issues_repo_path": "vr/vr_common/src/vr/util/ops_int_test.cpp", "max_issues_repo_name": "vladium/vrt", "max_issues_repo_head_hexsha": "57394a630c306b7529dbe4574036ea71420d00cf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vr/vr_common/src/vr/util/ops_int_test.cpp", "max_forks_repo_name": "vladium/vrt", "max_forks_repo_head_hexsha": "57394a630c306b7529dbe4574036ea71420d00cf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-09-09T15:46:20.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-09T15:46:20.000Z", "avg_line_length": 27.7090301003, "max_line_length": 139, "alphanum_fraction": 0.4924562462, "num_tokens": 2124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723317123102956, "lm_q2_score": 0.7090191337850933, "lm_q1q2_score": 0.4766960482784944}}
{"text": "/// \\file   test_parameter.cpp\n/// \\brief\n/// \\authors    maarten\n/// \\date       2021-02-08\n/// \\copyright  Copyright 2017-2021 The Institute for New Economic Thinking,\n///             Oxford Martin School, University of Oxford\n///             Licensed under the Apache License, Version 2.0 (the \"License\");\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 \"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///             You may obtain instructions to fulfill the attribution\n///             requirements in CITATION.cff\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE model_parallel\n\n#include <set>\n\n#include <boost/test/included/unit_test.hpp>\n\n\n#include <esl/simulation/parameter/sampler.hpp>\nusing namespace esl::simulation::parameter;\nusing namespace esl::simulation::parameter::sampler;\n\n\n\n\nBOOST_AUTO_TEST_SUITE(ESL)\n\n    ///\n    /// \\brief  This tests whether the grid sampler can generate points with\n    ///         different densities in each dimension, whether it generates the\n    ///         expected number of points and whether they are all unique.\n    ///\n    BOOST_AUTO_TEST_CASE(parameter_test_sampler_grid)\n    {\n        auto param0 = std::make_shared<interval<double>>(1.0, 5.0);\n        auto param1 = std::make_shared<interval<double>>(-3, 3.0);\n        auto param2= std::make_shared<interval<double>>(100, 200);\n\n        std::map<std::shared_ptr<interval<double>>, unsigned int> p;\n        p.emplace(param0, 2);\n        p.emplace(param1, 5);\n        p.emplace(param2, 3);\n        auto samples_ = grid(p);\n\n        BOOST_CHECK_EQUAL(samples_.size(), 2*5*3);\n\n        std::set<std::tuple<double, double, double>> unique_;\n        for(const auto &e: samples_){\n\n            unique_.insert( std::make_tuple( e.find(param0)->second\n                , e.find(param1)->second\n                , e.find(param2)->second\n            ) );\n        }\n        BOOST_CHECK_EQUAL(unique_.size(), 2*5*3);\n    }\n\n\n    BOOST_AUTO_TEST_CASE(parameter_test_sampler_hypercube)\n    {\n        auto param0 = std::make_shared<interval<double>>(1.0, 5.0);\n        auto param1 = std::make_shared<interval<double>>(-3, 3.0);\n        auto param2= std::make_shared<interval<double>>(100, 200);\n\n        std::vector<std::shared_ptr<interval<double>>> p;\n        p.emplace_back(param0);\n        p.emplace_back(param1);\n        p.emplace_back(param2);\n        auto samples_ = latin_hypercube(p, 10);\n\n        BOOST_CHECK_EQUAL(samples_.size(), 10 );\n\n        std::set<std::tuple<double, double, double>> unique_;\n        for(const auto &e: samples_){\n\n            unique_.insert(std::make_tuple\n                               ( e.find(param0)->second\n                                   , e.find(param1)->second\n                                   , e.find(param2)->second\n                               ));\n        }\n        BOOST_CHECK_EQUAL(unique_.size(), 10);\n    }\n\n    BOOST_AUTO_TEST_CASE(parameter_test_sampler_orthogonal)\n    {\n        int dimensions = 8;\n        int samples = 64;\n        std::seed_seq seed = {1,2,3,4,5};\n        int duplication  = 5;\n        auto res = improved_hypercube_sampling (dimensions, samples, seed, duplication);\n        for(int d = 0; d < dimensions; ++d) {\n            std::set<unsigned int> ps;\n            //std::cout << res[d][0];\n            ps.insert(res[d][0]);\n            for(int s = 1; s < samples; ++s) {\n            //    std::cout << \",\" << res[d][s];\n                ps.insert(res[d][s]);\n            }\n            BOOST_CHECK_EQUAL(ps.size(), samples);\n            //std::cout << std::endl;\n        }\n    }\n\nBOOST_AUTO_TEST_SUITE_END()  // ESL\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": "8e57cc1c93176a5cff67ca8a5a5dca9698f8b056", "size": 4110, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_parameter.cpp", "max_stars_repo_name": "vishalbelsare/ESL", "max_stars_repo_head_hexsha": "cea6feda1e588d5f441742dbb1e4c5479b47d357", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 37.0, "max_stars_repo_stars_event_min_datetime": "2019-10-13T12:23:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T10:40:29.000Z", "max_issues_repo_path": "test/test_parameter.cpp", "max_issues_repo_name": "vishalbelsare/ESL", "max_issues_repo_head_hexsha": "cea6feda1e588d5f441742dbb1e4c5479b47d357", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-03-20T04:44:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-12T06:18:33.000Z", "max_forks_repo_path": "test/test_parameter.cpp", "max_forks_repo_name": "vishalbelsare/ESL", "max_forks_repo_head_hexsha": "cea6feda1e588d5f441742dbb1e4c5479b47d357", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-11-06T15:59:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-09T17:28:24.000Z", "avg_line_length": 28.9436619718, "max_line_length": 88, "alphanum_fraction": 0.5800486618, "num_tokens": 942, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.47669604362342577}}
{"text": "#include <k4a/k4a.hpp>\n\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <array>\n\n#include <Eigen/Dense>\n\n#include <opencv2/core/core.hpp>\n#include <opencv2/core/eigen.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/calib3d/calib3d.hpp>\n\n#include <aruco/aruco.h>\n\n#include \"Pixel.h\"\n#include \"DepthPixelColorizer.h\"\n#include \"StaticImageProperties.h\"\n\nusing namespace std;\nusing namespace cv;\nusing namespace sen;\nusing namespace Eigen;\n\nk4a::calibration calibration;\nMat camera_matrix_color;\nMat dist_coeffs_color;\n\naruco::Dictionary dic;\naruco::CameraParameters CamParam;\naruco::MarkerDetector MDetector;\nstd::map<int, aruco::MarkerPoseTracker> MTracker_master;\nstd::map<int, aruco::MarkerPoseTracker> MTracker_sub;\nfloat MarkerSize = 0.1f;\n\nconst static Eigen::IOFormat CSVFormat(Eigen::StreamPrecision, Eigen::DontAlignCols, \", \", \"\\n\");\n\n\ntemplate <typename DataType>\nvoid writeToCSVfile(std::string name, Eigen::Array<DataType, -1, -1> matrix)\n{\n\tstd::ofstream file(name.c_str());\n\tfile << matrix.format(CSVFormat);\n}\n\nvoid eigenTransform2cvRvecTvec(const Transform<double, 3, Affine> frame, cv::Vec3d &rvec, cv::Vec3d &tvec)\n{\n\tTranslation<double, 3> t(frame.translation());\n\tQuaternion<double> q(frame.linear());\n\ttvec = cv::Vec3d(t.x(), t.y(), t.z());\n\tcv::Mat rotM;\n\teigen2cv(q.toRotationMatrix(), rotM);\n\tcv::Rodrigues(rotM, rvec);\n}\n\nvoid drawAxis(InputOutputArray _image, InputArray _cameraMatrix, InputArray _distCoeffs,\n\tInputArray _rvec, InputArray _tvec, float length)\n{\n\tCV_Assert(_image.getMat().total() != 0 &&\n\t\t(_image.getMat().channels() == 1 || _image.getMat().channels() == 3));\n\tCV_Assert(length > 0);\n\n\t// project axis points\n\tvector< Point3f > axisPoints;\n\taxisPoints.push_back(Point3f(0, 0, 0));\n\taxisPoints.push_back(Point3f(length, 0, 0));\n\taxisPoints.push_back(Point3f(0, length, 0));\n\taxisPoints.push_back(Point3f(0, 0, length));\n\tvector< Point2f > imagePoints;\n\tprojectPoints(axisPoints, _rvec, _tvec, _cameraMatrix, _distCoeffs, imagePoints);\n\n\t// draw axis lines\n\tline(_image, imagePoints[0], imagePoints[1], Scalar(0, 0, 255), 3);\n\tline(_image, imagePoints[0], imagePoints[2], Scalar(0, 255, 0), 3);\n\tline(_image, imagePoints[0], imagePoints[3], Scalar(255, 0, 0), 3);\n}\n\nint main(int argc, char **argv)\n{\n\tconst uint32_t deviceCount = k4a::device::get_installed_count();\n\tif (deviceCount == 0)\n\t{\n\t\tcout << \"no azure kinect devices detected!\" << endl;\n\t}\n\n\tk4a_device_configuration_t config = K4A_DEVICE_CONFIG_INIT_DISABLE_ALL;\n\tconfig.camera_fps = K4A_FRAMES_PER_SECOND_30;\n\tconfig.depth_mode = K4A_DEPTH_MODE_NFOV_UNBINNED;\n\tconfig.color_format = K4A_IMAGE_FORMAT_COLOR_BGRA32;\n\tconfig.color_resolution = K4A_COLOR_RESOLUTION_720P;\n\tconfig.synchronized_images_only = true;\n\n\tcout << \"Started opening K4A device...\" << endl;\n\tk4a::device dev_sub = k4a::device::open(1);\n\tdev_sub.start_cameras(&config);\n\tk4a::device dev_master = k4a::device::open(K4A_DEVICE_DEFAULT);\n\tdev_master.start_cameras(&config);\n\tcout << \"Finished opening K4A device.\" << endl;\n\n\tstd::pair<int, int> color_dimensions = GetColorDimensions(config.color_resolution);\n\tint texture_width = color_dimensions.first;\n\tint texture_height = color_dimensions.second;\n\n\tcalibration = dev_master.get_calibration(config.depth_mode, config.color_resolution);\n\tk4a_calibration_intrinsic_parameters_t *intrinsics_color = &calibration.color_camera_calibration.intrinsics.parameters;\n\tvector<float> _camera_matrix = {\n\t   intrinsics_color->param.fx, 0.f, intrinsics_color->param.cx,\n\t   0.f, intrinsics_color->param.fy, intrinsics_color->param.cy,\n\t   0.f, 0.f, 1.f };\n\tcamera_matrix_color = Mat(3, 3, CV_32F, &_camera_matrix[0]);\n\tvector<float> _dist_coeffs = { intrinsics_color->param.k1, intrinsics_color->param.k2, intrinsics_color->param.p1,\n\t\t\t\t\t\t\t\t   intrinsics_color->param.p2, intrinsics_color->param.k3, intrinsics_color->param.k4,\n\t\t\t\t\t\t\t\t   intrinsics_color->param.k5, intrinsics_color->param.k6 };\n\tdist_coeffs_color = Mat::zeros(5, 1, CV_32F);\n\tdic = aruco::Dictionary::load(\"ARUCO_MIP_36h12\");\n\tCamParam.setParams(camera_matrix_color, dist_coeffs_color, cv::Size(texture_width, texture_height));\n\tMDetector.setDictionary(\"ARUCO_MIP_36h12\", 0.05f);\n\tMDetector.setDetectionMode(aruco::DM_NORMAL);\n\n\tk4a::capture capture_master;\n\tk4a::capture capture_sub;\n\n\tk4a::image colorImage_master;\n\tuint8_t *colorTextureBuffer_master;\n\tcv::Mat colorFrame_master;\n\n\tk4a::image colorImage_sub;\n\tuint8_t *colorTextureBuffer_sub;\n\tcv::Mat colorFrame_sub;\n\n\tEigen::Affine3d frame_master_marker;\n\tEigen::Affine3d frame_sub_marker;\n\tEigen::Affine3d frame_master_sub;\n\n\tbool poseEstimationOK_master = false;\n\tbool poseEstimationOK_sub = false;\n\n\twhile (1)\n\t{\n\t\tif (dev_master.get_capture(&capture_master, std::chrono::milliseconds(0)) && dev_sub.get_capture(&capture_sub, std::chrono::milliseconds(0)))\n\t\t{\n\t\t\t//master\n\t\t\t{\n\t\t\t\tcolorImage_master = capture_master.get_color_image();\n\t\t\t\tcolorTextureBuffer_master = colorImage_master.get_buffer();\n\t\t\t\tcolorFrame_master = cv::Mat(colorImage_master.get_height_pixels(), colorImage_master.get_width_pixels(), CV_8UC4, colorTextureBuffer_master);\n\t\t\t\tcvtColor(colorFrame_master, colorFrame_master, COLOR_BGRA2BGR);\n\n\t\t\t\t{\n\t\t\t\t\tvector<aruco::Marker> Markers = MDetector.detect(colorFrame_master);\n\t\t\t\t\tfor (auto &marker : Markers)\n\t\t\t\t\t{\n\t\t\t\t\t\tMTracker_master[marker.id].estimatePose(marker, CamParam, MarkerSize);\n\t\t\t\t\t}\n\t\t\t\t\tif (CamParam.isValid() && MarkerSize != -1)\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (unsigned int i = 0; i < Markers.size(); ++i)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (Markers[i].isPoseValid())\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcv::Mat transformationMatrix_master = Markers[i].getTransformMatrix();\n\t\t\t\t\t\t\t\tcv2eigen(transformationMatrix_master, frame_master_marker.matrix());\n\t\t\t\t\t\t\t\tposeEstimationOK_master = true;\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\tposeEstimationOK_master = false;\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\n\t\t\t//sub\n\t\t\t{\n\n\t\t\t\tcolorImage_sub = capture_sub.get_color_image();\n\t\t\t\tcolorTextureBuffer_sub = colorImage_sub.get_buffer();\n\t\t\t\tcolorFrame_sub = cv::Mat(colorImage_sub.get_height_pixels(), colorImage_sub.get_width_pixels(), CV_8UC4, colorTextureBuffer_sub);\n\t\t\t\tcvtColor(colorFrame_sub, colorFrame_sub, COLOR_BGRA2BGR);\n\n\t\t\t\t{\n\t\t\t\t\tvector<aruco::Marker> Markers = MDetector.detect(colorFrame_sub);\n\t\t\t\t\tfor (auto &marker : Markers)\n\t\t\t\t\t{\n\t\t\t\t\t\tMTracker_sub[marker.id].estimatePose(marker, CamParam, MarkerSize);\n\t\t\t\t\t}\n\t\t\t\t\tif (CamParam.isValid() && MarkerSize != -1)\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (unsigned int i = 0; i < Markers.size(); ++i)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (Markers[i].isPoseValid())\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcv::Mat transformationMatrix_sub = Markers[i].getTransformMatrix();\n\t\t\t\t\t\t\t\tcv2eigen(transformationMatrix_sub, frame_sub_marker.matrix());\n\t\t\t\t\t\t\t\tposeEstimationOK_sub = true;\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\tposeEstimationOK_sub = false;\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\n\t\t\tif (poseEstimationOK_master && poseEstimationOK_sub)\n\t\t\t{\n\t\t\t\tEigen::Affine3d frame_master_sub = frame_master_marker * frame_sub_marker.inverse();\n\n\t\t\t\tcv::Vec3d rvec, tvec;\n\t\t\t\teigenTransform2cvRvecTvec(frame_sub_marker, rvec, tvec);\n\t\t\t\tdrawAxis(colorFrame_sub, camera_matrix_color, dist_coeffs_color, rvec, tvec, 0.5f);\n\n\t\t\t\tEigen::Affine3d frame_sub_master = frame_sub_marker * frame_master_marker.inverse();\n\t\t\t\teigenTransform2cvRvecTvec(frame_sub_master, rvec, tvec);\n\t\t\t\tEigen::Matrix4d frame_matrix = frame_sub_master.matrix();\n\t\t\t\tstd::cout << \"frame sub master\" << std::endl;\n\t\t\t\twriteToCSVfile<double>(\"frame_sub_master.csv\", frame_matrix);\n\t\t\t\tstd::cout << \"save matrix into csv file OK.\\n\";\n\n\t\t\t\tstd::cout << \"frame sub marker\" << std::endl;\n\t\t\t\tframe_matrix = frame_sub_marker.matrix();\n\t\t\t\twriteToCSVfile<double>(\"frame_sub_marker.csv\", frame_matrix);\n\t\t\t\tstd::cout << \"save matrix into csv file OK.\\n\";\n\t\t\t\tdrawAxis(colorFrame_sub, camera_matrix_color, dist_coeffs_color, rvec, tvec, 0.5f);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tstd::cout << endl;\n\t\t\t}\n\n\t\t\timshow(\"color sub\", colorFrame_sub);\n\t\t}\n\t\tif (waitKey(30) == 27 || waitKey(30) == 'q')\n\t\t{\n\t\t\tdev_master.close();\n\t\t\tdev_sub.close();\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn 0;\n}", "meta": {"hexsha": "4f99c6c6debd75e8522dfce80aa17243f9510bd2", "size": 8055, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Aruco_TwoKinects_Calibration_Extrinsics/Source_TwoKinects_Calibration.cpp", "max_stars_repo_name": "xiongmao4hao/KinectAzureDKProgramming", "max_stars_repo_head_hexsha": "6936ec5e03c7c995d0ca3297bd0e8407a7a261b7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 122.0, "max_stars_repo_stars_event_min_datetime": "2019-08-29T05:28:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T11:49:56.000Z", "max_issues_repo_path": "Aruco_TwoKinects_Calibration_Extrinsics/Source_TwoKinects_Calibration.cpp", "max_issues_repo_name": "xiongmao4hao/KinectAzureDKProgramming", "max_issues_repo_head_hexsha": "6936ec5e03c7c995d0ca3297bd0e8407a7a261b7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2020-04-15T10:17:22.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-06T07:51:08.000Z", "max_forks_repo_path": "Aruco_TwoKinects_Calibration_Extrinsics/Source_TwoKinects_Calibration.cpp", "max_forks_repo_name": "xiongmao4hao/KinectAzureDKProgramming", "max_forks_repo_head_hexsha": "6936ec5e03c7c995d0ca3297bd0e8407a7a261b7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 31.0, "max_forks_repo_forks_event_min_datetime": "2019-10-11T10:06:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-12T11:05:03.000Z", "avg_line_length": 33.012295082, "max_line_length": 145, "alphanum_fraction": 0.7176908752, "num_tokens": 2259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893353516963, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.47660654039814115}}
{"text": "/**\n * @copyright   Copyright (c) 2021, Swift Engineering Inc.\n * @license     Licensed under the MIT license. See LICENSE for details.\n */\n#include \"Motor_current_consumption_model.hpp\"\n#include <cmath>\n#include <cstdio>\n#include <limits>\n#include <cstdint>\n#include <boost/math/tools/rational.hpp>\n\nMotor_current_consumption_model::Motor_current_consumption_model(const std::vector<double>\n        &current_consumption_model_coeff) {\n    m_current_consumption_model_coeff = current_consumption_model_coeff;\n    m_model_type = RPM;\n    m_c = 0;\n    m_r = 1;\n    m_last_current = 0;\n}\n\nMotor_current_consumption_model::Motor_current_consumption_model(const std::vector<double>\n        &current_consumption_model_coeff, const double C, const double R) {\n    if (R <= 0) {\n        throw (\"R must be greater than 0\"); // NOLINT\n    }\n\n    if (C < 0) {\n        throw (\"C must be greater than or equal to 0\");  // NOLINT\n    }\n\n    m_current_consumption_model_coeff = current_consumption_model_coeff;\n    m_model_type = TORQUE;\n    m_c = C;\n    m_r = R;\n    m_last_current = 0;\n    // TODO(Mike Lyons) throw and exception if ?? is zero\n}\n\ndouble  Motor_current_consumption_model::get_current(const double value) {\n    return boost::math::tools::evaluate_polynomial(m_current_consumption_model_coeff.data(), value,\n            m_current_consumption_model_coeff.size());\n}\n\ndouble  Motor_current_consumption_model::get_current(const double value, const double timestep) {\n    double current = get_current(value);\n    current = current - (m_c / m_r) * (current - m_last_current) /\n              (timestep);  // for RPM the dynamic response component equals 0\n    m_last_current = current;\n    return current;\n}\n", "meta": {"hexsha": "0e1d421e003f3a3208abd9ac9d667a7e24423804", "size": 1703, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Motor_current_consumption_model.cpp", "max_stars_repo_name": "SwiftEngineering/avionics_sim", "max_stars_repo_head_hexsha": "8fa3ef497137dd54966ff9de43cbcf2bfbf82d96", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Motor_current_consumption_model.cpp", "max_issues_repo_name": "SwiftEngineering/avionics_sim", "max_issues_repo_head_hexsha": "8fa3ef497137dd54966ff9de43cbcf2bfbf82d96", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Motor_current_consumption_model.cpp", "max_forks_repo_name": "SwiftEngineering/avionics_sim", "max_forks_repo_head_hexsha": "8fa3ef497137dd54966ff9de43cbcf2bfbf82d96", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3921568627, "max_line_length": 99, "alphanum_fraction": 0.7099236641, "num_tokens": 410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152498, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.47660653528167807}}
{"text": "#include <boost/test/unit_test.hpp>\n#include <moreorg/OrganizationModel.hpp>\n#include <moreorg/OrganizationModelAsk.hpp>\n#include <moreorg/Algebra.hpp>\n#include \"test_utils.hpp\"\n#include <moreorg/vocabularies/OM.hpp>\n#include <moreorg/algebra/Connectivity.hpp>\n#include <graph_analysis/BaseGraph.hpp>\n#include <graph_analysis/GraphIO.hpp>\n\nusing namespace moreorg;\nusing namespace moreorg::algebra;\n\nBOOST_AUTO_TEST_SUITE(algebra)\n\nBOOST_AUTO_TEST_CASE(max)\n{\n    ModelPool a;\n    a[\"a\"] = 1;\n    a[\"b\"] = 1;\n\n    ModelPool b;\n    b[\"a\"] = 2;\n    b[\"b\"] = 1;\n    b[\"c\"] = 2;\n\n    {\n        ModelPool c = Algebra::max(a,b);\n        BOOST_REQUIRE_MESSAGE( c[\"a\"] == 2 && c[\"b\"] == 1 && c[\"c\"] == 2, \"ModelPool max: expected, a:2,b:1,c:2 got \" << c.toString());\n    }\n\n    ModelPool c;\n    c[\"a\"] = 4;\n    c[\"b\"] = 0;\n    c[\"c\"] = 1;\n    c[\"d\"] = 1;\n\n    ModelPool::List poolList;\n    poolList.push_back(a);\n    poolList.push_back(b);\n    poolList.push_back(c);\n\n    ModelPool maxPool = Algebra::max(poolList);\n    BOOST_REQUIRE_MESSAGE(maxPool[\"a\"] == 4 && maxPool[\"b\"] == 1 && maxPool[\"c\"] == 2 && maxPool[\"d\"] == 1,\n            \"ModelPool max of list: expected: a:4,b:1,c:2,d:1 got \" << maxPool.toString());\n}\n\nBOOST_AUTO_TEST_CASE(min)\n{\n    ModelPool a;\n    a[\"a\"] = 1;\n    a[\"b\"] = 1;\n\n    ModelPool b;\n    b[\"a\"] = 2;\n    b[\"b\"] = 0;\n    b[\"c\"] = 2;\n\n    {\n        ModelPool c = Algebra::min(a,b);\n        BOOST_REQUIRE_MESSAGE( c[\"a\"] == 1 && c[\"b\"] == 0 && c[\"c\"] == 2, \"ModelPool min: expected, a:1,b:0,c:2 got \" << c.toString());\n    }\n\n    ModelPool c;\n    c[\"a\"] = 4;\n    c[\"b\"] = 1;\n    c[\"c\"] = 1;\n    c[\"d\"] = 1;\n\n    ModelPool::List poolList;\n    poolList.push_back(a);\n    poolList.push_back(b);\n    poolList.push_back(c);\n\n    ModelPool minPool = Algebra::min(poolList);\n    BOOST_REQUIRE_MESSAGE(minPool[\"a\"] == 1 && minPool[\"b\"] == 0 && minPool[\"c\"] == 1 && minPool[\"d\"] == 1,\n            \"ModelPool min of list: expected: a:1,b:0,c:1,d:1 got \" << minPool.toString());\n}\n\nBOOST_AUTO_TEST_CASE(resource_support)\n{\n    using namespace owlapi::vocabulary;\n    using namespace owlapi::model;\n    using namespace moreorg::vocabulary;\n\n    OrganizationModel::Ptr om(new OrganizationModel(getRootDir() + \"/test/data/om-schema-v0.7.owl\"));\n    OrganizationModelAsk ask(om);\n    {\n\n        IRI actor = OM::resolve(\"Actor\");\n        IRI sherpa = OM::resolve(\"Sherpa\");\n        IRI crex = OM::resolve(\"CREX\");\n\n        IRIList resources;\n        resources.push_back(sherpa);\n        resources.push_back(actor);\n        resources.push_back(crex);\n\n        base::VectorXd count = base::VectorXd::Zero(3);\n        count(0) = 1;\n        count(1) = 1;\n        count(2) = 1;\n        ResourceSupportVector supportVector(count, resources);\n\n        ResourceSupportVector e_supportVector = supportVector.embedClassRelationship(ask);\n        BOOST_TEST_MESSAGE(\"Test: \" << e_supportVector.toString());\n    }\n    //{\n    //    IRI system = OM::resolve(\"Sherpa\");\n    //    IRI service  = OM::resolve(\"StereoImageProvider\");\n\n    //    IRIList combination;\n    //    combination.push_back(system);\n\n    //    IRIList services;\n    //    services.push_back(service);\n\n    //    IRIList supportedServices = om.filterSupportedModels(combination, services);\n    //    BOOST_REQUIRE_MESSAGE(supportedServices.size() == 1, \"Sherpa support StereoImagerProvider\");\n    //}\n}\n\n\nBOOST_AUTO_TEST_CASE(resource_support_vector)\n{\n    {\n        ResourceSupportVector nullSupport;\n        BOOST_REQUIRE_MESSAGE(nullSupport.isNull(), \"ResourceSupportVector is null\");\n    }\n\n    {\n        base::VectorXd aSizes(3);\n        aSizes(0) = 1;\n        aSizes(1) = 1;\n        aSizes(2) = 1;\n\n        ResourceSupportVector a(aSizes);\n\n        base::VectorXd bSizes(3);\n        bSizes(0) = 1;\n        bSizes(1) = 1;\n        bSizes(2) = 0;\n        ResourceSupportVector b(bSizes);\n\n        ResourceSupportVector intersection = ResourceSupportVector::intersection(a,b);\n\n        BOOST_REQUIRE_MESSAGE(intersection(0) == 1, \"Dim 0 --> 1\");\n        BOOST_REQUIRE_MESSAGE(intersection(1) == 1, \"Dim 1 --> 1\");\n        BOOST_REQUIRE_MESSAGE(intersection(2) == 0, \"Dim 1 --> 0\");\n\n        BOOST_REQUIRE_MESSAGE(a.contains(b), \"ResourceSupportVector a contains b\");\n        BOOST_REQUIRE_MESSAGE(!b.contains(a), \"ResourceSupportVector b does not contain a\");\n\n        {\n            ResourceSupportVector missing = a.missingSupportFrom(b);\n            BOOST_REQUIRE_MESSAGE(missing(2) == 1, \"Missing support in dimension 2: \" << missing(2));\n        }\n    }\n\n    {\n        base::VectorXd aSizes(3);\n        aSizes(0) = 1;\n        aSizes(1) = 1;\n        aSizes(2) = 1;\n\n        ResourceSupportVector a(aSizes);\n\n        base::VectorXd bSizes(3);\n        bSizes(0) = 0;\n        bSizes(1) = 0;\n        bSizes(2) = 3;\n        ResourceSupportVector b(bSizes);\n\n        ResourceSupportVector intersection = ResourceSupportVector::intersection(a,b);\n\n        BOOST_REQUIRE_MESSAGE(intersection(0) == 0, \"Dim 0 --> 0\");\n        BOOST_REQUIRE_MESSAGE(intersection(1) == 0, \"Dim 1 --> 0\");\n        BOOST_REQUIRE_MESSAGE(intersection(2) == 1, \"Dim 1 --> 1\");\n    }\n}\n\nBOOST_AUTO_TEST_CASE(composition)\n{\n    ModelPool empty;\n\n    ModelPool a;\n    a[\"http://model#a\"] = 1;\n    a[\"http://model#b\"] = 4;\n    a[\"http://model#c\"] = 3;\n\n    {\n        ModelPool::Set aSet;\n        aSet.insert(a);\n        ModelPool::Set rSet = Algebra::maxCompositions(a, empty);\n        BOOST_REQUIRE_MESSAGE(rSet == aSet, \"Composition with model pool and empty set results in first argument\");\n    }\n    {\n        ModelPool::Set aSet;\n        aSet.insert(a);\n        ModelPool::Set rSet = Algebra::maxCompositions(empty,a);\n        BOOST_REQUIRE_MESSAGE(rSet == aSet, \"Composition with empty set and model pool results in second argument\");\n    }\n\n    ModelPool b;\n    b[\"http://model#a\"] = 2;\n    b[\"http://model#b\"] = 4;\n    b[\"http://model#c\"] = 1;\n\n    {\n        ModelPool::Set aSet;\n        aSet.insert(a);\n\n        ModelPool::Set bSet;\n        bSet.insert(b);\n\n        // With min operator\n        ModelPool::Set cSet = Algebra::maxCompositions(a,b);\n        BOOST_REQUIRE_MESSAGE(cSet.size() == 1, \"1 composition expected: was \" << cSet.size());\n        ModelPool c = *cSet.begin();\n        BOOST_REQUIRE_MESSAGE(c[\"http://model#a\"] == 2, \"Composition entry a->2 expected, was a->\" << c[\"http://model#a\"]);\n        BOOST_REQUIRE_MESSAGE(c[\"http://model#b\"] == 4, \"Composition entry b->4 expected, was b->\" << c[\"http://model#b\"]);\n        BOOST_REQUIRE_MESSAGE(c[\"http://model#c\"] == 3, \"Composition entry c->3 expected, was c->\" << c[\"http://model#c\"]);\n    }\n    {\n        ModelPool::Set aSet;\n        aSet.insert(a);\n\n        ModelPool::Set bSet;\n        bSet.insert(a);\n        bSet.insert(b);\n        ModelPool::Set cSet = Algebra::maxCompositions(aSet,bSet);\n        BOOST_REQUIRE_MESSAGE(cSet.size() == 2, \"2 compositions expected: was 2 \" << cSet.size() << ModelPool::toString(cSet));\n\n        ModelPool e0 = a;\n        BOOST_REQUIRE_MESSAGE(cSet.find(e0) != cSet.end(), \"Compositions contains 'a[+]a'\");\n\n        ModelPool e1;\n        e1[\"http://model#a\"] = 2;\n        e1[\"http://model#b\"] = 4;\n        e1[\"http://model#c\"] = 3;\n        BOOST_REQUIRE_MESSAGE(cSet.find(e1) != cSet.end(), \"Compositions contains 'a[+]b'\");\n    }\n    // Identical set\n    {\n        ModelPool::Set bSet;\n        bSet.insert(a);\n        bSet.insert(b);\n        ModelPool::Set cSet = Algebra::maxCompositions(bSet,bSet);\n        BOOST_REQUIRE_MESSAGE(cSet.size() == 3, \"3 compositions expected: was 3 \" << cSet.size() << ModelPool::toString(cSet));\n\n        ModelPool e0 = a;\n        BOOST_REQUIRE_MESSAGE(cSet.find(e0) != cSet.end(), \"Compositions contains 'a[+]a'\");\n\n        ModelPool e1;\n        e1[\"http://model#a\"] = 2;\n        e1[\"http://model#b\"] = 4;\n        e1[\"http://model#c\"] = 3;\n        BOOST_REQUIRE_MESSAGE(cSet.find(e1) != cSet.end(), \"Compositions contains 'a[+]b'\");\n\n        ModelPool e2 = b;\n        BOOST_REQUIRE_MESSAGE(cSet.find(e1) != cSet.end(), \"Compositions contains 'b[+]b'\");\n    }\n}\n\nBOOST_AUTO_TEST_CASE(connectivity)\n{\n    OrganizationModel::Ptr om = make_shared<OrganizationModel>(getOMSchema());\n    OrganizationModelAsk ask(om);\n\n    owlapi::model::IRI ifModel0 = vocabulary::OM::resolve(\"EmiActive\");\n    owlapi::model::IRI ifModel1 = vocabulary::OM::resolve(\"EmiPassive\");\n\n    BOOST_REQUIRE_MESSAGE( ask.ontology().isRelatedTo(ifModel0,\n                vocabulary::OM::compatibleWith(), ifModel1), \"Interfaces are compatible\");\n    {\n        ModelPool modelPool;\n        modelPool[vocabulary::OM::resolve(\"Payload\")] = 2;\n        BOOST_REQUIRE_MESSAGE( Connectivity::isFeasible(modelPool, ask), \"ModelPool: \" << modelPool.toString() );\n    }\n    {\n        ModelPool modelPool;\n        modelPool[vocabulary::OM::resolve(\"Payload\")] = 10;\n\n        BOOST_REQUIRE_MESSAGE( Connectivity::isFeasible(modelPool, ask), \"ModelPool: \" << modelPool.toString() );\n    }\n    {\n        ModelPool modelPool;\n        modelPool[vocabulary::OM::resolve(\"Payload\")] = 20;\n\n        BOOST_REQUIRE_MESSAGE( Connectivity::isFeasible(modelPool, ask), \"ModelPool: \" << modelPool.toString() );\n    }\n    {\n        ModelPool modelPool;\n        modelPool[vocabulary::OM::resolve(\"Payload\")] = 40;\n\n        graph_analysis::BaseGraph::Ptr baseGraph;\n        BOOST_REQUIRE_MESSAGE( Connectivity::isFeasible(modelPool, ask,baseGraph,0), \"ModelPool: \" << modelPool.toString() );\n        graph_analysis::io::GraphIO::write(\"/tmp/organization-model-connectivity-test-payload-10.dot\", baseGraph);\n    }\n    {\n        ModelPool modelPool;\n        modelPool[vocabulary::OM::resolve(\"CREX\")] = 1;\n\n        BOOST_REQUIRE_MESSAGE(Connectivity::isFeasible(modelPool, ask), \"ModelPool: \" << modelPool.toString() );\n\n    }\n    {\n        ModelPool modelPool;\n        modelPool[vocabulary::OM::resolve(\"CREX\")] = 2;\n\n        BOOST_REQUIRE_MESSAGE( !Connectivity::isFeasible(modelPool, ask), \"ModelPool: \" << modelPool.toString() );\n    }\n    {\n        ModelPool modelPool;\n        modelPool[vocabulary::OM::resolve(\"CREX\")] = 10;\n\n        BOOST_REQUIRE_MESSAGE( !Connectivity::isFeasible(modelPool, ask, 30000), \"ModelPool: \" << modelPool.toString() );\n\n    }\n    {\n        ModelPool modelPool;\n        modelPool[vocabulary::OM::resolve(\"Sherpa\")] = 1;\n        BOOST_REQUIRE_MESSAGE( Connectivity::isFeasible(modelPool, ask), \"ModelPool: \" << modelPool.toString() );\n    }\n    {\n        ModelPool modelPool;\n        modelPool[vocabulary::OM::resolve(\"Sherpa\")] = 2;\n        BOOST_REQUIRE_MESSAGE( Connectivity::isFeasible(modelPool, ask), \"ModelPool: \" << modelPool.toString() );\n    }\n    {\n        ModelPool modelPool;\n        modelPool[vocabulary::OM::resolve(\"Sherpa\")] = 20;\n        BOOST_REQUIRE_MESSAGE( Connectivity::isFeasible(modelPool, ask), \"ModelPool: \" << modelPool.toString() );\n    }\n    {\n        ModelPool modelPool;\n        modelPool[vocabulary::OM::resolve(\"Sherpa\")] = 1;\n        modelPool[vocabulary::OM::resolve(\"CREX\")] = 1;\n\n        BOOST_REQUIRE_MESSAGE( Connectivity::isFeasible(modelPool, ask), \"ModelPool: \" << modelPool.toString() );\n    }\n    {\n        ModelPool modelPool;\n        modelPool[vocabulary::OM::resolve(\"Sherpa\")] = 1;\n        modelPool[vocabulary::OM::resolve(\"CREX\")] = 10;\n\n        BOOST_REQUIRE_MESSAGE(!Connectivity::isFeasible(modelPool, ask, 30000), \"ModelPool: \" << modelPool.toString() );\n    }\n    {\n        ModelPool modelPool;\n        modelPool[vocabulary::OM::resolve(\"Sherpa\")] = 4;\n        modelPool[vocabulary::OM::resolve(\"CREX\")] = 3;\n\n        BOOST_REQUIRE_MESSAGE(Connectivity::isFeasible(modelPool, ask), \"ModelPool: \" << modelPool.toString() );\n    }\n    {\n        ModelPool modelPool;\n        modelPool[vocabulary::OM::resolve(\"Sherpa\")] = 10;\n        modelPool[vocabulary::OM::resolve(\"CREX\")] = 10;\n\n        graph_analysis::BaseGraph::Ptr baseGraph;\n        BOOST_REQUIRE_MESSAGE( Connectivity::isFeasible(modelPool, ask, baseGraph,0), \"ModelPool: \" << modelPool.toString() );\n        graph_analysis::io::GraphIO::write(\"/tmp/organization-model-connectivity-test-sherpa10-cex10.dot\", baseGraph);\n    }\n    {\n        ModelPool modelPool;\n        modelPool[vocabulary::OM::resolve(\"Sherpa\")] = 4;\n        modelPool[vocabulary::OM::resolve(\"CREX\")] = 10;\n\n        BOOST_REQUIRE_MESSAGE(!Connectivity::isFeasible(modelPool, ask, 30000), \"ModelPool: \" << modelPool.toString() );\n    }\n    {\n        ModelPool modelPool;\n        modelPool[vocabulary::OM::resolve(\"Sherpa\")] = 6;\n        modelPool[vocabulary::OM::resolve(\"CREX\")] = 10;\n\n        graph_analysis::BaseGraph::Ptr baseGraph;\n        BOOST_REQUIRE_MESSAGE(!Connectivity::isFeasible(modelPool, ask, baseGraph, 30000), \"ModelPool: \" << modelPool.toString() );\n        if(baseGraph)\n        {\n            graph_analysis::io::GraphIO::write(\"/tmp/organization-model-connectivity-test-sherpa6-cex10.dot\", baseGraph);\n        }\n    }\n    {\n        ModelPool modelPool;\n        modelPool[vocabulary::OM::resolve(\"Sherpa\")] = 8;\n        modelPool[vocabulary::OM::resolve(\"CREX\")] = 10;\n\n        BOOST_REQUIRE_MESSAGE(!Connectivity::isFeasible(modelPool, ask, 30000), \"ModelPool: \" << modelPool.toString() );\n    }\n    {\n        ModelPool modelPool;\n        modelPool[vocabulary::OM::resolve(\"Sherpa\")] = 9;\n        modelPool[vocabulary::OM::resolve(\"CREX\")] = 10;\n\n        BOOST_REQUIRE_MESSAGE(Connectivity::isFeasible(modelPool, ask), \"ModelPool: \" << modelPool.toString() );\n    }\n\n    {\n        ModelPool modelPool;\n        modelPool[vocabulary::OM::resolve(\"Sherpa\")] = 5;\n        modelPool[vocabulary::OM::resolve(\"CREX\")] = 3;\n        modelPool[vocabulary::OM::resolve(\"BaseCamp\")] = 3;\n        modelPool[vocabulary::OM::resolve(\"Payload\")] = 10;\n\n        // active: 2x5\n        // passive: 3x3\n\n        graph_analysis::BaseGraph::Ptr baseGraph;\n        bool feasible = Connectivity::isFeasible(modelPool, ask, baseGraph,60000);\n        if(baseGraph)\n        {\n            graph_analysis::io::GraphIO::write(\"/tmp/organization-model-connectivity-test-full-team_s5c3b5p25.dot\", baseGraph);\n        }\n        BOOST_TEST_MESSAGE(\"Evaluation done: \" << Connectivity::getStatistics().toString());\n        BOOST_REQUIRE_MESSAGE(feasible, \"ModelPool: \" << modelPool.toString() );\n    }\n}\n\nBOOST_AUTO_TEST_CASE(connectivity_multiple_interfaces)\n{\n    OrganizationModel::Ptr om(new OrganizationModel(getRootDir() + \"/test/data/om-multiple-interfaces.owl\") );\n    OrganizationModelAsk ask(om);\n\n    {\n        ModelPool modelPool;\n        modelPool[vocabulary::OM::resolve(\"RobotA\")] = 2;\n\n        BOOST_REQUIRE_MESSAGE(!Connectivity::isFeasible(modelPool, ask), \"RobotA 2 should not be a valid combination: ModelPool: \" << modelPool.toString() );\n    }\n    {\n        ModelPool modelPool;\n        modelPool[vocabulary::OM::resolve(\"RobotB\")] = 2;\n\n        BOOST_REQUIRE_MESSAGE(!Connectivity::isFeasible(modelPool, ask), \"ModelPool: \" << modelPool.toString() );\n    }\n    {\n        ModelPool modelPool;\n        modelPool[vocabulary::OM::resolve(\"RobotC\")] = 2;\n\n        BOOST_REQUIRE_MESSAGE( !Connectivity::isFeasible(modelPool, ask), \"ModelPool: \" << modelPool.toString() );\n\n    }\n    {\n        ModelPool modelPool;\n        modelPool[vocabulary::OM::resolve(\"RobotA\")] = 1;\n        modelPool[vocabulary::OM::resolve(\"RobotB\")] = 1;\n\n        BOOST_REQUIRE_MESSAGE( Connectivity::isFeasible(modelPool, ask), \"ModelPool: \" << modelPool.toString() );\n    }\n    {\n        ModelPool modelPool;\n        modelPool[vocabulary::OM::resolve(\"RobotA\")] = 1;\n        modelPool[vocabulary::OM::resolve(\"RobotC\")] = 1;\n\n        BOOST_REQUIRE_MESSAGE( Connectivity::isFeasible(modelPool, ask), \"ModelPool: \" << modelPool.toString() );\n    }\n    {\n        ModelPool modelPool;\n        modelPool[vocabulary::OM::resolve(\"RobotB\")] = 1;\n        modelPool[vocabulary::OM::resolve(\"RobotC\")] = 1;\n\n        BOOST_REQUIRE_MESSAGE( !Connectivity::isFeasible(modelPool, ask), \"ModelPool: \" << modelPool.toString() );\n    }\n    {\n        ModelPool modelPool;\n        modelPool[vocabulary::OM::resolve(\"RobotA\")] = 1;\n        modelPool[vocabulary::OM::resolve(\"RobotB\")] = 1;\n        modelPool[vocabulary::OM::resolve(\"RobotC\")] = 1;\n\n        BOOST_REQUIRE_MESSAGE( Connectivity::isFeasible(modelPool, ask), \"ModelPool: \" << modelPool.toString() );\n    }\n}\n\nBOOST_AUTO_TEST_CASE(subset_superset)\n{\n    ModelPool modelPoolA;\n    ModelPool modelPoolB;\n\n    BOOST_REQUIRE_MESSAGE( Algebra::isSubset(modelPoolA, modelPoolB), \"Empty models are subsets\" );\n    BOOST_REQUIRE_MESSAGE( Algebra::isSuperset(modelPoolA, modelPoolB), \"Empty models are supersets\" );\n\n    modelPoolA[vocabulary::OM::resolve(\"RobotA\")] = 1;\n    modelPoolB[vocabulary::OM::resolve(\"RobotA\")] = 1;\n\n    BOOST_REQUIRE_MESSAGE( Algebra::isSubset(modelPoolA, modelPoolB), \"Equal model pool are subsets\" );\n    BOOST_REQUIRE_MESSAGE( Algebra::isSubset(modelPoolB, modelPoolA), \"Equal model pool are subsets\" );\n    BOOST_REQUIRE_MESSAGE( Algebra::isSuperset(modelPoolA, modelPoolB), \"Equal model pool are supersets\" );\n    BOOST_REQUIRE_MESSAGE( Algebra::isSuperset(modelPoolB, modelPoolA), \"Equal model pool are supersets\" );\n\n    modelPoolA[vocabulary::OM::resolve(\"RobotB\")] = 1;\n    BOOST_REQUIRE_MESSAGE( !Algebra::isSubset(modelPoolA, modelPoolB), \"A is not subset of B\");\n    BOOST_REQUIRE_MESSAGE( Algebra::isSubset(modelPoolB, modelPoolA), \"B is subset of A\");\n    BOOST_REQUIRE_MESSAGE( Algebra::isSuperset(modelPoolA, modelPoolB), \"A is superset of B\");\n    BOOST_REQUIRE_MESSAGE( !Algebra::isSuperset(modelPoolB, modelPoolA), \"B is not a superset of A\");\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "b318913a439760517d22a711009df6eb4f1dee32", "size": 17566, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_Algebra.cpp", "max_stars_repo_name": "tomcreutz/knowledge-reasoning-moreorg", "max_stars_repo_head_hexsha": "545fa92eaf0fc8ccc4cc042bd994afc918d16f68", "max_stars_repo_licenses": ["BSD-3-Clause"], "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_Algebra.cpp", "max_issues_repo_name": "tomcreutz/knowledge-reasoning-moreorg", "max_issues_repo_head_hexsha": "545fa92eaf0fc8ccc4cc042bd994afc918d16f68", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-02-26T11:11:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-26T19:16:10.000Z", "max_forks_repo_path": "test/test_Algebra.cpp", "max_forks_repo_name": "tomcreutz/knowledge-reasoning-moreorg", "max_forks_repo_head_hexsha": "545fa92eaf0fc8ccc4cc042bd994afc918d16f68", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-17T13:02:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-17T13:02:49.000Z", "avg_line_length": 35.2024048096, "max_line_length": 157, "alphanum_fraction": 0.6236479563, "num_tokens": 4744, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.47660653016521465}}
{"text": "\n#include<iostream>\n#include<algorithm>\n#include<fstream>\n#include<chrono>\n\n#include<ros/ros.h>\n#include <cv_bridge/cv_bridge.h>\n\n#include<opencv2/core/core.hpp>\n\n#include\"../../ORB_SLAM2/include/System.h\"\n#include <geometry_msgs/PoseStamped.h>\n#include <sensor_msgs/Imu.h>\n\n//Eigen\n#include <Eigen/Core>\n#include <Eigen/Geometry> \n#include <Eigen/Dense>\n\n\nros::Publisher  pose_pub;\nros::Publisher  imu_pub;\n\nclass EkfFusion\n{\npublic:\n    EkfFusion(){}\n\n    void CamPoseCallback(const geometry_msgs::PoseStampedConstPtr& msg)\n    {\n        Eigen::Vector3f cam_t(msg->pose.position.x,msg->pose.position.y,msg->pose.position.z);\n        Eigen::Quaternionf cam_q(msg->pose.orientation.w,msg->pose.orientation.x,\n                             msg->pose.orientation.y,msg->pose.orientation.z);\n\t\n\tcam_R_wc_ = cam_q.toRotationMatrix();\n\t\n\tEigen::Matrix4f T_bc; //transformation matrix of camera frame wrt. body frame\n\t\n\tT_bc << 0.0148655429818, -0.999880929698, 0.00414029679422, -0.0216401454975,\n         0.999557249008, 0.0149672133247, 0.025715529948, -0.064676986768,\n        -0.0257744366974, 0.00375618835797, 0.999660727178, 0.00981073058949,\n         0.0, 0.0, 0.0, 1.0;\n\t\n\tEigen::Matrix4f T_cb;\n\tT_cb = T_bc.inverse();\n\t\n\tEigen::Matrix3f R_cb = T_cb.block<3,3>(0,0);\n\t//Eigen::Vector3f t_cb = T_cb.block<3,1>(0,3);\n\n        \n\t\n\tEigen::Vector3f acc_w = cam_R_wc_*(R_cb*acc_b_) + Eigen::Vector3f(0,9.81,0);\n\t\n//         geometry_msgs::PoseStamped pose_msg;\n//         pose_msg.pose.position.x = cam_t(0);\n//         pose_msg.pose.position.y = cam_t(1);\n//         pose_msg.pose.position.z = cam_t(2);\n//         pose_msg.pose.orientation.x = cam_q.x();\n//         pose_msg.pose.orientation.y = cam_q.y();\n//         pose_msg.pose.orientation.z = cam_q.z();\n//         pose_msg.pose.orientation.w = cam_q.w();\n//         pose_msg.header = msg->header;\n//         pose_pub.publish(pose_msg);\n\tsensor_msgs::Imu imu_msg;\n        imu_msg.linear_acceleration.x = acc_w(0);\n        imu_msg.linear_acceleration.y = acc_w(1);\n        imu_msg.linear_acceleration.z = acc_w(2);\n        imu_msg.header = msg->header;\n        imu_pub.publish(imu_msg);\n    }\n\n    void ImuCallback(const sensor_msgs::ImuConstPtr& msg)\n    {\n        Eigen::Vector3f imu_acc(msg->linear_acceleration.x,msg->linear_acceleration.y,msg->linear_acceleration.z);\n        Eigen::Vector3f imu_omega(msg->angular_velocity.x,msg->angular_velocity.y,msg->angular_velocity.z);\n\n\tacc_b_ = 0.8*acc_b_ + 0.2*imu_acc;\n\t\n//         sensor_msgs::Imu imu_msg;\n//         imu_msg.angular_velocity.x = imu_omega(0);\n//         imu_msg.angular_velocity.y = imu_omega(1);\n//         imu_msg.angular_velocity.z = imu_omega(2);\n//         imu_msg.linear_acceleration.x = imu_acc(0);\n//         imu_msg.linear_acceleration.y = imu_acc(1);\n//         imu_msg.linear_acceleration.z = imu_acc(2);\n//         imu_msg.header = msg->header;\n//         imu_pub.publish(imu_msg);\n    }\n    \n    Eigen::Matrix3f cam_R_wc_;\n    Eigen::Vector3f acc_b_;\n\n};\n\nint main(int argc, char **argv)\n{\n    ros::init(argc, argv, \"ekf_fusion\");\n    ros::start();\n\n    EkfFusion ekf;\n\n    ros::NodeHandle nodeHandler;\n\n    pose_pub = nodeHandler.advertise<geometry_msgs::PoseStamped>(\"/ekf_pose\",1);\n    imu_pub  = nodeHandler.advertise<sensor_msgs::Imu>(\"/ekf_imu\",1);\n    ros::Subscriber cam_sub = nodeHandler.subscribe(\"/cam_pose\", 1, &EkfFusion::CamPoseCallback, &ekf);\n    ros::Subscriber imu_sub = nodeHandler.subscribe(\"/imu\", 1, &EkfFusion::ImuCallback, &ekf);\n    \n    ros::spin();\n\n    ros::shutdown();\n\n    return 0;\n}\n\n\n", "meta": {"hexsha": "729aca8a3335183a1d571ce574b4bd6baddacd44", "size": 3551, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/orb_imu/src/ekf_fusion.cc", "max_stars_repo_name": "JinyaoZhu/orb_imu", "max_stars_repo_head_hexsha": "d1c4b847d5f58794880b85c70c2ac7568aa52f2b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-24T09:51:04.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-24T09:51:04.000Z", "max_issues_repo_path": "src/orb_imu/src/ekf_fusion.cc", "max_issues_repo_name": "JinyaoZhu/orb_imu", "max_issues_repo_head_hexsha": "d1c4b847d5f58794880b85c70c2ac7568aa52f2b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/orb_imu/src/ekf_fusion.cc", "max_forks_repo_name": "JinyaoZhu/orb_imu", "max_forks_repo_head_hexsha": "d1c4b847d5f58794880b85c70c2ac7568aa52f2b", "max_forks_repo_licenses": ["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.093220339, "max_line_length": 114, "alphanum_fraction": 0.6572796395, "num_tokens": 1034, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4764889197478427}}
{"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/*!\n * \\file\n**/\n#ifndef BOOST_SIMD_ARITHMETIC_FUNCTIONS_REM_HPP_INCLUDED\n#define BOOST_SIMD_ARITHMETIC_FUNCTIONS_REM_HPP_INCLUDED\n#include <boost/simd/include/functor.hpp>\n#include <boost/dispatch/include/functor.hpp>\n\n/*!\n * \\ingroup boost_simd_arithmetic\n * \\defgroup boost_simd_arithmetic_rem rem\n *\n * \\par Description\n * This function computes the floating-point remainder of dividing a0 by a1.\n * The return value is a0-n*a1, where n is the quotient a0/a1 rounded\n * toward zero to an integer.\\par\n * if one prefer: if a1 is zero returns a0, else return\n * a0-divfix(a0,a1)*a1\n *\n * \\par Header file\n *\n * \\code\n * #include <nt2/include/functions/rem.hpp>\n * \\endcode\n *\n * \\par Alias\n * \\arg fmod\n *\n * \\synopsis\n *\n * \\code\n * namespace boost::simd\n * {\n *   template <class A0>\n *     meta::call<tag::rem_(A0,A0)>::type\n *     rem(const A0 & a0,const A0 & a1);\n * }\n * \\endcode\n *\n * \\param a0 the first parameter of rem\n * \\param a1 the second parameter of rem\n *\n * \\return a value of the common type of the parameters\n *\n * \\par Notes\n * In SIMD mode, this function acts elementwise on the inputs vectors elements\n * \\par\n *\n**/\n\nnamespace boost { namespace simd { namespace tag\n  {\n    /*!\n     * \\brief Define the tag rem_ of functor rem\n     *        in namespace boost::simd::tag for toolbox boost.simd.arithmetic\n    **/\n    struct rem_ : ext::elementwise_<rem_> { typedef ext::elementwise_<rem_> parent; };\n  }\n  BOOST_DISPATCH_FUNCTION_IMPLEMENTATION(tag::rem_, rem, 2)\n  BOOST_DISPATCH_FUNCTION_IMPLEMENTATION(tag::rem_, fmod, 2)\n} }\n\n#endif\n\n// modified by jt the 25/12/2010\n", "meta": {"hexsha": "29e81dd1406b048ae66791febff0034d80d772a8", "size": 2105, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/arithmetic/include/boost/simd/arithmetic/functions/rem.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/rem.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/rem.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": 28.4459459459, "max_line_length": 86, "alphanum_fraction": 0.6228028504, "num_tokens": 551, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833789613196, "lm_q2_score": 0.6150878696277512, "lm_q1q2_score": 0.4764368404143831}}
{"text": "#ifndef HOUSE_H\n#define HOUSE_H\n\n#include <Eigen/Dense>\n\n#include <vector>\n\nclass HOUSE {\n\n    public:\n\n        // Dynamical model type\n        typedef std::function <Eigen::VectorXd (double, double,\n            const Eigen::VectorXd&, const Eigen::VectorXd&)> dyn_model;\n\n        // Measurement model type\n        typedef std::function <Eigen::VectorXd (double,\n            const Eigen::VectorXd&, const Eigen::VectorXd&)> meas_model;\n\n        // Distribution type\n        class Dist {\n\n            public:\n\n                int n;\n\n                Eigen::VectorXd mean, skew, kurt;\n                Eigen::MatrixXd cov, covL;\n\n                // Generate distribution from sigma points & weights\n                Dist(const Eigen::MatrixXd& X, const Eigen::VectorXd& w);\n\n                // Generate zero-mean Gaussian distribution\n                Dist(const Eigen::MatrixXd& S);\n\n        };\n\n        // Augmented state sigma point type\n        class Sigma {\n\n            public:\n\n                int n_state, n_noise, n_pts;\n\n                Eigen::MatrixXd state, noise;\n                Eigen::VectorXd wgt;\n\n                Sigma(const Dist& distX, const Dist& distW, double delta);\n\n        };\n\n        // Constructor\n        HOUSE(\n            const dyn_model& f_,\n            const meas_model& h_,\n            int nz_,\n            double t0,\n            const Dist& distx0,\n            const Dist& distw_,\n            const Dist& distv_,\n            double delta_\n        );\n\n        // Prediction step\n        void predict(double tp);\n\n        // Update step with one measurement\n        void update(const Eigen::VectorXd& z);\n\n        // Run filter for sequence of measurements\n        void run(const Eigen::VectorXd& tz, const Eigen::MatrixXd& Z);\n\n        // Dynamical model\n        const dyn_model f;\n\n        // Measurement model type\n        const meas_model h;\n\n        // Dimensions of state & measurement\n        const int nx, nz;\n\n        // Dimensions of process & measurement noise\n        const int nw, nv;\n\n        // Distribution of process noise\n        const Dist distw;\n\n        // Distribution of measurement noise\n        const Dist distv;\n\n        // Minimal weight at mean\n        const double delta;\n\n        // History of state estimate distributions\n        std::vector<Dist> distx;\n\n        // Times\n        std::vector<double> t;\n\n        // Reset filter\n        void reset(double t0, const Dist& distx0);\n\n        // Save results\n        void save(const std::string& filename);\n\n};\n\n#endif\n", "meta": {"hexsha": "12eae658ec01c469b226a9938415d13be6915ea1", "size": 2524, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "house.hpp", "max_stars_repo_name": "SIOSlab/HOUSE", "max_stars_repo_head_hexsha": "81381a2384bd84be1afc49cace288c0606ee480f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "house.hpp", "max_issues_repo_name": "SIOSlab/HOUSE", "max_issues_repo_head_hexsha": "81381a2384bd84be1afc49cace288c0606ee480f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "house.hpp", "max_forks_repo_name": "SIOSlab/HOUSE", "max_forks_repo_head_hexsha": "81381a2384bd84be1afc49cace288c0606ee480f", "max_forks_repo_licenses": ["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.1559633028, "max_line_length": 74, "alphanum_fraction": 0.545562599, "num_tokens": 508, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.47643683908572687}}
{"text": "#define BOOST_TEST_MODULE\n#include <boost/test/unit_test.hpp>\n#include <util/test_macros.hpp>\n#include <string>\n#include <random>\n#include <set>\n#include <sstream>\n#include <vector>\n#include <algorithm>\n#include <util/cityhash_tc.hpp>\n#include <cmath>\n\n#include <numerics/armadillo.hpp>\n\n// ML-Data Utils\n#include <unity/toolkits/ml_data_2/standardization-inl.hpp>\n\n// Testing utils common to all of ml_data\n#include <unity/toolkits/ml_data_2/testing_utils.hpp>\n\nusing namespace turi;\n\ntypedef arma::vec DenseVector;\ntypedef sparse_vector<double, size_t> SparseVector;\n\ntypedef arma::mat DenseMatrix;\n\nstruct standardization  {\n\n  public:\n\n  /*\n   * Test the L2-scaler by generating random points and then projecting them\n   * and inverse projecting back to get the same point back.\n   */\n  void _run_l2_scaling_test(size_t n, const std::string& run_string) {\n\n    sframe X;\n    v2::ml_data data;\n    std::tie(X, data) = v2::make_random_sframe_and_ml_data(n, run_string);\n    TS_ASSERT(n == X.size());\n    TS_ASSERT(n == data.size());\n\n    // Take a snapshot of the created metadata\n    std::shared_ptr<v2::ml_metadata> metadata = data.metadata();\n    size_t total_size;\n    std::shared_ptr<l2_rescaling> scaler;\n    DenseVector x, ans, sp1, sp2;\n    SparseVector sp_x, sp_ans;\n    DenseMatrix Xmat;\n\n\n    scaler.reset(new l2_rescaling(metadata, true));\n\n    // Test for the reference encoding section.\n    // ---------------------------------------------------------------------\n    total_size = scaler->get_total_size();\n\n    x.resize(total_size);\n    sp_x.resize(total_size);\n    sp1.resize(total_size);\n    sp2.resize(total_size);\n    ans.resize(total_size);\n    sp_ans.resize(total_size);\n    Xmat.resize(n, total_size);\n\n    for(auto it = data.get_iterator(0,1,false,true); !it.done(); ++it){\n      // Densevector\n      x.zeros();\n      it.fill_row_expr(x);\n      ans = x;\n      scaler->transform(x);\n      Xmat.row(it.row_index()) = x.t();\n      sp1 = x;\n      scaler->inverse_transform(x);\n      TS_ASSERT(approx_equal(x, ans, \"absdiff\",  1e-5));\n\n      // Sparse vector\n      sp_x.zeros();\n      it.fill_row_expr(sp_x);\n      sp_ans = sp_x;\n      scaler->transform(sp_x);\n      sp2 = sp_x;\n      TS_ASSERT(approx_equal(sp1, sp2, \"absdiff\",  1e-5));\n      scaler->inverse_transform(sp_x);\n      TS_ASSERT(approx_equal(sp_x, sp_ans, \"absdiff\", 1e-5));\n    }\n\n    // Check that each col has norm 1\n    for(size_t i = 0; i < Xmat.n_cols-1; i++){\n      TS_ASSERT(std::abs(arma::norm(Xmat.col(i), 2)/std::sqrt(n) - 1) < 3e-1);\n    }\n\n    // Test without reference encoding.\n    // ---------------------------------------------------------------------\n    scaler.reset(new l2_rescaling(metadata, false));\n    total_size = scaler->get_total_size();\n    x.resize(total_size);\n    sp_x.resize(total_size);\n    sp1.resize(total_size);\n    sp2.resize(total_size);\n    ans.resize(total_size);\n    sp_ans.resize(total_size);\n    Xmat.resize(n, total_size);\n\n    for(auto it = data.get_iterator(); !it.done(); ++it){\n      x.zeros();\n      it.fill_row_expr(x);\n      ans = x;\n      scaler->transform(x);\n      Xmat.row(it.row_index()) = x.t();\n      sp1 = x;\n      scaler->inverse_transform(x);\n      TS_ASSERT(approx_equal(x, ans, \"absdiff\",  1e-5));\n\n      // Sparse vector\n      sp_x.zeros();\n      it.fill_row_expr(sp_x);\n      sp_ans = sp_x;\n      scaler->transform(sp_x);\n      sp2 = sp_x;\n      TS_ASSERT(approx_equal(sp1, sp2, \"absdiff\",  1e-5));\n      scaler->inverse_transform(sp_x);\n      TS_ASSERT(approx_equal(sp_x, sp_ans, \"absdiff\",  1e-5));\n    }\n\n    // Check that each col has norm 1\n    for(size_t i = 0; i < Xmat.n_cols-1; i++){\n      TS_ASSERT(std::abs(arma::norm(Xmat.col(i), 2)/std::sqrt(n) - 1) < 3e-1);\n    }\n\n    // Save and Load\n    dir_archive archive_write;\n    archive_write.open_directory_for_write(\"standardization_tests\");\n    turi::oarchive oarc(archive_write);\n    oarc << *scaler;\n    archive_write.close();\n    dir_archive archive_read;\n    archive_read.open_directory_for_read(\"standardization_tests\");\n    turi::iarchive iarc(archive_read);\n    iarc >> *scaler;\n\n    // Test after save and load\n    // ---------------------------------------------------------------------\n    TS_ASSERT(total_size == scaler->get_total_size());\n    total_size = scaler->get_total_size();\n    x.resize(total_size);\n    sp_x.resize(total_size);\n    sp1.resize(total_size);\n    sp2.resize(total_size);\n    ans.resize(total_size);\n    sp_ans.resize(total_size);\n    Xmat.resize(n, total_size);\n\n    for(auto it = data.get_iterator(); !it.done(); ++it){\n      // Densevector\n      x.zeros();\n      it.fill_row_expr(x);\n      ans = x;\n      scaler->transform(x);\n      Xmat.row(it.row_index()) = x.t();\n      sp1 = x;\n      scaler->inverse_transform(x);\n      TS_ASSERT(approx_equal(x, ans, \"absdiff\",  1e-5));\n\n      // Sparse vector\n      sp_x.zeros();\n      it.fill_row_expr(sp_x);\n      sp_ans = sp_x;\n      scaler->transform(sp_x);\n      sp2 = sp_x;\n      TS_ASSERT(approx_equal(sp1, sp2, \"absdiff\",  1e-5));\n      scaler->inverse_transform(sp_x);\n      TS_ASSERT(approx_equal(sp_x, sp_ans, \"absdiff\",  1e-5));\n    }\n\n    // Check that each col has norm 1\n    for(size_t i = 0; i < Xmat.n_cols-1; i++){\n      TS_ASSERT(std::abs(arma::norm(Xmat.col(i))/std::sqrt(n) - 1) < 3e-1);\n    }\n  }\n\n  void test_standardization_n() {\n    _run_l2_scaling_test(100, \"n\");\n  }\n\n  void test_standardization_v() {\n    _run_l2_scaling_test(100, \"v\");\n  }\n\n};\n\nBOOST_FIXTURE_TEST_SUITE(_standardization, standardization)\nBOOST_AUTO_TEST_CASE(test_standardization_n) {\n  standardization::test_standardization_n();\n}\nBOOST_AUTO_TEST_CASE(test_standardization_v) {\n  standardization::test_standardization_v();\n}\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "fd6192a7bbdabea0b69d5f5547c9bd7c680d4657", "size": 5734, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "test/unity/toolkits/ml_data_2/standardization_interface_tests.cxx", "max_stars_repo_name": "shreyasvj25/turicreate", "max_stars_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-12-15T20:03:51.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-15T20:03:51.000Z", "max_issues_repo_path": "test/unity/toolkits/ml_data_2/standardization_interface_tests.cxx", "max_issues_repo_name": "shreyasvj25/turicreate", "max_issues_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-09-08T02:18:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T00:39:44.000Z", "max_forks_repo_path": "test/unity/toolkits/ml_data_2/standardization_interface_tests.cxx", "max_forks_repo_name": "shreyasvj25/turicreate", "max_forks_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-10-21T17:46:28.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-21T17:46:28.000Z", "avg_line_length": 28.5273631841, "max_line_length": 78, "alphanum_fraction": 0.623648413, "num_tokens": 1522, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.47643683908572687}}
{"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/test/unit_test.hpp>\n\n#include \"Molassembler/Detail/CyclicPolygons.h\"\n\n#include \"Molassembler/Temple/Random.h\"\n#include \"Molassembler/Temple/Stringify.h\"\n#include \"Molassembler/Temple/constexpr/Jsf.h\"\n\n#include <iomanip>\n#include <iostream>\n#include <fstream>\n\nusing namespace Scine::Molassembler;\nusing namespace std::string_literals;\n\nextern Temple::Generator<> generator;\n\nvoid writeAngleAnalysisFiles(\n  const std::vector<double>& edgeLengths,\n  const std::string& baseName\n) {\n  using namespace CyclicPolygons;\n\n  const double longestEdge = Temple::max(edgeLengths);\n  const double minR = longestEdge / 2 + 1e-10;\n  const double lowerBound = minR;\n  const double upperBound = std::max(\n    Detail::regularCircumradius(edgeLengths.size(), longestEdge),\n    minR\n  );\n\n  double rootGuess = Detail::regularCircumradius(\n    edgeLengths.size(),\n    std::max(Temple::average(edgeLengths), minR)\n  );\n\n  if(rootGuess < lowerBound) {\n    rootGuess = lowerBound;\n  } else if(rootGuess > upperBound) {\n    rootGuess = upperBound;\n  }\n\n  double circumradius;\n  bool circumcenterInside;\n\n  std::tie(circumradius, circumcenterInside) = CyclicPolygons::Detail::convexCircumradius(edgeLengths);\n\n  std::ofstream scanFile(baseName + \".csv\"s);\n  scanFile << std::fixed << std::setprecision(8);\n\n  const unsigned nScanSteps = 1000;\n  const double stepSize = (upperBound - lowerBound) / nScanSteps;\n  for(unsigned i = 0; i <= nScanSteps; i++) {\n    const double currentR = lowerBound + i * stepSize;\n    scanFile << currentR << \", \"\n      << Detail::circumcenterInside::centralAnglesDeviation(currentR, edgeLengths)\n      << \", \"\n      << Detail::circumcenterOutside::centralAnglesDeviation(currentR, edgeLengths, longestEdge)\n      << std::endl;\n  }\n\n  scanFile.close();\n\n  std::ofstream metaFile(baseName + \"-meta.csv\"s);\n  metaFile << std::fixed << std::setprecision(8);\n  for(unsigned i = 0; i < edgeLengths.size(); i++) {\n    metaFile << edgeLengths[i];\n    if(i != edgeLengths.size() - 1) {\n      metaFile << \", \";\n    }\n  }\n  metaFile << std::endl;\n  metaFile << rootGuess << \", \" << circumradius << std::endl;\n  metaFile.close();\n}\n\nBOOST_AUTO_TEST_CASE(CentralAngleRootFinding, *boost::unit_test::label(\"Molassembler\")) {\n  unsigned failureIndex = 0;\n\n  const double upperLimit = 5.6; // Fr-Fr single\n  const double lowerLimit = 0.7; // H-H single\n\n  const unsigned nTests = 1000;\n\n  for(unsigned nSides = 3; nSides < 10; ++nSides) {\n    for(unsigned testNumber = 0; testNumber < nTests; testNumber++) {\n      std::vector<double> edgeLengths = Temple::Random::getN<double>(lowerLimit, upperLimit, nSides, generator.engine);\n      while(!CyclicPolygons::exists(edgeLengths)) {\n        edgeLengths = Temple::Random::getN<double>(lowerLimit, upperLimit, nSides, generator.engine);\n      }\n\n      double circumradius = std::nan(\"\");\n      bool circumcenterInside = false;\n\n      auto assignCircumradius = [&]() -> void {\n        std::tie(circumradius, circumcenterInside) = CyclicPolygons::Detail::convexCircumradius(\n          edgeLengths\n        );\n      };\n\n      BOOST_CHECK_NO_THROW(assignCircumradius());\n      BOOST_CHECK(!std::isnan(circumradius));\n\n      double deviation;\n      if(circumcenterInside) {\n        deviation = CyclicPolygons::Detail::circumcenterInside::centralAnglesDeviation(\n          circumradius,\n          edgeLengths\n        );\n      } else {\n        deviation = CyclicPolygons::Detail::circumcenterOutside::centralAnglesDeviation(\n          circumradius,\n          edgeLengths,\n          Temple::max(edgeLengths)\n        );\n      }\n\n      bool pass = std::fabs(deviation) < 1e-4;\n\n      BOOST_CHECK_MESSAGE(\n        pass,\n        \"Central angle deviation norm is not smaller than 1e-5 for \" << Temple::stringify(edgeLengths)\n          << \", circumcenter is inside: \" << std::boolalpha << circumcenterInside << \", deviation: \" << deviation\n      );\n\n      const double internalAngleSumDeviation = Temple::sum(\n        CyclicPolygons::Detail::generalizedInternalAngles(edgeLengths, circumradius, circumcenterInside)\n      ) - (nSides - 2) * M_PI;\n\n      pass = pass && (std::fabs(internalAngleSumDeviation) < 1e-5);\n\n      BOOST_CHECK_MESSAGE(\n        std::fabs(internalAngleSumDeviation) < 1e-5,\n        \"Internal angle sum deviation from \" << (nSides - 2)\n          <<  \"\u03c0 for edge lengths \" << Temple::stringify(edgeLengths)\n          << \" is \" << internalAngleSumDeviation\n          << \", whose norm is not less than 1e-5\"\n      );\n\n      if(!pass) {\n        writeAngleAnalysisFiles(\n          edgeLengths,\n          \"angle-failure-\"s + std::to_string(failureIndex)\n        );\n\n        ++failureIndex;\n      }\n    }\n  }\n}\n", "meta": {"hexsha": "e5074bccf8ac0c7b083a1be9ba8d37dbde4ac2b5", "size": 4853, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/Detail/CyclicPolygons.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": "test/Detail/CyclicPolygons.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": "test/Detail/CyclicPolygons.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": 30.9108280255, "max_line_length": 119, "alphanum_fraction": 0.6602101793, "num_tokens": 1278, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.47643683908572687}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2015 NumScale SAS\n  @copyright 2015 J.T. Lapreste\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_FMA_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_FMA_HPP_INCLUDED\n\n#include <boost/simd/function/multiplies.hpp>\n#include <boost/simd/function/plus.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  BOOST_DISPATCH_OVERLOAD ( fma_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_< bd::unspecified_<A0> >\n                          , bd::scalar_< bd::unspecified_<A0> >\n                          , bd::scalar_< bd::unspecified_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE\n    A0 operator() ( A0 a0, A0 a1, A0 a2) const BOOST_NOEXCEPT\n    {\n      return plus(multiplies(a0, a1), a2);\n    }\n  };\n} } }\n\n#include <boost/simd/arch/common/scalar/function/correct_fma.hpp>\n#include <boost/simd/arch/common/simd/function/correct_fma.hpp>\n\n#endif\n", "meta": {"hexsha": "6a19873265991d9a2ad1f8c101e7d0741a263c92", "size": 1438, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/scalar/function/fma.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/scalar/function/fma.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/fma.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.4418604651, "max_line_length": 100, "alphanum_fraction": 0.5542420028, "num_tokens": 317, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4764368326843802}}
{"text": "// Andrew Naplavkov\n\n#ifndef BARK_DB_SLIPPY_TILE_HPP\n#define BARK_DB_SLIPPY_TILE_HPP\n\n#include <algorithm>\n#include <array>\n#include <bark/geometry/geometry_ops.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/range/algorithm_ext/erase.hpp>\n#include <cmath>\n\nnamespace bark::db::slippy {\n\nconstexpr int Pixels = 256;\n\n/// @see http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames\nstruct tile {\n    int x = 0;\n    int y = 0;\n    int z = 0;\n};\n\nusing tiles = std::vector<tile>;\n\ninline auto split(const tile& tl)\n{\n    std::array<tile, 4> res;\n    for (int i = 0; i < 2; ++i)\n        for (int j = 0; j < 2; ++j)\n            res[i * 2 + j] = {2 * tl.x + i, 2 * tl.y + j, tl.z + 1};\n    return res;\n}\n\ninline double left(const tile& tl)\n{\n    return tl.x / std::pow(2, tl.z) * 360 - 180;\n}\n\ninline double top(const tile& tl)\n{\n    constexpr auto Pi = boost::math::constants::pi<double>();\n    auto n = Pi - 2 * Pi * tl.y / std::pow(2, tl.z);\n    return 180 / Pi * atan((exp(n) - exp(-n)) / 2);\n}\n\ninline geometry::box extent(const tile& tl)\n{\n    return {{left(tl), top({tl.x, tl.y + 1, tl.z})},\n            {left({tl.x + 1, tl.y, tl.z}), top(tl)}};\n}\n\ninline geometry::box pixel(const tile& tl)\n{\n    auto ext = extent(tl);\n    auto center = boost::geometry::return_centroid<geometry::point>(ext);\n    return {center,\n            {center.x() + geometry::width(ext) / Pixels,\n             center.y() + geometry::height(ext) / Pixels}};\n}\n\ntemplate <class Predicate>\nvoid depth_first_search(tiles& tls, const tile& tl, const Predicate& p)\n{\n    if (!p(tl))\n        return;\n    tls.push_back(tl);\n    for (auto& sub_tl : split(tl))\n        depth_first_search(tls, sub_tl, p);\n}\n\ntemplate <class Predicate>\ntiles depth_first_search(const Predicate& p)\n{\n    tiles tls;\n    depth_first_search(tls, {}, p);\n    return tls;\n}\n\ninline tile match(const geometry::box& px, int zmax)\n{\n    using namespace boost::geometry;\n\n    auto px_area = area(px);\n    auto sub_px_area = px_area / 4.;\n\n    auto tiny = [&](const tile& tl) {\n        return tl.z > zmax || area(pixel(tl)) < sub_px_area;\n    };\n    auto filter = [&](const tile& tl) {\n        return intersects(px, extent(tl)) && !tiny(tl);\n    };\n    auto diff = [&](const tile& tl) {\n        return std::fabs(area(pixel(tl)) - px_area);\n    };\n    auto cmp = [&](const tile& lhs, const tile& rhs) {\n        return diff(lhs) < diff(rhs);\n    };\n\n    auto tls = depth_first_search(filter);\n    return tls.empty() ? tile{}\n                       : *std::min_element(tls.begin(), tls.end(), cmp);\n}\n\ninline tiles tile_coverage(const geometry::box& ext, int z)\n{\n    auto filter = [&](const tile& tl) {\n        if (tl.z > z || !boost::geometry::intersects(ext, extent(tl)))\n            return false;\n        if (tl.z < z)\n            return true;\n        geometry::box visible{};\n        boost::geometry::intersection(ext, extent(tl), visible);\n        auto sub_pixel = pixel(split(tl).front());\n        return geometry::width(visible) > geometry::width(sub_pixel) &&\n               geometry::height(visible) > geometry::height(sub_pixel);\n    };\n\n    auto tls = depth_first_search(filter);\n    boost::remove_erase_if(tls, [&](const tile& tl) { return tl.z != z; });\n    return tls;\n}\n\n}  // namespace bark::db::slippy\n\n#endif  // BARK_DB_SLIPPY_TILE_HPP\n", "meta": {"hexsha": "614ccd8ef9fd3798c00886a97c353627a68190cb", "size": 3311, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "db/slippy/detail/tile.hpp", "max_stars_repo_name": "storm-ptr/bark", "max_stars_repo_head_hexsha": "e4cd481183aba72ec6cf996eff3ac144c88b79b6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-11-05T10:27:35.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-02T06:25:53.000Z", "max_issues_repo_path": "db/slippy/detail/tile.hpp", "max_issues_repo_name": "storm-ptr/bark", "max_issues_repo_head_hexsha": "e4cd481183aba72ec6cf996eff3ac144c88b79b6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "db/slippy/detail/tile.hpp", "max_forks_repo_name": "storm-ptr/bark", "max_forks_repo_head_hexsha": "e4cd481183aba72ec6cf996eff3ac144c88b79b6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T18:01:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-07T08:34:04.000Z", "avg_line_length": 26.0708661417, "max_line_length": 75, "alphanum_fraction": 0.5946843854, "num_tokens": 928, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4764368326843802}}
{"text": "/// \\file\n/// Maintainer: Luzian Hug\n///\n\n#include \"background_subtraction.h\"\n\n#include \"Eigen/Core\"\n\n#include <opencv2/core/eigen.hpp>\n#include <opencv2/core/mat.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n\n#include <boost/log/trivial.hpp>\n\nnamespace MouseTrack {\nBackgroundSubtraction::BackgroundSubtraction() {\n  // empty\n}\n\nFrameWindow BackgroundSubtraction::operator()(const FrameWindow &window) const {\n  // Initializing return object\n  FrameWindow output = window;\n  // Cycle through all streams\n  for (size_t i = 0; i < _cage_frame.frames().size(); i++) {\n\n    // Copy the stuff we need from the FrameWindow objects\n    const PictureD &cage_image = _cage_frame.frames()[i].referencePicture;\n    const PictureD &mouse_image = window.frames()[i].referencePicture;\n\n    // Dimensions must match\n    if (!(cage_image.rows() == mouse_image.rows() &&\n          cage_image.cols() == mouse_image.cols())) {\n      // If it fails, return the input (do nothing)\n      BOOST_LOG_TRIVIAL(info)\n          << \"Frame dimensions (\" << mouse_image.rows() << \"x\"\n          << mouse_image.cols()\n          << \") do not match empty cage frame dimensions (\" << cage_image.rows()\n          << \"x\" << cage_image.cols()\n          << \"). Background subtraction cannot be performed.\";\n      return window;\n    }\n\n    // Perform the subtraction\n    PictureD sub = (mouse_image - cage_image).array().abs();\n\n    // Convert to opencv format and from [0,1] to [0,255] format\n    cv::Mat subcv;\n    sub = Eigen::floor(sub.array() * 255);\n    cv::eigen2cv(sub, subcv);\n    subcv.convertTo(subcv, CV_8UC1);\n\n    // Apply Otsu's Method for thresholding\n    cv::Mat maskcv;\n    double thresh_otsu = cv::threshold(subcv, maskcv, 0, 255,\n                                       cv::THRESH_BINARY + cv::THRESH_OTSU);\n    maskcv = subcv > (thresh_otsu * _otsu_factor);\n\n    // Convert back to Eigen\n    Eigen::MatrixXd mask;\n    maskcv = maskcv / 255;\n    cv::cv2eigen(maskcv, mask);\n    // A very low threshold means there's no significant bright\n    // spots, i.e. no mouse => set mask to zeros\n    if (thresh_otsu < 0.01 * 255) {\n      mask.setZero();\n    }\n\n    // Build Frame object...\n    output.frames()[i].normalizedDisparityMap =\n        mask.array() * output.frames()[i].normalizedDisparityMap.array();\n  }\n\n  return output;\n}\n\nconst FrameWindow &BackgroundSubtraction::cage_frame() const {\n  return _cage_frame;\n}\n\nvoid BackgroundSubtraction::cage_frame(FrameWindow &cage_frame) {\n\n  _cage_frame = cage_frame;\n}\n\ndouble BackgroundSubtraction::otsu_factor() const { return _otsu_factor; }\nvoid BackgroundSubtraction::otsu_factor(double otsu_factor) {\n  _otsu_factor = otsu_factor;\n}\n\n} // namespace MouseTrack\n", "meta": {"hexsha": "71fedb634b59d7805cd12f0db8336fbf8b3b3b2e", "size": 2687, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/frame_window_filtering/background_subtraction.cpp", "max_stars_repo_name": "itko/scanbox", "max_stars_repo_head_hexsha": "9a00c11eafb4cc2faa69bfcc76bdf0d8e295dcf3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-09T09:30:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-09T09:30:23.000Z", "max_issues_repo_path": "lib/frame_window_filtering/background_subtraction.cpp", "max_issues_repo_name": "itko/scanbox", "max_issues_repo_head_hexsha": "9a00c11eafb4cc2faa69bfcc76bdf0d8e295dcf3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 23.0, "max_issues_repo_issues_event_min_datetime": "2018-03-19T20:54:52.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-16T12:36:59.000Z", "max_forks_repo_path": "lib/frame_window_filtering/background_subtraction.cpp", "max_forks_repo_name": "itko/scanbox", "max_forks_repo_head_hexsha": "9a00c11eafb4cc2faa69bfcc76bdf0d8e295dcf3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-03-14T20:00:43.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-14T20:00:43.000Z", "avg_line_length": 29.5274725275, "max_line_length": 80, "alphanum_fraction": 0.6594715296, "num_tokens": 691, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577159, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4764368262830333}}
{"text": "#pragma once\n\n#include <Eigen/Core>\n\n#include <pcl/point_cloud.h>\n\n\nclass PointCloudDim2D\n{\npublic:\n    template<typename PointT>\n    static PointCloudDim2D getMinMaxData2D(const pcl::PointCloud<PointT>& kCloud)\n    {\n        PointT minPt, maxPt;\n        pcl::getMinMax3D(kCloud, minPt, maxPt);\n        \n        return PointCloudDim2D(\n            Eigen::Vector2f(minPt.x, minPt.y),\n            Eigen::Vector2f(maxPt.x, maxPt.y)\n        );\n    }\n\n    float getCloudLenX() const\n    {\n        return maxPt.x() - minPt.x();\n    }\n\n    float getCloudLenY() const\n    {\n        return maxPt.y() - minPt.y();\n    }\n\n    const Eigen::Vector2f& getCloudMaxPt() const\n    {\n        return maxPt;\n    }\n\n    const Eigen::Vector2f& getCloudMinPt() const\n    {\n        return minPt;\n    }\n\nprivate:\n    PointCloudDim2D(const Eigen::Vector2f& _minPt, const Eigen::Vector2f& _maxPt)\n      : minPt(_minPt), maxPt(_maxPt)\n    { }\n\n    Eigen::Vector2f minPt, maxPt;\n};\n", "meta": {"hexsha": "d4574e776e9279e0d6a0f8ad56f84dee6857f08e", "size": 953, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/point_cloud_dim_2d.hpp", "max_stars_repo_name": "troiwill/build-lidar-2d-bev-data", "max_stars_repo_head_hexsha": "d351b723e67bd48a720f5583ed8b231a58f50a8e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-05-28T02:43:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-09T11:55:19.000Z", "max_issues_repo_path": "include/point_cloud_dim_2d.hpp", "max_issues_repo_name": "troiwill/build-lidar-2d-bev-data", "max_issues_repo_head_hexsha": "d351b723e67bd48a720f5583ed8b231a58f50a8e", "max_issues_repo_licenses": ["MIT"], "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/point_cloud_dim_2d.hpp", "max_forks_repo_name": "troiwill/build-lidar-2d-bev-data", "max_forks_repo_head_hexsha": "d351b723e67bd48a720f5583ed8b231a58f50a8e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-09T11:55:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-09T11:55:22.000Z", "avg_line_length": 19.06, "max_line_length": 81, "alphanum_fraction": 0.5960125918, "num_tokens": 278, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321964553657, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.47639805700968035}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2013 Kyle Lutz <kyle.r.lutz@gmail.com>\n//\n// Distributed under the Boost Software License, Version 1.0\n// See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt\n//\n// See http://boostorg.github.com/compute for more information.\n//---------------------------------------------------------------------------//\n\n#ifndef BOOST_COMPUTE_ALGORITHM_ACCUMULATE_HPP\n#define BOOST_COMPUTE_ALGORITHM_ACCUMULATE_HPP\n\n#include <boost/preprocessor/seq/for_each.hpp>\n\n#include <boost/compute/system.hpp>\n#include <boost/compute/functional.hpp>\n#include <boost/compute/command_queue.hpp>\n#include <boost/compute/algorithm/reduce.hpp>\n#include <boost/compute/algorithm/detail/serial_accumulate.hpp>\n#include <boost/compute/container/array.hpp>\n#include <boost/compute/container/vector.hpp>\n#include <boost/compute/detail/iterator_range_size.hpp>\n\nnamespace boost {\nnamespace compute {\nnamespace detail {\n\n// Space complexity O(1)\ntemplate<class InputIterator, class T, class BinaryFunction>\ninline T generic_accumulate(InputIterator first,\n                            InputIterator last,\n                            T init,\n                            BinaryFunction function,\n                            command_queue &queue)\n{\n    const context &context = queue.get_context();\n\n    size_t size = iterator_range_size(first, last);\n    if(size == 0){\n        return init;\n    }\n\n    // accumulate on device\n    array<T, 1> device_result(context);\n    detail::serial_accumulate(\n        first, last, device_result.begin(), init, function, queue\n    );\n\n    // copy result to host\n    T result;\n    ::boost::compute::copy_n(device_result.begin(), 1, &result, queue);\n    return result;\n}\n\n// returns true if we can use reduce() instead of accumulate() when\n// accumulate() this is true when the function is commutative (such as\n// addition of integers) and the initial value is the identity value\n// for the operation (zero for addition, one for multiplication).\ntemplate<class T, class F>\ninline bool can_accumulate_with_reduce(T init, F function)\n{\n    (void) init;\n    (void) function;\n\n    return false;\n}\n\n/// \\internal_\n#define BOOST_COMPUTE_DETAIL_DECLARE_CAN_ACCUMULATE_WITH_REDUCE(r, data, type) \\\n    inline bool can_accumulate_with_reduce(type init, plus<type>) \\\n    { \\\n        return init == type(0); \\\n    } \\\n    inline bool can_accumulate_with_reduce(type init, multiplies<type>) \\\n    { \\\n        return init == type(1); \\\n    }\n\nBOOST_PP_SEQ_FOR_EACH(\n    BOOST_COMPUTE_DETAIL_DECLARE_CAN_ACCUMULATE_WITH_REDUCE,\n    _,\n    (char_)(uchar_)(short_)(ushort_)(int_)(uint_)(long_)(ulong_)\n)\n\ntemplate<class T>\ninline bool can_accumulate_with_reduce(T init, min<T>)\n{\n    return init == (std::numeric_limits<T>::max)();\n}\n\ntemplate<class T>\ninline bool can_accumulate_with_reduce(T init, max<T>)\n{\n    return init == (std::numeric_limits<T>::min)();\n}\n\n#undef BOOST_COMPUTE_DETAIL_DECLARE_CAN_ACCUMULATE_WITH_REDUCE\n\ntemplate<class InputIterator, class T, class BinaryFunction>\ninline T dispatch_accumulate(InputIterator first,\n                             InputIterator last,\n                             T init,\n                             BinaryFunction function,\n                             command_queue &queue)\n{\n    size_t size = iterator_range_size(first, last);\n    if(size == 0){\n        return init;\n    }\n\n    if(can_accumulate_with_reduce(init, function)){\n        T result;\n        reduce(first, last, &result, function, queue);\n        return result;\n    }\n    else {\n        return generic_accumulate(first, last, init, function, queue);\n    }\n}\n\n} // end detail namespace\n\n/// Returns the result of applying \\p function to the elements in the\n/// range [\\p first, \\p last) and \\p init.\n///\n/// If no function is specified, \\c plus will be used.\n///\n/// \\param first first element in the input range\n/// \\param last last element in the input range\n/// \\param init initial value\n/// \\param function binary reduction function\n/// \\param queue command queue to perform the operation\n///\n/// \\return the accumulated result value\n///\n/// In specific situations the call to \\c accumulate() can be automatically\n/// optimized to a call to the more efficient \\c reduce() algorithm. This\n/// occurs when the binary reduction function is recognized as associative\n/// (such as the \\c plus<int> function).\n///\n/// Note that because floating-point addition is not associative, calling\n/// \\c accumulate() with \\c plus<float> results in a less efficient serial\n/// reduction algorithm being executed. If a slight loss in precision is\n/// acceptable, the more efficient parallel \\c reduce() algorithm should be\n/// used instead.\n///\n/// For example:\n/// \\code\n/// // with vec = boost::compute::vector<int>\n/// accumulate(vec.begin(), vec.end(), 0, plus<int>());   // fast\n/// reduce(vec.begin(), vec.end(), &result, plus<int>()); // fast\n///\n/// // with vec = boost::compute::vector<float>\n/// accumulate(vec.begin(), vec.end(), 0, plus<float>());   // slow\n/// reduce(vec.begin(), vec.end(), &result, plus<float>()); // fast\n/// \\endcode\n///\n/// Space complexity: \\Omega(1)<br>\n/// Space complexity when optimized to \\c reduce(): \\Omega(n)\n///\n/// \\see reduce()\ntemplate<class InputIterator, class T, class BinaryFunction>\ninline T accumulate(InputIterator first,\n                    InputIterator last,\n                    T init,\n                    BinaryFunction function,\n                    command_queue &queue = system::default_queue())\n{\n    return detail::dispatch_accumulate(first, last, init, function, queue);\n}\n\n/// \\overload\ntemplate<class InputIterator, class T>\ninline T accumulate(InputIterator first,\n                    InputIterator last,\n                    T init,\n                    command_queue &queue = system::default_queue())\n{\n    typedef typename std::iterator_traits<InputIterator>::value_type IT;\n\n    return detail::dispatch_accumulate(first, last, init, plus<IT>(), queue);\n}\n\n} // end compute namespace\n} // end boost namespace\n\n#endif // BOOST_COMPUTE_ALGORITHM_ACCUMULATE_HPP\n", "meta": {"hexsha": "be20bee60eb4db7fe4bf05fdf40d5174462f66b6", "size": 6145, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/compute/algorithm/accumulate.hpp", "max_stars_repo_name": "sznaider/compute", "max_stars_repo_head_hexsha": "d36ef02b7860b9bcf5ea4911b77f1aa77b5f4059", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 918.0, "max_stars_repo_stars_event_min_datetime": "2016-12-22T02:53:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T06:21:35.000Z", "max_issues_repo_path": "include/boost/compute/algorithm/accumulate.hpp", "max_issues_repo_name": "sznaider/compute", "max_issues_repo_head_hexsha": "d36ef02b7860b9bcf5ea4911b77f1aa77b5f4059", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 203.0, "max_issues_repo_issues_event_min_datetime": "2016-12-27T12:09:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T20:46:55.000Z", "max_forks_repo_path": "include/boost/compute/algorithm/accumulate.hpp", "max_forks_repo_name": "sznaider/compute", "max_forks_repo_head_hexsha": "d36ef02b7860b9bcf5ea4911b77f1aa77b5f4059", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 122.0, "max_forks_repo_forks_event_min_datetime": "2016-12-22T17:38:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-22T14:25:49.000Z", "avg_line_length": 32.5132275132, "max_line_length": 80, "alphanum_fraction": 0.653539463, "num_tokens": 1341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.4763980535395203}}
{"text": "#include \"functions/functions.h\"\n#include \"functions/RealVector.h\"\n#include <math.h>\n#include <time.h>\n#include <iostream>\n#include <sstream>\n#include <iomanip>\n#include <string.h>\n#include <boost/lexical_cast.hpp>\n\n#ifndef M_PI\n#define M_PI 3.14159265\n#endif\n\n#define MAX_BUFFER_SIZE_FUNCTIONS__  655536\n\nusing namespace std;\n\nnamespace functions{\n\nstd::string tabulate(const string& st, int n_tabs)\n{\n  ostringstream os;\n  \n  for (int i = 0; i < n_tabs;i ++) {\n    os << \"\\t\";\n  }\n  \n  os << st;\n  \n  return os.str();\n}\n\ndouble reduceAngle(double phi)\n{\n  while ( fabs(phi) > M_PI) {\n    phi = phi + ( phi > 0.0 ? -1.0 : 1.0 ) * 2.0 * M_PI;\n  }\n  \n  return phi;\n}\n\nvoid rotateVector(std::vector<double> &v, double angle) {\n  if (v.size() >= 2) {\n    double x, y;\n    \n    cout << \"Angle: \" << angle << endl;\n    \n    x = v.at(0)*cos(angle) - v.at(1)*sin(angle);\n    y = v.at(0)*sin(angle) + v.at(1)*cos(angle);\n    v[0] = x;\n    v[1] = y;\n  }\n}\n\nvoid rotateVector(std::vector<double> &v, const DegMinSec &angle) {\n  rotateVector(v, angle.toRadians());\n}\n\t\nstd::vector<double>  getVectorFromFile(const std::string &fileName) throw (){\n\n\tvector <double> ret;\n\t\n\tifstream filestr;\n\ttry{\n\t\tfilestr.open( fileName.c_str() );\n\t\tfilestr.exceptions(ifstream::failbit | ifstream::badbit);\n\t\tret = getVectorFromStream(filestr);\n\t}\n\tcatch (...){\n// \t\tcout << \"Error flags: \" << filestr.rdstate() << endl;\n// \t\tret.clear();\n\t}\n\t\n\treturn ret;\n}\n\nstd::vector< double > getVectorFromStream(istream& is)\n{\n  vector<double> ret;\n  try {\n    while ( is.good() && !is.eof() ){\n      double au;\n      if (is >> au) {\n\tret.push_back(au);\n      }\n    }\n  }catch (exception &e) {\n      \n  }\n  return ret;\n}\n\nstd::vector< double > getVectorFromString(const string& s)\n{\n  vector<double> ret;\n  string ss = removeSpaces(s);\n  char *copy_ = new char[ss.length() + 1];\n  strcpy(copy_, ss.c_str());\n  char *tok = copy_;\n  tok = strtok(tok, \" \\n\\t\\r\");\n  try {\n    while ( tok != NULL && strlen(tok) > 0 ) {\n      ret.push_back(boost::lexical_cast<double>(tok));\n      tok = strtok(NULL, \" \\n\\t\\r\");\n    }  \n  } catch (exception &e) {\n    ret.clear();\n  }\n  delete[] copy_;\n  return ret;\n}\n\nbool getMatrixFromFile(const std::string &fileName, int width, std::vector<std::vector<double> > &v) throw (){\n\tbool ret = true;\n\t\n\tif (v.size() > 0) \n\t  v.clear();\n\t\n\tifstream filestr;\n\ttry{\n\t\t\n\t\tdouble aux;\n\t\tint i;\n\t\tfilestr.open( fileName.c_str() );\n\t\tfilestr.exceptions(ifstream::failbit | ifstream::badbit);\n\t\tchar buff[MAX_BUFFER_SIZE_FUNCTIONS__];\n\t\tfilestr.getline(buff, MAX_BUFFER_SIZE_FUNCTIONS__ - 1); // Discard the first line\n\t\twhile ( filestr.good() ){\n\t\t\tvector<double> v_aux;\n\t\t\t\n\t\t\tbool valid = false;\n\t\t\t\n\t\t\tfor (i = 0; i < width && filestr.good(); i++) {\n\t\t\t  filestr >> aux;\n\t\t\t  v_aux.push_back(aux);\n\t\t\t\tif (aux != 0.0) {\n\t\t\t\t\tvalid = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif (i == width && i > 0) {\n\t\t\t  if (valid) {\n\t\t\t    // Discard the zero vectors\n\t\t\t    v.push_back(v_aux);\n\t\t\t  }\n\t\t\t} else {\n\t\t\t  ret = false;\n\t\t\t}\n\t\t}\n\t}\n\tcatch (...){\n\t\tcout << \"Error flags: \" << filestr.rdstate() << endl;\n\t\tif  (!filestr.eof()){\n\t\t\tthrow;\n\t\t}\n\t}\n\t\n\treturn ret;\n}\n\nbool getMatrixFromFile(const std::string &fileName, std::vector<std::vector<double> > &v, bool discard_first) throw (){\n\tbool ret = true;\n\t\n\tif (v.size() > 0) \n\t  v.clear();\n\t\n\tifstream filestr;\n\tchar *buff = new char[MAX_BUFFER_SIZE_FUNCTIONS__ + 1];\n\ttry{\n\t\t\n\t\tfilestr.open( fileName.c_str() );\n\t\t\n\t\tif (filestr.is_open()) {\n// \t\t  filestr.exceptions(ifstream::failbit | ifstream::badbit);\n\t\t  if (discard_first) {\n\t\t\t  filestr.getline(buff, MAX_BUFFER_SIZE_FUNCTIONS__ - 1); // Discard the first line\n\t\t  }\n\t\t  while ( !filestr.eof() && filestr.good() ){\n\t\t\t  vector<double> v_aux;\n\t\t\t  filestr.getline(buff, MAX_BUFFER_SIZE_FUNCTIONS__ - 1); // Get the current line\n\t\t\t  if (strlen(buff) > 0) {\n\t\t\t    string s(buff);\n\t\t\t    v_aux = getVectorFromString(s);\n\t\t\t    if (v_aux.size() > 0) {\n\t\t\t\t  v.push_back(v_aux);\n\t\t\t    }\n\t\t\t  }\n\t\t  }\n\t\t  filestr.close();\n\t\t} else {\n\t\t  ret = false;\n\t\t}\n\t}\n\tcatch (exception &e){\n\t\tcerr << \"Error flags: \" << filestr.rdstate() << endl;\n\t\tcerr << \"Exception catched while loading file \" << fileName << \" from disk. Content: \" << e.what() << endl;\n\t\tif  (!filestr.eof()){\n\t\t  delete buff;\n\t\t  buff = NULL;\n\t\t\tthrow e;\n\t\t}\n\t\tfilestr.close();\n\t}\n\tdelete[] buff;\n\t\n\treturn ret;\n}\n\n\nstd::string showTime(struct timeval t1, struct timeval t2){\n\tlong usecs = (t2.tv_sec -t1.tv_sec)*1000.0 + (t2.tv_usec -t1.tv_usec)/1000.0;\n\tstd::ostringstream os;\n\tos <<  \": \"<<  usecs << \"ms\" << endl;\t\n\t\n\treturn os.str();\n}\n\nfloat calculateLapseTime(const struct timeval &t1, const struct timeval &t2) {\n\treturn (t2.tv_sec - t1.tv_sec) + (t2.tv_usec - t1.tv_usec)/1e6;\n}\n\t\nstring numberToString(int number, int anchor) {\n\tostringstream oss;\n\t\n\toss.str(\"\");\n  oss.fill('0');\n  oss.width(anchor);\n  oss << right << number; \n  return oss.str();\n}\n\nstring numberToString(double data, int precision) {\n  ostringstream oss;\n  oss << fixed << setprecision(precision) << data;\n  return oss.str();\n}\n\nstring printMatrix(const std::vector< std::vector< double > >& mat, const std::string &sep)\n{\n\tostringstream os;\n\t\n\tfor (unsigned int row = 0; row < mat.size(); row++) {\n\t\tos << printVector(mat[row]) << sep << endl; \n\t}\n\t\n\treturn os.str();\n}\n\nstring printMatrix(const std::vector< RealVector >& mat, const std::string &sep)\n{\n\tostringstream os;\n\t\n\tfor (unsigned int row = 0; row < mat.size(); row++) {\n\t\tos << printVector(mat[row]) << sep << endl; \n\t}\n\t\n\treturn os.str();\n}\n\nstring matrixToMatlabString(const std::string& name, const std::vector< std::vector< double > >& mat)\n{\n\tostringstream os;\n\t\n\tos << name << \" = [\" << printMatrix(mat, \";\") << \"];\" << endl;\n\t\n\treturn os.str();\n}\n\nstring matrixToMatlabString(const std::string& name, const std::vector< functions::RealVector>& mat)\n{\n\tostringstream os;\n\t\n\tos << name << \" = [\" << printMatrix(mat, \";\") << \"];\" << endl;\n\t\n\treturn os.str();\n}\n\nstring removeSpaces(const std::string &st)\n{\n  string ret;\n  if (st.size() == 0) {\n    return st;\n  }\n  unsigned int first, last;\n  for (first = 0; first < st.length() && (st.at(first)==' ' || st.at(first)=='\\r' || st.at(first)=='\\t') ; first++) {\n  }\n  for (last = st.length() ; last >= 1 && (st.at(last - 1)==' ' || st.at(last - 1)=='\\r' || st.at(last - 1)=='\\t') ; last--) {\n  }\n  if (first >= 0 && first < st.length() && last >= 0 && last <= st.length() && first < last) {\n    string ret_2(st, first, last);\n    ret = ret_2;\n  }\n  \n  return ret;\n}\n\nbool writeStringToFile(const string& filename, const std::string &text)\n{\n  bool ret_val = true;\n  \n  ofstream ofs;\n  \n  ofs.open(filename.c_str());\n  if (ofs.is_open()) {\n    ofs << text;\n  } else {\n    ret_val = false;\n  }\n  ofs.close();\n  \n  return ret_val;\n}\n\ndouble pathLength(const vector< vector< double > >& path)\n{\n  double length = 0.0;\n  \n  for (unsigned int i = 0; i < path.size() - 1 && path.size() > 1; i++) {\n    length += distance_(path[i], path[i + 1]);\n  }\n  \n  return length;\n}\n\ndouble distance_(const std::vector<double> &v1, const std::vector<double> &v2)\n{\n  unsigned int length = minimum(v1.size(), v2.size());\n  double distance = 0.0;\n  \n  for (unsigned int i = 0; i < length; i++) {\n    distance += pow(v1.at(i) - v2.at(i), 2.0);\n  }\n  \n  return sqrt(distance);\n}\n\nstring loadStringFile(const string& filename)\n{\n  string ret;\n  \n  ifstream filestr;\n  char *buff = new char[MAX_BUFFER_SIZE_FUNCTIONS__ + 1];\n  try {\n    filestr.open( filename.c_str() );\n    if (filestr.is_open()) {\n      filestr.exceptions(ifstream::failbit | ifstream::badbit);\n      while ( !filestr.eof() && filestr.good() ) {\n\tfilestr.getline(buff, MAX_BUFFER_SIZE_FUNCTIONS__ - 1); // Get the current line\n\tstring s(buff);\n\ts.append(\"\\n\");\n\tif (s.size() > 0) {\n\t  ret.append(s);\n\t}\n      }\n      filestr.close();\n    }\n  }\n  catch (exception &e){\n    cerr << \"Error flags: \" << filestr.rdstate() << endl;\n    cerr << \"Exception catched while loading file \" << filename << \" from disk. Content: \" << e.what() << endl;\n    if  (!filestr.eof()){\n      delete[] buff;\n      buff = NULL;\n      throw e;\n    }\n    filestr.close();\n  }\n  delete[] buff;\n  \n  return ret;\n}\n\n\n} // End of namespace functions\n", "meta": {"hexsha": "f4b2a07ba33273ab8d477d38f7316f74e3c3c7d3", "size": 8188, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/functions.cpp", "max_stars_repo_name": "robotics-upo/functions", "max_stars_repo_head_hexsha": "2cfcd720fc71e195569a60877aa8f0e4345eb31a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/functions.cpp", "max_issues_repo_name": "robotics-upo/functions", "max_issues_repo_head_hexsha": "2cfcd720fc71e195569a60877aa8f0e4345eb31a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/functions.cpp", "max_forks_repo_name": "robotics-upo/functions", "max_forks_repo_head_hexsha": "2cfcd720fc71e195569a60877aa8f0e4345eb31a", "max_forks_repo_licenses": ["BSD-3-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.7765957447, "max_line_length": 125, "alphanum_fraction": 0.5928187592, "num_tokens": 2430, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.4763980488383589}}
{"text": "// \n// Implements iLQR (on a traditional chain) for nonlinear dynamics and cost.\n//\n// Arun Venkatraman (arunvenk@cs.cmu.edu)\n// December 2016\n//\n\n#pragma once\n\n\n#include <templated/taylor_expansion.hh>\n#include <utils/debug_utils.hh>\n\n#include <Eigen/Dense>\n\n#include <functional>\n#include <vector>\n\nnamespace ilqr\n{\n\n// Defined in templated/taylor_expansion.hh\n//template<int _rows, int _cols>\n//using Matrix = Eigen::Matrix<double, _rows, _cols>;\n//\n//template<int _rows>\n//using Vector = Eigen::Matrix<double, _rows, 1>;\n\ntemplate<int xdim, int udim>\nstruct HindsightBranch\n{\n    using Dynamics = std::function<Vector<xdim>(const Vector<xdim> &x, const Vector<udim> &u)>;\n    using Cost = std::function<double(const Vector<xdim> &x, const Vector<udim> &u, const int t)>;\n    using FinalCost = std::function<double(const Vector<xdim> &x)>;\n\n    HindsightBranch(const Dynamics &dyn, const FinalCost &cost_final, const Cost &cost_regular, const double prob)\n        : dynamics(dyn), final_cost(cost_final), cost(cost_regular), probability(prob)\n    {\n    }\n\n    Dynamics dynamics;\n    FinalCost final_cost;\n    Cost cost;\n\n    double probability = 0;\n\n    // Feedback control gains.\n    std::vector<Matrix<udim, xdim>> Ks;\n    std::vector<Vector<udim>> ks;\n\n    // Linearization points.\n    std::vector<Vector<xdim>> xhat;\n    std::vector<Vector<udim>> uhat;\n};\n\ntemplate<int xdim, int udim>\nclass iLQRHindsightSolver\n{\n    static_assert(xdim > 0, \"State dimension should be greater than 0\");\n    static_assert(udim > 0, \"Control dimension should be greater than 0\");\npublic:\n    using Dynamics = std::function<Vector<xdim>(const Vector<xdim> &x, const Vector<udim> &u)>;\n    using Cost = std::function<double(const Vector<xdim> &x, const Vector<udim> &u, const int t)>;\n    using FinalCost = std::function<double(const Vector<xdim> &x)>;\n\n    iLQRHindsightSolver(const std::vector<HindsightBranch<xdim,udim>> &branches);\n\n    // Computes the control at timestep 0 using K0_, k0_ that is\n    // shared across all branches.\n    inline Vector<udim> compute_first_control(const Vector<xdim> &x0) const;\n\n    // Computes the control at timestep t at xt.\n    // :param alpha - Backtracking line search parameter. \n    //      Setting to 1 gives regular forward pass.\n    inline Vector<udim> compute_control_stepsize(const int branch_num, const Vector<xdim> &xt, const int t, const double alpha) const;\n\n    // :param alpha - Backtracking line search parameter. \n    //      Setting to 1 gives regular forward pass.\n    inline double forward_pass(const int branch_num,\n            const Vector<xdim> x_init, \n            std::vector<Vector<xdim>> &states, std::vector<Vector<udim>> &controls, \n            const double alpha ) const;\n\n\n    // :param x_init - Initial state from which to start the system from.\n    // :param u_nominal - Initial control used for the whole sequence during \n    //      the first forward pass.\n    // :param mu - Levenberg-Marquardt parameter for damping the least-squares. \n    //      Setting it to 0 gets the default behavior. The damping makes the \n    //      state-space steps smaller over iterations. \n    inline void solve(const int T, const Vector<xdim> &x_init, \n            const Vector<udim> u_nominal, const double mu, \n            const int max_iters = 1000, bool verbose = false, \n            const double cost_convg_ratio = 1e-4, const double start_alpha = 1.0,\n            const bool warm_start = false, const int t_offset = 0);\n\n    // Returns how many timesteps we have computed control policies for.\n    inline int timesteps() const;\n\n    // Set the probability of a branch. Allows it to be done in place so  \n    // warm start solving can be used.\n    inline void set_branch_probability(const int branch_num, const double probability);\n\nprivate:\n    std::vector<HindsightBranch<xdim,udim>> branches_;\n\n    // Feedback control gains.\n    Matrix<udim, xdim> K0_; \n    Vector<udim> k0_; \n\n    // Linearization points for the first timestep.\n    Vector<xdim> xhat0_ = Vector<xdim>::Zero();\n    Vector<udim> uhat0_ = Vector<udim>::Zero();\n\n    // Performs one timestep of the bellman backup.\n    // :param t - passed to the cost runction\n    // :param mu - Levenberg-Marquardt parameter\n    inline void bellman_backup(const int branch_num, const int t, \n        const double mu, \n        const Matrix<xdim,xdim> &Vt1, const Matrix<1,xdim> &Gt1, \n        Matrix<xdim,xdim> &Vt, Matrix<1,xdim> &Gt);\n\n    inline double total_branch_probability();\n\n};\n\n} // namespace lqr\n\n#include <templated/iLQR_hindsight_impl.hh>\n\n", "meta": {"hexsha": "36b1b59d6da72540f1c93719fcc0d13cffd3614d", "size": 4556, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/templated/iLQR_hindsight.hh", "max_stars_repo_name": "LAIRLAB/qr_trees", "max_stars_repo_head_hexsha": "66eb7310daa1d9978158198a508d02bf2128a377", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-16T08:42:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-16T08:42:33.000Z", "max_issues_repo_path": "src/templated/iLQR_hindsight.hh", "max_issues_repo_name": "LAIRLAB/qr_trees", "max_issues_repo_head_hexsha": "66eb7310daa1d9978158198a508d02bf2128a377", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/templated/iLQR_hindsight.hh", "max_forks_repo_name": "LAIRLAB/qr_trees", "max_forks_repo_head_hexsha": "66eb7310daa1d9978158198a508d02bf2128a377", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-07-10T03:25:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-22T15:58:44.000Z", "avg_line_length": 34.7786259542, "max_line_length": 134, "alphanum_fraction": 0.6870061457, "num_tokens": 1212, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.47639804475269815}}
{"text": "// Copyright 2015-2018 Hans Dembinski\n//\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n//[ guide_histogram_streaming\n\n#include <boost/histogram.hpp>\n#include <boost/histogram/ostream.hpp>\n#include <cassert>\n#include <iostream>\n#include <sstream>\n#include <string>\n\nint main() {\n  using namespace boost::histogram;\n\n  std::ostringstream os;\n\n  auto h1 = make_histogram(axis::regular<>(5, -1.0, 1.0, \"axis 1\"));\n  h1.at(0) = 2;\n  h1.at(1) = 4;\n  h1.at(2) = 3;\n  h1.at(4) = 1;\n\n  // 1D histograms are rendered as an ASCII drawing\n  os << h1;\n\n  auto h2 = make_histogram(axis::regular<>(2, -1.0, 1.0, \"axis 1\"),\n                           axis::category<std::string>({\"red\", \"blue\"}, \"axis 2\"));\n\n  // higher dimensional histograms just have their cell counts listed\n  os << h2;\n\n  std::cout << os.str() << std::endl;\n\n  assert(\n      os.str() ==\n      \"histogram(regular(5, -1, 1, metadata=\\\"axis 1\\\", options=underflow | overflow))\\n\"\n      \"               +-------------------------------------------------------------+\\n\"\n      \"[-inf,   -1) 0 |                                                             |\\n\"\n      \"[  -1, -0.6) 2 |==============================                               |\\n\"\n      \"[-0.6, -0.2) 4 |============================================================ |\\n\"\n      \"[-0.2,  0.2) 3 |=============================================                |\\n\"\n      \"[ 0.2,  0.6) 0 |                                                             |\\n\"\n      \"[ 0.6,    1) 1 |===============                                              |\\n\"\n      \"[   1,  inf) 0 |                                                             |\\n\"\n      \"               +-------------------------------------------------------------+\\n\"\n      \"histogram(\\n\"\n      \"  regular(2, -1, 1, metadata=\\\"axis 1\\\", options=underflow | overflow)\\n\"\n      \"  category(\\\"red\\\", \\\"blue\\\", metadata=\\\"axis 2\\\", options=overflow)\\n\"\n      \"  (-1 0): 0 ( 0 0): 0 ( 1 0): 0 ( 2 0): 0 (-1 1): 0 ( 0 1): 0\\n\"\n      \"  ( 1 1): 0 ( 2 1): 0 (-1 2): 0 ( 0 2): 0 ( 1 2): 0 ( 2 2): 0\\n\"\n      \")\");\n}\n\n//]\n", "meta": {"hexsha": "52bf2b9d4f29ae1f95bbd270efc953e9e4b5c955", "size": 2189, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/histogram/examples/guide_histogram_streaming.cpp", "max_stars_repo_name": "cpp-pm/boost", "max_stars_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 109.0, "max_stars_repo_stars_event_min_datetime": "2016-05-25T12:14:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-11T03:17:31.000Z", "max_issues_repo_path": "libs/histogram/examples/guide_histogram_streaming.cpp", "max_issues_repo_name": "cpp-pm/boost", "max_issues_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 186.0, "max_issues_repo_issues_event_min_datetime": "2016-05-05T14:01:09.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-20T22:38:43.000Z", "max_forks_repo_path": "libs/histogram/examples/guide_histogram_streaming.cpp", "max_forks_repo_name": "cpp-pm/boost", "max_forks_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2016-05-05T15:48:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-10T03:16:44.000Z", "avg_line_length": 37.1016949153, "max_line_length": 89, "alphanum_fraction": 0.387391503, "num_tokens": 636, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321720225278, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.47639803596587604}}
{"text": "#include <iostream>\n#include <cstdlib>\n#include <cstring>\n#include <helib/FHE.h>\n#include <NTL/ZZ.h>\n#include <NTL/ZZX.h>\n#include <map>\n#include <string>\n#include <ctime>\n#include <chrono>\n//#include <NTL/lzz_pXFactoring.h>\n\n#include <helib/EncryptedArray.h>\n#include <fstream>\n#include <sstream>\n#include <sys/time.h>\n\n#include \"mc_driver.hpp\"\nNTL_CLIENT\n\nusing namespace MC;\n\nint main( const int argc, const char **argv )\n{\n    /** check for the right # of arguments **/\n    if( argc == 3 )\n    {\n        MC::MC_Driver driver;\n\n        /** example for piping input from terminal, i.e., using cat / \n          if( std::strncmp( argv[ 1 ], \"-o\", 2 ) == 0 )\n          {\n          driver.parse( std::cin );\n          }\n         * simple help menu *\n         else if( std::strncmp( argv[ 1 ], \"-h\", 2 ) == 0 )\n         {\n         std::cout << \"use -o for pipe to std::cin\\n\";\n         std::cout << \"just give a filename to count from a file\\n\";\n         std::cout << \"use -h to get this menu\\n\";\n         return( EXIT_SUCCESS );\n         }\n         * example reading input from a file *\n         else\n         {\n\n         * assume file, prod code, use stat to check **/\n        driver.parse( argv[1] );\n        vector<string> inputlist = driver.inputlist;\n        vector<string> outputlist = driver.outputlist;\n        vector<tuple<string, MC::Bexp*>> eqnlist = driver.eqnlist;\n        \n        \n        // init HElib argument\n        long m = 0, p = 2, r = 1;\n        long depth = atoi(argv[2]);\n        long L = depth * 30; //Level\n        long c = 2;\n        long w = 64;\n        long d = 1;\n        long security = 128;\n        long s = 0;//slot\n        ZZX G;\n        \n        m = FindM(security, L, c, p, d, s, 0);\n\tcout << \"selected m : \" << m << endl;\n\tcerr << m << \", \" ;\n        FHEcontext context(m, p, r);\n        buildModChain(context, L, c);\n        FHESecKey sk(context);\n        const FHEPubKey& pk = sk;\n        \n        G = context.alMod.getFactorsOverZZ()[0];\n\n        sk.GenSecKey(w);\n\n        addSome1DMatrices(sk);\n        cout << \"generated Key : \" << endl;\n\n        \n\n        //encrypt inputlist, make memory\n        map<string, Ctxt> memory;\n\n        for(vector<string>::size_type i = 0; i < inputlist.size(); i++){\n            Ctxt tmp(pk);\n            int plaintext = 0;\n            //plaintext modification\n            if(i == 3 || i ==11)\n                plaintext=1;\n            cout << \"input : \" << inputlist[i] << \" : \" << plaintext << endl;\n            pk.Encrypt(tmp, to_ZZX(plaintext));\n            memory.insert( make_pair(inputlist[i], tmp) );\n        }\n        Ctxt true_ctxt(pk);\n        pk.Encrypt(true_ctxt, to_ZZX(1));\n        memory.insert( make_pair(\"true\", true_ctxt) );\n\n        Ctxt false_ctxt(pk);\n        pk.Encrypt(false_ctxt, to_ZZX(0));\n        memory.insert( make_pair(\"false\", false_ctxt) );\n         \n        /* for(auto i = memory.begin(); i!= memory.end(); i++){\n            ZZX memory_res;\n            sk.Decrypt(memory_res, i->second);\n            cout << i->first << \" : \" << memory_res[0] << endl;\n        }*/\n\t//int start_time = time(0);\n        std::chrono::system_clock::time_point StartTime = std::chrono::system_clock::now();\n\n        for(auto i = 0 ; i < eqnlist.size(); i++){\n            string lv = get<0>(eqnlist[i]);\n            Bexp* bexp = get<1>(eqnlist[i]);\n            auto top_op = bexp->head;\n            int constant = bexp->constant;\n            string var = bexp->var;\n            Bexp* l_child = bexp->left;\n            Bexp* r_child = bexp->right;\n            if(top_op == MC::Bexp::Head::CONST){\n                if(constant == 1){\n                    memory.insert(make_pair(lv, true_ctxt ));\n                }\n                else if(constant == 0){\n                    memory.insert(make_pair(lv, false_ctxt));\n                }\n            }\n            else if(top_op == MC::Bexp::Head::VAR){\n                memory.insert(make_pair(lv, memory.find(var)->second));\n            }\n            else if(top_op == MC::Bexp::Head::AND){\n                auto lchild_op = l_child->head;\n                string lchild_var = l_child->var;\n                int lchild_const = l_child->constant;\n                Ctxt lchild_ctxt(pk);\n                if(lchild_op == MC::Bexp::Head::CONST){\n                    if(lchild_const == 1){\n                        lchild_ctxt = true_ctxt;\n                    }\n                    else{\n                        lchild_ctxt = false_ctxt;\n                    }\n                }\n                else if(lchild_op == MC::Bexp::Head::VAR){\n                    lchild_ctxt = memory.find(lchild_var)->second;\n                }\n\n                auto rchild_op = r_child->head;\n                string rchild_var = r_child->var;\n                int rchild_const = r_child->constant;\n                Ctxt rchild_ctxt(pk);\n                if(rchild_op == MC::Bexp::Head::CONST){\n                    if(rchild_const == 1){\n                        rchild_ctxt = true_ctxt;\n                    }\n                    else{\n                        rchild_ctxt = false_ctxt;\n                    }\n                }\n                else if(rchild_op == MC::Bexp::Head::VAR){\n                    rchild_ctxt = memory.find(rchild_var)->second;\n                }\n\n                /* \n                ZZX lchild_res;\n                ZZX rchild_res;\n                sk.Decrypt(lchild_res, lchild_ctxt);\n                sk.Decrypt(rchild_res, rchild_ctxt);\n                */\n\n                lchild_ctxt *= rchild_ctxt;\n                lchild_ctxt.reLinearize();               \n                \n                //ZZX and_res;\n                //sk.Decrypt(and_res, lchild_ctxt);\n                //cout << lchild_var << \" * \" << rchild_var << \" = \" << lv << endl;\n                //cout << lchild_res[0] << \" * \" << rchild_res[0] << \" = \" << and_res[0] << endl;\n\n\n\n                memory.insert(make_pair(lv, lchild_ctxt));\n                \n            }\n            else if(top_op == MC::Bexp::Head::XOR){\n                auto lchild_op = l_child->head;\n                string lchild_var = l_child->var;\n                int lchild_const = l_child->constant;\n                Ctxt lchild_ctxt(pk);\n                if(lchild_op == MC::Bexp::Head::CONST){\n                    if(lchild_const == 1){\n                        lchild_ctxt = true_ctxt;\n                    }\n                    else{\n                        lchild_ctxt = false_ctxt;\n                    }\n                }\n                else if(lchild_op == MC::Bexp::Head::VAR){\n                    lchild_ctxt = memory.find(lchild_var)->second;\n                }\n\n                auto rchild_op = r_child->head;\n                string rchild_var = r_child->var;\n                int rchild_const = r_child->constant;\n                Ctxt rchild_ctxt(pk);\n                if(rchild_op == MC::Bexp::Head::CONST){\n                    if(rchild_const == 1){\n                        rchild_ctxt = true_ctxt;\n                    }\n                    else{\n                        rchild_ctxt = false_ctxt;\n                    }\n                }\n                else if(rchild_op == MC::Bexp::Head::VAR){\n                    rchild_ctxt = memory.find(rchild_var)->second;\n                }\n\n                \n                /*\n                ZZX lchild_res;\n                ZZX rchild_res;\n                sk.Decrypt(lchild_res, lchild_ctxt);\n                sk.Decrypt(rchild_res, rchild_ctxt);\n                */\n                \n\n                lchild_ctxt += rchild_ctxt;                \n\n                /*\n                ZZX and_res;\n                sk.Decrypt(and_res, lchild_ctxt);\n                cout << lchild_var << \" + \" << rchild_var << \" = \" << lv << endl;\n                cout << lchild_res[0] << \" + \" << rchild_res[0] << \" = \" << and_res[0] << endl;\n                */\n\n                memory.insert(make_pair(lv, lchild_ctxt));\n                \n            }\n            else if(top_op == MC::Bexp::Head::OR){\n                auto lchild_op = l_child->head;\n                string lchild_var = l_child->var;\n                int lchild_const = l_child->constant;\n                Ctxt lchild_ctxt(pk);\n                if(lchild_op == MC::Bexp::Head::CONST){\n                    if(lchild_const == 1){\n                        lchild_ctxt = true_ctxt;\n                    }\n                    else{\n                        lchild_ctxt = false_ctxt;\n                    }\n                }\n                else if(lchild_op == MC::Bexp::Head::VAR){\n                    lchild_ctxt = memory.find(lchild_var)->second;\n                }\n\n                auto rchild_op = r_child->head;\n                string rchild_var = r_child->var;\n                int rchild_const = r_child->constant;\n                Ctxt rchild_ctxt(pk);\n                if(rchild_op == MC::Bexp::Head::CONST){\n                    if(rchild_const == 1){\n                        rchild_ctxt = true_ctxt;\n                    }\n                    else{\n                        rchild_ctxt = false_ctxt;\n                    }\n                }\n                else if(rchild_op == MC::Bexp::Head::VAR){\n                    rchild_ctxt = memory.find(rchild_var)->second;\n                }\n\n                \n                /*\n                ZZX lchild_res;\n                ZZX rchild_res;\n                sk.Decrypt(lchild_res, lchild_ctxt);\n                sk.Decrypt(rchild_res, rchild_ctxt);\n                */\n                \n\n\n                Ctxt tmp_ctxt1 = lchild_ctxt;\n                tmp_ctxt1 += rchild_ctxt;\n                lchild_ctxt *= rchild_ctxt;\n                lchild_ctxt +=tmp_ctxt1;\n                lchild_ctxt.reLinearize();\n\n                \n                /*\n                ZZX and_res;\n                sk.Decrypt(and_res, lchild_ctxt);\n                cout << lchild_var << \" or \" << rchild_var << \" = \" << lv << endl;\n                cout << lchild_res[0] << \" or \" << rchild_res[0] << \" = \" << and_res[0] << endl;\n                */\n\n                memory.insert(make_pair(lv, lchild_ctxt));\n                \n            }\n            else if(top_op == MC::Bexp::Head::NOT){\n                auto rchild_op = r_child->head;\n                string rchild_var = r_child->var;\n                int rchild_const = r_child->constant;\n                Ctxt rchild_ctxt(pk);\n                if(rchild_op == MC::Bexp::Head::CONST){\n                    if(rchild_const == 1){\n                        rchild_ctxt = true_ctxt;\n                    }\n                    else{\n                        rchild_ctxt = false_ctxt;\n                    }\n                }\n                else if(rchild_op == MC::Bexp::Head::VAR){\n                    rchild_ctxt = memory.find(rchild_var)->second;\n                }\n                \n                //ZZX rchild_res;\n                //sk.Decrypt(rchild_res, rchild_ctxt);\n\n                rchild_ctxt += true_ctxt;\n\n                /*\n                ZZX and_res;\n                sk.Decrypt(and_res, rchild_ctxt);\n                cout << \"not \" << rchild_var << \" = \" << lv << endl;\n                cout << \"not \" << rchild_res[0] << \" = \" << and_res[0] << endl;\n                */\n\n                memory.insert(make_pair(lv, rchild_ctxt));\n            }\n            \n\n        }\n        cout << \"circuit evaluation finished\" << endl;\n        for(auto i = 0; i < outputlist.size(); i++){\n            ZZX tmp_res;\n            sk.Decrypt(tmp_res, memory.find(outputlist[i])->second) ;\n            cout << \"output : \" << outputlist[i] << \" : \" << tmp_res[0] << endl;   \n        }\n\n        std::chrono::system_clock::time_point EndTime = std::chrono::system_clock::now();\n        std::chrono::milliseconds mill  = std::chrono::duration_cast<std::chrono::milliseconds>(EndTime - StartTime);\n\n\t//int eval_time = time(0) - start_time;\n\tstring circuit_filename = argv[1];\n\tstring depth_string = argv[2];\n\tcircuit_filename += depth_string;\n\t\n\t\n        cerr << depth_string << \", \" <<  mill.count()  << endl;\n        /*}*/\n        //driver.print( std::cout ) << \"\\n\";\n    }\n    else\n    {\n        /** exit with failure condition **/\n        return ( EXIT_FAILURE );\n    }\n    return( EXIT_SUCCESS );\n}\n", "meta": {"hexsha": "f112eaee8c3ad7c0184a031a3c194061bc0361fb", "size": 12188, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "homomorphic_evaluation/and_time_gen/main.cpp", "max_stars_repo_name": "dklee0501/PLDI_20_242_artifact_publication", "max_stars_repo_head_hexsha": "f2b73df9165c76e8b521d8ebd639d68321e3862b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-14T02:37:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T02:37:58.000Z", "max_issues_repo_path": "homomorphic_evaluation/and_time_gen/main.cpp", "max_issues_repo_name": "dklee0501/Lobster", "max_issues_repo_head_hexsha": "f2b73df9165c76e8b521d8ebd639d68321e3862b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homomorphic_evaluation/and_time_gen/main.cpp", "max_forks_repo_name": "dklee0501/Lobster", "max_forks_repo_head_hexsha": "f2b73df9165c76e8b521d8ebd639d68321e3862b", "max_forks_repo_licenses": ["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.0446927374, "max_line_length": 117, "alphanum_fraction": 0.4417459797, "num_tokens": 2763, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818409, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.47634992976005475}}
{"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_HOMOGRAPHY_HPP\n#define PIC_COMPUTER_VISION_NELDER_MEAD_OPT_HOMOGRAPHY_HPP\n\n#include \"../util/nelder_mead_opt_base.hpp\"\n#include \"../util/std_util.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 NelderMeadOptHomography: public NelderMeadOptBase<float>\n{\npublic:\n    std::vector< Eigen::Vector2f > m0, m1;\n\n    /**\n     * @brief NelderMeadOptHomography\n     * @param m0\n     * @param m1\n     * @param inliers\n     */\n    NelderMeadOptHomography(std::vector< Eigen::Vector2f > &m0,\n                            std::vector< Eigen::Vector2f > &m1,\n                            std::vector< unsigned int > inliers) : NelderMeadOptBase()\n    {\n        filterInliers(m0, inliers, this->m0);\n        filterInliers(m1, inliers, this->m1);\n    }\n\n    /**\n     * @brief Homography\n     * @param H\n     * @param p\n     * @return\n     */\n    Eigen::Vector2f Homography(Eigen::Matrix3f &H, Eigen::Vector2f &p)\n    {\n        Eigen::Vector3f ret = H * Eigen::Vector3f(p[0], p[1], 1.0f);\n\n        return Eigen::Vector2f(ret[0] / ret[2], ret[1] / ret[2]);\n    }\n\n    /**\n     * @brief function\n     * @param x\n     * @param n\n     * @return\n     */\n    float function(float *x, unsigned int n)\n    {\n        float err = 0.0f;\n\n        Eigen::Matrix3f H = getMatrixfFromLinearArray(x, 3, 3);\n        H(2, 2) = 1.0f;\n\n        Eigen::Matrix3f H_inv = H.inverse();\n\n        for(unsigned int i = 0; i < m0.size(); i++) {\n            float dU, dV;\n\n            // | H p0 - p1 | error\n            Eigen::Vector2f p0_H = Homography(H, m0[i]);\n\n            dU = m1[i][0] - p0_H[0];\n            dV = m1[i][1] - p0_H[1];\n\n            err += dU * dU + dV * dV;\n\n            // | H p1 - p0 | error\n            Eigen::Vector2f p1_H = Homography(H_inv, m1[i]);\n\n            dU = m0[i][0] - p1_H[0];\n            dV = m0[i][1] - p1_H[1];\n\n            err += dU * dU + dV * dV;\n\n        }\n\n        return err;\n    }\n\n    /**\n     * @brief run\n     * @param x_start\n     * @param n\n     * @param epsilon\n     * @param x\n     * @return\n     */\n    float *run(float *x_start, unsigned int n, float epsilon = 1e-4f, int max_iterations = 1000, float *x = NULL)\n    {\n        if(n != 8) {\n            return x_start;\n        }\n\n        if(x == NULL) {\n            x = new float[n + 1];\n        }\n\n        x = run_aux(x_start, n, epsilon, max_iterations, x);\n        x[8] = 1.0f;\n\n        return x;\n    }\n};\n\n#endif\n\n}\n\n#endif // PIC_COMPUTER_VISION_NELDER_MEAD_OPT_HOMOGRAPHY_HPP\n", "meta": {"hexsha": "36b2726f5b82df0391fad7a5b4225b00b4fc44ac", "size": 3023, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/computer_vision/nelder_mead_opt_homography.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_homography.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_homography.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": 22.0656934307, "max_line_length": 113, "alphanum_fraction": 0.5583857096, "num_tokens": 960, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.752012562644147, "lm_q2_score": 0.6334102775181399, "lm_q1q2_score": 0.4763324860015567}}
{"text": "#include \"ScannerCorridor.h\"\n\n#include <AdventOfCodeCommon/DisableLibraryWarningsMacros.h>\n\n__BEGIN_LIBRARIES_DISABLE_WARNINGS\n#include <boost/algorithm/string.hpp>\n#include <boost/lexical_cast.hpp>\n__END_LIBRARIES_DISABLE_WARNINGS\n\nnamespace AdventOfCode\n{\nnamespace Year2017\n{\nnamespace Day13\n{\n\nScannerCorridor::ScannerCorridor(RangeToDepthMap rangeToDepthMap)\n    : m_rangeToDepthMap{rangeToDepthMap}\n{\n\n}\n\nunsigned ScannerCorridor::severityOfWholeTrip() const\n{\n    unsigned severity = 0;\n    for (const auto& depthRangePair : m_rangeToDepthMap)\n    {\n        unsigned depth;\n        unsigned range;\n        std::tie(depth, range) = depthRangePair;\n\n        if (isCaught(range, depth))\n        {\n            severity += depth * range;\n        }\n    }\n\n    return severity;\n}\n\nunsigned ScannerCorridor::smallestDelayNotToGetCaught() const\n{\n    unsigned smallestDelay = 0;\n    while (true)\n    {\n        bool isEverCaught = false;\n        for (const auto& depthRangePair : m_rangeToDepthMap)\n        {\n            unsigned depth;\n            unsigned range;\n            std::tie(depth, range) = depthRangePair;\n\n            if (isCaught(range, depth, smallestDelay))\n            {\n                isEverCaught = true;\n                break;\n            }\n        }\n\n        if (!isEverCaught)\n        {\n            break;\n        }\n\n        ++smallestDelay;\n    }\n\n    return smallestDelay;\n}\n\nScannerCorridor ScannerCorridor::fromScannerRangeLines(const std::vector<std::string> scannerRangeLines)\n{\n    RangeToDepthMap rangeToDepthMap;\n    for (const auto& scannerRangeLine : scannerRangeLines)\n    {\n        std::vector<std::string> tokens;\n        boost::split(tokens, scannerRangeLine, boost::is_any_of(\": \"), boost::token_compress_on);\n\n        if (tokens.size() != 2)\n        {\n            throw std::runtime_error(\"Each line needs to have exactly 2 tokens.\");\n        }\n\n        unsigned depth = boost::lexical_cast<unsigned>(tokens[0]);\n        unsigned range = boost::lexical_cast<unsigned>(tokens[1]);\n\n        if (range < 2)\n        {\n            throw std::runtime_error(\"Range less than 2 is invalid.\");\n        }\n\n        bool insertionTookPlace;\n        std::tie(std::ignore, insertionTookPlace) = rangeToDepthMap.insert(std::make_pair(depth, range));\n        if (!insertionTookPlace)\n        {\n            throw std::runtime_error(\"Same depth appears twice in the input lines.\");\n        }\n    }\n\n    return ScannerCorridor{std::move(rangeToDepthMap)};\n}\n\nconstexpr bool ScannerCorridor::isCaught(unsigned range, unsigned depth, unsigned delay)\n{\n    unsigned totalStepsInPath = (2 * (range - 1));\n\n    // Smallest delay value that has the equivalent effect\n    unsigned minEquivalentDelay = delay % totalStepsInPath;\n\n    // Number of steps the scanner has taken since last being at the top\n    unsigned scannerNumStepsFromTop = (depth + minEquivalentDelay) % totalStepsInPath;\n\n    unsigned scannerPos{};\n\n    // Scanner in the first half of its path\n    if (scannerNumStepsFromTop <= range - 1)\n    {\n        scannerPos = scannerNumStepsFromTop;\n    }\n\n    // Scanner in the second half of its path\n    else\n    {\n        // Number of steps the scanner has taken since last being at the bottom\n        unsigned scannerNumStepsFromBottom = scannerNumStepsFromTop - (range - 1);\n\n        scannerPos = (range - 1) - scannerNumStepsFromBottom;\n    }\n\n    return scannerPos == 0;\n}\n\n}\n}\n}\n", "meta": {"hexsha": "371d140b8ea4d3ea381bdc468d10bfa8863a9e97", "size": 3408, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/AdventOfCode2017/Day13-PacketScanners/ScannerCorridor.cpp", "max_stars_repo_name": "dbartok/advent-of-code-cpp", "max_stars_repo_head_hexsha": "c8c2df7a21980f8f3e42128f7bc5df8288f18490", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/AdventOfCode2017/Day13-PacketScanners/ScannerCorridor.cpp", "max_issues_repo_name": "dbartok/advent-of-code-cpp", "max_issues_repo_head_hexsha": "c8c2df7a21980f8f3e42128f7bc5df8288f18490", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/AdventOfCode2017/Day13-PacketScanners/ScannerCorridor.cpp", "max_forks_repo_name": "dbartok/advent-of-code-cpp", "max_forks_repo_head_hexsha": "c8c2df7a21980f8f3e42128f7bc5df8288f18490", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.0588235294, "max_line_length": 105, "alphanum_fraction": 0.6437793427, "num_tokens": 796, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.63341026367784, "lm_q1q2_score": 0.4763324826342443}}
{"text": "#pragma once\n\n#include <boost/optional.hpp>\n#include <crab/domains/term/term_expr.hpp>\n#include <crab/domains/term/term_operators.hpp>\n\n/*\n   Simplifiers for table terms after giving meaning to functors.\n*/\n\nnamespace crab {\nnamespace domains {\nnamespace term {\n\n// Common API to simplifiers\ntemplate <class Num, class Ftor> class Simplifier {\nprotected:\n  using term_table_t = term_table<Num, Ftor>;\n  using term_id_t = typename term_table_t::term_id_t;\n\n  term_table_t &_ttbl;\n\npublic:\n  Simplifier(term_table_t &term_table) : _ttbl(term_table) {}\n\n  virtual ~Simplifier() {}\n\n  virtual void simplify() = 0;\n\n  // This should not modify the term table\n  // FIXME: cannot make const the method without changing\n  // constness of other methods.\n  virtual boost::optional<term_id_t> simplify_term(term_id_t t) = 0;\n};\n\n// Trivial simplifier by giving standard mathematical meaning\n// to arithmetic operators assuming that conmutativity,\n// associativity etc properties hold as expected.\ntemplate <class Num> class NumSimplifier : Simplifier<Num, term_operator_t> {\n  using simplifier_t = Simplifier<Num, term_operator_t>;\n\n  using term_table_t = term_table<Num, term_operator_t>;\n  using term_id_t = typename term_table_t::term_id_t;\n  using term_t = typename term_table_t::term_t;\n\n  // Simplify term f(left,right)\n  boost::optional<term_id_t> simplify_term(term_operator_t f, term_id_t left,\n                                           term_id_t right) {\n    // Only consider these two rules:\n    //   '/'('*'(x,y),x) = y\n    //   '/'('*'(x,y),y) = x\n    switch (f) {\n    case TERM_OP_SDIV:\n    case TERM_OP_UDIV: {\n      term_t *tleft = this->_ttbl.get_term_ptr(left);\n      term_t *tright = this->_ttbl.get_term_ptr(right);\n\n      if ((tleft->kind() == TERM_APP) && term_ftor(tleft) == TERM_OP_MUL) {\n        const std::vector<term_id_t> &args(term_args(tleft));\n        assert(args.size() == 2);\n        term_t *tl = this->_ttbl.get_term_ptr(args[0]);\n        term_t *tr = this->_ttbl.get_term_ptr(args[1]);\n\n        if (tl == tright)\n          return args[1];\n        if (tr == tright)\n          return args[0];\n      }\n    }\n    default:\n      return boost::optional<term_id_t>();\n    }\n  }\n\npublic:\n  NumSimplifier(term_table_t &term_table) : simplifier_t(term_table) {}\n\n  void simplify() {}\n\n  boost::optional<term_id_t> simplify_term(term_id_t t) {\n    if (term_t *tt = this->_ttbl.get_term_ptr(t)) {\n      if (tt->kind() == TERM_APP) {\n        const std::vector<term_id_t> &args(term_args(tt));\n        assert(args.size() == 2);\n        return simplify_term(term_ftor(tt), args[0], args[1]);\n      }\n    }\n    return boost::optional<term_id_t>();\n  }\n};\n\n} // end namespace term\n} // end namespace domains\n} // end namespace crab\n", "meta": {"hexsha": "283b9a27616b1b1d8146f96c6789650fbf8a14a4", "size": 2740, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/crab/domains/term/simplify.hpp", "max_stars_repo_name": "seahorn/crab", "max_stars_repo_head_hexsha": "82e3d9c94a3b112d4db344e34ae9f789b51d0ec0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 152.0, "max_stars_repo_stars_event_min_datetime": "2016-02-28T06:04:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T10:44:56.000Z", "max_issues_repo_path": "include/crab/domains/term/simplify.hpp", "max_issues_repo_name": "seahorn/crab", "max_issues_repo_head_hexsha": "82e3d9c94a3b112d4db344e34ae9f789b51d0ec0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 43.0, "max_issues_repo_issues_event_min_datetime": "2017-07-03T06:25:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T21:09:32.000Z", "max_forks_repo_path": "include/crab/domains/term/simplify.hpp", "max_forks_repo_name": "seahorn/crab", "max_forks_repo_head_hexsha": "82e3d9c94a3b112d4db344e34ae9f789b51d0ec0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 28.0, "max_forks_repo_forks_event_min_datetime": "2015-11-22T15:51:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-30T00:46:57.000Z", "avg_line_length": 28.8421052632, "max_line_length": 77, "alphanum_fraction": 0.6594890511, "num_tokens": 728, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.752012562644147, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.4763324755934774}}
{"text": "//\n// Created by Vlad Argunov on 19/10/2021.\n//\n\n#include \"FileManagement.h\"\n#include <string>\n#include <fstream>\n#include <sstream>\n#include <Eigen/Dense>\n#include <stdlib.h>\n\n\nstd::vector<int> size_of_csv(const std::string& path){\n// The solution is from https://stackoverflow.com/questions/415515/how-can-i-read-and-manipulate-csv-file-data-in-c?noredirect=1&lq=1\n// It is enhanced to compute the rows and columns of csv\n    int rows = 0;\n    int cols = 0;\n\n    std::ifstream  data(path);\n    std::string line;\n    bool compute_cols = 0;\n    while(std::getline(data,line))\n    {\n        if (compute_cols == 0){\n            cols = count(line.begin(), line.end(), ',');\n            compute_cols = 1;\n        }\n\n        rows++;\n    }\n    std::vector<int> v {rows, cols + 1};\n    return v;\n}\n\n\nvoid read_csv_into_matrix(const std::string& path, Eigen::MatrixXd & result ){\n// The solution is from https://stackoverflow.com/questions/415515/how-can-i-read-and-manipulate-csv-file-data-in-c?noredirect=1&lq=1\n// It is enhanced to handle Eigen matrices\n\n    std::ifstream data(path);\n    std::string line;\n\n    std::vector<int> matrix_size = size_of_csv(path);\n    result.resize(matrix_size[0], matrix_size[1]);\n\n    int row = 0;\n    while(std::getline(data,line))\n    {\n\n        std::stringstream  lineStream(line);\n        std::string        cell;\n\n        int col = 0;\n        while(std::getline(lineStream,cell,','))\n        {\n\n            if (row == 0 && col == 0){\n                cell = cell.substr(3);\n\n            }\n\n            double numeric_cell = atof(cell.c_str());\n            result(row, col) = numeric_cell;\n            col++;\n        }\n        row++;\n    }\n\n}\n\nvoid saveData(std::string fileName, Eigen::MatrixXd  matrix)\n{\n    // Code from https://aleksandarhaber.com/eigen-matrix-library-c-tutorial-saving-and-loading-data-in-from-a-csv-file/\n    //https://eigen.tuxfamily.org/dox/structEigen_1_1IOFormat.html\n    const static Eigen::IOFormat CSVFormat(Eigen::FullPrecision, Eigen::DontAlignCols, \", \", \"\\n\");\n\n    std::ofstream file(fileName);\n    if (file.is_open())\n    {\n        file << matrix.format(CSVFormat);\n        file.close();\n    }\n}\n", "meta": {"hexsha": "5aa4e1d801a042508724d702164d60143b9a574e", "size": 2163, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/FileManagement.cpp", "max_stars_repo_name": "vladargunov/QuantKit", "max_stars_repo_head_hexsha": "858f58f6ed6f3ed2b55a618639bcbb82e9ef5bb9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/FileManagement.cpp", "max_issues_repo_name": "vladargunov/QuantKit", "max_issues_repo_head_hexsha": "858f58f6ed6f3ed2b55a618639bcbb82e9ef5bb9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/FileManagement.cpp", "max_forks_repo_name": "vladargunov/QuantKit", "max_forks_repo_head_hexsha": "858f58f6ed6f3ed2b55a618639bcbb82e9ef5bb9", "max_forks_repo_licenses": ["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.75, "max_line_length": 133, "alphanum_fraction": 0.6093388812, "num_tokens": 557, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.626124191181315, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.476261771281852}}
{"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_FUNCTION_STIRLING_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_STIRLING_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-euler\n    Function object implementing stirling capabilities\n\n    Computes stirling formula for the gamma function\n\n    @par Semantic:\n\n    For every parameter of floating type T\n\n    @code\n    T r = stirling(x);\n    @endcode\n\n    Computes \\f$\\Gamma(x) \\approx \\sqrt{2 \\pi} x^{x-\\frac12} e^{-x} ( 1 + \\frac1{x} P(\\frac1{x}))\\f$,\n    where \\f$P\\f$ is a polynomial.\n\n    The formula implementation is usable for x between 33 and 172, according cephes\n\n    @see gamma\n\n  **/\n  const boost::dispatch::functor<tag::stirling_> stirling = {};\n} }\n#endif\n\n#include <boost/simd/function/scalar/stirling.hpp>\n#include <boost/simd/function/simd/stirling.hpp>\n\n#endif\n", "meta": {"hexsha": "734fd2424b1d58c43b6ea0a30c5453b276ca1b4b", "size": 1268, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/stirling.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/function/stirling.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/function/stirling.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": 25.36, "max_line_length": 101, "alphanum_fraction": 0.596214511, "num_tokens": 295, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.6261241842048092, "lm_q1q2_score": 0.47626176937242276}}
{"text": "// Copyright Louis Dionne 2013-2017\r\n// Distributed under the Boost Software License, Version 1.0.\r\n// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\r\n\r\n#include <boost/hana/assert.hpp>\r\n#include <boost/hana/equal.hpp>\r\n#include <boost/hana/if.hpp>\r\n#include <boost/hana/integral_constant.hpp>\r\n#include <boost/hana/minus.hpp>\r\n#include <boost/hana/optional.hpp>\r\n#include <boost/hana/pair.hpp>\r\n#include <boost/hana/tuple.hpp>\r\n#include <boost/hana/unfold_right.hpp>\r\nnamespace hana = boost::hana;\r\n\r\n\r\nBOOST_HANA_CONSTANT_CHECK(\r\n    hana::unfold_right<hana::tuple_tag>(hana::int_c<10>, [](auto x) {\r\n        return hana::if_(x == hana::int_c<0>,\r\n            hana::nothing,\r\n            hana::just(hana::make_pair(x, x - hana::int_c<1>))\r\n        );\r\n    })\r\n    ==\r\n    hana::tuple_c<int, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1>\r\n);\r\n\r\nint main() { }\r\n", "meta": {"hexsha": "0e78885153f1c863e4ecf8cc291c48947c7be02a", "size": 879, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/hana/example/unfold_right.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": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/hana/example/unfold_right.cpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-04T18:00:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-04T18:00:00.000Z", "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/hana/example/unfold_right.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 30.3103448276, "max_line_length": 82, "alphanum_fraction": 0.6427758817, "num_tokens": 264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.47626176406573917}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2012-2015 NumScale SAS\n  @copyright 2015 J.T.Lapreste\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_FUNCTION_FMA_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_FMA_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n  /*!\n\n    @ingroup group-arithmetic\n    Function object function implementing fma capabilities\n\n    Computes the (fused) multiply add of the three parameters.\n\n    @par semantic:\n    For any given value @c x,  @c y,  @c z of type @c T:\n\n    @code\n    T r = fma(x, y, z);\n    @endcode\n\n    The code is similar to:\n\n    @code\n    T r = x*y+z;\n    @endcode\n\n    @par Note\n    Correct fused multiply/add implies\n\n    - only one rounding\n\n    - no \"intermediate\" overflow\n\n    fma provides this each time it is reasonable\n    in terms of performance (mainly if the system has the hard\n    wired capability).\n\n    If you need \"real\" fma capabilities in all circumstances in your own\n    code you can use correct_fma (although it can be expansive).\n\n    Also :\n\n\n    - fma(x, y, z, nooverflow_) provides a \"only one rounding\" mode but does not care for possible\n    intermediate overflow.\n\n    @par Decorators\n\n    std_ for floating entries\n\n    @par Alias\n\n    @c madd\n\n    @see  correct_fma, fms, fnma, fnms\n  **/\n    const boost::dispatch::functor<tag::fma_> fma = {};\n  }\n} }\n#endif\n\n#include <boost/simd/function/scalar/fma.hpp>\n#include <boost/simd/function/simd/fma.hpp>\n\n#endif\n", "meta": {"hexsha": "9b236049c339e03edeb9cc18edb0ae3818447e27", "size": 1760, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/fma.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/function/fma.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/function/fma.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": 22.8571428571, "max_line_length": 100, "alphanum_fraction": 0.60625, "num_tokens": 429, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.47626176406573917}}
{"text": "//////////////////////////////////\n// This implementation has been //\n// placed in the public domain  //\n// by\t\t\t        //\n//\t\t\t      \t//\n// Petter Solnoer - 1/11/2021 \t//\n//////////////////////////////////\n\n#include \"joye_libert.h\"\n#include \"misc.h\"\n\n#include <iostream>\n//#include <NTL/ZZ_pXFactoring.h>\n//#include <NTL/ZZ_pEX.h>\n//#include <NTL/GF2X.h>\n//#include <NTL/GF2E.h>\n//#include <NTL/GF2XFactoring.h>\n\nvoid jl_key_gen(mpz_t N, mpz_t y, mpz_t k, mpz_t p)\n{\n\t//** Generate primes p, q congruent to 1 mod 2^{k}. **\n\t// Start by initializing a prng.\n\tgmp_randstate_t state;\n\tgmp_randinit_mt(state);\n\n\t// Variable to hold q\n\tmpz_t q;\n\tmpz_init(q);\n\t// Variables to hold test primes\n\tmpz_t p_test, q_test;\n\tmpz_init(p_test);\n\tmpz_init(q_test);\n\t\n\t// Variable to hold pseudo-safeness test divisor\n\t// and pseudo_test assume 32-bit messages.\n\tmpz_t pseudo_safeness_divisor, pseudo_test_p, pseudo_test_q;\n\tmpz_init(pseudo_safeness_divisor);\n\tmpz_init(pseudo_test_p);\n\tmpz_init(pseudo_test_q);\n\t\n\t// Set divisor to 2^{32}\n\tmpz_ui_pow_ui(pseudo_safeness_divisor, 2, 32);\n\n\t// Set p to random value with 1024 bits\n\tmpz_urandomb(p_test, state, 1024);\n\t\n\t// Find the modulus\n\tmpz_t mod;\n\tmpz_init(mod);\n\tmpz_mod(mod, p_test, pseudo_safeness_divisor);\n\n\tmpz_sub(p_test, p_test, mod);\n\tmpz_add_ui(p_test, p_test, 1);\n\n\t// We now have a number that is congruent to 1, as desired.\n\t// Now we must check if it is prime!\n\n\t//mpz_nextprime(p_test, p_test);\n\t// Start by finding appropriate p\n\tmpz_t one;\n\tmpz_init_set_ui(one, 1);\n\n\tstd::cout << \"Find appropriate p\\n\";\n\tmpz_t t;\n\tmpz_init(t);\n\twhile(true)\n\t{\n\t\t// check if prime\n\t\t//mpz_mod(t, p_test, pseudo_safeness_divisor);\n\t\t//gmp_printf(\"%Zd is the congruence.\\n\", t);\n\t\t//if (mpz_congruent_2exp_p(p_test, one, 32))\n\t\tif (mpz_probab_prime_p(p_test, 30))\n\t\t{\n\t\t\t// check for pseudo-safeness\n\t\t\t// condition: p_test - 1 / 2^{k} is also prime\n\t\t\tmpz_t tmp;\n\t\t\tmpz_init(tmp);\n\t\t\tmpz_sub_ui(tmp, p_test, 1);\n\n\t\t\tmpz_divexact(pseudo_test_p, tmp, pseudo_safeness_divisor);\n\t\t\tif (mpz_probab_prime_p(pseudo_test_p, 30))\n\t\t\t{\n\t\t\t\t// We have probably found a good value\n\t\t\t\t// for p\n\t\t\t\tgmp_printf(\"Good value for p: %Zd\\n\", p_test);\n\t\t\t\tmpz_set(p, p_test);\n\t\t\t\tbreak;\n\t\t\t}\t\n\t\t}\n\t\t// Check next prime, probabilistic, chance of composite passing\n\t\t// is extremely small\n\t\tmpz_add(p_test, p_test, pseudo_safeness_divisor);\n\t}\n\n\t// Proceed to find appropriate q\n\tstd::cout << \"Find appropriate q\\n\";\n\tmpz_add(q_test, p_test, pseudo_safeness_divisor);\n\t//mpz_nextprime(q_test, p_test);\n\twhile(true)\n\t{\n\t\t// check if prime\n\t\tif (mpz_probab_prime_p(q_test, 30))\n\t\t{\n\t\t\t// Check for pseudo-safeness\n\t\t\t// condition: q_test - 1 / 2^{k} is also prime\n\t\t\tmpz_t tmp;\n\t\t\tmpz_init(tmp);\n\t\t\tmpz_sub_ui(tmp, q_test, 1);\n\n\t\t\tmpz_cdiv_q(pseudo_test_q, tmp, pseudo_safeness_divisor);\n\t\t\tif (mpz_probab_prime_p(pseudo_test_q, 30))\n\t\t\t{\n\t\t\t\t// We have probably found a good value\n\t\t\t\t// for q\n\t\t\t\tgmp_printf(\"Good value for q: %Zd\\n\", q_test);\n\t\t\t\tmpz_set(q, q_test);\n\t\t\t\tbreak;\n\t\t\t}\t\n\t\t}\n\t\t// Check next prime, probabilistic, chance of composite passing\n\t\t// is extremely small\n\t\tmpz_add(q_test, q_test, pseudo_safeness_divisor);\n\t}\n\n\t// Set N = p*q\n\tmpz_mul(N, p, q);\n\n\t// Find y, using algorithm 2 from Joye-Libert paper\n\t// Assume that the authors mean an arbitrary primitive 2^{th}\n\t// root of unity, i.e., a generator for the cyclic group under multiplication.\n\t\n\t// First select elements from the multiplicative groups Zp* and Zq*\n\t//\n\t// Select a generator for the multiplicative group 2^{k}\n\t// Iterate through primes and divide (?)\n\t//std::set<mpz_t> prime_factors;\n\t//std::set<mpz_t>::iterator it;\n\t// Array to hold prime factors\n\t// and number of prime factors\n\t/* ###################################### CONFERENCE PAPER SHIT #############\n\tmpz_t prime_factors[1000];\n\tint num_prime_factors = 0;\n\n\tmpz_t i, j;\n\tmpz_init(i);\n\tmpz_init(j);\n\n\tmpz_set_ui(i, 2);\n\tmpz_sub_ui(j, pseudo_safeness_divisor, 1);\n\tstd::cout << \"Find prime factors\\n\";\n\twhile(true)\n\t{\n\t\tif(mpz_divisible_p(j, i))\n\t\t{\n\t\t\tgmp_printf(\"%Zd is a prime factor\\n\", i);\n\t\t\tmpz_set(prime_factors[num_prime_factors], i);\n\t\t\tnum_prime_factors++;\n\t\t\tmpz_divexact(j, j, i);\n\t\t\tgmp_printf(\"j is now: %Zd\\n\", j);\n\t\t\tif(!mpz_cmp(j,one))\n\t\t\t{\n\t\t\t\tstd::cout << \"Breaking out\\n\";\n\t\t\t\tbreak;\n\t\t\t}\n\t\t} else {\n\t\t\tmpz_nextprime(i, i);\n\t\t}\n\t}\n\n\tstd::cout << \"Find a generator\\n\";\n\n\n\t// We need to 2^{k} is an extension field with characteristic 2.\n\t// So we need to use polynomials to represent the elements of\n\t// the multiplicative group. We use the NTL library by\n\t// Victor Shoup to do this.\n\t\n\t// We begin by defining the underlying field GF(2):\n\t//NTL::ZZ_p::init(NTL::ZZ(2));\n\t// Declare a polynomial and initialize with degree k=32\n\t\n\tNTL::GF2X irred_polynomial;\n\t\n\n\t\n\tNTL::BuildIrred(irred_polynomial, 32);\n\tNTL::GF2XModulus pol_mod(irred_polynomial);\n\tNTL::GF2E::init(irred_polynomial);\n\t// Declare and initialize a polynomial used\n\t// to search for generator.\n\tNTL::GF2X g_pol;\n\tNTL::GF2X f_pol;\n\tNTL::BuildIrred(f_pol, 30);\n\n\t// Variable to check if generator is found\n\tint generator_found = 0;\n\n\tmpz_t exponent, flag, g;\n\tmpz_init(exponent);\n\tmpz_init(flag);\n\tmpz_init(g);\n\n\tNTL::ZZ ntl_exponent;\n\tNTL::GF2X ntl_flag, g_pol_min;\n\t*/ // #### CONFERENCE PAPER SHIT\n\n\t/*mpz_t flag, exponent, g;\n\tmpz_init(flag);\n\tmpz_init(exponent);\n\tmpz_init_set_ui(g, 1);*/\n\t// j should contain 2^{k} - 1\n\t//\n\t/* #### CONFERENCE PAPER SHIT\n\tmpz_sub_ui(j, pseudo_safeness_divisor, 1);\n\twhile(true)\n\t{\n\t\tgenerator_found = 1;\n\t\t// Pick a value in the set\n\t\t//mpz_add_ui(g, g, 1);\n\t\tg_pol = NTL::GF2X::zero();\n\t\twhile (NTL::IsZero(g_pol))\n\t\t{\n\t\t\t// A primitive polynomial must be\n\t\t\t// irreducible\n\t\t\tNTL::BuildRandomIrred(g_pol, f_pol);\n\t\t}\n\t\tstd::cout << \"pol_mod: \" << irred_polynomial << std::endl;\n\t\tstd::cout << \"g_pol: \" << g_pol << std::endl;\n\n\t\t// Test if value is a generator\n\t\tfor (int i = 0; i < num_prime_factors; ++i)\n\t\t{\n\t\t\tmpz_divexact(exponent, j, prime_factors[i]);\n\t\t\tgmp_printf(\"Exponent being tested: %Zd\\n\", exponent);\n\n\t\t\t// Convert exponent to MPZ::ZZ\n\t\t\tMPZToZZ(&ntl_exponent, exponent);\n\n\t\t\t//mpz_powm(flag, g, exponent, pseudo_safeness_divisor);\n\t\t\tNTL::PowerMod(ntl_flag, g_pol, ntl_exponent, pol_mod);\n\n\t\t\tstd::cout << \"Flag: \" << ntl_flag << std::endl;\n\n\t\t\tunsigned char buffer[4];\n\t\t\tunsigned int integer = 0;\t\t\n\t\t\tMyBytesFromGF2X(buffer, ntl_flag, 4);\n\t\t\tstd::memcpy(&integer, buffer, 4);\n\t\t\t//ZZToMPZ(flag, &ntl_flag);\n\t\t\t\n\t\t\tstd::cout << \"Integer: \" << integer << std::endl;\n\n\t\t\t//gmp_printf(\"Flag: %Zd\\n\", flag);\n\t\t\t//if (!mpz_cmp(flag, one))\n\t\t\tif(integer == 1)\n\t\t\t{\n\t\t\t\t// Not a generator\n\t\t\t\t//gmp_printf(\"%Zd is not a generator!\\n\", g);\n\t\t\t\tgenerator_found = 0;\n\t\t\t\t//exit(1);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif(generator_found)\n\t\t{\n\t\t\tstd::cout << \"g_pol before: \" << g_pol << std::endl;\n\t\t\tunsigned char buffer[4];\n\t\t\tunsigned int g_int = 0;\n\t\t\tMyBytesFromGF2X(buffer, g_pol, 4);\n\t\t\tstd::memcpy(&g_int, buffer, 4);\n\t\t\tmpz_set_ui(g, g_int);\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tgmp_printf(\"The generator found: %Zd\\n\", g);\n\t\n\t// We have found a generator! Now we complete algorithm 2 from Joye-Libert paper\n\t// Pick yp and yq at random from the multiplicative cyclic groups of Zp and Zq\n\tmpz_t yp, yq;\n\tmpz_init(yp);\n\tmpz_init(yq);\n\n\twhile(true)\n\t{\n\t\tmpz_urandomm(yp, state, p);\n\t\tmpz_urandomm(yq, state, q);\n\t\tif ( mpz_cmpabs_ui(yp, 0) && mpz_cmpabs_ui(yq, 0) )\n\t\t{\n\t\t\tbreak;\n\t\t}\n\t}\n\t// Check legendre symbol, update using generator\n\tint legendre_p, legendre_q;\n\n\tgmp_printf(\"yp: %Zd\\n\", yp);\n\tgmp_printf(\"yq: %Zd\\n\", yq);\n\n\tint test_leg;\n\n\tlegendre_p = mpz_legendre(yp, p);\n\tlegendre_q = mpz_legendre(yq, q);\n\tstd::cout << \"Legendre yp/p pre-check: \" << legendre_p << std::endl;\n\tstd::cout << \"Legendre yq/q pre-check: \" << legendre_q << std::endl;\n\n\tstd::cout << \"Check legendre symbols\\n\";\n\t\n\tif (legendre_p == 1)\n\t{\n\t\t// Update yp using generator\n\t\tmpz_mul(yp, yp, g);\n\t\tmpz_mod(yp, yp, p);\n\t\tlegendre_p = mpz_legendre(yp, p);\n\t\tstd::cout << \"Legendre yp/p post-check: \" << legendre_p << std::endl;\n\t}\n\tif (legendre_q == 1)\n\t{\n\t\t// Update yq\n\t\tmpz_mul(yq, yq, g);\n\t\tmpz_mod(yq, yq, q);\n\t\tlegendre_q = mpz_legendre(yq, q);\n\t\tstd::cout << \"Legendre yq/q post-check: \" << legendre_q << std::endl;\n\t}\n\n\tstd::cout << \"Legendre symbols are good\\n\";\n\t// Set y\n\tmpz_t p_inv;\n\tmpz_init(p_inv);\n\t//mpz_invert(p_inv, p, q);\n\tmpz_invert(p_inv, p, N);\n\n\tmpz_sub(y, yq, yp);\n\tmpz_mod(y, y, q);\n\tmpz_mul(y, y, p_inv);\n\t//mpz_mod(y, y, q);\n\tmpz_mul(y, y, p);\n\tmpz_add(y, y, yp);\n\n\tgmp_printf(\"N: %Zd\\n\", N);\n\tgmp_printf(\"The y found: %Zd\\n\", y);\n\n\t// Check if desirable properties for y has been attained:\n\t// Check jacibo first:\n\tint jacobi_n;\n\t*/ // ################### CONFERENCE PAPER SHIT\n\t// Generate a random y in Z_{N}\n\tmpz_set_ui(y, 0);\n\twhile ((mpz_legendre(y, p) != -1) & (mpz_legendre(y,q) != -1))\n\t{\n\t\t// Generate random y in Z_N\n\t\tmpz_urandomm(y, state, N);\n\t}\n\tint jacobi_n = mpz_jacobi(y, N);\n\tint legendre_p = mpz_legendre(y, p);\n\tint legendre_q = mpz_legendre(y, q);\n\n\tstd::cout << \"Jacobi: \" << jacobi_n << std::endl;\n\tstd::cout << \"Legendre y/p final: \" << legendre_p << std::endl;\n\tstd::cout << \"Legendre y/q final: \" << legendre_q << std::endl;\n}\n\nvoid jl_encrypt(mpz_t *c, mpz_t *m, mpz_t *y)\n{\n\n}\n\nvoid jl_decrypt(mpz_t *m, mpz_t *c, mpz_t *p)\n{\n}\n", "meta": {"hexsha": "2e0af3134878c14abe72db342b7c87cc4c291e8e", "size": 9241, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "joye_libert_journal/old_misc/old_joye_libert.cpp", "max_stars_repo_name": "pettsol/LabeledHomomorphicControl", "max_stars_repo_head_hexsha": "052a8f30c9ecb53c3a9d35cfbfefb310ef0772dd", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "joye_libert_journal/old_misc/old_joye_libert.cpp", "max_issues_repo_name": "pettsol/LabeledHomomorphicControl", "max_issues_repo_head_hexsha": "052a8f30c9ecb53c3a9d35cfbfefb310ef0772dd", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "joye_libert_journal/old_misc/old_joye_libert.cpp", "max_forks_repo_name": "pettsol/LabeledHomomorphicControl", "max_forks_repo_head_hexsha": "052a8f30c9ecb53c3a9d35cfbfefb310ef0772dd", "max_forks_repo_licenses": ["Apache-2.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.0433604336, "max_line_length": 81, "alphanum_fraction": 0.646575046, "num_tokens": 3117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.47626176406573906}}
{"text": "/*\n * Software License Agreement (BSD License)\n *\n *  Copyright (c) 2011-2014, Willow Garage, Inc.\n *  Copyright (c) 2014-2015, Open Source Robotics Foundation\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions\n *  are met:\n *\n *   * Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *   * Redistributions in binary form must reproduce the above\n *     copyright notice, this list of conditions and the following\n *     disclaimer in the documentation and/or other materials provided\n *     with the distribution.\n *   * Neither the name of Open Source Robotics Foundation nor the names of its\n *     contributors may be used to endorse or promote products derived\n *     from this software without specific prior written permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n *  \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n *  POSSIBILITY OF SUCH DAMAGE.\n */\n\n/** \\author Jia Pan */\n\n\n#include <hpp/fcl/math/transform.h>\n#include <boost/math/constants/constants.hpp>\n\nnamespace fcl\n{\n\nvoid Quaternion3f::fromRotation(const Matrix3f& R)\n{\n  const int next[3] = {1, 2, 0};\n\n  FCL_REAL trace = R(0, 0) + R(1, 1) + R(2, 2);\n  FCL_REAL root;\n\n  if(trace > 0.0)\n  {\n    // |w| > 1/2, may as well choose w > 1/2\n    root = sqrt(trace + 1.0);  // 2w\n    data[0] = 0.5 * root;\n    root = 0.5 / root;  // 1/(4w)\n    data[1] = (R(2, 1) - R(1, 2))*root;\n    data[2] = (R(0, 2) - R(2, 0))*root;\n    data[3] = (R(1, 0) - R(0, 1))*root;\n  }\n  else\n  {\n    // |w| <= 1/2\n    int i = 0;\n    if(R(1, 1) > R(0, 0))\n    {\n      i = 1;\n    }\n    if(R(2, 2) > R(i, i))\n    {\n      i = 2;\n    }\n    int j = next[i];\n    int k = next[j];\n\n    root = sqrt(R(i, i) - R(j, j) - R(k, k) + 1.0);\n    FCL_REAL* quat[3] = { &data[1], &data[2], &data[3] };\n    *quat[i] = 0.5 * root;\n    root = 0.5 / root;\n    data[0] = (R(k, j) - R(j, k)) * root;\n    *quat[j] = (R(j, i) + R(i, j)) * root;\n    *quat[k] = (R(k, i) + R(i, k)) * root;\n  }\n}\n\nvoid Quaternion3f::toRotation(Matrix3f& R) const\n{\n  assert (.99 < data [0]*data [0] + data [1]*data [1] +\n\t  data [2]*data [2] + data [3]*data [3]);\n  assert (data [0]*data [0] + data [1]*data [1] +\n\t  data [2]*data [2] + data [3]*data [3] < 1.01);\n  FCL_REAL twoX  = 2.0*data[1];\n  FCL_REAL twoY  = 2.0*data[2];\n  FCL_REAL twoZ  = 2.0*data[3];\n  FCL_REAL twoWX = twoX*data[0];\n  FCL_REAL twoWY = twoY*data[0];\n  FCL_REAL twoWZ = twoZ*data[0];\n  FCL_REAL twoXX = twoX*data[1];\n  FCL_REAL twoXY = twoY*data[1];\n  FCL_REAL twoXZ = twoZ*data[1];\n  FCL_REAL twoYY = twoY*data[2];\n  FCL_REAL twoYZ = twoZ*data[2];\n  FCL_REAL twoZZ = twoZ*data[3];\n\n  R.setValue(1.0 - (twoYY + twoZZ), twoXY - twoWZ, twoXZ + twoWY,\n             twoXY + twoWZ, 1.0 - (twoXX + twoZZ), twoYZ - twoWX,\n             twoXZ - twoWY, twoYZ + twoWX, 1.0 - (twoXX + twoYY));\n}\n\n\nvoid Quaternion3f::fromAxes(const Vec3f axis[3])\n{\n  // Algorithm in Ken Shoemake's article in 1987 SIGGRAPH course notes\n  // article \"Quaternion Calculus and Fast Animation\".\n\n  const int next[3] = {1, 2, 0};\n\n  FCL_REAL trace = axis[0][0] + axis[1][1] + axis[2][2];\n  FCL_REAL root;\n\n  if(trace > 0.0)\n  {\n    // |w| > 1/2, may as well choose w > 1/2\n    root = sqrt(trace + 1.0);  // 2w\n    data[0] = 0.5 * root;\n    root = 0.5 / root;  // 1/(4w)\n    data[1] = (axis[1][2] - axis[2][1])*root;\n    data[2] = (axis[2][0] - axis[0][2])*root;\n    data[3] = (axis[0][1] - axis[1][0])*root;\n  }\n  else\n  {\n    // |w| <= 1/2\n    int i = 0;\n    if(axis[1][1] > axis[0][0])\n    {\n      i = 1;\n    }\n    if(axis[2][2] > axis[i][i])\n    {\n      i = 2;\n    }\n    int j = next[i];\n    int k = next[j];\n\n    root = sqrt(axis[i][i] - axis[j][j] - axis[k][k] + 1.0);\n    FCL_REAL* quat[3] = { &data[1], &data[2], &data[3] };\n    *quat[i] = 0.5 * root;\n    root = 0.5 / root;\n    data[0] = (axis[j][k] - axis[k][j]) * root;\n    *quat[j] = (axis[i][j] + axis[j][i]) * root;\n    *quat[k] = (axis[i][k] + axis[k][i]) * root;\n  }\n}\n\nvoid Quaternion3f::toAxes(Vec3f axis[3]) const\n{\n  FCL_REAL twoX  = 2.0*data[1];\n  FCL_REAL twoY  = 2.0*data[2];\n  FCL_REAL twoZ  = 2.0*data[3];\n  FCL_REAL twoWX = twoX*data[0];\n  FCL_REAL twoWY = twoY*data[0];\n  FCL_REAL twoWZ = twoZ*data[0];\n  FCL_REAL twoXX = twoX*data[1];\n  FCL_REAL twoXY = twoY*data[1];\n  FCL_REAL twoXZ = twoZ*data[1];\n  FCL_REAL twoYY = twoY*data[2];\n  FCL_REAL twoYZ = twoZ*data[2];\n  FCL_REAL twoZZ = twoZ*data[3];\n\n  axis[0].setValue(1.0 - (twoYY + twoZZ), twoXY + twoWZ, twoXZ - twoWY);\n  axis[1].setValue(twoXY - twoWZ, 1.0 - (twoXX + twoZZ), twoYZ + twoWX);\n  axis[2].setValue(twoXZ + twoWY, twoYZ - twoWX, 1.0 - (twoXX + twoYY));\n}\n\n\nvoid Quaternion3f::fromAxisAngle(const Vec3f& axis, FCL_REAL angle)\n{\n  FCL_REAL half_angle = 0.5 * angle;\n  FCL_REAL sn = sin((double)half_angle);\n  data[0] = cos((double)half_angle);\n  data[1] = sn * axis[0];\n  data[2] = sn * axis[1];\n  data[3] = sn * axis[2];\n}\n\nvoid Quaternion3f::toAxisAngle(Vec3f& axis, FCL_REAL& angle) const\n{\n  double sqr_length = data[1] * data[1] + data[2] * data[2] + data[3] * data[3];\n  if(sqr_length > 0)\n  {\n    angle = 2.0 * acos((double)data[0]);\n    double inv_length = 1.0 / sqrt(sqr_length);\n    axis[0] = inv_length * data[1];\n    axis[1] = inv_length * data[2];\n    axis[2] = inv_length * data[3];\n  }\n  else\n  {\n    angle = 0;\n    axis[0] = 1;\n    axis[1] = 0;\n    axis[2] = 0;\n  }\n}\n\nFCL_REAL Quaternion3f::dot(const Quaternion3f& other) const\n{\n  return data[0] * other.data[0] + data[1] * other.data[1] + data[2] * other.data[2] + data[3] * other.data[3];\n}\n\nQuaternion3f Quaternion3f::operator + (const Quaternion3f& other) const\n{\n  return Quaternion3f(data[0] + other.data[0], data[1] + other.data[1],\n                      data[2] + other.data[2], data[3] + other.data[3]);\n}\n\nconst Quaternion3f& Quaternion3f::operator += (const Quaternion3f& other)\n{\n  data[0] += other.data[0];\n  data[1] += other.data[1];\n  data[2] += other.data[2];\n  data[3] += other.data[3];\n\n  return *this;\n}\n\nQuaternion3f Quaternion3f::operator - (const Quaternion3f& other) const\n{\n  return Quaternion3f(data[0] - other.data[0], data[1] - other.data[1],\n                      data[2] - other.data[2], data[3] - other.data[3]);\n}\n\nconst Quaternion3f& Quaternion3f::operator -= (const Quaternion3f& other)\n{\n  data[0] -= other.data[0];\n  data[1] -= other.data[1];\n  data[2] -= other.data[2];\n  data[3] -= other.data[3];\n\n  return *this;\n}\n\nQuaternion3f Quaternion3f::operator * (const Quaternion3f& other) const\n{\n  return Quaternion3f(data[0] * other.data[0] - data[1] * other.data[1] - data[2] * other.data[2] - data[3] * other.data[3],\n                      data[0] * other.data[1] + data[1] * other.data[0] + data[2] * other.data[3] - data[3] * other.data[2],\n                      data[0] * other.data[2] - data[1] * other.data[3] + data[2] * other.data[0] + data[3] * other.data[1],\n                      data[0] * other.data[3] + data[1] * other.data[2] - data[2] * other.data[1] + data[3] * other.data[0]);\n}\n\n\nconst Quaternion3f& Quaternion3f::operator *= (const Quaternion3f& other)\n{\n  FCL_REAL a = data[0] * other.data[0] - data[1] * other.data[1] - data[2] * other.data[2] - data[3] * other.data[3];\n  FCL_REAL b = data[0] * other.data[1] + data[1] * other.data[0] + data[2] * other.data[3] - data[3] * other.data[2];\n  FCL_REAL c = data[0] * other.data[2] - data[1] * other.data[3] + data[2] * other.data[0] + data[3] * other.data[1];\n  FCL_REAL d = data[0] * other.data[3] + data[1] * other.data[2] - data[2] * other.data[1] + data[3] * other.data[0];\n\n  data[0] = a;\n  data[1] = b;\n  data[2] = c;\n  data[3] = d;\n  return *this;\n}\n\nQuaternion3f Quaternion3f::operator - () const\n{\n  return Quaternion3f(-data[0], -data[1], -data[2], -data[3]);\n}\n\nQuaternion3f Quaternion3f::operator * (FCL_REAL t) const\n{\n  return Quaternion3f(data[0] * t, data[1] * t, data[2] * t, data[3] * t);\n}\n\nconst Quaternion3f& Quaternion3f::operator *= (FCL_REAL t)\n{\n  data[0] *= t;\n  data[1] *= t;\n  data[2] *= t;\n  data[3] *= t;\n\n  return *this;\n}\n\n\nQuaternion3f& Quaternion3f::conj()\n{\n  data[1] = -data[1];\n  data[2] = -data[2];\n  data[3] = -data[3];\n  return *this;\n}\n\nQuaternion3f& Quaternion3f::inverse()\n{\n  FCL_REAL sqr_length = data[0] * data[0] + data[1] * data[1] + data[2] * data[2] + data[3] * data[3];\n  if(sqr_length > 0)\n  {\n    FCL_REAL inv_length = 1 / std::sqrt(sqr_length);\n    data[0] *= inv_length;\n    data[1] *= (-inv_length);\n    data[2] *= (-inv_length);\n    data[3] *= (-inv_length);\n  }\n  else\n  {\n    data[1] = -data[1];\n    data[2] = -data[2];\n    data[3] = -data[3];\n  }\n\n  return *this;\n}\n\nVec3f Quaternion3f::transform(const Vec3f& v) const\n{\n  Vec3f u(getX(), getY(), getZ());\n  double s = getW();\n  Vec3f vprime = 2*u.dot(v)*u + (s*s - u.dot(u))*v + 2*s*u.cross(v);\n  return vprime;\n}\n\nQuaternion3f conj(const Quaternion3f& q)\n{\n  Quaternion3f r(q);\n  return r.conj();\n}\n\nQuaternion3f inverse(const Quaternion3f& q)\n{\n  Quaternion3f res(q);\n  return res.inverse();\n}\n\nvoid Quaternion3f::fromEuler(FCL_REAL a, FCL_REAL b, FCL_REAL c)\n{\n  Matrix3f R;\n  R.setEulerYPR(a, b, c);\n\n  fromRotation(R);\n}\n\nvoid Quaternion3f::toEuler(FCL_REAL& a, FCL_REAL& b, FCL_REAL& c) const\n{\n  Matrix3f R;\n  toRotation(R);\n  a = atan2(R(1, 0), R(0, 0));\n  b = asin(-R(2, 0));\n  c = atan2(R(2, 1), R(2, 2));\n\n  if(b == boost::math::constants::pi<double>() * 0.5)\n  {\n    if(a > 0)\n      a -= boost::math::constants::pi<double>();\n    else \n      a += boost::math::constants::pi<double>();\n\n    if(c > 0)\n      c -= boost::math::constants::pi<double>();\n    else\n      c += boost::math::constants::pi<double>();\n  }\n}\n\n\nVec3f Quaternion3f::getColumn(std::size_t i) const\n{\n  switch(i)\n  {\n  case 0:\n    return Vec3f(data[0] * data[0] + data[1] * data[1] - data[2] * data[2] - data[3] * data[3],\n                 2 * (- data[0] * data[3] + data[1] * data[2]),\n                 2 * (data[1] * data[3] + data[0] * data[2]));\n  case 1:\n    return Vec3f(2 * (data[1] * data[2] + data[0] * data[3]),\n                 data[0] * data[0] - data[1] * data[1] + data[2] * data[2] - data[3] * data[3],\n                 2 * (data[2] * data[3] - data[0] * data[1]));\n  case 2:\n    return Vec3f(2 * (data[1] * data[3] - data[0] * data[2]),\n                 2 * (data[2] * data[3] + data[0] * data[1]),\n                 data[0] * data[0] - data[1] * data[1] - data[2] * data[2] + data[3] * data[3]);\n  default:\n    return Vec3f();\n  }\n}\n\nVec3f Quaternion3f::getRow(std::size_t i) const\n{\n  switch(i)\n  {\n  case 0:\n    return Vec3f(data[0] * data[0] + data[1] * data[1] - data[2] * data[2] - data[3] * data[3],\n                 2 * (data[0] * data[3] + data[1] * data[2]),\n                 2 * (data[1] * data[3] - data[0] * data[2]));\n  case 1:\n    return Vec3f(2 * (data[1] * data[2] - data[0] * data[3]),\n                 data[0] * data[0] - data[1] * data[1] + data[2] * data[2] - data[3] * data[3],\n                 2 * (data[2] * data[3] + data[0] * data[1]));\n  case 2:\n    return Vec3f(2 * (data[1] * data[3] + data[0] * data[2]),\n                 2 * (data[2] * data[3] - data[0] * data[1]),\n                 data[0] * data[0] - data[1] * data[1] - data[2] * data[2] + data[3] * data[3]);\n  default:\n    return Vec3f();\n  }\n}\n\n\nconst Matrix3f& Transform3f::getRotationInternal() const\n{\n  boost::mutex::scoped_lock slock(const_cast<boost::mutex&>(lock_));\n  if(!matrix_set)\n  {\n    q.toRotation(R);\n    matrix_set = true;\n  }\n\n  return R;\n}\n\n\nTransform3f inverse(const Transform3f& tf)\n{\n  Transform3f res(tf);\n  return res.inverse();\n}\n\nvoid relativeTransform(const Transform3f& tf1, const Transform3f& tf2,\n                       Transform3f& tf)\n{\n  const Quaternion3f& q1_inv = fcl::conj(tf1.getQuatRotation());\n  tf = Transform3f(q1_inv * tf2.getQuatRotation(), q1_inv.transform(tf2.getTranslation() - tf1.getTranslation()));\n}\n\nvoid relativeTransform2(const Transform3f& tf1, const Transform3f& tf2,\n                       Transform3f& tf)\n{\n  const Quaternion3f& q1inv = fcl::conj(tf1.getQuatRotation());\n  const Quaternion3f& q2_q1inv = tf2.getQuatRotation() * q1inv;\n  tf = Transform3f(q2_q1inv, tf2.getTranslation() - q2_q1inv.transform(tf1.getTranslation()));\n}\n\n\n\n}\n", "meta": {"hexsha": "c64b26667f83a87238969403db84858f69dce971", "size": 12926, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/math/transform.cpp", "max_stars_repo_name": "nassimeblinlaas/hpp-fcl-nouveau", "max_stars_repo_head_hexsha": "0a52cde1b64b1e9f25cf38bb60a80b06f98ec37a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/math/transform.cpp", "max_issues_repo_name": "nassimeblinlaas/hpp-fcl-nouveau", "max_issues_repo_head_hexsha": "0a52cde1b64b1e9f25cf38bb60a80b06f98ec37a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/math/transform.cpp", "max_forks_repo_name": "nassimeblinlaas/hpp-fcl-nouveau", "max_forks_repo_head_hexsha": "0a52cde1b64b1e9f25cf38bb60a80b06f98ec37a", "max_forks_repo_licenses": ["BSD-3-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.7884187082, "max_line_length": 125, "alphanum_fraction": 0.5804579916, "num_tokens": 4713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.47626176406573906}}
{"text": "//  (C) Copyright 2006 Eric Niebler, Olivier Gygi\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#include <boost/test/unit_test.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/random.hpp>\n#include <boost/range/iterator_range.hpp>\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/weighted_median.hpp>\n\nusing namespace boost;\nusing namespace unit_test;\nusing namespace accumulators;\n\n///////////////////////////////////////////////////////////////////////////////\n// test_stat\n//\nvoid test_stat()\n{\n    // Median estimation of normal distribution N(1,1) using samples from a narrow normal distribution N(1,0.01)\n    // The weights equal to the likelihood ratio of the corresponding samples\n\n    // two random number generators\n    double mu = 1.;\n    double sigma_narrow = 0.01;\n    double sigma = 1.;\n    boost::lagged_fibonacci607 rng;\n    boost::normal_distribution<> mean_sigma_narrow(mu,sigma_narrow);\n    boost::variate_generator<boost::lagged_fibonacci607&, boost::normal_distribution<> > normal_narrow(rng, mean_sigma_narrow);\n\n    accumulator_set<double, stats<tag::weighted_median(with_p_square_quantile) >, double > acc;\n    accumulator_set<double, stats<tag::weighted_median(with_density) >, double >\n        acc_dens( density_cache_size = 10000, density_num_bins = 1000 );\n    accumulator_set<double, stats<tag::weighted_median(with_p_square_cumulative_distribution) >, double >\n        acc_cdist( p_square_cumulative_distribution_num_cells = 100 );\n\n\n    for (std::size_t i=0; i<1000000; ++i)\n    {\n        double sample = normal_narrow();\n        double w = std::exp(\n            0.5 * (sample - mu) * (sample - mu) * (\n                1./sigma_narrow/sigma_narrow - 1./sigma/sigma\n            )\n        );\n        acc(sample, weight = w);\n        acc_dens(sample, weight = w);\n        acc_cdist(sample, weight = w);\n    }\n\n    BOOST_CHECK_CLOSE(1., weighted_median(acc), 2);\n    BOOST_CHECK_CLOSE(1., weighted_median(acc_dens), 3);\n    BOOST_CHECK_CLOSE(1., weighted_median(acc_cdist), 3);\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// init_unit_test_suite\n//\ntest_suite* init_unit_test_suite( int argc, char* argv[] )\n{\n    test_suite *test = BOOST_TEST_SUITE(\"weighted_median test\");\n\n    test->add(BOOST_TEST_CASE(&test_stat));\n\n    return test;\n}\n", "meta": {"hexsha": "60321d1c0042bc7f77b9d4242935a455390692ce", "size": 2564, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/libs/accumulators/test/weighted_median.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/accumulators/test/weighted_median.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/accumulators/test/weighted_median.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": 36.6285714286, "max_line_length": 127, "alphanum_fraction": 0.6657566303, "num_tokens": 605, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255927, "lm_q2_score": 0.6261241842048092, "lm_q1q2_score": 0.47626176257791375}}
{"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#include <boost/simd/arithmetic/include/functions/divround2even.hpp>\n#include <boost/simd/sdk/config.hpp>\n\n#include <nt2/sdk/unit/module.hpp>\n#include <nt2/sdk/unit/tests/type_expr.hpp>\n#include <nt2/sdk/unit/tests/relation.hpp>\n#include <nt2/sdk/unit/tests/ulp.hpp>\n\n#include <boost/simd/include/constants/one.hpp>\n#include <boost/simd/include/constants/inf.hpp>\n#include <boost/simd/include/constants/zero.hpp>\n#include <boost/simd/include/constants/minf.hpp>\n#include <boost/simd/include/constants/mone.hpp>\n#include <boost/simd/include/constants/nan.hpp>\n#include <boost/simd/include/constants/valmin.hpp>\n#include <boost/simd/include/constants/valmax.hpp>\n\nNT2_TEST_CASE_TPL ( divround2even_real,  BOOST_SIMD_REAL_TYPES)\n{\n  using boost::simd::divround2even;\n  using boost::simd::tag::divround2even_;\n  typedef typename boost::dispatch::meta::call<divround2even_(T,T)>::type r_t;\n  typedef T wished_r_t;\n\n  // return type conformity test\n  NT2_TEST_TYPE_IS( r_t, wished_r_t );\n\n  // specific values tests\n  NT2_TEST_EQUAL(divround2even(boost::simd::Inf<T>(), boost::simd::Inf<T>()), boost::simd::Nan<r_t>());\n  NT2_TEST_EQUAL(divround2even(boost::simd::Minf<T>(), boost::simd::Minf<T>()), boost::simd::Nan<r_t>());\n  NT2_TEST_EQUAL(divround2even(boost::simd::Mone<T>(), boost::simd::Mone<T>()), boost::simd::One<r_t>());\n  NT2_TEST_EQUAL(divround2even(boost::simd::Nan<T>(), boost::simd::Nan<T>()), boost::simd::Nan<r_t>());\n  NT2_TEST_EQUAL(divround2even(boost::simd::One<T>(), boost::simd::One<T>()), boost::simd::One<r_t>());\n} // end of test for floating_\n\nNT2_TEST_CASE_TPL ( divround2even_unsigned_int,  BOOST_SIMD_UNSIGNED_TYPES)\n{\n\n  using boost::simd::divround2even;\n  using boost::simd::tag::divround2even_;\n  typedef typename boost::dispatch::meta::call<divround2even_(T,T)>::type r_t;\n  typedef T wished_r_t;\n\n\n  // return type conformity test\n  NT2_TEST_TYPE_IS( r_t, wished_r_t );\n\n  // specific values tests\n  NT2_TEST_EQUAL(divround2even(boost::simd::One<T>(), boost::simd::One<T>()), boost::simd::One<r_t>());\n  NT2_TEST_EQUAL(divround2even(T(5), T(2)), T(2));\n  NT2_TEST_EQUAL(divround2even(T(7), T(2)), T(4));\n  NT2_TEST_EQUAL(divround2even(T(9), T(3)), T(3));\n  NT2_TEST_EQUAL(divround2even(T(10), T(3)), T(3));\n  NT2_TEST_EQUAL(divround2even(T(11), T(3)), T(4));\n  NT2_TEST_EQUAL(divround2even(T(12), T(3)), T(4));\n  NT2_TEST_EQUAL(divround2even(T(18), T(6)), T(3));\n  NT2_TEST_EQUAL(divround2even(T(20), T(6)), T(3));\n  NT2_TEST_EQUAL(divround2even(T(22), T(6)), T(4));\n  NT2_TEST_EQUAL(divround2even(T(24), T(6)), T(4));\n  NT2_TEST_EQUAL(divround2even(boost::simd::Valmax<T>(),boost::simd::Two<T>()), boost::simd::Valmax<T>()/boost::simd::Two<T>()+boost::simd::One<T>());\n\n} // end of test for unsigned_int_\n\nNT2_TEST_CASE_TPL ( divround2even_signed_int, BOOST_SIMD_INTEGRAL_SIGNED_TYPES)\n{\n\n  using boost::simd::divround2even;\n  using boost::simd::tag::divround2even_;\n  typedef typename boost::dispatch::meta::call<divround2even_(T,T)>::type r_t;\n  typedef T wished_r_t;\n\n\n  // return type conformity test\n  NT2_TEST_TYPE_IS( r_t, wished_r_t );\n\n  // specific values tests\n  NT2_TEST_EQUAL(divround2even(boost::simd::Mone<T>(), boost::simd::Mone<T>()), boost::simd::One<r_t>());\n  NT2_TEST_EQUAL(divround2even(boost::simd::One<T>(), boost::simd::One<T>()), boost::simd::One<r_t>());\n  NT2_TEST_EQUAL(divround2even(T(5), T(2)), T(2));\n  NT2_TEST_EQUAL(divround2even(T(7), T(2)), T(4));\n  NT2_TEST_EQUAL(divround2even(T(-5), T(2)), T(-2));\n  NT2_TEST_EQUAL(divround2even(T(-7), T(2)), T(-4));\n  NT2_TEST_EQUAL(divround2even(T(-4),T(0)), boost::simd::Valmin<r_t>());\n  NT2_TEST_EQUAL(divround2even(T(4),T(0)), boost::simd::Valmax<r_t>());\n  NT2_TEST_EQUAL(divround2even(T(4),T(3)), T(1));\n  NT2_TEST_EQUAL(divround2even(T(-4),T(-3)), T(1));\n  NT2_TEST_EQUAL(divround2even(T(4),T(-3)), T(-1));\n  NT2_TEST_EQUAL(divround2even(T(-4),T(3)), T(-1));\n  NT2_TEST_EQUAL(divround2even(T(5),T(3)), T(2));\n  NT2_TEST_EQUAL(divround2even(T(-5),T(-3)), T(2));\n  NT2_TEST_EQUAL(divround2even(T(5),T(-3)), T(-2));\n  NT2_TEST_EQUAL(divround2even(T(-5),T(3)), T(-2));\n\n  NT2_TEST_EQUAL(divround2even(T(5),T(4)), T(1));\n  NT2_TEST_EQUAL(divround2even(T(-5),T(-4)), T(1));\n  NT2_TEST_EQUAL(divround2even(T(5),T(-4)), T(-1));\n  NT2_TEST_EQUAL(divround2even(T(-5),T(4)), T(-1));\n  NT2_TEST_EQUAL(divround2even(T(6),T(4)), T(2));\n  NT2_TEST_EQUAL(divround2even(T(-6),T(-4)), T(2));\n  NT2_TEST_EQUAL(divround2even(T(6),T(-4)), T(-2));\n  NT2_TEST_EQUAL(divround2even(T(-6),T(4)), T(-2));\n  NT2_TEST_EQUAL(divround2even(T(8),T(4)), T(2));\n  NT2_TEST_EQUAL(divround2even(T(-8),T(-4)), T(2));\n  NT2_TEST_EQUAL(divround2even(T(8),T(-4)), T(-2));\n  NT2_TEST_EQUAL(divround2even(T(-8),T(4)), T(-2));\n  NT2_TEST_EQUAL(divround2even(T(9),T(4)), T(2));\n  NT2_TEST_EQUAL(divround2even(T(-9),T(-4)), T(2));\n  NT2_TEST_EQUAL(divround2even(T(9),T(-4)), T(-2));\n  NT2_TEST_EQUAL(divround2even(T(-9),T(4)), T(-2));\n  NT2_TEST_EQUAL(divround2even(T(10),T(4)), T(2));\n  NT2_TEST_EQUAL(divround2even(T(-10),T(-4)), T(2));\n  NT2_TEST_EQUAL(divround2even(T(10),T(-4)), T(-2));\n  NT2_TEST_EQUAL(divround2even(T(-10),T(4)), T(-2));\n\n} // end of test for signed_int_\n", "meta": {"hexsha": "e42c7122684e3b6d53109c2ff4f2aba443c149da", "size": 5655, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/base/unit/arithmetic/scalar/divround2even.cpp", "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/unit/arithmetic/scalar/divround2even.cpp", "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/unit/arithmetic/scalar/divround2even.cpp", "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": 45.6048387097, "max_line_length": 150, "alphanum_fraction": 0.6643678161, "num_tokens": 1844, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.6513548782017746, "lm_q1q2_score": 0.47617857144190934}}
{"text": "#include <iostream>\n#include <fstream>\n#include <algorithm>\n#include <vector>\n#include <numeric>\n#include <tuple>\n\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/storage.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n#include \"Solution.hpp\"\n#include \"Helper.hpp\"\n\nusing namespace std;\nnamespace ublas = boost::numeric::ublas;\n\n// Check if Solution is feasible\nbool checkSolution(\n\tconst vector<bool> &yi,\n\tconst vector<tuple<int,int,double>> &flow,\n\tconst unsigned int &flowNumber,\n\tconst ublas::matrix<double> &cij,\n\tconst vector<double> &bi,\n\tvector<double> dj,\n\tconst double &sum_dj)\n{\n\tdouble sum = 0.0;\n\t// Conditions are: forall j in J: sum of xij = 1\n\t//\t\t\t\t   if xij !0 0 then yi = 1\n\t//\t\t\t\t   sum_{j in J} xij * dj <= bi*yi, forall i in I\n\tfor (size_t f = 0; f < flowNumber; f++)\n\t{\n\t\tif (yi[get<0>(flow[f])] == 0)\n\t\t\treturn false;\n\n\t\tsum += get<2>(flow[f]);\n\t\tdj[get<1>(flow[f])] -= get<2>(flow[f]);\n\t}\n\n\tif (sum != sum_dj)\n\t\treturn false;\n\n\tfor (size_t j = 0; j != cij.size2(); ++j)\n\t{\n\t\tif (dj[j] != 0.0)\n\t\t\treturn false;\n\t}\n\t\n\treturn true;\n}\n\n// Obejtive Function of FLP\ndouble f(\n\tconst vector<bool> &yi,\n\tconst vector<double> &fi,\n\tconst double &transportation_cost)\n{\n\tdouble z = 0.0;\n\n\tfor (size_t i = 0; i != yi.size(); ++i)\n\t\tz += yi[i] * fi[i];\n\n\tz += transportation_cost;\n\n\treturn z;\n}\n\n// Checks if Capacity can fullfill the Demand\nbool canUpdateXij(\n\tconst vector<double> &bi,\n\tconst vector<bool> &yi,\n\tconst double &sum_dj)\n{\n\tif (inner_product(yi.begin(), yi.end(), bi.begin(), 0.0) < sum_dj)\n\t\treturn false;\n\telse\n\t\treturn true;\n}", "meta": {"hexsha": "72440d76c64b5355714628fdb4c523a9c5b5851b", "size": 1626, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "VNS Implementierung/VNS Implementierung/Solution.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/Solution.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/Solution.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": 20.325, "max_line_length": 67, "alphanum_fraction": 0.6494464945, "num_tokens": 505, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.6513548714339144, "lm_q1q2_score": 0.476178566494207}}
{"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 qle/termstructures/optionletstripper1.hpp\n    \\brief Optionlet (caplet/floorlet) volatility strippers\n    \\ingroup termstructures\n*/\n\n#ifndef quantext_optionletstripper1_hpp\n#define quantext_optionletstripper1_hpp\n\n#include <ql/instruments/capfloor.hpp>\n#include <ql/quotes/simplequote.hpp>\n#include <qle/termstructures/optionletstripper.hpp>\n\n#include <boost/optional.hpp>\n\nnamespace QuantExt {\nusing namespace QuantLib;\nusing boost::optional;\n\ntypedef std::vector<std::vector<boost::shared_ptr<CapFloor> > > CapFloorMatrix;\n\n/*! Helper class to strip optionlet (i.e. caplet/floorlet) volatilities\n    (a.k.a. forward-forward volatilities) from the (cap/floor) term\n    volatilities of a CapFloorTermVolSurface.\n    \\ingroup termstructures\n*/\nclass OptionletStripper1 : public QuantExt::OptionletStripper {\npublic:\n    // If dontThrow is set to true than any vols that would throw are set to dontThrowMinVol (default is 0.0)\n    OptionletStripper1(const boost::shared_ptr<QuantExt::CapFloorTermVolSurface>&,\n                       const boost::shared_ptr<IborIndex>& index, Rate switchStrikes = Null<Rate>(),\n                       Real accuracy = 1.0e-6, Natural maxIter = 100,\n                       const Handle<YieldTermStructure>& discount = Handle<YieldTermStructure>(),\n                       const VolatilityType type = ShiftedLognormal, const Real displacement = 0.0,\n                       bool dontThrow = false, const optional<VolatilityType> targetVolatilityType = boost::none,\n                       const optional<Real> targetDisplacement = boost::none, Real dontThrowMinVol = 0.0);\n\n    const Matrix& capFloorPrices() const;\n    const Matrix& capletVols() const;\n    const Matrix& capFloorVolatilities() const;\n    const Matrix& optionletPrices() const;\n    Rate switchStrike() const;\n    const Handle<YieldTermStructure>& discountCurve() const { return discount_; }\n\n    //! \\name LazyObject interface\n    //@{\n    void performCalculations() const;\n    //@}\nprivate:\n    mutable Matrix capFloorPrices_, optionletPrices_;\n    mutable Matrix capFloorVols_;\n    mutable Matrix optionletStDevs_, capletVols_;\n\n    mutable CapFloorMatrix capFloors_;\n    mutable std::vector<std::vector<boost::shared_ptr<SimpleQuote> > > volQuotes_;\n    mutable std::vector<std::vector<boost::shared_ptr<PricingEngine> > > capFloorEngines_;\n    bool floatingSwitchStrike_;\n    mutable bool capFlooMatrixNotInitialized_;\n    mutable Rate switchStrike_;\n    Real accuracy_;\n    Natural maxIter_;\n    bool dontThrow_;\n    Real dontThrowMinVol_;\n    const VolatilityType inputVolatilityType_;\n    const Real inputDisplacement_;\n};\n} // namespace QuantExt\n\n#endif\n", "meta": {"hexsha": "f7afa0eb6021ccee16fcad3cfb6ef776a57a3936", "size": 3415, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "QuantExt/qle/termstructures/optionletstripper1.hpp", "max_stars_repo_name": "paul-giltinan/Engine", "max_stars_repo_head_hexsha": "49b6e142905ca2cce93c2ae46e9ac69380d9f7a1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "QuantExt/qle/termstructures/optionletstripper1.hpp", "max_issues_repo_name": "paul-giltinan/Engine", "max_issues_repo_head_hexsha": "49b6e142905ca2cce93c2ae46e9ac69380d9f7a1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "QuantExt/qle/termstructures/optionletstripper1.hpp", "max_forks_repo_name": "paul-giltinan/Engine", "max_forks_repo_head_hexsha": "49b6e142905ca2cce93c2ae46e9ac69380d9f7a1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.2528735632, "max_line_length": 113, "alphanum_fraction": 0.7373352855, "num_tokens": 795, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.47617856154650484}}
{"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\u00e4nkt), 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\nint main(int, char**)\n{\n    using namespace std;\n    \n    \n\n    // Define a 6x6 sparse matrix in a 3x3 block-sparse\n    // Should be \n#if 0 \n    typedef mat::parameters<row_major, mtl::index::c_index, fixed::dimensions<2, 2> > parameters1;\n    typedef dense2D<double, parameters1>    m_t;\n#endif\n\n    // Define a 6x6 sparse matrix in a 3x3 block-sparse\n\ttypedef mtl::dense2D<double>    m_t;\n\ttypedef mtl::compressed2D<m_t>  matrix_t;\n    matrix_t                        A(3, 3);\n    {\n\t\tmtl::mat::inserter<matrix_t> ins(A);\n\n\t// First block\n\tm_t  B(2, 2);\n\tB= 0.0;\n\tB[0][0]= 1.0; B[1][1]= 5.0;\n\tins(0, 2) << B;\n\n\t// Second block\n\tB=       0.0;\n\tB[0][1]= 2.0; B[1][0]= 3.0;\n\tins(1, 0) << B;\n\n\tB= 0.0;\n\tB[1][0]= 6.0; B[1][1]= 4.0;\n\tins(2, 1) << B;\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 0]] // b1\n    [             [ 0 5]] \n    [[ 0 2]             ] // b2\n    [[ 3 0]             ]\n    [       [ 0 0]      ] // b3\n    [       [ 6 4]      ]\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\ttypedef mtl::dense_vector<double> v_t;\n\ttypedef mtl::dense_vector<v_t>    vector_t;\n    vector_t                     x(3);\n\n    // x= [[1, 2], [3, 4], [4, 6]]^T\n    x[0]= v_t(2, 1.0); x[0][1]= 2.0; // first block of x = [1, 2]^T\n    x[1]= v_t(2, 3.0); x[1][1]= 4.0; \n    x[2]= v_t(2, 5.0); x[2][1]= 6.0; \n    cout << \"x is \" << x << endl; \n\n    // For y we would only need the vector sizes [[?, ?], [?, ?], [?, ?]]^T\n    vector_t                     y(3, v_t(2));\n\n    // Block-sparse matrix * blocked vector !!!\n    y= A*x;\n\n    cout << \"y after multiplication is \" << y << endl\n\t << \"Should be [[5, 30], [4, 3], [0, 34]]^T.\" << endl; \n\n    MTL_THROW_IF(y[1][1] != 3.0, mtl::runtime_error(\"y[1][1] should be 3.0!\\n\"));\n\n    return 0;\n}\n", "meta": {"hexsha": "82804d124580b3ebfc9ceb832be023f950dd5519", "size": 2835, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/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/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/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.6363636364, "max_line_length": 100, "alphanum_fraction": 0.5216931217, "num_tokens": 1049, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585903489891, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.47617855928431746}}
{"text": "#ifndef MULTIARRAY_HH\n#define MULTIARRAY_HH\n\n#include <Eigen/Core>\n\n/*!\n * \\brief Class to store multiple matrices\n *\n * Class MultiArray stores multiple two-dimenional arrays in a single, bigger\n * array, making sure that each subarray is aligned on an appropriate memory\n * boundary.\n */\nclass MultiArray\n{\n\t//! The number of elements in a single (SSE) packet\n\tstatic const int pkt_size = Eigen::internal::packet_traits<double>::size;\n\npublic:\n\t//! Return type of a sub-array\n\ttypedef Eigen::ArrayXXd::AlignedMapType Block;\n\t//! Read-only type of a sub-array\n\ttypedef Eigen::ArrayXXd::ConstAlignedMapType ConstBlock;\n\n\t/*!\n\t * \\brief Constructor\n\t *\n\t * Create a new MultiArray object that can hold \\a m matrices of size\n\t * \\a n1 x \\a n2.\n\t * \\param n1 The number of rows in each sub-array\n\t * \\param n2 The number of columns in each sub-array\n\t * \\param m  The number of sub-arrays in this object\n\t */\n\tMultiArray(int n1, int n2, int m):\n\t\t_n1(n1), _n2(n2),\n\t\t_nn(pkt_size * ((_n1*_n2+pkt_size-1) / pkt_size)),\n\t\t_A(_nn, m) {}\n\n\t//! Return the number of sub-arrays in this MultiArray\n\tint blocks() const { return _A.cols(); }\n\n\t//! Return the \\a m'th sub-array, writable\n\tBlock operator[](int m)\n\t{\n\t\treturn Eigen::ArrayXXd::MapAligned(_A.data()+m*_nn, _n1, _n2);\n\t}\n\t//! Return the \\a m'th sub-array, read-only\n\tConstBlock operator[](int m) const\n\t{\n\t\treturn Eigen::ArrayXXd::MapAligned(_A.data()+m*_nn, _n1, _n2);\n\t}\n\n\t//! Copy \\a count sub-arrays from \\a arr into this array\n\tvoid copy(int m, const MultiArray& arr, int am, int count)\n\t{\n\t\t_A.block(0, m, _nn, count) = arr._A.block(0, am, _nn, count);\n\t}\n\nprivate:\n\tMultiArray(int n1, int n2, int nn, Eigen::ArrayXXd A):\n\t\t_n1(n1), _n2(n2), _nn(nn), _A(A) {}\n\n\t//! The number of rows in each sub-array\n\tint _n1;\n\t//! The number of columns in each sub-array\n\tint _n2;\n\t//! The number of elements in each sub-array, rounded up to an entire packet\n\tint _nn;\n\t//! The actual data matrix\n\tEigen::ArrayXXd _A;\n};\n\n#endif // MULTIARRAY_HH", "meta": {"hexsha": "f83ba6bf6e601adc498033a68a71241f9cdaaec1", "size": 1988, "ext": "hh", "lang": "C++", "max_stars_repo_path": "MultiArray.hh", "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": "MultiArray.hh", "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": "MultiArray.hh", "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": 27.6111111111, "max_line_length": 77, "alphanum_fraction": 0.6861167002, "num_tokens": 613, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585903489891, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.47617855928431746}}
{"text": "\n\n/* --------------------------------------------------------------------- \n * \n * Copyright (C) 2000 - 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 and Ralf Hartmann, University of Heidelberg, 2000 \n */ \n\n\n// @sect3{Include files}  \n\n// \u8fd9\u4e9b\u7b2c\u4e00\u4e2a\u5305\u542b\u6587\u4ef6\u5728\u524d\u9762\u7684\u4f8b\u5b50\u4e2d\u90fd\u5df2\u7ecf\u5904\u7406\u8fc7\u4e86\uff0c\u6240\u4ee5\u6211\u4eec\u4e0d\u518d\u89e3\u91ca\u5176\u4e2d\u7684\u5185\u5bb9\u3002\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/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/numerics/matrix_tools.h> \n#include <deal.II/numerics/error_estimator.h> \n#include <deal.II/numerics/data_out.h> \n\n// \u5728\u8fd9\u4e2a\u4f8b\u5b50\u4e2d\uff0c\u6211\u4eec\u5c06\u4e0d\u4f7f\u7528DoFHandler\u7c7b\u9ed8\u8ba4\u4f7f\u7528\u7684\u7f16\u53f7\u65b9\u6848\uff0c\u800c\u662f\u4f7f\u7528Cuthill-McKee\u7b97\u6cd5\u5bf9\u5176\u8fdb\u884c\u91cd\u65b0\u7f16\u53f7\u3002\u6b63\u5982\u5728 step-2 \u4e2d\u5df2\u7ecf\u89e3\u91ca\u8fc7\u7684\uff0c\u5fc5\u8981\u7684\u51fd\u6570\u88ab\u58f0\u660e\u5728\u4ee5\u4e0b\u6587\u4ef6\u4e2d\u3002\n\n#include <deal.II/dofs/dof_renumbering.h> \n\n// \u7136\u540e\u6211\u4eec\u5c06\u5c55\u793a\u4e00\u4e2a\u5c0f\u6280\u5de7\uff0c\u5982\u4f55\u786e\u4fdd\u5bf9\u8c61\u5728\u4ecd\u5728\u4f7f\u7528\u65f6\u4e0d\u88ab\u5220\u9664\u3002\u4e3a\u6b64\uff0cdeal.II\u6709\u4e00\u4e2aSmartPointer\u8f85\u52a9\u7c7b\uff0c\u5b83\u88ab\u58f0\u660e\u5728\u8fd9\u4e2a\u6587\u4ef6\u4e2d\u3002\n\n#include <deal.II/base/smartpointer.h> \n\n// \u63a5\u4e0b\u6765\uff0c\u6211\u4eec\u8981\u4f7f\u7528\u4ecb\u7ecd\u4e2d\u63d0\u5230\u7684\u51fd\u6570 VectorTools::integrate_difference() \uff0c\u6211\u4eec\u8981\u4f7f\u7528\u4e00\u4e2aConvergenceTable\uff0c\u5728\u8fd0\u884c\u8fc7\u7a0b\u4e2d\u6536\u96c6\u6240\u6709\u91cd\u8981\u7684\u6570\u636e\uff0c\u5e76\u5728\u6700\u540e\u4ee5\u8868\u683c\u5f62\u5f0f\u6253\u5370\u51fa\u6765\u3002\u8fd9\u4e9b\u6765\u81ea\u4e8e\u4ee5\u4e0b\u4e24\u4e2a\u6587\u4ef6\u3002\n\n#include <deal.II/numerics/vector_tools.h> \n#include <deal.II/base/convergence_table.h> \n\n// \u6700\u540e\uff0c\u6211\u4eec\u9700\u8981\u4f7f\u7528FEFaceValues\u7c7b\uff0c\u5b83\u4e0eFEValues\u7c7b\u5728\u540c\u4e00\u4e2a\u6587\u4ef6\u4e2d\u58f0\u660e\u3002\n\n#include <deal.II/fe/fe_values.h> \n\n#include <array> \n#include <fstream> \n#include <iostream> \n\n// \u5728\u6211\u4eec\u7ee7\u7eed\u5b9e\u9645\u6267\u884c\u4e4b\u524d\u7684\u6700\u540e\u4e00\u6b65\u662f\u6253\u5f00\u4e00\u4e2a\u547d\u540d\u7a7a\u95f4 <code>Step7</code> \uff0c\u6211\u4eec\u5c06\u628a\u6240\u6709\u7684\u4e1c\u897f\u653e\u8fdb\u53bb\uff0c\u6b63\u5982\u5728\u4ecb\u7ecd\u7684\u6700\u540e\u6240\u8ba8\u8bba\u7684\uff0c\u5e76\u628a\u547d\u540d\u7a7a\u95f4 <code>dealii</code> \u7684\u6210\u5458\u5bfc\u5165\u5176\u4e2d\u3002\n\nnamespace Step7 \n{ \n  using namespace dealii; \n// @sect3{Equation data}  \n\n// \u5728\u5b9e\u73b0\u5b9e\u9645\u6c42\u89e3\u7684\u7c7b\u4e4b\u524d\uff0c\u6211\u4eec\u9996\u5148\u58f0\u660e\u548c\u5b9a\u4e49\u4e00\u4e9b\u4ee3\u8868\u53f3\u624b\u8fb9\u548c\u6c42\u89e3\u7c7b\u7684\u51fd\u6570\u7c7b\u3002\u7531\u4e8e\u6211\u4eec\u8981\u5c06\u6570\u503c\u5f97\u5230\u7684\u89e3\u4e0e\u7cbe\u786e\u7684\u8fde\u7eed\u89e3\u8fdb\u884c\u6bd4\u8f83\uff0c\u6211\u4eec\u9700\u8981\u4e00\u4e2a\u4ee3\u8868\u8fde\u7eed\u89e3\u7684\u51fd\u6570\u5bf9\u8c61\u3002\u53e6\u4e00\u65b9\u9762\uff0c\u6211\u4eec\u9700\u8981\u53f3\u624b\u8fb9\u7684\u51fd\u6570\uff0c\u800c\u8fd9\u4e2a\u51fd\u6570\u5f53\u7136\u4e0e\u89e3\u5171\u4eab\u4e00\u4e9b\u7279\u5f81\u3002\u4e3a\u4e86\u51cf\u5c11\u5982\u679c\u6211\u4eec\u5fc5\u987b\u540c\u65f6\u6539\u53d8\u4e24\u4e2a\u7c7b\u4e2d\u7684\u67d0\u4e9b\u4e1c\u897f\u800c\u4ea7\u751f\u7684\u4f9d\u8d56\u6027\uff0c\u6211\u4eec\u5c06\u4e24\u4e2a\u51fd\u6570\u7684\u5171\u540c\u7279\u5f81\u79fb\u5230\u4e00\u4e2a\u57fa\u7c7b\u4e2d\u3002\n\n// \u89e3\uff08\u6b63\u5982\u4ecb\u7ecd\u4e2d\u6240\u89e3\u91ca\u7684\uff0c\u6211\u4eec\u9009\u62e9\u4e09\u4e2a\u6307\u6570\u4e4b\u548c\uff09\u548c\u53f3\u624b\u8fb9\u7684\u5171\u540c\u7279\u5f81\u662f\uff1a\u6307\u6570\u7684\u6570\u91cf\uff0c\u5b83\u4eec\u7684\u4e2d\u5fc3\uff0c\u4ee5\u53ca\u5b83\u4eec\u7684\u534a\u5bbd\u3002\u6211\u4eec\u5728\u4ee5\u4e0b\u7c7b\u522b\u4e2d\u58f0\u660e\u5b83\u4eec\u3002\u7531\u4e8e\u6307\u6570\u7684\u6570\u91cf\u662f\u4e00\u4e2a\u7f16\u8bd1\u65f6\u7684\u5e38\u6570\uff0c\u6211\u4eec\u4f7f\u7528\u4e00\u4e2a\u56fa\u5b9a\u957f\u5ea6\u7684 <code>std::array</code> \u6765\u5b58\u50a8\u4e2d\u5fc3\u70b9\u3002\n\n  template <int dim> \n  class SolutionBase \n  { \n  protected: \n    static const std::array<Point<dim>, 3> source_centers; \n    static const double                    width; \n  }; \n\n// \u8868\u793a\u6307\u6570\u4e2d\u5fc3\u548c\u5bbd\u5ea6\u7684\u53d8\u91cf\u521a\u521a\u88ab\u58f0\u660e\uff0c\u73b0\u5728\u6211\u4eec\u8fd8\u9700\u8981\u7ed9\u5b83\u4eec\u8d4b\u503c\u3002\u5728\u8fd9\u91cc\uff0c\u6211\u4eec\u53ef\u4ee5\u5c55\u793a\u53e6\u4e00\u4e2a\u5c0f\u5c0f\u7684\u6a21\u677f\u9b54\u6cd5\uff0c\u5373\u6211\u4eec\u5982\u4f55\u6839\u636e\u7ef4\u5ea6\u7ed9\u8fd9\u4e9b\u53d8\u91cf\u5206\u914d\u4e0d\u540c\u7684\u503c\u3002\u6211\u4eec\u5c06\u5728\u7a0b\u5e8f\u4e2d\u53ea\u4f7f\u75282\u7ef4\u7684\u60c5\u51b5\uff0c\u4f46\u6211\u4eec\u5c55\u793a1\u7ef4\u7684\u60c5\u51b5\u662f\u4e3a\u4e86\u8bf4\u660e\u4e00\u4e2a\u6709\u7528\u7684\u6280\u672f\u3002\n\n// \u9996\u5148\u6211\u4eec\u4e3a1d\u60c5\u51b5\u4e0b\u7684\u4e2d\u5fc3\u8d4b\u503c\uff0c\u6211\u4eec\u5c06\u4e2d\u5fc3\u7b49\u8ddd\u79bb\u5730\u653e\u5728-1/3\u30010\u548c1/3\u5904\u3002\u8fd9\u4e2a\u5b9a\u4e49\u7684<code>template &lt;&gt;</code>\u5934\u663e\u793a\u4e86\u4e00\u4e2a\u660e\u786e\u7684\u4e13\u4e1a\u5316\u3002\u8fd9\u610f\u5473\u7740\uff0c\u8fd9\u4e2a\u53d8\u91cf\u5c5e\u4e8e\u4e00\u4e2a\u6a21\u677f\uff0c\u4f46\u662f\u6211\u4eec\u5e76\u6ca1\u6709\u5411\u7f16\u8bd1\u5668\u63d0\u4f9b\u4e00\u4e2a\u6a21\u677f\uff0c\u8ba9\u5b83\u901a\u8fc7\u7528\u4e00\u4e9b\u5177\u4f53\u7684\u503c\u6765\u66ff\u4ee3 <code>dim</code> \u6765\u4e13\u95e8\u5316\u4e00\u4e2a\u5177\u4f53\u7684\u53d8\u91cf\uff0c\u800c\u662f\u81ea\u5df1\u63d0\u4f9b\u4e00\u4e2a\u4e13\u95e8\u5316\uff0c\u5728\u8fd9\u4e2a\u4f8b\u5b50\u4e2d\u662f <code>dim=1</code>  \u3002\u5982\u679c\u7f16\u8bd1\u5668\u5728\u6a21\u677f\u53c2\u6570\u7b49\u4e8e1\u7684\u5730\u65b9\u770b\u5230\u4e86\u5bf9\u8fd9\u4e2a\u53d8\u91cf\u7684\u5f15\u7528\uff0c\u5b83\u5c31\u77e5\u9053\u5b83\u4e0d\u9700\u8981\u901a\u8fc7\u66ff\u6362 <code>dim</code> \u4ece\u6a21\u677f\u4e2d\u751f\u6210\u8fd9\u4e2a\u53d8\u91cf\uff0c\u800c\u662f\u53ef\u4ee5\u7acb\u5373\u4f7f\u7528\u4e0b\u9762\u7684\u5b9a\u4e49\u3002\n\n  template <> \n  const std::array<Point<1>, 3> SolutionBase<1>::source_centers = { \n    {Point<1>(-1.0 / 3.0), Point<1>(0.0), Point<1>(+1.0 / 3.0)}}; \n\n// \u540c\u6837\u5730\uff0c\u6211\u4eec\u53ef\u4ee5\u4e3a <code>dim=2</code> \u63d0\u4f9b\u4e00\u4e2a\u660e\u786e\u7684\u7279\u6b8a\u5316\u3002\u6211\u4eec\u5c062d\u60c5\u51b5\u4e0b\u7684\u4e2d\u5fc3\u653e\u7f6e\u5982\u4e0b\u3002\n\n  template <> \n  const std::array<Point<2>, 3> SolutionBase<2>::source_centers = { \n    {Point<2>(-0.5, +0.5), Point<2>(-0.5, -0.5), Point<2>(+0.5, -0.5)}}; \n\n// \u8fd8\u9700\u8981\u7ed9\u6307\u6570\u7684\u534a\u5bbd\u6307\u5b9a\u4e00\u4e2a\u503c\u3002\u6211\u4eec\u5e0c\u671b\u5bf9\u6240\u6709\u7ef4\u5ea6\u4f7f\u7528\u76f8\u540c\u7684\u6570\u503c\u3002\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0c\u6211\u4eec\u53ea\u9700\u5411\u7f16\u8bd1\u5668\u63d0\u4f9b\u4e00\u4e2a\u6a21\u677f\uff0c\u5b83\u53ef\u4ee5\u901a\u8fc7\u7528\u4e00\u4e2a\u5177\u4f53\u7684\u503c\u66ff\u6362 <code>dim</code> \u6765\u751f\u6210\u4e00\u4e2a\u5177\u4f53\u7684\u5b9e\u4f8b\u3002\n\n  template <int dim> \n  const double SolutionBase<dim>::width = 1. / 8.; \n\n// \u5728\u58f0\u660e\u548c\u5b9a\u4e49\u4e86\u89e3\u548c\u53f3\u624b\u7684\u7279\u5f81\u540e\uff0c\u6211\u4eec\u53ef\u4ee5\u58f0\u660e\u4ee3\u8868\u8fd9\u4e24\u8005\u7684\u7c7b\u3002\u5b83\u4eec\u90fd\u4ee3\u8868\u8fde\u7eed\u51fd\u6570\uff0c\u6240\u4ee5\u5b83\u4eec\u90fd\u6d3e\u751f\u4e8eFunction&lt;dim&gt;\u57fa\u7c7b\uff0c\u5b83\u4eec\u4e5f\u7ee7\u627f\u4e86SolutionBase\u7c7b\u4e2d\u5b9a\u4e49\u7684\u7279\u5f81\u3002\n\n// \u5b9e\u9645\u7684\u7c7b\u662f\u5728\u4e0b\u9762\u58f0\u660e\u7684\u3002\u8bf7\u6ce8\u610f\uff0c\u4e3a\u4e86\u8ba1\u7b97\u6570\u503c\u89e3\u4e0e\u8fde\u7eed\u89e3\u5728L2\u548cH1\uff08\u534a\uff09\u51c6\u5219\u4e0b\u7684\u8bef\u5dee\uff0c\u6211\u4eec\u5fc5\u987b\u63d0\u4f9b\u7cbe\u786e\u89e3\u7684\u503c\u548c\u68af\u5ea6\u3002\u8fd9\u6bd4\u6211\u4eec\u5728\u4ee5\u524d\u7684\u4f8b\u5b50\u4e2d\u6240\u505a\u7684\u8981\u591a\uff0c\u5728\u4ee5\u524d\u7684\u4f8b\u5b50\u4e2d\uff0c\u6211\u4eec\u6240\u63d0\u4f9b\u7684\u53ea\u662f\u4e00\u4e2a\u6216\u4e00\u5217\u70b9\u7684\u503c\u3002\u5e78\u8fd0\u7684\u662f\uff0cFunction\u7c7b\u4e5f\u6709\u7528\u4e8e\u68af\u5ea6\u7684\u865a\u62df\u51fd\u6570\uff0c\u6240\u4ee5\u6211\u4eec\u53ef\u4ee5\u7b80\u5355\u5730\u91cd\u8f7dFunction\u57fa\u7c7b\u4e2d\u5404\u81ea\u7684\u865a\u62df\u6210\u5458\u51fd\u6570\u3002\u8bf7\u6ce8\u610f\uff0c\u4e00\u4e2a\u51fd\u6570\u5728 <code>dim</code> \u7a7a\u95f4\u7ef4\u5ea6\u4e0a\u7684\u68af\u5ea6\u662f\u4e00\u4e2a\u5927\u5c0f\u4e3a <code>dim</code> \u7684\u5411\u91cf\uff0c\u5373\u4e00\u4e2a\u7b49\u7ea7\u4e3a1\u3001\u7ef4\u5ea6\u4e3a <code>dim</code> \u7684\u5f20\u91cf\u3002\u5c31\u50cf\u5176\u4ed6\u5f88\u591a\u4e1c\u897f\u4e00\u6837\uff0c\u8be5\u5e93\u63d0\u4f9b\u4e86\u4e00\u4e2a\u5408\u9002\u7684\u7c7b\u3002\u8fd9\u4e2a\u7c7b\u7684\u4e00\u4e2a\u65b0\u7279\u70b9\u662f\uff0c\u5b83\u660e\u786e\u5730\u4f7f\u7528\u4e86\u5f20\u91cf\u5bf9\u8c61\uff0c\u4e4b\u524d\u5728  step-3  \u548c  step-4  \u4e2d\u4f5c\u4e3a\u4e2d\u95f4\u8bcd\u51fa\u73b0\u3002\u5f20\u91cf\u662f\u6807\u91cf\uff08\u7b49\u7ea7\u4e3a\u96f6\u7684\u5f20\u91cf\uff09\u3001\u5411\u91cf\uff08\u7b49\u7ea7\u4e3a\u4e00\u7684\u5f20\u91cf\uff09\u548c\u77e9\u9635\uff08\u7b49\u7ea7\u4e3a\u4e8c\u7684\u5f20\u91cf\uff09\u4ee5\u53ca\u9ad8\u7ef4\u5bf9\u8c61\u7684\u6982\u62ec\u3002\u5f20\u91cf\u7c7b\u9700\u8981\u4e24\u4e2a\u6a21\u677f\u53c2\u6570\uff1a\u5f20\u91cf\u7b49\u7ea7\u548c\u5f20\u91cf\u7ef4\u5ea6\u3002\u4f8b\u5982\uff0c\u5728\u8fd9\u91cc\u6211\u4eec\u4f7f\u7528\u7b49\u7ea7\u4e3a\u4e00\u7684\u5f20\u91cf\uff08\u5411\u91cf\uff09\uff0c\u7ef4\u5ea6\u4e3a <code>dim</code> (so they have <code>dim</code> \u9879\uff09\u3002\u867d\u7136\u8fd9\u6bd4\u4f7f\u7528Vector\u7684\u7075\u6d3b\u6027\u8981\u5dee\u4e00\u4e9b\uff0c\u4f46\u5f53\u7f16\u8bd1\u65f6\u77e5\u9053\u5411\u91cf\u7684\u957f\u5ea6\u65f6\uff0c\u7f16\u8bd1\u5668\u53ef\u4ee5\u751f\u6210\u66f4\u5feb\u7684\u4ee3\u7801\u3002\u6b64\u5916\uff0c\u6307\u5b9a\u4e00\u4e2a\u79e9\u4e3a1\u3001\u7ef4\u6570\u4e3a <code>dim</code> \u7684\u5f20\u91cf\uff0c\u53ef\u4ee5\u4fdd\u8bc1\u5f20\u91cf\u5177\u6709\u6b63\u786e\u7684\u5f62\u72b6\uff08\u56e0\u4e3a\u5b83\u662f\u5185\u7f6e\u4e8e\u5bf9\u8c61\u672c\u8eab\u7684\u7c7b\u578b\u4e2d\u7684\uff09\uff0c\u6240\u4ee5\u7f16\u8bd1\u5668\u53ef\u4ee5\u4e3a\u6211\u4eec\u6293\u4f4f\u5927\u591a\u6570\u4e0e\u5c3a\u5bf8\u6709\u5173\u7684\u9519\u8bef\u3002\n\n  template <int dim> \n  class Solution : public Function<dim>, protected SolutionBase<dim> \n  { \n  public: \n    virtual double value(const Point<dim> & p, \n                         const unsigned int component = 0) const override; \n\n    virtual Tensor<1, dim> \n    gradient(const Point<dim> & p, \n             const unsigned int component = 0) const override; \n  }; \n\n//\u7cbe\u786e\u89e3\u7c7b\u7684\u503c\u548c\u68af\u5ea6\u7684\u5b9e\u9645\u5b9a\u4e49\u662f\u6839\u636e\u5176\u6570\u5b66\u5b9a\u4e49\uff0c\u4e0d\u9700\u8981\u8fc7\u591a\u89e3\u91ca\u3002\n\n// \u552f\u4e00\u503c\u5f97\u4e00\u63d0\u7684\u662f\uff0c\u5982\u679c\u6211\u4eec\u8bbf\u95ee\u4e00\u4e2a\u4f9d\u8d56\u6a21\u677f\u7684\u57fa\u7c7b\u7684\u5143\u7d20\uff08\u5728\u672c\u4f8b\u4e2d\u662fSolutionBase&lt;dim&gt;\u7684\u5143\u7d20\uff09\uff0c\u90a3\u4e48C++\u8bed\u8a00\u4f1a\u5f3a\u8feb\u6211\u4eec\u5199  <code>this-&gt;source_centers</code>  \uff0c\u5bf9\u4e8e\u57fa\u7c7b\u7684\u5176\u4ed6\u6210\u5458\u4e5f\u662f\u5982\u6b64\u3002\u5982\u679c\u57fa\u7c7b\u4e0d\u4f9d\u8d56\u6a21\u677f\uff0cC++\u5c31\u4e0d\u9700\u8981 <code>this-&gt;</code> \u7684\u9650\u5b9a\u3002\u8fd9\u4e00\u70b9\u7684\u539f\u56e0\u5f88\u590d\u6742\uff0cC++\u4e66\u7c4d\u4f1a\u5728<i>two-stage (name) lookup</i>\u8fd9\u53e5\u8bdd\u4e0b\u8fdb\u884c\u89e3\u91ca\uff0c\u5728deal.II FAQs\u4e2d\u4e5f\u6709\u5f88\u957f\u7684\u63cf\u8ff0\u3002\n\n  template <int dim> \n  double Solution<dim>::value(const Point<dim> &p, const unsigned int) const \n  { \n    double return_value = 0; \n    for (const auto &center : this->source_centers) \n      { \n        const Tensor<1, dim> x_minus_xi = p - center; \n        return_value += \n          std::exp(-x_minus_xi.norm_square() / (this->width * this->width)); \n      } \n\n    return return_value; \n  } \n\n// \u540c\u6837\uff0c\u8fd9\u4e5f\u662f\u5bf9\u89e3\u7684\u68af\u5ea6\u7684\u8ba1\u7b97\u3002 \u4e3a\u4e86\u4ece\u6307\u6570\u7684\u8d21\u732e\u4e2d\u79ef\u7d2f\u68af\u5ea6\uff0c\u6211\u4eec\u5206\u914d\u4e86\u4e00\u4e2a\u5bf9\u8c61  <code>return_value</code>  \uff0c\u5b83\u8868\u793a\u79e9  <code>1</code>  \u548c\u7ef4  <code>dim</code>  \u7684\u5f20\u91cf\u7684\u6570\u5b66\u91cf\u3002\u5b83\u7684\u9ed8\u8ba4\u6784\u9020\u51fd\u6570\u5c06\u5176\u8bbe\u7f6e\u4e3a\u53ea\u5305\u542b\u96f6\u7684\u5411\u91cf\uff0c\u6240\u4ee5\u6211\u4eec\u4e0d\u9700\u8981\u660e\u786e\u5173\u5fc3\u5b83\u7684\u521d\u59cb\u5316\u3002\n\n// \u6ce8\u610f\uff0c\u6211\u4eec\u4e5f\u53ef\u4ee5\u628a\u5bf9\u8c61\u7684\u7c7b\u578b\u5b9a\u4e3aPoint&lt;dim&gt;\uff0c\u800c\u4e0d\u662fTensor&lt;1,dim&gt;\u3002\u7b49\u7ea71\u7684\u5f20\u91cf\u548c\u70b9\u51e0\u4e4e\u662f\u53ef\u4ee5\u4ea4\u6362\u7684\uff0c\u800c\u4e14\u53ea\u6709\u975e\u5e38\u7ec6\u5fae\u7684\u6570\u5b66\u542b\u4e49\u4e0d\u540c\u3002\u4e8b\u5b9e\u4e0a\uff0cPoint&lt;dim&gt;\u7c7b\u662f\u7531Tensor&lt;1,dim&gt;\u7c7b\u6d3e\u751f\u51fa\u6765\u7684\uff0c\u8fd9\u5c31\u5f25\u8865\u4e86\u5b83\u4eec\u7684\u76f8\u4e92\u4ea4\u6362\u80fd\u529b\u3002\u5b83\u4eec\u7684\u4e3b\u8981\u533a\u522b\u5728\u4e8e\u5b83\u4eec\u5728\u903b\u8f91\u4e0a\u7684\u542b\u4e49\uff1a\u70b9\u662f\u7a7a\u95f4\u4e2d\u7684\u70b9\uff0c\u6bd4\u5982\u6211\u4eec\u8981\u8bc4\u4f30\u4e00\u4e2a\u51fd\u6570\u7684\u4f4d\u7f6e\uff08\u4f8b\u5982\uff0c\u89c1\u8fd9\u4e2a\u51fd\u6570\u7684\u7b2c\u4e00\u4e2a\u53c2\u6570\u7684\u7c7b\u578b\uff09\u3002\u53e6\u4e00\u65b9\u9762\uff0c\u79e91\u7684\u5f20\u91cf\u5177\u6709\u76f8\u540c\u7684\u53d8\u6362\u5c5e\u6027\uff0c\u4f8b\u5982\uff0c\u5f53\u6211\u4eec\u6539\u53d8\u5750\u6807\u7cfb\u65f6\uff0c\u5b83\u4eec\u9700\u8981\u4ee5\u67d0\u79cd\u65b9\u5f0f\u65cb\u8f6c\uff1b\u7136\u800c\uff0c\u5b83\u4eec\u4e0d\u5177\u6709\u70b9\u6240\u5177\u6709\u7684\u76f8\u540c\u5185\u6db5\uff0c\u53ea\u662f\u6bd4\u5750\u6807\u65b9\u5411\u6240\u8de8\u8d8a\u7684\u7a7a\u95f4\u66f4\u62bd\u8c61\u7684\u5bf9\u8c61\u3002\u4e8b\u5b9e\u4e0a\uff0c\u68af\u5ea6\u751f\u6d3b\u5728 \"\u5bf9\u7b49 \"\u7684\u7a7a\u95f4\u4e2d\uff0c\u56e0\u4e3a\u5b83\u4eec\u7684\u5206\u91cf\u7684\u7ef4\u5ea6\u4e0d\u662f\u957f\u5ea6\uff0c\u800c\u662f\u957f\u5ea6\u4e0a\u7684\u4e00\u4e2a\uff09\u3002\n\n  template <int dim> \n  Tensor<1, dim> Solution<dim>::gradient(const Point<dim> &p, \n                                         const unsigned int) const \n  { \n    Tensor<1, dim> return_value; \n\n    for (const auto &center : this->source_centers) \n      { \n        const Tensor<1, dim> x_minus_xi = p - center; \n\n// \u5bf9\u4e8e\u68af\u5ea6\uff0c\u6ce8\u610f\u5b83\u7684\u65b9\u5411\u662f\u6cbf\u7740\uff08x-x_i\uff09\uff0c\u6240\u4ee5\u6211\u4eec\u628a\u8fd9\u4e2a\u8ddd\u79bb\u5411\u91cf\u7684\u500d\u6570\u52a0\u8d77\u6765\uff0c\u5176\u4e2d\u7684\u56e0\u5b50\u662f\u7531\u6307\u6570\u7ed9\u51fa\u3002\n\n        return_value += \n          (-2. / (this->width * this->width) * \n           std::exp(-x_minus_xi.norm_square() / (this->width * this->width)) * \n           x_minus_xi); \n      } \n\n    return return_value; \n  } \n\n// \u9664\u4e86\u4ee3\u8868\u7cbe\u786e\u89e3\u7684\u51fd\u6570\u5916\uff0c\u6211\u4eec\u8fd8\u9700\u8981\u4e00\u4e2a\u51fd\u6570\uff0c\u5728\u7ec4\u88c5\u79bb\u6563\u65b9\u7a0b\u7684\u7ebf\u6027\u7cfb\u7edf\u65f6\uff0c\u6211\u4eec\u53ef\u4ee5\u5c06\u5176\u4f5c\u4e3a\u53f3\u624b\u3002\u8fd9\u53ef\u4ee5\u901a\u8fc7\u4e0b\u9762\u7684\u7c7b\u548c\u5176\u51fd\u6570\u7684\u5b9a\u4e49\u6765\u5b9e\u73b0\u3002\u8bf7\u6ce8\u610f\uff0c\u8fd9\u91cc\u6211\u4eec\u53ea\u9700\u8981\u51fd\u6570\u7684\u503c\uff0c\u800c\u4e0d\u662f\u5b83\u7684\u68af\u5ea6\u6216\u9ad8\u9636\u5bfc\u6570\u3002\n\n  template <int dim> \n  class RightHandSide : public Function<dim>, protected SolutionBase<dim> \n  { \n  public: \n    virtual double value(const Point<dim> & p, \n                         const unsigned int component = 0) const override; \n  }; \n\n// \u53f3\u624b\u8fb9\u7684\u503c\u662f\u7531\u89e3\u7684\u8d1f\u62c9\u666e\u62c9\u65af\u52a0\u4e0a\u89e3\u672c\u8eab\u7ed9\u51fa\u7684\uff0c\u56e0\u4e3a\u6211\u4eec\u8981\u89e3\u51b3\u4ea5\u59c6\u970d\u5179\u65b9\u7a0b\u7684\u95ee\u9898\u3002\n\n  template <int dim> \n  double RightHandSide<dim>::value(const Point<dim> &p, \n                                   const unsigned int) const \n  { \n    double return_value = 0; \n    for (const auto &center : this->source_centers) \n      { \n        const Tensor<1, dim> x_minus_xi = p - center; \n\n// \u7b2c\u4e00\u4e2a\u8d21\u732e\u662f\u62c9\u666e\u62c9\u65af\u7684\u3002\n\n        return_value += \n          ((2. * dim - \n            4. * x_minus_xi.norm_square() / (this->width * this->width)) / \n           (this->width * this->width) * \n           std::exp(-x_minus_xi.norm_square() / (this->width * this->width))); \n\n// \u800c\u7b2c\u4e8c\u4e2a\u662f\u89e3\u51b3\u65b9\u6848\u672c\u8eab\u3002\n\n        return_value += \n          std::exp(-x_minus_xi.norm_square() / (this->width * this->width)); \n      } \n\n    return return_value; \n  } \n// @sect3{The Helmholtz solver class}  \n\n// \u7136\u540e\u6211\u4eec\u9700\u8981\u505a\u6240\u6709\u5de5\u4f5c\u7684\u7c7b\u3002\u9664\u4e86\u5b83\u7684\u540d\u5b57\uff0c\u5b83\u7684\u63a5\u53e3\u4e0e\u524d\u9762\u7684\u4f8b\u5b50\u57fa\u672c\u76f8\u540c\u3002\n\n// \u5176\u4e2d\u4e00\u4e2a\u4e0d\u540c\u70b9\u662f\uff0c\u6211\u4eec\u5c06\u5728\u51e0\u79cd\u6a21\u5f0f\u4e0b\u4f7f\u7528\u8fd9\u4e2a\u7c7b\uff1a\u7528\u4e8e\u4e0d\u540c\u7684\u6709\u9650\u5143\uff0c\u4ee5\u53ca\u7528\u4e8e\u81ea\u9002\u5e94\u7ec6\u5316\u548c\u5168\u5c40\u7ec6\u5316\u3002\u5168\u5c40\u7ec6\u5316\u8fd8\u662f\u81ea\u9002\u5e94\u7ec6\u5316\u7684\u51b3\u5b9a\u662f\u901a\u8fc7\u5728\u7c7b\u7684\u9876\u90e8\u58f0\u660e\u7684\u679a\u4e3e\u7c7b\u578b\u4f20\u8fbe\u7ed9\u8be5\u7c7b\u7684\u6784\u9020\u51fd\u6570\u7684\u3002\u6784\u9020\u51fd\u6570\u63a5\u6536\u4e00\u4e2a\u6709\u9650\u5143\u5bf9\u8c61\u548c\u7ec6\u5316\u6a21\u5f0f\u4f5c\u4e3a\u53c2\u6570\u3002\n\n// \u9664\u4e86 <code>process_solution</code> \u51fd\u6570\u5916\uff0c\u5176\u4f59\u7684\u6210\u5458\u51fd\u6570\u4e0e\u4e4b\u524d\u4e00\u6837\u3002\u5728\u89e3\u88ab\u8ba1\u7b97\u51fa\u6765\u540e\uff0c\u6211\u4eec\u5bf9\u5b83\u8fdb\u884c\u4e00\u4e9b\u5206\u6790\uff0c\u6bd4\u5982\u8ba1\u7b97\u5404\u79cd\u89c4\u8303\u7684\u8bef\u5dee\u3002\u4e3a\u4e86\u5b9e\u73b0\u4e00\u4e9b\u8f93\u51fa\uff0c\u5b83\u9700\u8981\u7ec6\u5316\u5468\u671f\u7684\u7f16\u53f7\uff0c\u56e0\u6b64\u5f97\u5230\u5b83\u4f5c\u4e3a\u4e00\u4e2a\u53c2\u6570\u3002\n\n  template <int dim> \n  class HelmholtzProblem \n  { \n  public: \n    enum RefinementMode \n    { \n      global_refinement, \n      adaptive_refinement \n    }; \n\n    HelmholtzProblem(const FiniteElement<dim> &fe, \n                     const RefinementMode      refinement_mode); \n\n    void run(); \n\n  private: \n    void setup_system(); \n    void assemble_system(); \n    void solve(); \n    void refine_grid(); \n    void process_solution(const unsigned int cycle); \n\n// \u73b0\u5728\u662f\u8fd9\u4e2a\u7c7b\u7684\u6570\u636e\u5143\u7d20\u3002\u5728\u6211\u4eec\u4ee5\u524d\u7684\u4f8b\u5b50\u4e2d\u5df2\u7ecf\u4f7f\u7528\u8fc7\u7684\u53d8\u91cf\u4e2d\uff0c\u53ea\u6709\u6709\u9650\u5143\u5bf9\u8c61\u4e0d\u540c\u3002\u8fd9\u4e2a\u7c7b\u7684\u5bf9\u8c61\u6240\u64cd\u4f5c\u7684\u6709\u9650\u5143\u88ab\u4f20\u9012\u7ed9\u8fd9\u4e2a\u7c7b\u7684\u6784\u9020\u51fd\u6570\u3002\u5b83\u5fc5\u987b\u5b58\u50a8\u4e00\u4e2a\u6307\u5411\u6709\u9650\u5143\u7684\u6307\u9488\uff0c\u4f9b\u6210\u5458\u51fd\u6570\u4f7f\u7528\u3002\u73b0\u5728\uff0c\u5bf9\u4e8e\u672c\u7c7b\u6765\u8bf4\uff0c\u8fd9\u6ca1\u6709\u4ec0\u4e48\u5927\u4e0d\u4e86\u7684\uff0c\u4f46\u7531\u4e8e\u6211\u4eec\u60f3\u5728\u8fd9\u4e9b\u7a0b\u5e8f\u4e2d\u5c55\u793a\u6280\u672f\u800c\u4e0d\u662f\u89e3\u51b3\u65b9\u6848\uff0c\u6211\u4eec\u5c06\u5728\u8fd9\u91cc\u6307\u51fa\u4e00\u4e2a\u7ecf\u5e38\u51fa\u73b0\u7684\u95ee\u9898--\u5f53\u7136\u4e5f\u5305\u62ec\u6b63\u786e\u7684\u89e3\u51b3\u65b9\u6848\u3002\n\n// \u8003\u8651\u4ee5\u4e0b\u5728\u6240\u6709\u793a\u4f8b\u7a0b\u5e8f\u4e2d\u51fa\u73b0\u7684\u60c5\u51b5\uff1a\u6211\u4eec\u6709\u4e00\u4e2a\u4e09\u89d2\u5f62\u5bf9\u8c61\uff0c\u6211\u4eec\u6709\u4e00\u4e2a\u6709\u9650\u5143\u5bf9\u8c61\uff0c\u6211\u4eec\u8fd8\u6709\u4e00\u4e2aDoFHandler\u7c7b\u578b\u7684\u5bf9\u8c61\uff0c\u5b83\u540c\u65f6\u4f7f\u7528\u524d\u4e24\u4e2a\u5bf9\u8c61\u3002\u8fd9\u4e09\u4e2a\u5bf9\u8c61\u7684\u5bff\u547d\u4e0e\u5176\u4ed6\u5927\u591a\u6570\u5bf9\u8c61\u76f8\u6bd4\u90fd\u76f8\u5f53\u957f\uff1a\u5b83\u4eec\u57fa\u672c\u4e0a\u662f\u5728\u7a0b\u5e8f\u5f00\u59cb\u65f6\u6216\u5916\u5faa\u73af\u65f6\u8bbe\u7f6e\u7684\uff0c\u5e76\u5728\u6700\u540e\u88ab\u9500\u6bc1\u3002\u95ee\u9898\u662f\uff1a\u6211\u4eec\u80fd\u5426\u4fdd\u8bc1DoFHandler\u4f7f\u7528\u7684\u4e24\u4e2a\u5bf9\u8c61\u7684\u5bff\u547d\u81f3\u5c11\u4e0e\u5b83\u4eec\u88ab\u4f7f\u7528\u7684\u65f6\u95f4\u76f8\u540c\uff1f\u8fd9\u610f\u5473\u7740DoFHandler\u5fc5\u987b\u5bf9\u5176\u4ed6\u5bf9\u8c61\u7684\u9500\u6bc1\u60c5\u51b5\u6709\u4e00\u5b9a\u7684\u4e86\u89e3\u3002\n\n// \u6211\u4eec\u5c06\u5728\u8fd9\u91cc\u5c55\u793a\u5e93\u5982\u4f55\u8bbe\u6cd5\u627e\u51fa\u5bf9\u4e00\u4e2a\u5bf9\u8c61\u4ecd\u6709\u6d3b\u52a8\u7684\u5f15\u7528\uff0c\u5e76\u4e14\u4ece\u4f7f\u7528\u5bf9\u8c61\u7684\u89d2\u5ea6\u6765\u770b\uff0c\u8be5\u5bf9\u8c61\u4ecd\u7136\u6d3b\u7740\u3002\u57fa\u672c\u4e0a\uff0c\u8be5\u65b9\u6cd5\u662f\u6cbf\u7740\u4ee5\u4e0b\u601d\u8def\u8fdb\u884c\u7684\uff1a\u6240\u6709\u53d7\u5230\u8fd9\u79cd\u6f5c\u5728\u5371\u9669\u7684\u6307\u9488\u7684\u5bf9\u8c61\u90fd\u6765\u81ea\u4e00\u4e2a\u53eb\u505aSubscriptor\u7684\u7c7b\u3002\u4f8b\u5982\uff0cTriangulation\u3001DoFHandler\u548cFiniteElement\u7c7b\u7684\u4e00\u4e2a\u57fa\u7c7b\u90fd\u6d3e\u751f\u4e8eSubscriptor\u3002\u540e\u9762\u8fd9\u4e2a\u7c7b\u5e76\u6ca1\u6709\u63d0\u4f9b\u592a\u591a\u7684\u529f\u80fd\uff0c\u4f46\u662f\u5b83\u6709\u4e00\u4e2a\u5185\u7f6e\u7684\u8ba1\u6570\u5668\uff0c\u6211\u4eec\u53ef\u4ee5\u8ba2\u9605\u8fd9\u4e2a\u8ba1\u6570\u5668\uff0c\u56e0\u6b64\u8fd9\u4e2a\u7c7b\u7684\u540d\u5b57\u5c31\u53eb \"\u8ba2\u9605\u5668\"\u3002\u6bcf\u5f53\u6211\u4eec\u521d\u59cb\u5316\u4e00\u4e2a\u6307\u5411\u8be5\u5bf9\u8c61\u7684\u6307\u9488\u65f6\uff0c\u6211\u4eec\u53ef\u4ee5\u589e\u52a0\u5b83\u7684\u4f7f\u7528\u8ba1\u6570\u5668\uff0c\u800c\u5f53\u6211\u4eec\u79fb\u5f00\u6307\u9488\u6216\u4e0d\u518d\u9700\u8981\u5b83\u65f6\uff0c\u6211\u4eec\u518d\u51cf\u5c11\u8ba1\u6570\u5668\u3002\u8fd9\u6837\uff0c\u6211\u4eec\u5c31\u53ef\u4ee5\u968f\u65f6\u68c0\u67e5\u6709\u591a\u5c11\u4e2a\u5bf9\u8c61\u8fd8\u5728\u4f7f\u7528\u8be5\u5bf9\u8c61\u3002\u6b64\u5916\uff0c\u8be5\u7c7b\u9700\u8981\u77e5\u9053\u4e00\u4e2a\u6307\u9488\uff0c\u5b83\u53ef\u4ee5\u7528\u6765\u544a\u8bc9\u8ba2\u9605\u5bf9\u8c61\u5b83\u7684\u65e0\u6548\u6027\u3002\n\n// \u5982\u679c\u4e00\u4e2a\u4eceSubscriptor\u7c7b\u6d3e\u751f\u51fa\u6765\u7684\u5bf9\u8c61\u88ab\u9500\u6bc1\uff0c\u5b83\u4e5f\u5fc5\u987b\u8c03\u7528Subscriptor\u7c7b\u7684\u6790\u6784\u51fd\u6570\u3002\u5728\u8fd9\u4e2a\u6790\u6784\u5668\u4e2d\uff0c\u6211\u4eec\u4f7f\u7528\u5b58\u50a8\u7684\u6307\u9488\u544a\u8bc9\u6240\u6709\u8ba2\u9605\u7684\u5bf9\u8c61\u8be5\u5bf9\u8c61\u7684\u65e0\u6548\u6027\u3002\u5f53\u5bf9\u8c61\u51fa\u73b0\u5728\u79fb\u52a8\u8868\u8fbe\u5f0f\u7684\u53f3\u4fa7\u65f6\uff0c\u4e5f\u4f1a\u53d1\u751f\u540c\u6837\u7684\u60c5\u51b5\uff0c\u4e5f\u5c31\u662f\u8bf4\uff0c\u5728\u64cd\u4f5c\u540e\u5b83\u5c06\u4e0d\u518d\u5305\u542b\u6709\u6548\u7684\u5185\u5bb9\u3002\u5728\u8bd5\u56fe\u8bbf\u95ee\u88ab\u8ba2\u9605\u7684\u5bf9\u8c61\u4e4b\u524d\uff0c\u8ba2\u9605\u7c7b\u5e94\u8be5\u68c0\u67e5\u5b58\u50a8\u5728\u5176\u76f8\u5e94\u6307\u9488\u4e2d\u7684\u503c\u3002\n\n// \u8fd9\u6b63\u662fSmartPointer\u7c7b\u6b63\u5728\u505a\u7684\u4e8b\u60c5\u3002\u5b83\u57fa\u672c\u4e0a\u5c31\u50cf\u4e00\u4e2a\u6307\u9488\u4e00\u6837\uff0c\u4e5f\u5c31\u662f\u8bf4\uff0c\u5b83\u53ef\u4ee5\u88ab\u53d6\u6d88\u5f15\u7528\uff0c\u53ef\u4ee5\u88ab\u5206\u914d\u7ed9\u5176\u4ed6\u6307\u9488\uff0c\u7b49\u7b49\u3002\u9664\u6b64\u4e4b\u5916\uff0c\u5f53\u6211\u4eec\u8bd5\u56fe\u89e3\u9664\u5f15\u7528\u8fd9\u4e2a\u7c7b\u6240\u4ee3\u8868\u7684\u6307\u9488\u65f6\uff0c\u5b83\u4f7f\u7528\u4e0a\u9762\u63cf\u8ff0\u7684\u673a\u5236\u6765\u627e\u51fa\u8fd9\u4e2a\u6307\u9488\u662f\u5426\u662f\u60ac\u7a7a\u7684\u3002\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0c\u4f1a\u629b\u51fa\u4e00\u4e2a\u5f02\u5e38\u3002\n\n// \u5728\u672c\u4f8b\u7a0b\u5e8f\u4e2d\uff0c\u6211\u4eec\u5e0c\u671b\u4fdd\u62a4\u6709\u9650\u5143\u5bf9\u8c61\uff0c\u907f\u514d\u56e0\u67d0\u79cd\u539f\u56e0\u5bfc\u81f4\u6240\u6307\u5411\u7684\u6709\u9650\u5143\u5728\u4f7f\u7528\u4e2d\u88ab\u7834\u574f\u3002\u56e0\u6b64\uff0c\u6211\u4eec\u4f7f\u7528\u4e86\u4e00\u4e2a\u6307\u5411\u6709\u9650\u5143\u5bf9\u8c61\u7684SmartPointer\uff1b\u7531\u4e8e\u6709\u9650\u5143\u5bf9\u8c61\u5728\u6211\u4eec\u7684\u8ba1\u7b97\u4e2d\u5b9e\u9645\u4e0a\u4ece\u672a\u6539\u53d8\uff0c\u6211\u4eec\u4f20\u9012\u4e86\u4e00\u4e2aconst FiniteElement&lt;dim&gt;\u4f5c\u4e3aSmartPointer\u7c7b\u7684\u6a21\u677f\u53c2\u6570\u3002\u8bf7\u6ce8\u610f\uff0c\u8fd9\u6837\u58f0\u660e\u7684\u6307\u9488\u662f\u5728\u6784\u9020\u6c42\u89e3\u5bf9\u8c61\u65f6\u88ab\u5206\u914d\u7684\uff0c\u5e76\u5728\u9500\u6bc1\u65f6\u88ab\u9500\u6bc1\uff0c\u6240\u4ee5\u5bf9\u6709\u9650\u5143\u5bf9\u8c61\u9500\u6bc1\u7684\u9501\u5b9a\u8d2f\u7a7f\u4e86\u8fd9\u4e2aHelmholtzProblem\u5bf9\u8c61\u7684\u751f\u547d\u5468\u671f\u3002\n\n    Triangulation<dim> triangulation; \n    DoFHandler<dim>    dof_handler; \n\n    SmartPointer<const FiniteElement<dim>> fe; \n\n    AffineConstraints<double> 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// \u5012\u6570\u7b2c\u4e8c\u4e2a\u53d8\u91cf\u5b58\u50a8\u4e86\u4f20\u9012\u7ed9\u6784\u9020\u51fd\u6570\u7684\u7ec6\u5316\u6a21\u5f0f\u3002\u7531\u4e8e\u5b83\u53ea\u5728\u6784\u9020\u51fd\u6570\u4e2d\u8bbe\u7f6e\uff0c\u6211\u4eec\u53ef\u4ee5\u58f0\u660e\u8fd9\u4e2a\u53d8\u91cf\u4e3a\u5e38\u6570\uff0c\u4ee5\u907f\u514d\u6709\u4eba\u4e0d\u7531\u81ea\u4e3b\u5730\u8bbe\u7f6e\u5b83\uff08\u4f8b\u5982\u5728\u4e00\u4e2a \"if \"\u8bed\u53e5\u4e2d\uff0c==\u5076\u7136\u88ab\u5199\u6210=\uff09\u3002\n\n    const RefinementMode refinement_mode; \n\n// \u5bf9\u4e8e\u6bcf\u4e2a\u7ec6\u5316\u7ea7\u522b\uff0c\u4e00\u4e9b\u6570\u636e\uff08\u6bd4\u5982\u5355\u5143\u683c\u7684\u6570\u91cf\uff0c\u6216\u8005\u6570\u503c\u89e3\u7684L2\u8bef\u5dee\uff09\u5c06\u88ab\u751f\u6210\uff0c\u5e76\u5728\u4e4b\u540e\u6253\u5370\u51fa\u6765\u3002TableHandler\u53ef\u4ee5\u7528\u6765\u6536\u96c6\u6240\u6709\u8fd9\u4e9b\u6570\u636e\uff0c\u5e76\u5728\u8fd0\u884c\u7ed3\u675f\u540e\u4ee5\u7b80\u5355\u6587\u672c\u6216LaTeX\u683c\u5f0f\u7684\u8868\u683c\u8f93\u51fa\u3002\u8fd9\u91cc\u6211\u4eec\u4e0d\u4ec5\u4f7f\u7528TableHandler\uff0c\u8fd8\u4f7f\u7528\u4e86\u6d3e\u751f\u7c7bConvergenceTable\uff0c\u5b83\u8fd8\u53ef\u4ee5\u8bc4\u4f30\u6536\u655b\u7387\u3002\n\n    ConvergenceTable convergence_table; \n  }; \n// @sect3{The HelmholtzProblem class implementation}  \n// @sect4{HelmholtzProblem::HelmholtzProblem constructor}  \n\n// \u5728\u8fd9\u4e2a\u7c7b\u7684\u6784\u9020\u51fd\u6570\u4e2d\uff0c\u6211\u4eec\u53ea\u8bbe\u7f6e\u4f5c\u4e3a\u53c2\u6570\u4f20\u9012\u7684\u53d8\u91cf\uff0c\u5e76\u5c06DoF\u5904\u7406\u7a0b\u5e8f\u5bf9\u8c61\u4e0e\u4e09\u89d2\u5f62\uff08\u4e0d\u8fc7\u76ee\u524d\u662f\u7a7a\u7684\uff09\u76f8\u5173\u8054\u3002\n\n  template <int dim> \n  HelmholtzProblem<dim>::HelmholtzProblem(const FiniteElement<dim> &fe, \n                                          const RefinementMode refinement_mode) \n    : dof_handler(triangulation) \n    , fe(&fe) \n    , refinement_mode(refinement_mode) \n  {} \n// @sect4{HelmholtzProblem::setup_system}  \n\n// \u4e0b\u9762\u7684\u51fd\u6570\u8bbe\u7f6e\u4e86\u81ea\u7531\u5ea6\u3001\u77e9\u9635\u548c\u5411\u91cf\u7684\u5927\u5c0f\u7b49\u3002\u5b83\u7684\u5927\u90e8\u5206\u529f\u80fd\u5728\u524d\u9762\u7684\u4f8b\u5b50\u4e2d\u5df2\u7ecf\u5c55\u793a\u8fc7\u4e86\uff0c\u552f\u4e00\u4e0d\u540c\u7684\u662f\u5728\u7b2c\u4e00\u6b21\u5206\u914d\u81ea\u7531\u5ea6\u540e\u7acb\u5373\u8fdb\u884c\u91cd\u65b0\u7f16\u53f7\u7684\u6b65\u9aa4\u3002\n\n// \u91cd\u7f16\u81ea\u7531\u5ea6\u5e76\u4e0d\u96be\uff0c\u53ea\u8981\u4f60\u4f7f\u7528\u5e93\u4e2d\u7684\u4e00\u79cd\u7b97\u6cd5\u3002\u5b83\u53ea\u9700\u8981\u4e00\u884c\u4ee3\u7801\u3002\u8fd9\u65b9\u9762\u7684\u66f4\u591a\u4fe1\u606f\u53ef\u4ee5\u5728  step-2  \u4e2d\u627e\u5230\u3002\n\n// \u4f46\u662f\u8bf7\u6ce8\u610f\uff0c\u5f53\u4f60\u5bf9\u81ea\u7531\u5ea6\u8fdb\u884c\u91cd\u65b0\u7f16\u53f7\u65f6\uff0c\u4f60\u5fc5\u987b\u5728\u5206\u914d\u81ea\u7531\u5ea6\u540e\u7acb\u5373\u8fdb\u884c\uff0c\u56e0\u4e3a\u8bf8\u5982\u60ac\u7a7a\u8282\u70b9\u3001\u7a00\u758f\u6a21\u5f0f\u7b49\u90fd\u53d6\u51b3\u4e8e\u91cd\u65b0\u7f16\u53f7\u540e\u7684\u7edd\u5bf9\u6570\u3002\n\n// \u6211\u4eec\u5728\u8fd9\u91cc\u4ecb\u7ecd\u91cd\u65b0\u7f16\u53f7\u7684\u539f\u56e0\u662f\uff0c\u8fd9\u662f\u4e00\u4e2a\u76f8\u5bf9\u4fbf\u5b9c\u7684\u64cd\u4f5c\uff0c\u4f46\u5f80\u5f80\u6709\u4e00\u4e2a\u6709\u5229\u7684\u6548\u679c\u3002\u867d\u7136CG\u8fed\u4ee3\u672c\u8eab\u4e0e\u81ea\u7531\u5ea6\u7684\u5b9e\u9645\u6392\u5e8f\u65e0\u5173\uff0c\u4f46\u6211\u4eec\u5c06\u4f7f\u7528SSOR\u4f5c\u4e3a\u4e00\u4e2a\u9884\u5904\u7406\u7a0b\u5e8f\u3002SSOR\u4f1a\u7ecf\u8fc7\u6240\u6709\u7684\u81ea\u7531\u5ea6\uff0c\u5e76\u505a\u4e00\u4e9b\u53d6\u51b3\u4e8e\u4e4b\u524d\u53d1\u751f\u7684\u64cd\u4f5c\uff1b\u56e0\u6b64\uff0cSSOR\u64cd\u4f5c\u5e76\u4e0d\u72ec\u7acb\u4e8e\u81ea\u7531\u5ea6\u7684\u7f16\u53f7\uff0c\u800c\u4e14\u4f17\u6240\u5468\u77e5\uff0c\u5b83\u7684\u6027\u80fd\u4f1a\u901a\u8fc7\u4f7f\u7528\u91cd\u65b0\u7f16\u53f7\u6280\u672f\u5f97\u5230\u6539\u5584\u3002\u4e00\u4e2a\u5c0f\u5b9e\u9a8c\u8868\u660e\uff0c\u786e\u5b9e\u5982\u6b64\uff0c\u4f8b\u5982\uff0c\u7528\u8fd9\u91cc\u4f7f\u7528\u7684Q1\u7a0b\u5e8f\u8fdb\u884c\u81ea\u9002\u5e94\u7ec6\u5316\u7684\u7b2c\u4e94\u4e2a\u7ec6\u5316\u5468\u671f\u7684CG\u8fed\u4ee3\u6b21\u6570\uff0c\u5728\u6ca1\u6709\u91cd\u7f16\u53f7\u7684\u60c5\u51b5\u4e0b\u4e3a40\u6b21\uff0c\u800c\u5728\u91cd\u7f16\u53f7\u7684\u60c5\u51b5\u4e0b\u4e3a36\u6b21\u3002\u5bf9\u4e8e\u8fd9\u4e2a\u7a0b\u5e8f\u4e2d\u7684\u6240\u6709\u8ba1\u7b97\uff0c\u4e00\u822c\u90fd\u53ef\u4ee5\u89c2\u5bdf\u5230\u7c7b\u4f3c\u7684\u8282\u7701\u3002\n\n  template <int dim> \n  void HelmholtzProblem<dim>::setup_system() \n  { \n    dof_handler.distribute_dofs(*fe); \n    DoFRenumbering::Cuthill_McKee(dof_handler); \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    DynamicSparsityPattern dsp(dof_handler.n_dofs(), dof_handler.n_dofs()); \n    DoFTools::make_sparsity_pattern(dof_handler, dsp); \n    hanging_node_constraints.condense(dsp); \n    sparsity_pattern.copy_from(dsp); \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// @sect4{HelmholtzProblem::assemble_system}  \n\n// \u4e3a\u624b\u5934\u7684\u95ee\u9898\u7ec4\u88c5\u65b9\u7a0b\u7ec4\uff0c\u4e3b\u8981\u662f\u50cf\u4e4b\u524d\u7684\u4f8b\u5b50\u7a0b\u5e8f\u4e00\u6837\u3002\u7136\u800c\uff0c\u65e0\u8bba\u5982\u4f55\uff0c\u6709\u4e9b\u4e1c\u897f\u5df2\u7ecf\u6539\u53d8\u4e86\uff0c\u6240\u4ee5\u6211\u4eec\u5bf9\u8fd9\u4e2a\u51fd\u6570\u8fdb\u884c\u4e86\u76f8\u5f53\u5e7f\u6cdb\u7684\u8bc4\u8bba\u3002\n\n// \u5728\u8be5\u51fd\u6570\u7684\u9876\u90e8\uff0c\u4f60\u4f1a\u53d1\u73b0\u901a\u5e38\u7684\u5404\u79cd\u53d8\u91cf\u58f0\u660e\u3002\u4e0e\u4ee5\u524d\u7684\u7a0b\u5e8f\u76f8\u6bd4\uff0c\u91cd\u8981\u7684\u662f\u6211\u4eec\u5e0c\u671b\u89e3\u51b3\u7684\u95ee\u9898\u4e5f\u662f\u53cc\u4e8c\u6b21\u5143\u7684\uff0c\u56e0\u6b64\u5fc5\u987b\u4f7f\u7528\u8db3\u591f\u7cbe\u786e\u7684\u6b63\u4ea4\u516c\u5f0f\u3002\u6b64\u5916\uff0c\u6211\u4eec\u9700\u8981\u8ba1\u7b97\u9762\u7684\u79ef\u5206\uff0c\u5373 <code>dim-1</code> \u7ef4\u7684\u5bf9\u8c61\u3002\u90a3\u4e48\uff0c\u9762\u7684\u6b63\u4ea4\u516c\u5f0f\u7684\u58f0\u660e\u5c31\u5f88\u76f4\u63a5\u4e86\u3002\n\n  template <int dim> \n  void HelmholtzProblem<dim>::assemble_system() \n  { \n    QGauss<dim>     quadrature_formula(fe->degree + 1); \n    QGauss<dim - 1> face_quadrature_formula(fe->degree + 1); \n\n    const unsigned int n_q_points      = quadrature_formula.size(); \n    const unsigned int n_face_q_points = face_quadrature_formula.size(); \n\n    const unsigned int dofs_per_cell = fe->n_dofs_per_cell(); \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// \u7136\u540e\u6211\u4eec\u9700\u8981\u4e00\u4e9b\u5bf9\u8c61\u6765\u8bc4\u4f30\u6b63\u4ea4\u70b9\u4e0a\u7684\u5f62\u72b6\u51fd\u6570\u7684\u503c\u3001\u68af\u5ea6\u7b49\u3002\u867d\u7136\u770b\u8d77\u6765\u7528\u4e00\u4e2a\u5bf9\u8c61\u6765\u505a\u57df\u79ef\u5206\u548c\u9762\u79ef\u5206\u5e94\u8be5\u662f\u53ef\u884c\u7684\uff0c\u4f46\u662f\u6709\u4e00\u4e2a\u5fae\u5999\u7684\u533a\u522b\uff0c\u56e0\u4e3a\u57df\u79ef\u5206\u7684\u6743\u91cd\u5305\u62ec\u57df\u4e2d\u5355\u5143\u7684\u5ea6\u91cf\uff0c\u800c\u9762\u79ef\u5206\u7684\u6b63\u4ea4\u9700\u8981\u4f4e\u7ef4\u6d41\u5f62\u4e2d\u9762\u7684\u5ea6\u91cf\u3002\u5728\u5185\u90e8\uff0c\u8fd9\u4e24\u4e2a\u7c7b\u90fd\u6839\u690d\u4e8e\u4e00\u4e2a\u5171\u540c\u7684\u57fa\u7c7b\uff0c\u5b83\u5b8c\u6210\u4e86\u5927\u90e8\u5206\u5de5\u4f5c\uff0c\u5e76\u4e3a\u57df\u79ef\u5206\u548c\u9762\u79ef\u5206\u63d0\u4f9b\u4e86\u76f8\u540c\u7684\u63a5\u53e3\u3002\n\n// \u5bf9\u4e8e\u4ea5\u59c6\u970d\u5179\u65b9\u7a0b\u7684\u53cc\u7ebf\u6027\u5f62\u5f0f\u7684\u57df\u79ef\u5206\uff0c\u6211\u4eec\u9700\u8981\u8ba1\u7b97\u503c\u548c\u68af\u5ea6\uff0c\u4ee5\u53ca\u6b63\u4ea4\u70b9\u7684\u6743\u91cd\u3002\u6b64\u5916\uff0c\u6211\u4eec\u9700\u8981\u5b9e\u7ec6\u80de\u4e0a\u7684\u6b63\u4ea4\u70b9\uff08\u800c\u4e0d\u662f\u5355\u4f4d\u7ec6\u80de\u4e0a\u7684\u6b63\u4ea4\u70b9\uff09\u6765\u8bc4\u4f30\u53f3\u624b\u8fb9\u7684\u51fd\u6570\u3002\u6211\u4eec\u7528\u6765\u83b7\u53d6\u8fd9\u4e9b\u4fe1\u606f\u7684\u5bf9\u8c61\u662f\u4e4b\u524d\u8ba8\u8bba\u8fc7\u7684FEValues\u7c7b\u3002\n\n// \u5bf9\u4e8e\u9762\u79ef\u5206\uff0c\u6211\u4eec\u53ea\u9700\u8981\u5f62\u72b6\u51fd\u6570\u7684\u503c\u4ee5\u53ca\u6743\u91cd\u3002\u6211\u4eec\u8fd8\u9700\u8981\u5b9e\u5fc3\u5355\u5143\u4e0a\u7684\u6cd5\u5411\u91cf\u548c\u6b63\u4ea4\u70b9\uff0c\u56e0\u4e3a\u6211\u4eec\u8981\u4ece\u7cbe\u786e\u89e3\u5bf9\u8c61\u4e2d\u786e\u5b9aNeumann\u503c\uff08\u89c1\u4e0b\u6587\uff09\u3002\u7ed9\u6211\u4eec\u63d0\u4f9b\u8fd9\u4e9b\u4fe1\u606f\u7684\u7c7b\u88ab\u79f0\u4e3aFEFaceValues\u3002\n\n    FEValues<dim> fe_values(*fe, \n                            quadrature_formula, \n                            update_values | update_gradients | \n                              update_quadrature_points | update_JxW_values); \n\n    FEFaceValues<dim> fe_face_values(*fe, \n                                     face_quadrature_formula, \n                                     update_values | update_quadrature_points | \n                                       update_normal_vectors | \n                                       update_JxW_values); \n\n// \u7136\u540e\u6211\u4eec\u9700\u8981\u4e00\u4e9b\u4ece\u4ee5\u524d\u7684\u4f8b\u5b50\u4e2d\u5df2\u7ecf\u77e5\u9053\u7684\u5bf9\u8c61\u3002\u4e00\u4e2a\u8868\u793a\u53f3\u4fa7\u51fd\u6570\u7684\u5bf9\u8c61\uff0c\u5b83\u5728\u5355\u5143\u683c\u4e0a\u6b63\u4ea4\u70b9\u7684\u503c\uff0c\u5355\u5143\u683c\u77e9\u9635\u548c\u53f3\u4fa7\uff0c\u4ee5\u53ca\u5355\u5143\u683c\u4e0a\u81ea\u7531\u5ea6\u7684\u6307\u6570\u3002\n\n// \u8bf7\u6ce8\u610f\uff0c\u6211\u4eec\u5bf9\u53f3\u624b\u8fb9\u5bf9\u8c61\u7684\u64cd\u4f5c\u53ea\u662f\u67e5\u8be2\u6570\u636e\uff0c\u7edd\u4e0d\u4f1a\u6539\u53d8\u8be5\u5bf9\u8c61\u3002\u56e0\u6b64\u6211\u4eec\u53ef\u4ee5\u58f0\u660e\u5b83  <code>const</code>  \u3002\n\n    const RightHandSide<dim> right_hand_side; \n    std::vector<double>      rhs_values(n_q_points); \n\n// \u6700\u540e\u6211\u4eec\u5b9a\u4e49\u4e00\u4e2a\u8868\u793a\u7cbe\u786e\u89e3\u51fd\u6570\u7684\u5bf9\u8c61\u3002\u6211\u4eec\u5c06\u7528\u5b83\u6765\u8ba1\u7b97\u8fb9\u754c\u4e0a\u7684\u8bfa\u4f0a\u66fc\u503c\u3002\u901a\u5e38\u60c5\u51b5\u4e0b\uff0c\u6211\u4eec\u5f53\u7136\u4f1a\u4f7f\u7528\u4e00\u4e2a\u5355\u72ec\u7684\u5bf9\u8c61\u6765\u8ba1\u7b97\uff0c\u7279\u522b\u662f\u7531\u4e8e\u7cbe\u786e\u89e3\u901a\u5e38\u662f\u672a\u77e5\u7684\uff0c\u800c\u8bfa\u4f0a\u66fc\u503c\u662f\u89c4\u5b9a\u7684\u3002\u7136\u800c\uff0c\u6211\u4eec\u5c06\u6709\u70b9\u5077\u61d2\uff0c\u4f7f\u7528\u6211\u4eec\u5df2\u7ecf\u6709\u7684\u4fe1\u606f\u3002\u5f53\u7136\uff0c\u73b0\u5b9e\u751f\u6d3b\u4e2d\u7684\u7a0b\u5e8f\u4f1a\u5728\u8fd9\u91cc\u91c7\u53d6\u5176\u4ed6\u65b9\u5f0f\u3002\n\n    Solution<dim> exact_solution; \n\n// \u73b0\u5728\u662f\u6240\u6709\u5355\u5143\u683c\u7684\u4e3b\u5faa\u73af\u3002\u8fd9\u4e0e\u4e4b\u524d\u7684\u4f8b\u5b50\u57fa\u672c\u6ca1\u6709\u53d8\u5316\uff0c\u6240\u4ee5\u6211\u4eec\u53ea\u5bf9\u6709\u53d8\u5316\u7684\u5730\u65b9\u8fdb\u884c\u8bc4\u8bba\u3002\n\n    for (const auto &cell : dof_handler.active_cell_iterators()) \n      { \n        cell_matrix = 0.; \n        cell_rhs    = 0.; \n\n        fe_values.reinit(cell); \n\n        right_hand_side.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            { \n              for (unsigned int j = 0; j < dofs_per_cell; ++j) \n\n// \u7b2c\u4e00\u4ef6\u6539\u53d8\u7684\u4e8b\u60c5\u662f\u53cc\u7ebf\u6027\u5f62\u5f0f\u3002\u5b83\u73b0\u5728\u5305\u542b\u4e86\u4ea5\u59c6\u970d\u5179\u65b9\u7a0b\u7684\u9644\u52a0\u9879\u3002\n\n                cell_matrix(i, j) += \n                  ((fe_values.shape_grad(i, q_point) *     // grad phi_i(x_q) \n                      fe_values.shape_grad(j, q_point)     // grad phi_j(x_q) \n                    +                                      // \n                    fe_values.shape_value(i, q_point) *    // phi_i(x_q) \n                      fe_values.shape_value(j, q_point)) * // phi_j(x_q) \n                   fe_values.JxW(q_point));                // dx \n\n              cell_rhs(i) += (fe_values.shape_value(i, q_point) * // phi_i(x_q) \n                              rhs_values[q_point] *               // f(x_q) \n                              fe_values.JxW(q_point));            // dx \n            } \n\n// \u7136\u540e\u662f\u53f3\u624b\u8fb9\u7684\u7b2c\u4e8c\u9879\uff0c\u5373\u7b49\u9ad8\u7ebf\u79ef\u5206\u3002\u9996\u5148\u6211\u4eec\u8981\u627e\u51fa\u8fd9\u4e2a\u5355\u5143\u683c\u7684\u9762\u4e0e\u8fb9\u754c\u90e8\u5206Gamma2\u7684\u4ea4\u70b9\u662f\u5426\u4e3a\u975e\u96f6\u3002\u4e3a\u6b64\uff0c\u6211\u4eec\u5bf9\u6240\u6709\u9762\u8fdb\u884c\u5faa\u73af\uff0c\u68c0\u67e5\u5176\u8fb9\u754c\u6307\u793a\u5668\u662f\u5426\u7b49\u4e8e <code>1</code> \uff0c\u8fd9\u662f\u6211\u4eec\u5728\u4e0b\u9762\u7684 <code>run()</code> \u51fd\u6570\u4e2d\u4e3a\u7ec4\u6210Gamma2\u7684\u8fb9\u754c\u90e8\u5206\u6307\u5b9a\u7684\u503c\u3002(\u8fb9\u754c\u6307\u793a\u5668\u7684\u9ed8\u8ba4\u503c\u662f <code>0</code> \uff0c\u6240\u4ee5\u53ea\u6709\u5728\u6211\u4eec\u660e\u786e\u8bbe\u7f6e\u7684\u60c5\u51b5\u4e0b\uff0c\u9762\u7684\u6307\u793a\u5668\u624d\u80fd\u7b49\u4e8e <code>1</code> \u3002)\n\n        for (const auto &face : cell->face_iterators()) \n          if (face->at_boundary() && (face->boundary_id() == 1)) \n            { \n\n// \u5982\u679c\u6211\u4eec\u6765\u5230\u8fd9\u91cc\uff0c\u90a3\u4e48\u6211\u4eec\u5df2\u7ecf\u627e\u5230\u4e86\u4e00\u4e2a\u5c5e\u4e8eGamma2\u7684\u5916\u90e8\u9762\u3002\u63a5\u4e0b\u6765\uff0c\u6211\u4eec\u5fc5\u987b\u8ba1\u7b97\u5f62\u72b6\u51fd\u6570\u7684\u503c\u548c\u5176\u4ed6\u6570\u91cf\uff0c\u8fd9\u4e9b\u90fd\u662f\u6211\u4eec\u5728\u8ba1\u7b97\u8f6e\u5ed3\u79ef\u5206\u65f6\u9700\u8981\u7684\u3002\u8fd9\u662f\u7528 <code>reinit</code> \u51fd\u6570\u5b8c\u6210\u7684\uff0c\u6211\u4eec\u5df2\u7ecf\u4eceFEValue\u7c7b\u4e2d\u77e5\u9053\u4e86\u3002\n\n              fe_face_values.reinit(cell, face); \n\n// \u7136\u540e\uff0c\u6211\u4eec\u53ef\u4ee5\u901a\u8fc7\u5728\u6240\u6709\u7684\u6b63\u4ea4\u70b9\u4e0a\u8fdb\u884c\u5faa\u73af\u6765\u8fdb\u884c\u79ef\u5206\u3002        \u5728\u6bcf\u4e2a\u6b63\u4ea4\u70b9\u4e0a\uff0c\u6211\u4eec\u9996\u5148\u8ba1\u7b97\u6cd5\u7ebf\u5bfc\u6570\u7684\u503c\u3002\u6211\u4eec\u4f7f\u7528\u7cbe\u786e\u89e3\u7684\u68af\u5ea6\u548c\u4ece <code>fe_face_values</code> \u5bf9\u8c61\u4e2d\u83b7\u5f97\u7684\u5f53\u524d\u6b63\u4ea4\u70b9\u5904\u7684\u9762\u7684\u6cd5\u5411\u91cf\u6765\u8fdb\u884c\u8ba1\u7b97\u3002\u7136\u540e\u7528\u5b83\u6765\u8ba1\u7b97\u8fd9\u4e2a\u9762\u5bf9\u53f3\u624b\u8fb9\u7684\u989d\u5916\u8d21\u732e\u3002\n\n              for (unsigned int q_point = 0; q_point < n_face_q_points; \n                   ++q_point) \n                { \n                  const double neumann_value = \n                    (exact_solution.gradient( \n                       fe_face_values.quadrature_point(q_point)) * \n                     fe_face_values.normal_vector(q_point)); \n\n                  for (unsigned int i = 0; i < dofs_per_cell; ++i) \n                    cell_rhs(i) += \n                      (fe_face_values.shape_value(i, q_point) * // phi_i(x_q) \n                       neumann_value *                          // g(x_q) \n                       fe_face_values.JxW(q_point));            // dx \n                } \n            } \n\n// \u73b0\u5728\u6211\u4eec\u6709\u4e86\u672c\u5355\u5143\u7684\u8d21\u732e\uff0c\u6211\u4eec\u53ef\u4ee5\u628a\u5b83\u8f6c\u79fb\u5230\u5168\u5c40\u77e9\u9635\u548c\u53f3\u624b\u8fb9\u7684\u5411\u91cf\uff0c\u5c31\u50cf\u4e4b\u524d\u7684\u4f8b\u5b50\u4e00\u6837\u3002\n\n        cell->get_dof_indices(local_dof_indices); \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      } \n\n// \u540c\u6837\uff0c\u5bf9\u8fb9\u754c\u503c\u7684\u6d88\u9664\u548c\u5904\u7406\u4e5f\u5728\u524d\u9762\u663e\u793a\u8fc7\u3002\n\n// \u7136\u800c\uff0c\u6211\u4eec\u6ce8\u610f\u5230\uff0c\u73b0\u5728\u6211\u4eec\u63d2\u503c\u8fb9\u754c\u503c\u7684\u8fb9\u754c\u6307\u6807\uff08\u7531 <code>interpolate_boundary_values</code> \u7684\u7b2c\u4e8c\u4e2a\u53c2\u6570\u8868\u793a\uff09\u4e0d\u518d\u4ee3\u8868\u6574\u4e2a\u8fb9\u754c\u4e86\u3002\u76f8\u53cd\uff0c\u5b83\u662f\u6211\u4eec\u6ca1\u6709\u6307\u5b9a\u5176\u4ed6\u6307\u6807\u7684\u90a3\u90e8\u5206\u8fb9\u754c\uff08\u89c1\u4e0b\u6587\uff09\u3002\u56e0\u6b64\uff0c\u8fb9\u754c\u4e0a\u4e0d\u5c5e\u4e8eGamma1\u7684\u81ea\u7531\u5ea6\u88ab\u6392\u9664\u5728\u8fb9\u754c\u503c\u7684\u63d2\u503c\u4e4b\u5916\uff0c\u5c31\u50cf\u6211\u4eec\u5e0c\u671b\u7684\u90a3\u6837\u3002\n\n    hanging_node_constraints.condense(system_matrix); \n    hanging_node_constraints.condense(system_rhs); \n\n    std::map<types::global_dof_index, double> boundary_values; \n    VectorTools::interpolate_boundary_values(dof_handler, \n                                             0, \n                                             Solution<dim>(), \n                                             boundary_values); \n    MatrixTools::apply_boundary_values(boundary_values, \n                                       system_matrix, \n                                       solution, \n                                       system_rhs); \n  } \n// @sect4{HelmholtzProblem::solve}  \n\n// \u89e3\u65b9\u7a0b\u7ec4\u7684\u65b9\u6cd5\u4e0e\u4e4b\u524d\u4e00\u6837\u3002\n\n  template <int dim> \n  void HelmholtzProblem<dim>::solve() \n  { \n    SolverControl            solver_control(1000, 1e-12); \n    SolverCG<Vector<double>> cg(solver_control); \n\n    PreconditionSSOR<SparseMatrix<double>> preconditioner; \n    preconditioner.initialize(system_matrix, 1.2); \n\n    cg.solve(system_matrix, solution, system_rhs, preconditioner); \n\n    hanging_node_constraints.distribute(solution); \n  } \n// @sect4{HelmholtzProblem::refine_grid}  \n\n// \u73b0\u5728\u662f\u505a\u7f51\u683c\u7ec6\u5316\u7684\u51fd\u6570\u3002\u6839\u636e\u4f20\u9012\u7ed9\u6784\u9020\u51fd\u6570\u7684\u7ec6\u5316\u6a21\u5f0f\uff0c\u6211\u4eec\u8fdb\u884c\u5168\u5c40\u6216\u9002\u5e94\u6027\u7ec6\u5316\u3002\n\n// \u5168\u5c40\u7ec6\u5316\u5f88\u7b80\u5355\uff0c\u6240\u4ee5\u6ca1\u6709\u4ec0\u4e48\u53ef\u8bc4\u8bba\u7684\u3002 \u5728\u9002\u5e94\u6027\u7ec6\u5316\u7684\u60c5\u51b5\u4e0b\uff0c\u6211\u4eec\u4f7f\u7528\u7684\u51fd\u6570\u548c\u7c7b\u4e0e\u524d\u9762\u7684\u4f8b\u5b50\u7a0b\u5e8f\u76f8\u540c\u3002\u8bf7\u6ce8\u610f\uff0c\u6211\u4eec\u53ef\u4ee5\u5c06\u8bfa\u4f0a\u66fc\u8fb9\u754c\u4e0e\u8fea\u91cc\u5207\u7279\u8fb9\u754c\u533a\u522b\u5bf9\u5f85\uff0c\u4e8b\u5b9e\u4e0a\u5728\u8fd9\u91cc\u4e5f\u5e94\u8be5\u8fd9\u6837\u505a\uff0c\u56e0\u4e3a\u6211\u4eec\u5728\u90e8\u5206\u8fb9\u754c\u4e0a\u6709\u8bfa\u4f0a\u66fc\u8fb9\u754c\u6761\u4ef6\uff0c\u4f46\u662f\u7531\u4e8e\u6211\u4eec\u5728\u8fd9\u91cc\u6ca1\u6709\u63cf\u8ff0\u8bfa\u4f0a\u66fc\u503c\u7684\u51fd\u6570\uff08\u6211\u4eec\u53ea\u662f\u5728\u7ec4\u88c5\u77e9\u9635\u65f6\u4ece\u7cbe\u786e\u89e3\u4e2d\u6784\u9020\u8fd9\u4e9b\u503c\uff09\uff0c\u6211\u4eec\u7701\u7565\u4e86\u8fd9\u4e2a\u7ec6\u8282\uff0c\u5c3d\u7ba1\u4ee5\u4e25\u683c\u6b63\u786e\u7684\u65b9\u5f0f\u505a\u8fd9\u4e9b\u5e76\u4e0d\u96be\u6dfb\u52a0\u3002\n\n// \u5728\u5f00\u5173\u7684\u6700\u540e\uff0c\u6211\u4eec\u6709\u4e00\u4e2a\u770b\u8d77\u6765\u7a0d\u5fae\u6709\u70b9\u5947\u602a\u7684\u9ed8\u8ba4\u60c5\u51b5\uff1a\u4e00\u4e2a <code>Assert</code> statement with a <code>false</code> \u6761\u4ef6\u3002\u7531\u4e8e <code>Assert</code> \u5b8f\u5728\u6761\u4ef6\u4e3a\u5047\u7684\u65f6\u5019\u4f1a\u5f15\u53d1\u4e00\u4e2a\u9519\u8bef\uff0c\u8fd9\u610f\u5473\u7740\u53ea\u8981\u6211\u4eec\u78b0\u5230\u8fd9\u4e2a\u8bed\u53e5\uff0c\u7a0b\u5e8f\u5c31\u4f1a\u88ab\u4e2d\u6b62\u3002\u8fd9\u662f\u6545\u610f\u7684\u3002\u73b0\u5728\u6211\u4eec\u53ea\u5b9e\u73b0\u4e86\u4e24\u79cd\u7ec6\u5316\u7b56\u7565\uff08\u5168\u5c40\u6027\u548c\u9002\u5e94\u6027\uff09\uff0c\u4f46\u6709\u4eba\u53ef\u80fd\u60f3\u589e\u52a0\u7b2c\u4e09\u79cd\u7b56\u7565\uff08\u4f8b\u5982\uff0c\u5177\u6709\u4e0d\u540c\u7ec6\u5316\u6807\u51c6\u7684\u9002\u5e94\u6027\uff09\uff0c\u5e76\u5728\u51b3\u5b9a\u7ec6\u5316\u6a21\u5f0f\u7684\u679a\u4e3e\u4e2d\u589e\u52a0\u7b2c\u4e09\u4e2a\u6210\u5458\u3002\u5982\u679c\u4e0d\u662fswitch\u8bed\u53e5\u7684\u9ed8\u8ba4\u60c5\u51b5\uff0c\u8fd9\u4e2a\u51fd\u6570\u4f1a\u7b80\u5355\u5730\u8fd0\u884c\u5230\u7ed3\u675f\u800c\u4e0d\u505a\u4efb\u4f55\u4e8b\u60c5\u3002\u8fd9\u5f88\u53ef\u80fd\u4e0d\u662f\u539f\u610f\u3002\u56e0\u6b64\uff0c\u5728deal.II\u5e93\u4e2d\uff0c\u4f60\u4f1a\u53d1\u73b0\u4e00\u4e2a\u9632\u5fa1\u6027\u7684\u7f16\u7a0b\u6280\u672f\uff0c\u90a3\u5c31\u662f\u603b\u662f\u6709\u9ed8\u8ba4\u7684\u4e2d\u6b62\u6848\u4f8b\uff0c\u4ee5\u786e\u4fdd\u5728switch\u8bed\u53e5\u4e2d\u5217\u51fa\u6848\u4f8b\u65f6\u6ca1\u6709\u8003\u8651\u7684\u503c\u6700\u7ec8\u88ab\u6293\u4f4f\uff0c\u5e76\u8feb\u4f7f\u7a0b\u5e8f\u5458\u6dfb\u52a0\u4ee3\u7801\u6765\u5904\u7406\u5b83\u4eec\u3002\u6211\u4eec\u8fd8\u5c06\u5728\u4e0b\u9762\u7684\u5176\u4ed6\u5730\u65b9\u4f7f\u7528\u540c\u6837\u7684\u6280\u672f\u3002\n\n  template <int dim> \n  void HelmholtzProblem<dim>::refine_grid() \n  { \n    switch (refinement_mode) \n      { \n        case global_refinement: \n          { \n            triangulation.refine_global(1); \n            break; \n          } \n\n        case adaptive_refinement: \n          { \n            Vector<float> estimated_error_per_cell( \n              triangulation.n_active_cells()); \n\n            KellyErrorEstimator<dim>::estimate( \n              dof_handler, \n              QGauss<dim - 1>(fe->degree + 1), \n              std::map<types::boundary_id, const Function<dim> *>(), \n              solution, \n              estimated_error_per_cell); \n\n            GridRefinement::refine_and_coarsen_fixed_number( \n              triangulation, estimated_error_per_cell, 0.3, 0.03); \n\n            triangulation.execute_coarsening_and_refinement(); \n\n            break; \n          } \n\n        default: \n          { \n            Assert(false, ExcNotImplemented()); \n          } \n      } \n  } \n// @sect4{HelmholtzProblem::process_solution}  \n\n// \u6700\u540e\uff0c\u6211\u4eec\u60f3\u5728\u8ba1\u7b97\u51fa\u89e3\u51b3\u65b9\u6848\u540e\u5bf9\u5176\u8fdb\u884c\u5904\u7406\u3002\u4e3a\u6b64\uff0c\u6211\u4eec\u7528\u5404\u79cd\uff08\u534a\uff09\u51c6\u5219\u5bf9\u8bef\u5dee\u8fdb\u884c\u79ef\u5206\uff0c\u5e76\u751f\u6210\u8868\u683c\uff0c\u8fd9\u4e9b\u8868\u683c\u4ee5\u540e\u5c06\u88ab\u7528\u6765\u4ee5\u6f02\u4eae\u7684\u683c\u5f0f\u663e\u793a\u5bf9\u8fde\u7eed\u89e3\u7684\u6536\u655b\u60c5\u51b5\u3002\n\n  template <int dim> \n  void HelmholtzProblem<dim>::process_solution(const unsigned int cycle) \n  { \n\n// \u6211\u4eec\u7684\u7b2c\u4e00\u4e2a\u4efb\u52a1\u662f\u8ba1\u7b97\u8bef\u5dee\u51c6\u5219\u3002\u4e3a\u4e86\u6574\u5408\u8ba1\u7b97\u51fa\u7684\u6570\u503c\u89e3\u548c\u8fde\u7eed\u89e3\u4e4b\u95f4\u7684\u5dee\u5f02\uff08\u7531\u672c\u6587\u4ef6\u9876\u90e8\u5b9a\u4e49\u7684Solution\u7c7b\u63cf\u8ff0\uff09\uff0c\u6211\u4eec\u9996\u5148\u9700\u8981\u4e00\u4e2a\u5411\u91cf\u6765\u4fdd\u5b58\u6bcf\u4e2a\u5355\u5143\u7684\u8bef\u5dee\u51c6\u5219\u3002\u7531\u4e8e16\u4f4d\u6570\u7684\u7cbe\u5ea6\u5bf9\u8fd9\u4e9b\u6570\u91cf\u6765\u8bf4\u5e76\u4e0d\u90a3\u4e48\u91cd\u8981\uff0c\u6211\u4eec\u901a\u8fc7\u4f7f\u7528 <code>float</code> \u800c\u4e0d\u662f <code>double</code> \u503c\u6765\u8282\u7701\u4e00\u4e9b\u5185\u5b58\u3002\n\n// \u4e0b\u4e00\u6b65\u662f\u4f7f\u7528\u5e93\u4e2d\u7684\u4e00\u4e2a\u51fd\u6570\u6765\u8ba1\u7b97\u6bcf\u4e2a\u5355\u5143\u7684L2\u51c6\u5219\u7684\u8bef\u5dee\u3002 \u6211\u4eec\u5fc5\u987b\u5c06DoF\u5904\u7406\u7a0b\u5e8f\u5bf9\u8c61\u3001\u4fdd\u5b58\u6570\u503c\u89e3\u7684\u8282\u70b9\u503c\u7684\u5411\u91cf\u3001\u4f5c\u4e3a\u51fd\u6570\u5bf9\u8c61\u7684\u8fde\u7eed\u89e3\u3001\u5b83\u5e94\u5c06\u6bcf\u4e2a\u5355\u5143\u4e0a\u7684\u8bef\u5dee\u89c4\u8303\u653e\u5165\u7684\u5411\u91cf\u3001\u8ba1\u7b97\u8be5\u89c4\u8303\u7684\u6b63\u4ea4\u89c4\u5219\uff0c\u4ee5\u53ca\u8981\u4f7f\u7528\u7684\u89c4\u8303\u7c7b\u578b\u4f20\u9012\u7ed9\u5b83\u3002\u8fd9\u91cc\uff0c\u6211\u4eec\u4f7f\u7528\u9ad8\u65af\u516c\u5f0f\uff0c\u5728\u6bcf\u4e2a\u7a7a\u95f4\u65b9\u5411\u4e0a\u6709\u4e09\u4e2a\u70b9\uff0c\u5e76\u8ba1\u7b97L2\u89c4\u8303\u3002\n\n// \u6700\u540e\uff0c\u6211\u4eec\u60f3\u5f97\u5230\u5168\u5c40L2\u51c6\u5219\u3002\u8fd9\u5f53\u7136\u53ef\u4ee5\u901a\u8fc7\u5bf9\u6bcf\u4e2a\u5355\u5143\u683c\u4e0a\u7684\u89c4\u8303\u7684\u5e73\u65b9\u6c42\u548c\uff0c\u7136\u540e\u53d6\u8be5\u503c\u7684\u5e73\u65b9\u6839\u6765\u5f97\u5230\u3002\u8fd9\u76f8\u5f53\u4e8e\u53d6\u6bcf\u4e2a\u5355\u5143\u683c\u4e0a\u7684\u89c4\u8303\u5411\u91cf\u7684l2\uff08\u5c0f\u5199 <code>l</code>  \uff09\u89c4\u8303\u3002\n\n    Vector<float> difference_per_cell(triangulation.n_active_cells()); \n    VectorTools::integrate_difference(dof_handler, \n                                      solution, \n                                      Solution<dim>(), \n                                      difference_per_cell, \n                                      QGauss<dim>(fe->degree + 1), \n                                      VectorTools::L2_norm); \n    const double L2_error = \n      VectorTools::compute_global_error(triangulation, \n                                        difference_per_cell, \n                                        VectorTools::L2_norm); \n\n// \u901a\u8fc7\u540c\u6837\u7684\u7a0b\u5e8f\uff0c\u6211\u4eec\u53ef\u4ee5\u5f97\u5230H1\u534a\u6b63\u6001\u3002\u6211\u4eec\u91cd\u65b0\u4f7f\u7528 <code>difference_per_cell</code> \u5411\u91cf\uff0c\u56e0\u4e3a\u5728\u8ba1\u7b97\u4e86\u4e0a\u9762\u7684 <code>L2_error</code> \u53d8\u91cf\u540e\uff0c\u5b83\u4e0d\u518d\u88ab\u4f7f\u7528\u3002\u5168\u5c40 $H^1$ \u534a\u6b63\u6001\u8bef\u5dee\u7684\u8ba1\u7b97\u65b9\u6cd5\u662f\uff1a\u53d6\u6bcf\u4e2a\u5355\u5143\u683c\u4e0a\u7684\u8bef\u5dee\u7684\u5e73\u65b9\u548c\uff0c\u7136\u540e\u53d6\u5176\u5e73\u65b9\u6839--\u8fd9\u4e2a\u64cd\u4f5c\u7531 VectorTools::compute_global_error. \u65b9\u4fbf\u5730\u6267\u884c\u3002\n    VectorTools::integrate_difference(dof_handler, \n                                      solution, \n                                      Solution<dim>(), \n                                      difference_per_cell, \n                                      QGauss<dim>(fe->degree + 1), \n                                      VectorTools::H1_seminorm); \n    const double H1_error = \n      VectorTools::compute_global_error(triangulation, \n                                        difference_per_cell, \n                                        VectorTools::H1_seminorm); \n\n// \u6700\u540e\uff0c\u6211\u4eec\u8ba1\u7b97\u51fa\u6700\u5927\u6cd5\u7ebf\u3002\u5f53\u7136\uff0c\u6211\u4eec\u5b9e\u9645\u4e0a\u4e0d\u80fd\u8ba1\u7b97\u57df\u4e2d*\u6240\u6709*\u70b9\u4e0a\u7684\u771f\u6b63\u7684\u6700\u5927\u8bef\u5dee\uff0c\u800c\u53ea\u80fd\u8ba1\u7b97\u6709\u9650\u7684\u8bc4\u4f30\u70b9\u4e0a\u7684\u6700\u5927\u8bef\u5dee\uff0c\u4e3a\u4e86\u65b9\u4fbf\u8d77\u89c1\uff0c\u6211\u4eec\u4ecd\u7136\u79f0\u4e4b\u4e3a \"\u6b63\u4ea4\u70b9\"\uff0c\u5e76\u7528\u4e00\u4e2a\u6b63\u4ea4\u7c7b\u578b\u7684\u5bf9\u8c61\u6765\u8868\u793a\uff0c\u5c3d\u7ba1\u6211\u4eec\u5b9e\u9645\u4e0a\u6ca1\u6709\u8fdb\u884c\u4efb\u4f55\u79ef\u5206\u3002\n\n// \u7136\u540e\u662f\u6211\u4eec\u60f3\u5728\u54ea\u4e9b\u70b9\u4e0a\u7cbe\u786e\u5730\u8fdb\u884c\u8bc4\u4f30\u7684\u95ee\u9898\u3002\u4e8b\u5b9e\u8bc1\u660e\uff0c\u6211\u4eec\u5f97\u5230\u7684\u7ed3\u679c\u76f8\u5f53\u654f\u611f\u5730\u53d6\u51b3\u4e8e\u6240\u4f7f\u7528\u7684 \"\u6b63\u4ea4 \"\u70b9\u3002\u8fd8\u6709\u4e00\u4e2a\u8d85\u878d\u5408\u7684\u95ee\u9898\u3002\u5728\u67d0\u4e9b\u7f51\u683c\u4e0a\uff0c\u5bf9\u4e8e\u591a\u9879\u5f0f\u7a0b\u5ea6 $k\\ge 2$ \uff0c\u6709\u9650\u5143\u89e3\u51b3\u65b9\u6848\u5728\u8282\u70b9\u70b9\u4ee5\u53caGauss-Lobatto\u70b9\u4e0a\u7279\u522b\u7cbe\u786e\uff0c\u6bd4\u968f\u673a\u9009\u62e9\u7684\u70b9\u8981\u7cbe\u786e\u5f97\u591a\u3002(\u53c2\u89c1 @cite Li2019 \u548c\u7b2c1.2\u8282\u7684\u8ba8\u8bba\u548c\u53c2\u8003\u6587\u732e\uff0c\u4ee5\u4e86\u89e3\u66f4\u591a\u8fd9\u65b9\u9762\u7684\u4fe1\u606f)\u3002\u6362\u53e5\u8bdd\u8bf4\uff0c\u5982\u679c\u6211\u4eec\u6709\u5174\u8da3\u627e\u5230\u6700\u5927\u7684\u5dee\u503c $u(\\mathbf x)-u_h(\\mathbf x)$ \uff0c\u90a3\u4e48\u6211\u4eec\u5e94\u8be5\u770b\u4e00\u4e0b $\\mathbf x$ \uff0c\u8fd9\u4e9b\u70b9\u7279\u522b\u4e0d\u5c5e\u4e8e\u8fd9\u79cd \"\u7279\u6b8a \"\u7684\u70b9\uff0c\u800c\u4e14\u6211\u4eec\u7279\u522b\u4e0d\u5e94\u8be5\u7528`QGauss(fe->degree+1)`\u6765\u5b9a\u4e49\u6211\u4eec\u8bc4\u4f30\u7684\u5730\u65b9\u3002\u76f8\u53cd\uff0c\u6211\u4eec\u4f7f\u7528\u4e00\u4e2a\u7279\u6b8a\u7684\u6b63\u4ea4\u89c4\u5219\uff0c\u8be5\u89c4\u5219\u662f\u901a\u8fc7\u68af\u5f62\u89c4\u5219\u8fed\u4ee3\u6709\u9650\u5143\u7684\u5ea6\u6570\u4e58\u4ee52\u518d\u52a0\u4e0a\u6bcf\u4e2a\u7a7a\u95f4\u65b9\u5411\u76841\u800c\u5f97\u5230\u7684\u3002\u8bf7\u6ce8\u610f\uff0cQIterated\u7c7b\u7684\u6784\u9020\u51fd\u6570\u9700\u8981\u4e00\u4e2a\u4e00\u7ef4\u6b63\u4ea4\u89c4\u5219\u548c\u4e00\u4e2a\u6570\u5b57\uff0c\u8fd9\u4e2a\u6570\u5b57\u544a\u8bc9\u5b83\u5728\u6bcf\u4e2a\u7a7a\u95f4\u65b9\u5411\u91cd\u590d\u8fd9\u4e2a\u89c4\u5219\u7684\u9891\u7387\u3002\n\n// \u4f7f\u7528\u8fd9\u4e2a\u7279\u6b8a\u7684\u6b63\u4ea4\u89c4\u5219\uff0c\u6211\u4eec\u5c31\u53ef\u4ee5\u5c1d\u8bd5\u627e\u5230\u6bcf\u4e2a\u5355\u5143\u7684\u6700\u5927\u8bef\u5dee\u3002\u6700\u540e\uff0c\u6211\u4eec\u901a\u8fc7\u8c03\u7528 VectorTools::compute_global_error. \u6765\u8ba1\u7b97\u6bcf\u4e2a\u5355\u5143\u4e0a\u7684L\u65e0\u7a77\u5927\u8bef\u5dee\u7684\u5168\u5c40L\u65e0\u7a77\u5927\u8bef\u5dee\u3002\n    const QTrapezoid<1>  q_trapez; \n    const QIterated<dim> q_iterated(q_trapez, fe->degree * 2 + 1); \n    VectorTools::integrate_difference(dof_handler, \n                                      solution, \n                                      Solution<dim>(), \n                                      difference_per_cell, \n                                      q_iterated, \n                                      VectorTools::Linfty_norm); \n    const double Linfty_error = \n      VectorTools::compute_global_error(triangulation, \n                                        difference_per_cell, \n                                        VectorTools::Linfty_norm); \n\n// \u5728\u6240\u6709\u8fd9\u4e9b\u9519\u8bef\u88ab\u8ba1\u7b97\u51fa\u6765\u4e4b\u540e\uff0c\u6211\u4eec\u6700\u7ec8\u5199\u51fa\u4e00\u4e9b\u8f93\u51fa\u3002\u6b64\u5916\uff0c\u6211\u4eec\u901a\u8fc7\u6307\u5b9a\u5217\u7684\u952e\u548c\u503c\u5c06\u91cd\u8981\u7684\u6570\u636e\u6dfb\u52a0\u5230TableHandler\u4e2d\u3002 \u6ce8\u610f\uff0c\u6ca1\u6709\u5fc5\u8981\u4e8b\u5148\u5b9a\u4e49\u5217\u7684\u952e -- \u53ea\u9700\u6dfb\u52a0\u503c\u5373\u53ef\uff0c\u5217\u5c06\u6309\u7167\u7b2c\u4e00\u6b21\u6dfb\u52a0\u503c\u7684\u987a\u5e8f\u88ab\u5f15\u5165\u5230\u8868\u4e2d\u3002\n\n    const unsigned int n_active_cells = triangulation.n_active_cells(); \n    const unsigned int n_dofs         = dof_handler.n_dofs(); \n\n    std::cout << \"Cycle \" << cycle << ':' << std::endl \n              << \"   Number of active cells:       \" << n_active_cells \n              << std::endl \n              << \"   Number of degrees of freedom: \" << n_dofs << 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\", L2_error); \n    convergence_table.add_value(\"H1\", H1_error); \n    convergence_table.add_value(\"Linfty\", Linfty_error); \n  } \n// @sect4{HelmholtzProblem::run}  \n\n// \u548c\u524d\u9762\u7684\u4f8b\u5b50\u7a0b\u5e8f\u4e00\u6837\uff0c <code>run</code> \u51fd\u6570\u63a7\u5236\u6267\u884c\u7684\u6d41\u7a0b\u3002\u57fa\u672c\u5e03\u5c40\u4e0e\u524d\u9762\u7684\u4f8b\u5b50\u4e00\u6837\uff1a\u5728\u8fde\u7eed\u7ec6\u5316\u7684\u7f51\u683c\u4e0a\u6709\u4e00\u4e2a\u5916\u5faa\u73af\uff0c\u5728\u8fd9\u4e2a\u5faa\u73af\u4e2d\u9996\u5148\u662f\u95ee\u9898\u7684\u8bbe\u7f6e\uff0c\u7ec4\u88c5\u7ebf\u6027\u7cfb\u7edf\uff0c\u6c42\u89e3\uff0c\u548c\u540e\u5904\u7406\u3002\n\n// \u4e3b\u5faa\u73af\u7684\u7b2c\u4e00\u4e2a\u4efb\u52a1\u662f\u521b\u5efa\u548c\u7ec6\u5316\u7f51\u683c\u3002\u8fd9\u548c\u524d\u9762\u7684\u4f8b\u5b50\u4e00\u6837\uff0c\u552f\u4e00\u7684\u533a\u522b\u662f\u6211\u4eec\u60f3\u628a\u8fb9\u754c\u7684\u4e00\u90e8\u5206\u6807\u8bb0\u4e3a\u8bfa\u4f0a\u66fc\u578b\uff0c\u800c\u4e0d\u662f\u8fea\u91cc\u5e0c\u578b\u3002\n\n// \u4e3a\u6b64\uff0c\u6211\u4eec\u5c06\u4f7f\u7528\u4ee5\u4e0b\u60ef\u4f8b\u3002\u5c5e\u4e8eGamma1\u7684\u9762\u5c06\u6709\u8fb9\u754c\u6307\u793a\u5668 <code>0</code> \uff08\u8fd9\u662f\u9ed8\u8ba4\u7684\uff0c\u6240\u4ee5\u6211\u4eec\u4e0d\u9700\u8981\u660e\u786e\u8bbe\u7f6e\uff09\uff0c\u5c5e\u4e8eGamma2\u7684\u9762\u5c06\u4f7f\u7528 <code>1</code> \u4f5c\u4e3a\u8fb9\u754c\u6307\u793a\u5668\u3002 \u4e3a\u4e86\u8bbe\u7f6e\u8fd9\u4e9b\u503c\uff0c\u6211\u4eec\u5728\u6240\u6709\u5355\u5143\u683c\u4e0a\u5faa\u73af\uff0c\u7136\u540e\u5728\u7ed9\u5b9a\u5355\u5143\u683c\u7684\u6240\u6709\u9762\u4e0a\u5faa\u73af\uff0c\u68c0\u67e5\u5b83\u662f\u5426\u662f\u6211\u4eec\u60f3\u7528Gamma2\u8868\u793a\u7684\u8fb9\u754c\u7684\u4e00\u90e8\u5206\uff0c\u5982\u679c\u662f\uff0c\u5219\u5c06\u5176\u8fb9\u754c\u6307\u793a\u5668\u8bbe\u7f6e\u4e3a <code>1</code>  \u3002\u5728\u672c\u7a0b\u5e8f\u4e2d\uff0c\u6211\u4eec\u8ba4\u4e3a\u5de6\u8fb9\u548c\u5e95\u90e8\u7684\u8fb9\u754c\u662fGamma2\u3002\u6211\u4eec\u901a\u8fc7\u8be2\u95ee\u4e00\u4e2a\u9762\u7684\u4e2d\u70b9\u7684x\u6216y\u5750\u6807\uff08\u5373\u5411\u91cf\u5206\u91cf0\u548c1\uff09\u662f\u5426\u7b49\u4e8e-1\u6765\u786e\u5b9a\u4e00\u4e2a\u9762\u662f\u5426\u662f\u8be5\u8fb9\u754c\u7684\u4e00\u90e8\u5206\uff0c\u4f46\u6211\u4eec\u5fc5\u987b\u7ed9\u51fa\u4e00\u4e9b\u5c0f\u7684\u56de\u65cb\u4f59\u5730\uff0c\u56e0\u4e3a\u6bd4\u8f83\u5728\u4e2d\u95f4\u8ba1\u7b97\u4e2d\u4f1a\u6709\u56db\u820d\u4e94\u5165\u7684\u6d6e\u70b9\u6570\u662f\u4e0d\u7a33\u5b9a\u7684\u3002\n\n// \u503c\u5f97\u6ce8\u610f\u7684\u662f\uff0c\u6211\u4eec\u5fc5\u987b\u5728\u8fd9\u91cc\u5bf9\u6240\u6709\u7684\u5355\u5143\u683c\u8fdb\u884c\u5faa\u73af\uff0c\u800c\u4e0d\u4ec5\u4ec5\u662f\u6d3b\u52a8\u5355\u5143\u683c\u3002\u539f\u56e0\u662f\u5728\u7ec6\u5316\u65f6\uff0c\u65b0\u521b\u5efa\u7684\u9762\u4f1a\u7ee7\u627f\u5176\u7236\u9762\u7684\u8fb9\u754c\u6307\u6807\u3002\u5982\u679c\u6211\u4eec\u73b0\u5728\u53ea\u8bbe\u7f6e\u6d3b\u52a8\u9762\u7684\u8fb9\u754c\u6307\u793a\u5668\uff0c\u7c97\u5316\u4e00\u4e9b\u5355\u5143\u5e76\u5728\u4ee5\u540e\u7ec6\u5316\u5b83\u4eec\uff0c\u5b83\u4eec\u5c06\u518d\u6b21\u62e5\u6709\u6211\u4eec\u6ca1\u6709\u4fee\u6539\u7684\u7236\u5355\u5143\u7684\u8fb9\u754c\u6307\u793a\u5668\uff0c\u800c\u4e0d\u662f\u6211\u4eec\u60f3\u8981\u7684\u90a3\u4e2a\u3002\u56e0\u6b64\uff0c\u6211\u4eec\u5fc5\u987b\u6539\u53d8Gamma2\u4e0a\u6240\u6709\u5355\u5143\u7684\u9762\u7684\u8fb9\u754c\u6307\u6807\uff0c\u65e0\u8bba\u5b83\u4eec\u662f\u5426\u5904\u4e8e\u6d3b\u52a8\u72b6\u6001\u3002\u53e6\u5916\uff0c\u6211\u4eec\u5f53\u7136\u4e5f\u53ef\u4ee5\u5728\u6700\u7c97\u7684\u7f51\u683c\u4e0a\u5b8c\u6210\u8fd9\u9879\u5de5\u4f5c\uff08\u5373\u5728\u7b2c\u4e00\u4e2a\u7ec6\u5316\u6b65\u9aa4\u4e4b\u524d\uff09\uff0c\u4e4b\u540e\u624d\u7ec6\u5316\u7f51\u683c\u3002\n\n  template <int dim> \n  void HelmholtzProblem<dim>::run() \n  { \n    const unsigned int n_cycles = \n      (refinement_mode == global_refinement) ? 5 : 9; \n    for (unsigned int cycle = 0; cycle < n_cycles; ++cycle) \n      { \n        if (cycle == 0) \n          { \n            GridGenerator::hyper_cube(triangulation, -1., 1.); \n            triangulation.refine_global(3); \n\n            for (const auto &cell : triangulation.cell_iterators()) \n              for (const auto &face : cell->face_iterators()) \n                { \n                  const auto center = face->center(); \n                  if ((std::fabs(center(0) - (-1.0)) < 1e-12) || \n                      (std::fabs(center(1) - (-1.0)) < 1e-12)) \n                    face->set_boundary_id(1); \n                } \n          } \n        else \n          refine_grid(); \n\n// \u63a5\u4e0b\u6765\u7684\u6b65\u9aa4\u5728\u524d\u9762\u7684\u4f8b\u5b50\u4e2d\u5df2\u7ecf\u77e5\u9053\u4e86\u3002\u8fd9\u4e3b\u8981\u662f\u6bcf\u4e2a\u6709\u9650\u5143\u7a0b\u5e8f\u7684\u57fa\u672c\u8bbe\u7f6e\u3002\n\n        setup_system(); \n\n        assemble_system(); \n        solve(); \n\n// \u5728\u8fd9\u4e00\u8fde\u4e32\u7684\u51fd\u6570\u8c03\u7528\u4e2d\uff0c\u6700\u540e\u4e00\u6b65\u901a\u5e38\u662f\u5bf9\u81ea\u5df1\u611f\u5174\u8da3\u7684\u6570\u91cf\u7684\u8ba1\u7b97\u89e3\u8fdb\u884c\u8bc4\u4f30\u3002\u8fd9\u5728\u4e0b\u9762\u7684\u51fd\u6570\u4e2d\u5b8c\u6210\u3002\u7531\u4e8e\u8be5\u51fd\u6570\u4ea7\u751f\u7684\u8f93\u51fa\u663e\u793a\u4e86\u5f53\u524d\u7ec6\u5316\u6b65\u9aa4\u7684\u7f16\u53f7\uff0c\u6211\u4eec\u5c06\u8fd9\u4e2a\u7f16\u53f7\u4f5c\u4e3a\u4e00\u4e2a\u53c2\u6570\u4f20\u9012\u3002\n\n        process_solution(cycle); \n      } \n// @sect5{Output of graphical data}  \n\n// \u5728\u6700\u540e\u4e00\u6b21\u8fed\u4ee3\u540e\uff0c\u6211\u4eec\u5728\u6700\u7ec6\u7684\u7f51\u683c\u4e0a\u8f93\u51fa\u89e3\u51b3\u65b9\u6848\u3002\u8fd9\u662f\u7528\u4e0b\u9762\u7684\u8bed\u53e5\u5e8f\u5217\u5b8c\u6210\u7684\uff0c\u6211\u4eec\u5728\u4ee5\u524d\u7684\u4f8b\u5b50\u4e2d\u5df2\u7ecf\u8ba8\u8bba\u8fc7\u4e86\u3002\u7b2c\u4e00\u6b65\u662f\u751f\u6210\u4e00\u4e2a\u5408\u9002\u7684\u6587\u4ef6\u540d\uff08\u8fd9\u91cc\u79f0\u4e3a <code>vtk_filename</code> \uff0c\u56e0\u4e3a\u6211\u4eec\u60f3\u4ee5VTK\u683c\u5f0f\u8f93\u51fa\u6570\u636e\uff1b\u6211\u4eec\u6dfb\u52a0\u524d\u7f00\u4ee5\u533a\u5206\u8be5\u6587\u4ef6\u540d\u4e0e\u4e0b\u9762\u5176\u4ed6\u8f93\u51fa\u6587\u4ef6\u7684\u6587\u4ef6\u540d\uff09\u3002\u5728\u8fd9\u91cc\uff0c\u6211\u4eec\u901a\u8fc7\u7f51\u683c\u7ec6\u5316\u7b97\u6cd5\u6765\u589e\u52a0\u540d\u79f0\uff0c\u548c\u4e0a\u9762\u4e00\u6837\uff0c\u6211\u4eec\u8981\u786e\u4fdd\u5728\u589e\u52a0\u4e86\u53e6\u4e00\u79cd\u7ec6\u5316\u65b9\u6cd5\u800c\u6ca1\u6709\u901a\u8fc7\u4e0b\u9762\u7684switch\u8bed\u53e5\u6765\u5904\u7406\u7684\u60c5\u51b5\u4e0b\uff0c\u4e2d\u6b62\u7a0b\u5e8f\u3002\n\n    std::string vtk_filename; \n    switch (refinement_mode) \n      { \n        case global_refinement: \n          vtk_filename = \"solution-global\"; \n          break; \n        case adaptive_refinement: \n          vtk_filename = \"solution-adaptive\"; \n          break; \n        default: \n          Assert(false, ExcNotImplemented()); \n      } \n\n// \u6211\u4eec\u7528\u4e00\u4e2a\u540e\u7f00\u6765\u589e\u52a0\u6587\u4ef6\u540d\uff0c\u8868\u793a\u6211\u4eec\u5728\u8ba1\u7b97\u4e2d\u4f7f\u7528\u7684\u6709\u9650\u5143\u3002\u4e3a\u6b64\uff0c\u6709\u9650\u5143\u57fa\u7c7b\u5c06\u6bcf\u4e2a\u5750\u6807\u53d8\u91cf\u4e2d\u5f62\u72b6\u51fd\u6570\u7684\u6700\u5927\u591a\u9879\u5f0f\u7a0b\u5ea6\u5b58\u50a8\u4e3a\u4e00\u4e2a\u53d8\u91cf <code>degree</code> \uff0c\u6211\u4eec\u5728\u5207\u6362\u8bed\u53e5\u4e2d\u4f7f\u7528\uff08\u6ce8\u610f\uff0c\u53cc\u7ebf\u6027\u5f62\u72b6\u51fd\u6570\u7684\u591a\u9879\u5f0f\u7a0b\u5ea6\u5b9e\u9645\u4e0a\u662f2\uff0c\u56e0\u4e3a\u5b83\u4eec\u5305\u542b\u672f\u8bed <code>x*y</code> \uff1b\u4f46\u662f\uff0c\u6bcf\u4e2a\u5750\u6807\u53d8\u91cf\u7684\u591a\u9879\u5f0f\u7a0b\u5ea6\u4ecd\u7136\u53ea\u67091\uff09\u3002\u6211\u4eec\u518d\u6b21\u4f7f\u7528\u540c\u6837\u7684\u9632\u5fa1\u6027\u7f16\u7a0b\u6280\u672f\u6765\u9632\u6b62\u591a\u9879\u5f0f\u9636\u6570\u5177\u6709\u610f\u5916\u503c\u7684\u60c5\u51b5\uff0c\u5728switch\u8bed\u53e5\u7684\u9ed8\u8ba4\u5206\u652f\u4e2d\u4f7f\u7528 <code>Assert (false, ExcNotImplemented())</code> \u8fd9\u4e2a\u6210\u8bed\u3002\n\n    switch (fe->degree) \n      { \n        case 1: \n          vtk_filename += \"-q1\"; \n          break; \n        case 2: \n          vtk_filename += \"-q2\"; \n          break; \n\n        default: \n          Assert(false, ExcNotImplemented()); \n      } \n\n// \u4e00\u65e6\u6211\u4eec\u6709\u4e86\u8f93\u51fa\u6587\u4ef6\u7684\u57fa\u672c\u540d\u79f0\uff0c\u6211\u4eec\u5c31\u4e3aVTK\u8f93\u51fa\u6dfb\u52a0\u4e00\u4e2a\u5408\u9002\u7684\u6269\u5c55\u540d\uff0c\u6253\u5f00\u4e00\u4e2a\u6587\u4ef6\uff0c\u5e76\u5c06\u89e3\u51b3\u65b9\u6848\u7684\u5411\u91cf\u6dfb\u52a0\u5230\u5c06\u8fdb\u884c\u5b9e\u9645\u8f93\u51fa\u7684\u5bf9\u8c61\u4e2d\u3002\n\n    vtk_filename += \".vtk\"; \n    std::ofstream output(vtk_filename); \n\n    DataOut<dim> data_out; \n    data_out.attach_dof_handler(dof_handler); \n    data_out.add_data_vector(solution, \"solution\"); \n\n// \u73b0\u5728\u50cf\u4ee5\u524d\u4e00\u6837\u5efa\u7acb\u4e2d\u95f4\u683c\u5f0f\u662f\u4e0b\u4e00\u6b65\u3002\u6211\u4eec\u5728\u8fd9\u91cc\u518d\u4ecb\u7ecd\u4e00\u4e0bdeal.II\u7684\u4e00\u4e2a\u7279\u70b9\u3002\u5176\u80cc\u666f\u5982\u4e0b\uff1a\u5728\u8fd9\u4e2a\u51fd\u6570\u7684\u4e00\u4e9b\u8fd0\u884c\u4e2d\uff0c\u6211\u4eec\u4f7f\u7528\u4e86\u53cc\u4e8c\u6b21\u5143\u7684\u6709\u9650\u5143\u3002\u7136\u800c\uff0c\u7531\u4e8e\u51e0\u4e4e\u6240\u6709\u7684\u8f93\u51fa\u683c\u5f0f\u90fd\u53ea\u652f\u6301\u53cc\u7ebf\u6027\u6570\u636e\uff0c\u6240\u4ee5\u6570\u636e\u53ea\u5199\u6210\u4e86\u53cc\u7ebf\u6027\uff0c\u4fe1\u606f\u56e0\u6b64\u800c\u4e22\u5931\u3002 \u5f53\u7136\uff0c\u6211\u4eec\u4e0d\u80fd\u6539\u53d8\u56fe\u5f62\u7a0b\u5e8f\u63a5\u53d7\u5176\u8f93\u5165\u7684\u683c\u5f0f\uff0c\u4f46\u6211\u4eec\u53ef\u4ee5\u7528\u4e0d\u540c\u7684\u65b9\u5f0f\u6765\u5199\u6570\u636e\uff0c\u8fd9\u6837\u6211\u4eec\u5c31\u80fd\u66f4\u63a5\u8fd1\u4e8e\u56db\u6b21\u65b9\u8fd1\u4f3c\u4e2d\u7684\u4fe1\u606f\u3002\u4f8b\u5982\uff0c\u6211\u4eec\u53ef\u4ee5\u628a\u6bcf\u4e2a\u5355\u5143\u5199\u6210\u56db\u4e2a\u5b50\u5355\u5143\uff0c\u6bcf\u4e2a\u5b50\u5355\u5143\u90fd\u6709\u53cc\u7ebf\u6570\u636e\uff0c\u8fd9\u6837\u6211\u4eec\u5728\u4e09\u89d2\u56fe\u4e2d\u7684\u6bcf\u4e2a\u5355\u5143\u90fd\u6709\u4e5d\u4e2a\u6570\u636e\u70b9\u3002\u5f53\u7136\uff0c\u56fe\u5f62\u7a0b\u5e8f\u663e\u793a\u7684\u8fd9\u4e9b\u6570\u636e\u4ecd\u7136\u53ea\u662f\u53cc\u7ebf\u6027\u7684\uff0c\u4f46\u81f3\u5c11\u6211\u4eec\u53c8\u7ed9\u51fa\u4e86\u4e00\u4e9b\u6211\u4eec\u62e5\u6709\u7684\u4fe1\u606f\u3002\n\n// \u4e3a\u4e86\u5141\u8bb8\u5728\u6bcf\u4e2a\u5b9e\u9645\u5355\u5143\u4e2d\u5199\u5165\u591a\u4e2a\u5b50\u5355\u5143\uff0c <code>build_patches</code> \u51fd\u6570\u63a5\u53d7\u4e00\u4e2a\u53c2\u6570\uff08\u9ed8\u8ba4\u4e3a <code>1</code>  \uff0c\u8fd9\u5c31\u662f\u4e3a\u4ec0\u4e48\u4f60\u5728\u4e4b\u524d\u7684\u4f8b\u5b50\u4e2d\u6ca1\u6709\u770b\u5230\u8fd9\u4e2a\u53c2\u6570\uff09\u3002\u8fd9\u4e2a\u53c2\u6570\u8868\u793a\u6bcf\u4e2a\u7a7a\u95f4\u65b9\u5411\u4e0a\u7684\u6bcf\u4e2a\u5355\u5143\u5e94\u88ab\u7ec6\u5206\u4e3a\u591a\u5c11\u4e2a\u5b50\u5355\u5143\u6765\u8f93\u51fa\u3002\u4f8b\u5982\uff0c\u5982\u679c\u4f60\u7ed9\u51fa  <code>2</code>  \uff0c\u8fd9\u5c06\u5bfc\u81f4\u4e8c\u7ef4\u76844\u4e2a\u5355\u5143\u548c\u4e09\u7ef4\u76848\u4e2a\u5355\u5143\u3002\u5bf9\u4e8e\u4e8c\u6b21\u5143\u5143\u7d20\uff0c\u6bcf\u4e2a\u7a7a\u95f4\u65b9\u5411\u7684\u4e24\u4e2a\u5b50\u5355\u5143\u663e\u7136\u662f\u6b63\u786e\u7684\u9009\u62e9\uff0c\u6240\u4ee5\u8fd9\u5c31\u662f\u6211\u4eec\u6240\u9009\u62e9\u7684\u3002\u4e00\u822c\u6765\u8bf4\uff0c\u5bf9\u4e8e\u591a\u9879\u5f0f\u9636\u7684\u5143\u7d20 <code>q</code>, we use <code>q</code> \u7ec6\u5206\uff0c\u5143\u7d20\u7684\u987a\u5e8f\u4e5f\u662f\u6309\u7167\u4e0a\u8ff0\u65b9\u5f0f\u786e\u5b9a\u7684\u3002\n\n// \u6709\u4e86\u8fd9\u6837\u751f\u6210\u7684\u4e2d\u95f4\u683c\u5f0f\uff0c\u6211\u4eec\u5c31\u53ef\u4ee5\u5b9e\u9645\u5199\u5165\u56fe\u5f62\u8f93\u51fa\u4e86\u3002\n\n    data_out.build_patches(fe->degree); \n    data_out.write_vtk(output); \n// @sect5{Output of convergence tables}  \n\n// \u5728\u56fe\u5f62\u8f93\u51fa\u4e4b\u540e\uff0c\u6211\u4eec\u8fd8\u60f3\u4ece\u6211\u4eec\u5728  <code>process_solution</code>  \u4e2d\u8fdb\u884c\u7684\u8bef\u5dee\u8ba1\u7b97\u4e2d\u751f\u6210\u8868\u683c\u3002\u5728\u90a3\u91cc\uff0c\u6211\u4eec\u7528\u6bcf\u4e2a\u7ec6\u5316\u6b65\u9aa4\u7684\u5355\u5143\u683c\u6570\u91cf\u4ee5\u53ca\u4e0d\u540c\u89c4\u8303\u7684\u8bef\u5dee\u6765\u586b\u5145\u4e00\u4e2a\u8868\u683c\u5bf9\u8c61\u3002\n\n// \u4e3a\u4e86\u4f7f\u8fd9\u4e9b\u6570\u636e\u6709\u66f4\u597d\u7684\u6587\u672c\u8f93\u51fa\uff0c\u6211\u4eec\u53ef\u80fd\u60f3\u8bbe\u7f6e\u8f93\u51fa\u65f6\u5199\u5165\u6570\u503c\u7684\u7cbe\u5ea6\u3002\u6211\u4eec\u4f7f\u75283\u4f4d\u6570\uff0c\u8fd9\u5bf9\u8bef\u5dee\u89c4\u8303\u6765\u8bf4\u901a\u5e38\u662f\u8db3\u591f\u7684\u3002\u9ed8\u8ba4\u60c5\u51b5\u4e0b\uff0c\u6570\u636e\u662f\u4ee5\u5b9a\u70b9\u7b26\u53f7\u5199\u5165\u7684\u3002\u7136\u800c\uff0c\u5bf9\u4e8e\u4eba\u4eec\u60f3\u770b\u5230\u7684\u79d1\u5b66\u7b26\u53f7\u7684\u5217\uff0c\u53e6\u4e00\u4e2a\u51fd\u6570\u8c03\u7528\u8bbe\u7f6e\u4e86 <code>scientific_flag</code> to <code>true</code>  \uff0c\u5bfc\u81f4\u6570\u5b57\u7684\u6d6e\u70b9\u8868\u793a\u3002\n\n    convergence_table.set_precision(\"L2\", 3); \n    convergence_table.set_precision(\"H1\", 3); \n    convergence_table.set_precision(\"Linfty\", 3); \n\n    convergence_table.set_scientific(\"L2\", true); \n    convergence_table.set_scientific(\"H1\", true); \n    convergence_table.set_scientific(\"Linfty\", true); \n\n// \u5bf9\u4e8e\u8f93\u51fa\u5230LaTeX\u6587\u4ef6\u7684\u8868\u683c\uff0c\u9ed8\u8ba4\u7684\u5217\u7684\u6807\u9898\u662f\u4f5c\u4e3a\u53c2\u6570\u7ed9 <code>add_value</code> \u51fd\u6570\u7684\u952e\u3002\u8981\u60f3\u62e5\u6709\u4e0d\u540c\u4e8e\u9ed8\u8ba4\u7684TeX\u6807\u9898\uff0c\u4f60\u53ef\u4ee5\u901a\u8fc7\u4ee5\u4e0b\u51fd\u6570\u8c03\u7528\u6765\u6307\u5b9a\u5b83\u4eec\u3002\u6ce8\u610f\uff0c`\\\\'\u88ab\u7f16\u8bd1\u5668\u7b80\u5316\u4e3a`\\'\uff0c\u8fd9\u6837\uff0c\u771f\u6b63\u7684TeX\u6807\u9898\u5c31\u662f\uff0c\u4f8b\u5982\uff0c` $L^\\infty$  -error'\u3002\n\n    convergence_table.set_tex_caption(\"cells\", \"\\\\# cells\"); \n    convergence_table.set_tex_caption(\"dofs\", \"\\\\# dofs\"); \n    convergence_table.set_tex_caption(\"L2\", \"$L^2$-error\"); \n    convergence_table.set_tex_caption(\"H1\", \"$H^1$-error\"); \n    convergence_table.set_tex_caption(\"Linfty\", \"$L^\\\\infty$-error\"); \n\n// \u6700\u540e\uff0c\u8868\u683c\u4e2d\u6bcf\u4e00\u5217\u7684\u9ed8\u8ba4LaTeX\u683c\u5f0f\u662f`c'\uff08\u5c45\u4e2d\uff09\u3002\u8981\u6307\u5b9a\u4e00\u4e2a\u4e0d\u540c\u7684\uff08\u5982`\u53f3'\uff09\uff0c\u53ef\u4ee5\u4f7f\u7528\u4ee5\u4e0b\u51fd\u6570\u3002\n\n    convergence_table.set_tex_format(\"cells\", \"r\"); \n    convergence_table.set_tex_format(\"dofs\", \"r\"); \n\n// \u5728\u8fd9\u4e4b\u540e\uff0c\u6211\u4eec\u7ec8\u4e8e\u53ef\u4ee5\u628a\u8868\u5199\u5230\u6807\u51c6\u8f93\u51fa\u6d41 <code>std::cout</code> \uff08\u5728\u591a\u5199\u4e00\u884c\u7a7a\u884c\u4e4b\u540e\uff0c\u4f7f\u4e8b\u60c5\u770b\u8d77\u6765\u66f4\u6f02\u4eae\uff09\u3002\u8bf7\u6ce8\u610f\uff0c\u6587\u672c\u683c\u5f0f\u7684\u8f93\u51fa\u662f\u975e\u5e38\u7b80\u5355\u7684\uff0c\u6807\u9898\u53ef\u80fd\u4e0d\u4f1a\u76f4\u63a5\u6253\u5370\u5728\u7279\u5b9a\u7684\u5217\u4e0a\u9762\u3002\n\n    std::cout << std::endl; \n    convergence_table.write_text(std::cout); \n\n// \u8be5\u8868\u4e5f\u53ef\u4ee5\u5199\u6210LaTeX\u6587\u4ef6\u3002 \u5728\u8c03\u7528 \"latex filename \"\u548c\u4f8b\u5982 \"xdvi filename \"\u540e\uff0c\u53ef\u4ee5\u67e5\u770b\uff08\u5f88\u597d\u7684\uff09\u683c\u5f0f\u5316\u7684\u8868\u683c\uff0c\u5176\u4e2dfilename\u662f\u6211\u4eec\u73b0\u5728\u8981\u5199\u5165\u8f93\u51fa\u7684\u6587\u4ef6\u540d\u3002\u6211\u4eec\u6784\u5efa\u6587\u4ef6\u540d\u7684\u65b9\u6cd5\u548c\u4ee5\u524d\u4e00\u6837\uff0c\u4f46\u6709\u4e00\u4e2a\u4e0d\u540c\u7684\u524d\u7f00 \"error\"\u3002\n\n    std::string error_filename = \"error\"; \n    switch (refinement_mode) \n      { \n        case global_refinement: \n          error_filename += \"-global\"; \n          break; \n        case adaptive_refinement: \n          error_filename += \"-adaptive\"; \n          break; \n        default: \n          Assert(false, ExcNotImplemented()); \n      } \n\n    switch (fe->degree) \n      { \n        case 1: \n          error_filename += \"-q1\"; \n          break; \n        case 2: \n          error_filename += \"-q2\"; \n          break; \n        default: \n          Assert(false, ExcNotImplemented()); \n      } \n\n    error_filename += \".tex\"; \n    std::ofstream error_table_file(error_filename); \n\n    convergence_table.write_tex(error_table_file); \n// @sect5{Further table manipulations}  \n\n// \u5728\u5168\u5c40\u7ec6\u5316\u7684\u60c5\u51b5\u4e0b\uff0c\u8f93\u51fa\u6536\u655b\u7387\u4e5f\u53ef\u80fd\u662f\u6709\u610f\u4e49\u7684\u3002\u8fd9\u53ef\u4ee5\u901a\u8fc7ConvergenceTable\u63d0\u4f9b\u7684\u6bd4\u5e38\u89c4TableHandler\u7684\u529f\u80fd\u6765\u5b9e\u73b0\u3002\u7136\u800c\uff0c\u6211\u4eec\u53ea\u4e3a\u5168\u5c40\u7ec6\u5316\u505a\u8fd9\u4ef6\u4e8b\uff0c\u56e0\u4e3a\u5bf9\u4e8e\u81ea\u9002\u5e94\u7ec6\u5316\u6765\u8bf4\uff0c\u786e\u5b9a\u50cf\u6536\u655b\u987a\u5e8f\u8fd9\u6837\u7684\u4e8b\u60c5\u662f\u6bd4\u8f83\u9ebb\u70e6\u7684\u3002\u5728\u6b64\uff0c\u6211\u4eec\u8fd8\u5c55\u793a\u4e86\u4e00\u4e9b\u53ef\u4ee5\u7528\u8868\u6765\u505a\u7684\u5176\u4ed6\u4e8b\u60c5\u3002\n\n    if (refinement_mode == global_refinement) \n      { \n\n// \u7b2c\u4e00\u4ef6\u4e8b\u662f\uff0c\u4eba\u4eec\u53ef\u4ee5\u5c06\u5355\u4e2a\u5217\u7ec4\u5408\u5728\u4e00\u8d77\uff0c\u5f62\u6210\u6240\u8c13\u7684\u8d85\u7ea7\u5217\u3002\u4ece\u672c\u8d28\u4e0a\u8bb2\uff0c\u8fd9\u4e9b\u5217\u4fdd\u6301\u4e0d\u53d8\uff0c\u4f46\u88ab\u5206\u7ec4\u7684\u90a3\u4e9b\u5217\u5c06\u5f97\u5230\u4e00\u4e2a\u8d2f\u7a7f\u4e00\u7ec4\u4e2d\u6240\u6709\u5217\u7684\u6807\u9898\u3002\u4f8b\u5982\uff0c\u8ba9\u6211\u4eec\u628a \"\u5468\u671f \"\u548c \"\u5355\u5143\u683c \"\u4e24\u5217\u5408\u5e76\u6210\u4e00\u4e2a\u540d\u4e3a \"n\u5355\u5143\u683c \"\u7684\u8d85\u7ea7\u5217\u3002\n\n        convergence_table.add_column_to_supercolumn(\"cycle\", \"n cells\"); \n        convergence_table.add_column_to_supercolumn(\"cells\", \"n cells\"); \n\n// \u63a5\u4e0b\u6765\uff0c\u6ca1\u6709\u5fc5\u8981\u603b\u662f\u8f93\u51fa\u6240\u6709\u7684\u5217\uff0c\u6216\u8005\u6309\u7167\u5b83\u4eec\u5728\u8fd0\u884c\u8fc7\u7a0b\u4e2d\u6700\u521d\u6dfb\u52a0\u7684\u987a\u5e8f\u3002\u9009\u62e9\u548c\u91cd\u65b0\u6392\u5217\u5217\u7684\u5de5\u4f5c\u65b9\u5f0f\u5982\u4e0b\uff08\u6ce8\u610f\uff0c\u8fd9\u5305\u62ec\u8d85\u7ea7\u5217\uff09\u3002\n\n        std::vector<std::string> new_order; \n        new_order.emplace_back(\"n cells\"); \n        new_order.emplace_back(\"H1\"); \n        new_order.emplace_back(\"L2\"); \n        convergence_table.set_column_order(new_order); \n\n// \u5bf9\u4e8e\u5728\u8fd9\u4e4b\u524d\u53d1\u751f\u5728ConvergenceTable\u4e0a\u7684\u4e00\u5207\uff0c\u4f7f\u7528\u4e00\u4e2a\u7b80\u5355\u7684TableHandler\u5c31\u8db3\u591f\u4e86\u3002\u4e8b\u5b9e\u4e0a\uff0cConvergenceTable\u662f\u7531TableHandler\u6d3e\u751f\u51fa\u6765\u7684\uff0c\u4f46\u5b83\u63d0\u4f9b\u4e86\u81ea\u52a8\u8bc4\u4f30\u6536\u655b\u7387\u7684\u989d\u5916\u529f\u80fd\u3002\u4f8b\u5982\uff0c\u4e0b\u9762\u662f\u6211\u4eec\u5982\u4f55\u8ba9\u8868\u8ba1\u7b97\u51cf\u5c11\u7387\u548c\u6536\u655b\u7387\uff08\u6536\u655b\u7387\u662f\u51cf\u5c11\u7387\u7684\u4e8c\u8fdb\u5236\u5bf9\u6570\uff09\u3002\n\n        convergence_table.evaluate_convergence_rates( \n          \"L2\", ConvergenceTable::reduction_rate); \n        convergence_table.evaluate_convergence_rates( \n          \"L2\", ConvergenceTable::reduction_rate_log2); \n        convergence_table.evaluate_convergence_rates( \n          \"H1\", ConvergenceTable::reduction_rate); \n        convergence_table.evaluate_convergence_rates( \n          \"H1\", ConvergenceTable::reduction_rate_log2); \n\n// \u8fd9\u4e9b\u51fd\u6570\u7684\u6bcf\u4e00\u6b21\u8c03\u7528\u90fd\u4f1a\u4ea7\u751f\u4e00\u4e2a\u989d\u5916\u7684\u5217\uff0c\u4e0e\u539f\u6765\u7684\u5217\uff08\u5728\u6211\u4eec\u7684\u4f8b\u5b50\u4e2d\u662f \"L2 \"\u548c \"H1 \"\u5217\uff09\u5408\u5e76\u6210\u4e00\u4e2a\u8d85\u7ea7\u5217\u3002\n\n// \u6700\u540e\uff0c\u6211\u4eec\u60f3\u518d\u6b21\u5199\u4e0b\u8fd9\u4e2a\u6536\u655b\u56fe\uff0c\u9996\u5148\u5199\u5230\u5c4f\u5e55\u4e0a\uff0c\u7136\u540e\u4ee5LaTeX\u683c\u5f0f\u5199\u5230\u78c1\u76d8\u4e0a\u3002\u6587\u4ef6\u540d\u8fd8\u662f\u6309\u7167\u4e0a\u9762\u7684\u65b9\u6cd5\u6784\u5efa\u3002\n\n        std::cout << std::endl; \n        convergence_table.write_text(std::cout); \n\n        std::string conv_filename = \"convergence\"; \n        switch (refinement_mode) \n          { \n            case global_refinement: \n              conv_filename += \"-global\"; \n              break; \n            case adaptive_refinement: \n              conv_filename += \"-adaptive\"; \n              break; \n            default: \n              Assert(false, ExcNotImplemented()); \n          } \n        switch (fe->degree) \n          { \n            case 1: \n              conv_filename += \"-q1\"; \n              break; \n            case 2: \n              conv_filename += \"-q2\"; \n              break; \n            default: \n              Assert(false, ExcNotImplemented()); \n          } \n        conv_filename += \".tex\"; \n\n        std::ofstream table_file(conv_filename); \n        convergence_table.write_tex(table_file); \n      } \n  } \n\n// \u5728\u8fdb\u5165 <code>main()</code> \u4e4b\u524d\u7684\u6700\u540e\u4e00\u6b65\u662f\u5173\u95ed\u547d\u540d\u7a7a\u95f4 <code>Step7</code> \uff0c\u6211\u4eec\u5df2\u7ecf\u628a\u8fd9\u4e2a\u7a0b\u5e8f\u6240\u9700\u8981\u7684\u4e00\u5207\u90fd\u653e\u5728\u8fd9\u4e2a\u547d\u540d\u7a7a\u95f4\u91cc\u3002\n\n} // namespace Step7 \n// @sect3{Main function}  \n\n// \u4e3b\u51fd\u6570\u4e3b\u8981\u548c\u4ee5\u524d\u4e00\u6837\u3002\u552f\u4e00\u4e0d\u540c\u7684\u662f\uff0c\u6211\u4eec\u89e3\u4e86\u4e09\u6b21\uff0c\u4e00\u6b21\u662fQ1\u548c\u9002\u5e94\u6027\u7ec6\u5316\uff0c\u4e00\u6b21\u662fQ1\u5143\u7d20\u548c\u5168\u5c40\u7ec6\u5316\uff0c\u4e00\u6b21\u662fQ2\u5143\u7d20\u548c\u5168\u5c40\u7ec6\u5316\u3002\n\n// \u7531\u4e8e\u6211\u4eec\u5728\u4e0b\u9762\u4e3a\u4e24\u4e2a\u7a7a\u95f4\u7ef4\u5ea6\u5b9e\u4f8b\u5316\u4e86\u51e0\u4e2a\u6a21\u677f\u7c7b\uff0c\u6211\u4eec\u901a\u8fc7\u5728\u51fd\u6570\u7684\u5f00\u5934\u58f0\u660e\u4e00\u4e2a\u5e38\u6570\u6765\u8868\u793a\u7a7a\u95f4\u7ef4\u5ea6\u7684\u6570\u91cf\uff0c\u4f7f\u4e4b\u66f4\u52a0\u901a\u7528\u3002\u5982\u679c\u4f60\u60f3\u57281d\u62162d\u4e2d\u8fd0\u884c\u7a0b\u5e8f\uff0c\u90a3\u4e48\u4f60\u53ea\u9700\u8981\u6539\u53d8\u8fd9\u4e2a\u5b9e\u4f8b\uff0c\u800c\u4e0d\u662f\u4e0b\u9762\u7684\u6240\u6709\u7528\u6cd5\u3002\n\nint main() \n{ \n  const unsigned int dim = 2; \n\n  try \n    { \n      using namespace dealii; \n      using namespace Step7; \n\n// \u73b0\u5728\u662f\u5bf9\u4e3b\u7c7b\u7684\u4e09\u6b21\u8c03\u7528\u3002\u6bcf\u4e2a\u8c03\u7528\u90fd\u88ab\u5c01\u9501\u5728\u5927\u62ec\u53f7\u4e2d\uff0c\u4ee5\u4fbf\u5728\u533a\u5757\u7ed3\u675f\u65f6\u548c\u6211\u4eec\u8fdb\u5165\u4e0b\u4e00\u4e2a\u8fd0\u884c\u4e4b\u524d\u9500\u6bc1\u5404\u81ea\u7684\u5bf9\u8c61\uff08\u5373\u6709\u9650\u5143\u548cHelmholtzProblem\u5bf9\u8c61\uff09\u3002\u8fd9\u5c31\u907f\u514d\u4e86\u53d8\u91cf\u540d\u79f0\u7684\u51b2\u7a81\uff0c\u4e5f\u786e\u4fdd\u4e86\u5728\u4e09\u6b21\u8fd0\u884c\u4e2d\u7684\u4e00\u6b21\u8fd0\u884c\u7ed3\u675f\u540e\u7acb\u5373\u91ca\u653e\u5185\u5b58\uff0c\u800c\u4e0d\u662f\u53ea\u5728 <code>try</code> \u5757\u7684\u672b\u5c3e\u91ca\u653e\u3002\n\n      { \n        std::cout << \"Solving with Q1 elements, adaptive refinement\" \n                  << std::endl \n                  << \"=============================================\" \n                  << std::endl \n                  << std::endl; \n\n        FE_Q<dim>             fe(1); \n        HelmholtzProblem<dim> helmholtz_problem_2d( \n          fe, HelmholtzProblem<dim>::adaptive_refinement); \n\n        helmholtz_problem_2d.run(); \n\n        std::cout << std::endl; \n      } \n\n      { \n        std::cout << \"Solving with Q1 elements, global refinement\" << std::endl \n                  << \"===========================================\" << std::endl \n                  << std::endl; \n\n        FE_Q<dim>             fe(1); \n        HelmholtzProblem<dim> helmholtz_problem_2d( \n          fe, HelmholtzProblem<dim>::global_refinement); \n\n        helmholtz_problem_2d.run(); \n\n        std::cout << std::endl; \n      } \n\n      { \n        std::cout << \"Solving with Q2 elements, global refinement\" << std::endl \n                  << \"===========================================\" << std::endl \n                  << std::endl; \n\n        FE_Q<dim>             fe(2); \n        HelmholtzProblem<dim> helmholtz_problem_2d( \n          fe, HelmholtzProblem<dim>::global_refinement); \n\n        helmholtz_problem_2d.run(); \n\n        std::cout << std::endl; \n      } \n      { \n        std::cout << \"Solving with Q2 elements, adaptive refinement\" \n                  << std::endl \n                  << \"===========================================\" << std::endl \n                  << std::endl; \n\n        FE_Q<dim>             fe(2); \n        HelmholtzProblem<dim> helmholtz_problem_2d( \n          fe, HelmholtzProblem<dim>::adaptive_refinement); \n\n        helmholtz_problem_2d.run(); \n\n        std::cout << std::endl; \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\n  return 0; \n} \n\n", "meta": {"hexsha": "596fe5d533b07fb48d451f8af1b5dbeac932f9a7", "size": 36669, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-7/step-7.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-7/step-7.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-7/step-7.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": 40.0754098361, "max_line_length": 623, "alphanum_fraction": 0.6464315907, "num_tokens": 16635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548646660543, "lm_q2_score": 0.7310585727705126, "lm_q1q2_score": 0.47617855772989603}}
{"text": "/*    This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.\n *    See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.\n *    Author(s):       Siargey Kachanovich\n *\n *    Copyright (C) 2019 Inria\n *\n *    Modification(s):\n *      - YYYY/MM Author: Description of the modification\n */\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE \"oracle\"\n#include <boost/test/unit_test.hpp>\n#include <gudhi/Unitary_tests_utils.h>\n\n#include <string>\n\n#include <gudhi/Implicit_manifold_intersection_oracle.h>\n\n#include <gudhi/Functions/Function_Sm_in_Rd.h>\n#include <gudhi/Functions/Cartesian_product.h>\n\n#include <gudhi/Coxeter_triangulation.h>\n\n#include <random>\n#include <cstdlib>\n\nusing namespace Gudhi::coxeter_triangulation;\n\nBOOST_AUTO_TEST_CASE(oracle) {\n  Function_Sm_in_Rd fun_sph(5.1111, 2);\n  auto oracle = make_oracle(fun_sph);\n  Coxeter_triangulation<> cox_tr(oracle.amb_d());\n  // cox_tr.change_offset(Eigen::VectorXd::Random(oracle.amb_d()));\n\n  Eigen::VectorXd seed = fun_sph.seed();\n  auto s = cox_tr.locate_point(seed);\n\n  std::size_t num_intersected_edges = 0;\n  for (auto f : s.face_range(oracle.cod_d())) {\n    auto qr = oracle.intersects(f, cox_tr);\n    if (qr.success) num_intersected_edges++;\n    auto vertex_it = f.vertex_range().begin();\n    Eigen::Vector3d p1 = cox_tr.cartesian_coordinates(*vertex_it++);\n    Eigen::Vector3d p2 = cox_tr.cartesian_coordinates(*vertex_it++);\n    BOOST_CHECK(vertex_it == f.vertex_range().end());\n    Eigen::MatrixXd m(3, 3);\n    if (qr.success) {\n      m.col(0) = qr.intersection;\n      m.col(1) = p1;\n      m.col(2) = p2;\n      GUDHI_TEST_FLOAT_EQUALITY_CHECK(m.determinant(), 0.0, 1e-10);\n    }\n  }\n  BOOST_CHECK(num_intersected_edges == 3 || num_intersected_edges == 4);\n}\n", "meta": {"hexsha": "ed2042f5d0cba21df5f3612aa5fba8e656d60505", "size": 1803, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Coxeter_triangulation/test/oracle_test.cpp", "max_stars_repo_name": "VincentRouvreau/gudhi-devel", "max_stars_repo_head_hexsha": "c6a7f0258406542b0c2b10bb6b2878f27b13394b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-05T05:45:06.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-05T05:45:06.000Z", "max_issues_repo_path": "src/Coxeter_triangulation/test/oracle_test.cpp", "max_issues_repo_name": "gspr/gudhi-devel", "max_issues_repo_head_hexsha": "6b8f24647a6f290f4e2f2f307de660dfae93cc90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Coxeter_triangulation/test/oracle_test.cpp", "max_forks_repo_name": "gspr/gudhi-devel", "max_forks_repo_head_hexsha": "6b8f24647a6f290f4e2f2f307de660dfae93cc90", "max_forks_repo_licenses": ["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.6315789474, "max_line_length": 101, "alphanum_fraction": 0.7054908486, "num_tokens": 519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619436290698, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.47612295121787385}}
{"text": "//  Copyright John Maddock 2007.\r\n//  Copyright Paul A. Bristow 2007.\r\n\r\n//  Use, modification and distribution are subject to the\r\n//  Boost Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifdef _MSC_VER\r\n# pragma warning (disable : 4305) // 'initializing' : truncation from 'long double' to 'const eval_type'\r\n# pragma warning (disable : 4244) //  conversion from 'long double' to 'const eval_type'\r\n#endif\r\n\r\n#include <iostream>\r\n\r\n//[policy_eg_3\r\n\r\n#include <boost/math/distributions/binomial.hpp>\r\n\r\n//\r\n// Begin by defining a policy type, that gives the\r\n// behaviour we want:\r\n//\r\nusing namespace boost::math::policies;\r\ntypedef policy<\r\n   promote_float<false>,\r\n   discrete_quantile<integer_round_nearest>\r\n> mypolicy;\r\n//\r\n// Then define a distribution that uses it:\r\n//\r\ntypedef boost::math::binomial_distribution<float, mypolicy> mybinom;\r\n//\r\n//  And now use it to get the quantile:\r\n//\r\nint main()\r\n{\r\n   std::cout << \"quantile is: \" <<\r\n      quantile(mybinom(200, 0.25), 0.05) << std::endl;\r\n}\r\n\r\n//]\r\n\r\n", "meta": {"hexsha": "1817187cf40d374e855ac36fdec35762e9b736a5", "size": 1100, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/example/policy_eg_3.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/math/example/policy_eg_3.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/math/example/policy_eg_3.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": 25.5813953488, "max_line_length": 105, "alphanum_fraction": 0.6818181818, "num_tokens": 294, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619436290698, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.47612295121787374}}
{"text": "#include <NTL/ZZ.h>\n#include \"prng.hh\"\n\n/*\n * KK is the number of elements drawn from an urn where there are NN1 white\n * balls and NN2 black balls; the result is the number of white balls in\n * the KK sample.\n *\n * The implementation is based on an adaptation of the H2PEC alg for large\n * numbers; see hgd.cc for details\n */\nNTL::ZZ HGD(const NTL::ZZ &KK,\n            const NTL::ZZ &NN1,\n            const NTL::ZZ &NN2,\n            PRNG *prng);\n", "meta": {"hexsha": "083aea7a5d42972c1cf56454d446febb5eaa3769", "size": 447, "ext": "hh", "lang": "C++", "max_stars_repo_path": "ope-from-cryptodb/lib/hgd.hh", "max_stars_repo_name": "xietian1/mpkix-judgement", "max_stars_repo_head_hexsha": "2cca8b509d2804c85bb39abc397f34ad4f2666b1", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ope-from-cryptodb/lib/hgd.hh", "max_issues_repo_name": "xietian1/mpkix-judgement", "max_issues_repo_head_hexsha": "2cca8b509d2804c85bb39abc397f34ad4f2666b1", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ope-from-cryptodb/lib/hgd.hh", "max_forks_repo_name": "xietian1/mpkix-judgement", "max_forks_repo_head_hexsha": "2cca8b509d2804c85bb39abc397f34ad4f2666b1", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.9375, "max_line_length": 75, "alphanum_fraction": 0.644295302, "num_tokens": 126, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8244619350028205, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.47612294623625484}}
{"text": "#include <boost/random/linear_congruential.hpp>\n", "meta": {"hexsha": "f53e6dbdb6799fe3cd12ea5862936c815c753812", "size": 48, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_random_linear_congruential.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_random_linear_congruential.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_random_linear_congruential.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 24.0, "max_line_length": 47, "alphanum_fraction": 0.8333333333, "num_tokens": 12, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.4761229462362547}}
{"text": "/**\n * @author     : Zhao Chonyyao (cyzhao@zju.edu.cn)\n * @date       : 2021-04-30\n * @description: embedded elasticity mass spring method problem\n * @version    : 1.0\n */\n#include <memory>\n#include <string>\n#include <boost/property_tree/ptree.hpp>\n\n#include \"Common/error.h\"\n\n// TODO: possible bad idea of having dependence to model in problem module\n#include \"Model/fem/elas_energy.h\"\n#include \"Model/fem/mass_matrix.h\"\n#include \"Model/mass_spring/mass_spring_obj.h\"\n#include \"Model/mass_spring/para.h\"\n#include \"Geometry/extract_surface.imp\"\n#include \"Geometry/interpolate.h\"\n\n#include \"Problem/energy/basic_energy.h\"\n#include \"Io/io.h\"\n#include \"Geometry/extract_surface.imp\"\n#include \"libigl/include/igl/readOBJ.h\"\n\n#include \"embedded_mass_spring_problem.h\"\n\nnamespace PhysIKA {\nusing namespace std;\nusing namespace Eigen;\nusing namespace igl;\n\ntemplate <typename T>\nusing MAT = Eigen::Matrix<T, -1, -1>;\ntemplate <typename T>\nusing VEC = Eigen::Matrix<T, -1, 1>;\n\ntemplate <typename T>\nembedded_ms_problem_builder<T>::embedded_ms_problem_builder(const T* x, const boost::property_tree::ptree& para_tree)\n{\n    pt_                     = para_tree;\n    auto blender            = para_tree.get_child(\"blender\");\n    auto simulation_para    = para_tree.get_child(\"simulation_para\");\n    auto common             = para_tree.get_child(\"common\");\n    para::dt                = common.get<double>(\"time_step\", 0.01);\n    para::line_search       = simulation_para.get<int>(\"line_search\", true);  // todo\n    para::density           = common.get<double>(\"density\", 10);\n    para::frame             = common.get<int>(\"frame\", 100);\n    para::newton_fastMS     = simulation_para.get<string>(\"newton_fastMS\");\n    para::stiffness         = simulation_para.get<double>(\"stiffness\", 8000);\n    para::gravity           = common.get<double>(\"gravity\", 9.8);\n    para::object_name       = blender.get<string>(\"surf\");\n    para::out_dir_simulator = common.get<string>(\"out_dir_simulator\");\n    para::simulation_type   = simulation_para.get<string>(\"simulation\", \"static\");\n    para::weight_line_search =\n        simulation_para.get<double>(\"weight_line_search\", 1e-5);\n    para::input_object   = common.get<string>(\"input_object\");\n    para::force_function = simulation_para.get<string>(\"force_function\");\n    para::intensity      = simulation_para.get<double>(\"intensity\");\n    para::coll_z         = simulation_para.get<bool>(\"coll_z\", false);\n    //TODO: need to check exception\n\n    const string filename        = common.get<string>(\"embedded_object\", \"\");\n    const string filename_coarse = common.get<string>(\"input_object\", \"\");\n    if (filename_coarse.empty() || filename.empty())\n    {\n        cerr << \"no coarse mesh\" << __LINE__ << endl;\n        exit(1);\n    }\n\n    Matrix<T, -1, -1> nods;\n    MatrixXi          cells;\n    Matrix<T, -1, -1> nods_coarse;\n    MatrixXi          cells_coarse;\n\n    if (filename.rfind(\".obj\") != string::npos)\n    {\n        readOBJ(filename.c_str(), nods, cells);\n        nods.transposeInPlace();\n        cells.transposeInPlace();\n    }\n    else\n    {\n        IF_ERR(exit, mesh_read_from_vtk<T, 4>(filename.c_str(), nods, cells));\n    }\n    IF_ERR(exit, mesh_read_from_vtk<T, 4>(filename_coarse.c_str(), nods_coarse, cells_coarse));\n\n    if (cells.size() == 0)\n        cells.resize(4, 0);\n    if (cells_coarse.size() == 0)\n        cells_coarse.resize(4, 0);\n    interp_pts_in_tets<T, 3>(nods, cells, nods_coarse, fine_to_coarse_coef_);\n    interp_pts_in_tets<T, 3>(nods_coarse, cells_coarse, nods, coarse_to_fine_coef_);\n\n    const size_t num_nods = nods_coarse.cols();\n    if (x != nullptr)\n    {\n        nods        = Map<const MAT<T>>(x, nods.rows(), nods.cols());\n        nods_coarse = nods * fine_to_coarse_coef_;\n    }\n\n    REST_           = nods;\n    cells_          = cells;\n    fine_verts_num_ = REST_.cols();\n\n    //read fixed points\n    vector<size_t> cons(0);\n    if (para_tree.find(\"input_constraint\") != para_tree.not_found())\n    {\n        const string cons_file_path = common.get<string>(\"input_constraint\");\n        /*  IF_ERR(exit, read_fixed_verts_from_csv(cons_file_path.c_str(), cons));*/\n    }\n    cout << \"constrint \" << cons.size() << \" points\" << endl;\n\n    //calc mass vector\n    Matrix<T, -1, 1> mass_vec(num_nods);\n    calc_mass_vector<T>(nods_coarse, cells_coarse, para::density, mass_vec);\n    // mass_calculator<T, 3, 4, 1, 1, basis_func, quadrature>(nods_coarse, cells_coarse, para::density, mass_vec);\n\n    cout << \"build energy\" << endl;\n    int ELAS = 0;\n    int GRAV = 1;\n    int KIN  = 2;\n    int POS  = 3;\n    if (para_tree.get<std::string>(\"solver_type\") == \"explicit\")\n        POS = 2;\n\n    ebf_.resize(POS + 1);\n    ebf_[ELAS] = make_shared<MassSpringObj<T>>(para::input_object.c_str(), para::stiffness);\n    char axis  = common.get<char>(\"grav_axis\", 'y') | 0x20;\n    ebf_[GRAV] = make_shared<gravity_energy<T, 3>>(num_nods, 1, para::gravity, mass_vec, axis);\n    kinetic_   = make_shared<momentum<T, 3>>(nods_coarse.data(), num_nods, mass_vec, para::dt);\n\n    if (para_tree.get<string>(\"solver_type\") == \"implicit\")\n        ebf_[KIN] = kinetic_;\n\n    ebf_[POS] = make_shared<position_constraint<T, 3>>(nods_coarse.data(), num_nods, simulation_para.get<double>(\"w_pos\", 1e6), cons);\n\n    //set constraint\n    enum constraint_type\n    {\n        COLL\n    };\n    cbf_.resize(COLL + 1);\n    collider_  = nullptr;\n    cbf_[COLL] = collider_;\n\n    shared_ptr<Problem<T, 3>> pb      = make_shared<Problem<T, 3>>(ebf_[0], nullptr);\n    auto                      dat_str = make_shared<dat_str_core<T, 3>>(pb->Nx() / 3, para_tree.get<bool>(\"hes_is_const\", false));\n    compute_hes_pattern(pb->energy_, dat_str);\n    ebf_[0]->Hes(nods_coarse.data(), dat_str);\n    SparseMatrix<T> K = dat_str->get_hes();\n\n    embedded_interp_ = make_shared<embedded_interpolate<T>>(nods_coarse, coarse_to_fine_coef_, fine_to_coarse_coef_, K, 5868.03 / 2);\n\n    if (para_tree.get<string>(\"solver_type\") == \"explicit\")\n    {\n        Map<Matrix<T, -1, 1>> position(nods_coarse.data(), nods_coarse.size());\n        semi_implicit_ = make_shared<semi_implicit<T>>(para::dt, mass_vec, position);\n    }\n}\n\ntemplate <typename T>\nint embedded_ms_problem_builder<T>::update_problem(const T* x, const T* v)\n{\n    embedded_interp_->update_verts(x, fine_verts_num_);\n    const Eigen::Matrix<T, -1, -1>& verts = embedded_interp_->get_verts();\n\n    IF_ERR(return, kinetic_->update_location_and_velocity(verts.data(), v));\n    if (collider_ != nullptr)\n        IF_ERR(return, collider_->update(verts.data()));\n    return 0;\n}\n\ntemplate class embedded_ms_problem_builder<double>;\n\ntemplate class embedded_ms_problem_builder<float>;\n\n}  // namespace PhysIKA\n", "meta": {"hexsha": "d3aa23c4652dee9b01df6e870c2b971ba798ab50", "size": 6680, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Source/Dynamics/FiniteElementMethod/Source/Problem/integrated_problem/embedded_mass_spring_problem.cc", "max_stars_repo_name": "weikm/sandcarSimulation2", "max_stars_repo_head_hexsha": "fe499d0a3289c0ac1acce69c7dc78d8ce1b2708a", "max_stars_repo_licenses": ["Apache-2.0"], "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/Dynamics/FiniteElementMethod/Source/Problem/integrated_problem/embedded_mass_spring_problem.cc", "max_issues_repo_name": "weikm/sandcarSimulation2", "max_issues_repo_head_hexsha": "fe499d0a3289c0ac1acce69c7dc78d8ce1b2708a", "max_issues_repo_licenses": ["Apache-2.0"], "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/Dynamics/FiniteElementMethod/Source/Problem/integrated_problem/embedded_mass_spring_problem.cc", "max_forks_repo_name": "weikm/sandcarSimulation2", "max_forks_repo_head_hexsha": "fe499d0a3289c0ac1acce69c7dc78d8ce1b2708a", "max_forks_repo_licenses": ["Apache-2.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.1111111111, "max_line_length": 134, "alphanum_fraction": 0.6511976048, "num_tokens": 1804, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619306896955, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.47612294374544517}}
{"text": "#ifndef STAN_MATH_PRIM_SCAL_FUN_EXPM1_HPP\n#define STAN_MATH_PRIM_SCAL_FUN_EXPM1_HPP\n\n#include <stan/math/prim/scal/fun/boost_policy.hpp>\n#include <boost/math/special_functions/expm1.hpp>\n\nnamespace stan {\n  namespace math {\n\n    /**\n     * Return the natural exponentiation of x minus one.\n     * Returns infinity for infinity argument and -infinity for\n     * -infinity argument.\n     *\n     * @param[in] x Argument.\n     * @return Natural exponentiation of argument minus one.\n     */\n    inline double expm1(double x) {\n      return boost::math::expm1(x, boost_policy_t());\n    }\n\n    /**\n     * Integer version of expm1.\n     *\n     * @param[in] x Argument.\n     * @return Natural exponentiation of argument minus one.\n     */\n    inline double expm1(int x) {\n      return expm1(static_cast<double>(x));\n    }\n\n  }\n}\n#endif\n", "meta": {"hexsha": "090ad2c92c8a316667ba686711965bdbbde3eedb", "size": 828, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/scal/fun/expm1.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/prim/scal/fun/expm1.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/prim/scal/fun/expm1.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": 23.6571428571, "max_line_length": 63, "alphanum_fraction": 0.6618357488, "num_tokens": 210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8244619177503206, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.47612293627301616}}
{"text": "#include <boost/math/interpolators/barycentric_rational.hpp>\n", "meta": {"hexsha": "b2cfcf4bbb7fdb7d86c9d18af198818dd8830276", "size": 61, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_interpolators_barycentric_rational.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_interpolators_barycentric_rational.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_interpolators_barycentric_rational.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 30.5, "max_line_length": 60, "alphanum_fraction": 0.8524590164, "num_tokens": 16, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.47612293627301605}}
{"text": "#include \"luminosityHadronic.h\"\n\n#include <fparameters/parameters.h>\n#include <fmath/RungeKutta.h>\n#include <fmath/interpolation.h>\n#include <flosses/crossSectionInel.h>\n#include <fmath/physics.h>\n#include <algorithm>\n\n#include <boost/math/special_functions/bessel.hpp>\n\n/*double fpp(double Ep, double E)         //funcion a integrar   x=Eproton; E=Epion\n{\n\tdouble L = log(Ep/1.6); //el 1.6 son TeV en erg\n\tdouble x = E/Ep; \n\tdouble Bg = 1.3+0.14*L+0.011*L*L;\n\tdouble beta = 1.0/(1.79+0.11*L+0.008*L*L);\n\tdouble kappa = 1.0/(0.801+0.049*L+0.014*L*L);\n\t\n\tdouble equis_b = pow(x,beta);\n\tdouble factor = 1-equis_b;\n\tdouble f;\n\tif (factor =! 0)\t{\n\t\t\n\t\tdouble f1 = Bg*log(x)/x;\n\t\tdouble f2 = factor/(1.0+kappa*equis_b*factor);\n\t\tdouble f3 = 1.0/log(x) - 4.0*beta*equis_b/factor - 4.0*kappa*beta*equis_b*(1.0-2.0*equis_b)/(1.0+kappa*equis_b*factor);\n\t\t\n\t\tf      =  f1*pow(f2,4)*f3;\n\t}\n\telse\t{\n\t\tf = 0.0;\n\t}\n\treturn f;\t\t\n}*/\n\ndouble cHadron(double E)  //limite inferior\n{\t\n\tdouble Kpi = 0.17;\n\tdouble thr = 0.0016; //1GeV\n\n\treturn std::max(E+P2(neutralPionMass*cLight2)/(4*E),thr*Kpi); //== Ekin > Ethr\n}\n\ndouble dHadron()         //limite superior   \n{\n\treturn 1.6e-12*pow(10.0,13.0);   //esto es un infinito                                \n}\n\n\n/*double fHadron(double Ep, double E, const Particle& p, const SpaceCoord& psc) //funcion a integrar   x=Ecreator; L=L(Ega)\n{\t\n\tdouble Kpi = 0.17;\n\tdouble eval = p.mass*cLight2+Ep/Kpi;\n\tdouble Ekin = Ep/Kpi;\n\tdouble distCreator=0.0;\n\tif (Ep < p.emax() && Ep >= p.emin()) {\n\t\tdistCreator = p.distribution.interpolate({ { 0, Ep } }, &psc);\n\t}\n\t\n\tdouble thr = 0.0016; //1GeV\n\t//double sigma = 30e-27*(0.95+0.06*log(Ekin/thr));\n\t\n\tdouble l = log10((protonMass*cLight2+Ep/Kpi)/1.6);\n\tdouble sigma = 1.e-27 * (34.3+1.88*l+0.25*l*l);\n\tdouble pionEmiss = sigma*distCreator*fpp(Ep,E)/Ep; //Kpi;  //sigma = crossSectionHadronicDelta(Ekin)\n\t\n\tdouble result = pionEmiss; ///sqrt(P2(Epi)-P2(neutralPionMass*cLight2));\n\treturn result;\n}*/\n\ndouble heaviside(double x,double a,double b)\n{\n\treturn (a <= x && x <= b ? 1.0 : 0.0);\n}\n\ndouble auxf3(double dGeV, double sGeV, double gx, double GammaGeV, double isoGeV)\n{\n\tdouble pGeV = protonMass*cLight2/1.6e-3;\n\tdouble piGeV = neutralPionMass*cLight2/1.6e-3;\n\tdouble gd = (sGeV + dGeV*dGeV - pGeV*pGeV)/(2.0*dGeV*sqrt(sGeV));\n\tdouble betad = sqrt(1.0-1.0/(gd*gd));\n\tdouble epi = (dGeV*dGeV+piGeV*piGeV-pGeV*pGeV)/(2.0*dGeV);\n\tdouble ppi = sqrt(epi*epi-piGeV*piGeV);\n\tdouble aux1 = 0.5/(betad*gd*ppi);   // REVISAR ESTE p_pi\n\tdouble aux2 = P2(dGeV-isoGeV)+GammaGeV*GammaGeV;\n\tdouble h = heaviside(gx*piGeV,gd*(epi-betad*ppi),gd*(epi+betad*ppi));\n\t\n\treturn aux1*h/aux2;    // [GeV^-3]\n\t\n}\n\ndouble inclusiveSigma(double sGeV)\n{\n\tdouble pGeV = protonMass*cLight2/1.6e-3;\n\tdouble piGeV = neutralPionMass*cLight2/1.6e-3;\n\tdouble eta=sqrt(P2(sGeV-P2(piGeV)-P2(2.0*pGeV))-4.0*P2(piGeV*2.0*pGeV))/(2.0*piGeV*sqrt(sGeV));\n\tdouble pthr = 0.78; //[GeV]\n\tdouble sigma=0.0;;\n\t\n\t// s = 2mp(Ek+2mp) = 2mp(E+mp)\n\t// E = s/2mp - mp\n\t// p = sqrt(E**2-m**2)\n\tdouble p = sqrt(P2(0.5*sGeV/pGeV-pGeV)-P2(pGeV));\n\t\n\tif (p >= pthr && p <= 0.96) {\n\t\tsigma = 0.032*eta*eta+0.04*pow(eta,6)+0.047*pow(eta,8);\n\t} else if (p > 0.96 && p <= 1.27) {\n\t\tsigma = 32.6*pow(p-0.8,3.21);\n\t} else if (p > 1.27 && p <= 8.0) {\n\t\tsigma = 5.4*pow(p-0.8,0.81);\n\t} else if (p > 8.0) {\n\t\tsigma = 32.0 * log(p) + 48.5 / sqrt(p) - 59.5;\n\t}\n\treturn 1.0e-27 * sigma;     // [cm^2]\n}\n/*\ndouble dsigma(double gx, double gr, double sGeV)\n{\n\tdouble GammaGeV = 0.0575;\n\tdouble pGeV = protonMass*cLight2/1.6e-3;\n\tdouble piGeV = neutralPionMass * cLight2 / 1.6e-3;\n\tdouble isoGeV = 1.236;\n\tdouble atan1 = atan((sqrt(sGeV)-pGeV-isoGeV)/GammaGeV);\n\tdouble atan2 = atan((pGeV+piGeV-isoGeV)/GammaGeV);\n\tdouble aux1 = GammaGeV/(atan1-atan2);\n\t\n\tdouble Min = pGeV+piGeV;\n\tdouble Max = sqrt(sGeV)-pGeV;\n\tdouble integ= integSimpson(log(Min),log(Max),[&](double log_dGeV)\n\t\t\t\t\t{\n\t\t\t\t\t\tdouble dGeV = exp(log_dGeV);\n\t\t\t\t\t\treturn auxf3(dGeV,sGeV,gx,GammaGeV,isoGeV)*dGeV;\n\t\t\t\t\t},30);\n\treturn inclusiveSigma(sGeV)*aux1*integ*piGeV;  // [cm^2]\n}*/\n\ndouble dsigma(double gx, double gr, double sGeV)\n{\n\tdouble GammaGeV = 0.0575;\n\tdouble pGeV = protonMass*cLight2/1.6e-3;\n\tdouble piGeV = neutralPionMass * cLight2 / 1.6e-3;\n\tdouble isoGeV = 1.236;\n\tdouble atan1 = atan((sqrt(sGeV)-pGeV-isoGeV)/GammaGeV);\n\tdouble atan2 = atan((pGeV+piGeV-isoGeV)/GammaGeV);\n\tdouble aux1 = GammaGeV/(atan1-atan2);\n\t\n\tdouble Min = pGeV+piGeV;\n\tdouble Max = sqrt(sGeV)-pGeV;\n\t\n\tdouble integ= RungeKuttaSimple(Min,Max,[&](double dGeV)\n\t\t\t\t\t{return auxf3(dGeV,sGeV,gx,GammaGeV,isoGeV);});\n\t\n\treturn inclusiveSigma(sGeV)*aux1*integ*piGeV;  // [cm^2]\n}\n\ndouble auxf2(double gx, double gr, double epi, double normtemp, double sGeV)\n{\n\tdouble piGeV = neutralPionMass*cLight2/1.6e-3;\n\tdouble g = epi/piGeV;\n\tdouble beta = sqrt(1.0-1.0/(g*g));\n\tdouble betax = sqrt(1.0-1.0/(gx*gx));\n\tdouble q = sqrt(2.0*(gr+1.0))/normtemp;\n\t\n\tdouble f1 = exp(-q*g*gx*(1.0-beta*betax))-exp(-q*g*gx*(1.0+beta*betax));\n\t\n\treturn f1/(betax*gx) * dsigma(gx,gr,sGeV);\n}\n\n/*\ndouble auxf(double gr, double epi, double normtemp)\n{\n\tdouble piGeV = neutralPionMass*cLight2 / 1.6e-3;\n\tdouble pGeV = protonMass*cLight2/1.6e-3;\n\tdouble sGeV = 2.0*P2(pGeV)*(gr+1.0);\n\tdouble ji = (sGeV-4.0*P2(pGeV)+P2(piGeV))/(2.0*sqrt(sGeV));\n\tdouble Max = ji/piGeV;\n\tdouble integral = integSimpson(0.0,log(Max),[gr,epi,normtemp,sGeV](double log_gx)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tdouble gx = exp(log_gx);\n\t\t\t\t\t\t\treturn auxf2(gx,gr,epi,normtemp,sGeV)*gx;\n\t\t\t\t\t\t},30);\n\tdouble result = (gr*gr-1.0) / sqrt(2.0*(gr+1.0)) * integral;\n}*/\n\ndouble auxf(double gr, double epi, double normtemp)\n{\n\tdouble piGeV = neutralPionMass*cLight2 / 1.6e-3;\n\tdouble pGeV = protonMass*cLight2/1.6e-3;\n\tdouble sGeV = 2.0*P2(pGeV)*(gr+1.0);\n\tdouble ji = (sGeV-4.0*P2(pGeV)+P2(piGeV))/(2.0*sqrt(sGeV));\n\tdouble Max = ji/piGeV;\n\tdouble integral = RungeKuttaSimple(1.0,Max,[gr,epi,normtemp,sGeV](double gx)\n\t\t\t\t\t\t{return auxf2(gx,gr,epi,normtemp,sGeV);});\n\t//double integral = qMidPointLog(1.0,Max,[gr,epi,normtemp,sGeV](double gx)\n\t//\t\t\t\t\t{return auxf2(gx,gr,epi,normtemp,sGeV);},1.0e-2);\n\tdouble result = (gr*gr-1.0) / sqrt(2.0*(gr+1.0)) * integral;\n}\n\n/*\ndouble fPion(double epi, double density, double temp)\n{\n\tdouble normtemp = boltzmann* temp / (protonMass*cLight2);\n\tdouble k2 = boost::math::cyl_bessel_k(2, 1.0/normtemp);\n\tdouble piGeV = neutralPionMass*cLight2/1.6e-3;\n\tdouble constant = cLight*density*density/(4.0*piGeV*normtemp*k2*k2);\n\treturn constant * integSimpson(0.0,log(1.0e3),[epi,normtemp](double log_gr)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tdouble gr = exp(log_gr);\n\t\t\t\t\t\t\treturn auxf(gr,epi,normtemp)*gr;\n\t\t\t\t\t\t},30);\t//  [cm-3 s-1 GeV-1]\n}*/\n\ndouble fPion(double epi, double density, double temp)\n{\n\tdouble normtemp = boltzmann* temp / (protonMass*cLight2);\n\tdouble k2 = boost::math::cyl_bessel_k(2, 1.0/normtemp);\n\tdouble piGeV = neutralPionMass*cLight2/1.6e-3;\n\tdouble constant = cLight*density*density/(4.0*piGeV*normtemp*k2*k2);\n\t\n\treturn constant * RungeKuttaSimple(1.0,1.0e3,[&](double gr)\n\t\t\t\t\t\t{return auxf(gr,epi,normtemp);});         //  [cm-3 s-1 GeV-1]\n\t//return constant * qImpropLog(1.0,1.0e3,[epi,normtemp](double gr)\n\t//\t\t\t\t\t{return auxf(gr,epi,normtemp);},1.0e-2);\n}\n\n\ndouble fHadron(double epi, double density, double temp)\n{\n\tdouble piGeV = neutralPionMass*cLight2/1.6e-3;\n\tdouble qpi = fPion(epi,density,temp);\n\treturn qpi / sqrt(P2(epi)-P2(piGeV));   // [cm-3 s-1 GeV-2]\n}\n\n/*\ndouble luminosityHadronic(double E,\n\tconst double density, double temp)\n{\n\tdouble Kpi = 0.17;\n\tdouble thr = 0.0016; //1GeV\n\n\t//double Max  = dHadron();   //esto es un infinito \n\tdouble Min  = cHadron(E);\n\t//double Min = E+P2(0.5*neutralPionMass*cLight2)/E;\n\tMin = Min / 1.6e-3;\n\tdouble Max = 1.0e3;\n\tdouble integral = 2.0*integSimpson(log(Min),log(Max),[density,temp](double logepi)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tdouble epi = exp(logepi);\n\t\t\t\t\t\t\treturn fHadron(epi,density,temp)*epi;\n\t\t\t\t\t\t},30); // [cm-3 s-1 GeV-1]\n\t\t\n\tdouble jpp = integral * E*planck * 0.25/pi; // [erg s^-1 Hz^-1 cm^-3]\n\tjpp = jpp / (1.6e-3);\n\treturn jpp;\n}\n*/\n\ndouble luminosityHadronic(double E,\n\tconst double density, double temp)\n{\n\tdouble Kpi = 0.17;\n\tdouble thr = 0.0016; //1GeV\n\n\t//double Max  = dHadron();   //esto es un infinito \n\tdouble Min  = cHadron(E);\n\t//double Min = E+P2(0.5*neutralPionMass*cLight2)/E;\n\tMin = Min / 1.6e-3;\n\tdouble Max = 1.0e3;  // [en GeV]\n\t\n\t//double integral = 2.0*cLight*density*RungeKuttaSimple(Min, Max, \n\t//\t[&E,&p,&psc](double x) {return fHadron(x, E, p, psc); });    //integra entre Emin y Emax\n\t\n\tdouble integral = 2.0*RungeKuttaSimple(Min,Max,[&](double epi)\n\t\t\t\t\t\t\t{return fHadron(epi,density,temp);}); // [cm-3 s-1 GeV-1]\n\t//double integral = 2.0*qMidPointLog(Min,Max,[density,temp](double epi)\n\t//\t\t\t\t\t\t{return fHadron(epi,density,temp);},1.0e-2);\n\t//double integral = 2.0*qromoLog(Min,Max,[density,temp](double epi){return fHadron(epi,density,temp);});\n\t/*double integral = 2.0*cLight*density*RungeKutta(p.emin(), p.emax(),\n\t\t[E](double u){\n\t\t\treturn cHadron(u,E);\n\t\t}, \n\t\t[E](double u){\n\t\t\treturn dHadron(u,E);\n\t\t}, \n\t\t[&p,&psc](double u, double t){\n\t\t\treturn fHadron(u,t,p, psc);  \n\t\t}); */\n\t\t\n\tdouble jpp = integral * E*planck * 0.25/pi; // [erg s^-1 Hz^-1 cm^-3]\n\tjpp = jpp / (1.6e-3);\n\treturn jpp;\n}\n\n\n\n/*\ndouble fPP(double x, double E, Particle& creator )         //funcion a integrar   x=Eproton; E=Epion\n{\n\t//DataInjection* data = (DataInjection*)voiddata;\n\t//double E = data->E;    //esta E corresponde a la energia del foton emitido; E=Ega\n\t//double mass   = data->mass;\n\t//Vector& Ncreator = data->Ncreator;\n\t//Vector& Ecreator = data->Ecreator;\n\t//const double mass   = particle.mass;\n\t//const Vector& Ncreator = creator.distribution.values;\n\t//const Vector& Ecreator = creator.eDim()->values;\n\tdouble L      = log(x/1.6); //el 1.6 son TeV en erg\n\tdouble ap     = 3.67+0.83*L+0.075*P2(L);\n\tdouble se     = crossSectionHadronic(x);\n\tdouble Bp     = ap+0.25;\n\tdouble r      = 2.6*pow(ap,-0.5);\n\tdouble alpha  = 0.98*pow(ap,-0.5);\n\tdouble equis  = E/x;\n\tdouble factor = 1-pow(equis,alpha);\n\tdouble f;\n\tif (factor =! 0)\t{\n\t\tf      = 4*alpha*Bp*pow(equis,(alpha-1))*pow((factor/(1+r*pow(equis,alpha)*factor)),4)\n      \t         *(1/factor+r*(1-2*pow(equis,alpha))/(1+r*pow(equis,alpha)*factor))*\n     \t         pow((1-chargedPionMass*cLight2/(equis*x)),0.5);\n\t}\n\telse\t{\n\t\tf = 0.0;\n\t}*/", "meta": {"hexsha": "f7c9f1db83780bc8a19aaeb76326c883646cb5df", "size": 10275, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/lib/fluminosities/luminosityHadronic.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/lib/fluminosities/luminosityHadronic.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/lib/fluminosities/luminosityHadronic.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": 31.712962963, "max_line_length": 123, "alphanum_fraction": 0.6401946472, "num_tokens": 3930, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835493924954, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.47610251583422436}}
{"text": "// This file is part of MLDB. Copyright 2015 mldb.ai inc. All rights reserved.\n\n/* svd.cc\n   Jeremy Barnes, 15 June 2003\n   Copyright (c) 2003 Jeremy Barnes.  All rights reserved.\n   $Source$\n\n   Singular value decomposition functions, implementation.\n*/\n\n#if 0\n\n#include \"svd.h\"\n#include \"eigenvalues.h\"\n#include \"mldb/utils/distribution.h\"\n#include \"mldb/utils/distribution_simd.h\"\n#include \"mldb/arch/exception.h\"\n#include <boost/timer.hpp>\n#include <iostream>\n\nusing namespace std;\n\nnamespace ML {\n\n\ntemplate<class Float>\nstd::tuple<distribution<Float>, boost::multi_array<Float, 2>,\n             boost::multi_array<Float, 2> >\nsvd_impl(const boost::multi_array<Float, 2> & A, int nsv)\n{\n    /* We make the m x n square matrix\n       [ 0  A ]\n       [ AT 0 ]\n\n       (where AT is A transposed) and take its eigenvalues.  This is basically\n       because the more efficient SVD procedure has problems in calculating the\n       left singular vectors when A has a large range in its singular values.\n       This is also what Matlab does.\n\n       Note that this could be optimised a lot to make use of the sparseness.\n       If A is tall and skinny or short and fat, a lot of cycles will be\n       wasted multiplying zero by zero.\n    */\n\n    bool profile = false;\n\n    boost::timer::cpu_timert;\n    double t0 = t.elapsed();\n\n    size_t m = A.shape()[0];\n    size_t n = A.shape()[1];\n    size_t mnmin = std::min(m, n);\n\n    if (nsv < 0 || nsv > mnmin)\n        throw Exception(\"asked for more singular values than min(m,n)\");\n\n    /* Make the array\n\n       [ 0  A ]\n       [ A' 0 ]\n\n       to find the eigenvalues with.\n    */\n    boost::multi_array<Float, 2> A_(m+n, m+n);\n    A_.fill(0.0);\n    for (unsigned i = 0;  i < m;  ++i) {\n        for (unsigned j = 0;  j < n;  ++j) {\n            A_[n + i][j] = A[i][j];\n            A_[j][n + i] = A[i][j];\n        }\n    }\n    \n    if (profile) {\n        cerr << \"SVD: array construction: \" << -t0 + (t.elapsed()) << endl;\n        t0 = t.elapsed();\n    }\n\n    //cerr << \"A_ = \" << endl << A_ << endl;\n\n    /* Get the eigeneverything. */\n    distribution<Float> E;\n    vector<distribution<Float> > W;\n    std::tie(E, W) = eigenvectors(A_, nsv);\n\n    if (profile) {\n        cerr << \"SVD: eigenvalues: \" << -t0 + (t.elapsed()) << endl;\n        t0 = t.elapsed();\n    }\n    \n    //cerr << \"done eigeneverything\" << endl;\n\n    //cerr << \"E = \" << E << endl;\n    \n    //cerr << \"W = \" << endl;\n    //for (unsigned i = 0;  i < W.size();  ++i)\n    //    cerr << W[i] << endl;\n    //cerr << endl;\n    \n    /* Note: matlab does here some special processing to only select the ones\n       that are independent... not really sure so leaving it out.\n\n       >> type svds\n\n       ...\n\n       % Which (left singular) vectors are already orthogonal, with norm\n       % 1/sqrt(2)?\n       UU = W(1:m,:)' * W(1:m,:);\n       dUU = diag(UU);\n       VV = W(m+(1:n),:)' * W(m+(1:n),:);\n       dVV = diag(VV);\n       indpos = find((d > dtol) & (abs(dUU-0.5) <= uvtol)\n                     & (abs(dVV-0.5) <= uvtol));\n       indpos = indpos(1:min(end,k));\n       npos = length(indpos);\n       U = sqrt(2) * W(1:m,indpos);\n       s = d(indpos);\n       V = sqrt(2) * W(m+(1:n),indpos);\n\n       ...\n    */\n    \n    boost::multi_array<Float, 2> U(boost::extents[nsv][m]);\n    boost::multi_array<Float, 2> V(boost::extents[nsv][n]);\n\n    for (unsigned i = 0;  i < m;  ++i)\n        for (unsigned j = 0;  j < nsv;  ++j)\n            U[j][i] = std::sqrt(2.0) * W[j][i];\n\n    for (unsigned i = 0;  i < n;  ++i)\n        for (unsigned j = 0;  j < nsv;  ++j)\n            V[j][i] = std::sqrt(2.0) * W[j][i+m];\n\n    if (profile) {\n        cerr << \"SVD: singular vectors: \" << -t0 + (t.elapsed()) << endl;\n        t0 = t.elapsed();\n    }\n\n    //cerr << \"U = \" << endl << U << endl;\n    //cerr << \"V = \" << endl << V << endl;\n    \n    //boost::multi_array<Float, 2> D = diag(E);\n    //D.fill(0.0);\n    //for (unsigned i = 0;  i < std::min(m, n);  ++i)\n    //    D[i][i] = E[i];\n\n    //boost::multi_array<Float, 2> VT(std::min(m, n), n);\n    //for (unsigned i = 0;  i < n;  ++i)\n    //    for (unsigned j = 0;  j < std::min(m, n);  ++j)\n    //        VT[j][i] = V[i][j];\n\n    //cerr << \"U * D * VT = \" << endl << U * D * VT << endl;\n\n    //cerr << \"A = \" << endl << A << endl;\n\n    if (profile) cerr << \"SVD: total: \" << t.elapsed().wall << endl;\n\n    return std::make_tuple(E, U, V);\n}\n\nstd::tuple<distribution<float>, boost::multi_array<float, 2>,\n             boost::multi_array<float, 2> >\nsvd(const boost::multi_array<float, 2> & A)\n{\n    return svd_impl(A, std::min(A.shape()[0], A.shape()[1]));\n}\n\nstd::tuple<distribution<double>, boost::multi_array<double, 2>,\n             boost::multi_array<double, 2> >\nsvd(const boost::multi_array<double, 2> & A)\n{\n    return svd_impl(A, (A.shape()[0], A.shape()[1]));\n}\n\nstd::tuple<distribution<float>, boost::multi_array<float, 2>,\n             boost::multi_array<float, 2> >\nsvd(const boost::multi_array<float, 2> & A, size_t nsv)\n{\n    return svd_impl(A, nsv);\n}\n\nstd::tuple<distribution<double>, boost::multi_array<double, 2>,\n             boost::multi_array<double, 2> >\nsvd(const boost::multi_array<double, 2> & A, size_t nsv)\n{\n    return svd_impl(A, nsv);\n}\n\n} // namespace ML\n\n#endif\n", "meta": {"hexsha": "c40fada720737e5e1fe8302b01b1c13ffacc9b40", "size": 5238, "ext": "cc", "lang": "C++", "max_stars_repo_path": "plugins/jml/algebra/svd.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/algebra/svd.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/algebra/svd.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": 27.28125, "max_line_length": 79, "alphanum_fraction": 0.533982436, "num_tokens": 1651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961427, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4761025134999069}}
{"text": "#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <cmath>\n#include \"UKF/Types.h\"\n#include \"UKF/Integrator.h\"\n#include \"UKF/StateVector.h\"\n#include \"UKF/MeasurementVector.h\"\n#include \"UKF/Core.h\"\n#include \"ahrs.h\"\n\n/*\nThis is an implementation of an Unscented Kalman filter for a 9-axis AHRS,\nusing accelerometer, gyroscope and magnetometer to estimate attitude and\nangular velocity.\n*/\n\n/* Value of g in m/s^2. */\n#define G_ACCEL (9.80665)\n\n/* Default magnetic field norm in Gauss. */\n#define MAG_NORM (0.45)\n\nenum AHRS_Keys {\n    /* AHRS filter fields. */\n    Attitude,\n    AngularVelocity,\n\n    /* Parameter estimation filter fields. */\n    AccelerometerBias,\n    GyroscopeBias,\n    MagnetometerBias,\n    MagnetometerScaleFactor,\n    MagneticFieldNorm,\n    MagneticFieldInclination,\n\n    /* AHRS measurement vector fields. */\n    Accelerometer,\n    Gyroscope,\n    Magnetometer\n};\n\n/*\nThe AHRS state vector contains the following:\n- Attitude as a quaternion (NED frame to body frame)\n- Angular velocity (body frame, rad/s)\n*/\nusing AHRS_StateVector = UKF::StateVector<\n    UKF::Field<Attitude, UKF::Quaternion>,\n    UKF::Field<AngularVelocity, UKF::Vector<3>>\n>;\n\nnamespace UKF {\nnamespace Parameters {\ntemplate <> constexpr real_t AlphaSquared<AHRS_StateVector> = 1e-2;\ntemplate <> constexpr real_t Kappa<AHRS_StateVector> = 3.0;\n}\n}\n\n/*\nIn addition to the AHRS filter, an online parameter estimation filter is also\nimplemented in order to calculate biases in each of the sensors.\nThe magnetometer scale factor is represented as a direction cosine matrix\nwith no normalisation constraint.\n*/\n\nusing AHRS_SensorErrorVector = UKF::StateVector<\n    UKF::Field<AccelerometerBias, UKF::Vector<3>>,\n    UKF::Field<GyroscopeBias, UKF::Vector<3>>,\n    UKF::Field<MagnetometerBias, UKF::Vector<3>>,\n    UKF::Field<MagnetometerScaleFactor, UKF::Vector<3>>,\n    UKF::Field<MagneticFieldNorm, real_t>,\n    UKF::Field<MagneticFieldInclination, real_t>\n>;\n\nnamespace UKF {\nnamespace Parameters {\ntemplate <> constexpr real_t AlphaSquared<AHRS_SensorErrorVector> = 1.0;\ntemplate <> constexpr real_t Kappa<AHRS_SensorErrorVector> = 3.0;\n}\n\n/* AHRS process model. */\ntemplate <> template <>\nAHRS_StateVector AHRS_StateVector::derivative<>() const {\n    AHRS_StateVector output;\n\n    /* Calculate change in attitude. */\n    UKF::Quaternion omega_q;\n    omega_q.vec() = get_field<AngularVelocity>() * 0.5;\n    omega_q.w() = 0;\n    output.set_field<Attitude>(omega_q.conjugate() * get_field<Attitude>());\n\n    /* Assume constant angular velocity. */\n    output.set_field<AngularVelocity>(UKF::Vector<3>(0, 0, 0));\n\n    return output;\n}\n}\n\nusing AHRS_MeasurementVector = UKF::DynamicMeasurementVector<\n    UKF::Field<Accelerometer, UKF::Vector<3>>,\n    UKF::Field<Gyroscope, UKF::Vector<3>>,\n    UKF::Field<Magnetometer, UKF::Vector<3>>\n>;\n\nnamespace UKF {\n/*\nThis is the measurement model that's actually used in the filter, because\nit's the one which takes the parameter estimation filter state as an input.\n*/\ntemplate <> template <>\nUKF::Vector<3> AHRS_MeasurementVector::expected_measurement\n<AHRS_StateVector, Accelerometer, AHRS_SensorErrorVector>(\n        const AHRS_StateVector& state, const AHRS_SensorErrorVector& input) {\n    return input.get_field<AccelerometerBias>() + state.get_field<Attitude>() * UKF::Vector<3>(0, 0, -G_ACCEL);\n}\n\ntemplate <> template <>\nUKF::Vector<3> AHRS_MeasurementVector::expected_measurement\n<AHRS_StateVector, Gyroscope, AHRS_SensorErrorVector>(\n        const AHRS_StateVector& state, const AHRS_SensorErrorVector& input) {\n    return input.get_field<GyroscopeBias>() + state.get_field<AngularVelocity>();\n}\n\ntemplate <> template <>\nUKF::Vector<3> AHRS_MeasurementVector::expected_measurement\n<AHRS_StateVector, Magnetometer, AHRS_SensorErrorVector>(\n        const AHRS_StateVector& state, const AHRS_SensorErrorVector& input) {\n    return input.get_field<MagnetometerBias>().array() + input.get_field<MagnetometerScaleFactor>().array() *\n        (state.get_field<Attitude>() * UKF::Vector<3>(\n            input.get_field<MagneticFieldNorm>() *\n                std::cos(std::atan(input.get_field<MagneticFieldInclination>())),\n            0.0,\n            -input.get_field<MagneticFieldNorm>() *\n                std::sin(std::atan(input.get_field<MagneticFieldInclination>())))).array();\n}\n\n}\n\nusing AHRS_Filter = UKF::SquareRootCore<\n    AHRS_StateVector,\n    AHRS_MeasurementVector,\n    UKF::IntegratorHeun\n>;\n\nnamespace UKF {\n/*\nAHRS parameter estimation filter process model. Since the evolution of sensor\nerrors is by definition unpredictable, this does nothing.\n*/\ntemplate <> template <>\nAHRS_SensorErrorVector AHRS_SensorErrorVector::derivative<>() const {\n    return AHRS_SensorErrorVector::Zero();\n}\n\n/*\nAHRS parameter estimation filter measurement model. These take in the current\nstate estimate and sensor scale factor and bias estimates, and use them to\ncalculate predicted measurements.\nThese functions are just the same as the state measurement model, but with\ntheir arguments flipped.\n*/\ntemplate <> template <>\nUKF::Vector<3> AHRS_MeasurementVector::expected_measurement\n<AHRS_SensorErrorVector, Accelerometer, AHRS_StateVector>(\n        const AHRS_SensorErrorVector& state, const AHRS_StateVector& input) {\n    return state.get_field<AccelerometerBias>() + input.get_field<Attitude>() * UKF::Vector<3>(0, 0, -G_ACCEL);\n}\n\ntemplate <> template <>\nUKF::Vector<3> AHRS_MeasurementVector::expected_measurement\n<AHRS_SensorErrorVector, Gyroscope, AHRS_StateVector>(\n        const AHRS_SensorErrorVector& state, const AHRS_StateVector& input) {\n    return state.get_field<GyroscopeBias>() + input.get_field<AngularVelocity>();\n}\n\ntemplate <> template <>\nUKF::Vector<3> AHRS_MeasurementVector::expected_measurement\n<AHRS_SensorErrorVector, Magnetometer, AHRS_StateVector>(\n        const AHRS_SensorErrorVector& state, const AHRS_StateVector& input) {\n    return state.get_field<MagnetometerBias>().array() + state.get_field<MagnetometerScaleFactor>().array() *\n        (input.get_field<Attitude>() * UKF::Vector<3>(\n            state.get_field<MagneticFieldNorm>() *\n                std::cos(std::atan(state.get_field<MagneticFieldInclination>())),\n            0.0,\n            -state.get_field<MagneticFieldNorm>() *\n                std::sin(std::atan(state.get_field<MagneticFieldInclination>())))).array();\n}\n\n}\n\n/* Just use the Euler integrator since there's no process model. */\nusing AHRS_ParameterEstimationFilter = UKF::SquareRootParameterEstimationCore<\n    AHRS_SensorErrorVector,\n    AHRS_MeasurementVector\n>;\n\nstatic AHRS_Filter ahrs;\nstatic AHRS_ParameterEstimationFilter ahrs_errors;\nstatic AHRS_MeasurementVector meas;\nstatic UKF::Vector<3> acceleration;\n\n/*\nThe following functions provide a ctypes-compatible interface for ease of\ntesting.\n*/\n\nvoid ukf_init() {\n    /* Initialise state vector and covariance. */\n    ahrs.state.set_field<Attitude>(UKF::Quaternion(1, 0, 0, 0));\n    ahrs.state.set_field<AngularVelocity>(UKF::Vector<3>(0, 0, 0));\n    acceleration << UKF::Vector<3>(0, 0, 0);\n    ahrs.root_covariance = AHRS_StateVector::CovarianceMatrix::Zero();\n    ahrs.root_covariance.diagonal() <<\n        1e0, 1e0, 3.2e0,\n        1e-3 * UKF::Vector<3>::Ones();\n\n    /* Set measurement noise covariance. */\n    ahrs.measurement_root_covariance <<\n        0.5 * UKF::Vector<3>::Ones(),\n        0.004 * UKF::Vector<3>::Ones(),\n        0.1 * UKF::Vector<3>::Ones();\n\n    /* Set process noise covariance. */\n    ahrs.process_noise_root_covariance = AHRS_StateVector::CovarianceMatrix::Zero();\n    ahrs.process_noise_root_covariance.diagonal() <<\n        5e-5 * UKF::Vector<3>::Ones(),\n        5e-3 * UKF::Vector<3>::Ones();\n\n    /* Initialise scale factor and bias errors. */\n    ahrs_errors.state.set_field<AccelerometerBias>(UKF::Vector<3>(0, 0, 0));\n    ahrs_errors.state.set_field<GyroscopeBias>(UKF::Vector<3>(0, 0, 0));\n    ahrs_errors.state.set_field<MagnetometerBias>(UKF::Vector<3>(0, 0, 0));\n    ahrs_errors.state.set_field<MagnetometerScaleFactor>(UKF::Vector<3>(1, 1, 1));\n    ahrs_errors.state.set_field<MagneticFieldNorm>(MAG_NORM);\n    ahrs_errors.state.set_field<MagneticFieldInclination>(0.0);\n\n    /* Initialise scale factor and bias error covariance. */\n    ahrs_errors.root_covariance = AHRS_SensorErrorVector::CovarianceMatrix::Zero();\n    ahrs_errors.root_covariance.diagonal() <<\n        0.8 * UKF::Vector<3>::Ones(),\n        0.02 * UKF::Vector<3>::Ones(),\n        5.0e-2 * UKF::Vector<3>::Ones(), 1.0e-1 * UKF::Vector<3>::Ones(),\n        0.4, 0.7;\n\n    /* Set measurement noise covariance. */\n    ahrs_errors.measurement_root_covariance << ahrs.measurement_root_covariance;\n\n    /*\n    Set bias error process noise \u2013\u00a0this is derived from bias instability.\n\n    Bias instability is actually characterised as a 1/f flicker noise rather\n    than the white noise (which is what we're specifying using the process\n    noise covariance), so these are tuned by hand to values which allow the\n    filter to track biases over time, but not change too quickly.\n    */\n    ahrs_errors.process_noise_root_covariance = AHRS_SensorErrorVector::CovarianceMatrix::Zero();\n    ahrs_errors.process_noise_root_covariance.diagonal() <<\n        1e-5f * UKF::Vector<3>::Ones(),\n        1e-7f * UKF::Vector<3>::Ones(),\n        1e-5f * UKF::Vector<3>::Ones(), 1e-6f * UKF::Vector<3>::Ones(),\n        1e-7f, 1e-7f;\n}\n\nvoid ukf_set_attitude(real_t w, real_t x, real_t y, real_t z) {\n    ahrs.state.set_field<Attitude>(UKF::Quaternion(w, x, y, z));\n}\n\nvoid ukf_set_angular_velocity(real_t x, real_t y, real_t z) {\n    ahrs.state.set_field<AngularVelocity>(UKF::Vector<3>(x, y, z));\n}\n\nvoid ukf_get_state(struct ukf_state_t *in) {\n    in->attitude[0] = ahrs.state.get_field<Attitude>().x();\n    in->attitude[1] = ahrs.state.get_field<Attitude>().y();\n    in->attitude[2] = ahrs.state.get_field<Attitude>().z();\n    in->attitude[3] = ahrs.state.get_field<Attitude>().w();\n    in->angular_velocity[0] = ahrs.state.get_field<AngularVelocity>()[0];\n    in->angular_velocity[1] = ahrs.state.get_field<AngularVelocity>()[1];\n    in->angular_velocity[2] = ahrs.state.get_field<AngularVelocity>()[2];\n    in->acceleration[0] = acceleration[0];\n    in->acceleration[1] = acceleration[1];\n    in->acceleration[2] = acceleration[2];\n}\n\nvoid ukf_set_state(struct ukf_state_t *in) {\n    ahrs.state.set_field<Attitude>(\n        UKF::Quaternion(in->attitude[3], in->attitude[0], in->attitude[1], in->attitude[2]));\n    ahrs.state.set_field<AngularVelocity>(\n        UKF::Vector<3>(in->angular_velocity[0], in->angular_velocity[1], in->angular_velocity[2]));\n}\n\nvoid ukf_get_state_covariance(\n        real_t state_covariance[AHRS_StateVector::covariance_size()*AHRS_StateVector::covariance_size()]) {\n    Eigen::Map<typename AHRS_StateVector::CovarianceMatrix> covariance_map(state_covariance);\n    covariance_map = ahrs.root_covariance * ahrs.root_covariance.transpose();\n}\n\nvoid ukf_get_state_covariance_diagonal(\n        real_t state_covariance_diagonal[AHRS_StateVector::covariance_size()]) {\n    Eigen::Map<UKF::Vector<AHRS_StateVector::covariance_size()>> covariance_map(state_covariance_diagonal);\n    covariance_map = (ahrs.root_covariance * ahrs.root_covariance.transpose()).diagonal();\n}\n\nvoid ukf_get_state_error(struct ukf_state_error_t *in) {\n    AHRS_StateVector::StateVectorDelta state_error;\n    state_error = (ahrs.root_covariance * ahrs.root_covariance.transpose()).cwiseAbs().rowwise().sum().cwiseSqrt();\n\n    in->attitude[0] = state_error[0];\n    in->attitude[1] = state_error[1];\n    in->attitude[2] = state_error[2];\n    in->angular_velocity[0] = state_error[3];\n    in->angular_velocity[1] = state_error[4];\n    in->angular_velocity[2] = state_error[5];\n}\n\n/*\nThis assumes accelerometer, gyroscope and magnetometer measurements are\npresent and in that order.\n*/\nvoid ukf_get_innovation(struct ukf_innovation_t *in) {\n    in->accel[0] = ahrs.innovation[0];\n    in->accel[1] = ahrs.innovation[1];\n    in->accel[2] = ahrs.innovation[2];\n    in->gyro[0] = ahrs.innovation[3];\n    in->gyro[1] = ahrs.innovation[4];\n    in->gyro[2] = ahrs.innovation[5];\n    in->mag[0] = ahrs.innovation[6];\n    in->mag[1] = ahrs.innovation[7];\n    in->mag[2] = ahrs.innovation[8];\n}\n\nvoid ukf_sensor_clear() {\n    meas = AHRS_MeasurementVector();\n}\n\nvoid ukf_sensor_set_accelerometer(real_t x, real_t y, real_t z) {\n    meas.set_field<Accelerometer>(UKF::Vector<3>(x, y, z));\n}\n\nvoid ukf_sensor_set_gyroscope(real_t x, real_t y, real_t z) {\n    meas.set_field<Gyroscope>(UKF::Vector<3>(x, y, z));\n}\n\nvoid ukf_sensor_set_magnetometer(real_t x, real_t y, real_t z) {\n    meas.set_field<Magnetometer>(UKF::Vector<3>(x, y, z));\n}\n\nvoid ukf_set_params(struct ukf_sensor_params_t *in) {\n    ahrs.measurement_root_covariance <<\n        std::sqrt(in->accel_covariance[0]), std::sqrt(in->accel_covariance[1]), std::sqrt(in->accel_covariance[2]),\n        std::sqrt(in->gyro_covariance[0]), std::sqrt(in->gyro_covariance[1]), std::sqrt(in->gyro_covariance[2]),\n        std::sqrt(in->mag_covariance[0]), std::sqrt(in->mag_covariance[1]), std::sqrt(in->mag_covariance[2]);\n    ahrs_errors.measurement_root_covariance << ahrs.measurement_root_covariance;\n}\n\nvoid ukf_iterate(float dt) {\n    /*\n    Split the parameter estimation filter into a priori and a posteriori\n    steps, to reduce the CPU load each iteration.\n    */\n    static int step = 0;\n\n    switch(step++) {\n        case 0:\n            /*\n            The time delta is not used by the parameter estimation filter, so\n            there's no need to adjust it.\n            */\n            ahrs_errors.a_priori_step();\n            ahrs_errors.innovation_step(meas, ahrs.state);\n            break;\n        case 1:\n            ahrs_errors.a_posteriori_step();\n\n            /* Clip parameters to physically reasonable values. */\n            ahrs_errors.state.set_field<MagneticFieldNorm>(\n                std::max(0.2f, std::min(0.7f, ahrs_errors.state.get_field<MagneticFieldNorm>())));\n\n            UKF::Vector<3> temp;\n            temp = ahrs_errors.state.get_field<AccelerometerBias>();\n            temp[0] = std::max(real_t(-G_ACCEL/4.0), std::min(real_t(G_ACCEL/4.0), temp[0]));\n            temp[1] = std::max(real_t(-G_ACCEL/4.0), std::min(real_t(G_ACCEL/4.0), temp[1]));\n            temp[2] = std::max(real_t(-G_ACCEL/4.0), std::min(real_t(G_ACCEL/4.0), temp[2]));\n            ahrs_errors.state.set_field<AccelerometerBias>(temp);\n\n            temp = ahrs_errors.state.get_field<MagnetometerScaleFactor>();\n            temp[0] = std::max(real_t(0.5f), std::min(2.0f, temp[0]));\n            temp[1] = std::max(real_t(0.5f), std::min(2.0f, temp[1]));\n            temp[2] = std::max(real_t(0.5f), std::min(2.0f, temp[2]));\n            ahrs_errors.state.set_field<MagnetometerScaleFactor>(temp);\n\n            step = 0;\n            break;\n    }\n\n    /*\n    Do a normal iteration for the AHRS filter, with the current state of\n    the parameter estimation filter as the measurement input.\n    */\n    ahrs.a_priori_step(dt);\n    ahrs.innovation_step(meas, ahrs_errors.state);\n    ahrs.a_posteriori_step();\n\n    acceleration << meas.get_field<Accelerometer>() - ahrs_errors.state.get_field<AccelerometerBias>() -\n        (ahrs.state.get_field<Attitude>() * UKF::Vector<3>(0, 0, -G_ACCEL));\n}\n\nvoid ukf_set_process_noise(real_t process_noise_covariance[AHRS_StateVector::covariance_size()]) {\n    Eigen::Map<typename AHRS_StateVector::StateVectorDelta> covariance_map(process_noise_covariance);\n    ahrs.process_noise_root_covariance = AHRS_StateVector::CovarianceMatrix::Zero();\n    ahrs.process_noise_root_covariance.diagonal() << covariance_map;\n    ahrs.process_noise_root_covariance = ahrs.process_noise_root_covariance.llt().matrixU();\n}\n\nvoid ukf_get_parameters(struct ukf_sensor_errors_t *in) {\n    in->accel_bias[0] = ahrs_errors.state.get_field<AccelerometerBias>()[0];\n    in->accel_bias[1] = ahrs_errors.state.get_field<AccelerometerBias>()[1];\n    in->accel_bias[2] = ahrs_errors.state.get_field<AccelerometerBias>()[2];\n    in->gyro_bias[0] = ahrs_errors.state.get_field<GyroscopeBias>()[0];\n    in->gyro_bias[1] = ahrs_errors.state.get_field<GyroscopeBias>()[1];\n    in->gyro_bias[2] = ahrs_errors.state.get_field<GyroscopeBias>()[2];\n    in->mag_bias[0] = ahrs_errors.state.get_field<MagnetometerBias>()[0];\n    in->mag_bias[1] = ahrs_errors.state.get_field<MagnetometerBias>()[1];\n    in->mag_bias[2] = ahrs_errors.state.get_field<MagnetometerBias>()[2];\n    in->mag_scale[0] = ahrs_errors.state.get_field<MagnetometerScaleFactor>()[0];\n    in->mag_scale[1] = ahrs_errors.state.get_field<MagnetometerScaleFactor>()[1];\n    in->mag_scale[2] = ahrs_errors.state.get_field<MagnetometerScaleFactor>()[2];\n    in->mag_field_norm = ahrs_errors.state.get_field<MagneticFieldNorm>();\n    in->mag_field_inclination = std::atan(ahrs_errors.state.get_field<MagneticFieldInclination>());\n}\n\nvoid ukf_get_parameters_error(struct ukf_sensor_errors_t *in) {\n    AHRS_SensorErrorVector::StateVectorDelta parameters_error;\n    parameters_error =\n        (ahrs_errors.root_covariance * ahrs_errors.root_covariance.transpose()).cwiseAbs().rowwise().sum().cwiseSqrt();\n\n    in->accel_bias[0] = parameters_error[0];\n    in->accel_bias[1] = parameters_error[1];\n    in->accel_bias[2] = parameters_error[2];\n    in->gyro_bias[0] = parameters_error[3];\n    in->gyro_bias[1] = parameters_error[4];\n    in->gyro_bias[2] = parameters_error[5];\n    in->mag_bias[0] = parameters_error[6];\n    in->mag_bias[1] = parameters_error[7];\n    in->mag_bias[2] = parameters_error[8];\n    in->mag_scale[0] = parameters_error[9];\n    in->mag_scale[1] = parameters_error[10];\n    in->mag_scale[2] = parameters_error[11];\n    in->mag_field_norm = parameters_error[12];\n    in->mag_field_inclination = parameters_error[13];\n}\n\nuint32_t ukf_config_get_state_dim() {\n    return AHRS_StateVector::covariance_size();\n}\n\nuint32_t ukf_config_get_measurement_dim() {\n    return AHRS_MeasurementVector::max_size();\n}\n\nenum ukf_precision_t ukf_config_get_precision() {\n    if(sizeof(real_t) == 8) {\n        return UKF_PRECISION_DOUBLE;\n    } else {\n        return UKF_PRECISION_FLOAT;\n    }\n}\n", "meta": {"hexsha": "93f54e79d49a128959995a4b3b28e92d73a0ba1a", "size": 18136, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/ahrs/ahrs.cpp", "max_stars_repo_name": "rafaelrietmann/ukf", "max_stars_repo_head_hexsha": "bf53dacafbfee8c7591c48a66b50229f82afe4b4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 320.0, "max_stars_repo_stars_event_min_datetime": "2015-01-07T05:49:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:52:15.000Z", "max_issues_repo_path": "examples/ahrs/ahrs.cpp", "max_issues_repo_name": "msnh2012/ukf", "max_issues_repo_head_hexsha": "04f0a996fee1f49699142bf5b149548a8d3a4ad1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 22.0, "max_issues_repo_issues_event_min_datetime": "2015-03-03T17:28:32.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T14:46:54.000Z", "max_forks_repo_path": "examples/ahrs/ahrs.cpp", "max_forks_repo_name": "msnh2012/ukf", "max_forks_repo_head_hexsha": "04f0a996fee1f49699142bf5b149548a8d3a4ad1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 155.0, "max_forks_repo_forks_event_min_datetime": "2015-02-20T01:18:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-22T01:58:53.000Z", "avg_line_length": 38.7521367521, "max_line_length": 119, "alphanum_fraction": 0.7040692545, "num_tokens": 5057, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835330070839, "lm_q2_score": 0.5698526514141572, "lm_q1q2_score": 0.4761025064969543}}
{"text": "/*\n ___ ___ __     __ ____________\n|   |   |  |   |__|__|__   ___/  Ubiquitout Internet @ IIT-CNR\n|   |   |  |  /__/  /  /  /      C++ support library\n|   |   |  |/__/  /   /  /       https://github.com/ccicconetti/support/\n|_______|__|__/__/   /__/\n\nLicensed under the MIT License <http://opensource.org/licenses/MIT>.\nCopyright (c) 2019 Claudio Cicconetti https://ccicconetti.github.io/\n\nPermission is hereby  granted, free of charge, to any  person obtaining a copy\nof this software and associated  documentation files (the \"Software\"), to deal\nin the Software  without restriction, including without  limitation the rights\nto  use, copy,  modify, merge,  publish, distribute,  sublicense, and/or  sell\ncopies  of  the Software,  and  to  permit persons  to  whom  the Software  is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE  IS PROVIDED \"AS  IS\", WITHOUT WARRANTY  OF ANY KIND,  EXPRESS OR\nIMPLIED,  INCLUDING BUT  NOT  LIMITED TO  THE  WARRANTIES OF  MERCHANTABILITY,\nFITNESS FOR  A PARTICULAR PURPOSE AND  NONINFRINGEMENT. IN NO EVENT  SHALL THE\nAUTHORS  OR COPYRIGHT  HOLDERS  BE  LIABLE FOR  ANY  CLAIM,  DAMAGES OR  OTHER\nLIABILITY, WHETHER IN AN ACTION OF  CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE  OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*/\n\n#include \"stat.h\"\n\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\nnamespace bacc = boost::accumulators;\n\nnamespace uiiit {\nnamespace support {\n\nclass Accumulator final\n{\n public:\n  Accumulator()\n      : theObj() {\n  }\n\n  ~Accumulator() {}\n\n  boost::accumulators::accumulator_set<\n      SummaryStat::Real,\n      boost::accumulators::stats<boost::accumulators::tag::mean,\n                                 boost::accumulators::tag::variance,\n                                 boost::accumulators::tag::min,\n                                 boost::accumulators::tag::max>>\n      theObj;\n};\n\nSummaryStat::SummaryStat()\n    : theAcc(new Accumulator()) {\n}\n\nSummaryStat::~SummaryStat() {\n}\n\nvoid SummaryStat::operator()(const Real aValue) {\n  theAcc->theObj(aValue);\n}\n\nvoid SummaryStat::reset() {\n  theAcc = std::make_unique<Accumulator>();\n}\n\nSummaryStat::Real SummaryStat::mean() const {\n  return bacc::mean(theAcc->theObj);\n}\n\nSummaryStat::Real SummaryStat::min() const {\n  return bacc::min(theAcc->theObj);\n}\n\nSummaryStat::Real SummaryStat::max() const {\n  return bacc::max(theAcc->theObj);\n}\n\nbool SummaryStat::empty() const {\n  return bacc::count(theAcc->theObj) == 0;\n}\n\nsize_t SummaryStat::count() const {\n  return bacc::count(theAcc->theObj);\n}\n\nSummaryStat::Real SummaryStat::stddev() const {\n  return sqrt(bacc::variance(theAcc->theObj));\n}\n\n} // namespace support\n} // namespace uiiit\n", "meta": {"hexsha": "1bf80e653d75f053e79e52d94ef8a8abec4ef052", "size": 3103, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Support/stat.cpp", "max_stars_repo_name": "ccicconetti/support", "max_stars_repo_head_hexsha": "d2535294de845eafc0ba237b2daee225c62e7f06", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Support/stat.cpp", "max_issues_repo_name": "ccicconetti/support", "max_issues_repo_head_hexsha": "d2535294de845eafc0ba237b2daee225c62e7f06", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Support/stat.cpp", "max_forks_repo_name": "ccicconetti/support", "max_forks_repo_head_hexsha": "d2535294de845eafc0ba237b2daee225c62e7f06", "max_forks_repo_licenses": ["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.1262135922, "max_line_length": 78, "alphanum_fraction": 0.6964228166, "num_tokens": 788, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.47610007758609907}}
{"text": "#define BOOST_TEST_MODULE pcraster geo scan_conversion\n#include <boost/test/unit_test.hpp>\n#include <algorithm>\n#include \"geo_scanconversion.h\"\n\n\nBOOST_AUTO_TEST_CASE(midpoint_line)\n{\n  using namespace geo;\n\n  {\n    // N line.\n    RememberPoints<size_t> points;\n    points = midpointLine(0, 0, 0, 2, points);\n    BOOST_CHECK(points.size() == 3);\n    BOOST_CHECK(points[0] == (std::pair<size_t, size_t>(0, 0)));\n    BOOST_CHECK(points[1] == (std::pair<size_t, size_t>(0, 1)));\n    BOOST_CHECK(points[2] == (std::pair<size_t, size_t>(0, 2)));\n  }\n\n  {\n    // S line.\n    RememberPoints<size_t> points;\n    points = midpointLine(0, 2, 0, 0, points);\n    BOOST_CHECK(points.size() == 3);\n    BOOST_CHECK(points[0] == (std::pair<size_t, size_t>(0, 2)));\n    BOOST_CHECK(points[1] == (std::pair<size_t, size_t>(0, 1)));\n    BOOST_CHECK(points[2] == (std::pair<size_t, size_t>(0, 0)));\n  }\n\n  {\n    // E line.\n    RememberPoints<size_t> points;\n    points = midpointLine(0, 0, 2, 0, points);\n    BOOST_CHECK(points.size() == 3);\n    BOOST_CHECK(points[0] == (std::pair<size_t, size_t>(0, 0)));\n    BOOST_CHECK(points[1] == (std::pair<size_t, size_t>(1, 0)));\n    BOOST_CHECK(points[2] == (std::pair<size_t, size_t>(2, 0)));\n  }\n\n  {\n    // W line.\n    RememberPoints<size_t> points;\n    points = midpointLine(2, 0, 0, 0, points);\n    BOOST_CHECK(points.size() == 3);\n    BOOST_CHECK(points[0] == (std::pair<size_t, size_t>(2, 0)));\n    BOOST_CHECK(points[1] == (std::pair<size_t, size_t>(1, 0)));\n    BOOST_CHECK(points[2] == (std::pair<size_t, size_t>(0, 0)));\n  }\n\n  {\n    // NE line.\n    RememberPoints<size_t> points;\n    points = midpointLine(0, 0, 2, 2, points);\n    BOOST_CHECK(points.size() == 3);\n    BOOST_CHECK(points[0] == (std::pair<size_t, size_t>(0, 0)));\n    BOOST_CHECK(points[1] == (std::pair<size_t, size_t>(1, 1)));\n    BOOST_CHECK(points[2] == (std::pair<size_t, size_t>(2, 2)));\n  }\n\n  {\n    // NW line.\n    RememberPoints<size_t> points;\n    points = midpointLine(2, 0, 0, 2, points);\n    BOOST_CHECK(points.size() == 3);\n    BOOST_CHECK(points[0] == (std::pair<size_t, size_t>(2, 0)));\n    BOOST_CHECK(points[1] == (std::pair<size_t, size_t>(1, 1)));\n    BOOST_CHECK(points[2] == (std::pair<size_t, size_t>(0, 2)));\n  }\n\n  {\n    // SW line.\n    RememberPoints<size_t> points;\n    points = midpointLine(2, 2, 0, 0, points);\n    BOOST_CHECK(points.size() == 3);\n    BOOST_CHECK(points[0] == (std::pair<size_t, size_t>(2, 2)));\n    BOOST_CHECK(points[1] == (std::pair<size_t, size_t>(1, 1)));\n    BOOST_CHECK(points[2] == (std::pair<size_t, size_t>(0, 0)));\n  }\n\n  {\n    // SE line.\n    RememberPoints<size_t> points;\n    points = midpointLine(0, 2, 2, 0, points);\n    BOOST_CHECK(points.size() == 3);\n    BOOST_CHECK(points[0] == (std::pair<size_t, size_t>(0, 2)));\n    BOOST_CHECK(points[1] == (std::pair<size_t, size_t>(1, 1)));\n    BOOST_CHECK(points[2] == (std::pair<size_t, size_t>(2, 0)));\n  }\n\n  {\n    // ENE line.\n    RememberPoints<size_t> points;\n    points = midpointLine(5, 8, 9, 11, points);\n    BOOST_CHECK(points.size() == 5);\n    BOOST_CHECK(points[0] == (std::pair<size_t, size_t>(5, 8)));\n    BOOST_CHECK(points[1] == (std::pair<size_t, size_t>(6, 9)));\n    BOOST_CHECK(points[2] == (std::pair<size_t, size_t>(7, 9)));\n    BOOST_CHECK(points[3] == (std::pair<size_t, size_t>(8, 10)));\n    BOOST_CHECK(points[4] == (std::pair<size_t, size_t>(9, 11)));\n  }\n\n  {\n    // WSW line.\n    RememberPoints<int> points;\n    points = midpointLine(-5, -8, -9, -11, points);\n    BOOST_CHECK(points.size() == 5);\n    BOOST_CHECK(points[0] == (std::pair<int, int>(-5, -8)));\n    BOOST_CHECK(points[1] == (std::pair<int, int>(-6, -9)));\n    BOOST_CHECK(points[2] == (std::pair<int, int>(-7, -9)));\n    BOOST_CHECK(points[3] == (std::pair<int, int>(-8, -10)));\n    BOOST_CHECK(points[4] == (std::pair<int, int>(-9, -11)));\n  }\n\n  {\n    // NNE line.\n    RememberPoints<size_t> points;\n    points = midpointLine(8, 5, 11, 9, points);\n    BOOST_CHECK(points.size() == 5);\n    BOOST_CHECK(points[0] == (std::pair<size_t, size_t>(8, 5)));\n    BOOST_CHECK(points[1] == (std::pair<size_t, size_t>(9, 6)));\n    BOOST_CHECK(points[2] == (std::pair<size_t, size_t>(9, 7)));\n    BOOST_CHECK(points[3] == (std::pair<size_t, size_t>(10, 8)));\n    BOOST_CHECK(points[4] == (std::pair<size_t, size_t>(11, 9)));\n  }\n\n  {\n    // ESE line.\n    RememberPoints<int> points;\n    points = midpointLine<int>(5, -8, 9, -11, points);\n    BOOST_CHECK(points.size() == 5);\n    BOOST_CHECK(points[0] == (std::pair<int, int>(5, -8)));\n    BOOST_CHECK(points[1] == (std::pair<int, int>(6, -9)));\n    BOOST_CHECK(points[2] == (std::pair<int, int>(7, -9)));\n    BOOST_CHECK(points[3] == (std::pair<int, int>(8, -10)));\n    BOOST_CHECK(points[4] == (std::pair<int, int>(9, -11)));\n  }\n\n  {\n    // WNW line.\n    RememberPoints<int> points;\n    points = midpointLine(-5, 8, -9, 11, points);\n    BOOST_CHECK(points.size() == 5);\n    BOOST_CHECK(points[0] == (std::pair<int, int>(-5, 8)));\n    BOOST_CHECK(points[1] == (std::pair<int, int>(-6, 9)));\n    BOOST_CHECK(points[2] == (std::pair<int, int>(-7, 9)));\n    BOOST_CHECK(points[3] == (std::pair<int, int>(-8, 10)));\n    BOOST_CHECK(points[4] == (std::pair<int, int>(-9, 11)));\n  }\n\n  {\n    // SSE line.\n    RememberPoints<int> points;\n    points = midpointLine<int>(8, -5, 11, -9, points);\n    BOOST_CHECK(points.size() == 5);\n    BOOST_CHECK(points[0] == (std::pair<int, int>(8, -5)));\n    BOOST_CHECK(points[1] == (std::pair<int, int>(9, -6)));\n    BOOST_CHECK(points[2] == (std::pair<int, int>(9, -7)));\n    BOOST_CHECK(points[3] == (std::pair<int, int>(10, -8)));\n    BOOST_CHECK(points[4] == (std::pair<int, int>(11, -9)));\n  }\n\n  {\n    // NNW line.\n    RememberPoints<int> points;\n    points = midpointLine(-8, 5, -11, 9, points);\n    BOOST_CHECK(points.size() == 5);\n    BOOST_CHECK(points[0] == (std::pair<int, int>(-8, 5)));\n    BOOST_CHECK(points[1] == (std::pair<int, int>(-9, 6)));\n    BOOST_CHECK(points[2] == (std::pair<int, int>(-9, 7)));\n    BOOST_CHECK(points[3] == (std::pair<int, int>(-10, 8)));\n    BOOST_CHECK(points[4] == (std::pair<int, int>(-11, 9)));\n  }\n}\n\n\n\ntemplate<class Integral>\nvoid testCirclePoints(\n         const geo::RememberPoints<Integral>& points,\n         const std::pair<Integral, Integral>& point) {\n  typedef std::pair<Integral, Integral> Point;\n  Integral x = point.first;\n  Integral y = point.second;\n\n  BOOST_CHECK(std::find(points.begin(), points.end(),\n         Point(x, y)) != points.end());\n  BOOST_CHECK(std::find(points.begin(), points.end(),\n         Point(x, -y)) != points.end());\n  BOOST_CHECK(std::find(points.begin(), points.end(),\n         Point(-x, -y)) != points.end());\n  BOOST_CHECK(std::find(points.begin(), points.end(),\n         Point(-x, y)) != points.end());\n  BOOST_CHECK(std::find(points.begin(), points.end(),\n         Point(y, x)) != points.end());\n  BOOST_CHECK(std::find(points.begin(), points.end(),\n         Point(y, -x)) != points.end());\n  BOOST_CHECK(std::find(points.begin(), points.end(),\n         Point(-y, -x)) != points.end());\n  BOOST_CHECK(std::find(points.begin(), points.end(),\n         Point(-y, x)) != points.end());\n}\n\n\nBOOST_AUTO_TEST_CASE(midpoint_circle_nr_points)\n{\n  using namespace geo;\n\n  {\n    RememberPoints<int> points;\n    points = midpointCircle(0, 0, 0, points);\n    BOOST_CHECK(points.size() == 1);\n  }\n\n  {\n    RememberPoints<int> points;\n    points = midpointCircle(0, 0, 1, points);\n    BOOST_CHECK(points.size() == 4);\n  }\n\n  {\n    RememberPoints<int> points;\n    points = midpointCircle(0, 0, 0, 1, points);\n    BOOST_CHECK(points.size() == 5);\n  }\n\n  {\n    RememberPoints<int> points;\n    points = midpointCircle(0, 0, 2, points);\n    BOOST_CHECK(points.size() == 12);\n  }\n\n  {\n    RememberPoints<int> points;\n    points = midpointCircle(0, 0, 0, 2, points);\n    BOOST_CHECK(points.size() == 21);\n  }\n\n  {\n    RememberPoints<int> points;\n    points = midpointCircle(0, 0, 1, 2, points);\n    BOOST_CHECK(points.size() == 20);\n  }\n}\n\n\nBOOST_AUTO_TEST_CASE(midpoint_circle)\n{\n  using namespace geo;\n\n  typedef std::pair<int, int> Point;\n\n  {\n    RememberPoints<int> points;\n    points = midpointCircle(0, 0, 1, points);\n    BOOST_CHECK(points.size() == 4);\n    BOOST_CHECK(std::find(points.begin(), points.end(),\n         Point(0, 1)) != points.end());\n    BOOST_CHECK(std::find(points.begin(), points.end(),\n         Point(1, 0)) != points.end());\n    BOOST_CHECK(std::find(points.begin(), points.end(),\n         Point(0, -1)) != points.end());\n    BOOST_CHECK(std::find(points.begin(), points.end(),\n         Point(-1, 0)) != points.end());\n  }\n\n  {\n    RememberPoints<int> points;\n    points = midpointCircle(0, 0, 17, points);\n    BOOST_CHECK(points.size() == 96);\n    std::vector<Point> pointsInOctant;\n    pointsInOctant.push_back(Point( 0, 17));\n    pointsInOctant.push_back(Point( 1, 17));\n    pointsInOctant.push_back(Point( 2, 17));\n    pointsInOctant.push_back(Point( 3, 17));\n    pointsInOctant.push_back(Point( 4, 17));\n    pointsInOctant.push_back(Point( 5, 16));\n    pointsInOctant.push_back(Point( 6, 16));\n    pointsInOctant.push_back(Point( 7, 15));\n    pointsInOctant.push_back(Point( 8, 15));\n    pointsInOctant.push_back(Point( 9, 14));\n    pointsInOctant.push_back(Point(10, 14));\n    pointsInOctant.push_back(Point(11, 13));\n    pointsInOctant.push_back(Point(12, 12));\n    pointsInOctant.push_back(Point(17,  0));\n\n    for(std::vector<Point>::const_iterator it = pointsInOctant.begin();\n         it != pointsInOctant.end(); ++it) {\n      testCirclePoints(points, *it);\n    }\n  }\n\n  {\n    RememberPoints<int> innerPoints;\n    innerPoints = midpointCircle(0, 0, 13, innerPoints);\n    BOOST_CHECK(innerPoints.size() == 72);\n    std::vector<Point> pointsInOctant;\n    pointsInOctant.push_back(Point( 0, 13));\n    pointsInOctant.push_back(Point( 1, 13));\n    pointsInOctant.push_back(Point( 2, 13));\n    pointsInOctant.push_back(Point( 3, 13));\n    pointsInOctant.push_back(Point( 4, 12));\n    pointsInOctant.push_back(Point( 5, 12));\n    pointsInOctant.push_back(Point( 6, 12));\n    pointsInOctant.push_back(Point( 7, 11));\n    pointsInOctant.push_back(Point( 8, 10));\n    pointsInOctant.push_back(Point( 9,  9));\n\n    for(std::vector<Point>::const_iterator it = pointsInOctant.begin();\n         it != pointsInOctant.end(); ++it) {\n      testCirclePoints(innerPoints, *it);\n    }\n\n    size_t nrPointsInnerOctant = static_cast<size_t>(static_cast<double>(\n         innerPoints.size()) / 8.0) - 1;\n    BOOST_CHECK(nrPointsInnerOctant == 8);\n\n    RememberPoints<int> outerPoints;\n    outerPoints = midpointCircle(0, 0, 17, outerPoints);\n\n    size_t nrPointsOuterOctant = static_cast<size_t>(static_cast<double>(\n         outerPoints.size()) / 8.0) - 1;\n    BOOST_CHECK(nrPointsOuterOctant == 11);\n  }\n\n  {\n    RememberPoints<int> points;\n    points = midpointCircle(0, 0, 13, 17, points);\n    BOOST_CHECK(points.size() == 460);\n\n    std::vector<Point> pointsInOctant;\n\n    // Inner circle.\n    pointsInOctant.push_back(Point( 0, 13));\n    pointsInOctant.push_back(Point( 1, 13));\n    pointsInOctant.push_back(Point( 2, 13));\n    pointsInOctant.push_back(Point( 3, 13));\n    pointsInOctant.push_back(Point( 4, 12));\n    pointsInOctant.push_back(Point( 5, 12));\n    pointsInOctant.push_back(Point( 6, 12));\n    pointsInOctant.push_back(Point( 7, 11));\n    pointsInOctant.push_back(Point( 8, 10));\n    pointsInOctant.push_back(Point( 9,  9));\n\n    // Outer circle.\n    pointsInOctant.push_back(Point( 0, 17));\n    pointsInOctant.push_back(Point( 1, 17));\n    pointsInOctant.push_back(Point( 2, 17));\n    pointsInOctant.push_back(Point( 3, 17));\n    pointsInOctant.push_back(Point( 4, 17));\n    pointsInOctant.push_back(Point( 5, 16));\n    pointsInOctant.push_back(Point( 6, 16));\n    pointsInOctant.push_back(Point( 7, 15));\n    pointsInOctant.push_back(Point( 8, 15));\n    pointsInOctant.push_back(Point( 9, 14));\n    pointsInOctant.push_back(Point(10, 14));\n    pointsInOctant.push_back(Point(11, 13));\n    pointsInOctant.push_back(Point(12, 12));\n\n    // Points between circles.\n    pointsInOctant.push_back(Point( 0, 14));\n    pointsInOctant.push_back(Point( 0, 15));\n    pointsInOctant.push_back(Point( 0, 16));\n    pointsInOctant.push_back(Point( 1, 14));\n    pointsInOctant.push_back(Point( 1, 15));\n    pointsInOctant.push_back(Point( 1, 16));\n    pointsInOctant.push_back(Point( 2, 14));\n    pointsInOctant.push_back(Point( 2, 15));\n    pointsInOctant.push_back(Point( 2, 16));\n    pointsInOctant.push_back(Point( 3, 14));\n    pointsInOctant.push_back(Point( 3, 15));\n    pointsInOctant.push_back(Point( 3, 16));\n    pointsInOctant.push_back(Point( 4, 13));\n    pointsInOctant.push_back(Point( 4, 14));\n    pointsInOctant.push_back(Point( 4, 15));\n    pointsInOctant.push_back(Point( 4, 16));\n    pointsInOctant.push_back(Point( 5, 13));\n    pointsInOctant.push_back(Point( 5, 14));\n    pointsInOctant.push_back(Point( 5, 15));\n    pointsInOctant.push_back(Point( 6, 13));\n    pointsInOctant.push_back(Point( 6, 14));\n    pointsInOctant.push_back(Point( 6, 15));\n    pointsInOctant.push_back(Point( 7, 12));\n    pointsInOctant.push_back(Point( 7, 13));\n    pointsInOctant.push_back(Point( 7, 14));\n    pointsInOctant.push_back(Point( 8, 11));\n    pointsInOctant.push_back(Point( 8, 12));\n    pointsInOctant.push_back(Point( 8, 13));\n    pointsInOctant.push_back(Point( 8, 14));\n    pointsInOctant.push_back(Point( 9, 10));\n    pointsInOctant.push_back(Point( 9, 11));\n    pointsInOctant.push_back(Point( 9, 12));\n    pointsInOctant.push_back(Point( 9, 13));\n    pointsInOctant.push_back(Point(10, 10));\n    pointsInOctant.push_back(Point(10, 11));\n    pointsInOctant.push_back(Point(10, 12));\n    pointsInOctant.push_back(Point(10, 13));\n    pointsInOctant.push_back(Point(11, 11));\n    pointsInOctant.push_back(Point(11, 12));\n\n    for(std::vector<Point>::const_iterator it = pointsInOctant.begin();\n         it != pointsInOctant.end(); ++it) {\n      testCirclePoints(points, *it);\n    }\n  }\n}\n", "meta": {"hexsha": "4ea6ade0e4c3e9c7284ed3216904713180832958", "size": 13959, "ext": "cc", "lang": "C++", "max_stars_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcrgeo/geo_scanconversiontest.cc", "max_stars_repo_name": "quanpands/wflow", "max_stars_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcrgeo/geo_scanconversiontest.cc", "max_issues_repo_name": "quanpands/wflow", "max_issues_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcrgeo/geo_scanconversiontest.cc", "max_forks_repo_name": "quanpands/wflow", "max_forks_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.2972972973, "max_line_length": 73, "alphanum_fraction": 0.6228239845, "num_tokens": 4398, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431679972357831, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.47610007539675575}}
{"text": "//\n// Created by foxfire on 1/20/18.\n//\n\n#ifndef GFX_OPENGL_HPP\n#define GFX_OPENGL_HPP\n\n#include \"gfx.hpp\"\n\n#include <cstdint>\n\n#define _USE_MATH_DEFINES\n#include <GL/glew.h>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\nnamespace fox\n{\n\tclass counter;\n}\nstruct OBJ_MODEL;\n\nclass gfx_opengl : public gfx\n{\npublic:\n\tgfx_opengl();\n\t\n\t~gfx_opengl() override;\n\t\n\tvoid init(int w, int h) override;\n\t\n\tvoid render() override;\n\t\n\tvoid resize(int w, int h) override;\n\t\n\tvoid deinit() override;\n\nprivate:\n\tint win_w, win_h;\n\t// an empty vertex array object to bind to\n\tuint32_t default_vao;\n\t\n\tEigen::Vector3f eye, target, up;\n\tEigen::Affine3f V;\n\tEigen::Projective3f P;\n\t// model matrix (specific to the model instance)\n\tEigen::Projective3f MVP;\n\tEigen::Affine3f M, MV;\n\t// TODO: should this be Affine3f ?\n\tEigen::Matrix3f normal_matrix;\n\t// more shader uniforms\n\tEigen::Vector4f light_pos, color;\n\tEigen::Vector3f La, Ls, Ld;\n\tEigen::Vector3f Ka, Ks, Kd;\n\tfloat shininess;\n\tEigen::Vector3f rot, trans;\n\tfloat scale;\n\t\n\tGLuint shader_id, shader_vert_id, shader_frag_id;\n\tGLuint vertex_vbo, normal_vbo;\n\t\n\tfox::counter *update_counter;\n\tfox::counter *fps_counter;\n\t\n\tfloat rot_vel;\n\t\n\tOBJ_MODEL *mesh;\n\t\n\tvoid print_info();\n\tvoid load_shaders();\n};\n\n\n#endif //GFX_OPENGL_HPP\n", "meta": {"hexsha": "8ea78e42a4f4222cbf36901f2c32572734e3215c", "size": 1269, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "gfx/gfx_opengl.hpp", "max_stars_repo_name": "foxfire256/opengl_testing1", "max_stars_repo_head_hexsha": "3e379540a1e9a651caf80e5b593015ebaa56d403", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gfx/gfx_opengl.hpp", "max_issues_repo_name": "foxfire256/opengl_testing1", "max_issues_repo_head_hexsha": "3e379540a1e9a651caf80e5b593015ebaa56d403", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gfx/gfx_opengl.hpp", "max_forks_repo_name": "foxfire256/opengl_testing1", "max_forks_repo_head_hexsha": "3e379540a1e9a651caf80e5b593015ebaa56d403", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.92, "max_line_length": 50, "alphanum_fraction": 0.7186761229, "num_tokens": 373, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.4761000724871216}}
{"text": "\n#include <algorithm>\n#include <numeric>\n#include <cmath>\n\n#include <boost/tuple/tuple.hpp>\n\n#include <ConsensusCore/Interval.hpp>\n#include <ConsensusCore/LValue.hpp>\n\n\nnamespace ConsensusCore {\n\ntemplate<typename M>\nScaledMatrix<M>::ScaledMatrix(int rows, int cols)\n    : M(rows, cols)\n    , logScalars_(cols, static_cast<F>(0))\n{ }\n\ntemplate<typename M>\nScaledMatrix<M>::ScaledMatrix(const ScaledMatrix<M>& other)\n    : M(other)\n    , logScalars_(other.logScalars_)\n{ }\n\ntemplate<typename M>\ninline const ScaledMatrix<M>&\nScaledMatrix<M>::Null()\n{\n    static ScaledMatrix<M>* nullObj = new ScaledMatrix<M>(0, 0);\n    return *nullObj;\n}\n\ntemplate<typename M>\ninline void\nScaledMatrix<M>::FinishEditingColumn(int j, int usedBegin, int usedEnd)\n{\n    // get the constant to scale by\n    F c = static_cast<F>(0);\n    for (int i = usedBegin; i < usedEnd; ++i)\n    {\n        c = std::max(c, M::Get(i, j));\n    }\n\n    // set it\n    if (c != static_cast<F>(0) && c != static_cast<F>(1))\n    {\n        for (int i = usedBegin; i < usedEnd; ++i)\n        {\n            M::Set(i, j, M::Get(i, j) / c);\n        }\n        logScalars_[j] = std::log(c);\n    }\n    else\n    {\n        logScalars_[j] = static_cast<F>(0);\n    }\n\n    M::FinishEditingColumn(j, usedBegin, usedEnd);\n}\n\ntemplate<typename M>\ninline typename M::FloatType\nScaledMatrix<M>::GetLogScale(int j) const\n{\n    return logScalars_[j];\n}\n\ntemplate<typename M>\ninline typename M::FloatType\nScaledMatrix<M>::GetLogProdScales(int beginColumn, int endColumn) const\n{\n    return std::accumulate(logScalars_.begin() + beginColumn,\n                           logScalars_.begin() + endColumn,\n                           static_cast<F>(0));\n}\n\ntemplate<typename M>\ninline typename M::FloatType\nScaledMatrix<M>::GetLogProdScales() const\n{\n    return std::accumulate(logScalars_.begin(),\n                           logScalars_.end(),\n                           static_cast<F>(0));\n}\n\n}\n", "meta": {"hexsha": "670c5c5fdccce18d5aa50774bb9ebca39c764999", "size": 1925, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ConsensusCore/include/ConsensusCore/Matrix/ScaledMatrix-inl.hpp", "max_stars_repo_name": "pb-cdunn/pbccs", "max_stars_repo_head_hexsha": "fb327a7145791d3c023bc63717f5de2925225ccc", "max_stars_repo_licenses": ["BSD-3-Clause-Clear"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ConsensusCore/include/ConsensusCore/Matrix/ScaledMatrix-inl.hpp", "max_issues_repo_name": "pb-cdunn/pbccs", "max_issues_repo_head_hexsha": "fb327a7145791d3c023bc63717f5de2925225ccc", "max_issues_repo_licenses": ["BSD-3-Clause-Clear"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ConsensusCore/include/ConsensusCore/Matrix/ScaledMatrix-inl.hpp", "max_forks_repo_name": "pb-cdunn/pbccs", "max_forks_repo_head_hexsha": "fb327a7145791d3c023bc63717f5de2925225ccc", "max_forks_repo_licenses": ["BSD-3-Clause-Clear"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.875, "max_line_length": 71, "alphanum_fraction": 0.6176623377, "num_tokens": 504, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.6406358548398982, "lm_q1q2_score": 0.4761000724871216}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#pragma once\n\n#include <boost/preprocessor/arithmetic/dec.hpp>\n#include <boost/preprocessor/arithmetic/inc.hpp>\n#include <boost/preprocessor/control/expr_iif.hpp>\n#include <boost/preprocessor/list/adt.hpp>\n#include <boost/preprocessor/repetition/for.hpp>\n#include <boost/preprocessor/repetition/repeat.hpp>\n#include <boost/preprocessor/tuple/to_list.hpp>\n#include <limits>\n#include <pup.h>\n#include <vector>\n\n#include \"DataStructures/Tensor/TypeAliases.hpp\"\n#include \"Options/Options.hpp\"\n#include \"Parallel/CharmPupable.hpp\"\n#include \"PointwiseFunctions/Hydro/EquationsOfState/EquationOfState.hpp\"  // IWYU pragma: keep\n#include \"Utilities/Math.hpp\"\n#include \"Utilities/TMPL.hpp\"\n\n/// \\cond\nclass DataVector;\n/// \\endcond\n\n// IWYU pragma: no_forward_declare Tensor\n\nnamespace EquationsOfState {\n/*!\n * \\ingroup EquationsOfStateGroup\n * \\brief A spectral equation of state\n *\n * This equation of state is determined as a function of \\f$x =\n * \\ln(\\rho/\\rho_0)\\f$ where \\f$\\rho\\f$ is the rest mass density and\n * \\f$\\rho_0\\f$ is the provided reference density.  The adiabatic\n * index \\f$\\Gamma(x)\\f$ is defined such that\n * \\f{equation}{\n * \\frac{d \\ln p}{dx} = \\Gamma(x) = \\sum_{n=0}^N\n * \\gamma_n x^n\n * \\f}\n *\n * for the set of spectral coefficinets \\f$\\gamma_n\\f$ when\n * \\f$0 < x < x_u = \\ln(\\rho_u/\\rho_0)\\f$, where \\f$\\rho_u\\f$ is the provided\n * upper density.\n *\n * For \\f$ x < 0 \\f$, \\f$ \\Gamma(x) = \\gamma_0 \\f$.\n *\n * For \\f$ x > x_u \\f$, \\f$ \\Gamma(x) = \\Gamma(x_u) \\f$\n *\n *\n */\nclass Spectral : public EquationOfState<true, 1> {\n public:\n  static constexpr size_t thermodynamic_dim = 1;\n  static constexpr bool is_relativistic = true;\n\n  struct ReferenceDensity {\n    using type = double;\n    static constexpr Options::String help = {\"Reference density rho_0\"};\n    static double lower_bound() { return 0.0; }\n  };\n\n  struct ReferencePressure {\n    using type = double;\n    static constexpr Options::String help = {\"Reference pressure p_0\"};\n    static double lower_bound() { return 0.0; }\n  };\n\n  struct Coefficients {\n    using type = std::vector<double>;\n    static constexpr Options::String help = {\"Spectral coefficients gamma_i\"};\n  };\n\n  struct UpperDensity {\n    using type = double;\n    static constexpr Options::String help = {\"Upper density rho_u\"};\n    static double lower_bound() { return 0.0; }\n  };\n\n  static constexpr Options::String help = {\n      \"A spectral equation of state.  Defining x = log(rho/rho_0), Gamma(x) = \"\n      \"Sum_i gamma_i x^i, then the pressure is determined from d(log P)/dx = \"\n      \"Gamma(x) for x > 0.  For x < 0 the EOS is a polytrope with \"\n      \"Gamma(x)=Gamma(0).  For x > x_u = log(rho_u/rho_0), Gamma(x) = \"\n      \"Gamma(x_u).\\n\"\n      \"To get smooth equations of state, it is recommended that the second \"\n      \"and third supplied coefficient should be 0. It is up to the user to \"\n      \"choose coefficients that are physically reasonable, e.g. that \"\n      \"satisfy causality.\"};\n\n  using options = tmpl::list<ReferenceDensity, ReferencePressure, Coefficients,\n                             UpperDensity>;\n\n  Spectral() = default;\n  Spectral(const Spectral&) = default;\n  Spectral& operator=(const Spectral&) = default;\n  Spectral(Spectral&&) = default;\n  Spectral& operator=(Spectral&&) = default;\n  ~Spectral() override = default;\n\n  Spectral(double reference_density, double reference_pressure,\n           std::vector<double> coefficients, double upper_density);\n\n  EQUATION_OF_STATE_FORWARD_DECLARE_MEMBERS(Spectral, 1)\n\n  WRAPPED_PUPable_decl_base_template(  // NOLINT\n      SINGLE_ARG(EquationOfState<true, 1>), Spectral);\n\n  /// The lower bound of the rest mass density that is valid for this EOS\n  double rest_mass_density_lower_bound() const override { return 0.0; }\n\n  /// The upper bound of the rest mass density that is valid for this EOS\n  double rest_mass_density_upper_bound() const override {\n    return std::numeric_limits<double>::max();\n  }\n\n  /// The lower bound of the specific internal energy that is valid for this EOS\n  /// at the given rest mass density \\f$\\rho\\f$\n  double specific_internal_energy_lower_bound(\n      const double /* rest_mass_density */) const override {\n    return 0.0;\n  }\n\n  /// The upper bound of the specific internal energy that is valid for this EOS\n  /// at the given rest mass density \\f$\\rho\\f$\n  double specific_internal_energy_upper_bound(\n      const double /* rest_mass_density */) const override {\n    return std::numeric_limits<double>::max();\n  }\n\n  /// The lower bound of the specific enthalpy that is valid for this EOS\n  double specific_enthalpy_lower_bound() const override { return 1.0; }\n\n private:\n  EQUATION_OF_STATE_FORWARD_DECLARE_MEMBER_IMPLS(1)\n\n  double gamma(const double x) const;\n  double integral_of_gamma(const double x) const;\n  double chi_from_density(const double density) const;\n  double specific_internal_energy_from_density(const double density) const;\n  double specific_enthalpy_from_density(const double density) const;\n  double pressure_from_density(const double density) const;\n  double pressure_from_log_density(const double x) const;\n  double rest_mass_density_from_enthalpy(const double specific_enthalpy) const;\n\n  double reference_density_ = std::numeric_limits<double>::signaling_NaN();\n  double reference_pressure_ = std::numeric_limits<double>::signaling_NaN();\n  std::vector<double> integral_coefficients_{};\n  std::vector<double> gamma_coefficients_{};\n  double x_max_ = std::numeric_limits<double>::signaling_NaN();\n  double gamma_of_x_max_ = std::numeric_limits<double>::signaling_NaN();\n  double integral_of_gamma_of_x_max_ =\n      std::numeric_limits<double>::signaling_NaN();\n  std::vector<double> table_of_specific_energies_{};\n  // Information for Gaussian quadrature\n  size_t number_of_quadrature_coefs_ =\n      std::numeric_limits<size_t>::signaling_NaN();\n  std::vector<double> quadrature_weights_{};\n  std::vector<double> quadrature_points_{};\n};\n\n}  // namespace EquationsOfState\n", "meta": {"hexsha": "80dc5e9ff774f0b065c73f3f5fde463af3401606", "size": 6029, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/PointwiseFunctions/Hydro/EquationsOfState/Spectral.hpp", "max_stars_repo_name": "Shabibti/spectre", "max_stars_repo_head_hexsha": "0fa0353e209ef2bc53100f7101bd05f12e812f5e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-11T00:17:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-11T00:17:33.000Z", "max_issues_repo_path": "src/PointwiseFunctions/Hydro/EquationsOfState/Spectral.hpp", "max_issues_repo_name": "Shabibti/spectre", "max_issues_repo_head_hexsha": "0fa0353e209ef2bc53100f7101bd05f12e812f5e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/PointwiseFunctions/Hydro/EquationsOfState/Spectral.hpp", "max_forks_repo_name": "Shabibti/spectre", "max_forks_repo_head_hexsha": "0fa0353e209ef2bc53100f7101bd05f12e812f5e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.5393939394, "max_line_length": 94, "alphanum_fraction": 0.7186929839, "num_tokens": 1548, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.47606505115406555}}
{"text": "#include \"exception.hh\"\n#include \"network.hh\"\n#include \"timer.hh\"\n\n#include <Eigen/Dense>\n#include <iostream>\n#include <utility>\n\n#include <sys/resource.h>\n#include <sys/time.h>\n\nusing namespace std;\nusing namespace Eigen;\n\nconstexpr size_t batch_size = 1;\nconstexpr size_t input_size = 3;\n\nvoid program_body()\n{\n  /* remove limit on stack size */\n  const rlimit limits { RLIM_INFINITY, RLIM_INFINITY };\n  CheckSystemCall( \"setrlimit\", setrlimit( RLIMIT_STACK, &limits ) );\n\n  /* seed C RNG for Eigen random weight initialization */\n  // srand( Timer::timestamp_ns() );\n  srand( 0 );\n\n  /* construct neural network on heap */\n  auto nn = make_unique<Network<float, batch_size, input_size, 4, 4, 2, 1>>();\n  nn->initializeWeightsRandomly();\n\n  srand( 10 );\n  /* initialize inputs */\n  Matrix<float, batch_size, input_size> input = Matrix<float, batch_size, input_size>::Random();\n\n  /* forward prop */\n  nn->apply( input );\n\n  /* back prop */\n  nn->computeDeltas();\n  nn->evaluateGradients( input );\n\n  /* print */\n  const IOFormat CleanFmt( 4, 0, \", \", \"\\n\", \"[\", \"]\" );\n  cout << \"input:\" << endl << input.format( CleanFmt ) << endl << endl;\n  nn->print();\n\n  unsigned int numLayers = nn->getNumLayers();\n\n  for ( unsigned int layerNum = 0; layerNum < numLayers; layerNum++ ) {\n    cout << \"Layer \" << layerNum << \"\\n\";\n    const unsigned int input_size_ = nn->getLayerInputSize( layerNum );\n    const unsigned int output_size_ = nn->getLayerOutputSize( layerNum );\n    cout << \" input size: \" << input_size_ << \" -> \"\n         << \"output_size: \" << output_size_ << endl\n         << endl;\n\n    unsigned int numParams = nn->getNumParams( layerNum );\n    vector<float> gradients( numParams, 0 );\n\n    for ( unsigned int paramNum = 0; paramNum < numParams; paramNum++ ) {\n      float gradient = nn->getEvaluatedGradient( layerNum, paramNum );\n      gradients[paramNum] = gradient;\n    }\n\n    cout << \"  weightGradients \";\n    for ( unsigned int paramNum = 0; paramNum < numParams; paramNum++ ) {\n      if ( paramNum % output_size_ == 0 )\n        cout << endl << \"   \";\n      if ( paramNum == input_size_ * output_size_ ) {\n        cout << endl;\n        cout << \"  biasGradients\" << endl << \"   \";\n      }\n      cout << gradients[paramNum] << \" \";\n    }\n    cout << endl;\n    cout << endl << endl;\n  }\n}\n\nint main()\n{\n  try {\n    program_body();\n    return EXIT_SUCCESS;\n  } catch ( const exception& e ) {\n    cerr << e.what() << \"\\n\";\n    return EXIT_FAILURE;\n  }\n}", "meta": {"hexsha": "1d025a05fc2c65e088070b1f6dc71be90ecc04b5", "size": 2463, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/frontend/back_propagation_formula.cc", "max_stars_repo_name": "stanford-stagecast/nnfun", "max_stars_repo_head_hexsha": "14300c4320b9b90b4f54d8fc49f66166a490c257", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2022-01-04T23:08:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-10T06:57:30.000Z", "max_issues_repo_path": "src/frontend/back_propagation_formula.cc", "max_issues_repo_name": "stanford-stagecast/nnfun", "max_issues_repo_head_hexsha": "14300c4320b9b90b4f54d8fc49f66166a490c257", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/frontend/back_propagation_formula.cc", "max_forks_repo_name": "stanford-stagecast/nnfun", "max_forks_repo_head_hexsha": "14300c4320b9b90b4f54d8fc49f66166a490c257", "max_forks_repo_licenses": ["Apache-2.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.3666666667, "max_line_length": 96, "alphanum_fraction": 0.6163215591, "num_tokens": 656, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4760650511540655}}
{"text": "#include <Eigen/Core>\n#include <iostream>\n\n#include <Python.h> // for Py_ssize_t\n\ntypedef Eigen::Matrix<float, Eigen::Dynamic, 1> NumpyVecF;\n\nstatic Eigen::VectorXf buf2vecf(float *mem, Py_ssize_t n)\n{\n    return Eigen::Map<NumpyVecF>(mem, n);\n}\n\nstatic void vecf2buf(const Eigen::VectorXf& vec, float *mem)\n{\n    Eigen::Map<NumpyVecF>(mem, vec.size()) = vec;\n}\n\n// In Python, the default is row-major (C) while in Eigen it's ColMajor (F).\ntypedef Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> NumpyMatF;\n\nstatic Eigen::MatrixXf buf2matf(float *mem, Py_ssize_t h, Py_ssize_t w)\n{\n    // This does the conversion, so very likely makes a copy.\n    return Eigen::Map<NumpyMatF>(mem, h, w);\n}\n\nstatic void matf2buf(const Eigen::MatrixXf& mat, float *mem)\n{\n    Eigen::Map<NumpyMatF>(mem, mat.rows(), mat.cols()) = mat;\n}\n\n", "meta": {"hexsha": "06e53765b9a5b74ebff82117947b7a43d108bfc3", "size": 842, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pydensecrf/eigen_impl.cpp", "max_stars_repo_name": "arlain23/pydensecrf", "max_stars_repo_head_hexsha": "dee24b055d92dbbc906d50b282e0862d83c0cf80", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1765.0, "max_stars_repo_stars_event_min_datetime": "2015-11-13T19:32:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T06:41:04.000Z", "max_issues_repo_path": "pydensecrf/eigen_impl.cpp", "max_issues_repo_name": "arlain23/pydensecrf", "max_issues_repo_head_hexsha": "dee24b055d92dbbc906d50b282e0862d83c0cf80", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 112.0, "max_issues_repo_issues_event_min_datetime": "2015-11-23T21:52:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-20T13:29:43.000Z", "max_forks_repo_path": "pydensecrf/eigen_impl.cpp", "max_forks_repo_name": "arlain23/pydensecrf", "max_forks_repo_head_hexsha": "dee24b055d92dbbc906d50b282e0862d83c0cf80", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 461.0, "max_forks_repo_forks_event_min_datetime": "2015-11-23T20:08:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T22:24:08.000Z", "avg_line_length": 26.3125, "max_line_length": 88, "alphanum_fraction": 0.6971496437, "num_tokens": 258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4760650511540655}}
{"text": "#ifndef MI_MATH_HPP\n#define MI_MATH_HPP 1\n#include <Eigen/Dense>\nnamespace mi\n{\n        typedef Eigen::Vector3d Vector3d;\n        typedef Eigen::Vector3f Vector3f;\n        typedef Eigen::Matrix< short , 3 , 1> Vector3s;\n        typedef Eigen::Vector3d Point3d;\n        typedef Eigen::Vector3f Point3f;\n        typedef Eigen::Vector3i Point3i;\n        typedef Eigen::Vector3f Color3f;\n};\n#endif//f MI_MATH_HPP\n", "meta": {"hexsha": "2201d8e2e6e6141d8786b0df8148960fdb43f1d2", "size": 409, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mi/volmath.hpp", "max_stars_repo_name": "tmichi/mivol", "max_stars_repo_head_hexsha": "89131e7ad75e0acba5e03b6bb26095e32bb70e43", "max_stars_repo_licenses": ["MIT"], "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/mi/volmath.hpp", "max_issues_repo_name": "tmichi/mivol", "max_issues_repo_head_hexsha": "89131e7ad75e0acba5e03b6bb26095e32bb70e43", "max_issues_repo_licenses": ["MIT"], "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/mi/volmath.hpp", "max_forks_repo_name": "tmichi/mivol", "max_forks_repo_head_hexsha": "89131e7ad75e0acba5e03b6bb26095e32bb70e43", "max_forks_repo_licenses": ["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.2666666667, "max_line_length": 55, "alphanum_fraction": 0.6772616137, "num_tokens": 114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7981867585368343, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4760650397008869}}
{"text": "/*\n@copyright Louis Dionne 2015\nDistributed under the Boost Software License, Version 1.0.\n(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n */\n\n#include <boost/hana/sandbox/searchable_set.hpp>\n\n#include <boost/hana/assert.hpp>\n#include <boost/hana/config.hpp>\n#include <boost/hana/tuple.hpp>\n#include <boost/hana/type.hpp>\n\n#include <test/auto/base.hpp>\n#include <test/cnumeric.hpp>\n#include <test/injection.hpp>\n#include <test/numeric.hpp>\n\n// instances\n#include <test/auto/applicative.hpp>\n#include <test/auto/comparable.hpp>\n#include <test/auto/functor.hpp>\n#include <test/auto/monad.hpp>\n#include <test/auto/searchable.hpp>\nusing namespace boost::hana;\n\n\nnamespace boost { namespace hana { namespace test {\n    template <>\n    auto instances<SearchableSet> = make<Tuple>(\n          type<Comparable>\n        , type<Functor>\n        , type<Applicative>\n        , type<Monad>\n        , type<Searchable>\n    );\n\n    template <>\n    auto objects<SearchableSet> = make<Tuple>(\n        singleton(numeric(0)),\n        singleton(numeric(1)),\n        doubleton(numeric(0), numeric(1)),\n        doubleton(numeric(0), numeric(3)),\n        doubleton(numeric(0), numeric(0))\n    );\n}}}\n\n\ntemplate <int i>\nconstexpr auto n = test::numeric(i);\n\ntemplate <int i>\nconstexpr auto c = test::cnumeric<int, i>;\n\nint main() {\n    test::check_datatype<SearchableSet>();\n    using test::x;\n    auto f = test::injection([]{});\n    auto g = test::injection([]{});\n\n    // union_\n    {\n        BOOST_HANA_CONSTANT_CHECK(equal(\n            union_(singleton(c<0>), singleton(c<0>)),\n            singleton(c<0>)\n        ));\n        BOOST_HANA_CONSTANT_CHECK(equal(\n            union_(singleton(c<0>), singleton(c<1>)),\n            doubleton(c<0>, c<1>)\n        ));\n        BOOST_HANA_CONSTANT_CHECK(equal(\n            union_(singleton(c<0>), doubleton(c<0>, c<1>)),\n            doubleton(c<0>, c<1>)\n        ));\n    }\n\n    // Comparable\n    {\n        // equal\n        {\n            BOOST_HANA_CONSTEXPR_CHECK(equal(singleton(n<0>), singleton(n<0>)));\n            BOOST_HANA_CONSTEXPR_CHECK(not_(equal(singleton(n<0>), singleton(n<1>))));\n\n            BOOST_HANA_CONSTEXPR_CHECK(equal(singleton(n<0>), doubleton(n<0>, n<0>)));\n            BOOST_HANA_CONSTEXPR_CHECK(not_(equal(singleton(n<0>), doubleton(n<0>, n<1>))));\n            BOOST_HANA_CONSTEXPR_CHECK(not_(equal(singleton(n<0>), doubleton(n<1>, n<1>))));\n\n            BOOST_HANA_CONSTEXPR_CHECK(equal(doubleton(n<0>, n<1>), doubleton(n<0>, n<1>)));\n            BOOST_HANA_CONSTEXPR_CHECK(equal(doubleton(n<0>, n<1>), doubleton(n<1>, n<0>)));\n            BOOST_HANA_CONSTEXPR_CHECK(not_(equal(doubleton(n<0>, n<1>), doubleton(n<0>, n<0>))));\n            BOOST_HANA_CONSTEXPR_CHECK(not_(equal(doubleton(n<0>, n<1>), doubleton(n<3>, n<4>))));\n        }\n    }\n\n    // Functor\n    {\n        // transform\n        {\n            BOOST_HANA_CONSTEXPR_CHECK(equal(\n                transform(singleton(n<0>), f),\n                singleton(f(n<0>))\n            ));\n            BOOST_HANA_CONSTEXPR_CHECK(equal(\n                transform(doubleton(n<0>, n<1>), f),\n                doubleton(f(n<0>), f(n<1>))\n            ));\n            BOOST_HANA_CONSTEXPR_CHECK(equal(\n                transform(doubleton(n<0>, n<0>), f),\n                singleton(f(n<0>))\n            ));\n        }\n    }\n\n    // Applicative\n    {\n        // ap\n        {\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                ap(singleton(f), singleton(x<0>)),\n                singleton(f(x<0>))\n            ));\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                ap(singleton(f), doubleton(x<0>, x<1>)),\n                doubleton(f(x<0>), f(x<1>))\n            ));\n\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                ap(doubleton(f, g), singleton(x<0>)),\n                doubleton(f(x<0>), g(x<0>))\n            ));\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                ap(doubleton(f, g), doubleton(x<0>, x<1>)),\n                union_(doubleton(f(x<0>), f(x<1>)), doubleton(g(x<0>), g(x<1>)))\n            ));\n        }\n\n        // lift\n        {\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                lift<SearchableSet>(x<0>),\n                singleton(x<0>)\n            ));\n        }\n    }\n\n    // Monad\n    {\n        // flatten\n        {\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                flatten(singleton(singleton(c<0>))),\n                singleton(c<0>)\n            ));\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                flatten(singleton(doubleton(c<0>, c<1>))),\n                doubleton(c<0>, c<1>)\n            ));\n\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                flatten(doubleton(singleton(c<0>), singleton(c<1>))),\n                doubleton(c<0>, c<1>)\n            ));\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                flatten(doubleton(doubleton(c<0>, c<1>), singleton(c<2>))),\n                union_(doubleton(c<0>, c<1>), singleton(c<2>))\n            ));\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                flatten(doubleton(singleton(c<0>), doubleton(c<1>, c<2>))),\n                union_(doubleton(c<0>, c<1>), singleton(c<2>))\n            ));\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                flatten(doubleton(doubleton(c<0>, c<1>), doubleton(c<2>, c<3>))),\n                union_(doubleton(c<0>, c<1>), doubleton(c<2>, c<3>))\n            ));\n        }\n    }\n\n    // Searchable\n    {\n\n        BOOST_HANA_CONSTEXPR_LAMBDA auto is = [](auto x) {\n            return [=](auto y) { return equal(x, y); };\n        };\n\n        // any_of\n        {\n            BOOST_HANA_CONSTEXPR_CHECK(any_of(singleton(n<0>), is(n<0>)));\n            BOOST_HANA_CONSTEXPR_CHECK(not_(any_of(singleton(n<0>), is(n<1>))));\n            BOOST_HANA_CONSTEXPR_CHECK(any_of(doubleton(n<0>, n<1>), is(n<0>)));\n            BOOST_HANA_CONSTEXPR_CHECK(any_of(doubleton(n<0>, n<1>), is(n<1>)));\n            BOOST_HANA_CONSTEXPR_CHECK(not_(any_of(doubleton(n<0>, n<1>), is(n<2>))));\n        }\n\n        // find_if\n        {\n            BOOST_HANA_CONSTANT_CHECK(find_if(singleton(c<0>), is(c<0>)) == just(c<0>));\n            BOOST_HANA_CONSTANT_CHECK(find_if(singleton(c<1>), is(c<0>)) == nothing);\n\n            BOOST_HANA_CONSTANT_CHECK(find_if(doubleton(c<0>, c<1>), is(c<0>)) == just(c<0>));\n            BOOST_HANA_CONSTANT_CHECK(find_if(doubleton(c<0>, c<1>), is(c<1>)) == just(c<1>));\n            BOOST_HANA_CONSTANT_CHECK(find_if(doubleton(c<0>, c<1>), is(c<2>)) == nothing);\n        }\n\n        // subset\n        {\n            BOOST_HANA_CONSTEXPR_CHECK(subset(singleton(n<0>), singleton(n<0>)));\n            BOOST_HANA_CONSTEXPR_CHECK(not_(subset(singleton(n<1>), singleton(n<0>))));\n\n            BOOST_HANA_CONSTEXPR_CHECK(subset(singleton(n<0>), doubleton(n<0>, n<1>)));\n            BOOST_HANA_CONSTEXPR_CHECK(subset(singleton(n<1>), doubleton(n<0>, n<1>)));\n            BOOST_HANA_CONSTEXPR_CHECK(not_(subset(singleton(n<2>), doubleton(n<0>, n<1>))));\n\n            BOOST_HANA_CONSTEXPR_CHECK(subset(doubleton(n<0>, n<1>), doubleton(n<0>, n<1>)));\n            BOOST_HANA_CONSTEXPR_CHECK(not_(subset(doubleton(n<0>, n<2>), doubleton(n<0>, n<1>))));\n            BOOST_HANA_CONSTEXPR_CHECK(not_(subset(doubleton(n<2>, n<3>), doubleton(n<0>, n<1>))));\n        }\n    }\n}\n", "meta": {"hexsha": "c1964797a393ff763e76dc8588e3a9c0f20efb99", "size": 7277, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/sandbox/searchable_set.cpp", "max_stars_repo_name": "josephwinston/hana", "max_stars_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/sandbox/searchable_set.cpp", "max_issues_repo_name": "josephwinston/hana", "max_issues_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/sandbox/searchable_set.cpp", "max_forks_repo_name": "josephwinston/hana", "max_forks_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.2283105023, "max_line_length": 99, "alphanum_fraction": 0.541569328, "num_tokens": 1944, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154240079185319, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.47605069359691504}}
{"text": "//=======================================================================\n// Copyright 2009 Trustees of Indiana University.\n// Authors: Michael Hansen, Andrew Lumsdaine\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n\n#include <fstream>\n#include <iostream>\n#include <set>\n\n#include <boost/foreach.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/graph/grid_graph.hpp>\n#include <boost/random.hpp>\n#include <boost/test/minimal.hpp>\n\nusing namespace boost;\n\n// Function that prints a vertex to std::cout\ntemplate <typename Vertex>\nvoid print_vertex(Vertex vertex_to_print) {\n\n  std::cout << \"(\";\n\n  for (std::size_t dimension_index = 0;\n       dimension_index < vertex_to_print.size();\n       ++dimension_index) {\n    std::cout << vertex_to_print[dimension_index];\n\n    if (dimension_index != (vertex_to_print.size() - 1)) {\n      std::cout << \", \";\n    }\n  }\n\n  std::cout << \")\";\n}\n\ntemplate <unsigned int Dims>\nvoid do_test(minstd_rand& generator) {\n  typedef grid_graph<Dims> Graph;\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  typedef typename graph_traits<Graph>::vertex_descriptor vertex_descriptor;\n  typedef typename graph_traits<Graph>::edge_descriptor edge_descriptor;\n\n  std::cout << \"Dimensions: \" << Dims << \", lengths: \";\n\n  // Randomly generate the dimension lengths (3-10) and wrapping\n  boost::array<vertices_size_type, Dims> lengths;\n  boost::array<bool, Dims> wrapped;\n\n  for (unsigned int dimension_index = 0;\n       dimension_index < Dims;\n       ++dimension_index) {\n    lengths[dimension_index] = 3 + (generator() % 8);\n    wrapped[dimension_index] = ((generator() % 2) == 0);\n\n    std::cout << lengths[dimension_index] <<\n      (wrapped[dimension_index] ? \" [W]\" : \" [U]\") << \", \";\n  }\n\n  std::cout << std::endl;\n\n  Graph graph(lengths, wrapped);\n\n  // Verify dimension lengths and wrapping\n  for (unsigned int dimension_index = 0;\n       dimension_index < Dims;\n       ++dimension_index) {\n    BOOST_REQUIRE(graph.length(dimension_index) == lengths[dimension_index]);\n    BOOST_REQUIRE(graph.wrapped(dimension_index) == wrapped[dimension_index]);\n  }\n\n  // Verify matching indices\n  for (vertices_size_type vertex_index = 0;\n       vertex_index < num_vertices(graph);\n       ++vertex_index) {\n    BOOST_REQUIRE(get(boost::vertex_index, graph, vertex(vertex_index, graph)) == vertex_index);\n  }\n\n  for (edges_size_type edge_index = 0;\n       edge_index < num_edges(graph);\n       ++edge_index) {\n\n    edge_descriptor current_edge = edge_at(edge_index, graph);\n    BOOST_REQUIRE(get(boost::edge_index, graph, current_edge) == edge_index);\n  }\n\n  // Verify all vertices are within bounds\n  vertices_size_type vertex_count = 0;\n  BOOST_FOREACH(vertex_descriptor current_vertex, vertices(graph)) {\n\n    vertices_size_type current_index =\n      get(boost::vertex_index, graph, current_vertex);\n\n    for (unsigned int dimension_index = 0;\n         dimension_index < Dims;\n         ++dimension_index) {\n      BOOST_REQUIRE(/*(current_vertex[dimension_index] >= 0) && */ // Always true\n                   (current_vertex[dimension_index] < lengths[dimension_index]));\n    }\n\n    // Verify out-edges of this vertex\n    edges_size_type out_edge_count = 0;\n    std::set<vertices_size_type> target_vertices;\n\n    BOOST_FOREACH(edge_descriptor out_edge,\n                  out_edges(current_vertex, graph)) {\n\n      target_vertices.insert\n        (get(boost::vertex_index, graph, target(out_edge, graph)));\n\n      ++out_edge_count;\n    }\n\n    BOOST_REQUIRE(out_edge_count == out_degree(current_vertex, graph));\n\n    // Verify in-edges of this vertex\n    edges_size_type in_edge_count = 0;\n\n    BOOST_FOREACH(edge_descriptor in_edge,\n                  in_edges(current_vertex, graph)) {\n\n      BOOST_REQUIRE(target_vertices.count\n                   (get(boost::vertex_index, graph, source(in_edge, graph))) > 0);\n\n      ++in_edge_count;\n    }\n\n    BOOST_REQUIRE(in_edge_count == in_degree(current_vertex, graph));\n\n    // The number of out-edges and in-edges should be the same\n    BOOST_REQUIRE(degree(current_vertex, graph) ==\n                 out_degree(current_vertex, graph) +\n                 in_degree(current_vertex, graph));\n\n    // Verify adjacent vertices to this vertex\n    vertices_size_type adjacent_count = 0;\n\n    BOOST_FOREACH(vertex_descriptor adjacent_vertex,\n                  adjacent_vertices(current_vertex, graph)) {\n\n      BOOST_REQUIRE(target_vertices.count\n                   (get(boost::vertex_index, graph, adjacent_vertex)) > 0);\n\n      ++adjacent_count;\n    }\n\n    BOOST_REQUIRE(adjacent_count == out_degree(current_vertex, graph));\n\n    // Verify that this vertex is not listed as connected to any\n    // vertices outside of its adjacent vertices.\n    BOOST_FOREACH(vertex_descriptor unconnected_vertex, vertices(graph)) {\n\n      vertices_size_type unconnected_index =\n        get(boost::vertex_index, graph, unconnected_vertex);\n\n      if ((unconnected_index == current_index) ||\n          (target_vertices.count(unconnected_index) > 0)) {\n        continue;\n      }\n\n      BOOST_REQUIRE(!edge(current_vertex, unconnected_vertex, graph).second);\n      BOOST_REQUIRE(!edge(unconnected_vertex, current_vertex, graph).second);\n    }\n\n    ++vertex_count;\n  }\n\n  BOOST_REQUIRE(vertex_count == num_vertices(graph));\n\n  // Verify all edges are within bounds\n  edges_size_type edge_count = 0;\n  BOOST_FOREACH(edge_descriptor current_edge, edges(graph)) {\n\n    vertices_size_type source_index =\n      get(boost::vertex_index, graph, source(current_edge, graph));\n\n    vertices_size_type target_index =\n      get(boost::vertex_index, graph, target(current_edge, graph));\n\n    BOOST_REQUIRE(source_index != target_index);\n    BOOST_REQUIRE(/* (source_index >= 0) : always true && */ (source_index < num_vertices(graph)));\n    BOOST_REQUIRE(/* (target_index >= 0) : always true && */ (target_index < num_vertices(graph)));\n\n    // Verify that the edge is listed as existing in both directions\n    BOOST_REQUIRE(edge(source(current_edge, graph), target(current_edge, graph), graph).second);\n    BOOST_REQUIRE(edge(target(current_edge, graph), source(current_edge, graph), graph).second);\n\n    ++edge_count;\n  }\n\n  BOOST_REQUIRE(edge_count == num_edges(graph));\n}\n\nint test_main(int argc, char* argv[]) {\n\n  std::size_t random_seed = time(0);\n\n  if (argc > 1) {\n    random_seed = lexical_cast<std::size_t>(argv[1]);\n  }\n\n  minstd_rand generator(random_seed);\n\n  do_test<0>(generator);\n  do_test<1>(generator);\n  do_test<2>(generator);\n  do_test<3>(generator);\n  do_test<4>(generator);\n\n  return (0);\n}\n", "meta": {"hexsha": "dc5baac12a15bf0a019b979ca0ebb7cdf0c627d6", "size": 6827, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "deps/src/boost_1_65_1/libs/graph/test/grid_graph_test.cpp", "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/libs/graph/test/grid_graph_test.cpp", "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/libs/graph/test/grid_graph_test.cpp", "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": 31.3165137615, "max_line_length": 99, "alphanum_fraction": 0.6754064743, "num_tokens": 1522, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.47605067602819967}}
{"text": "#include <iostream>\n\n#include <cuda.h>\n#include <cuda_runtime_api.h>\n\n#include <blitz.h>\n\nusing namespace blitz;\n// M N\nShape input_shape(2);\n// N M\nShape output_shape(2);\n\nvoid compare_cpu_gpu(size_t size, float* output_cpu, float* output_gpu) {\n  for (size_t i = 0; i < size; ++i) {\n    if (output_cpu[i] > output_gpu[i] + 1e-3 ||\n      output_cpu[i] < output_gpu[i] - 1e-3) {\n      std::cout << \"Index: \" << i << \", CPU: \" << output_cpu[i] <<\n        \", GPU: \" << output_gpu[i] << std::endl;\n    }\n  }\n}\n\nvoid transpose(size_t m, size_t n) {\n  // set up cpu\n  CPUTensor<float> input_cpu(input_shape);\n  CPUTensor<float> output_cpu(output_shape);\n  // set up gpu\n  GPUTensor<float> input_gpu(input_shape);\n  GPUTensor<float> output_gpu(output_shape);\n  CPUTensor<float> output_copy(output_shape);\n  // init values\n  Backend<CPUTensor, float>::UniformDistributionFunc(&input_cpu, 0.0, 1.0);\n  cudaMemcpy(input_gpu.data(), input_cpu.data(),\n    input_cpu.size() * sizeof(float), cudaMemcpyHostToDevice);\n  // transpose\n  Backend<CPUTensor, float>::Transpose2DFunc(&input_cpu, &output_cpu);\n  Backend<GPUTensor, float>::Transpose2DFunc(&input_gpu, &output_gpu);\n  // copy from gpu to cpu\n  cudaMemcpy(output_copy.data(), output_gpu.data(),\n    output_gpu.size() * sizeof(float), cudaMemcpyDeviceToHost);\n  compare_cpu_gpu(output_cpu.size(), output_cpu.data(), output_copy.data());\n}\n\nint main(int argc, char** argv) {\n  const size_t NUM_ARGS = 2;\n  FLAGS_logtostderr = true;\n  google::InitGoogleLogging(argv[0]);\n  // M N\n  if (argc != NUM_ARGS + 1) {\n    LOG(FATAL) << \"Not enough args!\" << \" argc \" << argc;\n  }\n  const size_t M = atoi(argv[1]);\n  const size_t N = atoi(argv[2]);\n  // set shapes\n  input_shape[0] = M;\n  input_shape[1] = N;\n  output_shape[0] = N;\n  output_shape[1] = M;\n  // run\n  transpose(M, N);\n  return 0;\n}\n", "meta": {"hexsha": "0c9e49dfe3e856fc4e76d6565ee6305afe52f697", "size": 1829, "ext": "cc", "lang": "C++", "max_stars_repo_path": "samples/gpu/matrix/matrix_transpose.cc", "max_stars_repo_name": "ncic-sugon/blitz", "max_stars_repo_head_hexsha": "ea9a06dc78ef15d772e36d5d47ffac8d3f46034d", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 149.0, "max_stars_repo_stars_event_min_datetime": "2020-07-14T08:59:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-16T03:06:41.000Z", "max_issues_repo_path": "samples/gpu/matrix/matrix_transpose.cc", "max_issues_repo_name": "ten1123love/blitz", "max_issues_repo_head_hexsha": "ea9a06dc78ef15d772e36d5d47ffac8d3f46034d", "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": "samples/gpu/matrix/matrix_transpose.cc", "max_forks_repo_name": "ten1123love/blitz", "max_forks_repo_head_hexsha": "ea9a06dc78ef15d772e36d5d47ffac8d3f46034d", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 130.0, "max_forks_repo_forks_event_min_datetime": "2020-07-14T09:00:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-16T03:06:42.000Z", "avg_line_length": 28.578125, "max_line_length": 76, "alphanum_fraction": 0.6610169492, "num_tokens": 542, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.6654105454764747, "lm_q1q2_score": 0.47605067128124007}}
{"text": "\n// Copyright (c) 2012 Christopher Lux <christopherlux@gmail.com>\n// Distributed under the Modified BSD License, see license.txt.\n\n#include <exception>\n#include <stdexcept>\n\n#include <boost/utility.hpp>\n\nnamespace scm {\nnamespace data {\nnamespace detail {\n\n/*\n\ntemplate<typename val_type>\nbool build_lookup_table<val_type>(boost::scoped_array<val_type>& dst,\n                                  const piecewise_function_weighted_1d<unsigned char, val_type>& scal_trafu,\n                                  unsigned size)\n{\n    if (size < 1) {\n        return (false);\n    }\n\n    float    dst_ind_scal_factor = float(size - 1) / 255.0f;\n\n    unsigned dst_ind_begin;\n    unsigned dst_ind_end;\n\n    float    dst_ind_begin_weight;\n    val_type dst_ind_begin_value;\n    val_type dst_ind_end_value;\n\n    float lerp_factor;\n    float lerp_factor_w;\n    float part_step_size;\n\n    // clear beginning\n    if (scal_trafu.empty()) {\n        dst_ind_begin = 0;\n        dst_ind_end   = size - 1;\n    }\n    else {\n        dst_ind_begin   = 0;\n        dst_ind_end     = unsigned(math::floor(float(scal_trafu.stops_begin()->first) * dst_ind_scal_factor));\n    }\n\n    for (unsigned dst_ind = dst_ind_begin; dst_ind < dst_ind_end; ++dst_ind) {\n        dst[dst_ind] = val_type(0);\n    }\n\n    // fill lookup table\n    for (scm::piecewise_function_weighted_1d<unsigned char, val_type>::const_stop_iterator it_left = scal_trafu.stops_begin();\n         it_left  != scal_trafu.stops_end();\n         ++it_left) {\n\n        dst_ind_begin           = unsigned(math::floor(float(it_left->first) * dst_ind_scal_factor));\n        dst_ind_begin_value     = it_left->second._value;\n        dst_ind_begin_weight    = it_left->second._weight;\n\n        scm::piecewise_function_weighted_1d<unsigned char, val_type>::const_stop_iterator it_right = boost::next(it_left);\n        if (it_right != scal_trafu.stops_end()) {\n            dst_ind_end         = unsigned(math::floor(float(it_right->first) * dst_ind_scal_factor));\n            dst_ind_end_value   = it_right->second._value;\n        }\n        else {\n            dst_ind_end         = dst_ind_begin + 1;\n            dst_ind_end_value   = dst_ind_begin_value;\n        }\n        \n        part_step_size = 1.0f / float(dst_ind_end - dst_ind_begin);\n        lerp_factor = 0.0f;\n        lerp_factor_w = 0.0f;\n\n        for (unsigned dst_ind = dst_ind_begin; dst_ind < dst_ind_end; ++dst_ind) {\n            //lerp_factor = math::shoothstep(dst_ind_begin, dst_ind_end, dst_ind);\n            //// smoothstep\n            //float s = math::clamp(float(dst_ind-dst_ind_begin)/float(dst_ind_end-dst_ind_begin), 0.0f, 1.0f);\n            //s = scm::detail::non_linear_value_weight<float>(s, dst_ind_begin_weight);\n            //lerp_factor_w = (s*s*(3.0f-2.0f*s));\n\n            lerp_factor_w = scm::detail::non_linear_value_weight<float>(lerp_factor, dst_ind_begin_weight);\n            dst[dst_ind] = math::lerp(dst_ind_begin_value, dst_ind_end_value, lerp_factor_w);\n            lerp_factor += part_step_size;\n        }\n    }\n\n    // clear end\n    for (unsigned dst_ind = dst_ind_end; dst_ind < size; ++dst_ind) {\n        dst[dst_ind] = val_type(0);\n    }\n\n\n    // original code\n    //float a;\n    //float step = 255.0f / float(size - 1);\n    //for (unsigned i = 0; i < size; i++) {\n    //    a = float(i) * step;\n    //    dst[i] = scal_trafu[a]; \n    //}\n\n    return (true);\n}\n\n*/\n\ntemplate<typename val_type>\nstruct build_lookup_table_impl<val_type, unsigned char>\n{\n    static bool build_table(boost::scoped_array<val_type>& dst,\n                            const piecewise_function_1d<unsigned char, val_type>& scal_trafu,\n                            unsigned size)\n    {\n        using namespace scm::math;\n\n        if (size < 1) {\n            return (false);\n        }\n        \n        float    dst_ind_scal_factor = float(size - 1) / 255.0f;\n        \n        unsigned dst_ind_begin;\n        unsigned dst_ind_end;\n        \n        val_type dst_ind_begin_value;\n        val_type dst_ind_end_value;\n        \n        float lerp_factor;\n        float part_step_size;\n        \n        // clear beginning\n        if (scal_trafu.empty()) {\n            dst_ind_begin = 0;\n            dst_ind_end   = size - 1;\n        }\n        else {\n            dst_ind_begin   = 0;\n            dst_ind_end     = unsigned(floor(float(scal_trafu.stops_begin()->first) * dst_ind_scal_factor));\n        }\n        \n        for (unsigned dst_ind = dst_ind_begin; dst_ind < dst_ind_end; ++dst_ind) {\n            dst[dst_ind] = val_type(0);\n        }\n        \n        // fill lookup table\n        for (typename scm::data::piecewise_function_1d<unsigned char, val_type>::const_stop_iterator it_left = scal_trafu.stops_begin();\n            it_left  != scal_trafu.stops_end();\n            ++it_left) {\n        \n            dst_ind_begin       = unsigned(floor(float(it_left->first) * dst_ind_scal_factor));\n            dst_ind_begin_value = it_left->second;\n        \n            typename scm::data::piecewise_function_1d<unsigned char, val_type>::const_stop_iterator it_right = boost::next(it_left);\n            if (it_right != scal_trafu.stops_end()) {\n            dst_ind_end         = unsigned(floor(float(it_right->first) * dst_ind_scal_factor));\n            dst_ind_end_value   = it_right->second;\n            }\n            else {\n            dst_ind_end         = dst_ind_begin + 1;\n            dst_ind_end_value   = dst_ind_begin_value;\n            }\n            \n            part_step_size = 1.0f / float(dst_ind_end - dst_ind_begin);\n            lerp_factor = 0.0f;\n        \n            for (unsigned dst_ind = dst_ind_begin; dst_ind < dst_ind_end; ++dst_ind) {\n            //lerp_factor = math::shoothstep(dst_ind_begin, dst_ind_end, dst_ind);\n            dst[dst_ind] = lerp(dst_ind_begin_value, dst_ind_end_value, lerp_factor);\n            lerp_factor += part_step_size;\n            }\n        }\n        \n        // clear end\n        for (unsigned dst_ind = dst_ind_end; dst_ind < size; ++dst_ind) {\n            dst[dst_ind] = val_type(0);\n        }\n        \n        \n        // original code\n        //float a;\n        //float step = 255.0f / float(size - 1);\n        //for (unsigned i = 0; i < size; i++) {\n        //    a = float(i) * step;\n        //    dst[i] = scal_trafu[a]; \n        //}\n        \n        return (true);\n    }\n}; // struct_look_uptable_impl\n\ntemplate<typename val_type>\nstruct build_lookup_table_impl<val_type, float>\n{\n    static bool build_table(boost::scoped_array<val_type>&                dst,\n                            const piecewise_function_1d<float, val_type>& scal_trafu,\n                            unsigned                                      size)\n    {\n        using namespace scm::math;\n\n        if (size < 1) {\n            return (false);\n        }\n    \n        float    dst_ind_scal_factor = float(size - 1);\n        \n        unsigned dst_ind_begin;\n        unsigned dst_ind_end;\n        \n        val_type dst_ind_begin_value;\n        val_type dst_ind_end_value;\n        \n        float lerp_factor;\n        float part_step_size;\n        \n        // clear beginning\n        if (scal_trafu.empty()) {\n            dst_ind_begin = 0;\n            dst_ind_end   = size - 1;\n        }\n        else {\n            dst_ind_begin   = 0;\n            dst_ind_end     = unsigned(floor(scal_trafu.stops_begin()->first * dst_ind_scal_factor));\n        }\n        \n        for (unsigned dst_ind = dst_ind_begin; dst_ind < dst_ind_end; ++dst_ind) {\n            dst[dst_ind] = val_type(0);\n        }\n        \n        // fill lookup table\n        for (typename scm::data::piecewise_function_1d<float, val_type>::const_stop_iterator it_left = scal_trafu.stops_begin();\n            it_left  != scal_trafu.stops_end();\n            ++it_left) {\n        \n            dst_ind_begin       = unsigned(floor(it_left->first * dst_ind_scal_factor));\n            dst_ind_begin_value = it_left->second;\n        \n            typename scm::data::piecewise_function_1d<float, val_type>::const_stop_iterator it_right = boost::next(it_left);\n            if (it_right != scal_trafu.stops_end()) {\n            dst_ind_end         = unsigned(floor(it_right->first * dst_ind_scal_factor));\n            dst_ind_end_value   = it_right->second;\n            }\n            else {\n            dst_ind_end         = dst_ind_begin + 1;\n            dst_ind_end_value   = dst_ind_begin_value;\n            }\n            \n            part_step_size = 1.0f / float(dst_ind_end - dst_ind_begin);\n            lerp_factor = 0.0f;\n        \n            for (unsigned dst_ind = dst_ind_begin; dst_ind < dst_ind_end; ++dst_ind) {\n            //lerp_factor = math::shoothstep(dst_ind_begin, dst_ind_end, dst_ind);\n            dst[dst_ind] = lerp(dst_ind_begin_value, dst_ind_end_value, lerp_factor);\n            lerp_factor += part_step_size;\n            }\n        }\n        \n        // clear end\n        for (unsigned dst_ind = dst_ind_end; dst_ind < size; ++dst_ind) {\n            dst[dst_ind] = val_type(0);\n        }\n        \n        \n        // original code\n        //float a;\n        //float step = 255.0f / float(size - 1);\n        //for (unsigned i = 0; i < size; i++) {\n        //    a = float(i) * step;\n        //    dst[i] = scal_trafu[a]; \n        //}\n        \n        return (true);\n    }\n}; // struct_look_uptable_impl\n\n} // namespace detail\n} // namespace data\n} // namespace scm\n", "meta": {"hexsha": "31108063569fcc79d45369ee58956479d121ac26", "size": 9360, "ext": "inl", "lang": "C++", "max_stars_repo_path": "scm_gl_util/src/scm/gl_util/data/analysis/transfer_function/build_lookup_table.inl", "max_stars_repo_name": "Nyran/schism", "max_stars_repo_head_hexsha": "c2cdb8884e3e6714a3b291f0f754220b7f5cbc7b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2015-09-17T06:01:03.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-23T07:10:20.000Z", "max_issues_repo_path": "scm_gl_util/src/scm/gl_util/data/analysis/transfer_function/build_lookup_table.inl", "max_issues_repo_name": "Nyran/schism", "max_issues_repo_head_hexsha": "c2cdb8884e3e6714a3b291f0f754220b7f5cbc7b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2015-01-06T14:11:32.000Z", "max_issues_repo_issues_event_max_datetime": "2016-12-12T10:26:53.000Z", "max_forks_repo_path": "scm_gl_util/src/scm/gl_util/data/analysis/transfer_function/build_lookup_table.inl", "max_forks_repo_name": "Nyran/schism", "max_forks_repo_head_hexsha": "c2cdb8884e3e6714a3b291f0f754220b7f5cbc7b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T20:56:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-02T19:03:20.000Z", "avg_line_length": 33.6690647482, "max_line_length": 136, "alphanum_fraction": 0.5669871795, "num_tokens": 2280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4760142830590473}}
{"text": "\n#ifndef _MSC_VER\n#include \"update_ops_cpp.hpp\"\nextern \"C\"{\n#include \"utility.h\"\n}\n#else\n#include \"update_ops_cpp.hpp\"\n#include \"utility.h\"\n#endif\n#include <Eigen/Core>\n#include <functional>\n\nvoid multi_qubit_dense_matrix_gate_eigen(const UINT* target_qubit_index_list, UINT target_qubit_index_count, const CTYPE* matrix, CTYPE* state, ITYPE dim) {\n\n    // matrix dim, mask, buffer\n    const ITYPE matrix_dim = 1ULL << target_qubit_index_count;\n    const ITYPE* matrix_mask_list = create_matrix_mask_list(target_qubit_index_list, target_qubit_index_count);\n    Eigen::Map<const Eigen::Matrix<std::complex<double>,Eigen::Dynamic,Eigen::Dynamic,Eigen::RowMajor>, Eigen::Aligned> eigen_matrix((std::complex<double>*)matrix,matrix_dim,matrix_dim);\n    Eigen::VectorXcd buffer(matrix_dim);\n    std::complex<double>* eigen_state = reinterpret_cast<std::complex<double>*>(state);\n\n    // insert index\n    const UINT* sorted_insert_index_list = create_sorted_ui_list(target_qubit_index_list, target_qubit_index_count);\n\n    // loop variables\n    const ITYPE loop_dim = dim >> target_qubit_index_count;\n\n    ITYPE state_index;\n    for(state_index = 0 ; state_index < loop_dim ; ++state_index ){\n        // create base index\n        ITYPE basis_0 = state_index;\n        for(UINT cursor=0; cursor < target_qubit_index_count ; cursor++){\n            UINT insert_index = sorted_insert_index_list[cursor];\n            basis_0 = insert_zero_to_basis_index(basis_0, 1ULL << insert_index , insert_index );\n        }\n\n        // fetch vector\n        for(ITYPE y = 0 ; y < matrix_dim ; ++y){\n            buffer[y] = eigen_state[basis_0 ^ matrix_mask_list[y]];\n        }\n\n        buffer = eigen_matrix * buffer;\n\n        // set result\n        for(ITYPE y = 0 ; y < matrix_dim ; ++y){\n            eigen_state[basis_0 ^ matrix_mask_list[y]] = buffer[y];\n        }\n    }\n    free((UINT*)sorted_insert_index_list);\n    free((ITYPE*)matrix_mask_list);\n}\n\nvoid multi_qubit_dense_matrix_gate_eigen(const UINT* target_qubit_index_list, UINT target_qubit_index_count, const Eigen::Matrix<std::complex<double>,Eigen::Dynamic,Eigen::Dynamic,Eigen::RowMajor>& eigen_matrix, CTYPE* state, ITYPE dim){\n    // matrix dim, mask, buffer\n    const ITYPE matrix_dim = 1ULL << target_qubit_index_count;\n    const ITYPE* matrix_mask_list = create_matrix_mask_list(target_qubit_index_list, target_qubit_index_count);\n    Eigen::VectorXcd buffer(matrix_dim);\n    std::complex<double>* eigen_state = reinterpret_cast<std::complex<double>*>(state);\n\n    // insert index\n    const UINT* sorted_insert_index_list = create_sorted_ui_list(target_qubit_index_list, target_qubit_index_count);\n\n    // loop variables\n    const ITYPE loop_dim = dim >> target_qubit_index_count;\n\n    ITYPE state_index;\n    for(state_index = 0 ; state_index < loop_dim ; ++state_index ){\n        // create base index\n        ITYPE basis_0 = state_index;\n        for(UINT cursor=0; cursor < target_qubit_index_count ; cursor++){\n            UINT insert_index = sorted_insert_index_list[cursor];\n            basis_0 = insert_zero_to_basis_index(basis_0, 1ULL << insert_index , insert_index );\n        }\n\n        // fetch vector\n        for(ITYPE y = 0 ; y < matrix_dim ; ++y){\n            buffer[y] = eigen_state[basis_0 ^ matrix_mask_list[y]];\n        }\n\n        buffer = eigen_matrix * buffer;\n\n        // set result\n        for(ITYPE y = 0 ; y < matrix_dim ; ++y){\n            eigen_state[basis_0 ^ matrix_mask_list[y]] = buffer[y];\n        }\n    }\n    free((UINT*)sorted_insert_index_list);\n    free((ITYPE*)matrix_mask_list);\n}\n\nvoid multi_qubit_dense_matrix_gate_eigen(const UINT* target_qubit_index_list, UINT target_qubit_index_count, const Eigen::MatrixXcd& eigen_matrix, CTYPE* state, ITYPE dim) {\n\n    // matrix dim, mask, buffer\n    const ITYPE matrix_dim = 1ULL << target_qubit_index_count;\n    const ITYPE* matrix_mask_list = create_matrix_mask_list(target_qubit_index_list, target_qubit_index_count);\n    std::complex<double>* cppstate = reinterpret_cast<std::complex<double>*>(state);\n    Eigen::VectorXcd buffer(matrix_dim);\n\n    // insert index\n    const UINT* sorted_insert_index_list = create_sorted_ui_list(target_qubit_index_list, target_qubit_index_count);\n\n    // loop variables\n    const ITYPE loop_dim = dim >> target_qubit_index_count;\n\n    ITYPE state_index;\n    for(state_index = 0 ; state_index < loop_dim ; ++state_index ){\n        // create base index\n        ITYPE basis_0 = state_index;\n        for(UINT cursor=0; cursor < target_qubit_index_count ; cursor++){\n            UINT insert_index = sorted_insert_index_list[cursor];\n            basis_0 = insert_zero_to_basis_index(basis_0, 1ULL << insert_index , insert_index );\n        }\n\n        // fetch vector\n        for(ITYPE y = 0 ; y < matrix_dim ; ++y){\n            buffer[y] = cppstate[basis_0 ^ matrix_mask_list[y]];\n        }\n\n        buffer = eigen_matrix * buffer;\n\n        // set result\n        for(ITYPE y = 0 ; y < matrix_dim ; ++y){\n            cppstate[basis_0 ^ matrix_mask_list[y]] = buffer[y];\n        }\n    }\n    free((UINT*)sorted_insert_index_list);\n    free((ITYPE*)matrix_mask_list);\n}\n\nvoid multi_qubit_sparse_matrix_gate_eigen(const UINT* target_qubit_index_list, UINT target_qubit_index_count, const Eigen::SparseMatrix<std::complex<double>>& eigen_matrix, CTYPE* state, ITYPE dim) {\n\t// matrix dim, mask, buffer\n\tconst ITYPE matrix_dim = 1ULL << target_qubit_index_count;\n\tconst ITYPE* matrix_mask_list = create_matrix_mask_list(target_qubit_index_list, target_qubit_index_count);\n\tEigen::VectorXcd buffer(matrix_dim);\n\tstd::complex<double>* eigen_state = reinterpret_cast<std::complex<double>*>(state);\n\n\t// insert index\n\tconst UINT* sorted_insert_index_list = create_sorted_ui_list(target_qubit_index_list, target_qubit_index_count);\n\n\t// loop variables\n\tconst ITYPE loop_dim = dim >> target_qubit_index_count;\n\n\tITYPE state_index;\n\tfor (state_index = 0; state_index < loop_dim; ++state_index) {\n\t\t// create base index\n\t\tITYPE basis_0 = state_index;\n\t\tfor (UINT cursor = 0; cursor < target_qubit_index_count; cursor++) {\n\t\t\tUINT insert_index = sorted_insert_index_list[cursor];\n\t\t\tbasis_0 = insert_zero_to_basis_index(basis_0, 1ULL << insert_index, insert_index);\n\t\t}\n\n\t\t// fetch vector\n\t\tfor (ITYPE y = 0; y < matrix_dim; ++y) {\n\t\t\tbuffer[y] = eigen_state[basis_0 ^ matrix_mask_list[y]];\n\t\t}\n\n\t\tbuffer = eigen_matrix * buffer;\n\n\t\t// set result\n\t\tfor (ITYPE y = 0; y < matrix_dim; ++y) {\n\t\t\teigen_state[basis_0 ^ matrix_mask_list[y]] = buffer[y];\n\t\t}\n\t}\n\tfree((UINT*)sorted_insert_index_list);\n\tfree((ITYPE*)matrix_mask_list);\n}\n\nvoid reversible_boolean_gate(const UINT* target_qubit_index_list, UINT target_qubit_index_count, std::function<ITYPE(ITYPE,ITYPE)> function_ptr, CTYPE* state, ITYPE dim) {\n\n\t// matrix dim, mask, buffer\n\tconst ITYPE matrix_dim = 1ULL << target_qubit_index_count;\n\tconst ITYPE* matrix_mask_list = create_matrix_mask_list(target_qubit_index_list, target_qubit_index_count);\n\n\t// insert index\n\tconst UINT* sorted_insert_index_list = create_sorted_ui_list(target_qubit_index_list, target_qubit_index_count);\n\n\t// loop variables\n\tconst ITYPE loop_dim = dim >> target_qubit_index_count;\n\n\tCTYPE* buffer = (CTYPE*)malloc((size_t)(sizeof(CTYPE)*matrix_dim));\n\tITYPE state_index;\n\tfor (state_index = 0; state_index < loop_dim; ++state_index) {\n\t\t// create base index\n\t\tITYPE basis_0 = state_index;\n\t\tfor (UINT cursor = 0; cursor < target_qubit_index_count; cursor++) {\n\t\t\tUINT insert_index = sorted_insert_index_list[cursor];\n\t\t\tbasis_0 = insert_zero_to_basis_index(basis_0, 1ULL << insert_index, insert_index);\n\t\t}\n\n\t\t// compute matrix-vector multiply\n\n\t\tfor (ITYPE x = 0; x < matrix_dim; ++x) {\n\t\t\tITYPE y = function_ptr(x, matrix_dim);\n\t\t\tbuffer[y] = state[basis_0 ^ matrix_mask_list[x]];\n\t\t}\n\n\t\t// set result\n\t\tfor (ITYPE y = 0; y < matrix_dim; ++y) {\n\t\t\tstate[basis_0 ^ matrix_mask_list[y]] = buffer[y];\n\t\t}\n\t}\n\tfree(buffer);\n\tfree((UINT*)sorted_insert_index_list);\n\tfree((ITYPE*)matrix_mask_list);\n}\n", "meta": {"hexsha": "cdd8fe790b32ad609d06b82e69d2e3a15d9eaff7", "size": 7965, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/csim/update_ops_cpp.cpp", "max_stars_repo_name": "yoooopeeee/qulacs", "max_stars_repo_head_hexsha": "25276cbfc448572ab57e30df84afddc24132b53d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 260.0, "max_stars_repo_stars_event_min_datetime": "2018-10-13T15:58:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T11:03:58.000Z", "max_issues_repo_path": "src/csim/update_ops_cpp.cpp", "max_issues_repo_name": "yoooopeeee/qulacs", "max_issues_repo_head_hexsha": "25276cbfc448572ab57e30df84afddc24132b53d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 182.0, "max_issues_repo_issues_event_min_datetime": "2018-10-14T02:29:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-06T20:23:18.000Z", "max_forks_repo_path": "src/csim/update_ops_cpp.cpp", "max_forks_repo_name": "yoooopeeee/qulacs", "max_forks_repo_head_hexsha": "25276cbfc448572ab57e30df84afddc24132b53d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 88.0, "max_forks_repo_forks_event_min_datetime": "2018-10-10T03:46:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-27T21:56:05.000Z", "avg_line_length": 38.4782608696, "max_line_length": 237, "alphanum_fraction": 0.7073446328, "num_tokens": 2048, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.5926665999540697, "lm_q1q2_score": 0.4760142830590472}}
{"text": "#include <fstream>\n#include <iostream>\n#include <vector>\n\n#include <Eigen/Geometry>\n#include \"GINS.hpp\"\n\nusing namespace std;\n\n// comment to turn off gnss interrupt\n#define INTERRUPT_ON\nconst double CONVERGENCE_TIME = 500;\nconst double GNSS_TIME = 180;\nconst double INTERRUPT_TIME = 60;\nconst double MOTION_TIME = 456370;\n\nstring read_path = \"/home/ubuntu/Dataset/\";\nstring imu_data_name = \"A15_imu.bin\";\nstring gnss_data_name = \"GNSS_RTK.txt\";\nstring truth_name = \"truth.nav\";\n\n#ifdef INTERRUPT_ON\nstring output_name = \"result_interrupt.nav\";\n#else\nstring output_name = \"result.nav\";\n#endif\n\nclass Truth {\npublic:\n  double week;\n  double second;\n  Eigen::Vector3d pos;\n  Eigen::Vector3d vel;\n  Eigen::Vector3d att;\n};\n\nint main(int argc, char const *argv[]) {\n  // read files\n  ifstream imu_data((read_path + imu_data_name).c_str(), ios::in | ios::binary);\n  ifstream gnss_data((read_path + gnss_data_name).c_str());\n  ifstream truth_data((read_path + truth_name).c_str());\n  ofstream result_data((read_path + output_name).c_str(), ios::trunc);\n\n  if (!imu_data || !gnss_data || !truth_data || !result_data) exit(-1);\n\n  // parse data and save\n  iNav::IMUData imu_frame;\n  iNav::GnssData gnss_frame;\n  Truth truth_frame;\n  vector<iNav::IMUData> imu_vec;\n  vector<iNav::GnssData> gnss_vec;\n  vector<Truth> truth_vec;\n\n  iNav::NavData initial_state;\n  initial_state.timestamp = 456300.0;\n  initial_state.pos = Eigen::Vector3d(30.444787369, 114.471863247, 20.910);\n  initial_state.pos_std = Eigen::Vector3d(0.005, 0.004, 0.008);\n  initial_state.vel = Eigen::Vector3d(0, 0, 0);\n  initial_state.vel_std = Eigen::Vector3d(0.003, 0.004, 0.004);\n  initial_state.att = Eigen::Vector3d(0.854, -2.0345, 185.696);\n  initial_state.att_std = Eigen::Vector3d(0.003, 0.003, 0.023);\n\n  iNav::IMUParam imu_param;\n  imu_param.ARW = 0.003;\n  imu_param.VRW = 0.03;\n  imu_param.gyro_bias_std = 0.027;\n  imu_param.T_gyro_bias = 4;\n  imu_param.acc_bias_std = 15;\n  imu_param.T_acc_bias = 4;\n  imu_param.gyro_scalar_std = 300;\n  imu_param.T_gyro_scalar = 4;\n  imu_param.acc_scalar_std = 300;\n  imu_param.T_acc_scalar = 4;\n\n  Eigen::Vector3d l_b(0.136, -0.301, -0.184);\n\n  // save data in vector\n  while (fabs(imu_frame.timestamp - initial_state.timestamp) > 0.001)\n    imu_data.read((char *)&imu_frame, sizeof(imu_frame));\n  imu_vec.push_back(imu_frame);\n\n  while (truth_frame.second < initial_state.timestamp) {\n    truth_data >> truth_frame.week >> truth_frame.second >>\n        truth_frame.pos[0] >> truth_frame.pos[1] >> truth_frame.pos[2] >>\n        truth_frame.vel[0] >> truth_frame.vel[1] >> truth_frame.vel[2] >>\n        truth_frame.att[0] >> truth_frame.att[1] >> truth_frame.att[2];\n  }\n  truth_vec.push_back(truth_frame);\n\n  while (gnss_frame.timestamp < initial_state.timestamp) {\n    gnss_data >> gnss_frame.timestamp >> gnss_frame.pos[0] >>\n        gnss_frame.pos[1] >> gnss_frame.pos[2] >> gnss_frame.pos_std[0] >>\n        gnss_frame.pos_std[1] >> gnss_frame.pos_std[2];\n  }\n  gnss_vec.push_back(gnss_frame);\n\n  while (imu_data.read((char *)&imu_frame, sizeof(imu_frame)))\n    imu_vec.push_back(imu_frame);\n\n  while (!gnss_data.eof()) {\n    gnss_data >> gnss_frame.timestamp >> gnss_frame.pos[0] >>\n        gnss_frame.pos[1] >> gnss_frame.pos[2] >> gnss_frame.pos_std[0] >>\n        gnss_frame.pos_std[1] >> gnss_frame.pos_std[2];\n    gnss_vec.push_back(gnss_frame);\n  }\n\n  while (!truth_data.eof()) {\n    truth_data >> truth_frame.week >> truth_frame.second >>\n        truth_frame.pos[0] >> truth_frame.pos[1] >> truth_frame.pos[2] >>\n        truth_frame.vel[0] >> truth_frame.vel[1] >> truth_frame.vel[2] >>\n        truth_frame.att[0] >> truth_frame.att[1] >> truth_frame.att[2];\n    truth_vec.push_back(truth_frame);\n  }\n\n  iNav::GINS gnss_ins(initial_state, imu_param, l_b, imu_vec[0]);\n\n  iNav::NavData nav_output;\n  bool interrupt_flag = false;\n  double record_time = initial_state.timestamp;\n  int i = 1;\n  for (int j = 1; j < imu_vec.size(); j++) {\n    if (i < gnss_vec.size()) {\n      if (imu_vec[j].timestamp < gnss_vec[i].timestamp) {\n        nav_output = gnss_ins.Mechanization(imu_vec[j]);\n        gnss_ins.Prediction();\n      } else if (!interrupt_flag) {\n        nav_output = gnss_ins.GNSSUpdate(gnss_vec[i++], imu_vec[j]);\n      } else {\n        i++;\n        nav_output = gnss_ins.Mechanization(imu_vec[j]);\n        gnss_ins.Prediction();\n      }\n    } else {\n      nav_output = gnss_ins.Mechanization(imu_vec[j]);\n      gnss_ins.Prediction();\n    }\n\n#ifdef INTERRUPT_ON\n    if (imu_vec[j].timestamp - initial_state.timestamp < CONVERGENCE_TIME) {\n      // wait for convergence\n    } else {\n      if (imu_vec[j].timestamp - record_time > GNSS_TIME && !interrupt_flag) {\n        interrupt_flag = true;\n        record_time = imu_vec[j].timestamp;\n      }\n\n      if (imu_vec[j].timestamp - record_time > INTERRUPT_TIME &&\n          interrupt_flag) {\n        interrupt_flag = false;\n        record_time = imu_vec[j].timestamp;\n      }\n    }\n#endif\n\n    // nav files output\n    if (nav_output.timestamp > MOTION_TIME) {\n      result_data.precision(12);\n      result_data << 2017 << \" \" << nav_output.timestamp << \" \";\n      result_data << nav_output.pos[0] << \" \" << nav_output.pos[1] << \" \"\n                  << nav_output.pos[2] << \" \";\n      result_data << nav_output.vel[0] << \" \" << nav_output.vel[1] << \" \"\n                  << nav_output.vel[2] << \" \";\n      auto yaw =\n          nav_output.att[2] >= 0 ? nav_output.att[2] : nav_output.att[2] + 360;\n      result_data << nav_output.att[0] << \" \" << nav_output.att[1] << \" \" << yaw\n                  << endl;\n    }\n\n    // terminal output\n    cout.precision(12);\n    cout << \"---\" << endl;\n    cout << \"my position: \" << endl;\n    cout << nav_output.timestamp << endl;\n    cout << nav_output.pos.transpose() << endl;\n\n    cout << \"truth: \" << endl;\n    cout << truth_vec[j].second << endl;\n    cout << truth_vec[j].pos.transpose() << endl;\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "090eba86a70938b24fd820dda3deb497f8533de4", "size": 5916, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/GINS_test.cpp", "max_stars_repo_name": "LauZanMo/INS", "max_stars_repo_head_hexsha": "13bd9427c98ba551318f76c94dc793273d2dd070", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-13T02:29:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-13T02:29:54.000Z", "max_issues_repo_path": "src/GINS_test.cpp", "max_issues_repo_name": "LauZanMo/INS", "max_issues_repo_head_hexsha": "13bd9427c98ba551318f76c94dc793273d2dd070", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/GINS_test.cpp", "max_forks_repo_name": "LauZanMo/INS", "max_forks_repo_head_hexsha": "13bd9427c98ba551318f76c94dc793273d2dd070", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-28T01:05:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T01:05:16.000Z", "avg_line_length": 32.3278688525, "max_line_length": 80, "alphanum_fraction": 0.6497633536, "num_tokens": 1736, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.803173791645582, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.47601428026680553}}
{"text": "// Declares State class and model hyperparameters\n\n#ifndef STATE_HPP\n#define STATE_HPP\n\n#include <Eigen/Dense>\n#include <gsl/gsl_randist.h>\n\n///////////////////////////\n// Model hyperparameters //\n///////////////////////////\n\n// Vague gamma prior on CRP concentration\n#define VG_SHAPE 1.0\n#define VG_RATE 0.05\n#define VG_INIT 1.0\n\n// Normal Gamma prior on cluster-level action parameters\n#define NG_SHAPE 1.0\n#define NG_RATE 0.05\n#define NG_NU 0.5\n#define NG_MU 0.0\n\n///////////////////////\n// Class declaration //\n///////////////////////\n\nclass State\n{\n\npublic:\n    // Random number generator\n    const gsl_rng* rng;\n\n    // Model variables               // Shape\n    double conc; // DP concentration\n    Eigen::ArrayXi  z;               // (NUM_OBJECTS)\n    Eigen::ArrayXXi events_pos;      // (NUM_ACTIONS,NUM_OBJECTS)\n    Eigen::ArrayXXi events_neg;      // (NUM_ACTIONS,NUM_OBJECTS)\n    Eigen::ArrayXXd strengths;       // (NUM_ACTIONS,NUM_OBJECTS)\n    Eigen::ArrayXi  counts;          // (NUM_CLUSTERS)\n    Eigen::ArrayXXd action_means;    // (NUM_ACTIONS,NUM_CLUSTERS)\n    Eigen::ArrayXXd action_precs;    // (NUM_ACTIONS,NUM_CLUSTERS)\n\n    // Constructor\n    State(const gsl_rng *r, \n          Eigen::Ref<Eigen::ArrayXXi> events_pos, \n          Eigen::Ref<Eigen::ArrayXXi> events_neg);\n    \n    // Resample the state\n    void update(int num_proposals); \n\n    // For debugging\n    void print_vars(bool show_events = false);\n\nprivate:\n    // Internal update functions\n    void update_conc();\n    void update_z(int num_proposals);\n    void update_action_params();\n    void update_strengths(int num_proposals);\n};\n\n#endif // End include guard\n", "meta": {"hexsha": "f84a536ed859b7c04a6702609207c019fed1d02c", "size": 1647, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "bench/clustering/state.hpp", "max_stars_repo_name": "crafthpc/fphpc", "max_stars_repo_head_hexsha": "6911fd7d3961feec92c8a4c2812b83e7b98ca9d6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-02-23T22:38:32.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-21T13:08:53.000Z", "max_issues_repo_path": "bench/clustering/state.hpp", "max_issues_repo_name": "crafthpc/fphpc", "max_issues_repo_head_hexsha": "6911fd7d3961feec92c8a4c2812b83e7b98ca9d6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2018-11-11T20:38:00.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-15T20:50:37.000Z", "max_forks_repo_path": "bench/clustering/state.hpp", "max_forks_repo_name": "crafthpc/fphpc", "max_forks_repo_head_hexsha": "6911fd7d3961feec92c8a4c2812b83e7b98ca9d6", "max_forks_repo_licenses": ["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.3384615385, "max_line_length": 66, "alphanum_fraction": 0.6326654523, "num_tokens": 416, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.47601427747456376}}
{"text": "#include <unordered_map>\n#include <iostream>\n\n#include <Eigen/Core>\n\n#include \"DBSCAN.h\"\n\n#include \"LineGroup.h\"\n\n#include \"LineDetection.h\"\n\nnamespace localization\n{\n\nvoid LineDetection::filterLineCluster(const std::vector<Line>& cluster)\n{\n    if (cluster.empty()) return;\n\n    std::vector<LineGroup> orientationFiltered;\n    filterByOrientation(cluster, orientationFiltered);\n\n    std::vector<LineGroup> proximityFiltered;\n    for (int i = 0; i < orientationFiltered.size(); ++i)\n    {\n        filterByProximity(orientationFiltered[i], proximityFiltered);\n    }\n    \n    filteredLines_.clear();\n    for (int i = 0; i < proximityFiltered.size(); ++i)\n    {\n        filteredLines_.push_back(proximityFiltered[i].convertToLine());\n    }\n}\n\nvoid LineDetection::filterByOrientation(const std::vector<Line>& cluster, \n                                        std::vector<LineGroup>& filtered) \n{\n    for (int i = 0; i < cluster.size(); ++i) \n    {\n        groupByOrientation(cluster[i], filtered);\n    }\n} \n\nvoid LineDetection::groupByOrientation(const Line& line, std::vector<LineGroup>& groups)\n{\n    bool groupFound = false;\n    for (int i = 0; i < groups.size() && !groupFound; ++i) \n    {\n        if (groups[i].isCollateral(line, 0.80))\n        {\n            groups[i].add(line);\n            groupFound = true;\n        }\n    }\n\n    if (!groupFound)\n    {\n        groups.push_back(LineGroup(line));\n    }\n}\n\nvoid LineDetection::filterByProximity(const LineGroup& group, \n                                      std::vector<LineGroup>& filtered)\n{\n    std::vector<const Line*> lines = group.getLines();\n    std::vector<Vector> centroids(lines.size());\n    for (int i = 0; i < lines.size(); ++i)\n    {\n        centroids[i] = lines[i]->getCentroid();\n    }\n\n    std::vector<int> clusterMemberships;\n    DBSCAN::DBSCAN(centroids, 50, 1, clusterMemberships);\n\n    parseClusterMemberships(clusterMemberships, lines, filtered);\n}\n\nvoid LineDetection::parseClusterMemberships(const std::vector<int>& clusterMemberships, \n                                            const std::vector<const Line*>& cluster,\n                                                  std::vector<LineGroup>& filtered)\n{\n    if (cluster.size() != clusterMemberships.size()) return;\n\n    std::unordered_map<int, LineGroup> groups;\n\n    std::unordered_map<int, LineGroup>::iterator it = groups.end();\n    for (int i = 0; i < clusterMemberships.size(); ++i) \n    {\n        int groupId = clusterMemberships[i];\n        it = groups.find(groupId);\n        if (it != groups.end()) \n        {\n            it->second.add(*cluster[i]);\n        } \n        else \n        {\n            groups.insert({ groupId, LineGroup(*cluster[i]) });\n        }\n    }\n\n    for (it = groups.begin(); it != groups.end(); it++) \n    {\n        filtered.push_back(it->second);\n    }\n}\n\n}", "meta": {"hexsha": "1d88187e1cefbfa4afb9887d4ef89bd477bf99ab", "size": 2816, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/localization/arena-detection/LineDetection.cpp", "max_stars_repo_name": "elikos/elikos_localization", "max_stars_repo_head_hexsha": "0eca76e5c836b1b0f407afffe0d1b85605d3cfa1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-02-24T08:29:06.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-24T08:29:06.000Z", "max_issues_repo_path": "src/localization/arena-detection/LineDetection.cpp", "max_issues_repo_name": "elikos/elikos_localization", "max_issues_repo_head_hexsha": "0eca76e5c836b1b0f407afffe0d1b85605d3cfa1", "max_issues_repo_licenses": ["MIT"], "max_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/arena-detection/LineDetection.cpp", "max_forks_repo_name": "elikos/elikos_localization", "max_forks_repo_head_hexsha": "0eca76e5c836b1b0f407afffe0d1b85605d3cfa1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-02-12T23:06:13.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-12T23:06:13.000Z", "avg_line_length": 26.3177570093, "max_line_length": 88, "alphanum_fraction": 0.5855823864, "num_tokens": 662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.47601427747456376}}
{"text": "#include <Eigen/Geometry>\n#include <ros/ros.h>\n#include <tf/transform_datatypes.h>\n#include <tf/transform_broadcaster.h>\n#include <tf/transform_listener.h>\n#include <tf/transform_broadcaster.h>\n#include <tf_conversions/tf_eigen.h>\n#include <geometry_msgs/QuaternionStamped.h>\n#include <robot_kf/WheelOdometry.h>\n#include <nav_msgs/Odometry.h>\n#include <sensor_msgs/Imu.h>\n#include <robot_kf/robot_kf.h>\n\nusing Eigen::Vector3d;\nusing Eigen::Matrix3d;\ntypedef Eigen::Matrix<double, 6, 6> Matrix6d;\n\nstatic double const big = 99999.0;\n\nstatic boost::shared_ptr<tf::TransformListener> sub_tf;\nstatic boost::shared_ptr<tf::TransformBroadcaster> pub_tf;\nstatic ros::Subscriber sub_compass, sub_encoders, sub_gps;\nstatic ros::Publisher pub_fused;\n\nstatic robot_kf::KalmanFilter kf;\nstatic geometry_msgs::Twist velocity;\n\nstatic std::string global_frame_id, odom_frame_id, base_frame_id, offset_frame_id;\nstatic boost::shared_ptr<tf::Transform> offset_tf;\n\nstatic ros::Time prev_odom_time;\nstatic ros::Time prev_compass_time;\n\nstatic void publish(ros::Time stamp)\n{\n    Vector3d const state = kf.getState();\n    Matrix3d const cov = kf.getCovariance();\n\n    // Wrap the fused state estimate in a ROS message.\n    geometry_msgs::PoseStamped fused_base;\n    fused_base.header.stamp    = stamp;\n    fused_base.header.frame_id = odom_frame_id;\n    fused_base.pose.position.x = state[0];\n    fused_base.pose.position.y = state[1];\n    fused_base.pose.position.z = 0.0;\n    fused_base.pose.orientation = tf::createQuaternionMsgFromYaw(state[2]);\n\n    /*\n     * We actually want to publish the /map to /base_footprint transform, but\n     * this would cause /base_footprint to have two parents. Instead, we need\n     * to publish the /map to /odom transform. See this chart:\n     *\n     * /map --[T1]--> /odom --[T2]--> /base_footprint\n     * /map ----------[T3]----------> /base_footprint\n     *\n     * The output of the Kalman filter is T3, but we want T1. We find T1 by\n     * computing T1 = T3 * inv(T2), where T2 is provided by the odometry\n     * source.\n     */\n    tf::Vector3 const pos(state[0], state[1], 0);\n    tf::Quaternion const ori = tf::createQuaternionFromYaw(state[2]);\n    tf::Transform t3(ori, pos);\n\n    tf::StampedTransform t2;\n    try {\n        sub_tf->waitForTransform(odom_frame_id, base_frame_id, stamp, ros::Duration(1.0));\n        sub_tf->lookupTransform(odom_frame_id, base_frame_id, stamp, t2);\n    } catch (tf::TransformException const &e) {\n        ROS_WARN(\"%s\", e.what());\n        return;\n    }\n\n    tf::Transform const t1 = t3 * t2.inverse();\n    tf::StampedTransform transform(t1, stamp, global_frame_id, odom_frame_id);\n    pub_tf->sendTransform(transform);\n\n    // Relative frame to fix RViz numerical stability issues.\n    if (offset_tf) {\n        tf::StampedTransform offset_stamped(*offset_tf, stamp, global_frame_id, offset_frame_id);\n        pub_tf->sendTransform(offset_stamped);\n    }\n    \n    // Publish the odometry message.\n    nav_msgs::Odometry msg;\n    msg.header.stamp = stamp;\n    msg.header.frame_id = global_frame_id;\n    msg.child_frame_id = base_frame_id;\n    msg.pose.pose =  fused_base.pose;\n\n    // Use the covariance estimated by the filter.\n    Eigen::Map<Matrix6d> cov_out(&msg.pose.covariance.front());\n    cov_out.topLeftCorner<2, 2>() = cov.topLeftCorner<2, 2>();\n    cov_out(5, 5) = cov(2, 2);\n\n    // TODO: Estimate the covariance of the encoders.\n    msg.twist.twist = velocity;\n    msg.twist.covariance[0] = -1;\n    pub_fused.publish(msg);\n}\n\nstatic void updateCompass(sensor_msgs::Imu const &msg)\n{\n    if (msg.header.frame_id != base_frame_id) {\n        ROS_ERROR_THROTTLE(10, \"Imu message must have frame_id '%s'\",\n                           base_frame_id.c_str());\n        return;\n    }\n\n    double const yaw = tf::getYaw(msg.orientation);\n    Eigen::Map<Eigen::Matrix3d const> cov_raw(&msg.orientation_covariance.front());\n\n    kf.update_compass(yaw, cov_raw(2, 2));\n}\n\nstatic void updateEncoders(robot_kf::WheelOdometry const &msg)\n{\n    if (msg.header.frame_id != base_frame_id) {\n        ROS_ERROR_THROTTLE(10, \"WheelOdometry message must have frame_id '%s'\", base_frame_id.c_str());\n        return;\n    } else if (msg.separation <= 0) {\n        ROS_ERROR_THROTTLE(10, \"Wheel separation in WheelOdometry message must be positive.\");\n        return;\n    }\n\n    Eigen::Vector2d const z_raw = (Eigen::Vector2d() <<\n        msg.left.movement, msg.right.movement).finished();\n    Eigen::Matrix2d const cov_z_raw = (Eigen::Matrix2d() <<\n        msg.left.variance, 0.0, 0.0, msg.right.variance).finished();\n\n    // Prevent the encoders from double-counting rotation in conjunction with\n    // the compass.\n    Eigen::Vector2d z;\n    Eigen::Matrix2d cov_z;\n    if (prev_odom_time < prev_compass_time) {\n        ros::Duration const dt_encoders = msg.header.stamp - prev_odom_time;\n        ros::Duration const dt_compass  = prev_odom_time - prev_compass_time;\n        ros::Duration const dt_ignore = dt_encoders - dt_compass;\n        double const ratio = 1.0 - dt_ignore.toSec() / dt_encoders.toSec();\n        z = ratio * z_raw;\n        cov_z = ratio * cov_z_raw;\n    } else {\n        z = z_raw;\n        cov_z = cov_z_raw;\n    }\n    // FIXME: Correct the GPS in the same way.\n\n    // Compute velocity using the wheel encoders. Theoretically the GPS and\n    // compass could also be used to estimate these velocities, but those\n    // estimates are too noisy to justify the complexity of adding two more\n    // state variables.\n    double const movement_linear = (z[1] + z[0]) / 2;\n    double const movement_angular = (z[1] - z[0]) / msg.separation;\n    double const delta_time = msg.timestep.toSec();\n    velocity.linear.x = movement_linear / delta_time;\n    velocity.angular.z = movement_angular / delta_time;\n\n    kf.update_encoders(z, cov_z, msg.separation);\n    publish(msg.header.stamp);\n}\n\nstatic void updateGps(nav_msgs::Odometry const &msg)\n{\n    if (msg.header.frame_id != global_frame_id) {\n        ROS_ERROR_THROTTLE(10, \"GPS message must have frame_id '%s'\",\n                           global_frame_id.c_str());\n        return;\n    }\n\n    Eigen::Vector2d const z_raw = (Eigen::Vector2d() <<\n        msg.pose.pose.position.x, msg.pose.pose.position.y).finished();\n    Eigen::Map<Eigen::Matrix<double, 6, 6> const> cov6_raw(\n        &msg.pose.covariance.front()\n    );\n    Eigen::Matrix2d const cov_raw = cov6_raw.topLeftCorner<2, 2>();\n\n    /* The GPS gives a position relative to child_frame_id, which is located at\n     * the center of the GPS antennna. However, the Kalman filter only manipulates\n     * quantities in base_frame_id. So the situation is:\n     *\n     *     /map --[ T1 ]--> /gps <--[ T2 ]-- /base_footprint\n     *     /map -----------[ T3 ]----------> /base_footprint\n     *\n     * Transformation T1 is provided by the GPS, T2 is a static transformation\n     * provided by the URDF, and T3 is the desired translation. Therefore, we\n     * can find T3 by: T3 = T1 * T2^{-1}.\n     */\n    tf::StampedTransform t2_inv;\n    try {\n        sub_tf->lookupTransform(msg.child_frame_id, base_frame_id, ros::Time(0), t2_inv);\n    } catch (tf::TransformException const &e) {\n        ROS_WARN(\"%s\", e.what());\n        return;\n    }\n\n    tf::Vector3 const z_bt_raw(z_raw[0], z_raw[1], 0);\n    tf::Vector3 const z_bt = t2_inv * z_bt_raw;\n    Eigen::Vector2d const z = (Eigen::Vector2d() << z_bt[0], z_bt[1]).finished();\n    // TODO: Transform the covariance matrix using the rotation matrix.\n    Eigen::Matrix2d const cov = cov_raw;\n\n    if (!offset_tf) {\n        tf::Vector3 const pos_offset(z[0], z[1], 0.0);\n        tf::Quaternion const ori_offset(0.0, 0.0, 0.0, 1.0);\n        offset_tf = boost::make_shared<tf::Transform>(ori_offset, pos_offset);\n        ROS_INFO(\"Initialized %s to (%f, %f)\", offset_frame_id.c_str(), z[0], z[1]);\n    }\n\n    kf.update_gps(z, cov);\n}\n\nint main(int argc, char **argv)\n{\n    ros::init(argc, argv, \"robot_kf_node\");\n\n    // Initialize the skeleton twist message.\n    velocity.linear.y = 0;\n    velocity.linear.z = 0;\n    velocity.angular.x = 0;\n    velocity.angular.y = 0;\n\n    ros::NodeHandle nh, nh_node(\"~\");\n    nh_node.param<std::string>(\"global_frame_id\", global_frame_id, \"/map\");\n    nh_node.param<std::string>(\"odom_frame_id\", odom_frame_id, \"/odom\");\n    nh_node.param<std::string>(\"base_frame_id\", base_frame_id, \"/base_footprint\");\n    nh_node.param<std::string>(\"offset_frame_id\", offset_frame_id, \"/map_offset\");\n\n    sub_tf = boost::make_shared<tf::TransformListener>();\n    pub_tf = boost::make_shared<tf::TransformBroadcaster>();\n    sub_compass  = nh.subscribe(\"compass\", 1, &updateCompass);\n    sub_encoders = nh.subscribe(\"wheel_odom\", 1, &updateEncoders);\n    sub_gps      = nh.subscribe(\"gps\", 1, &updateGps);\n    pub_fused    = nh.advertise<nav_msgs::Odometry>(\"odom_fused\", 100);\n\n    ros::spin();\n    return 0;\n}\n", "meta": {"hexsha": "5494d90f609e59c8176196ce350d58044e33038a", "size": 8840, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/robot_kf_node.cc", "max_stars_repo_name": "mkoval/robot_kf", "max_stars_repo_head_hexsha": "985110b2dff1105519e9d3d8d2b9e9d30d270f1f", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2018-05-24T07:44:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T06:23:19.000Z", "max_issues_repo_path": "src/robot_kf_node.cc", "max_issues_repo_name": "mkoval/robot_kf", "max_issues_repo_head_hexsha": "985110b2dff1105519e9d3d8d2b9e9d30d270f1f", "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/robot_kf_node.cc", "max_forks_repo_name": "mkoval/robot_kf", "max_forks_repo_head_hexsha": "985110b2dff1105519e9d3d8d2b9e9d30d270f1f", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2016-04-19T07:57:43.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-29T06:49:40.000Z", "avg_line_length": 37.2995780591, "max_line_length": 103, "alphanum_fraction": 0.6667420814, "num_tokens": 2396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.47601427747456376}}
{"text": "\n// Copyright (C) 2018 Thanaphon Chavengsaksongkram <as12production@gmail.com>, He Sun <he.sun@ed.ac.uk>\n// This file is subject to the license terms in the LICENSE file\n// found in the top-level directory of this distribution.\n\n#ifndef GSPARSE_ER_APPROXIMATEER_HPP\n#define GSPARSE_ER_APPROXIMATEER_HPP\n\n#include \"../Interface/EffectiveResistance.hpp\"\n#include \"../Config.hpp\"\n#include \"../Util/JL.hpp\"  // Building Random Projection\n\n// Approximate ER Policies\n#include \"Policy/AproxERSLMJacobiCG.hpp\"\n\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\nnamespace gSparse \n{\n    namespace ER \n    {\n\n        /// \\ingroup EffectiveResistance\n        ///\n        /// This class calculates Approxmation of Graph's Effective Resistance.\n        /// There are many approach to this problem. Such approach is set via class Policy.\n        template <typename Policy> \n        class _ApproximateER : public IEffectiveResistance, private Policy\n        {\n        public:\n            using Policy::_calculateER;\n            inline gSparse::COMPUTE_INFO CalculateER( gSparse::PrecisionRowMatrix & er,\n                const gSparse::Graph & graph)\n            {\n                return _calculateER(er, graph);\n            }\n        };\n        typedef _ApproximateER<Policy::AproxERSLMJacobiCG> ApproximateER; //<! ApproximateER class to calculate effective resistance\n    }\n}\n#endif\n\n", "meta": {"hexsha": "4c9f6299761ff2ff7807cebadb3c2094dad76793", "size": 1369, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/gSparse/ER/ApproximateER.hpp", "max_stars_repo_name": "As-12/gSparse", "max_stars_repo_head_hexsha": "66c7d60544565d4bdafbffa0ba08d62db620f9d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-09-14T09:38:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-11T13:03:55.000Z", "max_issues_repo_path": "include/gSparse/ER/ApproximateER.hpp", "max_issues_repo_name": "As-12/gSparse", "max_issues_repo_head_hexsha": "66c7d60544565d4bdafbffa0ba08d62db620f9d1", "max_issues_repo_licenses": ["MIT"], "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/gSparse/ER/ApproximateER.hpp", "max_forks_repo_name": "As-12/gSparse", "max_forks_repo_head_hexsha": "66c7d60544565d4bdafbffa0ba08d62db620f9d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-11T13:03:58.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-11T13:03:58.000Z", "avg_line_length": 31.8372093023, "max_line_length": 132, "alphanum_fraction": 0.6800584368, "num_tokens": 307, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737775116229, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.47601427189008005}}
{"text": "//============================================================================\n//\n// This file is part of the Thea toolkit.\n//\n// This software is distributed under the BSD license, as detailed in the\n// accompanying LICENSE.txt file. Portions are derived from other works:\n// their respective licenses and copyright information are reproduced in\n// LICENSE.txt and/or in the relevant source files.\n//\n// Author: Siddhartha Chaudhuri\n// First version: 2014\n//\n//============================================================================\n\n#ifndef __Thea_Algorithms_Icp3_hpp__\n#define __Thea_Algorithms_Icp3_hpp__\n\n#include \"../Common.hpp\"\n#include \"BvhN.hpp\"\n#include \"MetricL2.hpp\"\n#include \"PointTraitsN.hpp\"\n#include \"../AffineTransformN.hpp\"\n#include \"../Math.hpp\"\n#include \"../MatVec.hpp\"\n#include \"../HyperplaneN.hpp\"\n#include <Eigen/SVD>\n\nnamespace Thea {\nnamespace Algorithms {\n\n/** Align two sets of points in 3D using the Iterative Closest Point (ICP) algorithm. */\ntemplate <typename ScalarT = Real>\nclass Icp3\n{\n  private:\n    typedef Vector<3, ScalarT>       VectorT;  ///< 3D vector.\n    typedef Matrix<3, 3, ScalarT>    MatrixT;  ///< 3x3 matrix.\n    typedef HyperplaneN<3, ScalarT>  PlaneT;   ///< Plane in 3-space.\n\n    /** The default weight per point. */\n    template <typename T> struct DefaultWeightFunc\n    {\n      double getTranslationWeight(T const & t) const { return 1; }\n      double getRotationWeight(T const & t) const { return 1; }\n    };\n\n  public:\n    typedef AffineTransformN<3, ScalarT> AffineTransformT;  ///< Affine transform in 3 dimensions.\n\n    /**\n     * Constructor.\n     *\n     * @param fractional_error_threshold_ The maximum fractional change in error to determine convergence (negative for\n     *   default).\n     * @param min_iterations_ The minimum number of iterations (negative for default).\n     * @param max_iterations_ The maximum number of iterations (negative for default).\n     * @param verbose_ If true, print extra debugging information.\n     */\n    Icp3(ScalarT fractional_error_threshold_ = -1, intx min_iterations_ = -1, intx max_iterations_ = -1, bool verbose_ = false)\n    : fractional_error_threshold(fractional_error_threshold_), min_iterations(min_iterations_), max_iterations(max_iterations_),\n      has_up(false), verbose(verbose_)\n    {\n      if (fractional_error_threshold < 0) fractional_error_threshold = 0.0001;\n      if (min_iterations < 0) min_iterations = 3;\n      if (max_iterations < 0) max_iterations = 10;\n    }\n\n    /** Set the up vector. Subsequent alignments will only rotate around the up vector. */\n    void setUpVector(VectorT const & up_) { up = up_.normalized(); has_up = true; }\n\n    /** Check if the up vector has been set. */\n    bool hasUpVector() const { return has_up; }\n\n    /**\n     * Get the up vector, if it has been set.\n     *\n     * @see hasUpVector();\n     */\n    VectorT const & getUpVector() const { return up; }\n\n    /** Clear the up vector. Subsequent alignments will be unconstrained. */\n    void clearUpVector() { has_up = false; }\n\n    /** Find the transform that best aligns the point set \\a from to the point set \\a to. */\n    template <typename FromT, typename ToT>\n    AffineTransformT align(intx from_num_pts, FromT const * from, intx to_num_pts, ToT const * to, ScalarT * error = nullptr)\n                     const\n    {\n      return align(from_num_pts, from, (DefaultWeightFunc<FromT> *)nullptr, to_num_pts, to, error);\n    }\n\n    /**\n     * Find the transform that best aligns the point set \\a from to the point set \\a to, with a per-point weight assigned to the\n     * cost of aligning each element of \\a from.\n     */\n    template <typename FromT, typename ToT, typename FromWeightFuncT>\n    AffineTransformT align(intx from_num_pts, FromT const * from, FromWeightFuncT * from_weight_func,\n                           intx to_num_pts, ToT const * to, ScalarT * error = nullptr) const\n    {\n      if (from_num_pts <= 0 || to_num_pts <= 0)\n        return AffineTransformT::identity();\n\n      BvhN<ToT, 3, ScalarT> to_bvh(to, to + to_num_pts);\n      to_bvh.enableNearestNeighborAcceleration();\n\n      return align(from_num_pts, from, from_weight_func, to_bvh, error);\n    }\n\n    /** Find the transform that best aligns the point set \\a from to the proximity query structure \\a to. */\n    template <typename FromT, typename ToProximityQueryStructureT>\n    AffineTransformT align(intx from_num_pts, FromT const * from, ToProximityQueryStructureT const & to,\n                           ScalarT * error = nullptr) const\n    {\n      return align(from_num_pts, from, (DefaultWeightFunc<FromT> *)nullptr, to, error);\n    }\n\n    /**\n     * Find the transform that best aligns the point set \\a from to the proximity query structure \\a to, with a per-point weight\n     * assigned to the cost of aligning each element of \\a from.\n     */\n    template <typename FromT, typename ToProximityQueryStructureT, typename FromWeightFuncT>\n    AffineTransformT align(intx from_num_pts, FromT const * from, FromWeightFuncT * from_weight_func,\n                           ToProximityQueryStructureT const & to, ScalarT * error = nullptr) const\n    {\n      return align(from_num_pts, from, from_weight_func, nullptr, to, nullptr, error);\n    }\n\n    /**\n     * Find the transform that best aligns the point set \\a from to the point set \\a to, assuming both sets have known symmetry\n     * planes. The computed alignment will ensure the symmetry planes coincide.\n     */\n    template <typename FromT, typename ToT>\n    AffineTransformT alignSymmetric(intx from_num_pts, FromT const * from, PlaneT const & from_symmetry_plane,\n                                    intx to_num_pts, ToT const * to, PlaneT const & to_symmetry_plane,\n                                    ScalarT * error = nullptr) const\n    {\n      return alignSymmetric(from_num_pts, from, (DefaultWeightFunc<FromT> *)nullptr, from_symmetry_plane,\n                            to_num_pts, to, to_symmetry_plane, error);\n    }\n\n    /**\n     * Find the transform that best aligns the point set \\a from to the point set \\a to, with a per-point weight assigned to the\n     * cost of aligning each element of \\a from, and assuming both sets have known symmetry planes. The computed alignment will\n     * ensure the symmetry planes coincide.\n     */\n    template <typename FromT, typename ToT, typename FromWeightFuncT>\n    AffineTransformT alignSymmetric(intx from_num_pts, FromT const * from, FromWeightFuncT * from_weight_func,\n                                    PlaneT const & from_symmetry_plane,\n                                    intx to_num_pts, ToT const * to, PlaneT const & to_symmetry_plane,\n                                    ScalarT * error = nullptr) const\n    {\n      if (from_num_pts <= 0 || to_num_pts <= 0)\n        return AffineTransformT::identity();\n\n      BvhN<ToT, 3, ScalarT> to_bvh(to, to + to_num_pts);\n      to_bvh.enableNearestNeighborAcceleration();\n\n      return alignSymmetric(from_num_pts, from, from_weight_func, from_symmetry_plane, to_bvh, to_symmetry_plane, error);\n    }\n\n    /**\n     * Find the transform that best aligns the point set \\a from to the proximity query structure \\a to, assuming both \\a from\n     * and \\a to have known symmetry planes. The computed alignment will ensure the symmetry planes coincide.\n     */\n    template <typename FromT, typename ToProximityQueryStructureT>\n    AffineTransformT alignSymmetric(intx from_num_pts, FromT const * from, PlaneT const & from_symmetry_plane,\n                                    ToProximityQueryStructureT const & to, PlaneT const & to_symmetry_plane,\n                                    ScalarT * error = nullptr) const\n    {\n      return alignSymmetric(from_num_pts, from, (DefaultWeightFunc<FromT> *)nullptr, from_symmetry_plane, to, to_symmetry_plane,\n                            error);\n    }\n\n    /**\n     * Find the transform that best aligns the point set \\a from to the proximity query structure \\a to, with a per-point weight\n     * assigned to the cost of aligning each element of \\a from, and assuming both \\a from and \\a to have known symmetry planes.\n     * The computed alignment will ensure the symmetry planes coincide.\n     */\n    template <typename FromT, typename ToProximityQueryStructureT, typename FromWeightFuncT>\n    AffineTransformT alignSymmetric(intx from_num_pts, FromT const * from, FromWeightFuncT * from_weight_func,\n                                    PlaneT const & from_symmetry_plane,\n                                    ToProximityQueryStructureT const & to, PlaneT const & to_symmetry_plane,\n                                    ScalarT * error = nullptr) const\n    {\n      return align(from_num_pts, from, from_weight_func, &from_symmetry_plane, to, &to_symmetry_plane, error);\n    }\n\n  private:\n    /**\n     * Find the transform that best aligns the point set \\a from to the proximity query structure \\a to, with a per-point weight\n     * assigned to the cost of aligning each element of \\a from.\n     */\n    template <typename FromT, typename ToProximityQueryStructureT, typename FromWeightFuncT>\n    AffineTransformT align(intx from_num_pts, FromT const * from, FromWeightFuncT * from_weight_func,\n                           PlaneT const * from_symmetry_plane, ToProximityQueryStructureT const & to,\n                           PlaneT const * to_symmetry_plane, ScalarT * error = nullptr) const\n    {\n      if (verbose)\n        THEA_CONSOLE << \"Icp3(fractional_error_threshold = \" << fractional_error_threshold\n                     <<    \", min_iterations = \" << min_iterations\n                     <<    \", max_iterations = \" << max_iterations << ')';\n\n      if (from_num_pts <= 0)\n      {\n        if (error) *error = 0;\n        return AffineTransformT::identity();\n      }\n\n      Array<VectorT> from_points((size_t)from_num_pts);\n      Array<VectorT> to_points((size_t)from_num_pts);\n      for (size_t i = 0; i < from_points.size(); ++i)\n        from_points[i] = PointTraitsN<FromT, 3, ScalarT>::getPosition(from[i]);\n\n      AffineTransformT old_tr = AffineTransformT::identity();\n      ScalarT old_error = measureError(old_tr, from_num_pts, &from_points[0], from_weight_func, to, &to_points[0]);\n      if (verbose) THEA_CONSOLE << \"[Icp3] Initial error: \" << old_error;\n\n      if (old_error <= std::numeric_limits<ScalarT>::min())\n      {\n        if (error) *error = old_error;\n        return old_tr;\n      }\n\n      ScalarT new_error = old_error;\n      AffineTransformT new_tr = old_tr;\n      for (intx i = 0; i < max_iterations; ++i)\n      {\n        // Align using the point mapping created by the last call to measureError()\n        AffineTransformT inc_tr = alignOneStep(from_num_pts, &from_points[0], from_weight_func, from_symmetry_plane,\n                                               &to_points[0], to_symmetry_plane);\n\n        // Update the overall transform\n        new_tr = inc_tr * old_tr;\n\n        // Compute the new error and the new mapping between points\n        if (i < max_iterations - 1 || error)\n          new_error = measureError(inc_tr, from_num_pts, &from_points[0], from_weight_func, to, &to_points[0]);\n\n        if (i < max_iterations - 1)\n        {\n          ScalarT frac_change = (old_error - new_error) / old_error;\n\n          if (verbose)\n            THEA_CONSOLE << \"[Icp3] Iteration \" << i << \" error: \" << new_error << \" (fractional change: \" << frac_change << ')';\n\n          if (i >= min_iterations && frac_change < fractional_error_threshold)\n          {\n            if (frac_change > 0)  // we improved slightly\n            {\n              if (error) *error = new_error;\n              return new_tr;\n            }\n            else  // the previous alignment was better\n            {\n              if (error) *error = old_error;\n              return old_tr;\n            }\n          }\n\n          for (size_t j = 0; j < from_points.size(); ++j)  // transform original points to prevent drift\n            from_points[j] = new_tr * PointTraitsN<FromT, 3, ScalarT>::getPosition(from[j]);\n        }\n        else\n        {\n          if (verbose)\n            THEA_CONSOLE << \"[Icp3] Iteration \" << i << \" error: \" << new_error;\n        }\n\n        old_error = new_error;\n        old_tr = new_tr;\n      }\n\n      if (error) *error = new_error;\n      return new_tr;\n    }\n\n    /**\n     * Align a point set to a proximity query structure, in one ICP step, after finding the nearest neighbor of each point in\n     * the first set in the structure.\n     */\n    template <typename FromT, typename ToProximityQueryStructureT, typename FromWeightFuncT>\n    AffineTransformT alignOneStep(intx from_num_pts, FromT const * from, FromWeightFuncT * from_weight_func,\n                                  PlaneT const * from_sym_plane, ToProximityQueryStructureT const & to,\n                                  PlaneT const * to_sym_plane, VectorT * to_points) const\n    {\n      for (intx i = 0; i < from_num_pts; ++i)\n      {\n        intx index = to.template closestElement<MetricL2>(PointTraitsN<FromT, 3, ScalarT>::getPosition(from[i]), -1,\n                                                          UniversalCompatibility(), nullptr, &to_points[i]);\n        if (index < 0)\n          throw Error(format(\"Icp3: Couldn't get nearest neighbor of source point %ld\", i));\n      }\n\n      return alignOneStep(from_num_pts, from, from_weight_func, from_sym_plane, to_points, to_sym_plane);\n    }\n\n    /** Align one point set to another, in one ICP step, with a known bijective mapping between the points. */\n    template <typename FromT, typename FromWeightFuncT>\n    AffineTransformT alignOneStep(intx num_pts, FromT const * from, FromWeightFuncT * from_weight_func,\n                                  PlaneT const * from_sym_plane, VectorT const * to, PlaneT const * to_sym_plane) const\n    {\n      // When both point sets have symmetry planes, we'll align the projections. This does *NOT* minimize the correct error\n      // function, but provides a simple approximation to the true solution which is ok for now.\n      bool use_symmetry = from_sym_plane && to_sym_plane;\n\n      // Find centroids of the two sets\n      VectorT p_mean = VectorT::Zero();\n      VectorT q_mean = VectorT::Zero();\n      ScalarT sum_weights = 0;\n      for (intx i = 0; i < num_pts; ++i)\n      {\n        VectorT p = PointTraitsN<FromT, 3, ScalarT>::getPosition(from[i]);\n        VectorT q = to[i];\n        if (use_symmetry)\n        {\n          p = from_sym_plane->closestPoint(p);\n          q = to_sym_plane->closestPoint(q);\n        }\n\n        if (from_weight_func)\n        {\n          ScalarT weight = (ScalarT)from_weight_func->getTranslationWeight(from[i]);\n          p_mean += weight * p;\n          q_mean += weight * q;\n          sum_weights += weight;\n        }\n        else\n        {\n          p_mean += p;\n          q_mean += q;\n          sum_weights += 1;\n        }\n      }\n\n      p_mean /= sum_weights;\n      q_mean /= sum_weights;\n\n      // Find cross-covariance matrix\n      MatrixT cov; cov.setZero();\n      for (intx i = 0; i < num_pts; ++i)\n      {\n        VectorT p = PointTraitsN<FromT, 3, ScalarT>::getPosition(from[i]);\n        VectorT q = to[i];\n        if (use_symmetry)\n        {\n          p = from_sym_plane->closestPoint(p);\n          q = to_sym_plane->closestPoint(q);\n        }\n\n        VectorT dp = p - p_mean;\n        VectorT dq = q - q_mean;\n\n        if (has_up)  // remove the component in the up direction\n        {\n          dp = dp - (dp.dot(up) * up);\n          dq = dq - (dq.dot(up) * up);\n        }\n\n        if (from_weight_func)\n        {\n          ScalarT weight = (ScalarT)from_weight_func->getRotationWeight(from[i]);\n          dp *= weight;\n          dq *= weight;\n        }\n\n        cov += (dp * dq.transpose());  // outer product\n      }\n\n      Eigen::JacobiSVD<MatrixT> svd(cov, Eigen::ComputeFullU | Eigen::ComputeFullV);\n      MatrixT rot = svd.matrixU() * svd.matrixV().transpose();\n\n      if (use_symmetry && rot.determinant() < 0)  // matching two planar projections can cause flips in the symmetry plane\n      {\n        // Generate the transformation that flips in the (origin-centered) target symmetry plane\n        VectorT n = to_sym_plane->getNormal();\n        MatrixT nn = n * n.transpose();  // outer product\n        MatrixT flip = MatrixT::Identity() - static_cast<ScalarT>(2) * nn;\n        rot = flip * rot;\n      }\n\n      VectorT trans = q_mean - rot * p_mean;\n\n      return AffineTransformT(rot, trans);\n    }\n\n    /** Measure the alignment error of a mapping from each point of \\a from to its nearest neighbor in \\a to. */\n    template <typename FromT, typename ToProximityQueryStructureT, typename FromWeightFuncT>\n    static ScalarT measureError(AffineTransformT const & tr,\n                                intx from_num_pts, FromT const * from, FromWeightFuncT * from_weight_func,\n                                ToProximityQueryStructureT const & to, VectorT * to_points)\n    {\n      if (from_num_pts <= 0)\n        return 0;\n\n      for (intx i = 0; i < from_num_pts; ++i)\n      {\n        intx index = to.template closestElement<MetricL2>(PointTraitsN<FromT, 3, ScalarT>::getPosition(from[i]), -1,\n                                                          UniversalCompatibility(), nullptr, &to_points[i]);\n        if (index < 0)\n          throw Error(format(\"Icp3: Couldn't get nearest neighbor of source point %ld\", i));\n      }\n\n      return measureError(tr, from_num_pts, from, from_weight_func, to_points);\n    }\n\n    /**\n     * Measure the alignment error of a mapping from each point of \\a from to each point of \\a to, with a known bijective\n     * mapping between them.\n     */\n    template <typename FromT, typename FromWeightFuncT>\n    static ScalarT measureError(AffineTransformT const & tr,\n                                intx num_pts, FromT const * from, FromWeightFuncT * from_weight_func,\n                                VectorT const * to)\n    {\n      if (num_pts <= 0)\n        return 0;\n\n      VectorT p_mean = VectorT::Zero();\n      VectorT q_mean = VectorT::Zero();\n\n      ScalarT sum_weights = 0;\n      for (intx i = 0; i < num_pts; ++i)\n      {\n        VectorT p = PointTraitsN<FromT, 3, ScalarT>::getPosition(from[i]);\n        VectorT const & q = to[i];\n\n        if (from_weight_func)\n        {\n          ScalarT weight = (ScalarT)from_weight_func->getTranslationWeight(from[i]);\n          p_mean += weight * p;\n          q_mean += weight * q;\n          sum_weights += weight;\n        }\n        else\n        {\n          p_mean += p;\n          q_mean += q;\n          sum_weights += 1;\n        }\n      }\n\n      p_mean /= sum_weights;\n      q_mean /= sum_weights;\n\n      ScalarT err = (tr * p_mean - q_mean).squaredNorm();\n\n      for (intx i = 0; i < num_pts; ++i)\n      {\n        VectorT p = PointTraitsN<FromT, 3, ScalarT>::getPosition(from[i]);\n        VectorT q = to[i];\n\n        VectorT dp = p - p_mean;\n        VectorT dq = q - q_mean;\n        if (from_weight_func)\n        {\n          ScalarT weight = (ScalarT)from_weight_func->getRotationWeight(from[i]);\n          err += weight * weight * (tr.getLinear() * dp - dq).squaredNorm();\n        }\n        else\n          err += (tr.getLinear() * dp - dq).squaredNorm();\n      }\n\n      return err;\n    }\n\n    double fractional_error_threshold;  ///< Maximum fractional change in error to determine convergence.\n    intx min_iterations;  ///< Minimum number of iterations.\n    intx max_iterations;  ///< Maximum number of iterations.\n    bool has_up;\n    VectorT up;\n    bool verbose;  ///< Print lots of debugging information?\n\n}; // class Icp3\n\n} // namespace Algorithms\n} // namespace Thea\n\n#endif\n", "meta": {"hexsha": "241447a434454775a865d680b6338c9357e97c82", "size": 19601, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Code/Source/Algorithms/Icp3.hpp", "max_stars_repo_name": "sidch/Thea", "max_stars_repo_head_hexsha": "d5ea3e3f1bd7389255cfabf1d55a6fe88c3c7db7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 77.0, "max_stars_repo_stars_event_min_datetime": "2016-11-06T17:25:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T16:30:34.000Z", "max_issues_repo_path": "Code/Source/Algorithms/Icp3.hpp", "max_issues_repo_name": "sidch/Thea", "max_issues_repo_head_hexsha": "d5ea3e3f1bd7389255cfabf1d55a6fe88c3c7db7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-04-22T16:47:04.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-22T16:47:04.000Z", "max_forks_repo_path": "Code/Source/Algorithms/Icp3.hpp", "max_forks_repo_name": "sidch/Thea", "max_forks_repo_head_hexsha": "d5ea3e3f1bd7389255cfabf1d55a6fe88c3c7db7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 20.0, "max_forks_repo_forks_event_min_datetime": "2015-10-17T20:38:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T09:56:27.000Z", "avg_line_length": 40.9206680585, "max_line_length": 129, "alphanum_fraction": 0.6166011938, "num_tokens": 4702, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4760129654308149}}
{"text": "#include \"opttmp/vectorization/register_tiling.hpp\"\n\n#include <cassert>\n\n#include <boost/align/aligned_allocator.hpp>\nusing boost::alignment::aligned_allocator;\n\n#include <Vc/Vc>\nusing Vc::double_v;\nconstexpr size_t total_width = 16;\nconstexpr size_t blocking = total_width / double_v::size();\n\nusing namespace opttmp::vectorization;\n\nconstexpr size_t array_length = 8192 * 2 * 2 * 2;\nconstexpr size_t iterations = array_length / total_width;\n\nint main(void) {\n  std::vector<double, aligned_allocator<double, 32>> A(array_length);\n  std::vector<double, aligned_allocator<double, 32>> B(array_length);\n  for (size_t i = 0; i < array_length; i++) {\n    A[i] = static_cast<double>(i);\n  }\n  for (size_t i = 0; i < array_length; i++) {\n    B[i] = static_cast<double>(i);\n  }\n\n  using reg_array = register_array<double_v, blocking>;\n  reg_array r = 0.0;\n  for (size_t i = 0; i < iterations; i++) {\n    reg_array a_reg(A.data() + i * total_width, Vc::flags::vector_aligned);\n    reg_array b_reg(B.data() + i * total_width, Vc::flags::vector_aligned);\n    r += a_reg * b_reg;\n  }\n  for (size_t i = 0; i < r.size(); i++) {\n    std::cout << \"r[\" << i << \"]: \" << r[i] << std::endl;\n  }\n}\n\n  // reg_array a(data_up.data(), Vc::flags::vector_aligned);\n  // reg_array b = 2.0;\n  // reg_array c = 3.141;\n\t  // for (size_t i = 0; i < 1000000; i++) {\n  //   // r += c * (a - b);\n  //   r = c * (r - a);\n  // }\n", "meta": {"hexsha": "54ec17b7965eb403709c5ad1b3b594d55e3e8d8d", "size": 1395, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/register_blocking_minimal.cpp", "max_stars_repo_name": "DavidPfander-UniStuttgart/AutoTuneTMP", "max_stars_repo_head_hexsha": "f5fb836778b04c2ab0fbcc4d36c466e577e96e65", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-11-06T15:02:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-14T20:25:50.000Z", "max_issues_repo_path": "examples/register_blocking_minimal.cpp", "max_issues_repo_name": "DavidPfander-UniStuttgart/AutoTuneTMP", "max_issues_repo_head_hexsha": "f5fb836778b04c2ab0fbcc4d36c466e577e96e65", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-01-25T21:25:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-14T17:35:27.000Z", "max_forks_repo_path": "examples/register_blocking_minimal.cpp", "max_forks_repo_name": "DavidPfander-UniStuttgart/AutoTuneTMP", "max_forks_repo_head_hexsha": "f5fb836778b04c2ab0fbcc4d36c466e577e96e65", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-15T11:05:43.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-15T11:05:43.000Z", "avg_line_length": 29.6808510638, "max_line_length": 75, "alphanum_fraction": 0.6301075269, "num_tokens": 434, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645723, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.47601296543081484}}
{"text": "//\n// Copyright (c) 2020 INRIA\n//\n\n#ifndef __pinocchio_math_mutliprecision_mpfr_hpp__\n#define __pinocchio_math_mutliprecision_mpfr_hpp__\n\n#include \"pinocchio/math/multiprecision.hpp\"\n#include \"pinocchio/math/sincos.hpp\"\n\n#include <boost/serialization/nvp.hpp>\n#include <boost/multiprecision/mpfr.hpp>\n\nnamespace pinocchio\n{\ntemplate <\n    unsigned S_digits10, boost::multiprecision::mpfr_allocation_type S_alloc,\n    boost::multiprecision::expression_template_option S_et, unsigned C_digits10,\n    boost::multiprecision::mpfr_allocation_type C_alloc,\n    boost::multiprecision::expression_template_option C_et, unsigned X_digits10,\n    boost::multiprecision::mpfr_allocation_type X_alloc,\n    boost::multiprecision::expression_template_option X_et>\nstruct SINCOSAlgo<\n    boost::multiprecision::number<\n        boost::multiprecision::mpfr_float_backend<X_digits10, X_alloc>, X_et>,\n    boost::multiprecision::number<\n        boost::multiprecision::mpfr_float_backend<S_digits10, S_alloc>, S_et>,\n    boost::multiprecision::number<\n        boost::multiprecision::mpfr_float_backend<C_digits10, C_alloc>, C_et>>\n{\n  static void run(\n      boost::multiprecision::number<\n          boost::multiprecision::mpfr_float_backend<X_digits10, X_alloc>,\n          X_et> const& a,\n      boost::multiprecision::number<\n          boost::multiprecision::mpfr_float_backend<S_digits10, S_alloc>, S_et>*\n          sa,\n      boost::multiprecision::number<\n          boost::multiprecision::mpfr_float_backend<C_digits10, C_alloc>, C_et>*\n          ca)\n  {\n    mpfr_srcptr x_mpfr((a.backend().data()));\n    mpfr_ptr s_mpfr(sa->backend().data());\n    mpfr_ptr c_mpfr(ca->backend().data());\n    mpfr_sin_cos(s_mpfr, c_mpfr, x_mpfr, MPFR_RNDN);\n  }\n};\n}  // namespace pinocchio\n\n#endif  // ifndef __pinocchio_math_mutliprecision_hpp__\n", "meta": {"hexsha": "001343ddb9ff840027e7485f276a49194e752797", "size": 1811, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/math/multiprecision-mpfr.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/math/multiprecision-mpfr.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/math/multiprecision-mpfr.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": 35.5098039216, "max_line_length": 80, "alphanum_fraction": 0.7371617891, "num_tokens": 458, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4760129595606964}}
{"text": "// -----------------------------------------------------------------------\r\n// RTToolbox - DKFZ radiotherapy quantitative evaluation library\r\n//\r\n// Copyright (c) German Cancer Research Center (DKFZ),\r\n// Software development for Integrated Diagnostics and Therapy (SIDT).\r\n// ALL RIGHTS RESERVED.\r\n// See rttbCopyright.txt or\r\n// http://www.dkfz.de/en/sidt/projects/rttb/copyright.html\r\n//\r\n// This software is distributed WITHOUT ANY WARRANTY; without even\r\n// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\r\n// PURPOSE.  See the above copyright notices for more information.\r\n//\r\n//------------------------------------------------------------------------\r\n\r\n#define _USE_MATH_DEFINES\r\n#include <cmath>\r\n\r\n#include <exception>\r\n#include <map>\r\n\r\n#include <boost/make_shared.hpp>\r\n#include <boost/shared_ptr.hpp>\r\n\r\n#include \"rttbTCPLQModel.h\"\r\n#include \"rttbDvhBasedModels.h\"\r\n#include \"rttbIntegration.h\"\r\n#include \"rttbInvalidParameterException.h\"\r\n#include \"rttbExceptionMacros.h\"\r\n\r\nnamespace rttb\r\n{\r\n\r\n\tnamespace models\r\n\t{\r\n\r\n\t\tTCPLQModel::TCPLQModel(): TCPModel() {\r\n\t\t\t_name = \"TCPLQModel\";\r\n\t\t\tfillParameterMap();\r\n\t\t}\r\n\r\n\t\tTCPLQModel::TCPLQModel(DVHPointer aDVH, BioModelParamType aAlphaMean, BioModelParamType aBeta,\r\n\t\t                       BioModelParamType aRho,\r\n\t\t                       int aNumberOfFractions): TCPModel(aDVH, aNumberOfFractions), _alphaMean(aAlphaMean),\r\n\t\t\t_alphaVariance(0),\r\n\t\t\t_alpha_beta(aAlphaMean / aBeta), _rho(aRho)  {\r\n\t\t\t_name = \"TCPLQModel\";\r\n\t\t\tfillParameterMap();\r\n\t\t}\r\n\r\n\r\n\t\tTCPLQModel::TCPLQModel(DVHPointer aDVH, BioModelParamType aRho, int aNumberOfFractions,\r\n\t\t                       BioModelParamType aAlpha_Beta,\r\n\t\t                       BioModelParamType aAlphaMean, BioModelParamType aAlphaVariance): TCPModel(aDVH, aNumberOfFractions),\r\n\t\t\t_alphaMean(aAlphaMean),\r\n\t\t\t_alphaVariance(aAlphaVariance), _alpha_beta(aAlpha_Beta), _rho(aRho) {\r\n\t\t\tfillParameterMap();\r\n\t\t\t_name = \"TCPLQModel\";\r\n\t\t}\r\n\r\n\t\tvoid TCPLQModel::setParameters(const BioModelParamType aAlphaMean,\r\n\t\t                               const BioModelParamType aAlpha_Beta,\r\n\t\t                               const BioModelParamType aRho, const BioModelParamType aAlphaVariance)\r\n\t\t{\r\n\t\t\t_alphaMean = aAlphaMean;\r\n\t\t\t_alphaVariance = aAlphaVariance;\r\n\t\t\t_alpha_beta = aAlpha_Beta;\r\n\t\t\t_rho = aRho;\r\n\r\n\t\t\t//reset _value, because parameters have changed.\r\n\t\t\t_value = 0;\r\n\t\t}\r\n\r\n\t\tvoid TCPLQModel::setAlpha(const BioModelParamType aAlphaMean,\r\n\t\t                          const BioModelParamType aAlphaVariance)\r\n\t\t{\r\n\t\t\t_alphaVariance = aAlphaVariance;\r\n\t\t\t_alphaMean = aAlphaMean;\r\n\t\t}\r\n\r\n\t\tvoid TCPLQModel::setAlphaBeta(const BioModelParamType aAlpha_Beta)\r\n\t\t{\r\n\t\t\t_alpha_beta = aAlpha_Beta;\r\n\t\t}\r\n\r\n\t\tvoid TCPLQModel::setRho(const BioModelParamType aRho)\r\n\t\t{\r\n\t\t\t_rho = aRho;\r\n\t\t}\r\n\r\n\t\tconst BioModelParamType TCPLQModel::getAlphaBeta()\r\n\t\t{\r\n\t\t\treturn _alpha_beta;\r\n\t\t}\r\n\r\n\t\tconst BioModelParamType TCPLQModel::getAlphaMean()\r\n\t\t{\r\n\t\t\treturn _alphaMean;\r\n\t\t}\r\n\r\n\t\tconst BioModelParamType TCPLQModel::getAlphaVariance()\r\n\t\t{\r\n\t\t\treturn _alphaVariance;\r\n\t\t}\r\n\r\n\t\tconst BioModelParamType TCPLQModel::getRho()\r\n\t\t{\r\n\t\t\treturn _rho;\r\n\t\t}\r\n\r\n\t\tlong double TCPLQModel::calcTCPi(BioModelParamType aRho, BioModelParamType aAlphaMean, double vj,\r\n\t\t                                 double bedj)\r\n\t\t{\r\n\t\t\treturn exp(-aRho * vj * exp(-aAlphaMean * bedj));\r\n\t\t}\r\n\r\n\t\tlong double TCPLQModel::calcTCP(std::map<rttb::DoseTypeGy, rttb::DoseCalcType> aBEDDVH,\r\n\t\t                                BioModelParamType aRho,\r\n\t\t                                BioModelParamType aAlphaMean, double aDeltaV)\r\n\t\t{\r\n\t\t\tstd::map<rttb::DoseTypeGy, rttb::DoseCalcType>::iterator it;\r\n\t\t\tlong double tcp = 1;\r\n\r\n\t\t\tfor (it = aBEDDVH.begin(); it != aBEDDVH.end(); ++it)\r\n\t\t\t{\r\n\t\t\t\tlong double tcpi = this->calcTCPi(aRho, aAlphaMean, (*it).second * aDeltaV, (*it).first);\r\n\t\t\t\ttcp = tcp * tcpi;\r\n\t\t\t}\r\n\r\n\t\t\treturn tcp;\r\n\t\t}\r\n\r\n\t\tlong double TCPLQModel::calcTCPAlphaNormalDistribution(\r\n\t\t    std::map<rttb::DoseTypeGy, rttb::DoseCalcType> aBEDDVH,\r\n\t\t    BioModelParamType aRho, BioModelParamType aAlphaMean,\r\n\t\t    BioModelParamType aAlphaVariance, double aDeltaV)\r\n\t\t{\r\n\r\n\t\t\tstd::map<rttb::DoseTypeGy, rttb::DoseCalcType>::iterator it;\r\n\t\t\tstd::vector<DoseCalcType> volumeV2;\r\n\t\t\tstd::vector<DoseTypeGy> bedV2;\r\n\t\t\tint i = 0;\r\n\r\n\t\t\tfor (it = aBEDDVH.begin(); it != aBEDDVH.end(); ++it)\r\n\t\t\t{\r\n\t\t\t\tvolumeV2.push_back((*it).second * aDeltaV);\r\n\t\t\t\tbedV2.push_back((*it).first);\r\n\t\t\t\ti++;\r\n\t\t\t}\r\n\r\n\t\t\tstruct TcpParams params = {aAlphaMean, aAlphaVariance, aRho, volumeV2, bedV2};\r\n\r\n\t\t\tdouble result = integrateTCP(0, params);\r\n\r\n\t\t\tif (result == -100)\r\n\t\t\t{\r\n\t\t\t\tstd::cerr << \"Integration error!\\n\";\r\n\t\t\t\treturn -1;\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tlong double tcp = 1 / (pow(2 * M_PI, 0.5) * _alphaVariance) * result;\r\n\r\n\t\t\t\treturn tcp;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tBioModelValueType TCPLQModel::calcModel(const double doseFactor)\r\n\t\t{\r\n\t\t\tcore::DVH variantDVH = core::DVH(_dvh->getDataDifferential(),\r\n\t\t\t                                 (DoseTypeGy)(_dvh->getDeltaD() * doseFactor),\r\n\t\t\t                                 _dvh->getDeltaV(), \"temporary\", \"temporary\");\r\n\t\t\tauto spDVH = boost::make_shared<core::DVH>(variantDVH);\r\n\r\n\t\t\tBioModelValueType value = 0;\r\n\r\n\t\t\tif (_alphaVariance == 0)\r\n\t\t\t{\r\n\t\t\t\tif (_alphaMean <= 0 || _alpha_beta <= 0 || _rho <= 0)\r\n\t\t\t\t{\r\n\t\t\t\t\tthrow core::InvalidParameterException(\"Parameter invalid: alpha, alpha/beta, rho and number of fractions must >0!\");\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (_numberOfFractions <= 1)\r\n\t\t\t\t{\r\n\t\t\t\t\tthrow core::InvalidParameterException(\"Parameter invalid: numberOfFractions must be >1! The dvh should be an accumulated-dvh of all fractions, not a single fraction-dvh!\");\r\n\t\t\t\t}\r\n\r\n\t\t\t\tstd::map<rttb::DoseTypeGy, rttb::DoseCalcType> dataBED = calcBEDDVH(spDVH, _numberOfFractions,\r\n\t\t\t\t        _alpha_beta);\r\n\r\n\t\t\t\tvalue = (BioModelValueType)this->calcTCP(dataBED, _rho, _alphaMean, variantDVH.getDeltaV());\r\n\t\t\t\treturn value;\r\n\t\t\t}\r\n\r\n\t\t\t//if alpha normal distribution\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tif (this->_alpha_beta <= 0 || this->_alphaMean <= 0 || this->_alphaVariance < 0 || _rho <= 0)\r\n\t\t\t\t{\r\n\t\t\t\t\tthrow core::InvalidParameterException(\"Parameter invalid: alpha/beta, alphaMean, rho and number of fractions must >0!\");\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (_numberOfFractions <= 1)\r\n\t\t\t\t{\r\n\t\t\t\t\tthrow core::InvalidParameterException(\"Parameter invalid: numberOfFractions must be >1! The dvh should be an accumulated-dvh of all fractions, not a single fraction-dvh!\");\r\n\t\t\t\t}\r\n\r\n\t\t\t\tstd::map<rttb::DoseTypeGy, rttb::DoseCalcType> dataBED = calcBEDDVH(spDVH, _numberOfFractions,\r\n\t\t\t\t        _alpha_beta);\r\n\t\t\t\tvalue = (BioModelValueType)(this->calcTCPAlphaNormalDistribution(dataBED, _rho, _alphaMean,\r\n\t\t\t\t                            _alphaVariance,\r\n\t\t\t\t                            variantDVH.getDeltaV()));\r\n\t\t\t\treturn value;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tvoid TCPLQModel::setParameterVector(const ParamVectorType& aParameterVector)\r\n\t\t{\r\n\t\t\tif (aParameterVector.size() != 4)\r\n\t\t\t{\r\n\t\t\t\tthrow core::InvalidParameterException(\"Parameter invalid: aParameterVector.size must be 4! \");\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\t_alphaMean = aParameterVector.at(0);\r\n\t\t\t\t_alphaVariance = aParameterVector.at(1);\r\n\t\t\t\t_alpha_beta = aParameterVector.at(2);\r\n\t\t\t\t_rho = aParameterVector.at(3);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tvoid TCPLQModel::setParameterByID(const int aParamId, const BioModelParamType aValue)\r\n\t\t{\r\n\t\t\tif (aParamId == 0)\r\n\t\t\t{\r\n\t\t\t\t_alphaMean = aValue;\r\n\t\t\t}\r\n\t\t\telse if (aParamId == 1)\r\n\t\t\t{\r\n\t\t\t\t_alphaVariance = aValue;\r\n\t\t\t}\r\n\t\t\telse if (aParamId == 2)\r\n\t\t\t{\r\n\t\t\t\t_alpha_beta = aValue;\r\n\t\t\t}\r\n\t\t\telse if (aParamId == 3)\r\n\t\t\t{\r\n\t\t\t\t_rho = aValue;\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tthrow core::InvalidParameterException(\"Parameter invalid: aParamID must be 0(alphaMean) or 1(alphaVariance) or 2(alpha_beta) or 3(rho)! \");\r\n\t\t\t}\r\n\r\n\t\t}\r\n\r\n\t\tconst int TCPLQModel::getParameterID(const std::string& aParamName) const\r\n\t\t{\r\n\t\t\tif (aParamName == \"alphaMean\")\r\n\t\t\t{\r\n\t\t\t\treturn 0;\r\n\t\t\t}\r\n\t\t\telse if (aParamName == \"alphaVariance\")\r\n\t\t\t{\r\n\t\t\t\treturn 1;\r\n\t\t\t}\r\n\t\t\telse if (aParamName == \"alpha_beta\")\r\n\t\t\t{\r\n\t\t\t\treturn 2;\r\n\t\t\t}\r\n\t\t\telse if (aParamName == \"rho\")\r\n\t\t\t{\r\n\t\t\t\treturn 3;\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\trttbExceptionMacro(core::InvalidParameterException,\r\n\t\t\t\t                   << \"Parameter name \" << aParamName <<\r\n\t\t\t\t                   \" invalid: it should be alphaMean or alphaVariance or alpha_beta or rho!\");\r\n\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tstd::map<std::string, double> TCPLQModel::getParameterMap() const{\r\n\t\t\treturn parameterMap;\r\n\t\t}\r\n\r\n\t\tvoid TCPLQModel::fillParameterMap(){\r\n\t\t\tparameterMap[\"numberOfFraction\"] = getNumberOfFractions();\r\n\t\t\tparameterMap[\"alphaMean\"] = getAlphaMean();\r\n\t\t\tparameterMap[\"alphaVariance\"] = getAlphaVariance();\r\n\t\t\tparameterMap[\"alpha_beta\"] = getAlphaBeta();\r\n\t\t\tparameterMap[\"rho\"] = getRho();\r\n\t\t}\r\n\r\n\t\tstd::string TCPLQModel::getModelType() const{\r\n\t\t\treturn _name;\r\n\t\t}\r\n\r\n\t}//end namespace models\r\n}//end namespace rttb\r\n\r\n\r\n", "meta": {"hexsha": "9651baa1e29dc1b5117c771c8f90169892e30661", "size": 8944, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/models/rttbTCPLQModel.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/models/rttbTCPLQModel.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/models/rttbTCPLQModel.cpp", "max_forks_repo_name": "MIC-DKFZ/RTTB", "max_forks_repo_head_hexsha": "8b772501fd3fffcb67233a9307661b03dff72785", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2018-06-24T21:09:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-09T09:30:49.000Z", "avg_line_length": 29.3245901639, "max_line_length": 178, "alphanum_fraction": 0.6248881932, "num_tokens": 2533, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4760129595606964}}
{"text": "// Boost.Geometry Index\n// Unit Test\n\n// Copyright (c) 2011-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#include <geometry_index_test_common.hpp>\n\n#include <boost/geometry/index/detail/algorithms/path_intersection.hpp>\n\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/point.hpp>\n#include <boost/geometry/geometries/box.hpp>\n#include <boost/geometry/geometries/linestring.hpp>\n#include <boost/geometry/geometries/segment.hpp>\n\n//#include <boost/geometry/io/wkt/read.hpp>\n\ntemplate <typename Box, typename Linestring>\nvoid test_path_intersection(Box const& box, Linestring const& path,\n                            bool expected_result,\n                            typename bg::default_length_result<Linestring>::type expected_dist)\n{\n    typename bgi::detail::default_path_intersection_distance_type<Box, Linestring>::type dist;\n\n    bool value = bgi::detail::path_intersection(box, path, dist);\n    BOOST_CHECK(value == expected_result);\n    if ( value && expected_result )\n        BOOST_CHECK_CLOSE(dist, expected_dist, 0.0001);\n\n    if ( ::boost::size(path) == 2 )\n    {\n        typedef typename ::boost::range_value<Linestring>::type P;\n        typedef bg::model::segment<P> Seg;\n        typename bgi::detail::default_path_intersection_distance_type<Box, Seg>::type dist;\n        Seg seg(*::boost::begin(path), *(::boost::begin(path)+1));\n        bool value = bgi::detail::path_intersection(box, seg, dist);\n        BOOST_CHECK(value == expected_result);\n        if ( value && expected_result )\n            BOOST_CHECK_CLOSE(dist, expected_dist, 0.0001);\n    }\n}\n\ntemplate <typename Box, typename Linestring>\nvoid test_geometry(std::string const& wkt_g, std::string const& wkt_path,\n                   bool expected_result,\n                   typename bg::default_length_result<Linestring>::type expected_dist)\n{\n    Box box;\n    bg::read_wkt(wkt_g, box);\n    Linestring path;\n    bg::read_wkt(wkt_path, path);\n    test_path_intersection(box, path, expected_result, expected_dist);\n}\n\nvoid test_large_integers()\n{\n    typedef bg::model::point<int, 2, bg::cs::cartesian> int_point_type;\n    typedef bg::model::point<double, 2, bg::cs::cartesian> double_point_type;\n\n    bg::model::box<int_point_type> int_box;\n    bg::model::box<double_point_type> double_box;\n    typedef bg::model::linestring<int_point_type> IP;\n    IP int_path;\n    typedef bg::model::linestring<double_point_type> DP;\n    DP double_path;\n\n    std::string const str_box = \"POLYGON((1536119 192000, 1872000 528000))\";\n    std::string const str_path = \"LINESTRING(1535000 191000, 1873000 191000, 1873000 300000, 1536119 300000)\";\n    bg::read_wkt(str_box, int_box);\n    bg::read_wkt(str_box, double_box);\n    bg::read_wkt(str_path, int_path);\n    bg::read_wkt(str_path, double_path);\n\n    bg::default_length_result<IP>::type int_value;\n    bool int_result = bgi::detail::path_intersection(int_box, int_path, int_value);\n    bg::default_length_result<DP>::type double_value;\n    bool double_result = bgi::detail::path_intersection(double_box, double_path, double_value);\n\n    BOOST_CHECK(int_result == double_result);\n    if ( int_result && double_result )\n        BOOST_CHECK_CLOSE(int_value, double_value, 0.0001);\n}\n\nint test_main(int, char* [])\n{\n    typedef bg::model::point<int, 2, bg::cs::cartesian> P2ic;\n    typedef bg::model::point<float, 2, bg::cs::cartesian> P2fc;\n    typedef bg::model::point<double, 2, bg::cs::cartesian> P2dc;\n\n    typedef bg::model::point<int, 3, bg::cs::cartesian> P3ic;\n    typedef bg::model::point<float, 3, bg::cs::cartesian> P3fc;\n    typedef bg::model::point<double, 3, bg::cs::cartesian> P3dc;\n\n    typedef bg::model::linestring<P2ic> L2ic;\n    typedef bg::model::linestring<P2fc> L2fc;\n    typedef bg::model::linestring<P2dc> L2dc;\n\n    typedef bg::model::linestring<P3ic> L3ic;\n    typedef bg::model::linestring<P3fc> L3fc;\n    typedef bg::model::linestring<P3dc> L3dc;\n    \n    // IMPORTANT! For 2-point linestrings comparable distance optimization is enabled!\n\n    test_geometry<bg::model::box<P2ic>, L2ic>(\"POLYGON((0 1,2 4))\", \"LINESTRING(0 0, 2 5)\", true, 1.0f/5);\n    test_geometry<bg::model::box<P2fc>, L2fc>(\"POLYGON((0 1,2 4))\", \"LINESTRING(0 0, 2 5)\", true, 1.0f/5);\n    test_geometry<bg::model::box<P2dc>, L2dc>(\"POLYGON((0 1,2 4))\", \"LINESTRING(0 0, 2 5)\", true, 1.0/5);\n    test_geometry<bg::model::box<P3ic>, L3ic>(\"POLYGON((0 1 2,2 4 6))\", \"LINESTRING(0 0 0, 2 5 7)\", true, 2.0f/7);\n    test_geometry<bg::model::box<P3fc>, L3fc>(\"POLYGON((0 1 2,2 4 6))\", \"LINESTRING(0 0 0, 2 5 7)\", true, 2.0f/7);\n    test_geometry<bg::model::box<P3dc>, L3dc>(\"POLYGON((0 1 2,2 4 6))\", \"LINESTRING(0 0 0, 2 5 7)\", true, 2.0/7);\n\n    test_geometry<bg::model::box<P2fc>, L2fc>(\"POLYGON((0 1,2 4))\", \"LINESTRING(0 0, 1 0, 1 5)\", true, 2);\n    test_geometry<bg::model::box<P2fc>, L2fc>(\"POLYGON((0 1,2 4))\", \"LINESTRING(0 0, 3 0, 3 2, 0 2)\", true, 6);\n    test_geometry<bg::model::box<P2fc>, L2fc>(\"POLYGON((0 1,2 4))\", \"LINESTRING(1 2, 3 3, 0 3)\", true, 0);\n    \n    test_large_integers();\n\n    return 0;\n}\n", "meta": {"hexsha": "9c4901ee8c61a39231888a1171966a8785064a51", "size": 5231, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "index/test/algorithms/path_intersection.cpp", "max_stars_repo_name": "jkerkela/geometry", "max_stars_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 326.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T13:47:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T02:13:59.000Z", "max_issues_repo_path": "index/test/algorithms/path_intersection.cpp", "max_issues_repo_name": "jkerkela/geometry", "max_issues_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 623.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T23:45:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T11:15:23.000Z", "max_forks_repo_path": "Libs/boost_1_76_0/libs/geometry/index/test/algorithms/path_intersection.cpp", "max_forks_repo_name": "Antd23rus/S2DE", "max_forks_repo_head_hexsha": "47cc7151c2934cd8f0399a9856c1e54894571553", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-01-14T15:50:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T03:58:36.000Z", "avg_line_length": 42.5284552846, "max_line_length": 114, "alphanum_fraction": 0.6784553623, "num_tokens": 1624, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.47601295956069634}}
{"text": "/********************************************************************************\n*  This file is part of CinoLib                                                 *\n*  Copyright(C) 2016: Marco Livesu                                              *\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*                                                                               *\n*     Marco Livesu (marco.livesu@gmail.com)                                     *\n*     http://pers.ge.imati.cnr.it/livesu/                                       *\n*                                                                               *\n*     Daniela Cabiddu                                                           *\n*     http://www.imati.cnr.it/index.php/people/8-curricula/119-daniela-cabiddu  *\n*                                                                               *\n*     Italian National Research Council (CNR)                                   *\n*     Institute for Applied Mathematics and Information Technologies (IMATI)    *\n*     Via de Marini, 6                                                          *\n*     16149 Genoa,                                                              *\n*     Italy                                                                     *\n*********************************************************************************/\n#include <cinolib/polygon_maximum_inscribed_circle.h>\n#include <cinolib/geometry/segment.h>\n#include <cinolib/min_max_inf.h>\n\n// Most of this is coming from here:\n// http://www.boost.org/doc/libs/1_65_1/libs/polygon/doc/voronoi_diagram.htm\n// http://www.boost.org/doc/libs/1_65_0/libs/polygon/example/voronoi_basic_tutorial.cpp\n//\n#ifdef CINOLIB_USES_BOOST\n#include <boost/geometry/geometries/polygon.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry.hpp>\n#include <boost/polygon/voronoi.hpp>\n//\nusing boost::polygon::voronoi_builder;\nusing boost::polygon::voronoi_diagram;\nusing boost::polygon::voronoi_edge;\nusing boost::polygon::x;\nusing boost::polygon::y;\nusing boost::polygon::low;\nusing boost::polygon::high;\n//\nstruct polygon_point\n{\n    int x;\n    int y;\n    polygon_point(int x, int y) : x(x), y(y) {}\n};\n//\nstruct polygon_segment\n{\n    polygon_point p0;\n    polygon_point p1;\n    polygon_segment(int x1, int y1, int x2, int y2) : p0(x1, y1), p1(x2, y2) {}\n};\n//\ntemplate<>\nstruct boost::polygon::geometry_concept<polygon_point>\n{\n    typedef boost::polygon::point_concept type;\n};\n//\ntemplate<>\nstruct boost::polygon::point_traits<polygon_point>\n{\n    typedef int coordinate_type;\n    static inline coordinate_type get(const polygon_point & point, orientation_2d orient)\n    {\n        return (orient == HORIZONTAL) ? point.x : point.y;\n    }\n};\n//\ntemplate<>\nstruct boost::polygon::geometry_concept<polygon_segment>\n{\n    typedef boost::polygon::segment_concept type;\n};\n//\ntemplate<>\nstruct boost::polygon::segment_traits<polygon_segment>\n{\n    typedef int coordinate_type;\n    typedef polygon_point point_type;\n\n    static inline point_type get(const polygon_segment& segment, direction_1d dir)\n    {\n        return dir.to_int() ? segment.p1 : segment.p0;\n    }\n};\n//\ntypedef boost::geometry::model::d2::point_xy<double> BoostPoint;\ntypedef boost::geometry::model::polygon<BoostPoint>  BoostPolygon;\n\n#endif // CINOLIB_USES_BOOST\n", "meta": {"hexsha": "ffa5438fbf48f24ab2ad74fbb8b10dd0b360606b", "size": 5089, "ext": "tpp", "lang": "C++", "max_stars_repo_path": "include/cinolib/polygon_maximum_inscribed_circle.tpp", "max_stars_repo_name": "francescozoccheddu/cinolib", "max_stars_repo_head_hexsha": "6d6f7d359db673aca1c203a208f50e0a7a362b76", "max_stars_repo_licenses": ["MIT"], "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/cinolib/polygon_maximum_inscribed_circle.tpp", "max_issues_repo_name": "francescozoccheddu/cinolib", "max_issues_repo_head_hexsha": "6d6f7d359db673aca1c203a208f50e0a7a362b76", "max_issues_repo_licenses": ["MIT"], "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/cinolib/polygon_maximum_inscribed_circle.tpp", "max_forks_repo_name": "francescozoccheddu/cinolib", "max_forks_repo_head_hexsha": "6d6f7d359db673aca1c203a208f50e0a7a362b76", "max_forks_repo_licenses": ["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.0353982301, "max_line_length": 89, "alphanum_fraction": 0.5081548438, "num_tokens": 962, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.47601295956069634}}
{"text": "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n//\n// gDLS*: Generalized Pose-and-Scale Estimation Given Scale and Gravity Priors\n//\n// Victor Fragoso, Joseph DeGol, Gang Hua.\n// Proc. of the IEEE/CVF Conf. on Computer Vision and Pattern Recognition 2020.\n//\n// Please contact the author of this library if you have any questions.\n// Author: Victor Fragoso (victor.fragoso@microsoft.com)\n\n#include <vector>\n\n#include <pybind11/pybind11.h>\n#include <pybind11/stl.h>\n#include <pybind11/eigen.h>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include \"gdls_star/pinhole_camera.h\"\n#include \"gdls_star/camera_feature_correspondence_2d_3d.h\"\n#include \"gdls_star/estimate_similarity_transformation.h\"\n#include \"gdls_star/gdls_star.h\"\n#include \"gdls_star/gdls_star_robust_estimator.h\"\n#include \"gdls_star/util.h\"\n\nnamespace py = pybind11;\n\nusing msft::PinholeCamera;\nusing msft::CameraFeatureCorrespondence2D3D;\nusing msft::GdlsStar;\nusing msft::GdlsStarRobustEstimator;\n\nstruct PySolution {\n  Eigen::Vector4d rotation = Eigen::Vector4d(1.0, 0.0, 0.0, 0.0);\n  Eigen::Vector3d translation = Eigen::Vector3d::Zero();\n  double scale = 1.0;\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n};\n\nstruct PyRansacSolution {\n  PySolution best_solution;\n  std::vector<int> inliers;\n};\n\nstd::vector<PySolution> EstimateSimilarityTransformation(\n    const GdlsStar::Priors& priors,\n    const std::vector<CameraFeatureCorrespondence2D3D>& correspondences) {\n  std::vector<PySolution> final_solutions;\n  GdlsStar::Solution solution;\n  // Compute input datum.\n  const GdlsStar::Input input = msft::ComputeInputDatum(correspondences);\n  GdlsStar estimator;\n  estimator.EstimateSimilarityTransformation(input, &solution);\n  final_solutions.resize(solution.rotations.size());\n  for (int i = 0; i < solution.rotations.size(); ++i) {\n    const Eigen::Quaterniond& rotation = solution.rotations[i];\n    final_solutions[i].rotation = Eigen::Vector4d(rotation.w(),\n                                                  rotation.x(),\n                                                  rotation.y(),\n                                                  rotation.z());\n    final_solutions[i].translation = solution.translations[i];\n    final_solutions[i].scale = solution.scales[i];\n  }\n  return final_solutions;\n}\n\n// Computes the similarity transformation given 2D-3D correspondences and priors\n// using a RANSAC estimator.\nPyRansacSolution EstimateSimilarityTransformationViaRansac(\n    const GdlsStarRobustEstimator::RansacParameters& params,\n    const GdlsStar::Priors& priors,\n    const std::vector<CameraFeatureCorrespondence2D3D>& correspondences) {\n  PyRansacSolution final_solution;\n  GdlsStarRobustEstimator::RansacSummary ransac_summary;\n  GdlsStarRobustEstimator estimator(params);\n  const GdlsStar::Solution solution =\n      estimator.Estimate(priors, correspondences, &ransac_summary);\n  const Eigen::Quaterniond& rotation = solution.rotations[0];\n  final_solution.best_solution.rotation = Eigen::Vector4d(rotation.w(),\n                                                          rotation.x(),\n                                                          rotation.y(),\n                                                          rotation.z());\n  final_solution.best_solution.translation = solution.translations[0];\n  final_solution.best_solution.scale = solution.scales[0];\n  final_solution.inliers = ransac_summary.inliers;\n  return final_solution;\n}\n\nPYBIND11_MODULE(pygdls_star, module) {\n  module.doc() = \"gDLS* Python module\"; // Optional module docstring.\n\n  // Ransac parameter class.\n  py::class_<GdlsStarRobustEstimator::RansacParameters>(module, \"RansacParams\")\n      .def(py::init<>())\n      .def_readwrite(\"failure_probability\",\n                     &GdlsStarRobustEstimator::RansacParameters::failure_probability)\n      .def_readwrite(\"reprojection_error_thresh\",\n                     &GdlsStarRobustEstimator::RansacParameters::reprojection_error_thresh)\n      .def_readwrite(\"min_iterations\",\n                     &GdlsStarRobustEstimator::RansacParameters::min_iterations)\n      .def_readwrite(\"max_iterations\",\n                     &GdlsStarRobustEstimator::RansacParameters::max_iterations);\n\n  // Ransac summary class.\n  py::class_<GdlsStarRobustEstimator::RansacSummary>(module, \"RansacSummary\")\n      .def(py::init<>())\n      .def_readwrite(\"inliers\",\n                     &GdlsStarRobustEstimator::RansacSummary::inliers)\n      .def_readwrite(\"num_iterations\",\n                     &GdlsStarRobustEstimator::RansacSummary::num_iterations)\n      .def_readwrite(\"confidence\",\n                     &GdlsStarRobustEstimator::RansacSummary::confidence)\n      .def_readwrite(\"num_hypotheses\",\n                     &GdlsStarRobustEstimator::RansacSummary::num_hypotheses);\n\n  // Pinhole camera.\n  py::class_<PinholeCamera>(module, \"PinholeCamera\")\n      .def(py::init<const double,\n                    const Eigen::Vector2d,\n                    const Eigen::Vector4d,\n                    const Eigen::Vector3d>(),\n           py::arg(\"focal_length\") = 1.0,\n           py::arg(\"principal_point\") = Eigen::Vector2d::Zero(),\n           py::arg(\"world_to_cam_rot\") = Eigen::Vector4d(1.0, 0.0, 0.0, 0.0),\n           py::arg(\"world_to_cam_trans\") = Eigen::Vector3d::Zero())\n      .def(\"project_point\", &PinholeCamera::ProjectPoint)\n      .def(\"pixel_to_unit_ray\", &PinholeCamera::PixelToUnitRay)\n      .def(\"get_position\", &PinholeCamera::GetPosition);\n\n  // CameraFeatureCorrespondence2D3D.\n  py::class_<CameraFeatureCorrespondence2D3D>(module,\n                                              \"CameraFeatureCorrespondence2D3D\")\n      .def(py::init<>())\n      .def_readwrite(\"camera\", &CameraFeatureCorrespondence2D3D::camera)\n      .def_readwrite(\"observation\",\n                     &CameraFeatureCorrespondence2D3D::observation)\n      .def_readwrite(\"point\", &CameraFeatureCorrespondence2D3D::point);\n\n  // Priors.\n  py::class_<GdlsStar::Priors>(module, \"Priors\")\n      .def(py::init<>())\n      .def_readwrite(\"world_down_direction\",\n                     &GdlsStar::Priors::world_down_direction)\n      .def_readwrite(\"query_down_direction\",\n                     &GdlsStar::Priors::query_down_direction)\n      .def_readwrite(\"scale_penalty\", &GdlsStar::Priors::scale_penalty)\n      .def_readwrite(\"scale_prior\", &GdlsStar::Priors::scale_prior)\n      .def_readwrite(\"gravity_penalty\", &GdlsStar::Priors::gravity_penalty);\n\n  // PySolution.\n  py::class_<PySolution>(module, \"Solution\")\n      .def(py::init<>())\n      .def_readwrite(\"rotation\", &PySolution::rotation)\n      .def_readwrite(\"translation\", &PySolution::translation)\n      .def_readwrite(\"scale\", &PySolution::scale);\n\n  // PyRansacSolution.\n  py::class_<PyRansacSolution>(module, \"RansacSolution\")\n      .def(py::init<>())\n      .def_readwrite(\"best_solution\", &PyRansacSolution::best_solution)\n      .def_readwrite(\"inliers\", &PyRansacSolution::inliers);\n\n  // Estimate similarity transformation using plain gDLS*.\n  module.def(\"estimate\", &EstimateSimilarityTransformation);\n  module.def(\"estimate_ransac\", &EstimateSimilarityTransformationViaRansac);\n}\n", "meta": {"hexsha": "6bb4712a307eb275ac49b3191b8a01fb423ecfcd", "size": 7106, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/python/pybind.cc", "max_stars_repo_name": "vfragoso/gdls_star", "max_stars_repo_head_hexsha": "38e2dbc9996ddf4618cbc679d41588594935c5f9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-05-06T18:09:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-09T08:40:06.000Z", "max_issues_repo_path": "src/python/pybind.cc", "max_issues_repo_name": "vfragoso/gdls_star", "max_issues_repo_head_hexsha": "38e2dbc9996ddf4618cbc679d41588594935c5f9", "max_issues_repo_licenses": ["MIT"], "max_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/pybind.cc", "max_forks_repo_name": "vfragoso/gdls_star", "max_forks_repo_head_hexsha": "38e2dbc9996ddf4618cbc679d41588594935c5f9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-10-29T19:25:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-10T11:39:45.000Z", "avg_line_length": 42.2976190476, "max_line_length": 91, "alphanum_fraction": 0.679144385, "num_tokens": 1810, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.47601295956069634}}
{"text": "/*\nCopyright 2020 Standard Cyborg\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#include \"standard_cyborg/math/Transform.hpp\"\n\n#include \"standard_cyborg/math/Mat3x4.hpp\"\n#include \"standard_cyborg/math/Mat3x3.hpp\"\n#include \"standard_cyborg/util/DataUtils.hpp\"\n\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Wdocumentation\"\n#ifndef DEBUG\n#define EIGEN_NO_DEBUG  1\n#endif\n#include <Eigen/Core>\n#include <Eigen/Cholesky>\n#pragma clang diagnostic pop\n\nnamespace standard_cyborg {\nnamespace math {\n\n// This function is derived from the transforms3d python package and specialized for 3x3 matrices.\n// You may find the original source of this function at:\n//     https://github.com/matthew-brett/transforms3d/blob/8f81b063686f9b892bdbd4775d02615dce028105/transforms3d/affines.py#L156-L246\n//\n// **********************\n// Copyright and Licenses\n// **********************\n//\n// Retrieved from https://github.com/matthew-brett/transforms3d/blob/master/LICENSE on Dec. 2, 2019\n//\n// Transforms3d\n// ============\n//\n// The transforms3d package, including all examples, code snippets and attached\n// documentation is covered by the 2-clause BSD license.\n//\n//    Copyright (c) 2009-2017, Matthew Brett and Christoph Gohlke\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 notice,\n//    this list of conditions and the following disclaimer.\n//\n//    2. Redistributions in binary form must reproduce the above copyright\n//    notice, this list of conditions and the following disclaimer in the\n//    documentation and/or other materials provided with the distribution.\n//\n//    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n//    IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n//    THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n//    PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\n//    CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n//    EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n//    PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n//    PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n//    LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n//    NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n//    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// 3rd party code and data\n// =======================\n//\n// Some code distributed within the transforms3d sources was developed by other\n// projects. This code is distributed under its respective licenses that are\n// listed below.\n//\n// Sphinx autosummary extension\n// ----------------------------\n//\n// This extension has been copied from NumPy (Jul 16, 2010) as the one shipped with\n// Sphinx 0.6 doesn't work properly.\n//\n// ::\n//\n//  Copyright (c) 2007-2009 Stefan van der Walt and Sphinx team\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//    a. Redistributions of source code must retain the above copyright notice,\n//       this list of conditions and the following disclaimer.\n//    b. 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//    c. Neither the name of the Enthought 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//\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 REGENTS 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\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 SUCH\n//  DAMAGE.\n\ntypedef Eigen::Matrix<float, 3, 3> EMat3;\ntypedef Eigen::Vector3f EVec3;\n\nTransform Transform::fromMat3x4(const math::Mat3x4& A) {\n    Transform transform;\n\n    // Start by extracting the translation. This part is very easy.\n    transform.translation = {A.m03, A.m13, A.m23};\n    \n    // R = rotation\n    // Z = zoom (scale)\n    // S = shear\n    EMat3 RZS;\n    RZS << A.m00, A.m01, A.m02,\n           A.m10, A.m11, A.m12,\n           A.m20, A.m21, A.m22;\n\n    // Use the Cholesky decomposition to perform the separation\n    // This part very closely mirrors the original implementation, only specialized for 3x3 matrices\n    EMat3 RZSt_RZS (RZS.transpose() * RZS);\n    Eigen::LLT<EMat3> cholesky;\n    cholesky.compute(RZSt_RZS);\n    EMat3 ZS (cholesky.matrixL().transpose());\n    EVec3 Z (ZS.diagonal());\n    EMat3 R (RZS * ZS.inverse());\n    \n    // Detect and fix if the rotation flips parity\n    if (R.determinant() < 0.0f) {\n        Z(0) = -Z(0);\n        ZS.row(0) = -ZS.row(0);\n        R = RZS * ZS.inverse();\n    }\n\n    // Extract the result into StandardCyborg data types\n    transform.scale = toVec3(Z);\n    \n    transform.shear = math::Vec3{\n        ZS(0, 1) / Z(0),\n        ZS(0, 2) / Z(0),\n        ZS(1, 2) / Z(1)\n    };\n    \n    transform.rotation = math::Quaternion::fromMat3x3(toMat3x3(R));\n    \n    return transform;\n}\n\nTransform Transform::fromMat3x4(const math::Mat3x4& A, std::string srcFrame, std::string destFrame) {\n  Transform t (Transform::fromMat3x4(A));\n  t.srcFrame = srcFrame;\n  t.destFrame = destFrame;\n  return t;\n}\n\nTransform Transform::inverse() const {\n  Mat3x4 m (Mat3x4::fromTransform(*this));\n  return Transform::fromMat3x4(m.invert(), destFrame, srcFrame);\n}\n\n\n} // namespace math\n} // namespace standard_cyborg\n", "meta": {"hexsha": "ac3142e91499b5e96614eddd12db159e4fcb4d52", "size": 6880, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "scsdk/c++/scsdk/standard_cyborg/math/Transform.cpp", "max_stars_repo_name": "StandardCyborg/scsdk", "max_stars_repo_head_hexsha": "92f80bf2a580ebaafa6b0d1052d90d5c8f6682f7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2020-11-26T01:07:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-14T07:45:19.000Z", "max_issues_repo_path": "scsdk/c++/scsdk/standard_cyborg/math/Transform.cpp", "max_issues_repo_name": "StandardCyborg/scsdk", "max_issues_repo_head_hexsha": "92f80bf2a580ebaafa6b0d1052d90d5c8f6682f7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scsdk/c++/scsdk/standard_cyborg/math/Transform.cpp", "max_forks_repo_name": "StandardCyborg/scsdk", "max_forks_repo_head_hexsha": "92f80bf2a580ebaafa6b0d1052d90d5c8f6682f7", "max_forks_repo_licenses": ["Apache-2.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.2222222222, "max_line_length": 132, "alphanum_fraction": 0.7095930233, "num_tokens": 1691, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059414036511, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4760129536905776}}
{"text": "#include <boost/random/binomial_distribution.hpp>\n", "meta": {"hexsha": "651e2fbf34b5075bdd2e3f1d821282a2a0bc87c4", "size": 50, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_random_binomial_distribution.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_random_binomial_distribution.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_random_binomial_distribution.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 25.0, "max_line_length": 49, "alphanum_fraction": 0.84, "num_tokens": 9, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105941403651, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.47601295369057756}}
{"text": "//\n//! Copyright \u00a9 2018\n//! Brandon Kohn\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#pragma once\n\n#include <geometrix/utility/utilities.hpp>\n#include <geometrix/primitive/point_traits.hpp>\n#include <boost/functional/hash.hpp>\n#include <unordered_map>\n\nnamespace geometrix {\n\n\ttemplate <typename Point, typename NumberComparisonPolicy>\n\tclass triangle_complex\n\t{\n\t\tstruct point_compare\n\t\t{\n\t\t\tpoint_compare(const NumberComparisonPolicy& cmp)\n\t\t\t\t: cmp(cmp)\n\t\t\t{}\n\n\t\t\tbool operator()(const Point& a, const Point& b) const\n\t\t\t{\n\t\t\t\treturn lexicographically_less_than(a, b, cmp);\n\t\t\t}\n\n\t\t\tNumberComparisonPolicy cmp;\n\t\t};\n\n\t\tusing vertex_handle = std::uint32_t;\n\t\tusing invalid_handle = std::integral_constant<vertex_handle, static_cast<vertex_handle>(-1)>;\n\t\tusing vertex_handle_map = std::map<Point, vertex_handle>;\n\t\tusing vertex_point_map = std::vector<Point>;\n\t\tusing edge_key = std::tuple<vertex_handle, vertex_handle>;\n\t\tusing trig_key = std::tuple<vertex_handle, vertex_handle, vertex_handle>;\n\n\t\tstruct half_edge\n\t\t{\n\t\t\thalf_edge(vertex_handle o = invalid_handle::value, bool constrained = false)\n\t\t\t\t: opposite(o)\n\t\t\t\t, constrained(constrained)\n\t\t\t{}\n\n\t\t\tvertex_handle opposite;\n\t\t\tbool constrained;\n\t\t};\n\n\t\tusing triangle_edge_opposite_vertex_map = std::unordered_map<edge_key, half_edge, boost::hash<edge_key>>;\n\t\tusing triangle_map = std::unordered_map<trig_key, std::array<Point, 3>, boost::hash<trig_key>>;\n\n\tpublic:\n\n\t\ttriangle_complex() = default;\n\t\ttriangle_complex(const NumberComparisonPolicy& cmp)\n\t\t\t: m_cmp(cmp)\n\t\t\t, m_vertexHandleMap(point_compare(cmp))\n\t\t{}\n\n\t\tbool add_triangle(Point a, Point b, Point c)\n\t\t{\n\t\t\tsort(a, b, c);\n\t\t\tauto key = get_triangle_key(a, b, c);\n\t\t\tvertex_handle u, v, w;\n\t\t\tstd::tie(u, v, w) = key;\n\t\t\treturn add_triangle(u, v, w);\n\t\t}\n\n\t\tbool set_constraint(const Point& a, const Point& b, bool c)\n\t\t{\n\t\t\tauto u = get_vertex_handle(a);\n\t\t\tauto v = get_vertex_handle(b);\n\t\t\tauto it = m_edgeVertexMap.find(edge_key(u, v));\n\t\t\tif (it != m_edgeVertexMap.end()) {\n\t\t\t\tit->second.constrained = c;\n\n\t\t\t\tit = m_edgeVertexMap.find(edge_key(v, u));\n\t\t\t\tif (it != m_edgeVertexMap.end()) {\n\t\t\t\t\tit->second.constrained = c;\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn false;\n\t\t}\n\n\t\ttemplate <typename EncroachSegmentPredicate, typename TrianglePredicate>\n\t\tvoid refine(const stk::units::angle& minAngle, EncroachSegmentPredicate&& is_encroached, TrianglePredicate&& is_bad)\n\t\t{\n\t\t\tauto badSegs = get_encroaching_segments(std::forward<EncroachSegmentPredicate>(is_encroached));\n\t\t\tsplit_encroaching_segments(badSegs);\n\n\t\t\tstd::deque<trig_key> badTrigs;\n\n\t\t\tfor(auto item : m_triangleMap)\n\t\t\t{\n\t\t\t\tif (is_bad(item.first, item.second))\n\t\t\t\t\tbadTrigs.emplace_back(item.first);\n\t\t\t}\n\t\t}\n\n\t\t/*\n        bool delete_triangle(Point a, Point b, Point c)\n        {\n            sort(a,b,c);\n            auto key = find_triangle_key(a, b, c);\n\n            if(is_valid(key))\n            {\n                vertex_handle u, v, w;\n                std::tie(u,v,w) = key;\n                delete_triangle(u, v, w);\n                return true;\n            }\n\n            return false;\n        }\n\t\t*/\n\n        void insert_vertex(const Point& p, Point a, Point b, Point c)\n        {\n            sort(a,b,c);\n            auto key = find_triangle_key(a, b, c);\n\n            GEOMETRIX_ASSERT(is_valid(key));\n            GEOMETRIX_ASSERT(point_in_circumcircle(p, a, b, c, m_cmp) == point_circle_orientation::inside);\n\n            vertex_handle u = get_vertex_handle(p), v, w, x;\n            std::tie(v,w,x) = key;\n            insert_vertex(u, v, w, x);\n        }\n\n    private:\n\n\t\ttemplate <typename EncroachSegmentPredicate>\n\t\tstd::deque<edge_key> get_encroaching_segments(EncroachSegmentPredicate&& is_encroached) const\n\t\t{\n\t\t\tstd::deque<edge_key> badSegs;\n\n\t\t\tfor (auto item : m_edgeVertexMap) \n\t\t\t{\n\t\t\t\tvertex_handle u, v;\n\t\t\t\tstd::tie(u, v) = item.first;\n\t\t\t\tauto w = item.second.opposite;\n\n\t\t\t\tif (is_encroached(m_points[w], m_points[u], m_points[v]))\n\t\t\t\t\tbadSegs.push_back(item.first);\n\t\t\t}\n\n\t\t\treturn std::move(badSegs);\n\t\t}\n\n\t\tbool in_diametral_circle(Point const& p, Point const& o, Point const& d)\n\t\t{\n\t\t\t//! If the angle between OP and DP is obtuse, then P is inside the diametral circle of OD.\n\t\t\t//! two vectors have obtuse angle if dot product is negative.\n\t\t\tauto dp = dot_product(o - p, d - p);\n\t\t\treturn dp < constants::zero<decltype(dp)>();\n\t\t}\n\n\t\t//bool in_diametral_lens(Angle const& theta, Point const& o, Point const& d, const Point& p)\n\t\tbool in_diametral_lens(Point const& p, Point const& o, Point const& d)\n\t\t{\n\t\t\t//static const stk::units::angle theta = 0.523599 * units::si::radians;\n\t\t\tconstexpr auto cos_theta = 0.86602529158;//cos(theta);\n\t\t\tconstexpr auto v2_cos_theta2_1 = 2.0 * cos_theta * cos_theta - 1.0;\n            constexpr auto e2 = v2_cos_theta2_1 * v2_cos_theta2_1;\n\t\t\t\n            stk::vector2 op = o - p;\n\t\t\tstk::vector2 dp = d - p;\n\t\t\tauto dt = dot_product(op, dp);\n\t\t\treturn (dt * dt) >= (e2 * magnitude_sqrd(op) * magnitude_sqrd(dp));\n\t\t}\n\n        bool add_triangle(vertex_handle u, vertex_handle v, vertex_handle w)\n        {\n            auto key = trig_key(u,v,w);\n            auto it = m_triangleMap.find(key);\n            if(it == m_triangleMap.end())\n            {\n                m_edgeVertexMap[edge_key(u,v)] = w;\n                m_edgeVertexMap[edge_key(v,w)] = u;\n                m_edgeVertexMap[edge_key(w,u)] = v;\n\n                std::array<Point,3> trig = {m_points[u],m_points[v],m_points[w]};\n                m_triangleMap.emplace_hint(it, key, trig);\n                return true;\n            }\n\n            return false;\n        }\n\n        void delete_triangle(vertex_handle u, vertex_handle v, vertex_handle w, bool& uvConstrained, bool& vwConstrained, bool& wuConstrained)\n        {\n            m_triangleMap.erase(trig_key(u,v,w));\n            m_edgeVertexMap.erase(edge_key(u,v));\n            m_edgeVertexMap.erase(edge_key(v,w));\n            m_edgeVertexMap.erase(edge_key(w,u));\n            m_triangleMap.erase(trig_key(u,v,w));\n\n\t\t\tauto it = m_edgeVertexMap.find(edge_key(u,v));\n\t\t\tif(it != m_edgeVertexMap.end())\n\t\t\t{ \n\t\t\t\tuvConstrained = it->second.constrained;\n\t\t\t\tm_edgeVertexMap.erase(it);\n\t\t\t}\n\n\t\t\tit = m_edgeVertexMap.find(edge_key(v,w));\n\t\t\tif(it != m_edgeVertexMap.end())\n\t\t\t{ \n\t\t\t\tvwConstrained = it->second.constrained;\n\t\t\t\tm_edgeVertexMap.erase(it);\n\t\t\t}\n\n\t\t\tit = m_edgeVertexMap.find(edge_key(w,u));\n\t\t\tif(it != m_edgeVertexMap.end())\n\t\t\t{ \n\t\t\t\twuConstrained = it->second.constrained;\n\t\t\t\tm_edgeVertexMap.erase(it);\n\t\t\t}\n        }\n        \n        void insert_vertex(vertex_handle u, vertex_handle v, vertex_handle w, vertex_handle x)\n        {\n\t\t\tbool vwConstrained = false;\n\t\t\tbool wxConstrained = false;\n\t\t\tbool xvConstrained = false;\n            delete_triangle(v,w,x, vwConstrained, wxConstrained, xvConstrained);\n            dig_cavity(u,v,w, vwConstrained);\n            dig_cavity(u,w,x, wxConstrained);\n            dig_cavity(u,x,v, xvConstrained);\n        }\n\n        half_edge adjacent(vertex_handle u, vertex_handle v) const\n        {\n            auto key = edge_key(u,v);\n            auto it = m_edgeVertexMap.find(key);\n            if(it != m_edgeVertexMap.end())\n                return it->second;\n\n            return half_edge(invalid_handle::value);\n        }\n\n        bool is_sorted(const Point& a, const Point& b, const Point& c) const\n        {\n            return lexicographically_less_than(a,b,m_cmp) && lexicographically_less_than(a,c,m_cmp) && is_ccw(a,b,c);\n        }\n\n        bool is_ccw(const Point& a, const Point& b, const Point& c) const\n        {\n            return (get_orientation(a, b, c, m_cmp) != oriented_right);\n        }\n\n        void sort(Point& a, Point& b, Point& c) const\n        {\n            using std::swap;\n\n            //! A should always be the lexicographically lowest point. Then all points should order CCW.\n            if(lexicographically_less_than(c, a, m_cmp))\n                swap(a,c);\n\n            if(lexicographically_less_than(b, a, m_cmp))\n                swap(a,b);\n\n            if(!is_ccw(a, b, c))\n                swap(b,c);\n        }\n\n        bool is_degenerate(const Point& a, const Point& b, const Point& c) const\n        {\n            return (numeric_sequence_equals(a, b, m_cmp) ||\n                    numeric_sequence_equals(b, c, m_cmp) ||\n                    numeric_sequence_equals(c, a, m_cmp));\n        }\n\n        vertex_handle find_vertex_handle(const Point& p) const\n        {\n\t        auto it = m_vertexHandleMap.lower_bound(p);\n        \tif( it != m_vertexHandleMap.end() && !m_vertexHandleMap.key_comp()(p, it->first) )\n                return it->second;\n\n            return invalid_handle::value;\n        }\n\n        vertex_handle get_vertex_handle(const Point& p) const\n        {\n\t        auto it = m_vertexHandleMap.lower_bound(p);\n        \tif( it != m_vertexHandleMap.end() && !m_vertexHandleMap.key_comp()(p, it->first) )\n                return it->second;\n\n\t\t    auto vDescriptor = get_descriptor();\n\t\t    m_vertexHandleMap.insert(it, std::make_pair(p, vDescriptor));\n            if(vDescriptor >= m_points.size())\n                m_points.emplace_back(p);\n            else\n                m_points[vDescriptor] = p;\n            return vDescriptor;\n        }\n\n        vertex_handle get_descriptor() const\n        {\n            if(m_freeDescriptors.empty())\n                return m_points.size();\n\n            auto v = m_freeDescriptors.top();\n            m_freeDescriptors.pop();\n            return v;\n        }\n\n        trig_key get_triangle_key(const Point& a, const Point& b, const Point& c) const\n        {\n            GEOMETRIX_ASSERT(is_sorted(a,b,c));\n            auto v0 = get_vertex_handle(a);\n            auto v1 = get_vertex_handle(b);\n            auto v2 = get_vertex_handle(c);\n            return trig_key(v0, v1, v2);\n        }\n\n        trig_key find_triangle_key(const Point& a, const Point& b, const Point& c) const\n        {\n            GEOMETRIX_ASSERT(is_sorted(a,b,c));\n            auto v0 = find_vertex_handle(a);\n            auto v1 = find_vertex_handle(b);\n            auto v2 = find_vertex_handle(c);\n            return trig_key(v0, v1, v2);\n        }\n\n        bool is_valid(trig_key const& key) const\n        {\n            return std::get<0>(key) != invalid_handle::value &&\n                std::get<1>(key) != invalid_handle::value &&\n                std::get<2>(key) != invalid_handle::value;\n        }\n\n        void dig_cavity(vertex_handle u, vertex_handle v, vertex_handle w, bool vwConstrained)\n        {\n            auto x = adjacent(w,v);\n            if(x.opposite != invalid_handle::value)\n            {\n                if(!x.constrained && point_in_circumcircle(m_points[v], m_points[w], m_points[x], u, m_cmp) == point_circle_orientation::inside)\n                {\n\t\t\t\t\tbool wvConstrained = false, vxConstrained = false, xwConstrained = false;\n                    delete_triangle(w,v,x, wvConstrained, vxConstrained, xwConstrained);\n                    dig_cavity(u,v,x, vxConstrained);\n                    dig_cavity(u,x,w, xwConstrained);\n                }\n\t\t\t\telse \n\t\t\t\t{\n\t\t\t\t\tadd_triangle(u, v, w);\n\t\t\t\t\tauto it = m_edgeVertexMap.find(edge_key(v, w));\n\t\t\t\t\tGEOMETRIX_ASSERT(it != m_edgeVertexMap.end());\n\t\t\t\t\tif (it != m_edgeVertexMap.end())\n\t\t\t\t\t\tit->second.constrained = vwConstrained;\n\t\t\t\t}\n            }\n        }\n\n        NumberComparisonPolicy            m_cmp;\n        mutable vertex_handle_map         m_vertexHandleMap;\n        mutable std::stack<vertex_handle> m_freeDescriptors;\n        mutable vertex_point_map          m_points;\n        triangle_edge_opposite_vertex_map m_edgeVertexMap;\n        triangle_map                      m_triangleMap;\n\n    };\n\n}//! namespace geometrix;\n\n", "meta": {"hexsha": "0dec469e6fb3ec13a70bd449f8de889533fad903", "size": 11827, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "geometrix/algorithm/triangle_complex.hpp", "max_stars_repo_name": "brandon-kohn/Geometrix", "max_stars_repo_head_hexsha": "e107e13b469632c7d12cb236bd4fb8b17ff928e3", "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": "geometrix/algorithm/triangle_complex.hpp", "max_issues_repo_name": "brandon-kohn/Geometrix", "max_issues_repo_head_hexsha": "e107e13b469632c7d12cb236bd4fb8b17ff928e3", "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": "geometrix/algorithm/triangle_complex.hpp", "max_forks_repo_name": "brandon-kohn/Geometrix", "max_forks_repo_head_hexsha": "e107e13b469632c7d12cb236bd4fb8b17ff928e3", "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.7077747989, "max_line_length": 144, "alphanum_fraction": 0.604126152, "num_tokens": 2987, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.4759887416524401}}
{"text": "#include <iostream>\n#include <armadillo>\n#include<complex>\n#include<cstdlib>\n#include <ctime>\n#include <string>\n#include \"Particle.h\"\n#include \"Spherical.h\"\n#include \"Cubic.h\"\n#include \"Rhombohedral.h\"\n#include \"Shell.h\"\nusing namespace std;                                                                                 \nusing namespace arma;                                                                                \n\nint main(){\n    // Input \n    int sizeCells;  //sizeCells of lattice in +/-ve x/y/z direction\n    int pSizeCells;  // size of the particle (radius, edge) in unit cells - carved out of bulk lattice\n    double disorderStrength; // Magnitude of disorder potential\n    double disorderCoverage; // fraction of disordered states above orderRadius\n    char pShape; // Spherical, Cubic or Rhombohedral\n\n\n    // Parameters and data structures (Don't need to change those)\n    const double tHopping = 1;\n    const double deltatHopping = 0.4; \n    const complex<double> spinOrbitCoupling(0,1); \n\n    // Geometry of the model;\n    const rowvec latVec1 (\"0 0.5 0.5\");\n    const rowvec latVec2 (\"0.5 0 0.5\");\n    const rowvec latVec3 (\"0.5 0.5 0\");\n    const rowvec sublatVec (\"0.25 0.25 0.25\");\n    const rowvec comShift (\"-0.5 -0.5 -0.5\"); // to have centre of mass of sublatOne at the origin\n    const double latVecNorm = 1/sqrt(2); // cubic cell size a = 1\n    const double sublatVecNorm = sqrt(3)/4;\n\n    const double delta = 0.01; // small number for numerical comparisons\n\n    // Read input from file\n    ifstream inputfile;\n    inputfile.open(\"input.txt\");\n    char buffer [512];\n    string line;\n    while (getline(inputfile, line)) {\n        sscanf(line.c_str(), \"sizeCells = %d %s\", &sizeCells, buffer);\n        sscanf(line.c_str(), \"particleSizeCells = %d %s\", &pSizeCells, buffer);\n        sscanf(line.c_str(), \"disorderStrength = %lf %s\", &disorderStrength, buffer);\n        sscanf(line.c_str(), \"disorderCoverage = %lf %s\", &disorderCoverage, buffer);\n        sscanf(line.c_str(), \"particleShape = %c %s\", &pShape, buffer);\n    }\n\n    Particle * myParticle;\n\n    if (pShape == 'S' || pShape == 's') {\n        myParticle = new Spherical(pSizeCells*latVecNorm, pSizeCells*latVecNorm - sublatVecNorm);\n    } else if (pShape == 'C' ||  pShape == 'c') {\n        myParticle = new Cubic (pSizeCells*latVecNorm, pSizeCells*latVecNorm - sublatVecNorm);\n    } else if (pShape == 'R' || pShape == 'r') {\n        myParticle = new Rhombohedral(pSizeCells*latVecNorm, pSizeCells*latVecNorm - sublatVecNorm); \n\t} else if (pShape == 'H' || pShape == 'h') {\n        myParticle = new Shell(pSizeCells*latVecNorm, pSizeCells*latVecNorm - 4*sublatVecNorm);\n    } else { cout << \"Wrong particle type - exiting\" << endl; return 1;}\n    cout << \"Input: \"<< sizeCells << \" \" << pSizeCells << \" \" <<  disorderStrength << \" \" << disorderCoverage << \" \" << myParticle->shape << endl;\n\n    int pCells = 0; // # unit cells belonging to the particle\n    int dummy = 0; \n    rowvec dummyVec(3);\n    cx_mat dummyMat(2,2);\n    rowvec pcomShift(3);\n\n    cx_mat unity(2,2), sigma_x(2,2), sigma_y(2,2), sigma_z(2,2); // Pauli matrices\n    unity.fill(0), sigma_x.fill(0), sigma_y.fill(0), sigma_z.fill(0);\n    mat dummy_unity={{1,0},{0,1}}, dummy_sigma_x={{0,1},{1,0}};\n    mat dummy_sigma_y={{0,-1},{1,0}}, dummy_sigma_z={{1,0},{0,-1}};\n    unity.set_real(dummy_unity);\n    sigma_x.set_real(dummy_sigma_x);\n    sigma_y.set_imag(dummy_sigma_y);\n    sigma_z.set_real(dummy_sigma_z);\n\n    // Rhombohedral has the shape of the unit cell, so don't need to carve out\n    if (myParticle->shape == \"Rhombohedral\") {\n        sizeCells = pSizeCells; \n    } \n\n    // Set up lattice and calculate number of cells within particle\n    for (int i=-sizeCells; i<sizeCells; i++) {\n        for (int j=-sizeCells;  j<sizeCells; j++) {\n            for (int k=-sizeCells; k<sizeCells; k++) {\n                dummyVec=i*latVec1+j*latVec2+k*latVec3-comShift;\n                if (myParticle->WithinParticle(dummyVec)) {\n                    pcomShift=pcomShift+2*dummyVec+sublatVec;\n                    pCells++;\n                }\n            }\n        }\n    }   \n\n    // Finding particle's COM\n    pcomShift=0.5*pcomShift/pCells;\n\n    // Set up data structures for the particle\n    myParticle->SetDataStructures(pCells);\n\n    // Carve out the unit sphere out of lattice\n    for (int i=-sizeCells; i<sizeCells; i++) {\n        for (int j=-sizeCells;  j<sizeCells; j++) {\n            for (int k=-sizeCells; k<sizeCells; k++) {\n                dummyVec=i*latVec1+j*latVec2+k*latVec3-comShift;\n                if (myParticle->WithinParticle(dummyVec)) {\n                    myParticle->sublatOne(dummy,0)=dummy;\n                    myParticle->sublatOne(dummy,span(1,3))=dummyVec-pcomShift; \n                    myParticle->sublatTwo(dummy,0)=dummy;\n                    myParticle->sublatTwo(dummy,span(1,3))=dummyVec+sublatVec-pcomShift;\n                    dummy++;\n                }\n            }\n        }\n    }   \n\n    // Set up the Hamiltonian\n    for (int i=0; i<pCells; i++) {\n        for (int j=0; j<pCells; j++) {\n            // Set up nearest neighbour hoppings (between sublattices)\n            dummyVec=myParticle->sublatOne(i,span(1,3))-myParticle->sublatTwo(j,span(1,3));\n            if (dot(dummyVec,dummyVec) < sublatVecNorm*sublatVecNorm+delta) {\n                if (i==j) {\n                    // hoppings within a cell i\n                    myParticle->Hamiltonian(span(4*i+0,4*i+1),span(4*i+2,4*i+3))+=(tHopping+deltatHopping)*unity;\n                    myParticle->Hamiltonian(span(4*i+2,4*i+3),span(4*i+0,4*i+1))+=(tHopping+deltatHopping)*unity;\n                } else {\n                    // hoppings from sublatTwo of cell j to sublatOne of cell i\n                    myParticle->Hamiltonian(span(4*i+0,4*i+1),span(4*j+2,4*j+3))+=(tHopping)*unity;\n                    // hoppings from sublatOne of cell i to sublatTwo of cell j\n                    myParticle->Hamiltonian(span(4*j+2,4*j+3),span(4*i+0,4*i+1))+=(tHopping)*unity;\n                }\n            }\n\n            // Set up next nearest neighbour hoppings (within each sublattice)\n            dummyVec=myParticle->sublatOne(i,span(1,3))-myParticle->sublatOne(j,span(1,3)); \n            if ( (dot(dummyVec,dummyVec) < latVecNorm*latVecNorm+delta)  && \n                    (dot(dummyVec,dummyVec) > sublatVecNorm*sublatVecNorm+delta) ) { \n\n                // Matrix elements are direction-dependent\n                if ( (dummyVec(0) > 0 && dummyVec(1) > 0) || (dummyVec(0) > 0 &&\n                            dummyVec(2) > 0) || (dummyVec(1) > 0 && dummyVec(2) > 0) ) {\n                    dummyVec = cross(sublatVec, dummyVec-sublatVec);\n                } else if ( (dummyVec(1) < 0 && dummyVec(2) < 0) || (dummyVec(0) > 0 &&\n                            dummyVec(1) < 0) || (dummyVec(0) > 0 && dummyVec(2) < 0) ) {\n                    dummyVec = cross(-latVec1+sublatVec, dummyVec+latVec1-sublatVec);\n                } else if ( (dummyVec(0) < 0 && dummyVec(1) > 0) || (dummyVec(0) < 0 &&\n                            dummyVec(2) < 0) || (dummyVec(1) > 0 && dummyVec(2) < 0) ) {\n                    dummyVec = cross(-latVec2+sublatVec, dummyVec+latVec2-sublatVec);\n                } else if ( (dummyVec(0) < 0 && dummyVec(2) > 0) || (dummyVec(1) < 0 &&\n                            dummyVec(2) > 0) || (dummyVec(0) < 0 && dummyVec(1) < 0) ) {\n                    dummyVec = cross(-latVec3+sublatVec, dummyVec+latVec3-sublatVec);\n                } else {}\n                dummyMat=dummyVec(0)*sigma_x+dummyVec(1)*sigma_y+dummyVec(2)*sigma_z;\n                // See if both atoms are connected to the same linking atom\n                // hoppings from cell j to cell i within sublattice One\n                myParticle->Hamiltonian(span(4*i,4*i+1),span(4*j,4*j+1))=spinOrbitCoupling*dummyMat;\n                // hoppings from cell i to cell j within sublattice One\n                // Minus sign for hopping in opposite direction\n                myParticle->Hamiltonian(span(4*j,4*j+1),span(4*i,4*i+1))=-spinOrbitCoupling*dummyMat;\n                // hoppings from cell j to cell i within sublattice Two\n                // Minus sign for sublattice  \n                myParticle->Hamiltonian(span(4*i+2,4*i+3),span(4*j+2,4*j+3))=-spinOrbitCoupling*dummyMat;\n                // hoppings from cell i to cell j within sublattice Two\n                myParticle->Hamiltonian(span(4*j+2,4*j+3),span(4*i+2,4*i+3))=spinOrbitCoupling*dummyMat;\n            }\n        } \n    }\n\n    myParticle->AddDisorder(disorderStrength, disorderCoverage, delta);\n\n    // abs returns a matrix, max returns a vector, 2nd max - largest value\n    if (max(max(abs(myParticle->Hamiltonian-myParticle->Hamiltonian.t()))) > delta ) {\n        cout << \"Error, Hamiltonian is not Hermitian by at least \" << delta << endl;\n    }\n\n    // Get the eigenvectors and eigevalues\n    eig_sym(myParticle->eigvals, myParticle->eigvecs, myParticle->Hamiltonian);\n\n    myParticle->PrintInfo(disorderStrength);\n\n    // Find the middle of the spectrum (Dirac point, E=0, for clean spectrum) \n    for (int i=0; i<4*pCells-1;i++) {\n        if (myParticle->eigvals(i) > 0 && myParticle->eigvals(i-1) < 0) {\n            dummy = i ;\n        }\n    }\n    cout << \"First state above E=0 is #: \" << dummy << \" with E= \" << myParticle->eigvals(dummy) << endl; \n    dummy=2*pCells;\n    cout << \"Picking state #: \" << dummy << \" with E= \" << myParticle->eigvals(dummy) << endl; \n\n    mat probDensity(2*pCells,4+100); \n    probDensity(span(0,pCells-1),span(0,2))=myParticle->sublatOne.cols(1,3);\n    probDensity(span(pCells,2*pCells-1),span(0,2))=myParticle->sublatTwo.cols(1,3);\n\n    // Calculate probability density of probDensity labelled dummy at each lattice site\n    for (int i=0; i<pCells; i++) {\n\t\tfor (int j=0; j<100; j++) {\n        probDensity(i,3+j)=norm(myParticle->eigvecs(span(4*i,4*i+1),dummy+j))*norm(myParticle->eigvecs(span(4*i,4*i+1),dummy+j));\n        probDensity(pCells+i,3+j)=norm(myParticle->eigvecs(span(4*i+2,4*i+3),dummy+j))*norm(myParticle->eigvecs(span(4*i+2,4*i+3),dummy+j));\n\t\t}\n    }    \n    // Save all eigenvalues and a particular eigenvector\n    myParticle->eigvals.save(\"output_eigvals.txt\",raw_ascii);\n    probDensity.save(\"output_state.txt\", raw_ascii);\n    return 0;\n}\n", "meta": {"hexsha": "4f38ce6975fd18005b899f953bb73724b5fc5881", "size": 10283, "ext": "cc", "lang": "C++", "max_stars_repo_path": "main.cc", "max_stars_repo_name": "Trave11er/FuKaneMeleModel", "max_stars_repo_head_hexsha": "bb1bb8c9bb4bfb8928bc4e9019538a38e2a6f5be", "max_stars_repo_licenses": ["MIT"], "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.cc", "max_issues_repo_name": "Trave11er/FuKaneMeleModel", "max_issues_repo_head_hexsha": "bb1bb8c9bb4bfb8928bc4e9019538a38e2a6f5be", "max_issues_repo_licenses": ["MIT"], "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.cc", "max_forks_repo_name": "Trave11er/FuKaneMeleModel", "max_forks_repo_head_hexsha": "bb1bb8c9bb4bfb8928bc4e9019538a38e2a6f5be", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-05-11T07:51:41.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-11T07:51:41.000Z", "avg_line_length": 48.5047169811, "max_line_length": 146, "alphanum_fraction": 0.5825148303, "num_tokens": 3038, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.4759887416524401}}
{"text": "#pragma once\n#include \"vector.hpp\"\n#include <boost/operators.hpp>\n#include <iostream>\n\nnamespace dmc\n{\n\ttemplate <class Scalar, int Dimension>\n\tclass dual\n\t\t: boost::addable<dual<Scalar, Dimension>\n\t\t, boost::addable<dual<Scalar, Dimension>, Scalar\n\t\t, boost::subtractable<dual<Scalar, Dimension>\n\t\t, boost::subtractable<dual<Scalar, Dimension>, Scalar\n\t\t, boost::multipliable<dual<Scalar, Dimension>\n\t\t, boost::multipliable<dual<Scalar, Dimension>, Scalar\n\t\t, boost::dividable<dual<Scalar, Dimension>\n\t\t, boost::dividable<dual<Scalar, Dimension>, Scalar\n\t\t, boost::equality_comparable<dual<Scalar, Dimension>\n\t\t, boost::equality_comparable<dual<Scalar, Dimension>, Scalar\n\t\t, boost::less_than_comparable<dual<Scalar, Dimension>\n\t\t, boost::less_than_comparable<dual<Scalar, Dimension>, Scalar\n\t\t>>>>>>>>>>>>\n\t{\n\tpublic:\n\t\ttypedef Scalar scalar_type;\n\t\tstatic const int dimension = Dimension;\n\t\ttypedef vector<scalar_type, dimension> vector_type;\n\n\t\tdual() = default;\n\n\t\tdual(scalar_type value)\n\t\t\t: value_(value)\n\t\t{\n\t\t}\n\n\t\tdual(scalar_type value, const vector_type& grad)\n\t\t\t: value_(value)\n\t\t\t, grad_(grad)\n\t\t{\n\t\t}\n\n\t\tscalar_type& value()\n\t\t{\n\t\t\treturn value_;\n\t\t}\n\n\t\tconst scalar_type& value() const\n\t\t{\n\t\t\treturn value_;\n\t\t}\n\n\t\tvector_type& grad()\n\t\t{\n\t\t\treturn grad_;\n\t\t}\n\n\t\tconst vector_type& grad() const\n\t\t{\n\t\t\treturn grad_;\n\t\t}\n\n\t\tconst dual& operator+() const\n\t\t{\n\t\t\treturn *this;\n\t\t}\n\n\t\tdual operator-() const\n\t\t{\n\t\t\treturn dual(-value_, -grad_);\n\t\t}\n\n\t\tdual& operator+=(const dual& rhs)\n\t\t{\n\t\t\tvalue_ += rhs.value_;\n\t\t\tgrad_ += rhs.grad_;\n\t\t\treturn *this;\n\t\t}\n\n\t\tdual& operator-=(const dual& rhs)\n\t\t{\n\t\t\tvalue_ -= rhs.value_;\n\t\t\tgrad_ -= rhs.grad_;\n\t\t\treturn *this;\n\t\t}\n\n\t\tdual& operator*=(const dual& rhs)\n\t\t{\n\t\t\tgrad_ = value_ * rhs.grad_ + rhs.value_ * grad_;\n\t\t\tvalue_ *= rhs.value_;\n\t\t\treturn *this;\n\t\t}\n\n\t\tdual& operator/=(const dual& rhs)\n\t\t{\n\t\t\tgrad_ = (grad_ * rhs.value_ - value_ * rhs.grad_) / (rhs.value_ * rhs.value_);\n\t\t\tvalue_ /= rhs.value_;\n\t\t\treturn *this;\n\t\t}\n\n\t\tfriend bool operator==(const dual& lhs, const dual& rhs)\n\t\t{\n\t\t\treturn lhs.value_ == rhs.value_;\n\t\t}\n\n\t\tfriend bool operator<(const dual& lhs, const dual& rhs)\n\t\t{\n\t\t\treturn lhs.value_ < rhs.value_;\n\t\t}\n\n\t\tfriend dual abs(const dual& d)\n\t\t{\n\t\t\treturn d.value() < static_cast<scalar_type>(0.0) ? -d : d;\n\t\t}\n\n\t\tfriend dual sqrt(const dual& d)\n\t\t{\n\t\t\tauto value = std::sqrt(d.value());\n\t\t\tauto grad = value * static_cast<scalar_type>(0.5) * d.grad() / d.value();\n\t\t\treturn dual(value, grad);\n\t\t}\n\n\t\tfriend dual sin(const dual& d)\n\t\t{\n\t\t\tauto value = std::sin(d.value());\n\t\t\tauto grad = d.grad() * std::cos(d.value());\n\t\t\treturn dual(value, grad);\n\t\t}\n\n\t\tfriend dual cos(const dual& d)\n\t\t{\n\t\t\tauto value = std::cos(d.value());\n\t\t\tauto grad = -d.grad() * std::sin(d.value());\n\t\t\treturn dual(value, grad);\n\t\t}\n\n\tprivate:\n\t\tscalar_type value_{};\n\t\tvector_type grad_;\n\t};\n\n\ttemplate <class Scalar, int Dimension>\n\tScalar value(const dual<Scalar, Dimension>& d)\n\t{\n\t\treturn d.value();\n\t}\n\n\ttemplate <class Scalar>\n\tScalar value(const Scalar& value)\n\t{\n\t\treturn value;\n\t}\n\n\ttemplate <class Scalar, int Dimension>\n\tScalar grad(const dual<Scalar, Dimension>& d)\n\t{\n\t\treturn d.grad();\n\t}\n\n\ttemplate <class Scalar, int Dimension>\n\tstd::ostream& operator<<(std::ostream& os, const dual<Scalar, Dimension>& d)\n\t{\n\t\tos << \"{ \" << d.value() << \", \" << d.grad().transpose() << \" }\";\n\t\treturn os;\n\t}\n}\n", "meta": {"hexsha": "410aa4662978b5848fcba08468acd16f99a5373e", "size": 3376, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/dmc/dual.hpp", "max_stars_repo_name": "planaria/dmc", "max_stars_repo_head_hexsha": "6d11fa49227b21c66fa52736a3d9272bd0ccbfa4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2017-08-08T05:02:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-10T21:06:17.000Z", "max_issues_repo_path": "include/dmc/dual.hpp", "max_issues_repo_name": "planaria/dmc", "max_issues_repo_head_hexsha": "6d11fa49227b21c66fa52736a3d9272bd0ccbfa4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2019-08-17T16:23:30.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-28T06:29:57.000Z", "max_forks_repo_path": "include/dmc/dual.hpp", "max_forks_repo_name": "planaria/dmc", "max_forks_repo_head_hexsha": "6d11fa49227b21c66fa52736a3d9272bd0ccbfa4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-11-15T21:14:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T16:34:47.000Z", "avg_line_length": 20.3373493976, "max_line_length": 81, "alphanum_fraction": 0.6404028436, "num_tokens": 1000, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4758918026784483}}
{"text": "#ifndef OOQPRECOURSEINTERFACE_HPP\n#define OOQPRECOURSEINTERFACE_HPP\n\n#include \"stochasticInput.hpp\"\n#include \"QpGenVars.h\"\n#include \"QpGenResiduals.h\"\n#include \"SimpleVector.h\"\n#include \"Status.h\"\n#include \"QpGenData.h\"\n#include \"OoqpVersion.h\"\n#include <boost/scoped_ptr.hpp>\n#include \"SparseGenMatrix.h\"\n#include \"SparseSymMatrix.h\"\n\nusing boost::scoped_ptr;\n\n\ntemplate<typename SOLVER, typename FORMULATION>\nclass OOQPRecourseInterface {\npublic:\n  OOQPRecourseInterface(stochasticInput &, int scenarioNumber, const std::vector<double> &firstStageSolution);\n\n  void go();\n  double getObjective() const;\n  \n  std::vector<double> getPrimalColSolution() const;\n  std::vector<double> getDualRowSolution() const;\n  \nprotected:\n  scoped_ptr<FORMULATION> qp;\n  scoped_ptr<QpGenData> prob;\n  scoped_ptr<QpGenVars> vars;\n  scoped_ptr<Residuals> resid;\n  scoped_ptr<SOLVER> s;\n  vector<int> primalOffsets;\n  vector<int> rowToEqIneqIdx;\n  vector<int> rowOffsets;\n};\n\n\nnamespace{\n\n  void scanRows(CoinPackedMatrix& Wrow, \n\t\tstd::vector<double>& lb, std::vector<double>& ub, \t\t\n\t\tint &my, int &mz, int &nnzA, int &nnzC, \n\t\tvector<int> &rowToEqIneqIdx) \n  {\n    \n    my = mz = nnzA = nnzC = 0;\n    \n    int nrow = lb.size(), rowi=0;\n    for (int i = 0; i < nrow; i++) {\n      if (lb[i] == ub[i]) {\n\tmy++;\n\tnnzA += Wrow.getVectorSize(i);\n\trowToEqIneqIdx[rowi++]=my;\n      } else {\n\tmz++;\n\tnnzC += Wrow.getVectorSize(i);\n\trowToEqIneqIdx[rowi++]=-mz-1;\n      }\n    }\n  }\n  \n  \n  void separateRows(CoinPackedMatrix& Wrow, \n\t\t    std::vector<double>& lb, std::vector<double>& ub,\n\t\t    SparseGenMatrix &A, SparseGenMatrix &C) \n  {\n    int *rowptrA = A.krowM(), *rowptrC = C.krowM();\n    int *colidxA = A.jcolM(), *colidxC = C.jcolM();\n    double *eltA = A.M(), *eltC = C.M();\n    \n    int nnzA = 0, nnzC = 0;\n    int nrowA = 0, nrowC = 0;\n    \n    int *rowptr, *colidx, *nnz, *nr;\n    double *elt;\n    \n    int nrow = lb.size();\n    for (int i = 0; i < nrow; i++) {\n      if (lb[i] == ub[i]) {\n\trowptr = rowptrA;\n\tcolidx = colidxA;\n\telt = eltA;\n\tnr = &nrowA;\n\tnnz = &nnzA;\n      } else {\n\trowptr = rowptrC;\n\tcolidx = colidxC;\n\telt = eltC;\n\tnr = &nrowC;\n\tnnz = &nnzC;\n      }\n      \n      rowptr[(*nr)++] = *nnz;\n      for (CoinBigIndex k = Wrow.getVectorFirst(i); k < Wrow.getVectorLast(i); k++) {\n\tcolidx[*nnz] = Wrow.getIndices()[k];\n\telt[(*nnz)++] = Wrow.getElements()[k];\n      }\n    }\n    rowptrA[nrowA] = nnzA;\n    rowptrC[nrowC] = nnzC;\n    \n  }\n  \n  //we do not deal with cross terms here\n  void formQ(stochasticInput &input, int scenNumber,\n\t     const CoinPackedMatrix& Qrow,\n\t     SparseSymMatrix &Q) \n  {\n    int *rowQ = Q.krowM(), *colidx = Q.jcolM();\n    double *elt = Q.M();\n    \n    int nnzQ = 0;\n    int nrowQ = 0;\n    //int offset = 0;\n    \n    int nrow = input.nSecondStageVars(scenNumber);\n    for (int i = 0; i < nrow; i++) {\n      rowQ[nrowQ++] = nnzQ;\n      for (CoinBigIndex k = Qrow.getVectorFirst(i); k < Qrow.getVectorLast(i); k++) {\n\t//colidx[nnzQ] = Qrow.getIndices()[k]+offset;\n\tcolidx[nnzQ] = Qrow.getIndices()[k];\n\telt[nnzQ++] = Qrow.getElements()[k];\n      }\n    }\n    rowQ[nrowQ] = nnzQ;\n    //offset += nrow;\n  }\n}\n\ntemplate<typename SOLVER, typename FORMULATION>\nOOQPRecourseInterface<SOLVER,FORMULATION>::OOQPRecourseInterface(stochasticInput &input, int scenNumber, const std::vector<double> &firstStageSolution)\n{\n  int nvar2 = input.nSecondStageVars(scenNumber);\n  int ncons2 = input.nSecondStageCons(scenNumber);\n\n  CoinPackedMatrix Wrow, Trow;\n  Wrow.reverseOrderedCopyOf(input.getSecondStageConstraints(scenNumber));\n  Trow.reverseOrderedCopyOf(input.getLinkingConstraints(scenNumber));\n\n  vector<double> Tx(ncons2);\n  Trow.times(&firstStageSolution[0],&Tx[0]);\n\n  vector<double> rowlb = input.getSecondStageRowLB(scenNumber),\n    rowub = input.getSecondStageRowUB(scenNumber);\n  \n  for (int k = 0; k < ncons2; k++) {\n    if (rowub[k] < 1e20) {\n      rowub[k] -= Tx[k];\n    }\n    if (rowlb[k] >-1e20) {\n      rowlb[k] -= Tx[k];\n    }\n  }\n\n  rowToEqIneqIdx.resize(ncons2);\n\n  int my, mz, nnzA, nnzC;\n  scanRows(Wrow, rowlb, rowub, my, mz, nnzA, nnzC, rowToEqIneqIdx);\n\n\n  int nnzQ = input.getSecondStageHessian(scenNumber).getNumElements();\n  CoinPackedMatrix Qrow;\n  Qrow.reverseOrderedCopyOf(input.getSecondStageHessian(scenNumber));\n\n\n  qp.reset(new FORMULATION(nvar2,my,mz,nnzQ,nnzA,nnzC));\n  prob.reset(dynamic_cast<QpGenData*>(qp->makeData()));\n  \n  separateRows(Wrow, rowlb, rowub, \n\t       dynamic_cast<SparseGenMatrix&>(*prob->A),\n\t       dynamic_cast<SparseGenMatrix&>(*prob->C));\n\n  formQ(input, scenNumber, Qrow,\n\tdynamic_cast<SparseSymMatrix&>(*prob->Q));\n\n  \n  // the beauty of OOP...\n  double *bA = dynamic_cast<SimpleVector&>(*prob->bA).elements();\n  double *bl = dynamic_cast<SimpleVector&>(*prob->bl).elements();\n  double *bu = dynamic_cast<SimpleVector&>(*prob->bu).elements();\n  double *iclow = dynamic_cast<SimpleVector&>(*prob->iclow).elements();\n  double *icupp = dynamic_cast<SimpleVector&>(*prob->icupp).elements();\n  double *g = dynamic_cast<SimpleVector&>(*prob->g).elements();\n  double *blx = dynamic_cast<SimpleVector&>(*prob->blx).elements();\n  double *bux = dynamic_cast<SimpleVector&>(*prob->bux).elements();\n  double *ixupp = dynamic_cast<SimpleVector&>(*prob->ixupp).elements();\n  double *ixlow = dynamic_cast<SimpleVector&>(*prob->ixlow).elements();\n  \n  int eq_idx = 0, ineq_idx = 0;\n  //std::vector<double> const &l = input.getSecondStageRowLB(scenNumber);\n  //std::vector<double> const &u = input.getSecondStageRowUB(scenNumber);\n  int nrow = input.nSecondStageCons(scenNumber);\n  for (int k = 0; k < nrow; k++) {\n    if (rowlb[k] == rowub[k]) {\n      bA[eq_idx++] = rowlb[k];\n    } else {\n      if (rowlb[k] > -1e20) {\n\tbl[ineq_idx] = rowlb[k];\n\ticlow[ineq_idx] = 1.;\n      } else {\n\tbl[ineq_idx] = 0.;\n\ticlow[ineq_idx] = 0.;\n      }\n      if (rowub[k] < 1e20) {\n\tbu[ineq_idx] = rowub[k];\n\ticupp[ineq_idx] = 1.;\n      } else {\n\tbu[ineq_idx] = 0.;\n\ticupp[ineq_idx] = 0.;\n      }\n      ineq_idx++;\n    }\n  }\n  \n  //double RESCALE=1.0;\n  int idx = 0;\n  std::vector<double> const &l = input.getSecondStageColLB(scenNumber);\n  std::vector<double> const &u = input.getSecondStageColUB(scenNumber);\n  std::vector<double> const &c = input.getSecondStageObj(scenNumber);\n  int ncol = input.nSecondStageVars(scenNumber);\n  for (int k = 0; k < ncol; k++) {\n    //g[idx] = RESCALE*c[k];\n    g[idx] = c[k];\n    if (l[k] > -1e20) {\n      blx[idx] = l[k];\n      ixlow[idx] = 1.;\n    } else {\n      blx[idx] = 0.;\n      ixlow[idx] = 0.;\n    }\n    if (u[k] < 1e20) {\n      bux[idx] = u[k];\n      ixupp[idx] = 1.;\n    } else {\n      bux[idx] = 0.;\n      ixupp[idx] = 0.;\n    }\n    idx++;\n  }\n\n  vars.reset(dynamic_cast<QpGenVars*>(qp->makeVariables(prob.get())));\n  resid.reset(qp->makeResiduals(prob.get()));\n  s.reset(new SOLVER(qp.get(),prob.get()));\n\n}\n\n\ntemplate<typename S, typename F>\nvoid OOQPRecourseInterface<S,F>::go() \n{\n  //s->monitorSelf();\n#ifdef TIMING\n  int result = s->solve(prob.get(),vars.get(),resid.get());\n\n  if ( 0 == result ) {\n    double objective = prob->objectiveValue(vars.get());\n    \n    cout << \" \" << prob->nx << \" variables, \" \n   \t << prob->my  << \" equality constraints, \" \n   \t << prob->mz  << \" inequality constraints.\\n\";\n    \n    cout << \" Iterates: \" << s->iter\n   \t <<\",    Optimal Solution:  \" << objective << endl;\n  }\n#else\n  s->solve(prob.get(),vars.get(),resid.get());\n#endif\n}\n\ntemplate<typename S, typename F>\ndouble OOQPRecourseInterface<S,F>::getObjective() const {\n\treturn prob->objectiveValue(vars.get());\n}\n\ntemplate<typename S, typename F>\nstd::vector<double> OOQPRecourseInterface<S,F>::getPrimalColSolution() const\n{\n  double const *sol = &dynamic_cast<SimpleVector const&>(*vars->x)[0];\n  return std::vector<double>(sol, sol+vars->x->length());\n}\n\ntemplate<typename S, typename F>\nstd::vector<double> OOQPRecourseInterface<S,F>::getDualRowSolution() const\n{\n  std::vector<double> out; \n  out.reserve(vars->y->length()+vars->z->length());\n  \n  double const *eqsol = &dynamic_cast<SimpleVector const&>(*vars->y)[0];\n  double const *ineqsol = &dynamic_cast<SimpleVector const&>(*vars->z)[0];\n\n  for(int idx=0; idx<vars->y->length()+vars->z->length(); idx++) {\n    int r=rowToEqIneqIdx[idx];\n    if(r>=0) out.push_back(eqsol[r]);\n    else     out.push_back(ineqsol[-r-1]);\n  }\n  return out;\n}\n\n#endif\n", "meta": {"hexsha": "86e8109f82fd0e840c236a3f038ee8fd17623fcc", "size": 8301, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "PIPS-IPM/Core/QpGen/OOQPRecourseInterface.hpp", "max_stars_repo_name": "dRehfeldt/PIPS", "max_stars_repo_head_hexsha": "24d3ea89a0a1aa77c133cfc698a568eb685c9fdb", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2020-10-29T15:14:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-14T13:31:54.000Z", "max_issues_repo_path": "PIPS-IPM/Core/QpGen/OOQPRecourseInterface.hpp", "max_issues_repo_name": "dRehfeldt/PIPS", "max_issues_repo_head_hexsha": "24d3ea89a0a1aa77c133cfc698a568eb685c9fdb", "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": "PIPS-IPM/Core/QpGen/OOQPRecourseInterface.hpp", "max_forks_repo_name": "dRehfeldt/PIPS", "max_forks_repo_head_hexsha": "24d3ea89a0a1aa77c133cfc698a568eb685c9fdb", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-02-15T16:30:44.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-15T16:30:44.000Z", "avg_line_length": 27.396039604, "max_line_length": 151, "alphanum_fraction": 0.6324539212, "num_tokens": 2712, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4758918026784482}}
{"text": "#include <gtest/gtest.h>\n#include <boost/math/distributions.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <stan/math/prim/mat.hpp>\n#include <math/prim/mat/prob/vector_rng_test_helper.hpp>\n#include <math/prim/mat/prob/VectorIntRNGTestRig.hpp>\n#include <limits>\n#include <vector>\n\nclass NegativeBinomial2TestRig : public VectorIntRNGTestRig {\n public:\n  NegativeBinomial2TestRig()\n      : VectorIntRNGTestRig(10000, 10, {0, 1, 2, 3, 4, 5, 6}, {0.1, 1.7, 3.99},\n                            {1, 2, 3}, {-2.1, -0.5, 0.0}, {-3, -1, 0},\n                            {0.1, 1.1, 4.99}, {1, 2, 3}, {-3.0, -2.0, 0.0},\n                            {-3, -1, 0}) {}\n\n  template <typename T1, typename T2, typename T3, typename T_rng>\n  auto generate_samples(const T1& mu, const T2& phi, const T3&,\n                        T_rng& rng) const {\n    return stan::math::neg_binomial_2_rng(mu, phi, rng);\n  }\n\n  template <typename T1>\n  double pmf(int y, T1 mu, double phi, double) const {\n    return std::exp(stan::math::neg_binomial_2_lpmf(y, mu, phi));\n  }\n};\n\nTEST(ProbDistributionsNegativeBinomial2, errorCheck) {\n  check_dist_throws_all_types(NegativeBinomial2TestRig());\n}\n\nTEST(ProbDistributionsNegativeBinomial2, distributionCheck) {\n  check_counts_real_real(NegativeBinomial2TestRig());\n}\n", "meta": {"hexsha": "a1a870bec18fc0f6201023a6b2fe36f020e99184", "size": 1290, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/math_unit/math/prim/mat/prob/neg_binomial_2_test.cpp", "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": "tests/math_unit/math/prim/mat/prob/neg_binomial_2_test.cpp", "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": "tests/math_unit/math/prim/mat/prob/neg_binomial_2_test.cpp", "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.8648648649, "max_line_length": 79, "alphanum_fraction": 0.6465116279, "num_tokens": 420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4758918026784482}}
{"text": "//\n// Created by mateusz\n//\n#include <boost/test/unit_test.hpp>\n#include <cpuclassifier/CPULearnColumn.hpp>\n#include <numeric>\n\nBOOST_AUTO_TEST_SUITE(nbc4cpu_TestSuite)\n\nBOOST_AUTO_TEST_SUITE(LearnColumn_TestSuite)\n\n\nBOOST_AUTO_TEST_CASE(PrecalulatedTest_Size6) {\n\n  std::vector<float> vec = {1, 1, 1, 2, 2, 2};\n\n  nbc4cpu::CPULearnColumn<float> learner =\n      nbc4cpu::CPULearnColumn<float>(vec);\n  const auto res = learner();\n\n  BOOST_CHECK_CLOSE(res.first, 1.5, 0.1);\n  BOOST_CHECK_CLOSE(res.second, 0.3, 0.1);\n}\n\nBOOST_AUTO_TEST_CASE(PrecalulatedTest_Size12) {\n\n  std::vector<float> vec = {91, 11, 1111, 32, 26, 2, 22, 894, 345};\n\n  nbc4cpu::CPULearnColumn<float> learner =\n      nbc4cpu::CPULearnColumn<float>(vec);\n  const auto res = learner();\n\n  BOOST_CHECK_CLOSE(res.first, 281.55555555556, 0.1);\n  BOOST_CHECK_CLOSE(res.second, 181213.77777778, 0.1);\n}\n\nBOOST_AUTO_TEST_CASE(CompareWithCpu_LargeVectorTest) {\n\n  srand(1234); // set rand seed to make test repeatable\n\n  std::vector<float> vec(500000);\n  std::generate(vec.begin(), vec.end(), []() { return rand() % 250; });\n\n  nbc4cpu::CPULearnColumn<float> learner =\n      nbc4cpu::CPULearnColumn<float>(vec);\n  const auto res = learner();\n\n  float sum = 0.0;\n  sum       = std::accumulate(vec.begin(), vec.end(), sum);\n  float avg = sum / static_cast<float>(vec.size());\n\n  BOOST_CHECK_CLOSE(res.first, avg, 1);\n\n  float variance = 0;\n  for (float i : vec) {\n    float dif = i - avg;\n    variance += dif * dif;\n  }\n  variance = variance / static_cast<float>(vec.size() - 1);\n\n  BOOST_CHECK_CLOSE(res.second, variance, 1);\n}\n\n\nBOOST_AUTO_TEST_CASE(PrecalulatedTest_Size6_double) {\n\n  std::vector<double> vec = {1, 1, 1, 2, 2, 2};\n\n  nbc4cpu::CPULearnColumn<double> learner =\n      nbc4cpu::CPULearnColumn<double>(vec);\n  const auto res = learner();\n\n  BOOST_CHECK_CLOSE(res.first, 1.5, 0.1);\n  BOOST_CHECK_CLOSE(res.second, 0.3, 0.1);\n}\n\nBOOST_AUTO_TEST_CASE(PrecalulatedTest_Size12_double) {\n\n  std::vector<double> vec = {91, 11, 1111, 32, 26, 2, 22, 894, 345};\n\n  nbc4cpu::CPULearnColumn<double> learner =\n      nbc4cpu::CPULearnColumn<double>(vec);\n  const auto res = learner();\n\n  BOOST_CHECK_CLOSE(res.first, 281.55555555556, 0.1);\n  BOOST_CHECK_CLOSE(res.second, 181213.77777778, 0.1);\n}\n\nBOOST_AUTO_TEST_CASE(CompareWithCpu_LargeVectorTest_double) {\n\n  srand(1234); // set rand seed to make test repeatable\n\n  std::vector<double> vec(5000000);\n  std::generate(vec.begin(), vec.end(), []() { return rand() % 250; });\n\n  nbc4cpu::CPULearnColumn<double> learner =\n      nbc4cpu::CPULearnColumn<double>(vec);\n  const auto res = learner();\n\n  double sum = 0.0;\n  sum        = std::accumulate(vec.begin(), vec.end(), sum);\n  double avg = sum / static_cast<double>(vec.size());\n\n  BOOST_CHECK_CLOSE(res.first, avg, 1);\n\n  double variance = 0;\n  for (double i : vec) {\n    double dif = i - avg;\n    variance += dif * dif;\n  }\n  variance = variance / static_cast<double>(vec.size() - 1);\n\n  BOOST_CHECK_CLOSE(res.second, variance, 1);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "3c2a7585b807987e068882d59e26854dde220639", "size": 3054, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/cpuTest/learn_column_test.cpp", "max_stars_repo_name": "przestaw/nbc4gpu", "max_stars_repo_head_hexsha": "641945ac3974ec9df78a4217ebd133576791c58a", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/cpuTest/learn_column_test.cpp", "max_issues_repo_name": "przestaw/nbc4gpu", "max_issues_repo_head_hexsha": "641945ac3974ec9df78a4217ebd133576791c58a", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/cpuTest/learn_column_test.cpp", "max_forks_repo_name": "przestaw/nbc4gpu", "max_forks_repo_head_hexsha": "641945ac3974ec9df78a4217ebd133576791c58a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.6638655462, "max_line_length": 71, "alphanum_fraction": 0.6853307138, "num_tokens": 954, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4758918026784482}}
{"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\n/*\n*\n*   Tutorial: Algebraic multigrid preconditioner (only available with the OpenCL backend, experimental)\n*\n*/\n\n\n\n#ifndef NDEBUG     //without NDEBUG the performance of sparse ublas matrices is poor.\n #define NDEBUG\n#endif\n\n#include <boost/numeric/ublas/matrix_sparse.hpp>\n#include <boost/numeric/ublas/operation_sparse.hpp>\n\n#define VIENNACL_WITH_UBLAS 1\n\n#define SOLVER_ITERS 2500\n//#define SCALAR float\n#define SCALAR double\n\n//#define SOLVER_TOLERANCE 1e-5\n#define SOLVER_TOLERANCE 1e-9\n\n#include \"viennacl/vector.hpp\"\n#include \"viennacl/coordinate_matrix.hpp\"\n#include \"viennacl/compressed_matrix.hpp\"\n#include \"viennacl/linalg/ilu.hpp\"\n#include \"viennacl/linalg/cg.hpp\"\n#include \"viennacl/linalg/bicgstab.hpp\"\n#include \"viennacl/io/matrix_market.hpp\"\n#include \"viennacl/linalg/norm_2.hpp\"\n\n#include \"viennacl/linalg/amg.hpp\"\n\n#include <iostream>\n#include <vector>\n#include <ctime>\n#include \"vector-io.hpp\"\n\n\ntemplate<typename MatrixType, typename VectorType, typename SolverTag, typename PrecondTag>\nvoid run_solver(MatrixType const & matrix, VectorType const & rhs, VectorType const & ref_result, SolverTag const & solver, PrecondTag const & precond)\n{\n  VectorType result(rhs);\n  VectorType residual(rhs);\n\n  result = viennacl::linalg::solve(matrix, rhs, solver, precond);\n  residual -= viennacl::linalg::prod(matrix, result);\n  std::cout << \"  > Relative residual: \" << viennacl::linalg::norm_2(residual) / viennacl::linalg::norm_2(rhs) << std::endl;\n  std::cout << \"  > Iterations: \" << solver.iters() << std::endl;\n  result -= ref_result;\n  std::cout << \"  > Relative deviation from result: \" << viennacl::linalg::norm_2(result) / viennacl::linalg::norm_2(ref_result) << std::endl;\n}\n\ntemplate<typename ScalarType>\nvoid run_amg(viennacl::linalg::cg_tag & cg_solver,\n             boost::numeric::ublas::vector<ScalarType> & /*ublas_vec*/,\n             boost::numeric::ublas::vector<ScalarType> & /*ublas_result*/,\n             boost::numeric::ublas::compressed_matrix<ScalarType> & ublas_matrix,\n             viennacl::vector<ScalarType> & vcl_vec,\n             viennacl::vector<ScalarType> & vcl_result,\n             viennacl::compressed_matrix<ScalarType> & vcl_compressed_matrix,\n             std::string info,\n             viennacl::linalg::amg_tag & amg_tag)\n{\n\n  viennacl::linalg::amg_precond<boost::numeric::ublas::compressed_matrix<ScalarType> > ublas_amg = viennacl::linalg::amg_precond<boost::numeric::ublas::compressed_matrix<ScalarType> > (ublas_matrix, amg_tag);\n  boost::numeric::ublas::vector<ScalarType> avgstencil;\n  unsigned int coarselevels = amg_tag.get_coarselevels();\n\n  std::cout << \"-- CG with AMG preconditioner, \" << info << \" --\" << std::endl;\n\n  std::cout << \" * Setup phase (ublas types)...\" << std::endl;\n\n  // Coarse level measure might have been changed during setup. Reload!\n  ublas_amg.tag().set_coarselevels(coarselevels);\n  ublas_amg.setup();\n\n  std::cout << \" * Operator complexity: \" << ublas_amg.calc_complexity(avgstencil) << std::endl;\n\n  amg_tag.set_coarselevels(coarselevels);\n  viennacl::linalg::amg_precond<viennacl::compressed_matrix<ScalarType> > vcl_amg = viennacl::linalg::amg_precond<viennacl::compressed_matrix<ScalarType> > (vcl_compressed_matrix, amg_tag);\n  std::cout << \" * Setup phase (ViennaCL types)...\" << std::endl;\n  vcl_amg.tag().set_coarselevels(coarselevels);\n  vcl_amg.setup();\n\n  std::cout << \" * CG solver (ublas types)...\" << std::endl;\n  //run_solver(ublas_matrix, ublas_vec, ublas_result, cg_solver, ublas_amg);\n\n  std::cout << \" * CG solver (ViennaCL types)...\" << std::endl;\n  run_solver(vcl_compressed_matrix, vcl_vec, vcl_result, cg_solver, vcl_amg);\n\n}\n\nint main()\n{\n  //\n  // Print some device info\n  //\n  std::cout << std::endl;\n  std::cout << \"----------------------------------------------\" << std::endl;\n  std::cout << \"               Device Info\" << std::endl;\n  std::cout << \"----------------------------------------------\" << std::endl;\n\n#ifdef VIENNACL_WITH_OPENCL\n  // Optional: Customize OpenCL backend\n  viennacl::ocl::platform pf = viennacl::ocl::get_platforms()[0];\n  std::vector<viennacl::ocl::device> const & devices = pf.devices();\n\n  // Optional: Set first device to first context:\n  viennacl::ocl::setup_context(0, devices[0]);\n\n  // Optional: 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  std::cout << viennacl::ocl::current_device().info() << std::endl;\n  viennacl::context ctx(viennacl::ocl::get_context(1));\n#else\n  viennacl::context ctx;\n#endif\n\n  typedef float    ScalarType;  // feel free to change this to double if supported by your device\n\n\n  //\n  // Set up the matrices and vectors for the iterative solvers (cf. iterative.cpp)\n  //\n  boost::numeric::ublas::vector<ScalarType> ublas_vec, ublas_result;\n  boost::numeric::ublas::compressed_matrix<ScalarType> ublas_matrix;\n\n  viennacl::linalg::cg_tag cg_solver;\n  viennacl::linalg::amg_tag amg_tag;\n  viennacl::linalg::amg_precond<boost::numeric::ublas::compressed_matrix<ScalarType> > ublas_amg;\n\n  // Read matrix\n  if (!viennacl::io::read_matrix_market_file(ublas_matrix, \"../examples/testdata/mat65k.mtx\"))\n  {\n    std::cout << \"Error reading Matrix file\" << std::endl;\n    return EXIT_FAILURE;\n  }\n\n  // Set up rhs and result vector\n  if (!readVectorFromFile(\"../examples/testdata/rhs65025.txt\", ublas_vec))\n  {\n    std::cout << \"Error reading RHS file\" << std::endl;\n    return 0;\n  }\n\n  if (!readVectorFromFile(\"../examples/testdata/result65025.txt\", ublas_result))\n  {\n    std::cout << \"Error reading Result file\" << std::endl;\n    return 0;\n  }\n\n  viennacl::vector<ScalarType> vcl_vec(ublas_vec.size(), ctx);\n  viennacl::vector<ScalarType> vcl_result(ublas_vec.size(), ctx);\n  viennacl::compressed_matrix<ScalarType> vcl_compressed_matrix(ublas_vec.size(), ublas_vec.size(), ctx);\n\n  // Copy to GPU\n  viennacl::copy(ublas_matrix, vcl_compressed_matrix);\n  viennacl::copy(ublas_vec, vcl_vec);\n  viennacl::copy(ublas_result, vcl_result);\n\n  //\n  // Run solver without preconditioner\n  //\n  std::cout << \"-- CG solver (CPU, no preconditioner) --\" << std::endl;\n  run_solver(ublas_matrix, ublas_vec, ublas_result, cg_solver, viennacl::linalg::no_precond());\n\n  std::cout << \"-- CG solver (GPU, no preconditioner) --\" << std::endl;\n  run_solver(vcl_compressed_matrix, vcl_vec, vcl_result, cg_solver, viennacl::linalg::no_precond());\n\n  //\n  // With AMG Preconditioner RS+DIRECT\n  //\n  amg_tag = viennacl::linalg::amg_tag(VIENNACL_AMG_COARSE_RS,       // coarsening strategy\n                                      VIENNACL_AMG_INTERPOL_DIRECT, // interpolation strategy\n                                      0.25, // strength of dependence threshold\n                                      0.2,  // interpolation weight\n                                      0.67, // jacobi smoother weight\n                                      3,    // presmoothing steps\n                                      3,    // postsmoothing steps\n                                      0);   // number of coarse levels to be used (0: automatically use as many as reasonable)\n  run_amg (cg_solver, ublas_vec, ublas_result, ublas_matrix, vcl_vec, vcl_result, vcl_compressed_matrix, \"RS COARSENING, DIRECT INTERPOLATION\", amg_tag);\n\n  //\n  // With AMG Preconditioner RS+CLASSIC\n  //\n  amg_tag = viennacl::linalg::amg_tag(VIENNACL_AMG_COARSE_RS, VIENNACL_AMG_INTERPOL_CLASSIC, 0.25, 0.2, 0.67, 3, 3, 0);\n  run_amg ( cg_solver, ublas_vec, ublas_result, ublas_matrix, vcl_vec, vcl_result, vcl_compressed_matrix, \"RS COARSENING, CLASSIC INTERPOLATION\", amg_tag);\n\n  //\n  // With AMG Preconditioner ONEPASS+DIRECT\n  //\n  amg_tag = viennacl::linalg::amg_tag(VIENNACL_AMG_COARSE_ONEPASS, VIENNACL_AMG_INTERPOL_DIRECT,0.25, 0.2, 0.67, 3, 3, 0);\n  run_amg (cg_solver, ublas_vec, ublas_result, ublas_matrix, vcl_vec, vcl_result, vcl_compressed_matrix, \"ONEPASS COARSENING, DIRECT INTERPOLATION\", amg_tag);\n\n  //\n  // With AMG Preconditioner RS0+DIRECT\n  //\n  amg_tag = viennacl::linalg::amg_tag(VIENNACL_AMG_COARSE_RS0, VIENNACL_AMG_INTERPOL_DIRECT, 0.25, 0.2, 0.67, 3, 3, 0);\n  run_amg (cg_solver, ublas_vec, ublas_result, ublas_matrix, vcl_vec, vcl_result, vcl_compressed_matrix, \"RS0 COARSENING, DIRECT INTERPOLATION\", amg_tag);\n\n  //\n  // With AMG Preconditioner RS3+DIRECT\n  //\n  amg_tag = viennacl::linalg::amg_tag(VIENNACL_AMG_COARSE_RS3, VIENNACL_AMG_INTERPOL_DIRECT, 0.25, 0.2, 0.67, 3, 3, 0);\n  run_amg (cg_solver, ublas_vec, ublas_result, ublas_matrix, vcl_vec, vcl_result, vcl_compressed_matrix, \"RS3 COARSENING, DIRECT INTERPOLATION\", amg_tag);\n\n  //\n  // With AMG Preconditioner AG\n  //\n  amg_tag = viennacl::linalg::amg_tag(VIENNACL_AMG_COARSE_AG, VIENNACL_AMG_INTERPOL_AG, 0.08, 0, 0.67, 3, 3, 0);\n  run_amg (cg_solver, ublas_vec, ublas_result, ublas_matrix, vcl_vec, vcl_result, vcl_compressed_matrix, \"AG COARSENING, AG INTERPOLATION\", amg_tag);\n\n  //\n  // With AMG Preconditioner SA\n  //\n  amg_tag = viennacl::linalg::amg_tag(VIENNACL_AMG_COARSE_AG, VIENNACL_AMG_INTERPOL_SA, 0.08, 0.67, 0.67, 3, 3, 0);\n  run_amg (cg_solver, ublas_vec, ublas_result, ublas_matrix, vcl_vec, vcl_result, vcl_compressed_matrix, \"AG COARSENING, SA INTERPOLATION\",amg_tag);\n\n\n  //\n  //  That's it.\n  //\n  std::cout << \"!!!! TUTORIAL COMPLETED SUCCESSFULLY !!!!\" << std::endl;\n\n  return EXIT_SUCCESS;\n}\n\n", "meta": {"hexsha": "585cfe722758fd92e3cd4229190924181f610893", "size": 10196, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/tutorial/amg.cpp", "max_stars_repo_name": "denis14/ViennaCL-1.5.2", "max_stars_repo_head_hexsha": "fec808905cca30196e10126681611bdf8da5297a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/tutorial/amg.cpp", "max_issues_repo_name": "denis14/ViennaCL-1.5.2", "max_issues_repo_head_hexsha": "fec808905cca30196e10126681611bdf8da5297a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/tutorial/amg.cpp", "max_forks_repo_name": "denis14/ViennaCL-1.5.2", "max_forks_repo_head_hexsha": "fec808905cca30196e10126681611bdf8da5297a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.3003952569, "max_line_length": 208, "alphanum_fraction": 0.6672224402, "num_tokens": 2924, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4758918026784482}}
{"text": "#include <boost/compute/random/normal_distribution.hpp>\n", "meta": {"hexsha": "dfa2310a118a215e4b5cba39f4e10a9af288df32", "size": 56, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_compute_random_normal_distribution.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_compute_random_normal_distribution.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_compute_random_normal_distribution.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 28.0, "max_line_length": 55, "alphanum_fraction": 0.8392857143, "num_tokens": 11, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4758918026784482}}
{"text": "#define BOOST_TEST_MODULE \"test_PWMcos_potential\"\n\n#ifdef BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n#else\n#include <boost/test/included/unit_test.hpp>\n#endif\n\n#include <mjolnir/forcefield/PWMcos/PWMcosPotential.hpp>\n\nBOOST_AUTO_TEST_CASE(PWMcos_Potential_f)\n{\n    mjolnir::LoggerManager::set_default_logger(\"test_pwmcos_potential.log\");\n\n    using real_type = double;\n    using potential_type = mjolnir::PWMcosPotential<real_type>;\n\n    constexpr std::size_t N = 1000;\n    constexpr real_type   h = 1e-6;\n\n    potential_type potential;\n\n    const real_type r_0   = 7.0;\n    const real_type r_min = 1.0;\n    const real_type r_max = 15.0;\n    const real_type dr    = (r_max - r_min) / N;\n\n    const real_type rsigma = 1.0;\n\n    for(std::size_t i=0; i<N; ++i)\n    {\n        const real_type r   = r_min + i * dr;\n        const real_type f1  = potential.f(r_0, r + h, rsigma);\n        const real_type f2  = potential.f(r_0, r - h, rsigma);\n        const real_type df_numeric  = (f1 - f2) / (2 * h);\n        const real_type df_analytic = potential.f_df(r_0, r, rsigma).second;\n\n        if((f1 == 0.0 || f2 == 0.0) && !(f1 == 0.0 && f2 == 0.0))\n        {\n            // the numeric differentiation becomes unstable here.\n        }\n        else\n        {\n            BOOST_TEST(df_numeric == df_analytic, boost::test_tools::tolerance(h));\n        }\n\n        const real_type f1_ = potential.f_df(r_0, r+h, rsigma).first;\n        const real_type f2_ = potential.f_df(r_0, r-h, rsigma).first;\n        BOOST_TEST(f1 == f1_, boost::test_tools::tolerance(h));\n        BOOST_TEST(f2 == f2_, boost::test_tools::tolerance(h));\n    }\n}\n\nBOOST_AUTO_TEST_CASE(PWMcos_Potential_g)\n{\n    mjolnir::LoggerManager::set_default_logger(\"test_pwmcos_potential.log\");\n\n    using real_type = double;\n    using potential_type = mjolnir::PWMcosPotential<real_type>;\n\n    constexpr std::size_t N = 1000;\n    constexpr real_type   h = 1e-6;\n    constexpr real_type  pi = mjolnir::math::constants<real_type>::pi();\n\n    potential_type potential;\n\n    const real_type theta_0   = pi * 0.5;\n    const real_type theta_min = pi * 0.3;\n    const real_type theta_max = pi * 0.7;\n    const real_type dtheta    = (theta_max - theta_min) / N;\n\n    const real_type delta = pi / 18.0;\n    const real_type delta2 = delta * 2;\n    const real_type pi_over_2delta = pi / delta2;\n\n    for(std::size_t i=0; i<N; ++i)\n    {\n        const real_type theta = theta_min + i * dtheta;\n        const real_type g1  = potential.g(theta_0, theta + h, delta, delta2, pi_over_2delta);\n        const real_type g2  = potential.g(theta_0, theta - h, delta, delta2, pi_over_2delta);\n        const real_type dg_numeric  = (g1 - g2) / (2 * h);\n        const real_type dg_analytic = potential.g_dg(theta_0, theta, delta, delta2, pi_over_2delta).second;\n\n        if((g1 == 0.0 || g2 == 0.0) && !(g1 == 0.0 && g2 == 0.0))\n        {\n            // the numeric differentiation becomes unstable here.\n        }\n        else\n        {\n            BOOST_TEST(dg_numeric == dg_analytic, boost::test_tools::tolerance(h));\n        }\n        const real_type g1_ = potential.g_dg(theta_0, theta+h, delta, delta2, pi_over_2delta).first;\n        const real_type g2_ = potential.g_dg(theta_0, theta-h, delta, delta2, pi_over_2delta).first;\n        BOOST_TEST(g1 == g1_, boost::test_tools::tolerance(h));\n        BOOST_TEST(g2 == g2_, boost::test_tools::tolerance(h));\n    }\n}\n", "meta": {"hexsha": "d4c8937a8096c7c10e45b5c9410e14622d0accdc", "size": 3404, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/core/test_pwmcos_potential.cpp", "max_stars_repo_name": "ToruNiina/Mjolnir", "max_stars_repo_head_hexsha": "44435dd3afc12f5c8ea27a66d7ab282df3e588ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2017-02-01T08:28:38.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-25T15:47:51.000Z", "max_issues_repo_path": "test/core/test_pwmcos_potential.cpp", "max_issues_repo_name": "Mjolnir-MD/Mjolnir", "max_issues_repo_head_hexsha": "043df4080720837042c6b67a5495ecae198bc2b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 60.0, "max_issues_repo_issues_event_min_datetime": "2019-01-14T08:11:33.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-29T08:26:36.000Z", "max_forks_repo_path": "test/core/test_pwmcos_potential.cpp", "max_forks_repo_name": "Mjolnir-MD/Mjolnir", "max_forks_repo_head_hexsha": "043df4080720837042c6b67a5495ecae198bc2b3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2019-01-13T11:03:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-01T11:38:00.000Z", "avg_line_length": 34.7346938776, "max_line_length": 107, "alphanum_fraction": 0.6351351351, "num_tokens": 1032, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4758918026784482}}
{"text": "#include <geometry.h>\n#include <tiny.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n\ntypedef tiny::MathTypes<float> MT;\ntypedef MT::quaternion_type    Q;\ntypedef MT::vector3_type       V;\ntypedef MT::real_type          T;\ntypedef MT::value_traits       VT;\n\n\nBOOST_AUTO_TEST_SUITE(geometry);\n\nBOOST_AUTO_TEST_CASE(overlap_obb_obb_test)\n{\n  // touching bottom-top faces\n  {\n    V const centerA   = V::make(0.0, 0.0, 0.0);\n    V const half_extA = V::make(1.0, 1.0, 1.0);\n    Q const qA        = Q::identity();\n\n    geometry::OBB<MT> obbA = geometry::make_obb<MT>(centerA, qA, half_extA);\n\n    V const centerB   = V::make(0.0, -2.0, 0.0);\n    V const half_extB = V::make(1.0, 1.0, 1.0);\n    Q const qB        = Q::Ry(VT::pi_quarter());\n\n    geometry::OBB<MT> obbB = geometry::make_obb<MT>(centerB, qB, half_extB);\n\n    bool const test1 = geometry::overlap_obb_obb(obbA,obbB);\n    bool const test2 = geometry::overlap_obb_obb(obbB,obbA);\n\n    BOOST_CHECK(test1);\n    BOOST_CHECK(test2);\n  }\n  // touching left-right faces\n  {\n    V const centerA   = V::make(0.0, 0.0, 0.0);\n    V const half_extA = V::make(1.0, 1.0, 1.0);\n    Q const qA        = Q::identity();\n\n    geometry::OBB<MT> obbA = geometry::make_obb<MT>(centerA, qA, half_extA);\n\n    V const centerB   = V::make(2.0, 0.0, 0.0);\n    V const half_extB = V::make(1.0, 1.0, 1.0);\n    Q const qB        = Q::Rx(VT::pi_quarter());\n\n    geometry::OBB<MT> obbB = geometry::make_obb<MT>(centerB, qB, half_extB);\n\n    bool const test1 = geometry::overlap_obb_obb(obbA,obbB);\n    bool const test2 = geometry::overlap_obb_obb(obbB,obbA);\n\n    BOOST_CHECK(test1);\n    BOOST_CHECK(test2);\n  }\n  // touching front-back faces\n  {\n    V const centerA   = V::make(0.0, 0.0, 0.0);\n    V const half_extA = V::make(1.0, 1.0, 1.0);\n    Q const qA        = Q::identity();\n\n    geometry::OBB<MT> obbA = geometry::make_obb<MT>(centerA, qA, half_extA);\n\n    V const centerB   = V::make(0.0, 0.0, 2.0);\n    V const half_extB = V::make(1.0, 1.0, 1.0);\n    Q const qB        = Q::Rz(VT::pi_quarter());\n\n    geometry::OBB<MT> obbB = geometry::make_obb<MT>(centerB, qB, half_extB);\n\n    bool const test1 = geometry::overlap_obb_obb(obbA,obbB);\n    bool const test2 = geometry::overlap_obb_obb(obbB,obbA);\n\n    BOOST_CHECK(test1);\n    BOOST_CHECK(test2);\n  }\n  // separating bottom-top faces\n  {\n    V const centerA   = V::make(0.0, 0.0, 0.0);\n    V const half_extA = V::make(1.0, 1.0, 1.0);\n    Q const qA        = Q::identity();\n\n    geometry::OBB<MT> obbA = geometry::make_obb<MT>(centerA, qA, half_extA);\n\n    V const centerB   = V::make(0.0, -2.1, 0.0);\n    V const half_extB = V::make(1.0, 1.0, 1.0);\n    Q const qB        = Q::Ry(VT::pi_quarter());\n\n    geometry::OBB<MT> obbB = geometry::make_obb<MT>(centerB, qB, half_extB);\n\n    bool const test1 = geometry::overlap_obb_obb(obbA,obbB);\n    bool const test2 = geometry::overlap_obb_obb(obbB,obbA);\n\n    BOOST_CHECK(!test1);\n    BOOST_CHECK(!test2);\n  }\n  // separating left-right faces\n  {\n    V const centerA   = V::make(0.0, 0.0, 0.0);\n    V const half_extA = V::make(1.0, 1.0, 1.0);\n    Q const qA        = Q::identity();\n\n    geometry::OBB<MT> obbA = geometry::make_obb<MT>(centerA, qA, half_extA);\n\n    V const centerB   = V::make(2.1, 0.0, 0.0);\n    V const half_extB = V::make(1.0, 1.0, 1.0);\n    Q const qB        = Q::Rx(VT::pi_quarter());\n\n    geometry::OBB<MT> obbB = geometry::make_obb<MT>(centerB, qB, half_extB);\n\n    bool const test1 = geometry::overlap_obb_obb(obbA,obbB);\n    bool const test2 = geometry::overlap_obb_obb(obbB,obbA);\n\n    BOOST_CHECK(!test1);\n    BOOST_CHECK(!test2);\n  }\n  // separating front-back faces\n  {\n    V const centerA   = V::make(0.0, 0.0, 0.0);\n    V const half_extA = V::make(1.0, 1.0, 1.0);\n    Q const qA        = Q::identity();\n\n    geometry::OBB<MT> obbA = geometry::make_obb<MT>(centerA, qA, half_extA);\n\n    V const centerB   = V::make(0.0, 0.0, 2.1);\n    V const half_extB = V::make(1.0, 1.0, 1.0);\n    Q const qB        = Q::Rz(VT::pi_quarter());\n\n    geometry::OBB<MT> obbB = geometry::make_obb<MT>(centerB, qB, half_extB);\n\n    bool const test1 = geometry::overlap_obb_obb(obbA,obbB);\n    bool const test2 = geometry::overlap_obb_obb(obbB,obbA);\n    \n    BOOST_CHECK(!test1);\n    BOOST_CHECK(!test2);\n  }\n  // A inside of B\n  {\n    V const centerA   = V::make(0.0, 0.0, 0.0);\n    V const half_extA = V::make(0.5, 0.5, 0.5);\n    Q const qA        = Q::identity();\n\n    geometry::OBB<MT> obbA = geometry::make_obb<MT>(centerA, qA, half_extA);\n\n    V const centerB   = V::make(0.0, 0.0, 0.0);\n    V const half_extB = V::make(1.0, 1.0, 1.0);\n    Q const qB        = Q::Ry(VT::pi_quarter());\n\n    geometry::OBB<MT> obbB = geometry::make_obb<MT>(centerB, qB, half_extB);\n\n    bool const test1 = geometry::overlap_obb_obb(obbA,obbB);\n    bool const test2 = geometry::overlap_obb_obb(obbB,obbA);\n\n    BOOST_CHECK(test1);\n    BOOST_CHECK(test2);\n  }\n  // B inside of A\n  {\n    V const centerA   = V::make(0.0, 0.0, 0.0);\n    V const half_extA = V::make(1.0, 1.0, 1.0);\n    Q const qA        = Q::identity();\n\n    geometry::OBB<MT> obbA = geometry::make_obb<MT>(centerA, qA, half_extA);\n\n    V const centerB   = V::make(0.0, 0.0, 0.0);\n    V const half_extB = V::make(0.5, 0.5, 0.5);\n    Q const qB        = Q::Ry(VT::pi_quarter());\n\n    geometry::OBB<MT> obbB = geometry::make_obb<MT>(centerB, qB, half_extB);\n\n    bool const test1 = geometry::overlap_obb_obb(obbA,obbB);\n    bool const test2 = geometry::overlap_obb_obb(obbB,obbA);\n\n    BOOST_CHECK(test1);\n    BOOST_CHECK(test2);\n  }\n  // touching edge-edge-case\n  {\n    V const centerA   = V::make(0.0, 0.0, 0.0);\n    V const half_extA = V::make(1.0, 1.0, 1.0);\n    Q const qA        = Q::identity();\n\n    geometry::OBB<MT> obbA = geometry::make_obb<MT>(centerA, qA, half_extA);\n\n    V const centerB   = V::make(2.0, 2.0, 0.0);\n    V const half_extB = V::make(1.0, 1.0, 1.0);\n    Q const qB        = Q::Ru(VT::pi_half(), centerB );\n\n    geometry::OBB<MT> obbB = geometry::make_obb<MT>(centerB, qB, half_extB);\n\n    bool const test1 = geometry::overlap_obb_obb(obbA,obbB);\n    bool const test2 = geometry::overlap_obb_obb(obbB,obbA);\n\n    BOOST_CHECK(test1);\n    BOOST_CHECK(test2);\n  }\n  // separating edge-edge-case\n  {\n    V const centerA   = V::make(0.0, 0.0, 0.0);\n    V const half_extA = V::make(1.0, 1.0, 1.0);\n    Q const qA        = Q::identity();\n\n    geometry::OBB<MT> obbA = geometry::make_obb<MT>(centerA, qA, half_extA);\n\n    V const centerB   = V::make(2.01, 2.01, 0.0);\n    V const half_extB = V::make(1.0, 1.0, 1.0);\n    Q const qB        = Q::Ru(VT::pi_half(), centerB );\n\n    geometry::OBB<MT> obbB = geometry::make_obb<MT>(centerB, qB, half_extB);\n\n    bool const test1 = geometry::overlap_obb_obb(obbA,obbB);\n    bool const test2 = geometry::overlap_obb_obb(obbB,obbA);\n\n    BOOST_CHECK(!test1);\n    BOOST_CHECK(!test2);\n  }\n\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "bdd4ea21d1437fe2ca21cba215780bd71bab5eb3", "size": 7019, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/FOUNDATION/GEOMETRY/unit_tests/geometry_overlap_obb_obb/geometry_overlap_obb_obb.cpp", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-11-27T09:44:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-13T00:24:21.000Z", "max_issues_repo_path": "PROX/FOUNDATION/GEOMETRY/unit_tests/geometry_overlap_obb_obb/geometry_overlap_obb_obb.cpp", "max_issues_repo_name": "erleben/matchstick", "max_issues_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_issues_repo_licenses": ["MIT"], "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/FOUNDATION/GEOMETRY/unit_tests/geometry_overlap_obb_obb/geometry_overlap_obb_obb.cpp", "max_forks_repo_name": "erleben/matchstick", "max_forks_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_forks_repo_licenses": ["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.1955555556, "max_line_length": 76, "alphanum_fraction": 0.6117680581, "num_tokens": 2650, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851919, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4758917961283255}}
{"text": "#include \"GridUtils.h\"\n\n#include <queue>\n#include <Eigen/SparseCore>\n#include <Eigen/IterativeLinearSolvers>\n#include <cassert>\n#include <LBFGS.h>\n\n#include \"GradientDescent.h\"\n\nar::real ar::GridUtils2D::getLinearClampedF(const real* linear, real x, real y, int width, int height)\n{\n    int ix = static_cast<int>(x);\n    int iy = static_cast<int>(y);\n    real fx = x - ix;\n    real fy = y - iy;\n    real v00 = getLinearClamped(linear, ix, iy, width, height);\n    real v10 = getLinearClamped(linear, ix + 1, iy, width, height);\n    real v01 = getLinearClamped(linear, ix, iy + 1, width, height);\n    real v11 = getLinearClamped(linear, ix + 1, iy + 1, width, height);\n    real v0 = v00 + fx * (v01 - v00); //correct???\n    real v1 = v10 + fx * (v11 - v10);\n    return v0 + fy * (v1 - v0);\n}\n\nconst ar::real& ar::GridUtils2D::getClamped(const grid_t& grid, int x, int y)\n{\n    int width = (int)grid.rows();\n    int height = (int)grid.cols();\n    clampCoord(x, y, width, height);\n    return grid(x, y);\n}\n\nar::real& ar::GridUtils2D::atClamped(grid_t& grid, int x, int y)\n{\n    int width = (int)grid.rows();\n    int height = (int)grid.cols();\n    clampCoord(x, y, width, height);\n    return grid(x, y);\n}\n\nar::real ar::GridUtils2D::getClampedF(const grid_t& grid, real x, real y)\n{\n    int ix = static_cast<int>(x);\n    int iy = static_cast<int>(y);\n    real fx = x - ix;\n    real fy = y - iy;\n    real v00 = getClamped(grid, ix, iy);\n    real v10 = getClamped(grid, ix + 1, iy);\n    real v01 = getClamped(grid, ix, iy + 1);\n    real v11 = getClamped(grid, ix + 1, iy + 1);\n    real v0 = v00 + fy * (v01 - v00);\n    real v1 = v10 + fy * (v11 - v10);\n    return v0 + fx * (v1 - v0);\n}\n\nar::GridUtils2D::grad_t ar::GridUtils2D::getGradientLinear(const real* linear, int x, int y, int width, int height)\n{\n    grad_t grad;\n    //x\n    if (x == 0)\n        grad.x() = getLinear(linear, x + 1, y, width) - getLinear(linear, x, y, width); //forward\n    else if (x == width - 1)\n        grad.x() = getLinear(linear, x, y, width) - getLinear(linear, x - 1, y, width); //backward\n    else\n        grad.x() = 0.5 * (getLinear(linear, x + 1, y, width) - getLinear(linear, x - 1, y, width)); //central\n\n    //y\n    if (y == 0)\n        grad.y() = getLinear(linear, x, y + 1, width) - getLinear(linear, x, y, width); //forward\n    else if (y == height - 1)\n        grad.y() = getLinear(linear, x, y, width) - getLinear(linear, x, y - 1, width); //backward\n    else\n        grad.y() = 0.5 * (getLinear(linear, x, y + 1, width) - getLinear(linear, x, y - 1, width)); //central\n\n    return grad;\n}\n\nar::GridUtils2D::grad_t ar::GridUtils2D::getGradient(const grid_t& grid, Eigen::Index i, Eigen::Index j)\n{\n\tgrad_t grad;\n\t//x\n\tif (i == 0)\n\t\tgrad.x() = grid(i + 1, j) - grid(i, j); //forward\n\telse if (i == grid.rows() - 1)\n\t\tgrad.x() = grid(i, j) - grid(i - 1, j); //backward\n\telse\n\t\tgrad.x() = 0.5 * (grid(i + 1, j) - grid(i - 1, j)); //central\n\n\t//y\n\tif (j == 0)\n\t\tgrad.y() = grid(i, j + 1) - grid(i, j); //forward\n\telse if (j == grid.cols() - 1)\n\t\tgrad.y() = grid(i, j) - grid(i, j - 1); //backward\n\telse\n\t\tgrad.y() = 0.5 * (grid(i, j + 1) - grid(i, j - 1)); //central\n\n\treturn grad;\n}\n\nar::real ar::GridUtils2D::getGradientPosLinear(const real* linear, int x, int y, int width, int height)\n{\n    real val = real(0);\n    //x\n    if (x == 0)\n        val += ar::utils::sqr(getLinear(linear, x + 1, y, width) - getLinear(linear, x, y, width));\n    else if (x == width - 1)\n        val += ar::utils::sqr(getLinear(linear, x, y, width) - getLinear(linear, x - 1, y, width));\n    else\n        val += ar::utils::sqr(std::max(real(0), getLinear(linear, x, y, width) - getLinear(linear, x - 1, y, width)))\n            + ar::utils::sqr(std::min(real(0), getLinear(linear, x + 1, y, width) - getLinear(linear, x, y, width)));\n\n    //y\n    if (y == 0)\n        val += ar::utils::sqr(getLinear(linear, x, y + 1, width) - getLinear(linear, x, y, width));\n    else if (y == height - 1)\n        val += ar::utils::sqr(getLinear(linear, x, y, width) - getLinear(linear, x, y - 1, width));\n    else\n        val += ar::utils::sqr(std::max(real(0), getLinear(linear, x, y, width) - getLinear(linear, x, y - 1, width)))\n            + ar::utils::sqr(std::min(real(0), getLinear(linear, x, y + 1, width) - getLinear(linear, x, y, width)));\n\n    return std::sqrt(val);\n}\n\nar::real ar::GridUtils2D::getGradientNegLinear(const real* linear, int x, int y, int width, int height)\n{\n    real val = real(0);\n    //x\n    if (x == 0)\n        val += ar::utils::sqr(getLinear(linear, x + 1, y, width) - getLinear(linear, x, y, width));\n    else if (x == width - 1)\n        val += ar::utils::sqr(getLinear(linear, x, y, width) - getLinear(linear, x - 1, y, width));\n    else\n        val += ar::utils::sqr(std::min(real(0), getLinear(linear, x, y, width) - getLinear(linear, x - 1, y, width)))\n            + ar::utils::sqr(std::max(real(0), getLinear(linear, x + 1, y, width) - getLinear(linear, x, y, width)));\n\n    //y\n    if (y == 0)\n        val += ar::utils::sqr(getLinear(linear, x, y + 1, width) - getLinear(linear, x, y, width));\n    else if (y == height - 1)\n        val += ar::utils::sqr(getLinear(linear, x, y, width) - getLinear(linear, x, y - 1, width));\n    else\n        val += ar::utils::sqr(std::min(real(0), getLinear(linear, x, y, width) - getLinear(linear, x, y - 1, width)))\n            + ar::utils::sqr(std::max(real(0), getLinear(linear, x, y + 1, width) - getLinear(linear, x, y, width)));\n\n    return std::sqrt(val);\n}\n\nar::GridUtils2D::grad_t ar::GridUtils2D::getGradientLinearF(const real* linear, real x, real y, int width, int height)\n{\n    grad_t grad;\n    grad.x() = getLinearClampedF(linear, x + 0.5f, y, width, height) - getLinearClampedF(\n        linear, x - 0.5f, y, width, height);\n    grad.y() = getLinearClampedF(linear, x, y + 0.5f, width, height) - getLinearClampedF(\n        linear, x, y - 0.5f, width, height);\n    return grad;\n}\n\nar::real ar::GridUtils2D::getLaplacianLinear(const real* linear, int x, int y, int width, int height)\n{\n    real laplacian = real(0);\n    //x\n    if (x == 0)\n        laplacian += getLinear(linear, x, y, width) - 2 * getLinear(linear, x + 1, y, width) + getLinear(\n            linear, x + 2, y, width);\n    else if (x == width - 1)\n        laplacian += getLinear(linear, x - 2, y, width) - 2 * getLinear(linear, x - 1, y, width) + getLinear(\n            linear, x, y, width);\n    else\n        laplacian += getLinear(linear, x - 1, y, width) - 2 * getLinear(linear, x, y, width) + getLinear(\n            linear, x + 1, y, width);\n\n    //y\n    if (y == 0)\n        laplacian += getLinear(linear, x, y, width) - 2 * getLinear(linear, x, y + 1, width) + getLinear(\n            linear, x, y + 2, width);\n    else if (y == height - 1)\n        laplacian += getLinear(linear, x, y - 2, width) - 2 * getLinear(linear, x, y - 1, width) + getLinear(\n            linear, x, y, width);\n    else\n        laplacian += getLinear(linear, x, y - 1, width) - 2 * getLinear(linear, x, y, width) + getLinear(\n            linear, x, y + 1, width);\n\n    return laplacian;\n}\n\nar::real ar::GridUtils2D::getLaplacian(const grid_t & grid, Eigen::Index i, Eigen::Index j)\n{\n\treal laplacian = real(0);\n\n\t//x\n\tif (i == 0)\n\t\tlaplacian += grid(i, j) - 2 * grid(i + 1, j) + grid(i + 2, j);\n\telse if (i == grid.rows() - 1)\n\t\tlaplacian += grid(i - 2, j) - 2 * grid(i - 1, j) + grid(i, j);\n\telse\n\t\tlaplacian += grid(i - 1, j) - 2 * grid(i, j) + grid(i + 1, j);\n\n\t//j\n\tif (j == 0)\n\t\tlaplacian += grid(i, j) - 2 * grid(i, j + 1) + grid(i, j + 2);\n\telse if (j == grid.cols() - 1)\n\t\tlaplacian += grid(i, j - 2) - 2 * grid(i, j - 1) + grid(i, j);\n\telse\n\t\tlaplacian += grid(i, j - 1) - 2 * grid(i, j) + grid(i, j + 1);\n\n\treturn laplacian;\n}\n\nstd::pair<ar::GridUtils2D::grid_t, ar::GridUtils2D::grid_t> ar::GridUtils2D::getFullGradient(const grid_t & v)\n{\n\tEigen::Index rows = v.rows();\n\tEigen::Index cols = v.cols();\n\tgrid_t dx(rows, cols);\n\tgrid_t dy(rows, cols);\n\n\tfor (Eigen::Index j = 0; j<cols; ++j)\n\t{\n\t\tfor (Eigen::Index i = 0; i<rows; ++i)\n\t\t{\n\t\t\tgrad_t g = getGradient(v, i, j);\n\t\t\tdx(i, j) = g.x();\n\t\t\tdy(i, j) = g.y();\n\t\t}\n\t}\n\n\treturn std::make_pair(dx, dy);\n}\n\nar::GridUtils2D::grid_t ar::GridUtils2D::getFullLaplacian(const grid_t & v)\n{\n\tEigen::Index rows = v.rows();\n\tEigen::Index cols = v.cols();\n\tgrid_t laplacian(rows, cols);\n\n\tfor (Eigen::Index j = 0; j<cols; ++j)\n\t{\n\t\tfor (Eigen::Index i = 0; i<rows; ++i)\n\t\t{\n\t\t\tlaplacian(i, j) = getLaplacian(v, i, j);\n\t\t}\n\t}\n\n\treturn laplacian;\n}\n\nar::GridUtils2D::grid_t ar::GridUtils2D::fillGrid(const grid_t& input, const bgrid_t& valid)\n{\n    int width = (int)input.rows();\n    int height = (int)input.cols();\n    grid_t grids[2] = {input, grid_t(width, height)};\n    bgrid_t filled[2] = {valid, bgrid_t(width, height)};\n    for (int i = 0; ; ++i)\n    {\n        bool hasChanges = false;\n        int ci = i % 2;\n        int ni = 1 - ci;\n        for (int y = 0; y < height; ++y)\n        {\n            for (int x = 0; x < width; ++x)\n            {\n                if (filled[ci](x, y))\n                {\n                    filled[ni](x, y) = true;\n                    grids[ni](x, y) = grids[ci](x, y);\n                    continue;\n                }\n                real avg = real(0);\n                int count = 0;\n                if (x - 1 >= 0 && filled[ci](x - 1, y))\n                {\n                    avg += grids[ci](x - 1, y);\n                    count++;\n                }\n                if (x + 1 < width && filled[ci](x + 1, y))\n                {\n                    avg += grids[ci](x + 1, y);\n                    count++;\n                }\n                if (y - 1 >= 0 && filled[ci](x, y - 1))\n                {\n                    avg += grids[ci](x, y - 1);\n                    count++;\n                }\n                if (y + 1 < height && filled[ci](x, y + 1))\n                {\n                    avg += grids[ci](x, y + 1);\n                    count++;\n                }\n                if (count > 0)\n                {\n                    filled[ni](x, y) = true;\n                    grids[ni](x, y) = avg / count;\n                    hasChanges = true;\n                }\n                else\n                    filled[ni](x, y) = false;\n            }\n        }\n        if (!hasChanges)\n        {\n            return grids[ni];\n        }\n    }\n}\n\nar::GridUtils2D::grid_t ar::GridUtils2D::fillGridDiffusion(const grid_t& input, const bgrid_t& valid)\n{\n    //find number of unknowns\n    int width = (int)input.rows();\n    int height = (int)input.cols();\n\tEigen::Index numEmpty = 0;\n\tigrid_t indices = igrid_t::Constant(width, height, -1);\n\tfor (int y = 0; y < height; ++y)\n\t{\n\t\tfor (int x = 0; x < width; ++x)\n\t\t{\n\t\t\tif (!valid(x, y)) {\n\t\t\t\tindices(x, y) = numEmpty;\n\t\t\t\tnumEmpty++;\n\t\t\t}\n\t\t}\n\t}\n\n    //build matrix\n    std::vector<Eigen::Triplet<real>> entries;\n\tentries.reserve(5 * numEmpty);\n\tVectorX rhs = VectorX::Zero(numEmpty);\n\tconst int neighborsX[] = { -1, 1, 0, 0 };\n\tconst int neighborsY[] = { 0, 0, -1, 1 };\n\tfor (int y = 0; y < height; ++y)\n\t{\n\t\tfor (int x = 0; x < width; ++x)\n\t\t{\n\t\t\tif (!valid(x, y)) {\n\t\t\t\tint row = indices(x, y);\n\t\t\t\tint c = 0;\n\t\t\t\tfor (int i = 0; i < 4; ++i) {\n\t\t\t\t\tint ix = x + neighborsX[i];\n\t\t\t\t\tint iy = y + neighborsY[i];\n\t\t\t\t\tif (ix < 0 || ix >= width || iy < 0 || iy >= height) continue; //outside, Neumann boundary\n\t\t\t\t\tif (valid(ix, iy)) {\n\t\t\t\t\t\t//dirichlet boundary\n\t\t\t\t\t\trhs[indices(x, y)] += input(ix, iy);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\t//inside\n\t\t\t\t\t\tentries.emplace_back(row, indices(ix, iy), -1);\n\t\t\t\t\t}\n\t\t\t\t\tc++;\n\t\t\t\t}\n\t\t\t\tentries.emplace_back(row, row, c);\n\t\t\t}\n\t\t}\n\t}\n\tEigen::SparseMatrix<real> M(numEmpty, numEmpty);\n\tM.setFromTriplets(entries.begin(), entries.end());\n\n    //Solve it\n\tEigen::ConjugateGradient<Eigen::SparseMatrix<real>> cg(M);\n\tVectorX r = cg.solve(rhs);\n\n\t//Map back\n\tgrid_t result(width, height);\n\tfor (int y = 0; y < height; ++y)\n\t{\n\t\tfor (int x = 0; x < width; ++x)\n\t\t{\n\t\t\tif (!valid(x, y))\n\t\t\t\tresult(x, y) = r[indices(x, y)];\n\t\t\telse\n\t\t\t\tresult(x, y) = input(x, y);\n\t\t}\n\t}\n\treturn result;\n}\n\nvoid ar::GridUtils2D::fillGridDiffusionAdjoint(grid_t& adjInput, const grid_t& adjOutput, const grid_t& input,\n    const bgrid_t& valid)\n{\n    //find number of unknowns\n    int width = (int)input.rows();\n    int height = (int)input.cols();\n    Eigen::Index numEmpty = 0;\n    igrid_t indices = igrid_t::Constant(width, height, -1);\n    for (int y = 0; y < height; ++y)\n    {\n        for (int x = 0; x < width; ++x)\n        {\n            if (!valid(x, y)) {\n                indices(x, y) = numEmpty;\n                numEmpty++;\n            }\n        }\n    }\n\n    //build matrix\n    std::vector<Eigen::Triplet<real>> entries;\n    entries.reserve(5 * numEmpty);\n    VectorX rhs = VectorX::Zero(numEmpty);\n    const int neighborsX[] = { -1, 1, 0, 0 };\n    const int neighborsY[] = { 0, 0, -1, 1 };\n    for (int y = 0; y < height; ++y)\n    {\n        for (int x = 0; x < width; ++x)\n        {\n            if (!valid(x, y)) {\n                int row = indices(x, y);\n                int c = 0;\n                for (int i = 0; i < 4; ++i) {\n                    int ix = x + neighborsX[i];\n                    int iy = y + neighborsY[i];\n                    if (ix < 0 || ix >= width || iy < 0 || iy >= height) continue; //outside, Neumann boundary\n                    if (valid(ix, iy)) {\n                        //dirichlet boundary\n                        rhs[indices(x, y)] += adjOutput(ix, iy);\n                    }\n                    else {\n                        //inside\n                        entries.emplace_back(indices(ix, iy), row, -1);\n                    }\n                    c++;\n                }\n                entries.emplace_back(row, row, c);\n            }\n        }\n    }\n    Eigen::SparseMatrix<real> M(numEmpty, numEmpty);\n    M.setFromTriplets(entries.begin(), entries.end());\n\n    //Solve it\n    Eigen::ConjugateGradient<Eigen::SparseMatrix<real>> cg(M);\n    VectorX r = cg.solve(rhs);\n\n    //Map back\n    grid_t result(width, height);\n    for (int y = 0; y < height; ++y)\n    {\n        for (int x = 0; x < width; ++x)\n        {\n            if (!valid(x, y))\n                adjInput(x, y) += r[indices(x, y)];\n        }\n    }\n}\n\nvoid ar::GridUtils2D::invertDisplacementDirectShepard(const grid_t& inputX, const grid_t& inputY, grid_t& outputX,\n                                                      grid_t& outputY, real h)\n{\n    int width = (int)inputX.rows();\n    int height = (int)inputX.cols();\n    //find max displacement -> radius\n    real maxDisp = sqrt((inputX * inputX + inputY * inputY).maxCoeff()) + 2 * h;\n    int radius = static_cast<int>(ceil(maxDisp / h));\n    //run the shepard interpolation\n    //#pragma omp parallel for schedule(dynamic,8)\n    for (int y = 0; y < height; ++y)\n    {\n        for (int x = 0; x < width; ++x)\n        {\n            vec2_t v(0, 0);\n            real w = 0;\n            vec2_t p1(x * h, y * h);\n            for (int iy = std::max(0, y - radius); iy <= std::min(height - 1, y + radius); iy++)\n            {\n                for (int ix = std::max(0, x - radius); ix <= std::min(width - 1, x + radius); ix++)\n                {\n                    vec2_t u(inputX(ix, iy), inputY(ix, iy));\n                    vec2_t p2 = vec2_t(ix * h, iy * h) + u;\n                    real d = (p1 - p2).norm() + 0.000000001;\n                    if (d <= maxDisp)\n                    {\n                        real wi = (1 / d - 1 / maxDisp);\n                        wi *= wi;\n                        v += wi * u;\n                        w += wi;\n                    }\n                }\n            }\n            if (w > 0)\n            {\n                v /= w;\n            }\n            outputX(x, y) = v.x();\n            outputY(x, y) = v.y();\n        }\n    }\n}\n\nvoid ar::GridUtils2D::invertDisplacementDirectShepardAdjoint(\n    grid_t& adjInputX, grid_t& adjInputY,\n    const grid_t& adjOutputX, const grid_t& adjOutputY, \n    const grid_t& inputX, const grid_t& inputY, const grid_t& outputX, const grid_t& outputY,\n    real h)\n{\n    int width = (int)inputX.rows();\n    int height = (int)inputX.cols();\n    //find max displacement -> radius\n    real maxDisp = sqrt((inputX * inputX + inputY * inputY).maxCoeff()) + 2 * h;\n    int radius = static_cast<int>(ceil(maxDisp / h));\n    //compute the adjoint of the shepard interpolation\n    for (int y = height - 1; y >= 0; --y)\n    {\n        for (int x = width - 1; x>=0; --x)\n        {\n            //compute terms that are needed from the forward pass\n            real w = 0;\n            vec2_t p1(x * h, y * h);\n            for (int iy = std::max(0, y - radius); iy <= std::min(height - 1, y + radius); iy++)\n            {\n                for (int ix = std::max(0, x - radius); ix <= std::min(width - 1, x + radius); ix++)\n                {\n                    vec2_t u(inputX(ix, iy), inputY(ix, iy));\n                    vec2_t p2 = vec2_t(ix * h, iy * h) + u;\n                    real d = (p1 - p2).norm() + 0.000000001;\n                    if (d <= maxDisp)\n                    {\n                        real wi = square(1 / d - 1 / maxDisp);\n                        w += wi;\n                    }\n                }\n            }\n            assert(w > 0);\n            \n            vec2_t adjOutput(adjOutputX(x, y), adjOutputY(x, y));\n            vec2_t adjV = adjOutput / w;\n            real adjW = -(vec2_t(outputX(x, y), outputY(x, y)) / (w*w)).dot(adjV);\n\n            //compute adjoint, add it to the gradient of each component\n            for (int iy = std::min(height - 1, y + radius); iy >= std::max(0, y - radius); --iy)\n            {\n                for (int ix = std::min(width - 1, x + radius); ix >= std::max(0, x - radius); --ix)\n                {\n                    vec2_t u(inputX(ix, iy), inputY(ix, iy));\n                    vec2_t p2 = vec2_t(ix * h, iy * h) + u;\n                    real d = (p1 - p2).norm() + 0.000000001;\n                    if (d <= maxDisp)\n                    {\n                        real wi = square(1 / d - 1 / maxDisp);\n                        real adjWi = adjW;\n                        vec2_t adjU = wi * adjV;\n                        adjWi += u.dot(adjV);\n                        real adjD = -(2 / square(d)) * (1 / d - 1 / maxDisp) * adjWi;\n\n                        adjU += (p2 - p1) / d * adjD;\n                        adjInputX(ix, iy) += adjU.x();\n                        adjInputY(ix, iy) += adjU.y();\n                    }\n                }\n            }\n        }\n    }\n}\n\nvoid ar::GridUtils2D::invertDisplacement(const grid_t& inputX, const grid_t& inputY, grid_t& outputX, grid_t& outputY,\n                                         real h)\n{\n    invertDisplacementDirectShepard(inputX, inputY, outputX, outputY, h);\n    //TODO: global optimization\n}\n\nar::GridUtils2D::grid_t ar::GridUtils2D::advectGridSemiLagrange(const grid_t& input, const grid_t& dispX, const grid_t& dispY,\n                                                    real step)\n{\n    int width = (int)input.rows();\n    int height = (int)input.cols();\n    grid_t output(width, height);\n    //#pragma omp parallel for\n    for (int y = 0; y < height; ++y)\n    {\n        for (int x = 0; x < width; ++x)\n        {\n            vec2_t v(dispX(x, y), dispY(x, y));\n            output(x, y) = getClampedF(input, x + step * v.x(), y + step * v.y());\n        }\n    }\n    return output;\n}\n\nvoid ar::GridUtils2D::advectGridSemiLagrangeAdjoint(grid_t& adjInput, grid_t& adjDispX, grid_t& adjDispY, \n    real step, const grid_t& adjOutput, const grid_t& dispX, const grid_t& dispY, const grid_t& input)\n{\n    int width = (int)adjOutput.rows();\n    int height = (int)adjOutput.cols();\n    assert(adjInput.rows() == width); assert(adjInput.cols() == height);\n    assert(adjDispX.rows() == width); assert(adjDispX.cols() == height);\n    assert(adjDispY.rows() == width); assert(adjDispY.cols() == height);\n\n    for (int ky = height-1; ky >= 0; --ky)\n    {\n        for (int kx = width-1; kx >= 0; --kx)\n        {\n            //variables from the forward pass\n            vec2_t v(dispX(kx, ky), dispY(kx, ky));\n            real x = kx + step * v.x();\n            real y = ky + step * v.y();\n            int ix = static_cast<int>(x);\n            int iy = static_cast<int>(y);\n            real fx = x - ix;\n            real fy = y - iy;\n            real v00 = getClamped(input, ix, iy);\n            real v10 = getClamped(input, ix + 1, iy);\n            real v01 = getClamped(input, ix, iy + 1);\n            real v11 = getClamped(input, ix + 1, iy + 1);\n            real v0 = v00 + fy * (v01 - v00);\n            real v1 = v10 + fy * (v11 - v10);\n            //adjoint of the input\n            real adjB = adjOutput(kx, ky);\n            real adjV0 = (1 - fx) * adjB;\n            real adjV1 = fx * adjB;\n            real adjFx = (v1 - v0) * adjB;\n            real adjV10 = (1 - fy) * adjV1;\n            real adjV11 = fy * adjV1;\n            real adjFy = (v11 - v10) * adjV1;\n            real adjV00 = (1 - fy) * adjV0;\n            real adjV01 = fy * adjV0;\n            adjFy += (v01 - v00) * adjV0;\n            atClamped(adjInput, ix, iy) += adjV00;\n            atClamped(adjInput, ix + 1, iy) += adjV10;\n            atClamped(adjInput, ix, iy + 1) += adjV01;\n            atClamped(adjInput, ix + 1, iy + 1) += adjV11;\n            real adjIx = -adjFx; real adjX = adjFx;\n            real adjIy = -adjFy; real adjY = adjFy;\n            real adjUx = step * adjX;\n            real adjUy = step * adjY;\n            adjDispX(kx, ky) += adjUx;\n            adjDispY(kx, ky) += adjUy;\n        }\n    }\n}\n\nconst ar::real ar::GridUtils2D::directForwardKernelRadiusIn = 1.5;\nconst ar::real ar::GridUtils2D::directForwardKernelRadiusOut = 4.0;\nconst ar::real ar::GridUtils2D::directForwardOuterKernelWeight = 1e-5;\nconst ar::real ar::GridUtils2D::directForwardOuterSdfThreshold = 1.01;\nconst ar::real ar::GridUtils2D::directForwardOuterSdfWeight = 1e-10;\n\nar::GridUtils2D::grid_t ar::GridUtils2D::advectGridDirectForward(const grid_t& input, const grid_t& dispX,\n    const grid_t& dispY, real step, grid_t* outputWeights)\n{\n    int width = (int)input.rows();\n    int height = (int)input.cols();\n    grid_t weights = grid_t::Constant(width, height, 0);\n    grid_t output = grid_t::Zero(width, height);\n    real kernelDenom = 1.0 / (2 * square(directForwardKernelRadiusIn / 3)); //98% of the Gaussian kernel is within kernelRadius\n    //blend into output grid\n    for (int y=0; y<height; ++y)\n    {\n        for (int x=0; x<width; ++x)\n        {\n            real value = input(x, y);\n\t\t\treal extraWeight = 1;\n\t\t\tif (value <= -directForwardOuterSdfThreshold || value >= directForwardOuterSdfThreshold)\n\t\t\t\textraWeight = std::max(directForwardOuterSdfWeight, -std::abs(value)+ directForwardOuterSdfThreshold);\n            vec2_t v(dispX(x, y), dispY(x, y));\n            vec2_t p = vec2_t(x, y) - step * v;\n            for (int ix = std::max(0, (int)std::floor(p.x() - directForwardKernelRadiusOut)); ix <= std::min(width-1, (int)std::ceil(p.x() + directForwardKernelRadiusOut)); ++ix)\n            {\n                for (int iy = std::max(0, (int)std::floor(p.y() - directForwardKernelRadiusOut)); iy <= std::min(height - 1, (int)std::ceil(p.y() + directForwardKernelRadiusOut)); ++iy)\n                {\n                    real d = (vec2_t(ix, iy) - p).squaredNorm();\n                    if (d <= square(directForwardKernelRadiusIn))\n                    {\n                        real w = exp(-d * kernelDenom) * extraWeight;\n                        output(ix, iy) += w * value;\n                        weights(ix, iy) += w;\n                    } else if (d <= square(directForwardKernelRadiusOut))\n                    {\n\t\t\t\t\t\treal w = exp(-d * kernelDenom) * directForwardOuterKernelWeight * extraWeight;\n\t\t\t\t\t\toutput(ix, iy) += w * value;\n\t\t\t\t\t\tweights(ix, iy) += w;\n                    }\n                }\n            }\n        }\n    }\n    //normalize\n    //output /= weights;\n\toutput = grid_t::NullaryExpr(width, height, [&output, &input, &weights](Eigen::Index row, Eigen::Index col)->real\n    {\n\t\tconst real weight = weights(row, col);\n\t\t//return weight == 0 ? input(row, col) : output(row, col) / weight;\n\t\treturn weight == 0 ? (weights.rows()+weights.cols()) : output(row, col) / weight; //well outside if weight=0\n\t});\n\t//TODO: change this also in the adjoint versions\n\n\t//place output weights\n\tif (outputWeights)\n\t\t*outputWeights = weights;\n    //done\n    return output;\n}\n\n//TODO: implement changes to the forward problem (different blur kernels and weights) also in the adjoint\n\nvoid ar::GridUtils2D::advectGridDirectForwardAdjoint(grid_t& adjInput, grid_t& adjDispX, grid_t& adjDispY,\n    const grid_t& adjOutput, const grid_t& dispX, const grid_t& dispY, const grid_t& input, const grid_t& output,\n    real step, const grid_t& weights)\n{\n    int width = (int)input.rows();\n    int height = (int)input.cols();\n\treal kernelDenom = 1.0 / (2 * square(directForwardKernelRadiusIn / 3)); //98% of the Gaussian kernel is within kernelRadius\n\n    /*\n    output = grid_t::NullaryExpr(width, height, [&output, &input, &weights](Eigen::Index row, Eigen::Index col)->real\n    {\n\t\tconst real weight = weights(row, col);\n\t\t//return weight == 0 ? input(row, col) : output(row, col) / weight;\n\t\treturn weight == 0 ? (weights.rows()+weights.cols()) : output(row, col) / weight; //well outside if weight=0\n\t});\n     */\n    //adjoint: normalize\n    grid_t adjOut = grid_t::NullaryExpr(width, height, [&adjOutput, &weights](Eigen::Index row, Eigen::Index col)->real\n    {\n        const real weight = weights(row, col);\n        return weight == 0 ? 0 : adjOutput(row, col) / weight; //well outside if weight=0\n    });\n    grid_t adjWeights = grid_t::NullaryExpr(width, height, [&adjOutput, &output, &weights](Eigen::Index row, Eigen::Index col)->real\n    {\n        const real weight = weights(row, col);\n        return weight == 0 ? 0 : -(adjOutput(row, col) * output(row, col)) / square(weight); //well outside if weight=0\n    });\n\n    //adjoint: blend into output grid\n    for (int y=height-1; y>=0; --y)\n    {\n        for (int x=width-1; x>=0; --x)\n        {\n            real value = input(x, y);\n\t\t\treal extraWeight = 1;\n\t\t\tif (value <= -directForwardOuterSdfThreshold || value >= directForwardOuterSdfThreshold)\n\t\t\t\textraWeight = std::max(directForwardOuterSdfWeight, -std::abs(value) + directForwardOuterSdfThreshold);\n            vec2_t v(dispX(x, y), dispY(x, y));\n            vec2_t p = vec2_t(x, y) - step * v;\n            real adjValue = 0;\n            vec2_t adjP(0, 0);\n            for (int ix = std::min(width - 1, (int)std::ceil(p.x() + directForwardKernelRadiusOut)); ix >= std::max(0, (int)std::floor(p.x() - directForwardKernelRadiusOut)); --ix)\n            {\n                for (int iy = std::min(height - 1, (int)std::ceil(p.y() + directForwardKernelRadiusOut)); iy >= std::max(0, (int)std::floor(p.y() - directForwardKernelRadiusOut)); --iy)\n                {\n                    real d = (vec2_t(ix, iy) - p).squaredNorm();\n                    if (d <= square(directForwardKernelRadiusIn))\n                    {\n                        real w = exp(-d * kernelDenom) * extraWeight;\n                        real adjW = adjWeights(ix, iy);\n                        adjValue += w * adjOut(ix, iy);\n                        adjW += value * adjOut(ix, iy);\n                        real adjD = -exp(-d * kernelDenom)*kernelDenom*extraWeight*adjW;\n                        adjP += 2 * (p - vec2_t(ix, iy)) * adjD;\n                    } \n                \telse if (d <= square(directForwardKernelRadiusOut))\n                    {\n\t\t\t\t\t\treal w = exp(-d * kernelDenom) * extraWeight * directForwardOuterKernelWeight;\n\t\t\t\t\t\treal adjW = adjWeights(ix, iy);\n\t\t\t\t\t\tadjValue += w * adjOut(ix, iy);\n\t\t\t\t\t\tadjW += value * adjOut(ix, iy);\n\t\t\t\t\t\treal adjD = -exp(-d * kernelDenom) * kernelDenom * extraWeight * directForwardOuterKernelWeight * adjW;\n\t\t\t\t\t\tadjP += 2 * (p - vec2_t(ix, iy)) * adjD;\n                    }\n                }\n            }\n            vec2_t adjV = -step * adjP;\n            adjDispX(x, y) += adjV.x();\n            adjDispY(x, y) += adjV.y();\n            adjInput(x, y) += adjValue;\n        }\n    }\n}\n\nar::GridUtils2D::grid_t ar::GridUtils2D::advectGridDirectForwardAdjOpMult(const grid_t & adjInput, \n\tconst grid_t & dispX, const grid_t & dispY, real step, const grid_t & weights)\n{\n\tint width = (int)adjInput.rows();\n\tint height = (int)adjInput.cols();\n\tgrid_t output(width, height);\n\n\treal kernelDenom = 1.0 / (2 * square(directForwardKernelRadiusIn / 3)); //98% of the Gaussian kernel is within kernelRadius\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t //blend into output grid\n\tfor (int y = 0; y<height; ++y)\n\t{\n\t\tfor (int x = 0; x<width; ++x)\n\t\t{\n\t\t\t//TODO: Do I need the correction by directForwardOuterSdfThreshold and directForwardOuterSdfWeight here?\n\t\t\treal out = 0;\n\t\t\tvec2_t v(dispX(x, y), dispY(x, y));\n\t\t\tvec2_t p = vec2_t(x, y) - step * v;\n\t\t\tfor (int ix = std::max(0, (int)std::floor(p.x() - directForwardKernelRadiusOut)); ix <= std::min(width - 1, (int)std::ceil(p.x() + directForwardKernelRadiusOut)); ++ix)\n\t\t\t{\n\t\t\t\tfor (int iy = std::max(0, (int)std::floor(p.y() - directForwardKernelRadiusOut)); iy <= std::min(height - 1, (int)std::ceil(p.y() + directForwardKernelRadiusOut)); ++iy)\n\t\t\t\t{\n\t\t\t\t\treal d = (vec2_t(ix, iy) - p).squaredNorm();\n\t\t\t\t\tif (d <= square(directForwardKernelRadiusIn))\n\t\t\t\t\t{\n\t\t\t\t\t\treal w = exp(-d * kernelDenom);\n\t\t\t\t\t\tout -= adjInput(ix, iy) * w / weights(ix, iy);\n\t\t\t\t\t}\n\t\t\t\t\telse if (d <= square(directForwardKernelRadiusOut))\n\t\t\t\t\t{\n\t\t\t\t\t\treal w = exp(-d * kernelDenom) * directForwardOuterKernelWeight;\n\t\t\t\t\t\tout -= adjInput(ix, iy) * w / weights(ix, iy);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\toutput(x, y) = -out;\n\t\t}\n\t}\n\n\treturn output;\n}\n\nar::GridUtils2D::grid_t ar::GridUtils2D::recoverSDFViscosity(const grid_t& input, real viscosity, int iterations)\n{\n    int width = input.rows();\n    int height = input.cols();\n    grid_t output(width, height);\n    grid_t inputOrigin = input;\n\n    //use ar::GradientDescent\n    auto gradFun = [&width, &height, &viscosity, &inputOrigin](const Eigen::Matrix<real, Eigen::Dynamic, 1>& a)\n    {\n        //allocate result\n        Eigen::Matrix<real, Eigen::Dynamic, 1> grad(width * height);\n        //compute new values\n        //#pragma omp parallel for\n        for (int y = 0; y < height; ++y)\n        {\n            for (int x = 0; x < width; ++x)\n            {\n                grad_t g = getGradientLinear(a.data(), x, y, width, height);\n                double l = getLaplacianLinear(a.data(), x, y, width, height);\n                double update = ar::utils::sgn(getLinear(inputOrigin.data(), x, y, width)) * (1 - g.norm()) + viscosity\n                    * l;\n                atLinear(grad.data(), x, y, width) = update;\n            }\n        }\n        //return array\n        return grad;\n    };\n\n    VectorX inputLinear = linearize(input);\n    GradientDescent<Eigen::Matrix<real, Eigen::Dynamic, 1>> gd(inputLinear, gradFun);\n    for (int i = 0; i < iterations; ++i)\n    {\n        bool end = gd.step();\n        CI_LOG_I(\"Iteration \" << i << \", step size: \" << gd.getLastStepSize());\n        if (end) break;\n    }\n\n    return delinearize(gd.getCurrentSolution(), width, height);\n}\n\nar::GridUtils2D::grid_t ar::GridUtils2D::recoverSDFUpwind(const grid_t& input, int iterations)\n{\n    int width = input.rows();\n    int height = input.cols();\n    grid_t output(width, height);\n    grid_t inputOrigin = input;\n\n    //use ar::GradientDescent\n    auto gradFun = [&width, &height, &inputOrigin](const Eigen::Matrix<real, Eigen::Dynamic, 1>& a)\n    {\n        //allocate result\n        Eigen::Matrix<real, Eigen::Dynamic, 1> grad(width * height);\n        //compute new values\n        //#pragma omp parallel for\n        for (int y = 0; y < height; ++y)\n        {\n            for (int x = 0; x < width; ++x)\n            {\n                real gradPos = getGradientPosLinear(a.data(), x, y, width, height);\n                real gradNeg = getGradientNegLinear(a.data(), x, y, width, height);\n                int sgn = ar::utils::sgn(getLinear(inputOrigin.data(), x, y, width));\n                double update = std::max(0, sgn) * gradPos + std::min(0, sgn) * gradNeg - sgn;\n                atLinear(grad.data(), x, y, width) = update;\n            }\n        }\n        //return array\n        return grad;\n    };\n\n    Eigen::Matrix<real, Eigen::Dynamic, 1> inputLinear = linearize(input);\n    GradientDescent<Eigen::Matrix<real, Eigen::Dynamic, 1>> gd(inputLinear, gradFun);\n    for (int i = 0; i < iterations; ++i)\n    {\n        bool end = gd.step();\n        CI_LOG_I(\"Iteration \" << i << \", step size: \" << gd.getLastStepSize());\n        if (end) break;\n    }\n\n    return delinearize(gd.getCurrentSolution(), width, height);\n}\n\nar::GridUtils2D::grid_t ar::GridUtils2D::recoverSDFSussmann(\n\tconst grid_t& input, real epsilon, int iterations, RecoverSDFSussmannAdjointStorage* adjointStorage)\n{\n\tint width = input.rows();\n\tint height = input.cols();\n\tgrid_t inputOrigin = input;\n\n\tbgrid_t canChange = bgrid_t::Constant(width, height, true);\n\tfor (int x=1; x<width; ++x)\n\t\tfor (int y=1; y<height; ++y)\n\t\t{\n\t\t\tint c = utils::insideEq(input(x-1, y-1)) \n\t\t\t\t| (utils::insideEq(input(x-1, y)) << 1) \n\t\t\t\t| (utils::insideEq(input(x, y-1)) << 2) \n\t\t\t\t| (utils::insideEq(input(x, y)) << 3);\n\t\t\tif (!(c==0b0000 || c==0b111))\n\t\t\t{\n\t\t\t\tcanChange(x - 1, y - 1) = false;\n\t\t\t\tcanChange(x - 1, y) = false;\n\t\t\t\tcanChange(x, y - 1) = false;\n\t\t\t\tcanChange(x, y) = false;\n\t\t\t}\n\t\t}\n\n    if (adjointStorage) {\n        adjointStorage->epsilon = epsilon;\n        adjointStorage->inputs.push_back(inputOrigin);\n        adjointStorage->canChange = canChange;\n    }\n\n#if 0\n    real finalCost = 0;\n    const auto gradient = [width, height, &inputOrigin, &canChange, epsilon, &finalCost](const VectorX& x) -> VectorX\n    {\n        grid_t grad = recoverSDFSussmannGradient(delinearize(x, width, height), inputOrigin, canChange, finalCost, epsilon);\n        return linearize(grad);\n    };\n    //start value\n    VectorX value = linearize(input);\n    //run optimization\n    GradientDescent<VectorX> gd(value, gradient);\n    gd.setEpsilon(1e-15);\n    gd.setLinearStepsize(0.001);\n    gd.setMaxStepsize(0.5);\n    int oi;\n    for (oi = 0; oi < iterations; ++oi) {\n        bool done = gd.step();\n        CI_LOG_I(\"Iteration \" << oi << \"/\" << iterations << \", cost = \" << finalCost << \", stepsize = \" << gd.getLastStepSize());\n        if (done) break;\n    }\n    value = gd.getCurrentSolution();\n    return delinearize(value, width, height);\n#elif 1\n    //fixed step size\n    real stepsize = 0.5;\n    real cost = 0;\n    grid_t value = input;\n    for (int i=0; i<iterations; ++i)\n    {\n        grid_t grad = recoverSDFSussmannGradient(value, inputOrigin, canChange, cost, epsilon);\n        value -= stepsize * grad;\n        if (adjointStorage) adjointStorage->inputs.push_back(value);\n    }\n    if (adjointStorage) {\n        adjointStorage->iterations = iterations;\n        adjointStorage->stepsize = stepsize;\n    }\n    return value;\n#else\n\tLBFGSpp::LBFGSParam<real> params;\n\tparams.epsilon = 1e-10;\n\tparams.max_iterations = iterations;\n\tLBFGSpp::LBFGSSolver<real> lbfgs(params);\n\n\tLBFGSpp::LBFGSSolver<real>::ObjectiveFunction_t gradFun = [width, height, &inputOrigin, &canChange, epsilon](const VectorX& va, VectorX& gradient) -> real\n\t{\n\t\treal cost = 0;\n\t\tgrid_t grad = recoverSDFSussmannGradient(delinearize(va, width, height), inputOrigin, canChange, cost, epsilon);\n\t\tgradient = linearize(grad);\n\t\treturn cost;\n\t};\n\tLBFGSpp::LBFGSSolver<real>::CallbackFunction_t callback([iterations](const VectorX& x, const real& v, int k) -> bool {\n\t\tCI_LOG_I(\"Iteration \" << k << \"/\" << iterations << \", cost = \" << v);\n\t\treturn true;\n\t});\n\n\treal finalCost = 0;\n\tVectorX value = linearize(input);\n\tint finalIterations = lbfgs.minimize(gradFun, value, finalCost, callback);\n    return delinearize(value, width, height);\n#endif\n}\n\nvoid ar::GridUtils2D::recoverSDFSussmannAdjoint(const grid_t& input, const grid_t& output, const grid_t& adjOutput,\n\tgrid_t& adjInput, const RecoverSDFSussmannAdjointStorage& adjointStorage)\n{\n\t//Adjoint of recoverSDFSussmann\n\t\n    const grid_t& input0 = adjointStorage.inputs[0];\n    grid_t adjValue = adjOutput;\n    for (int i=adjointStorage.iterations-1; i>=0; --i)\n    {\n        grid_t adjGrad = -adjointStorage.stepsize * adjValue;\n        recoverSDFSussmannGradientAdjoint(adjointStorage.inputs[i], input0, adjointStorage.canChange, adjointStorage.epsilon, adjGrad, adjValue);\n    }\n    adjInput += adjValue;\n}\n\nar::GridUtils2D::grid_t ar::GridUtils2D::recoverSDFSussmannGradient(\n\tconst grid_t& input, const grid_t& input0, const bgrid_t& canChange,\n\treal& cost, real epsilon)\n{\n\tint width = input.rows();\n\tint height = input.cols();\n\n\tVectorX inputLinear = linearize(input);\n\tconst real* a = inputLinear.data();\n\n\tgrid_t gradient(width, height);\n\n\tcost = 0;\n\tfor (int y = 0; y < height; ++y)\n\t{\n\t\tfor (int x = 0; x < width; ++x)\n\t\t{\n\t\t\tif (!canChange(x, y))\n\t\t\t{\n\t\t\t\tgradient(x, y) = 0;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\treal phi0 = input0(x, y);\n\t\t\treal s = phi0 / sqrt(phi0*phi0 + epsilon);\n\t\t\treal s01 = utils::sgn(s);\n\n\t\t\treal phi = getLinear(a, x, y, width);\n\t\t\treal ta = x > 0\n\t\t\t\t? (phi - getLinear(a, x - 1, y, width))\n\t\t\t\t: -s01;// (getLinear(a, x + 1, y, width) - phi);\n\t\t\treal tb = x < width - 1\n\t\t\t\t? (getLinear(a, x + 1, y, width) - phi)\n\t\t\t\t: s01;// (phi - getLinear(a, x - 1, y, width));\n\t\t\treal tc = y > 0\n\t\t\t\t? (phi - getLinear(a, x, y - 1, width))\n\t\t\t\t: -s01;// (getLinear(a, x, y - 1, width) - phi);\n\t\t\treal td = y < height - 1\n\t\t\t\t? (getLinear(a, x, y + 1, width) - phi)\n\t\t\t\t: s01;// (phi - getLinear(a, x, y - 1, width));\n\t\t\treal aPos = std::max(real(0), ta), aNeg = std::min(real(0), ta);\n\t\t\treal bPos = std::max(real(0), tb), bNeg = std::min(real(0), tb);\n\t\t\treal cPos = std::max(real(0), tc), cNeg = std::min(real(0), tc);\n\t\t\treal dPos = std::max(real(0), td), dNeg = std::min(real(0), td);\n\n\t\t\treal g = 0;\n\t\t\tif (phi0 > 0)\n\t\t\t\tg = sqrt(std::max(aPos*aPos, bNeg*bNeg) + std::max(cPos*cPos, dNeg*dNeg)) - 1;\n\t\t\telse if (phi0 < 0)\n\t\t\t\tg = sqrt(std::max(aNeg*aNeg, bPos*bPos) + std::max(cNeg*cNeg, dPos*dPos)) - 1;\n\n\t\t\tcost += 0.5 * square(g);\n\n\t\t\tgradient(x, y) = s * g;\n\t\t}\n\t}\n\n\treturn gradient;\n}\n\nvoid ar::GridUtils2D::recoverSDFSussmannGradientAdjoint(const grid_t& input, const grid_t& input0,\n    const bgrid_t& canChange, real epsilon, const grid_t& adjOutput, grid_t& adjInput)\n{\n    int width = input.rows();\n    int height = input.cols();\n    for (int y = 0; y < height; ++y)\n    {\n        for (int x = 0; x < width; ++x)\n        {\n            if (!canChange(x, y))\n                continue;\n\n            real phi0 = input0(x, y);\n            real s = phi0 / sqrt(phi0*phi0 + epsilon);\n            real s01 = utils::sgn(s);\n\n            real phi = input(x, y);\n            real ta = x > 0\n                ? (phi - input(x - 1, y))\n                : -s01;// (getLinear(a, x + 1, y, width) - phi);\n            real tb = x < width - 1\n                ? (input(x + 1, y) - phi)\n                : s01;// (phi - getLinear(a, x - 1, y, width));\n            real tc = y > 0\n                ? (phi - input(x, y - 1))\n                : -s01;// (getLinear(a, x, y - 1, width) - phi);\n            real td = y < height - 1\n                ? (input(x, y + 1) - phi)\n                : s01;// (phi - getLinear(a, x, y - 1, width));\n\n            if (phi0 > 0)\n            {\n                real ap = std::max(ta, real(0)), bm = std::min(tb, real(0)), cp = std::max(tc, real(0)), dm = std::min(td, real(0));\n                real ab = std::max(ap*ap, bm*bm), cd = std::max(cp*cp, dm*dm);\n                real adjAB = (s / (2 * sqrt(ab + cd))) * adjOutput(x, y), adjCD = adjAB;\n                real adjAp = ap * ap > bm*bm ? 0.5*ap*adjAB : 0;\n                if (x > 0 && ta > 0) { adjInput(x, y) += adjAp; adjInput(x - 1, y) -= adjAp; }\n                real adjBm = ap * ap < bm*bm ? 0.5*bm*adjAB : 0;\n                if (x < width - 1 && tb < 0) { adjInput(x, y) -= adjBm; adjInput(x + 1, y) += adjBm; }\n                real adjCp = cp * cp > dm*dm ? 0.5*cp*adjCD : 0;\n                if (y > 0 && tc > 0) { adjInput(x, y) += adjCp; adjInput(x, y - 1) -= adjCp; }\n                real adjDm = cp * cp < dm*dm ? 0.5*dm*adjCD : 0;\n                if (y < height - 1 && td < 0) { adjInput(x, y) -= adjDm; adjInput(x, y + 1) += adjDm; }\n            } else\n            {\n                real am = std::min(ta, real(0)), bp = std::max(tb, real(0)), cm = std::min(tc, real(0)), dp = std::max(td, real(0));\n                real ab = std::max(am*am, bp*bp), cd = std::max(cm*cm, dp*dp);\n                real adjAB = (s / (2 * sqrt(ab + cd))) * adjOutput(x, y), adjCD = adjAB;\n                real adjAm = am * am > bp*bp ? 0.5*am*adjAB : 0;\n                if (x > 0 && ta < 0) { adjInput(x, y) += adjAm; adjInput(x - 1, y) -= adjAm; }\n                real adjBp = am * am < bp*bp ? 0.5*bp*adjAB : 0;\n                if (x < width - 1 && tb > 0) { adjInput(x, y) -= adjBp; adjInput(x + 1, y) += adjBp; }\n                real adjCm = cm * cm > dp*dp ? 0.5*cm*adjCD : 0;\n                if (y > 0 && tc < 0) { adjInput(x, y) += adjCm; adjInput(x, y - 1) -= adjCm; }\n                real adjDp = cm * cm < dp*dp ? 0.5*dp*adjCD : 0;\n                if (y < height - 1 && td > 0) { adjInput(x, y) -= adjDp; adjInput(x, y + 1) += adjDp; }\n            }\n        }\n    }\n}\n\nar::GridUtils2D::grid_t ar::GridUtils2D::recoverSDFFastMarching(const grid_t& input)\n{\n    int width = input.rows();\n    int height = input.cols();\n    grid_t output = input;//(width, height);\n    bgrid_t accepted = bgrid_t::Constant(width, height, false);\n\n    //TODO: inside\n\n    //outside loop\n    typedef std::tuple<real, int, int, real> et;\n    auto comp = [](const et& a, const et& b) {return std::get<0>(a) > std::get<0>(b); };\n    std::priority_queue<et, std::vector<et>, decltype(comp)> close(comp);\n    //initial poits\n    for (int x=0; x<width; ++x) for (int y=0; y<height; ++y)\n    {\n        if (!utils::outside(input(x, y))) continue; //we are inside\n        //find boundary case\n        int c = (x > 0 && utils::insideEq(input(x - 1, y))) ? 1 : 0\n            | ((x < width - 1 && utils::insideEq(input(x + 1, y))) ? 2 : 0)\n            | ((y > 0 && utils::insideEq(input(x, y - 1))) ? 4 : 0)\n            | ((y > height - 1 && utils::insideEq(input(x, y + 1))) ? 8 : 0);\n        if (c == 0) continue; //completely outside, no boundary\n        \n        //process boundary case\n        real vOld = input(x, y);\n        real vNew = 0;\n        switch (c) // +y -y +x -x\n        {\n        case 0b0001:\n        case 0b0010:\n        case 0b0100:\n        case 0b1000:\n        { //case a)\n            real v = c == 0b0001 ? input(x - 1, y)\n                : c == 0b0010 ? input(x + 1, y)\n                : c == 0b0100 ? input(x, y - 1)\n                : /*c == 0b1000 ?*/ input(x, y + 1);\n            real s = v / (v - vOld); assert(s > 0);\n            vNew = s;\n        }break;\n        case 0b0101:\n        case 0b1010:\n        case 0b0110:\n        case 0b1001:\n        { //case b)\n            real v1 = c == 0b0101 ? input(x - 1, y)\n                : c == 0b1010 ? input(x + 1, y)\n                : c == 0b0110 ? input(x + 1, y)\n                : /*c == 0b1001 ?*/ input(x - 1, y);\n            real v2 = c == 0b0101 ? input(x, y - 1)\n                : c == 0b1010 ? input(x, y + 1)\n                : c == 0b0110 ? input(x, y - 1)\n                : /*c == 0b1001 ?*/ input(x, y + 1);\n            real s = v1 / (v1 - vOld); assert(s > 0);\n            real t = v2 / (v2 - vOld); assert(t > 0);\n            vNew = s * t / sqrt(s*s + t * t);\n        } break;\n        case 0b1110:\n        case 0b1101:\n        case 0b1011:\n        case 0b0111:\n        { //case c)\n            real vs1 = c == 0b1110 ? input(x, y - 1)\n                : c == 0b1101 ? input(x, y + 1)\n                : c == 0b1011 ? input(x + 1, y)\n                : /*c == 0b0111 ?*/ input(x - 1, y);\n            real vs2 = c == 0b1110 ? input(x, y + 1)\n                : c == 0b1101 ? input(x, y - 1)\n                : c == 0b1011 ? input(x - 1, y)\n                : /*c == 0b0111 ?*/ input(x + 1, y);\n            real vt = c == 0b1110 ? input(x - 1, y)\n                : c == 0b1101 ? input(x + 1, y)\n                : c == 0b1011 ? input(x, y + 1)\n                : /*c == 0b0111 ?*/ input(x, y - 1);\n            real s1 = vs1 / (vs1 - vOld); assert(s1 > 0);\n            real s2 = vs2 / (vs2 - vOld); assert(s2 > 0);\n            real s = std::min(s1, s2);\n            real t = vt / (vt - vOld); assert(t > 0);\n            vNew = s * t / sqrt(s*s + t * t);\n        } break;\n        case 0b0011:\n        case 0b1100:\n        { //case d)\n            real vs1 = c == 0b0011 ? input(x - 1, y)\n                : /*c == 0b1100 ?*/ input(x, y - 1);\n            real vs2 = c == 0b0011 ? input(x + 1, y)\n                : /*c == 0b1100 ?*/ input(x, y + 1);\n            real s1 = vs1 / (vs1 - vOld); assert(s1 > 0);\n            real s2 = vs2 / (vs2 - vOld); assert(s2 > 0);\n            vNew = std::min(s1, s2);\n        } break;\n        case 0b1111:\n        { //case e);\n            real vs1 = input(x - 1, y);\n            real vs2 = input(x + 1, y);\n            real vt1 = input(x, y - 1);\n            real vt2 = input(x, y + 1);\n            real s1 = vs1 / (vs1 - vOld); assert(s1 > 0);\n            real s2 = vs2 / (vs2 - vOld); assert(s2 > 0);\n            real t1 = vt1 / (vt1 - vOld); assert(t1 > 0);\n            real t2 = vt2 / (vt2 - vOld); assert(t2 > 0);\n            real s = std::min(s1, s2);\n            real t = std::min(t1, t2);\n            vNew = s * t / sqrt(s*s + t * t);\n        } break;\n        }\n        assert(vNew > 0);\n\n        //write output and mark as done\n        output(x, y) = vNew;\n        \n        //add to the queue\n        close.emplace(real(0), x, y, vNew);\n    }\n    //sweep\n    while(!close.empty())\n    {\n        et e = close.top(); close.pop();\n        real v = std::get<3>(e);\n        int x = std::get<1>(e);\n        int y = std::get<2>(e);\n        \n        if (accepted(x, y)) continue; //already processed\n\n        //mark current as processed\n        output(x, y) = v;\n        accepted(x, y) = true;\n\n        //add neighbors to the list\n        int neighbors[4][2] = { {-1,0}, {+1,0}, {0,-1}, {0,+1} };\n        const static real BIG = 1e10;\n        for (int i=0; i<4; ++i)\n        {\n            int ix = x + neighbors[i][0];\n            int iy = y + neighbors[i][1];\n            if (ix < 0 || iy < 0 || ix >= width || iy >= height) continue;\n            if (!utils::outside(input(ix, iy))) continue;\n            if (accepted(ix, iy)) continue;\n            real a = (ix + 1) >= width ? BIG\n                : !accepted(ix + 1, iy) ? BIG\n                : output(ix + 1, iy);\n            real b = (ix - 1) < 0 ? BIG\n                : !accepted(ix - 1, iy) ? BIG\n                : output(ix - 1, iy);\n            real c = (iy + 1) >= height ? BIG\n                : !accepted(ix, iy + 1) ? BIG\n                : output(ix, iy + 1);\n            real d = (iy - 1) < 0 ? BIG\n                : !accepted(ix, iy - 1) ? BIG\n                : output(ix, iy - 1);\n            real ab = std::min(a, b);\n            real cd = std::min(c, d);\n            real vNew = NAN;\n            if (ab < BIG && cd < BIG)\n                vNew = 0.5 * sqrt(-square(ab) + 2 * ab*cd - square(cd) + 2) + (ab + cd) / 2;\n            else if (ab < BIG)\n                vNew = ab + 1;\n            else if (cd < BIG)\n                vNew = cd + 1;\n            close.emplace(vNew, ix, iy, vNew);\n        }\n    }\n\n    return output;\n}\n", "meta": {"hexsha": "7affb5a18d11891ff7f1d7aa538dac48f7004def", "size": 47498, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ActionReconstructionLib/GridUtils.cpp", "max_stars_repo_name": "shamanDevel/SparseSurfaceConstraints", "max_stars_repo_head_hexsha": "88357ff847369a45b9f16f9f44159196138f9147", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2020-03-08T18:28:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T20:32:56.000Z", "max_issues_repo_path": "ActionReconstructionLib/GridUtils.cpp", "max_issues_repo_name": "shamanDevel/SparseSurfaceConstraints", "max_issues_repo_head_hexsha": "88357ff847369a45b9f16f9f44159196138f9147", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ActionReconstructionLib/GridUtils.cpp", "max_forks_repo_name": "shamanDevel/SparseSurfaceConstraints", "max_forks_repo_head_hexsha": "88357ff847369a45b9f16f9f44159196138f9147", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-03-26T01:54:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-18T13:32:46.000Z", "avg_line_length": 36.8773291925, "max_line_length": 185, "alphanum_fraction": 0.5140426965, "num_tokens": 15023, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851918, "lm_q2_score": 0.6187804196836383, "lm_q1q2_score": 0.47589178531489457}}
{"text": "#ifndef __ROBOT_SIMULATOR__KIN__\n#define __ROBOT_SIMULATOR__KIN__\n#include <ros/ros.h>\n#include <robot_state_publisher/robot_state_publisher.h>\n#include <urdf/model.h>\n#include <sensor_msgs/JointState.h>\n#include <kdl_parser/kdl_parser.hpp>\n#include <kdl/jntarrayvel.hpp>\n#include <kdl/chainjnttojacsolver.hpp>\n#include <kdl/chainfksolverpos_recursive.hpp>\n#include <kdl/chainiksolverpos_lma.hpp>\n#include <boost/thread.hpp>\n#include <Eigen/Dense>\n\n/**\n  Class that maintains a kinematic simulation of the robot loaded in the robot_description parameter\n  in the ROS parameter server. It publishes the TF transforms through the robot state publisher.\n**/\nclass RobotSimulator\n{\npublic:\n  RobotSimulator(double frequency);\n\n  /**\n    Initializes the kinematic chain connecting base_link to end_effector_link.\n    The end_effector_link name will be used to index this chain.\n\n    @param base_link The kinematic chain base link.\n    @param end_effector_link The kinematic chain end-effector.\n    @param desired_pose: Initialization pose for the end-effector\n    @return True for a successful initialization; False in case of failure.\n  **/\n  bool initKinematicChain(const std::string &base_link, const std::string &end_effector_link, const std::vector<double> &desired_pose);\n\n  /**\n    Set the desired chain to a pose.\n  **/\n  bool setPose(const std::string &end_effector_link, const std::vector<double> &desired_pose);\n\n  /**\n    Get an initialized kinematic chain.\n\n    @param end_effector_link The name of the chain's end-effector.\n    @param chain The variable where to store the chain.\n    @return False for failure in getting the chain.\n  **/\n  bool getKinematicChain(const std::string &end_effector_link, KDL::Chain &chain);\n\n  /**\n    Gets the pose of the end-effector.\n  **/\n  bool getPose(const std::string &end_effector_link, KDL::Frame &pose);\n\n  /**\n    Gets the current kinematic chain joint state\n  **/\n  bool getJointState(const std::string &end_effector_link, KDL::JntArray &q);\n\n  /**\n    Set the current joint velocities for the joint chain\n  **/\n  bool setJointVelocities(const std::string &end_effector_link, const Eigen::VectorXd &joint_velocities);\nprivate:\n  boost::shared_ptr<robot_state_publisher::RobotStatePublisher> robot_publisher_;\n  KDL::Tree tree_;\n\n  std::vector<std::string> end_effector_link_name_;\n  std::vector<KDL::Chain> chain_;\n  std::vector<KDL::JntArrayVel> joint_state_;\n  std::vector<boost::shared_ptr<KDL::ChainFkSolverPos_recursive> > fk_solver_;\n  std::vector<boost::shared_ptr<KDL::ChainIkSolverPos_LMA> > ik_solver_;\n  std::map<std::string, double> joint_positions_;\n  std::vector<Eigen::VectorXd> current_joint_velocities_;\n  boost::mutex velocities_mutex_;\n  boost::thread sim_thread_;\n  ros::Publisher joint_state_pub_;\n  sensor_msgs::JointState joint_msg_;\n  double frequency_;\n\n  /**\n    Gets a KDL frame from a vector with a 7 dimensional pose description.\n\n    @param pose_in Vector with a 3 dimensional position and a 4 dimensional quaternion representing orientation.\n    @return The KDL frame that represents the same pose.\n  **/\n  KDL::Frame getKDLPose(const std::vector<double> &pose_in);\n\n  /**\n    Simulation thread.\n  **/\n  void simulation();\n\n  /**\n    Apply the given joint velocities to the kinematic chain indexed by the end-effector link.\n\n    @param joint_velocities The joint velocities vector.\n    @param end_effector_link The kinematic chain end-effector.\n    @param dt Time step.\n    @return False in case of failure.\n  **/\n  bool applyJointVelocities(const Eigen::VectorXd &joint_velocities, const std::string &end_effector_link, double dt);\n};\n\n#endif", "meta": {"hexsha": "4bca02c5cd0d865c25324a24fb701482047a39d3", "size": 3626, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pr2_algorithms/include/pr2_algorithms/robot_simulator.hpp", "max_stars_repo_name": "diogoalmeida/pr2_controller_framework", "max_stars_repo_head_hexsha": "852240638d8da439485d69fb1f627db5845c6820", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pr2_algorithms/include/pr2_algorithms/robot_simulator.hpp", "max_issues_repo_name": "diogoalmeida/pr2_controller_framework", "max_issues_repo_head_hexsha": "852240638d8da439485d69fb1f627db5845c6820", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pr2_algorithms/include/pr2_algorithms/robot_simulator.hpp", "max_forks_repo_name": "diogoalmeida/pr2_controller_framework", "max_forks_repo_head_hexsha": "852240638d8da439485d69fb1f627db5845c6820", "max_forks_repo_licenses": ["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.8653846154, "max_line_length": 135, "alphanum_fraction": 0.7539988969, "num_tokens": 880, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4758620044349727}}
{"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 ANISOTROPIC_HPP\n#define ANISOTROPIC_HPP\n\n#include <iosfwd>\n\n#include \"Config.hpp\"\n\n#include <Eigen/Core>\n\n#include \"utils/MathUtils.hpp\"\n\n/*! \\file Anisotropic.hpp\n *  \\class Anisotropic\n *  \\brief describes a medium with anisotropy, i.e. liquid crystal\n *  \\author Roberto Di Remigio\n *  \\date 2014\n */\n\nclass Anisotropic __final\n{\nprivate:\n    /// Diagonal of the permittivity tensor in the lab-fixed frame\n    Eigen::Vector3d epsilonLab_;\n    /// Euler angles (in degrees) relating molecule-fixed and lab-fixed frames\n    Eigen::Vector3d eulerAngles_;\n    /// Permittivity tensor in molecule-fixed frame\n    Eigen::Matrix3d epsilon_;\n    /// Inverse of the permittivity tensor in molecule-fixed frame\n    Eigen::Matrix3d epsilonInv_;\n    /// molecule-fixed to lab-fixed frames rotation matrix\n    Eigen::Matrix3d R_;\n    /// Determinant of the permittivity tensor\n    double detEps_;\n    /*! Initializes some internals: molecule-fixed to lab-fixed frame rotation matrix,\n     * permittivity tensor in molecule-fixed frame and its inverse\n     */\n    void build() {\n        // 1. construct rotation matrix from Euler angles\n\t    eulerRotation(R_, eulerAngles_);\n\t    // 2. Apply the rotation matrix: epsilon_ = R_^t * epsilonLab_ * R_\n\t    epsilon_ = R_.transpose() * epsilonLab_.asDiagonal() * R_;\n\t    // 3. Obtain epsilonInv_ = R_ * epsilonLab_^-1 * R_^t\n\t    Eigen::Vector3d scratch;\n\t    scratch << (1.0/epsilonLab_(0)), (1.0/epsilonLab_(1)), (1.0/epsilonLab_(2));\n\t    epsilonInv_ = R_ * scratch.asDiagonal() * R_.transpose();\n\t    // 4. As a __final step, calculate the determinant\n\t    detEps_ = epsilonLab_(0) * epsilonLab_(1) * epsilonLab_(2);\n    }\npublic:\n    Anisotropic() :\n\t    epsilonLab_(Eigen::Vector3d::Ones()), eulerAngles_(Eigen::Vector3d::Zero()) { this->build(); }\n    /*!\n     * \\param[in] eigen_eps eigenvalues of the permittivity tensors\n     * \\param[in] euler_ang Euler angles in degrees\n     */\n    Anisotropic(const Eigen::Vector3d & eigen_eps, const Eigen::Vector3d & euler_ang) :\n\t    epsilonLab_(eigen_eps), eulerAngles_(euler_ang) { this->build(); }\n    const Eigen::Matrix3d & epsilon() const { return epsilon_; }\n    const Eigen::Matrix3d & epsilonInv() const { return epsilonInv_; }\n    double detEps() const { return detEps_; }\n    friend std::ostream & operator<<(std::ostream & os, Anisotropic & arg) {\n        os << \"Permittivity tensor diagonal (lab frame)   = \" << arg.epsilonLab_.transpose() << std::endl;\n        os << \"Euler angles (molecule-to-lab frame)       = \" << arg.eulerAngles_.transpose() << std::endl;\n        os << \"Permittivity tensor (molecule-fixed frame) =\\n\" << arg.epsilon_;\n        return os;\n    }\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW /* See http://eigen.tuxfamily.org/dox/group__TopicStructHavingEigenMembers.html */\n};\n\n#endif // ANISOTROPIC_HPP\n", "meta": {"hexsha": "391635a7729766224b296b3ba0edc9afed7a07cd", "size": 3935, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "external/PCMSolver/PCMSolver-source/src/green/dielectric_profile/Anisotropic.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/dielectric_profile/Anisotropic.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/dielectric_profile/Anisotropic.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": 40.9895833333, "max_line_length": 118, "alphanum_fraction": 0.6828462516, "num_tokens": 1030, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4758620044349727}}
{"text": "#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <ctime>\n\n#include <kv/qr.hpp>\n\nnamespace ub = boost::numeric::ublas;\n\nint main()\n{\n\tint i, j;\n\tub::matrix<double> a, q, r;\n\n\ta.resize(2, 2);\n\n\ta(0, 0) = 1.;\n\ta(0, 1) = 2.;\n\ta(1, 0) = 3.;\n\ta(1, 1) = 4.;\n\n\tkv::qr(a, q, r);\n\n\tstd::cout << q << \"\\n\";\n\tstd::cout << r << \"\\n\";\n\tstd::cout << a - prod(q, r) << \"\\n\";\n\tstd::cout << prod(q, trans(q)) << \"\\n\";\n\n\tfor (i=0; i<10; i++) {\n\t\tkv::qr(a, q, r);\n\t\ta = prod(r, q);\n\t\tstd::cout << a << \"\\n\";\n\t}\n\n\ta.resize(5, 5);\n\tsrand(time(NULL));\n\tfor (i=0; i<5; i++) {\n\t\tfor (j=0; j<5; j++) {\n\t\t\ta(i, j) = (double)rand();\n\t\t}\n\t}\n\n\tkv::qr(a, q, r);\n\n\t// std::cout << q << \"\\n\";\n\t// std::cout << r << \"\\n\";\n\tstd::cout << a - prod(q, r) << \"\\n\";\n\tstd::cout << prod(q, trans(q)) << \"\\n\";\n}\n", "meta": {"hexsha": "7386880f5cf91b0410d733c5ffa3ee9d56d20ae7", "size": 851, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/test-qr.cc", "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": "test/test-qr.cc", "max_issues_repo_name": "soonho-tri/kv", "max_issues_repo_head_hexsha": "4963be6560d8600cdc9ff22d004b2b965ae7b1df", "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": "test/test-qr.cc", "max_forks_repo_name": "soonho-tri/kv", "max_forks_repo_head_hexsha": "4963be6560d8600cdc9ff22d004b2b965ae7b1df", "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": 17.02, "max_line_length": 41, "alphanum_fraction": 0.4747356052, "num_tokens": 349, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4758619989910708}}
{"text": "/*\n * ForceDihedral.cpp\n *\n *  Created on: 27 feb 2018\n *      Author: lorenzo\n */\n\n#include \"ForceDihedral.h\"\n\n#include <Eigen/Dense>\n\nnamespace ashell {\n\nForceDihedral::ForceDihedral(std::string name) :\n\t\t\t\tForceComputer(name),\n\t\t\t\t_kb(100.),\n\t\t\t\t_theta0(0.) {\n\n}\n\nForceDihedral::~ForceDihedral() {\n\n}\n\nvoid ForceDihedral::set_kb(double n_kb) {\n\t_kb = n_kb;\n}\n\nvoid ForceDihedral::set_theta0(double n_theta0) {\n\t_theta0 = n_theta0;\n}\n\nvoid ForceDihedral::_compute_forces(ullint step) {\n\tconst vector_vec3 &poss = _particles->positions();\n\n\tfor(auto &dihedral : _sys_props->dihedrals()) {\n\t\tuint i = dihedral->members[0];\n\t\tuint j = dihedral->members[1];\n\t\tuint k = dihedral->members[2];\n\t\tuint l = dihedral->members[3];\n\n\t\tvec3 i_pos = poss[i];\n\t\tvec3 j_pos = poss[j];\n\t\tvec3 k_pos = poss[k];\n\t\tvec3 l_pos = poss[l];\n\n\t\t// see Sofia Biagi's thesis, pag. 114\n\t\tvec3 r_ij = _sys_props->box()->minimum_image(j_pos, i_pos);\n\t\tvec3 r_kj = _sys_props->box()->minimum_image(j_pos, k_pos);\n\t\tvec3 r_kl = _sys_props->box()->minimum_image(l_pos, k_pos);\n\n\t\tdouble r_kj_sqr = r_kj.dot(r_kj);\n\t\tdouble r_kj_mod = sqrt(r_kj_sqr);\n\n\t\tvec3 m = r_ij.cross(r_kj);\n\t\tvec3 n = r_kj.cross(r_kl);\n\n\t\tdouble m_sqr = m.dot(m);\n\t\tdouble n_sqr = n.dot(n);\n\n\t\tdouble costheta = m.dot(n) / (sqrt(m_sqr) * sqrt(n_sqr));\n\t\tif(costheta > 1.) costheta = 1.;\n\t\tif(costheta < -1.) costheta = -1.;\n\n\t\tdouble theta = acos(costheta);\n\t\tif(r_ij.dot(n) < 0.) theta = -theta;\n\t\t// we use the so-called polymer convention, for which theta(polymer) = theta(IUPAC) +/- pi\n\t\ttheta -= M_PI;\n\n\t\tdouble dVdtheta = _kb * sin(theta - _theta0);\n\t\tvec3 F_i = (-dVdtheta * r_kj_mod / m_sqr) * m;\n\t\tvec3 F_l = (dVdtheta * r_kj_mod / n_sqr) * n;\n\n\t\t// We compute Fj and Fk from Fi and Fl by knowing that  F_i + Fj + Fk + Fl == 0\n\t\t// and that the dihedral potential energy function is rotationally invariant\n\t\tvec3 S = (r_ij.dot(r_kj) / r_kj_sqr) * F_i - (r_kl.dot(r_kj) / r_kj_sqr) * F_l;\n\n\t\t_forces[i] += F_i;\n\t\t_forces[j] += -F_i + S;\n\t\t_forces[k] += -F_l - S;\n\t\t_forces[l] += F_l;\n\n\t\tdouble energy = _kb * (1. - cos(theta - _theta0));\n\n//\t\tBOOST_LOG_TRIVIAL(info) << costheta << \" \" << (theta*180/M_PI) << \" \" << energy;\n\n\t\t_energy += energy;\n\t\t_energies[i] += energy / 4.;\n\t\t_energies[j] += energy / 4.;\n\t\t_energies[k] += energy / 4.;\n\t\t_energies[l] += energy / 4.;\n\t}\n}\n\n} /* namespace ashell */\n", "meta": {"hexsha": "0ea63aa53d6a3ffe97f4d3098ed3236a9d27955a", "size": 2351, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/computers/ForceDihedral.cpp", "max_stars_repo_name": "lorenzo-rovigatti/ashell", "max_stars_repo_head_hexsha": "f6c3d4b009ec9229d972a5cc851e90a772f3575b", "max_stars_repo_licenses": ["MIT"], "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/computers/ForceDihedral.cpp", "max_issues_repo_name": "lorenzo-rovigatti/ashell", "max_issues_repo_head_hexsha": "f6c3d4b009ec9229d972a5cc851e90a772f3575b", "max_issues_repo_licenses": ["MIT"], "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/computers/ForceDihedral.cpp", "max_forks_repo_name": "lorenzo-rovigatti/ashell", "max_forks_repo_head_hexsha": "f6c3d4b009ec9229d972a5cc851e90a772f3575b", "max_forks_repo_licenses": ["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.4895833333, "max_line_length": 92, "alphanum_fraction": 0.6346235644, "num_tokens": 856, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.78793120560257, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.47585673784946525}}
{"text": "//!\n//! Contains the implementation of functions for computing the likelihood.\n//!\n//! \\file likelihood/likelihood.hpp\n//! \\author Darren Shen\n//! \\date May 2014\n//! \\license General Public License version 3 or later\n//! \\copyright (c) 2014, NICTA\n//!\n\n#pragma once\n\n#include <Eigen/Dense>\n\n#include \"datatype/datatypes.hpp\"\n\nnamespace obsidian\n{\n  namespace lh\n  {\n    //! Calculate the Gaussian log likelihood.\n    //! \n    //! \\param real Vector containing the real sensor data.\n    //! \\param candidate Vector containing the simulated sensor data.\n    //! \\param sensorSd The standard deviation of sensor noise.\n    //!\n    double gaussian(const Eigen::VectorXd &real, const Eigen::VectorXd &candidate, double sensorSd);\n\n    //!\n    //! Calculate the normal inverse Gamma marginal log likelihood\n    //! \n    //! \\param real Vector containing the real sensor data\n    //! \\param candidate Vector containing the simulated sensor data\n    //! \\param A, B Alpha and beta parameters\n    //!\n    double normalInverseGamma(const Eigen::VectorXd &real, const Eigen::VectorXd &candidate, double A, double B);\n\n    template<ForwardModel f>\n    double likelihood(const typename Types<f>::Results& synthetic, const typename Types<f>::Results& real,\n                      const typename Types<f>::Spec& spec);\n\n    Eigen::VectorXd mtLikelihoodVector(const Eigen::MatrixX4cd& impedences);\n\n    std::vector<double> likelihoodAll(const GlobalResults& synthetic, const GlobalResults& real, const GlobalSpec& spec,\n                                      const std::set<ForwardModel>& enabled);\n  }\n}\n", "meta": {"hexsha": "600efa8745e744d586c8aabcdb1e89a8fe07dfff", "size": 1587, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/likelihood/likelihood.hpp", "max_stars_repo_name": "NICTA/obsidian", "max_stars_repo_head_hexsha": "911984dae2116415cc30621691d4020c34ea9e15", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2015-01-04T13:50:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-22T01:03:57.000Z", "max_issues_repo_path": "src/likelihood/likelihood.hpp", "max_issues_repo_name": "NICTA/obsidian", "max_issues_repo_head_hexsha": "911984dae2116415cc30621691d4020c34ea9e15", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/likelihood/likelihood.hpp", "max_forks_repo_name": "NICTA/obsidian", "max_forks_repo_head_hexsha": "911984dae2116415cc30621691d4020c34ea9e15", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2016-08-31T05:42:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-21T21:37:47.000Z", "avg_line_length": 33.0625, "max_line_length": 120, "alphanum_fraction": 0.6836798992, "num_tokens": 339, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879312056025699, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4758567378494652}}
{"text": "/***************************************************************************\n* Copyright (c) Johan Mabille, Sylvain Corlay and Wolf Vollprecht          *\n* Copyright (c) QuantStack                                                 *\n*                                                                          *\n* Distributed under the terms of the BSD 3-Clause License.                 *\n*                                                                          *\n* The full license is in the file LICENSE, distributed with this software. *\n****************************************************************************/\n\n#include <benchmark/benchmark.h>\n\n#ifdef HAS_XTENSOR\n#include \"xtensor/xnoalias.hpp\"\n#include \"xtensor/xio.hpp\"\n#include \"xtensor/xrandom.hpp\"\n#include \"xtensor/xtensor.hpp\"\n#include \"xtensor/xarray.hpp\"\n#endif\n\n#ifdef HAS_EIGEN\n#include <Eigen/Dense>\n#include <Eigen/Core>\n#endif\n\n#ifdef HAS_BLITZ\n#include <blitz/array.h>\n#endif\n\n#ifdef HAS_ARMADILLO\n#include <armadillo>\n#endif\n\n#ifdef HAS_PYTHONIC\n#include <pythonic/core.hpp>\n#include <pythonic/python/core.hpp>\n#include <pythonic/types/ndarray.hpp>\n#include <pythonic/numpy/random/rand.hpp>\n#endif\n\n#define RANGE 3, 1000\n#define MULTIPLIER 8\n\n\n#ifdef HAS_XTENSOR\nvoid Add2D_XTensor(benchmark::State& state)\n{\n    using namespace xt;\n\n    xtensor<double, 2> a = random::rand<double>({state.range(0), state.range(0)});\n    xtensor<double, 2> b = random::rand<double>({state.range(0), state.range(0)});\n\n    for (auto _ : state)\n    {\n        xtensor<double, 2> res(a + b);\n        benchmark::DoNotOptimize(res.data());\n    }\n}\nBENCHMARK(Add2D_XTensor)->RangeMultiplier(MULTIPLIER)->Range(RANGE);\n#endif\n\n#ifdef HAS_EIGEN\nvoid Add2D_Eigen(benchmark::State& state)\n{\n    using namespace Eigen;\n    MatrixXd a = MatrixXd::Random(state.range(0), state.range(0));\n    MatrixXd b = MatrixXd::Random(state.range(0), state.range(0));\n    for (auto _ : state)\n    {\n        MatrixXd res(state.range(0), state.range(0));\n        res.noalias() = a + b;\n        benchmark::DoNotOptimize(res.data());\n    }\n}\nBENCHMARK(Add2D_Eigen)->RangeMultiplier(MULTIPLIER)->Range(RANGE);\n#endif\n\n#ifdef HAS_BLITZ\nvoid Add2D_Blitz(benchmark::State& state)\n{\n    using namespace blitz;\n    Array<double, 2> a(state.range(0), state.range(0));\n    Array<double, 2> b(state.range(0), state.range(0));\n    for (auto _ : state)\n    {\n        Array<double, 2> res(a + b);\n        benchmark::DoNotOptimize(res.data());\n    }\n}\nBENCHMARK(Add2D_Blitz)->RangeMultiplier(MULTIPLIER)->Range(RANGE);\n#endif\n\n#ifdef HAS_ARMADILLO\nvoid Add2D_Arma(benchmark::State& state)\n{\n    using namespace arma;\n    mat a = randu<mat>(state.range(0), state.range(0));\n    mat b = randu<mat>(state.range(0), state.range(0));\n    for (auto _ : state)\n    {\n        mat res = a + b;\n        benchmark::DoNotOptimize(res.memptr());\n    }\n}\nBENCHMARK(Add2D_Arma)->RangeMultiplier(MULTIPLIER)->Range(RANGE);\n#endif\n\n#ifdef HAS_PYTHONIC\nvoid Add2D_Pythonic(benchmark::State& state)\n{\n    auto x = pythonic::numpy::random::rand(state.range(0), state.range(0));\n    auto y = pythonic::numpy::random::rand(state.range(0), state.range(0));\n\n    for (auto _ : state)\n    {\n        pythonic::types::ndarray<double, 2> z = x + y;\n        benchmark::DoNotOptimize(z.fbegin());\n    }\n}\nBENCHMARK(Add2D_Pythonic)->RangeMultiplier(MULTIPLIER)->Range(RANGE);\n#endif\n\n#undef RANGE\n#undef MULTIPLIER\n\n", "meta": {"hexsha": "11473482a2d83833ee7bbbb14d155d74e1a624d5", "size": 3398, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/benchmark_add_2d.hpp", "max_stars_repo_name": "breznak/xtensor-benchmark", "max_stars_repo_head_hexsha": "1a4afb5ca75a4119c09a4063975c5bc5aa1d8e66", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-02-26T01:27:57.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-03T09:16:32.000Z", "max_issues_repo_path": "src/benchmark_add_2d.hpp", "max_issues_repo_name": "breznak/xtensor-benchmark", "max_issues_repo_head_hexsha": "1a4afb5ca75a4119c09a4063975c5bc5aa1d8e66", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2018-04-05T07:02:10.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-16T23:06:50.000Z", "max_forks_repo_path": "src/benchmark_add_2d.hpp", "max_forks_repo_name": "breznak/xtensor-benchmark", "max_forks_repo_head_hexsha": "1a4afb5ca75a4119c09a4063975c5bc5aa1d8e66", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-02-21T08:08:57.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-30T13:59:03.000Z", "avg_line_length": 27.184, "max_line_length": 82, "alphanum_fraction": 0.6047675103, "num_tokens": 877, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879312056025699, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4758567378494652}}
{"text": "#pragma once\n\n#include <polyfem/Problem.hpp>\n#include <polyfem/ExpressionValue.hpp>\n\n#include <vector>\n#include <Eigen/Dense>\n\nnamespace polyfem\n{\n\tclass GenericTensorProblem: public Problem\n\t{\n\tpublic:\n\t\tGenericTensorProblem(const std::string &name);\n\n\t\tvoid rhs(const std::string &formulation, const Eigen::MatrixXd &pts, const double t, Eigen::MatrixXd &val) const override;\n\t\tbool is_rhs_zero() const override { return fabs(rhs_.maxCoeff())<1e-10 && fabs(rhs_.minCoeff())<1e-10; }\n\n\t\tvoid bc(const Mesh &mesh, const Eigen::MatrixXi &global_ids, const Eigen::MatrixXd &uv, const Eigen::MatrixXd &pts, const double t, Eigen::MatrixXd &val) const override;\n\t\tvoid neumann_bc(const Mesh &mesh, const Eigen::MatrixXi &global_ids, const Eigen::MatrixXd &uv, const Eigen::MatrixXd &pts, const double t, Eigen::MatrixXd &val) const override;\n\n\t\tbool has_exact_sol() const override { return false; }\n\t\tbool is_scalar() const override { return false; }\n\n\t\tvoid set_parameters(const json &params) override;\n\n\t\tbool is_dimention_dirichet(const int tag, const int dim) const override;\n\t\tbool all_dimentions_dirichelt() const override { return all_dimentions_dirichelt_; }\n\n\t\t// bool is_mixed() const override { return is_mixed_; }\n\tprivate:\n\t\tbool all_dimentions_dirichelt_ = true;\n\t\t// bool is_mixed_ = false;\n\n\t\tstd::vector<Eigen::Matrix<ExpressionValue, 1, 3, Eigen::RowMajor>> forces_;\n\t\tstd::vector<Eigen::Matrix<ExpressionValue, 1, 3, Eigen::RowMajor>> displacements_;\n\n\t\tstd::vector<Eigen::Matrix<bool, 1, 3, Eigen::RowMajor>> dirichelt_dimentions_;\n\n\t\tEigen::Matrix<double, 1, 3, Eigen::RowMajor> rhs_;\n\t\tbool is_all_;\n\t};\n\n\n\tclass GenericScalarProblem: public Problem\n\t{\n\tpublic:\n\t\tGenericScalarProblem(const std::string &name);\n\n\t\tvoid rhs(const std::string &formulation, const Eigen::MatrixXd &pts, const double t, Eigen::MatrixXd &val) const override;\n\t\tbool is_rhs_zero() const override { return fabs(rhs_) < 1e-10; }\n\n\t\tvoid bc(const Mesh &mesh, const Eigen::MatrixXi &global_ids, const Eigen::MatrixXd &uv, const Eigen::MatrixXd &pts, const double t, Eigen::MatrixXd &val) const override;\n\t\tvoid neumann_bc(const Mesh &mesh, const Eigen::MatrixXi &global_ids, const Eigen::MatrixXd &uv, const Eigen::MatrixXd &pts, const double t, Eigen::MatrixXd &val) const override;\n\n\t\tbool has_exact_sol() const override { return false; }\n\t\tbool is_scalar() const override { return true; }\n\n\t\tvoid set_parameters(const json &params) override;\n\n\tprivate:\n\t\tstd::vector<Eigen::Matrix<ExpressionValue, 1, 1, Eigen::RowMajor>> neumann_;\n\t\tstd::vector<Eigen::Matrix<ExpressionValue, 1, 1, Eigen::RowMajor>> dirichlet_;\n\n\t\tdouble rhs_;\n\t\tbool is_all_;\n\t};\n}\n\n", "meta": {"hexsha": "a7edcc2fcde70344507b54c79234b3965184d839", "size": 2646, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/problem/GenericProblem.hpp", "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/problem/GenericProblem.hpp", "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/problem/GenericProblem.hpp", "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": 37.8, "max_line_length": 179, "alphanum_fraction": 0.7396069539, "num_tokens": 710, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.47585673183450017}}
{"text": "/*\n\nCopyright (c) 2005-2018, University of Oxford.\nAll rights reserved.\n\nUniversity of Oxford means the Chancellor, Masters and Scholars of the\nUniversity of Oxford, having an administrative office at Wellington\nSquare, Oxford OX1 2JD, UK.\n\nThis file is part of Chaste.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n * Redistributions of source code must retain the above copyright notice,\n   this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice,\n   this list of conditions and the following disclaimer in the documentation\n   and/or other materials provided with the distribution.\n * Neither the name of the University of Oxford nor the names of its\n   contributors may be used to endorse or promote products derived from this\n   software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\nGOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\nHOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\nLIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\nOF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*/\n\n#ifndef AVERAGESOURCEPARABOLICPDE_HPP_\n#define AVERAGESOURCEPARABOLICPDE_HPP_\n\n#include \"ChasteSerialization.hpp\"\n#include <boost/serialization/base_object.hpp>\n\n#include \"AbstractCellPopulation.hpp\"\n#include \"TetrahedralMesh.hpp\"\n#include \"AbstractLinearParabolicPde.hpp\"\n\n/**\n * A parabolic PDE to be solved numerically using the finite element method, for\n * coupling to a cell-based simulation.\n *\n * The PDE takes the form\n *\n * c*du/dt = Grad.(D*Grad(u)) + k*u*rho(x),\n *\n * where the scalars c, D and k are specified by the members mDuDtCoefficient,\n * mDiffusionCoefficient and mSourceCoefficient, respectively. Their values must\n * be set in the constructor.\n *\n * The function rho(x) denotes the local density of non-apoptotic cells. This\n * quantity is computed for each element of a 'coarse' finite element mesh that is\n * passed to the method SetupSourceTerms() and stored in the member mCellDensityOnCoarseElements.\n * For a point x, rho(x) is defined to be the number of non-apoptotic cells whose\n * centres lie in each finite element containing that point, scaled by the area of\n * that element.\n */\ntemplate<unsigned DIM>\nclass AveragedSourceParabolicPde : public AbstractLinearParabolicPde<DIM,DIM>\n{\n    friend class TestCellBasedParabolicPdes;\n\nprivate:\n\n    /** Needed for serialization.*/\n    friend class boost::serialization::access;\n    /**\n     * Serialize the PDE and its member variables.\n     *\n     * @param archive the archive\n     * @param version the current version of this class\n     */\n    template<class Archive>\n    void serialize(Archive & archive, const unsigned int version)\n    {\n       archive & boost::serialization::base_object<AbstractLinearParabolicPde<DIM, DIM> >(*this);\n       archive & mDuDtCoefficient;\n       archive & mDiffusionCoefficient;\n       archive & mSourceCoefficient;\n       archive & mCellDensityOnCoarseElements;\n    }\n\nprotected:\n\n    /** The cell population member. */\n    AbstractCellPopulation<DIM, DIM>& mrCellPopulation;\n\n    /** Coefficient of rate of change term.  */\n    double mDuDtCoefficient;\n\n    /** Diffusion coefficient. */\n    double mDiffusionCoefficient;\n\n    /** Coefficient of the rate of uptake of the dependent variable by non-apoptotic cells. */\n    double mSourceCoefficient;\n\n    /** Vector of averaged cell densities on elements of the coarse mesh. */\n    std::vector<double> mCellDensityOnCoarseElements;\n\npublic:\n\n    /**\n     * Constructor.\n     *\n     * @param rCellPopulation reference to the cell population\n     * @param duDtCoefficient rate of reaction (defaults to 1.0)\n     * @param diffusionCoefficient rate of diffusion (defaults to 1.0)\n     * @param sourceCoefficient the source term coefficient (defaults to 0.0)\n     */\n    AveragedSourceParabolicPde(AbstractCellPopulation<DIM, DIM>& rCellPopulation,\n                               double duDtCoefficient=1.0,\n                               double diffusionCoefficient=1.0,\n                               double sourceCoefficient=0.0);\n\n    /**\n     * @return const reference to the cell population (used in archiving).\n     */\n    const AbstractCellPopulation<DIM>& rGetCellPopulation() const;\n\n    /**\n     * Set up the source terms.\n     *\n     * \\todo this is identical to the one in AveragedSourceEllipticPde so refactor.\n     *\n     * @param rCoarseMesh reference to the coarse mesh\n     * @param pCellPdeElementMap optional pointer to the map from cells to coarse elements\n     */\n    void virtual SetupSourceTerms(TetrahedralMesh<DIM,DIM>& rCoarseMesh, std::map<CellPtr, unsigned>* pCellPdeElementMap=nullptr);\n\n    /**\n     * Overridden ComputeDuDtCoefficientFunction() method.\n     *\n     * @return the function c(x) in \"c(x) du/dt = Grad.(DiffusionTerm(x)*Grad(u))+LinearSourceTerm(x)+NonlinearSourceTerm(x, u)\"\n     *\n     * @param rX the point in space at which the function c is computed\n     */\n    virtual double ComputeDuDtCoefficientFunction(const ChastePoint<DIM>& rX);\n\n    /**\n     * Overridden ComputeSourceTerm() method.\n     *\n     * @return computed source term.\n     *\n     * @param rX the point in space at which the nonlinear source term is computed\n     * @param u the value of the dependent variable at the point\n     * @param pElement the mesh element that x is contained in (optional; defaults to NULL).\n     */\n    virtual double ComputeSourceTerm(const ChastePoint<DIM>& rX,\n                                     double u,\n                                     Element<DIM,DIM>* pElement=NULL);\n\n    /**\n     * Overridden ComputeSourceTermAtNode() method. That is never called.\n     *\n     * @return computed source term at a node.\n     *\n     * @param rNode the node at which the nonlinear source term is computed\n     * @param u the value of the dependent variable at the node\n     */\n    virtual double ComputeSourceTermAtNode(const Node<DIM>& rNode, double u);\n\n    /**\n     * Overridden ComputeDiffusionTerm() method.\n     *\n     * @param rX the point in space at which the diffusion term is computed\n     * @param pElement the mesh element that x is contained in (optional; defaults to NULL).\n     *\n     * @return a matrix.\n     */\n    virtual c_matrix<double,DIM,DIM> ComputeDiffusionTerm(const ChastePoint<DIM>& rX, Element<DIM,DIM>* pElement=NULL);\n\n    /**\n     * @return the uptake rate.\n     *\n     * @param elementIndex the element we wish to return the uptake rate for\n     */\n    double GetUptakeRateForElement(unsigned elementIndex);\n};\n\n#include \"SerializationExportWrapper.hpp\"\nEXPORT_TEMPLATE_CLASS_SAME_DIMS(AveragedSourceParabolicPde)\n\nnamespace boost\n{\nnamespace serialization\n{\n/**\n * Serialize information required to construct a AveragedSourceParabolicPde.\n */\ntemplate<class Archive, unsigned DIM>\ninline void save_construct_data(\n    Archive & ar, const AveragedSourceParabolicPde<DIM>* t, const unsigned int file_version)\n{\n    // Save data required to construct instance\n    const AbstractCellPopulation<DIM, DIM>* p_cell_population = &(t->rGetCellPopulation());\n    ar & p_cell_population;\n}\n\n/**\n * De-serialize constructor parameters and initialise a AveragedSourceParabolicPde.\n */\ntemplate<class Archive, unsigned DIM>\ninline void load_construct_data(\n    Archive & ar, AveragedSourceParabolicPde<DIM>* t, const unsigned int file_version)\n{\n    // Retrieve data from archive required to construct new instance\n    AbstractCellPopulation<DIM, DIM>* p_cell_population;\n    ar >> p_cell_population;\n\n    // Invoke inplace constructor to initialise instance\n    ::new(t)AveragedSourceParabolicPde<DIM>(*p_cell_population);\n}\n}\n} // namespace ...\n\n#endif /*AVERAGESOURCEPARABOLICPDE_HPP_*/\n", "meta": {"hexsha": "3b583cb7372e5fd7360c3c2532138164bf51e4c4", "size": 8332, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cell_based/src/cell_based_pde/pdes/AveragedSourceParabolicPde.hpp", "max_stars_repo_name": "DGermano8/ChasteDom", "max_stars_repo_head_hexsha": "539a3a811698214c0938489b0cfdffd1abccf667", "max_stars_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cell_based/src/cell_based_pde/pdes/AveragedSourceParabolicPde.hpp", "max_issues_repo_name": "DGermano8/ChasteDom", "max_issues_repo_head_hexsha": "539a3a811698214c0938489b0cfdffd1abccf667", "max_issues_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cell_based/src/cell_based_pde/pdes/AveragedSourceParabolicPde.hpp", "max_forks_repo_name": "DGermano8/ChasteDom", "max_forks_repo_head_hexsha": "539a3a811698214c0938489b0cfdffd1abccf667", "max_forks_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.1964285714, "max_line_length": 130, "alphanum_fraction": 0.7225156025, "num_tokens": 1882, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.47585673183450017}}
{"text": "#include <CGAL/Simple_cartesian.h>\n#include <CGAL/boost/graph/graph_traits_Triangulation_2.h>\n\n#include <boost/graph/graph_test.hpp>\n#include <boost/graph/random.hpp>\n#include <boost/assign.hpp>\n\ntypedef CGAL::Simple_cartesian<double> Kernel;\ntypedef CGAL::Triangulation_2<Kernel> Triangulation;\ntypedef typename Triangulation::Point Point;\ntypedef typename Triangulation::Vertex Vertex;\ntypedef typename Triangulation::Vertex Vertex_handle;\n\nint test_main(int, char*[])\n{\n  using namespace boost::assign;\n\n  Triangulation t;\n  {\n    std::vector<Point> v;\n    // taken from the triangulation test cases, should be randomly generated\n    v += Point(5,6,1), Point(1,9,1), Point(6,14,1), Point(4,12,1), Point(3,29,1),  Point(6,7,1),\n      Point(6,39,1), Point(8,9,1), Point(10,18,1), Point(75625,155625,10000),\n      Point(10,50,2), Point(6,15,2), Point(6,16,2), Point(10,11,1),\n      Point(10,40,1), Point(60,-10,1);\n\n    t.insert(v.begin(), v.end());\n  }\n  \n  typedef typename boost::graph_traits<Triangulation>::vertex_descriptor vertex_t;\n  std::vector<vertex_t> vv;\n  for(typename Triangulation::Finite_vertices_iterator it = t.finite_vertices_begin(); \n      it != t.finite_vertices_end(); ++it) { \n    vv.push_back(it);\n  }\n\n\n  std::vector< std::pair<vertex_t, vertex_t> > e;\n  for(Triangulation::All_edges_iterator it = t.all_edges_begin(); \n      it != t.all_edges_end(); ++it) { \n    e.push_back(\n      std::make_pair(\n        it->first->vertex((it->second + 2) % 3)\n        , it->first->vertex((it->second + 1) % 3)));\n  }\n\n  boost::graph_test<Triangulation> gt;\n  gt.test_bidirectional_graph(vv, e, t);\n  return 0;\n}\n\n\n", "meta": {"hexsha": "b1a68271b073ac753ea56b0cdb8d2fad3fd8aab6", "size": 1628, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "graphics/cgal/BGL/test/BGL/test_Triangulation_2.cpp", "max_stars_repo_name": "hlzz/dotfiles", "max_stars_repo_head_hexsha": "0591f71230c919c827ba569099eb3b75897e163e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-03-30T14:31:52.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-02T05:01:32.000Z", "max_issues_repo_path": "graphics/cgal/BGL/test/BGL/test_Triangulation_2.cpp", "max_issues_repo_name": "hlzz/dotfiles", "max_issues_repo_head_hexsha": "0591f71230c919c827ba569099eb3b75897e163e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "graphics/cgal/BGL/test/BGL/test_Triangulation_2.cpp", "max_forks_repo_name": "hlzz/dotfiles", "max_forks_repo_head_hexsha": "0591f71230c919c827ba569099eb3b75897e163e", "max_forks_repo_licenses": ["BSD-3-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.7169811321, "max_line_length": 96, "alphanum_fraction": 0.67997543, "num_tokens": 500, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311856832191, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.47585672581953503}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// Unit Test\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\n#include <geometry_test_common.hpp>\n\n#include <boost/geometry/strategies/strategy_transform.hpp>\n#include <boost/geometry/algorithms/transform.hpp>\n#include <boost/geometry/geometries/point.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n\ntemplate <typename T, typename P>\ninline T check_distance(P const& p)\n{\n    T x = bg::get<0>(p);\n    T y = bg::get<1>(p);\n    T z = bg::get<2>(p);\n    return sqrt(x * x + y * y + z * z);\n}\n\ntemplate <typename T>\nvoid test_transformations_spherical()\n{\n    T const input_long = 15.0;\n    T const input_lat = 5.0;\n\n    T const expected_long = 0.26179938779914943653855361527329;\n    T const expected_lat = 0.08726646259971647884618453842443;\n\n    // Can be checked using http://www.calc3d.com/ejavascriptcoordcalc.html\n    // (for phi use long, in radians, for theta use lat, in radians, they are listed there as \"theta, phi\")\n    T const expected_polar_x = 0.084186;\n    T const expected_polar_y = 0.0225576;\n    T const expected_polar_z = 0.996195;\n\n    // Can be checked with same URL using 90-theta for lat.\n    // So for theta use 85 degrees, in radians: 0.08726646259971647884618453842443\n    T const expected_equatorial_x = 0.962250;\n    T const expected_equatorial_y = 0.257834;\n    T const expected_equatorial_z = 0.0871557;\n\n    // 1: Spherical-polar (lat=5, so it is near the pole - on a unit sphere)\n    bg::model::point<T, 2, bg::cs::spherical<bg::degree> > sp(input_long, input_lat);\n\n    // 1a: to radian\n    bg::model::point<T, 2, bg::cs::spherical<bg::radian> > spr;\n    bg::transform(sp, spr);\n    BOOST_CHECK_CLOSE(bg::get<0>(spr), expected_long, 0.001);\n    BOOST_CHECK_CLOSE(bg::get<1>(spr), expected_lat, 0.001);\n\n    // 1b: to cartesian-3d\n    bg::model::point<T, 3, bg::cs::cartesian> pc3;\n    bg::transform(sp, pc3);\n    BOOST_CHECK_CLOSE(bg::get<0>(pc3), expected_polar_x, 0.001);\n    BOOST_CHECK_CLOSE(bg::get<1>(pc3), expected_polar_y, 0.001);\n    BOOST_CHECK_CLOSE(bg::get<2>(pc3), expected_polar_z, 0.001);\n    BOOST_CHECK_CLOSE(check_distance<T>(pc3), 1.0, 0.001);\n\n    // 1c: back\n    bg::transform(pc3, spr);\n    BOOST_CHECK_CLOSE(bg::get<0>(spr), expected_long, 0.001);\n    BOOST_CHECK_CLOSE(bg::get<1>(spr), expected_lat, 0.001);\n\n    // 2: Spherical-equatorial (lat=5, so it is near the equator)\n    bg::model::point<T, 2, bg::cs::spherical_equatorial<bg::degree> > se(input_long, input_lat);\n\n    // 2a: to radian \n    bg::model::point<T, 2, bg::cs::spherical_equatorial<bg::radian> > ser;\n    bg::transform(se, ser);\n    BOOST_CHECK_CLOSE(bg::get<0>(ser), expected_long, 0.001);\n    BOOST_CHECK_CLOSE(bg::get<1>(ser), expected_lat, 0.001);\n\n    bg::transform(se, pc3);\n    BOOST_CHECK_CLOSE(bg::get<0>(pc3), expected_equatorial_x, 0.001);\n    BOOST_CHECK_CLOSE(bg::get<1>(pc3), expected_equatorial_y, 0.001);\n    BOOST_CHECK_CLOSE(bg::get<2>(pc3), expected_equatorial_z, 0.001);\n    BOOST_CHECK_CLOSE(check_distance<T>(pc3), 1.0, 0.001);\n\n    // 2c: back\n    bg::transform(pc3, ser);\n    BOOST_CHECK_CLOSE(bg::get<0>(spr), expected_long, 0.001);  // expected_long\n    BOOST_CHECK_CLOSE(bg::get<1>(spr), expected_lat, 0.001); // expected_lat\n\n\n    // 3: Spherical-polar including radius\n    bg::model::point<T, 3, bg::cs::spherical<bg::degree> > sp3(input_long, input_lat, 0.5);\n\n    // 3a: to radian\n    bg::model::point<T, 3, bg::cs::spherical<bg::radian> > spr3;\n    bg::transform(sp3, spr3);\n    BOOST_CHECK_CLOSE(bg::get<0>(spr3), expected_long, 0.001);\n    BOOST_CHECK_CLOSE(bg::get<1>(spr3), expected_lat, 0.001);\n    BOOST_CHECK_CLOSE(bg::get<2>(spr3), 0.5, 0.001);\n\n    // 3b: to cartesian-3d\n    bg::transform(sp3, pc3);\n    BOOST_CHECK_CLOSE(bg::get<0>(pc3), expected_polar_x / 2.0, 0.001);\n    BOOST_CHECK_CLOSE(bg::get<1>(pc3), expected_polar_y / 2.0, 0.001);\n    BOOST_CHECK_CLOSE(bg::get<2>(pc3), expected_polar_z / 2.0, 0.001);\n    BOOST_CHECK_CLOSE(check_distance<T>(pc3), 0.5, 0.001);\n\n    // 3c: back\n    bg::transform(pc3, spr3);\n    BOOST_CHECK_CLOSE(bg::get<0>(spr3), expected_long, 0.001);\n    BOOST_CHECK_CLOSE(bg::get<1>(spr3), expected_lat, 0.001);\n    BOOST_CHECK_CLOSE(bg::get<2>(spr3), 0.5, 0.001);\n\n\n    // 4: Spherical-equatorial including radius\n    bg::model::point<T, 3, bg::cs::spherical_equatorial<bg::degree> > se3(input_long, input_lat, 0.5);\n\n    // 4a: to radian\n    bg::model::point<T, 3, bg::cs::spherical_equatorial<bg::radian> > ser3;\n    bg::transform(se3, ser3);\n    BOOST_CHECK_CLOSE(bg::get<0>(ser3), expected_long, 0.001);\n    BOOST_CHECK_CLOSE(bg::get<1>(ser3), expected_lat, 0.001);\n    BOOST_CHECK_CLOSE(bg::get<2>(ser3), 0.5, 0.001);\n\n    // 4b: to cartesian-3d\n    bg::transform(se3, pc3);\n    BOOST_CHECK_CLOSE(bg::get<0>(pc3), expected_equatorial_x / 2.0, 0.001);\n    BOOST_CHECK_CLOSE(bg::get<1>(pc3), expected_equatorial_y / 2.0, 0.001);\n    BOOST_CHECK_CLOSE(bg::get<2>(pc3), expected_equatorial_z / 2.0, 0.001);\n    BOOST_CHECK_CLOSE(check_distance<T>(pc3), 0.5, 0.001);\n\n    // 4c: back\n    bg::transform(pc3, ser3);\n    BOOST_CHECK_CLOSE(bg::get<0>(ser3), expected_long, 0.001);\n    BOOST_CHECK_CLOSE(bg::get<1>(ser3), expected_lat, 0.001);\n    BOOST_CHECK_CLOSE(bg::get<2>(ser3), 0.5, 0.001);\n}\n\nint test_main(int, char* [])\n{\n    test_transformations_spherical<double>();\n\n    return 0;\n}\n", "meta": {"hexsha": "36b327e3efc5f6d2ac851f408368b2c71274e229", "size": 5828, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/geometry/test/strategies/transform_cs.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2016-04-12T16:29:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-28T11:01:57.000Z", "max_issues_repo_path": "boost/libs/geometry/test/strategies/transform_cs.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-10-31T19:35:14.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-04T17:11:27.000Z", "max_forks_repo_path": "boost/libs/geometry/test/strategies/transform_cs.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-09-09T02:38:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-30T00:24:24.000Z", "avg_line_length": 38.8533333333, "max_line_length": 107, "alphanum_fraction": 0.6781056966, "num_tokens": 1950, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.787931185683219, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4758567258195349}}
{"text": "#include \"spectral_clustering.h\"\n\n#include <set>\n#include <array>\n#include <algorithm>\n\n#include <Eigen/Sparse>\n#include <igl/eigs.h>\n\n#include <algorithms/shortest_path.h>\n\nusing namespace shortest_path;\n\nSpectralClustering::SpectralClustering(std::shared_ptr<Geometry> geometry, unsigned int k, double delta, double eta):\n\t_delta(delta),\n\t_eta(eta) {\n\n\tif (geometry == nullptr) {\n\t\treturn;\n\t}\n\n\t// Generate affinity matrix from mesh faces\n\tEigen::MatrixXd W = affinity_matrix(geometry);\n\n\t// Degree matrix\n\tEigen::DiagonalMatrix<double, -1> Ds = W.rowwise().sum().cwiseInverse().cwiseSqrt().asDiagonal();\n\n\t// Graph Laplacian\n\tEigen::MatrixXd L = Ds * (W * Ds);\n\n\tEigen::MatrixXd M = Eigen::MatrixXd::Identity(L.rows(), L.cols());\n\n\tEigen::GeneralizedSelfAdjointEigenSolver<Eigen::MatrixXd> es(L, M, Eigen::ComputeEigenvectors);\n\tEigen::MatrixXd U = es.eigenvectors().real().rightCols(k);\n\n\t// kmeans clustering\n\tEigen::MatrixXd V = U.colwise().normalized();\n\tEigen::MatrixXd Q = V * V.transpose();\n\n\t// Group faces by clusters\n\tEigen::VectorXi guess = initial_guess(Q, k);\n\n\t_segment_by_face = k_means_lloyds(guess, V, k);\n}\n\nSpectralClustering::~SpectralClustering() {\n}\n\nconst Eigen::VectorXi& SpectralClustering::segment_by_face() const {\n\treturn _segment_by_face;\n}\n\nEigen::MatrixXd SpectralClustering::affinity_matrix(std::shared_ptr<Geometry> geometry) {\n\tEigen::SparseMatrix<double> G(geometry->faces().rows(), geometry->faces().rows());\n\tEigen::SparseMatrix<double> A(geometry->faces().rows(), geometry->faces().rows());\n\n\tstd::set<Eigen::DenseIndex> eta_list;\n\tunsigned int num_adj = 0;\n\tconst Eigen::SparseMatrix<int>& adj = geometry->adjacency_matrix();\n\tconst trimesh::trimesh_t& halfedge_mesh = geometry->halfedge();\n\n\tunsigned int count = 0;\n\n\tstd::vector<Eigen::Triplet<double>> g_triplets;\n\tstd::vector<Eigen::Triplet<double>> a_triplets;\n\tEigen::DenseIndex v_count = geometry->vertices().rows();\n\tfor (Eigen::DenseIndex i = 0; i < v_count; ++i) {\n\t\tfor (Eigen::DenseIndex j = i + 1; j < v_count; ++j) {\n\t\t\ttrimesh::index_t he_index = halfedge_mesh.directed_edge2he_index(i, j);\n\n\t\t\tif (he_index < 0) {\n\t\t\t\t// Invalid vertex pair??\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst trimesh::trimesh_t::halfedge_t& he = halfedge_mesh.halfedge(he_index);\n\t\t\tconst trimesh::trimesh_t::halfedge_t& op_he = halfedge_mesh.halfedge(he.opposite_he);\n\n\t\t\tif (he.face < 0 || op_he.face < 0) {\n\t\t\t\t// This edge is on a boundary!\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tEigen::DenseIndex r = he.face;\n\t\t\tEigen::DenseIndex s = op_he.face;\n\n\t\t\tEigen::VectorXi face1 = geometry->faces().row(r);\n\t\t\tEigen::VectorXi face2 = geometry->faces().row(s);\n\n\t\t\tdouble gd = geodesic_distance({ he.to_vertex, op_he.to_vertex }, face1, face2, geometry->vertices());\n\t\t\tdouble ad = angular_distance(face1, face2, geometry->vertices());\n\n\t\t\tg_triplets.emplace_back(Eigen::Triplet<double>(r, s, gd));\n\t\t\tg_triplets.emplace_back(Eigen::Triplet<double>(s, r, gd));\n\t\t\ta_triplets.emplace_back(Eigen::Triplet<double>(r, s, ad));\n\t\t\ta_triplets.emplace_back(Eigen::Triplet<double>(s, r, ad));\n\n\t\t\t++count;\n\t\t}\n\t}\n\n\tdouble geodesic_avg = 0.0;\n\tdouble angular_avg = 0.0;\n\n\tG.setFromTriplets(g_triplets.begin(), g_triplets.end());\n\tA.setFromTriplets(a_triplets.begin(), a_triplets.end());\n\n\tif (count > 0) {\n\t\tgeodesic_avg = G.sum() / static_cast<double>(2 * count);\n\t\tangular_avg = A.sum() / static_cast<double>(2 * count);\n\t}\n\n\tG = G * (_delta / geodesic_avg);\n\tA = A * ((1.0 - _delta) / angular_avg);\n\n\tEigen::MatrixXd W = floyd_warshall(G + A);\n\n\tstd::vector<std::pair<Eigen::DenseIndex, Eigen::DenseIndex>> inf_entries;\n\tfor (Eigen::DenseIndex i = 0; i < W.rows(); ++i) {\n\t\tfor (Eigen::DenseIndex j = 0; j < W.cols(); ++j) {\n\t\t\tif (W(i, j) > std::numeric_limits<double>::max()) {\n\t\t\t\tW(i, j) = 0.0;\n\t\t\t\tinf_entries.emplace_back(std::pair<Eigen::DenseIndex, Eigen::DenseIndex>(i, j));\n\t\t\t}\n\t\t}\n\t}\n\n\tdouble sigma = W.sum() / (std::pow(geometry->faces().rows(), 2.0));\n\tdouble den = 2 * std::pow(sigma, 2.0);\n\tW = -1.0 * W / den;\n\n\tfor (Eigen::DenseIndex i = 0; i < W.rows(); ++i) {\n\t\tfor (Eigen::DenseIndex j = 0; j < W.cols(); ++j) {\n\t\t\tW(i, j) = std::exp(W(i, j));\n\t\t}\n\t}\n\n\tfor (auto it : inf_entries) {\n\t\tW(it.first, it.second) = 0.0;\n\t}\n\n\tfor (Eigen::DenseIndex i = 0; i < W.rows(); ++i) {\n\t\tW(i, i) = 1.0;\n\t}\n\n\treturn W;\n}\n\ndouble SpectralClustering::geodesic_distance(std::array<Eigen::DenseIndex,2> edge_verts, const Eigen::VectorXi& face1, const Eigen::VectorXi& face2, const Eigen::MatrixXd& V) const {\n\tif (face1.size() <= 0 || face2.size() <= 0) {\n\t\treturn 0.0;\n\t}\n\n\tEigen::VectorXd edge_center = (V.row(edge_verts[0]) + V.row(edge_verts[1])).transpose() / 2.0;\n\n\tEigen::VectorXd face1_center = Eigen::VectorXd::Zero(edge_center.rows());\n\tfor (Eigen::DenseIndex i = 0; i < face1.size(); ++i) {\n\t\tface1_center += V.row(face1(i)).transpose();\n\t}\n\tface1_center /= face1.size();\n\n\tEigen::VectorXd face2_center = Eigen::VectorXd::Zero(edge_center.rows());\n\tfor (Eigen::DenseIndex i = 0; i < face2.size(); ++i) {\n\t\tface2_center += V.row(face2(i)).transpose();\n\t}\n\tface2_center /= face2.size();\n\n\treturn (edge_center - face1_center).norm() + (edge_center - face2_center).norm();\n}\n\ndouble SpectralClustering::angular_distance(const Eigen::VectorXi& face1, const Eigen::VectorXi& face2, const Eigen::MatrixXd& V) const {\n\tif (face1.size() != 3 || face2.size() != 3) {\n\t\treturn 0.0;\n\t}\n\n\tEigen::Vector3d e1 = (V.row(face1(0)) - V.row(face1(1))).block<1, 3>(0, 0).normalized().transpose();\n\tEigen::Vector3d e2 = (V.row(face1(2)) - V.row(face1(1))).block<1, 3>(0, 0).normalized().transpose();\n\n\tEigen::Vector3d face1_normal = e1.cross(e2).normalized();\n\n\te1 = (V.row(face2(0)) - V.row(face2(1))).block<1, 3>(0, 0).normalized().transpose();\n\te2 = (V.row(face2(2)) - V.row(face2(1))).block<1, 3>(0, 0).normalized().transpose();\n\n\tEigen::Vector3d face2_normal = e1.cross(e2).normalized();\n\n\tEigen::VectorXd face1_center = Eigen::VectorXd::Zero(V.row(face1(0)).cols());\n\tfor (Eigen::DenseIndex i = 0; i < face1.size(); ++i) {\n\t\tface1_center += V.row(face1(i)).transpose();\n\t}\n\tface1_center /= face1.size();\n\n\tEigen::VectorXd face2_center = Eigen::VectorXd::Zero(V.row(face2(0)).cols());\n\tfor (Eigen::DenseIndex i = 0; i < face2.size(); ++i) {\n\t\tface2_center += V.row(face2(i)).transpose();\n\t}\n\tface2_center /= face2.size();\n\n\tbool use_eta = face1_normal.dot((face2_center - face1_center).block<3, 1>(0, 0).normalized()) < 0.0;\n\t\n\treturn ((use_eta) ? _eta : 1.0) * (1.0 - face1_normal.dot(face2_normal));\n}\n\nEigen::VectorXi SpectralClustering::k_means_lloyds(const Eigen::VectorXi& guess, const Eigen::MatrixXd& V, unsigned int k) {\n\t// guess\n\tEigen::VectorXi means = guess; //initial_guess(V, k);\n\tEigen::VectorXi prev_means = means;\n\n\tstd::cout << means << std::endl; \n\n\tEigen::VectorXi assignment = Eigen::VectorXi::Constant(V.rows(),-1);\n\tEigen::VectorXi next_assignment = assignment;\n\n\tdouble stop_threshold = 0.001 * means.rowwise().norm().minCoeff();\n\n\tdo {\n\t\t// assign\n\t\tfor (Eigen::DenseIndex i = 0; i < V.rows(); ++i) {\n\t\t\tdouble min_dist = std::numeric_limits<double>::max();\n\t\t\tEigen::DenseIndex min_index = -1;\n\n\t\t\tfor (Eigen::DenseIndex j = 0; j < means.rows(); ++j) {\n\t\t\t\tdouble dist = (V.row(means(j)) - V.row(i)).norm();\n\n\t\t\t\tif (dist < min_dist) {\n\t\t\t\t\tmin_dist = dist;\n\t\t\t\t\tmin_index = j;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (min_index < 0) {\n\t\t\t\t// There was no nearest centroid?? Something is wrong..\n\t\t\t\tthrow std::logic_error(\"Finding nearest centroid failed??\");\n\t\t\t}\n\n\t\t\tnext_assignment(i) = min_index;\n\t\t}\n\n\t\tif ((assignment - next_assignment).sum() == 0) {\n\t\t\t// converged\n\t\t\tstd::cout << \"Converged!\" << std::endl;\n\t\t\tbreak;\n\t\t}\n\n\t\t// update\n\t\tassignment = next_assignment;\n\n\t\tEigen::MatrixXd numeric_means = Eigen::MatrixXd::Zero(means.rows(), V.cols());\n\t\tEigen::VectorXi c_count = Eigen::VectorXi::Zero(means.rows());\n\t\tmeans = Eigen::VectorXi::Zero(k);\n\n\t\tfor (Eigen::DenseIndex i = 0; i < assignment.rows(); ++i) {\n\t\t\tnumeric_means.row(assignment(i)) += V.row(i);\n\t\t\tc_count(assignment(i))++;\n\t\t}\n\n\t\tfor (Eigen::DenseIndex i = 0; i < c_count.rows(); ++i) {\n\t\t\tif (c_count(i) > 0) {\n\t\t\t\tnumeric_means.row(i) /= c_count(i);\n\t\t\t}\n\t\t}\n\n\t\t// Find nearest vector in V closest to each numeric mean\n\t\tfor (Eigen::DenseIndex i = 0; i < numeric_means.rows(); ++i) {\n\t\t\tdouble min_dist = std::numeric_limits<double>::max();\n\t\t\tEigen::DenseIndex min_index = -1;\n\n\t\t\tfor (Eigen::DenseIndex j = 0; j < V.rows(); ++j) {\n\t\t\t\tdouble dist = (V.row(j) - numeric_means.row(i)).norm();\n\n\t\t\t\tif (dist < min_dist) {\n\t\t\t\t\tmin_dist = dist;\n\t\t\t\t\tmin_index = j;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (min_index < 0) {\n\t\t\t\t// There was no nearest vector?? Something is wrong..\n\t\t\t\tthrow std::logic_error(\"Finding nearest point to centroid failed??\");\n\t\t\t}\n\n\t\t\tmeans(i) = min_index;\n\t\t}\n\n\t\tprev_means = means;\n\n\t} while (true);\n\n\tstd::cout << means << std::endl;\n\n\treturn next_assignment;\n}\n\nEigen::VectorXi SpectralClustering::initial_guess(const Eigen::MatrixXd& Q, unsigned int k) {\n\t//\"\"\"Computes an initial guess for the cluster-centers\"\"\"\n\tint n = Q.rows();\n\tdouble min_value = std::numeric_limits<double>::max();\n\tstd::array<int, 2> min_indices = { -1, -1 };\n\n\tfor (int i = 0; i < Q.rows(); ++i) {\n\t\tfor (int j = 0; j < Q.cols(); ++j) {\n\t\t\tif (i != j && Q(i, j) < min_value) {\n\t\t\t\tmin_value = Q(i, j);\n\t\t\t\tmin_indices = { i, j };\n\t\t\t}\n\t\t}\n\t}\n\t\n\tstd::set<int> chosen = { min_indices[0], min_indices[1] };\n\n\twhile (chosen.size() < k) {\n\t\tdouble min_max = std::numeric_limits<double>::max();\n\t\tdouble cur_max = 0.0;\n\t\tint new_index = -1;\n\n\t\tfor (Eigen::DenseIndex i = 0; i < n; ++i) {\n\t\t\tif (chosen.count(i) <= 0) {\n\t\t\t\tcur_max = std::numeric_limits<double>::min();\n\t\t\t\tfor (auto c : chosen) {\n\t\t\t\t\tif (cur_max < Q(c, i)) {\n\t\t\t\t\t\tcur_max = Q(c, i);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (min_max - cur_max > 1e-6) {\n\t\t\t\t\tmin_max = cur_max;\n\t\t\t\t\tnew_index = i;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tchosen.insert(new_index);\n\t}\n\n\tEigen::VectorXi guess(chosen.size());\n\tEigen::DenseIndex j = 0;\n\tfor (auto c : chosen) {\n\t\tguess(j++) = c;\n\t}\n\n\treturn guess;\n}", "meta": {"hexsha": "5c486e9c98d0f754b3fcd93e055796a29fc6e7b2", "size": 9929, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/geometry/segmentation/spectral_clustering.cpp", "max_stars_repo_name": "josefgraus/self_similiarity", "max_stars_repo_head_hexsha": "c032daa3009f60fdc8a52c437a07c6e3ba2efe4b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-25T09:35:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-25T09:35:14.000Z", "max_issues_repo_path": "src/geometry/segmentation/spectral_clustering.cpp", "max_issues_repo_name": "josefgraus/self_similarity", "max_issues_repo_head_hexsha": "c032daa3009f60fdc8a52c437a07c6e3ba2efe4b", "max_issues_repo_licenses": ["MIT"], "max_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/segmentation/spectral_clustering.cpp", "max_forks_repo_name": "josefgraus/self_similarity", "max_forks_repo_head_hexsha": "c032daa3009f60fdc8a52c437a07c6e3ba2efe4b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-02-25T09:35:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-12T13:26:38.000Z", "avg_line_length": 29.1173020528, "max_line_length": 182, "alphanum_fraction": 0.6427636217, "num_tokens": 3129, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527869325346, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.47566823884368775}}
{"text": "// Naive Fibonacci calculation\n\n#include <active/shared.hpp>\n#include <active/promise.hpp>\n#include <iostream>\n\n#ifdef ACTIVE_USE_BOOST\n\t#include <boost/make_shared.hpp>\n#endif\n\ntypedef active::basic ao_type;\n\nstruct fib : public active::shared<fib, ao_type>, public active::handle<fib,int>\n{\n\tstruct calculate\n\t{\n\t\tint value;\n\t\tactive::sink<int>::sp result;\n\t};\n\n\tvoid active_method( calculate calculate )\n\t{\n\t\tif( calculate.value > 2 )\n\t\t{\n\t\t\tm_total=0;\n\t\t\tm_result = calculate.result;\n\t\t\tfib::calculate\n\t\t\t\tlhs = { calculate.value-1, shared_from_this() },\n\t\t\t\trhs = { calculate.value-2, shared_from_this() };\n\n\t\t\t// Note: temporary AO destroyed only after its last message.\n\t\t\t(*active::platform::make_shared<fib>())(lhs);\n\t\t\t(*active::platform::make_shared<fib>())(rhs);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcalculate.result->send(1);\n\t\t}\n\t}\n\n\tvoid active_method( int sub_result )\n\t{\n\t\tif( m_total ) m_result->send(m_total+sub_result);\n\t\telse m_total = sub_result;\n\t}\n\nprivate:\n\tint m_total;\n\tsp m_result;\n};\n\nint main(int argc, char**argv)\n{\n\tif( argc<2 ) { std::cout << \"Usage: fib N\\n\"; return 1; }\n\tactive::platform::shared_ptr<active::promise<int> > result = active::platform::make_shared<active::promise<int> >();\n\tfib::calculate calc = { atoi(argv[1]), result };\n\t(*active::platform::make_shared<fib>())(calc);\n\tactive::run();\n\tstd::cout << \"Result = \" << result->get() << std::endl;\n}\n", "meta": {"hexsha": "604bbee821067fb978b69fb1007290659e654294", "size": 1378, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "samples/fib.cpp", "max_stars_repo_name": "alarouche/cppao", "max_stars_repo_head_hexsha": "5519c8014286c60200bc7123b445b57848168584", "max_stars_repo_licenses": ["MIT", "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": "samples/fib.cpp", "max_issues_repo_name": "alarouche/cppao", "max_issues_repo_head_hexsha": "5519c8014286c60200bc7123b445b57848168584", "max_issues_repo_licenses": ["MIT", "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": "samples/fib.cpp", "max_forks_repo_name": "alarouche/cppao", "max_forks_repo_head_hexsha": "5519c8014286c60200bc7123b445b57848168584", "max_forks_repo_licenses": ["MIT", "Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.5901639344, "max_line_length": 117, "alphanum_fraction": 0.6676342525, "num_tokens": 386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708562, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.4756540621077362}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2013   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2013   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#include <nt2/exponential/include/functions/log.hpp>\n#include <boost/simd/sdk/simd/native.hpp>\n#include <boost/simd/sdk/simd/io.hpp>\n#include <vector>\n\n#include <nt2/sdk/unit/module.hpp>\n#include <nt2/sdk/unit/tests/cover.hpp>\n#include <nt2/sdk/unit/args.hpp>\n\nNT2_TEST_CASE_TPL(log,  NT2_SIMD_REAL_TYPES)\n{\n  using boost::simd::native;\n  typedef BOOST_SIMD_DEFAULT_EXTENSION  ext_t;\n  typedef native<T,ext_t>                  vT;\n\n  using nt2::unit::args;\n  const std::size_t NR = args(\"samples\", NT2_NB_RANDOM_TEST);\n  const double ulpd = args(\"ulpd\", 0.5);\n  const T min = args(\"min\", T(0));\n  const T max = args(\"max\", T(100));\n\n  NT2_CREATE_BUF(in0, T, NR, min, max);\n\n  std::vector<T> ref(NR);\n  for(std::size_t i=0; i!=NR; ++i)\n    ref[i] = std::log(in0[i]);\n\n  NT2_COVER_ULP_EQUAL(nt2::tag::log_, ((vT,in0)), ref, ulpd);\n}\n", "meta": {"hexsha": "1a3eece88e273536a0a59457a1e529611c40ca86", "size": 1339, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/core/exponential/cover/simd/log.cpp", "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/exponential/cover/simd/log.cpp", "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/exponential/cover/simd/log.cpp", "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.2368421053, "max_line_length": 80, "alphanum_fraction": 0.568334578, "num_tokens": 367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.47565406210773614}}
{"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#include <stapl/array.hpp>\n#include <stapl/algorithm.hpp>\n#include <stapl/utility/do_once.hpp>\n#include <boost/lexical_cast.hpp>\n\ntypedef unsigned long long ulong_type;\n\n////////////////////////////////////////////////////////////////////////////////\n/// @brief Returns true if a given number is NOT divisible by\n///        3 or 5 and returns false otherwise.\n////////////////////////////////////////////////////////////////////////////////\nstruct three_five_divisor\n{\n  template<typename T>\n  bool operator()(T i)\n  {\n    return !((i % 3) == 0 || (i % 5) == 0);\n  }\n};\n\n\nstapl::exit_code stapl_main(int argc, char** argv)\n{\n  ulong_type num = boost::lexical_cast<ulong_type> (argv[1]);\n\n  // Creates array container of unsigned integers that will be used for storage.\n  stapl::array<ulong_type> b(num);\n\n  // Creates view over container.\n  stapl::array_view<stapl::array<ulong_type>> vw(b);\n\n  // Fills the container with values from 1 to n.\n  stapl::iota(vw, 1);\n\n  // For numbers in the container that return true to the three_five_divisor\n  //   functor, they are set to 0.\n  stapl::replace_if(vw, three_five_divisor(), 0);\n\n  // Adds the total of all elements in container.\n  ulong_type total = stapl::accumulate(vw, (ulong_type)0);\n\n  // Prints the total sum.\n  stapl::do_once ([&] {\n    std::cout << \"The total is: \" << total << std::endl;\n  });\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "ba1d3876074d4194204d1df9dc30456a1b1af2c7", "size": 1747, "ext": "cc", "lang": "C++", "max_stars_repo_path": "stapl_release/examples/project_euler/pe_1a.cc", "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/examples/project_euler/pe_1a.cc", "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/examples/project_euler/pe_1a.cc", "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": 29.1166666667, "max_line_length": 80, "alphanum_fraction": 0.6319404694, "num_tokens": 424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228625116081, "lm_q2_score": 0.7185943925708562, "lm_q1q2_score": 0.4756540573152914}}
{"text": "//==================================================================================================\n/*\n  Copyright 2017 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//! [twopower]\n#include <boost/simd/bitwise.hpp>\n#include <boost/simd/pack.hpp>\n#include <iostream>\n\nnamespace bs = boost::simd;\nusing pack_it = bs::pack<std::int32_t, 4>;\n\nint main() {\n  pack_it pi = {1, 2, -1, 5};\n\n  std::cout << \"---- simd\" << '\\n'\n            << \"<- pi =               \" << pi << '\\n'\n            << \"-> bs::twopower(pi) = \" << bs::twopower(pi) << '\\n';\n\n  std::int32_t xi = 4;\n\n  std::cout << \"---- scalar\" << '\\n'\n            << \"<- xi =               \" << xi << '\\n'\n            << \"-> bs::twopower(xi) = \" << bs::twopower(xi) << '\\n';\n  return 0;\n}\n//! [twopower]\n", "meta": {"hexsha": "68f32c1e85d01e24e37733d759b0e61d6df60ae0", "size": 970, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/doc/bitwise/twopower.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": "test/doc/bitwise/twopower.cpp", "max_issues_repo_name": "remymuller/boost.simd", "max_issues_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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/doc/bitwise/twopower.cpp", "max_forks_repo_name": "remymuller/boost.simd", "max_forks_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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.3125, "max_line_length": 100, "alphanum_fraction": 0.4010309278, "num_tokens": 249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943805178139, "lm_q2_score": 0.6619228625116081, "lm_q1q2_score": 0.47565404933710714}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2015 NumScale SAS\n  @copyright 2015 J.T.Lapreste\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_COMMON_DETAIL_SCALAR_F_INVTRIG_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_DETAIL_SCALAR_F_INVTRIG_HPP_INCLUDED\n\n#include <boost/simd/function/horn.hpp>\n#include <boost/simd/constant/constant.hpp>\n#include <boost/simd/constant/half.hpp>\n#include <boost/simd/constant/mhalf.hpp>\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/constant/pio_2.hpp>\n#include <boost/simd/constant/pio_2lo.hpp>\n#include <boost/simd/constant/pio_3.hpp>\n#include <boost/simd/constant/pio_4.hpp>\n#include <boost/simd/constant/pio_4lo.hpp>\n#include <boost/simd/constant/tan_3pio_8.hpp>\n#include <boost/simd/constant/tanpio_8.hpp>\n#include <boost/simd/constant/two.hpp>\n#include <boost/simd/constant/twopio_3.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/function/scalar/abs.hpp>\n#include <boost/simd/function/scalar/bitofsign.hpp>\n#include <boost/simd/function/scalar/bitwise_xor.hpp>\n#include <boost/simd/function/scalar/fma.hpp>\n#include <boost/simd/function/scalar/is_eqz.hpp>\n#include <boost/simd/function/scalar/is_inf.hpp>\n#include <boost/simd/function/scalar/minusone.hpp>\n#include <boost/simd/function/scalar/oneminus.hpp>\n#include <boost/simd/function/scalar/oneplus.hpp>\n#include <boost/simd/function/scalar/rec.hpp>\n#include <boost/simd/function/scalar/sqr.hpp>\n#include <boost/simd/function/scalar/sqrt.hpp>\n#include <boost/dispatch/meta/scalar_of.hpp>\n\nnamespace boost { namespace simd\n{\n  namespace detail\n  {\n    namespace bd =  boost::dispatch;\n    namespace bs =  boost::simd;\n\n   template < class A0,\n             class unit_tag,\n             class style,\n             class base_A0 = bd::scalar_of_t<A0>\n  >\n  struct invtrig_base{};\n\n  template < class A0 >\n  struct invtrig_base<A0,tag::radian_tag,tag::not_simd_type, float>\n  {\n    static BOOST_FORCEINLINE A0 asin(A0 a0) BOOST_NOEXCEPT\n    {\n      A0 sign, x, z;\n      x = bs::abs(a0);\n      sign = bitofsign(a0);\n      if ((x < Constant<A0,0x38d1b717>())) return a0; //1.0e-4\n      if ((x >  One<A0>())) return Nan<A0>();\n      auto bx_larger_05    = (x > Half<A0>());\n      if (bx_larger_05)\n      {\n        z = Half<A0>()*oneminus(x);\n        x =  sqrt(z);\n      }\n      else\n      {\n        z = sqr(x);\n      }\n      A0 z1 = horn<A0,\n        0x3e2aaae4,\n        0x3d9980f6,\n        0x3d3a3ec7,\n        0x3cc617e3,\n        0x3d2cb352\n        > (z);\n      z1 = fma(z1, z*x, x);\n      if(bx_larger_05)\n      {\n        z1 = z1+z1;\n        z1 = Pio_2<A0>()-z1;\n      }\n      return bitwise_xor(z1, sign);\n    }\n\n    static BOOST_FORCEINLINE A0 acos(const  A0& a0) BOOST_NOEXCEPT\n    {\n      if (a0 < Mhalf<A0>())\n        return Pi<A0>()-asin( sqrt(oneplus(a0)*Half<A0>()))*Two<A0>();\n      else if (a0 > Half<A0>())\n        return asin( sqrt(oneminus(a0)*Half<A0>()))*Two<A0>();\n      return (Pio_2<A0>()-asin(a0));\n    }\n\n    static BOOST_FORCEINLINE A0 atan(A0 a0) BOOST_NOEXCEPT\n    {\n      A0 x  = kernel_atan(a0);\n      return bitwise_xor(x, bitofsign(a0));\n    }\n\n    static BOOST_FORCEINLINE A0 kernel_atan(A0 a0) BOOST_NOEXCEPT\n    {\n      if (is_eqz(a0))  return Zero<A0>();\n      if (is_inf(a0))  return Pio_2<A0>();\n      A0 x = bs::abs(a0);\n      A0 y = 0.0;\n      A0 more = Zero<A0>();\n      if( x > Tan_3pio_8<A0>())\n      {\n        y = Pio_2<A0>();\n        more = Pio_2lo<A0>();\n        x = -rec(x);\n      }\n      else if( x > Tanpio_8<A0>())\n      {\n        y = Pio_4<A0>();\n        more =  Pio_4lo<A0>();\n        x = minusone(x)/oneplus(x);\n      }\n      A0 z = sqr(x);\n      A0 z1 = horn<A0\n        , 0xbeaaaa2aul  // -3.3333293e-01\n        , 0x3e4c925ful  //  1.9991724e-01\n        , 0xbe0e1b85ul  // -1.4031009e-01\n        , 0x3da4f0d1ul  //  8.5460119e-02\n        > (z);\n    z1 = fma(x, z1*z, x);\n\n      return y+(z1+more);\n    }\n  };\n}\n} }\n#endif\n", "meta": {"hexsha": "46b6ed25b579358e82f430941d315cea47554914", "size": 4270, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arch/common/detail/scalar/f_invtrig.hpp", "max_stars_repo_name": "yaeldarmon/boost.simd", "max_stars_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/simd/arch/common/detail/scalar/f_invtrig.hpp", "max_issues_repo_name": "yaeldarmon/boost.simd", "max_issues_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/arch/common/detail/scalar/f_invtrig.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": 29.4482758621, "max_line_length": 100, "alphanum_fraction": 0.5922716628, "num_tokens": 1344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278633625321, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.4756138118196892}}
{"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\u2019s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n#pragma once\n\n#include \"algorithms/public/STFT.hpp\"\n#include \"algorithms/util/AlgorithmUtils.hpp\"\n#include \"algorithms/util/FluidEigenMappings.hpp\"\n#include \"algorithms/GraphPlayUtils.hpp\"\n#include \"data/TensorTypes.hpp\"\n#include \"data/FluidDataSet.hpp\"\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <vector>\n#include <fstream>\n#include <random>\n\nnamespace fluid {\nnamespace algorithm {\n\nclass GraphPlay {\n\npublic:\n  using  MatrixXd = Eigen::MatrixXd;\n  using  VectorXd = Eigen::VectorXd;\n  using  DataSet = FluidDataSet<std::string, double, 1>;\n\n  void init(RealVectorView audio, index sampleRate,\n            index windowSize, index fftSize, index hopSize, index numBands,\n            index distance, double threshold, RealVectorView output) {\n    using namespace Eigen;\n    using namespace _impl;\n    using namespace std;\n    mWindowSize = windowSize;\n    mFFTSize = fftSize;\n    mHopSize = hopSize;\n    mFrameSize = (mFFTSize / 2) + 1;\n    mThreshold = threshold;\n    STFT stft = STFT(mWindowSize, mFFTSize, mHopSize);\n    mLength = std::floor((audio.size() + mHopSize) / mHopSize);\n    mSpectrogram = ComplexMatrix(mLength, mFrameSize);\n    stft.process(audio, mSpectrogram);\n    RealMatrix magnitude(mLength, mFrameSize);\n    stft.magnitude(mSpectrogram, magnitude);\n    mDM = mUtils.computeDM(magnitude, numBands, sampleRate, windowSize, fftSize, distance);\n    mDM.diagonal().setZero();\n    mForbidden = ArrayXXd::Ones(mDM.rows(), mDM.cols());\n    mVisited = ArrayXXd::Zero(mDM.rows(), mDM.cols());\n    ArrayXd odf = mDM.diagonal(1).array();\n    mRP = (mDM.array() < threshold).cast<double>();\n    mRP = mRP.array() * mForbidden.array();\n    mInitialized = true;\n  }\n\n\n  void processFrame(ComplexVectorView out, double start, double threshold,\n    index minLength, index minDist, index forget, RealVectorView output) {\n    using namespace Eigen;\n    using namespace _impl;\n    using namespace std;\n    if(mThreshold != threshold){\n      mRP =  (mDM.array() < threshold).cast<double>();\n      mRP = mRP.array() * mForbidden.array();\n      mThreshold = threshold;\n    }\n    mVisited = (mVisited.array() - 1).cwiseMax(0);\n    index startFrame = lrint(start * (mSpectrogram.rows() - 1));\n    if(startFrame != mStartFrame ){\n      mStartFrame = startFrame;\n      mPos = mStartFrame;\n      index nNeighbors = mRP.col(mPos).sum();\n      while(nNeighbors == 0){\n        nNeighbors = mRP.col(mPos).sum();\n        mPos = (mPos + 1) % mSpectrogram.rows();\n      }\n      mCount = 0;\n    }\n    else if (mCount < minLength){\n      mPos = (mPos + 1) % mSpectrogram.rows();\n      mCount++;\n    }\n    else{\n        index nNeighbors = mRP.col(mPos).sum();\n        index nForbidden = mForbidden.col(mPos).sum();\n        index prevPos = mPos;\n        if(nNeighbors > 0){\n          std::vector<index> candidates(nNeighbors);\n          index nCandidates = 0;\n          for(index i = 0; i < mRP.rows(); i++)\n            if(abs(i - mPos) > minDist && mRP(mPos, i) > 0 && mVisited(mPos, i) <= 0){\n              candidates[nCandidates++] = i;\n            }\n            index next = mUtils.randInt(nCandidates);\n            mPos = candidates[next];\n            mCount = 0;\n        }\n        if (mPos == prevPos){\n          mPos = (mPos + 1) % mSpectrogram.rows();\n        }\n        mVisited(prevPos, mPos) = forget;\n    }\n    out = mSpectrogram.row(mPos);\n    output(0)  = mPos;\n  }\n\n  bool initialized(){\n    return mInitialized;\n  }\n\n  index num{0};\n\n  index mWindowSize;\n  index mHopSize;\n  index mFFTSize;\n\nprivate:\n  GraphPlayUtils mUtils;\n  index mFrameSize;\n  ComplexMatrix mSpectrogram;\n  MatrixXd mDM;\n  MatrixXd mRP;\n  MatrixXd mForbidden;\n  MatrixXd mVisited;\n  VectorXd mDeg;\n  bool mInitialized{false};\n  int mPos{0};\n  index mLength;\n  index mStartFrame{-1};\n  index mEndFrame;\n  double mThreshold;\n  index mCount{0};\n};\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "bd86d7e934cf28697513822a10cfd1eeb64f80c1", "size": 4279, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/GraphPlay.hpp", "max_stars_repo_name": "flucoma/graph_loop_grain", "max_stars_repo_head_hexsha": "db9bbc603412d44a49b0d882bc3fdb604aeb63d1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2021-06-05T10:43:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-24T10:40:25.000Z", "max_issues_repo_path": "include/algorithms/GraphPlay.hpp", "max_issues_repo_name": "flucoma/graph_loop_grain", "max_issues_repo_head_hexsha": "db9bbc603412d44a49b0d882bc3fdb604aeb63d1", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/algorithms/GraphPlay.hpp", "max_forks_repo_name": "flucoma/graph_loop_grain", "max_forks_repo_head_hexsha": "db9bbc603412d44a49b0d882bc3fdb604aeb63d1", "max_forks_repo_licenses": ["BSD-3-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.1338028169, "max_line_length": 91, "alphanum_fraction": 0.6541247955, "num_tokens": 1147, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278540866547, "lm_q2_score": 0.538983220687684, "lm_q1q2_score": 0.4756138068201468}}
{"text": "/*\n * Copyright (c) 2008 Radu Bogdan Rusu <rusu -=- cs.tum.edu>\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n *     * Redistributions of source code must retain the above copyright\n *       notice, this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above copyright\n *       notice, this list of conditions and the following disclaimer in the\n *       documentation and/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * $Id: transforms.cpp 23275 2009-08-28 20:27:09Z mariusmuja $\n *\n */\n\n/** \\author Radu Bogdan Rusu */\n\n#include <point_cloud_mapping/geometry/angles.h>\n#include <point_cloud_mapping/geometry/transforms.h>\n#include <point_cloud_mapping/geometry/nearest.h>\n\n#include <Eigen/SVD>\n\n\nnamespace cloud_geometry\n{\n  namespace transforms\n  {\n\n  /**\n   * See header file\n   */\n  bool getPointsRigidTransformation(const sensor_msgs::PointCloud& pc_a_, const sensor_msgs::PointCloud& pc_b_,\n\t\t  Eigen::Matrix4d &transformation)\n  {\n\n\t  assert (pc_a_.get_points_size()==pc_b_.get_points_size());\n\n\t  sensor_msgs::PointCloud pc_a = pc_a_;\n\t  sensor_msgs::PointCloud pc_b = pc_b_;\n\n\t  // translate both point cloud so that their centroid will be in origin\n\t  geometry_msgs::Point32 centroid_a;\n\t  geometry_msgs::Point32 centroid_b;\n\n\t  nearest::computeCentroid(pc_a, centroid_a);\n\t  nearest::computeCentroid(pc_b, centroid_b);\n\n\t  for (size_t i=0;i<pc_a.get_points_size();++i) {\n\t\t  pc_a.points[i].x -= centroid_a.x;\n\t\t  pc_a.points[i].y -= centroid_a.y;\n\t\t  pc_a.points[i].z -= centroid_a.z;\n\t  }\n\n\t  for (size_t i=0;i<pc_b.get_points_size();++i) {\n\t\t  pc_b.points[i].x -= centroid_b.x;\n\t\t  pc_b.points[i].y -= centroid_b.y;\n\t\t  pc_b.points[i].z -= centroid_b.z;\n\t  }\n\n\t  // solve for rotation\n\t  Eigen::Matrix3d correlation;\n\t  correlation.setZero();\n\n\t  for (size_t i=0;i<pc_a.get_points_size();++i) {\n\t\t  correlation(0,0) += pc_a.points[i].x * pc_b.points[i].x;\n\t\t  correlation(0,1) += pc_a.points[i].x * pc_b.points[i].y;\n\t\t  correlation(0,2) += pc_a.points[i].x * pc_b.points[i].z;\n\n\t\t  correlation(1,0) += pc_a.points[i].y * pc_b.points[i].x;\n\t\t  correlation(1,1) += pc_a.points[i].y * pc_b.points[i].y;\n\t\t  correlation(1,2) += pc_a.points[i].y * pc_b.points[i].z;\n\n\t\t  correlation(2,0) += pc_a.points[i].z * pc_b.points[i].x;\n\t\t  correlation(2,1) += pc_a.points[i].z * pc_b.points[i].y;\n\t\t  correlation(2,2) += pc_a.points[i].z * pc_b.points[i].z;\n\t  }\n\n\t  Eigen::JacobiSVD<Eigen::Matrix3d> svd(correlation);\n\n\t  Eigen::Matrix3d Ut = svd.matrixU().transpose();\n\t  Eigen::Matrix3d V = svd.matrixV();\n\t  Eigen::Matrix3d X = V*Ut;\n\n\t  double det = X.determinant();\n\t  if (det<0) {\n\t\t  V.col(2) = -V.col(2);\n\t\t  X = V*Ut;\n\t  }\n\n\t  transformation.setZero();\n\t  transformation.topLeftCorner<3,3>() = X;\n\t  transformation(3,3) = 1;\n\n\t  sensor_msgs::PointCloud pc_rotated_a;\n\t  transformPoints(pc_a_.points, pc_rotated_a.points, transformation);\n\n\t  geometry_msgs::Point32 centroid_rotated_a;\n\t  nearest::computeCentroid(pc_rotated_a, centroid_rotated_a);\n\n\t  transformation(0,3) = centroid_b.x - centroid_rotated_a.x;\n\t  transformation(1,3) = centroid_b.y - centroid_rotated_a.y;\n\t  transformation(2,3) = centroid_b.z - centroid_rotated_a.z;\n\n\t  return true;\n\n  }\n\n\n  /**\n   * See header file\n   */\n\tbool getPointsRigidTransformation(const sensor_msgs::PointCloud& pc_a_, const std::vector<int>& indices_a,\n\t\t\t\t\t\t\t\t\t\t  const sensor_msgs::PointCloud& pc_b_, const std::vector<int>& indices_b,\n\t\t\t\t\t\t\t\t\t\t  Eigen::Matrix4d &transformation)\n\t{\n\n\t  assert (indices_a.size()==indices_b.size());\n\n\t  sensor_msgs::PointCloud pc_a;\n\t  sensor_msgs::PointCloud pc_b;\n\n\t  getPointCloud(pc_a_, indices_a, pc_a);\n\t  getPointCloud(pc_b_, indices_b, pc_b);\n\n\t  // translate both point cloud so that their centroid will be in origin\n\t  geometry_msgs::Point32 centroid_a;\n\t  geometry_msgs::Point32 centroid_b;\n\n\t  nearest::computeCentroid(pc_a, centroid_a);\n\t  nearest::computeCentroid(pc_b, centroid_b);\n\n\t  for (size_t i=0;i<pc_a.get_points_size();++i) {\n\t\t  pc_a.points[i].x -= centroid_a.x;\n\t\t  pc_a.points[i].y -= centroid_a.y;\n\t\t  pc_a.points[i].z -= centroid_a.z;\n\t  }\n\n\t  for (size_t i=0;i<pc_b.get_points_size();++i) {\n\t\t  pc_b.points[i].x -= centroid_b.x;\n\t\t  pc_b.points[i].y -= centroid_b.y;\n\t\t  pc_b.points[i].z -= centroid_b.z;\n\t  }\n\n\t  // solve for rotation\n\t  Eigen::Matrix3d correlation;\n\t  correlation.setZero();\n\n\t  for (size_t i=0;i<pc_a.get_points_size();++i) {\n\t\t  correlation(0,0) += pc_a.points[i].x * pc_b.points[i].x;\n\t\t  correlation(0,1) += pc_a.points[i].x * pc_b.points[i].y;\n\t\t  correlation(0,2) += pc_a.points[i].x * pc_b.points[i].z;\n\n\t\t  correlation(1,0) += pc_a.points[i].y * pc_b.points[i].x;\n\t\t  correlation(1,1) += pc_a.points[i].y * pc_b.points[i].y;\n\t\t  correlation(1,2) += pc_a.points[i].y * pc_b.points[i].z;\n\n\t\t  correlation(2,0) += pc_a.points[i].z * pc_b.points[i].x;\n\t\t  correlation(2,1) += pc_a.points[i].z * pc_b.points[i].y;\n\t\t  correlation(2,2) += pc_a.points[i].z * pc_b.points[i].z;\n\t  }\n\n\t  Eigen::JacobiSVD<Eigen::Matrix3d> svd(correlation);\n\n\t  Eigen::Matrix3d Ut = svd.matrixU().transpose();\n\t  Eigen::Matrix3d V = svd.matrixV();\n\t  Eigen::Matrix3d X = V*Ut;\n\n\t  double det = X.determinant();\n\t  if (det<0) {\n\t\t  V.col(2) = -V.col(2);\n\t\t  X = V*Ut;\n\t  }\n\n\t  transformation.setZero();\n\t  transformation.topLeftCorner<3,3>() = X;\n\t  transformation(3,3) = 1;\n\n\t  sensor_msgs::PointCloud pc_rotated_a;\n\t  getPointCloud(pc_a_, indices_a, pc_a);\n\t  transformPoints(pc_a.points, pc_rotated_a.points, transformation);\n\n\t  geometry_msgs::Point32 centroid_rotated_a;\n\t  nearest::computeCentroid(pc_rotated_a, centroid_rotated_a);\n\n\t  transformation(0,3) = centroid_b.x - centroid_rotated_a.x;\n\t  transformation(1,3) = centroid_b.y - centroid_rotated_a.y;\n\t  transformation(2,3) = centroid_b.z - centroid_rotated_a.z;\n\n\n//\t  transformation.setIdentity();\n//\t  transformation(0,3) = centroid_b.x - centroid_a.x;\n//\t  transformation(1,3) = centroid_b.y - centroid_a.y;\n//\t  transformation(2,3) = centroid_b.z - centroid_a.z;\n\n\t  return true;\n\n  }\n\n    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n    /** \\brief Obtain a 4x4 rigid transformation matrix (with translation)\n      * \\param plane_a the normalized coefficients of the first plane\n      * \\param plane_b the normalized coefficients of the second plane\n      * \\param tx the desired translation on x-axis\n      * \\param ty the desired translation on y-axis\n      * \\param tz the desired translation on z-axis\n      * \\param transformation the resultant transformation matrix\n      */\n    void\n      getPlaneToPlaneTransformation (const std::vector<double> &plane_a, const std::vector<double> &plane_b,\n                                     float tx, float ty, float tz, Eigen::Matrix4d &transformation)\n    {\n      double angle = cloud_geometry::angles::getAngleBetweenPlanes (plane_a, plane_b);\n      // Compute the rotation axis R = Nplane x (0, 0, 1)\n      geometry_msgs::Point32 r_axis;\n      r_axis.x = plane_a[1]*plane_b[2] - plane_a[2]*plane_b[1];\n      r_axis.y = plane_a[2]*plane_b[0] - plane_a[0]*plane_b[2];\n      r_axis.z = plane_a[0]*plane_b[1] - plane_a[1]*plane_b[0];\n\n      if (r_axis.z < 0)\n        angle = -angle;\n\n      // Build a normalized quaternion\n      double s = sin (0.5 * angle) / sqrt (r_axis.x * r_axis.x + r_axis.y * r_axis.y + r_axis.z * r_axis.z);\n      double x = r_axis.x * s;\n      double y = r_axis.y * s;\n      double z = r_axis.z * s;\n      double w = cos (0.5 * angle);\n\n      // Convert the quaternion to a 3x3 matrix\n      double ww = w * w; double xx = x * x; double yy = y * y; double zz = z * z;\n      double wx = w * x; double wy = w * y; double wz = w * z;\n      double xy = x * y; double xz = x * z; double yz = y * z;\n\n      transformation (0, 0) = xx - yy - zz + ww; transformation (0, 1) = 2*(xy - wz);       transformation (0, 2) = 2*(xz + wy);       transformation (0, 3) = tx;\n      transformation (1, 0) = 2*(xy + wz);       transformation (1, 1) = -xx + yy -zz + ww; transformation (1, 2) = 2*(yz - wx);       transformation (1, 3) = ty;\n      transformation (2, 0) = 2*(xz - wy);       transformation (2, 1) = 2*(yz + wx);       transformation (2, 2) = -xx -yy + zz + ww; transformation (2, 3) = tz;\n      transformation (3, 0) = 0;                 transformation (3, 1) = 0;                 transformation (3, 2) = 0;                 transformation (3, 3) = 1;\n    }\n\n    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n    /** \\brief Obtain a 4x4 rigid transformation matrix (with translation)\n      * \\param plane_a the normalized coefficients of the first plane\n      * \\param plane_b the normalized coefficients of the second plane\n      * \\param tx the desired translation on x-axis\n      * \\param ty the desired translation on y-axis\n      * \\param tz the desired translation on z-axis\n      * \\param transformation the resultant transformation matrix\n      */\n    void\n      getPlaneToPlaneTransformation (const std::vector<double> &plane_a, const geometry_msgs::Point32 &plane_b,\n                                     float tx, float ty, float tz, Eigen::Matrix4d &transformation)\n    {\n      double angle = cloud_geometry::angles::getAngleBetweenPlanes (plane_a, plane_b);\n      // Compute the rotation axis R = Nplane x (0, 0, 1)\n      geometry_msgs::Point32 r_axis;\n      r_axis.x = plane_a[1]*plane_b.z - plane_a[2]*plane_b.y;\n      r_axis.y = plane_a[2]*plane_b.x - plane_a[0]*plane_b.z;\n      r_axis.z = plane_a[0]*plane_b.y - plane_a[1]*plane_b.x;\n\n      if (r_axis.z < 0)\n        angle = -angle;\n\n      // Build a normalized quaternion\n      double s = sin (0.5 * angle) / sqrt (r_axis.x * r_axis.x + r_axis.y * r_axis.y + r_axis.z * r_axis.z);\n      double x = r_axis.x * s;\n      double y = r_axis.y * s;\n      double z = r_axis.z * s;\n      double w = cos (0.5 * angle);\n\n      // Convert the quaternion to a 3x3 matrix\n      double ww = w * w; double xx = x * x; double yy = y * y; double zz = z * z;\n      double wx = w * x; double wy = w * y; double wz = w * z;\n      double xy = x * y; double xz = x * z; double yz = y * z;\n\n      transformation (0, 0) = xx - yy - zz + ww; transformation (0, 1) = 2*(xy - wz);       transformation (0, 2) = 2*(xz + wy);       transformation (0, 3) = tx;\n      transformation (1, 0) = 2*(xy + wz);       transformation (1, 1) = -xx + yy -zz + ww; transformation (1, 2) = 2*(yz - wx);       transformation (1, 3) = ty;\n      transformation (2, 0) = 2*(xz - wy);       transformation (2, 1) = 2*(yz + wx);       transformation (2, 2) = -xx -yy + zz + ww; transformation (2, 3) = tz;\n      transformation (3, 0) = 0;                 transformation (3, 1) = 0;                 transformation (3, 2) = 0;                 transformation (3, 3) = 1;\n    }\n\n    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n    /** \\brief Convert an axis-angle representation to a 3x3 rotation matrix\n      * \\note The formula is given by: A = I * cos (th) + ( 1 - cos (th) ) * axis * axis' - E * sin (th), where\n      * E = [0 -axis.z axis.y; axis.z 0 -axis.x; -axis.y axis.x 0]\n      * \\param axis the axis\n      * \\param angle the angle\n      * \\param rotation the resultant rotation\n      */\n    void\n      convertAxisAngleToRotationMatrix (const geometry_msgs::Point32 &axis, double angle, Eigen::Matrix3d &rotation)\n    {\n      double cos_a = cos (angle);\n      double sin_a = sin (angle);\n      double cos_a_m = 1.0 - cos_a;\n\n      double a_xy = axis.x * axis.y * cos_a_m;\n      double a_xz = axis.x * axis.z * cos_a_m;\n      double a_yz = axis.y * axis.z * cos_a_m;\n\n      double s_x = sin_a * axis.x;\n      double s_y = sin_a * axis.y;\n      double s_z = sin_a * axis.z;\n\n      rotation (0, 0) = cos_a + axis.x * axis.x * cos_a_m;\n      rotation (0, 1) = a_xy - s_z;\n      rotation (0, 2) = a_xz + s_y;\n      rotation (1, 0) = a_xy + s_z;\n      rotation (1, 1) = cos_a + axis.y * axis.y * cos_a_m;\n      rotation (1, 2) = a_yz - s_x;\n      rotation (2, 0) = a_xz - s_y;\n      rotation (2, 1) = a_yz + s_x;\n      rotation (2, 2) = cos_a + axis.z * axis.z * cos_a_m;\n    }\n\n  }\n}\n", "meta": {"hexsha": "8de1da8392aa067370b5def08c1e257f51b56be8", "size": 13165, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "11_learning_materials/stanford_self_driving_car/perception/point_cloud_mapping/src/cloud_geometry/transforms.cpp", "max_stars_repo_name": "EatAllBugs/autonomous_learning", "max_stars_repo_head_hexsha": "02ff7b0fa7b131a2f2203505ef5cc7e43b40bc47", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2021-09-01T14:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T08:49:57.000Z", "max_issues_repo_path": "11_learning_materials/stanford_self_driving_car/perception/point_cloud_mapping/src/cloud_geometry/transforms.cpp", "max_issues_repo_name": "yinflight/autonomous_learning", "max_issues_repo_head_hexsha": "02ff7b0fa7b131a2f2203505ef5cc7e43b40bc47", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "11_learning_materials/stanford_self_driving_car/perception/point_cloud_mapping/src/cloud_geometry/transforms.cpp", "max_forks_repo_name": "yinflight/autonomous_learning", "max_forks_repo_head_hexsha": "02ff7b0fa7b131a2f2203505ef5cc7e43b40bc47", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-10-10T00:58:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-23T13:16:09.000Z", "avg_line_length": 39.5345345345, "max_line_length": 162, "alphanum_fraction": 0.6175465249, "num_tokens": 3764, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375735, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.475609605880849}}
{"text": "//\n// Created by \u0421\u0435\u0440\u0433\u0435\u0439 \u041a\u0440\u0438\u0432\u043e\u043d\u043e\u0441 on 01.09.17.\n//\n#include \"Fraction.h\"\n#include \"Integer.h\"\n#include \"Sum.h\"\n#include \"Product.h\"\n\n#include <boost/lexical_cast.hpp>\n\n// \n// namespace std{\n//     template<>\n//     struct is_signed<boost::multiprecision::cpp_int> {\n//         bool value = true;\n//     };\n// }\n//\n\nnamespace omnn{\nnamespace math {\n\tFraction::Fraction(const Integer& n)\n\t\t: base(n, 1)\n\t{\n\t}\n\n\tFraction::Fraction(boost::rational<a_int>&& r)\n\t: base(r.numerator(), r.denominator())\n\t{\n\t}\n\n    Fraction::Fraction(const boost::multiprecision::cpp_dec_float_100& f)\n    {\n        auto s = boost::lexical_cast<std::string>(f);\n        if (s==\"nan\") {\n            throw s;\n        }\n        auto doti = s.find_first_of('.');\n        if (doti == -1)\n        {\n            numerator() = Integer(boost::multiprecision::cpp_int(f));\n            denominator() = 1;\n        }\n        else\n        {\n            auto afterDotI = doti + 1;\n            auto fsz = s.length() - afterDotI;\n            denominator() = 10_v ^ fsz;\n            numerator() = Integer(boost::multiprecision::cpp_int(s.c_str()+afterDotI));\n            if (s[0]=='-') {\n                numerator() = -numerator();\n            }\n            s.erase(doti);\n            numerator() += Integer(boost::multiprecision::cpp_int(s)) * denominator();\n        }\n    }\n    \n\tValuable Fraction::operator -() const\n    {\n        return Fraction(-getNumerator(), getDenominator());\n    }\n\n    bool Fraction::operator ==(const Valuable& v) const\n    {\n        auto eq = v.IsFraction() && Hash()==v.Hash();\n        if(eq){\n            auto& ch = v.as<Fraction>();\n            eq= _1.Hash() == ch._1.Hash()\n                && _2.Hash() == ch._2.Hash()\n                && _1 == ch._1\n                && _2 == ch._2;\n        } else if (v.IsExponentiation()) {\n            eq = v.operator==(*this);\n        }\n        return eq;\n    }\n\n    void Fraction::solve(const Variable& va, solutions_t& s) const {\n        numerator().solve(va, s);\n        solutions_t exclude;\n        denominator().solve(va, exclude);\n        for(auto& so:exclude)\n            s.erase(so);\n    }\n    \n    Valuable::solutions_t Fraction::Distinct() const {\n        Valuable::solutions_t branches;\n        for (auto&& n : numerator().Distinct()) {\n            for (auto&& d : denominator().Distinct()) {\n                branches.emplace(n / d);\n            }\n        }\n        return branches;\n    }\n\n    void Fraction::optimize()\n    {\n//        if (!optimizations) {\n//            hash = numerator().Hash() ^ denominator().Hash();\n//            return;\n//        }\n    reoptimize_the_fraction:\n        numerator().optimize();\n        denominator().optimize();\n        \n        while(denominator().IsFraction())\n        {\n            auto& fdn = denominator().as<Fraction>();\n            numerator() *= fdn.denominator();\n            denominator() = std::move(fdn.numerator());\n        }\n\n//        if (numerator().IsSum()) {\n//            Become(numerator()/denominator());\n//            return;\n//        }\n        \n        if (denominator().IsInt())\n        {\n            if (denominator().ca() == 1)\n            {\n                Become(std::move(numerator()));\n                return;\n            }\n            else if (denominator() < 0) {\n                numerator() = -numerator();\n                denominator() = -denominator();\n            }\n        }\n        \n        if (numerator().IsExponentiation()) {\n            auto& e = numerator().as<Exponentiation>();\n            auto& exp = e.getExponentiation();\n            if (exp.IsInt() && exp < 0) {\n                denominator() *= e.getBase() ^ (-exp);\n                numerator() = 1;\n            } else if (exp.IsFraction()) {\n                auto& f = exp.as<Fraction>();\n                auto in = e.getBase() / (denominator() ^ f.Reciprocal());\n                if (in.IsInt())\n                {\n                    e.setBase(std::move(in));\n                    Become(std::move(e));\n                    return;\n                }\n            }\n        }\n\n        // integers\n        if (numerator().IsInt())\n        {\n            auto& n = numerator().ca();\n            auto& denom = denominator();\n            auto dni = denom.IsInt();\n            if (n == 0)\n            {\n                if (dni && denom == 0_v)\n                    throw \"NaN\";\n                Become(std::move(numerator()));\n                return;\n            }\n            if (dni)\n            {\n                auto& dn = denominator().ca();\n                if (n < 0 && dn < 0) {\n                    numerator() = -numerator();\n                    denominator() = -denominator();\n                    goto reoptimize_the_fraction;\n                }\n                if (dn == 1)\n                {\n                    Become(std::move(numerator()));\n                    return;\n                }\n                if (dn == -1)\n                {\n                    Become(-numerator());\n                    return;\n                }\n                auto d = boost::gcd(n, dn);\n                if (d != 1) {\n                    numerator() /= Integer(d);\n                    denominator() /= Integer(d);\n                    optimize();\n                    return;\n                }\n            }\n        }\n        else\n        {\n            std::vector<Variable> coVa;\n\n            if (numerator().IsProduct()) {\n                //if (denominator().IsProduct()) {\n                    Become(numerator() / denominator());\n                    return;\n                //}\n                //else\n                //{\n                //    auto n = Product::cast(numerator());\n                    //if (n->Has(denominator()))\n\t\t\t\t\t//{\n     //                   Become(*n / denominator());\n     //                   return;\n     //               }\n     //           }\n            }\n            else if (denominator().IsProduct())\n            {\n                auto& dn = denominator().as<Product>();\n                if (dn.Has(numerator())) {\n                    denominator() /= numerator();\n                    numerator() = 1_v;\n                    goto reoptimize_the_fraction;\n                }\n                else if (numerator().IsInt() || numerator().IsSimpleFraction()) {\n                    for (auto& m : dn)\n                    {\n                        if (m.IsVa()) {\n                            numerator() *= m ^ -1;\n                        }\n                        else if (m.IsExponentiation()) {\n                            auto& e = m.as<Exponentiation>();\n                            numerator() *= e.getBase() ^ -e.getExponentiation();\n                        }\n                        else\n                            numerator() /= m;\n                    }\n                    Become(std::move(numerator()));\n                    return;\n                }\n            }\n            else if (denominator().FindVa() && !denominator().IsSum())\n            {\n                Become(Product{ std::move(numerator()), Exponentiation( std::move(denominator()), -1)});\n                return;\n            }\n            else // no products\n            {\n                // sum\n//                auto s = Sum::cast(numerator());\n//                if (s) {\n//                    auto sum(std::move(*s));\n//                    sum /= denominator();\n//                    Become(std::move(sum));\n//                    return;\n//                }\n            }\n        }\n        \n        if (IsFraction()) {\n            if(IsSimple())\n                hash = numerator().Hash() ^ denominator().Hash();\n            else if (!denominator().IsSum())\n                Become(numerator()*(denominator()^-1));\n        }\n    }\n\n    bool Fraction::MultiplyIfSimplifiable(const Valuable& v)\n    {\n        auto is = IsSimpleFraction() && v.IsSimple();\n        if(is){\n            *this *= v;\n        } else if (!v.IsFraction()) {\n            auto s = v.IsMultiplicationSimplifiable(*this);\n            is = s.first;\n            if (is) {\n                Become(std::move(s.second));\n            }\n        } else {\n            IMPLEMENT\n        }\n        return is;\n    }\n\n    std::pair<bool,Valuable> Fraction::IsMultiplicationSimplifiable(const Valuable& v) const\n    {\n        std::pair<bool,Valuable> is;\n        is.first = IsSimpleFraction() && v.IsSimple();\n        if(is.first){\n            is.second = *this * v;\n        } else if (v.IsConstant()) {\n        } else if (!v.IsFraction()) {\n            is = v.IsMultiplicationSimplifiable(*this);\n        } else {\n            IMPLEMENT\n        }\n        return is;\n    }\n\nbool Fraction::SumIfSimplifiable(const Valuable& v)\n{\n    auto is = IsSimpleFraction() && v.IsSimple();\n    if(is){\n        *this += v;\n    } else if (!v.IsFraction()) {\n        auto s = v.IsSummationSimplifiable(*this);\n        is = s.first;\n        if (is) {\n            Become(std::move(s.second));\n        }\n    } else {\n        IMPLEMENT\n    }\n    return is;\n}\n\nstd::pair<bool,Valuable> Fraction::IsSummationSimplifiable(const Valuable& v) const\n{\n    std::pair<bool,Valuable> is;\n    auto simple = IsSimpleFraction();\n    is.first = simple && v.IsSimple();\n    if(is.first){\n        is.second = *this + v;\n    } else if (v.IsVa()) {\n        is.first = !simple && HasVa(v.as<Variable>());\n        if (is.first) {\n            LOG_AND_IMPLEMENT(\"Optimize summation of \" << *this << \" with \" << v);\n        }\n    } else if (!v.IsFraction()) {\n        is = v.IsSummationSimplifiable(*this);\n    } else {\n        IMPLEMENT\n    }\n    return is;\n}\n\n    Valuable& Fraction::operator +=(const Valuable& v)\n    {\n        if (v.IsFraction()){\n            auto& f = v.as<Fraction>();\n            if(denominator() == f.denominator()) {\n                numerator() += f.numerator();\n            } else {\n                numerator() = numerator() * f.denominator() + f.numerator() * denominator();\n                denominator() *= f.denominator();\n            }\n        }\n        else if(v.IsInt() && IsSimple()) {\n            setNumerator(numerator() + denominator() * v.as<Integer>());\n        } else {\n            return Become(Sum {*this, v});\n        }\n\n        optimize();\n        return *this;\n    }\n\n    Valuable& Fraction::operator *=(const Valuable& v)\n    {\n        if (v.IsFraction())\n        {\n            auto& f = v.as<Fraction>();\n            numerator() *= f.numerator();\n            denominator() *= f.denominator();\n        }\n        else if (v.IsInt())\n        {\n            numerator() *= v;\n        }\n        else\n        {\n            return Become(v * *this);\n        }\n\t\t\n        optimize();\n        return *this;\n    }\n\n    Valuable& Fraction::operator /=(const Valuable& v)\n    {\n        if (v.IsFraction())\n        {\n            auto& f = v.as<Fraction>();\n            numerator() *= f.denominator();\n            denominator() *= f.numerator();\n        }\n        else if (v.IsProduct())\n        {\n            for(auto& _ : v.as<Product>())\n                *this /= _;\n        }\n        else\n        {\n            denominator() *= v;\n        }\n        optimize();\n        return *this;\n    }\n\n    Valuable& Fraction::operator %=(const Valuable& v)\n    {\n        Integer d(*this / v);\n\t\treturn *this -= d * v;\n    }\n\n    Valuable& Fraction::operator^=(const Valuable& v)\n    {\n        if(v.IsFraction()){\n            auto& vf = v.as<Fraction>();\n            auto& vfdn = vf.denominator();\n            if (vfdn == 2_v)\n                ;\n            else if (vfdn.bit(0_v)!=1_v) {\n                IMPLEMENT\n            }\n        }\n        numerator() ^= v;\n        denominator() ^= v;\n        optimized = {};\n        optimize();\n        return *this;\n//        if(v.IsInt())\n//        {\n//            auto i = v.ca();\n//            if (i != 0_v) {\n//                if (i > 1_v) {\n//                    auto a = *this;\n//                    for (auto n = i; n > 1_v; --n) {\n//                        *this *= a;\n//                    }\n//                    optimize();\n//                    return *this;\n//                }\n//            }\n//            else { // zero\n//                if (numerator() == 0_v)\n//                    throw \"NaN\"; // feel free to handle this properly\n//                else\n//                    return Become(1_v);\n//            }\n//        }\n//        else if(IsSimple())\n//        {\n//            auto f = Fraction::cast(v);\n//            if (f->IsSimple())\n//            {\n//                auto n = f->numerator();\n//                auto dn = f->denominator();\n//\n//                if (n != 1_v)\n//                    *this ^= n;\n//                Valuable nroot;\n//                Valuable left =0, right = *this;\n//\n//                for (;;)\n//                {\n//                    nroot = left +(right - left) / 2_v;\n//                    auto result = nroot ^ dn;\n//                    if (result == *this)\n//                        return Become(std::move(nroot));\n//                    else if (*this < result)\n//                        right = nroot;\n//                    else\n//                        left = nroot;\n//                }\n//            }\n//        }\n//\n//        return Become(Exponentiation(*this, v));\n    }\n    \n    Valuable& Fraction::d(const Variable& x)\n    {\n        if (IsSimpleFraction()) {\n            Become(0_v);\n        } else {\n            IMPLEMENT\n        }\n        return *this;\n    }\n    \n    bool Fraction::operator <(const Valuable& v) const\n    {\n        if (v.IsFraction())\n        {\n            auto& f = v.as<Fraction>();\n            return numerator() * f.denominator() < f.numerator() * denominator();\n        }\n        else if (v.IsInt())\n        {\n            if(denominator()<0)\n                return -numerator() < v * -denominator();\n            else\n                return numerator() < v * denominator();\n        }\n        else\n            return base::operator <(v);\n    }\n    \n    Fraction::operator double() const\n    {\n        return static_cast<double>(numerator()) / static_cast<double>(denominator());\n    }\n    \n    Valuable& Fraction::sq(){\n        numerator().sq();\n        denominator().sq();\n        optimize();\n        return *this;\n    }\n\n    Valuable Fraction::Sqrt() const\n    {\n        return numerator().Sqrt() / denominator().Sqrt();\n    }\n\n    std::ostream& Fraction::print_sign(std::ostream& out) const\n    {\n        return out << '/';\n    }\n    \n    const Valuable::vars_cont_t& Fraction::getCommonVars() const\n    {\n        vars = numerator().getCommonVars();\n        for(auto& r : denominator().getCommonVars())\n        {\n            vars[r.first] -= r.second;\n        }\n        return vars;\n    }\n    \n    Valuable Fraction::InCommonWith(const Valuable& v) const\n    {\n        auto c = 1_v;\n        if (v.IsFraction()) {\n            auto& f = v.as<Fraction>();\n            c *= getNumerator().InCommonWith(f.getNumerator());\n            c /= getDenominator().InCommonWith(f.getDenominator());\n        }\n        else\n        {\n            c = getNumerator().InCommonWith(v);\n        }\n        return c;\n    }\n\n    bool Fraction::IsComesBefore(const Valuable& v) const\n    {\n//        auto va1 = FindVa();\n//        auto va2 = v.FindVa();\n//        return !va1 && !va2\n//            ? (IsSimple() && (v.IsInt() || (v.IsFraction() && Fraction::cast(v)->IsSimple())) ? operator<(v) : str().length() < v.str().length())\n//                : (va1 && va2\n//                   ? str().length() < v.str().length()\n//                   : va1!=nullptr );\n        auto mve = base::getMaxVaExp();\n        auto vmve = v.getMaxVaExp();\n        auto is = mve > vmve;\n        if (mve != vmve)\n        {}\n        else if (v.IsFraction())\n        {\n            if (IsSimple() && v.IsSimpleFraction())\n                is = *this < v;\n            else\n            {\n                auto& f = v.as<Fraction>();\n                is = numerator().IsComesBefore(f.numerator()) || denominator().IsComesBefore(f.denominator());\n            }\n//            auto e = cast(v);\n//            bool numerator()IsVa = numerator().IsVa();\n//            bool vbaseIsVa = e->numerator().IsVa();\n//            if (numerator()IsVa && vbaseIsVa)\n//                is = denominator() == e->denominator() ? numerator().IsComesBefore(e->numerator()) : denominator() > e->denominator();\n//            else if(numerator()IsVa)\n//                is = false;\n//            else if(vbaseIsVa)\n//                is = true;\n//            else if(numerator() == e->numerator())\n//                is = denominator().IsComesBefore(e->denominator());\n//            else if(denominator() == e->denominator())\n//                is = numerator().IsComesBefore(e->numerator());\n//            else\n//            {\n//                auto expComesBefore = denominator().IsComesBefore(e->denominator());\n//                auto ebaseComesBefore = numerator().IsComesBefore(e->numerator());\n//                is = ebaseComesBefore || expComesBefore;//expComesBefore==ebaseComesBefore || str().length() > e->str().length();\n//            }\n        }\n        else if(v.IsProduct())\n            is = Product{*this}.IsComesBefore(v);\n        else if(v.IsSum())\n            is = Sum{*this}.IsComesBefore(v);\n        else if(v.IsVa())\n            is = FindVa();\n        else if(v.IsInt())\n            is = true;\n        else\n            IMPLEMENT\n\n        return is;\n    }\n    \n    Fraction::operator unsigned char() const\n    {\n        return static_cast<unsigned char>(static_cast<Integer>(*this));\n    }\n  \n    Fraction::operator a_int() const\n    {\n        if (!IsSimple()) {\n            IMPLEMENT\n        }\n        return static_cast<a_int>(numerator())/static_cast<a_int>(denominator());\n    }\n    \n    Fraction::operator boost::multiprecision::cpp_dec_float_100() const\n    {\n        if (IsSimple())\n        {\n            boost::multiprecision::cpp_dec_float_100 f(numerator().ca());\n            f /= boost::multiprecision::cpp_dec_float_100(denominator().ca());\n            // TODO : check validity\n            return f;\n        }\n        else\n            IMPLEMENT;\n    }\n    \n    Valuable Fraction::operator()(const Variable& v, const Valuable& augmentation) const\n    {\n        return (augmentation * denominator() - numerator())(v);\n    }\n    \n    omnn::math::Fraction Fraction::Reciprocal() const\n    {\n        return Fraction(denominator(), numerator());\n    }\n\n    bool Fraction::IsSimple() const\n    {\n        return numerator().IsInt()\n            && denominator().IsInt()\n        ;\n    }\n}}\n", "meta": {"hexsha": "b765ea579692ef5e47bcbf676afcef5c03b46d16", "size": 18456, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "omnn/math/Fraction.cpp", "max_stars_repo_name": "ohhmm/openmind", "max_stars_repo_head_hexsha": "fa3692f9924df13a4e0f265a320977b2b2aaba76", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2017-08-13T18:46:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-14T14:18:10.000Z", "max_issues_repo_path": "omnn/math/Fraction.cpp", "max_issues_repo_name": "ohhmm/openmind", "max_issues_repo_head_hexsha": "fa3692f9924df13a4e0f265a320977b2b2aaba76", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 36.0, "max_issues_repo_issues_event_min_datetime": "2017-11-26T12:42:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-20T09:38:33.000Z", "max_forks_repo_path": "omnn/math/Fraction.cpp", "max_forks_repo_name": "ohhmm/openmind", "max_forks_repo_head_hexsha": "fa3692f9924df13a4e0f265a320977b2b2aaba76", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-08-28T07:00:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-04T19:59:55.000Z", "avg_line_length": 28.9278996865, "max_line_length": 147, "alphanum_fraction": 0.4268530559, "num_tokens": 4170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708698, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4756096005759102}}
{"text": "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n//------------------------------------------------------------------------------\n// Pose.h\n//\n// Stores the camera pose as a 3d position and rotation.\n// it is the transform that will bring things into a camera relative space, not \n// the transform that would position a proxy object into the orientation of the\n// camera\n//------------------------------------------------------------------------------\n\n#include \"Pose.h\"\n\n#include \"Utils\\cv.h\"\n\n#include <Eigen\\Dense>\n#include <Eigen\\Geometry> \n#include <opencv2\\core\\eigen.hpp>\n#include <opencv2\\calib3d\\calib3d.hpp>\n\nnamespace mage\n{\n    Pose::Pose()\n    {\n        // initialization \n        m_viewMatrix = cv::Matx34f::eye();\n        m_inverseViewMatrix = cv::Matx44f::eye();\n    }\n\n    Pose::Pose(const cv::Matx44f& worldMatrix)\n    {\n        m_inverseViewMatrix = worldMatrix;\n        cv::Matx44f temp = Invert(worldMatrix);\n        m_viewMatrix = temp.get_minor<3, 4>(0, 0);\n    }\n\n    Pose::Pose(const cv::Matx31f& viewSpacePosition, const cv::Matx33f& viewSpaceRotationMatrix)\n    {\n        SetViewSpacePositionAndRotation(viewSpacePosition, viewSpaceRotationMatrix);\n    }\n\n    void Pose::SetViewMatrix(const cv::Matx34f& viewMat)\n    {\n            m_viewMatrix(0, 0) = viewMat(0, 0);\n            m_viewMatrix(0, 1) = viewMat(0, 1);\n            m_viewMatrix(0, 2) = viewMat(0, 2);\n            m_viewMatrix(0, 3) = viewMat(0, 3);\n\n            m_viewMatrix(1, 0) = viewMat(1, 0);\n            m_viewMatrix(1, 1) = viewMat(1, 1);\n            m_viewMatrix(1, 2) = viewMat(1, 2);\n            m_viewMatrix(1, 3) = viewMat(1, 3);\n\n            m_viewMatrix(2, 0) = viewMat(2, 0);\n            m_viewMatrix(2, 1) = viewMat(2, 1);\n            m_viewMatrix(2, 2) = viewMat(2, 2);\n            m_viewMatrix(2, 3) = viewMat(2, 3);\n\n            ComputeInverseViewMatrix();\n    }\n\n    void Pose::SetViewSpacePositionAndRotation(const cv::Matx31f& positionMatrix, const cv::Matx33f& viewSpaceRotationMatrix)\n    {\n        m_viewMatrix(0, 3) = positionMatrix(0,0);\n        m_viewMatrix(1, 3) = positionMatrix(1,0);\n        m_viewMatrix(2, 3) = positionMatrix(2,0);\n\n        m_viewMatrix(0, 0) = viewSpaceRotationMatrix(0, 0);\n        m_viewMatrix(0, 1) = viewSpaceRotationMatrix(0, 1);\n        m_viewMatrix(0, 2) = viewSpaceRotationMatrix(0, 2);\n\n        m_viewMatrix(1, 0) = viewSpaceRotationMatrix(1, 0);\n        m_viewMatrix(1, 1) = viewSpaceRotationMatrix(1, 1);\n        m_viewMatrix(1, 2) = viewSpaceRotationMatrix(1, 2);\n\n        m_viewMatrix(2, 0) = viewSpaceRotationMatrix(2, 0);\n        m_viewMatrix(2, 1) = viewSpaceRotationMatrix(2, 1);\n        m_viewMatrix(2, 2) = viewSpaceRotationMatrix(2, 2);\n\n        ComputeInverseViewMatrix();\n    }\n\n    cv::Matx31f Pose::GetViewSpacePosition() const\n    {\n        return m_viewMatrix.col(3);\n    }\n\n    cv::Matx31f Pose::GetViewSpaceRodriguesRotation() const\n    {\n        cv::Matx31f rotation;\n        cv::Rodrigues(GetRotationMatrix(), rotation);\n        return rotation;\n    }\n\n    float Pose::GetRoll() const\n    {\n        // Todo: perf. converting from mat to quat back to mat to calculate roll.\n        auto quat = ToQuat(Rotation(m_inverseViewMatrix));\n\n        float yaw;\n        float pitch;\n        float roll;\n\n        ToEuler(quat, yaw, pitch, roll);\n\n        return roll;\n    }\n\n    cv::Point3f Pose::GetWorldSpacePosition() const\n    {\n        return{ m_inverseViewMatrix(0,3), m_inverseViewMatrix(1,3), m_inverseViewMatrix(2,3) };\n    }\n\n    cv::Vec3f Pose::GetWorldSpaceForward() const\n    {\n        return{ m_inverseViewMatrix(0,2), m_inverseViewMatrix(1,2), m_inverseViewMatrix(2,2) };\n    }\n\n    cv::Vec3f Pose::GetWorldSpaceRight() const\n    {\n        return{ m_inverseViewMatrix(0,0), m_inverseViewMatrix(1,0), m_inverseViewMatrix(2,0) };\n    }\n\n    // right handed, column major\n    cv::Matx33f Pose::GetRotationMatrix() const\n    {\n        return m_viewMatrix.get_minor<3, 3>(0, 0);\n    }\n\n    // use eigen to handle the rotation matrix <=> quaternion conversion\n    Quaternion Pose::GetRotationQuaternion() const\n    {\n        Eigen::Matrix3f eigenMat;\n        cv::cv2eigen(GetRotationMatrix(), eigenMat);\n\n        return Eigen::Quaternionf{ eigenMat }.normalized();\n    }\n\n    //right handed, column major\n    const cv::Matx34f& Pose::GetViewMatrix() const\n    {\n        return m_viewMatrix;\n    }\n\n    cv::Matx44f Pose::GetViewMatrix4x4() const\n    {\n        return {\n            m_viewMatrix(0, 0), m_viewMatrix(0, 1), m_viewMatrix(0, 2), m_viewMatrix(0, 3),\n            m_viewMatrix(1, 0), m_viewMatrix(1, 1), m_viewMatrix(1, 2), m_viewMatrix(1, 3),\n            m_viewMatrix(2, 0), m_viewMatrix(2, 1), m_viewMatrix(2, 2), m_viewMatrix(2, 3),\n                             0,                  0,                  0,                  1\n        };\n    }\n\n    //right handed, column major\n    const cv::Matx44f& Pose::GetInverseViewMatrix() const\n    {\n        return m_inverseViewMatrix;\n    }\n\n    cv::Matx34f Pose::GetRelativeViewMatrix(const Pose& toFrame) const\n    {\n        return toFrame.GetViewMatrix() * m_inverseViewMatrix;\n    }\n\n    void Pose::ComputeInverseViewMatrix()\n    {\n        m_inverseViewMatrix = Invert(m_viewMatrix);\n    }\n}", "meta": {"hexsha": "45e8dfd4f217b85c35c7e668173de288d4c0a60d", "size": 5241, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Core/MAGESLAM/Source/Data/Pose.cpp", "max_stars_repo_name": "syntheticmagus/mageslam", "max_stars_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 70.0, "max_stars_repo_stars_event_min_datetime": "2020-05-07T03:09:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T01:04:54.000Z", "max_issues_repo_path": "Core/MAGESLAM/Source/Data/Pose.cpp", "max_issues_repo_name": "syntheticmagus/mageslam", "max_issues_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-06-01T00:34:01.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-08T07:43:32.000Z", "max_forks_repo_path": "Core/MAGESLAM/Source/Data/Pose.cpp", "max_forks_repo_name": "syntheticmagus/mageslam", "max_forks_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2020-05-07T03:09:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:36:49.000Z", "avg_line_length": 30.649122807, "max_line_length": 125, "alphanum_fraction": 0.5949246327, "num_tokens": 1519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128672997041659, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4756095952709713}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n#include <iomanip>\n#include <vector>\n#include <igl/remove_unreferenced.h>\n#include \"SecondFundamentalForm/MidedgeAverageFormulation.h\"\n#include \"Stitch.h\"\n#include \"MeshConnectivity.h\"\n#include <igl/cotmatrix.h>\n#include <igl/boundary_facets.h>\n#include <igl/boundary_loop.h>\n\nvoid stitchMeshes(const Eigen::MatrixXd& V, const Eigen::MatrixXi& F, Eigen::MatrixXd& stitchedV, Eigen::MatrixXi& stitchedF, std::vector<Eigen::Vector3i> &bnd_edges, Eigen::VectorXi& newIndex)\n{\n    std::map<int, int> parentvert;\n    int nverts = V.rows();\n    std::vector<bool> seam(nverts,false);\n    std::vector<std::vector<int> > bls;\n       \n    igl::boundary_loop(F, bls);\n       \n    std::vector<int> boundVerts;\n       \n    for(auto &b : bls)\n        for(int i = 0; i < b.size(); i++)\n        {\n            boundVerts.push_back(b[i]);\n        }\n    \n    for(int i = 0; i < boundVerts.size(); i++)\n    {\n        for(int j = 0; j < boundVerts.size(); j++)\n        {\n            if(j == i)\n                continue;\n            int v1 = boundVerts[i];\n            int v2 = boundVerts[j];\n            if((V.row(v1) - V.row(v2)).norm() < 1e-5)\n            {\n                seam[v1] = true;\n                seam[v2] = true;\n                auto it = parentvert.find(v1);\n                \n                if(it == parentvert.end())\n                    parentvert[v2] = v1;\n                else\n                    parentvert[v2] = it->second;\n            }\n        }\n    }\n\n    int nfaces = F.rows();\n    Eigen::MatrixXi mappedF = F;\n\n    for (int i = 0; i < nfaces; i++)\n    { \n        for (int j = 0; j < 3; j++)\n        {\n            auto it = parentvert.find(mappedF(i, j));\n            if (it != parentvert.end())\n                mappedF(i,j) = it->second;\n        }\n    }\n \n\n    Eigen::VectorXi I;\n    Eigen::VectorXi J;\n    igl::remove_unreferenced(V, mappedF, stitchedV, stitchedF, I, J);\n\n    std::cout << \"number of verts over all patches :  \" << V.rows() << \" number of verts after stitching : \" << stitchedV.rows() << std::endl;\n    std::cout << \"number of faces over all patches :  \" << F.rows() << \" number of faces after stitching : \" << stitchedF.rows() << std::endl;\n    \n    nverts = stitchedV.rows();\n   \n    newIndex = I;\n    for (int i = 0; i < newIndex.size(); i++)\n    {\n        if (newIndex(i) == -1)\n        {\n            auto it = parentvert.find(i);\n            newIndex(i) = I(it->second);\n        }\n    }\n\n    //compute boundary\n \n    Eigen::MatrixXi bndV;\n    Eigen::MatrixXi bndF;\n    Eigen::MatrixXi OppBndV;\n    igl::boundary_facets(F,bndV, bndF, OppBndV);\n    bnd_edges.clear();\n    for (int i = 0; i < bndV.rows(); i++)\n    {\n        if (!(seam[bndV(i,0)] && seam[bndV(i,1)])) // both vertices are not on the seam then it's still a boundary\n            bnd_edges.push_back(Eigen::Vector3i(bndV(i,0), bndV(i,1), F(bndF(i),OppBndV(i)))); \n    }\n\n}\n\n\nvoid stitchMeshesWithTol(const Eigen::MatrixXd &V, const Eigen::MatrixXi &F, Eigen::MatrixXd &stitchedV, Eigen::MatrixXi &stitchedF, double tol)\n{\n    std::map<int, int> parentvert;\n    int nverts = V.rows();\n    std::vector<bool> seam(nverts,false);\n    std::vector<std::vector<int> > bls;\n       \n    igl::boundary_loop(F, bls);\n       \n    std::vector<int> boundVerts;\n       \n    for(auto &b : bls)\n        for(int i = 0; i < b.size(); i++)\n        {\n            boundVerts.push_back(b[i]);\n        }\n       \n    for(int i = 0; i < boundVerts.size(); i++)\n    {\n        for(int j = 0; j < boundVerts.size(); j++)\n        {\n            if(j == i)\n                continue;\n            int v1 = boundVerts[i];\n            int v2 = boundVerts[j];\n            if((V.row(v1) - V.row(v2)).norm() < 1e-5)\n            {\n                seam[v1] = true;\n                seam[v2] = true;\n                auto it = parentvert.find(v1);\n                \n                if(it == parentvert.end())\n                    parentvert[v2] = v1;\n                else\n                    parentvert[v2] = it->second;\n            }\n        }\n    }\n\n    int nfaces = F.rows();\n    Eigen::MatrixXi mappedF = F;\n\n    for (int i = 0; i < nfaces; i++)\n    { \n        for (int j = 0; j < 3; j++)\n        {\n            auto it = parentvert.find(mappedF(i, j));\n            if (it != parentvert.end())\n                mappedF(i,j) = it->second;\n        }\n    }\n \n\n    Eigen::VectorXi I;\n    Eigen::VectorXi J;\n    igl::remove_unreferenced(V, mappedF, stitchedV, stitchedF, I, J);\n\n    std::cout << \"number of verts over all patches :  \" << V.rows() << \" number of verts after stitching : \" << stitchedV.rows() << std::endl;\n    std::cout << \"number of faces over all patches :  \" << F.rows() << \" number of faces after stitching : \" << stitchedF.rows() << std::endl;\n}\n\nvoid testStitchMeshes()\n{\n   /* Eigen::MatrixXd V1(8,3);\n    Eigen::MatrixXi F1(4,3);\n    Eigen::MatrixXd nV1;\n    Eigen::MatrixXi nF1;\n    V1.setZero();\n    V1.row(0) << 0, 0, 0;\n    V1.row(1) << 1, 0, 0;\n    V1.row(2) << 0, 1, 0;\n    V1.row(3) << 1, 1, 0;\n    Eigen::RowVector3d shift;\n    shift << -1, 0 ,0;\n    for (int j = 0; j < 4; j++)\n        V1.row(j+4) = V1.row(j) + shift;\n    F1 << 0, 1, 3, 0, 3, 2, 4, 5, 7, 4, 7, 6;\n    SimulationSetup setup1;\n    MidedgeAverageFormulation sff;\n    MeshConnectivity mesh1(F1);\n    setup1.buildRestFundamentalForms(mesh1, V1, sff);\n    stitchMeshes(V1,F1,nV1,nF1,setup1);\n\n    Eigen::MatrixXd nV2;\n    Eigen::MatrixXi nF2;\n    SimulationSetup setup2;\n    MeshConnectivity mesh2(nF1);\n    MidedgeAverageFormulation sff2;\n    setup2.buildRestFundamentalForms(mesh2, nV1, sff2);\n    stitchMeshes(nV1,nF1,nV2,nF2,setup2);\n\n    std::cout << \"laplacian difference : \" << (setup1.laplacian - setup2.laplacian).norm() << std::endl;   \n    std::cout << \"laplace position : \" << (setup1.laplacian * nV1).norm() << std::endl;*/\n\n}\n", "meta": {"hexsha": "0bc9f9da206af8a32818cb5af1795a1980f35e0b", "size": 5817, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Stitch.cpp", "max_stars_repo_name": "csyzzkdcz/effective-garbanzo", "max_stars_repo_head_hexsha": "87223ecfc26371a9b251a70a0111ca4e0d95b594", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Stitch.cpp", "max_issues_repo_name": "csyzzkdcz/effective-garbanzo", "max_issues_repo_head_hexsha": "87223ecfc26371a9b251a70a0111ca4e0d95b594", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Stitch.cpp", "max_forks_repo_name": "csyzzkdcz/effective-garbanzo", "max_forks_repo_head_hexsha": "87223ecfc26371a9b251a70a0111ca4e0d95b594", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.6785714286, "max_line_length": 193, "alphanum_fraction": 0.5231218841, "num_tokens": 1765, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128672997041659, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4756095952709713}}
{"text": "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n#include \"UnfilteredIMU.h\"\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include \"Utils/cv.h\"\n#include <boost/optional.hpp>\n\n#include <arcana/containers/sorted_vector.h>\n#include <arcana/analysis/object_trace.h>\n#include <arcana/analysis/data_point.h>\n\nnamespace E = Eigen;\n\nnamespace mage\n{\n    using seconds = std::chrono::duration<double>;\n\n    struct alignas(16) UnfilteredIMU::Impl\n    {\n        E::Matrix4d m_bodyIMUToBodyCamera = E::Matrix4d::Identity();\n        E::Matrix3d m_bodyIMUToBodyCameraRotationOnly = E::Matrix3d::Identity();\n        E::Matrix4d m_bodyCameraToBodyIMU = E::Matrix4d::Identity();\n\n        mage::SensorSample::Timestamp m_gyroTime{};\n        mage::SensorSample::Timestamp m_accelTime{};\n\n        mira::sorted_vector<mage::SensorSample, mage::SensorSample::Compare> m_samples;\n\n        mage::SensorSample::Timestamp m_previousTs{};\n        mage::Pose m_previousPose;\n\n        Eigen::Vector3d Gravity = Eigen::Vector3d::Zero();\n\n        Eigen::Vector3d Acceleration = Eigen::Vector3d::Zero();\n        Eigen::Vector3d Velocity = Eigen::Vector3d::Zero();\n        Eigen::Vector3d Position = Eigen::Vector3d::Zero();\n\n        E::AngleAxisd AngularVelocity = E::AngleAxisd::Identity();\n        Eigen::Quaterniond Orientation = Eigen::Quaterniond::Identity();\n\n        void ProcessGyroUntil(mage::SensorSample::Timestamp ts)\n        {\n            if (m_gyroTime == mage::SensorSample::Timestamp{})\n                m_gyroTime = ts;\n\n            seconds dt = ts - m_gyroTime;\n\n            E::AngleAxisd av = AngularVelocity;\n            av.angle() *= dt.count();\n\n            Orientation = Orientation * av;\n            Orientation.normalize();\n\n            m_gyroTime = ts;\n        }\n\n        void SetAngularVelocity(Eigen::Map<const Eigen::Vector3f> value)\n        {\n            Eigen::Vector3f angularVelocityInCameraSpace{\n                value[1],\n                value[0],\n                -value[2]\n            };\n            AngularVelocity = E::AngleAxisd(mira::deg2rad<double>(angularVelocityInCameraSpace.x()), E::Vector3d::UnitX())\n                * E::AngleAxisd(mira::deg2rad<double>(angularVelocityInCameraSpace.y()), E::Vector3d::UnitY())\n                * E::AngleAxisd(mira::deg2rad<double>(angularVelocityInCameraSpace.z()), E::Vector3d::UnitZ());\n        }\n\n        void ProcessAccelerationUntil(mage::SensorSample::Timestamp ts)\n        {\n            if (m_accelTime == mage::SensorSample::Timestamp{})\n                m_accelTime = ts;\n\n            seconds dt = ts - m_accelTime;\n\n            E::Vector3d vi = Velocity;\n\n            Velocity += dt.count() * (Acceleration - Gravity);\n            Position += 0.5 * (Velocity + vi) * dt.count();\n\n            FIRE_OBJECT_TRACE(\"IMU Linear Velocity.UnfilteredIMU\", this, (mira::make_data_point<float>(\n                ts,\n                (float)Velocity.norm()\n            )));\n\n            m_accelTime = ts;\n        }\n\n        void SetLinearAcceleration(Eigen::Map<const Eigen::Vector3f> value)\n        {\n            Eigen::Vector3f sensorAccelInCameraSpace{\n                value[1],\n                value[0],\n                -value[2]\n            };\n\n            Acceleration = Orientation * sensorAccelInCameraSpace.cast<double>();\n\n            Gravity = 0.9 * Gravity + 0.1 * Acceleration;\n        }\n\n        void ProcessPose(mage::SensorSample::Timestamp ts, const mage::Pose& pose)\n        {\n            assert(ts >= m_previousTs);\n\n            PredictUpTo(ts);\n\n            auto transform = Decompose(pose.GetInverseViewMatrix());\n\n            Orientation = transform.second.cast<double>();\n            Position = ToMap(transform.first).cast<double>();\n\n            if (m_previousTs == mage::SensorSample::Timestamp{})\n            {\n                Velocity = E::Vector3d::Zero();\n                AngularVelocity = E::AngleAxisd::Identity();\n            }\n            else\n            {\n                seconds dt = ts - m_previousTs;\n                auto previous = Decompose(m_previousPose.GetInverseViewMatrix());\n            \n                Velocity = (Position - ToMap(previous.first).cast<double>()) / dt.count();\n            \n                AngularVelocity = (transform.second * previous.second.inverse()).cast<double>();\n                AngularVelocity.angle() /= dt.count();\n            }\n\n            m_previousPose = pose;\n            m_previousTs = ts;\n        }\n\n        void PredictUpTo(mage::SensorSample::Timestamp timestamp)\n        {\n            auto from = m_samples.begin();\n            auto to = std::find_if(from, m_samples.end(), [timestamp](const mage::SensorSample& sample)\n            {\n                return sample.GetTimestamp() > timestamp;\n            });\n\n            for (auto itr = from; itr != to; itr++)\n            {\n                if (itr->GetType() == mage::SensorSample::SampleType::Gyrometer)\n                {\n                    ProcessGyroUntil(itr->GetTimestamp());\n                    SetAngularVelocity({ itr->GetData().data(), 3 });\n                }\n                else if (itr->GetType() == mage::SensorSample::SampleType::Accelerometer)\n                {\n                    ProcessAccelerationUntil(itr->GetTimestamp());\n                    SetLinearAcceleration({ itr->GetData().data(), 3 });\n                }\n            }\n\n            m_samples.erase(from, to);\n\n            ProcessGyroUntil(timestamp);\n            ProcessAccelerationUntil(timestamp);\n        }\n    };\n\n    UnfilteredIMU::UnfilteredIMU(const device::IMUCharacterization& imuCharacterization)\n        : m_impl{ std::allocate_shared<Impl, Eigen::aligned_allocator<Impl>>({}) }\n    {\n        m_impl->m_bodyIMUToBodyCamera = E::Map<const E::Matrix4f>(imuCharacterization.BodyIMUToBodyCamera.data(), 4, 4).cast<double>();\n        m_impl->m_bodyIMUToBodyCameraRotationOnly = m_impl->m_bodyIMUToBodyCamera.block<3, 3>(0, 0);\n        m_impl->m_bodyCameraToBodyIMU = E::Map<const E::Matrix4f>(imuCharacterization.BodyCameraToBodyIMU.data(), 4, 4).cast<double>();\n    }\n\n    UnfilteredIMU::~UnfilteredIMU() = default;\n\n    void UnfilteredIMU::AddSample(const mage::SensorSample& sample)\n    {\n        if (sample.GetType() == mage::SensorSample::SampleType::Gyrometer ||\n            sample.GetType() == mage::SensorSample::SampleType::Accelerometer)\n        {\n            m_impl->m_samples.insert(sample);\n        }\n    }\n\n    mage::Pose UnfilteredIMU::GetPose() const\n    {\n        Eigen::Vector3f position{ m_impl->Position.cast<float>() };\n        return mage::Pose(FromQuatAndTrans(m_impl->Orientation.cast<float>(), { position.x(), position.y(), position.z() }));\n    }\n\n    void UnfilteredIMU::PredictUpTo(mage::SensorSample::Timestamp timestamp)\n    {\n        m_impl->PredictUpTo(timestamp);\n    }\n\n    void UnfilteredIMU::AddPose(const mage::Pose& pose, mage::SensorSample::Timestamp timestamp)\n    {\n        m_impl->ProcessPose(timestamp, pose);\n    }\n}\n", "meta": {"hexsha": "518ad0af26226b25fba5ec3237333b0cb91d8ebf", "size": 6958, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Core/MAGESLAM/Source/Fuser/UnfilteredIMU.cpp", "max_stars_repo_name": "syntheticmagus/mageslam", "max_stars_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 70.0, "max_stars_repo_stars_event_min_datetime": "2020-05-07T03:09:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T01:04:54.000Z", "max_issues_repo_path": "Core/MAGESLAM/Source/Fuser/UnfilteredIMU.cpp", "max_issues_repo_name": "syntheticmagus/mageslam", "max_issues_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-06-01T00:34:01.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-08T07:43:32.000Z", "max_forks_repo_path": "Core/MAGESLAM/Source/Fuser/UnfilteredIMU.cpp", "max_forks_repo_name": "syntheticmagus/mageslam", "max_forks_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2020-05-07T03:09:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:36:49.000Z", "avg_line_length": 34.6169154229, "max_line_length": 135, "alphanum_fraction": 0.5830698477, "num_tokens": 1585, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182187, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.475607075970042}}
{"text": "#include <boost/test/unit_test.hpp>\n\n#define VMATH_CORE_SWIZZLE_ENABLE_ELEMENT_ACCESSORS\n#include <vmath/core/vector.hpp>\n#include <vmath/core/swizzle/swizzle4.hpp>\n\nBOOST_AUTO_TEST_SUITE(swizzle4)\n\nBOOST_AUTO_TEST_CASE(negate_op) {\n\tvmath::core::Vector<float, 4> V;\n\tV.x = 20.12f;\n\tV.y = 100.89f;\n\tV.z = -18.2f;\n\tV.w = 35.62f;\n\tvmath::core::Vector<float, 4> V_neg;\n\tV_neg = -V.yzxx;\n\tBOOST_CHECK_CLOSE(V_neg.x, -100.89f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_neg.y, 18.2f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_neg.z, -20.12f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_neg.w, -20.12f, 1e-4f);\n}\n\nBOOST_AUTO_TEST_CASE(add_op) {\n\tvmath::core::Vector<float, 4> V1;\n\tV1.x = 20.12f;\n\tV1.y = 100.89f;\n\tV1.z = -18.2f;\n\tV1.w = 35.62f;\n\tvmath::core::Vector<float, 4> V2;\n\tV2.x = 10.34f;\n\tV2.y = -15.5f;\n\tV2.z = 20.2f;\n\tV2.w = -200.34f;\n\tvmath::core::Vector<float, 4> V_add;\n\tV_add = V1.yxyx + V2.xxxx;\n\tBOOST_CHECK_CLOSE(V_add.x, 111.23f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_add.y, 30.46f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_add.z, 111.23f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_add.w, 30.46f, 1e-4f);\n\tV_add = V2.xxxx + V1.yxyx;\n\tBOOST_CHECK_CLOSE(V_add.x, 111.23f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_add.y, 30.46f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_add.x, 111.23f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_add.w, 30.46f, 1e-4f);\n}\n\nBOOST_AUTO_TEST_CASE(add_eq_op) {\n\tvmath::core::Vector<float, 4> V1;\n\tV1.x = 20.12f;\n\tV1.y = 100.89f;\n\tV1.z = -18.2f;\n\tV1.w = 35.62f;\n\tvmath::core::Vector<float, 4> V2;\n\tV2.x = 10.34f;\n\tV2.y = -15.5f;\n\tV2.z = 20.2f;\n\tV2.w = -200.34f;\n\tvmath::core::Vector<float, 4> V_add = V1;\n\tV_add.yxzw += V2.xxxx;\n\tBOOST_CHECK_CLOSE(V_add.x, 30.46f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_add.y, 111.23f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_add.z, -7.859999999f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_add.w, 45.96f, 1e-4f);\n}\n\nBOOST_AUTO_TEST_CASE(sub_op) {\n\tvmath::core::Vector<float, 4> V1;\n\tV1.x = 20.12f;\n\tV1.y = 100.89f;\n\tV1.z = -18.2f;\n\tV1.w = 35.62f;\n\tvmath::core::Vector<float, 4> V2;\n\tV2.x = 10.34f;\n\tV2.y = -15.5f;\n\tV2.z = 20.12f;\n\tV2.w = -200.34f;\n\tvmath::core::Vector<float, 4> V_sub;\n\tV_sub = V1.yxxx - V2.xxzx;\n\tBOOST_CHECK_CLOSE(V_sub.x, 90.55f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_sub.y, 9.78f, 1e-4f);\n\tBOOST_CHECK_SMALL(V_sub.z, 1e-7f);\n\tBOOST_CHECK_CLOSE(V_sub.w, 9.78f, 1e-4f);\n\tV_sub = V2.xxzx - V1.yxxx;\n\tBOOST_CHECK_CLOSE(V_sub.x, -90.55f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_sub.y, -9.78f, 1e-4f);\n\tBOOST_CHECK_SMALL(V_sub.z, 1e-7f);\n\tBOOST_CHECK_CLOSE(V_sub.w, -9.78f, 1e-4f);\n}\n\nBOOST_AUTO_TEST_CASE(sub_eq_op) {\n\tvmath::core::Vector<float, 4> V1;\n\tV1.x = 20.12f;\n\tV1.y = 100.89f;\n\tV1.z = -18.2f;\n\tV1.w = 35.62f;\n\tvmath::core::Vector<float, 4> V2;\n\tV2.x = 10.34f;\n\tV2.y = -15.5f;\n\tV2.z = 20.2f;\n\tV2.w = -200.34f;\n\tvmath::core::Vector<float, 4> V_sub = V1;\n\tV_sub.yxwz -= V2.xxxx;\n\tBOOST_CHECK_CLOSE(V_sub.x, 9.78f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_sub.y, 90.55f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_sub.z, -28.54f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_sub.w, 25.28f, 1e-4f);\n}\n\nBOOST_AUTO_TEST_CASE(mult_op) {\n\tvmath::core::Vector<float, 4> V1;\n\tV1.x = 20.12f;\n\tV1.y = 100.89f;\n\tV1.z = -18.2f;\n\tV1.w = 35.62f;\n\tvmath::core::Vector<float, 4> V2;\n\tV2.x = 10.34f;\n\tV2.y = -15.5f;\n\tV2.z = 20.2f;\n\tV2.w = -200.34f;\n\tvmath::core::Vector<float, 4> V_mult;\n\tV_mult = V1.yxxx * V2.xxxx;\n\tBOOST_CHECK_CLOSE(V_mult.x, 1043.2026f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_mult.y, 208.0408f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_mult.z, 208.0408f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_mult.w, 208.0408f, 1e-4f);\n\tV_mult = V2.xxxx * V1.yxxx;\n\tBOOST_CHECK_CLOSE(V_mult.x, 1043.2026f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_mult.y, 208.0408f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_mult.z, 208.0408f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_mult.w, 208.0408f, 1e-4f);\n}\n\nBOOST_AUTO_TEST_CASE(mult_eq_op) {\n\tvmath::core::Vector<float, 4> V1;\n\tV1.x = 20.12f;\n\tV1.y = 100.89f;\n\tV1.z = -18.2f;\n\tV1.w = 35.62f;\n\tvmath::core::Vector<float, 4> V2;\n\tV2.x = 10.34f;\n\tV2.y = -15.5f;\n\tV2.z = 20.2f;\n\tV2.w = -200.34f;\n\tvmath::core::Vector<float, 4> V_mult = V1;\n\tV_mult.yxzw *= V2.xyxx;\n\tBOOST_CHECK_CLOSE(V_mult.x, -311.86f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_mult.y, 1043.2026f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_mult.z, -188.188f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_mult.w, 368.3108f, 1e-4f);\n}\n\nBOOST_AUTO_TEST_CASE(div_op) {\n\tvmath::core::Vector<float, 4> V1;\n\tV1.x = 20.0f;\n\tV1.y = 40.0f;\n\tV1.z = 60.0f;\n\tV1.w = 80.0f;\n\tvmath::core::Vector<float, 4> V2;\n\tV2.x = 2.0f;\n\tV2.y = 4.0f;\n\tV2.z = 6.0f;\n\tV2.z = 8.0f;\n\tvmath::core::Vector<float, 4> V_div;\n\tV_div = V1.yxxz / V2.xxxz;\n\tBOOST_CHECK_CLOSE(V_div.x, 20.0f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_div.y, 10.0f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_div.z, 10.0f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_div.z, 10.0f, 1e-4f);\n\tV_div = V1.xxxx / V2.yxxy;\n\tBOOST_CHECK_CLOSE(V_div.x, 5.0f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_div.y, 10.0f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_div.z, 10.0f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_div.w, 5.0f, 1e-4f);\n}\n\nBOOST_AUTO_TEST_CASE(div_eq_op) {\n\tvmath::core::Vector<float, 4> V1;\n\tV1.x = 20.0f;\n\tV1.y = 40.0f;\n\tV1.z = 60.0f;\n\tV1.w = 80.0f;\n\tvmath::core::Vector<float, 4> V2;\n\tV2.x = 2.0f;\n\tV2.y = 4.0f;\n\tV2.z = 6.0f;\n\tV2.w = 8.0f;\n\tvmath::core::Vector<float, 4> V_div = V1;\n\tV_div.yxzw /= V2.yxxx;\n\tBOOST_CHECK_CLOSE(V_div.x, 10.0f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_div.y, 10.0f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_div.z, 30.0f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_div.w, 40.0f, 1e-4f);\n}\n\nBOOST_AUTO_TEST_CASE(scalar_mult_op) {\n\tvmath::core::Vector<float, 4> V;\n\tV.x = 20.12f;\n\tV.y = 100.89f;\n\tV.z = -18.2f;\n\tV.w = 35.62f;\n\tfloat s = -34.45f;\n\tvmath::core::Vector<float, 4> V_mult;\n\tV_mult = V.xyzw * s;\n\tBOOST_CHECK_CLOSE(V_mult.x, -693.134f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_mult.y, -3475.6605f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_mult.z, 626.99f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_mult.w, -1227.109f, 1e-4f);\n}\n\nBOOST_AUTO_TEST_CASE(scalar_mult_eq_op) {\n\tvmath::core::Vector<float, 4> V;\n\tV.x = 20.12f;\n\tV.y = 100.89f;\n\tV.z = -18.2f;\n\tV.w = 35.62f;\n\tfloat s = -34.45f;\n\tvmath::core::Vector<float, 4> V_mult = V;\n\tV_mult.xyzw *= s;\n\tBOOST_CHECK_CLOSE(V_mult.x, -693.134f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_mult.y, -3475.6605f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_mult.z, 626.99f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_mult.w, -1227.109f, 1e-4f);\n}\n\nBOOST_AUTO_TEST_CASE(scalar_div_op) {\n\tvmath::core::Vector<float, 4> V;\n\tV.x = 20.12f;\n\tV.y = 100.89f;\n\tV.z = -18.2f;\n\tV.w = 35.62f;\n\tfloat s = -34.45f;\n\tvmath::core::Vector<float, 4> V_div;\n\tV_div = V.xyzw / s;\n\tBOOST_CHECK_CLOSE(V_div.x, -0.5840348330914369f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_div.y, -2.9285921625544264f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_div.z, 0.5283018867924527f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_div.w, -1.0339622641509432f, 1e-4f);\n}\n\nBOOST_AUTO_TEST_CASE(scalar_div_eq_op) {\n\tvmath::core::Vector<float, 4> V;\n\tV.x = 20.12f;\n\tV.y = 100.89f;\n\tV.z = -18.2f;\n\tV.w = 35.62f;\n\tfloat s = -34.45f;\n\tvmath::core::Vector<float, 4> V_div = V;\n\tV_div.xyzw /= s;\n\tBOOST_CHECK_CLOSE(V_div.x, -0.5840348330914369f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_div.y, -2.9285921625544264f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_div.z, 0.5283018867924527f, 1e-4f);\n\tBOOST_CHECK_CLOSE(V_div.w, -1.0339622641509432f, 1e-4f);\n}\n\nBOOST_AUTO_TEST_CASE(swizzles) {\n\tvmath::core::Vector<float, 4> V;\n\tV.x = 20.12f;\n\tV.y = 100.89f;\n\tV.z = -18.2f;\n\t// 2d swizzles <x, y, z, w>\n\tauto xx = V.xx;\n\tBOOST_CHECK_CLOSE(xx.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xx.getE2(), V.x, 1e-4f);\n\tauto xy = V.xy;\n\tBOOST_CHECK_CLOSE(xy.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xy.getE2(), V.y, 1e-4f);\n\tauto xz = V.xz;\n\tBOOST_CHECK_CLOSE(xz.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xz.getE2(), V.z, 1e-4f);\n\tauto xw = V.xw;\n\tBOOST_CHECK_CLOSE(xw.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xw.getE2(), V.w, 1e-4f);\n\tauto yx = V.yx;\n\tBOOST_CHECK_CLOSE(yx.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yx.getE2(), V.x, 1e-4f);\n\tauto yy = V.yy;\n\tBOOST_CHECK_CLOSE(yy.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yy.getE2(), V.y, 1e-4f);\n\tauto yz = V.yz;\n\tBOOST_CHECK_CLOSE(yz.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yz.getE2(), V.z, 1e-4f);\n\tauto yw = V.yw;\n\tBOOST_CHECK_CLOSE(yw.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yw.getE2(), V.w, 1e-4f);\n\tauto zx = V.zx;\n\tBOOST_CHECK_CLOSE(zx.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zx.getE2(), V.x, 1e-4f);\n\tauto zy = V.zy;\n\tBOOST_CHECK_CLOSE(zy.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zy.getE2(), V.y, 1e-4f);\n\tauto zz = V.zz;\n\tBOOST_CHECK_CLOSE(zz.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zz.getE2(), V.z, 1e-4f);\n\tauto zw = V.zw;\n\tBOOST_CHECK_CLOSE(zw.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zw.getE2(), V.w, 1e-4f);\n\tauto wx = V.wx;\n\tBOOST_CHECK_CLOSE(wx.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wx.getE2(), V.x, 1e-4f);\n\tauto wy = V.wy;\n\tBOOST_CHECK_CLOSE(wy.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wy.getE2(), V.y, 1e-4f);\n\tauto wz = V.wz;\n\tBOOST_CHECK_CLOSE(wz.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wz.getE2(), V.z, 1e-4f);\n\tauto ww = V.ww;\n\tBOOST_CHECK_CLOSE(ww.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(ww.getE2(), V.w, 1e-4f);\n\t// 3d swizzles <x, y, z, w>\n\tauto xxx = V.xxx;\n\tBOOST_CHECK_CLOSE(xxx.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxx.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxx.getE3(), V.x, 1e-4f);\n\tauto xxy = V.xxy;\n\tBOOST_CHECK_CLOSE(xxy.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxy.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxy.getE3(), V.y, 1e-4f);\n\tauto xxz = V.xxz;\n\tBOOST_CHECK_CLOSE(xxz.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxz.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxz.getE3(), V.z, 1e-4f);\n\tauto xxw = V.xxw;\n\tBOOST_CHECK_CLOSE(xxw.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxw.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxw.getE3(), V.w, 1e-4f);\n\tauto xyx = V.xyx;\n\tBOOST_CHECK_CLOSE(xyx.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyx.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyx.getE3(), V.x, 1e-4f);\n\tauto xyy = V.xyy;\n\tBOOST_CHECK_CLOSE(xyy.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyy.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyy.getE3(), V.y, 1e-4f);\n\tauto xyz = V.xyz;\n\tBOOST_CHECK_CLOSE(xyz.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyz.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyz.getE3(), V.z, 1e-4f);\n\tauto xyw = V.xyw;\n\tBOOST_CHECK_CLOSE(xyw.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyw.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyw.getE3(), V.w, 1e-4f);\n\tauto xzx = V.xzx;\n\tBOOST_CHECK_CLOSE(xzx.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzx.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzx.getE3(), V.x, 1e-4f);\n\tauto xzy = V.xzy;\n\tBOOST_CHECK_CLOSE(xzy.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzy.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzy.getE3(), V.y, 1e-4f);\n\tauto xzz = V.xzz;\n\tBOOST_CHECK_CLOSE(xzz.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzz.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzz.getE3(), V.z, 1e-4f);\n\tauto xzw = V.xzw;\n\tBOOST_CHECK_CLOSE(xzw.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzw.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzw.getE3(), V.w, 1e-4f);\n\tauto xwx = V.xwx;\n\tBOOST_CHECK_CLOSE(xwx.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xwx.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(xwx.getE3(), V.x, 1e-4f);\n\tauto xwy = V.xwy;\n\tBOOST_CHECK_CLOSE(xwy.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xwy.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(xwy.getE3(), V.y, 1e-4f);\n\tauto xwz = V.xwz;\n\tBOOST_CHECK_CLOSE(xwz.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xwz.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(xwz.getE3(), V.z, 1e-4f);\n\tauto xww = V.xww;\n\tBOOST_CHECK_CLOSE(xww.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xww.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(xww.getE3(), V.w, 1e-4f);\n\tauto yxx = V.yxx;\n\tBOOST_CHECK_CLOSE(yxx.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxx.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxx.getE3(), V.x, 1e-4f);\n\tauto yxy = V.yxy;\n\tBOOST_CHECK_CLOSE(yxy.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxy.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxy.getE3(), V.y, 1e-4f);\n\tauto yxz = V.yxz;\n\tBOOST_CHECK_CLOSE(yxz.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxz.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxz.getE3(), V.z, 1e-4f);\n\tauto yxw = V.yxw;\n\tBOOST_CHECK_CLOSE(yxw.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxw.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxw.getE3(), V.w, 1e-4f);\n\tauto yyx = V.yyx;\n\tBOOST_CHECK_CLOSE(yyx.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyx.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyx.getE3(), V.x, 1e-4f);\n\tauto yyy = V.yyy;\n\tBOOST_CHECK_CLOSE(yyy.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyy.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyy.getE3(), V.y, 1e-4f);\n\tauto yyz = V.yyz;\n\tBOOST_CHECK_CLOSE(yyz.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyz.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyz.getE3(), V.z, 1e-4f);\n\tauto yyw = V.yyw;\n\tBOOST_CHECK_CLOSE(yyw.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyw.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyw.getE3(), V.w, 1e-4f);\n\tauto yzx = V.yzx;\n\tBOOST_CHECK_CLOSE(yzx.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzx.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzx.getE3(), V.x, 1e-4f);\n\tauto yzy = V.yzy;\n\tBOOST_CHECK_CLOSE(yzy.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzy.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzy.getE3(), V.y, 1e-4f);\n\tauto yzz = V.yzz;\n\tBOOST_CHECK_CLOSE(yzz.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzz.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzz.getE3(), V.z, 1e-4f);\n\tauto yzw = V.yzw;\n\tBOOST_CHECK_CLOSE(yzw.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzw.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzw.getE3(), V.w, 1e-4f);\n\tauto ywx = V.ywx;\n\tBOOST_CHECK_CLOSE(ywx.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(ywx.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(ywx.getE3(), V.x, 1e-4f);\n\tauto ywy = V.ywy;\n\tBOOST_CHECK_CLOSE(ywy.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(ywy.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(ywy.getE3(), V.y, 1e-4f);\n\tauto ywz = V.ywz;\n\tBOOST_CHECK_CLOSE(ywz.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(ywz.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(ywz.getE3(), V.z, 1e-4f);\n\tauto yww = V.yww;\n\tBOOST_CHECK_CLOSE(yww.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yww.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(yww.getE3(), V.w, 1e-4f);\n\tauto zxx = V.zxx;\n\tBOOST_CHECK_CLOSE(zxx.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxx.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxx.getE3(), V.x, 1e-4f);\n\tauto zxy = V.zxy;\n\tBOOST_CHECK_CLOSE(zxy.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxy.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxy.getE3(), V.y, 1e-4f);\n\tauto zxz = V.zxz;\n\tBOOST_CHECK_CLOSE(zxz.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxz.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxz.getE3(), V.z, 1e-4f);\n\tauto zxw = V.zxw;\n\tBOOST_CHECK_CLOSE(zxw.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxw.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxw.getE3(), V.w, 1e-4f);\n\tauto zyx = V.zyx;\n\tBOOST_CHECK_CLOSE(zyx.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyx.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyx.getE3(), V.x, 1e-4f);\n\tauto zyy = V.zyy;\n\tBOOST_CHECK_CLOSE(zyy.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyy.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyy.getE3(), V.y, 1e-4f);\n\tauto zyz = V.zyz;\n\tBOOST_CHECK_CLOSE(zyz.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyz.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyz.getE3(), V.z, 1e-4f);\n\tauto zyw = V.zyw;\n\tBOOST_CHECK_CLOSE(zyw.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyw.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyw.getE3(), V.w, 1e-4f);\n\tauto zzx = V.zzx;\n\tBOOST_CHECK_CLOSE(zzx.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzx.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzx.getE3(), V.x, 1e-4f);\n\tauto zzy = V.zzy;\n\tBOOST_CHECK_CLOSE(zzy.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzy.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzy.getE3(), V.y, 1e-4f);\n\tauto zzz = V.zzz;\n\tBOOST_CHECK_CLOSE(zzz.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzz.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzz.getE3(), V.z, 1e-4f);\n\tauto zzw = V.zzw;\n\tBOOST_CHECK_CLOSE(zzw.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzw.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzw.getE3(), V.w, 1e-4f);\n\tauto zwx = V.zwx;\n\tBOOST_CHECK_CLOSE(zwx.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zwx.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(zwx.getE3(), V.x, 1e-4f);\n\tauto zwy = V.zwy;\n\tBOOST_CHECK_CLOSE(zwy.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zwy.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(zwy.getE3(), V.y, 1e-4f);\n\tauto zwz = V.zwz;\n\tBOOST_CHECK_CLOSE(zwz.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zwz.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(zwz.getE3(), V.z, 1e-4f);\n\tauto zww = V.zww;\n\tBOOST_CHECK_CLOSE(zww.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zww.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(zww.getE3(), V.w, 1e-4f);\n\tauto wxx = V.wxx;\n\tBOOST_CHECK_CLOSE(wxx.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wxx.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(wxx.getE3(), V.x, 1e-4f);\n\tauto wxy = V.wxy;\n\tBOOST_CHECK_CLOSE(wxy.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wxy.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(wxy.getE3(), V.y, 1e-4f);\n\tauto wxz = V.wxz;\n\tBOOST_CHECK_CLOSE(wxz.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wxz.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(wxz.getE3(), V.z, 1e-4f);\n\tauto wxw = V.wxw;\n\tBOOST_CHECK_CLOSE(wxw.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wxw.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(wxw.getE3(), V.w, 1e-4f);\n\tauto wyx = V.wyx;\n\tBOOST_CHECK_CLOSE(wyx.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wyx.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(wyx.getE3(), V.x, 1e-4f);\n\tauto wyy = V.wyy;\n\tBOOST_CHECK_CLOSE(wyy.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wyy.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(wyy.getE3(), V.y, 1e-4f);\n\tauto wyz = V.wyz;\n\tBOOST_CHECK_CLOSE(wyz.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wyz.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(wyz.getE3(), V.z, 1e-4f);\n\tauto wyw = V.wyw;\n\tBOOST_CHECK_CLOSE(wyw.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wyw.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(wyw.getE3(), V.w, 1e-4f);\n\tauto wzx = V.wzx;\n\tBOOST_CHECK_CLOSE(wzx.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wzx.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(wzx.getE3(), V.x, 1e-4f);\n\tauto wzy = V.wzy;\n\tBOOST_CHECK_CLOSE(wzy.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wzy.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(wzy.getE3(), V.y, 1e-4f);\n\tauto wzz = V.wzz;\n\tBOOST_CHECK_CLOSE(wzz.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wzz.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(wzz.getE3(), V.z, 1e-4f);\n\tauto wzw = V.wzw;\n\tBOOST_CHECK_CLOSE(wzw.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wzw.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(wzw.getE3(), V.w, 1e-4f);\n\tauto wwx = V.wwx;\n\tBOOST_CHECK_CLOSE(wwx.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wwx.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wwx.getE3(), V.x, 1e-4f);\n\tauto wwy = V.wwy;\n\tBOOST_CHECK_CLOSE(wwy.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wwy.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wwy.getE3(), V.y, 1e-4f);\n\tauto wwz = V.wwz;\n\tBOOST_CHECK_CLOSE(wwz.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wwz.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wwz.getE3(), V.z, 1e-4f);\n\tauto www = V.www;\n\tBOOST_CHECK_CLOSE(www.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(www.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(www.getE3(), V.w, 1e-4f);\n\t// 4d swizzles <x, y, z, w>\n\tauto xxxx = V.xxxx;\n\tBOOST_CHECK_CLOSE(xxxx.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxxx.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxxx.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxxx.getE4(), V.x, 1e-4f);\n\tauto xxxy = V.xxxy;\n\tBOOST_CHECK_CLOSE(xxxy.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxxy.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxxy.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxxy.getE4(), V.y, 1e-4f);\n\tauto xxxz = V.xxxz;\n\tBOOST_CHECK_CLOSE(xxxz.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxxz.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxxz.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxxz.getE4(), V.z, 1e-4f);\n\tauto xxxw = V.xxxw;\n\tBOOST_CHECK_CLOSE(xxxw.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxxw.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxxw.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxxw.getE4(), V.w, 1e-4f);\n\tauto xxyx = V.xxyx;\n\tBOOST_CHECK_CLOSE(xxyx.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxyx.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxyx.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxyx.getE4(), V.x, 1e-4f);\n\tauto xxyy = V.xxyy;\n\tBOOST_CHECK_CLOSE(xxyy.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxyy.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxyy.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxyy.getE4(), V.y, 1e-4f);\n\tauto xxyz = V.xxyz;\n\tBOOST_CHECK_CLOSE(xxyz.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxyz.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxyz.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxyz.getE4(), V.z, 1e-4f);\n\tauto xxyw = V.xxyw;\n\tBOOST_CHECK_CLOSE(xxyw.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxyw.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxyw.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxyw.getE4(), V.w, 1e-4f);\n\tauto xxzx = V.xxzx;\n\tBOOST_CHECK_CLOSE(xxzx.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxzx.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxzx.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxzx.getE4(), V.x, 1e-4f);\n\tauto xxzy = V.xxzy;\n\tBOOST_CHECK_CLOSE(xxzy.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxzy.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxzy.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxzy.getE4(), V.y, 1e-4f);\n\tauto xxzz = V.xxzz;\n\tBOOST_CHECK_CLOSE(xxzz.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxzz.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxzz.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxzz.getE4(), V.z, 1e-4f);\n\tauto xxzw = V.xxzw;\n\tBOOST_CHECK_CLOSE(xxzw.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxzw.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxzw.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxzw.getE4(), V.w, 1e-4f);\n\tauto xxwx = V.xxwx;\n\tBOOST_CHECK_CLOSE(xxwx.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxwx.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxwx.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxwx.getE4(), V.x, 1e-4f);\n\tauto xxwy = V.xxwy;\n\tBOOST_CHECK_CLOSE(xxwy.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxwy.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxwy.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxwy.getE4(), V.y, 1e-4f);\n\tauto xxwz = V.xxwz;\n\tBOOST_CHECK_CLOSE(xxwz.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxwz.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxwz.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxwz.getE4(), V.z, 1e-4f);\n\tauto xxww = V.xxww;\n\tBOOST_CHECK_CLOSE(xxww.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxww.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxww.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(xxww.getE4(), V.w, 1e-4f);\n\tauto xyxx = V.xyxx;\n\tBOOST_CHECK_CLOSE(xyxx.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyxx.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyxx.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyxx.getE4(), V.x, 1e-4f);\n\tauto xyxy = V.xyxy;\n\tBOOST_CHECK_CLOSE(xyxy.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyxy.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyxy.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyxy.getE4(), V.y, 1e-4f);\n\tauto xyxz = V.xyxz;\n\tBOOST_CHECK_CLOSE(xyxz.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyxz.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyxz.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyxz.getE4(), V.z, 1e-4f);\n\tauto xyxw = V.xyxw;\n\tBOOST_CHECK_CLOSE(xyxw.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyxw.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyxw.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyxw.getE4(), V.w, 1e-4f);\n\tauto xyyx = V.xyyx;\n\tBOOST_CHECK_CLOSE(xyyx.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyyx.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyyx.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyyx.getE4(), V.x, 1e-4f);\n\tauto xyyy = V.xyyy;\n\tBOOST_CHECK_CLOSE(xyyy.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyyy.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyyy.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyyy.getE4(), V.y, 1e-4f);\n\tauto xyyz = V.xyyz;\n\tBOOST_CHECK_CLOSE(xyyz.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyyz.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyyz.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyyz.getE4(), V.z, 1e-4f);\n\tauto xyyw = V.xyyw;\n\tBOOST_CHECK_CLOSE(xyyw.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyyw.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyyw.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyyw.getE4(), V.w, 1e-4f);\n\tauto xyzx = V.xyzx;\n\tBOOST_CHECK_CLOSE(xyzx.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyzx.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyzx.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyzx.getE4(), V.x, 1e-4f);\n\tauto xyzy = V.xyzy;\n\tBOOST_CHECK_CLOSE(xyzy.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyzy.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyzy.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyzy.getE4(), V.y, 1e-4f);\n\tauto xyzz = V.xyzz;\n\tBOOST_CHECK_CLOSE(xyzz.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyzz.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyzz.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyzz.getE4(), V.z, 1e-4f);\n\tauto xyzw = V.xyzw;\n\tBOOST_CHECK_CLOSE(xyzw.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyzw.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyzw.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyzw.getE4(), V.w, 1e-4f);\n\tauto xywx = V.xywx;\n\tBOOST_CHECK_CLOSE(xywx.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xywx.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(xywx.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(xywx.getE4(), V.x, 1e-4f);\n\tauto xywy = V.xywy;\n\tBOOST_CHECK_CLOSE(xywy.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xywy.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(xywy.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(xywy.getE4(), V.y, 1e-4f);\n\tauto xywz = V.xywz;\n\tBOOST_CHECK_CLOSE(xywz.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xywz.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(xywz.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(xywz.getE4(), V.z, 1e-4f);\n\tauto xyww = V.xyww;\n\tBOOST_CHECK_CLOSE(xyww.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyww.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyww.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(xyww.getE4(), V.w, 1e-4f);\n\tauto xzxx = V.xzxx;\n\tBOOST_CHECK_CLOSE(xzxx.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzxx.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzxx.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzxx.getE4(), V.x, 1e-4f);\n\tauto xzxy = V.xzxy;\n\tBOOST_CHECK_CLOSE(xzxy.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzxy.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzxy.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzxy.getE4(), V.y, 1e-4f);\n\tauto xzxz = V.xzxz;\n\tBOOST_CHECK_CLOSE(xzxz.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzxz.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzxz.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzxz.getE4(), V.z, 1e-4f);\n\tauto xzxw = V.xzxw;\n\tBOOST_CHECK_CLOSE(xzxw.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzxw.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzxw.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzxw.getE4(), V.w, 1e-4f);\n\tauto xzyx = V.xzyx;\n\tBOOST_CHECK_CLOSE(xzyx.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzyx.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzyx.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzyx.getE4(), V.x, 1e-4f);\n\tauto xzyy = V.xzyy;\n\tBOOST_CHECK_CLOSE(xzyy.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzyy.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzyy.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzyy.getE4(), V.y, 1e-4f);\n\tauto xzyz = V.xzyz;\n\tBOOST_CHECK_CLOSE(xzyz.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzyz.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzyz.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzyz.getE4(), V.z, 1e-4f);\n\tauto xzyw = V.xzyw;\n\tBOOST_CHECK_CLOSE(xzyw.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzyw.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzyw.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzyw.getE4(), V.w, 1e-4f);\n\tauto xzzx = V.xzzx;\n\tBOOST_CHECK_CLOSE(xzzx.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzzx.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzzx.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzzx.getE4(), V.x, 1e-4f);\n\tauto xzzy = V.xzzy;\n\tBOOST_CHECK_CLOSE(xzzy.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzzy.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzzy.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzzy.getE4(), V.y, 1e-4f);\n\tauto xzzz = V.xzzz;\n\tBOOST_CHECK_CLOSE(xzzz.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzzz.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzzz.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzzz.getE4(), V.z, 1e-4f);\n\tauto xzzw = V.xzzw;\n\tBOOST_CHECK_CLOSE(xzzw.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzzw.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzzw.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzzw.getE4(), V.w, 1e-4f);\n\tauto xzwx = V.xzwx;\n\tBOOST_CHECK_CLOSE(xzwx.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzwx.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzwx.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzwx.getE4(), V.x, 1e-4f);\n\tauto xzwy = V.xzwy;\n\tBOOST_CHECK_CLOSE(xzwy.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzwy.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzwy.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzwy.getE4(), V.y, 1e-4f);\n\tauto xzwz = V.xzwz;\n\tBOOST_CHECK_CLOSE(xzwz.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzwz.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzwz.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzwz.getE4(), V.z, 1e-4f);\n\tauto xzww = V.xzww;\n\tBOOST_CHECK_CLOSE(xzww.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzww.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzww.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(xzww.getE4(), V.w, 1e-4f);\n\tauto xwxx = V.xwxx;\n\tBOOST_CHECK_CLOSE(xwxx.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xwxx.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(xwxx.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xwxx.getE4(), V.x, 1e-4f);\n\tauto xwxy = V.xwxy;\n\tBOOST_CHECK_CLOSE(xwxy.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xwxy.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(xwxy.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xwxy.getE4(), V.y, 1e-4f);\n\tauto xwxz = V.xwxz;\n\tBOOST_CHECK_CLOSE(xwxz.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xwxz.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(xwxz.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xwxz.getE4(), V.z, 1e-4f);\n\tauto xwxw = V.xwxw;\n\tBOOST_CHECK_CLOSE(xwxw.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xwxw.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(xwxw.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xwxw.getE4(), V.w, 1e-4f);\n\tauto xwyx = V.xwyx;\n\tBOOST_CHECK_CLOSE(xwyx.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xwyx.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(xwyx.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(xwyx.getE4(), V.x, 1e-4f);\n\tauto xwyy = V.xwyy;\n\tBOOST_CHECK_CLOSE(xwyy.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xwyy.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(xwyy.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(xwyy.getE4(), V.y, 1e-4f);\n\tauto xwyz = V.xwyz;\n\tBOOST_CHECK_CLOSE(xwyz.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xwyz.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(xwyz.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(xwyz.getE4(), V.z, 1e-4f);\n\tauto xwyw = V.xwyw;\n\tBOOST_CHECK_CLOSE(xwyw.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xwyw.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(xwyw.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(xwyw.getE4(), V.w, 1e-4f);\n\tauto xwzx = V.xwzx;\n\tBOOST_CHECK_CLOSE(xwzx.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xwzx.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(xwzx.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(xwzx.getE4(), V.x, 1e-4f);\n\tauto xwzy = V.xwzy;\n\tBOOST_CHECK_CLOSE(xwzy.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xwzy.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(xwzy.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(xwzy.getE4(), V.y, 1e-4f);\n\tauto xwzz = V.xwzz;\n\tBOOST_CHECK_CLOSE(xwzz.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xwzz.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(xwzz.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(xwzz.getE4(), V.z, 1e-4f);\n\tauto xwzw = V.xwzw;\n\tBOOST_CHECK_CLOSE(xwzw.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xwzw.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(xwzw.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(xwzw.getE4(), V.w, 1e-4f);\n\tauto xwwx = V.xwwx;\n\tBOOST_CHECK_CLOSE(xwwx.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xwwx.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(xwwx.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(xwwx.getE4(), V.x, 1e-4f);\n\tauto xwwy = V.xwwy;\n\tBOOST_CHECK_CLOSE(xwwy.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xwwy.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(xwwy.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(xwwy.getE4(), V.y, 1e-4f);\n\tauto xwwz = V.xwwz;\n\tBOOST_CHECK_CLOSE(xwwz.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xwwz.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(xwwz.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(xwwz.getE4(), V.z, 1e-4f);\n\tauto xwww = V.xwww;\n\tBOOST_CHECK_CLOSE(xwww.getE1(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(xwww.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(xwww.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(xwww.getE4(), V.w, 1e-4f);\n\tauto yxxx = V.yxxx;\n\tBOOST_CHECK_CLOSE(yxxx.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxxx.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxxx.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxxx.getE4(), V.x, 1e-4f);\n\tauto yxxy = V.yxxy;\n\tBOOST_CHECK_CLOSE(yxxy.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxxy.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxxy.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxxy.getE4(), V.y, 1e-4f);\n\tauto yxxz = V.yxxz;\n\tBOOST_CHECK_CLOSE(yxxz.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxxz.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxxz.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxxz.getE4(), V.z, 1e-4f);\n\tauto yxxw = V.yxxw;\n\tBOOST_CHECK_CLOSE(yxxw.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxxw.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxxw.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxxw.getE4(), V.w, 1e-4f);\n\tauto yxyx = V.yxyx;\n\tBOOST_CHECK_CLOSE(yxyx.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxyx.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxyx.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxyx.getE4(), V.x, 1e-4f);\n\tauto yxyy = V.yxyy;\n\tBOOST_CHECK_CLOSE(yxyy.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxyy.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxyy.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxyy.getE4(), V.y, 1e-4f);\n\tauto yxyz = V.yxyz;\n\tBOOST_CHECK_CLOSE(yxyz.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxyz.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxyz.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxyz.getE4(), V.z, 1e-4f);\n\tauto yxyw = V.yxyw;\n\tBOOST_CHECK_CLOSE(yxyw.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxyw.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxyw.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxyw.getE4(), V.w, 1e-4f);\n\tauto yxzx = V.yxzx;\n\tBOOST_CHECK_CLOSE(yxzx.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxzx.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxzx.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxzx.getE4(), V.x, 1e-4f);\n\tauto yxzy = V.yxzy;\n\tBOOST_CHECK_CLOSE(yxzy.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxzy.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxzy.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxzy.getE4(), V.y, 1e-4f);\n\tauto yxzz = V.yxzz;\n\tBOOST_CHECK_CLOSE(yxzz.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxzz.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxzz.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxzz.getE4(), V.z, 1e-4f);\n\tauto yxzw = V.yxzw;\n\tBOOST_CHECK_CLOSE(yxzw.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxzw.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxzw.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxzw.getE4(), V.w, 1e-4f);\n\tauto yxwx = V.yxwx;\n\tBOOST_CHECK_CLOSE(yxwx.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxwx.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxwx.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxwx.getE4(), V.x, 1e-4f);\n\tauto yxwy = V.yxwy;\n\tBOOST_CHECK_CLOSE(yxwy.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxwy.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxwy.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxwy.getE4(), V.y, 1e-4f);\n\tauto yxwz = V.yxwz;\n\tBOOST_CHECK_CLOSE(yxwz.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxwz.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxwz.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxwz.getE4(), V.z, 1e-4f);\n\tauto yxww = V.yxww;\n\tBOOST_CHECK_CLOSE(yxww.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxww.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxww.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(yxww.getE4(), V.w, 1e-4f);\n\tauto yyxx = V.yyxx;\n\tBOOST_CHECK_CLOSE(yyxx.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyxx.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyxx.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyxx.getE4(), V.x, 1e-4f);\n\tauto yyxy = V.yyxy;\n\tBOOST_CHECK_CLOSE(yyxy.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyxy.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyxy.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyxy.getE4(), V.y, 1e-4f);\n\tauto yyxz = V.yyxz;\n\tBOOST_CHECK_CLOSE(yyxz.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyxz.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyxz.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyxz.getE4(), V.z, 1e-4f);\n\tauto yyxw = V.yyxw;\n\tBOOST_CHECK_CLOSE(yyxw.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyxw.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyxw.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyxw.getE4(), V.w, 1e-4f);\n\tauto yyyx = V.yyyx;\n\tBOOST_CHECK_CLOSE(yyyx.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyyx.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyyx.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyyx.getE4(), V.x, 1e-4f);\n\tauto yyyy = V.yyyy;\n\tBOOST_CHECK_CLOSE(yyyy.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyyy.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyyy.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyyy.getE4(), V.y, 1e-4f);\n\tauto yyyz = V.yyyz;\n\tBOOST_CHECK_CLOSE(yyyz.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyyz.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyyz.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyyz.getE4(), V.z, 1e-4f);\n\tauto yyyw = V.yyyw;\n\tBOOST_CHECK_CLOSE(yyyw.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyyw.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyyw.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyyw.getE4(), V.w, 1e-4f);\n\tauto yyzx = V.yyzx;\n\tBOOST_CHECK_CLOSE(yyzx.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyzx.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyzx.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyzx.getE4(), V.x, 1e-4f);\n\tauto yyzy = V.yyzy;\n\tBOOST_CHECK_CLOSE(yyzy.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyzy.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyzy.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyzy.getE4(), V.y, 1e-4f);\n\tauto yyzz = V.yyzz;\n\tBOOST_CHECK_CLOSE(yyzz.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyzz.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyzz.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyzz.getE4(), V.z, 1e-4f);\n\tauto yyzw = V.yyzw;\n\tBOOST_CHECK_CLOSE(yyzw.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyzw.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyzw.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyzw.getE4(), V.w, 1e-4f);\n\tauto yywx = V.yywx;\n\tBOOST_CHECK_CLOSE(yywx.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yywx.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yywx.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(yywx.getE4(), V.x, 1e-4f);\n\tauto yywy = V.yywy;\n\tBOOST_CHECK_CLOSE(yywy.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yywy.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yywy.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(yywy.getE4(), V.y, 1e-4f);\n\tauto yywz = V.yywz;\n\tBOOST_CHECK_CLOSE(yywz.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yywz.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yywz.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(yywz.getE4(), V.z, 1e-4f);\n\tauto yyww = V.yyww;\n\tBOOST_CHECK_CLOSE(yyww.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyww.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyww.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(yyww.getE4(), V.w, 1e-4f);\n\tauto yzxx = V.yzxx;\n\tBOOST_CHECK_CLOSE(yzxx.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzxx.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzxx.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzxx.getE4(), V.x, 1e-4f);\n\tauto yzxy = V.yzxy;\n\tBOOST_CHECK_CLOSE(yzxy.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzxy.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzxy.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzxy.getE4(), V.y, 1e-4f);\n\tauto yzxz = V.yzxz;\n\tBOOST_CHECK_CLOSE(yzxz.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzxz.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzxz.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzxz.getE4(), V.z, 1e-4f);\n\tauto yzxw = V.yzxw;\n\tBOOST_CHECK_CLOSE(yzxw.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzxw.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzxw.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzxw.getE4(), V.w, 1e-4f);\n\tauto yzyx = V.yzyx;\n\tBOOST_CHECK_CLOSE(yzyx.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzyx.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzyx.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzyx.getE4(), V.x, 1e-4f);\n\tauto yzyy = V.yzyy;\n\tBOOST_CHECK_CLOSE(yzyy.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzyy.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzyy.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzyy.getE4(), V.y, 1e-4f);\n\tauto yzyz = V.yzyz;\n\tBOOST_CHECK_CLOSE(yzyz.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzyz.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzyz.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzyz.getE4(), V.z, 1e-4f);\n\tauto yzyw = V.yzyw;\n\tBOOST_CHECK_CLOSE(yzyw.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzyw.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzyw.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzyw.getE4(), V.w, 1e-4f);\n\tauto yzzx = V.yzzx;\n\tBOOST_CHECK_CLOSE(yzzx.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzzx.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzzx.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzzx.getE4(), V.x, 1e-4f);\n\tauto yzzy = V.yzzy;\n\tBOOST_CHECK_CLOSE(yzzy.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzzy.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzzy.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzzy.getE4(), V.y, 1e-4f);\n\tauto yzzz = V.yzzz;\n\tBOOST_CHECK_CLOSE(yzzz.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzzz.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzzz.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzzz.getE4(), V.z, 1e-4f);\n\tauto yzzw = V.yzzw;\n\tBOOST_CHECK_CLOSE(yzzw.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzzw.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzzw.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzzw.getE4(), V.w, 1e-4f);\n\tauto yzwx = V.yzwx;\n\tBOOST_CHECK_CLOSE(yzwx.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzwx.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzwx.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzwx.getE4(), V.x, 1e-4f);\n\tauto yzwy = V.yzwy;\n\tBOOST_CHECK_CLOSE(yzwy.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzwy.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzwy.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzwy.getE4(), V.y, 1e-4f);\n\tauto yzwz = V.yzwz;\n\tBOOST_CHECK_CLOSE(yzwz.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzwz.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzwz.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzwz.getE4(), V.z, 1e-4f);\n\tauto yzww = V.yzww;\n\tBOOST_CHECK_CLOSE(yzww.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzww.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzww.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(yzww.getE4(), V.w, 1e-4f);\n\tauto ywxx = V.ywxx;\n\tBOOST_CHECK_CLOSE(ywxx.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(ywxx.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(ywxx.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(ywxx.getE4(), V.x, 1e-4f);\n\tauto ywxy = V.ywxy;\n\tBOOST_CHECK_CLOSE(ywxy.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(ywxy.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(ywxy.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(ywxy.getE4(), V.y, 1e-4f);\n\tauto ywxz = V.ywxz;\n\tBOOST_CHECK_CLOSE(ywxz.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(ywxz.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(ywxz.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(ywxz.getE4(), V.z, 1e-4f);\n\tauto ywxw = V.ywxw;\n\tBOOST_CHECK_CLOSE(ywxw.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(ywxw.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(ywxw.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(ywxw.getE4(), V.w, 1e-4f);\n\tauto ywyx = V.ywyx;\n\tBOOST_CHECK_CLOSE(ywyx.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(ywyx.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(ywyx.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(ywyx.getE4(), V.x, 1e-4f);\n\tauto ywyy = V.ywyy;\n\tBOOST_CHECK_CLOSE(ywyy.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(ywyy.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(ywyy.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(ywyy.getE4(), V.y, 1e-4f);\n\tauto ywyz = V.ywyz;\n\tBOOST_CHECK_CLOSE(ywyz.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(ywyz.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(ywyz.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(ywyz.getE4(), V.z, 1e-4f);\n\tauto ywyw = V.ywyw;\n\tBOOST_CHECK_CLOSE(ywyw.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(ywyw.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(ywyw.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(ywyw.getE4(), V.w, 1e-4f);\n\tauto ywzx = V.ywzx;\n\tBOOST_CHECK_CLOSE(ywzx.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(ywzx.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(ywzx.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(ywzx.getE4(), V.x, 1e-4f);\n\tauto ywzy = V.ywzy;\n\tBOOST_CHECK_CLOSE(ywzy.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(ywzy.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(ywzy.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(ywzy.getE4(), V.y, 1e-4f);\n\tauto ywzz = V.ywzz;\n\tBOOST_CHECK_CLOSE(ywzz.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(ywzz.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(ywzz.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(ywzz.getE4(), V.z, 1e-4f);\n\tauto ywzw = V.ywzw;\n\tBOOST_CHECK_CLOSE(ywzw.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(ywzw.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(ywzw.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(ywzw.getE4(), V.w, 1e-4f);\n\tauto ywwx = V.ywwx;\n\tBOOST_CHECK_CLOSE(ywwx.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(ywwx.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(ywwx.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(ywwx.getE4(), V.x, 1e-4f);\n\tauto ywwy = V.ywwy;\n\tBOOST_CHECK_CLOSE(ywwy.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(ywwy.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(ywwy.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(ywwy.getE4(), V.y, 1e-4f);\n\tauto ywwz = V.ywwz;\n\tBOOST_CHECK_CLOSE(ywwz.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(ywwz.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(ywwz.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(ywwz.getE4(), V.z, 1e-4f);\n\tauto ywww = V.ywww;\n\tBOOST_CHECK_CLOSE(ywww.getE1(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(ywww.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(ywww.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(ywww.getE4(), V.w, 1e-4f);\n\tauto zxxx = V.zxxx;\n\tBOOST_CHECK_CLOSE(zxxx.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxxx.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxxx.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxxx.getE4(), V.x, 1e-4f);\n\tauto zxxy = V.zxxy;\n\tBOOST_CHECK_CLOSE(zxxy.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxxy.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxxy.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxxy.getE4(), V.y, 1e-4f);\n\tauto zxxz = V.zxxz;\n\tBOOST_CHECK_CLOSE(zxxz.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxxz.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxxz.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxxz.getE4(), V.z, 1e-4f);\n\tauto zxxw = V.zxxw;\n\tBOOST_CHECK_CLOSE(zxxw.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxxw.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxxw.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxxw.getE4(), V.w, 1e-4f);\n\tauto zxyx = V.zxyx;\n\tBOOST_CHECK_CLOSE(zxyx.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxyx.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxyx.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxyx.getE4(), V.x, 1e-4f);\n\tauto zxyy = V.zxyy;\n\tBOOST_CHECK_CLOSE(zxyy.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxyy.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxyy.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxyy.getE4(), V.y, 1e-4f);\n\tauto zxyz = V.zxyz;\n\tBOOST_CHECK_CLOSE(zxyz.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxyz.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxyz.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxyz.getE4(), V.z, 1e-4f);\n\tauto zxyw = V.zxyw;\n\tBOOST_CHECK_CLOSE(zxyw.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxyw.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxyw.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxyw.getE4(), V.w, 1e-4f);\n\tauto zxzx = V.zxzx;\n\tBOOST_CHECK_CLOSE(zxzx.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxzx.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxzx.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxzx.getE4(), V.x, 1e-4f);\n\tauto zxzy = V.zxzy;\n\tBOOST_CHECK_CLOSE(zxzy.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxzy.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxzy.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxzy.getE4(), V.y, 1e-4f);\n\tauto zxzz = V.zxzz;\n\tBOOST_CHECK_CLOSE(zxzz.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxzz.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxzz.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxzz.getE4(), V.z, 1e-4f);\n\tauto zxzw = V.zxzw;\n\tBOOST_CHECK_CLOSE(zxzw.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxzw.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxzw.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxzw.getE4(), V.w, 1e-4f);\n\tauto zxwx = V.zxwx;\n\tBOOST_CHECK_CLOSE(zxwx.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxwx.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxwx.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxwx.getE4(), V.x, 1e-4f);\n\tauto zxwy = V.zxwy;\n\tBOOST_CHECK_CLOSE(zxwy.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxwy.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxwy.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxwy.getE4(), V.y, 1e-4f);\n\tauto zxwz = V.zxwz;\n\tBOOST_CHECK_CLOSE(zxwz.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxwz.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxwz.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxwz.getE4(), V.z, 1e-4f);\n\tauto zxww = V.zxww;\n\tBOOST_CHECK_CLOSE(zxww.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxww.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxww.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(zxww.getE4(), V.w, 1e-4f);\n\tauto zyxx = V.zyxx;\n\tBOOST_CHECK_CLOSE(zyxx.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyxx.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyxx.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyxx.getE4(), V.x, 1e-4f);\n\tauto zyxy = V.zyxy;\n\tBOOST_CHECK_CLOSE(zyxy.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyxy.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyxy.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyxy.getE4(), V.y, 1e-4f);\n\tauto zyxz = V.zyxz;\n\tBOOST_CHECK_CLOSE(zyxz.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyxz.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyxz.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyxz.getE4(), V.z, 1e-4f);\n\tauto zyxw = V.zyxw;\n\tBOOST_CHECK_CLOSE(zyxw.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyxw.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyxw.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyxw.getE4(), V.w, 1e-4f);\n\tauto zyyx = V.zyyx;\n\tBOOST_CHECK_CLOSE(zyyx.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyyx.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyyx.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyyx.getE4(), V.x, 1e-4f);\n\tauto zyyy = V.zyyy;\n\tBOOST_CHECK_CLOSE(zyyy.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyyy.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyyy.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyyy.getE4(), V.y, 1e-4f);\n\tauto zyyz = V.zyyz;\n\tBOOST_CHECK_CLOSE(zyyz.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyyz.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyyz.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyyz.getE4(), V.z, 1e-4f);\n\tauto zyyw = V.zyyw;\n\tBOOST_CHECK_CLOSE(zyyw.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyyw.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyyw.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyyw.getE4(), V.w, 1e-4f);\n\tauto zyzx = V.zyzx;\n\tBOOST_CHECK_CLOSE(zyzx.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyzx.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyzx.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyzx.getE4(), V.x, 1e-4f);\n\tauto zyzy = V.zyzy;\n\tBOOST_CHECK_CLOSE(zyzy.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyzy.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyzy.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyzy.getE4(), V.y, 1e-4f);\n\tauto zyzz = V.zyzz;\n\tBOOST_CHECK_CLOSE(zyzz.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyzz.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyzz.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyzz.getE4(), V.z, 1e-4f);\n\tauto zyzw = V.zyzw;\n\tBOOST_CHECK_CLOSE(zyzw.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyzw.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyzw.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyzw.getE4(), V.w, 1e-4f);\n\tauto zywx = V.zywx;\n\tBOOST_CHECK_CLOSE(zywx.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zywx.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(zywx.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(zywx.getE4(), V.x, 1e-4f);\n\tauto zywy = V.zywy;\n\tBOOST_CHECK_CLOSE(zywy.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zywy.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(zywy.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(zywy.getE4(), V.y, 1e-4f);\n\tauto zywz = V.zywz;\n\tBOOST_CHECK_CLOSE(zywz.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zywz.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(zywz.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(zywz.getE4(), V.z, 1e-4f);\n\tauto zyww = V.zyww;\n\tBOOST_CHECK_CLOSE(zyww.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyww.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyww.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(zyww.getE4(), V.w, 1e-4f);\n\tauto zzxx = V.zzxx;\n\tBOOST_CHECK_CLOSE(zzxx.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzxx.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzxx.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzxx.getE4(), V.x, 1e-4f);\n\tauto zzxy = V.zzxy;\n\tBOOST_CHECK_CLOSE(zzxy.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzxy.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzxy.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzxy.getE4(), V.y, 1e-4f);\n\tauto zzxz = V.zzxz;\n\tBOOST_CHECK_CLOSE(zzxz.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzxz.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzxz.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzxz.getE4(), V.z, 1e-4f);\n\tauto zzxw = V.zzxw;\n\tBOOST_CHECK_CLOSE(zzxw.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzxw.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzxw.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzxw.getE4(), V.w, 1e-4f);\n\tauto zzyx = V.zzyx;\n\tBOOST_CHECK_CLOSE(zzyx.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzyx.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzyx.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzyx.getE4(), V.x, 1e-4f);\n\tauto zzyy = V.zzyy;\n\tBOOST_CHECK_CLOSE(zzyy.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzyy.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzyy.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzyy.getE4(), V.y, 1e-4f);\n\tauto zzyz = V.zzyz;\n\tBOOST_CHECK_CLOSE(zzyz.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzyz.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzyz.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzyz.getE4(), V.z, 1e-4f);\n\tauto zzyw = V.zzyw;\n\tBOOST_CHECK_CLOSE(zzyw.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzyw.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzyw.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzyw.getE4(), V.w, 1e-4f);\n\tauto zzzx = V.zzzx;\n\tBOOST_CHECK_CLOSE(zzzx.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzzx.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzzx.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzzx.getE4(), V.x, 1e-4f);\n\tauto zzzy = V.zzzy;\n\tBOOST_CHECK_CLOSE(zzzy.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzzy.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzzy.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzzy.getE4(), V.y, 1e-4f);\n\tauto zzzz = V.zzzz;\n\tBOOST_CHECK_CLOSE(zzzz.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzzz.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzzz.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzzz.getE4(), V.z, 1e-4f);\n\tauto zzzw = V.zzzw;\n\tBOOST_CHECK_CLOSE(zzzw.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzzw.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzzw.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzzw.getE4(), V.w, 1e-4f);\n\tauto zzwx = V.zzwx;\n\tBOOST_CHECK_CLOSE(zzwx.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzwx.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzwx.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzwx.getE4(), V.x, 1e-4f);\n\tauto zzwy = V.zzwy;\n\tBOOST_CHECK_CLOSE(zzwy.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzwy.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzwy.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzwy.getE4(), V.y, 1e-4f);\n\tauto zzwz = V.zzwz;\n\tBOOST_CHECK_CLOSE(zzwz.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzwz.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzwz.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzwz.getE4(), V.z, 1e-4f);\n\tauto zzww = V.zzww;\n\tBOOST_CHECK_CLOSE(zzww.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzww.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzww.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(zzww.getE4(), V.w, 1e-4f);\n\tauto zwxx = V.zwxx;\n\tBOOST_CHECK_CLOSE(zwxx.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zwxx.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(zwxx.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(zwxx.getE4(), V.x, 1e-4f);\n\tauto zwxy = V.zwxy;\n\tBOOST_CHECK_CLOSE(zwxy.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zwxy.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(zwxy.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(zwxy.getE4(), V.y, 1e-4f);\n\tauto zwxz = V.zwxz;\n\tBOOST_CHECK_CLOSE(zwxz.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zwxz.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(zwxz.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(zwxz.getE4(), V.z, 1e-4f);\n\tauto zwxw = V.zwxw;\n\tBOOST_CHECK_CLOSE(zwxw.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zwxw.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(zwxw.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(zwxw.getE4(), V.w, 1e-4f);\n\tauto zwyx = V.zwyx;\n\tBOOST_CHECK_CLOSE(zwyx.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zwyx.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(zwyx.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(zwyx.getE4(), V.x, 1e-4f);\n\tauto zwyy = V.zwyy;\n\tBOOST_CHECK_CLOSE(zwyy.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zwyy.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(zwyy.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(zwyy.getE4(), V.y, 1e-4f);\n\tauto zwyz = V.zwyz;\n\tBOOST_CHECK_CLOSE(zwyz.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zwyz.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(zwyz.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(zwyz.getE4(), V.z, 1e-4f);\n\tauto zwyw = V.zwyw;\n\tBOOST_CHECK_CLOSE(zwyw.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zwyw.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(zwyw.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(zwyw.getE4(), V.w, 1e-4f);\n\tauto zwzx = V.zwzx;\n\tBOOST_CHECK_CLOSE(zwzx.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zwzx.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(zwzx.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zwzx.getE4(), V.x, 1e-4f);\n\tauto zwzy = V.zwzy;\n\tBOOST_CHECK_CLOSE(zwzy.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zwzy.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(zwzy.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zwzy.getE4(), V.y, 1e-4f);\n\tauto zwzz = V.zwzz;\n\tBOOST_CHECK_CLOSE(zwzz.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zwzz.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(zwzz.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zwzz.getE4(), V.z, 1e-4f);\n\tauto zwzw = V.zwzw;\n\tBOOST_CHECK_CLOSE(zwzw.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zwzw.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(zwzw.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zwzw.getE4(), V.w, 1e-4f);\n\tauto zwwx = V.zwwx;\n\tBOOST_CHECK_CLOSE(zwwx.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zwwx.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(zwwx.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(zwwx.getE4(), V.x, 1e-4f);\n\tauto zwwy = V.zwwy;\n\tBOOST_CHECK_CLOSE(zwwy.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zwwy.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(zwwy.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(zwwy.getE4(), V.y, 1e-4f);\n\tauto zwwz = V.zwwz;\n\tBOOST_CHECK_CLOSE(zwwz.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zwwz.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(zwwz.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(zwwz.getE4(), V.z, 1e-4f);\n\tauto zwww = V.zwww;\n\tBOOST_CHECK_CLOSE(zwww.getE1(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(zwww.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(zwww.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(zwww.getE4(), V.w, 1e-4f);\n\tauto wxxx = V.wxxx;\n\tBOOST_CHECK_CLOSE(wxxx.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wxxx.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(wxxx.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(wxxx.getE4(), V.x, 1e-4f);\n\tauto wxxy = V.wxxy;\n\tBOOST_CHECK_CLOSE(wxxy.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wxxy.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(wxxy.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(wxxy.getE4(), V.y, 1e-4f);\n\tauto wxxz = V.wxxz;\n\tBOOST_CHECK_CLOSE(wxxz.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wxxz.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(wxxz.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(wxxz.getE4(), V.z, 1e-4f);\n\tauto wxxw = V.wxxw;\n\tBOOST_CHECK_CLOSE(wxxw.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wxxw.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(wxxw.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(wxxw.getE4(), V.w, 1e-4f);\n\tauto wxyx = V.wxyx;\n\tBOOST_CHECK_CLOSE(wxyx.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wxyx.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(wxyx.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(wxyx.getE4(), V.x, 1e-4f);\n\tauto wxyy = V.wxyy;\n\tBOOST_CHECK_CLOSE(wxyy.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wxyy.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(wxyy.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(wxyy.getE4(), V.y, 1e-4f);\n\tauto wxyz = V.wxyz;\n\tBOOST_CHECK_CLOSE(wxyz.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wxyz.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(wxyz.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(wxyz.getE4(), V.z, 1e-4f);\n\tauto wxyw = V.wxyw;\n\tBOOST_CHECK_CLOSE(wxyw.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wxyw.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(wxyw.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(wxyw.getE4(), V.w, 1e-4f);\n\tauto wxzx = V.wxzx;\n\tBOOST_CHECK_CLOSE(wxzx.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wxzx.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(wxzx.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(wxzx.getE4(), V.x, 1e-4f);\n\tauto wxzy = V.wxzy;\n\tBOOST_CHECK_CLOSE(wxzy.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wxzy.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(wxzy.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(wxzy.getE4(), V.y, 1e-4f);\n\tauto wxzz = V.wxzz;\n\tBOOST_CHECK_CLOSE(wxzz.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wxzz.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(wxzz.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(wxzz.getE4(), V.z, 1e-4f);\n\tauto wxzw = V.wxzw;\n\tBOOST_CHECK_CLOSE(wxzw.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wxzw.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(wxzw.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(wxzw.getE4(), V.w, 1e-4f);\n\tauto wxwx = V.wxwx;\n\tBOOST_CHECK_CLOSE(wxwx.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wxwx.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(wxwx.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wxwx.getE4(), V.x, 1e-4f);\n\tauto wxwy = V.wxwy;\n\tBOOST_CHECK_CLOSE(wxwy.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wxwy.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(wxwy.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wxwy.getE4(), V.y, 1e-4f);\n\tauto wxwz = V.wxwz;\n\tBOOST_CHECK_CLOSE(wxwz.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wxwz.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(wxwz.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wxwz.getE4(), V.z, 1e-4f);\n\tauto wxww = V.wxww;\n\tBOOST_CHECK_CLOSE(wxww.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wxww.getE2(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(wxww.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wxww.getE4(), V.w, 1e-4f);\n\tauto wyxx = V.wyxx;\n\tBOOST_CHECK_CLOSE(wyxx.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wyxx.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(wyxx.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(wyxx.getE4(), V.x, 1e-4f);\n\tauto wyxy = V.wyxy;\n\tBOOST_CHECK_CLOSE(wyxy.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wyxy.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(wyxy.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(wyxy.getE4(), V.y, 1e-4f);\n\tauto wyxz = V.wyxz;\n\tBOOST_CHECK_CLOSE(wyxz.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wyxz.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(wyxz.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(wyxz.getE4(), V.z, 1e-4f);\n\tauto wyxw = V.wyxw;\n\tBOOST_CHECK_CLOSE(wyxw.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wyxw.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(wyxw.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(wyxw.getE4(), V.w, 1e-4f);\n\tauto wyyx = V.wyyx;\n\tBOOST_CHECK_CLOSE(wyyx.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wyyx.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(wyyx.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(wyyx.getE4(), V.x, 1e-4f);\n\tauto wyyy = V.wyyy;\n\tBOOST_CHECK_CLOSE(wyyy.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wyyy.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(wyyy.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(wyyy.getE4(), V.y, 1e-4f);\n\tauto wyyz = V.wyyz;\n\tBOOST_CHECK_CLOSE(wyyz.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wyyz.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(wyyz.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(wyyz.getE4(), V.z, 1e-4f);\n\tauto wyyw = V.wyyw;\n\tBOOST_CHECK_CLOSE(wyyw.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wyyw.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(wyyw.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(wyyw.getE4(), V.w, 1e-4f);\n\tauto wyzx = V.wyzx;\n\tBOOST_CHECK_CLOSE(wyzx.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wyzx.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(wyzx.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(wyzx.getE4(), V.x, 1e-4f);\n\tauto wyzy = V.wyzy;\n\tBOOST_CHECK_CLOSE(wyzy.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wyzy.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(wyzy.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(wyzy.getE4(), V.y, 1e-4f);\n\tauto wyzz = V.wyzz;\n\tBOOST_CHECK_CLOSE(wyzz.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wyzz.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(wyzz.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(wyzz.getE4(), V.z, 1e-4f);\n\tauto wyzw = V.wyzw;\n\tBOOST_CHECK_CLOSE(wyzw.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wyzw.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(wyzw.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(wyzw.getE4(), V.w, 1e-4f);\n\tauto wywx = V.wywx;\n\tBOOST_CHECK_CLOSE(wywx.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wywx.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(wywx.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wywx.getE4(), V.x, 1e-4f);\n\tauto wywy = V.wywy;\n\tBOOST_CHECK_CLOSE(wywy.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wywy.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(wywy.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wywy.getE4(), V.y, 1e-4f);\n\tauto wywz = V.wywz;\n\tBOOST_CHECK_CLOSE(wywz.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wywz.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(wywz.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wywz.getE4(), V.z, 1e-4f);\n\tauto wyww = V.wyww;\n\tBOOST_CHECK_CLOSE(wyww.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wyww.getE2(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(wyww.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wyww.getE4(), V.w, 1e-4f);\n\tauto wzxx = V.wzxx;\n\tBOOST_CHECK_CLOSE(wzxx.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wzxx.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(wzxx.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(wzxx.getE4(), V.x, 1e-4f);\n\tauto wzxy = V.wzxy;\n\tBOOST_CHECK_CLOSE(wzxy.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wzxy.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(wzxy.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(wzxy.getE4(), V.y, 1e-4f);\n\tauto wzxz = V.wzxz;\n\tBOOST_CHECK_CLOSE(wzxz.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wzxz.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(wzxz.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(wzxz.getE4(), V.z, 1e-4f);\n\tauto wzxw = V.wzxw;\n\tBOOST_CHECK_CLOSE(wzxw.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wzxw.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(wzxw.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(wzxw.getE4(), V.w, 1e-4f);\n\tauto wzyx = V.wzyx;\n\tBOOST_CHECK_CLOSE(wzyx.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wzyx.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(wzyx.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(wzyx.getE4(), V.x, 1e-4f);\n\tauto wzyy = V.wzyy;\n\tBOOST_CHECK_CLOSE(wzyy.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wzyy.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(wzyy.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(wzyy.getE4(), V.y, 1e-4f);\n\tauto wzyz = V.wzyz;\n\tBOOST_CHECK_CLOSE(wzyz.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wzyz.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(wzyz.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(wzyz.getE4(), V.z, 1e-4f);\n\tauto wzyw = V.wzyw;\n\tBOOST_CHECK_CLOSE(wzyw.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wzyw.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(wzyw.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(wzyw.getE4(), V.w, 1e-4f);\n\tauto wzzx = V.wzzx;\n\tBOOST_CHECK_CLOSE(wzzx.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wzzx.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(wzzx.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(wzzx.getE4(), V.x, 1e-4f);\n\tauto wzzy = V.wzzy;\n\tBOOST_CHECK_CLOSE(wzzy.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wzzy.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(wzzy.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(wzzy.getE4(), V.y, 1e-4f);\n\tauto wzzz = V.wzzz;\n\tBOOST_CHECK_CLOSE(wzzz.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wzzz.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(wzzz.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(wzzz.getE4(), V.z, 1e-4f);\n\tauto wzzw = V.wzzw;\n\tBOOST_CHECK_CLOSE(wzzw.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wzzw.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(wzzw.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(wzzw.getE4(), V.w, 1e-4f);\n\tauto wzwx = V.wzwx;\n\tBOOST_CHECK_CLOSE(wzwx.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wzwx.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(wzwx.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wzwx.getE4(), V.x, 1e-4f);\n\tauto wzwy = V.wzwy;\n\tBOOST_CHECK_CLOSE(wzwy.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wzwy.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(wzwy.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wzwy.getE4(), V.y, 1e-4f);\n\tauto wzwz = V.wzwz;\n\tBOOST_CHECK_CLOSE(wzwz.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wzwz.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(wzwz.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wzwz.getE4(), V.z, 1e-4f);\n\tauto wzww = V.wzww;\n\tBOOST_CHECK_CLOSE(wzww.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wzww.getE2(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(wzww.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wzww.getE4(), V.w, 1e-4f);\n\tauto wwxx = V.wwxx;\n\tBOOST_CHECK_CLOSE(wwxx.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wwxx.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wwxx.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(wwxx.getE4(), V.x, 1e-4f);\n\tauto wwxy = V.wwxy;\n\tBOOST_CHECK_CLOSE(wwxy.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wwxy.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wwxy.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(wwxy.getE4(), V.y, 1e-4f);\n\tauto wwxz = V.wwxz;\n\tBOOST_CHECK_CLOSE(wwxz.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wwxz.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wwxz.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(wwxz.getE4(), V.z, 1e-4f);\n\tauto wwxw = V.wwxw;\n\tBOOST_CHECK_CLOSE(wwxw.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wwxw.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wwxw.getE3(), V.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(wwxw.getE4(), V.w, 1e-4f);\n\tauto wwyx = V.wwyx;\n\tBOOST_CHECK_CLOSE(wwyx.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wwyx.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wwyx.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(wwyx.getE4(), V.x, 1e-4f);\n\tauto wwyy = V.wwyy;\n\tBOOST_CHECK_CLOSE(wwyy.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wwyy.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wwyy.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(wwyy.getE4(), V.y, 1e-4f);\n\tauto wwyz = V.wwyz;\n\tBOOST_CHECK_CLOSE(wwyz.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wwyz.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wwyz.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(wwyz.getE4(), V.z, 1e-4f);\n\tauto wwyw = V.wwyw;\n\tBOOST_CHECK_CLOSE(wwyw.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wwyw.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wwyw.getE3(), V.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(wwyw.getE4(), V.w, 1e-4f);\n\tauto wwzx = V.wwzx;\n\tBOOST_CHECK_CLOSE(wwzx.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wwzx.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wwzx.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(wwzx.getE4(), V.x, 1e-4f);\n\tauto wwzy = V.wwzy;\n\tBOOST_CHECK_CLOSE(wwzy.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wwzy.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wwzy.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(wwzy.getE4(), V.y, 1e-4f);\n\tauto wwzz = V.wwzz;\n\tBOOST_CHECK_CLOSE(wwzz.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wwzz.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wwzz.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(wwzz.getE4(), V.z, 1e-4f);\n\tauto wwzw = V.wwzw;\n\tBOOST_CHECK_CLOSE(wwzw.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wwzw.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wwzw.getE3(), V.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(wwzw.getE4(), V.w, 1e-4f);\n\tauto wwwx = V.wwwx;\n\tBOOST_CHECK_CLOSE(wwwx.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wwwx.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wwwx.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wwwx.getE4(), V.x, 1e-4f);\n\tauto wwwy = V.wwwy;\n\tBOOST_CHECK_CLOSE(wwwy.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wwwy.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wwwy.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wwwy.getE4(), V.y, 1e-4f);\n\tauto wwwz = V.wwwz;\n\tBOOST_CHECK_CLOSE(wwwz.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wwwz.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wwwz.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wwwz.getE4(), V.z, 1e-4f);\n\tauto wwww = V.wwww;\n\tBOOST_CHECK_CLOSE(wwww.getE1(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wwww.getE2(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wwww.getE3(), V.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(wwww.getE4(), V.w, 1e-4f);\n}\n\nBOOST_AUTO_TEST_CASE(assign_op) {\n\tvmath::core::Vector<float, 2> V2;\n\tV2.x = 20.12f;\n\tV2.y = 100.89f;\n\tvmath::core::Vector<float, 3> V3;\n\tV3.x = 20.12f;\n\tV3.y = 100.89f;\n\tV3.z = -18.2f;\n\tvmath::core::Vector<float, 4> V4;\n\tV4.x = 20.12f;\n\tV4.y = 100.89f;\n\tV4.z = -18.2f;\n\tV4.w = 35.62f;\n\tvmath::core::Vector<float, 4> V;\n\tV.x = 0.0f;\n\tV.y = 0.0f;\n\tV.z = 0.0f;\n\tV.w = 0.0f;\n\t// 2d swizzle assign <x, y, z, w> from vector\n\tV.xy = V2;\n\tBOOST_CHECK_CLOSE(V.x, V2.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.y, V2.y, 1e-4f);\n\tBOOST_CHECK_SMALL(V.z, 1e-7f);\n\tBOOST_CHECK_SMALL(V.w, 1e-7f);\n\tV.wz = V2;\n\tBOOST_CHECK_CLOSE(V.x, V2.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.y, V2.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.z, V2.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.w, V2.x, 1e-4f);\n\tV.yw = V2;\n\tBOOST_CHECK_CLOSE(V.x, V2.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.y, V2.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.z, V2.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.w, V2.y, 1e-4f);\n\t// 2d swizzle assign <x, y, z, w> from swizzle\n\tV.xy = V2.yy;\n\tBOOST_CHECK_CLOSE(V.x, V2.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.y, V2.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.z, V2.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.w, V2.y, 1e-4f);\n\tV.yz = V2.xy;\n\tBOOST_CHECK_CLOSE(V.x, V2.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.y, V2.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.z, V2.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.w, V2.y, 1e-4f);\n\tV.zw = V2.xx;\n\tBOOST_CHECK_CLOSE(V.x, V2.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.y, V2.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.z, V2.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.w, V2.x, 1e-4f);\n\t// 3d swizzle assign <x, y, z, w> from vector\n\tV.xyz = V3;\n\tBOOST_CHECK_CLOSE(V.x, V3.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.y, V3.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.z, V3.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.w, V2.x, 1e-4f);\n\tV.zxw = V3;\n\tBOOST_CHECK_CLOSE(V.x, V3.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.y, V3.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.z, V3.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.w, V3.z, 1e-4f);\n\tV.wxy = V3;\n\tBOOST_CHECK_CLOSE(V.x, V3.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.y, V3.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.z, V3.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.w, V3.x, 1e-4f);\n\t// 3d swizzle assign <x, y, z, w> from swizzle\n\tV.xyz = V3.xyz;\n\tBOOST_CHECK_CLOSE(V.x, V3.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.y, V3.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.z, V3.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.w, V3.x, 1e-4f);\n\tV.zxw = V3.zzz;\n\tBOOST_CHECK_CLOSE(V.x, V3.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.y, V3.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.z, V3.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.w, V3.z, 1e-4f);\n\tV.wxy = V3.yyx;\n\tBOOST_CHECK_CLOSE(V.x, V3.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.y, V3.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.z, V3.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.w, V3.y, 1e-4f);\n\t// 4d swizzle assign <x, y, z, w> from vector\n\tV.xzyw = V4;\n\tBOOST_CHECK_CLOSE(V.x, V4.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.y, V4.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.z, V4.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.w, V4.w, 1e-4f);\n\tV.yxzw = V4;\n\tBOOST_CHECK_CLOSE(V.x, V4.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.y, V4.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.z, V4.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.w, V4.w, 1e-4f);\n\tV.zwyx = V4;\n\tBOOST_CHECK_CLOSE(V.x, V4.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.y, V4.z, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.z, V4.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.w, V4.y, 1e-4f);\n\t// 4d swizzle assign <x, y, z, w> from swizzle\n\tV.xzyw = V4.xxxx;\n\tBOOST_CHECK_CLOSE(V.x, V4.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.y, V4.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.z, V4.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.w, V4.x, 1e-4f);\n\tV.yxzw = V4.wwyy;\n\tBOOST_CHECK_CLOSE(V.x, V4.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.y, V4.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.z, V4.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.w, V4.y, 1e-4f);\n\tV.zwyx = V4.wzyx;\n\tBOOST_CHECK_CLOSE(V.x, V4.x, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.y, V4.y, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.z, V4.w, 1e-4f);\n\tBOOST_CHECK_CLOSE(V.w, V4.z, 1e-4f);\n}\n\nBOOST_AUTO_TEST_CASE(equals) {\n\tvmath::core::Vector<float, 4> V1;\n\tV1.x = 20.12f;\n\tV1.y = 100.89f;\n\tV1.z = 18.2f;\n\tV1.w = 35.62f;\n\tvmath::core::Vector<float, 4> V2;\n\tV2.x = 10.34f;\n\tV2.y = 15.5f;\n\tV2.z = 20.2f;\n\tV2.w = 200.34f;\n\tvmath::core::Vector<float, 4> V3;\n\tV3.x = 20.12f;\n\tV3.y = 100.89f;\n\tV3.z = 18.2f;\n\tV3.w = 35.62f;\n\tBOOST_CHECK(!V1.xyzw.equals(V2));\n\tBOOST_CHECK(!V2.xyzw.equals(V3));\n\tBOOST_CHECK(V1.xyzw.equals(V1));\n\tBOOST_CHECK(V1.xyzw.equals(V3));\n}\n\nBOOST_AUTO_TEST_CASE(equals_specify_ulp) {\n\tvmath::core::Vector<float, 4> V1;\n\tV1.x = 20.12f;\n\tV1.y = 100.89f;\n\tV1.z = 18.2f;\n\tV1.w = 35.62f;\n\tvmath::core::Vector<float, 4> V2;\n\tV2.x = 10.34f;\n\tV2.y = 15.5f;\n\tV2.z = 20.2f;\n\tV2.w = 200.34f;\n\tvmath::core::Vector<float, 4> V3;\n\tV3.x = 20.12f;\n\tV3.y = 100.89f;\n\tV3.z = 18.2f;\n\tV3.w = 35.62f;\n\tBOOST_CHECK(!V1.xyzw.equals(V2, 3));\n\tBOOST_CHECK(!V2.xyzw.equals(V3, 3));\n\tBOOST_CHECK(V1.xyzw.equals(V1, 3));\n\tBOOST_CHECK(V1.xyzw.equals(V3, 3));\n}\n\nBOOST_AUTO_TEST_CASE(equals_op) {\n\tvmath::core::Vector<float, 4> V1;\n\tV1.x = 20.12f;\n\tV1.y = 100.89f;\n\tV1.z = 18.2f;\n\tV1.w = 35.62f;\n\tvmath::core::Vector<float, 4> V2;\n\tV2.x = 10.34f;\n\tV2.y = 15.5f;\n\tV2.z = 20.2f;\n\tV2.w = 200.34f;\n\tvmath::core::Vector<float, 4> V3;\n\tV3.x = 20.12f;\n\tV3.y = 100.89f;\n\tV3.z = 18.2f;\n\tV3.w = 35.62f;\n\tBOOST_CHECK(V1.xyzw != V2);\n\tBOOST_CHECK(V2.xyzw != V3);\n\tBOOST_CHECK(V1.xyzw == V1);\n\tBOOST_CHECK(V1.xyzw == V3);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "e2c42b647c4494d2d6703321d362b0d9b14ad87b", "size": 76249, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/swizzle4.cpp", "max_stars_repo_name": "ChasingCarrots/vmath", "max_stars_repo_head_hexsha": "06cc93e0d3d152306dbd63b60fa7cc4761f331bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-09-15T13:56:26.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-15T13:56:26.000Z", "max_issues_repo_path": "test/swizzle4.cpp", "max_issues_repo_name": "kernan/math", "max_issues_repo_head_hexsha": "6c28e7e731a2ea47a7b66b5dd4170283e84f1e02", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2016-07-05T19:11:09.000Z", "max_issues_repo_issues_event_max_datetime": "2017-05-08T21:19:58.000Z", "max_forks_repo_path": "test/swizzle4.cpp", "max_forks_repo_name": "kernan/vmath", "max_forks_repo_head_hexsha": "6c28e7e731a2ea47a7b66b5dd4170283e84f1e02", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-11-06T21:00:34.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-06T21:00:34.000Z", "avg_line_length": 37.5241141732, "max_line_length": 57, "alphanum_fraction": 0.6805859749, "num_tokens": 33203, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624890918021, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.47559516903082544}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// Unit Test\n\n// Copyright (c) 2007-2014 Barend Gehrels, Amsterdam, the Netherlands.\n// Copyright (c) 2008-2014 Bruno Lalande, Paris, France.\n// Copyright (c) 2009-2014 Mateusz Loskot, London, UK.\n\n// This file was modified by Oracle on 2014.\n// Modifications copyright (c) 2014, Oracle and/or its affiliates.\n\n// Contributed and/or modified by Menelaos Karavelas, on behalf of Oracle\n\n// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library\n// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_TEST_MODULE\n#define BOOST_TEST_MODULE test_pythagoras_point_box\n#endif\n\n#include <boost/test/included/unit_test.hpp>\n\n#if defined(_MSC_VER)\n#  pragma warning( disable : 4101 )\n#endif\n\n#include <boost/core/ignore_unused.hpp>\n#include <boost/timer.hpp>\n\n#include <boost/concept/requires.hpp>\n#include <boost/concept_check.hpp>\n\n#include <boost/geometry/algorithms/assign.hpp>\n#include <boost/geometry/algorithms/expand.hpp>\n#include <boost/geometry/strategies/cartesian/distance_pythagoras_point_box.hpp>\n#include <boost/geometry/strategies/concepts/distance_concept.hpp>\n\n\n#include <boost/geometry/geometries/point.hpp>\n#include <boost/geometry/geometries/box.hpp>\n#include <boost/geometry/geometries/adapted/c_array.hpp>\n#include <boost/geometry/geometries/adapted/boost_tuple.hpp>\n\n#include <test_common/test_point.hpp>\n\n#ifdef HAVE_TTMATH\n#  include <boost/geometry/extensions/contrib/ttmath_stub.hpp>\n#endif\n\n\nnamespace bg = boost::geometry;\n\n\nBOOST_GEOMETRY_REGISTER_C_ARRAY_CS(cs::cartesian)\nBOOST_GEOMETRY_REGISTER_BOOST_TUPLE_CS(cs::cartesian)\n\n\ntemplate <typename Box, typename Coordinate>\ninline void assign_values(Box& box,\n                          Coordinate const& x1,\n                          Coordinate const& y1,\n                          Coordinate const& z1,\n                          Coordinate const& x2,\n                          Coordinate const& y2,\n                          Coordinate const& z2)\n{\n    typename bg::point_type<Box>::type p1, p2;\n    bg::assign_values(p1, x1, y1, z1);\n    bg::assign_values(p2, x2, y2, z2);\n    bg::assign(box, p1);\n    bg::expand(box, p2);\n}\n\ntemplate <typename Point, typename Box>\ninline void test_null_distance_3d()\n{\n    Point p;\n    bg::assign_values(p, 1, 2, 4);\n    Box b;\n    assign_values(b, 1, 2, 3, 4, 5, 6);\n\n    typedef bg::strategy::distance::pythagoras_point_box<> pythagoras_pb_type;\n    typedef typename bg::strategy::distance::services::return_type\n        <\n            pythagoras_pb_type, Point, Box\n        >::type return_type;\n\n    pythagoras_pb_type pythagoras_pb;\n    return_type result = pythagoras_pb.apply(p, b);\n\n    BOOST_CHECK_EQUAL(result, return_type(0));\n\n    bg::assign_values(p, 1, 3, 4);\n    result = pythagoras_pb.apply(p, b);\n    BOOST_CHECK_EQUAL(result, return_type(0));\n\n    bg::assign_values(p, 2, 3, 4);\n    result = pythagoras_pb.apply(p, b);\n    BOOST_CHECK_EQUAL(result, return_type(0));\n}\n\ntemplate <typename Point, typename Box>\ninline void test_axis_3d()\n{\n    Box b;\n    assign_values(b, 0, 0, 0, 1, 1, 1);\n    Point p;\n    bg::assign_values(p, 2, 0, 0);\n\n    typedef bg::strategy::distance::pythagoras_point_box<> pythagoras_pb_type;\n    typedef typename bg::strategy::distance::services::return_type\n        <\n            pythagoras_pb_type, Point, Box\n        >::type return_type;\n\n    pythagoras_pb_type pythagoras_pb;\n\n    return_type result = pythagoras_pb.apply(p, b);\n    BOOST_CHECK_EQUAL(result, return_type(1));\n\n    bg::assign_values(p, 0, 2, 0);\n    result = pythagoras_pb.apply(p, b);\n    BOOST_CHECK_EQUAL(result, return_type(1));\n\n    bg::assign_values(p, 0, 0, 2);\n    result = pythagoras_pb.apply(p, b);\n    BOOST_CHECK_CLOSE(result, return_type(1), 0.001);\n}\n\ntemplate <typename Point, typename Box>\ninline void test_arbitrary_3d()\n{\n    Box b;\n    assign_values(b, 0, 0, 0, 1, 2, 3);\n    Point p;\n    bg::assign_values(p, 9, 8, 7);\n\n    {\n        typedef bg::strategy::distance::pythagoras_point_box<> strategy_type;\n        typedef typename bg::strategy::distance::services::return_type\n            <\n                strategy_type, Point, Box\n            >::type return_type;\n\n        strategy_type strategy;\n        return_type result = strategy.apply(p, b);\n        BOOST_CHECK_CLOSE(result, return_type(10.77032961427), 0.001);\n    }\n\n    {\n        // Check comparable distance\n        typedef bg::strategy::distance::comparable::pythagoras_point_box<>\n            strategy_type;\n\n        typedef typename bg::strategy::distance::services::return_type\n            <\n                strategy_type, Point, Box\n            >::type return_type;\n\n        strategy_type strategy;\n        return_type result = strategy.apply(p, b);\n        BOOST_CHECK_EQUAL(result, return_type(116));\n    }\n}\n\ntemplate <typename Point, typename Box, typename CalculationType>\ninline void test_services()\n{\n    namespace bgsd = bg::strategy::distance;\n    namespace services = bg::strategy::distance::services;\n\n    {\n        // Compile-check if there is a strategy for this type\n        typedef typename services::default_strategy\n            <\n                bg::point_tag, bg::box_tag, Point, Box\n            >::type pythagoras_pb_strategy_type;\n\n        // reverse geometry tags\n        typedef typename services::default_strategy\n            <\n                bg::box_tag, bg::point_tag, Box, Point\n            >::type reversed_pythagoras_pb_strategy_type;\n\n        boost::ignore_unused\n            <\n                pythagoras_pb_strategy_type,\n                reversed_pythagoras_pb_strategy_type\n            >();\n    }\n\n    Point p;\n    bg::assign_values(p, 1, 2, 3);\n\n    Box b;\n    assign_values(b, 4, 5, 6, 14, 15, 16);\n\n    double const sqr_expected = 3*3 + 3*3 + 3*3; // 27\n    double const expected = sqrt(sqr_expected); // sqrt(27)=5.1961524227\n\n    // 1: normal, calculate distance:\n\n    typedef bgsd::pythagoras_point_box<CalculationType> strategy_type;\n\n    BOOST_CONCEPT_ASSERT\n        ( (bg::concepts::PointDistanceStrategy<strategy_type, Point, Box>) );\n\n    typedef typename bgsd::services::return_type\n        <\n            strategy_type, Point, Box\n        >::type return_type;\n\n    strategy_type strategy;\n    return_type result = strategy.apply(p, b);\n    BOOST_CHECK_CLOSE(result, return_type(expected), 0.001);\n\n    // 2: the strategy should return the same result if we reverse parameters\n    //    result = strategy.apply(p2, p1);\n    //    BOOST_CHECK_CLOSE(result, return_type(expected), 0.001);\n\n\n    // 3: \"comparable\" to construct a \"comparable strategy\" for Point/Box\n    //    a \"comparable strategy\" is a strategy which does not calculate the exact distance, but\n    //    which returns results which can be mutually compared (e.g. avoid sqrt)\n\n    // 3a: \"comparable_type\"\n    typedef typename services::comparable_type\n        <\n            strategy_type\n        >::type comparable_type;\n\n    // 3b: \"get_comparable\"\n    comparable_type comparable = bgsd::services::get_comparable\n        <\n            strategy_type\n        >::apply(strategy);\n\n    typedef typename bgsd::services::return_type\n        <\n            comparable_type, Point, Box\n        >::type comparable_return_type;\n\n    comparable_return_type c_result = comparable.apply(p, b);\n    BOOST_CHECK_CLOSE(c_result, return_type(sqr_expected), 0.001);\n\n    // 4: the comparable_type should have a distance_strategy_constructor as well,\n    //    knowing how to compare something with a fixed distance\n    comparable_return_type c_dist5 = services::result_from_distance\n        <\n            comparable_type, Point, Box\n        >::apply(comparable, 5.0);\n\n    comparable_return_type c_dist6 = services::result_from_distance\n        <\n            comparable_type, Point, Box\n        >::apply(comparable, 6.0);\n\n    // If this is the case:\n    BOOST_CHECK(c_dist5 < c_result && c_result < c_dist6);\n\n    // This should also be the case\n    return_type dist5 = services::result_from_distance\n        <\n            strategy_type, Point, Box\n        >::apply(strategy, 5.0);\n    return_type dist6 = services::result_from_distance\n        <\n            strategy_type, Point, Box\n        >::apply(strategy, 6.0);\n    BOOST_CHECK(dist5 < result && result < dist6);\n}\n\ntemplate\n<\n    typename CoordinateType,\n    typename CalculationType,\n    typename AssignType\n>\ninline void test_big_2d_with(AssignType const& x1, AssignType const& y1,\n                             AssignType const& x2, AssignType const& y2,\n                             AssignType const& zero)\n{\n    typedef bg::model::point<CoordinateType, 2, bg::cs::cartesian> point_type;\n    typedef bg::model::box<point_type> box_type;\n    typedef bg::strategy::distance::pythagoras_point_box\n        <\n            CalculationType\n        > pythagoras_pb_type;\n\n    pythagoras_pb_type pythagoras_pb;\n    typedef typename bg::strategy::distance::services::return_type\n        <\n            pythagoras_pb_type, point_type, box_type\n        >::type return_type;\n\n\n    point_type p;\n    box_type b;\n    bg::assign_values(b, zero, zero, x1, y1);\n    bg::assign_values(p, x2, y2);\n    return_type d = pythagoras_pb.apply(p, b);\n\n    BOOST_CHECK_CLOSE(d, return_type(1076554.5485833955678294387789057), 0.001);\n}\n\ntemplate <typename CoordinateType, typename CalculationType>\ninline void test_big_2d()\n{\n    test_big_2d_with<CoordinateType, CalculationType>\n        (123456.78900001, 234567.89100001,\n         987654.32100001, 876543.21900001,\n         0.0);\n}\n\ntemplate <typename CoordinateType, typename CalculationType>\ninline void test_big_2d_string()\n{\n    test_big_2d_with<CoordinateType, CalculationType>\n        (\"123456.78900001\", \"234567.89100001\",\n         \"987654.32100001\", \"876543.21900001\",\n         \"0.0000000000000\");\n}\n\ntemplate <typename CoordinateType>\ninline void test_integer(bool check_types)\n{\n    typedef bg::model::point<CoordinateType, 2, bg::cs::cartesian> point_type;\n    typedef bg::model::box<point_type> box_type;\n\n    point_type p;\n    box_type b;\n    bg::assign_values(b, 0, 0, 12345678, 23456789);\n    bg::assign_values(p, 98765432, 87654321);\n\n    typedef bg::strategy::distance::pythagoras_point_box<> pythagoras_type;\n    typedef typename bg::strategy::distance::services::comparable_type\n        <\n            pythagoras_type\n        >::type comparable_type;\n\n    typedef typename bg::strategy::distance::services::return_type\n        <\n            pythagoras_type, point_type, box_type\n        >::type distance_type;\n    typedef typename bg::strategy::distance::services::return_type\n        <\n            comparable_type, point_type, box_type\n        >::type cdistance_type;\n\n    pythagoras_type pythagoras;\n    distance_type distance = pythagoras.apply(p, b);\n    BOOST_CHECK_CLOSE(distance, 107655455.02347542, 0.001);\n\n    comparable_type comparable;\n    cdistance_type cdistance = comparable.apply(p, b);\n    BOOST_CHECK_EQUAL(cdistance, 11589696996311540.0);\n\n    distance_type distance2 = sqrt(distance_type(cdistance));\n    BOOST_CHECK_CLOSE(distance, distance2, 0.001);\n\n    if (check_types)\n    {\n        BOOST_CHECK((boost::is_same<distance_type, double>::type::value));\n        BOOST_CHECK((boost::is_same<cdistance_type, boost::long_long_type>::type::value));\n    }\n}\n\ntemplate <typename P1, typename P2>\nvoid test_all_3d()\n{\n    test_null_distance_3d<P1, bg::model::box<P2> >();\n    test_axis_3d<P1, bg::model::box<P2> >();\n    test_arbitrary_3d<P1, bg::model::box<P2> >();\n\n    test_null_distance_3d<P2, bg::model::box<P1> >();\n    test_axis_3d<P2, bg::model::box<P1> >();\n    test_arbitrary_3d<P2, bg::model::box<P1> >();\n}\n\ntemplate <typename P>\nvoid test_all_3d()\n{\n    test_all_3d<P, int[3]>();\n    test_all_3d<P, float[3]>();\n    test_all_3d<P, double[3]>();\n    test_all_3d<P, test::test_point>();\n    test_all_3d<P, bg::model::point<int, 3, bg::cs::cartesian> >();\n    test_all_3d<P, bg::model::point<float, 3, bg::cs::cartesian> >();\n    test_all_3d<P, bg::model::point<double, 3, bg::cs::cartesian> >();\n}\n\ntemplate <typename P, typename Strategy>\nvoid time_compare_s(int const n)\n{\n    typedef bg::model::box<P> box_type;\n\n    boost::timer t;\n    P p;\n    box_type b;\n    bg::assign_values(b, 0, 0, 1, 1);\n    bg::assign_values(p, 2, 2);\n    Strategy strategy;\n    typename bg::strategy::distance::services::return_type\n        <\n            Strategy, P, box_type\n        >::type s = 0;\n    for (int i = 0; i < n; i++)\n    {\n        for (int j = 0; j < n; j++)\n        {\n            bg::set<0>(p, bg::get<0>(p) + 0.001);\n            s += strategy.apply(p, b);\n        }\n    }\n    std::cout << \"s: \" << s << \" t: \" << t.elapsed() << std::endl;\n}\n\ntemplate <typename P>\ninline void time_compare(int const n)\n{\n    time_compare_s<P, bg::strategy::distance::pythagoras_point_box<> >(n);\n    time_compare_s\n        <\n            P, bg::strategy::distance::comparable::pythagoras_point_box<>\n        >(n);\n}\n\n\n\n\nBOOST_AUTO_TEST_CASE( test_integer_all )\n{\n    test_integer<int>(true);\n    test_integer<boost::long_long_type>(true);\n    test_integer<double>(false);\n}\n\n\nBOOST_AUTO_TEST_CASE( test_3d_all )\n{\n    test_all_3d<int[3]>();\n    test_all_3d<float[3]>();\n    test_all_3d<double[3]>();\n\n    test_all_3d<test::test_point>();\n\n    test_all_3d<bg::model::point<int, 3, bg::cs::cartesian> >();\n    test_all_3d<bg::model::point<float, 3, bg::cs::cartesian> >();\n    test_all_3d<bg::model::point<double, 3, bg::cs::cartesian> >();\n}\n\n\nBOOST_AUTO_TEST_CASE( test_big_2d_all )\n{\n    test_big_2d<float, float>();\n    test_big_2d<double, double>();\n    test_big_2d<long double, long double>();\n    test_big_2d<float, long double>();\n}\n\n\nBOOST_AUTO_TEST_CASE( test_services_all )\n{\n    test_services\n        <\n            bg::model::point<float, 3, bg::cs::cartesian>,\n            bg::model::box<double[3]>,\n            long double\n        >();\n    test_services<double[3], bg::model::box<test::test_point>, float>();\n\n    // reverse the point and box types\n    test_services\n        <\n            double[3],\n            bg::model::box<bg::model::point<float, 3, bg::cs::cartesian> >,\n            long double\n        >();\n    test_services<test::test_point, bg::model::box<double[3]>, float>();\n}\n\n\nBOOST_AUTO_TEST_CASE( test_time_compare )\n{\n    // TODO move this to another non-unit test\n    //    time_compare<bg::model::point<double, 2, bg::cs::cartesian> >(10000);\n}\n\n\n#if defined(HAVE_TTMATH)\nBOOST_AUTO_TEST_CASE( test_ttmath_all )\n{\n    typedef ttmath::Big<1,4> tt;\n    typedef bg::model::point<tt, 3, bg::cs::cartesian> tt_point;\n\n    //test_all_3d<tt[3]>();\n    test_all_3d<tt_point>();\n    test_all_3d<tt_point, tt_point>();\n    test_big_2d<tt, tt>();\n    test_big_2d_string<tt, tt>();\n}\n#endif\n", "meta": {"hexsha": "295febcb30a664bb4262f975f10108045c972d81", "size": 14908, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "deps/src/boost_1_65_1/libs/geometry/test/strategies/pythagoras_point_box.cpp", "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/libs/geometry/test/strategies/pythagoras_point_box.cpp", "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/libs/geometry/test/strategies/pythagoras_point_box.cpp", "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": 29.4624505929, "max_line_length": 96, "alphanum_fraction": 0.6533404883, "num_tokens": 4017, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529376, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.47559516286981085}}
{"text": "#ifdef HOPS_GUROBI_FOUND\n\n#include <Eigen/Core>\n\n#include <hops/LinearProgram/LinearProgramGurobiImpl.hpp>\n#include <hops/LinearProgram/GurobiEnvironmentSingleton.hpp>\n\nnamespace {\n    std::vector<GRBVar> addVariablesToModel(GRBModel *model, size_t numberOfVariables) {\n        std::vector<GRBVar> variables;\n        for (size_t i = 0; i < numberOfVariables; ++i) {\n            variables.emplace_back(model->addVar(\n                    -GRB_INFINITY,\n                    +GRB_INFINITY,\n                    0,\n                    GRB_CONTINUOUS,\n                    \"x_\" + std::to_string(i))\n            );\n        }\n        return variables;\n    }\n\n    void addLinearConstraints(const Eigen::MatrixXd &inequalityA,\n                              const Eigen::VectorXd &inequalityB,\n                              GRBModel *model,\n                              const std::vector<GRBVar> &variables) {\n        for (long i = 0; i < inequalityA.rows(); ++i) {\n            GRBLinExpr expression;\n            double coefficients[inequalityA.cols()];\n            for (long j = 0; j < inequalityA.cols(); ++j) {\n                coefficients[j] = inequalityA.coeff(i, j);\n            }\n            expression.addTerms(coefficients, &variables[0], inequalityA.cols());\n            model->addConstr(expression, GRB_LESS_EQUAL, inequalityB(i), \"row_\" + std::to_string(i));\n        }\n    }\n\n    void addObjective(const Eigen::VectorXd &objective, GRBModel *model,\n                      const std::vector<GRBVar> &variables) {\n        GRBLinExpr objectiveExpression = 0.0;\n        objectiveExpression.addTerms(objective.data(), &variables[0], objective.rows());\n        model->setObjective(objectiveExpression, GRB_MAXIMIZE);\n    }\n\n    hops::LinearProgramStatus parseGurobiStatus(int returnCode) {\n        switch (returnCode) {\n            case 2: {\n                return hops::LinearProgramStatus::OPTIMAL;\n            }\n            case 3: {\n                return hops::LinearProgramStatus::INFEASIBLE;\n            }\n            case 4: {\n                return hops::LinearProgramStatus::UNDEFINED;\n            }\n            case 5: {\n                return hops::LinearProgramStatus::UNBOUNDED;\n            }\n            default: {\n                return hops::LinearProgramStatus::ERROR;\n            }\n        }\n    }\n}\n\nhops::LinearProgramGurobiImpl::LinearProgramGurobiImpl(const Eigen::MatrixXd &A, const Eigen::VectorXd &b) :\n        LinearProgram(A, b),\n        model(std::make_unique<GRBModel>(GRBModel(GurobiEnvironmentSingleton::getInstance().getGurobiEnvironment()))) {\n    variables = addVariablesToModel(model.get(), A.cols());\n    addLinearConstraints(A, b, model.get(), variables);\n    model->update();\n}\n\nhops::LinearProgramGurobiImpl::LinearProgramGurobiImpl(const hops::LinearProgramGurobiImpl &other) :\n        LinearProgram(other.A, other.b),\n        variables(other.variables) {\n    model = std::make_unique<GRBModel>(*other.model);\n}\n\nhops::LinearProgramGurobiImpl &hops::LinearProgramGurobiImpl::operator=(const hops::LinearProgramGurobiImpl &other) {\n    this->A = other.A;\n    this->b = other.b;\n    this->model = std::make_unique<GRBModel>(*other.model);\n    this->variables = other.variables;\n    return *this;\n}\n\nhops::LinearProgramSolution hops::LinearProgramGurobiImpl::solve(const Eigen::VectorXd &objective) const {\n    addObjective(objective, model.get(), variables);\n    model->update();\n\n    try {\n        model->optimize();\n\n        int status = model->get(GRB_IntAttr_Status);\n\n        if (status == GRB_INF_OR_UNBD) {\n            model->set(GRB_IntParam_Presolve, 0);\n            model->optimize();\n            status = model->get(GRB_IntAttr_Status);\n        }\n        if (status == GRB_OPTIMAL) {\n            double objectiveValue = model->get(GRB_DoubleAttr_ObjVal);\n            auto numberOfColumns = model->get(GRB_IntAttr_NumVars);\n            auto modelVariables = model->getVars();\n            Eigen::VectorXd solution(numberOfColumns);\n            for (int i = 0; i < numberOfColumns; ++i) {\n                solution(i) = modelVariables[i].get(GRB_DoubleAttr_X);\n            }\n            return LinearProgramSolution(objectiveValue, solution, parseGurobiStatus(status));\n        } else if (status == GRB_INFEASIBLE) {\n            return LinearProgramSolution(std::numeric_limits<double>::quiet_NaN(),\n                                         Eigen::VectorXd(),\n                                         LinearProgramStatus::INFEASIBLE);\n        } else if (status == GRB_UNBOUNDED) {\n            return LinearProgramSolution(std::numeric_limits<double>::quiet_NaN(),\n                                         Eigen::VectorXd(),\n                                         LinearProgramStatus::UNBOUNDED);\n        } else if (status == GRB_UNDEFINED) {\n            return LinearProgramSolution(std::numeric_limits<double>::quiet_NaN(),\n                                         Eigen::VectorXd(),\n                                         LinearProgramStatus::UNDEFINED);\n        }\n    }\n    catch (const GRBException &e) {\n        throw std::runtime_error(\"Gurobi encountered an exception: \" + e.getMessage());\n    }\n    throw std::runtime_error(\"Exception: Gurobi failed to provide problem status or exception.\");\n}\n\nstd::tuple<Eigen::MatrixXd, Eigen::VectorXd>\nhops::LinearProgramGurobiImpl::removeRedundantConstraints(double tolerance) {\n    std::vector<long> constraintsToRemove;\n    for (int i = 0; i < static_cast<int>(A.rows()); ++i) {\n        GRBConstr constraintToTestForRedundancy = model->getConstrByName(\"row_\" + std::to_string(i));\n        model->remove(constraintToTestForRedundancy);\n        model->update();\n        GRBLinExpr constraintLHS;\n        double coefficients[A.cols()];\n        for (long j = 0; j < A.cols(); ++j) {\n            coefficients[j] = A.coeff(i, j);\n        }\n        constraintLHS.addTerms(coefficients, &variables[0], A.cols());\n        try {\n            auto temporaryConstraint = model->addConstr(constraintLHS, GRB_LESS_EQUAL, b(i) + 10);\n            model->update();\n            auto solution = solve(A.row(i));\n            model->remove(temporaryConstraint);\n            model->update();\n\n            if (solution.status != LinearProgramStatus::OPTIMAL || solution.objectiveValue + tolerance > b(i)) {\n                model->addConstr(constraintLHS, GRB_LESS_EQUAL, b(i), \"row_\" + std::to_string(i));\n                model->update();\n            } else {\n                constraintsToRemove.emplace_back(i);\n            }\n        }\n        catch (GRBException &e) {\n            std::cerr << \"error code \" << e.getErrorCode() << \": \" << e.getMessage() << std::endl;\n        }\n    }\n\n    std::vector<long> constraintsToKeep;\n    for (long i = 0; i < A.rows(); ++i) {\n        if (std::find(constraintsToRemove.begin(), constraintsToRemove.end(), i) == constraintsToRemove.end()) {\n            constraintsToKeep.emplace_back(i);\n        }\n    }\n\n    Eigen::MatrixXd newA(constraintsToKeep.size(), A.cols());\n    Eigen::VectorXd newb(constraintsToKeep.size());\n    for (size_t i = 0; i < constraintsToKeep.size(); ++i) {\n        newb(i) = b(constraintsToKeep.at(i));\n        newA.row(i) = A.row(constraintsToKeep.at(i));\n    }\n\n    *this = LinearProgramGurobiImpl(newA, newb);\n    return std::make_tuple(A, b);\n}\n\nhops::LinearProgramSolution hops::LinearProgramGurobiImpl::computeChebyshevCenter() const {\n    //Extend system by dimension for radius\n    const long numberOfRows = A.rows();\n    const long numberOfColumns = A.cols();\n    Eigen::MatrixXd A_ext = A;\n    Eigen::MatrixXd l_col(numberOfRows + 1, 1);\n    l_col << A.rowwise().norm(), -1;\n    A_ext.conservativeResize(numberOfRows + 1, numberOfColumns + 1);\n    A_ext.row(numberOfRows) = Eigen::VectorXd::Zero(numberOfColumns + 1);\n    A_ext.col(numberOfColumns) = l_col;\n    Eigen::VectorXd b_ext = b;\n    b_ext.conservativeResize(numberOfRows + 1);\n    b_ext(numberOfRows) = 0;\n\n    //make objective\n    Eigen::VectorXd obj = Eigen::VectorXd::Zero(numberOfColumns + 1);\n    obj(numberOfColumns) = 1;\n\n    LinearProgramSolution chebyshevSolution = LinearProgramGurobiImpl(A_ext, b_ext).solve(obj);\n    chebyshevSolution.optimalParameters.conservativeResize(A.cols());\n    return chebyshevSolution;\n}\n\nstd::vector<long> hops::LinearProgramGurobiImpl::computeUnconstrainedDimensions() const {\n    std::vector<long> directions;\n    for (long i = 0; i < A.cols(); ++i) {\n        Eigen::VectorXd objective = Eigen::VectorXd::Zero(A.cols());\n        objective(i) = 1.0;\n        auto forwardSolution = solve(objective);\n        if (forwardSolution.status != hops::LinearProgramStatus::OPTIMAL) {\n            directions.push_back(i + 1);\n        }\n\n        auto backwardSolution = solve(-objective);\n        if (backwardSolution.status != hops::LinearProgramStatus::OPTIMAL) {\n            directions.push_back(-i - 1);\n        }\n    }\n    return directions;\n}\n\n\nstd::tuple<Eigen::MatrixXd, Eigen::VectorXd>\nhops::LinearProgramGurobiImpl::addBoxConstraintsToUnconstrainedDimensions(double lb, double ub) {\n    std::vector<long> unconstrainedDimensions = computeUnconstrainedDimensions();\n\n    for (const auto &unconstrainedDimension : unconstrainedDimensions) {\n        A.conservativeResize(A.rows() + 1, A.cols());\n        A.row(A.rows() - 1) = Eigen::VectorXd::Zero(A.cols());\n        b.conservativeResize(b.rows() + 1);\n        if (unconstrainedDimension > 0) {\n            A(A.rows() - 1, unconstrainedDimension - 1) = 1;\n            b(b.rows() - 1) = ub;\n        } else {\n            A(A.rows() - 1, -unconstrainedDimension - 1) = -1;\n            b(b.rows() - 1) = lb;\n        }\n    }\n    *this = LinearProgramGurobiImpl(A, b);\n    return std::make_tuple(A, b);\n}\n\n#endif //HOPS_GUROBI_FOUND\n", "meta": {"hexsha": "4af37548224b326c751d7128d2486459064a2078", "size": 9718, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "include/hops/LinearProgram/LinearProgramGurobiImpl.cpp", "max_stars_repo_name": "modsim/hops", "max_stars_repo_head_hexsha": "4285dd75a07dd844295440a0756b3ba25f5819ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2020-11-26T05:13:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T02:08:40.000Z", "max_issues_repo_path": "include/hops/LinearProgram/LinearProgramGurobiImpl.cpp", "max_issues_repo_name": "modsim/hops", "max_issues_repo_head_hexsha": "4285dd75a07dd844295440a0756b3ba25f5819ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-02-20T23:16:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-20T23:16:34.000Z", "max_forks_repo_path": "include/hops/LinearProgram/LinearProgramGurobiImpl.cpp", "max_forks_repo_name": "modsim/hops", "max_forks_repo_head_hexsha": "4285dd75a07dd844295440a0756b3ba25f5819ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.8278688525, "max_line_length": 119, "alphanum_fraction": 0.6021815188, "num_tokens": 2325, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4755951628698108}}
{"text": "#include <boost/multiprecision/cpp_int.hpp>\n#include <iostream>\n\n#include \"../include/brute_force.hpp\"\n#include \"../include/encryption.hpp\"\n#include \"../include/key_generator.hpp\"\n\nint main() {\n  Key_pair keys = generate_keys(256, true);\n  encrypt_file(\"original.txt\", \"encriptado.txt\", keys.pub_key);\n  decrypt_file(\"encriptado.txt\", \"decriptado.txt\", keys.priv_key);\n}\n", "meta": {"hexsha": "3cbfbf4658b18c38616b6e588e6e1d19590bc995", "size": 371, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "paulora2405/cal-tf", "max_stars_repo_head_hexsha": "7fc1c5f5b070ff7dc2800ced5951f6e37abc1db5", "max_stars_repo_licenses": ["MIT"], "max_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": "paulora2405/cal-tf", "max_issues_repo_head_hexsha": "7fc1c5f5b070ff7dc2800ced5951f6e37abc1db5", "max_issues_repo_licenses": ["MIT"], "max_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": "paulora2405/cal-tf", "max_forks_repo_head_hexsha": "7fc1c5f5b070ff7dc2800ced5951f6e37abc1db5", "max_forks_repo_licenses": ["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.5384615385, "max_line_length": 66, "alphanum_fraction": 0.7331536388, "num_tokens": 90, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4755689637238382}}
{"text": "/*\n Copyright (C) 2021 Quaternion Risk Management Ltd\n All rights reserved.\n*/\n\n// clang-format off\n#include <boost/test/unit_test.hpp>\n#include <boost/test/data/test_case.hpp>\n// clang-format on\n\n#include <qle/cashflows/durationadjustedcmscoupon.hpp>\n#include <qle/cashflows/durationadjustedcmscoupontsrpricer.hpp>\n#include <qle/models/linearannuitymapping.hpp>\n\n#include \"toplevelfixture.hpp\"\n\n#include <ql/time/date.hpp>\n#include <ql/cashflows/cmscoupon.hpp>\n#include <ql/cashflows/lineartsrpricer.hpp>\n#include <ql/termstructures/yieldtermstructure.hpp>\n#include <ql/termstructures/yield/flatforward.hpp>\n#include <ql/termstructures/volatility/swaption/swaptionconstantvol.hpp>\n#include <ql/indexes/swap/euriborswap.hpp>\n\nusing namespace QuantExt;\nusing namespace QuantLib;\n\nBOOST_FIXTURE_TEST_SUITE(QuantExtTestSuite, qle::test::TopLevelFixture)\n\nBOOST_AUTO_TEST_SUITE(DurationAdjustedCouponTest)\n\nBOOST_AUTO_TEST_CASE(testAgainstCmsCoupon) {\n\n    BOOST_TEST_MESSAGE(\"Testing duration adjusted cms coupons vs. vanilla cms coupon...\");\n\n    Date today(25, January, 2021);\n    Settings::instance().evaluationDate() = today;\n\n    Handle<YieldTermStructure> discountCurve(\n        boost::make_shared<FlatForward>(0, NullCalendar(), 0.01, Actual365Fixed()));\n    Handle<YieldTermStructure> forwardCurve(boost::make_shared<FlatForward>(0, NullCalendar(), 0.02, Actual365Fixed()));\n    Handle<SwaptionVolatilityStructure> swaptionVol(boost::make_shared<ConstantSwaptionVolatility>(\n        0, NullCalendar(), Unadjusted, 0.0050, Actual365Fixed(), Normal));\n    Handle<Quote> reversion(boost::make_shared<SimpleQuote>(0.01));\n\n    Date startDate = Date(25, January, 2025);\n    Date endDate = Date(25, January, 2026);\n    Date payDate = Date(27, January, 2026);\n    Size fixingDays = 2;\n    auto index = boost::make_shared<EuriborSwapIsdaFixA>(10 * Years, forwardCurve, discountCurve);\n\n    CmsCoupon cmsCoupon(payDate, 1.0, startDate, endDate, fixingDays, index);\n    DurationAdjustedCmsCoupon durationAdjustedCmsCoupon(payDate, 1.0, startDate, endDate, fixingDays, index, 0);\n\n    auto cmsPricer = boost::make_shared<LinearTsrPricer>(swaptionVol, reversion, discountCurve,\n                                                         LinearTsrPricer::Settings().withRateBound(-2.0, 2.0));\n\n    auto durationAdjustedCmsPricer = boost::make_shared<DurationAdjustedCmsCouponTsrPricer>(\n        swaptionVol, boost::make_shared<LinearAnnuityMappingBuilder>(reversion), -2.0, 2.0);\n\n    cmsCoupon.setPricer(cmsPricer);\n    durationAdjustedCmsCoupon.setPricer(durationAdjustedCmsPricer);\n\n    BOOST_TEST_MESSAGE(\"cms coupon rate                   = \" << cmsCoupon.rate());\n    BOOST_TEST_MESSAGE(\"cms coupon convexity adj          = \" << cmsCoupon.convexityAdjustment());\n    BOOST_TEST_MESSAGE(\"duration adjusted cms coupon rate = \" << durationAdjustedCmsCoupon.rate());\n    BOOST_TEST_MESSAGE(\"dur adj cms coupon convexity adj  = \" << durationAdjustedCmsCoupon.convexityAdjustment());\n\n    Real tol = 1E-6; // percentage tolerance, i.e. we have 1E-8 effectively\n\n    BOOST_CHECK_CLOSE(cmsCoupon.rate(), durationAdjustedCmsCoupon.rate(), tol);\n    BOOST_CHECK_CLOSE(cmsCoupon.convexityAdjustment(), durationAdjustedCmsCoupon.convexityAdjustment(), tol);\n}\n\nBOOST_AUTO_TEST_CASE(testHistoricalValues) {\n\n    BOOST_TEST_MESSAGE(\"Testing duration adjusted cms coupon historical rates...\");\n\n    Date today(25, January, 2021);\n    Settings::instance().evaluationDate() = today;\n\n    Date startDate = Date(25, June, 2020);\n    Date endDate = Date(25, June, 2021);\n    Date payDate = Date(27, June, 2021);\n    Size fixingDays = 2;\n\n    Handle<YieldTermStructure> discountCurve(\n        boost::make_shared<FlatForward>(0, NullCalendar(), 0.01, Actual365Fixed()));\n    Handle<YieldTermStructure> forwardCurve(boost::make_shared<FlatForward>(0, NullCalendar(), 0.02, Actual365Fixed()));\n\n    auto index = boost::make_shared<EuriborSwapIsdaFixA>(10 * Years, forwardCurve, discountCurve);\n\n    Date fixingDate = index->fixingCalendar().advance(startDate, -(fixingDays * Days), Preceding);\n    Real fixingValue = 0.01;\n    index->addFixing(fixingDate, fixingValue);\n\n    // we do not need a vol surface or an annuity mapping builder, since the coupon amount is determistic\n    auto pricer =\n        boost::make_shared<DurationAdjustedCmsCouponTsrPricer>(Handle<SwaptionVolatilityStructure>(), nullptr);\n\n    DurationAdjustedCmsCoupon cpn0(payDate, 1.0, startDate, endDate, fixingDays, index, 0);\n    DurationAdjustedCmsCoupon cpn1(payDate, 1.0, startDate, endDate, fixingDays, index, 1);\n    DurationAdjustedCmsCoupon cpn10(payDate, 1.0, startDate, endDate, fixingDays, index, 10);\n\n    cpn0.setPricer(pricer);\n    cpn1.setPricer(pricer);\n    cpn10.setPricer(pricer);\n\n    BOOST_TEST_MESSAGE(\"duration = 0  : rate = \" << cpn0.rate());\n    BOOST_TEST_MESSAGE(\"duration = 1  : rate = \" << cpn1.rate());\n    BOOST_TEST_MESSAGE(\"duration = 10 : rate = \" << cpn10.rate());\n\n    BOOST_TEST_MESSAGE(\"duration = 0  : indexFixing = \" << cpn0.indexFixing());\n    BOOST_TEST_MESSAGE(\"duration = 1  : indexFixing = \" << cpn1.indexFixing());\n    BOOST_TEST_MESSAGE(\"duration = 10 : indexFixing = \" << cpn10.indexFixing());\n\n    auto durationAdjustment = [](const Real S, const Size i) {\n        if (i == 0)\n            return 1.0;\n        Real tmp = 0.0;\n        for (Size j = 0; j < i; ++j)\n            tmp += 1.0 / std::pow(1.0 + S, j + 1);\n        return tmp;\n    };\n\n    Real tol = 1.0E-6;\n\n    BOOST_CHECK_CLOSE(cpn0.rate(), fixingValue * durationAdjustment(fixingValue, 0), tol);\n    BOOST_CHECK_CLOSE(cpn1.rate(), fixingValue * durationAdjustment(fixingValue, 1), tol);\n    BOOST_CHECK_CLOSE(cpn10.rate(), fixingValue * durationAdjustment(fixingValue, 10), tol);\n\n    BOOST_CHECK_CLOSE(cpn0.indexFixing(), fixingValue * durationAdjustment(fixingValue, 0), tol);\n    BOOST_CHECK_CLOSE(cpn1.indexFixing(), fixingValue * durationAdjustment(fixingValue, 1), tol);\n    BOOST_CHECK_CLOSE(cpn10.indexFixing(), fixingValue * durationAdjustment(fixingValue, 10), tol);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "194826ccbad491ab72141194a234c98a4bc96db5", "size": 6090, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QuantExt/test/durationadjustedcmscoupon.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/test/durationadjustedcmscoupon.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/test/durationadjustedcmscoupon.cpp", "max_forks_repo_name": "mrslezak/Engine", "max_forks_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 180.0, "max_forks_repo_forks_event_min_datetime": "2016-10-08T14:23:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T10:43:05.000Z", "avg_line_length": 43.5, "max_line_length": 120, "alphanum_fraction": 0.7224958949, "num_tokens": 1651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.47556895935690435}}
{"text": "#pragma once\n#include <Eigen/Core>\n#include <memory>\n#include \"ear/helpers/output_gains.hpp\"\n#include \"ear/layout.hpp\"\n#include \"ear/metadata.hpp\"\n#include \"ear/warnings.hpp\"\n\nnamespace ear {\n\n  class GainCalculatorHOAImpl {\n   public:\n    GainCalculatorHOAImpl(const Layout& layout);\n\n    void calculate(const HOATypeMetadata& metadata, OutputGainMat& direct,\n                   const WarningCB& warning_cb = default_warning_cb);\n\n    template <typename T>\n    void calculate(const HOATypeMetadata& metadata,\n                   std::vector<std::vector<T>>& direct,\n                   const WarningCB& warning_cb = default_warning_cb) {\n      OutputGainMatVecT<T> direct_wrap(direct);\n      calculate(metadata, direct_wrap, warning_cb);\n    }\n\n   private:\n    Eigen::Matrix<double, Eigen::Dynamic, 3> points;\n    Eigen::Array<bool, Eigen::Dynamic, 1> is_lfe;\n    Eigen::MatrixXd G_virt;\n  };\n\n}  // namespace ear\n", "meta": {"hexsha": "8780155db89e439b2aa93ea3c66b736dca40413c", "size": 913, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/hoa/gain_calculator_hoa.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/hoa/gain_calculator_hoa.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/hoa/gain_calculator_hoa.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": 27.6666666667, "max_line_length": 74, "alphanum_fraction": 0.6801752464, "num_tokens": 212, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8459424217727027, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.475568950623036}}
{"text": "// Copyright 2017 Emanuele Palazzolo (emanuele.palazzolo@uni-bonn.de), Cyrill Stachniss, University of Bonn\n#include \"fastcd/point_covariance3d.h\"\n#include <Eigen/Core>\n#include \"fastcd/mesh.h\"\n\nnamespace fastcd {\n\nPointCovariance3d::PointCovariance3d(const Eigen::Vector3d &point,\n                           const Eigen::Matrix3d &covariance, double chi_square)\n    : point_(point), covariance_(covariance) {\n  Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> es(covariance_);\n  eigenvalues_ = es.eigenvalues();\n  eigenvectors_ = es.eigenvectors();\n  scaling_.setZero();\n  for (int i = 0; i < 3; i++) {\n    scaling_(i, i) = sqrt(chi_square) * sqrt(eigenvalues_(i));\n  }\n  Eigen::Vector3d vertex;\n  vertex << 1, 0, 0;\n  vertex = eigenvectors_ * scaling_ * vertex + point_;\n  vertices_.push_back(vertex);\n  vertex << -1, 0, 0;\n  vertex = eigenvectors_ * scaling_ * vertex + point_;\n  vertices_.push_back(vertex);\n  vertex << 0, 1, 0;\n  vertex = eigenvectors_ * scaling_ * vertex + point_;\n  vertices_.push_back(vertex);\n  vertex << 0, -1, 0;\n  vertex = eigenvectors_ * scaling_ * vertex + point_;\n  vertices_.push_back(vertex);\n  vertex << 0, 0, 1;\n  vertex = eigenvectors_ * scaling_ * vertex + point_;\n  vertices_.push_back(vertex);\n  vertex << 0, 0, -1;\n  vertex = eigenvectors_ * scaling_ * vertex + point_;\n  vertices_.push_back(vertex);\n}\n\nMesh PointCovariance3d::ToMesh(int stacks, int slices, float r, float g,\n                               float b, float a) const {\n  Mesh::Material material;\n  material.ambient = glow::vec3(0.1, 0.1, 0.1);\n  material.diffuse = glow::vec3(r, g, b);\n  material.specular = glow::vec3(0, 0, 0);\n  material.emission = glow::vec3(0, 0, 0);\n  material.alpha = a;\n  std::vector<Mesh::Material> materials;\n  materials.push_back(material);\n\n  std::vector<Mesh::Vertex> vertices;\n  float t_step = M_PI / static_cast<float>(slices);\n  float s_step = M_PI / static_cast<float>(stacks);\n  for (float t = -M_PI / 2; t <= (M_PI / 2) + .0001; t += t_step) {\n    for (float s = -M_PI; s <= M_PI + .0001; s += s_step) {\n      Eigen::Vector3d vertex;\n      vertex << cos(t) * cos(s), cos(t) * sin(s), sin(t);\n      vertex = eigenvectors_ * scaling_ * vertex + point_;\n      Mesh::Vertex v1;\n      v1.position = glow::vec4(vertex(0), vertex(1), vertex(2), 1);\n      vertices.push_back(v1);\n\n      Mesh::Vertex v2;\n      vertex << cos(t + t_step) * cos(s), cos(t + t_step) * sin(s),\n          sin(t + t_step);\n      vertex = eigenvectors_ * scaling_ * vertex + point_;\n      v2.position = glow::vec4(vertex(0), vertex(1), vertex(2), 1);\n      vertices.push_back(v2);\n    }\n  }\n\n  std::vector<Mesh::Triangle> triangles;\n  for (size_t i = 2; i < vertices.size(); i++) {\n    Mesh::Triangle t;\n    t.vertices[0] = i-2;\n    t.vertices[1] = i % 2 == 0 ? i - 1 : i;\n    t.vertices[2] = i % 2 == 0 ? i : i - 1;\n\n    if (t.vertices[0] != t.vertices[1] && t.vertices[1] != t.vertices[2] &&\n        t.vertices[2] != t.vertices[0]) {\n      triangles.push_back(t);\n    }\n  }\n\n  Mesh mesh(vertices, triangles, materials);\n  return mesh;\n}\n\nEigen::Vector3d PointCovariance3d::Point() const { return point_; }\n\nEigen::Matrix3d PointCovariance3d::Covariance() const { return covariance_; }\n\nEigen::Vector3d PointCovariance3d::Eigenvalues() const { return eigenvalues_; }\n\nEigen::Matrix3d PointCovariance3d::Eigenvectors() const {\n  return eigenvectors_;\n}\n\nEigen::Matrix3d PointCovariance3d::Scaling() const { return scaling_; }\n\nstd::vector<Eigen::Vector3d> PointCovariance3d::Vertices() const {\n  return vertices_;\n}\n\n}  // namespace fastcd\n", "meta": {"hexsha": "8d157621bda52534e5039ac0598b94cd6143b41b", "size": 3546, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/fastcd/point_covariance3d.cpp", "max_stars_repo_name": "PRBonn/fast_change_detection", "max_stars_repo_head_hexsha": "46667aab4fd3ded71a82478b8909965a3ead6a5d", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 35.0, "max_stars_repo_stars_event_min_datetime": "2018-06-27T23:45:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T12:43:06.000Z", "max_issues_repo_path": "src/fastcd/point_covariance3d.cpp", "max_issues_repo_name": "Photogrammetry-Robotics-Bonn/fast_change_detection", "max_issues_repo_head_hexsha": "46667aab4fd3ded71a82478b8909965a3ead6a5d", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-05-22T13:45:50.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-31T19:09:44.000Z", "max_forks_repo_path": "src/fastcd/point_covariance3d.cpp", "max_forks_repo_name": "PRBonn/fast_change_detection", "max_forks_repo_head_hexsha": "46667aab4fd3ded71a82478b8909965a3ead6a5d", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2018-05-25T08:45:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-06T05:32:41.000Z", "avg_line_length": 33.7714285714, "max_line_length": 107, "alphanum_fraction": 0.6446700508, "num_tokens": 1111, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424217727027, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.475568950623036}}
{"text": "#ifndef CLOUD_CPP\n#define CLOUD_CPP\n\n#include <iostream>\n#include \"../include/cloud.h\"\n#include <Eigen/Dense>\n\nusing Eigen::MatrixXd;\n\nCloud::Cloud(float _Ox, float _Oy, float _Oz, size_t _total_points, float _dmin):\n    Ox(_Ox), Oy(_Oy), Oz(_Oz), total_points(_total_points), dmin(_dmin)\n{\n    if( dmin < 0.0f ) dmin = 0.001f;\n    if( Ox < 0.0f )   Ox   = 1.0f;\n    if( Oy < 0.0f )   Oy   = 1.0f;\n    if( Oz < 0.0f )   Oz   = 1.0f;\n}\n\nCloud::~Cloud()\n{\n    into_points.clear();\n}\n\nbool\nCloud::build(QOpenGLShaderProgram* program)\n{\n    // BUILD CLOUD\n    std::random_device rd;\n    std::default_random_engine re(rd());\n\n    // Generators\n    std::uniform_real_distribution<float> xgen{-Ox, Ox};\n    std::uniform_real_distribution<float> ygen{-Oy, Oy};\n    std::uniform_real_distribution<float> zgen{-Oz, Oz};\n\n    // Prepare deque to receive information\n    into_points.clear();\n\n    for(size_t i=0; i < total_points; ++i){\n        float x = xgen(re);\n        float y = ygen(re);\n        float z = zgen(re);\n\n        if( into(x, y, z) ){\n            bool distance_ok = true;\n            for(size_t j=0; j < into_points.size(); j+=3){\n                float dist = distance(\n                    x, y, z,\n                    into_points[j+0],\n                    into_points[j+1],\n                    into_points[j+2]\n                );\n\n                if( dist <= dmin ){\n                    distance_ok = false;\n                    break;\n                }\n            }\n\n            if( distance_ok ){\n                into_points.push_back(x);\n                into_points.push_back(y);\n                into_points.push_back(z);\n            }\n        }\n    }\n\n    // Once we have all the correct points into our shape.\n    // Build datas\n    size_t npoints = into_points.size()/3;\n    GLfloat* positions = new GLfloat[npoints*3];\n    GLuint* indices = new GLuint[npoints];\n\n    for(size_t i=0; i < npoints; ++i){\n        size_t idx = (i*3);\n        positions[idx+0] = into_points[idx+0];\n        positions[idx+1] = into_points[idx+1];\n        positions[idx+2] = into_points[idx+2];\n        indices[i] = GLuint(i);\n    }\n\n    // BUILD BUFFERS (will be sent to GPU with `update_buffers()` method.\n    set_vertices_geometry(\n        program->attributeLocation(\"position\"), positions, indices);\n\n    set_vertices_colors(\n        program->attributeLocation(\"color\"), new GLfloat[npoints*3]);\n\n    return initialize(npoints, npoints, 3);\n}\n\n\nQVector3D\nCloud::compute_gravity_center() const\n{\n    QVector3D gcenter(0.0f, 0.0f, 0.0f);\n    size_t npoints = into_points.size()/3;\n\n    for(size_t i=0; i < npoints; ++i){\n        size_t idx = (i*3);\n        gcenter += QVector3D(\n            into_points[idx+0],\n            into_points[idx+1],\n            into_points[idx+2]\n        );\n    }\n\n    return model_matrix() * (gcenter/float(npoints));\n}\n\nstd::deque<float>\nCloud::compute_deviations() const\n{\n    std::deque<float> deviations(into_points.size());\n    QVector3D gcenter = compute_gravity_center();\n    size_t npoints = points_into_cloud();\n\n    std::cerr << gcenter[0] << \" \" << gcenter[1] << \" \" << gcenter[2] << std::endl;\n\n    for(size_t i=0; i < npoints; ++i){\n        size_t idx = (i*3);\n\n        QVector3D p(\n            into_points[idx+0],\n            into_points[idx+1],\n            into_points[idx+2]\n        );\n\n        p = model_matrix() * p;\n\n        deviations[idx+0] = p[0] - gcenter.x();\n        deviations[idx+1] = p[1] - gcenter.y();\n        deviations[idx+2] = p[2] - gcenter.z();\n    }\n\n    return deviations;\n}\n\nstd::deque<float>\nCloud::compute_correlation_matrix() const\n{\n    std::deque<float> deviations = compute_deviations();\n    size_t npoints = points_into_cloud();\n\n    //          | x0, y0, z0 |\n    // matrix   | x1, y1, z1 |\n    //          | x2, y2, z2 |\n    //\n    //          | x0, x1, x2 |\n    // t_matrix | y0, y1, y2 |\n    //          | z0, z1, z2 |\n    std::deque<std::deque<float>> matrix(npoints);\n\n    std::deque<std::deque<float>> t_matrix(3);\n    t_matrix[0] = std::deque<float>(npoints); // x\n    t_matrix[1] = std::deque<float>(npoints); // y\n    t_matrix[2] = std::deque<float>(npoints); // z\n\n    for(size_t i=0; i < npoints; ++i){\n        size_t idx = (i*3);\n        matrix[i] = std::deque<float>(3);\n        matrix[i][0] = t_matrix[0][i] = deviations[idx+0];\n        matrix[i][1] = t_matrix[1][i] = deviations[idx+1];\n        matrix[i][2] = t_matrix[2][i] = deviations[idx+2];\n    }\n\n    std::cerr << matrix.size() << \" \" << t_matrix[0].size() << std::endl;\n\n    // Correlation matrix (out)[3*3] = t_matrix[3*npts] * matrix[npts*3];\n    std::deque<float> out(9);\n    for(size_t i=0; i < 3; ++i){\n        for(size_t j=0; j < 3; ++j){\n            out[(i*3)+j] = 0.0f;\n            for(size_t h=0; h < npoints; ++h){\n                out[(i*3)+j] += (t_matrix[i][h] * matrix[h][j]);\n            }\n        }\n    }\n\n    return out;\n}\n\n// Compute determinant of a matrix (3x3)\nfloat\nCloud::compute_determinant(const std::deque<float>& mat)\n{\n    if(mat.size() != 9)\n        return 0;\n\n    return + mat[0]*((mat[4]*mat[8]) - (mat[5]*mat[7]))\n           - mat[1]*((mat[3]*mat[8]) - (mat[5]*mat[6]))\n           + mat[2]*((mat[3]*mat[7]) - (mat[4]*mat[6]));\n}\n\n//https://en.wikipedia.org/wiki/Eigenvalue_algorithm#3%C3%973_matrices\nstd::deque<float>\nCloud::eigenvalues(const std::deque<float>& matrix)\n{\n    std::deque<float> eigenvalues(3);\n    if( matrix.size() == 9 ){\n        float r0 = (matrix[1]*matrix[1]) +\n                   (matrix[2]*matrix[2]) +\n                   (matrix[5]*matrix[5]);\n\n        if( r0 == 0.0f ){\n            eigenvalues[0] = matrix[0];\n            eigenvalues[1] = matrix[4];\n            eigenvalues[2] = matrix[8];\n        }\n        else {\n            float q = (matrix[0] + matrix[4] + matrix[8])/3;\n            float r1 = (\n                std::pow(matrix[0] - q, 2.0f) +\n                std::pow(matrix[4] - q, 2.0f) +\n                std::pow(matrix[8] - q, 2.0f) +\n                2 * r0\n            );\n\n            float p = std::sqrt(r1/6);\n            std::deque<float> A_minus_LambdaI = matrix;\n            A_minus_LambdaI[0] -= q;\n            A_minus_LambdaI[4] -= q;\n            A_minus_LambdaI[8] -= q;\n\n            for(size_t i = 0; i < 9; ++i)\n                A_minus_LambdaI[i] *= (1/p);\n\n            float det = Cloud::compute_determinant(A_minus_LambdaI)/2.0f;\n            float phi;\n            const float PI = std::atan(1.0f) * 4.0f;\n\n            if( det <= -1 ){\n                phi = PI / 3.0f;\n            }\n            else\n            if( det >= 1 ){\n                phi = 0.0f;\n            }\n            else {\n                phi = std::acos(det) / 3.0f;\n            }\n\n            eigenvalues[0] = q + 2 * p * std::cos(phi);\n            eigenvalues[2] = q + 2 * p * std::cos(phi + (2*PI/3));\n            eigenvalues[1] = 3 * q - eigenvalues[0] - eigenvalues[2];\n        }\n    }\n\n    return eigenvalues;\n}\n\n// Naive test\nbool\nCloud::into(float x, float y, float z)\n{\n    return (  (x >= -Ox && x <= Ox)\n           && (y >= -Oy && y <= Oy)\n           && (z >= -Oz && z <= Oz) );\n}\n\n// Compute euclidean distance between two 3D points.\nfloat\nCloud::distance(float x, float y, float z, float xx, float yy, float zz)\n{\n    return std::sqrt(\n                std::pow(xx-x, 2.0f) +\n                std::pow(yy-y, 2.0f) +\n                std::pow(zz-z, 2.0f));\n}\n\n// ELLIPSOID CLOUD CLASS\nEllipsoidCloud::EllipsoidCloud(float _Ox, float _Oy, float _Oz, size_t _total_points, float _dmin):\n    Cloud(_Ox, _Oy, _Oz, _total_points, _dmin)\n{}\n\n// Maths from https://en.wikipedia.org/wiki/Ellipsoid\nbool\nEllipsoidCloud::into(float x, float y, float z)\n{\n    return (((x*x)/(Ox*Ox)) + ((y*y)/(Oy*Oy)) + ((z*z)/(Oz*Oz))) <= 1.0f;\n}\n\n#endif // CLOUD_CPP\n", "meta": {"hexsha": "cb59f3b74e7164221b847ebb7337d8c248913f63", "size": 7734, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cloud.cpp", "max_stars_repo_name": "spokendotcpp/FIG", "max_stars_repo_head_hexsha": "2039720370f31330a4238753cf70454eb79791f5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cloud.cpp", "max_issues_repo_name": "spokendotcpp/FIG", "max_issues_repo_head_hexsha": "2039720370f31330a4238753cf70454eb79791f5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cloud.cpp", "max_forks_repo_name": "spokendotcpp/FIG", "max_forks_repo_head_hexsha": "2039720370f31330a4238753cf70454eb79791f5", "max_forks_repo_licenses": ["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.2323943662, "max_line_length": 99, "alphanum_fraction": 0.5120248254, "num_tokens": 2363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195385342972, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.47556132882634333}}
{"text": "//  Copyright (c) 2018-2019 Cem Bassoy\n//\n//  Distributed under the Boost Software License, Version 1.0. (See\n//  accompanying file LICENSE_1_0.txt or copy at\n//  http://www.boost.org/LICENSE_1_0.txt)\n//\n//  The authors gratefully acknowledge the support of\n//  Fraunhofer and Google in producing this work\n//  which started as a Google Summer of Code project.\n//\n\n\n\n#include <boost/numeric/ublas/tensor.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include <boost/multiprecision/cpp_bin_float.hpp>\n#include \"utility.hpp\"\n\nBOOST_AUTO_TEST_SUITE(test_tensor_arithmetic_operations/*, * boost::unit_test::depends_on(\"test_tensor\")*/)\n\nusing double_extended = boost::multiprecision::cpp_bin_float_double_extended;\n\nusing test_types = zip<int,float,double_extended>::with_t<boost::numeric::ublas::layout::first_order, boost::numeric::ublas::layout::last_order>;\n\nstruct fixture\n{\n  using extents_type = boost::numeric::ublas::extents<>;\n\n  std::vector<extents_type> extents =\n    {\n//      extents_type{},    // 0\n      extents_type{1,1}, // 1\n      extents_type{1,2}, // 2\n      extents_type{2,1}, // 3\n      extents_type{2,3}, // 4\n      extents_type{2,3,1}, // 5\n      extents_type{4,1,3}, // 6\n      extents_type{1,2,3}, // 7\n      extents_type{4,2,3}, // 8\n      extents_type{4,2,3,5} // 9\n  };\n};\n\n\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_binary_arithmetic_operations, value,  test_types, fixture)\n{\n    namespace ublas = boost::numeric::ublas;\n    using value_type  = typename value::first_type;\n    using layout_type = typename value::second_type;\n    using tensor_type  = ublas::tensor_dynamic<value_type,layout_type>;\n\n\n    auto check = [](auto const& e)\n    {\n        auto t  = tensor_type (e);\n        auto t2 = tensor_type (e);\n        auto r  = tensor_type (e);\n        auto v  = value_type  {};\n\n        std::iota(t.begin(), t.end(), v);\n        std::iota(t2.begin(), t2.end(), v+2);\n\n        r = t + t + t + t2;\n\n        for(auto i = 0ul; i < t.size(); ++i)\n            BOOST_CHECK_EQUAL ( r(i), 3*t(i) + t2(i) );\n\n\n        r = t2 / (t+3) * (t+1) - t2; // r = ( t2/ ((t+3)*(t+1)) ) - t2\n\n        for(auto i = 0ul; i < t.size(); ++i)\n            BOOST_CHECK_EQUAL ( r(i), t2(i) / (t(i)+3)*(t(i)+1) - t2(i) );\n\n        r = 3+t2 / (t+3) * (t+1) * t - t2; // r = 3+( t2/ ((t+3)*(t+1)*t) ) - t2\n\n        for(auto i = 0ul; i < t.size(); ++i)\n            BOOST_CHECK_EQUAL ( r(i), 3+t2(i) / (t(i)+3)*(t(i)+1)*t(i) - t2(i) );\n\n        r = t2 - t + t2 - t;\n\n        for(auto i = 0ul; i < r.size(); ++i)\n            BOOST_CHECK_EQUAL ( r(i), 4 );\n\n\n        r = t * t * t * t2;\n\n        for(auto i = 0ul; i < t.size(); ++i)\n            BOOST_CHECK_EQUAL ( r(i), t(i)*t(i)*t(i)*t2(i) );\n\n        r = (t2/t2) * (t2/t2);\n\n        for(auto i = 0ul; i < t.size(); ++i)\n            BOOST_CHECK_EQUAL ( r(i), 1 );\n    };\n\n    for(auto const& e : extents)\n        check(e);\n\n\n    BOOST_CHECK_NO_THROW ( tensor_type t = tensor_type(extents.at(0)) + tensor_type(extents.at(0))  );\n    BOOST_CHECK_THROW    ( tensor_type t = tensor_type(extents.at(0)) + tensor_type(extents.at(2)), std::runtime_error  );\n    BOOST_CHECK_THROW    ( tensor_type t = tensor_type(extents.at(1)) + tensor_type(extents.at(2)), std::runtime_error  );\n\n\n}\n\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_unary_arithmetic_operations, value,  test_types, fixture)\n{\n    namespace ublas = boost::numeric::ublas;\n    using value_type  = typename value::first_type;\n    using layout_type = typename value::second_type;\n    using tensor_type  = ublas::tensor_dynamic<value_type,layout_type>;\n\n\n    auto check = [](auto const& e)\n    {\n        auto t  = tensor_type (e);\n        auto t2 = tensor_type (e);\n        auto v  = value_type  {};\n\n        std::iota(t.begin(), t.end(), v);\n        std::iota(t2.begin(), t2.end(), v+2);\n\n        tensor_type r1 = t + 2 + t + 2;\n\n        for(auto i = 0ul; i < t.size(); ++i)\n            BOOST_CHECK_EQUAL ( r1(i), 2*t(i) + 4 );\n\n        tensor_type r2 = 2 + t + 2 + t;\n\n        for(auto i = 0ul; i < t.size(); ++i)\n            BOOST_CHECK_EQUAL ( r2(i), 2*t(i) + 4 );\n\n        tensor_type r3 = (t-2) + (t-2);\n\n        for(auto i = 0ul; i < t.size(); ++i)\n            BOOST_CHECK_EQUAL ( r3(i), 2*t(i) - 4 );\n\n        tensor_type r4 = (t*2) * (3*t);\n\n        for(auto i = 0ul; i < t.size(); ++i)\n            BOOST_CHECK_EQUAL ( r4(i), 2*3*t(i)*t(i) );\n\n        tensor_type r5 = (t2*2) / (2*t2) * t2;\n\n        for(auto i = 0ul; i < t.size(); ++i)\n            BOOST_CHECK_EQUAL ( r5(i), (t2(i)*2) / (2*t2(i)) * t2(i) );\n\n        tensor_type r6 = (t2/2+1) / (2/t2+1) / t2;\n\n        for(auto i = 0ul; i < t.size(); ++i)\n            BOOST_CHECK_EQUAL ( r6(i), (t2(i)/2+1) / (2/t2(i)+1) / t2(i) );\n\n    };\n\n    for(auto const& e : extents)\n        check(e);\n\n    BOOST_CHECK_NO_THROW ( tensor_type t = tensor_type(extents.at(0)) + 2 + tensor_type(extents.at(0))  );\n    BOOST_CHECK_THROW    ( tensor_type t = tensor_type(extents.at(0)) + 2 + tensor_type(extents.at(2)), std::runtime_error  );\n    BOOST_CHECK_THROW    ( tensor_type t = tensor_type(extents.at(1)) + 2 + tensor_type(extents.at(2)), std::runtime_error  );\n    BOOST_CHECK_THROW    ( tensor_type t = tensor_type(extents.at(2)) + 2 + tensor_type(extents.at(2)) + tensor_type(extents.at(1)), std::runtime_error  );\n    BOOST_CHECK_THROW    ( tensor_type t = tensor_type(extents.at(2)) + 2 + tensor_type(extents.at(2)) + 2 + tensor_type(extents.at(1)), std::runtime_error  );\n}\n\n\n\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_assign_arithmetic_operations, value,  test_types, fixture)\n{\n    namespace ublas = boost::numeric::ublas;\n    using value_type  = typename value::first_type;\n    using layout_type = typename value::second_type;\n    using tensor_type  = ublas::tensor_dynamic<value_type,layout_type>;\n\n\n    auto check = [](auto const& e)\n    {\n        auto t  = tensor_type (e);\n        auto t2 = tensor_type (e);\n        auto r  = tensor_type (e);\n        auto v  = value_type  {};\n\n        std::iota(t.begin(), t.end(), v);\n        std::iota(t2.begin(), t2.end(), v+2);\n\n        r  = t + 2;\n        r += t;\n        r += 2;\n\n        for(auto i = 0ul; i < t.size(); ++i)\n            BOOST_CHECK_EQUAL ( r(i), 2*t(i) + 4 );\n\n        r  = 2 + t;\n        r += t;\n        r += 2;\n        (void)r;\n        for(auto i = 0ul; i < t.size(); ++i)\n            BOOST_CHECK_EQUAL ( r(i), 2*t(i) + 4 );\n\n        for(auto i = 0ul; i < t.size(); ++i)\n            BOOST_CHECK_EQUAL ( r(i), 2*t(i) + 4 );\n\n        r = (t-2);\n        r += t;\n        r -= 2;\n\n        for(auto i = 0ul; i < t.size(); ++i)\n            BOOST_CHECK_EQUAL ( r(i), 2*t(i) - 4 );\n\n        r  = (t*2);\n        r *= 3;\n        r *= t;\n\n        for(auto i = 0ul; i < t.size(); ++i)\n            BOOST_CHECK_EQUAL ( r(i), 2*3*t(i)*t(i) );\n\n        r  = (t2*2);\n        r /= 2;\n        r /= t2;\n        r *= t2;\n\n        for(auto i = 0ul; i < t.size(); ++i)\n            BOOST_CHECK_EQUAL ( r(i), (t2(i)*2) / (2*t2(i)) * t2(i) );\n\n        r  = (t2/2+1);\n        r /= (2/t2+1);\n        r /= t2;\n\n        for(auto i = 0ul; i < t.size(); ++i)\n            BOOST_CHECK_EQUAL ( r(i), (t2(i)/2+1) / (2/t2(i)+1) / t2(i) );\n\n        tensor_type q = -r;\n        for(auto i = 0ul; i < t.size(); ++i)\n            BOOST_CHECK_EQUAL ( q(i), -r(i) );\n\n        tensor_type p = +r;\n        for(auto i = 0ul; i < t.size(); ++i)\n            BOOST_CHECK_EQUAL ( p(i), r(i) );\n        \n    };\n\n    for(auto const& e : extents)\n        check(e);\n\n    auto r  = tensor_type (extents.at(0));\n\n    BOOST_CHECK_NO_THROW ( r += tensor_type(extents.at(0)) + 2 + tensor_type(extents.at(0))  );\n    BOOST_CHECK_THROW    ( r += tensor_type(extents.at(0)) + 2 + tensor_type(extents.at(2)), std::runtime_error  );\n    BOOST_CHECK_THROW    ( r += tensor_type(extents.at(1)) + 2 + tensor_type(extents.at(2)), std::runtime_error  );\n    BOOST_CHECK_THROW    ( r += tensor_type(extents.at(2)) + 2 + tensor_type(extents.at(2)) + tensor_type(extents.at(1)), std::runtime_error  );\n    BOOST_CHECK_THROW    ( r += tensor_type(extents.at(2)) + 2 + tensor_type(extents.at(2)) + 2 + tensor_type(extents.at(1)), std::runtime_error  );\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "98484ccf710b9b5f8d34a129f9b58d16b0d47141", "size": 8143, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/tensor/test_operators_arithmetic.cpp", "max_stars_repo_name": "samd2/ublas", "max_stars_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 96.0, "max_stars_repo_stars_event_min_datetime": "2015-01-23T10:15:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T18:31:02.000Z", "max_issues_repo_path": "test/tensor/test_operators_arithmetic.cpp", "max_issues_repo_name": "samd2/ublas", "max_issues_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 105.0, "max_issues_repo_issues_event_min_datetime": "2015-01-14T09:01:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-05T06:10:39.000Z", "max_forks_repo_path": "test/tensor/test_operators_arithmetic.cpp", "max_forks_repo_name": "samd2/ublas", "max_forks_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 157.0, "max_forks_repo_forks_event_min_datetime": "2015-01-26T13:35:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T11:12:27.000Z", "avg_line_length": 30.9619771863, "max_line_length": 159, "alphanum_fraction": 0.5491833477, "num_tokens": 2602, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195385342971, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.4755613288263433}}
{"text": "\r\n// Copyright 2016, 2017 Peter Dimov.\r\n//\r\n// Distributed under the Boost Software License, Version 1.0.\r\n//\r\n// See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt\r\n\r\n\r\n#include <boost/mp11/map.hpp>\r\n#include <boost/mp11/list.hpp>\r\n#include <boost/mp11/integral.hpp>\r\n#include <boost/core/lightweight_test_trait.hpp>\r\n#include <type_traits>\r\n#include <tuple>\r\n#include <utility>\r\n\r\nusing boost::mp11::mp_int;\r\n\r\nstruct Q_inc\r\n{\r\n    template<class T, class U> using fn = mp_int<U::value + 1>;\r\n};\r\n\r\nint main()\r\n{\r\n    using boost::mp11::mp_map_update_q;\r\n    using boost::mp11::mp_list;\r\n\r\n    using M1 = mp_list<>;\r\n\r\n    using M2 = mp_map_update_q<M1, std::pair<char, mp_int<0>>, Q_inc>;\r\n    BOOST_TEST_TRAIT_TRUE((std::is_same<M2, mp_list<std::pair<char, mp_int<0>>>>));\r\n\r\n    using M3 = mp_map_update_q<M2, std::pair<char, mp_int<0>>, Q_inc>;\r\n    BOOST_TEST_TRAIT_TRUE((std::is_same<M3, mp_list<std::pair<char, mp_int<1>>>>));\r\n\r\n    using M4 = mp_map_update_q<M3, std::pair<int, mp_int<0>>, Q_inc>;\r\n    BOOST_TEST_TRAIT_TRUE((std::is_same<M4, mp_list<std::pair<char, mp_int<1>>, std::pair<int, mp_int<0>>>>));\r\n\r\n    using M5 = mp_map_update_q<M4, std::pair<long, mp_int<0>>, Q_inc>;\r\n    BOOST_TEST_TRAIT_TRUE((std::is_same<M5, mp_list<std::pair<char, mp_int<1>>, std::pair<int, mp_int<0>>, std::pair<long, mp_int<0>>>>));\r\n\r\n    using M6 = mp_map_update_q<M5, std::pair<long, mp_int<0>>, Q_inc>;\r\n    BOOST_TEST_TRAIT_TRUE((std::is_same<M6, mp_list<std::pair<char, mp_int<1>>, std::pair<int, mp_int<0>>, std::pair<long, mp_int<1>>>>));\r\n\r\n    using M7 = mp_map_update_q<M6, std::pair<char, mp_int<0>>, Q_inc>;\r\n    BOOST_TEST_TRAIT_TRUE((std::is_same<M7, mp_list<std::pair<char, mp_int<2>>, std::pair<int, mp_int<0>>, std::pair<long, mp_int<1>>>>));\r\n\r\n    return boost::report_errors();\r\n}\r\n", "meta": {"hexsha": "6e03d4c1b8a3bbe9663c6f3a3f369294b92f333f", "size": 1844, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/mp11/test/mp_map_update_q.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": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/mp11/test/mp_map_update_q.cpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-04T18:00:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-04T18:00:00.000Z", "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/mp11/test/mp_map_update_q.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 35.4615384615, "max_line_length": 139, "alphanum_fraction": 0.6610629067, "num_tokens": 565, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195385342972, "lm_q2_score": 0.647798211152541, "lm_q1q2_score": 0.4755613238346466}}
{"text": "#include <big_types.h>\n#include <big_absolute_convergence.h>\n#include <big_relative_convergence.h>\n#include <big_stagnation.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n\nBOOST_AUTO_TEST_SUITE(big_stop_criteria);\n\nBOOST_AUTO_TEST_CASE(absolute_testing)\n{\n  BOOST_CHECK(  big::absolute_convergence(  1.0,   0.01) == false  );\n  BOOST_CHECK(  big::absolute_convergence(  0.01,  0.01) == true   );\n  BOOST_CHECK(  big::absolute_convergence(  0.005, 0.01) == true   );\n  BOOST_CHECK(  big::absolute_convergence(  0.0,   0.01) == true   );\n  BOOST_CHECK(  big::absolute_convergence(  0.0,   0.0 ) == true   );\n\n//  BOOST_CHECK_THROW(  big::absolute_convergence( -1.0,   0.01), std::invalid_argument  ); // 2012-09-30 Kenny: Should we throw an exception?\n//  BOOST_CHECK_THROW(  big::absolute_convergence(  1.0,  -0.01), std::invalid_argument  ); // 2012-09-30 Kenny: Should we throw an exception?\n  \n}\n\nBOOST_AUTO_TEST_CASE(relative_testing)\n{\n  \n  // Test is:  fabs(old - new) / fabs(old) <= tol\n  \n  BOOST_CHECK(  big::relative_convergence(  1.0, 1.0, 0.01 ) == true   );\n  BOOST_CHECK(  big::relative_convergence(  1.0, 1.0, 0.0  ) == true   );\n  \n  BOOST_CHECK(  big::relative_convergence(  1.0, 1.1, 0.11 ) == true   );\n  BOOST_CHECK(  big::relative_convergence(  1.0, 1.1, 0.09 ) == false  );\n  BOOST_CHECK(  big::relative_convergence(  1.0, 0.9, 0.11 ) == true   );\n  BOOST_CHECK(  big::relative_convergence(  1.0, 0.9, 0.09 ) == false  );\n\n  BOOST_CHECK(  big::relative_convergence(  0.0, 0.0, 0.11 ) == true   );\n  BOOST_CHECK(  big::relative_convergence(  0.0, .1, 0.11  ) == false  );\n  \n  \n  //  BOOST_CHECK_THROW(  big::relative_convergence( 1.0, 1.0, -0.01), std::invalid_argument  ); // 2012-09-30 Kenny: Should we throw an exception?\n}\n\nBOOST_AUTO_TEST_CASE(stagnation_testing)\n{\n  typedef ublas::vector<double>            vector_type;\n  vector_type x;\n  vector_type y;\n  \n  \n  x.resize(2);\n  y.resize(2);\n  \n  x(0) = 0.01;\n  x(1) = 0.01;\n  \n  y(0) = 0.01;\n  y(1) = 0.01;\n\n  BOOST_CHECK(  big::stagnation(  x, y, 0.01 ) == true   );\n\n  \n  x(0) = 0.01;\n  x(1) = 0.01;\n  \n  y(0) = 0.01 + 2*0.01;\n  y(1) = 0.01;\n  \n  BOOST_CHECK(  big::stagnation(  x, y, 0.01 ) == false   );\n  \n  BOOST_CHECK(  big::stagnation(  x, y, 0.0  ) == false  );\n  BOOST_CHECK(  big::stagnation(  x, x, 0.0  ) == true   );\n\n  //  BOOST_CHECK_THROW(  big::stagnation( x, y, -0.01), std::invalid_argument  ); // 2012-09-30 Kenny: Should we throw an exception?\n\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "30ef9f4674333c76529ffc2108b7abe2b0fdaeae", "size": 2634, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/FOUNDATION/BIG/unit_tests/big_stop_criteria/unit_big_stop_criteria.cpp", "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/FOUNDATION/BIG/unit_tests/big_stop_criteria/unit_big_stop_criteria.cpp", "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/FOUNDATION/BIG/unit_tests/big_stop_criteria/unit_big_stop_criteria.cpp", "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.1219512195, "max_line_length": 147, "alphanum_fraction": 0.6431283219, "num_tokens": 947, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.734119526900183, "lm_q1q2_score": 0.4755613212897849}}
{"text": "//  (C) Copyright Eric Niebler, Olivier Gygi 2006.\r\n//  Use, modification and distribution are subject to the\r\n//  Boost Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n// Test case for weighted_p_square_cumul_dist.hpp\r\n\r\n#include <cmath>\r\n#include <boost/random.hpp>\r\n#include <boost/test/unit_test.hpp>\r\n#include <boost/test/floating_point_comparison.hpp>\r\n#include <boost/accumulators/numeric/functional/vector.hpp>\r\n#include <boost/accumulators/numeric/functional/complex.hpp>\r\n#include <boost/accumulators/numeric/functional/valarray.hpp>\r\n#include <boost/accumulators/accumulators.hpp>\r\n#include <boost/accumulators/statistics/stats.hpp>\r\n#include <boost/accumulators/statistics/weighted_p_square_cumul_dist.hpp>\r\n\r\nusing namespace boost;\r\nusing namespace unit_test;\r\nusing namespace boost::accumulators;\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// erf() not known by VC++ compiler!\r\n// my_erf() computes error function by numerically integrating with trapezoidal rule\r\n//\r\ndouble my_erf(double const& x, int const& n = 1000)\r\n{\r\n    double sum = 0.;\r\n    double delta = x/n;\r\n    for (int i = 1; i < n; ++i)\r\n        sum += std::exp(-i*i*delta*delta) * delta;\r\n    sum += 0.5 * delta * (1. + std::exp(-x*x));\r\n    return sum * 2. / std::sqrt(3.141592653);\r\n}\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// test_stat\r\n//\r\nvoid test_stat()\r\n{\r\n    // tolerance in %\r\n    double epsilon = 4;\r\n\r\n    typedef accumulator_set<double, stats<tag::weighted_p_square_cumulative_distribution>, double > accumulator_t;\r\n\r\n    accumulator_t acc_upper(p_square_cumulative_distribution_num_cells = 100);\r\n    accumulator_t acc_lower(p_square_cumulative_distribution_num_cells = 100);\r\n\r\n    // two random number generators\r\n    double mu_upper = 1.0;\r\n    double mu_lower = -1.0;\r\n    boost::lagged_fibonacci607 rng;\r\n    boost::normal_distribution<> mean_sigma_upper(mu_upper,1);\r\n    boost::normal_distribution<> mean_sigma_lower(mu_lower,1);\r\n    boost::variate_generator<boost::lagged_fibonacci607&, boost::normal_distribution<> > normal_upper(rng, mean_sigma_upper);\r\n    boost::variate_generator<boost::lagged_fibonacci607&, boost::normal_distribution<> > normal_lower(rng, mean_sigma_lower);\r\n\r\n    for (std::size_t i=0; i<100000; ++i)\r\n    {\r\n        double sample = normal_upper();\r\n        acc_upper(sample, weight = std::exp(-mu_upper * (sample - 0.5 * mu_upper)));\r\n    }\r\n\r\n    for (std::size_t i=0; i<100000; ++i)\r\n    {\r\n        double sample = normal_lower();\r\n        acc_lower(sample, weight = std::exp(-mu_lower * (sample - 0.5 * mu_lower)));\r\n    }\r\n\r\n    typedef iterator_range<std::vector<std::pair<double, double> >::iterator > histogram_type;\r\n    histogram_type histogram_upper = weighted_p_square_cumulative_distribution(acc_upper);\r\n    histogram_type histogram_lower = weighted_p_square_cumulative_distribution(acc_lower);\r\n\r\n    // Note that applying importance sampling results in a region of the distribution\r\n    // to be estimated more accurately and another region to be estimated less accurately\r\n    // than without importance sampling, i.e., with unweighted samples\r\n\r\n    for (std::size_t i = 0; i < histogram_upper.size(); ++i)\r\n    {\r\n        // problem with small results: epsilon is relative (in percent), not absolute!\r\n\r\n        // check upper region of distribution\r\n        if ( histogram_upper[i].second > 0.1 )\r\n            BOOST_CHECK_CLOSE( 0.5 * (1.0 + my_erf( histogram_upper[i].first / std::sqrt(2.0) )), histogram_upper[i].second, epsilon );\r\n        // check lower region of distribution\r\n        if ( histogram_lower[i].second < -0.1 )\r\n            BOOST_CHECK_CLOSE( 0.5 * (1.0 + my_erf( histogram_lower[i].first / std::sqrt(2.0) )), histogram_lower[i].second, epsilon );\r\n    }\r\n}\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// init_unit_test_suite\r\n//\r\ntest_suite* init_unit_test_suite( int argc, char* argv[] )\r\n{\r\n    test_suite *test = BOOST_TEST_SUITE(\"weighted_p_square_cumulative_distribution test\");\r\n\r\n    test->add(BOOST_TEST_CASE(&test_stat));\r\n\r\n    return test;\r\n}\r\n\r\n", "meta": {"hexsha": "cdd1327c6877146531ed61469ddffa64609bf01a", "size": 4233, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/accumulators/test/weighted_p_square_cumul_dist.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": 85.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T20:36:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T20:38:31.000Z", "max_issues_repo_path": "libs/boost/libs/accumulators/test/weighted_p_square_cumul_dist.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/accumulators/test/weighted_p_square_cumul_dist.cpp", "max_forks_repo_name": "flingone/frameworks_base_cmds_remoted", "max_forks_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2015-01-28T16:33:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-12T05:04:39.000Z", "avg_line_length": 40.7019230769, "max_line_length": 136, "alphanum_fraction": 0.6539097567, "num_tokens": 988, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195152660687, "lm_q2_score": 0.6477982043529716, "lm_q1q2_score": 0.47556130376983324}}
{"text": "/*    Copyright (c) 2010-2014, 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 *      150411    D. Dirkx          Migrated and updated from personal code.\n *\n *    References\n *\n *    Notes\n *\n */\n\n#define BOOST_TEST_MAIN\n\n#include <fstream>\n#include <limits>\n#include <map>\n\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/unit_test.hpp>\n\n#include <Eigen/Core>\n\n#include <Tudat/Astrodynamics/BasicAstrodynamics/orbitalElementConversions.h>\n#include <Tudat/Basics/testMacros.h>\n#include <Tudat/Mathematics/BasicMathematics/basicMathematicsFunctions.h>\n#include <Tudat/Mathematics/BasicMathematics/mathematicalConstants.h>\n\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/UnitTests/keplerPropagatorTestData.h\"\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/keplerPropagator.h\"\n#include \"Tudat/Astrodynamics/Ephemerides/keplerEphemeris.h\"\n#include \"Tudat/InputOutput/basicInputOutput.h\"\n\nnamespace tudat\n{\nnamespace unit_tests\n{\n\nBOOST_AUTO_TEST_SUITE( test_keplerEphemeris )\n\n//! Test 1: Comparison of KeplerEphemeris output with benchmark data from (Melman, 2010).\n//! (see testPropagateKeplerOrbit_Eccentric_Melman).\nBOOST_AUTO_TEST_CASE( testKeplerEphemerisElliptical )\n{\n    // Load the expected propagation history.\n    // Create expected propagation history.\n    PropagationHistory expectedPropagationHistory = getODTBXBenchmarkData( );\n\n    // Set Earth gravitational parameter [m^3 s^-2].\n    const double earthGravitationalParameter = 398600.4415e9;\n\n    // Compute propagation history.\n    PropagationHistory computedPropagationHistory;\n    computedPropagationHistory[ 0.0 ] = expectedPropagationHistory[ 0.0 ];\n\n    ephemerides::KeplerEphemeris keplerEphemeris(\n                expectedPropagationHistory[ 0.0 ],\n                0.0, earthGravitationalParameter );\n\n    for( PropagationHistory::iterator stateIterator = expectedPropagationHistory.begin( );\n         stateIterator != expectedPropagationHistory.end( ); stateIterator++ )\n    {\n        // Compute next entry.\n        computedPropagationHistory[ stateIterator->first ] =\n                orbital_element_conversions::convertCartesianToKeplerianElements(\n                    keplerEphemeris.getCartesianStateFromEphemeris( stateIterator->first ),\n                    earthGravitationalParameter );\n\n        // Check that computed results match expected results.\n        BOOST_CHECK_CLOSE_FRACTION(\n                    computedPropagationHistory[ stateIterator->first ]( 5 ),\n                    expectedPropagationHistory[ stateIterator->first ]( 5 ),\n                    2.0e-14 );\n    }\n}\n\n//! Test 2: Comparison of KeplerEphemeris with that of GTOP (hyperbolic).\n//! (see testPropagateKeplerOrbit_hyperbolic_GTOP).\nBOOST_AUTO_TEST_CASE( testKeplerEphemerisHyperbolic )\n{\n    // Load the expected propagation history.\n    PropagationHistory expectedPropagationHistory = getGTOPBenchmarkData( );\n\n    // Compute propagation history.\n    PropagationHistory computedPropagationHistory;\n    computedPropagationHistory[ 0.0 ] = expectedPropagationHistory[ 0.0 ];\n\n    ephemerides::KeplerEphemeris keplerEphemeris(\n                expectedPropagationHistory[ 0.0 ],\n                0.0, getGTOPGravitationalParameter( ) );\n\n    for( PropagationHistory::iterator stateIterator = expectedPropagationHistory.begin( );\n         stateIterator != expectedPropagationHistory.end( ); stateIterator++ )\n    {\n        // Compute next entry.\n        computedPropagationHistory[ stateIterator->first ] =\n                orbital_element_conversions::convertCartesianToKeplerianElements(\n                    keplerEphemeris.getCartesianStateFromEphemeris( stateIterator->first ),\n                    getGTOPGravitationalParameter( ) );\n\n        // Check that computed results match expected results.\n        BOOST_CHECK_CLOSE_FRACTION(\n                    computedPropagationHistory[ stateIterator->first ]( 5 ),\n                    expectedPropagationHistory[ stateIterator->first ]( 5 ),\n                    1.0e-15 );\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END( )\n\n} // namespace unit_tests\n\n} // namespace tudat\n\n", "meta": {"hexsha": "5942811209d10c7d48666c735b694204f45d2192", "size": 5745, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/Ephemerides/UnitTests/unitTestKeplerEphemeris.cpp", "max_stars_repo_name": "JPelamatti/ThesisTUDAT", "max_stars_repo_head_hexsha": "b94ce35fb7c8fa44ae83238e296a979dfa3adfe8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tudat/Astrodynamics/Ephemerides/UnitTests/unitTestKeplerEphemeris.cpp", "max_issues_repo_name": "JPelamatti/ThesisTUDAT", "max_issues_repo_head_hexsha": "b94ce35fb7c8fa44ae83238e296a979dfa3adfe8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tudat/Astrodynamics/Ephemerides/UnitTests/unitTestKeplerEphemeris.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.9343065693, "max_line_length": 99, "alphanum_fraction": 0.7209747607, "num_tokens": 1274, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195152660687, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.47556130376983313}}
{"text": "\n#include <boost/test/unit_test.hpp>\n#include \"a_star.h\"\n\nBOOST_AUTO_TEST_SUITE(a_star)\n\nBOOST_AUTO_TEST_CASE(simple_path_1)\n{\n\ttypedef math::a_star::point point;\n\n\tstruct dummy {\n\t\tstatic math::scalar score(point const &p) {\n\t\t\treturn (p - point(1, 0)).length_sq() + (p.x == 0 && (p.y == 0 || p.y == -1) ? 1000.0f : 0.0f);\n\t\t}\n\t};\n\n\tmath::a_star a_star(point(-1, 0), point(1, 0), &dummy::score);\n\ta_star.calculate_path();\n\tBOOST_REQUIRE(!a_star.have_failed());\n\n\tstd::vector<point> path = a_star.build_path();\n\tBOOST_REQUIRE(path.size() == 3);\n\tBOOST_REQUIRE(path[0] == point(-1, 0));\n\tBOOST_REQUIRE(path[1] == point( 0, 1));\n\tBOOST_REQUIRE(path[2] == point( 1, 0));\n}\n\nBOOST_AUTO_TEST_CASE(simple_path_2)\n{\n\ttypedef math::a_star::point point;\n\n\tstruct dummy {\n\t\tstatic math::scalar score(point const &p) {\n\t\t\treturn (p - point(1, 0)).length_sq() + (p.x == 0 && (p.y == 0 || p.y == -1) ? 1000.0f : 0.0f);\n\t\t}\n\t};\n\n\tmath::a_star a_star(point(-2, 0), point(1, 0), &dummy::score);\n\ta_star.calculate_path();\n\tBOOST_REQUIRE(!a_star.have_failed());\n\n\tstd::vector<point> path = a_star.build_path();\n\tBOOST_REQUIRE(path.size() == 4);\n\tBOOST_REQUIRE(path[0] == point(-2, 0));\n\tBOOST_REQUIRE(path[1] == point(-1, 0));\n\tBOOST_REQUIRE(path[2] == point( 0, 1));\n\tBOOST_REQUIRE(path[3] == point( 1, 0));\n}\n\nBOOST_AUTO_TEST_CASE(simple_path_3)\n{\n\ttypedef math::a_star::point point;\n\n\tstruct dummy {\n\t\tstatic math::scalar score(point const &p) {\n\t\t\treturn (p - point(1, 0)).length_sq() + (p.x == 0 && (p.y == 0 || p.y == -1) ? 1000.0f : 0.0f);\n\t\t}\n\t};\n\n\tmath::a_star a_star(point(-1, 0), point(2, 0), &dummy::score);\n\ta_star.calculate_path();\n\tBOOST_REQUIRE(!a_star.have_failed());\n\n\tstd::vector<point> path = a_star.build_path();\n\tBOOST_REQUIRE(path.size() == 4);\n\tBOOST_REQUIRE(path[0] == point(-1, 0));\n\tBOOST_REQUIRE(path[1] == point( 0, 1));\n\tBOOST_REQUIRE(path[2] == point( 1, 0));\n\tBOOST_REQUIRE(path[3] == point( 2, 0));\n}\n\nBOOST_AUTO_TEST_CASE(simple_path_without_obstacles)\n{\n\ttypedef math::a_star::point point;\n\n\tstruct dummy {\n\t\tstatic math::scalar score(point const &p) {\n\t\t\treturn math::scalar((p - point(10, 0)).length_sq());\n\t\t}\n\t};\n\n\tmath::a_star a_star(point(0, 0), point(10, 0), &dummy::score);\n\ta_star.calculate_path();\n\tBOOST_REQUIRE(!a_star.have_failed());\n\n\tstd::vector<point> path = a_star.build_path();\n\n\tfor (int i = 0; i <= 10; ++i)\n\t{\n\t\tBOOST_REQUIRE (path[i] == point(i, 0));\n\t}\n}\n\nBOOST_AUTO_TEST_CASE(simple_path_4)\n{\n\ttypedef math::a_star::point point;\n\n\tstruct dummy {\n\t\tstatic math::scalar score(point const &p) {\n\t\t\treturn (p - point(10, 0)).length_sq() + (p.x == 5 && (p.y > -5 && p.y < 3) ? 1000.0f : 0.0f);\n\t\t}\n\t};\n\n\tmath::a_star a_star(point(0, 0), point(10, 0), &dummy::score);\n\ta_star.calculate_path();\n\tBOOST_REQUIRE(!a_star.have_failed());\n\n\tstd::vector<point> path = a_star.build_path();\n\n\tBOOST_REQUIRE(path.size() == 12);\n\tBOOST_REQUIRE(path[0] == point(0, 0));\n\tBOOST_REQUIRE(path[1] == point(1, 0));\n\tBOOST_REQUIRE(path[2] == point(2, 0));\n\tBOOST_REQUIRE(path[3] == point(3, 0));\n\tBOOST_REQUIRE(path[4] == point(4, 1));\n\tBOOST_REQUIRE(path[5] == point(4, 2));\n\tBOOST_REQUIRE(path[6] == point(5, 3));\n\tBOOST_REQUIRE(path[7] == point(6, 2));\n\tBOOST_REQUIRE(path[8] == point(7, 1));\n\tBOOST_REQUIRE(path[9] == point(8, 0));\n\tBOOST_REQUIRE(path[10] == point(9, 0));\n\tBOOST_REQUIRE(path[11] == point(10, 0));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "855c5c03d3d917f21dc99398999f4fda61fd0ced", "size": 3367, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/math/test_a_star.cc", "max_stars_repo_name": "mnvl/scratch", "max_stars_repo_head_hexsha": "7717772e0b9a85c8feb73fdc3562425f48b4a727", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-08-15T11:55:32.000Z", "max_stars_repo_stars_event_max_datetime": "2016-08-15T11:55:32.000Z", "max_issues_repo_path": "src/math/test_a_star.cc", "max_issues_repo_name": "mnvl/scratch", "max_issues_repo_head_hexsha": "7717772e0b9a85c8feb73fdc3562425f48b4a727", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/math/test_a_star.cc", "max_forks_repo_name": "mnvl/scratch", "max_forks_repo_head_hexsha": "7717772e0b9a85c8feb73fdc3562425f48b4a727", "max_forks_repo_licenses": ["BSD-3-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.7222222222, "max_line_length": 97, "alphanum_fraction": 0.6385506386, "num_tokens": 1111, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387914176259, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4755442857360717}}
{"text": "#include <gtest/gtest.h>\n#include <Eigen/Dense>\n\n#include <memory>\n\n#include \"refill/filters/extended_kalman_filter.h\"\n#include \"refill/system_models/linear_system_model.h\"\n#include \"refill/measurement_models/linear_measurement_model.h\"\n\nnamespace refill {\n\nTEST(ExtendedKalmanFilterTest, ConstructorTest) {\n  ExtendedKalmanFilter filter_1;\n\n  EXPECT_EQ(GaussianDistribution().mean(), filter_1.state().mean());\n  EXPECT_EQ(GaussianDistribution().cov(), filter_1.state().cov());\n\n  GaussianDistribution initial_state(Eigen::Vector2d::Zero(),\n                                     Eigen::Matrix2d::Identity());\n\n  ExtendedKalmanFilter filter_2(initial_state);\n\n  EXPECT_EQ(Eigen::Vector2d::Zero(), filter_2.state().mean());\n  EXPECT_EQ(Eigen::Matrix2d::Identity(), filter_2.state().cov());\n\n  GaussianDistribution system_noise(Eigen::Vector2d::Zero(),\n                                    Eigen::Matrix2d::Identity());\n  GaussianDistribution measurement_noise(Eigen::Vector2d::Zero(),\n                                         Eigen::Matrix2d::Identity() * 2.0);\n\n  LinearSystemModel system_model(Eigen::Matrix2d::Identity(), system_noise);\n  LinearMeasurementModel measurement_model(Eigen::Matrix2d::Identity(),\n                                           measurement_noise);\n  ExtendedKalmanFilter filter_3(\n      initial_state,\n      std::unique_ptr<LinearSystemModel>(new LinearSystemModel(system_model)),\n      std::unique_ptr<LinearMeasurementModel>(\n          new LinearMeasurementModel(measurement_model)));\n\n  EXPECT_EQ(Eigen::Vector2d::Zero(), filter_3.state().mean());\n  EXPECT_EQ(Eigen::Matrix2d::Identity(), filter_3.state().cov());\n\n  filter_3.predict();\n\n  EXPECT_EQ(Eigen::Vector2d::Zero(), filter_3.state().mean());\n  EXPECT_EQ(Eigen::Matrix2d::Identity() * 2.0, filter_3.state().cov());\n\n  filter_3.update(Eigen::Vector2d::Constant(3.0));\n\n  EXPECT_EQ(Eigen::Vector2d::Constant(1.5), filter_3.state().mean());\n  EXPECT_EQ(Eigen::Matrix2d::Identity(), filter_3.state().cov());\n}\n\nTEST(ExtendedKalmanFilterTest, SetterTest) {\n  GaussianDistribution initial_state(Eigen::Vector2d::Zero(),\n                                     Eigen::Matrix2d::Identity());\n\n  ExtendedKalmanFilter filter_1(initial_state);\n\n  initial_state.setDistributionParameters(Eigen::Vector2d::Ones(),\n                             Eigen::Matrix2d::Identity() * 2.0);\n  filter_1.setState(initial_state);\n\n  EXPECT_EQ(Eigen::Vector2d::Ones(), filter_1.state().mean());\n  EXPECT_EQ(Eigen::Matrix2d::Identity() * 2.0, filter_1.state().cov());\n}\n\nTEST(ExtendedKalmanFilterTest, PredictionTest) {\n  GaussianDistribution initial_state(Eigen::Vector2d::Zero(),\n                                     Eigen::Matrix2d::Identity());\n  GaussianDistribution system_noise(Eigen::Vector2d::Zero(),\n                                    Eigen::Matrix2d::Identity());\n  GaussianDistribution measurement_noise(Eigen::Vector2d::Zero(),\n                                         Eigen::Matrix2d::Identity());\n\n  LinearSystemModel system_model(Eigen::Matrix2d::Identity(), system_noise,\n                                 Eigen::Matrix2d::Identity());\n  LinearMeasurementModel measurement_model(Eigen::Matrix2d::Identity(),\n                                           measurement_noise);\n\n  // object for testing ekf with standard models\n  ExtendedKalmanFilter filter_1(\n      initial_state,\n      std::unique_ptr<LinearSystemModel>(new LinearSystemModel(system_model)),\n      std::unique_ptr<LinearMeasurementModel>(\n          new LinearMeasurementModel(measurement_model)));\n\n  // test prediction with standard models\n  filter_1.predict();\n\n  EXPECT_EQ(Eigen::Vector2d::Zero(), filter_1.state().mean());\n  EXPECT_EQ(Eigen::Matrix2d::Identity() * 2.0, filter_1.state().cov());\n\n  filter_1.setState(initial_state);\n\n  // test prediction with standard models and input\n  filter_1.predict(Eigen::Vector2d::Ones());\n\n  EXPECT_EQ(Eigen::Vector2d::Ones(), filter_1.state().mean());\n  EXPECT_EQ(Eigen::Matrix2d::Identity() * 2.0, filter_1.state().cov());\n\n  // object for testing ekf with external model\n  ExtendedKalmanFilter filter_2(initial_state);\n\n  // test prediction with external model and no input\n  filter_2.predict(system_model);\n\n  EXPECT_EQ(Eigen::Vector2d::Zero(), filter_2.state().mean());\n  EXPECT_EQ(Eigen::Matrix2d::Identity() * 2.0, filter_2.state().cov());\n\n  filter_2.setState(initial_state);\n\n  // test prediction with external model and input\n  filter_2.predict(system_model, Eigen::Vector2d::Ones());\n\n  EXPECT_EQ(Eigen::Vector2d::Ones(), filter_2.state().mean());\n  EXPECT_EQ(Eigen::Matrix2d::Identity() * 2.0, filter_2.state().cov());\n}\n\nTEST(ExtendedKalmanFilterTest, UpdateTest) {\n  GaussianDistribution initial_state(Eigen::Vector2d::Zero(),\n                                     Eigen::Matrix2d::Identity());\n  GaussianDistribution system_noise(Eigen::Vector2d::Zero(),\n                                    Eigen::Matrix2d::Identity());\n  GaussianDistribution measurement_noise(Eigen::Vector2d::Zero(),\n                                         Eigen::Matrix2d::Identity());\n\n  LinearSystemModel system_model(Eigen::Matrix2d::Identity(), system_noise,\n                                 Eigen::Matrix2d::Identity());\n  LinearMeasurementModel measurement_model(Eigen::Matrix2d::Identity(),\n                                           measurement_noise);\n\n  // object for testing ekf with standard models\n  ExtendedKalmanFilter filter_1(\n      initial_state,\n      std::unique_ptr<LinearSystemModel>(new LinearSystemModel(system_model)),\n      std::unique_ptr<LinearMeasurementModel>(\n          new LinearMeasurementModel(measurement_model)));\n\n  // test update with standard models\n  filter_1.update(Eigen::Vector2d::Ones());\n\n  EXPECT_EQ(Eigen::Vector2d::Ones() / 2.0, filter_1.state().mean());\n  EXPECT_EQ(Eigen::Matrix2d::Identity() / 2.0, filter_1.state().cov());\n\n  // object for testing ekf with external model\n  ExtendedKalmanFilter filter_2(initial_state);\n\n  // test update with external model\n  filter_2.update(measurement_model, Eigen::Vector2d::Ones());\n\n  EXPECT_EQ(Eigen::Vector2d::Ones() / 2.0, filter_2.state().mean());\n  EXPECT_EQ(Eigen::Matrix2d::Identity() / 2.0, filter_2.state().cov());\n}\n\n}  // namespace refill\n", "meta": {"hexsha": "69fb27016089a785a6a8889eee28e2ee0b7c6bee", "size": 6202, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/tests/extended_kalman_filter_test.cc", "max_stars_repo_name": "jwidauer/refill", "max_stars_repo_head_hexsha": "64947e0a8e15855f4a5ad048f09f8d38715bbe91", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-06-13T07:28:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-08T11:26:34.000Z", "max_issues_repo_path": "src/tests/extended_kalman_filter_test.cc", "max_issues_repo_name": "jwidauer/refill", "max_issues_repo_head_hexsha": "64947e0a8e15855f4a5ad048f09f8d38715bbe91", "max_issues_repo_licenses": ["MIT"], "max_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/extended_kalman_filter_test.cc", "max_forks_repo_name": "jwidauer/refill", "max_forks_repo_head_hexsha": "64947e0a8e15855f4a5ad048f09f8d38715bbe91", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-06-01T13:21:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-01T20:33:20.000Z", "avg_line_length": 39.5031847134, "max_line_length": 78, "alphanum_fraction": 0.6717188004, "num_tokens": 1457, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149978955811, "lm_q2_score": 0.6297746143530797, "lm_q1q2_score": 0.4754263016690456}}
{"text": "/* boost random/exponential_distribution.hpp header file\n *\n * Copyright Jens Maurer 2000-2001\n * Permission to use, copy, modify, sell, and distribute this software\n * is hereby granted without fee provided that the above copyright notice\n * appears in all copies and that both that copyright notice and this\n * permission notice appear in supporting documentation,\n *\n * Jens Maurer makes no representations about the suitability of this\n * software for any purpose. It is provided \"as is\" without express or\n * implied warranty.\n *\n * See http://www.boost.org for most recent version including documentation.\n *\n * $Id: exponential_distribution.hpp 11696 2001-11-14 21:53:38Z jmaurer $\n *\n * Revision history\n *  2001-02-18  moved to individual header files\n */\n\n#ifndef BOOST_RANDOM_EXPONENTIAL_DISTRIBUTION_HPP\n#define BOOST_RANDOM_EXPONENTIAL_DISTRIBUTION_HPP\n\n#include <cmath>\n#include <cassert>\n#include <boost/random/uniform_01.hpp>\n\nnamespace boost {\n\n// exponential distribution: p(x) = lambda * exp(-lambda * x)\ntemplate<class UniformRandomNumberGenerator, class RealType = double>\nclass exponential_distribution\n{\npublic:\n  typedef UniformRandomNumberGenerator base_type;\n  typedef RealType result_type;\n\n  exponential_distribution(base_type& rng, result_type lambda)\n    : _rng(rng), _lambda(lambda) { assert(lambda > 0); }\n  // compiler-generated copy ctor is fine\n  // uniform_01 cannot be assigned, neither can this class\n  result_type operator()()\n  { \n#ifndef BOOST_NO_STDC_NAMESPACE\n    using std::log;\n#endif\n    return -1.0 / _lambda * log(1-_rng());\n  }\n\n#ifndef BOOST_NO_OPERATORS_IN_NAMESPACE\n  friend bool operator==(const exponential_distribution& x, \n                         const exponential_distribution& y)\n  { return x._lambda == y._lambda && x._rng == y._rng; }\n#else\n  // Use a member function\n  bool operator==(const exponential_distribution& rhs) const\n  { return _lambda == rhs._lambda && _rng == rhs._rng;  }\n#endif\nprivate:\n  uniform_01<base_type, RealType> _rng;\n  const result_type _lambda;\n};\n\n} // namespace boost\n\n#endif // BOOST_RANDOM_EXPONENTIAL_DISTRIBUTION_HPP\n", "meta": {"hexsha": "c2c010a9aa9f5411561be3d4fbf4f65bf731280c", "size": 2111, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "vegastrike/boost/1_28/boost/random/exponential_distribution.hpp", "max_stars_repo_name": "Ezeer/VegaStrike_win32FR", "max_stars_repo_head_hexsha": "75891b9ccbdb95e48e15d3b4a9cd977955b97d1f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "vegastrike/boost/1_28/boost/random/exponential_distribution.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/random/exponential_distribution.hpp", "max_forks_repo_name": "Ezeer/VegaStrike_win32FR", "max_forks_repo_head_hexsha": "75891b9ccbdb95e48e15d3b4a9cd977955b97d1f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5074626866, "max_line_length": 76, "alphanum_fraction": 0.7489341544, "num_tokens": 495, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.47542629996957314}}
{"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\nnamespace bsplines {\n  using namespace sm::kinematics;\n\n    // given T, T'\\in\\mathrm{SE}(3), define Exp_{T}(h), h\\in\\mathbb{R}^6 , Log_{T}(T') \n    // [p,\\theta]\\in\\mathbb{R}^6 , \\mathrm{SE}(3) \\ni T = Exp[p, \\theta] = [exp(-\\theta) p]\n    //                                                                     [      0      1] \n    // T = [R t] \\in\\mathrm{SE}(3), Log T = [t  -log(R)]\n    //     [0 1]\n    // T \\oplus [a, b] = Exp_{T}([a, b]) = Exp[a, b] * T\n    // T1 \\ominus T2 = Log_{T2}(T1) = Log(T1 * T2^{-1})\n    BSplinePose::BSplinePose(int splineOrder, const RotationalKinematics::Ptr & rotationalKinematics) \n      : BSpline(splineOrder), rotation_(rotationalKinematics)\n    {\n      \n    }\n\n    BSplinePose::~BSplinePose()\n    {\n\n    }\n      \n    Eigen::Matrix4d BSplinePose::transformation(double tk) const\n    {\n      return curveValueToTransformation(eval(tk));\n    }\n\n    // T: transformation  p: axis angle  C: spline control points\n    // dT/dC = dT/dp * dp/dC\n    Eigen::Matrix4d BSplinePose::transformationAndJacobian(double tk, Eigen::MatrixXd * J, Eigen::VectorXi * coefficientIndices) const\n    {\n      Eigen::MatrixXd JS;  // dp/dC\n      Eigen::VectorXd p;\n      p = evalDAndJacobian(tk,0,&JS, coefficientIndices);\n      \n      Eigen::MatrixXd JT;  // dT/dp\n      Eigen::Matrix4d T = curveValueToTransformationAndJacobian( p, &JT );      \n      \n      if(J)\n      {\n        *J = JT * JS;\n      }\n\n      return T;\n    }\n\n    // Log_{O(\\theta)}O(\\theta + \\delta) = J\\delta\n    // => J\\delta = Log(O(\\theta + \\delta) * O(\\theta)^{-1})\n    //            = Log(exp(-(\\theta + \\delta)) * exp(\\theta))\n    //            = Log(exp(-Jr(\\theta)\\delta))\n    //            = Jr(\\theta)\\delta\n    Eigen::Matrix3d BSplinePose::orientationAndJacobian(double tk, Eigen::MatrixXd * J, Eigen::VectorXi * coefficientIndices) const\n    {\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      {\n        *J = JO * JS;\n      }\n\n      return C;\n\n    }\n\n    // Log_{IO(\\theta)}IO(\\theta + \\delta) = J\\delta\n    // => J\\delta = Log(IO(\\theta + \\delta) * IO(\\theta)^{-1})\n    //            = Log(exp(\\theta + \\delta) * exp(-\\theta))\n    //            = Log(Jl(\\theta)\\delta)\n    //            = -Jl(\\theta)\\delta\n    //            = -exp(\\theta)Jr(\\theta)\\delta\n    Eigen::Matrix3d BSplinePose::inverseOrientationAndJacobian(double tk, Eigen::MatrixXd * J, Eigen::VectorXi * coefficientIndices) const\n    {\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      {\n        *J = -C * JO * JS;\n      }\n\n      return C;\n\n    }\n\n\n    Eigen::Matrix4d BSplinePose::inverseTransformationAndJacobian(double tk, Eigen::MatrixXd * J, Eigen::VectorXi * coefficientIndices) const\n    {\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      {\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      {\n        *coefficientIndices = localCoefficientVectorIndices(tk);\n      }\n      \n      return T;\n    }\n    \n    Eigen::Matrix4d BSplinePose::inverseTransformation(double tk) const\n    {\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\n\n    // d(Tv)/dC = d(Tv)/dT * dT/dp * dp/dC\n    // d(Tv)/dT s.t. Exp_{T}(h)v - Tv = d(Tv)/dT * h\n    Eigen::Vector4d BSplinePose::transformVectorAndJacobian(double tk, const Eigen::Vector4d & v_tk, Eigen::MatrixXd * J, Eigen::VectorXi * coefficientIndices) const\n    {\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      {\n        *J = sm::kinematics::boxMinus(v_n) * JT;\n      }\n\n      return v_n;\n    }\n\n    Eigen::Vector4d BSplinePose::inverseTransformVectorAndJacobian(double tk, const Eigen::Vector4d & v_tk, Eigen::MatrixXd * J, Eigen::VectorXi * coefficientIndices) const\n    {\n      Eigen::MatrixXd JT;\n      Eigen::Matrix4d T_n_vk = inverseTransformationAndJacobian(tk, &JT, coefficientIndices);\n      Eigen::Vector4d v_n = T_n_vk * v_tk;\n\n      if(J)\n      {\n        *J = sm::kinematics::boxMinus(v_n) * JT;\n      }\n\n      return v_n;\n    }\n      \n    Eigen::Vector3d BSplinePose::position(double tk) const\n    {\n      return eval(tk).head<3>();\n    }\n\n\n\n    Eigen::Matrix3d BSplinePose::orientation(double tk) const\n    {\n      return rotation_->parametersToRotationMatrix(eval(tk).tail<3>());\n    }\n\n    Eigen::Matrix3d BSplinePose::inverseOrientation(double tk) const\n    {\n      return rotation_->parametersToRotationMatrix(eval(tk).tail<3>()).transpose();\n    }\n\n\n\n    Eigen::Vector3d BSplinePose::linearVelocity(double tk) const\n    {\n      return evalD(tk,1).head<3>();\n    }\n\n    Eigen::Vector3d BSplinePose::linearVelocityBodyFrame(double tk) const\n    {\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    Eigen::Vector3d BSplinePose::linearAcceleration(double tk) const\n    {\n      return evalD(tk,2).head<3>();\n    }\n\n    Eigen::Vector3d BSplinePose::linearAccelerationBodyFrame(double tk) const\n    {\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\n    Eigen::Vector3d BSplinePose::linearAccelerationAndJacobian(double tk, Eigen::MatrixXd * J, Eigen::VectorXi * coefficientIndices) const\n    {\n      \n      Eigen::Vector3d a = evalDAndJacobian(tk,2,J,coefficientIndices).head<3>();\n      if(J)\n      {\n        J->conservativeResize(3,J->cols());\n      }\n      return a;\n    }\n    \n    // {}_w\\omege_{wb}\n    // \\omega_w_{b,w} (angular velocity of the body frame as seen from the world frame, expressed in the world frame)\n    Eigen::Vector3d BSplinePose::angularVelocity(double tk) const\n    {\n      Eigen::Vector3d omega;\n      Eigen::VectorXd r = evalD(tk,0);\n      Eigen::VectorXd v = evalD(tk,1);\n\n      omega = -rotation_->parametersToSMatrix(r.tail<3>()) * v.tail<3>();\n      return omega;\n    }\n\n    // {}_b\\omege_{wb}\n    // \\omega_w_{b,b} (angular velocity of the body frame as seen from the world frame, expressed in the body frame)\n    Eigen::Vector3d BSplinePose::angularVelocityBodyFrame(double tk) const\n    {\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 = -C_w_b.transpose() * S * v.tail<3>();\n      return omega;      \n\n    }\n\n    // \\omega_w_{b,b} (angular velocity of the body frame as seen from the world frame, expressed in the body frame)\n    Eigen::Vector3d BSplinePose::angularVelocityBodyFrameAndJacobian(double tk, Eigen::MatrixXd * J, Eigen::VectorXi * coefficientIndices) const\n    {\n      Eigen::MatrixXd Jr;\n      Eigen::Matrix3d C_b_w = inverseOrientationAndJacobian(tk,&Jr,NULL);\n      \n      Eigen::Vector3d omega = angularVelocityAndJacobian(tk, J, coefficientIndices);\n      omega = C_b_w * omega;\n\n      if(J)\n      {\n        *J = C_b_w * (*J) + sm::kinematics::crossMx(omega) * Jr;\n      }\n\n      return omega;\n    }\n\n\n    // \\omega_w_{b,w} (angular velocity of the body frame as seen from the world frame, expressed in the world frame)\n    Eigen::Vector3d BSplinePose::angularVelocityAndJacobian(double tk, Eigen::MatrixXd * J, Eigen::VectorXi * coefficientIndices) const\n    {\n\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      // 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      // \\omega = -Jr(\\theta) * \\dot{\\theta}\n      // \\theta, \\dot{\\theta} are independent, then \n      //    d\\omega/dC = d\\omega/d\\theta * d\\theta/dC + d\\omega/d\\dot{\\theta} * d\\dot{\\theta}/dC\n      //  d\\omega/d\\theta * d\\theta/dC + d\\omega/d\\dot{\\theta} * d\\dot{\\theta}/dC\n      // = -R * [d(Jr(\\theta)\\dot{\\theta})/d\\theta   Jr(\\theta)] * [    d\\theta/dC    ]\n      //                                                           [ d\\dot{\\theta}/dC ]\n      Eigen::Matrix<double,3,6> Jo;\n      omega = -rotation_->angularVelocityAndJacobian(p,pdot,&Jo);\n      \n      //std::cout << \"Jo:\\n\" << Jo << std::endl;\n      if(J)\n      {\n        *J = -Jo * Jpdot;\n      }\n\n      return omega;\n    }\n\n    // {}_b\\dot\\omega_{wb}\n    // \\omega_dot_w_{b,b} (angular acceleration of the body frame as seen from the world frame, expressed in the body frame)\n    Eigen::Vector3d BSplinePose::angularAccelerationBodyFrame(double tk) const\n    {\n    \tEigen::Vector3d p = evalD(tk,0).tail<3>();\n      Eigen::Vector3d v = evalD(tk,1).tail<3>();\n    \tEigen::Vector3d a = evalD(tk,2).tail<3>();\n    \tEigen::Matrix3d C_w_b = rotation_->parametersToRotationMatrix(p);\n\n      Eigen::Matrix<double,3,6> Jo;\n      rotation_->angularVelocityAndJacobian(p,v,&Jo);\n\n      Eigen::Matrix<double,6,1> va;\n      va << v, a;\n\n      return -C_w_b.transpose() * (Jo * va);\n    }\n\n    // \\omega_dot_w_{b,b} (angular acceleration of the body frame as seen from the world frame, expressed in the body frame)\n    Eigen::Vector3d BSplinePose::angularAccelerationBodyFrameAndJacobian(double tk, Eigen::MatrixXd * J, Eigen::VectorXi * coefficientIndices) const\n    {\n      Eigen::MatrixXd Jr;\n    \tEigen::Matrix3d C_b_w = inverseOrientationAndJacobian(tk,&Jr,NULL);\n\n      Eigen::Vector3d acce = angularAccelerationAndJacobian(tk, J, coefficientIndices);\n      acce = C_b_w * acce;\n\n      if(J)\n    \t{\n    \t\t*J = C_b_w * (*J) + sm::kinematics::crossMx(acce) * Jr;\n    \t}\n\n      return acce;\n    }\n\n    // {}_w\\dot\\omega_{wb}\n    // \\omega_dot_w_{b,w} (angular acceleration of the body frame as seen from the world frame, expressed in the world frame)\n    Eigen::Vector3d BSplinePose::angularAcceleration(double tk) const\n    {\n    \tEigen::Vector3d p = evalD(tk,0).tail<3>();\n      Eigen::Vector3d v = evalD(tk,1).tail<3>();\n    \tEigen::Vector3d a = evalD(tk,2).tail<3>();\n\n      Eigen::Matrix<double,3,6> Jo;\n      rotation_->angularVelocityAndJacobian(p,v,&Jo);\n\n      Eigen::Matrix<double,6,1> va;\n      va << v, a;\n\n      return -(Jo * va);\n    }\n\n    // \\todo Only support RotationVector by now\n    // \\omega_dot_w_{b,w} (angular acceleration of the body frame as seen from the world frame, expressed in the world frame)\n    Eigen::Vector3d BSplinePose::angularAccelerationAndJacobian(double tk, Eigen::MatrixXd * J, Eigen::VectorXi * coefficientIndices) const\n    {\n      Eigen::Vector3d p;\n      Eigen::Vector3d v;\n    \tEigen::Vector3d a;\n      Eigen::MatrixXd Jp;\n      Eigen::MatrixXd Jv;\n      Eigen::MatrixXd Ja;\n      p = evalDAndJacobian(tk,0,&Jp,NULL).tail<3>();\n      v = evalDAndJacobian(tk,1,&Jv,NULL).tail<3>();\n      a = evalDAndJacobian(tk,2,&Ja,coefficientIndices).tail<3>();\n\n      Eigen::Matrix<double,3,6> Jo;\n      rotation_->angularVelocityAndJacobian(p,v,&Jo);\n\n      Eigen::Matrix<double,6,1> va;\n      va << v, a;\n\n      Eigen::Vector3d acce = -(Jo * va);\n\n      // Rearrange the spline jacobian matrices. Now Ja is the\n    \t// jacobian of p wrt the spline coefficients stacked on top\n    \t// of the jacobian of a wrt the spline coefficients.\n    \tJa.block(0,0,3,Ja.cols()) = Jp.block(3,0,3,Jp.cols());\n\n      // Rearrange the spline jacobian matrices. Now Jv is the\n    \t// jacobian of p wrt the spline coefficients stacked on top\n    \t// of the jacobian of v wrt the spline coefficients.\n    \tJv.block(0,0,3,Jv.cols()) = Jp.block(3,0,3,Jp.cols());\n\n      rotation_->angularVelocityAndJacobian(p,a,&Jo);\n\n      // f(\\theta, \\dot\\theta) = \\frac{\\partial Jr(\\theta)\\dot\\theta}{\\partial\\theta}\\dot\\theta\n      // [ \\frac{\\partial f}{\\partial\\theta}  \\frac{\\partial f}{\\partial\\dot\\theta} ]\n      Eigen::Matrix<double,3,6> Jpp;\n\n      double factor[5];\n      const double pv = p.dot(v);\n      const double v2 = v.squaredNorm();\n      const double p2 = p.squaredNorm();\n      if(p2 < 1e-14)\n      {\n        const double p4 = p2 * p2;\n        // Series[(x Sin[x] + 2 Cos[x] - 2) / x^4, {x, 0, 4}]\n        factor[0] = -1.0 / 12 + p2 / 180 - p4 / 6720;\n        // Series[(x - Sin[x]) / x^3, {x, 0, 4}]\n        factor[1] = 1.0 / 6 - p2 / 120 + p4 / 5040;\n        // Series[(3 Sin[x] - x Cos[x] - 2 x) / (x^5), {x, 0, 4}]\n        factor[2] = -1.0 / 60 + p2 / 1260 - p4 / 60480;\n        // Series[((x^2 - 8) Cos[x] - 5 x Sin[x] + 8) / x^6, {x, 0, 4}]\n        factor[3] = 1.0 / 90 - p2 / 1680 + p4 / 75600;\n        // Series[((x^2 - 15) Sin[x] + 7 x Cos[x] + 8 x) / x^7, {x, 0, 4}]\n        factor[4] = 1.0 / 630 - p2 / 15120 + p4 / 831600;\n      }\n      else\n      {\n        const double p1 = std::sqrt(p2);\n        const double p3 = p1 * p2;\n        const double p4 = p1 * p3;\n        const double p5 = p1 * p4;\n        const double p6 = p1 * p5;\n        const double p7 = p1 * p6;\n        const double cosp = std::cos(p1);\n        const double sinp = std::sin(p1);\n\n        factor[0] = (p1 * sinp + 2 * cosp - 2) / p4;\n        factor[1] = (p1 - sinp) / p3;\n        factor[2] = (3 * sinp - p1 * cosp - 2 * p1) / p5;\n        factor[3] = ((p2 - 8) * cosp - 5 * p1 * sinp + 8) / p6;\n        factor[4] = ((p2 - 15) * sinp + 7 * p1 * cosp + 8 * p1) / p7;\n      }\n\n      Jpp.leftCols<3>() = factor[0] * sm::kinematics::crossMx(v) * (pv * Eigen::Matrix3d::Identity() + p * v.transpose()) +\n                          factor[1] * (v2 * Eigen::Matrix3d::Identity() - v * v.transpose()) +\n                          factor[2] * (pv * pv * Eigen::Matrix3d::Identity() + 2 * pv * p * v.transpose() - 2 * pv * v * p.transpose() - p2 * v * v.transpose()) +\n                          factor[3] * pv * sm::kinematics::crossMx(v) * p * p.transpose() +\n                          factor[2] * (v2 * p * p.transpose() - pv * v * p.transpose()) +\n                          factor[4] * (pv * pv * p * p.transpose() - pv * p2 * v * p.transpose());\n      Jpp.rightCols<3>() = factor[0] * (sm::kinematics::crossMx(v) * p * p.transpose() - pv * sm::kinematics::crossMx(p)) +\n                           factor[1] * (2 * p * v.transpose() - v * p.transpose() - pv * Eigen::Matrix3d::Identity()) +\n                           factor[2] * (2 * pv * p * p.transpose() - pv * p2 * Eigen::Matrix3d::Identity() - p2 * v * p.transpose());\n\n      if(J)\n    \t{\n    \t\t*J = -Jpp * Jv - Jo * Ja;\n    \t}\n\n      return acce;\n    }\n\n    void BSplinePose::initPoseSpline(double t0, double t1, const Eigen::Matrix4d & T_n_t0, const Eigen::Matrix4d & T_n_t1)\n    {\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    \n    void BSplinePose::addPoseSegment(double tk, const Eigen::Matrix4d & T_n_tk)\n    {\n      Eigen::VectorXd vk = transformationToCurveValue(T_n_tk);\n      \n      addCurveSegment(tk, vk);\n    }\n\n    void BSplinePose::addPoseSegment2(double tk, const Eigen::Matrix4d & T_n_tk, double lambda)\n    {\n      Eigen::VectorXd vk = transformationToCurveValue(T_n_tk);\n      \n      addCurveSegment2(tk, vk, lambda);\n    }\n\n\n    Eigen::Matrix4d BSplinePose::curveValueToTransformation( const Eigen::VectorXd & c ) const\n    {\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\n    // dT/dp s.t. T(p + \\delta) = Exp(dT/dp \\delta)T(p)\n    Eigen::Matrix4d BSplinePose::curveValueToTransformationAndJacobian( const Eigen::VectorXd & p, Eigen::MatrixXd * J ) const\n    {\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      {    \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    }\n\n    Eigen::VectorXd BSplinePose::transformationToCurveValue( const Eigen::Matrix4d & T ) const\n    {\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\n    void BSplinePose::initPoseSpline2(const Eigen::VectorXd & times, const Eigen::Matrix<double,6,Eigen::Dynamic> & poses, int numSegments, double lambda)\n    {\n      initSpline2(times, poses, numSegments, lambda);\n    }\n\n    void BSplinePose::initPoseSpline3(const Eigen::VectorXd & times, const Eigen::Matrix<double,6,Eigen::Dynamic> & poses, int numSegments, double lambda)\n    {\n      initSpline3(times, poses, numSegments, lambda);\n    }\n\n    void BSplinePose::initPoseSplineSparse(const Eigen::VectorXd & times, const Eigen::Matrix<double,6,Eigen::Dynamic> & poses, int numSegments, double lambda)\n    {\n      initSplineSparse(times, poses, numSegments, lambda);\n    }\n    \n    void BSplinePose::initPoseSplineSparseKnots(const Eigen::VectorXd &times, const Eigen::MatrixXd &interpolationPoints, const Eigen::VectorXd knots, double lambda)\n    {\n    \tinitSplineSparseKnots(times, interpolationPoints, knots, lambda);\n    }\n    \n    RotationalKinematics::Ptr BSplinePose::rotation() const\n    {\n      return rotation_;\n    }\n  } // namespace bsplines\n", "meta": {"hexsha": "68d6009e6289d480524a0f63dee03c80966925f7", "size": 19269, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "aslam_nonparametric_estimation/bsplines/src/BSplinePose.cpp", "max_stars_repo_name": "huangqinjin/kalibr", "max_stars_repo_head_hexsha": "5bc7b73ce8185c734152def716e7d657a2736ec5", "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": "huangqinjin/kalibr", "max_issues_repo_head_hexsha": "5bc7b73ce8185c734152def716e7d657a2736ec5", "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": "huangqinjin/kalibr", "max_forks_repo_head_hexsha": "5bc7b73ce8185c734152def716e7d657a2736ec5", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.7495361781, "max_line_length": 172, "alphanum_fraction": 0.5900669469, "num_tokens": 5807, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149978955811, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.4754262964233932}}
{"text": "#ifndef particle_hpp\n#define particle_hpp\n\n#include <Eigen/Core>\n\nnamespace elasty\n{\n    struct Particle\n    {\n        Particle(const Eigen::Vector3d& x, const Eigen::Vector3d& v, const double m) :\n        x(x),\n        v(v),\n        p(x),\n        f(Eigen::Vector3d::Zero()),\n        m(m),\n        w(1.0 / m)\n        {\n        }\n\n        Eigen::Vector3d x;\n        Eigen::Vector3d v;\n        Eigen::Vector3d p;\n        Eigen::Vector3d f;\n        double m;\n        double w;\n    };\n}\n\n#endif /* particle_hpp */\n", "meta": {"hexsha": "b3d7c2945157b9c411474dcc2ceb73cbf6132bbc", "size": 510, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/elasty/particle.hpp", "max_stars_repo_name": "0x0c/elasty", "max_stars_repo_head_hexsha": "3995cacbefa8d7f39249e9f75fa291828e2e7c2d", "max_stars_repo_licenses": ["MIT"], "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/elasty/particle.hpp", "max_issues_repo_name": "0x0c/elasty", "max_issues_repo_head_hexsha": "3995cacbefa8d7f39249e9f75fa291828e2e7c2d", "max_issues_repo_licenses": ["MIT"], "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/elasty/particle.hpp", "max_forks_repo_name": "0x0c/elasty", "max_forks_repo_head_hexsha": "3995cacbefa8d7f39249e9f75fa291828e2e7c2d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.0, "max_line_length": 86, "alphanum_fraction": 0.5019607843, "num_tokens": 137, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.6297746143530797, "lm_q1q2_score": 0.4754262947239209}}
{"text": "/**\n * \\file libs/numeric/ublasx/dot.cpp\n *\n * \\brief Test suite for the \\c dot operation.\n *\n * Copyright (c) 2011, Marco Guazzone\n * \n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\n\n#include <boost/numeric/ublas/fwd.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_expression.hpp>\n#include <boost/numeric/ublas/traits.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/vector_expression.hpp>\n#include <boost/numeric/ublasx/operation/dot.hpp>\n#include <boost/numeric/ublasx/tags.hpp>\n#include <functional>\n#include <iostream>\n#include \"libs/numeric/ublasx/test/utils.hpp\"\n\n\nstatic const double tol = 1.0e-5;\n\n\nnamespace ublas = ::boost::numeric::ublas;\nnamespace ublasx = ::boost::numeric::ublasx;\n\n\nBOOST_UBLASX_TEST_DEF( test_vector_container )\n{\n\tBOOST_UBLASX_DEBUG_TRACE( \"TEST Vector Container\" );\n\n\ttypedef double value_type;\n\ttypedef ublas::vector<value_type> vector_type;\n\ttypedef ublas::vector_traits<vector_type>::size_type size_type;\n\n\tsize_type n(3);\n\n\tvector_type v1(n);\n\tv1(0) = 1;\n\tv1(1) = 2;\n\tv1(2) = 3;\n\n\tvector_type v2(n);\n\tv2(0) = 4;\n\tv2(1) = 5;\n\tv2(2) = 6;\n\n\tvalue_type expect(0);\n\tvalue_type res(0);\n\n\t// dot(v1,v2)\n\texpect = ublas::inner_prod(v1, v2);\n\tres = ublasx::dot(v1, v2);\n\tBOOST_UBLASX_DEBUG_TRACE( \"dot(\" << v1 << \",\" << v2 << \") = \" << res << \" ==> \" << expect );\n\tBOOST_UBLASX_TEST_CHECK_CLOSE( res, expect, tol );\n}\n\n\nBOOST_UBLASX_TEST_DEF( test_vector_expression )\n{\n\tBOOST_UBLASX_DEBUG_TRACE( \"TEST Vector Expression\" );\n\n\ttypedef double value_type;\n\ttypedef ublas::vector<value_type> vector_type;\n\ttypedef ublas::vector_traits<vector_type>::size_type size_type;\n\n\tsize_type n(3);\n\n\tvector_type v1(n);\n\tv1(0) = 1;\n\tv1(1) = 2;\n\tv1(2) = 3;\n\n\tvector_type v2(n);\n\tv2(0) = 4;\n\tv2(1) = 5;\n\tv2(2) = 6;\n\n\tvalue_type expect(0);\n\tvalue_type res(0);\n\n\t// dot(-v1,-v2)\n\texpect = ublas::inner_prod(v1, v2);\n\tres = ublasx::dot(-v1, -v2);\n\tBOOST_UBLASX_DEBUG_TRACE( \"dot(\" << v1 << \",\" << v2 << \") = \" << res << \" ==> \" << expect );\n\tBOOST_UBLASX_TEST_CHECK_CLOSE( res, expect, tol );\n}\n\n\nBOOST_UBLASX_TEST_DEF( test_vector_reference )\n{\n\tBOOST_UBLASX_DEBUG_TRACE( \"TEST Vector Reference\" );\n\n\ttypedef double value_type;\n\ttypedef ublas::vector<value_type> vector_type;\n\ttypedef ublas::vector_reference<vector_type> vector_reference_type;\n\ttypedef ublas::vector_traits<vector_type>::size_type size_type;\n\n\tsize_type n(3);\n\n\tvector_type v1(n);\n\tv1(0) = 1;\n\tv1(1) = 2;\n\tv1(2) = 3;\n\n\tvector_type v2(n);\n\tv2(0) = 4;\n\tv2(1) = 5;\n\tv2(2) = 6;\n\n\tvalue_type expect(0);\n\tvalue_type res(0);\n\n\t// dot(ref(v1),ref(v2))\n\texpect = ublas::inner_prod(vector_reference_type(v1), vector_reference_type(v2));\n\tres = ublasx::dot(v1, v2);\n\tBOOST_UBLASX_DEBUG_TRACE( \"dot(\" << v1 << \",\" << v2 << \") = \" << res << \" ==> \" << expect );\n\tBOOST_UBLASX_TEST_CHECK_CLOSE( res, expect, tol );\n}\n\n\nBOOST_UBLASX_TEST_DEF( test_col_major_matrix_container )\n{\n\tBOOST_UBLASX_DEBUG_TRACE( \"TEST Column-major Matrix Container\" );\n\n\ttypedef double value_type;\n\ttypedef ublas::matrix<value_type, ublas::column_major> matrix_type;\n\ttypedef ublas::vector<value_type> vector_type;\n\ttypedef ublas::matrix_traits<matrix_type>::size_type size_type;\n\n\tsize_type nr = 3;\n\tsize_type nc = 4;\n\n\tmatrix_type A(nr, nc);\n\tA(0,0) =  1; A(0,1) =  2; A(0,2) =  3; A(0,3) =  4;\n\tA(1,0) =  5; A(1,1) =  6; A(1,2) =  7; A(1,3) =  8;\n\tA(2,0) =  9; A(2,1) = 10; A(2,2) = 11; A(2,3) = 12;\n\n\tmatrix_type B(nr, nc);\n\tB(0,0) = 13; B(0,1) = 14; B(0,2) = 15; B(0,3) = 16;\n\tB(1,0) = 17; B(1,1) = 18; B(1,2) = 19; B(1,3) = 20;\n\tB(2,0) = 21; B(2,1) = 22; B(2,2) = 23; B(2,3) = 24;\n\n\tvector_type dot_1(nc);\n\tfor (size_type i = 0; i < nc; ++i)\n\t{\n\t\tdot_1(i) = ublas::inner_prod(ublas::column(A,i), ublas::column(B,i));\n\t}\n\n\tvector_type dot_2(nr);\n\tfor (size_type i = 0; i < nr; ++i)\n\t{\n\t\tdot_2(i) = ublas::inner_prod(ublas::row(A,i), ublas::row(B,i));\n\t}\n\n\n\tvector_type expect;;\n\tvector_type res;;\n\n\n\t// dot<1>(A,B)\n\texpect = dot_1;\n\tres = ublasx::dot<1>(A, B);\n\tBOOST_UBLASX_DEBUG_TRACE( \"dot<1>(\" << A << \",\" << B << \") = \" << res << \" ==> \" << expect );\n\tBOOST_UBLASX_TEST_CHECK_VECTOR_CLOSE( res, expect, expect.size(), tol );\n\n\t// dot<2>(A,B)\n\texpect = dot_2;\n\tres = ublasx::dot<2>(A, B);\n\tBOOST_UBLASX_DEBUG_TRACE( \"dot<2>(\" << A << \",\" << B << \") = \" << res << \" ==> \" << expect );\n\tBOOST_UBLASX_TEST_CHECK_VECTOR_CLOSE( res, expect, expect.size(), tol );\n}\n\n\nBOOST_UBLASX_TEST_DEF( test_row_major_matrix_container )\n{\n\tBOOST_UBLASX_DEBUG_TRACE( \"TEST Row-major Matrix Container\" );\n\n\ttypedef double value_type;\n\ttypedef ublas::matrix<value_type, ublas::row_major> matrix_type;\n\ttypedef ublas::vector<value_type> vector_type;\n\ttypedef ublas::matrix_traits<matrix_type>::size_type size_type;\n\n\tsize_type nr = 3;\n\tsize_type nc = 4;\n\n\tmatrix_type A(nr, nc);\n\tA(0,0) =  1; A(0,1) =  2; A(0,2) =  3; A(0,3) =  4;\n\tA(1,0) =  5; A(1,1) =  6; A(1,2) =  7; A(1,3) =  8;\n\tA(2,0) =  9; A(2,1) = 10; A(2,2) = 11; A(2,3) = 12;\n\n\tmatrix_type B(nr, nc);\n\tB(0,0) = 13; B(0,1) = 14; B(0,2) = 15; B(0,3) = 16;\n\tB(1,0) = 17; B(1,1) = 18; B(1,2) = 19; B(1,3) = 20;\n\tB(2,0) = 21; B(2,1) = 22; B(2,2) = 23; B(2,3) = 24;\n\n\tvector_type dot_1(nc);\n\tfor (size_type i = 0; i < nc; ++i)\n\t{\n\t\tdot_1(i) = ublas::inner_prod(ublas::column(A,i), ublas::column(B,i));\n\t}\n\n\tvector_type dot_2(nr);\n\tfor (size_type i = 0; i < nr; ++i)\n\t{\n\t\tdot_2(i) = ublas::inner_prod(ublas::row(A,i), ublas::row(B,i));\n\t}\n\n\n\tvector_type expect;;\n\tvector_type res;;\n\n\n\t// dot<1>(A,B)\n\texpect = dot_1;\n\tres = ublasx::dot<1>(A, B);\n\tBOOST_UBLASX_DEBUG_TRACE( \"dot<1>(\" << A << \",\" << B << \") = \" << res << \" ==> \" << expect );\n\tBOOST_UBLASX_TEST_CHECK_VECTOR_CLOSE( res, expect, expect.size(), tol );\n\n\t// dot<2>(A,B)\n\texpect = dot_2;\n\tres = ublasx::dot<2>(A, B);\n\tBOOST_UBLASX_DEBUG_TRACE( \"dot<2>(\" << A << \",\" << B << \") = \" << res << \" ==> \" << expect );\n\tBOOST_UBLASX_TEST_CHECK_VECTOR_CLOSE( res, expect, expect.size(), tol );\n}\n\n\nBOOST_UBLASX_TEST_DEF( test_matrix_expression )\n{\n\tBOOST_UBLASX_DEBUG_TRACE( \"TEST Matrix Expression\" );\n\n\ttypedef double value_type;\n\ttypedef ublas::matrix<value_type> matrix_type;\n\ttypedef ublas::vector<value_type> vector_type;\n\ttypedef ublas::matrix_traits<matrix_type>::size_type size_type;\n\n\tsize_type nr = 3;\n\tsize_type nc = 4;\n\n\tmatrix_type A(nr, nc);\n\tA(0,0) =  1; A(0,1) =  2; A(0,2) =  3; A(0,3) =  4;\n\tA(1,0) =  5; A(1,1) =  6; A(1,2) =  7; A(1,3) =  8;\n\tA(2,0) =  9; A(2,1) = 10; A(2,2) = 11; A(2,3) = 12;\n\n\tmatrix_type B(nr, nc);\n\tB(0,0) = 13; B(0,1) = 14; B(0,2) = 15; B(0,3) = 16;\n\tB(1,0) = 17; B(1,1) = 18; B(1,2) = 19; B(1,3) = 20;\n\tB(2,0) = 21; B(2,1) = 22; B(2,2) = 23; B(2,3) = 24;\n\n\tvector_type dot_1(nr);\n\tfor (size_type i = 0; i < nr; ++i)\n\t{\n\t\tdot_1(i) = ublas::inner_prod(ublas::row(A,i), ublas::row(B,i));\n\t}\n\n\tvector_type dot_2(nc);\n\tfor (size_type i = 0; i < nc; ++i)\n\t{\n\t\tdot_2(i) = ublas::inner_prod(ublas::column(A,i), ublas::column(B,i));\n\t}\n\n\n\tvector_type expect;;\n\tvector_type res;;\n\n\n\t// dot<1>(A',B')\n\texpect = dot_1;\n\tres = ublasx::dot<1>(ublas::trans(A), ublas::trans(B));\n\tBOOST_UBLASX_DEBUG_TRACE( \"dot<1>(\" << ublas::trans(A) << \",\" << ublas::trans(B) << \") = \" << res << \" ==> \" << expect );\n\tBOOST_UBLASX_TEST_CHECK_VECTOR_CLOSE( res, expect, expect.size(), tol );\n\n\t// dot<2>(A',B')\n\texpect = dot_2;\n\tres = ublasx::dot<2>(ublas::trans(A), ublas::trans(B));\n\tBOOST_UBLASX_DEBUG_TRACE( \"dot<2>(\" << ublas::trans(A) << \",\" << ublas::trans(B) << \") = \" << res << \" ==> \" << expect );\n\tBOOST_UBLASX_TEST_CHECK_VECTOR_CLOSE( res, expect, expect.size(), tol );\n}\n\n\nBOOST_UBLASX_TEST_DEF( test_matrix_reference )\n{\n\tBOOST_UBLASX_DEBUG_TRACE( \"TEST Matrix Reference\" );\n\n\ttypedef double value_type;\n\ttypedef ublas::matrix<value_type> matrix_type;\n\ttypedef ublas::matrix_reference<matrix_type> matrix_reference_type;\n\ttypedef ublas::vector<value_type> vector_type;\n\ttypedef ublas::matrix_traits<matrix_type>::size_type size_type;\n\n\tsize_type nr = 3;\n\tsize_type nc = 4;\n\n\tmatrix_type A(nr, nc);\n\tA(0,0) =  1; A(0,1) =  2; A(0,2) =  3; A(0,3) =  4;\n\tA(1,0) =  5; A(1,1) =  6; A(1,2) =  7; A(1,3) =  8;\n\tA(2,0) =  9; A(2,1) = 10; A(2,2) = 11; A(2,3) = 12;\n\n\tmatrix_type B(nr, nc);\n\tB(0,0) = 13; B(0,1) = 14; B(0,2) = 15; B(0,3) = 16;\n\tB(1,0) = 17; B(1,1) = 18; B(1,2) = 19; B(1,3) = 20;\n\tB(2,0) = 21; B(2,1) = 22; B(2,2) = 23; B(2,3) = 24;\n\n\tvector_type dot_1(nc);\n\tfor (size_type i = 0; i < nc; ++i)\n\t{\n\t\tdot_1(i) = ublas::inner_prod(ublas::column(A,i), ublas::column(B,i));\n\t}\n\n\tvector_type dot_2(nr);\n\tfor (size_type i = 0; i < nr; ++i)\n\t{\n\t\tdot_2(i) = ublas::inner_prod(ublas::row(A,i), ublas::row(B,i));\n\t}\n\n\n\tvector_type expect;;\n\tvector_type res;;\n\n\n\t// dot<1>(ref(A),ref(B))\n\texpect = dot_1;\n\tres = ublasx::dot<1>(matrix_reference_type(A), matrix_reference_type(B));\n\tBOOST_UBLASX_DEBUG_TRACE( \"dot<1>(\" << A << \",\" << B << \") = \" << res << \" ==> \" << expect );\n\tBOOST_UBLASX_TEST_CHECK_VECTOR_CLOSE( res, expect, expect.size(), tol );\n\n\t// dot<2>(ref(A),ref(B))\n\texpect = dot_2;\n\tres = ublasx::dot<2>(matrix_reference_type(A), matrix_reference_type(B));\n\tBOOST_UBLASX_DEBUG_TRACE( \"dot<2>(\" << A << \",\" << B << \") = \" << res << \" ==> \" << expect );\n\tBOOST_UBLASX_TEST_CHECK_VECTOR_CLOSE( res, expect, expect.size(), tol );\n}\n\n\nint main()\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Suite: 'dot' operation\");\n\n\tBOOST_UBLASX_TEST_BEGIN();\n\n\tBOOST_UBLASX_TEST_DO( test_vector_container );\n\tBOOST_UBLASX_TEST_DO( test_vector_expression );\n\tBOOST_UBLASX_TEST_DO( test_vector_reference );\n\tBOOST_UBLASX_TEST_DO( test_col_major_matrix_container );\n\tBOOST_UBLASX_TEST_DO( test_row_major_matrix_container );\n\tBOOST_UBLASX_TEST_DO( test_matrix_expression );\n\tBOOST_UBLASX_TEST_DO( test_matrix_reference );\n\n\tBOOST_UBLASX_TEST_END();\n}\n", "meta": {"hexsha": "9529ab6d9527e68592bc664c030c9414391b1dd0", "size": 9860, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/ublasx/test/dot.cpp", "max_stars_repo_name": "comcon1/boost-ublasx", "max_stars_repo_head_hexsha": "290b92b643a944825df99bece3468a4f81518056", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/numeric/ublasx/test/dot.cpp", "max_issues_repo_name": "comcon1/boost-ublasx", "max_issues_repo_head_hexsha": "290b92b643a944825df99bece3468a4f81518056", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/numeric/ublasx/test/dot.cpp", "max_forks_repo_name": "comcon1/boost-ublasx", "max_forks_repo_head_hexsha": "290b92b643a944825df99bece3468a4f81518056", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4651810585, "max_line_length": 122, "alphanum_fraction": 0.6326572008, "num_tokens": 3702, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6297746143530797, "lm_q1q2_score": 0.4754262947239208}}
{"text": "/**\n * laminate_main reads the input file `laminate_input` and `material_data`,\n * construct a laminate model containing material properties and response to\n * the load, and save the stress and strain profile into \n * `laminate_profile_data.txt`, and save the A,B, and D submatrices into\n * `stifness_submatrices ABD.txt`.\n * \n * `laminate_profile_data.txt` contains the following columns (in order):\n * Coordinates, stress_x, stress_y, stress_xy, strain_x, strain_y, strain_xy.\n * \n * `stiffness_submatrices_ABD.txt` contains the A, B, and D submatrices of the\n * composite laminate, in the given order separate by new lines.\n * \n */\n\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <Eigen/Dense>\n#include \"../include/input_parser.h\"\n#include \"../include/ply.h\"\n#include \"../include/laminate.h\"\n\nvoid save_laminate_profile(laminate& lam);\n\nint main() {\n    std::vector<std::string> input_strings = \n        read_composite_input(\"input_files/laminate_input.lmc\");\n    std::vector<ply> ply_vector = \n        get_ply_vector(input_strings, \"input_files/material_data.lmc\");\n    Eigen::Matrix<double, 6, 1> load_vector = get_load_vector(input_strings[3]);\n    double min_thickness = get_minimum_ply_thickness(input_strings[2]);\n    double pt_spacing = min_thickness/20.;\n    laminate lam(ply_vector, load_vector, pt_spacing);\n    save_laminate_profile(lam);\n    std::cout << \"Laminate_main -- Data saved.\" << std::endl;\n    return 0;\n}\n\nvoid save_laminate_profile(laminate& lam) {\n    std::ofstream profile_file;\n    profile_file.open(\"output_files/laminate_profile_data.txt\");\n    auto i_sigma = lam.stresses_.begin();\n    auto i_eps = lam.strains_.begin();\n    auto i_pt = lam.profile_pt_.begin();\n    for (; i_sigma != lam.stresses_.end(); i_sigma++, i_eps++, i_pt++) {\n        Eigen::Matrix<double, 7, 1> combined_data;\n        combined_data << *i_pt, *i_sigma, *i_eps;\n        \n        Eigen::Map<Eigen::Matrix<double, 1, 7>> \n            row(combined_data.data(), combined_data.size());\n        profile_file << row << std::endl;\n    }\n    std::ofstream stiffness_file;\n    stiffness_file.open(\"output_files/stiffness_submatrices ABD.txt\");\n    stiffness_file << lam.A_;\n    stiffness_file << std::endl<< std::endl;\n    stiffness_file << lam.B_;\n    stiffness_file << std::endl << std::endl;\n    stiffness_file << lam.D_;\n    stiffness_file << std::endl << std::endl;\n}", "meta": {"hexsha": "0b096054691c2e5be13b804e7b53a25456c4f438", "size": 2406, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/laminate_main.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": "src/laminate_main.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": "src/laminate_main.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": 38.1904761905, "max_line_length": 80, "alphanum_fraction": 0.6961762261, "num_tokens": 611, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6297746143530797, "lm_q1q2_score": 0.4754262947239208}}
{"text": "// This file is part of Eigen, a lightweight C++ template library\n// for linear algebra.\n//\n// Copyright (C) 2014 Benoit Steiner <benoit.steiner.goog@gmail.com>\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 \"main.h\"\n\n\n#include <Eigen/CXX11/Tensor>\n\nusing Eigen::MatrixXf;\nusing Eigen::Tensor;\n\nstatic void test_simple()\n{\n  MatrixXf m1(3,3);\n  MatrixXf m2(3,3);\n  m1.setRandom();\n  m2.setRandom();\n\n  TensorMap<Tensor<float, 2> > mat1(m1.data(), 3,3);\n  TensorMap<Tensor<float, 2> > mat2(m2.data(), 3,3);\n\n  Tensor<float, 2> mat3(3,3);\n  mat3 = mat1;\n\n  typedef Tensor<float, 1>::DimensionPair DimPair;\n  Eigen::array<DimPair, 1> dims;\n  dims[0] = DimPair(1, 0);\n\n  mat3 = mat3.contract(mat2, dims).eval();\n\n  VERIFY_IS_APPROX(mat3(0, 0), (m1*m2).eval()(0,0));\n  VERIFY_IS_APPROX(mat3(0, 1), (m1*m2).eval()(0,1));\n  VERIFY_IS_APPROX(mat3(0, 2), (m1*m2).eval()(0,2));\n  VERIFY_IS_APPROX(mat3(1, 0), (m1*m2).eval()(1,0));\n  VERIFY_IS_APPROX(mat3(1, 1), (m1*m2).eval()(1,1));\n  VERIFY_IS_APPROX(mat3(1, 2), (m1*m2).eval()(1,2));\n  VERIFY_IS_APPROX(mat3(2, 0), (m1*m2).eval()(2,0));\n  VERIFY_IS_APPROX(mat3(2, 1), (m1*m2).eval()(2,1));\n  VERIFY_IS_APPROX(mat3(2, 2), (m1*m2).eval()(2,2));\n}\n\n\nstatic void test_const()\n{\n  MatrixXf input(3,3);\n  input.setRandom();\n  MatrixXf output = input;\n  output.rowwise() -= input.colwise().maxCoeff();\n\n  Eigen::array<int, 1> depth_dim;\n  depth_dim[0] = 0;\n  Tensor<float, 2>::Dimensions dims2d;\n  dims2d[0] = 1;\n  dims2d[1] = 3;\n  Eigen::array<int, 2> bcast;\n  bcast[0] = 3;\n  bcast[1] = 1;\n  const TensorMap<Tensor<const float, 2> > input_tensor(input.data(), 3, 3);\n  Tensor<float, 2> output_tensor= (input_tensor - input_tensor.maximum(depth_dim).eval().reshape(dims2d).broadcast(bcast));\n\n  for (int i = 0; i < 3; ++i) {\n    for (int j = 0; j < 3; ++j) {\n      VERIFY_IS_APPROX(output(i, j), output_tensor(i, j));\n    }\n  }\n}\n\n\nvoid test_cxx11_tensor_forced_eval()\n{\n  CALL_SUBTEST(test_simple());\n  CALL_SUBTEST(test_const());\n}\n", "meta": {"hexsha": "43dc9561f93e288a156674cba75d59d91063bfe1", "size": 2138, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "External/eigen-3.3.7/unsupported/test/cxx11_tensor_forced_eval.cpp", "max_stars_repo_name": "RokKos/eol-cloth", "max_stars_repo_head_hexsha": "b9c6f55f25ba17f33532ea5eefa41fedd29c5206", "max_stars_repo_licenses": ["MIT"], "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/eigen-3.3.7/unsupported/test/cxx11_tensor_forced_eval.cpp", "max_issues_repo_name": "RokKos/eol-cloth", "max_issues_repo_head_hexsha": "b9c6f55f25ba17f33532ea5eefa41fedd29c5206", "max_issues_repo_licenses": ["MIT"], "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/eigen-3.3.7/unsupported/test/cxx11_tensor_forced_eval.cpp", "max_forks_repo_name": "RokKos/eol-cloth", "max_forks_repo_head_hexsha": "b9c6f55f25ba17f33532ea5eefa41fedd29c5206", "max_forks_repo_licenses": ["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.725, "max_line_length": 123, "alphanum_fraction": 0.6463985033, "num_tokens": 779, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6297746074044135, "lm_q1q2_score": 0.47542628947826854}}
{"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/*!\n * \\file\n**/\n#ifndef BOOST_SIMD_CONSTANT_CONSTANTS_SQRT_2_HPP_INCLUDED\n#define BOOST_SIMD_CONSTANT_CONSTANTS_SQRT_2_HPP_INCLUDED\n\n#include <boost/simd/include/functor.hpp>\n#include <boost/simd/sdk/constant/register.hpp>\n#include <boost/simd/sdk/constant/constant.hpp>\n\n/*!\n * \\ingroup boost_simd_constant\n * \\defgroup boost_simd_constant_sqrt_2 Sqrt_2\n *\n * \\par Description\n * Constant Sqrt_2 = \\f$\\sqrt2\\f$\n *\n * \\par Header file\n *\n * \\code\n * #include <nt2/include/functions/sqrt_2.hpp>\n * \\endcode\n *\n *\n * \\synopsis\n *\n * \\code\n * namespace boost::simd\n * {\n *   template <class T,class A0>\n *     meta::call<tag::sqrt_2_(A0)>::type\n *     Sqrt_2();\n * }\n * \\endcode\n *\n *\n * \\param T template parameter of Sqrt_2\n *\n * \\return type T value\n *\n *\n**/\n\nnamespace boost { namespace simd\n{\n  namespace tag\n  {\n    /*!\n     * \\brief Define the tag Sqrt_2 of functor Sqrt_2\n     *        in namespace boost::simd::tag for toolbox boost.simd.constant\n    **/\n    BOOST_SIMD_CONSTANT_REGISTER( Sqrt_2, double, 1\n                                , 0x3FB504F3, 0x3ff6A09E667F3BCCULL\n                                );\n  }\n\n  BOOST_SIMD_CONSTANT_IMPLEMENTATION(boost::simd::tag::Sqrt_2, Sqrt_2)\n} }\n\n#include <boost/simd/sdk/constant/common.hpp>\n\n#endif\n", "meta": {"hexsha": "78766f97c008fee9a843c1a50ef80f78cadac6f5", "size": 1761, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/constant/include/boost/simd/constant/constants/sqrt_2.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/constant/include/boost/simd/constant/constants/sqrt_2.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/constant/include/boost/simd/constant/constants/sqrt_2.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": 24.8028169014, "max_line_length": 80, "alphanum_fraction": 0.5809199319, "num_tokens": 468, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.4754262894782685}}
{"text": "#ifdef COMPILATION// -*-indent-tabs-mode:t;c-basic-offset:4;tab-width:4-*-\n$CXX -DNDEBUG $0 -o $0x -lboost_timer&&$0x&&rm $0x;exit\n#endif\n// \u00a9 Alfredo A. Correa 2019-2020\n\n#include \"../array.hpp\"\n\n#include<iostream>\n#include<vector>\n#include<numeric> // iota\n#include<algorithm>\n\nnamespace multi = boost::multi;\nusing std::cout;\n\ntemplate<class Matrix, class Vector, class idx = typename std::decay_t<Vector>::difference_type>\nauto gj_solve(Matrix&& A, Vector&& y)->decltype(y[0]/=A[0][0], y){\n\tidx Asize = size(A);\n\tfor(idx r = 0; r != Asize; ++r){\n\t\tauto&& Ar = A[r]; auto const& Arr = Ar[r];\n\t\tfor(idx c = r + 1; c != Asize; ++c) Ar[c] /= Arr;\n\t\tauto const& yr = (y[r] /= Arr);\n\t\tfor(idx r2 = r + 1; r2 != Asize; ++r2){\n\t\t\tauto&& Ar2 = A[r2]; auto const& Ar2r = A[r2][r];\n\t\t\tfor(idx c = r + 1; c != Asize; ++c) Ar2[c] -= Ar2r*Ar[c];\n\t\t\ty[r2] -= Ar2r*yr;\n\t\t}\n\t}\n\tfor(idx r = Asize - 1; r > 0; --r){\n\t\tauto const& yr = y[r];\n\t\tfor(idx r2 = r-1; r2 >=0; --r2) y[r2] -= A[r2][r]*yr;\n\t}\n\treturn y;\n}\n\ntemplate<class Matrix, class Vector, class idx = typename std::decay_t<Vector>::difference_type>\nauto gj_solve2(Matrix&& A, Vector&& y)->decltype(y[0]/=A[0][0], y){\n\tidx Asize = size(A);\n\tfor(idx r = 0; r != Asize; ++r){\n\t\tauto&& Ar = A[r]; auto const& Arr = Ar[r];\n\t//\tstd::transform(Ar.begin() + r + 1, Ar.end(), Ar.begin() + r + 1, [&](auto const& a){return a/Arr;});\n\t\tfor(idx c = r + 1; c != Asize; ++c) Ar[c] /= Arr;\n\t\tauto const& yr = (y[r] /= Arr);\n\t\tfor(idx r2 = r + 1; r2 != Asize; ++r2){\n\t\t\tauto&& Ar2 = A[r2]; auto const& Ar2r = A[r2][r];\n\t\t\tstd::transform(std::move(Ar2).begin() + r + 1, std::move(Ar2).end(), std::move(Ar).begin() + r + 1, std::move(Ar2).begin() + r + 1, [&](auto&& a, auto&& b){return a - Ar2r*b;});\n\t\t\ty[r2] -= Ar2r*yr;\n\t\t}\n\t}\n\tfor(idx r = Asize - 1; r > 0; --r){\n\t\tauto const& yr = y[r];\n\t\tfor(idx r2 = r-1; r2 >=0; --r2) y[r2] -= A[r2][r]*yr;\n\t}\n\treturn y;\n}\n\n#include <boost/timer/timer.hpp>\n\nint main(){\n\t{\n\t\tmulti::array<double, 2> A = {{-3., 2., -4.},{0., 1., 2.},{2., 4., 5.}};\n\t\tmulti::array<double, 1> y = {12.,5.,2.}; //(M); assert(y.size() == M); iota(y.begin(), y.end(), 3.1);\n\t\tgj_solve(A, y);\n\t\tcout << y[0] <<\" \"<< y[1] <<\" \"<< y[2] << std::endl;\n\t}\n\t{\n\t\tmulti::array<double, 2> A({6000, 7000}); std::iota(A.data(), A.data() + A.num_elements(), 0.1);\n\t\tstd::transform(A.data(), A.data() + A.num_elements(), A.data(), [](auto x){return x/=2.e6;});\n\t\tstd::vector<double> y(3000); std::iota(y.begin(), y.end(), 0.2);\n\t\t{\n\t\t\tboost::timer::auto_cpu_timer t;\n\t\t\tgj_solve(A({1000, 4000}, {0, 3000}), y);\n\t\t}\n\t\tcout << y[45] << std::endl;\n\t}\n\t{\n\t\tmulti::array<double, 2> A({6000, 7000}); std::iota(A.data(), A.data() + A.num_elements(), 0.1);\n\t\tstd::transform(A.data(), A.data() + A.num_elements(), A.data(), [](auto x){return x/=2.e6;});\n\t\tstd::vector<double> y(3000); std::iota(y.begin(), y.end(), 0.2);\n\t\t{\n\t\t\tboost::timer::auto_cpu_timer t;\n\t\t\tgj_solve2(A({1000, 4000}, {0, 3000}), y);\n\t\t}\n\t\tcout << y[45] << std::endl;\n\t}\n}\n\n", "meta": {"hexsha": "3ea1b83746896a1a9231b18214b9c2f4f51817f1", "size": 2969, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/gj_solve.cpp", "max_stars_repo_name": "correaa/b-multi", "max_stars_repo_head_hexsha": "1e961f877662aa7a26933834f9064d2ec8b00b4a", "max_stars_repo_licenses": ["Intel"], "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/gj_solve.cpp", "max_issues_repo_name": "correaa/b-multi", "max_issues_repo_head_hexsha": "1e961f877662aa7a26933834f9064d2ec8b00b4a", "max_issues_repo_licenses": ["Intel"], "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": "examples/gj_solve.cpp", "max_forks_repo_name": "correaa/b-multi", "max_forks_repo_head_hexsha": "1e961f877662aa7a26933834f9064d2ec8b00b4a", "max_forks_repo_licenses": ["Intel"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7386363636, "max_line_length": 180, "alphanum_fraction": 0.5446278208, "num_tokens": 1169, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.4754262825331436}}
{"text": "\n// ratslam headers\n#include <Ratslam.hpp>\n#include <RatslamGraphics.h>\n\n// boost property trees\n#include <boost/property_tree/ptree.hpp>\n#include <boost/property_tree/ini_parser.hpp>\n\n// opencv for video input.\n#include <opencv2/opencv.hpp>\n#include <opencv2/highgui/highgui.hpp>\n\n#include <string>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n\ndouble time_diff_to_double(unsigned long sec2, unsigned long nsec2, unsigned long sec1, unsigned long nsec1)\n{\n\tdouble rsec, rnsec;\n\n\trsec = sec2 - sec1;\n\n\tif (nsec2 > nsec1)\n\t{\n\t\trnsec = nsec2 - nsec1;\n\t}\n\telse\n\t{\n\t\trnsec = 1000000000 - nsec1 + nsec2;\n\t\trsec--;\n\t}\n\n\treturn (double)rsec + 1.0/1000000000.0*(double)rnsec;\n}\n\nint main(int argc, char * argv[])\n{\n\tif (argc < 2)\n\t{\n\t\tstd::cout << argv[0] << \"(ERROR): Usage: ratslam config_file.txt\" << std::endl;\n\t\tcin.get();\n\t\treturn -1;\n\t}\n\t\n\t// read settings from the config file\n\tboost::property_tree::ptree settings;\n\tread_ini(argv[1], settings);\n\t\n\t// video reader for receiving camera input\n\tcv::VideoCapture video_reader;\n\tstd::string dataset_video_filename;\n\tstd::string dataset_csv_filename;\n\tstd::string csv_line;\n\tstd::istringstream iss;\n\t\n\t// read the video filename from the settings\n\tgri::get_setting_from_ptree<std::string>(dataset_video_filename, settings, \"gri.robot_name\", \"\");\n\tdataset_video_filename = \"log_\" + dataset_video_filename + \".avi\";\n\n\t// read the csv filename from the settings\n\tgri::get_setting_from_ptree<std::string>(dataset_csv_filename, settings, \"gri.robot_name\", \"\");\t\n\tdataset_csv_filename = \"log_\" + dataset_csv_filename + \".txt\";\t\t\n\n\tvideo_reader.open(dataset_video_filename);\n\tif (!video_reader.isOpened())\n\t{\n\t\tstd::cout << argv[0] << \"(ERROR): Failed to open video \" << \n\t\t\tdataset_video_filename << std::endl;\n\t\tcin.get();\n\t\treturn -1;\n\t}\n\t\n\t// open the robot's log as a csv to get translational and rotational \n\t// velocities, and time differences\n\tstd::ifstream csv_in(dataset_csv_filename.c_str());\n\tif (!csv_in.is_open())\n\t{\n\t\tstd::cout << argv[0] << \"(ERROR): Failed to open csv file \" << \n\t\t\tdataset_csv_filename << std::endl;\n\t\tcin.get();\n\t\treturn -1;\n\t}\n\t\n\t// discard the titles line\n\tgetline(csv_in, csv_line);\n\t\n\t// fetch the ratslam settings and construct a new ratslam object\n\tboost::property_tree::ptree ratslam_settings;\n\tgri::get_setting_child(ratslam_settings, settings, \"ratslam\");\n\tratslam::Ratslam * ratslam = new ratslam::Ratslam(ratslam_settings);\n\t\n\t// ratslam inputs\n\tcv::Mat frame;\n\tdouble delta_time_s, trans_vel, rot_vel;\n\tdouble time_s, last_time_s;\n\tunsigned long current_sec, current_nsec, last_sec, last_nsec;\n\t\n\t// construct a new ratslam graphics object to allow drawing ratslam\n\tboost::property_tree::ptree ratslam_graphics_settings;\n\tgri::get_setting_child(ratslam_graphics_settings, settings, \"draw\");\n\tIrrEventReceiver Event_Receiver;\n\tratslam::RatslamGraphics * ratslam_graphics =\n\t\tnew ratslam::RatslamGraphics(ratslam_graphics_settings, \n\t\t&Event_Receiver, ratslam);\n\n\n\t//discard one frame\n\tvideo_reader.grab();\n\n\t// get the associated csv information\n\tgetline(csv_in, csv_line, ',');\n\tiss.clear();\n\tiss.str(csv_line);\n\tiss >> last_sec;\n\tgetline(csv_in, csv_line, ',');\n\tiss.clear();\n\tiss.str(csv_line);\n\tiss >> last_nsec;\n\t\t\n\tgetline(csv_in, csv_line, '\\n');\n\n\t// start a processing loop\n\twhile (video_reader.grab() && ratslam_graphics->begin())\n\t{\n\t\t// get a frame from the video file \n\t\tvideo_reader.retrieve(frame, 0);\n\t\t\n\t\t// get the associated csv information\n\t\tgetline(csv_in, csv_line, ',');\n\t\tiss.clear();\n\t\tiss.str(csv_line);\n\t\tiss >> current_sec;\n\t\tgetline(csv_in, csv_line, ',');\n\t\tiss.clear();\n\t\tiss.str(csv_line);\n\t\tiss >> current_nsec;\n\n\t\tdelta_time_s = time_diff_to_double(current_sec, current_nsec, last_sec, last_nsec);\n\t\tlast_sec = current_sec;\n\t\tlast_nsec = current_nsec;\n\n\t\tgetline(csv_in, csv_line, ',');\n\t\tiss.clear();\n\t\tiss.str(csv_line);\n\t\tiss >> trans_vel;\n\t\tgetline(csv_in, csv_line, ',');\n\t\tiss.clear();\n\t\tiss.str(csv_line);\n\t\tiss >> rot_vel;\n\t\t\n\t\tgetline(csv_in, csv_line, '\\n');\n\t\t\n\t\t// set the ratslam inputs\n\t\tratslam->set_view_rgb(frame.data);\n\t\tratslam->set_odom(trans_vel, rot_vel);\n\t\tratslam->set_delta_time(delta_time_s);\n\t\t\n\t\t// process a single frame\n\t\tratslam->process();\n\t\t\n\t\tratslam_graphics->end();\n\t\t\n\t}\n\t\n\tdelete ratslam_graphics;\n\tdelete ratslam;\n\t\n\treturn 0;\n}\n", "meta": {"hexsha": "d0faf6d4eb628f07c67f99dbc9afd83c4127c5b5", "size": 4300, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ratslam-ratslam_ros/examples/opencv/main.cpp", "max_stars_repo_name": "feixiao5566/ratslam_feixiao5566", "max_stars_repo_head_hexsha": "5c5113bb95c698d8bb92b43f94b6563320c472ab", "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": "ratslam-ratslam_ros/examples/opencv/main.cpp", "max_issues_repo_name": "feixiao5566/ratslam_feixiao5566", "max_issues_repo_head_hexsha": "5c5113bb95c698d8bb92b43f94b6563320c472ab", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-10-31T00:59:32.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-31T00:59:32.000Z", "max_forks_repo_path": "ratslam-ratslam_ros/examples/opencv/main.cpp", "max_forks_repo_name": "feixiao5566/ratslam_feixiao5566", "max_forks_repo_head_hexsha": "5c5113bb95c698d8bb92b43f94b6563320c472ab", "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": 25.0, "max_line_length": 108, "alphanum_fraction": 0.7095348837, "num_tokens": 1194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.4754262789869637}}
{"text": "#ifndef KIDONO_FEATURE_EXTRACTOR_HPP\n#define KIDONO_FEATURE_EXTRACTOR_HPP\n\n#include <vector>\n#include <Eigen/Dense>\n#include <Eigen/StdVector>\n#include <boost/range/algorithm.hpp>\n#include <pcl/point_types.h>\n#include <pcl/point_cloud.h>\n#include <pcl/common/centroid.h>\n#include <pcl/filters/extract_indices.h>\n#include <pcl/filters/impl/plane_clipper3D.hpp>\n\nnamespace hdl_people_detection {\n\n/**\n * @brief A class to extract Kidono's features\n * @see Kiyosumi Kidono et al., \"Pedestrian Recognition Using High-definition LIDAR\"\n * @see http://www.aisl.cs.tut.ac.jp/~jun/pdffiles/kidono-iv2011.pdf\n */\nclass KidonoFeatureExtractor {\nprivate:\n  double distance_scale;\npublic:\n  /**\n   * @brief constructor\n   * @param distance_scale\n   */\n  KidonoFeatureExtractor(double distance_scale = 1.0)\n    : distance_scale(distance_scale)\n  {}\n\n  /**\n   * @brief extract features\n   * @param cloud  src cloud\n   * @return extracted feature vector\n   */\n  std::vector<float> extract(pcl::PointCloud<pcl::PointXYZI>::ConstPtr cloud) const {\n    std::vector<float> feature;\t\tfeature.reserve(256);\n    feature.push_back(cloud->points.size());\n    feature.push_back(minimumDistance(cloud) * distance_scale);\n\n    Eigen::Vector3f mean;\n    Eigen::Matrix3f covariance;\n\n    boost::copy(covariance3d(cloud, mean, covariance), std::back_inserter(feature));\n\n    auto centered_cloud = centeredCloud(cloud, mean);\n\n    boost::copy(inertiaMoment3d(cloud), std::back_inserter(feature));\n\n    Eigen::SelfAdjointEigenSolver<Eigen::Matrix3f> solver(covariance);\n\n    Eigen::Vector3f e1 = solver.eigenvectors().col(2);\n    Eigen::Vector3f e2 = solver.eigenvectors().col(1);\n    Eigen::Vector3f e3 = solver.eigenvectors().col(0);\n\n    if (e1.z() < 0.0f) {\n      e1 = -e1;\n    }\n\n    boost::copy(covarianceIn3zones(centered_cloud, e1, e2, e3), std::back_inserter(feature));\n    boost::copy(histogram2d(centered_cloud, e1, e2, 14, 7), std::back_inserter(feature));\n    boost::copy(histogram2d(centered_cloud, e1, e3, 9, 5), std::back_inserter(feature));\n    boost::copy(sliceFeature(centered_cloud, e1, e2, e3, 10), std::back_inserter(feature));\n    boost::copy(intensityDistribution(centered_cloud, 25), std::back_inserter(feature));\n\n    return feature;\n  }\n\nprivate:\n  template<typename T>\n  T square(T v) const { return v * v; }\n\n  pcl::PointCloud<pcl::PointXYZI>::Ptr centeredCloud(const pcl::PointCloud<pcl::PointXYZI>::ConstPtr& cloud, const Eigen::Vector3f& mean) const {\n    pcl::PointCloud<pcl::PointXYZI>::Ptr centered_cloud(new pcl::PointCloud<pcl::PointXYZI>());\n    centered_cloud->resize(cloud->size());\n    for (int i = 0; i < cloud->size(); i++) {\n      centered_cloud->at(i).getVector3fMap() = cloud->at(i).getVector3fMap() - mean;\n      centered_cloud->at(i).intensity = cloud->at(i).intensity;\n    }\n    centered_cloud->width = centered_cloud->size();\n    centered_cloud->height = 1;\n    centered_cloud->is_dense = false;\n\n    return centered_cloud;\n  }\n\n  float minimumDistance(const pcl::PointCloud<pcl::PointXYZI>::ConstPtr& cloud) const {\n    float dist = cloud->front().getVector3fMap().squaredNorm();\n    for (int i = 1; i < cloud->size(); i++) {\n      dist = std::min(dist, cloud->at(i).getVector3fMap().squaredNorm());\n    }\n    return sqrtf(dist);\n  }\n\n  std::vector<float> covariance3d(const pcl::PointCloud<pcl::PointXYZI>::ConstPtr& cloud, Eigen::Vector3f& mean, Eigen::Matrix3f& covariance) const {\n    Eigen::Vector4f centroid;\n    pcl::compute3DCentroid(*cloud, centroid);\n    pcl::computeCovarianceMatrix(*cloud, centroid, covariance);\n\n    mean = centroid.topLeftCorner(3, 1);\n\n    std::vector<float> feature(6);\n    feature[0] = covariance(0, 0);\t\tfeature[1] = covariance(0, 1);\t\tfeature[2] = covariance(0, 2);\n    feature[3] = covariance(1, 1);\t\tfeature[4] = covariance(1, 2);\n    feature[5] = covariance(2, 2);\n    return feature;\n  }\n\n  std::vector<float> inertiaMoment3d(const pcl::PointCloud<pcl::PointXYZI>::ConstPtr& centered_cloud) const {\n    std::vector<float> feature(6, 0.0f);\n\n    for (int i = 0; i < centered_cloud->size(); i++) {\n      const auto& pt = centered_cloud->at(i);\n      feature[0] += square(pt.y) + square(pt.z);\n      feature[1] += -pt.x * pt.y;\n      feature[2] += -pt.x * pt.z;\n      feature[3] += square(pt.x) + square(pt.z);\n      feature[4] += -pt.y * pt.z;\n      feature[5] += square(pt.x) + square(pt.y);\n    }\n\n    return feature;\n  }\n\n  std::vector<float> covariance2d(const pcl::PointCloud<pcl::PointXYZI>::ConstPtr& cloud, const Eigen::Vector3f& e1, const Eigen::Vector3f& e2) const {\n    if (cloud->empty()){\n      return std::vector<float>(3, 0.0f);\n    }\n\n    Eigen::MatrixXf ptdata(cloud->size(), 2);\n    for (int i = 0; i < cloud->size(); i++) {\n      ptdata(i, 0) = cloud->at(i).getVector3fMap().dot(e1);\n      ptdata(i, 1) = cloud->at(i).getVector3fMap().dot(e2);\n    }\n\n    Eigen::Vector2f mean = ptdata.colwise().mean().transpose();\n    Eigen::MatrixXf centered = ptdata.rowwise() - mean.transpose();\n    Eigen::Matrix2f covariance = (centered.transpose() * centered) / cloud->size();\n\n    std::vector<float> feature(3);\n    feature[0] = covariance(0, 0);\tfeature[1] = covariance(0, 1);\n    feature[2] = covariance(1, 1);\n\n    return feature;\n  }\n\n  std::vector<float> covarianceIn3zones(const pcl::PointCloud<pcl::PointXYZI>::ConstPtr& centered_cloud, const Eigen::Vector3f& e1, const Eigen::Vector3f& e2, const Eigen::Vector3f& e3) const {\n    pcl::PointCloud<pcl::PointXYZI>::Ptr upper_cloud(new pcl::PointCloud<pcl::PointXYZI>());\n    pcl::PointCloud<pcl::PointXYZI>::Ptr lower_cloud(new pcl::PointCloud<pcl::PointXYZI>());\n    pcl::PointCloud<pcl::PointXYZI>::Ptr right_cloud(new pcl::PointCloud<pcl::PointXYZI>());\n    pcl::PointCloud<pcl::PointXYZI>::Ptr left_cloud(new pcl::PointCloud<pcl::PointXYZI>());\n\n    pcl::PointIndices::Ptr indices(new pcl::PointIndices());\n\n    pcl::PlaneClipper3D<pcl::PointXYZI> clipper(Eigen::Vector4f(e1.x(), e1.y(), e1.z(), 0.0f));\n    clipper.clipPointCloud3D(*centered_cloud, indices->indices);\n\n    pcl::ExtractIndices<pcl::PointXYZI> extract;\n    extract.setInputCloud(centered_cloud);\n    extract.setIndices(indices);\n    extract.filter(*upper_cloud);\n\n    extract.setNegative(true);\n    extract.filter(*lower_cloud);\n\n    indices->indices.clear();\n    clipper.setPlaneParameters(Eigen::Vector4f(e2.x(), e2.y(), e2.z(), 0.0f));\n    clipper.clipPointCloud3D(*lower_cloud, indices->indices);\n\n    extract.setInputCloud(lower_cloud);\n    extract.setIndices(indices);\n    extract.setNegative(false);\n    extract.filter(*left_cloud);\n\n    extract.setNegative(true);\n    extract.filter(*right_cloud);\n\n    std::vector<float> feature;\t\tfeature.reserve(9);\n    boost::copy(covariance2d(upper_cloud, e1, e2), std::back_inserter(feature));\n    boost::copy(covariance2d(left_cloud, e1, e2), std::back_inserter(feature));\n    boost::copy(covariance2d(right_cloud, e1, e2), std::back_inserter(feature));\n\n    return feature;\n  }\n\n  std::vector<float> histogram2d(const pcl::PointCloud<pcl::PointXYZI>::ConstPtr& cloud, const Eigen::Vector3f& axis1, const Eigen::Vector3f& axis2, int bin1, int bin2) const {\n    std::vector<Eigen::Vector2f> pts2d(cloud->size());\n    for (int i = 0; i < cloud->size(); i++) {\n      pts2d[i][0] = cloud->at(i).getVector3fMap().dot(axis1);\n      pts2d[i][1] = cloud->at(i).getVector3fMap().dot(axis2);\n    }\n\n    Eigen::Array2f min_pt = pts2d.front();\n    Eigen::Array2f max_pt = pts2d.front();\n    for (int i = 1; i < pts2d.size(); i++) {\n      min_pt = pts2d[i].array().min(min_pt);\n      max_pt = pts2d[i].array().max(max_pt);\n    }\n\n    Eigen::Array2f size = max_pt - min_pt;\n    Eigen::Array2f inv_size = Eigen::Array2f(bin1 - 0.1f, bin2 - 0.1f) / size;\n\n    float weight = 1.0f / pts2d.size();\n    std::vector<float> hist(bin1 * bin2, 0.0f);\n    for (int i = 0; i < pts2d.size(); i++) {\n      Eigen::Array2i index = ((pts2d[i].array() - min_pt) * inv_size).cast<int>();\n      hist[index[0] + index[1] * bin1] += weight;\n    }\n\n    return hist;\n  }\n\n  std::vector<float> sliceFeature(const pcl::PointCloud<pcl::PointXYZI>::ConstPtr& centered_cloud, const Eigen::Vector3f& e1, const Eigen::Vector3f& e2, const Eigen::Vector3f& e3, int slice_n = 10) const {\n    Eigen::Matrix3f cvt2eigenspace;\n    cvt2eigenspace << e1.transpose(), e2.transpose(), e3.transpose();\n\n    float e1_min = 9999.0f;\n    float e1_max = -9999.0f;\n\n    std::vector<Eigen::Vector3f> aligned_cloud(centered_cloud->size());\n    for (int i = 0; i < centered_cloud->size(); i++) {\n      aligned_cloud[i] = cvt2eigenspace * centered_cloud->at(i).getVector3fMap();\n      e1_min = std::min(e1_min, aligned_cloud[i][0]);\n      e1_max = std::max(e1_max, aligned_cloud[i][0]);\n    }\n\n    float height = e1_max - e1_min;\n    float scale = (slice_n - 0.1f) / height;\n\n    std::vector<Eigen::Array2f> min_pts(slice_n);\n    std::vector<Eigen::Array2f> max_pts(slice_n);\n    for (int i = 0; i < slice_n; i++) {\n      min_pts[i] = Eigen::Array2f::Ones() * 9999.0f;\n      max_pts[i] = Eigen::Array2f::Ones() * -9999.0f;\n    }\n\n    for (int i = 0; i < aligned_cloud.size(); i++) {\n      int n = static_cast<int>((aligned_cloud[i][0] - e1_min) * scale);\n      min_pts[n] = min_pts[n].min(aligned_cloud[i].bottomLeftCorner(2, 1).array());\n      max_pts[n] = max_pts[n].max(aligned_cloud[i].bottomLeftCorner(2, 1).array());\n    }\n\n    std::vector<float> feature;\n    feature.reserve(slice_n * 2);\n\n    for (int i = 0; i < slice_n; i++){\n      Eigen::Array2f w = max_pts[i] - min_pts[i];\n      if (w[0] > 0.0f && w[1] > 0.0f) {\n        feature.push_back(w[0]);\n        feature.push_back(w[1]);\n      }\n      else {\n        feature.push_back(0.0f);\n        feature.push_back(0.0f);\n      }\n    }\n\n    return feature;\n  }\n\n  std::vector<float> intensityDistribution(const pcl::PointCloud<pcl::PointXYZI>::ConstPtr& centered_cloud, int hist_n = 25) const {\n    Eigen::ArrayXf intensity(centered_cloud->size());\n    for (int i = 0; i < centered_cloud->size(); i++) {\n      intensity[i] = centered_cloud->at(i).intensity;\n    }\n\n    float weight = 1.0f / intensity.size();\n    std::vector<float> feature(hist_n + 2, 0.0f);\n\n    float scale = (hist_n - 0.1f) / 255.0f;\n    for (int i = 0; i < intensity.size(); i++) {\n      int n = static_cast<int>(intensity[i] * scale);\n      feature[n] += weight;\n    }\n\n    float mean = intensity.mean();\n    float stddev = sqrt((intensity - mean).square().mean());\n\n    feature[hist_n] = mean;\n    feature[hist_n + 1] = stddev;\n\n    return feature;\n  }\n};\n\n}\n\n\n#endif\n", "meta": {"hexsha": "1f2a03bebf162b07e4a49f3ae0d1ffb4f57fc8d6", "size": 10474, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/hdl_people_detection/kidono_feature_extractor.hpp", "max_stars_repo_name": "y-lai/hdl_people_tracking", "max_stars_repo_head_hexsha": "fb7ec799047b8ea833a175abd2599793b8966c24", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 207.0, "max_stars_repo_stars_event_min_datetime": "2018-03-10T14:56:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T07:32:53.000Z", "max_issues_repo_path": "include/hdl_people_detection/kidono_feature_extractor.hpp", "max_issues_repo_name": "y-lai/hdl_people_tracking", "max_issues_repo_head_hexsha": "fb7ec799047b8ea833a175abd2599793b8966c24", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 24.0, "max_issues_repo_issues_event_min_datetime": "2018-02-19T10:50:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T19:44:55.000Z", "max_forks_repo_path": "include/hdl_people_detection/kidono_feature_extractor.hpp", "max_forks_repo_name": "y-lai/hdl_people_tracking", "max_forks_repo_head_hexsha": "fb7ec799047b8ea833a175abd2599793b8966c24", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 91.0, "max_forks_repo_forks_event_min_datetime": "2018-02-23T09:44:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-03T01:38:14.000Z", "avg_line_length": 35.8698630137, "max_line_length": 205, "alphanum_fraction": 0.6535230094, "num_tokens": 3144, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.6297746004557471, "lm_q1q2_score": 0.4754262772874914}}
{"text": "//\n//  Copyright (c) 2007\n//  Tsai, Dung-Bang\t\n//  National Taiwan University, Department of Physics\n// \n//  E-Mail : dbtsai (at) gmail.com\n//  Begine : 2007/11/20\n//  Last modify : 2007/11/22\n//  Version : v0.1\n//\n//  EXPGM_PAD computes the matrix exponential exp(H) for general matrixs,\n//  including complex and real matrixs using the irreducible (p,p) degree\n//  rational Pade approximation to the exponential \n//  exp(z) = r(z)=(+/-)( I+2*(Q(z)/P(z))).\n//\n//  Usage : \n//\n//    U = expm_pad(H)\n//    U = expm_pad(H, p)\n//    \n//    where p is internally set to 6 (recommended and gererally satisfactory).\n//\n//  See also MATLAB supplied functions, EXPM and EXPM1.\n//\n//  Reference :\n//  EXPOKIT, Software Package for Computing Matrix Exponentials.\n//  ACM - Transactions On Mathematical Software, 24(1):130-156, 1998\n//\n//  Permission to use, copy, modify, distribute and sell this software\n//  and its documentation for any purpose is hereby granted without fee,\n//  provided that the above copyright notice appear in all copies and\n//  that both that copyright notice and this permission notice appear\n//  in supporting documentation.  The authors make no representations\n//  about the suitability of this software for any purpose.\n//  It is provided \"as is\" without express or implied warranty.\n//\n\n#ifndef BOOST_NUMERIC_UBLASX_OPERATION_EXPM_HPP\n#define BOOST_NUMERIC_UBLASX_OPERATION_EXPM_HPP\n\n\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n#include <complex>\n#include <stdexcept>\n\n\nnamespace boost { namespace numeric { namespace ublasx {\n\n\ntemplate<typename MATRIX>\nMATRIX expm_pad(const MATRIX &H, const int p = 6)\n{\n\ttypedef typename MATRIX::value_type value_type;\n        typedef typename MATRIX::size_type size_type;\n\ttypedef double real_value_type;\t// Correct me. Need to modify.\n\tassert(H.size1() == H.size2());\t\n\tconst size_type n = H.size1();\n\tconst identity_matrix<value_type> I(n);\n\tmatrix<value_type> U(n,n),H2(n,n),P(n,n),Q(n,n);\n\treal_value_type norm = 0.0;\n\n// Calcuate Pade coefficients  (1-based instead of 0-based as in the c vector)\n\tvector<real_value_type> c(p+2);\n\tc(1)=1;  \n\tfor(size_type i = 1; i <= p; ++i) \n\t\tc(i+1) = c(i) * ((p + 1.0 - i)/(i * (2.0 * p + 1 - i)));\n// Calcuate the infinty norm of H, which is defined as the largest row sum of a matrix\n\tfor(size_type i=0; i<n; ++i)\n\t{\n\t\treal_value_type temp = 0.0;\n\t\tfor(size_type j=0;j<n;j++)\n\t\t\ttemp += std::abs<real_value_type>(H(i,j)); // Correct me, if H is complex, can I use that abs?\n\t\tnorm = std::max<real_value_type>(norm, temp);\n\t}\n\tif (norm == 0.0) \n\t{\n\t\tthrow ::std::runtime_error(\"[expm_pad] Error: null input.\");\n\t}\n// Scaling, seek s such that || H*2^(-s) || < 1/2, and set scale = 2^(-s)\n \tint s = 0;\n\treal_value_type scale = 1.0;\n\tif(norm > 0.5)\n\t{\n\t\ts = std::max<int>(0, static_cast<int>((log(norm) / log(2.0) + 2.0)));\n\t\tscale /= static_cast<real_value_type>(std::pow(2.0, s));\n\t\tU.assign(scale * H); // Here U is used as temp value due to that H is const\n\t}\n// Horner evaluation of the irreducible fraction, see the following ref above.\n// Initialise P (numerator) and Q (denominator) \n\tH2.assign( prod(U, U) );\n\tQ.assign( c(p+1)*I );\n\tP.assign( c(p)*I );\n\tsize_type odd = 1;\n\tfor( size_type k = p - 1; k > 0; --k)\n\t{\n\t\tif( odd == 1)\n\t\t{\n\t\t\tQ = ( prod(Q, H2) + c(k) * I ); \n\t\t}\n\t\telse\n\t\t{\n\t\t\tP = ( prod(P, H2) + c(k) * I );\n\t\t}\n\t\todd = 1 - odd;\n\t}\n\tif( odd == 1)\n\t{\n\t\tQ = ( prod(Q, U) );\t\n\t\tQ -= P ;\n\t\t//U.assign( -(I + 2*(Q\\P)));\n\t}\n\telse\n\t{\n\t\tP = (prod(P, U));\n\t\tQ -= P;\n\t\t//U.assign( I + 2*(Q\\P));\n\t}\n// In origine expokit package, they use lapack ZGESV to obtain inverse matrix,\n// and in that ZGESV routine, it uses LU decomposition for obtaing inverse matrix.\n// Since in ublas, there is no matrix inversion template, I simply use the build-in\n// LU decompostion package in ublas, and back substitute by myself.\n//\n//////////////// Implement Matrix Inversion ///////////////////////\n\tpermutation_matrix<size_type> pm(n); \n\tint res = lu_factorize(Q, pm);\n\tif( res != 0)\n\t{\n\t\tthrow ::std::runtime_error(\"[expm_pad] Error: matrix inversion in template expm_pad.\");\n\t}\n\tH2 = I;  // H2 is not needed anymore, so it is temporary used as identity matrix for substituting.\n\tlu_substitute(Q, pm, H2); \n\tif( odd == 1)\n\t\tU.assign( -(I + 2.0 * prod(H2, P)));\n \telse\n\t\tU.assign( I + 2.0 * prod(H2, P));\n// Squaring \n\tfor(size_t i = 0; i < s; ++i)\n\t{\n\t\tU = (prod(U,U));\n\t}\n\treturn U;\n}\n\n}}} // Namespace boost::numeric::ublasx\n\n\n#endif // BOOST_NUMERIC_UBLASX_OPERATION_EXPM_HPP\n", "meta": {"hexsha": "0d71a40f67ce7531442279ddebfd6451b65015d0", "size": 4555, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/ublasx/operation/expm.hpp", "max_stars_repo_name": "comcon1/boost-ublasx", "max_stars_repo_head_hexsha": "290b92b643a944825df99bece3468a4f81518056", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "boost/numeric/ublasx/operation/expm.hpp", "max_issues_repo_name": "comcon1/boost-ublasx", "max_issues_repo_head_hexsha": "290b92b643a944825df99bece3468a4f81518056", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "boost/numeric/ublasx/operation/expm.hpp", "max_forks_repo_name": "comcon1/boost-ublasx", "max_forks_repo_head_hexsha": "290b92b643a944825df99bece3468a4f81518056", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3666666667, "max_line_length": 99, "alphanum_fraction": 0.648518112, "num_tokens": 1425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916205190225, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.475389785599181}}
{"text": "#ifndef ALM_HERMITE_QUATERNION_CURVE_H\n#define ALM_HERMITE_QUATERNION_CURVE_H\n\n#include <Eigen/Dense>\n#include <iostream>\n#include <math.h>\n#include <algorithm>\n\nclass HermiteQuaternionCurve{\npublic:\n\tHermiteQuaternionCurve(const Eigen::Quaterniond & quat_start, const Eigen::Vector3d & angular_velocity_start,\n\t\t\t\t\t\t   const Eigen::Quaterniond & quat_end, const Eigen::Vector3d & angular_velocity_end);\n\t~HermiteQuaternionCurve();\n\n\t// All values are expressed in \"world frame\"\n\tvoid evaluate(const double & s_in, Eigen::Quaterniond & quat_out);\n\tvoid getAngularVelocity(const double & s_in, Eigen::Vector3d & ang_vel_out);\n\tvoid getAngularAcceleration(const double & s_in, Eigen::Vector3d & ang_acc_out);\n\nprivate:\n\tEigen::Quaterniond qa; // Starting quaternion\n\tEigen::Vector3d omega_a; // Starting Angular Velocity\n\tEigen::Quaterniond qb; // Ending quaternion\n\tEigen::Vector3d omega_b; // Ending Angular velocity\n\n\tEigen::AngleAxisd omega_a_aa; // axis angle representation of omega_a\n\tEigen::AngleAxisd omega_b_aa; // axis angle representation of omega_b\n\n\tvoid initialize_data_structures();\n\n\tvoid computeBasis(const double & s_in); // computes the basis functions\n\tvoid computeOmegas();\n\n\tEigen::Quaterniond q0; // quat0\n\tEigen::Quaterniond q1; // quat1\n\tEigen::Quaterniond q2; // quat1\n\tEigen::Quaterniond q3; // quat1\n\n\tdouble b1; // basis 1\n\tdouble b2; // basis 2\n\tdouble b3; // basis 3\n\n\tdouble bdot1; // 1st derivative of basis 1\n\tdouble bdot2; // 1st derivative of basis 2\n\tdouble bdot3; // 1st derivative of basis 3\n\n\tdouble bddot1; // 2nd derivative of basis 1\n\tdouble bddot2; // 2nd derivative of basis 2\n\tdouble bddot3; // 2nd derivative of basis 3\n\n\tEigen::Vector3d omega_1;\n\tEigen::Vector3d omega_2;\n\tEigen::Vector3d omega_3;\n\n\tEigen::AngleAxisd omega_1aa;\n\tEigen::AngleAxisd omega_2aa;\n\tEigen::AngleAxisd omega_3aa;\n\n\t// Allocate memory for quaternion operations\n\tEigen::Quaterniond qtmp1;\n\tEigen::Quaterniond qtmp2;\n\tEigen::Quaterniond qtmp3;\n\n\t// progression variable\n\tdouble s_;\n\t// by default clamps within 0 and 1.\n\tdouble clamp(const double & s_in, double lo = 0.0, double hi = 1.0);\n\n\tvoid printQuat(const Eigen::Quaterniond & quat);\n\n};\n\n#endif", "meta": {"hexsha": "b5d0af06839f3393816749083ed5ee3c10dc2a8f", "size": 2172, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/avatar_locomanipulation/helpers/hermite_quaternion_curve.hpp", "max_stars_repo_name": "stevenjj/icra2020locomanipulation", "max_stars_repo_head_hexsha": "414085b68cc1b3b24f7b920b543bba9d95350c16", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-01-06T11:43:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-14T22:59:09.000Z", "max_issues_repo_path": "include/avatar_locomanipulation/helpers/hermite_quaternion_curve.hpp", "max_issues_repo_name": "stevenjj/icra2020locomanipulation", "max_issues_repo_head_hexsha": "414085b68cc1b3b24f7b920b543bba9d95350c16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/avatar_locomanipulation/helpers/hermite_quaternion_curve.hpp", "max_forks_repo_name": "stevenjj/icra2020locomanipulation", "max_forks_repo_head_hexsha": "414085b68cc1b3b24f7b920b543bba9d95350c16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-09-03T16:08:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T11:13:49.000Z", "avg_line_length": 29.7534246575, "max_line_length": 110, "alphanum_fraction": 0.7541436464, "num_tokens": 616, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.4753135227152815}}
{"text": "// Copyright Louis Dionne 2013-2016\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#include <boost/hana/assert.hpp>\n#include <boost/hana/back.hpp>\n#include <boost/hana/drop_front.hpp>\n#include <boost/hana/equal.hpp>\n#include <boost/hana/front.hpp>\n#include <boost/hana/integral_constant.hpp>\n#include <boost/hana/range.hpp>\nnamespace hana = boost::hana;\n\n\nBOOST_HANA_CONSTANT_CHECK(hana::front(hana::range_c<int, 0, 5>) == hana::int_c<0>);\nBOOST_HANA_CONSTANT_CHECK(hana::back(hana::range_c<unsigned long, 0, 5>) == hana::ulong_c<4>);\nBOOST_HANA_CONSTANT_CHECK(hana::drop_front(hana::range_c<int, 0, 5>) == hana::make_range(hana::int_c<1>, hana::int_c<5>));\n\nint main() { }\n", "meta": {"hexsha": "b1598be81e045912265e1d8f99b081db7ca37bd0", "size": 772, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.62.0/libs/hana/example/range/range_c.cpp", "max_stars_repo_name": "sita1999/arangodb", "max_stars_repo_head_hexsha": "6a4f462fa209010cd064f99e63d85ce1d432c500", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2016-03-04T15:44:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-31T11:06:25.000Z", "max_issues_repo_path": "3rdParty/boost/1.62.0/libs/hana/example/range/range_c.cpp", "max_issues_repo_name": "lipper/arangodb", "max_issues_repo_head_hexsha": "66ea1fd4946668192e3f0d1060f0844f324ad7b8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 49.0, "max_issues_repo_issues_event_min_datetime": "2016-02-29T17:59:52.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-05T04:59:26.000Z", "max_forks_repo_path": "3rdParty/boost/1.62.0/libs/hana/example/range/range_c.cpp", "max_forks_repo_name": "lipper/arangodb", "max_forks_repo_head_hexsha": "66ea1fd4946668192e3f0d1060f0844f324ad7b8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2015-11-02T09:37:09.000Z", "max_forks_repo_forks_event_max_datetime": "2017-05-05T06:38:49.000Z", "avg_line_length": 38.6, "max_line_length": 122, "alphanum_fraction": 0.7396373057, "num_tokens": 231, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.6370307875894139, "lm_q1q2_score": 0.47531351757366047}}
{"text": "// -----------------------------------------------------------------------------\n// Fern \u00a9 Geoneric\n//\n// This file is part of Geoneric Fern which is available under the terms of\n// the GNU General Public License (GPL), version 2. If you do not want to\n// be bound by the terms of the GPL, you may purchase a proprietary license\n// from Geoneric (http://www.geoneric.eu/contact).\n// -----------------------------------------------------------------------------\n#define BOOST_TEST_MODULE fern algorithm algebra elementary factorial\n#include <boost/test/unit_test.hpp>\n#include \"fern/core/data_customization_point/scalar.h\"\n#include \"fern/algorithm/core/test/test_utils.h\"\n#include \"fern/algorithm/algebra/elementary/factorial.h\"\n\n\nnamespace fa = fern::algorithm;\n\n\ntemplate<\n    class Value>\nusing OutOfDomainPolicy = fa::factorial::OutOfDomainPolicy<Value>;\n\n\nBOOST_AUTO_TEST_CASE(out_of_domain_policy)\n{\n    {\n        OutOfDomainPolicy<int> policy;\n        BOOST_CHECK( policy.within_domain(5));\n        BOOST_CHECK(!policy.within_domain(-5));\n        BOOST_CHECK( policy.within_domain(0));\n        BOOST_CHECK( policy.within_domain(-0));\n    }\n\n    {\n        OutOfDomainPolicy<double> policy;\n        BOOST_CHECK( policy.within_domain(5));\n        BOOST_CHECK(!policy.within_domain(-5));\n        BOOST_CHECK(!policy.within_domain(-5.01));\n        BOOST_CHECK(!policy.within_domain(-4.99));\n        BOOST_CHECK( policy.within_domain(0));\n        BOOST_CHECK( policy.within_domain(-0));\n    }\n}\n\n\ntemplate<\n    class Value,\n    class Result>\nusing OutOfRangePolicy = fa::factorial::OutOfRangePolicy<Value, Result>;\n\n\ntemplate<\n    class Value,\n    class Result>\nstruct VerifyWithinRange\n{\n    bool operator()(\n        Value const& value)\n    {\n        fa::SequentialExecutionPolicy sequential;\n\n        OutOfRangePolicy<Value, Result> policy;\n        Result result;\n\n        fa::algebra::factorial(sequential, value, result);\n\n        return policy.within_range(value, result);\n    }\n};\n\n\nBOOST_AUTO_TEST_CASE(out_of_range_policy)\n{\n    {\n        VerifyWithinRange<uint8_t, uint8_t> verify;\n        BOOST_CHECK_EQUAL(verify(0), true);\n        BOOST_CHECK_EQUAL(verify(5), true);\n        BOOST_CHECK_EQUAL(verify(6), false);\n    }\n\n    {\n        VerifyWithinRange<int32_t, int32_t> verify;\n        BOOST_CHECK_EQUAL(verify(0), true);\n        BOOST_CHECK_EQUAL(verify(5), true);\n        BOOST_CHECK_EQUAL(verify(6), true);\n        BOOST_CHECK_EQUAL(verify(11), true);\n        BOOST_CHECK_EQUAL(verify(13), false);\n    }\n\n    {\n        VerifyWithinRange<uint32_t, uint32_t> verify;\n        BOOST_CHECK_EQUAL(verify(0), true);\n        BOOST_CHECK_EQUAL(verify(5), true);\n        BOOST_CHECK_EQUAL(verify(11), true);\n        BOOST_CHECK_EQUAL(verify(13), false);\n    }\n\n    {\n        VerifyWithinRange<uint64_t, uint64_t> verify;\n        BOOST_CHECK_EQUAL(verify(0), true);\n        BOOST_CHECK_EQUAL(verify(5), true);\n        BOOST_CHECK_EQUAL(verify(20), true);\n        BOOST_CHECK_EQUAL(verify(21), false);\n    }\n\n    {\n        VerifyWithinRange<float, float> verify;\n        BOOST_CHECK_EQUAL(verify(34.0f), true);\n        BOOST_CHECK_EQUAL(verify(35.0f), false);\n        BOOST_CHECK_EQUAL(verify(fern::infinity<float>()), false);\n    }\n\n    {\n        VerifyWithinRange<double, double> verify;\n        BOOST_CHECK_EQUAL(verify(170.0), true);\n        BOOST_CHECK_EQUAL(verify(171.0), false);\n        BOOST_CHECK_EQUAL(verify(fern::infinity<double>()), false);\n    }\n}\n\n\ntemplate<\n    class Value,\n    class Result>\nvoid verify_integral_value(\n    Value const& value,\n    Result const& result_we_want)\n{\n    fa::SequentialExecutionPolicy sequential;\n\n    Result result_we_get;\n    fa::algebra::factorial(sequential, value, result_we_get);\n\n    BOOST_CHECK_EQUAL(result_we_get, result_we_want);\n}\n\n\ntemplate<\n    class Value,\n    class Result>\nvoid verify_floating_point_value(\n    Value const& value,\n    Result const& result_we_want)\n{\n    fa::SequentialExecutionPolicy sequential;\n\n    Result result_we_get;\n    fa::algebra::factorial(sequential, value, result_we_get);\n\n    BOOST_CHECK_CLOSE(result_we_get, result_we_want, 1e-6);\n}\n\n\nBOOST_AUTO_TEST_CASE(algorithm)\n{\n    {\n        verify_integral_value<uint8_t, uint8_t>(0, 1);\n        verify_integral_value<uint8_t, uint8_t>(1, 1);\n        verify_integral_value<uint8_t, uint8_t>(2, 2);\n        verify_integral_value<uint8_t, uint8_t>(3, 6);\n        verify_integral_value<uint8_t, uint8_t>(5, 120);\n    }\n\n    {\n        verify_integral_value<int32_t, int32_t>(0, 1);\n        verify_integral_value<int32_t, int32_t>(1, 1);\n        verify_integral_value<int32_t, int32_t>(2, 2);\n        verify_integral_value<int32_t, int32_t>(3, 6);\n        verify_integral_value<int32_t, int32_t>(6, 720);\n        verify_integral_value<int32_t, int32_t>(12, 479001600);\n    }\n\n    {\n        verify_floating_point_value<double, double>(0.0, 1.0);\n        verify_floating_point_value<double, double>(1.0, 1.0);\n        verify_floating_point_value<double, double>(10.0, 3628800.0);\n    }\n}\n", "meta": {"hexsha": "241df02c44a5e0380ddd069f90e1ee1aa7f13589", "size": 5021, "ext": "cc", "lang": "C++", "max_stars_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/fern/source/fern/algorithm/algebra/elementary/test/factorial_test.cc", "max_stars_repo_name": "quanpands/wflow", "max_stars_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/fern/source/fern/algorithm/algebra/elementary/test/factorial_test.cc", "max_issues_repo_name": "quanpands/wflow", "max_issues_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/fern/source/fern/algorithm/algebra/elementary/test/factorial_test.cc", "max_forks_repo_name": "quanpands/wflow", "max_forks_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0502793296, "max_line_length": 80, "alphanum_fraction": 0.6526588329, "num_tokens": 1227, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.4753135155231725}}
{"text": "/*\n *\n * Copyright (c) Toon Knapen, Karl Meerbergen & 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_SYEV_HPP\n#define BOOST_NUMERIC_BINDINGS_LAPACK_SYEV_HPP\n\n#include <boost/numeric/bindings/traits/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\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK\n#  include <boost/static_assert.hpp>\n#  include <boost/type_traits.hpp>\n#endif\n\n#include <cassert>\n\n\nnamespace boost { namespace numeric { namespace bindings {\n\n  namespace lapack {\n\n    ///////////////////////////////////////////////////////////////////\n    //\n    // Eigendecomposition of a real symmetric matrix A = Q * D * Q'\n    //\n    ///////////////////////////////////////////////////////////////////\n\n    /*\n     * syev() computes the eigendecomposition of a N x N matrix\n     * A = Q * D * Q',  where Q is a N x N orthogonal matrix and\n     * D is a diagonal matrix. The diagonal elements D(i,i) is an\n     * eigenvalue of A and Q(:,i) is a corresponding eigenvector.\n     *\n     * On return of syev, A is overwritten by Q and w contains the main\n     * diagonal of D.\n     *\n     * int syev (char jobz, char uplo, A& a, W& w, minimal_workspace ) ;\n     *    jobz : 'V' : compute eigenvectors\n     *           'N' : do not compute eigenvectors\n     *    uplo : 'U' : only the upper triangular part of A is used on input.\n     *           'L' : only the lower triangular part of A is used on input.\n     */\n\n    namespace detail {\n\n      inline\n      void syev (char const jobz, char const uplo, integer_t const n,\n                 float* a, integer_t const lda,\n                 float* w, float* work, integer_t const lwork, integer_t& info)\n      {\n        LAPACK_SSYEV (&jobz, &uplo, &n, a, &lda, w, work, &lwork, &info);\n      }\n\n      inline\n      void syev (char const jobz, char const uplo, integer_t const n,\n                 double* a, integer_t const lda,\n                 double* w, double* work, integer_t const lwork, integer_t& info)\n      {\n        LAPACK_DSYEV (&jobz, &uplo, &n, a, &lda, w, work, &lwork, &info);\n      }\n\n\n      template <typename A, typename W, typename Work>\n      int syev (char jobz, char uplo, A& a, W& w, Work& work) {\n\n/*#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK\n        BOOST_STATIC_ASSERT((boost::is_same<\n          typename traits::matrix_traits<A>::matrix_structure,\n          traits::general_t\n        >::value));\n#endif*/\n\n        integer_t const n = traits::matrix_size1 (a);\n        assert ( n>0 );\n        assert (traits::matrix_size2 (a)==n);\n        assert (traits::leading_dimension (a)>=n);\n        assert (traits::vector_size (w)==n);\n        assert (3*n-1 <= traits::vector_size (work));\n        assert ( uplo=='U' || uplo=='L' );\n        assert ( jobz=='N' || jobz=='V' );\n\n        integer_t info;\n        detail::syev (jobz, uplo, n,\n                     traits::matrix_storage (a),\n                     traits::leading_dimension (a),\n                     traits::vector_storage (w),\n                     traits::vector_storage (work),\n                     traits::vector_size (work),\n                     info);\n        return info;\n      }\n    }  // namespace detail\n\n\n    // Function that allocates work arrays\n    template <typename A, typename W>\n    int syev (char jobz, char uplo, A& a, W& w, optimal_workspace ) {\n       typedef typename A::value_type value_type ;\n\n       std::ptrdiff_t const n = traits::matrix_size1 (a);\n\n       traits::detail::array<value_type> work( std::max<std::ptrdiff_t>(1,34*n) );\n       return detail::syev(jobz, uplo, a, w, work);\n    } // syev()\n\n\n    // Function that allocates work arrays\n    template <typename A, typename W>\n    int syev (char jobz, char uplo, A& a, W& w, minimal_workspace ) {\n       typedef typename A::value_type value_type ;\n\n       std::ptrdiff_t const n = traits::matrix_size1 (a);\n\n       traits::detail::array<value_type> work( std::max<std::ptrdiff_t>(1,3*n-1) );\n       return detail::syev(jobz, uplo, a, w, work);\n    } // syev()\n\n\n    // Function that allocates work arrays\n    template <typename A, typename W, typename Work>\n    int syev (char jobz, char uplo, A& a, W& w, detail::workspace1<Work> workspace ) {\n       typedef typename traits::matrix_traits<A>::value_type value_type ;\n\n       return detail::syev(jobz, uplo, a, w, workspace.select(value_type()));\n    } // syev()\n\n    // Function without workarray as argument\n    template <typename A, typename W>\n    inline\n    int syev (char jobz, char uplo, A& a, W& w) {\n       return syev(jobz, uplo, a, w, optimal_workspace());\n    } // syev()\n\n    //\n    // With UPLO integrated in matrix type (this is not possible\n    // since a contains the eigenvectors afterwards and thus A cannot be symmetric)\n    //\n    template <typename A, typename W>\n    int syev (char jobz, A& a, W& w, optimal_workspace ) {\n       typedef typename A::value_type value_type ;\n\n       std::ptrdiff_t const n = traits::matrix_size1 (a);\n       char uplo = traits::matrix_uplo_tag( a ) ;\n/*#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK\n       typedef typename traits::matrix_traits<A>::matrix_structure matrix_structure ;\n       BOOST_STATIC_ASSERT( (boost::mpl::or_< boost::is_same< matrix_structure, traits::symmetric_t >\n                                            , boost::is_same< matrix_structure, traits::hermitian_t >\n                                            >::value)\n                          ) ;\n#endif*/\n\n       traits::detail::array<value_type> work( std::max<std::ptrdiff_t>(1,34*n) );\n       return detail::syev(jobz, uplo, a, w, work);\n    } // syev()\n\n\n    // Function that allocates work arrays\n    template <typename A, typename W>\n    int syev (char jobz, A& a, W& w, minimal_workspace ) {\n       typedef typename A::value_type value_type ;\n\n       std::ptrdiff_t const n = traits::matrix_size1 (a);\n       char uplo = traits::matrix_uplo_tag( a ) ;\n/*#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK\n       typedef typename traits::matrix_traits<A>::matrix_structure matrix_structure ;\n       BOOST_STATIC_ASSERT( (boost::mpl::or_< boost::is_same< matrix_structure, traits::symmetric_t >\n                                            , boost::is_same< matrix_structure, traits::hermitian_t >\n                                            >::value)\n                          ) ;\n#endif*/\n       traits::detail::array<value_type> work( std::max<std::ptrdiff_t>(1,3*n-1) );\n       return detail::syev(jobz, uplo, a, w, work);\n    } // syev()\n\n\n    // Function that allocates work arrays\n    template <typename A, typename W, typename Work>\n    int syev (char jobz, A& a, W& w, detail::workspace1<Work> workspace ) {\n       typedef typename A::value_type value_type ;\n       char uplo = traits::matrix_uplo_tag( a ) ;\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK\n       typedef typename traits::matrix_traits<A>::matrix_structure matrix_structure ;\n       BOOST_STATIC_ASSERT( (boost::mpl::or_< boost::is_same< matrix_structure, traits::symmetric_t >\n                                            , boost::is_same< matrix_structure, traits::hermitian_t >\n                                            >::value)\n                          ) ;\n#endif\n       return detail::syev(jobz, uplo, a, w, workspace.select(value_type()));\n    } // syev()\n\n    // Function without workarray as argument\n    template <typename A, typename W>\n    inline\n    int syev (char jobz, A& a, W& w) {\n       char uplo = traits::matrix_uplo_tag( a ) ;\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK\n       typedef typename traits::matrix_traits<A>::matrix_structure matrix_structure ;\n       BOOST_STATIC_ASSERT( (boost::mpl::or_< boost::is_same< matrix_structure, traits::symmetric_t >\n                                            , boost::is_same< matrix_structure, traits::hermitian_t >\n                                            >::value)\n                          ) ;\n#endif\n       return syev(jobz, uplo, a, w, optimal_workspace());\n    } // syev()\n\n  }\n\n\n\n}}}\n\n#endif\n", "meta": {"hexsha": "6a78ac51639ed8c94d0a52949d5c0f7573be01a7", "size": 8365, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/boost/numeric/bindings/lapack/syev.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/syev.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/syev.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": 37.1777777778, "max_line_length": 101, "alphanum_fraction": 0.5959354453, "num_tokens": 2074, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389817407016, "lm_q2_score": 0.6370308013713524, "lm_q1q2_score": 0.47531351347268397}}
{"text": "/** @file layouts.cc\n * @author David F. Gleich\n * @date 2008-09-25\n * @copyright Stanford University, 2008\n * Graph layout wrappers\n */\n\n/** History\n *  2008-09-25: Initial coding\n *  2008-09-27: Fixed progressive calls\n */\n\n#include \"include/matlab_bgl.h\"\n\n#include <yasmic/undir_simple_csr_matrix_as_graph.hpp>\n#include <yasmic/simple_csr_matrix_as_graph.hpp>\n#include <yasmic/iterator_utility.hpp>\n\n#include <boost/graph/kamada_kawai_spring_layout.hpp>\n#include <yasmic/boost_mod/fruchterman_reingold.hpp>\n#include <boost/graph/gursoy_atun_layout.hpp>\n#include <boost/graph/circle_layout.hpp>\n#include <boost/graph/random_layout.hpp>\n#include <boost/graph/simple_point.hpp>\n\n// for constant_value_property_map\n#include <yasmic/boost_mod/core_numbers.hpp>\n\n#include <vector>\n#include <iostream>\n#include <algorithm>\n\n#include <math.h>\n#ifndef M_PI\n#define M_PI 3.14159265358979323846\n#endif\n\n#include \"libmbgl_util.hpp\"\n\n/** Monitor tolerance for Kamada-Kawai layout with a maximum iteration limit\n * This class fixes problems with the boost layout_tolerance code.\n */\ntemplate <typename T = double>\nclass layout_and_iteration_tolerance\n{\npublic:\n  layout_and_iteration_tolerance(const T& tolerance=0.001, int maxiter = 100)\n  : maxiter(maxiter), iter(0), tolerance(tolerance), \n    first_energy((std::numeric_limits<T>::max)()),\n    last_energy((std::numeric_limits<T>::max)()),\n    first_local_energy((std::numeric_limits<T>::max)()),\n    last_local_energy((std::numeric_limits<T>::max)()) { }\n    \n  template<typename Graph>\n  bool \n  operator()(T delta_p, \n              typename boost::graph_traits<Graph>::vertex_descriptor p,\n              const Graph& g,\n              bool global)\n  {\n    bool done = false;\n    if (global) {\n      if (first_energy == (std::numeric_limits<T>::max)()) {\n        first_energy = delta_p;\n        last_energy = delta_p;\n        return delta_p < (std::numeric_limits<T>::epsilon)();\n      }\n      T diff = last_energy - delta_p;\n      if (diff < T(0)) diff = -diff;\n      done = (delta_p < (std::numeric_limits<T>::epsilon)() \n              || diff/first_energy < tolerance);\n      last_energy = delta_p;\n    } else {\n      if (first_local_energy == (std::numeric_limits<T>::max)()) {\n        first_local_energy = delta_p;\n        last_local_energy = delta_p;\n        return delta_p < (std::numeric_limits<T>::epsilon)();\n      }\n      T diff = last_local_energy - delta_p;\n      // uncommenting the following line causes the layout to cycle\n      // if (diff < T(0)) diff = -diff; \n      done = (delta_p < (std::numeric_limits<T>::epsilon)() \n              || diff/first_local_energy < tolerance);\n      last_local_energy = delta_p;\n    }\n    if (!done && global) {\n      iter++;\n      done = iter>maxiter;\n    }\n    return done;\n  }\n              \nprivate:\n  int maxiter, iter;   \n  T tolerance;\n  T first_energy;\n  T last_energy;\n  T first_local_energy;\n  T last_local_energy;\n};\n\n/** Compute a spring layout of a graph\n * @param nverts the number of vertices in the graph\n * @param ja the connectivity for each vertex\n * @param ia the row connectivity points into ja\n * @param weight the weight of each edge (can be NULL for unweighted graphs)\n * @param tol the stopping tolerance in terms of layout change\n * @param iterations the maximum number of global layout iterations\n * @param spring_constant the spring constant\n * @param progressive a binary value (0 or 1) if we should reuse the positions\n * @param positions an array of positions, length nverts*2\n * @param spring_strength a matrix of spring strengths between vertices,\n *           size nverts-by-nverts\n * @param distance a matrix of distances between vertices,\n *           size nverts-by-nverts\n */\nint kamada_kawai_spring_layout(\n    mbglIndex nverts, mbglIndex *ja, mbglIndex *ia, double *weight,\n    double tol, int iterations, double spring_constant, int progressive, \n    double edge_length,\n    double *positions,\n    double *spring_strength, double *distance)\n{\n  using namespace yasmic;\n  using namespace boost;\n  typedef undir_simple_csr_matrix<mbglIndex,double> crs_graph;\n  crs_graph g(nverts, nverts, ia[nverts], ia, ja, weight);\n  assert(nverts == 0 || positions);\n  if (tol < 0 || spring_strength == NULL || distance == NULL) { return -1; }\n  std::vector<simple_point<double> > position_vec(nverts);\n  std::vector<std::pair<double,double> > partial_deriv_vec(nverts);\n  if (!progressive) {\n    // initial random layout\n    circle_graph_layout(g,\n        make_iterator_property_map(position_vec.begin(),get(vertex_index,g)),\n        (double)nverts*edge_length/(2*M_PI));\n  } else {\n    // copy the layout from positions\n    mbglIndex n = num_vertices(g);\n    for (mbglIndex i = 0; i<n; i++) {\n      position_vec[i].x = positions[i+0*n];\n      position_vec[i].y = positions[i+1*n];\n    }\n  }\n  bool rval = false;\n  if (weight == NULL) {\n    rval = kamada_kawai_spring_layout(g,\n      make_iterator_property_map(position_vec.begin(),get(vertex_index,g)),\n      boost::detail::constant_value_property_map<double>(1.0), // edge_weight\n      boost::edge_length(edge_length), // edge_or_side_length\n      layout_and_iteration_tolerance<double>(tol,iterations), // done\n      spring_constant,\n      get(vertex_index,g),\n      row_matrix<double>(distance,nverts,nverts),\n      row_matrix<double>(spring_strength,nverts,nverts),\n      make_iterator_property_map(partial_deriv_vec.begin(),get(vertex_index,g)));\n  } else {\n    rval = kamada_kawai_spring_layout(g,\n      make_iterator_property_map(position_vec.begin(),get(vertex_index,g)),\n      get(edge_weight,g), // edge_weight\n      boost::edge_length(edge_length), // edge_or_side_length\n      layout_and_iteration_tolerance<double>(tol,iterations), // done\n      spring_constant,\n      get(vertex_index,g),\n      row_matrix<double>(distance,nverts,nverts),\n      row_matrix<double>(spring_strength,nverts,nverts),\n      make_iterator_property_map(partial_deriv_vec.begin(),get(vertex_index,g)));\n  }\n  if (rval) {\n    mbglIndex n = num_vertices(g);\n    for (mbglIndex i = 0; i<n; i++) {\n      positions[i+0*n] = position_vec[i].x;\n      positions[i+1*n] = position_vec[i].y;\n    }\n    return 0;\n  } else {\n    return -2;\n  }\n}\n\n/** Compute a force directed layout of a graph\n * @param nverts the number of vertices in the graph\n * @param ja the connectivity for each vertex\n * @param ia the row connectivity points into ja\n * @param iterations the number of iterations to run\n * @param initial_temp the initial temperature of the system\n * @param grid_force_pairs a binary value (0 or 1) if the alg should use\n *   a grid to compute the force between pairs\n * @param width the total width of the layout\n * @param height the total height of the layout\n * @param progressive a binary value (0 or 1) if we should start from\n *   the positions in the positions value\n * @param positions an array of positions, length nverts*2\n */\nint fruchterman_reingold_force_directed_layout(\n    mbglIndex nverts, mbglIndex *ja, mbglIndex *ia,\n    int iterations, double initial_temp, int grid_force_pairs,\n    double width, double height, int progressive,\n    double *positions)\n{\n  using namespace yasmic;\n  using namespace boost;\n  typedef simple_csr_matrix<mbglIndex,double> crs_graph;\n  crs_graph g(nverts, nverts, ia[nverts], ia, ja, NULL);\n  assert(nverts == 0 || positions);\n  std::vector<simple_point<double> > position_vec(nverts);\n  if (width <= 0 || height <= 0 || iterations <= 0) { return -1; }\n  if (!progressive) {\n    // initial random layout\n    minstd_rand gen;\n    random_graph_layout(g,\n        make_iterator_property_map(position_vec.begin(),get(vertex_index,g)),\n        -width/2.0, width/2.0, -height/2.0, height/2.0, gen);\n  } else {\n    // copy the layout from positions\n    mbglIndex n = num_vertices(g);\n    for (mbglIndex i = 0; i<n; i++) {\n      position_vec[i].x = positions[i+0*n];\n      position_vec[i].y = positions[i+1*n];\n    }\n  }\n  if (grid_force_pairs) {\n    fruchterman_reingold_force_directed_layout(g,\n        make_iterator_property_map(position_vec.begin(),get(vertex_index,g)),\n        width, height,\n        cooling(linear_cooling<double>(iterations, initial_temp)));\n  } else {\n    fruchterman_reingold_force_directed_layout(g,\n        make_iterator_property_map(position_vec.begin(),get(vertex_index,g)),\n        width, height,\n        cooling(linear_cooling<double>(iterations, initial_temp)).\n          force_pairs(all_force_pairs()));\n  }\n  // copy the positions over\n  mbglIndex n = num_vertices(g);\n  for (mbglIndex i = 0; i<n; i++) {\n    positions[i+0*n] = position_vec[i].x;\n    positions[i+1*n] = position_vec[i].y;\n  }\n  return 0;\n}\n\n\n/** A helper function to allocate the points and convert back to positions\n */\ntemplate <typename Graph, typename Topology>\nint gursoy_atun_layout_helper(const Graph& g, bool weighted,\n    Topology space, int space_dim, int nsteps,\n    double diameter_i, double diameter_f, double lc_i, double lc_f,\n    double *positions)\n{\n  using namespace boost;\n  std::vector<typename Topology::point_type> position_map(num_vertices(g));\n  if (weighted) {\n    gursoy_atun_layout(g, space,\n      make_iterator_property_map(position_map.begin(),get(vertex_index,g)),\n      nsteps, diameter_i, diameter_f, lc_i, lc_f, get(vertex_index,g),\n      get(edge_weight,g));\n  } else {\n    gursoy_atun_layout(g, space,\n          make_iterator_property_map(position_map.begin(),get(vertex_index,g)),\n          nsteps, diameter_i, diameter_f, lc_i, lc_f, get(vertex_index,g));\n  }\n  // copy the positions over\n  mbglIndex n = num_vertices(g);\n  mbglIndex numdim = (mbglIndex)space_dim;\n  for (mbglIndex i = 0; i<n; i++) {\n    for (mbglIndex d = 0; d<numdim; d++) {\n      positions[i+d*n] = position_map[i][d];\n    }\n  }\n  return 0;\n}\n\nconst int gursoy_atun_invalid_dim = -10;\nconst int gursoy_atun_dim_too_large = -11;\nconst int gursoy_atun_max_dim = 10;\n\n/** Compute a topologically uniform layout\n * @param nverts the number of vertices in the graph\n * @param ja the connectivity for each vertex\n * @param ia the row connectivity points into ja\n * @param weight the weight of each edge (can be NULL for unweighted graphs)\n * @param topology the topology type\n * @param topology_dim the topology dimension\n * @param iterations the number of iterations\n * @param diameter_i the initial diameter for modifications\n * @param diameter_f the final diameter for modifications\n * @param learning_constant_i the initial learning constant\n * @param learning_constant_f the final learning constant\n * @param positions an array of positions, length nverts*topology_dim\n */\nint gursoy_atun_layout(\n    mbglIndex nverts, mbglIndex *ja, mbglIndex *ia, double *weight,\n    gursoy_atun_layout_topology_t topology, int topology_dim,\n    int iterations, double diameter_i, double diameter_f,\n    double learning_constant_i, double learning_constant_f,\n    double *positions)\n{\n  using namespace yasmic;\n  using namespace boost;\n\n  typedef simple_csr_matrix<mbglIndex,double> crs_graph;\n  crs_graph g(nverts, nverts, ia[nverts], ia, ja, weight);\n  assert(nverts == 0 || positions);\n\n  switch (topology) {\n  case BALL_LAYOUT_TOPOLOGY:\n    if (topology_dim<2) { return gursoy_atun_invalid_dim; }\n    if (topology_dim>gursoy_atun_max_dim) { return gursoy_atun_dim_too_large; }\n    switch (topology_dim) {\n    case 2:\n      gursoy_atun_layout_helper(g, weight!=NULL,\n          ball_topology<2>(),topology_dim,iterations,diameter_i,diameter_f,\n          learning_constant_i, learning_constant_f, positions);\n      break;\n    case 3:\n      gursoy_atun_layout_helper(g, weight!=NULL,\n          ball_topology<3>(),topology_dim,iterations,diameter_i,diameter_f,\n          learning_constant_i, learning_constant_f, positions);\n      break;\n    case 4:\n      gursoy_atun_layout_helper(g, weight!=NULL,\n          ball_topology<4>(),topology_dim,iterations,diameter_i,diameter_f,\n          learning_constant_i, learning_constant_f, positions);\n      break;\n    case 5:\n      gursoy_atun_layout_helper(g, weight!=NULL,\n          ball_topology<5>(),topology_dim,iterations,diameter_i,diameter_f,\n          learning_constant_i, learning_constant_f, positions);\n      break;\n    case 6:\n      gursoy_atun_layout_helper(g, weight!=NULL,\n          ball_topology<6>(),topology_dim,iterations,diameter_i,diameter_f,\n          learning_constant_i, learning_constant_f, positions);\n      break;\n    case 7:\n      gursoy_atun_layout_helper(g, weight!=NULL,\n          ball_topology<7>(),topology_dim,iterations,diameter_i,diameter_f,\n          learning_constant_i, learning_constant_f, positions);\n      break;\n    case 8:\n      gursoy_atun_layout_helper(g, weight!=NULL,\n          ball_topology<8>(),topology_dim,iterations,diameter_i,diameter_f,\n          learning_constant_i, learning_constant_f, positions);\n      break;\n    case 9:\n      gursoy_atun_layout_helper(g, weight!=NULL,\n          ball_topology<9>(),topology_dim,iterations,diameter_i,diameter_f,\n          learning_constant_i, learning_constant_f, positions);\n      break;\n    case 10:\n      gursoy_atun_layout_helper(g, weight!=NULL,\n          ball_topology<10>(),topology_dim,iterations,diameter_i,diameter_f,\n          learning_constant_i, learning_constant_f, positions);\n      break;\n    }\n    break;\n  case CUBE_LAYOUT_TOPOLOGY:\n    if (topology_dim<2) { return gursoy_atun_invalid_dim; }\n    if (topology_dim>gursoy_atun_max_dim) { return gursoy_atun_dim_too_large; }\n    switch (topology_dim) {\n    case 2:\n      gursoy_atun_layout_helper(g, weight!=NULL,\n          hypercube_topology<2>(),topology_dim,iterations,diameter_i,diameter_f,\n          learning_constant_i, learning_constant_f, positions);\n      break;\n    case 3:\n      gursoy_atun_layout_helper(g, weight!=NULL,\n          hypercube_topology<3>(),topology_dim,iterations,diameter_i,diameter_f,\n          learning_constant_i, learning_constant_f, positions);\n      break;\n    case 4:\n      gursoy_atun_layout_helper(g, weight!=NULL,\n          hypercube_topology<4>(),topology_dim,iterations,diameter_i,diameter_f,\n          learning_constant_i, learning_constant_f, positions);\n      break;\n    case 5:\n      gursoy_atun_layout_helper(g, weight!=NULL,\n          hypercube_topology<5>(),topology_dim,iterations,diameter_i,diameter_f,\n          learning_constant_i, learning_constant_f, positions);\n      break;\n    case 6:\n      gursoy_atun_layout_helper(g, weight!=NULL,\n          hypercube_topology<6>(),topology_dim,iterations,diameter_i,diameter_f,\n          learning_constant_i, learning_constant_f, positions);\n      break;\n    case 7:\n      gursoy_atun_layout_helper(g, weight!=NULL,\n          hypercube_topology<7>(),topology_dim,iterations,diameter_i,diameter_f,\n          learning_constant_i, learning_constant_f, positions);\n      break;\n    case 8:\n      gursoy_atun_layout_helper(g, weight!=NULL,\n          hypercube_topology<8>(),topology_dim,iterations,diameter_i,diameter_f,\n          learning_constant_i, learning_constant_f, positions);\n      break;\n    case 9:\n      gursoy_atun_layout_helper(g, weight!=NULL,\n          hypercube_topology<9>(),topology_dim,iterations,diameter_i,diameter_f,\n          learning_constant_i, learning_constant_f, positions);\n      break;\n    case 10:\n      gursoy_atun_layout_helper(g, weight!=NULL,\n          hypercube_topology<10>(),topology_dim,iterations,diameter_i,diameter_f,\n          learning_constant_i, learning_constant_f, positions);\n      break;\n    }\n    break;\n  case HEART_LAYOUT_TOPOLOGY:\n    if (topology_dim!=2) { return gursoy_atun_invalid_dim; }\n    gursoy_atun_layout_helper(g, weight!=NULL,\n      heart_topology<>(),topology_dim,iterations,diameter_i,diameter_f,\n      learning_constant_i, learning_constant_f, positions);\n    break;\n  default:\n    return -1;\n  }\n  return 0;\n}\n", "meta": {"hexsha": "1dfa4f6771b0c3f1dd337716892a68c8637676ef", "size": 15758, "ext": "cc", "lang": "C++", "max_stars_repo_path": "2A/Graphes/TPs/matlab_bgl/libmbgl/layouts.cc", "max_stars_repo_name": "anajmedd/ENSEEIHT-Projects", "max_stars_repo_head_hexsha": "e4077fe8882ae35be52e53f29a3a988a0d6f83f0", "max_stars_repo_licenses": ["Apache-2.0"], "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": "2A/Graphes/TPs/matlab_bgl/libmbgl/layouts.cc", "max_issues_repo_name": "anajmedd/ENSEEIHT-Projects", "max_issues_repo_head_hexsha": "e4077fe8882ae35be52e53f29a3a988a0d6f83f0", "max_issues_repo_licenses": ["Apache-2.0"], "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": "2A/Graphes/TPs/matlab_bgl/libmbgl/layouts.cc", "max_forks_repo_name": "anajmedd/ENSEEIHT-Projects", "max_forks_repo_head_hexsha": "e4077fe8882ae35be52e53f29a3a988a0d6f83f0", "max_forks_repo_licenses": ["Apache-2.0"], "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": 37.4299287411, "max_line_length": 81, "alphanum_fraction": 0.7004061429, "num_tokens": 4020, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.47531350523993054}}
{"text": "//                Copyright Robert J McCabe 2015.\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//     Please report any bugs, typos, or suggestions to\n//         https://github.com/rjmccabe3701/stat_log/issues\n\n#include \"common.h\"\n#include \"hw_intf_stat_tags.h\"\n#include <stat_log/stat_log.h>\n#include <stat_log/backends/shared_mem_backend.h>\n#include <stat_log/loggers/shared_memory_logger.h>\n#include <stat_log/util/compile_proxy.h>\n\n//Statistics\n#include <stat_log/stats/stats_common.h>\n#include <stat_log/stats/simple_counter.h>\n#include <stat_log/stats/simple_status.h>\n#include <stat_log/stats/stat_array.h>\n#if 1\n#include <stat_log/stats/accumulator.h>\n#include <stat_log/stats/accumulator_types/count.h>\n#include <stat_log/stats/accumulator_types/min.h>\n#include <stat_log/stats/accumulator_types/max.h>\n#include <stat_log/stats/accumulator_types/mean.h>\n#include <stat_log/stats/accumulator_types/histogram.h>\n\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics.hpp>\n#endif\n\n#include <type_traits>\n\n#define STAT_LOG_MAC_SIS_SHM_NAME \"STAT_LOG_MAC_SIS\"\n#define STAT_LOG_HW_INTF_SHM_NAME \"STAT_LOG_HW_INTF\"\n#define STAT_LOG_TEXT_LOGGER_NAME \"SHM_LOGGER_TEXT\"\n#define STAT_LOG_TEXT_LOGGER_SIZE_BYTES 4194304\n#define STAT_LOG_HEXDUMP_LOGGER_NAME \"SHM_LOGGER_HEXDUMP\"\n#define STAT_LOG_HEXDUMP_LOGGER_SIZE_BYTES 4194304\n\n\nusing MacSisOpStat = stat_log::LogStatOperational<MAC_SIS_STATS, MAC_SIS_LOG>;\nusing MacSisControlStat = stat_log::LogStatControl<MAC_SIS_STATS, MAC_SIS_LOG>;\n\nusing HwIntfOpStat = stat_log::LogStatOperational<hw_intf::HW_INTF_STATS, hw_intf::HW_INTF_LOG>;\nusing HwIntfControlStat = stat_log::LogStatControl<hw_intf::HW_INTF_STATS, hw_intf::HW_INTF_LOG>;\n\nusing LogGen = stat_log::shared_mem_logger_generator;\nusing LogRet = stat_log::shared_mem_logger_retriever;\n\n/*********************************\n * Statistic definitions\n *********************************/\nnamespace stat_log\n{\n   namespace ba = boost::accumulators;\n   //Default stat\n   template <typename Tag, class Enable>\n   struct stat_tag_to_type\n   {\n      using type = SimpleCounter<int>;\n   };\n\n   //Mac: IP sent: Histogram of IP pkt sizes sizes\n   template <>\n   struct stat_tag_to_type<mac::IP_PKT_SENT_SIZE_TAG>\n   {\n      using type = Accumulator<\n         stat_log::HistogramCount<\n            int,\n            300, //start bin\n            1500, //stop bin\n            10 //num_bits\n         >\n      >;\n   };\n\n   //Mac: IP rcvd: summary statistics of IP pkt sizes:\n   //  count, min, max, mean\n   template <>\n   struct stat_tag_to_type<mac::IP_PKT_RCVD_SIZE_TAG>\n   {\n      using type = Accumulator<\n         ba::accumulator_set<\n               double\n               , ba::stats<\n                  ba::tag::count\n                  , ba::tag::min\n                  , ba::tag::max\n                  , ba::tag::mean\n               >\n            >\n         >;\n   };\n\n   //Mac: tx power level: array of power levels (ints)\n   template <>\n   struct stat_tag_to_type<mac::TX_POWER_LEVEL_TAG>\n   {\n      using type = StatArray<sis::max_nbrs, SimpleStatus<int>>;\n   };\n\n   //Mac: rx power level: array of received powers in dB (doubles)\n   template <>\n   struct stat_tag_to_type<mac::RX_POWER_LEVEL_TAG>\n   {\n      using type = StatArray<sis::max_nbrs, SimpleStatus<double>>;\n   };\n\n   //Sis: prop delay: per-nbr density histogram of delays\n   template <>\n   struct stat_tag_to_type<sis::PROP_DELAY_TAG>\n   {\n      using type = StatArray<sis::max_nbrs,\n               Accumulator<\n                  stat_log::HistogramDensity<\n                  // stat_log::HistogramCount<\n                     double,\n                     50, //start bin\n                     400, //stop bin\n                     7 //num_bits\n                  >\n               >\n            >;\n   };\n\n   //Sis: channel quality: per-nbr, per-frequency channel quality enumeration\n   template <>\n   struct stat_tag_to_type<sis::CHANNEL_QUALITY_TAG>\n   {\n      using type = StatArray<sis::max_nbrs,\n                                StatArray<sis::num_frequencies,\n                                    SimpleStatus<int>\n                                 >\n                            >;\n   };\n\n   //Sis: frame rx status: array of counters (per nbr and rx status)\n   template <>\n   struct stat_tag_to_type<sis::FRAME_RX_STATUS_TAG>\n   {\n      using type = StatArray<sis::max_nbrs,\n                                StatArray<sis::num_rx_frame_status,\n                                    SimpleCounter<int>\n                                 >\n                            >;\n   };\n\n   //Sis: link status: per-nbr link status indicator (int)\n   template <>\n   struct stat_tag_to_type<sis::LINK_STATUS_TAG>\n   {\n      using type = StatArray<sis::max_nbrs, SimpleStatus<int>>;\n   };\n\n   //HwIntf: fault: array of counters (per each fault type)\n   template <>\n   struct stat_tag_to_type<hw_intf::FPGA_FAULT_TAG>\n   {\n      using type = StatArray<hw_intf::num_fpga_faults, int>;\n   };\n\n   //HwIntf: interrupt: array of counters (per each interrupt)\n   template <>\n   struct stat_tag_to_type<hw_intf::INTERRUPT_TAG>\n   {\n      using type = StatArray<hw_intf::num_fpga_interrupts, int>;\n   };\n}\n\n/*********************************\n * common logger and initializer definitions\n *********************************/\nnamespace\n{\n   using namespace stat_log;\n   template <typename Tag>\n   inline LogGenProxy logCommon(LogLevel ll, int log_idx)\n   {\n      constexpr auto is_mac_sis_tag = TagBelongsToLog<Tag, MacSisOpStat>::value;\n      constexpr auto is_hw_intf_tag = TagBelongsToLog<Tag, HwIntfOpStat>::value;\n      static_assert(is_mac_sis_tag || is_hw_intf_tag, \"Bad tag in logCommon!\\n\");\n      using TheOpStat = std::conditional_t<\n         is_mac_sis_tag, MacSisOpStat, HwIntfOpStat>;\n      TheOpStat& stat = stat_log::getStatLogSingleton<TheOpStat>();\n      return stat.template getLog<Tag>(ll, log_idx);\n   }\n\n   template <typename MacSisStatType, typename HwIntfStatType, typename LogType>\n   void initializeCommon()\n   {\n      auto& macSisStat = stat_log::getStatLogSingleton<MacSisStatType>();\n      auto& hwIntfStat = stat_log::getStatLogSingleton<HwIntfStatType>();\n\n      macSisStat.init(STAT_LOG_MAC_SIS_SHM_NAME);\n      hwIntfStat.init(STAT_LOG_HW_INTF_SHM_NAME);\n      auto text_logger = std::make_shared<LogType>(\n            STAT_LOG_TEXT_LOGGER_NAME,\n            STAT_LOG_TEXT_LOGGER_SIZE_BYTES);\n\n      macSisStat.addLogger(text_logger);\n      hwIntfStat.addLogger(text_logger);\n\n      auto hexdump_logger = std::make_shared<LogType>(\n            STAT_LOG_HEXDUMP_LOGGER_NAME,\n            STAT_LOG_HEXDUMP_LOGGER_SIZE_BYTES);\n\n      macSisStat.addLogger(hexdump_logger);\n      hwIntfStat.addLogger(hexdump_logger);\n   }\n}\n\n/*********************************\n * definitions of the \"compile_proxy\" API's methods\n *********************************/\nnamespace stat_log\n{\n   template <typename Tag>\n   LogGenProxy logger(LogLevel ll)\n   {\n      return logCommon<Tag>(ll, 0);\n   }\n\n   template <typename Tag>\n   LogGenProxy hexDumper(LogLevel ll)\n   {\n      return logCommon<Tag>(ll, 1);\n   }\n\n   template <typename Tag, typename ...Args>\n   void writeStat(Args... args)\n   {\n      constexpr auto is_mac_sis_tag = TagBelongsToStat<Tag, MacSisOpStat>::value;\n      constexpr auto is_hw_intf_tag = TagBelongsToStat<Tag, HwIntfOpStat>::value;\n      static_assert(is_mac_sis_tag || is_hw_intf_tag, \"Bad tag in writeStat!\\n\");\n      using TheOpStat = std::conditional_t<\n         is_mac_sis_tag, MacSisOpStat, HwIntfOpStat>;\n      stat_log::getStatLogSingleton<TheOpStat>().template writeStat<Tag>(args...);\n   }\n\n   //EXPLICIT TEMPLATE INSTANTIATIONS\n   //MAC\n   template void writeStat<mac::IP_PKTS_SENT_TAG>(int val);\n   template void writeStat<mac::IP_PKTS_RCVD_TAG>(int val);\n   template void writeStat<mac::IP_PKT_SENT_SIZE_TAG>(int val);\n   template void writeStat<mac::IP_PKT_RCVD_SIZE_TAG>(int val);\n   template void writeStat<mac::TX_POWER_LEVEL_TAG>(int idx, int val);\n   template void writeStat<mac::RX_POWER_LEVEL_TAG>(int idx, double val);\n\n   //SIS\n   template void writeStat<sis::PROP_DELAY_TAG>(int nbr_idx, double delay_us);\n   template void writeStat<sis::CHANNEL_QUALITY_TAG>(int nbr_idx, int freq_idx, double qual);\n   template void writeStat<sis::FRAME_RX_STATUS_TAG>(int nbr_idx, int rx_status_enum, int val);\n   template void writeStat<sis::LINK_STATUS_TAG>(int nbr_idx, int val);\n\n   //HW_INTF\n   template void writeStat<hw_intf::FPGA_FAULT_TAG>(int fault_idx, int val);\n   template void writeStat<hw_intf::BYTES_SENT_TAG>(int val);\n   template void writeStat<hw_intf::BYTES_RCVD_TAG>(int val);\n   template void writeStat<hw_intf::INTERRUPT_TAG>(int interrupt_idx, int val);\n\n   template LogGenProxy logger<hw_intf::HW_INTF_LOG>(LogLevel ll);\n   template LogGenProxy hexDumper<hw_intf::HW_INTF_LOG>(LogLevel ll);\n   template LogGenProxy logger<mac::MAC_LOG>(LogLevel ll);\n   template LogGenProxy hexDumper<mac::MAC_LOG>(LogLevel ll);\n   template LogGenProxy logger<sis::SIS_LOG>(LogLevel ll);\n   template LogGenProxy hexDumper<sis::SIS_LOG>(LogLevel ll);\n\n//TODO: this will be super annoying for the user to have to define the\n// stat hierarchy AND explicitly instantiate each of them ...\n// Think  of a way to automate this.\n\n}\n\ntemplate <>\nvoid initializeStatistics<false == IsOperational>()\n{\n    initializeCommon<MacSisControlStat, HwIntfControlStat, LogRet>();\n}\n\ntemplate <>\nvoid initializeStatistics<true == IsOperational>()\n{\n   initializeCommon<MacSisOpStat, HwIntfOpStat, LogGen>();\n}\n\nvoid handleCommandLineArgs(int argc, char** argv)\n{\n   auto& macSisControlStat = getStatLogSingleton<MacSisControlStat>();\n   auto& hwIntfControlStat = getStatLogSingleton<HwIntfControlStat>();\n\n   //Assign a few enumeration and dimension names to make stat-viewing pretty.\n   // TODO: design this better\n#if 0\n   hwIntfControlStat.assignEnumerationNames<\n      hw_intf::MISC_FPGA_FAULT_TAG>({\"OVER_TEMP\", \"INVALID_COMMAND\", \"UNKNOWN_FAULT\"});\n\n   macSisControlStat.assignEnumerationNames<\n      sis::MAC_PKTS_DOWN_TAG>({\"L\", \"M\", \"H\"});\n\n   macSisControlStat.assignDimensionNames<\n      sis::MAC_PKTS_DOWN_TAG>({\"Priority\", \"Traffic Type\"});\n#endif\n\n   macSisControlStat.parseUserCommands(argc, argv);\n   hwIntfControlStat.parseUserCommands(argc, argv);\n   macSisControlStat.showOutput();\n}\n\n", "meta": {"hexsha": "dc8a31dd7a11aa6d1adce45ccf08b646c3b28545", "size": 10413, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_full/common.cpp", "max_stars_repo_name": "vladon/stat_log", "max_stars_repo_head_hexsha": "39cd364d6010dd6fd1d734d474961becccc04a09", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-08-08T18:12:59.000Z", "max_stars_repo_stars_event_max_datetime": "2016-08-08T18:12:59.000Z", "max_issues_repo_path": "test/test_full/common.cpp", "max_issues_repo_name": "vladon/stat_log", "max_issues_repo_head_hexsha": "39cd364d6010dd6fd1d734d474961becccc04a09", "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/test_full/common.cpp", "max_forks_repo_name": "vladon/stat_log", "max_forks_repo_head_hexsha": "39cd364d6010dd6fd1d734d474961becccc04a09", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-07-05T07:50:08.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-13T08:59:29.000Z", "avg_line_length": 33.4823151125, "max_line_length": 97, "alphanum_fraction": 0.6727167963, "num_tokens": 2594, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389817407016, "lm_q2_score": 0.6370307875894138, "lm_q1q2_score": 0.4753135031894424}}
{"text": "#ifndef TEST_UNIT_TORSTEN_COUPLED_ONECPT_MODEL_TEST_FIXTURE\n#define TEST_UNIT_TORSTEN_COUPLED_ONECPT_MODEL_TEST_FIXTURE\n\n#include <stan/math/rev/core/recover_memory.hpp>\n#include <gtest/gtest.h>\n#include <boost/numeric/odeint.hpp>\n#include <stan/math/torsten/test/unit/test_fixture_model.hpp>\n#include <stan/math/torsten/pmx_onecpt_model.hpp>\n#include <stan/math/torsten/pmx_solve_onecpt_rk45.hpp>\n#include <stan/math/torsten/pmx_solve_onecpt_bdf.hpp>\n#include <stan/math/torsten/pmx_ode_model.hpp>\n#include <iostream>\n#include <sstream>\n#include <vector>\n#include <string>\n\nstruct CoupledOneCptODE {\n  /**\n   * Coupled model functor\n   */\n  template <typename T0, typename T1, typename T2, typename T3>\n  inline\n  Eigen::Matrix<typename stan::return_type_t<T0, T1, T2, T3>, -1, 1>\n  operator()(const T0& t,\n             const Eigen::Matrix<T1, -1, 1>& x,\n             const Eigen::Matrix<T2, -1, 1>& x_pk,\n             const std::vector<T3>& theta,\n             const std::vector<double>& x_r,\n             const std::vector<int>& x_i,\n             std::ostream* pstream_) const {\n    typedef typename boost::math::tools::promote_args<T0, T1, T2, T3>::type\n      scalar;\n\n    scalar\n      VC = theta[1],\n      Mtt = theta[3],\n      circ0 = theta[4],\n      alpha = theta[5],\n      gamma = theta[6],\n      ktr = 4 / Mtt,\n      prol = x[0] + circ0,\n      transit = x[1] + circ0,\n      circ = x[2] + circ0,\n      conc = x_pk[1] / VC,\n      Edrug = alpha * conc;\n\n    Eigen::Matrix<scalar, -1, 1> dxdt(3);\n    dxdt << ktr * prol * ((1 - Edrug) * pow(circ0 / circ, gamma) - 1),\n      ktr * (prol - transit),\n      ktr * (transit - circ);\n\n    return dxdt;\n  }\n\n  /**\n   * full ODE model functor\n   */\n  template <typename T0, typename T1, typename T2>\n  inline\n  Eigen::Matrix<typename stan::return_type_t<T0, T1, T2>, -1, 1>\n  operator()(const T0& t,\n             const Eigen::Matrix<T1, -1, 1>& x,\n             std::ostream* pstream_,\n             const std::vector<T2>& theta,\n             const std::vector<double>& x_r,\n             const std::vector<int>& x_i) const {\n    using scalar = typename stan::return_type_t<T0, T1, T2>;\n    \n    T2 CL = theta[0];\n    T2 VC = theta[1];\n    T2 ka = theta[2];\n    T2 Mtt = theta[3];\n    T2 circ0 = theta[4];\n    T2 alpha = theta[5];\n    T2 gamma = theta[6];\n    T2 ktr = 4.0 / Mtt;\n    scalar prol = x[2] + circ0;\n    scalar transit = x[3] + circ0;\n    scalar circ = x[4] + circ0;\n    scalar Edrug = alpha * x[1] / VC;\n\n    Eigen::Matrix<scalar, -1, 1>  dxdt(5);\n    dxdt << - ka * x[0],\n      ka * x[0] - CL / VC * x[1],\n      ktr * prol * ((1 - Edrug) * pow(circ0 / circ, gamma) - 1),\n      ktr * (prol - transit),\n      ktr * (transit - circ);\n    \n    return dxdt;\n  }\n};\n\ntemplate<typename T>\nstruct test_coupled_onecpt : public TorstenPMXTest<test_coupled_onecpt<T> > {\n  const size_t nOde;\n  test_coupled_onecpt() : nOde(5) {\n    this -> ncmt = nOde;           // # of PD compartments\n    this -> reset_events(10);\n    this -> theta.resize(1);\n    this -> theta[0] = {10, 35, 2.0, 125, 5, 3e-4, 0.17};\n    this -> biovar.resize(1);\n    this -> biovar[0] = {1, 1, 1, 1, 1};\n    this -> tlag.resize(1);\n    this -> tlag[0] = {0, 0, 0, 0, 0};\n\n    for(int i = 0; i < this -> nt; i++) {\n      this -> time[i] = i * 0.25; \n    }\n    this -> time[this -> nt - 1] = 4.0;\n\n    this -> amt[0] = 10000.0;\n    this -> cmt[0] = 1;\n    this -> evid[0] = 1;\n  }\n};\n\n#endif\n", "meta": {"hexsha": "e2250d88206582e010716def33531d864188ce84", "size": 3408, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/unit/test_fixture_coupled_onecpt.hpp", "max_stars_repo_name": "metrumresearchgroup/torsten_math", "max_stars_repo_head_hexsha": "318cee4199342bd36d5f2b1241c6760acfcf58b7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/unit/test_fixture_coupled_onecpt.hpp", "max_issues_repo_name": "metrumresearchgroup/torsten_math", "max_issues_repo_head_hexsha": "318cee4199342bd36d5f2b1241c6760acfcf58b7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-04-27T23:53:22.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-27T23:57:43.000Z", "max_forks_repo_path": "test/unit/test_fixture_coupled_onecpt.hpp", "max_forks_repo_name": "metrumresearchgroup/torsten_math", "max_forks_repo_head_hexsha": "318cee4199342bd36d5f2b1241c6760acfcf58b7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8813559322, "max_line_length": 77, "alphanum_fraction": 0.5713028169, "num_tokens": 1159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834648, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4752585750109511}}
{"text": "#ifndef STAN_MATH_PRIM_MAT_PROB_DIRICHLET_RNG_HPP\n#define STAN_MATH_PRIM_MAT_PROB_DIRICHLET_RNG_HPP\n\n#include <stan/math/prim/meta.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/random/gamma_distribution.hpp>\n#include <boost/random/uniform_real_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <stan/math/prim/mat/fun/log_sum_exp.hpp>\n#include <cmath>\n\nnamespace stan {\nnamespace math {\n\n/**\n * Return a draw from a Dirichlet distribution with specified\n * parameters and pseudo-random number generator.\n *\n * For prior counts greater than zero, the usual algorithm that\n * draws gamma variates and normalizes is used.\n *\n * For prior counts less than zero (i.e., parameters with value\n * less than one), a log-scale version of the following algorithm\n * is used to deal with underflow:\n *\n * <blockquote>\n * G. Marsaglia and W. Tsang. A simple method for generating gamma\n * variables. ACM Transactions on Mathematical Software.\n * 26(3):363--372, 2000.\n * </blockquote>\n *\n * @tparam RNG Type of pseudo-random number generator.\n * @param alpha Prior count (plus 1) parameter for Dirichlet.\n * @param rng Pseudo-random number generator.\n */\ntemplate <class RNG>\ninline Eigen::VectorXd dirichlet_rng(\n    const Eigen::Matrix<double, Eigen::Dynamic, 1>& alpha, RNG& rng) {\n  using Eigen::VectorXd;\n  using boost::gamma_distribution;\n  using boost::random::uniform_real_distribution;\n  using boost::variate_generator;\n  using std::exp;\n  using std::log;\n\n  // separate algorithm if any parameter is less than 1\n  if (alpha.minCoeff() < 1) {\n    variate_generator<RNG&, uniform_real_distribution<> > uniform_rng(\n        rng, uniform_real_distribution<>(0.0, 1.0));\n    VectorXd log_y(alpha.size());\n    for (int i = 0; i < alpha.size(); ++i) {\n      variate_generator<RNG&, gamma_distribution<> > gamma_rng(\n          rng, gamma_distribution<>(alpha(i) + 1, 1));\n      double log_u = log(uniform_rng());\n      log_y(i) = log(gamma_rng()) + log_u / alpha(i);\n    }\n    double log_sum_y = log_sum_exp(log_y);\n    VectorXd theta(alpha.size());\n    for (int i = 0; i < alpha.size(); ++i) {\n      theta(i) = exp(log_y(i) - log_sum_y);\n    }\n    return theta;\n  }\n\n  // standard normalized gamma algorithm\n  Eigen::VectorXd y(alpha.rows());\n  for (int i = 0; i < alpha.rows(); i++) {\n    variate_generator<RNG&, gamma_distribution<> > gamma_rng(\n        rng, gamma_distribution<>(alpha(i, 0), 1e-7));\n    y(i) = gamma_rng();\n  }\n  return y / y.sum();\n}\n\n}  // namespace math\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "10462ba20ae6d25f7d83a9551df23047dd216774", "size": 2543, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/prim/mat/prob/dirichlet_rng.hpp", "max_stars_repo_name": "PhilClemson/math", "max_stars_repo_head_hexsha": "fffe604a7ead4525be2551eb81578c5f351e5c87", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "stan/math/prim/mat/prob/dirichlet_rng.hpp", "max_issues_repo_name": "PhilClemson/math", "max_issues_repo_head_hexsha": "fffe604a7ead4525be2551eb81578c5f351e5c87", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stan/math/prim/mat/prob/dirichlet_rng.hpp", "max_forks_repo_name": "PhilClemson/math", "max_forks_repo_head_hexsha": "fffe604a7ead4525be2551eb81578c5f351e5c87", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.6025641026, "max_line_length": 70, "alphanum_fraction": 0.6964215494, "num_tokens": 657, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4752585698432706}}
{"text": "#if defined(WITH_CPLEX) || defined(WITH_GUROBI)\n\n#include <boost/python.hpp>\n#include <boost/python/module.hpp>\n#include <opengm/python/opengmpython.hxx>\n#include <opengm/python/converter.hxx>\n#include <opengm/python/numpyview.hxx>\n\n#include <opengm/inference/icm.hxx>\n#include <opengm/learning/maximum_likelihood_learning.hxx>\n\n#define DefaultErrorFn DefaultErrorFn_TrwsExternal_ML\n#include \"helper.hxx\"\n\nnamespace bp = boost::python;\nnamespace op = opengm::python;\nnamespace ol = opengm::learning;\n\nnamespace opengm{\n\n\n    template<class PARAM>\n    PARAM * pyMaxLikelihoodParamConstructor(\n\tsize_t maximumNumberOfIterations=100,\n\tdouble gradientStepSize=0.1,\n\tdouble weightStoppingCriteria=0.00000001,\n\tdouble gradientStoppingCriteria=0.00000001,\n\tbool infoFlag=true,\n\tbool infoEveryStep=false,\n\tdouble weightRegularizer = 1.0,\n\tsize_t beliefPropagationMaximumNumberOfIterations = 20,\n\tdouble beliefPropagationConvergenceBound = 0.0001,\n\tdouble beliefPropagationDamping = 0.5,\n\tdouble beliefPropagationTemperature = 0.3,\n\topengm::Tribool beliefPropagationIsAcyclic=opengm::Tribool(opengm::Tribool::Maybe)\n    ){\n        PARAM * p  = new PARAM();\n\tp->maximumNumberOfIterations_ = maximumNumberOfIterations;\n\tp->gradientStepSize_ = gradientStepSize;\n\tp->weightStoppingCriteria_ = weightStoppingCriteria;\n\tp->gradientStoppingCriteria_ = gradientStoppingCriteria;\n\tp->infoFlag_ = infoFlag;\n\tp->infoEveryStep_ = infoEveryStep;\n\tp->weightRegularizer_ = weightRegularizer;\n\tp->beliefPropagationMaximumNumberOfIterations_ = beliefPropagationMaximumNumberOfIterations;\n\tp->beliefPropagationConvergenceBound_ = beliefPropagationConvergenceBound;\n\tp->beliefPropagationDamping_ = beliefPropagationDamping;\n\tp->beliefPropagationTemperature_ = beliefPropagationTemperature;\n\tp->beliefPropagationIsAcyclic_ = beliefPropagationIsAcyclic;\n        return p;\n    }\n\n    template<class DATASET>\n    void export_max_likelihood_learner(const std::string & clsName){\n        typedef learning::MaximumLikelihoodLearner<DATASET> PyLearner;\n        typedef typename PyLearner::Parameter PyLearnerParam;\n        typedef typename PyLearner::DatasetType DatasetType;\n\n        const std::string paramClsName = clsName + std::string(\"Parameter\");\n\n        bp::class_<PyLearnerParam>(paramClsName.c_str(), bp::init<>())\n\t  .def(\"__init__\", make_constructor(&pyMaxLikelihoodParamConstructor<PyLearnerParam> ,boost::python::default_call_policies()))\n\t  //.def_readwrite(\"maxIterations\", &PyLearnerParam::maximumNumberOfIterations_)\n        ;\n\n        boost::python::class_<PyLearner>( clsName.c_str(), boost::python::init<DatasetType &, const PyLearnerParam &>() )\n            .def(\"learn\",&PyLearner::learn)\n        ;\n    }\n\n  //template void\n  //export_max_likelihood_learner<op::GmAdderHammingLossDataset> (const std::string& className);\n\n    template void\n    export_max_likelihood_learner<op::GmAdderFlexibleLossDataset> (const std::string& className);\n}\n\n\n\n#endif\n\n", "meta": {"hexsha": "82fc5d099ff07c93dc458b3040077359b1baf243", "size": 2939, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/interfaces/python/opengm/learning/pyMaxLikelihoodLearner.cxx", "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": "src/interfaces/python/opengm/learning/pyMaxLikelihoodLearner.cxx", "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": "src/interfaces/python/opengm/learning/pyMaxLikelihoodLearner.cxx", "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": 35.8414634146, "max_line_length": 127, "alphanum_fraction": 0.7744130657, "num_tokens": 720, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.6224593452091672, "lm_q1q2_score": 0.47523761023948147}}
{"text": "// 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//     * 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// This file was created by Steffen Urban (urbste@googlemail.com) October 2019\n\n#include \"theia/sfm/estimators/estimate_radial_dist_uncalibrated_absolute_pose.h\"\n\n#include <ceres/rotation.h>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <memory>\n#include <vector>\n\n#include \"theia/sfm/camera/projection_matrix_utils.h\"\n#include \"theia/sfm/create_and_initialize_ransac_variant.h\"\n#include \"theia/sfm/estimators/feature_correspondence_2d_3d.h\"\n#include \"theia/sfm/pose/four_point_focal_length_radial_distortion.h\"\n#include \"theia/sfm/types.h\"\n#include \"theia/solvers/estimator.h\"\n#include \"theia/solvers/sample_consensus_estimator.h\"\n#include \"theia/util/util.h\"\n\nnamespace theia {\nnamespace {\n\nvoid DistortPoint(const Eigen::Vector2d& point2d, const double& distortion,\n                  Eigen::Vector2d* distorted_point) {\n  const double r_u_sq = point2d[0] * point2d[0] + point2d[1] * point2d[1];\n\n  const double denom = 2.0 * distortion * r_u_sq;\n  const double inner_sqrt = 1.0 - 4.0 * distortion * r_u_sq;\n\n  // If the denominator is nearly zero then we can evaluate the distorted\n  // coordinates as k or r_u^2 goes to zero. Both evaluate to the identity.\n  if (std::abs(denom) < 1e-15 || inner_sqrt < 0.0) {\n    (*distorted_point)[0] = point2d[0];\n    (*distorted_point)[1] = point2d[1];\n  } else {\n    const double scale = (1.0 - std::sqrt(inner_sqrt)) / denom;\n    (*distorted_point)[0] = point2d[0] * scale;\n    (*distorted_point)[1] = point2d[1] * scale;\n  }\n}\n\nusing Eigen::Matrix3d;\nusing Eigen::Vector2d;\nusing Eigen::Vector3d;\n// An estimator for computing the uncalibrated absolute pose from 4 feature\n// correspondences. The feature correspondences should be normalized such that\n// the principal point is at (0, 0).\nclass RadialDistUncalibratedAbsolutePoseEstimator\n    : public Estimator<FeatureCorrespondence2D3D,\n                       RadialDistUncalibratedAbsolutePose> {\n public:\n  RadialDistUncalibratedAbsolutePoseEstimator() {}\n\n  // 4 correspondences are needed to determine the absolute pose.\n  double SampleSize() const { return 4; }\n\n  // Estimates candidate absolute poses from correspondences.\n  bool EstimateModel(\n      const std::vector<FeatureCorrespondence2D3D>& correspondences,\n      std::vector<RadialDistUncalibratedAbsolutePose>* absolute_poses) const {\n    const Vector2d features[4] = {\n        correspondences[0].feature, correspondences[1].feature,\n        correspondences[2].feature, correspondences[3].feature};\n    const Vector3d world_points[4] = {\n        correspondences[0].world_point, correspondences[1].world_point,\n        correspondences[2].world_point, correspondences[3].world_point};\n\n    std::vector<Matrix3d> rotations;\n    std::vector<Vector3d> translations;\n    std::vector<double> radial_distortions;\n    std::vector<double> focal_lenghts;\n\n    if (!FourPointsPoseFocalLengthRadialDistortion(\n            features, world_points, meta_data_.max_focal_length,\n            meta_data_.min_focal_length, meta_data_.max_radial_distortion,\n            meta_data_.min_radial_distortion, &rotations, &translations,\n            &radial_distortions, &focal_lenghts))\n      return false;\n\n    absolute_poses->resize(rotations.size());\n    for (int i = 0; i < rotations.size(); ++i) {\n      (*absolute_poses)[i].radial_distortion = radial_distortions[i];\n      (*absolute_poses)[i].focal_length = focal_lenghts[i];\n      (*absolute_poses)[i].rotation = rotations[i];\n      (*absolute_poses)[i].translation = translations[i];\n    }\n\n    return rotations.size() > 0;\n  }\n\n  // The error for a correspondences given an absolute pose. This is the squared\n  // reprojection error.\n  double Error(const FeatureCorrespondence2D3D& correspondence,\n               const RadialDistUncalibratedAbsolutePose& absolute_pose) const {\n    // undistort the feature with the estimated radial distortion parameter\n    // project der world point with the given focal length and\n    // compare it to the undistorted image point\n    Matrix3d K =\n        Vector3d(absolute_pose.focal_length, absolute_pose.focal_length, 1.0)\n            .asDiagonal();\n    if (absolute_pose.translation[2] < 0.0) {\n        return 1.0e10;\n    }\n    Vector3d reproj_pt = (absolute_pose.rotation * correspondence.world_point +\n                          absolute_pose.translation);\n    const Eigen::Vector2d reproj_pt_2d = (K * reproj_pt).hnormalized();\n    Eigen::Vector2d distorted_point;\n    DistortPoint(reproj_pt_2d, absolute_pose.radial_distortion,\n                 &distorted_point);\n\n    return (distorted_point - correspondence.feature).squaredNorm();\n  }\n\n  void SetMetadata(RadialDistUncalibratedAbsolutePoseMetaData meta_data) {\n    meta_data_ = meta_data;\n  }\n\n private:\n  RadialDistUncalibratedAbsolutePoseMetaData meta_data_;\n\n  DISALLOW_COPY_AND_ASSIGN(RadialDistUncalibratedAbsolutePoseEstimator);\n};\n\n}  // namespace\n\nbool EstimateRadialDistUncalibratedAbsolutePose(\n    const RansacParameters& ransac_params, const RansacType& ransac_type,\n    const std::vector<FeatureCorrespondence2D3D>& normalized_correspondences,\n    const RadialDistUncalibratedAbsolutePoseMetaData& meta_data,\n    RadialDistUncalibratedAbsolutePose* absolute_pose,\n    RansacSummary* ransac_summary) {\n  RadialDistUncalibratedAbsolutePoseEstimator absolute_pose_estimator;\n  absolute_pose_estimator.SetMetadata(meta_data);\n\n  std::unique_ptr<\n      SampleConsensusEstimator<RadialDistUncalibratedAbsolutePoseEstimator> >\n      ransac = CreateAndInitializeRansacVariant(ransac_type, ransac_params,\n                                                absolute_pose_estimator);\n  // Estimate the absolute pose.\n  const bool success = ransac->Estimate(normalized_correspondences,\n                                        absolute_pose, ransac_summary);\n\n  return success;\n}\n\n}  // namespace theia\n", "meta": {"hexsha": "cb0e877a3486745c973a2d2a6040d05fe02e3be5", "size": 7599, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/sfm/estimators/estimate_radial_dist_uncalibrated_absolute_pose.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/estimators/estimate_radial_dist_uncalibrated_absolute_pose.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/estimators/estimate_radial_dist_uncalibrated_absolute_pose.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": 41.9834254144, "max_line_length": 81, "alphanum_fraction": 0.7336491644, "num_tokens": 1847, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.6224593382055109, "lm_q1q2_score": 0.4752375981926576}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n#include <vector>\n\n#include \"../flux_worker.hpp\"\n\nnamespace boltzmann {\nnamespace impl_mls {\n\n/**\n * @brief SpecularReflection\n *\n * velocity part (in Lagrange basis)\n *\n * upper hemisphere: outflow\n * lower hemisphere: inflow\n *\n */\nclass SpecularReflection : public boltzmann::impl::flux_worker\n{\n  using boltzmann::impl::flux_worker::vec_t;\n  using boltzmann::impl::flux_worker::mat_t;\n\n public:\n  SpecularReflection(const vec_t& hermite_weights, const vec_t& hermite_nodes)\n      : w_(hermite_weights)\n      , x_(hermite_nodes)\n  {\n    /* empty */\n  }\n\n  /**\n   *\n   *\n   * @param out Ordering: out(i,j) = f(x_i, y_j)\n   * \\remark{Also see documentation of @ref H2N.}\n   * @param in\n   */\n  virtual void apply(mat_t& out, const mat_t& in, const dealii::Point<2>& dummy) const;\n\n private:\n  const vec_t w_;\n  const vec_t x_;\n};\n\nvoid\nSpecularReflection::apply(mat_t& out, const mat_t& in, const dealii::Point<2>& dummy) const\n{\n  AssertDimension(in.rows(), out.rows());\n  AssertDimension(in.cols(), out.cols());\n  AssertDimension(in.cols(), w_.size());\n\n  int N = w_.size();\n\n  int nhalf = N / 2;\n\n  // reflection\n  for (int j = 0; j < N; ++j) {\n    for (int i = 0; i < N; ++i) {\n      if (i < nhalf)\n        out(i, j) = in(N - 1 - i, j);\n      else\n        out(i, j) = in(i, j);\n    }\n  }\n\n  // multiply with weights\n  for (int j = 0; j < N; ++j) {\n    for (int i = 0; i < N; ++i) {\n      out(i, j) *= x_[i];\n    }\n  }\n}\n\n}  // end namespace impl\n}  // end namespace boltzmann\n", "meta": {"hexsha": "ff42b6d1672cb169d6e79db4d299e618a435de56", "size": 1518, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/matrix/bc/impl/mls/specular_reflection.hpp", "max_stars_repo_name": "simonpp/2dBoltzmann", "max_stars_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/matrix/bc/impl/mls/specular_reflection.hpp", "max_issues_repo_name": "simonpp/2dBoltzmann", "max_issues_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/matrix/bc/impl/mls/specular_reflection.hpp", "max_forks_repo_name": "simonpp/2dBoltzmann", "max_forks_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.4615384615, "max_line_length": 91, "alphanum_fraction": 0.5988142292, "num_tokens": 476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4752375928454798}}
{"text": "#pragma once\n\n#include <merely3d/types.hpp>\n#include <merely3d/color.hpp>\n#include <Eigen/Dense>\n\nnamespace merely3d\n{\n    struct Rectangle\n    {\n        Rectangle() : extents(Eigen::Vector2f::Zero()) {}\n        explicit Rectangle(const Eigen::Vector2f & extents) : extents(extents) {}\n        Rectangle(float x_extent, float y_extent)\n            : extents(Eigen::Vector2f(x_extent, y_extent)) {}\n\n        UnalignedVector2f extents;\n    };\n\n    struct Box\n    {\n        Box() : extents(Eigen::Vector3f::Zero()) {}\n        explicit Box(const Eigen::Vector3f & extents) : extents(extents) {}\n        Box(float x_extent, float y_extent, float z_extent)\n            : extents(Eigen::Vector3f(x_extent, y_extent, z_extent)) {}\n\n        Eigen::Vector3f extents;\n    };\n\n    struct Sphere\n    {\n        Sphere() : radius(1.0) {}\n        explicit Sphere(float radius) : radius(radius) {}\n\n        float radius;\n    };\n\n    struct Line\n    {\n        Line(const Eigen::Vector3f & from, const Eigen::Vector3f & to, const Color & color = blue())\n                : from(from), to(to), color(color) {}\n\n        Eigen::Vector3f from;\n        Eigen::Vector3f to;\n        Color           color;\n    };\n\n    static const Color DEFAULT_PARTICLE_COLOR = Color(0.1, 0.1, 0.7);\n    static float DEFAULT_PARTICLE_RADIUS = 0.2;\n\n    struct Particle\n    {\n        Particle() : Particle(Eigen::Vector3f::Zero()) {}\n        Particle(const Eigen::Vector3f & position,\n                 float radius = DEFAULT_PARTICLE_RADIUS,\n                 const Color & color = DEFAULT_PARTICLE_COLOR)\n            : position(position), color(color), radius(radius) {}\n        Particle(float x, float y, float z,\n                 float radius = DEFAULT_PARTICLE_RADIUS,\n                 const Color & color = DEFAULT_PARTICLE_COLOR)\n            : Particle(Eigen::Vector3f(x, y, z), radius, color)\n        {}\n\n        Eigen::Vector3f position;\n        Color           color;\n        float           radius;\n\n        Particle with_radius(float new_radius) const\n        {\n            return Particle(position, new_radius, color);\n        }\n\n        Particle with_position(const Eigen::Vector3f & new_position) const\n        {\n            return Particle(new_position, radius, color);\n        }\n\n        Particle with_position(float x, float y, float z) const\n        {\n            return Particle(x, y, z, radius, color);\n        }\n\n        Particle with_color(const Color & new_color) const\n        {\n            return Particle(position, radius, new_color);\n        }\n    };\n}\n", "meta": {"hexsha": "2c0f461092d68e10b15d1d865706f43297614825", "size": 2535, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/merely3d/primitives.hpp", "max_stars_repo_name": "digitalillusions/merely3d", "max_stars_repo_head_hexsha": "c14326d4bef325b64da25fb8bf79c32665299549", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-01-07T12:31:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-31T04:47:16.000Z", "max_issues_repo_path": "include/merely3d/primitives.hpp", "max_issues_repo_name": "digitalillusions/merely3d", "max_issues_repo_head_hexsha": "c14326d4bef325b64da25fb8bf79c32665299549", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2018-10-18T13:54:29.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-06T13:48:24.000Z", "max_forks_repo_path": "include/merely3d/primitives.hpp", "max_forks_repo_name": "digitalillusions/merely3d", "max_forks_repo_head_hexsha": "c14326d4bef325b64da25fb8bf79c32665299549", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-02-03T19:10:31.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-05T14:10:15.000Z", "avg_line_length": 28.8068181818, "max_line_length": 100, "alphanum_fraction": 0.5771203156, "num_tokens": 579, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.47523759284547973}}
{"text": "/*\n * libcluster -- A collection of hierarchical Bayesian clustering algorithms.\n * Copyright (C) 2013 Daniel M. Steinberg (daniel.m.steinberg@gmail.com)\n *\n * This file is part of libcluster.\n *\n * libcluster is free software: you can redistribute it and/or modify it under\n * the terms of the GNU Lesser General Public License as published by the Free\n * Software Foundation, either version 3 of the License, or (at your option)\n * any later version.\n *\n * libcluster 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 libcluster. If not, see <http://www.gnu.org/licenses/>.\n */\n\n#include <boost/math/special_functions.hpp>\n#include \"distributions.h\"\n#include \"probutils.h\"\n\n//\n// Namespaces\n//\n\nusing namespace std;\nusing namespace Eigen;\nusing namespace probutils;\nusing namespace boost::math;\n\n\n//\n//  File scope variables\n//\n\n// Define pi\nconst double pi = constants::pi<double>(); // Boost high precision pi\n\n\n//\n// Private Helper Functions\n//\n\n/* Compare an <int,double> double pair by the double member. Useful\n *  for sorting an array in descending order while retaining a notion of\n *  the original order of the array.\n *\n *  returns: true if i.second > j.second.\n */\nbool inline obscomp (\n        const std::pair<int,double>& i, // the first pair to compare.\n        const std::pair<int,double>& j // the second pair to compare.\n        )\n{\n        return i.second > j.second;\n}\n\n\n/* Enumerate the dimensions.\n *\n *  returns: 1:D or if D = 1, return 1.\n */\nArrayXd enumdims (const int D)\n{\n        ArrayXd l;\n\n        if (D > 1)\n                l = ArrayXd::LinSpaced(D, 1, D);\n        else\n                l.setOnes(1);\n\n        return l;\n}\n\n\n//\n// Stick-Breaking (Dirichlet Process) weight distribution.\n//\n\ndistributions::StickBreak::StickBreak ()\n        : WeightDist(),\n        alpha1_p(distributions::ALPHA1PRIOR),\n        alpha2_p(distributions::ALPHA2PRIOR),\n        alpha1(ArrayXd::Constant(1, distributions::ALPHA1PRIOR)),\n        alpha2(ArrayXd::Constant(1, distributions::ALPHA2PRIOR)),\n        E_logv(ArrayXd::Zero(1)),\n        E_lognv(ArrayXd::Zero(1)),\n        E_logpi(ArrayXd::Zero(1)),\n        ordvec(1, pair<int,double>(0,0))\n{\n        this->priorfcalc();\n}\n\n\ndistributions::StickBreak::StickBreak (const double concentration)\n        : WeightDist(),\n        alpha2_p(distributions::ALPHA2PRIOR),\n        alpha2(ArrayXd::Constant(1, distributions::ALPHA2PRIOR)),\n        E_logv(ArrayXd::Zero(1)),\n        E_lognv(ArrayXd::Zero(1)),\n        E_logpi(ArrayXd::Zero(1)),\n        ordvec(1, pair<int,double>(0,0))\n{\n        if (concentration <=0)\n                throw invalid_argument(\"Concentration parameter has to be > 0!\");\n\n        this->alpha1_p = concentration;\n        this->alpha1 = ArrayXd::Constant(1, concentration);\n        this->priorfcalc();\n}\n\n\nvoid distributions::StickBreak::priorfcalc (void)\n{\n        // Prior free energy contribution\n        this->F_p = lgamma(this->alpha1_p) + lgamma(this->alpha2_p)\n                    - lgamma(this->alpha1_p + this->alpha2_p);\n}\n\n\nvoid distributions::StickBreak::update (const ArrayXd& Nk)\n{\n        const int K = Nk.size();\n\n        // Destructively resize members to be the same size as Nk, no-op if same\n        this->alpha1.resize(K);\n        this->alpha2.resize(K);\n        this->E_logv.resize(K);\n        this->E_lognv.resize(K);\n        this->E_logpi.resize(K);\n        this->ordvec.resize(K, pair<int,double>(-1, -1));\n\n        // Order independent update\n        this->Nk     = Nk;\n        this->alpha1 = this->alpha1_p + Nk;\n\n        // Get at sort size order of clusters\n        for (int k = 0; k < K; ++k)\n        {\n                this->ordvec[k].first  = k;\n                this->ordvec[k].second = Nk(k);\n        }\n        sort(this->ordvec.begin(), this->ordvec.end(), obscomp);\n\n        // Now do order dependent updates\n        const double N = Nk.sum();\n        double cumNk = 0, cumE_lognv = 0;\n        for (int idx = 0, k; idx < K; ++idx)\n        {\n                k = this->ordvec[idx].first;\n\n                // Alpha 2\n                cumNk += Nk(k); // Accumulate cluster size sum\n                this->alpha2(k) = this->alpha2_p + (N - cumNk);\n\n                // Expected stick lengths\n                double psisum    = digamma(this->alpha1(k) + this->alpha2(k));\n                this->E_logv(k)  = digamma(this->alpha1(k)) - psisum;\n                this->E_lognv(k) = digamma(this->alpha2(k)) - psisum;\n\n                // Expected weights\n                this->E_logpi(k) = this->E_logv(k) + cumE_lognv;\n                cumE_lognv += E_lognv(k); // Accumulate log stick length left\n        }\n}\n\n\ndouble distributions::StickBreak::fenergy () const\n{\n        const int K = this->alpha1.size();\n\n        return K * this->F_p + (mxlgamma(this->alpha1 + this->alpha2).array()\n                                - mxlgamma(this->alpha1).array() - mxlgamma(this->alpha2).array()\n                                + (this->alpha1 - this->alpha1_p) * this->E_logv\n                                + (this->alpha2 - this->alpha2_p) * this->E_lognv).sum();\n}\n\n\n//\n// Generalised Dirichlet weight distribution.\n//\n\nvoid distributions::GDirichlet::update (const ArrayXd& Nk)\n{\n        // Call base class (stick breaking) update\n        this->StickBreak::update(Nk);\n        const int smallk = (this->ordvec.end() - 1)->first; // Get smallest cluster\n\n        // Set last stick lengths to 1 ( log(0) = 1 ) and adjust log marginal\n        this->E_logpi(smallk) = this->E_logpi(smallk) - this->E_logv(smallk);\n        this->E_logv(smallk)  = 0; // exp(E[log v_K]) = 1\n        this->E_lognv(smallk) = 0; // Undefined, but set to zero\n}\n\n\ndouble distributions::GDirichlet::fenergy () const\n{\n        const int K = this->ordvec.size();\n\n        // GDir only has K-1 parameters, so we don't calculate the last F contrib.\n        double Fpi = 0;\n        for (int idx = 0, k = 0; idx < K-1; ++idx)\n        {\n                k = this->ordvec[idx].first;\n                Fpi += lgamma(this->alpha1(k) + this->alpha2(k))\n                       - lgamma(this->alpha1(k)) - lgamma(this->alpha2(k))\n                       + (this->alpha1(k) - this->alpha1_p) * this->E_logv(k)\n                       + (this->alpha2(k) - this->alpha2_p) * this->E_lognv(k);\n        }\n\n        return (K-1) * this->F_p + Fpi;\n}\n\n\n//\n// Dirichlet weight distribution.\n//\n\ndistributions::Dirichlet::Dirichlet ()\n        : WeightDist(),\n        alpha_p(distributions::ALPHA1PRIOR),\n        alpha(ArrayXd::Constant(1, distributions::ALPHA1PRIOR)),\n        E_logpi(ArrayXd::Zero(1))\n{\n}\n\n\ndistributions::Dirichlet::Dirichlet (const double alpha)\n        : WeightDist(),\n        E_logpi(ArrayXd::Zero(1))\n{\n        if (alpha <= 0)\n                throw invalid_argument(\"Alpha prior must be > 0!\");\n\n        alpha_p = alpha;\n        this->alpha = ArrayXd::Constant(1, alpha);\n}\n\n\nvoid distributions::Dirichlet::update (const ArrayXd& Nk)\n{\n        const int K = Nk.size();\n\n        // Destructively resize members to be the same size as Nk, no-op if same\n        this->alpha.resize(K);\n        this->E_logpi.resize(K);\n\n        // Hyperparameter update\n        this->Nk    = Nk;\n        this->alpha = this->alpha_p + Nk;\n\n        // Expectation update\n        this->E_logpi = mxdigamma(this->alpha).array() - digamma(this->alpha.sum());\n}\n\n\ndouble distributions::Dirichlet::fenergy () const\n{\n        const int K = this->alpha.size();\n\n        return lgamma(this->alpha.sum()) - (this->alpha_p-1) * this->E_logpi.sum()\n               + ((this->alpha-1) * this->E_logpi - mxlgamma(this->alpha).array()).sum()\n               - lgamma(K * this->alpha_p) + K * lgamma(this->alpha_p);\n}\n\n\n//\n// Gaussian Wishart cluster distribution.\n//\n\ndistributions::GaussWish::GaussWish (\n        const double clustwidth,\n        const unsigned int D\n        )\n        : ClusterDist(clustwidth, D),\n        nu_p(D),\n        beta_p(distributions::BETAPRIOR),\n        m_p(RowVectorXd::Zero(D))\n{\n        if (clustwidth <= 0)\n                throw invalid_argument(\"clustwidth must be > 0!\");\n\n        // Create Prior\n        this->iW_p = this->nu_p * this->prior * MatrixXd::Identity(D, D);\n\n        try\n        { this->logdW_p = -logdet(this->iW_p); }\n        catch (invalid_argument e)\n        { throw invalid_argument(string(\"Creating prior: \").append(e.what())); }\n\n        // Calculate prior free energy contribution\n        this->F_p = mxlgamma((this->nu_p + 1\n                              - enumdims(this->m_p.cols())).matrix() / 2).sum();\n\n        this->clearobs(); // Empty suff. stats. and set posteriors equal to priors\n}\n\n\nvoid distributions::GaussWish::addobs(const VectorXd& qZk, const MatrixXd& X)\n{\n        if (X.cols() != this->D)\n                throw invalid_argument(\"Mismatched dims. of cluster params and obs.!\");\n        if (qZk.rows() != X.rows())\n                throw invalid_argument(\"qZk and X ar not the same length!\");\n\n        MatrixXd qZkX = qZk.asDiagonal() * X;\n\n        this->N_s += qZk.sum();\n        this->x_s += qZkX.colwise().sum();       // [1xD] row vector\n        this->xx_s.noalias() += qZkX.transpose() * X; // [DxD] matrix\n}\n\n\nvoid distributions::GaussWish::update ()\n{\n        // Prepare the Sufficient statistics\n        RowVectorXd xk = RowVectorXd::Zero(this->D);\n        if (this->N_s > 0)\n                xk = this->x_s/this->N_s;\n        MatrixXd Sk = this->xx_s - xk.transpose() * this->x_s;\n        RowVectorXd xk_m = xk - this->m_p;         // for iW, (xk - m)\n\n        // Update posterior params\n        this->N    = this->N_s;\n        this->nu   = this->nu_p + this->N;\n        this->beta = this->beta_p + this->N;\n        this->m    = (this->beta_p * this->m_p + this->x_s) / this->beta;\n        this->iW   = this->iW_p + Sk\n                     + (this->beta_p * this->N/this->beta) * xk_m.transpose() * xk_m;\n\n        try\n        { this->logdW = -logdet(this->iW); }\n        catch (invalid_argument e)\n        { throw runtime_error(string(\"Calc log(det(W)): \").append(e.what())); }\n}\n\n\nvoid distributions::GaussWish::clearobs ()\n{\n        // Reset parameters back to prior values\n        this->nu    = this->nu_p;\n        this->beta  = this->beta_p;\n        this->m     = this->m_p;\n        this->iW    = this->iW_p;\n        this->logdW = this->logdW_p;\n\n        // Empty sufficient statistics\n        this->N_s  = 0;\n        this->x_s  = RowVectorXd::Zero(D);\n        this->xx_s = MatrixXd::Zero(D,D);\n}\n\n\nVectorXd distributions::GaussWish::Eloglike (const MatrixXd& X) const\n{\n        // Expectations of log Gaussian likelihood\n        VectorXd E_logX(X.rows());\n        double sumpsi = mxdigamma((this->nu+1-enumdims(this->D)).matrix()/2).sum();\n        try\n        {\n                E_logX = 0.5 * (sumpsi + this->logdW - this->D * (1/this->beta + log(pi))\n                                - this->nu * mahaldist(X, this->m, this->iW).array()).matrix();\n        }\n        catch (invalid_argument e)\n        { throw(string(\"Calculating Gaussian likelihood: \").append(e.what())); }\n\n        return E_logX;\n}\n\n\ndistributions::ArrayXb distributions::GaussWish::splitobs (\n        const MatrixXd& X\n        ) const\n{\n\n        // Find the principle eigenvector using the power method if not done so\n        VectorXd eigvec;\n        eigpower(this->iW, eigvec);\n\n        // 'split' the observations perpendicular to this eigenvector.\n        return (((X.rowwise() - this->m)\n                 * eigvec.asDiagonal()).array().rowwise().sum()) >= 0;\n}\n\n\ndouble distributions::GaussWish::fenergy () const\n{\n        const ArrayXd l = enumdims(this->D);\n        double sumpsi = mxdigamma((this->nu + 1 - l).matrix() / 2).sum();\n\n        return this->F_p + (this->D * (this->beta_p/this->beta - 1 - this->nu\n                                       - log(this->beta_p/this->beta))\n                            + this->nu * ((this->iW.ldlt().solve(this->iW_p)).trace()\n                                          + this->beta_p * mahaldist(this->m, this->m_p, this->iW).coeff(0,0))\n                            + this->nu_p * (this->logdW_p - this->logdW) + this->N*sumpsi)/2\n               - mxlgamma((this->nu+1-l).matrix() / 2).sum();\n}\n\n\n//\n// Normal Gamma parameter distribution.\n//\n\ndistributions::NormGamma::NormGamma (\n        const double clustwidth,\n        const unsigned int D\n        )\n        : ClusterDist(clustwidth, D),\n        nu_p(distributions::NUPRIOR),\n        beta_p(distributions::BETAPRIOR),\n        m_p(RowVectorXd::Zero(D))\n{\n        if (clustwidth <= 0)\n                throw invalid_argument(\"clustwidth must be > 0!\");\n\n        // Create Prior\n        this->L_p = this->nu_p * this->prior * RowVectorXd::Ones(D);\n        this->logL_p = this->L_p.array().log().sum();\n\n        this->clearobs(); // Empty suff. stats. and set posteriors equal to priors\n}\n\n\nvoid distributions::NormGamma::addobs (const VectorXd& qZk, const MatrixXd& X)\n{\n        if (X.cols() != this->D)\n                throw invalid_argument(\"Mismatched dims. of cluster params and obs.!\");\n        if (qZk.rows() != X.rows())\n                throw invalid_argument(\"qZk and X ar not the same length!\");\n\n        MatrixXd qZkX = qZk.asDiagonal() * X;\n\n        this->N_s  += qZk.sum();\n        this->x_s  += qZkX.colwise().sum();                           // [1xD]\n        this->xx_s += (qZkX.array() * X.array()).colwise().sum().matrix(); // [1xD]\n}\n\n\nvoid distributions::NormGamma::update ()\n{\n        // Prepare the Sufficient statistics\n        RowVectorXd xk = RowVectorXd::Zero(this->D);\n        RowVectorXd Sk = RowVectorXd::Zero(this->D);\n        if (this->N_s > 0)\n        {\n                xk = this->x_s/this->N_s;\n                Sk = this->xx_s.array() - this->x_s.array().square()/this->N_s;\n        }\n\n        // Update posterior params\n        this->N    = this->N_s;\n        this->beta = this->beta_p + this->N;\n        this->nu   = this->nu_p + this->N/2;\n        this->m    = (this->beta_p * this->m_p + x_s) / this->beta;\n        this->L    = this->L_p + Sk/2 + (this->beta_p * this->N / (2 * this->beta))\n                     * (xk - this->m_p).array().square().matrix();\n\n        if ((this->L.array() <= 0).any())\n                throw invalid_argument(string(\"Calc log(L): Variance is zero or less!\"));\n\n        this->logL = this->L.array().log().sum();\n}\n\n\nvoid distributions::NormGamma::clearobs ()\n{\n        // Reset parameters back to prior values\n        this->nu   = this->nu_p;\n        this->beta = this->beta_p;\n        this->m    = this->m_p;\n        this->L    = this->L_p;\n        this->logL = this->logL_p;\n\n        // Empty sufficient statistics\n        this->N_s  = 0;\n        this->x_s  = RowVectorXd::Zero(this->D);\n        this->xx_s = RowVectorXd::Zero(this->D);\n}\n\n\nVectorXd distributions::NormGamma::Eloglike (const MatrixXd& X) const\n{\n        // Distance evaluation in the exponent\n        VectorXd Xmdist = (X.rowwise() - this->m).array().square().matrix()\n                          * this->L.array().inverse().matrix().transpose();\n\n        // Expectations of log Gaussian likelihood\n        return 0.5 * (this->D * (digamma(this->nu) - log(2 * pi) - 1/this->beta)\n                      - this->logL - this->nu * Xmdist.array());\n}\n\n\ndistributions::ArrayXb distributions::NormGamma::splitobs (\n        const MatrixXd& X\n        ) const\n{\n        // Find location of largest element in L, this is the 'eigenvector'\n        int eigvec;\n        this->L.maxCoeff(&eigvec);\n\n        // 'split' the observations perpendicular to this 'eigenvector'.\n        return (X.col(eigvec).array() - this->m(eigvec)) >= 0;\n}\n\n\ndouble distributions::NormGamma::fenergy () const\n{\n        const VectorXd iL = this->L.array().inverse().matrix().transpose();\n\n        return D*(lgamma(this->nu_p) - lgamma(this->nu)\n                  + this->N*digamma(this->nu)/2 - this->nu)\n               + D/2 * (log(this->beta) - log(this->beta_p) - 1 + this->beta_p/this->beta)\n               + this->beta_p*this->nu/2*(this->m - this->m_p).array().square().matrix()*iL\n               + this->nu_p*(this->logL - this->logL_p) + this->nu*this->L_p*iL;\n}\n\n\n//\n// Exponential Gamma parameter distribution.\n//\n\ndistributions::ExpGamma::ExpGamma (const double obsmag, const unsigned int D)\n        : ClusterDist(obsmag, D),\n        a_p(distributions::APRIOR),\n        b_p(obsmag)\n{\n        this->clearobs(); // Empty suff. stats. and set posteriors equal to priors\n}\n\n\nvoid distributions::ExpGamma::addobs (const VectorXd& qZk, const MatrixXd& X)\n{\n        if (X.cols() != this->D)\n                throw invalid_argument(\"Mismatched dims. of cluster params and obs.!\");\n        if (qZk.rows() != X.rows())\n                throw invalid_argument(\"qZk and X ar not the same length!\");\n\n        this->N_s += qZk.sum();\n        this->x_s += (qZk.asDiagonal() * X).colwise().sum();\n}\n\n\nvoid distributions::ExpGamma::update ()\n{\n        // Update posterior params\n        this->N    = this->N_s;\n        this->a    = this->a_p + this->N;\n        this->ib   = (this->b_p + this->x_s.array()).array().inverse().matrix();\n        this->logb = -this->ib.array().log().sum();\n}\n\n\nvoid distributions::ExpGamma::clearobs ()\n{\n        // Reset parameters back to prior values\n        this->a    = this->a_p;\n        this->ib   = RowVectorXd::Constant(this->D, 1/this->b_p);\n        this->logb = this->D * log(this->b_p);\n\n        // Empty sufficient statistics\n        this->N_s = 0;\n        this->x_s = RowVectorXd::Zero(this->D);\n}\n\n\nVectorXd distributions::ExpGamma::Eloglike (const MatrixXd& X) const\n{\n        return this->D * digamma(this->a) - this->logb\n               - (this->a * X * this->ib.transpose()).array();\n}\n\n\ndistributions::ArrayXb distributions::ExpGamma::splitobs (\n        const MatrixXd& X\n        ) const\n{\n        ArrayXd XdotL = X;// * (this->a * this->ib).transpose();\n        return (XdotL > (XdotL.sum()/XdotL.size()));\n}\n\n\ndouble distributions::ExpGamma::fenergy () const\n{\n        return this->D * ((this->a - this->a_p) * digamma(this->a) - this->a\n                          - this->a_p * log(this->b_p) - lgamma(this->a) + lgamma(this->a_p))\n               + this->b_p * this->a * this->ib.sum() + this->a_p * this->logb;\n}\n", "meta": {"hexsha": "ad7d96fc1c2a9789ac2f6eb5409b3e075ad3521d", "size": 18404, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdparty/LibCluster/src/distributions.cpp", "max_stars_repo_name": "mfkiwl/ICE", "max_stars_repo_head_hexsha": "e660d031bb1bcea664db1de4946fd8781be5b627", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 50.0, "max_stars_repo_stars_event_min_datetime": "2019-10-12T01:22:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T23:28:26.000Z", "max_issues_repo_path": "3rdparty/LibCluster/src/distributions.cpp", "max_issues_repo_name": "wuyou33/Enabling-Robust-State-Estimation-through-Measurement-Error-Covariance-Adaptation", "max_issues_repo_head_hexsha": "2f1ff054b7c5059da80bb3b2f80c05861a02cc36", "max_issues_repo_licenses": ["MIT"], "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/LibCluster/src/distributions.cpp", "max_forks_repo_name": "wuyou33/Enabling-Robust-State-Estimation-through-Measurement-Error-Covariance-Adaptation", "max_forks_repo_head_hexsha": "2f1ff054b7c5059da80bb3b2f80c05861a02cc36", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2019-11-05T01:50:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T06:23:44.000Z", "avg_line_length": 31.1404399323, "max_line_length": 110, "alphanum_fraction": 0.5637361443, "num_tokens": 5046, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.4752375928454796}}
{"text": "#define BOOST_TEST_MODULE TEST_MODEL_EXPR\n#include <boost/test/unit_test.hpp>\n#include \"libs/experiments/ROC.h\"\n#include <cmath>\n\nfloat trancate(float input, int by)\n{\n    input *= by;\n    return std::roundf(input)/by;\n}\n\nBOOST_AUTO_TEST_CASE(test_basic_algorithm) \n{\n    constexpr exprs::value_type acc = 0.461538f;\n    constexpr exprs::value_type rmse = 1.03775f;\n    constexpr exprs::value_type roc_area = 0.380952f;\n    const  exprs::data_array tpr{\n        0.f, 0.142857f, 0.714286f, 1.f\n    };\n\n    const exprs::data_array fpr{\n        0.f, 0.333333f, 0.833333f, 1.f\n    };\n\n    exprs::data_array actual_measures = {\n        1.f, 0.f, 2.f, 1.f, 0.f, 1.f, 2.f, 0.f, 0.f, 1.f, 1.f, 0.f, 0.f\n    };\n\n    exprs::data_array calcualted_values = {\n        1.f, 1.f, 1.f, 0.f, 2.f, 1.f, 2.f, 1.f, 2.f, 0.f, 1.f, 0.f, 1.f\n    };\n\n    exprs::ROC roc_calc;\n    BOOST_TEST(roc_calc.results.area == 0.f);\n    BOOST_TEST(roc_calc.results.accuracy == 0.f);\n    BOOST_TEST(roc_calc.results.rmse == 0.f);\n    BOOST_TEST(roc_calc.results.fall_out.empty());\n    BOOST_TEST(roc_calc.results.sensitivity.empty());\n    BOOST_TEST_REQUIRE((roc_calc.calculate(actual_measures, calcualted_values)));\n    BOOST_TEST(trancate(roc_calc.results.area, 4) == trancate(roc_area, 4));\n    BOOST_TEST(trancate(roc_calc.results.rmse, 4) == trancate(rmse, 4));\n    BOOST_TEST(trancate(roc_calc.results.accuracy, 4) == trancate(acc, 4));\n    BOOST_TEST_REQUIRE(roc_calc.results.sensitivity.size() == tpr.size());\n    BOOST_TEST_REQUIRE(roc_calc.results.fall_out.size() == fpr.size());\n    BOOST_TEST_REQUIRE(roc_calc.results.fall_out.size() == roc_calc.results.sensitivity.size());\n    for (auto i = 0u; i < roc_calc.results.sensitivity.size(); i++) {\n        BOOST_TEST(trancate(roc_calc.results.sensitivity[i], 4) == trancate(tpr[i], 4));\n        BOOST_TEST(trancate(roc_calc.results.fall_out[i], 4) == trancate(fpr[i], 4));\n    }\n}\n\nBOOST_AUTO_TEST_CASE(test_invalid_entries)\n{\n    exprs::ROC roc_calc;\n    BOOST_TEST_REQUIRE((roc_calc.classes_calculate(std::vector<int>{}, std::vector<float>{}) == false));\n    BOOST_TEST(roc_calc.results.accuracy == 0.f);\n    BOOST_TEST(roc_calc.results.rmse == 0.f);\n    BOOST_TEST(roc_calc.results.fall_out.empty());\n    BOOST_TEST(roc_calc.results.sensitivity.empty());\n    BOOST_TEST_REQUIRE((roc_calc.calculate(std::vector<float>{}, std::vector<float>{}) == false));\n    BOOST_TEST(roc_calc.results.accuracy == 0.f);\n    BOOST_TEST(roc_calc.results.rmse == 0.f);\n    BOOST_TEST(roc_calc.results.fall_out.empty());\n    BOOST_TEST(roc_calc.results.sensitivity.empty());\n    BOOST_TEST_REQUIRE((roc_calc.calculate(std::vector<float>{1.f, 2.f, 3.f}, std::vector<float>{1.f, 2.f}) == false));\n    BOOST_TEST(roc_calc.results.accuracy == 0.f);\n    BOOST_TEST(roc_calc.results.rmse == 0.f);\n    BOOST_TEST(roc_calc.results.fall_out.empty());\n    BOOST_TEST(roc_calc.results.sensitivity.empty());\n    BOOST_TEST_REQUIRE((roc_calc.classes_calculate(std::vector<int>{1, 2, 3}, std::vector<float>{1.f, 2.f}) == false));\n    BOOST_TEST(roc_calc.results.accuracy == 0.f);\n    BOOST_TEST(roc_calc.results.rmse == 0.f);\n    BOOST_TEST(roc_calc.results.fall_out.empty());\n    BOOST_TEST(roc_calc.results.sensitivity.empty());\n}\n\nBOOST_AUTO_TEST_CASE(test_classifier_calc)\n{\n    constexpr exprs::value_type acc = 0.461538f;\n    constexpr exprs::value_type rmse = 1.03775f;\n    constexpr exprs::value_type roc_area = 0.380952f;\n    const  exprs::data_array tpr{\n        0.f, 0.142857f, 0.714286f, 1.f\n    };\n\n    const exprs::data_array fpr{\n        0.f, 0.333333f, 0.833333f, 1.f\n    };\n\n    std::vector<int> actual_measures = {\n        1, 0, 2, 1, 0, 1, 2, 0, 0, 1, 1, 0, 0\n    };\n\n    exprs::data_array calcualted_values = {\n        1.f, 1.f, 1.f, 0.f, 2.f, 1.f, 2.f, 1.f, 2.f, 0.f, 1.f, 0.f, 1.f\n    };\n    exprs::ROC roc_calc;\n    BOOST_TEST(roc_calc.results.area == 0.f);\n    BOOST_TEST(roc_calc.results.accuracy == 0.f);\n    BOOST_TEST(roc_calc.results.rmse == 0.f);\n    BOOST_TEST(roc_calc.results.fall_out.empty());\n    BOOST_TEST(roc_calc.results.sensitivity.empty());\n    BOOST_TEST_REQUIRE((roc_calc.classes_calculate(actual_measures, calcualted_values)));\n    BOOST_TEST(trancate(roc_calc.results.area, 4) == trancate(roc_area, 4));\n    BOOST_TEST(trancate(roc_calc.results.rmse, 4) == trancate(rmse, 4));\n    BOOST_TEST(trancate(roc_calc.results.accuracy, 4) == trancate(acc, 4));\n    BOOST_TEST_REQUIRE(roc_calc.results.sensitivity.size() == tpr.size());\n    BOOST_TEST_REQUIRE(roc_calc.results.fall_out.size() == fpr.size());\n    BOOST_TEST_REQUIRE(roc_calc.results.fall_out.size() == roc_calc.results.sensitivity.size());\n    for (auto i = 0u; i < roc_calc.results.sensitivity.size(); i++) {\n        BOOST_TEST(trancate(roc_calc.results.sensitivity[i], 4) == trancate(tpr[i], 4));\n        BOOST_TEST(trancate(roc_calc.results.fall_out[i], 4) == trancate(fpr[i], 4));\n    }\n}\n", "meta": {"hexsha": "bc48caba42826fe7fc9cca6a0a02ef254604851e", "size": 4887, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/libs/experiments/ut/test_algorithm.cpp", "max_stars_repo_name": "boazsade/machine_learinig_models", "max_stars_repo_head_hexsha": "eb1f9eda0e4e25a6d028b25682dfb20628a20624", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/libs/experiments/ut/test_algorithm.cpp", "max_issues_repo_name": "boazsade/machine_learinig_models", "max_issues_repo_head_hexsha": "eb1f9eda0e4e25a6d028b25682dfb20628a20624", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libs/experiments/ut/test_algorithm.cpp", "max_forks_repo_name": "boazsade/machine_learinig_models", "max_forks_repo_head_hexsha": "eb1f9eda0e4e25a6d028b25682dfb20628a20624", "max_forks_repo_licenses": ["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.4956521739, "max_line_length": 119, "alphanum_fraction": 0.6764886433, "num_tokens": 1519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911057, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4752375861458337}}
{"text": "#include <cstdlib>\n#include <boost/numeric/ublas/io.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 <Eigen/Core>\n#include <boost/numeric/bindings/ublas/vector.hpp>\n#include <boost/numeric/bindings/ublas/matrix_proxy.hpp>\n#include <boost/numeric/bindings/ublas/matrix_expression.hpp>\n#include <boost/numeric/bindings/eigen/vector.hpp>\n#include <boost/numeric/bindings/blas/level1.hpp>\n\nnamespace ublas=boost::numeric::ublas;\nnamespace blas=boost::numeric::bindings::blas;\n\n\nint main(int argc, char *argv[]) {\n  {\n    typedef ublas::vector<double> vector;\n    typedef ublas::matrix<double> matrix;\n    typedef vector::size_type size_type;\n    size_type n=8;\n    vector v(n);\n    blas::set(1.0, v);\n    std::cout << v << '\\n';\n    matrix M(n, 2*n);\n    for (size_type j=0; j<2*n; ++j)\n      for (size_type i=0; i<n; ++i) \n     \tM(i, j)=1;\n    ublas::matrix_column<matrix> mc(M, 2);\n    ublas::matrix_row<matrix> mr(M, 3);\n    blas::set(2.0, mc);\n    blas::set(3.0, mr);\n    std::cout << M << '\\n';\n  }\n\n  {\n    typedef Eigen::Matrix<double, Eigen::Dynamic, 1> vector;\n    typedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> matrix;\n    typedef int size_type;\n    size_type n=8;\n    vector v(n);\n    blas::set(1.0, v);\n    std::cout << v << '\\n';\n    matrix M(n, 2*n);\n    for (size_type j=0; j<2*n; ++j)\n      for (size_type i=0; i<n; ++i) \n     \tM(i, j)=1;\n    auto mc=M.col(2);\n    auto mr=M.row(3);\n    blas::set(2.0, mc);\n    blas::set(3.0, mr);\n    std::cout << M << '\\n';\n  }\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "6b8e79b9c5aefc2b311ba3a3f6ef2048c0e2345a", "size": 1612, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/blas/set.cc", "max_stars_repo_name": "rabauke/numeric_bindings", "max_stars_repo_head_hexsha": "f4de93bd7a01a8b31c9367fad35c81d086768f99", "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/blas/set.cc", "max_issues_repo_name": "rabauke/numeric_bindings", "max_issues_repo_head_hexsha": "f4de93bd7a01a8b31c9367fad35c81d086768f99", "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/blas/set.cc", "max_forks_repo_name": "rabauke/numeric_bindings", "max_forks_repo_head_hexsha": "f4de93bd7a01a8b31c9367fad35c81d086768f99", "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.2807017544, "max_line_length": 73, "alphanum_fraction": 0.6271712159, "num_tokens": 515, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911057, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4752375861458337}}
{"text": "// Author: Henrique Mendon\u00e7a <henrique@apache.org>\n#include \"rsba/solveRSpnp.h\"\n#include \"rsba/mat/cam.h\"\n#include \"rsba/VideoSfmBaRs.h\"\n#include \"rsba/struct/VideoSfM.h\"\n\n#include <ceres/rotation.h>\n#include <opencv2/core/core_c.h>\n#if (defined(CV_VERSION_EPOCH) && CV_VERSION_EPOCH == 2)\n#include <opencv2/core/internal.hpp>\n#else\n#define __OPENCV_BUILD\n#include <opencv2/cvconfig.h>\n#include <opencv2/core/private.hpp>\n#endif\n#include <iostream>\n//#include <boost/timer/timer.hpp>\n\nusing namespace ::cv;\nusing namespace ::vision;\nusing namespace ::vision::sfm;\n\n\ntemplate <typename TF>\nstruct RsBA: public ReprojectionError {\n  TF point[NUM_POINT_PARAMS];\n  SHUTTER rs;\n  const int* const scanlines;\n\n  RsBA(const double camera[NUM_CAM_PARAMS],\n       const TF* const observed, // 2D\n       const TF* const point3d,\n       const SHUTTER _rs,\n       const int* const _scanlines) // 3D\n  : scanlines(_scanlines)\n  {\n    observed_x = (observed[0]); observed_y = (observed[1]);\n    memcpy(camera_params, camera, sizeof(camera_params));\n    memcpy(point, point3d, sizeof(point));\n    rs = _rs;\n  };\n\n\n  template <typename T>\n  bool operator()(const T* const pose0,\n                  T* residuals) const {\n    return operator()(pose0, pose0, residuals);\n  };\n\n\n  template <typename T>\n  bool operator()(const T* const pose0,\n                  const T* const pose1,\n                  T* residuals) const {\n    T pose[6];\n    T obs[2] = { T(observed_x), T(observed_x) };\n    interpolate_rs(pose0, pose1, rs, scanlines, obs, pose);\n\n    T camera[NUM_CAM_PARAMS];\n    for (short i = 0; i < NUM_CAM_PARAMS; i++)\n      camera[i] = T(camera_params[i]);\n\n    T proj[2]; //reprojection\n    T p[NUM_POINT_PARAMS] = { T(point[0]), T(point[1]), T(point[2]) };\n    if ( ! w2i(camera, pose, p, proj, false)) {\n      return false;\n    }\n\n    // The error is the difference between the reprojection and observed position.\n    residuals[0] = (proj[0] - T(observed_x));\n    residuals[1] = (proj[1] - T(observed_y));\n\n    T threshold(5);\n    if (abs(residuals[0]) < threshold and abs(residuals[1]) < threshold) {\n      return true;\n    } else { //TODO check matches\n      return true;\n    }\n  }\n\n\n  // Factory to hide the construction of the CostFunction object from the client code.\n  static ceres::CostFunction* Create(\n      const double camera[NUM_CAM_PARAMS],\n      const TF* const observed,\n      const TF* const point3d,\n      const SHUTTER rs,\n      const int* const scanlines)\n  {\n    return (new ceres::AutoDiffCostFunction<RsBA,\n        NUM_RESIDUALS\n        ,NUM_POSE_PARAMS // Initial frame pose\n        ,NUM_POSE_PARAMS\n        >( // Final frame pose\n                new RsBA(camera, observed, point3d, rs, scanlines)));\n  }\n};\n\n\nbool vision::solveRsPnP(InputArray _opoints, InputArray _ipoints,\n                  InputArray _cameraMatrix, InputArray _distCoeffs,\n                  OutputArray _rvec, OutputArray _tvec,\n                  OutputArray _rvec2, OutputArray _tvec2,\n                  const SHUTTER shutter, const int scanlines[2],\n                  bool useExtrinsicGuess, int flags)\n{\n  //boost::timer::auto_cpu_timer btimer;\n\n  _rvec.create(3, 1, CV_64F);\n  _tvec.create(3, 1, CV_64F);\n  _rvec2.create(3, 1, CV_64F);\n  _tvec2.create(3, 1, CV_64F);\n  cv::Mat rvec = _rvec.getMat(), tvec = _tvec.getMat();\n  cv::Mat rvec2 = _rvec2.getMat(), tvec2 = _tvec2.getMat();\n\n  if (cv::norm(rvec, NORM_L1) + cv::norm(tvec, NORM_L1) +\n      cv::norm(rvec2, NORM_L1) + cv::norm(tvec2, NORM_L1) == 0) {\n    if (solvePnP(_opoints, _ipoints, _cameraMatrix, _distCoeffs, rvec, tvec, useExtrinsicGuess, flags))\n    { // GS Init\n      rvec.copyTo(rvec2);\n      tvec.copyTo(tvec2);\n      std::cout << \"GS PnP Init: \" << rvec << tvec << endl;\n    }\n  }\n\n  {\n    ceres::Problem problem;\n    Mat opoints = _opoints.getMat(), ipoints = _ipoints.getMat();\n\n    vector<double> pose(NUM_POSE_PARAMS), pose2(NUM_POSE_PARAMS);\n    { // Init poses\n      double rInv[3];\n      assign3(rvec.at<Vec3d>(0, 0).val, pose.data());\n      invert3(pose.data(), rInv);\n      ceres::AngleAxisRotatePoint(rInv, (-tvec.at<Vec3d>(0, 0)).val, pose.data()+3);\n\n      assign3(rvec2.at<Vec3d>(0, 0).val, pose2.data());\n      invert3(pose2.data(), rInv);\n      ceres::AngleAxisRotatePoint(rInv, (-tvec2.at<Vec3d>(0, 0)).val, pose2.data()+3);\n    }\n\n    std::vector<double> cam = sfmCam(_cameraMatrix.getMat(), _distCoeffs.getMat());\n    for (int i = 0; i < _opoints.size().width; i++) {\n      ceres::CostFunction* costFunction = RsBA<float>::Create(cam.data(),\n                                                              ipoints.at<Vec2f>(0, i).val,\n                                                              opoints.at<Vec3f>(0, i).val,\n                                                              shutter, scanlines);\n      problem.AddResidualBlock(costFunction, NULL, pose.data(), pose2.data());\n    }\n\n    // Make Ceres automatically detect the bundle structure. Note that the\n    // standard solver, SPARSE_NORMAL_CHOLESKY, also works fine but it is slower\n    // for standard bundle adjustment problems.\n    ceres::Solver::Options options;\n    options.linear_solver_type = ceres::SPARSE_SCHUR;\n    //options.minimizer_progress_to_stdout = true;\n    options.max_num_iterations = 10;\n\n    ceres::Solver::Summary summary;\n    ceres::Solve(options, &problem, &summary);\n    if (summary.IsSolutionUsable())\n    {\n//      std::cout << summary.BriefReport() << endl;\n\n      assign3(pose.data(), rvec.at<Vec3d>(0, 0).val);\n      assign3(pose.data()+3, tvec.at<Vec3d>(0, 0).val);\n      // invert translation\n      ceres::AngleAxisRotatePoint(pose.data(), tvec.at<Vec3d>(0, 0).val, tvec.at<Vec3d>(0, 0).val);\n      tvec *= -1;\n//      std::cout << rvec << endl;\n//      std::cout << tvec << endl;\n\n\n      assign3(pose2.data(), rvec2.at<Vec3d>(0, 0).val);\n      assign3(pose2.data()+3, tvec2.at<Vec3d>(0, 0).val);\n      // invert translation\n      ceres::AngleAxisRotatePoint(pose2.data(), tvec2.at<Vec3d>(0, 0).val, tvec2.at<Vec3d>(0, 0).val);\n      tvec2 *= -1;\n//      std::cout << rvec2 << endl;\n//      std::cout << tvec2 << endl;\n\n\n//      solvePnP(_opoints, _ipoints, _cameraMatrix, _distCoeffs, orvec, otvec, useExtrinsicGuess, flags);\n//      std::cout << orvec << endl;\n//      std::cout << otvec << endl;\n\n      return true;\n    }\n  }\n\n  return false;\n}\n\nnamespace vision\n{\n    namespace pnpransac\n    {\n        struct CameraParameters\n        {\n            void init(Mat _intrinsics, Mat _distCoeffs, const SHUTTER _shutter, const int* _scanlines)\n            {\n                _intrinsics.copyTo(intrinsics);\n                _distCoeffs.copyTo(distortion);\n                shutter = _shutter;\n                scanlines = _scanlines;\n            }\n\n            Mat intrinsics;\n            Mat distortion;\n            SHUTTER shutter;\n            const int* scanlines;\n        };\n\n        struct Parameters\n        {\n            int iterationsCount;\n            float reprojectionError;\n            int minInliersCount;\n            bool useExtrinsicGuess;\n            int flags;\n            CameraParameters camera;\n            int min_points_count;\n        };\n\n\n        static vector<Point2f> project3dPoints(const Mat& opoints, const Mat& ipoints, const Parameters& params,\n                                           const Mat& rvec,  const Mat& tvec,\n                                           const Mat& rvec2, const Mat& tvec2)\n        {\n          vector<Point2f> projected_points(opoints.cols);\n\n          for (int i = 0; i < opoints.cols; i++) {\n            Point3f op(opoints.at<Vec3f>(0, i));\n            Point2f ip(ipoints.at<Vec2f>(0, i));\n\n            vector<double> pose(6, 0);\n            assign3(rvec.at<Vec3d>(0, 0).val, pose.data());\n            double rInv[3];\n            invert3(pose.data(), rInv);\n            ceres::AngleAxisRotatePoint(rInv, (-tvec.at<Vec3d>(0, 0)).val, pose.data()+3);\n\n            vector<double> pose2(6, 0);\n            assign3(rvec2.at<Vec3d>(0, 0).val, pose2.data());\n            invert3(pose2.data(), rInv);\n            ceres::AngleAxisRotatePoint(rInv, (-tvec2.at<Vec3d>(0, 0)).val, pose2.data()+3);\n\n            std::vector<double> cam = sfmCam(params.camera.intrinsics, params.camera.distortion);\n            double point[] = { op.x, op.y, op.z };\n            double obs[] = { ip.x, ip.y };\n            double poseInter[NUM_POSE_PARAMS];\n            interpolate_rs(pose.data(), pose2.data(), params.camera.shutter, params.camera.scanlines, obs, poseInter);\n\n\n            double proj[2]; //reprojection\n            if ( ! w2i(cam.data(), poseInter, point, proj, false)) {\n              std::abort();\n            }\n            projected_points[i].x = proj[0];\n            projected_points[i].y = proj[1];\n          }\n\n          return projected_points;\n        }\n\n        static void pnpTask(const vector<char>& pointsMask, const Mat& objectPoints, const Mat& imagePoints,\n                     const Parameters& params, vector<int>& inliers,\n                     Mat& rvec, Mat& tvec, Mat& rvec2, Mat& tvec2,\n                     const Mat& rvecInit, const Mat& tvecInit, const Mat& rvecInit2, const Mat& tvecInit2,\n                     Mutex& resultsMutex)\n        {\n            Mat modelObjectPoints(1, params.min_points_count, CV_32FC3), modelImagePoints(1, params.min_points_count, CV_32FC2);\n            for (int i = 0, colIndex = 0; i < (int)pointsMask.size(); i++)\n            {\n                if (pointsMask[i])\n                {\n                    Mat colModelImagePoints = modelImagePoints(Rect(colIndex, 0, 1, 1));\n                    imagePoints.col(i).copyTo(colModelImagePoints);\n                    Mat colModelObjectPoints = modelObjectPoints(Rect(colIndex, 0, 1, 1));\n                    objectPoints.col(i).copyTo(colModelObjectPoints);\n                    colIndex = colIndex+1;\n                }\n            }\n\n            //filter same 3d points, hang in solveRsPnP\n            double eps = 1e-10;\n            int num_same_points = 0;\n            for (int i = 0; i < params.min_points_count; i++)\n                for (int j = i + 1; j < params.min_points_count; j++)\n                {\n                    if (norm(modelObjectPoints.at<Vec3f>(0, i) - modelObjectPoints.at<Vec3f>(0, j)) < eps)\n                        num_same_points++;\n                }\n            if (num_same_points > 0)\n                return;\n\n            Mat localRvec, localTvec;\n            Mat localRvec2, localTvec2;\n            rvecInit.copyTo(localRvec);\n            tvecInit.copyTo(localTvec);\n            rvecInit2.copyTo(localRvec2);\n            tvecInit2.copyTo(localTvec2);\n\n            vector<int> localInliers;\n            vision::solveRsPnP(modelObjectPoints, modelImagePoints,\n                params.camera.intrinsics, params.camera.distortion,\n                localRvec, localTvec,\n                localRvec2, localTvec2,\n                params.camera.shutter, params.camera.scanlines,\n                params.useExtrinsicGuess, params.flags);\n\n\n            vector<Point2f> projected_points = project3dPoints(objectPoints, imagePoints, params, localRvec, localTvec, localRvec2, localTvec2);\n            for (int i = 0; i < objectPoints.cols; i++) {\n                Point2f p(imagePoints.at<Vec2f>(0, i));\n                if ((norm(p - projected_points[i]) < params.reprojectionError)) {\n                    localInliers.push_back(i);\n                }\n            }\n\n            if (localInliers.size() > inliers.size())\n            {\n              cout << localInliers.size() << \"/\" << objectPoints.cols << endl;\n              resultsMutex.lock();\n\n              inliers.clear();\n              inliers.resize(localInliers.size());\n              memcpy(&inliers[0], &localInliers[0], sizeof(int) * localInliers.size());\n              localRvec.copyTo(rvec);\n              localTvec.copyTo(tvec);\n              localRvec2.copyTo(rvec2);\n              localTvec2.copyTo(tvec2);\n\n              resultsMutex.unlock();\n            }\n        }\n\n        class PnPSolver\n        {\n        public:\n            void operator()( const BlockedRange& r ) const\n            {\n                vector<char> pointsMask(objectPoints.cols, 0);\n                memset(&pointsMask[0], 1, parameters.min_points_count );\n                for( int i=r.begin(); i!=r.end(); ++i )\n                {\n                    generateVar(pointsMask);\n                    pnpTask(pointsMask, objectPoints, imagePoints, parameters,\n                            inliers, rvec, tvec, rvec2, tvec2,\n                            initRvec, initTvec, initRvec2, initTvec2, syncMutex);\n\n                    if ((int)inliers.size() >= parameters.minInliersCount)\n                    {\n#ifdef HAVE_TBB\n                        tbb::task::self().cancel_group_execution();\n#else\n                        break;\n#endif\n                    }\n                }\n            }\n\n            PnPSolver(const Mat& _objectPoints, const Mat& _imagePoints, const Parameters& _parameters,\n                Mat& _rvec, Mat& _tvec, Mat& _rvec2,\n                Mat& _tvec2, vector<int>& _inliers):\n            objectPoints(_objectPoints), imagePoints(_imagePoints), parameters(_parameters),\n            rvec(_rvec), tvec(_tvec), rvec2(_rvec2), tvec2(_tvec2), inliers(_inliers)\n            {\n              rvec.copyTo(initRvec);\n              tvec.copyTo(initTvec);\n              rvec2.copyTo(initRvec2);\n              tvec2.copyTo(initTvec2);\n\n              generator.state = theRNG().state; //to control it somehow...\n            }\n\n        private:\n            PnPSolver& operator=(const PnPSolver&);\n\n            const Mat& objectPoints;\n            const Mat& imagePoints;\n            const Parameters& parameters;\n            Mat &rvec, &tvec;\n            Mat &rvec2, &tvec2;\n            vector<int>& inliers;\n            Mat initRvec, initTvec;\n            Mat initRvec2, initTvec2;\n\n            static RNG generator;\n            static Mutex syncMutex;\n\n            void generateVar(vector<char>& mask) const\n            {\n                int size = (int)mask.size();\n                for (int i = 0; i < size; i++)\n                {\n                    int i1 = generator.uniform(0, size);\n                    int i2 = generator.uniform(0, size);\n                    char curr = mask[i1];\n                    mask[i1] = mask[i2];\n                    mask[i2] = curr;\n                }\n            }\n        };\n\n        Mutex PnPSolver::syncMutex;\n        RNG PnPSolver::generator;\n\n    }\n}\n\n\n\nvoid vision::solveRsPnPRansac(InputArray _opoints, InputArray _ipoints,\n                        InputArray _cameraMatrix, InputArray _distCoeffs,\n                        OutputArray _rvec, OutputArray _tvec,\n                        OutputArray _rvec2, OutputArray _tvec2,\n                        const SHUTTER shutter, const int scanlines[2],\n                        bool useExtrinsicGuess, int iterationsCount,\n                        float reprojectionError, int minInliersCount,\n                        OutputArray _inliers, int flags, int min_points_count)\n{\n  //boost::timer::auto_cpu_timer btimer;\n\n    Mat opoints = _opoints.getMat(), ipoints = _ipoints.getMat();\n    Mat cameraMatrix = _cameraMatrix.getMat(), distCoeffs = _distCoeffs.getMat();\n\n    CV_Assert(opoints.isContinuous());\n    CV_Assert(opoints.depth() == CV_32F);\n    CV_Assert((opoints.rows == 1 && opoints.channels() == 3) || opoints.cols*opoints.channels() == 3);\n    CV_Assert(ipoints.isContinuous());\n    CV_Assert(ipoints.depth() == CV_32F);\n    CV_Assert((ipoints.rows == 1 && ipoints.channels() == 2) || ipoints.cols*ipoints.channels() == 2);\n\n    _rvec.create(3, 1, CV_64FC1);\n    _tvec.create(3, 1, CV_64FC1);\n    _rvec2.create(3, 1, CV_64FC1);\n    _tvec2.create(3, 1, CV_64FC1);\n    Mat rvec = _rvec.getMat();\n    Mat tvec = _tvec.getMat();\n    Mat rvec2 = _rvec2.getMat();\n    Mat tvec2 = _tvec2.getMat();\n\n    if (cv::norm(rvec, NORM_L1) + cv::norm(tvec, NORM_L1) +\n        cv::norm(rvec2, NORM_L1) + cv::norm(tvec2, NORM_L1) == 0) {\n      cv::Mat gs_inliers;\n      solvePnPRansac(opoints, ipoints, cameraMatrix, distCoeffs, rvec, tvec,\n                     useExtrinsicGuess, iterationsCount, reprojectionError*2,\n                     minInliersCount, gs_inliers, flags);\n\n      if (gs_inliers.rows > 4)\n      { // GS Init\n        rvec.copyTo(rvec2);\n        tvec.copyTo(tvec2);\n        std::cout << \"GS PnP Init: \" << rvec << tvec << endl;\n      }\n    }\n\n    Mat objectPoints = opoints.reshape(3, 1), imagePoints = ipoints.reshape(2, 1);\n\n    if (minInliersCount <= 0)\n        minInliersCount = objectPoints.cols;\n    pnpransac::Parameters params;\n    params.iterationsCount = iterationsCount;\n    params.minInliersCount = minInliersCount;\n    params.reprojectionError = reprojectionError;\n    params.useExtrinsicGuess = useExtrinsicGuess;\n    params.camera.init(cameraMatrix, distCoeffs, shutter, scanlines);\n    params.flags = flags;\n    params.min_points_count = min_points_count;\n\n    vector<int> localInliers;\n    Mat localRvec, localTvec;\n    Mat localRvec2, localTvec2;\n    rvec.copyTo(localRvec);\n    tvec.copyTo(localTvec);\n    rvec2.copyTo(localRvec2);\n    tvec2.copyTo(localTvec2);\n\n    if (objectPoints.cols >= params.min_points_count)\n    {\n        cv::parallel_for(BlockedRange(0,iterationsCount),\n            pnpransac::PnPSolver(objectPoints, imagePoints, params,\n                localRvec, localTvec, localRvec2, localTvec2, localInliers));\n    }\n\n    if (localInliers.size() >= (size_t)params.min_points_count)\n    {\n        if (flags != CV_P3P)\n        {\n            int i, pointsCount = (int)localInliers.size();\n            Mat inlierObjectPoints(1, pointsCount, CV_32FC3), inlierImagePoints(1, pointsCount, CV_32FC2);\n            for (i = 0; i < pointsCount; i++)\n            {\n                int index = localInliers[i];\n                Mat colInlierImagePoints = inlierImagePoints(Rect(i, 0, 1, 1));\n                imagePoints.col(index).copyTo(colInlierImagePoints);\n                Mat colInlierObjectPoints = inlierObjectPoints(Rect(i, 0, 1, 1));\n                objectPoints.col(index).copyTo(colInlierObjectPoints);\n            }\n            vision::solveRsPnP(inlierObjectPoints, inlierImagePoints,\n                params.camera.intrinsics, params.camera.distortion,\n                localRvec, localTvec,\n                localRvec2, localTvec2,\n                shutter, scanlines,\n                true, flags);\n        }\n        localRvec.copyTo(rvec);\n        localTvec.copyTo(tvec);\n        localRvec2.copyTo(rvec2);\n        localTvec2.copyTo(tvec2);\n        if (_inliers.needed())\n            Mat(localInliers).copyTo(_inliers);\n    }\n    else\n    {\n      tvec.setTo(Scalar(0));\n      tvec2.setTo(Scalar(0));\n      Mat R = Mat::eye(3, 3, CV_64F);\n      Rodrigues(R, rvec);\n      Rodrigues(R, rvec2);\n      if ( _inliers.needed() ) _inliers.release();\n    }\n    return;\n}\n\n", "meta": {"hexsha": "0519a9e694629f6a4c1eef13a705cc33d7525e79", "size": 18852, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/rsba/solveRSpnp.cpp", "max_stars_repo_name": "henrique/rsba", "max_stars_repo_head_hexsha": "9b05416abd2800b2d7a5e3400ddee82b93690a66", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 48.0, "max_stars_repo_stars_event_min_datetime": "2015-06-21T03:42:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T12:52:06.000Z", "max_issues_repo_path": "src/rsba/solveRSpnp.cpp", "max_issues_repo_name": "nemo110110/rsba", "max_issues_repo_head_hexsha": "9b05416abd2800b2d7a5e3400ddee82b93690a66", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-05-08T20:52:25.000Z", "max_issues_repo_issues_event_max_datetime": "2017-05-08T20:52:25.000Z", "max_forks_repo_path": "src/rsba/solveRSpnp.cpp", "max_forks_repo_name": "nemo110110/rsba", "max_forks_repo_head_hexsha": "9b05416abd2800b2d7a5e3400ddee82b93690a66", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-08-24T09:33:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-13T12:57:51.000Z", "avg_line_length": 35.8403041825, "max_line_length": 144, "alphanum_fraction": 0.5691703798, "num_tokens": 5018, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911057, "lm_q2_score": 0.6224593171945416, "lm_q1q2_score": 0.4752375754514779}}
{"text": "#include <Eigen/Core>\n#include <Eigen/SparseCore>\n#include <iostream>\n#include <random> // Requires C++ 11\n\n#include <SymEigsSolver.h>\n#include <MatOp/DenseSymMatProd.h>\n#include <MatOp/SparseSymMatProd.h>\n\nusing namespace Spectra;\n\n#define CATCH_CONFIG_MAIN\n#include \"catch.hpp\"\n\ntypedef Eigen::MatrixXd Matrix;\ntypedef Eigen::VectorXd Vector;\ntypedef Eigen::SparseMatrix<double> SpMatrix;\n\n// Traits to obtain operation type from matrix type\ntemplate <typename MatType>\nstruct OpTypeTrait\n{\n    typedef DenseSymMatProd<double> OpType;\n};\n\ntemplate <>\nstruct OpTypeTrait<SpMatrix>\n{\n    typedef SparseSymMatProd<double> OpType;\n};\n\n// Generate random sparse matrix\nSpMatrix sprand(int size, double prob = 0.5)\n{\n    SpMatrix mat(size, size);\n    std::default_random_engine gen;\n    gen.seed(0);\n    std::uniform_real_distribution<double> distr(-1.0, 1.0);\n    for(int i = 0; i < size; i++)\n    {\n        for(int j = 0; j < size; j++)\n        {\n            if(distr(gen) < prob)\n                mat.insert(i, j) = distr(gen);\n        }\n    }\n    return mat;\n}\n\n\ntemplate <typename MatType, int SelectionRule>\nvoid run_test(const MatType& mat, int k, int m)\n{\n    typename OpTypeTrait<MatType>::OpType op(mat);\n    SymEigsSolver<double, SelectionRule, typename OpTypeTrait<MatType>::OpType>\n        eigs(&op, k, m);\n    eigs.init();\n    int nconv = eigs.compute();\n    int niter = eigs.num_iterations();\n    int nops  = eigs.num_operations();\n\n    INFO( \"nconv = \" << nconv );\n    INFO( \"niter = \" << niter );\n    INFO( \"nops  = \" << nops  );\n    REQUIRE( eigs.info() == SUCCESSFUL );\n\n    Vector evals = eigs.eigenvalues();\n    Matrix evecs = eigs.eigenvectors();\n\n    Matrix resid = mat.template selfadjointView<Eigen::Lower>() * evecs - evecs * evals.asDiagonal();\n    const double err = resid.array().abs().maxCoeff();\n\n    INFO( \"||AU - UD||_inf = \" << err );\n    REQUIRE( err == Approx(0.0) );\n}\n\ntemplate <typename MatType>\nvoid run_test_sets(const MatType& mat, int k, int m)\n{\n    SECTION( \"Largest Magnitude\" )\n    {\n        run_test<MatType, LARGEST_MAGN>(mat, k, m);\n    }\n    SECTION( \"Largest Value\" )\n    {\n        run_test<MatType, LARGEST_ALGE>(mat, k, m);\n    }\n    SECTION( \"Smallest Magnitude\" )\n    {\n        run_test<MatType, SMALLEST_MAGN>(mat, k, m);\n    }\n    SECTION( \"Smallest Value\" )\n    {\n        run_test<MatType, SMALLEST_ALGE>(mat, k, m);\n    }\n    SECTION( \"Both Ends\" )\n    {\n        run_test<MatType, BOTH_ENDS>(mat, k, m);\n    }\n}\n\nTEST_CASE(\"Eigensolver of symmetric real matrix [10x10]\", \"[eigs_sym]\")\n{\n    std::srand(123);\n\n    const Matrix A = Eigen::MatrixXd::Random(10, 10);\n    const Matrix M = A + A.transpose();\n    int k = 3;\n    int m = 6;\n\n    run_test_sets(M, k, m);\n}\n\nTEST_CASE(\"Eigensolver of symmetric real matrix [100x100]\", \"[eigs_sym]\")\n{\n    std::srand(123);\n\n    const Matrix A = Eigen::MatrixXd::Random(100, 100);\n    const Matrix M = A + A.transpose();\n    int k = 10;\n    int m = 20;\n\n    run_test_sets(M, k, m);\n}\n\nTEST_CASE(\"Eigensolver of symmetric real matrix [1000x1000]\", \"[eigs_sym]\")\n{\n    std::srand(123);\n\n    const Matrix A = Eigen::MatrixXd::Random(1000, 1000);\n    const Matrix M = A + A.transpose();\n    int k = 20;\n    int m = 50;\n\n    run_test_sets(M, k, m);\n}\n\nTEST_CASE(\"Eigensolver of sparse symmetric real matrix [10x10]\", \"[eigs_sym]\")\n{\n    std::srand(123);\n\n    // Eigen solver only uses the lower triangle\n    const SpMatrix M = sprand(10, 0.5);\n    int k = 3;\n    int m = 6;\n\n    run_test_sets(M, k, m);\n}\n\nTEST_CASE(\"Eigensolver of sparse symmetric real matrix [100x100]\", \"[eigs_sym]\")\n{\n    std::srand(123);\n\n    // Eigen solver only uses the lower triangle\n    const SpMatrix M = sprand(100, 0.5);\n    int k = 10;\n    int m = 20;\n\n    run_test_sets(M, k, m);\n}\n\nTEST_CASE(\"Eigensolver of sparse symmetric real matrix [1000x1000]\", \"[eigs_sym]\")\n{\n    std::srand(123);\n\n    // Eigen solver only uses the lower triangle\n    const SpMatrix M = sprand(1000, 0.5);\n    int k = 20;\n    int m = 50;\n\n    run_test_sets(M, k, m);\n}\n", "meta": {"hexsha": "9871d78f6c8909e553545969a62b33eec29ec968", "size": 4014, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "MPSSC/SIMLR/MATLAB/External/spectra-master/test/SymEigs.cpp", "max_stars_repo_name": "ishspsy/project", "max_stars_repo_head_hexsha": "704804ccba0f65ea07735676f2d61a54b09e138c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2017-07-25T18:04:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-24T02:27:16.000Z", "max_issues_repo_path": "Other_functions/SIMLR/External/spectra-master/test/SymEigs.cpp", "max_issues_repo_name": "ishspsy/MKerW-A", "max_issues_repo_head_hexsha": "84547f79bf8f33dda0ee4d913a85d82ff5dc433e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2021-05-15T13:55:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-19T21:41:34.000Z", "max_forks_repo_path": "MPSSC/SIMLR/MATLAB/External/spectra-master/test/SymEigs.cpp", "max_forks_repo_name": "zhengzhongpku/project", "max_forks_repo_head_hexsha": "704804ccba0f65ea07735676f2d61a54b09e138c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2018-02-13T06:25:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-13T14:00:16.000Z", "avg_line_length": 23.2023121387, "max_line_length": 101, "alphanum_fraction": 0.6225710015, "num_tokens": 1203, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.47522712927439936}}
{"text": "#include <engine/Neighbours.hpp>\r\n\r\n#include <Eigen/Dense>\r\n\r\nnamespace Engine\r\n{\r\n    namespace Neighbours\r\n    {\r\n        std::vector<scalar> Get_Shell_Radius(const Data::Geometry & geometry, const int n_shells)\r\n        {\r\n            const scalar shell_width = 1e-3;\r\n            auto shell_radius = std::vector<scalar>(n_shells);\r\n\r\n            Vector3 a = geometry.bravais_vectors[0];\r\n            Vector3 b = geometry.bravais_vectors[1];\r\n            Vector3 c = geometry.bravais_vectors[2];\r\n\r\n            // The n_shells + 2 is a value that is big enough by experience to \r\n            // produce enough needed shells, but is small enough to run sufficiently fast\r\n            int tMax = n_shells + 2;\r\n            int imax = std::min(tMax, geometry.n_cells[0]-1),\r\n                jmax = std::min(tMax, geometry.n_cells[1]-1),\r\n                kmax = std::min(tMax, geometry.n_cells[2]-1);\r\n\r\n            // Abort condidions for all 3 vectors\r\n            if (a.norm() == 0.0) imax = 0;\r\n            if (b.norm() == 0.0) jmax = 0;\r\n            if (c.norm() == 0.0) kmax = 0;\r\n\r\n            int i, j, k, iatom, jatom, ishell;\r\n            scalar current_radius=0, dx, min_distance=0;\r\n            Vector3 x0={0,0,0}, x1={0,0,0};\r\n            for (ishell = 0; ishell < n_shells; ++ishell)\r\n            {\r\n                min_distance = current_radius;\r\n                current_radius = 1e10;\r\n                for (iatom = 0; iatom < geometry.n_cell_atoms; ++iatom)\r\n                {\r\n                    x0 =  geometry.cell_atoms[iatom][0] * a\r\n                        + geometry.cell_atoms[iatom][1] * b\r\n                        + geometry.cell_atoms[iatom][2] * c;\r\n                    // Note: due to symmetry we only need to check half the space\r\n                    for (i = imax; i >= 0; --i)\r\n                    {\r\n                        for (j = jmax; j >= -jmax; --j)\r\n                        {\r\n                            for (k = kmax; k >= -kmax; --k)\r\n                            {\r\n                                for (jatom = 0; jatom < geometry.n_cell_atoms; ++jatom)\r\n                                {\r\n                                    if ( !( iatom==jatom && i==0 && j==0 && k==0 ) )\r\n                                    {\r\n                                        x1 =  geometry.cell_atoms[jatom][0] * a\r\n                                            + geometry.cell_atoms[jatom][1] * b\r\n                                            + geometry.cell_atoms[jatom][2] * c\r\n                                            + i*a + j*b + k*c;\r\n                                        dx = (x0-x1).norm();\r\n                                        if (dx - min_distance > shell_width && dx < current_radius)\r\n                                        {\r\n                                            current_radius = dx;\r\n                                            shell_radius[ishell] = dx;\r\n                                        }\r\n                                    }\r\n                                }//endfor jatom\r\n                            }//endfor k\r\n                        }//endfor j\r\n                    }//endfor i\r\n                }//endfor iatom\r\n            }\r\n\r\n            return shell_radius;\r\n        }\r\n        \r\n        void Get_Neighbours_in_Shells(const Data::Geometry & geometry, int n_shells, pairfield & neighbours, intfield & shells, bool use_redundant_neighbours)\r\n        {\r\n            const scalar shell_width = 1e-3;\r\n            auto shell_radius = Get_Shell_Radius(geometry, n_shells);\r\n            \r\n            Vector3 a = geometry.bravais_vectors[0];\r\n            Vector3 b = geometry.bravais_vectors[1];\r\n            Vector3 c = geometry.bravais_vectors[2];\r\n\r\n            // The n_shells + 2 is a value that is big enough by experience to \r\n            // produce enough needed shells, but is small enough to run sufficiently fast\r\n            int tMax = n_shells + 2;\r\n            int imax = std::min(tMax, geometry.n_cells[0]-1),\r\n                jmax = std::min(tMax, geometry.n_cells[1]-1),\r\n                kmax = std::min(tMax, geometry.n_cells[2]-1);\r\n            int imin, jmin, kmin, jatommin;\r\n            // If redundant neighbours should not be used, we restrict the search to half of the space\r\n            if( use_redundant_neighbours )\r\n            {\r\n                imin=-imax; jmin=-jmax; kmin=-kmax;\r\n            }\r\n            else\r\n            {\r\n                imin=0; jmin=-jmax; kmin=-kmax;\r\n            }\r\n\r\n            // Abort condidions for all 3 vectors\r\n            if (a.norm() == 0.0) imax = 0;\r\n            if (b.norm() == 0.0) jmax = 0;\r\n            if (c.norm() == 0.0) kmax = 0;\r\n\r\n            int i, j, k, iatom, jatom, ishell;\r\n            scalar dx, radius;\r\n            Vector3 x0={0,0,0}, x1={0,0,0};\r\n            for (iatom = 0; iatom < geometry.n_cell_atoms; ++iatom)\r\n            {\r\n                if( use_redundant_neighbours )\r\n                    jatommin=0;\r\n                else\r\n                    jatommin=iatom;\r\n\r\n                x0 =  geometry.cell_atoms[iatom][0] * a\r\n                    + geometry.cell_atoms[iatom][1] * b\r\n                    + geometry.cell_atoms[iatom][2] * c;\r\n                for (ishell = 0; ishell < n_shells; ++ishell)\r\n                {\r\n                    radius = shell_radius[ishell];\r\n                    for (i = imax; i >= imin; --i)\r\n                    {\r\n                        for (j = jmax; j >= jmin; --j)\r\n                        {\r\n                            for (k = kmax; k >= kmin; --k)\r\n                            {\r\n                                for (jatom = jatommin; jatom < geometry.n_cell_atoms; ++jatom)\r\n                                {\r\n                                    if ((jatom > iatom) || (i>0 || (i==0 && j>0) || (i==0 && j==0 && k>0)) || use_redundant_neighbours)\r\n                                    {\r\n                                        x1 =  geometry.cell_atoms[jatom][0] * a\r\n                                            + geometry.cell_atoms[jatom][1] * b\r\n                                            + geometry.cell_atoms[jatom][2] * c\r\n                                            + i*a + j*b + k*c;\r\n                                        dx = (x0-x1).norm();\r\n                                        if (std::abs(dx - radius) < shell_width)\r\n                                        {\r\n                                            Pair neigh;\r\n                                            neigh.i = iatom;\r\n                                            neigh.j = jatom;\r\n                                            neigh.translations[0] = i;\r\n                                            neigh.translations[1] = j;\r\n                                            neigh.translations[2] = k;\r\n                                            neighbours.push_back( neigh );\r\n                                            shells.push_back(ishell);\r\n                                        }\r\n                                    }\r\n                                }//endfor jatom\r\n                            }//endfor k\r\n                        }//endfor j\r\n                    }//endfor i\r\n                }//endfor ishell\r\n            }//endfor iatom\r\n        }\r\n\r\n\r\n        pairfield Get_Pairs_in_Radius(const Data::Geometry & geometry, scalar radius)\r\n        {\r\n            auto pairs = pairfield(0);\r\n\r\n            if (radius > 1e-6)\r\n            {\r\n                Vector3 a = geometry.bravais_vectors[0];\r\n                Vector3 b = geometry.bravais_vectors[1];\r\n                Vector3 c = geometry.bravais_vectors[2];\r\n\r\n                Vector3 bounds_diff = geometry.bounds_max - geometry.bounds_min;\r\n                Vector3 ratio = {\r\n                    bounds_diff[0]/std::max(1, geometry.n_cells[0]),\r\n                    bounds_diff[1]/std::max(1, geometry.n_cells[1]),\r\n                    bounds_diff[2]/std::max(1, geometry.n_cells[2]) };\r\n\r\n                // This should give enough translations to contain all DDI pairs\r\n                int imax = 0, jmax = 0, kmax = 0;\r\n                if ( bounds_diff[0] > 0 )\r\n                    imax = std::min(geometry.n_cells[0], (int)(1.1 * radius * geometry.n_cells[0] / bounds_diff[0]));\r\n                if ( bounds_diff[1] > 0 )\r\n                    jmax = std::min(geometry.n_cells[1], (int)(1.1 * radius * geometry.n_cells[1] / bounds_diff[1]));\r\n                if ( bounds_diff[2] > 0 )\r\n                    kmax = std::min(geometry.n_cells[2], (int)(1.1 * radius * geometry.n_cells[2] / bounds_diff[2]));\r\n\r\n                int i,j,k;\r\n                scalar dx;\r\n                Vector3 x0={0,0,0}, x1={0,0,0};\r\n\r\n                // Abort condidions for all 3 vectors\r\n                if (a.norm() == 0.0) imax = 0;\r\n                if (b.norm() == 0.0) jmax = 0;\r\n                if (c.norm() == 0.0) kmax = 0;\r\n\r\n                for (int iatom = 0; iatom < geometry.n_cell_atoms; ++iatom)\r\n                {\r\n                    x0 = geometry.cell_atoms[iatom];\r\n                    for (i = imax; i >= -imax; --i)\r\n                    {\r\n                        for (j = jmax; j >= -jmax; --j)\r\n                        {\r\n                            for (k = kmax; k >= -kmax; --k)\r\n                            {\r\n                                for (int jatom = 0; jatom < geometry.n_cell_atoms; ++jatom)\r\n                                {\r\n                                    x1 = geometry.cell_atoms[jatom] + i*a + j*b + k*c;\r\n                                    dx = (x0-x1).norm();\r\n                                    if (dx < radius)\r\n                                    {\r\n                                        pairs.push_back( {iatom, jatom, {i, j, k} } );\r\n                                    }\r\n                                }//endfor jatom\r\n                            }//endfor k\r\n                        }//endfor j\r\n                    }//endfor i\r\n                }//endfor iatom\r\n            }\r\n\r\n            return pairs;\r\n        }\r\n\r\n        Vector3 DMI_Normal_from_Pair(const Data::Geometry & geometry, const Pair & pair, int chirality)\r\n        {\r\n            Vector3 ta = geometry.bravais_vectors[0];\r\n            Vector3 tb = geometry.bravais_vectors[1];\r\n            Vector3 tc = geometry.bravais_vectors[2];\r\n\r\n            int da = pair.translations[0];\r\n            int db = pair.translations[1];\r\n            int dc = pair.translations[2];\r\n\r\n            Vector3 ipos = geometry.cell_atoms[pair.i];\r\n            Vector3 jpos = geometry.cell_atoms[pair.j] + da*ta + db*tb + dc*tc;\r\n\r\n            if (chirality == 1)\r\n            {\r\n                // Bloch chirality\r\n                return (jpos - ipos).normalized();\r\n            }\r\n            else if (chirality == -1)\r\n            {\r\n                // Inverse Bloch chirality\r\n                return (ipos - jpos).normalized();\r\n            }\r\n            else if (chirality == 2)\r\n            {\r\n                // Neel chirality (surface)\r\n                return (jpos - ipos).normalized().cross(Vector3{0,0,1});\r\n            }\r\n            else if (chirality == -2)\r\n            {\r\n                // Inverse Neel chirality (surface)\r\n                return Vector3{0,0,1}.cross((jpos - ipos).normalized());\r\n            }\r\n            else\r\n            {\r\n                return Vector3{ 0,0,0 };\r\n            }\r\n        }\r\n\r\n        void DDI_from_Pair(const Data::Geometry & geometry, const Pair & pair, scalar & magnitude, Vector3 & normal)\r\n        {\r\n            Vector3 ta = geometry.bravais_vectors[0];\r\n            Vector3 tb = geometry.bravais_vectors[1];\r\n            Vector3 tc = geometry.bravais_vectors[2];\r\n\r\n            int da = pair.translations[0];\r\n            int db = pair.translations[1];\r\n            int dc = pair.translations[2];\r\n\r\n            Vector3 ipos = geometry.cell_atoms[pair.i];\r\n            Vector3 jpos = geometry.cell_atoms[pair.j] + da*ta + db*tb + dc*tc;\r\n\r\n            // Calculate positions and difference vector\r\n            Vector3 vector_ij = jpos - ipos;\r\n\r\n            // Length of difference vector\r\n            magnitude = vector_ij.norm();\r\n            normal = vector_ij.normalized();\r\n        }\r\n\r\n    }// end Namespace Neighbours\r\n}// end Namespace Engine\r\n", "meta": {"hexsha": "f1698c00ee6e2c39574c1bbcf6d0faf24eff29af", "size": 12261, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "core/src/engine/Neighbours.cpp", "max_stars_repo_name": "Zeleznyj/spirit", "max_stars_repo_head_hexsha": "5e23bf3be5aa4bacf5aae24514b0b22cbd395619", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "core/src/engine/Neighbours.cpp", "max_issues_repo_name": "Zeleznyj/spirit", "max_issues_repo_head_hexsha": "5e23bf3be5aa4bacf5aae24514b0b22cbd395619", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "core/src/engine/Neighbours.cpp", "max_forks_repo_name": "Zeleznyj/spirit", "max_forks_repo_head_hexsha": "5e23bf3be5aa4bacf5aae24514b0b22cbd395619", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.7892857143, "max_line_length": 159, "alphanum_fraction": 0.3984993067, "num_tokens": 2716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.4752271292743993}}
{"text": "/**\n * Copyright (c) 2017 Melown Technologies SE\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * *  Redistributions of source code must retain the above copyright notice,\n *    this list of conditions and the following disclaimer.\n *\n * *  Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in the\n *    documentation and/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * @file math.hpp\n * @author Ondrej Prochazka <ondrej.prochazka@citationtech.net>\n *\n * Low level math helper functions\n */\n      \n#ifndef MATH_MATH_HPP\n#define MATH_MATH_HPP\n\n#include <algorithm>\n#include <stdexcept>\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\n#include \"dbglog/dbglog.hpp\"\n\n\nnamespace math {\n\nnamespace ublas = boost::numeric::ublas;\n\n/** square function */\ntemplate <typename T>\nT sqr( T val ) { return val * val; }\n\nnamespace detail {\n\n// enabled for N == 1\ntemplate<int N, typename T>\ntypename std::enable_if<N == 1, T>::type pow( T value ) {\n    return value;\n}\n// enabled for even N\ntemplate<int N, typename T>\ntypename std::enable_if<(N > 1) && (N & 1) == 0, T>::type pow( T value ) {\n    return pow<N/2>(value * value);\n}\n// enabled for odd N\ntemplate<int N, typename T>\ntypename std::enable_if<(N > 1) && (N & 1) == 1, T>::type pow( T value ) {\n    return pow<N/2>(value * value) * value;\n}\n\n} // namespace detail\n\n/** Power function with integer compile-time exponent */\ntemplate<int N, typename T>\nT pow( T value ) {\n    return detail::pow<N>(value);\n}\n\n/** even and odd */\n\ntemplate <typename T>\nbool even( T val ) { return ( val >> 1 << 1 == val ); }\n\ntemplate <typename T>\nbool odd( T val ) { return ( val >> 1 << 1 != val ); }\n\n\n/** interval check */\n\ntemplate<typename T>\nbool ccinterval( const T & lb, const T  & ub, const T & value ) {\n    return ( lb <= value && value <= ub );\n}\n    \n\n/**\n  * Signum function\n  */\n  \ntemplate <typename Value_t>\nint sgn( const Value_t & value ) {\n   if ( value > 0 ) return 1;\n   if ( value < 0 ) return -1;\n   return 0;\n}\n\n/** Clamp value to given range.\n */\ntemplate <typename T>\ninline T clamp(T value, T min, T max)\n{\n    return std::max(min, std::min(value, max));\n}\n\ntemplate <typename T>\ninline bool isInteger(T value, T tolerance = T(0))\n{\n    T integer;\n    return (std::abs(std::modf(value, &integer)) <= tolerance);\n}\n\n/**\n  * Matrix inversion\n  */\n\ntemplate <typename T, typename L, typename C>\nublas::matrix<T,L,C> matrixInvert( const ublas::matrix<T,L,C> & input ) {\n\n    typedef ublas::permutation_matrix<std::size_t> pmatrix;\n\n    // create a working copy of the input\n    ublas::matrix<T,L,C> A(input);\n\n    // create a permutation matrix for the LU-factorization\n    pmatrix pm(A.size1());\n\n    // perform LU-factorization\n    auto res = lu_factorize(A,pm);\n    if( res != 0 ) {\n        LOGTHROW(warn1, std::runtime_error)\n            << \"Singular matrix in math::matrixInvert. Aborting.\";\n    }\n\n    // create identity matrix of \"inverse\"\n    ublas::matrix<T,L,C> inverse = ublas::identity_matrix<T>(A.size1());\n\n    // backsubstitute to get the inverse\n    lu_substitute(A, pm, inverse);\n    return inverse;\n}\n\ntemplate <typename T, typename L, typename C>\nbool matrixInvertInplace( ublas::matrix<T,L,C> &input)\n{\n    typedef ublas::permutation_matrix<std::size_t> pmatrix;\n\n    // create a working copy of the input\n    ublas::matrix<T,L,C> A(input);\n\n    // create a permutation matrix for the LU-factorization\n    pmatrix pm(A.size1());\n\n    // perform LU-factorization\n    auto res = lu_factorize(A,pm);\n    if (res != 0) { return false; }\n\n    // backsubstitute to get the inverse\n    lu_substitute(A, pm, input);\n    return true;\n}\n\n\n/**\n * Returns the trace of a square matrix.\n */\ntemplate <class T, class L, class C>\ndouble trace(ublas::matrix<T, L, C> m) {\n    const int n = m.size1();\n    ublas::matrix_vector_range<ublas::matrix<T, L, C>> diag\n            (m, ublas::range(0, n), ublas::range(0, n));\n    return sum(diag);\n}\n\n/**\n * Matrix determinant\n */\n\ntemplate <class matrix_T>\ndouble determinant(ublas::matrix_expression<matrix_T> const& mat_r)\n{\n  double det = 1.0;\n\n  matrix_T mLu(mat_r() );\n  ublas::permutation_matrix<std::size_t> pivots(mat_r().size1() );\n\n  int is_singular = lu_factorize(mLu, pivots);\n\n  if (!is_singular)\n  {\n    for (std::size_t i=0; i < pivots.size(); ++i)\n    {\n      if (pivots(i) != i)\n        det *= -1.0;\n\n      det *= mLu(i,i);\n    }\n  }\n  else\n    det = 0.0;\n\n  return det;\n} \n\n\n/**\n * Solve a 2x2 linear system\n */\ntemplate<typename MatrixType, typename VectorType>\nvoid solve2x2(const MatrixType &mat, const VectorType &rhs, VectorType &result)\n{\n    double det = mat(0,0)*mat(1,1) - mat(0,1)*mat(1,0);\n\n    // check the determinant\n    if (std::abs(det) < 1e-14) {\n        LOGTHROW(err1, std::runtime_error) << \"Singular matrix in solve2x2.\";\n    }\n\n    det = 1.0 / det;\n    result(0) = (rhs(0)*mat(1,1) - mat(0,1)*rhs(1)) * det;\n    result(1) = (mat(0,0)*rhs(1) - rhs(0)*mat(1,0)) * det;\n}\n\n                                                                               \n} // namespace math\n\n#endif // MATH_MATH_HPP\n      \n", "meta": {"hexsha": "695f312e120d442e4e3f5624e1a27647f35efc64", "size": 6247, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "externals/browser/externals/browser/externals/libmath/math/math.hpp", "max_stars_repo_name": "HanochZhu/vts-browser-unity-plugin", "max_stars_repo_head_hexsha": "32a22d41e21b95fb015326f95e401d87756d0374", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-02T08:42:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-02T08:42:59.000Z", "max_issues_repo_path": "externals/browser/externals/browser/externals/libmath/math/math.hpp", "max_issues_repo_name": "HanochZhu/vts-browser-unity-plugin", "max_issues_repo_head_hexsha": "32a22d41e21b95fb015326f95e401d87756d0374", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "externals/browser/externals/browser/externals/libmath/math/math.hpp", "max_forks_repo_name": "HanochZhu/vts-browser-unity-plugin", "max_forks_repo_head_hexsha": "32a22d41e21b95fb015326f95e401d87756d0374", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.8140495868, "max_line_length": 79, "alphanum_fraction": 0.6511925724, "num_tokens": 1707, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.47522712296625236}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#include \"Domain/CoordinateMaps/CubicScale.hpp\"\n\n#include <array>\n#include <boost/none.hpp>\n#include <ostream>\n#include <pup.h>\n#include <pup_stl.h>\n#include <utility>\n\n#include \"ControlSystem/FunctionOfTime.hpp\"\n#include \"DataStructures/DataVector.hpp\"\n#include \"DataStructures/Tensor/Tensor.hpp\"\n#include \"ErrorHandling/Error.hpp\"\n#include \"NumericalAlgorithms/RootFinding/NewtonRaphson.hpp\"\n#include \"Utilities/ConstantExpressions.hpp\"\n#include \"Utilities/DereferenceWrapper.hpp\"\n#include \"Utilities/GenerateInstantiations.hpp\"\n#include \"Utilities/MakeWithValue.hpp\"\n\nnamespace CoordMapsTimeDependent {\n\nCubicScale::CubicScale(const double outer_boundary) noexcept\n    : outer_boundary_(outer_boundary) {\n  if (outer_boundary_ <= 0.0) {\n    ERROR(\"For invertability, we require outer_boundary to be positive.\\n\");\n  }\n}\n\ntemplate <typename T>\nstd::array<tt::remove_cvref_wrap_t<T>, 1> CubicScale::operator()(\n    const std::array<T, 1>& source_coords, const double time,\n    const std::unordered_map<std::string, FunctionOfTime&>& map_list) const\n    noexcept {\n  const auto a_of_t = map_list.at(f_of_t_a_).func(time)[0][0];\n  const auto b_of_t = map_list.at(f_of_t_b_).func(time)[0][0];\n  return {{source_coords[0] *\n           (a_of_t +\n            (b_of_t - a_of_t) * square(source_coords[0] / outer_boundary_))}};\n}\n\ntemplate <typename T>\nboost::optional<std::array<tt::remove_cvref_wrap_t<T>, 1>> CubicScale::inverse(\n    const std::array<T, 1>& target_coords, const double time,\n    const std::unordered_map<std::string, FunctionOfTime&>& map_list) const\n    noexcept {\n  // the original coordinates are found by solving for the roots\n  // of (b-a)/X^2*\\xi^3 + a*\\xi - x = 0, where a and b are the FunctionsOfTime,\n  // X is the outer_boundary, and x represents the mapped coordinates\n  const auto a_of_t = map_list.at(f_of_t_a_).func(time)[0][0];\n  const auto b_of_t = map_list.at(f_of_t_b_).func(time)[0][0];\n\n  // these checks ensure that the function is monotonically increasing\n  // and that there is one real root in the domain of \\xi, [0,X]\n  if (a_of_t <= 0.0) {\n    ERROR(\"We require expansion_a > 0 for invertibility, however expansion_a = \"\n          << a_of_t << \".\");\n  }\n  if (b_of_t < 2.0 / 3.0 * a_of_t or b_of_t <= 0.0) {\n    ERROR(\"The map is invertible only if 0 < expansion_b < expansion_a*2/3, \"\n          << \" but expansion_b = \" << b_of_t << \" and expansion_a = \" << a_of_t\n          << \".\");\n  }\n\n  // Make the coordinates dimensionless\n  const tt::remove_cvref_wrap_t<T> x_bar = target_coords[0] / outer_boundary_;\n\n  // Check if x_bar is outside of the range of the map\n  if (x_bar < 0.0 or x_bar > b_of_t) {\n    return boost::none;\n  }\n\n  // with the assumptions above:\n  // x_bar lies within the range [0,b]\n  // and \\xi_bar = \\xi/X is restricted to the domain [0,1]\n  // For an initial guess, we provide a linearly approximated solution for\n  // \\xi_bar, which is just x_bar/b.\n  const tt::remove_cvref_wrap_t<T> initial_guess = x_bar / b_of_t;\n  const double cubic_coef_a = (b_of_t - a_of_t);\n\n  const auto cubic_and_deriv =\n      [&cubic_coef_a, &a_of_t, &x_bar ](double x) noexcept {\n    return std::make_pair(x * (cubic_coef_a * square(x) + a_of_t) - x_bar,\n                          3.0 * cubic_coef_a * square(x) + a_of_t);\n  };\n\n  // The original implementation of this inverse function used a cubic\n  // equation solver. However, given that the problem of finding the inverse\n  // in this case is well constrained -- using a Newton-Raphson root find with\n  // a linearly approximated guess is almost twice as fast.\n  // Using google benchmark,\n  // the CubicEquation solver: ~ 480 ns\n  // boost implemented Newton-Raphson: ~ 280 ns\n  // minimal Newton-Raphson from Numerical Recipes: ~ 255 ns\n  // Despite the minimal Newton-Raphson being more efficient than the boost\n  // version, here we utilize the boost implementation, as it includes\n  // additional checks for zero derivative, checks on bounds, and can implement\n  // bisection if necessary.\n  return {\n      {{outer_boundary_ * RootFinder::newton_raphson(\n                              cubic_and_deriv, initial_guess, 0.0, 1.0, 14)}}};\n}\n\ntemplate <typename T>\nstd::array<tt::remove_cvref_wrap_t<T>, 1> CubicScale::frame_velocity(\n    const std::array<T, 1>& source_coords, const double time,\n    const std::unordered_map<std::string, FunctionOfTime&>& map_list) const\n    noexcept {\n  const auto dt_a_of_t = map_list.at(f_of_t_a_).func_and_deriv(time)[1][0];\n  const auto dt_b_of_t = map_list.at(f_of_t_b_).func_and_deriv(time)[1][0];\n  const auto frame_vel =\n      source_coords[0] *\n      (dt_a_of_t +\n       (dt_b_of_t - dt_a_of_t) * square(source_coords[0] / outer_boundary_));\n\n  return {{frame_vel}};\n}\n\ntemplate <typename T>\ntnsr::Ij<tt::remove_cvref_wrap_t<T>, 1, Frame::NoFrame> CubicScale::jacobian(\n    const std::array<T, 1>& source_coords, const double time,\n    const std::unordered_map<std::string, FunctionOfTime&>& map_list) const\n    noexcept {\n  const auto a_of_t = map_list.at(f_of_t_a_).func(time)[0][0];\n  const auto b_of_t = map_list.at(f_of_t_b_).func(time)[0][0];\n  auto jac{\n      make_with_value<tnsr::Ij<tt::remove_cvref_wrap_t<T>, 1, Frame::NoFrame>>(\n          dereference_wrapper(source_coords[0]), 0.0)};\n\n  get<0, 0>(jac) =\n      a_of_t +\n      3.0 * (b_of_t - a_of_t) * square(source_coords[0] / outer_boundary_);\n\n  return jac;\n}\n\ntemplate <typename T>\ntnsr::Ij<tt::remove_cvref_wrap_t<T>, 1, Frame::NoFrame>\nCubicScale::inv_jacobian(\n    const std::array<T, 1>& source_coords, const double time,\n    const std::unordered_map<std::string, FunctionOfTime&>& map_list) const\n    noexcept {\n  const auto a_of_t = map_list.at(f_of_t_a_).func(time)[0][0];\n  const auto b_of_t = map_list.at(f_of_t_b_).func(time)[0][0];\n  auto inv_jac{\n      make_with_value<tnsr::Ij<tt::remove_cvref_wrap_t<T>, 1, Frame::NoFrame>>(\n          dereference_wrapper(source_coords[0]), 0.0)};\n\n  get<0, 0>(inv_jac) = 1.0 / (a_of_t +\n                              3.0 * (b_of_t - a_of_t) *\n                                  square(source_coords[0] / outer_boundary_));\n\n  return inv_jac;\n}\n\ntemplate <typename T>\ntnsr::Iaa<tt::remove_cvref_wrap_t<T>, 1, Frame::NoFrame> CubicScale::hessian(\n    const std::array<T, 1>& source_coords, const double time,\n    const std::unordered_map<std::string, FunctionOfTime&>& map_list) const\n    noexcept {\n  const auto a_of_t_and_derivs = map_list.at(f_of_t_a_).func_and_2_derivs(time);\n  const auto b_of_t_and_derivs = map_list.at(f_of_t_b_).func_and_2_derivs(time);\n\n  auto result{\n      make_with_value<tnsr::Iaa<tt::remove_cvref_wrap_t<T>, 1, Frame::NoFrame>>(\n          dereference_wrapper(source_coords[0]), 0.0)};\n  // time-time\n  get<0, 0, 0>(result) = a_of_t_and_derivs[2][0] * source_coords[0] +\n                         (b_of_t_and_derivs[2][0] - a_of_t_and_derivs[2][0]) *\n                             cube(source_coords[0]) / square(outer_boundary_);\n  // time-space\n  get<0, 0, 1>(result) =\n      a_of_t_and_derivs[1][0] +\n      3.0 * (b_of_t_and_derivs[1][0] - a_of_t_and_derivs[1][0]) *\n          square(source_coords[0] / outer_boundary_);\n  // space-space\n  get<0, 1, 1>(result) = 6.0 *\n                         (b_of_t_and_derivs[0][0] - a_of_t_and_derivs[0][0]) *\n                         source_coords[0] / square(outer_boundary_);\n\n  return result;\n}\n\nvoid CubicScale::pup(PUP::er& p) noexcept {\n  p | f_of_t_a_;\n  p | f_of_t_b_;\n  p | outer_boundary_;\n}\n\nbool operator==(const CoordMapsTimeDependent::CubicScale& lhs,\n                const CoordMapsTimeDependent::CubicScale& rhs) noexcept {\n  return lhs.f_of_t_a_ == rhs.f_of_t_a_ and lhs.f_of_t_b_ == rhs.f_of_t_b_ and\n         lhs.outer_boundary_ == rhs.outer_boundary_;\n}\n\n// Explicit instantiations\n/// \\cond\ntemplate boost::optional<std::array<tt::remove_cvref_wrap_t<double>, 1>>\nCubicScale::inverse(\n    const std::array<double, 1>& target_coords, const double time,\n    const std::unordered_map<std::string, FunctionOfTime&>& map_list) const\n    noexcept;\ntemplate boost::optional<std::array<\n    tt::remove_cvref_wrap_t<std::reference_wrapper<const double>>, 1>>\nCubicScale::inverse(\n    const std::array<std::reference_wrapper<const double>, 1>& target_coords,\n    const double time,\n    const std::unordered_map<std::string, FunctionOfTime&>& map_list) const\n    noexcept;\n\n#define DTYPE(data) BOOST_PP_TUPLE_ELEM(0, data)\n\n#define INSTANTIATE(_, data)                                                   \\\n  template std::array<tt::remove_cvref_wrap_t<DTYPE(data)>, 1> CubicScale::    \\\n  operator()(const std::array<DTYPE(data), 1>& source_coords,                  \\\n             const double time,                                                \\\n             const std::unordered_map<std::string, FunctionOfTime&>& map_list) \\\n      const noexcept;                                                          \\\n  template std::array<tt::remove_cvref_wrap_t<DTYPE(data)>, 1>                 \\\n  CubicScale::frame_velocity(                                                  \\\n      const std::array<DTYPE(data), 1>& source_coords, const double time,      \\\n      const std::unordered_map<std::string, FunctionOfTime&>& map_list)        \\\n      const noexcept;                                                          \\\n  template tnsr::Ij<tt::remove_cvref_wrap_t<DTYPE(data)>, 1, Frame::NoFrame>   \\\n  CubicScale::jacobian(                                                        \\\n      const std::array<DTYPE(data), 1>& source_coords, const double time,      \\\n      const std::unordered_map<std::string, FunctionOfTime&>& map_list)        \\\n      const noexcept;                                                          \\\n  template tnsr::Ij<tt::remove_cvref_wrap_t<DTYPE(data)>, 1, Frame::NoFrame>   \\\n  CubicScale::inv_jacobian(                                                    \\\n      const std::array<DTYPE(data), 1>& source_coords, const double time,      \\\n      const std::unordered_map<std::string, FunctionOfTime&>& map_list)        \\\n      const noexcept;                                                          \\\n  template tnsr::Iaa<tt::remove_cvref_wrap_t<DTYPE(data)>, 1, Frame::NoFrame>  \\\n  CubicScale::hessian(                                                         \\\n      const std::array<DTYPE(data), 1>& source_coords, const double time,      \\\n      const std::unordered_map<std::string, FunctionOfTime&>& map_list)        \\\n      const noexcept;\n\nGENERATE_INSTANTIATIONS(INSTANTIATE, (double, DataVector,\n                                      std::reference_wrapper<const double>,\n                                      std::reference_wrapper<const DataVector>))\n#undef DTYPE\n#undef INSTANTIATE\n/// \\endcond\n}  // namespace CoordMapsTimeDependent\n", "meta": {"hexsha": "2536d539cbdf7a8088f4987105071e6eaf548197", "size": 10777, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Domain/CoordinateMaps/CubicScale.cpp", "max_stars_repo_name": "marissawalker/spectre", "max_stars_repo_head_hexsha": "afc8205e2f697de5e8e4f05e881499e05c9fd8a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Domain/CoordinateMaps/CubicScale.cpp", "max_issues_repo_name": "marissawalker/spectre", "max_issues_repo_head_hexsha": "afc8205e2f697de5e8e4f05e881499e05c9fd8a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Domain/CoordinateMaps/CubicScale.cpp", "max_forks_repo_name": "marissawalker/spectre", "max_forks_repo_head_hexsha": "afc8205e2f697de5e8e4f05e881499e05c9fd8a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.281124498, "max_line_length": 80, "alphanum_fraction": 0.6411802914, "num_tokens": 2937, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568416, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4752271166581052}}
{"text": "#pragma once\n\n#include <route_solver/structs/data_structs.hpp>\n#include <route_solver/solution/truck_solution.hpp>\n\n#include <Eigen/Core>\n\nnamespace rs {\nrs::TruckSolution truckSolve(\n\tconst std::vector<Vehicle>& venchiles,\n\tconst std::vector<rs::Zone>& zones,\n\tconst std::vector<Task>& tasks,\n\tconst Eigen::MatrixXd& destTimeMatrix,\n\tconst Eigen::MatrixXd& getDestMatrix,\n\tconst BeeColonyParams& beeParams,\n\tbool partialSolutionEnabled,\n\trs::Statistics* stat = 0\n);\n\n}\n", "meta": {"hexsha": "82f17e2345eba3d5d7026734d5fdd9c386cf52f1", "size": 470, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/route_solver/include/route_solver/solve/truck_solver.hpp", "max_stars_repo_name": "antlad/route_solver_service", "max_stars_repo_head_hexsha": "a6a24766066e2da734079fb25e216afad72ad14b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-03-28T09:34:22.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-30T16:30:49.000Z", "max_issues_repo_path": "libs/route_solver/include/route_solver/solve/truck_solver.hpp", "max_issues_repo_name": "antlad/route_solver_service", "max_issues_repo_head_hexsha": "a6a24766066e2da734079fb25e216afad72ad14b", "max_issues_repo_licenses": ["MIT"], "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/route_solver/include/route_solver/solve/truck_solver.hpp", "max_forks_repo_name": "antlad/route_solver_service", "max_forks_repo_head_hexsha": "a6a24766066e2da734079fb25e216afad72ad14b", "max_forks_repo_licenses": ["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.380952381, "max_line_length": 51, "alphanum_fraction": 0.7659574468, "num_tokens": 116, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7772998508568416, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4752271166581052}}
{"text": "// Test program for ConvexHull2d class\n//\n// Command line compile options used:\n// Visual Studio 2013: \n//    cl /W4 /O2 /EHsc /Fehull.exe main.cpp\n// Linux (Debian) g++ 4.9.2:\n//    g++ -std=c++11 -Wall -Wextra -pedantic -O2 -o hull main.cpp\n//\n// Usage: \n//    hull [COUNT] [TRUE]\n//\n// Options:\n//    COUNT = number of random points to generate for each test. Defaults to 10\n//    TRUE =  Flag to write data to file and create gnuplot script. You must specify a COUNT to use this flag.\n//            This will create 4 files: dbl_test.dat, dbl_test.gp, int_test.dat, int_test.gp.\n// Examples:\n//    hull  - Generates 10 random integers and doubles with no write to disk.\n//    hull 20  - Generates 20 random integers and doubles with no write to disk.\n//    hull 20 true  - Generates 20 random integers and doubles and creates data file and gnuplot script.\n//\n\n#include \"convexhull2d.h\"\n#include <Eigen/Dense>\n#include <Eigen/StdVector>\n#include <iostream>\n#include <iomanip>\n#include <vector>\n#include <random>\n#include <fstream>\n#include <chrono>\n#include <string>\n#include <limits>\n\n\n\nusing namespace hpm;\nusing namespace Eigen;\nusing Timer = std::chrono::steady_clock;\nusing Duration = std::chrono::duration<double, std::milli>;\nusing DoubleLimit = std::numeric_limits<double>;\nusing IntLimit = std::numeric_limits<int>;\n\ntemplate <typename T>\nstruct Point2d\n{\n  T x;\n  T y;\n};\n\ntemplate <typename T>\nvoid writeData(const std::string& data_file, const std::vector<T>& points, \n               ConvexHull2d<T>& hull, std::vector<std::pair<double, double>> rotated)\n{\n  std::ofstream data(data_file);\n  if (!data.is_open()) return;\n  data << std::setprecision(15);\n  data << \"# Point set\\n\";\n  for (auto i : points) {\n    data << i.x() << \" \" << i.y() << '\\n';\n  }\n\n  data << \"\\n# Centroid\\n\";\n  data << hull.getCentroid().first << ' ' << hull.getCentroid().second << \"\\n\";\n\n  data << \"\\n# Convex hull\\n\";\n  if (!hull.isEmpty()) {\n    for (auto i : hull.getHull()) {\n      data << i.x() << \" \" << i.y() << '\\n';\n    }\n    data << hull.getHull().front().x() << \" \" << hull.getHull().front().y() << '\\n';\n  }\n\n  data << \"\\n# Rotated vertices\\n\";\n  if (!rotated.empty()) {\n    for (auto i : rotated) {\n      data << i.first << \" \" << i.second << '\\n';\n    }\n    data << rotated.front().first << \" \" << rotated.front().second << '\\n';\n  }\n\n}\n\nvoid writeGPScript(const std::string& script, const std::string& data)\n{\n  std::ofstream gp(script);\n  if (!gp.is_open()) return;\n  gp << \"set title \\\"Convex Hull Test\\\"\\n\";\n  gp << \"set key outside right box\\n\";\n  gp << \"set size ratio -1\\n\";\n  gp << \"plot \\\"\" << data << \"\\\" every :::0::0 title \\\"All Points\\\" with points, \\\\\\n\";\n  gp << \"\\\"\\\" every :::1::1 title \\\"Centroid\\\" with points, \\\\\\n\";\n  gp << \"\\\"\\\" every :::2::2 title \\\"Convex Hull\\\" with lp, \\\\\\n\";\n  gp << \"\\\"\\\" every :::3::3 title \\\"Rotated\\\" with lp\\n\";\n  gp << \"\\npause -1\\n\";\n}\n\nint main(int argc, char* argv[])\n{\n  size_t num_points = 10; // Default number of points\n  bool do_write = false; \n\n  if (argc > 1) {\n    int arg1 = std::strtol(argv[1], nullptr, 10);\n    if (arg1 >= 0 && arg1 < IntLimit::max() / 2) {\n      num_points = arg1;\n    }\n    else\n      std::cout << \"\\nInvalid number of points! Defaulting to \" << num_points << \" points per test.\\n\";\n    if (argc > 2) {\n      std::string arg2(argv[2]);\n      std::transform(arg2.begin(), arg2.end(), arg2.begin(), ::toupper);\n      if (arg2 == \"TRUE\") do_write = true;\n    }\n  }\n\n  const int min_int = 0;\n  //const int min_int = IntLimit::min();\n  const int max_int = IntLimit::max();\n  //const double min_double = 0.0;\n  const double min_double = -std::sqrt(std::sqrt(DoubleLimit::max())) * 10e24;\n  const double max_double = std::sqrt(std::sqrt(DoubleLimit::max())) * 10e24;\n\n  std::mt19937 engine;\n  engine.seed(std::random_device{}());\n\n  // Start timer and generate random integers to test\n  auto timer_start = Timer::now();\n  std::vector<Vector2i> int_points(num_points);\n  std::uniform_int_distribution<> int_distribution(min_int, max_int);\n  for (auto& i : int_points) {\n    i.x() = int_distribution(engine);\n    i.y() = int_distribution(engine);\n  }\n\n  // Generate random doubles to test\n  std::vector<Vector2d> double_points(num_points);\n  std::uniform_real_distribution<> double_distribution(min_double, max_double);\n  for (auto& i : double_points) {\n    i.x() = double_distribution(engine);\n    i.y() = double_distribution(engine);\n  }\n  auto random_time = Timer::now() - timer_start;\n\n  // Create hulls\n  auto hull_timer_start = Timer::now();\n  ConvexHull2d<Vector2i> int_hull(int_points);\n  auto int_hull_time = Timer::now() - hull_timer_start;\n\n  ConvexHull2d<Vector2d> double_hull(double_points);\n  auto double_hull_time = Timer::now() - hull_timer_start - int_hull_time;\n  auto hull_time = Timer::now() - hull_timer_start;\n  \n  // Test rotate\n  const double to_radians = acos(-1) / 180.0; \n  std::pair<double, double> centroid = double_hull.getCentroid();\n  std::vector<std::pair<double, double>> double_rotated = double_hull.rotateVertices(-45.0 * to_radians, centroid);\n  std::vector<std::pair<double, double>> int_rotated = int_hull.rotateVertices(45.0 * to_radians);\n\n  if (do_write) {\n    writeData(\"int_test.dat\", int_points, int_hull, int_rotated);\n    writeGPScript(\"int_test.gp\", \"int_test.dat\");\n    writeData(\"dbl_test.dat\", double_points, double_hull, double_rotated);\n    writeGPScript(\"dbl_test.gp\", \"dbl_test.dat\");\n  }\n  auto total_time = Timer::now() - timer_start;\n  auto write_time = total_time - hull_time - random_time;\n\n  std::cout << \"\\nMin int: \" << min_int << '\\n';\n  std::cout << \"Max int: \" << max_int << '\\n';\n  std::cout << \"Min double: \" << min_double << '\\n';\n  std::cout << \"Max double: \" << max_double << '\\n';\n\n  std::cout << \"\\nRandom creation time: \" << Duration(random_time).count() << \" ms\\n\";\n  std::cout << \"Hull creation time: \" << Duration(hull_time).count() << \" ms\\n\";\n  std::cout << \"Write time: \" << Duration(write_time).count() << \" ms\\n\";\n\n  std::cout << \"\\nTotal time: \" << Duration(total_time).count() << \" ms\\n\";\n  std::cout << \"Total points: \" << int_points.size() + double_points.size() << '\\n';\n\n  std::cout << \"\\nInteger hull point count: \" << int_hull.getHull().size() << '\\n';\n  std::cout << \"Integer hull creation time: \" << Duration(int_hull_time).count() << \" ms\\n\";\n  std::cout << \"Integer hull area: \" << int_hull.getArea() << '\\n';\n  std::cout << \"Integer hull is \" << (int_hull.isValid() ? \"valid\\n\" : \"not valid\\n\");\n\n  std::cout << \"\\nDouble hull point count: \" << double_hull.getHull().size() << '\\n';\n  std::cout << \"Double hull creation time: \" << Duration(double_hull_time).count() << \" ms\\n\";\n  std::cout << \"Double hull area: \" << double_hull.getArea() << '\\n';\n  std::cout << \"Double hull is \" << (double_hull.isValid() ? \"valid\\n\" : \"not valid\\n\");\n\n  std::getchar();\n}\n\n", "meta": {"hexsha": "cb1c58c5fd6fa3ac41201a99389a892c05621a97", "size": 6834, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "hull2d/hull.cpp", "max_stars_repo_name": "hpmachining/splines", "max_stars_repo_head_hexsha": "9df0e51eac3169f0f518159752719f3b0fbfdb9c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-07-22T15:29:18.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-04T21:31:33.000Z", "max_issues_repo_path": "hull2d/hull.cpp", "max_issues_repo_name": "hpmachining/splines", "max_issues_repo_head_hexsha": "9df0e51eac3169f0f518159752719f3b0fbfdb9c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hull2d/hull.cpp", "max_forks_repo_name": "hpmachining/splines", "max_forks_repo_head_hexsha": "9df0e51eac3169f0f518159752719f3b0fbfdb9c", "max_forks_repo_licenses": ["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.4093264249, "max_line_length": 115, "alphanum_fraction": 0.6273046532, "num_tokens": 1993, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.4752083579378396}}
{"text": "//-----------------------------------------------------------------------------\n#include <utility>\n#include <iostream>\n#include <iomanip>\n#include <algorithm>\n#include <vector>\n#include <queue>\n#include <set>\n#include <map>\n#include <string>\n#include <cstdio>\n#include <cstdlib>\n#include <cmath>\n#include <cstring>\n#include <omp.h>\n//-----------------------------------------------------------------------------\n#include <ilcplex/ilocplex.h>\n//-----------------------------------------------------------------------------\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/planar_face_traversal.hpp>\n#include <boost/graph/boyer_myrvold_planar_test.hpp>\n//-----------------------------------------------------------------------------\n#define pb push_back\n#define mp make_pair\n#define MAXSTR 1024\n#define MAX 100\n#define EPS 1e-6\n\nusing namespace std;\nusing namespace boost;\n\n#include \"combinadic.h\"\n\ntypedef pair<int, int> ii;\ntypedef adjacency_list< vecS, vecS, undirectedS,\n    property<vertex_index_t, int>,\n    property<edge_index_t, int> > Graph;\ntypedef vector< graph_traits<Graph>::edge_descriptor > vec_t;\n\nbool found = false;\nchar errmsg[MAXSTR];\n\nint nNodes = 0;\nint nCols  = 0;\nint cbSize = 4;\n\nvector<vector<int>> graphIn;\nmap<vector<int>, int> colsId;\n\nint sgn(double a) { return ((a > EPS) ? (1) : ((a < -EPS) ? (-1) : (0))); }\nint cmp(double a, double b = 0.0) { return sgn(a - b); }\n\n/*\n    Print elapsed time.\n    */\nvoid printElapsedTime(double start, double stop)\n{\n    double elapsed = stop - start;\n    printf(\"Elapsed time: %.3lfs.\\n\", elapsed);\n}\n//-----------------------------------------------------------------------------\n// Mac\n#ifdef __MACH__\n#include <mach/clock.h>\n#include <mach/mach.h>\n#endif\n//-----------------------------------------------------------------------------\n/*  Get clock time.\n    */\nvoid current_utc_time(struct timespec *ts) \n{\n    #ifdef __MACH__ // OS X does not have clock_gettime, use clock_get_time\n        clock_serv_t cclock;\n        mach_timespec_t mts;\n        host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock);\n        clock_get_time(cclock, &mts);\n        mach_port_deallocate(mach_task_self(), cclock);\n        ts->tv_sec = mts.tv_sec;\n        ts->tv_nsec = mts.tv_nsec;\n    #else\n        clock_gettime(CLOCK_REALTIME, ts);\n    #endif\n}\n\ndouble getTime()\n{\n    timespec ts;\n    current_utc_time(&ts);\n    return double(ts.tv_sec) + double(ts.tv_nsec) / 1e9;\n}\n//-----------------------------------------------------------------------------\nint faces_count = 0;\nmap< vector<int>, int > hasFace;\n// Some planar face traversal visitors that will \n// print the vertices and edges on the faces\nstruct output_visitor : public planar_face_traversal_visitor\n{\n    vector<int> faceVertices;\n    void begin_face(){ printf(\"New face: \"); }\n    void end_face(){\n        printf(\"\\n\");\n        sort(faceVertices.begin(), faceVertices.end());\n        hasFace[faceVertices] = 1;\n        faceVertices.clear();\n        faces_count++;\n    }\n};\n\nstruct vertex_output_visitor : public output_visitor\n{\n    template <typename Vertex> \n    void next_vertex(Vertex v) \n    { \n        std::cout << v + 1 << \" \";\n        faceVertices.pb((int)v);\n    }\n};\n\nstruct edge_output_visitor : public output_visitor\n{\n    template <typename Edge> \n    void next_edge(Edge e)\n    { \n        std::cout << e << \" \"; \n    }\n};\n//-----------------------------------------------------------------------------\nCPXENVptr env = NULL;\nCPXLPptr  lp  = NULL;\n//-----------------------------------------------------------------------------\nvoid readData()\n{\n    printf(\"---------- Input graph ----------\\n\");\n    //- - - - - - - - - - - - - - - - - - -\n    scanf(\"%d\", &nNodes);\n    printf(\"%d\\n\", nNodes);\n    // cbSize = nNodes-1;\n    //- - - - - - - - - - - - - - - - - - -\n    \n    graphIn.resize( nNodes + 1 );\n    for (int i = 1; i <= nNodes; i++)\n    {\n        graphIn[i].resize( nNodes + 1 );\n    }\n    \n    //- - - - - - - - - - - - - - - - - - -\n    for (int i = 1; i < nNodes; i++)\n    {\n        for (int j = i + 1; j <= nNodes; j++)\n        {\n            scanf(\"%d\", &graphIn[i][j]);\n            graphIn[j][i] = graphIn[i][j];\n            printf(\"%d \", graphIn[i][j]);\n        }\n        printf(\"\\n\");\n    }\n    printf(\"---------------------------------\\n\\n\");\n    //- - - - - - - - - - - - - - - - - - -\n}\n//-----------------------------------------------------------------------------\nint findColID( int i, int j, int k )\n{\n    map< vector<int>, int >::iterator itm;\n    \n    vector< int > v(3);\n    v[0] = i;\n    v[1] = j;\n    v[2] = k;\n    \n    itm = colsId.find( v );\n    if (itm == colsId.end())\n    {\n        return -1;\n        // cout << \"Cannot find colId x_\" << j << '(' << h << ')' << '_' << k << '\\n';\n        // abort();\n    }\n    else\n    {\n        return itm->second;\n    }\n}\n//-----------------------------------------------------------------------------\nvoid buildModel()\n{\n    int status = 0;\n    \n    //- - - - - - - - - - - - - - - - - - -\n    CPXchgobjsen( env, lp, CPX_MAX );\n    \n    nCols  = nNodes * (nNodes - 1) / 2;\n    printf(\"nCols = %d\\n\", nCols);\n    nCols += nNodes * (nNodes * nNodes - 3 * nNodes + 2) / 6;\n    printf(\"nCols = %d\\n\", nCols);\n    //- - - - - - - - - - - - - - - - - - -\n    \n    //- - - - - - - - - - - - - - - - - - -\n    char    sense[2];\n    int     rmatbeg[2];\n    double  rhs[2];\n    \n    char*   ctype    = new char[nCols + 1];\n    char**  cname    = new char*[nCols + 1];\n    char**  rname    = new char*[1];\n    rname[0] = new char[20];\n    int*    rmatind  = new int[nCols + 1];\n    double* rmatval  = new double[nCols + 1];\n    double* obj      = new double[nCols + 1];\n    double* lb       = new double[nCols + 1];\n    double* ub       = new double[nCols + 1];\n    //- - - - - - - - - - - - - - - - - - -\n    \n    //- - - - - - - - - - - - - - - - - - -\n    int col = 0;\n    for (int i = 1; i < nNodes; i++)\n    {\n        for (int j = i + 1; j <= nNodes; j++, col++)\n        {\n            vector<int> v(3);\n            v[0] = i;\n            v[1] = j;\n            v[2] = 0;\n            colsId[v] = col;\n            \n            cname[col] = new char[20];\n            sprintf(cname[col], \"x_%d_%d\", i, j);\n            lb[col]    = 0.0;\n            ub[col]    = 1.0;\n            ctype[col] = 'B';\n            obj[col]   = graphIn[i][j];\n        }\n    }\n    //- - - - - - - - - - - - - - - - - - -\n    printf(\"col = %d\\n\", col);\n    \n    //- - - - - - - - - - - - - - - - - - -\n    for (int i = 1; i < nNodes - 1; i++)\n    {\n        for (int j = i + 1; j < nNodes; j++)\n        {\n            for (int k = j + 1; k <= nNodes; k++, col++)\n            {\n                vector<int> v(3);\n                v[0] = i;\n                v[1] = j;\n                v[2] = k;\n                colsId[v] = col;\n                \n                cname[col] = new char[20];\n                sprintf(cname[col], \"f_%d_%d_%d\", i, j, k);\n                lb[col]    = 0.0;\n                ub[col]    = 1.0;\n                ctype[col] = 'B';\n                obj[col]   = 0.0;\n            }\n        }\n    }\n    //- - - - - - - - - - - - - - - - - - -\n    printf(\"col = %d\\n\", col);\n    \n    //- - - - - - - - - - - - - - - - - - -\n    if (status = CPXnewcols( env, lp, nCols, obj, lb, ub, ctype, (char **) cname ))\n    {\n        printf(\"CPXnewcols: Could not add new columns, error %d\\n\", status);\n        abort();\n    }\n    //- - - - - - - - - - - - - - - - - - -\n    printf(\"CCCCCC\\n\");\n    \n    //R7 - - - - - - - - - - - - - - - - - - -\n    rhs[0]     = 3.0 * (nNodes - 2);\n    sense[0]   = 'E';\n    rmatbeg[0] = 0;\n    \n    int p = 0;\n    for (int i = 1; i < nNodes; i++)\n    {\n        for (int j = i + 1; j <= nNodes; j++, p++)\n        {\n            rmatind[p] = p;\n            rmatval[p] = 1.0;\n        }\n    }\n    sprintf(rname[0], \"R7\");\n    \n    if (status = CPXaddrows( env, lp,\n                            (int) 0, (int) 1, p,\n                            (const double *) rhs, (const char *) sense,\n                            (const int *) rmatbeg, (const int *) rmatind,\n                            (const double *) rmatval,\n                            NULL, (char **) rname ))\n    {\n        printf(\"CPXaddrows: Could not add new rows (%s)\\n\", rname);\n        abort();\n    }\n    printf(\"777777\\n\");\n    //R7 - - - - - - - - - - - - - - - - - - -\n    \n    //R8 - - - - - - - - - - - - - - - - - - -\n    rhs[0]   = 0.0;\n    sense[0] = 'E';\n    rmatbeg[0] = 0;\n    \n    for (int i = 1; i < nNodes; i++)\n    {\n        for (int j = i + 1; j <= nNodes; j++)\n        {\n            p = 0;\n            for (int k = 1; k < i; k++, p++)\n            {\n                rmatind[p] = findColID( k, i, j );;\n                rmatval[p] = 1.0;\n            }\n            for (int k = i + 1; k < j; k++, p++)\n            {\n                rmatind[p] = findColID( i, k, j );;\n                rmatval[p] = 1.0;\n            }\n            for (int k = j + 1; k <= nNodes; k++, p++)\n            {\n                rmatind[p] = findColID( i, j, k );;\n                rmatval[p] = 1.0;\n            }\n            rmatind[p] = findColID( i, j, 0 );;\n            rmatval[p] = -2.0;\n            p++;\n            \n            sprintf(rname[0], \"R8_%d_%d\", i, j);\n            \n            if (status = CPXaddrows( env, lp,\n                                    (int) 0, (int) 1, p,\n                                    (const double *) rhs, (const char *) sense,\n                                    (const int *) rmatbeg, (const int *) rmatind,\n                                    (const double *) rmatval,\n                                    NULL, (char **) rname ))\n            {\n                printf(\"CPXaddrows: Could not add new rows (%s)\\n\", rname);\n                abort();\n            }\n        }\n    }\n    printf(\"888888\\n\");\n    //R8 - - - - - - - - - - - - - - - - - - -\n    \n    //R9 - - - - - - - - - - - - - - - - - - -\n    rhs[0]     = 3.0;\n    sense[0]   = 'G';\n    rmatbeg[0] = 0;\n    \n    for (int i = 1; i <= nNodes; i++)\n    {\n        p = 0;\n        for (int j = 1; j < i; j++, p++)\n        {\n            rmatind[p] = findColID( j, i, 0 );\n            rmatval[p] = 1.0;\n        }\n        for (int j = nNodes; j > i; j--, p++)\n        {\n            rmatind[p] = findColID( i, j, 0 );\n            rmatval[p] = 1.0;\n        }\n        sprintf(rname[0], \"R9_%d\", i);\n        \n        if (status = CPXaddrows( env, lp,\n                                (int) 0, (int) 1, p,\n                                (const double *) rhs, (const char *) sense,\n                                (const int *) rmatbeg, (const int *) rmatind,\n                                (const double *) rmatval,\n                                NULL, (char **) rname ))\n        {\n            printf(\"CPXaddrows: Could not add new rows (%s)\\n\", rname);\n            abort();\n        }\n    }\n    printf(\"999999\\n\");\n    //R9  - - - - - - - - - - - - - - - - - - -\n    \n    //R10 - - - - - - - - - - - - - - - - - - -\n    rhs[0]     = 0.0;\n    sense[0]   = 'L';\n    rmatbeg[0] = 0;\n    \n    for (int i = 1; i < nNodes - 1; i++)\n    {\n        for (int j = i + 1; j < nNodes; j++)\n        {\n            for (int k = j + 1; k <= nNodes; k++)\n            {\n                p = 0;\n                rmatind[p] = findColID( i, j, k );;\n                rmatval[p] = 1.0;\n                p++;\n                rmatind[p] = findColID( i, j, 0 );;\n                rmatval[p] = -1.0;\n                p++;\n                \n                sprintf(rname[0], \"R10_%d_%d_%d\", i, j, k);\n                \n                if (status = CPXaddrows( env, lp,\n                                        (int) 0, (int) 1, p,\n                                        (const double *) rhs, (const char *) sense,\n                                        (const int *) rmatbeg, (const int *) rmatind,\n                                        (const double *) rmatval,\n                                        NULL, (char **) rname ))\n                {\n                    printf(\"CPXaddrows: Could not add new rows (%s)\\n\", rname);\n                    abort();\n                }\n            }\n        }\n    }\n    printf(\"101010\\n\");\n    //R10 - - - - - - - - - - - - - - - - - - -\n    \n    //R11 - - - - - - - - - - - - - - - - - - -\n    rhs[0]     = 0.0;\n    sense[0]   = 'L';\n    rmatbeg[0] = 0;\n    \n    for (int i = 1; i < nNodes - 1; i++)\n    {\n        for (int j = i + 1; j < nNodes; j++)\n        {\n            for (int k = j + 1; k <= nNodes; k++)\n            {\n                p = 0;\n                rmatind[p] = findColID( i, j, k );;\n                rmatval[p] = 1.0;\n                p++;\n                rmatind[p] = findColID( j, k, 0 );;\n                rmatval[p] = -1.0;\n                p++;\n                \n                sprintf(rname[0], \"R11_%d_%d_%d\", i, j, k);\n                \n                if (status = CPXaddrows( env, lp,\n                                        (int) 0, (int) 1, p,\n                                        (const double *) rhs, (const char *) sense,\n                                        (const int *) rmatbeg, (const int *) rmatind,\n                                        (const double *) rmatval,\n                                        NULL, (char **) rname ))\n                {\n                    printf(\"CPXaddrows: Could not add new rows (%s)\\n\", rname);\n                    abort();\n                }\n            }\n        }\n    }\n    printf(\"111111\\n\");\n    //R11 - - - - - - - - - - - - - - - - - - -\n    \n    //R12 - - - - - - - - - - - - - - - - - - -\n    rhs[0]     = 0.0;\n    sense[0]   = 'L';\n    rmatbeg[0] = 0;\n    \n    for (int i = 1; i < nNodes - 1; i++)\n    {\n        for (int j = i + 1; j < nNodes; j++)\n        {\n            for (int k = j + 1; k <= nNodes; k++)\n            {\n                p = 0;\n                rmatind[p] = findColID( i, j, k );;\n                rmatval[p] = 1.0;\n                p++;\n                rmatind[p] = findColID( i, k, 0 );;\n                rmatval[p] = -1.0;\n                p++;\n                \n                sprintf(rname[0], \"R12_%d_%d_%d\", i, j, k);\n                \n                if (status = CPXaddrows( env, lp,\n                                        (int) 0, (int) 1, p,\n                                        (const double *) rhs, (const char *) sense,\n                                        (const int *) rmatbeg, (const int *) rmatind,\n                                        (const double *) rmatval,\n                                        NULL, (char **) rname ))\n                {\n                    printf(\"CPXaddrows: Could not add new rows (%s)\\n\", rname);\n                    abort();\n                }\n            }\n        }\n    }\n    printf(\"121212\\n\");\n    //R12 - - - - - - - - - - - - - - - - - - -\n    \n    //- - - - - - - - - - - - - - - - - - -\n    delete[] rmatind;\n    \n    delete[] rmatval;\n    delete[] obj;\n    delete[] lb;\n    delete[] ub;\n    delete[] ctype;\n    \n    for (int i = 0; i <= nCols; i++)\n    {\n        delete[] cname[i];\n    }\n    delete[] cname;\n    \n    delete[] rname[0];\n    delete[] rname;\n    //- - - - - - - - - - - - - - - - - - -\n}\n//-----------------------------------------------------------------------------\nvoid openCplex()\n{\n    int status = 0;\n    \n    if (!(env = CPXopenCPLEX( &status )))\n    {\n        printf(\"Could not open CPLEX environment.\\n\");\n        CPXgeterrorstring( env, status, errmsg );\n        printf(\"%s\\n\", errmsg);\n        abort();\n    }\n    \n    if (status = CPXsetintparam( env, CPX_PARAM_SCRIND, CPX_ON ))\n    {\n        printf(\"PARAM_SCRIND: Failure to turn on screen indicator, error %d\\n\",\n            status);\n        abort();\n    }\n    \n    if (status = CPXsetintparam (env, CPX_PARAM_SIMDISPLAY, 2))\n    {\n        printf(\"PARAM_SIMDISPLAY: Failed to turn up simplex display level.\\n\");\n        abort();\n    }\n    \n    if (status = CPXsetintparam( env, CPX_PARAM_DATACHECK, CPX_ON ))\n    {\n        printf(\"PARAM_DATACHECK: Failure to turn on data checking, error %d\\n\",\n            status);\n        abort();\n    }\n    \n    if (!(lp = CPXcreateprob( env, &status, \"PLANAR\" )))\n    {\n        printf(\"Failed to create LP PLANAR.\\n\");\n        abort();\n    }\n}\n//-----------------------------------------------------------------------------\nvoid writeSolutions()\n{\n    int    solStat  = 0;\n    double objValue = 0.0;\n    \n    double* x = new double[nCols + 1];\n    if (x == NULL)\n    {\n        printf(\"Could not allocate memory for solution.\\n\");\n        abort();\n    }\n    \n    int status = CPXsolution( env, lp, &solStat, &objValue, x, NULL, NULL, NULL);\n    if (status)\n    {\n        printf(\"Failed to obtain cplex solution.\\n\");\n        abort();\n    }\n    \n    printf(\"\\nSolution status = %d\\n\", solStat);\n    printf(\"Solution value  = %.0lf\\n\\n\", objValue);\n    \n    //- - - - - - - - - - - - - - - - - - -\n    int col = 0;\n    for (int i = 1; i < nNodes; i++)\n    {\n        for (int j = i + 1; j <= nNodes; j++, col++)\n        {\n            if (cmp(x[col]) == 1)\n            {\n                printf(\"x(%d,%d) = %0.lf\\n\", i, j, x[col]);\n            }\n        }\n    }\n    \n    for (int i = 1; i < nNodes - 1; i++)\n    {\n        for (int j = i + 1; j < nNodes; j++)\n        {\n            for (int k = j + 1; k <= nNodes; k++, col++)\n            {\n                if (cmp(x[col]) == 1)\n                {\n                    printf(\"f(%d,%d, %d) = %0.lf\\n\", i, j, k, x[col]);\n                }\n            }\n        }\n    }\n    //- - - - - - - - - - - - - - - - - - -\n    delete[] x;\n    //- - - - - - - - - - - - - - - - - - -\n}\n//-----------------------------------------------------------------------------\nvoid addCut( vector<int>& S )\n{\n    int status = 0;\n    static int r13 = 1;\n    \n    //- - - - - - - - - - - - - - - - - - -\n    char    sense[2];\n    int     rmatbeg[2];\n    double  rhs[2];\n    \n    char**  rname    = new char*[1];\n    rname[0]         = new char[20];\n    int*    rmatind  = new int[nCols + 1];\n    double* rmatval  = new double[nCols + 1];\n    //- - - - - - - - - - - - - - - - - - -\n    \n    //- - - - - - - - - - - - - - - - - - -\n    rhs[0]   = 2 * (S.size() - 2) - 1;\n    sense[0] = 'L';\n    rmatbeg[0] = 0;\n    \n    int p = 0;\n    for (int i = 1; i < S.size() - 1; i++)\n    {\n        for (int j = i + 1; j < S.size(); j++)\n        {\n            for (int k = j + 1; k <= S.size(); k++)\n            {\n                vector<int> tmpVertices;\n                tmpVertices.pb(S[i-1]); tmpVertices.pb(S[j-1]); tmpVertices.pb(S[k-1]);\n                if (hasFace.count(tmpVertices))\n                {\n                    rmatind[p] = findColID( S[i-1]+1, S[j-1]+1, S[k-1]+1 );\n                    rmatval[p] = 1.0;\n                    p++;\n                }\n            }\n        }\n    }\n    \n    sprintf(rname[0], \"R13_%d\", r13++);\n    \n    if (status = CPXaddrows( env, lp,\n                            (int) 0, (int) 1, p,\n                            (const double *) rhs, (const char *) sense,\n                            (const int *) rmatbeg, (const int *) rmatind,\n                            (const double *) rmatval,\n                            NULL, (char **) rname ))\n    {\n        printf(\"CPXaddrows: Could not add new rows (%s)\\n\", rname);\n        abort();\n    }\n    //- - - - - - - - - - - - - - - - - - -\n    \n    //- - - - - - - - - - - - - - - - - - -\n    delete[] rmatind;  \n    delete[] rmatval;\n    delete[] rname[0];\n    delete[] rname;\n    //- - - - - - - - - - - - - - - - - - -\n    \n}\n//-----------------------------------------------------------------------------\n//vector<ii> getEdges()\nmap<ii, bool> getEdges()\n{\n    int    solStat  = 0;\n    double objValue = 0.0;\n    \n    double* x = new double[nCols + 1];\n    if (x == NULL)\n    {\n        printf(\"Could not allocate memory for solution.\\n\");\n        abort();\n    }\n    \n    int status = CPXsolution(env, lp, &solStat, &objValue, x, NULL, NULL, NULL);\n    if (status)\n    {\n        printf(\"Failed to obtain cplex solution.\\n\");\n        abort();\n    }\n    \n    // vector<ii> resp;\n    map<ii, bool> resp;\n    //- - - - - - - - - - - - - - - - - - -\n    int col = 0;\n    for (int i = 1; i < nNodes; i++)\n    {\n        for (int j = i + 1; j <= nNodes; j++, col++)\n        {\n            if (cmp(x[col]) == 1)\n            {\n                // resp.pb(mp(i, j));\n                resp[mp(i, j)] = true;\n            }\n        }\n    }\n    delete [] x;\n    return resp;\n}\n//-----------------------------------------------------------------------------\n//Solution obtained from the relaxed model.\nmap<ii, bool> sol;\n//Was this combination of edges used as a restriction already?\nmap<vector<ii>, int> cutFound;\n//A list having MPGs used as restrictions.\nmap<int64, vector<ii>> edgesListM;    //smallest\nvector<vector<ii>> edgesListV;        //smpg\n\n/*\n    Add a set of edges that generates a cut.\n    edgesIdx    ---> Set of edges\n    t           ---> Iteration number\n*/\nvoid findCut(vector<ii> edgesIdx, int t)\n{\n    //get num of vertices\n    //m = 3n - 6; n = (m+6)/3\n    int graphSize = (edgesIdx.size()+6)/3;\n    vector<int> S;\n    set<int> V;\n\n    //create the graph which will generate a restriction 13\n    Graph tmp_planar(graphSize);\n    for (int i = 0; i < edgesIdx.size(); ++i)\n    {\n        int u = edgesIdx[i].first, v = edgesIdx[i].second;\n        if (!V.count(u))\n        {\n            S.pb(u);\n            V.insert(u);\n        }\n        if (!V.count(v))\n        {\n            S.pb(v);\n            V.insert(v);\n        }\n        add_edge(u, v, tmp_planar);\n    }\n    //Necessary.\n    sort(S.begin(), S.end());\n\n    //Initialize the interior edge index; necessary for face traversal.\n    property_map<Graph, edge_index_t>::type e_index = get(edge_index, tmp_planar);\n    graph_traits<Graph>::edges_size_type edge_count = 0;\n    graph_traits<Graph>::edge_iterator ei, ei_end;\n    for (tie(ei, ei_end) = edges(tmp_planar); ei != ei_end; ++ei)\n        put(e_index, *ei, edge_count++);\n\n    vector<vec_t> embedding(num_vertices(tmp_planar));\n    if (boyer_myrvold_planarity_test(tmp_planar, &embedding[0]))\n    {\n        //Clear the face set.\n        hasFace.clear();\n\n        vertex_output_visitor v_vis;\n        printf(\"---------- Adding cut ----------\\n\");\n        planar_face_traversal(tmp_planar, &embedding[0], v_vis);\n        printf(\"Number of faces = %d\\n\", faces_count);\n        printf(\"Number of edges = %d\\n\", num_edges(tmp_planar));\n        printf(\"--------------------------------\\n\");\n        faces_count = 0;\n\n        cutFound[edgesIdx]++;\n        addCut(S);\n    }\n}\n//-----------------------------------------------------------------------------\n/*\n    n       ---> Size of the input array\n    k       ---> Size of the combination\n    app     ---> Approach option\n*/\nvoid combine(int n, int k, int app)\n{\n    Combination c(n, k);\n    int64 ub = c.choose(n, k);\n    #pragma omp parallel for shared(edgesListM, edgesListV)\n    for (int64 i = 0; i < ub; i++)\n    {\n        Graph tmp_planar(k);\n\n        vector<int> S = c.element(i).getArray();\n        vector<ii> edges;\n        \n        for (int vertex = 0; vertex < S.size()-1; vertex++)\n        {\n            int u = S[vertex];\n            for (int adj = vertex+1; adj < S.size(); adj++)\n            {\n                int v = S[adj];\n                //add an edge if (u, v) belongs to the solution found\n                if (!sol.count(mp(u+1, v+1))) continue;\n                edges.pb(mp(u, v));\n                add_edge(u, v, tmp_planar);\n            }\n        }\n        //Was this restriction inserted already?\n        if (cutFound.count(edges)) continue;\n        \n        //Cannot be maximal\n        if (num_edges(tmp_planar) != 3*S.size()-6) continue;\n\n        //Is it planar?\n        if (boyer_myrvold_planarity_test(tmp_planar))\n        {\n            #pragma omp critical\n            {\n                if (app) edgesListM[i] = edges;\n                else edgesListV.pb(edges);\n            }\n        }\n    }\n}\n//-----------------------------------------------------------------------------\nvoid bcSmallest(int app)\n{\n    // mipBasis();\n    int t = 0;\n    while (true)\n    {\n        if (CPXmipopt( env, lp ))\n        {\n            printf(\"CPXmipopt: Failed to optimize LP.\\n\");\n            abort();\n        }\n        char name[20];\n        sprintf(name, \"planar-%d.lp\", t);\n        CPXwriteprob(env, lp, name, NULL);\n\n        sol = getEdges();\n        map<ii, bool>::iterator ed;\n        writeSolutions();\n\n        //Build the solution graph.\n        Graph planar;\n        for (ed = sol.begin(); ed != sol.end(); ed++)\n        {\n            ii at = ed->first;\n            int a = at.first-1, b = at.second-1;\n            add_edge(a, b, planar);\n        }\n\n        if (boyer_myrvold_planarity_test(planar))\n        {\n            printf(\"Maximal Planar Subgraph found!\\n\");\n            break;\n        }\n        else\n        {\n            //S initial size must be at least 4.\n            edgesListM.clear();\n            cbSize = 4;\n            found = true;\n            while (cbSize < nNodes)\n            {\n                double st = getTime();\n                printf(\"Combination size = %d\\n\", cbSize);\n                combine(nNodes, cbSize, app);\n                double fn = getTime();\n                printElapsedTime(st, fn);\n                \n                if (edgesListM.size()) break;\n                cbSize++;\n            }\n            if (edgesListM.size() == 0)\n            {\n                printf(\"There is no MPG for restriction 13.\\n\");\n                return;\n            }\n            //Use the first that was found.\n            findCut(edgesListM.begin()->second, t);\n        }\n        // char m_name[20];\n        // sprintf(m_name, \"MIPS-%d\", t);\n        // CPXwritemipstarts(env, lp, m_name, 0, 0);\n        t++;\n    }\n}\n//-----------------------------------------------------------------------------\nvoid bcSMPG(int app)\n{\n    // mipBasis();\n    int t = 0;\n    while (true)\n    {\n        if (CPXmipopt( env, lp ))\n        {\n            printf(\"CPXmipopt: Failed to optimize LP.\\n\");\n            abort();\n        }\n        char name[20];\n        sprintf(name, \"planar-%d.lp\", t);\n        CPXwriteprob(env, lp, name, NULL);\n\n        sol = getEdges();\n        map<ii, bool>::iterator ed;\n        writeSolutions();\n\n        //Build the solution graph.\n        Graph planar;\n        for (ed = sol.begin(); ed != sol.end(); ed++)\n        {\n            ii at = ed->first;\n            int a = at.first-1, b = at.second-1;\n            add_edge(a, b, planar);\n        }\n\n        if (boyer_myrvold_planarity_test(planar))\n        {\n            printf(\"Maximal Planar Subgraph found!\\n\");\n            break;\n        }\n        else\n        {\n            edgesListV.clear();\n            cbSize = 4;\n            found = true;\n            while (cbSize < nNodes)\n            {\n                double st = getTime();\n                printf(\"Combination size = %d\\n\", cbSize);\n                combine(nNodes, cbSize, app);\n                double fn = getTime();\n                printElapsedTime(st, fn);\n                cbSize++;\n            }\n            if (edgesListV.size() == 0)\n            {\n                printf(\"There is no MPG for restriction 13.\\n\");\n                return;\n            }\n\n            //Having all MPGs generated, we have to get the smallest one\n            //which is not a subgraph of any other.\n            int idx = edgesListV.size()-1;\n            vector<ii>::iterator vit;\n            for (int i = 0; i < edgesListV.size()-1; i++)\n            {\n                found = true;\n                for (int j = i+1; j < edgesListV.size(); j++)\n                {\n                    if (edgesListV[i].size() == edgesListV[j].size()) continue;\n\n                    vector<ii> tmp(edgesListV[j].size());\n                    vit = set_intersection(edgesListV[i].begin(), edgesListV[i].end(),\n                        edgesListV[j].begin(), edgesListV[j].end(), tmp.begin());\n\n                    //If the smallest subgraph is a subgraph of any other,\n                    //then it cannot be a restriction.\n                    int sz = (int)(vit-tmp.begin());\n                    if (sz == edgesListV[i].size())\n                    {\n                        found = false;\n                        break;\n                    }\n                }\n                if (found)\n                {\n                    idx = i;\n                    break;\n                }\n            }\n            //Use the smallest as the best cut.\n            findCut(edgesListV[idx], t);\n        }\n        t++;\n    }\n}\n//-----------------------------------------------------------------------------\nint main(int argv, char** argc)\n{\n    // ios::sync_with_stdio(false);\n    if (argv < 2)\n    {\n        printf(\"ERROR! Required num. of arguments: 2\\n\");\n        printf(\"Try:\\nsmallest - ./a.out 1\\nsmpg     - ./a.out 0\\n\");\n        return 0;\n    }\n    \n    int status;\n    \n    readData();\n    openCplex();\n    \n    if (argv == 2)\n    {\n        buildModel();\n    }\n    else if (argv == 3)\n    {\n        if (status = CPXreadcopyprob(env, lp, argc[2], \"LP\"))\n        {\n            printf(\"Error! Could not read file!\\n\");\n            exit(1);\n        }\n    }\n\n    int option = atoi(argc[1]);\n    \n    if (option) bcSmallest(option);\n    else bcSMPG(option);\n\n    if (status = CPXwriteprob(env, lp, \"planar.lp\", NULL))\n    {\n        printf(\"CPXwriteprob: Failed to write LP to disk, error %d\\n\",\n            status);\n    }\n    \n    writeSolutions();\n    \n    if (status = CPXfreeprob(env, &lp))\n    {\n        printf(\"CPXfreeprob failed, error code %d\\n\", status);\n    }\n    \n    if (status = CPXcloseCPLEX(&env))\n    {\n        CPXgeterrorstring(env, status, errmsg);\n        printf(\"CPXcloseCPLEX: Could not close CPLEX environment.\\n\");\n        printf(\"%s\\n\", errmsg);\n    }\n    //- - - - - - - - - - - - - - - - - - -\n    \n    return 0;\n}\n//-----------------------------------------------------------------------------\nvoid mipBasis()\n{\n    int status = 0;\n\n    // int cstat[nCols + 1];\n    // int rstat[nRows + 1];\n\n    int nFaces, x, nzcnt = 0, effortlevel = 0;\n    int beg = 0;\n\n    vector<int> varindices;\n    vector<double> values;\n    for (int i = 1; i < nNodes; i++)\n    {\n        for (int j = i + 1; j <= nNodes; j++)\n        {\n            scanf(\"%d\", &x);\n            vector<int> tmp;\n            tmp.pb(i); tmp.pb(j); tmp.pb(0);\n\n            varindices.pb(colsId[tmp]);\n            values.pb(x ? 1.0 : 0.0);\n            nzcnt++;\n        }\n    }\n\n    map< vector<int>, int > sFaces;\n    scanf(\"%d\", &nFaces);\n    for (int i = 0; i < nFaces; i++)\n    {\n        vector<int> sF;\n        for (int j = 0; j < 3; j++)\n        {\n            scanf(\"%d\", &x);\n            sF.pb(x+1);\n        }\n        sort(sF.begin(), sF.end());\n        sFaces[sF] = 1;\n    }\n\n    for (int i = 1; i < nNodes - 1; i++)\n    {\n        for (int j = i + 1; j < nNodes; j++)\n        {\n            for (int k = j + 1; k <= nNodes; k++)\n            {\n                vector<int> tmp;\n                tmp.pb(i); tmp.pb(j); tmp.pb(k);\n                \n                varindices.pb(colsId[tmp]);\n                values.pb(sFaces.count(tmp) ? 1.0 : 0.0);\n                nzcnt++;\n            }\n        }\n    }\n    printf(\"Result: %d\\n\", nzcnt);\n\n    int arr_varindices[nzcnt];\n    double arr_values[nzcnt];\n    copy(varindices.begin(), varindices.end(), arr_varindices);\n    copy(values.begin(), values.end(), arr_values);\n\n    /* Now copy the mip start */\n\n    CPXsetintparam( env, CPX_PARAM_ADVIND, 1 );\n\n    if (status = CPXaddmipstarts (env, lp, 1, nzcnt, &beg, arr_varindices,\n        arr_values, &effortlevel, NULL))\n    {\n        printf(\"CPXaddmipstarts: Could not add mip start.\\n\");\n        abort();\n    }\n\n    CPXwritemipstarts(env, lp, \"MIPS\", 0, 0);\n}\n//-----------------------------------------------------------------------------\n", "meta": {"hexsha": "1fad489fcbfde9db29257725463be1fc85fe4137", "size": 31798, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "branch-and-cut/planar-omp.cpp", "max_stars_repo_name": "viniciusmalloc/dimpling", "max_stars_repo_head_hexsha": "f4eb82aab11463ec8fae2c80bda6b747c19800b2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "branch-and-cut/planar-omp.cpp", "max_issues_repo_name": "viniciusmalloc/dimpling", "max_issues_repo_head_hexsha": "f4eb82aab11463ec8fae2c80bda6b747c19800b2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "branch-and-cut/planar-omp.cpp", "max_forks_repo_name": "viniciusmalloc/dimpling", "max_forks_repo_head_hexsha": "f4eb82aab11463ec8fae2c80bda6b747c19800b2", "max_forks_repo_licenses": ["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.7764705882, "max_line_length": 87, "alphanum_fraction": 0.3870369206, "num_tokens": 8733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432182679956, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.4752083561441623}}
{"text": "#include \"highgui.h\"\n#include \"imgproc.h\"\n#include \"feature.h\"\n#include \"draw.h\"\n#include <armadillo>\n#include <iostream>\n#include <opencv2/highgui/highgui.hpp>\n\nusing namespace arma;\nusing namespace std;\n\nint main() {\n  srand(getpid());\n  //cube I = load_image(\"600px-Line_with_outliers.svg.png\");\n  cube I = load_image(\"twolines.bmp\");\n  //cube I = load_image(\"Hough_Lines_Tutorial_Original_Image.jpg\");\n  mat E = canny2(rgb2gray(I), 7, 3.0);\n  E = ((E % (E > 0.01)) > 0) % ones(E.n_rows, E.n_cols);\n\n  // after we get the image, try to resize it\n  double scale_factor = 1.0;\n  double cc = E(0,0);\n  uvec ind = find(E != cc);\n  vector<vec> A;\n  for (uword i : ind) {\n    vec index = { (double)(i % E.n_rows), (double)(i / E.n_rows) };\n    A.push_back(index);\n  }\n\n  disp_image(\"original\", I);\n  disp_image(\"canny\", E);\n  disp_wait();\n\n  mat R = lines2(E, A);\n\n  // filter out to only get 0.5 or higher radius\n  int max_count = -1;\n  for (uword i = 0; i < R.n_cols; i++) {\n    if (R(0,i) < 0.5) {\n      break;\n    }\n    max_count = (int)i;\n  }\n  if (max_count > -1) {\n    R = R.cols(0,max_count);\n  } else {\n    R = mat();\n  }\n\n  // select the highest one and show it\n  cube L = gray2rgb(E);\n\n  for (int k = 0; k < R.n_cols; k++) {\n    double theta = R(2, k) * M_PI / 180.0;\n    double b = R(1, k) / sin(theta);\n    double m = -cos(theta) / sin(theta);\n    double y1 = b;\n    double y2 = m*I.n_cols + b;\n    draw_line(L, vec({ 0, 0, 1 }), {y1, 0}, {y2, (double)I.n_cols});\n  }\n\n  disp_image(\"hough_lines\", L);\n  disp_wait();\n  return 0;\n}\n", "meta": {"hexsha": "79e5ff4e2ca43f4f93fca56477f9dae9818ade50", "size": 1540, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "visual/test_cpu/test.cpp", "max_stars_repo_name": "timrobot/Tachikoma-Project", "max_stars_repo_head_hexsha": "c7af70f2c58fe43f25331fd03589845480ae0f16", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-11-11T19:04:33.000Z", "max_stars_repo_stars_event_max_datetime": "2016-11-11T19:04:33.000Z", "max_issues_repo_path": "visual/test_cpu/test.cpp", "max_issues_repo_name": "TimothyYong/Tachikoma-Project", "max_issues_repo_head_hexsha": "c7af70f2c58fe43f25331fd03589845480ae0f16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "visual/test_cpu/test.cpp", "max_forks_repo_name": "TimothyYong/Tachikoma-Project", "max_forks_repo_head_hexsha": "c7af70f2c58fe43f25331fd03589845480ae0f16", "max_forks_repo_licenses": ["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.3333333333, "max_line_length": 68, "alphanum_fraction": 0.5805194805, "num_tokens": 538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.47520834826264313}}
{"text": "/*! \\file\n  \\brief Functors to convert data to doubles.\n  \\details SVG plot assumes all data are convertible to double or uncertain value type unc before being plotted.\n    The functors are used to convert both 1D and 2D (pairs of data values) to be converted.\n    Note that uncertain value class unc only holds double precision so higher precision data type\n    will therefore lose information.  This seems a reasonable design decision as any real data\n    to be plotted is unlikely to have more than double precision (about 16 decimal digits).\n\n    \"svg_plot\\example\\convertible_to_double.cpp\" demonstrates that built-in types\n    @c float, @c double, @c long double @ Boost.Multiprecision @c cpp_bin_float_quad \n    work as expected, as well as a sample User Defined Type (UDT) a fixed-point type.\n\n    Types that cannot be converted to double nor constructible from double provoke a compile-time message:\n    \"Uncertain types must be convertible to double!\"\n\n    (This uses checks using http://www.cplusplus.com/reference/type_traits/is_constructible/\n      @c BOOST_STATIC_ASSERT_MSG(std::is_constructible<T, double>::value, \"Uncertain types must be convertible to double!\");\n     ).\n*/\n\n// Copyright Jacob Voytko 2007\n// Copyright Paul A. Bristow 2009, 2012, 2013, 2018, 2021\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_SVG_DETAIL_FUNCTORS_HPP\n#define BOOST_SVG_DETAIL_FUNCTORS_HPP\n\n#include <boost/quan/unc.hpp>\n#include <boost/quan/meas.hpp>\n\nnamespace boost {\nnamespace svg {\nnamespace detail\n{\n  using namespace boost::quan;\n\n  /*! \\class boost::svg::detail::double_1d_convert\n     \\brief This functor allows any 1D data that can be converted to @c double to be plotted.\n */\nclass double_1d_convert\n{\npublic:\n    typedef double result_type; //!< result type is @c double.\n\n    //! To convert a single data value to double.\n    //! \\tparam T Any type that can be converted to double.\n    //! \\returns A single @c double data value.\n    template <class T>\n    double operator()(T val) const \n    {\n      BOOST_STATIC_ASSERT_MSG(std::is_constructible<T, double>::value, \"Uncertain types must be convertible to double!\");\n\n       return static_cast<double>(val); //! \\return Value that has been converted to double.\n    }\n}; // class double_1d_convert\n\n /*! \\class boost::svg::detail::unc_1d_convert\n      \\brief This functor allows any 1D data that can be converted to @c boost::quan::unc (uncertain double) to be plotted.\n      \\details Defaults provided by the @c unc class constructor ensure that\n        uncertainty, degrees of freedom information, and uncertain type are suitably set too.\n*/\ntemplate <bool correlated>\nclass unc_1d_convert\n{\npublic:\n    typedef unc<correlated> result_type; //!< @c result_type is an uncertain floating-point type.\n\n    /*!< Convert to uncertain type,\n      providing defaults for uncertainty,  degrees of freedom information, and type (meaning undefined).\n      \\return value including uncertainty information.\n       \\tparam T Any data type with a value that can be converted to double, for example: @c double, @c uncun, @c Meas.\n      */\n    template <class T>\n    unc<correlated> operator()(T val) const\n    {\n      return (result_type)val;\n      /*! \\return uncertain type (uncertainty, degrees of freedom information, and type meaning undefined). */\n    }\n}; // template <bool correlated> class default_1d_convert\n\n/*! \\class boost::svg::detail::meas_1d_convert\n      \\brief This functor allows any 1D data that can be converted to measurements\n      (with uncertain doubles) to be plotted.\n      \\details Defaults provided by the meas class constructor ensure that\n        uncertainty, degrees of freedom information, type, and order, timestamp and id are suitably set too.\n    \\tparam T Any data type with a value that can be converted to double, for example: double, unc, Meas.\n    \\return uncertain type (uncertainty, degrees of freedom information, and type meaning undefined).\n*/\nclass meas_1d_convert\n{ \npublic:\n    typedef Meas result_type; //!< result type includes an uncertain floating-point type.\n\n    template <class T>\n    Meas operator()(T val) const\n    /*!< Convert to Meas type,\n      providing defaults for uncertainty, degrees of freedom information, and uncertain type.\n      \\return value including uncertainty and other information.\n    */\n    {\n      BOOST_STATIC_ASSERT_MSG(std::is_constructible<T, double>::value, \"Uncertain types must be that can be converted to double!\");\n      return static_cast<result_type>(val);\n    }\n}; // class default_1d_convert\n\nclass pair_double_2d_convert\n{ /*! \\class boost::svg::detail::pair_double_2d_convert\n      \\brief This functor allows any 2-D data that can be converted to type @c std::pair<double, double> to be plotted.\n     Convert a pair of X and Y (whose types can be converted to double values) to a pair of @c doubles.\n     \\tparam T type whose value can be converted to @c double.\n     \\tparam U type whose value can be converted to @c  double.\n     \\returns @c std::pair of @c double data point values.\n  */\npublic:\n    typedef std::pair<double, double> result_type; //!< result type is a pair (X and Y) of doubles.\n\n    double i; //!< Current value, 1st set by start(double i0).\n    void start(double i0)\n    { //! Set a start value.\n      i = i0;\n    }\n\n    template <typename T, typename U>\n    std::pair<double, double> operator()(const std::pair<T, U>& a) const\n    { //! Assumes that a conversion from double yields just the value component of the uncertain value.\n      BOOST_STATIC_ASSERT_MSG(std::is_constructible<T, double>::value, \"Uncertain types must be convertible to double!\");\n      BOOST_STATIC_ASSERT_MSG(std::is_constructible<U, double>::value, \"Uncertain types must be convertible to double!\");\n      return std::pair<double, double>(static_cast<double>(a.first), static_cast<double>(a.second));\n    }\n\n    template <typename T>\n    std::pair<double, double> operator()(T a)\n    {  //! Convert a pair of X and Y values to a @c std::pair of @c doubles.\n       //! \\return @c std::pair of doubles.\n        return std::pair<double, double>(i++, static_cast<double>(a));\n    }\n}; // class pair_double_2d_convert\n\ntemplate <bool correlated>\nclass pair_unc_2d_convert\n{ /*! \\class boost::svg::detail::pair_unc_2d_convert\n      \\brief This functor allows any 2D data that can be converted to type @c std::pair<unc, unc> to be plotted.\n*/\npublic:\n    typedef std::pair<unc<correlated>, unc<correlated> > result_type; //!< result type is pair of uncertain values.\n\n    unc<correlated> i;  //!< Current uncertain value, 1st set by start(double i0).\n\n    void start(unc<correlated> i0)\n    { //!< Set a start value.\n       i = i0;\n    }\n\n    //!< \\tparam T type that can be converted to double.\n    //!< \\tparam U type that can be converted to double.\n    //! \\returns A @c std::pair of double data point values.\n    template <class T, class U>\n    std::pair<unc<correlated>, unc<correlated> > operator()(const std::pair<T, U>& a) const\n    { //!< Convert a pair of X and Y uncertain type values to a pair of @c doubles.\n      //! Cast to double so that can use with float, long double and UDTs.\n      //! \\return @c std::pair of uncs.\n      BOOST_STATIC_ASSERT_MSG(std::is_constructible<T, double>::value, \"Uncertain types must be convertible to double!\");\n      BOOST_STATIC_ASSERT_MSG(std::is_constructible<U, double>::value, \"Uncertain types must be convertible to double!\");\n       return std::pair<unc<correlated>, unc<correlated> >(\n         (unc<correlated>)(a.first), (unc<correlated>)(static_cast<double>(a.second))\n         );\n    }\n\n    template <typename T>    //!< \\tparam T Any type that can be converted to double.\n    std::pair<unc<correlated>, unc<correlated> > operator()(T a)\n    {  //!< Convert a pair of X and Y uncertain type values to a @c std::pair of @c unc.\n      BOOST_STATIC_ASSERT_MSG(std::is_constructible<T, double>::value, \"Uncertain types must be convertible to double!\");\n      return std::pair<unc <correlated>, unc<correlated> >(i++, (unc<correlated>)a); //! \\return pair of unc.\n    }\n}; // class pair_unc_2d_convert\n\n /*! This functor allows any 2D data that can be converted to type @c std::pair<Meas, unc> to be plotted.\n   \\tparam correlated @c true if the uncertainties are correlated (for example, adding to a constant value).\n   */\ntemplate <bool correlated>\nclass pair_Meas_2d_convert\n{\npublic:\n    typedef std::pair<Meas, unc<correlated> > result_type;\n    //!< result type is pair of Meas (uncertain including datetime etc) and an uncertain value.\n\n    Meas i; //!< Current Meas (uncun + datetime etc) value.\n\n    void start(Meas i0)\n    { //!< Set a start value.\n       i = i0;\n    }\n    //!< Convert a pair of X and Y uncertain type values to a pair of uncertain types uncun.\n    //! \\return pair of Meas (an unc including time, ID and order info) & an unc.\n    //! Cast to double so that can potentially use with @c float, @c long double.\n    //!< \\tparam T type that can be converted to double.\n    //!< \\tparam U type that can be converted to uncertain type @c unc.\n    //! \\returns A @c std::pair of double precision data-point values.\n    template <typename T, typename U>\n    std::pair<Meas, unc<correlated> > operator()(const std::pair<T, U>& a) const\n    {  \n      BOOST_STATIC_ASSERT_MSG(std::is_constructible<T, double>::value, \"Uncertain types must be convertible to uncun!\");\n      BOOST_STATIC_ASSERT_MSG(std::is_constructible<U, double>::value, \"Uncertain types must be convertible to uncun!\");\n      return std::pair<Meas, unc<correlated> >((Meas)(static_cast<Meas>(a.first)), (unc<correlated>)(static_cast<unc<correlated>>(a.second)));\n    }\n\n    template <typename T>  //!< \\tparam T Any type that can be converted to uncun. \n    std::pair<Meas, unc<correlated> > operator()(T a)\n    {  //!< Convert a pair of X and Y uncertain type values to a pair of Meas & unc.\n        return std::pair<Meas, unc<correlated> >(i++, (unc<correlated>)(static_cast<double>(a)));\n        //! \\return pair of Meas & unc.\n    }\n}; // class pair_Meas_2d_convert\n\n /*! This functor allows any 2D data that can be converted to type double to be plotted.\n   \\tparam correlated @c true if the uncertainties are correlated (for example, adding up to a constant value).\n   */\ntemplate <bool correlated>\nclass pair_Meas_2d_double_convert\n{\npublic:\n //typedef std::pair<Meas, unc<correlated> > result_type;\n  typedef std::pair<double, double > result_type;\n  //!< result type is pair of double values.\n\n  Meas i; //!< Current Meas (uncun + datetime etc) value.\n\n  void start(Meas i0)\n  { //!< Set a start value.\n    i = i0;\n  }\n  //!< Convert a pair of X and Y uncertain type values to a pair of doubles.\n  //! \\return pair of Meas (unc including time, ID and order info) & an unc.\n  //! Cast to double so that can potentially use with float, long double.\n  //!< \\tparam T type that can be converted to double.\n  //!< \\tparam U type that can be converted to double.\n  //! \\returns A @c std::pair of @c double precision data-point values.\n  template <typename T, typename U>\n  std::pair<Meas, unc<correlated> > operator()(const std::pair<T, U>& a) const\n  {  \n    BOOST_STATIC_ASSERT_MSG(std::is_constructible<T, double>::value, \"Uncertain types must be convertible to double!\");\n    BOOST_STATIC_ASSERT_MSG(std::is_constructible<U, double>::value, \"Uncertain types must be convertible to double!\");\n     return std::pair<Meas, unc<correlated> >((Meas)(static_cast<Meas>(a.first)), (unc<correlated>)(static_cast<uncun>(a.second))); // OK uncertain values.\n     // but fails for \\boost\\libs\\svg_plot\\example\\convertible_to_double.cpp and this compiles\n     //return std::pair<Meas, unc<correlated> >((Meas)(static_cast<double>(a.first)), (unc<correlated>)(static_cast<double>(a.second)));\n     // but does not work for uncertainty displays.  Not fully understood.\n }\n\n  //! Convert a pair of X and Y uncertain type values to a pair of @c Meas & @c unc.\n  //! \\tparam T Any type that can be converted to @c double.\n  template <typename T>    \n  std::pair<Meas, unc<correlated> > operator()(T a)\n  {  \n    return std::pair<Meas, unc<correlated> >(i++, (unc<correlated>)(static_cast<double>(a)));\n    //! \\return pair of Meas & unc.\n  }\n}; // class pair_Meas_2d_double_convert\n\n} // namespace detail\n} // namespace svg\n} // namespace boost\n\n#endif // BOOST_SVG_DETAIL_FUNCTORS_HPP\n", "meta": {"hexsha": "75db0296afce15fd3c41295a5459bcd5aec37da1", "size": 12513, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/svg_plot/detail/functors.hpp", "max_stars_repo_name": "pabristow/svg_plot", "max_stars_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2016-03-09T03:23:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T14:02:07.000Z", "max_issues_repo_path": "include/boost/svg_plot/detail/functors.hpp", "max_issues_repo_name": "pabristow/svg_plot", "max_issues_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2018-03-05T14:39:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-22T09:00:33.000Z", "max_forks_repo_path": "include/boost/svg_plot/detail/functors.hpp", "max_forks_repo_name": "pabristow/svg_plot", "max_forks_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2016-11-04T14:36:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-17T08:12:03.000Z", "avg_line_length": 46.6902985075, "max_line_length": 155, "alphanum_fraction": 0.6978342524, "num_tokens": 3162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417487156366, "lm_q2_score": 0.7217431943271999, "lm_q1q2_score": 0.47520834038112375}}
{"text": "#include <gtest/gtest.h>\n#include \"humanoids/rave_to_rbdl.hpp\"\n#include <openrave-core.h>\n#include \"trajopt/configuration_space.hpp\"\n#include \"trajopt/rave_utils.hpp\"\n#include \"trajopt/utils.hpp\"\n#include <boost/foreach.hpp>\n#include \"utils/eigen_conversions.hpp\"\n#include \"utils/stl_to_string.hpp\"\n#include <iostream>\n#include \"osgviewer/osgviewer.hpp\"\n#include <Eigen/Geometry>\n#include <rbdl_utils.h>\n\nusing namespace std;\nusing namespace OpenRAVE;\nusing namespace trajopt;\nusing namespace util;\nusing namespace Eigen;\n\nVector3d axisAngleToEulerZYX(const Vector3d& in) {\n  double rx = in(0), ry = in(1), rz = in(2);\n  Matrix3d mat = toMatrix3d(OpenRAVE::geometry::matrixFromAxisAngle(OpenRAVE::Vector(rx, ry, rz)));\n  return mat.eulerAngles(2,1,0);\n}\nVector3d eulerZYXtoAxisAngle(const Vector3d& in) {\n  double rz = in(0), ry = in(1), rx = in(2);\n  Matrix3d mat; mat = AngleAxisd(rz, Vector3d::UnitZ())\n               * AngleAxisd(ry, Vector3d::UnitY())\n               * AngleAxisd(rx, Vector3d::UnitX());\n  OpenRAVE::TransformMatrix tm;\n  tm.rotfrommat(mat(0,0), mat(0,1), mat(0,2), mat(1,0), mat(1,1), mat(1,2), mat(2,0), mat(2,1), mat(2,2));\n  return toVector3d(OpenRAVE::geometry::axisAngleFromMatrix(tm));\n\n}\n\nVectorXd toRBDLOrder(const DblVec& _x) {\n  VectorXd x = toVectorXd(_x);\n  int n = x.size();\n  VectorXd y(n);\n  y.topRows(3) = x.middleRows(n-6,3);\n  y.middleRows(3,3) = axisAngleToEulerZYX(x.bottomRows(3));\n  y.bottomRows(n-6) = x.topRows(n-6);\n  return y;\n}\nDblVec toRaveOrder(const VectorXd& x) {\n  int n = x.size();\n  VectorXd y(x.size());\n  y.topRows(n-6) = x.bottomRows(n-6);\n  y.middleRows(n-6,3) = x.topRows(3);\n  y.bottomRows(3) = eulerZYXtoAxisAngle(x.middleRows(3,3));\n  return toDblVec(y);\n}\n\n\n#define EXPECT_MATRIX_NEAR(_mat0, _mat1, abstol) do {\\\n    Eigen::MatrixXd mat0=_mat0, mat1=_mat1;\\\n    ASSERT_TRUE(mat0.rows() == mat1.rows());\\\n    ASSERT_TRUE(mat0.cols() == mat1.cols());\\\n    bool fail = false;\\\n    for (int i=0; i < mat0.rows(); ++i) {\\\n      for (int j=0; j < mat0.cols(); ++j) {\\\n        if (fabs(mat0(i,j) - mat1(i,j)) > abstol) {\\\n          fail = true;\\\n        }\\\n      }\\\n    }\\\n    if (fail) {\\\n      char msg[1000];\\\n      sprintf(msg, \"%s !=\\n %s    (tol %.2e) at %s:%i\\n\", CSTR(mat0), CSTR(mat1), abstol, __FILE__, __LINE__);\\\n      GTEST_NONFATAL_FAILURE_(msg);\\\n    }\\\n} while(0)\n\nTEST(math, rotation_conversion) {\n  {\n    Vector3d x = Vector3d::Random();\n    EXPECT_MATRIX_NEAR(x, axisAngleToEulerZYX(eulerZYXtoAxisAngle(x)),1e-6);\n    EXPECT_MATRIX_NEAR(x, eulerZYXtoAxisAngle(axisAngleToEulerZYX(x)),1e-6);\n  }\n  {\n    VectorXd x = VectorXd::Random(40);\n    EXPECT_MATRIX_NEAR(x, toVectorXd(toRaveOrder(toRBDLOrder(toDblVec(x)))),1e-6);\n    EXPECT_MATRIX_NEAR(x, toRBDLOrder(toRaveOrder(x)),1e-6);\n  }\n}\n\nTEST(fixed_base, kinematics) {\n  /**\n   *\n   * Check to see that OpenRAVE kinematics gives the same result as RBDL kinematics on fixed-base robot\n   */\n  EnvironmentBasePtr env = RaveCreateEnvironment();\n  env->StopSimulation();\n  env->Load(\"robots/pr2-beta-static.zae\");\n  RobotBasePtr robot = GetRobot(*env);\n  vector<int> inds;\n  for (int i=0; i < robot->GetDOF(); ++i) inds.push_back(i);\n  RobotAndDOFPtr rad(new RobotAndDOF(robot, inds));\n  DblVec dofvals = rad->RandomDOFValues();\n\n\n  robot->SetDOFValues(dofvals,true);\n\n  std::map<KinBody::LinkPtr, unsigned> link2id;\n  boost::shared_ptr<rbd::Model> model = MakeRBDLModel(robot, false, link2id);\n  rbd::Math::VectorNd Q = toVectorXd(dofvals);\n  rbd::UpdateKinematicsCustom(*model, &Q, NULL, NULL);\n\n  cout << \"model hier\\n\" << rbd::Utils::GetModelHierarchy (*model) << endl;\n  cout << \"model dof overview\\n\" << rbd::Utils::GetModelDOFOverview (*model) << endl;\n  cout << \"named bodies\\n\" << rbd::Utils::GetNamedBodyOriginsOverview(*model) << endl;\n\n  BOOST_FOREACH(KinBody::JointPtr joint, robot->GetJoints()) {\n    KinBody::LinkPtr childLink = joint->GetHierarchyChildLink();\n    int i = link2id[childLink];\n    cout << childLink->GetName() << \" \" << childLink->GetTransform() <<  endl;\n    DblVec vals;\n    joint->GetValues(vals);\n    cout << \"vasls: \" << vals[0] << endl;\n    EXPECT_MATRIX_NEAR(toVector3d((toRave(model->X_base[i]) * joint->GetInternalHierarchyRightTransform()).trans),\n        toVector3d(childLink->GetTransform().trans), 1e-4);\n    EXPECT_MATRIX_NEAR(toMatrix3d(toRave(model->X_base[i]) * joint->GetInternalHierarchyRightTransform()),\n        toMatrix3d(childLink->GetTransform()), 1e-4);\n\n  }\n  RaveDestroy();\n}\n\n\nTEST(floating_base, kinematics) {\n\n  EnvironmentBasePtr env = RaveCreateEnvironment();\n  env->StopSimulation();\n  env->Load(string(BIGDATA_DIR) + \"/atlas.xml\");\n  RobotBasePtr robot = GetRobot(*env);\n  DblVec lower(robot->GetDOF(), -1000);\n  DblVec upper(robot->GetDOF(), 1000);\n  robot->SetDOFLimits(lower, upper);\n\n\n  vector<int> inds;\n  for (int i=0; i < robot->GetDOF(); ++i) inds.push_back(i);\n  RobotAndDOFPtr rad(new RobotAndDOF(robot, inds, OpenRAVE::DOF_XYZ | OpenRAVE::DOF_Rotation3D));\n  DblVec dofvals = rad->RandomDOFValues();\n  rad->SetDOFValues(dofvals);\n\n  std::map<KinBody::LinkPtr, unsigned> link2id;\n  boost::shared_ptr<rbd::Model> model = MakeRBDLModel(robot, true, link2id);\n  rbd::Math::VectorNd Q = toRBDLOrder(dofvals);\n  rbd::UpdateKinematicsCustom(*model, &Q, NULL, NULL);\n\n  cout << Q.transpose() << endl;\n  cout << Str(rad->GetDOFValues()) << endl;\n\n  BOOST_FOREACH(KinBody::JointPtr joint, robot->GetJoints()) {\n    KinBody::LinkPtr childLink = joint->GetHierarchyChildLink();\n    int i = link2id[childLink];\n    cout << childLink->GetName() << endl;\n    EXPECT_MATRIX_NEAR(toVector3d((toRave(model->X_base[i]) * joint->GetInternalHierarchyRightTransform()).trans),\n        toVector3d(childLink->GetTransform().trans), 1e-4);\n    EXPECT_MATRIX_NEAR(toMatrix3d(toRave(model->X_base[i]) * joint->GetInternalHierarchyRightTransform()),\n        toMatrix3d(childLink->GetTransform()), 1e-4);\n  }\n  RaveDestroy();\n}\n\n\n\n\nTEST(fixed_base, dynamics) {\n  /**\n   *\n   * Simulate fixed-base robot\n   */\n  EnvironmentBasePtr env = RaveCreateEnvironment();\n  env->StopSimulation();\n  env->Load(\"robots/puma.robot.xml\");\n  RobotBasePtr robot = GetRobot(*env);\n\n  std::map<KinBody::LinkPtr, unsigned> link2id;\n  boost::shared_ptr<rbd::Model> model = MakeRBDLModel(robot, false, link2id);\n\n  VectorXd Q = VectorXd::Zero(model->dof_count);\n  VectorXd QD = VectorXd::Zero(model->dof_count);\n  VectorXd QDD = VectorXd::Zero(model->dof_count);\n  VectorXd Tau = VectorXd::Zero(model->dof_count);\n\n  OSGViewerPtr viewer = OSGViewer::GetOrCreate(env);\n\n\n  float dt = .01;\n  for (int i=0; i < 100; ++i) {\n    rbd::ForwardDynamics(*model, Q, QD, Tau, QDD, NULL);\n    Q += QD * dt;\n    QD += QDD * dt;\n    robot->SetDOFValues(toDblVec(Q), false);\n    viewer->Idle();\n  }\n  RaveDestroy();\n\n\n}\n\n\n\nTEST(floating_base, dynamics) {\n  /**\n   *\n   * Simulate fixed-base robot\n   */\n  EnvironmentBasePtr env = RaveCreateEnvironment();\n  env->StopSimulation();\n  env->Load(string(BIGDATA_DIR)+\"/atlas.xml\");\n  RobotBasePtr robot = GetRobot(*env);\n  DblVec lower(robot->GetDOF(), -10000);\n  DblVec upper(robot->GetDOF(), 10000);\n  robot->SetDOFLimits(lower, upper);\n\n  vector<int> inds;\n  for (int i=0; i < robot->GetDOF(); ++i) inds.push_back(i);\n  RobotAndDOFPtr rad(new RobotAndDOF(robot, inds, OpenRAVE::DOF_XYZ | OpenRAVE::DOF_Rotation3D));\n\n  std::map<KinBody::LinkPtr, unsigned> link2id;\n  boost::shared_ptr<rbd::Model> model = MakeRBDLModel(robot, true, link2id);\n\n  VectorXd Q = VectorXd::Zero(model->dof_count);\n  VectorXd QD = VectorXd::Zero(model->dof_count);\n  VectorXd QDD = VectorXd::Zero(model->dof_count);\n  VectorXd Tau = VectorXd::Zero(model->dof_count);\n\n  OSGViewerPtr viewer = OSGViewer::GetOrCreate(env);\n\n  vector<rbdmath::SpatialVector> f_ext(model->f.size(), rbdmath::SpatialVectorZero);\n\n  KinBody::LinkPtr l_foot = robot->GetLink(\"l_foot\");\n\n  float dt = .005;\n  for (int i=0; i < 1000; ++i) {\n\n    OpenRAVE::Transform body_frame = robot->GetTransform();\n    Vector3d l_foot_pos = toVector3d( (body_frame.inverse()*l_foot->GetTransform()).trans);\n    Vector3d l_foot_force = toMatrix3d(body_frame).inverse() * Vector3d(0,0,10);\n    cout << l_foot_force.transpose() << endl;\n    cout << l_foot_pos.transpose() << endl;\n//    f_ext[link2id[l_foot]] = concat(l_foot_force, l_foot_force.cross(l_foot_pos));\n    Vector3d l_foot_force2(0,0,10);\n    f_ext[link2id[l_foot]] = concat(l_foot_force2,toVector3d(l_foot->GetTransform().trans).cross( l_foot_force2)) ;\n\n\n    Tau = -QD*.1;\n    rbd::ForwardDynamics(*model, Q, QD, Tau, QDD, &f_ext);\n    Q += QD * dt;\n    QD += QDD * dt;\n    rad->SetDOFValues(toRaveOrder(Q));\n    viewer->Idle();\n  }\n  RaveDestroy();\n\n\n}\n\nTEST(fixed_base, invdynamics) {\n\n  EnvironmentBasePtr env = RaveCreateEnvironment();\n  env->StopSimulation();\n  env->Load(\"robots/puma.robot.xml\");\n  RobotBasePtr robot = GetRobot(*env);\n\n  std::map<KinBody::LinkPtr, unsigned> link2id;\n  boost::shared_ptr<rbd::Model> model = MakeRBDLModel(robot, false, link2id);\n\n  VectorXd Q = VectorXd::Zero(robot->GetDOF());\n  VectorXd QDot = VectorXd::Zero(robot->GetDOF());\n  VectorXd QDDot = VectorXd::Zero(robot->GetDOF());\n  VectorXd Tau = VectorXd::Zero(robot->GetDOF());\n  rbd::InverseDynamics(*model, Q, QDot, QDDot, Tau, NULL);\n  DblVec tau_rave;\n  robot->SetDOFVelocities(toDblVec(QDot));\n  robot->ComputeInverseDynamics(tau_rave, toDblVec(QDDot));\n  EXPECT_MATRIX_NEAR(toVectorXd(tau_rave), Tau, 1e-4);\n}\n\n\nint main(int argc, char** argv)\n{\n  ::testing::InitGoogleTest(&argc, argv);\n  RaveInitialize(false);\n\n  return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "6e5711decea904bdcbf35e260db8dd73c9ac5787", "size": 9523, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/humanoids/rbdl-unit.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/rbdl-unit.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/rbdl-unit.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": 32.6130136986, "max_line_length": 115, "alphanum_fraction": 0.6786726872, "num_tokens": 3019, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056295505783, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.47514224653058035}}
{"text": "/* Copyright (C) 2019 IBM Corp.\n * This program is Licensed under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *   http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License. See accompanying LICENSE file.\n */\n\n#include <gtest/gtest.h>\n#include <NTL/ZZX.h>\n#include <helib/Context.h>\n#include <helib/PolyModRing.h>\n#include <helib/EncryptedArray.h>\n#include <helib/exceptions.h>\n\nnamespace {\n\nTEST(TestPolyModRing, canBeConstructed)\n{\n  const long p = 5;\n  const long r = 3;\n  NTL::ZZX G;\n  NTL::SetCoeff(G, 1, 1);\n  NTL::SetCoeff(G, 0, -1);\n  helib::PolyModRing poly(p, r, G);\n  EXPECT_EQ(poly.p, p);\n  EXPECT_EQ(poly.r, r);\n  EXPECT_EQ(poly.G, G);\n  EXPECT_EQ(poly.p2r, pow(p, r));\n}\n\nTEST(TestPolyModRing, canBeCopyConstructed)\n{\n  const long p = 5;\n  const long r = 3;\n  NTL::ZZX G;\n  NTL::SetCoeff(G, 1, 1);\n  NTL::SetCoeff(G, 0, -1);\n  helib::PolyModRing poly(p, r, G);\n  helib::PolyModRing copy(poly);\n  EXPECT_EQ(poly, copy);\n}\n\nTEST(TestPolyModRing, canBeMoveConstructed)\n{\n  const long p = 5;\n  const long r = 3;\n  NTL::ZZX G;\n  NTL::SetCoeff(G, 1, 1);\n  NTL::SetCoeff(G, 0, -1);\n  helib::PolyModRing poly(p, r, G);\n  helib::PolyModRing copied(poly);\n  helib::PolyModRing moved(std::move(poly));\n  EXPECT_EQ(copied, moved);\n}\n\nTEST(TestPolyModRing, equalsAndNotEqualsAreCorrect)\n{\n  const long p = 5;\n  const long r = 3;\n  NTL::ZZX G;\n  NTL::SetCoeff(G, 1, 1);\n  NTL::SetCoeff(G, 0, -1);\n  helib::PolyModRing poly1(p, r, G);\n  helib::PolyModRing poly2(p + 2, r, G);\n  helib::PolyModRing poly3(p, r + 2, G);\n  helib::PolyModRing poly4(p, r, G + 2);\n  helib::PolyModRing polyA(p, r, G);\n\n  EXPECT_EQ(poly1, polyA);\n  EXPECT_FALSE(poly1 != polyA);\n\n  EXPECT_NE(poly1, poly2);\n  EXPECT_NE(poly1, poly3);\n  EXPECT_NE(poly1, poly4);\n\n  EXPECT_FALSE(poly1 == poly2);\n  EXPECT_FALSE(poly1 == poly3);\n  EXPECT_FALSE(poly1 == poly4);\n}\n\n} // namespace\n", "meta": {"hexsha": "4338909bd7a943f977a1c8c1d03c75c73189e2ea", "size": 2272, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/TestPolyModRing.cpp", "max_stars_repo_name": "lparth/homeenc-HElib", "max_stars_repo_head_hexsha": "072ffc8af2662876c445ad5ae8614ca65f20c10b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-02-06T09:26:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-06T09:26:23.000Z", "max_issues_repo_path": "tests/TestPolyModRing.cpp", "max_issues_repo_name": "lparth/homeenc-HElib", "max_issues_repo_head_hexsha": "072ffc8af2662876c445ad5ae8614ca65f20c10b", "max_issues_repo_licenses": ["Apache-2.0"], "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/TestPolyModRing.cpp", "max_forks_repo_name": "lparth/homeenc-HElib", "max_forks_repo_head_hexsha": "072ffc8af2662876c445ad5ae8614ca65f20c10b", "max_forks_repo_licenses": ["Apache-2.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.1149425287, "max_line_length": 75, "alphanum_fraction": 0.681778169, "num_tokens": 741, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056040203135, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.47514222453288657}}
{"text": "//=======================================================================\r\n// Copyright 2001 Jeremy G. Siek, Andrew Lumsdaine, Lie-Quan Lee, \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, Indiana University,\r\n// Bloomington, IN 47405.\r\n//\r\n// Permission to modify the code and to distribute the code is\r\n// granted, provided the text of this NOTICE is retained, a notice if\r\n// the code was modified is included with the above COPYRIGHT NOTICE\r\n// and with the COPYRIGHT NOTICE in the LICENSE file, and that the\r\n// LICENSE 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#include <boost/config.hpp>\r\n#include <vector>\r\n#include <deque>\r\n#include <boost/graph/topological_sort.hpp>\r\n#include <boost/graph/adjacency_list.hpp>\r\nint\r\nmain()\r\n{\r\n  using namespace boost;\r\n  const char *tasks[] = {\r\n    \"pick up kids from school\",\r\n    \"buy groceries (and snacks)\",\r\n    \"get cash at ATM\",\r\n    \"drop off kids at soccer practice\",\r\n    \"cook dinner\",\r\n    \"pick up kids from soccer\",\r\n    \"eat dinner\"\r\n  };\r\n  const int n_tasks = sizeof(tasks) / sizeof(char *);\r\n\r\n  adjacency_list < listS, vecS, directedS > g(n_tasks);\r\n\r\n  add_edge(0, 3, g);\r\n  add_edge(1, 3, g);\r\n  add_edge(1, 4, g);\r\n  add_edge(2, 1, g);\r\n  add_edge(3, 5, g);\r\n  add_edge(4, 6, g);\r\n  add_edge(5, 6, g);\r\n\r\n  std::deque < int >topo_order;\r\n\r\n  topological_sort(g, std::front_inserter(topo_order),\r\n                   vertex_index_map(identity_property_map()));\r\n\r\n  int n = 1;\r\n  for (std::deque < int >::iterator i = topo_order.begin();\r\n       i != topo_order.end(); ++i, ++n)\r\n    std::cout << tasks[*i] << std::endl;\r\n\r\n  return EXIT_SUCCESS;\r\n}\r\n", "meta": {"hexsha": "e349b5f4e78abd50f643721a43dcac04d52e4a0c", "size": 2265, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sdk/boost_1_30_0/libs/graph/example/topo-sort2.cpp", "max_stars_repo_name": "acidicMercury8/xray-1.0", "max_stars_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-01-30T12:51:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-31T08:36:49.000Z", "max_issues_repo_path": "sdk/boost_1_30_0/libs/graph/example/topo-sort2.cpp", "max_issues_repo_name": "acidicMercury8/xray-1.0", "max_issues_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_issues_repo_licenses": ["Linux-OpenIB"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sdk/boost_1_30_0/libs/graph/example/topo-sort2.cpp", "max_forks_repo_name": "acidicMercury8/xray-1.0", "max_forks_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.3181818182, "max_line_length": 74, "alphanum_fraction": 0.6304635762, "num_tokens": 546, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.689305616785446, "lm_q2_score": 0.6893056040203135, "lm_q1q2_score": 0.47514222453288657}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   tstGaussKronrodIntegrator.cpp\n//! \\author Luke Kersting\n//! \\brief  Gauss-Kronrod quadrature integrator unit tests.\n//!\n//---------------------------------------------------------------------------//\n\n// Std Lib Includes\n#include <iostream>\n#include <limits>\n#include <stdexcept>\n\n// Boost Includes\n#include <boost/function.hpp>\n#include <boost/bind.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/math/tools/precision.hpp>\n\n// FRENSIE Includes\n#include \"Utility_GaussKronrodIntegrator.hpp\"\n#include \"Utility_Vector.hpp\"\n#include \"Utility_ArrayView.hpp\"\n#include \"Utility_TypeNameTraits.hpp\"\n#include \"Utility_UnitTestHarnessWithMain.hpp\"\n\n//---------------------------------------------------------------------------//\n// Testing Types\n//---------------------------------------------------------------------------//\n\ntypedef boost::multiprecision::cpp_dec_float_50 long_float;\n\nstruct X2Functor\n{\n  double operator()( const double x ) const\n  {\n    if( x >= 0.0 && x <= 1.0 )\n      return x*x;\n    else\n      return 0.0;\n  }\n\n  static double getIntegratedValue()\n  {\n    return 1.0/3.0;\n  }\n\n  static double getLowerIntegratedValue()\n  {\n    return 1.0/24.0;\n  }\n\n  static double getUpperIntegratedValue()\n  {\n    return 7.0/24.0;\n  }\n};\n\nstruct X2FunctorParameter\n{\n  double operator()( const double x, const double y ) const\n  {\n    if( y >= 0.0 && y <= 1.0 )\n      return y*y*x;\n    else\n      return 0.0;\n  }\n\n  static double getIntegratedValue()\n  {\n    return 1.0/3.0;\n  }\n\n  static double getLowerIntegratedValue()\n  {\n    return 1.0/24.0;\n  }\n\n  static double getUpperIntegratedValue()\n  {\n    return 7.0/24.0;\n  }\n};\n\nstruct X2FunctorLong\n{\n  long double operator()( const long double x ) const\n  {\n    if( x >= 0.0L && x <= 1.0L )\n      return x*x;\n    else\n      return 0.0L;\n  }\n\n  static long double getIntegratedValue()\n  {\n    return 1.0L/3.0L;\n  }\n\n  static long double getLowerIntegratedValue()\n  {\n    return 1.0L/24.0L;\n  }\n\n  static long double getUpperIntegratedValue()\n  {\n    return 7.0L/24.0L;\n  }\n};\n\nstruct X2FunctorBoost\n{\n  long_float operator()( const long_float x ) const\n  {\n    if( x >= 0.0L && x <= 1.0L )\n      return x*x;\n    else\n      return 0.0L;\n  }\n\n  static long_float getIntegratedValue()\n  {\n    return 1.0L/3.0L;\n  }\n\n  static long_float getLowerIntegratedValue()\n  {\n    return 1.0L/24.0L;\n  }\n\n  static long_float getUpperIntegratedValue()\n  {\n    return 7.0L/24.0L;\n  }\n};\n\nstruct X3Functor\n{\n  double operator()( const double x ) const\n  {\n    if( x >= 0.0 && x <= 1.0 )\n      return x*x*x;\n    else\n      return 0.0;\n  }\n\n  static double getIntegratedValue()\n  {\n    return 0.25;\n  }\n\n  static double getLowerIntegratedValue()\n  {\n    return 1.0/64.0;\n  }\n\n  static double getUpperIntegratedValue()\n  {\n    return 15.0/64.0;\n  }\n};\n\nstruct X3FunctorParameter\n{\n  double operator()( const double x, const double y ) const\n  {\n    if( y >= 0.0 && y <= 1.0 )\n      return y*y*y*x;\n    else\n      return 0.0;\n  }\n\n  static double getIntegratedValue()\n  {\n    return 0.25;\n  }\n\n  static double getLowerIntegratedValue()\n  {\n    return 1.0/64.0;\n  }\n\n  static double getUpperIntegratedValue()\n  {\n    return 15.0/64.0;\n  }\n};\n\nstruct X3FunctorLong\n{\n  long double operator()( const long double x ) const\n  {\n    if( x >= 0.0L && x <= 1.0L )\n      return x*x*x;\n    else\n      return 0.0L;\n  }\n\n  static long double getIntegratedValue()\n  {\n    return 0.25L;\n  }\n\n  static long double getLowerIntegratedValue()\n  {\n    return 1.0L/64.0L;\n  }\n\n  static long double getUpperIntegratedValue()\n  {\n    return 15.0L/64.0L;\n  }\n};\n\nstruct X3FunctorBoost\n{\n  long_float operator()( const long_float x ) const\n  {\n    if( x >= 0.0L && x <= 1.0L )\n      return x*x*x;\n    else\n      return 0.0L;\n  }\n\n  static long_float getIntegratedValue()\n  {\n    return 0.25L;\n  }\n\n  static long_float getLowerIntegratedValue()\n  {\n    return 1.0L/64.0L;\n  }\n\n  static long_float getUpperIntegratedValue()\n  {\n    return 15.0L/64.0L;\n  }\n};\n\nnamespace Utility{\n\nTYPE_NAME_TRAITS_QUICK_DECL( boost::multiprecision::cpp_dec_float_50 );\nTYPE_NAME_TRAITS_QUICK_DECL( X2Functor );\nTYPE_NAME_TRAITS_QUICK_DECL( X2FunctorParameter );\nTYPE_NAME_TRAITS_QUICK_DECL( X2FunctorLong );\nTYPE_NAME_TRAITS_QUICK_DECL( X2FunctorBoost );\nTYPE_NAME_TRAITS_QUICK_DECL( X3Functor );\nTYPE_NAME_TRAITS_QUICK_DECL( X3FunctorParameter );\nTYPE_NAME_TRAITS_QUICK_DECL( X3FunctorLong );\nTYPE_NAME_TRAITS_QUICK_DECL( X3FunctorBoost );\n\n} // end Utility namespace\n\ntypedef std::tuple<X2Functor,X3Functor> TestFunctors;\ntypedef std::tuple<X2FunctorLong,X3FunctorLong> TestFunctorsLong;\ntypedef std::tuple<X2FunctorBoost,X3FunctorBoost> TestFunctorsBoost;\ntypedef std::tuple<X2FunctorParameter,X3FunctorParameter> TestFunctorsParameter;\n\n//---------------------------------------------------------------------------//\n// Testing Functions\n//---------------------------------------------------------------------------//\n\ndouble exp_neg_x( const double x )\n{\n  return exp( -x );\n}\n\ndouble exp_neg_abs_x( const double x, const double a )\n{\n  return exp( -a*fabs(x) );\n}\n\ndouble inv_sqrt_abs_x( const double x )\n{\n  return 1/sqrt(fabs(x));\n}\n\n//---------------------------------------------------------------------------//\n// Testing Structs.\n//---------------------------------------------------------------------------//\nclass TestGaussKronrodIntegrator : public Utility::GaussKronrodIntegrator<double>\n{\npublic:\n  TestGaussKronrodIntegrator( const double relative_error_tol )\n    : Utility::GaussKronrodIntegrator<double>( relative_error_tol )\n  { /* ... */ }\n\n  ~TestGaussKronrodIntegrator()\n  { /* ... */ }\n\n  // Allow public access to the GaussKronrodIntegrator protected member functions\n  using Utility::GaussKronrodIntegrator<double>::calculateQuadratureIntegrandValuesAtAbscissa;\n  using Utility::GaussKronrodIntegrator<double>::bisectAndIntegrateBinInterval;\n  using Utility::GaussKronrodIntegrator<double>::rescaleAbsoluteError;\n  using Utility::GaussKronrodIntegrator<double>::subintervalTooSmall;\n  using Utility::GaussKronrodIntegrator<double>::checkRoundoffError;\n  using Utility::GaussKronrodIntegrator<double>::sortBins;\n  using Utility::GaussKronrodIntegrator<double>::getWynnEpsilonAlgorithmExtrapolation;\n};\n\n//---------------------------------------------------------------------------//\n// Tests\n//---------------------------------------------------------------------------//\n// Check that functions can be integrated over [0,1]\nFRENSIE_UNIT_TEST_TEMPLATE( GaussKronrodIntegrator,\n                            integrateWithPointRule,\n                            TestFunctors )\n{\n  FETCH_TEMPLATE_PARAM( 0, Functor );\n\n  Utility::GaussKronrodIntegrator<double> gk_integrator( 1e-12 );\n\n  double absolute_error, result_abs, result_asc, test_result, tol;\n  double result;\n\n  Functor functor_instance;\n\n  gk_integrator.integrateWithPointRule<15>( functor_instance,\n                                        0.0,\n                                        1.0,\n                                        result,\n                                        absolute_error,\n                                        result_abs,\n                                        result_asc );\n\n  tol = absolute_error/result;\n  test_result = result;\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( Functor::getIntegratedValue(), test_result, tol );\n\n  gk_integrator.integrateWithPointRule<21>( functor_instance,\n                                        0.0,\n                                        1.0,\n                                        result,\n                                        absolute_error,\n                                        result_abs,\n                                        result_asc );\n\n  tol = absolute_error/result;\n  test_result = result;\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( Functor::getIntegratedValue(), test_result, tol );\n\n  gk_integrator.integrateWithPointRule<31>( functor_instance,\n                                        0.0,\n                                        1.0,\n                                        result,\n                                        absolute_error,\n                                        result_abs,\n                                        result_asc );\n\n  tol = absolute_error/result;\n  test_result = result;\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( Functor::getIntegratedValue(), test_result, tol );\n\n  gk_integrator.integrateWithPointRule<41>( functor_instance,\n                                        0.0,\n                                        1.0,\n                                        result,\n                                        absolute_error,\n                                        result_abs,\n                                        result_asc );\n\n  tol = absolute_error/result;\n  test_result = result;\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( Functor::getIntegratedValue(), test_result, tol );\n\n  gk_integrator.integrateWithPointRule<51>( functor_instance,\n                                        0.0,\n                                        1.0,\n                                        result,\n                                        absolute_error,\n                                        result_abs,\n                                        result_asc );\n\n  tol = absolute_error/result;\n  test_result = result;\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( Functor::getIntegratedValue(), test_result, tol );\n\n  gk_integrator.integrateWithPointRule<61>( functor_instance,\n                                        0.0,\n                                        1.0,\n                                        result,\n                                        absolute_error,\n                                        result_abs,\n                                        result_asc );\n\n  tol = absolute_error/result;\n  test_result = result;\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( Functor::getIntegratedValue(), test_result, tol );\n}\n\n//---------------------------------------------------------------------------//\n// Check that quadrature integrand values can be evaluated at abscissa\nFRENSIE_UNIT_TEST_TEMPLATE( GaussKronrodIntegrator,\n                            calculateQuadratureIntegrandValuesAtAbscissa,\n                            TestFunctors )\n{\n  FETCH_TEMPLATE_PARAM( 0, Functor );\n\n  TestGaussKronrodIntegrator test_integrator( 1e-12 );\n\n  double half_length = 0.5;\n  double midpoint = 0.5;\n  double abscissa = 0.5;\n\n  double integrand_value_lower, integrand_value_upper ;\n\n  Functor functor_instance;\n\n  test_integrator.calculateQuadratureIntegrandValuesAtAbscissa(\n                functor_instance,\n                abscissa,\n                half_length,\n                midpoint,\n                integrand_value_lower,\n                integrand_value_upper );\n\n\n  double tol = 1e-12;\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( functor_instance( 0.25 ), integrand_value_lower, tol );\n  FRENSIE_CHECK_FLOATING_EQUALITY( functor_instance( 0.75 ), integrand_value_upper, tol );\n}\n\n//---------------------------------------------------------------------------//\n// Check that quadrature integrand can be bisected and integrated\nFRENSIE_UNIT_TEST_TEMPLATE( GaussKronrodIntegrator,\n                            bisectAndIntegrateBinInterval,\n                            TestFunctors )\n{\n  FETCH_TEMPLATE_PARAM( 0, Functor );\n\n  TestGaussKronrodIntegrator test_integrator( 1e-12 );\n\n  Utility::BinTraits<double> bin, bin_1, bin_2;\n\n  double bin_1_asc, bin_2_asc, tol_1, tol_2;\n\n  bin.lower_limit = 0.0;\n  bin.upper_limit = 1.0;\n\n\n  Functor functor_instance;\n\n  test_integrator.bisectAndIntegrateBinInterval<15>(\n                functor_instance,\n                bin,\n                bin_1,\n                bin_2,\n                bin_1_asc,\n                bin_2_asc );\n\n  tol_1 = bin_1.error/bin_1.result;\n  tol_2 = bin_2.error/bin_2.result;\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( Functor::getLowerIntegratedValue(),\n                          static_cast<double>( bin_1.result ),\n                          tol_1 );\n  FRENSIE_CHECK_FLOATING_EQUALITY( Functor::getUpperIntegratedValue(),\n                          static_cast<double>( bin_2.result ),\n                          tol_2 );\n\n  FRENSIE_CHECK_EQUAL( bin_1.lower_limit, bin.lower_limit );\n  FRENSIE_CHECK_FLOATING_EQUALITY( bin_1.upper_limit, 0.5, 1e-15);\n  FRENSIE_CHECK_FLOATING_EQUALITY( bin_2.lower_limit, 0.5, 1e-15 );\n  FRENSIE_CHECK_EQUAL( bin_2.upper_limit, bin.upper_limit );\n\n\n  test_integrator.bisectAndIntegrateBinInterval<21>(\n                functor_instance,\n                bin,\n                bin_1,\n                bin_2,\n                bin_1_asc,\n                bin_2_asc );\n\n  tol_1 = bin_1.error/bin_1.result;\n  tol_2 = bin_2.error/bin_2.result;\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( Functor::getLowerIntegratedValue(),\n                          static_cast<double>( bin_1.result ),\n                          tol_1 );\n  FRENSIE_CHECK_FLOATING_EQUALITY( Functor::getUpperIntegratedValue(),\n                          static_cast<double>( bin_2.result ),\n                          tol_2 );\n\n\n  test_integrator.bisectAndIntegrateBinInterval<31>(\n                functor_instance,\n                bin,\n                bin_1,\n                bin_2,\n                bin_1_asc,\n                bin_2_asc );\n\n  tol_1 = bin_1.error/bin_1.result;\n  tol_2 = bin_2.error/bin_2.result;\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( Functor::getLowerIntegratedValue(),\n                          static_cast<double>( bin_1.result ),\n                          tol_1 );\n  FRENSIE_CHECK_FLOATING_EQUALITY( Functor::getUpperIntegratedValue(),\n                          static_cast<double>( bin_2.result ),\n                          tol_2 );\n\n\n  test_integrator.bisectAndIntegrateBinInterval<41>(\n                functor_instance,\n                bin,\n                bin_1,\n                bin_2,\n                bin_1_asc,\n                bin_2_asc );\n\n  tol_1 = bin_1.error/bin_1.result;\n  tol_2 = bin_2.error/bin_2.result;\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( Functor::getLowerIntegratedValue(),\n                          static_cast<double>( bin_1.result ),\n                          tol_1 );\n  FRENSIE_CHECK_FLOATING_EQUALITY( Functor::getUpperIntegratedValue(),\n                          static_cast<double>( bin_2.result ),\n                          tol_2 );\n\n\n  test_integrator.bisectAndIntegrateBinInterval<51>(\n                functor_instance,\n                bin,\n                bin_1,\n                bin_2,\n                bin_1_asc,\n                bin_2_asc );\n\n  tol_1 = bin_1.error/bin_1.result;\n  tol_2 = bin_2.error/bin_2.result;\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( Functor::getLowerIntegratedValue(),\n                          static_cast<double>( bin_1.result ),\n                          tol_1 );\n  FRENSIE_CHECK_FLOATING_EQUALITY( Functor::getUpperIntegratedValue(),\n                          static_cast<double>( bin_2.result ),\n                          tol_2 );\n\n\n  test_integrator.bisectAndIntegrateBinInterval<61>(\n                functor_instance,\n                bin,\n                bin_1,\n                bin_2,\n                bin_1_asc,\n                bin_2_asc );\n\n  tol_1 = bin_1.error/bin_1.result;\n  tol_2 = bin_2.error/bin_2.result;\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( Functor::getLowerIntegratedValue(),\n                          static_cast<double>( bin_1.result ),\n                          tol_1 );\n  FRENSIE_CHECK_FLOATING_EQUALITY( Functor::getUpperIntegratedValue(),\n                          static_cast<double>( bin_2.result ),\n                          tol_2 );\n}\n\n//---------------------------------------------------------------------------//\n// Check that the error can be re-scaled\nFRENSIE_UNIT_TEST( GaussKronrodIntegrator,\n                   rescaleAbsoluteError )\n{\n  TestGaussKronrodIntegrator test_integrator( 1e-12 );\n\n  double absolute_error = 0.0;\n  double result_abs = 0.0;\n  double result_asc = 0.0;\n  double tol = 1e-12;\n  double limit = std::numeric_limits<double>::min() / ( 50.0 *\n                   std::numeric_limits<double>::epsilon() );\n\n  absolute_error = limit/2.0;\n\n  test_integrator.rescaleAbsoluteError(\n                absolute_error,\n                result_abs,\n                result_asc );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( limit/2.0, absolute_error, tol );\n\n\n  absolute_error = 1.0;\n  result_asc = 2.0;\n\n  test_integrator.rescaleAbsoluteError(\n                absolute_error,\n                result_abs,\n                result_asc );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( 2.0, absolute_error, tol );\n\n\n  absolute_error = 1.0;\n  result_asc = 800.0;\n\n  test_integrator.rescaleAbsoluteError(\n                absolute_error,\n                result_abs,\n                result_asc );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( 100.0, absolute_error, tol );\n\n\n  absolute_error = 50.0*std::numeric_limits<double>::epsilon();\n  result_asc = 0.0;\n  result_abs = 2.0;\n  double min_error = 50.0*std::numeric_limits<double>::epsilon() * result_abs;\n\n  test_integrator.rescaleAbsoluteError(\n                absolute_error,\n                result_abs,\n                result_asc );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( min_error, absolute_error, tol );\n}\n\n//---------------------------------------------------------------------------//\n// Check the roundoff error\nFRENSIE_UNIT_TEST( GaussKronrodIntegrator,\n                   checkRoundoffError )\n{\n  TestGaussKronrodIntegrator test_integrator( 1e-12 );\n\n  Utility::BinTraits<double> bin, bin_1, bin_2;\n  int round_off_1 = 0;\n  int round_off_2 = 0;\n  int number_of_interactions = 0;\n  double error_12 = 0.0, bin_1_asc = 0.0, bin_2_asc = 0.0;\n  double tol = 1e-12;\n\n  bin.result = 9.9999;\n  bin_1.result = 5.0;\n  bin_2.result = 5.0;\n\n  bin.error = 1.0;\n  bin_1.error = 0.5;\n  bin_2.error = 0.49;\n\n  bin_1_asc = bin_1.error;\n  bin_2_asc = bin_2.error;\n\n\n  test_integrator.checkRoundoffError(\n                bin,\n                bin_1,\n                bin_2,\n                bin_1_asc,\n                bin_2_asc,\n                round_off_1,\n                round_off_2,\n                number_of_interactions );\n\n  FRENSIE_CHECK_EQUAL( 0, round_off_1 );\n  FRENSIE_CHECK_EQUAL( 0, round_off_2 );\n\n  bin_1_asc = 0.0;\n  bin_2_asc = 0.0;\n\n\n  test_integrator.checkRoundoffError(\n                bin,\n                bin_1,\n                bin_2,\n                bin_1_asc,\n                bin_2_asc,\n                round_off_1,\n                round_off_2,\n                number_of_interactions );\n\n  FRENSIE_CHECK_EQUAL( 1, round_off_1 );\n  FRENSIE_CHECK_EQUAL( 0, round_off_2 );\n\n\n  bin_2.error = 0.501;\n  number_of_interactions = 10;\n\n  test_integrator.checkRoundoffError(\n                bin,\n                bin_1,\n                bin_2,\n                bin_1_asc,\n                bin_2_asc,\n                round_off_1,\n                round_off_2,\n                number_of_interactions );\n\n  FRENSIE_CHECK_EQUAL( 2, round_off_1 );\n  FRENSIE_CHECK_EQUAL( 1, round_off_2 );\n\n\n  bin.result = 9.9;\n\n  test_integrator.checkRoundoffError(\n                bin,\n                bin_1,\n                bin_2,\n                bin_1_asc,\n                bin_2_asc,\n                round_off_1,\n                round_off_2,\n                number_of_interactions );\n\n  FRENSIE_CHECK_EQUAL( 2, round_off_1 );\n  FRENSIE_CHECK_EQUAL( 2, round_off_2 );\n}\n\n//---------------------------------------------------------------------------//\n// Check the roundoff error\nFRENSIE_UNIT_TEST( GaussKronrodIntegrator,\n                   checkRoundoffError2 )\n{\n  TestGaussKronrodIntegrator test_integrator( 1e-12 );\n\n  Utility::ExtrapolatedBinTraits<double> bin, bin_1, bin_2;\n  int round_off_1 = 0;\n  int round_off_2 = 0;\n  int round_off_3 = 0;\n  int number_of_interactions = 0;\n  bool extrapolate = false;\n  double error_12 = 0.0, bin_1_asc = 0.0, bin_2_asc = 0.0;\n  double tol = 1e-12;\n\n  bin.result = 9.9999;\n  bin_1.result = 5.0;\n  bin_2.result = 5.0;\n\n  bin.error = 1.0;\n  bin_1.error = 0.5;\n  bin_2.error = 0.49;\n\n  bin_1_asc = bin_1.error;\n  bin_2_asc = bin_2.error;\n\n\n  test_integrator.checkRoundoffError(\n                bin,\n                bin_1,\n                bin_2,\n                bin_1_asc,\n                bin_2_asc,\n                round_off_1,\n                round_off_2,\n                round_off_3,\n                extrapolate,\n                number_of_interactions );\n\n  FRENSIE_CHECK_EQUAL( 0, round_off_1 );\n  FRENSIE_CHECK_EQUAL( 0, round_off_2 );\n  FRENSIE_CHECK_EQUAL( 0, round_off_3 );\n\n  bin_1_asc = 0.0;\n  bin_2_asc = 0.0;\n\n\n  test_integrator.checkRoundoffError(\n                bin,\n                bin_1,\n                bin_2,\n                bin_1_asc,\n                bin_2_asc,\n                round_off_1,\n                round_off_2,\n                round_off_3,\n                extrapolate,\n                number_of_interactions );\n\n  FRENSIE_CHECK_EQUAL( 1, round_off_1 );\n  FRENSIE_CHECK_EQUAL( 0, round_off_2 );\n  FRENSIE_CHECK_EQUAL( 0, round_off_3 );\n\n  extrapolate = true;\n\n  test_integrator.checkRoundoffError(\n                bin,\n                bin_1,\n                bin_2,\n                bin_1_asc,\n                bin_2_asc,\n                round_off_1,\n                round_off_2,\n                round_off_3,\n                extrapolate,\n                number_of_interactions );\n\n  FRENSIE_CHECK_EQUAL( 1, round_off_1 );\n  FRENSIE_CHECK_EQUAL( 1, round_off_2 );\n  FRENSIE_CHECK_EQUAL( 0, round_off_3 );\n\n  bin_2.error = 0.501;\n  number_of_interactions = 10;\n\n  test_integrator.checkRoundoffError(\n                bin,\n                bin_1,\n                bin_2,\n                bin_1_asc,\n                bin_2_asc,\n                round_off_1,\n                round_off_2,\n                round_off_3,\n                extrapolate,\n                number_of_interactions );\n\n  FRENSIE_CHECK_EQUAL( 1, round_off_1 );\n  FRENSIE_CHECK_EQUAL( 2, round_off_2 );\n  FRENSIE_CHECK_EQUAL( 1, round_off_3 );\n\n\n  bin.result = 9.9;\n\n  test_integrator.checkRoundoffError(\n                bin,\n                bin_1,\n                bin_2,\n                bin_1_asc,\n                bin_2_asc,\n                round_off_1,\n                round_off_2,\n                round_off_3,\n                extrapolate,\n                number_of_interactions );\n\n  FRENSIE_CHECK_EQUAL( 1, round_off_1 );\n  FRENSIE_CHECK_EQUAL( 2, round_off_2 );\n  FRENSIE_CHECK_EQUAL( 2, round_off_3 );\n}\n\n//---------------------------------------------------------------------------//\n// Check that the error list can be sorted\nFRENSIE_UNIT_TEST( GaussKronrodIntegrator,\n                   sortBins )\n{\n  TestGaussKronrodIntegrator test_integrator( 1e-12 );\n\n  Utility::ExtrapolatedBinTraits<double> bin, bin_1, bin_2;\n\n  int nr_max = 0;\n  int number_of_intervals = 1;\n\n  // Set up bin order array\n  std::vector<int> bin_order(1);\n  bin_order[0] = 0;\n\n  // Set bin array\n  Utility::GaussKronrodIntegrator<double>::BinArray bin_array(1000);\n  bin.error = 10.0;\n  bin_array[0] = bin;\n\n  // Set bin_1 and bin_2\n  bin_1.error = 5.0;\n  bin_2.error = 2.0;\n\n  test_integrator.sortBins(\n                bin_order,\n                bin_array,\n                bin_1,\n                bin_2,\n                number_of_intervals,\n                nr_max );\n\n  FRENSIE_CHECK_EQUAL( 0, bin_order[0] );\n  FRENSIE_CHECK_EQUAL( 1, bin_order[1] );\n  FRENSIE_CHECK_EQUAL( 0, nr_max );\n\n  nr_max = 0;\n  number_of_intervals = 3;\n\n  // Set up bin order array\n  bin_order.resize(3);\n  bin_order[0] = 0;\n  bin_order[1] = 1;\n  bin_order[2] = 2;\n\n  // Set bin array\n  bin.error = 10.0;\n  bin_array[0] = bin;\n  bin.error = 8.0;\n  bin_array[1] = bin;\n  bin.error = 1.0;\n  bin_array[2] = bin;\n\n  // Set bin_1 and bin_2\n  bin_1.error = 5.0;\n  bin_2.error = 2.0;\n\n  test_integrator.sortBins(\n                bin_order,\n                bin_array,\n                bin_1,\n                bin_2,\n                number_of_intervals,\n                nr_max );\n\n  FRENSIE_CHECK_EQUAL( 1, bin_order[0] );\n  FRENSIE_CHECK_EQUAL( 0, bin_order[1] );\n  FRENSIE_CHECK_EQUAL( 3, bin_order[2] );\n  FRENSIE_CHECK_EQUAL( 2, bin_order[3] );\n  FRENSIE_CHECK_EQUAL( 0, nr_max );\n\n  // Test with nr_max != 0\n  nr_max = 1;\n  number_of_intervals = 3;\n\n  // Set up bin order array\n  bin_order.resize(3);\n  bin_order[0] = 0;\n  bin_order[1] = 1;\n  bin_order[2] = 2;\n\n  // Set bin array\n  bin.error = 10.0;\n  bin_array[0] = bin;\n  bin.error = 8.0;\n  bin_array[1] = bin;\n  bin.error = 1.0;\n  bin_array[2] = bin;\n\n  // Set bin_1 and bin_2\n  bin_1.error = 11.0;\n  bin_2.error = 2.0;\n\n  test_integrator.sortBins(\n                bin_order,\n                bin_array,\n                bin_1,\n                bin_2,\n                number_of_intervals,\n                nr_max );\n\n  FRENSIE_CHECK_EQUAL( 1, bin_order[0] );\n  FRENSIE_CHECK_EQUAL( 0, bin_order[1] );\n  FRENSIE_CHECK_EQUAL( 3, bin_order[2] );\n  FRENSIE_CHECK_EQUAL( 2, bin_order[3] );\n  FRENSIE_CHECK_EQUAL( 0, nr_max );\n\n\n  // Test 3\n  nr_max = 0;\n  number_of_intervals = 3;\n\n  // Set up bin order array\n  bin_order.resize(3);\n  bin_order[0] = 1;\n  bin_order[1] = 0;\n  bin_order[2] = 2;\n\n  bin_array.clear();\n\n  // Set bin array\n  bin.error = 0.673651;\n  bin_array[0] = bin;\n  bin.error = 1.90537;\n  bin_array[1] = bin;\n  bin.error = 6.50354e-15;\n  bin_array[2] = bin;\n\n  // Set bin_1 and bin_2\n  bin_1.error = 0.673652;\n  bin_2.error = 6.50353e-15;\n\n  test_integrator.sortBins(\n                bin_order,\n                bin_array,\n                bin_1,\n                bin_2,\n                number_of_intervals,\n                nr_max );\n\n  FRENSIE_CHECK_EQUAL( 1, bin_order[0] );\n  FRENSIE_CHECK_EQUAL( 0, bin_order[1] );\n  FRENSIE_CHECK_EQUAL( 2, bin_order[2] );\n  FRENSIE_CHECK_EQUAL( 3, bin_order[3] );\n  FRENSIE_CHECK_EQUAL( 0, nr_max );\n\n  // Test 4\n  nr_max = 3;\n  number_of_intervals = 6;\n\n  // Set up bin order array\n  bin_order.resize(6);\n  bin_order[0] = 3;\n  bin_order[1] = 4;\n  bin_order[2] = 0;\n  bin_order[3] = 2;\n  bin_order[4] = 1;\n  bin_order[5] = 5;\n\n  bin_array.clear();\n\n  // Set bin array\n  bin.error = 4.0;\n  bin_array[0] = bin;\n  bin.error = 2.0;\n  bin_array[1] = bin;\n  bin.error = 3.0;\n  bin_array[2] = bin;\n  bin.error = 6.0;\n  bin_array[3] = bin;\n  bin.error = 5.0;\n  bin_array[4] = bin;\n  bin.error = 1.0;\n  bin_array[5] = bin;\n\n  // Set bin_1 and bin_2\n  bin_1.error = 2.5;\n  bin_2.error = 0.5;\n\n  test_integrator.sortBins(\n                bin_order,\n                bin_array,\n                bin_1,\n                bin_2,\n                number_of_intervals,\n                nr_max );\n\n  FRENSIE_CHECK_EQUAL( 3, bin_order[0] );\n  FRENSIE_CHECK_EQUAL( 4, bin_order[1] );\n  FRENSIE_CHECK_EQUAL( 0, bin_order[2] );\n  FRENSIE_CHECK_EQUAL( 2, bin_order[3] );\n  FRENSIE_CHECK_EQUAL( 1, bin_order[4] );\n  FRENSIE_CHECK_EQUAL( 5, bin_order[5] );\n  FRENSIE_CHECK_EQUAL( 6, bin_order[6] );\n  FRENSIE_CHECK_EQUAL( 3, nr_max );\n\n  // Test 5\n  nr_max = 3;\n  number_of_intervals = 6;\n\n  // Set up bin order array\n  bin_order.resize(6);\n  bin_order[0] = 3;\n  bin_order[1] = 4;\n  bin_order[2] = 0;\n  bin_order[3] = 2;\n  bin_order[4] = 1;\n  bin_order[5] = 5;\n\n  bin_array.clear();\n\n  // Set bin array\n  bin.error = 4.0;\n  bin_array[0] = bin;\n  bin.error = 2.0;\n  bin_array[1] = bin;\n  bin.error = 3.0;\n  bin_array[2] = bin;\n  bin.error = 6.0;\n  bin_array[3] = bin;\n  bin.error = 5.0;\n  bin_array[4] = bin;\n  bin.error = 1.0;\n  bin_array[5] = bin;\n\n  // Set bin_1 and bin_2\n  bin_1.error = 4.5;\n  bin_2.error = 0.5;\n\n  test_integrator.sortBins(\n                bin_order,\n                bin_array,\n                bin_1,\n                bin_2,\n                number_of_intervals,\n                nr_max );\n\n  FRENSIE_CHECK_EQUAL( 3, bin_order[0] );\n  FRENSIE_CHECK_EQUAL( 4, bin_order[1] );\n  FRENSIE_CHECK_EQUAL( 2, bin_order[2] );\n  FRENSIE_CHECK_EQUAL( 0, bin_order[3] );\n  FRENSIE_CHECK_EQUAL( 1, bin_order[4] );\n  FRENSIE_CHECK_EQUAL( 5, bin_order[5] );\n  FRENSIE_CHECK_EQUAL( 6, bin_order[6] );\n  FRENSIE_CHECK_EQUAL( 2, nr_max );\n}\n\n//---------------------------------------------------------------------------//\n// Check that the Wynn Epsilon-Algorithm extrapolated value can be calculated\nFRENSIE_UNIT_TEST( GaussKronrodIntegrator,\n                   getWynnEpsilonAlgorithmExtrapolation )\n{\n  TestGaussKronrodIntegrator test_integrator( 1e-12 );\n\n  std::vector<double> bin_extrapolated_result(52);\n  std::vector<double> last_three_results(3);\n  double extrapolated_result, extrapolated_error;\n  int number_of_extrapolated_intervals, number_of_extrapolated_calls;\n  double tol = 1e-16;\n  number_of_extrapolated_calls = 0;\n\n  // test 1\n  number_of_extrapolated_intervals = 2;\n  bin_extrapolated_result[0] = 3.93505142975913369L;\n  bin_extrapolated_result[1] = 3.95407442555431254L;\n  bin_extrapolated_result[2] = 3.96752571487956640L;\n\n  test_integrator.getWynnEpsilonAlgorithmExtrapolation(\n                bin_extrapolated_result,\n                last_three_results,\n                extrapolated_result,\n                extrapolated_error,\n                number_of_extrapolated_intervals,\n                number_of_extrapolated_calls );\n\n  FRENSIE_CHECK_EQUAL( number_of_extrapolated_intervals, 2 );\n  FRENSIE_CHECK_EQUAL( number_of_extrapolated_calls, 1 );\n  FRENSIE_CHECK_FLOATING_EQUALITY( extrapolated_error,\n                          std::numeric_limits<double>::max(),\n                          tol );\n  FRENSIE_CHECK_FLOATING_EQUALITY( extrapolated_result,\n                          3.99999999999999645,\n                          tol );\n  FRENSIE_CHECK_FLOATING_EQUALITY( last_three_results[0],\n                          3.99999999999999645,\n                          tol );\n  FRENSIE_CHECK_FLOATING_EQUALITY( last_three_results[1],\n                          0.0,\n                          tol );\n  FRENSIE_CHECK_FLOATING_EQUALITY( last_three_results[2],\n                          0.0,\n                          tol );\n\n  // test 2\n  number_of_extrapolated_intervals = 3;\n  bin_extrapolated_result[0] = 3.99999999999999645L;\n  bin_extrapolated_result[1] = 3.95407442555431254L;\n  bin_extrapolated_result[2] = 3.96752571487956640L;\n  bin_extrapolated_result[3] = 3.97703721277715605L;\n  bin_extrapolated_result[4] = 3.96752571487956640L;\n\n  test_integrator.getWynnEpsilonAlgorithmExtrapolation(\n                bin_extrapolated_result,\n                last_three_results,\n                extrapolated_result,\n                extrapolated_error,\n                number_of_extrapolated_intervals,\n                number_of_extrapolated_calls );\n\n  FRENSIE_CHECK_EQUAL( number_of_extrapolated_intervals, 3 );\n  FRENSIE_CHECK_EQUAL( number_of_extrapolated_calls, 2 );\n  FRENSIE_CHECK_FLOATING_EQUALITY( extrapolated_error,\n                          std::numeric_limits<double>::max(),\n                          tol );\n  FRENSIE_CHECK_FLOATING_EQUALITY( extrapolated_result,\n                          4.00000000000000355,\n                          tol );\n  FRENSIE_CHECK_FLOATING_EQUALITY( last_three_results[0],\n                          3.99999999999999645,\n                          tol );\n  FRENSIE_CHECK_FLOATING_EQUALITY( last_three_results[1],\n                          4.00000000000000355,\n                          tol );\n  FRENSIE_CHECK_FLOATING_EQUALITY( last_three_results[2],\n                          0.0,\n                          tol );\n\n\n  // test 3\n  number_of_extrapolated_intervals = 4;\n  bin_extrapolated_result[0] = 3.99999999999999645L;\n  bin_extrapolated_result[1] = 4.00000000000000355L;\n  bin_extrapolated_result[2] = 3.96752571487956640L;\n  bin_extrapolated_result[3] = 3.97703721277715605L;\n  bin_extrapolated_result[4] = 3.98376285743978320L;\n  bin_extrapolated_result[5] = 3.97703721277715605L;\n\n  test_integrator.getWynnEpsilonAlgorithmExtrapolation(\n                bin_extrapolated_result,\n                last_three_results,\n                extrapolated_result,\n                extrapolated_error,\n                number_of_extrapolated_intervals,\n                number_of_extrapolated_calls );\n\n  FRENSIE_CHECK_EQUAL( number_of_extrapolated_intervals, 4 );\n  FRENSIE_CHECK_EQUAL( number_of_extrapolated_calls, 3 );\n  FRENSIE_CHECK_FLOATING_EQUALITY( extrapolated_error,\n                          std::numeric_limits<double>::max(),\n                          tol );\n  FRENSIE_CHECK_FLOATING_EQUALITY( extrapolated_result,\n                          4.00000000000000089,\n                          tol );\n  FRENSIE_CHECK_FLOATING_EQUALITY( last_three_results[0],\n                          3.99999999999999645,\n                          tol );\n  FRENSIE_CHECK_FLOATING_EQUALITY( last_three_results[1],\n                          4.00000000000000355,\n                          tol );\n  FRENSIE_CHECK_FLOATING_EQUALITY( last_three_results[2],\n                          4.00000000000000089,\n                          tol );\n\n\n  // test 4\n  number_of_extrapolated_intervals = 5;\n  bin_extrapolated_result[0] = 4.00000000000000089L;\n  bin_extrapolated_result[1] = 4.00000000000000355L;\n  bin_extrapolated_result[2] = 3.99999999999999911L;\n  bin_extrapolated_result[3] = 3.97703721277715605L;\n  bin_extrapolated_result[4] = 3.98376285743978320L;\n  bin_extrapolated_result[5] = 3.98851860638857758L;\n  bin_extrapolated_result[6] = 3.98376285743978320L;\n\n\n  test_integrator.getWynnEpsilonAlgorithmExtrapolation(\n                bin_extrapolated_result,\n                last_three_results,\n                extrapolated_result,\n                extrapolated_error,\n                number_of_extrapolated_intervals,\n                number_of_extrapolated_calls );\n\n  FRENSIE_CHECK_EQUAL( number_of_extrapolated_intervals, 5 );\n  FRENSIE_CHECK_EQUAL( number_of_extrapolated_calls, 4 );\n  FRENSIE_CHECK_FLOATING_EQUALITY( extrapolated_error,\n                          5.68434188608080149e-14,\n                          tol );\n  FRENSIE_CHECK_FLOATING_EQUALITY( extrapolated_result,\n                          3.99999999999998135,\n                          tol );\n  FRENSIE_CHECK_FLOATING_EQUALITY( last_three_results[0],\n                          4.00000000000000355,\n                          tol );\n  FRENSIE_CHECK_FLOATING_EQUALITY( last_three_results[1],\n                          4.00000000000000089,\n                          tol );\n  FRENSIE_CHECK_FLOATING_EQUALITY( last_three_results[2],\n                          3.99999999999998135,\n                          tol );\n\n}\n\n//---------------------------------------------------------------------------//\n// Check that functions can be integrated over [0,1] adaptively\nFRENSIE_UNIT_TEST_TEMPLATE( GaussKronrodIntegrator,\n                            integrateAdaptively,\n                            TestFunctors )\n{\n  FETCH_TEMPLATE_PARAM( 0, Functor );\n\n  Utility::GaussKronrodIntegrator<double> gk_integrator( 1e-12 );\n\n  double result, absolute_error, tol;\n\n  Functor functor_instance;\n\n  // Test the 15-point rule\n  gk_integrator.integrateAdaptively<15>( functor_instance,\n\t\t\t\t  0.0,\n\t\t\t\t  1.0,\n\t\t\t\t  result,\n\t\t\t\t  absolute_error );\n\n  tol = absolute_error/result;\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( Functor::getIntegratedValue(), result, tol );\n\n\n  // Test the 21-point rule\n  gk_integrator.integrateAdaptively<21>( functor_instance,\n\t\t\t\t  0.0,\n\t\t\t\t  1.0,\n\t\t\t\t  result,\n\t\t\t\t  absolute_error );\n\n  tol = absolute_error/result;\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( Functor::getIntegratedValue(), result, tol );\n\n\n  // Test the 31-point rule\n  gk_integrator.integrateAdaptively<31>( functor_instance,\n\t\t\t\t  0.0,\n\t\t\t\t  1.0,\n\t\t\t\t  result,\n\t\t\t\t  absolute_error );\n\n  tol = absolute_error/result;\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( Functor::getIntegratedValue(), result, tol );\n\n\n  // Test the 41-point rule\n  gk_integrator.integrateAdaptively<41>( functor_instance,\n\t\t\t\t  0.0,\n\t\t\t\t  1.0,\n\t\t\t\t  result,\n\t\t\t\t  absolute_error );\n\n  tol = absolute_error/result;\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( Functor::getIntegratedValue(), result, tol );\n\n\n  // Test the 51-point rule\n  gk_integrator.integrateAdaptively<51>( functor_instance,\n\t\t\t\t  0.0,\n\t\t\t\t  1.0,\n\t\t\t\t  result,\n\t\t\t\t  absolute_error );\n\n  tol = absolute_error/result;\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( Functor::getIntegratedValue(), result, tol );\n\n\n  // Test the 61-point rule\n  gk_integrator.integrateAdaptively<61>( functor_instance,\n\t\t\t\t  0.0,\n\t\t\t\t  1.0,\n\t\t\t\t  result,\n\t\t\t\t  absolute_error );\n\n  tol = absolute_error/result;\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( Functor::getIntegratedValue(), result, tol );\n}\n\n//---------------------------------------------------------------------------//\n// Check that functions can be integrated over [0,1] adaptively\nFRENSIE_UNIT_TEST_TEMPLATE( GaussKronrodIntegrator,\n                            integrateAdaptively_long_double,\n                            TestFunctorsLong )\n{\n  FETCH_TEMPLATE_PARAM( 0, Functor );\n\n  Utility::GaussKronrodIntegrator<long double> gk_integrator( 1e-12 );\n\n  long double result, absolute_error, tol;\n\n  Functor functor_instance;\n\n  // Test the 15-point rule\n  gk_integrator.integrateAdaptively<15,long double>( functor_instance,\n\t\t\t\t  0.0L,\n\t\t\t\t  1.0L,\n\t\t\t\t  result,\n\t\t\t\t  absolute_error );\n\n  tol = absolute_error/result;\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( (double)Functor::getIntegratedValue(),\n                          (double)result,\n                          (double)tol );\n\n\n  // Test the 21-point rule\n  gk_integrator.integrateAdaptively<21>( functor_instance,\n\t\t\t\t  0.0L,\n\t\t\t\t  1.0L,\n\t\t\t\t  result,\n\t\t\t\t  absolute_error );\n\n  tol = absolute_error/result;\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( (double)Functor::getIntegratedValue(),\n                          (double)result,\n                          (double)tol );\n\n\n  // Test the 31-point rule\n  gk_integrator.integrateAdaptively<31,long double>( functor_instance,\n\t\t\t\t  0.0L,\n\t\t\t\t  1.0L,\n\t\t\t\t  result,\n\t\t\t\t  absolute_error );\n\n  tol = absolute_error/result;\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( (double)Functor::getIntegratedValue(),\n                          (double)result,\n                          (double)tol );\n\n\n  // Test the 41-point rule\n  gk_integrator.integrateAdaptively<41,long double>( functor_instance,\n\t\t\t\t  0.0L,\n\t\t\t\t  1.0L,\n\t\t\t\t  result,\n\t\t\t\t  absolute_error );\n\n  tol = absolute_error/result;\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( (double)Functor::getIntegratedValue(),\n                          (double)result,\n                          (double)tol );\n\n\n  // Test the 51-point rule\n  gk_integrator.integrateAdaptively<51,long double>( functor_instance,\n\t\t\t\t  0.0L,\n\t\t\t\t  1.0L,\n\t\t\t\t  result,\n\t\t\t\t  absolute_error );\n\n  tol = absolute_error/result;\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( (double)Functor::getIntegratedValue(),\n                          (double)result,\n                          (double)tol );\n\n\n  // Test the 61-point rule\n  gk_integrator.integrateAdaptively<61,long double>( functor_instance,\n\t\t\t\t  0.0L,\n\t\t\t\t  1.0L,\n\t\t\t\t  result,\n\t\t\t\t  absolute_error );\n\n  tol = absolute_error/result;\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( (double)Functor::getIntegratedValue(),\n                          (double)result,\n                          (double)tol );\n\n}\n\n//---------------------------------------------------------------------------//\n// Check that functions can be integrated over [0,1] adaptively\nFRENSIE_UNIT_TEST_TEMPLATE( GaussKronrodIntegrator,\n                            integrateAdaptively_long_float,\n                            TestFunctorsBoost )\n{\n  FETCH_TEMPLATE_PARAM( 0, Functor );\n\n  Utility::GaussKronrodIntegrator<long_float> gk_integrator( 1e-12 );\n\n  long_float result, absolute_error, tol;\n\n  Functor functor_instance;\n\n  // Test the 15-point rule\n  gk_integrator.integrateAdaptively<15,long_float>( functor_instance,\n\t\t\t\t  (long_float)0,\n\t\t\t\t  (long_float)1,\n\t\t\t\t  result,\n\t\t\t\t  absolute_error );\n\n  tol = absolute_error/result;\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( (double)Functor::getIntegratedValue(),\n                          (double)result,\n                          (double)tol );\n\n\n  // Test the 21-point rule\n  gk_integrator.integrateAdaptively<21,long_float>( functor_instance,\n\t\t\t\t  (long_float)0,\n\t\t\t\t  (long_float)1,\n\t\t\t\t  result,\n\t\t\t\t  absolute_error );\n\n  tol = absolute_error/result;\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( (double)Functor::getIntegratedValue(),\n                          (double)result,\n                          (double)tol );\n\n\n  // Test the 31-point rule\n  gk_integrator.integrateAdaptively<31,long_float>( functor_instance,\n\t\t\t\t  (long_float)0,\n\t\t\t\t  (long_float)1,\n\t\t\t\t  result,\n\t\t\t\t  absolute_error );\n\n  tol = absolute_error/result;\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( (double)Functor::getIntegratedValue(),\n                          (double)result,\n                          (double)tol );\n\n\n  // Test the 41-point rule\n  gk_integrator.integrateAdaptively<41,long_float>( functor_instance,\n\t\t\t\t  (long_float)0,\n\t\t\t\t  (long_float)1,\n\t\t\t\t  result,\n\t\t\t\t  absolute_error );\n\n  tol = absolute_error/result;\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( (double)Functor::getIntegratedValue(),\n                          (double)result,\n                          (double)tol );\n\n\n  // Test the 51-point rule\n  gk_integrator.integrateAdaptively<51,long_float>( functor_instance,\n\t\t\t\t  (long_float)0,\n\t\t\t\t  (long_float)1,\n\t\t\t\t  result,\n\t\t\t\t  absolute_error );\n\n  tol = absolute_error/result;\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( (double)Functor::getIntegratedValue(),\n                          (double)result,\n                          (double)tol );\n\n\n  // Test the 61-point rule\n  gk_integrator.integrateAdaptively<61,long_float>( functor_instance,\n\t\t\t\t  (long_float)0,\n\t\t\t\t  (long_float)1,\n\t\t\t\t  result,\n\t\t\t\t  absolute_error );\n\n  tol = absolute_error/result;\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( (double)Functor::getIntegratedValue(),\n                          (double)result,\n                          (double)tol );\n}\n\n//---------------------------------------------------------------------------//\n// Check that functions can be integrated over [0,1] adaptively\nFRENSIE_UNIT_TEST_TEMPLATE( GaussKronrodIntegrator,\n                            integrateAdaptively_parameter,\n                            TestFunctorsParameter )\n{\n  FETCH_TEMPLATE_PARAM( 0, Functor );\n\n  Utility::GaussKronrodIntegrator<double> gk_integrator( 1e-12 );\n\n  double result, absolute_error, tol;\n\n  Functor functor_instance;\n\n  // Test the 15-point rule\n  gk_integrator.integrateAdaptively<15>( functor_instance,\n          1.0,\n\t\t\t\t  0.0,\n\t\t\t\t  1.0,\n\t\t\t\t  result,\n\t\t\t\t  absolute_error );\n\n  tol = absolute_error/result;\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( Functor::getIntegratedValue(), result, tol );\n\n\n  // Test the 21-point rule\n  gk_integrator.integrateAdaptively<21>( functor_instance,\n                  1.0,\n\t\t\t\t  0.0,\n\t\t\t\t  1.0,\n\t\t\t\t  result,\n\t\t\t\t  absolute_error );\n\n  tol = absolute_error/result;\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( Functor::getIntegratedValue(), result, tol );\n\n\n  // Test the 31-point rule\n  gk_integrator.integrateAdaptively<31>( functor_instance,\n                  1.0,\n\t\t\t\t  0.0,\n\t\t\t\t  1.0,\n\t\t\t\t  result,\n\t\t\t\t  absolute_error );\n\n  tol = absolute_error/result;\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( Functor::getIntegratedValue(), result, tol );\n\n\n  // Test the 41-point rule\n  gk_integrator.integrateAdaptively<41>( functor_instance,\n                  1.0,\n\t\t\t\t  0.0,\n\t\t\t\t  1.0,\n\t\t\t\t  result,\n\t\t\t\t  absolute_error );\n\n  tol = absolute_error/result;\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( Functor::getIntegratedValue(), result, tol );\n\n\n  // Test the 51-point rule\n  gk_integrator.integrateAdaptively<51>( functor_instance,\n                  1.0,\n\t\t\t\t  0.0,\n\t\t\t\t  1.0,\n\t\t\t\t  result,\n\t\t\t\t  absolute_error );\n\n  tol = absolute_error/result;\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( Functor::getIntegratedValue(), result, tol );\n\n\n  // Test the 61-point rule\n  gk_integrator.integrateAdaptively<61>( functor_instance,\n                  1.0,\n\t\t\t\t  0.0,\n\t\t\t\t  1.0,\n\t\t\t\t  result,\n\t\t\t\t  absolute_error );\n\n  tol = absolute_error/result;\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( Functor::getIntegratedValue(), result, tol );\n}\n\n//---------------------------------------------------------------------------//\n// Check that a function with integrable singularities can be integrated\nFRENSIE_UNIT_TEST( GaussKronrodIntegrator,\n\t\t   integrateAdaptivelyWynnEpsilon )\n{\n  boost::function<double (double x)> function_wrapper = inv_sqrt_abs_x;\n\n  std::vector<double> points_of_interest( 3 );\n  points_of_interest[0] = -1.0;\n  points_of_interest[1] = 0.0; // integrable singularity\n  points_of_interest[2] = 1.0;\n\n  Utility::GaussKronrodIntegrator<double> gk_int( 1e-12, 0.0, 100000 );\n\n  double result, absolute_error;\n\n  gk_int.integrateAdaptivelyWynnEpsilon( function_wrapper,\n\t\t\t\t\t Utility::arrayView(points_of_interest),\n\t\t\t\t\t result,\n\t\t\t\t\t absolute_error );\n\n\n  double tol = absolute_error/result;\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( result, 4.0, tol );\n\n\n\n  std::vector<long double> long_points_of_interest( 2 );\n  points_of_interest[0] = -1.0L;\n  points_of_interest[1] = 1.0L;\n\n  Utility::GaussKronrodIntegrator<long double> gk_long_int( 1e-12, 0.0, 100000 );\n\n  long double long_result, long_absolute_error;\n\n  gk_long_int.integrateAdaptivelyWynnEpsilon( function_wrapper,\n                                              Utility::arrayView(long_points_of_interest),\n                                              long_result,\n                                              long_absolute_error );\n\n\n  long double long_tol = long_absolute_error/long_result;\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( (double)result, 4.0, (double)tol );\n}\n\n//---------------------------------------------------------------------------//\n// Check that a function with no singularities can be integrated using Wynn Epsilon\nFRENSIE_UNIT_TEST_TEMPLATE( GaussKronrodIntegrator,\n                            integrateAdaptivelyWynnEpsilon_no_singularities,\n                            TestFunctors )\n{\n  FETCH_TEMPLATE_PARAM( 0, Functor );\n\n  Functor functor_instance;\n\n  std::vector<double> points_of_interest( 3 );\n  points_of_interest[0] = 0.0;\n  points_of_interest[1] = 0.5;\n  points_of_interest[2] = 1.0;\n\n  Utility::GaussKronrodIntegrator<double> gkq_set( 1e-12, 0.0, 100000 );\n\n  double result, absolute_error;\n\n  gkq_set.integrateAdaptivelyWynnEpsilon(\n                                        functor_instance,\n                                        Utility::arrayView(points_of_interest),\n                                        result,\n                                        absolute_error );\n\n  double tol = absolute_error/result;\n\n  FRENSIE_CHECK_FLOATING_EQUALITY( Functor::getIntegratedValue(), result, tol );\n}\n\n//---------------------------------------------------------------------------//\n// Check that warnings can be thrown\nFRENSIE_UNIT_TEST_TEMPLATE( GaussKronrodIntegrator,\n                            warnOnDirtyIntegration,\n                            TestFunctorsBoost )\n{\n  FETCH_TEMPLATE_PARAM( 0, Functor );\n\n  Utility::GaussKronrodIntegrator<long_float> gk_integrator( 1e-20, 0.0, 2 );\n\n  long_float result, absolute_error, tol;\n\n  Functor functor_instance;\n\n  // Integration should only throw warnings\n  try\n  {\n    gk_integrator.integrateAdaptively<15,long_float>( functor_instance,\n\t\t\t\t  (long_float)-1,\n\t\t\t\t  (long_float)2,\n\t\t\t\t  result,\n\t\t\t\t  absolute_error );\n  }\n  catch( std::exception exception )\n  {\n    FRENSIE_CHECK( 1 );\n  }\n  catch( ... )\n  {\n    FRENSIE_CHECK( 0 );\n  }\n\n  // Integration should throw exception\n  try\n  {\n    gk_integrator.throwExceptionOnDirtyIntegration();\n\n    gk_integrator.integrateAdaptively<15,long_float>( functor_instance,\n\t\t\t\t  (long_float)-1,\n\t\t\t\t  (long_float)2,\n\t\t\t\t  result,\n\t\t\t\t  absolute_error );\n  }\n  catch( std::exception exception )\n  {\n    FRENSIE_CHECK( 1 );\n  }\n  catch( ... )\n  {\n    FRENSIE_CHECK( 0 );\n  }\n\n  // Integration should only throw warnings\n  try\n  {\n    gk_integrator.warnOnDirtyIntegration();\n\n    gk_integrator.integrateAdaptively<15,long_float>( functor_instance,\n\t\t\t\t  (long_float)-1,\n\t\t\t\t  (long_float)2,\n\t\t\t\t  result,\n\t\t\t\t  absolute_error );\n  }\n  catch( std::exception exception )\n  {\n    FRENSIE_CHECK( 0 );\n  }\n  catch( ... )\n  {\n    FRENSIE_CHECK( 0 );\n  }\n\n  // Integration should throw exception\n  try\n  {\n  Utility::GaussKronrodIntegrator<long_float> gk_int( 1e-50, 0.0, 2);\n\n  gk_integrator.integrateAdaptively<15,long_float>( functor_instance,\n\t\t\t\t  (long_float)0,\n\t\t\t\t  (long_float)1,\n\t\t\t\t  result,\n\t\t\t\t  absolute_error );\n  }\n  catch( std::exception exception )\n  {\n    FRENSIE_CHECK( 1 );\n  }\n  catch( ... )\n  {\n    FRENSIE_CHECK( 0 );\n  }\n}\n\n//---------------------------------------------------------------------------//\n// end tstGaussKronrodIntegrator.cpp\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "787ca0201cd84357a5f5438876c52f6273065707", "size": 48546, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "packages/utility/integrator/test/tstGaussKronrodIntegrator.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/utility/integrator/test/tstGaussKronrodIntegrator.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/utility/integrator/test/tstGaussKronrodIntegrator.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": 27.0904017857, "max_line_length": 94, "alphanum_fraction": 0.5826638652, "num_tokens": 12410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.6859494678483918, "lm_q1q2_score": 0.47511739974072703}}
{"text": "/**\n * main for testing the graphs\n * by R. Falque\n * 20/08/2019\n **/\n\n// dependencies\n#include <cstdlib>\n#include <iostream>\n#include <limits>\n\n#include <Eigen/Core>\n\n#include \"gtest/gtest.h\"\n\n#include \"libGraphCpp/graph.hpp\"\n#include \"libGraphCpp/graphOptions.hpp\"\n\n#include <yaml-cpp/yaml.h>\n\n/*\n * TEST CONSTRUCTORS\n */\nTEST(constructors, string)\n{\n    libgraphcpp::Graph graph(\"../data/graphs_test/0_graph_complete.obj\");\n\n    EXPECT_EQ(graph.num_nodes(), 36);\n    EXPECT_EQ(graph.num_edges(), 68);\n}\n\nTEST(constructors, stringAndOpts)\n{\n    graphOptions opts;\n    opts.loadYAML(\"../tests_config.yaml\");\n\n    libgraphcpp::Graph graph(\"../data/graphs_test/0_graph_complete.obj\", opts);\n\n    EXPECT_EQ(graph.num_nodes(), 36);\n    EXPECT_EQ(graph.num_edges(), 68);\n}\n\nTEST(constructors, edgeList)\n{\n    Eigen::MatrixXd nodes;\n    nodes.resize(5, 3);\n    nodes << 1, 2, 3,\n             4, 5, 6,\n             1, 8, 9,\n             2, 8, 9,\n             3, 8, 9;\n\n    Eigen::MatrixXi edges;\n    edges.resize(4, 2);\n    edges << 0, 1,\n             1, 2,\n             2, 3,\n             3, 4;\n\n    libgraphcpp::Graph graph(nodes, edges);\n\n    EXPECT_EQ(graph.num_nodes(), 5);\n    EXPECT_EQ(graph.num_edges(), 4);\n}\n\nTEST(constructors, edgeListAndOpts)\n{\n    graphOptions opts;\n    opts.loadYAML(\"../tests_config.yaml\");\n\n    Eigen::MatrixXd nodes;\n    nodes.resize(5, 3);\n    nodes << 1, 2, 3,\n             4, 5, 6,\n             1, 8, 9,\n             2, 8, 9,\n             3, 8, 9;\n\n    Eigen::MatrixXi edges;\n    edges.resize(4, 2);\n    edges << 0, 1,\n             0, 2,\n             0, 3,\n             0, 4;\n\n    libgraphcpp::Graph graph(nodes, edges, opts);\n\n    EXPECT_EQ(graph.num_nodes(), 5);\n    EXPECT_EQ(graph.num_edges(), 4);\n}\n\nTEST(constructors, adjacencyMatrix)\n{\n    Eigen::MatrixXd nodes;\n    nodes.resize(4, 3);\n    nodes << 1, 2, 3,\n             4, 5, 6,\n             1, 8, 9,\n             2, 8, 9;\n\n    Eigen::MatrixXi edges;\n    edges.resize(4, 4);\n    edges << 0, 1, 0, 1,\n             1, 0, 0, 1,\n             0, 0, 0, 1,\n             1, 1, 1, 0;\n\n    libgraphcpp::Graph graph(nodes, edges);\n\n    EXPECT_EQ(graph.num_nodes(), 4);\n    EXPECT_EQ(graph.num_edges(), 4);\n}\n\nTEST(constructors, adjacencyMatrixAndOpts)\n{\n    graphOptions opts;\n    opts.loadYAML(\"../tests_config.yaml\");\n\n    Eigen::MatrixXd nodes;\n    nodes.resize(4, 3);\n    nodes << 1, 2, 3,\n             4, 5, 6,\n             1, 8, 9,\n             2, 8, 9;\n\n    Eigen::MatrixXi edges;\n    edges.resize(4, 4);\n    edges << 0, 1, 0, 1,\n             1, 0, 0, 1,\n             0, 0, 0, 1,\n             1, 1, 1, 0;\n\n    libgraphcpp::Graph graph(nodes, edges, opts);\n\n    EXPECT_EQ(graph.num_nodes(), 4);\n    EXPECT_EQ(graph.num_edges(), 4);\n}\n\n\n/*\n * TEST GRAPH CONNECTIVITY\n */\nTEST(graphConnectivity, disconnected)\n{\n    libgraphcpp::Graph graph(\"../data/graphs_test/6_disconnected.obj\");\n\n    EXPECT_EQ(graph.is_connected(), false);\n    EXPECT_EQ(graph.is_biconnected(), false);\n    EXPECT_EQ(graph.is_triconnected(), false);\n}\n\nTEST(graphConnectivity, connected)\n{\n    libgraphcpp::Graph graph(\"../data/graphs_test/3_1_node_connectetivity.obj\");\n    \n    EXPECT_EQ(graph.is_connected(), true);\n    EXPECT_EQ(graph.is_biconnected(), false);\n    EXPECT_EQ(graph.is_triconnected(), false);\n}\n\nTEST(graphConnectivity, biconnected)\n{\n    libgraphcpp::Graph graph(\"../data/graphs_test/5_2_edge_connectetivity.obj\");\n\n    EXPECT_EQ(graph.is_connected(), true);\n    EXPECT_EQ(graph.is_biconnected(), true);\n    EXPECT_EQ(graph.is_triconnected(), false);\n}\n\nTEST(graphConnectivity, triconnected)\n{\n    libgraphcpp::Graph graph(\"../data/graphs_test/0_graph_complete.obj\");\n\n    EXPECT_EQ(graph.is_connected(), true);\n    EXPECT_EQ(graph.is_biconnected(), true);\n    EXPECT_EQ(graph.is_triconnected(), true);\n}\n\n\n/*\n * TEST Dijkstra\n */\nTEST(graphDikjstra, unreachable)\n{\n    libgraphcpp::Graph graph(\"../data/graphs_test/6_disconnected.obj\");\n\n    EXPECT_EQ(graph.dijkstra(0, 1), std::numeric_limits<double>::infinity());\n}\n\nTEST(graphDikjstra, reachable)\n{\n    libgraphcpp::Graph graph(\"../data/graphs_test/0_graph_complete.obj\");\n\n    EXPECT_EQ(graph.dijkstra(0, 1), 20);\n}\n\nint main(int argc, char* argv[])\n{\n\ttesting::InitGoogleTest(&argc, argv);\n\treturn RUN_ALL_TESTS();\n}", "meta": {"hexsha": "92266c3d287ec9ce63c480228a2cfe80b590a3ee", "size": 4247, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/graph_tests.cpp", "max_stars_repo_name": "rFalque/libGraphCpp", "max_stars_repo_head_hexsha": "a01a13496f683325f45a8ec8e72390cbe8624ace", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2020-06-30T13:10:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-16T03:17:50.000Z", "max_issues_repo_path": "tests/graph_tests.cpp", "max_issues_repo_name": "rFalque/libGraphCpp", "max_issues_repo_head_hexsha": "a01a13496f683325f45a8ec8e72390cbe8624ace", "max_issues_repo_licenses": ["MIT"], "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/graph_tests.cpp", "max_forks_repo_name": "rFalque/libGraphCpp", "max_forks_repo_head_hexsha": "a01a13496f683325f45a8ec8e72390cbe8624ace", "max_forks_repo_licenses": ["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.1293532338, "max_line_length": 80, "alphanum_fraction": 0.6001883683, "num_tokens": 1270, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081925, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.4751173908470659}}
{"text": "#include <string>\n#include <sstream>\n#include <iostream>\n#include <map>\n#include <regex>\n#include <fstream>\n#include <boost/algorithm/string.hpp>\n\n#include \"../common.hpp\"\n\nusing namespace std;\n\nbool has_adjacent_digits(const string &s) {\n    for (int i = 1; i < s.size(); i++) {\n        if (s[i - 1] == s[i]) {\n            return true;\n        }\n    }\n    return false;\n}\n\nbool has_double_digits(const string &s) {\n    for (int i = 1; i < s.size(); i++) {\n        if (s[i - 1] == s[i]) { // Found double\n            // Check that the one before, and the one after doesn't match\n            if ((i >= 2 && s[i-2] == s[i])) {\n                continue;\n            }\n            if ((i + 1) < s.size() && s[i+1] == s[i])  {\n                continue;\n            }\n            return true;\n        }\n    }\n    return false;\n}\n\nbool is_monotonic(const string &s) {\n    for (int i = 1; i < s.size(); i++) {\n        if (s[i - 1] > s[i]) {\n            return false;\n        }\n    }\n    return true;\n}\n\nbool passes1(const string &s) {\n    return is_monotonic(s) && has_adjacent_digits(s);\n}\n\nbool passes2(const string &s) {\n    return is_monotonic(s) && has_double_digits(s);\n}\n\nint main() {\n    int answer1 = 0;\n    int answer2 = 0;\n\n    assert(passes1(\"111111\") == true);\n    assert(passes1(\"223450\") == false);\n    assert(passes1(\"123789\") == false);\n    assert(passes1(\"700000\") == false);\n\n    assert(passes2(\"112233\") == true);\n    assert(passes2(\"123444\") == false);\n    assert(passes2(\"111122\") == true);\n    assert(passes2(\"666999\") == false);\n    \n\n    // Bruteforce :)\n    for (int i = 235741; i < 706948; i++) {\n        string s = to_string(i);\n\n        if (passes1(s)) {\n            answer1++;\n        }\n\n        if (passes2(s)) { \n            answer2++;\n        }\n    }\n\n    cout << \"Answer 4.1: \" << answer1 << endl;\n    cout << \"Answer 4.2: \" << answer2 << endl;\n}", "meta": {"hexsha": "5caab13af05a2bf37df4e627bd164e984359d6c0", "size": 1872, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "2019/4.cpp", "max_stars_repo_name": "bramp/aoc", "max_stars_repo_head_hexsha": "e6e2bf343786e58b3e0513dc88858e54c06f1cf6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2019/4.cpp", "max_issues_repo_name": "bramp/aoc", "max_issues_repo_head_hexsha": "e6e2bf343786e58b3e0513dc88858e54c06f1cf6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2019/4.cpp", "max_forks_repo_name": "bramp/aoc", "max_forks_repo_head_hexsha": "e6e2bf343786e58b3e0513dc88858e54c06f1cf6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.0235294118, "max_line_length": 73, "alphanum_fraction": 0.4967948718, "num_tokens": 542, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419704455588, "lm_q2_score": 0.6859494614282922, "lm_q1q2_score": 0.4751173865897621}}
{"text": "\n#include <iostream>\n#include <boost/numeric/ublas/banded.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/operation.hpp>\n#include <iomanip>\n\n#include \"utils.hpp\"\n\nusing namespace boost::numeric::ublas;\n\nint expected_index( size_t index, column_major ) {\n   // this is the data shown on http://www.netlib.org/lapack/lug/node124.html\n   // read column-by-column, aka column_major\n   int mapping[] = { 0, 11, 21, 31, 12, 22, 32, 42, 23, 33, 43, 53, 34, 44, 54, 0, 45, 55, 0, 0 };\n   return mapping[ index ];\n}\n\n\nint expected_index( size_t index, row_major ) {\n   // this is the data shown on http://www.netlib.org/lapack/lug/node124.html\n   // read row-by-row, aka row_major\n   int mapping[] = { 0, 0, 11, 12, 0, 21, 22, 23, 31, 32, 33, 34, 42, 43, 44, 45, 53, 54, 55, 0 };\n   return mapping[ index ];\n}\n\nint expected_index_6_by_5( size_t index, column_major ) {\n   // read column-by-column, aka column_major\n   int mapping[] = { 0, 11, 21, 31, 12, 22, 32, 42, 23, 33, 43, 53, 34, 44, 54, 64, 45, 55, 65, 0 };\n   return mapping[ index ];\n}\n\nint expected_index_6_by_5( size_t index, row_major ) {\n   // read row-by-row, aka row_major\n   int mapping[] = { 0, 0, 11, 12, 0, 21, 22, 23, 31, 32, 33, 34, 42, 43, 44, 45, 53, 54, 55, 0, 64, 65, 0, 0 };\n   return mapping[ index ];\n}\n\nint expected_index_5_by_6( size_t index, column_major ) {\n   // read column-by-column, aka column_major\n   int mapping[] = { 0, 11, 21, 31, 12, 22, 32, 42, 23, 33, 43, 53, 34, 44, 54, 0, 45, 55, 0, 0, 56, 0, 0, 0 };\n   return mapping[ index ];\n}\n\nint expected_index_5_by_6( size_t index, row_major ) {\n   // read row-by-row, aka row_major\n   int mapping[] = { 0, 0, 11, 12, 0, 21, 22, 23, 31, 32, 33, 34, 42, 43, 44, 45, 53, 54, 55, 56};\n   return mapping[ index ];\n}\n\ntemplate< typename Orientation >\nbool test_band_storage() {\n        \n    int m = 5;\n    int n = 5;\n    int kl = 2;\n    int ku = 1;\n    \n    banded_matrix< int, Orientation > test_matrix( m, n, kl, ku );\n    test_matrix.clear();\n    size_t band_storage_size = test_matrix.data().size();\n    \n    test_matrix( 0, 0 ) = 11;\n    test_matrix( 0, 1 ) = 12;\n    test_matrix( 1, 0 ) = 21;\n    test_matrix( 1, 1 ) = 22;\n    test_matrix( 1, 2 ) = 23;\n    test_matrix( 2, 0 ) = 31;\n    test_matrix( 2, 1 ) = 32;\n    test_matrix( 2, 2 ) = 33;\n    test_matrix( 2, 3 ) = 34;\n    test_matrix( 3, 1 ) = 42;\n    test_matrix( 3, 2 ) = 43;\n    test_matrix( 3, 3 ) = 44;\n    test_matrix( 3, 4 ) = 45;\n    test_matrix( 4, 2 ) = 53;\n    test_matrix( 4, 3 ) = 54;\n    test_matrix( 4, 4 ) = 55;\n        \n    BOOST_UBLAS_TEST_TRACE( \"Full matrix\" );\n    BOOST_UBLAS_TEST_TRACE( std::setw( 3 ) << test_matrix );\n    \n    BOOST_UBLAS_TEST_TRACE( \"data() of matrix\" );\n    for ( size_t i = 0; i < band_storage_size; ++i ) {\n        std::cerr << test_matrix.data()[ i ] << \" \";\n    }\n    std::cerr << std::endl;\n   \n    BOOST_UBLAS_TEST_TRACE( \"Expected data() of matrix\" );\n    for ( size_t i = 0; i < band_storage_size; ++i ) {\n        std::cerr << expected_index( i, Orientation() ) << \" \";\n    }\n    std::cerr << std::endl;\n    \n    size_t mismatch = 0;\n\n    for ( size_t i = 0; i < band_storage_size; ++i ) {\n      if ( test_matrix.data()[ i ] != expected_index( i, Orientation() ) ) {\n        ++mismatch;\n      }\n    }\n\n    return 0 == mismatch;\n}\n\ntemplate< typename Orientation >\nbool test_band_storage_6_by_5() {\n\n    int m = 6;\n    int n = 5;\n    int kl = 2;\n    int ku = 1;\n\n\n    banded_matrix< int, Orientation > test_matrix( m, n, kl, ku );\n    test_matrix.clear();\n    size_t band_storage_size = test_matrix.data().size();\n\n    test_matrix( 0, 0 ) = 11;\n    test_matrix( 0, 1 ) = 12;\n    test_matrix( 1, 0 ) = 21;\n    test_matrix( 1, 1 ) = 22;\n    test_matrix( 1, 2 ) = 23;\n    test_matrix( 2, 0 ) = 31;\n    test_matrix( 2, 1 ) = 32;\n    test_matrix( 2, 2 ) = 33;\n    test_matrix( 2, 3 ) = 34;\n    test_matrix( 3, 1 ) = 42;\n    test_matrix( 3, 2 ) = 43;\n    test_matrix( 3, 3 ) = 44;\n    test_matrix( 3, 4 ) = 45;\n    test_matrix( 4, 2 ) = 53;\n    test_matrix( 4, 3 ) = 54;\n    test_matrix( 4, 4 ) = 55;\n    test_matrix( 5, 3 ) = 64;\n    test_matrix( 5, 4 ) = 65;\n\n    BOOST_UBLAS_TEST_TRACE( \"Full matrix\" );\n    BOOST_UBLAS_TEST_TRACE( std::setw( 3 ) << test_matrix );\n\n    BOOST_UBLAS_TEST_TRACE( \"data() of matrix\" );\n    for ( size_t i = 0; i < band_storage_size; ++i ) {\n        std::cerr << test_matrix.data()[ i ] << \" \";\n    }\n    std::cerr << std::endl;\n\n    BOOST_UBLAS_TEST_TRACE( \"Expected data() of matrix\" );\n    for ( size_t i = 0; i < band_storage_size; ++i ) {\n        std::cerr << expected_index_6_by_5( i, Orientation() ) << \" \";\n    }\n    std::cerr << std::endl;\n\n    size_t mismatch = 0;\n\n    for ( size_t i = 0; i < band_storage_size; ++i ) {\n      if ( test_matrix.data()[ i ] != expected_index_6_by_5( i, Orientation() ) ) {\n        ++mismatch;\n      }\n    }\n\n    return 0 == mismatch;\n}\n\ntemplate< typename Orientation >\nbool test_band_storage_5_by_6() {\n\n    int m = 5;\n    int n = 6;\n    int kl = 2;\n    int ku = 1;\n\n    banded_matrix< int, Orientation > test_matrix( m, n, kl, ku );\n    test_matrix.clear();\n    size_t band_storage_size = test_matrix.data().size();\n\n    test_matrix( 0, 0 ) = 11;\n    test_matrix( 0, 1 ) = 12;\n    test_matrix( 1, 0 ) = 21;\n    test_matrix( 1, 1 ) = 22;\n    test_matrix( 1, 2 ) = 23;\n    test_matrix( 2, 0 ) = 31;\n    test_matrix( 2, 1 ) = 32;\n    test_matrix( 2, 2 ) = 33;\n    test_matrix( 2, 3 ) = 34;\n    test_matrix( 3, 1 ) = 42;\n    test_matrix( 3, 2 ) = 43;\n    test_matrix( 3, 3 ) = 44;\n    test_matrix( 3, 4 ) = 45;\n    test_matrix( 4, 2 ) = 53;\n    test_matrix( 4, 3 ) = 54;\n    test_matrix( 4, 4 ) = 55;\n    test_matrix( 4, 5 ) = 56;\n\n    BOOST_UBLAS_TEST_TRACE( \"Full matrix\" );\n    BOOST_UBLAS_TEST_TRACE( std::setw( 3 ) << test_matrix );\n\n    BOOST_UBLAS_TEST_TRACE( \"data() of matrix\" );\n    for ( size_t i = 0; i < band_storage_size; ++i ) {\n        std::cerr << test_matrix.data()[ i ] << \" \";\n    }\n    std::cerr << std::endl;\n\n    BOOST_UBLAS_TEST_TRACE( \"Expected data() of matrix\" );\n    for ( size_t i = 0; i < band_storage_size; ++i ) {\n        std::cerr << expected_index_5_by_6( i, Orientation() ) << \" \";\n    }\n    std::cerr << std::endl;\n\n    size_t mismatch = 0;\n\n    for ( size_t i = 0; i < band_storage_size; ++i ) {\n      if ( test_matrix.data()[ i ] != expected_index_5_by_6( i, Orientation() ) ) {\n        ++mismatch;\n      }\n    }\n\n    return 0 == mismatch;\n}\n\n\n\n\nBOOST_UBLAS_TEST_DEF( banded_matrix_column_major )\n{\n\tBOOST_UBLAS_TEST_TRACE( \"Test case: storage layout banded_matrix < column_major >\" );\n\n    BOOST_UBLAS_TEST_CHECK( test_band_storage< column_major >() );\n}\n\nBOOST_UBLAS_TEST_DEF( banded_matrix_row_major )\n{\n\tBOOST_UBLAS_TEST_TRACE( \"Test case: storage layout banded_matrix < row_major >\" );\n\n    BOOST_UBLAS_TEST_CHECK( test_band_storage< row_major >() );\n}\n\nBOOST_UBLAS_TEST_DEF( banded_matrix_column_major_6_by_5 )\n{\n    BOOST_UBLAS_TEST_TRACE( \"Test case: storage layout banded_matrix < column_major > 6x5\" );\n\n    BOOST_UBLAS_TEST_CHECK( test_band_storage_6_by_5< column_major >() );\n}\n\nBOOST_UBLAS_TEST_DEF( banded_matrix_row_major_6_by_5 )\n{\n    BOOST_UBLAS_TEST_TRACE( \"Test case: storage layout banded_matrix < row_major > 6x5\" );\n\n    BOOST_UBLAS_TEST_CHECK( test_band_storage_6_by_5< row_major >() );\n}\n\nBOOST_UBLAS_TEST_DEF( banded_matrix_column_major_5_by_6 )\n{\n    BOOST_UBLAS_TEST_TRACE( \"Test case: storage layout banded_matrix < column_major > 5x6\" );\n\n    BOOST_UBLAS_TEST_CHECK( test_band_storage_5_by_6< column_major >() );\n}\n\nBOOST_UBLAS_TEST_DEF( banded_matrix_row_major_5_by_6 )\n{\n    BOOST_UBLAS_TEST_TRACE( \"Test case: storage layout banded_matrix < row_major > 5x6\" );\n\n    BOOST_UBLAS_TEST_CHECK( test_band_storage_5_by_6< row_major >() );\n}\n\nint main()\n{\n\n\tBOOST_UBLAS_TEST_SUITE( \"Test storage layout of banded matrix type\" );\n\n\tBOOST_UBLAS_TEST_TRACE( \"Example data taken from http://www.netlib.org/lapack/lug/node124.html\" );\n\n\tBOOST_UBLAS_TEST_BEGIN();\n\n    BOOST_UBLAS_TEST_DO( banded_matrix_column_major );\n    \n    BOOST_UBLAS_TEST_DO( banded_matrix_row_major );\n\n    BOOST_UBLAS_TEST_DO( banded_matrix_column_major_6_by_5 );\n\n    BOOST_UBLAS_TEST_DO( banded_matrix_row_major_6_by_5 );\n\n    BOOST_UBLAS_TEST_DO( banded_matrix_column_major_5_by_6 );\n\n    BOOST_UBLAS_TEST_DO( banded_matrix_row_major_5_by_6 );\n\n    BOOST_UBLAS_TEST_END();\n}\n", "meta": {"hexsha": "d5c640b93202abb392e4d38f6f9fe78cdecde23a", "size": 8340, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/ublas/test/test_banded_storage_layout.cpp", "max_stars_repo_name": "cpp-pm/boost", "max_stars_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "libs/numeric/ublas/test/test_banded_storage_layout.cpp", "max_issues_repo_name": "cpp-pm/boost", "max_issues_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "libs/numeric/ublas/test/test_banded_storage_layout.cpp", "max_forks_repo_name": "cpp-pm/boost", "max_forks_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 28.9583333333, "max_line_length": 112, "alphanum_fraction": 0.6181055156, "num_tokens": 2921, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737473266735, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.4750428862057126}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2012-2015 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_CONSTANT_MINDENORMAL_HPP_INCLUDED\n#define BOOST_SIMD_CONSTANT_MINDENORMAL_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n  /*!\n    @ingroup group-constant\n\n    Generate the the least of all non zero positive value including denormals.\n\n    @par Semantic:\n\n    @code\n    T r = Mindenormal<T>();\n    @endcode\n\n    is similar to:\n\n    @code\n    if T is integral\n      r = T(1)\n    else if T is double\n      r =  4.940656458412465e-324;\n    else if T is float\n      r = 1.4012985e-45;\n    @endcode\n\n    @return The Mindenormal constant for the proper type\n  **/\n  template<typename T> T Mindenormal();\n\n  namespace functional\n  {\n    /*!\n      @ingroup group-callable-constant\n      Generate the  constant mindenormal.\n\n      @return The Mindenormal constant for the proper type\n    **/\n    const boost::dispatch::functor<tag::mindenormal_> mindenormal = {};\n  }\n} }\n#endif\n\n#include <boost/simd/constant/definition/mindenormal.hpp>\n#include <boost/simd/arch/common/scalar/constant/constant_value.hpp>\n#include <boost/simd/arch/common/simd/constant/constant_value.hpp>\n\n#endif\n", "meta": {"hexsha": "a011444ca57d00b6f70e8abbe8402d3d0dd6b3da", "size": 1517, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/constant/mindenormal.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/constant/mindenormal.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/constant/mindenormal.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": 24.868852459, "max_line_length": 100, "alphanum_fraction": 0.608437706, "num_tokens": 352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583376458153, "lm_q2_score": 0.682573740869499, "lm_q1q2_score": 0.47504288601622197}}
{"text": "#include <string>\n\n#define BOOST_TEST_MODULE DenseLatticeMultTests\n\n\n\n#include \"DenseLattice.h\"\n#include \"MIAConfig.h\"\n\n#ifdef MIA_USE_HEADER_ONLY_TESTS\r\n#include <boost/test/included/unit_test.hpp>\r\n#else\r\n#include <boost/test/unit_test.hpp>\r\n#endif\n\n\ntemplate<typename T1,typename T2,typename T3>\nvoid multwork(const std::string & _result){\n    typedef LibMIA::DenseLattice<T1> Lat1;\n    typedef LibMIA::DenseLattice<T2> Lat2;\n    typedef LibMIA::DenseLattice<T3> Lat3;\n\n    Lat1 test1= Lat1(5,5,10);\n    test1.load(\"data/test1.bin\");\n    Lat2 test2= Lat2(5,5,10);\n\n    test2.load(\"data/test2.bin\");\n    Lat3 test3=test1*test2;\n    test3.save(_result);\n    Lat3 test3check;\n    test3check.load(_result);\n    BOOST_CHECK( test3 == test3check );\n\n}\n\nBOOST_AUTO_TEST_CASE( DenseLatticeMultTests )\n{\n\n\n    multwork<double,double,double>(\"data/multtest_ddd.bin\");\n    multwork<float,float,double>(\"data/multtest_dff.bin\");\n    multwork<float,float,float>(\"data/multtest_fff.bin\");\n    multwork<double,double,float>(\"data/multtest_ddf.bin\");\n    multwork<int32_t,int32_t,int32_t>(\"data/multtest_iii.bin\");\n    multwork<int64_t,int64_t,int64_t>(\"data/multtest_lll.bin\");\n\n\n\n\n}\n", "meta": {"hexsha": "db1fc4b7ced084bbb024e3ffe0fb84932984e6dd", "size": 1172, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tests/DenseLattice/denselatticemulttests.cpp", "max_stars_repo_name": "extragoya/LibNT", "max_stars_repo_head_hexsha": "60372bf4e3c5d6665185358c4756da4fe547f093", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-26T05:11:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-26T05:11:32.000Z", "max_issues_repo_path": "src/tests/DenseLattice/denselatticemulttests.cpp", "max_issues_repo_name": "extragoya/LibNT", "max_issues_repo_head_hexsha": "60372bf4e3c5d6665185358c4756da4fe547f093", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/DenseLattice/denselatticemulttests.cpp", "max_forks_repo_name": "extragoya/LibNT", "max_forks_repo_head_hexsha": "60372bf4e3c5d6665185358c4756da4fe547f093", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-09-21T15:38:23.000Z", "max_forks_repo_forks_event_max_datetime": "2017-09-21T15:38:23.000Z", "avg_line_length": 22.9803921569, "max_line_length": 63, "alphanum_fraction": 0.7201365188, "num_tokens": 342, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583376458153, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.47504288152229734}}
{"text": "// -*- Mode: c++; c-basic-offset: 4 -*-\n\n// This C++ script reads a CFN with enumerated variables and table cost\n// functions only and computes a possibly improved starting upper\n// bound (the sum of all the maximum finite costs in tables where\n// finite means less than the initially provided upper bound).\n// Author: George Katsirelos\n\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <vector>\n#include <string>\n#include <tuple>\n#include <map>\n#include <unordered_map>\n#include <boost/format.hpp>\n\nusing namespace std;\nusing boost::format;\n\nconst bool debug = false;\n\ntemplate<typename T>\nostream& operator<<(ostream& os, vector<T> const& v)\n{\n    os << \"[\";\n    for(auto& t : v)\n        os << t << ' ';\n    os << \"]\";\n    return os;\n}\n\ntypedef long long Cost;\n\nstruct wcsptuple {\n    vector<size_t> tup;\n    Cost cost;\n};\n\nstruct wcspfunc {\n    Cost defcost;\n    vector<size_t> scope;\n    vector< wcsptuple > specs;\n\n    size_t arity() const { return scope.size(); }\n};\n\nstruct wcsp {\n    string name;\n    Cost ub;\n\n    vector<size_t> domains;\n    size_t nvars() const { return domains.size(); }\n\n    vector<wcspfunc> functions;\n};\n\ntemplate<typename T>\nvector<T> read_vec(istream& is)\n{\n    vector<T> r;\n    T s;\n    is >> s;\n    while(is) {\n        r.push_back(s);\n        is >> s;\n    }\n    return r;\n}\n\ntemplate<typename T>\nvector<T> read_vec(string const& line)\n{\n    istringstream iss(line);\n    return read_vec<T>(iss);\n}\n\ntuple<string, size_t, size_t, size_t, Cost> read_header(string const& line)\n{\n    istringstream iss(line);\n\n    string name;\n    size_t nvars;\n    size_t domsize;\n    size_t nfun;\n    Cost ub;\n\n    iss >> name >> nvars >> domsize >> nfun >> ub;\n    return make_tuple(name, nvars, domsize, nfun, ub);\n}\n\nwcspfunc read_fun(istream& is)\n{\n    string line;\n    getline(is, line);\n    vector<Cost> hd = read_vec<Cost>(line);\n    size_t arity = hd[0];\n    Cost defcost = hd[hd.size()-2];\n    size_t nspec = hd[hd.size()-1];\n\n    vector<wcsptuple> specs;\n    for(size_t i = 0; i != nspec; ++i) {\n        getline(is, line);\n        vector<Cost> v = read_vec<Cost>(line);\n        specs.push_back( {vector<size_t>(v.begin(), v.begin()+arity), v[v.size()-1]} );\n    }\n\n    return { defcost, vector<size_t>(hd.begin()+1, hd.begin()+1+arity),\n            specs };\n}\n\nwcsp readwcsp(istream& is)\n{\n    wcsp w;\n\n    size_t nvars;\n    size_t domsize;\n    size_t nfun;\n\n    string line;\n\n    getline(is, line);\n    tie(w.name, nvars, domsize, nfun, w.ub) = read_header(line);\n\n    getline(is, line);\n    w.domains = read_vec<size_t>(line);\n\n    for(size_t i = 0; i != nfun; ++i)\n        w.functions.push_back(read_fun(is));\n\n    return w;\n}\n\nvoid write_wcsp(wcsp const& w, ostream &ofs)\n{\n    size_t maxd = *max_element(w.domains.begin(), w.domains.end());\n    ofs << w.name << ' ' << w.nvars()\n        << ' ' << maxd\n        << ' ' << w.functions.size() << ' ' << w.ub << \"\\n\";\n\n    for(auto& d : w.domains)\n        ofs << d << ' ';\n    ofs << \"\\n\";\n\n    for(auto& f: w.functions) {\n        ofs << f.arity() << ' ';\n        for(auto& v : f.scope)\n            ofs << v << ' ';\n        ofs << f.defcost << ' ' << f.specs.size() << \"\\n\";\n        for(auto& s : f.specs) {\n            for(auto& v : s.tup)\n                ofs << v << ' ';\n            ofs << min(s.cost, w.ub) << \"\\n\";\n        }\n    }\n}\n\nint main(int argc, char* argv[])\n{\n    if( argc != 3 ) {\n        cout << \"usage: \" << argv[0] << \" <wcsp-input> <wcnf-output>\\n\";\n        return 1;\n    }\n\n    ifstream ifs(argv[1]);\n    ofstream ofs(argv[2]);\n\n    if( !ifs ) {\n        cout << \"could not open \" << argv[1] << \"\\n\";\n        return 1;\n    }\n\n    if( !ofs ) {\n        cout << \"could not open \" << argv[2] << \"\\n\";\n        return 1;\n    }\n\n    wcsp w = readwcsp(ifs);\n    //cout << \"initial top \" << w.ub << \"\\n\";\n    Cost newtop = 0;\n    for(auto const& f : w.functions) {\n        auto me = std::max_element(f.specs.begin(), f.specs.end(),\n                                   [&](wcsptuple const& m, wcsptuple const& c){\n                                       return c.cost < w.ub &&\n                                       (c.cost > m.cost ||\n                                        m.cost >= w.ub);\n                                   });\n        //cout << \"max of function \" << f.scope << \": \" << me->cost << \"\\n\";\n        newtop += me->cost;\n    }\n    cout << \"new top \" << newtop << \"\\n\";\n    w.ub = newtop;\n    write_wcsp(w, ofs);\n\n    return 0;\n}\n", "meta": {"hexsha": "e5aae3c78732bb5f5f2e71e061a93cf5a139acf8", "size": 4447, "ext": "cc", "lang": "C++", "max_stars_repo_path": "misc/script/wcsp-better-top.cc", "max_stars_repo_name": "kad15/SandBoxToulbar2", "max_stars_repo_head_hexsha": "31430ec5e6c6cec1eabe6f5d04bfb8134777821c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 33.0, "max_stars_repo_stars_event_min_datetime": "2018-08-16T18:14:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T10:26:18.000Z", "max_issues_repo_path": "misc/script/wcsp-better-top.cc", "max_issues_repo_name": "kad15/SandBoxToulbar2", "max_issues_repo_head_hexsha": "31430ec5e6c6cec1eabe6f5d04bfb8134777821c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2018-08-09T06:53:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T10:26:24.000Z", "max_forks_repo_path": "misc/script/wcsp-better-top.cc", "max_forks_repo_name": "kad15/SandBoxToulbar2", "max_forks_repo_head_hexsha": "31430ec5e6c6cec1eabe6f5d04bfb8134777821c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2018-06-06T15:19:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-11T17:09:27.000Z", "avg_line_length": 22.4595959596, "max_line_length": 87, "alphanum_fraction": 0.5230492467, "num_tokens": 1244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583376458152, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.4750428815222973}}
{"text": "#define BOOST_TEST_MODULE vector\n\n#include <boost/test/unit_test.hpp>\n#include <boost/test/test_case_template.hpp>\n#include <boost/mpl/list.hpp>\n\n\n#include <mla/vector/all.h++>\n#include <mla/vector/convert.h++>\n\n\ntypedef boost::mpl::list<\n\tmla::vector::Dense<float>,\n\tmla::vector::Dense<double>,\n\tmla::vector::SparseCS<float>,\n\tmla::vector::SparseCS<double>\n> vector_type_list;\n\n\nusing VectorTypeFrom = mla::vector::Dense<float>;\n\n\n\nBOOST_AUTO_TEST_SUITE(vector)\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( convert, VectorTypeTo, vector_type_list )\n{\n\tsize_t vector_size = 6;\n\n\t//VectorTypeFrom from(vector_size);\t// g++ throws segfault\n\tmla::vector::Dense<float> from(vector_size);\n\n\tfrom.setValue(1, 1.0f);\n\tfrom.setValue(3, 3.0f);\n\tfrom.setValue(5, 5.0f);\n\n\tVectorTypeTo to(vector_size);\n\n\n\tmla::vector::convert(from, to);\n\n\tBOOST_CHECK_EQUAL(from.size(), to.size());\n\n\tfor(size_t i = 0; i < vector_size; i++)\n\t{\n\t\tBOOST_CHECK_EQUAL(from.getValue(i), to.getValue(i));\n\t}\n}\n\n\n\nBOOST_AUTO_TEST_SUITE_END()\n\n", "meta": {"hexsha": "34822e7429e34d125ccfd11a9076492aa5c1cf6f", "size": 997, "ext": "c++", "lang": "C++", "max_stars_repo_path": "unit_tests/test_vector_convert.c++", "max_stars_repo_name": "ruimaciel/mla", "max_stars_repo_head_hexsha": "b05f5913067af31a345cd2187de25871dbe31856", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "unit_tests/test_vector_convert.c++", "max_issues_repo_name": "ruimaciel/mla", "max_issues_repo_head_hexsha": "b05f5913067af31a345cd2187de25871dbe31856", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unit_tests/test_vector_convert.c++", "max_forks_repo_name": "ruimaciel/mla", "max_forks_repo_head_hexsha": "b05f5913067af31a345cd2187de25871dbe31856", "max_forks_repo_licenses": ["BSD-3-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.1272727273, "max_line_length": 72, "alphanum_fraction": 0.7221664995, "num_tokens": 277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544335934766, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.47491871660064366}}
{"text": "\n\n#include <bio/random.h>\nUSING_BIO_NS\n\n#include <boost/test/unit_test.hpp>\nusing namespace boost;\nusing boost::unit_test::test_suite;\n\n#include <iostream>\nusing namespace std;\n\n\nvoid\ncheck_random()\n{\n\tcout << \"******* check_random()\" << endl;\n\n\t//make sure that we can seed the random numbers at will\n\tseed_default_rng(1234);\n\tBOOST_CHECK_EQUAL(get_uniform_index(5), 3u);\n\tBOOST_CHECK_EQUAL(get_uniform_index(5), 4u);\n\tBOOST_CHECK_EQUAL(get_uniform_index(5), 3u);\n\tBOOST_CHECK_EQUAL(get_uniform_index(5), 3u);\n\tBOOST_CHECK_EQUAL(get_uniform_index(5), 4u);\n\n\t//make sure our random values are within range - check a few times\n\tfor (size_t i = 1; i < 1000; ++i)\n\t{\n\t\tBIO_NS::float_t rnd_01 = BIO_NS::float_t(get_uniform_01());\n\t\tBOOST_CHECK(0.0 <= rnd_01);\n\t\tBOOST_CHECK(rnd_01 <= 1.0);\n\t}\n\n\t//do tests over various ranges\n\tfor (size_t max = 1; max < 100; ++max)\n\t{\n\t\t//check we hit every number in the range - this _could_ take a long time\n\t\tfor (size_t num = 0; max != num; ++num)\n\t\t{\n\t\t\tsize_t rnd_idx;\n\t\t\twhile (num != (rnd_idx = get_uniform_index(max)))\n\t\t\t{\n\t\t\t\t//check we are in the right range\n\t\t\t\tBOOST_CHECK(rnd_idx < max);\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid register_random_tests(test_suite * test)\n{\n\ttest->add(BOOST_TEST_CASE(&check_random), 0);\n}\n\n\n", "meta": {"hexsha": "e535e7376ee14224295d239a9745ebad20653e77", "size": 1247, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "C++/test/check_random.cpp", "max_stars_repo_name": "JohnReid/biopsy", "max_stars_repo_head_hexsha": "1eeb714ba5b53f2ecf776d865d32e2078cbc0338", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "C++/test/check_random.cpp", "max_issues_repo_name": "JohnReid/biopsy", "max_issues_repo_head_hexsha": "1eeb714ba5b53f2ecf776d865d32e2078cbc0338", "max_issues_repo_licenses": ["MIT"], "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++/test/check_random.cpp", "max_forks_repo_name": "JohnReid/biopsy", "max_forks_repo_head_hexsha": "1eeb714ba5b53f2ecf776d865d32e2078cbc0338", "max_forks_repo_licenses": ["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.8771929825, "max_line_length": 74, "alphanum_fraction": 0.6928628709, "num_tokens": 374, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6791786991753931, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.47491871234398697}}
{"text": "#include <benchmark.hpp>\n#include <mpi.hpp>\n\n#include <boost/container/vector.hpp>\n#include <mpi.h>\n\n#include <algorithm>\n#include <cmath>\n#include <iostream>\n#include <random>\n#include <stdexcept>\n\nnamespace\n{\n\nstatic constexpr std::size_t ITERATIONS_COUNT = 100;\n\nnamespace bc = boost::container;\n\nstruct Data\n{\n    bc::vector<double> a;\n    bc::vector<double> b;\n};\n\nData generate_data(std::size_t size)\n{\n    Data data;\n    if (my::mpi::is_current_process_root())\n    {\n        data.a.resize(size, bc::default_init_t{});\n        data.b.resize(size, bc::default_init_t{});\n\n        auto generator = []()\n        {\n            static std::mt19937 prng(std::random_device{}());\n            static std::uniform_real_distribution<double> dist(-1000, 1000);\n            return dist(prng);\n        };\n\n        std::generate(data.a.data(), data.a.data() + size, generator);\n        std::generate(data.b.data(), data.b.data() + size, generator);\n    }\n    return data;\n}\n\ndouble dot_product_regular(const double* a, const double* b, std::size_t size)\n{\n    double dot_product = 0;\n    for (std::size_t i = 0; i < size; ++i)\n    {\n        dot_product += a[i] * b[i];\n    }\n    return dot_product;\n}\n\ndouble dot_product_mpi(const double* a, const double* b, std::size_t size)\n{\n    const auto& mpi_params = my::mpi::Params::get_instance();\n\n    auto get_offset = [&mpi_params](std::size_t index, std::size_t size) -> std::size_t\n    {\n        std::size_t offset;\n        std::size_t quotient = size / mpi_params.process_count();\n        std::size_t remainder = size % mpi_params.process_count();\n\n        if (index <= remainder)\n        {\n            offset = (quotient + 1) * index;\n        }\n        else\n        {\n            offset = (quotient + 1) * remainder;\n            offset += quotient * (index - remainder);\n        }\n\n        return offset;\n    };\n\n    auto get_count = [&mpi_params](std::size_t index, std::size_t size) -> std::size_t\n    {\n        std::size_t count;\n        std::size_t quotient  = size / mpi_params.process_count();\n        std::size_t remainder = size % mpi_params.process_count();\n\n        count = quotient + (index < remainder ? 1 : 0);\n\n        return count;\n    };\n\n    bc::vector<int> counts, offsets;\n\n    if (my::mpi::is_current_process_root())\n    {\n        counts.resize (mpi_params.process_count(), bc::default_init_t{});\n        offsets.resize(mpi_params.process_count(), bc::default_init_t{});\n\n        for (std::size_t i = 0; i < mpi_params.process_count(); ++i)\n        {\n            offsets[i] = static_cast<int>(get_offset(i, size));\n            counts[i]  = static_cast<int>(get_count(i, size));\n        }\n    }\n\n    std::size_t size_part = get_count(mpi_params.process_id(), size);\n    bc::vector<double> a_part(size_part, bc::default_init_t{});\n    bc::vector<double> b_part(size_part, bc::default_init_t{});\n\n    my::mpi::scatterv(a, counts.data(), offsets.data(), MPI_DOUBLE, a_part.data(), static_cast<int>(size_part), MPI_DOUBLE);\n    my::mpi::scatterv(b, counts.data(), offsets.data(), MPI_DOUBLE, b_part.data(), static_cast<int>(size_part), MPI_DOUBLE);\n\n    double dot_product_part = 0;\n    for (std::size_t i = 0; i < size_part; ++i)\n    {\n        dot_product_part += a_part[i] * b_part[i];\n    }\n\n    double dot_product = 0;\n    my::mpi::reduce(&dot_product_part, &dot_product, 1, MPI_DOUBLE, MPI_SUM);\n\n    return dot_product;\n}\n\nvoid benchmark(const double* a, const double* b, std::size_t size)\n{\n    if (my::mpi::is_current_process_root())\n    {\n        auto dot_product_regular_wrapper = [a, b, size]()\n        {\n            return dot_product_regular(a, b, size);\n        };\n        double dot_product_regular_result = my::benchmark_function(dot_product_regular_wrapper, ITERATIONS_COUNT);\n        my::print_result(\"Regular time: \", dot_product_regular_result);\n    }\n\n    double dot_product_mpi_result;\n    {\n        auto dot_product_mpi_wrapper = [a, b, size]()\n        {\n            return dot_product_mpi(a, b, size);\n        };\n        dot_product_mpi_result = my::benchmark_function(dot_product_mpi_wrapper, ITERATIONS_COUNT);\n    }\n    if (my::mpi::is_current_process_root())\n    {\n        my::print_result(\"    MPI time: \", dot_product_mpi_result);\n    }\n}\n\nvoid test(const double* a, const double* b, std::size_t size)\n{\n    auto are_doubles_equal = [](double a, double b) -> bool\n    {\n        static constexpr double accuracy = 1e-3;\n        return std::abs(a - b) < accuracy;\n    };\n\n    double result_mpi = dot_product_mpi(a, b, size);\n\n    if (my::mpi::is_current_process_root())\n    {\n        double result_regular = dot_product_regular(a, b, size);\n        if (!are_doubles_equal(result_regular, result_mpi))\n        {\n            throw std::runtime_error(\"Test failed!\");\n        }\n        std::cout << \"Test passed\" << std::endl;\n    }\n}\n\n}  // namespace\n\nint main(int argc, char* argv[]) try\n{\n    my::mpi::Control mpi_control(argc, argv);\n\n    const auto& mpi_params = my::mpi::Params::get_instance();\n    static constexpr int size = 1 << 23;\n\n    if (size < mpi_params.process_count())\n    {\n        throw std::runtime_error(\"Vector length is less than processor count, please decrease number of processors.\");\n    }\n\n    auto [a, b] = generate_data(size);\n\n    bool do_test = false;\n\n    if (do_test)\n        test(a.data(), b.data(), size);\n    else\n        benchmark(a.data(), b.data(), size);\n\n    return EXIT_SUCCESS;\n}\ncatch (const std::exception& e)\n{\n    std::cerr << \"Exception caught: \" << e.what() << std::endl;\n    return EXIT_FAILURE;\n}\ncatch (...)\n{\n    std::cerr << \"An unknown exception caught\" << std::endl;\n    return EXIT_FAILURE;\n}\n", "meta": {"hexsha": "b5bd0029010e13fe8a5a44e55b560b51851fd4b1", "size": 5633, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mpi-dot-product/src/main.cpp", "max_stars_repo_name": "kovdan01/parallel-computing", "max_stars_repo_head_hexsha": "878d836e4b05563dc7fe11b6d7ca65fea950b5b7", "max_stars_repo_licenses": ["Intel"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/mpi-dot-product/src/main.cpp", "max_issues_repo_name": "kovdan01/parallel-computing", "max_issues_repo_head_hexsha": "878d836e4b05563dc7fe11b6d7ca65fea950b5b7", "max_issues_repo_licenses": ["Intel"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mpi-dot-product/src/main.cpp", "max_forks_repo_name": "kovdan01/parallel-computing", "max_forks_repo_head_hexsha": "878d836e4b05563dc7fe11b6d7ca65fea950b5b7", "max_forks_repo_licenses": ["Intel"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3446601942, "max_line_length": 124, "alphanum_fraction": 0.6103319723, "num_tokens": 1413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587586, "lm_q2_score": 0.679178686187839, "lm_q1q2_score": 0.47491869900572564}}
{"text": "// Copyright (C) 2018-2020 Chris Richardson (chris@bpi.cam.ac.uk)\n// SPDX-License-Identifier:    MIT\n\n#include \"CreateA.h\"\n#include <Eigen/Sparse>\n#include <memory>\n#include <set>\n#include <spmv/L2GMap.h>\n\n//-----------------------------------------------------------------------------\n// Divide size into N ~equal chunks\nstd::vector<std::int64_t> owner_ranges(std::int64_t size, std::int64_t N)\n{\n  // Compute number of items per process and remainder\n  const std::int64_t n = N / size;\n  const std::int64_t r = N % size;\n\n  // Compute local range\n  std::vector<std::int64_t> ranges;\n  for (int rank = 0; rank < (size + 1); ++rank) {\n    if (rank < r)\n      ranges.push_back(rank * (n + 1));\n    else\n      ranges.push_back(rank * n + r);\n  }\n\n  return ranges;\n}\n//-----------------------------------------------------------------------------\nspmv::Matrix<double> create_A(MPI_Comm comm, int N)\n{\n  int mpi_rank;\n  MPI_Comm_rank(comm, &mpi_rank);\n  int mpi_size;\n  MPI_Comm_size(comm, &mpi_size);\n\n  // Make a square Matrix divided evenly across cores\n  std::vector<std::int64_t> ranges = owner_ranges(mpi_size, N);\n\n  std::int64_t r0 = ranges[mpi_rank];\n  std::int64_t r1 = ranges[mpi_rank + 1];\n  int M = r1 - r0;\n\n  // Local part of the matrix\n  // Must be RowMajor and compressed\n  Eigen::SparseMatrix<double, Eigen::RowMajor> A(M, N);\n\n  // Set up A\n  // Add entries on all local rows\n  // Using [local_row, global_column] indexing\n  double gamma = 0.1;\n  for (int i = 0; i < M; ++i) {\n    // Global column diagonal index\n    int c0 = r0 + i;\n    // Special case for very first and last global rows\n    if (c0 == 0) {\n      A.insert(i, c0) = 1.0 - gamma;\n      A.insert(i, c0 + 1) = gamma;\n    } else if (c0 == (N - 1)) {\n      A.insert(i, c0 - 1) = gamma;\n      A.insert(i, c0) = 1.0 - gamma;\n    } else {\n      A.insert(i, c0 - 1) = gamma;\n      A.insert(i, c0) = 1.0 - 2.0 * gamma;\n      A.insert(i, c0 + 1) = gamma;\n    }\n  }\n  A.makeCompressed();\n\n  // Remap columns to local indexing\n  std::set<std::int64_t> ghost_indices;\n  std::int32_t nnz = A.outerIndexPtr()[M];\n  for (std::int32_t i = 0; i < nnz; ++i) {\n    std::int32_t global_index = A.innerIndexPtr()[i];\n    if (global_index < r0 or global_index >= r1)\n      ghost_indices.insert(global_index);\n  }\n\n  std::vector<std::int64_t> ghosts(ghost_indices.begin(), ghost_indices.end());\n  auto col_l2g = std::make_shared<spmv::L2GMap>(comm, M, ghosts);\n  auto row_l2g\n      = std::make_shared<spmv::L2GMap>(comm, M, std::vector<std::int64_t>());\n\n  // Rebuild A using local indices\n  auto Alocal = std::make_shared<Eigen::SparseMatrix<double, Eigen::RowMajor>>(\n      M, M + ghosts.size());\n  std::vector<Eigen::Triplet<double>> vals;\n  std::int32_t* Aouter = A.outerIndexPtr();\n  std::int32_t* Ainner = A.innerIndexPtr();\n  double* Aval = A.valuePtr();\n\n  for (std::int32_t row = 0; row < M; ++row) {\n    for (std::int32_t j = Aouter[row]; j < Aouter[row + 1]; ++j) {\n      std::int32_t col = col_l2g->global_to_local(Ainner[j]);\n      double val = Aval[j];\n      vals.push_back(Eigen::Triplet<double>(row, col, val));\n    }\n  }\n  Alocal->setFromTriplets(vals.begin(), vals.end());\n\n  return spmv::Matrix<double>(Alocal, col_l2g, row_l2g);\n}\n//-----------------------------------------------------------------------------\n", "meta": {"hexsha": "faec28685ab188c97707f504cd688a244d2df5e0", "size": 3288, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "demos/CreateA.cpp", "max_stars_repo_name": "Excalibur-SLE/spmv", "max_stars_repo_head_hexsha": "7bd7aa05c5c7018c807160e1d1d70b11a8143eca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "demos/CreateA.cpp", "max_issues_repo_name": "Excalibur-SLE/spmv", "max_issues_repo_head_hexsha": "7bd7aa05c5c7018c807160e1d1d70b11a8143eca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-05-04T15:55:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-04T15:56:02.000Z", "max_forks_repo_path": "demos/CreateA.cpp", "max_forks_repo_name": "Excalibur-SLE/spmv", "max_forks_repo_head_hexsha": "7bd7aa05c5c7018c807160e1d1d70b11a8143eca", "max_forks_repo_licenses": ["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.6153846154, "max_line_length": 79, "alphanum_fraction": 0.5812043796, "num_tokens": 999, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6791786861878392, "lm_q2_score": 0.6992544085240402, "lm_q1q2_score": 0.4749186904924122}}
{"text": "/*=========================================================================\n\n  Program:   Visualization Toolkit\n  Module:    TestBoostAlgorithms.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 \"vtkActor.h\"\n#include \"vtkBoostBrandesCentrality.h\"\n#include \"vtkBoostBreadthFirstSearch.h\"\n#include \"vtkBoostBreadthFirstSearchTree.h\"\n#include \"vtkBoostConnectedComponents.h\"\n#include \"vtkDataSetAttributes.h\"\n#include \"vtkFloatArray.h\"\n#include \"vtkGlyph3D.h\"\n#include \"vtkGlyphSource2D.h\"\n#include \"vtkGraphLayoutView.h\"\n#include \"vtkGraphToPolyData.h\"\n#include \"vtkGraphWriter.h\"\n#include \"vtkTransform.h\"\n#include \"vtkMatrix4x4.h\"\n#include \"vtkMutableUndirectedGraph.h\"\n#include \"vtkPolyDataMapper.h\"\n#include \"vtkProperty.h\"\n#include \"vtkRegressionTestImage.h\"\n#include \"vtkRenderer.h\"\n#include \"vtkRenderWindow.h\"\n#include \"vtkRenderWindowInteractor.h\"\n#include \"vtkSmartPointer.h\"\n\n#include <boost/version.hpp>\n#include \"vtkBoostBiconnectedComponents.h\"\n\n#define VTK_CREATE(type,name) \\\n  vtkSmartPointer<type> name = vtkSmartPointer<type>::New()\n\nint TestBoostBrandesCentrality(int argc, char* argv[])\n{\n  // Create the test graph\n  VTK_CREATE(vtkMutableUndirectedGraph, g);\n\n  VTK_CREATE(vtkMatrix4x4, mat1);\n  mat1->SetElement(1,3, 5);\n  VTK_CREATE(vtkTransform, transform1);\n  transform1->SetMatrix(mat1);\n\n  VTK_CREATE(vtkMatrix4x4, mat2);\n  mat2->SetElement(1,3, 0);\n  VTK_CREATE(vtkTransform, transform2);\n  transform2->SetMatrix(mat2);\n\n  VTK_CREATE(vtkFloatArray, weights);\n  weights->SetName(\"weights\");\n  g->GetEdgeData()->AddArray(weights);\n\n  VTK_CREATE(vtkPoints, pts);\n  g->AddVertex();\n  pts->InsertNextPoint(1, 1, 0);\n  g->AddVertex();\n  pts->InsertNextPoint(1, 0, 0);\n  g->AddVertex();\n  pts->InsertNextPoint(1, -1, 0);\n  g->AddVertex();\n  pts->InsertNextPoint(2, 0, 0);\n  g->AddVertex();\n  pts->InsertNextPoint(3, 0, 0);\n  g->AddVertex();\n  pts->InsertNextPoint(2.5, 1, 0);\n  g->AddVertex();\n  pts->InsertNextPoint(4, 1, 0);\n  g->AddVertex();\n  pts->InsertNextPoint(4, 0, 0);\n  g->AddVertex();\n  pts->InsertNextPoint(4, -1, 0);\n\n  g->SetPoints(pts);\n\n  vtkEdgeType e = g->AddEdge(0, 3);\n  weights->InsertTuple1(e.Id, 10);\n\n  e = g->AddEdge(1, 3);\n  weights->InsertTuple1(e.Id, 10);\n\n  e = g->AddEdge(2, 3);\n  weights->InsertTuple1(e.Id, 10);\n\n  e = g->AddEdge(3, 4);\n  weights->InsertTuple1(e.Id, 1);\n\n  e = g->AddEdge(3, 5);\n  weights->InsertTuple1(e.Id, 10);\n\n  e = g->AddEdge(5, 4);\n  weights->InsertTuple1(e.Id, 10);\n\n  e = g->AddEdge(6, 4);\n  weights->InsertTuple1(e.Id, 10);\n\n  e = g->AddEdge(7, 4);\n  weights->InsertTuple1(e.Id, 10);\n\n  e = g->AddEdge(8, 4);\n  weights->InsertTuple1(e.Id, 10);\n\n  // Test centrality\n  VTK_CREATE(vtkBoostBrandesCentrality, centrality);\n  centrality->SetInputData(g);\n  centrality->SetEdgeWeightArrayName(\"weights\");\n  centrality->SetInvertEdgeWeightArray(1);\n  centrality->UseEdgeWeightArrayOn();\n\n  VTK_CREATE(vtkGraphLayoutView, view);\n  view->SetLayoutStrategyToPassThrough();\n  view->SetRepresentationFromInputConnection(centrality->GetOutputPort());\n  view->ResetCamera();\n  view->SetColorVertices(1);\n  view->SetVertexColorArrayName(\"centrality\");\n  view->SetColorEdges(1);\n  view->SetEdgeColorArrayName(\"centrality\");\n\n  int retVal = vtkRegressionTestImage(view->GetRenderWindow());\n  if (retVal == vtkRegressionTester::DO_INTERACTOR)\n  {\n    view->GetInteractor()->Initialize();\n    view->GetInteractor()->Start();\n    retVal = vtkRegressionTester::PASSED;\n  }\n\n  return !retVal;\n}\n", "meta": {"hexsha": "1f8c4f1ae7646f3b431233381ecae45170861624", "size": 4183, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "Infovis/BoostGraphAlgorithms/Testing/Cxx/TestBoostBrandesCentrality.cxx", "max_stars_repo_name": "forestGzh/VTK", "max_stars_repo_head_hexsha": "bc98327275bd5cfa95c5825f80a2755a458b6da8", "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/Testing/Cxx/TestBoostBrandesCentrality.cxx", "max_issues_repo_name": "forestGzh/VTK", "max_issues_repo_head_hexsha": "bc98327275bd5cfa95c5825f80a2755a458b6da8", "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/Testing/Cxx/TestBoostBrandesCentrality.cxx", "max_forks_repo_name": "forestGzh/VTK", "max_forks_repo_head_hexsha": "bc98327275bd5cfa95c5825f80a2755a458b6da8", "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": 29.2517482517, "max_line_length": 75, "alphanum_fraction": 0.6698541716, "num_tokens": 1180, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.4748958058873225}}
{"text": "/*!\n * \\file\n * \\author Nikos Tsakiridis <tsakirin@auth.gr>\n * \\version 1.0\n *\n * \\brief Implementation of a random engine\n */\n\n#ifndef RANDOM_ENGINE\n#define RANDOM_ENGINE\n\n#include <boost/random/uniform_real_distribution.hpp>\n#include <boost/random/uniform_int_distribution.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/cauchy_distribution.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <assert.h>\n\nextern size_t SEED; /*!< The seed must be defined externally */\n\n/*!\n * \\brief Generate a random float between (min, max) from a uniform distribution\n *\n * \\param min : lower value\n * \\param max : upper value\n *\n * \\return A random double within (min, max)\n */\n\ninline double rand_uniform_real(const double min, const double max) {\n  assert(min < max);\n  thread_local boost::random::mt19937 generator(SEED);\n  boost::random::uniform_real_distribution<> dist(min, max);\n  return dist(generator);\n}\n\n/**\n * \\brief Generate a random int within [min, max] from a uniform distribution\n *\n * \\param min : lower value\n * \\param max : upper value\n *\n * \\return A random integer within [min, max]\n */\n\ninline int rand_uniform_int(const float min, const float max) {\n  assert(min < max);\n  thread_local boost::random::mt19937 generator(SEED);\n  boost::random::uniform_int_distribution<> dist(min, max);\n  return dist(generator);\n}\n\n/*!\n * \\brief Generate a random float from a normal distribution\n *\n * \\param mean  : mean value of the normal distribution\n * \\param sigma : standard deviation of the normal distribution\n *\n * \\return A random double\n */\n\ninline double rand_normal(const double mean, const double sigma) {\n  thread_local boost::random::mt19937 generator(SEED);\n  boost::random::normal_distribution<> dist(mean, sigma);\n  return dist(generator);\n}\n\n/*!\n * \\brief Generate a random float from a Cauchy distribution\n *\n * \\param mean  : mean value of the Cauchy distribution\n * \\param sigma : standard deviation of the Cauchy distribution\n *\n * \\return A random double\n */\n\ninline double rand_cauchy(const double mean, const double sigma) {\n  thread_local boost::random::mt19937 generator(SEED);\n  boost::random::normal_distribution<> dist(mean, sigma);\n  return dist(generator);\n}\n\n#endif  // RANDOM_ENGINE\n", "meta": {"hexsha": "2bdb6ed90eee4394c773f5811a35c1d16683303c", "size": 2253, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/rand.hpp", "max_stars_repo_name": "tsakiridis/deplusplus", "max_stars_repo_head_hexsha": "383754182c929ab51d9af045bbf138d6d74c009c", "max_stars_repo_licenses": ["MIT"], "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/rand.hpp", "max_issues_repo_name": "tsakiridis/deplusplus", "max_issues_repo_head_hexsha": "383754182c929ab51d9af045bbf138d6d74c009c", "max_issues_repo_licenses": ["MIT"], "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/rand.hpp", "max_forks_repo_name": "tsakiridis/deplusplus", "max_forks_repo_head_hexsha": "383754182c929ab51d9af045bbf138d6d74c009c", "max_forks_repo_licenses": ["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.8214285714, "max_line_length": 80, "alphanum_fraction": 0.729249889, "num_tokens": 529, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799253, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.4748957984473225}}
{"text": "/*\nCopyright (c) 2013 Daniel Stahlke\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 <vector>\n#include <math.h>\n// This must be included before gnuplot-iostream.h in order to support plotting blitz arrays.\n#include <blitz/array.h>\n\n#include \"gnuplot-iostream.h\"\n\n// Yes, I'm including a *.cc file.  It contains main().\n#include \"examples-framework.cc\"\n\nvoid demo_blitz_basic() {\n\t// -persist option makes the window not disappear when your program exits\n\tGnuplot gp(\"gnuplot -persist\");\n\n\tblitz::Array<double, 2> arr(100, 100);\n\t{\n\t\tblitz::firstIndex i;\n\t\tblitz::secondIndex j;\n\t\tarr = (i-50) * (j-50);\n\t}\n\tgp << \"set pm3d map; set palette\" << std::endl;\n\tgp << \"splot '-'\" << std::endl;\n\tgp.send(arr);\n}\n\nvoid demo_blitz_waves_binary() {\n\tGnuplot gp(\"gnuplot -persist\");\n\n\t// example from Blitz manual:\n\tint N = 64, cycles = 3;\n\tdouble midpoint = (N-1)/2.;\n\tdouble omega = 2.0 * M_PI * cycles / double(N);\n\tdouble tau = - 10.0 / N;\n\tblitz::Array<double, 2> F(N, N);\n\tblitz::firstIndex i;\n\tblitz::secondIndex j;\n\tF = cos(omega * sqrt(pow2(i-midpoint) + pow2(j-midpoint)))\n\t\t* exp(tau * sqrt(pow2(i-midpoint) + pow2(j-midpoint)));\n\n\tgp << \"splot '-' binary\" << gp.binfmt(F) << \"dx=10 dy=10 origin=(5,5,0) with pm3d notitle\" << std::endl;\n\tgp.sendBinary(F);\n}\n\nvoid demo_blitz_sierpinski_binary() {\n\tGnuplot gp(\"gnuplot -persist\");\n\n\tint N = 256;\n\tblitz::Array<blitz::TinyVector<uint8_t, 4>, 2> F(N, N);\n\tfor(int i=0; i<N; i++)\n\tfor(int j=0; j<N; j++) {\n\t\tF(i, j)[0] = i;\n\t\tF(i, j)[1] = j;\n\t\tF(i, j)[2] = 0;\n\t\tF(i, j)[3] = (i&j) ? 0 : 255;\n\t}\n\n\tgp << \"plot '-' binary\" << gp.binfmt(F) << \"with rgbalpha notitle\" << std::endl;\n\tgp.sendBinary(F);\n}\n\nvoid demo_blitz_waves_binary_file() {\n\tGnuplot gp(\"gnuplot -persist\");\n\n\t// example from Blitz manual:\n\tint N = 64, cycles = 3;\n\tdouble midpoint = (N-1)/2.;\n\tdouble omega = 2.0 * M_PI * cycles / double(N);\n\tdouble tau = - 10.0 / N;\n\tblitz::Array<double, 2> F(N, N);\n\tblitz::firstIndex i;\n\tblitz::secondIndex j;\n\tF = cos(omega * sqrt(pow2(i-midpoint) + pow2(j-midpoint)))\n\t\t* exp(tau * sqrt(pow2(i-midpoint) + pow2(j-midpoint)));\n\n\tgp << \"splot\" << gp.binaryFile(F) << \"dx=10 dy=10 origin=(5,5,0) with pm3d notitle\" << std::endl;\n}\n\nvoid demo_blitz_sierpinski_binary_file() {\n\tGnuplot gp(\"gnuplot -persist\");\n\n\tint N = 256;\n\tblitz::Array<blitz::TinyVector<uint8_t, 4>, 2> F(N, N);\n\tfor(int i=0; i<N; i++)\n\tfor(int j=0; j<N; j++) {\n\t\tF(i, j)[0] = i;\n\t\tF(i, j)[1] = j;\n\t\tF(i, j)[2] = 0;\n\t\tF(i, j)[3] = (i&j) ? 0 : 255;\n\t}\n\n\tgp << \"plot\" << gp.binaryFile(F) << \"with rgbalpha notitle\" << std::endl;\n}\n\nvoid register_demos() {\n\tregister_demo(\"basic\",                        demo_blitz_basic);\n\tregister_demo(\"waves_binary\",           demo_blitz_waves_binary);\n\tregister_demo(\"sierpinski_binary\",      demo_blitz_sierpinski_binary);\n\tregister_demo(\"waves_binary_file\",      demo_blitz_waves_binary_file);\n\tregister_demo(\"sierpinski_binary_file\", demo_blitz_sierpinski_binary_file);\n}\n", "meta": {"hexsha": "c2b5226e3e0c810f42aa8d915827a31c70743e25", "size": 3913, "ext": "cc", "lang": "C++", "max_stars_repo_path": "legacy/examples-blitz.cc", "max_stars_repo_name": "zenfey/gnuplot-iostream", "max_stars_repo_head_hexsha": "0e4c5d77a9b2d89b4b9c42e4b1808ce0ef9b3339", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 282.0, "max_stars_repo_stars_event_min_datetime": "2015-04-26T22:33:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T17:23:42.000Z", "max_issues_repo_path": "legacy/examples-blitz.cc", "max_issues_repo_name": "zenfey/gnuplot-iostream", "max_issues_repo_head_hexsha": "0e4c5d77a9b2d89b4b9c42e4b1808ce0ef9b3339", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 21.0, "max_issues_repo_issues_event_min_datetime": "2015-11-04T14:59:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T23:59:33.000Z", "max_forks_repo_path": "legacy/examples-blitz.cc", "max_forks_repo_name": "zenfey/gnuplot-iostream", "max_forks_repo_head_hexsha": "0e4c5d77a9b2d89b4b9c42e4b1808ce0ef9b3339", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 93.0, "max_forks_repo_forks_event_min_datetime": "2015-06-22T21:00:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T07:59:55.000Z", "avg_line_length": 31.8130081301, "max_line_length": 105, "alphanum_fraction": 0.6764630718, "num_tokens": 1215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251201477016, "lm_q2_score": 0.7371581510799253, "lm_q1q2_score": 0.4748957984473225}}
{"text": "/* Boost numeric test for orders of quadrature formulas test file\r\n\r\n Copyright 2015 Gregor de Cillia\r\n Copyright 2015 Mario Mulansky <mario.mulansky@gmx.net>\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// disable checked iterator warning for msvc\r\n#include <boost/config.hpp>\r\n\r\n#ifdef BOOST_MSVC\r\n    #pragma warning(disable:4996)\r\n#endif\r\n\r\n#define BOOST_TEST_MODULE order_quadrature_formula\r\n\r\n#include <iostream>\r\n#include <cmath>\r\n\r\n#include <boost/test/unit_test.hpp>\r\n\r\n#include <boost/mpl/vector.hpp>\r\n\r\n#include <boost/numeric/odeint.hpp>\r\n\r\n#include <boost/numeric/ublas/vector.hpp>\r\n\r\nusing namespace boost::unit_test;\r\nusing namespace boost::numeric::odeint;\r\nnamespace mpl = boost::mpl;\r\n\r\ntypedef double value_type;\r\ntypedef value_type time_type;\r\ntypedef value_type state_type;\r\n\r\nBOOST_AUTO_TEST_SUITE( order_of_convergence_test )\r\n\r\n/* defines the simple monomial f(t) = (p+1) * t^p.*/\r\nstruct monomial\r\n{\r\n    int power;\r\n\r\n    monomial(int p = 0) : power( p ){};\r\n\r\n    void operator()( const state_type &x , state_type &dxdt , const time_type t )\r\n    {\r\n        dxdt = ( 1.0 + power ) * pow( t, power );\r\n    }\r\n};\r\n\r\n\r\n/* generic test for all steppers that support integrate_const */\r\ntemplate< class Stepper >\r\nstruct stepper_order_test\r\n{\r\n    void operator()( int steps = 1 )\r\n    {\r\n        const int estimated_order = estimate_order( steps );\r\n        const int defined_order = Stepper::order_value;\r\n\r\n        std::cout << boost::format( \"%-20i%-20i\\n\" )\r\n\t    % estimated_order %  defined_order;\r\n\r\n        BOOST_REQUIRE_EQUAL( estimated_order, defined_order );\r\n    }\r\n\r\n    /*\r\n    the order of the stepper is estimated by trying to solve the ODE\r\n    x'(t) = (p+1) * t^p\r\n    until the errors are too big to be justified by finite precision.\r\n    the first value p for which the problem is *not* solved within the\r\n    finite precision tolerance is the estimate for the order of the scheme.\r\n     */\r\n    int estimate_order( int steps )\r\n    {\r\n        const double dt = 1.0/steps;\r\n        const double tolerance = steps*1E-15;\r\n        int p;\r\n        for( p = 0; true; p++ )\r\n        {\r\n            // begin with x'(t) = t^0 = 1\r\n            //         => x (t) = t\r\n            // then use   x'(t) = 2*t^1\r\n            //         => x (t) = t^2\r\n            // ...\r\n            state_type x = 0.0;\r\n\r\n            double t = integrate_n_steps( Stepper(), monomial( p ), x, 0.0, dt,\r\n                                          steps );\r\n            if( fabs( x - pow( t, ( 1.0 + p ) ) ) > tolerance )\r\n                break;\r\n        }\r\n        // the smallest power p for which the test failed is the estimated order,\r\n        // as the solution for this power is x(t) = t^{p+1}\r\n        return p;\r\n    }\r\n};\r\n\r\n\r\ntypedef mpl::vector<\r\n    euler< state_type > ,\r\n    modified_midpoint< state_type > ,\r\n    runge_kutta4< state_type > ,\r\n    runge_kutta4_classic< state_type > ,\r\n    runge_kutta_cash_karp54_classic< state_type > ,\r\n    runge_kutta_cash_karp54< state_type > ,\r\n    runge_kutta_dopri5< state_type > ,\r\n    runge_kutta_fehlberg78< state_type >\r\n    > runge_kutta_steppers;\r\n\r\ntypedef mpl::vector<\r\n    adams_bashforth< 2, state_type, double, state_type, double,\r\n                     vector_space_algebra, default_operations,\r\n                     initially_resizer, runge_kutta_fehlberg78< state_type > >,\r\n    adams_bashforth< 3, state_type, double, state_type, double,\r\n                     vector_space_algebra, default_operations,\r\n                     initially_resizer, runge_kutta_fehlberg78< state_type > >,\r\n    adams_bashforth< 4, state_type, double, state_type, double,\r\n                     vector_space_algebra, default_operations,\r\n                     initially_resizer, runge_kutta_fehlberg78< state_type > >,\r\n    adams_bashforth< 5, state_type, double, state_type, double,\r\n                     vector_space_algebra, default_operations,\r\n                     initially_resizer, runge_kutta_fehlberg78< state_type > >,\r\n    adams_bashforth< 6, state_type, double, state_type, double,\r\n                     vector_space_algebra, default_operations,\r\n                     initially_resizer, runge_kutta_fehlberg78< state_type > >,\r\n    adams_bashforth< 7, state_type, double, state_type, double,\r\n                     vector_space_algebra, default_operations,\r\n                     initially_resizer, runge_kutta_fehlberg78< state_type > >,\r\n    adams_bashforth< 8, state_type, double, state_type, double,\r\n                     vector_space_algebra, default_operations,\r\n                     initially_resizer, runge_kutta_fehlberg78< state_type > >\r\n    > ab_steppers;\r\n\r\n\r\ntypedef mpl::vector<\r\n    adams_bashforth_moulton< 2, state_type, double, state_type, double,\r\n                             vector_space_algebra, default_operations,\r\n                             initially_resizer,\r\n                             runge_kutta_fehlberg78< state_type > >,\r\n    adams_bashforth_moulton< 3, state_type, double, state_type, double,\r\n                             vector_space_algebra, default_operations,\r\n                             initially_resizer,\r\n                             runge_kutta_fehlberg78< state_type > >,\r\n    adams_bashforth_moulton< 4, state_type, double, state_type, double,\r\n                             vector_space_algebra, default_operations,\r\n                             initially_resizer,\r\n                             runge_kutta_fehlberg78< state_type > >,\r\n    adams_bashforth_moulton< 5, state_type, double, state_type, double,\r\n                             vector_space_algebra, default_operations,\r\n                             initially_resizer,\r\n                             runge_kutta_fehlberg78< state_type > >,\r\n    adams_bashforth_moulton< 6, state_type, double, state_type, double,\r\n                             vector_space_algebra, default_operations,\r\n                             initially_resizer,\r\n                             runge_kutta_fehlberg78< state_type > >,\r\n    adams_bashforth_moulton< 7, state_type, double, state_type, double,\r\n                             vector_space_algebra, default_operations,\r\n                             initially_resizer,\r\n                             runge_kutta_fehlberg78< state_type > >,\r\n    adams_bashforth_moulton< 8, state_type, double, state_type, double,\r\n                             vector_space_algebra, default_operations,\r\n                             initially_resizer,\r\n                             runge_kutta_fehlberg78< state_type > >\r\n    > abm_steppers;\r\n\r\n\r\nBOOST_AUTO_TEST_CASE_TEMPLATE( runge_kutta_test , Stepper, runge_kutta_steppers )\r\n{\r\n    stepper_order_test< Stepper > tester;\r\n    tester(10);\r\n}\r\n\r\n\r\nBOOST_AUTO_TEST_CASE_TEMPLATE( adams_bashforth_test , Stepper, ab_steppers )\r\n{\r\n    stepper_order_test< Stepper > tester;\r\n    tester(16);\r\n}\r\n\r\n\r\nBOOST_AUTO_TEST_CASE_TEMPLATE( adams_bashforth_moultion_test , Stepper, abm_steppers )\r\n{\r\n    stepper_order_test< Stepper > tester;\r\n    tester(16);\r\n}\r\n\r\nBOOST_AUTO_TEST_SUITE_END()\r\n", "meta": {"hexsha": "5c41db4ce3b96bd40d69bc1501ed3916f3b7e435", "size": 7137, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/odeint/test/numeric/order_quadrature_formula.cpp", "max_stars_repo_name": "lijgame/boost", "max_stars_repo_head_hexsha": "ec2214a19cdddd1048058321a8105dd0231dac47", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-12-15T19:57:24.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-15T19:57:24.000Z", "max_issues_repo_path": "thirdparty-cpp/boost_1_62_0/libs/numeric/odeint/test/numeric/order_quadrature_formula.cpp", "max_issues_repo_name": "nxplatform/nx-mobile", "max_issues_repo_head_hexsha": "0dc174c893f2667377cb2ef7e5ffeb212fa8b3e5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thirdparty-cpp/boost_1_62_0/libs/numeric/odeint/test/numeric/order_quadrature_formula.cpp", "max_forks_repo_name": "nxplatform/nx-mobile", "max_forks_repo_head_hexsha": "0dc174c893f2667377cb2ef7e5ffeb212fa8b3e5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.171875, "max_line_length": 87, "alphanum_fraction": 0.6068376068, "num_tokens": 1687, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.737158174177441, "lm_q2_score": 0.6442250996557036, "lm_q1q2_score": 0.4748957982214785}}
{"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_PINV_HPP_INCLUDED\n#define NT2_LINALG_FUNCTIONS_PINV_HPP_INCLUDED\n#include <nt2/include/functor.hpp>\n#include <boost/simd/include/functor.hpp>\n#include <boost/dispatch/include/functor.hpp>\n#include <nt2/sdk/memory/container.hpp>\n#include <nt2/sdk/meta/size_as.hpp>\n#include <nt2/sdk/meta/value_as.hpp>\n#include <nt2/core/container/dsl/value_type.hpp>\n#include <nt2/core/container/dsl/size.hpp>\n#include <nt2/include/functions/issquare.hpp>\n\n/*!\n * @brief inv  pseudo-inverse of matrix.\n * pinv(x) is the pseudo-inverse of the matrix expression x.\n *\n * x = pinv(a) produces a matrix x of the same dimensions\n * as trans(a) so that a*x*a = a, x*a*x = x and a*x and x*a\n * are hermitian. the computation is based on svd(a) and any\n * singular values less than a tolerance are treated as zero.\n * the default tolerance is max(size(a)) * norm(a) * eps<class(a)> .\n *\n * pinv(a,tol) uses the tolerance tol instead of the default.\n *\n **/\n\nnamespace nt2 { namespace tag\n  {\n    /*!\n     * \\brief Define the tag pinv_ of functor pinv\n     *        in namespace nt2::tag for toolbox algebra\n    **/\n    struct pinv_ :  ext::unspecified_<pinv_> { typedef ext::unspecified_<pinv_> parent; };\n  }\n\n  BOOST_DISPATCH_FUNCTION_IMPLEMENTATION(tag::pinv_, pinv, 1)\n  BOOST_DISPATCH_FUNCTION_IMPLEMENTATION(tag::pinv_, pinv, 2)\n\n}\n\nnamespace nt2 { namespace ext\n{\n  template<class Domain, class Expr,  int N>\n  struct  size_of<tag::pinv_, Domain, N, Expr>\n  {\n    typedef typename boost::proto::result_of::child_c<Expr&,0>::value_type  c0_t;\n    typedef typename c0_t::extent_type                               result_type;\n    BOOST_FORCEINLINE result_type operator()(Expr& e) const\n    {\n      result_type sizee = boost::proto::child_c<0>(e).extent();\n      std::swap(sizee[0], sizee[1]);\n      return sizee;\n    }\n  };\n\n template <class Domain, class Expr,  int N>\n struct value_type < tag::pinv_, Domain,N,Expr>\n  : meta::value_as<Expr,0>\n {};\n} }\n\n#endif\n\n", "meta": {"hexsha": "11fe5dfc06c3d9a6b1984a20c86b65340648427b", "size": 2480, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/linalg/include/nt2/linalg/functions/pinv.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/pinv.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/pinv.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": 34.4444444444, "max_line_length": 90, "alphanum_fraction": 0.6330645161, "num_tokens": 639, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.47489579581676017}}
{"text": "// \r\n// $Id$\r\n//\r\n//\r\n// Original author: Darren Kessner <darren@proteowizard.org>\r\n//\r\n// Copyright 2006 Louis Warschaw Prostate Cancer Center\r\n//   Cedars Sinai Medical Center, Los Angeles, California  90048\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\"); \r\n// you may not use this file except in compliance with the License. \r\n// You may obtain a copy of the License at \r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software \r\n// distributed under the License is distributed on an \"AS IS\" BASIS, \r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \r\n// See the License for the specific language governing permissions and \r\n// limitations under the License.\r\n//\r\n\r\n\r\n#include \"TransientData.hpp\"\r\n#include \"pwiz/data/misc/FrequencyData.hpp\"\r\n#include \"pwiz/utility/misc/unit.hpp\"\r\n#include <boost/filesystem/operations.hpp>\r\n#include <iostream>\r\n#include <cstring>\r\n#include <fstream>\r\n#include <stdexcept>\r\n#include <iterator>\r\n\r\n\r\nusing namespace std;\r\nusing namespace pwiz::data;\r\nusing namespace pwiz::util;\r\n\r\n\r\nostream* os_ = 0;\r\n\r\n\r\nconst double startTime_ = 0.116800;\r\nconst double observationDuration_ = .768;\r\nconst double A_ = 1.075339687500000e+008;\r\nconst double B_ = -3.454602661132810e+008;\r\nconst unsigned int sampleCount_ = 100;\r\n\r\n\r\nstring filename_ = \"TransientDataTest_test.dat\";\r\nstring filenameText_ = \"TransientDataTest_test.dat.txt\";\r\n\r\n \r\nvoid createTestTransients()\r\n{\r\n    TransientData td;\r\n    td.startTime(startTime_);\r\n    td.observationDuration(observationDuration_);\r\n    td.A(A_);\r\n    td.B(B_);\r\n\r\n    td.data().resize(sampleCount_);\r\n    fill(td.data().begin(), td.data().end(), 1);\r\n    \r\n    td.write(filename_);\r\n    td.write(filenameText_, TransientData::Text);\r\n}\r\n\r\n\r\nvoid testBasic(const TransientData& td)\r\n{\r\n    unit_assert(td.startTime() == startTime_); \r\n    unit_assert(td.data().size() == sampleCount_); \r\n    unit_assert_equal(td.observationDuration(), observationDuration_, 1e-12);\r\n    unit_assert_equal(td.A(), A_, 1e-12);\r\n    unit_assert_equal(td.B(), B_, 1e-3);\r\n    unit_assert_equal(td.bandwidth(), sampleCount_/observationDuration_/2, 1e-10);\r\n\r\n    unit_assert(td.data().size() == sampleCount_);\r\n    for (unsigned int i=0; i<sampleCount_; i++)\r\n        unit_assert(td.data()[i] == 1);\r\n    \r\n    if (os_) *os_ \r\n        << setprecision(12)\r\n        << \"Start time: \" << td.startTime() << endl\r\n        << \"Observation duration: \" << td.observationDuration() << endl\r\n        << \"Calibration parameter A: \" << td.A() << endl\r\n        << \"Calibration parameter B: \" << td.B() << endl\r\n        << \"Number of samples: \" << td.data().size() << endl\r\n        << \"Bandwidth: \" << td.bandwidth() << endl\r\n        << \"Magnetic field = \" << td.magneticField() << endl << endl;\r\n}\r\n\r\n\r\nvoid test()\r\n{\r\n    createTestTransients();\r\n\r\n    TransientData td(filename_);\r\n    testBasic(td);\r\n\r\n    TransientData tdText(filenameText_);\r\n    testBasic(tdText);\r\n\r\n    boost::filesystem::remove(filename_);\r\n    boost::filesystem::remove(filenameText_);\r\n}\r\n\r\n\r\nclass TestSignal : public TransientData::Signal\r\n{\r\n    public:\r\n\r\n    virtual double operator()(double t) const\r\n    {\r\n        // sum of two decaying sinusoids at frequencies 100000 and 101000\r\n        return exp(-t)*(cos(100000*2*M_PI*t) + cos(101000*2*M_PI*t));\r\n    }\r\n};\r\n\r\n\r\nvoid testAdd()\r\n{\r\n    if (os_) *os_ << \"testAdd()\\n\";\r\n\r\n    if (os_) *os_ << \"creating signal with two peaks\\n\";\r\n\r\n    TransientData td;\r\n    td.observationDuration(.768);\r\n    td.A(A_);\r\n    td.B(B_);\r\n\r\n    td.data().resize(1048576);\r\n    td.add(TestSignal());\r\n\r\n    if (os_) *os_ << \"computing fft\\n\";\r\n\r\n    FrequencyData fd;\r\n    td.computeFFT(1, fd);\r\n\r\n    // \"peak detection\"  \r\n\r\n    double threshold = 100000 * fd.noiseFloor();\r\n    vector<FrequencyDatum> peaks;\r\n\r\n    for (FrequencyData::iterator it=fd.data().begin(); it!=fd.data().end(); ++it)\r\n        if (abs(it->y) > threshold)\r\n            peaks.push_back(*it);\r\n\r\n    if (os_)\r\n    {\r\n        *os_ << \"found peaks: \" << peaks.size() << endl;\r\n        copy(peaks.begin(), peaks.end(), ostream_iterator<FrequencyDatum>(*os_, \"\\n\"));\r\n    }\r\n    \r\n    unit_assert(peaks.size() == 2);\r\n    unit_assert(peaks[0].x == 100000);\r\n    unit_assert(peaks[1].x == 101000);\r\n}\r\n\r\n\r\nint main(int argc, char* argv[])\r\n{\r\n    try\r\n    {\r\n        if (argc>1 && !strcmp(argv[1],\"-v\")) os_ = &cout;\r\n        if (os_) *os_ << \"TransientDataTest\\n\";\r\n        test();\r\n        testAdd();\r\n        return 0;\r\n    }\r\n    catch (exception& e)\r\n    {\r\n        cerr << e.what() << endl;\r\n        return 1;\r\n    }\r\n}\r\n\r\n\r\n", "meta": {"hexsha": "b14f4577054ae5f77d6c0c59c74124f01257353b", "size": 4679, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pwiz_aux/sfcap/transient/TransientDataTest.cpp", "max_stars_repo_name": "austinkeller/pwiz", "max_stars_repo_head_hexsha": "aa8e575cb40fd5e97cc7d922e4d8da44c9277cca", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pwiz_aux/sfcap/transient/TransientDataTest.cpp", "max_issues_repo_name": "austinkeller/pwiz", "max_issues_repo_head_hexsha": "aa8e575cb40fd5e97cc7d922e4d8da44c9277cca", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pwiz_aux/sfcap/transient/TransientDataTest.cpp", "max_forks_repo_name": "austinkeller/pwiz", "max_forks_repo_head_hexsha": "aa8e575cb40fd5e97cc7d922e4d8da44c9277cca", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9944444444, "max_line_length": 88, "alphanum_fraction": 0.611882881, "num_tokens": 1198, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286833, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.4748957958167601}}
{"text": "//\n//  Jacobian.cpp\n//  Eigen_test\n//\n//  Created by Emil Iliev on 18.10.19.\n//  Copyright \u00a9 2019 Emil Iliev. All rights reserved.\n//\n\n#include \"Jacobian.hpp\"\n#include <iostream>\n#include <Eigen/SVD>\n\nJacobian::Jacobian() : mtxf(MatrixFactory::getInstance()){\n}\n\nvoid Jacobian::setJacobianConfiguration( unsigned int row , unsigned int col ) {\n    //We don't know configuration\n    _jacobian.resize(row , col);\n}\n\nEigen::MatrixXf& Jacobian::getJacobian() {\n    //Get calculated Jacobian\n    return _jacobian;\n}\n\n// Transformation matrix representation\n//\n//|r11 r12 r13 d14|\n//|r21 r22 r23 d24|\n//|r31 r32 r33 d34|\n//|  0   0   0   1|\n//\n\n/************************************************************************/\n/* Main routine for J calculation                                       */\n/************************************************************************/\nvoid Jacobian::calculateJacobian( HomMatrixHolder& hom_matrix_handler , JointHandler& jhandler , Eigen::Matrix4f& full) {\n    unsigned int col_num = jhandler.size();\n\n    if (!col_num) {\n        //Zero size not allowed\n        return;\n    }\n\n    unsigned int row_num = NUMBEROFSETPARAMETERS;\n    unsigned int size = hom_matrix_handler.size();\n    //Set J confiruration\n    setJacobianConfiguration(row_num , col_num);\n    \n    std::vector<Eigen::Matrix4f> trans_matrix_holder;\n    for (int index = 0; index < size + 1; ++index) {\n        trans_matrix_holder.push_back(Eigen::Matrix4f::Identity());\n    }\n\n    for (int index = 1; index < size + 1; ++index) {\n        trans_matrix_holder[index] = trans_matrix_holder[index - 1] * hom_matrix_handler[index - 1];\n    }\n\n    for (unsigned int i = 1 ; i < col_num + 1 ; ++i) {\n        calculateColumnOfJacobian_New(trans_matrix_holder[i - 1],DHINDEX(i),jhandler[DHINDEX(i)].getJointType(),full);\n    }\n}\n\nJacobian* Jacobian::_instance = NULL;\n\nJacobian* Jacobian::getInstance() {\n    if (!_instance)\n        _instance = new Jacobian();\n\n    return _instance;\n}\n\nEigen::MatrixXf Jacobian::psevdoInverse() {\n    Eigen::MatrixXf inv;\n    Eigen::JacobiSVD<Eigen::MatrixXf> svd;\n    svd.compute(_jacobian , Eigen::ComputeThinU | Eigen::ComputeThinV);\n//    svd.pinv(inv);\n    double epsilon = std::numeric_limits<double>::epsilon();\n    double tolerance = epsilon * std::max(_jacobian.cols(), _jacobian.rows()) *svd.singularValues().array().abs()(0);\n    inv = svd.matrixV() * (svd.singularValues().array().abs() > tolerance).select(svd.singularValues().array().inverse(), 0).matrix().asDiagonal() * svd.matrixU().adjoint();\n    return inv;\n}\n\nvoid Jacobian::calculateColumnOfJacobian_New(Eigen::Matrix4f& hom_matrix_handler, unsigned int ind, JointT jt, Eigen::Matrix4f& fullm) {\n    Eigen::Vector3f z0(0.0f , 0.0f , 1.0f);\n    Eigen::Vector3f zi;\n    Eigen::Matrix4f transf_matrix = hom_matrix_handler;\n    Eigen::Matrix3f rot_m;\n\n    Eigen::Vector3f p_end_effector;\n    Eigen::Vector3f pi;\n\n    //Position of end effector\n    p_end_effector<< fullm(0,3), fullm(1,3), fullm(2,3);\n    rot_m = transf_matrix.block(0,0,3,3);\n\n    //\n    //  Zi-1\n    //\n    zi = rot_m * z0;\n    pi << transf_matrix(0,3) , transf_matrix(1,3) , transf_matrix(2,3);\n\n    //\n    //  (Pe - Pi-1)\n    //\n    Eigen::Vector3f delta_vec = p_end_effector - pi;\n\n    //\n    //  Zi x (Pe - Pi-1)\n    //\n    Eigen::Vector3f d_rev = zi.cross(delta_vec);\n\n    //We should get type of joint and go further\n    switch(jt) {\n    case PRISMATIC:\n        //For prismatic joint everything is simple :\n        //        | z | <--- calculated vector z\n        // Cind = |   |\n        //        | 0 | <--- zero vector3f\n        _jacobian(0,ind) = zi(0);\n        _jacobian(1,ind) = zi(1);\n        _jacobian(2,ind) = zi(2);\n        _jacobian(3,ind) = 0.0f;\n        _jacobian(4,ind) = 0.0f;\n        _jacobian(5,ind) = 0.0f;\n        break;\n    case REVOLUTE:\n        //For revolute joint everything is harder :\n        //        | z * d | <--- calculated vector z * vector d\n        // Cind = |       |\n        //        |   z   | <--- calculated vector z\n        _jacobian(0,ind) = d_rev(0);\n        _jacobian(1,ind) = d_rev(1);\n        _jacobian(2,ind) = d_rev(2);\n        _jacobian(3,ind) = zi(0);\n        _jacobian(4,ind) = zi(1);\n        _jacobian(5,ind) = zi(2);\n        break;\n    default:\n        break;\n    }\n}\n", "meta": {"hexsha": "567bcf5369e98855a0278f0a3c933f662efcb30d", "size": 4277, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Eigen_test/Eigen_test/Solvers/Jacobian.cpp", "max_stars_repo_name": "emiliev/RoboticArm", "max_stars_repo_head_hexsha": "69d0a73166c819d93cef28b7a6b6cc267345dd68", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Eigen_test/Eigen_test/Solvers/Jacobian.cpp", "max_issues_repo_name": "emiliev/RoboticArm", "max_issues_repo_head_hexsha": "69d0a73166c819d93cef28b7a6b6cc267345dd68", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Eigen_test/Eigen_test/Solvers/Jacobian.cpp", "max_forks_repo_name": "emiliev/RoboticArm", "max_forks_repo_head_hexsha": "69d0a73166c819d93cef28b7a6b6cc267345dd68", "max_forks_repo_licenses": ["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.9090909091, "max_line_length": 173, "alphanum_fraction": 0.5838204349, "num_tokens": 1256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286833, "lm_q2_score": 0.6442250996557036, "lm_q1q2_score": 0.47489579078147887}}
{"text": "#include <gauxc/xc_integrator/xc_host_util.hpp>\n\n#include \"host_weights.hpp\"\n#include \"host_collocation.hpp\"\n#include \"host_zmat.hpp\"\n#include \"integrator_common.hpp\"\n#include \"blas.hpp\"\n#include \"util.hpp\"\n\n#include <Eigen/Core>\n\nnamespace GauXC  {\nnamespace integrator::host {\n\n\n\ntemplate <typename F, size_t n_deriv>\nvoid process_batches_host_replicated_p(\n  XCIntegratorState      integrator_state,\n  XCWeightAlg            weight_alg,\n  const functional_type& func,\n  const BasisSet<F>&     basis,\n  const Molecule   &     mol,\n  const MolMeta    &     meta,\n  XCHostData<F>    &     host_data,\n  std::vector< XCTask >& tasks,\n  const F*               P,\n  F*                     VXC,\n  F*                     exc,\n  F*                     n_el\n) {\n\n  const int32_t nbf = basis.nbf();\n\n  auto task_comparator = []( const XCTask& a, const XCTask& b ) {\n    return (a.points.size() * a.nbe) > (b.points.size() * b.nbe);\n  };\n  std::sort( tasks.begin(), tasks.end(), task_comparator );\n\n\n  if( not integrator_state.modified_weights_are_stored )\n    partition_weights_host( weight_alg, mol, meta, tasks );\n\n\n  std::fill( VXC, VXC + size_t(nbf)*nbf, F(0.) );\n  *exc = 0.;\n\n  size_t ntasks = tasks.size();\n  for( size_t iT = 0; iT < ntasks; ++iT ) {\n\n    auto& task = tasks[iT];\n\n    const int32_t  npts    = task.points.size();\n    const int32_t  nbe     = task.nbe;\n    const int32_t  nshells = task.shell_list.size();\n\n    const F* points      = task.points.data()->data();\n    const F* weights     = task.weights.data();\n    const int32_t* shell_list = task.shell_list.data();\n\n    F* basis_eval = host_data.basis_eval.data();\n    F* den_eval   = host_data.den_scr.data();\n    F* nbe_scr    = host_data.nbe_scr.data();\n    F* zmat       = host_data.zmat.data();\n\n    F* eps        = host_data.eps.data();\n    F* gamma      = host_data.gamma.data();\n    F* vrho       = host_data.vrho.data();\n    F* vgamma     = host_data.vgamma.data();\n\n    F* dbasis_x_eval = nullptr;\n    F* dbasis_y_eval = nullptr;\n    F* dbasis_z_eval = nullptr;\n    F* dden_x_eval = nullptr;\n    F* dden_y_eval = nullptr;\n    F* dden_z_eval = nullptr;\n\n    if( n_deriv > 0 ) {\n      dbasis_x_eval = basis_eval    + npts * nbe;\n      dbasis_y_eval = dbasis_x_eval + npts * nbe;\n      dbasis_z_eval = dbasis_y_eval + npts * nbe;\n      dden_x_eval   = den_eval    + npts;\n      dden_y_eval   = dden_x_eval + npts;\n      dden_z_eval   = dden_y_eval + npts;\n    }\n\n\n    // Get the submatrix map for batch\n    auto submat_map = gen_compressed_submat_map( basis, task.shell_list );\n\n\n    // Evaluate Collocation Matrix \n    if( n_deriv == 1 )\n      eval_collocation_deriv1( npts, nshells, nbe, points, basis, shell_list, \n                               basis_eval, dbasis_x_eval, dbasis_y_eval, \n                               dbasis_z_eval );\n    else\n      eval_collocation( npts, nshells, nbe, points, basis, shell_list, basis_eval );\n\n\n    // Extrat Submatrix\n    const F* den_ptr_use = P;\n    if( nbe != nbf ) {\n      detail::submat_set( nbf, nbf, nbe, nbe, P, nbf, nbe_scr, nbe, submat_map );\n      den_ptr_use = nbe_scr;\n    } \n\n    // Z = P * BF\n    GauXC::blas::gemm( 'N', 'N', nbe, npts, nbe, 1., den_ptr_use, nbe,\n                       basis_eval, nbe, 0., zmat, nbe );\n    \n\n    // Evaluate the density \n    for( int32_t i = 0; i < npts; ++i ) {\n\n      const size_t ioff = size_t(i) * nbe;\n      const F*     zmat_i = zmat + ioff;\n\n      den_eval[i] = \n        2. * GauXC::blas::dot( nbe, basis_eval + ioff, 1, zmat_i, 1 );\n\n      if( n_deriv > 0 ) {\n        const F dx = \n          4. * GauXC::blas::dot( nbe, dbasis_x_eval + ioff, 1, zmat_i, 1 );\n        const F dy = \n          4. * GauXC::blas::dot( nbe, dbasis_y_eval + ioff, 1, zmat_i, 1 );\n        const F dz = \n          4. * GauXC::blas::dot( nbe, dbasis_z_eval + ioff, 1, zmat_i, 1 );\n\n        dden_x_eval[i] = dx;\n        dden_y_eval[i] = dy;\n        dden_z_eval[i] = dz;\n\n        gamma[i] = dx*dx + dy*dy + dz*dz;\n      }\n\n    }\n\n\n    // Evaluate XC functional\n    if( func.is_gga() )\n      func.eval_exc_vxc( npts, den_eval, gamma, eps, vrho, vgamma );\n    else\n      func.eval_exc_vxc( npts, den_eval, eps, vrho );\n\n\n    // Factor weights into XC results\n    for( int32_t i = 0; i < npts; ++i ) {\n      eps[i]  *= weights[i];\n      vrho[i] *= weights[i];\n    }\n\n    if( func.is_gga() )\n      for( int32_t i = 0; i < npts; ++i ) vgamma[i] *= weights[i];\n    \n\n\n    // Scalar integrations\n    if( n_el )\n      for( int32_t i = 0; i < npts; ++i ) *n_el += weights[i] * den_eval[i];\n\n    for( int32_t i = 0; i < npts; ++i ) *exc += eps[i] * den_eval[i];\n    \n\n    // Assemble Z\n    if( func.is_gga() )\n      zmat_gga_host( npts, nbe, vrho, vgamma, basis_eval, dbasis_x_eval,\n                     dbasis_y_eval, dbasis_z_eval, dden_x_eval, dden_y_eval,\n                     dden_z_eval, zmat ); \n    else\n      zmat_lda_host( npts, nbe, vrho, basis_eval, zmat ); \n\n\n\n    // Update VXC XXX: Only LT\n    GauXC::blas::syr2k( 'L', 'N', nbe, npts, F(1.), basis_eval,\n                        nbe, zmat, nbe, F(0.), nbe_scr, nbe );\n\n\n    detail::inc_by_submat( nbf, nbf, nbe, nbe, VXC, nbf, nbe_scr, nbe,\n                           submat_map );\n  }\n\n  // Symmetrize VXC\n  for( int32_t j = 0;   j < nbf; ++j )\n  for( int32_t i = j+1; i < nbf; ++i )\n    VXC[ j + i*nbf ] = VXC[ i + j*nbf ];\n\n}\n\n\n#define HOST_IMPL( F, ND ) \\\ntemplate \\\nvoid process_batches_host_replicated_p<F, ND>(\\\n  XCIntegratorState      integrator_state, \\\n  XCWeightAlg            weight_alg,\\\n  const functional_type& func,\\\n  const BasisSet<F>&     basis,\\\n  const Molecule   &     mol,\\\n  const MolMeta    &     meta,\\\n  XCHostData<F>    &     host_data,\\\n  std::vector< XCTask >& local_work,\\\n  const F*               P,\\\n  F*                     VXC,\\\n  F*                     exc,\\\n  F*                     n_el\\\n) \n\nHOST_IMPL( double, 0 );\nHOST_IMPL( double, 1 );\n\n}\n}\n", "meta": {"hexsha": "99ab69011b362034e42b33f1d9d6da08049ec623", "size": 5881, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/integrator/host/xc_host_util.cxx", "max_stars_repo_name": "ValeevGroup/GauXC", "max_stars_repo_head_hexsha": "cbc377c191e1159540d8ed923338cb849ae090ee", "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": "src/integrator/host/xc_host_util.cxx", "max_issues_repo_name": "ValeevGroup/GauXC", "max_issues_repo_head_hexsha": "cbc377c191e1159540d8ed923338cb849ae090ee", "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": "src/integrator/host/xc_host_util.cxx", "max_forks_repo_name": "ValeevGroup/GauXC", "max_forks_repo_head_hexsha": "cbc377c191e1159540d8ed923338cb849ae090ee", "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.4813084112, "max_line_length": 84, "alphanum_fraction": 0.560108825, "num_tokens": 1872, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907933, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.47487223484486496}}
{"text": "#include <Eigen/Dense>\n#include <vtkDelaunay3D.h>\n#include <vtkDataSetSurfaceFilter.h>\n#include <vtkPolyDataReader.h>\n#include <vtkPolyDataWriter.h>\n#include <vtkPolyData.h>\n#include <vtkPointData.h>\n#include <vtkCellArray.h>\n#include <vtkDoubleArray.h>\n#include <vtkIdFilter.h>\n#include <vtkSmartPointer.h>\n\ntypedef Eigen::Vector3d Vector3d;\ntypedef Eigen::VectorXd VectorXd;\ntypedef Eigen::Matrix3d Matrix3d;\ntypedef Eigen::Matrix3Xd Matrix3Xd;\ntypedef Eigen::Map<Matrix3Xd> Map3Xd;\n\nint main(){\n    clock_t t1;\n    t1 = clock();\n    for(auto i=0; i < 10000; ++i){\n        vtkNew<vtkPolyDataReader> reader;\n        reader->SetFileName(\"T7.vtk\");\n        reader->Update();\n        auto poly = reader->GetOutput();\n        auto N = poly->GetNumberOfPoints();\n        auto pts = (double*) poly->GetPoints()->GetData()->GetVoidPointer(0);\n        Map3Xd points(pts,3,N);\n\n        // Project points to unit sphere\n        points.colwise().normalize();\n\n        // Create a 3D tessellation\n        auto idf = vtkSmartPointer<vtkIdFilter>::New();\n        idf->PointIdsOn();\n        idf->SetIdsArrayName(\"OrigIds\");\n        idf->SetInputData(poly);\n        auto d3d = vtkSmartPointer<vtkDelaunay3D>::New();\n        d3d->SetInputConnection(idf->GetOutputPort());\n        auto dssf = vtkSmartPointer<vtkDataSetSurfaceFilter>::New();\n        dssf->SetInputConnection(d3d->GetOutputPort());\n        dssf->Update();\n        auto final = dssf->GetOutput();\n        auto interim = final->GetPolys();\n        interim->InitTraversal();\n        auto origIds = vtkIdTypeArray::SafeDownCast(\n                                final->GetPointData()->GetArray(\"OrigIds\"));\n        auto pointIds = vtkSmartPointer<vtkIdList>::New();\n        auto finalCells = vtkSmartPointer<vtkCellArray>::New();\n        while(interim->GetNextCell(pointIds)){\n            int numIds = pointIds->GetNumberOfIds();\n            finalCells->InsertNextCell(numIds);\n            for(auto j=0; j < numIds; j++ ){\n                int id = (int)origIds->GetTuple1( pointIds->GetId(j) );\n                finalCells->InsertCellPoint(id);\n            }\n        }\n        poly->SetPolys(finalCells);\n        auto writer = vtkSmartPointer<vtkPolyDataWriter>::New();\n        writer->SetFileName(\"Mesh.vtk\");\n        writer->SetInputData(poly);\n        writer->Write();\n\n    }\n\n    float diff((float)clock() - (float)t1);\n    std::cout << \"Time elapsed : \" << diff / CLOCKS_PER_SEC\n              << \" seconds\" << std::endl;\n    return 0;\n}\n", "meta": {"hexsha": "0ec79a302ebec3ae138715ff09bbfdd3375e4f0a", "size": 2485, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "CPP/vtk3d.cxx", "max_stars_repo_name": "amit112amit/learning-cgal", "max_stars_repo_head_hexsha": "a00b2a559cc9bd38fd041873353423f13406cb01", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-06-01T06:55:57.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-18T15:54:13.000Z", "max_issues_repo_path": "CPP/vtk3d.cxx", "max_issues_repo_name": "amit112amit/learning-cgal", "max_issues_repo_head_hexsha": "a00b2a559cc9bd38fd041873353423f13406cb01", "max_issues_repo_licenses": ["MIT"], "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/vtk3d.cxx", "max_forks_repo_name": "amit112amit/learning-cgal", "max_forks_repo_head_hexsha": "a00b2a559cc9bd38fd041873353423f13406cb01", "max_forks_repo_licenses": ["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.5138888889, "max_line_length": 77, "alphanum_fraction": 0.6173038229, "num_tokens": 635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.47487222540950674}}
{"text": "#include \"Product.h\"\n#include \"Config.h\"\n#include \"State.h\"\n#include <boost/lexical_cast.hpp>\n#include <ctpp2/CDT.hpp>\n#include <macgyver/TimeParser.h>\n#include <macgyver/Exception.h>\n#include <spine/HTTP.h>\n\nnamespace\n{\n// ----------------------------------------------------------------------\n/*!\n * \\brief Distance between two points along earth surface\n *\n * \\param theLon1 Longitude of point 1\n * \\param theLat1 Latitude of point 1\n * \\param theLon2 Longitude of point 2\n * \\param theLat2 Latitude of point 2\n * \\return The distance in kilometers\n *\n *  Haversine Formula (from R.W. Sinnott, \"Virtues of the Haversine\",\n *  Sky and Telescope, vol. 68, no. 2, 1984, p. 159)\n *  will give mathematically and computationally exact results. The\n *  intermediate result c is the great circle distance in radians. The\n *  great circle distance d will be in the same units as R.\n *\n *  When the two points are antipodal (on opposite sides of the Earth),\n *  the Haversine Formula is ill-conditioned, but the error, perhaps\n *  as large as 2 km (1 mi), is in the context of a distance near\n *  20,000 km (12,000 mi). Further, there is a possibility that roundoff\n *  errors might cause the value of sqrt(a) to exceed 1.0, which would\n *  cause the inverse sine to crash without the bulletproofing provided by\n *  the min() function.\n *\n * The code was taken from NFmiLocation::Distance\n */\n// ----------------------------------------------------------------------\n\ndouble torad(double theValue)\n{\n  return theValue * 3.14159265358979323846 / 180.0;\n}\ndouble geodistance(double theLon1, double theLat1, double theLon2, double theLat2)\n{\n  double lo1 = torad(theLon1);\n  double la1 = torad(theLat1);\n\n  double lo2 = torad(theLon2);\n  double la2 = torad(theLat2);\n\n  double dlon = lo2 - lo1;\n  double dlat = la2 - la1;\n  double sindlat = sin(dlat / 2);\n  double sindlon = sin(dlon / 2);\n\n  double a = sindlat * sindlat + cos(la1) * cos(la2) * sindlon * sindlon;\n  double help1 = sqrt(a);\n  double c = 2. * asin(std::min(1., help1));\n\n  return 6371.220 * c;\n}\n}  // namespace\n\nnamespace SmartMet\n{\nnamespace Plugin\n{\nnamespace CrossSection\n{\n// ----------------------------------------------------------------------\n/*!\n * \\brief Initialize the product from JSON\n */\n// ----------------------------------------------------------------------\n\nvoid Product::init(const Json::Value& theJson, const Config& theConfig)\n{\n  try\n  {\n    if (!theJson.isObject())\n      throw Fmi::Exception(BCP, \"Product JSON is not a JSON object (name-value pairs)\");\n\n    // Iterate through all the members\n\n    const auto members = theJson.getMemberNames();\n    for (const auto& name : members)\n    {\n      const Json::Value& json = theJson[name];\n\n      if (name == \"layers\")\n        layers.init(json, theConfig);\n      else\n        throw Fmi::Exception(BCP,\n                                         \"Product does not have a setting named '\" + name + \"'\");\n    }\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Generate the product into the template hash tables\n *\n */\n// ----------------------------------------------------------------------\n\nvoid Product::generate(CTPP::CDT& theGlobals,\n                       State& theState,\n                       const SmartMet::Spine::TimeSeriesGenerator::LocalTimeList& theTimes)\n{\n  try\n  {\n    // Initialize the structure\n\n    theGlobals[\"layers\"] = CTPP::CDT(CTPP::CDT::HASH_VAL);\n\n    // Process all times\n\n    for (const auto& time : theTimes)\n    {\n      theState.time(time);\n      layers.generate(theGlobals, theState);\n    }\n\n    // Generate bounding box\n\n    const auto& env = theState.envelope();\n    if (env.IsInit() != 0)\n    {\n      theGlobals[\"bbox\"] = CTPP::CDT(CTPP::CDT::HASH_VAL);\n      theGlobals[\"bbox\"][\"xmin\"] = env.MinX;\n      theGlobals[\"bbox\"][\"xmax\"] = env.MaxX;\n      theGlobals[\"bbox\"][\"ymin\"] = env.MinY;\n      theGlobals[\"bbox\"][\"ymax\"] = env.MaxY;\n    }\n\n    // Distance between the two points\n\n    theGlobals[\"distance\"] = geodistance(theState.query().longitude1,\n                                         theState.query().latitude1,\n                                         theState.query().longitude2,\n                                         theState.query().latitude2);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n}  // namespace CrossSection\n}  // namespace Plugin\n}  // namespace SmartMet\n", "meta": {"hexsha": "2b698c4fce2f5498a4634877a4693effc754f796", "size": 4512, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cross_section/Product.cpp", "max_stars_repo_name": "fmidev/smartmet-plugin-cross_section", "max_stars_repo_head_hexsha": "c421523a7f1ba7887d44dc8a229fbf22b4393faa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cross_section/Product.cpp", "max_issues_repo_name": "fmidev/smartmet-plugin-cross_section", "max_issues_repo_head_hexsha": "c421523a7f1ba7887d44dc8a229fbf22b4393faa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cross_section/Product.cpp", "max_forks_repo_name": "fmidev/smartmet-plugin-cross_section", "max_forks_repo_head_hexsha": "c421523a7f1ba7887d44dc8a229fbf22b4393faa", "max_forks_repo_licenses": ["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.7388535032, "max_line_length": 97, "alphanum_fraction": 0.5709219858, "num_tokens": 1121, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297967961706, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.47486424164626473}}
{"text": "\n#include <fstream>\n#include <iostream>\n#include <string>\n#include <stdlib.h>\n#include <vector> \n//#include <random>\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\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//Intermediate Variables\nint blocksize;\nint hsegsize;\ndouble *partialsums;\ndouble *sum_op;\t\t\ndouble *yint_e;\ndouble *yint_m;\ndouble **y_e;\ndouble **y_m;\n\n\nstruct timespec t0;\n\nclock_t total_begin = clock();\nMatrixXdr pheno;\nMatrixXdr mask;\nMatrixXdr covariate;  \nMatrixXdr Q;\nMatrixXdr v1; //W^ty\nMatrixXdr v2;            //QW^ty\nMatrixXdr v3;    //WQW^ty\nMatrixXdr new_pheno;\n\n\n\ngenotype g;\ngenotype g1;\ngenotype g2;\nMatrixXdr geno_matrix; //(p,n)\ngenotype* Geno;\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)\nMatrixXdr sum2;\nMatrixXdr sum;  \n////////\n//related to phenotype\t\ndouble y_sum; \ndouble y_mean;\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;\nbool use_cov=false; \n\n\n//// jackknife index wich are computed based on annotation file\nMatrixXdr dic_index;\nMatrixXdr jack_bin_size;\nvector<int> len;\nvector<int> Annot;\nint Njack=100;\nint Nbin=8;\nint Nz=10;\n///////\n\n//define random vector z's\nMatrixXdr  all_zb;\nMatrixXdr res;\nMatrixXdr XXz;\nMatrixXdr Xy;\nMatrixXdr yXXy;\n\n\n\n\n\n\nstd::istream& newline(std::istream& in)\n{\n    if ((in >> std::ws).peek() != std::char_traits<char>::to_int_type('\\n')) {\n        in.setstate(std::ios_base::failbit);\n    }\n    return in.ignore();\n}\n\n\nint read_cov(bool std,int Nind, std::string filename, std::string covname){\n\tifstream ifs(filename.c_str(), ios::in); \n\tstd::string line; \n\tstd::istringstream in; \n\tint covIndex = 0; \n\tstd::getline(ifs,line); \n\tin.str(line); \n\tstring b;\n\tvector<vector<int> > missing; \n\tint covNum=0;  \n\twhile(in>>b)\n\t{\n\t\tif(b!=\"FID\" && b !=\"IID\"){\n\t\tmissing.push_back(vector<int>()); //push an empty row  \n\t\tif(b==covname && covname!=\"\")\n\t\t\tcovIndex=covNum; \n\t\tcovNum++; \n\t\t}\n\t}\n\tvector<double> cov_sum(covNum, 0); \n\tif(covname==\"\")\n\t{\n\t\tcovariate.resize(Nind, covNum); \n\t\tcout<< \"Read in \"<<covNum << \" Covariates.. \"<<endl;\n\t}\n\telse \n\t{\n\t\tcovariate.resize(Nind, 1); \n\t\tcout<< \"Read in covariate \"<<covname<<endl;  \n\t}\n\n\t\n\tint j=0; \n\twhile(std::getline(ifs, line)){\n\t\tin.clear(); \n\t\tin.str(line);\n\t\tstring temp;\n\t\tin>>temp; in>>temp; //FID IID \n\t\tfor(int k=0; k<covNum; k++){\n\t\t\t\n\t\t\tin>>temp;\n\t\t\tif(temp==\"NA\")\n\t\t\t{\n\t\t\t\tmissing[k].push_back(j);\n\t\t\t\tcontinue; \n\t\t\t} \n\t\t\tdouble cur = atof(temp.c_str()); \n\t\t\tif(cur==-9)\n\t\t\t{\n\t\t\t\tmissing[k].push_back(j); \n\t\t\t\tcontinue; \n\t\t\t}\n\t\t\tif(covname==\"\")\n\t\t\t{\n\t\t\t\tcov_sum[k]= cov_sum[k]+ cur; \n\t\t\t\tcovariate(j,k) = cur; \n\t\t\t}\n\t\t\telse\n\t\t\t\tif(k==covIndex)\n\t\t\t\t{\n\t\t\t\t\tcovariate(j, 0) = cur;\n\t\t\t\t\tcov_sum[k] = cov_sum[k]+cur; \n\t\t\t\t}\n\t\t}\n\t\t//if(j<10) \n\t\t//\tcout<<covariate.block(j,0,1, covNum)<<endl; \n\t\tj++;\n\t}\n\t//compute cov mean and impute \n\tfor (int a=0; a<covNum ; a++)\n\t{\n\t\tint missing_num = missing[a].size(); \n\t\tcov_sum[a] = cov_sum[a] / (Nind - missing_num);\n\n\t\tfor(int b=0; b<missing_num; b++)\n\t\t{\n                        int index = missing[a][b];\n                        if(covname==\"\")\n                                covariate(index, a) = cov_sum[a];\n                        else if (a==covIndex)\n                                covariate(index, 0) = cov_sum[a];\n                } \n\t}\n\tif(std)\n\t{\n\t\tMatrixXdr cov_std;\n\t\tcov_std.resize(1,covNum);  \n\t\tMatrixXdr sum = covariate.colwise().sum();\n\t\tMatrixXdr sum2 = (covariate.cwiseProduct(covariate)).colwise().sum();\n\t\tMatrixXdr temp;\n//\t\ttemp.resize(Nind, 1); \n//\t\tfor(int i=0; i<Nind; i++)\n//\t\t\ttemp(i,0)=1;  \n\t\tfor(int b=0; b<covNum; b++)\n\t\t{\n\t\t\tcov_std(0,b) = sum2(0,b) + Nind*cov_sum[b]*cov_sum[b]- 2*cov_sum[b]*sum(0,b);\n\t\t\tcov_std(0,b) =sqrt((Nind- 1)/cov_std(0,b)) ;\n\t\t\tdouble scalar=cov_std(0,b); \n\t\t\tfor(int j=0; j<Nind; j++)\n\t\t\t{\n\t\t\t\tcovariate(j,b) = covariate(j,b)-cov_sum[b];  \n\t\t\t\tcovariate(j,b) =covariate(j,b)*scalar;\n\t\t\t} \n\t\t\t//covariate.col(b) = covariate.col(b) -temp*cov_sum[b];\n\t\t\t\n\t\t}\n\t}\t\n\treturn covNum; \n}\n\n/*void read_cov(int Nind, std::string filename, std::string covname){\n\tifstream ifs(filename.c_str(), ios::in); \n\tstd::string line; \n\tstd::istringstream in; \n\tint covIndex = 0; \n\tstd::getline(ifs,line); \n\tin.str(line); \n\tstring b;\n\tvector<vector<int> > missing; \n\tint covNum=0;  \n\twhile(in>>b)\n\t{\n\t\tmissing.push_back(vector<int>()); //push an empty row  \n\t\tif(b==covname && covname!=\"\")\n\t\t\tcovIndex=covNum; \n\t\tcovNum++; \n\t}\n\tvector<double> cov_sum(covNum, 0); \n\tif(covname==\"\")\n\t{\n\t\tcovariate.resize(Nind, covNum); \n\t\tcout<< \"Read in \"<<covNum << \" Covariates.. \"<<endl;\n\t}\n\telse \n\t{\n\t\tcovariate.resize(Nind, 1); \n\t\tcout<< \"Read in covariate \"<<covname<<endl;  \n\t}\n\n\t\n\tint j=0; \n\twhile(std::getline(ifs, line)){\n\t\tin.clear(); \n\t\tin.str(line);\n\t\tstring temp; \n\t\tfor(int k=0; k<covNum; k++){\n\t\t\tin>>temp;\n\t\t\tif(temp==\"NA\")\n\t\t\t{\n\t\t\t\tmissing[k].push_back(j);\n\t\t\t\tcontinue;  \n\t\t\t} \n\t\t\tint cur = atof(temp.c_str()); \n\t\t\tif(cur==-9)\n\t\t\t{\n\t\t\t\tmissing[k].push_back(j); \n\t\t\t\tcontinue; \n\t\t\t}\n\t\t\tif(covname==\"\")\n\t\t\t{\n\t\t\t\tcov_sum[k]= cov_sum[k]+ cur; \n\t\t\t\tcovariate(j,k) = cur; \n\t\t\t}\n\t\t\telse\n\t\t\t\tif(k==covIndex)\n\t\t\t\t{\n\t\t\t\t\tcovariate(j, 0) = cur;\n\t\t\t\t\tcov_sum[k] = cov_sum[k]+cur; \n\t\t\t\t}\n\t\t} \n\t\tj++;\n\t}\n\t//compute cov mean and impute \n\tfor (int a=0; a<covNum ; a++)\n\t{\n\t\tint missing_num = missing[a].size(); \n\t\tcov_sum[a] = cov_sum[a] / (covNum - missing_num);\n\n\t\tfor(int b=0; b<missing_num; b++)\n\t\t{\n                        int index = missing[a][b];\n                        if(covname==\"\")\n                                covariate(index, a) = cov_sum[a];\n                        else if (a==covIndex)\n                                covariate(index, 0) = cov_sum[a];\n                } \n\t}\n}*/\nvoid read_pheno2(int Nind, std::string filename){\n//\tpheno.resize(Nind,1); \n\tifstream ifs(filename.c_str(), ios::in); \n\t\n\tstd::string line;\n\tstd::istringstream in;  \n\tint phenocount=0; \n//read header\n\tstd::getline(ifs,line); \n\tin.str(line); \n\tstring b; \n\twhile(in>>b)\n\t{\n\t\tif(b!=\"FID\" && b !=\"IID\")\n\t\t\tphenocount++; \n\t}\n\tpheno.resize(Nind, phenocount);\n\tmask.resize(Nind, phenocount);\n\tint i=0;  \n\twhile(std::getline(ifs, line)){\n\t\tin.clear(); \n\t\tin.str(line); \n\t\tstring temp;\n\t\t//fid,iid\n\t\t//todo: fid iid mapping; \n\t\t//todo: handle missing phenotype\n\t\tin>>temp; in>>temp; \n\t\tfor(int j=0; j<phenocount;j++) {\n\t\t\tin>>temp;\n\t\t\tdouble cur = atof(temp.c_str());\n\t\t\tif(temp==\"NA\" || cur==-9){\n\t\t\tpheno(i,j)=0;\n\t\t\tmask(i,j)=0;\n\t\t\t}\n\t\t\telse{\n\t\t\tpheno(i,j)=atof(temp.c_str());\n\t\t\tmask(i,j)=1;\n\n\t\t\t}\n\n    \n\t\t}\n\t\ti++;\n\t}\n\t//cout<<pheno; \n}\nvoid read_pheno(int Nind, std::string filename){\n\tpheno.resize(Nind, 1); \n\tifstream ifs(filename.c_str(), ios::in); \n\t\n\tstd::string line;\n\tint i=0;  \n\twhile(std::getline(ifs, line)){\n\t\tpheno(i,0) = atof(line.c_str());\n\t\tif(pheno(i,0)==-1)\n\t\t\tcout<<\"WARNING: missing phenotype\"<<endl; \n\t\ti++;  \n\t}\n\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\t\t//cout << \"Nops = \" << Ncol_op << \"\\t\" <<g.Nsegments_hori << endl;\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\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\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,partialsums,y_m);\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[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\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\t//cout << \"ncol_op = \" << Ncol_op << endl;\n\n\tint seg_iter;\n\tfor(seg_iter=0;seg_iter<g.Nsegments_hori-1;seg_iter++){\nmailman::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\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, seg_iter * g.segment_size_hori, g.p[seg_iter],op,yint_e,partialsums,y_e);\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[n_iter][k_iter];\n\t\t\ty_e[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}\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\nvoid initial_var(int key)\n{\n    /*if(key==1)\n        g=g1;\n    if(key==2)\n    \tg=g2;*/\n   // g=Geno[key];\n    p = g.Nsnp;\n\tn = g.Nindv;\n\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\tsum2.resize(p,1); \n\tsum.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\n\t//TODO: Initialization of c with gaussian distribution\n\tc = MatrixXdr::Random(p,k);\n\n\n\t// Initial intermediate data structures\n\tblocksize = k;\n\t 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\tpartialsums = new double [blocksize];\n\tsum_op = new double[blocksize];\n\tyint_e = new double [hsize*blocksize];\n\tyint_m = new double [hsize*blocksize];\n\tmemset (yint_m, 0, hsize*blocksize * sizeof(double));\n\tmemset (yint_e, 0, hsize*blocksize * sizeof(double));\n\n\ty_e  = new double*[g.Nindv];\n\tfor (int i = 0 ; i < g.Nindv ; i++) {\n\t\ty_e[i] = new double[blocksize];\n\t\tmemset (y_e[i], 0, blocksize * sizeof(double));\n\t}\n\n\ty_m = new double*[hsegsize];\n\tfor (int i = 0 ; i < hsegsize ; i++)\n\t\ty_m[i] = new double[blocksize];\n\tfor(int i=0;i<p;i++){\n\t\tmeans(i,0) = g.get_col_mean(i);\n\t\tstds(i,0) =1/g.get_col_std(i);\n\t\t//sum2(i,0) =g.get_col_sum2(i); \n\t\tsum(i,0)= g.get_col_sum(i); \n\t}\n\n\n\n\n}\n\nMatrixXdr multi_Xz (MatrixXdr zb){\n\n              for(int j=0; j<g.Nsnp;j++)\n                zb(j,0) =zb(j,0) *stds(j,0);\n                                              \n\t\tMatrixXdr new_zb = zb.transpose(); \n\t        MatrixXdr new_res(1, g.Nindv);\n\t\tmultiply_y_post_fast(new_zb, 1, new_res, false); \n\t\tMatrixXdr new_resid(1, g.Nsnp); \n\t\tMatrixXdr zb_scale_sum = new_zb * means;\n\t\tnew_resid = zb_scale_sum * MatrixXdr::Constant(1,g.Nindv, 1);\n\t\tnew_res=new_res - new_resid;\n       return new_res;\n\n}\t\n\ndouble compute_yVKVy(int s){\n\tMatrixXdr new_pheno_sum = new_pheno.colwise().sum();\n\tMatrixXdr res(g.Nsnp, 1); \n\tmultiply_y_pre_fast(new_pheno,1,res,false); \n\tres = res.cwiseProduct(stds); \n\tMatrixXdr resid(g.Nsnp, 1); \n\tresid = means.cwiseProduct(stds); \n\tresid = resid *new_pheno_sum; \t\n\tMatrixXdr Xy(g.Nsnp,1); \n\tXy = res-resid; \n\tdouble ytVKVy = (Xy.array()* Xy.array()).sum(); \n\tytVKVy = ytVKVy/g.Nsnp; \n\treturn ytVKVy;\n\n}\n\ndouble compute_yXXy(){\n\n//for (int i=0;i<g.Nindv;i++)\n\t//pheno(i,0)=1;\n\n        MatrixXdr res(g.Nsnp, 1);\n        multiply_y_pre_fast(pheno,1,res,false);\n        res = res.cwiseProduct(stds);\n        MatrixXdr resid(g.Nsnp, 1);\n        resid = means.cwiseProduct(stds);\n        resid = resid *y_sum;\n        MatrixXdr Xy(g.Nsnp,1);\n        Xy = res-resid;\n    \n        double yXXy = (Xy.array()* Xy.array()).sum();\n        \n\n        return yXXy;\n\n}\n\n\n\n\n\n double compute_tr_k(int s){\n\t  \n\t   /* if (s==1)\n         initial_var(1);  \n        if(s==2) \n         initial_var(2); \n*/\n        initial_var(s);\n\t    double tr_k =0 ;\n \t\tMatrixXdr temp = sum2 + g.Nindv* means.cwiseProduct(means) - 2 * means.cwiseProduct(sum);\n\t\ttemp = temp.cwiseProduct(stds);\n\t\ttemp = temp.cwiseProduct(stds); \n\t\ttr_k = temp.sum() / g.Nsnp;\n\t   \n\t//    cout<<g.Nindv<<\"    \"<<g.Nsnp<<\" s:   \"<<temp.sum()<<\"\\n\"; \n\t//    cout<<tr_k<<\"\\n\";\n\t   return tr_k;\n\t}\n\t\nMatrixXdr  compute_XXz (){\n\n\t//mask\n\tfor (int i=0;i<Nz;i++)\n\t   for(int j=0;j<g.Nindv;j++)\n\t\t all_zb(j,i)=all_zb(j,i)*mask(j,0);\n\n         res.resize(g.Nsnp, Nz);\n         multiply_y_pre_fast(all_zb,Nz,res, false);\n\n//         cout<<res<<endl;\n\n        MatrixXdr zb_sum = all_zb.colwise().sum();\n        \n\n\tfor(int j=0; j<g.Nsnp; j++)\n            for(int k=0; k<Nz;k++)\n                 res(j,k) = res(j,k)*stds(j,0);\n\n        MatrixXdr resid(g.Nsnp, Nz);\n        MatrixXdr inter = means.cwiseProduct(stds);\n        resid = inter * zb_sum;\n        MatrixXdr inter_zb = res - resid;\n       \n\n\tfor(int k=0; k<Nz; k++)\n            for(int j=0; j<g.Nsnp;j++)\n                inter_zb(j,k) =inter_zb(j,k) *stds(j,0);\n\n       MatrixXdr new_zb = inter_zb.transpose();\n       MatrixXdr new_res(Nz, g.Nindv);\n       \n       multiply_y_post_fast(new_zb, Nz, new_res, false);\n       \n       MatrixXdr new_resid(Nz, g.Nsnp);\n       MatrixXdr zb_scale_sum = new_zb * means;\n       new_resid = zb_scale_sum * MatrixXdr::Constant(1,g.Nindv, 1);\n\n\t//return new_res;\n\n                      /// new zb \n       MatrixXdr temp=new_res - new_resid;\n\n\tfor (int i=0;i<Nz;i++)\n           for(int j=0;j<g.Nindv;j++)\n                 temp(i,j)=temp(i,j)*mask(j,0);\n\n\n\treturn temp.transpose();\n       \n\n}\n\n\nvoid read_annot (string filename){\n        ifstream inp(filename.c_str());\n        if (!inp.is_open()){\n                cerr << \"Error reading file \"<< filename <<endl;\n                exit(1);\n        }\n        string line;\n        int j = 0 ;\n        int linenum = 0 ;\n        int num_parti;\n        stringstream check1(line);\n        string intermediate;\n        vector <string> tokens;\n        while(std::getline (inp, line)){\n                linenum ++;\n                char c = line[0];\n                if (c=='#')\n                        continue;\n                istringstream ss (line);\n                if (line.empty())\n                        continue;\n                j++;\n                //cout<<line<<endl;\n\n                stringstream check1(line);\n                string intermediate;\n                vector <string> tokens;\n                // Tokenizing w.r.t. space ' ' \n                while(getline(check1, intermediate, ' '))\n                 {\n                      tokens.push_back(intermediate);\n                 }\n                 if(linenum==1){\n                 num_parti=tokens.size();\n                 if(num_parti!=Nbin)\n                        cout<<\"number of col of annot file does not match number of bins\"<<endl;\n                len.resize(num_parti,0);\n                }\n                int index_annot=0;\n                for(int i = 0; i < tokens.size(); i++){\n                        if (tokens[i]==\"1\")\n                            index_annot=i;\n                }\n                   Annot.push_back(index_annot);\n                   len[index_annot]++;\n       }\n\n\n\tdic_index=MatrixXdr::Zero(Njack,Nbin);\n  \tjack_bin_size=MatrixXdr::Zero(Njack,Nbin);      \n\n\n\tint num_snps=0;\n        for (int i=0;i<num_parti;i++){\n                //cout<<len[i]<<endl;\n                num_snps+=len[i];\n        }\n  //      cout<<\"step size: \"<<endl;\n        int step_size=num_snps/Njack;\n         int step_size_rem=num_snps%Njack;\n    //    cout<<step_size<<endl;\n      //  cout<<\"reminder: \"<<step_size_rem<<endl;\n         int temp=step_size;\n\n         //for (int i=0;i<Njack;i++)\n           //      for (int j=0;j<num_parti;j++)\n             //           dic_index(i,j)=0;\n\n        j=1;\n\n        for (int i=0;i<Annot.size();i++){\n                if(i==(step_size*j) && j<Njack ){\n                     j++;\n                     for (int k=0; k<num_parti;k++)\n                        dic_index(j-1,k)=dic_index(j-2,k);\n                }\n                dic_index(j-1,Annot[i])=dic_index(j-1,Annot[i])+1;\n        }\n\n        //handle not removing a bin in jackknife se\n        for(int i=0;i<Nbin;i++){\n\t   for(int j=0;j<Njack;j++){\n\t\tif(j==0 && dic_index(j,i)==len[i]){\n\t\t\tdic_index(j,i)=len[i]/2;\n\t\t\tdic_index(j+1,i)=len[i]-dic_index(j,i);\n\t\t}\n\t\telse if ( j!=0 && (dic_index(j,i)-dic_index(j-1,i))==len[i] ){\n\t\t\tdic_index(j-1,i)=len[i]/2;\n\t\t\tdic_index(j,i)=len[i]-dic_index(j-1,i);\n\t\t}\n\t   }\n       }\n//cout<<\"end reading annot\"<<endl;\n\n}\n\nvoid count_fam(std::string filename){\n        ifstream ifs(filename.c_str(), ios::in);\n\n        std::string line;\n        int i=0;\n        while(std::getline(ifs, line)){\n                i++;\n        }\n        g.Nindv=i-1;\n}\n\n\nint main(int argc, char const *argv[]){\n  \n\nparse_args(argc,argv);\n////////////////////////////////////////////\n///////////////////////////////////////////\n    \n    //MAX_ITER =  command_line_opts.max_iterations ; \n        int B = command_line_opts.batchNum;\n        k_orig = command_line_opts.num_of_evec ;\n        debug = command_line_opts.debugmode ;\n        check_accuracy = command_line_opts.getaccuracy;\n        var_normalize = false;\n        accelerated_em = command_line_opts.accelerated_em;\n        k = k_orig + command_line_opts.l;\n        k = (int)ceil(k/10.0)*10;\n        command_line_opts.l = k - k_orig;\n        //p = g.Nsnp;\n        //n = g.Nindv;\n        bool toStop=false;\n        toStop=true;\n        srand((unsigned int) time(0));\n        //Nz=10;\n\tNz=command_line_opts.num_of_evec;\n        k=Nz;\n         ///clock_t io_end = clock();\n\n\tNjack=command_line_opts.jack_number;\n\n////\nstring filename;\n//filename=\"/home/alipazoki/filter4_no_mhc/mafld/annot.txt\";\n//filename=\"/home/alipazoki/RHEmc_online/example/annot_filter4.txt\";\n//filename=command_line_opts.Annot_PATH;\n//read_annot(filename);\t\n//cout<<dic_index<<endl;\n//cout<<jack_bin_size<<endl;\n//////////////////////////// Read multi genotypes\nstring line;\nint cov_num;\nint num_files=0;\n//string name=\"/home/alipazoki/filter4_no_mhc/mafld/adr.txt\";\n//string name=\"/home/alipazoki/UKBB/maf_ld/sub_indv/adr.txt\";\nstring name=command_line_opts.GENOTYPE_FILE_PATH;\n//cout<<name<<endl;\nifstream f (name.c_str());\nwhile(getline(f,line))\n   num_files++;    \n   \nstring file_names[num_files];\n\nint i=0;\nifstream ff (name.c_str());\nwhile(getline(ff,line)) {\n    \n    file_names[i]=line;\n    cout<<file_names[i]<<\"\\n\";\n    i++;\n}\n\nNbin=num_files;\n    \n cout<<\"Number of the bins: \"<<Nbin<<endl;   \n\nfilename=command_line_opts.Annot_PATH;\nread_annot(filename);\n\n///reading phnotype and save the number of indvs\n//filename=\"/home/alipazoki/UKBB/kathy_pheno/height.pheno\";    \n//filename=\"/home/alipazoki/UKBB/maf_ld/sub_indv/10k.bmi.pheno\";\nfilename=command_line_opts.PHENOTYPE_FILE_PATH;\ncount_fam(filename);\nread_pheno2(g.Nindv,filename);\ncout<<\"Number of Indvs :\"<<g.Nindv<<endl;\ny_sum=pheno.sum();\n\n//read covariate\n//std::string covfile=\"/home/alipazoki/UKBB/kathy_pheno/height.covar\";\n//:qstd::string covfile=\"/home/alipazoki/UKBB/maf_ld/sub_indv/10k.bmi.covar\";\n//bool usee_cov=false;\n//if(usee_cov==true){\nstd::string covfile=command_line_opts.COVARIATE_FILE_PATH;\nstd::string covname=\"\";\nif(covfile!=\"\"){\n     use_cov=true;\n     cov_num=read_cov(false,g.Nindv, covfile, covname);\n\t//cout<<cov_num<<endl;\n}\nelse if(covfile==\"\")\n     cout<<\"No Covariate File Specified\"<<endl;\n\n/// regress out cov from phenotypes\n\nif(use_cov==true){\nMatrixXdr mat_mask=mask.replicate(1,cov_num);\ncovariate=covariate.cwiseProduct(mat_mask);\n\nMatrixXdr WtW= covariate.transpose()*covariate;\nQ=WtW.inverse(); // Q=(W^tW)^-1\n//cout<<\" Number of covariates\"<<cov_num<<endl;\n\nMatrixXdr v1=covariate.transpose()*pheno; //W^ty\nMatrixXdr v2=Q*v1;            //QW^ty\nMatrixXdr v3=covariate*v2;    //WQW^ty\npheno=pheno-v3;\npheno=pheno.cwiseProduct(mask);\n }                 \n////// normalize phenotype\n\n//bool pheno_norm=false;\ny_sum=pheno.sum();\ny_mean = y_sum/mask.sum();\n\n//if(pheno_norm==true){\nfor(int i=0; i<g.Nindv; i++){\n   if(pheno(i,0)!=0)\n      pheno(i,0) =pheno(i,0) - y_mean; //center phenotype\n}\ny_sum=pheno.sum();\n\n//}\n\n\n\n\n\n\n\n\n//define random vector z's\n//Nz=1;\n\nall_zb= MatrixXdr::Random(g.Nindv,Nz);\nall_zb = all_zb * sqrt(3);\nMatrixXdr output;\n//define \n\n//e\n//Njack=1;\n\nXXz=MatrixXdr::Zero(g.Nindv,Nbin*(Njack+1)*Nz);\nyXXy=MatrixXdr::Zero(Nbin,Njack+1);\n\nfor(int bin_index=0; bin_index<Nbin; bin_index++){\n\n    std::stringstream f3;\n    f3 << file_names[bin_index] << \".bed\";\n    string name=f3.str();\n    cout<<name<<endl;\n    ifstream ifs (name.c_str(), ios::in|ios::binary);\n\t\n    g.read_header=true;\n     //E\n     for (int jack_index=0;jack_index<Njack;jack_index++){\n\t\n\t//cout<<\"reading \"<<jack_index<<\"-th jckknf blck of \"<<bin_index<<\"-th bin\"<<endl;\n\t\n\tif (jack_index==0){\n\t\tg.Nsnp=dic_index(jack_index,bin_index);\n\t\tjack_bin_size(jack_index,bin_index)=g.Nsnp;\n\t}\n\telse{\n\t        g.Nsnp=dic_index(jack_index,bin_index)-dic_index(jack_index-1,bin_index);\n\t\tjack_bin_size(jack_index,bin_index)=g.Nsnp;\n        }\n       if(g.Nsnp!=0){\n\t  //cout<<\"Zero SNPSsss\"<<endl;\n       \n\t\n\t//g.Nsnp=len[bin_index];  \n  \t//cout<<\"#SNPs\"<<g.Nsnp<<endl; \n   \t\n\t  g.read_plink(ifs,file_names[bin_index],missing,fast_mode);\n    \t  initial_var(0);\n//////// do computation for i-th jack block of j-th bin \n\n\t/// compute XXz\n\toutput=compute_XXz();\n//\tcout<<output.col(0).sum()<<endl;\n\tfor (int z_index=0;z_index<Nz;z_index++){\n\t\t XXz.col((bin_index*(Njack+1)*Nz)+(jack_index*Nz)+z_index)=output.col(z_index);\n\t\t XXz.col((bin_index*(Njack+1)*Nz)+(Njack*Nz)+z_index)+=output.col(z_index);   /// save whole sample\n\t}\n\t///compute yXXy\n\tyXXy(bin_index,jack_index)= compute_yXXy();\n\tyXXy(bin_index,Njack)+= yXXy(bin_index,jack_index);\n\t//// contribtion of each jackknife SUBSAMPLE (not block)\n\t\n\t\n\n\n///////end computation\n/////////////////////////////////destruct class g\n\tdelete[] sum_op;\n        delete[] partialsums;\n        delete[] yint_e; \n        delete[] yint_m;\n        for (int i  = 0 ; i < hsegsize; i++)\n                delete[] y_m [i]; \n        delete[] y_m;\n\n        for (int i  = 0 ; i < g.Nindv; i++)\n                delete[] y_e[i]; \n        delete[] y_e;\n\t\n\tstd::vector< std::vector<int> >().swap(g.p);\n        std::vector< std::vector<int> >().swap(g.not_O_j);\n        std::vector< std::vector<int> >().swap(g.not_O_i);\n\t\n\t//g.p.clear();\n\t//g.not_O_j.clear();\n\t//g.not_O_i.clear();\n\tg.columnsum.clear();\n\tg.columnsum2.clear();\n\tg.columnmeans.clear();\n\tg.columnmeans2.clear();\n\t//std::vector< std::vector<int> >().swap(g.columnsum);\n\t//std::vector< std::vector<int> >().swap(g.columnsum2);\n\t//std::vector< std::vector<double> >().swap(g.columnmeans);\n\t//std::vector< std::vector<double> >().swap(g.columnmeans2);\n\tg.read_header=false;\n/////////////////////////////////////////////\n       } //end of else \n   }// end of loop over jack blocks\n          \n  if(bin_index==0){\n        //cout<<\"zzzzzzzzzzzz\"<<XXz.col((bin_index*Njack*Nz)+(Njack*Nz)).sum()<<endl;\n        //cout<<bin_index<<\" \"<<Njack<<\" \"<<0<<endl; \n\t//cout<<\"zzzzzzzzzzzz\"<<XXz.col((bin_index*Njack*Nz)+(Njack*Nz)).sum()<<endl;\n\t}\n   // contribtion of each jackknife SUBSAMPLE (not block)\n   \n   \n for(int jack_index=0;jack_index<Njack;jack_index++){\n\tfor (int z_index=0;z_index<Nz;z_index++){\n\t MatrixXdr v1=XXz.col((bin_index*(Njack+1)*Nz)+(Njack*Nz)+z_index);\n\t// cout<<bin_index<<\" \"<<Njack<<\" \"<<z_index<<endl;\n\n\t//cout<<\"v1: \"<<v1.sum()<<endl; \n\tMatrixXdr v2=XXz.col((bin_index*(Njack+1)*Nz)+(jack_index*Nz)+z_index); \n        // cout<<bin_index<<\" \"<<jack_index<<\" \"<<z_index<<endl;\n\t//cout<<\"v2: \"<<v2.sum()<<endl; \n\tXXz.col((bin_index*(Njack+1)*Nz)+(jack_index*Nz)+z_index)=v1-v2;                    \n        \n\t//cout<<\"real v1: \"<<XXz.col((bin_index*Njack*Nz)+(Njack*Nz)+z_index).sum()<<endl;\n\t//cout<<\"real v2: \"<<XXz.col((bin_index*Njack*Nz)+(jack_index*Nz)+z_index).sum()<<endl;\n\n       }\n\tyXXy(bin_index,jack_index)=yXXy(bin_index,Njack)-yXXy(bin_index,jack_index);\n}\n \n} //end of loop over bins\n\n\n/// normal equations LHS\nMatrixXdr  A_trs(Nbin,Nbin);\nMatrixXdr b_trk(Nbin,1);\nMatrixXdr c_yky(Nbin,1);\n\nMatrixXdr X_l(Nbin+1,Nbin+1);\nMatrixXdr Y_r(Nbin+1,1);\n//int bin_index=0;\nint jack_index=Njack; \nMatrixXdr B1;\nMatrixXdr B2;\nMatrixXdr C1;\nMatrixXdr C2;\ndouble trkij;\ndouble yy=(pheno.array() * pheno.array()).sum();\nint Nindv_mask=mask.sum();\nMatrixXdr jack;\nMatrixXdr point_est;\nMatrixXdr enrich_jack;\nMatrixXdr enrich_point_est;\n\njack.resize(Nbin+1,Njack);\npoint_est.resize(Nbin+1,1);\n\nenrich_jack.resize(Nbin,Njack);\nenrich_point_est.resize(Nbin,1);\n\n\nfor (jack_index=0;jack_index<=Njack;jack_index++){\n\n  for (int i=0;i<Nbin;i++){\n\n\tb_trk(i,0)=Nindv_mask;\n\t\n\tif(jack_index==Njack)\n\tc_yky(i,0)=yXXy(i,jack_index)/len[i];\n\telse\n\tc_yky(i,0)=yXXy(i,jack_index)/(len[i]-jack_bin_size(jack_index,i));\n\t//cout<<\"bin \"<<i<<\"yXXy \"<<yXXy(i,jack_index)<<endl;\n\tfor (int j=i;j<Nbin;j++){\n\t\t//cout<<Njack<<endl;\n\t\tB1=XXz.block(0,(i*(Njack+1)*Nz)+(jack_index*Nz),g.Nindv,Nz);\n\t\tB2=XXz.block(0,(j*(Njack+1)*Nz)+(jack_index*Nz),g.Nindv,Nz);\n\t\tC1=B1.array()*B2.array();\t\n\t\tC2=C1.colwise().sum();\n\t\ttrkij=C2.sum();\n\t\t\n\t\t//cout<<\"tr\"<<i<<\" \"<<j<<\" : \"<<trkij<<endl;\n\t        if(jack_index==Njack)\n\t\ttrkij=trkij/len[i]/len[j]/Nz;\n\t\telse\n\t\t trkij=trkij/(len[i]-jack_bin_size(jack_index,i))/(len[j]-jack_bin_size(jack_index,j))/Nz;\n\t\tA_trs(i,j)=trkij;\n\t\tA_trs(j,i)=trkij;\n\t\t\n\t}\n  }\n\n\nX_l<<A_trs,b_trk,b_trk.transpose(),Nindv_mask;\nY_r<<c_yky,yy;\n\nMatrixXdr herit=X_l.colPivHouseholderQr().solve(Y_r);\n\ndouble temp_sig=0;\ndouble temp_sum=0;\n\nif(jack_index==Njack){\n     for(int i=0;i<(Nbin+1);i++)\n\t  point_est(i,0)=herit(i,0);\n}\nelse{\nfor(int i=0;i<(Nbin+1);i++)\n      jack(i,jack_index)=herit(i,0);\t\n}\n\ndouble total_val=0;\nfor(int i=0; i<Nbin;i++)\n    total_val+=herit(i,0);\n\n/*\nfor(int i=0; i<Nbin;i++){\n   cout<<herit(i,0)/herit.sum()<<\" \";\n}\n\tcout<<total_val/herit.sum()<<endl;\n*/\n//cout<<X_l<<endl;\n//cout<<Y_r<<endl;\n//cout<<\"ddddddddddd\"<<endl;\n\n}// end of loop over jacks\n\n//cout<<\"helolll\"<<endl;\ndouble temp_sig=0;\ndouble temp_sum=0;\n\ntemp_sig=0;\ntemp_sum=point_est.sum();\nfor (int j=0;j<Nbin;j++){\n        point_est(j,0)=point_est(j,0)/temp_sum;\n        temp_sig+=point_est(j,0);\n}\npoint_est(Nbin,0)=temp_sig;\n\n\nfor (int i=0;i<Njack;i++){\n   temp_sig=0;\n   temp_sum=jack.col(i).sum();\n   for (int j=0;j<Nbin;j++){\n        jack(j,i)=jack(j,i)/temp_sum;\n        temp_sig+=jack(j,i);\n   }\n   jack(Nbin,i)=temp_sig;\n}\n\n///compute enrichment\n\ndouble per_her;\ndouble per_size;\nint total_size=0;\n\nfor (int i=0;i<Nbin;i++)\n   total_size+=len[i];\n\nfor (int j=0;j<Nbin;j++){\n        per_her=point_est(j,0)/point_est(Nbin,0);\n        per_size=(double)len[j]/total_size;\n        enrich_point_est(j,0)=per_her/per_size;\n\t//cout<<j<<\" \"<<per_her<<\" \"<<total_size<<\" \"<<len[j]<<\" \"<<per_size<<\" \"<<enrich_point_est(j,0)<<endl;\n}\n\n\nfor (int i=0;i<Njack;i++){\n    per_size=0;\n    total_size=0;\n    for (int j=0;j<Nbin;j++){\n\ttotal_size+=(len[j]-jack_bin_size(i,j));\n    }\n   for (int j=0;j<Nbin;j++){\n   \tper_her=jack(j,i)/jack(Nbin,i);\n\tper_size=(double)(len[j]-jack_bin_size(i,j))/total_size;\n\tenrich_jack(j,i)=per_her/per_size;\n\t}\n}\n\n\n\n////compute jackknife SE\nMatrixXdr sum_row=jack.rowwise().mean();\nMatrixXdr SEjack;\nSEjack=MatrixXdr::Zero(Nbin+1,1);\ndouble temp_val=0;\nfor (int i=0;i<=Nbin;i++){\n    for (int j=0;j<Njack;j++){\n\ttemp_val=jack(i,j)-sum_row(i);\n\ttemp_val= temp_val* temp_val;\n\tSEjack(i,0)+=temp_val;\n    }\n    SEjack(i,0)=SEjack(i,0)*(Njack-1)/Njack;\n    SEjack(i,0)=sqrt(SEjack(i,0));\n}\n///////// compute jackknife SE of enrichment\n sum_row=enrich_jack.rowwise().mean();\nMatrixXdr enrich_SEjack;\nenrich_SEjack=MatrixXdr::Zero(Nbin,1);\n temp_val=0;\nfor (int i=0;i<Nbin;i++){\n    for (int j=0;j<Njack;j++){\n        temp_val=enrich_jack(i,j)-sum_row(i);\n        temp_val= temp_val* temp_val;\n        enrich_SEjack(i,0)+=temp_val;\n    }\n    enrich_SEjack(i,0)=enrich_SEjack(i,0)*(Njack-1)/Njack;\n    enrich_SEjack(i,0)=sqrt(enrich_SEjack(i,0));\n}\n\n\n//for (int i=0;i<Njack;i++)\n  //  cout<<jack.col(i).transpose()<<endl;\ncout<<\"OUTPUT: \"<<endl;\nfor (int j=0;j<Nbin;j++)\n     cout<<\"h^2 of bin \"<<j<<\" : \"<<point_est(j,0)<<\" ,  SE: \"<<SEjack(j,0)<<endl;\ncout<<\"Total h^2 : \"<<point_est(Nbin,0)<<\" , SE: \"<<SEjack(Nbin,0)<<endl;\nfor (int j=0;j<Nbin;j++)\n     cout<<\"Enrichment of bin \"<<j<<\" :\"<<enrich_point_est(j,0)<<\" ,  SE: \"<<enrich_SEjack(j,0)<<endl;\n\n/*cout<<\"Point estimates :\"<<endl;\ncout<<point_est.transpose()<<endl;\ncout<<\"SEs     :\"<<endl;\ncout<<SEjack.transpose()<<endl;\n\ncout<<\"Enrichment :\"<<endl;\ncout<<enrich_point_est.transpose()<<endl;\ncout<<\"SEs     :\"<<endl;\ncout<<enrich_SEjack.transpose()<<endl;\n*/\n std::ofstream outfile;\nstring add_output=command_line_opts.OUTPUT_FILE_PATH;\noutfile.open(add_output.c_str(), std::ios_base::app);\n\noutfile<<\"Point estimates :\"<<endl;\noutfile<<point_est.transpose()<<endl;\noutfile<<\"SEs     :\"<<endl;\noutfile<<SEjack.transpose()<<endl;\n      \noutfile<<\"Enrichment :\"<<endl;\noutfile<<enrich_point_est.transpose()<<endl;\noutfile<<\"SEs     :\"<<endl;\noutfile<<enrich_SEjack.transpose()<<endl;\n\n\n\n\n\n\n\n\n\treturn 0;\n}\n", "meta": {"hexsha": "53ea8a9eedbae3faac81f029657b476bf9ff34a4", "size": 32761, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/RHEmc.cpp", "max_stars_repo_name": "fcooper8472/RHE-mc", "max_stars_repo_head_hexsha": "e2c87e10dff5b668aa2e145fd43b61a0da91d16b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-08T17:07:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-08T17:07:08.000Z", "max_issues_repo_path": "src/RHEmc.cpp", "max_issues_repo_name": "fcooper8472/RHE-mc", "max_issues_repo_head_hexsha": "e2c87e10dff5b668aa2e145fd43b61a0da91d16b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2020-09-30T14:53:00.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-22T20:04:23.000Z", "max_forks_repo_path": "src/RHEmc.cpp", "max_forks_repo_name": "fcooper8472/RHE-mc", "max_forks_repo_head_hexsha": "e2c87e10dff5b668aa2e145fd43b61a0da91d16b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2019-06-06T02:18:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-26T17:02:56.000Z", "avg_line_length": 24.7252830189, "max_line_length": 136, "alphanum_fraction": 0.6068190837, "num_tokens": 10432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.47481041721478745}}
{"text": "#include \"discrete_sequence.hpp\"\n#include \"pow2.hpp\"\n#include <boost/hana/integral_constant.hpp>\n#include <array>\n\nusing namespace boost::hana::literals;\n\nstd::array<int, 5> a{{1, 2, 3, 4, 5}};\n\ntemplate <typename UnderlyingExpr>\nstruct multiply_expr\n{\n    constexpr explicit multiply_expr(unsigned mult, UnderlyingExpr const& expr) :\n        mult{mult}, expr{expr} {};\n\n    constexpr auto operator()(size_t index) const {\n        return mult * expr(index);\n    }\n\n    unsigned              mult;\n    UnderlyingExpr const& expr;\n};\n\ntemplate <long long N, typename UnderlyingSequence>\nconstexpr auto operator*(unsigned mult, pow_expr<N, UnderlyingSequence> const& pow)\n{\n    return multiply_expr{mult, pow};\n}\n\nint main()\n{\n    auto s = discrete_sequence{a};\n    auto e = 2 * (s ^ 2_c);\n\n    return e(0);\n}\n", "meta": {"hexsha": "931af7febe3289f38e041be07b81b60d5c74a79b", "size": 807, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "4_manual_expression_templates/main4.cpp", "max_stars_repo_name": "rgrover/yap-demos", "max_stars_repo_head_hexsha": "d4e100f9fb835bea2a6505f2ed9b8e87ee1ee928", "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": "4_manual_expression_templates/main4.cpp", "max_issues_repo_name": "rgrover/yap-demos", "max_issues_repo_head_hexsha": "d4e100f9fb835bea2a6505f2ed9b8e87ee1ee928", "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": "4_manual_expression_templates/main4.cpp", "max_forks_repo_name": "rgrover/yap-demos", "max_forks_repo_head_hexsha": "d4e100f9fb835bea2a6505f2ed9b8e87ee1ee928", "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": 21.8108108108, "max_line_length": 83, "alphanum_fraction": 0.6741016109, "num_tokens": 208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.47481041218257886}}
{"text": "/**\n * \\ file Chebyshev1Filter.cpp\n */\n\n#include <ATK/EQ/Chebyshev1Filter.h>\n#include <ATK/EQ/IIRFilter.h>\n\n#include <ATK/Mock/FFTCheckerFilter.h>\n#include <ATK/Mock/SimpleSinusGeneratorFilter.h>\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_NO_MAIN\n#include <boost/test/unit_test.hpp>\n\n#define PROCESSSIZE (1024*64)\n\nBOOST_AUTO_TEST_CASE( IIRFilter_Chebyshev1LowPassCoefficients_1k_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(1000);\n  \n  ATK::IIRFilter<ATK::Chebyshev1LowPassCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_cut_frequency(100);\n  filter.set_ripple(3);\n  filter.set_order(3);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(100, 0));\n  frequency_checks.push_back(std::make_pair(1000, 0.01587182644655375));\n  frequency_checks.push_back(std::make_pair(10000, 0));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_Chebyshev1LowPassCoefficients_100_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(100);\n  \n  ATK::IIRFilter<ATK::Chebyshev1LowPassCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_cut_frequency(100);\n  filter.set_ripple(3);\n  filter.set_order(3);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(10, 0));\n  frequency_checks.push_back(std::make_pair(100, 0.8413951421002385));\n  frequency_checks.push_back(std::make_pair(1000, 0));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_Chebyshev1LowPassCoefficients_2k_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(2000);\n  \n  ATK::IIRFilter<ATK::Chebyshev1LowPassCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_cut_frequency(100);\n  filter.set_ripple(3);\n  filter.set_order(3);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(100, 0));\n  frequency_checks.push_back(std::make_pair(1000, 0));\n  frequency_checks.push_back(std::make_pair(2000, 0.005576397202690614));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_Chebyshev1LowPassCoefficients_200_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(200);\n  \n  ATK::IIRFilter<ATK::Chebyshev1LowPassCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_cut_frequency(100);\n  filter.set_ripple(3);\n  filter.set_order(3);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(100, 0));\n  frequency_checks.push_back(std::make_pair(200, 0.1962613670420864));\n  frequency_checks.push_back(std::make_pair(1000, 0));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_Chebyshev1HighPassCoefficients_1k_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(1000);\n  \n  ATK::IIRFilter<ATK::Chebyshev1HighPassCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_cut_frequency(100);\n  filter.set_ripple(3);\n  filter.set_order(3);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(100, 0));\n  frequency_checks.push_back(std::make_pair(1000, 0.9792933050029933));\n  frequency_checks.push_back(std::make_pair(10000, 0));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_Chebyshev1HighPassCoefficients_100_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(100);\n  \n  ATK::IIRFilter<ATK::Chebyshev1HighPassCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_cut_frequency(100);\n  filter.set_ripple(3);\n  filter.set_order(3);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(10, 0));\n  frequency_checks.push_back(std::make_pair(100, 0.841395141674365));\n  frequency_checks.push_back(std::make_pair(1000, 0));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_Chebyshev1HighPassCoefficients_2k_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(2000);\n  \n  ATK::IIRFilter<ATK::Chebyshev1HighPassCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_cut_frequency(100);\n  filter.set_ripple(3);\n  filter.set_order(3);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(100, 0));\n  frequency_checks.push_back(std::make_pair(1000, 0));\n  frequency_checks.push_back(std::make_pair(2000, 0.994533852735074));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_Chebyshev1HighPassCoefficients_200_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(200);\n  \n  ATK::IIRFilter<ATK::Chebyshev1HighPassCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_cut_frequency(100);\n  filter.set_ripple(3);\n  filter.set_order(3);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(100, 0));\n  frequency_checks.push_back(std::make_pair(200, 0.841014519725825));\n  frequency_checks.push_back(std::make_pair(1000, 0));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_Chebyshev1BandPassCoefficients_1k_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(1000);\n  \n  ATK::IIRFilter<ATK::Chebyshev1BandPassCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_cut_frequencies(std::make_pair(200, 1000));\n  filter.set_ripple(3);\n  filter.set_order(3);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(100, 0));\n  frequency_checks.push_back(std::make_pair(1000, 0.84139514149622));\n  frequency_checks.push_back(std::make_pair(10000, 0));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_Chebyshev1BandPassCoefficients_100_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(100);\n  \n  ATK::IIRFilter<ATK::Chebyshev1BandPassCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_cut_frequencies(std::make_pair(200, 1000));\n  filter.set_ripple(3);\n  filter.set_order(3);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(10, 0));\n  frequency_checks.push_back(std::make_pair(100, 0.14682528623369445));\n  frequency_checks.push_back(std::make_pair(1000, 0));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_Chebyshev1BandPassCoefficients_2k_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(2000);\n  \n  ATK::IIRFilter<ATK::Chebyshev1BandPassCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_cut_frequencies(std::make_pair(200, 1000));\n  filter.set_ripple(3);\n  filter.set_order(3);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(100, 0));\n  frequency_checks.push_back(std::make_pair(1000, 0));\n  frequency_checks.push_back(std::make_pair(2000, 0.1462850319776135));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_Chebyshev1BandPassCoefficients_200_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(200);\n  \n  ATK::IIRFilter<ATK::Chebyshev1BandPassCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_cut_frequencies(std::make_pair(200, 1000));\n  filter.set_ripple(3);\n  filter.set_order(3);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(100, 0));\n  frequency_checks.push_back(std::make_pair(200, 0.8413951007802791));\n  frequency_checks.push_back(std::make_pair(1000, 0));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_Chebyshev1BandStopCoefficients_1k_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(1000);\n  \n  ATK::IIRFilter<ATK::Chebyshev1BandStopCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_cut_frequencies(std::make_pair(200, 1000));\n  filter.set_ripple(3);\n  filter.set_order(3);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(100, 0));\n  frequency_checks.push_back(std::make_pair(1000, 0.8413951401352051));\n  frequency_checks.push_back(std::make_pair(10000, 0));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_Chebyshev1BandStopCoefficients_100_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(100);\n  \n  ATK::IIRFilter<ATK::Chebyshev1BandStopCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_cut_frequencies(std::make_pair(200, 1000));\n  filter.set_ripple(3);\n  filter.set_order(3);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(10, 0));\n  frequency_checks.push_back(std::make_pair(100, 0.8485500087021252));\n  frequency_checks.push_back(std::make_pair(1000, 0));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_Chebyshev1BandStopCoefficients_2k_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(2000);\n  \n  ATK::IIRFilter<ATK::Chebyshev1BandStopCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_cut_frequencies(std::make_pair(200, 1000));\n  filter.set_ripple(3);\n  filter.set_order(3);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(100, 0));\n  frequency_checks.push_back(std::make_pair(1000, 0));\n  frequency_checks.push_back(std::make_pair(2000, 0.8490125934799859));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_Chebyshev1BandStopCoefficients_200_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(200);\n  \n  ATK::IIRFilter<ATK::Chebyshev1BandStopCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_cut_frequencies(std::make_pair(200, 1000));\n  filter.set_ripple(3);\n  filter.set_order(3);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(100, 0));\n  frequency_checks.push_back(std::make_pair(200, 0.8413953236422822));\n  frequency_checks.push_back(std::make_pair(1000, 0));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n", "meta": {"hexsha": "a1afeab4af00d402f338acebd8cad12825ef3605", "size": 16494, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/EQ/Chebyshev1Filter.cpp", "max_stars_repo_name": "apohl79/AudioTK", "max_stars_repo_head_hexsha": "05ac241b0bc6a8f841d93257b4d81e5961b1f627", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-05-17T15:29:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T22:26:08.000Z", "max_issues_repo_path": "tests/EQ/Chebyshev1Filter.cpp", "max_issues_repo_name": "apohl79/AudioTK", "max_issues_repo_head_hexsha": "05ac241b0bc6a8f841d93257b4d81e5961b1f627", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/EQ/Chebyshev1Filter.cpp", "max_forks_repo_name": "apohl79/AudioTK", "max_forks_repo_head_hexsha": "05ac241b0bc6a8f841d93257b4d81e5961b1f627", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-04-21T13:43:57.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-28T19:10:14.000Z", "avg_line_length": 33.2540322581, "max_line_length": 73, "alphanum_fraction": 0.7734327634, "num_tokens": 4683, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891130942474, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4748104021181611}}
{"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/** \\file VectorDesignVariableTest.cpp\n    \\brief This file tests the VectorDesignVariable class.\n  */\n\n#include <cstddef>\n#include <iomanip>\n#include <iostream>\n\n#include <gtest/gtest.h>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n#include <cholmod.h>\n#include <SuiteSparseQR.hpp>\n\n#include \"aslam/calibration/algorithms/linalg.h\"\n#include \"aslam/calibration/base/Timestamp.h\"\n#include \"aslam/calibration/core/LinearSolver.h\"\n#include \"aslam/calibration/statistics/NormalDistribution.h\"\n\nvoid evaluateSVDSPQRSolver(const Eigen::MatrixXd& A, const Eigen::VectorXd& b, const Eigen::VectorXd& x,\n                           double tol = 1e-9) {\n    cholmod_common cholmod;\n    cholmod_l_start(&cholmod);\n    cholmod_sparse* A_CS = aslam::calibration::eigenDenseToCholmodSparseCopy(A, &cholmod);\n    cholmod_dense b_CD;\n    aslam::calibration::eigenDenseToCholmodDenseView(b, &b_CD);\n    Eigen::VectorXd x_est;\n    aslam::calibration::LinearSolver linearSolver;\n    for (std::ptrdiff_t i = 1; i < A.cols(); ++i) {\n        //    double before = aslam::calibration::Timestamp::now();\n        linearSolver.solve(A_CS, &b_CD, i, x_est);\n        //    double after = aslam::calibration::Timestamp::now();\n        double error = (b - A * x_est).norm();\n        //    std::cout << std::fixed << std::setprecision(18) << \"noscale: \" << \"error: \"\n        //      << error << \" est_diff: \" << (x - x_est).norm() << \" time: \"\n        //      << after - before << std::endl;\n        ASSERT_NEAR(error, 0, tol);\n        linearSolver.getOptions().columnScaling = true;\n        //    before = aslam::calibration::Timestamp::now();\n        linearSolver.solve(A_CS, &b_CD, i, x_est);\n        //    after = aslam::calibration::Timestamp::now();\n        error = (b - A * x_est).norm();\n        //    std::cout << std::fixed << std::setprecision(18) << \"onscale: \" << \"error: \"\n        //      << error << \" est_diff: \" << (x - x_est).norm() << \" time: \"\n        //      << after - before << std::endl;\n        linearSolver.getOptions().columnScaling = false;\n        ASSERT_NEAR(error, 0, tol);\n        //    std::cout << \"SVD rank: \" << linearSolver.getSVDRank() << std::endl;\n        //    std::cout << \"SVD rank deficiency: \" << linearSolver.getSVDRankDeficiency()\n        //      << std::endl;\n        //    std::cout << \"QR rank: \" << linearSolver.getQRRank() << std::endl;\n        //    std::cout << \"QR rank deficiency: \"\n        //      << linearSolver.getQRRankDeficiency() << std::endl;\n        //    std::cout << \"SV gap: \" << linearSolver.getSvGap() << std::endl;\n    }\n    cholmod_l_free_sparse(&A_CS, &cholmod);\n    cholmod_l_finish(&cholmod);\n}\n\nvoid evaluateSVDSolver(const Eigen::MatrixXd& A, const Eigen::VectorXd& b, const Eigen::VectorXd& x) {\n    //  const double before = aslam::calibration::Timestamp::now();\n    const Eigen::JacobiSVD<Eigen::MatrixXd> svd(A, Eigen::ComputeThinU | Eigen::ComputeThinV);\n    Eigen::VectorXd x_est = svd.solve(b);\n    //  const double after = aslam::calibration::Timestamp::now();\n    //  const double error = (b - A * x_est).norm();\n    //  std::cout << std::fixed << std::setprecision(18) << \"error: \" << error\n    //    << \" est_diff: \" << (x - x_est).norm() << \" time: \" << after - before\n    //    << std::endl;\n    //  std::cout << \"estimated rank: \" << svd.nonzeroSingularValues() << std::endl;\n    //  std::cout << \"estimated rank deficiency: \"\n    //    << A.cols() - svd.nonzeroSingularValues() << std::endl;\n}\n\nvoid evaluateSPQRSolver(const Eigen::MatrixXd& A, const Eigen::VectorXd& b, const Eigen::VectorXd& x) {\n    cholmod_common cholmod;\n    cholmod_l_start(&cholmod);\n    cholmod_sparse* A_CS = aslam::calibration::eigenDenseToCholmodSparseCopy(A, &cholmod);\n    cholmod_dense b_CD;\n    aslam::calibration::eigenDenseToCholmodDenseView(b, &b_CD);\n    Eigen::VectorXd x_est;\n    //  const double before = aslam::calibration::Timestamp::now();\n    SuiteSparseQR_factorization<double>* factor =\n        SuiteSparseQR_factorize<double>(SPQR_ORDERING_BEST, SPQR_DEFAULT_TOL, A_CS, &cholmod);\n    cholmod_dense* Qtb = SuiteSparseQR_qmult<double>(SPQR_QTX, factor, &b_CD, &cholmod);\n    cholmod_dense* x_est_cd = SuiteSparseQR_solve<double>(SPQR_RETX_EQUALS_B, factor, Qtb, &cholmod);\n    cholmod_l_free_dense(&Qtb, &cholmod);\n    aslam::calibration::cholmodDenseToEigenDenseCopy(x_est_cd, x_est);\n    cholmod_l_free_dense(&x_est_cd, &cholmod);\n    //  std::cout << \"estimated rank: \" << factor->rank << std::endl;\n    //  std::cout << \"estimated rank deficiency: \" << A.cols() - factor->rank\n    //    << std::endl;\n    SuiteSparseQR_free(&factor, &cholmod);\n    //  const double after = aslam::calibration::Timestamp::now();\n    //  const double error = (b - A * x_est).norm();\n    //  std::cout << std::fixed << std::setprecision(18) << \"error: \" << error\n    //    << \" est_diff: \" << (x - x_est).norm() << \" time: \" << after - before\n    //    << std::endl;\n    cholmod_l_free_sparse(&A_CS, &cholmod);\n    cholmod_l_finish(&cholmod);\n}\n\nTEST(AslamCalibrationTestSuite, testLinearSolver) {\n    Eigen::MatrixXd A = Eigen::MatrixXd::Random(100, 30);\n    const Eigen::VectorXd x = Eigen::VectorXd::Random(30);\n    Eigen::VectorXd b = A * x;\n\n    //  std::cout << \"-------------------------------------------------\" << std::endl;\n    //  std::cout << \"|                  Standard case                |\" << std::endl;\n    //  std::cout << \"-------------------------------------------------\" << std::endl;\n    //  std::cout << \"SVD-SPQR solver\" << std::endl;\n    evaluateSVDSPQRSolver(A, b, x);\n    //  std::cout << \"SVD solver\" << std::endl;\n    evaluateSVDSolver(A, b, x);\n    //  std::cout << \"SPQR solver\" << std::endl;\n    evaluateSPQRSolver(A, b, x);\n\n    //  std::cout << \"-------------------------------------------------\" << std::endl;\n    //  std::cout << \"|                 Badly scaled case             |\" << std::endl;\n    //  std::cout << \"-------------------------------------------------\" << std::endl;\n    //  A.col(2) = 1e6 * A.col(2);\n    //  A.col(28) = 1e6 * A.col(28);\n    //  b = A * x;\n    //  std::cout << \"SVD-SPQR solver\" << std::endl;\n    //  evaluateSVDSPQRSolver(A, b, x, 1e-3);\n    //  std::cout << \"SVD solver\" << std::endl;\n    //  evaluateSVDSolver(A, b, x);\n    //  std::cout << \"SPQR solver\" << std::endl;\n    //  evaluateSPQRSolver(A, b, x);\n\n    //  std::cout << \"-------------------------------------------------\" << std::endl;\n    //  std::cout << \"|                 Rank-deficient case 1         |\" << std::endl;\n    //  std::cout << \"-------------------------------------------------\" << std::endl;\n    //  A = Eigen::MatrixXd::Random(100, 30);\n    //  A.col(10) = Eigen::VectorXd::Zero(A.rows());\n    //  b = A * x;\n    //  std::cout << \"SVD-SPQR solver\" << std::endl;\n    //  evaluateSVDSPQRSolver(A, b, x, 1e-3);\n    //  std::cout << \"SVD solver\" << std::endl;\n    //  evaluateSVDSolver(A, b, x);\n    //  std::cout << \"SPQR solver\" << std::endl;\n    //  evaluateSPQRSolver(A, b, x);\n\n    //  std::cout << \"-------------------------------------------------\" << std::endl;\n    //  std::cout << \"|                 Rank-deficient case 2         |\" << std::endl;\n    //  std::cout << \"-------------------------------------------------\" << std::endl;\n    //  A = Eigen::MatrixXd::Random(100, 30);\n    //  A.col(10) = 2 * A.col(1) + 5 * A.col(20);\n    //  b = A * x;\n    //  std::cout << \"SVD-SPQR solver\" << std::endl;\n    //  evaluateSVDSPQRSolver(A, b, x, 1e-3);\n    //  std::cout << \"SVD solver\" << std::endl;\n    //  evaluateSVDSolver(A, b, x);\n    //  std::cout << \"SPQR solver\" << std::endl;\n    //  evaluateSPQRSolver(A, b, x);\n\n    //  std::cout << \"-------------------------------------------------\" << std::endl;\n    //  std::cout << \"|                 Near rank-deficient case 1    |\" << std::endl;\n    //  std::cout << \"-------------------------------------------------\" << std::endl;\n    //  A = Eigen::MatrixXd::Random(100, 30);\n    //  A.col(10) = Eigen::VectorXd::Zero(A.rows());\n    //  b = A * x;\n    //  A.col(10) = aslam::calibration::NormalDistribution<100>(\n    //    Eigen::VectorXd::Zero(A.rows()),\n    //    1e-6 * Eigen::MatrixXd::Identity(A.rows(), A.rows())).getSample();\n    //  std::cout << \"SVD-SPQR solver\" << std::endl;\n    //  evaluateSVDSPQRSolver(A, b, x, 1e-3);\n    //  std::cout << \"SVD solver\" << std::endl;\n    //  evaluateSVDSolver(A, b, x);\n    //  std::cout << \"SPQR solver\" << std::endl;\n    //  evaluateSPQRSolver(A, b, x);\n\n    //  std::cout << \"-------------------------------------------------\" << std::endl;\n    //  std::cout << \"|                 Near rank-deficient case 2    |\" << std::endl;\n    //  std::cout << \"-------------------------------------------------\" << std::endl;\n    //  A = Eigen::MatrixXd::Random(100, 30);\n    //  A.col(10) = 2 * A.col(1) + 5 * A.col(20);\n    //  b = A * x;\n    //  A.col(10) = aslam::calibration::NormalDistribution<100>(A.col(10),\n    //    1e-20 * Eigen::MatrixXd::Identity(A.rows(), A.rows())).getSample();\n    //  std::cout << \"SVD-SPQR solver\" << std::endl;\n    //  evaluateSVDSPQRSolver(A, b, x, 1e-3);\n    //  std::cout << \"SVD solver\" << std::endl;\n    //  evaluateSVDSolver(A, b, x);\n    //  std::cout << \"SPQR solver\" << std::endl;\n    //  evaluateSPQRSolver(A, b, x);\n}\n", "meta": {"hexsha": "f30deab0fd6f52e3bc7ea5b88100de1675af7307", "size": 10614, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "aslam_incremental_calibration/incremental_calibration/test/LinearSolverTest.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/test/LinearSolverTest.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/test/LinearSolverTest.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": 51.2753623188, "max_line_length": 104, "alphanum_fraction": 0.5118711136, "num_tokens": 2936, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435083355187, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4747515683360914}}
{"text": "\n#include <csapex/model/node.h>\n#include <csapex/msg/io.h>\n#include <csapex/utility/register_apex_plugin.h>\n\n#include <csapex/msg/generic_value_message.hpp>\n#include <csapex_scan_2d/scan_message.h>\n\n#include <csapex/model/node_modifier.h>\n#include <csapex/param/parameter_factory.h>\n\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics.hpp>\n#include <cslibs_laser_processing/common/yaml-io.hpp>\n\nnamespace\n{\ndouble normalize(double angle)\n{\n    while (angle <= -M_PI)\n        angle += 2 * M_PI;\n    while (angle > M_PI)\n        angle -= 2 * M_PI;\n    return angle;\n}\n}  // namespace\n\nnamespace csapex\n{\nusing namespace lib_laser_processing;\nusing namespace boost::accumulators;\nusing namespace connection_types;\n\nclass HeightPitchAngle : public csapex::Node\n{\npublic:\n    HeightPitchAngle() : toggle_counter_(0), toggle_(false)\n    {\n    }\n\n    virtual void setup(NodeModifier& node_modifier) override\n    {\n        input_ = node_modifier.addInput<ScanMessage>(\"filtered scan\");\n        output_pitch_ = node_modifier.addOutput<double>(\"pitch\");\n        output_height_ = node_modifier.addOutput<double>(\"height\");\n    }\n\n    void setupParameters(Parameterizable& parameters) override\n    {\n        parameters.addParameter(param::factory::declareRange(\"start height\", 0.05, 1.0, 0.1, 0.001), std::bind(&HeightPitchAngle::updateStartParameters, this));\n        parameters.addParameter(param::factory::declareRange(\"start pitch\", -M_PI, M_PI, 0.0, 0.01), std::bind(&HeightPitchAngle::updateStartParameters, this));\n        parameters.addParameter(param::factory::declareRange(\"switch after\", 1, 100, 1, 1));\n        parameters.addParameter(param::factory::declareBool(\"renew\", false));\n\n        parameters.addParameter(param::factory::declareTrigger(\"reset\"), std::bind(&HeightPitchAngle::reset, this));\n        parameters.addParameter(param::factory::declareBool(\"degrees\", false));\n    }\n\n    virtual void process() override\n    {\n        ScanMessage::ConstPtr in = msg::getMessage<ScanMessage>(input_);\n        const Scan& scan = in->value;\n        bool deg = readParameter<bool>(\"degrees\");\n        int toggle_after = readParameter<int>(\"switch after\");\n        bool renew = readParameter<bool>(\"renew\");\n\n        for (const LaserBeam& b : scan.rays) {\n            if (b.range() > 0.f)\n                mean_dist_(b.posX());\n        }\n\n        if (toggle_) {\n            /// fit height\n            height_ = sin(pitch_) * mean(mean_dist_);\n        } else {\n            /// fit angle\n            pitch_ = normalize(asin(height_ / mean(mean_dist_)));\n        }\n        ++toggle_counter_;\n\n        if (toggle_counter_ >= toggle_after) {\n            toggle_counter_ = 0;\n            toggle_ = !toggle_;\n            if (renew)\n                reset();\n        }\n\n        double out_pitch = pitch_;\n        if (deg)\n            out_pitch *= 180.0 / M_PI;\n\n        msg::publish(output_pitch_, out_pitch);\n        msg::publish(output_height_, height_);\n    }\n\nprivate:\n    Input* input_;\n    Output* output_pitch_;\n    Output* output_height_;\n    double height_;\n    double pitch_;\n    int toggle_counter_;\n    bool toggle_;\n\n    accumulator_set<double, stats<tag::mean>> mean_dist_;\n\n    void reset() override\n    {\n        mean_dist_ = accumulator_set<double, stats<tag::mean>>();\n    }\n\n    void updateStartParameters()\n    {\n        height_ = readParameter<double>(\"start height\");\n        pitch_ = readParameter<double>(\"start pitch\");\n        reset();\n    }\n};\n}  // namespace csapex\n\nCSAPEX_REGISTER_CLASS(csapex::HeightPitchAngle, csapex::Node)\n", "meta": {"hexsha": "51d206d56715385055ea4358f4e63b30846df4ca", "size": 3579, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "csapex_scan_2d/src/height_pitch_angle.cpp", "max_stars_repo_name": "AdrianZw/csapex_core_plugins", "max_stars_repo_head_hexsha": "1b23c90af7e552c3fc37c7dda589d751d2aae97f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-09-02T15:33:22.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-06T22:09:33.000Z", "max_issues_repo_path": "csapex_scan_2d/src/height_pitch_angle.cpp", "max_issues_repo_name": "AdrianZw/csapex_core_plugins", "max_issues_repo_head_hexsha": "1b23c90af7e552c3fc37c7dda589d751d2aae97f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-02-14T19:53:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-14T19:53:30.000Z", "max_forks_repo_path": "csapex_scan_2d/src/height_pitch_angle.cpp", "max_forks_repo_name": "AdrianZw/csapex_core_plugins", "max_forks_repo_head_hexsha": "1b23c90af7e552c3fc37c7dda589d751d2aae97f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2016-10-12T00:55:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-10T17:49:25.000Z", "avg_line_length": 29.3360655738, "max_line_length": 160, "alphanum_fraction": 0.6459905001, "num_tokens": 850, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4747515618798561}}
{"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_SSE1_SCALAR_FUNCTION_RSQRT_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_X86_SSE1_SCALAR_FUNCTION_RSQRT_HPP_INCLUDED\n#include <boost/simd/detail/overload.hpp>\n\n#include <boost/simd/function/raw.hpp>\n#include <boost/simd/function/pedantic.hpp>\n#include <boost/simd/function/abs.hpp>\n#include <boost/simd/function/if_nan_else.hpp>\n#include <boost/simd/function/if_zero_else.hpp>\n#include <boost/simd/function/is_eqz.hpp>\n#include <boost/simd/function/is_ltz.hpp>\n#include <boost/simd/function/refine_rsqrt.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/detail/constant/denormalfactor.hpp>\n#include <boost/simd/detail/constant/denormalsqrtfactor.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd =  boost::dispatch;\n  namespace bs =  boost::simd;\n  BOOST_DISPATCH_OVERLOAD ( rsqrt_\n                          , (typename A0)\n                          , bs::sse1_\n                          , bs::raw_tag\n                          , bd::scalar_<bd::single_<A0>>\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() (raw_tag const&\n                                    , const A0 & a0) const BOOST_NOEXCEPT\n    {\n      float inv;\n      _mm_store_ss( &inv, _mm_rsqrt_ss( _mm_load_ss( &a0 ) ) );\n      return inv;\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( rsqrt_\n                          , (typename A0)\n                          , bs::sse1_\n                          , bs::raw_tag\n                          , bd::scalar_<bd::double_<A0>>\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() (raw_tag const&\n                                    , const A0 & a0) const BOOST_NOEXCEPT\n    {\n      float inv = a0;\n      _mm_store_ss( &inv, _mm_rsqrt_ss( _mm_load_ss( &inv ) ) );\n      return double(inv);\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( rsqrt_\n                          , (typename A0)\n                          , bs::sse1_\n                          , bd::scalar_<bd::single_<A0>>\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() (const A0 & a00) const BOOST_NOEXCEPT\n    {\n      if (is_eqz(a00)) return Inf<A0>();\n      #ifndef BOOST_SIMD_NO_INFINITIES\n      if (a00 == Inf<A0>()) return Zero<A0>();\n      #endif\n      A0 a0 =  raw_(rsqrt)(a00);\n      A0 y = sqr(a0)*a00;\n      return a0*Ratio<A0, 1, 8>()*fnms(y, fnms(A0(3), y, A0(10)), A0(15)); //this is Halley cubically convergent iteration\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( rsqrt_\n                          , (typename A0)\n                          , bs::sse1_\n                          , bs::pedantic_tag\n                          , bd::scalar_<bd::single_<A0>>\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() (pedantic_tag const&\n                                    ,const A0 & a00) const BOOST_NOEXCEPT\n    {\n      if (is_eqz(a00)) return Inf<A0>();\n      #ifndef BOOST_SIMD_NO_INFINITIES\n      if (a00 == Inf<A0>()) return Zero<A0>();\n      #endif\n      A0 a0 = a00;\n      auto is_den = bs::abs(a00) < Smallestposval<A0>();\n      #ifndef BOOST_SIMD_NO_DENORMALS\n      a0 *= if_else(is_den, Denormalfactor<A0>(), One<A0>());\n      #endif\n      a0 = refine_rsqrt(a0, refine_rsqrt(a0, raw_(rsqrt)(a0)));// Two Newton is sometimes better than one halley\n      #ifndef BOOST_SIMD_NO_DENORMALS\n      a0 *= if_else(is_den, Denormalsqrtfactor<A0>(), One<A0>());\n      #endif\n      return a0;\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( rsqrt_\n                          , (typename A0)\n                          , bs::sse1_\n                          , bs::pedantic_tag\n                          , bd::scalar_<bd::double_<A0>>\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() (pedantic_tag const&\n                                    ,const A0 & a00) const BOOST_NOEXCEPT\n    {\n      if (is_eqz(a00)) return Inf<A0>();\n      #ifndef BOOST_SIMD_NO_INFINITIES\n      if (a00 == Inf<A0>()) return Zero<A0>();\n      #endif\n      A0 a01 =  a00;\n      auto is_den = bs::abs(a00) < Smallestposval<A0>();\n      #ifndef BOOST_SIMD_NO_DENORMALS\n      a01 *= if_else(is_den, Denormalfactor<A0>(), One<A0>());\n      #endif\n      A0 a0 =  raw_(rsqrt)(a01);\n      A0 y = sqr(a0)*a01;\n      a0 = a0*Ratio<A0, 1, 8>()*fnms(y, fnms(A0(3), y, A0(10)), A0(15)); //this is Halley cubically convergent iteration\n      a0 = refine_rsqrt(a00, a0);//this is Newton iteration\n      #ifndef BOOST_SIMD_NO_DENORMALS\n      a0 *= if_else(is_den, Denormalsqrtfactor<A0>(), One<A0>());\n      #endif\n      return a0;\n    }\n  };\n} } }\n\n#endif\n\n", "meta": {"hexsha": "e9ef56b9563c05efb53e5ab37b8ecd451c6c8a6c", "size": 4901, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arch/x86/sse1/scalar/function/rsqrt.hpp", "max_stars_repo_name": "nickporubsky/boost-simd-clone", "max_stars_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_stars_repo_licenses": ["BSL-1.0"], "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": "include/boost/simd/arch/x86/sse1/scalar/function/rsqrt.hpp", "max_issues_repo_name": "nickporubsky/boost-simd-clone", "max_issues_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "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/sse1/scalar/function/rsqrt.hpp", "max_forks_repo_name": "nickporubsky/boost-simd-clone", "max_forks_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_forks_repo_licenses": ["BSL-1.0"], "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": 34.7588652482, "max_line_length": 122, "alphanum_fraction": 0.5264231789, "num_tokens": 1282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4747515618798561}}
{"text": "#ifndef CTCD_HPP\n#define CTCD_HPP 1\n\n#include <Eigen/Geometry>\n#include <vector>\n\nnamespace mcl {\n\n// Source: Etienne Vouga\n// https://github.com/evouga/collisiondetection\n\nstruct TimeInterval\n{\n    TimeInterval(double tl, double tu) : l(tl), u(tu)\n    {\n        if(l > u) std::swap(l, u);\n        l = std::max(l, 0.0);\n        u = std::min(u, 1.0);\n    }\n\n    TimeInterval() : l(0), u(0) {}\n\n    // Returns whether or not the intersection of the intervals is nonempty\n    static bool overlap(const TimeInterval &t1, const TimeInterval &t2);\n    static bool overlap(const std::vector<TimeInterval> &intervals);\n\n    // Returns the intersection of the intervals **asuming the intersection is nonempty**\n    static TimeInterval intersect(const std::vector<TimeInterval> &intervals);\n\n    double l, u;\n};\n\nclass CTCD\n{\npublic:\n    // Looks for collisions between edges (q0start, p0start) and (q1start, p1start) as they move towards\n    // (q0end, p0end) and (q1end, p1end). Returns true if the edges ever come closer than a distance eta to each\n    // other, and stores the earliest time (in the interval [0,1]) at which they do so in t.\n    // WARNING: Does not work correctly if two edges are parallel at the time of intersection -- vertexEdgeCTCD\n    // should catch this case, though.\n    static bool edgeEdgeCTCD(\n\t\tconst Eigen::Vector3d &q0start,\n\t\tconst Eigen::Vector3d &p0start,\n\t\tconst Eigen::Vector3d &q1start,\n\t\tconst Eigen::Vector3d &p1start,\n\t\tconst Eigen::Vector3d &q0end,\n\t\tconst Eigen::Vector3d &p0end,\n\t\tconst Eigen::Vector3d &q1end,\n\t\tconst Eigen::Vector3d &p1end,\n\t\tdouble eta,\n\t\tdouble &t,\n\t\tstd::vector<double> *all_t = nullptr);\n\n    // Looks for collisions between the vertex q0start and the face (q1start, q2start, q3start) as they move\n    // towards q0end and (q1end, q2end, q3end). Returns true if the vertex and face ever come closer than a distance\n    // eta to each, and stores the earliest time (in the interval [0,1]) at which they do so in t.\n    static bool vertexFaceCTCD(const Eigen::Vector3d &q0start,\n                               const Eigen::Vector3d &q1start,\n                               const Eigen::Vector3d &q2start,\n                               const Eigen::Vector3d &q3start,\n                               const Eigen::Vector3d &q0end,\n                               const Eigen::Vector3d &q1end,\n                               const Eigen::Vector3d &q2end,\n                               const Eigen::Vector3d &q3end,\n                               double eta,\n                               double &t,\n\t\t\t\t\t\t\t\tstd::vector<double> *all_t = nullptr);\n\n    // Looks for the degenerate case of collisions between the vertex q0start and the edge (q1start, s2start) as they\n    // move towards q0end and (q1end, q2end). Returns true if the vertex and edge ever come closer than a distance\n    // eta to each other, and stores the earliest time (in the interval [0,1]) at which they do so in t.\n    static bool vertexEdgeCTCD(const Eigen::Vector3d &q0start,\n                              const Eigen::Vector3d &q1start,\n                              const Eigen::Vector3d &q2start,\n                              const Eigen::Vector3d &q0end,\n                              const Eigen::Vector3d &q1end,\n                              const Eigen::Vector3d &q2end,\n                              double eta,\n                              double &t,\n\t\t\t\t\t\t\tstd::vector<double> *all_t = nullptr\n\t\t\t\t\t\t\t);\n\n    static bool vertexEdgeCTCD(const Eigen::Vector2d &q0start,\n                              const Eigen::Vector2d &q1start,\n                              const Eigen::Vector2d &q2start,\n                              const Eigen::Vector2d &q0end,\n                              const Eigen::Vector2d &q1end,\n                              const Eigen::Vector2d &q2end,\n                              double eta,\n                              double &t,\n\t\t\t\t\t\t\t\tstd::vector<double> *all_t = nullptr);\n    // Looks for the degenerate case of collisions between the vertices q1start and q2start, as they move towards\n    // q1end and q2end. Returns true if the vertices ever come closer than a distane of eta to each other, and stores\n    // the earliest time (in the interval [0,1]) at which they do so in t.\n    static bool vertexVertexCTCD(const Eigen::Vector3d &q1start,\n                                const Eigen::Vector3d &q2start,\n                                const Eigen::Vector3d &q1end,\n                                const Eigen::Vector3d &q2end,\n                                double eta, double &t,\n\t\t\t\t\t\t\t\tstd::vector<double> *all_t = nullptr);\n    static bool vertexVertexCTCD(const Eigen::Vector2d &q1start,\n                                const Eigen::Vector2d &q2start,\n                                const Eigen::Vector2d &q1end,\n                                const Eigen::Vector2d &q2end,\n                                double eta, double &t,\n\t\t\t\t\t\t\t\tstd::vector<double> *all_t = nullptr);\n\nprivate:\n    // Solves the quadratic equation ax^2 + bx + c = 0, and puts the roots in t0, t1, in ascending order.\n    // Returns the number of real roots found.\n    static int getQuadRoots(double a, double b, double c, double &t0, double &t1);\n\n    // Conservatively checks if the polynomial of degree degree, with coefficients op, could be positive (if pos is true)\n    // or negative (if pos is negative) on the interval [0,1].\n    static bool couldHaveRoots(double *op, int degree, bool pos);\n\n    // Looks at the interval [t1, t2], on which a polynomial of degree degree and coefficients op is assumed to have\n    // constant sign, and determines if the polynomial is all positive or all negative on that interval.\n    // If positive, and pos is true, or if negative, and pos is false, clamps the interval to [0,1] and adds it to\n    // intervals.\n    static void checkInterval(double t1, double t2, double * op, int degree, std::vector<TimeInterval> &intervals, bool pos);\n\n    // Computes the intervals of x in [0,1] where the polynomial of degree n, with coefficients in op\n    // (given in \"natural,\" descending order of power of x) is positive (when pos = true) or negative (if pos = false).\n    static void findIntervals(double *op, int n, std::vector<TimeInterval> & intervals, bool pos);\n\n    static void distancePoly3D(const Eigen::Vector3d &x10,\n                               const Eigen::Vector3d &x20,\n                               const Eigen::Vector3d &x30,\n                               const Eigen::Vector3d &v10,\n                               const Eigen::Vector3d &v20,\n                               const Eigen::Vector3d &v30,\n                               double minDSquared,\n                               std::vector<TimeInterval> &result);\n\n    static void barycentricPoly3D(const Eigen::Vector3d &x10,\n                                  const Eigen::Vector3d &x20,\n                                  const Eigen::Vector3d &x30,\n                                  const Eigen::Vector3d &v10,\n                                  const Eigen::Vector3d &v20,\n                                  const Eigen::Vector3d &v30,\n                                  std::vector<TimeInterval> &result);\n\n    static void planePoly3D(const Eigen::Vector3d &x10,\n                            const Eigen::Vector3d &x20,\n                            const Eigen::Vector3d &x30,\n                            const Eigen::Vector3d &v10,\n                            const Eigen::Vector3d &v20,\n                            const Eigen::Vector3d &v30,\n                            std::vector<TimeInterval> &result);\n\n};\n\n} // namespace mcl\n\n#endif", "meta": {"hexsha": "1b8a1232e44d1199e6b89783dcea7b2a3859b63d", "size": 7610, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/MCL/ccd_internal/CTCD.hpp", "max_stars_repo_name": "mattoverby/mclccd", "max_stars_repo_head_hexsha": "2137e4edee822c62c4aa5485cb83d7f8191c950c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/MCL/ccd_internal/CTCD.hpp", "max_issues_repo_name": "mattoverby/mclccd", "max_issues_repo_head_hexsha": "2137e4edee822c62c4aa5485cb83d7f8191c950c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/MCL/ccd_internal/CTCD.hpp", "max_forks_repo_name": "mattoverby/mclccd", "max_forks_repo_head_hexsha": "2137e4edee822c62c4aa5485cb83d7f8191c950c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.7820512821, "max_line_length": 125, "alphanum_fraction": 0.5700394218, "num_tokens": 1798, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4747515618798561}}
{"text": "#include \"subdiv_evaluator.h\"\n#include \"mesh.h\"\n\n#include <opensubdiv/far/topologyRefiner.h>\n#include <opensubdiv/far/topologyDescriptor.h>\n#include <opensubdiv/far/primvarRefiner.h>\n#include <opensubdiv/far/stencilTable.h>\n#include <opensubdiv/far/patchTableFactory.h>\n#include <opensubdiv/far/patchMap.h>\n\n#include <Eigen/Eigen>\n\n#include <vector>\n#include <random>\n\nusing namespace OpenSubdiv;\nusing namespace Eigen;\n\nstd::vector<SurfacePoint> SurfacePoint::generate(const int n_points, const int n_triangles)\n{\n    std::vector<SurfacePoint> sps(n_points);\n\n    std::mt19937 random_generator(1);\n    std::uniform_real_distribution dist_u(0.0, 1.0);\n    std::uniform_real_distribution dist_v(0.0, 1.0);\n    std::uniform_int_distribution dist_face(0, n_triangles-1);\n    for (int i{0}; i < n_points; ++i)\n    {\n        // generate random u,v\n        double u = dist_u(random_generator);\n        double v = dist_v(random_generator);\n        if ((u+v) > 1)\n        {\n            u = 1 - u;\n            v = 1 - v;\n        }\n\n        sps[i].u << u, v;\n        sps[i].face = dist_face(random_generator);\n    }\n\n    return sps;\n}\n\n\nSubdivEvaluator::SubdivEvaluator(const Mesh &mesh)\n{\n    using Refiner_t = Far::TopologyRefinerFactory<Far::TopologyDescriptor>;\n    \n    n_vertices = mesh.n_vertices();\n\n    // create refiner using descriptor\n    Far::TopologyDescriptor desc;\n    desc.numVertices = n_vertices;\n    desc.numFaces = mesh.n_triangles();\n    std::vector<int> num_verts_per_face(mesh.n_triangles(), 3);\n    desc.numVertsPerFace = num_verts_per_face.data();\n    desc.vertIndicesPerFace = &mesh.triangles()[0](0);\n    // desc.vertIndicesPerFace = &topo.triangles[0](0);\n\n    Sdc::SchemeType type = Sdc::SCHEME_LOOP;\n    Sdc::Options options;\n    options.SetVtxBoundaryInterpolation(Sdc::Options::VTX_BOUNDARY_NONE);\n    Far::TopologyRefiner *refiner_for_patch_table = Refiner_t::Create(desc, Refiner_t::Options(type, options));\n\n    // refine topology (adaptive takes care of irregular vertices)\n    const int max_isolation = 0; // do not change this!\n    refiner_for_patch_table->RefineAdaptive(Far::TopologyRefiner::AdaptiveOptions(max_isolation));\n\n    // generate PatchTable that will be used to evaluate surface limit\n    Far::PatchTableFactory::Options patch_options;\n    patch_options.endCapType = Far::PatchTableFactory::Options::ENDCAP_BSPLINE_BASIS;\n    patch_table = Far::PatchTableFactory::Create(*refiner_for_patch_table, patch_options);\n\n    // compute total number of points needed to evaluate patch table\n    // use local points around irregular vertices\n    n_refiner_vertices = refiner_for_patch_table->GetNumVerticesTotal();\n    n_local_points = patch_table->GetNumLocalPoints();\n\n    // create a buffer to hold the position of the refined verts and local points\n    evaluation_verts_buffer.resize(n_refiner_vertices + n_local_points);\n\n    // refiner for subdividing mesh\n    refiner = Refiner_t::Create(desc, Refiner_t::Options(type, options));\n\n    // uniformly refine topology up to maxlevel\n    refiner->RefineUniform(Far::TopologyRefiner::UniformOptions(maxlevel));\n\n    delete refiner_for_patch_table;\n}\n\nstd::shared_ptr<Mesh> SubdivEvaluator::generate_refined_mesh(const std::vector<Vector3d> &coarse_verts, int level)\n{\n    // Reference: http://graphics.pixar.com/opensubdiv/docs/far_tutorial_1_1.html\n\n    // allocate buffer for vertex primvar data.\n    // length = sum of vertices at all levels\n    std::vector<OSDVertex> vbuffer(refiner->GetNumVerticesTotal());\n    OSDVertex *verts{&vbuffer[0]}; // this interface is used for filling up\n\n    // copy coarse mesh positions\n    for (int i{0}; i < coarse_verts.size(); ++i)\n    {\n        verts[i].point = coarse_verts[i];\n    }\n    // use primar refiner for filling other levels using interpolation\n    Far::PrimvarRefiner primvar_refiner(*refiner);\n    // Note: previous level verts are used for next level interpolation\n    OSDVertex *src = verts;\n    for (int l{1}; l <= level; ++l)\n    {\n        OSDVertex *dst = src + refiner->GetLevel(l - 1).GetNumVertices();\n        primvar_refiner.Interpolate(l, src, dst);\n        src = dst;\n    }\n    // src will point to vertices at `level` interpolation after end of above loop\n\n    std::shared_ptr<Mesh> mesh_refined = std::make_shared<Mesh>();\n\n    // extract refined vertices\n    const Far::TopologyLevel &ref_level = refiner->GetLevel(level);\n    int n_verts_out = ref_level.GetNumVertices();\n    mesh_refined->vertices().resize(n_verts_out);\n    for (int v{0}; v < n_verts_out; ++v)\n    {\n        mesh_refined->vertices()[v] = src[v].point;\n    }\n\n    // extract refined faces into out topo\n    int n_faces = ref_level.GetNumFaces();\n    mesh_refined->triangles().resize(n_faces);\n    for (int f{0}; f < n_faces; ++f)\n    {\n        Far::ConstIndexArray face_vert_ids = ref_level.GetFaceVertices(f);\n        for (int v{0}; v < face_vert_ids.size(); ++v)\n        {\n            mesh_refined->triangles()[f](v) = face_vert_ids[v];\n        }\n    }\n\n    mesh_refined->update_adjacencies();\n\n    return mesh_refined;\n}\n\nvoid SubdivEvaluator::evaluate_subdiv_surface(const std::vector<Vector3d> &coarse_verts, const std::vector<SurfacePoint> &uvs,\n                                              SurfaceFeatures &sf, const bool compute_dX) const\n{\n    // compute local points from coarse verts\n    // 263 - 269\n    for (int i{0}; i < n_vertices; ++i)\n        evaluation_verts_buffer[i].point = coarse_verts[i];\n    int n_stencils = patch_table->GetLocalPointStencilTable()->GetNumStencils();\n    patch_table->ComputeLocalPointValues(&evaluation_verts_buffer[0], &evaluation_verts_buffer[n_refiner_vertices]);\n\n    // get all stencils from patch table\n    // (necesary to obtain the weights for the gradients)\n    // 273 - 289\n    const Far::StencilTable *stencil_table = patch_table->GetLocalPointStencilTable();\n    std::vector<Far::Stencil> stencils(n_stencils);\n    for (int i{0}; i < n_stencils; ++i)\n    {\n        stencils[i] = stencil_table->GetStencil(Far::Index(i));\n    }\n\n    // create PatchMap to locate patches in the table\n    // 292\n    Far::PatchMap patch_map(*patch_table);\n\n    // zero output\n    sf.set_zero();\n\n    // evaluate surface at uvs\n    // 326 - 412\n    for (int i{0}; i < uvs.size(); ++i)\n    {\n        // locate patch corresponding to uv\n        // 327 - 332\n        int face = uvs[i].face;\n        double u = uvs[i].u[0];\n        double v = uvs[i].u[1];\n        const Far::PatchTable::PatchHandle *patch_handle = patch_map.FindPatch(face, u, v);\n\n        // evaluate patch weights\n        // 336 - 337\n        patch_table->EvaluateBasis(*patch_handle, u, v, sf.p_weights, sf.du_weights, sf.dv_weights);\n\n        // identify control vertices corresponding to this patch\n        // 339\n        Far::ConstIndexArray cvs = patch_table->GetPatchVertices(*patch_handle);\n\n        // for each control vertex\n        // 340 - 411\n        for (int cv1{0}; cv1 < cvs.size(); ++cv1)\n        {\n            // fill surface features by corresponding weighted combination of control vertices\n            // 341 - 349\n            sf.update(evaluation_verts_buffer[cvs[cv1]].point, i, cv1);\n\n            // compute normals at uv on surface\n            // 351 - 357\n            // done at end\n            // Note: derivative wrt normal is not implemented\n\n            // compute derivative wrt control vertices\n            // 362 - 410\n            if (!compute_dX) continue;\n\n            MatrixXd accumulated_weights(3, n_vertices);\n            accumulated_weights.setZero();\n            std::vector<bool> has_nonzero_weight(n_vertices, false);\n            for (int cv2{0}; cv2 < cvs.size(); ++cv2)\n            {\n                if (cvs[cv2] < n_vertices)  // regular vertex\n                {\n                    int c{0};\n                    accumulated_weights(c++, cvs[cv2]) += sf.p_weights[cv2];\n                    accumulated_weights(c++, cvs[cv2]) += sf.du_weights[cv2];\n                    accumulated_weights(c++, cvs[cv2]) += sf.dv_weights[cv2];\n                    has_nonzero_weight[cv2] = true;\n                }\n                else  // local point\n                {\n                    int idx_offset = cvs[cv2] - n_vertices;\n                    // look at the stencil associated with this local point and distribute its weight over the control vertices\n                    const Far::Index *stencil_idx = stencils[idx_offset].GetVertexIndices();\n                    const float *stencil_weights = stencils[idx_offset].GetWeights();\n                    for (int s{0}; s < stencils[idx_offset].GetSize(); ++s)\n                    {\n                        int c{0};\n                        accumulated_weights(c++, stencil_idx[s]) += sf.p_weights[cv2] * stencil_weights[s];\n                        accumulated_weights(c++, stencil_idx[s]) += sf.du_weights[cv2] * stencil_weights[s];\n                        accumulated_weights(c++, stencil_idx[s]) += sf.dv_weights[cv2] * stencil_weights[s];\n                        has_nonzero_weight[stencil_idx[s]] = true;\n                    }\n                }\n            }\n\n            // store the weights\n            float scale = 1.f / cvs.size();\n            for (int cv3{0}; cv3 < n_vertices; ++cv3)\n            {\n                if(has_nonzero_weight[cv3])\n                {\n                    int c{0};\n                    sf.dSdX.add(i, cv3, accumulated_weights(c++, cv3)*scale);\n                    sf.dSudX.add(i, cv3, accumulated_weights(c++, cv3)*scale);\n                    sf.dSvdX.add(i, cv3, accumulated_weights(c++, cv3)*scale);\n                }\n            }\n        }\n    }\n    \n    sf.compute_normal();\n}", "meta": {"hexsha": "c9105a8ea8343980334b90fe4bd8e159541b7b54", "size": 9618, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/subdiv_evaluator.cpp", "max_stars_repo_name": "pmkalshetti/parametric_sphere_fitting", "max_stars_repo_head_hexsha": "1d86a18a997ecbc6ab4234c9550db1cc6c707b42", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-10-26T07:50:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T00:41:14.000Z", "max_issues_repo_path": "src/subdiv_evaluator.cpp", "max_issues_repo_name": "pmkalshetti/parametric_sphere_fitting", "max_issues_repo_head_hexsha": "1d86a18a997ecbc6ab4234c9550db1cc6c707b42", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/subdiv_evaluator.cpp", "max_forks_repo_name": "pmkalshetti/parametric_sphere_fitting", "max_forks_repo_head_hexsha": "1d86a18a997ecbc6ab4234c9550db1cc6c707b42", "max_forks_repo_licenses": ["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.7176470588, "max_line_length": 127, "alphanum_fraction": 0.6239342899, "num_tokens": 2401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390746, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.47475156187985607}}
{"text": "/*\n * Software License Agreement (BSD License)\n *\n *  Copyright (c) 2020, Clearpath Robotics\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions\n *  are met:\n *\n *   * Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *   * Redistributions in binary form must reproduce the above\n *     copyright notice, this list of conditions and the following\n *     disclaimer in the documentation and/or other materials provided\n *     with the distribution.\n *   * Neither the name of the copyright holder 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 (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#include <fuse_constraints/normal_prior_pose_2d.h>\n#include <fuse_core/util.h>\n\n#include <Eigen/Core>\n#include <glog/logging.h>\n\n\nnamespace fuse_constraints\n{\n\nNormalPriorPose2D::NormalPriorPose2D(const fuse_core::MatrixXd& A, const fuse_core::Vector3d& b) :\n  A_(A),\n  b_(b)\n{\n  CHECK_GT(A_.rows(), 0);\n  CHECK_EQ(A_.cols(), 3);\n  set_num_residuals(A_.rows());\n}\n\nbool NormalPriorPose2D::Evaluate(\n  double const* const* parameters,\n  double* residuals,\n  double** jacobians) const\n{\n  fuse_core::Vector3d full_residuals_vector;\n  full_residuals_vector[0] = parameters[0][0] - b_[0];  // position x\n  full_residuals_vector[1] = parameters[0][1] - b_[1];  // position y\n  full_residuals_vector[2] = fuse_core::wrapAngle2D(parameters[1][0] - b_[2]);  // orientation\n\n  // Scale the residuals by the square root information matrix to account for the measurement uncertainty.\n  Eigen::Map<fuse_core::VectorXd> residuals_vector(residuals, num_residuals());\n  residuals_vector = A_ * full_residuals_vector;\n\n  if (jacobians != nullptr)\n  {\n    // Jacobian wrt position\n    if (jacobians[0] != nullptr)\n    {\n      Eigen::Map<fuse_core::MatrixXd>(jacobians[0], num_residuals(), 2) = A_.leftCols<2>();\n    }\n\n    // Jacobian wrt orientation\n    if (jacobians[1] != nullptr)\n    {\n      Eigen::Map<fuse_core::VectorXd>(jacobians[1], num_residuals()) = A_.col(2);\n    }\n  }\n  return true;\n}\n\n}  // namespace fuse_constraints\n", "meta": {"hexsha": "d69f71381b80e48fc3ffdf2f7a267a568005f074", "size": 3085, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "fuse_constraints/src/normal_prior_pose_2d.cpp", "max_stars_repo_name": "mcx/fuse", "max_stars_repo_head_hexsha": "3825e489ceaba394fb07c87e0e52dce9485da19b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 383.0, "max_stars_repo_stars_event_min_datetime": "2018-07-02T07:20:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:51:06.000Z", "max_issues_repo_path": "fuse_constraints/src/normal_prior_pose_2d.cpp", "max_issues_repo_name": "mcx/fuse", "max_issues_repo_head_hexsha": "3825e489ceaba394fb07c87e0e52dce9485da19b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 117.0, "max_issues_repo_issues_event_min_datetime": "2018-07-16T10:32:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-02T20:15:16.000Z", "max_forks_repo_path": "fuse_constraints/src/normal_prior_pose_2d.cpp", "max_forks_repo_name": "BrettRD/fuse", "max_forks_repo_head_hexsha": "c8481b3b1eb01e855f341187b9f1f88d4d58acc2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 74.0, "max_forks_repo_forks_event_min_datetime": "2018-10-01T10:10:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T04:48:22.000Z", "avg_line_length": 36.2941176471, "max_line_length": 106, "alphanum_fraction": 0.7244732577, "num_tokens": 763, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426303, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4747515554236207}}
{"text": "/*\n * optimize_tnc.cpp\n *\n *  Created on: Feb 9, 2010\n *      Author: smitty\n */\n\n#include <iostream>\n#include <stdio.h>\n#include <nlopt.hpp>\n#include <math.h>\n\n#include \"cont_models.h\"\n\n#include <armadillo>\nusing namespace arma;\n\n#define LARGE 1000000000\n\ntypedef struct {\n    rowvec x;\n    mat ovcv;\n} analysis_data;\n\ntypedef struct {\n    Tree * tree;\n} analysis_data_tree;\n\ndouble nlopt_bm_sr(unsigned n, const double *x, double *grad, void *data) {\n    if (x[1] <= 0) {\n        return LARGE;\n    }\n    //cout << x[0] << \" \" << x[1] << endl;\n    analysis_data * d = (analysis_data *) data;\n    mat tvcv = (d->ovcv) * x[1];\n    rowvec m = rowvec(d->x.n_cols); m.fill(x[0]);\n    double like = norm_pdf_multivariate(d->x, m, tvcv);\n    return -like;\n}\n\ndouble nlopt_bm_sr_log(unsigned n, const double *x, double *grad, void *data) {\n    if (x[1] <= 0) {\n        return LARGE;\n    }\n    //cout << x[0] << \" \" << x[1] << endl;\n    analysis_data * d = (analysis_data *) data;\n    mat tvcv = (d->ovcv) * x[1];\n    rowvec m = rowvec(d->x.n_cols); m.fill(x[0]);\n    double like = norm_log_pdf_multivariate(d->x, m, tvcv);\n    return -like;\n}\n\n/*\n * single alpha ou\n */\ndouble nlopt_ou_sr_log(unsigned n, const double *x, double *grad, void *data) {\n    if (x[1] <= 0 || x[2] <= 0) {\n        return LARGE;\n    }\n    double alpha = x[2];\n    analysis_data * d = (analysis_data *) data;\n    mat vcvDiag(d->ovcv.n_cols,d->ovcv.n_cols); vcvDiag.zeros(); \n    vcvDiag.diag() = (d->ovcv).diag();\n    mat tm(vcvDiag.n_cols,vcvDiag.n_cols);\n    tm.ones();\n    mat diagi = trans(vcvDiag * tm);\n    mat diagj = vcvDiag * tm;\n    mat Tij = diagi + diagj - (2 * d->ovcv);\n    mat ouvcv = (1. / (2. * alpha)) * exp(-alpha * Tij) % (1. - exp(-2. * alpha * d->ovcv));\n    ouvcv = ouvcv * x[1];\n    rowvec m = rowvec(d->x.n_cols); m.fill(x[0]);\n    double like = norm_log_pdf_multivariate(d->x,m,ouvcv);\n    return -like;\n}\n\n\ndouble nlopt_bm_bl(unsigned n, const double *x, double *grad, void *data){\n    for (unsigned int i=0;i<n;i++){\n        if (x[i] <= 0){\n            return LARGE;\n        }   \n    }\n    double sigma =1;// x[0];//1;\n    analysis_data_tree * d = (analysis_data_tree *) data;\n    Tree * tr = d->tree;\n    for (int i=0;i<tr->getNodeCount();i++){\n        if (tr->getNode(i) != tr->getRoot()){\n            tr->getNode(i)->setBL(x[i+1]);\n        }\n    }\n    double like = calc_bm_prune(tr,sigma);\n    //cout << like <<\" \" << sigma << endl;\n    return -like;\n}\n\nvector<double> optimize_single_rate_bm_nlopt(rowvec & _x, mat & _vcv, bool log) {\n    analysis_data a;\n    a.x = _x;\n    a.ovcv = _vcv;\n\n    //nlopt::opt opt(nlopt::LN_NELDERMEAD, 2);\n    //nlopt::opt opt(nlopt::LN_BOBYQA,2);\n    //BOBYQA is better but the other finishes more\n    nlopt::opt opt(nlopt::LN_SBPLX, 2);\n    //nlopt::opt opt(nlopt::LN_PRAXIS,2);\n\n    opt.set_lower_bounds(0.000000001);\n    opt.set_upper_bounds(100000);\n    opt.set_ftol_abs(0.000001);\n    if (log) {\n        opt.set_min_objective(nlopt_bm_sr_log, &a);\n    } else {\n        opt.set_min_objective(nlopt_bm_sr, &a);\n    }\n    opt.set_xtol_rel(0.000001);\n    opt.set_maxeval(5000);\n\n    double minf;\n    //2 parameters, 1 anc, 2 rate\n    vector<double> x(2,1);\n    nlopt::result result = opt.optimize(x, minf);\n    vector<double> results;\n    results.push_back(x[0]);\n    results.push_back(x[1]);\n    results.push_back(minf);\n    return results;\n}\n\nvector<double> optimize_single_rate_bm_ou_nlopt(rowvec & _x, mat & _vcv) {\n    analysis_data a;\n    a.x = _x;\n    a.ovcv = _vcv;\n\n    //nlopt::opt opt(nlopt::LN_NELDERMEAD, 3);\n    //BOBYQA is better but the other finishes more\n    //nlopt::opt opt(nlopt::LN_BOBYQA,3);\n    nlopt::opt opt(nlopt::LN_SBPLX, 3);\n    //nlopt::opt opt(nlopt::LN_PRAXIS,3);\n    opt.set_min_objective(nlopt_ou_sr_log, &a);\n    opt.set_lower_bounds(0.000000001);\n    opt.set_upper_bounds(100000);\n    opt.set_xtol_rel(0.000001);\n    opt.set_ftol_rel(0.00001);\n    opt.set_maxeval(5000);\n    double minf;\n    //2 parameters, 1 anc, 2 rate, 3 alpha\n    vector<double> x(3, 1);\n    nlopt::result result = opt.optimize(x, minf);\n//    cout << result << endl;\n    vector<double> results;\n    results.push_back(x[0]); results.push_back(x[1]); results.push_back(x[2]);\n    results.push_back(minf);\n    return results;\n}\n\nvector<double> optimize_single_rate_bm_bl(Tree * tr) {\n    analysis_data_tree a;\n    a.tree = tr;\n    int n = 1+tr->getNodeCount() - 1;\n    //nlopt::opt opt(nlopt::LN_NELDERMEAD, n);\n    //BOBYQA is better but the other finishes more\n    //nlopt::opt opt(nlopt::LN_BOBYQA,n);\n    nlopt::opt opt(nlopt::LN_SBPLX,n);\n    //nlopt::opt opt(nlopt::LN_COBYLA,n);\n    //nlopt::opt opt(nlopt::LN_PRAXIS,n);\n    opt.set_min_objective(nlopt_bm_bl, &a);\n    opt.set_lower_bounds(0.0001);\n    opt.set_upper_bounds(100000);\n    opt.set_xtol_rel(0.000001);\n    opt.set_ftol_rel(0.000001);\n    opt.set_maxeval(100000);\n    double minf;\n    vector<double> x(n, 1);\n    nlopt::result result = opt.optimize(x, minf);\n    cout << result << endl;\n    vector<double> results;\n    for (int i=0;i<tr->getNodeCount();i++){\n        if (tr->getNode(i) != tr->getRoot()){\n            tr->getNode(i)->setBL(x[i+1]);\n        }\n    }\n    results.push_back(x[0]); \n    results.push_back(minf);\n    return results;\n}\n\n\n", "meta": {"hexsha": "0bc95d04d246c657dbc571ae3f2f36eb929d2621", "size": 5257, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/phyx-1.01/src/optimize_cont_models_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_cont_models_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_cont_models_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": 27.9627659574, "max_line_length": 92, "alphanum_fraction": 0.6026250713, "num_tokens": 1757, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.47475155542362063}}
{"text": "\n\n/* --------------------------------------------------------------------- \n * \n * Copyright (C) 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: Jean-Paul Pelteret, 2021 \n */ \n\n\n\n// \u6211\u4eec\u9996\u5148\u5305\u62ec\u6240\u6709\u5fc5\u8981\u7684deal.II\u5934\u6587\u4ef6\u548c\u4e00\u4e9bC++\u76f8\u5173\u7684\u6587\u4ef6\u3002\u8fd9\u7b2c\u4e00\u4e2a\u5934\u6587\u4ef6\u5c06\u4f7f\u6211\u4eec\u80fd\u591f\u8bbf\u95ee\u4e00\u4e2a\u6570\u636e\u7ed3\u6784\uff0c\u4f7f\u6211\u4eec\u80fd\u591f\u5728\u5176\u4e2d\u5b58\u50a8\u4efb\u610f\u7684\u6570\u636e\u3002\n\n#include <deal.II/algorithms/general_data_storage.h> \n\n// \u63a5\u4e0b\u6765\u662f\u4e00\u4e9b\u6838\u5fc3\u7c7b\uff0c\u5305\u62ec\u4e00\u4e2a\u63d0\u4f9b\u65f6\u95f4\u6b65\u8fdb\u7684\u5b9e\u73b0\u3002\n\n#include <deal.II/base/discrete_time.h> \n#include <deal.II/base/numbers.h> \n#include <deal.II/base/parameter_acceptor.h> \n#include <deal.II/base/symmetric_tensor.h> \n#include <deal.II/base/tensor.h> \n#include <deal.II/base/timer.h> \n#include <deal.II/base/utilities.h> \n\n// \u7136\u540e\u662f\u4e00\u4e9b\u6807\u9898\uff0c\u5b9a\u4e49\u4e86\u4e00\u4e9b\u6709\u7528\u7684\u5750\u6807\u53d8\u6362\u548c\u8fd0\u52a8\u5b66\u5173\u7cfb\uff0c\u8fd9\u4e9b\u5173\u7cfb\u5728\u975e\u7ebf\u6027\u5f39\u6027\u4e2d\u7ecf\u5e38\u51fa\u73b0\u3002\n\n#include <deal.II/physics/transformations.h> \n#include <deal.II/physics/elasticity/kinematics.h> \n#include <deal.II/physics/elasticity/standard_tensors.h> \n\n// \u4e0b\u9762\u4e24\u4e2a\u6807\u5934\u63d0\u4f9b\u4e86\u6211\u4eec\u8fdb\u884c\u81ea\u52a8\u5fae\u5206\u6240\u9700\u7684\u6240\u6709\u529f\u80fd\uff0c\u5e76\u4f7f\u7528deal.II\u53ef\u4ee5\u5229\u7528\u7684\u7b26\u53f7\u8ba1\u7b97\u673a\u4ee3\u6570\u7cfb\u7edf\u3002\u6240\u6709\u81ea\u52a8\u5fae\u5206\u548c\u7b26\u53f7\u5fae\u5206\u5c01\u88c5\u7c7b\u7684\u5934\u6587\u4ef6\uff0c\u4ee5\u53ca\u4efb\u4f55\u9700\u8981\u7684\u8f85\u52a9\u6570\u636e\u7ed3\u6784\uff0c\u90fd\u88ab\u6536\u96c6\u5728\u8fd9\u4e9b\u7edf\u4e00\u7684\u5934\u6587\u4ef6\u4e2d\u3002\n\n#include <deal.II/differentiation/ad.h> \n#include <deal.II/differentiation/sd.h> \n\n// \u5305\u62ec\u8fd9\u4e2a\u5934\u6587\u4ef6\u4f7f\u6211\u4eec\u6709\u80fd\u529b\u5c06\u8f93\u51fa\u5199\u5165\u6587\u4ef6\u6d41\u4e2d\u3002\n\n#include <fstream> \n\n// \u6309\u7167\u60ef\u4f8b\uff0c\u6574\u4e2a\u6559\u7a0b\u7a0b\u5e8f\u88ab\u5b9a\u4e49\u5728\u5b83\u81ea\u5df1\u72ec\u7279\u7684\u547d\u540d\u7a7a\u95f4\u4e2d\u3002\n\nnamespace Step71 \n{ \n  using namespace dealii; \n// @sect3{An introductory example: The fundamentals of automatic and symbolic differentiation}  \n\n// \u81ea\u52a8\u548c\u8c61\u5f81\u6027\u7684\u533a\u5206\u6709\u4e00\u4e9b\u795e\u5947\u548c\u795e\u79d8\u7684\u7279\u8d28\u3002\u5c3d\u7ba1\u5728\u4e00\u4e2a\u9879\u76ee\u4e2d\u4f7f\u7528\u5b83\u4eec\u4f1a\u56e0\u591a\u79cd\u539f\u56e0\u800c\u53d7\u76ca\uff0c\u4f46\u4e86\u89e3\u5982\u4f55\u4f7f\u7528\u8fd9\u4e9b\u6846\u67b6\u6216\u5982\u4f55\u5229\u7528\u5b83\u4eec\u7684\u969c\u788d\u53ef\u80fd\u4f1a\u8d85\u8fc7\u8bd5\u56fe\u5c06\u5b83\u4eec\uff08\u53ef\u9760\u5730\uff09\u6574\u5408\u5230\u5de5\u4f5c\u4e2d\u7684\u5f00\u53d1\u8005\u7684\u8010\u5fc3\u3002\n\n// \u5c3d\u7ba1\u4f5c\u8005\u5e0c\u671b\u80fd\u591f\u6210\u529f\u5730\u8bf4\u660e\u8fd9\u4e9b\u5de5\u5177\u662f\u5982\u4f55\u88ab\u6574\u5408\u5230\u6709\u9650\u5143\u5efa\u6a21\u7684\u5de5\u4f5c\u6d41\u7a0b\u4e2d\u7684\uff0c\u4f46\u6700\u597d\u8fd8\u662f\u5148\u9000\u4e00\u6b65\uff0c\u4ece\u57fa\u7840\u5f00\u59cb\u3002\u56e0\u6b64\uff0c\u4e00\u5f00\u59cb\uff0c\u6211\u4eec\u5148\u770b\u770b\u5982\u4f55\u4f7f\u7528\u8fd9\u4e24\u4e2a\u6846\u67b6\u6765\u533a\u5206\u4e00\u4e2a \"\u7b80\u5355 \"\u7684\u6570\u5b66\u51fd\u6570\uff0c\u8fd9\u6837\u5c31\u53ef\u4ee5\u7262\u56fa\u5730\u5efa\u7acb\u548c\u7406\u89e3\u57fa\u672c\u7684\u64cd\u4f5c\uff08\u5305\u62ec\u5b83\u4eec\u7684\u987a\u5e8f\u548c\u529f\u80fd\uff09\uff0c\u5e76\u4f7f\u5176\u590d\u6742\u7a0b\u5ea6\u964d\u5230\u6700\u4f4e\u3002\u5728\u672c\u6559\u7a0b\u7684\u7b2c\u4e8c\u90e8\u5206\uff0c\u6211\u4eec\u5c06\u628a\u8fd9\u4e9b\u57fa\u672c\u539f\u7406\u4ed8\u8bf8\u5b9e\u8df5\uff0c\u5e76\u5728\u6b64\u57fa\u7840\u4e0a\u8fdb\u4e00\u6b65\u53d1\u5c55\u3002\n\n// \u4f34\u968f\u7740\u5bf9\u4f7f\u7528\u6846\u67b6\u7684\u7b97\u6cd5\u6b65\u9aa4\u7684\u63cf\u8ff0\uff0c\u6211\u4eec\u5c06\u5bf9\u5b83\u4eec*\u53ef\u80fd\u5728\u540e\u53f0\u505a\u7684\u4e8b\u60c5\u6709\u4e00\u4e2a\u7b80\u5316\u7684\u770b\u6cd5\u3002\u8fd9\u79cd\u63cf\u8ff0\u5728\u5f88\u5927\u7a0b\u5ea6\u4e0a\u662f\u4e3a\u4e86\u5e2e\u52a9\u7406\u89e3\uff0c\u6211\u4eec\u9f13\u52b1\u8bfb\u8005\u67e5\u770b @ref auto_symb_diff \u6a21\u5757\u6587\u6863\uff0c\u4ee5\u83b7\u5f97\u5bf9\u8fd9\u4e9b\u5de5\u5177\u5b9e\u9645\u5de5\u4f5c\u7684\u66f4\u6b63\u5f0f\u63cf\u8ff0\u3002\n\n//  @sect4{An analytical function}  \n  namespace SimpleExample \n  { \n\n// \u4e3a\u4e86\u8ba9\u8bfb\u8005\u76f8\u4fe1\u8fd9\u4e9b\u5de5\u5177\u5728\u5b9e\u8df5\u4e2d\u786e\u5b9e\u6709\u7528\uff0c\u8ba9\u6211\u4eec\u9009\u62e9\u4e00\u4e2a\u51fd\u6570\uff0c\u7528\u624b\u8ba1\u7b97\u5206\u6790\u5bfc\u6570\u5e76\u4e0d\u96be\u3002\u53ea\u662f\u5b83\u7684\u590d\u6742\u7a0b\u5ea6\u8db3\u4ee5\u8ba9\u4f60\u8003\u8651\u662f\u5426\u771f\u7684\u8981\u53bb\u505a\u8fd9\u4e2a\u7ec3\u4e60\uff0c\u4e5f\u53ef\u80fd\u8ba9\u4f60\u6000\u7591\u4f60\u662f\u5426\u5b8c\u5168\u786e\u5b9a\u4f60\u5bf9\u5176\u5bfc\u6570\u7684\u8ba1\u7b97\u548c\u5b9e\u73b0\u662f\u6b63\u786e\u7684\u3002\u5f53\u7136\uff0c\u95ee\u9898\u7684\u5173\u952e\u5728\u4e8e\uff0c\u51fd\u6570\u7684\u5fae\u5206\u5728\u67d0\u79cd\u610f\u4e49\u4e0a\u662f\u76f8\u5bf9\u516c\u5f0f\u5316\u7684\uff0c\u5e94\u8be5\u662f\u8ba1\u7b97\u673a\u64c5\u957f\u7684\u4e8b\u60c5--\u5982\u679c\u6211\u4eec\u80fd\u5728\u73b0\u6709\u7684\u8f6f\u4ef6\u57fa\u7840\u4e0a\u7406\u89e3\u8fd9\u4e9b\u89c4\u5219\uff0c\u6211\u4eec\u5c31\u4e0d\u5fc5\u8d39\u529b\u5730\u81ea\u5df1\u505a\u4e86\u3002\n\n// \u6211\u4eec\u4e3a\u6b64\u9009\u62e9\u4e86\u53cc\u53d8\u91cf\u4e09\u89d2\u51fd\u6570 $f(x,y) = \\cos\\left(\\frac{y}{x}\\right)$ \u3002\u6ce8\u610f\uff0c\u8fd9\u4e2a\u51fd\u6570\u662f\u4ee5\u6570\u5b57\u7c7b\u578b\u4e3a\u6a21\u677f\u7684\u3002\u8fd9\u6837\u505a\u662f\u56e0\u4e3a\u6211\u4eec\u7ecf\u5e38\uff08\u4f46\u4e0d\u603b\u662f\uff09\u53ef\u4ee5\u4f7f\u7528\u7279\u6b8a\u7684\u81ea\u52a8\u5fae\u5206\u548c\u7b26\u53f7\u7c7b\u578b\u6765\u66ff\u4ee3\u5b9e\u6570\u6216\u590d\u6570\u7c7b\u578b\uff0c\u7136\u540e\u8fd9\u4e9b\u7c7b\u578b\u5c06\u6267\u884c\u4e00\u4e9b\u57fa\u672c\u7684\u8ba1\u7b97\uff0c\u4f8b\u5982\u8bc4\u4f30\u4e00\u4e2a\u51fd\u6570\u503c\u53ca\u5176\u5bfc\u6570\u3002\u6211\u4eec\u5c06\u5229\u7528\u8fd9\u4e00\u7279\u6027\uff0c\u786e\u4fdd\u6211\u4eec\u53ea\u9700\u8981\u5b9a\u4e49\u4e00\u6b21\u6211\u4eec\u7684\u51fd\u6570\uff0c\u7136\u540e\u5c31\u53ef\u4ee5\u5728\u6211\u4eec\u5e0c\u671b\u5bf9\u5176\u8fdb\u884c\u5fae\u5206\u64cd\u4f5c\u7684\u4efb\u4f55\u60c5\u51b5\u4e0b\u91cd\u65b0\u4f7f\u7528\u3002\n\n    template <typename NumberType> \n    NumberType f(const NumberType &x, const NumberType &y) \n    { \n      return std::cos(y / x); \n    } \n\n// \u6211\u4eec\u6ca1\u6709\u7acb\u5373\u63ed\u793a\u8fd9\u4e2a\u51fd\u6570\u7684\u5bfc\u6570\uff0c\u800c\u662f\u5411\u524d\u58f0\u660e\u8fd4\u56de\u5bfc\u6570\u7684\u51fd\u6570\uff0c\u5e76\u5c06\u5b83\u4eec\u7684\u5b9a\u4e49\u63a8\u8fdf\u5230\u4ee5\u540e\u3002\u6b63\u5982\u51fd\u6570\u540d\u79f0\u6240\u6697\u793a\u7684\uff0c\u5b83\u4eec\u5206\u522b\u8fd4\u56de\u5bfc\u6570  $\\frac{df(x,y)}{dx}$  \u3002\n\n    double df_dx(const double x, const double y); \n// $\\frac{df(x,y)}{dy}$  :\n\n    double df_dy(const double x, const double y); \n// $\\frac{d^{2}f(x,y)}{dx^{2}}$  :\n\n    double d2f_dx_dx(const double x, const double y); \n// $\\frac{d^{2}f(x,y)}{dx dy}$  :\n\n    double d2f_dx_dy(const double x, const double y); \n// $\\frac{d^{2}f(x,y)}{dy dx}$  :\n\n    double d2f_dy_dx(const double x, const double y); \n\n// \u6700\u540e\u662f  $\\frac{d^{2}f(x,y)}{dy^{2}}$  \u3002\n\n    double d2f_dy_dy(const double x, const double y); \n// @sect4{Computing derivatives using automatic differentiation}  \n\n// \u9996\u5148\uff0c\u6211\u4eec\u5c06\u4f7f\u7528AD\u4f5c\u4e3a\u5de5\u5177\uff0c\u4e3a\u6211\u4eec\u81ea\u52a8\u8ba1\u7b97\u5bfc\u6570\u3002\u6211\u4eec\u5c06\u7528\u53c2\u6570`x`\u548c`y`\u6765\u8bc4\u4f30\u51fd\u6570\uff0c\u5e76\u671f\u671b\u5f97\u5230\u7684\u503c\u548c\u6240\u6709\u7684\u5bfc\u6570\u90fd\u80fd\u5728\u7ed9\u5b9a\u7684\u516c\u5dee\u8303\u56f4\u5185\u5339\u914d\u3002\n\n    void \n    run_and_verify_ad(const double x, const double y, const double tol = 1e-12) \n    { \n\n// \u6211\u4eec\u7684\u51fd\u6570 $f(x,y)$ \u662f\u4e00\u4e2a\u6807\u91cf\u503c\u51fd\u6570\uff0c\u5176\u53c2\u6570\u4ee3\u8868\u4ee3\u6570\u8ba1\u7b97\u6216\u5f20\u91cf\u8ba1\u7b97\u4e2d\u9047\u5230\u7684\u5178\u578b\u8f93\u5165\u53d8\u91cf\u3002\u7531\u4e8e\u8fd9\u4e2a\u539f\u56e0\uff0c Differentiation::AD::ScalarFunction \u7c7b\u662f\u5408\u9002\u7684\u5305\u88c5\u7c7b\uff0c\u53ef\u4ee5\u7528\u6765\u505a\u6211\u4eec\u9700\u8981\u7684\u8ba1\u7b97\u3002(\u4f5c\u4e3a\u6bd4\u8f83\uff0c\u5982\u679c\u51fd\u6570\u53c2\u6570\u4ee3\u8868\u6709\u9650\u5143\u5355\u5143\u7684\u81ea\u7531\u5ea6\uff0c\u6211\u4eec\u4f1a\u5e0c\u671b\u4ee5\u4e0d\u540c\u7684\u65b9\u5f0f\u5904\u7406\u5b83\u4eec)\u3002\u95ee\u9898\u7684\u7a7a\u95f4\u7ef4\u5ea6\u662f\u4e0d\u76f8\u5173\u7684\uff0c\u56e0\u4e3a\u6211\u4eec\u6ca1\u6709\u77e2\u91cf\u6216\u5f20\u91cf\u503c\u7684\u53c2\u6570\u9700\u8981\u5bb9\u7eb3\uff0c\u6240\u4ee5`dim`\u6a21\u677f\u53c2\u6570\u88ab\u4efb\u610f\u5206\u914d\u4e3a1\u7684\u503c\u3002 \u7b2c\u4e8c\u4e2a\u6a21\u677f\u53c2\u6570\u89c4\u5b9a\u4e86\u5c06\u4f7f\u7528\u54ea\u4e2aAD\u6846\u67b6\uff08deal.II\u652f\u6301\u51e0\u4e2a\u5916\u90e8AD\u6846\u67b6\uff09\uff0c\u4ee5\u53ca\u8fd9\u4e2a\u6846\u67b6\u63d0\u4f9b\u7684\u57fa\u7840\u6570\u5b57\u7c7b\u578b\u5c06\u88ab\u4f7f\u7528\u3002\u8fd9\u4e2a\u6570\u5b57\u7c7b\u578b\u5f71\u54cd\u4e86\u5fae\u5206\u8fd0\u7b97\u7684\u6700\u5927\u987a\u5e8f\uff0c\u4ee5\u53ca\u7528\u4e8e\u8ba1\u7b97\u5b83\u4eec\u7684\u57fa\u7840\u7b97\u6cd5\u3002\u9274\u4e8e\u5176\u6a21\u677f\u6027\u8d28\uff0c\u8fd9\u4e2a\u9009\u62e9\u662f\u4e00\u4e2a\u7f16\u8bd1\u65f6\u7684\u51b3\u5b9a\uff0c\u56e0\u4e3a\u8bb8\u591a\uff08\u4f46\u4e0d\u662f\u5168\u90e8\uff09AD\u5e93\u5229\u7528\u7f16\u8bd1\u65f6\u7684\u5143\u7f16\u7a0b\uff0c\u4ee5\u6709\u6548\u7684\u65b9\u5f0f\u5b9e\u73b0\u8fd9\u4e9b\u7279\u6b8a\u7684\u6570\u5b57\u7c7b\u578b\u3002\u7b2c\u4e09\u4e2a\u6a21\u677f\u53c2\u6570\u8bf4\u660e\u4e86\u7ed3\u679c\u7c7b\u578b\u662f\u4ec0\u4e48\uff1b\u5728\u6211\u4eec\u7684\u4f8b\u5b50\u4e2d\uff0c\u6211\u4eec\u8981\u5904\u7406\u7684\u662f \"\u53cc\u6570\"\u3002\n\n      constexpr unsigned int                     dim = 1; \n      constexpr Differentiation::AD::NumberTypes ADTypeCode = \n        Differentiation::AD::NumberTypes::sacado_dfad_dfad; \n      using ADHelper = \n        Differentiation::AD::ScalarFunction<dim, ADTypeCode, double>; \n\n// \u6211\u4eec\u6709\u5fc5\u8981\u5728\u6211\u4eec\u7684 @p ADHelper \u7c7b\u4e2d\u9884\u5148\u767b\u8bb0\u51fd\u6570 $f(x,y)$ \u6709\u591a\u5c11\u4e2a\u53c2\u6570\uff08\u6211\u4eec\u5c06\u79f0\u4e4b\u4e3a \"\u72ec\u7acb\u53d8\u91cf\"\uff09\u3002\u8fd9\u4e9b\u53c2\u6570\u662f`x`\u548c`y`\uff0c\u6240\u4ee5\u663e\u7136\u6709\u4e24\u4e2a\u3002\n\n      constexpr unsigned int n_independent_variables = 2; \n\n// \u6211\u4eec\u73b0\u5728\u6709\u8db3\u591f\u7684\u4fe1\u606f\u6765\u521b\u5efa\u548c\u521d\u59cb\u5316\u4e00\u4e2a\u8f85\u52a9\u7c7b\u7684\u5b9e\u4f8b\u3002\u6211\u4eec\u8fd8\u53ef\u4ee5\u5f97\u5230\u5177\u4f53\u7684\u6570\u5b57\u7c7b\u578b\uff0c\u5b83\u5c06\u5728\u6240\u6709\u540e\u7eed\u8ba1\u7b97\u4e2d\u4f7f\u7528\u3002\u8fd9\u5f88\u6709\u7528\uff0c\u56e0\u4e3a\u6211\u4eec\u53ef\u4ee5\u4ece\u8fd9\u91cc\u5f00\u59cb\u901a\u8fc7\u5f15\u7528\u8fd9\u4e2a\u7c7b\u578b\u6765\u7f16\u5199\u4e00\u5207\uff0c\u5982\u679c\u6211\u4eec\u60f3\u6539\u53d8\u4f7f\u7528\u7684\u6846\u67b6\u6216\u6570\u5b57\u7c7b\u578b\uff08\u4f8b\u5982\uff0c\u5982\u679c\u6211\u4eec\u9700\u8981\u66f4\u591a\u7684\u5fae\u5206\u8fd0\u7b97\uff09\uff0c\u90a3\u4e48\u6211\u4eec\u53ea\u9700\u8981\u8c03\u6574`ADTypeCode`\u6a21\u677f\u53c2\u6570\u3002\n\n      ADHelper ad_helper(n_independent_variables); \n      using ADNumberType = typename ADHelper::ad_type; \n\n// \u4e0b\u4e00\u6b65\u662f\u5728\u8f85\u52a9\u7c7b\u4e2d\u6ce8\u518c\u81ea\u53d8\u91cf\u7684\u6570\u503c\u3002\u8fd9\u6837\u505a\u662f\u56e0\u4e3a\u51fd\u6570\u548c\u5b83\u7684\u5bfc\u6570\u5c06\u6b63\u597d\u9488\u5bf9\u8fd9\u4e9b\u53c2\u6570\u8fdb\u884c\u8bc4\u4f30\u3002\u7531\u4e8e\u6211\u4eec\u6309\u7167`{x,y}`\u7684\u987a\u5e8f\u6ce8\u518c\u5b83\u4eec\uff0c\u53d8\u91cf`x`\u5c06\u88ab\u5206\u914d\u5230\u5206\u91cf\u53f7`0`\uff0c\u800c`y`\u5c06\u662f\u5206\u91cf\u53f7`1`--\u8fd9\u4e2a\u7ec6\u8282\u5c06\u5728\u63a5\u4e0b\u6765\u7684\u51e0\u884c\u4e2d\u4f7f\u7528\u3002\n\n      ad_helper.register_independent_variables({x, y}); \n\n// \u6211\u4eec\u73b0\u5728\u8981\u6c42\u8f85\u52a9\u7c7b\u5411\u6211\u4eec\u63d0\u4f9b\u81ea\u53d8\u91cf\u53ca\u5176\u81ea\u52a8\u533a\u5206\u7684\u8868\u793a\u3002\u8fd9\u4e9b\u88ab\u79f0\u4e3a \"\u654f\u611f\u53d8\u91cf\"\uff0c\u56e0\u4e3a\u4ece\u73b0\u5728\u5f00\u59cb\uff0c\u6211\u4eec\u5bf9\u7ec4\u4ef6`\u72ec\u7acb\u53d8\u91cf_ad`\u6240\u505a\u7684\u4efb\u4f55\u64cd\u4f5c\u90fd\u4f1a\u88abAD\u6846\u67b6\u8ddf\u8e2a\u548c\u8bb0\u5f55\uff0c\u5e76\u4e14\u5728\u6211\u4eec\u8981\u6c42\u8ba1\u7b97\u5b83\u4eec\u7684\u5bfc\u6570\u65f6\uff0c\u4f1a\u88ab\u8003\u8651\u3002\u5e2e\u52a9\u5668\u8fd4\u56de\u7684\u662f\u4e00\u4e2a\u53ef\u81ea\u52a8\u5fae\u5206\u7684 \"\u5411\u91cf\"\uff0c\u4f46\u662f\u6211\u4eec\u53ef\u4ee5\u786e\u5b9a\uff0c\u7b2c2\u4e2a\u5143\u7d20\u4ee3\u8868 \"x\"\uff0c\u7b2c1\u4e2a\u5143\u7d20\u4ee3\u8868 \"y\"\u3002\u4e3a\u4e86\u5b8c\u5168\u786e\u4fdd\u8fd9\u4e9b\u53d8\u91cf\u7684\u6570\u5b57\u7c7b\u578b\u6ca1\u6709\u4efb\u4f55\u6b67\u4e49\uff0c\u6211\u4eec\u7ed9\u6240\u6709\u7684\u81ea\u52a8\u5fae\u5206\u53d8\u91cf\u52a0\u4e0a`ad'\u7684\u540e\u7f00\u3002\n\n      const std::vector<ADNumberType> independent_variables_ad = \n        ad_helper.get_sensitive_variables(); \n      const ADNumberType &x_ad = independent_variables_ad[0]; \n      const ADNumberType &y_ad = independent_variables_ad[1]; \n\n// \u6211\u4eec\u53ef\u4ee5\u7acb\u5373\u5c06\u81ea\u53d8\u91cf\u7684\u654f\u611f\u8868\u793a\u6cd5\u4f20\u9012\u7ed9\u6211\u4eec\u7684\u6a21\u677f\u51fd\u6570\uff0c\u8ba1\u7b97\u51fa  $f(x,y)$  \u3002\u8fd9\u4e5f\u4f1a\u8fd4\u56de\u4e00\u4e2a\u53ef\u81ea\u52a8\u5fae\u5206\u7684\u6570\u5b57\u3002\n\n      const ADNumberType f_ad = f(x_ad, y_ad); \n\n// \u6240\u4ee5\u73b0\u5728\u8981\u95ee\u7684\u81ea\u7136\u662f\uff0c\u6211\u4eec\u628a\u8fd9\u4e9b\u7279\u6b8a\u7684`x_ad`\u548c`y_ad`\u53d8\u91cf\u4f20\u9012\u7ed9\u51fd\u6570`f`\uff0c\u800c\u4e0d\u662f\u539f\u6765\u7684`double`\u53d8\u91cf`x`\u548c`y`\uff0c\u5b9e\u9645\u4e0a\u8ba1\u7b97\u4e86\u4ec0\u4e48\uff1f\u6362\u53e5\u8bdd\u8bf4\uff0c\u8fd9\u4e00\u5207\u4e0e\u6211\u4eec\u60f3\u8981\u786e\u5b9a\u7684\u5bfc\u6570\u7684\u8ba1\u7b97\u6709\u4ec0\u4e48\u5173\u7cfb\uff1f\u6216\u8005\uff0c\u66f4\u7b80\u6d01\u5730\u8bf4\u3002\u8fd9\u4e2a\u8fd4\u56de\u7684`ADNumberType`\u5bf9\u8c61\u6709\u4ec0\u4e48\u7279\u522b\u4e4b\u5904\uff0c\u4f7f\u5b83\u6709\u80fd\u529b\u795e\u5947\u5730\u8fd4\u56de\u5bfc\u6570\uff1f\n\n// \u4ece\u672c\u8d28\u4e0a\u8bb2\uff0c\u8fd9*\u53ef\u4ee5*\u505a\u7684\u662f\u4ee5\u4e0b\u51e0\u70b9\u3002\u8fd9\u4e2a\u7279\u6b8a\u7684\u6570\u5b57\u53ef\u4ee5\u88ab\u770b\u4f5c\u662f\u4e00\u4e2a\u6570\u636e\u7ed3\u6784\uff0c\u5b83\u5b58\u50a8\u4e86\u51fd\u6570\u503c\uff0c\u4ee5\u53ca\u89c4\u5b9a\u7684\u5bfc\u6570\u6570\u91cf\u3002\u5bf9\u4e8e\u4e00\u4e2a\u671f\u671b\u6709\u4e24\u4e2a\u53c2\u6570\u7684\u4e00\u6b21\u53ef\u5bfc\u6570\uff0c\u5b83\u53ef\u80fd\u770b\u8d77\u6765\u50cf\u8fd9\u6837\u3002\n\n// \n// @code\n//  struct ADNumberType\n//  {\n//    double value; The value of the object\n//    double derivatives[2]; Array of derivatives of the object with\n//                  respect to x and y\n//  };\n//  @endcode\n\n// \u5bf9\u4e8e\u6211\u4eec\u7684\u81ea\u53d8\u91cf`x_ad`\uff0c`x_ad.value`\u7684\u8d77\u59cb\u503c\u53ea\u662f\u5b83\u7684\u8d4b\u503c\uff08\u5373\u8fd9\u4e2a\u53d8\u91cf\u4ee3\u8868\u7684\u5b9e\u503c\uff09\u3002\u5bfc\u6570`x_ad.derivatives[0]`\u5c06\u88ab\u521d\u59cb\u5316\u4e3a`1'\uff0c\u56e0\u4e3a`x'\u662f\u7b2c2\u4e2a\u72ec\u7acb\u53d8\u91cf\u548c $\\frac{d(x)}{dx} = 1$  \u3002\u5bfc\u6570`x.derivatives[1]`\u5c06\u88ab\u521d\u59cb\u5316\u4e3a\u96f6\uff0c\u56e0\u4e3a\u7b2c\u4e00\u4e2a\u81ea\u53d8\u91cf\u662f`y`\u548c $\\frac{d(x)}{dy} = 0$  \u3002\n\n// \u4e3a\u4e86\u4f7f\u51fd\u6570\u5bfc\u6570\u6709\u610f\u4e49\uff0c\u6211\u4eec\u5fc5\u987b\u5047\u8bbe\u8fd9\u4e2a\u51fd\u6570\u4e0d\u4ec5\u5728\u5206\u6790\u610f\u4e49\u4e0a\u662f\u53ef\u5fae\u7684\uff0c\u800c\u4e14\u5728\u8bc4\u4f30\u70b9`x,y`\u4e5f\u662f\u53ef\u5fae\u7684\u3002\u6211\u4eec\u53ef\u4ee5\u5229\u7528\u8fd9\u4e24\u4e2a\u5047\u8bbe\uff1a\u5f53\u6211\u4eec\u5728\u6570\u5b66\u8fd0\u7b97\u4e2d\u4f7f\u7528\u8fd9\u79cd\u6570\u5b57\u7c7b\u578b\u65f6\uff0cAD\u6846\u67b6\u53ef\u4ee5**\u7684\n//\u91cd\u8f7d\u64cd\u4f5c\uff08\u4f8b\u5982\uff0c`%operator+()`, `%operator*()`\u4ee5\u53ca`%sin()`, `%exp()`, \u7b49\u7b49\uff09\uff0c\u4f7f\u8fd4\u56de\u7684\u7ed3\u679c\u5177\u6709\u9884\u671f\u503c\u3002\u540c\u65f6\uff0c\u5b83\u5c06\u901a\u8fc7\u5bf9\u88ab\u91cd\u8f7d\u7684\u786e\u5207\u51fd\u6570\u7684\u4e86\u89e3\u548c\u5bf9\u8fde\u9501\u89c4\u5219\u7684\u4e25\u683c\u5e94\u7528\u6765\u8ba1\u7b97\u5bfc\u6570\u3002\u56e0\u6b64\uff0c`%sin()`\u51fd\u6570\uff08\u5176\u53c2\u6570`a`\u672c\u8eab\u662f\u81ea\u53d8\u91cf`x`\u548c`y`\u7684\u4e00\u4e2a\u51fd\u6570 *\u53ef\u80fd*\u88ab\u5b9a\u4e49\u5982\u4e0b\u3002\n\n// \n// @code\n// ADNumberType sin(const ADNumberType &a)\n// {\n//   ADNumberType output;\n//\n//   // For the input argument \"a\", \"a.value\" is simply its value.\n//   output.value = sin(a.value);\n//\n//   // We know that the derivative of sin(a) is cos(a), but we need\n//   // to also consider the chain rule and that the input argument\n//   // `a` is also differentiable with respect to the original\n//   // independent variables `x` and `y`. So `a.derivatives[0]`\n//   // and `a.derivatives[1]` respectively represent the partial\n//   // derivatives of `a` with respect to its inputs `x` and `y`.\n//   output.derivatives[0] = cos(a.value)*a.derivatives[0];\n//   output.derivatives[1] = cos(a.value)*a.derivatives[1];\n//\n//   return output;\n// }\n// @endcode\n\n// \u5f53\u7136\uff0c\u6240\u6709\u8fd9\u4e9b\u4e5f\u53ef\u4ee5\u7528\u4e8e\u4e8c\u9636\u751a\u81f3\u9ad8\u9636\u5bfc\u6570\u3002\n\n// \u6240\u4ee5\u73b0\u5728\u5f88\u660e\u663e\uff0c\u901a\u8fc7\u4e0a\u8ff0\u8868\u793a\uff0c`ADNumberType`\u643a\u5e26\u4e86\u4e00\u4e9b\u989d\u5916\u7684\u6570\u636e\uff0c\u8fd9\u4e9b\u6570\u636e\u4ee3\u8868\u4e86\u53ef\u5fae\u8c03\u51fd\u6570\u76f8\u5bf9\u4e8e\u539f\u59cb\uff08\u654f\u611f\uff09\u81ea\u53d8\u91cf\u7684\u5404\u79cd\u5bfc\u6570\u3002\u56e0\u6b64\u5e94\u8be5\u6ce8\u610f\u5230\uff0c\u4f7f\u7528\u5b83\u4eec\u4f1a\u4ea7\u751f\u8ba1\u7b97\u5f00\u9500\uff08\u56e0\u4e3a\u6211\u4eec\u5728\u505a\u5bfc\u6570\u8ba1\u7b97\u65f6\u8981\u8ba1\u7b97\u989d\u5916\u7684\u51fd\u6570\uff09\uff0c\u4ee5\u53ca\u5b58\u50a8\u8fd9\u4e9b\u7ed3\u679c\u7684\u5185\u5b58\u5f00\u9500\u3002\u56e0\u6b64\uff0c\u89c4\u5b9a\u7684\u5fae\u5206\u8fd0\u7b97\u7684\u7ea7\u6570\u6700\u597d\u4fdd\u6301\u5728\u6700\u4f4e\u6c34\u5e73\uff0c\u4ee5\u9650\u5236\u8ba1\u7b97\u6210\u672c\u3002\u4f8b\u5982\uff0c\u6211\u4eec\u53ef\u4ee5\u81ea\u5df1\u8ba1\u7b97\u7b2c\u4e00\u7ea7\u5bfc\u6570\uff0c\u7136\u540e\u4f7f\u7528 Differentiation::AD::VectorFunction \u8f85\u52a9\u7c7b\u6765\u786e\u5b9a\u4f9d\u8d56\u51fd\u6570\u96c6\u5408\u7684\u68af\u5ea6\uff0c\u8fd9\u5c06\u662f\u539f\u59cb\u6807\u91cf\u51fd\u6570\u7684\u7b2c\u4e8c\u7ea7\u5bfc\u6570\u3002\n\n// \u8fd8\u503c\u5f97\u6ce8\u610f\u7684\u662f\uff0c\u7531\u4e8e\u94fe\u5f0f\u89c4\u5219\u662f\u65e0\u5dee\u522b\u5e94\u7528\u7684\uff0c\u6211\u4eec\u53ea\u770b\u5230\u8ba1\u7b97\u7684\u8d77\u70b9\u548c\u7ec8\u70b9`{x,y}`  $\\rightarrow$  `f(x,y)`\uff0c\u6211\u4eec\u6c38\u8fdc\u53ea\u80fd\u67e5\u8be2\u5230`f`\u7684\u603b\u5bfc\u6570\uff1b\u90e8\u5206\u5bfc\u6570\uff08\u4e0a\u4f8b\u4e2d\u7684`a.\u5bfc\u6570[0]`\u548c`a.\u5bfc\u6570[1]`\uff09\u662f\u4e2d\u95f4\u503c\uff0c\u5bf9\u6211\u4eec\u662f\u9690\u85cf\u7684\u3002\n\n// \u597d\u7684\uff0c\u65e2\u7136\u6211\u4eec\u73b0\u5728\u81f3\u5c11\u77e5\u9053\u4e86`f_ad'\u4ee3\u8868\u4ec0\u4e48\uff0c\u4ee5\u53ca\u5b83\u7684\u7f16\u7801\u662f\u4ec0\u4e48\uff0c\u8ba9\u6211\u4eec\u628a\u6240\u6709\u7684\u4e1c\u897f\u7528\u4e8e\u5b9e\u9645\u7684\u7528\u9014\u3002\u4e3a\u4e86\u83b7\u5f97\u90a3\u4e9b\u9690\u85cf\u7684\u6d3e\u751f\u7ed3\u679c\uff0c\u6211\u4eec\u5c06\u6700\u7ec8\u7ed3\u679c\u6ce8\u518c\u5230\u5e2e\u52a9\u7c7b\u4e2d\u3002\u5728\u8fd9\u4e4b\u540e\uff0c\u6211\u4eec\u4e0d\u80fd\u518d\u6539\u53d8`f_ad`\u7684\u503c\uff0c\u4e5f\u4e0d\u80fd\u8ba9\u8fd9\u4e9b\u53d8\u5316\u53cd\u6620\u5728\u5e2e\u52a9\u8005\u7c7b\u8fd4\u56de\u7684\u7ed3\u679c\u4e2d\u3002\n\n      ad_helper.register_dependent_variable(f_ad); \n\n// \u4e0b\u4e00\u6b65\u662f\u63d0\u53d6\u5bfc\u6570\uff08\u7279\u522b\u662f\u51fd\u6570\u68af\u5ea6\u548cHessian\uff09\u3002\u4e3a\u6b64\uff0c\u6211\u4eec\u9996\u5148\u521b\u5efa\u4e00\u4e9b\u4e34\u65f6\u6570\u636e\u7ed3\u6784\uff08\u7ed3\u679c\u7c7b\u578b\u4e3a`double`\uff09\u6765\u5b58\u50a8\u5bfc\u6570\uff08\u6ce8\u610f\uff0c\u6240\u6709\u7684\u5bfc\u6570\u90fd\u662f\u4e00\u6b21\u6027\u8fd4\u56de\u7684\uff0c\u800c\u4e0d\u662f\u5355\u72ec\u8fd4\u56de\uff09...\n\n      Vector<double>     Df(ad_helper.n_dependent_variables()); \n      FullMatrix<double> D2f(ad_helper.n_dependent_variables(), \n                             ad_helper.n_independent_variables()); \n\n// ... \u7136\u540e\u6211\u4eec\u8981\u6c42\u52a9\u624b\u7c7b\u8ba1\u7b97\u8fd9\u4e9b\u5bfc\u6570\uff0c\u4ee5\u53ca\u51fd\u6570\u503c\u672c\u8eab\u3002\u5c31\u8fd9\u6837\u4e86\u3002\u6211\u4eec\u5f97\u5230\u4e86\u6211\u4eec\u60f3\u5f97\u5230\u7684\u4e00\u5207\u3002\n\n      const double computed_f = ad_helper.compute_value(); \n      ad_helper.compute_gradient(Df); \n      ad_helper.compute_hessian(D2f); \n\n// \u6211\u4eec\u53ef\u4ee5\u901a\u8fc7\u4e0e\u5206\u6790\u65b9\u6848\u7684\u6bd4\u8f83\u6765\u8bf4\u670d\u81ea\u5df1\uff0cAD\u6846\u67b6\u662f\u6b63\u786e\u7684\u3002(\u6216\u8005\uff0c\u5982\u679c\u4f60\u50cf\u4f5c\u8005\u4e00\u6837\uff0c\u4f60\u4f1a\u505a\u76f8\u53cd\u7684\u4e8b\u60c5\uff0c\u5b81\u613f\u9a8c\u8bc1\u4f60\u5bf9\u5206\u6790\u65b9\u6848\u7684\u5b9e\u73b0\u662f\u6b63\u786e\u7684\uff01)\n\n      AssertThrow(std::abs(f(x, y) - computed_f) < tol, \n                  ExcMessage(std::string(\"Incorrect value computed for f. \") + \n                             std::string(\"Hand-calculated value: \") + \n                             Utilities::to_string(f(x, y)) + \n                             std::string(\" ; \") + \n                             std::string(\"Value computed by AD: \") + \n                             Utilities::to_string(computed_f))); \n\n// \u56e0\u4e3a\u6211\u4eec\u77e5\u9053\u81ea\u53d8\u91cf\u7684\u6392\u5e8f\uff0c\u6240\u4ee5\u6211\u4eec\u77e5\u9053\u68af\u5ea6\u7684\u54ea\u4e2a\u90e8\u5206\u4e0e\u54ea\u4e2a\u5bfc\u6570\u6709\u5173......\u3002\n\n      const double computed_df_dx = Df[0]; \n      const double computed_df_dy = Df[1]; \n\n      AssertThrow(std::abs(df_dx(x, y) - computed_df_dx) < tol, \n                  ExcMessage( \n                    std::string(\"Incorrect value computed for df/dx. \") + \n                    std::string(\"Hand-calculated value: \") + \n                    Utilities::to_string(df_dx(x, y)) + std::string(\" ; \") + \n                    std::string(\"Value computed by AD: \") + \n                    Utilities::to_string(computed_df_dx))); \n      AssertThrow(std::abs(df_dy(x, y) - computed_df_dy) < tol, \n                  ExcMessage( \n                    std::string(\"Incorrect value computed for df/dy. \") + \n                    std::string(\"Hand-calculated value: \") + \n                    Utilities::to_string(df_dy(x, y)) + std::string(\" ; \") + \n                    std::string(\"Value computed by AD: \") + \n                    Utilities::to_string(computed_df_dy))); \n\n// .......\u5bf9\u4e8eHessian\u4e5f\u662f\u5982\u6b64\u3002\n\n      const double computed_d2f_dx_dx = D2f[0][0]; \n      const double computed_d2f_dx_dy = D2f[0][1]; \n      const double computed_d2f_dy_dx = D2f[1][0]; \n      const double computed_d2f_dy_dy = D2f[1][1]; \n\n      AssertThrow(std::abs(d2f_dx_dx(x, y) - computed_d2f_dx_dx) < tol, \n                  ExcMessage( \n                    std::string(\"Incorrect value computed for d2f/dx_dx. \") + \n                    std::string(\"Hand-calculated value: \") + \n                    Utilities::to_string(d2f_dx_dx(x, y)) + std::string(\" ; \") + \n                    std::string(\"Value computed by AD: \") + \n                    Utilities::to_string(computed_d2f_dx_dx))); \n      AssertThrow(std::abs(d2f_dx_dy(x, y) - computed_d2f_dx_dy) < tol, \n                  ExcMessage( \n                    std::string(\"Incorrect value computed for d2f/dx_dy. \") + \n                    std::string(\"Hand-calculated value: \") + \n                    Utilities::to_string(d2f_dx_dy(x, y)) + std::string(\" ; \") + \n                    std::string(\"Value computed by AD: \") + \n                    Utilities::to_string(computed_d2f_dx_dy))); \n      AssertThrow(std::abs(d2f_dy_dx(x, y) - computed_d2f_dy_dx) < tol, \n                  ExcMessage( \n                    std::string(\"Incorrect value computed for d2f/dy_dx. \") + \n                    std::string(\"Hand-calculated value: \") + \n                    Utilities::to_string(d2f_dy_dx(x, y)) + std::string(\" ; \") + \n                    std::string(\"Value computed by AD: \") + \n                    Utilities::to_string(computed_d2f_dy_dx))); \n      AssertThrow(std::abs(d2f_dy_dy(x, y) - computed_d2f_dy_dy) < tol, \n                  ExcMessage( \n                    std::string(\"Incorrect value computed for d2f/dy_dy. \") + \n                    std::string(\"Hand-calculated value: \") + \n                    Utilities::to_string(d2f_dy_dy(x, y)) + std::string(\" ; \") + \n                    std::string(\"Value computed by AD: \") + \n                    Utilities::to_string(computed_d2f_dy_dy))); \n    } \n\n// \u8fd9\u5f88\u4e0d\u9519\u3002\u5728\u8ba1\u7b97\u8fd9\u4e2a\u4e09\u89d2\u51fd\u6570\u7684\u4e8c\u9636\u5bfc\u6570\u65f6\u5e76\u6ca1\u6709\u592a\u591a\u7684\u5de5\u4f5c\u3002\n\n//  @sect4{Hand-calculated derivatives of the analytical solution}  \n\n// \u65e2\u7136\u6211\u4eec\u73b0\u5728\u77e5\u9053\u4e86\u8ba9AD\u6846\u67b6\u4e3a\u6211\u4eec\u8ba1\u7b97\u8fd9\u4e9b\u5bfc\u6570\u9700\u8981\u591a\u5c11 \"\u6267\u884c\u5de5\u4f5c\"\uff0c\u8ba9\u6211\u4eec\u628a\u5b83\u4e0e\u624b\u5de5\u8ba1\u7b97\u5e76\u5728\u51e0\u4e2a\u72ec\u7acb\u7684\u51fd\u6570\u4e2d\u5b9e\u73b0\u7684\u540c\u6837\u7684\u5bfc\u6570\u8fdb\u884c\u6bd4\u8f83\u3002\n\n// \u8fd9\u91cc\u662f $f(x,y) = \\cos\\left(\\frac{y}{x}\\right)$ \u7684\u4e24\u4e2a\u4e00\u9636\u5bfc\u6570\u3002\n\n//  $\\frac{df(x,y)}{dx} = \\frac{y}{x^2} \\sin\\left(\\frac{y}{x}\\right)$  \n    double df_dx(const double x, const double y) \n    { \n      Assert(x != 0.0, ExcDivideByZero()); \n      return y * std::sin(y / x) / (x * x); \n    } \n// $\\frac{df(x,y)}{dx} = -\\frac{1}{x} \\sin\\left(\\frac{y}{x}\\right)$  \n    double df_dy(const double x, const double y) \n    { \n      return -std::sin(y / x) / x; \n    } \n\n// \u8fd9\u91cc\u662f $f(x,y)$ \u7684\u56db\u4e2a\u4e8c\u6b21\u5bfc\u6570\u3002\n\n//  $\\frac{d^{2}f(x,y)}{dx^{2}} = -\\frac{y}{x^4} (2x \\sin\\left(\\frac{y}{x}\\right) + y \\cos\\left(\\frac{y}{x}\\right))$  \n    double d2f_dx_dx(const double x, const double y) \n    { \n      return -y * (2 * x * std::sin(y / x) + y * std::cos(y / x)) / \n             (x * x * x * x); \n    } \n// $\\frac{d^{2}f(x,y)}{dx dy} = \\frac{1}{x^3} (x \\sin\\left(\\frac{y}{x}\\right) + y \\cos\\left(\\frac{y}{x}\\right))$  \n    double d2f_dx_dy(const double x, const double y) \n    { \n      return (x * std::sin(y / x) + y * std::cos(y / x)) / (x * x * x); \n    } \n// $\\frac{d^{2}f(x,y)}{dy dx} = \\frac{1}{x^3} (x \\sin\\left(\\frac{y}{x}\\right) + y \\cos\\left(\\frac{y}{x}\\right))$  \uff08\u6b63\u5982\u9884\u671f\u7684\u90a3\u6837\uff0c\u6839\u636e[\u65bd\u74e6\u8328\u5b9a\u7406]\uff08https:en.wikipedia.org/wiki/Symmetry_of_second_derivatives\uff09\uff09\u3002\n\n    double d2f_dy_dx(const double x, const double y) \n    { \n      return (x * std::sin(y / x) + y * std::cos(y / x)) / (x * x * x); \n    } \n// $\\frac{d^{2}f(x,y)}{dy^{2}} = -\\frac{1}{x^2} \\cos\\left(\\frac{y}{x}\\right)$  \n    double d2f_dy_dy(const double x, const double y) \n    { \n      return -(std::cos(y / x)) / (x * x); \n    } \n\n// \u55ef......\u4e0a\u9762\u6709\u5f88\u591a\u5730\u65b9\u6211\u4eec\u53ef\u4ee5\u5f15\u5165\u9519\u8bef\uff0c\u7279\u522b\u662f\u5728\u5e94\u7528\u94fe\u5f0f\u89c4\u5219\u7684\u65f6\u5019\u3002\u867d\u7136\u5b83\u4eec\u4e0d\u662f\u94f6\u5f39\uff0c\u4f46\u81f3\u5c11\u8fd9\u4e9bAD\u6846\u67b6\u53ef\u4ee5\u4f5c\u4e3a\u4e00\u4e2a\u9a8c\u8bc1\u5de5\u5177\uff0c\u786e\u4fdd\u6211\u4eec\u6ca1\u6709\u72af\u4efb\u4f55\u9519\u8bef\uff08\u65e0\u8bba\u662f\u8ba1\u7b97\u8fd8\u662f\u6267\u884c\uff09\uff0c\u4ece\u800c\u5bf9\u6211\u4eec\u7684\u7ed3\u679c\u4ea7\u751f\u8d1f\u9762\u5f71\u54cd\u3002\n\n// \u5f53\u7136\uff0c\u8fd9\u4e2a\u4f8b\u5b50\u7684\u91cd\u70b9\u662f\uff0c\u6211\u4eec\u53ef\u80fd\u9009\u62e9\u4e86\u4e00\u4e2a\u76f8\u5bf9\u7b80\u5355\u7684\u51fd\u6570 $f(x,y)$ \uff0c\u6211\u4eec\u53ef\u4ee5\u624b\u5de5\u9a8c\u8bc1AD\u6846\u67b6\u8ba1\u7b97\u7684\u5bfc\u6570\u662f\u5426\u6b63\u786e\u3002\u4f46\u662fAD\u6846\u67b6\u5e76\u4e0d\u5173\u5fc3\u8fd9\u4e2a\u51fd\u6570\u662f\u5426\u7b80\u5355\u3002\u5b83\u53ef\u80fd\u662f\u4e00\u4e2a\u590d\u6742\u5f97\u591a\u7684\u8868\u8fbe\u5f0f\uff0c\u6216\u8005\u53d6\u51b3\u4e8e\u4e24\u4e2a\u4ee5\u4e0a\u7684\u53d8\u91cf\uff0c\u5b83\u4ecd\u7136\u80fd\u591f\u8ba1\u7b97\u51fa\u5bfc\u6570--\u552f\u4e00\u7684\u533a\u522b\u662f\uff0c*\u6211\u4eec*\u4e0d\u80fd\u518d\u60f3\u51fa\u5bfc\u6570\u6765\u9a8c\u8bc1AD\u6846\u67b6\u7684\u6b63\u786e\u6027\u3002\n\n//  @sect4{Computing derivatives using symbolic differentiation}  \n\n// \u6211\u4eec\u73b0\u5728\u8981\u7528\u7b26\u53f7\u5fae\u5206\u6cd5\u91cd\u590d\u540c\u6837\u7684\u7ec3\u4e60\u3002\u672f\u8bed \"\u7b26\u53f7\u5fae\u5206 \"\u6709\u70b9\u8bef\u5bfc\uff0c\u56e0\u4e3a\u5fae\u5206\u53ea\u662f\u8ba1\u7b97\u673a\u4ee3\u6570\u7cfb\u7edf\uff08CAS\uff09\uff08\u5373\u7b26\u53f7\u6846\u67b6\uff09\u63d0\u4f9b\u7684\u4e00\u4e2a\u5de5\u5177\u3002\u7136\u800c\uff0c\u5728\u6709\u9650\u5143\u5efa\u6a21\u548c\u5e94\u7528\u7684\u80cc\u666f\u4e0b\uff0c\u5b83\u662fCAS\u6700\u5e38\u89c1\u7684\u7528\u9014\uff0c\u56e0\u6b64\u5c06\u662f\u6211\u4eec\u5173\u6ce8\u7684\u91cd\u70b9\u3002\u518d\u4e00\u6b21\uff0c\u6211\u4eec\u5c06\u63d0\u4f9b\u53c2\u6570\u503c`x`\u548c`y`\u6765\u8bc4\u4f30\u6211\u4eec\u7684\u51fd\u6570 $f(x,y) = \\cos\\left(\\frac{y}{x}\\right)$ \u548c\u5b83\u7684\u5bfc\u6570\uff0c\u5e76\u63d0\u4f9b\u4e00\u4e2a\u516c\u5dee\u6765\u6d4b\u8bd5\u8fd4\u56de\u7ed3\u679c\u7684\u6b63\u786e\u6027\u3002\n\n    void \n    run_and_verify_sd(const double x, const double y, const double tol = 1e-12) \n    { \n\n// \u6211\u4eec\u9700\u8981\u505a\u7684\u7b2c\u4e00\u6b65\u662f\u5f62\u6210\u7b26\u53f7\u53d8\u91cf\uff0c\u4ee3\u8868\u6211\u4eec\u5e0c\u671b\u5bf9\u5176\u8fdb\u884c\u5fae\u5206\u7684\u51fd\u6570\u53c2\u6570\u3002\u540c\u6837\uff0c\u8fd9\u4e9b\u5c06\u662f\u6211\u4eec\u95ee\u9898\u7684\u72ec\u7acb\u53d8\u91cf\uff0c\u56e0\u6b64\u5728\u67d0\u79cd\u610f\u4e49\u4e0a\u662f\u539f\u59cb\u53d8\u91cf\uff0c\u4e0e\u5176\u4ed6\u53d8\u91cf\u6ca1\u6709\u4efb\u4f55\u5173\u7cfb\u3002\u6211\u4eec\u901a\u8fc7\u521d\u59cb\u5316\u4e00\u4e2a\u7b26\u53f7\u7c7b\u578b Differentiation::SD::Expression, \u6765\u521b\u5efa\u8fd9\u4e9b\u7c7b\u578b\u7684\uff08\u72ec\u7acb\uff09\u53d8\u91cf\uff0c\u8fd9\u4e2a\u7b26\u53f7\u7c7b\u578b\u662f\u5bf9\u7b26\u53f7\u6846\u67b6\u6240\u4f7f\u7528\u7684\u4e00\u7ec4\u7c7b\u7684\u5305\u88c5\uff0c\u6709\u4e00\u4e2a\u552f\u4e00\u7684\u6807\u8bc6\u3002\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0c\u8fd9\u4e2a\u6807\u8bc6\u7b26\uff0c\u4e00\u4e2a `std::string`, \u5bf9\u4e8e $x$ \u7684\u53c2\u6570\u6765\u8bf4\uff0c\u662f\u7b80\u5355\u7684 \"x\"\uff0c\u540c\u6837\uff0c\u5bf9\u4e8e\u4f9d\u8d56\u51fd\u6570\u7684 $y$ \u53c2\u6570\u6765\u8bf4\uff0c\u4e5f\u662f \"y\"\u3002\u50cf\u4ee5\u524d\u4e00\u6837\uff0c\u6211\u4eec\u5c06\u7528`sd`\u4f5c\u4e3a\u7b26\u53f7\u53d8\u91cf\u540d\u79f0\u7684\u540e\u7f00\uff0c\u8fd9\u6837\u6211\u4eec\u5c31\u53ef\u4ee5\u6e05\u695a\u5730\u770b\u5230\u54ea\u4e9b\u53d8\u91cf\u662f\u7b26\u53f7\u6027\u7684\uff08\u800c\u4e0d\u662f\u6570\u5b57\u6027\u7684\uff09\u3002\n\n      const Differentiation::SD::Expression x_sd(\"x\"); \n      const Differentiation::SD::Expression y_sd(\"y\"); \n\n// \u4f7f\u7528\u8ba1\u7b97 $f(x,y)$ \u7684\u6a21\u677f\u5316\u51fd\u6570\uff0c\u6211\u4eec\u53ef\u4ee5\u5c06\u8fd9\u4e9b\u72ec\u7acb\u53d8\u91cf\u4f5c\u4e3a\u53c2\u6570\u4f20\u9012\u7ed9\u8be5\u51fd\u6570\u3002\u8fd4\u56de\u7684\u7ed3\u679c\u5c06\u662f\u53e6\u4e00\u4e2a\u7b26\u53f7\u7c7b\u578b\uff0c\u4ee3\u8868\u7528\u4e8e\u8ba1\u7b97  $\\cos\\left(\\frac{y}{x}\\right)$  \u7684\u64cd\u4f5c\u5e8f\u5217\u3002\n\n      const Differentiation::SD::Expression f_sd = f(x_sd, y_sd); \n\n// \u5728\u8fd9\u4e00\u70b9\u4e0a\uff0c\u6253\u5370\u51fa\u8868\u8fbe\u5f0f`f_sd`\u662f\u5408\u6cd5\u7684\uff0c\u5982\u679c\u6211\u4eec\u8fd9\u6837\u505a\u7684\u8bdd \n// @code\n//  std::cout << \"f(x,y) = \" << f_sd << std::endl;\n//  @endcode \n//\u6211\u4eec\u4f1a\u770b\u5230`f(x,y) = cos(y/x)`\u6253\u5370\u5230\u63a7\u5236\u53f0\u3002\n\n// \u4f60\u53ef\u80fd\u4f1a\u6ce8\u610f\u5230\uff0c\u6211\u4eec\u5728\u6784\u5efa\u6211\u4eec\u7684\u7b26\u53f7\u51fd\u6570`f_sd`\u65f6\uff0c\u6ca1\u6709\u8bf4\u660e\u6211\u4eec\u53ef\u80fd\u8981\u5982\u4f55\u4f7f\u7528\u5b83\u3002\u4e0e\u4e0a\u9762\u663e\u793a\u7684AD\u65b9\u6cd5\u76f8\u6bd4\uff0c\u6211\u4eec\u4ece\u8c03\u7528`f(x_sd, y_sd)`\u8fd4\u56de\u7684\u4e0d\u662f\u51fd\u6570`f`\u5728\u67d0\u4e2a\u7279\u5b9a\u70b9\u7684\u8bc4\u4ef7\uff0c\u800c\u5b9e\u9645\u4e0a\u662f\u5728\u4e00\u4e2a\u901a\u7528\u7684\u3001\u5c1a\u672a\u786e\u5b9a\u7684\u70b9\u7684\u8bc4\u4ef7\u7684\u7b26\u53f7\u8868\u793a\u3002\u8fd9\u662f\u4f7f\u7b26\u53f7\u6846\u67b6\uff08CAS\uff09\u4e0d\u540c\u4e8e\u81ea\u52a8\u533a\u5206\u6846\u67b6\u7684\u5173\u952e\u70b9\u4e4b\u4e00\u3002\u6bcf\u4e2a\u53d8\u91cf`x_sd`\u548c`y_sd`\uff0c\u751a\u81f3\u590d\u5408\u4f9d\u8d56\u51fd\u6570`f_sd`\uff0c\u5728\u67d0\u79cd\u610f\u4e49\u4e0a\u5206\u522b\u662f\u6570\u503c\u7684 \"\u5360\u4f4d\u7b26 \"\u548c\u64cd\u4f5c\u7684\u7ec4\u5408\u3002\u4e8b\u5b9e\u4e0a\uff0c\u7528\u4e8e\u7ec4\u6210\u51fd\u6570\u7684\u5404\u4e2a\u7ec4\u4ef6\u4e5f\u662f\u5360\u4f4d\u7b26\u3002\u64cd\u4f5c\u5e8f\u5217\u88ab\u7f16\u7801\u6210\u4e00\u4e2a\u6811\u72b6\u7684\u6570\u636e\u7ed3\u6784\uff08\u6982\u5ff5\u4e0a\u7c7b\u4f3c\u4e8e[\u62bd\u8c61\u8bed\u6cd5\u6811](https:en.wikipedia.org/wiki/Abstract_syntax_tree)\uff09\u3002\n\n// \u4e00\u65e6\u6211\u4eec\u5f62\u6210\u4e86\u8fd9\u4e9b\u6570\u636e\u7ed3\u6784\uff0c\u6211\u4eec\u5c31\u53ef\u4ee5\u628a\u6211\u4eec\u53ef\u80fd\u60f3\u5bf9\u5b83\u4eec\u8fdb\u884c\u7684\u4efb\u4f55\u64cd\u4f5c\u63a8\u8fdf\u5230\u4ee5\u540e\u7684\u67d0\u4e2a\u65f6\u95f4\u3002\u8fd9\u4e9b\u5360\u4f4d\u7b26\u4e2d\u7684\u6bcf\u4e00\u4e2a\u90fd\u4ee3\u8868\u4e86\u4e00\u4e9b\u4e1c\u897f\uff0c\u4f46\u6211\u4eec\u6709\u673a\u4f1a\u5728\u4efb\u4f55\u65b9\u4fbf\u7684\u65f6\u95f4\u70b9\u4e0a\u5b9a\u4e49\u6216\u91cd\u65b0\u5b9a\u4e49\u5b83\u4eec\u6240\u4ee3\u8868\u7684\u4e1c\u897f\u3002\u56e0\u6b64\uff0c\u5bf9\u4e8e\u8fd9\u4e2a\u7279\u5b9a\u7684\u95ee\u9898\uff0c\u6211\u4eec\u60f3\u628a \"x \"\u548c \"y \"\u4e0e*\u4e00\u4e9b*\u6570\u503c\uff08\u7c7b\u578b\u5c1a\u672a\u786e\u5b9a\uff09\u8054\u7cfb\u8d77\u6765\u662f\u6709\u9053\u7406\u7684\uff0c\u4f46\u6211\u4eec\u53ef\u4ee5\u5728\u6982\u5ff5\u4e0a\uff08\u5982\u679c\u6709\u610f\u4e49\u7684\u8bdd\uff09\u7ed9 \"y/x \"\u8fd9\u4e2a\u6bd4\u7387\u8d4b\u503c\uff0c\u800c\u4e0d\u662f\u5355\u72ec\u7ed9 \"x \"\u548c \"y \"\u8fd9\u4e9b\u53d8\u91cf\u8d4b\u503c\u3002\u6211\u4eec\u8fd8\u53ef\u4ee5\u5c06 \"x \"\u6216 \"y \"\u4e0e\u5176\u4ed6\u4e00\u4e9b\u7b26\u53f7\u51fd\u6570`g(a,b)`\u8054\u7cfb\u8d77\u6765\u3002\u8fd9\u4e9b\u64cd\u4f5c\u4e2d\u7684\u4efb\u4f55\u4e00\u4e2a\u90fd\u6d89\u53ca\u5230\u5bf9\u6240\u8bb0\u5f55\u7684\u64cd\u4f5c\u6811\u7684\u64cd\u4f5c\uff0c\u4ee5\u53ca\u7528\u5176\u4ed6\u4e1c\u897f\u66ff\u6362\u6811\u4e0a\u7684\u7a81\u51fa\u8282\u70b9\uff08\u4ee5\u53ca\u8be5\u8282\u70b9\u7684\u5b50\u6811\uff09\u3002\u8fd9\u91cc\u7684\u5173\u952e\u8bcd\u662f \"\u66ff\u6362\"\uff0c\u4e8b\u5b9e\u4e0a\uff0c\u5728 Differentiation::SD \u547d\u540d\u7a7a\u95f4\u4e2d\u6709\u8bb8\u591a\u51fd\u6570\u7684\u540d\u79f0\u4e2d\u90fd\u6709\u8fd9\u4e2a\u8bcd\u3002\n\n// \u8fd9\u79cd\u80fd\u529b\u4f7f\u6846\u67b6\u5b8c\u5168\u901a\u7528\u3002\u5728\u6709\u9650\u5143\u6a21\u62df\u7684\u80cc\u666f\u4e0b\uff0c\u6211\u4eec\u901a\u5e38\u4f1a\u5bf9\u6211\u4eec\u7684\u7b26\u53f7\u7c7b\u578b\u8fdb\u884c\u7684\u64cd\u4f5c\u7c7b\u578b\u662f\u51fd\u6570\u7ec4\u5408\u3001\u5fae\u5206\u3001\u66ff\u6362\uff08\u90e8\u5206\u6216\u5b8c\u5168\uff09\u548c\u8bc4\u4f30\uff08\u5373\u7b26\u53f7\u7c7b\u578b\u5411\u5176\u6570\u5b57\u5bf9\u5e94\u7269\u7684\u8f6c\u6362\uff09\u3002\u4f46\u5982\u679c\u4f60\u9700\u8981\uff0c\u4e00\u4e2aCAS\u7684\u80fd\u529b\u5f80\u5f80\u4e0d\u6b62\u8fd9\u4e9b\u3002\u5b83\u53ef\u4ee5\u5f62\u6210\u51fd\u6570\u7684\u53cd\u5bfc\u6570\uff08\u79ef\u5206\uff09\uff0c\u5bf9\u5f62\u6210\u51fd\u6570\u7684\u8868\u8fbe\u5f0f\u8fdb\u884c\u7b80\u5316\uff08\u4f8b\u5982\uff0c\u7528 $1$ \u66ff\u6362 $(\\sin a)^2 + (\\cos a)^2$ \uff1b\u6216\u8005\uff0c\u66f4\u7b80\u5355\uff1a\u5982\u679c\u51fd\u6570\u505a\u4e86\u50cf`1+2`\u8fd9\u6837\u7684\u8fd0\u7b97\uff0cCAS\u53ef\u4ee5\u7528`3`\u66ff\u6362\u5b83\uff09\uff0c\u7b49\u7b49\u3002\u53d8\u91cf\u6240\u4ee3\u8868\u7684*\u8868\u8fbe\u5f0f\u662f\u4ece\u51fd\u6570 $f$ \u7684\u5b9e\u73b0\u65b9\u5f0f\u4e2d\u5f97\u5230\u7684\uff0c\u4f46CAS\u53ef\u4ee5\u5bf9\u5176\u8fdb\u884c\u4efb\u4f55\u529f\u80fd\u7684\u64cd\u4f5c\u3002\n\n// \u5177\u4f53\u6765\u8bf4\uff0c\u4e3a\u4e86\u8ba1\u7b97\u56e0\u679c\u51fd\u6570\u76f8\u5bf9\u4e8e\u5404\u4e2a\u81ea\u53d8\u91cf\u7684\u4e00\u9636\u5bfc\u6570\u7684\u7b26\u53f7\u8868\u793a\uff0c\u6211\u4eec\u4f7f\u7528 Differentiation::SD::Expression::differentiate() \u51fd\u6570\uff0c\u81ea\u53d8\u91cf\u4f5c\u4e3a\u5176\u53c2\u6570\u3002\u6bcf\u6b21\u8c03\u7528\u90fd\u4f1a\u5bfc\u81f4CAS\u901a\u8fc7\u7ec4\u6210`f_sd`\u7684\u8fd0\u7b97\u6811\uff0c\u5e76\u5bf9\u8868\u8fbe\u5f0f\u6811\u7684\u6bcf\u4e2a\u8282\u70b9\u8fdb\u884c\u76f8\u5bf9\u4e8e\u7ed9\u5b9a\u7b26\u53f7\u53c2\u6570\u7684\u5fae\u5206\u3002\n\n      const Differentiation::SD::Expression df_dx_sd = f_sd.differentiate(x_sd); \n      const Differentiation::SD::Expression df_dy_sd = f_sd.differentiate(y_sd); \n\n// \u4e3a\u4e86\u8ba1\u7b97\u4e8c\u9636\u5bfc\u6570\u7684\u7b26\u53f7\u8868\u793a\uff0c\u6211\u4eec\u53ea\u9700\u5bf9\u81ea\u53d8\u91cf\u7684\u4e00\u9636\u5bfc\u6570\u8fdb\u884c\u5fae\u5206\u3002\u6240\u4ee5\u8981\u8ba1\u7b97\u9ad8\u9636\u5bfc\u6570\uff0c\u6211\u4eec\u9996\u5148\u9700\u8981\u8ba1\u7b97\u4f4e\u9636\u5bfc\u6570\u3002\u7531\u4e8e\u8c03\u7528 \"differentiate() \"\u7684\u8fd4\u56de\u7c7b\u578b\u662f\u4e00\u4e2a\u8868\u8fbe\u5f0f\uff0c\u6211\u4eec\u539f\u5219\u4e0a\u53ef\u4ee5\u901a\u8fc7\u5c06\u4e24\u4e2a\u8c03\u7528\u8fde\u5728\u4e00\u8d77\uff0c\u76f4\u63a5\u4ece\u6807\u91cf\u4e0a\u6267\u884c\u53cc\u500d\u5fae\u5206\u3002\u4f46\u662f\u5728\u8fd9\u4e2a\u7279\u6b8a\u7684\u60c5\u51b5\u4e0b\uff0c\u8fd9\u662f\u4e0d\u9700\u8981\u7684\uff0c\u56e0\u4e3a\u6211\u4eec\u624b\u5934\u6709\u4e2d\u95f4\u7ed3\u679c\uff09\u3002)\n\n      const Differentiation::SD::Expression d2f_dx_dx_sd = \n        df_dx_sd.differentiate(x_sd); \n      const Differentiation::SD::Expression d2f_dx_dy_sd = \n        df_dx_sd.differentiate(y_sd); \n      const Differentiation::SD::Expression d2f_dy_dx_sd = \n        df_dy_sd.differentiate(x_sd); \n      const Differentiation::SD::Expression d2f_dy_dy_sd = \n        df_dy_sd.differentiate(y_sd); \n\n// \u4f7f\u7528\u8bed\u53e5\n// @code\n//  std::cout << \"df_dx_sd: \" << df_dx_sd << std::endl;\n//  std::cout << \"df_dy_sd: \" << df_dy_sd << std::endl;\n//  std::cout << \"d2f_dx_dx_sd: \" << d2f_dx_dx_sd << std::endl;\n//  std::cout << \"d2f_dx_dy_sd: \" << d2f_dx_dy_sd << std::endl;\n//  std::cout << \"d2f_dy_dx_sd: \" << d2f_dy_dx_sd << std::endl;\n//  std::cout << \"d2f_dy_dy_sd: \" << d2f_dy_dy_sd << std::endl;\n//  @endcode\n//  \u6253\u5370\u7531CAS\u8ba1\u7b97\u7684\u7b2c\u4e00\u548c\u7b2c\u4e8c\u5bfc\u6570\u7684\u8868\u8fbe\u5f0f\uff0c\u5f97\u5230\u4ee5\u4e0b\u8f93\u51fa\u3002\n//  @code{.sh}\n//  df_dx_sd: y*sin(y/x)/x**2\n//  df_dy_sd: -sin(y/x)/x\n//  d2f_dx_dx_sd: -y**2*cos(y/x)/x**4 - 2*y*sin(y/x)/x**3\n//  d2f_dx_dy_sd: sin(y/x)/x**2 + y*cos(y/x)/x**3\n//  d2f_dy_dx_sd: sin(y/x)/x**2 + y*cos(y/x)/x**3\n//  d2f_dy_dy_sd: -cos(y/x)/x**2\n//  @endcode \n//  \u8fd9\u4e0e\u524d\u9762\u4ecb\u7ecd\u7684\u8fd9\u4e9b\u5bfc\u6570\u7684\u5206\u6790\u8868\u8fbe\u5f0f\u76f8\u6bd4\uff0c\u6548\u679c\u5f88\u597d\u3002\n\n// \u73b0\u5728\u6211\u4eec\u5df2\u7ecf\u5f62\u6210\u4e86\u51fd\u6570\u53ca\u5176\u5bfc\u6570\u7684\u7b26\u53f7\u8868\u8fbe\u5f0f\uff0c\u6211\u4eec\u60f3\u5bf9\u51fd\u6570\u7684\u4e3b\u8981\u53c2\u6570`x`\u548c`y`\u7684\u6570\u5b57\u503c\u8fdb\u884c\u8bc4\u4f30\u3002\u4e3a\u4e86\u8fbe\u5230\u8fd9\u4e2a\u76ee\u7684\uff0c\u6211\u4eec\u6784\u9020\u4e86\u4e00\u4e2a*\u66ff\u4ee3\u56fe*\uff0c\u5b83\u5c06\u7b26\u53f7\u503c\u6620\u5c04\u5230\u5b83\u4eec\u7684\u6570\u5b57\u5bf9\u5e94\u503c\u3002\n\n      const Differentiation::SD::types::substitution_map substitution_map = \n        Differentiation::SD::make_substitution_map( \n          std::pair<Differentiation::SD::Expression, double>{x_sd, x}, \n          std::pair<Differentiation::SD::Expression, double>{y_sd, y}); \n\n// \u8fd9\u4e2a\u8fc7\u7a0b\u7684\u6700\u540e\u4e00\u6b65\u662f\u5c06\u6240\u6709\u7684\u7b26\u53f7\u53d8\u91cf\u548c\u64cd\u4f5c\u8f6c\u6362\u6210\u6570\u503c\uff0c\u5e76\u4ea7\u751f\u8fd9\u4e2a\u64cd\u4f5c\u7684\u6570\u503c\u7ed3\u679c\u3002\u4e3a\u4e86\u505a\u5230\u8fd9\u4e00\u70b9\uff0c\u6211\u4eec\u5728\u4e0a\u9762\u5df2\u7ecf\u63d0\u5230\u7684\u6b65\u9aa4\u4e2d\uff0c\u5c06\u66ff\u6362\u56fe\u4e0e\u7b26\u53f7\u53d8\u91cf\u7ed3\u5408\u8d77\u6765\u3002\"\u66ff\u6362\"\u3002\n\n// \u4e00\u65e6\u6211\u4eec\u628a\u8fd9\u4e2a\u66ff\u6362\u56fe\u4f20\u9012\u7ed9CAS\uff0c\u5b83\u5c31\u4f1a\u628a\u7b26\u53f7\u53d8\u91cf\u7684\u6bcf\u4e2a\u5b9e\u4f8b\uff08\u6216\u8005\u66f4\u4e00\u822c\u7684\uff0c\u5b50\u8868\u8fbe\u5f0f\uff09\u66ff\u6362\u6210\u5b83\u7684\u6570\u5b57\u5bf9\u5e94\u7269\uff0c\u7136\u540e\u628a\u8fd9\u4e9b\u7ed3\u679c\u5728\u64cd\u4f5c\u6811\u4e0a\u4f20\u64ad\uff0c\u5982\u679c\u53ef\u80fd\u7684\u8bdd\uff0c\u7b80\u5316\u6811\u4e0a\u7684\u6bcf\u4e2a\u8282\u70b9\u3002\u5982\u679c\u8fd0\u7b97\u6811\u88ab\u7b80\u5316\u4e3a\u4e00\u4e2a\u5355\u4e00\u7684\u503c\uff08\u4e5f\u5c31\u662f\u8bf4\uff0c\u6211\u4eec\u5df2\u7ecf\u5c06\u6240\u6709\u7684\u72ec\u7acb\u53d8\u91cf\u66ff\u6362\u6210\u4e86\u5b83\u4eec\u7684\u6570\u5b57\u5bf9\u5e94\u503c\uff09\uff0c\u90a3\u4e48\u8bc4\u4f30\u5c31\u5b8c\u6210\u4e86\u3002\n\n// \u7531\u4e8eC++\u7684\u5f3a\u7c7b\u578b\u7279\u6027\uff0c\u6211\u4eec\u9700\u8981\u6307\u793aCAS\u5c06\u5176\u5bf9\u7ed3\u679c\u7684\u8868\u793a\u8f6c\u6362\u4e3a\u5185\u5728\u7684\u6570\u636e\u7c7b\u578b\uff08\u672c\u4f8b\u4e2d\u4e3a`double'\uff09\u3002\u8fd9\u5c31\u662f \"\u8bc4\u4f30 \"\u6b65\u9aa4\uff0c\u901a\u8fc7\u6a21\u677f\u7c7b\u578b\u6211\u4eec\u5b9a\u4e49\u4e86\u8fd9\u4e2a\u8fc7\u7a0b\u7684\u8fd4\u56de\u7c7b\u578b\u3002\u65b9\u4fbf\u7684\u662f\uff0c\u5982\u679c\u6211\u4eec\u786e\u5b9a\u6211\u4eec\u5df2\u7ecf\u8fdb\u884c\u4e86\u5b8c\u6574\u7684\u66ff\u6362\uff0c\u8fd9\u4e24\u4e2a\u6b65\u9aa4\u53ef\u4ee5\u4e00\u6b21\u5b8c\u6210\u3002\n\n      const double computed_f = \n        f_sd.substitute_and_evaluate<double>(substitution_map); \n\n      AssertThrow(std::abs(f(x, y) - computed_f) < tol, \n                  ExcMessage(std::string(\"Incorrect value computed for f. \") + \n                             std::string(\"Hand-calculated value: \") + \n                             Utilities::to_string(f(x, y)) + \n                             std::string(\" ; \") + \n                             std::string(\"Value computed by AD: \") + \n                             Utilities::to_string(computed_f))); \n\n// \u6211\u4eec\u53ef\u4ee5\u5bf9\u7b2c\u4e00\u4e2a\u5bfc\u6570\u505a\u540c\u6837\u7684\u5904\u7406......\n\n      const double computed_df_dx = \n        df_dx_sd.substitute_and_evaluate<double>(substitution_map); \n      const double computed_df_dy = \n        df_dy_sd.substitute_and_evaluate<double>(substitution_map); \n\n      AssertThrow(std::abs(df_dx(x, y) - computed_df_dx) < tol, \n                  ExcMessage( \n                    std::string(\"Incorrect value computed for df/dx. \") + \n                    std::string(\"Hand-calculated value: \") + \n                    Utilities::to_string(df_dx(x, y)) + std::string(\" ; \") + \n                    std::string(\"Value computed by AD: \") + \n                    Utilities::to_string(computed_df_dx))); \n      AssertThrow(std::abs(df_dy(x, y) - computed_df_dy) < tol, \n \n \n \n \n \n                    Utilities::to_string(computed_df_dy))); \n\n// ...\u4ee5\u53ca\u4e8c\u9636\u5bfc\u6570\u3002\u8bf7\u6ce8\u610f\uff0c\u6211\u4eec\u53ef\u4ee5\u5728\u8fd9\u4e9b\u64cd\u4f5c\u4e2d\u91cd\u590d\u4f7f\u7528\u76f8\u540c\u7684\u66ff\u6362\u56fe\uff0c\u56e0\u4e3a\u6211\u4eec\u5e0c\u671b\u9488\u5bf9\u76f8\u540c\u7684`x`\u548c`y`\u503c\u8bc4\u4f30\u6240\u6709\u8fd9\u4e9b\u51fd\u6570\u3002\u4fee\u6539\u7f6e\u6362\u56fe\u4e2d\u7684\u503c\uff0c\u5c31\u53ef\u4ee5\u5f97\u5230\u76f8\u540c\u7684\u7b26\u53f7\u8868\u8fbe\u5f0f\u7684\u8bc4\u4f30\u7ed3\u679c\uff0c\u540c\u65f6\u7ed9\u81ea\u53d8\u91cf\u5206\u914d\u4e0d\u540c\u7684\u503c\u3002\u6211\u4eec\u4e5f\u53ef\u4ee5\u5f88\u9ad8\u5174\u5730\u8ba9\u6bcf\u4e2a\u53d8\u91cf\u5728\u4e00\u6b21\u4e2d\u4ee3\u8868\u4e00\u4e2a\u5b9e\u503c\uff0c\u5728\u4e0b\u4e00\u6b21\u4e2d\u4ee3\u8868\u4e00\u4e2a\u590d\u503c\u3002\n\n      const double computed_d2f_dx_dx = \n        d2f_dx_dx_sd.substitute_and_evaluate<double>(substitution_map); \n      const double computed_d2f_dx_dy = \n        d2f_dx_dy_sd.substitute_and_evaluate<double>(substitution_map); \n      const double computed_d2f_dy_dx = \n        d2f_dy_dx_sd.substitute_and_evaluate<double>(substitution_map); \n      const double computed_d2f_dy_dy = \n        d2f_dy_dy_sd.substitute_and_evaluate<double>(substitution_map); \n\n      AssertThrow(std::abs(d2f_dx_dx(x, y) - computed_d2f_dx_dx) < tol, \n                  ExcMessage( \n                    std::string(\"Incorrect value computed for d2f/dx_dx. \") + \n                    std::string(\"Hand-calculated value: \") + \n                    Utilities::to_string(d2f_dx_dx(x, y)) + std::string(\" ; \") + \n                    std::string(\"Value computed by SD: \") + \n                    Utilities::to_string(computed_d2f_dx_dx))); \n      AssertThrow(std::abs(d2f_dx_dy(x, y) - computed_d2f_dx_dy) < tol, \n                  ExcMessage( \n                    std::string(\"Incorrect value computed for d2f/dx_dy. \") + \n                    std::string(\"Hand-calculated value: \") + \n                    Utilities::to_string(d2f_dx_dy(x, y)) + std::string(\" ; \") + \n                    std::string(\"Value computed by SD: \") + \n                    Utilities::to_string(computed_d2f_dx_dy))); \n      AssertThrow(std::abs(d2f_dy_dx(x, y) - computed_d2f_dy_dx) < tol, \n                  ExcMessage( \n                    std::string(\"Incorrect value computed for d2f/dy_dx. \") + \n                    std::string(\"Hand-calculated value: \") + \n                    Utilities::to_string(d2f_dy_dx(x, y)) + std::string(\" ; \") + \n                    std::string(\"Value computed by SD: \") + \n                    Utilities::to_string(computed_d2f_dy_dx))); \n      AssertThrow(std::abs(d2f_dy_dy(x, y) - computed_d2f_dy_dy) < tol, \n                  ExcMessage( \n                    std::string(\"Incorrect value computed for d2f/dy_dy. \") + \n                    std::string(\"Hand-calculated value: \") + \n                    Utilities::to_string(d2f_dy_dy(x, y)) + std::string(\" ; \") + \n                    std::string(\"Value computed by SD: \") + \n                    Utilities::to_string(computed_d2f_dy_dy))); \n    } \n// @sect4{The SimpleExample::run() function}  \n\n// \u7528\u6765\u9a71\u52a8\u8fd9\u4e9b\u521d\u59cb\u4f8b\u5b50\u7684\u51fd\u6570\u662f\u76f4\u63a5\u7684\u3002\u6211\u4eec\u5c06\u4efb\u610f\u9009\u62e9\u4e00\u4e9b\u503c\u6765\u8bc4\u4f30\u8be5\u51fd\u6570\uff08\u5c3d\u7ba1\u77e5\u9053`x = 0`\u662f\u4e0d\u5141\u8bb8\u7684\uff09\uff0c\u7136\u540e\u5c06\u8fd9\u4e9b\u503c\u4f20\u9012\u7ed9\u4f7f\u7528AD\u548cSD\u6846\u67b6\u7684\u51fd\u6570\u3002\n\n    void run() \n    { \n      const double x = 1.23; \n      const double y = 0.91; \n\n      std::cout << \"Simple example using automatic differentiation...\" \n                << std::endl; \n      run_and_verify_ad(x, y); \n      std::cout << \"... all calculations are correct!\" << std::endl; \n\n      std::cout << \"Simple example using symbolic differentiation.\" \n                << std::endl; \n      run_and_verify_sd(x, y); \n      std::cout << \"... all calculations are correct!\" << std::endl; \n    } \n\n  } // namespace SimpleExample \n// @sect3{A more complex example: Using automatic and symbolic differentiation to compute derivatives at continuum points}  \n\n// \u73b0\u5728\u6211\u4eec\u5df2\u7ecf\u4ecb\u7ecd\u4e86\u81ea\u52a8\u5206\u5316\u548c\u7b26\u53f7\u5206\u5316\u80cc\u540e\u7684\u539f\u7406\uff0c\u6211\u4eec\u5c06\u901a\u8fc7\u5236\u5b9a\u4e24\u4e2a\u8026\u5408\u7684\u78c1\u529b\u5b66\u6784\u6210\u6cd5\u5c06\u5176\u4ed8\u8bf8\u5b9e\u65bd\uff1a\u4e00\u4e2a\u662f\u4e0e\u901f\u7387\u65e0\u5173\u7684\uff0c\u53e6\u4e00\u4e2a\u5219\u8868\u73b0\u4e3a\u4e0e\u901f\u7387\u6709\u5173\u7684\u884c\u4e3a\u3002\n\n// \u6b63\u5982\u4f60\u5728\u4ecb\u7ecd\u4e2d\u8bb0\u5f97\u7684\u90a3\u6837\uff0c\u6211\u4eec\u5c06\u8003\u8651\u7684\u6750\u6599\u6784\u6210\u6cd5\u5219\u8981\u6bd4\u4e0a\u9762\u7684\u7b80\u5355\u4f8b\u5b50\u590d\u6742\u5f97\u591a\u3002\u8fd9\u4e0d\u4ec5\u4ec5\u662f\u56e0\u4e3a\u6211\u4eec\u5c06\u8003\u8651\u7684\u51fd\u6570 $\\psi_{0}$ \u7684\u5f62\u5f0f\uff0c\u800c\u4e14\u7279\u522b\u662f\u56e0\u4e3a $\\psi_{0}$ \u4e0d\u4ec5\u4ec5\u53d6\u51b3\u4e8e\u4e24\u4e2a\u6807\u91cf\u53d8\u91cf\uff0c\u800c\u662f\u53d6\u51b3\u4e8e\u4e00\u5927\u5806*\u5f20\u91cf\uff0c\u6bcf\u4e2a\u5f20\u91cf\u90fd\u6709\u51e0\u4e2a\u7ec4\u6210\u90e8\u5206\u3002\u5728\u67d0\u4e9b\u60c5\u51b5\u4e0b\uff0c\u8fd9\u4e9b\u662f*\u5bf9\u79f0*\u5f20\u91cf\uff0c\u5bf9\u4e8e\u8fd9\u4e9b\u5f20\u91cf\u6765\u8bf4\uff0c\u53ea\u6709\u4e00\u4e2a\u5206\u91cf\u5b50\u96c6\u5b9e\u9645\u4e0a\u662f\u72ec\u7acb\u7684\uff0c\u6211\u4eec\u5fc5\u987b\u8003\u8651\u8ba1\u7b97 $\\frac{\\partial\\psi_{0}}{\\partial \\mathbf{C}}$ \u8fd9\u6837\u7684\u5bfc\u6570\u7684\u5b9e\u9645\u610f\u4e49\uff0c\u5176\u4e2d $\\mathbf C$ \u662f\u4e00\u4e2a\u5bf9\u79f0\u5f20\u91cf\u3002\u5e0c\u671b\u8fd9\u4e00\u5207\u5c06\u5728\u4e0b\u9762\u53d8\u5f97\u6e05\u6670\u3002\u6211\u4eec\u4e5f\u5c06\u6e05\u695a\u5730\u770b\u5230\uff0c\u7528\u624b\u6765\u505a\u8fd9\u4ef6\u4e8b\uff0c\u5728\u6700\u597d\u7684\u60c5\u51b5\u4e0b\uff0c\u5c06\u662f\u975e\u5e38*\u7e41\u7410\uff0c\u800c\u5728\u6700\u574f\u7684\u60c5\u51b5\u4e0b\uff0c\u5145\u6ee1\u4e86\u96be\u4ee5\u53d1\u73b0\u7684\u9519\u8bef\u3002\n\n  namespace CoupledConstitutiveLaws \n  { \n// @sect4{Constitutive parameters}  \n\n// \u6211\u4eec\u5148\u63cf\u8ff0\u4e00\u4e0b\u80fd\u91cf\u51fd\u6570\u63cf\u8ff0\u4e2d\u51fa\u73b0\u7684\u5404\u79cd\u6750\u6599\u53c2\u6570  $\\psi_{0}$  \u3002\n\n// ConstitutiveParameters\u7c7b\u88ab\u7528\u6765\u4fdd\u5b58\u8fd9\u4e9b\u6570\u503c\u3002\u6240\u6709\u53c2\u6570\u7684\u503c\uff08\u5305\u62ec\u6784\u6210\u53c2\u6570\u548c\u6d41\u53d8\u53c2\u6570\uff09\u90fd\u6765\u81ea\u4e8e  @cite Pelteret2018a  \uff0c\u5e76\u7ed9\u51fa\u4e86\u80fd\u591f\u4ea7\u751f\u5927\u81f4\u4ee3\u8868\u771f\u5b9e\u7684\u3001\u5b9e\u9a8c\u5ba4\u5236\u9020\u7684\u78c1\u6d3b\u6027\u805a\u5408\u7269\u7684\u6784\u6210\u54cd\u5e94\u7684\u503c\uff0c\u5f53\u7136\uff0c\u8fd9\u91cc\u4f7f\u7528\u7684\u5177\u4f53\u6570\u503c\u5bf9\u672c\u7a0b\u5e8f\u7684\u76ee\u7684\u6ca1\u6709\u5f71\u54cd\u3002\n\n// \u524d\u56db\u4e2a\u6784\u6210\u53c2\u6570\u5206\u522b\u4ee3\u8868\n\n// \u5f39\u6027\u526a\u5207\u6a21\u91cf $\\mu_{e}$  \u3002\n\n// --\u78c1\u9971\u548c\u65f6\u7684\u5f39\u6027\u526a\u5207\u6a21\u91cf  $\\mu_{e}^{\\infty}$  \u3002\n\n// - \u5f39\u6027\u526a\u5207\u6a21\u91cf\u7684\u9971\u548c\u78c1\u573a\u5f3a\u5ea6  $h_{e}^{\\text{sat}}$  \uff0c\u4ee5\u53ca\n\n// \u6cca\u677e\u6bd4  $\\nu$  \u3002\n\n    class ConstitutiveParameters : public ParameterAcceptor \n    { \n    public: \n      ConstitutiveParameters(); \n\n      double mu_e       = 30.0e3; \n      double mu_e_inf   = 250.0e3; \n      double mu_e_h_sat = 212.2e3; \n      double nu_e       = 0.49; \n\n// \u63a5\u4e0b\u6765\u7684\u56db\u4e2a\uff0c\u53ea\u4e0e\u901f\u7387\u76f8\u5173\u7684\u6750\u6599\u6709\u5173\uff0c\u662f\u4ee5\u4e0b\u7684\u53c2\u6570\n\n// - \u7c98\u5f39\u6027\u526a\u5207\u6a21\u91cf  $\\mu_{v}$  \u3002\n\n// - \u78c1\u9971\u548c\u65f6\u7684\u7c98\u5f39\u6027\u526a\u5207\u6a21\u91cf  $\\mu_{v}^{\\infty}$  \u3002\n\n// \u7c98\u5f39\u6027\u526a\u5207\u6a21\u91cf\u7684\u9971\u548c\u78c1\u573a\u5f3a\u5ea6 $h_{v}^{\\text{sat}}$  \uff0c\u4ee5\u53ca\n\n// --\u7279\u5f81\u677e\u5f1b\u65f6\u95f4  $\\tau$  \u3002\n\n      double mu_v       = 20.0e3; \n      double mu_v_inf   = 35.0e3; \n      double mu_v_h_sat = 92.84e3; \n      double tau_v      = 0.6; \n\n// \u6700\u540e\u4e00\u4e2a\u53c2\u6570\u662f\u76f8\u5bf9\u78c1\u5bfc\u7387  $\\mu_{r}$  \u3002\n\n      double mu_r = 6.0; \n\n      bool initialized = false; \n    }; \n\n// \u53c2\u6570\u662f\u901a\u8fc7ParameterAcceptor\u6846\u67b6\u521d\u59cb\u5316\u7684\uff0c\u8be5\u6846\u67b6\u5728  step-60  \u4e2d\u6709\u8be6\u7ec6\u8ba8\u8bba\u3002\n\n    ConstitutiveParameters::ConstitutiveParameters() \n      : ParameterAcceptor(\"/Coupled Constitutive Laws/Constitutive Parameters/\") \n    { \n      add_parameter(\"Elastic shear modulus\", mu_e); \n      add_parameter(\"Elastic shear modulus at magnetic saturation\", mu_e_inf); \n      add_parameter( \n        \"Saturation magnetic field strength for elastic shear modulus\", \n        mu_e_h_sat); \n      add_parameter(\"Poisson ratio\", nu_e); \n\n      add_parameter(\"Viscoelastic shear modulus\", mu_v); \n      add_parameter(\"Viscoelastic shear modulus at magnetic saturation\", \n                    mu_v_inf); \n      add_parameter( \n        \"Saturation magnetic field strength for viscoelastic shear modulus\", \n        mu_v_h_sat); \n      add_parameter(\"Characteristic relaxation time\", tau_v); \n\n      add_parameter(\"Relative magnetic permeability\", mu_r); \n\n      parse_parameters_call_back.connect([&]() { initialized = true; }); \n    } \n// @sect4{Constitutive laws: Base class}  \n\n// \u7531\u4e8e\u6211\u4eec\u5c06\u4e3a\u540c\u4e00\u7c7b\u6750\u6599\u5236\u5b9a\u4e24\u79cd\u6784\u6210\u6cd5\uff0c\u56e0\u6b64\u5b9a\u4e49\u4e00\u4e2a\u57fa\u7c7b\u4ee5\u786e\u4fdd\u5b83\u4eec\u6709\u7edf\u4e00\u7684\u63a5\u53e3\u662f\u6709\u610f\u4e49\u7684\u3002\n\n// \u7c7b\u7684\u58f0\u660e\u4ece\u6784\u9020\u51fd\u6570\u5f00\u59cb\uff0c\u5b83\u5c06\u63a5\u53d7\u4e00\u7ec4\u6784\u6210\u53c2\u6570\uff0c\u8fd9\u4e9b\u53c2\u6570\u4e0e\u6750\u6599\u5b9a\u5f8b\u672c\u8eab\u4e00\u8d77\u51b3\u5b9a\u4e86\u6750\u6599\u7684\u54cd\u5e94\u3002\n\n    template <int dim> \n    class Coupled_Magnetomechanical_Constitutive_Law_Base \n    { \n    public: \n      Coupled_Magnetomechanical_Constitutive_Law_Base( \n        const ConstitutiveParameters &constitutive_parameters); \n\n// \u6211\u4eec\u5c06\u5728\u4e00\u4e2a\u65b9\u6cd5\u4e2d\u8ba1\u7b97\u548c\u5b58\u50a8\u8fd9\u4e9b\u503c\uff0c\u800c\u4e0d\u662f\u968f\u610f\u8ba1\u7b97\u548c\u8fd4\u56de\u52a8\u529b\u5b66\u53d8\u91cf\u6216\u5176\u7ebf\u6027\u5316\u3002\u7136\u540e\u8fd9\u4e9b\u7f13\u5b58\u7684\u7ed3\u679c\u5c06\u5728\u8bf7\u6c42\u65f6\u8fd4\u56de\u3002\u6211\u4eec\u5c06\u628a\u4e3a\u4ec0\u4e48\u8981\u8fd9\u6837\u505a\u7684\u7cbe\u786e\u89e3\u91ca\u63a8\u8fdf\u5230\u4ee5\u540e\u7684\u9636\u6bb5\u3002\u73b0\u5728\u91cd\u8981\u7684\u662f\u770b\u5230\u8fd9\u4e2a\u51fd\u6570\u63a5\u53d7\u6240\u6709\u7684\u573a\u53d8\u91cf\uff0c\u5373\u78c1\u573a\u77e2\u91cf $\\boldsymbol{\\mathbb{H}}$ \u548c\u53f3Cauchy-Green\u53d8\u5f62\u5f20\u91cf $\\mathbf{C}$ \uff0c\u4ee5\u53ca\u65f6\u95f4\u79bb\u6563\u5668\u3002\u9664\u4e86 @p constitutive_parameters, \u4e4b\u5916\uff0c\u8fd9\u4e9b\u90fd\u662f\u8ba1\u7b97\u6750\u6599\u54cd\u5e94\u6240\u9700\u7684\u57fa\u672c\u91cf\u3002\n\n      virtual void update_internal_data(const SymmetricTensor<2, dim> &C, \n                                        const Tensor<1, dim> &         H, \n                                        const DiscreteTime &time) = 0; \n\n// \u63a5\u4e0b\u6765\u7684\u51e0\u4e2a\u51fd\u6570\u63d0\u4f9b\u4e86\u63a2\u6d4b\u6750\u6599\u54cd\u5e94\u7684\u63a5\u53e3\uff0c\u8fd9\u4e9b\u54cd\u5e94\u662f\u7531\u4e8e\u65bd\u52a0\u7684\u53d8\u5f62\u548c\u78c1\u8377\u8f7d\u5f15\u8d77\u7684\u3002\n\n// \u7531\u4e8e\u8be5\u7c7b\u6750\u6599\u53ef\u4ee5\u7528\u81ea\u7531\u80fd $\\psi_{0}$ \u6765\u8868\u793a\uff0c\u6211\u4eec\u53ef\u4ee5\u8ba1\u7b97\u51fa......\n\n      virtual double get_psi() const = 0; \n\n// ... \u4ee5\u53ca\u4e24\u4e2a\u52a8\u529b\u5b66\u91cf\u3002\n\n// \u78c1\u611f\u5e94\u77e2\u91cf  $\\boldsymbol{\\mathbb{B}}$  \uff0c\u548c\n\n// --\u76ae\u5965\u62c9-\u57fa\u5c14\u970d\u592b\u603b\u5e94\u529b\u5f20\u91cf $\\mathbf{S}^{\\text{tot}}$  \u3002\n      virtual Tensor<1, dim> get_B() const = 0; \n\n      virtual SymmetricTensor<2, dim> get_S() const = 0; \n\n// .......\u4ee5\u53ca\u52a8\u529b\u5b66\u91cf\u7684\u7ebf\u6027\u5316\uff0c\u5b83\u4eec\u662f\u3002\n\n// --\u78c1\u9759\u529b\u5b66\u6b63\u5207\u5f20\u91cf  $\\mathbb{D}$  \u3002\n\n// - \u603b\u7684\u53c2\u8003\u6027\u78c1\u5f39\u6027\u8026\u5408\u5f20\u91cf $\\mathfrak{P}^{\\text{tot}}$  \uff0c\u4ee5\u53ca\n\n// --\u603b\u7684\u53c2\u8003\u5f39\u6027\u6b63\u5207\u5f20\u91cf $\\mathcal{H}^{\\text{tot}}$  \u3002\n\n      virtual SymmetricTensor<2, dim> get_DD() const = 0; \n\n      virtual Tensor<3, dim> get_PP() const = 0; \n\n      virtual SymmetricTensor<4, dim> get_HH() const = 0; \n\n// \u6211\u4eec\u8fd8\u5c06\u5b9a\u4e49\u4e00\u4e2a\u65b9\u6cd5\uff0c\u4e3a\u8fd9\u4e2a\u7c7b\u5b9e\u4f8b\u63d0\u4f9b\u4e00\u4e2a\u673a\u5236\uff0c\u5728\u8fdb\u5165\u4e0b\u4e00\u4e2a\u65f6\u95f4\u6bb5\u4e4b\u524d\u505a\u4efb\u4f55\u989d\u5916\u7684\u4efb\u52a1\u3002\u540c\u6837\uff0c\u8fd9\u6837\u505a\u7684\u539f\u56e0\u5c06\u5728\u7a0d\u540e\u53d8\u5f97\u6e05\u6670\u3002\n\n      virtual void update_end_of_timestep() \n      {} \n\n// \u5728\u8be5\u7c7b\u7684`\u4fdd\u62a4'\u90e8\u5206\uff0c\u6211\u4eec\u5b58\u50a8\u4e86\u4e00\u4e2a\u5bf9\u652f\u914d\u6750\u6599\u54cd\u5e94\u7684\u6784\u6210\u53c2\u6570\u5b9e\u4f8b\u7684\u5f15\u7528\u3002\u4e3a\u4e86\u65b9\u4fbf\u8d77\u89c1\uff0c\u6211\u4eec\u8fd8\u5b9a\u4e49\u4e86\u4e00\u4e9b\u51fd\u6570\u6765\u8fd4\u56de\u5404\u79cd\u6784\u6210\u53c2\u6570\uff08\u5305\u62ec\u660e\u786e\u5b9a\u4e49\u7684\uff0c\u4ee5\u53ca\u8ba1\u7b97\u7684\uff09\u3002\n\n\u4e0e\u6750\u6599\u7684\u5f39\u6027\u54cd\u5e94\u6709\u5173\u7684\u53c2\u6570\u4f9d\u6b21\u662f\uff1a//\u3002\n\n// - \u5f39\u6027\u526a\u5207\u6a21\u91cf\u3002\n\n// - \u9971\u548c\u78c1\u573a\u4e0b\u7684\u5f39\u6027\u526a\u5207\u6a21\u91cf\u3002\n\n// - \u5f39\u6027\u526a\u5207\u6a21\u91cf\u7684\u9971\u548c\u78c1\u573a\u5f3a\u5ea6\u3002\n\n// - \u6cca\u677e\u6bd4\u3002\n\n// \u6cca\u677e\u6bd4\u3001Lam&eacute;\u53c2\u6570\uff0c\u4ee5\u53ca\n\n// \u4f53\u79ef\u6a21\u91cf\u3002\n\n    protected: \n      const ConstitutiveParameters &constitutive_parameters; \n\n      double get_mu_e() const; \n\n      double get_mu_e_inf() const; \n\n      double get_mu_e_h_sat() const; \n\n      double get_nu_e() const; \n\n      double get_lambda_e() const; \n\n      double get_kappa_e() const; \n\n// \u4e0e\u6750\u6599\u7684\u5f39\u6027\u54cd\u5e94\u6709\u5173\u7684\u53c2\u6570\u4f9d\u6b21\u662f\n\n// - \u7c98\u5f39\u6027\u526a\u5207\u6a21\u91cf\u3002\n\n// -- \u78c1\u9971\u548c\u65f6\u7684\u7c98\u5f39\u6027\u526a\u5207\u6a21\u91cf\u3002\n\n// - \u7c98\u5f39\u6027\u526a\u5207\u6a21\u91cf\u7684\u9971\u548c\u78c1\u573a\u5f3a\u5ea6\uff0c\u4ee5\u53ca\n\n\u7c98\u5f39\u6027\u526a\u5207\u6a21\u91cf\u7684\u9971\u548c\u78c1\u573a\u5f3a\u5ea6\uff0c\u548c//--\u7279\u5f81\u677e\u5f1b\u65f6\u95f4\u3002\n\n      double get_mu_v() const; \n\n      double get_mu_v_inf() const; \n\n      double get_mu_v_h_sat() const; \n\n      double get_tau_v() const; \n\n// \u4e0e\u6750\u6599\u7684\u78c1\u54cd\u5e94\u6709\u5173\u7684\u53c2\u6570\u4f9d\u6b21\u662f\uff1a\u3002\n\n// \u76f8\u5bf9\u78c1\u5bfc\u7387\uff0c\u4ee5\u53ca\n\n// - \u78c1\u5bfc\u7387\u5e38\u6570 $\\mu_{0}$ \uff08\u5176\u5b9e\u4e0d\u662f\u4e00\u4e2a\u6750\u6599\u5e38\u6570\uff0c\u800c\u662f\u4e00\u4e2a\u666e\u904d\u7684\u5e38\u6570\uff0c\u4e3a\u4e86\u7b80\u5355\u8d77\u89c1\uff0c\u6211\u4eec\u5728\u8fd9\u91cc\u5206\u7ec4\uff09\u3002\n\n// \u6211\u4eec\u8fd8\u5c06\u5b9e\u73b0\u4e00\u4e2a\u51fd\u6570\uff0c\u4ece\u65f6\u95f4\u79bb\u6563\u6027\u4e2d\u8fd4\u56de\u65f6\u95f4\u6b65\u957f\u3002\n\n      double get_mu_r() const; \n\n      constexpr double get_mu_0() const; \n      double           get_delta_t(const DiscreteTime &time) const; \n    }; \n\n// \u5728\u4e0b\u6587\u4e2d\uff0c\u8ba9\u6211\u4eec\u4ece\u5b9e\u73b0\u521a\u624d\u5b9a\u4e49\u7684\u7c7b\u7684\u51e0\u4e2a\u76f8\u5bf9\u7410\u788e\u7684\u6210\u5458\u51fd\u6570\u5f00\u59cb\u3002\n\n    template <int dim> \n    Coupled_Magnetomechanical_Constitutive_Law_Base<dim>:: \n      Coupled_Magnetomechanical_Constitutive_Law_Base( \n        const ConstitutiveParameters &constitutive_parameters) \n      : constitutive_parameters(constitutive_parameters) \n    { \n      Assert(get_kappa_e() > 0, ExcInternalError()); \n    } \n\n    template <int dim> \n    double \n    Coupled_Magnetomechanical_Constitutive_Law_Base<dim>::get_mu_e() const \n    { \n      return constitutive_parameters.mu_e; \n    } \n\n    template <int dim> \n    double \n    Coupled_Magnetomechanical_Constitutive_Law_Base<dim>::get_mu_e_inf() const \n    { \n      return constitutive_parameters.mu_e_inf; \n    } \n\n    template <int dim> \n    double \n    Coupled_Magnetomechanical_Constitutive_Law_Base<dim>::get_mu_e_h_sat() const \n    { \n      return constitutive_parameters.mu_e_h_sat; \n    } \n\n    template <int dim> \n    double \n    Coupled_Magnetomechanical_Constitutive_Law_Base<dim>::get_nu_e() const \n    { \n      return constitutive_parameters.nu_e; \n    } \n\n    template <int dim> \n    double \n    Coupled_Magnetomechanical_Constitutive_Law_Base<dim>::get_lambda_e() const \n    { \n      return 2.0 * get_mu_e() * get_nu_e() / (1.0 - 2.0 * get_nu_e()); \n    } \n\n    template <int dim> \n    double \n    Coupled_Magnetomechanical_Constitutive_Law_Base<dim>::get_kappa_e() const \n    { \n      return (2.0 * get_mu_e() * (1.0 + get_nu_e())) / \n             (3.0 * (1.0 - 2.0 * get_nu_e())); \n    } \n\n    template <int dim> \n    double \n    Coupled_Magnetomechanical_Constitutive_Law_Base<dim>::get_mu_v() const \n    { \n      return constitutive_parameters.mu_v; \n    } \n\n    template <int dim> \n    double \n    Coupled_Magnetomechanical_Constitutive_Law_Base<dim>::get_mu_v_inf() const \n    { \n      return constitutive_parameters.mu_v_inf; \n    } \n\n    template <int dim> \n    double \n    Coupled_Magnetomechanical_Constitutive_Law_Base<dim>::get_mu_v_h_sat() const \n    { \n      return constitutive_parameters.mu_v_h_sat; \n    } \n\n    template <int dim> \n    double \n    Coupled_Magnetomechanical_Constitutive_Law_Base<dim>::get_tau_v() const \n    { \n      return constitutive_parameters.tau_v; \n    } \n\n    template <int dim> \n    double \n    Coupled_Magnetomechanical_Constitutive_Law_Base<dim>::get_mu_r() const \n    { \n      return constitutive_parameters.mu_r; \n    } \n\n    template <int dim> \n    constexpr double \n    Coupled_Magnetomechanical_Constitutive_Law_Base<dim>::get_mu_0() const \n    { \n      return 4.0 * numbers::PI * 1e-7; \n    } \n\n    template <int dim> \n    double Coupled_Magnetomechanical_Constitutive_Law_Base<dim>::get_delta_t( \n      const DiscreteTime &time) const \n    { \n      return time.get_previous_step_size(); \n    } \n// @sect4{Magnetoelastic constitutive law (using automatic differentiation)}  \n\n// \u6211\u4eec\u5c06\u9996\u5148\u8003\u8651\u4e00\u79cd\u975e\u8017\u6563\u6027\u6750\u6599\uff0c\u5373\u53d7\u78c1\u8d85\u5f39\u6027\u6784\u6210\u6cd5\u5219\u652f\u914d\u7684\u6750\u6599\uff0c\u5728\u6d78\u5165\u78c1\u573a\u65f6\u8868\u73b0\u51fa\u50f5\u786c\u3002\u6b63\u5982\u4ecb\u7ecd\u4e2d\u6240\u8ff0\uff0c\u8fd9\u79cd\u6750\u6599\u7684\u50a8\u80fd\u5bc6\u5ea6\u51fd\u6570\u53ef\u80fd\u7531\n// @f[\n//    \\psi_{0} \\left( \\mathbf{C}, \\boldsymbol{\\mathbb{H}} \\right)\n//  = \\frac{1}{2} \\mu_{e} f_{\\mu_{e}} \\left( \\boldsymbol{\\mathbb{H}} \\right)\n//      \\left[ \\text{tr}(\\mathbf{C}) - d - 2 \\ln (\\text{det}(\\mathbf{F}))\n//      \\right]\n//  + \\lambda_{e} \\ln^{2} \\left(\\text{det}(\\mathbf{F}) \\right)\n//  - \\frac{1}{2} \\mu_{0} \\mu_{r} \\text{det}(\\mathbf{F})\n//      \\left[ \\boldsymbol{\\mathbb{H}} \\cdot \\mathbf{C}^{-1} \\cdot\n//      \\boldsymbol{\\mathbb{H}} \\right]\n//  @f]\n//  \u548c\n//  @f[\n//   f_{\\mu_{e}} \\left( \\boldsymbol{\\mathbb{H}} \\right)\n//  = 1 + \\left[ \\frac{\\mu_{e}^{\\infty}}{\\mu_{e}} - 1 \\right]\n//      \\tanh \\left( 2 \\frac{\\boldsymbol{\\mathbb{H}} \\cdot\n//      \\boldsymbol{\\mathbb{H}}}\n//        {\\left(h_{e}^{\\text{sat}}\\right)^{2}} \\right) .\n//  @f]\n//  \u7ed9\u51fa\u3002\n\n// \u73b0\u5728\u6765\u770b\u770b\u5b9e\u73b0\u8fd9\u79cd\u884c\u4e3a\u7684\u7c7b\u3002\u7531\u4e8e\u6211\u4eec\u5e0c\u671b\u8fd9\u4e2a\u7c7b\u80fd\u5b8c\u5168\u63cf\u8ff0\u4e00\u79cd\u6750\u6599\uff0c\u6240\u4ee5\u6211\u4eec\u5c06\u5b83\u6807\u8bb0\u4e3a \"final\"\uff0c\u8fd9\u6837\u7ee7\u627f\u6811\u5c31\u5728\u8fd9\u91cc\u7ec8\u6b62\u4e86\u3002\u5728\u7c7b\u7684\u9876\u90e8\uff0c\u6211\u4eec\u5b9a\u4e49\u4e86\u8f85\u52a9\u7c7b\u578b\uff0c\u6211\u4eec\u5c06\u5728\u6807\u91cf\u80fd\u91cf\u5bc6\u5ea6\u51fd\u6570\u7684AD\u8ba1\u7b97\u4e2d\u4f7f\u7528\u5b83\u3002\u8bf7\u6ce8\u610f\uff0c\u6211\u4eec\u5e0c\u671b\u5b83\u80fd\u8fd4\u56de \"double \"\u7c7b\u578b\u7684\u503c\u3002\u6211\u4eec\u8fd8\u5fc5\u987b\u6307\u5b9a\u7a7a\u95f4\u7ef4\u5ea6\u7684\u6570\u91cf\uff0c`dim'\uff0c\u4ee5\u4fbf\u5efa\u7acb\u77e2\u91cf\u3001\u5f20\u91cf\u548c\u5bf9\u79f0\u5f20\u91cf\u573a\u4e0e\u5b83\u4eec\u6240\u542b\u5206\u91cf\u6570\u91cf\u4e4b\u95f4\u7684\u8054\u7cfb\u3002\u7528\u4e8eADHelper\u7c7b\u7684\u5177\u4f53\u7684`ADTypeCode`\u5c06\u5728\u5b9e\u9645\u4f7f\u7528\u8be5\u7c7b\u7684\u65f6\u5019\u4f5c\u4e3a\u6a21\u677f\u53c2\u6570\u63d0\u4f9b\u3002\n\n    template <int dim, Differentiation::AD::NumberTypes ADTypeCode> \n    class Magnetoelastic_Constitutive_Law_AD final \n      : public Coupled_Magnetomechanical_Constitutive_Law_Base<dim> \n    { \n      using ADHelper = \n        Differentiation::AD::ScalarFunction<dim, ADTypeCode, double>; \n      using ADNumberType = typename ADHelper::ad_type; \n\n    public: \n      Magnetoelastic_Constitutive_Law_AD( \n        const ConstitutiveParameters &constitutive_parameters); \n\n// \u7531\u4e8e\u57fa\u7c7b\u7684\u516c\u5171\u63a5\u53e3\u662f\u7eaf \"\u865a\u62df \"\u7684\uff0c\u8fd9\u91cc\u6211\u4eec\u5c06\u58f0\u660e\u8fd9\u4e2a\u7c7b\u5c06\u8986\u76d6\u6240\u6709\u8fd9\u4e9b\u57fa\u7c7b\u65b9\u6cd5\u3002\n\n      virtual void update_internal_data(const SymmetricTensor<2, dim> &C, \n                                        const Tensor<1, dim> &         H, \n                                        const DiscreteTime &) override; \n\n      virtual double get_psi() const override; \n\n      virtual Tensor<1, dim> get_B() const override; \n\n      virtual SymmetricTensor<2, dim> get_S() const override; \n\n      virtual SymmetricTensor<2, dim> get_DD() const override; \n\n      virtual Tensor<3, dim> get_PP() const override; \n\n      virtual SymmetricTensor<4, dim> get_HH() const override; \n\n// \u5728\u8fd9\u4e2a\u7c7b\u7684`private`\u90e8\u5206\uff0c\u6211\u4eec\u9700\u8981\u5b9a\u4e49\u4e00\u4e9b\u63d0\u53d6\u5668\uff0c\u8fd9\u4e9b\u63d0\u53d6\u5668\u5c06\u5e2e\u52a9\u6211\u4eec\u8bbe\u7f6e\u81ea\u53d8\u91cf\uff0c\u968f\u540e\u5f97\u5230\u4e0e\u56e0\u53d8\u91cf\u76f8\u5173\u7684\u8ba1\u7b97\u503c\u3002\u5982\u679c\u8fd9\u4e2a\u7c7b\u662f\u5728\u6709\u9650\u5143\u95ee\u9898\u7684\u80cc\u666f\u4e0b\u4f7f\u7528\uff0c\u90a3\u4e48\u8fd9\u4e9b\u63d0\u53d6\u5668\u4e2d\u7684\u6bcf\u4e00\u4e2a\u90fd\uff08\u5f88\u53ef\u80fd\uff09\u4e0e\u89e3\u573a\u7684\u4e00\u4e2a\u5206\u91cf\uff08\u5728\u672c\u4f8b\u4e2d\uff0c\u4f4d\u79fb\u548c\u78c1\u6807\u52bf\uff09\u7684\u68af\u5ea6\u6709\u5173\u3002\u6b63\u5982\u4f60\u73b0\u5728\u53ef\u80fd\u63a8\u65ad\u7684\u90a3\u6837\uff0c\u8fd9\u91cc \"C \"\u8868\u793a\u53f3Cauchy-Green\u5f20\u91cf\uff0c\"H \"\u8868\u793a\u78c1\u573a\u5411\u91cf\u3002\n\n    private: \n      const FEValuesExtractors::Vector             H_components; \n      const FEValuesExtractors::SymmetricTensor<2> C_components; \n\n// \u8fd9\u662f\u4e00\u4e2a\u81ea\u52a8\u5fae\u5206\u52a9\u624b\u7684\u5b9e\u4f8b\uff0c\u6211\u4eec\u5c06\u8bbe\u7f6e\u5b83\u6765\u5b8c\u6210\u4e0e\u6784\u6210\u6cd5\u5219\u6709\u5173\u7684\u6240\u6709\u5fae\u5206\u8ba1\u7b97......\n\n      ADHelper ad_helper; \n\n// ... \u4ee5\u4e0b\u4e09\u4e2a\u6210\u5458\u53d8\u91cf\u5c06\u5b58\u50a8\u6765\u81ea @p ad_helper. \u7684\u8f93\u51fa\u3002  @p ad_helper \u4e00\u6b21\u6027\u8fd4\u56de\u5173\u4e8e\u6240\u6709\u573a\u53d8\u91cf\u7684\u5bfc\u6570\uff0c\u56e0\u6b64\u6211\u4eec\u5c06\u4fdd\u7559\u5b8c\u6574\u7684\u68af\u5ea6\u5411\u91cf\u548cHessian\u77e9\u9635\u3002\u6211\u4eec\u5c06\u4ece\u4e2d\u63d0\u53d6\u6211\u4eec\u771f\u6b63\u611f\u5174\u8da3\u7684\u5355\u4e2a\u6761\u76ee\u3002\n\n      double             psi; \n      Vector<double>     Dpsi; \n      FullMatrix<double> D2psi; \n    }; \n\n// \u5728\u8bbe\u7f6e\u5b57\u6bb5\u7ec4\u4ef6\u63d0\u53d6\u5668\u65f6\uff0c\u5bf9\u4e8e\u5b83\u4eec\u7684\u987a\u5e8f\u662f\u5b8c\u5168\u4efb\u610f\u7684\u3002\u4f46\u91cd\u8981\u7684\u662f\uff0c\u8fd9\u4e9b\u63d0\u53d6\u5668\u6ca1\u6709\u91cd\u53e0\u7684\u7d22\u5f15\u3002\u8fd9\u4e9b\u63d0\u53d6\u5668\u7684\u7ec4\u4ef6\u603b\u6570\u5b9a\u4e49\u4e86 @p ad_helper \u9700\u8981\u8ddf\u8e2a\u7684\u72ec\u7acb\u53d8\u91cf\u7684\u6570\u91cf\uff0c\u5e76\u4e14\u6211\u4eec\u5c06\u5bf9\u5176\u8fdb\u884c\u5bfc\u6570\u3002\u7531\u6b64\u4ea7\u751f\u7684\u6570\u636e\u7ed3\u6784 @p Dpsi \u548c @p D2psi \u4e5f\u5fc5\u987b\u6709\u76f8\u5e94\u7684\u5927\u5c0f\u3002\u4e00\u65e6 @p ad_helper \u88ab\u914d\u7f6e\u597d\uff08\u5b83\u7684\u8f93\u5165\u53c2\u6570\u662f $\\mathbf{C}$ \u548c $\\boldsymbol{\\mathbb{H}}$ \u7684\u7ec4\u4ef6\u603b\u6570\uff09\uff0c\u6211\u4eec\u5c31\u53ef\u4ee5\u76f4\u63a5\u8be2\u95ee\u5b83\u4f7f\u7528\u591a\u5c11\u4e2a\u72ec\u7acb\u53d8\u91cf\u3002\n\n    template <int dim, Differentiation::AD::NumberTypes ADTypeCode> \n    Magnetoelastic_Constitutive_Law_AD<dim, ADTypeCode>:: \n      Magnetoelastic_Constitutive_Law_AD( \n        const ConstitutiveParameters &constitutive_parameters) \n      : Coupled_Magnetomechanical_Constitutive_Law_Base<dim>( \n          constitutive_parameters) \n      , H_components(0) \n      , C_components(Tensor<1, dim>::n_independent_components) \n      , ad_helper(Tensor<1, dim>::n_independent_components + \n                  SymmetricTensor<2, dim>::n_independent_components) \n      , psi(0.0) \n      , Dpsi(ad_helper.n_independent_variables()) \n      , D2psi(ad_helper.n_independent_variables(), \n              ad_helper.n_independent_variables()) \n    {} \n\n// \u5982\u524d\u6240\u8ff0\uff0c\u7531\u4e8e\u81ea\u52a8\u5fae\u5206\u5e93\u7684\u5de5\u4f5c\u65b9\u5f0f\uff0c @p ad_helper \u5c06\u603b\u662f\u540c\u65f6\u8fd4\u56de\u80fd\u91cf\u5bc6\u5ea6\u51fd\u6570\u76f8\u5bf9\u4e8e\u6240\u6709\u573a\u53d8\u91cf\u7684\u5bfc\u6570\u3002\u7531\u4e8e\u8fd9\u4e2a\u539f\u56e0\uff0c\u5728\u51fd\u6570`get_B()`\u3001`get_S()`\u7b49\u4e2d\u8ba1\u7b97\u5bfc\u6570\u662f\u6ca1\u6709\u610f\u4e49\u7684\uff0c\u56e0\u4e3a\u6211\u4eec\u4f1a\u505a\u5f88\u591a\u989d\u5916\u7684\u8ba1\u7b97\uff0c\u7136\u540e\u76f4\u63a5\u4e22\u5f03\u3002\u56e0\u6b64\uff0c\u5904\u7406\u8fd9\u4e2a\u95ee\u9898\u7684\u6700\u597d\u65b9\u6cd5\u662f\u7528\u4e00\u4e2a\u5355\u4e00\u7684\u51fd\u6570\u8c03\u7528\u6765\u5b8c\u6210\u6240\u6709\u7684\u524d\u671f\u8ba1\u7b97\uff0c\u7136\u540e\u6211\u4eec\u5728\u9700\u8981\u65f6\u63d0\u53d6\u5b58\u50a8\u7684\u6570\u636e\u3002\u8fd9\u5c31\u662f\u6211\u4eec\u5728 \"update_internal_data() \"\u65b9\u6cd5\u4e2d\u8981\u505a\u7684\u3002\u7531\u4e8e\u6750\u6599\u662f\u4e0e\u901f\u7387\u65e0\u5173\u7684\uff0c\u6211\u4eec\u53ef\u4ee5\u5ffd\u7565DiscreteTime\u53c2\u6570\u3002\n\n    template <int dim, Differentiation::AD::NumberTypes ADTypeCode> \n    void \n    Magnetoelastic_Constitutive_Law_AD<dim, ADTypeCode>::update_internal_data( \n      const SymmetricTensor<2, dim> &C, \n      const Tensor<1, dim> &         H, \n      const DiscreteTime &) \n    { \n      Assert(determinant(C) > 0, ExcInternalError()); \n\n// \u7531\u4e8e\u6211\u4eec\u5728\u6bcf\u4e2a\u65f6\u95f4\u6b65\u9aa4\u4e2d\u90fd\u4f1a\u91cd\u590d\u4f7f\u7528 @p ad_helper \u6570\u636e\u7ed3\u6784\uff0c\u6240\u4ee5\u6211\u4eec\u9700\u8981\u5728\u4f7f\u7528\u524d\u6e05\u9664\u5b83\u7684\u6240\u6709\u9648\u65e7\u4fe1\u606f\u3002\n\n      ad_helper.reset(); \n\n// \u4e0b\u4e00\u6b65\u662f\u8bbe\u7f6e\u6240\u6709\u5b57\u6bb5\u7ec4\u4ef6\u7684\u503c\u3002\u8fd9\u4e9b\u5b9a\u4e49\u4e86 \"\u70b9\"\uff0c\u6211\u4eec\u5c06\u56f4\u7ed5\u8fd9\u4e2a\u70b9\u8ba1\u7b97\u51fd\u6570\u68af\u5ea6\u53ca\u5176\u7ebf\u6027\u5316\u3002\u6211\u4eec\u4e4b\u524d\u521b\u5efa\u7684\u63d0\u53d6\u5668\u63d0\u4f9b\u4e86\u5b57\u6bb5\u548c @p ad_helper \u4e2d\u7684\u6ce8\u518c\u8868\u4e4b\u95f4\u7684\u5173\u8054 -- \u5b83\u4eec\u5c06\u88ab\u53cd\u590d\u4f7f\u7528\uff0c\u4ee5\u786e\u4fdd\u6211\u4eec\u5bf9\u54ea\u4e2a\u53d8\u91cf\u5bf9\u5e94\u4e8e`H`\u6216`C`\u7684\u54ea\u4e2a\u5206\u91cf\u6709\u6b63\u786e\u7684\u89e3\u91ca\u3002\n\n      ad_helper.register_independent_variable(H, H_components); \n      ad_helper.register_independent_variable(C, C_components); \n\n// \u73b0\u5728\u6211\u4eec\u5df2\u7ecf\u5b8c\u6210\u4e86\u6700\u521d\u7684\u8bbe\u7f6e\uff0c\u6211\u4eec\u53ef\u4ee5\u68c0\u7d22\u6211\u4eec\u5b57\u6bb5\u7684AD\u5bf9\u5e94\u5173\u7cfb\u3002\u8fd9\u4e9b\u662f\u771f\u6b63\u7684\u80fd\u91cf\u51fd\u6570\u7684\u72ec\u7acb\u53d8\u91cf\uff0c\u5e76\u4e14\u5bf9\u7528\u5b83\u4eec\u8fdb\u884c\u7684\u8ba1\u7b97\u662f \"\u654f\u611f\u7684\"\u3002\u8bf7\u6ce8\u610f\uff0cAD\u6570\u88ab\u89c6\u4e3a\u4e00\u79cd\u7279\u6b8a\u7684\u6570\u5b57\u7c7b\u578b\uff0c\u53ef\u4ee5\u5728\u8bb8\u591a\u6a21\u677f\u5316\u7684\u7c7b\u4e2d\u4f7f\u7528\uff08\u5728\u8fd9\u4e2a\u4f8b\u5b50\u4e2d\uff0c\u4f5c\u4e3aTensor\u548cSymmetricTensor\u7c7b\u7684\u6807\u91cf\u7c7b\u578b\uff09\u3002\n\n      const Tensor<1, dim, ADNumberType> H_ad = \n        ad_helper.get_sensitive_variables(H_components); \n      const SymmetricTensor<2, dim, ADNumberType> C_ad = \n        ad_helper.get_sensitive_variables(C_components); \n\n// \u6211\u4eec\u8fd8\u53ef\u4ee5\u5728\u8bb8\u591a\u4ee5\u6807\u91cf\u7c7b\u578b\u4e3a\u6a21\u677f\u7684\u51fd\u6570\u4e2d\u4f7f\u7528\u5b83\u4eec\u3002\u56e0\u6b64\uff0c\u5bf9\u4e8e\u6211\u4eec\u9700\u8981\u7684\u8fd9\u4e9b\u4e2d\u95f4\u503c\uff0c\u6211\u4eec\u53ef\u4ee5\u8fdb\u884c\u5f20\u91cf\u8fd0\u7b97\u548c\u4e00\u4e9b\u6570\u5b66\u51fd\u6570\u3002\u7531\u6b64\u4ea7\u751f\u7684\u7c7b\u578b\u4e5f\u5c06\u662f\u4e00\u4e2a\u81ea\u52a8\u53ef\u5206\u7684\u6570\u5b57\uff0c\u5b83\u5bf9\u8fd9\u4e9b\u51fd\u6570\u4e2d\u7684\u64cd\u4f5c\u8fdb\u884c\u7f16\u7801\u3002\n\n      const ADNumberType det_F_ad = std::sqrt(determinant(C_ad)); \n      const SymmetricTensor<2, dim, ADNumberType> C_inv_ad = invert(C_ad); \n      AssertThrow(det_F_ad > ADNumberType(0.0), \n                  ExcMessage(\"Volumetric Jacobian must be positive.\")); \n\n// \u63a5\u4e0b\u6765\u6211\u4eec\u5c06\u8ba1\u7b97\u51fa\u5728\u78c1\u573a\u5f71\u54cd\u4e0b\u5bfc\u81f4\u526a\u5207\u6a21\u91cf\u53d8\u5316\uff08\u589e\u52a0\uff09\u7684\u6bd4\u4f8b\u51fd\u6570......\n\n      const ADNumberType f_mu_e_ad = \n        1.0 + (this->get_mu_e_inf() / this->get_mu_e() - 1.0) * \n                std::tanh((2.0 * H_ad * H_ad) / \n                          (this->get_mu_e_h_sat() * this->get_mu_e_h_sat())); \n\n// ...\u7136\u540e\u6211\u4eec\u5c31\u53ef\u4ee5\u5b9a\u4e49\u6750\u6599\u7684\u50a8\u80fd\u5bc6\u5ea6\u51fd\u6570\u3002\u6211\u4eec\u5c06\u5728\u540e\u9762\u770b\u5230\uff0c\u8fd9\u4e2a\u4f8b\u5b50\u8db3\u591f\u590d\u6742\uff0c\u503c\u5f97\u4f7f\u7528AD\uff0c\u81f3\u5c11\u53ef\u4ee5\u9a8c\u8bc1\u4e00\u4e2a\u65e0\u8f85\u52a9\u7684\u5b9e\u73b0\u3002\n\n      const ADNumberType psi_ad = \n        0.5 * this->get_mu_e() * f_mu_e_ad * \n          (trace(C_ad) - dim - 2.0 * std::log(det_F_ad))                 // \n        + this->get_lambda_e() * std::log(det_F_ad) * std::log(det_F_ad) // \n        - 0.5 * this->get_mu_0() * this->get_mu_r() * det_F_ad * \n            (H_ad * C_inv_ad * H_ad); // \n\n// \u50a8\u5b58\u7684\u80fd\u91cf\u5bc6\u5ea6\u51fd\u6570\u5b9e\u9645\u4e0a\u662f\u8fd9\u4e2a\u95ee\u9898\u7684\u56e0\u53d8\u91cf\uff0c\u6240\u4ee5\u4f5c\u4e3a \"\u914d\u7f6e \"\u9636\u6bb5\u7684\u6700\u540e\u4e00\u6b65\uff0c\u6211\u4eec\u7528 @p ad_helper. \u6ce8\u518c\u5176\u5b9a\u4e49\u3002\n      ad_helper.register_dependent_variable(psi_ad); \n\n// \u6700\u540e\uff0c\u6211\u4eec\u53ef\u4ee5\u68c0\u7d22\u5b58\u50a8\u7684\u80fd\u91cf\u5bc6\u5ea6\u51fd\u6570\u7684\u7ed3\u679c\u503c\uff0c\u4ee5\u53ca\u5b83\u76f8\u5bf9\u4e8e\u8f93\u5165\u5b57\u6bb5\u7684\u68af\u5ea6\u548cHessian\uff0c\u5e76\u5c06\u5b83\u4eec\u7f13\u5b58\u8d77\u6765\u3002\n\n      psi = ad_helper.compute_value(); \n      ad_helper.compute_gradient(Dpsi); \n      ad_helper.compute_hessian(D2psi); \n    } \n\n// \u4e0b\u9762\u7684\u51e0\u4e2a\u51fd\u6570\u53ef\u4ee5\u67e5\u8be2 $\\psi_{0}$ \u7684\u5b58\u50a8\u503c\uff0c\u5e76\u63d0\u53d6\u68af\u5ea6\u5411\u91cf\u548cHessian\u77e9\u9635\u7684\u6240\u9700\u6210\u5206\u3002\u6211\u4eec\u518d\u6b21\u5229\u7528\u63d0\u53d6\u5668\u6765\u8868\u8fbe\u6211\u4eec\u5e0c\u671b\u68c0\u7d22\u7684\u603b\u68af\u5ea6\u5411\u91cf\u548cHessian\u77e9\u9635\u7684\u54ea\u4e9b\u90e8\u5206\u3002\u5b83\u4eec\u53ea\u8fd4\u56de\u80fd\u91cf\u51fd\u6570\u7684\u5bfc\u6570\uff0c\u6240\u4ee5\u5bf9\u4e8e\u6211\u4eec\u7684\u52a8\u80fd\u53d8\u91cf\u7684\u5b9a\u4e49\u548c\u5b83\u4eec\u7684\u7ebf\u6027\u5316\uff0c\u8fd8\u9700\u8981\u8fdb\u884c\u4e00\u4e9b\u64cd\u4f5c\u6765\u5f62\u6210\u6240\u9700\u7684\u7ed3\u679c\u3002\n\n    template <int dim, Differentiation::AD::NumberTypes ADTypeCode> \n    double Magnetoelastic_Constitutive_Law_AD<dim, ADTypeCode>::get_psi() const \n    { \n      return psi; \n    } \n\n    template <int dim, Differentiation::AD::NumberTypes ADTypeCode> \n    Tensor<1, dim> \n    Magnetoelastic_Constitutive_Law_AD<dim, ADTypeCode>::get_B() const \n    { \n      const Tensor<1, dim> dpsi_dH = \n        ad_helper.extract_gradient_component(Dpsi, H_components); \n      return -dpsi_dH; \n    } \n\n    template <int dim, Differentiation::AD::NumberTypes ADTypeCode> \n    SymmetricTensor<2, dim> \n    Magnetoelastic_Constitutive_Law_AD<dim, ADTypeCode>::get_S() const \n    { \n      const SymmetricTensor<2, dim> dpsi_dC = \n        ad_helper.extract_gradient_component(Dpsi, C_components); \n      return 2.0 * dpsi_dC; \n    } \n\n    template <int dim, Differentiation::AD::NumberTypes ADTypeCode> \n    SymmetricTensor<2, dim> \n    Magnetoelastic_Constitutive_Law_AD<dim, ADTypeCode>::get_DD() const \n    { \n      const Tensor<2, dim> dpsi_dH_dH = \n        ad_helper.extract_hessian_component(D2psi, H_components, H_components); \n      return -symmetrize(dpsi_dH_dH); \n    } \n\n// \u8bf7\u6ce8\u610f\uff0c\u5bf9\u4e8e\u8026\u5408\u9879\u6765\u8bf4\uff0c\u63d0\u53d6\u5668\u53c2\u6570\u7684\u987a\u5e8f\u7279\u522b\u91cd\u8981\uff0c\u56e0\u4e3a\u5b83\u51b3\u5b9a\u4e86\u5b9a\u5411\u5bfc\u6570\u7684\u63d0\u53d6\u987a\u5e8f\u3002\u56e0\u6b64\uff0c\u5982\u679c\u6211\u4eec\u5728\u8c03\u7528`extract_hessian_component()`\u65f6\u98a0\u5012\u4e86\u63d0\u53d6\u5668\u7684\u987a\u5e8f\uff0c\u90a3\u4e48\u6211\u4eec\u5b9e\u9645\u4e0a\u662f\u5728\u68c0\u7d22  $\\left[ \\mathfrak{P}^{\\text{tot}} \\right]^{T}$  \u7684\u4e00\u90e8\u5206\u3002\n\n    template <int dim, Differentiation::AD::NumberTypes ADTypeCode> \n    Tensor<3, dim> \n    Magnetoelastic_Constitutive_Law_AD<dim, ADTypeCode>::get_PP() const \n    { \n      const Tensor<3, dim> dpsi_dC_dH = \n        ad_helper.extract_hessian_component(D2psi, C_components, H_components); \n      return -2.0 * dpsi_dC_dH; \n    } \n\n    template <int dim, Differentiation::AD::NumberTypes ADTypeCode> \n    SymmetricTensor<4, dim> \n    Magnetoelastic_Constitutive_Law_AD<dim, ADTypeCode>::get_HH() const \n    { \n      const SymmetricTensor<4, dim> dpsi_dC_dC = \n        ad_helper.extract_hessian_component(D2psi, C_components, C_components); \n      return 4.0 * dpsi_dC_dC; \n    } \n// @sect4{Magneto-viscoelastic constitutive law (using symbolic algebra and differentiation)}  \n\n// \u6211\u4eec\u8981\u8003\u8651\u7684\u7b2c\u4e8c\u4e2a\u6750\u6599\u5b9a\u5f8b\u5c06\u662f\u4e00\u4e2a\u4ee3\u8868\u5177\u6709\u5355\u4e00\u8017\u6563\u673a\u5236\u7684\u78c1\u6da1\u5f39\u6750\u6599\u3002\u6211\u4eec\u5c06\u8003\u8651\u8fd9\u79cd\u6750\u6599\u7684\u81ea\u7531\u80fd\u5bc6\u5ea6\u51fd\u6570\u5b9a\u4e49\u4e3a\n// @f{align*}{\n//    \\psi_{0} \\left( \\mathbf{C}, \\mathbf{C}_{v}, \\boldsymbol{\\mathbb{H}}\n//    \\right)\n//  &= \\psi_{0}^{ME} \\left( \\mathbf{C}, \\boldsymbol{\\mathbb{H}} \\right)\n//  + \\psi_{0}^{MVE} \\left( \\mathbf{C}, \\mathbf{C}_{v},\n//  \\boldsymbol{\\mathbb{H}} \\right)\n//  \\\\ \\psi_{0}^{ME} \\left( \\mathbf{C}, \\boldsymbol{\\mathbb{H}} \\right)\n//  &= \\frac{1}{2} \\mu_{e} f_{\\mu_{e}^{ME}} \\left( \\boldsymbol{\\mathbb{H}}\n//  \\right)\n//      \\left[ \\text{tr}(\\mathbf{C}) - d - 2 \\ln (\\text{det}(\\mathbf{F}))\n//      \\right]\n//  + \\lambda_{e} \\ln^{2} \\left(\\text{det}(\\mathbf{F}) \\right)\n//  - \\frac{1}{2} \\mu_{0} \\mu_{r} \\text{det}(\\mathbf{F})\n//      \\left[ \\boldsymbol{\\mathbb{H}} \\cdot \\mathbf{C}^{-1} \\cdot\n//      \\boldsymbol{\\mathbb{H}} \\right]\n//  \\\\ \\psi_{0}^{MVE} \\left( \\mathbf{C}, \\mathbf{C}_{v},\n//  \\boldsymbol{\\mathbb{H}} \\right)\n//  &= \\frac{1}{2} \\mu_{v} f_{\\mu_{v}^{MVE}} \\left( \\boldsymbol{\\mathbb{H}}\n//  \\right)\n//      \\left[ \\mathbf{C}_{v} : \\left[\n//        \\left[\\text{det}\\left(\\mathbf{F}\\right)\\right]^{-\\frac{2}{d}}\n//        \\mathbf{C} \\right] - d - \\ln\\left(\n//        \\text{det}\\left(\\mathbf{C}_{v}\\right) \\right)  \\right]\n//  @f}\n//  \uff0c\u5176\u4e2d\n//  @f[\n//    f_{\\mu_{e}}^{ME} \\left( \\boldsymbol{\\mathbb{H}} \\right)\n//  = 1 + \\left[ \\frac{\\mu_{e}^{\\infty}}{\\mu_{e}} - 1 \\right]\n//      \\tanh \\left( 2 \\frac{\\boldsymbol{\\mathbb{H}} \\cdot\n//      \\boldsymbol{\\mathbb{H}}}\n//        {\\left(h_{e}^{\\text{sat}}\\right)^{2}} \\right)\n//  @f]\n\n// @f[\n//    f_{\\mu_{v}}^{MVE} \\left( \\boldsymbol{\\mathbb{H}} \\right)\n//  = 1 + \\left[ \\frac{\\mu_{v}^{\\infty}}{\\mu_{v}} - 1 \\right]\n//      \\tanh \\left( 2 \\frac{\\boldsymbol{\\mathbb{H}} \\cdot\n//      \\boldsymbol{\\mathbb{H}}}\n//        {\\left(h_{v}^{\\text{sat}}\\right)^{2}} \\right),\n//  @f]\n//  \u4e0e\u5185\u90e8\u7c98\u6027\u53d8\u91cf\n//  @f[\n//  \\mathbf{C}_{v}^{(t)}\n//  = \\frac{1}{1 + \\frac{\\Delta t}{\\tau_{v}}} \\left[\n//      \\mathbf{C}_{v}^{(t-1)}\n//    + \\frac{\\Delta t}{\\tau_{v}}\n//      \\left[\\left[\\text{det}\\left(\\mathbf{F}\\right)\\right]^{-\\frac{2}{d}}\n//      \\mathbf{C} \\right]^{-1}\n//    \\right]\n//  @f]\n//  \u7684\u6f14\u5316\u89c4\u5f8b\u76f8\u7ed3\u5408\uff0c\u8be5\u6f14\u5316\u89c4\u5f8b\u91c7\u7528\u4e00\u9636\u540e\u5411\u5dee\u5206\u8fd1\u4f3c\u6cd5\u8fdb\u884c\u79bb\u6563\u3002\n\n// \u518d\u4e00\u6b21\uff0c\u8ba9\u6211\u4eec\u770b\u770b\u5728\u4e00\u4e2a\u5177\u4f53\u7684\u7c7b\u4e2d\u662f\u5982\u4f55\u5b9e\u73b0\u7684\u3002\u6211\u4eec\u73b0\u5728\u5c06\u5229\u7528SD\u65b9\u6cd5\uff0c\u800c\u4e0d\u662f\u4e4b\u524d\u7c7b\u4e2d\u4f7f\u7528\u7684AD\u6846\u67b6\u3002\u4e3a\u4e86\u652f\u6301\u8fd9\u4e00\u70b9\uff0c\u8fd9\u4e2a\u7c7b\u7684\u6784\u9020\u51fd\u6570\u4e0d\u4ec5\u63a5\u53d7 @p constitutive_parameters, \uff0c\u800c\u4e14\u8fd8\u63a5\u53d7\u4e24\u4e2a\u989d\u5916\u7684\u53d8\u91cf\uff0c\u8fd9\u4e9b\u53d8\u91cf\u5c06\u88ab\u7528\u6765\u521d\u59cb\u5316\u4e00\u4e2a Differentiation::SD::BatchOptimizer. \u6211\u4eec\u5c06\u5728\u540e\u9762\u7ed9\u51fa\u66f4\u591a\u7684\u80cc\u666f\u3002\n\n    template <int dim> \n    class Magnetoviscoelastic_Constitutive_Law_SD final \n      : public Coupled_Magnetomechanical_Constitutive_Law_Base<dim> \n    { \n    public: \n      Magnetoviscoelastic_Constitutive_Law_SD( \n        const ConstitutiveParameters &               constitutive_parameters, \n        const Differentiation::SD::OptimizerType     optimizer_type, \n        const Differentiation::SD::OptimizationFlags optimization_flags); \n\n// \u548c\u81ea\u52a8\u533a\u5206\u52a9\u624b\u4e00\u6837\uff0c Differentiation::SD::BatchOptimizer \u5c06\u4e00\u6b21\u6027\u8fd4\u56de\u4e00\u4e2a\u7ed3\u679c\u96c6\u5408\u3002\u56e0\u6b64\uff0c\u4e3a\u4e86\u53ea\u505a\u4e00\u6b21\uff0c\u6211\u4eec\u5c06\u5229\u7528\u4e0e\u4e4b\u524d\u7c7b\u4f3c\u7684\u65b9\u6cd5\uff0c\u5728`update_internal_data()`\u51fd\u6570\u4e2d\u505a\u6240\u6709\u6602\u8d35\u7684\u8ba1\u7b97\uff0c\u5e76\u5c06\u7ed3\u679c\u7f13\u5b58\u8d77\u6765\uff0c\u4ee5\u4fbf\u5206\u5c42\u63d0\u53d6\u3002\n\n      virtual void update_internal_data(const SymmetricTensor<2, dim> &C, \n                                        const Tensor<1, dim> &         H, \n                                        const DiscreteTime &time) override; \n\n      virtual double get_psi() const override; \n\n      virtual Tensor<1, dim> get_B() const override; \n\n      virtual SymmetricTensor<2, dim> get_S() const override; \n\n      virtual SymmetricTensor<2, dim> get_DD() const override; \n\n      virtual Tensor<3, dim> get_PP() const override; \n\n      virtual SymmetricTensor<4, dim> get_HH() const override; \n\n// \u56e0\u4e3a\u6211\u4eec\u8981\u5904\u7406\u7684\u662f\u4e00\u4e2a\u4e0e\u901f\u7387\u6709\u5173\u7684\u6750\u6599\uff0c\u6240\u4ee5\u6211\u4eec\u5fc5\u987b\u5728\u9002\u5f53\u7684\u65f6\u5019\u66f4\u65b0\u5386\u53f2\u53d8\u91cf\u3002\u8fd9\u5c06\u662f\u8fd9\u4e2a\u51fd\u6570\u7684\u76ee\u7684\u3002\n\n      virtual void update_end_of_timestep() override; \n\n// \u5728\u8be5\u7c7b\u7684`private`\u90e8\u5206\uff0c\u6211\u4eec\u5c06\u5e0c\u671b\u8ddf\u8e2a\u5185\u90e8\u7684\u7c98\u6027\u53d8\u5f62\uff0c\u6240\u4ee5\u4e0b\u9762\u4e24\u4e2a\uff08\u5b9e\u503c\u7684\uff0c\u975e\u7b26\u53f7\u7684\uff09\u6210\u5458\u53d8\u91cf\u5206\u522b\u6301\u6709\n\n// - \u5185\u90e8\u53d8\u91cf\u65f6\u95f4\u6b65\u957f\uff08\u5982\u679c\u5d4c\u5165\u975e\u7ebf\u6027\u6c42\u89e3\u5668\u6846\u67b6\uff0c\u5219\u4e3a\u725b\u987f\u6b65\u957f\uff09\u7684\u503c\uff0c\u4ee5\u53ca\n\n// - \u5185\u90e8\u53d8\u91cf\u5728\u524d\u4e00\u4e2a\u65f6\u95f4\u6b65\u957f\u7684\u503c\u3002\n\n// \uff08\u6211\u4eec\u5c06\u8fd9\u4e9b\u53d8\u91cf\u6807\u8bb0\u4e3a \"Q\"\uff0c\u4ee5\u4fbf\u4e8e\u8bc6\u522b\uff1b\u5728\u8ba1\u7b97\u7684\u6d77\u6d0b\u4e2d\uff0c\u4e0d\u4e00\u5b9a\u5bb9\u6613\u5c06`Cv`\u6216`C_v`\u4e0e`C`\u533a\u5206\u5f00\u6765\uff09\u3002\n\n    private: \n      SymmetricTensor<2, dim> Q_t; \n      SymmetricTensor<2, dim> Q_t1; \n\n// \u7531\u4e8e\u6211\u4eec\u5c06\u4f7f\u7528\u7b26\u53f7\u7c7b\u578b\uff0c\u6211\u4eec\u9700\u8981\u5b9a\u4e49\u4e00\u4e9b\u7b26\u53f7\u53d8\u91cf\uff0c\u4ee5\u4fbf\u4e0e\u6846\u67b6\u4e00\u8d77\u4f7f\u7528\u3002(\u5b83\u4eec\u90fd\u4ee5 \"SD \"\u4e3a\u540e\u7f00\uff0c\u4ee5\u65b9\u4fbf\u533a\u5206\u7b26\u53f7\u7c7b\u578b\u6216\u8868\u8fbe\u5f0f\u4e0e\u5b9e\u503c\u7c7b\u578b\u6216\u6807\u91cf\u3002) \u8fd9\u53ef\u4ee5\u5728\u524d\u9762\u505a\u4e00\u6b21\uff08\u751a\u81f3\u6709\u53ef\u80fd\u4f5c\u4e3a \"\u9759\u6001 \"\u53d8\u91cf\uff09\uff0c\u4ee5\u5c3d\u91cf\u51cf\u5c11\u4e0e\u521b\u5efa\u8fd9\u4e9b\u53d8\u91cf\u76f8\u5173\u7684\u5f00\u9500\u3002\u4e3a\u4e86\u5b9e\u73b0\u901a\u7528\u7f16\u7a0b\u7684\u7ec8\u6781\u76ee\u6807\uff0c\u6211\u4eec\u751a\u81f3\u53ef\u4ee5\u7528\u7b26\u53f7\u6765\u63cf\u8ff0\u6784\u6210\u53c2\u6570\uff0c*\u6709\u53ef\u80fd*\u5141\u8bb8\u4e00\u4e2a\u7c7b\u7684\u5b9e\u4f8b\u5728\u8fd9\u4e9b\u503c\u7684\u4e0d\u540c\u8f93\u5165\u4e0b\u88ab\u91cd\u590d\u4f7f\u7528\u3002\n\n// \u8fd9\u4e9b\u662f\u4ee3\u8868\u5f39\u6027\u3001\u7c98\u6027\u548c\u78c1\u6027\u6750\u6599\u53c2\u6570\u7684\u7b26\u53f7\u6807\u91cf\uff08\u5b9a\u4e49\u7684\u987a\u5e8f\u4e0e\u5b83\u4eec\u5728 @p ConstitutiveParameters \u7c7b\u4e2d\u51fa\u73b0\u7684\u987a\u5e8f\u57fa\u672c\u76f8\u540c\uff09\u3002\u6211\u4eec\u8fd8\u5b58\u50a8\u4e86\u4e00\u4e2a\u7b26\u53f7\u8868\u8fbe\u5f0f\uff0c @p delta_t_sd, \uff0c\u8868\u793a\u65f6\u95f4\u6b65\u957f\uff09\u3002)\n\n      const Differentiation::SD::Expression mu_e_sd; \n      const Differentiation::SD::Expression mu_e_inf_sd; \n      const Differentiation::SD::Expression mu_e_h_sat_sd; \n      const Differentiation::SD::Expression lambda_e_sd; \n      const Differentiation::SD::Expression mu_v_sd; \n      const Differentiation::SD::Expression mu_v_inf_sd; \n      const Differentiation::SD::Expression mu_v_h_sat_sd; \n      const Differentiation::SD::Expression tau_v_sd; \n      const Differentiation::SD::Expression delta_t_sd; \n      const Differentiation::SD::Expression mu_r_sd; \n\n// \u63a5\u4e0b\u6765\u6211\u4eec\u5b9a\u4e49\u4e00\u4e9b\u4ee3\u8868\u72ec\u7acb\u573a\u53d8\u91cf\u7684\u5f20\u91cf\u7b26\u53f7\u53d8\u91cf\uff0c\u5728\u6b64\u57fa\u7840\u4e0a\uff0c\u80fd\u91cf\u5bc6\u5ea6\u51fd\u6570\u88ab\u53c2\u6570\u5316\u3002\n\n      const Tensor<1, dim, Differentiation::SD::Expression>          H_sd; \n      const SymmetricTensor<2, dim, Differentiation::SD::Expression> C_sd; \n\n// \u540c\u6837\uff0c\u6211\u4eec\u4e5f\u6709\u5185\u90e8\u7c98\u6027\u53d8\u91cf\u7684\u7b26\u53f7\u8868\u793a\uff08\u5305\u62ec\u5b83\u7684\u5f53\u524d\u503c\u548c\u5b83\u5728\u524d\u4e00\u4e2a\u65f6\u95f4\u6bb5\u7684\u503c\uff09\u3002\n\n      const SymmetricTensor<2, dim, Differentiation::SD::Expression> Q_t_sd; \n      const SymmetricTensor<2, dim, Differentiation::SD::Expression> Q_t1_sd; \n\n// \u6211\u4eec\u8fd8\u5e94\u8be5\u5b58\u50a8\u4ece\u5c5e\u8868\u8fbe\u5f0f\u7684\u5b9a\u4e49\u3002\u867d\u7136\u6211\u4eec\u53ea\u8ba1\u7b97\u4e00\u6b21\uff0c\u4f46\u6211\u4eec\u9700\u8981\u5b83\u4eec\u4ece\u4e0b\u9762\u58f0\u660e\u7684 @p optimizer \u4e2d\u68c0\u7d22\u6570\u636e\u3002\u6b64\u5916\uff0c\u5f53\u5e8f\u5217\u5316\u4e00\u4e2a\u50cf\u8fd9\u6837\u7684\u6750\u6599\u7c7b\u65f6\uff08\u4e0d\u662f\u4f5c\u4e3a\u672c\u6559\u7a0b\u7684\u4e00\u90e8\u5206\uff09\uff0c\u6211\u4eec\u8981\u4e48\u9700\u8981\u628a\u8fd9\u4e9b\u8868\u8fbe\u5f0f\u4e5f\u5e8f\u5217\u5316\uff0c\u8981\u4e48\u9700\u8981\u5728\u91cd\u65b0\u52a0\u8f7d\u65f6\u91cd\u5efa\u5b83\u4eec\u3002\n\n      Differentiation::SD::Expression                          psi_sd; \n      Tensor<1, dim, Differentiation::SD::Expression>          B_sd; \n      SymmetricTensor<2, dim, Differentiation::SD::Expression> S_sd; \n      SymmetricTensor<2, dim, Differentiation::SD::Expression> BB_sd; \n      Tensor<3, dim, Differentiation::SD::Expression>          PP_sd; \n      SymmetricTensor<4, dim, Differentiation::SD::Expression> HH_sd; \n\n// \u7136\u540e\uff0c\u4e0b\u4e00\u4e2a\u53d8\u91cf\u662f\u7528\u4e8e\u8bc4\u4f30\u4ece\u5c5e\u51fd\u6570\u7684\u4f18\u5316\u5668\u3002\u66f4\u5177\u4f53\u5730\u8bf4\uff0c\u5b83\u63d0\u4f9b\u4e86\u52a0\u901f\u8bc4\u4f30\u7b26\u53f7\u4f9d\u8d56\u8868\u8fbe\u5f0f\u7684\u53ef\u80fd\u6027\u3002\u8fd9\u662f\u4e00\u4e2a\u91cd\u8981\u7684\u5de5\u5177\uff0c\u56e0\u4e3a\u5bf9\u5197\u957f\u8868\u8fbe\u5f0f\u7684\u672c\u5730\u8bc4\u4f30\uff08\u4e0d\u4f7f\u7528\u52a0\u901f\u65b9\u6cd5\uff0c\u800c\u662f\u76f4\u63a5\u5bf9\u7b26\u53f7\u8868\u8fbe\u5f0f\u8fdb\u884c\u8bc4\u4f30\uff09\u4f1a\u975e\u5e38\u6162\u3002 Differentiation::SD::BatchOptimizer \u7c7b\u63d0\u4f9b\u4e86\u4e00\u79cd\u673a\u5236\uff0c\u53ef\u4ee5\u5c06\u7b26\u53f7\u8868\u8fbe\u5f0f\u6811\u8f6c\u5316\u4e3a\u53e6\u4e00\u79cd\u4ee3\u7801\u8def\u5f84\uff0c\u4f8b\u5982\uff0c\u5728\u5404\u79cd\u4ece\u5c5e\u8868\u8fbe\u5f0f\u4e4b\u95f4\u5171\u4eab\u4e2d\u95f4\u7ed3\u679c\uff08\u610f\u5473\u7740\u8fd9\u4e9b\u4e2d\u95f4\u503c\u6bcf\u6b21\u8bc4\u4f30\u53ea\u8ba1\u7b97\u4e00\u6b21\uff09\u548c/\u6216\u4f7f\u7528\u5373\u65f6\u7f16\u8bd1\u5668\u7f16\u8bd1\u4ee3\u7801\uff08\u4ece\u800c\u68c0\u7d22\u8bc4\u4f30\u6b65\u9aa4\u7684\u63a5\u8fd1\u539f\u751f\u6027\u80fd\uff09\u3002\n\n// \u6267\u884c\u8fd9\u79cd\u4ee3\u7801\u8f6c\u6362\u5728\u8ba1\u7b97\u4e0a\u662f\u975e\u5e38\u6602\u8d35\u7684\uff0c\u6240\u4ee5\u6211\u4eec\u5b58\u50a8\u4e86\u4f18\u5316\u5668\uff0c\u4f7f\u5176\u5728\u6bcf\u4e2a\u7c7b\u5b9e\u4f8b\u4e2d\u53ea\u505a\u4e00\u6b21\u3002\u8fd9\u4e5f\u8fdb\u4e00\u6b65\u4fc3\u4f7f\u6211\u4eec\u51b3\u5b9a\u5c06\u6784\u6210\u53c2\u6570\u672c\u8eab\u53d8\u6210\u7b26\u53f7\u5316\u3002\u8fd9\u6837\u6211\u4eec\u5c31\u53ef\u4ee5\u5728\u51e0\u79cd\u6750\u6599\uff08\u5f53\u7136\u662f\u76f8\u540c\u7684\u80fd\u91cf\u51fd\u6570\uff09\u548c\u6f5c\u5728\u7684\u591a\u4e2a\u8fde\u7eed\u4f53\u70b9\uff08\u5982\u679c\u5d4c\u5165\u5230\u6709\u9650\u5143\u6a21\u62df\u4e2d\uff09\u4e2d\u91cd\u590d\u4f7f\u7528\u8fd9\u4e2a @p optimizer \u7684\u5355\u4e00\u5b9e\u4f8b\u3002\n\n// \u6b63\u5982\u6a21\u677f\u53c2\u6570\u6240\u6307\u5b9a\u7684\uff0c\u6570\u503c\u7ed3\u679c\u5c06\u662f<tt>double</tt>\u7c7b\u578b\u3002\n\n      Differentiation::SD::BatchOptimizer<double> optimizer; \n\n// \u5728\u8bc4\u4f30\u9636\u6bb5\uff0c\u6211\u4eec\u5fc5\u987b\u5c06\u7b26\u53f7\u53d8\u91cf\u6620\u5c04\u5230\u5b83\u4eec\u7684\u5b9e\u503c\u5bf9\u5e94\u7269\u3002\u4e0b\u4e00\u4e2a\u65b9\u6cd5\u5c06\u63d0\u4f9b\u8fd9\u4e2a\u529f\u80fd\u3002\n\n// \u8fd9\u4e2a\u7c7b\u7684\u6700\u540e\u4e00\u4e2a\u65b9\u6cd5\u5c06\u914d\u7f6e  @p optimizer.  \u3002\n      Differentiation::SD::types::substitution_map \n      make_substitution_map(const SymmetricTensor<2, dim> &C, \n                            const Tensor<1, dim> &         H, \n                            const double                   delta_t) const; \n\n      void initialize_optimizer(); \n    }; \n\n// \u7531\u4e8e\u9759\u6b62\u53d8\u5f62\u72b6\u6001\u662f\u6750\u6599\u88ab\u8ba4\u4e3a\u662f\u5b8c\u5168\u677e\u5f1b\u7684\u72b6\u6001\uff0c\u5185\u90e8\u7c98\u6027\u53d8\u91cf\u88ab\u521d\u59cb\u5316\u4e3a\u540c\u4e00\u5f20\u91cf\uff0c\u5373  $\\mathbf{C}_{v} = \\mathbf{I}$  \u3002\u4ee3\u8868\u6784\u6210\u53c2\u6570\u3001\u65f6\u95f4\u6b65\u957f\u3001\u573a\u548c\u5185\u90e8\u53d8\u91cf\u7684\u5404\u79cd\u7b26\u53f7\u53d8\u91cf\u90fd\u6709\u4e00\u4e2a\u552f\u4e00\u7684\u6807\u8bc6\u7b26\u3002\u4f18\u5316\u5668\u88ab\u4f20\u9012\u7ed9\u4e24\u4e2a\u53c2\u6570\uff0c\u8fd9\u4e24\u4e2a\u53c2\u6570\u58f0\u660e\u4e86\u5e94\u8be5\u5e94\u7528\u54ea\u79cd\u4f18\u5316\uff08\u52a0\u901f\uff09\u6280\u672f\uff0c\u4ee5\u53caCAS\u5e94\u8be5\u91c7\u53d6\u54ea\u4e9b\u989d\u5916\u6b65\u9aa4\u6765\u5e2e\u52a9\u63d0\u9ad8\u8bc4\u4f30\u671f\u95f4\u7684\u6027\u80fd\u3002\n\n    template <int dim> \n    Magnetoviscoelastic_Constitutive_Law_SD<dim>:: \n      Magnetoviscoelastic_Constitutive_Law_SD( \n        const ConstitutiveParameters &               constitutive_parameters, \n        const Differentiation::SD::OptimizerType     optimizer_type, \n        const Differentiation::SD::OptimizationFlags optimization_flags) \n      : Coupled_Magnetomechanical_Constitutive_Law_Base<dim>( \n          constitutive_parameters) \n      , Q_t(Physics::Elasticity::StandardTensors<dim>::I) \n      , Q_t1(Physics::Elasticity::StandardTensors<dim>::I) \n      , mu_e_sd(\"mu_e\") \n      , mu_e_inf_sd(\"mu_e_inf\") \n      , mu_e_h_sat_sd(\"mu_e_h_sat\") \n      , lambda_e_sd(\"lambda_e\") \n      , mu_v_sd(\"mu_v\") \n      , mu_v_inf_sd(\"mu_v_inf\") \n      , mu_v_h_sat_sd(\"mu_v_h_sat\") \n      , tau_v_sd(\"tau_v\") \n      , delta_t_sd(\"delta_t\") \n      , mu_r_sd(\"mu_r\") \n      , H_sd(Differentiation::SD::make_vector_of_symbols<dim>(\"H\")) \n      , C_sd(Differentiation::SD::make_symmetric_tensor_of_symbols<2, dim>(\"C\")) \n      , Q_t_sd( \n          Differentiation::SD::make_symmetric_tensor_of_symbols<2, dim>(\"Q_t\")) \n      , Q_t1_sd( \n          Differentiation::SD::make_symmetric_tensor_of_symbols<2, dim>(\"Q_t1\")) \n      , optimizer(optimizer_type, optimization_flags) \n    { \n      initialize_optimizer(); \n    } \n\n// \u66ff\u6362\u56fe\u53ea\u662f\u5c06\u4ee5\u4e0b\u6240\u6709\u6570\u636e\u914d\u5bf9\u5728\u4e00\u8d77\u3002\n\n// - \u6784\u6210\u53c2\u6570\uff08\u4ece\u57fa\u7c7b\u4e2d\u83b7\u53d6\u7684\u503c\uff09\u3002\n\n// - \u65f6\u95f4\u6b65\u957f\uff08\u4ece\u65f6\u95f4\u79bb\u6563\u5668\u4e2d\u83b7\u53d6\u5176\u503c\uff09\u3002\n\n// \u573a\u503c\uff08\u5176\u503c\u7531\u8c03\u7528\u8be5 @p Magnetoviscoelastic_Constitutive_Law_SD \u5b9e\u4f8b\u7684\u5916\u90e8\u51fd\u6570\u89c4\u5b9a\uff09\uff0c\u4ee5\u53ca\n\n// \u5f53\u524d\u548c\u4e4b\u524d\u7684\u5185\u90e8\u7c98\u6027\u53d8\u5f62\uff08\u5176\u503c\u5b58\u50a8\u5728\u8fd9\u4e2a\u7c7b\u5b9e\u4f8b\u4e2d\uff09\u3002\n\n    template <int dim> \n    Differentiation::SD::types::substitution_map \n    Magnetoviscoelastic_Constitutive_Law_SD<dim>::make_substitution_map( \n      const SymmetricTensor<2, dim> &C, \n      const Tensor<1, dim> &         H, \n      const double                   delta_t) const \n    { \n      return Differentiation::SD::make_substitution_map( \n        std::make_pair(mu_e_sd, this->get_mu_e()), \n        std::make_pair(mu_e_inf_sd, this->get_mu_e_inf()), \n        std::make_pair(mu_e_h_sat_sd, this->get_mu_e_h_sat()), \n        std::make_pair(lambda_e_sd, this->get_lambda_e()), \n        std::make_pair(mu_v_sd, this->get_mu_v()), \n        std::make_pair(mu_v_inf_sd, this->get_mu_v_inf()), \n        std::make_pair(mu_v_h_sat_sd, this->get_mu_v_h_sat()), \n        std::make_pair(tau_v_sd, this->get_tau_v()), \n        std::make_pair(delta_t_sd, delta_t), \n        std::make_pair(mu_r_sd, this->get_mu_r()), \n        std::make_pair(H_sd, H), \n        std::make_pair(C_sd, C), \n        std::make_pair(Q_t_sd, Q_t), \n        std::make_pair(Q_t1_sd, Q_t1)); \n    } \n\n// \u7531\u4e8e\u7b26\u53f7\u8868\u8fbe\u5f0f\u7684 \"\u81ea\u7136 \"\u4f7f\u7528\uff0c\u914d\u7f6e @p optimizer \u7684\u5927\u90e8\u5206\u8fc7\u7a0b\u770b\u8d77\u6765\u4e0e\u6784\u5efa\u81ea\u52a8\u533a\u5206\u5e2e\u52a9\u5668\u7684\u8fc7\u7a0b\u975e\u5e38\u76f8\u4f3c\u3002\u5c3d\u7ba1\u5982\u6b64\uff0c\u6211\u4eec\u8fd8\u662f\u8981\u518d\u6b21\u8be6\u7ec6\u8bf4\u660e\u8fd9\u4e9b\u6b65\u9aa4\uff0c\u4ee5\u5f3a\u8c03\u8fd9\u4e24\u4e2a\u6846\u67b6\u7684\u4e0d\u540c\u4e4b\u5904\u3002\n\n// \u8be5\u51fd\u6570\u4ece\u7b26\u53f7\u5316\u7f16\u7801\u53d8\u5f62\u68af\u5ea6\u884c\u5217\u5f0f\u7684\u8868\u8fbe\u5f0f\u5f00\u59cb\uff08\u7528\u53f3Cauchy-Green\u53d8\u5f62\u5f20\u91cf\u8868\u793a\uff0c\u5373\u6211\u4eec\u7684\u4e3b\u8981\u573a\u53d8\u91cf\uff09\uff0c\u4ee5\u53ca $\\mathbf{C}$ \u672c\u8eab\u7684\u9006\u3002\n\n    template <int dim> \n    void Magnetoviscoelastic_Constitutive_Law_SD<dim>::initialize_optimizer() \n    { \n      const Differentiation::SD::Expression det_F_sd = \n        std::sqrt(determinant(C_sd)); \n      const SymmetricTensor<2, dim, Differentiation::SD::Expression> C_inv_sd = \n        invert(C_sd); \n\n// \u63a5\u4e0b\u6765\u662f\u81ea\u7531\u80fd\u5bc6\u5ea6\u51fd\u6570\u7684\u5f39\u6027\u90e8\u5206\u7684\u9971\u548c\u51fd\u6570\u7684\u7b26\u53f7\u8868\u793a\uff0c\u7136\u540e\u662f\u81ea\u7531\u80fd\u5bc6\u5ea6\u51fd\u6570\u7684\u78c1\u5f39\u6027\u8d21\u732e\u3002\u8fd9\u4e00\u5207\u90fd\u4e0e\u6211\u4eec\u4e4b\u524d\u770b\u5230\u7684\u7ed3\u6784\u76f8\u540c\u3002\n\n      const Differentiation::SD::Expression f_mu_e_sd = \n        1.0 + \n        (mu_e_inf_sd / mu_e_sd - 1.0) * \n          std::tanh((2.0 * H_sd * H_sd) / (mu_e_h_sat_sd * mu_e_h_sat_sd)); \n\n      const Differentiation::SD::Expression psi_ME_sd = \n        0.5 * mu_e_sd * f_mu_e_sd * \n          (trace(C_sd) - dim - 2.0 * std::log(det_F_sd)) + \n        lambda_e_sd * std::log(det_F_sd) * std::log(det_F_sd) - \n        0.5 * this->get_mu_0() * mu_r_sd * det_F_sd * (H_sd * C_inv_sd * H_sd); \n\n// \u6b64\u5916\uff0c\u6211\u4eec\u8fd8\u5b9a\u4e49\u4e86\u81ea\u7531\u80fd\u5bc6\u5ea6\u51fd\u6570\u7684\u78c1-\u7c98\u5f39\u6027\u8d21\u732e\u3002\u5b9e\u73b0\u8fd9\u4e00\u70b9\u6240\u9700\u7684\u7b2c\u4e00\u4e2a\u7ec4\u4ef6\u662f\u4e00\u4e2a\u7f29\u653e\u51fd\u6570\uff0c\u5b83\u5c06\u4f7f\u7c98\u6027\u526a\u5207\u6a21\u91cf\u5728\u78c1\u573a\u5f71\u54cd\u4e0b\u53d1\u751f\u53d8\u5316\uff08\u589e\u52a0\uff09\uff08\u89c1 @cite Pelteret2018a  \uff0c\u516c\u5f0f29\uff09\u3002\u6b64\u540e\uff0c\u6211\u4eec\u53ef\u4ee5\u8ba1\u7b97\u80fd\u91cf\u5bc6\u5ea6\u51fd\u6570\u7684\u8017\u6563\u5206\u91cf\uff1b\u5176\u8868\u8fbe\u5f0f\u89c1 @cite Pelteret2018a \uff08\u516c\u5f0f28\uff09\uff0c\u8fd9\u662f\u5bf9 @cite Linder2011a \uff08\u516c\u5f0f46\uff09\u4e2d\u63d0\u51fa\u7684\u80fd\u91cf\u5bc6\u5ea6\u51fd\u6570\u7684\u76f4\u63a5\u6269\u5c55\u3002\n\n      const Differentiation::SD::Expression f_mu_v_sd = \n        1.0 + \n        (mu_v_inf_sd / mu_v_sd - 1.0) * \n          std::tanh((2.0 * H_sd * H_sd) / (mu_v_h_sat_sd * mu_v_h_sat_sd)); \n\n      const Differentiation::SD::Expression psi_MVE_sd = \n        0.5 * mu_v_sd * f_mu_v_sd * \n        (Q_t_sd * (std::pow(det_F_sd, -2.0 / dim) * C_sd) - dim - \n         std::log(determinant(Q_t_sd))); \n\n// \u4ece\u8fd9\u4e9b\u6784\u4ef6\u4e2d\uff0c\u6211\u4eec\u53ef\u4ee5\u5b9a\u4e49\u6750\u6599\u7684\u603b\u81ea\u7531\u80fd\u5bc6\u5ea6\u51fd\u6570\u3002\n\n      psi_sd = psi_ME_sd + psi_MVE_sd; \n\n// \u76ee\u524d\uff0c\u5bf9\u4e2d\u79d1\u9662\u6765\u8bf4\uff0c\u53d8\u91cf @p Q_t_sd \u4f3c\u4e4e\u662f\u72ec\u7acb\u4e8e @p C_sd. \u7684\uff0c\u6211\u4eec\u7684\u5f20\u91cf\u7b26\u53f7\u8868\u8fbe\u5f0f @p Q_t_sd \u53ea\u662f\u6709\u4e00\u4e2a\u4e0e\u4e4b\u76f8\u5173\u7684\u6807\u8bc6\u7b26\uff0c\u6ca1\u6709\u4efb\u4f55\u4e1c\u897f\u5c06\u5176\u4e0e\u53e6\u4e00\u4e2a\u5f20\u91cf\u7b26\u53f7\u8868\u8fbe\u5f0f @p C_sd. \u8054\u7cfb\u8d77\u6765\u3002\u56e0\u6b64\uff0c\u76f8\u5bf9\u4e8e @p C_sd \u7684\u4efb\u4f55\u5bfc\u6570\u5c06\u5ffd\u7565\u8fd9\u79cd\u5185\u5728\u7684\u4f9d\u8d56\u5173\u7cfb\uff0c\u6b63\u5982\u6211\u4eec\u4ece\u8fdb\u5316\u89c4\u5f8b\u53ef\u4ee5\u770b\u5230\u7684\uff0c\u5b9e\u9645\u4e0a\u662f $\\mathbf{C}_{v} = \\mathbf{C}_{v} \\left( \\mathbf{C}, t \\right)$  \u3002\u8fd9\u610f\u5473\u7740\uff0c\u76f8\u5bf9\u4e8e $\\mathbf{C}$ \u63a8\u5bfc\u4efb\u4f55\u51fd\u6570 $f = f(\\mathbf{C}, \\mathbf{Q})$ \u5c06\u8fd4\u56de\u90e8\u5206\u5bfc\u6570 $\\frac{\\partial f(\\mathbf{C}, \\mathbf{Q})}{\\partial \\mathbf{C}}\n//  \\Big\\vert_{\\mathbf{Q}}$ \uff0c\u800c\u4e0d\u662f\u603b\u5bfc\u6570 $\\frac{d f(\\mathbf{C}, \\mathbf{Q}(\\mathbf{C}))}{d \\mathbf{C}} =\n//  \\frac{\\partial f(\\mathbf{C}, \\mathbf{Q}(\\mathbf{C}))}{\\partial\n//  \\mathbf{C}} \\Big\\vert_{\\mathbf{Q}} + \\frac{\\partial f(\\mathbf{C},\n//  \\mathbf{Q}(\\mathbf{C}))}{\\partial \\mathbf{Q}}\n//  \\Big\\vert_{\\mathbf{C}} : \\frac{d \\mathbf{Q}(\\mathbf{C}))}{d\n//  \\mathbf{C}}$  \u3002\n\n// \u76f8\u6bd4\u4e4b\u4e0b\uff0c\u5728\u5f53\u524d\u7684AD\u5e93\u4e2d\uff0c\u603b\u5bfc\u6570\u5c06\u603b\u662f\u88ab\u8fd4\u56de\u3002\u8fd9\u610f\u5473\u7740\u5bf9\u4e8e\u8fd9\u7c7b\u6750\u6599\u6a21\u578b\u6765\u8bf4\uff0c\u8ba1\u7b97\u51fa\u7684\u52a8\u80fd\u53d8\u91cf\u662f\u4e0d\u6b63\u786e\u7684\uff0c\u8fd9\u4f7f\u5f97AD\u6210\u4e3a\u4ece\u80fd\u91cf\u5bc6\u5ea6\u51fd\u6570\u4e2d\u63a8\u5bfc\u51fa\uff08\u8fde\u7eed\u70b9\u6c34\u5e73\uff09\u8fd9\u79cd\u8017\u6563\u6027\u6750\u6599\u7684\u6784\u6210\u6cd5\u7684\u4e0d\u6b63\u786e\u5de5\u5177\u3002\n\n// \u6b63\u662f\u8fd9\u79cd\u7279\u5b9a\u7684\u63a7\u5236\u6c34\u5e73\u63cf\u8ff0\u4e86SD\u548cAD\u6846\u67b6\u4e4b\u95f4\u7684\u4e00\u4e2a\u51b3\u5b9a\u6027\u5dee\u5f02\u3002\u5728\u51e0\u884c\u4e2d\uff0c\u6211\u4eec\u5c06\u5bf9\u5185\u90e8\u53d8\u91cf @p Q_t_sd \u7684\u8868\u8fbe\u5f0f\u8fdb\u884c\u64cd\u4f5c\uff0c\u4f7f\u5176\u4ea7\u751f\u6b63\u786e\u7684\u7ebf\u6027\u5316\u3002\n//\u4f46\u662f\uff0c\n//\u9996\u5148\uff0c\u6211\u4eec\u5c06\u8ba1\u7b97\u52a8\u80fd\u53d8\u91cf\u7684\u7b26\u53f7\u8868\u8fbe\u5f0f\uff0c\u5373\u78c1\u611f\u5e94\u5411\u91cf\u548cPiola-Kirchhoff\u5e94\u529b\u5f20\u91cf\u3002\u6267\u884c\u5fae\u5206\u7684\u4ee3\u7801\u76f8\u5f53\u63a5\u8fd1\u4e8e\u6a21\u4eff\u7406\u8bba\u4e2d\u6240\u8ff0\u7684\u5b9a\u4e49\u3002\n\n      B_sd = -Differentiation::SD::differentiate(psi_sd, H_sd); \n      S_sd = 2.0 * Differentiation::SD::differentiate(psi_sd, C_sd); \n\n// \u56e0\u4e3a\u4e0b\u4e00\u6b65\u662f\u5bf9\u4e0a\u8ff0\u5185\u5bb9\u8fdb\u884c\u7ebf\u6027\u5316\uff0c\u6240\u4ee5\u73b0\u5728\u662f\u544a\u77e5CAS  @p Q_t_sd  \u5bf9  @p C_sd,  \u7684\u660e\u786e\u4f9d\u8d56\u6027\u7684\u9002\u5f53\u65f6\u673a\uff0c\u5373\u8bf4\u660e  $\\mathbf{C}_{v} = \\mathbf{C}_{v} \\left( \\mathbf{C}, t\\right)$  \u3002\u8fd9\u610f\u5473\u7740\u672a\u6765\u6240\u6709\u5173\u4e8e @p C_sd \u7684\u5fae\u5206\u8fd0\u7b97\u5c06\u8003\u8651\u5230\u8fd9\u79cd\u4f9d\u8d56\u5173\u7cfb\uff08\u5373\u8ba1\u7b97\u603b\u5bfc\u6570\uff09\u3002\u6362\u53e5\u8bdd\u8bf4\uff0c\u6211\u4eec\u5c06\u8f6c\u6362\u4e00\u4e9b\u8868\u8fbe\u5f0f\uff0c\u4f7f\u5176\u5185\u5728\u53c2\u6570\u5316\u4ece $f(\\mathbf{C}, \\mathbf{Q})$ \u53d8\u4e3a $f(\\mathbf{C}, \\mathbf{Q}(\\mathbf{C}))$  .\n\n// \u4e3a\u4e86\u505a\u5230\u8fd9\u4e00\u70b9\uff0c\u6211\u4eec\u8003\u8651\u65f6\u95f4\u79bb\u6563\u7684\u6f14\u5316\u89c4\u5f8b\u3002\u7531\u6b64\uff0c\u6211\u4eec\u6709\u4e86\u5185\u90e8\u53d8\u91cf\u5728\u5176\u5386\u53f2\u4e0a\u7684\u660e\u786e\u8868\u8fbe\uff0c\u4ee5\u53ca\u4e3b\u8981\u573a\u53d8\u91cf\u3002\u8fd9\u5c31\u662f\u5b83\u5728\u8fd9\u4e2a\u8868\u8fbe\u5f0f\u4e2d\u63cf\u8ff0\u7684\u5185\u5bb9\u3002\n\n      const SymmetricTensor<2, dim, Differentiation::SD::Expression> \n        Q_t_sd_explicit = \n          (1.0 / (1.0 + delta_t_sd / tau_v_sd)) * \n          (Q_t1_sd + \n           (delta_t_sd / tau_v_sd * std::pow(det_F_sd, 2.0 / dim) * C_inv_sd)); \n\n// \u63a5\u4e0b\u6765\u6211\u4eec\u4ea7\u751f\u4e00\u4e2a\u4e2d\u95f4\u66ff\u6362\u56fe\uff0c\u5b83\u5c06\u5728\u4e00\u4e2a\u8868\u8fbe\u5f0f\u4e2d\u627e\u5230 @p Q_t_sd \uff08\u6211\u4eec\u7684\u6807\u8bc6\u7b26\uff09\u7684\u6bcf\u4e2a\u5b9e\u4f8b\uff0c\u5e76\u7528 @p Q_t_sd_explicit. \u4e2d\u7684\u5b8c\u6574\u8868\u8fbe\u5f0f\u6765\u66ff\u6362\u5b83\u3002\n      const Differentiation::SD::types::substitution_map \n        substitution_map_explicit = Differentiation::SD::make_substitution_map( \n          std::make_pair(Q_t_sd, Q_t_sd_explicit)); \n\n// \u6211\u4eec\u53ef\u4ee5\u5728\u4e24\u4e2a\u52a8\u529b\u5b66\u53d8\u91cf\u4e0a\u8fdb\u884c\u8fd9\u79cd\u66ff\u6362\uff0c\u5e76\u7acb\u5373\u5c06\u66ff\u6362\u540e\u7684\u7ed3\u679c\u4e0e\u573a\u53d8\u91cf\u8fdb\u884c\u533a\u5206\u3002(\u5982\u679c\u4f60\u613f\u610f\uff0c\u8fd9\u53ef\u4ee5\u5206\u6210\u4e24\u6b65\u8fdb\u884c\uff0c\u4e2d\u95f4\u7684\u7ed3\u679c\u50a8\u5b58\u5728\u4e00\u4e2a\u4e34\u65f6\u53d8\u91cf\u4e2d)\u3002\u540c\u6837\uff0c\u5982\u679c\u4f60\u5ffd\u7565\u4e86\u4ee3\u6362\u6240\u4ea7\u751f\u7684 \"\u590d\u6742\u6027\"\uff0c\u8fd9\u4e9b\u5c06\u8fd0\u52a8\u53d8\u91cf\u7ebf\u6027\u5316\u5e76\u4ea7\u751f\u4e09\u4e2a\u5207\u5411\u5f20\u91cf\u7684\u8c03\u7528\u4e0e\u7406\u8bba\u4e2d\u6240\u8ff0\u7684\u975e\u5e38\u76f8\u4f3c\u3002\n\n      BB_sd = symmetrize(Differentiation::SD::differentiate( \n        Differentiation::SD::substitute(B_sd, substitution_map_explicit), \n        H_sd)); \n      PP_sd = -Differentiation::SD::differentiate( \n        Differentiation::SD::substitute(S_sd, substitution_map_explicit), H_sd); \n      HH_sd = \n        2.0 * \n        Differentiation::SD::differentiate( \n          Differentiation::SD::substitute(S_sd, substitution_map_explicit), \n          C_sd); \n\n// \u73b0\u5728\u6211\u4eec\u9700\u8981\u544a\u8bc9 @p optimizer \u6211\u4eec\u9700\u8981\u63d0\u4f9b\u54ea\u4e9b\u6761\u76ee\u7684\u6570\u503c\uff0c\u4ee5\u4fbf\u5b83\u80fd\u6210\u529f\u5730\u8fdb\u884c\u8ba1\u7b97\u3002\u8fd9\u4e9b\u57fa\u672c\u4e0a\u5145\u5f53\u4e86 @p optimizer \u5fc5\u987b\u8bc4\u4f30\u7684\u6240\u6709\u4ece\u5c5e\u51fd\u6570\u7684\u8f93\u5165\u53c2\u6570\u3002\u5b83\u4eec\u7edf\u79f0\u4e3a\u95ee\u9898\u7684\u81ea\u53d8\u91cf\u3001\u5386\u53f2\u53d8\u91cf\u3001\u65f6\u95f4\u6b65\u957f\u548c\u6784\u6210\u53c2\u6570\uff08\u56e0\u4e3a\u6211\u4eec\u6ca1\u6709\u5728\u80fd\u91cf\u5bc6\u5ea6\u51fd\u6570\u4e2d\u786c\u7f16\u7801\u5b83\u4eec\uff09\u3002\n\n// \u56e0\u6b64\uff0c\u6211\u4eec\u771f\u6b63\u60f3\u8981\u7684\u662f\u4e3a\u5b83\u63d0\u4f9b\u4e00\u4e2a\u7b26\u53f7\u96c6\u5408\uff0c\u6211\u4eec\u53ef\u4ee5\u8fd9\u6837\u5b8c\u6210\u3002\n// @code\n//  optimizer.register_symbols(Differentiation::SD::make_symbol_map(\n//    mu_e_sd, mu_e_inf_sd, mu_e_h_sat_sd, lambda_e_sd,\n//    mu_v_sd, mu_v_inf_sd, mu_v_h_sat_sd, tau_v_sd,\n//    delta_t_sd, mu_r_sd,\n//    H_sd, C_sd,\n//    Q_t_sd, Q_t1_sd));\n//  @endcode \n//  \u4f46\u8fd9\u5b9e\u9645\u4e0a\u90fd\u5df2\u7ecf\u88ab\u7f16\u7801\u4e3a\u66ff\u6362\u56fe\u7684\u952e\u3002\u8fd9\u6837\u505a\u8fd8\u610f\u5473\u7740\u6211\u4eec\u9700\u8981\u5728\u4e24\u4e2a\u5730\u65b9\uff08\u8fd9\u91cc\u548c\u6784\u5efa\u66ff\u6362\u56fe\u65f6\uff09\u7ba1\u7406\u8fd9\u4e9b\u7b26\u53f7\uff0c\u8fd9\u5f88\u70e6\u4eba\uff0c\u800c\u4e14\u5982\u679c\u8fd9\u4e2a\u6750\u6599\u7c7b\u88ab\u4fee\u6539\u6216\u6269\u5c55\uff0c\u53ef\u80fd\u4f1a\u51fa\u73b0\u9519\u8bef\u3002\u7531\u4e8e\u6211\u4eec\u6b64\u65f6\u5bf9\u6570\u503c\u4e0d\u611f\u5174\u8da3\uff0c\u6240\u4ee5\u5982\u679c\u66ff\u6362\u56fe\u4e2d\u4e0e\u6bcf\u4e2a\u952e\u9879\u76f8\u5173\u7684\u6570\u503c\u88ab\u586b\u5165\u65e0\u6548\u7684\u6570\u636e\u4e5f\u6ca1\u6709\u5173\u7cfb\u3002\u6240\u4ee5\u6211\u4eec\u5c06\u7b80\u5355\u5730\u521b\u5efa\u4e00\u4e2a\u5047\u7684\u66ff\u6362\u56fe\uff0c\u5e76\u4ece\u4e2d\u63d0\u53d6\u7b26\u53f7\u3002\u8bf7\u6ce8\u610f\uff0c\u4efb\u4f55\u4f20\u9012\u7ed9 @p optimizer \u7684\u66ff\u6362\u56fe\u90fd\u5fc5\u987b\u81f3\u5c11\u5305\u542b\u8fd9\u4e9b\u7b26\u53f7\u7684\u6761\u76ee\u3002\n\n      optimizer.register_symbols( \n        Differentiation::SD::Utilities::extract_symbols( \n          make_substitution_map({}, {}, 0))); \n\n// \u7136\u540e\u6211\u4eec\u901a\u77e5\u4f18\u5316\u5668\u6211\u4eec\u60f3\u8981\u8ba1\u7b97\u54ea\u4e9b\u6570\u503c\uff0c\u5728\u6211\u4eec\u7684\u60c5\u51b5\u4e0b\uff0c\u8fd9\u5305\u62ec\u6240\u6709\u7684\u56e0\u53d8\u91cf\uff08\u5373\u80fd\u91cf\u5bc6\u5ea6\u51fd\u6570\u53ca\u5176\u5404\u79cd\u5bfc\u6570\uff09\u3002\n\n      optimizer.register_functions(psi_sd, B_sd, S_sd, BB_sd, PP_sd, HH_sd); \n\n// \u6700\u540e\u4e00\u6b65\u662f\u6700\u7ec8\u786e\u5b9a\u4f18\u5316\u5668\u3002\u901a\u8fc7\u8fd9\u4e2a\u8c03\u7528\uff0c\u5b83\u5c06\u786e\u5b9a\u4e00\u4e2a\u7b49\u4ef7\u7684\u4ee3\u7801\u8def\u5f84\uff0c\u4e00\u6b21\u6027\u8bc4\u4f30\u6240\u6709\u7684\u4ece\u5c5e\u51fd\u6570\uff0c\u4f46\u8ba1\u7b97\u6210\u672c\u6bd4\u76f4\u63a5\u8bc4\u4f30\u7b26\u53f7\u8868\u8fbe\u5f0f\u65f6\u8981\u4f4e\u3002\u6ce8\u610f\uff1a\u8fd9\u662f\u4e00\u4e2a\u6602\u8d35\u7684\u8c03\u7528\uff0c\u6240\u4ee5\u6211\u4eec\u5e0c\u671b\u5c3d\u53ef\u80fd\u5c11\u5730\u6267\u884c\u5b83\u3002\u6211\u4eec\u5728\u7c7b\u7684\u6784\u9020\u51fd\u6570\u4e2d\u5b8c\u6210\u4e86\u8fd9\u4e00\u8fc7\u7a0b\uff0c\u5b9e\u73b0\u4e86\u6bcf\u4e2a\u7c7b\u5b9e\u4f8b\u53ea\u88ab\u8c03\u7528\u4e00\u6b21\u7684\u76ee\u6807\u3002\n\n      optimizer.optimize(); \n    } \n\n// \u7531\u4e8e @p optimizer \u7684\u914d\u7f6e\u662f\u5728\u524d\u9762\u5b8c\u6210\u7684\uff0c\u6240\u4ee5\u6bcf\u6b21\u6211\u4eec\u60f3\u8ba1\u7b97\u52a8\u80fd\u53d8\u91cf\u6216\u5b83\u4eec\u7684\u7ebf\u6027\u5316\uff08\u5bfc\u6570\uff09\u65f6\uff0c\u8981\u505a\u7684\u4e8b\u60c5\u5c31\u5f88\u5c11\u4e86\u3002\n\n    template <int dim> \n    void Magnetoviscoelastic_Constitutive_Law_SD<dim>::update_internal_data( \n      const SymmetricTensor<2, dim> &C, \n      const Tensor<1, dim> &         H, \n      const DiscreteTime &           time) \n    { \n\n// \u4e3a\u4e86\u66f4\u65b0\u5185\u90e8\u5386\u53f2\u53d8\u91cf\uff0c\u6211\u4eec\u9996\u5148\u9700\u8981\u8ba1\u7b97\u4e00\u4e9b\u57fa\u672c\u91cf\uff0c\u8fd9\u4e00\u70b9\u6211\u4eec\u4e4b\u524d\u5df2\u7ecf\u770b\u5230\u4e86\u3002\u6211\u4eec\u8fd8\u53ef\u4ee5\u5411\u65f6\u95f4\u79bb\u6563\u5668\u8be2\u95ee\u7528\u4e8e\u4ece\u4e0a\u4e00\u4e2a\u65f6\u95f4\u6b65\u957f\u8fed\u4ee3\u5230\u5f53\u524d\u65f6\u95f4\u6b65\u957f\u7684\u65f6\u95f4\u6b65\u957f\u3002\n\n      const double delta_t = this->get_delta_t(time); \n\n      const double                  det_F = std::sqrt(determinant(C)); \n      const SymmetricTensor<2, dim> C_inv = invert(C); \n      AssertThrow(det_F > 0.0, \n                  ExcMessage(\"Volumetric Jacobian must be positive.\")); \n\n// \u73b0\u5728\uff0c\u6211\u4eec\u53ef\u4ee5\u6309\u7167\u6f14\u5316\u89c4\u5f8b\u7ed9\u51fa\u7684\u5b9a\u4e49\uff0c\u7ed3\u5408\u6240\u9009\u62e9\u7684\u65f6\u95f4\u79bb\u6563\u5316\u65b9\u6848\uff0c\u66f4\u65b0\uff08\u5b9e\u503c\uff09\u5185\u90e8\u7c98\u6027\u53d8\u5f62\u5f20\u91cf\u3002\n\n      Q_t = (1.0 / (1.0 + delta_t / this->get_tau_v())) * \n            (Q_t1 + (delta_t / this->get_tau_v()) * std::pow(det_F, 2.0 / dim) * \n                      C_inv); \n\n// \u63a5\u4e0b\u6765\u6211\u4eec\u5411\u4f18\u5316\u5668\u4f20\u9012\u6211\u4eec\u5e0c\u671b\u81ea\u53d8\u91cf\u3001\u65f6\u95f4\u6b65\u957f\u548c\uff08\u672c\u8c03\u7528\u9690\u542b\u7684\uff09\u6784\u6210\u53c2\u6570\u6240\u4ee3\u8868\u7684\u6570\u503c\u3002\n\n      const auto substitution_map = make_substitution_map(C, H, delta_t); \n\n// \u5728\u8fdb\u884c\u4e0b\u4e00\u6b21\u8c03\u7528\u65f6\uff0c\u7528\u4e8e\uff08\u6570\u503c\uff09\u8bc4\u4f30\u4ece\u5c5e\u51fd\u6570\u7684\u8c03\u7528\u8def\u5f84\u8981\u6bd4\u5b57\u5178\u66ff\u6362\u66f4\u5feb\u3002\n\n      optimizer.substitute(substitution_map); \n    } \n\n// \u5728\u8c03\u7528\u4e86`update_internal_data()`\u4e4b\u540e\uff0c\u4ece\u4f18\u5316\u5668\u4e2d\u63d0\u53d6\u6570\u636e\u5c31\u6709\u6548\u4e86\u3002\u5728\u8fdb\u884c\u8bc4\u4f30\u65f6\uff0c\u6211\u4eec\u9700\u8981\u4ece\u4f18\u5316\u5668\u4e2d\u63d0\u53d6\u6570\u636e\u7684\u786e\u5207\u7b26\u53f7\u8868\u8fbe\u5f0f\u3002\u8fd9\u610f\u5473\u7740\u6211\u4eec\u9700\u8981\u5728\u4f18\u5316\u5668\u7684\u751f\u547d\u5468\u671f\u5185\u5b58\u50a8\u6240\u6709\u56e0\u53d8\u91cf\u7684\u7b26\u53f7\u8868\u8fbe\u5f0f\uff08\u81ea\u7136\uff0c\u5bf9\u8f93\u5165\u53d8\u91cf\u4e5f\u6709\u540c\u6837\u7684\u6697\u793a\uff09\u3002\n\n    template <int dim> \n    double Magnetoviscoelastic_Constitutive_Law_SD<dim>::get_psi() const \n    { \n      return optimizer.evaluate(psi_sd); \n    } \n\n    template <int dim> \n    Tensor<1, dim> Magnetoviscoelastic_Constitutive_Law_SD<dim>::get_B() const \n    { \n      return optimizer.evaluate(B_sd); \n    } \n\n    template <int dim> \n    SymmetricTensor<2, dim> \n    Magnetoviscoelastic_Constitutive_Law_SD<dim>::get_S() const \n    { \n      return optimizer.evaluate(S_sd); \n    } \n\n    template <int dim> \n    SymmetricTensor<2, dim> \n    Magnetoviscoelastic_Constitutive_Law_SD<dim>::get_DD() const \n    { \n      return optimizer.evaluate(BB_sd); \n    } \n\n    template <int dim> \n    Tensor<3, dim> Magnetoviscoelastic_Constitutive_Law_SD<dim>::get_PP() const \n    { \n      return optimizer.evaluate(PP_sd); \n    } \n\n    template <int dim> \n    SymmetricTensor<4, dim> \n    Magnetoviscoelastic_Constitutive_Law_SD<dim>::get_HH() const \n    { \n      return optimizer.evaluate(HH_sd); \n    } \n\n// \u5f53\u5728\u65f6\u95f4\u4e0a\u5411\u524d\u79fb\u52a8\u65f6\uff0c\u5185\u90e8\u53d8\u91cf\u7684 \"\u5f53\u524d \"\u72b6\u6001\u77ac\u95f4\u5b9a\u4e49\u4e86 \"\u524d \"\u65f6\u95f4\u6bb5\u7684\u72b6\u6001\u3002\u56e0\u6b64\uff0c\u6211\u4eec\u8bb0\u5f55\u5386\u53f2\u53d8\u91cf\u7684\u503c\uff0c\u4f5c\u4e3a\u4e0b\u4e00\u4e2a\u65f6\u95f4\u6b65\u957f\u7684 \"\u8fc7\u53bb\u503c \"\u4f7f\u7528\u3002\n\n    template <int dim> \n    void Magnetoviscoelastic_Constitutive_Law_SD<dim>::update_end_of_timestep() \n    { \n      Q_t1 = Q_t; \n    } \n// @sect3{A more complex example (continued): Parameters and hand-derived material classes}  \n\n// \u73b0\u5728\u6211\u4eec\u5df2\u7ecf\u770b\u5230\u4e86AD\u548cSD\u6846\u67b6\u5982\u4f55\u5728\u5b9a\u4e49\u8fd9\u4e9b\u6784\u6210\u6cd5\u5219\u65b9\u9762\u505a\u4e86\u5927\u91cf\u7684\u5de5\u4f5c\uff0c\u4e3a\u4e86\u9a8c\u8bc1\uff0c\u6211\u4eec\u5c06\u624b\u5de5\u5b9e\u73b0\u76f8\u5e94\u7684\u7c7b\uff0c\u5e76\u5bf9\u6846\u67b6\u4e0e\u672c\u5730\u5b9e\u73b0\u505a\u4e00\u4e9b\u521d\u6b65\u7684\u57fa\u51c6\u6d4b\u8bd5\u3002\n\n// \u4e3a\u4e86\u4fdd\u8bc1\u4f5c\u8005\u7684\u7406\u667a\uff0c\u4e0b\u9762\u8bb0\u5f55\u7684\uff08\u5e0c\u671b\u662f\u51c6\u786e\u7684\uff09\u662f\u52a8\u80fd\u53d8\u91cf\u548c\u5b83\u4eec\u7684\u5207\u7ebf\u7684\u5b8c\u6574\u5b9a\u4e49\uff0c\u4ee5\u53ca\u4e00\u4e9b\u4e2d\u95f4\u8ba1\u7b97\u8fc7\u7a0b\u3002\u7531\u4e8e\u6784\u6210\u6cd5\u5219\u7c7b\u7684\u7ed3\u6784\u548c\u8bbe\u8ba1\u5df2\u7ecf\u5728\u524d\u9762\u6982\u8ff0\u8fc7\u4e86\uff0c\u6211\u4eec\u5c06\u7565\u8fc7\u5b83\uff0c\u53ea\u662f\u5728 \"update_internal_data() \"\u65b9\u6cd5\u7684\u5b9a\u4e49\u4e2d\u5bf9\u5404\u9636\u6bb5\u7684\u8ba1\u7b97\u8fdb\u884c\u5212\u5206\u3002\u5c06\u5bfc\u6570\u8ba1\u7b97\uff08\u53ca\u5176\u9002\u5ea6\u8868\u8fbe\u7684\u53d8\u91cf\u540d\uff09\u4e0e\u51fa\u73b0\u5728\u7c7b\u63cf\u8ff0\u4e2d\u7684\u6587\u6863\u5b9a\u4e49\u8054\u7cfb\u8d77\u6765\u5e94\u8be5\u662f\u5f88\u5bb9\u6613\u7684\u3002\u7136\u800c\uff0c\u6211\u4eec\u5c06\u501f\u6b64\u673a\u4f1a\u4ecb\u7ecd\u4e24\u79cd\u5b9e\u73b0\u6784\u6210\u6cd5\u7c7b\u7684\u4e0d\u540c\u8303\u5f0f\u3002\u7b2c\u4e8c\u79cd\u5c06\u6bd4\u7b2c\u4e00\u79cd\u63d0\u4f9b\u66f4\u591a\u7684\u7075\u6d3b\u6027\uff08\u4ece\u800c\u4f7f\u5176\u66f4\u5bb9\u6613\u6269\u5c55\uff0c\u5728\u4f5c\u8005\u770b\u6765\uff09\uff0c\u4f46\u8981\u727a\u7272\u4e00\u4e9b\u6027\u80fd\u3002\n\n//  @sect4{Magnetoelastic constitutive law (hand-derived)}  \n\n// \u4ece\u524d\u9762\u63d0\u5230\u7684\u50a8\u5b58\u80fd\u91cf\u4e2d\uff0c\u5bf9\u4e8e\u8fd9\u79cd\u78c1\u5f39\u6027\u6750\u6599\uff0c\u5b9a\u4e49\u4e3a\n// @f[\n//    \\psi_{0} \\left( \\mathbf{C}, \\boldsymbol{\\mathbb{H}} \\right)\n//  = \\frac{1}{2} \\mu_{e} f_{\\mu_{e}} \\left( \\boldsymbol{\\mathbb{H}} \\right)\n//      \\left[ \\text{tr}(\\mathbf{C}) - d - 2 \\ln (\\text{det}(\\mathbf{F}))\n//      \\right]\n//  + \\lambda_{e} \\ln^{2} \\left(\\text{det}(\\mathbf{F}) \\right)\n//  - \\frac{1}{2} \\mu_{0} \\mu_{r} \\text{det}(\\mathbf{F})\n//      \\left[ \\boldsymbol{\\mathbb{H}} \\cdot \\mathbf{C}^{-1} \\cdot\n//      \\boldsymbol{\\mathbb{H}} \\right]\n//  @f]\n//  \u4e0e\n//  @f[\n//   f_{\\mu_{e}} \\left( \\boldsymbol{\\mathbb{H}} \\right)\n//  = 1 + \\left[ \\frac{\\mu_{e}^{\\infty}}{\\mu_{e}} - 1 \\right]\n//      \\tanh \\left( 2 \\frac{\\boldsymbol{\\mathbb{H}} \\cdot\n//      \\boldsymbol{\\mathbb{H}}}\n//        {\\left(h_{e}^{\\text{sat}}\\right)^{2}} \\right) ,\n//  \\\\ \\text{det}(\\mathbf{F}) = \\sqrt{\\text{det}(\\mathbf{C})}\n//  @f]\n//  \uff0c\u5bf9\u5e94\u4e8e\u78c1\u611f\u5e94\u5411\u91cf\u548c\u603bPiola-Kirchhoff\u5e94\u529b\u5f20\u91cf\u7684\u7b2c\u4e00\u5bfc\u6570\u662f\n//  @f[\n//   \\boldsymbol{\\mathbb{B}} \\left( \\mathbf{C}, \\boldsymbol{\\mathbb{H}}\n//   \\right)\n//  \\dealcoloneq - \\frac{d \\psi_{0}}{d \\boldsymbol{\\mathbb{H}}}\n//  = - \\frac{1}{2} \\mu_{e} \\left[ \\text{tr}(\\mathbf{C}) - d - 2 \\ln\n//  (\\text{det}(\\mathbf{F}))\n//        \\right] \\frac{d f_{\\mu_{e}} \\left( \\boldsymbol{\\mathbb{H}}\n//        \\right)}{d \\boldsymbol{\\mathbb{H}}}\n//  + \\mu_{0} \\mu_{r} \\text{det}(\\mathbf{F}) \\left[ \\mathbf{C}^{-1} \\cdot\n//  \\boldsymbol{\\mathbb{H}}\n//      \\right]\n//  @f] \n\n// @f{align}\n//   \\mathbf{S}^{\\text{tot}} \\left( \\mathbf{C}, \\boldsymbol{\\mathbb{H}}\n//   \\right)\n//  \\dealcoloneq 2 \\frac{d \\psi_{0} \\left( \\mathbf{C},\n//  \\boldsymbol{\\mathbb{H}} \\right)}{d \\mathbf{C}}\n//  &= \\mu_{e} f_{\\mu_{e}} \\left( \\boldsymbol{\\mathbb{H}} \\right)\n//      \\left[ \\frac{d\\,\\text{tr}(\\mathbf{C})}{d \\mathbf{C}}\n//      - 2 \\frac{1}{\\text{det}(\\mathbf{F})}\n//      \\frac{d\\,\\text{det}(\\mathbf{F})}{d \\mathbf{C}} \\right]\n//  + 4 \\lambda_{e} \\ln \\left(\\text{det}(\\mathbf{F}) \\right)\n//      \\frac{1}{\\text{det}(\\mathbf{F})} \\frac{d\\,\\text{det}(\\mathbf{F})}{d\n//      \\mathbf{C}}\n//  - \\mu_{0} \\mu_{r} \\left[\n//      \\left[ \\boldsymbol{\\mathbb{H}} \\cdot \\mathbf{C}^{-1} \\cdot\n//      \\boldsymbol{\\mathbb{H}} \\right] \\frac{d\\,\\text{det}(\\mathbf{F})}{d\n//      \\mathbf{C}} + \\text{det}(\\mathbf{F}) \\frac{d \\left[\n//      \\boldsymbol{\\mathbb{H}} \\cdot \\mathbf{C}^{-1} \\cdot\n//      \\boldsymbol{\\mathbb{H}}\n//        \\right]}{d \\mathbf{C}} \\right]\n//  \\\\ &= \\mu_{e} f_{\\mu_{e}} \\left( \\boldsymbol{\\mathbb{H}} \\right)\n//      \\left[ \\mathbf{I} - \\mathbf{C}^{-1} \\right]\n//  + 2 \\lambda_{e} \\ln \\left(\\text{det}(\\mathbf{F}) \\right) \\mathbf{C}^{-1}\n//  - \\mu_{0} \\mu_{r} \\left[\n//      \\frac{1}{2}  \\left[ \\boldsymbol{\\mathbb{H}} \\cdot \\mathbf{C}^{-1}\n//      \\cdot \\boldsymbol{\\mathbb{H}} \\right] \\text{det}(\\mathbf{F})\n//      \\mathbf{C}^{-1}\n//  - \\text{det}(\\mathbf{F})\n//      \\left[ \\mathbf{C}^{-1} \\cdot \\boldsymbol{\\mathbb{H}} \\right] \\otimes\n//        \\left[ \\mathbf{C}^{-1} \\cdot \\boldsymbol{\\mathbb{H}} \\right]\n//        \\right]\n//  @f} \n//  \u4e0e\n//  @f[\n//    \\frac{d f_{\\mu_{e}} \\left( \\boldsymbol{\\mathbb{H}} \\right)}{d\n//    \\boldsymbol{\\mathbb{H}}}\n//  = \\left[ \\frac{\\mu_{e}^{\\infty}}{\\mu_{e}} - 1 \\right]\n//    \\text{sech}^{2} \\left( 2 \\frac{\\boldsymbol{\\mathbb{H}} \\cdot\n//    \\boldsymbol{\\mathbb{H}}}\n//      {\\left(h_{e}^{\\text{sat}}\\right)^{2}} \\right)\n//    \\left[ \\frac{4} {\\left(h_{e}^{\\text{sat}}\\right)^{2}}\n//    \\boldsymbol{\\mathbb{H}} \\right]\n//  @f] \u3002\n\n// @f[\n//    \\frac{d\\,\\text{tr}(\\mathbf{C})}{d \\mathbf{C}}\n//  = \\mathbf{I}\n//  \\quad \\text{(the second-order identity tensor)}\n//  @f] \n\n// @f[\n//    \\frac{d\\,\\text{det}(\\mathbf{F})}{d \\mathbf{C}}\n//  = \\frac{1}{2} \\text{det}(\\mathbf{F}) \\mathbf{C}^{-1}\n//  @f] \n\n// @f[\n//  \\frac{d C^{-1}_{ab}}{d C_{cd}}\n//  = - \\text{sym} \\left( C^{-1}_{ac} C^{-1}_{bd} \\right)\n//  = -\\frac{1}{2} \\left[ C^{-1}_{ac} C^{-1}_{bd} + C^{-1}_{ad} C^{-1}_{bc}\n//  \\right]\n//  @f] \n\n// @f[\n//    \\frac{d \\left[ \\boldsymbol{\\mathbb{H}} \\cdot \\mathbf{C}^{-1} \\cdot\n//    \\boldsymbol{\\mathbb{H}} \\right]}{d \\mathbf{C}}\n//  = - \\left[ \\mathbf{C}^{-1} \\cdot \\boldsymbol{\\mathbb{H}} \\right] \\otimes\n//    \\left[ \\mathbf{C}^{-1} \\cdot \\boldsymbol{\\mathbb{H}} \\right]\n//  @f] \n//  \u5728\u4e0a\u9762\u7684\u4e00\u4e2a\u63a8\u5bfc\u4e2d\u4f7f\u7528\u5bf9\u79f0\u7b97\u5b50 $\\text{sym} \\left( \\bullet \\right)$ \u6709\u52a9\u4e8e\u786e\u4fdd\u6240\u4ea7\u751f\u7684\u79e9-4\u5f20\u91cf\uff0c\u7531\u4e8e $\\mathbf{C}$ \u7684\u5bf9\u79f0\u6027\u800c\u6301\u6709\u5c0f\u7684\u5bf9\u79f0\u6027\uff0c\u4ecd\u7136\u5c06\u79e9-2\u5bf9\u79f0\u5f20\u91cf\u6620\u5c04\u4e3a\u79e9-2\u5bf9\u79f0\u5f20\u91cf\u3002\u53c2\u89c1SymmetricTensor\u7c7b\u6587\u6863\u548c step-44 \u7684\u4ecb\u7ecd\uff0c\u5e76\u8fdb\u4e00\u6b65\u89e3\u91ca\u5728\u56db\u9636\u5f20\u91cf\u7684\u80cc\u666f\u4e0b\u5bf9\u79f0\u6027\u7684\u542b\u4e49\u3002\n\n//\u6bcf\u4e2a\u8fd0\u52a8\u5b66\u53d8\u91cf\u76f8\u5bf9\u4e8e\u5176\u53c2\u6570\u7684\u7ebf\u6027\u5316\u662f\n// @f[\n//  \\mathbb{D} \\left( \\mathbf{C}, \\boldsymbol{\\mathbb{H}} \\right)\n//  = \\frac{d \\boldsymbol{\\mathbb{B}}}{d \\boldsymbol{\\mathbb{H}}}\n//  = - \\frac{1}{2} \\mu_{e} \\left[ \\text{tr}(\\mathbf{C}) - d - 2 \\ln\n//  (\\text{det}(\\mathbf{F}))\n//      \\right] \\frac{d^{2} f_{\\mu_{e}} \\left( \\boldsymbol{\\mathbb{H}}\n//      \\right)}{d \\boldsymbol{\\mathbb{H}} \\otimes d \\boldsymbol{\\mathbb{H}}}\n//  + \\mu_{0} \\mu_{r} \\text{det}(\\mathbf{F}) \\mathbf{C}^{-1}\n//  @f] \n\n// @f{align}\n//  \\mathfrak{P}^{\\text{tot}} \\left( \\mathbf{C}, \\boldsymbol{\\mathbb{H}}\n//  \\right) = - \\frac{d \\mathbf{S}^{\\text{tot}}}{d \\boldsymbol{\\mathbb{H}}}\n//  &= - \\mu_{e}\n//      \\left[ \\frac{d\\,\\text{tr}(\\mathbf{C})}{d \\mathbf{C}}\n//      - 2 \\frac{1}{\\text{det}(\\mathbf{F})}\n//      \\frac{d\\,\\text{det}(\\mathbf{F})}{d \\mathbf{C}} \\right]\n//        \\otimes \\frac{d f_{\\mu_{e} \\left( \\boldsymbol{\\mathbb{H}}\n//        \\right)}}{d \\boldsymbol{\\mathbb{H}}}\n//  + \\mu_{0} \\mu_{r} \\left[\n//      \\frac{d\\,\\text{det}(\\mathbf{F})}{d \\mathbf{C}} \\otimes\n//        \\frac{d \\left[ \\boldsymbol{\\mathbb{H}} \\cdot \\mathbf{C}^{-1} \\cdot\n//        \\boldsymbol{\\mathbb{H}}\n//          \\right]}{d \\boldsymbol{\\mathbb{H}}} \\right]\n//  + \\text{det}(\\mathbf{F})\n//      \\frac{d^{2} \\left[ \\boldsymbol{\\mathbb{H}} \\cdot \\mathbf{C}^{-1}\n//      \\cdot \\boldsymbol{\\mathbb{H}}\n//        \\right]}{d \\mathbf{C} \\otimes d \\boldsymbol{\\mathbb{H}}}\n//  \\\\ &= - \\mu_{e}\n//      \\left[ \\mathbf{I} - \\mathbf{C}^{-1} \\right] \\otimes\n//        \\frac{d f_{\\mu_{e} \\left( \\boldsymbol{\\mathbb{H}} \\right)}}{d\n//        \\boldsymbol{\\mathbb{H}}}\n//  + \\mu_{0} \\mu_{r} \\left[\n//      \\text{det}(\\mathbf{F}) \\mathbf{C}^{-1} \\otimes\n//        \\left[ \\mathbf{C}^{-1} \\cdot \\boldsymbol{\\mathbb{H}} \\right]\n//        \\right]\n//  + \\text{det}(\\mathbf{F})\n//      \\frac{d^{2} \\left[ \\boldsymbol{\\mathbb{H}} \\cdot \\mathbf{C}^{-1}\n//      \\cdot \\boldsymbol{\\mathbb{H}}\n//        \\right]}{d \\mathbf{C} \\otimes \\mathbf{C} \\boldsymbol{\\mathbb{H}}}\n//  @f} \n\n\n// @f{align}\n//  \\mathcal{H}^{\\text{tot}} \\left( \\mathbf{C}, \\boldsymbol{\\mathbb{H}}\n//  \\right) = 2 \\frac{d \\mathbf{S}^{\\text{tot}}}{d \\mathbf{C}}\n//  &= 2 \\mu_{e} f_{\\mu_{e}} \\left( \\boldsymbol{\\mathbb{H}} \\right)\n//      \\left[ - \\frac{d \\mathbf{C}^{-1}}{d \\mathbf{C}} \\right]\n//    + 4 \\lambda_{e} \\left[ \\mathbf{C}^{-1} \\otimes \\left[\n//    \\frac{1}{\\text{det}(\\mathbf{F})} \\frac{d \\, \\text{det}(\\mathbf{F})}{d\n//    \\mathbf{C}} \\right] + \\ln \\left(\\text{det}(\\mathbf{F}) \\right) \\frac{d\n//    \\mathbf{C}^{-1}}{d \\mathbf{C}} \\right]\n//  \\\\ &- \\mu_{0} \\mu_{r}  \\left[\n//   \\text{det}(\\mathbf{F}) \\mathbf{C}^{-1} \\otimes \\frac{d \\left[\n//   \\boldsymbol{\\mathbb{H}} \\cdot \\mathbf{C}^{-1} \\cdot\n//   \\boldsymbol{\\mathbb{H}} \\right]}{d \\mathbf{C}}\n//  + \\left[ \\boldsymbol{\\mathbb{H}} \\cdot \\mathbf{C}^{-1} \\cdot\n//  \\boldsymbol{\\mathbb{H}} \\right] \\mathbf{C}^{-1} \\otimes \\frac{d \\,\n//  \\text{det}(\\mathbf{F})}{d \\mathbf{C}}\n//  + \\left[ \\boldsymbol{\\mathbb{H}} \\cdot \\mathbf{C}^{-1} \\cdot\n//  \\boldsymbol{\\mathbb{H}} \\right] \\text{det}(\\mathbf{F}) \\frac{d\n//  \\mathbf{C}^{-1}}{d \\mathbf{C}}\n//  \\right]\n//  \\\\ &+ 2 \\mu_{0} \\mu_{r} \\left[ \\left[\n//      \\left[ \\mathbf{C}^{-1} \\cdot \\boldsymbol{\\mathbb{H}} \\right] \\otimes\n//        \\left[ \\mathbf{C}^{-1} \\cdot \\boldsymbol{\\mathbb{H}} \\right]\n//        \\right] \\otimes \\frac{d \\, \\text{det}(\\mathbf{F})}{d \\mathbf{C}}\n//      - \\text{det}(\\mathbf{F})\n//      \\frac{d^{2} \\left[ \\boldsymbol{\\mathbb{H}} \\cdot \\mathbf{C}^{-1}\n//      \\cdot \\boldsymbol{\\mathbb{H}}\\right]}{d \\mathbf{C} \\otimes d\n//      \\mathbf{C}}\n//  \\right]\n//  \\\\ &= 2 \\mu_{e} f_{\\mu_{e}} \\left( \\boldsymbol{\\mathbb{H}} \\right)\n//      \\left[ - \\frac{d \\mathbf{C}^{-1}}{d \\mathbf{C}} \\right]\n//   + 4 \\lambda_{e} \\left[ \\frac{1}{2} \\mathbf{C}^{-1} \\otimes\n//   \\mathbf{C}^{-1} + \\ln \\left(\\text{det}(\\mathbf{F}) \\right) \\frac{d\n//   \\mathbf{C}^{-1}}{d \\mathbf{C}} \\right]\n//  \\\\ &- \\mu_{0} \\mu_{r}  \\left[\n//   - \\text{det}(\\mathbf{F}) \\mathbf{C}^{-1} \\otimes \\left[ \\left[\n//   \\mathbf{C}^{-1} \\cdot \\boldsymbol{\\mathbb{H}} \\right] \\otimes\n//    \\left[ \\mathbf{C}^{-1} \\cdot \\boldsymbol{\\mathbb{H}} \\right] \\right]\n//  + \\frac{1}{2} \\left[ \\boldsymbol{\\mathbb{H}} \\cdot \\mathbf{C}^{-1} \\cdot\n//  \\boldsymbol{\\mathbb{H}} \\right] \\text{det}(\\mathbf{F})  \\mathbf{C}^{-1}\n//  \\otimes \\mathbf{C}^{-1}\n//  + \\left[ \\boldsymbol{\\mathbb{H}} \\cdot \\mathbf{C}^{-1} \\cdot\n//  \\boldsymbol{\\mathbb{H}} \\right] \\text{det}(\\mathbf{F}) \\frac{d\n//  \\mathbf{C}^{-1}}{d \\mathbf{C}}\n//  \\right]\n//  \\\\ &+ 2 \\mu_{0} \\mu_{r} \\left[ \\frac{1}{2} \\text{det}(\\mathbf{F}) \\left[\n//      \\left[ \\mathbf{C}^{-1} \\cdot \\boldsymbol{\\mathbb{H}} \\right] \\otimes\n//        \\left[ \\mathbf{C}^{-1} \\cdot \\boldsymbol{\\mathbb{H}} \\right]\n//        \\right] \\otimes \\mathbf{C}^{-1}\n//      - \\text{det}(\\mathbf{F})\n//      \\frac{d^{2} \\left[ \\boldsymbol{\\mathbb{H}} \\cdot \\mathbf{C}^{-1}\n//      \\cdot \\boldsymbol{\\mathbb{H}}\\right]}{d \\mathbf{C} \\otimes d\n//      \\mathbf{C}}\n//  \\right]\n//  @f}\n//  \u4e0e\n//  @f[\n//   \\frac{d^{2} f_{\\mu_{e}} \\left( \\boldsymbol{\\mathbb{H}} \\right)}{d\n//   \\boldsymbol{\\mathbb{H}} \\otimes d \\boldsymbol{\\mathbb{H}}}\n//  = -2 \\left[ \\frac{\\mu_{e}^{\\infty}}{\\mu_{e}} - 1 \\right]\n//    \\tanh \\left( 2 \\frac{\\boldsymbol{\\mathbb{H}} \\cdot\n//    \\boldsymbol{\\mathbb{H}}}\n//      {\\left(h_{e}^{\\text{sat}}\\right)^{2}} \\right)\n//    \\text{sech}^{2} \\left( 2 \\frac{\\boldsymbol{\\mathbb{H}} \\cdot\n//    \\boldsymbol{\\mathbb{H}}}\n//      {\\left(h_{e}^{\\text{sat}}\\right)^{2}} \\right)\n//    \\left[ \\frac{4} {\\left(h_{e}^{\\text{sat}}\\right)^{2}} \\mathbf{I}\n//    \\right]\n//  @f] \n\n// @f[\n//  \\frac{d \\left[ \\boldsymbol{\\mathbb{H}} \\cdot \\mathbf{C}^{-1} \\cdot\n//  \\boldsymbol{\\mathbb{H}}\n//          \\right]}{d \\boldsymbol{\\mathbb{H}}}\n//  = 2 \\mathbf{C}^{-1} \\cdot \\boldsymbol{\\mathbb{H}}\n//  @f] \n\n// @f[\n//  \\frac{d^{2} \\left[ \\boldsymbol{\\mathbb{H}} \\cdot \\mathbf{C}^{-1} \\cdot\n//  \\boldsymbol{\\mathbb{H}}\\right]}{d \\mathbf{C} \\otimes d\n//  \\boldsymbol{\\mathbb{H}}} \\Rightarrow \\frac{d^{2} \\left[ \\mathbb{H}_{e}\n//  C^{-1}_{ef} \\mathbb{H}_{f}\n//        \\right]}{d C_{ab} d \\mathbb{H}_{c}}\n//  = - C^{-1}_{ac} C^{-1}_{be} \\mathbb{H}_{e} - C^{-1}_{ae} \\mathbb{H}_{e}\n//  C^{-1}_{bc}\n//  @f] \n\n// @f{align}\n//  \\frac{d^{2} \\left[ \\boldsymbol{\\mathbb{H}} \\cdot \\mathbf{C}^{-1} \\cdot\n//  \\boldsymbol{\\mathbb{H}}\\right]}{d \\mathbf{C} \\otimes d \\mathbf{C}}\n//  &= -\\frac{d \\left[\\left[ \\mathbf{C}^{-1} \\cdot \\boldsymbol{\\mathbb{H}}\n//  \\right] \\otimes\n//        \\left[ \\mathbf{C}^{-1} \\cdot \\boldsymbol{\\mathbb{H}}\n//        \\right]\\right]}{d \\mathbf{C}}\n//  \\\\ \\Rightarrow\n//  \\frac{d^{2} \\left[ \\mathbb{H}_{e} C^{-1}_{ef} \\mathbb{H}_{f}\n//        \\right]}{d C_{ab} d C_{cd}}\n//  &= \\text{sym} \\left( C^{-1}_{ae} \\mathbb{H}_{e} C^{-1}_{cf}\n//  \\mathbb{H}_{f} C^{-1}_{bd}\n//            + C^{-1}_{ce} \\mathbb{H}_{e} C^{-1}_{bf} \\mathbb{H}_{f}\n//            C^{-1}_{ad} \\right)\n//  \\\\ &= \\frac{1}{2} \\left[\n//       C^{-1}_{ae} \\mathbb{H}_{e} C^{-1}_{cf} \\mathbb{H}_{f} C^{-1}_{bd}\n//     + C^{-1}_{ae} \\mathbb{H}_{e} C^{-1}_{df} \\mathbb{H}_{f} C^{-1}_{bc}\n//     + C^{-1}_{ce} \\mathbb{H}_{e} C^{-1}_{bf} \\mathbb{H}_{f} C^{-1}_{ad}\n//     + C^{-1}_{be} \\mathbb{H}_{e} C^{-1}_{df} \\mathbb{H}_{f} C^{-1}_{ac}\n//    \\right]\n//  @f}\n\n// \u597d\u5427\uff0c\u5f88\u5feb\u5c31\u5347\u7ea7\u4e86--\u5c3d\u7ba1 $\\psi_{0}$ \u548c $f_{\\mu_e}$ \u7684\u5b9a\u4e49\u53ef\u80fd\u5df2\u7ecf\u7ed9\u51fa\u4e86\u4e00\u4e9b\u63d0\u793a\uff0c\u8bf4\u660e\u8ba1\u7b97\u52a8\u80fd\u573a\u548c\u5b83\u4eec\u7684\u7ebf\u6027\u5316\u9700\u8981\u4e00\u4e9b\u52aa\u529b\uff0c\u4f46\u6700\u7ec8\u7684\u5b9a\u4e49\u53ef\u80fd\u6bd4\u6700\u521d\u60f3\u8c61\u7684\u8981\u590d\u6742\u4e00\u4e9b\u3002\u4e86\u89e3\u4e86\u6211\u4eec\u73b0\u5728\u6240\u505a\u7684\uff0c\u4e5f\u8bb8\u53ef\u4ee5\u8bf4\u6211\u4eec\u771f\u7684\u4e0d\u60f3\u8ba1\u7b97\u8fd9\u4e9b\u51fd\u6570\u76f8\u5bf9\u4e8e\u5176\u53c2\u6570\u7684\u4e00\u3001\u4e8c\u6b21\u5bfc\u6570--\u4e0d\u7ba1\u6211\u4eec\u5728\u5fae\u79ef\u5206\u8bfe\u4e0a\u505a\u5f97\u5982\u4f55\uff0c\u6216\u8005\u6211\u4eec\u53ef\u80fd\u662f\u591a\u4e48\u597d\u7684\u7a0b\u5e8f\u5458\u3002\n\n// \u5728\u6700\u7ec8\u5b9e\u73b0\u8fd9\u4e9b\u7684\u7c7b\u65b9\u6cd5\u5b9a\u4e49\u4e2d\uff0c\u6211\u4eec\u4ee5\u7a0d\u5fae\u4e0d\u540c\u7684\u65b9\u5f0f\u7ec4\u6210\u8fd9\u4e9b\u8ba1\u7b97\u3002\u4e00\u4e9b\u4e2d\u95f4\u6b65\u9aa4\u4e5f\u88ab\u4fdd\u7559\u4e0b\u6765\uff0c\u4ee5\u4fbf\u4ece\u53e6\u4e00\u4e2a\u89d2\u5ea6\u8bf4\u660e\u5982\u4f55\u7cfb\u7edf\u5730\u8ba1\u7b97\u5bfc\u6570\u3002\u6b64\u5916\uff0c\u4e00\u4e9b\u8ba1\u7b97\u88ab\u5206\u89e3\u5f97\u66f4\u5c11\u6216\u66f4\u8fdb\u4e00\u6b65\uff0c\u4ee5\u91cd\u7528\u4e00\u4e9b\u4e2d\u95f4\u503c\uff0c\u5e76\u5e0c\u671b\u80fd\u5e2e\u52a9\u8bfb\u8005\u8ddf\u968f\u5bfc\u6570\u7684\u64cd\u4f5c\u3002\n\n    template <int dim> \n    class Magnetoelastic_Constitutive_Law final \n      : public Coupled_Magnetomechanical_Constitutive_Law_Base<dim> \n    { \n    public: \n      Magnetoelastic_Constitutive_Law( \n        const ConstitutiveParameters &constitutive_parameters); \n\n      virtual void update_internal_data(const SymmetricTensor<2, dim> &C, \n                                        const Tensor<1, dim> &         H, \n                                        const DiscreteTime &) override; \n\n      virtual double get_psi() const override; \n\n      virtual Tensor<1, dim> get_B() const override; \n\n      virtual SymmetricTensor<2, dim> get_S() const override; \n\n      virtual SymmetricTensor<2, dim> get_DD() const override; \n\n      virtual Tensor<3, dim> get_PP() const override; \n\n      virtual SymmetricTensor<4, dim> get_HH() const override; \n\n    private: \n      double                  psi; \n      Tensor<1, dim>          B; \n      SymmetricTensor<2, dim> S; \n      SymmetricTensor<2, dim> BB; \n      Tensor<3, dim>          PP; \n      SymmetricTensor<4, dim> HH; \n    }; \n\n    template <int dim> \n    Magnetoelastic_Constitutive_Law<dim>::Magnetoelastic_Constitutive_Law( \n      const ConstitutiveParameters &constitutive_parameters) \n      : Coupled_Magnetomechanical_Constitutive_Law_Base<dim>( \n          constitutive_parameters) \n      , psi(0.0) \n    {} \n\n// \u5bf9\u4e8e\u8fd9\u4e2a\u7c7b\u7684\u66f4\u65b0\u65b9\u6cd5\uff0c\u6211\u4eec\u5c06\u7b80\u5355\u5730\u9884\u5148\u8ba1\u7b97\u4e00\u4e2a\u4e2d\u95f4\u503c\u7684\u96c6\u5408\uff08\u7528\u4e8e\u51fd\u6570\u6c42\u503c\u3001\u5bfc\u6570\u8ba1\u7b97\u7b49\uff09\uff0c\u5e76 \"\u624b\u52a8 \"\u5b89\u6392\u5b83\u4eec\u7684\u987a\u5e8f\uff0c\u4ee5\u4f7f\u5176\u91cd\u590d\u4f7f\u7528\u6700\u5927\u5316\u3002\u8fd9\u610f\u5473\u7740\u6211\u4eec\u5fc5\u987b\u81ea\u5df1\u7ba1\u7406\uff0c\u5e76\u51b3\u5b9a\u54ea\u4e9b\u503c\u5fc5\u987b\u5728\u5176\u4ed6\u503c\u4e4b\u524d\u8ba1\u7b97\uff0c\u540c\u65f6\u4fdd\u6301\u4ee3\u7801\u672c\u8eab\u7684\u67d0\u79cd\u79e9\u5e8f\u6216\u7ed3\u6784\u7684\u6a21\u6837\u3002\u8fd9\u5f88\u6709\u6548\uff0c\u4f46\u4e5f\u8bb8\u6709\u70b9\u4e4f\u5473\u3002\u5b83\u5bf9\u7c7b\u7684\u672a\u6765\u6269\u5c55\u4e5f\u6ca1\u6709\u592a\u5927\u7684\u5e2e\u52a9\uff0c\u56e0\u4e3a\u6240\u6709\u8fd9\u4e9b\u503c\u90fd\u662f\u8fd9\u4e2a\u5355\u4e00\u65b9\u6cd5\u7684\u5c40\u90e8\u3002\n\n// \u6709\u8da3\u7684\u662f\uff0c\u8fd9\u79cd\u9884\u5148\u8ba1\u7b97\u5728\u591a\u4e2a\u5730\u65b9\u4f7f\u7528\u7684\u4e2d\u95f4\u8868\u8fbe\u5f0f\u7684\u57fa\u672c\u6280\u672f\u6709\u4e00\u4e2a\u540d\u5b57\uff1a[\u5171\u540c\u5b50\u8868\u8fbe\u5f0f\u6d88\u9664\uff08CSE\uff09]\uff08https\uff1aen.wikipedia.org/wiki/Common_subexpression_elimination\uff09\u3002\u5b83\u662f\u8ba1\u7b97\u673a\u4ee3\u6570\u7cfb\u7edf\u5728\u627f\u62c5\u8bc4\u4f30\u7c7b\u4f3c\u8868\u8fbe\u5f0f\u7684\u4efb\u52a1\u65f6\u7528\u6765\u51cf\u5c11\u8ba1\u7b97\u8d39\u7528\u7684\u4e00\u79cd\u7b56\u7565\u3002\n\n    template <int dim> \n    void Magnetoelastic_Constitutive_Law<dim>::update_internal_data( \n      const SymmetricTensor<2, dim> &C, \n      const Tensor<1, dim> &         H, \n      const DiscreteTime &) \n    { \n      const double                  det_F = std::sqrt(determinant(C)); \n      const SymmetricTensor<2, dim> C_inv = invert(C); \n      AssertThrow(det_F > 0.0, \n                  ExcMessage(\"Volumetric Jacobian must be positive.\")); \n\n// \u78c1\u5f39\u6027\u80fd\u7684\u9971\u548c\u51fd\u6570\u3002\n\n      const double two_h_dot_h_div_h_sat_squ = \n        (2.0 * H * H) / (this->get_mu_e_h_sat() * this->get_mu_e_h_sat()); \n      const double tanh_two_h_dot_h_div_h_sat_squ = \n        std::tanh(two_h_dot_h_div_h_sat_squ); \n\n      const double f_mu_e = \n        1.0 + (this->get_mu_e_inf() / this->get_mu_e() - 1.0) * \n                tanh_two_h_dot_h_div_h_sat_squ; \n\n// \u9971\u548c\u51fd\u6570\u7684\u4e00\u9636\u5bfc\u6570\uff0c\u6ce8\u610f\u5230  $\\frac{d \\tanh(x)}{dx} = \\text{sech}^{2}(x)$  \u3002\n\n      const double dtanh_two_h_dot_h_div_h_sat_squ = \n        std::pow(1.0 / std::cosh(two_h_dot_h_div_h_sat_squ), 2.0); \n      const Tensor<1, dim> dtwo_h_dot_h_div_h_sat_squ_dH = \n        2.0 * 2.0 / (this->get_mu_e_h_sat() * this->get_mu_e_h_sat()) * H; \n\n      const Tensor<1, dim> df_mu_e_dH = \n        (this->get_mu_e_inf() / this->get_mu_e() - 1.0) * \n        (dtanh_two_h_dot_h_div_h_sat_squ * dtwo_h_dot_h_div_h_sat_squ_dH); \n\n// \u9971\u548c\u5ea6\u51fd\u6570\u7684\u4e8c\u9636\u5bfc\u6570\uff0c\u6ce8\u610f  $\\frac{d \\text{sech}^{2}(x)}{dx} = -2 \\tanh(x) \\text{sech}^{2}(x)$  \u3002\n\n      const double d2tanh_two_h_dot_h_div_h_sat_squ = \n        -2.0 * tanh_two_h_dot_h_div_h_sat_squ * dtanh_two_h_dot_h_div_h_sat_squ; \n      const SymmetricTensor<2, dim> d2two_h_dot_h_div_h_sat_squ_dH_dH = \n        2.0 * 2.0 / (this->get_mu_e_h_sat() * this->get_mu_e_h_sat()) * \n        Physics::Elasticity::StandardTensors<dim>::I; \n\n      const SymmetricTensor<2, dim> d2f_mu_e_dH_dH = \n        (this->get_mu_e_inf() / this->get_mu_e() - 1.0) * \n        (d2tanh_two_h_dot_h_div_h_sat_squ * \n           symmetrize(outer_product(dtwo_h_dot_h_div_h_sat_squ_dH, \n                                    dtwo_h_dot_h_div_h_sat_squ_dH)) + \n         dtanh_two_h_dot_h_div_h_sat_squ * d2two_h_dot_h_div_h_sat_squ_dH_dH); \n\n// \u4ece\u573a/\u8fd0\u52a8\u5b66\u53d8\u91cf\u4e2d\u76f4\u63a5\u83b7\u5f97\u7684\u4e00\u4e9b\u4e2d\u95f4\u91cf\u3002\n\n      const double         log_det_F         = std::log(det_F); \n      const double         tr_C              = trace(C); \n      const Tensor<1, dim> C_inv_dot_H       = C_inv * H; \n      const double         H_dot_C_inv_dot_H = H * C_inv_dot_H; \n\n// \u4e2d\u95f4\u91cf\u7684\u4e00\u9636\u5bfc\u6570\u3002\n\n      const SymmetricTensor<2, dim> d_tr_C_dC = \n        Physics::Elasticity::StandardTensors<dim>::I; \n      const SymmetricTensor<2, dim> ddet_F_dC     = 0.5 * det_F * C_inv; \n      const SymmetricTensor<2, dim> dlog_det_F_dC = 0.5 * C_inv; \n\n      const Tensor<1, dim> dH_dot_C_inv_dot_H_dH = 2.0 * C_inv_dot_H; \n\n      SymmetricTensor<4, dim> dC_inv_dC; \n      for (unsigned int A = 0; A < dim; ++A) \n        for (unsigned int B = A; B < dim; ++B) \n          for (unsigned int C = 0; C < dim; ++C) \n            for (unsigned int D = C; D < dim; ++D) \n              dC_inv_dC[A][B][C][D] -=               // \n                0.5 * (C_inv[A][C] * C_inv[B][D]     // \n                       + C_inv[A][D] * C_inv[B][C]); // \n\n      const SymmetricTensor<2, dim> dH_dot_C_inv_dot_H_dC = \n        -symmetrize(outer_product(C_inv_dot_H, C_inv_dot_H)); \n\n// \u4e2d\u95f4\u91cf\u7684\u4e8c\u9636\u5bfc\u6570\u3002\n\n      const SymmetricTensor<4, dim> d2log_det_F_dC_dC = 0.5 * dC_inv_dC; \n\n      const SymmetricTensor<4, dim> d2det_F_dC_dC = \n        0.5 * (outer_product(C_inv, ddet_F_dC) + det_F * dC_inv_dC); \n\n      const SymmetricTensor<2, dim> d2H_dot_C_inv_dot_H_dH_dH = 2.0 * C_inv; \n\n      Tensor<3, dim> d2H_dot_C_inv_dot_H_dC_dH; \n      for (unsigned int A = 0; A < dim; ++A) \n        for (unsigned int B = 0; B < dim; ++B) \n          for (unsigned int C = 0; C < dim; ++C) \n            d2H_dot_C_inv_dot_H_dC_dH[A][B][C] -= \n              C_inv[A][C] * C_inv_dot_H[B] + // \n              C_inv_dot_H[A] * C_inv[B][C];  // \n\n      SymmetricTensor<4, dim> d2H_dot_C_inv_dot_H_dC_dC; \n      for (unsigned int A = 0; A < dim; ++A) \n        for (unsigned int B = A; B < dim; ++B) \n          for (unsigned int C = 0; C < dim; ++C) \n            for (unsigned int D = C; D < dim; ++D) \n              d2H_dot_C_inv_dot_H_dC_dC[A][B][C][D] += \n                0.5 * (C_inv_dot_H[A] * C_inv_dot_H[C] * C_inv[B][D] + \n                       C_inv_dot_H[A] * C_inv_dot_H[D] * C_inv[B][C] + \n                       C_inv_dot_H[B] * C_inv_dot_H[C] * C_inv[A][D] + \n                       C_inv_dot_H[B] * C_inv_dot_H[D] * C_inv[A][C]); \n\n// \u50a8\u5b58\u7684\u80fd\u91cf\u5bc6\u5ea6\u51fd\u6570\u3002\n\n      psi = \n        (0.5 * this->get_mu_e() * f_mu_e) * \n          (tr_C - dim - 2.0 * std::log(det_F)) + \n        this->get_lambda_e() * (std::log(det_F) * std::log(det_F)) - \n        (0.5 * this->get_mu_0() * this->get_mu_r()) * det_F * (H * C_inv * H); \n\n// \u52a8\u80fd\u91cf\u3002\n\n      B = -(0.5 * this->get_mu_e() * (tr_C - dim - 2.0 * log_det_F)) * \n            df_mu_e_dH // \n          + 0.5 * this->get_mu_0() * this->get_mu_r() * det_F * \n              dH_dot_C_inv_dot_H_dH; // \n\n      S = 2.0 * (0.5 * this->get_mu_e() * f_mu_e) *                        // \n            (d_tr_C_dC - 2.0 * dlog_det_F_dC)                              // \n          + 2.0 * this->get_lambda_e() * (2.0 * log_det_F * dlog_det_F_dC) // \n          - 2.0 * (0.5 * this->get_mu_0() * this->get_mu_r()) *            // \n              (H_dot_C_inv_dot_H * ddet_F_dC                               // \n               + det_F * dH_dot_C_inv_dot_H_dC);                           // \n\n// \u52a8\u80fd\u91cf\u7684\u7ebf\u6027\u5316\u3002\n\n      BB = -(0.5 * this->get_mu_e() * (tr_C - dim - 2.0 * log_det_F)) * // \n             d2f_mu_e_dH_dH                                             // \n           + 0.5 * this->get_mu_0() * this->get_mu_r() * det_F * \n               d2H_dot_C_inv_dot_H_dH_dH; // \n\n      PP = -2.0 * (0.5 * this->get_mu_e()) *                                  // \n             outer_product(Tensor<2, dim>(d_tr_C_dC - 2.0 * dlog_det_F_dC),   // \n                           df_mu_e_dH)                                        // \n           +                                                                  // \n           2.0 * (0.5 * this->get_mu_0() * this->get_mu_r()) *                // \n             (outer_product(Tensor<2, dim>(ddet_F_dC), dH_dot_C_inv_dot_H_dH) // \n              + det_F * d2H_dot_C_inv_dot_H_dC_dH);                           // \n\n      HH = \n        4.0 * (0.5 * this->get_mu_e() * f_mu_e) * (-2.0 * d2log_det_F_dC_dC) // \n        + 4.0 * this->get_lambda_e() *                                       // \n            (2.0 * outer_product(dlog_det_F_dC, dlog_det_F_dC)               // \n             + 2.0 * log_det_F * d2log_det_F_dC_dC)                          // \n        - 4.0 * (0.5 * this->get_mu_0() * this->get_mu_r()) *                // \n            (H_dot_C_inv_dot_H * d2det_F_dC_dC                               // \n             + outer_product(ddet_F_dC, dH_dot_C_inv_dot_H_dC)               // \n             + outer_product(dH_dot_C_inv_dot_H_dC, ddet_F_dC)               // \n             + det_F * d2H_dot_C_inv_dot_H_dC_dC);                           // \n    } \n\n    template <int dim> \n    double Magnetoelastic_Constitutive_Law<dim>::get_psi() const \n    { \n      return psi; \n    } \n\n    template <int dim> \n    Tensor<1, dim> Magnetoelastic_Constitutive_Law<dim>::get_B() const \n    { \n      return B; \n    } \n\n    template <int dim> \n    SymmetricTensor<2, dim> Magnetoelastic_Constitutive_Law<dim>::get_S() const \n    { \n      return S; \n    } \n\n    template <int dim> \n    SymmetricTensor<2, dim> Magnetoelastic_Constitutive_Law<dim>::get_DD() const \n    { \n      return BB; \n    } \n\n    template <int dim> \n    Tensor<3, dim> Magnetoelastic_Constitutive_Law<dim>::get_PP() const \n    { \n      return PP; \n    } \n\n    template <int dim> \n    SymmetricTensor<4, dim> Magnetoelastic_Constitutive_Law<dim>::get_HH() const \n    { \n      return HH; \n    } \n// @sect4{Magneto-viscoelastic constitutive law (hand-derived)}  \n\n// \u5982\u524d\u6240\u8ff0\uff0c\u6211\u4eec\u5c06\u8003\u8651\u7684\u5177\u6709\u4e00\u79cd\u8017\u6563\u673a\u5236\u7684\u78c1\u6da1\u6d41\u6750\u6599\u7684\u81ea\u7531\u80fd\u5bc6\u5ea6\u51fd\u6570\u5b9a\u4e49\u4e3a \n// @f[\n//    \\psi_{0} \\left( \\mathbf{C}, \\mathbf{C}_{v}, \\boldsymbol{\\mathbb{H}}\n//    \\right)\n//  = \\psi_{0}^{ME} \\left( \\mathbf{C}, \\boldsymbol{\\mathbb{H}} \\right)\n//  + \\psi_{0}^{MVE} \\left( \\mathbf{C}, \\mathbf{C}_{v},\n//  \\boldsymbol{\\mathbb{H}} \\right)\n//  @f] \u3002\n\n// @f[\n//    \\psi_{0}^{ME} \\left( \\mathbf{C}, \\boldsymbol{\\mathbb{H}} \\right)\n//  = \\frac{1}{2} \\mu_{e} f_{\\mu_{e}^{ME}} \\left( \\boldsymbol{\\mathbb{H}}\n//  \\right)\n//      \\left[ \\text{tr}(\\mathbf{C}) - d - 2 \\ln (\\text{det}(\\mathbf{F}))\n//      \\right]\n//  + \\lambda_{e} \\ln^{2} \\left(\\text{det}(\\mathbf{F}) \\right)\n//  - \\frac{1}{2} \\mu_{0} \\mu_{r} \\text{det}(\\mathbf{F})\n//      \\left[ \\boldsymbol{\\mathbb{H}} \\cdot \\mathbf{C}^{-1} \\cdot\n//      \\boldsymbol{\\mathbb{H}} \\right]\n//  @f] \n\n// @f[\n//    \\psi_{0}^{MVE} \\left( \\mathbf{C}, \\mathbf{C}_{v},\n//    \\boldsymbol{\\mathbb{H}} \\right)\n//  = \\frac{1}{2} \\mu_{v} f_{\\mu_{v}^{MVE}} \\left( \\boldsymbol{\\mathbb{H}}\n//  \\right)\n//      \\left[ \\mathbf{C}_{v} : \\left[\n//        \\left[\\text{det}\\left(\\mathbf{F}\\right)\\right]^{-\\frac{2}{d}}\n//        \\mathbf{C} \\right] - d - \\ln\\left(\n//        \\text{det}\\left(\\mathbf{C}_{v}\\right) \\right)  \\right]\n//  @f]\n//  \u4e0e\n//  @f[\n//    f_{\\mu_{e}}^{ME} \\left( \\boldsymbol{\\mathbb{H}} \\right)\n//  = 1 + \\left[ \\frac{\\mu_{e}^{\\infty}}{\\mu_{e}} - 1 \\right]\n//      \\tanh \\left( 2 \\frac{\\boldsymbol{\\mathbb{H}} \\cdot\n//      \\boldsymbol{\\mathbb{H}}}\n//        {\\left(h_{e}^{\\text{sat}}\\right)^{2}} \\right)\n//  @f]\n// \n// @f[\n//    f_{\\mu_{v}}^{MVE} \\left( \\boldsymbol{\\mathbb{H}} \\right)\n//  = 1 + \\left[ \\frac{\\mu_{v}^{\\infty}}{\\mu_{v}} - 1 \\right]\n//      \\tanh \\left( 2 \\frac{\\boldsymbol{\\mathbb{H}} \\cdot\n//      \\boldsymbol{\\mathbb{H}}}\n//        {\\left(h_{v}^{\\text{sat}}\\right)^{2}} \\right)\n//  @f]\n//  \u548c\u6f14\u53d8\u89c4\u5f8b\n//  @f[\n//   \\dot{\\mathbf{C}}_{v} \\left( \\mathbf{C} \\right)\n//  = \\frac{1}{\\tau} \\left[\n//        \\left[\\left[\\text{det}\\left(\\mathbf{F}\\right)\\right]^{-\\frac{2}{d}}\n//          \\mathbf{C}\\right]^{-1}\n//      - \\mathbf{C}_{v} \\right]\n//  @f] \uff0c\n//  \u5176\u672c\u8eab\u662f\u4ee5 $\\mathbf{C}$ \u4e3a\u53c2\u6570\u7684\u3002\u6839\u636e\u8bbe\u8ba1\uff0c\u80fd\u91cf $\\psi_{0}^{ME} \\left( \\mathbf{C}, \\boldsymbol{\\mathbb{H}} \\right)$ \u7684\u78c1\u5f39\u6027\u90e8\u5206\u4e0e\u524d\u9762\u4ecb\u7ecd\u7684\u78c1\u5f39\u6027\u6750\u6599\u7684\u78c1\u5f39\u6027\u90e8\u5206\u662f\u76f8\u540c\u7684\u3002\u56e0\u6b64\uff0c\u5bf9\u4e8e\u6e90\u4e8e\u8fd9\u90e8\u5206\u80fd\u91cf\u7684\u5404\u79cd\u8d21\u732e\u7684\u5bfc\u6570\uff0c\u8bf7\u53c2\u8003\u524d\u9762\u7684\u7ae0\u8282\u3002\u6211\u4eec\u5c06\u7ee7\u7eed\u5f3a\u8c03\u6765\u81ea\u8fd9\u4e9b\u6761\u6b3e\u7684\u5177\u4f53\u8d21\u732e\uff0c\u7528 $ME$ \u5bf9\u7a81\u51fa\u7684\u6761\u6b3e\u8fdb\u884c\u4e0a\u6807\uff0c\u800c\u6765\u81ea\u78c1\u5f39\u6027\u90e8\u5206\u7684\u8d21\u732e\u5219\u7528 $MVE$ \u4e0a\u6807\u3002\u6b64\u5916\uff0c\u963b\u5c3c\u9879\u7684\u78c1\u9971\u548c\u51fd\u6570 $f_{\\mu_{v}}^{MVE} \\left( \\boldsymbol{\\mathbb{H}} \\right)$ \u5177\u6709\u4e0e\u5f39\u6027\u9879\u76f8\u540c\u7684\u5f62\u5f0f\uff08\u5373 $f_{\\mu_{e}}^{ME} \\left( \\boldsymbol{\\mathbb{H}} \\right)$ \uff09\uff0c\u56e0\u6b64\u5176\u5bfc\u6570\u7684\u7ed3\u6784\u4e0e\u4e4b\u524d\u770b\u5230\u7684\u76f8\u540c\uff1b\u552f\u4e00\u7684\u53d8\u5316\u662f\u4e09\u4e2a\u6784\u6210\u53c2\u6570\uff0c\u73b0\u5728\u4e0e\u7c98\u6027\u526a\u5207\u6a21\u91cf $\\mu_{v}$ \u800c\u975e\u5f39\u6027\u526a\u5207\u6a21\u91cf $\\mu_{e}$ \u76f8\u5173\u3002\n\n// \u5bf9\u4e8e\u8fd9\u79cd\u78c1-\u7c98\u5f39\u6027\u6750\u6599\uff0c\u5bf9\u5e94\u4e8e\u78c1\u611f\u5e94\u77e2\u91cf\u548cPiola-Kirchhoff\u603b\u5e94\u529b\u5f20\u91cf\u7684\u7b2c\u4e00\u5bfc\u6570\u662f\n// @f[\n//   \\boldsymbol{\\mathbb{B}} \\left( \\mathbf{C}, \\mathbf{C}_{v},\n//   \\boldsymbol{\\mathbb{H}} \\right)\n//  \\dealcoloneq - \\frac{\\partial \\psi_{0} \\left( \\mathbf{C}, \\mathbf{C}_{v},\n//  \\boldsymbol{\\mathbb{H}} \\right)}{\\partial \\boldsymbol{\\mathbb{H}}}\n//  \\Big\\vert_{\\mathbf{C}, \\mathbf{C}_{v}} \\equiv\n//  \\boldsymbol{\\mathbb{B}}^{ME} \\left( \\mathbf{C}, \\boldsymbol{\\mathbb{H}}\n//  \\right)\n//  + \\boldsymbol{\\mathbb{B}}^{MVE} \\left( \\mathbf{C}, \\mathbf{C}_{v},\n//  \\boldsymbol{\\mathbb{H}} \\right) =  - \\frac{d \\psi_{0}^{ME} \\left(\n//  \\mathbf{C}, \\boldsymbol{\\mathbb{H}} \\right)}{d \\boldsymbol{\\mathbb{H}}}\n//     - \\frac{\\partial \\psi_{0}^{MVE} \\left( \\mathbf{C}, \\mathbf{C}_{v},\n//     \\boldsymbol{\\mathbb{H}} \\right)}{\\partial \\boldsymbol{\\mathbb{H}}}\n//  @f] \n\n// @f[\n//   \\mathbf{S}^{\\text{tot}} \\left( \\mathbf{C}, \\mathbf{C}_{v},\n//   \\boldsymbol{\\mathbb{H}} \\right)\n//  \\dealcoloneq 2 \\frac{\\partial \\psi_{0} \\left( \\mathbf{C}, \\mathbf{C}_{v},\n//  \\boldsymbol{\\mathbb{H}} \\right)}{\\partial \\mathbf{C}}\n//  \\Big\\vert_{\\mathbf{C}_{v}, \\boldsymbol{\\mathbb{H}}} \\equiv\n//  \\mathbf{S}^{\\text{tot}, ME} \\left( \\mathbf{C}, \\boldsymbol{\\mathbb{H}}\n//  \\right)\n//  + \\mathbf{S}^{\\text{tot}, MVE} \\left( \\mathbf{C}, \\mathbf{C}_{v},\n//  \\boldsymbol{\\mathbb{H}}\n//      \\right)\n//  =  2 \\frac{d \\psi_{0}^{ME} \\left( \\mathbf{C}, \\boldsymbol{\\mathbb{H}}\n//  \\right)}{d \\mathbf{C}}\n//   + 2 \\frac{\\partial \\psi_{0}^{MVE} \\left( \\mathbf{C}, \\mathbf{C}_{v},\n//   \\boldsymbol{\\mathbb{H}} \\right)}{\\partial \\mathbf{C}}\n//  @f]\n//  \uff0c\u5176\u4e2d\u7c98\u6027\u8d21\u732e\u4e3a\n//  @f[\n//    \\boldsymbol{\\mathbb{B}}^{MVE} \\left( \\mathbf{C}, \\mathbf{C}_{v},\n//    \\boldsymbol{\\mathbb{H}} \\right)\n//  = - \\frac{\\partial \\psi_{0}^{MVE} \\left( \\mathbf{C}, \\mathbf{C}_{v},\n//  \\boldsymbol{\\mathbb{H}} \\right)}{\\partial \\boldsymbol{\\mathbb{H}}}\n//  \\Big\\vert_{\\mathbf{C}, \\mathbf{C}_{v}} = - \\frac{1}{2} \\mu_{v}\n//      \\left[ \\mathbf{C}_{v} : \\left[\n//        \\left[\\text{det}\\left(\\mathbf{F}\\right)\\right]^{-\\frac{2}{d}}\n//        \\mathbf{C} \\right] - d - \\ln\\left(\n//        \\text{det}\\left(\\mathbf{C}_{v}\\right) \\right)  \\right]\n//        \\frac{\\partial f_{\\mu_{v}^{MVE}} \\left( \\boldsymbol{\\mathbb{H}}\n//        \\right)}{\\partial \\boldsymbol{\\mathbb{H}}}\n//  @f] \n\n// @f[\n//    \\mathbf{S}^{\\text{tot}, MVE} \\left( \\mathbf{C}, \\mathbf{C}_{v},\n//    \\boldsymbol{\\mathbb{H}}\n//      \\right)\n//  = 2 \\frac{\\partial \\psi_{0}^{MVE} \\left( \\mathbf{C}, \\mathbf{C}_{v},\n//  \\boldsymbol{\\mathbb{H}} \\right)}{\\partial \\mathbf{C}}\n//  \\Big\\vert_{\\mathbf{C}_{v}, \\boldsymbol{\\mathbb{H}}} = \\mu_{v}\n//  f_{\\mu_{v}^{MVE}} \\left( \\boldsymbol{\\mathbb{H}} \\right)\n//         \\left[  \\left[ \\mathbf{C}_{v} : \\mathbf{C} \\right] \\left[ -\n//         \\frac{1}{d}\n//         \\left[\\text{det}\\left(\\mathbf{F}\\right)\\right]^{-\\frac{2}{d}}\n//         \\mathbf{C}^{-1} \\right]\n//         + \\left[\\text{det}\\left(\\mathbf{F}\\right)\\right]^{-\\frac{2}{d}}\n//         \\mathbf{C}_{v}\n//   \\right]\n//  @f]\n//  \u548c\n//  @f[\n//  \\frac{\\partial f_{\\mu_{v}^{MVE}} \\left( \\boldsymbol{\\mathbb{H}}\n//  \\right)}{\\partial \\boldsymbol{\\mathbb{H}}} \\equiv \\frac{d\n//  f_{\\mu_{v}^{MVE}} \\left( \\boldsymbol{\\mathbb{H}} \\right)}{d\n//  \\boldsymbol{\\mathbb{H}}} .\n//  @f] \n//  \u65f6\u95f4\u5fae\u7f29\u7684\u6f14\u5316\u89c4\u5f8b\uff0c\n//  @f[\n//  \\mathbf{C}_{v}^{(t)} \\left( \\mathbf{C} \\right)\n//  = \\frac{1}{1 + \\frac{\\Delta t}{\\tau_{v}}} \\left[\n//      \\mathbf{C}_{v}^{(t-1)}\n//    + \\frac{\\Delta t}{\\tau_{v}}\n//      \\left[\\left[\\text{det}\\left(\\mathbf{F}\\right)\\right]^{-\\frac{2}{d}}\n//      \\mathbf{C} \\right]^{-1}\n//    \\right]\n//  @f]\n//  \u4e5f\u5c06\u51b3\u5b9a\u5185\u90e8\u53d8\u91cf\u76f8\u5bf9\u4e8e\u573a\u53d8\u91cf\u7684\u7ebf\u6027\u5316\u662f\u5982\u4f55\u6784\u6210\u7684\u3002\n\n// \u6ce8\u610f\uff0c\u4e3a\u4e86\u83b7\u5f97\u8fd9\u79cd\u8017\u6563\u6750\u6599\u7684\u78c1\u611f\u5e94\u77e2\u91cf\u548c\u603bPiola-Kirchhoff\u5e94\u529b\u5f20\u91cf\u7684*\u6b63\u786e\u8868\u8fbe\u5f0f\uff0c\u6211\u4eec\u5fc5\u987b\u4e25\u683c\u9075\u5b88\u5e94\u7528Coleman-Noll\u7a0b\u5e8f\u7684\u7ed3\u679c\uff1a\u6211\u4eec\u5fc5\u987b\u53d6*\u90e8\u5206\u5bfc\u6570*\u3002\n//\u81ea\u7531\u80fd\u5bc6\u5ea6\u51fd\u6570\u4e0e\u573a\u53d8\u91cf\u7684\u5173\u7cfb\u3002(\u5bf9\u4e8e\u6211\u4eec\u7684\u975e\u8017\u6563\u6027\u78c1\u5f39\u6027\u6750\u6599\uff0c\u53d6\u90e8\u5206\u5bfc\u6570\u6216\u5168\u90e8\u5bfc\u6570\u90fd\u4f1a\u6709\u540c\u6837\u7684\u7ed3\u679c\uff0c\u6240\u4ee5\u4e4b\u524d\u6ca1\u6709\u5fc5\u8981\u63d0\u8bf7\u5927\u5bb6\u6ce8\u610f\u8fd9\u4e00\u70b9)\u3002\u64cd\u4f5c\u7684\u5173\u952e\u90e8\u5206\u662f\u51bb\u7ed3\u5185\u90e8\u53d8\u91cf $\\mathbf{C}_{v}^{(t)} \\left( \\mathbf{C} \\right)$ \uff0c\u540c\u65f6\u8ba1\u7b97 $\\psi_{0}^{MVE} \\left( \\mathbf{C}, \\mathbf{C}_{v} \\left( \\mathbf{C} \\right), \\boldsymbol{\\mathbb{H}} \\right)$ \u76f8\u5bf9\u4e8e $\\mathbf{C}$ \u7684\u5bfc\u6570-- $\\mathbf{C}_{v}^{(t)}$ \u5bf9 $\\mathbf{C}$ \u7684\u4f9d\u8d56\u6027\u4e0d\u88ab\u8003\u8651\u3002\u5f53\u51b3\u5b9a\u662f\u4f7f\u7528AD\u8fd8\u662fSD\u6765\u6267\u884c\u8fd9\u4e2a\u4efb\u52a1\u65f6\uff0c\u9009\u62e9\u662f\u5f88\u6e05\u695a\u7684--\u53ea\u6709\u7b26\u53f7\u6846\u67b6\u63d0\u4f9b\u4e86\u4e00\u4e2a\u673a\u5236\u6765\u5b8c\u6210\u8fd9\u4e2a\u4efb\u52a1\uff1b\u5982\u524d\u6240\u8ff0\uff0cAD\u53ea\u80fd\u8fd4\u56de\u603b\u5bfc\u6570\uff0c\u6240\u4ee5\u5b83\u4e0d\u9002\u5408\u8fd9\u4e2a\u4efb\u52a1\u3002\n\n// \u4e3a\u4e86\u5bf9\u4e8b\u60c5\u8fdb\u884c\u603b\u7ed3\uff0c\u6211\u4eec\u5c06\u4ecb\u7ecd\u8fd9\u79cd\u901f\u5ea6\u4f9d\u8d56\u6027\u8026\u5408\u6750\u6599\u7684\u6750\u6599\u5207\u7ebf\u3002\u4e24\u4e2a\u52a8\u80fd\u53d8\u91cf\u76f8\u5bf9\u4e8e\u5176\u53c2\u6570\u7684\u7ebf\u6027\u5316\u662f \n// @f[\n//  \\mathbb{D} \\left( \\mathbf{C}, \\mathbf{C}_{v}, \\boldsymbol{\\mathbb{H}}\n//  \\right) = \\frac{d \\boldsymbol{\\mathbb{B}}}{d \\boldsymbol{\\mathbb{H}}}\n//  \\equiv \\mathbb{D}^{ME} \\left( \\mathbf{C}, \\boldsymbol{\\mathbb{H}} \\right)\n//  + \\mathbb{D}^{MVE} \\left( \\mathbf{C}, \\mathbf{C}_{v},\n//  \\boldsymbol{\\mathbb{H}} \\right) = \\frac{d \\boldsymbol{\\mathbb{B}}^{ME}}{d\n//  \\boldsymbol{\\mathbb{H}}}\n//  + \\frac{d \\boldsymbol{\\mathbb{B}}^{MVE}}{d \\boldsymbol{\\mathbb{H}}}\n//  @f] \n// \n// @f[\n//  \\mathfrak{P}^{\\text{tot}} \\left( \\mathbf{C}, \\mathbf{C}_{v},\n//  \\boldsymbol{\\mathbb{H}} \\right) = - \\frac{d \\mathbf{S}^{\\text{tot}}}{d\n//  \\boldsymbol{\\mathbb{H}}} \\equiv \\mathfrak{P}^{\\text{tot}, ME} \\left(\n//  \\mathbf{C}, \\boldsymbol{\\mathbb{H}} \\right)\n//  + \\mathfrak{P}^{\\text{tot}, MVE} \\left( \\mathbf{C}, \\mathbf{C}_{v},\n//  \\boldsymbol{\\mathbb{H}} \\right) = - \\frac{d \\mathbf{S}^{\\text{tot},\n//  ME}}{d \\boldsymbol{\\mathbb{H}}}\n//  - \\frac{d \\mathbf{S}^{\\text{tot}, MVE}}{d \\boldsymbol{\\mathbb{H}}}\n//  @f] \n// \n// @f[\n//  \\mathcal{H}^{\\text{tot}} \\left( \\mathbf{C}, \\mathbf{C}_{v},\n//  \\boldsymbol{\\mathbb{H}} \\right) = 2 \\frac{d \\mathbf{S}^{\\text{tot}}}{d\n//  \\mathbf{C}} \\equiv \\mathcal{H}^{\\text{tot}, ME} \\left( \\mathbf{C},\n//  \\boldsymbol{\\mathbb{H}} \\right)\n//  + \\mathcal{H}^{\\text{tot}, MVE} \\left( \\mathbf{C}, \\mathbf{C}_{v},\n//  \\boldsymbol{\\mathbb{H}} \\right) = 2 \\frac{d \\mathbf{S}^{\\text{tot},\n//  ME}}{d \\mathbf{C}}\n//  + 2 \\frac{d \\mathbf{S}^{\\text{tot}, MVE}}{d \\mathbf{C}}\n//  @f] \n//  \u5176\u4e2d\u7c98\u6027\u8d21\u732e\u7684\u5207\u7ebf\u4e3a\n//  @f[\n//  \\mathbb{D}^{MVE} \\left( \\mathbf{C}, \\mathbf{C}_{v},\n//  \\boldsymbol{\\mathbb{H}} \\right) = - \\frac{1}{2} \\mu_{v}\n//      \\left[ \\mathbf{C}_{v} : \\left[\n//        \\left[\\text{det}\\left(\\mathbf{F}\\right)\\right]^{-\\frac{2}{d}}\n//        \\mathbf{C} \\right] - d - \\ln\\left(\n//        \\text{det}\\left(\\mathbf{C}_{v}\\right) \\right)  \\right]\n//        \\frac{\\partial^{2} f_{\\mu_{v}^{MVE}} \\left( \\boldsymbol{\\mathbb{H}}\n//        \\right)}{\\partial \\boldsymbol{\\mathbb{H}} \\otimes\n//        d \\boldsymbol{\\mathbb{H}}}\n//  @f] \n// \n// @f[\n//  \\mathfrak{P}^{\\text{tot}, MVE} \\left( \\mathbf{C}, \\mathbf{C}_{v},\n//  \\boldsymbol{\\mathbb{H}} \\right) = - \\mu_{v}\n//         \\left[  \\left[ \\mathbf{C}_{v} : \\mathbf{C} \\right] \\left[ -\n//         \\frac{1}{d}\n//         \\left[\\text{det}\\left(\\mathbf{F}\\right)\\right]^{-\\frac{2}{d}}\n//         \\mathbf{C}^{-1} \\right]\n//         + \\left[\\text{det}\\left(\\mathbf{F}\\right)\\right]^{-\\frac{2}{d}}\n//         \\mathbf{C}_{v}\n//   \\right] \\otimes \\frac{d f_{\\mu_{v}^{MVE}} \\left( \\boldsymbol{\\mathbb{H}}\n//   \\right)}{d \\boldsymbol{\\mathbb{H}}}\n//  @f] \n// \n// @f{align}\n//  \\mathcal{H}^{\\text{tot}, MVE} \\left( \\mathbf{C}, \\mathbf{C}_{v},\n//  \\boldsymbol{\\mathbb{H}} \\right)\n//  &= 2 \\mu_{v} f_{\\mu_{v}^{MVE}} \\left( \\boldsymbol{\\mathbb{H}} \\right)\n//    \\left[ - \\frac{1}{d}\n//    \\left[\\text{det}\\left(\\mathbf{F}\\right)\\right]^{-\\frac{2}{d}}\n//    \\mathbf{C}^{-1} \\right] \\otimes\n//    \\left[ \\mathbf{C}_{v} + \\mathbf{C} : \\frac{d \\mathbf{C}_{v}}{d\n//    \\mathbf{C}} \\right]\n//  \\\\ &+ 2 \\mu_{v} f_{\\mu_{v}^{MVE}} \\left( \\boldsymbol{\\mathbb{H}} \\right)\n//  \\left[ \\mathbf{C}_{v} : \\mathbf{C} \\right]\n//    \\left[\n//      \\frac{1}{d^{2}}\n//      \\left[\\text{det}\\left(\\mathbf{F}\\right)\\right]^{-\\frac{2}{d}}\n//      \\mathbf{C}^{-1} \\otimes \\mathbf{C}^{-1}\n//      - \\frac{1}{d}\n//      \\left[\\text{det}\\left(\\mathbf{F}\\right)\\right]^{-\\frac{2}{d}} \\frac{d\n//      \\mathbf{C}^{-1}}{d \\mathbf{C}}\n//    \\right]\n//  \\\\ &+ 2 \\mu_{v} f_{\\mu_{v}^{MVE}} \\left( \\boldsymbol{\\mathbb{H}} \\right)\n//    \\left[\n//      -\\frac{1}{d}\n//      \\left[\\text{det}\\left(\\mathbf{F}\\right)\\right]^{-\\frac{2}{d}}\n//      \\mathbf{C}_{v} \\otimes \\mathbf{C}^{-1}\n//      + \\left[\\text{det}\\left(\\mathbf{F}\\right)\\right]^{-\\frac{2}{d}}\n//      \\frac{d \\mathbf{C}_{v}}{d \\mathbf{C}}\n//    \\right]\n//  @f}\n//  \u4e0e\n//  @f[\n//  \\frac{\\partial^{2} f_{\\mu_{v}^{MVE}} \\left( \\boldsymbol{\\mathbb{H}}\n//  \\right)}{\\partial \\boldsymbol{\\mathbb{H}} \\otimes\n//  d \\boldsymbol{\\mathbb{H}}} \\equiv \\frac{d^{2} f_{\\mu_{v}^{MVE}} \\left(\n//  \\boldsymbol{\\mathbb{H}} \\right)}{d \\boldsymbol{\\mathbb{H}} \\otimes d\n//  \\boldsymbol{\\mathbb{H}}}\n//  @f]\n//  \uff0c\u4ece\u6f14\u5316\u5b9a\u5f8b\u6765\u770b\uff0c\n//  @f[\n//  \\frac{d \\mathbf{C}_{v}}{d \\mathbf{C}}\n//  \\equiv \\frac{d \\mathbf{C}_{v}^{(t)}}{d \\mathbf{C}}\n//   = \\frac{\\frac{\\Delta t}{\\tau_{v}} }{1 + \\frac{\\Delta t}{\\tau_{v}}}\n//   \\left[\n//      \\frac{1}{d}\n//      \\left[\\text{det}\\left(\\mathbf{F}\\right)\\right]^{\\frac{2}{d}}\n//      \\mathbf{C}^{-1} \\otimes \\mathbf{C}^{-1}\n//     + \\left[\\text{det}\\left(\\mathbf{F}\\right)\\right]^{\\frac{2}{d}} \\frac{d\n//     \\mathbf{C}^{-1}}{d \\mathbf{C}}\n//    \\right] .\n//  @f]\n//  \u6ce8\u610f\uff0c\u53ea\u662f $\\mathcal{H}^{\\text{tot}, MVE}$ \u7684\u6700\u540e\u4e00\u9879\u5305\u542b\u5185\u90e8\u53d8\u91cf\u7684\u5207\u7ebf\u3002\u8fd9\u4e2a\u7279\u6b8a\u6f14\u5316\u89c4\u5f8b\u7684\u7ebf\u6027\u5316\u662f\u7ebf\u6027\u7684\u3002\u5173\u4e8e\u975e\u7ebf\u6027\u6f14\u5316\u5b9a\u5f8b\u7684\u4f8b\u5b50\uff0c\u8fd9\u79cd\u7ebf\u6027\u5316\u5fc5\u987b\u4ee5\u8fed\u4ee3\u7684\u65b9\u5f0f\u6c42\u89e3\uff0c\u89c1 @cite Koprowski  -Theiss2011a\u3002\n\n    template <int dim> \n    class Magnetoviscoelastic_Constitutive_Law final \n      : public Coupled_Magnetomechanical_Constitutive_Law_Base<dim> \n    { \n    public: \n      Magnetoviscoelastic_Constitutive_Law( \n        const ConstitutiveParameters &constitutive_parameters); \n\n      virtual void update_internal_data(const SymmetricTensor<2, dim> &C, \n                                        const Tensor<1, dim> &         H, \n                                        const DiscreteTime &time) override; \n\n      virtual double get_psi() const override; \n\n      virtual Tensor<1, dim> get_B() const override; \n\n      virtual SymmetricTensor<2, dim> get_S() const override; \n\n      virtual SymmetricTensor<2, dim> get_DD() const override; \n\n      virtual Tensor<3, dim> get_PP() const override; \n\n      virtual SymmetricTensor<4, dim> get_HH() const override; \n\n      virtual void update_end_of_timestep() override; \n\n    private: \n      SymmetricTensor<2, dim> Q_t; \n      SymmetricTensor<2, dim> Q_t1; \n\n      double                  psi; \n      Tensor<1, dim>          B; \n      SymmetricTensor<2, dim> S; \n      SymmetricTensor<2, dim> BB; \n      Tensor<3, dim>          PP; \n      SymmetricTensor<4, dim> HH; \n\n// \u4e00\u4e2a\u7528\u4e8e\u5b58\u50a8\u6240\u6709\u4e2d\u95f4\u8ba1\u7b97\u7684\u6570\u636e\u7ed3\u6784\u3002\u6211\u4eec\u5f88\u5feb\u5c31\u4f1a\u51c6\u786e\u5730\u770b\u5230\u5982\u4f55\u5229\u7528\u8fd9\u4e00\u70b9\u6765\u4f7f\u6211\u4eec\u5b9e\u9645\u8fdb\u884c\u8ba1\u7b97\u7684\u90a3\u90e8\u5206\u4ee3\u7801\u53d8\u5f97\u5e72\u51c0\u548c\u5bb9\u6613\uff08\u597d\u5427\uff0c\u81f3\u5c11\u662f\u66f4\u5bb9\u6613\uff09\u9075\u5faa\u548c\u7ef4\u62a4\u3002\u4f46\u662f\u73b0\u5728\uff0c\u6211\u4eec\u53ef\u4ee5\u8bf4\uff0c\u5b83\u5c06\u5141\u8bb8\u6211\u4eec\u628a\u8ba1\u7b97\u4e2d\u95f4\u91cf\u7684\u5bfc\u6570\u7684\u90a3\u90e8\u5206\u4ee3\u7801\u4ece\u4f7f\u7528\u5b83\u4eec\u7684\u5730\u65b9\u79fb\u5f00\u3002\n\n      mutable GeneralDataStorage cache; \n\n// \u63a5\u4e0b\u6765\u7684\u4e24\u4e2a\u51fd\u6570\u662f\u7528\u6765\u66f4\u65b0\u573a\u548c\u5185\u90e8\u53d8\u91cf\u7684\u72b6\u6001\u7684\uff0c\u5728\u6211\u4eec\u8fdb\u884c\u4efb\u4f55\u8be6\u7ec6\u7684\u8ba1\u7b97\u4e4b\u524d\u4f1a\u88ab\u8c03\u7528\u3002\n\n      void set_primary_variables(const SymmetricTensor<2, dim> &C, \n                                 const Tensor<1, dim> &         H) const; \n\n      void update_internal_variable(const DiscreteTime &time); \n\n// \u8be5\u7c7b\u63a5\u53e3\u7684\u5176\u4f59\u90e8\u5206\u4e13\u95e8\u7528\u4e8e\u8ba1\u7b97\u81ea\u7531\u80fd\u5bc6\u5ea6\u51fd\u6570\u53ca\u5176\u6240\u6709\u5bfc\u6570\u6240\u9700\u7684\u7ec4\u4ef6\u7684\u65b9\u6cd5\u3002\n\n// \u8fd0\u52a8\u5b66\u53d8\u91cf\uff0c\u6216\u79f0\u573a\u53d8\u91cf\u3002\n\n      const Tensor<1, dim> &get_H() const; \n\n      const SymmetricTensor<2, dim> &get_C() const; \n\n// \u9971\u548c\u5ea6\u51fd\u6570\u7684\u4e00\u822c\u5316\u8868\u8ff0\uff0c\u6240\u9700\u7684\u6784\u6210\u53c2\u6570\u4f5c\u4e3a\u53c2\u6570\u4f20\u9012\u7ed9\u6bcf\u4e2a\u51fd\u6570\u3002\n\n      double get_two_h_dot_h_div_h_sat_squ(const double mu_h_sat) const; \n\n      double get_tanh_two_h_dot_h_div_h_sat_squ(const double mu_h_sat) const; \n\n      double get_f_mu(const double mu, \n                      const double mu_inf, \n                      const double mu_h_sat) const; \n\n// \u9971\u548c\u5ea6\u51fd\u6570\u4e00\u9636\u5bfc\u6570\u7684\u4e00\u822c\u5316\u8868\u8ff0\uff0c\u6240\u9700\u7684\u6784\u6210\u53c2\u6570\u4f5c\u4e3a\u53c2\u6570\u4f20\u9012\u7ed9\u6bcf\u4e2a\u51fd\u6570\u3002\n\n      double get_dtanh_two_h_dot_h_div_h_sat_squ(const double mu_h_sat) const; \n\n      Tensor<1, dim> \n      get_dtwo_h_dot_h_div_h_sat_squ_dH(const double mu_h_sat) const; \n\n      Tensor<1, dim> get_df_mu_dH(const double mu, \n                                  const double mu_inf, \n                                  const double mu_h_sat) const; \n\n// \u9971\u548c\u5ea6\u51fd\u6570\u4e8c\u9636\u5bfc\u6570\u7684\u5e7f\u4e49\u516c\u5f0f\uff0c\u6240\u9700\u7684\u6784\u6210\u53c2\u6570\u4f5c\u4e3a\u53c2\u6570\u4f20\u9012\u7ed9\u6bcf\u4e2a\u51fd\u6570\u3002\n\n      double get_d2tanh_two_h_dot_h_div_h_sat_squ(const double mu_h_sat) const; \n\n      SymmetricTensor<2, dim> \n      get_d2two_h_dot_h_div_h_sat_squ_dH_dH(const double mu_h_sat) const; \n\n      SymmetricTensor<2, dim> get_d2f_mu_dH_dH(const double mu, \n                                               const double mu_inf, \n                                               const double mu_h_sat) const; \n\n// \u4ece\u573a/\u8fd0\u52a8\u5b66\u53d8\u91cf\u4e2d\u76f4\u63a5\u83b7\u5f97\u7684\u4e2d\u95f4\u91cf\u3002\n\n      const double &get_det_F() const; \n\n      const SymmetricTensor<2, dim> &get_C_inv() const; \n\n      const double &get_log_det_F() const; \n\n \n\n      const Tensor<1, dim> &get_C_inv_dot_H() const; \n\n \n\n// \u4e2d\u95f4\u91cf\u7684\u4e00\u9636\u5bfc\u6570\u3002\n\n      const SymmetricTensor<4, dim> &get_dC_inv_dC() const; \n\n      const SymmetricTensor<2, dim> &get_d_tr_C_dC() const; \n\n      const SymmetricTensor<2, dim> &get_ddet_F_dC() const; \n\n      const SymmetricTensor<2, dim> &get_dlog_det_F_dC() const; \n\n \n\n \n\n// \u5185\u90e8\u53d8\u91cf\u76f8\u5bf9\u4e8e\u573a\u53d8\u91cf\u7684\u5bfc\u6570\u3002\u6ce8\u610f\uff0c\u6211\u4eec\u53ea\u9700\u8981\u5185\u90e8\u53d8\u91cf\u7684\u8fd9\u4e2a\u5bfc\u6570\uff0c\u56e0\u4e3a\u8fd9\u4e2a\u53d8\u91cf\u53ea\u662f\u4f5c\u4e3a\u52a8\u529b\u5b66\u53d8\u91cf\u7ebf\u6027\u5316\u7684\u4e00\u90e8\u5206\u800c\u88ab\u5fae\u5206\u3002\n\n      const SymmetricTensor<4, dim> & \n      get_dQ_t_dC(const DiscreteTime &time) const; \n\n// \u4e2d\u95f4\u91cf\u7684\u4e8c\u9636\u5bfc\u6570\u3002\n\n      const SymmetricTensor<4, dim> &get_d2log_det_F_dC_dC() const; \n\n      const SymmetricTensor<4, dim> &get_d2det_F_dC_dC() const; \n\n \n\n      const Tensor<3, dim> &get_d2H_dot_C_inv_dot_H_dC_dH() const; \n\n      const SymmetricTensor<4, dim> &get_d2H_dot_C_inv_dot_H_dC_dC() const; \n    }; \n\n    template <int dim> \n    Magnetoviscoelastic_Constitutive_Law< \n      dim>::Magnetoviscoelastic_Constitutive_Law(const ConstitutiveParameters \n                                                   &constitutive_parameters) \n      : Coupled_Magnetomechanical_Constitutive_Law_Base<dim>( \n          constitutive_parameters) \n      , Q_t(Physics::Elasticity::StandardTensors<dim>::I) \n      , Q_t1(Physics::Elasticity::StandardTensors<dim>::I) \n      , psi(0.0) \n    {} \n\n    template <int dim> \n    void Magnetoviscoelastic_Constitutive_Law<dim>::update_internal_data( \n      const SymmetricTensor<2, dim> &C, \n      const Tensor<1, dim> &         H, \n      const DiscreteTime &           time) \n    { \n\n// \u8bb0\u5f55\u5e94\u7528\u7684\u53d8\u5f62\u72b6\u6001\u4ee5\u53ca\u78c1\u8f7d\u8377\u3002\u6b64\u540e\uff0c\u6839\u636e\u65b0\u7684\u53d8\u5f62\u72b6\u6001\u66f4\u65b0\u5185\u90e8\uff08\u7c98\u6027\uff09\u53d8\u91cf\u3002\n\n      set_primary_variables(C, H); \n      update_internal_variable(time); \n\n// \u6839\u636e\u5f53\u524d\u78c1\u573a\u83b7\u53d6\u5f39\u6027\u548c\u7c98\u6027\u9971\u548c\u51fd\u6570\u7684\u503c...\n\n \n                                     this->get_mu_e_inf(), \n                                     this->get_mu_e_h_sat()); \n\n      const double f_mu_v = get_f_mu(this->get_mu_v(), \n                                     this->get_mu_v_inf(), \n                                     this->get_mu_v_h_sat()); \n\n// ... \u4ee5\u53ca\u5b83\u4eec\u7684\u4e00\u9636\u5bfc\u6570...\n\n      const Tensor<1, dim> df_mu_e_dH = get_df_mu_dH(this->get_mu_e(), \n                                                     this->get_mu_e_inf(), \n                                                     this->get_mu_e_h_sat()); \n\n      const Tensor<1, dim> df_mu_v_dH = get_df_mu_dH(this->get_mu_v(), \n                                                     this->get_mu_v_inf(), \n                                                     this->get_mu_v_h_sat()); \n\n// ...\u4ee5\u53ca\u5b83\u4eec\u7684\u4e8c\u9636\u5bfc\u6570\u3002\n\n      const SymmetricTensor<2, dim> d2f_mu_e_dH_dH = \n        get_d2f_mu_dH_dH(this->get_mu_e(), \n                         this->get_mu_e_inf(), \n                         this->get_mu_e_h_sat()); \n\n      const SymmetricTensor<2, dim> d2f_mu_v_dH_dH = \n        get_d2f_mu_dH_dH(this->get_mu_v(), \n                         this->get_mu_v_inf(), \n                         this->get_mu_v_h_sat()); \n\n// \u4e2d\u95f4\u91cf\u3002\u8bf7\u6ce8\u610f\uff0c\u7531\u4e8e\u6211\u4eec\u662f\u4ece\u4e00\u4e2a\u7f13\u5b58\u4e2d\u83b7\u53d6\u8fd9\u4e9b\u503c\uff0c\u800c\u8fd9\u4e2a\u7f13\u5b58\u7684\u5bff\u547d\u6bd4\u8fd9\u4e2a\u51fd\u6570\u8c03\u7528\u7684\u5bff\u547d\u957f\uff0c\u6240\u4ee5\u6211\u4eec\u53ef\u4ee5\u5bf9\u7ed3\u679c\u8fdb\u884c\u522b\u540d\uff0c\u800c\u4e0d\u662f\u4ece\u7f13\u5b58\u4e2d\u590d\u5236\u8fd9\u4e2a\u503c\u3002\n\n      const double &                 det_F = get_det_F(); \n      const SymmetricTensor<2, dim> &C_inv = get_C_inv(); \n\n      const double &log_det_F         = get_log_det_F(); \n      const double &tr_C              = get_trace_C(); \n      const double &H_dot_C_inv_dot_H = get_H_dot_C_inv_dot_H(); \n\n// \u4e2d\u95f4\u503c\u7684\u7b2c\u4e00\u5bfc\u6570\uff0c\u4ee5\u53ca\u5185\u90e8\u53d8\u91cf\u76f8\u5bf9\u4e8e\u53f3Cauchy-Green\u53d8\u5f62\u5f20\u91cf\u7684\u90a3\u90e8\u5206\u3002\n\n      const SymmetricTensor<2, dim> &d_tr_C_dC     = get_d_tr_C_dC(); \n      const SymmetricTensor<2, dim> &ddet_F_dC     = get_ddet_F_dC(); \n      const SymmetricTensor<2, dim> &dlog_det_F_dC = get_dlog_det_F_dC(); \n\n      const SymmetricTensor<4, dim> &dQ_t_dC = get_dQ_t_dC(time); \n\n      const Tensor<1, dim> &dH_dot_C_inv_dot_H_dH = get_dH_dot_C_inv_dot_H_dH(); \n\n      const SymmetricTensor<2, dim> &dH_dot_C_inv_dot_H_dC = \n        get_dH_dot_C_inv_dot_H_dC(); \n\n// \u4e2d\u95f4\u503c\u7684\u4e8c\u9636\u5bfc\u6570\u3002\n\n      const SymmetricTensor<4, dim> &d2log_det_F_dC_dC = \n        get_d2log_det_F_dC_dC(); \n\n      const SymmetricTensor<4, dim> &d2det_F_dC_dC = get_d2det_F_dC_dC(); \n\n      const SymmetricTensor<2, dim> &d2H_dot_C_inv_dot_H_dH_dH = \n        get_d2H_dot_C_inv_dot_H_dH_dH(); \n\n      const Tensor<3, dim> &d2H_dot_C_inv_dot_H_dC_dH = \n        get_d2H_dot_C_inv_dot_H_dC_dH(); \n\n      const SymmetricTensor<4, dim> &d2H_dot_C_inv_dot_H_dC_dC = \n        get_d2H_dot_C_inv_dot_H_dC_dC(); \n\n// \u7531\u4e8e\u7ebf\u6027\u5316\u7684\u5b9a\u4e49\u53d8\u5f97\u7279\u522b\u5197\u957f\uff0c\u6211\u4eec\u5c06\u628a\u81ea\u7531\u80fd\u5bc6\u5ea6\u51fd\u6570\u5206\u89e3\u6210\u4e09\u4e2a\u76f8\u52a0\u7684\u90e8\u5206\u3002\n\n// --\u7c7b\u4f3c \"\u65b0\u80e1\u514b \"\u7684\u9879\u3002\n\n// -- \u4e0e\u901f\u5ea6\u6709\u5173\u7684\u9879\uff0c\u4ee5\u53ca\n\n// --\u7c7b\u4f3c\u4e8e\u50a8\u5b58\u5728\u78c1\u573a\u4e2d\u7684\u80fd\u91cf\u7684\u9879\u3002\n\n// \u4e3a\u4e86\u4fdd\u6301\u4e00\u81f4\uff0c\u8fd9\u4e9b\u8d21\u732e\u4e2d\u7684\u6bcf\u4e00\u4e2a\u90fd\u5c06\u88ab\u5355\u72ec\u52a0\u5165\u5230\u6211\u4eec\u60f3\u8981\u8ba1\u7b97\u7684\u53d8\u91cf\u4e2d\uff0c\u5176\u987a\u5e8f\u4e5f\u662f\u5982\u6b64\u3002\n\n// \u6240\u4ee5\uff0c\u9996\u5148\u8fd9\u662f\u80fd\u91cf\u5bc6\u5ea6\u51fd\u6570\u672c\u8eab\u3002\n\n      psi = (0.5 * this->get_mu_e() * f_mu_e) * \n              (tr_C - dim - 2.0 * std::log(det_F)) + \n            this->get_lambda_e() * (std::log(det_F) * std::log(det_F)); \n      psi += (0.5 * this->get_mu_v() * f_mu_v) * \n             (Q_t * (std::pow(det_F, -2.0 / dim) * C) - dim - \n              std::log(determinant(Q_t))); \n      psi -= \n        (0.5 * this->get_mu_0() * this->get_mu_r()) * det_F * (H * C_inv * H); \n\n// ...\u7136\u540e\u662f\u78c1\u611f\u5e94\u5f3a\u5ea6\u548cPiola-Kirchhoff\u5e94\u529b\u3002\n\n      B = \n        -(0.5 * this->get_mu_e() * (tr_C - dim - 2.0 * log_det_F)) * df_mu_e_dH; \n      B -= (0.5 * this->get_mu_v()) * \n           (Q_t * (std::pow(det_F, -2.0 / dim) * C) - dim - \n            std::log(determinant(Q_t))) * \n           df_mu_v_dH; \n      B += 0.5 * this->get_mu_0() * this->get_mu_r() * det_F * \n           dH_dot_C_inv_dot_H_dH; \n\n      S = 2.0 * (0.5 * this->get_mu_e() * f_mu_e) *                         // \n            (d_tr_C_dC - 2.0 * dlog_det_F_dC)                               // \n          + 2.0 * this->get_lambda_e() * (2.0 * log_det_F * dlog_det_F_dC); // \n      S += 2.0 * (0.5 * this->get_mu_v() * f_mu_v) * \n           ((Q_t * C) * \n              ((-2.0 / dim) * std::pow(det_F, -2.0 / dim - 1.0) * ddet_F_dC) + \n            std::pow(det_F, -2.0 / dim) * Q_t);                // dC/dC = II \n      S -= 2.0 * (0.5 * this->get_mu_0() * this->get_mu_r()) * // \n           (H_dot_C_inv_dot_H * ddet_F_dC                      // \n            + det_F * dH_dot_C_inv_dot_H_dC);                  // \n\n// ...... \u6700\u540e\u662f\u7531\u4e8e\u52a8\u80fd\u53d8\u91cf\u7684\u7ebf\u6027\u5316\u800c\u4ea7\u751f\u7684\u5207\u7ebf\u3002\n\n      BB = -(0.5 * this->get_mu_e() * (tr_C - dim - 2.0 * log_det_F)) * \n           d2f_mu_e_dH_dH; \n      BB -= (0.5 * this->get_mu_v()) * \n            (Q_t * (std::pow(det_F, -2.0 / dim) * C) - dim - \n             std::log(determinant(Q_t))) * \n            d2f_mu_v_dH_dH; \n      BB += 0.5 * this->get_mu_0() * this->get_mu_r() * det_F * \n            d2H_dot_C_inv_dot_H_dH_dH; \n\n      PP = -2.0 * (0.5 * this->get_mu_e()) * \n           outer_product(Tensor<2, dim>(d_tr_C_dC - 2.0 * dlog_det_F_dC), \n                         df_mu_e_dH); \n      PP -= 2.0 * (0.5 * this->get_mu_v()) * \n            outer_product(Tensor<2, dim>((Q_t * C) * \n                                           ((-2.0 / dim) * \n                                            std::pow(det_F, -2.0 / dim - 1.0) * \n                                            ddet_F_dC) + \n                                         std::pow(det_F, -2.0 / dim) * Q_t), \n                          df_mu_v_dH); \n      PP += 2.0 * (0.5 * this->get_mu_0() * this->get_mu_r()) * \n            (outer_product(Tensor<2, dim>(ddet_F_dC), dH_dot_C_inv_dot_H_dH) + \n             det_F * d2H_dot_C_inv_dot_H_dC_dH); \n\n      HH = \n        4.0 * (0.5 * this->get_mu_e() * f_mu_e) * (-2.0 * d2log_det_F_dC_dC) // \n        + 4.0 * this->get_lambda_e() *                                       // \n            (2.0 * outer_product(dlog_det_F_dC, dlog_det_F_dC)               // \n             + 2.0 * log_det_F * d2log_det_F_dC_dC);                         // \n      HH += 4.0 * (0.5 * this->get_mu_v() * f_mu_v) * \n            (outer_product((-2.0 / dim) * std::pow(det_F, -2.0 / dim - 1.0) * \n                             ddet_F_dC, \n                           C * dQ_t_dC + Q_t) + \n             (Q_t * C) * \n               (outer_product(ddet_F_dC, \n                              (-2.0 / dim) * (-2.0 / dim - 1.0) * \n                                std::pow(det_F, -2.0 / dim - 2.0) * ddet_F_dC) + \n                ((-2.0 / dim) * std::pow(det_F, -2.0 / dim - 1.0) * \n                 d2det_F_dC_dC)) + \n             outer_product(Q_t, \n                           (-2.0 / dim) * std::pow(det_F, -2.0 / dim - 1.0) * \n                             ddet_F_dC) + \n             std::pow(det_F, -2.0 / dim) * dQ_t_dC); \n      HH -= 4.0 * (0.5 * this->get_mu_0() * this->get_mu_r()) * // \n            (H_dot_C_inv_dot_H * d2det_F_dC_dC                  // \n             + outer_product(ddet_F_dC, dH_dot_C_inv_dot_H_dC)  // \n             + outer_product(dH_dot_C_inv_dot_H_dC, ddet_F_dC)  // \n             + det_F * d2H_dot_C_inv_dot_H_dC_dC);              // \n\n// \u73b0\u5728\u6211\u4eec\u5df2\u7ecf\u7528\u5b8c\u4e86\u5b58\u50a8\u5728\u7f13\u5b58\u4e2d\u7684\u6240\u6709\u4e34\u65f6\u53d8\u91cf\uff0c\u6211\u4eec\u53ef\u4ee5\u628a\u5b83\u6e05\u9664\u6389\uff0c\u4ee5\u91ca\u653e\u4e00\u4e9b\u5185\u5b58\u3002\n\n      cache.reset(); \n    } \n\n    template <int dim> \n    double Magnetoviscoelastic_Constitutive_Law<dim>::get_psi() const \n    { \n      return psi; \n    } \n\n    template <int dim> \n    Tensor<1, dim> Magnetoviscoelastic_Constitutive_Law<dim>::get_B() const \n    { \n      return B; \n    } \n\n    template <int dim> \n    SymmetricTensor<2, dim> \n    Magnetoviscoelastic_Constitutive_Law<dim>::get_S() const \n    { \n      return S; \n    } \n\n    template <int dim> \n    SymmetricTensor<2, dim> \n    Magnetoviscoelastic_Constitutive_Law<dim>::get_DD() const \n    { \n      return BB; \n    } \n\n    template <int dim> \n    Tensor<3, dim> Magnetoviscoelastic_Constitutive_Law<dim>::get_PP() const \n    { \n      return PP; \n    } \n\n    template <int dim> \n    SymmetricTensor<4, dim> \n    Magnetoviscoelastic_Constitutive_Law<dim>::get_HH() const \n    { \n      return HH; \n    } \n\n    template <int dim> \n    void Magnetoviscoelastic_Constitutive_Law<dim>::update_end_of_timestep() \n    { \n      Q_t1 = Q_t; \n    } \n\n    template <int dim> \n    void Magnetoviscoelastic_Constitutive_Law<dim>::update_internal_variable( \n      const DiscreteTime &time) \n    { \n      const double delta_t = this->get_delta_t(time); \n\n      Q_t = (1.0 / (1.0 + delta_t / this->get_tau_v())) * \n            (Q_t1 + (delta_t / this->get_tau_v()) * \n                      std::pow(get_det_F(), 2.0 / dim) * get_C_inv()); \n    } \n\n// \u63a5\u4e0b\u6765\u7684\u51e0\u4e2a\u51fd\u6570\u5b9e\u73b0\u4e86\u9971\u548c\u5ea6\u51fd\u6570\u7684\u5e7f\u4e49\u8868\u8ff0\uff0c\u4ee5\u53ca\u5b83\u7684\u5404\u79cd\u5bfc\u6570\u3002\n\n    template <int dim> \n    double \n    Magnetoviscoelastic_Constitutive_Law<dim>::get_two_h_dot_h_div_h_sat_squ( \n      const double mu_h_sat) const \n    { \n      const Tensor<1, dim> &H = get_H(); \n      return (2.0 * H * H) / (mu_h_sat * mu_h_sat); \n    } \n\n    template <int dim> \n    double Magnetoviscoelastic_Constitutive_Law< \n      dim>::get_tanh_two_h_dot_h_div_h_sat_squ(const double mu_h_sat) const \n    { \n      return std::tanh(get_two_h_dot_h_div_h_sat_squ(mu_h_sat)); \n    } \n\n// \u4e00\u4e2a\u6bd4\u4f8b\u51fd\u6570\uff0c\u5b83\u5c06\u4f7f\u526a\u5207\u6a21\u91cf\u5728\u78c1\u573a\u7684\u5f71\u54cd\u4e0b\u53d1\u751f\u53d8\u5316\uff08\u589e\u52a0\uff09\u3002\n\n \n    double Magnetoviscoelastic_Constitutive_Law<dim>::get_f_mu( \n      const double mu, \n      const double mu_inf, \n      const double mu_h_sat) const \n    { \n      return 1.0 + \n             (mu_inf / mu - 1.0) * get_tanh_two_h_dot_h_div_h_sat_squ(mu_h_sat); \n    } \n\n// \u7f29\u653e\u51fd\u6570\u7684\u4e00\u9636\u5bfc\u6570\n\n    template <int dim> \n    double Magnetoviscoelastic_Constitutive_Law< \n      dim>::get_dtanh_two_h_dot_h_div_h_sat_squ(const double mu_h_sat) const \n    { \n      return std::pow(1.0 / std::cosh(get_two_h_dot_h_div_h_sat_squ(mu_h_sat)), \n                      2.0); \n    } \n\n    template <int dim> \n    Tensor<1, dim> Magnetoviscoelastic_Constitutive_Law< \n      dim>::get_dtwo_h_dot_h_div_h_sat_squ_dH(const double mu_h_sat) const \n    { \n      return 2.0 * 2.0 / (mu_h_sat * mu_h_sat) * get_H(); \n    } \n\n    template <int dim> \n    Tensor<1, dim> Magnetoviscoelastic_Constitutive_Law<dim>::get_df_mu_dH( \n      const double mu, \n      const double mu_inf, \n      const double mu_h_sat) const \n  template <int dim> \n      return (mu_inf / mu - 1.0) * \n             (get_dtanh_two_h_dot_h_div_h_sat_squ(mu_h_sat) * \n              get_dtwo_h_dot_h_div_h_sat_squ_dH(mu_h_sat)); \n    } \n\n    template <int dim> \n    double Magnetoviscoelastic_Constitutive_Law< \n      dim>::get_d2tanh_two_h_dot_h_div_h_sat_squ(const double mu_h_sat) const \n    { \n      return -2.0 * get_tanh_two_h_dot_h_div_h_sat_squ(mu_h_sat) * \n             get_dtanh_two_h_dot_h_div_h_sat_squ(mu_h_sat); \n    } \n\n    template <int dim> \n    SymmetricTensor<2, dim> Magnetoviscoelastic_Constitutive_Law< \n      dim>::get_d2two_h_dot_h_div_h_sat_squ_dH_dH(const double mu_h_sat) const \n    { \n      return 2.0 * 2.0 / (mu_h_sat * mu_h_sat) * \n             Physics::Elasticity::StandardTensors<dim>::I; \n    } \n\n    template <int dim> \n    SymmetricTensor<2, dim> \n    Magnetoviscoelastic_Constitutive_Law<dim>::get_d2f_mu_dH_dH( \n      const double mu, \n      const double mu_inf, \n      const double mu_h_sat) const \n    { \n      return (mu_inf / mu - 1.0) * \n             (get_d2tanh_two_h_dot_h_div_h_sat_squ(mu_h_sat) * \n                symmetrize( \n                  outer_product(get_dtwo_h_dot_h_div_h_sat_squ_dH(mu_h_sat), \n                                get_dtwo_h_dot_h_div_h_sat_squ_dH(mu_h_sat))) + \n              get_dtanh_two_h_dot_h_div_h_sat_squ(mu_h_sat) * \n                get_d2two_h_dot_h_div_h_sat_squ_dH_dH(mu_h_sat)); \n    } \n\n// \u5bf9\u4e8e\u6211\u4eec\u4e3a\u8fd9\u4e2a\u6750\u6599\u7c7b\u91c7\u7528\u7684\u7f13\u5b58\u8ba1\u7b97\u65b9\u6cd5\uff0c\u6240\u6709\u8ba1\u7b97\u7684\u6839\u57fa\u662f\u573a\u53d8\u91cf\uff0c\u4ee5\u53ca\u4e0d\u53ef\u6539\u53d8\u7684\u8f85\u52a9\u6570\u636e\uff0c\u5982\u6784\u6210\u53c2\u6570\u548c\u65f6\u95f4\u6b65\u957f\u3002\u56e0\u6b64\uff0c\u6211\u4eec\u9700\u8981\u4ee5\u4e0e\u5176\u4ed6\u53d8\u91cf\u4e0d\u540c\u7684\u65b9\u5f0f\u5c06\u5b83\u4eec\u8f93\u5165\u7f13\u5b58\uff0c\u56e0\u4e3a\u5b83\u4eec\u662f\u7531\u7c7b\u672c\u8eab\u4e4b\u5916\u89c4\u5b9a\u7684\u8f93\u5165\u3002\u8fd9\u4e2a\u51fd\u6570\u53ea\u662f\u5c06\u5b83\u4eec\u4ece\u8f93\u5165\u53c2\u6570\u4e2d\u76f4\u63a5\u6dfb\u52a0\u5230\u7f13\u5b58\u4e2d\uff0c\u540c\u65f6\u68c0\u67e5\u90a3\u91cc\u662f\u5426\u6709\u7b49\u6548\u7684\u6570\u636e\uff08\u6211\u4eec\u5e0c\u671b\u6bcf\u4e2a\u65f6\u95f4\u6b65\u957f\u6216\u725b\u987f\u8fed\u4ee3\u53ea\u8c03\u7528\u4e00\u6b21`update_internal_data()`\u65b9\u6cd5\uff09\u3002\n\n    template <int dim> \n    void Magnetoviscoelastic_Constitutive_Law<dim>::set_primary_variables( \n      const SymmetricTensor<2, dim> &C, \n      const Tensor<1, dim> &         H) const \n    { \n\n// \u8bbe\u7f6e  $\\boldsymbol{\\mathbb{H}}$  \u7684\u503c\u3002\n\n      const std::string name_H(\"H\"); \n      Assert(!cache.stores_object_with_name(name_H), \n             ExcMessage( \n               \"The primary variable has already been added to the cache.\")); \n      cache.add_unique_copy(name_H, H); \n\n// \u8bbe\u7f6e  $\\mathbf{C}$  \u7684\u503c\u3002\n\n      const std::string name_C(\"C\"); \n      Assert(!cache.stores_object_with_name(name_C), \n             ExcMessage( \n               \"The primary variable has already been added to the cache.\")); \n      cache.add_unique_copy(name_C, C); \n    } \n\n// \u6b64\u540e\uff0c\u6211\u4eec\u53ef\u4ee5\u5728\u4efb\u4f55\u65f6\u95f4\u70b9\u4ece\u7f13\u5b58\u4e2d\u83b7\u53d6\u5b83\u4eec\u3002\n\n    template <int dim> \n    const Tensor<1, dim> & \n    Magnetoviscoelastic_Constitutive_Law<dim>::get_H() const \n    { \n      const std::string name(\"H\"); \n      Assert(cache.stores_object_with_name(name), \n             ExcMessage(\"Primary variables must be added to the cache.\")); \n      return cache.template get_object_with_name<Tensor<1, dim>>(name); \n    } \n\n    template <int dim> \n    const SymmetricTensor<2, dim> & \n    Magnetoviscoelastic_Constitutive_Law<dim>::get_C() const \n    { \n      const std::string name(\"C\"); \n      Assert(cache.stores_object_with_name(name), \n             ExcMessage(\"Primary variables must be added to the cache.\")); \n      return cache.template get_object_with_name<SymmetricTensor<2, dim>>(name); \n    } \n\n// \u5f53\u6211\u4eec\u9700\u8981\u4e3b\u8981\u53d8\u91cf\u65f6\uff0c\u4fdd\u8bc1\u5b83\u4eec\u5728\u7f13\u5b58\u4e2d\uff0c\u6211\u4eec\u4e0d\u80fd\u4ece\u5b83\u4eec\u4e2d\u8ba1\u7b97\u51fa\u6240\u6709\u7684\u4e2d\u95f4\u503c\uff08\u65e0\u8bba\u662f\u76f4\u63a5\uff0c\u8fd8\u662f\u95f4\u63a5\uff09\u3002\n\n// \u5982\u679c\u7f13\u5b58\u4e2d\u8fd8\u6ca1\u6709\u5b58\u50a8\u6211\u4eec\u8981\u627e\u7684\u503c\uff0c\u90a3\u4e48\u6211\u4eec\u5c31\u5feb\u901f\u8ba1\u7b97\uff0c\u628a\u5b83\u5b58\u50a8\u5728\u7f13\u5b58\u4e2d\uff0c\u7136\u540e\u8fd4\u56de\u521a\u521a\u5b58\u50a8\u5728\u7f13\u5b58\u4e2d\u7684\u503c\u3002\u8fd9\u6837\u6211\u4eec\u5c31\u53ef\u4ee5\u628a\u5b83\u4f5c\u4e3a\u4e00\u4e2a\u5f15\u7528\u8fd4\u56de\uff0c\u907f\u514d\u590d\u5236\u5bf9\u8c61\u3002\u540c\u6837\u7684\u9053\u7406\u4e5f\u9002\u7528\u4e8e\u590d\u5408\u51fd\u6570\u53ef\u80fd\u4f9d\u8d56\u7684\u4efb\u4f55\u503c\u3002\u6362\u53e5\u8bdd\u8bf4\uff0c\u5982\u679c\u5728\u6211\u4eec\u76ee\u524d\u611f\u5174\u8da3\u7684\u8ba1\u7b97\u4e4b\u524d\u6709\u4e00\u4e2a\u4f9d\u8d56\u94fe\uff0c\u90a3\u4e48\u5728\u6211\u4eec\u7ee7\u7eed\u4f7f\u7528\u8fd9\u4e9b\u503c\u4e4b\u524d\uff0c\u6211\u4eec\u53ef\u4ee5\u4fdd\u8bc1\u89e3\u51b3\u8fd9\u4e9b\u4f9d\u8d56\u5173\u7cfb\u3002\u5c3d\u7ba1\u4ece\u7f13\u5b58\u4e2d\u83b7\u53d6\u6570\u636e\u662f\u6709\u6210\u672c\u7684\uff0c\u4f46 \"\u5df2\u89e3\u51b3\u7684\u4f9d\u8d56\u5173\u7cfb \"\u7684\u6982\u5ff5\u53ef\u80fd\u8db3\u591f\u65b9\u4fbf\uff0c\u4f7f\u5176\u503c\u5f97\u770b\u4e00\u4e0b\u8fd9\u4e2a\u989d\u5916\u7684\u6210\u672c\u3002\u5982\u679c\u8fd9\u4e9b\u6750\u6599\u5b9a\u5f8b\u88ab\u5d4c\u5165\u5230\u6709\u9650\u5143\u6846\u67b6\u4e2d\uff0c\u90a3\u4e48\u989d\u5916\u7684\u6210\u672c\u751a\u81f3\u53ef\u80fd\u4e0d\u4f1a\u88ab\u6ce8\u610f\u5230\u3002\n\n    template <int dim> \n    const double &Magnetoviscoelastic_Constitutive_Law<dim>::get_det_F() const \n    { \n      const std::string name(\"det_F\"); \n      if (cache.stores_object_with_name(name) == false) \n        { \n          const double det_F = std::sqrt(determinant(get_C())); \n          AssertThrow(det_F > 0.0, \n                      ExcMessage(\"Volumetric Jacobian must be positive.\")); \n          cache.add_unique_copy(name, det_F); \n        } \n\n      return cache.template get_object_with_name<double>(name); \n    } \n\n    template <int dim> \n    const SymmetricTensor<2, dim> & \n    Magnetoviscoelastic_Constitutive_Law<dim>::get_C_inv() const \n    { \n      const std::string name(\"C_inv\"); \n      if (cache.stores_object_with_name(name) == false) \n        { \n          cache.add_unique_copy(name, invert(get_C())); \n        } \n\n      return cache.template get_object_with_name<SymmetricTensor<2, dim>>(name); \n    } \n\n    template <int dim> \n    const double & \n    Magnetoviscoelastic_Constitutive_Law<dim>::get_log_det_F() const \n    { \n      const std::string name(\"log(det_F)\"); \n      if (cache.stores_object_with_name(name) == false) \n        cache.add_unique_copy(name, std::log(get_det_F())); \n\n      return cache.template get_object_with_name<double>(name); \n    } \n\n    template <int dim> \n    const double &Magnetoviscoelastic_Constitutive_Law<dim>::get_trace_C() const \n    { \n      const std::string name(\"trace(C)\"); \n      if (cache.stores_object_with_name(name) == false) \n        cache.add_unique_copy(name, trace(get_C())); \n\n      return cache.template get_object_with_name<double>(name); \n    } \n\n    template <int dim> \n    const Tensor<1, dim> & \n    Magnetoviscoelastic_Constitutive_Law<dim>::get_C_inv_dot_H() const \n    { \n      const std::string name(\"C_inv_dot_H\"); \n      if (cache.stores_object_with_name(name) == false) \n        cache.add_unique_copy(name, get_C_inv() * get_H()); \n\n      return cache.template get_object_with_name<Tensor<1, dim>>(name); \n    } \n\n    template <int dim> \n    const double & \n    Magnetoviscoelastic_Constitutive_Law<dim>::get_H_dot_C_inv_dot_H() const \n    { \n      const std::string name(\"H_dot_C_inv_dot_H\"); \n      if (cache.stores_object_with_name(name) == false) \n        cache.add_unique_copy(name, get_H() * get_C_inv_dot_H()); \n\n      return cache.template get_object_with_name<double>(name); \n    } \n\n    template <int dim> \n    const SymmetricTensor<4, dim> & \n    Magnetoviscoelastic_Constitutive_Law<dim>::get_dQ_t_dC( \n      const DiscreteTime &time) const \n    { \n      const std::string name(\"dQ_t_dC\"); \n      if (cache.stores_object_with_name(name) == false) \n        { \n          const double  delta_t = this->get_delta_t(time); \n          const double &det_F   = get_det_F(); \n\n          const SymmetricTensor<4, dim> dQ_t_dC = \n            (1.0 / (1.0 + delta_t / this->get_tau_v())) * \n            (delta_t / this->get_tau_v()) * \n            ((2.0 / dim) * std::pow(det_F, 2.0 / dim - 1.0) * \n               outer_product(get_C_inv(), get_ddet_F_dC()) + \n             std::pow(det_F, 2.0 / dim) * get_dC_inv_dC()); \n\n          cache.add_unique_copy(name, dQ_t_dC); \n        } \n\n      return cache.template get_object_with_name<SymmetricTensor<4, dim>>(name); \n    } \n\n    template <int dim> \n    const SymmetricTensor<4, dim> & \n    Magnetoviscoelastic_Constitutive_Law<dim>::get_dC_inv_dC() const \n    { \n      const std::string name(\"dC_inv_dC\"); \n      if (cache.stores_object_with_name(name) == false) \n        { \n          const SymmetricTensor<2, dim> &C_inv = get_C_inv(); \n          SymmetricTensor<4, dim>        dC_inv_dC; \n\n          for (unsigned int A = 0; A < dim; ++A) \n            for (unsigned int B = A; B < dim; ++B) \n              for (unsigned int C = 0; C < dim; ++C) \n                for (unsigned int D = C; D < dim; ++D) \n                  dC_inv_dC[A][B][C][D] -=               // \n                    0.5 * (C_inv[A][C] * C_inv[B][D]     // \n                           + C_inv[A][D] * C_inv[B][C]); // \n\n          cache.add_unique_copy(name, dC_inv_dC); \n        } \n\n      return cache.template get_object_with_name<SymmetricTensor<4, dim>>(name); \n    } \n\n    template <int dim> \n    const SymmetricTensor<2, dim> & \n    Magnetoviscoelastic_Constitutive_Law<dim>::get_d_tr_C_dC() const \n    { \n      const std::string name(\"d_tr_C_dC\"); \n      if (cache.stores_object_with_name(name) == false) \n        cache.add_unique_copy(name, \n                              Physics::Elasticity::StandardTensors<dim>::I); \n\n      return cache.template get_object_with_name<SymmetricTensor<2, dim>>(name); \n    } \n\n    template <int dim> \n    const SymmetricTensor<2, dim> & \n    Magnetoviscoelastic_Constitutive_Law<dim>::get_ddet_F_dC() const \n    { \n      const std::string name(\"ddet_F_dC\"); \n      if (cache.stores_object_with_name(name) == false) \n        cache.add_unique_copy(name, 0.5 * get_det_F() * get_C_inv()); \n\n      return cache.template get_object_with_name<SymmetricTensor<2, dim>>(name); \n    } \n\n    template <int dim> \n    const SymmetricTensor<2, dim> & \n    Magnetoviscoelastic_Constitutive_Law<dim>::get_dlog_det_F_dC() const \n    { \n      const std::string name(\"dlog_det_F_dC\"); \n      if (cache.stores_object_with_name(name) == false) \n        cache.add_unique_copy(name, 0.5 * get_C_inv()); \n\n      return cache.template get_object_with_name<SymmetricTensor<2, dim>>(name); \n    } \n\n    template <int dim> \n    const Tensor<1, dim> & \n    Magnetoviscoelastic_Constitutive_Law<dim>::get_dH_dot_C_inv_dot_H_dH() const \n    { \n      const std::string name(\"dH_dot_C_inv_dot_H_dH\"); \n      if (cache.stores_object_with_name(name) == false) \n        cache.add_unique_copy(name, 2.0 * get_C_inv_dot_H()); \n\n      return cache.template get_object_with_name<Tensor<1, dim>>(name); \n    } \n\n    template <int dim> \n    const SymmetricTensor<2, dim> & \n    Magnetoviscoelastic_Constitutive_Law<dim>::get_dH_dot_C_inv_dot_H_dC() const \n    { \n      const std::string name(\"dH_dot_C_inv_dot_H_dC\"); \n      if (cache.stores_object_with_name(name) == false) \n        { \n          const Tensor<1, dim> C_inv_dot_H = get_C_inv_dot_H(); \n          cache.add_unique_copy( \n            name, -symmetrize(outer_product(C_inv_dot_H, C_inv_dot_H))); \n        } \n\n      return cache.template get_object_with_name<SymmetricTensor<2, dim>>(name); \n    } \n\n    template <int dim> \n    const SymmetricTensor<4, dim> & \n    Magnetoviscoelastic_Constitutive_Law<dim>::get_d2log_det_F_dC_dC() const \n    { \n      const std::string name(\"d2log_det_F_dC_dC\"); \n      if (cache.stores_object_with_name(name) == false) \n        cache.add_unique_copy(name, 0.5 * get_dC_inv_dC()); \n\n      return cache.template get_object_with_name<SymmetricTensor<4, dim>>(name); \n    } \n\n    template <int dim> \n    const SymmetricTensor<4, dim> & \n    Magnetoviscoelastic_Constitutive_Law<dim>::get_d2det_F_dC_dC() const \n    { \n      const std::string name(\"d2det_F_dC_dC\"); \n      if (cache.stores_object_with_name(name) == false) \n        cache.add_unique_copy(name, \n                              0.5 * \n                                (outer_product(get_C_inv(), get_ddet_F_dC()) + \n                                 get_det_F() * get_dC_inv_dC())); \n\n      return cache.template get_object_with_name<SymmetricTensor<4, dim>>(name); \n    } \n\n    template <int dim> \n    const SymmetricTensor<2, dim> & \n    Magnetoviscoelastic_Constitutive_Law<dim>::get_d2H_dot_C_inv_dot_H_dH_dH() \n      const \n    { \n      const std::string name(\"d2H_dot_C_inv_dot_H_dH_dH\"); \n      if (cache.stores_object_with_name(name) == false) \n        cache.add_unique_copy(name, 2.0 * get_C_inv()); \n\n      return cache.template get_object_with_name<SymmetricTensor<2, dim>>(name); \n    } \n\n    template <int dim> \n    const Tensor<3, dim> & \n    Magnetoviscoelastic_Constitutive_Law<dim>::get_d2H_dot_C_inv_dot_H_dC_dH() \n      const \n    { \n      const std::string name(\"d2H_dot_C_inv_dot_H_dC_dH\"); \n      if (cache.stores_object_with_name(name) == false) \n        { \n          const Tensor<1, dim> &         C_inv_dot_H = get_C_inv_dot_H(); \n          const SymmetricTensor<2, dim> &C_inv       = get_C_inv(); \n\n          Tensor<3, dim> d2H_dot_C_inv_dot_H_dC_dH; \n          for (unsigned int A = 0; A < dim; ++A) \n            for (unsigned int B = 0; B < dim; ++B) \n              for (unsigned int C = 0; C < dim; ++C) \n                d2H_dot_C_inv_dot_H_dC_dH[A][B][C] -= \n                  C_inv[A][C] * C_inv_dot_H[B] + // \n                  C_inv_dot_H[A] * C_inv[B][C];  // \n\n          cache.add_unique_copy(name, d2H_dot_C_inv_dot_H_dC_dH); \n        } \n\n      return cache.template get_object_with_name<Tensor<3, dim>>(name); \n    } \n\n    template <int dim> \n    const SymmetricTensor<4, dim> & \n    Magnetoviscoelastic_Constitutive_Law<dim>::get_d2H_dot_C_inv_dot_H_dC_dC() \n      const \n    { \n      const std::string name(\"d2H_dot_C_inv_dot_H_dC_dC\"); \n      if (cache.stores_object_with_name(name) == false) \n        { \n          const Tensor<1, dim> &         C_inv_dot_H = get_C_inv_dot_H(); \n          const SymmetricTensor<2, dim> &C_inv       = get_C_inv(); \n\n          SymmetricTensor<4, dim> d2H_dot_C_inv_dot_H_dC_dC; \n          for (unsigned int A = 0; A < dim; ++A) \n            for (unsigned int B = A; B < dim; ++B) \n              for (unsigned int C = 0; C < dim; ++C) \n                for (unsigned int D = C; D < dim; ++D) \n                  d2H_dot_C_inv_dot_H_dC_dC[A][B][C][D] += \n                    0.5 * (C_inv_dot_H[A] * C_inv_dot_H[C] * C_inv[B][D] + \n                           C_inv_dot_H[A] * C_inv_dot_H[D] * C_inv[B][C] + \n                           C_inv_dot_H[B] * C_inv_dot_H[C] * C_inv[A][D] + \n                           C_inv_dot_H[B] * C_inv_dot_H[D] * C_inv[A][C]); \n\n          cache.add_unique_copy(name, d2H_dot_C_inv_dot_H_dC_dC); \n        } \n\n      return cache.template get_object_with_name<SymmetricTensor<4, dim>>(name); \n    } \n// @sect4{Rheological experiment parameters}  \n\n//  @p RheologicalExperimentParameters \u7c7b\u662f\u7528\u6765\u9a71\u52a8\u6570\u503c\u5b9e\u9a8c\u7684\uff0c\u8fd9\u4e9b\u5b9e\u9a8c\u5c06\u5728\u6211\u4eec\u5df2\u7ecf\u5b9e\u73b0\u4e86\u6784\u6210\u6cd5\u5219\u7684\u8026\u5408\u6750\u6599\u4e0a\u8fdb\u884c\u3002\n\n    class RheologicalExperimentParameters : public ParameterAcceptor \n    { \n    public: \n      RheologicalExperimentParameters(); \n\n// \u8fd9\u4e9b\u662f\u8981\u6a21\u62df\u7684\u6d41\u53d8\u5b66\u8bd5\u6837\u7684\u5c3a\u5bf8\u3002\u5b83\u4eec\u6709\u6548\u5730\u5b9a\u4e49\u4e86\u6211\u4eec\u865a\u62df\u5b9e\u9a8c\u7684\u6d4b\u91cf\u70b9\u3002\n\n      double sample_radius = 0.01; \n      double sample_height = 0.001; \n\n// \u4e09\u4e2a\u7a33\u6001\u8d1f\u8f7d\u53c2\u6570\u5206\u522b\u662f\n\n// - \u8f74\u5411\u62c9\u4f38\u3002\n\n// -- \u526a\u5207\u5e94\u53d8\u632f\u5e45\uff0c\u548c\n\n// - \u8f74\u5411\u78c1\u573a\u5f3a\u5ea6\u3002\n\n      double lambda_2 = 0.95; \n      double gamma_12 = 0.05; \n      double H_2      = 60.0e3; \n\n// \u6b64\u5916\uff0c\u968f\u65f6\u95f4\u53d8\u5316\u7684\u6d41\u53d8\u5b66\u8d1f\u8f7d\u6761\u4ef6\u7684\u53c2\u6570\u4e3a\n\n// --\u52a0\u8f7d\u5468\u671f\u7684\u9891\u7387\u3002\n\n// - \u8d1f\u8f7d\u5468\u671f\u7684\u6570\u91cf\uff0c\u4ee5\u53ca\n\n// - \u6bcf\u4e2a\u5468\u671f\u7684\u79bb\u6563\u65f6\u95f4\u6b65\u6570\u3002\n\n      double       frequency         = 1.0 / (2.0 * numbers::PI); \n      unsigned int n_cycles          = 5; \n      unsigned int n_steps_per_cycle = 2500; \n\n// \u6211\u4eec\u8fd8\u58f0\u660e\u4e86\u4e00\u4e9b\u4e0d\u8a00\u81ea\u660e\u7684\u53c2\u6570\uff0c\u8fd9\u4e9b\u53c2\u6570\u4e0e\u7528\u901f\u7387\u4f9d\u8d56\u578b\u548c\u901f\u7387\u975e\u4f9d\u8d56\u578b\u6750\u6599\u8fdb\u884c\u7684\u5b9e\u9a8c\u6240\u4ea7\u751f\u7684\u8f93\u51fa\u6570\u636e\u6709\u5173\u3002\n\n      bool        output_data_to_file = true; \n      std::string output_filename_rd = \n        \"experimental_results-rate_dependent.csv\"; \n      std::string output_filename_ri = \n        \"experimental_results-rate_independent.csv\"; \n\n// \u63a5\u4e0b\u6765\u7684\u51e0\u4e2a\u51fd\u6570\u5c06\u8ba1\u7b97\u4e0e\u65f6\u95f4\u6709\u5173\u7684\u5b9e\u9a8c\u53c2\u6570...\n\n      double start_time() const; \n\n      double end_time() const; \n\n      double delta_t() const; \n\n// ...... \u800c\u4e0b\u9762\u4e24\u4e2a\u5219\u89c4\u5b9a\u4e86\u4efb\u4f55\u65f6\u5019\u7684\u673a\u68b0\u548c\u78c1\u529b\u8d1f\u8f7d......\n\n      Tensor<1, 3> get_H(const double time) const; \n\n      Tensor<2, 3> get_F(const double time) const; \n\n// ...... \u800c\u8fd9\u6700\u540e\u4e00\u4e2a\u662f\u5c06\u5b9e\u9a8c\u7684\u72b6\u6001\u8f93\u51fa\u5230\u63a7\u5236\u53f0\u3002\n\n      bool print_status(const int step_number) const; \n\n      bool initialized = false; \n    }; \n\n    RheologicalExperimentParameters::RheologicalExperimentParameters() \n      : ParameterAcceptor(\"/Coupled Constitutive Laws/Rheological Experiment/\") \n    { \n      add_parameter(\"Experimental sample radius\", sample_radius); \n      add_parameter(\"Experimental sample radius\", sample_height); \n\n      add_parameter(\"Axial stretch\", lambda_2); \n      add_parameter(\"Shear strain amplitude\", gamma_12); \n      add_parameter(\"Axial magnetic field strength\", H_2); \n\n      add_parameter(\"Frequency\", frequency); \n      add_parameter(\"Number of loading cycles\", n_cycles); \n      add_parameter(\"Discretisation for each cycle\", n_steps_per_cycle); \n\n      add_parameter(\"Output experimental results to file\", output_data_to_file); \n      add_parameter(\"Output file name (rate dependent constitutive law)\", \n                    output_filename_rd); \n      add_parameter(\"Output file name (rate independent constitutive law)\", \n                    output_filename_ri); \n\n      parse_parameters_call_back.connect([&]() -> void { initialized = true; }); \n    } \n\n    double RheologicalExperimentParameters::start_time() const \n    { \n      return 0.0; \n    } \n\n    double RheologicalExperimentParameters::end_time() const \n    { \n      return n_cycles / frequency; \n    } \n\n    double RheologicalExperimentParameters::delta_t() const \n    { \n      return (end_time() - start_time()) / (n_steps_per_cycle * n_cycles); \n    } \n\n    bool \n    RheologicalExperimentParameters::print_status(const int step_number) const \n    { \n      return (step_number % (n_cycles * n_steps_per_cycle / 100)) == 0; \n    } \n\n// \u65bd\u52a0\u7684\u78c1\u573a\u603b\u662f\u4e0e\u6d41\u53d8\u4eea\u8f6c\u5b50\u7684\u65cb\u8f6c\u8f74\u5bf9\u9f50\u3002\n\n    Tensor<1, 3> RheologicalExperimentParameters::get_H(const double) const \n    { \n      return Tensor<1, 3>({0.0, 0.0, H_2}); \n    } \n\n// \u6839\u636e\u6d41\u53d8\u4eea\u548c\u6837\u54c1\u7684\u51e0\u4f55\u5f62\u72b6\u3001\u91c7\u6837\u70b9\u548c\u5b9e\u9a8c\u53c2\u6570\uff0c\u8ba1\u7b97\u51fa\u5e94\u7528\u7684\u53d8\u5f62\uff08\u68af\u5ea6\uff09\u3002\u6839\u636e\u4ecb\u7ecd\u4e2d\u8bb0\u5f55\u7684\u4f4d\u79fb\u66f2\u7ebf\uff0c\u53d8\u5f62\u68af\u5ea6\u53ef\u4ee5\u7528\u76f4\u89d2\u5750\u6807\u8868\u793a\u4e3a \n// @f[\n//  \\mathbf{F} = \\begin{bmatrix}\n//     \\frac{\\cos\\left(\\alpha\\right)}{\\sqrt{\\lambda_{3}}}\n//  & -\\frac{\\sin\\left(\\alpha\\right)}{\\sqrt{\\lambda_{3}}}\n//  & -\\tau R \\sqrt{\\lambda_{3}} \\sin\\left(\\Theta + \\alpha\\right)\n//  \\\\  \\frac{\\sin\\left(\\alpha\\right)}{\\sqrt{\\lambda_{3}}}\n//  & \\frac{\\cos\\left(\\alpha\\right)}{\\sqrt{\\lambda_{3}}}\n//  & -\\tau R \\sqrt{\\lambda_{3}} \\cos\\left(\\Theta + \\alpha\\right)\n//  \\\\  0 & 0 & \\lambda_{3}\n//  \\end{bmatrix}\n//  @f] \u3002\n\n    Tensor<2, 3> RheologicalExperimentParameters::get_F(const double time) const \n    { \n      AssertThrow((sample_radius > 0.0 && sample_height > 0.0), \n                  ExcMessage(\"Non-physical sample dimensions\")); \n      AssertThrow(lambda_2 > 0.0, \n                  ExcMessage(\"Non-physical applied axial stretch\")); \n\n      const double sqrt_lambda_2     = std::sqrt(lambda_2); \n      const double inv_sqrt_lambda_2 = 1.0 / sqrt_lambda_2; \n\n      const double alpha_max = \n        std::atan(std::tan(gamma_12) * sample_height / \n                  sample_radius); // Small strain approximation \n      const double A       = sample_radius * alpha_max; \n      const double w       = 2.0 * numbers::PI * frequency; // in rad /s \n      const double gamma_t = A * std::sin(w * time); \n      const double tau_t = \n        gamma_t / \n        (sample_radius * sample_height); // Torsion angle per unit length \n      const double alpha_t = tau_t * lambda_2 * sample_height; \n\n      Tensor<2, 3> F; \n      F[0][0] = inv_sqrt_lambda_2 * std::cos(alpha_t); \n      F[0][1] = -inv_sqrt_lambda_2 * std::sin(alpha_t); \n      F[0][2] = -tau_t * sample_radius * sqrt_lambda_2 * std::sin(alpha_t); \n      F[1][0] = inv_sqrt_lambda_2 * std::sin(alpha_t); \n      F[1][1] = inv_sqrt_lambda_2 * std::cos(alpha_t); \n      F[1][2] = tau_t * sample_radius * sqrt_lambda_2 * std::cos(alpha_t); \n      F[2][0] = 0.0; \n      F[2][1] = 0.0; \n      F[2][2] = lambda_2; \n\n      AssertThrow((F[0][0] > 0) && (F[1][1] > 0) && (F[2][2] > 0), \n                  ExcMessage(\"Non-physical deformation gradient component.\")); \n      AssertThrow(std::abs(determinant(F) - 1.0) < 1e-6, \n                  ExcMessage(\"Volumetric Jacobian is not equal to unity.\")); \n\n      return F; \n    } \n// @sect4{Rheological experiment: Parallel plate rotational rheometer}  \n\n// \u8fd9\u662f\u5c06\u9a71\u52a8\u6570\u503c\u5b9e\u9a8c\u7684\u51fd\u6570\u3002\n\n    template <int dim> \n    void run_rheological_experiment( \n      const RheologicalExperimentParameters &experimental_parameters, \n      Coupled_Magnetomechanical_Constitutive_Law_Base<dim> \n        &material_hand_calculated, \n      Coupled_Magnetomechanical_Constitutive_Law_Base<dim> \n        &               material_assisted_computation, \n      TimerOutput &     timer, \n      const std::string filename) \n    { \n\n// \u6211\u4eec\u53ef\u4ee5\u5229\u7528\u624b\u5de5\u5b9e\u73b0\u7684\u6784\u6210\u6cd5\uff0c\u5c06\u6211\u4eec\u7528\u5b83\u8fbe\u5230\u7684\u7ed3\u679c\u4e0e\u7528AD\u6216SD\u5f97\u5230\u7684\u7ed3\u679c\u8fdb\u884c\u6bd4\u8f83\u3002\u901a\u8fc7\u8fd9\u79cd\u65b9\u5f0f\uff0c\u6211\u4eec\u53ef\u4ee5\u9a8c\u8bc1\u5b83\u4eec\u4ea7\u751f\u4e86\u76f8\u540c\u7684\u7ed3\u679c\uff08\u8fd9\u8868\u660e\u8981\u4e48\u4e24\u79cd\u5b9e\u73b0\u65b9\u5f0f\u90fd\u6709\u5f88\u5927\u7684\u53ef\u80fd\u6027\u662f\u6b63\u786e\u7684\uff0c\u8981\u4e48\u5c31\u662f\u5b83\u4eec\u90fd\u6709\u76f8\u540c\u7684\u7f3a\u9677\u800c\u4e0d\u6b63\u786e\uff09\u3002\u65e0\u8bba\u54ea\u79cd\u65b9\u5f0f\uff0c\u5bf9\u4e8e\u5b8c\u5168\u81ea\u6211\u5b9e\u73b0\u7684\u53d8\u4f53\u6765\u8bf4\uff0c\u8fd9\u90fd\u662f\u4e00\u4e2a\u5f88\u597d\u7684\u7406\u667a\u68c0\u67e5\uff0c\u5f53\u53d1\u73b0\u7ed3\u679c\u4e4b\u95f4\u7684\u5dee\u5f02\u65f6\uff0c\u5f53\u7136\u53ef\u4ee5\u4f5c\u4e3a\u4e00\u79cd\u8c03\u8bd5\u7b56\u7565\uff09\u3002)\n\n      const auto check_material_class_results = \n        []( \n          const Coupled_Magnetomechanical_Constitutive_Law_Base<dim> &to_verify, \n          const Coupled_Magnetomechanical_Constitutive_Law_Base<dim> &blessed, \n          const double tol = 1e-6) { \n          (void)to_verify; \n          (void)blessed; \n          (void)tol; \n\n          Assert(std::abs(blessed.get_psi() - to_verify.get_psi()) < tol, \n                 ExcMessage(\"No match for psi. Error: \" + \n                            Utilities::to_string(std::abs( \n                              blessed.get_psi() - to_verify.get_psi())))); \n\n          Assert((blessed.get_B() - to_verify.get_B()).norm() < tol, \n                 ExcMessage(\"No match for B. Error: \" + \n                            Utilities::to_string( \n                              (blessed.get_B() - to_verify.get_B()).norm()))); \n          Assert((blessed.get_S() - to_verify.get_S()).norm() < tol, \n                 ExcMessage(\"No match for S. Error: \" + \n                            Utilities::to_string( \n                              (blessed.get_S() - to_verify.get_S()).norm()))); \n\n          Assert((blessed.get_DD() - to_verify.get_DD()).norm() < tol, \n                 ExcMessage(\"No match for BB. Error: \" + \n                            Utilities::to_string( \n                              (blessed.get_DD() - to_verify.get_DD()).norm()))); \n          Assert((blessed.get_PP() - to_verify.get_PP()).norm() < tol, \n                 ExcMessage(\"No match for PP. Error: \" + \n                            Utilities::to_string( \n                              (blessed.get_PP() - to_verify.get_PP()).norm()))); \n          Assert((blessed.get_HH() - to_verify.get_HH()).norm() < tol, \n                 ExcMessage(\"No match for HH. Error: \" + \n                            Utilities::to_string( \n                              (blessed.get_HH() - to_verify.get_HH()).norm()))); \n        }; \n\n// \u6211\u4eec\u5c06\u628a\u6750\u6599\u7684\u6784\u6210\u6027\u54cd\u5e94\u8f93\u51fa\u5230\u6587\u4ef6\u4e2d\u8fdb\u884c\u540e\u5904\u7406\uff0c\u6240\u4ee5\u5728\u8fd9\u91cc\u6211\u4eec\u58f0\u660e\u4e00\u4e2a`stream`\uff0c\u5b83\u5c06\u4f5c\u4e3a\u8fd9\u4e2a\u8f93\u51fa\u7684\u7f13\u51b2\u533a\u3002\u6211\u4eec\u5c06\u4f7f\u7528\u4e00\u4e2a\u7b80\u5355\u7684CSV\u683c\u5f0f\u6765\u8f93\u51fa\u7ed3\u679c\u3002\n\n      std::ostringstream stream; \n      stream \n        << \"Time;Axial magnetic field strength [A/m];Axial magnetic induction [T];Shear strain [%];Shear stress [Pa]\\n\"; \n\n// \u4f7f\u7528DiscreteTime\u7c7b\uff0c\u6211\u4eec\u4f7f\u7528\u4e00\u4e2a\u56fa\u5b9a\u7684\u65f6\u95f4\u6b65\u957f\u6765\u8fed\u4ee3\u6bcf\u4e2a\u65f6\u95f4\u6bb5\u3002\n\n      for (DiscreteTime time(experimental_parameters.start_time(), \n                             experimental_parameters.end_time() + \n                               experimental_parameters.delta_t(), \n                             experimental_parameters.delta_t()); \n           time.is_at_end() == false; \n           time.advance_time()) \n        { \n          if (experimental_parameters.print_status(time.get_step_number())) \n            std::cout << \"Timestep = \" << time.get_step_number() \n                      << \" @ time = \" << time.get_current_time() << \"s.\" \n                      << std::endl; \n\n// \u6211\u4eec\u83b7\u53d6\u5e76\u8ba1\u7b97\u5728\u8fd9\u4e2a\u65f6\u95f4\u6b65\u957f\u4e2d\u5e94\u7528\u4e8e\u6750\u6599\u7684\u8d1f\u8f7d...\n\n          const Tensor<1, dim> H = \n            experimental_parameters.get_H(time.get_current_time()); \n          const Tensor<2, dim> F = \n            experimental_parameters.get_F(time.get_current_time()); \n          const SymmetricTensor<2, dim> C = \n            Physics::Elasticity::Kinematics::C(F); \n\n// ...\u7136\u540e\u6211\u4eec\u66f4\u65b0\u6750\u6599\u7684\u72b6\u6001...\n\n          { \n            TimerOutput::Scope timer_section(timer, \"Hand calculated\"); \n            material_hand_calculated.update_internal_data(C, H, time); \n            material_hand_calculated.update_end_of_timestep(); \n          } \n\n          { \n            TimerOutput::Scope timer_section(timer, \"Assisted computation\"); \n            material_assisted_computation.update_internal_data(C, H, time); \n            material_assisted_computation.update_end_of_timestep(); \n          } \n\n// ...\u5e76\u6d4b\u8bd5\u4e24\u8005\u4e4b\u95f4\u7684\u5dee\u5f02\u3002\n\n          check_material_class_results(material_hand_calculated, \n                                       material_assisted_computation); \n\n          if (experimental_parameters.output_data_to_file) \n            { \n\n// \u63a5\u4e0b\u6765\u6211\u4eec\u8981\u505a\u7684\u662f\u6536\u96c6\u4e00\u4e9b\u7ed3\u679c\u8fdb\u884c\u540e\u5904\u7406\u3002\u6240\u6709\u7684\u6570\u91cf\u90fd\u5728 \"\u5f53\u524d\u914d\u7f6e \"\u4e2d\uff08\u800c\u4e0d\u662f \"\u53c2\u8003\u914d\u7f6e\"\uff0c\u6240\u6709\u7531\u6784\u6210\u6cd5\u5219\u8ba1\u7b97\u7684\u6570\u91cf\u90fd\u5728\u8fd9\u4e2a\u6846\u67b6\u4e2d\uff09\u3002\n\n              const Tensor<1, dim> h = \n                Physics::Transformations::Covariant::push_forward(H, F); \n              const Tensor<1, dim> b = \n                Physics::Transformations::Piola::push_forward( \n                  material_hand_calculated.get_B(), F); \n              const SymmetricTensor<2, dim> sigma = \n                Physics::Transformations::Piola::push_forward( \n                  material_hand_calculated.get_S(), F); \n              stream << time.get_current_time() << \";\" << h[2] << \";\" << b[2] \n                     << \";\" << F[1][2] * 100.0 << \";\" << sigma[1][2] << \"\\n\"; \n            } \n        } \n\n// \u6700\u540e\uff0c\u6211\u4eec\u5c06\u5e94\u53d8\u5e94\u529b\u548c\u78c1\u8f7d\u8377\u5386\u53f2\u8f93\u51fa\u5230\u6587\u4ef6\u4e2d\u3002\n\n      if (experimental_parameters.output_data_to_file) \n        { \n          std::ofstream output(filename); \n          output << stream.str(); \n        } \n    } \n// @sect4{The CoupledConstitutiveLaws::run() function}  \n\n// \u8fd9\u4e2a\u9a71\u52a8\u51fd\u6570\u7684\u76ee\u7684\u662f\u8bfb\u53d6\u6587\u4ef6\u4e2d\u7684\u6240\u6709\u53c2\u6570\uff0c\u5e76\u5728\u6b64\u57fa\u7840\u4e0a\u521b\u5efa\u6bcf\u4e2a\u6784\u6210\u6cd5\u5219\u7684\u4ee3\u8868\u6027\u5b9e\u4f8b\uff0c\u5e76\u8c03\u7528\u51fd\u6570\u5bf9\u5176\u8fdb\u884c\u6d41\u53d8\u5b66\u5b9e\u9a8c\u3002\n\n    void run(int argc, char *argv[]) \n    { \n      using namespace dealii; \n\n      constexpr unsigned int dim = 3; \n\n      const ConstitutiveParameters          constitutive_parameters; \n      const RheologicalExperimentParameters experimental_parameters; \n\n      std::string parameter_file; \n      if (argc > 1) \n        parameter_file = argv[1]; \n      else \n        parameter_file = \"parameters.prm\"; \n      ParameterAcceptor::initialize(parameter_file, \"used_parameters.prm\"); \n\n// \u6211\u4eec\u5f00\u59cb\u5b9e\u9645\u5de5\u4f5c\uff0c\u4f7f\u7528\u6211\u4eec\u4e0e\u901f\u7387\u65e0\u5173\u7684\u6784\u6210\u6cd5\u914d\u7f6e\u548c\u8fd0\u884c\u5b9e\u9a8c\u3002\u8fd9\u91cc\u7684\u81ea\u52a8\u53ef\u5fae\u8c03\u6570\u7c7b\u578b\u662f\u786c\u7f16\u7801\u7684\uff0c\u4f46\u662f\u901a\u8fc7\u4e00\u4e9b\u5de7\u5999\u7684\u6a21\u677f\u8bbe\u8ba1\uff0c\u53ef\u4ee5\u5728\u8fd0\u884c\u65f6\u9009\u62e9\u4f7f\u7528\u54ea\u79cd\u6846\u67b6\uff08\u4f8b\u5982\uff0c\u901a\u8fc7\u53c2\u6570\u6587\u4ef6\u9009\u62e9\uff09\u3002\u6211\u4eec\u5c06\u540c\u65f6\u7528\u5b8c\u5168\u624b\u5de5\u5b9e\u73b0\u7684\u53cd\u9762\u6750\u6599\u6cd5\u8fdb\u884c\u5b9e\u9a8c\uff0c\u5e76\u68c0\u67e5\u5b83\u4e0e\u6211\u4eec\u7684\u8f85\u52a9\u5b9e\u73b0\u7684\u8ba1\u7b97\u7ed3\u679c\u3002\n\n      { \n        TimerOutput timer(std::cout, \n                          TimerOutput::summary, \n                          TimerOutput::wall_times); \n        std::cout \n          << \"Coupled magnetoelastic constitutive law using automatic differentiation.\" \n          << std::endl; \n\n        constexpr Differentiation::AD::NumberTypes ADTypeCode = \n          Differentiation::AD::NumberTypes::sacado_dfad_dfad; \n\n        Magnetoelastic_Constitutive_Law<dim> material(constitutive_parameters); \n        Magnetoelastic_Constitutive_Law_AD<dim, ADTypeCode> material_ad( \n          constitutive_parameters); \n\n        run_rheological_experiment(experimental_parameters, \n                                   material, \n                                   material_ad, \n                                   timer, \n                                   experimental_parameters.output_filename_ri); \n\n        std::cout << \"... all calculations are correct!\" << std::endl; \n      } \n\n// \u63a5\u4e0b\u6765\u6211\u4eec\u5bf9\u4e0e\u901f\u7387\u76f8\u5173\u7684\u6784\u6210\u6cd5\u5219\u505a\u540c\u6837\u7684\u5904\u7406\u3002\u5982\u679cSymEngine\u88ab\u8bbe\u7f6e\u4e3a\u4f7f\u7528LLVM\u5373\u65f6\u7f16\u8bd1\u5668\uff0c\u5219\u9ed8\u8ba4\u9009\u62e9\u6700\u9ad8\u6027\u80fd\u7684\u9009\u9879\uff0c\u8be5\u7f16\u8bd1\u5668\uff08\u7ed3\u5408\u4e00\u4e9b\u79ef\u6781\u7684\u7f16\u8bd1\u6807\u5fd7\uff09\u4ea7\u751f\u6240\u6709\u53ef\u7528\u9009\u9879\u4e2d\u6700\u5feb\u7684\u4ee3\u7801\u8bc4\u4f30\u8def\u5f84\u3002\u4f5c\u4e3a\u540e\u5907\u63aa\u65bd\uff0c\u6240\u8c13\u7684 \"lambda \"\u4f18\u5316\u5668\uff08\u5b83\u53ea\u9700\u8981\u4e00\u4e2a\u517c\u5bb9C++11\u7684\u7f16\u8bd1\u5668\uff09\u5c06\u88ab\u9009\u4e2d\u3002\u540c\u65f6\uff0c\u6211\u4eec\u5c06\u8981\u6c42CAS\u8fdb\u884c\u666e\u901a\u5b50\u8868\u8fbe\u5f0f\u7684\u6d88\u9664\uff0c\u4ee5\u5c3d\u91cf\u51cf\u5c11\u8bc4\u4f30\u8fc7\u7a0b\u4e2d\u4f7f\u7528\u7684\u4e2d\u95f4\u8ba1\u7b97\u7684\u6570\u91cf\u3002\u6211\u4eec\u5c06\u8bb0\u5f55\u5728SD\u5b9e\u73b0\u7684\u6784\u9020\u5668\u5185\u6267\u884c \"\u521d\u59cb\u5316 \"\u6b65\u9aa4\u6240\u9700\u7684\u65f6\u95f4\uff0c\u56e0\u4e3a\u8fd9\u6b63\u662f\u4e0a\u8ff0\u8f6c\u6362\u53d1\u751f\u7684\u5730\u65b9\u3002\n\n      { \n        TimerOutput timer(std::cout, \n                          TimerOutput::summary, \n                          TimerOutput::wall_times); \n        std::cout \n          << \"Coupled magneto-viscoelastic constitutive law using symbolic differentiation.\" \n          << std::endl; \n\n#ifdef DEAL_II_SYMENGINE_WITH_LLVM \n        std::cout << \"Using LLVM optimizer.\" << std::endl; \n        constexpr Differentiation::SD::OptimizerType optimizer_type = \n          Differentiation::SD::OptimizerType::llvm; \n        constexpr Differentiation::SD::OptimizationFlags optimization_flags = \n          Differentiation::SD::OptimizationFlags::optimize_all; \n#else \n        std::cout << \"Using lambda optimizer.\" << std::endl; \n        constexpr Differentiation::SD::OptimizerType optimizer_type = \n          Differentiation::SD::OptimizerType::lambda; \n        constexpr Differentiation::SD::OptimizationFlags optimization_flags = \n          Differentiation::SD::OptimizationFlags::optimize_cse; \n#endif \n\n        Magnetoviscoelastic_Constitutive_Law<dim> material( \n          constitutive_parameters); \n\n        timer.enter_subsection(\"Initialize symbolic CL\"); \n        Magnetoviscoelastic_Constitutive_Law_SD<dim> material_sd( \n          constitutive_parameters, optimizer_type, optimization_flags); \n        timer.leave_subsection(); \n\n        run_rheological_experiment(experimental_parameters, \n                                   material, \n                                   material_sd, \n                                   timer, \n                                   experimental_parameters.output_filename_rd); \n\n        std::cout << \"... all calculations are correct!\" << std::endl; \n      } \n    } \n\n  } // namespace CoupledConstitutiveLaws \n\n} // namespace Step71 \n// @sect3{The main() function}  \n\n// \u4e3b\u51fd\u6570\u53ea\u8c03\u7528\u4e24\u7ec4\u8981\u6267\u884c\u7684\u4f8b\u5b50\u7684\u9a71\u52a8\u51fd\u6570\u3002\n\nint main(int argc, char *argv[]) \n{ \n  Step71::SimpleExample::run(); \n  Step71::CoupledConstitutiveLaws::run(argc, argv); \n\n  return 0; \n} \n\n", "meta": {"hexsha": "9a2640f04f3c77b8f46c0ff5f5a34d1c7ae0f0bc", "size": 132870, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-71/step-71.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-71/step-71.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-71/step-71.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.6626865672, "max_line_length": 439, "alphanum_fraction": 0.6083841349, "num_tokens": 54192, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.47475155542362063}}
{"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#include <nt2/trigonometric/include/functions/rem_pio2_straight.hpp>\n#include <boost/fusion/tuple.hpp>\n#include <nt2/sdk/meta/as_integer.hpp>\n#include <nt2/sdk/meta/as_floating.hpp>\n#include <nt2/sdk/unit/tests/ulp.hpp>\n#include <nt2/sdk/unit/tests/relation.hpp>\n#include <nt2/sdk/unit/tests/type_expr.hpp>\n#include <nt2/sdk/unit/module.hpp>\n\n#include <nt2/include/constants/pio_2.hpp>\n#include <nt2/include/constants/pio_4.hpp>\n#include <nt2/include/constants/one.hpp>\n#include <nt2/include/constants/zero.hpp>\n\nNT2_TEST_CASE_TPL ( rem_pio2_straight_real__1_0,  NT2_REAL_TYPES)\n{\n\n  using nt2::rem_pio2_straight;\n  using nt2::tag::rem_pio2_straight_;\n  typedef typename nt2::meta::as_integer<T>::type iT;\n\n\n  NT2_TEST_TYPE_IS( (typename boost::dispatch::meta::call<rem_pio2_straight_(T)>::type)\n                  , (std::pair<iT,T>)\n                  );\n\n  {\n    T r1;\n    NT2_TEST_EQUAL( rem_pio2_straight(nt2::Pio_2<T>(), r1), nt2::One<iT>());\n    NT2_TEST_ULP_EQUAL( r1, nt2::Zero<T>(), 0.5);\n    NT2_TEST_EQUAL( rem_pio2_straight(nt2::Pio_4<T>(), r1), nt2::One<iT>());\n    NT2_TEST_ULP_EQUAL( r1, -nt2::Pio_4<T>(), 0.5);\n  }\n}\n", "meta": {"hexsha": "99b227c4fb93b1f7d98bd5df007c08287eb8216d", "size": 1640, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/core/trigonometric/unit/scalar/rem_pio2_straight.cpp", "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/unit/scalar/rem_pio2_straight.cpp", "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/unit/scalar/rem_pio2_straight.cpp", "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.1395348837, "max_line_length": 87, "alphanum_fraction": 0.6097560976, "num_tokens": 462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7025300449389326, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.47474494469694134}}
{"text": "//==================================================================================================\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#include <boost/simd/function/frexp.hpp>\n#include <boost/simd/function/toint.hpp>\n#include <boost/simd/function/pedantic.hpp>\n#include <boost/simd/constant/nbmantissabits.hpp>\n#include <boost/simd/constant/halfeps.hpp>\n#include <scalar_test.hpp>\n\nnamespace bs = boost::simd;\n\nSTF_CASE_TPL(\"Check basic behavior of pedantic_(frexp)\", STF_IEEE_TYPES)\n{\n  STF_EXPR_IS( (bs::pedantic_(bs::frexp)(T(0))), (std::pair<T,T>) );\n\n  auto p = bs::pedantic_(bs::frexp)(T(1));\n  STF_EQUAL(p.first  , T(0.5));\n  STF_EQUAL(p.second , T(1));\n}\n\nSTF_CASE_TPL(\"Check behavior of pedantic_(frexp) on Zero\", STF_IEEE_TYPES)\n{\n  auto r = bs::pedantic_(bs::frexp)(T(0));\n\n  STF_EQUAL (r.first , T(0));\n  STF_EQUAL (r.second, T(0));\n  STF_EQUAL (ldexp(r.first,bs::toint(r.second)), T(0));\n}\n\nSTF_CASE_TPL(\"Check behavior of pedantic_(frexp) on Valmax\", STF_IEEE_TYPES)\n{\n  auto r = bs::pedantic_(bs::frexp)(bs::Valmax<T>());\n\n  STF_ULP_EQUAL (r.first , T(1)-bs::Halfeps<T>(), 1);\n  STF_EQUAL     (r.second, bs::Limitexponent<T>());\n  STF_EQUAL     (ldexp(r.first,bs::toint(r.second)),bs::Valmax<T>());\n}\n\n#ifndef BOOST_SIMD_NO_INVALID\n#include <boost/simd/constant/nan.hpp>\n\nSTF_CASE_TPL(\"Check behavior of pedantic_(frexp) on NaN\", STF_IEEE_TYPES)\n{\n  auto r = bs::pedantic_(bs::frexp)(bs::Nan<T>());\n\n  STF_IEEE_EQUAL(r.first , bs::Nan<T>());\n  STF_EQUAL     (r.second, T(0));\n  STF_IEEE_EQUAL(ldexp(r.first,bs::toint(r.second)), bs::Nan<T>());\n}\n#endif\n\n#ifndef BOOST_SIMD_NO_INFINITIES\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/minf.hpp>\n\nSTF_CASE_TPL(\"Check behavior of pedantic_(frexp) on infinites\", STF_IEEE_TYPES)\n{\n  auto r = bs::pedantic_(bs::frexp)(bs::Inf<T>());\n  auto q = bs::pedantic_(bs::frexp)(bs::Minf<T>());\n\n  STF_IEEE_EQUAL(r.first , bs::Inf<T>());\n  STF_EQUAL     (r.second, T(0));\n  STF_IEEE_EQUAL(ldexp(r.first,bs::toint(r.second)), bs::Inf<T>());\n\n  STF_IEEE_EQUAL(q.first , bs::Minf<T>());\n  STF_EQUAL     (q.second, T(0));\n  STF_IEEE_EQUAL(ldexp(q.first,bs::toint(q.second)), bs::Minf<T>());\n}\n#endif\n\n#ifndef BOOST_SIMD_NO_DENORMALS\n#include <boost/simd/detail/constant/minexponent.hpp>\n#include <boost/simd/constant/mindenormal.hpp>\n\nSTF_CASE_TPL(\"Check behavior of pedantic_(frexp) on denormals\", STF_IEEE_TYPES)\n{\n  auto r = bs::pedantic_(bs::frexp)(bs::Mindenormal<T>());\n\n  STF_ULP_EQUAL (r.first, T(0.5), 1);\n  STF_EQUAL     (r.second, bs::Minexponent<T>()-bs::Nbmantissabits<T>()+1);\n  STF_EQUAL     (ldexp(r.first,bs::toint(r.second)),bs::Mindenormal<T>());\n}\n#endif\n", "meta": {"hexsha": "8ebddc0b2515b85ba4c0bc82b4b8c8f814c6c862", "size": 2891, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/scalar/frexp.pedantic.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": "test/function/scalar/frexp.pedantic.cpp", "max_issues_repo_name": "remymuller/boost.simd", "max_issues_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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/function/scalar/frexp.pedantic.cpp", "max_forks_repo_name": "remymuller/boost.simd", "max_forks_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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": 32.1222222222, "max_line_length": 100, "alphanum_fraction": 0.6392251816, "num_tokens": 897, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.6757645944891558, "lm_q1q2_score": 0.4747449393521143}}
{"text": "// Copyright 2015-2018 Hans Dembinski\n//\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n//[ guide_indexed_access\n\n#include <boost/format.hpp>\n#include <boost/histogram.hpp>\n#include <cassert>\n#include <iostream>\n#include <numeric> // for std::accumulate\n#include <sstream>\n\nusing namespace boost::histogram;\n\nint main() {\n  // make histogram with 2 x 2 = 4 bins (not counting under-/overflow bins)\n  auto h = make_histogram(axis::regular<>(2, -1.0, 1.0), axis::regular<>(2, 2.0, 4.0));\n\n  h(weight(1), -0.5, 2.5); // bin index 0, 0\n  h(weight(2), -0.5, 3.5); // bin index 0, 1\n  h(weight(3), 0.5, 2.5);  // bin index 1, 0\n  h(weight(4), 0.5, 3.5);  // bin index 1, 1\n\n  // use the `indexed` range adaptor to iterate over all bins;\n  // it is not only more convenient but also faster than a hand-crafted loop!\n  std::ostringstream os;\n  for (auto&& x : indexed(h)) {\n    // x is a special accessor object\n    const auto i = x.index(0); // current index along first axis\n    const auto j = x.index(1); // current index along second axis\n    const auto b0 = x.bin(0);  // current bin interval along first axis\n    const auto b1 = x.bin(1);  // current bin interval along second axis\n    const auto v = *x;         // \"dereference\" to get the bin value\n    os << boost::format(\"%i %i [%2i, %i) [%2i, %i): %i\\n\") % i % j % b0.lower() %\n              b0.upper() % b1.lower() % b1.upper() % v;\n  }\n\n  std::cout << os.str() << std::flush;\n\n  assert(os.str() == \"0 0 [-1, 0) [ 2, 3): 1\\n\"\n                     \"1 0 [ 0, 1) [ 2, 3): 3\\n\"\n                     \"0 1 [-1, 0) [ 3, 4): 2\\n\"\n                     \"1 1 [ 0, 1) [ 3, 4): 4\\n\");\n\n  // `indexed` skips underflow and overflow bins by default, but can be called\n  // with the second argument `coverage::all` to walk over all bins\n  std::ostringstream os2;\n  for (auto&& x : indexed(h, coverage::all)) {\n    os2 << boost::format(\"%2i %2i: %i\\n\") % x.index(0) % x.index(1) % *x;\n  }\n\n  std::cout << os2.str() << std::flush;\n\n  assert(os2.str() == \"-1 -1: 0\\n\"\n                      \" 0 -1: 0\\n\"\n                      \" 1 -1: 0\\n\"\n                      \" 2 -1: 0\\n\"\n\n                      \"-1  0: 0\\n\"\n                      \" 0  0: 1\\n\"\n                      \" 1  0: 3\\n\"\n                      \" 2  0: 0\\n\"\n\n                      \"-1  1: 0\\n\"\n                      \" 0  1: 2\\n\"\n                      \" 1  1: 4\\n\"\n                      \" 2  1: 0\\n\"\n\n                      \"-1  2: 0\\n\"\n                      \" 0  2: 0\\n\"\n                      \" 1  2: 0\\n\"\n                      \" 2  2: 0\\n\");\n}\n\n//]\n", "meta": {"hexsha": "5850c1d3ce75344a461393db77a44e9186c46dfc", "size": 2649, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/histogram/examples/guide_indexed_access.cpp", "max_stars_repo_name": "cpp-pm/boost", "max_stars_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "libs/histogram/examples/guide_indexed_access.cpp", "max_issues_repo_name": "cpp-pm/boost", "max_issues_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "libs/histogram/examples/guide_indexed_access.cpp", "max_forks_repo_name": "cpp-pm/boost", "max_forks_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 33.5316455696, "max_line_length": 87, "alphanum_fraction": 0.4907512269, "num_tokens": 890, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300449389326, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.4747449355220513}}
{"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/*!\n * \\file\n**/\n#ifndef BOOST_SIMD_CONSTANT_CONSTANTS_NBMANTISSABITS_HPP_INCLUDED\n#define BOOST_SIMD_CONSTANT_CONSTANTS_NBMANTISSABITS_HPP_INCLUDED\n\n#include <boost/simd/include/functor.hpp>\n#include <boost/simd/sdk/meta/int_c.hpp>\n#include <boost/simd/sdk/constant/constant.hpp>\n\n/*!\n * \\ingroup boost_simd_constant\n * \\defgroup boost_simd_constant_nbmantissabits Nbmantissabits\n *\n * \\par Description\n * Constant Nbmantissabits, The number of mantissa bits of a floating point number,\n * i.e. 53 for double and 24 for float.\n * \\par\n * The value of this constant is type dependant. This means that for different\n * types it does not represent the same mathematical number.\n *\n * \\par Header file\n *\n * \\code\n * #include <nt2/include/functions/nbmantissabits.hpp>\n * \\endcode\n *\n *\n * \\synopsis\n *\n * \\code\n * namespace boost::simd\n * {\n *   template <class T,class A0>\n *     meta::call<tag::nbmantissabits_(A0)>::type\n *     Nbmantissabits();\n * }\n * \\endcode\n *\n *\n * \\param T template parameter of Nbmantissabits\n *\n * \\return type T value\n *\n *\n**/\n\nnamespace boost { namespace simd\n{\n  namespace tag\n  {\n    /*!\n     * \\brief Define the tag Nbmantissabits of functor Nbmantissabits\n     *        in namespace boost::simd::tag for toolbox boost.simd.constant\n    **/\n    struct Nbmantissabits : ext::pure_constant_<Nbmantissabits>\n    {\n      template<class Target, class Dummy=void>\n      struct  apply : meta::int_c < typename Target::type\n                                  , sizeof(typename Target::type)*CHAR_BIT\n                                  >\n      {};\n    };\n\n    template<class T, class Dummy>\n    struct  Nbmantissabits::apply<boost::dispatch::meta::single_<T>,Dummy>\n          : meta::int_c<boost::simd::int32_t,23> {};\n\n    template<class T, class Dummy>\n    struct  Nbmantissabits::apply<boost::dispatch::meta::double_<T>,Dummy>\n          : meta::int_c<boost::simd::int64_t,52> {};\n  }\n\n  BOOST_SIMD_CONSTANT_IMPLEMENTATION(boost::simd::tag::Nbmantissabits, Nbmantissabits)\n} }\n\n#include <boost/simd/sdk/constant/common.hpp>\n\n#endif\n", "meta": {"hexsha": "ec7c0258cfb8dfc80d8e95957f28fa07367592fe", "size": 2564, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/constant/include/boost/simd/constant/constants/nbmantissabits.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/constant/include/boost/simd/constant/constants/nbmantissabits.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/constant/include/boost/simd/constant/constants/nbmantissabits.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": 29.1363636364, "max_line_length": 86, "alphanum_fraction": 0.6205148206, "num_tokens": 660, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.4747449355220513}}
{"text": "/* boost random/exponential_distribution.hpp header file\r\n *\r\n * Copyright Jens Maurer 2000-2001\r\n * Copyright Steven Watanabe 2011\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 most recent version including documentation.\r\n *\r\n * $Id: exponential_distribution.hpp 71018 2011-04-05 21:27:52Z steven_watanabe $\r\n *\r\n * Revision history\r\n *  2001-02-18  moved to individual header files\r\n */\r\n\r\n#ifndef BOOST_RANDOM_EXPONENTIAL_DISTRIBUTION_HPP\r\n#define BOOST_RANDOM_EXPONENTIAL_DISTRIBUTION_HPP\r\n\r\n#include <boost/config/no_tr1/cmath.hpp>\r\n#include <iosfwd>\r\n#include <boost/assert.hpp>\r\n#include <boost/limits.hpp>\r\n#include <boost/random/detail/config.hpp>\r\n#include <boost/random/detail/operators.hpp>\r\n#include <boost/random/uniform_01.hpp>\r\n\r\nnamespace boost {\r\nnamespace random {\r\n\r\n/**\r\n * The exponential distribution is a model of \\random_distribution with\r\n * a single parameter lambda.\r\n *\r\n * It has \\f$\\displaystyle p(x) = \\lambda e^{-\\lambda x}\\f$\r\n */\r\ntemplate<class RealType = double>\r\nclass exponential_distribution\r\n{\r\npublic:\r\n    typedef RealType input_type;\r\n    typedef RealType result_type;\r\n\r\n    class param_type\r\n    {\r\n    public:\r\n\r\n        typedef exponential_distribution distribution_type;\r\n\r\n        /**\r\n         * Constructs parameters with a given lambda.\r\n         *\r\n         * Requires: lambda > 0\r\n         */\r\n        param_type(RealType lambda_arg = RealType(1.0))\r\n          : _lambda(lambda_arg) { BOOST_ASSERT(_lambda > RealType(0)); }\r\n\r\n        /** Returns the lambda parameter of the distribution. */\r\n        RealType lambda() const { return _lambda; }\r\n\r\n        /** Writes the parameters to a @c std::ostream. */\r\n        BOOST_RANDOM_DETAIL_OSTREAM_OPERATOR(os, param_type, parm)\r\n        {\r\n            os << parm._lambda;\r\n            return os;\r\n        }\r\n        \r\n        /** Reads the parameters from a @c std::istream. */\r\n        BOOST_RANDOM_DETAIL_ISTREAM_OPERATOR(is, param_type, parm)\r\n        {\r\n            is >> parm._lambda;\r\n            return is;\r\n        }\r\n\r\n        /** Returns true if the two sets of parameters are equal. */\r\n        BOOST_RANDOM_DETAIL_EQUALITY_OPERATOR(param_type, lhs, rhs)\r\n        { return lhs._lambda == rhs._lambda; }\r\n\r\n        /** Returns true if the two sets of parameters are different. */\r\n        BOOST_RANDOM_DETAIL_INEQUALITY_OPERATOR(param_type)\r\n\r\n    private:\r\n        RealType _lambda;\r\n    };\r\n\r\n    /**\r\n     * Constructs an exponential_distribution with a given lambda.\r\n     *\r\n     * Requires: lambda > 0\r\n     */\r\n    explicit exponential_distribution(RealType lambda_arg = RealType(1.0))\r\n      : _lambda(lambda_arg) { BOOST_ASSERT(_lambda > RealType(0)); }\r\n\r\n    /**\r\n     * Constructs an exponential_distribution from its parameters\r\n     */\r\n    explicit exponential_distribution(const param_type& parm)\r\n      : _lambda(parm.lambda()) {}\r\n\r\n    // compiler-generated copy ctor and assignment operator are fine\r\n\r\n    /** Returns the lambda parameter of the distribution. */\r\n    RealType lambda() const { return _lambda; }\r\n\r\n    /** Returns the smallest value that the distribution can produce. */\r\n    RealType min BOOST_PREVENT_MACRO_SUBSTITUTION () const\r\n    { return RealType(0); }\r\n    /** Returns the largest value that the distribution can produce. */\r\n    RealType max BOOST_PREVENT_MACRO_SUBSTITUTION () const\r\n    { return (std::numeric_limits<RealType>::infinity)(); }\r\n\r\n    /** Returns the parameters of the distribution. */\r\n    param_type param() const { return param_type(_lambda); }\r\n    /** Sets the parameters of the distribution. */\r\n    void param(const param_type& parm) { _lambda = parm.lambda(); }\r\n\r\n    /**\r\n     * Effects: Subsequent uses of the distribution do not depend\r\n     * on values produced by any engine prior to invoking reset.\r\n     */\r\n    void reset() { }\r\n\r\n    /**\r\n     * Returns a random variate distributed according to the\r\n     * exponential distribution.\r\n     */\r\n    template<class Engine>\r\n    result_type operator()(Engine& eng) const\r\n    { \r\n        using std::log;\r\n        return -result_type(1) /\r\n            _lambda * log(result_type(1)-uniform_01<RealType>()(eng));\r\n    }\r\n\r\n    /**\r\n     * Returns a random variate distributed according to the exponential\r\n     * distribution with parameters specified by param.\r\n     */\r\n    template<class Engine>\r\n    result_type operator()(Engine& eng, const param_type& parm) const\r\n    { \r\n        return exponential_distribution(parm)(eng);\r\n    }\r\n\r\n    /** Writes the distribution to a std::ostream. */\r\n    BOOST_RANDOM_DETAIL_OSTREAM_OPERATOR(os, exponential_distribution, ed)\r\n    {\r\n        os << ed._lambda;\r\n        return os;\r\n    }\r\n\r\n    /** Reads the distribution from a std::istream. */\r\n    BOOST_RANDOM_DETAIL_ISTREAM_OPERATOR(is, exponential_distribution, ed)\r\n    {\r\n        is >> ed._lambda;\r\n        return is;\r\n    }\r\n\r\n    /**\r\n     * Returns true iff the two distributions will produce identical\r\n     * sequences of values given equal generators.\r\n     */\r\n    BOOST_RANDOM_DETAIL_EQUALITY_OPERATOR(exponential_distribution, lhs, rhs)\r\n    { return lhs._lambda == rhs._lambda; }\r\n    \r\n    /**\r\n     * Returns true iff the two distributions will produce different\r\n     * sequences of values given equal generators.\r\n     */\r\n    BOOST_RANDOM_DETAIL_INEQUALITY_OPERATOR(exponential_distribution)\r\n\r\nprivate:\r\n    result_type _lambda;\r\n};\r\n\r\n} // namespace random\r\n\r\nusing random::exponential_distribution;\r\n\r\n} // namespace boost\r\n\r\n#endif // BOOST_RANDOM_EXPONENTIAL_DISTRIBUTION_HPP\r\n", "meta": {"hexsha": "5b59c8fde6606912cb9e32a199f7a218cd3bacab", "size": 5688, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/random/exponential_distribution.hpp", "max_stars_repo_name": "PXLVision/opengv", "max_stars_repo_head_hexsha": "e48f77da4db7b8cee36ec677ed4ff5c5354571bb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 460.0, "max_stars_repo_stars_event_min_datetime": "2016-01-13T12:49:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-20T04:10:40.000Z", "max_issues_repo_path": "master/core/third/boost/random/exponential_distribution.hpp", "max_issues_repo_name": "isuhao/klib", "max_issues_repo_head_hexsha": "a59837857689d0e60d3df6d2ebd12c3160efa794", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 197.0, "max_issues_repo_issues_event_min_datetime": "2017-07-06T16:53:59.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-31T17:57:51.000Z", "max_forks_repo_path": "master/core/third/boost/random/exponential_distribution.hpp", "max_forks_repo_name": "isuhao/klib", "max_forks_repo_head_hexsha": "a59837857689d0e60d3df6d2ebd12c3160efa794", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 148.0, "max_forks_repo_forks_event_min_datetime": "2016-01-17T03:16:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T12:20:36.000Z", "avg_line_length": 31.0819672131, "max_line_length": 82, "alphanum_fraction": 0.6517229255, "num_tokens": 1209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300449389326, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.47474493093460624}}
{"text": "/*\n dparallel_recursion: distributed parallel_recursion skeleton\n Copyright (C) 2015-2020 Millan A. Martinez, Basilio B. Fraguela, Jose C. Cabaleiro. Universidade da Coruna\n \n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n \n http://www.apache.org/licenses/LICENSE-2.0\n \n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*/\n\n///\n/// \\file     topsorts_dstack.cpp\n/// \\author   Millan A. Martinez  <millan.alvarez@udc.es>\n/// \\author   Basilio B. Fraguela <basilio.fraguela@udc.es>\n/// \\author   Jose C. Cabaleiro   <jc.cabaleiro@usc.es>\n///\n\n#include <cstdio>\n#include <cstdlib>\n#include <chrono>\n#include <vector>\n#include <numeric>\n#include <algorithm>\n#include <boost/serialization/vector.hpp>\n#include <dparallel_recursion/dparallel_stack_recursion.h>\n\nusing namespace dpr;\n\nint nthreads = 4;\nint *A = nullptr; /* holds acyclic digraph compatible with 1,2,...,n */\n\nstruct Problem {\n  \n  static int SZ;\n  \n  std::vector<int> value_;\n  std::vector<int> children_;\n\n  //If root is false, it generates the default empty problem []\n  //If root is true, it generates the root problem 1 2 3 ... SZ\n  Problem(const bool root = false) {\n    if (root) {\n      value_.resize(SZ);\n      std::iota(value_.begin(), value_.end(), 1);\n    }\n  }\n\n  // copy constructor\n  Problem(const std::vector<int>& v) :\n  value_(v)\n  { }\n  \n  //move constructor\n  Problem(std::vector<int>&& v) :\n  value_(std::move(v))\n  { }\n\n  /*\n  //print current problem\n  void print() const noexcept {\n    printf(\"[\");\n    for(const auto& v : value_) printf(\" %d\", v);\n    printf(\" ]\\n\");\n  }\n  */\n\n  bool empty() const noexcept { return value_.empty(); }\n\n  // Requires i in 0..(SZ-1)\n  Problem adj(const int i) const noexcept {\n    auto copy = value_;\n    std::swap(copy[i], copy[i+1]);\n    return copy;\n  }\n\n//  Problem f() const noexcept\n//  { int i = 1;\n//\n//    while( (i < SZ) && (value_[i-1] < value_[i]) ) {\n//      i++;\n//    }\n//\n//    if (i == SZ) {\n//      return Problem();\n//    } else {\n//      return adj(i - 1);\n//    }\n//  }\n\n  bool reverse(const int s, const int i) const noexcept {\n    return (i <= (s - 1)) || ( (i == (s + 1)) && (s <= (SZ-3)) && (value_[s] < value_[s+2]) );\n  }\n  \n  void fill_nchildren() {\n    if (!empty()) { //dismiss empty problems\n      // findindex\n      int idx;\n      for(idx = 0; (idx < (SZ-1)) && (value_[idx] < value_[idx+1]); idx++);\n      for (int i = 0; i < (SZ-1); i++) {\n        if(A[value_[i] * SZ + value_[i+1] - SZ - 1] != 1) {\n          if (reverse(idx, i)) {\n            children_.push_back(i);\n          }\n        }\n      }\n    }\n  }\n\n//  void fill_nchildren() {\n//    if (!empty()) { //dismiss empty problems\n//      for (int i = 0; i < (SZ-1); i++) { // implements \"reverse\"\n//        if(A[value_[i] * SZ + value_[i+1] - SZ - 1] != 1) {\n//          const auto w = adj(i); // This problem cannot have w == null/empty\n//          if (value_ == w.f().value_) {\n//            children_.push_back(i);\n//          }\n//        }\n//      }\n//    }\n//  }\n\n  // Generate the i-th child problem, i in [0..(nchildren()-1)]\n  // Does not test whether that child should exist!\n  Problem child(const int i) const noexcept { return adj(children_[i]); }\n\n  size_t nchildren() const noexcept { return children_.size(); }\n\n  template<typename Archive>\n  void serialize(Archive &ar, const unsigned int) {\n    ar & value_ & children_;\n  }\n\n};\n\n\nint Problem::SZ = 9;\n\nstruct MyInfo : public Arity<UNKNOWN> {\n  \n  static bool is_base(const Problem& p) { return !p.nchildren(); }\n  \n  static int num_children(const Problem& p) { return p.nchildren(); }\n\n  static Problem child(int i, const Problem& p) { return p.child(i); }\n\n  //static bool do_parallel(const Problem& p) { ... }\n};\n\n\nstruct MyBody : public EmptyBody<Problem, size_t, true> {\n  \n  static void pre(Problem& p) { p.fill_nchildren(); }\n\n  static size_t base(const Problem& p) { return 1; }\n  \n  static size_t non_base(const Problem& p) { return base(p); }\n\n//  static size_t post(const Problem& p, const size_t* v) {\n//    return std::accumulate(v, v + p.nchildren(), (size_t)1);\n//  }\n\n  static void post(const size_t& r, size_t& rr) {\n    rr += r;\n  }\n  \n};\n\n//BOOST_IS_BITWISE_SERIALIZABLE(Problem);\n\nint main(int argc, char** argv)\n{\n  int rank;\n  int nprocs;\n  int chunkSize = 4;\n  int chunksToSteal = dpr::CHUNKS_TO_STEAL_DEFAULT;\n  unsigned int pollingInterval = dpr::POLLING_INTERVAL_DEFAULT;\n  int stackSize = 100;\n  int threads_request_policy = dpr::THREAD_MPI_STEAL_POLICY_DEFAULT;\n  int mpi_workrequest_limits = dpr::MPI_WORKREQUEST_LIMITS_DEFAULT;\n  int trp_predict_workcount = dpr::TRP_PREDICT_WORKCOUNT_DEFAULT;\n  int partitioner = 0;\n  int m;\n\n  if (getenv(\"OMP_NUM_THREADS\"))\n    nthreads = atoi(getenv(\"OMP_NUM_THREADS\"));\n  \n  if (argc > 1) {\n    chunkSize = atoi(argv[1]);\n  }\n\n  if (argc > 2) {\n    chunksToSteal = atoi(argv[2]);\n  }\n\n  if (argc > 3) {\n    pollingInterval = atoi(argv[3]);\n  }\n\n  if (argc > 4) {\n    threads_request_policy = atoi(argv[4]);\n  }\n\n  if (argc > 5) {\n    stackSize = atoi(argv[5]);\n  }\n\n  if (argc > 6) {\n    partitioner = atoi(argv[6]);\n  }\n\n  if (argc > 7) {\n    mpi_workrequest_limits = atoi(argv[7]);\n  }\n\n  if (argc > 8) {\n    trp_predict_workcount = atoi(argv[8]);\n  }\n\n  dpr_stack_init(argc, argv, nprocs, rank, nthreads, chunksToSteal, pollingInterval, stackSize, threads_request_policy, mpi_workrequest_limits, trp_predict_workcount);\n\n  if (rank == 0) {\n    printf(\"\\nEnter number of vertices and edges:\");\n\n    scanf(\"%d %d\", &Problem::SZ, &m);\n    MPI_Bcast(&Problem::SZ, 1, MPI_INT, 0, MPI_COMM_WORLD);\n    MPI_Bcast(&m, 1, MPI_INT, 0, MPI_COMM_WORLD);\n    printf(\"\\nEnter %d edge(s) as pairs i j, i<j : \\n\", m);\n    //printf(\"%d %d\\n\", Problem::SZ, m);\n    A = (int *)calloc(Problem::SZ * Problem::SZ, sizeof(int));\n\n    for(int k=1; k<=m; k++) {\n      int i, j;\n      scanf(\"%d %d\", &i, &j);\n      MPI_Bcast(&i, 1, MPI_INT, 0, MPI_COMM_WORLD);\n      MPI_Bcast(&j, 1, MPI_INT, 0, MPI_COMM_WORLD);\n      if (i >= j) {\n        printf (\"\\nEdge must have form i<j\");\n        return 0;\n      }\n      A[(i - 1) * Problem::SZ + (j - 1)] = 1;\n      //printf(\"%d %d\\n\", i, j);\n    }\n\n    printf(\"Nprocs=%d threads=%d sz=%d chunkSize=%d stackSize=%d chunksToSteal=%d pollingI=%d trp=%d partitioner=%d mpiWrLimits=%d trpPredWc=%d\\n\", nprocs, nthreads, Problem::SZ, chunkSize, stackSize, chunksToSteal, pollingInterval, threads_request_policy, partitioner, mpi_workrequest_limits, trp_predict_workcount);\n  } else {\n    MPI_Bcast(&Problem::SZ, 1, MPI_INT, 0, MPI_COMM_WORLD);\n    MPI_Bcast(&m, 1, MPI_INT, 0, MPI_COMM_WORLD);\n\n    A = (int *)calloc(Problem::SZ * Problem::SZ, sizeof(int));\n\n    for(int k=1; k<=m; k++) {\n      int i, j;\n      MPI_Bcast(&i, 1, MPI_INT, 0, MPI_COMM_WORLD);\n      MPI_Bcast(&j, 1, MPI_INT, 0, MPI_COMM_WORLD);\n      if (i >= j) {\n        return 0;\n      }\n      A[(i - 1) * Problem::SZ + (j - 1)] = 1;\n      //printf(\"%d %d\\n\", i, j);\n    }\n  }\n\n  Problem input(true);\n\n  const auto t0 = std::chrono::steady_clock::now();\n\n  size_t result;\n  if (partitioner == 2) {\n    result = dparallel_stack_recursion<size_t> (input, MyInfo(), MyBody(), chunkSize, dpr::partitioner::automatic(), dpr::ReplicatedInput);\n  } else {\n    result = dparallel_stack_recursion<size_t> (input, MyInfo(), MyBody(), chunkSize, dpr::partitioner::simple(), dpr::ReplicatedInput);\n  }\n  \n  const auto t1 = std::chrono::steady_clock::now();\n  double time = std::chrono::duration<double>(t1 - t0).count();\n\n  if (rank == 0) {\n    printf(\"Result: %zu\\nTime: %lf\\n\", result, time);\n  }\n\n  free(A);\n\n  MPI_Finalize();\n\n  return 0;\n}\n", "meta": {"hexsha": "241f4e1807a1812d70eb2a16c56be3b33f25cfb4", "size": 7936, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "benchmarks/topsorts_dstack.cpp", "max_stars_repo_name": "fraguela/dparallel_recursion", "max_stars_repo_head_hexsha": "30050242b7d01766fee5a3107c7a79db5c512d9e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2022-01-01T07:48:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T14:01:35.000Z", "max_issues_repo_path": "benchmarks/topsorts_dstack.cpp", "max_issues_repo_name": "fraguela/dparallel_recursion", "max_issues_repo_head_hexsha": "30050242b7d01766fee5a3107c7a79db5c512d9e", "max_issues_repo_licenses": ["Apache-2.0"], "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/topsorts_dstack.cpp", "max_forks_repo_name": "fraguela/dparallel_recursion", "max_forks_repo_head_hexsha": "30050242b7d01766fee5a3107c7a79db5c512d9e", "max_forks_repo_licenses": ["Apache-2.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.9931972789, "max_line_length": 317, "alphanum_fraction": 0.6101310484, "num_tokens": 2409, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757645879592642, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.4747449305559152}}
{"text": "#pragma once\n#include <cmath>\n#include <algorithm>\n#include <limits>\n#include <Eigen/Geometry>\n#include <boost/optional.hpp>\n#include \"BaryCoordT.hh\"\n#include \"util.hh\"\n#include \"RangeAdaptor.hh\"\n\nnamespace kt84 {\n    namespace eigen_util {\n        template <typename TMatrix>\n        inline auto range_elements(TMatrix& m) -> RangeAdaptor<decltype(m.data())> {\n            return make_RangeAdaptor(m.data(), m.data() + m.size());\n        }\n        template <typename TVector, typename TScalar>\n        inline void push_back(TVector& v, TScalar s) {\n            int n = v.size();\n            v.conservativeResize(n + 1);\n            v[n] = s;\n        }\n        template <typename TVector>\n        inline void erase_at(TVector& v, int index) {\n            int n = v.size();\n            auto tmp(v);\n            v.resize(n - 1);\n            v << tmp.head(index), tmp.tail(n - 1 - index);\n        }\n        template <typename TVector>\n        inline void swap_xy(TVector& v) {\n            std::swap(v.x(), v.y());\n        }\n        template <typename TAlignedBox>\n        inline void bbox_add_margin(TAlignedBox& bbox, double ratio, bool is_margin_square = false) {\n            if (is_margin_square) {\n                typedef typename TAlignedBox::VectorType VectorType;\n                VectorType margin = VectorType::Ones();\n                margin *= bbox.diagonal().norm() * ratio;\n                bbox.max() += margin;\n                bbox.min() -= margin;\n            } else {\n                bbox.extend((1 + ratio) * bbox.max() - ratio * bbox.min());\n                bbox.extend((1 + ratio) * bbox.min() - ratio * bbox.max());\n            }\n        }\n        inline Eigen::Vector2d bbox_bilinear(const Eigen::AlignedBox2d& bbox, double tx, double ty) {            // (0, 0) corresponds to bbox.min, (1, 1) corresponds to bbox.max\n            double x = (1 - tx) * bbox.min().x() + tx * bbox.max().x();\n            double y = (1 - ty) * bbox.min().y() + ty * bbox.max().x();\n            return Eigen::Vector2d(x, y);\n        }\n        inline Eigen::Vector3d bbox_trilinear(const Eigen::AlignedBox3d& bbox, double tx, double ty, double tz) {            // (0, 0, 0) corresponds to bbox.min, (1, 1, 1) corresponds to bbox.max\n            double x = (1 - tx) * bbox.min().x() + tx * bbox.max().x();\n            double y = (1 - ty) * bbox.min().y() + ty * bbox.max().x();\n            double z = (1 - tz) * bbox.min().z() + tz * bbox.max().z();\n            return Eigen::Vector3d(x, y, z);\n        }\n        inline Eigen::Vector3d orientation_color(Eigen::Vector3d d) {\n            auto cx = d.x() > 0 ? Eigen::Vector3d(1, 0, 0) : Eigen::Vector3d(0, 1, 1);\n            auto cy = d.y() > 0 ? Eigen::Vector3d(0, 1, 0) : Eigen::Vector3d(1, 0, 1);\n            auto cz = d.z() > 0 ? Eigen::Vector3d(0, 0, 1) : Eigen::Vector3d(1, 1, 0);\n            d /= std::abs<double>(d.sum());\n            d = d.cwiseAbs();\n            return d.x() * cx + d.y() * cy + d.z() * cz;\n        }\n        inline Eigen::Vector3d heat_color(double t) {\n            // t     | 0    | 0.25 | 0.5   | 0.75   | 1   |\n            // color | blue | cyan | green | yellow | red |\n            t = util::clamp(t, 0., 1.);\n            Eigen::Vector3d colors[5] = {\n                Eigen::Vector3d(0, 0, 1),\n                Eigen::Vector3d(0, 1, 1),\n                Eigen::Vector3d(0, 1, 0),\n                Eigen::Vector3d(1, 1, 0),\n                Eigen::Vector3d(1, 0, 0)\n            };\n            int i = t < 0.25 ? 0 : t < 0.5 ? 1 : t < 0.75 ? 2 : 3;\n            double s = (t - i * 0.25) * 4;\n            return (1 - s) * colors[i] + s * colors[i + 1];\n        }\n        template <int N>\n        inline int closest_axis(const Eigen::Matrix<double, N, 1, 0, N, 1>& v) {\n            int result = -1;\n            double v_abs_max = 0;\n            for (int i = 0; i < N; ++i) {\n                double v_abs = std::abs(v[i]);\n                if (v_abs_max < v_abs) {\n                    v_abs_max = v_abs;\n                    result = i;\n                }\n            }\n            return result;\n        }\n        inline Eigen::Vector2d compute_gradient(const Eigen::Vector2d& x0, const Eigen::Vector2d& x1, const Eigen::Vector2d& x2, double y0, double y1, double y2) {\n            /*\n                a.x0 + b = y0\n                a.x1 + b = y1\n                a.x2 + b = y2\n                -->\n                a.(x1 - x0) = y1 - y0\n                a.(x2 - x0) = y2 - y0\n                -->\n                |(x1 - x0)^T| * a = |y1 - y0|\n                |(x2 - x0)^T|       |y2 - y0|\n            */\n            Eigen::Matrix2d A;\n            A << Eigen::RowVector2d(x1 - x0),\n                 Eigen::RowVector2d(x2 - x0);\n            return A.inverse() * Eigen::Vector2d(y1 - y0, y2 - y0);\n        }\n        inline Eigen::Vector3d compute_gradient(const Eigen::Vector3d& x0, const Eigen::Vector3d& x1, const Eigen::Vector3d& x2, const Eigen::Vector3d& x3, double y0, double y1, double y2, double y3) {\n            /*\n                a.x0 + b = y0\n                a.x1 + b = y1\n                a.x2 + b = y2\n                a.x3 + b = y3\n                -->\n                a.(x1 - x0) = y1 - y0\n                a.(x2 - x0) = y2 - y0\n                a.(x3 - x0) = y3 - y0\n                -->\n                |(x1 - x0)^T|       |y1 - y0|\n                |(x2 - x0)^T| * a = |y2 - y0|\n                |(x3 - x0)^T|       |y3 - y0|\n            */\n            Eigen::Matrix3d A;\n            A << Eigen::RowVector3d(x1 - x0),\n                 Eigen::RowVector3d(x2 - x0),\n                 Eigen::RowVector3d(x3 - x0);\n            return A.inverse() * Eigen::Vector3d(y1 - y0, y2 - y0, y3 - y0);\n        }\n        inline Eigen::Vector3d compute_gradient(const Eigen::Vector3d& x0, const Eigen::Vector3d& x1, const Eigen::Vector3d& x2, double y0, double y1, double y2) {\n            /*\n                Compute gradient restricted to the tangent vectors on the triangle x0-x1-x2.\n                a.x0 + b = y0\n                a.x1 + b = y1\n                a.x2 + b = y2\n                a.n      = 0                (n: normal)\n                -->\n                a.(x1 - x0) = y1 - y0\n                a.(x2 - x0) = y2 - y0\n                a.n         = 0\n                -->\n                |(x1 - x0)^T|       |y1 - y0|\n                |(x2 - x0)^T| * a = |y2 - y0|\n                | n       ^T|       |0      |\n            */\n            Eigen::Matrix3d A;\n            A << Eigen::RowVector3d(x1 - x0),\n                 Eigen::RowVector3d(x2 - x0),\n                 Eigen::RowVector3d((x1 - x0).cross(x2 - x0));\n            return A.inverse() * Eigen::Vector3d(y1 - y0, y2 - y0, 0);\n        }\n        inline Eigen::Vector2d rotate90(const Eigen::Vector2d& xy) { return Eigen::Vector2d(-xy[1], xy[0]); }\n        inline double angle(const Eigen::Vector2d& d0, const Eigen::Vector2d& d1) { return std::atan2(rotate90(d0).dot(d1), d0.dot(d1)); }\n        inline double angle(const Eigen::Vector3d& d0, const Eigen::Vector3d& d1) { return std::acos(d0.normalized().dot(d1.normalized())); }\n        template <class T>\n        inline void orthonormalize(const T& unit, T& p) {\n            p -= unit.dot(p) * unit;\n            p.normalize();\n        }\n        template <class T>\n        inline bool project_to_line(const T& line_v0, const T& line_v1, const T& point, Eigen::Vector2d& t) {\n            /*\n                x0 := line_v0\n                x1 := line_v1\n                y := point\n                compute t (which sums up to one) such that\n                    | t[0] * x0 + t[1] * x1 - y |^2\n                is minimized.\n                ---------------------\n                u := t[1]\n                (1 - u) * x0 + u * x1 =~ y\n                u =~ (y - x0).dot(x1 - x0) / (x1 - x0).squaredNorm()\n            */\n            \n            double r = (line_v1 - line_v0).squaredNorm();\n            if (r == 0)\n                // degenerate\n                return false;\n            \n            t[1] = (point - line_v0).dot(line_v1 - line_v0) / r;\n            t[0] = 1 - t[1];\n            \n            return true;\n        }\n        \n        template <class T>\n        inline bool project_to_triangle(const T& triangle_v0, const T& triangle_v1, const T& triangle_v2, const T& point, Eigen::Vector3d& t) {\n            /*\n                x0 := triangle_v0\n                x1 := triangle_v1\n                x2 := triangle_v2\n                y := point\n                compute t (which sums up to one) such that\n                    | t[0] * x0 + t[1] * x1 + t[2] * x2 - y |^2\n                is minimized.\n                ---------------------\n                u := t[1]\n                v := t[2]\n                (1 - u - v) * x0 + u * x1 + v * x2 =~ y\n                (x1-x0, x2-x0) * |u| =~ y-x0\n                                 |v|\n                |u| =~ |(x1-x0).squaredNorm(), (x1-x0).dot(x2-x0)   |^-1 * | (x1-x0).dot(y-x0) |\n                |v|    |(x1-x0).dot(x2-x0)   , (x2-x0).squaredNorm()|      | (x2-x0).dot(y-x0) |\n            */\n            \n            T d01 = triangle_v1 - triangle_v0;\n            T d02 = triangle_v2 - triangle_v0;\n            T d0p = point       - triangle_v0;\n            Eigen::Matrix2d M;\n            M <<\n                d01.squaredNorm(), d01.dot(d02),\n                d01.dot(d02)     , d02.squaredNorm();\n            if (M.determinant() == 0)\n                // degenerate\n                return false;\n            \n            Eigen::Vector2d b;\n            b <<\n                d01.dot(d0p),\n                d02.dot(d0p);\n            \n            Eigen::Vector2d uv = ((Eigen::Matrix2d)M.inverse()) * b;\n            \n            t[0] = 1 - uv[0] - uv[1];\n            t[1] = uv[0];\n            t[2] = uv[1];\n            \n            return true;\n        }\n        \n        template <class T>\n        inline boost::optional<double> distance_to_line(const T& line_v0, const T& line_v1, const T& point, bool do_clamp = false) {\n            Eigen::Vector2d t;\n            if (!project_to_line(line_v0, line_v1, point, t))\n                // degenrate case\n                return boost::none;\n            \n            if (do_clamp) {\n                t[0] = util::clamp(t[0], 0.0, 1.0);\n                t[1] = 1 - t[0];\n            }\n            \n            return (t[0] * line_v0 + t[1] * line_v1 - point).norm();\n        }\n        \n        template <class T>\n        inline boost::optional<double> distance_to_triangle(const T& triangle_v0, const T& triangle_v1, const T& triangle_v2, const T& point, bool do_clamp = false) {\n            Eigen::Vector3d t;\n            if (!project_to_triangle(triangle_v0, triangle_v1, triangle_v2, point, t))\n                // degenrate case\n                return boost::none;\n            \n            if (do_clamp && t[0] < 0 || t[1] < 0 || t[2] < 0) {\n                double d0 = *distance_to_line(triangle_v0, triangle_v1, point, true);\n                double d1 = *distance_to_line(triangle_v1, triangle_v2, point, true);\n                double d2 = *distance_to_line(triangle_v2, triangle_v0, point, true);\n                return util::min(d0, d1, d2);\n            }\n            \n            return (t[0] * triangle_v0 + t[1] * triangle_v1 + t[2] * triangle_v2 - point).norm();\n        }\n        inline double triangle_area(const Eigen::Vector2d& v0, const Eigen::Vector2d& v1, const Eigen::Vector2d& v2) {\n            Eigen::Vector2d d1 = v1 - v0;\n            Eigen::Vector2d d2 = v2 - v0;\n            return d1.x() * d2.y() - d1.y() * d2.x();\n        }\n        inline double triangle_area(const Eigen::Vector3d& v0, const Eigen::Vector3d& v1, const Eigen::Vector3d& v2) {\n            Eigen::Vector3d d1 = v1 - v0;\n            Eigen::Vector3d d2 = v2 - v0;\n            return d1.cross(d2).norm() / 2;\n        }\n        template <class T>\n        inline bool intersection(const T& line0_p0, const T& line0_p1, const T& line1_p0, const T& line1_p1, double& line0_coordinate, double& line1_coordinate) {\n            /*\n                notation:\n                    v0 := line0_p0\n                    v1 := line0_p1\n                    w0 := line1_p0\n                    w1 := line1_p1\n                    s  := line0_coordinate\n                    t  := line1_coordinate\n                seek for (s, t) which minimizes:\n                    |(1 - s) * v0 + s * v1 - (1 - t) * w0 - t * w1|^2\n                least square sense:\n                    | v1-v0, -w1+w0 | * |s| =~ -v0+w0\n                                        |t|\n            */\n            T d0 = line0_p1 - line0_p0;\n            T d1 = line1_p1 - line1_p0;\n            T e  = line1_p0 - line0_p0;\n            double d0d0 = d0.squaredNorm();\n            double d0d1 = d0.dot(d1);\n            double d1d1 = d1.squaredNorm();\n            Eigen::Matrix2d A;\n            A <<\n                d0d0, -d0d1,\n                -d0d1, d1d1;\n            \n            if (A.determinant() == 0)\n                // two lines are parallel\n                return false;\n            \n            Eigen::Vector2d b(d0.dot(e), -d1.dot(e));\n            Eigen::Vector2d st = ((Eigen::Matrix2d)A.inverse()) * b;\n            \n            line0_coordinate = st[0];\n            line1_coordinate = st[1];\n            return true;\n        }\n        template <typename T>\n        inline std::vector<T> eigen_vectorx_to_std_vector(const Eigen::Matrix<T, -1, 1>& eigen_vectorx) {\n            int n = eigen_vectorx.rows();\n            std::vector<T> result(n);\n            for (int i = 0; i < n; ++i)\n                result[i] = eigen_vectorx[i];\n            return result;\n        }\n        template <typename T>\n        inline Eigen::Matrix<T, -1, 1> std_vector_to_eigen_vectorx(const std::vector<T>& std_vector) {\n            int n = std_vector.size();\n            Eigen::Matrix<T, -1, 1> result = Eigen::Matrix<T, -1, 1>::Zero(n);\n            for (int i = 0; i < n; ++i)\n                result[i] = std_vector[i];\n            return result;\n        }\n        template <typename TVector>\n        inline int max_axis(const TVector& v) {\n            int index_max = -1;\n            typename TVector::Scalar value_max = -std::numeric_limits<typename TVector::Scalar>::max();\n            for (int i = 0; i < v.size(); ++i) {\n                if (value_max < v[i]) {\n                    value_max = v[i];\n                    index_max = i;\n                }\n            }\n            return index_max;\n        }\n        template <typename TVector>\n        inline int min_axis(const TVector& v) {\n            int index_min = -1;\n            typename TVector::Scalar value_min = std::numeric_limits<typename TVector::Scalar>::max();\n            for (int i = 0; i < v.size(); ++i) {\n                if (value_min < v[i]) {\n                    value_min = v[i];\n                    index_min = i;\n                }\n            }\n            return index_min;\n        }\n        template <typename TVector>\n        inline void rotate(TVector& v) {\n            TVector tmp(v);\n            int n = v.size();\n            for (int i = 0; i < n; ++i)\n                v[i] = tmp[(i + 1) % n];\n        }\n        template <typename TVector>\n        inline void reverse(TVector& v) {\n            TVector tmp(v);\n            int n = v.size();\n            for (int i = 0; i < n; ++i)\n                v[i] = tmp[n - 1 - i];\n        }\n    }\n}\n", "meta": {"hexsha": "67907874154cee417223eb3a7a6c462d7f8066d8", "size": 15281, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/kt84/eigen_util.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/eigen_util.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/eigen_util.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": 41.5244565217, "max_line_length": 201, "alphanum_fraction": 0.4404162031, "num_tokens": 4355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757645879592641, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.4747449305559151}}
{"text": "#ifndef _PARSER_H_\n#define _PARSER_H_\n\n#include <boost/regex.hpp>\n#include <string>\n#include <unordered_map>\n#include <vector>\nclass Parser {\n  using operator_map = std::unordered_map<int, std::vector<char>>;\n\n public:\n  int max_op_m;\n  boost::regex re_number_m, re_operator_m;\n  std::unordered_map<int, boost::regex> re_operands_m;\n\n  Parser(operator_map m = operator_map({{0, {'+', '*'}}}), int max_op = 0,\n         std::string num = \"\\\\d+\", std::string op = \"[^\\\\d]\");\n\n  int64_t operate(const int64_t &a, const int64_t &b, const char &op);\n\n  std::string extract_parenthesis(std::string &line);\n\n  int64_t compute_expression(std::string line);\n\n  int64_t evaluate(std::string line);\n};\n\n#endif", "meta": {"hexsha": "5bb12a3da5a38914bbe65b1a21fbe3ea4bf534f9", "size": 697, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "2020/day18/cpp/include/parser.hpp", "max_stars_repo_name": "ivobatkovic/advent-of-code", "max_stars_repo_head_hexsha": "e43489bcd2307f0f3ac8b0ec4e850f0a201f9944", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-12-14T16:24:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-06T16:40:13.000Z", "max_issues_repo_path": "2020/day18/cpp/include/parser.hpp", "max_issues_repo_name": "ivobatkovic/advent-of-code", "max_issues_repo_head_hexsha": "e43489bcd2307f0f3ac8b0ec4e850f0a201f9944", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2019-12-03T14:18:13.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-03T08:29:32.000Z", "max_forks_repo_path": "2020/day18/cpp/include/parser.hpp", "max_forks_repo_name": "ivobatkovic/advent-of-code", "max_forks_repo_head_hexsha": "e43489bcd2307f0f3ac8b0ec4e850f0a201f9944", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-12-06T07:25:57.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-08T12:42:37.000Z", "avg_line_length": 24.8928571429, "max_line_length": 74, "alphanum_fraction": 0.6901004304, "num_tokens": 193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.6548947425132314, "lm_q1q2_score": 0.4747137328723166}}
{"text": "///\n/// \\file vandermonde_matrix.hpp\n///\n#ifndef MXPFIT_VANDERMONDE_MATRIX_HPP\n#define MXPFIT_VANDERMONDE_MATRIX_HPP\n\n#include <cassert>\n\n#include <Eigen/Core>\n\n#include <mxpfit/matrix_free_gemv.hpp>\n\nnamespace mxpfit\n{\n\n///\n/// ### VandermondeMatrix\n///\n/// Expression of a rectangular column Vandermonde matrix.\n///\n/// \\tparam T  Scalar type of matrix elements\n///\n/// This class represents a \\f$ m \\times n \\f$ column Vandermonde matrix of\n/// the form\n///\n/// \\f[\n///   \\bm{V}(\\bm{t}) = \\left[ \\begin{array}{cccc}\n///     1         & 1         & \\dots  & 1         \\\\\n///     t_{1}^{}  & t_{2}^{}  & \\dots  & t_{n}^{}  \\\\\n///     \\vdots    & \\vdots    & \\ddots & \\vdots    \\\\\n///     t_{1}^{m} & t_{2}^{m} & \\dots  & t_{n}^{m} \\\\\n///   \\end{array} \\right].\n/// \\f]\n///\n/// This class represents a Vandermonde matrix expression from the given number\n/// of rows, \\f$ m, \\f$ and a vector expression for the coefficients of the\n/// second row, \\f$(t_1,t_2,\\dots,t_n).\\f$ If the given vector expression is\n/// l-value, this class wraps the existing vector expression, otherwise storage\n/// for coefficients are allocated.\n///\n/// This class also provides the interface for matrix-vector multiplication\n/// compatible to `MatrixFreeGEMV`. For this purpose, the class also allocate\n/// internal a vector of size \\f$n\\f$ as working space.\n///\n\ntemplate <typename T>\nclass VandermondeMatrix\n{\npublic:\n    using Scalar          = T;\n    using RealScalar      = typename Eigen::NumTraits<T>::Real;\n    using StorageIndex    = Eigen::Index;\n    using Index           = Eigen::Index;\n    using CoeffsVector    = Eigen::Matrix<Scalar, Eigen::Dynamic, 1>;\n    using CoeffsVectorRef = Eigen::Ref<const CoeffsVector>;\n    using PlainObject = Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>;\n\nprivate:\n    Index m_rows;\n    mutable CoeffsVector m_workspace;\n    CoeffsVectorRef m_coeffs;\n\npublic:\n    /// Default constructor: create an empty matrix\n    VandermondeMatrix()\n        : m_rows(),\n          m_workspace(),\n          m_coeffs(m_workspace) // need to initialize Eigen::Ref object\n    {\n    }\n\n    ///\n    /// Create a Vandermonde matrix from number of rows and coefficients of the\n    /// first row.\n    ///\n    template <typename InputType>\n    VandermondeMatrix(Index nrows, const InputType& coeffs)\n        : m_rows(nrows), m_workspace(coeffs.size()), m_coeffs(coeffs)\n    {\n        EIGEN_STATIC_ASSERT_VECTOR_ONLY(InputType);\n    }\n\n    /// Copy constructor\n    VandermondeMatrix(const VandermondeMatrix& other)\n        : m_rows(other.m_rows),\n          m_workspace(other.m_workspace),\n          m_coeffs(other.m_coeffs)\n    {\n    }\n\n    /// Default destructor\n    ~VandermondeMatrix()\n    {\n    }\n\n    /// Delete assignment operator as a consequence that Eigen::Ref is\n    /// non-assignable\n    VandermondeMatrix& operator=(const VandermondeMatrix& other) = delete;\n\n    /// \\return the number of rows\n    Index rows() const\n    {\n        return m_rows;\n    }\n\n    /// \\return the number of columns\n    Index cols() const\n    {\n        return m_coeffs.size();\n    }\n\n    /// Set elements of Vandermonde matrix\n    template <typename Derived>\n    void setMatrix(Index nrows, const Eigen::EigenBase<Derived>& coeffs)\n    {\n        EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived);\n        m_rows = nrows;\n        if (m_workspace.size() != coeffs.size())\n        {\n            m_workspace.resize(coeffs.size());\n        }\n        m_coeffs.~CoeffsVectorRef();\n        ::new (&m_coeffs) CoeffsVectorRef(coeffs.derived());\n    }\n\n    void setMatrix(Index nrows, const CoeffsVectorRef& coeffs)\n    {\n        m_rows = nrows;\n        if (&(coeffs.derived()) != &m_coeffs)\n        {\n            if (m_workspace.size() != coeffs.size())\n            {\n                m_workspace.resize(coeffs.size());\n            }\n            m_coeffs.~CoeffsVectorRef();\n            ::new (&m_coeffs) CoeffsVectorRef(coeffs);\n        }\n    }\n\n    ///\n    /// \\return A const reference to the coefficients of the second row\n    ///\n    const CoeffsVectorRef& coeffs() const\n    {\n        return m_coeffs;\n    }\n\n    ///\n    /// \\return The same Vandermonde matrix in dense form.\n    ///\n    PlainObject toDenseMatrix() const\n    {\n        PlainObject ret(rows(), cols());\n        for (Index j = 0; j < cols(); ++j)\n        {\n            auto x = m_coeffs(j);\n            auto v = Scalar(1);\n            ret(0, j) = v;\n            for (Index i = 1; i < rows(); ++i)\n            {\n                v *= x;\n                ret(i, j) = v;\n            }\n        }\n        return ret;\n    }\n\n    /// Compute matrix-vector product of the form `dst += alpha * A * rhs`\n    template <typename Dest, typename RHS>\n    void apply(Dest& dst, const Eigen::MatrixBase<RHS>& rhs, Scalar alpha) const\n    {\n        apply_impl(dst, rhs, alpha, coeffs());\n    }\n\n    /// Compute matrix-vector product of the form\n    /// `dst += alpha * A.conjugate() * rhs`\n    template <typename Dest, typename RHS>\n    void applyConjugate(Dest& dst, const Eigen::MatrixBase<RHS>& rhs,\n                        Scalar alpha) const\n    {\n        apply_impl(dst, rhs, alpha, coeffs().conjugate());\n    }\n\n    /// Compute matrix-vector product of the form\n    /// `dst += alpha * A.transpose() * rhs`\n    template <typename Dest, typename RHS>\n    void applyTranspose(Dest& dst, const Eigen::MatrixBase<RHS>& rhs,\n                        Scalar alpha) const\n    {\n        apply_transpose_impl(dst, rhs, alpha, coeffs());\n    }\n\n    /// Compute matrix-vector product of the form\n    /// `dst += alpha * A.adjoint() * rhs`\n    template <typename Dest, typename RHS>\n    void applyAdjoint(Dest& dst, const Eigen::MatrixBase<RHS>& rhs,\n                      Scalar alpha) const\n    {\n        apply_transpose_impl(dst, rhs, alpha, coeffs().conjugate());\n    }\n\nprivate:\n    template <typename Dest, typename RHS, typename CoeffsV>\n    void apply_impl(Dest& dst, const Eigen::MatrixBase<RHS>& rhs, Scalar alpha,\n                    const Eigen::MatrixBase<CoeffsV>& coeffs) const\n    {\n        EIGEN_STATIC_ASSERT_VECTOR_ONLY(Dest);\n        EIGEN_STATIC_ASSERT_VECTOR_ONLY(RHS);\n\n        assert(dst.size() == rows());\n        assert(rhs.size() == cols());\n\n        if (alpha == Scalar(/*zero*/))\n        {\n            return;\n        }\n\n        m_workspace = rhs.derived();\n\n        dst(0) += alpha * m_workspace.sum();\n        for (Index i = 1; i < rows(); ++i)\n        {\n            m_workspace.array() *= coeffs.array();\n            dst(i) += alpha * m_workspace.sum();\n        }\n    }\n\n    template <typename Dest, typename RHS, typename CoeffsV>\n    void apply_transpose_impl(Dest& dst, const Eigen::MatrixBase<RHS>& rhs,\n                              Scalar alpha,\n                              const Eigen::MatrixBase<CoeffsV>& coeffs) const\n    {\n        EIGEN_STATIC_ASSERT_VECTOR_ONLY(Dest);\n        EIGEN_STATIC_ASSERT_VECTOR_ONLY(RHS);\n\n        assert(dst.size() == cols());\n        assert(rhs.size() == rows());\n\n        for (Index i = 0; i < cols(); ++i)\n        {\n            auto x = coeffs(i);\n            // Evaluate polynomial using Honer's method\n            auto s = Scalar();\n            for (Index j = 0; j < rows(); ++j)\n            {\n                s = s * x + rhs(rows() - j - 1);\n            }\n\n            dst(i) += alpha * s;\n        }\n    }\n};\n\n} // namespace mxpfit\n\n#endif /* MXPFIT_VANDERMONDE_MATRIX_HPP */\n", "meta": {"hexsha": "11255a54d66e4a65b972664094458aa21973ce04", "size": 7374, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mxpfit/vandermonde_matrix.hpp", "max_stars_repo_name": "hydeik/mxpfit", "max_stars_repo_head_hexsha": "a18621b191e426f549374cff0af3374861e9f065", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-04-25T07:07:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T09:13:11.000Z", "max_issues_repo_path": "include/mxpfit/vandermonde_matrix.hpp", "max_issues_repo_name": "hydeik/mxpfit", "max_issues_repo_head_hexsha": "a18621b191e426f549374cff0af3374861e9f065", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-07-04T08:42:03.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-15T02:57:05.000Z", "max_forks_repo_path": "include/mxpfit/vandermonde_matrix.hpp", "max_forks_repo_name": "hydeik/mxpfit", "max_forks_repo_head_hexsha": "a18621b191e426f549374cff0af3374861e9f065", "max_forks_repo_licenses": ["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.6926070039, "max_line_length": 80, "alphanum_fraction": 0.5725522105, "num_tokens": 1841, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702880639791, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.47471373089234853}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   tstMomentumConversion.cpp\n//! \\author Alex Robinson\n//! \\brief  The momentum conversion unit tests\n//!\n//---------------------------------------------------------------------------//\n\n// Boost Includes\n#include <boost/units/quantity.hpp>\n#include <boost/units/systems/si.hpp>\n#include <boost/units/systems/cgs.hpp>\n\n// Trilinos Includes\n#include <Teuchos_UnitTestHarness.hpp>\n\n// FRENSIE Includes\n#include \"Utility_MomentumUnits.hpp\"\n#include \"Utility_RawPhysicalConstants.hpp\"\n\nusing namespace Utility::Units;\nusing boost::units::quantity;\n\n//---------------------------------------------------------------------------//\n// Tests\n//---------------------------------------------------------------------------//\n// Check that the momentum units can be converted\nTEUCHOS_UNIT_TEST( MomentumConversion, convert )\n{\n  quantity<AtomicMomentum> atomic_momentum_q( 1.0*mec_momentum );\n\n  quantity<MeCMomentum> mec_momentum_q( 1.0*atomic_momentum );\n\n  TEST_FLOATING_EQUALITY( \n\t\tatomic_momentum_q.value(), \n\t\tUtility::RawPhysicalConstants::inverse_fine_structure_constant,\n\t\t1e-15 );\n  TEST_FLOATING_EQUALITY( \n\t\t\tmec_momentum_q.value(),\n\t\t\tUtility::RawPhysicalConstants::fine_structure_constant,\n\t\t\t1e-15 );\n}\n\n//---------------------------------------------------------------------------//\n// end tstMomentumConversion.cpp\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "9e21509f46e204e5383c31d57bf8da697fbf53da", "size": 1494, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "packages/utility/units/test/tstMomentumConversion.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/utility/units/test/tstMomentumConversion.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/utility/units/test/tstMomentumConversion.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": 31.7872340426, "max_line_length": 79, "alphanum_fraction": 0.5220883534, "num_tokens": 280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.47471372798991524}}
{"text": "//=======================================================================\n// Copyright (c) 2014 Piotr Smulewicz\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n/**\n * @file k_center_test.cpp\n * @brief\n * @author Piotr Smulewicz\n * @version 1.0\n * @date 2014-01-28\n */\n\n#include \"test_utils/test_result_check.hpp\"\n#include \"greedy/k_center/in_balls.hpp\"\n\n#include \"paal/data_structures/metric/basic_metrics.hpp\"\n#include \"paal/greedy/k_center/k_center.hpp\"\n#include \"paal/utils/irange.hpp\"\n\n#include <boost/test/unit_test.hpp>\n\nBOOST_AUTO_TEST_CASE(KCenter) {\n    std::size_t const NUM_CENTERS = 3;\n    std::size_t const NUM_ITEMS = 6;\n    const double OPTIMAL = 1;\n    const double APPROXIMATION_RATIO = 2;\n    auto metric = [](int a, int b) { return 0.1 + abs(a - b) * 0.9; };\n    auto items = paal::irange(NUM_ITEMS);\n    std::vector<int> centers;\n    // solution\n    double radius = paal::greedy::kCenter(metric, NUM_CENTERS, items.begin(),\n                                          items.end(), back_inserter(centers));\n    LOGLN(\"Radius \" << radius);\n    LOGLN(\"Centers:\");\n    LOG_COPY_RANGE_DEL(centers, \" \");\n    LOGLN(\"\");\n    BOOST_CHECK_EQUAL(centers.size(), NUM_CENTERS);\n    check_result(radius, OPTIMAL, APPROXIMATION_RATIO);\n    paal::in_balls(items, centers, metric, radius);\n}\n", "meta": {"hexsha": "d150ef1124cd78cfc442541e7e99510e68b18d23", "size": 1479, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/greedy/k_center/k_center_test.cpp", "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": "test/greedy/k_center/k_center_test.cpp", "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": "test/greedy/k_center/k_center_test.cpp", "max_forks_repo_name": "Kommeren/AA", "max_forks_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-24T06:23:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-24T06:23:56.000Z", "avg_line_length": 33.6136363636, "max_line_length": 79, "alphanum_fraction": 0.6051386072, "num_tokens": 387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.4747137182251124}}
{"text": "#ifndef CLUSTER_H\n#define CLUSTER_H 1\n\n#include <set>\n#include <vector>\n#include <STD/Iostream.hpp>\n\n//#include <boost/unordered_map.hpp>\n#include <boost/foreach.hpp>\n\nnamespace Clustering{\n\n  typedef double Coord;            // a coordinate\n  typedef double Distance;         // distance\n  typedef unsigned int Dimensions; // how many dimensions\n  typedef unsigned int PointId;    // the id of this point\n  typedef unsigned int ClusterId;  // the id of this cluster\n\n  typedef std::vector<Coord> Point;    // a point (a centroid)\n  typedef std::vector<Point> Points;   // collection of points\n\n  typedef std::set<PointId> SetPoints; // set of points\n\n  // ClusterId -> (PointId, PointId, PointId, .... )\n  typedef std::vector<SetPoints> ClustersToPoints;\n  // PointId -> ClusterId\n  typedef std::vector<ClusterId> PointsToClusters;\n  // coll of centroids\n  typedef std::vector<Point> Centroids;\n\n  //\n  // Dump a point\n  //\n  std::ostream& operator << (std::ostream& os, Point& p);\n\n  //\n  // distance between two points\n  //\n  Distance distance(const Point & x, const Point & y);\n\n  //\n  // Dump collection of Points\n  //\n  std::ostream& operator << (std::ostream& os, Points& cps);\n\n  //\n  // Dump a Set of points\n  //\n  std::ostream& operator << (std::ostream& os, SetPoints & sp);\n\n  //\n  // Dump centroids\n  //\n  std::ostream& operator << (std::ostream& os, Centroids & cp);\n\n\n  //\n  // Dump ClustersToPoints\n  //\n  std::ostream& operator << (std::ostream& os, ClustersToPoints & cp);\n\n  //\n  // Dump ClustersToPoints\n  //\n  std::ostream& operator << (std::ostream& os, PointsToClusters & pc);\n\n\n  //\n  // This class stores all the points available in the model\n  //\n  class PointsSpace{\n\n    //\n    // Dump collection of points\n    //\n    friend std::ostream& operator << (std::ostream& os, PointsSpace & ps){\n\n      PointId i = 0;\n      BOOST_FOREACH(Points::value_type p, ps.points__){\n\tos << \"point[\"<<i++<<\"]=\" << p << std::endl;\n      }\n      return os;\n    };\n\n  public:\n\n    PointsSpace(PointId num_points, Dimensions num_dimensions)\n      : num_points__(num_points), num_dimensions__(num_dimensions)\n    {init_points();};\n\n    inline const PointId getNumPoints() const {return num_points__;}\n    inline const PointId getNumDimensions() const {return num_dimensions__;}\n    inline const Point& getPoint(PointId pid) const { return points__[pid];}\n    inline void setPoint(PointId pid, int dim, double val) { points__.at(pid).at(dim) = val;}\n\n  private:\n    //\n    // Init collection of points\n    //\n    void init_points();\n\n    PointId num_points__;\n    Dimensions num_dimensions__;\n    Points points__;\n  };\n\n  //\n  //  This class represents a cluster\n  //\n  class Clusters {\n\n  private:\n\n    ClusterId num_clusters__;    // number of clusters\n    PointsSpace& ps__;           // the point space\n    Dimensions num_dimensions__; // the dimensions of vectors\n    PointId num_points__;        // total number of points\n    ClustersToPoints clusters_to_points__;\n    PointsToClusters points_to_clusters__;\n    Centroids centroids__;\n\n    //\n    // Zero centroids\n    //\n    void zero_centroids();\n\n    //\n    // Zero centroids\n    //\n    void compute_centroids();\n\n    //\n    // Initial partition points among available clusters\n    //\n    void initial_partition_points();\n\n  public:\n\n    //const ClustersToPoints & getClusters() const { return clusters_to_points__; }\n    const Centroids & getCentroids() const { return centroids__; }\n    //\n    // Dump ClustersToPoints\n    //\n    friend std::ostream& operator << (std::ostream& os, Clusters & cl){\n\n      ClusterId cid = 0;\n      BOOST_FOREACH(ClustersToPoints::value_type set, cl.clusters_to_points__){\n\tos << \"Cluster[\"<<cid<<\"]=(\";\n\tBOOST_FOREACH(SetPoints::value_type pid, set){\n\t  Point p = cl.ps__.getPoint(pid);\n\t  os << \"(\" << p << \")\";\n\t}\n\tos << \")\" << std::endl;\n\tcid++;\n      }\n      return os;\n    }\n\n\n    Clusters(ClusterId num_clusters, PointsSpace & ps)\n      : num_clusters__(num_clusters), ps__(ps),\n\tnum_dimensions__(ps.getNumDimensions()),\n\tnum_points__(ps.getNumPoints()),\n\tpoints_to_clusters__(num_points__, 0){\n\n      ClusterId i = 0;\n      Dimensions dim;\n      for (; i < num_clusters; i++){\n\tPoint point;   // each centroid is a point\n\tfor (dim=0; dim<num_dimensions__; dim++)\n\t  point.push_back(0.0);\n\tSetPoints set_of_points;\n\n\t// init centroids\n\tcentroids__.push_back(point);\n\n\t// init clusterId -> set of points\n\tclusters_to_points__.push_back(set_of_points);\n\t// init point <- cluster\n      }\n      /*\n      std::cout << \"Centroids\"\n\t\t<<std::endl<< centroids__;\n      std::cout << \"PointsToClusters\"\n\t\t<<std::endl<< points_to_clusters__;\n      std::cout << \"ClustersToPoints\"\n\t\t<<std::endl<< clusters_to_points__;\n      */\n    };\n\n    //\n    // k-means\n    //\n    void k_means (void);\n  };\n\n};\n\n\n#endif\n", "meta": {"hexsha": "40ba3addaff64c13c8057fe04272bc14c26f52e5", "size": 4799, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libBoost/EnjoLibBoost/KMeans.hpp", "max_stars_repo_name": "hlp2/EnjoLib", "max_stars_repo_head_hexsha": "6bb69d0b00e367a800b0ef2804808fd1303648f4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libBoost/EnjoLibBoost/KMeans.hpp", "max_issues_repo_name": "hlp2/EnjoLib", "max_issues_repo_head_hexsha": "6bb69d0b00e367a800b0ef2804808fd1303648f4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libBoost/EnjoLibBoost/KMeans.hpp", "max_forks_repo_name": "hlp2/EnjoLib", "max_forks_repo_head_hexsha": "6bb69d0b00e367a800b0ef2804808fd1303648f4", "max_forks_repo_licenses": ["BSD-3-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.8756218905, "max_line_length": 93, "alphanum_fraction": 0.6422171286, "num_tokens": 1218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702642896702, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.4747137153226789}}
{"text": "/*=============================================================================\r\n    Copyright (c) 2001-2003 Daniel Nuffer\r\n    http://spirit.sourceforge.net/\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#include <boost/spirit/include/classic_core.hpp>\r\n#include <boost/spirit/include/classic_ast.hpp>\r\n#include <boost/assert.hpp>\r\n\r\n#include <iostream>\r\n#include <stack>\r\n#include <functional>\r\n#include <string>\r\n\r\n// This example shows how to use an AST and tree_iter_node instead of\r\n// tree_val_node\r\n////////////////////////////////////////////////////////////////////////////\r\nusing namespace std;\r\nusing namespace BOOST_SPIRIT_CLASSIC_NS;\r\n\r\ntypedef char const*         iterator_t;\r\ntypedef tree_match<iterator_t, node_iter_data_factory<> >\r\n    parse_tree_match_t;\r\n\r\ntypedef parse_tree_match_t::tree_iterator iter_t;\r\n\r\ntypedef ast_match_policy<iterator_t, node_iter_data_factory<> > match_policy_t;\r\ntypedef scanner<iterator_t, scanner_policies<iter_policy_t, match_policy_t> > scanner_t;\r\ntypedef rule<scanner_t> rule_t;\r\n\r\n\r\n//  grammar rules\r\nrule_t expression, term, factor, integer;\r\n\r\n////////////////////////////////////////////////////////////////////////////\r\nlong evaluate(parse_tree_match_t hit);\r\nlong eval_expression(iter_t const& i);\r\nlong eval_term(iter_t const& i);\r\nlong eval_factor(iter_t const& i);\r\nlong eval_integer(iter_t const& i);\r\n\r\nlong evaluate(parse_tree_match_t hit)\r\n{\r\n    return eval_expression(hit.trees.begin());\r\n}\r\n\r\nlong eval_expression(iter_t const& i)\r\n{\r\n    cout << \"In eval_expression. i->value = \" <<\r\n        string(i->value.begin(), i->value.end()) <<\r\n        \" i->children.size() = \" << i->children.size() << endl;\r\n\r\n    cout << \"ID: \" << i->value.id().to_long() << endl;\r\n\r\n    if (i->value.id() == integer.id())\r\n    {\r\n        BOOST_ASSERT(i->children.size() == 0);\r\n        return strtol(i->value.begin(), 0, 10);\r\n    }\r\n    else if (i->value.id() == factor.id())\r\n    {\r\n        // factor can only be unary minus\r\n        BOOST_ASSERT(*i->value.begin() == '-');\r\n        return - eval_expression(i->children.begin());\r\n    }\r\n    else if (i->value.id() == term.id())\r\n    {\r\n        if (*i->value.begin() == '*')\r\n        {\r\n            BOOST_ASSERT(i->children.size() == 2);\r\n            return eval_expression(i->children.begin()) *\r\n                eval_expression(i->children.begin()+1);\r\n        }\r\n        else if (*i->value.begin() == '/')\r\n        {\r\n            BOOST_ASSERT(i->children.size() == 2);\r\n            return eval_expression(i->children.begin()) /\r\n                eval_expression(i->children.begin()+1);\r\n        }\r\n        else\r\n            BOOST_ASSERT(0);\r\n    }\r\n    else if (i->value.id() == expression.id())\r\n    {\r\n        if (*i->value.begin() == '+')\r\n        {\r\n            BOOST_ASSERT(i->children.size() == 2);\r\n            return eval_expression(i->children.begin()) +\r\n                eval_expression(i->children.begin()+1);\r\n        }\r\n        else if (*i->value.begin() == '-')\r\n        {\r\n            BOOST_ASSERT(i->children.size() == 2);\r\n            return eval_expression(i->children.begin()) -\r\n                eval_expression(i->children.begin()+1);\r\n        }\r\n        else\r\n            BOOST_ASSERT(0);\r\n    }\r\n    else\r\n        BOOST_ASSERT(0); // error\r\n\r\n   return 0;\r\n}\r\n\r\n////////////////////////////////////////////////////////////////////////////\r\nint\r\nmain()\r\n{\r\n    BOOST_SPIRIT_DEBUG_RULE(integer);\r\n    BOOST_SPIRIT_DEBUG_RULE(factor);\r\n    BOOST_SPIRIT_DEBUG_RULE(term);\r\n    BOOST_SPIRIT_DEBUG_RULE(expression);\r\n    //  Start grammar definition\r\n    integer     =   leaf_node_d[ lexeme_d[ (!ch_p('-') >> +digit_p) ] ];\r\n    factor      =   integer\r\n                |   inner_node_d[ch_p('(') >> expression >> ch_p(')')]\r\n                |   (root_node_d[ch_p('-')] >> factor);\r\n    term        =   factor >>\r\n                    *(  (root_node_d[ch_p('*')] >> factor)\r\n                      | (root_node_d[ch_p('/')] >> factor)\r\n                    );\r\n    expression  =   term >>\r\n                    *(  (root_node_d[ch_p('+')] >> term)\r\n                      | (root_node_d[ch_p('-')] >> term)\r\n                    );\r\n    //  End grammar definition\r\n\r\n\r\n    cout << \"/////////////////////////////////////////////////////////\\n\\n\";\r\n    cout << \"\\t\\tThe simplest working calculator...\\n\\n\";\r\n    cout << \"/////////////////////////////////////////////////////////\\n\\n\";\r\n    cout << \"Type an expression...or [q or Q] to quit\\n\\n\";\r\n\r\n    string str;\r\n    while (getline(cin, str))\r\n    {\r\n        if (str.empty() || str[0] == 'q' || str[0] == 'Q')\r\n            break;\r\n\r\n        const char* str_begin = str.c_str();\r\n        const char* str_end = str.c_str();\r\n        while (*str_end)\r\n            ++str_end;\r\n\r\n        scanner_t scan(str_begin, str_end);\r\n\r\n        parse_tree_match_t hit = expression.parse(scan);\r\n\r\n\r\n        if (hit && str_begin == str_end)\r\n        {\r\n#if defined(BOOST_SPIRIT_DUMP_PARSETREE_AS_XML)\r\n            // dump parse tree as XML\r\n            std::map<rule_id, std::string> rule_names;\r\n            rule_names[&integer] = \"integer\";\r\n            rule_names[&factor] = \"factor\";\r\n            rule_names[&term] = \"term\";\r\n            rule_names[&expression] = \"expression\";\r\n            tree_to_xml(cout, hit.trees, str.c_str(), rule_names);\r\n#endif\r\n\r\n            // print the result\r\n            cout << \"parsing succeeded\\n\";\r\n            cout << \"result = \" << evaluate(hit) << \"\\n\\n\";\r\n        }\r\n        else\r\n        {\r\n            cout << \"parsing failed\\n\";\r\n        }\r\n    }\r\n\r\n    cout << \"Bye... :-) \\n\\n\";\r\n    return 0;\r\n}\r\n\r\n\r\n", "meta": {"hexsha": "1031d4d61ec43690d1c32859b72753c3cdfe5388", "size": 5832, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/spirit/classic/example/fundamental/more_calculators/ast_calc2.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/spirit/classic/example/fundamental/more_calculators/ast_calc2.cpp", "max_issues_repo_name": "flingone/frameworks_base_cmds_remoted", "max_issues_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/boost/libs/spirit/classic/example/fundamental/more_calculators/ast_calc2.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": 32.2209944751, "max_line_length": 89, "alphanum_fraction": 0.4943415638, "num_tokens": 1278, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.7248702642896702, "lm_q1q2_score": 0.4747137153226789}}
{"text": "#include \"../secp256k1/include/MultiExponent.h\"\n\n#include <boost/filesystem.hpp>\n#include <boost/test/unit_test.hpp>\n#include <boost/thread.hpp>\n\nBOOST_AUTO_TEST_CASE(multiexponentation_test)\n{\n    std::vector<int> sizes = {1, 4, 20, 57,136, 235, 1260, 4420, 7880, 16050, 10, 100, 1000, 5000};\n\n    for(unsigned int j = 0; j < sizes.size(); ++j){\n        int size = sizes[j];\n        std::vector<secp_primitives::GroupElement> gens;\n        std::vector<secp_primitives::Scalar> scalars;\n\n        secp_primitives::GroupElement r;\n        gens.resize(size);\n        scalars.resize(size);\n        for (int i = 0; i < size; ++i) {\n            gens[i].randomize();\n            scalars[i].randomize();\n\n            r += gens[i] * scalars[i];\n        }\n\n        secp_primitives::MultiExponent multiexponent(gens, scalars);\n        secp_primitives::GroupElement result = multiexponent.get_multiple();\n\n        BOOST_CHECK_EQUAL(r,result);\n    }\n}\n\n", "meta": {"hexsha": "88e0052a0b9d37580a23d22893b4abd916dd813e", "size": 940, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/multiexponentation_test.cpp", "max_stars_repo_name": "mattt21/zcoin", "max_stars_repo_head_hexsha": "730f0c39ba47f762627f13a1e9ea66d76b57a57d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 582.0, "max_stars_repo_stars_event_min_datetime": "2016-09-26T00:08:04.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-25T19:07:24.000Z", "max_issues_repo_path": "src/test/multiexponentation_test.cpp", "max_issues_repo_name": "mattt21/zcoin", "max_issues_repo_head_hexsha": "730f0c39ba47f762627f13a1e9ea66d76b57a57d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 570.0, "max_issues_repo_issues_event_min_datetime": "2016-09-28T07:29:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-26T10:24:19.000Z", "max_forks_repo_path": "src/test/multiexponentation_test.cpp", "max_forks_repo_name": "mattt21/zcoin", "max_forks_repo_head_hexsha": "730f0c39ba47f762627f13a1e9ea66d76b57a57d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 409.0, "max_forks_repo_forks_event_min_datetime": "2016-09-21T12:37:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-18T14:54:17.000Z", "avg_line_length": 28.4848484848, "max_line_length": 99, "alphanum_fraction": 0.6191489362, "num_tokens": 266, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.6548947155710233, "lm_q1q2_score": 0.47471371334271073}}
{"text": "#pragma once\n#include <iostream>\n\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n\n#include <unsupported/Eigen/NonLinearOptimization>\n//#include <unsupported/Eigen/LevenbergMarquardt>\n\n// LM minimize for the model y = a w + b x + c y + d z\n//typedef std::vector<Eigen::Vector4d,Eigen::aligned_allocator<Eigen::Vector4d> > Point4DVector;\ntypedef std::vector<Eigen::Vector4d > Point4DVector;\ntypedef std::vector<Eigen::Vector3d > Point3DVector;\ntypedef std::vector<Eigen::Matrix3d > Matrix3DVector;\ntypedef std::vector<Eigen::Matrix4d > Matrix4DVector;\ntypedef std::vector<Eigen::Affine3d > Affine3DVector;\ntypedef std::vector<Eigen::Affine3f > Affine3fVector;\n\ntypedef std::vector<Eigen::Vector3d > Vector3dVector;\ntypedef std::vector<Eigen::Quaterniond > QuaterniondVector;\n\ntypedef Eigen::Matrix<double,7,1> Vector7d ;\ntypedef std::vector<Vector7d > Vector7dVector;\n\n// Generic functor\ntemplate<typename _Scalar, int NX = Eigen::Dynamic, int NY = Eigen::Dynamic>\nstruct Functor\n{\ntypedef _Scalar Scalar;\nenum {\n    InputsAtCompileTime = NX,\n    ValuesAtCompileTime = NY\n};\ntypedef Eigen::Matrix<Scalar,InputsAtCompileTime,1> InputType;\ntypedef Eigen::Matrix<Scalar,ValuesAtCompileTime,1> ValueType;\ntypedef Eigen::Matrix<Scalar,ValuesAtCompileTime,InputsAtCompileTime> JacobianType;\n\nint m_inputs, m_values;\n\nFunctor() : m_inputs(InputsAtCompileTime), m_values(ValuesAtCompileTime) {}\nFunctor(int inputs, int values) : m_inputs(inputs), m_values(values) {}\n\nint inputs() const { return m_inputs; }\nint values() const { return m_values; }\n\n};\n\nvoid NormalizeQ(Eigen::Quaterniond &Q);\nvoid Affine3d_From_Qt( Eigen::Affine3d& T_a2b, Eigen::Quaterniond Q_a2b,Eigen::Vector3d t_a2b );\nvoid Affine3d_To_Vector( const Eigen::Affine3d& T,Eigen::Matrix<double,16,1>& V );\nvoid Vector_To_Affine3d(  const Eigen::VectorXd& V ,Eigen::Affine3d& T);\n\nstruct Q_bc_Functor : Functor<double>\n{\n  int operator()(const Eigen::VectorXd &x, Eigen::VectorXd &fvec) const\n  {\n      // 0  = w * p[0] + x * p[1] + y * p[2] + z * p[3]\n    for(unsigned int i = 0; i < this->Mct_sub_Mb.size(); ++i)\n      {\n      fvec(i) = this->Mct_sub_Mb[i](0) * x(0) + this->Mct_sub_Mb[i](1) * x(1) +\n              this->Mct_sub_Mb[i](2) * x(2) + this->Mct_sub_Mb[i](3) * x(3) +\n              (pow( x(0),2 ) + pow( x(1),2 ) + pow( x(2),2 ) + pow( x(3),2 ) - 1)*1;\n      }\n    return 0;\n  }\n\n  Point4DVector Mct_sub_Mb;\n\n  int inputs() const { return 2; } // There are two parameters of the model\n  int values() const { return this->Mct_sub_Mb.size(); } // The number of observations\n};\n\nstruct Q_bc_FunctorNumericalDiff : Eigen::NumericalDiff<Q_bc_Functor> {};\n\nstruct T_bc_Functor : Functor<double>\n{\n    Eigen::VectorXd t_temp_N;\n    Eigen::MatrixXd R_temp_N;\n\n    int operator()(const Eigen::VectorXd &x, Eigen::VectorXd &fvec) const\n    {\n        fvec = t_temp_N - R_temp_N * x;\n        return 0;\n    }\n    int inputs() const { return 2; } // There are two parameters of the model\n    int values() const { return t_temp_N.rows(); } // The number of observations\n};\nstruct T_bc_FunctorNumericalDiff : Eigen::NumericalDiff<T_bc_Functor> {};\n\nPoint4DVector GeneratePoints(const Eigen::MatrixXd M);\n\n\nstruct T_rw_Functor : Functor<double>\n{\n    QuaterniondVector Q_r2w_V;\n    Vector3dVector t_r2w_V;\n    int operator()(const Eigen::VectorXd &Q_t_r2w, Eigen::VectorXd &fvec) const\n    {\n        for(int i=0;i<Q_r2w_V.size();i++)\n        {\n            fvec(i*7+0) = Q_r2w_V.at(i).x() - Q_t_r2w(0);\n            fvec(i*7+1) = Q_r2w_V.at(i).y() - Q_t_r2w(1);\n            fvec(i*7+2) = Q_r2w_V.at(i).z() - Q_t_r2w(2);\n            fvec(i*7+3) = Q_r2w_V.at(i).w() - Q_t_r2w(3);\n\n\n            for(int j=0;j<3;j++)\n            {\n                fvec(i*7+4+j) = t_r2w_V.at(i)(j) - Q_t_r2w(j+4);\n            }\n        }\n    }\n    int inputs() const { return 2; } // There are two parameters of the model\n    int values() const { return Q_r2w_V.size()*7; } // The number of observations\n};\nstruct T_rw_FunctorNumericalDiff : Eigen::NumericalDiff<T_rw_Functor> {};\n\nstruct InCal_Functor : Functor<double>\n{\n    Affine3DVector T_w2b_V,T_r2c_V;\n    int operator()(const Eigen::VectorXd &T_In, Eigen::VectorXd &fvec) const\n    {\n//        Eigen::Quaterniond Q_r2w( T_In(3),T_In(0),T_In(1),T_In(2) ) ,Q_b2c( T_In(3+7),T_In(0+7),T_In(1+7),T_In(2+7) );\n//        Eigen::Vector3d t_r2w( T_In(4),T_In(5),T_In(6) ) ,t_b2c( T_In(4+7),T_In(5+7),T_In(6+7) );\n\n        Eigen::Affine3d T_r2w,T_c2b;\n//        Affine3d_From_Qt(T_r2w,Q_r2w,t_r2w);\n//        Affine3d_From_Qt(T_b2c,Q_b2c,t_b2c);\n        Eigen::VectorXd V_r2w,V_c2b;\n        V_r2w = T_In.block<16,1>(0,0);\n        V_c2b = T_In.block<16,1>(16,0);\n\n        Vector_To_Affine3d(V_r2w,T_r2w);\n        Vector_To_Affine3d(V_c2b,T_c2b);\n\n\n        for(int i=0;i<T_w2b_V.size();i++)\n        {\n            Eigen::Affine3d T_r2b_1 = T_c2b * T_r2c_V.at(i);\n            Eigen::Affine3d T_r2b_2 = T_w2b_V.at(i) * T_r2w;\n\n            Eigen::Matrix4d T_err = T_r2b_1.matrix() - T_r2b_2.matrix();\n\n//            Eigen::Affine3d T_r2r =  T_r2b_1.inverse() * T_r2b_2;\n//            Eigen::Matrix4d T_err = T_r2r.matrix() - Eigen::Affine3d::Identity().matrix();\n\n            for(int j=0;j<4;j++)\n            {\n                for(int k=0;k<4;k++)\n                {\n                    fvec(i*16+j*4+k) = T_err(j,k);\n                }\n            }\n        }\n    }\n    int inputs() const { return 2; } // There are two parameters of the model\n    int values() const { return T_w2b_V.size()*16; } // The number of observations\n};\nstruct Incal_FunctorNumericalDiff : Eigen::NumericalDiff<InCal_Functor> {};\n\n\n\nint Cal_Q_bc(Eigen::MatrixXf M,Eigen::VectorXf& xf);\nint Cal_T_bc(Eigen::VectorXf t_temp_N,Eigen::MatrixXf R_temp_N,Eigen::VectorXf& t_b2c);\nint InstallCalib_LM( Eigen::Affine3f &T_b2c,  Eigen::Affine3f &T_r2w, Affine3fVector& T_r2c_V,Affine3fVector& T_w2b_V);\nint Cal_T_rw(Eigen::Affine3f& T_r2w,Affine3fVector& T_r2w_V_f);\n\n", "meta": {"hexsha": "5100f705ce801c047a4a38e4799ab9f05caaf590", "size": 5905, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "aruco_ros/EigenLM.hpp", "max_stars_repo_name": "ecdeng/camera_LAM_ros", "max_stars_repo_head_hexsha": "4fc9de6a397d8af8f1af8d85ca641f6acc9b5ca6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-02-08T00:41:42.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-08T00:41:42.000Z", "max_issues_repo_path": "aruco_ros/EigenLM.hpp", "max_issues_repo_name": "ecdeng/camera_LAM_ros", "max_issues_repo_head_hexsha": "4fc9de6a397d8af8f1af8d85ca641f6acc9b5ca6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "aruco_ros/EigenLM.hpp", "max_forks_repo_name": "ecdeng/camera_LAM_ros", "max_forks_repo_head_hexsha": "4fc9de6a397d8af8f1af8d85ca641f6acc9b5ca6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-08-04T03:42:33.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-21T03:24:12.000Z", "avg_line_length": 35.1488095238, "max_line_length": 120, "alphanum_fraction": 0.6487722269, "num_tokens": 2006, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583695, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.47456185602032713}}
{"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\u2019s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n#pragma once\n\n#include \"../util/FluidEigenMappings.hpp\"\n#include \"../util/NNFuncs.hpp\"\n#include \"../util/NNLayer.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 <random>\n\nnamespace fluid {\nnamespace algorithm {\n\nclass MLP\n{\n  using ArrayXd = Eigen::ArrayXd;\n  using ArrayXXd = Eigen::ArrayXXd;\n\npublic:\n  explicit MLP() = default;\n  ~MLP() = default;\n\n  void init(index inputSize, index outputSize,\n            FluidTensor<index, 1> hiddenSizes, index hiddenAct, index outputAct)\n  {\n    mLayers.clear();\n    std::vector<index> sizes = {inputSize};\n    std::vector<index> activations = {};\n    for (auto&& s : hiddenSizes)\n    {\n      sizes.push_back(s);\n      activations.push_back(hiddenAct);\n    }\n    sizes.push_back(outputSize);\n    activations.push_back(outputAct);\n    for (index i = 0; i < asSigned(sizes.size() - 1); i++)\n    {\n      mLayers.push_back(NNLayer(sizes[asUnsigned(i)], sizes[asUnsigned(i + 1)],\n                                activations[asUnsigned(i)]));\n    }\n    for (auto&& l : mLayers) l.init();\n    mInitialized = true;\n    mTrained = false;\n  }\n\n  void getParameters(index layer, RealMatrixView W, RealVectorView b,\n                     index& layerType) const\n  {\n    using namespace _impl;\n    W = asFluid(mLayers[asUnsigned(layer)].getWeights());\n    b = asFluid(mLayers[asUnsigned(layer)].getBiases());\n    layerType = mLayers[asUnsigned(layer)].getActType();\n  }\n\n  void setParameters(index layer, RealMatrixView W, RealVectorView b,\n                     index layerType)\n  {\n    using namespace Eigen;\n    using namespace std;\n    using namespace _impl;\n    MatrixXd weights = asEigen<Matrix>(W);\n    VectorXd biases = asEigen<Matrix>(b);\n    mLayers[asUnsigned(layer)].init(weights, biases, layerType);\n  }\n\n  void clear()\n  {\n    for (auto&& l : mLayers) l.init();\n    mInitialized = false;\n    mTrained = false;\n  }\n\n  double loss(ArrayXXd pred, ArrayXXd out)\n  {\n    assert(pred.rows() == out.rows());\n    return (pred - out).square().sum() / out.rows();\n  }\n\n  void process(RealMatrixView in, RealMatrixView out, index startLayer,\n               index endLayer)\n  {\n    using namespace _impl;\n    using namespace Eigen;\n    ArrayXXd input = asEigen<Eigen::Array>(in);\n    ArrayXXd output = ArrayXXd::Zero(out.rows(), out.cols());\n    forward(input, output, startLayer, endLayer);\n    out = asFluid(output);\n  }\n\n  void processFrame(RealVectorView in, RealVectorView out, index startLayer,\n                    index endLayer)\n  {\n    using namespace _impl;\n    using namespace Eigen;\n    ArrayXd  tmpIn = asEigen<Eigen::Array>(in);\n    ArrayXXd input(1, tmpIn.size());\n    input.row(0) = tmpIn;\n    ArrayXXd output = ArrayXXd::Zero(1, out.size());\n    forward(input, output, startLayer, endLayer);\n    ArrayXd tmpOut = output.row(0);\n    out = asFluid(tmpOut);\n  }\n\n  void forward(Eigen::Ref<ArrayXXd> in, Eigen::Ref<ArrayXXd> out)\n  {\n    forward(in, out, 0, asSigned(mLayers.size()));\n  }\n\n  void forward(Eigen::Ref<ArrayXXd> in, Eigen::Ref<ArrayXXd> out,\n               index startLayer, index endLayer)\n  {\n    if (startLayer >= asSigned(mLayers.size()) ||\n        endLayer > asSigned(mLayers.size()))\n      return;\n    if (startLayer < 0 || endLayer <= 0) return;\n    ArrayXXd input = in;\n    ArrayXXd output;\n    for (index i = startLayer; i < endLayer; i++)\n    {\n      auto&& l = mLayers[asUnsigned(i)];\n      output = ArrayXXd::Zero(input.rows(), l.outputSize());\n      l.forward(input, output);\n      input = output;\n    }\n    out = output;\n  }\n\n  void backward(Eigen::Ref<ArrayXXd> out)\n  {\n    index    nRows = out.rows();\n    ArrayXXd chain =\n        ArrayXXd::Zero(nRows, mLayers[mLayers.size() - 1].inputSize());\n    mLayers[mLayers.size() - 1].backward(out, chain);\n    for (index i = asSigned(mLayers.size() - 2); i >= 0; i--)\n    {\n      ArrayXXd tmp = ArrayXXd::Zero(nRows, mLayers[asUnsigned(i)].inputSize());\n      mLayers[asUnsigned(i)].backward(chain, tmp);\n      chain = tmp;\n    }\n  }\n\n  void update(double learningRate, double momentum)\n  {\n    for (auto&& l : mLayers) l.update(learningRate, momentum);\n  }\n\n  index size() const { return asSigned(mLayers.size()); }\n  bool  trained() const { return mTrained; }\n  void  setTrained(bool val) { mTrained = val; }\n  index initialized() const { return mInitialized; }\n\n  // 0 = size of the input, 1 = output size of first hidden\n  index outputSize(index layer) const\n  {\n    if (layer == 0) return mLayers[0].inputSize();\n    if (layer < 0 || layer > asSigned(mLayers.size())) return 0;\n    return mLayers[asUnsigned(layer - 1)].outputSize();\n  }\n\n  index inputSize(index layer) const\n  {\n    return (layer >= asSigned(mLayers.size()) || layer < 0)\n               ? 0\n               : mLayers[asUnsigned(layer)].inputSize();\n  }\n\n  index dims() const\n  {\n    return mLayers.size() == 0 ? 0 : mLayers[0].inputSize();\n  }\n\n  std::vector<NNLayer> mLayers;\n  bool                 mInitialized{false};\n  bool                 mTrained{false};\n};\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "f7ba833f4865e3c7a535dedd5aa3a339085a6dfe", "size": 5547, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/public/MLP.hpp", "max_stars_repo_name": "elgiano/flucoma-core", "max_stars_repo_head_hexsha": "d34a04e7a68f24eaf09b24df57020d45664061fc", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/algorithms/public/MLP.hpp", "max_issues_repo_name": "elgiano/flucoma-core", "max_issues_repo_head_hexsha": "d34a04e7a68f24eaf09b24df57020d45664061fc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-03-15T10:39:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-15T13:19:22.000Z", "max_forks_repo_path": "include/algorithms/public/MLP.hpp", "max_forks_repo_name": "elgiano/flucoma-core", "max_forks_repo_head_hexsha": "d34a04e7a68f24eaf09b24df57020d45664061fc", "max_forks_repo_licenses": ["BSD-3-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.1947368421, "max_line_length": 80, "alphanum_fraction": 0.63601947, "num_tokens": 1473, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.4745618475328694}}
{"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_ARITHMETIC_HPP\n#define BOOST_ASTRONOMY_COORDINATE_ARITHMETIC_HPP\n\n#include <type_traits>\n\n#include <boost/units/quantity.hpp>\n#include <boost/geometry/geometries/point.hpp>\n#include <boost/geometry/arithmetic/cross_product.hpp>\n#include <boost/geometry/arithmetic/dot_product.hpp>\n#include <boost/geometry/algorithms/transform.hpp>\n#include <boost/geometry/core/cs.hpp>\n#include <boost/units/conversion.hpp>\n\n#include <boost/astronomy/coordinate/base_representation.hpp>\n#include <boost/astronomy/coordinate/cartesian_representation.hpp>\n\n\nnamespace boost { namespace astronomy { namespace coordinate {\n\nnamespace bg = boost::geometry;\nnamespace bu = boost::units;\n\n\n//!Returns the cross product of representation1 and representation2\ntemplate\n<\n    template<typename ...> class Representation1,\n    template<typename ...> class Representation2,\n    typename ...Args1,\n    typename ...Args2\n>\nauto cross\n(\n    Representation1<Args1...> const& representation1,\n    Representation2<Args2...> const& representation2\n)\n{\n    /*!both the coordinates/vector are first converted into\n    cartesian coordinate system then cross product of both cartesian\n    vectors is converted into requested type and returned*/\n\n    /*checking types if it is not subclass of\n    base_representaion then compile time erorr is generated*/\n    //BOOST_STATIC_ASSERT_MSG((boost::astronomy::detail::is_base_template_of\n    //    <\n    //        boost::astronomy::coordinate::base_representation,\n    //        Representation1<Args1...>\n    //    >::value),\n    //    \"First argument type is expected to be a representation class\");\n    //BOOST_STATIC_ASSERT_MSG((boost::astronomy::detail::is_base_template_of\n    //    <\n    //        boost::astronomy::coordinate::base_representation,\n    //        Representation2<Args2...>\n    //    >::value),\n    //    \"Second argument type is expected to be a representation class\");\n\n    /*converting both coordinates/vector into cartesian system*/\n\n    typedef Representation1<Args1...> representation1_type;\n    typedef Representation2<Args2...> representation2_type;\n\n    bg::model::point\n    <\n        typename std::conditional\n        <\n            sizeof(typename representation2_type::type) >=\n                sizeof(typename representation1_type::type),\n            typename representation2_type::type,\n            typename representation1_type::type\n        >::type,\n        3,\n        bg::cs::cartesian\n    > tempPoint1, tempPoint2, result;\n\n    bg::transform(representation1.get_point(), tempPoint1);\n    bg::transform(representation2.get_point(), tempPoint2);\n\n    bg::set<0>(result, (bg::get<1>(tempPoint1)*bg::get<2>(tempPoint2)) -\n        ((bg::get<2>(tempPoint1)*\n        bu::conversion_factor(typename representation1_type::quantity3::unit_type(),\n        typename representation1_type::quantity2::unit_type()))*\n        (bg::get<1>(tempPoint2)*\n        bu::conversion_factor(typename representation2_type::quantity2::unit_type(),\n        typename representation2_type::quantity3::unit_type()))));\n\n    bg::set<1>(result, (bg::get<2>(tempPoint1)*bg::get<0>(tempPoint2)) -\n        ((bg::get<0>(tempPoint1)*\n        bu::conversion_factor(typename representation1_type::quantity1::unit_type(),\n        typename representation1_type::quantity3::unit_type()))*\n        (bg::get<2>(tempPoint2)*\n        bu::conversion_factor(typename representation2_type::quantity3::unit_type(),\n        typename representation2_type::quantity1::unit_type()))));\n\n    bg::set<2>(result, (bg::get<0>(tempPoint1)*bg::get<1>(tempPoint2)) -\n        ((bg::get<1>(tempPoint1)*\n        bu::conversion_factor(typename representation1_type::quantity2::unit_type(),\n        typename representation1_type::quantity1::unit_type()))*\n        (bg::get<0>(tempPoint2)*\n        bu::conversion_factor(typename representation2_type::quantity1::unit_type(),\n        typename representation2_type::quantity2::unit_type()))));\n\n    return Representation1\n        <\n            typename representation1_type::type,\n            bu::quantity<typename bu::multiply_typeof_helper\n            <\n                typename representation1_type::quantity2::unit_type,\n                typename representation2_type::quantity3::unit_type>::type\n            >,\n            bu::quantity<typename bu::multiply_typeof_helper\n            <\n                typename representation1_type::quantity3::unit_type,\n                typename representation2_type::quantity1::unit_type>::type\n            >,\n            bu::quantity<typename bu::multiply_typeof_helper\n            <\n                typename representation1_type::quantity1::unit_type,\n                typename representation2_type::quantity2::unit_type>::type\n            >\n        >(result);\n}\n\n\n//! Returns dot product of representation1 and representation2\ntemplate<typename Representation1, typename Representation2>\nauto dot(Representation1 const& representation1, Representation2 const& representation2)\n{\n    /*!both the coordinates/vector are first converted into\n    cartesian coordinate system then dot product of both cartesian\n    product is converted into requested type and returned*/\n\n    /*converting both coordinates/vector into cartesian system*/\n    bg::model::point\n    <\n        typename std::conditional\n        <\n            sizeof(typename Representation2::type) >=\n                sizeof(typename Representation1::type),\n            typename Representation2::type,\n            typename Representation1::type\n        >::type,\n        3,\n        bg::cs::cartesian\n    > tempPoint1, tempPoint2;\n\n    auto cartesian1 = make_cartesian_representation(representation1);\n    auto cartesian2 = make_cartesian_representation(representation2);\n\n    typedef decltype(cartesian1) cartesian1_type;\n    typedef decltype(cartesian2) cartesian2_type;\n\n    bg::set<0>(tempPoint1, cartesian1.get_x().value());\n    bg::set<1>(tempPoint1,\n        static_cast<typename cartesian1_type::quantity1>(cartesian1.get_y()).value());\n    bg::set<2>(tempPoint1,\n        static_cast<typename cartesian1_type::quantity1>(cartesian1.get_z()).value());\n\n    bg::set<0>(tempPoint2, cartesian2.get_x().value());\n    bg::set<1>(tempPoint2,\n        static_cast<typename cartesian2_type::quantity1>(cartesian2.get_y()).value());\n    bg::set<2>(tempPoint2,\n        static_cast<typename cartesian2_type::quantity1>(cartesian2.get_z()).value());\n\n    return bg::dot_product(tempPoint1, tempPoint2) *\n        typename cartesian1_type::quantity1::unit_type() *\n        typename cartesian2_type::quantity1::unit_type();\n}\n\n\n//! Returns magnitude of the cartesian vector\ntemplate\n<\n    typename CoordinateType,\n    typename XQuantity,\n    typename YQuantity,\n    typename ZQuantity\n>\nauto magnitude\n(\n    cartesian_representation\n    <\n        CoordinateType,\n        XQuantity,\n        YQuantity,\n        ZQuantity\n    > const& vector\n)\n{\n    CoordinateType result = 0;\n    bg::model::point\n    <\n        CoordinateType,\n        3,\n        bg::cs::cartesian\n    > tempPoint;\n\n    bg::set<0>(tempPoint, vector.get_x().value());\n    bg::set<1>(tempPoint, static_cast<XQuantity>(vector.get_y()).value());\n    bg::set<2>(tempPoint, static_cast<XQuantity>(vector.get_z()).value());\n\n    result += std::pow(bg::get<0>(tempPoint), 2) +\n        std::pow(bg::get<1>(tempPoint), 2) +\n        std::pow(bg::get<2>(tempPoint), 2);\n\n    return std::sqrt(result) * typename XQuantity::unit_type();\n}\n\n\n//! Returns magnitude of the vector other than cartesian\ntemplate <typename Coordinate>\nauto magnitude(Coordinate const& vector)\n{\n    return bg::get<2>(vector.get_point()) * typename Coordinate::quantity3::unit_type();\n}\n\n\n//! Returns the unit vector of vector given\ntemplate <typename ...Args>\ncartesian_representation<Args...>\nunit_vector(cartesian_representation<Args...> const& vector)\n{\n    bg::model::point\n    <\n        typename cartesian_representation<Args...>::type,\n        3,\n        bg::cs::cartesian\n    > tempPoint;\n    auto mag = magnitude(vector); //magnitude of vector\n\n    //performing calculations to find unit vector\n    bg::set<0>(tempPoint, vector.get_x().value() / mag.value());\n    bg::set<1>(tempPoint,\n        vector.get_y().value() /\n        static_cast<typename cartesian_representation<Args...>::quantity2>(mag).value());\n    bg::set<2>(tempPoint,\n        vector.get_z().value() /\n        static_cast<typename cartesian_representation<Args...>::quantity3>(mag).value());\n\n    return cartesian_representation<Args...>(tempPoint);\n}\n\n//! Returns unit vector of given vector other than Cartesian\ntemplate <typename Coordinate>\nauto unit_vector(Coordinate const& vector)\n{\n    Coordinate tempVector;\n\n    tempVector.set_lat(vector.get_lat());\n    tempVector.set_lon(vector.get_lon());\n    tempVector.set_dist(1.0 * typename Coordinate::quantity3::unit_type());\n\n    return tempVector;\n}\n\n\n//! Returns sum of representation1 and representation2 \ntemplate<typename Representation1, typename Representation2>\nRepresentation1 sum\n(\n    Representation1 const& representation1,\n    Representation2 const& representation2\n)\n{\n    /*!both the coordinates/vector are first converted into\n    cartesian coordinate system then sum of both cartesian\n    vectors is converted into the type of first argument and returned*/\n\n    /*checking types if it is not subclass of\n    base_representaion then compile time erorr is generated*/\n    //BOOST_STATIC_ASSERT_MSG((boost::astronomy::detail::is_base_template_of\n    //    <\n    //        boost::astronomy::coordinate::base_representation,\n    //        Representation1\n    //    >::value),\n    //    \"First argument type is expected to be a representation class\");\n    //BOOST_STATIC_ASSERT_MSG((boost::astronomy::detail::is_base_template_of\n    //    <\n    //        boost::astronomy::coordinate::base_representation,\n    //        Representation2\n    //    >::value),\n    //    \"Second argument type is expected to be a representation class\");\n\n    /*converting both coordinates/vector into cartesian system*/\n    bg::model::point\n    <\n        typename std::conditional\n        <\n            sizeof(typename Representation2::type) >=\n                sizeof(typename Representation1::type),\n            typename Representation2::type,\n            typename Representation1::type\n        >::type,\n        3,\n        bg::cs::cartesian\n    > result;\n\n    auto cartesian1 = make_cartesian_representation(representation1);\n    auto cartesian2 = make_cartesian_representation(representation2);\n\n    typedef decltype(cartesian1) cartesian1_type;\n\n    //performing calculation to find the sum\n    bg::set<0>(result, (cartesian1.get_x().value() +\n        static_cast<typename cartesian1_type::quantity1>(cartesian2.get_x()).value()));\n    bg::set<1>(result, (cartesian1.get_y().value() +\n        static_cast<typename cartesian1_type::quantity2>(cartesian2.get_y()).value()));\n    bg::set<2>(result, (cartesian1.get_z().value() +\n        static_cast<typename cartesian1_type::quantity3>(cartesian2.get_z()).value()));\n\n    return Representation1(result);\n}\n\n\n//! Returns mean of representation1 and representation2\ntemplate<typename Representation1, typename Representation2>\nRepresentation1 mean\n(\n    Representation1 const& representation1,\n    Representation2 const& representation2\n)\n{\n\n    /*!both the coordinates/vector are first converted into\n    cartesian coordinate system then mean of both cartesian\n    vectors is converted into the type of first argument and returned*/\n\n    /*checking return type if it is not subclass of\n    base_representaion then compile time erorr is generated*/\n    //BOOST_STATIC_ASSERT_MSG((boost::astronomy::detail::is_base_template_of\n    //    <boost::astronomy::coordinate::base_representation, ReturnType>::value),\n    //    \"return type is expected to be a representation class\");\n\n    /*converting both coordinates/vector into cartesian system*/\n    bg::model::point\n    <\n        typename std::conditional\n        <\n            sizeof(typename Representation2::type) >=\n                sizeof(typename Representation1::type),\n            typename Representation2::type,\n            typename Representation1::type\n        >::type,\n        3,\n        bg::cs::cartesian\n    > result;\n\n    auto cartesian1 = make_cartesian_representation(representation1);\n    auto cartesian2 = make_cartesian_representation(representation2);\n\n    typedef decltype(cartesian1) cartesian1_type;\n\n    //performing calculation to find the mean\n    bg::set<0>(result, (cartesian1.get_x().value() +\n        static_cast<typename cartesian1_type::quantity1>(cartesian2.get_x()).value())/2);\n    bg::set<1>(result, (cartesian1.get_y().value() +\n        static_cast<typename cartesian1_type::quantity2>(cartesian2.get_y()).value())/2);\n    bg::set<2>(result, (cartesian1.get_z().value() +\n        static_cast<typename cartesian1_type::quantity3>(cartesian2.get_z()).value())/2);\n\n    return Representation1(result);\n}\n\n}}} // namespace boost::astronomy::coordinate\n#endif // !BOOST_ASTRONOMY_COORDINATE_ARITHMETIC_HPP\n", "meta": {"hexsha": "c918eb9f18b70c0e440c8bc8bbc8d074463a7c80", "size": 13187, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/astronomy/coordinate/arithmetic.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/arithmetic.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/arithmetic.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": 35.6405405405, "max_line_length": 89, "alphanum_fraction": 0.6854477895, "num_tokens": 2983, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711604559846, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.4745618432891402}}
{"text": "// Copyright (c) 2014-2020 The Virie Project\n// Copyright (c) 2012-2013 The Cryptonote developers\n// Distributed under the MIT/X11 software license, see the accompanying\n// file COPYING or http://www.opensource.org/licenses/mit-license.php.\n\n#include <cstddef>\n#include <cstdint>\n#include <fstream>\n#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <boost/program_options.hpp>\n\n#include \"common/util.h\"\n#include \"string_tools.h\"\n#include \"common/command_line.h\"\n#include \"currency_core/currency_config.h\"\n#include \"currency_core/difficulty.h\"\n\n#define COUNT_GENERATE 2000\n#define DEFAULT_TEST_DIFFICULTY_TARGET        120\n\n#define NEXT_DIFFICULTY_ALGO(A,B,C) currency::next_difficulty(A,B,C)\n\nnamespace fs = boost::filesystem;\n\nbool generate(const std::string& file_name, uint64_t count = COUNT_GENERATE)\n{\n  struct powers_t\n  {\n    uint64_t step;\n    uint64_t power;\n  };\n\n  const std::vector<powers_t> table_powers{ {100, 10}, {500, 1000}, {1000, 10000}, {1500, 100000}, {~0ull, 10} };\n\n  std::vector<std::uint64_t> times;\n  times.reserve(DIFFICULTY_WINDOW + 1);\n  times.push_back(0);\n\n  std::vector<currency::wide_difficulty_type> diffs;;\n  diffs.reserve(DIFFICULTY_WINDOW + 1);\n  diffs.push_back(DIFFICULTY_STARTER);\n\n  uint64_t time = 100;\n  TRY_ENTRY();\n    std::srand(unsigned(std::time(0)));\n    fs::ofstream fo;\n    fo.open(file_name);\n\n    fo << times.front() << \"\\t\" << diffs.front() << std::endl;\n    for (uint64_t i = 0; i < count; ++i)\n    {\n      currency::wide_difficulty_type w_diff = NEXT_DIFFICULTY_ALGO(times, diffs, DEFAULT_TEST_DIFFICULTY_TARGET);\n      currency::difficulty_type diff = w_diff.convert_to<uint64_t>();\n\n      fo << time << \"\\t\" << diff << std::endl;\n\n      times.push_back(time);\n      w_diff += diffs.front();\n      diffs.insert(diffs.begin(), w_diff);\n\n      while (times.size() > DIFFICULTY_WINDOW)\n        times.erase(times.begin());\n\n      while (diffs.size() > DIFFICULTY_WINDOW)\n        diffs.pop_back();\n\n      const uint64_t power_limit = std::find_if(std::begin(table_powers), std::end(table_powers), [i](const powers_t& e) -> bool\n      {\n        return i < e.step;\n      }) -> power;\n\n      const uint64_t power_rand = power_limit + std::rand() * power_limit / 5 / RAND_MAX; //  rnd = 20%\n      const uint64_t l = 120 * diff / power_rand;\n      time += l + 1;\n\n    }\n  CATCH_ENTRY(\"generate to: \" << file_name, false);\n  std::cout << \"Generated to: \" << file_name << std::endl;\n  return true;\n}\n\nnamespace po = boost::program_options;\n\nnamespace\n{\n  const command_line::arg_descriptor<bool> arg_generate = {\"generate\", \"Generate table\"};\n  const command_line::arg_descriptor<std::string> arg_file_name = {\"file\", \"File name\", \"data.txt\"};\n}\n\nint main(int argc, char *argv[]) {\n\n  epee::string_tools::set_module_name_and_folder(argv[0]);\n  epee::log_space::get_set_log_detalisation_level(true, LOG_LEVEL_4);\n  epee::log_space::log_singletone::add_logger(LOGGER_CONSOLE, NULL, NULL, LOG_LEVEL_4);\n\n  po::options_description desc_options(\"Allowed options\");\n  command_line::add_arg(desc_options, command_line::arg_help);\n  command_line::add_arg(desc_options, arg_generate);\n  command_line::add_arg(desc_options, arg_file_name);\n\n  po::variables_map vm;\n\n  bool r = command_line::handle_error_helper(desc_options, [&]()\n  {\n    po::store(po::parse_command_line(argc, argv, desc_options), vm);\n    if (command_line::has_arg(vm, command_line::arg_help))\n    {\n      std::cout << desc_options << std::endl;\n      return false;\n    }\n    po::notify(vm);\n    return true;\n  });\n  if (!r)\n    return EXIT_FAILURE;\n\n  const std::string file_name = command_line::get_arg(vm, arg_file_name);\n  if (command_line::has_arg(vm, arg_generate))\n    return generate(file_name) ? EXIT_SUCCESS : EXIT_FAILURE;\n\n  std::vector<uint64_t> timestamps;\n  timestamps.reserve(DIFFICULTY_WINDOW + 1);\n  std::vector<currency::wide_difficulty_type> wide_cumulative_difficulties;\n  wide_cumulative_difficulties.reserve(DIFFICULTY_WINDOW + 1);\n\n  TRY_ENTRY();\n    fs::ifstream data(file_name);\n    data.exceptions(std::fstream::badbit);\n    data.clear(data.rdstate());\n    uint64_t timestamp, difficulty;\n    currency::wide_difficulty_type wide_cumulative_difficulty = 0;\n    for (size_t n = 0; data >> timestamp >> difficulty; ++n)\n    {\n      currency::wide_difficulty_type wide_res = NEXT_DIFFICULTY_ALGO(timestamps, wide_cumulative_difficulties, DEFAULT_TEST_DIFFICULTY_TARGET);\n      if (wide_res.convert_to<uint64_t>() != difficulty) {\n        std::cout << \"Wrong wide difficulty for block \" << n << std::endl\n                  << \"Expected: \" << difficulty << std::endl\n                  << \"Found: \" << wide_res << std::endl;\n        return EXIT_FAILURE;\n      }\n\n      timestamps.push_back(timestamp);\n      if (timestamps.size() > DIFFICULTY_WINDOW)\n        timestamps.erase(timestamps.begin());\n\n      wide_cumulative_difficulties.insert(wide_cumulative_difficulties.begin(), wide_cumulative_difficulty += difficulty);\n      if (wide_cumulative_difficulties.size() > DIFFICULTY_WINDOW)\n        wide_cumulative_difficulties.pop_back();\n    }\n    if (!data.eof())\n      data.clear(std::fstream::badbit);\n  CATCH_ENTRY(\"difficulty test from: \" << file_name, EXIT_FAILURE);\n\n  std::cout << \"TEST SUCCESS\" << std::endl;\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "81c1667547ab31894d6435b0664bd160476e52f6", "size": 5284, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/difficulty/difficulty.cpp", "max_stars_repo_name": "Virie/Virie", "max_stars_repo_head_hexsha": "fc5ad5816678b06b88d08a6842e43d4205915b39", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-07T13:26:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-07T13:26:43.000Z", "max_issues_repo_path": "tests/difficulty/difficulty.cpp", "max_issues_repo_name": "Virie/Virie", "max_issues_repo_head_hexsha": "fc5ad5816678b06b88d08a6842e43d4205915b39", "max_issues_repo_licenses": ["MIT"], "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/difficulty/difficulty.cpp", "max_forks_repo_name": "Virie/Virie", "max_forks_repo_head_hexsha": "fc5ad5816678b06b88d08a6842e43d4205915b39", "max_forks_repo_licenses": ["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.2327044025, "max_line_length": 143, "alphanum_fraction": 0.6901968206, "num_tokens": 1384, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.47455686975157385}}
{"text": "#include <boost/math/special_functions/ellint_2.hpp>\n", "meta": {"hexsha": "104be5721ca954f5f27775cb48d31156b7861001", "size": 53, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_special_functions_ellint_2.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_special_functions_ellint_2.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_special_functions_ellint_2.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 26.5, "max_line_length": 52, "alphanum_fraction": 0.8301886792, "num_tokens": 14, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.4745568639716013}}
{"text": "//\n// Created by robinjodon on 29.04.20.\n//\n#include <cassert>\n#include <iostream>\n#include \"tbb/tbb.h\"\n#include \"InterlockingSolver_Ipopt.h\"\n#include <Eigen/SparseQR>\n#include \"Utility/SparseOperations.h\"\n\n#define HAVE_CSTDDEF\n#include <IpIpoptApplication.hpp>\n#undef HAVE_CSTDDEF\n\nusing namespace Ipopt;\n\n\nconst double COIN_DBL_MAX = std::numeric_limits<double>::max();\n\n\n/* ----------------------------------------------------------------------------------------------------------------- */\n/* ----IPOPT INTERLOCKING SOLVER------------------------------------------------------------------------------------ */\n/* ----------------------------------------------------------------------------------------------------------------- */\n\ntemplate<typename Scalar>\nbool InterlockingSolver_Ipopt<Scalar>::isTranslationalInterlocking(InterlockingSolver_Ipopt::pInterlockingData &data) {\n    vector<EigenTriple> tris;\n    Eigen::Vector2i size;\n\n    InterlockingSolver<Scalar>::computeTranslationalInterlockingMatrix(tris, size);\n\n    if (!checkSpecialCase(data, tris, false, size)) {\n        return false;\n    }\n\n    int num_var = size[1];\n    InterlockingSolver<Scalar>::appendAuxiliaryVariables(tris, size);\n    InterlockingSolver<Scalar>::appendMergeConstraints(tris, size, false);\n\n    return solve(data, tris, false, size[0], size[1], num_var);\n}\n\ntemplate<typename Scalar>\nbool InterlockingSolver_Ipopt<Scalar>::isRotationalInterlocking(InterlockingSolver_Ipopt::pInterlockingData &data) {\n    vector<EigenTriple> tris;\n    Eigen::Vector2i size;\n\n    InterlockingSolver<Scalar>::computeRotationalInterlockingMatrix(tris, size);\n\n//    std::cout << \"special case\" << std::endl;\n    if (!checkSpecialCase(data, tris, true, size)) {\n        return false;\n    }\n\n    int num_var = size[1];\n    InterlockingSolver<Scalar>::appendAuxiliaryVariables(tris, size);\n    InterlockingSolver<Scalar>::appendMergeConstraints(tris, size, true);\n\n//    std::cout << \"solve\" << std::endl;\n    return solve(data, tris, true, size[0], size[1], num_var);\n}\n\ntemplate<typename Scalar>\nbool InterlockingSolver_Ipopt<Scalar>::checkSpecialCase(pInterlockingData &data,\n                                                        vector<EigenTriple> copy_tris,\n                                                        bool rotationalInterlockingCheck,\n                                                        Eigen::Vector2i copy_size) {\n    return true;\n}\n\ntemplate<typename Scalar>\nbool InterlockingSolver_Ipopt<Scalar>::solve(InterlockingSolver_Ipopt::pInterlockingData &data, vector<EigenTriple> &tris,\n                                             bool rotationalInterlockingCheck,\n                                             int num_row,\n                                             int num_col,\n                                             int num_var) {\n\n\n    // [0] - Instance for Ipopt App and NLP\n    SmartPtr<IpoptProblem> interlock_pb = new IpoptProblem();       // problem to solve\n    SmartPtr<IpoptApplication> app = IpoptApplicationFactory();     // solver\n\n    // [1] - Define the matrix B\n    EigenSpMat b(num_row, num_col);\n    b.setFromTriplets(tris.begin(), tris.end());\n\n    interlock_pb->initialize(b);\n\n    // [2] - Set some options for the solver \n    app->Options()->SetIntegerValue(\"print_level\", 5);\n\n    // C.2 Termination\n    app->Options()->SetNumericValue(\"tol\", 1e-5);\n    app->Options()->SetNumericValue(\"acceptable_tol\", 1e-5);\n\n    // C.4 NLP\n    app->Options()->SetStringValue(\"jac_c_constant\", \"yes\");\n    app->Options()->SetStringValue(\"jac_d_constant\", \"yes\");\n    app->Options()->SetStringValue(\"hessian_constant\", \"yes\");\n\n    // C.7 Multiplier update\n    app->Options()->SetStringValue(\"alpha_for_y\", \"primal-and-full\");   // step size use the primal step size and full step if delta x \u00a1= alpha for y tol\n    app->Options()->SetNumericValue(\"alpha_for_y_tol\", 100);            // Tolerance for switching to full equality multiplier steps\n\n    // C.8 Line search \n    app->Options()->SetIntegerValue(\"max_soc\", 0);                      // Disable 2ndOrder correction for trial steps at each iter.\n\n    // C.10 Restoration phase\n    app->Options()->SetStringValue(\"expect_infeasible_problem\", \"yes\"); // enable heuristics to detect infeasibility quicker\n\n    // todo: Exiting if t > 0 and lambda = 0 \n\n    // C.11 Linear Solver \n    app->Options()->SetStringValue(\"linear_solver\", \"mumps\");           // only available yet with installed IPOPT lib\n    app->Options()->SetIntegerValue(\"min_refinement_steps\", 0);         // iterative refinement steps/linear solve. Default=1 (changes Sum of the final values of constraints)\n    app->Options()->SetIntegerValue(\"max_refinement_steps\", 5);         // \n    // C.20 MUMPS settings \n    //  pivot_order is the most significant parameter\n    //  * 1, 3 not accessible (can't install SCOTCH, 1 is manual mode)\n    //  * 2 (AMF) is very slow (approximate minimum fill)\n    //  * 4 (PORD) is slow.\n    //  * 0 (AMD) quite fast (approximate minimum degree ordering)\n    //  * 5 (METIS) is slow\n    //  * 6 (QAMD the fastest (aproximate minimum degree ordering + quasi-dense row detection)\n    //  * 77 (auto) seems to use AMD\n    app->Options()->SetIntegerValue(\"mumps_pivot_order\", 6);            // 0, 2, 6 are showing best perfs           (see MUMPS ICNTL(7))\n    app->Options()->SetIntegerValue(\"mumps_scaling\",   4);             // Huge differences (7 and 8 are slower),    (see MUMPS ICNTL(8))\n\n    // C.6 Barrier param\n    bool mehrotra = false;\n    if (mehrotra) { \n        // Runs Mehrotra predictor-corrector algo. Works well with LPs. A bit more aggressive but slightly slower than adaptive coupled with LOQO. \n        app->Options()->SetStringValue(\"mehrotra_algorithm\", \"yes\");\n        app->Options()->SetNumericValue(\"tol\", 1e+1);\n        app->Options()->SetNumericValue(\"acceptable_tol\", 1e+1);\n        app->Options()->SetIntegerValue(\"min_refinement_steps\", 0);         // iterative refinement steps/linear solve. Default=1 (changes Sum of the final values of constraints)\n        app->Options()->SetIntegerValue(\"max_refinement_steps\", 5);         // \n    } else { \n        app->Options()->SetStringValue(\"mu_strategy\", \"adaptive\");\n        /* Oracle for the new barrier param - Deetermines how the new barrier is computed in each \"free mode\" iteration\n         * probing/loqo/quality-function (default) */\n        app->Options()->SetStringValue(\"mu_oracle\", \"loqo\");\n    }\n\n    \n    // For debugging purposes\n    // app->Options()->SetStringValue(\"derivative_test\", \"first-order\");\n\n\n    // [3] - Intialize the IpoptApplication and process the options\n    ApplicationReturnStatus status;\n    status = app->Initialize();\n    if (status != Solve_Succeeded) {\n        printf(\"\\n\\n*** Error during initialization!\\n\");\n    }\n    \n    // [5] - Optimzation\n    status = app->OptimizeTNLP(interlock_pb);\n\n    if (status == Solve_Succeeded) {\n        printf(\"\\n\\n*** The problem solved!\\n\");\n    } else {\n        printf(\"\\n\\n*** The problem FAILED!\\n\");\n    }\n\n    unpackSolution(data, rotationalInterlockingCheck, interlock_pb->x_solution.data(), num_var);\n    if(interlock_pb->max_abs_t < 1E-4){\n        return true;\n    }\n    else{\n        return false;\n    }\n}\n\ntemplate<typename Scalar>\nvoid InterlockingSolver_Ipopt<Scalar>::unpackSolution(InterlockingSolver_Ipopt::pInterlockingData &data,\n                                                      bool rotationalInterlockingCheck,\n                                                      const double *solution,\n                                                      int num_var) {\n    data = make_shared<typename InterlockingSolver<Scalar>::InterlockingData>();\n    for (pContactGraphNode node: graph->nodes) {\n        Vector3 trans(0, 0, 0);\n        Vector3 rotate(0, 0, 0);\n        Vector3 center = (node->centroid).template cast<double>();\n        if (node->dynamicID != -1) {\n            if (rotationalInterlockingCheck) {\n                trans = Vector3(solution[node->dynamicID * 6],\n                                solution[node->dynamicID * 6 + 1],\n                                solution[node->dynamicID * 6 + 2]);\n                rotate = -Vector3(solution[node->dynamicID * 6 + 3],\n                                  solution[node->dynamicID * 6 + 4],\n                                  solution[node->dynamicID * 6 + 5]);\n            } else {\n                trans = Vector3(solution[node->dynamicID * 3],\n                                solution[node->dynamicID * 3 + 1],\n                                solution[node->dynamicID * 3 + 2]);\n            }\n        }\n\n        data->traslation.push_back(trans);\n        data->rotation.push_back(rotate);\n        data->center.push_back(center);\n\n//        std::cout << node->staticID << \":\" << trans.transpose() << \", \" << rotate.transpose() << std::endl;\n    }\n}\n\n/* ------------------------------------------------------------------------------------------------------------------ */\n/* ----IPOPT INTERLOCKING PROBLEM------------------------------------------------------------------------------------ */\n/* ------------------------------------------------------------------------------------------------------------------ */\n\n\nIpoptProblem::IpoptProblem() {\n    index_style = TNLP::C_STYLE;\n    big_m = 5E7;                    // a smaller bigM works 5e6, solving is faster but final lambda is not exactly 0 \n}\n\n// destructor\nIpoptProblem::~IpoptProblem() = default;\n\n\n// returns the problem dimensions\nbool IpoptProblem::get_nlp_info(int &n, int &m, int &nnz_jac_g, int &nnz_h_lag, IndexStyleEnum &_index_style) {\n    n = n_var;                                    // N+M variables [x, t, lamdba]\n    m = n_constraints;                            // M inequalities\n    nnz_jac_g = non_zero_jacobian_elements;       // non zero elements in Jacobian\n    nnz_h_lag = non_zero_hessian_elements;        // non-zero elements in Lagrangian Hessian\n    _index_style = index_style;                    // use the C style indexing (0-based)\n\n    return true;\n}\n\nbool IpoptProblem::initialize(EigenSpMat &mat) {\n    n_var_real = mat.cols() - mat.rows();         // variables without big M multiplier lambda and aux vars\n    n_var = 1 + mat.cols();                       // variables including big M multiplier and auxiliary vars\n    n_constraints = mat.rows();                   // Constraints inequalities\n\n    mat.prune(0.0, 1E-9);\n    b_coeff = mat; \n\n    set_vectors_dimensions();\n    \n    set_bounds_info();\n\n    append_bigm_variables(mat);\n\n    non_zero_jacobian_elements = b_coeff.nonZeros();     // non zero elements in Jacobian (initial B matrix + id(m,m))\n    non_zero_hessian_elements = 0;                             // non-zero elements in Lagrangian Hessian\n\n    return true;\n}\n\nvoid IpoptProblem::set_vectors_dimensions() {\n    // allocate size for x vector\n    x.resize(n_var);\n    x_solution.resize(n_var);\n\n    x_l.resize(n_var);\n    x_u.resize(n_var);\n\n    g_l.resize(n_constraints);\n    g_u.resize(n_constraints);\n}\n\nvoid IpoptProblem::append_bigm_variables(EigenSpMat &mat) {\n    b_coeff.conservativeResize(mat.rows(), n_var);\n    b_coeff.reserve(mat.nonZeros() + mat.rows());\n    for (int c = 0; c < mat.rows(); ++c) {\n        b_coeff.insert(c, n_var-1) = 1.0;\n    }\n    b_coeff.finalize();\n    b_coeff.prune(0.0, 1E-9);\n}\n\n// returns the variable bounds\nbool IpoptProblem::get_bounds_info(int n, Number *x_l, Number *x_u, int m, Number *g_l, Number *g_u) {\n\n    for (int i = 0; i < n_var; i++) {\n        x_l[i] = this->x_l[i];\n        x_u[i] = this->x_u[i];\n    }\n\n    for (int i = 0; i < this->n_constraints; i++) {\n        g_l[i] = this->g_l[i];\n        g_u[i] = this->g_u[i];\n    }\n\n    return true;\n}\n\nbool IpoptProblem::set_bounds_info() {\n    // Dynamic allocation\n\n    for (int i = 0; i < n_constraints; i++) {\n        g_l[i] = 0;\n        g_u[i] = COIN_DBL_MAX;\n    }\n\n    for (int i = 0; i < n_var; i++) {\n        if (i < n_var_real) {\n            // x_i is defined in R\n            x_l[i] = COIN_DBL_MAX * (-1.0);\n            x_u[i] = COIN_DBL_MAX;\n        } else {\n            // lambda and aux variables >= 0\n            x_l[i] = 0.0;\n            x_u[i] = COIN_DBL_MAX;  //don't need to be inifinite, 1 is enough. However unbounding reduce execution time\n        }\n    }\n    return true;\n}\n\n// returns the initial point for the problem\nbool IpoptProblem::get_starting_point(int n, bool init_x, Number *x, bool init_z, Number *z_L, Number *z_U,\n                                      int m, bool init_lambda, Number *lambda) {\n\n    for (int i = 0; i < n_var; i++) {\n        if (i < n_var_real) {\n            this->x[i] = x[i] = 0.0;\n        } else {\n            this->x[i] = x[i] = 0.0;  // note: setting 0 instead of 1 makes the code faster\n        }\n    }\n    return true;\n}\n\n// return the objective function\nbool IpoptProblem::eval_f(int n, const Number *x, bool new_x, Number &obj_value) {\n    this->obj_value = 0.0;\n    for (int i = 0; i < n_var-1; i++) {\n        if (i >= n_var_real)\n            obj_value -= x[i];\n    }\n    this->obj_value += x[this->n_var-1] * this->big_m;\n    \n    obj_value = this->obj_value;\n    return true;\n}\n\n// return the gradient of the objective function grad_{x} f(x)\nbool IpoptProblem::eval_grad_f(int n, const Number *x, bool new_x, Number *grad_f) {\n    // minus everywhere --> searching for maximum\n    // loop through n_var -1\n    for (int i = 0; i < n_var-1; i++)\n        if (i < n_var_real) {\n            grad_f[i] = 0.0;\n        } else {\n            grad_f[i] = -1.0;\n        }\n    // Last constribition: the big_m\n    grad_f[n_var-1] = big_m;\n    return true;\n}\n\n// return the value of the constraints: g(x)\n// Computes g = B * X\nbool IpoptProblem::eval_g(int n, const Number *x, bool new_x, int m, Number *g) {\n    Eigen::Map<const Eigen::VectorXd> vecx(x, n);\n    VectorXd vecg = b_coeff * vecx;\n    std::copy(vecg.data(), vecg.data() + m, g);\n    return true;\n}\n\n// return the triplet structure or values of the Jacobian\nbool IpoptProblem::eval_jac_g(int n, const Number *x, bool new_x,\n                              int m, int nele_jac, int *iRow, int *jCol, Number *values) {\n    if (values == nullptr) {\n        // return the 2 first triplet index row, col for the structure of the Jacobian\n        int idx = 0;\n        for (int k = 0; k < b_coeff.outerSize(); ++k) {\n            for (SparseMatrix<double>::InnerIterator it(b_coeff, k); it; ++it) {\n                iRow[idx] = it.row();\n                jCol[idx] = it.col();\n                idx++;\n            }\n        }\n    } else {\n        // loop through B sparse elements and get values.\n        int idx = 0;\n        for (int k = 0; k < b_coeff.outerSize(); ++k) {\n            for (SparseMatrix<double>::InnerIterator it(b_coeff, k); it; ++it) {\n                values[idx] = it.value();\n                idx++;\n            }\n        }\n\n    }\n    return true;\n}\n\n//return the structure or values of the Hessian\nbool IpoptProblem::eval_h(int n, const Number *x, bool new_x, Number obj_factor, int m, const Number *lambda,\n                          bool new_lambda, int nele_hess, int *iRow, int *jCol, Number *values) {\n\n    if (values == nullptr) {\n        // return the structure. This is a symmetric matrix, fill the lower left triangle only.\n        int idx = 0;\n        for (int row = 0; row < non_zero_hessian_elements; row++) {\n            for (int col = 0; col <= row; col++) {\n                iRow[idx] = row;\n                jCol[idx] = col;\n                idx++;\n            }\n        }\n    } else {\n        // Hessian is zero\n        // fixme: faster and neater declaration here\n        int idx = 0;\n        for (int k = 0; k < b_coeff.outerSize(); ++k) {\n            for (SparseMatrix<double>::InnerIterator it(b_coeff, k); it; ++it) {\n                values[idx] = 0;\n            }\n        }\n    }\n\n    return true;\n}\n\nvoid IpoptProblem::finalize_solution(SolverReturn status,\n                                     int n,\n                                     const Number *x,\n                                     const Number *z_L,\n                                     const Number *z_U,\n                                     int m,\n                                     const Number *g,\n                                     const Number *lambda,\n                                     Number obj_value,\n                                     const IpoptData *ip_data,\n                                     IpoptCalculatedQuantities *ip_cq) {\n\n\n    // For this example, we write the solution to the console\n    max_abs_t = 0;\n//    printf(\"Solution of the primal variables, x\\n\");\n    for (int i = 0; i < n; i++) {\n        this->x[i] = x_solution[i] = x[i];\n        if(i >= n_var_real && i < n_var - 1){\n            max_abs_t = std::max(x[i], max_abs_t);\n        }\n    }\n\n    printf(\"Maximum |t|:\\t %E\\n\", max_abs_t);\n    printf(\"Lambda     :\\t %E\\n\", x[n_var-1]);\n    \n    Number sum_g = 0;\n    for (int i = 0; i < m; i++)\n        sum_g+= std::abs(g[i]);\n    printf(\"Sum of the final values of the constraints:\\t %.3f\\n\", sum_g);\n}\n\n\nvoid TemporaryFunction_InterlockingSolver_Ipopt ()\n{\n    InterlockingSolver_Ipopt<double> solver(nullptr, nullptr);\n}\n\ntemplate class InterlockingSolver_Ipopt<float>;\ntemplate class InterlockingSolver_Ipopt<double>;", "meta": {"hexsha": "7da369443749e0a0fe91115a96d9e83a056a0a48", "size": 17250, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/TopoLite/Interlocking/InterlockingSolver_Ipopt.cpp", "max_stars_repo_name": "carlostapiarq/TopoLite", "max_stars_repo_head_hexsha": "d6eb9125518a88ea546917df5217978f34661b2c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2020-06-10T08:28:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-07T02:55:35.000Z", "max_issues_repo_path": "src/TopoLite/Interlocking/InterlockingSolver_Ipopt.cpp", "max_issues_repo_name": "carlostapiarq/TopoLite", "max_issues_repo_head_hexsha": "d6eb9125518a88ea546917df5217978f34661b2c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-06-08T12:21:49.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-10T07:56:42.000Z", "max_forks_repo_path": "src/TopoLite/Interlocking/InterlockingSolver_Ipopt.cpp", "max_forks_repo_name": "carlostapiarq/TopoLite", "max_forks_repo_head_hexsha": "d6eb9125518a88ea546917df5217978f34661b2c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-06-22T10:07:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-04T06:02:33.000Z", "avg_line_length": 37.6637554585, "max_line_length": 178, "alphanum_fraction": 0.5565217391, "num_tokens": 4263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.47455686397160124}}
{"text": "\n#include <boost/math/tools/roots.hpp>\n#include <boost/math/distributions/binomial.hpp>\n\n#include <sys/types.h>\n#include <sys/stat.h>\n#include <time.h>\n#include <sstream>\n#include <unordered_map>\n#include <iostream>\n\nusing namespace std;\nextern \"C\" double tau_c(double edit_error, int kmer_size, double MAX_ERROR,double MAX_EDIT_ERROR)\n{\n\t// cout << MAX_EDIT_ERROR << \"\\t\" << (MAX_ERROR - MAX_EDIT_ERROR) << endl;\n\tconst double ERROR_RATIO = (MAX_ERROR - MAX_EDIT_ERROR) / MAX_EDIT_ERROR;\n\t\n\tdouble gap_error = std::min(1.0, ERROR_RATIO * edit_error);\n\tdouble a = (1 - gap_error) / (1 + gap_error);\n\tdouble b = 1 / (2 * std::exp(kmer_size * edit_error) - 1);\n\treturn a * b;\n}\n\nextern \"C\" double solve_inverse_jaccard_c(int j, int kmer_size, double MAX_ERROR,double MAX_EDIT_ERROR)\n{\n\tif (j == 0)\n\t{\n\t\treturn 1;\n\t}\n\tif (j == 1)\n\t{\n\t\treturn 0;\n\t}\n\treturn boost::math::tools::newton_raphson_iterate([j, kmer_size,MAX_ERROR,MAX_EDIT_ERROR](double d){\n\t\tconst double ERROR_RATIO = (MAX_ERROR - MAX_EDIT_ERROR) / MAX_EDIT_ERROR;\n\t\tdouble E = exp(d * kmer_size);\n\t\treturn make_tuple(\n\t\t\t((1 - d * ERROR_RATIO) / (1 + d * ERROR_RATIO)) * (1.0 / (2 * E - 1)) - j,\n\t\t\t2 * (- kmer_size * E + ERROR_RATIO - 2 * ERROR_RATIO * E + E * kmer_size * pow(d * ERROR_RATIO, 2)) /\n\t\t\t\tpow((2 * E - 1) * (1 + d * ERROR_RATIO), 2)\n\t\t);\n\t}, 0.10, 0.0, 1.0, numeric_limits<double>::digits);\n}\n\n\nextern \"C\" double relaxed_jaccard_estimate_c(int s, int kmer_size, double  MAX_EDIT_ERROR, double MAX_ERROR, double result)\n{\n\t\n\tusing namespace boost::math;\n\tconst double CI = 0.75;\n\tconst double Q2 = (1.0 - CI) / 2; // one side interval probability\n\t// cout << \"tau\" << endl;\n\tresult = ceil(s * tau_c(MAX_EDIT_ERROR, kmer_size,MAX_ERROR,MAX_EDIT_ERROR));\n\t// cout << result << endl;\n\tfor (; result >= 0; result--) {\n\t\t\n\t\tdouble d = solve_inverse_jaccard_c(result / s, kmer_size,MAX_ERROR,MAX_EDIT_ERROR); // returns edit error\n\t\t\n\t\tdouble x = quantile(complement(binomial(s, tau_c(d, kmer_size,MAX_ERROR,MAX_EDIT_ERROR)), Q2)); // inverse binomial \n\t\tdouble low_d = solve_inverse_jaccard_c(x / s, kmer_size,MAX_ERROR,MAX_EDIT_ERROR);\n\t\tif (100 * (1 - low_d) < MAX_EDIT_ERROR) {\n\t\t\tresult++; \n\t\t\tbreak;\n\t\t}\n\t}\n\t\n\tresult = max(result, 0.0);\n\treturn result;\n}\n\n\nextern \"C\" int fun1(int a){\n\treturn a*4;\n}\n\n\n", "meta": {"hexsha": "fdc6295a60b5b7727cddf5eb82d9cdb3a7b1d362", "size": 2276, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Seq/util_c.cpp", "max_stars_repo_name": "mateog4712/SEDEF", "max_stars_repo_head_hexsha": "dc05b661854a96b934ee098bedb970a5040b697b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Seq/util_c.cpp", "max_issues_repo_name": "mateog4712/SEDEF", "max_issues_repo_head_hexsha": "dc05b661854a96b934ee098bedb970a5040b697b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Seq/util_c.cpp", "max_forks_repo_name": "mateog4712/SEDEF", "max_forks_repo_head_hexsha": "dc05b661854a96b934ee098bedb970a5040b697b", "max_forks_repo_licenses": ["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.5584415584, "max_line_length": 123, "alphanum_fraction": 0.6726713533, "num_tokens": 707, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4745568639716012}}
{"text": "#include <mass.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n\nBOOST_AUTO_TEST_SUITE(mass);\n\nBOOST_AUTO_TEST_CASE(capsule)\n{\n  float const rho = 1.0f;\n  float const R   = 1.0f;\n  float const H   = 2.0f;\n    \n  mass::Properties<float> P = mass::compute_capsule(rho,R,H);\n  \n  BOOST_CHECK( P.m_m   > 0.0f ); \n  BOOST_CHECK( P.m_Ixx > 0.0f ); \n  BOOST_CHECK( P.m_Iyy > 0.0f ); \n  BOOST_CHECK( P.m_Izz > 0.0f ); \n  BOOST_CHECK_CLOSE( P.m_Ixx, P.m_Izz, 0.01f );\n  BOOST_CHECK( P.m_Izz > P.m_Iyy );  \n  \n  BOOST_CHECK(  P.is_body_space() );  \n  BOOST_CHECK( !P.is_model_space() );  \n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "2d78ab3716b6d2d17e0a2e61232b7dc5f6f5e9d0", "size": 767, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/SIMULATION/MASS/unit_tests/mass_capsule/mass_capsule.cpp", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-11-27T09:44:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-13T00:24:21.000Z", "max_issues_repo_path": "PROX/SIMULATION/MASS/unit_tests/mass_capsule/mass_capsule.cpp", "max_issues_repo_name": "erleben/matchstick", "max_issues_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_issues_repo_licenses": ["MIT"], "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/SIMULATION/MASS/unit_tests/mass_capsule/mass_capsule.cpp", "max_forks_repo_name": "erleben/matchstick", "max_forks_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_forks_repo_licenses": ["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.7419354839, "max_line_length": 61, "alphanum_fraction": 0.6883963494, "num_tokens": 249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956580806813577, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.47455685241165535}}
{"text": "\n/*\ngammaGenerator.cpp - This file is part of the Bayesembler (v1.1.1)\n\n\nThe MIT License (MIT)\n\nCopyright (c) 2014 Lasse Maretty and Jonas Andreas Sibbesen\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*/\n\n\n#include <math.h>\n#include <gammaGenerator.h>\n#include <boost/math/constants/constants.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/math/distributions/gamma.hpp>\n#include <boost/math/distributions/lognormal.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <boost/random/gamma_distribution.hpp>\n#include <boost/random/lognormal_distribution.hpp>\n\n\n/*\n Gamma-sampler class\n */\n\nSymmetricGammaGenerator::SymmetricGammaGenerator(HyperPrior * hyper_prior_in, int slice_iterations_in, double slice_window_size_in, int slice_max_windows_in, boost::random::mt19937* mt_rng_pt_in) {\n\n    hyper_prior = hyper_prior_in;\n    slice_iterations = slice_iterations_in;\n    slice_window_size = slice_window_size_in;\n    slice_max_windows = slice_max_windows_in;\n\tmt_rng_pt = mt_rng_pt_in;\n}\n\n\n// Init gamma with sample from the hyperprior\ndouble SymmetricGammaGenerator::initGamma() {\n\t\t\n\treturn hyper_prior->init();\n}\n\ndouble SymmetricGammaGenerator::generateGamma(ExpressionValueContainer expression) {\n    \n\tvector<double> expression_s_plus;\n\t\n\tfor (int i = 0; i < expression.getPlusSize(); i++) {\n\t\t\n\t\tint idx = expression.getPlus(i);\n\t\tdouble value = expression.getValue(idx);\n\t\texpression_s_plus.push_back(value);\n    }\n\t\n    // Init gamma and uniform sampler\n    uniform_01_sampler_t sample_uniform_01(mt_rng_pt);\n\t    \n    double gamma_current = sample_uniform_01();\n\n\tif (gamma_current < double_underflow) {\n\t\t\n\t\tgamma_current = double_underflow;\t\t\n\t}\n\t\n\tdouble gamma = gamma_current;\n\t\t    \n\tfor (int i=0; i < slice_iterations; i++) {\n\t    \n        double y = calculateLogDensity(expression_s_plus, gamma_current) + hyper_prior->calculateLogDensity(gamma_current) + log(1-sample_uniform_01());\t\t\t\n\t\t\n        // Find slice by \"step-out\"\n        double left = gamma_current - sample_uniform_01() * slice_window_size;\n        double right = left + slice_window_size;\n\t        \n        int j = floor(slice_max_windows*sample_uniform_01());\n        int k = slice_max_windows-1-j;\n\t\t\t\n\t\t// Truncate at zero\n        if (left < double_underflow) {\n\t            \n            left = double_underflow;\n            j = 0;\n        }\n\n        while (j > 0 && y < (calculateLogDensity(expression_s_plus, left) + hyper_prior->calculateLogDensity(left))) {\n\t\t\t\n\t\t\tleft = left - slice_window_size;\n            j--;\n\n            if (left < double_underflow) {\n\n                left = double_underflow;\n                break;\n            }\n\t\t}\n\t\n        // Expand window to the right\n        while (k > 0 && y < (calculateLogDensity(expression_s_plus, right) + hyper_prior->calculateLogDensity(right))) {\n\t\t\t\n\t\t\tright = right + slice_window_size;\n            k--;\n        }\n\t\t\t\n\t\t// Sample from the window until in slice\n\t\tgamma = sample_uniform_01()*(right-left) + left;\n\t    \n\t\twhile ( y >= (calculateLogDensity(expression_s_plus, gamma) + hyper_prior->calculateLogDensity(gamma))) {\n\t\t\t  \n\t\t\tif (gamma < gamma_current) {\n\t\t\t\t\n\t\t\t\tleft = gamma;\n\t\t\t\tgamma = sample_uniform_01()*(right-left) + left;\n\t\t\t\t\t\t\t\t\n\t\t\t} else {\n\t\t\t\t\t\n\t\t\t\tright = gamma;\n\t\t\t\tgamma = sample_uniform_01()*(right-left) + left;\n\t\t\t}\n\t\t}\n\n\t\tgamma_current = gamma;\t\n\t}\n\t    \n    return gamma;\t\t\n\t\n}\n\ndouble SymmetricGammaGenerator::calculateLogDensity(vector<double>& expression, double gamma) {\n    \n    int size = expression.size();\n    \n    // Init prob with normalisation constant\n    double prob = boost::math::lgamma(size*gamma) - size*boost::math::lgamma(gamma);\n    \n    for (int i=0; i < size; i++) {\n        prob += (gamma-1)*log(expression[i]);\n    }\n    \n    return prob;\n}\n\nFixedGammaGenerator::FixedGammaGenerator(double gamma_in) {\n    gamma = gamma_in;\n}\n\ndouble FixedGammaGenerator::initGamma() {\n\t\n\treturn gamma;\n}\n\ndouble FixedGammaGenerator::generateGamma(ExpressionValueContainer expression) {\n      \n    return gamma;\n}\n\n\nGammaHyperPrior::GammaHyperPrior(double shape_in, double scale_in, mt_rng_pt_t mt_rng_pt_in) {\n\n    shape = shape_in;\n    scale = scale_in;\n\tmt_rng_pt = mt_rng_pt_in;\n};\n\ndouble GammaHyperPrior::init() {\n\t\n\tboost::random::gamma_distribution<> gamma_dist(shape, scale);\n\tboost::random::variate_generator<boost::random::mt19937*, boost::random::gamma_distribution<> > sample_gamma(mt_rng_pt, gamma_dist);\n\t\n\tdouble gamma = sample_gamma();\n\t\n\treturn gamma;\n}\n\ndouble GammaHyperPrior::calculateLogDensity(double gamma) {\n    \t\n\tdouble prob = (shape-1)*log(gamma) - (gamma/scale);\n\t\n    return prob;\n    \n};\n\n\nLogNormalHyperPrior::LogNormalHyperPrior(double location_in, double scale_in, mt_rng_pt_t mt_rng_pt_in) {\n    \n    location = location_in;\n    scale = scale_in;\n\tmt_rng_pt = mt_rng_pt_in;\n}\n\ndouble LogNormalHyperPrior::init() {\n    \n\tboost::random::lognormal_distribution<> lognormal_dist(location, scale);\n\tboost::random::variate_generator<boost::random::mt19937*, boost::random::lognormal_distribution<> > sample_gamma(mt_rng_pt, lognormal_dist);\n    \n\tdouble gamma = sample_gamma();\n\t\n\treturn gamma;\n}\n\ndouble LogNormalHyperPrior::calculateLogDensity(double gamma) {\n    \t\t\n\tdouble prob = - log(gamma) - pow(log(gamma)-location,2)/(2*pow(scale,2));\t\n    \n    return prob;\n}\n\n\n\n", "meta": {"hexsha": "76239975a019ff7a8095b7f41e9b9ffdbc5e73b6", "size": 6277, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/gammaGenerator.cpp", "max_stars_repo_name": "bhurwitz33/bayesembler", "max_stars_repo_head_hexsha": "b1d8200d5ffa2ae3476391d9f35f26e5f14f517f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-10T15:43:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-10T15:43:12.000Z", "max_issues_repo_path": "src/gammaGenerator.cpp", "max_issues_repo_name": "bhurwitz33/bayesembler", "max_issues_repo_head_hexsha": "b1d8200d5ffa2ae3476391d9f35f26e5f14f517f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gammaGenerator.cpp", "max_forks_repo_name": "bhurwitz33/bayesembler", "max_forks_repo_head_hexsha": "b1d8200d5ffa2ae3476391d9f35f26e5f14f517f", "max_forks_repo_licenses": ["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.7743362832, "max_line_length": 197, "alphanum_fraction": 0.7030428549, "num_tokens": 1476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.4745441874731069}}
{"text": "/* Copyright 2020 CNRS-AIST JRL */\n\n#include <Eigen/Core>\n\n#include <benchmark/benchmark.h>\n\n#include \"common.h\"\n\nusing namespace Eigen;\n\n// A = B\nstatic void BM_Copy_MatrixXd(benchmark::State & state)\n{\n  MatrixXd source = MatrixXd::Random(state.range(0), state.range(0));\n  MatrixXd target(state.range(0), state.range(0));\n\n  for(auto _ : state) target = source;\n}\n\n// A = B^T\nstatic void BM_Copy_MatrixXd_Source_Transpose(benchmark::State & state)\n{\n  MatrixXd source = MatrixXd::Random(state.range(0), state.range(0));\n  MatrixXd target(state.range(0), state.range(0));\n\n  for(auto _ : state) target = source.transpose();\n}\n\n// A^T = B\nstatic void BM_Copy_MatrixXd_Target_Transpose(benchmark::State & state)\n{\n  MatrixXd source = MatrixXd::Random(state.range(0), state.range(0));\n  MatrixXd target(state.range(0), state.range(0));\n\n  for(auto _ : state) target.transpose() = source;\n}\n\n// A += B\nstatic void BM_Add_MatrixXd(benchmark::State & state)\n{\n  MatrixXd source = MatrixXd::Random(state.range(0), state.range(0));\n  MatrixXd target(state.range(0), state.range(0));\n\n  for(auto _ : state) target += source;\n}\n\n// A += B^T\nstatic void BM_Add_MatrixXd_Source_Transpose(benchmark::State & state)\n{\n  MatrixXd source = MatrixXd::Random(state.range(0), state.range(0));\n  MatrixXd target(state.range(0), state.range(0));\n\n  for(auto _ : state) target += source.transpose();\n}\n\n// A += B^T\nstatic void BM_Add_MatrixXd_Target_Transpose(benchmark::State & state)\n{\n  MatrixXd source = MatrixXd::Random(state.range(0), state.range(0));\n  MatrixXd target(state.range(0), state.range(0));\n\n  for(auto _ : state) target.transpose() += source;\n}\n\n// y = A*x\nstatic void BM_Mult_VectorXd(benchmark::State & state)\n{\n  MatrixXd A = MatrixXd::Random(state.range(0), state.range(0));\n  VectorXd x = VectorXd::Random(state.range(0));\n  VectorXd y(state.range(0));\n\n  for(auto _ : state) y.noalias() = A * x;\n}\n\n// row = (A*x)^T\nstatic void BM_Mult_VectorXd_Source_Transpose(benchmark::State & state)\n{\n  MatrixXd A = MatrixXd::Random(state.range(0), state.range(0));\n  VectorXd x = VectorXd::Random(state.range(0));\n  MatrixXd y(2, state.range(0));\n\n  for(auto _ : state) y.row(1).noalias() = (A * x).transpose();\n}\n\n// row^T = A*x\nstatic void BM_Mult_VectorXd_Target_Transpose(benchmark::State & state)\n{\n  MatrixXd A = MatrixXd::Random(state.range(0), state.range(0));\n  VectorXd x = VectorXd::Random(state.range(0));\n  MatrixXd y(2, state.range(0));\n\n  for(auto _ : state) y.row(1).transpose().noalias() = A * x;\n}\n\n// y = L*x\nstatic void BM_Mult_VectorXd_Triangular(benchmark::State & state)\n{\n  MatrixXd A = MatrixXd::Random(state.range(0), state.range(0));\n  VectorXd x = VectorXd::Random(state.range(0));\n  VectorXd y(state.range(0));\n\n  for(auto _ : state) y.noalias() = A.template triangularView<Lower>() * x;\n}\n\n// y = L*x\nstatic void BM_Mult_VectorXd_TriangularOptim4(benchmark::State & state)\n{\n  MatrixXd A = MatrixXd::Random(state.range(0), state.range(0));\n  A.template triangularView<StrictlyUpper>().setZero();\n  VectorXd x = VectorXd::Random(state.range(0));\n  VectorXd y(state.range(0));\n\n  const int bsize = 4;\n  for(auto _ : state)\n  {\n    int nBlock = A.cols() / bsize;\n    y.setZero();\n    int s = 0;\n    int r = A.cols();\n    for(int i = 0; i < nBlock; ++i)\n    {\n      y.tail(r).noalias() += A.block(s, s, r, bsize) * x.segment(s, bsize);\n      s += bsize;\n      r -= bsize;\n    }\n    y.tail(r).noalias() += A.bottomRightCorner(r, r) * x.tail(r);\n  }\n}\n\n// y = L*x\nstatic void BM_Mult_VectorXd_TriangularOptim8(benchmark::State & state)\n{\n  MatrixXd A = MatrixXd::Random(state.range(0), state.range(0));\n  A.template triangularView<StrictlyUpper>().setZero();\n  VectorXd x = VectorXd::Random(state.range(0));\n  VectorXd y(state.range(0));\n\n  const int bsize = 8;\n  for(auto _ : state)\n  {\n    int nBlock = A.cols() / bsize;\n    y.setZero();\n    int s = 0;\n    int r = A.cols();\n    for(int i = 0; i < nBlock; ++i)\n    {\n      y.tail(r).noalias() += A.block(s, s, r, bsize) * x.segment(s, bsize);\n      s += bsize;\n      r -= bsize;\n    }\n    y.tail(r).noalias() += A.bottomRightCorner(r, r) * x.tail(r);\n  }\n}\n\n// y = L*x\nstatic void BM_Mult_VectorXd_TriangularOptim16(benchmark::State & state)\n{\n  MatrixXd A = MatrixXd::Random(state.range(0), state.range(0));\n  A.template triangularView<StrictlyUpper>().setZero();\n  VectorXd x = VectorXd::Random(state.range(0));\n  VectorXd y(state.range(0));\n\n  const int bsize = 16;\n  for(auto _ : state)\n  {\n    int nBlock = A.cols() / bsize;\n    y.setZero();\n    int s = 0;\n    int r = A.cols();\n    for(int i = 0; i < nBlock; ++i)\n    {\n      y.tail(r).noalias() += A.block(s, s, r, bsize) * x.segment(s, bsize);\n      s += bsize;\n      r -= bsize;\n    }\n    y.tail(r).noalias() += A.bottomRightCorner(r, r) * x.tail(r);\n  }\n}\n\n// C = A*B\nstatic void BM_Mult_MatrixXd(benchmark::State & state)\n{\n  MatrixXd A = MatrixXd::Random(state.range(0), state.range(0));\n  MatrixXd B = MatrixXd::Random(state.range(0), state.range(0));\n  MatrixXd target(state.range(0), state.range(0));\n\n  for(auto _ : state) target.noalias() = A * B;\n}\n\n// C = A^T*B\nstatic void BM_Mult_MatrixXd_AT(benchmark::State & state)\n{\n  MatrixXd A = MatrixXd::Random(state.range(0), state.range(0));\n  MatrixXd B = MatrixXd::Random(state.range(0), state.range(0));\n  MatrixXd target(state.range(0), state.range(0));\n\n  for(auto _ : state) target.noalias() = A.transpose() * B;\n}\n\n// C = A*B^T\nstatic void BM_Mult_MatrixXd_BT(benchmark::State & state)\n{\n  MatrixXd A = MatrixXd::Random(state.range(0), state.range(0));\n  MatrixXd B = MatrixXd::Random(state.range(0), state.range(0));\n  MatrixXd target(state.range(0), state.range(0));\n\n  for(auto _ : state) target.noalias() = A * B.transpose();\n}\n\n// C = A^T*B^T\nstatic void BM_Mult_MatrixXd_AT_BT(benchmark::State & state)\n{\n  MatrixXd A = MatrixXd::Random(state.range(0), state.range(0));\n  MatrixXd B = MatrixXd::Random(state.range(0), state.range(0));\n  MatrixXd target(state.range(0), state.range(0));\n\n  for(auto _ : state) target.noalias() = A.transpose() * B.transpose();\n}\n\n// C^T = A*B\nstatic void BM_Mult_MatrixXd_Target_Transpose(benchmark::State & state)\n{\n  MatrixXd A = MatrixXd::Random(state.range(0), state.range(0));\n  MatrixXd B = MatrixXd::Random(state.range(0), state.range(0));\n  MatrixXd target(state.range(0), state.range(0));\n\n  for(auto _ : state) target.transpose().noalias() = A * B;\n}\n\n// Y = L*X\nstatic void BM_Mult_MatrixXd_Triangular(benchmark::State & state)\n{\n  MatrixXd A = MatrixXd::Random(state.range(0), state.range(0));\n  MatrixXd B = MatrixXd::Random(state.range(0), state.range(0));\n  MatrixXd C = MatrixXd::Random(state.range(0), state.range(0));\n\n  for(auto _ : state) C.noalias() = A.template triangularView<Lower>() * B;\n}\n\n// y = L*x\nstatic void BM_Mult_MatrixXd_TriangularOptim4(benchmark::State & state)\n{\n  MatrixXd A = MatrixXd::Random(state.range(0), state.range(0));\n  A.template triangularView<StrictlyUpper>().setZero();\n  MatrixXd B = MatrixXd::Random(state.range(0), state.range(0));\n  MatrixXd C = MatrixXd::Random(state.range(0), state.range(0));\n\n  const int bsize = 4;\n  for(auto _ : state)\n  {\n    int nBlock = A.cols() / bsize;\n    C.setZero();\n    int s = 0;\n    int r = A.cols();\n    for(int i = 0; i < nBlock; ++i)\n    {\n      C.bottomRows(r).noalias() += A.block(s, s, r, bsize) * B.middleRows(s, bsize);\n      s += bsize;\n      r -= bsize;\n    }\n    C.bottomRows(r).noalias() += A.bottomRightCorner(r, r) * B.bottomRows(r);\n  }\n}\n\n// y = L*x\nstatic void BM_Mult_MatrixXd_TriangularOptim8(benchmark::State & state)\n{\n  MatrixXd A = MatrixXd::Random(state.range(0), state.range(0));\n  A.template triangularView<StrictlyUpper>().setZero();\n  MatrixXd B = MatrixXd::Random(state.range(0), state.range(0));\n  MatrixXd C = MatrixXd::Random(state.range(0), state.range(0));\n\n  const int bsize = 8;\n  for(auto _ : state)\n  {\n    int nBlock = A.cols() / bsize;\n    C.setZero();\n    int s = 0;\n    int r = A.cols();\n    for(int i = 0; i < nBlock; ++i)\n    {\n      C.bottomRows(r).noalias() += A.block(s, s, r, bsize) * B.middleRows(s, bsize);\n      s += bsize;\n      r -= bsize;\n    }\n    C.bottomRows(r).noalias() += A.bottomRightCorner(r, r) * B.bottomRows(r);\n  }\n}\n\n// y = L*x\nstatic void BM_Mult_MatrixXd_TriangularOptim16(benchmark::State & state)\n{\n  MatrixXd A = MatrixXd::Random(state.range(0), state.range(0));\n  A.template triangularView<StrictlyUpper>().setZero();\n  MatrixXd B = MatrixXd::Random(state.range(0), state.range(0));\n  MatrixXd C = MatrixXd::Random(state.range(0), state.range(0));\n\n  const int bsize = 16;\n  for(auto _ : state)\n  {\n    int nBlock = A.cols() / bsize;\n    C.setZero();\n    int s = 0;\n    int r = A.cols();\n    for(int i = 0; i < nBlock; ++i)\n    {\n      C.bottomRows(r).noalias() += A.block(s, s, r, bsize) * B.middleRows(s, bsize);\n      s += bsize;\n      r -= bsize;\n    }\n    C.bottomRows(r).noalias() += A.bottomRightCorner(r, r) * B.bottomRows(r);\n  }\n}\n\n// y = D*x\nstatic void BM_Mult_Diagonal_VectorXd(benchmark::State & state)\n{\n  VectorXd d = VectorXd::Random(state.range(0));\n  VectorXd x = VectorXd::Random(state.range(0));\n  VectorXd y(state.range(0));\n\n  for(auto _ : state) y.noalias() = d.asDiagonal() * x;\n}\n\n// y = d*x\nstatic void BM_Mult_scalar_VectorXd(benchmark::State & state)\n{\n  double d = VectorXd::Random(1)[0];\n  VectorXd x = VectorXd::Random(state.range(0));\n  VectorXd y(state.range(0));\n\n  for(auto _ : state) y.noalias() = d * x;\n}\n\n// MAT_BENCHMARK(BM_Copy_MatrixXd);\n// MAT_BENCHMARK(BM_Copy_MatrixXd_Source_Transpose);\n// MAT_BENCHMARK(BM_Copy_MatrixXd_Target_Transpose);\n// MAT_BENCHMARK(BM_Add_MatrixXd);\n// MAT_BENCHMARK(BM_Add_MatrixXd_Source_Transpose);\n// MAT_BENCHMARK(BM_Add_MatrixXd_Target_Transpose);\n// MAT_BENCHMARK(BM_Mult_VectorXd);\n// MAT_BENCHMARK(BM_Mult_VectorXd_Source_Transpose);\n// MAT_BENCHMARK(BM_Mult_VectorXd_Target_Transpose);\n// MAT_BENCHMARK(BM_Mult_VectorXd_Triangular);\n// MAT_BENCHMARK(BM_Mult_VectorXd_TriangularOptim4);\n// MAT_BENCHMARK(BM_Mult_VectorXd_TriangularOptim8);\n// MAT_BENCHMARK(BM_Mult_VectorXd_TriangularOptim16);\nMAT_BENCHMARK(BM_Mult_MatrixXd);\n// MAT_BENCHMARK(BM_Mult_MatrixXd_AT);\n// MAT_BENCHMARK(BM_Mult_MatrixXd_BT);\n// MAT_BENCHMARK(BM_Mult_MatrixXd_AT_BT);\n// MAT_BENCHMARK(BM_Mult_MatrixXd_Target_Transpose);\n// MAT_BENCHMARK(BM_Mult_MatrixXd_Triangular);\n// MAT_BENCHMARK(BM_Mult_MatrixXd_TriangularOptim4);\n// MAT_BENCHMARK(BM_Mult_MatrixXd_TriangularOptim8);\n// MAT_BENCHMARK(BM_Mult_MatrixXd_TriangularOptim16);\nMAT_BENCHMARK(BM_Mult_Diagonal_VectorXd);\nMAT_BENCHMARK(BM_Mult_scalar_VectorXd);\n\nBENCHMARK_MAIN();\n", "meta": {"hexsha": "4be42adea2d740066f268af57cc2758fd1e14f06", "size": 10582, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "benchmarks/BasicEigen.cpp", "max_stars_repo_name": "mehdi-benallegue/jrl-qp", "max_stars_repo_head_hexsha": "b6d2268dcd1e91708585474b3f0f93c9104887c0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2020-08-20T09:06:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T03:42:58.000Z", "max_issues_repo_path": "benchmarks/BasicEigen.cpp", "max_issues_repo_name": "mehdi-benallegue/jrl-qp", "max_issues_repo_head_hexsha": "b6d2268dcd1e91708585474b3f0f93c9104887c0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-11-21T10:29:57.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-21T11:13:41.000Z", "max_forks_repo_path": "benchmarks/BasicEigen.cpp", "max_forks_repo_name": "mehdi-benallegue/jrl-qp", "max_forks_repo_head_hexsha": "b6d2268dcd1e91708585474b3f0f93c9104887c0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-09-04T12:11:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-04T12:11:44.000Z", "avg_line_length": 29.3130193906, "max_line_length": 84, "alphanum_fraction": 0.6668871669, "num_tokens": 3221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.4745441833958513}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2015 Jose Aparicio\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n#ifndef quantlib_cva_swap_engine_hpp\n#define quantlib_cva_swap_engine_hpp\n\n#include <ql/handle.hpp>\n#include <ql/instruments/vanillaswap.hpp>\n#include <ql/termstructures/defaulttermstructure.hpp>\n\nnamespace QuantLib {\n\n    class YieldTermStructure;\n    class Quote;\n\n  /*! Bilateral (CVA and DVA) default adjusted vanilla swap pricing\n    engine. Collateral is not considered. No wrong way risk is \n    considered (rates and counterparty default are uncorrelated).\n    Based on:\n    Sorensen,  E.H.  and  Bollier,  T.F.,  Pricing  swap  default \n    risk. Financial Analysts Journal, 1994, 50, 23\u201333\n    Also see sect. II-5 in: Risk Neutral Pricing of Counterparty Risk\n    D. Brigo, M. Masetti, 2004\n    or in sections 3 and 4 of \"A Formula for Interest Rate Swaps \n      Valuation under Counterparty Risk in presence of Netting Agreements\"\n    D. Brigo and M. Masetti; May 4, 2005\n\n    to do: Compute fair rate through iteration instead of the \n    current approximation .\n    to do: write Issuer based constructors (event type)\n    to do: Check consistency between option engine discount and the one given\n   */\n  class CounterpartyAdjSwapEngine : public VanillaSwap::engine {\n    public:\n      //! \\name Constructors\n      //@{\n      //! \n      /*! Creates the engine from an arbitrary swaption engine.\n        If the investor default model is not given a default \n        free one is assumed.\n        @param discountCurve Used in pricing.\n        @param swaptionEngine Determines the volatility and thus the \n        exposure model.\n        @param ctptyDTS Counterparty default curve.\n        @param ctptyRecoveryRate Counterparty recovey rate.\n        @param invstDTS Investor (swap holder) default curve.\n        @param invstRecoveryRate Investor recovery rate.\n       */\n      CounterpartyAdjSwapEngine(\n          const Handle<YieldTermStructure>& discountCurve,\n          const Handle<PricingEngine>& swaptionEngine,\n          const Handle<DefaultProbabilityTermStructure>& ctptyDTS,\n          Real ctptyRecoveryRate,\n          const Handle<DefaultProbabilityTermStructure>& invstDTS =\n              Handle<DefaultProbabilityTermStructure>(),\n          Real invstRecoveryRate = 0.999);\n      /*! Creates an engine with a black volatility model for the \n        exposure.\n        If the investor default model is not given a default \n        free one is assumed.\n        @param discountCurve Used in pricing.\n        @param blackVol Black volatility used in the exposure model.\n        @param ctptyDTS Counterparty default curve.\n        @param ctptyRecoveryRate Counterparty recovey rate.\n        @param invstDTS Investor (swap holder) default curve.\n        @param invstRecoveryRate Investor recovery rate.\n       */\n      CounterpartyAdjSwapEngine(\n          const Handle<YieldTermStructure>& discountCurve,\n          const Volatility blackVol,\n          const Handle<DefaultProbabilityTermStructure>& ctptyDTS,\n          Real ctptyRecoveryRate,\n          const Handle<DefaultProbabilityTermStructure>& invstDTS =\n              Handle<DefaultProbabilityTermStructure>(),\n          Real invstRecoveryRate = 0.999);\n      /*! Creates an engine with a black volatility model for the \n        exposure. The volatility is given as a quote.\n        If the investor default model is not given a default \n        free one is assumed.\n        @param discountCurve Used in pricing.\n        @param blackVol Black volatility used in the exposure model.\n        @param ctptyDTS Counterparty default curve.\n        @param ctptyRecoveryRate Counterparty recovey rate.\n        @param invstDTS Investor (swap holder) default curve.\n        @param invstRecoveryRate Investor recovery rate.\n      */\n      CounterpartyAdjSwapEngine(\n          const Handle<YieldTermStructure>& discountCurve,\n          const Handle<Quote>& blackVol,\n          const Handle<DefaultProbabilityTermStructure>& ctptyDTS,\n          Real ctptyRecoveryRate,\n          const Handle<DefaultProbabilityTermStructure>& invstDTS =\n              Handle<DefaultProbabilityTermStructure>(),\n          Real invstRecoveryRate = 0.999);\n      //@}\n      void calculate() const;\n    private:\n      Handle<PricingEngine> baseSwapEngine_;\n      Handle<PricingEngine> swaptionletEngine_;\n      Handle<YieldTermStructure> discountCurve_;\n      Handle<DefaultProbabilityTermStructure> defaultTS_;\t  \n      Real ctptyRecoveryRate_;\n      Handle<DefaultProbabilityTermStructure> invstDTS_;\t  \n      Real invstRecoveryRate_;\n  };\n\n}\n\n\n/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2015 Jose Aparicio\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n#include <ql/cashflows/fixedratecoupon.hpp>\n#include <ql/cashflows/floatingratecoupon.hpp>\n#include <ql/indexes/iborindex.hpp>\n#include <ql/instruments/makevanillaswap.hpp>\n#include <ql/exercise.hpp>\n#include <ql/pricingengines/swap/discountingswapengine.hpp>\n#include <ql/termstructures/credit/flathazardrate.hpp>\n#include <ql/pricingengines/swaption/blackswaptionengine.hpp>\n#include <boost/make_shared.hpp>\n\nnamespace QuantLib {\n  \n  inline CounterpartyAdjSwapEngine::CounterpartyAdjSwapEngine(\n      const Handle<YieldTermStructure>& discountCurve,\n      const Handle<PricingEngine>& swaptionEngine,\n      const Handle<DefaultProbabilityTermStructure>& ctptyDTS,\n      Real ctptyRecoveryRate,\n      const Handle<DefaultProbabilityTermStructure>& invstDTS,\n      Real invstRecoveryRate)\n  : baseSwapEngine_(Handle<PricingEngine>(\n      boost::make_shared<DiscountingSwapEngine>(discountCurve))),\n    swaptionletEngine_(swaptionEngine),\n    discountCurve_(discountCurve),\n    defaultTS_(ctptyDTS), \n    ctptyRecoveryRate_(ctptyRecoveryRate),\n    invstDTS_(invstDTS.empty() ? Handle<DefaultProbabilityTermStructure>(\n        boost::make_shared<FlatHazardRate>(0, ctptyDTS->calendar(), 1.e-12, \n        ctptyDTS->dayCounter()) ) : invstDTS ),\n    invstRecoveryRate_(invstRecoveryRate)\n  {\n      registerWith(discountCurve);\n      registerWith(ctptyDTS);\n      registerWith(invstDTS_);\n      registerWith(swaptionEngine);\n  }\n\n    inline CounterpartyAdjSwapEngine::CounterpartyAdjSwapEngine(\n        const Handle<YieldTermStructure>& discountCurve,\n        const Volatility blackVol,\n        const Handle<DefaultProbabilityTermStructure>& ctptyDTS,\n        Real ctptyRecoveryRate,\n        const Handle<DefaultProbabilityTermStructure>& invstDTS,\n        Real invstRecoveryRate)\n  : baseSwapEngine_(Handle<PricingEngine>(\n      boost::make_shared<DiscountingSwapEngine>(discountCurve))),\n    swaptionletEngine_(Handle<PricingEngine>(\n      boost::make_shared<BlackSwaptionEngine>(discountCurve,\n        blackVol))),\n    discountCurve_(discountCurve),\n    defaultTS_(ctptyDTS), \n    ctptyRecoveryRate_(ctptyRecoveryRate),\n    invstDTS_(invstDTS.empty() ? Handle<DefaultProbabilityTermStructure>(\n        boost::make_shared<FlatHazardRate>(0, ctptyDTS->calendar(), 1.e-12, \n        ctptyDTS->dayCounter()) ) : invstDTS ),\n    invstRecoveryRate_(invstRecoveryRate)\n  {\n      registerWith(discountCurve);\n      registerWith(ctptyDTS);\n      registerWith(invstDTS_);\n  }\n\n  inline CounterpartyAdjSwapEngine::CounterpartyAdjSwapEngine(\n        const Handle<YieldTermStructure>& discountCurve,\n        const Handle<Quote>& blackVol,\n        const Handle<DefaultProbabilityTermStructure>& ctptyDTS,\n        Real ctptyRecoveryRate,\n        const Handle<DefaultProbabilityTermStructure>& invstDTS,\n        Real invstRecoveryRate)\n  : baseSwapEngine_(Handle<PricingEngine>(\n      boost::make_shared<DiscountingSwapEngine>(discountCurve))),\n    swaptionletEngine_(Handle<PricingEngine>(\n      boost::make_shared<BlackSwaptionEngine>(discountCurve,\n        blackVol))),\n    discountCurve_(discountCurve),\n    defaultTS_(ctptyDTS), \n    ctptyRecoveryRate_(ctptyRecoveryRate),\n    invstDTS_(invstDTS.empty() ? Handle<DefaultProbabilityTermStructure>(\n        boost::make_shared<FlatHazardRate>(0, ctptyDTS->calendar(), 1.e-12, \n        ctptyDTS->dayCounter()) ) : invstDTS ),\n    invstRecoveryRate_(invstRecoveryRate)\n  {\n      registerWith(discountCurve);\n      registerWith(ctptyDTS);\n      registerWith(invstDTS_);\n      registerWith(blackVol);\n  }\n\n  inline void CounterpartyAdjSwapEngine::calculate() const {\n      /* both DTS, YTS ref dates and pricing date consistency \n         checks? settlement... */\n    QL_REQUIRE(!discountCurve_.empty(),\n                 \"no discount term structure set\");\n    QL_REQUIRE(!defaultTS_.empty(),\n                 \"no ctpty default term structure set\");\n    QL_REQUIRE(!swaptionletEngine_.empty(),\n                 \"no swap option engine set\");\n\n    Date priceDate = defaultTS_->referenceDate();\n\n    Real cumOptVal = 0., \n        cumPutVal = 0.;\n    // Vanilla swap so 0 leg is floater\n\n    std::vector<Date>::const_iterator nextFD = \n      arguments_.fixedPayDates.begin();\n    Date swapletStart = priceDate;\n    while (*nextFD < priceDate) ++nextFD;\n\n    // Compute fair spread for strike value:\n    // copy args into the non risky engine\n    Swap::arguments * noCVAArgs = dynamic_cast<Swap::arguments*>(\n      baseSwapEngine_->getArguments());\n    QL_REQUIRE(noCVAArgs != 0, \"wrong argument type\");\n\n    noCVAArgs->legs = this->arguments_.legs;\n    noCVAArgs->payer = this->arguments_.payer;\n\n    baseSwapEngine_->calculate();\n\n    boost::shared_ptr<FixedRateCoupon> coupon = boost::dynamic_pointer_cast<FixedRateCoupon>(arguments_.legs[0][0]);\n    QL_REQUIRE(coupon,\"dynamic cast of fixed leg coupon failed.\");\n    Rate baseSwapRate = coupon->rate();\n\n    const Swap::results * vSResults =  \n        dynamic_cast<const Swap::results *>(baseSwapEngine_->getResults());\n    QL_REQUIRE(vSResults != 0, \"wrong result type\");\n\n    Rate baseSwapFairRate = -baseSwapRate * vSResults->legNPV[1] / \n        vSResults->legNPV[0];\n    Real baseSwapNPV = vSResults->value;\n\n    VanillaSwap::Type reversedType = arguments_.type == VanillaSwap::Payer ? \n        VanillaSwap::Receiver : VanillaSwap::Payer;\n\n    // Swaplet options summatory:\n    while(nextFD != arguments_.fixedPayDates.end()) {\n      // iFD coupon not fixed, create swaptionlet:\n      boost::shared_ptr<FloatingRateCoupon> floatCoupon = boost::dynamic_pointer_cast<FloatingRateCoupon>(arguments_.legs[1][0]);\n      QL_REQUIRE(floatCoupon,\"dynamic cast of floating leg coupon failed.\");\n      boost::shared_ptr<IborIndex> swapIndex = boost::dynamic_pointer_cast<IborIndex>(floatCoupon->index());\n      QL_REQUIRE(swapIndex,\"dynamic cast of floating leg index failed.\");\n\n      // Alternatively one could cap this period to, say, 1M \n      // Period swapPeriod = boost::dynamic_pointer_cast<FloatingRateCoupon>(\n      //   arguments_.legs[1][0])->index()->tenor();\n\n      Period baseSwapsTenor(arguments_.fixedPayDates.back().serialNumber() \n\t    - swapletStart.serialNumber(), Days);\n      boost::shared_ptr<VanillaSwap> swaplet = MakeVanillaSwap(\n        baseSwapsTenor,\n        swapIndex, \n        baseSwapFairRate // strike\n        )\n\t    .withType(arguments_.type)\n\t    .withNominal(arguments_.nominal)\n          ////////\t    .withSettlementDays(2)\n        .withEffectiveDate(swapletStart)\n        .withTerminationDate(arguments_.fixedPayDates.back());\n      boost::shared_ptr<VanillaSwap> revSwaplet = MakeVanillaSwap(\n        baseSwapsTenor,\n        swapIndex, \n        baseSwapFairRate // strike\n        )\n\t    .withType(reversedType)\n\t    .withNominal(arguments_.nominal)\n          /////////\t    .withSettlementDays(2)\n        .withEffectiveDate(swapletStart)\n        .withTerminationDate(arguments_.fixedPayDates.back());\n\n      Swaption swaptionlet(swaplet, \n        boost::make_shared<EuropeanExercise>(swapletStart));\n      Swaption putSwaplet(revSwaplet, \n        boost::make_shared<EuropeanExercise>(swapletStart));\n      swaptionlet.setPricingEngine(swaptionletEngine_.currentLink());\n      putSwaplet.setPricingEngine(swaptionletEngine_.currentLink());\n\n      // atm underlying swap means that the value of put = value\n      // call so this double pricing is not needed\n      cumOptVal += swaptionlet.NPV() * defaultTS_->defaultProbability(\n          swapletStart, *nextFD);\n      cumPutVal += putSwaplet.NPV()  * invstDTS_->defaultProbability(\n\t      swapletStart, *nextFD);\n\n      swapletStart = *nextFD;\n      ++nextFD;\n    }\n  \n    results_.value = baseSwapNPV - (1.-ctptyRecoveryRate_) * cumOptVal\n        + (1.-invstRecoveryRate_) * cumPutVal;\n\n    results_.fairRate =  -baseSwapRate * (vSResults->legNPV[1] \n        - (1.-ctptyRecoveryRate_) * cumOptVal + \n          (1.-invstRecoveryRate_) * cumPutVal )\n      / vSResults->legNPV[0];\n\n  }\n\n\n}\n\n#endif\n", "meta": {"hexsha": "998aeb71aaeee28da30e610afd534480878e8bc6", "size": 14040, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/pricingengines/swap/cvaswapengine.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/pricingengines/swap/cvaswapengine.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/pricingengines/swap/cvaswapengine.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": 40.5780346821, "max_line_length": 129, "alphanum_fraction": 0.7061253561, "num_tokens": 3406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079209, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4745434121300511}}
{"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#ifdef Cygwin\n// availability of std::to_string\n#define _GLIBCXX_USE_C99 1\n#endif\n\n#include <iostream>\n\n// #include <boost/timer/timer.hpp>\n\n\n#include \"dune/grid/config.h\"\n#include \"dune/grid/uggrid.hh\"\n#include <dune/istl/operators.hh>\n\n#include \"utilities/enums.hh\"\n#include \"fem/assemble.hh\"\n#include \"fem/spaces.hh\"\n#include \"io/vtk.hh\"\n#include \"io/matlab.hh\"\n#include \"linalg/direct.hh\"\n#include \"linalg/apcg.hh\"\n#include \"linalg/threadedMatrix.hh\"\n#include \"linalg/triplet.hh\"\n#include \"mg/multigrid.hh\"\n#include \"mg/additiveMultigrid.hh\"\n#include \"utilities/gridGeneration.hh\"\n#include \"utilities/kaskopt.hh\"\n#include \"utilities/memory.hh\"\n\nusing namespace Kaskade;\n#include \"elastomechanics.hh\"\n\nint main(int argc, char *argv[])\n{\n  using namespace boost::fusion;\n\n  std::cout << \"Start elastomechanics tutorial program\" << std::endl;\n  \n  int coarseGridSize, maxit, order, refinements, solver, verbose;\n  bool additive, direct, vtk;\n  double atol;\n  std::string material;\n  \n  if (getKaskadeOptions(argc,argv,Options\n    (\"refinements\",      refinements,     3,          \"number of uniform grid refinements\")\n    (\"coarse\",           coarseGridSize,  1,          \"number of coarse grid elements along each cube edge\")\n    (\"order\",            order,           1,          \"finite element ansatz order\")\n    (\"material\",         material,        \"steel\",    \"type of material\")\n    (\"direct\",           direct,          true,       \"if true, use a direct solver\")\n    (\"solver\",           solver,          2,          \"0=UMFPACK, 1=PARDISO 2=MUMPS 3=SUPERLU 4=UMFPACK32/64 5=UMFPACK64\")\n    (\"additive\",         additive,        false,      \"use additive multigrid\")\n    (\"verbosity\",        verbose,         0,          \"amount of reported details\")\n    (\"vtk\",              vtk,             false,      \"write solution to VTK file\")\n    (\"atol\",             atol,            1e-8,       \"absolute energy error tolerance for iterative solver\")\n    (\"maxit\",            maxit,           100,        \"maximum number of iterations\")))\n    return 1;\n\n  boost::timer::cpu_timer totalTimer;\n\n  std::cout << \"refinements of original mesh : \" << refinements << std::endl;\n  std::cout << \"discretization order         : \" << order << std::endl;\n\n\n  constexpr int DIM = 3;\n  using Grid = Dune::UGGrid<DIM>;\n  using Spaces = boost::fusion::vector<H1Space<Grid> const*>;\n  using VariableDescriptions = boost::fusion::vector<VariableDescription<0,DIM,0> >;\n  using VarSetDesc = VariableSetDescription<Spaces,VariableDescriptions>;\n  using Functional = ElasticityFunctional<VarSetDesc>;\n  using Assembler = VariationalFunctionalAssembler<LinearizationAt<Functional> >;\n  using CoefficientVectors = VarSetDesc::CoefficientVectorRepresentation<0,1>::type;\n\n  Dune::FieldVector<double,DIM> c0(0.0), dc(1.0);\n  GridManager<Grid> gridManager( createCuboid<Grid>(c0,dc,1.0/coarseGridSize,true) );\n  gridManager.globalRefine(refinements);\n  gridManager.enforceConcurrentReads(true);\n  std::cout << \"grid creation & refinement time: \" << totalTimer.format();\n\n\t\n  // construction of finite element space for the scalar solution T.\n  H1Space<Grid> h1Space(gridManager,gridManager.grid().leafGridView(),order);\n\t\n  Spaces spaces(&h1Space);\n\t\n  std::string varNames[1] = { \"u\" };\n\t\n  VarSetDesc varSetDesc(spaces,varNames);\n\n  // Create the variational functional.\n  Functional F(ElasticModulus::material(material));\n\t\n  // construct Galerkin representation\n  Assembler assembler(gridManager,spaces);\n  VarSetDesc::VariableSet x(varSetDesc);\n  VarSetDesc::VariableSet dx(varSetDesc);\n\n\t\n\t\n  boost::timer::cpu_timer assembTimer;\n  assembler.assemble(linearization(F,x));\n  std::cout << \"computing time for assemble: \" << boost::timer::format(assembTimer.elapsed()) << \"\\n\";\n  \n  CoefficientVectors rhs(assembler.rhs());\n  CoefficientVectors solution(VarSetDesc::CoefficientVectorRepresentation<0,1>::init(spaces));\n  boost::timer::cpu_timer solveTimer;\n  if (direct)\n  {\n    DirectType directType = static_cast<DirectType>(solver);\n    AssembledGalerkinOperator<Assembler> A(assembler, directType == DirectType::MUMPS || directType == DirectType::PARDISO);\n    directInverseOperator(A,directType,MatrixProperties::POSITIVEDEFINITE).applyscaleadd(-1.0,rhs,solution);\n    x.data = solution.data;\n  }\n  else\n  {\n    using X = Dune::BlockVector<Dune::FieldVector<double,DIM>>;\n    DefaultDualPairing<X,X> dp;\n    using Matrix = NumaBCRSMatrix<Dune::FieldMatrix<double,DIM,DIM>>;\n    using LinOp = Dune::MatrixAdapter<Matrix,X,X>;\n    Matrix Amat(assembler.get<0,0>(),true);\n    LinOp A(Amat);\n    SymmetricLinearOperatorWrapper<X,X> sa(A,dp);\n    PCGEnergyErrorTerminationCriterion<double> term(atol,maxit);\n    \n    \n    Dune::InverseOperatorResult res;\n    X xi(component<0>(rhs).N());\n\n    std::unique_ptr<SymmetricPreconditioner<X,X>> mg;\n    if (additive)\n    {\n      if (order==1)\n        mg = moveUnique(makeBPX(Amat,gridManager));\n      else\n      {\n        H1Space<Grid> p1Space(gridManager,gridManager.grid().leafGridView(),1);\n        mg = moveUnique(makePBPX(Amat,h1Space,p1Space));\n      }\n    }\n    else\n      mg = makeMultigrid(Amat,h1Space);\n\n\n    Pcg<X,X> pcg(sa,*mg,term,verbose);\n    pcg.apply(xi,component<0>(rhs),res);\n    xi *= -1;\n    component<0>(x) = xi;\n  }\n  std::cout << \"computing time for solve: \" << solveTimer.format();\n\n  // output of solution in VTK format for visualization,\n  // the data are written as ascii stream into file elasto.vtu,\n  // possible is also binary\n  if (vtk)\n    writeVTKFile(x,\"elasto\",IoOptions().setOrder(order).setPrecision(7));\n\n  std::cout << \"total computing time: \" << boost::timer::format(totalTimer.elapsed()) << \"\\n\";\n  std::cout << \"End elastomechanics tutorial program\" << std::endl;\n  \n  return 0;\n}\n", "meta": {"hexsha": "f0453cd804575d4e5fe9ea5b7c5e9ecaf814e9ac", "size": 6630, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Kaskade/tutorial/elastomechanics/elastomechanics.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/elastomechanics/elastomechanics.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:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-09T22:02:36.000Z", "max_forks_repo_path": "Kaskade/tutorial/elastomechanics/elastomechanics.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": 38.323699422, "max_line_length": 124, "alphanum_fraction": 0.6117647059, "num_tokens": 1743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920068519376, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.47454340931133865}}
{"text": "// The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt\n/*\n\n    This is an example illustrating the use of the graph_labeler and\n    structural_graph_labeling_trainer objects.\n\n    Suppose you have a bunch of objects and you need to label each of them as true or\n    false.  Suppose further that knowing the labels of some of these objects tells you\n    something about the likely label of the others.  This is common in a number of domains.\n    For example, in image segmentation problems you need to label each pixel, and knowing\n    the labels of neighboring pixels gives you information about the likely label since\n    neighboring pixels will often have the same label.\n    \n    We can generalize this problem by saying that we have a graph and our task is to label\n    each node in the graph as true or false.  Additionally, the edges in the graph connect\n    nodes which are likely to share the same label.  In this example program, each node\n    will have a feature vector which contains information which helps tell if the node\n    should be labeled as true or false.  The edges also contain feature vectors which give\n    information indicating how strong the edge's labeling consistency constraint should be.\n    This is useful since some nodes will have uninformative feature vectors and the only\n    way to tell how they should be labeled is by looking at their neighbor's labels.\n\n    Therefore, this program will show you how to learn two things using machine learning.\n    The first is a linear classifier which operates on each node and predicts if it should\n    be labeled as true or false.  The second thing is a linear function of the edge\n    vectors.  This function outputs a penalty for giving two nodes connected by an edge\n    differing labels.  The graph_labeler object puts these two things together and uses\n    them to compute a labeling which takes both into account.  In what follows, we will use\n    a structural SVM method to find the parameters of these linear functions which minimize\n    the number of mistakes made by a graph_labeler.\n\n\n    Finally, you might also consider reading the book Structured Prediction and Learning in\n    Computer Vision by Sebastian Nowozin and Christoph H. Lampert since it contains a good\n    introduction to machine learning methods such as the algorithm implemented by the\n    structural_graph_labeling_trainer.\n*/\n\n#include <dlib/svm_threaded.h>\n#include <iostream>\n\nusing namespace std;\nusing namespace dlib;\n\n// ----------------------------------------------------------------------------------------\n\n// The first thing we do is define the kind of graph object we will be using.\n// Here we are saying there will be 2-D vectors at each node and 1-D vectors at\n// each edge.  (You should read the matrix_ex.cpp example program for an introduction\n// to the matrix object.)\ntypedef matrix<double,2,1> node_vector_type;\ntypedef matrix<double,1,1> edge_vector_type;\ntypedef graph<node_vector_type, edge_vector_type>::kernel_1a_c graph_type;\n\n// ----------------------------------------------------------------------------------------\n\ntemplate <\n    typename graph_type,\n    typename labels_type\n    >\nvoid make_training_examples(\n    dlib::array<graph_type>& samples,\n    labels_type& labels\n)\n{\n    /*\n        This function makes 3 graphs we will use for training.   All of them\n        will contain 4 nodes and have the structure shown below:\n\n          (0)-----(1)\n           |       |\n           |       |\n           |       |\n          (3)-----(2)\n\n        In this example, each node has a 2-D vector.  The first element of this vector\n        is 1 when the node should have a label of false while the second element has\n        a value of 1 when the node should have a label of true.  Additionally, the \n        edge vectors will contain a value of 1 when the nodes connected by the edge\n        should share the same label and a value of 0 otherwise.  \n        \n        We want to see that the machine learning method is able to figure out how \n        these features relate to the labels.  If it is successful it will create a \n        graph_labeler which can predict the correct labels for these and other \n        similarly constructed graphs.\n\n        Finally, note that these tools require all values in the edge vectors to be >= 0.\n        However, the node vectors may contain both positive and negative values. \n    */\n\n    samples.clear();\n    labels.clear();\n\n    std::vector<bool> label;\n    graph_type g;\n\n    // ---------------------------\n    g.set_number_of_nodes(4);\n    label.resize(g.number_of_nodes());\n    // store the vector [0,1] into node 0.  Also label it as true.\n    g.node(0).data = 0, 1; label[0] = true;\n    // store the vector [0,0] into node 1.\n    g.node(1).data = 0, 0; label[1] = true;  // Note that this node's vector doesn't tell us how to label it.\n                                             // We need to take the edges into account to get it right.\n    // store the vector [1,0] into node 2.\n    g.node(2).data = 1, 0; label[2] = false;\n    // store the vector [0,0] into node 3.\n    g.node(3).data = 0, 0; label[3] = false;\n\n    // Add the 4 edges as shown in the ASCII art above.\n    g.add_edge(0,1);\n    g.add_edge(1,2);\n    g.add_edge(2,3);\n    g.add_edge(3,0);\n\n    // set the 1-D vector for the edge between node 0 and 1 to the value of 1.\n    edge(g,0,1) = 1; \n    // set the 1-D vector for the edge between node 1 and 2 to the value of 0.\n    edge(g,1,2) = 0;\n    edge(g,2,3) = 1;\n    edge(g,3,0) = 0;\n    // output the graph and its label.\n    samples.push_back(g);\n    labels.push_back(label);\n\n    // ---------------------------\n    g.set_number_of_nodes(4);\n    label.resize(g.number_of_nodes());\n    g.node(0).data = 0, 1; label[0] = true;\n    g.node(1).data = 0, 1; label[1] = true;\n    g.node(2).data = 1, 0; label[2] = false;\n    g.node(3).data = 1, 0; label[3] = false;\n\n    g.add_edge(0,1);\n    g.add_edge(1,2);\n    g.add_edge(2,3);\n    g.add_edge(3,0);\n\n    // This time, we have strong edges between all the nodes.  The machine learning \n    // tools will have to learn that when the node information conflicts with the \n    // edge constraints that the node information should dominate.\n    edge(g,0,1) = 1;\n    edge(g,1,2) = 1; \n    edge(g,2,3) = 1;\n    edge(g,3,0) = 1;\n    samples.push_back(g);\n    labels.push_back(label);\n    // ---------------------------\n\n    g.set_number_of_nodes(4);\n    label.resize(g.number_of_nodes());\n    g.node(0).data = 1, 0; label[0] = false;\n    g.node(1).data = 1, 0; label[1] = false;\n    g.node(2).data = 1, 0; label[2] = false;\n    g.node(3).data = 0, 0; label[3] = false;\n\n    g.add_edge(0,1);\n    g.add_edge(1,2);\n    g.add_edge(2,3);\n    g.add_edge(3,0);\n\n    edge(g,0,1) = 0;\n    edge(g,1,2) = 0;\n    edge(g,2,3) = 1;\n    edge(g,3,0) = 0;\n    samples.push_back(g);\n    labels.push_back(label);\n    // ---------------------------\n\n}\n\n// ----------------------------------------------------------------------------------------\n\nint main()\n{\n    try\n    {\n        // Get the training samples we defined above.\n        dlib::array<graph_type> samples;\n        std::vector<std::vector<bool> > labels;\n        make_training_examples(samples, labels);\n\n\n        // Create a structural SVM trainer for graph labeling problems.  The vector_type\n        // needs to be set to a type capable of holding node or edge vectors.\n        typedef matrix<double,0,1> vector_type;\n        structural_graph_labeling_trainer<vector_type> trainer;\n        // This is the usual SVM C parameter.  Larger values make the trainer try \n        // harder to fit the training data but might result in overfitting.  You \n        // should set this value to whatever gives the best cross-validation results.\n        trainer.set_c(10);\n\n        // Do 3-fold cross-validation and print the results.  In this case it will\n        // indicate that all nodes were correctly classified.  \n        cout << \"3-fold cross-validation: \" << cross_validate_graph_labeling_trainer(trainer, samples, labels, 3) << endl;\n\n        // Since the trainer is working well.  Let's have it make a graph_labeler \n        // based on the training data.\n        graph_labeler<vector_type> labeler = trainer.train(samples, labels);\n\n\n        /*\n            Let's try the graph_labeler on a new test graph.  In particular, let's\n            use one with 5 nodes as shown below:\n\n            (0 F)-----(1 T)\n              |         |\n              |         |\n              |         |\n            (3 T)-----(2 T)------(4 T)\n\n            I have annotated each node with either T or F to indicate the correct \n            output (true or false).  \n        */\n        graph_type g;\n        g.set_number_of_nodes(5);\n        g.node(0).data = 1, 0;  // Node data indicates a false node.\n        g.node(1).data = 0, 1;  // Node data indicates a true node.\n        g.node(2).data = 0, 0;  // Node data is ambiguous.\n        g.node(3).data = 0, 0;  // Node data is ambiguous.\n        g.node(4).data = 0.1, 0; // Node data slightly indicates a false node.\n\n        g.add_edge(0,1);\n        g.add_edge(1,2);\n        g.add_edge(2,3);\n        g.add_edge(3,0);\n        g.add_edge(2,4);\n\n        // Set the edges up so nodes 1, 2, 3, and 4 are all strongly connected.\n        edge(g,0,1) = 0;\n        edge(g,1,2) = 1;\n        edge(g,2,3) = 1;\n        edge(g,3,0) = 0;\n        edge(g,2,4) = 1;\n\n        // The output of this shows all the nodes are correctly labeled.\n        cout << \"Predicted labels: \" << endl;\n        std::vector<bool> temp = labeler(g);\n        for (unsigned long i = 0; i < temp.size(); ++i)\n            cout << \" \" << i << \": \" << temp[i] << endl;\n\n\n\n        // Breaking the strong labeling consistency link between node 1 and 2 causes\n        // nodes 2, 3, and 4 to flip to false.  This is because of their connection\n        // to node 4 which has a small preference for false.\n        edge(g,1,2) = 0;\n        cout << \"Predicted labels: \" << endl;\n        temp = labeler(g);\n        for (unsigned long i = 0; i < temp.size(); ++i)\n            cout << \" \" << i << \": \" << temp[i] << endl;\n    }\n    catch (std::exception& e)\n    {\n        cout << \"Error, an exception was thrown!\" << endl;\n        cout << e.what() << endl;\n    }\n}\n\n", "meta": {"hexsha": "984a93bf52c17d9233f87218514b1d54a70fb366", "size": 10305, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dlib/examples/graph_labeling_ex.cpp", "max_stars_repo_name": "maxmert/nlp-mitie", "max_stars_repo_head_hexsha": "ec3153ef2fe7a80e7cf3d80d14b388b8cd679343", "max_stars_repo_licenses": ["Unlicense"], "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": "examples/graph_labeling_ex.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": "examples/graph_labeling_ex.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": 39.6346153846, "max_line_length": 122, "alphanum_fraction": 0.6098010674, "num_tokens": 2632, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920068519378, "lm_q2_score": 0.5926665999540697, "lm_q1q2_score": 0.4745434093113386}}
{"text": "#include \"UCCSD.hpp\"\n#include \"GateFunction.hpp\"\n#include \"FermionToSpinTransformation.hpp\"\n#include \"CommutingSetGenerator.hpp\"\n#include <boost/math/constants/constants.hpp>\n\nusing namespace xacc::quantum;\n\nnamespace xacc {\nnamespace vqe {\n\n\nstd::shared_ptr<Function> UCCSD::generate(\n\t\tstd::shared_ptr<AcceleratorBuffer> buffer,\n\t\tstd::vector<InstructionParameter> parameters) {\n\n\tauto runtimeOptions = RuntimeOptions::instance();\n\n\tif (!runtimeOptions->exists(\"n-electrons\")) {\n\t\txacc::error(\"To use this UCCSD State Prep IRGenerator, you \"\n\t\t\t\t\"must specify the number of electrons.\");\n\t}\n\n\tif (!runtimeOptions->exists(\"n-qubits\")) {\n\t\txacc::error(\"To use this UCCSD State Prep IRGenerator, you \"\n\t\t\t\t\"must specify the number of qubits.\");\n\t}\n\n\tauto nQubits = std::stoi((*runtimeOptions)[\"n-qubits\"]);\n\tauto nElectrons = std::stoi((*runtimeOptions)[\"n-electrons\"]);\n\n\t// Compute the number of parameters\n\tauto _nOccupied = (int) std::ceil(nElectrons / 2.0);\n\tauto _nVirtual = nQubits / 2 - _nOccupied;\n\tauto nSingle = _nOccupied * _nVirtual;\n\tauto nDouble = std::pow(nSingle, 2);\n\tauto _nParameters = nSingle + nDouble;\n\n\tauto singletIndex = [=](int i, int j) -> int {\n\t\treturn i * _nOccupied + j;\n\t};\n\n\tauto doubletIndex = [=](int i, int j, int k, int l) -> int {\n\t\treturn\n\t\t(i * _nOccupied * _nVirtual * _nOccupied +\n\t\t\t\tj * _nVirtual * _nOccupied +\n\t\t\t\tk * _nOccupied +\n\t\t\t\tl);\n\t};\n\n\tstd::vector<xacc::InstructionParameter> variables;\n\tstd::vector<std::string> params;\n\tfor (int i = 0; i < _nParameters; i++) {\n\t\tparams.push_back(\"theta\" + std::to_string(i));\n\t\tvariables.push_back(InstructionParameter(\"theta\" + std::to_string(i)));\n\t}\n\n\tauto kernel = std::make_shared<FermionKernel>(\"fermiUCCSD\");\n\txacc::info(\"Constructing UCCSD Fermion Operator.\");\n\tfor (int i = 0; i < _nVirtual; i++) {\n\t\tfor (int j = 0; j < _nOccupied; j++) {\n\t\t\tfor (int l = 0; l < 2; l++) {\n\t\t\t\tstd::vector<std::pair<int, int>> operators { { 2\n\t\t\t\t\t\t* (i + _nOccupied) + l, 1 }, { 2 * j + l, 0 } };\n\t\t\t\tauto fermiInstruction1 = std::make_shared<FermionInstruction>(\n\t\t\t\t\t\toperators, params[singletIndex(i, j)]);\n\t\t\t\tkernel->addInstruction(fermiInstruction1);\n\n\t\t\t\tstd::vector<std::pair<int, int>> operators2 { { 2 * j + l, 1 },\n\t\t\t\t\t\t{ 2 * (i + _nOccupied) + l, 0 } };\n\t\t\t\tauto fermiInstruction2 = std::make_shared<FermionInstruction>(\n\t\t\t\t\t\toperators2, params[singletIndex(i, j)]);\n\n\n\t\t\t\tauto nP = fermiInstruction2->nParameters();\n\t\t\t\tInstructionParameter p(-1.0*std::complex<double>(1,0));\n\t\t\t\tfermiInstruction2->setParameter(nP-2,p);\n\n\t\t\t\tkernel->addInstruction(fermiInstruction2);\n\n\t\t\t}\n\t\t}\n\t}\n\n\tfor (int i = 0; i < _nVirtual; i++) {\n\t\tfor (int j = 0; j < _nOccupied; j++) {\n\t\t\tfor (int l = 0; l < 2; l++) {\n\t\t\t\tfor (int i2 = 0; i2 < _nVirtual; i2++) {\n\t\t\t\t\tfor (int j2 = 0; j2 < _nOccupied; j2++) {\n\t\t\t\t\t\tfor (int l2 = 0; l2 < 2; l2++) {\n\t\t\t\t\t\t\tstd::vector<std::pair<int, int>> operators1 { { 2\n\t\t\t\t\t\t\t\t\t* (i + _nOccupied) + l, 1 },\n\t\t\t\t\t\t\t\t\t{ 2 * j + l, 0 }, { 2 * (i2 + _nOccupied)\n\t\t\t\t\t\t\t\t\t\t\t+ l2, 1 }, { 2 * j2 + l2, 0 } };\n\n\t\t\t\t\t\t\tstd::vector<std::pair<int, int>> operators2 { { 2\n\t\t\t\t\t\t\t\t\t* j2 + l2, 1 }, { 2 * (i2 + _nOccupied)\n\t\t\t\t\t\t\t\t\t+ l2, 0 }, { 2 * j + l, 1 }, { 2\n\t\t\t\t\t\t\t\t\t* (i + _nOccupied) + l, 0 } };\n\n\t\t\t\t\t\t\tauto doubletIdx1 = nSingle\n\t\t\t\t\t\t\t\t\t+ doubletIndex(i, j, i2, j2);\n\t\t\t\t\t\t\tauto doubletIdx2 = nSingle\n\t\t\t\t\t\t\t\t\t+ doubletIndex(i, j, i2, j2);\n\n\t\t\t\t\t\t\tauto fermiInstruction1 = std::make_shared<\n\t\t\t\t\t\t\t\t\tFermionInstruction>(operators1,\n\t\t\t\t\t\t\t\t\tparams[doubletIdx1]);\n\n\t\t\t\t\t\t\tkernel->addInstruction(fermiInstruction1);\n\n\t\t\t\t\t\t\tauto fermiInstruction2 = std::make_shared<\n\t\t\t\t\t\t\t\t\tFermionInstruction>(operators2,\n\t\t\t\t\t\t\t\t\tparams[doubletIdx2]);\n\n\t\t\t\t\t\t\tauto nP = fermiInstruction2->nParameters();\n\t\t\t\t\t\t\tInstructionParameter p(-1.0*std::complex<double>(1,0));\n\t\t\t\t\t\t\tfermiInstruction2->setParameter(nP-2,p);\n\t\t\t\t\t\t\tkernel->addInstruction(fermiInstruction2);\n\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//\tstd::cout << \"KERNEL: \\n\" << kernel->toString(\"\") << \"\\n\";\n\t// Create the FermionIR to pass to our transformation.\n\tauto fermionir = std::make_shared<FermionIR>();\n\tfermionir->addKernel(kernel);\n\n\txacc::info(\"Done constructing UCCSD Fermion Operator.\");\n\txacc::info(\"Mapping UCCSD Fermion Operator to Spin. \");\n\n\tstd::shared_ptr<FermionToSpinTransformation> transform;\n\tif (xacc::optionExists(\"fermion-transformation\")) {\n\t\tauto transformStr = xacc::getOption(\"fermion-transformation\");\n\t\ttransform = xacc::getService<FermionToSpinTransformation>(\n\t\t\t\ttransformStr);\n\t} else {\n\t\ttransform = xacc::getService<FermionToSpinTransformation>(\n\t\t\t\t\"jw\");\n\t}\n\n\tauto compositeResult = transform->transform(*kernel.get());\n//\tauto resultsStr = compositeResult.toString();\n//\tboost::replace_all(resultsStr, \"+\", \"+\\n\");\n\n\t// Create the Spin Hamiltonian\n\tauto transformedIR = compositeResult.toXACCIR();\n\txacc::info(\"Done mapping UCCSD Fermion Operator to Spin.\");\n\n\tstd::unordered_map<std::string, Term> terms = compositeResult.getTerms();\n\n\tCommutingSetGenerator gen;\n\tauto commutingSets = gen.getCommutingSet(compositeResult, nQubits);\n\tauto pi = boost::math::constants::pi<double>();\n\tauto gateRegistry = xacc::getService<IRProvider>(\"gate\");\n\n\tauto uccsdGateFunction = gateRegistry->createFunction(\"uccsdPrep\",{},\n\t\t\tvariables);\n\n\n\t// Perform Trotterization...\n\tfor (auto s : commutingSets) {\n\n\t\tfor (auto inst : s) {\n\t\t\tTerm spinInst = inst;\n\n\t\t\t// Get the individual pauli terms\n\t\t\tauto termsMap = std::get<2>(spinInst);\n\n\t\t\tstd::vector<std::pair<int,std::string>> terms;\n\t\t\tfor (auto& kv : termsMap) {\n\t\t\t\tif (kv.second != \"I\" && !kv.second.empty()) {\n\t\t\t\t\tterms.push_back({kv.first, kv.second});\n\t\t\t\t}\n\t\t\t}\n\t\t\t// The largest qubit index is on the last term\n\t\t\tint largestQbitIdx = terms[terms.size() - 1].first;\n\t\t\tauto tempFunction = gateRegistry->createFunction(\"temp\", {}, {});\n\n\t\t\tfor (int i = 0; i < terms.size(); i++) {\n\n\t\t\t\tauto qbitIdx = terms[i].first;\n\t\t\t\tauto gateName = terms[i].second;\n\n\t\t\t\tif (i < terms.size() - 1) {\n\t\t\t\t\tauto cnot =\n\t\t\t\t\t\t\tgateRegistry->createInstruction(\n\t\t\t\t\t\t\t\t\t\"CNOT\",\n\t\t\t\t\t\t\t\t\tstd::vector<int> { qbitIdx,\n\t\t\t\t\t\t\t\t\t\t\tterms[i + 1].first });\n\t\t\t\t\ttempFunction->addInstruction(cnot);\n\t\t\t\t}\n\n\t\t\t\tif (gateName == \"X\") {\n\t\t\t\t\tauto hadamard =\n\t\t\t\t\t\t\tgateRegistry->createInstruction(\n\t\t\t\t\t\t\t\t\t\"H\", std::vector<int> { qbitIdx });\n\t\t\t\t\ttempFunction->insertInstruction(0, hadamard);\n\t\t\t\t} else if (gateName == \"Y\") {\n\t\t\t\t\tauto rx =\n\t\t\t\t\t\t\tgateRegistry->createInstruction(\n\t\t\t\t\t\t\t\t\t\"Rx\", std::vector<int> { qbitIdx });\n\t\t\t\t\tInstructionParameter p(pi / 2.0);\n\t\t\t\t\trx->setParameter(0, p);\n\t\t\t\t\ttempFunction->insertInstruction(0, rx);\n\t\t\t\t}\n\n\t\t\t\t// Add the Rotation for the last term\n\t\t\t\tif (i == terms.size() - 1) {\n\t\t\t\t\t// FIXME DONT FORGET DIVIDE BY 2\n\t\t\t\t\tstd::stringstream ss;\n\t\t\t\t\tss << 2*std::imag(std::get<0>(spinInst)) << \" * \"\n\t\t\t\t\t\t\t<< std::get<1>(spinInst);\n\t\t\t\t\tauto rz =\n\t\t\t\t\t\t\tgateRegistry->createInstruction(\n\t\t\t\t\t\t\t\t\t\"Rz\", std::vector<int> { qbitIdx });\n\n\t\t\t\t\tInstructionParameter p(ss.str());\n\t\t\t\t\trz->setParameter(0, p);\n\t\t\t\t\ttempFunction->addInstruction(rz);\n\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tint counter = tempFunction->nInstructions();\n\t\t\t// Add the instruction on the backend of the circuit\n\t\t\tfor (int i = terms.size() - 1; i >= 0; i--) {\n\n\t\t\t\tauto qbitIdx = terms[i].first;\n\t\t\t\tauto gateName = terms[i].second;\n\n\t\t\t\tif (i < terms.size() - 1) {\n\t\t\t\t\tauto cnot =\n\t\t\t\t\t\t\tgateRegistry->createInstruction(\n\t\t\t\t\t\t\t\t\t\"CNOT\",\n\t\t\t\t\t\t\t\t\tstd::vector<int> { qbitIdx,\n\t\t\t\t\t\t\t\t\t\t\tterms[i + 1].first });\n\t\t\t\t\ttempFunction->insertInstruction(counter, cnot);\n\t\t\t\t\tcounter++;\n\t\t\t\t}\n\n\t\t\t\tif (gateName == \"X\") {\n\t\t\t\t\tauto hadamard =\n\t\t\t\t\t\t\tgateRegistry->createInstruction(\n\t\t\t\t\t\t\t\t\t\"H\", std::vector<int> { qbitIdx });\n\t\t\t\t\ttempFunction->addInstruction(hadamard);\n\t\t\t\t} else if (gateName == \"Y\") {\n\t\t\t\t\tauto rx =\n\t\t\t\t\t\t\tgateRegistry->createInstruction(\n\t\t\t\t\t\t\t\t\t\"Rx\", std::vector<int> { qbitIdx });\n\t\t\t\t\tInstructionParameter p(4 * pi - (pi /2.0));\n\t\t\t\t\trx->setParameter(0, p);\n\t\t\t\t\ttempFunction->addInstruction(rx);\n\t\t\t\t}\n\n\t\t\t}\n\t\t\t// Add to the total UCCSD State Prep function\n\t\t\tfor (auto inst : tempFunction->getInstructions()) {\n\t\t\t\tuccsdGateFunction->addInstruction(inst);\n\t\t\t}\n\t\t}\n\t}\n\n\tfor (int i = nElectrons-1; i >= 0; i--) {\n\t\tauto xGate = gateRegistry->createInstruction(\n\t\t\t\t\"X\", std::vector<int>{i});\n\t\tuccsdGateFunction->insertInstruction(0,xGate);\n\t}\n\n\treturn uccsdGateFunction;\n}\n\n}\n}\n\n", "meta": {"hexsha": "40c1ff9a1005f4b476e10d464a9e88996bb41d14", "size": 8306, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ir/algorithms/uccsd/UCCSD.cpp", "max_stars_repo_name": "czhao39/xacc-vqe", "max_stars_repo_head_hexsha": "4ad1d9308794e28c37772b7ea29cd3923388168a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ir/algorithms/uccsd/UCCSD.cpp", "max_issues_repo_name": "czhao39/xacc-vqe", "max_issues_repo_head_hexsha": "4ad1d9308794e28c37772b7ea29cd3923388168a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ir/algorithms/uccsd/UCCSD.cpp", "max_forks_repo_name": "czhao39/xacc-vqe", "max_forks_repo_head_hexsha": "4ad1d9308794e28c37772b7ea29cd3923388168a", "max_forks_repo_licenses": ["BSD-3-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.6642857143, "max_line_length": 74, "alphanum_fraction": 0.6217192391, "num_tokens": 2514, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4745434064926262}}
{"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 <mitkImageCast.h>\n#include <itkExceptionObject.h>\n#include <itkImageFileWriter.h>\n#include <mitkBaseDataIOFactory.h>\n#include <mitkQBallImage.h>\n#include <itkTensorDerivedMeasurementsFilter.h>\n#include <itkDiffusionQballGeneralizedFaImageFilter.h>\n#include <mitkTensorImage.h>\n#include \"mitkCommandLineParser.h\"\n#include <boost/algorithm/string.hpp>\n#include <itksys/SystemTools.hxx>\n#include <itkMultiThreader.h>\n\n/**\n * Calculate indices derived from Qball or tensor images\n */\nint main(int argc, char* argv[])\n{\n    mitkCommandLineParser parser;\n\n    parser.setTitle(\"Diffusion Indices\");\n    parser.setCategory(\"Diffusion Related Measures\");\n    parser.setDescription(\"\");\n    parser.setContributor(\"MBI\");\n\n    parser.setArgumentPrefix(\"--\", \"-\");\n    parser.addArgument(\"input\", \"i\", mitkCommandLineParser::InputFile, \"Input:\", \"input image (tensor, Q-ball or FSL/MRTrix SH-coefficient image)\", us::Any(), false);\n    parser.addArgument(\"index\", \"idx\", mitkCommandLineParser::String, \"Index:\", \"index (fa, gfa, ra, ad, rd, ca, l2, l3, md)\", us::Any(), false);\n    parser.addArgument(\"outFile\", \"o\", mitkCommandLineParser::OutputFile, \"Output:\", \"output file\", us::Any(), false);\n\n    map<string, us::Any> parsedArgs = parser.parseArguments(argc, argv);\n    if (parsedArgs.size()==0)\n        return EXIT_FAILURE;\n\n    string inFileName = us::any_cast<string>(parsedArgs[\"input\"]);\n    string index = us::any_cast<string>(parsedArgs[\"index\"]);\n    string outFileName = us::any_cast<string>(parsedArgs[\"outFile\"]);\n\n    string ext = itksys::SystemTools::GetFilenameLastExtension(outFileName);\n    if (ext.empty())\n        outFileName += \".nrrd\";\n\n    try\n    {\n        // load input image\n        const std::string s1=\"\", s2=\"\";\n        std::vector<mitk::BaseData::Pointer> infile = mitk::BaseDataIO::LoadBaseDataFromFile( inFileName, s1, s2, false );\n\n        if( boost::algorithm::ends_with(inFileName, \".qbi\") && index==\"gfa\" )\n        {\n            typedef itk::Vector<float, QBALL_ODFSIZE>   OdfVectorType;\n            typedef itk::Image<OdfVectorType,3>         ItkQballImageType;\n            mitk::QBallImage::Pointer mitkQballImage = dynamic_cast<mitk::QBallImage*>(infile.at(0).GetPointer());\n            ItkQballImageType::Pointer itk_qbi = ItkQballImageType::New();\n            mitk::CastToItkImage(mitkQballImage, itk_qbi);\n\n\n            typedef itk::DiffusionQballGeneralizedFaImageFilter<float,float,QBALL_ODFSIZE> GfaFilterType;\n            GfaFilterType::Pointer gfaFilter = GfaFilterType::New();\n            gfaFilter->SetInput(itk_qbi);\n            gfaFilter->SetComputationMethod(GfaFilterType::GFA_STANDARD);\n            gfaFilter->Update();\n\n            itk::ImageFileWriter< itk::Image<float,3> >::Pointer fileWriter = itk::ImageFileWriter< itk::Image<float,3> >::New();\n            fileWriter->SetInput(gfaFilter->GetOutput());\n            fileWriter->SetFileName(outFileName);\n            fileWriter->Update();\n        }\n        else if( boost::algorithm::ends_with(inFileName, \".dti\") )\n        {\n            typedef itk::Image< itk::DiffusionTensor3D<float>, 3 >    ItkTensorImage;\n            mitk::TensorImage::Pointer mitkTensorImage = dynamic_cast<mitk::TensorImage*>(infile.at(0).GetPointer());\n            ItkTensorImage::Pointer itk_dti = ItkTensorImage::New();\n            mitk::CastToItkImage(mitkTensorImage, itk_dti);\n\n            typedef itk::TensorDerivedMeasurementsFilter<float> MeasurementsType;\n            MeasurementsType::Pointer measurementsCalculator = MeasurementsType::New();\n            measurementsCalculator->SetInput(itk_dti.GetPointer() );\n\n            if(index==\"fa\")\n                measurementsCalculator->SetMeasure(MeasurementsType::FA);\n            else if(index==\"ra\")\n                measurementsCalculator->SetMeasure(MeasurementsType::RA);\n            else if(index==\"ad\")\n                measurementsCalculator->SetMeasure(MeasurementsType::AD);\n            else if(index==\"rd\")\n                measurementsCalculator->SetMeasure(MeasurementsType::RD);\n            else if(index==\"ca\")\n                measurementsCalculator->SetMeasure(MeasurementsType::CA);\n            else if(index==\"l2\")\n                measurementsCalculator->SetMeasure(MeasurementsType::L2);\n            else if(index==\"l3\")\n                measurementsCalculator->SetMeasure(MeasurementsType::L3);\n            else if(index==\"md\")\n                measurementsCalculator->SetMeasure(MeasurementsType::MD);\n            else\n            {\n                MITK_WARN << \"No valid diffusion index for input image (tensor image) defined\";\n                return EXIT_FAILURE;\n            }\n\n            measurementsCalculator->Update();\n\n            itk::ImageFileWriter< itk::Image<float,3> >::Pointer fileWriter = itk::ImageFileWriter< itk::Image<float,3> >::New();\n            fileWriter->SetInput(measurementsCalculator->GetOutput());\n            fileWriter->SetFileName(outFileName);\n            fileWriter->Update();\n        }\n        else\n            std::cout << \"Diffusion index \" << index << \" not supported for supplied file type.\";\n    }\n    catch (itk::ExceptionObject e)\n    {\n        std::cout << e;\n        return EXIT_FAILURE;\n    }\n    catch (std::exception e)\n    {\n        std::cout << e.what();\n        return EXIT_FAILURE;\n    }\n    catch (...)\n    {\n        std::cout << \"ERROR!?!\";\n        return EXIT_FAILURE;\n    }\n    return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "4454344ef2521cc159ec348af86743c8cff8e727", "size": 5915, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Modules/DiffusionImaging/MiniApps/DiffusionIndices.cpp", "max_stars_repo_name": "danielknorr/MITK", "max_stars_repo_head_hexsha": "b1b9780b2a6671d8118313c5ef71e9aa128362be", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/MiniApps/DiffusionIndices.cpp", "max_issues_repo_name": "danielknorr/MITK", "max_issues_repo_head_hexsha": "b1b9780b2a6671d8118313c5ef71e9aa128362be", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/MiniApps/DiffusionIndices.cpp", "max_forks_repo_name": "danielknorr/MITK", "max_forks_repo_head_hexsha": "b1b9780b2a6671d8118313c5ef71e9aa128362be", "max_forks_repo_licenses": ["BSD-3-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.7931034483, "max_line_length": 166, "alphanum_fraction": 0.631783601, "num_tokens": 1363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4745434064926262}}
{"text": "/*\n    This file is part of Nori, a simple educational ray tracer\n\n    Copyright (c) 2015 by Wenzel Jakob\n*/\n\n#include <nori/mesh.h>\n#include <nori/bsdf.h>\n#include <nori/emitter.h>\n#include <nori/warp.h>\n#include <Eigen/Geometry>\n\nNORI_NAMESPACE_BEGIN\n\nMesh::Mesh() { }\n\nMesh::~Mesh() {\n    delete m_bsdf;\n    delete m_emitter;\n}\n\nvoid Mesh::activate() {\n    if (!m_bsdf) {\n        /* If no material was assigned, instantiate a diffuse BRDF */\n        m_bsdf = static_cast<BSDF *>(\n            NoriObjectFactory::createInstance(\"diffuse\", PropertyList()));\n    }\n\n    //generate cdf if emitted\n    if(isEmitter()){\n        dpdf.reserve(getTriangleCount());\n        for(size_t i = 0; i < getTriangleCount(); ++i){\n            dpdf.append(surfaceArea(i));\n        }\n        dpdf.normalize();\n    }\n}\n\nfloat Mesh::surfaceArea(uint32_t index) const {\n    uint32_t i0 = m_F(0, index), i1 = m_F(1, index), i2 = m_F(2, index);\n\n    const Point3f p0 = m_V.col(i0), p1 = m_V.col(i1), p2 = m_V.col(i2);\n\n    return 0.5f * Vector3f((p1 - p0).cross(p2 - p0)).norm();\n}\n\nbool Mesh::rayIntersect(uint32_t index, const Ray3f &ray, float &u, float &v, float &t) const {\n    uint32_t i0 = m_F(0, index), i1 = m_F(1, index), i2 = m_F(2, index);\n    const Point3f p0 = m_V.col(i0), p1 = m_V.col(i1), p2 = m_V.col(i2);\n\n    /* Find vectors for two edges sharing v[0] */\n    Vector3f edge1 = p1 - p0, edge2 = p2 - p0;\n\n    /* Begin calculating determinant - also used to calculate U parameter */\n    Vector3f pvec = ray.d.cross(edge2);\n\n    /* If determinant is near zero, ray lies in plane of triangle */\n    float det = edge1.dot(pvec);\n\n    if (det > -1e-8f && det < 1e-8f)\n        return false;\n    float inv_det = 1.0f / det;\n\n    /* Calculate distance from v[0] to ray origin */\n    Vector3f tvec = ray.o - p0;\n\n    /* Calculate U parameter and test bounds */\n    u = tvec.dot(pvec) * inv_det;\n    if (u < 0.0 || u > 1.0)\n        return false;\n\n    /* Prepare to test V parameter */\n    Vector3f qvec = tvec.cross(edge1);\n\n    /* Calculate V parameter and test bounds */\n    v = ray.d.dot(qvec) * inv_det;\n    if (v < 0.0 || u + v > 1.0)\n        return false;\n\n    /* Ray intersects triangle -> compute t */\n    t = edge2.dot(qvec) * inv_det;\n\n    return t >= ray.mint && t <= ray.maxt;\n}\n\nBoundingBox3f Mesh::getBoundingBox(uint32_t index) const {\n    BoundingBox3f result(m_V.col(m_F(0, index)));\n    result.expandBy(m_V.col(m_F(1, index)));\n    result.expandBy(m_V.col(m_F(2, index)));\n    return result;\n}\n\nPoint3f Mesh::getCentroid(uint32_t index) const {\n    return (1.0f / 3.0f) *\n        (m_V.col(m_F(0, index)) +\n         m_V.col(m_F(1, index)) +\n         m_V.col(m_F(2, index)));\n}\n\nvoid Mesh::addChild(NoriObject *obj) {\n    switch (obj->getClassType()) {\n        case EBSDF:\n            if (m_bsdf)\n                throw NoriException(\n                    \"Mesh: tried to register multiple BSDF instances!\");\n            m_bsdf = static_cast<BSDF *>(obj);\n            break;\n\n        case EEmitter: {\n                Emitter *emitter = static_cast<Emitter *>(obj);\n                if (m_emitter)\n                    throw NoriException(\n                        \"Mesh: tried to register multiple Emitter instances!\");\n                m_emitter = emitter;\n            }\n            break;\n\n        default:\n            throw NoriException(\"Mesh::addChild(<%s>) is not supported!\",\n                                classTypeName(obj->getClassType()));\n    }\n}\n\nstd::string Mesh::toString() const {\n    return tfm::format(\n        \"Mesh[\\n\"\n        \"  name = \\\"%s\\\",\\n\"\n        \"  vertexCount = %i,\\n\"\n        \"  triangleCount = %i,\\n\"\n        \"  bsdf = %s,\\n\"\n        \"  emitter = %s\\n\"\n        \"]\",\n        m_name,\n        m_V.cols(),\n        m_F.cols(),\n        m_bsdf ? indent(m_bsdf->toString()) : std::string(\"null\"),\n        m_emitter ? indent(m_emitter->toString()) : std::string(\"null\")\n    );\n}\n\nstd::string Intersection::toString() const {\n    if (!mesh)\n        return \"Intersection[invalid]\";\n\n    return tfm::format(\n        \"Intersection[\\n\"\n        \"  p = %s,\\n\"\n        \"  t = %f,\\n\"\n        \"  uv = %s,\\n\"\n        \"  shFrame = %s,\\n\"\n        \"  geoFrame = %s,\\n\"\n        \"  mesh = %s\\n\"\n        \"]\",\n        p.toString(),\n        t,\n        uv.toString(),\n        indent(shFrame.toString()),\n        indent(geoFrame.toString()),\n        mesh ? mesh->toString() : std::string(\"null\")\n    );\n}\n\nPoint3f Mesh::squareToUniformMesh(Sampler *sampler, Normal3f &n, float &pdf) const {\n    Point2f sample2D = sampler->next2D();\n    float ep1 = sample2D.x(), ep2 = sample2D.y();\n\n    //important: use another random number!\n    size_t tri_idx = dpdf.sample(sampler->next1D());\n\n    uint32_t idx0 = m_F(0, tri_idx), idx1 = m_F(1, tri_idx), idx2 = m_F(2, tri_idx);\n    Point3f p0 = m_V.col(idx0), p1 = m_V.col(idx1), p2 = m_V.col(idx2);\n\n    float alpha = 1.0f - sqrt(1.0f - ep1), beta = ep2 * sqrt(1.0f - ep1), gamma = 1.0f - alpha - beta;\n    if(m_N.size() > 0){\n        n = alpha * m_N.col(idx0) + beta * m_N.col(idx1) + gamma * m_N.col(idx2);\n    }else{\n        n = Normal3f((p1 - p0).cross(p2 - p0));\n    }\n    n.normalize();\n    pdf = dpdf.getNormalization();\n    return alpha * p0 + beta * p1 + gamma * p2;\n}\n\nfloat Mesh::squareToUniformMeshPDF() const {\n    return dpdf.getNormalization();\n}\nNORI_NAMESPACE_END\n", "meta": {"hexsha": "4b397cac41166169398a3affec797c4cec57234e", "size": 5319, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mesh.cpp", "max_stars_repo_name": "liu-xiao-ke/KRenderer", "max_stars_repo_head_hexsha": "d567d46c96423e59855f276666d0d88ad8a67f27", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/mesh.cpp", "max_issues_repo_name": "liu-xiao-ke/KRenderer", "max_issues_repo_head_hexsha": "d567d46c96423e59855f276666d0d88ad8a67f27", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mesh.cpp", "max_forks_repo_name": "liu-xiao-ke/KRenderer", "max_forks_repo_head_hexsha": "d567d46c96423e59855f276666d0d88ad8a67f27", "max_forks_repo_licenses": ["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.2925531915, "max_line_length": 102, "alphanum_fraction": 0.5572476029, "num_tokens": 1591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.5926665999540697, "lm_q1q2_score": 0.4745434064926261}}
{"text": "#include <string>\n\n#define BOOST_TEST_MODULE SparseCompareTests\n\n\n\n\n#include \"MIAConfig.h\"\n\n#ifdef MIA_USE_HEADER_ONLY_TESTS\r\n#include <boost/test/included/unit_test.hpp>\r\n#else\r\n#include <boost/test/unit_test.hpp>\r\n#endif\n#include \"DenseMIA.h\"\r\n#include \"SparseMIA.h\"\n\r\n\r\n\r\n\n\r\n\r\ntemplate<typename data_type>\r\nvoid do_work(size_t dim1, size_t dim2, size_t dim3){\n\n\r\n    typedef LibMIA::SparseMIA<data_type,3> MIAType;\r\n    MIAType test1(dim1,dim2,dim3);\r\n    test1.resize(test1.dimensionality()/2);\r\n    //testing resize functionality\r\n    BOOST_CHECK_MESSAGE(test1.data_end()-test1.data_begin()==test1.dimensionality()/2,std::string(\"Resize test of data for \")+typeid(data_type).name());\r\n    BOOST_CHECK_MESSAGE(test1.index_end()-test1.index_begin()==test1.dimensionality()/2,std::string(\"Resize test of indices for \")+typeid(data_type).name());\n\r\n    //test sorting\n    test1.rand_indices();\r\n    test1.sort();\r\n    bool passed=true;\r\n    for(auto i=test1.index_begin()+1;i<test1.index_end();++i)\r\n        passed=(passed&& *(i-1)<=*i);\r\n    BOOST_CHECK_MESSAGE(passed,std::string(\"Sorting test for \")+typeid(data_type).name());\r\n\r\n    //testing removal of duplicates\r\n    test1.randu(0,2);\r\n    *(test1.data_begin())=2;\r\n    *(test1.data_begin()+1)=1;\r\n    *(test1.index_begin())=2;\r\n    *(test1.index_begin()+1)=1;\r\n    test1.setSorted(false);\r\n    auto i=test1.index_begin()+2;\r\n    for(auto data_it=test1.data_begin()+2;i<test1.index_end();++i,++data_it)\r\n        if (*data_it>=1){\r\n            *data_it=2;\r\n            *i=2;\r\n        }\r\n        else{\r\n            *data_it=1;\r\n            *i=1;\r\n        }\r\n\r\n    test1.collect_duplicates();\r\n    BOOST_CHECK_MESSAGE(test1.data_end()-test1.data_begin()==2,std::string(\"Collect duplicates test 1 of data size for \")+typeid(data_type).name());\r\n    BOOST_CHECK_MESSAGE(test1.index_end()-test1.index_begin()==2,std::string(\"Collect duplicates test 1 of indices size for \")+typeid(data_type).name());\r\n    passed=(*(test1.data_begin())==1 && *(test1.data_begin()+1)==2);\r\n    BOOST_CHECK_MESSAGE(passed,std::string(\"Collect duplicates test 1 of data content for \")+typeid(data_type).name());\r\n\r\n    //testing collection of duplicates where we add duplicated entries\r\n    test1.resize(test1.dimensionality()/2);\r\n    test1.randu(0,2);\r\n    *(test1.data_begin())=1;\r\n    *(test1.data_begin()+1)=1;\r\n    *(test1.index_begin())=2;\r\n    *(test1.index_begin()+1)=1;\r\n    test1.setSorted(false);\r\n    size_t counter1=1,counter2=1;\r\n    i=test1.index_begin()+2;\r\n    for(auto data_it=test1.data_begin()+2;i<test1.index_end();++i,++data_it)\r\n        if (*data_it>=1){\r\n            *data_it=1;\r\n            *i=1;\r\n            ++counter1;\r\n        }\r\n        else{\r\n            *data_it=1;\r\n            *i=2;\r\n            ++counter2;\r\n        }\r\n\r\n\r\n    test1.collect_duplicates(std::plus<data_type>());\r\n    BOOST_CHECK_MESSAGE(test1.data_end()-test1.data_begin()==2,std::string(\"Collect duplicates test 2 of data size for \")+typeid(data_type).name());\r\n    BOOST_CHECK_MESSAGE(test1.index_end()-test1.index_begin()==2,std::string(\"Collect duplicates test 2 of indices size for \")+typeid(data_type).name());\r\n    passed=(*(test1.data_begin())==(data_type)counter1 && *(test1.data_begin()+1)==(data_type)counter2);\r\n    BOOST_CHECK_MESSAGE(passed,std::string(\"Collect duplicates test 2 of data content for \")+typeid(data_type).name());\r\n\r\n    MIAType test2; //zero dimensionality\r\n\r\n    test2.rand_indices(); //make sure no error thrown when dimensionality is zero\r\n\r\n\r\n    LibMIA::SparseMIA<data_type,4> test_reorder(dim1,dim2,dim3,dim2);\r\n    LibMIA::SparseMIA<data_type,4> test_reorder2;\r\n    auto linIdxSequence=test_reorder.linIdxSequence();\r\n\r\n    linIdxSequence={{2,0,3,1}};\r\n\r\n    test_reorder.resize(test_reorder.dimensionality()/2);\r\n    test_reorder.randu(-5,5);\r\n    test_reorder.rand_indices();\r\n    test_reorder.collect_duplicates();\n    test_reorder2=test_reorder;\r\n    test_reorder.sort(linIdxSequence);\r\n    test_reorder2.change_linIdx_sequence(linIdxSequence);\r\n    test_reorder2.sort();\r\n    passed=true;\r\n    auto data_it=test_reorder.data_begin();\r\n    auto data_it2=test_reorder2.data_begin();\r\n    auto it=test_reorder.index_begin();\r\n    auto it2=test_reorder2.index_begin();\r\n    for(;data_it<test_reorder.data_end();++data_it,++it,++data_it2,++it2){ //do a manual check, b/c if we use == operator, a sort will occur, nullifying the test\r\n        if(*data_it!=*data_it2){\r\n            passed=false;\r\n            break;\r\n        }\r\n        if(*it!=*it2){\r\n            passed=false;\r\n            break;\r\n        }\r\n    }\r\n\r\n    BOOST_CHECK_MESSAGE(passed,std::string(\"Sparse reording sort 1 for \")+typeid(data_type).name());\r\n\r\n    //try another linIdxSequence\r\n    linIdxSequence={{1,2,3,0}};\r\n    test_reorder2=test_reorder;\r\n    test_reorder.sort(linIdxSequence);\r\n    test_reorder2.change_linIdx_sequence(linIdxSequence);\r\n    test_reorder2.sort();\r\n    passed=true;\r\n    data_it=test_reorder.data_begin();\r\n    data_it2=test_reorder2.data_begin();\r\n    it=test_reorder.index_begin();\r\n    it2=test_reorder2.index_begin();\r\n    for(;data_it<test_reorder.data_end();++data_it,++it,++data_it2,++it2){ //do a manual check, b/c if we use == operator, a sort will occur, nullifying the test\r\n        if(*data_it!=*data_it2){\r\n            passed=false;\r\n            break;\r\n        }\r\n        if(*it!=*it2){\r\n            passed=false;\r\n            break;\r\n        }\r\n    }\r\n\r\n    BOOST_CHECK_MESSAGE(passed,std::string(\"Sparse reording sort 2 for \")+typeid(data_type).name());\r\n\r\n    //try another linIdxSequence\r\n    linIdxSequence={{0,1,2,3}};\r\n    test_reorder2=test_reorder;\r\n    test_reorder.sort(linIdxSequence);\r\n    test_reorder2.change_linIdx_sequence(linIdxSequence);\r\n    test_reorder2.sort();\r\n    passed=true;\r\n    data_it=test_reorder.data_begin();\r\n    data_it2=test_reorder2.data_begin();\r\n    it=test_reorder.index_begin();\r\n    it2=test_reorder2.index_begin();\r\n    for(;data_it<test_reorder.data_end();++data_it,++it,++data_it2,++it2){ //do a manual check, b/c if we use == operator, a sort will occur, nullifying the test\r\n        if(*data_it!=*data_it2){\r\n            passed=false;\r\n            break;\r\n        }\r\n        if(*it!=*it2){\r\n            passed=false;\r\n            break;\r\n        }\r\n    }\r\n\r\n    BOOST_CHECK_MESSAGE(passed,std::string(\"Sparse reording sort 3 for \")+typeid(data_type).name());\r\n\r\n    //try another linIdxSequence\r\n    linIdxSequence={{2,3,0,1}};\r\n    test_reorder2=test_reorder;\r\n    test_reorder.sort(linIdxSequence);\r\n    test_reorder2.change_linIdx_sequence(linIdxSequence);\r\n    test_reorder2.sort();\r\n    passed=true;\r\n    data_it=test_reorder.data_begin();\r\n    data_it2=test_reorder2.data_begin();\r\n    it=test_reorder.index_begin();\r\n    it2=test_reorder2.index_begin();\r\n    for(;data_it<test_reorder.data_end();++data_it,++it,++data_it2,++it2){ //do a manual check, b/c if we use == operator, a sort will occur, nullifying the test\r\n        if(*data_it!=*data_it2){\r\n            passed=false;\r\n            break;\r\n        }\r\n        if(*it!=*it2){\r\n            passed=false;\r\n            break;\r\n        }\r\n    }\r\n\r\n    BOOST_CHECK_MESSAGE(passed,std::string(\"Sparse reording sort 3 for \")+typeid(data_type).name());\r\n\r\n\n}\n\n\n\r\n\r\nBOOST_AUTO_TEST_CASE( SparseCompareTests )\n{\n\r\n    //size_t dim1=3,dim2=4,dim3=5;\r\n    size_t dim1=3,dim2=3,dim3=3;\r\n\r\n\r\n    do_work<float>(dim1,dim2,dim3);\n    do_work<double>(dim1,dim2,dim3);\n    do_work<int32_t>(dim1,dim2,dim3);\n    do_work<int64_t>(dim1,dim2,dim3);\n}\r\n", "meta": {"hexsha": "fc6bd7215c3a2a83a8b99efabde6b55dd99294d5", "size": 7524, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tests/SparseMIA/sparse_mia_functions.cpp", "max_stars_repo_name": "extragoya/LibNT", "max_stars_repo_head_hexsha": "60372bf4e3c5d6665185358c4756da4fe547f093", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-26T05:11:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-26T05:11:32.000Z", "max_issues_repo_path": "src/tests/SparseMIA/sparse_mia_functions.cpp", "max_issues_repo_name": "extragoya/LibNT", "max_issues_repo_head_hexsha": "60372bf4e3c5d6665185358c4756da4fe547f093", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/SparseMIA/sparse_mia_functions.cpp", "max_forks_repo_name": "extragoya/LibNT", "max_forks_repo_head_hexsha": "60372bf4e3c5d6665185358c4756da4fe547f093", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-09-21T15:38:23.000Z", "max_forks_repo_forks_event_max_datetime": "2017-09-21T15:38:23.000Z", "avg_line_length": 33.8918918919, "max_line_length": 162, "alphanum_fraction": 0.6383572568, "num_tokens": 1976, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.4745216511817006}}
{"text": "// Copyright (c) 2021 Graphcore Ltd. All rights reserved.\n#define BOOST_TEST_MODULE ConstExprReduceProdUnittest\n\n#include <boost/optional.hpp>\n#include <boost/test/unit_test.hpp>\n\n#include <popart/ces/reduceprodce.hpp>\n#include <popart/graph.hpp>\n#include <popart/ir.hpp>\n#include <popart/op/reduceprod.hpp>\n\n#include <string>\n\nusing namespace popart;\n\nconst Shape SHAPE          = {2, 3, 5};\nconst int64_t RANK         = SHAPE.size();\nconst int64_t ELEMENT_SIZE = sizeof(int64_t);\n\n// Constant folds a ReduceProd with the provided keepdims and axes atributes and\n// a 2 * 3 * 5 constant tensor of 2s as input.\nvoid check_combination(nonstd::optional_lite::optional<Shape> axes,\n                       int64_t keepdims,\n                       int64_t num_elements) {\n\n  // Print out axes and keepdims\n  BOOST_TEST_MESSAGE(\"keepdims: \" + std::to_string(keepdims));\n  std::string axes_string;\n  if (axes.has_value()) {\n    for (auto axis : axes.value()) {\n      axes_string += std::to_string(axis) + \" \";\n    }\n    BOOST_TEST_MESSAGE(\"axes: \" + axes_string);\n  } else\n    BOOST_TEST_MESSAGE(\"no axes provided\");\n  BOOST_TEST_MESSAGE(\"\");\n\n  // Create a small graph with one node and one constant tensor\n  Ir ir;\n  Graph &g = ir.getMainGraph();\n\n  Op::Settings settings(g, \"test_reduceprod\");\n\n  // set up input and output tensors\n  const TensorInfo input_info{DataType::INT64, SHAPE};\n  const std::vector<int64_t> input_data(input_info.nelms(), 2);\n  g.addConstInit(\"input\", input_info, input_data.data(), \"input_init\");\n  g.addActGrad(\"output\");\n\n  auto op = g.createConnectedOp<ReduceProdOp>(\n      {{ReduceProdOp::getInIndex(), \"input\"}},\n      {{ReduceProdOp::getOutIndex(), \"output\"}},\n      Onnx::Operators::ReduceProd_11,\n      axes,\n      keepdims,\n      settings);\n\n  ConstExprReduceProd ce_reduce_prod(op);\n  ce_reduce_prod;\n\n  int64_t expected_element = 1\n                             << (SHAPE[0] * SHAPE[1] * SHAPE[2] / num_elements);\n\n  // The result returned is just a memcpy of the raw array in the resulting\n  // tensor. 8 bytes per element.\n  auto result = ce_reduce_prod.compute();\n\n  // Check that the result has the size we expect\n  BOOST_REQUIRE_MESSAGE(num_elements * ELEMENT_SIZE == result.size(),\n                        \"Number of returned bytes was \" +\n                            std::to_string(result.size()) + \"; expected \" +\n                            std::to_string(num_elements * ELEMENT_SIZE));\n\n  // Compare the bytes to what we expect to see\n  for (int i = 0; i < num_elements; i++) {\n    int64_t returned_element;\n    std::memcpy(\n        &returned_element, &result.data()[i * ELEMENT_SIZE], ELEMENT_SIZE);\n\n    BOOST_CHECK_MESSAGE(expected_element == returned_element,\n                        \"expected element \" + std::to_string(expected_element) +\n                            \", got \" + std::to_string(returned_element));\n  }\n}\n\nBOOST_AUTO_TEST_CASE(TestConstExprReduceProd) {\n  // positive axes\n  for (int combination = 0; combination < (1 << RANK); ++combination) {\n    Shape axes;\n    int64_t num_elements = 1;\n    for (int i = 0; i < RANK; ++i) {\n      if ((combination >> i) & 1)\n        axes.push_back(i);\n      else\n        num_elements *= SHAPE[i];\n    }\n    check_combination(axes, 0, num_elements);\n    check_combination(axes, 1, num_elements);\n  }\n\n  // negative axes\n  for (int combination = 1; combination < (1 << RANK); ++combination) {\n    Shape axes;\n    int64_t num_elements = 1;\n    for (int i = 0; i < RANK; i++) {\n      if ((combination >> i) & 1)\n        axes.push_back(-i - 1);\n      else\n        num_elements *= SHAPE[2 - i];\n    }\n    check_combination(axes, 0, num_elements);\n    check_combination(axes, 1, num_elements);\n  }\n\n  // no axes\n  check_combination(nonstd::nullopt, 0, 1);\n  check_combination(nonstd::nullopt, 1, 1);\n\n  // duplicated axes\n  check_combination(Shape{1, 1}, 0, 10);\n  check_combination(Shape{1, -2}, 1, 10);\n\n  // mixed negative and positive axes\n  check_combination(Shape{1, -1}, 0, 2);\n  check_combination(Shape{1, -3}, 1, 5);\n}", "meta": {"hexsha": "148206803c213ed8c3c4df46de4d2a4b7369b7a7", "size": 4019, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/unittests/ces/reduceprodce.cpp", "max_stars_repo_name": "graphcore/popart", "max_stars_repo_head_hexsha": "15ce5b098638dc34a4d41ae2a7621003458df798", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 61.0, "max_stars_repo_stars_event_min_datetime": "2020-07-06T17:11:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T14:42:51.000Z", "max_issues_repo_path": "tests/unittests/ces/reduceprodce.cpp", "max_issues_repo_name": "graphcore/popart", "max_issues_repo_head_hexsha": "15ce5b098638dc34a4d41ae2a7621003458df798", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-02-25T01:30:29.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-09T11:13:14.000Z", "max_forks_repo_path": "tests/unittests/ces/reduceprodce.cpp", "max_forks_repo_name": "graphcore/popart", "max_forks_repo_head_hexsha": "15ce5b098638dc34a4d41ae2a7621003458df798", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-07-15T12:33:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-07T06:55:00.000Z", "avg_line_length": 31.8968253968, "max_line_length": 80, "alphanum_fraction": 0.6387160985, "num_tokens": 1077, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850402140659, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.4745216507086085}}
{"text": "\n#include <Eigen/Dense>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <cmath>\n#include \"UKF/Types.h\"\n#include \"UKF/Integrator.h\"\n#include \"UKF/StateVector.h\"\n#include \"UKF/MeasurementVector.h\"\n#include \"UKF/Core.h\"\n#include \"filter.h\"\n\nstatic double fov = 90;\nstatic int width = 672;\nstatic int height = 672;\n\nenum StateFields {\n    CameraPosition,\n    CameraQuat,\n    CameraVelocity,\n    CameraAngVelocity,\n    CameraAcceleration,\n    CameraAngAcceleration,\n    ActorPosition,\n    ActorYaw,\n    ActorVelocity,\n    ActorYawVelocity,\n    ActorAcceleration,\n    ActorYawAcceleration\n};\n\nusing TrajectoryStateVector = UKF::StateVector<\n    UKF::Field<CameraPosition, UKF::Vector<3>>,\n    UKF::Field<CameraQuat, UKF::Vector<4>>,\n    UKF::Field<CameraVelocity, UKF::Vector<3>>,\n    UKF::Field<CameraAngVelocity, UKF::Vector<3>>,\n    UKF::Field<CameraAcceleration, UKF::Vector<3>>,\n    UKF::Field<CameraAngAcceleration, UKF::Vector<3>>,\n    UKF::Field<ActorPosition, UKF::Vector<3>>,\n    UKF::Field<ActorYaw, real_t>,\n    UKF::Field<ActorVelocity, UKF::Vector<3>>,\n    UKF::Field<ActorYawVelocity, real_t>,\n    UKF::Field<ActorAcceleration, UKF::Vector<3>>,\n    UKF::Field<ActorYawAcceleration, real_t>\n>;\n\n\nnamespace UKF {\n    template <> template<>\n    TrajectoryStateVector TrajectoryStateVector::derivative<>() const {\n        TrajectoryStateVector temp;\n\n        /* Position derivative */\n        temp.set_field<CameraPosition>(get_field<CameraVelocity>());\n        UKF::Vector<3> ang_vel = get_field<CameraAngVelocity>();\n        float cr = std::cos(ang_vel[0] * 0.5);\n        float sr = std::sin(ang_vel[0] * 0.5);\n        float cp = std::cos(ang_vel[1] * 0.5);\n        float sp = std::sin(ang_vel[1] * 0.5);\n        float cy = std::cos(ang_vel[2] * 0.5);\n        float sy = std::sin(ang_vel[2] * 0.5);\n        temp.set_field<CameraQuat>(\n            UKF::Vector<4>(cr * cp * cy + sr * sp * sy, //w\n                            sr * cp * cy - cr * sp * sy, //x\n                            cr * sp * cy + sr * cp * sy, //y\n                            cr * cp * sy - sr * sp * cy  //z\n                            ));\n\n        /* Velocity derivative */\n        temp.set_field<CameraVelocity>(get_field<CameraAcceleration>());\n        temp.set_field<CameraAngVelocity>(get_field<CameraAngAcceleration>());\n\n        /* Acceleration derivative */\n        temp.set_field<CameraAcceleration>(Vector<3>(0,0,0));\n        temp.set_field<CameraAngAcceleration>(0);\n\n        /* Position derivative */\n        temp.set_field<ActorPosition>(get_field<ActorVelocity>());\n        temp.set_field<ActorYaw>(get_field<ActorYawVelocity>());\n\n        /* Velocity derivative */\n        temp.set_field<ActorVelocity>(get_field<ActorAcceleration>());\n        temp.set_field<ActorYawVelocity>(get_field<ActorYawAcceleration>());\n\n        /* Acceleration derivative */\n        temp.set_field<ActorAcceleration>(Vector<3>(0,0,0));\n        temp.set_field<ActorYawAcceleration>(0);\n\n        return temp;\n    }\n}\n\nenum MeasurementFields {\n    BoundingBox,\n    Depth,\n    DronePosition,\n    DroneYaw,\n    DronePitch,\n    HDE\n};\n\nusing MeasurementVector = UKF::DynamicMeasurementVector<\n    UKF::Field<BoundingBox, UKF::Vector<2>>,\n    UKF::Field<Depth, real_t>,\n    UKF::Field<DronePosition, UKF::Vector<3>>,\n    UKF::Field<DroneYaw, real_t>,\n    UKF::Field<DronePitch, real_t>,\n    UKF::Field<HDE, real_t>\n>;\n\nusing MotionForecastingCore = UKF::Core<\n    TrajectoryStateVector,\n    MeasurementVector,\n    UKF::IntegratorRK4\n>;\n\nUKF::Vector<4> flatten(UKF::Vector<4> quat) {\n    double length = sqrt(quat[0] * quat[0] + quat[3] * quat[3]);\n    return UKF::Vector<4>(quat[0] / length, 0, 0, quat[3] / length);\n}\n\nfloat getYaw(UKF::Vector<4> q) {\n    q = flatten(q);\n    double siny_cosp = 2 * (q[0] * q[3] + q[1] * q[2]);\n    double cosy_cosp = 1 - 2 * (q[2] * q[2] + q[3] * q[3]);\n    return std::atan2(siny_cosp, cosy_cosp);\n}\n\nfloat getPitch(UKF::Vector<4> q) {\n    UKF::Vector<4> f = flatten(q);\n\n    float dot_product = f[0] * q[0] + f[1] * q[1] + f[2] * q[2] + f[3] * q[3];\n    float angle = acos(2*dot_product*dot_product - 1);\n    return angle;\n}\n\nnamespace UKF {\n    template <> template <>\n    UKF::Vector<2> MeasurementVector::expected_measurement\n    <TrajectoryStateVector, BoundingBox>(\n            const TrajectoryStateVector& state) {\n        double fx = width/fov;\n        double fy = height/fov;\n        int cu = width/2;\n        int cv = height/2;\n\n        UKF::Vector<3> diff = state.get_field<ActorPosition>() - state.get_field<CameraPosition>();\n\n        float camera_yaw = getYaw(state.get_field<CameraQuat>());\n        float camera_pitch = getPitch(state.get_field<CameraQuat>());\n\n        float actor_yaw = std::atan2(diff[0], diff[1]);\n        float actor_pitch = std::atan2(diff[2], std::sqrt(diff[1]*diff[1] + diff[0]*diff[0]));\n\n        int u = fx*(actor_yaw - camera_yaw) + cu;\n        int v = fy*(actor_pitch - camera_pitch) + cv;\n\n        return UKF::Vector<2>(u, v);\n    }\n    template <> template <>\n    real_t MeasurementVector::expected_measurement\n    <TrajectoryStateVector, Depth>(\n            const TrajectoryStateVector& state) {\n        // Calculate vector r_q/c between drone and actor, and get the magnitude of that\n        UKF::Vector<3> diff = state.get_field<CameraPosition>() - state.get_field<ActorPosition>();\n        return diff.norm();\n    }\n    template <> template <>\n    UKF::Vector<3> MeasurementVector::expected_measurement\n    <TrajectoryStateVector, DronePosition>(\n            const TrajectoryStateVector& state) {\n        return state.get_field<CameraPosition>();\n    }\n    template <> template <>\n    real_t MeasurementVector::expected_measurement\n    <TrajectoryStateVector, DroneYaw>(\n            const TrajectoryStateVector& state) {\n        UKF::Vector<4> q = state.get_field<CameraQuat>();\n        return getYaw(q);\n    }\n    template <> template <>\n    real_t MeasurementVector::expected_measurement\n    <TrajectoryStateVector, DronePitch>(\n            const TrajectoryStateVector& state) {\n        UKF::Vector<4> q = state.get_field<CameraQuat>();\n        return getPitch(q);\n    }\n    template <> template <>\n    real_t MeasurementVector::expected_measurement\n    <TrajectoryStateVector, HDE>(\n            const TrajectoryStateVector& state) {\n        float yaw_actor = state.get_field<ActorYaw>();\n        float yaw_camera = getYaw(state.get_field<CameraQuat>());\n        return yaw_actor - yaw_camera;\n    }\n}\n\nstatic MotionForecastingCore filter;\nstatic MeasurementVector meas;\n\nvoid ukf_init(float x, float y, float z, float yaw) {\n    filter.state.set_field<CameraPosition>(UKF::Vector<3>(0,0,0));\n    filter.state.set_field<CameraQuat>(UKF::Vector<4>(cos(yaw/2), 0, 0, sin(yaw/2)));\n    filter.state.set_field<CameraVelocity>(UKF::Vector<3>(0,0,0));\n    filter.state.set_field<CameraAngVelocity>(UKF::Vector<3>(0,0,0));\n    filter.state.set_field<CameraAcceleration>(UKF::Vector<3>(0,0,0));\n    filter.state.set_field<CameraAngAcceleration>(UKF::Vector<3>(0,0,0));\n    filter.state.set_field<ActorPosition>(UKF::Vector<3>(0,0,0));\n    filter.state.set_field<ActorYaw>(0);\n    filter.state.set_field<ActorVelocity>(UKF::Vector<3>(0,0,0));\n    filter.state.set_field<ActorYawVelocity>(0);\n    filter.state.set_field<ActorAcceleration>(UKF::Vector<3>(0,0,0));\n    filter.state.set_field<ActorYawAcceleration>(0);\n    filter.covariance = TrajectoryStateVector::CovarianceMatrix::Identity();\n\n    filter.process_noise_covariance = TrajectoryStateVector::CovarianceMatrix::Identity() * 0.1;\n    filter.measurement_covariance << 1e-2, 1e-2, 0.1, 0.2, 0.2, 0.2, 0.1, 0.1, 1e-2;\n}\n\n\ncinematography_msgs::msg::MultiDOF get_state(rclcpp::Duration duration) {\n    cinematography_msgs::msg::MultiDOF point;\n    point.duration = duration.seconds();\n    point.x = filter.state.get_field<ActorPosition>()[0];\n    point.y = filter.state.get_field<ActorPosition>()[1];\n    point.z = filter.state.get_field<ActorPosition>()[2];\n    point.yaw = filter.state.get_field<ActorYaw>();\n    point.vx = filter.state.get_field<ActorVelocity>()[0];\n    point.vy = filter.state.get_field<ActorVelocity>()[1];\n    point.vz = filter.state.get_field<ActorVelocity>()[2];\n    point.ax = filter.state.get_field<ActorAcceleration>()[0];\n    point.ay = filter.state.get_field<ActorAcceleration>()[1];\n    point.az = filter.state.get_field<ActorAcceleration>()[2];\n\n    return point;\n}\n\ncinematography_msgs::msg::MultiDOF get_state(rclcpp::Duration duration, MotionForecastingCore filter) {\n    cinematography_msgs::msg::MultiDOF point;\n    point.duration = duration.seconds();\n    point.x = filter.state.get_field<ActorPosition>()[0];\n    point.y = filter.state.get_field<ActorPosition>()[1];\n    point.z = filter.state.get_field<ActorPosition>()[2];\n    point.yaw = filter.state.get_field<ActorYaw>();\n    point.vx = filter.state.get_field<ActorVelocity>()[0];\n    point.vy = filter.state.get_field<ActorVelocity>()[1];\n    point.vz = filter.state.get_field<ActorVelocity>()[2];\n    point.ax = filter.state.get_field<ActorAcceleration>()[0];\n    point.ay = filter.state.get_field<ActorAcceleration>()[1];\n    point.az = filter.state.get_field<ActorAcceleration>()[2];\n\n    return point;\n}\n\n// forecast length must be at least 2 (now and next point)\nstd::vector<cinematography_msgs::msg::MultiDOF> ukf_iterate(rclcpp::Duration point_duration, int forecast_length) {\n    if (forecast_length < 2) {\n        return std::vector<cinematography_msgs::msg::MultiDOF>();\n    }\n\n    std::vector<cinematography_msgs::msg::MultiDOF> path;\n    path.reserve(forecast_length);\n\n    path[0] = get_state(point_duration);\n    \n    filter.step(point_duration.seconds(), meas);\n    path[1] = get_state(point_duration);\n\n    MotionForecastingCore forecaster = filter;\n    for(int i = 2; i < forecast_length; i++) {\n        forecaster.step(point_duration.seconds(), MeasurementVector());\n        path[i] = get_state(point_duration, forecaster);\n    }\n\n    return path;\n}\n\nvoid ukf_meas_clear() {\n    meas = MeasurementVector();\n}\n\nvoid ukf_set_fov(float f) {\n    fov = f;\n}\n\nvoid ukf_set_bb(float width, float height) {\n    meas.set_field<BoundingBox>(UKF::Vector<2>(width, height));\n}\n\nvoid ukf_set_depth(float depth) {\n    meas.set_field<Depth>(depth);\n}\n\nvoid ukf_set_position(float x, float y, float z) {\n    meas.set_field<DronePosition>(UKF::Vector<3>(x, y, z));\n}\n\nvoid ukf_set_yaw(float yaw) {\n    meas.set_field<DroneYaw>(yaw);\n}\n\nvoid ukf_set_pitch(float pitch) {\n    meas.set_field<DronePitch>(pitch);\n}\n\nvoid ukf_set_hde(float hde) {\n    meas.set_field<HDE>(hde);\n}", "meta": {"hexsha": "40acfa75fc9c57473389ba6cade08c7fbec5d738", "size": 10573, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ros2/src/cinematography/src/filter.cpp", "max_stars_repo_name": "nightduck/AirSim", "max_stars_repo_head_hexsha": "2ba7124ceff7607f23463f483cd3e2cbe026d0ca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ros2/src/cinematography/src/filter.cpp", "max_issues_repo_name": "nightduck/AirSim", "max_issues_repo_head_hexsha": "2ba7124ceff7607f23463f483cd3e2cbe026d0ca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2021-02-25T22:32:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-20T17:17:12.000Z", "max_forks_repo_path": "ros2/src/cinematography/src/filter.cpp", "max_forks_repo_name": "nightduck/AirSim", "max_forks_repo_head_hexsha": "2ba7124ceff7607f23463f483cd3e2cbe026d0ca", "max_forks_repo_licenses": ["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.3279220779, "max_line_length": 115, "alphanum_fraction": 0.6594154923, "num_tokens": 2898, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044094, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.47450443406651405}}
{"text": "///////////////////////////////////////////////////////////////\n//  Copyright 2012 John Maddock. Distributed under the Boost\n//  Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt\n\n//\n// Compare arithmetic results using fixed_int to GMP results.\n//\n\n#ifdef _MSC_VER\n#define _SCL_SECURE_NO_WARNINGS\n#endif\n\n#include <nil/crypto3/multiprecision/gmp.hpp>\n#include <nil/crypto3/multiprecision/fixed_int.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_int.hpp>\n#include \"test.hpp\"\n\ntemplate<class T>\nT generate_random(unsigned bits_wanted) {\n    static boost::random::mt19937 gen;\n    typedef boost::random::mt19937::result_type random_type;\n\n    T max_val;\n    unsigned digits;\n    if (std::numeric_limits<T>::is_bounded && (bits_wanted == std::numeric_limits<T>::digits)) {\n        max_val = (std::numeric_limits<T>::max)();\n        digits = std::numeric_limits<T>::digits;\n    } else {\n        max_val = T(1) << bits_wanted;\n        digits = bits_wanted;\n    }\n\n    unsigned bits_per_r_val = std::numeric_limits<random_type>::digits - 1;\n    while ((random_type(1) << bits_per_r_val) > (gen.max)())\n        --bits_per_r_val;\n\n    unsigned terms_needed = digits / bits_per_r_val + 1;\n\n    T val = 0;\n    for (unsigned i = 0; i < terms_needed; ++i) {\n        val *= (gen.max)();\n        val += gen();\n    }\n    val %= max_val;\n    return val;\n}\n\nint main() {\n    using namespace nil::crypto3::multiprecision;\n    typedef number<fixed_int<1024, true>> packed_type;\n    unsigned last_error_count = 0;\n    for (int i = 0; i < 1000; ++i) {\n        mpz_int a = generate_random<mpz_int>(1000);\n        mpz_int b = generate_random<mpz_int>(512);\n        mpz_int c = generate_random<mpz_int>(256);\n        mpz_int d = generate_random<mpz_int>(32);\n\n        int si = d.convert_to<int>();\n\n        packed_type a1 = a.str();\n        packed_type b1 = b.str();\n        packed_type c1 = c.str();\n        packed_type d1 = d.str();\n\n        BOOST_CHECK_EQUAL(a.str(), a1.str());\n        BOOST_CHECK_EQUAL(b.str(), b1.str());\n        BOOST_CHECK_EQUAL(c.str(), c1.str());\n        BOOST_CHECK_EQUAL(d.str(), d1.str());\n        BOOST_CHECK_EQUAL(mpz_int(a + b).str(), packed_type(a1 + b1).str());\n        BOOST_CHECK_EQUAL(mpz_int(a - b).str(), packed_type(a1 - b1).str());\n        BOOST_CHECK_EQUAL(mpz_int(mpz_int(-a) + b).str(), packed_type(packed_type(-a1) + b1).str());\n        BOOST_CHECK_EQUAL(mpz_int(mpz_int(-a) - b).str(), packed_type(packed_type(-a1) - b1).str());\n        BOOST_CHECK_EQUAL(mpz_int(c * d).str(), packed_type(c1 * d1).str());\n        BOOST_CHECK_EQUAL(mpz_int(c * -d).str(), packed_type(c1 * -d1).str());\n        BOOST_CHECK_EQUAL(mpz_int(-c * d).str(), packed_type(-c1 * d1).str());\n        BOOST_CHECK_EQUAL(mpz_int(b * c).str(), packed_type(b1 * c1).str());\n        BOOST_CHECK_EQUAL(mpz_int(a / b).str(), packed_type(a1 / b1).str());\n        BOOST_CHECK_EQUAL(mpz_int(a / -b).str(), packed_type(a1 / -b1).str());\n        BOOST_CHECK_EQUAL(mpz_int(-a / b).str(), packed_type(-a1 / b1).str());\n        BOOST_CHECK_EQUAL(mpz_int(a / d).str(), packed_type(a1 / d1).str());\n        BOOST_CHECK_EQUAL(mpz_int(a % b).str(), packed_type(a1 % b1).str());\n        BOOST_CHECK_EQUAL(mpz_int(a % -b).str(), packed_type(a1 % -b1).str());\n        BOOST_CHECK_EQUAL(mpz_int(-a % b).str(), packed_type(-a1 % b1).str());\n        BOOST_CHECK_EQUAL(mpz_int(a % d).str(), packed_type(a1 % d1).str());\n        // bitwise ops:\n        BOOST_CHECK_EQUAL(mpz_int(a | b).str(), packed_type(a1 | b1).str());\n        BOOST_CHECK_EQUAL(mpz_int(a & b).str(), packed_type(a1 & b1).str());\n        BOOST_CHECK_EQUAL(mpz_int(a ^ b).str(), packed_type(a1 ^ b1).str());\n        // Now check operations involving integers:\n        BOOST_CHECK_EQUAL(mpz_int(a + si).str(), packed_type(a1 + si).str());\n        BOOST_CHECK_EQUAL(mpz_int(a + -si).str(), packed_type(a1 + -si).str());\n        BOOST_CHECK_EQUAL(mpz_int(-a + si).str(), packed_type(-a1 + si).str());\n        BOOST_CHECK_EQUAL(mpz_int(si + a).str(), packed_type(si + a1).str());\n        BOOST_CHECK_EQUAL(mpz_int(a - si).str(), packed_type(a1 - si).str());\n        BOOST_CHECK_EQUAL(mpz_int(a - -si).str(), packed_type(a1 - -si).str());\n        BOOST_CHECK_EQUAL(mpz_int(-a - si).str(), packed_type(-a1 - si).str());\n        BOOST_CHECK_EQUAL(mpz_int(si - a).str(), packed_type(si - a1).str());\n        BOOST_CHECK_EQUAL(mpz_int(b * si).str(), packed_type(b1 * si).str());\n        BOOST_CHECK_EQUAL(mpz_int(b * -si).str(), packed_type(b1 * -si).str());\n        BOOST_CHECK_EQUAL(mpz_int(-b * si).str(), packed_type(-b1 * si).str());\n        BOOST_CHECK_EQUAL(mpz_int(si * b).str(), packed_type(si * b1).str());\n        BOOST_CHECK_EQUAL(mpz_int(a / si).str(), packed_type(a1 / si).str());\n        BOOST_CHECK_EQUAL(mpz_int(a / -si).str(), packed_type(a1 / -si).str());\n        BOOST_CHECK_EQUAL(mpz_int(-a / si).str(), packed_type(-a1 / si).str());\n        BOOST_CHECK_EQUAL(mpz_int(a % si).str(), packed_type(a1 % si).str());\n        BOOST_CHECK_EQUAL(mpz_int(a % -si).str(), packed_type(a1 % -si).str());\n        BOOST_CHECK_EQUAL(mpz_int(-a % si).str(), packed_type(-a1 % si).str());\n        BOOST_CHECK_EQUAL(mpz_int(a | si).str(), packed_type(a1 | si).str());\n        BOOST_CHECK_EQUAL(mpz_int(a & si).str(), packed_type(a1 & si).str());\n        BOOST_CHECK_EQUAL(mpz_int(a ^ si).str(), packed_type(a1 ^ si).str());\n        BOOST_CHECK_EQUAL(mpz_int(si | a).str(), packed_type(si | a1).str());\n        BOOST_CHECK_EQUAL(mpz_int(si & a).str(), packed_type(si & a1).str());\n        BOOST_CHECK_EQUAL(mpz_int(si ^ a).str(), packed_type(si ^ a1).str());\n        BOOST_CHECK_EQUAL(mpz_int(gcd(a, b)).str(), packed_type(gcd(a1, b1)).str());\n        BOOST_CHECK_EQUAL(mpz_int(lcm(c, d)).str(), packed_type(lcm(c1, d1)).str());\n\n        if (last_error_count != boost::detail::test_errors()) {\n            last_error_count = boost::detail::test_errors();\n            std::cout << std::hex << std::showbase;\n\n            std::cout << \"a    = \" << a << std::endl;\n            std::cout << \"a1   = \" << a1 << std::endl;\n            std::cout << \"b    = \" << b << std::endl;\n            std::cout << \"b1   = \" << b1 << std::endl;\n            std::cout << \"c    = \" << c << std::endl;\n            std::cout << \"c1   = \" << c1 << std::endl;\n            std::cout << \"d    = \" << d << std::endl;\n            std::cout << \"d1   = \" << d1 << std::endl;\n            std::cout << \"a + b   = \" << a + b << std::endl;\n            std::cout << \"a1 + b1 = \" << a1 + b1 << std::endl;\n            std::cout << std::dec;\n            std::cout << \"a - b   = \" << a - b << std::endl;\n            std::cout << \"a1 - b1 = \" << a1 - b1 << std::endl;\n            std::cout << \"-a + b   = \" << mpz_int(-a) + b << std::endl;\n            std::cout << \"-a1 + b1 = \" << packed_type(-a1) + b1 << std::endl;\n            std::cout << \"-a - b   = \" << mpz_int(-a) - b << std::endl;\n            std::cout << \"-a1 - b1 = \" << packed_type(-a1) - b1 << std::endl;\n            std::cout << \"c*d    = \" << c * d << std::endl;\n            std::cout << \"c1*d1  = \" << c1 * d1 << std::endl;\n            std::cout << \"b*c    = \" << b * c << std::endl;\n            std::cout << \"b1*c1  = \" << b1 * c1 << std::endl;\n            std::cout << \"a/b    = \" << a / b << std::endl;\n            std::cout << \"a1/b1  = \" << a1 / b1 << std::endl;\n            std::cout << \"a/d    = \" << a / d << std::endl;\n            std::cout << \"a1/d1  = \" << a1 / d1 << std::endl;\n            std::cout << \"a%b    = \" << a % b << std::endl;\n            std::cout << \"a1%b1  = \" << a1 % b1 << std::endl;\n            std::cout << \"a%d    = \" << a % d << std::endl;\n            std::cout << \"a1%d1  = \" << a1 % d1 << std::endl;\n        }\n    }\n    return boost::report_errors();\n}\n", "meta": {"hexsha": "ebcd2145018a0e32936806e9bc60f737acb5701c", "size": 7846, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "snark-logic/libs-source/multiprecision/test/test_fixed_int.cpp", "max_stars_repo_name": "podlodkin/podlodkin-freeton-year-control", "max_stars_repo_head_hexsha": "e394c11f2414804d2fbde93a092ae589d4359739", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-14T18:09:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-14T18:09:38.000Z", "max_issues_repo_path": "libs/multiprecision/test/test_fixed_int.cpp", "max_issues_repo_name": "Curryrasul/knapsack-snark", "max_issues_repo_head_hexsha": "633515a13906407338a81b9874d964869ddec624", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/multiprecision/test/test_fixed_int.cpp", "max_forks_repo_name": "Curryrasul/knapsack-snark", "max_forks_repo_head_hexsha": "633515a13906407338a81b9874d964869ddec624", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-12T10:53:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-12T10:53:21.000Z", "avg_line_length": 50.2948717949, "max_line_length": 100, "alphanum_fraction": 0.5503441244, "num_tokens": 2324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.63341027059799, "lm_q1q2_score": 0.4744795343604938}}
{"text": "/* areagrid - a geometric data structure which splits an area into rectangles\n*/\n#include <iostream>\n#include <tuple>\n#include <array>\n#include <algorithm>\n#include <climits>\n#include <random>\n#include <string>\n#include <sstream>\n#include <unordered_map>\n#include <unordered_set>\n#include <tuple>\n#include <algorithm>\n#include <vector>\n#include <boost/format.hpp>\n\nstruct EquiDistRange {\n    EquiDistRange(int min, int max, int divisions)\n    : min_{std::min(min, max)}, max_{std::max(min, max)}\n    , dist_{max_ - min_}\n    , divisions_{divisions}\n    , d_{static_cast<double>((dist_)/divisions_)}\n    {}\n    int operator[](int i) const {\n        return static_cast<int>(min_ + d_ * i);\n    }\n    struct Iterator { \n        const EquiDistRange& r_;\n        int index_ { 0 };\n        bool operator==(const Iterator& b) const { return index_ == b.index_; }\n        bool operator!=(const Iterator& b) const { return !(*this == b); }\n        bool operator<(const Iterator& b) const { return index_ < b.index_; }\n        bool operator<=(const Iterator& b) const { return index_ <= b.index_; }\n        bool operator>(const Iterator& b) const { return index_ > b.index_; }\n        bool operator>=(const Iterator& b) const { return index_ >= b.index_; }\n        Iterator& operator++() { ++index_; return *this; }\n        Iterator operator++(int) { auto tmp = *this; ++index_; return tmp; }\n        Iterator& operator--() { --index_; return *this; }\n        Iterator operator--(int) { auto tmp = *this; --index_; return tmp; }\n        int operator*() { return r_[index_]; }\n    };\n    Iterator begin() const { return Iterator{*this}; }\n    Iterator end() const { return Iterator{*this, divisions_ + 1}; }\n    const int min_, max_, dist_, divisions_;\n    double d_;\n};\n\nstruct Point {\n  int x, y;\n  bool is_top_left(const Point& other) const noexcept {\n    return x < other.x && y < other.y;\n  }\n  bool is_top_left_eq(const Point& other) const noexcept {\n    return x <= other.x && y <= other.y;\n  }\n  bool operator==(const Point& p) const noexcept {\n    return x == p.x && y == p.y;\n  }\n};\n\n\nstd::ostream& operator<<(std::ostream& o, const Point& p) {\n  return o << '(' << p.x << \", \" << p.y << ')';\n}\n\nstruct Rect {\n  Point min, max;\n  void sanitize() {\n    if (min.x > max.x)\n      std::swap(min.x, max.x);\n    if (min.y > max.y)\n      std::swap(min.y, max.y);\n  }\n  bool operator==(const Rect& o) const noexcept { return min == o.min && max == o.max; }\n  bool contains(const Point& p) const noexcept {\n    return min.is_top_left_eq(p) && p.is_top_left_eq(max);\n  }\n  int width() const noexcept { return max.x - min.x + 1; }\n  int height() const noexcept { return max.y - min.y + 1; }\n  int area() const noexcept { return width() * height(); }\n  bool intersects(const Rect& r, Rect* intersection = nullptr) const noexcept {\n    Rect tmp{ std::max(min.x, r.min.x)\n            , std::max(min.y, r.min.y)\n            , std::min(max.x, r.max.x)\n            , std::min(max.y, r.max.y)\n            };\n    auto tl = tmp.min.is_top_left_eq(tmp.max);\n    if (tl && intersection != nullptr) {\n      *intersection = tmp;\n    }\n    return tl;\n  }\n  Point center() const noexcept { return Point{ min.x + width()/2, min.y + height()/2};}\n  template<typename T>\n  static \n  Rect bounding_rect(T begin, const T end) {\n    Rect tmp = { INT_MAX, INT_MAX, INT_MIN, INT_MIN};\n    for(;begin != end; ++begin) {\n      const Rect* ptr = static_cast<const Rect*>(*begin);\n      tmp.min.x = std::min(ptr->min.x, tmp.min.x);\n      tmp.min.y = std::min(ptr->min.y, tmp.min.y);\n      tmp.max.x = std::max(ptr->max.x, tmp.max.x);\n      tmp.max.y = std::max(ptr->max.y, tmp.max.y);\n    }\n    return tmp;\n  }\n  template<typename T>\n  static \n  bool intersect(T begin, const T end, Rect* intersection = nullptr) {\n    Rect tmp = { INT_MIN, INT_MIN, INT_MAX, INT_MAX};\n    for(;begin != end; ++begin) {\n      const Rect* ptr = static_cast<const Rect*>(*begin);\n      if (!tmp.intersects(*ptr, &tmp))\n        return false;\n    }\n    if (intersection != nullptr) {\n      *intersection = tmp;\n    }\n    return true;\n  }\n};\n\nclass Randomizer {\npublic:\n  Randomizer(unsigned area_width  = 1'000'000\n           , unsigned area_height = 1'000'000\n           , unsigned max_width   =  200'000\n           , unsigned max_height  =  200'000) \n  : distx(0, area_width - 1)\n  , disty(0, area_height - 1)\n  , max_width_{max_width}\n  , max_height_{max_height}\n  {\n    if (area_width < max_width || area_height < max_height)\n        throw \"Randomizer: Illegal dimensions\";\n  }\n  void operator()(Point& p) {\n    p.x = distx(rd);\n    p.y = disty(rd);\n  }\n  void operator()(Rect& r) {\n    operator()(r.min);\n    std::uniform_int_distribution<unsigned> distw(0, std::min(max_width_, distx.max() - r.min.x));\n    std::uniform_int_distribution<unsigned> disth(0, std::min(max_height_, disty.max() - r.min.y));\n    r.max.x = r.min.x + distw(rd);\n    r.max.y = r.min.y + disth(rd);\n    r.sanitize();\n  }\nprivate:\n  std::random_device rd;\n  std::uniform_int_distribution<unsigned> distx;\n  std::uniform_int_distribution<unsigned> disty;\n  unsigned max_width_, max_height_;\n};\n\nstruct RectScale {\n    const Rect bounds_;\n    const unsigned width_, height_;\n    const double fx_, fy_;\n    RectScale(const Rect& bounds, unsigned width = 100, unsigned height = 100)\n    : bounds_{bounds}\n    , width_{width}\n    , height_{height} \n    , fx_{width_/static_cast<double>(bounds_.width())}\n    , fy_{height_/static_cast<double>(bounds_.height())}\n    {}\n    Rect operator()(const Rect& r) const {\n        return Rect{\n            static_cast<int>(std::floor(fx_ * ( r.min.x - bounds_.min.x)))\n          , static_cast<int>(std::floor(fy_ * ( r.min.y - bounds_.min.y)))\n          , static_cast<int>(std::ceil(fx_ * ( r.max.x - bounds_.min.x)))\n          , static_cast<int>(std::ceil(fy_ * ( r.max.y - bounds_.min.y)))\n        };\n    }\n    Point operator()(const Point& p) const {\n      return Point{\n        static_cast<int>(fx_ * (p.x - bounds_.min.x))\n      , static_cast<int>(fy_ * (p.y - bounds_.min.y))\n      };\n    }\n};\n\nstd::ostream& operator<<(std::ostream& o, const Rect& r) {\n  return o << '[' << r.min << \", \" << r.max << ']';\n}\n\nbool operator<(const Point& a, const Point& b) {\n  return std::tie(a.x, a.y) < std::tie(b.x, b.y);\n}\n\nbool operator<(const Rect& a, const Rect& b) {\n  return std::tie(a.min, a.max) < std::tie(b.min, b.max);\n}\n\nstruct VRect {\n  Rect r;\n  int value;\n  operator Rect*() noexcept { return &r; }\n  bool operator==(const VRect& o) const noexcept { return r == o.r && value == o.value;}\n};\nstd::ostream& operator<<(std::ostream& o, const VRect& r) {\n  return o << '[' << r.value << \", \" << r.r.min << \", \" << r.r.max << ']';\n}\nbool operator<(const VRect& a, const VRect& b) {\n  return a < b;\n}\n\ntemplate<typename T>\nvoid print_all(const T& l) {\n  for(const auto& e : l) {\n    std::cout << e << std::endl;\n  }\n}\n\nnamespace std\n{\n  template<> struct hash<Point>\n  {\n    typedef Point argument_type;\n    typedef std::size_t result_type;\n    result_type operator()(argument_type const& s) const noexcept\n    {\n      result_type const h1 ( std::hash<int>{}(s.x) );\n      result_type const h2 ( std::hash<int>{}(s.y) );\n      return h1 ^ (h2 << 1); \n    }\n  };\n  template<> struct hash<Rect>\n  {\n    typedef Rect argument_type;\n    typedef std::size_t result_type;\n    result_type operator()(argument_type const& s) const noexcept\n    {\n      result_type const h1 ( std::hash<Point>{}(s.min) );\n      result_type const h2 ( std::hash<Point>{}(s.max) );\n      return h1 ^ (h2 << 1); \n    }\n  };\n  template<> struct hash<VRect>\n  {\n    typedef VRect argument_type;\n    typedef std::size_t result_type;\n    result_type operator()(argument_type const& s) const noexcept\n    {\n      result_type const h1 ( std::hash<Rect>{}(s.r) );\n      result_type const h2 ( std::hash<int>{}(s.value) );\n      return h1 ^ (h2 << 1); \n    }\n  };\n}\n\nclass VRectGrid {\npublic:\n  using it_t  = std::vector<VRect>::size_type;\n  using set_t = std::unordered_set<it_t>;\n  using map_t = std::unordered_map<Point, set_t>;\n  template<typename T>\n  VRectGrid(const RectScale& scale, T begin, const T end);\n  // const set_t& operator()(int x, int y);\n  // const set_t& operator()(const Point&);\n  size_t rects_containing(const Point&, std::vector<VRect>& result);\n  const RectScale scale_;\nprivate:\n  map_t map_;\n  const std::vector<VRect> vec_;\n};\n\ntemplate<typename T>\nVRectGrid::VRectGrid(const RectScale& scale, T begin, const T end)\n: scale_{scale}, vec_(begin, end)\n{\n  for(int y = 0; y <= scale_.height_ + 1; ++y) {\n    for(int x = 0; x <= scale_.width_ + 1; ++x) {\n      Point p{x, y};\n      set_t set;\n      for(size_t i = 0; i < vec_.size(); ++i) {\n        if (scale_(vec_[i].r).contains(p)) {\n          set.insert(i);\n        }\n      }\n      map_.insert({p, set});\n    }\n  }\n}\n// const VRectGrid::set_t& VRectGrid::operator()(const Point& p) {\n//   return map_[scale_(p)];\n// }\n// const VRectGrid::set_t& VRectGrid::operator()(int x, int y) {\n//   return this->operator()(Point{x, y});\n// }\nsize_t VRectGrid::rects_containing(const Point& p, std::vector<VRect>& result) {\n  size_t ret = 0;\n  decltype(auto) res = map_[scale_(p)];\n  std::cout << \"Checking \" << res.size() << \" VRects\" << std::endl;\n  for(const auto& e : res) {\n    if (vec_[e].r.contains(p)) {\n      ++ret;\n      result.push_back(vec_[e]);\n    }\n  }\n  return ret;\n}\n\n// std::ostream& operator<<(std::ostream& o, VRectGrid& g) {\n//   boost::format fmt{\"%3d\"};\n//   for(int y = g.scale_.height_ + 1; y >= 0; --y) {\n//     for(int x = 0; x <= g.scale_.width_ + 1; ++x) {\n//       auto s = g(x, y).size();\n//       std::cout << fmt % s << \" \";\n//     }\n//     std::cout << std::endl;\n//   }\n//   return o;\n// }\n\nint main() {\n  using namespace std;\n  std::array<VRect, 2000> rs;\n  Randomizer rnd;\n  int idx = 1;\n  for(auto & e : rs) {\n    e.value = idx++;\n    rnd(e.r);\n  }\n  // print_all(rs);\n  std::sort(rs.begin(), rs.end(), [](const VRect& a, const VRect& b) { return a.r < b.r;});\n  std::cout << \"***********\" << std::endl;\n  print_all(rs);\n  Rect bounds = Rect::bounding_rect(rs.begin(), rs.end());\n  std::cout << \"*\" << bounds << std::endl;\n\n  const int buckets = 5;\n  float rects_per_bucket = rs.size() / (float)buckets;\n  float dx = static_cast<float>(bounds.width())/rs.size();\n  for(size_t i = 0; i < rs.size(); ++i) {\n    int current_x = dx * i;\n    int bucket = i / rects_per_bucket;\n    cout << i << \" \" << current_x << \" \" << bucket \n         << \" \" << rs[i].r.min.x \n         << \" \" << rs[i] << rs[i].r.center()\n         << endl;\n  }\n  auto b = rs.begin();\n  int bb = 0;\n  for(size_t i = 0; ; ++i) {\n    int bucket = i / rects_per_bucket;\n    if (bb < bucket) {\n      Rect intersection;\n      auto intersect = Rect::intersect(b, rs.begin() + i, &intersection);\n      cout << \"Bucket \" << bb << \" intersect: \" \n           << boolalpha << intersect << \": \" << intersection \n           << static_cast<float>(intersection.area())/bounds.area()/buckets << endl;\n      bb = bucket;\n      b = rs.begin() + i;\n    }\n    if (i >= rs.size())\n      break;\n  }\n  // EquiDistRange r{0, 8, 3};\n  // for(auto i : r) {\n  //   cout << i << \", \";\n  // }\n  // cout << endl;\n  RectScale scale(bounds, 30, 30);\n  VRectGrid vrg{scale, rs.begin(), rs.end()};\n  Point p;\n  std::vector<VRect> res;\n  for(int i = 0; i < 20; ++i) {\n    res.resize(0);\n    rnd(p);\n    cout << \"**** Loopkup \" << p \n         << \": \" << vrg.rects_containing(p, res) << \"VRects:\" \n         << endl;\n    print_all(res);\n  }\n  cout << \"*******\" << endl;\n  // std::string bla;\n  // cin >> bla;\n}", "meta": {"hexsha": "513e10e48bb914e9d36770348e223b6ba00806c6", "size": 11555, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "experiments/areagrid.cpp", "max_stars_repo_name": "noeld/cpp", "max_stars_repo_head_hexsha": "572a145f8c79f7292b7b0611822ed34792df4e9c", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "experiments/areagrid.cpp", "max_issues_repo_name": "noeld/cpp", "max_issues_repo_head_hexsha": "572a145f8c79f7292b7b0611822ed34792df4e9c", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "experiments/areagrid.cpp", "max_forks_repo_name": "noeld/cpp", "max_forks_repo_head_hexsha": "572a145f8c79f7292b7b0611822ed34792df4e9c", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4078947368, "max_line_length": 99, "alphanum_fraction": 0.5784508871, "num_tokens": 3388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872243177518, "lm_q2_score": 0.6334102567576901, "lm_q1q2_score": 0.4744795310890126}}
{"text": "/*\n * Copyright (C) 2018 Swift Navigation Inc.\n * Contact: Swift Navigation <dev@swiftnav.com>\n *\n * This source is subject to the license found in the file 'LICENSE' which must\n * be distributed together with this source. All other rights reserved.\n *\n * THIS CODE AND INFORMATION IS PROVIDED \"AS IS\" WITHOUT WARRANTY OF ANY KIND,\n * EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.\n */\n\n#include \"covariance_functions/covariance_functions.h\"\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <gtest/gtest.h>\n#include <iostream>\n#include <vector>\n\nnamespace albatross {\n\nstd::vector<Eigen::Vector3d> points_on_a_line(const int n) {\n  std::vector<Eigen::Vector3d> xs;\n  for (int i = 0; i < n; i++) {\n    Eigen::Vector3d x;\n    for (int j = 0; j < 3; j++)\n      x[static_cast<std::size_t>(j)] = 1000 * i + j;\n    xs.push_back(x);\n  }\n  return xs;\n}\n\nTEST(test_covariance_functions, test_build_covariance) {\n  using Feature = Eigen::Vector3d;\n  using Noise = IndependentNoise<Feature>;\n  using SqExp = SquaredExponential<EuclideanDistance>;\n  using RadialSqExp = SquaredExponential<RadialDistance>;\n\n  CovarianceFunction<SqExp> sqexp = {SqExp()};\n  CovarianceFunction<Constant> constant = {Constant()};\n  CovarianceFunction<Noise> noise = {Noise()};\n  CovarianceFunction<RadialSqExp> radial_sqexp = {RadialSqExp()};\n\n  // Add and multiply covariance functions together and make sure they are\n  // still capable of producing a covariance matrix.\n  auto product = sqexp * radial_sqexp;\n  auto covariance_function = constant + product + noise;\n\n  auto xs = points_on_a_line(5);\n  Eigen::MatrixXd C = symmetric_covariance(covariance_function, xs);\n  assert(C.rows() == xs.size());\n  assert(C.cols() == xs.size());\n}\n\n/*\n * In the following we test any covariance functions which should support\n * Eigen::Vector feature vectors.\n */\ntemplate <typename T>\nclass TestVectorCovarianceFunctions : public ::testing::Test {\n\npublic:\n  typedef CovarianceFunction<T> CovFunc;\n  T value_;\n};\n\ntypedef ::testing::Types<\n    SquaredExponential<EuclideanDistance>, SquaredExponential<RadialDistance>,\n    Exponential<EuclideanDistance>, Exponential<AngularDistance>,\n    Exponential<RadialDistance>>\n    VectorCompatibleCovarianceFunctions;\n\nTYPED_TEST_CASE(TestVectorCovarianceFunctions,\n                VectorCompatibleCovarianceFunctions);\n\nTYPED_TEST(TestVectorCovarianceFunctions, WorksWithEigen) {\n  typename TestFixture::CovFunc covariance_function;\n  auto xs = points_on_a_line(5);\n  Eigen::MatrixXd C = symmetric_covariance(covariance_function, xs);\n  assert(C.rows() == xs.size());\n  assert(C.cols() == xs.size());\n  // Make sure C is positive definite.\n  auto inverse = C.inverse();\n}\n\nTYPED_TEST(TestVectorCovarianceFunctions, WorksDirectlyOnCovarianceterms) {\n  typename TestFixture::CovFunc covariance_function;\n  auto xs = points_on_a_line(5);\n  Eigen::MatrixXd C = symmetric_covariance(covariance_function.term, xs);\n  assert(C.rows() == xs.size());\n  assert(C.cols() == xs.size());\n  // Make sure C is positive definite.\n  auto inverse = C.inverse();\n}\n} // namespace albatross\n", "meta": {"hexsha": "3b42a8505a0fa371880b9cbb55dd7a5992f03286", "size": 3175, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tests/test_covariance_functions.cc", "max_stars_repo_name": "akleeman/albatross", "max_stars_repo_head_hexsha": "f89bf4c20e35b71ea4d89260dc981b1a2363d41b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/test_covariance_functions.cc", "max_issues_repo_name": "akleeman/albatross", "max_issues_repo_head_hexsha": "f89bf4c20e35b71ea4d89260dc981b1a2363d41b", "max_issues_repo_licenses": ["MIT"], "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/test_covariance_functions.cc", "max_forks_repo_name": "akleeman/albatross", "max_forks_repo_head_hexsha": "f89bf4c20e35b71ea4d89260dc981b1a2363d41b", "max_forks_repo_licenses": ["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.0729166667, "max_line_length": 79, "alphanum_fraction": 0.7354330709, "num_tokens": 791, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.749087201911703, "lm_q2_score": 0.6334102705979902, "lm_q1q2_score": 0.4744795272643831}}
{"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_TRIGONOMETRIC_FUNCTIONS_SIMD_COMMON_SINC_HPP_INCLUDED\n#define NT2_TOOLBOX_TRIGONOMETRIC_FUNCTIONS_SIMD_COMMON_SINC_HPP_INCLUDED\n#include <nt2/toolbox/trigonometric/functions/sinc.hpp>\n#include <nt2/sdk/meta/as_floating.hpp>\n#include <nt2/include/functions/simd/sin.hpp>\n#include <nt2/include/functions/simd/abs.hpp>\n#include <nt2/include/functions/simd/is_inf.hpp>\n#include <nt2/include/functions/simd/is_less.hpp>\n#include <nt2/include/functions/simd/if_else.hpp>\n#include <nt2/include/constants/eps.hpp>\n#include <nt2/include/constants/one.hpp>\n#include <nt2/include/constants/zero.hpp>\n#include <boost/simd/sdk/config.hpp>\n\n\nnamespace nt2 { namespace ext\n{\n  NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::sinc_, boost::simd::tag::simd_\n                            , (A0)(X)\n                            , ((simd_<arithmetic_<A0>,X>))\n                            )\n  {\n\n    typedef typename meta::as_floating<A0>::type result_type;\n\n    NT2_FUNCTOR_CALL(1)\n    {\n      return nt2::sinc(tofloat(a0));\n    }\n  };\n} }\n\nnamespace nt2 { namespace ext\n{\n  NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::sinc_, boost::simd::tag::simd_\n                            , (A0)(X)\n                            , ((simd_<floating_<A0>,X>))\n                            )\n  {\n\n    typedef A0 result_type;\n\n    NT2_FUNCTOR_CALL(1)\n    {\n      result_type r1 = nt2::if_else(nt2::lt(nt2::abs(a0), nt2::Eps<A0>()),\n                                    nt2::One<A0>(),\n                                    nt2::sin(a0)/a0);\n      #ifdef BOOST_SIMD_NO_INFINITIES\n      return r1;\n      #else\n      return nt2::if_else(nt2::is_inf(a0), nt2::Zero<A0>(), r1);\n      #endif\n    }\n  };\n} }\n\n\n#endif\n", "meta": {"hexsha": "3ead335a58b49cf8f559ddda39b2e59bf0dd9060", "size": 2175, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/trigonometric/include/nt2/toolbox/trigonometric/functions/simd/common/sinc.hpp", "max_stars_repo_name": "timblechmann/nt2", "max_stars_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-09-14T00:23:53.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-14T12:51:18.000Z", "max_issues_repo_path": "modules/core/trigonometric/include/nt2/toolbox/trigonometric/functions/simd/common/sinc.hpp", "max_issues_repo_name": "timblechmann/nt2", "max_issues_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/core/trigonometric/include/nt2/toolbox/trigonometric/functions/simd/common/sinc.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.4626865672, "max_line_length": 80, "alphanum_fraction": 0.5581609195, "num_tokens": 545, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145997, "lm_q2_score": 0.6261241842048092, "lm_q1q2_score": 0.4744733893591036}}
{"text": "\n#ifndef FNN_MODEL_HPP\n#define FNN_MODEL_HPP\n\n#include <vector>\n#include <list>\n#include <Eigen/Dense>\n#include \"SFML/System.hpp\"\n#include \"gnuplot_i.hpp\"\n\nstruct Data\n{\n  Eigen::MatrixXd &training_sample_i;\n  Eigen::MatrixXd &training_sample_o;\n  Eigen::MatrixXd &eval_input;\n  Eigen::MatrixXd &eval_output;\n  Data(Eigen::MatrixXd &t_i, Eigen::MatrixXd &t_o,\n      Eigen::MatrixXd &e_i, Eigen::MatrixXd &e_o) :\n    training_sample_i(t_i),\n    training_sample_o(t_o),\n    eval_input(e_i),\n    eval_output(e_o)\n  {}\n};\nclass FNN_Model\n{\n  public:\n    FNN_Model(\n        std::vector<unsigned int> layers);\n    ~FNN_Model();\n\n    void print_FNN();\n    static double normal_distri(double input);\n    void Manual_Set_FNN(\n        std::vector<Eigen::MatrixXd> &weights,\n        std::vector<Eigen::MatrixXd> &bias);\n    void Init();\n    void ResizeBatch();\n    void SetInput(Eigen::MatrixXd &inputs);\n    static double sigmoid(double input);\n    static double sigmoidPrime(double input);\n    void FeedForward();\n    void ComputeError(Eigen::MatrixXd &d_outputs);\n    void GradientDescent();\n    void BackProgagation(\n        Eigen::MatrixXd &inputs,\n        Eigen::MatrixXd &d_outputs);\n    void train(\n        Eigen::MatrixXd &training_sample_i,\n        Eigen::MatrixXd &training_sample_o,\n        unsigned int nbr_epoch,\n        unsigned int batch_size,\n        double learning_rate,\n        Eigen::MatrixXd &eval_input,\n        Eigen::MatrixXd &eval_output);\n    void core_train();\n    double evaluate(\n        Eigen::MatrixXd &eval_input,\n        Eigen::MatrixXd &eval_output,\n        unsigned int epoch);\n    double evaluate_MNIST(\n        Eigen::MatrixXd &eval_input,\n        Eigen::MatrixXd &eval_output,\n        unsigned int epoch);\n\n    sf::Thread train_thread;\n    sf::Mutex chart_mutex;\n    bool thread_state;\n    Gnuplot graph;\n\n  private:\n    unsigned int _nbr_layer;\n    unsigned int _batch_size;\n    unsigned int _nbr_epoch;\n    double _learning_rate;\n    std::vector<unsigned int> _layers;\n    std::vector<Eigen::MatrixXd> _weights;\n    std::vector<Eigen::MatrixXd> _bias;\n    std::vector<Eigen::MatrixXd> _zs;\n    std::vector<Eigen::MatrixXd> _activations;\n    std::vector<Eigen::MatrixXd> _errors;\n    struct Data *_mnist_data;\n    std::vector<double> _x;\n    std::vector<double> _y;\n};\n\n#endif\n", "meta": {"hexsha": "c7e9a9662a1cefe5eef4265f37bcbf1f541841ca", "size": 2306, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/FNN_Model.hpp", "max_stars_repo_name": "kwon-young/Millenium-Neural-Net", "max_stars_repo_head_hexsha": "c52d3a4ad6fd0b59a89cec95437f58194b039b2c", "max_stars_repo_licenses": ["MIT"], "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/FNN_Model.hpp", "max_issues_repo_name": "kwon-young/Millenium-Neural-Net", "max_issues_repo_head_hexsha": "c52d3a4ad6fd0b59a89cec95437f58194b039b2c", "max_issues_repo_licenses": ["MIT"], "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/FNN_Model.hpp", "max_forks_repo_name": "kwon-young/Millenium-Neural-Net", "max_forks_repo_head_hexsha": "c52d3a4ad6fd0b59a89cec95437f58194b039b2c", "max_forks_repo_licenses": ["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.2045454545, "max_line_length": 51, "alphanum_fraction": 0.6704249783, "num_tokens": 563, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.47447337722257377}}
{"text": "/* Copyright (C) 2012-2020 IBM Corp.\n * This program is Licensed under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *   http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License. See accompanying LICENSE file.\n */\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <numeric>\n#include <tuple>\n#include <NTL/BasicThreadPool.h>\n\n#include <helib/helib.h>\n\n#include <helib/intraSlot.h>\n#include <helib/binaryArith.h>\n\n#include \"gtest/gtest.h\"\n#include \"test_common.h\"\n\n#include <helib/debugging.h>\n\n// define flags FLAG_PRINT_ZZX, FLAG_PRINT_POLY, FLAG_PRINT_VEC, functions\n//        decryptAndPrint(ostream, ctxt, sk, ea, flags)\n//        decryptAndCompare(ctxt, sk, ea, pa);\n\nnamespace {\n\nstruct Parameters\n{\n  Parameters(long prm,\n             long bitSize,\n             long bitSize2,\n             long outSize,\n             bool bootstrap,\n             long seed,\n             long nthreads) :\n      prm(prm),\n      bitSize(bitSize),\n      bitSize2(bitSize2),\n      outSize(outSize),\n      bootstrap(bootstrap),\n      seed(seed),\n      nthreads(nthreads){};\n\n  long prm;       // parameter size (0-tiny,...,7-huge)\n  long bitSize;   // bitSize of input integers (<=32)\n  long bitSize2;  // bitSize of 2nd input integer (<=32)\n  long outSize;   // bitSize of output integers, as many as needed\n  bool bootstrap; // test multiplication with bootstrapping\n  long seed;      // PRG seed\n  long nthreads;  // number of threads\n\n  friend std::ostream& operator<<(std::ostream& os, const Parameters& params)\n  {\n    return os << \"{\"\n              << \"prm=\" << params.prm << \",\"\n              << \"bitSize=\" << params.bitSize << \",\"\n              << \"bitSize2=\" << params.bitSize2 << \",\"\n              << \"outSize=\" << params.outSize << \",\"\n              << \"bootstrap=\" << params.bootstrap << \",\"\n              << \"seed=\" << params.seed << \",\"\n              << \"nthreads=\" << params.nthreads << \"}\";\n  };\n};\n\nclass GTestBinaryArith :\n    public ::testing::TestWithParam<std::tuple<Parameters, int>>\n{\nprotected:\n  static std::vector<helib::zzX> unpackSlotEncoding;\n  constexpr static long mValues[8][15] = {\n      // clang-format off\n   // {p,phi(m),     m,  d,   m1,  m2,  m3,   g1,   g2,   g3,ord1,ord2,ord3,  B, c}\n      {2,    48,   105, 12,    3,  35,   0,   71,   76,    0,   2,   2,   0, 25, 2},\n      {2,   600,  1023, 10,   11,  93,   0,  838,  584,    0,  10,   6,   0, 25, 2},\n      {2,  2304,  4641, 24,    7,   3, 221, 3979, 3095, 3760,   6,   2,  -8, 25, 3},\n      {2,  5460,  8193, 26, 8193,   0,   0,   46,    0,    0, 210,   0,   0, 25, 3},\n      {2,  8190,  8191, 13, 8191,   0,   0,   39,    0,    0, 630,   0,   0, 25, 3},\n      {2, 10752, 11441, 48,   17, 673,   0, 4712, 2024,    0,  16, -14,   0, 25, 3},\n      {2, 15004, 15709, 22,   23, 683,   0, 4099,13663,    0,  22,  31,   0, 25, 3},\n      {2, 27000, 32767, 15,   31,   7, 151,11628,28087,25824,  30,   6, -10, 28, 4}\n      // clang-format on\n  };\n\n  static long correctBitSize(long minimum, long oldBitSize)\n  {\n    long newBitSize;\n    if (oldBitSize <= 0)\n      newBitSize = minimum;\n    else if (oldBitSize > 32)\n      newBitSize = 32;\n    else\n      newBitSize = oldBitSize;\n    return newBitSize;\n  };\n\n  // Validates the prm value, throwing if invalid\n  static long validatePrm(long prm)\n  {\n    if (prm < 0 || prm >= 5)\n      throw std::invalid_argument(\"prm must be in the interval [0, 4]\");\n    return prm;\n  };\n\n  static NTL::Vec<long> calculateMvec(const long* vals)\n  {\n    NTL::Vec<long> mvec;\n    NTL::append(mvec, vals[4]);\n    if (vals[5] > 1)\n      NTL::append(mvec, vals[5]);\n    if (vals[6] > 1)\n      NTL::append(mvec, vals[6]);\n    return mvec;\n  };\n\n  static std::vector<long> calculateGens(const long* vals)\n  {\n    std::vector<long> gens;\n    gens.push_back(vals[7]);\n    if (vals[8] > 1)\n      gens.push_back(vals[8]);\n    if (vals[9] > 1)\n      gens.push_back(vals[9]);\n    return gens;\n  };\n\n  static std::vector<long> calculateOrds(const long* vals)\n  {\n    std::vector<long> ords;\n    ords.push_back(vals[10]);\n    if (abs(vals[11]) > 1)\n      ords.push_back(vals[11]);\n    if (abs(vals[12]) > 1)\n      ords.push_back(vals[12]);\n    return ords;\n  };\n\n  static long calculateLevels(bool bootstrap, long outSize, long bitSize)\n  {\n    long L;\n    if (bootstrap)\n      L = 900; // that should be enough\n    else {\n      double nBits =\n          (outSize > 0 && outSize < 2 * bitSize) ? outSize : (2 * bitSize);\n      double three4twoLvls = log(nBits / 2) / log(1.5);\n      double add2NumsLvls = log(nBits) / log(2.0);\n      L = (5 + ceil(three4twoLvls + add2NumsLvls)) * 30;\n    }\n    return L;\n  };\n\n  // Returns a reference to the passed-in context once it has been modified to\n  // get it ready for test. This is not static because it uses quite a lot of\n  // state of the object.\n  helib::Context& prepareContext(helib::Context& context)\n  {\n    if (helib_test::verbose) {\n      std::cout << \"input bitSizes=\" << bitSize << ',' << bitSize2\n                << \", output size bound=\" << outSize << std::endl;\n      if (nthreads > 1)\n        std::cout << \"  using \" << NTL::AvailableThreads() << \" threads\\n\";\n      std::cout << \"computing key-independent tables...\" << std::flush;\n    }\n    buildModChain(context, L, c, /*willBeBootstrappable=*/bootstrap);\n    if (bootstrap) {\n      context.enableBootStrapping(mvec);\n    }\n    buildUnpackSlotEncoding(unpackSlotEncoding, *context.ea);\n    if (helib_test::verbose) {\n      std::cout << \" done.\\n\";\n      context.zMStar.printout();\n    }\n    return context;\n  };\n\n  void prepareSecKey(helib::SecKey& secKey)\n  {\n    if (helib_test::verbose) {\n      std::cout << \" L=\" << L << \", B=\" << B << std::endl;\n      std::cout << \"\\ncomputing key-dependent tables...\" << std::flush;\n    }\n    secKey.GenSecKey();\n    addSome1DMatrices(secKey); // compute key-switching matrices\n    addFrbMatrices(secKey);\n    if (bootstrap)\n      secKey.genRecryptData();\n    if (helib_test::verbose)\n      std::cout << \" done\\n\";\n  };\n\n  const long prm;\n  const long bitSize;\n  const long bitSize2;\n  const long outSize;\n  const bool bootstrap;\n  const long seed;\n  const long nthreads;\n\n  const long* vals;\n  const long p;\n  const long m;\n  const NTL::Vec<long> mvec;\n  const std::vector<long> gens;\n  const std::vector<long> ords;\n  const long B;\n  const long c;\n  const long L;\n  helib::Context context;\n  helib::SecKey secKey;\n\n  GTestBinaryArith() :\n      prm(validatePrm(std::get<0>(GetParam()).prm)),\n      bitSize(correctBitSize(5, std::get<0>(GetParam()).bitSize)),\n      bitSize2(correctBitSize(bitSize, std::get<0>(GetParam()).bitSize2)),\n      outSize(std::get<0>(GetParam()).outSize),\n      bootstrap(std::get<0>(GetParam()).bootstrap),\n      seed(std::get<0>(GetParam()).seed),\n      nthreads(std::get<0>(GetParam()).nthreads),\n      vals(mValues[prm]),\n      p(vals[0]),\n      m(vals[2]),\n      mvec(calculateMvec(vals)),\n      gens(calculateGens(vals)),\n      ords(calculateOrds(vals)),\n      B(vals[13]),\n      c(vals[14]),\n      L(calculateLevels(bootstrap, outSize, bitSize)),\n      context(m, p, /*r=*/1, gens, ords),\n      secKey(prepareContext(context)){};\n\n  void SetUp() override\n  {\n    if (seed)\n      NTL::SetSeed(NTL::ZZ(seed));\n    if (nthreads > 1)\n      NTL::SetNumThreads(nthreads);\n\n    prepareSecKey(secKey);\n\n    helib::activeContext = &context; // make things a little easier sometimes\n\n    helib::setupDebugGlobals(&secKey, context.ea);\n  }\n\n  virtual void TearDown() override\n  {\n#ifdef HELIB_DEBUG\n    helib::cleanupDebugGlobals();\n#endif\n  }\n\n  // This gets called once all of the tests have run\npublic:\n  static void TearDownTestCase()\n  {\n    if (helib_test::verbose)\n      helib::printAllTimers(std::cout);\n  };\n};\nconstexpr long GTestBinaryArith::mValues[8][15];\nstd::vector<helib::zzX> GTestBinaryArith::unpackSlotEncoding;\n\nTEST_P(GTestBinaryArith, fifteenForFour)\n{\n  // Randomly generate up to 15 integers from {0,1} with some entries\n  // randomly set to null.  We then encrypt and use the fifteenOrLess4Four\n  // function to calculate the binary representation of their sum.  This is\n  // then checked against the plaintext calculation.\n  // In this case each ciphertext is considered to be the encryption of one\n  // bit, however packing more into the slots is possible.\n  // LSB is at the start (left) of the vector.\n\n  // Note: fifteenOrLess4Four is not entirely thread safe so this test will only\n  // be ran single-threaded. Save current number of threads and set to 1.\n  auto numThreads = NTL::AvailableThreads();\n  NTL::SetNumThreads(1);\n\n  // vector of ciphertexts corresponding to encrypted input bit vectors.\n  std::vector<helib::Ctxt> inBuf(15, helib::Ctxt(secKey));\n  std::vector<helib::Ctxt*> inPtrs(15, nullptr);\n\n  // vector of ciphertexts corresponding to the summation of the input bit\n  // vectors.\n  std::vector<helib::Ctxt> outBuf(5, helib::Ctxt(secKey));\n\n  // Randomly generate and encrypt the input vectors.\n  long sum = 0;\n  std::string inputBits = \"(\";\n  for (int i = 0; i < 15; i++) {\n    if (NTL::RandomBnd(10) > 0) { // Leave empty (null) with small probability.\n      inPtrs[i] = &(inBuf[i]);\n      long bit = NTL::RandomBnd(2); // Select a randomised bit.\n      secKey.Encrypt(inBuf[i], NTL::ZZX(bit));\n      inputBits += std::to_string(bit) + \",\";\n      sum += bit; // Keep track of the plaintext sum.\n    } else\n      inputBits += \"-,\"; // This represents a null bit.\n  }\n  inputBits += \")\";\n\n  if (helib_test::verbose) {\n    std::cout << std::endl;\n    helib::CheckCtxt(inBuf[helib::lsize(inBuf) - 1], \"b4 15for4\");\n  }\n  // Add the encrypted bits.\n  long numOutputs = fifteenOrLess4Four(helib::CtPtrs_vectorCt(outBuf),\n                                       helib::CtPtrs_vectorPt(inPtrs));\n  if (helib_test::verbose) {\n    std::cout << \"numOutputs: \" << numOutputs << std::endl;\n    helib::CheckCtxt(outBuf[helib::lsize(outBuf) - 1], \"after 15for4\");\n  }\n\n  // Check the result.\n  long sum2 = 0;\n  for (int i = 0; i < numOutputs; i++) {\n    NTL::ZZX poly;\n    secKey.Decrypt(poly, outBuf[i]);\n    sum2 += to_long(ConstTerm(poly)) << i;\n  }\n  EXPECT_EQ(sum, sum2) << \"inputs = \" << inputBits << std::endl;\n  if (helib_test::verbose) {\n    std::cout << \"15to4 succeeded, sum\" << inputBits << \"=\" << sum2\n              << std::endl;\n  }\n\n  // Restore the number of threads to original value.\n  NTL::SetNumThreads(numThreads);\n}\n\nTEST_P(GTestBinaryArith, product)\n{\n  // Randomly generate a pair of numbers of a specified bit size and then\n  // encrypt them in binary representation. Then use multTwoNumbers to\n  // multiply the two positive binary numbers and then check against the\n  // plaintext calculation. Next, use multTwoNumbers with binary numbers in\n  // 2's complement to calculate the product where the multiplier is negative\n  // and then check against the plaintext calculation.\n  //\n  // In this case each ciphertext is considered to be the encryption of one\n  // bit, however packing more into the slots is possible.\n  // LSB is at the start (left) of the vector.\n\n  const helib::EncryptedArray& ea = *context.ea;\n  // outSize 1's on the least significant end of mask.\n  long mask = (outSize ? ((1L << outSize) - 1) : -1);\n\n  // Choose two random integers with correct bit sizes.\n  long multiplicand_data = NTL::RandomBits_long(bitSize);\n  long multiplier_data = NTL::RandomBits_long(bitSize2);\n\n  // Encrypt the individual bits.\n  NTL::Vec<helib::Ctxt> encrypted_product, encrypted_multiplicand,\n      encrypted_multiplier;\n\n  // Resize the vector of ciphertexts (encrypted_bits) to match the input size.\n  helib::resize(encrypted_multiplicand, bitSize, helib::Ctxt(secKey));\n  for (long i = 0; i < bitSize; i++) {\n    secKey.Encrypt(encrypted_multiplicand[i],\n                   NTL::ZZX((multiplicand_data >> i) & 1));\n    if (bootstrap) { // If bootstrapping then modulo down to a lower level.\n      encrypted_multiplicand[i].bringToSet(context.getCtxtPrimes(5));\n    }\n  }\n  helib::resize(encrypted_multiplier, bitSize2, helib::Ctxt(secKey));\n  for (long i = 0; i < bitSize2; i++) {\n    secKey.Encrypt(encrypted_multiplier[i],\n                   NTL::ZZX((multiplier_data >> i) & 1));\n    if (bootstrap) { // If bootstrapping then modulo down to a lower level.\n      encrypted_multiplier[i].bringToSet(context.getCtxtPrimes(5));\n    }\n  }\n  if (helib_test::verbose) {\n    std::cout << \"\\n  bits-size \" << bitSize << '+' << bitSize2;\n    if (outSize > 0)\n      std::cout << \"->\" << outSize;\n    helib::CheckCtxt(encrypted_multiplier[0], \"b4 multiplication\");\n  }\n  std::vector<long> slots; // Vector that will hold the decrypted result.\n  // Test multiplication with two positive numbers.\n  // A scope which tests multTwoNumbers using wrappers around the encrypted\n  // data.\n  {\n    helib::CtPtrs_VecCt output_wrapper(\n        encrypted_product); // A wrapper around the output vector.\n    helib::multTwoNumbers(output_wrapper,\n                          helib::CtPtrs_VecCt(encrypted_multiplicand),\n                          helib::CtPtrs_VecCt(encrypted_multiplier),\n                          /*negative=*/false,\n                          outSize,\n                          &unpackSlotEncoding);\n    helib::decryptBinaryNums(slots, output_wrapper, secKey, ea);\n  } // output_wrapper is deleted once out of scope.\n  if (helib_test::verbose)\n    helib::CheckCtxt(encrypted_product[helib::lsize(encrypted_product) - 1],\n                     \"after multiplication\");\n\n  // Calculate the multiplication in the plain.\n  long plaintext_product = multiplicand_data * multiplier_data;\n  EXPECT_EQ(slots[0], ((multiplicand_data * multiplier_data) & mask))\n      << \"Positive product error: multiplicand_data=\" << multiplicand_data\n      << \", multiplier_data=\" << multiplier_data << \", but product=\" << slots[0]\n      << \" (should be \" << plaintext_product << '&' << mask << '='\n      << (plaintext_product & mask) << \")\\n\";\n\n  if (helib_test::verbose) {\n    std::cout << \"positive product succeeded: \";\n    if (outSize)\n      std::cout << \"bottom \" << outSize << \" bits of \";\n    std::cout << multiplicand_data << \"*\" << multiplier_data << \"=\" << slots[0]\n              << std::endl;\n  }\n\n  // Test multiplication of numbers in 2's complement where the multiplier is\n  // negative.\n  secKey.Encrypt(encrypted_multiplier[bitSize2 - 1], NTL::ZZX(1));\n  decryptBinaryNums(slots,\n                    helib::CtPtrs_VecCt(encrypted_multiplier),\n                    secKey,\n                    ea,\n                    /*negative=*/true);\n  multiplier_data = slots[0];\n  encrypted_product.kill(); // Clear the data in encrypted_product.\n  // A scope which tests multTwoNumbers (with a negative multiplier) using\n  // wrappers around the encrypted data.\n  {\n    helib::CtPtrs_VecCt output_wrapper(\n        encrypted_product); // A wrapper around the output vector.\n    multTwoNumbers(output_wrapper,\n                   helib::CtPtrs_VecCt(encrypted_multiplicand),\n                   helib::CtPtrs_VecCt(encrypted_multiplier),\n                   /*negative=*/true,\n                   outSize,\n                   &unpackSlotEncoding);\n    decryptBinaryNums(slots, output_wrapper, secKey, ea, /*negative=*/true);\n  } // output_wrapper is deleted once out of scope.\n\n  if (helib_test::verbose)\n    helib::CheckCtxt(encrypted_product[helib::lsize(encrypted_product) - 1],\n                     \"after multiplication\");\n\n  // Calculate the multiplication in the plain.\n  plaintext_product = multiplicand_data * multiplier_data;\n  EXPECT_EQ((slots[0] & mask), (plaintext_product & mask))\n      << \"Negative product error: multiplicand_data=\" << multiplicand_data\n      << \", multiplier_data=\" << multiplier_data << \", but product=\" << slots[0]\n      << \" (should be \" << plaintext_product << '&' << mask << '='\n      << (plaintext_product & mask) << \")\\n\";\n  if (helib_test::verbose) {\n    std::cout << \"negative product succeeded: \";\n    if (outSize)\n      std::cout << \"bottom \" << outSize << \" bits of \";\n    std::cout << multiplicand_data << \"*\" << multiplier_data << \"=\" << slots[0]\n              << std::endl;\n  }\n\n#ifdef HELIB_DEBUG\n  // Print out the ciphertext with the lowest level after multiplication\n  // if HELIB_DEBUG is defined.\n  const helib::Ctxt* minCtxt = nullptr;\n  long minLvl = 10000000;\n  for (const helib::Ctxt& c : encrypted_product) {\n    long lvl = c.logOfPrimeSet();\n    if (lvl < minLvl) {\n      minCtxt = &c;\n      minLvl = lvl;\n    }\n  }\n  decryptAndPrint((std::cout << \" after multiplication: \"),\n                  *minCtxt,\n                  secKey,\n                  ea,\n                  0);\n  std::cout << std::endl;\n#endif\n}\n\nTEST_P(GTestBinaryArith, add)\n{\n  // Randomly generate a pair of numbers of a specified bit size and then\n  // encrypt them in binary representation. Then use addTwoNumbers to add the\n  // two binary numbers and then check against the plaintext calculation.\n  //\n  // In this case each ciphertext is considered to be the encryption of one\n  // bit, however packing more into the slots is possible.\n  // LSB is at the start(left) of the vector.\n\n  const helib::EncryptedArray& ea = *context.ea;\n  // outSize 1's on the least significant end of mask.\n  long mask = (outSize ? ((1L << outSize) - 1) : -1);\n\n  // Choose two random n-bit integers.\n  long addend_data = NTL::RandomBits_long(bitSize);\n  long augend_data = NTL::RandomBits_long(bitSize2);\n\n  // Encrypt the individual bits.\n  NTL::Vec<helib::Ctxt> encrypted_sum, encrypted_addend, encrypted_augend;\n\n  // Resize the vector of ciphertexts (encrypted_bits) to match the input size.\n  helib::resize(encrypted_addend, bitSize, helib::Ctxt(secKey));\n  for (long i = 0; i < bitSize; i++) {\n    secKey.Encrypt(encrypted_addend[i], NTL::ZZX((addend_data >> i) & 1));\n    if (bootstrap) { // If bootstrapping then modulo down to a lower level.\n      encrypted_addend[i].bringToSet(context.getCtxtPrimes(5));\n    }\n  }\n  // Resize the vector of ciphertexts (encrypted_bits) to match the input size.\n  helib::resize(encrypted_augend, bitSize2, helib::Ctxt(secKey));\n  for (long i = 0; i < bitSize2; i++) {\n    secKey.Encrypt(encrypted_augend[i], NTL::ZZX((augend_data >> i) & 1));\n    if (bootstrap) { // If bootstrapping then modulo down to a lower level.\n      encrypted_augend[i].bringToSet(context.getCtxtPrimes(5));\n    }\n  }\n  if (helib_test::verbose) {\n    std::cout << \"\\n  bits-size \" << bitSize << '+' << bitSize2;\n    if (outSize > 0)\n      std::cout << \"->\" << outSize;\n    std::cout << std::endl;\n    helib::CheckCtxt(encrypted_augend[0], \"b4 addition\");\n  }\n\n  std::vector<long>\n      decrypted_result; // Vector that will hold the decrypted result.\n  // Test addition.\n  // A scope which tests addTwoNumbers using wrappers around the encrypted data.\n  {\n    helib::CtPtrs_VecCt output_wrapper(\n        encrypted_sum); // A wrapper around the output vector.\n    helib::addTwoNumbers(output_wrapper,\n                         helib::CtPtrs_VecCt(encrypted_addend),\n                         helib::CtPtrs_VecCt(encrypted_augend),\n                         outSize,\n                         &unpackSlotEncoding);\n    helib::decryptBinaryNums(decrypted_result, output_wrapper, secKey, ea);\n  } // output_wrapper is deleted once out of scope.\n\n  if (helib_test::verbose)\n    helib::CheckCtxt(encrypted_sum[helib::lsize(encrypted_sum) - 1],\n                     \"after addition\");\n\n  // Calculate the addition in the plain.\n  long plaintext_sum = addend_data + augend_data;\n  EXPECT_EQ(decrypted_result[0], ((addend_data + augend_data) & mask))\n      << \"addTwoNums error: addend_data=\" << addend_data\n      << \", augend_data=\" << augend_data\n      << \", but plaintext_sum=\" << decrypted_result[0]\n      << \" (should be =\" << (plaintext_sum & mask) << \")\\n\";\n  if (helib_test::verbose) {\n    std::cout << \"addTwoNums succeeded: \";\n    if (outSize)\n      std::cout << \"bottom \" << outSize << \" bits of \";\n    std::cout << addend_data << \"+\" << augend_data << \"=\" << decrypted_result[0]\n              << std::endl;\n  }\n\n#ifdef HELIB_DEBUG\n  // Print out the ciphertext with the lowest level after addition if\n  // HELIB_DEBUG is defined.\n  const helib::Ctxt* minCtxt = nullptr;\n  long minLvl = 1000;\n  for (const helib::Ctxt& c : encrypted_sum) {\n    long lvl = c.logOfPrimeSet();\n    if (lvl < minLvl) {\n      minCtxt = &c;\n      minLvl = lvl;\n    }\n  }\n  decryptAndPrint((std::cout << \" after addition: \"), *minCtxt, secKey, ea, 0);\n  std::cout << std::endl;\n#endif\n}\n\nTEST_P(GTestBinaryArith, addManyNumbers)\n{\n  // Randomly generate a vector of numbers of a specified bit size and then\n  // encrypt them in binary representation. Then use addManyNumbers to add\n  // them all up and then check against the plaintext calculation.\n  //\n  // In this case each ciphertext is considered to be the encryption of one\n  // bit, however packing more into the slots is possible.\n  // LSB is at the start(left) of the vector.\n\n  const long num_summands = 5;\n  const helib::EncryptedArray& ea = *context.ea;\n  // outSize 1's on the least significant end of mask.\n  long mask = (outSize ? ((1L << outSize) - 1) : -1);\n\n  // Choose a set of random n-bit integers.\n  std::vector<long> summands_data;\n  for (long i = 0; i < num_summands; ++i)\n    summands_data.push_back(NTL::RandomBits_long(bitSize));\n\n  // Encrypt the individual bits.\n  std::vector<helib::Ctxt> encrypted_sum;\n  std::vector<std::vector<helib::Ctxt>> encrypted_summands;\n\n  // Utility function for encrypting a number into a binary representation.\n  const auto encrypt_binary_number =\n      [&](const long num) -> std::vector<helib::Ctxt> {\n    std::vector<helib::Ctxt> encrypted_num;\n    // Resize the vector of ciphertexts (encrypted_bits) to match the input\n    // size.\n    helib::resize(encrypted_num, bitSize, helib::Ctxt(secKey));\n    for (long i = 0; i < bitSize; i++) {\n      secKey.Encrypt(encrypted_num[i], NTL::ZZX((num >> i) & 1));\n      if (bootstrap) { // If bootstrapping then modulo down to a lower level.\n        encrypted_num[i].bringToSet(context.getCtxtPrimes(5));\n      }\n    }\n    return encrypted_num;\n  };\n\n  // Encrypt the set of numbers into binary representation.\n  for (long i = 0; i < num_summands; ++i)\n    encrypted_summands.push_back(encrypt_binary_number(summands_data[i]));\n\n  if (helib_test::verbose)\n    helib::CheckCtxt(encrypted_summands[0][0], \"b4 addition\");\n\n  std::vector<long>\n      decrypted_result; // Vector that will hold the decrypted result.\n  // Test summation.\n  // A scope which tests addManyNumbers using wrappers around the encrypted\n  // data.\n  {\n    helib::CtPtrs_vectorCt output_wrapper(\n        encrypted_sum); // A wrapper around the output vector.\n    helib::CtPtrMat_vectorCt summands_wrapper(\n        encrypted_summands); // A wrapper around the output vector.\n    helib::addManyNumbers(output_wrapper,\n                          summands_wrapper,\n                          outSize,\n                          &unpackSlotEncoding);\n    helib::decryptBinaryNums(decrypted_result, output_wrapper, secKey, ea);\n  } // output_wrapper is deleted once out of scope.\n\n  if (helib_test::verbose)\n    helib::CheckCtxt(encrypted_sum[helib::lsize(encrypted_sum) - 1],\n                     \"after addition\");\n\n  // Calculate the summation in the plain.\n  long plaintext_sum = std::accumulate(summands_data.begin(),\n                                       summands_data.end(),\n                                       0l,\n                                       std::plus<long>());\n  EXPECT_EQ(decrypted_result[0], plaintext_sum & mask);\n  if (helib_test::verbose) {\n    std::cout << \"addManyNums succeeded: \";\n    if (outSize)\n      std::cout << \"bottom \" << outSize << \" bits of \";\n    std::cout << summands_data[0];\n    for (long i = 1; i < num_summands; ++i)\n      std::cout << \"+\" << summands_data[i];\n    std::cout << \"=\" << decrypted_result[0] << std::endl;\n  }\n}\n\nTEST_P(GTestBinaryArith, negateNegatesCorrectly)\n{\n  // Randomly generate a number in 2's complement and negate it.\n\n  const helib::EncryptedArray& ea = *context.ea;\n  unsigned long input_data = NTL::RandomBits_long(bitSize);\n\n  long mask = ((1L << bitSize) - 1);\n  long expected_result = ((~input_data) + 1) & mask;\n  expected_result = helib::bitSetToLong(expected_result, bitSize);\n\n  std::vector<helib::Ctxt> encrypted_data(bitSize, helib::Ctxt(secKey));\n\n  for (long i = 0; i < bitSize; i++) {\n    secKey.Encrypt(encrypted_data[i], NTL::ZZX((input_data >> i) & 1));\n    if (bootstrap) { // If bootstrapping then modulo down to a lower level.\n      encrypted_data[i].bringToSet(context.getCtxtPrimes(5));\n    }\n  }\n\n  std::vector<long> decrypted_result;\n  std::vector<helib::Ctxt> result_vector(bitSize, helib::Ctxt(secKey));\n  helib::CtPtrs_vectorCt output_wrapper(result_vector);\n  helib::negateBinary(output_wrapper, helib::CtPtrs_vectorCt(encrypted_data));\n  helib::decryptBinaryNums(decrypted_result, output_wrapper, secKey, ea, true);\n\n  EXPECT_EQ(decrypted_result.size(), ea.size());\n  for (std::size_t i = 0; i < decrypted_result.size(); ++i) {\n    EXPECT_EQ(decrypted_result[i], expected_result) << \"i = \" << i << std::endl;\n  }\n\n  // Make sure it throws for incorrect-length args\n  const auto do_negate = [&]() {\n    helib::negateBinary(output_wrapper, helib::CtPtrs_vectorCt(encrypted_data));\n  };\n  encrypted_data.emplace_back(secKey);\n  EXPECT_THROW(do_negate(), helib::LogicError);\n  encrypted_data.pop_back();\n  encrypted_data.pop_back();\n  EXPECT_THROW(do_negate(), helib::LogicError);\n}\n\nTEST_P(GTestBinaryArith, subtractSubtractsCorrectly)\n{\n  // Randomly generate two numbers in 2's complement and subtract one from the\n  // other.\n  const helib::EncryptedArray& ea = *context.ea;\n  unsigned long minuend_data = NTL::RandomBits_long(bitSize);\n  unsigned long subtrahend_data = NTL::RandomBits_long(bitSize);\n\n  long mask = ((1L << bitSize) - 1);\n\n  // Do the bitSize-bit subtraction manually by negating the subtrahend, adding,\n  // and masking.\n  long expected_result =\n      (minuend_data + (((~subtrahend_data) + 1) & mask)) & mask;\n  expected_result = helib::bitSetToLong(expected_result, bitSize);\n\n  std::vector<helib::Ctxt> encrypted_minuend(bitSize, helib::Ctxt(secKey));\n  std::vector<helib::Ctxt> encrypted_subtrahend(bitSize, helib::Ctxt(secKey));\n\n  for (long i = 0; i < bitSize; i++) {\n    secKey.Encrypt(encrypted_minuend[i], NTL::ZZX((minuend_data >> i) & 1));\n    if (bootstrap) { // If bootstrapping then modulo down to a lower level.\n      encrypted_minuend[i].bringToSet(context.getCtxtPrimes(5));\n    }\n  }\n  for (long i = 0; i < bitSize; i++) {\n    secKey.Encrypt(encrypted_subtrahend[i],\n                   NTL::ZZX((subtrahend_data >> i) & 1));\n    if (bootstrap) { // If bootstrapping then modulo down to a lower level.\n      encrypted_subtrahend[i].bringToSet(context.getCtxtPrimes(5));\n    }\n  }\n  std::vector<long> decrypted_result;\n  std::vector<helib::Ctxt> result_vector(bitSize, helib::Ctxt(secKey));\n  helib::CtPtrs_vectorCt output_wrapper(result_vector);\n  helib::subtractBinary(output_wrapper,\n                        helib::CtPtrs_vectorCt(encrypted_minuend),\n                        helib::CtPtrs_vectorCt(encrypted_subtrahend));\n  helib::decryptBinaryNums(decrypted_result, output_wrapper, secKey, ea, true);\n\n  EXPECT_EQ(decrypted_result.size(), ea.size());\n  for (std::size_t i = 0; i < decrypted_result.size(); ++i) {\n    EXPECT_EQ(decrypted_result[i], expected_result) << \"i = \" << i << std::endl;\n  }\n\n  // Make sure it throws for incorrect-length args\n  result_vector.emplace_back(secKey);\n  const auto do_subtract = [&]() {\n    helib::subtractBinary(output_wrapper,\n                          helib::CtPtrs_vectorCt(encrypted_minuend),\n                          helib::CtPtrs_vectorCt(encrypted_subtrahend));\n  };\n  EXPECT_THROW(do_subtract(), helib::LogicError);\n  encrypted_subtrahend.emplace_back(secKey);\n  EXPECT_THROW(do_subtract(), helib::LogicError);\n}\n\nTEST_P(GTestBinaryArith, binaryMaskMasksCorrectly)\n{\n  const helib::EncryptedArray& ea = *context.ea;\n  const helib::PubKey& pubKey = secKey;\n  helib::Ctxt mask(secKey);\n  helib::Ptxt<helib::BGV> mask_data(context);\n  for (std::size_t i = 0; i < mask_data.size(); ++i)\n    mask_data[i] = i % 2;\n\n  pubKey.Encrypt(mask, mask_data);\n  std::vector<helib::Ctxt> eNums(bitSize, helib::Ctxt(secKey));\n  long input_number = NTL::RandomBits_long(bitSize);\n\n  for (long i = 0; i < bitSize; ++i)\n    secKey.Encrypt(eNums[i], NTL::ZZX((input_number >> i) & 1));\n\n  std::vector<helib::Ctxt> output(eNums);\n  helib::CtPtrs_vectorCt output_wrapper(output);\n  helib::binaryMask(output_wrapper, mask);\n\n  std::vector<long> decrypted_result;\n  helib::decryptBinaryNums(decrypted_result, output_wrapper, secKey, ea);\n\n  EXPECT_EQ(decrypted_result.size(), ea.size());\n  for (long i = 0; i < bitSize; ++i)\n    if (i % 2 == 1) {\n      EXPECT_EQ(decrypted_result[i], input_number) << \"i = \" << i << std::endl;\n    } else {\n      EXPECT_EQ(decrypted_result[i], 0L) << \"i = \" << i << std::endl;\n    }\n  // No error cases to test, all sized inputs are valid\n}\n\nTEST_P(GTestBinaryArith, binaryCondWorksCorrectly)\n{\n  const helib::EncryptedArray& ea = *context.ea;\n  const helib::PubKey& pubKey = secKey;\n  helib::Ctxt cond(secKey);\n  helib::Ptxt<helib::BGV> cond_data(context);\n  for (std::size_t i = 0; i < cond_data.size(); ++i)\n    cond_data[i] = i % 2;\n\n  pubKey.Encrypt(cond, cond_data);\n  std::vector<helib::Ctxt> lhsNums(bitSize, helib::Ctxt(secKey));\n  std::vector<helib::Ctxt> rhsNums(bitSize, helib::Ctxt(secKey));\n  long lhs_number = NTL::RandomBits_long(bitSize);\n  long rhs_number = NTL::RandomBits_long(bitSize);\n\n  for (long i = 0; i < bitSize; ++i) {\n    secKey.Encrypt(lhsNums[i], NTL::ZZX((lhs_number >> i) & 1));\n    secKey.Encrypt(rhsNums[i], NTL::ZZX((rhs_number >> i) & 1));\n  }\n\n  std::vector<helib::Ctxt> output(lhsNums);\n  helib::CtPtrs_vectorCt output_wrapper(output);\n  helib::binaryCond(output_wrapper,\n                    cond,\n                    helib::CtPtrs_vectorCt(lhsNums),\n                    helib::CtPtrs_vectorCt(rhsNums));\n\n  std::vector<long> decrypted_result;\n  helib::decryptBinaryNums(decrypted_result, output_wrapper, secKey, ea);\n\n  EXPECT_EQ(decrypted_result.size(), ea.size());\n  for (long i = 0; i < bitSize; ++i) {\n    EXPECT_EQ(decrypted_result[i], (i % 2) ? lhs_number : rhs_number)\n        << \"i = \" << i << std::endl;\n  }\n\n  // All three CtPtrs args must have same size.  Check that it throws if not.\n  const auto do_cond = [&]() {\n    helib::binaryCond(output_wrapper,\n                      cond,\n                      helib::CtPtrs_vectorCt(lhsNums),\n                      helib::CtPtrs_vectorCt(rhsNums));\n  };\n  lhsNums.emplace_back(secKey);\n  EXPECT_THROW(do_cond(), /*1*/ helib::LogicError);\n  rhsNums.emplace_back(secKey);\n  EXPECT_THROW(do_cond(), /*2*/ helib::LogicError);\n  output.emplace_back(secKey);\n  output.emplace_back(secKey);\n  EXPECT_THROW(do_cond(), /*3*/ helib::LogicError);\n}\n\nTEST_P(GTestBinaryArith, concatBinaryNumsConcatsCorrectly)\n{\n  const helib::EncryptedArray& ea = *context.ea;\n  long lhs_number = NTL::RandomBits_long(bitSize);\n  long rhs_number = NTL::RandomBits_long(bitSize);\n\n  std::vector<helib::Ctxt> lhs(bitSize, helib::Ctxt(secKey));\n  std::vector<helib::Ctxt> rhs(bitSize, helib::Ctxt(secKey));\n  for (long i = 0; i < bitSize; ++i) {\n    secKey.Encrypt(lhs[i], NTL::ZZX((lhs_number >> i) & 1));\n    secKey.Encrypt(rhs[i], NTL::ZZX((rhs_number >> i) & 1));\n  }\n\n  std::vector<helib::Ctxt> output(bitSize * 2, helib::Ctxt(secKey));\n  helib::CtPtrs_vectorCt output_wrapper(output);\n  helib::concatBinaryNums(output_wrapper,\n                          helib::CtPtrs_vectorCt(lhs),\n                          helib::CtPtrs_vectorCt(rhs));\n\n  std::vector<long> decrypted_result;\n  helib::decryptBinaryNums(decrypted_result, output_wrapper, secKey, ea);\n\n  EXPECT_EQ(decrypted_result.size(), ea.size());\n  for (std::size_t i = 0; i < decrypted_result.size(); ++i) {\n    EXPECT_EQ(decrypted_result[i], (rhs_number << bitSize) + lhs_number)\n        << \"i = \" << i << std::endl;\n  }\n\n  // Make sure that incorrect sizing issues throw\n  const auto do_concat = [&]() {\n    helib::concatBinaryNums(output_wrapper,\n                            helib::CtPtrs_vectorCt(lhs),\n                            helib::CtPtrs_vectorCt(rhs));\n  };\n  output.emplace_back(secKey);\n  EXPECT_THROW(do_concat(), helib::LogicError);\n  output.pop_back();\n  output.pop_back();\n  EXPECT_THROW(do_concat(), helib::LogicError);\n}\n\nTEST_P(GTestBinaryArith, splitBinaryNumsSplitsCorrectly)\n{\n  const helib::EncryptedArray& ea = *context.ea;\n  long lhs_number = NTL::RandomBits_long(bitSize + 1);\n  long rhs_number = NTL::RandomBits_long(bitSize);\n\n  std::vector<helib::Ctxt> lhs(bitSize + 1, helib::Ctxt(secKey));\n  std::vector<helib::Ctxt> rhs(bitSize, helib::Ctxt(secKey));\n  for (long i = 0; i < bitSize; ++i) {\n    secKey.Encrypt(lhs[i], NTL::ZZX((lhs_number >> i) & 1));\n    secKey.Encrypt(rhs[i], NTL::ZZX((rhs_number >> i) & 1));\n  }\n  secKey.Encrypt(lhs[bitSize], NTL::ZZX((lhs_number >> bitSize) & 1));\n\n  std::vector<helib::Ctxt> concatenation((bitSize * 2) + 1,\n                                         helib::Ctxt(secKey));\n  helib::CtPtrs_vectorCt concatenation_wrapper(concatenation);\n  helib::concatBinaryNums(concatenation_wrapper,\n                          helib::CtPtrs_vectorCt(lhs),\n                          helib::CtPtrs_vectorCt(rhs));\n\n  std::vector<helib::Ctxt> lhs_output(bitSize + 1, helib::Ctxt(secKey));\n  std::vector<helib::Ctxt> rhs_output(bitSize, helib::Ctxt(secKey));\n  helib::CtPtrs_vectorCt lhs_output_wrapper(lhs_output);\n  helib::CtPtrs_vectorCt rhs_output_wrapper(rhs_output);\n  helib::splitBinaryNums(lhs_output_wrapper,\n                         rhs_output_wrapper,\n                         concatenation_wrapper);\n\n  std::vector<long> decrypted_lhs;\n  std::vector<long> decrypted_rhs;\n  helib::decryptBinaryNums(decrypted_lhs, lhs_output_wrapper, secKey, ea);\n  helib::decryptBinaryNums(decrypted_rhs, rhs_output_wrapper, secKey, ea);\n\n  EXPECT_EQ(decrypted_lhs.size(), ea.size());\n  EXPECT_EQ(decrypted_rhs.size(), ea.size());\n  for (std::size_t i = 0; i < decrypted_lhs.size(); ++i) {\n    EXPECT_EQ(decrypted_lhs[i], lhs_number) << \"i = \" << i << std::endl;\n    EXPECT_EQ(decrypted_rhs[i], rhs_number) << \"i = \" << i << std::endl;\n  }\n\n  // Make sure it throws if the sizes don't line up\n  const auto do_split = [&]() {\n    helib::splitBinaryNums(lhs_output_wrapper,\n                           rhs_output_wrapper,\n                           concatenation_wrapper);\n  };\n  lhs_output.emplace_back(secKey);\n  EXPECT_THROW(do_split(), helib::LogicError);\n  lhs_output.pop_back();\n  lhs_output.pop_back();\n  EXPECT_THROW(do_split(), helib::LogicError);\n}\n\nTEST_P(GTestBinaryArith, bitwiseShiftShiftsCorrectly)\n{\n  const helib::EncryptedArray& ea = *context.ea;\n  long number = NTL::RandomBits_long(bitSize);\n\n  std::vector<helib::Ctxt> eNums(bitSize, helib::Ctxt(secKey));\n  for (long i = 0; i < bitSize; ++i)\n    secKey.Encrypt(eNums[i], NTL::ZZX((number >> i) & 1));\n\n  unsigned long mask = (1Lu << bitSize) - 1;\n  for (long shamt = 0; shamt <= bitSize; ++shamt) {\n    std::vector<helib::Ctxt> output(bitSize, helib::Ctxt(secKey));\n    helib::CtPtrs_vectorCt output_wrapper(output);\n\n    helib::leftBitwiseShift(output_wrapper,\n                            helib::CtPtrs_vectorCt(eNums),\n                            shamt);\n\n    std::vector<long> decrypted_result;\n    helib::decryptBinaryNums(decrypted_result, output_wrapper, secKey, ea);\n\n    EXPECT_EQ(decrypted_result.size(), ea.size());\n    for (std::size_t i = 0; i < decrypted_result.size(); ++i)\n      EXPECT_EQ(decrypted_result[i], (number << shamt) & mask)\n          << \"i = \" << i << std::endl;\n  }\n\n  // Make sure it throws if output and input aren't the same size\n  std::vector<helib::Ctxt> output(bitSize + 1, helib::Ctxt(secKey));\n  helib::CtPtrs_vectorCt output_wrapper(output);\n\n  const auto do_shift = [&]() {\n    helib::leftBitwiseShift(output_wrapper, helib::CtPtrs_vectorCt(eNums), 0);\n  };\n  EXPECT_THROW(do_shift(), helib::LogicError);\n  output.pop_back();\n  output.pop_back();\n  EXPECT_THROW(do_shift(), helib::LogicError);\n}\n\nTEST_P(GTestBinaryArith, bitwiseRotateRotatesCorrectly)\n{\n  const helib::EncryptedArray& ea = *context.ea;\n  long input = NTL::RandomBits_long(bitSize);\n\n  std::vector<helib::Ctxt> eNums(bitSize, helib::Ctxt(secKey));\n  for (long i = 0; i < bitSize; ++i)\n    secKey.Encrypt(eNums[i], NTL::ZZX((input >> i) & 1));\n\n  const auto plaintext_rotate = [](long num, long amt, long bitSize) {\n    // Make sure that amt is in the right range\n    amt = ((amt % bitSize) + bitSize) % bitSize;\n    long mask = (1LU << bitSize) - 1;\n    // Get the left hand part\n    long result = (num << amt) & mask;\n    // Get the right-hand part\n    result |= (num >> (bitSize - amt)) & mask;\n    return result;\n  };\n\n  // Test all rotation amounts from negative values which wrap around mod\n  // bitSize, up to positive values which wrap around mod bitSize.\n  for (long rotamt = -bitSize - 1; rotamt <= bitSize + 1; ++rotamt) {\n    std::vector<helib::Ctxt> output(bitSize, helib::Ctxt(secKey));\n    helib::CtPtrs_vectorCt output_wrapper(output);\n    helib::bitwiseRotate(output_wrapper, helib::CtPtrs_vectorCt(eNums), rotamt);\n    std::vector<long> decrypted_result;\n    helib::decryptBinaryNums(decrypted_result, output_wrapper, secKey, ea);\n    EXPECT_EQ(decrypted_result.size(), ea.size());\n    for (std::size_t i = 0; i < decrypted_result.size(); ++i) {\n      EXPECT_EQ(decrypted_result[i], plaintext_rotate(input, rotamt, bitSize))\n          << \"i = \" << i << std::endl;\n    }\n  }\n\n  // Check that non-matching input and output sizes throw\n  std::vector<helib::Ctxt> output(bitSize + 1, helib::Ctxt(secKey));\n  helib::CtPtrs_vectorCt output_wrapper(output);\n  const auto do_rotate = [&]() {\n    helib::bitwiseRotate(output_wrapper, helib::CtPtrs_vectorCt(eNums), 0);\n  };\n  EXPECT_THROW(do_rotate(), helib::LogicError);\n  output.pop_back();\n  output.pop_back();\n  EXPECT_THROW(do_rotate(), helib::LogicError);\n}\n\nTEST_P(GTestBinaryArith, binaryAndWithLongAndsCorrectly)\n{\n  const helib::EncryptedArray& ea = *context.ea;\n  long number = NTL::RandomBits_long(bitSize);\n\n  unsigned long long_mask = 0;\n  std::vector<long> mask;\n  std::vector<helib::Ctxt> eNums(bitSize, helib::Ctxt(secKey));\n  for (long i = 0; i < bitSize; ++i) {\n    secKey.Encrypt(eNums[i], NTL::ZZX((number >> i) & 1));\n    mask.push_back(i % 2);\n    long_mask |= (i % 2) << i;\n  }\n\n  std::vector<helib::Ctxt> output(bitSize, helib::Ctxt(secKey));\n  helib::CtPtrs_vectorCt output_wrapper(output);\n\n  helib::bitwiseAnd(output_wrapper, helib::CtPtrs_vectorCt(eNums), mask);\n\n  std::vector<long> decrypted_result;\n  helib::decryptBinaryNums(decrypted_result, output_wrapper, secKey, ea);\n\n  EXPECT_EQ(decrypted_result.size(), ea.size());\n  for (std::size_t i = 0; i < decrypted_result.size(); ++i) {\n    EXPECT_EQ(decrypted_result[i], (number & long_mask))\n        << \"i = \" << i << std::endl;\n  }\n\n  // Check that non-matching input and output sizes throw\n  const auto do_and = [&]() {\n    helib::bitwiseAnd(output_wrapper, helib::CtPtrs_vectorCt(eNums), mask);\n  };\n  output.emplace_back(secKey);\n  EXPECT_THROW(do_and(), helib::LogicError);\n  output.pop_back();\n  output.pop_back();\n  EXPECT_THROW(do_and(), helib::LogicError);\n}\n\nTEST_P(GTestBinaryArith, binaryXORXORsCorrectly)\n{\n  const helib::EncryptedArray& ea = *context.ea;\n  long lhs = NTL::RandomBits_long(bitSize);\n  long rhs = NTL::RandomBits_long(bitSize);\n\n  std::vector<helib::Ctxt> encrypted_lhs(bitSize, helib::Ctxt(secKey));\n  std::vector<helib::Ctxt> encrypted_rhs(bitSize, helib::Ctxt(secKey));\n\n  for (long i = 0; i < bitSize; ++i) {\n    secKey.Encrypt(encrypted_lhs[i], NTL::ZZX((lhs >> i) & 1));\n    secKey.Encrypt(encrypted_rhs[i], NTL::ZZX((rhs >> i) & 1));\n  }\n\n  std::vector<helib::Ctxt> output(bitSize, helib::Ctxt(secKey));\n  helib::CtPtrs_vectorCt output_wrapper(output);\n\n  helib::bitwiseXOR(output_wrapper,\n                    helib::CtPtrs_vectorCt(encrypted_lhs),\n                    helib::CtPtrs_vectorCt(encrypted_rhs));\n\n  std::vector<long> decrypted_result;\n  helib::decryptBinaryNums(decrypted_result, output_wrapper, secKey, ea);\n\n  EXPECT_EQ(decrypted_result.size(), ea.size());\n  for (std::size_t i = 0; i < decrypted_result.size(); ++i) {\n    EXPECT_EQ(decrypted_result[i], lhs ^ rhs) << \"i = \" << i << std::endl;\n  }\n\n  // Check that non-matching sizes throw\n  const auto do_xor = [&]() {\n    helib::bitwiseXOR(output_wrapper,\n                      helib::CtPtrs_vectorCt(encrypted_lhs),\n                      helib::CtPtrs_vectorCt(encrypted_rhs));\n  };\n  output.emplace_back(secKey);\n  EXPECT_THROW(do_xor(), helib::LogicError);\n  encrypted_lhs.emplace_back(secKey);\n  EXPECT_THROW(do_xor(), helib::LogicError);\n}\n\nTEST_P(GTestBinaryArith, binaryAndAndsCorrectly)\n{\n  const helib::EncryptedArray& ea = *context.ea;\n  long lhs = NTL::RandomBits_long(bitSize);\n  long rhs = NTL::RandomBits_long(bitSize);\n\n  std::vector<helib::Ctxt> encrypted_lhs(bitSize, helib::Ctxt(secKey));\n  std::vector<helib::Ctxt> encrypted_rhs(bitSize, helib::Ctxt(secKey));\n\n  for (long i = 0; i < bitSize; ++i) {\n    secKey.Encrypt(encrypted_lhs[i], NTL::ZZX((lhs >> i) & 1));\n    secKey.Encrypt(encrypted_rhs[i], NTL::ZZX((rhs >> i) & 1));\n  }\n\n  std::vector<helib::Ctxt> output(bitSize, helib::Ctxt(secKey));\n  helib::CtPtrs_vectorCt output_wrapper(output);\n\n  helib::bitwiseAnd(output_wrapper,\n                    helib::CtPtrs_vectorCt(encrypted_lhs),\n                    helib::CtPtrs_vectorCt(encrypted_rhs));\n\n  std::vector<long> decrypted_result;\n  helib::decryptBinaryNums(decrypted_result, output_wrapper, secKey, ea);\n\n  EXPECT_EQ(decrypted_result.size(), ea.size());\n  for (std::size_t i = 0; i < decrypted_result.size(); ++i) {\n    EXPECT_EQ(decrypted_result[i], lhs & rhs) << \"i = \" << i << std::endl;\n  }\n\n  // Make sure it throws if arguments' sizes don't match\n  const auto do_and = [&]() {\n    helib::bitwiseAnd(output_wrapper,\n                      helib::CtPtrs_vectorCt(encrypted_lhs),\n                      helib::CtPtrs_vectorCt(encrypted_rhs));\n  };\n  output.emplace_back(secKey);\n  EXPECT_THROW(do_and(), helib::LogicError);\n  encrypted_lhs.emplace_back(secKey);\n  EXPECT_THROW(do_and(), helib::LogicError);\n}\n\nTEST_P(GTestBinaryArith, binaryOrOrsCorrectly)\n{\n  const helib::EncryptedArray& ea = *context.ea;\n  long lhs = NTL::RandomBits_long(bitSize);\n  long rhs = NTL::RandomBits_long(bitSize);\n\n  std::vector<helib::Ctxt> encrypted_lhs(bitSize, helib::Ctxt(secKey));\n  std::vector<helib::Ctxt> encrypted_rhs(bitSize, helib::Ctxt(secKey));\n\n  for (long i = 0; i < bitSize; ++i) {\n    secKey.Encrypt(encrypted_lhs[i], NTL::ZZX((lhs >> i) & 1));\n    secKey.Encrypt(encrypted_rhs[i], NTL::ZZX((rhs >> i) & 1));\n  }\n\n  std::vector<helib::Ctxt> output(bitSize, helib::Ctxt(secKey));\n  helib::CtPtrs_vectorCt output_wrapper(output);\n\n  helib::bitwiseOr(output_wrapper,\n                   helib::CtPtrs_vectorCt(encrypted_lhs),\n                   helib::CtPtrs_vectorCt(encrypted_rhs));\n\n  std::vector<long> decrypted_result;\n  helib::decryptBinaryNums(decrypted_result, output_wrapper, secKey, ea);\n\n  EXPECT_EQ(decrypted_result.size(), ea.size());\n  for (std::size_t i = 0; i < decrypted_result.size(); ++i) {\n    EXPECT_EQ(decrypted_result[i], lhs | rhs) << \"i = \" << i << std::endl;\n  }\n\n  // Make sure it throws if arguments' sizes don't match\n  const auto do_or = [&]() {\n    helib::bitwiseOr(output_wrapper,\n                     helib::CtPtrs_vectorCt(encrypted_lhs),\n                     helib::CtPtrs_vectorCt(encrypted_rhs));\n  };\n  output.emplace_back(secKey);\n  EXPECT_THROW(do_or(), helib::LogicError);\n  encrypted_lhs.emplace_back(secKey);\n  EXPECT_THROW(do_or(), helib::LogicError);\n}\n\nTEST_P(GTestBinaryArith, bitwiseNotNotsCorrectly)\n{\n  const helib::EncryptedArray& ea = *context.ea;\n  long input = NTL::RandomBits_long(bitSize);\n\n  std::vector<helib::Ctxt> eNums(bitSize, helib::Ctxt(secKey));\n  long mask = (1LU << bitSize) - 1;\n\n  for (long i = 0; i < bitSize; ++i)\n    secKey.Encrypt(eNums[i], NTL::ZZX((input >> i) & 1));\n\n  std::vector<helib::Ctxt> output(bitSize, helib::Ctxt(secKey));\n  helib::CtPtrs_vectorCt output_wrapper(output);\n\n  helib::bitwiseNot(output_wrapper, helib::CtPtrs_vectorCt(eNums));\n\n  std::vector<long> decrypted_result;\n  helib::decryptBinaryNums(decrypted_result, output_wrapper, secKey, ea);\n\n  EXPECT_EQ(decrypted_result.size(), ea.size());\n  for (std::size_t i = 0; i < decrypted_result.size(); ++i) {\n    EXPECT_EQ(decrypted_result[i], (~input) & mask) << \"i = \" << i << std::endl;\n  }\n\n  // Make sure it throws if input and output are different sizes\n  const auto do_not = [&]() {\n    helib::bitwiseNot(output_wrapper, helib::CtPtrs_vectorCt(eNums));\n  };\n  output.emplace_back(secKey);\n  EXPECT_THROW(do_not(), helib::LogicError);\n  output.pop_back();\n  output.pop_back();\n  EXPECT_THROW(do_not(), helib::LogicError);\n}\n\nINSTANTIATE_TEST_SUITE_P(\n    smallParameterSizesRepeated,\n    GTestBinaryArith,\n    ::testing::Combine(\n        ::testing::Values(\n            // SLOW\n            Parameters(1, 5, 0, 0, false, 0, 1)\n            // FAST\n            // Parameters(0, 5, 0, 0, false, 0, 1)), ::testing::Range(0,2)\n\n            ),\n        ::testing::Range(0, 2)) // The range is for repeats\n);\n\n} // anonymous namespace\n", "meta": {"hexsha": "90cb03780f5486e814a2f939f57be8185a03830a", "size": 45779, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/GTestBinaryArith.cpp", "max_stars_repo_name": "jatanloya/HElib-PSI", "max_stars_repo_head_hexsha": "b5ec2844216ac87f1e20542e31ebb98363c14a6f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/GTestBinaryArith.cpp", "max_issues_repo_name": "jatanloya/HElib-PSI", "max_issues_repo_head_hexsha": "b5ec2844216ac87f1e20542e31ebb98363c14a6f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-11-05T10:55:33.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-05T12:59:21.000Z", "max_forks_repo_path": "tests/GTestBinaryArith.cpp", "max_forks_repo_name": "jatanloya/HElib-PSI", "max_forks_repo_head_hexsha": "b5ec2844216ac87f1e20542e31ebb98363c14a6f", "max_forks_repo_licenses": ["Apache-2.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.7407704655, "max_line_length": 84, "alphanum_fraction": 0.6450337491, "num_tokens": 13257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746404, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.4744733772225737}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n#include <boost/assert.hpp>\n#include <type_traits>\n\n#include \"spectral/basis/spectral_basis_factory_hermite.hpp\"\n#include \"spectral/basis/spectral_basis_factory_ks.hpp\"\n#include \"spectral/basis/toolbox/spectral_basis.hpp\"\n#include \"spectral/polar_to_hermite.hpp\"\n\n\nnamespace boltzmann {\n\nclass MQEval;  // forward declaration\n\nnamespace detail_ {\n/**\n * @helper to evaluate macroscopic quantities\n *\n * @param mq\n *\n * @return\n */\nstruct MQEval_helper\n{\n public:\n  typedef Eigen::Vector3d vector_t;\n  typedef Eigen::Matrix3d tensor_t;\n  typedef double scalar_t;\n\n public:\n  MQEval_helper(const MQEval &mq)\n      : mq_(mq)\n  { /* empty */\n  }\n\n  void operator()(const double *ptr_c, unsigned int N);\n\n  template <typename DERIVED>\n  void operator()(const Eigen::DenseBase<DERIVED> &c);\n\n public:\n  double m;    // mass\n  double e;    // energy\n  vector_t v;  // velocity\n  vector_t r;  // energy flow\n  tensor_t P;  // pressure\n  vector_t q;  // heat flow\n  tensor_t M;  // momentum flow\n\n private:\n  const MQEval &mq_;\n};\n\n}  // detail_\n\n/**\n * @brief macroscopic quantities evaluator\n *\n */\nclass MQEval\n{\n public:\n  typedef detail_::MQEval_helper evaluator_t;\n\n public:\n  MQEval() { /*  default constructor */}\n\n  template <typename BASIS>\n  MQEval(const BASIS &basis)\n  {\n    init(basis);\n  }\n\n  /**\n   *  @brief evaluator to do actual compuations\n   *\n   *  Returns a struct storing the moments, it has a const reference to *this\n   * (where the\n   *  coefficients are stored).\n   *\n   *  Attention: MQEval_helper depends on MQEval by a reference, make sure it\n   * does not run out of\n   * scope as\n   *  long as the MQEval_helper is in use.\n   *\n   */\n  detail_::MQEval_helper evaluator() const { return detail_::MQEval_helper(*this); }\n\n  /**\n   *\n   * @param basis  Polar-Laguerre basis\n   */\n  template <typename BASIS>\n  void init(const BASIS &basis);\n\n private:\n  typedef Eigen::VectorXd vec_t;\n  typedef Eigen::ArrayXd array_t;\n  typedef Eigen::MatrixXd mat_t;\n\n private:\n  /// basis size\n  unsigned int N_ = 0;\n  const double tol_ = 1e-10;\n\n  array_t mass_;\n  array_t energy_;\n  array_t ux_;\n  array_t uy_;\n  /// momentum flow\n  array_t uxx_;\n  array_t uyy_;\n  array_t uxy_;\n  /// energy flow\n  array_t rx_;\n  array_t ry_;\n\n public:\n  //@{\n  /// coefficients in Polar-Laguerre basis\n  const array_t &cmass() const { return mass_; }\n  const array_t &cenergy() const { return energy_; }\n  const array_t &cux() const { return ux_; }\n  const array_t &cuy() const { return uy_; }\n  const array_t &cuxx() const { return uxx_; }\n  const array_t &cuyy() const { return uyy_; }\n  const array_t &cuxy() const { return uxy_; }\n  const array_t &crx() const { return rx_; }\n  const array_t &cry() const { return ry_; }\n  //@}\n\n  unsigned int N() const { return N_; }\n\n private:\n  /**\n   * @brief trim non zero coefficients starting from the end\n   */\n  template <typename DERIVED>\n  void trim_coeff(Eigen::DenseBase<DERIVED> &coeffs);\n};\n\n// ---------------------------------------------------------------------------\ntemplate <typename BASIS>\nvoid\nMQEval::init(const BASIS &basis)\n{\n  typedef BASIS polar_basis_t;\n  // compute coefficients\n\n  int K = spectral::get_max_k(basis) + 1;\n  int N = basis.n_dofs();\n  N_ = N;\n\n  typedef SpectralBasisFactoryHN::basis_type hermite_basis_t;\n  hermite_basis_t hermite_basis;\n\n  SpectralBasisFactoryHN::create(hermite_basis, K, 2);\n  Polar2Hermite<polar_basis_t, hermite_basis_t> P2H(basis, hermite_basis);\n  typedef typename hermite_basis_t::elem_t hermite_elem_t;\n\n  typedef typename boost::mpl::at_c<typename hermite_elem_t::types_t, 0>::type hx_t;\n  typedef typename boost::mpl::at_c<typename hermite_elem_t::types_t, 1>::type hy_t;\n\n  typename hermite_elem_t::Acc::template get<hx_t> get_hx;\n  typename hermite_elem_t::Acc::template get<hy_t> get_hy;\n\n  // Hermite quadrature\n  QHermiteW quad(0.5, K);\n  // Hermite polynomials\n  HermiteNW<double> hermw(K);\n  hermw.compute(quad.pts());\n\n  // test for mass\n  vec_t herm_coeffs(N);\n  // apply \"quadrature\":\n  Eigen::Map<const array_t> x(quad.points_data(), K);\n  Eigen::Map<const array_t> w(quad.weights_data(), K);\n\n  // ------------------------------\n  // MASS\n  for (int i = 0; i < N; ++i) {\n    int kx = get_hx(hermite_basis.get_elem(i)).get_id().k;\n    int ky = get_hy(hermite_basis.get_elem(i)).get_id().k;\n    auto hx = hermw.get_array(kx);\n    auto hy = hermw.get_array(ky);\n\n    herm_coeffs[i] = (hx * w).sum() * (hy * w).sum();\n  }\n  mass_.resize(N);\n  P2H.to_hermite_T(mass_, herm_coeffs);\n\n  // ------------------------------\n  // ENERGY\n  for (int i = 0; i < N; ++i) {\n    int kx = get_hx(hermite_basis.get_elem(i)).get_id().k;\n    int ky = get_hy(hermite_basis.get_elem(i)).get_id().k;\n\n    auto hx = hermw.get_array(kx);\n    auto hy = hermw.get_array(ky);\n\n    herm_coeffs[i] =\n        (x * x * hx * w).sum() * (hy * w).sum() + (x * x * hy * w).sum() * (hx * w).sum();\n  }\n  energy_.resize(N);\n  P2H.to_hermite_T(energy_, herm_coeffs);\n\n  // ------------------------------\n  // MOMENTUM\n  vec_t herm_coeffs2(N);\n  for (int i = 0; i < N; ++i) {\n    int kx = get_hx(hermite_basis.get_elem(i)).get_id().k;\n    int ky = get_hy(hermite_basis.get_elem(i)).get_id().k;\n    auto hx = hermw.get_array(kx);\n    auto hy = hermw.get_array(ky);\n    double sumx = (x * hx * w).sum() * (hy * w).sum();\n    double sumy = (x * hy * w).sum() * (hx * w).sum();\n    herm_coeffs[i] = sumx;\n    herm_coeffs2[i] = sumy;\n  }\n\n  ux_.resize(N);\n  P2H.to_hermite_T(ux_, herm_coeffs);\n  uy_.resize(N);\n  P2H.to_hermite_T(uy_, herm_coeffs2);\n\n  // resize to non-zero contribution\n  trim_coeff(mass_);\n  trim_coeff(energy_);\n  trim_coeff(ux_);\n  trim_coeff(uy_);\n\n  uxx_.resize(N);\n  uxy_.resize(N);\n  uyy_.resize(N);\n  // ------------------------------\n  // Momentum flow\n  for (int i = 0; i < N; ++i) {\n    int kx = get_hx(hermite_basis.get_elem(i)).get_id().k;\n    int ky = get_hy(hermite_basis.get_elem(i)).get_id().k;\n    auto hx = hermw.get_array(kx);\n    auto hy = hermw.get_array(ky);\n    const double tx = (x * hx * w).sum();\n    const double ty = (x * hy * w).sum();\n    uxx_[i] = (x * x * hx * w).sum() * (hy * w).sum();\n    uxy_[i] = (x * hx * w).sum() * (x * hy * w).sum();\n    uyy_[i] = (x * x * hy * w).sum() * (hx * w).sum();\n  }\n  herm_coeffs = uxx_;\n  P2H.to_hermite_T(uxx_, herm_coeffs);\n  herm_coeffs = uxy_;\n  P2H.to_hermite_T(uxy_, herm_coeffs);\n  herm_coeffs = uyy_;\n  P2H.to_hermite_T(uyy_, herm_coeffs);\n\n  // ------------------------------\n  // Momentum flow\n  uxx_.resize(N);\n  uxy_.resize(N);\n  uyy_.resize(N);\n  for (int i = 0; i < N; ++i) {\n    int kx = get_hx(hermite_basis.get_elem(i)).get_id().k;\n    int ky = get_hy(hermite_basis.get_elem(i)).get_id().k;\n    auto hx = hermw.get_array(kx);\n    auto hy = hermw.get_array(ky);\n\n    uxx_[i] = (x * x * hx * w).sum() * (hy * w).sum();\n    uxy_[i] = (x * hx * w).sum() * (x * hy * w).sum();\n    uyy_[i] = (x * x * hy * w).sum() * (hx * w).sum();\n  }\n  herm_coeffs = uxx_;\n  P2H.to_hermite_T(uxx_, herm_coeffs);\n  herm_coeffs = uxy_;\n  P2H.to_hermite_T(uxy_, herm_coeffs);\n  herm_coeffs = uyy_;\n  P2H.to_hermite_T(uyy_, herm_coeffs);\n\n  // ------------------------------\n  // Energy flow\n  rx_.resize(N);\n  ry_.resize(N);\n  for (int i = 0; i < N; ++i) {\n    int kx = get_hx(hermite_basis.get_elem(i)).get_id().k;\n    int ky = get_hy(hermite_basis.get_elem(i)).get_id().k;\n    auto hx = hermw.get_array(kx);\n    auto hy = hermw.get_array(ky);\n\n    rx_[i] =\n        (x * x * x * hx * w).sum() * (hy * w).sum() + (x * hx * w).sum() * (x * x * hy * w).sum();\n    ry_[i] =\n        (x * x * x * hy * w).sum() * (hx * w).sum() + (x * hy * w).sum() * (x * x * hx * w).sum();\n  }\n  herm_coeffs = rx_;\n  P2H.to_hermite_T(rx_, herm_coeffs);\n  herm_coeffs = ry_;\n  P2H.to_hermite_T(ry_, herm_coeffs);\n\n  trim_coeff(uxx_);\n  trim_coeff(uxy_);\n  trim_coeff(uyy_);\n\n  trim_coeff(rx_);\n  trim_coeff(ry_);\n}\n\ntemplate <typename DERIVED>\nvoid\nMQEval::trim_coeff(Eigen::DenseBase<DERIVED> &coeffs)\n{\n  for (unsigned int i = N_ - 1; i >= 0; --i) {\n    if (std::abs(coeffs[i]) > tol_) {\n      DERIVED tmp = coeffs.segment(0, i + 1);\n      coeffs.derived().resize(i + 1);\n      coeffs = tmp;\n      break;\n    }\n  }\n}\n\nnamespace detail_ {\ntemplate <typename DERIVED>\nvoid\nMQEval_helper::operator()(const Eigen::DenseBase<DERIVED> &c)\n{\n  static_assert(DERIVED::RowsAtCompileTime == 1 || DERIVED::ColsAtCompileTime == 1,\n                \"Shape mismatch\");\n\n  BOOST_ASSERT(c.cols() * c.rows() == mq_.N());\n  auto &cmass = mq_.cmass();\n  auto &cux = mq_.cux();\n  auto &cuy = mq_.cuy();\n  auto &ce = mq_.cenergy();\n  auto &cuxx = mq_.cuxx();\n  auto &cuxy = mq_.cuxy();\n  auto &cuyy = mq_.cuyy();\n  auto &crx = mq_.crx();\n  auto &cry = mq_.cry();\n\n  auto ca = c.derived().array();\n\n  double rho = (ca.segment(0, cmass.size()) * cmass).sum();\n  m = rho;\n  double rho_vx = (ca.segment(0, cux.size()) * cux).sum();\n  double rho_vy = (ca.segment(0, cuy.size()) * cuy).sum();\n  // total energy\n  double rho_e = (ca.segment(0, ce.size()) * ce).sum();\n  e = rho_e / rho;\n  // energy density per unit volume\n  double w = 0.5 * rho_e;\n  double mxx = (ca.segment(0, cuxx.size()) * cuxx).sum();\n  double mxy = (ca.segment(0, cuxy.size()) * cuxy).sum();\n  double myy = (ca.segment(0, cuyy.size()) * cuyy).sum();\n  M << mxx, mxy, 0, mxy, myy, 0, 0, 0, 0;\n  v(0) = rho_vx / rho;\n  v(1) = rho_vy / rho;\n  v(2) = 0;\n  double pxx = mxx - rho * v(0) * v(0);\n  double pxy = mxy - rho * v(1) * v(0);\n  double pyy = myy - rho * v(1) * v(1);\n  P << pxx, pxy, 0, pxy, pyy, 0, 0, 0, 0;\n  // energy flow\n  r(0) = (ca.segment(0, crx.size()) * crx).sum();\n  r(1) = (ca.segment(0, cry.size()) * cry).sum();\n  r(2) = 0;\n  double v2 = v.squaredNorm();\n  // heat flow\n  q(0) = 0.5 * (r(0) - 2 * (v * M.row(0)).sum() + rho * v2 + 2 * v(0) * w + v2 * v(0) * rho);\n  q(1) = 0.5 * (r(1) - 2 * (v * M.row(1)).sum() + rho * v2 + 2 * v(1) * w + v2 * v(1) * rho);\n  q(2) = 0;\n}\n\ninline void\nMQEval_helper::operator()(const double *ptr_c, unsigned int N)\n{\n  assert(N == mq_.N());\n  Eigen::Map<const Eigen::ArrayXd> c(ptr_c, N);\n  this->operator()(c);\n}\n\n}  // detail_\n\n}  // end namespace boltzmann\n", "meta": {"hexsha": "bfd20929ccc2cb5263c07ce562ea53f1e826dd10", "size": 10125, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "spectral/macroscopic_quantities.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/macroscopic_quantities.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/macroscopic_quantities.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": 26.3671875, "max_line_length": 98, "alphanum_fraction": 0.5980246914, "num_tokens": 3433, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145998, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.4744733734988328}}
{"text": "#include \"visa.hpp\"\n#include <chrono>\n#include <thread>\n#include <iostream>\n#include <armadillo>\n#include <cstdlib>\n#include <ctime>\n\nusing namespace std;\n\nint main( int argc, char** argv )\n{\n  srand(time(0));\n  arma::vec gaussian(700);\n  for ( int i=0;i<gaussian.n_elem;i++ )\n  {\n    double x = static_cast<double>(i)-static_cast<double>(gaussian.n_elem)/2.0;\n    gaussian(i) = exp(-x*x*0.0001);\n  }\n  visa::WindowHandler plots;\n  try\n  {\n    plots.addLinePlot(\"Gaussian\");\n    plots.get(\"Gaussian\").setLimits(0.0,1.2);\n    plots.get(\"Gaussian\").fillVertexArray(gaussian);\n    for ( unsigned int i=0;i<10;i++ )\n    {\n      clog << \"Closes in \" << 10-i << \" sec...\\r\";\n      plots.show();\n      this_thread::sleep_for(chrono::seconds(1));\n    }\n  }\n  catch ( exception &exc )\n  {\n    cout << exc.what() << endl;\n    return 1;\n  }\n  catch (...)\n  {\n    cout << \"Unrecognized exception!\\n\";\n    return 1;\n  }\n  return 0;\n}\n", "meta": {"hexsha": "fa12008893c458992dec357fd8077f965aa3a7ca", "size": 921, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Examples/exLinePlot.cpp", "max_stars_repo_name": "davidkleiven/VISA", "max_stars_repo_head_hexsha": "1b07197a3ea1f88c40e7d9249e08deee360ea814", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-05-27T12:49:40.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-05T05:50:51.000Z", "max_issues_repo_path": "Examples/exLinePlot.cpp", "max_issues_repo_name": "davidkleiven/VISA", "max_issues_repo_head_hexsha": "1b07197a3ea1f88c40e7d9249e08deee360ea814", "max_issues_repo_licenses": ["MIT"], "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/exLinePlot.cpp", "max_forks_repo_name": "davidkleiven/VISA", "max_forks_repo_head_hexsha": "1b07197a3ea1f88c40e7d9249e08deee360ea814", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-04-11T10:05:49.000Z", "max_forks_repo_forks_event_max_datetime": "2018-04-11T10:05:49.000Z", "avg_line_length": 20.4666666667, "max_line_length": 79, "alphanum_fraction": 0.5950054289, "num_tokens": 279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.47446709490779904}}
{"text": "\n#include \"max.hpp\"\n#include \"ast.hpp\"\n#include \"parsers.hpp\"\n#include \"types.hpp\"\n#include <boost/variant.hpp>\n#include <stdexcept>\n#include <algorithm>\nnamespace HT\n{\n    void max(PASTNode astnode, ParsersHelper& ph)\n    {\n        auto myParserHelper(ph);\n        if (astnode->ch.size()<2)\n          throw std::runtime_error(\"Max should have at least one parameter\");\n        auto & secondCh = *astnode->ch.rbegin();\n        ph.parse(secondCh);\n\n        astnode->type = Simple;\n        astnode->token.tokenType = Complex;\n        astnode->token.info = boost::get<ComplexType>(secondCh->token.info);\n        std::for_each( ++astnode->ch.begin(), astnode->ch.end(), [&ph, &astnode](PASTNode an)\n                    {\n                    ph.parse(an);\n                    if (an->token.tokenType != Complex || !boost::get<ComplexType>(an->token.info).isReal())\n                    throw std::runtime_error(\"arguments of Max must be real\");\n                    auto cast = boost::get<ComplexType>(an->token.info);\n                    if (cast.isRational() && boost::get<ComplexType>(astnode->token.info).isRational())\n                    {\n                    if (cast.getRealR() > boost::get<ComplexType>(astnode->token.info).getRealR())\n                    astnode->token.info = cast;\n                    }\n                    else\n                    {\n                    auto cast2= boost::get<ComplexType>(astnode->token.info);\n                    cast.toinexact();\n                    cast2.toinexact();\n                    astnode->token.info = ComplexType( std::max(cast.getRealD(), cast2.getRealD()));\n                    }\n                    });\n        astnode->remove();\n    }\n}\n\n\n", "meta": {"hexsha": "d246e6e178c4650bc657362dcf17cc98797212d2", "size": 1693, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "funs/max.cpp", "max_stars_repo_name": "htfy96/htscheme", "max_stars_repo_head_hexsha": "b44c9f9672f69d9b3c2eb1c80969bcfcfec9990f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2015-07-07T01:30:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-14T10:45:01.000Z", "max_issues_repo_path": "funs/max.cpp", "max_issues_repo_name": "htfy96/htscheme", "max_issues_repo_head_hexsha": "b44c9f9672f69d9b3c2eb1c80969bcfcfec9990f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "funs/max.cpp", "max_forks_repo_name": "htfy96/htscheme", "max_forks_repo_head_hexsha": "b44c9f9672f69d9b3c2eb1c80969bcfcfec9990f", "max_forks_repo_licenses": ["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.8043478261, "max_line_length": 108, "alphanum_fraction": 0.5203780272, "num_tokens": 382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.47446709490779904}}
{"text": "/*\n *  fisher.cpp\n *\n *  Created by Ania M. Kedzierska on 11/11/11.\n *  Copyright 2011 Politecnic University of Catalonia, Center for Genomic Regulation.  This is program can be redistributed, modified or else as given by the terms of the GNU General Public License.\n *\n */\n\n#include <cstdlib>\n#include <cmath>\n\n#include \"fisher.h\"\n#include \"matrix.h\"\n#include \"state.h\"\n#include \"state_list.h\"\n#include \"alignment.h\"\n\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/vector_proxy.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/triangular.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n#include <stdexcept>\n\n\nnamespace ublas = boost::numeric::ublas;\n\n\n//Please refer to the Empar paper for the description of the procedure.\n\n//  The free parameters (without stochastic condition) are encoded as a linear index.\n// There will be np*nedges + rdf+1, where\n// np: free parameters of the transition matrices\n// rdf: df of the root.\n// We put the parameters in a matric, first the transition parameters, then the root parameters at the end.\n// Root parameters are present only for SSM and GMM.\n\n// Converts an edge-row-column to a linear index identifying the parameter for the given model.\nlong erc2param(Model &Mod, long e, long r, long c) {\n  long p = Mod.matrix_structure(r, c);\n  return e*Mod.np + p;\n}\n\n// Converts the root distribution index into a parameter index for the model.\nlong root2param(Tree &T, Model &Mod, long r) {\n  return T.nedges*Mod.np + Mod.root_structure(r);\n}\n\n// STEP 2\n// We then encode the free parameters taking into account the stochastic condition.\n// i.e. we remove the diagonal entry and first parameter of the root.\n\n\n// Converts an edge-row-column to a linear index identifying the free parameter.\nlong erc2freeparam(Tree &T, Model &Mod, long e, long r, long c) {\n  long p = Mod.matrix_structure(r, c);\n  long a,b;\n\n  // find first appearence of parameter p.\n  for (a=0; a < T.nalpha; a++) {\n    for(b=0; b < T.nalpha; b++) {\n      if (Mod.matrix_structure(a,b) == p) {\n        if (b > a) return e*Mod.df + p - a - 1;\n        else if (b < a) return e*Mod.df + p - a;\n        else return -1;\n\n      }\n    }\n  }\n\n  return -1;\n}\n\n// Converts the root distribution index into a free parameter index.\nlong root2freeparam(Tree &T, Model &Mod, long r) {\n  long p = Mod.root_structure(r);\n\n  if (p == 0) return -1;   // p = 0 is the parameter killed.\n  else return T.nedges*Mod.df + p - 1;\n}\n\n\n// Computes the state at the endpoints of an edge.\n// T: tree\n// e: edge\n// sth: state on hidden nodes\n// stl: state on leaves\n\n// Output:\n// a: the state of the source.\n// b: the state of the target.\n\nvoid edgestate(Tree &T, long e, State &sth, State &stl, long &a, long &b) {\n  a = sth.s[T.edges[e].s - T.nleaves];      // state on the source node\n  if (T.edges[e].t < T.nleaves){            // if the edge connects to a leaf\n    b = stl.s[T.edges[e].t];                // state on the target leaf\n  } else {\n    b = sth.s[T.edges[e].t - T.nleaves];    // state on the target node\n  }\n}\n\n\nvoid edgestate(Tree &T, long e, std::vector<int> &sth, std::vector<int> &stl, long &a, long &b) {\n  a = sth[T.edges[e].s - T.nleaves];      // state on the source node\n  if (T.edges[e].t < T.nleaves){          // if the edge connects to a leaf\n    b = stl[T.edges[e].t];                // state on the target leaf\n  } else {\n    b = sth[T.edges[e].t - T.nleaves];    // state on the target node\n  }\n}\n\n\n// Returns the root state\nlong rootstate(State &sth) {\n  return sth.s[0];\n}\n\nlong rootstate(std::vector<int> &sth) {\n  return sth[0];\n}\n\n\n// Let k be a parameter index (running over all free parameters on tm + root)\n// Every value of k describes a set of states compatible with it (see text).\n//   * if k corresponds to a transition matrix on edge e, parameter l, the compatible\n//     states are the ones with a state (a,b) on edge e, such that the free parameter\n//     on the entry (a,b) in the transition matrix is l.\n//   * if k corresponds to a root parameter, then the compatible states are the ones\n//     with root state matching that parameter.\n\n\n// The following functions fill three arrays of probabilities.\n\n// pleaf is a vector of joint probabilities on the leaves\nvoid fill_pleaf(Tree &T, StateList &sl, Parameters &Par, Array1 &pleaf) {\n  long i, j, l, u, v;\n  double p;\n\n  // Initializations\n  pleaf.resize(T.nstleaves);\n  for (i=0; i < T.nstleaves; i++) {\n    pleaf[i] = 0;\n  }\n\n  // Loop over all states\n  for (i=0; i < T.nstleaves; i++) {\n    for(j=0; j < T.nsthidden; j++) {\n\n      // Compute leaf probabilities\n      p = Par.r[rootstate(sl.h[j])];\n      for(l=0; l < T.nedges; l++) {\n        edgestate(T, l, sl.h[j], sl.l[i], u, v);\n        p = p*Par.tm[l][u][v];\n      }\n      pleaf[i] = pleaf[i] + p;\n    }\n  }\n}\n\n\n\n// pcond1 is a matrix of probabilities p(I and k), where \"I and k\" refers to states with\n// leaf state I and compatible with k.\n// rows in pcond1 are indexed by leaf states. Columns are indexed by a linear index encoding\n// a free parameter.\n\nvoid fill_pcond1(Tree &T, Model &Mod, StateList &sl, Parameters &Par, Array2 &pcond1) {\n\n  long i,j,l,u,v;\n  long k,e,a,b;\n  double p;\n  long npars = T.nedges*Mod.np + Mod.rdf + 1;\n\n  // Initializations\n  pcond1.resize(T.nstleaves);\n  for (i=0; i < T.nstleaves; i++) {\n    pcond1[i].resize(npars);\n    for(k=0; k < npars; k++) {\n      pcond1[i][k] = 0;\n    }\n  }\n\n  // Loop over all states\n  for (i=0; i < T.nstleaves; i++) {\n    for(j=0; j < T.nsthidden; j++) {\n\n      // Loop over edges\n      for(e=0; e < T.nedges; e++) {\n\n        // Compute cond1 probabilities\n        p = Par.r[rootstate(sl.h[j])];\n        for(l=0; l < T.nedges; l++) {\n          if (l == e) continue;\n          edgestate(T, l, sl.h[j], sl.l[i], u, v);\n          p = p*Par.tm[l][u][v];\n        }\n\n        edgestate(T, e, sl.h[j], sl.l[i], a, b);\n        k = erc2param(Mod, e, a, b);\n        pcond1[i][k] = pcond1[i][k] + p;\n      }\n\n      // Take care of root parameters in pcond1\n      p = 1;\n      for(l=0; l < T.nedges; l++) {\n        edgestate(T, l, sl.h[j], sl.l[i], u, v);\n        p = p*Par.tm[l][u][v];\n      }\n\n      k = root2param(T, Mod, rootstate(sl.h[j]));\n      pcond1[i][k] = pcond1[i][k] + p;\n    }\n  }\n}\n\n\n\n// pcond2 is a 3-dimensional array of probabilities p(I and k and kp) where \"I and k and kp\" refers\n// to states with leaf state I, and compatible with k and kp.\n\nvoid fill_pcond2(Tree &T, Model &Mod, StateList &sl, Parameters &Par, Array3 &pcond2) {\n  long i, j, l, u, v;\n  long k, e, a, b;\n  long kp, ep, ap, bp;\n  double p;\n\n  long npars = T.nedges*Mod.np + Mod.rdf + 1;\n\n  // Initializations\n  pcond2.resize(T.nstleaves);\n  for (i=0; i < T.nstleaves; i++) {\n    pcond2[i].resize(npars);\n    for(k=0; k < npars; k++) {\n      pcond2[i][k].resize(npars);\n      for(l=0; l < npars; l++) {\n        pcond2[i][k][l] = 0;\n      }\n    }\n  }\n\n  // Loop over all states\n  for (i=0; i < T.nstleaves; i++) {\n    for(j=0; j < T.nsthidden; j++) {\n\n      // Loop over pairs of edges for the edge-edge part of pcond2\n      for(e=0; e < T.nedges; e++) {\n        for(ep=0; ep < T.nedges; ep++) {\n\n          // when e==ep, the corresponding entry must be zero.\n          if (e==ep) continue;\n\n          // Compute cond2 probabilities\n          p = Par.r[rootstate(sl.h[j])];\n          for(l=0; l < T.nedges; l++) {\n            if (l == e || l == ep) continue;\n            edgestate(T, l, sl.h[j], sl.l[i], u, v);\n            p = p*Par.tm[l][u][v];\n          }\n\n          edgestate(T, e, sl.h[j], sl.l[i], a, b);\n          k = erc2param(Mod, e, a, b);\n\n          edgestate(T, ep, sl.h[j], sl.l[i], ap, bp);\n          kp = erc2param(Mod, ep, ap, bp);\n\n          pcond2[i][k][kp] = pcond2[i][k][kp] + p;\n        }\n      }\n\n      // Loop a single edge for the edge-root part of pcond2\n      for(e=0; e < T.nedges; e++) {\n        // Take care of root parameters in pcond1\n        p = 1;\n        for(l=0; l < T.nedges; l++) {\n          if (l == e) continue;\n          edgestate(T, l, sl.h[j], sl.l[i], u, v);\n          p = p*Par.tm[l][u][v];\n        }\n\n        edgestate(T, e, sl.h[j], sl.l[i], a, b);\n        k = erc2param(Mod, e, a, b);\n\n        kp = root2param(T, Mod, rootstate(sl.h[j]));\n\n        pcond2[i][k][kp] = pcond2[i][k][kp] + p;\n        pcond2[i][kp][k] = pcond2[i][kp][k] + p;\n      }\n\n      // Recall: In pcond2 with two root parameters k and kp,\n      // we always have p(I and k and kp) = 0.\n    }\n  }\n}\n\n\n// Puts the parameter values in a vector indexed as in the Fisher matrix for the model.\n// (4 parameters per edge on K81).\nvoid get_param_vector(Tree &T, Model &Mod, Parameters &Par, std::vector<double> &param) {\n  long e, a, b, k;\n  long npar = T.nedges * Mod.np + Mod.rdf + 1;\n  param.resize(npar);\n\n  for(e=0; e < T.nedges; e++) {\n    for(a=0; a < T.nalpha; a++) {\n      for(b=0; b < T.nalpha; b++) {\n        k = erc2param(Mod, e, a, b);\n        param[k] = Par.tm[e][a][b];\n      }\n    }\n  }\n\n  for(a=0; a < T.nalpha; a++) {\n    k = root2param(T, Mod, a);\n    param[k] = Par.r[a];\n  }\n}\n\n// Gets the free parameters for a branch\nvoid get_branch_free_param_vector(Tree &T, Model &Mod, Parameters &Par, long br, std::vector<double> &param) {\n  long a, b, k;\n  param.resize(Mod.df);\n\n  for(a=0; a < T.nalpha; a++) {\n    for(b=0; b < T.nalpha; b++) {\n      k = erc2freeparam(T, Mod, 0, a, b);\n      if(k < 0) continue;\n      param[k] = Par.tm[br][a][b];\n    }\n  }\n}\n\n\n// Puts the parameter values in a vector indexed as in the Fisher matrix for the free parameters.\n// (3 parameters per edge on K81).\nvoid get_free_param_vector(Tree &T, Model &Mod, Parameters &Par, std::vector<double> &param) {\n  long e, a, b, k;\n  long npar = T.nedges * Mod.df + Mod.rdf;\n  param.resize(npar);\n\n  for(e=0; e < T.nedges; e++) {\n    for(a=0; a < T.nalpha; a++) {\n      for(b=0; b < T.nalpha; b++) {\n        k = erc2freeparam(T, Mod, e, a, b);\n        if(k < 0) continue;\n        param[k] = Par.tm[e][a][b];\n      }\n    }\n  }\n\n  for(a=0; a < T.nalpha; a++) {\n    k = root2freeparam(T, Mod, a);\n    if(k < 0) continue;\n    param[k] = Par.r[a];\n  }\n}\n\n\n\n\n\n// Computes the observed Fisher information of all Parameters in Par, on the model with\n// hidden nodes and stores them in the matrix Imod ( no approximation, so the matrix is not diagonal).\n// The rows and columns of Imod are indexed by a number between 0 and np*nedges + rdf + 1, encoding the free parameters\n// of the model. The stochastic condition is not taken into account.\n\n// If data is not NULL, computes observed Fisher instead of expected Fisher.\n\n// The formula for the Fisher info of the model parameters (without stochastic constraints) is:\n// I(k, k') = sum_{leaf states I} N p(I and k)*p(I and k') / (p_k*p_k'*p(I))\n//                            - p(I and k and k') / (p_k*p_k')   <----- This term only when k!=k'\n// Here p_k denotes the value of the parameter k.\n\n// The observed Fisher info, is given by the same formula, but inside the sum must add the factor\n// x_I / N*p(I).\n\nvoid Fisher_information_model(Tree &T, Model &Mod, Parameters &Par, long N, Counts *data, Array2 &Imod) {\n  long i, j, k;\n\n  double factor;\n\n  std::vector<double> param;\n\n  Array1 pleaf;\n  Array2 pcond1;\n  Array3 pcond2;\n\n  StateList sl;\n\n  long npars = Mod.np*T.nedges + Mod.rdf + 1;\n\n  Array2 Ineg;\n  Ineg.resize(npars);\n  Imod.resize(npars);\n  for (i=0; i < npars; i++) {\n    Ineg[i].resize(npars);\n    Imod[i].resize(npars);\n    for(j=0; j < npars; j++) {\n      Ineg[i][j] = 0;\n      Imod[i][j] = 0;\n    }\n  }\n\n  if (data != NULL && data->nspecies != T.nleaves) {\n    throw std::length_error(\"ERROR: In Fisher_information_model. Counts don't match the tree.\");\n\n  }\n\n  sl = create_state_list(T);\n\n  // Fills stuff\n  fill_pleaf(T, sl, Par, pleaf);\n  fill_pcond1(T, Mod, sl, Par, pcond1);\n  fill_pcond2(T, Mod, sl, Par, pcond2);\n\n  get_param_vector(T, Mod, Par, param);\n\n  // Fills entries of Imod one by one.\n  for (i=0; i < npars; i++) {\n    for(j=0; j < npars; j++) {\n      for(k=0; k < T.nstleaves; k++) {\n        if (data == NULL) {    // Expected Fisher\n          factor = (double) N;\n        } else {               // Observed Fisher\n          factor = data->c[k] / pleaf[k];\n        }\n\n        Imod[i][j] = Imod[i][j] +\n          factor * pcond1[k][i] * pcond1[k][j] / pleaf[k];\n\n        Ineg[i][j] = Ineg[i][j] + factor * pcond2[k][i][j];\n      }\n\n      // We add up the negatives apart to minimize numerical errors.\n      Imod[i][j] = Imod[i][j] - Ineg[i][j];\n\n    }\n  }\n}\n\n\n\n// Takes The Fisher info matrix corresponding to a model Imod, and outputs a Fisher info matrix\n// for the free parameters. This means, taking into account the stochastic condition. What we do\n// is replace the diagonal parameter by \"1 - sum of other parameters\"\n// Imod has np*nedges + rdf + 1 rows and columns\n// Ifree has df*nedges + rdf rows and columns.\n\n// Here np means number of parameters, while df means degrees of freedom. For\n// example, K81 has np = 4 and df = 3. SSM has np = 8 and df = 6. The fact that SSM has two\n// stochastic constraints instead of one, means that SSM must be treated separately.\n\nvoid Fisher_information_free(Tree &T, Model &Mod, Array2 &Imod, Array2 &Ifree) {\n  long i, j, e, p, l;\n\n  long l1, l2;\n\n  long nfreepar = Mod.df*T.nedges + Mod.rdf;\n  long nmodpar = Mod.np*T.nedges + Mod.rdf + 1;\n\n  Ifree.resize(nfreepar);\n  for(i=0; i < nfreepar; i++) {\n    Ifree[i].resize(nfreepar);\n    for(j=0; j < nfreepar; j++) {\n      Ifree[i][j] = 0;\n    }\n  }\n\n  // Counts the number of times a parameter appears in the the transition matrices and root dist.\n  std::vector<double> coeff;\n  coeff.resize(nmodpar);\n  for(i=0; i < nmodpar; i++) {\n    coeff[i] = 0;\n  }\n\n  for(e=0; e < T.nedges; e++) {\n    for(i=0; i < T.nalpha; i++) {\n      for(j=0; j < T.nalpha; j++) {\n        p = erc2param(Mod, e, i, j);\n        coeff[p] = coeff[p] + 1;  // adds one to the corresponding parameter index.\n      }\n    }\n  }\n  for (i=0; i < T.nalpha; i++) {\n    p = root2param(T, Mod, i);\n    coeff[p] = coeff[p] + 1;\n  }\n\n  // translation between free parameters and model parameters.\n  std::vector<long> modpar;     // corresponding model parameter index\n  std::vector<long> modparkill; // corresponding model parameter which is killed.\n\n  modpar.resize(nfreepar);\n  modparkill.resize(nfreepar);\n\n  // Transition matrices\n  for(e=0; e < T.nedges; e++) {\n    for(i=0; i < T.nalpha; i++) {\n      for(j=0; j < T.nalpha; j++) {\n        l = erc2freeparam(T, Mod, e, i, j);\n        if (l < 0) continue;   // negative l means the parameter is killed.\n        modpar[l] = erc2param(Mod, e, i, j);\n        modparkill[l] = erc2param(Mod, e, i, i);\n      }\n    }\n  }\n\n  // Root\n  if (Mod.rdf > 0) {\n    for(i=0; i < T.nalpha; i++) {\n      l = root2freeparam(T, Mod, i);\n      if (l < 0) continue;   // negative l means the parameter is killed.\n      modpar[l] = root2param(T, Mod, i);\n      modparkill[l] = root2param(T, Mod, 0);\n    }\n  }\n\n  double c1, c2;\n  for(l1=0; l1 < nfreepar ; l1++) {\n    c1 = coeff[modpar[l1]]/coeff[modparkill[l1]];\n    for(l2=0; l2 < nfreepar; l2++) {\n      c2 = coeff[modpar[l2]]/coeff[modparkill[l2]];\n\n      Ifree[l1][l2] = Imod[modpar[l1]][modpar[l2]]\n           - c1 * Imod[modparkill[l1]][modpar[l2]]\n           - c2 * Imod[modpar[l1]][modparkill[l2]]\n           + c1*c2 * Imod[modparkill[l1]][modparkill[l2]];\n    }\n  }\n}\n\n\n// Computes the fisher information for the model with hidden nodes, and stores the result in I.\n// I is a matrix with df*nedges + rdf rows and cols.\n// the index for the rows and columns encodes a free parameter.\n// 0: first free param on edge 0\n// 1: second free param on edge 0\n// ...\n// df: first free param on edge 1\n// ...\n\nvoid Fisher_information(Tree &T, Model &Mod, Parameters &Par, long N, Array2 &I) {\n  Array2 Imod;\n\n  Fisher_information_model(T, Mod, Par, N, NULL, Imod);\n  Fisher_information_free(T, Mod, Imod, I);\n}\n\n\nvoid Observed_Fisher_information(Tree &T, Model &Mod, Parameters &Par, Counts &data, Array2 &I) {\n  Array2 Imod;\n\n  Fisher_information_model(T, Mod, Par, data.N, &data, Imod);\n  Fisher_information_free(T, Mod, Imod, I);\n}\n\n\n\n/* Matrix inversion routine.\n    Uses lu_factorize and lu_substitute in uBLAS to invert a matrix */\ntemplate<class T>\nbool matrix_inverse (const ublas::matrix<T>& input, ublas::matrix<T>& inverse) {\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> A(input);\n  // create a permutation matrix for the LU-factorization\n  pmatrix pm(A.size1());\n  // perform LU-factorization\n  int res = lu_factorize(A,pm);\n  if( res != 0 ) return false;\n  // create identity matrix of \"inverse\"\n  inverse.assign(ublas::identity_matrix<T>(A.size1()));\n  // backsubstitute to get the inverse\n  lu_substitute(A, pm, inverse);\n  return true;\n}\n\n\n// Computes the full covariance matrix for the MLE.\nvoid full_MLE_covariance_matrix(Tree &T, Model &Mod, Parameters &Par, long N, Array2 &Cov) {\n  long i, j;\n\n  long npars = Mod.df*T.nedges + Mod.rdf;\n  ublas::matrix<double> CC(npars, npars);\n  ublas::matrix<double> II(npars, npars);\n  Array2 I;\n\n  Fisher_information(T, Mod, Par, N, I);\n\n  // Need to convert from Matrix to ublas::matrix<double>\n  for(i=0; i < npars; i++) {\n    for(j=0; j < npars; j++) {\n      II(i, j) = I[i][j];\n    }\n  }\n\n  bool res = matrix_inverse(II, CC);\n  if (!res) {\n    throw std::out_of_range( \"Could not invert the Fisher information matrix.\" );\n  }\n\n  Cov.resize(npars);\n  for(i=0; i < npars; i++) {\n    Cov[i].resize(npars);\n    for(j=0; j < npars; j++) {\n      Cov[i][j] = CC(i,j);\n    }\n  }\n}\n\n\n// Computes the full covariance matrix for the MLE, using observed Fisher info.\nvoid full_MLE_observed_covariance_matrix(Tree &T, Model &Mod, Parameters &Par, Counts &data, Array2 &Cov) {\n  long i, j;\n\n  long npars = Mod.df*T.nedges + Mod.rdf;\n  ublas::matrix<double> CC(npars, npars);\n  ublas::matrix<double> II(npars, npars);\n  Array2 I;\n\n  Observed_Fisher_information(T, Mod, Par, data, I);\n\n  // Need to convert from Matrix to ublas::matrix<double>\n  for(i=0; i < npars; i++) {\n    for(j=0; j < npars; j++) {\n      II(i, j) = I[i][j];\n    }\n  }\n\n  bool res = matrix_inverse(II, CC);\n  if (!res) {\n    throw std::out_of_range(\"Could not invert the Fisher information matrix.\");\n  }\n\n  Cov.resize(npars);\n  for(i=0; i < npars; i++) {\n    Cov[i].resize(npars);\n    for(j=0; j < npars; j++) {\n      Cov[i][j] = CC(i,j);\n    }\n  }\n}\n\n\n\n// Extracts the covariance matrix for a given branch from the full covariance matrix.\nvoid branch_covariance_matrix(Model &Mod, Array2 &Covfull, long b, Array2 &Covbr) {\n  long i,j;\n\n  Covbr.resize(Mod.df);\n  for(i=0; i < Mod.df; i++) {\n    Covbr[i].resize(Mod.df);\n    for(j=0; j< Mod.df; j++) {\n      Covbr[i][j] = Covfull[Mod.df*b + i][Mod.df*b + j];\n    }\n  }\n}\n\n\n// Extracts the inverted covariance matrix for a given branch from the full covariance matrix.\nvoid branch_inverted_covariance_matrix(Model &Mod, Array2 &Covfull, long b, Array2 &Covbri) {\n  long i,j;\n\n  ublas::matrix<double> CC(Mod.df, Mod.df);\n  ublas::matrix<double> II(Mod.df, Mod.df);\n\n  for(i=0; i < Mod.df; i++) {\n    for(j=0; j< Mod.df; j++) {\n      CC(i,j) = Covfull[Mod.df*b + i][Mod.df*b + j];\n    }\n  }\n\n  bool res = matrix_inverse(CC, II);\n  if (!res) {\n    throw std::out_of_range( \"Could not invert the Covariance matrix.\" );\n  }\n\n  Covbri.resize(Mod.df);\n  for(i=0; i < Mod.df; i++) {\n    Covbri[i].resize(Mod.df);\n    for(j=0; j< Mod.df; j++) {\n      Covbri[i][j] = II(i,j);\n    }\n  }\n}\n", "meta": {"hexsha": "d02359f39b2082fc419344794d1578ce1c1a588e", "size": 19521, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/fisher.cpp", "max_stars_repo_name": "Algebraicphylogenetics/Empar", "max_stars_repo_head_hexsha": "1c2b4eec4ac0917c65786acf36de4b906d95715c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/fisher.cpp", "max_issues_repo_name": "Algebraicphylogenetics/Empar", "max_issues_repo_head_hexsha": "1c2b4eec4ac0917c65786acf36de4b906d95715c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/fisher.cpp", "max_forks_repo_name": "Algebraicphylogenetics/Empar", "max_forks_repo_head_hexsha": "1c2b4eec4ac0917c65786acf36de4b906d95715c", "max_forks_repo_licenses": ["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.3735465116, "max_line_length": 198, "alphanum_fraction": 0.5964346089, "num_tokens": 6203, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.47446708898390366}}
{"text": "// Copyright Louis Dionne 2013-2016\r\n// Distributed under the Boost Software License, Version 1.0.\r\n// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\r\n\r\n#include <boost/hana/div.hpp>\r\n#include <boost/hana/functional/reverse_partial.hpp>\r\nnamespace hana = boost::hana;\r\n\r\n\r\nconstexpr auto half = hana::reverse_partial(hana::div, 2);\r\nstatic_assert(half(4) == 2, \"\");\r\nstatic_assert(half(8) == 4, \"\");\r\n\r\nint main() { }\r\n", "meta": {"hexsha": "fafa1c40ea6bdd893a98b8720e0139a126a39680", "size": 451, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "thirdparty-cpp/boost_1_62_0/libs/hana/example/functional/reverse_partial.cpp", "max_stars_repo_name": "nxplatform/nx-mobile", "max_stars_repo_head_hexsha": "0dc174c893f2667377cb2ef7e5ffeb212fa8b3e5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-12-15T19:57:24.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-15T19:57:24.000Z", "max_issues_repo_path": "thirdparty-cpp/boost_1_62_0/libs/hana/example/functional/reverse_partial.cpp", "max_issues_repo_name": "nxplatform/nx-mobile", "max_issues_repo_head_hexsha": "0dc174c893f2667377cb2ef7e5ffeb212fa8b3e5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thirdparty-cpp/boost_1_62_0/libs/hana/example/functional/reverse_partial.cpp", "max_forks_repo_name": "nxplatform/nx-mobile", "max_forks_repo_head_hexsha": "0dc174c893f2667377cb2ef7e5ffeb212fa8b3e5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.0666666667, "max_line_length": 82, "alphanum_fraction": 0.6984478936, "num_tokens": 122, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.47446708898390366}}
{"text": "/*--------------------------------------------------------------------------\n \n File Name:         filter.cpp\n Date Created:      2017/08/07\n Date Modified:     2017/09/08\n \n Author:            Eric Cristofalo\n Contact:           eric.cristofalo@gmail.com\n \n Description:       ROS node for estimating realtime pose and odometry via EKF from Optitrack and Ouijibot IMU/wheel encoders\n \n -------------------------------------------------------------------------*/\n\n#include <iostream>\n#include <stdio.h>\n#include <math.h>\n#include <random>\n\n#include <ros/ros.h>\n#include <geometry_msgs/PoseStamped.h>\n// #include <geometry_msgs/Accel.h>\n#include <nav_msgs/Odometry.h>\n#include <sensor_msgs/Imu.h>\n#include <tf/transform_datatypes.h>\n#include <tf/transform_broadcaster.h>\n\n#include <ouijabot/Wheel_Spd.h>\n\n#include <Eigen/Dense>\n#include <Eigen/Core>\n#include <unsupported/Eigen/MatrixFunctions> // matrix exponential\n\nusing namespace std;\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\n\nclass filterClass {\n    \n  ros::NodeHandle nh_;\n  \n  ros::Subscriber process_imu_sub_;\n  ros::Subscriber process_wheel_speed_sub_;\n\n  ros::Subscriber ground_truth_sub_;\n  // ros::Subscriber ground_truth_accel_sub_;\n\n  ros::Publisher state_estimate_pub_;\n  tf::TransformBroadcaster state_estimate_broadcaster;\n  nav_msgs::Odometry stateEstimateMsg;\n  \n  // Initialalize Input Variables\n  int displayData, useOptitrack;\n  double r_w, r_b;\n  VectorXd q_cov_diag, r_cov_diag;\n\n  // Initialize Filter Variables\n  int initCount;\n  double count, initTime;\n  bool initPoseBool, predictBool, updateBool, gyroBool, wheelSpdBool;\n  ros::Time timeCur, timePrev;\n  VectorXd state, state_, state_gt, y, gyro, accel, wheel_spd;\n  MatrixXd Sigma, Sigma_, Q, R;\n  MatrixXd R_rl;\n    \npublic:\n  filterClass(int in_01, int in_02, double in_03, double in_04, vector<double> in_05, vector<double> in_06, vector<double> in_07) {\n\n    // Subscribe to Ouijibot IMU\n    process_imu_sub_ = nh_.subscribe(\"/ouijabot/imu\", 10, &filterClass::imuCallback, this);\n\n    // Subscribe to Ouijibot Wheel Encoders\n    process_wheel_speed_sub_ = nh_.subscribe(\"/ouijabot/wheel_spd\", 10, &filterClass::wheelSpeedCallback, this);\n\n    // Publish Odometry Message of State Estimate\n    state_estimate_pub_ = nh_.advertise<nav_msgs::Odometry>(\"/robot/state_estimate\", 10);\n\n    // Initialize Variables\n    displayData = in_01;\n    useOptitrack = in_02;\n    r_w = in_03;\n    r_b = in_04;\n    q_cov_diag = VectorXd::Zero(9);\n    for ( int i=0; i<9; i++ ) {\n      q_cov_diag(i) = in_05[i];\n    }\n    r_cov_diag = VectorXd::Zero(7);\n    for ( int i=0; i<7; i++ ) {\n      r_cov_diag(i) = in_06[i];\n    }\n    MatrixXd R_temp = MatrixXd::Zero(3,3);\n    for ( int i=0; i<3; i++ ) {\n      for ( int j=0; j<3; j++) {\n        R_temp(i,j) = in_07[i*3+j];\n      }\n    }\n    R_rl = MatrixXd(2,2);\n    R_rl = R_temp.block(0,0,2,2);\n\n    // Subscribe to Optitrack Ground Truth Topics\n    // Required mocap_interface_odom node to be publishing \"ground truth\" odometry data (position, derived velocity, and derived acceleration)\n    initPoseBool = false;\n    if ( useOptitrack ) {\n      initPoseBool = true; // Initialize the filter with current Optitrack measurement\n      ground_truth_sub_ = nh_.subscribe(\"/robot/pose\", 10, &filterClass::odomCallback, this);\n      // ground_truth_accel_sub_ = nh_.subscribe(\"/robot/accel\", 10, &filterClass::odomAccelCallback, this);\n    }\n\n    // Initialize Filter Variables\n    timeCur = ros::Time::now();\n    timePrev = ros::Time::now();\n    initCount = 0;\n    initTime = 0.0;\n    predictBool = false;\n    updateBool = false;\n    gyroBool = false;\n    wheelSpdBool = false;\n\n    // Initialize State Variables\n    count = 0;\n    state = VectorXd::Zero(9); // update: [x,y,theta,v_x,v_y,omega,a_x,a_y,a_omega]^T\n    state_ = VectorXd::Zero(9); // prediction: [x,y,theta,v_x,v_y,omega,a_x,a_y,a_omega]^T\n    state_gt = VectorXd::Zero(9); // ground truth: [x,y,theta,v_x,v_y,omega,a_x,a_y,a_omega]^T\n    y = VectorXd::Zero(7); // measurement: [w1, w2, w3, w4, w_gyro, a_x, a_y]^T\n    gyro = VectorXd::Zero(3); // gyro measurement\n    accel = VectorXd::Zero(3); // accelerometer measurement\n    wheel_spd = VectorXd::Zero(4); // wheel speed measurement\n    Q = q_cov_diag.asDiagonal(); // dynamics covariance matrix\n    R = r_cov_diag.asDiagonal(); // measurement covariance matrix\n    Sigma = 1E6*MatrixXd::Identity(9,9); // update: estimation error covariance matrix\n    Sigma_ = 1E6*MatrixXd::Identity(9,9); // update: estimation error covariance matrix\n\n    // double phiCur, theCur, psiCur;\n    // psiCur = M_PI/2.0;\n    // theCur = 0.0;\n    // phiCur = M_PI;\n    // MatrixXd R_phi = MatrixXd::Zero(3,3);\n    // MatrixXd R_the = MatrixXd::Zero(3,3);\n    // MatrixXd R_psi = MatrixXd::Zero(3,3);\n    // R_phi <<  1.0    ,   0.0         ,   0.0         ,\n    //           0.0    ,   cos(phiCur) ,   -sin(phiCur),\n    //           0.0    ,   sin(phiCur) ,   cos(phiCur) ;\n    // R_the <<  cos(theCur)    ,   0.0 ,   sin(theCur) ,\n    //           0.0            ,   1.0 ,   0.0         ,\n    //           -sin(theCur)   ,   0.0 ,   cos(theCur) ;\n    // R_psi <<  cos(psiCur)    ,   -sin(psiCur),   0.0,\n    //           sin(psiCur)    ,   cos(psiCur) ,   0.0,\n    //           0.0            ,   0.0         ,   1.0;\n    // // Quad Orientation\n    // MatrixXd R_test = MatrixXd::Zero(3,3);\n    // R_test = R_psi*R_the*R_phi;\n    // cout << \"ROTATION TEST:\" << endl << R_test;\n\n  }\n\n  void runFilter()\n  {\n    // Initialize Detection Timer\n    //std::clock_t start = std::clock();\n\n    // Time Interval\n    timeCur = ros::Time::now();\n    if ( count==0 ) {\n      timePrev = ros::Time::now();\n    }\n    double dt = (timeCur - timePrev).toSec();\n\n    // Prediction Step\n    // if ( predictBool ) {\n    // if ( predictBool && updateBool ) {\n    if ( updateBool ) {\n\n      // Define Property Matrices For Dynamics Matrices\n      MatrixXd Rwr = MatrixXd::Zero(2,2); // Active rotation watrix from world frame to local robot frame \n      Rwr <<  cos(state(2)), -sin(state(2)),\n              sin(state(2)),  cos(state(2));\n      MatrixXd Omega = MatrixXd::Zero(2,2);\n      Omega << 0.0, -state(5), state(5), 0.0;\n\n      // Construct Nonlinear Continuous-Time Dynamics Matrix\n      MatrixXd F_nl = MatrixXd::Zero(9,9);\n      F_nl.block(0,3,2,2) = Rwr.transpose();\n      F_nl(2,5) = 1.0;\n      F_nl.block(3,3,2,2) = Omega.transpose()*dt;\n      F_nl.block(3,6,3,3) = MatrixXd::Identity(3,3);\n      F_nl.block(6,6,2,2) = Omega.transpose()*dt;\n      // Discretize Dynamics Matrix\n      F_nl = F_nl.exp();\n      F_nl.block(0,3,3,3) = F_nl.block(0,3,3,3)*dt;\n      F_nl.block(0,6,3,3) = F_nl.block(0,6,3,3)*dt*dt;\n      F_nl.block(3,6,3,3) = F_nl.block(3,6,3,3)*dt;\n\n      // State Prediction\n      state_ = F_nl*state;\n\n      // Construct Linearized Continuous-Time Dynamics Matrix\n      MatrixXd F = MatrixXd::Zero(9,9);\n      F(0,2) = ( -sin(state(2))*state(3) - cos(state(2))*state(4) )*dt;\n      F(1,2) = (  cos(state(2))*state(3) - cos(state(2))*state(4) )*dt;\n      F.block(0,3,2,2) = Rwr.transpose();\n      F_nl(2,5) = 1.0;\n      F.block(3,3,2,2) = Omega.transpose()*dt;\n      F(3,5) = state(4)*dt;\n      F(4,5) = -state(3)*dt;\n      F.block(3,6,3,3) = MatrixXd::Identity(3,3);\n      F(6,5) = state(7)*dt;\n      F(7,5) = -state(6)*dt;\n      F.block(6,6,2,2) = Omega.transpose()*dt;\n      // Discretize Dynamics Matrix\n      F = F.exp();\n      F.block(0,3,3,3) = F.block(0,3,3,3)*dt;\n      F.block(0,6,3,3) = F.block(0,6,3,3)*dt*dt;\n      F.block(3,6,3,3) = F.block(3,6,3,3)*dt;\n\n      // EKF Covariance Prediction in Discrete Time\n      // MatrixXd Q_tilde = F*Q*F.transpose()*dt;\n      MatrixXd Q_tilde = Q;\n      Sigma_ = F*Sigma*F.transpose() + Q_tilde;\n\n      // End EKF Prediction\n      // predictBool = false; // TEMPORARY COMMENTED OUT\n      timePrev = timeCur;\n\n      if ( displayData ) {\n        cout << \"Prediction\" << endl;\n        cout << \"Time Interval: \" << endl << dt << endl;\n        // cout << \"Q: \" << endl << Q << endl;\n        // cout << \"Q_tilde: \" << endl << Q_tilde << endl;\n      }\n\n    }\n    else {\n      state_ = state;\n      Sigma_ = Sigma;\n    }\n\n    // Update Step\n    if ( updateBool ) {\n    // if ( predictBool && updateBool ) {\n\n      // Linear Measurement Matrix\n      MatrixXd H = MatrixXd::Zero(7,9);\n      double s = sqrt(2.0);\n      H(0,3) = -s/(2.0*r_w);  H(0,4) = -s/(2.0*r_w);  H(0,5) = r_b/r_w;\n      H(1,3) = -s/(2.0*r_w);  H(1,4) =  s/(2.0*r_w);  H(1,5) = r_b/r_w;\n      H(2,3) =  s/(2.0*r_w);  H(2,4) =  s/(2.0*r_w);  H(2,5) = r_b/r_w;\n      H(3,3) =  s/(2.0*r_w);  H(3,4) = -s/(2.0*r_w);  H(3,5) = r_b/r_w;\n      H.block(4,5,3,3) = MatrixXd::Identity(3,3);\n\n      // Kalman Gain in Discrete Time\n      // MatrixXd R_tilde = R/dt;\n      MatrixXd R_tilde = R;\n      MatrixXd S = (H*Sigma_*H.transpose() + R_tilde);\n      MatrixXd KalmanK = Sigma_*H.transpose()*S.inverse();  \n\n      // EKF State Update\n      state = state_ + KalmanK*(y - H*state_);\n\n      // EKF Covariance Update\n      Sigma = Sigma_ - KalmanK*H*Sigma_;\n      // cout << \"Sigma: \" << endl << Sigma(0,0) << endl << Sigma(3,3) << endl << \"-----------\" << endl;\n\n      // End EKF Update\n      updateBool = false;\n      // predictBool = false; // TEMPORARY HERE\n\n      if ( displayData ) {\n        cout << \"Update\" << endl;\n        // cout << \"R: \" << endl << R << endl;\n        // cout << \"R_tilde: \" << endl << R_tilde << endl;\n      }\n\n    }\n    else {\n      state = state_;\n      Sigma = Sigma_;\n    }\n\n    // Convert to Global Reference Frame\n    // Somewhat guessing on the transformations for the moment (see negative sign in gyro as well)\n    VectorXd state_output = VectorXd::Zero(9);\n    state_output.segment(0,2) = -R_rl*state.segment(0,2);\n    state_output(2) = state(2);\n    state_output.segment(3,2) = -R_rl*state.segment(3,2);\n    state_output(5) = state(5);\n    state_output.segment(6,2) = -R_rl*state.segment(6,2);\n    state_output(8) = state(8);\n\n    // Publish State Estimate Message\n    ros::Time pubTime = ros::Time::now();\n    // Publish Odometry Transform\n    geometry_msgs::Quaternion odom_quat = tf::createQuaternionMsgFromYaw(state_output(2));\n    geometry_msgs::TransformStamped odom_trans;\n    odom_trans.header.stamp = pubTime;\n    odom_trans.header.frame_id = \"/odom_frame_est\";\n    odom_trans.child_frame_id = \"/base_link_est\";\n    odom_trans.transform.translation.x = state_output(0);\n    odom_trans.transform.translation.y = state_output(1);\n    odom_trans.transform.translation.z = 0.0;\n    odom_trans.transform.rotation = odom_quat;\n    state_estimate_broadcaster.sendTransform(odom_trans);\n    // ros::Duration(0.5).sleep(); // sleep for half a second\n    // Set Final Pose\n    stateEstimateMsg.header.stamp = pubTime;\n    stateEstimateMsg.header.frame_id = \"/odom_frame_est\";\n    stateEstimateMsg.pose.pose.position.x = state_output(0);\n    stateEstimateMsg.pose.pose.position.y = state_output(1);\n    stateEstimateMsg.pose.pose.position.z = 0.0;\n    stateEstimateMsg.pose.pose.orientation = odom_quat;\n    // Set Final Pose Covariance\n    stateEstimateMsg.pose.covariance[0] = Sigma(0,0);\n    stateEstimateMsg.pose.covariance[1] = Sigma(1,1);\n    stateEstimateMsg.pose.covariance[2] = Sigma(2,2);\n    // Set Final Velocity\n    stateEstimateMsg.child_frame_id = \"/base_link_est\";\n    stateEstimateMsg.twist.twist.linear.x = state_output(3);\n    stateEstimateMsg.twist.twist.linear.y = state_output(4);\n    stateEstimateMsg.twist.twist.linear.z = 0.0;\n    stateEstimateMsg.twist.twist.angular.x = 0.0;\n    stateEstimateMsg.twist.twist.angular.y = 0.0;\n    stateEstimateMsg.twist.twist.angular.z = state_output(5);\n        // Set Final Velocity Covariance\n    stateEstimateMsg.twist.covariance[0] = Sigma(3,3);\n    stateEstimateMsg.twist.covariance[1] = Sigma(4,4);\n    stateEstimateMsg.twist.covariance[2] = Sigma(5,5);\n\n    // Publish Odometry Message\n    state_estimate_pub_.publish(stateEstimateMsg);\n\n    // Display Data in Terminal\n    if (displayData) {\n      cout << \"Prediction: \" << endl << state_ << endl;\n      // cout << \"Covariance: \" << endl << Sigma_(0,0) << endl << Sigma_(1,1) << endl << Sigma_(2,2) << endl << Sigma_(3,3) << endl << Sigma_(4,4) << endl << Sigma_(5,5) << endl;\n      cout << \"Update: \" << endl << state << endl;\n      // cout << \"Covariance: \" << endl << Sigma(0,0) << endl << Sigma(1,1) << endl << Sigma(2,2) << endl << Sigma(3,3) << endl << Sigma(4,4) << endl << Sigma(5,5) << endl;\n      // cout << \"------------------------------\" << endl;\n      // cout << \"Current Ground Truth: \" << endl << state_gt << endl;\n      // cout << \"Current Estimate: \" << endl << state << endl;\n      cout << \"Current Measurement: \" << endl << y << endl;\n      cout << \"------------------------------\" << endl;\n    }\n\n    // Update Filter Count\n    count++;\n  }\n\n  void readMeasurement()\n  {\n    if ( gyroBool && wheelSpdBool && !initPoseBool ) {\n      // Fill Measurement Vector\n      y.head(4) = wheel_spd;\n      y(4) = gyro(2);\n      y.tail(2) = accel.head(2);\n      // Reset Measurements\n      gyroBool = false;\n      wheelSpdBool = false;\n      // Run Filter Update\n      updateBool = true;\n      runFilter();\n    }\n  }\n\n  void imuCallback(const sensor_msgs::Imu& msg)\n  {\n    // Extract Data\n    // double qx, qy, qz, qw;\n    // qx = msg.orientation.x;\n    // qy = msg.orientation.y;\n    // qz = msg.orientation.z;\n    // qw = msg.orientation.w;\n    // Accelerometer is positioned with a rotation of pi about the z-axis!\n    accel(0) = -msg.linear_acceleration.x;\n    accel(1) = -msg.linear_acceleration.y;\n    accel(2) = msg.linear_acceleration.z;\n    // Filter Accelerometer Noise\n    if ( abs(accel(0)) < 0.25 ) accel(0) = 0;\n    if ( abs(accel(1)) < 0.25 ) accel(1) = 0;\n    if ( abs(accel(2)) < 0.25 ) accel(2) = 0;\n    // Convert to gyro measurement to radians/second\n    gyro(0) = msg.angular_velocity.x*M_PI/180.0;\n    gyro(1) = msg.angular_velocity.y*M_PI/180.0;\n    gyro(2) = -msg.angular_velocity.z*M_PI/180.0; // need negative sign here with negatives in final output\n    // Process EKF Measurement\n    gyroBool = true;\n    readMeasurement();\n  }\n\n  void wheelSpeedCallback(const ouijabot::Wheel_Spd& msg)\n  {\n    // Extract Data\n    // Convert from linear velocity to angular velocity (radians/second) with wheel radius\n    wheel_spd(0) = msg.wheel_spd[0]/r_w;\n    wheel_spd(1) = msg.wheel_spd[1]/r_w;\n    wheel_spd(2) = msg.wheel_spd[2]/r_w;\n    wheel_spd(3) = msg.wheel_spd[3]/r_w;\n    // Process EKF Measurement\n    wheelSpdBool = true;\n    readMeasurement();\n  }\n\n  void odomCallback(const geometry_msgs::PoseStamped& msg)\n  {\n    if ( useOptitrack ) {\n      // Extract Position\n      VectorXd state_temp = VectorXd::Zero(9);\n      state_temp(0) = msg.pose.position.x;  // x\n      state_temp(1) = msg.pose.position.y;  // x\n      double qx = msg.pose.orientation.x;\n      double qy = msg.pose.orientation.y;\n      double qz = msg.pose.orientation.z;\n      double qw = msg.pose.orientation.w;\n      double phiCur, theCur, psiCur;\n      tf::Quaternion q(qx, qy, qz, qw);\n      tf::Matrix3x3 m(q);\n      m.getRPY(phiCur, theCur, psiCur);\n      state_temp(2) = psiCur;               // theta\n      // // Extract Velocity\n      // state_temp(3) = msg.pose.orinetation.linear.x;   // v_x\n      // state_temp(4) = msg.pose.orinetation.linear.y;   // v_y\n      // state_temp(5) = msg.pose.orinetation.angular.z;  // omega\n      // Compute Initial Pose\n      if ( initPoseBool ) {\n        if ( initCount==0) {\n          timePrev = ros::Time::now();\n        }\n        timeCur = ros::Time::now();\n        double dt = (timeCur-timePrev).toSec();\n        initTime = initTime + dt;\n        if ( initTime<10.0 ) {\n          initCount++;\n          state = state + state_temp;\n        }\n        else {\n          // Average Poses\n          state = state/double(initCount);\n          // Convert to Local Robot Frame\n          // Somewhat guessing on the transformations for the moment (see negative sign in gyro as well)\n          VectorXd state_output = VectorXd::Zero(9,1);\n          state.segment(0,2) = -R_rl.transpose()*state.segment(0,2);\n          state(2) = state(2);\n          // Finish Up\n          timePrev = ros::Time::now();\n          initPoseBool = false;\n          predictBool = true;\n          cout << \"ouijabot_filter: initial mean pose after \" << double(initCount) << \" iterations and \" << initTime << \" seconds: \" << endl << state << endl;\n        }\n      }\n      else {\n        state_gt.head(6) = state_temp.head(6);\n      }\n    }\n  }\n\n  // void odomAccelCallback(const geometry_msgs::Accel& msg) {\n  //   if ( useOptitrack ) {\n  //     state_gt(6) = msg.linear.x;\n  //     state_gt(7) = msg.linear.y;\n  //     state_gt(8) = msg.angular.z;\n  //   }\n  // }\n\n};\n\nint main(int argc, char **argv)\n{\n  ros::init(argc, argv, \"filter\");\n  ros::NodeHandle nh(\"~\");\n  \n  int display_data_flag;\n  nh.param<int>(\"display_data_flag\", display_data_flag, 0);\n  int use_optitrack_flag;\n  nh.param<int>(\"use_optitrack_flag\", use_optitrack_flag, 0);\n\n  double wheel_radius;\n  nh.getParam( \"wheel_radius\", wheel_radius );\n  if (!nh.hasParam(\"wheel_radius\")) {\n    wheel_radius = 0.025;\n  }\n  double body_radius;\n  nh.getParam( \"body_radius\", body_radius );\n  if (!nh.hasParam(\"body_radius\")) {\n    body_radius = 0.1;\n  }\n\n  std::vector<double> q_cov_diag;\n  nh.getParam( \"q_cov_diag\", q_cov_diag );\n  if (!nh.hasParam(\"q_cov_diag\")) {\n    q_cov_diag = {0.0001, 0.0001, 0.0001, 0.001, 0.001, 0.001, 0.01, 0.01, 0.01};\n  }\n  std::vector<double> r_cov_diag;\n  nh.getParam( \"r_cov_diag\", r_cov_diag );\n  if (!nh.hasParam(\"r_cov_diag\")) {\n    r_cov_diag = {0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001};\n  }\n\n  std::vector<double> rotation_robot_local;\n  nh.getParam( \"rotation_robot_local\", rotation_robot_local );\n  if (!nh.hasParam(\"rotation_robot_local\")) {\n    rotation_robot_local = {0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, -1.0};\n  }\n\n  filterClass filter(\n    display_data_flag,\n    use_optitrack_flag,\n    wheel_radius,\n    body_radius,\n    q_cov_diag,\n    r_cov_diag,\n    rotation_robot_local\n  );\n\n  ros::Rate r(20); // 20 hz\n  while (ros::ok()) {\n    ros::spinOnce();\n    r.sleep();\n  }\n  ros::shutdown();\n  \n  return 0;\n}\n\n", "meta": {"hexsha": "84ba50b025ff01a9261901b276a3bed5f9cacfea", "size": 18158, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ouijabot_filter/src/filter.cpp", "max_stars_repo_name": "ashwinnalwade/ouijabot", "max_stars_repo_head_hexsha": "db5cb6f0c0fd3174ed8429f2cafd3697af10ca0e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-08-10T18:10:08.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-10T18:11:53.000Z", "max_issues_repo_path": "ouijabot_filter/src/filter.cpp", "max_issues_repo_name": "codingblazes/ouijabot", "max_issues_repo_head_hexsha": "db5cb6f0c0fd3174ed8429f2cafd3697af10ca0e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ouijabot_filter/src/filter.cpp", "max_forks_repo_name": "codingblazes/ouijabot", "max_forks_repo_head_hexsha": "db5cb6f0c0fd3174ed8429f2cafd3697af10ca0e", "max_forks_repo_licenses": ["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.8522072937, "max_line_length": 178, "alphanum_fraction": 0.5967617579, "num_tokens": 5631, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.47446708898390366}}
{"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 MFMG_DEALII_MATRIX_FREE_SMOOTHER_HPP\n#define MFMG_DEALII_MATRIX_FREE_SMOOTHER_HPP\n\n#include <mfmg/common/smoother.hpp>\n#include <mfmg/dealii/dealii_matrix_free_operator.hpp>\n\n#include <deal.II/lac/diagonal_matrix.h>\n#include <deal.II/lac/precondition.h>\n\n#include <boost/property_tree/ptree.hpp>\n\n#include <memory>\n\nnamespace mfmg\n{\ntemplate <int dim, typename VectorType>\nclass DealIIMatrixFreeSmoother final : public Smoother<VectorType>\n{\npublic:\n  using vector_type = VectorType;\n  using operator_type = DealIIMatrixFreeOperator<dim, VectorType>;\n  using preconditioner_type = dealii::DiagonalMatrix<VectorType>;\n  using chebyshev_preconditioner =\n      dealii::PreconditionChebyshev<operator_type, vector_type,\n                                    preconditioner_type>;\n\n  DealIIMatrixFreeSmoother(\n      std::shared_ptr<Operator<vector_type> const> op,\n      std::shared_ptr<boost::property_tree::ptree const> params);\n\n  virtual ~DealIIMatrixFreeSmoother() override = default;\n\n  void apply(vector_type const &b, vector_type &x) const override;\n\nprivate:\n  std::unique_ptr<chebyshev_preconditioner> _smoother;\n};\n} // namespace mfmg\n\n#endif\n", "meta": {"hexsha": "a8f61dbbeeaa96da348516572d64852d8bafcbf0", "size": 1916, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mfmg/dealii/dealii_matrix_free_smoother.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/dealii_matrix_free_smoother.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/dealii_matrix_free_smoother.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": 36.8461538462, "max_line_length": 75, "alphanum_fraction": 0.5730688935, "num_tokens": 391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056322076481139, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4744280504804674}}
{"text": "/***************************************************************************\n/* Javier Juan Albarracin - jajuaal1@ibime.upv.es                         */\n/* Universidad Politecnica de Valencia, Spain                             */\n/*                                                                        */\n/* Copyright (C) 2018 Javier Juan Albarracin                              */\n/*                                                                        */\n/***************************************************************************\n* CImg <-> MATLAB data type conversions                                    *\n***************************************************************************/\n\n#ifndef EIGENITK_HPP\n#define EIGENITK_HPP\n\n#include <stdexcept>\n#include <Eigen/Dense>\n#include <ITKUtils.hpp>\n#include <itkImage.h>\n#include <itkImageRegionConstIteratorWithIndex.h>\n\nusing namespace Eigen;\n\nclass EigenITK\n{\npublic:\n    template<typename ImageType, typename MaskType>\n    static Matrix<typename ImageType::PixelType, Dynamic, Dynamic> toEigen(const typename ImageType::Pointer image, const typename MaskType::Pointer mask);\n    template <typename ImageType, typename MaskType, typename Derived>\n    static typename ImageType::Pointer toITK(const DenseBase<Derived> &data, const typename MaskType::Pointer mask);\n    template <typename ImageType, typename MaskType, typename Derived>\n    static void toITK(const DenseBase<Derived> &data, const typename MaskType::Pointer mask, typename ImageType::Pointer image);\n};\n\ntemplate<typename ImageType, typename MaskType>\nMatrix<typename ImageType::PixelType, Dynamic, Dynamic> EigenITK::toEigen(const typename ImageType::Pointer image, const typename MaskType::Pointer mask)\n{\n    ITKUtils::AssertCompatibleImageAndMaskTypes<ImageType, MaskType>();\n    ITKUtils::AssertCompatibleImageAndMaskSizes<ImageType, MaskType>(image, mask);\n\n    const unsigned int ImageDimension = ImageType::ImageDimension;\n    const unsigned int MaskDimension = MaskType::ImageDimension;\n    const unsigned int ChannelsDimensionIndex = ImageDimension - 1;\n\n    typename ImageType::SizeType imageSize = image->GetLargestPossibleRegion().GetSize();\n\n    int rows = 1;\n    int cols = ImageDimension == MaskDimension ? 1 : imageSize[ChannelsDimensionIndex];\n    for (int j = 0; j < ChannelsDimensionIndex; ++j)\n    {\n        rows *= imageSize[j];\n    }\n    \n    Matrix<typename ImageType::PixelType, Dynamic, Dynamic> data(rows, cols);\n    \n    itk::ImageRegionConstIteratorWithIndex<MaskType> iterator(mask, mask->GetLargestPossibleRegion());\n    int i = 0;\n    iterator.GoToBegin();\n    while(!iterator.IsAtEnd())\n    {\n        if (iterator.Get())\n        {\n            itk::Index<MaskDimension> maskIndex = iterator.GetIndex();\n            itk::Index<ImageDimension> imageIndex = ITKUtils::GetSpatialIndex<MaskDimension, ImageDimension>(maskIndex);\n\n            if (ImageDimension == MaskDimension)\n                data(i, 0) = image->GetPixel(imageIndex);\n            else\n            {\n                for (int j = 0; j < imageSize[ChannelsDimensionIndex]; ++j)\n                {\n                    imageIndex[ChannelsDimensionIndex] = j;\n                    data(i, j) = image->GetPixel(imageIndex);\n                    \n                }\n            }\n            ++i;\n        }\n        ++iterator;\n    }\n    data.conservativeResize(i, data.cols());\n    return data;\n}\n\ntemplate <typename ImageType, typename MaskType, typename Derived>\ntypename ImageType::Pointer EigenITK::toITK(const DenseBase<Derived> &data, const typename MaskType::Pointer mask)\n{\n    ITKUtils::AssertCompatibleImageAndMaskTypes<ImageType, MaskType>();\n\n    typename ImageType::Pointer image = ImageType::New();\n    ITKUtils::AllocateRegionFromInput<ImageType, MaskType>(image, mask, data.cols());\n    EigenITK::toITK<ImageType, MaskType, Derived>(data, mask, image);\n\n    return image;\n}\n\ntemplate <typename ImageType, typename MaskType, typename Derived>\nvoid EigenITK::toITK(const DenseBase<Derived> &data, const typename MaskType::Pointer mask, typename ImageType::Pointer image)\n{\n    ITKUtils::AssertCompatibleImageAndMaskTypes<ImageType, MaskType>();\n    ITKUtils::AssertCompatibleImageAndMaskSizes<ImageType, MaskType>(image, mask);\n\n    const unsigned int ImageDimension = ImageType::ImageDimension;\n    const unsigned int MaskDimension = MaskType::ImageDimension;\n    const unsigned int ChannelsDimensionIndex = ImageDimension - 1;\n\n    itk::ImageRegionConstIterator<MaskType> it(mask, mask->GetLargestPossibleRegion());\n    it.GoToBegin();\n    int count = 0;\n    while (!it.IsAtEnd())\n    {\n        if (it.Get())\n            ++count;\n        ++it;\n    }\n    \n    if (count != data.rows())\n    {\n        std::stringstream s;\n        s << \"Incompatible number of rows and positive elements in the mask\" << std::endl;\n        throw std::runtime_error(s.str());\n    }\n\n    typename ImageType::SizeType imageSize = image->GetLargestPossibleRegion().GetSize();;\n\n    itk::ImageRegionConstIteratorWithIndex<MaskType> iterator(mask, mask->GetLargestPossibleRegion());\n    int i = 0;\n    iterator.GoToBegin();\n    while (!iterator.IsAtEnd())\n    {\n        itk::Index<MaskDimension> maskIndex = iterator.GetIndex();\n        itk::Index<ImageDimension> imageIndex = ITKUtils::GetSpatialIndex<MaskDimension, ImageDimension>(maskIndex);\n\n        if (ImageDimension == MaskDimension)\n            image->SetPixel(imageIndex, (typename ImageType::PixelType) iterator.Get() ? data(i, 0) : 0);\n        else\n        {\n            for (int j = 0; j < imageSize[ChannelsDimensionIndex]; j++)\n            {\n                imageIndex[ChannelsDimensionIndex] = j;\n                image->SetPixel(imageIndex, (typename ImageType::PixelType) iterator.Get() ? data(i, j) : 0);\n            }    \n        }\n        i += iterator.Get() ? 1 : 0;\n        ++iterator;\n    }\n}\n\n#endif", "meta": {"hexsha": "e5af76d95c2d7a32ddc6518e987a1650b9f98129", "size": 5869, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "EigenITK.hpp", "max_stars_repo_name": "javierjuan/tools", "max_stars_repo_head_hexsha": "fd51855d3babccabc2cf95e9d7ac00c0a390f7fc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "EigenITK.hpp", "max_issues_repo_name": "javierjuan/tools", "max_issues_repo_head_hexsha": "fd51855d3babccabc2cf95e9d7ac00c0a390f7fc", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "EigenITK.hpp", "max_forks_repo_name": "javierjuan/tools", "max_forks_repo_head_hexsha": "fd51855d3babccabc2cf95e9d7ac00c0a390f7fc", "max_forks_repo_licenses": ["Apache-2.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.925170068, "max_line_length": 155, "alphanum_fraction": 0.6190151644, "num_tokens": 1276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146849, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.47442804498411245}}
{"text": "#pragma once\n\n#include <polyfem/Common.hpp>\n#include <polyfem/NLProblem.hpp>\n#include <polyfem/MatrixUtils.hpp>\n#include <polyfem/State.hpp>\n\n#include <polyfem/Logger.hpp>\n\n#include <cppoptlib/problem.h>\n#include <cppoptlib/solver/isolver.h>\n#include <cppoptlib/linesearch/armijo.h>\n#include <cppoptlib/linesearch/morethuente.h>\n#include <Eigen/LU>\n#include <iostream>\n\nnamespace cppoptlib\n{\n\n\ttemplate <typename ProblemType>\n\tclass LbfgsSolverL2 : public ISolver<ProblemType, 1>\n\t{\n\tpublic:\n\t\tusing Superclass = ISolver<ProblemType, 1>;\n\t\tusing typename Superclass::Scalar;\n\t\tusing typename Superclass::THessian;\n\t\tusing typename Superclass::TVector;\n\t\tusing MatrixType = Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>;\n\n\t\tenum class LineSearch\n\t\t{\n\t\t\tArmijo,\n\t\t\tMoreThuente,\n\t\t};\n\n\t\tLineSearch line_search = LineSearch::Armijo;\n\n\t\tvoid setLineSearch(const std::string &name)\n\t\t{\n\t\t\tif (name == \"armijo\")\n\t\t\t{\n\t\t\t\tline_search = LineSearch::Armijo;\n\t\t\t}\n\t\t\telse if (name == \"more_thuente\")\n\t\t\t{\n\t\t\t\tline_search = LineSearch::MoreThuente;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tthrow std::invalid_argument(\"[SparseNewtonDescentSolver] Unknown line search.\");\n\t\t\t}\n\t\t\tpolyfem::logger().debug(\"\\tline search {}\", name);\n\t\t}\n\n\t\tvoid minimize(ProblemType &objFunc, TVector &x0)\n\t\t{\n\t\t\tconst size_t m = 10;\n\t\t\tconst size_t DIM = x0.rows();\n\t\t\tMatrixType sVector = MatrixType::Zero(DIM, m);\n\t\t\tMatrixType yVector = MatrixType::Zero(DIM, m);\n\t\t\tEigen::Matrix<Scalar, Eigen::Dynamic, 1> alpha = Eigen::Matrix<Scalar, Eigen::Dynamic, 1>::Zero(m);\n\t\t\tTVector grad(DIM), q(DIM), grad_old(DIM), s(DIM), y(DIM);\n\t\t\tobjFunc.gradient(x0, grad);\n\t\t\tTVector x_old = x0;\n\t\t\tTVector x_old2 = x0;\n\n\t\t\tsize_t iter = 0, globIter = 0;\n\t\t\tScalar H0k = 1;\n\t\t\tthis->m_current.reset();\n\t\t\tdo\n\t\t\t{\n\t\t\t\tconst Scalar relativeEpsilon = static_cast<Scalar>(0.0001) * std::max(static_cast<Scalar>(1.0), x0.norm());\n\n\t\t\t\tif (grad.norm() < relativeEpsilon)\n\t\t\t\t\tbreak;\n\n\t\t\t\t//Algorithm 7.4 (L-BFGS two-loop recursion)\n\t\t\t\tq = grad;\n\t\t\t\tconst int k = std::min(m, iter);\n\n\t\t\t\t// for i = k \u2212 1, k \u2212 2, . . . , k \u2212 m\u00a7\n\t\t\t\tfor (int i = k - 1; i >= 0; i--)\n\t\t\t\t{\n\t\t\t\t\t// alpha_i <- rho_i*s_i^T*q\n\t\t\t\t\tconst double rho = 1.0 / static_cast<TVector>(sVector.col(i))\n\t\t\t\t\t\t\t\t\t\t\t\t .dot(static_cast<TVector>(yVector.col(i)));\n\t\t\t\t\talpha(i) = rho * static_cast<TVector>(sVector.col(i)).dot(q);\n\t\t\t\t\t// q <- q - alpha_i*y_i\n\t\t\t\t\tq = q - alpha(i) * yVector.col(i);\n\t\t\t\t}\n\t\t\t\t// r <- H_k^0*q\n\t\t\t\tq = H0k * q;\n\t\t\t\t//for i k \u2212 m, k \u2212 m + 1, . . . , k \u2212 1\n\t\t\t\tfor (int i = 0; i < k; i++)\n\t\t\t\t{\n\t\t\t\t\t// beta <- rho_i * y_i^T * r\n\t\t\t\t\tconst Scalar rho = 1.0 / static_cast<TVector>(sVector.col(i))\n\t\t\t\t\t\t\t\t\t\t\t\t .dot(static_cast<TVector>(yVector.col(i)));\n\t\t\t\t\tconst Scalar beta = rho * static_cast<TVector>(yVector.col(i)).dot(q);\n\t\t\t\t\t// r <- r + s_i * ( alpha_i - beta)\n\t\t\t\t\tq = q + sVector.col(i) * (alpha(i) - beta);\n\t\t\t\t}\n\t\t\t\t// stop with result \"H_k*f_f'=q\"\n\n\t\t\t\t// any issues with the descent direction ?\n\t\t\t\tScalar descent = -grad.dot(q);\n\t\t\t\tScalar alpha_init = 1.0 / grad.norm();\n\t\t\t\tif (descent > -0.0001 * relativeEpsilon)\n\t\t\t\t{\n\t\t\t\t\tq = -1 * grad;\n\t\t\t\t\titer = 0;\n\t\t\t\t\talpha_init = 1.0;\n\t\t\t\t}\n\n\t\t\t\t// find steplength\n\t\t\t\t// const Scalar rate = MoreThuente<ProblemType, 1>::linesearch(x0, -q,  objFunc, alpha_init) ;\n\t\t\t\tScalar rate;\n\t\t\t\tswitch (line_search)\n\t\t\t\t{\n\t\t\t\tcase LineSearch::Armijo:\n\t\t\t\t\trate = Armijo<ProblemType, 1>::linesearch(x0, -q, objFunc);\n\t\t\t\t\tbreak;\n\t\t\t\tcase LineSearch::MoreThuente:\n\t\t\t\t\trate = MoreThuente<ProblemType, 1>::linesearch(x0, -q, objFunc);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t// update guess\n\t\t\t\tx0 = x0 - rate * q;\n\n\t\t\t\tgrad_old = grad;\n\t\t\t\tobjFunc.gradient(x0, grad);\n\n\t\t\t\ts = x0 - x_old;\n\t\t\t\ty = grad - grad_old;\n\n\t\t\t\t// update the history\n\t\t\t\tif (iter < m)\n\t\t\t\t{\n\t\t\t\t\tsVector.col(iter) = s;\n\t\t\t\t\tyVector.col(iter) = y;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\n\t\t\t\t\tsVector.leftCols(m - 1) = sVector.rightCols(m - 1).eval();\n\t\t\t\t\tsVector.rightCols(1) = s;\n\t\t\t\t\tyVector.leftCols(m - 1) = yVector.rightCols(m - 1).eval();\n\t\t\t\t\tyVector.rightCols(1) = y;\n\t\t\t\t}\n\t\t\t\t// update the scaling factor\n\t\t\t\tH0k = y.dot(s) / static_cast<double>(y.dot(y));\n\n\t\t\t\tx_old = x0;\n\t\t\t\tpolyfem::logger().debug(\"\\titer: {}, f = {}, \u2016g\u2016_2 = {}\", globIter, objFunc.value(x0), grad.norm());\n\n\t\t\t\titer++;\n\t\t\t\tglobIter++;\n\t\t\t\t++this->m_current.iterations;\n\t\t\t\tthis->m_current.gradNorm = grad.norm(); // template lpNorm<Eigen::Infinity>();\n\t\t\t\tthis->m_status = checkConvergence(this->m_stop, this->m_current);\n\t\t\t} while ((objFunc.callback(this->m_current, x0)) && (this->m_status == Status::Continue));\n\t\t}\n\t};\n\n} // namespace cppoptlib\n", "meta": {"hexsha": "a872fed31f29c0675595e5edca13bfb417051b0f", "size": 4556, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/solver/LbfgsSolver.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/solver/LbfgsSolver.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/solver/LbfgsSolver.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": 27.4457831325, "max_line_length": 111, "alphanum_fraction": 0.6079894644, "num_tokens": 1479, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4744280394877572}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2015 NumScale SAS\n  @copyright 2015 J.T.Lapreste\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_COMMON_DETAIL_SCALAR_F_LOG_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_DETAIL_SCALAR_F_LOG_HPP_INCLUDED\n\n#ifndef BOOST_SIMD_NO_NANS\n#include <boost/simd/function/scalar/is_nan.hpp>\n#endif\n#ifndef BOOST_SIMD_NO_INFINITIES\n#include <boost/simd/constant/inf.hpp>\n#endif\n#ifndef BOOST_SIMD_NO_DENORMALS\n#include <boost/simd/constant/mlog10two2nmb.hpp>\n#include <boost/simd/constant/mlog2two2nmb.hpp>\n#include <boost/simd/constant/mlogtwo2nmb.hpp>\n#include <boost/simd/constant/smallestposval.hpp>\n#include <boost/simd/constant/twotonmb.hpp>\n#include <boost/simd/function/scalar/abs.hpp>\n#endif\n#include <boost/simd/arch/common/detail/generic/f_log_kernel.hpp>\n#include <boost/simd/arch/common/detail/tags.hpp>\n#include <boost/simd/constant/log10_2hi.hpp>\n#include <boost/simd/constant/log10_2lo.hpp>\n#include <boost/simd/constant/log10_ehi.hpp>\n#include <boost/simd/constant/log10_elo.hpp>\n#include <boost/simd/constant/log2_em1.hpp>\n#include <boost/simd/constant/log_2hi.hpp>\n#include <boost/simd/constant/log_2lo.hpp>\n#include <boost/simd/constant/mhalf.hpp>\n#include <boost/simd/constant/minf.hpp>\n#include <boost/simd/constant/nan.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/function/scalar/fma.hpp>\n#include <boost/simd/function/scalar/is_eqz.hpp>\n#include <boost/simd/function/scalar/is_ltz.hpp>\n#include <boost/dispatch/meta/as_integer.hpp>\n#include <boost/dispatch/meta/scalar_of.hpp>\n\nnamespace boost { namespace simd\n{\n  namespace detail\n  {\n    namespace bd = boost::dispatch;\n    template < class A0,\n               class Style ,\n               class base_A0 = bd::scalar_of_t<A0>\n               >\n               struct logarithm{};\n\n    template < class A0 >\n    struct logarithm< A0, tag::not_simd_type, float>\n    {\n      using kernel_t = kernel<A0, tag::not_simd_type, float>;\n\n      static BOOST_FORCEINLINE A0 log(A0 const& a0) BOOST_NOEXCEPT\n      {\n      #ifndef BOOST_SIMD_NO_INFINITIES\n        if (BOOST_UNLIKELY(a0 == Inf<A0>())) return a0;\n      #endif\n      #ifdef BOOST_SIMD_NO_NANS\n        if (BOOST_UNLIKELY(is_ltz(a0))) return Nan<A0>();\n      #else\n        if (BOOST_UNLIKELY(is_nan(a0)||is_ltz(a0))) return Nan<A0>();\n      #endif\n        if (BOOST_UNLIKELY(is_eqz(a0))) return Minf<A0>();\n        A0 z = a0;\n      #ifndef BOOST_SIMD_NO_DENORMALS\n        A0 t = Zero<A0>();\n        if(BOOST_UNLIKELY(abs(z) < Smallestposval<A0>()))\n        {\n          z *= Twotonmb<A0>();\n          t = Mlogtwo2nmb<A0>();\n        }\n      #endif\n        A0 x, fe, x2, y;\n        kernel_t::log(z, fe, x, x2, y);\n        y = fma(fe, Log_2lo<A0>(), y);\n        y = fma(Mhalf<A0>(), x2, y);\n      #ifdef BOOST_SIMD_NO_DENORMALS\n        return fma(Log_2hi<A0>(), fe, x+y);\n      #else\n        return fma(Log_2hi<A0>(), fe, x+y+t);\n      #endif\n      }\n\n      static BOOST_FORCEINLINE  A0 log2(A0 const& a0) BOOST_NOEXCEPT\n      {\n#ifndef BOOST_SIMD_NO_INFINITIES\n        if (BOOST_UNLIKELY(a0 == Inf<A0>())) return a0;\n#endif\n#ifdef BOOST_SIMD_NO_NANS\n        if (BOOST_UNLIKELY(is_ltz(a0))) return Nan<A0>();\n#else\n        if (BOOST_UNLIKELY(is_nan(a0)||is_ltz(a0))) return Nan<A0>();\n#endif\n        if (BOOST_UNLIKELY(is_eqz(a0))) return Minf<A0>();\n        A0 z = a0;\n#ifndef BOOST_SIMD_NO_DENORMALS\n        A0 t = Zero<A0>();\n        if (BOOST_UNLIKELY(abs(z) < Smallestposval<A0>()))\n        {\n          z *= Twotonmb<A0>();\n          t = Mlog2two2nmb<A0>();\n        }\n#endif\n        A0 x, fe, x2, y;\n        kernel_t::log(z, fe, x, x2, y);\n        y = fma(Mhalf<A0>(),x2, y);\n        z = fma(x,Log2_em1<A0>(),y*Log2_em1<A0>());\n#ifdef BOOST_SIMD_NO_DENORMALS\n        return ((z+y)+x)+fe;\n#else\n        return ((z+y)+x)+fe+t;\n#endif\n      }\n\n      static BOOST_FORCEINLINE  A0 log10(A0 const& a0) BOOST_NOEXCEPT\n      {\n#ifndef BOOST_SIMD_NO_INFINITIES\n        if (BOOST_UNLIKELY(a0 == Inf<A0>())) return a0;\n#endif\n#ifdef BOOST_SIMD_NO_NANS\n        if (BOOST_UNLIKELY(is_ltz(a0))) return Nan<A0>();\n#else\n        if (BOOST_UNLIKELY(is_nan(a0)||is_ltz(a0))) return Nan<A0>();\n#endif\n        if (BOOST_UNLIKELY(is_eqz(a0))) return Minf<A0>();\n        A0 z = a0;\n#ifndef BOOST_SIMD_NO_DENORMALS\n        A0 t = Zero<A0>();\n        if (BOOST_UNLIKELY(abs(z) < Smallestposval<A0>()))\n        {\n          z *= Twotonmb<A0>();\n          t = Mlog10two2nmb<A0>();\n        }\n#endif\n        A0 x, fe, x2, y;\n        kernel_t::log(z, fe, x, x2, y);\n\n        y = fma(Mhalf<A0>(), x2, y);\n        z = (x+y)*Log10_elo<A0>();\n        z = fma( y, Log10_ehi<A0>(), z);\n        z = fma(Log10_ehi<A0>(), y,  z);\n        z = fma(Log10_2hi<A0>(), fe, z);\n#ifdef BOOST_SIMD_NO_DENORMALS\n        return fma(Log10_2lo<A0>(), fe, z);\n#else\n        return fma(Log10_2lo<A0>(),fe, z+t);\n#endif\n      }\n    };\n  }\n} }\n#endif\n", "meta": {"hexsha": "79b2e91fc88b8765d381f517cd9260a767387be8", "size": 5175, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arch/common/detail/scalar/f_log.hpp", "max_stars_repo_name": "yaeldarmon/boost.simd", "max_stars_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/simd/arch/common/detail/scalar/f_log.hpp", "max_issues_repo_name": "yaeldarmon/boost.simd", "max_issues_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/arch/common/detail/scalar/f_log.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": 31.5548780488, "max_line_length": 100, "alphanum_fraction": 0.6065700483, "num_tokens": 1529, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4744280394877572}}
{"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_LOG2_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_LOG2_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n    @ingroup group-exponential\n    This function object returns the base two logarithm of its argument.\n\n    @par Header <boost/simd/function/log2.hpp>\n\n    @par Decorators\n\n      - std_ for floating entries calls @c std::log2\n\n    @see log10, log, log1p\n\n    @par Example:\n\n      @snippet log2.cpp log2\n\n    @par Possible output:\n\n      @snippet log2.txt log2\n\n  **/\n  IEEEValue log2(IEEEValue const& x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/log2.hpp>\n#include <boost/simd/function/simd/log2.hpp>\n\n#endif\n", "meta": {"hexsha": "4a5acb462c0c9505633276638de96e71e3ad4d5c", "size": 1073, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/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/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/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": 22.829787234, "max_line_length": 100, "alphanum_fraction": 0.5796831314, "num_tokens": 234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478255, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4744280339914018}}
{"text": "#include <Configuration.h> // Package Path\n#include <avatar_locomanipulation/enable_pinocchio_with_hpp_fcl.h> // Enable HPP FCL\n// Multibody\n#include \"pinocchio/multibody/model.hpp\"\n#include \"pinocchio/multibody/data.hpp\"\n#include \"pinocchio/multibody/geometry.hpp\"\n// Parsers\n#include \"pinocchio/parsers/urdf.hpp\"\n#include \"pinocchio/parsers/srdf.hpp\"\n// Algorithms\n#include \"pinocchio/algorithm/geometry.hpp\"\n#include \"pinocchio/algorithm/kinematics.hpp\"\n// Standard\n#include <math.h> \n#include <iostream>\n#include <iomanip>\n#include <vector>\n#include <boost/shared_ptr.hpp>\n\npinocchio::fcl::Quaternion3f makeQuat(double w, double x, double y, double z){\n  pinocchio::fcl::Quaternion3f q;\n  q.w() = w;\n  q.x() = x;\n  q.y() = y;\n  q.z() = z;\n  return q;\n}\n\nint main(int argc, char ** argv){\n\n  pinocchio::Model model;\n  pinocchio::GeometryModel geomModel;\n\n  pinocchio::Data data(model);\n  pinocchio::GeometryData geomData(geomModel);\n  pinocchio::fcl::DistanceResult result;\n\n  //boost::shared_ptr <pinocchio::fcl::CollisionGeometry> CollisionGeometryPtr_t;\n\n  // create two boxes \n  boost::shared_ptr <pinocchio::fcl::CollisionGeometry> s1 (new hpp::fcl::Box (1, 1, 1));\n  boost::shared_ptr <pinocchio::fcl::CollisionGeometry> s2 (new hpp::fcl::Box (1, 1, 1));\n  static double pi = M_PI;\n  // give the boxes defined transforms\n  pinocchio::fcl::Transform3f tf1 (makeQuat (cos (pi/8), 0, 0, sin (pi/8)), pinocchio::fcl::Vec3f (-2, 1, .5));\n  pinocchio::fcl::Transform3f tf2 (makeQuat (cos (pi/8), 0, sin(pi/8),0), pinocchio::fcl::Vec3f (2, .5, .5));\n\n  //pinocchio::fcl::CollisionObject;\n  pinocchio::fcl::CollisionObject o1 (s1, tf1);\n  pinocchio::fcl::CollisionObject o2 (s2, tf2);\n\n  // Enable computation of nearest points\n  pinocchio::fcl::DistanceRequest distanceRequest (true, 0, 0, pinocchio::fcl::GST_INDEP);\n  pinocchio::fcl::DistanceResult distanceResult;\n\n  pinocchio::fcl::distance (&o1, &o2, distanceRequest, distanceResult);\n\n  const pinocchio::fcl::Vec3f& p1 = distanceResult.nearest_points [0];\n  const pinocchio::fcl::Vec3f& p2 = distanceResult.nearest_points [1];\n\n\n  std::cout << \"Applied transformations on two boxes\" << std::endl;\n  std::cout << \" Translation1 = \" << tf1.getTranslation() << std::endl\n\t    << \" Rotation1 = \" << tf1.getRotation () << std::endl\n\t    << \" Translation2 = \" << tf2.getTranslation() << std::endl\n\t    << \" Rotation2 = \" << tf2.getRotation () << std::endl;\n  std::cout << \"Closest points(nearest_points): p1 = \" << distanceResult.nearest_points [0]\n\t    << \", p2 = \" << distanceResult.nearest_points [1]\n        << \", distance(min_distance) = \" << distanceResult.min_distance << std::endl;\n\n}", "meta": {"hexsha": "96e07b9ab5aa747cb1418f4816b332fc6de69915", "size": 2644, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/collision_test_files/test_boxbox_computeDistance.cpp", "max_stars_repo_name": "stevenjj/icra2020locomanipulation", "max_stars_repo_head_hexsha": "414085b68cc1b3b24f7b920b543bba9d95350c16", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-01-06T11:43:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-14T22:59:09.000Z", "max_issues_repo_path": "test/collision_test_files/test_boxbox_computeDistance.cpp", "max_issues_repo_name": "stevenjj/icra2020locomanipulation", "max_issues_repo_head_hexsha": "414085b68cc1b3b24f7b920b543bba9d95350c16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/collision_test_files/test_boxbox_computeDistance.cpp", "max_forks_repo_name": "stevenjj/icra2020locomanipulation", "max_forks_repo_head_hexsha": "414085b68cc1b3b24f7b920b543bba9d95350c16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-09-03T16:08:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T11:13:49.000Z", "avg_line_length": 37.2394366197, "max_line_length": 111, "alphanum_fraction": 0.6936459909, "num_tokens": 843, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478254, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.47442803399140177}}
{"text": "#pragma once\n#include <boost/geometry.hpp>\n\n#include \"math.hpp\"\n\nnamespace gshhg {\n\nusing Cartesian =\n    boost::geometry::model::point<double, 3, boost::geometry::cs::cartesian>;\nusing GeodeticDegree = boost::geometry::model::point<\n    double, 3, boost::geometry::cs::geographic<boost::geometry::degree>>;\nusing GeodeticRadian = boost::geometry::model::point<\n    double, 3, boost::geometry::cs::geographic<boost::geometry::radian>>;\nusing Point =\n    boost::geometry::model::point<double, 2, boost::geometry::cs::cartesian>;\n\nusing Box = boost::geometry::model::box<Point>;\nusing Polygon = boost::geometry::model::polygon<Point>;\n\nusing Spheroid = boost::geometry::srs::spheroid<double>;\n\nusing Andoyer = boost::geometry::strategy::distance::andoyer<Spheroid>;\nusing Haversine = boost::geometry::strategy::distance::haversine<Spheroid>;\nusing Thomas = boost::geometry::strategy::distance::thomas<Spheroid>;\nusing Vincenty = boost::geometry::strategy::distance::vincenty<Spheroid>;\n\n\nGeodeticRadian cartesian_2_geodetic(const Cartesian& point);\nCartesian geodetic_2_cartesian(const GeodeticRadian& point);\n\ninline GeodeticRadian geodetic_2_radian(const GeodeticDegree& point) {\n  return GeodeticRadian(radians(point.get<0>()), radians(point.get<1>()),\n                        point.get<2>());\n}\n\ninline GeodeticDegree geodetic_2_degree(const GeodeticRadian& point) {\n  return GeodeticDegree(degrees(point.get<0>()), degrees(point.get<1>()),\n                        point.get<2>());\n}\n\n}  // namespace gshhg", "meta": {"hexsha": "5a4e60eaef61ed71f4987efdf01f0de44f15ef22", "size": 1508, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/core/geometry.hpp", "max_stars_repo_name": "fbriol/gshhg", "max_stars_repo_head_hexsha": "6a962b0e7a47d1e5b5afa12d19e1a46938889d46", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-30T18:15:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-30T18:15:57.000Z", "max_issues_repo_path": "src/core/geometry.hpp", "max_issues_repo_name": "fbriol/gshhg", "max_issues_repo_head_hexsha": "6a962b0e7a47d1e5b5afa12d19e1a46938889d46", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/core/geometry.hpp", "max_forks_repo_name": "fbriol/gshhg", "max_forks_repo_head_hexsha": "6a962b0e7a47d1e5b5afa12d19e1a46938889d46", "max_forks_repo_licenses": ["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.7804878049, "max_line_length": 77, "alphanum_fraction": 0.7228116711, "num_tokens": 397, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4744179958687745}}
{"text": "//==================================================================================================\n/**\n  Copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n**/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_COMMON_DETAIL_SIMD_F_TRIG_EVALUATION_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_DETAIL_SIMD_F_TRIG_EVALUATION_HPP_INCLUDED\n\n#include <boost/simd/function/horn.hpp>\n#include <boost/simd/constant/mhalf.hpp>\n#include <boost/simd/function/fma.hpp>\n#include <boost/simd/function/inc.hpp>\n#include <boost/simd/function/rec.hpp>\n#include <boost/simd/function/sqr.hpp>\n#include <boost/simd/detail/dispatch/meta/scalar_of.hpp>\n\nnamespace boost { namespace simd { namespace detail\n{\n  namespace bd =  boost::dispatch;\n  namespace bs =  boost::simd;\n\n  template <class A0> struct trig_evaluation < A0,  tag::simd_type, float>\n  {\n    typedef typename bd::as_integer<A0, signed>::type          iA0;\n    typedef typename bd::scalar_of<A0>::type                 stype;\n\n    static BOOST_FORCEINLINE A0 cos_eval(const A0& z)\n    {\n      const A0 y = bs::horn<A0\n        , 0x3d2aaaa5\n        , 0xbab60619\n        , 0x37ccf5ce > (z);\n      return bs::inc(bs::fma(z,bs::Mhalf<A0>(), y*bs::sqr(z)));\n    }\n\n    static BOOST_FORCEINLINE A0 sin_eval(const A0& z, const A0& x)\n    {\n      const A0 y1 =  bs::horn< A0\n        , 0xbe2aaaa2\n        , 0x3c08839d\n        , 0xb94ca1f9 > (z);\n      return bs::fma(bs::multiplies(y1,z),x,x);\n    }\n\n    static BOOST_FORCEINLINE A0 base_tancot_eval(const A0& z)\n    {\n      const A0 zz = bs::sqr(z);\n      return fma(bs::horn<A0\n                , 0x3eaaaa6f\n                , 0x3e0896dd\n                , 0x3d5ac5c9\n                , 0x3cc821b5\n                , 0x3b4c779c\n                , 0x3c19c53b>(zz), zz*z, z);\n    }\n\n    static BOOST_FORCEINLINE A0 tan_eval(const A0& z,  const iA0& n)\n    {\n      A0 y = base_tancot_eval(z);\n      return bs::if_else(bs::is_equal(n, bs::One<iA0>()),y,-bs::rec(y));\n    }\n\n    static BOOST_FORCEINLINE A0 cot_eval(const A0& z,  const iA0& n)\n    {\n      A0 y = base_tancot_eval(z);\n      return bs::if_else(bs::is_equal(n, One<iA0>()),bs::rec(y),-y);\n    }\n  };\n} } }\n\n#endif\n", "meta": {"hexsha": "922971c333ecb01d538102751ab0d104f7caec8e", "size": 2346, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/detail/simd/f_trig_evaluation.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/detail/simd/f_trig_evaluation.hpp", "max_issues_repo_name": "xmar/pythran", "max_issues_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/arch/common/detail/simd/f_trig_evaluation.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": 31.28, "max_line_length": 100, "alphanum_fraction": 0.5724637681, "num_tokens": 687, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4744179958687745}}
{"text": "#include <Eigen/Core>\n#include <Eigen/Dense>\n\nnamespace tyco\n{\nnamespace P3\n{\n\ntemplate<typename T, typename Cs>\nstruct row_vector\n{\n    Eigen::Matrix<T, 1, 4> raw_;\n};\n\ntemplate<typename T, typename Cs>\nstruct column_vector\n{\n    Eigen::Matrix<T, 4, 1> raw_;\n};\n\ntemplate<typename T, typename CsLeft, typename CsRight>\nstruct homography\n{\n    Eigen::Matrix<T, 4, 4> raw_;\n};\n\n// M^-1\ntemplate<typename T, typename CsLeftIn, typename CsRightIn>\nhomography<T, CsRightIn, CsLeftIn> inverse(const homography<T, CsLeftIn, CsRightIn>& M)\n{\n    return {M.raw_.inverse()};\n}\n\n// M * p\ntemplate<typename T, typename CsLeftIn, typename CsRightIn>\ncolumn_vector<T, CsLeftIn> operator*(\n    const homography<T, CsLeftIn, CsRightIn>& M,\n    const column_vector<T, CsRightIn>& p)\n{\n    return {M.raw_ * p.raw_};\n}\n\n// p^T * M\ntemplate<typename T, typename CsLeftIn, typename CsRightIn>\nrow_vector<T, CsRightIn> operator*(\n    const row_vector<T, CsLeftIn>& p,\n    const homography<T, CsLeftIn, CsRightIn>& M)\n{\n    return {p.raw_ * M.raw_};\n}\n\n// M1 * M2\ntemplate<typename T, typename CsLeft, typename CsMiddle, typename CsRight>\nconst homography<T, CsLeft, CsRight> operator*(\n    const homography<T, CsLeft, CsMiddle>& M1,\n    const homography<T, CsMiddle, CsRight>& M2)\n{\n    return {M1.raw_ * M2.raw_};\n}\n\n} // namespace P3\n} // namespace tyco\n", "meta": {"hexsha": "7084cb142a1d1be3a34cf108c45327a7314cc3f5", "size": 1335, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/tyco.hpp", "max_stars_repo_name": "mabur/tyco", "max_stars_repo_head_hexsha": "1a3ae83c7452e20fae3c62c4f25599e8e50aa3f5", "max_stars_repo_licenses": ["MIT"], "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/tyco.hpp", "max_issues_repo_name": "mabur/tyco", "max_issues_repo_head_hexsha": "1a3ae83c7452e20fae3c62c4f25599e8e50aa3f5", "max_issues_repo_licenses": ["MIT"], "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/tyco.hpp", "max_forks_repo_name": "mabur/tyco", "max_forks_repo_head_hexsha": "1a3ae83c7452e20fae3c62c4f25599e8e50aa3f5", "max_forks_repo_licenses": ["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.1904761905, "max_line_length": 87, "alphanum_fraction": 0.6951310861, "num_tokens": 402, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.47441799145451563}}
{"text": "//\n//  AMGCLSolver.hpp\n//  IPC\n//\n//  Created by Minchen Li on 11/06/19.\n//\n#pragma once\n\n#ifdef IPC_WITH_AMGCL\n\n#include \"LinSysSolver.hpp\"\n\n#include <amgcl/backend/builtin.hpp>\n#include <amgcl/make_solver.hpp>\n#include <amgcl/solver/cg.hpp>\n#include <amgcl/solver/lgmres.hpp>\n#include <amgcl/amg.hpp>\n#include <amgcl/coarsening/smoothed_aggregation.hpp>\n#include <amgcl/coarsening/plain_aggregates.hpp>\n#include <amgcl/coarsening/aggregation.hpp>\n#include <amgcl/coarsening/ruge_stuben.hpp>\n#include <amgcl/relaxation/spai0.hpp>\n#include <amgcl/relaxation/gauss_seidel.hpp>\n#include <amgcl/adapter/crs_tuple.hpp>\n#include <amgcl/adapter/block_matrix.hpp>\n#include <amgcl/solver/bicgstab.hpp>\n#include <amgcl/solver/gmres.hpp>\n#include <amgcl/solver/runtime.hpp>\n#include <amgcl/profiler.hpp>\n#include <amgcl/io/mm.hpp>\n#include <amgcl/relaxation/chebyshev.hpp>\n#include <amgcl/coarsening/runtime.hpp>\n#include <amgcl/relaxation/runtime.hpp>\n#include <amgcl/preconditioner/runtime.hpp>\n#include <amgcl/value_type/static_matrix.hpp>\n#include <amgcl/adapter/reorder.hpp>\n#include <amgcl/adapter/eigen.hpp>\n#include <amgcl/profiler.hpp>\n\n#include <boost/property_tree/ptree.hpp>\n\n#include <Eigen/Eigen>\n\n#include <vector>\n#include <set>\n\n// #define USE_BW_BACKEND // use blockwise backend, must undef USE_BW_AGGREGATION\n// #define USE_BW_AGGREGATION // use scalar backend but blockwise aggregation, must undef USE_BW_BACKEND\n// if neither of above is defined, will use scalar backend and aggregation\n\n// #define USE_AMG_SOLVER // use a single V-cycle to approximately solve the linear system\n// if not defined then will use V-cycle preconditioned CG to solve the linear system\n\nnamespace IPC {\n\ntemplate <typename vectorTypeI, typename vectorTypeS>\nclass AMGCLSolver : public LinSysSolver<vectorTypeI, vectorTypeS> {\n    typedef LinSysSolver<vectorTypeI, vectorTypeS> Base;\n\n#ifdef USE_BW_BACKEND\n    typedef amgcl::static_matrix<double, DIM, DIM> value_type;\n    typedef amgcl::static_matrix<double, DIM, 1> rhs_type;\n    typedef amgcl::backend::builtin<value_type> Backend;\n#else\n    typedef amgcl::backend::builtin<double> Backend;\n#endif\n    using Solver = amgcl::make_solver<\n        amgcl::runtime::preconditioner<Backend>,\n        amgcl::runtime::solver::wrapper<Backend>>;\n\nprotected:\n    Solver* solver;\n    boost::property_tree::ptree params;\n    std::vector<int> _ia, _ja;\n    std::vector<double> _a;\n\npublic:\n    AMGCLSolver(void);\n    ~AMGCLSolver(void);\n\n    LinSysSolverType type() const override { return LinSysSolverType::AMGCL; }\n\n    void set_pattern(const std::vector<std::set<int>>& vNeighbor, const std::set<int>& fixedVert) override;\n    void load(const char* filePath, Eigen::VectorXd& rhs) override;\n\n    void load_AMGCL(const char* filePath, Eigen::VectorXd& rhs);\n    void write_AMGCL(const char* filePath, const Eigen::VectorXd& rhs) const;\n\n    void copyOffDiag_IJ(void);\n    void copyOffDiag_a(void);\n\n    void analyze_pattern(void) override;\n\n    bool factorize(void) override;\n\n    void solve(Eigen::VectorXd& rhs, Eigen::VectorXd& result) override;\n};\n\n} // namespace IPC\n\n#endif\n", "meta": {"hexsha": "3128346327ae64f7438bd136b646e9b326808b99", "size": 3111, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/LinSysSolver/AMGCLSolver.hpp", "max_stars_repo_name": "Andlon/IPC", "max_stars_repo_head_hexsha": "3cdc29dac8486c0d62425290b4c23d03ee1d64b4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 344.0, "max_stars_repo_stars_event_min_datetime": "2020-07-03T14:08:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T14:01:11.000Z", "max_issues_repo_path": "src/LinSysSolver/AMGCLSolver.hpp", "max_issues_repo_name": "Andlon/IPC", "max_issues_repo_head_hexsha": "3cdc29dac8486c0d62425290b4c23d03ee1d64b4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 25.0, "max_issues_repo_issues_event_min_datetime": "2020-07-05T15:56:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T20:56:39.000Z", "max_forks_repo_path": "src/LinSysSolver/AMGCLSolver.hpp", "max_forks_repo_name": "Andlon/IPC", "max_forks_repo_head_hexsha": "3cdc29dac8486c0d62425290b4c23d03ee1d64b4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 46.0, "max_forks_repo_forks_event_min_datetime": "2020-07-04T05:04:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T02:09:23.000Z", "avg_line_length": 30.5, "max_line_length": 107, "alphanum_fraction": 0.7512054002, "num_tokens": 857, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412809, "lm_q2_score": 0.5506073655352403, "lm_q1q2_score": 0.474369287717724}}
{"text": "#include \"../innerproduct_proof_generator.h\"\n#include \"../innerproduct_proof_verifier.h\"\n#include \"../challenge_generator_impl.h\"\n\n#include \"./lelantus_test_fixture.h\"\n\n#include <boost/test/unit_test.hpp>\n\nnamespace lelantus {\n\nclass InnerProductTests : public LelantusTestingSetup {\npublic:\n    typedef InnerProductProofGenerator ProofGenerator;\n    typedef InnerProductProofVerifier ProofVerifier;\n    typedef InnerProductProof Proof;\n\npublic:\n    InnerProductTests() {}\n\npublic:\n    void Generate(size_t n) {\n        gens_g = RandomizeGroupElements(n);\n        gens_h = RandomizeGroupElements(n);\n        a = RandomizeScalars(n);\n        b = RandomizeScalars(n);\n        u.randomize();\n    }\n\n    Scalar ComputeC() const {\n        return Primitives::scalar_dot_product(a.begin(), a.end(), b.begin(), b.end());\n    }\n\n    GroupElement ComputePInit() const {\n        return ComputeMultiExponent(gens_g, a) + ComputeMultiExponent(gens_h, b);\n    }\n\n    GroupElement ComputeP(Scalar const &x) const {\n        return ComputePInit() + u * ComputeC() * x;\n    }\n\npublic:\n    std::vector<GroupElement> gens_g;\n    std::vector<GroupElement> gens_h;\n    std::vector<Scalar> a;\n    std::vector<Scalar> b;\n    GroupElement u;\n};\n\nBOOST_FIXTURE_TEST_SUITE(lelantus_inner_product_tests, InnerProductTests)\n\nBOOST_AUTO_TEST_CASE(prove_verify_one)\n{\n    size_t n = 1;\n    size_t log2_n = 0;\n\n    Generate(n);\n\n    Scalar x;\n    x.randomize();\n    unique_ptr<ChallengeGenerator> challengeGenerator = std::make_unique<ChallengeGeneratorImpl<CHash256>>(1);\n\n    // generating proofs\n    Proof proof;\n    ProofGenerator prover(gens_g, gens_h, u, 2);\n    prover.generate_proof(a, b, x, challengeGenerator, proof);\n\n    BOOST_CHECK_EQUAL(ComputePInit(), prover.get_P());\n\n    // validate\n    BOOST_CHECK_EQUAL(ComputeC(), proof.c_);\n    BOOST_CHECK_EQUAL(a.front(), proof.a_);\n    BOOST_CHECK_EQUAL(b.front(), proof.b_);\n    BOOST_CHECK_EQUAL(log2_n, proof.L_.size());\n    BOOST_CHECK_EQUAL(log2_n, proof.R_.size());\n\n    // verify\n    challengeGenerator.reset(new ChallengeGeneratorImpl<CHash256>(1));\n    BOOST_CHECK(ProofVerifier(gens_g, gens_h, u, ComputePInit(), 2).verify(x, proof, challengeGenerator));\n    challengeGenerator.reset(new ChallengeGeneratorImpl<CHash256>(1));\n    BOOST_CHECK(ProofVerifier(gens_g, gens_h, u, ComputePInit(), 2).verify_fast(n, x, proof, challengeGenerator));\n}\n\nBOOST_AUTO_TEST_CASE(prove_verify)\n{\n    size_t n = 32;\n    size_t log2_n = 5;\n\n    Generate(n);\n\n    Scalar x;\n    x.randomize();\n    unique_ptr<ChallengeGenerator> challengeGenerator = std::make_unique<ChallengeGeneratorImpl<CHash256>>(1);\n\n    // generating proofs\n    Proof proof;\n    ProofGenerator prover(gens_g, gens_h, u, 2);\n    prover.generate_proof(a, b, x, challengeGenerator, proof);\n\n    BOOST_CHECK_EQUAL(ComputePInit(), prover.get_P());\n\n    // validate\n    BOOST_CHECK_EQUAL(ComputeC(), proof.c_);\n    BOOST_CHECK_EQUAL(log2_n, proof.L_.size());\n    BOOST_CHECK_EQUAL(log2_n, proof.R_.size());\n\n    // verify\n    challengeGenerator.reset(new ChallengeGeneratorImpl<CHash256>(1));\n    BOOST_CHECK(ProofVerifier(gens_g, gens_h, u, ComputePInit(), 2).verify(x, proof, challengeGenerator));\n    challengeGenerator.reset(new ChallengeGeneratorImpl<CHash256>(1));\n    BOOST_CHECK(ProofVerifier(gens_g, gens_h, u, ComputePInit(), 2).verify_fast(n, x, proof, challengeGenerator));\n}\n\nBOOST_AUTO_TEST_CASE(fake_proof_not_verify)\n{\n    size_t n = 32;\n\n    // generating needed objects\n    Generate(n);\n\n    Scalar x;\n    x.randomize();\n    unique_ptr<ChallengeGenerator> challengeGenerator = std::make_unique<ChallengeGeneratorImpl<CHash256>>(1);\n\n    // generating genertor\n    Proof proof;\n    ProofGenerator(gens_g, gens_h, u, 2).generate_proof(a, b, x, challengeGenerator, proof);\n\n    // verify with fake P\n    GroupElement fakeP;\n    fakeP.randomize();\n\n    challengeGenerator.reset(new ChallengeGeneratorImpl<CHash256>(1));\n    BOOST_CHECK(!ProofVerifier(gens_g, gens_h, u, fakeP, 2).verify(x, proof, challengeGenerator));\n    challengeGenerator.reset(new ChallengeGeneratorImpl<CHash256>(1));\n    BOOST_CHECK(!ProofVerifier(gens_g, gens_h, u, fakeP, 2).verify_fast(n, x, proof, challengeGenerator));\n\n    // verify with fake proof\n    auto verify = [&](Scalar const &_x, Proof const &_p) -> void {\n        challengeGenerator.reset(new ChallengeGeneratorImpl<CHash256>(1));\n        BOOST_CHECK(!ProofVerifier(gens_g, gens_h, u, ComputePInit(), 2).verify(_x, _p, challengeGenerator));\n        challengeGenerator.reset(new ChallengeGeneratorImpl<CHash256>(1));\n        BOOST_CHECK(!ProofVerifier(gens_g, gens_h, u, ComputePInit(), 2).verify_fast(n, _x, _p, challengeGenerator));\n    };\n\n    auto fakeProof = proof;\n    fakeProof.a_.randomize();\n    verify(x, fakeProof);\n\n    fakeProof = proof;\n    fakeProof.b_.randomize();\n    verify(x, fakeProof);\n\n    fakeProof = proof;\n    fakeProof.c_.randomize();\n    verify(x, fakeProof);\n\n    fakeProof = proof;\n    fakeProof.L_[0].randomize();\n    verify(x, fakeProof);\n\n    fakeProof = proof;\n    fakeProof.R_[0].randomize();\n    verify(x, fakeProof);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n} // namespace lelantus", "meta": {"hexsha": "f36491a5241d3bd9720c472189cf7f854c4d8217", "size": 5144, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/liblelantus/test/inner_product_test.cpp", "max_stars_repo_name": "ConsulTent/firo", "max_stars_repo_head_hexsha": "c8f28bf3afe4ec29463a5facf3feed762e2d9133", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-05-19T13:17:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-26T14:21:53.000Z", "max_issues_repo_path": "src/liblelantus/test/inner_product_test.cpp", "max_issues_repo_name": "ConsulTent/firo", "max_issues_repo_head_hexsha": "c8f28bf3afe4ec29463a5facf3feed762e2d9133", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-10-23T04:19:56.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-23T04:20:07.000Z", "max_forks_repo_path": "src/liblelantus/test/inner_product_test.cpp", "max_forks_repo_name": "ConsulTent/firo", "max_forks_repo_head_hexsha": "c8f28bf3afe4ec29463a5facf3feed762e2d9133", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-10-17T08:24:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-26T18:45:25.000Z", "avg_line_length": 30.619047619, "max_line_length": 117, "alphanum_fraction": 0.7037325039, "num_tokens": 1303, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412808, "lm_q2_score": 0.5506073655352403, "lm_q1q2_score": 0.47436928771772396}}
{"text": "/*===========================================================================*\\\n\nAuthor: Matthias W. Smith\nEmail:  mwsmith2@uw.edu\nDate:   11/02/14\n\nDetail: This is a new test program for my Fid libraries \n\n\\*===========================================================================*/\n\n\n//--- std includes ----------------------------------------------------------//\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <cmath>\nusing std::vector;\nusing std::cout;\nusing std::endl;\n\n//--- other includes --------------------------------------------------------//\n#include <armadillo>\n\n//--- project includes ------------------------------------------------------//\n#include \"fid.h\"\nusing namespace fid;\n\n\nint main(int argc, char** argv)\n{\n  // set precision\n  cout.precision(10);\n  cout.setf(std::ios::fixed, std:: ios::floatfield);\n\n  // declare variables\n  int fid_length = 5000;\n  double ti = -1.0;\n  double dt = 0.001;\n  double ftruth = 23.0;\n\n  vector<double> wf_re;\n  vector<double> tm;\n  wf_re.reserve(fid_length);\n  tm.reserve(fid_length);\n\n  std::ofstream out;\n  out.precision(10);\n\n  for (int i = 0; i < fid_length; i++){\n    tm.push_back(i * dt + ti);\n  }\n\n  for (int i = 0; i < fid_length; ++i) {\n    wf_re.push_back(sin(40 * tm[i]));\n  }\n\n  auto wf_im = dsp::hilbert(wf_re);\n  arma::cx_vec wf(wf_im.size());\n\n  for (int i = 0; i < wf_re.size(); ++i) {\n    wf[i] = arma::cx_double(wf_re[i], wf_im[i]);\n  }\n  \n\n  auto wf_rc = dsp::rconvolve(wf, 4000);\n\n  out.open(\"wvd_test_rc_real.txt\");\n  for (int i = 0; i < wf_rc.n_elem; ++i) {\n    out << wf_rc[i].real() << \",\";\n  }\n  out.close();\n\n  out.open(\"wvd_test_rc_imag.txt\");\n  for (int i = 0; i < wf_rc.n_elem; ++i) {\n    out << wf_rc[i].imag() << \",\";\n  }\n  out.close();\n\n  return 0;\n}\n", "meta": {"hexsha": "ede3fb598a1fda0e6528d0b3de4e8c66646c1e26", "size": 1760, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "test/src/test_rconvolve.cxx", "max_stars_repo_name": "mwsmith2/libfid", "max_stars_repo_head_hexsha": "5b68bb27ed18e0412e59527c1d2ca5afb29ceb3a", "max_stars_repo_licenses": ["MIT"], "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/src/test_rconvolve.cxx", "max_issues_repo_name": "mwsmith2/libfid", "max_issues_repo_head_hexsha": "5b68bb27ed18e0412e59527c1d2ca5afb29ceb3a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-01-16T17:59:38.000Z", "max_issues_repo_issues_event_max_datetime": "2015-08-07T21:34:46.000Z", "max_forks_repo_path": "test/src/test_rconvolve.cxx", "max_forks_repo_name": "mwsmith2/fid-analysis", "max_forks_repo_head_hexsha": "5b68bb27ed18e0412e59527c1d2ca5afb29ceb3a", "max_forks_repo_licenses": ["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.7283950617, "max_line_length": 79, "alphanum_fraction": 0.4892045455, "num_tokens": 478, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4742728573653564}}
{"text": "// Copyright Nick Thompson, 2019\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n/*\n * References:\n * Ooura, Takuya, and Masatake Mori. \"A robust double exponential formula for Fourier-type integrals.\" Journal of computational and applied mathematics 112.1-2 (1999): 229-241.\n * http://www.kurims.kyoto-u.ac.jp/~ooura/intde.html\n */\n#ifndef BOOST_MATH_QUADRATURE_OOURA_FOURIER_INTEGRALS_HPP\n#define BOOST_MATH_QUADRATURE_OOURA_FOURIER_INTEGRALS_HPP\n#include <memory>\n#include <boost/math/quadrature/detail/ooura_fourier_integrals_detail.hpp>\n\nnamespace boost { namespace math { namespace quadrature {\n\ntemplate<class Real>\nclass ooura_fourier_sin {\npublic:\n    ooura_fourier_sin(const Real relative_error_tolerance = tools::root_epsilon<Real>(), size_t levels = sizeof(Real)) : impl_(std::make_shared<detail::ooura_fourier_sin_detail<Real>>(relative_error_tolerance, levels))\n    {}\n\n    template<class F>\n    std::pair<Real, Real> integrate(F const & f, Real omega) {\n        return impl_->integrate(f, omega);\n    }\n\n    // These are just for debugging/unit tests:\n    std::vector<std::vector<Real>> const & big_nodes() const {\n        return impl_->big_nodes();\n    }\n\n    std::vector<std::vector<Real>> const & weights_for_big_nodes() const {\n        return impl_->weights_for_big_nodes();\n    }\n\n    std::vector<std::vector<Real>> const & little_nodes() const {\n        return impl_->little_nodes();\n    }\n\n    std::vector<std::vector<Real>> const & weights_for_little_nodes() const {\n        return impl_->weights_for_little_nodes();\n    }\n\nprivate:\n    std::shared_ptr<detail::ooura_fourier_sin_detail<Real>> impl_;\n};\n\n\ntemplate<class Real>\nclass ooura_fourier_cos {\npublic:\n    ooura_fourier_cos(const Real relative_error_tolerance = tools::root_epsilon<Real>(), size_t levels = sizeof(Real)) : impl_(std::make_shared<detail::ooura_fourier_cos_detail<Real>>(relative_error_tolerance, levels))\n    {}\n\n    template<class F>\n    std::pair<Real, Real> integrate(F const & f, Real omega) {\n        return impl_->integrate(f, omega);\n    }\nprivate:\n    std::shared_ptr<detail::ooura_fourier_cos_detail<Real>> impl_;\n};\n\n\n}}}\n#endif\n", "meta": {"hexsha": "b31996c2bccb944c874168a404b2b49d076929e7", "size": 2280, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/math/quadrature/ooura_fourier_integrals.hpp", "max_stars_repo_name": "Harshitha91/Tmdb-react-native-node", "max_stars_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/math/quadrature/ooura_fourier_integrals.hpp", "max_issues_repo_name": "Harshitha91/Tmdb-react-native-node", "max_issues_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/math/quadrature/ooura_fourier_integrals.hpp", "max_forks_repo_name": "Harshitha91/Tmdb-react-native-node", "max_forks_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 33.0434782609, "max_line_length": 218, "alphanum_fraction": 0.7236842105, "num_tokens": 573, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4742728573653564}}
{"text": "#include <boost/simd/meta/is_power_of_2.hpp>\n#include <boost/mpl/assert.hpp>\n#include <boost/mpl/int.hpp>\n\nint main()\n{\n  using boost::mpl::int_;\n\n  BOOST_MPL_ASSERT    (( boost::simd::meta::is_power_of_2_c< 2  >::type ));\n  BOOST_MPL_ASSERT    (( boost::simd::meta::is_power_of_2_c< 32 >::type ));\n  BOOST_MPL_ASSERT_NOT(( boost::simd::meta::is_power_of_2_c< 0  >::type ));\n  BOOST_MPL_ASSERT_NOT(( boost::simd::meta::is_power_of_2_c< 6  >::type ));\n}\n", "meta": {"hexsha": "e995c8cf8a13f69e5af948306462471fad15fbc8", "size": 453, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/sdk/examples/meta/is_power_of_2_c.cpp", "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/sdk/examples/meta/is_power_of_2_c.cpp", "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/sdk/examples/meta/is_power_of_2_c.cpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 32.3571428571, "max_line_length": 75, "alphanum_fraction": 0.6843267108, "num_tokens": 145, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4742728512962739}}
{"text": "#include \"domain/finite_element/finite_element_gaussian.hpp\"\n\n#include <deal.II/fe/fe_dgq.h>\n#include <deal.II/fe/fe_q.h>\n#include <deal.II/fe/fe_update_flags.h>\n\nnamespace bart::domain::finite_element {\n\ntemplate <int dim>\nFiniteElementGaussian<dim>::FiniteElementGaussian(DiscretizationType discretization, int polynomial_degree)\n    : polynomial_degree_(polynomial_degree) {\n  std::string description{\"deal.II Gaussian, \" + std::to_string(dim) + \"D, \"};\n\n  const auto update_flags = dealii::update_values | dealii::update_gradients | dealii::update_quadrature_points |\n                            dealii::update_JxW_values;\n  const auto face_update_flags = dealii::update_values | dealii::update_gradients | dealii::update_quadrature_points |\n      dealii::update_JxW_values | dealii::update_normal_vectors;\n  \n  finite_element_ = GetFiniteElement(discretization);\n  cell_quadrature_ = std::make_shared<dealii::QGauss<dim>>(polynomial_degree + 1);\n  face_quadrature_ = std::make_shared<dealii::QGauss<dim - 1>>(polynomial_degree + 1);\n  values_ = std::make_shared<dealii::FEValues<dim>>(*finite_element_, *cell_quadrature_, update_flags);\n  face_values_ = std::make_shared<dealii::FEFaceValues<dim>>(*finite_element_, *face_quadrature_, face_update_flags);\n  \n  if (discretization == DiscretizationType::kDiscontinuousFEM) {\n    neighbor_face_values_ = \n        std::make_shared<dealii::FEFaceValues<dim>>(*finite_element_, *face_quadrature_, face_update_flags);\n    description += \"Discontinuous, \";\n  } else {\n    description += \"Continuous, \";\n  }\n  description += \"Q = \" + std::to_string(polynomial_degree);\n  this->set_description(description, utility::DefaultImplementation(true));\n}\n\ntemplate <int dim>\nauto FiniteElementGaussian<dim>::GetFiniteElement(DiscretizationType discretization)\n-> std::shared_ptr<dealii::FiniteElement<dim, dim>> {\n  switch (discretization) {\n    case DiscretizationType::kContinuousFEM: {\n      return std::make_shared<dealii::FE_Q<dim>>(polynomial_degree_);\n    }\n    case DiscretizationType::kDiscontinuousFEM: {\n      return std::make_shared<dealii::FE_DGQ<dim>>(polynomial_degree_);\n    }\n    default: {\n      AssertThrow(false, dealii::ExcMessage(\"Cannot build FiniteElementGaussian object with discretization type None\"));\n      break;\n    }\n  }\n}\n\ntemplate class FiniteElementGaussian<1>;\ntemplate class FiniteElementGaussian<2>;\ntemplate class FiniteElementGaussian<3>;\n\n} // namespace bart::domain::finite_element\n", "meta": {"hexsha": "8a2182d03bce11477a379087ebd2975e02ffc752", "size": 2461, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/domain/finite_element/finite_element_gaussian.cpp", "max_stars_repo_name": "SlaybaughLab/Transport", "max_stars_repo_head_hexsha": "8eb32cb8ae50c92875526a7540350ef9a85bc050", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2018-03-14T12:30:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T14:46:44.000Z", "max_issues_repo_path": "src/domain/finite_element/finite_element_gaussian.cpp", "max_issues_repo_name": "SlaybaughLab/Transport", "max_issues_repo_head_hexsha": "8eb32cb8ae50c92875526a7540350ef9a85bc050", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 194.0, "max_issues_repo_issues_event_min_datetime": "2017-07-07T01:38:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-19T18:21:19.000Z", "max_forks_repo_path": "src/domain/finite_element/finite_element_gaussian.cpp", "max_forks_repo_name": "SlaybaughLab/Transport", "max_forks_repo_head_hexsha": "8eb32cb8ae50c92875526a7540350ef9a85bc050", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2017-07-06T22:58:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-15T07:01:21.000Z", "avg_line_length": 42.4310344828, "max_line_length": 120, "alphanum_fraction": 0.7496952458, "num_tokens": 630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4742728512962739}}
{"text": "#include <cstdio>\n#include <fstream>\n\n#include <CGAL/ImageIO.h>\n#include <CGAL/IO/print_wavefront.h>\n#include <CGAL/Random.h>\n#include <CGAL/Side_of_triangle_mesh.h>\n\n#include <Eigen/Core>\n\n#include <igl/copyleft/cgal/polyhedron_to_mesh.h>\n#include <igl/jet.h>\n#include <igl/viewer/Viewer.h>\n\n#include \"image_level_surface_to_mesh_converter.h\"\n\ndouble volume(const Eigen::MatrixXd &V, const Eigen::MatrixXi &F,\n              const Eigen::VectorXi &include) {\n\n  double total_det = 0;\n\n  for (int i = 0; i < include.rows(); ++i) {\n    Eigen::Matrix3d p;\n    p << V(F(include(i), 0), 0), V(F(include(i), 1), 0), V(F(include(i), 2), 0),\n         V(F(include(i), 0), 1), V(F(include(i), 1), 1), V(F(include(i), 2), 1),\n         V(F(include(i), 0), 2), V(F(include(i), 1), 2), V(F(include(i), 2), 2);\n\n    total_det += p.determinant();\n  }\n\n  return std::abs(total_det / 6.0);\n}\n\nint main(int argc, char* argv[]) {\n\n  using namespace ::std;\n  using namespace ::CGAL;\n  using namespace ::cvc::skull_atlas;\n  typedef Exact_predicates_inexact_constructions_kernel Kernel;\n  typedef Polyhedron_3<Kernel> Polyhedron;\n  typedef Kernel::Point_3 Point;\n\n  bool debug = false;\n\n  if (argc < 4) {\n    fprintf(stderr, \"Usage: %s input_image.inr output_mesh.inr isovalue [debug]\\n\", argv[0]);\n    return -1;\n  }\n\n  if (argc == 5) {\n    debug = true;\n  }\n\n  CGAL::Random::State state;\n  unsigned int seed = 0;\n  CGAL::Random random(seed);\n  random.save_state(state);\n  default_random.restore_state(state);\n\n  const char* input_image_filename = argv[1];\n  const char* output_mesh_filename = argv[2];\n  double isovalue = atof(argv[3]);\n\n  if(debug){\n    fprintf(stderr, \"Input file is %s\\n\", input_image_filename);\n    fprintf(stderr, \"Output file is %s\\n\", output_mesh_filename);\n    fprintf(stderr, \"Using an isovalue of %lf\\n\", isovalue);\n  }\n\n  Image_3 image;\n  if (!image.read(input_image_filename)) {\n    fprintf(stderr, \"CGAL failed to read image file \\\"%s\\\".\\n\", input_image_filename);\n    return -1;\n  }\n\n  if(debug) fprintf(stderr, \"Finished reading image, now extracting surface...\\n\");\n\n  Polyhedron mesh = ImageLevelSurfaceToMeshConverter<>().convertToMesh(image, isovalue);\n\n  if(debug) fprintf(stderr, \"Created mesh. Now processing...\\n\");\n  mesh.keep_largest_connected_components(1);\n\n  CGAL::Side_of_triangle_mesh<Polyhedron, Kernel> inside(mesh);\n\n  for (int i = 0; i < image.xdim(); ++i) {\n    for (int j = 0; j < image.ydim(); ++j) {\n      for (int k = 0; k < image.zdim(); ++k) {\n        Point p(i * image.vx(), j * image.vy(), k * image.vz());\n        CGAL::Bounded_side res = inside(p);\n\n        // If it's outside, set the value to be zero.\n        if (!(res == CGAL::ON_BOUNDED_SIDE || res == CGAL::ON_BOUNDARY)) {\n          // Method for accessing data, found at the definition of static_evaluate\n          // in CGAL/ImageIO.h.\n          ((float*)image.data())[ (k * image.ydim() + j) * image.xdim() + i ] = 0.f;\n        }\n      }\n    }\n  }\n\n  // If debug is turned on, display the mesh.\n  if (debug) {\n    Eigen::MatrixXd V;\n    Eigen::MatrixXi F;\n\n    // Viewing the mesh after we're done.\n    igl::copyleft::cgal::polyhedron_to_mesh(mesh, V,F);\n    igl::viewer::Viewer viewer;\n    viewer.data.clear();\n    viewer.data.set_mesh(V, F);\n    viewer.launch();\n  }\n\n  if(debug) fprintf(stderr, \"Finished. Now writing image to %s\\n\", argv[2]);\n  // Call CGAL's _writeImage function.\n  _writeImage(image.image(), argv[2]);\n\n  return 0;\n}\n", "meta": {"hexsha": "68e68a48caced7c9a3a5bdad8e4cc0772758df06", "size": 3440, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cgal_mesh_generation/remove_nonbody.cpp", "max_stars_repo_name": "chipbuster/skull-atlas", "max_stars_repo_head_hexsha": "7f3ee009e1d5f65f101fe853a2cf6e12662970ee", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cgal_mesh_generation/remove_nonbody.cpp", "max_issues_repo_name": "chipbuster/skull-atlas", "max_issues_repo_head_hexsha": "7f3ee009e1d5f65f101fe853a2cf6e12662970ee", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cgal_mesh_generation/remove_nonbody.cpp", "max_forks_repo_name": "chipbuster/skull-atlas", "max_forks_repo_head_hexsha": "7f3ee009e1d5f65f101fe853a2cf6e12662970ee", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6666666667, "max_line_length": 93, "alphanum_fraction": 0.6348837209, "num_tokens": 1011, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.47427285129627383}}
{"text": "#include<bits/stdc++.h>\n\n#include <pcl/pcl_base.h>\n#include <pcl/point_types.h>\n#include <pcl/point_cloud.h>\n#include <pcl/filters/extract_indices.h>\n#include <pcl/segmentation/sac_segmentation.h>\n#include <pcl/common/transforms.h>\n\n#include <map_merge_3d/typedefs.h>\n#include<map_merge_3d/ransac_ground.h>\n\n#include <Eigen/Geometry>\n\nnamespace map_merge_3d \n{\n\nGroundPlane getGroundPlane(const PointCloudConstPtr &input)\n{\n  pcl::SACSegmentation<PointT> seg;\n  ModelCoeffPtr coefficients (new pcl::ModelCoefficients);\n  PointIndicesPtr ground (new pcl::PointIndices);\n\n  // Set up parameters for our segmentation/ extraction scheme\n  seg.setOptimizeCoefficients(true);\n  seg.setModelType(pcl::SACMODEL_PERPENDICULAR_PLANE); //only want points perpendicular to a given axis\n  seg.setMaxIterations(1000); // this is key (default is 50 and that sucks)\n  seg.setMethodType(pcl::SAC_RANSAC);\n  seg.setDistanceThreshold (0.2); // keep points within 0.5 m of the plane\n\n  // because we want a specific plane (X-Y Plane)\n  Eigen::Vector3f axis = Eigen::Vector3f(0.0,0.0,1.0); //z axis\n  seg.setAxis(axis);\n  seg.setEpsAngle(30.0f * (M_PI/180.0f)); // plane can be within 30 degrees of X-Y plane\n  seg.setProbability(0.95);\n  seg.setInputCloud(input);\n  seg.segment(*ground, *coefficients);\n\n  // Create the filtering object\n  pcl::ExtractIndices<PointT> extract;\n  extract.setInputCloud(input);\n  extract.setIndices(ground);\n\n  // Extract non-ground returns\n  PointCloudPtr points(new PointCloud);\n  extract.setNegative(false);\n  extract.filter(*points);\n\n  GroundPlane output;\n  output.ground = ground;\n  output.coefficients = coefficients;\n  output.points = points;\n\n  return output;\n}\n\nPointCloudPtr removeGround(const PointCloudConstPtr &input)\n{\n\n  GroundPlane planeInfo = getGroundPlane(input);\n\n  // to remove points below and within the plane\n  PointCloudPtr filtered(new PointCloud);\n  for(int i = 0; i < planeInfo.points->size(); i++)\n  {\n    PointT point = planeInfo.points->points[i];\n\n    if(point.x * planeInfo.coefficients->values[0] + point.y * planeInfo.coefficients->values[1] + \n        point.z *  planeInfo.coefficients->values[2] +  planeInfo.coefficients->values[3] > 0)\n    {\n      filtered->points.push_back(point);\n    }\n  }\n\n  return filtered;\n\n}\n\n// This helper function finds indices of points that are considered inliers,\n// given a plane description and a condition on distance from the plane.\nstd::vector<size_t> find_inlier_indices(\n    const PointCloudConstPtr &input_cloud_ptr,\n    const Plane& plane,\n    std::function<bool(float)> condition_z_fn)\n{\n    typedef Eigen::Transform<float, 3, Eigen::Affine, Eigen::DontAlign> Transform3f;\n\n    auto base_point = plane.base_point;\n    auto normal = plane.normal;\n\n    // Before rotation of the coordinate frame we need to relocate the point cloud to\n    // the position of base_point of the plane.\n    Transform3f world_to_ransac_base = Transform3f::Identity();\n    world_to_ransac_base.translate(-base_point);\n    PointCloudPtr ransac_base_cloud_ptr (new PointCloud);\n    pcl::transformPointCloud(*input_cloud_ptr, *ransac_base_cloud_ptr, world_to_ransac_base);\n\n    // We are going to use a quaternion to determine the rotation transform\n    // which is required to rotate a coordinate system that plane's normal\n    // becomes aligned with Z coordinate axis.\n    auto rotate_to_plane_quat = Eigen::Quaternionf::FromTwoVectors(\n        normal,\n        Eigen::Vector3f::UnitZ()\n    ).normalized();\n\n    // Now we can create a rotation transform and align the cloud that\n    // the candidate plane matches XY plane.\n    Transform3f ransac_base_to_ransac = Transform3f::Identity();\n    ransac_base_to_ransac.rotate(rotate_to_plane_quat);\n    PointCloudPtr aligned_cloud_ptr (new PointCloud);\n    pcl::transformPointCloud(*ransac_base_cloud_ptr, *aligned_cloud_ptr, ransac_base_to_ransac);\n\n    // Once the point cloud is transformed into the plane coordinates,\n    // We can apply a simple criterion on Z coordinate to find inliers.\n    std::vector<size_t> indices;\n    for (size_t i_point = 0; i_point < aligned_cloud_ptr->size(); i_point++)\n    {\n        const auto &p = (aligned_cloud_ptr->points)[i_point];\n        if (condition_z_fn(p.z))\n        {\n            indices.push_back(i_point);\n        }\n    }\n    return indices;\n}\n\n\n// This function performs plane detection with RANSAC sampling of planes\n// that lie on triplets of points randomly sampled from the cloud.\n// Among all trials the plane that is picked is the one that has the highest\n// number of inliers. Inlier points are then removed as belonging to the ground.\nPointCloudPtr remove_ground_ransac(const PointCloudConstPtr &input_cloud_ptr)\n{\n    // Threshold for rough point dropping by Z coordinate (meters)\n    const float rough_filter_thr = 0.5f;\n    // How much to decimate the input cloud for RANSAC sampling and inlier counting\n    const size_t decimation_rate = 10;\n\n    // Tolerance threshold on the distance of an inlier to the plane (meters)\n    const float ransac_tolerance = 0.1f;\n    // After the final plane is found this is the threshold below which all\n    // points are discarded as belonging to the ground.\n    const float remove_ground_threshold = 0.2f;\n\n    // To reduce the number of outliers (non-ground points) we can roughly crop\n    // the point cloud by Z coordinate in the range (-rough_filter_thr, rough_filter_thr).\n    // Simultaneously we perform decimation of the remaining points since the full\n    // point cloud is excessive for RANSAC.\n    std::mt19937::result_type decimation_seed = 41;\n    std::mt19937 rng_decimation(decimation_seed);\n    auto decimation_gen = std::bind(\n        std::uniform_int_distribution<size_t>(0, decimation_rate), rng_decimation);\n\n    PointCloudPtr filtered_ptr(new PointCloud);\n    for (auto &p : input_cloud_ptr->points)\n    {\n        if ((p.z > -rough_filter_thr) && (p.z < rough_filter_thr))\n        {\n            // Use random number generator to avoid introducing patterns\n            // (which are possible with structured subsampling\n            // like picking each Nth point).\n            if (decimation_gen() == 0)\n            {\n                filtered_ptr->points.push_back(p);\n            }\n        }\n    }\n\n    // We need a random number generator for sampling triplets of points.\n    std::mt19937::result_type sampling_seed = 42;\n    std::mt19937 sampling_rng(sampling_seed);\n    auto random_index_gen = std::bind(\n        std::uniform_int_distribution<size_t>(0, filtered_ptr->size()), sampling_rng);\n\n    // Number of RANSAC trials\n    const size_t num_iterations = 25;\n    // The best plane is determined by a pair of (number of inliers, plane specification)\n    typedef std::pair<size_t, Plane> BestPair;\n    auto best = std::unique_ptr<BestPair>();\n    for (size_t i_iter = 0; i_iter < num_iterations; i_iter++)\n    {\n        // Sample 3 random points.\n        // pa is special in the sense that is becomes an anchor - a base_point of the plane\n        Eigen::Vector3f pa = (*filtered_ptr)[random_index_gen()].getVector3fMap();\n        Eigen::Vector3f pb = (*filtered_ptr)[random_index_gen()].getVector3fMap();\n        Eigen::Vector3f pc = (*filtered_ptr)[random_index_gen()].getVector3fMap();\n\n        // Here we figure out the normal to the plane which can be easily calculated\n        // as a normalized cross product.\n        auto vb = pb - pa;\n        auto vc = pc - pa;\n        Eigen::Vector3f normal = vb.cross(vc).normalized();\n\n        // Flip the normal if points down\n        if (normal.dot(Eigen::Vector3f::UnitZ()) < 0)\n        {\n            normal = -normal;\n        }\n\n        Plane plane{pa, normal};\n\n        // Call find_inlier_indices to retrieve inlier indices.\n        // We will need only the number of inliers.\n        auto inlier_indices = find_inlier_indices(filtered_ptr, plane,\n            [&ransac_tolerance](float z) -> bool {\n                return (z >= -ransac_tolerance) && (z <= ransac_tolerance);\n            });\n\n        // If new best plane is found, update the best\n        bool found_new_best = false;\n        if (best)\n        {\n            if (inlier_indices.size() > best->first)\n            {\n                found_new_best = true;\n            }\n        }\n        else\n        {\n            // For the first trial update anyway\n            found_new_best = true;\n        }\n\n        if (found_new_best)\n        {\n            best = std::unique_ptr<BestPair>(new BestPair{inlier_indices.size(), plane});\n        }\n    }\n\n    // For the best plane filter out all the points that are\n    // below the plane + remove_ground_threshold.\n    PointCloudPtr cloud_no_ground_ptr (new PointCloud);\n    if (best)\n    {\n        auto inlier_indices = find_inlier_indices(input_cloud_ptr, best->second,\n            [&remove_ground_threshold](float z) -> bool {\n                return z <= remove_ground_threshold;\n            });\n        std::unordered_set<size_t> inlier_set(inlier_indices.begin(), inlier_indices.end());\n        for (size_t i_point = 0; i_point < input_cloud_ptr->size(); i_point++)\n        {\n            bool extract_non_ground = true;\n            if ((inlier_set.find(i_point) == inlier_set.end()) == extract_non_ground)\n            {\n                const auto &p = (input_cloud_ptr->points)[i_point];\n                cloud_no_ground_ptr->points.push_back(p);\n            }\n        }\n    }\n    else\n    {\n        *cloud_no_ground_ptr = *input_cloud_ptr;\n    }\n\n    return cloud_no_ground_ptr;\n}\n\n\n} // namespace map_merge_3d", "meta": {"hexsha": "38d326aab07188198d026694a0acfa48d798249e", "size": 9501, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "map_merge_3d/src/ransac_ground.cpp", "max_stars_repo_name": "leonardlohky/map_merge_3d", "max_stars_repo_head_hexsha": "35cf91cc3fe05efc272acb2d5f032f32853b3bee", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-12-20T23:12:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-27T15:53:00.000Z", "max_issues_repo_path": "map_merge_3d/src/ransac_ground.cpp", "max_issues_repo_name": "leonardlohky/map_merge_3d", "max_issues_repo_head_hexsha": "35cf91cc3fe05efc272acb2d5f032f32853b3bee", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-01-06T15:33:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-03T08:05:33.000Z", "max_forks_repo_path": "map_merge_3d/src/ransac_ground.cpp", "max_forks_repo_name": "leonardlohky/map_merge_3d", "max_forks_repo_head_hexsha": "35cf91cc3fe05efc272acb2d5f032f32853b3bee", "max_forks_repo_licenses": ["BSD-3-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.6833976834, "max_line_length": 103, "alphanum_fraction": 0.6775076308, "num_tokens": 2296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4742728512962738}}
{"text": "/*************************************************\n * Copyright (c) 2017 Toru Ito\n * Released under the MIT license\n * http://opensource.org/licenses/mit-license.php\n *************************************************/\n\n#ifndef Delaunay_hpp\n#define Delaunay_hpp\n\n#include <stdio.h>\n#include <vector>\n#include <set>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\nclass Delaunay\n{\npublic:\n    struct TriangleData\n    {\n        unsigned long   index1;\n        unsigned long   index2;\n        unsigned long   index3;\n        double          radius;\n        double          bounds[4];\n        Eigen::Vector2d center;\n        \n        TriangleData()\n        {\n            index1 = index2 = index3 = 0;\n            bounds[0] = bounds[1] = bounds[2] = bounds[3] = 0.0;\n            radius = 0.0;\n            center = Eigen::Vector2d::Zero();\n        }\n\n        bool IsInside( Eigen::Vector2d point )\n        {\n            if( point.x() < bounds[0] )\n                return false;\n\n            if( point.x() > bounds[1] )\n                return false;\n\n            if( point.y() < bounds[2] )\n                return false;\n\n            if( point.y() > bounds[3] )\n                return false;\n\n            if( ( point - center ).norm() > radius )\n                return false;\n        \n            return true;\n        }\n    };\n    \n    struct EdgeData\n    {\n        unsigned long index1, index2;\n        \n        EdgeData()\n        {\n            index1 = 0;\n            index2 = 0;\n        };\n        \n        EdgeData( unsigned long index1, unsigned long index2 )\n        {\n            if( index1 < index2 ) {\n                this->index1 = index1;\n                this->index2 = index2;\n            } else {\n                this->index1 = index2;\n                this->index2 = index1;\n            }\n        };\n    };\n    \npublic:\n    Delaunay();\n    ~Delaunay();\n\n    void SetPoint( std::vector< Eigen::Vector2d > *pPointList );\n    void GetResult( std::vector< Eigen::Vector2d > *pPointList, std::vector< std::vector< unsigned int > > *pIndexList );\n    \n    void Triangulation();\n    \nprivate:\n    std::vector< TriangleData >    m_Triangles;\n    std::vector< Eigen::Vector2d > m_Points;\n    std::vector< unsigned long >   m_InitTrianglePointIndex;\n    \n    void CreateInitTriangle();\n    void DeleteInitTriangle();\n    \n    void AddTriangle( unsigned long index1, unsigned long index2, unsigned long index3 );\n};\n\n#endif /* Delaunay_hpp */\n", "meta": {"hexsha": "7060387b4eef305e313b2a953d8ee5ef4b8bcddd", "size": 2438, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Delaunay/Delaunay.hpp", "max_stars_repo_name": "itoru257/Delaunay", "max_stars_repo_head_hexsha": "70d68dd447be99354b38da4a2698f0b579c09f1c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-01-10T13:16:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-11T09:42:47.000Z", "max_issues_repo_path": "Delaunay/Delaunay.hpp", "max_issues_repo_name": "itoru257/Delaunay", "max_issues_repo_head_hexsha": "70d68dd447be99354b38da4a2698f0b579c09f1c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Delaunay/Delaunay.hpp", "max_forks_repo_name": "itoru257/Delaunay", "max_forks_repo_head_hexsha": "70d68dd447be99354b38da4a2698f0b579c09f1c", "max_forks_repo_licenses": ["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.38, "max_line_length": 121, "alphanum_fraction": 0.4901558655, "num_tokens": 583, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4742728512962737}}
{"text": "#define BOOST_TEST_MODULE MultivariateGaussianModelTestSuite\n#define BOOST_TEST_DYN_LINK\n\n#include <boost/test/included/unit_test.hpp>\n#include <Eigen/Core>\n#include <hops/Model/MultivariateGaussianModel.hpp>\n\nBOOST_AUTO_TEST_SUITE(MultivariateGaussianModel)\n\n    BOOST_AUTO_TEST_CASE(computeNegativeLogLikelihood) {\n        double expectedValue = 1.98943678865;\n        Eigen::VectorXd mean1(2);\n        mean1 << -.8, -.8;\n        Eigen::VectorXd mean2(2);\n        mean2 << .8, .8;\n        Eigen::MatrixXd covariance(2, 2);\n        covariance << 0.04, 0, 0, 0.04;\n\n        hops::MultivariateGaussianModel multivariateGaussianModel1(mean1, covariance);\n        hops::MultivariateGaussianModel multivariateGaussianModel2(mean2, covariance);\n\n        Eigen::VectorXd evaluationPoint(2);\n        evaluationPoint << 0.8, 0.8;\n\n        double actualValue =\n                0.5 * (std::exp(-multivariateGaussianModel1.computeNegativeLogLikelihood(evaluationPoint)) +\n                       std::exp(-multivariateGaussianModel2.computeNegativeLogLikelihood(evaluationPoint)));\n\n        BOOST_CHECK_CLOSE(actualValue, expectedValue, 1e-2);\n    }\n\n    BOOST_AUTO_TEST_CASE(computeLogLikelihoodGradient) {\n        Eigen::VectorXd mean(2);\n        mean << -.8, -.8;\n        Eigen::MatrixXd covariance(2, 2);\n        covariance << 0.04, 0, 0, 0.04;\n\n        hops::MultivariateGaussianModel multivariateGaussianModel(mean, covariance);\n\n        Eigen::VectorXd evaluationPoint1(2);\n        evaluationPoint1 << 0.8, 0.8;\n\n        Eigen::VectorXd evaluationPoint2 =\n                evaluationPoint1 + 1e-5 * multivariateGaussianModel.computeLogLikelihoodGradient(evaluationPoint1);\n\n        // Tests if negative log likelihood decreases in gradient direction, thus checking correct sign of gradient.\n        BOOST_CHECK_GT(multivariateGaussianModel.computeNegativeLogLikelihood(evaluationPoint1),\n                  multivariateGaussianModel.computeNegativeLogLikelihood(evaluationPoint2));\n    }\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "57ca69bf08ae87ca1d589b786d3360e4db45c5e0", "size": 2009, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/Model/MultivariateGaussianModelTestSuite.cpp", "max_stars_repo_name": "modsim/hops", "max_stars_repo_head_hexsha": "4285dd75a07dd844295440a0756b3ba25f5819ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2020-11-26T05:13:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T02:08:40.000Z", "max_issues_repo_path": "tests/Model/MultivariateGaussianModelTestSuite.cpp", "max_issues_repo_name": "modsim/hops", "max_issues_repo_head_hexsha": "4285dd75a07dd844295440a0756b3ba25f5819ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-02-20T23:16:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-20T23:16:34.000Z", "max_forks_repo_path": "tests/Model/MultivariateGaussianModelTestSuite.cpp", "max_forks_repo_name": "modsim/hops", "max_forks_repo_head_hexsha": "4285dd75a07dd844295440a0756b3ba25f5819ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.3921568627, "max_line_length": 116, "alphanum_fraction": 0.7043305127, "num_tokens": 483, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384736, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.47427284522719104}}
{"text": "// Copyright Yamaha 2021\n// MIT License\n// https://github.com/yamaha-bps/cbr_control/blob/master/LICENSE\n\n#include <boost/numeric/odeint.hpp>\n\n#include <cbr_math/lie/group_product.hpp>\n#include <cbr_math/lie/Tn.hpp>\n\n#include <cbr_control/asif++.hpp>\n\n#include <matplot/matplot.h>\n\n#include <algorithm>\n#include <vector>\n\nstruct Dynamics\n{\n  template<typename T>\n  using State = cbr::lie::T2<T>;\n\n  template<typename T>\n  using Input = Eigen::Matrix<T, 1, 1>;\n\n  template<typename T>\n  Eigen::Matrix<T, 2, 1> f(const State<T> & x) const\n  {\n    return Eigen::Matrix<T, 2, 1>(x.translation()(1), 0);\n  }\n\n  template<typename T>\n  Eigen::Matrix<T, 2, 1> g(const State<T> & x) const\n  {\n    return Eigen::Matrix<T, 2, 1>(0, 1);\n  }\n};\n\nstruct SS\n{\n  template<typename T>\n  Eigen::Matrix<T, 2, 1> operator()(const cbr::lie::T2<T> & x) const\n  {\n    return Eigen::Matrix<T, 2, 1>(\n      T(2) - x.translation().x(),\n      T(2) - x.translation().y()\n    );\n  }\n};\n\nstruct Backup\n{\n  template<typename T>\n  Eigen::Matrix<T, 1, 1> operator()(const Dynamics::State<T> & x) const\n  {\n    return Eigen::Matrix<T, 1, 1>(-0.6);\n  }\n};\n\n\nint main()\n{\n  cbr::ASIFParams params;\n  params.dt = 0.02;\n  params.steps = 200;\n  params.constr_dist = 10;\n  params.relax_cost = 500;\n  params.debug = false;\n\n  Dynamics dyn;\n  Backup bu;\n  SS ss;\n\n  cbr::ASIF asif(dyn, bu, ss, params);\n  asif.setBounds(Eigen::Matrix<double, 1, 1>(-0.5), Eigen::Matrix<double, 1, 1>(1.5));\n\n  std::vector<double> sol_t;\n  std::vector<Eigen::Vector2d, Eigen::aligned_allocator<Eigen::Vector2d>> sol_x;\n  std::vector<double> sol_u, sol_udes;\n\n  Eigen::Vector2d x(-5, 1);\n  double udes = 1;\n\n  double t = 0;\n  double dt = 0.01;\n\n  boost::numeric::odeint::runge_kutta4<Eigen::Vector2d, double, Eigen::Vector2d, double,\n    boost::numeric::odeint::vector_space_algebra> stepper {};\n\n  for (int i = 0; i != static_cast<int>(10. / dt); ++i) {\n    Eigen::Matrix<double, 1, 1> u(udes);\n    asif.filter(cbr::lie::T2d(x), u);\n\n    sol_t.push_back(t);\n    sol_x.push_back(x);\n    sol_udes.push_back(udes);\n    sol_u.push_back(u(0));\n\n    stepper.do_step(\n      [&](const Eigen::Vector2d & x, Eigen::Vector2d & dx, double t) {dx(0) = x(1); dx(1) = u(0);},\n      x, t, dt\n    );\n    t += dt;\n  }\n\n  // helper function to extract stuff from solutions\n  auto ex_fn = [](const auto & item, auto ex_fn) {\n      std::vector<double> ret;\n      std::transform(item.cbegin(), item.cend(), std::back_inserter(ret), ex_fn);\n      return ret;\n    };\n\n\n  matplot::figure();\n  matplot::hold(matplot::on);\n  matplot::plot(sol_t, ex_fn(sol_x, [](auto s) {return s(0);}))->line_width(2);\n  matplot::plot(sol_t, ex_fn(sol_x, [](auto s) {return s(1);}))->line_width(2);\n  matplot::title(\"states\");\n  matplot::legend({\"x\", \"v\"});\n  matplot::figure();\n  matplot::hold(matplot::on);\n  matplot::plot(sol_t, sol_udes)->line_width(2);\n  matplot::plot(sol_t, sol_u)->line_width(2);\n  matplot::title(\"input\");\n  matplot::legend({\"u_{des}\", \"u\"});\n\n  matplot::show();\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "28b2e94df647d902a2230a25451ef97692ab4ed2", "size": 3011, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/asif_integrator.cpp", "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": "examples/asif_integrator.cpp", "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": "examples/asif_integrator.cpp", "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": 23.1615384615, "max_line_length": 99, "alphanum_fraction": 0.6220524743, "num_tokens": 1002, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384736, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.474272845227191}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// ars::example::search_reflection.cpp                                       //\n//                                                                           //\n//  Copyright 2009 Erwann Rogard. Distributed under the Boost                //\n//  Software License, Version 1.0. (See accompanying file                    //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)         //\n///////////////////////////////////////////////////////////////////////////////\n#include <boost/format.hpp>\n#include <boost/math/distributions/normal.hpp>\n#include <boost/statistics/detail/distribution_toolkit/distributions/normal/include.hpp>\n#include <boost/ars/search_reflection.hpp>\n#include <boost/ars/constant.hpp>\n\nvoid example_search_reflection(std::ostream& out){\n    std::cout << \"-> example_search_reflection\" << std::endl;\n    using namespace boost;\n    namespace st = boost::statistics::detail;\n\n    typedef double value_t;\n    typedef st::ars::point<value_t> point_t;\n    typedef st::ars::constant<value_t> const_;\n\n    struct local{\n        static std::ostream& write(\n            std::ostream& o,\n            const value_t& x_0,\n            const value_t& x_1,\n            unsigned n,\n            const point_t& p_0,\n            const point_t& p_1\n        ){\n            boost::format f(\"x_0 = %1%, x_1 = %2%, \");\n            f % x_0 % x_1;\n            o << f.str();\n            o << \", n = \" << n << \", p_0 : \" << p_0 << \", p_1 : \" << p_1;\n            return o;\n        }\n    };\n\n    value_t x_min,x_max, x_0, x_1;\n    point_t p_0,p_1;\n    unsigned n_max, n = 0;\n\n    {\n        typedef math::normal_distribution<value_t> mdist_t;\n        typedef const mdist_t& param_t;\n        x_min = const_::inf_;\n        x_max = const_::inf_;\n        n_max = 1e2;\n        const value_t mu = 0.0;\n        const value_t sigma = 2.0;\n        mdist_t mdist(mu,sigma);\n        out << (boost::format(\"N(%1%,%2%)\")%mu%sigma);\n\n        {\n            x_0 = 100.0;\n            x_1 = 100.01;\n            n = st::ars::search_reflection_dist(\n                x_min,\n                x_max,\n                mdist,\n                x_0,\n                x_1,\n                p_0,\n                p_1,\n                n_max\n            );\n            local::write(out,x_0,x_1,n,p_0,p_1);\n            out << std::endl;\n        } \n        \n        {\n            x_0 = -100.01;\n            x_1 = -100.00;\n            n = st::ars::search_reflection_dist(\n                x_min,\n                x_max,\n                mdist,\n                x_0,\n                x_1,\n                p_0,\n                p_1,\n                n_max\n            );\n            local::write(out,x_0,x_1,n,p_0,p_1);\n            out << std::endl;\n        }\n\n        {\n            x_0 = -0.02;\n            x_1 = -0.01;\n            n = st::ars::search_reflection_dist(\n                x_min,\n                x_max,\n                mdist,\n                x_0,\n                x_1,\n                p_0,\n                p_1,\n                n_max\n            );\n            local::write(out,x_0,x_1,n,p_0,p_1);\n            out << std::endl;\n        }\n        \n    }\n    out << \"<-\" << std::endl;\n}\n", "meta": {"hexsha": "720fa3dbf8939dc89018090b0fdfd75b4cbae215", "size": 3231, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "adaptive_rejection_sampling/libs/ars/example/search_reflection.cpp", "max_stars_repo_name": "rogard/boost_sandbox_statistics", "max_stars_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "adaptive_rejection_sampling/libs/ars/example/search_reflection.cpp", "max_issues_repo_name": "rogard/boost_sandbox_statistics", "max_issues_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "adaptive_rejection_sampling/libs/ars/example/search_reflection.cpp", "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": 29.6422018349, "max_line_length": 88, "alphanum_fraction": 0.411637264, "num_tokens": 800, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384735, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4742728452271909}}
{"text": "#include <gmock/gmock.h>\n\n#include <Eigen/Dense>\n#include <array>\n#include <vector>\n\n#include \"larq_compute_engine/core/fused_bgemm_functor.h\"\n#include \"larq_compute_engine/core/macros.h\"\n\nnamespace compute_engine {\nnamespace testing {\n\nnamespace ce = compute_engine;\nusing ce::core::Layout;\n\ntemplate <typename TBitpacked, typename T>\nvoid fused_test_rowmajor() {\n  // clang-format off\n  const int a_num_rows = 2;\n  const int a_num_cols = 9;\n  std::vector<T> a_data_float{1,  1, -1,  1, -1, -1, -1,  1,  1,\n                              1, -1,  1, -1, -1, -1,  1,  1, -1};\n  //const int b_num_rows = 9;\n  const int b_num_cols = 2;\n  std::vector<T> b_data_float{ -1,  1,\n                                1, -1,\n                               -1, -1,\n                                1, -1,\n                                1, -1,\n                                1,  1,\n                               -1,  1,\n                                1,  1,\n                                1, -1};\n  // clang-format on\n\n  // Both matrices above are stored row major so they\n  // are as they are shaped just as they appear in the code.\n  //\n  //  3 = -1 + 1 + 1 + 1 - 1 - 1 + 1 + 1 + 1\n  // -1 =  1 - 1 + 1 - 1 + 1 - 1 - 1 + 1 - 1\n  // -7 = -1 - 1 - 1 - 1 - 1 - 1 - 1 + 1 - 1\n  //  5 =  1 + 1 - 1 + 1 + 1 - 1 + 1 + 1 + 1\n  std::vector<T> c_expected{3, -1, -7, 5};\n\n  const int m = a_num_rows;\n  const int k = a_num_cols;\n  const int n = b_num_cols;\n  const int lda = k;\n  const int ldb = n;\n  const int ldc = n;\n\n  using TBGemmFunctor =\n      ce::core::ReferenceBGemmFunctor<TBitpacked, Layout::RowMajor, TBitpacked,\n                                      Layout::RowMajor, T>;\n  using TFusedBGemmFunctor =\n      ce::core::FusedBGemmFunctor<T, Layout::RowMajor, T, Layout::RowMajor, T,\n                                  TBitpacked, TBGemmFunctor>;\n\n  const int c_size = m * n;\n  std::vector<T> c(c_size);\n  TFusedBGemmFunctor fused_bgemm_functor;\n  fused_bgemm_functor(m, n, k, a_data_float.data(), lda, b_data_float.data(),\n                      ldb, c.data(), ldc);\n\n  EXPECT_THAT(c, ::testing::ElementsAreArray(c_expected));\n}\n\ntemplate <typename TBitpacked, typename T>\nvoid fused_test_colmajor() {\n  // clang-format off\n  const int a_num_rows = 2;\n  const int a_num_cols = 9;\n  std::vector<T> a_data_float{1,  1, -1,  1, -1, -1, -1,  1,  1,\n                              1, -1,  1, -1, -1, -1,  1,  1, -1};\n  const int b_num_rows = 9;\n  const int b_num_cols = 2;\n  std::vector<T> b_data_float{-1,  1, -1,  1,  1,  1, -1, 1,  1,\n                               1, -1, -1, -1, -1,  1,  1, 1, -1};\n  // clang-format on\n\n  // The `b` matrix is the transposed version of the one in the row major\n  // test so the output should be the same.\n\n  //  3 = -1 + 1 + 1 + 1 - 1 - 1 + 1 + 1 + 1\n  // -1 =  1 - 1 + 1 - 1 + 1 - 1 - 1 + 1 - 1\n  // -7 = -1 - 1 - 1 - 1 - 1 - 1 - 1 + 1 - 1\n  //  5 =  1 + 1 - 1 + 1 + 1 - 1 + 1 + 1 + 1\n  std::vector<T> c_expected{3, -1, -7, 5};\n\n  const int m = a_num_rows;\n  const int k = a_num_cols;\n  const int n = b_num_cols;\n  const int lda = k;\n  const int ldb = b_num_rows;\n  const int ldc = n;\n\n  using TBGemmFunctor =\n      ce::core::ReferenceBGemmFunctor<TBitpacked, Layout::RowMajor, TBitpacked,\n                                      Layout::ColMajor, T>;\n  using TFusedBGemmFunctor =\n      ce::core::FusedBGemmFunctor<T, Layout::RowMajor, T, Layout::ColMajor, T,\n                                  TBitpacked, TBGemmFunctor>;\n\n  const int c_size = m * n;\n  std::vector<T> c(c_size);\n  TFusedBGemmFunctor fused_bgemm_functor;\n  fused_bgemm_functor(m, n, k, a_data_float.data(), lda, b_data_float.data(),\n                      ldb, c.data(), ldc);\n\n  EXPECT_THAT(c, ::testing::ElementsAreArray(c_expected));\n}\n\ntemplate <typename TBitpacked, typename T>\nvoid fused_test_eigen(int m, int n, int k) {\n  using MatRowMajor =\n      Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;\n  using MatColMajor =\n      Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>;\n\n  const int a_num_rows = m;\n  const int a_num_cols = k;\n  const int b_num_rows = k;\n  const int b_num_cols = n;\n\n  MatRowMajor a(a_num_rows, a_num_cols);\n  MatColMajor b(b_num_rows, b_num_cols);\n\n  // Fill with random values\n  for (int i = 0; i < a_num_rows; ++i) {\n    for (int j = 0; j < a_num_cols; ++j) {\n      a(i, j) = (rand() % 2) ? 1 : -1;\n    }\n  }\n  for (int i = 0; i < b_num_rows; ++i) {\n    for (int j = 0; j < b_num_cols; ++j) {\n      b(i, j) = (rand() % 2) ? 1 : -1;\n    }\n  }\n\n  MatRowMajor c_correct = a * b;\n  const T* c_expected = c_correct.data();\n\n  const int lda = k;\n  const int ldb = b_num_rows;\n  const int ldc = n;\n\n  using TBGemmFunctor =\n      ce::core::ReferenceBGemmFunctor<TBitpacked, Layout::RowMajor, TBitpacked,\n                                      Layout::ColMajor, T>;\n  using TFusedBGemmFunctor =\n      ce::core::FusedBGemmFunctor<T, Layout::RowMajor, T, Layout::ColMajor, T,\n                                  TBitpacked, TBGemmFunctor>;\n\n  const int c_size = m * n;\n  std::vector<T> c(c_size);\n  TFusedBGemmFunctor fused_bgemm_functor;\n  fused_bgemm_functor(m, n, k, a.data(), lda, b.data(), ldb, c.data(), ldc);\n\n  EXPECT_THAT(c, ::testing::ElementsAreArray(c_expected, (size_t)c_size));\n}\n\nTEST(BitpackingBGEMMTests, RowMajorWithBitPadding8) {\n  fused_test_rowmajor<uint8_t, float>();\n}\n\nTEST(BitpackingBGEMMTests, RowMajorWithBitPadding64) {\n  fused_test_rowmajor<uint64_t, float>();\n}\n\nTEST(BitpackingBGEMMTests, ColMajorWithBitPadding8) {\n  fused_test_colmajor<uint8_t, float>();\n}\n\nTEST(BitpackingBGEMMTests, ColMajorWithBitPadding64) {\n  fused_test_colmajor<uint64_t, float>();\n}\n\nTEST(BitpackingBGEMMTests, ColMajorEigen) {\n  fused_test_eigen<uint64_t, float>(5, 7, 11);\n}\n\n}  // end namespace testing\n}  // end namespace compute_engine\n", "meta": {"hexsha": "a6340275ab3fa94e55ec4316797e7360f2004b47", "size": 5784, "ext": "cc", "lang": "C++", "max_stars_repo_path": "larq_compute_engine/core/tests/fused_bgemm_tests.cc", "max_stars_repo_name": "timdebruin/compute-engine", "max_stars_repo_head_hexsha": "bdd3c080ea330ad911cfb6b02dd41b6c574a7cf4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "larq_compute_engine/core/tests/fused_bgemm_tests.cc", "max_issues_repo_name": "timdebruin/compute-engine", "max_issues_repo_head_hexsha": "bdd3c080ea330ad911cfb6b02dd41b6c574a7cf4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "larq_compute_engine/core/tests/fused_bgemm_tests.cc", "max_forks_repo_name": "timdebruin/compute-engine", "max_forks_repo_head_hexsha": "bdd3c080ea330ad911cfb6b02dd41b6c574a7cf4", "max_forks_repo_licenses": ["Apache-2.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.4347826087, "max_line_length": 79, "alphanum_fraction": 0.571230982, "num_tokens": 1932, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.4742667103432684}}
{"text": "// ===============================================================================================================\n// Copyright (c) 2019, Cornell University. All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n// the following conditions are met:\n//\n//     * Redistributions of source code must retain the above copyright otice, this list of conditions and\n//       the following disclaimer.\n//\n//     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n//       the following disclaimer in the documentation and/or other materials provided with the distribution.\n//\n//     * Neither the name of Cornell University nor the names of its contributors may be used to endorse or\n//       promote products derived from this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE\n// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY\n// OF SUCH DAMAGE.\n//\n// Author: Kai Zhang (kz298@cornell.edu)\n//\n// The research is based upon work supported by the Office of the Director of National Intelligence (ODNI),\n// Intelligence Advanced Research Projects Activity (IARPA), via DOI/IBC Contract Number D17PC00287.\n// The U.S. Government is authorized to reproduce and distribute copies of this work for Governmental purposes.\n// ===============================================================================================================\n\n\n#include \"ceres/ceres.h\"\n#include \"glog/logging.h\"\n#include <Eigen/Dense>\n\n#include <iostream>\n#include <vector>\n#include <sstream>\n#include <fstream>\n#include <iomanip>\n#include <limits>\n\nusing Eigen::MatrixXd;\n\nusing ceres::AutoDiffCostFunction;\nusing ceres::Problem;\nusing ceres::Solver;\nusing ceres::Solve;\n\nusing std::cout;\nusing std::vector;\nusing std::string;\nusing std::istringstream;\nusing std::ifstream;\nusing std::ofstream;\nusing std::stod;\nusing std::runtime_error;\nusing std::setprecision;\n\ntypedef std::numeric_limits<double> dbl;\n#define INIT_VAL -1e10\n\n\nstruct RPCCamera {\n    RPCCamera() {}\n    \n    // RPC camera parameters\n    double col_numera[20] = {INIT_VAL};\n    double col_denomi[20] = {INIT_VAL};\n    double row_numera[20] = {INIT_VAL};\n    double row_denomi[20] = {INIT_VAL};\n    double lat_off = INIT_VAL, lat_scale = INIT_VAL;\n    double lon_off = INIT_VAL, lon_scale = INIT_VAL;\n    double alt_off = INIT_VAL, alt_scale = INIT_VAL;\n    double row_off = INIT_VAL, row_scale = INIT_VAL;\n    double col_off = INIT_VAL, col_scale = INIT_VAL;\n\n    // affine approximation of the RPC camera\n    // [col, row]^T = M * [lat, lon, alt]^T\n    double M11;\n    double M12;\n    double M13;\n    double M14;\n\n    double M21;\n    double M22;\n    double M23;\n    double M24;\n};\n\nstruct Observation {\n    Observation(RPCCamera* cam, double col, double row): cam(cam), col(col), row(row) {}\n    \n    RPCCamera* cam = NULL;\n    double col = INIT_VAL;\n    double row = INIT_VAL;\n};\n\nstruct ReprojResidual {\n    ReprojResidual(Observation* pixel): pixel(pixel) {}\n    \n    template <typename T>\n    bool operator() (const T* const lat, const T* const lon, const T* const alt,\n                     T* residuals) const {\n        RPCCamera& cam = *(this->pixel->cam);\n        \n        T lat_normed = (lat[0] - T(cam.lat_off)) / T(cam.lat_scale);\n        T lon_normed = (lon[0] - T(cam.lon_off)) / T(cam.lon_scale);\n        T alt_normed = (alt[0] - T(cam.alt_off)) / T(cam.alt_scale);\n        \n        T row_numera = this->apply_poly(cam.row_numera, lat_normed, lon_normed, alt_normed);\n        T row_denomi = this->apply_poly(cam.row_denomi, lat_normed, lon_normed, alt_normed);\n        \n        T predict_row = row_numera / row_denomi * T(cam.row_scale) + T(cam.row_off);\n        \n        T col_numera = this->apply_poly(cam.col_numera, lat_normed, lon_normed, alt_normed);\n        T col_denomi = this->apply_poly(cam.col_denomi, lat_normed, lon_normed, alt_normed);\n        \n        T predict_col = col_numera / col_denomi * T(cam.col_scale) + T(cam.col_off);\n        \n        residuals[0] = predict_row - T(this->pixel->row);\n        residuals[1] = predict_col - T(this->pixel->col);\n        return true;\n    }\n    \nprivate:\n    template <typename T>\n    T apply_poly(const double* const poly, T x, T y, T z) const {\n        T out = T(poly[0]);\n        out += poly[1]*y + poly[2]*x + poly[3]*z;\n        out += poly[4]*y*x + poly[5]*y*z +poly[6]*x*z;\n        out += poly[7]*y*y + poly[8]*x*x + poly[9]*z*z;\n        out += poly[10]*x*y*z;\n        out += poly[11]*y*y*y;\n        out += poly[12]*y*x*x + poly[13]*y*z*z + poly[14]*y*y*x;\n        out += poly[15]*x*x*x;\n        out += poly[16]*x*z*z + poly[17]*y*y*z + poly[18]*x*x*z;\n        out += poly[19]*z*z*z;\n        \n        return out;\n    }\n    \nprivate:\n    Observation* pixel = NULL;\n};\n\nvoid solve_initial(const vector<Observation*>& pixels, vector<double>& initial) {\n    assert (pixels.size() >= 2 && initial.size() == 3);\n\n    MatrixXd A(2 * pixels.size(), 3);  // one observation contributes to two equations\n    MatrixXd b(2 * pixels.size(), 1);  \n    for (int i=0; i < pixels.size(); ++i) {\n        A(i * 2, 0) = pixels[i]->cam->M11;\n        A(i * 2, 1) = pixels[i]->cam->M12;\n        A(i * 2, 2) = pixels[i]->cam->M13;\n        b(i * 2, 0) = pixels[i]->col - pixels[i]->cam->M14;\n\n        A(i * 2 + 1, 0) = pixels[i]->cam->M21;\n        A(i * 2 + 1, 1) = pixels[i]->cam->M22;\n        A(i * 2 + 1, 2) = pixels[i]->cam->M23;\n        b(i * 2 + 1, 0) = pixels[i]->row - pixels[i]->cam->M24;\n    }\n\n    MatrixXd x = A.bdcSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(b);\n    for (int i=0; i < 3; ++i) {\n        initial[i] = x(i, 0);\n    }\n}\n\nvoid refine_initial(const vector<Observation*>& pixels, const vector<double>& initial, vector <double>& final, vector <double>& reproj_error) {\n    assert (initial.size() == 3 && final.size() == 3 && reproj_error.size() == 2);\n\n    double lat = initial[0];\n    double lon = initial[1];\n    double alt = initial[2];\n    \n    Problem problem;\n    for (int i=0; i < pixels.size(); ++i) {\n        problem.AddResidualBlock(\n                                 new AutoDiffCostFunction<ReprojResidual, 2, 1, 1, 1>(new ReprojResidual(pixels[i])),\n                                 NULL, &lat, &lon, &alt);\n    }\n    \n    Solver::Options options;\n    options.max_num_iterations = 100;\n    // options.function_tolerance = 1e-10;\n    options.linear_solver_type = ceres::DENSE_QR;\n    // set the following options to true for debugging\n    options.minimizer_progress_to_stdout = false;\n    \n    Solver::Summary summary;\n    Solve(options, &problem, &summary);\n\n    double init_error = sqrt(summary.initial_cost * 2 / pixels.size());\n    double final_error = sqrt(summary.final_cost * 2 / pixels.size());\n\n    // for debugging\n    // cout << summary.BriefReport() << \"\\n\";\n    // cout << \"\\ninitial Point: (\" << initial[0] << \",\" << initial[1] << \",\" << initial[2] << \"), reproj_error: \" << init_error << \" pixels\\n\";\n    // cout << \"final Point:  (\" << lat << \",\" << lon << \",\" << alt << \"), reproj_error: \" << final_error << \" pixels\\n\";\n\n    // output\n    final[0] = lat;\n    final[1] = lon;\n    final[2] = alt;\n    reproj_error[0] = init_error;\n    reproj_error[1] = final_error;\n}\n\nvoid read_rpc_cameras(const string& fname, vector<RPCCamera*>& rpc_cameras) {\n    // number of rpc cameras\n    // camera_id\n    // 20 column numerator coefficients\n    // 20 column denominator coefficients\n    // 20 row numerator coefficients\n    // 20 row denominator coefficients\n    // 10 normalization constants: lat off, lat scale, lon off, lon scale, alt off, alt scale, col off, col scale\n    // 8 affine approximation coefficients: M11, M12, M13, M14, M21, M22, M23, M24\n    // ...\n\n    ifstream infile;\n    infile.open(fname);\n    if (!infile) {\n        throw runtime_error(\"unable to open \" + fname);\n    }\n\n    int cnt; \n    infile >> cnt; \n    for (int i=0; i<cnt; ++i) {\n        int cam_id;\n        // read camera id\n        infile >> cam_id;\n        assert(cam_id == i);\n\n        rpc_cameras.push_back(new RPCCamera());\n        RPCCamera *cam = rpc_cameras.back();\n\n        // read rpc camera parameters\n        for (int i = 0; i < 20; ++i) {\n            infile >> cam->col_numera[i];\n        }\n        for (int i = 0; i < 20; ++i) {\n            infile >> cam->col_denomi[i];\n        }\n        for (int i = 0; i < 20; ++i) {\n            infile >> cam->row_numera[i];\n        }\n        for (int i = 0; i < 20; ++i) {\n            infile >> cam->row_denomi[i];\n        }\n        infile >> cam->lat_off >> cam->lat_scale;\n        infile >> cam->lon_off >> cam->lon_scale;\n        infile >> cam->alt_off >> cam->alt_scale;\n        infile >> cam->col_off >> cam->col_scale;\n        infile >> cam->row_off >> cam->row_scale;\n\n        // read affine approximation parameters\n        infile >> cam->M11 >> cam->M12 >> cam->M13 >> cam->M14;\n        infile >> cam->M21 >> cam->M22 >> cam->M23 >> cam->M24;\n    }\n\n    infile.close();\n}\n\nvoid triangulate_tracks(const string& cameras_fname, const string& tracks_fname, const string& results_fname) {\n    vector<RPCCamera*> rpc_cameras;\n    read_rpc_cameras(cameras_fname, rpc_cameras);\n\n    ifstream infile;\n    infile.open(tracks_fname);\n    if (!infile) {\n        throw runtime_error(\"unable to open \" + tracks_fname);\n    }\n\n    ofstream outfile;\n    outfile.open(results_fname);\n    if (!outfile) {\n        throw runtime_error(\"unable to open \" + results_fname);\n    }\n    outfile << setprecision(dbl::max_digits10);\n\n    int cnt; \n    infile >> cnt; \n    outfile << cnt << '\\n';\n    for (int i=0; i<cnt; ++i) {\n        // read feature track length\n        int len;\n        infile >> len;\n        // read all the observations for this track\n        vector<Observation*> pixels;\n        for (int j=0; j < len; ++j) {\n            int cam_id;\n            double col, row;\n            infile >> cam_id >> col >> row;\n\n            assert(cam_id < rpc_cameras.size());\n            pixels.push_back(new Observation(rpc_cameras[cam_id], col, row));\n        }\n\n        // solve for (lat, lon, alt)\n        vector<double> initial(3, INIT_VAL);\n        vector<double> final(3, INIT_VAL);\n        vector<double> reproj_error(2, INIT_VAL);\n        solve_initial(pixels, initial);\n        refine_initial(pixels, initial, final, reproj_error);\n\n        // write results to file\n        // each line is \"intial lat, initial lon, initial alt, initial reproj err, final lat, final lon, final alt, final reproj err\"\n        outfile << initial[0] << \" \" << initial[1] << \" \" << initial[2] << \" \" << reproj_error[0] << \" \";\n        outfile << final[0] << \" \" << final[1] << \" \" << final[2] << \" \" << reproj_error[1] << \"\\n\";\n\n        // free memory\n        for (int i = 0; i < pixels.size(); ++i) {\n            delete pixels[i];\n        }\n    }\n\n    // close file\n    infile.close();\n    outfile.close();\n\n    // free memory\n    for (int i = 0; i < rpc_cameras.size(); ++i) {\n        delete rpc_cameras[i];\n    }\n}\n\n\nint main(int argc, char** argv) {\n    // program name, cameras_fname, tracks_fname, results_fname\n    assert(argc == 4);\n    google::InitGoogleLogging(argv[0]);\n    string cameras_fname = string(argv[1]);\n    string tracks_fname = string(argv[2]);\n    string results_fname = string(argv[3]);\n\n    triangulate_tracks(cameras_fname, tracks_fname, results_fname);\n    return 0;\n}\n", "meta": {"hexsha": "8d9bd4f5a8315791a1deecd93814a767c85d4f2f", "size": 12088, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "multi_rpc_triangulate/multi_rpc_triangulate.cpp", "max_stars_repo_name": "Kai-46/rpc_triangulation_solver", "max_stars_repo_head_hexsha": "052dbc4782b13571296e37df0a6e8b4408f1202f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2019-08-27T10:31:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-10T02:30:50.000Z", "max_issues_repo_path": "multi_rpc_triangulate/multi_rpc_triangulate.cpp", "max_issues_repo_name": "Kai-46/rpc_triangulation_solver", "max_issues_repo_head_hexsha": "052dbc4782b13571296e37df0a6e8b4408f1202f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-10-27T07:24:15.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-17T15:49:19.000Z", "max_forks_repo_path": "multi_rpc_triangulate/multi_rpc_triangulate.cpp", "max_forks_repo_name": "Kai-46/rpc_triangulation_solver", "max_forks_repo_head_hexsha": "052dbc4782b13571296e37df0a6e8b4408f1202f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-10-18T07:54:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-17T06:06:12.000Z", "avg_line_length": 35.4486803519, "max_line_length": 144, "alphanum_fraction": 0.5986929186, "num_tokens": 3204, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095992, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4742667103432684}}
{"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_HYPERBOLIC_FUNCTIONS_SIMD_COMMON_SINHC_HPP_INCLUDED\n#define NT2_HYPERBOLIC_FUNCTIONS_SIMD_COMMON_SINHC_HPP_INCLUDED\n#include <nt2/hyperbolic/functions/sinhc.hpp>\n#include <nt2/hyperbolic/functions/details/sinhc_kernel.hpp>\n#include <nt2/include/constants/half.hpp>\n#include <nt2/include/constants/log_2.hpp>\n#include <nt2/include/constants/maxlog.hpp>\n#include <nt2/include/constants/one.hpp>\n#include <nt2/include/constants/zero.hpp>\n#include <nt2/include/functions/simd/abs.hpp>\n#include <nt2/include/functions/simd/average.hpp>\n#include <nt2/include/functions/simd/divides.hpp>\n#include <nt2/include/functions/simd/exp.hpp>\n#include <nt2/include/functions/simd/if_else.hpp>\n#include <nt2/include/functions/simd/inbtrue.hpp>\n#include <nt2/include/functions/simd/is_greater.hpp>\n#include <nt2/include/functions/simd/is_less.hpp>\n#include <nt2/include/functions/simd/minus.hpp>\n#include <nt2/include/functions/simd/multiplies.hpp>\n#include <nt2/include/functions/simd/rec.hpp>\n#include <nt2/include/functions/simd/sqr.hpp>\n#include <nt2/include/functions/simd/unary_minus.hpp>\n#include <nt2/sdk/meta/as_logical.hpp>\n#include <nt2/sdk/meta/cardinal_of.hpp>\n#include <boost/simd/sdk/config.hpp>\n\n#ifndef BOOST_SIMD_NO_INFINITIES\n#include <nt2/include/constants/inf.hpp>\n#endif\n\nnamespace nt2 { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT  ( sinhc_, tag::cpu_\n                            , (A0)(X)\n                            , ((simd_<floating_<A0>,X>))\n                            )\n  {\n\n    typedef A0 result_type;\n\n    NT2_FUNCTOR_CALL(1)\n    {\n      //////////////////////////////////////////////////////////////////////////////\n      // if x = abs(a0) is less than 1 sinhc is computed using a polynomial(float)\n      // respectively rational(double) approx inspired from cephes sinh approx.\n      // else according x < Threshold e =  exp(x) or exp(x/2) is respectively\n      // computed\n      // * in the first case sinh is ((e-rec(e))/2)/x\n      // * in the second     sinh is (e/2/x)*e (avoiding undue overflow)\n      // Threshold is Maxlog - Log_2\n      //////////////////////////////////////////////////////////////////////////////\n      typedef typename meta::as_logical<A0>::type bA0;\n      result_type x = nt2::abs(a0);\n      bA0 lt1= lt(x, One<A0>());\n      std::size_t nb = inbtrue(lt1);\n      A0 z = Zero<A0>();\n      if( nb > 0)\n      {\n        z = details::sinhc_kernel<A0>::compute(sqr(x));\n        if(nb >= meta::cardinal_of<A0>::value) return z;\n      }\n      bA0 test1 = gt(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)/x;\n      A0 r =  if_else(test1, tmp1*tmp, average(tmp, -rec(tmp))/x);\n      #ifndef BOOST_SIMD_NO_INFINITIES\n      r = if_else(eq(x, Inf<A0>()), x, r);\n      #endif\n      return if_else(lt1, z, r);\n    }\n  };\n} }\n#endif\n", "meta": {"hexsha": "77a0c9a53721fceca36edd3d52c355c8d5ba5834", "size": 3372, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/hyperbolic/include/nt2/hyperbolic/functions/simd/common/sinhc.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/hyperbolic/include/nt2/hyperbolic/functions/simd/common/sinhc.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/hyperbolic/include/nt2/hyperbolic/functions/simd/common/sinhc.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.6265060241, "max_line_length": 84, "alphanum_fraction": 0.5940094899, "num_tokens": 864, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.47426670054607356}}
{"text": "//           Copyright Matthew Pulver 2018 - 2019.\n// Distributed under the Boost Software License, Version 1.0.\n//      (See accompanying file LICENSE_1_0.txt or copy at\n//           https://www.boost.org/LICENSE_1_0.txt)\n\n// THIS IS NOT MEANT TO BE COMPILED - ONLY FOR INCLUSION IN DOCUMENTATION.\n\n#include <boost/math/differentiation/autodiff.hpp>\n\nnamespace boost {\nnamespace math {\nnamespace differentiation {\n\n// Function returning a single variable of differentiation. Recommended: Use auto for type.\ntemplate <typename RealType, size_t Order, size_t... Orders>\nautodiff_fvar<RealType, Order, Orders...> make_fvar(RealType const& ca);\n\n// Function returning multiple independent variables of differentiation in a std::tuple.\ntemplate<typename RealType, size_t... Orders, typename... RealTypes>\nauto make_ftuple(RealTypes const&... ca);\n\n// Type of combined autodiff types. Recommended: Use auto for return type (C++14).\ntemplate <typename RealType, typename... RealTypes>\nusing promote = typename detail::promote_args_n<RealType, RealTypes...>::type;\n\nnamespace detail {\n\n// Single autodiff variable. Use make_fvar() or make_ftuple() to instantiate.\ntemplate <typename RealType, size_t Order>\nclass fvar {\n public:\n  // Query return value of function to get the derivatives.\n  template <typename... Orders>\n  get_type_at<RealType, sizeof...(Orders) - 1> derivative(Orders... orders) const;\n\n  // All of the arithmetic and comparison operators are overloaded.\n  template <typename RealType2, size_t Order2>\n  fvar& operator+=(fvar<RealType2, Order2> const&);\n\n  fvar& operator+=(root_type const&);\n\n  // ...\n};\n\n// Standard math functions are overloaded and called via argument-dependent lookup (ADL).\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> floor(fvar<RealType, Order> const&);\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> exp(fvar<RealType, Order> const&);\n\n// ...\n\n}  // namespace detail\n\n}  // namespace differentiation\n}  // namespace math\n}  // namespace boost\n/**/\n", "meta": {"hexsha": "17e541178a11b5d76613918208ffcbad2b717417", "size": 2024, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/synopsis.cpp", "max_stars_repo_name": "pulver/autodiff", "max_stars_repo_head_hexsha": "22f6a44c26c2cb27e6b1ff2228aa242db8b4d91c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 50.0, "max_stars_repo_stars_event_min_datetime": "2018-12-19T19:37:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-07T05:04:52.000Z", "max_issues_repo_path": "example/synopsis.cpp", "max_issues_repo_name": "pulver/autodiff", "max_issues_repo_head_hexsha": "22f6a44c26c2cb27e6b1ff2228aa242db8b4d91c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 33.0, "max_issues_repo_issues_event_min_datetime": "2018-12-19T18:36:18.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-04T12:09:11.000Z", "max_forks_repo_path": "example/synopsis.cpp", "max_forks_repo_name": "pulver/autodiff", "max_forks_repo_head_hexsha": "22f6a44c26c2cb27e6b1ff2228aa242db8b4d91c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2018-12-23T05:46:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-25T06:29:55.000Z", "avg_line_length": 33.7333333333, "max_line_length": 91, "alphanum_fraction": 0.7376482213, "num_tokens": 481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850933, "lm_q2_score": 0.6688802669716106, "lm_q1q2_score": 0.4742489074941533}}
{"text": "/********************************************************************************\n * Copyright 2009 The Robotics Group, The Maersk Mc-Kinney Moller Institute,\n * Faculty of Engineering, University of Southern Denmark\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n ********************************************************************************/\n\n#ifndef RW_MATH_VELOCITYSCREW6D_HPP\n#define RW_MATH_VELOCITYSCREW6D_HPP\n\n/**\n * @file VelocityScrew6D.hpp\n */\n#if !defined(SWIG)\n#include \"EAA.hpp\"\n#include \"Math.hpp\"\n#include \"Transform3D.hpp\"\n#include \"Vector3D.hpp\"\n\n#include <rw/common/Serializable.hpp>\n\n#include <Eigen/Core>\n#endif\n\nnamespace rw { namespace math {\n\n    /** @addtogroup math */\n    /*@{*/\n\n    /**\n     * @brief Class for representing 6 degrees of freedom velocity screws.\n     *\n     * \\f[\n     * \\mathbf{\\nu} =\n     * \\left[\n     *  \\begin{array}{c}\n     *  v_x\\\\\n     *  v_y\\\\\n     *  v_z\\\\\n     *  \\omega_x\\\\\n     *  \\omega_y\\\\\n     *  \\omega_z\n     *  \\end{array}\n     * \\right]\n     * \\f]\n     *\n     * A VelocityScrew is the description of a frames linear and rotational velocity\n     * with respect to some reference frame.\n     *\n     */\n    template< class T = double > class VelocityScrew6D\n    {\n      private:\n        T _screw[6];\n\n      public:\n        /**\n         * @brief Constructs a 6 degrees of freedom velocity screw\n         *\n         * @param vx [in] @f$ v_x @f$\n         * @param vy [in] @f$ v_y @f$\n         * @param vz [in] @f$ v_z @f$\n         * @param wx [in] @f$ \\omega_x @f$\n         * @param wy [in] @f$ \\omega_y @f$\n         * @param wz [in] @f$ \\omega_z @f$\n         */\n        VelocityScrew6D (T vx, T vy, T vz, T wx, T wy, T wz);\n\n        /**\n         * @brief Construct from Eigen vector representation.\n         * @param v [in] Eigen matrix with either one row or one column.\n         */\n        template< class R > VelocityScrew6D (const Eigen::MatrixBase< R >& v)\n        {\n            if (v.cols () != 1 || v.rows () != 6)\n                RW_THROW (\"Unable to initialize VectorND with \" << v.rows () << \" x \" << v.cols ()\n                                                                << \" matrix\");\n            /* For some reason the following does not WORK AT ALL (JIMMY)\n            _screw[0] = v(0,0);\n            _screw[1] = v(1,0);\n            _screw[2] = v(2,0);\n            _screw[3] = v(3,0);\n            _screw[4] = v(4,0);\n            _screw[5] = v(5,0);\n            */ // instead use\n            _screw[0] = v.row (0) (0);\n            _screw[1] = v.row (1) (0);\n            _screw[2] = v.row (2) (0);\n            _screw[3] = v.row (3) (0);\n            _screw[4] = v.row (4) (0);\n            _screw[5] = v.row (5) (0);\n        }\n\n        /**\n         * @brief Default Constructor. Initialized the velocity to 0\n         */\n        VelocityScrew6D ()\n        {\n            _screw[0] = _screw[1] = _screw[2] = _screw[3] = _screw[4] = _screw[5] = 0;\n        }\n\n        /**\n         * @brief Copy Constructor\n         * @param vs [in] the velocityscrew6D to copy\n         */\n        VelocityScrew6D (const VelocityScrew6D& vs)\n        {\n            for(size_t i = 0; i < vs.size(); i++){\n                this->_screw[i]=vs[i];\n            }\n        }\n\n        /**\n         * @brief Constructs a velocity screw in frame @f$ a @f$ from a\n         * transform @f$\\robabx{a}{b}{\\mathbf{T}} @f$.\n         *\n         * @param transform [in] the corresponding transform.\n         */\n        explicit VelocityScrew6D (const rw::math::Transform3D< T >& transform);\n\n        /**\n         * @brief Constructs a velocity screw from a linear and angular velocity\n         *\n         * @param linear [in] linear velocity\n         * @param angular [in] angular velocity\n         */\n        VelocityScrew6D (const Vector3D< T >& linear, const EAA< T >& angular);\n\n        /**\n         * @brief Extracts the linear velocity\n         *\n         * @return the linear velocity\n         */\n        const Vector3D< T > linear () const\n        {\n            return Vector3D< T > (_screw[0], _screw[1], _screw[2]);\n        }\n\n        /**\n         * @brief Extracts the angular velocity and represents it using an\n         * equivalent-angle-axis as @f$ \\dot{\\Theta}\\mathbf{k} @f$\n         *\n         * @return the angular velocity\n         */\n        const EAA< T > angular () const { return EAA< T > (_screw[3], _screw[4], _screw[5]); }\n\n        /**\n         * @brief get the size of the underlying vector\n         */\n        size_t size() const {return 6;}\n\n\n#if !defined(SWIG)\n        /**\n         * @brief Returns reference to velocity screw element\n         *\n         * @param index [in] index in the screw, index must be @f$ < 6 @f$.\n         *\n         * @return reference to velocity screw element\n         */\n        T& operator() (std::size_t index)\n        {\n            assert (index < 6);\n            return _screw[index];\n        }\n\n        /**\n         * @brief Returns const reference to velocity screw element\n         *\n         * @param index [in] index in the screw, index must be @f$ < 6 @f$.\n         *\n         * @return const reference to velocity screw element\n         */\n        const T& operator() (std::size_t index) const\n        {\n            assert (index < 6);\n            return _screw[index];\n        }\n\n        /**\n         * @brief Returns const reference to velocity screw element\n         *\n         * @param i [in] index in the screw, index must be @f$ < 6 @f$.\n         *\n         * @return const reference to velocity screw element\n         */\n        const T& operator[] (size_t i) const { return (*this) (i); }\n\n        /**\n         * @brief Returns const reference to velocity screw element\n         *\n         * @param i [in] index in the screw, index must be @f$ < 6 @f$.\n         *\n         * @return const reference to velocity screw element\n         */\n        T& operator[] (size_t i) { return (*this) (i); }\n#else\n        ARRAYOPERATOR (T);\n#endif\n\n        /**\n         * @brief Adds the velocity screw given as a parameter to the velocity screw.\n         *\n         * @param screw [in] Velocity screw to add\n         *\n         * @return reference to the VelocityScrew6D to support additional\n         * assignments.\n         */\n        VelocityScrew6D< T >& operator+= (const VelocityScrew6D< T >& screw)\n        {\n            _screw[0] += screw (0);\n            _screw[1] += screw (1);\n            _screw[2] += screw (2);\n            _screw[3] += screw (3);\n            _screw[4] += screw (4);\n            _screw[5] += screw (5);\n            return *this;\n        }\n\n        /**\n         * @brief Subtracts the velocity screw given as a parameter from the\n         * velocity screw.\n         *\n         * @param screw [in] Velocity screw to subtract\n         *\n         * @return reference to the VelocityScrew6D to support additional\n         * assignments.\n         */\n        VelocityScrew6D< T >& operator-= (const VelocityScrew6D< T >& screw)\n        {\n            _screw[0] -= screw (0);\n            _screw[1] -= screw (1);\n            _screw[2] -= screw (2);\n            _screw[3] -= screw (3);\n            _screw[4] -= screw (4);\n            _screw[5] -= screw (5);\n            return *this;\n        }\n\n        /**\n         * @brief Scales velocity screw with s\n         *\n         * @param s [in] scaling value\n         *\n         * @return reference to the VelocityScrew6D to support additional\n         * assigments\n         */\n        VelocityScrew6D< T >& operator*= (T s)\n        {\n            _screw[0] *= s;\n            _screw[1] *= s;\n            _screw[2] *= s;\n            _screw[3] *= s;\n            _screw[4] *= s;\n            _screw[5] *= s;\n            return *this;\n        }\n\n        /**\n         * @brief Comparison operator.\n         *\n         * The comparison operator makes a element wise comparison.\n         * Returns true only if all elements are equal.\n         *\n         * @param rhs [in] VelocityScrew6D to compare with\n         * @return True if equal.\n         */\n        bool operator== (const VelocityScrew6D< T >& rhs) const\n        {\n            for (int i = 0; i < 6; ++i) {\n                if (!(_screw[i] == rhs (i))) {\n                    return false;\n                }\n            }\n            return true;\n        }\n\n        /**\n         * @brief Comparison operator.\n         *\n         * The comparison operator makes a element wise comparison.\n         * Returns true if any of the elements are different.\n         *\n         * @param rhs [in] VelocityScrew6D to compare with\n         * @return True if not equal.\n         */\n        bool operator!= (const VelocityScrew6D< T >& rhs) const { return !(*this == rhs); }\n#if !defined(SWIGPYTHON)\n        /**\n         * @brief Scales velocity screw and returns scaled version\n         *\n         * @param s [in] scaling value\n         * @param screw [in] Screw to scale\n         * @return Scales screw\n         */\n        friend const VelocityScrew6D< T > operator* (T s, const VelocityScrew6D& screw)\n        {\n            VelocityScrew6D result = screw;\n            result *= s;\n            return result;\n        }\n#endif\n        /**\n         * @brief Scales velocity screw and returns scaled version\n         * @param s [in] scaling value\n         * @return Scales screw\n         */\n        const VelocityScrew6D< T > operator* (T s) const\n        {\n            VelocityScrew6D result = *this;\n            result *= s;\n            return result;\n        }\n\n#if !defined(SWIG)\n        /**\n         * @brief Changes frame of reference and velocity referencepoint of\n         * velocityscrew: @f$ \\robabx{b}{b}{\\mathbf{\\nu}}\\to\n         * \\robabx{a}{a}{\\mathbf{\\nu}} @f$\n         *\n         * The frames @f$ \\mathcal{F}_a @f$ and @f$ \\mathcal{F}_b @f$ are\n         * rigidly connected.\n         *\n         * @param aTb [in] the location of frame @f$ \\mathcal{F}_b @f$ wrt.\n         * frame @f$ \\mathcal{F}_a @f$: @f$ \\robabx{a}{b}{\\mathbf{T}} @f$\n         *\n         * @param bV [in] velocity screw wrt. frame @f$ \\mathcal{F}_b @f$: @f$\n         * \\robabx{b}{b}{\\mathbf{\\nu}} @f$\n         *\n         * @return the velocity screw wrt. frame @f$ \\mathcal{F}_a @f$: @f$\n         * \\robabx{a}{a}{\\mathbf{\\nu}} @f$\n         *\n         * Transformation of both the velocity reference point and of the base to\n         * which the VelocityScrew is expressed\n         *\n         * \\f[\n         * \\robabx{a}{a}{\\mathbf{\\nu}} =\n         * \\left[\n         *  \\begin{array}{c}\n         *  \\robabx{a}{a}{\\mathbf{v}} \\\\\n         *  \\robabx{a}{a}{\\mathbf{\\omega}}\n         *  \\end{array}\n         * \\right] =\n         * \\left[\n         *  \\begin{array}{cc}\n         *    \\robabx{a}{b}{\\mathbf{R}} & S(\\robabx{a}{b}{\\mathbf{p}})\n         *    \\robabx{a}{b}{\\mathbf{R}} \\\\\n         *    \\mathbf{0}^{3x3} & \\robabx{a}{b}{\\mathbf{R}}\n         *  \\end{array}\n         * \\right]\n         * \\robabx{b}{b}{\\mathbf{\\nu}} =\n         * \\left[\n         *  \\begin{array}{c}\n         *    \\robabx{a}{b}{\\mathbf{R}} \\robabx{b}{b}{\\mathbf{v}} +\n         *    \\robabx{a}{b}{\\mathbf{p}} \\times \\robabx{a}{b}{\\mathbf{R}}\n         *    \\robabx{b}{b}{\\mathbf{\\omega}}\\\\\n         *    \\robabx{a}{b}{\\mathbf{R}} \\robabx{b}{b}{\\mathbf{\\omega}}\n         *  \\end{array}\n         * \\right]\n         * \\f]\n         *\n         */\n        friend const VelocityScrew6D< T > operator* (const rw::math::Transform3D< T >& aTb,\n                                                     const VelocityScrew6D< T >& bV)\n        {\n            const Vector3D< T >& bv = bV.linear ();\n            const EAA< T >& bw      = bV.angular ();\n            const EAA< T >& aw      = aTb.R () * bw;\n            const Vector3D< T >& av = aTb.R () * bv + cross (aTb.P (), aw);\n            return VelocityScrew6D< T > (av, aw);\n        }\n#endif\n#if !defined(SWIG)\n        /**\n         * @brief Changes velocity referencepoint of\n         * velocityscrew: @f$ \\robabx{a}{q}{\\mathbf{\\nu}}\\to\n         * \\robabx{a}{p}{\\mathbf{\\nu}} @f$\n         *\n         * The vector should describe a translation from the current\n         * velocity reference point q to the wanted/new velocity reference point p\n         * seen from frame @f$ \\mathcal{F}_a @f$\n         *\n         * @param aPqTop [in] the translation from point q to point p seen in\n         * frame @f$ \\mathcal{F}_a @f$\n         *\n         * @param bV [in] velocity screw wrt. frame @f$ \\mathcal{F}_a @f$: @f$\n         * \\robabx{a}{q}{\\mathbf{\\nu}} @f$\n         *\n         * @return the velocity screw wrt. frame @f$ \\mathcal{F}_a @f$: @f$\n         * \\robabx{a}{p}{\\mathbf{\\nu}} @f$\n         *\n         * Transformation of the velocity reference point\n         *\n         * \\f[\n         * \\robabx{a}{p}{\\mathbf{\\nu}} =\n         * \\left[\n         *  \\begin{array}{c}\n         *  \\robabx{a}{p}{\\mathbf{v}} \\\\\n         *  \\robabx{a}{p}{\\mathbf{\\omega}}\n         *  \\end{array}\n         * \\right] =\n         * \\left[\n         *  \\begin{array}{cc}\n         *    \\robabx{a}{b}{\\mathbf{R}} & S(\\robabx{a}{b}{\\mathbf{p}})\n         *    \\robabx{a}{b}{\\mathbf{R}} \\\\\n         *    \\mathbf{0}^{3x3} & \\robabx{a}{b}{\\mathbf{R}}\n         *  \\end{array}\n         * \\right]\n         * \\robabx{a}{p}{\\mathbf{\\nu}} =\n         * \\left[\n         *  \\begin{array}{c}\n         *    \\robabx{a}{p}{\\mathbf{v}} +\n         *    \\robabx{a}{qTop}{\\mathbf{p}}\n         *    \\robabx{b}{b}{\\mathbf{\\omega}}\\\\\n         *    \\robabx{a}{b}{\\mathbf{R}} \\robabx{b}{b}{\\mathbf{\\omega}}\n         *  \\end{array}\n         * \\right]\n         * \\f]\n         *\n         */\n        friend const VelocityScrew6D< T > operator* (const Vector3D< T >& aPqTop,\n                                                     const VelocityScrew6D< T >& bV)\n        {\n            const Vector3D< T >& bv = bV.linear ();\n            const EAA< T >& bw      = bV.angular ();\n            const Vector3D< T >& av = bv + cross (aPqTop, bw);\n            return VelocityScrew6D< T > (av, bw);\n        }\n#endif\n#if !defined(SWIG)\n        /**\n         * @brief Changes frame of reference for velocityscrew: @f$\n         * \\robabx{b}{i}{\\mathbf{\\nu}}\\to \\robabx{a}{i}{\\mathbf{\\nu}}\n         * @f$\n         *\n         * @param aRb [in] the change in orientation between frame\n         * @f$ \\mathcal{F}_a @f$ and frame\n         * @f$ \\mathcal{F}_b @f$: @f$ \\robabx{a}{b}{\\mathbf{R}} @f$\n         *\n         * @param bV [in] velocity screw wrt. frame\n         * @f$ \\mathcal{F}_b @f$: @f$ \\robabx{b}{i}{\\mathbf{\\nu}} @f$\n         *\n         * @return the velocity screw wrt. frame @f$ \\mathcal{F}_a @f$:\n         * @f$ \\robabx{a}{i}{\\mathbf{\\nu}} @f$\n         *\n         * Transformation of the base to which the VelocityScrew is expressed. The velocity\n         * reference point is left intact\n         *\n         * \\f[\n         * \\robabx{a}{i}{\\mathbf{\\nu}} =\n         * \\left[\n         *  \\begin{array}{c}\n         *  \\robabx{a}{i}{\\mathbf{v}} \\\\\n         *  \\robabx{a}{i}{\\mathbf{\\omega}}\n         *  \\end{array}\n         * \\right] =\n         * \\left[\n         *  \\begin{array}{cc}\n         *    \\robabx{a}{b}{\\mathbf{R}} & \\mathbf{0}^{3x3} \\\\\n         *    \\mathbf{0}^{3x3} & \\robabx{a}{b}{\\mathbf{R}}\n         *  \\end{array}\n         * \\right]\n         * \\robabx{b}{i}{\\mathbf{\\nu}} =\n         * \\left[\n         *  \\begin{array}{c}\n         *    \\robabx{a}{b}{\\mathbf{R}} \\robabx{b}{i}{\\mathbf{v}} \\\\\n         *    \\robabx{a}{b}{\\mathbf{R}} \\robabx{b}{i}{\\mathbf{\\omega}}\n         *  \\end{array}\n         * \\right]\n         * \\f]\n         */\n        friend const VelocityScrew6D< T > operator* (const Rotation3D< T >& aRb,\n                                                     const VelocityScrew6D< T >& bV)\n        {\n            Vector3D< T > bv = bV.linear ();\n            EAA< T > bw      = bV.angular ();\n\n            return VelocityScrew6D< T > (aRb * bv, aRb * bw);\n        }\n#endif\n\n        /**\n         * @brief Adds two velocity screws together @f$\n         * \\mathbf{\\nu}_{12}=\\mathbf{\\nu}_1+\\mathbf{\\nu}_2 @f$\n         *\n         * @param screw2 [in] @f$ \\mathbf{\\nu}_2 @f$\n         *\n         * @return the velocity screw @f$ \\mathbf{\\nu}_{12} @f$\n         */\n        const VelocityScrew6D< T > operator+ (const VelocityScrew6D< T >& screw2) const\n        {\n            return VelocityScrew6D< T > (_screw[0] + screw2._screw[0],\n                                         _screw[1] + screw2._screw[1],\n                                         _screw[2] + screw2._screw[2],\n                                         _screw[3] + screw2._screw[3],\n                                         _screw[4] + screw2._screw[4],\n                                         _screw[5] + screw2._screw[5]);\n        }\n\n        /**\n         * @brief Subtracts two velocity screws\n         * \\f$\\mathbf{\\nu}_{12}=\\mathbf{\\nu}_1-\\mathbf{\\nu}_2\\f$\n         *\n         * \\param screw2 [in] \\f$\\mathbf{\\nu}_2\\f$\n         * \\return the velocity screw \\f$\\mathbf{\\nu}_{12} \\f$\n         */\n        const VelocityScrew6D< T > operator- (const VelocityScrew6D< T >& screw2) const\n        {\n            return VelocityScrew6D< T > (_screw[0] - screw2._screw[0],\n                                         _screw[1] - screw2._screw[1],\n                                         _screw[2] - screw2._screw[2],\n                                         _screw[3] - screw2._screw[3],\n                                         _screw[4] - screw2._screw[4],\n                                         _screw[5] - screw2._screw[5]);\n        }\n#if !defined(SWIG)\n        /**\n         * @brief Ouputs velocity screw to stream\n         *\n         * @param os [in/out] stream to use\n         * @param screw [in] velocity screw\n         * @return the resulting stream\n         */\n        friend std::ostream& operator<< (std::ostream& os, const VelocityScrew6D< T >& screw)\n        {\n            return os << \"{{\" << screw (0) << \",\" << screw (1) << \",\" << screw (2) << \"},{\"\n                      << screw (3) << \",\" << screw (4) << \",\" << screw (5) << \"}}\";\n        }\n#else\n        TOSTRING (rw::math::VelocityScrew6D< T >);\n#endif\n        /**\n         * @brief Takes the 1-norm of the velocity screw. All elements both\n         * angular and linear are given the same weight.\n         *\n         * @return the 1-norm\n         */\n        T norm1 () const\n        {\n            return fabs (_screw[0]) + fabs (_screw[1]) + fabs (_screw[2]) + fabs (_screw[3]) +\n                   fabs (_screw[4]) + fabs (_screw[5]);\n        }\n\n        /**\n         * @brief Takes the 2-norm of the velocity screw. All elements both\n         * angular and linear are given the same weight\n         *\n         * @return the 2-norm\n         */\n        T norm2 () const\n        {\n            return std::sqrt (Math::sqr (_screw[0]) + Math::sqr (_screw[1]) +\n                              Math::sqr (_screw[2]) + Math::sqr (_screw[3]) +\n                              Math::sqr (_screw[4]) + Math::sqr (_screw[5]));\n        }\n\n        /**\n         * @brief Takes the infinite norm of the velocity screw. All elements\n         * both angular and linear are given the same weight.\n         *\n         * @return the infinite norm\n         */\n        T normInf () const\n        {\n            return std::max (\n                fabs (_screw[0]),\n                std::max (fabs (_screw[1]),\n                          std::max (fabs (_screw[2]),\n                                    std::max (fabs (_screw[3]),\n                                              std::max (fabs (_screw[4]), fabs (_screw[5]))))));\n        }\n\n        /**\n           @brief Converter to Eigen vector\n         */\n        Eigen::Matrix< T, 6, 1 > e () const\n        {\n            Eigen::Matrix< T, 6, 1 > res;\n            for (size_t i = 0; i < 6; i++)\n                res (i) = _screw[i];\n            return res;\n        }\n    };\n\n    /**\n     * @brief Takes the 1-norm of the velocity screw. All elements both\n     * angular and linear are given the same weight.\n     *\n     * @param screw [in] the velocity screw\n     * @return the 1-norm\n     */\n    template< class T > T norm1 (const VelocityScrew6D< T >& screw) { return screw.norm1 (); }\n\n    /**\n     * @brief Takes the 2-norm of the velocity screw. All elements both\n     * angular and linear are given the same weight\n     *\n     * @param screw [in] the velocity screw\n     * @return the 2-norm\n     */\n    template< class T > T norm2 (const VelocityScrew6D< T >& screw) { return screw.norm2 (); }\n\n    /**\n     * @brief Takes the infinite norm of the velocity screw. All elements\n     * both angular and linear are given the same weight.\n     *\n     * @param screw [in] the velocity screw\n     *\n     * @return the infinite norm\n     */\n    template< class T > T normInf (const VelocityScrew6D< T >& screw) { return screw.normInf (); }\n\n    /**\n     * @brief Casts VelocityScrew6D<T> to VelocityScrew6D<Q>\n     *\n     * @param vs [in] VelocityScrew6D with type T\n     *\n     * @return VelocityScrew6D with type Q\n     */\n    template< class Q, class T > const VelocityScrew6D< Q > cast (const VelocityScrew6D< T >& vs)\n    {\n        return VelocityScrew6D< Q > (static_cast< Q > (vs (0)),\n                                     static_cast< Q > (vs (1)),\n                                     static_cast< Q > (vs (2)),\n                                     static_cast< Q > (vs (3)),\n                                     static_cast< Q > (vs (4)),\n                                     static_cast< Q > (vs (5)));\n    }\n#if !defined(SWIG)\n    extern template class rw::math::VelocityScrew6D< double >;\n    extern template class rw::math::VelocityScrew6D< float >;\n#else\n    SWIG_DECLARE_TEMPLATE (VelocityScrew6Dd, rw::math::VelocityScrew6D< double >);\n    SWIG_DECLARE_TEMPLATE (VelocityScrew6Df, rw::math::VelocityScrew6D< float >);\n#endif\n    using VelocityScrew6Dd = VelocityScrew6D< double >;\n    using VelocityScrew6Df = VelocityScrew6D< float >;\n\n    /*@}*/\n}}    // namespace rw::math\n\nnamespace rw { namespace common {\n    class OutputArchive;\n    class InputArchive;\n    namespace serialization {\n        /**\n         * @copydoc rw::common::serialization::write\n         * @relatedalso rw::math::VelocityScrew6D\n         */\n        template<>\n        void write (const rw::math::VelocityScrew6D< double >& sobject,\n                    rw::common::OutputArchive& oarchive, const std::string& id);\n\n        /**\n         * @copydoc rw::common::serialization::write\n         * @relatedalso rw::math::VelocityScrew6D\n         */\n        template<>\n        void write (const rw::math::VelocityScrew6D< float >& sobject,\n                    rw::common::OutputArchive& oarchive, const std::string& id);\n\n        /**\n         * @copydoc rw::common::serialization::read\n         * @relatedalso rw::math::VelocityScrew6D\n         */\n        template<>\n        void read (rw::math::VelocityScrew6D< double >& sobject, rw::common::InputArchive& iarchive,\n                   const std::string& id);\n\n        /**\n         * @copydoc rw::common::serialization::read\n         * @relatedalso rw::math::VelocityScrew6D\n         */\n        template<>\n        void read (rw::math::VelocityScrew6D< float >& sobject, rw::common::InputArchive& iarchive,\n                   const std::string& id);\n    }    // namespace serialization\n}}       // namespace rw::common\n\n#endif    // end include guard\n", "meta": {"hexsha": "ac6cf37aa274606d7c99cb1a7817325022e9cdc6", "size": 23772, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "RobWork/src/rw/math/VelocityScrew6D.hpp", "max_stars_repo_name": "ZLW07/RobWork", "max_stars_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-29T14:16:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T14:16:27.000Z", "max_issues_repo_path": "RobWork/src/rw/math/VelocityScrew6D.hpp", "max_issues_repo_name": "ZLW07/RobWork", "max_issues_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RobWork/src/rw/math/VelocityScrew6D.hpp", "max_forks_repo_name": "ZLW07/RobWork", "max_forks_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.4023154848, "max_line_length": 100, "alphanum_fraction": 0.477873128, "num_tokens": 6737, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191460821871, "lm_q2_score": 0.6688802537704064, "lm_q1q2_score": 0.47424890635953015}}
{"text": "#include \"log_number.hpp\"\n\n#include <gtest/gtest.h>\n\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_real_distribution.hpp>\n\nusing namespace ProbabilityDistributions;\n\nTEST(LogNumberTest, DefaultConstruction) {\n  LogNumber val;\n  EXPECT_EQ(0, val.to_double());\n}\n\nTEST(LogNumberTest, CopyConstruction) {\n  boost::random::mt19937 rng;\n  const unsigned int n_samples = 1000;\n  boost::random::uniform_real_distribution<> dist(-5,5);\n\n  for (unsigned int i = 0; i < n_samples; i++) {\n    double val = dist(rng);\n    LogNumber val2(val);\n    EXPECT_NEAR(val, val2.to_double(), 1e-10);\n  }\n}\n\nTEST(LogNumberTest, Assignment) {\n  boost::random::mt19937 rng;\n  const unsigned int n_samples = 1000;\n  boost::random::uniform_real_distribution<> dist(-5,5);\n\n  for (unsigned int i = 0; i < n_samples; i++) {\n    double val = dist(rng);\n    LogNumber val2;\n    val2 = val;\n    EXPECT_NEAR(val, val2.to_double(), 1e-10);\n  }\n}\n\nTEST(LogNumberTest, FromLog) {\n  boost::random::mt19937 rng;\n  const unsigned int n_samples = 1000;\n  boost::random::uniform_real_distribution<> dist(-5,5);\n\n  for (unsigned int i = 0; i < n_samples; i++) {\n    double val = dist(rng);\n    LogNumber val2;\n    val2.from_log(val);\n    EXPECT_NEAR(std::exp(val), val2.to_double(), 1e-10);\n  }\n}\n\nTEST(LogNumberTest, Sum) {\n  boost::random::mt19937 rng;\n  const unsigned int n_samples = 1000;\n  boost::random::uniform_real_distribution<> dist(-5,5);\n\n  for (unsigned int i = 0; i < n_samples; i++) {\n    double v1 = dist(rng), v2 = dist(rng);\n    LogNumber lv1(v1), lv2(v2);\n    EXPECT_NEAR(v1+v2, (lv1+lv2).to_double(), 1e-10);\n  }\n}\n\nTEST(LogNumberTest, Subtraction) {\n  boost::random::mt19937 rng;\n  const unsigned int n_samples = 1000;\n  boost::random::uniform_real_distribution<> dist(-5,5);\n\n  for (unsigned int i = 0; i < n_samples; i++) {\n    double v1 = dist(rng), v2 = dist(rng);\n    LogNumber lv1(v1), lv2(v2);\n    EXPECT_NEAR(v1-v2, (lv1-lv2).to_double(), 1e-10);\n  }\n}\n\nTEST(LogNumberTest, Multiplication) {\n  boost::random::mt19937 rng;\n  const unsigned int n_samples = 1000;\n  boost::random::uniform_real_distribution<> dist(-5,5);\n\n  for (unsigned int i = 0; i < n_samples; i++) {\n    double v1 = dist(rng), v2 = dist(rng);\n    LogNumber lv1(v1), lv2(v2);\n    EXPECT_NEAR(v1*v2, (lv1*lv2).to_double(), 1e-10);\n  }\n}\n\nTEST(LogNumberTest, Division) {\n  boost::random::mt19937 rng;\n  const unsigned int n_samples = 1000;\n  boost::random::uniform_real_distribution<> dist(-5,5);\n\n  for (unsigned int i = 0; i < n_samples; i++) {\n    double v1 = dist(rng), v2 = dist(rng);\n    LogNumber lv1(v1), lv2(v2);\n    EXPECT_NEAR(v1/v2, (lv1/lv2).to_double(), 1e-10);\n  }\n}\n", "meta": {"hexsha": "e9372473ac16f54c4e036ba93d5d9d230c7b463a", "size": 2665, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/log_number.cpp", "max_stars_repo_name": "mirandaconrado/probability-distributions", "max_stars_repo_head_hexsha": "6b7d86e181237eb134e6df6da60200beed66922f", "max_stars_repo_licenses": ["MIT"], "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/log_number.cpp", "max_issues_repo_name": "mirandaconrado/probability-distributions", "max_issues_repo_head_hexsha": "6b7d86e181237eb134e6df6da60200beed66922f", "max_issues_repo_licenses": ["MIT"], "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/log_number.cpp", "max_forks_repo_name": "mirandaconrado/probability-distributions", "max_forks_repo_head_hexsha": "6b7d86e181237eb134e6df6da60200beed66922f", "max_forks_repo_licenses": ["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.65, "max_line_length": 56, "alphanum_fraction": 0.6637898687, "num_tokens": 831, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802735722128, "lm_q2_score": 0.7090191214879991, "lm_q1q2_score": 0.4742489039488228}}
{"text": "#ifndef HMLIB_UBLAS_INC\n#define HMLIB_UBLAS_INC 100\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n\nnamespace hmLib {\n\tnamespace ublas {\n\t\ttemplate<typename T>\n\t\tbool invert(const boost::numeric::ublas::matrix<T>& a, boost::numeric::ublas::matrix<T>& b) {\n\t\t\tnamespace ub = boost::numeric::ublas;\n\t\t\tub::matrix<T> tmp(a);\n\t\t\tub::permutation_matrix<> pm(tmp.size1());\n\n\t\t\t//fail to factorize\n\t\t\tif(ub::lu_factorize(tmp, pm) != 0) return true;\n\n\t\t\tb = ub::identity_matrix<T>(tmp.size1());\n\n\t\t\tub::lu_substitute(tmp, pm, b);\n\n\t\t\treturn false;\n\t\t}\n\t}\n}\n#endif\n", "meta": {"hexsha": "049a97dbda9012d40f2adeab67e6b7249dc7f39d", "size": 590, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ublas.hpp", "max_stars_repo_name": "hmito/hmLib", "max_stars_repo_head_hexsha": "0f2515ba9c99c06d02e2fa633eeae73bcd793983", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ublas.hpp", "max_issues_repo_name": "hmito/hmLib", "max_issues_repo_head_hexsha": "0f2515ba9c99c06d02e2fa633eeae73bcd793983", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ublas.hpp", "max_forks_repo_name": "hmito/hmLib", "max_forks_repo_head_hexsha": "0f2515ba9c99c06d02e2fa633eeae73bcd793983", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-09-22T03:32:11.000Z", "max_forks_repo_forks_event_max_datetime": "2015-09-22T03:32:11.000Z", "avg_line_length": 21.8518518519, "max_line_length": 95, "alphanum_fraction": 0.6762711864, "num_tokens": 185, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.810478926981208, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.47421215563410113}}
{"text": "#include <boost/random/lagged_fibonacci.hpp>\n", "meta": {"hexsha": "1d1b45048c66a7a299b07e6816f39a214dde735a", "size": 45, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_random_lagged_fibonacci.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_random_lagged_fibonacci.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_random_lagged_fibonacci.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 22.5, "max_line_length": 44, "alphanum_fraction": 0.8222222222, "num_tokens": 11, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4742121502772411}}
{"text": "#include <iostream>\n#include <stdio.h>\n#include <fstream>\n#include <vector>\n//#include <map>\n//#include <set>\n#include <unordered_set>\n//#include <unordered_map>\n#include <cmath>\n#include <algorithm>\n\n// #include <gnuplot-iostream.h>\n#include <assert.h>\n#include <boost/program_options.hpp>\n#include <boost/filesystem.hpp>\n\n#include \"vector3d.hpp\"\n#include \"swiss_to_lat_lon.hpp\"\n#include \"height_map.hpp\"\n\nconst int horizon_angles = 360;\nconst int tile_size = 40;\n\n\nnamespace po = boost::program_options;\n\nstruct pos_hoz {\n    vector3d pos;\n    vector3d norm;\n    short elevation_angles[horizon_angles];\n    pos_hoz() : pos(0,0,0), norm(0,0,0) {\n        memset(elevation_angles, 0, sizeof(short) * horizon_angles);\n    }\n};\n\nbool EQ_DBL(double a, double b){\n    return std::abs(a-b)<EPS_DBL;\n}\n\nint main(int ac, char** av) {\n    \n    bool test = true;\n    //Variables to be assigned by program options\n    double height_map_resolution = 25.0;;\n    double north_bound = 1e100;\n    double south_bound = -1e100;\n    double east_bound = 1e100;\n    double west_bound = -1e100;\n    \n    \n    std::string input_file;\n    std::string output_file;\n    bool verbose = false;\n    \n    /*\n    // Declare the supported options.\n    po::options_description op_desc(\"Allowed options\");\n    \n    op_desc.add_options()\n    (\"help\", \"print options table\")\n    (\"input-file,i\", po::value<std::string>(&input_file), \"File containing height map data in x<space>y<space>z<newline> swiss coordinates format\")\n    (\"output-dir,o\", po::value<std::string>(&output_file), \"File for output data (default data_out.hoz)\")\n    (\"resolution,R\", po::value<double>(&height_map_resolution)->default_value(25.0), \"resolution of data (default: 25.0)\")\n    (\"nmax\",po::value<double>(&north_bound)->default_value(1e100), \"maximum north coordinate to be treated (default 1e100)\")\n    (\"nmin\",po::value<double>(&south_bound)->default_value(-1e100), \"minimum north coordinate to be treated (default -1e100)\")\n    (\"emax\",po::value<double>(&east_bound)->default_value(1e100), \"maximum east coordinate to be treated (default 1e100)\")\n    (\"emin\",po::value<double>(&west_bound)->default_value(-1e100), \"minimum east coordinate to be treated (default -1e100)\")\n    (\"verbose, v\", \"Verbose: output lots of text\")\n    ;\n    \n    po::positional_options_description pd;\n    pd.add(\"input-file\", 1).add(\"output-file\", 1);\n    \n    po::variables_map vm;\n    po::store(po::parse_command_line(ac, av, op_desc), vm);\n    po::notify(vm);\n    \n    if (vm.count(\"help\")) {\n        std::cout <<\"MountainOutline [options] [input file] [output base]\"<<std::endl<< op_desc << std::endl;\n        return 1;\n    }\n    \n    if (vm.count(\"verbose\")){\n        verbose = true;\n    }\n    if(!vm.count(\"input-file\")){\n        std::cout << \"Input file must be specified\" << std::endl;\n        exit(255);\n    }\n    if(!vm.count(\"output-dir\")){\n        output_file = std::string(\"data_out.hoz\");\n        std::cout << \"Output directory will be: \" << std::endl;\n    }\n    */\n    input_file = std::string(\"/Users/alexxx/HeightMaps/precieous/DHM25.xyz\");\n    std::ifstream ifs(input_file);\n    if (!ifs.is_open())\n        throw std::runtime_error(\"could not open file : \" + std::string(input_file));\n    \n    height_map grid_points(ifs, south_bound, north_bound, east_bound, west_bound);\n    \n    \n    //grid_points is a height_map, an unordered_set of all points in bounding box with\n    //the maximum and minimum x,y,h of all values stored.\n    \n    \n    std::pair<double,double> NE = swiss_to_lat_lon(grid_points.xmax()+height_map_resolution/2.0, grid_points.ymax()+height_map_resolution/2.0);\n    std::pair<double,double> SW = swiss_to_lat_lon(grid_points.xmin()-height_map_resolution/2.0, grid_points.ymin()-height_map_resolution/2.0);\n    \n    std::cout << \"NE: \" << grid_points.xmax() <<\", \" << grid_points.ymax() << \" SW: \"<< grid_points.xmin() << \" , \" << grid_points.ymin() <<  std::endl;\n    std::cout  << \"NE: \" << NE.first <<\", \" << NE.second << \" SW: \"<< SW.first << \", \" << SW.second <<  std::endl;\n    std::cout << \"Maximum height: \" << grid_points.hmax() << std::endl;\n    std::cout << \"Number of points in dataset: \" << grid_points.size() << std::endl;\n    \n    if(test){\n        double y_test = height_map_resolution*floor(601430.0/height_map_resolution);\n        double x_test = height_map_resolution*floor(126243.0/height_map_resolution);\n        auto it_v = grid_points.find_point(vector3d(x_test,y_test,0));      //get the gridpoint from the set\n        std::cout << \"Test point: \" << x_test <<\" \"<< y_test << std::endl;\n        std::cout << \"Resolution: \" << height_map_resolution << \", tile size: \"<< tile_size << std::endl;\n        vector3d v = *it_v;\n        double elevation_angles[360];\n        int theta_start = 0;\n        int theta_end = 360;\n        \n        //        time_t start_time  = time(NULL);\n        clock_t t = clock();\n        for(int theta = theta_start;theta<theta_end;theta++){\n            double phi = atan(grid_points.compute_elevation_angle(v,theta, height_map_resolution, 360.0/horizon_angles));\n            short phi_short = (short)((phi / M_PI_2) * std::numeric_limits<short>::max());\n            elevation_angles[theta] = phi_short;\n            \n        }\n        double run_time = ((double)(clock()-t))/CLOCKS_PER_SEC;\n        //        double run_time = difftime(time(NULL), start_time);\n        std::cout << \"phi = [\";\n        for(int theta = theta_start;theta<theta_end;theta++){\n            std::cout << elevation_angles[theta] << \";\";\n        }\n        std::cout << \"];\" << std::endl;\n        std::cout << \"runtime test point: \" << run_time << std::endl;\n        \n        return 0;\n    }\n    \n    \n\n    return 0;\n}\n\n\n\n\n\n\n", "meta": {"hexsha": "e2308665ab13452e0606a06267597e84e31b9c57", "size": 5704, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sources/mountain_outline.cpp", "max_stars_repo_name": "alexxxzzz/ValaisSun", "max_stars_repo_head_hexsha": "fca2610bf2f68df4c82a36e3f9464ca8f2de0b06", "max_stars_repo_licenses": ["MIT"], "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/mountain_outline.cpp", "max_issues_repo_name": "alexxxzzz/ValaisSun", "max_issues_repo_head_hexsha": "fca2610bf2f68df4c82a36e3f9464ca8f2de0b06", "max_issues_repo_licenses": ["MIT"], "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/mountain_outline.cpp", "max_forks_repo_name": "alexxxzzz/ValaisSun", "max_forks_repo_head_hexsha": "fca2610bf2f68df4c82a36e3f9464ca8f2de0b06", "max_forks_repo_licenses": ["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.5641025641, "max_line_length": 152, "alphanum_fraction": 0.6271037868, "num_tokens": 1504, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4742121502772411}}
{"text": "/**\n * @author Alessandro Bianco\n */\n\n/**\n * @addtogroup DFNs\n * @{\n */\n\n#include \"CeresEstimation.hpp\"\n\n#include <Errors/Assert.hpp>\n#include <Errors/AssertOnTest.hpp>\n#include <Macros/YamlcppMacros.hpp>\n\n#include <opencv2/calib3d.hpp>\n#include <Eigen/Geometry>\n\n#include <stdlib.h>\n#include <fstream>\n\nusing namespace PoseWrapper;\nusing namespace MatrixWrapper;\nusing namespace CorrespondenceMap3DWrapper;\nusing namespace Helpers;\nusing namespace BaseTypesWrapper;\n\nnamespace CDFF\n{\nnamespace DFN\n{\nnamespace Transform3DEstimation\n{\n\nCeresEstimation::CeresEstimation()\n{\n        parameters = DEFAULT_PARAMETERS;\n\n\tparametersHelper.AddParameter<float>(\"GeneralParameters\", \"MaximumAllowedError\", parameters.maximumAllowedError, DEFAULT_PARAMETERS.maximumAllowedError);\n\tparametersHelper.AddParameter<float>(\"GeneralParameters\", \"MaximumAllowedDeterminantError\", parameters.maximumAllowedDeterminantError, DEFAULT_PARAMETERS.maximumAllowedDeterminantError);\n\n\tconfigurationFilePath = \"\";\n}\n\nCeresEstimation::~CeresEstimation()\n{\n}\n\nvoid CeresEstimation::configure()\n{\n\tparametersHelper.ReadFile(configurationFilePath);\n\tValidateParameters();\n}\n\nvoid CeresEstimation::process()\n{\n\tint numberOfCorrespondenceMaps = GetNumberOfCorrespondenceMaps(inMatches);\n\tint numberOfCameras = ComputeNumberOfCameras(numberOfCorrespondenceMaps);\n\n\t//If there are not enough correspondences, process fails.\n\tfor(int mapIndex = 0; mapIndex < numberOfCorrespondenceMaps; mapIndex++)\n\t\t{\n\t\tif ( GetNumberOfCorrespondences ( GetCorrespondenceMap(inMatches, mapIndex) ) < 4 )\n\t\t\t{\n\t\t\toutError = -1;\n\t\t\toutSuccess = false;\n\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\tstd::vector<Transform3d> transformList(numberOfCorrespondenceMaps);\n\tInitializeTransforms(transformList);\n\toutError = SolveEstimation(inMatches, numberOfCameras, transformList);\n\t\n\tif (outError > parameters.maximumAllowedError || outError < 0)\n\t\t{\n\t\toutSuccess = false;\n\t\treturn;\n\t\t}\n\n\toutSuccess = SetOutputPoses(transformList);\n}\n\nCeresEstimation::Transform3DCostFunctor::Transform3DCostFunctor(Point3D source, Point3D sink)\n\t{\n\tthis->source = source;\n\tthis->sink = sink;\n\t}\n\ntemplate <typename T>\nbool CeresEstimation::Transform3DCostFunctor::operator()(const T* const cameraTransform, T* residual) const \n\t{\n\tT originalPoint[3] = {T(source.x), T(source.y), T(source.z)};\n\tT transformedPoint[3];\n\tTransformPoint(cameraTransform, originalPoint, transformedPoint);\n\n\tresidual[0] = T(sink.x) - transformedPoint[0];\n\tresidual[1] = T(sink.y) - transformedPoint[1];\n\tresidual[2] = T(sink.z) - transformedPoint[2];\n\n\treturn true;\n\t}\n\n//There is an extra computation repeated at this step (the first order transform is computed twice)\n//Moreover, we are actually adding a method for each order transform. And we will need to create a functor for each combination, which means exponential data.\n//Consider refactoring in one single functor that takes the full list of camera transform.\ntemplate <typename T>\nbool CeresEstimation::Transform3DCostFunctor::operator()(const T* const firstCameraTransform, const T* const secondCameraTransform, T* residual) const \n\t{\n\tT originalPoint[3] = {T(source.x), T(source.y), T(source.z)};\n\tT firstOrderTransformedPoint[3];\n\tTransformPoint(firstCameraTransform, originalPoint, firstOrderTransformedPoint);\n\tT secondOrderTransformedPoint[3];\n\tTransformPoint(secondCameraTransform, firstOrderTransformedPoint, secondOrderTransformedPoint);\n\n\tresidual[0] = T(sink.x) - secondOrderTransformedPoint[0];\n\tresidual[1] = T(sink.y) - secondOrderTransformedPoint[1];\n\tresidual[2] = T(sink.z) - secondOrderTransformedPoint[2];\n\n\treturn true;\n\t}\n\ntemplate <typename T>\nvoid CeresEstimation::Transform3DCostFunctor::TransformPoint(const T* const cameraTransform, const T* const originalPoint, T* transformedPoint) const\n\t{\n\n\ttransformedPoint[0] = cameraTransform[0]*originalPoint[0] + cameraTransform[1]*originalPoint[1] + cameraTransform[2]*originalPoint[2] + cameraTransform[3];\n\ttransformedPoint[1] = cameraTransform[4]*originalPoint[0] + cameraTransform[5]*originalPoint[1] + cameraTransform[6]*originalPoint[2] + cameraTransform[7];\n\ttransformedPoint[2] = cameraTransform[8]*originalPoint[0] + cameraTransform[9]*originalPoint[1] + cameraTransform[10]*originalPoint[2] + cameraTransform[11];\n\n\t}\n\nceres::CostFunction* CeresEstimation::Transform3DCostFunctor::Create(Point3D source, Point3D sink, int transformChainLength)\n\t{\n\tif (transformChainLength == 1)\n\t\t{\n\t\treturn \n\t\t\t(\n\t\t\tnew ceres::AutoDiffCostFunction<Transform3DCostFunctor, 3, 12>\n\t\t\t\t(\n\t\t\t\tnew Transform3DCostFunctor(source, sink)\n\t\t\t\t)\n\t\t\t);\n\t\t}\n\telse if (transformChainLength == 2)\n\t\t{\n\t\treturn \n\t\t\t(\n\t\t\tnew ceres::AutoDiffCostFunction<Transform3DCostFunctor, 3, 12, 12>\n\t\t\t\t(\n\t\t\t\tnew Transform3DCostFunctor(source, sink)\n\t\t\t\t)\n\t\t\t);\n\t\t}\n\telse\n\t\t{\n\t\tASSERT(false, \"Ceres Estimation error, unhandled chain length\");\n\t\t}\n\t}\n\nconst CeresEstimation::CeresEstimationOptionsSet CeresEstimation::DEFAULT_PARAMETERS =\n{\n\t/*.maximumAllowedError =*/ 0.01,\n\t/*.maximumAllowedDeterminantError =*/ 0.05\n};\n\nint CeresEstimation::ComputeNumberOfCameras(int numberOfCorrespondenceMaps)\n\t{\n\tconst int MAXIMUM_NUMBER_OF_CAMERAS = 8;\n\tfor(int candidateNumber = 0; candidateNumber < MAXIMUM_NUMBER_OF_CAMERAS; candidateNumber++)\n\t\t{\n\t\tint expectedCorrespondencesNumber = (candidateNumber * (candidateNumber - 1)) / 2;\n\t\tif (expectedCorrespondencesNumber == numberOfCorrespondenceMaps )\n\t\t\t{\n\t\t\treturn candidateNumber;\n\t\t\t}\n\t\tASSERT(expectedCorrespondencesNumber < numberOfCorrespondenceMaps, \"CorrespondenceMaps3DSequenceToMat error, number of correspondences is not as expected\");\n\t\t}\n\t\n\tASSERT(false, \"CorrespondenceMaps3DSequenceToMatConverter error, number of images is too large\");\n\treturn 0;\n\t}\n\nvoid CeresEstimation::InitializeTransforms(std::vector<Transform3d>& transformList)\n\t{\t\n\tfor(int mapIndex = 0; mapIndex < GetNumberOfCorrespondenceMaps(inMatches); mapIndex++)\n\t\t{\n\t\tconst CorrespondenceMap3D& map = GetCorrespondenceMap(inMatches, mapIndex);\n\t\tTransform3d& transform = transformList.at(mapIndex);\n\n\t\tcv::Mat coefficientMatrix, valueMatrix;\n\t\tbool success = CreateLinearSystem(map, coefficientMatrix, valueMatrix);\n\n\t\tcv::Mat solution;\n\t\tif (success)\n\t\t\t{\n\t\t\tfloat error = 0;\n\t\t\tsolution = SolveLinearSystem(coefficientMatrix, valueMatrix, error);\n\t\t\t}\n\t\tfor(int componentIndex = 0; componentIndex < 12; componentIndex++)\n\t\t\t{\n\t\t\ttransform[componentIndex] = success ? solution.at<float>(componentIndex) : 0;\n\t\t\t}\n\t\t}\n\t}\n\nfloat CeresEstimation::SolveEstimation(const CorrespondenceMap3DWrapper::CorrespondenceMaps3DSequence& sequence, int numberOfCameras, std::vector<Transform3d>& transformList)\n\t{\n\tceres::Problem transformEstimation;\n\tint numberOfResiduals = 0;\n\tint sourceIndex = 0;\n\tint sinkIndex = 1;\n\tint firstMapIndexWithSinkAsSource = numberOfCameras - 1; //This is the first map where the current sink becomes source\n\tfor(int mapIndex = 0; mapIndex < GetNumberOfCorrespondenceMaps(sequence); mapIndex++)\n\t\t{\n\t\tconst CorrespondenceMap3D& map = GetCorrespondenceMap(sequence, mapIndex);\n\t\tfor(int correspondenceIndex = 0; correspondenceIndex < GetNumberOfCorrespondences(map); correspondenceIndex++)\n\t\t\t{\n\t\t\tPoint3D sourcePoint = GetSource(map, correspondenceIndex);\n\t\t\tPoint3D sinkPoint = GetSink(map, correspondenceIndex);\n\n\t\t\tceres::CostFunction* transform3DCostFunctor = Transform3DCostFunctor::Create ( sourcePoint, sinkPoint, 1);\n\t\t\ttransformEstimation.AddResidualBlock( transform3DCostFunctor, NULL, transformList.at(mapIndex) );\n\t\t\tnumberOfResiduals += 3;\n\n\t\t\t//These are the constraints for the double transform sourcePoint -> sinkPoint -> secondSinkPoint\n\t\t\tfor(int secondSinkIndex = sinkIndex + 1; secondSinkIndex < numberOfCameras; secondSinkIndex++)\n\t\t\t\t{\n\t\t\t\tint secondMapIndex = firstMapIndexWithSinkAsSource + secondSinkIndex - sinkIndex - 1;\n\t\t\t\tconst CorrespondenceMap3D& secondMap = GetCorrespondenceMap(sequence, secondMapIndex);\n\t\t\t\tfor(int secondCorrespondenceIndex = 0; secondCorrespondenceIndex < GetNumberOfCorrespondences(secondMap); secondCorrespondenceIndex++)\n\t\t\t\t\t{\n\t\t\t\t\tPoint3D secondSourcePoint = GetSource(secondMap, secondCorrespondenceIndex);\n\t\t\t\t\tPoint3D secondSinkPoint = GetSink(secondMap, secondCorrespondenceIndex);\n\t\t\t\t\tif (sinkPoint.x == secondSourcePoint.x && sinkPoint.y == secondSourcePoint.y)\n\t\t\t\t\t\t{\n\t\t\t\t\t\tceres::CostFunction* transform3DCostFunctor = Transform3DCostFunctor::Create ( sourcePoint, secondSinkPoint, 2);\n\t\t\t\t\t\ttransformEstimation.AddResidualBlock( transform3DCostFunctor, NULL, transformList.at(mapIndex), transformList.at(secondMapIndex) );\n\t\t\t\t\t\tnumberOfResiduals += 3;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}\n\n\t\tif (sinkIndex == numberOfCameras - 1)\n\t\t\t{\n\t\t\tsourceIndex++;\n\t\t\tsinkIndex = sourceIndex+1;\n\t\t\tfirstMapIndexWithSinkAsSource = mapIndex + 1 + (numberOfCameras - sinkIndex);\n\t\t\t}\n\t\telse\n\t\t\t{\n\t\t\tsinkIndex++;\n\t\t\tfirstMapIndexWithSinkAsSource += numberOfCameras - sinkIndex;\n\t\t\t}\n\t\t}\n\n\tif (numberOfResiduals < 6 * numberOfCameras)\n\t\t{\n\t\treturn -1;\n\t\t}\n\n\t//Calling the solver\n\tceres::Solver::Options ceresOptions;\n\tceresOptions.linear_solver_type = ceres::DENSE_SCHUR;\n\tceresOptions.minimizer_progress_to_stdout = true;\n\tceresOptions.logging_type = ceres::SILENT;\n\tceres::Solver::Summary summary;\n\tceres::Solve(ceresOptions, &transformEstimation, &summary);\n\treturn summary.final_cost / static_cast<float>(numberOfResiduals);\n\t}\n\nbool CeresEstimation::SetOutputPoses(const std::vector<Transform3d>& transformList)\n\t{\n\tClear(outTransforms);\n\tint validTransformCount = 0;\n\tfor(int poseIndex = 0; poseIndex < transformList.size(); poseIndex++)\n\t\t{\n\t\tconst Transform3d& transform = transformList.at(poseIndex);\n\t\tPose3D pose;\n\n\t\tcv::Mat rotation = (cv::Mat_<double>(3, 3) <<\n\t\t\ttransform[0], transform[1], transform[2],\n\t\t\ttransform[4], transform[5], transform[6],\n\t\t\ttransform[8], transform[9], transform[10] );\n\t\tdouble rotationDeterminant = cv::determinant(rotation);\n\t\t\n\t\tif (std::abs(rotationDeterminant) >= 1 - parameters.maximumAllowedDeterminantError && std::abs(rotationDeterminant) <= 1 + parameters.maximumAllowedDeterminantError)\n\t\t\t{\n\t\t\tcv::Mat translation = (cv::Mat_<double>(3, 1) << transform[3], transform[7], transform[11] );\n\t\t\tcv::Mat position = - rotation.inv() * translation;\n\t\t\tSetPosition(pose, position.at<double>(0,0), position.at<double>(1,0), position.at<double>(2,0));\n\n\t\t\tdouble qw = std::sqrt(1.00 + rotation.at<double>(0,0) + rotation.at<double>(1,1) + rotation.at<double>(2,2)) / 2;\n\t\t\tdouble qx = (rotation.at<double>(2,1) - rotation.at<double>(1,2)) / ( 4 * qw );\n\t\t\tdouble qy = (rotation.at<double>(0,2) - rotation.at<double>(2,0)) / ( 4 * qw );\n\t\t\tdouble qz = (rotation.at<double>(1,0) - rotation.at<double>(0,1)) / ( 4 * qw );\n\t\t\tSetOrientation(pose, qx, qy, qz, qw);\n\n\t\t\tvalidTransformCount++;\n\t\t\t}\n\t\telse\n\t\t\t{\n\t\t\tSetPosition(pose, 0, 0, 0);\n\t\t\tSetOrientation(pose, 0, 0, 0, 0);\n\t\t\t}\n\n\t\tAddPose(outTransforms, pose);\t\t\n\t\t}\n\treturn (validTransformCount > 0);\n\t}\n\n\nbool CeresEstimation::CreateLinearSystem(const CorrespondenceMap3D& map, cv::Mat& coefficientMatrix, cv::Mat& valueMatrix)\n\t{\n\tconst float EPSILON = 0.00001;\n\tconst int NUMBER_OF_DEGREES_OF_FREEDOM = 6;\n\tconst int NUMBER_OF_VARIABLES = 12;\n\n\tcoefficientMatrix = cv::Mat();\n\tvalueMatrix = cv::Mat();\n\tfor(int correspondenceIndex = 0; correspondenceIndex < GetNumberOfCorrespondences(map); correspondenceIndex++)\n\t\t{\n\t\tPoint3D source = GetSource(map, correspondenceIndex);\n\t\tPoint3D sink = GetSink(map, correspondenceIndex);\n\t\n\t\tif (source.x != source.x || source.y != source.y || source.z != source.z || sink.x != sink.x || sink.y != sink.y || sink.z != sink.z)\n\t\t\t{\n\t\t\tcontinue;\n\t\t\t}\n\n\t\tcv::Mat coefficientMatrixPart = ( cv::Mat_<float>(3, 12) << \n\t\t\tsource.x, source.y, source.z, 1,    0, 0, 0, 0,    0, 0, 0, 0,\n\t\t\t0, 0, 0, 0,   source.x, source.y, source.z, 1,     0, 0, 0, 0,\n\t\t\t0, 0, 0, 0,   0, 0, 0, 0,     source.x, source.y, source.z, 1 );\n\t\tcv::Mat valueMatrixPart = ( cv::Mat_<float>(3, 1) << sink.x, sink.y, sink.z);\n\t\t\n\t\tif (coefficientMatrix.rows == 0)\n\t\t\t{\n\t\t\tcoefficientMatrix = coefficientMatrixPart;\n\t\t\tvalueMatrix = valueMatrixPart;\n\t\t\t}\t\t\n\t\telse\n\t\t\t{\n\t\t\tcv::Mat matrixList[2] = {coefficientMatrix, coefficientMatrixPart};\n\t\t\tcv::vconcat(matrixList, 2, coefficientMatrix);\n\t\t\tmatrixList[0] = valueMatrix;\n\t\t\tmatrixList[1] = valueMatrixPart;\n\t\t\tcv::vconcat(matrixList, 2, valueMatrix);\n\t\t\t}\n\t\t}\n\n\tif ( coefficientMatrix.rows < NUMBER_OF_VARIABLES )\n\t\t{\n\t\treturn false;\n\t\t}\n\n\tcv::Mat singulaValueMatrix;\n\tcv::SVD::compute(coefficientMatrix, singulaValueMatrix);\n\tint rank = cv::countNonZero( singulaValueMatrix > EPSILON );\n\treturn ( rank >= NUMBER_OF_DEGREES_OF_FREEDOM );\n\t}\n\ncv::Mat CeresEstimation::SolveLinearSystem(cv::Mat coefficientMatrix, cv::Mat valueMatrix, float& error)\n\t{\n\tcv::Mat pseudoInverse;\n\tcv::invert(coefficientMatrix, pseudoInverse, cv::DECOMP_SVD);\n\tcv::Mat transformMatrix = pseudoInverse * valueMatrix;\n\n\tcv::Mat errorMatrix = coefficientMatrix * transformMatrix - valueMatrix;\n\terror = cv::norm(errorMatrix);\n\treturn transformMatrix;\n\t}\n\nvoid CeresEstimation::ValidateParameters()\n{\n\tASSERT(parameters.maximumAllowedError > 0, \"LeastSquaresMinimization Configuration Error: maximumAllowedError has to be positive\");\n}\n\nvoid CeresEstimation::ValidateInputs(const CorrespondenceMap3D& map)\n{\n\t\n}\n\n}\n}\n}\n\n/** @} */\n", "meta": {"hexsha": "a1525335c3e00e61b1c7f3c691e868a35fe3c7bb", "size": 13223, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "DFNs/Transform3DEstimation/CeresEstimation.cpp", "max_stars_repo_name": "H2020-InFuse/cdff", "max_stars_repo_head_hexsha": "e55fd48f9a909d0c274c3dfa4fe2704bc5071542", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-02-26T15:09:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-30T07:39:01.000Z", "max_issues_repo_path": "DFNs/Transform3DEstimation/CeresEstimation.cpp", "max_issues_repo_name": "H2020-InFuse/cdff", "max_issues_repo_head_hexsha": "e55fd48f9a909d0c274c3dfa4fe2704bc5071542", "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": "DFNs/Transform3DEstimation/CeresEstimation.cpp", "max_forks_repo_name": "H2020-InFuse/cdff", "max_forks_repo_head_hexsha": "e55fd48f9a909d0c274c3dfa4fe2704bc5071542", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-06T12:09:05.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-06T12:09:05.000Z", "avg_line_length": 33.8184143223, "max_line_length": 187, "alphanum_fraction": 0.7415866294, "num_tokens": 3612, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257653, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.474212150277241}}
{"text": "\ufeff#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Exact_predicates_exact_constructions_kernel.h>\n#include <CGAL/Simple_cartesian.h>\n\n// Graphs\n#include <CGAL/Polyhedron_3.h>\n#include <CGAL/IO/Polyhedron_iostream.h>\n#include <CGAL/Surface_mesh.h>\n#include <CGAL/boost/graph/graph_traits_Regular_triangulation_2.h>\n#include <CGAL/boost/graph/properties_Regular_triangulation_2.h>\n\n#include <CGAL/Polygon_mesh_processing/locate.h>\n\n#include <CGAL/AABB_tree.h>\n#include <CGAL/AABB_face_graph_triangle_primitive.h>\n#include <CGAL/Bbox_3.h>\n#include <CGAL/boost/graph/io.h>\n#include <CGAL/boost/graph/named_params_helper.h>\n#include <CGAL/boost/graph/generators.h>\n#include <CGAL/boost/graph/helpers.h>\n#include <CGAL/Dimension.h>\n#include <CGAL/Kernel_traits.h>\n#include <CGAL/Origin.h>\n#include <CGAL/property_map.h>\n#include <CGAL/Random.h>\n#include <CGAL/Unique_hash_map.h>\n\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/properties.hpp>\n#include <boost/optional.hpp>\n\n#include <fstream>\n#include <iostream>\n#include <limits>\n#include <map>\n#include <set>\n#include <type_traits>\n#include <utility>\n#include <vector>\n\nnamespace PMP = CGAL::Polygon_mesh_processing;\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel    EPICK;\ntypedef CGAL::Exact_predicates_exact_constructions_kernel      EPECK;\n\ntypedef CGAL::Simple_cartesian<typename CGAL::internal::Exact_field_selector<double>::Type> Exact_kernel;\n\ntemplate<typename AABB_tree>\ntypename CGAL::Kernel_traits<typename AABB_tree::AABB_traits::Point_3>::type::Ray_2\nrandom_2D_ray(const AABB_tree& aabb_tree, CGAL::Random& rnd)\n{\n  typedef typename AABB_tree::AABB_traits::Point_3           Point_3;\n  typedef typename CGAL::Kernel_traits<Point_3>::type        Kernel;\n  typedef typename Kernel::FT                                FT;\n  typedef typename Kernel::Point_2                           Point_2;\n  typedef typename Kernel::Ray_2                             Ray_2;\n\n  const CGAL::Bbox_3& bbox = aabb_tree.bbox();\n\n  FT px = (bbox.xmin() == bbox.xmax()) ? bbox.xmin() : rnd.get_double(bbox.xmin(), bbox.xmax());\n  FT py = (bbox.ymin() == bbox.ymax()) ? bbox.ymin() : rnd.get_double(bbox.ymin(), bbox.ymax());\n\n  FT qx = (bbox.xmin() == bbox.xmax()) ? bbox.xmin() : rnd.get_double(bbox.xmin(), bbox.xmax());\n  FT qy = (bbox.ymin() == bbox.ymax()) ? bbox.ymin() : rnd.get_double(bbox.ymin(), bbox.ymax());\n\n  return Ray_2(Point_2(px, py), Point_2(qx, qy));\n}\n\ntemplate<typename AABB_tree>\ntypename CGAL::Kernel_traits<typename AABB_tree::AABB_traits::Point_3>::type::Ray_3\nrandom_3D_ray(const AABB_tree& aabb_tree, CGAL::Random& rnd)\n{\n  typedef typename AABB_tree::AABB_traits::Point_3           Point_3;\n  typedef typename CGAL::Kernel_traits<Point_3>::type        Kernel;\n  typedef typename Kernel::FT                                FT;\n  typedef typename Kernel::Ray_3                             Ray_3;\n\n  const CGAL::Bbox_3& bbox = aabb_tree.bbox();\n\n  FT px = (bbox.xmin() == bbox.xmax()) ? bbox.xmin() : rnd.get_double(bbox.xmin(), bbox.xmax());\n  FT py = (bbox.ymin() == bbox.ymax()) ? bbox.ymin() : rnd.get_double(bbox.ymin(), bbox.ymax());\n  FT pz = (bbox.zmin() == bbox.zmax()) ? bbox.zmin() : rnd.get_double(bbox.zmin(), bbox.zmax());\n\n  FT qx = (bbox.xmin() == bbox.xmax()) ? bbox.xmin() : rnd.get_double(bbox.xmin(), bbox.xmax());\n  FT qy = (bbox.ymin() == bbox.ymax()) ? bbox.ymin() : rnd.get_double(bbox.ymin(), bbox.ymax());\n  FT qz = (bbox.zmin() == bbox.zmax()) ? bbox.zmin() : rnd.get_double(bbox.zmin(), bbox.zmax());\n\n  return Ray_3(Point_3(px, py, pz), Point_3(qx, qy, qz));\n}\n\ntemplate<typename FT>\nbool is_equal(const FT& a, const FT& b)\n{\n  if(std::is_floating_point<FT>::value)\n    return (CGAL::abs(a - b) <= 1e-7); // numeric_limits' epsilon is too restrictive...\n  else\n    return (a == b);\n}\n\ntemplate<typename K, typename G>\nvoid test_snappers(const G& g)\n{\n  std::cout << \"  test snappers...\" << std::endl;\n\n  typedef typename K::FT                                              FT;\n\n  PMP::Barycentric_coordinates<FT> coords = CGAL::make_array(FT(1e-6), FT(0.9999999999999999999), FT(1e-7));\n  PMP::Face_location<G, FT> loc = std::make_pair(*(faces(g).first), coords);\n\n  // ---------------------------------------------------------------------------\n  PMP::internal::snap_coordinates_to_border<FT>(coords); // uses numeric_limits' epsilon()\n  assert(coords[0] == FT(1e-6) && coords[1] == FT(1) && coords[2] == FT(1e-7));\n\n  PMP::internal::snap_coordinates_to_border(coords, FT(1e-5));\n  assert(coords[0] == FT(0) && coords[1] == FT(1) && coords[2] == FT(0));\n\n  // ---------------------------------------------------------------------------\n  PMP::internal::snap_location_to_border<FT>(loc, g); // uses numeric_limits' epsilon()\n  assert(!PMP::is_on_face_border(loc, g));\n\n  PMP::internal::snap_location_to_border(loc, g, FT(1e-7));\n  assert(PMP::is_on_face_border(loc, g));\n}\n\ntemplate <typename K, int>\nstruct Point_to_bare_point\n{\n  typedef typename K::Point_2 type;\n};\n\ntemplate <typename K>\nstruct Point_to_bare_point<K, 3>\n{\n  typedef typename K::Point_3 type;\n};\n\ntemplate<typename K, typename G, typename VPM>\nvoid test_constructions(const G& g,\n                        const VPM vpm,\n                        CGAL::Random& rnd)\n{\n  std::cout << \"  test constructions...\" << std::endl;\n\n  typedef typename boost::graph_traits<G>::vertex_descriptor                 vertex_descriptor;\n  typedef typename boost::graph_traits<G>::halfedge_descriptor               halfedge_descriptor;\n  typedef typename boost::graph_traits<G>::face_descriptor                   face_descriptor;\n  typedef typename PMP::descriptor_variant<G>                                descriptor_variant;\n\n  typedef typename boost::property_traits<VPM>::value_type                        Point;\n  typedef typename boost::property_traits<VPM>::reference                         Point_reference;\n  typedef typename K::FT                                                          FT;\n  typedef typename Point_to_bare_point<K, Point::Ambient_dimension::value>::type  Bare_point;\n\n  typedef typename PMP::Barycentric_coordinates<FT>                          Barycentric_coordinates;\n  typedef typename PMP::Face_location<G, FT>                                 Face_location;\n\n  face_descriptor f = CGAL::internal::random_face_in_mesh(g, rnd);\n  halfedge_descriptor h = halfedge(f, g);\n  vertex_descriptor v = source(h, g);\n\n  Point_reference p = get(vpm, v);\n  Point_reference q = get(vpm, target(h, g));\n  Point_reference r = get(vpm, target(next(h, g), g));\n\n  const Bare_point bp(p);\n  const Bare_point bq(q);\n  const Bare_point br(r);\n\n  Barycentric_coordinates bar;\n  Face_location loc;\n  loc.first = f;\n\n  // ---------------------------------------------------------------------------\n  bar = PMP::barycentric_coordinates(p, q, r, p, K());\n  assert(is_equal(bar[0], FT(1)) && is_equal(bar[1], FT(0)) && is_equal(bar[2], FT(0)));\n  bar = PMP::barycentric_coordinates(p, q, r, q, K());\n  assert(is_equal(bar[0], FT(0)) && is_equal(bar[1], FT(1)) && is_equal(bar[2], FT(0)));\n  bar = PMP::barycentric_coordinates(p, q, r, r, K());\n  assert(is_equal(bar[0], FT(0)) && is_equal(bar[1], FT(0)) && is_equal(bar[2], FT(1)));\n\n  Point mp = Point(CGAL::midpoint(bp, bq));\n  bar = PMP::barycentric_coordinates(p, q, r, mp);\n  assert(is_equal(bar[0], FT(0.5)) && is_equal(bar[1], FT(0.5)) && is_equal(bar[2], FT(0)));\n\n  int n = 100;\n  while(n --> 0) // :)\n  {\n    const FT a = rnd.get_double(-1., 1.);\n    const FT b = rnd.get_double(-1., 1.);\n    const FT c = 1. - a - b;\n\n    // Point to location and inversely\n    Bare_point barycentric_pt = CGAL::barycenter(bp, a, bq, b, br, c);\n    bar = PMP::barycentric_coordinates(p, q, r, Point(barycentric_pt));\n    assert(is_equal(bar[0], a) && is_equal(bar[1], b) && is_equal(bar[2], c));\n\n    loc.second = bar;\n    const Bare_point barycentric_pt_2 =\n      Bare_point(PMP::construct_point(loc, g,\n                                      CGAL::parameters::vertex_point_map(vpm)\n                                                       .geom_traits(K())));\n\n    const FT sq_dist = CGAL::squared_distance(barycentric_pt, barycentric_pt_2);\n    assert(is_equal(sq_dist, FT(0)));\n  }\n\n  // ---------------------------------------------------------------------------\n  loc = std::make_pair(f, CGAL::make_array(FT(0.3), FT(0.4), FT(0.3)));\n  descriptor_variant dv = PMP::get_descriptor_from_location(loc, g);\n  const face_descriptor* fd = boost::get<face_descriptor>(&dv);\n  assert(fd);\n\n  loc = std::make_pair(f, CGAL::make_array(FT(0.5), FT(0.5), FT(0)));\n  dv = PMP::get_descriptor_from_location(loc, g);\n  const halfedge_descriptor* hd = boost::get<halfedge_descriptor>(&dv);\n  assert(hd);\n\n  loc = std::make_pair(f, CGAL::make_array(FT(1), FT(0), FT(0)));\n  assert(PMP::is_on_vertex(loc, source(halfedge(f, g), g), g));\n  dv = PMP::get_descriptor_from_location(loc, g);\n  if(const vertex_descriptor* v = boost::get<vertex_descriptor>(&dv)) { } else { assert(false); }\n\n  // ---------------------------------------------------------------------------\n  // just to check the API\n  PMP::construct_point(loc, g);\n  PMP::construct_point(loc, g, CGAL::parameters::default_values());\n}\n\ntemplate<typename K, typename G>\nvoid test_random_entities(const G& g, CGAL::Random& rnd)\n{\n  std::cout << \"  test random entities...\" << std::endl;\n\n  typedef typename boost::graph_traits<G>::halfedge_descriptor               halfedge_descriptor;\n  typedef typename boost::graph_traits<G>::face_descriptor                   face_descriptor;\n\n  typedef typename K::FT                                                     FT;\n  typedef typename PMP::Face_location<G, FT>                                 Face_location;\n\n  // ---------------------------------------------------------------------------\n  Face_location loc;\n\n  halfedge_descriptor h = CGAL::internal::random_halfedge_in_mesh(g, rnd);\n  if(is_border(h, g))\n    h = opposite(h, g);\n  face_descriptor f = CGAL::internal::random_face_in_mesh(g, rnd);\n\n  int nn = 100;\n  while(nn --> 0) // the infamous 'go to zero' operator\n  {\n    loc = PMP::random_location_on_mesh<FT>(g, rnd);\n    assert(loc.first != boost::graph_traits<G>::null_face());\n    assert(loc.second[0] >= FT(0) && loc.second[0] <= FT(1) &&\n           loc.second[1] >= FT(0) && loc.second[1] <= FT(1) &&\n           loc.second[2] >= FT(0) && loc.second[2] <= FT(1));\n\n    loc = PMP::random_location_on_face<FT>(f, g, rnd);\n    assert(loc.first == f);\n    assert(loc.second[0] >= FT(0) && loc.second[0] <= FT(1) &&\n           loc.second[1] >= FT(0) && loc.second[1] <= FT(1) &&\n           loc.second[2] >= FT(0) && loc.second[2] <= FT(1));\n\n    loc = PMP::random_location_on_halfedge<FT>(h, g, rnd);\n    assert(loc.first == face(h, g));\n    assert(loc.second[0] >= FT(0) && loc.second[0] <= FT(1) &&\n           loc.second[1] >= FT(0) && loc.second[1] <= FT(1) &&\n           loc.second[2] >= FT(0) && loc.second[2] <= FT(1));\n    int h_id = CGAL::halfedge_index_in_face(h, g);\n    assert(loc.second[(h_id+2)%3] == FT(0));\n  }\n}\n\ntemplate<typename K, typename G>\nvoid test_helpers(const G& g, CGAL::Random& rnd)\n{\n  std::cout << \"  test helpers...\" << std::endl;\n\n  typedef typename boost::graph_traits<G>::vertex_descriptor                 vertex_descriptor;\n  typedef typename boost::graph_traits<G>::halfedge_descriptor               halfedge_descriptor;\n  typedef typename boost::graph_traits<G>::face_descriptor                   face_descriptor;\n\n  typedef typename K::FT                                                     FT;\n  typedef typename PMP::Face_location<G, FT>                                 Face_location;\n\n  face_descriptor f = CGAL::internal::random_face_in_mesh(g, rnd);\n  halfedge_descriptor h = halfedge(f, g);\n  vertex_descriptor v = source(h, g);\n\n  // ---------------------------------------------------------------------------\n  // Local index\n  int pos = CGAL::vertex_index_in_face(v, f, g);\n  assert(pos == 0);\n  pos = CGAL::vertex_index_in_face(target(h, g), f, g);\n  assert(pos == 1);\n  pos = CGAL::vertex_index_in_face(target(next(h, g), g), f, g);\n  assert(pos == 2);\n\n  pos = CGAL::halfedge_index_in_face(h, g);\n  assert(pos == 0);\n  pos = CGAL::halfedge_index_in_face(next(h, g), g);\n  assert(pos == 1);\n  pos = CGAL::halfedge_index_in_face(prev(h, g), g);\n  assert(pos == 2);\n\n  // ---------------------------------------------------------------------------\n  // Incident faces\n  Face_location loc = PMP::random_location_on_face<FT>(f, g, rnd);\n  std::set<face_descriptor> s;\n  PMP::internal::incident_faces(loc, g, std::inserter(s, s.begin()));\n  assert(PMP::is_on_face_border(loc, g) || s.size() == 1);\n\n  loc = PMP::random_location_on_halfedge<FT>(h, g, rnd);\n  std::vector<face_descriptor> vec;\n  PMP::internal::incident_faces(loc, g, std::back_inserter(vec));\n  assert(PMP::is_on_vertex(loc, source(h, g), g) ||\n         PMP::is_on_vertex(loc, target(h, g), g) ||\n         vec.size() == 2);\n}\n\ntemplate<typename K, typename G>\nvoid test_predicates(const G& g, CGAL::Random& rnd)\n{\n  std::cout << \"  test predicates...\" << std::endl;\n\n  typedef typename K::FT                                                     FT;\n\n  typedef typename boost::graph_traits<G>::vertex_descriptor                 vertex_descriptor;\n  typedef typename boost::graph_traits<G>::halfedge_descriptor               halfedge_descriptor;\n  typedef typename boost::graph_traits<G>::face_descriptor                   face_descriptor;\n\n  typedef typename PMP::Face_location<G, FT>                                 Face_location;\n\n  face_descriptor f = CGAL::internal::random_face_in_mesh(g, rnd);\n  halfedge_descriptor h = halfedge(f, g);\n  vertex_descriptor v = source(h, g);\n\n  // ---------------------------------------------------------------------------\n  Face_location loc(f, CGAL::make_array(FT(1), FT(0), FT(0)));\n  assert(PMP::is_on_vertex<FT>(loc, v, g));\n  loc = Face_location(f, CGAL::make_array(FT(0), FT(1), FT(0)));\n  assert(PMP::is_on_vertex<FT>(loc, target(h, g), g));\n  loc = Face_location(f, CGAL::make_array(FT(0), FT(0), FT(1)));\n  assert(PMP::is_on_vertex<FT>(loc, target(next(h, g), g), g));\n  loc = Face_location(f, CGAL::make_array(FT(-1), FT(1), FT(1)));\n  assert(!PMP::is_on_vertex<FT>(loc, target(next(h, g), g), g));\n\n  // ---------------------------------------------------------------------------\n  loc = Face_location(f, CGAL::make_array(FT(0.5), FT(0.5), FT(0)));\n  assert(PMP::is_on_halfedge<FT>(loc, h, g));\n  loc = Face_location(f, CGAL::make_array(FT(0), FT(0.5), FT(0.5)));\n  assert(PMP::is_on_halfedge<FT>(loc, next(h, g), g));\n  loc = Face_location(f, CGAL::make_array(FT(-0.5), FT(1.5), FT(0)));\n  assert(!PMP::is_on_halfedge<FT>(loc, h, g));\n  loc = Face_location(f, CGAL::make_array(FT(0.1), FT(-0.6), FT(1.5)));\n  assert(!PMP::is_on_halfedge<FT>(loc, h, g));\n\n  // ---------------------------------------------------------------------------\n  loc = Face_location(f, CGAL::make_array(FT(0.3), FT(0.3), FT(0.4)));\n  assert(PMP::is_in_face<FT>(loc, g));\n  loc = Face_location(f, CGAL::make_array(FT(0), FT(0), FT(1)));\n  assert(PMP::is_in_face<FT>(loc, g));\n  loc = Face_location(f, CGAL::make_array(FT(0), FT(2), FT(-1)));\n  assert(!PMP::is_in_face<FT>(loc, g));\n\n  // ---------------------------------------------------------------------------\n  loc = Face_location(f, CGAL::make_array(FT(0.3), FT(0.3), FT(0.4)));\n  assert(!PMP::is_on_face_border<FT>(loc, g));\n  loc = Face_location(f, CGAL::make_array(FT(0), FT(0.6), FT(0.4)));\n  assert(PMP::is_on_face_border<FT>(loc, g));\n  loc = Face_location(f, CGAL::make_array(FT(0), FT(0), FT(1)));\n  assert(PMP::is_on_face_border<FT>(loc, g));\n  loc = Face_location(f, CGAL::make_array(FT(-0.2), FT(0), FT(1.2)));\n  assert(!PMP::is_on_face_border(loc, g));\n\n  // ---------------------------------------------------------------------------\n  int max = 1000, counter = 0;\n  typename boost::graph_traits<G>::halfedge_iterator hit, hend;\n  boost::tie(hit, hend) = halfedges(g);\n  for(; hit!=hend; ++hit)\n  {\n    const halfedge_descriptor h = *hit;\n    if(face(h, g) == boost::graph_traits<G>::null_face())\n      continue;\n\n    const int id_of_h = CGAL::halfedge_index_in_face(h, g);\n    const face_descriptor f = face(h, g);\n    loc.first = f;\n\n    loc.second[id_of_h] = FT(1);\n    loc.second[(id_of_h+1)%3] = FT(0);\n    loc.second[(id_of_h+2)%3] = FT(0);\n    boost::optional<halfedge_descriptor> opt_hd = CGAL::is_border(source(h, g), g);\n    assert(PMP::is_on_mesh_border<FT>(loc, g) == (opt_hd != boost::none));\n\n    loc.second[id_of_h] = FT(0.5);\n    loc.second[(id_of_h+1)%3] = FT(0.5);\n    assert(PMP::is_on_mesh_border<FT>(loc, g) == CGAL::is_border(edge(h, g), g));\n\n    // Even if the point does lie on the border of the mesh, 'false' is returned because\n    // another face descriptor should be used.\n    loc.second[id_of_h] = -0.5;\n    loc.second[(id_of_h+1)%3] = 1.5;\n    assert(!PMP::is_on_mesh_border<FT>(loc, g));\n\n    if(++counter > max)\n      break;\n  }\n}\n\ntemplate<typename K, typename G, typename VPM>\nvoid test_locate_in_face(const G& g,\n                         const VPM vpm,\n                         CGAL::Random& rnd)\n{\n  std::cout << \"  test locate_in_face()...\" << std::endl;\n\n  typedef typename boost::property_traits<VPM>::reference                    Point_reference;\n  typedef typename K::FT                                                     FT;\n\n  typedef typename boost::graph_traits<G>::vertex_descriptor                 vertex_descriptor;\n  typedef typename boost::graph_traits<G>::halfedge_descriptor               halfedge_descriptor;\n  typedef typename boost::graph_traits<G>::face_descriptor                   face_descriptor;\n\n  typedef typename PMP::Face_location<G, FT>                                 Face_location;\n\n  const face_descriptor f = CGAL::internal::random_face_in_mesh(g, rnd);\n  const halfedge_descriptor h = halfedge(f, g);\n  const vertex_descriptor v = target(h, g);\n\n  Face_location loc;\n  FT a = 0.1;\n  Point_reference p = get(vpm, v);\n\n  loc = PMP::locate_vertex<FT>(v, g);\n  assert(is_equal(loc.second[CGAL::vertex_index_in_face(v, loc.first, g)], FT(1)));\n  assert(is_equal(loc.second[(CGAL::vertex_index_in_face(v, loc.first, g)+1)%3], FT(0)));\n  assert(is_equal(loc.second[(CGAL::vertex_index_in_face(v, loc.first, g)+2)%3], FT(0)));\n\n  loc = PMP::locate_vertex<FT>(v, f, g);\n  assert(loc.first == f);\n  assert(is_equal(loc.second[0], FT(0)) && is_equal(loc.second[1], FT(1)) && is_equal(loc.second[2], FT(0)));\n\n  loc = PMP::locate_on_halfedge<FT>(h, a, g);\n  const int h_id = CGAL::halfedge_index_in_face(h, g);\n  assert(loc.first == f && is_equal(loc.second[(h_id+2)%3], FT(0)));\n\n  loc = PMP::locate_in_face(p, f, g, CGAL::parameters::vertex_point_map(vpm).geom_traits(K()));\n  int v_id = CGAL::vertex_index_in_face(v, f, g);\n  assert(loc.first == f && is_equal(loc.second[v_id], FT(1)));\n\n  // Internal vertex point pmap\n  typedef typename boost::property_map_value<G, CGAL::vertex_point_t>::type     Point;\n\n  Point p2 = get(CGAL::vertex_point, g, v);\n  PMP::locate_in_face(p2, f, g);\n  assert(loc.first == f && is_equal(loc.second[v_id], FT(1)));\n\n  // ---------------------------------------------------------------------------\n  loc.second[0] = FT(0.2);\n  loc.second[1] = FT(0.8);\n  loc.second[2] = FT(0);\n\n  halfedge_descriptor neigh_hd = opposite(halfedge(f, g), g);\n  face_descriptor neigh_f = face(neigh_hd, g);\n\n  // Want to check good correspondence seen from one side and the other. If unfortunately\n  // we have selected a border face, can't do anything!\n  if(neigh_f != boost::graph_traits<G>::null_face())\n  {\n    int neigh_hd_id = CGAL::halfedge_index_in_face(neigh_hd, g);\n    Face_location neigh_loc;\n    neigh_loc.first = neigh_f;\n    neigh_loc.second[neigh_hd_id] = FT(0.3);\n    neigh_loc.second[(neigh_hd_id+1)%3] = FT(0.7);\n    neigh_loc.second[(neigh_hd_id+2)%3] = FT(0);\n\n    PMP::locate_in_adjacent_face(loc, neigh_f, g);\n\n    assert(PMP::locate_in_common_face<FT>(loc, neigh_loc, g));\n\n    assert(PMP::locate_in_common_face<FT>(loc, p, neigh_loc, g, CGAL::parameters::vertex_point_map(vpm).geom_traits(K())));\n    assert(PMP::locate_in_common_face<FT>(loc, p, neigh_loc, g, CGAL::parameters::vertex_point_map(vpm).geom_traits(K()), 1e-7));\n  }\n}\n\ntemplate <typename K, typename VPM,\n          int dim = CGAL::Ambient_dimension<typename boost::property_traits<VPM>::value_type>::value>\nstruct Locate_with_AABB_tree_Tester // 2D case\n{\n  template <typename G>\n  void test(const G& g, const VPM vpm, CGAL::Random& rnd) const\n  {\n    std::cout << \"  test locate_with_AABB_tree (2D)...\" << std::endl;\n\n    typedef typename boost::property_traits<VPM>::reference                    Point_reference;\n\n    typedef typename K::FT                                                     FT;\n    typedef typename K::Ray_2                                                  Ray_2;\n    typedef typename K::Ray_3                                                  Ray_3;\n    typedef typename K::Point_3                                                Point_3;\n\n    typedef typename boost::graph_traits<G>::vertex_descriptor                 vertex_descriptor;\n    typedef typename boost::graph_traits<G>::halfedge_descriptor               halfedge_descriptor;\n    typedef typename boost::graph_traits<G>::face_descriptor                   face_descriptor;\n\n    typedef typename PMP::Face_location<G, FT>                                 Face_location;\n\n    face_descriptor f = CGAL::internal::random_face_in_mesh(g, rnd);\n    halfedge_descriptor h = halfedge(f, g);\n    vertex_descriptor v = target(h, g);\n\n    // ---------------------------------------------------------------------------\n    typedef typename boost::property_traits<VPM>::value_type                   Intrinsic_point;\n    typedef PMP::internal::Point_to_Point_3<G, Intrinsic_point>                Intrinsic_point_to_Point_3;\n    typedef PMP::internal::Point_to_Point_3_VPM<G, VPM>                        WrappedVPM;\n    typedef CGAL::AABB_face_graph_triangle_primitive<G, WrappedVPM>            AABB_face_graph_primitive;\n    typedef CGAL::AABB_traits<K, AABB_face_graph_primitive>                    AABB_face_graph_traits;\n\n    CGAL_static_assertion((std::is_same<typename AABB_face_graph_traits::Point_3, Point_3>::value));\n\n    Intrinsic_point_to_Point_3 to_p3;\n\n    CGAL::AABB_tree<AABB_face_graph_traits> tree_a;\n    Point_reference p_a = get(vpm, v);\n    const Point_3& p3_a = to_p3(p_a);\n\n    CGAL::AABB_tree<AABB_face_graph_traits> tree_b;\n    WrappedVPM vpm_b(vpm);\n    // ---------------------------------------------------------------------------\n\n    PMP::build_AABB_tree(g, tree_a, CGAL::parameters::vertex_point_map(vpm));\n    PMP::build_AABB_tree(g, tree_b, CGAL::parameters::vertex_point_map(vpm_b));\n    assert(tree_b.size() == num_faces(g));\n\n    Face_location loc = PMP::locate_with_AABB_tree(p_a, tree_a, g, CGAL::parameters::vertex_point_map(vpm));\n\n    // sanitize otherwise some test platforms fail\n    PMP::internal::snap_location_to_border(loc, g, FT(1e-7));\n\n    assert(PMP::is_on_vertex(loc, v, g)); // might fail du to precision issues...\n    assert(is_equal(loc.second[CGAL::vertex_index_in_face(v, loc.first, g)], FT(1)));\n    assert(is_equal(loc.second[(CGAL::vertex_index_in_face(v, loc.first, g)+1)%3], FT(0)));\n    assert(is_equal(loc.second[(CGAL::vertex_index_in_face(v, loc.first, g)+2)%3], FT(0)));\n    assert(is_equal(CGAL::squared_distance(to_p3(\n      PMP::construct_point<FT>(loc, g, CGAL::parameters::vertex_point_map(vpm))), p3_a), FT(0)));\n\n    loc = PMP::locate_with_AABB_tree(p_a, tree_a, g, CGAL::parameters::vertex_point_map(vpm));\n    assert(is_equal(CGAL::squared_distance(to_p3(\n      PMP::construct_point<FT>(loc, g, CGAL::parameters::vertex_point_map(vpm))), p3_a), FT(0)));\n\n    // ---------------------------------------------------------------------------\n    loc = PMP::locate(p_a, g, CGAL::parameters::vertex_point_map(vpm));\n    assert(is_equal(CGAL::squared_distance(to_p3(\n      PMP::construct_point(loc, g, CGAL::parameters::vertex_point_map(vpm))), p3_a), FT(0)));\n    assert(PMP::is_in_face(loc, g));\n\n    loc = PMP::locate_with_AABB_tree(CGAL::ORIGIN, tree_b, g, CGAL::parameters::vertex_point_map(vpm_b));\n    assert(PMP::is_in_face(loc, g));\n\n    loc = PMP::locate(CGAL::ORIGIN, g, CGAL::parameters::vertex_point_map(vpm_b));\n    assert(PMP::is_in_face(loc, g));\n\n    // ---------------------------------------------------------------------------\n    Ray_2 r2 = random_2D_ray<CGAL::AABB_tree<AABB_face_graph_traits> >(tree_a, rnd);\n    loc = PMP::locate_with_AABB_tree(r2, tree_a, g, CGAL::parameters::vertex_point_map(vpm));\n    if(loc.first != boost::graph_traits<G>::null_face())\n      assert(PMP::is_in_face(loc, g));\n\n    Ray_3 r3 = random_3D_ray<CGAL::AABB_tree<AABB_face_graph_traits> >(tree_b, rnd);\n    loc = PMP::locate_with_AABB_tree(r3, tree_b, g, CGAL::parameters::vertex_point_map(vpm_b)\n                                                                     .geom_traits(K()));\n  }\n};\n\ntemplate <typename K>\nstruct My_3D_Point\n{\n  typedef typename K::FT FT;\n\n  typedef K R; // so that we can use Kernel_traits\n  typedef CGAL::Dimension_tag<3>  Ambient_dimension;\n  typedef CGAL::Dimension_tag<0>  Feature_dimension;\n\n  My_3D_Point() { }\n  My_3D_Point(const CGAL::Origin& /*o*/) : cx(0), cy(0), cz(0) { }\n  My_3D_Point(const FT x, const FT y, const FT z) : cx(x), cy(y), cz(z) { }\n\n  FT x() const { return cx; }\n  FT y() const { return cy; }\n  FT z() const { return cz; }\n\nprivate:\n  FT cx, cy, cz;\n};\n\ntemplate <typename K, typename VPM>\nstruct Locate_with_AABB_tree_Tester<K, VPM, 3> // 3D\n{\n  template <typename G>\n  void test(const G& g, const VPM vpm, CGAL::Random& rnd) const\n  {\n    std::cout << \"  test locate_with_AABB_tree (3D)...\" << std::endl;\n\n    typedef typename boost::property_traits<VPM>::reference                    Point_reference;\n\n    typedef typename K::FT                                                     FT;\n    typedef typename K::Ray_3                                                  Ray_3;\n\n    typedef typename boost::graph_traits<G>::vertex_descriptor                 vertex_descriptor;\n    typedef typename boost::graph_traits<G>::halfedge_descriptor               halfedge_descriptor;\n    typedef typename boost::graph_traits<G>::face_descriptor                   face_descriptor;\n\n    typedef typename PMP::Face_location<G, FT>                                 Face_location;\n\n    face_descriptor f = CGAL::internal::random_face_in_mesh(g, rnd);\n    halfedge_descriptor h = halfedge(f, g);\n    vertex_descriptor v = target(h, g);\n\n    // ---------------------------------------------------------------------------\n    typedef CGAL::AABB_face_graph_triangle_primitive<G, VPM>                   AABB_face_graph_primitive;\n    typedef CGAL::AABB_traits<K, AABB_face_graph_primitive>                    AABB_face_graph_traits;\n\n    typedef typename K::Point_3                            Point_3;\n    CGAL_static_assertion((std::is_same<typename AABB_face_graph_traits::Point_3, Point_3>::value));\n\n    CGAL::AABB_tree<AABB_face_graph_traits> tree_a;\n    Point_reference p3_a = get(vpm, v);\n\n    // below tests the case where the value type of the VPM is not Kernel::Point_3\n    typedef My_3D_Point<K>                                                     Custom_point;\n    typedef std::map<vertex_descriptor, Custom_point>                          Custom_map;\n    typedef boost::associative_property_map<Custom_map>                        Custom_VPM;\n    typedef PMP::internal::Point_to_Point_3_VPM<G, Custom_VPM>                 WrappedVPM;\n    typedef CGAL::AABB_face_graph_triangle_primitive<G, WrappedVPM>            AABB_face_graph_primitive_with_WVPM;\n    typedef CGAL::AABB_traits<K, AABB_face_graph_primitive_with_WVPM>          AABB_face_graph_traits_with_WVPM;\n\n    CGAL::AABB_tree<AABB_face_graph_traits_with_WVPM> tree_b;\n    Custom_map custom_map;\n    for(vertex_descriptor vd : vertices(g))\n    {\n      const Point_reference p = get(vpm, vd);\n      custom_map[vd] = Custom_point(p.x(), p.y(), p.z());\n    }\n\n    Custom_VPM custom_vpm(custom_map);\n    WrappedVPM custom_vpm_3D(custom_vpm);\n    // ---------------------------------------------------------------------------\n\n    PMP::build_AABB_tree(g, tree_a); // just for the API\n    assert(tree_a.size() == num_faces(g));\n\n    PMP::build_AABB_tree(g, tree_a, CGAL::parameters::vertex_point_map(vpm));\n    PMP::build_AABB_tree(g, tree_b, CGAL::parameters::vertex_point_map(custom_vpm_3D));\n    assert(tree_b.size() == num_faces(g));\n\n    Face_location loc = PMP::locate_with_AABB_tree(p3_a, tree_a, g, CGAL::parameters::vertex_point_map(vpm));\n    assert(is_equal(loc.second[CGAL::vertex_index_in_face(v, loc.first, g)], FT(1)));\n    assert(is_equal(loc.second[(CGAL::vertex_index_in_face(v, loc.first, g)+1)%3], FT(0)));\n    assert(is_equal(loc.second[(CGAL::vertex_index_in_face(v, loc.first, g)+2)%3], FT(0)));\n    assert(is_equal(CGAL::squared_distance(PMP::construct_point(loc, g), p3_a), FT(0)));\n\n    loc = PMP::locate_with_AABB_tree(p3_a, tree_a, g, CGAL::parameters::vertex_point_map(vpm));\n    assert(is_equal(CGAL::squared_distance(PMP::construct_point(loc, g), p3_a), FT(0)));\n\n    // ---------------------------------------------------------------------------\n    loc = PMP::locate(p3_a, g, CGAL::parameters::snapping_tolerance(1e-7));\n    assert(is_equal(CGAL::squared_distance(PMP::construct_point(loc, g), p3_a), FT(0)));\n    assert(PMP::is_in_face(loc, g));\n\n    loc = PMP::locate_with_AABB_tree(CGAL::ORIGIN, tree_b, g, CGAL::parameters::vertex_point_map(custom_vpm_3D));\n    assert(PMP::is_in_face(loc, g));\n\n    // Doesn't necessarily have to wrap with a P_to_P3: it can be done automatically internally\n    loc = PMP::locate(CGAL::ORIGIN, g, CGAL::parameters::vertex_point_map(custom_vpm));\n    assert(PMP::is_in_face(loc, g));\n\n    // ---------------------------------------------------------------------------\n    Ray_3 r3 = random_3D_ray<CGAL::AABB_tree<AABB_face_graph_traits_with_WVPM> >(tree_b, rnd);\n    loc = PMP::locate_with_AABB_tree(r3, tree_b, g, CGAL::parameters::vertex_point_map(custom_vpm_3D));\n  }\n};\n\n\ntemplate<typename K, typename G, typename VPM>\nvoid test_locate(const G& g,\n                 const VPM vpm,\n                 CGAL::Random& rnd)\n{\n  assert(num_vertices(g) != 0 && num_faces(g) != 0);\n\n  test_snappers<K>(g);\n  test_constructions<K>(g, vpm, rnd);\n  test_random_entities<K>(g, rnd);\n  test_helpers<K>(g, rnd);\n  test_predicates<K>(g, rnd);\n  test_locate_in_face<K>(g, vpm, rnd);\n\n  // This test has slight syntax changes between 2D and 3D (e.g. testing ray_2 in 3D makes no sense)\n  Locate_with_AABB_tree_Tester<K, VPM> AABB_tester;\n  AABB_tester.test(g, vpm, rnd);\n}\n\ntemplate<typename K, typename G>\nvoid test_locate(const G& g, CGAL::Random& rnd)\n{\n  return test_locate<K>(g, CGAL::get_const_property_map(boost::vertex_point, g), rnd);\n}\n\ntemplate<typename K>\nvoid test_2D_triangulation(const std::string fname, CGAL::Random& rnd)\n{\n  typedef CGAL::Regular_triangulation_2<K>                    RT;\n\n  std::cout << \"Testing Regular_triangulation_2 \" << fname;\n\n  std::ifstream in(fname);\n  assert(in.good());\n\n  RT tr;\n  double x, y;\n  while(in >> x >> y)\n    tr.insert(typename RT::Point(x, y));\n\n  std::ofstream out(\"triangulation.off\");\n  out << \"OFF\\n\";\n  out << tr.number_of_vertices() << \" \" << std::distance(tr.finite_faces_begin(), tr.finite_faces_end()) << \" 0\\n\";\n\n  std::size_t counter = 0;\n  std::map<typename RT::Point_2, std::size_t> ids;\n  for(const auto& v : CGAL::make_range(tr.finite_vertices_begin(), tr.finite_vertices_end()))\n  {\n    out << v.point().point() << \" 0\\n\";\n    if(ids.insert(std::make_pair(v.point().point(), counter)).second)\n      ++counter;\n  }\n\n  for(const auto& fd : CGAL::make_range(tr.finite_faces_begin(), tr.finite_faces_end()))\n  {\n    out << \"3 \" << ids[fd.vertex(0)->point().point()] << \" \" << ids[fd.vertex(1)->point().point()] << \" \" << ids[fd.vertex(2)->point().point()] << \"\\n\";\n  }\n\n  out.close();\n\n  std::cout << \" (\" << tr.number_of_vertices() << \" vertices)...\" << std::endl;\n  std::cout << \"Kernel: \" << typeid(K()).name() << std::endl;\n\n  test_locate<K>(tr, rnd);\n}\n\ntemplate<typename K>\nvoid test_2D_surface_mesh(const std::string fname, CGAL::Random& rnd)\n{\n  typedef typename K::Point_2                                 Point;\n  typedef CGAL::Surface_mesh<Point>                           Mesh;\n\n  std::cout << \"Testing Surface_mesh \" << fname << \"...\" << std::endl;\n  std::cout << \"Kernel: \" << typeid(K()).name() << std::endl;\n\n  std::ifstream input(fname);\n  assert(input.good());\n\n  Mesh tm;\n  if(!input || !(input >> tm))\n  {\n    std::cerr << \"Error: cannot read file.\";\n    return;\n  }\n\n  test_locate<K>(tm, rnd);\n}\n\ntemplate<typename K>\nvoid test_surface_mesh_3D(const std::string fname, CGAL::Random& rnd)\n{\n  typedef typename K::Point_3                                 Point;\n  typedef CGAL::Surface_mesh<Point>                           Mesh;\n\n  std::cout << \"Testing (3D) Surface_mesh \" << fname << \"...\" << std::endl;\n  std::cout << \"Kernel: \" << typeid(K()).name() << std::endl;\n\n  std::ifstream input(fname);\n  Mesh tm;\n  if(!input || !(input >> tm))\n  {\n    std::cerr << \"Error: cannot read file.\";\n    return;\n  }\n\n  typedef typename boost::property_map<Mesh, CGAL::vertex_point_t>::const_type  VertexPointMap;\n  VertexPointMap vpm = CGAL::get_const_property_map(boost::vertex_point, tm);\n\n  test_locate<K>(tm, vpm, rnd);\n}\n\ntemplate<typename K>\nvoid test_surface_mesh_projection(const std::string fname, CGAL::Random& rnd)\n{\n  typedef typename K::Point_3                                       Point;\n  typedef CGAL::Surface_mesh<Point>                                 Mesh;\n  typedef typename K::Point_2                                       Projected_point;\n\n  typedef typename boost::graph_traits<Mesh>::vertex_descriptor     vertex_descriptor;\n\n  std::cout << \"Testing Projected Surface_mesh \" << fname << \"...\" << std::endl;\n  std::cout << \"Kernel: \" << typeid(K()).name() << std::endl;\n\n  std::ifstream input(fname);\n  Mesh tm;\n  if(!input || !(input >> tm))\n  {\n    std::cerr << \"Error: cannot read file.\";\n    return;\n  }\n\n  const auto& proj_vpm = tm.template add_property_map<typename Mesh::Vertex_index,\n                                                      Projected_point>(\"P2\", Projected_point()).first;\n\n  for(vertex_descriptor v : vertices(tm))\n  {\n    const Point& p = tm.point(v);\n    put(proj_vpm, v, Projected_point(p.x(), p.y()));\n  }\n\n  test_locate<K>(tm, proj_vpm, rnd);\n}\n\ntemplate<typename K>\nvoid test_polyhedron(const std::string fname, CGAL::Random& rnd)\n{\n  typedef CGAL::Polyhedron_3<K>                               Polyhedron;\n\n  std::cout << \"Testing Polyhedron_3 \" << fname << \"...\" << std::endl;\n  std::cout << \"Kernel: \" << typeid(K()).name() << std::endl;\n\n  std::ifstream input(fname);\n  Polyhedron poly;\n  if(!input || !(input >> poly))\n  {\n    std::cerr << \"Error: cannot read file.\";\n    return;\n  }\n\n  test_locate<K>(poly, rnd);\n}\n\ntemplate <typename K>\nvoid test(CGAL::Random& rnd)\n{\n  test_2D_triangulation<K>(\"data/stair.xy\", rnd);\n//  test_2D_surface_mesh<K>(\"data/blobby_2D.off\", rnd); // temporarily disabled, until Surface_mesh's IO is \"fixed\"\n  test_surface_mesh_3D<K>(CGAL::data_file_path(\"meshes/mech-holes-shark.off\"), rnd);\n  test_surface_mesh_projection<K>(\"data/unit-grid.off\", rnd);\n  test_polyhedron<K>(\"data-coref/elephant_split_2.off\", rnd);\n}\n\nint main()\n{\n  CGAL::Set_ieee_double_precision pfr;\n\n  std::cout.precision(17);\n  std::cout << std::fixed;\n\n//  CGAL::Random rnd(1557332474); // if needed to debug with a fixed seed\n  CGAL::Random rnd(CGAL::get_default_random());\n\n  std::cout << \"The seed is \" << rnd.get_seed() << std::endl;\n\n  test<EPICK>(rnd);\n  test<Exact_kernel>(rnd);\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "9102d733047abbe45f838b74151b446ac1ca2e2d", "size": 35853, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Polygon_mesh_processing/test/Polygon_mesh_processing/test_pmp_locate.cpp", "max_stars_repo_name": "ffteja/cgal", "max_stars_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-19T03:07:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-19T03:07:22.000Z", "max_issues_repo_path": "Polygon_mesh_processing/test/Polygon_mesh_processing/test_pmp_locate.cpp", "max_issues_repo_name": "ffteja/cgal", "max_issues_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "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": "Polygon_mesh_processing/test/Polygon_mesh_processing/test_pmp_locate.cpp", "max_forks_repo_name": "ffteja/cgal", "max_forks_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "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": 41.0687285223, "max_line_length": 152, "alphanum_fraction": 0.6059186121, "num_tokens": 9656, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.47421214492038083}}
{"text": "#include <iostream>\n#include <map>\n#include <vector>\n#include <utility>\n#include <string>\n#include <algorithm>\n#include <fstream>\n#include <boost/filesystem.hpp>\n#include <boost/foreach.hpp>\n#include <opencv2/opencv.hpp>\n#include <opencv2/features2d.hpp>\n#include <illust_image_similarity.hpp>\n\nusing namespace illust_image_similarity::feature;\n\nstd::vector<std::string> getFileNames(std::string pathStr) {\n\tstd::vector<std::string> res;\n\tnamespace fs = boost::filesystem;\n\tconst fs::path path(pathStr);\n\n\tBOOST_FOREACH(const fs::path& p, std::make_pair(fs::directory_iterator(path), fs::directory_iterator())) {\n\t\tif (!fs::is_directory(p))\n\t\t\tres.push_back(p.filename().string());\n\t}\n\treturn res;\n}\n\nint main(){\n\tcv::Mat mask = cv::imread(\"tentee_patch/mask/mask.png\", 0);\n\t// vvv For testing vvv //\n\t// b1, b3, y1 -> double edge\n\t// b2, p1, p2, p3 -> single edge\n\t// p3 -> no edge\n\t/*std::map<std::string, cv::Mat> images = {\n\t\t{ \"blue1\", cv::imread(\"../tentee_patch/dream/0001.png\") },\n\t\t{ \"blue2\", cv::imread(\"../tentee_patch/dream/0087.png\") },\n\t\t{ \"blue3\", cv::imread(\"../tentee_patch/dream/0006.png\") },\n\t\t{ \"blue4\", cv::imread(\"../tentee_patch/dream/0255.png\") },\n\t\t{ \"yell1\", cv::imread(\"../tentee_patch/dream/0005.png\") },\n\t\t{ \"pink1\", cv::imread(\"../tentee_patch/dream/0002.png\") },\n\t\t{ \"pink2\", cv::imread(\"../tentee_patch/dream/0132.png\") },\n\t\t{ \"pink3\", cv::imread(\"../tentee_patch/dream/0138.png\") },\n\t\t{ \"pink4\", cv::imread(\"../tentee_patch/dream/0004.png\") }\n\t};*/\n\t// memo: 1\u306812\u306f\u8fd1\u3044, 2\u306f\u9060\u3044\n\t// memo: 255\u30682\u306f\u3069\u3061\u3089\u3082\u7e1e\n\t// ^^^ For testing ^^^ //\n\tstd::map<std::string, cv::Mat> images;\n\n\tauto fileList = getFileNames(\"../tentee_patch/dream/\");\n\t{\n\t\tint cnt = 0;\n\t\tfor(auto&& fName : fileList){\n\t\t\tcv::Mat img = cv::imread(\"../tentee_patch/dream/\" + fName);\n\t\t\tif(++cnt % 10 == 0)\n\t\t\t\tstd::cout << \"loading: \"  << cnt << \" images...\" << std::endl;\n\t\t\tif(img.data)\n\t\t\t\timages[fName] = img;\n\t\t}\n\t}\n\n\tstd::cout << \"start\" << std::endl;\n\n\tstd::map<std::string, cv::MatND> hists;\n\tfor(auto&& [name, img] : images)\n\t\thists[name] = img | hueHistgramAlgorithm(mask);\n\n\tstd::map<std::string, cv::MatND> placements;\n\tfor(auto&& [name, img] : images)\n\t\tplacements[name] = img | placementAlgorithm;\n\n\tstd::map<std::string, std::vector<double>> directions;\n\tfor(auto&& [name, img] : images)\n\t\tdirections[name] = img | directionPreprocess | directionVec(mask);\n\n\tint cnt = 0;\n\tauto cdot = [](const std::vector<double>& lhs, const std::vector<double>& rhs) -> double {\n\t\tint dim = std::min(lhs.size(), rhs.size());\n\t\tdouble res = 0;\n\t\tfor(int i=0; i<dim; ++i)\n\t\t\tres += lhs[i] * rhs[i];\n\t\treturn res;\n\t};\n\t// from, type [hue, edge, dir], to, index (0-), score (0-1)\n\tconst int maxIndex = 5;\n\tstd::ofstream data(\"recommend_data.csv\");\n\tfor(auto&& [name, img] : images){\n\t\tif(++cnt % 10 == 0)\n\t\t\tstd::cout << cnt << \" / \" << images.size() << \" ... \" << std::endl;\n\n\t\tstd::vector<std::pair<double, std::string>> list_hue;\n\t\tstd::vector<std::pair<double, std::string>> list_edge;\n\t\tstd::vector<std::pair<double, std::string>> list_dir;\n\t\tauto&& pls  = placements.at(name);\n\t\tauto&& hist = hists.at(name);\n\t\tauto&& dir  = directions.at(name);\n\t\t// target\n\t\tfor(auto&& [tName, tImg] : images){\n\t\t\tif(name == tName) continue; // \u81ea\u8eab\u3068\u306f\u6bd4\u8f03\u3057\u306a\u3044 (edge,dir,hue\u306e\u30b9\u30b3\u30a2\u306f\u5e38\u306b1)\n\t\t\tauto&& tPls  = placements.at(tName);\n\t\t\tauto&& tHist = hists.at(tName);\n\t\t\tauto&& tDir  = directions.at(tName);\n\t\t\tlist_hue.emplace_back(cv::compareHist(hist, tHist, cv::HISTCMP_CORREL), tName);\n\n\t\t\tcv::Mat tmp;\n\t\t\t// Normalized Cross-Correlation\n\t\t\t//list_edge.emplace_back(cv::norm(img, tImg, cv::NORM_L1), tName);\n\t\t\tcv::matchTemplate(pls, tPls, tmp, CV_TM_CCOEFF_NORMED);\n\t\t\tlist_edge.emplace_back(tmp.at<float>(0,0), tName);\n\n\t\t\t// dot product\n\t\t\tlist_dir.emplace_back(cdot(dir, tDir), tName);\n\t\t}\n\n\t\tstd::sort(list_edge.begin(), list_edge.end());\n\t\tstd::reverse(list_edge.begin(), list_edge.end());\n\n\t\tstd::sort(list_dir.begin(), list_dir.end());\n\t\tstd::reverse(list_dir.begin(), list_dir.end());\n\n\t\tstd::sort(list_hue.begin(), list_hue.end());\n\t\tstd::reverse(list_hue.begin(), list_hue.end());\n\n\t\tfor(int i=0; i<maxIndex && i < list_hue.size(); ++i){\n\t\t\tauto [tHist, tName] = list_hue[i];\n\t\t\tdata << name << \",\" << \"hue\" << \",\" << tName << \",\" << i << \",\" << tHist << \"\\n\";\n\t\t}\n\n\t\tfor(int i=0; i<maxIndex && i < list_edge.size(); ++i){\n\t\t\tauto [tHist, tName] = list_edge[i];\n\t\t\tdata << name << \",\" << \"edge\" << \",\" << tName << \",\" << i << \",\" << tHist << \"\\n\";\n\t\t}\n\n\t\tfor(int i=0; i<maxIndex && i < list_dir.size(); ++i){\n\t\t\tauto [tHist, tName] = list_dir[i];\n\t\t\tdata << name << \",\" << \"dir\" << \",\" << tName << \",\" << i << \",\" << tHist << \"\\n\";\n\t\t}\n\t\tdata << std::flush;\n\n\t}\n\n\tstd::cout << \"end\" << std::endl;\n}\n\n", "meta": {"hexsha": "e2ddc96b8f612c794049531c117810a073c8de18", "size": 4671, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "app/genCSV.cpp", "max_stars_repo_name": "yukatayu/tentee_image_similarity", "max_stars_repo_head_hexsha": "ae787c1b530483b30fdd152dbe51e8b50a1d9c5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2020-05-07T17:30:04.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-22T02:11:45.000Z", "max_issues_repo_path": "app/genCSV.cpp", "max_issues_repo_name": "yukatayu/tentee_image_similarity", "max_issues_repo_head_hexsha": "ae787c1b530483b30fdd152dbe51e8b50a1d9c5b", "max_issues_repo_licenses": ["MIT"], "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/genCSV.cpp", "max_forks_repo_name": "yukatayu/tentee_image_similarity", "max_forks_repo_head_hexsha": "ae787c1b530483b30fdd152dbe51e8b50a1d9c5b", "max_forks_repo_licenses": ["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.2137931034, "max_line_length": 107, "alphanum_fraction": 0.6107899807, "num_tokens": 1516, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.47421214492038083}}
{"text": "/*\n * EigenvalueCovariance.cpp\n *\n *  Created on: May 6, 2015\n *      Author: dbazazian\n *  \n *  Modified by: Milos Prokop, August 2019\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 <cstdlib>\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#include <pcl/search/impl/kdtree.hpp>\n#include <pcl/kdtree/impl/kdtree_flann.hpp>\n\n\n#include <pcl/filters/statistical_outlier_removal.h>\n\n#include \"Difference_Eigenvalues.h\"\n\n#define KNN 20  \n\nusing namespace std;\nusing namespace Eigen;\n\n//Sigma threshold\n//float threshold = 0.05;\n\n//int main (int argc, char*argv[]){\u0080e\u0080e\u0080e\u0080e\u0080e\u0080e\u0080e\u0081e\u0081e\u0081e\u0081e\u0081e\npcl::PointCloud<pcl::PointXYZ>::Ptr extract_edges(pcl::PointCloud<pcl::PointXYZ>::Ptr& cloud, const std::string& outputname, bool writeFile ){\n\n    pcl::PointCloud<pcl::PointXYZ>::Ptr Normals (new pcl::PointCloud<pcl::PointXYZ>);\n    Normals->resize(cloud->size());\n\n    // K nearest neighbor search\n    int KNumbersNeighbor = 10; // numbers of neighbors 7 , 120\n    std::vector<int> NeighborsKNSearch(KNumbersNeighbor);\n    std::vector<float> NeighborsKNSquaredDistance(KNumbersNeighbor);\n\n    int* NumbersNeighbor = new  int [cloud ->points.size ()];\n    pcl::KdTreeFLANN<pcl::PointXYZ> kdtree;\n    kdtree.setInputCloud (cloud);\n    pcl::PointXYZ searchPoint;\n\n    double* SmallestEigen = new  double [cloud->points.size() ];\n    double* MiddleEigen = new  double [cloud->points.size() ];\n    double* LargestEigen = new  double [cloud->points.size() ];\n\n    //double* DLS = new  double [cloud->points.size() ];\n    //double* DLM = new  double [cloud->points.size() ];\n    //double* DMS = new  double [cloud->points.size() ];\n    double* Sigma = new  double [cloud->points.size() ];\n\n    // std::vector<double> SmallestEigen;\n    // std::vector<double> MiddleEigen;\n    // std::vector<double> LargestEigen;\n    //\n    // std::vector<double> DLS;\n    // std::vector<double> DML;\n    // std::vector<double> DMS;\n\n    //  ************ All the Points of the cloud *******************\n    for (size_t i = 0; i < cloud ->points.size (); ++i) {\n\n        searchPoint.x =   cloud->points[i].x;\n        searchPoint.y =   cloud->points[i].y;\n        searchPoint.z =   cloud->points[i].z;\n\n        if ( kdtree.nearestKSearch (searchPoint, KNumbersNeighbor, NeighborsKNSearch, NeighborsKNSquaredDistance) > 0 ) {\n                 NumbersNeighbor[i]= NeighborsKNSearch.size (); }\n            else { NumbersNeighbor[i] = 0; }\n\n        float Xmean; float Ymean; float Zmean;\n        float sum= 0.00;\n\n        // Computing Covariance Matrix\n        for (size_t ii = 0; ii < NeighborsKNSearch.size (); ++ii)\n            sum += cloud->points[ NeighborsKNSearch[ii] ].x;\n        \n        Xmean = sum / NumbersNeighbor[i];\n            \n        sum= 0.00;\n        for (size_t ii = 0; ii < NeighborsKNSearch.size (); ++ii)\n            sum += cloud->points[NeighborsKNSearch[ii] ].y;\n        Ymean = sum / NumbersNeighbor[i];\n            \n        sum= 0.00;\n        for (size_t ii = 0; ii < NeighborsKNSearch.size (); ++ii)\n            sum += cloud->points[NeighborsKNSearch[ii] ].z;\n        Zmean = sum / NumbersNeighbor[i];\n\n        float CovXX, CovXY, CovXZ, CovYX, CovYY, CovYZ, CovZX, CovZY, CovZZ;\n\n        sum = 0.00 ;\n        for (size_t ii = 0; ii < NeighborsKNSearch.size (); ++ii)\n            sum += ( (cloud->points[NeighborsKNSearch[ii] ].x - Xmean ) * ( cloud->points[NeighborsKNSearch[ii] ].x - Xmean )  );\n        CovXX = sum / ( NumbersNeighbor[i]-1);\n            \n        sum = 0.00 ;\n        for (size_t ii = 0; ii < NeighborsKNSearch.size (); ++ii)\n        sum += ( (cloud->points[NeighborsKNSearch[ii] ].x - Xmean ) * ( cloud->points[NeighborsKNSearch[ii] ].y - Ymean )  );\n        CovXY = sum / ( NumbersNeighbor[i]-1);\n        CovYX = CovXY ;\n\n        sum = 0.00 ;\n        for (size_t ii = 0; ii < NeighborsKNSearch.size (); ++ii)\n        sum += ( (cloud->points[NeighborsKNSearch[ii] ].x - Xmean ) * ( cloud->points[NeighborsKNSearch[ii] ].z - Zmean )  );\n        CovXZ= sum / ( NumbersNeighbor[i]-1); \n        CovZX = CovXZ;\n\n        sum = 0.00 ;\n        for (size_t ii = 0; ii < NeighborsKNSearch.size (); ++ii)\n            sum += ( (cloud->points[NeighborsKNSearch[ii] ].y - Ymean ) * ( cloud->points[NeighborsKNSearch[ii] ].y - Ymean )  );\n        CovYY = sum / ( NumbersNeighbor[i]-1);\n\n        sum = 0.00 ;\n        for (size_t ii = 0; ii < NeighborsKNSearch.size (); ++ii)\n            sum += ( (cloud->points[NeighborsKNSearch[ii] ].y - Ymean ) * ( cloud->points[NeighborsKNSearch[ii] ].z - Zmean )  );\n        CovYZ = sum / ( NumbersNeighbor[i]-1);\n        CovZY = CovYZ;\n\n        sum = 0.00 ;\n        for (size_t ii = 0; ii < NeighborsKNSearch.size (); ++ii)\n            sum += ( (cloud->points[NeighborsKNSearch[ii] ].z - Zmean ) * ( cloud->points[NeighborsKNSearch[ii] ].z - Zmean )  );\n        CovZZ = 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\n        if (EigenValue1 < EigenValue2)\n            Smallest =  EigenValue1;\n        else\n            Smallest = EigenValue2;\n\n        if (EigenValue3 < Smallest)\n            Smallest =  EigenValue3;\n\n\n        if(EigenValue1 <= EigenValue2 && EigenValue1 <= EigenValue3) {\n              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              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              Middle = EigenValue1;\n        if(EigenValue2 >= EigenValue3){Largest = EigenValue2; Smallest = EigenValue3;}\n        else{Largest = EigenValue3; Smallest = EigenValue2;}\n        }\n\n        SmallestEigen[i]= Smallest ;\n        MiddleEigen[i]= Middle;\n        LargestEigen[i]= Largest;\n\n        //DLS[i] = std::abs ( SmallestEigen[i] / LargestEigen[i]) ;          // std::abs ( LargestEigen[i] -  SmallestEigen[i] ) ;\n        //DLM[i] = std::abs ( MiddleEigen[i] /  LargestEigen[i]) ;             // std::abs (  LargestEigen[i] - MiddleEigen[i] ) ;\n        //DMS[i] = std::abs ( SmallestEigen[i] / MiddleEigen[i]) ;       // std::abs ( MiddleEigen[i] -  SmallestEigen[i] ) ;\n        \n        Sigma[i] = (SmallestEigen[i] ) / ( SmallestEigen[i] + MiddleEigen[i] + LargestEigen[i] ) ;\n    } \n\n    //std::cout<< \" Computing Sigma is Done! \" << std::endl;\n    // Color Map For the difference of the eigen values\n\n    double MaxD = 0.00;\n    double MinD = std::numeric_limits<double>::max();\n      \n    int Ncolors = 256;\n\n    for (size_t i = 0; i < cloud ->points.size (); ++i) {\n\n          if (Sigma [i] < MinD)\n              MinD= Sigma [i];\n\n          if (Sigma[i] > MaxD)\n              MaxD = Sigma [i];\n    }\n\n    //std::cout<< \" Minimum is :\" << MinD<< std::endl;\n    //std::cout<< \" Maximum  is :\" << MaxD << std::endl;\n\n\t/*\n\t  // computing the standard deviation\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\t  //MaxD = 10* stddvtion;\n\n\t  // Color table\n\t\tdouble line;\n\t\tdouble code[Ncolors][3];\n\t   ifstream colorcode ( \"/Path/TO/ArtificialPointClouds/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\n\n\t    // jet color map\n\n\tint level = 0;\n\tfloat step = ( ( MaxD -  MinD) / Ncolors ) ;\n\t    for (size_t i = 0; i < cloud ->points.size (); ++i) {\n    if (  SmallestEigen [i] <= MaxD ) {\n                level = floor( (SmallestEigen [i] - MinD ) /  step ) ;\n\n                cloud->points[i].r = code[ level ][0];\n                cloud->points[i].g =  code[ level ][1];\n                cloud->points[i].b =  code[ level ][2];\n    } // if sigma less than Max\n                }\n    */\n\n    int ePointsCount = 0;\n\n\n    int level = 0;\n    float step = ( ( MaxD -  MinD) / Ncolors ) ;\n    //  level = floor( (Sigma [i] - MinD ) /  step ) ;\n    float threshold = ( MinD + ( 6 * step) );\n    //float threshold=0.1;\n    //std::cout << ( MinD + ( 6 * step) ) << \"\\n\";\n\n    pcl::PointCloud<pcl::PointXYZ>::Ptr edgePoints (new pcl::PointCloud<pcl::PointXYZ>);\n    \n    for (size_t i = 0; i < cloud -> points.size(); ++i) {\n        if ( Sigma [i] > threshold ) {\n\n            edgePoints->points.push_back( cloud->points[i] );\n            ePointsCount++;\n    \n        }\n    }\n    if ( writeFile ){\n\n        pcl::PointCloud<pcl::PointXYZRGB> cloudRGB;\n        pcl::copyPointCloud(*edgePoints, cloudRGB);\n\n        for (size_t i = 0; i < cloudRGB.points.size(); ++i) {\n            cloudRGB.points[i].r = 255;\n            cloudRGB.points[i].g = 0;\n            cloudRGB.points[i].b = 0;\n        }\n\n        pcl::PLYWriter writePLY;\n        writePLY.write(outputname, cloudRGB,  true, false);\n        std::cout << \"File \" << outputname << \" written.\\n\";\n\n    }\n\n\n/*\n   //DELETE\n   pcl::PLYWriter writePLY;\n   pcl::PointCloud<pcl::PointXYZRGB> cloudRGB;\n   pcl::copyPointCloud(*edgePoints,cloudRGB);\n\n   for (size_t i = 0; i < cloudRGB.points.size(); ++i) {\n                cloudRGB.points[i].r = 255;\n                cloudRGB.points[i].g = 0;\n                cloudRGB.points[i].b = 0;\n\n   }\n  \n  writePLY.write(outputname, cloudRGB,  true, false);\n\n  pcl::PointCloud<pcl::PointXYZ>::Ptr filtered (new pcl::PointCloud<pcl::PointXYZ>);\n\n  pcl::StatisticalOutlierRemoval<pcl::PointXYZ> sor;\n  sor.setInputCloud (edgePoints);\n  sor.setMeanK (50);\n  sor.setStddevMulThresh (0.05);\n  sor.filter (*filtered);\n\n  pcl::copyPointCloud(*filtered,cloudRGB);\n  writePLY.write(outputname+\"_filtered.ply\", cloudRGB,  true, false);\n    \n*/\n\n    // writing the Sigma on the disk\n    //\t    \t   \t\tstd::ofstream ofsSigma;\n    //\t    \t   \t\tofsSigma.open(\"/Path/TO/SigmaDragon.txt\");\n    //\t    \t            for (size_t i = 0; i < cloud ->points.size (); ++i) {\n    //\t    \t            \tofsSigma << Sigma [i]<< \",\"<< std::endl ;\n    //\t    \t                    }\n    //  \tpcl::PLYWriter writePLY;\n    //  \twritePLY.write (OUTPUT_FILE, *cloud,  false);\n\n    //return 0;\n\n  return edgePoints;\n}\n", "meta": {"hexsha": "64fb2b13c39d711d849c14623d4e20e4cac8c58a", "size": 11856, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Edge_Extraction/Difference_Eigenvalues.cpp", "max_stars_repo_name": "Milos9304/LowOverlapPCRegistration", "max_stars_repo_head_hexsha": "fd9d7d3cb31978b700dc0160bc0fa022f02762f2", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2019-11-01T11:46:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T12:07:47.000Z", "max_issues_repo_path": "Edge_Extraction/Difference_Eigenvalues.cpp", "max_issues_repo_name": "Milos9304/LowOverlapPCRegistration", "max_issues_repo_head_hexsha": "fd9d7d3cb31978b700dc0160bc0fa022f02762f2", "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": "Edge_Extraction/Difference_Eigenvalues.cpp", "max_forks_repo_name": "Milos9304/LowOverlapPCRegistration", "max_forks_repo_head_hexsha": "fd9d7d3cb31978b700dc0160bc0fa022f02762f2", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-04-22T07:19:36.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-04T12:43:05.000Z", "avg_line_length": 33.9713467049, "max_line_length": 142, "alphanum_fraction": 0.5747300945, "num_tokens": 3459, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4742121449203808}}
{"text": "#include <boost/math/special_functions/legendre_stieltjes.hpp>\n", "meta": {"hexsha": "eae267ea60c159e12709aa974ccca21e75f58ccc", "size": 63, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_special_functions_legendre_stieltjes.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_special_functions_legendre_stieltjes.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_special_functions_legendre_stieltjes.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 31.5, "max_line_length": 62, "alphanum_fraction": 0.8571428571, "num_tokens": 16, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4742121449203808}}
{"text": "/*    Copyright (c) 2010-2019, Delft University of Technology\r\n *    All rigths reserved\r\n *\r\n *    This file is part of the Tudat. Redistribution and use in source and\r\n *    binary forms, with or without modification, are permitted exclusively\r\n *    under the terms of the Modified BSD license. You should have received\r\n *    a copy of the license with this file. If not, please or visit:\r\n *    http://tudat.tudelft.nl/LICENSE.\r\n *\r\n */\r\n\r\n#define BOOST_TEST_MAIN\r\n\r\n#include <boost/test/unit_test.hpp>\r\n\r\n#include \"Tudat/Basics/testMacros.h\"\r\n#include \"Tudat/Mathematics/BasicMathematics/mathematicalConstants.h\"\r\n\r\n#include \"Tudat/InputOutput/basicInputOutput.h\"\r\n\r\n#include \"Tudat/Astrodynamics/EarthOrientation/shortPeriodEarthOrientationCorrectionCalculator.h\"\r\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/timeConversions.h\"\r\n#include \"Tudat/External/SofaInterface/sofaTimeConversions.h\"\r\n\r\nnamespace tudat\r\n{\r\n\r\nnamespace unit_tests\r\n{\r\n\r\nusing namespace basic_astrodynamics;\r\nusing namespace sofa_interface;\r\nusing namespace earth_orientation;\r\nusing namespace input_output;\r\nusing namespace unit_conversions;\r\n\r\n//! NOTE on tolerances: 1 mm position error on Earth's surface due to single angle error in Earth orientation corresponds to\r\n//! 0.15 nrad angle uncertainty. This corresponds to 32 microarcseconds. For Earth rotation, this corresponds to 2.2 microseconds\r\n//! in UT1. The applied tolerances (1 microarc seconds and 50 ns) correspond to about 20-30 microns difference at Earth's surface.\r\nBOOST_AUTO_TEST_SUITE( test_short_period_eop_corrections )\r\n\r\n//! Test short-periodic ut1-utc variations by comparing to test output of UTLIBR.f file\r\nBOOST_AUTO_TEST_CASE( testShortPeriodLibrationalPolarMotion)\r\n{\r\n    // Create polar motion correction libration corrections\r\n    ShortPeriodEarthOrientationCorrectionCalculator< Eigen::Vector2d > polarMotionCalculator(\r\n               convertArcSecondsToRadians< double >( 1.0E-6 ), 0.0,\r\n    { getEarthOrientationDataFilesPath( ) + \"polarMotionLibrationAmplitudesQuasiDiurnalOnly.txt\" },\r\n    { getEarthOrientationDataFilesPath( ) + \"polarMotionLibrationFundamentalArgumentMultipliersQuasiDiurnalOnly.txt\" } );\r\n\r\n    //  Define test time\r\n    double testMjd = 54335.0;\r\n    double testJulianDay = testMjd + JULIAN_DAY_AT_0_MJD;\r\n    double testUtc = convertJulianDayToSecondsSinceEpoch( testJulianDay, JULIAN_DAY_ON_J2000 );\r\n    double testEphemerisTime = convertUTCtoTT( testUtc );\r\n\r\n    // Compute polar motion correction\r\n    double microAsToRadians =  mathematical_constants::PI / ( 180.0 * 1.0E6 * 3600.0 );\r\n    Eigen::Vector2d polarMotionCorrections = polarMotionCalculator.getCorrections( testEphemerisTime ) / microAsToRadians;\r\n\r\n    // Compare against IERS reference code. Difference between IERS code and this code occurs since the reference uses a slightly\r\n    // different implementation for computation. Difference (1 micro arc seconds) is well below observable threshold\r\n    BOOST_CHECK_SMALL( polarMotionCorrections( 0 ) - 24.65518398386097942, 1.0 );\r\n    BOOST_CHECK_SMALL( polarMotionCorrections( 1 ) + 14.11070254891893327, 1.0 );\r\n\r\n}\r\n\r\n//! Test short-periodic polar motion libration variations by comparing to test output of ORTHO_EOP.f file\r\nBOOST_AUTO_TEST_CASE( testShortPeriodOceanTidePolarMotion)\r\n{\r\n    // Create polar motion correction ocean tide corrections\r\n    ShortPeriodEarthOrientationCorrectionCalculator< Eigen::Vector2d > polarMotionCalculator(\r\n               convertArcSecondsToRadians< double >( 1.0E-6 ), 0.0,\r\n    { getEarthOrientationDataFilesPath( ) + \"polarMotionOceanTidesAmplitudes.txt\", },\r\n    { getEarthOrientationDataFilesPath( ) + \"polarMotionOceanTidesFundamentalArgumentMultipliers.txt\" } );\r\n\r\n    //  Define test time\r\n    double testMjd = 47100.0;\r\n    double testJulianDay = testMjd + JULIAN_DAY_AT_0_MJD;\r\n    double testUtc = convertJulianDayToSecondsSinceEpoch( testJulianDay, JULIAN_DAY_ON_J2000 );\r\n    double testEphemerisTime = convertUTCtoTT( testUtc );\r\n\r\n    // Compute polar motion correction\r\n    double microAsToRadians =  mathematical_constants::PI / ( 180.0 * 1.0E6 * 3600.0 );\r\n    Eigen::Vector2d polarMotionCorrections = polarMotionCalculator.getCorrections( testEphemerisTime ) / microAsToRadians;\r\n\r\n    // Compare against IERS reference code. Difference between IERS code and this code occurs since the reference uses a\r\n    // different algorothm for calculation (ortho-weights vs. Delaunay arguments). Difference (1 micro arc seconds) is well below\r\n    // observable threshold\r\n    BOOST_CHECK_SMALL( polarMotionCorrections.x( ) + 162.8386373279636530, 1.0 );\r\n    BOOST_CHECK_SMALL( polarMotionCorrections.y( ) - 117.7907525842668974, 1.0 );\r\n\r\n}\r\n\r\n//! Test short-periodic polar motion variations by checking if multiple contributions are properly combined\r\nBOOST_AUTO_TEST_CASE( testShortPeriodPolarMotionCombinedCorrections )\r\n{\r\n    // Create polar motion correction ocean tide corrections\r\n    ShortPeriodEarthOrientationCorrectionCalculator< Eigen::Vector2d > polarMotionOceanTideCorrectionCalculator(\r\n               convertArcSecondsToRadians< double >( 1.0E-6 ), 0.0,\r\n    { getEarthOrientationDataFilesPath( ) + \"polarMotionOceanTidesAmplitudes.txt\" },\r\n    { getEarthOrientationDataFilesPath( ) + \"polarMotionOceanTidesFundamentalArgumentMultipliers.txt\" } );\r\n\r\n    // Create polar motion correction libration corrections\r\n    ShortPeriodEarthOrientationCorrectionCalculator< Eigen::Vector2d > polarMotionLibrationCorrectionCalculator(\r\n               convertArcSecondsToRadians< double >( 1.0E-6 ), 0.0,\r\n    { getEarthOrientationDataFilesPath( ) + \"polarMotionLibrationAmplitudesQuasiDiurnalOnly.txt\" },\r\n    { getEarthOrientationDataFilesPath( ) + \"polarMotionLibrationFundamentalArgumentMultipliersQuasiDiurnalOnly.txt\" } );\r\n\r\n    // Create polar motion correction combined corrections\r\n    ShortPeriodEarthOrientationCorrectionCalculator< Eigen::Vector2d > polarMotionTotalCorrectionCalculator(\r\n               convertArcSecondsToRadians< double >( 1.0E-6 ), 0.0,\r\n    { getEarthOrientationDataFilesPath( ) + \"polarMotionOceanTidesAmplitudes.txt\",\r\n      getEarthOrientationDataFilesPath( ) + \"polarMotionLibrationAmplitudesQuasiDiurnalOnly.txt\" },\r\n    { getEarthOrientationDataFilesPath( ) + \"polarMotionOceanTidesFundamentalArgumentMultipliers.txt\",\r\n      getEarthOrientationDataFilesPath( ) + \"polarMotionLibrationFundamentalArgumentMultipliersQuasiDiurnalOnly.txt\" } );\r\n\r\n    //  Define test time\r\n    double testMjd = 47100.0;\r\n    double testJulianDay = testMjd + JULIAN_DAY_AT_0_MJD;\r\n    double testUtc = convertJulianDayToSecondsSinceEpoch( testJulianDay, JULIAN_DAY_ON_J2000 );\r\n    double testEphemerisTime = convertUTCtoTT( testUtc );\r\n\r\n    // Compute corrections and check validity of combination\r\n    Eigen::Vector2d polarMotionCorrectionOceanTides = polarMotionOceanTideCorrectionCalculator.getCorrections(\r\n                testEphemerisTime );\r\n    Eigen::Vector2d polarMotionCorrectionLibration = polarMotionLibrationCorrectionCalculator.getCorrections(\r\n                testEphemerisTime );\r\n    Eigen::Vector2d polarMotionCorrectionTotal = polarMotionTotalCorrectionCalculator.getCorrections( testEphemerisTime );\r\n\r\n\r\n    BOOST_CHECK_SMALL( std::fabs( polarMotionCorrectionTotal( 0 ) -\r\n                                  ( polarMotionCorrectionLibration( 0 ) + polarMotionCorrectionOceanTides( 0 ) ) ), 1.0E-24 );\r\n    BOOST_CHECK_SMALL( std::fabs( polarMotionCorrectionTotal( 1 ) -\r\n                                  ( polarMotionCorrectionLibration( 1 ) + polarMotionCorrectionOceanTides( 1 ) ) ), 1.0E-24 );\r\n}\r\n\r\n//! Test short-periodic ut1-utc variations by comparing to test output of UTLIBR.f file\r\nBOOST_AUTO_TEST_CASE( testShortPeriodLibrationalUt1)\r\n{\r\n    // Create UT1 correction libration corrections\r\n    ShortPeriodEarthOrientationCorrectionCalculator < double > ut1CorrectionCalculator(\r\n                1.0E-6, 0.0,\r\n    { getEarthOrientationDataFilesPath( ) + \"utcLibrationAmplitudes.txt\" },\r\n    { getEarthOrientationDataFilesPath( ) + \"utcLibrationFundamentalArgumentMultipliers.txt\" } );\r\n\r\n    //  Define test time\r\n    double testMjd = 44239.1 ;\r\n    double testJulianDay = testMjd + JULIAN_DAY_AT_0_MJD;\r\n    double testUtc = convertJulianDayToSecondsSinceEpoch( testJulianDay, JULIAN_DAY_ON_J2000 );\r\n    double testEphemerisTime = convertUTCtoTT( testUtc );\r\n\r\n    // Compute UT1 correction\r\n    double ut1Correction = ut1CorrectionCalculator.getCorrections( testEphemerisTime );\r\n\r\n    // Compare against IERS reference code. Difference between IERS code and this code occurs since the reference uses a slightly\r\n    // different implementation for computation. Difference (10 ns) is well below observable threshold for Earth rotation\r\n    BOOST_CHECK_SMALL( ut1Correction - 2.441143834386761746E-6, 1.0E-8 );\r\n\r\n    //  Define second test time\r\n    testMjd = 55227.4 ;\r\n    testJulianDay = testMjd + JULIAN_DAY_AT_0_MJD;\r\n    testUtc = convertJulianDayToSecondsSinceEpoch( testJulianDay, JULIAN_DAY_ON_J2000 );\r\n    testEphemerisTime = convertUTCtoTT( testUtc );\r\n\r\n    // Compute UT1 correction\r\n    ut1Correction = ut1CorrectionCalculator.getCorrections( testEphemerisTime );\r\n\r\n    // Compare against IERS reference code. Difference between IERS code and this code occurs since the reference uses a slightly\r\n    // different implementation for computation. Difference (10 ns) is well below observable threshold for Earth rotation\r\n    BOOST_CHECK_SMALL( ut1Correction + 2.655705844335680244E-6, 5.0E-8 );\r\n\r\n}\r\n\r\n//! Test short-periodic ut1-utc libration variations by comparing to test output of ORTHO_EOP.f file\r\nBOOST_AUTO_TEST_CASE( testShortPeriodOceanTideUt1 )\r\n{\r\n    // Create UT1 correction ocean tide corrections\r\n    ShortPeriodEarthOrientationCorrectionCalculator < double > ut1CorrectionCalculator =\r\n            ShortPeriodEarthOrientationCorrectionCalculator < double >(\r\n                1.0E-6, 0.0,\r\n    { getEarthOrientationDataFilesPath( ) + \"utcOceanTidesAmplitudes.txt\", },\r\n    { getEarthOrientationDataFilesPath( ) + \"utcOceanTidesFundamentalArgumentMultipliers.txt\" } );\r\n\r\n    //  Define test time\r\n    double testMjd = 47100.0;\r\n    double testJulianDay = testMjd + JULIAN_DAY_AT_0_MJD;\r\n    double testUtc = convertJulianDayToSecondsSinceEpoch( testJulianDay, JULIAN_DAY_ON_J2000 );\r\n    double testEphemerisTime = convertUTCtoTT( testUtc );\r\n    double ut1Correction = ut1CorrectionCalculator.getCorrections( testEphemerisTime );\r\n\r\n    // Compare against IERS reference code. Difference between IERS code and this code occurs since the reference uses a\r\n    // different algorothm for calculation (ortho-weights vs. Delaunay arguments). Difference (50 ns) is well below observable\r\n    // threshold for Earth rotation\r\n    BOOST_CHECK_SMALL( ut1Correction + 23.39092370609808214E-6, 5.0E-8 );\r\n\r\n}\r\n\r\n//! Test short-periodic ut1-utc variations by checking if multiple contributions are properly combined\r\nBOOST_AUTO_TEST_CASE( testShortPeriodUt1CombinedCorrections )\r\n{\r\n    // Create UT1 correction ocean tide corrections\r\n    ShortPeriodEarthOrientationCorrectionCalculator < double > ut1OceanTideCorrectionCalculator =\r\n            ShortPeriodEarthOrientationCorrectionCalculator < double >(\r\n                1.0E-6, 0.0,\r\n    { getEarthOrientationDataFilesPath( ) + \"utcOceanTidesAmplitudes.txt\" },\r\n    { getEarthOrientationDataFilesPath( ) + \"utcOceanTidesFundamentalArgumentMultipliers.txt\" } );\r\n\r\n    // Create UT1 correction libration corrections\r\n    ShortPeriodEarthOrientationCorrectionCalculator < double > ut1LibrationCorrectionCalculator(\r\n                1.0E-6, 0.0,\r\n    { getEarthOrientationDataFilesPath( ) + \"utcLibrationAmplitudes.txt\" },\r\n    { getEarthOrientationDataFilesPath( ) + \"utcLibrationFundamentalArgumentMultipliers.txt\" } );\r\n\r\n    // Create UT1 correction combined corrections\r\n    ShortPeriodEarthOrientationCorrectionCalculator < double > ut1TotalCorrectionCalculator(\r\n                1.0E-6, 0.0,\r\n    { getEarthOrientationDataFilesPath( ) + \"utcLibrationAmplitudes.txt\",\r\n                getEarthOrientationDataFilesPath( ) + \"utcOceanTidesAmplitudes.txt\" },\r\n    { getEarthOrientationDataFilesPath( ) + \"utcLibrationFundamentalArgumentMultipliers.txt\",\r\n                getEarthOrientationDataFilesPath( ) + \"utcOceanTidesFundamentalArgumentMultipliers.txt\" } );\r\n\r\n    //  Define test time\r\n    double testMjd = 47100.0;\r\n    double testJulianDay = testMjd + JULIAN_DAY_AT_0_MJD;\r\n    double testUtc = convertJulianDayToSecondsSinceEpoch( testJulianDay, JULIAN_DAY_ON_J2000 );\r\n    double testEphemerisTime = convertUTCtoTT( testUtc );\r\n\r\n    // Compute corrections and check validity of combination\r\n    double ut1CorrectionOceanTides = ut1OceanTideCorrectionCalculator.getCorrections( testEphemerisTime );\r\n    double ut1CorrectionLibration = ut1LibrationCorrectionCalculator.getCorrections( testEphemerisTime );\r\n    double ut1CorrectionTotal = ut1TotalCorrectionCalculator.getCorrections( testEphemerisTime );\r\n\r\n    BOOST_CHECK_SMALL( std::fabs( ut1CorrectionTotal - ( ut1CorrectionLibration + ut1CorrectionOceanTides ) ), 1.0E-20 );\r\n}\r\n\r\nBOOST_AUTO_TEST_SUITE_END( )\r\n\r\n}\r\n\r\n}\r\n\r\n\r\n\r\n", "meta": {"hexsha": "4404ab13c3dca63f2561016c2feb2e487a925c8c", "size": 13202, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/EarthOrientation/UnitTests/unitTestShortPeriodEopCorrections.cpp", "max_stars_repo_name": "sebranchett/tudat", "max_stars_repo_head_hexsha": "24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tudat/Astrodynamics/EarthOrientation/UnitTests/unitTestShortPeriodEopCorrections.cpp", "max_issues_repo_name": "sebranchett/tudat", "max_issues_repo_head_hexsha": "24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tudat/Astrodynamics/EarthOrientation/UnitTests/unitTestShortPeriodEopCorrections.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.8857142857, "max_line_length": 131, "alphanum_fraction": 0.7557188305, "num_tokens": 3265, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4742121449203808}}
{"text": "#include <boost/math/distributions/triangular.hpp>\n", "meta": {"hexsha": "1114f8cc8dab9666ae79ecfeb75927dbb68e41a1", "size": 51, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_distributions_triangular.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_distributions_triangular.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_distributions_triangular.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 25.5, "max_line_length": 50, "alphanum_fraction": 0.8235294118, "num_tokens": 11, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788995148791, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4742121395635204}}
{"text": "#define BOOST_TEST_MAIN\n#define BOOST_TEST_DYN_LINK\n\n#include <iostream>\n#include <boost/test/unit_test.hpp>\n\n#include \"Map/2d/RayToPixelMask.h\"\n#include \"Map/2d/MapLimits.h\"\n\nnamespace {\n\nbool isEqual(const Eigen::Array2i & lhs, const Eigen::Array2i & rhs) {\n    return ((lhs - rhs).matrix().lpNorm<1>() == 0);\n}\n\n}\n\nBOOST_AUTO_TEST_CASE(EQUAL) {\n    BOOST_CHECK(isEqual(Eigen::Array2i(1,3), Eigen::Array2i(1,3)) == true);\n}\n\nBOOST_AUTO_TEST_CASE(SingleCell) {\n    const Eigen::Array2i & begin = {1, 1};\n    const Eigen::Array2i & end = {1, 1};\n    const int subPixelScale = 1;\n\n    std::vector<Eigen::Array2i> ray = VISFS::Map::rayToPixelMask(begin, end, subPixelScale);\n    BOOST_CHECK(isEqual(ray[0], begin) == true);\n}\n\nBOOST_AUTO_TEST_CASE(AxisAlginedX) {\n    const Eigen::Array2i & begin = {1, 1};\n    const Eigen::Array2i & end = {3, 1};\n    const int subPixelScale = 1;\n    std::vector<Eigen::Array2i> ray = VISFS::Map::rayToPixelMask(begin, end, subPixelScale);\n    for (int i = 0; i < ray.size(); ++i) {\n        BOOST_CHECK(isEqual(ray[i], Eigen::Array2i({(1+i), 1})));\n    }\n    ray.clear();\n    ray = VISFS::Map::rayToPixelMask(end, begin, subPixelScale);\n    for (int i = 0; i < ray.size(); ++i) {\n        BOOST_CHECK(isEqual(ray[i], Eigen::Array2i({(1+i), 1})));\n    }\n}\n\nBOOST_AUTO_TEST_CASE(AxisAlginedY) {\n    const Eigen::Array2i & begin = {1, 1};\n    const Eigen::Array2i & end = {1, 3};\n    const int subPixelScale = 1;\n    std::vector<Eigen::Array2i> ray = VISFS::Map::rayToPixelMask(begin, end, subPixelScale);\n    for (int i = 0; i < ray.size(); ++i) {\n        BOOST_CHECK(isEqual(ray[i], Eigen::Array2i({1, 1+i})));\n    }\n    ray.clear();\n    ray = VISFS::Map::rayToPixelMask(end, begin, subPixelScale);\n    for (int i = 0; i < ray.size(); ++i) {\n        BOOST_CHECK(isEqual(ray[i], Eigen::Array2i({1, 1+i})));\n    }\n}\n\nBOOST_AUTO_TEST_CASE(Digonal) {\n    Eigen::Array2i begin = {1, 1};\n    Eigen::Array2i end = {3, 3};\n    const int subPixelScale = 1;\n    std::vector<Eigen::Array2i> rayReference = std::vector<Eigen::Array2i>{\n        Eigen::Array2i({1, 1}), Eigen::Array2i({2, 2}), Eigen::Array2i({3, 3})};\n    std::vector<Eigen::Array2i> ray = VISFS::Map::rayToPixelMask(begin, end, subPixelScale);\n    BOOST_REQUIRE(ray.size() == rayReference.size());\n    for (int i = 0; i < ray.size(); ++i) {\n        BOOST_CHECK(isEqual(ray[i], rayReference[i]));\n    }\n    ray.clear();\n    ray = VISFS::Map::rayToPixelMask(end, begin, subPixelScale);\n    BOOST_REQUIRE(ray.size() == rayReference.size());\n    for (int i = 0; i < ray.size(); ++i) {\n        BOOST_CHECK(isEqual(ray[i], rayReference[i]));\n    }\n\n    begin = Eigen::Array2i({1, 3});\n    end = Eigen::Array2i({3, 1});\n    rayReference = std::vector<Eigen::Array2i>{\n        Eigen::Array2i({1, 3}), Eigen::Array2i({2, 2}), Eigen::Array2i({3, 1})};\n    ray = VISFS::Map::rayToPixelMask(begin, end, subPixelScale);\n    BOOST_REQUIRE(ray.size() == rayReference.size());\n    for (int i = 0; i < ray.size(); ++i) {\n        BOOST_CHECK(isEqual(ray[i], rayReference[i]));\n    }\n    ray = VISFS::Map::rayToPixelMask(end, begin, subPixelScale);\n    BOOST_REQUIRE(ray.size() == rayReference.size());\n    for (int i = 0; i < ray.size(); ++i) {\n        BOOST_CHECK(isEqual(ray[i], rayReference[i]));\n    }\n}\n\nBOOST_AUTO_TEST_CASE(SteepLine) {\n    Eigen::Array2i begin = {1, 1};\n    Eigen::Array2i end = {2, 5};\n    const int subPixelScale = 1;\n    std::vector<Eigen::Array2i> rayReference = std::vector<Eigen::Array2i>{\n        Eigen::Array2i({1, 1}), Eigen::Array2i({1, 2}), Eigen::Array2i({1, 3}),\n        Eigen::Array2i({2, 3}), Eigen::Array2i({2, 4}), Eigen::Array2i({2, 5})};\n    std::vector<Eigen::Array2i> ray = VISFS::Map::rayToPixelMask(begin, end, subPixelScale);\n    BOOST_REQUIRE(ray.size() == rayReference.size());\n    for (int i = 0; i < ray.size(); ++i) {\n        BOOST_CHECK(isEqual(ray[i], rayReference[i]));\n    }\n    begin = {1, 1};\n    end = {2, 4};\n    rayReference = std::vector<Eigen::Array2i>{\n        Eigen::Array2i({1, 1}), Eigen::Array2i({1, 2}), Eigen::Array2i({2, 3}),\n        Eigen::Array2i({2, 4})};\n    ray = VISFS::Map::rayToPixelMask(begin, end, subPixelScale);\n    BOOST_REQUIRE(ray.size() == rayReference.size());\n    for (int i = 0; i < ray.size(); ++i) {\n        BOOST_CHECK(isEqual(ray[i], rayReference[i]));\n    }\n}\n\nBOOST_AUTO_TEST_CASE(FlatLine) {\n    Eigen::Array2i begin = {1, 1};\n    Eigen::Array2i end = {5, 2};\n    const int subPixelScale = 1;\n    std::vector<Eigen::Array2i> rayReference = std::vector<Eigen::Array2i>{\n        Eigen::Array2i({1, 1}), Eigen::Array2i({2, 1}), Eigen::Array2i({3, 1}),\n        Eigen::Array2i({3, 2}), Eigen::Array2i({4, 2}), Eigen::Array2i({5, 2})};\n    std::vector<Eigen::Array2i> ray = VISFS::Map::rayToPixelMask(begin, end, subPixelScale);\n    BOOST_REQUIRE(ray.size() == rayReference.size());\n    for (int i = 0; i < ray.size(); ++i) {\n        BOOST_CHECK(isEqual(ray[i], rayReference[i]));\n    }\n    begin = {1, 1};\n    end = {4, 2};\n    rayReference = std::vector<Eigen::Array2i>{\n        Eigen::Array2i({1, 1}), Eigen::Array2i({2, 1}), Eigen::Array2i({3, 2}),\n        Eigen::Array2i({4, 2})};\n    ray = VISFS::Map::rayToPixelMask(begin, end, subPixelScale);\n    BOOST_REQUIRE(ray.size() == rayReference.size());\n    for (int i = 0; i < ray.size(); ++i) {\n        BOOST_CHECK(isEqual(ray[i], rayReference[i]));\n    }\n}\n\nBOOST_AUTO_TEST_CASE(MultiScaleAxisAlignedX) {\n    int subPixelScale;\n    const int numCellsX = 10;\n    const int numCellsY = 10;\n    double resolution = 0.1;\n    Eigen::Vector2d max = {1.0, 1.0};\n    std::vector<Eigen::Array2i> rayReference = std::vector<Eigen::Array2i>{\n        Eigen::Array2i({9, 6}), Eigen::Array2i({9, 7}), Eigen::Array2i({9, 8}), Eigen::Array2i({9, 9})};\n    for (subPixelScale = 1; subPixelScale < 10000; subPixelScale *= 2) {\n        double superscaledResolution  = resolution / subPixelScale;\n        VISFS::Map::MapLimits superScaledLimits(superscaledResolution, max,\n            VISFS::Map::CellLimits(numCellsX * subPixelScale, numCellsY * subPixelScale));\n        Eigen::Array2i begin = superScaledLimits.getCellIndex(Eigen::Vector2d({0.05, 0.05}));\n        Eigen::Array2i end = superScaledLimits.getCellIndex(Eigen::Vector2d({0.35, 0.05}));\n        std::vector<Eigen::Array2i> ray = VISFS::Map::rayToPixelMask(begin, end, subPixelScale);\n        BOOST_REQUIRE(ray.size() == rayReference.size());\n        for (int i = 0; i < ray.size(); ++i) {\n            BOOST_CHECK(isEqual(ray[i], rayReference[i]));\n            // Eigen::Vector2d center = superScaledLimits.getCellCenter(ray[i]);\n            // std::cout << \"center: \" << center.transpose() << std::endl;\n        }\n    }\n}\n\nBOOST_AUTO_TEST_CASE(MultiScaleSkewedLine) {\n    int subPixelScale;\n    const int numCellsX = 1;\n    const int numCellsY = 1;\n    double resolution = 0.1;\n    Eigen::Vector2d max = {1.0, 1.0};\n    std::vector<Eigen::Array2i> rayReference = std::vector<Eigen::Array2i>{\n        Eigen::Array2i({8, 7}), Eigen::Array2i({8, 8}), Eigen::Array2i({9, 8}), Eigen::Array2i({9, 9})};\n    for (subPixelScale = 1; subPixelScale < 2; subPixelScale *= 2) {\n        double superscaledResolution  = resolution / subPixelScale;\n        VISFS::Map::MapLimits superScaledLimits(superscaledResolution, max,\n            VISFS::Map::CellLimits(numCellsX * subPixelScale, numCellsY * subPixelScale));\n        Eigen::Array2i begin = superScaledLimits.getCellIndex(Eigen::Vector2d({0.01, 0.09}));\n        Eigen::Array2i end = superScaledLimits.getCellIndex(Eigen::Vector2d({0.21, 0.19}));\n        std::vector<Eigen::Array2i> ray = VISFS::Map::rayToPixelMask(begin, end, subPixelScale);\n        BOOST_REQUIRE(ray.size() == rayReference.size());\n        for (int i = 0; i < ray.size(); ++i) {\n            BOOST_CHECK(isEqual(ray[i], rayReference[i]));\n        }\n    }\n\n    std::vector<Eigen::Array2i> rayReference2 = std::vector<Eigen::Array2i>{\n        Eigen::Array2i({8, 7}), Eigen::Array2i({8, 8}), Eigen::Array2i({8, 9}), Eigen::Array2i({9, 9})};\n    for (subPixelScale = 20; subPixelScale < 1000; subPixelScale *= 2) {\n        double superscaledResolution  = resolution / subPixelScale;\n        VISFS::Map::MapLimits superScaledLimits(superscaledResolution, max,\n            VISFS::Map::CellLimits(numCellsX * subPixelScale, numCellsY * subPixelScale));\n        Eigen::Array2i begin = superScaledLimits.getCellIndex(Eigen::Vector2d({0.01, 0.09}));\n        Eigen::Array2i end = superScaledLimits.getCellIndex(Eigen::Vector2d({0.21, 0.19}));\n        std::vector<Eigen::Array2i> ray = VISFS::Map::rayToPixelMask(begin, end, subPixelScale);\n        BOOST_REQUIRE(ray.size() == rayReference2.size());\n        for (int i = 0; i < ray.size(); ++i) {\n            BOOST_CHECK(isEqual(ray[i], rayReference2[i]));\n        }\n    }\n}\n", "meta": {"hexsha": "6d289d5f90fd12640f5e61975c3c54251235923e", "size": 8777, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/Map/2d/UT4RayToPixelMask/UT4RayToPixelMask.cpp", "max_stars_repo_name": "supersaiyajinggod/VISFS", "max_stars_repo_head_hexsha": "6567df9b064437a32dc96d6f03ef6cd4ea1b24ce", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-06-09T13:20:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-14T13:31:11.000Z", "max_issues_repo_path": "tests/Map/2d/UT4RayToPixelMask/UT4RayToPixelMask.cpp", "max_issues_repo_name": "supersaiyajinggod/VISFS", "max_issues_repo_head_hexsha": "6567df9b064437a32dc96d6f03ef6cd4ea1b24ce", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/Map/2d/UT4RayToPixelMask/UT4RayToPixelMask.cpp", "max_forks_repo_name": "supersaiyajinggod/VISFS", "max_forks_repo_head_hexsha": "6567df9b064437a32dc96d6f03ef6cd4ea1b24ce", "max_forks_repo_licenses": ["BSD-3-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.236453202, "max_line_length": 104, "alphanum_fraction": 0.6182066765, "num_tokens": 2795, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743735019594, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.47418225265588926}}
{"text": "//\n// Copyright (c) 2015-2020 CNRS INRIA\n// Copyright (c) 2015 Wandercraft, 86 rue de Paris 91400 Orsay, France.\n//\n\n#include \"pinocchio/math/fwd.hpp\"\n#include \"pinocchio/multibody/joint/joints.hpp\"\n#include \"pinocchio/algorithm/rnea.hpp\"\n#include \"pinocchio/algorithm/aba.hpp\"\n#include \"pinocchio/algorithm/crba.hpp\"\n#include \"pinocchio/algorithm/jacobian.hpp\"\n#include \"pinocchio/algorithm/compute-all-terms.hpp\"\n\n#include <boost/test/unit_test.hpp>\n#include <iostream>\n\nusing namespace pinocchio;\n\ntemplate<typename D>\nvoid addJointAndBody(Model & model,\n                     const JointModelBase<D> & jmodel,\n                     const Model::JointIndex parent_id,\n                     const SE3 & joint_placement,\n                     const std::string & joint_name,\n                     const Inertia & Y)\n{\n  Model::JointIndex idx;\n  \n  idx = model.addJoint(parent_id,jmodel,joint_placement,joint_name);\n  model.appendBodyToJoint(idx,Y);\n}\n\nBOOST_AUTO_TEST_SUITE(JointTranslation)\n  \nBOOST_AUTO_TEST_CASE(spatial)\n{\n  typedef TransformTranslationTpl<double,0> TransformTranslation;\n  typedef SE3::Vector3 Vector3;\n  \n  const Vector3 displacement(Vector3::Random());\n  SE3 Mplain, Mrand(SE3::Random());\n  \n  TransformTranslation Mtrans(displacement);\n  Mplain = Mtrans;\n  BOOST_CHECK(Mplain.translation().isApprox(displacement));\n  BOOST_CHECK(Mplain.rotation().isIdentity());\n  BOOST_CHECK((Mrand*Mplain).isApprox(Mrand*Mtrans));\n  \n  SE3 M(SE3::Random());\n  Motion v(Motion::Random());\n  \n  MotionTranslation mp(MotionTranslation::Vector3(1.,2.,3.));\n  Motion mp_dense(mp);\n  \n  BOOST_CHECK(M.act(mp).isApprox(M.act(mp_dense)));\n  BOOST_CHECK(M.actInv(mp).isApprox(M.actInv(mp_dense)));\n  \n  BOOST_CHECK(v.cross(mp).isApprox(v.cross(mp_dense)));\n}\n\nBOOST_AUTO_TEST_CASE(vsFreeFlyer)\n{\n  using namespace pinocchio;\n  typedef SE3::Vector3 Vector3;\n  typedef Eigen::Matrix <double, 6, 1> Vector6;\n  typedef Eigen::Matrix <double, 7, 1> VectorFF;\n  typedef SE3::Matrix3 Matrix3;\n\n  Model modelTranslation, modelFreeflyer;\n\n  Inertia inertia(1., Vector3(0.5, 0., 0.0), Matrix3::Identity());\n  SE3 pos(1); pos.translation() = SE3::LinearType(1.,0.,0.);\n\n  addJointAndBody(modelTranslation,JointModelTranslation(),0,SE3::Identity(),\"translation\",inertia);\n  addJointAndBody(modelFreeflyer,JointModelFreeFlyer(),0,SE3::Identity(),\"free-flyer\",inertia);\n\n  Data dataTranslation(modelTranslation);\n  Data dataFreeFlyer(modelFreeflyer);\n\n  Eigen::VectorXd q = Eigen::VectorXd::Ones(modelTranslation.nq);\n  VectorFF qff; qff << 1, 1, 1, 0, 0, 0, 1 ;\n  Eigen::VectorXd v = Eigen::VectorXd::Ones(modelTranslation.nv);\n  Vector6 vff; vff << 1, 1, 1, 0, 0, 0;\n  Eigen::VectorXd tauTranslation = Eigen::VectorXd::Ones(modelTranslation.nv);\n  Eigen::VectorXd tauff(6); tauff << 1, 1, 1, 0, 0, 0;\n  Eigen::VectorXd aTranslation = Eigen::VectorXd::Ones(modelTranslation.nv);\n  Eigen::VectorXd aff(vff);\n  \n  forwardKinematics(modelTranslation, dataTranslation, q, v);\n  forwardKinematics(modelFreeflyer, dataFreeFlyer, qff, vff);\n\n  computeAllTerms(modelTranslation, dataTranslation, q, v);\n  computeAllTerms(modelFreeflyer, dataFreeFlyer, qff, vff);\n\n  BOOST_CHECK(dataFreeFlyer.oMi[1].isApprox(dataTranslation.oMi[1]));\n  BOOST_CHECK(dataFreeFlyer.liMi[1].isApprox(dataTranslation.liMi[1]));\n  BOOST_CHECK(dataFreeFlyer.Ycrb[1].matrix().isApprox(dataTranslation.Ycrb[1].matrix()));\n  BOOST_CHECK(dataFreeFlyer.f[1].toVector().isApprox(dataTranslation.f[1].toVector()));\n  \n  Eigen::VectorXd nle_expected_ff(3); nle_expected_ff << dataFreeFlyer.nle[0],\n                                                         dataFreeFlyer.nle[1],\n                                                         dataFreeFlyer.nle[2]\n                                                         ;\n  BOOST_CHECK(nle_expected_ff.isApprox(dataTranslation.nle));\n  BOOST_CHECK(dataFreeFlyer.com[0].isApprox(dataTranslation.com[0]));\n\n  // InverseDynamics == rnea\n  tauTranslation = rnea(modelTranslation, dataTranslation, q, v, aTranslation);\n  tauff = rnea(modelFreeflyer, dataFreeFlyer, qff, vff, aff);\n\n  Vector3 tau_expected; tau_expected << tauff(0), tauff(1), tauff(2);\n  BOOST_CHECK(tauTranslation.isApprox(tau_expected));\n\n  // ForwardDynamics == aba\n  Eigen::VectorXd aAbaTranslation = aba(modelTranslation,dataTranslation, q, v, tauTranslation);\n  Eigen::VectorXd aAbaFreeFlyer = aba(modelFreeflyer,dataFreeFlyer, qff, vff, tauff);\n  Vector3 a_expected; a_expected << aAbaFreeFlyer[0],\n                                    aAbaFreeFlyer[1],\n                                    aAbaFreeFlyer[2]\n                                    ;\n  BOOST_CHECK(aAbaTranslation.isApprox(a_expected));\n\n  // crba\n  crba(modelTranslation, dataTranslation,q);\n  crba(modelFreeflyer, dataFreeFlyer, qff);\n\n  Eigen::Matrix<double, 3, 3> M_expected(dataFreeFlyer.M.topLeftCorner<3,3>());\n\n  BOOST_CHECK(dataTranslation.M.isApprox(M_expected));\n   \n  // Jacobian\n  Eigen::Matrix<double, 6, Eigen::Dynamic> jacobian_translation;jacobian_translation.resize(6,3); jacobian_translation.setZero();\n  Eigen::Matrix<double, 6, Eigen::Dynamic> jacobian_ff;jacobian_ff.resize(6,6);jacobian_ff.setZero();\n  computeJointJacobians(modelTranslation, dataTranslation, q);\n  computeJointJacobians(modelFreeflyer, dataFreeFlyer, qff);\n  getJointJacobian(modelTranslation, dataTranslation, 1, LOCAL, jacobian_translation);\n  getJointJacobian(modelFreeflyer, dataFreeFlyer, 1, LOCAL, jacobian_ff);\n\n  Eigen::Matrix<double, 6, 3> jacobian_expected; jacobian_expected << jacobian_ff.col(0),\n                                                                      jacobian_ff.col(1),\n                                                                      jacobian_ff.col(2)\n                                                                      ;\n  BOOST_CHECK(jacobian_translation.isApprox(jacobian_expected));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "c5492b0998751276c80a6c26d0ed154799f990ba", "size": 5861, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittest/joint-translation.cpp", "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": "unittest/joint-translation.cpp", "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": "unittest/joint-translation.cpp", "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": 39.8707482993, "max_line_length": 129, "alphanum_fraction": 0.679576864, "num_tokens": 1535, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743735019595, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.4741822424990138}}
{"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_SPECIAL_FUNCTIONS_IGAMMA_INVERSE_HPP\n#define BOOST_MATH_SPECIAL_FUNCTIONS_IGAMMA_INVERSE_HPP\n\n#ifdef _MSC_VER\n#pragma once\n#endif\n\n#include <boost/tr1/tuple.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/math/special_functions/sign.hpp>\n#include <boost/math/tools/roots.hpp>\n#include <boost/math/policies/error_handling.hpp>\n\nnamespace boost{ namespace math{\n\nnamespace detail{\n\ntemplate <class T>\nT find_inverse_s(T p, T q)\n{\n   //\n   // Computation of the Incomplete Gamma Function Ratios and their Inverse\n   // ARMIDO R. DIDONATO and ALFRED H. MORRIS, JR.\n   // ACM Transactions on Mathematical Software, Vol. 12, No. 4,\n   // December 1986, Pages 377-393.\n   //\n   // See equation 32.\n   //\n   BOOST_MATH_STD_USING\n   T t;\n   if(p < 0.5)\n   {\n      t = sqrt(-2 * log(p));\n   }\n   else\n   {\n      t = sqrt(-2 * log(q));\n   }\n   static const double a[4] = { 3.31125922108741, 11.6616720288968, 4.28342155967104, 0.213623493715853 };\n   static const double b[5] = { 1, 6.61053765625462, 6.40691597760039, 1.27364489782223, 0.3611708101884203e-1 };\n   T s = t - tools::evaluate_polynomial(a, t) / tools::evaluate_polynomial(b, t);\n   if(p < 0.5)\n      s = -s;\n   return s;\n}\n\ntemplate <class T>\nT didonato_SN(T a, T x, unsigned N, T tolerance = 0)\n{\n   //\n   // Computation of the Incomplete Gamma Function Ratios and their Inverse\n   // ARMIDO R. DIDONATO and ALFRED H. MORRIS, JR.\n   // ACM Transactions on Mathematical Software, Vol. 12, No. 4,\n   // December 1986, Pages 377-393.\n   //\n   // See equation 34.\n   //\n   T sum = 1;\n   if(N >= 1)\n   {\n      T partial = x / (a + 1);\n      sum += partial;\n      for(unsigned i = 2; i <= N; ++i)\n      {\n         partial *= x / (a + i);\n         sum += partial;\n         if(partial < tolerance)\n            break;\n      }\n   }\n   return sum;\n}\n\ntemplate <class T, class Policy>\ninline T didonato_FN(T p, T a, T x, unsigned N, T tolerance, const Policy& pol)\n{\n   //\n   // Computation of the Incomplete Gamma Function Ratios and their Inverse\n   // ARMIDO R. DIDONATO and ALFRED H. MORRIS, JR.\n   // ACM Transactions on Mathematical Software, Vol. 12, No. 4,\n   // December 1986, Pages 377-393.\n   //\n   // See equation 34.\n   //\n   BOOST_MATH_STD_USING\n   T u = log(p) + boost::math::lgamma(a + 1, pol);\n   return exp((u + x - log(didonato_SN(a, x, N, tolerance))) / a);\n}\n\ntemplate <class T, class Policy>\nT find_inverse_gamma(T a, T p, T q, const Policy& pol, bool* p_has_10_digits)\n{\n   //\n   // In order to understand what's going on here, you will\n   // need to refer to:\n   //\n   // Computation of the Incomplete Gamma Function Ratios and their Inverse\n   // ARMIDO R. DIDONATO and ALFRED H. MORRIS, JR.\n   // ACM Transactions on Mathematical Software, Vol. 12, No. 4,\n   // December 1986, Pages 377-393.\n   //\n   BOOST_MATH_STD_USING\n\n   T result;\n   *p_has_10_digits = false;\n\n   if(a == 1)\n   {\n      result = -log(q);\n      BOOST_MATH_INSTRUMENT_VARIABLE(result);\n   }\n   else if(a < 1)\n   {\n      T g = boost::math::tgamma(a, pol);\n      T b = q * g;\n      BOOST_MATH_INSTRUMENT_VARIABLE(g);\n      BOOST_MATH_INSTRUMENT_VARIABLE(b);\n      if((b > 0.6) || ((b >= 0.45) && (a >= 0.3)))\n      {\n         // DiDonato & Morris Eq 21:\n         //\n         // There is a slight variation from DiDonato and Morris here:\n         // the first form given here is unstable when p is close to 1,\n         // making it impossible to compute the inverse of Q(a,x) for small\n         // q.  Fortunately the second form works perfectly well in this case.\n         //\n         T u;\n         if((b * q > 1e-8) && (q > 1e-5))\n         {\n            u = pow(p * g * a, 1 / a);\n            BOOST_MATH_INSTRUMENT_VARIABLE(u);\n         }\n         else\n         {\n            u = exp((-q / a) - constants::euler<T>());\n            BOOST_MATH_INSTRUMENT_VARIABLE(u);\n         }\n         result = u / (1 - (u / (a + 1)));\n         BOOST_MATH_INSTRUMENT_VARIABLE(result);\n      }\n      else if((a < 0.3) && (b >= 0.35))\n      {\n         // DiDonato & Morris Eq 22:\n         T t = exp(-constants::euler<T>() - b);\n         T u = t * exp(t);\n         result = t * exp(u);\n         BOOST_MATH_INSTRUMENT_VARIABLE(result);\n      }\n      else if((b > 0.15) || (a >= 0.3))\n      {\n         // DiDonato & Morris Eq 23:\n         T y = -log(b);\n         T u = y - (1 - a) * log(y);\n         result = y - (1 - a) * log(u) - log(1 + (1 - a) / (1 + u));\n         BOOST_MATH_INSTRUMENT_VARIABLE(result);\n      }\n      else if (b > 0.1)\n      {\n         // DiDonato & Morris Eq 24:\n         T y = -log(b);\n         T u = y - (1 - a) * log(y);\n         result = y - (1 - a) * log(u) - log((u * u + 2 * (3 - a) * u + (2 - a) * (3 - a)) / (u * u + (5 - a) * u + 2));\n         BOOST_MATH_INSTRUMENT_VARIABLE(result);\n      }\n      else\n      {\n         // DiDonato & Morris Eq 25:\n         T y = -log(b);\n         T c1 = (a - 1) * log(y);\n         T c1_2 = c1 * c1;\n         T c1_3 = c1_2 * c1;\n         T c1_4 = c1_2 * c1_2;\n         T a_2 = a * a;\n         T a_3 = a_2 * a;\n\n         T c2 = (a - 1) * (1 + c1);\n         T c3 = (a - 1) * (-(c1_2 / 2) + (a - 2) * c1 + (3 * a - 5) / 2);\n         T c4 = (a - 1) * ((c1_3 / 3) - (3 * a - 5) * c1_2 / 2 + (a_2 - 6 * a + 7) * c1 + (11 * a_2 - 46 * a + 47) / 6);\n         T c5 = (a - 1) * (-(c1_4 / 4)\n                           + (11 * a - 17) * c1_3 / 6\n                           + (-3 * a_2 + 13 * a -13) * c1_2\n                           + (2 * a_3 - 25 * a_2 + 72 * a - 61) * c1 / 2\n                           + (25 * a_3 - 195 * a_2 + 477 * a - 379) / 12);\n\n         T y_2 = y * y;\n         T y_3 = y_2 * y;\n         T y_4 = y_2 * y_2;\n         result = y + c1 + (c2 / y) + (c3 / y_2) + (c4 / y_3) + (c5 / y_4);\n         BOOST_MATH_INSTRUMENT_VARIABLE(result);\n         if(b < 1e-28f)\n            *p_has_10_digits = true;\n      }\n   }\n   else\n   {\n      // DiDonato and Morris Eq 31:\n      T s = find_inverse_s(p, q);\n\n      BOOST_MATH_INSTRUMENT_VARIABLE(s);\n\n      T s_2 = s * s;\n      T s_3 = s_2 * s;\n      T s_4 = s_2 * s_2;\n      T s_5 = s_4 * s;\n      T ra = sqrt(a);\n\n      BOOST_MATH_INSTRUMENT_VARIABLE(ra);\n\n      T w = a + s * ra + (s * s -1) / 3;\n      w += (s_3 - 7 * s) / (36 * ra);\n      w -= (3 * s_4 + 7 * s_2 - 16) / (810 * a);\n      w += (9 * s_5 + 256 * s_3 - 433 * s) / (38880 * a * ra);\n\n      BOOST_MATH_INSTRUMENT_VARIABLE(w);\n\n      if((a >= 500) && (fabs(1 - w / a) < 1e-6))\n      {\n         result = w;\n         *p_has_10_digits = true;\n         BOOST_MATH_INSTRUMENT_VARIABLE(result);\n      }\n      else if (p > 0.5)\n      {\n         if(w < 3 * a)\n         {\n            result = w;\n            BOOST_MATH_INSTRUMENT_VARIABLE(result);\n         }\n         else\n         {\n            T D = (std::max)(T(2), T(a * (a - 1)));\n            T lg = boost::math::lgamma(a, pol);\n            T lb = log(q) + lg;\n            if(lb < -D * 2.3)\n            {\n               // DiDonato and Morris Eq 25:\n               T y = -lb;\n               T c1 = (a - 1) * log(y);\n               T c1_2 = c1 * c1;\n               T c1_3 = c1_2 * c1;\n               T c1_4 = c1_2 * c1_2;\n               T a_2 = a * a;\n               T a_3 = a_2 * a;\n\n               T c2 = (a - 1) * (1 + c1);\n               T c3 = (a - 1) * (-(c1_2 / 2) + (a - 2) * c1 + (3 * a - 5) / 2);\n               T c4 = (a - 1) * ((c1_3 / 3) - (3 * a - 5) * c1_2 / 2 + (a_2 - 6 * a + 7) * c1 + (11 * a_2 - 46 * a + 47) / 6);\n               T c5 = (a - 1) * (-(c1_4 / 4)\n                                 + (11 * a - 17) * c1_3 / 6\n                                 + (-3 * a_2 + 13 * a -13) * c1_2\n                                 + (2 * a_3 - 25 * a_2 + 72 * a - 61) * c1 / 2\n                                 + (25 * a_3 - 195 * a_2 + 477 * a - 379) / 12);\n\n               T y_2 = y * y;\n               T y_3 = y_2 * y;\n               T y_4 = y_2 * y_2;\n               result = y + c1 + (c2 / y) + (c3 / y_2) + (c4 / y_3) + (c5 / y_4);\n               BOOST_MATH_INSTRUMENT_VARIABLE(result);\n            }\n            else\n            {\n               // DiDonato and Morris Eq 33:\n               T u = -lb + (a - 1) * log(w) - log(1 + (1 - a) / (1 + w));\n               result = -lb + (a - 1) * log(u) - log(1 + (1 - a) / (1 + u));\n               BOOST_MATH_INSTRUMENT_VARIABLE(result);\n            }\n         }\n      }\n      else\n      {\n         T z = w;\n         T ap1 = a + 1;\n         if(w < 0.15f * ap1)\n         {\n            // DiDonato and Morris Eq 35:\n            T v = log(p) + boost::math::lgamma(ap1, pol);\n            T s = 1;\n            z = exp((v + w) / a);\n            s = boost::math::log1p(z / ap1 * (1 + z / (a + 2)));\n            z = exp((v + z - s) / a);\n            z = exp((v + z - s) / a);\n            s = boost::math::log1p(z / ap1 * (1 + z / (a + 2) * (1 + z / (a + 3))));\n            z = exp((v + z - s) / a);\n            BOOST_MATH_INSTRUMENT_VARIABLE(z);\n         }\n\n         if((z <= 0.01 * ap1) || (z > 0.7 * ap1))\n         {\n            result = z;\n            if(z <= 0.002 * ap1)\n               *p_has_10_digits = true;\n            BOOST_MATH_INSTRUMENT_VARIABLE(result);\n         }\n         else\n         {\n            // DiDonato and Morris Eq 36:\n            T ls = log(didonato_SN(a, z, 100, T(1e-4)));\n            T v = log(p) + boost::math::lgamma(ap1, pol);\n            z = exp((v + z - ls) / a);\n            result = z * (1 - (a * log(z) - z - v + ls) / (a - z));\n\n            BOOST_MATH_INSTRUMENT_VARIABLE(result);\n         }\n      }\n   }\n   return result;\n}\n\ntemplate <class T, class Policy>\nstruct gamma_p_inverse_func\n{\n   gamma_p_inverse_func(T a_, T p_, bool inv) : a(a_), p(p_), invert(inv)\n   {\n      //\n      // If p is too near 1 then P(x) - p suffers from cancellation\n      // errors causing our root-finding algorithms to \"thrash\", better\n      // to invert in this case and calculate Q(x) - (1-p) instead.\n      //\n      // Of course if p is *very* close to 1, then the answer we get will\n      // be inaccurate anyway (because there's not enough information in p)\n      // but at least we will converge on the (inaccurate) answer quickly.\n      //\n      if(p > 0.9)\n      {\n         p = 1 - p;\n         invert = !invert;\n      }\n   }\n\n   std::tr1::tuple<T, T, T> operator()(const T& x)const\n   {\n      BOOST_FPU_EXCEPTION_GUARD\n      //\n      // Calculate P(x) - p and the first two derivates, or if the invert\n      // flag is set, then Q(x) - q and it's derivatives.\n      //\n      typedef typename policies::evaluation<T, Policy>::type value_type;\n      typedef typename lanczos::lanczos<T, Policy>::type evaluation_type;\n      typedef typename policies::normalise<\n         Policy, \n         policies::promote_float<false>, \n         policies::promote_double<false>, \n         policies::discrete_quantile<>,\n         policies::assert_undefined<> >::type forwarding_policy;\n\n      BOOST_MATH_STD_USING  // For ADL of std functions.\n\n      T f, f1;\n      value_type ft;\n      f = static_cast<T>(boost::math::detail::gamma_incomplete_imp(\n               static_cast<value_type>(a), \n               static_cast<value_type>(x), \n               true, invert,\n               forwarding_policy(), &ft));\n      f1 = static_cast<T>(ft);\n      T f2;\n      T div = (a - x - 1) / x;\n      f2 = f1;\n      if((fabs(div) > 1) && (tools::max_value<T>() / fabs(div) < f2))\n      {\n         // overflow:\n         f2 = -tools::max_value<T>() / 2;\n      }\n      else\n      {\n         f2 *= div;\n      }\n\n      if(invert)\n      {\n         f1 = -f1;\n         f2 = -f2;\n      }\n\n      return std::tr1::make_tuple(f - p, f1, f2);\n   }\nprivate:\n   T a, p;\n   bool invert;\n};\n\ntemplate <class T, class Policy>\nT gamma_p_inv_imp(T a, T p, const Policy& pol)\n{\n   BOOST_MATH_STD_USING  // ADL of std functions.\n\n   static const char* function = \"boost::math::gamma_p_inv<%1%>(%1%, %1%)\";\n\n   BOOST_MATH_INSTRUMENT_VARIABLE(a);\n   BOOST_MATH_INSTRUMENT_VARIABLE(p);\n\n   if(a <= 0)\n      policies::raise_domain_error<T>(function, \"Argument a in the incomplete gamma function inverse must be >= 0 (got a=%1%).\", a, pol);\n   if((p < 0) || (p > 1))\n      policies::raise_domain_error<T>(function, \"Probabilty must be in the range [0,1] in the incomplete gamma function inverse (got p=%1%).\", p, pol);\n   if(p == 1)\n      return tools::max_value<T>();\n   if(p == 0)\n      return 0;\n   bool has_10_digits;\n   T guess = detail::find_inverse_gamma<T>(a, p, 1 - p, pol, &has_10_digits);\n   if((policies::digits<T, Policy>() <= 36) && has_10_digits)\n      return guess;\n   T lower = tools::min_value<T>();\n   if(guess <= lower)\n      guess = tools::min_value<T>();\n   BOOST_MATH_INSTRUMENT_VARIABLE(guess);\n   //\n   // Work out how many digits to converge to, normally this is\n   // 2/3 of the digits in T, but if the first derivative is very\n   // large convergence is slow, so we'll bump it up to full \n   // precision to prevent premature termination of the root-finding routine.\n   //\n   unsigned digits = policies::digits<T, Policy>();\n   if(digits < 30)\n   {\n      digits *= 2;\n      digits /= 3;\n   }\n   else\n   {\n      digits /= 2;\n      digits -= 1;\n   }\n   if((a < 0.125) && (fabs(gamma_p_derivative(a, guess, pol)) > 1 / sqrt(tools::epsilon<T>())))\n      digits = policies::digits<T, Policy>() - 2;\n   //\n   // Go ahead and iterate:\n   //\n   boost::uintmax_t max_iter = policies::get_max_root_iterations<Policy>();\n   guess = tools::halley_iterate(\n      detail::gamma_p_inverse_func<T, Policy>(a, p, false),\n      guess,\n      lower,\n      tools::max_value<T>(),\n      digits,\n      max_iter);\n   policies::check_root_iterations(function, max_iter, pol);\n   BOOST_MATH_INSTRUMENT_VARIABLE(guess);\n   if(guess == lower)\n      guess = policies::raise_underflow_error<T>(function, \"Expected result known to be non-zero, but is smaller than the smallest available number.\", pol);\n   return guess;\n}\n\ntemplate <class T, class Policy>\nT gamma_q_inv_imp(T a, T q, const Policy& pol)\n{\n   BOOST_MATH_STD_USING  // ADL of std functions.\n\n   static const char* function = \"boost::math::gamma_q_inv<%1%>(%1%, %1%)\";\n\n   if(a <= 0)\n      policies::raise_domain_error<T>(function, \"Argument a in the incomplete gamma function inverse must be >= 0 (got a=%1%).\", a, pol);\n   if((q < 0) || (q > 1))\n      policies::raise_domain_error<T>(function, \"Probabilty must be in the range [0,1] in the incomplete gamma function inverse (got q=%1%).\", q, pol);\n   if(q == 0)\n      return tools::max_value<T>();\n   if(q == 1)\n      return 0;\n   bool has_10_digits;\n   T guess = detail::find_inverse_gamma<T>(a, 1 - q, q, pol, &has_10_digits);\n   if((policies::digits<T, Policy>() <= 36) && has_10_digits)\n      return guess;\n   T lower = tools::min_value<T>();\n   if(guess <= lower)\n      guess = tools::min_value<T>();\n   //\n   // Work out how many digits to converge to, normally this is\n   // 2/3 of the digits in T, but if the first derivative is very\n   // large convergence is slow, so we'll bump it up to full \n   // precision to prevent premature termination of the root-finding routine.\n   //\n   unsigned digits = policies::digits<T, Policy>();\n   if(digits < 30)\n   {\n      digits *= 2;\n      digits /= 3;\n   }\n   else\n   {\n      digits /= 2;\n      digits -= 1;\n   }\n   if((a < 0.125) && (fabs(gamma_p_derivative(a, guess, pol)) > 1 / sqrt(tools::epsilon<T>())))\n      digits = policies::digits<T, Policy>();\n   //\n   // Go ahead and iterate:\n   //\n   boost::uintmax_t max_iter = policies::get_max_root_iterations<Policy>();\n   guess = tools::halley_iterate(\n      detail::gamma_p_inverse_func<T, Policy>(a, q, true),\n      guess,\n      lower,\n      tools::max_value<T>(),\n      digits,\n      max_iter);\n   policies::check_root_iterations(function, max_iter, pol);\n   if(guess == lower)\n      guess = policies::raise_underflow_error<T>(function, \"Expected result known to be non-zero, but is smaller than the smallest available number.\", pol);\n   return guess;\n}\n\n} // namespace detail\n\ntemplate <class T1, class T2, class Policy>\ninline typename tools::promote_args<T1, T2>::type \n   gamma_p_inv(T1 a, T2 p, const Policy& pol)\n{\n   typedef typename tools::promote_args<T1, T2>::type result_type;\n   return detail::gamma_p_inv_imp(\n      static_cast<result_type>(a),\n      static_cast<result_type>(p), pol);\n}\n\ntemplate <class T1, class T2, class Policy>\ninline typename tools::promote_args<T1, T2>::type \n   gamma_q_inv(T1 a, T2 p, const Policy& pol)\n{\n   typedef typename tools::promote_args<T1, T2>::type result_type;\n   return detail::gamma_q_inv_imp(\n      static_cast<result_type>(a),\n      static_cast<result_type>(p), pol);\n}\n\ntemplate <class T1, class T2>\ninline typename tools::promote_args<T1, T2>::type \n   gamma_p_inv(T1 a, T2 p)\n{\n   return gamma_p_inv(a, p, policies::policy<>());\n}\n\ntemplate <class T1, class T2>\ninline typename tools::promote_args<T1, T2>::type \n   gamma_q_inv(T1 a, T2 p)\n{\n   return gamma_q_inv(a, p, policies::policy<>());\n}\n\n} // namespace math\n} // namespace boost\n\n#endif // BOOST_MATH_SPECIAL_FUNCTIONS_IGAMMA_INVERSE_HPP\n\n\n\n", "meta": {"hexsha": "a7dce6f99b5667f5d1ba1fc789456800191f6425", "size": 17204, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "external/boost_1_44_0/boost/math/special_functions/detail/igamma_inverse.hpp", "max_stars_repo_name": "RaptDept/slimtune", "max_stars_repo_head_hexsha": "a9a248a342a51d95b7c833bce5bb91bf3db987f3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 26.0, "max_stars_repo_stars_event_min_datetime": "2015-07-01T03:26:50.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-06T06:00:38.000Z", "max_issues_repo_path": "external/boost_1_44_0/boost/math/special_functions/detail/igamma_inverse.hpp", "max_issues_repo_name": "RaptDept/slimtune", "max_issues_repo_head_hexsha": "a9a248a342a51d95b7c833bce5bb91bf3db987f3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-12-02T17:31:28.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-02T17:31:28.000Z", "max_forks_repo_path": "external/boost_1_44_0/boost/math/special_functions/detail/igamma_inverse.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-02-05T19:34:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-01T08:46:34.000Z", "avg_line_length": 31.22323049, "max_line_length": 156, "alphanum_fraction": 0.5278423622, "num_tokens": 5423, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.6406358617010351, "lm_q1q2_score": 0.47418224023387917}}
{"text": "//          Copyright Carl Philipp Reh 2009 - 2016.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n\n#include <fcppt/make_int_range_count.hpp>\n#include <fcppt/tag_type.hpp>\n#include <fcppt/use.hpp>\n#include <fcppt/algorithm/loop.hpp>\n#include <fcppt/algorithm/loop_break_mpl.hpp>\n#include <fcppt/preprocessor/disable_gcc_warning.hpp>\n#include <fcppt/preprocessor/pop_warning.hpp>\n#include <fcppt/preprocessor/push_warning.hpp>\n#include <fcppt/config/external_begin.hpp>\n#include <boost/mpl/range_c.hpp>\n#include <boost/test/unit_test.hpp>\n#include <fcppt/config/external_end.hpp>\n\n\nFCPPT_PP_PUSH_WARNING\nFCPPT_PP_DISABLE_GCC_WARNING(-Weffc++)\n\nBOOST_AUTO_TEST_CASE(\n\talgorithm_loop_mpl\n)\n{\nFCPPT_PP_POP_WARNING\n\n\tint value{\n\t\t0\n\t};\n\n\tfcppt::algorithm::loop(\n\t\tboost::mpl::range_c<\n\t\t\tint,\n\t\t\t0,\n\t\t\t5\n\t\t>{},\n\t\t[\n\t\t\t&value\n\t\t](\n\t\t\tauto const _index\n\t\t)\n\t\t{\n\t\t\tFCPPT_USE(\n\t\t\t\t_index\n\t\t\t);\n\n\t\t\ttypedef\n\t\t\tfcppt::tag_type<\n\t\t\t\tdecltype(\n\t\t\t\t\t_index\n\t\t\t\t)\n\t\t\t>\n\t\t\tindex;\n\n\t\t\tstatic_assert(\n\t\t\t\tindex::value\n\t\t\t\t<\n\t\t\t\t5,\n\t\t\t\t\"\"\n\t\t\t);\n\n\t\t\tvalue +=\n\t\t\t\tindex::value;\n\t\t}\n\t);\n\n\tBOOST_CHECK_EQUAL(\n\t\tvalue,\n\t\t10\n\t);\n}\n\nFCPPT_PP_PUSH_WARNING\nFCPPT_PP_DISABLE_GCC_WARNING(-Weffc++)\n\nBOOST_AUTO_TEST_CASE(\n\talgorithm_loop_range\n)\n{\nFCPPT_PP_POP_WARNING\n\n\tint value{\n\t\t0\n\t};\n\n\tfcppt::algorithm::loop(\n\t\tfcppt::make_int_range_count(\n\t\t\t5\n\t\t),\n\t\t[\n\t\t\t&value\n\t\t](\n\t\t\tint const _value\n\t\t)\n\t\t{\n\t\t\tvalue +=\n\t\t\t\t_value;\n\t\t}\n\t);\n\n\tBOOST_CHECK_EQUAL(\n\t\tvalue,\n\t\t10\n\t);\n}\n", "meta": {"hexsha": "58c95c677fea2c14535fce1b62b52caaa2de8e91", "size": 1568, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/algorithm/loop.cpp", "max_stars_repo_name": "vinzenz/fcppt", "max_stars_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "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": "test/algorithm/loop.cpp", "max_issues_repo_name": "vinzenz/fcppt", "max_issues_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "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/algorithm/loop.cpp", "max_forks_repo_name": "vinzenz/fcppt", "max_forks_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "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": 14.3853211009, "max_line_length": 61, "alphanum_fraction": 0.6709183673, "num_tokens": 505, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6406358548398982, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.4741822314836552}}
{"text": "//  Copyright John Maddock 2006.\r\n//  Use, modification and distribution are subject to the\r\n//  Boost Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n//\r\n// Basic sanity check that header <boost/math/special_functions/bessel.hpp>\r\n// #includes all the files that it needs to.\r\n//\r\n#include <boost/math/special_functions/bessel_prime.hpp>\r\n//\r\n// Note this header includes no other headers, this is\r\n// important if this test is to be meaningful:\r\n//\r\n#include \"test_compile_result.hpp\"\r\n\r\nvoid compile_and_link_test()\r\n{\r\n   check_result<float>(boost::math::cyl_bessel_j_prime<float>(f, f));\r\n   check_result<double>(boost::math::cyl_bessel_j_prime<double>(d, d));\r\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\r\n   check_result<long double>(boost::math::cyl_bessel_j_prime<long double>(l, l));\r\n#endif\r\n\r\n   check_result<float>(boost::math::cyl_neumann_prime<float>(f, f));\r\n   check_result<double>(boost::math::cyl_neumann_prime<double>(d, d));\r\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\r\n   check_result<long double>(boost::math::cyl_neumann_prime<long double>(l, l));\r\n#endif\r\n\r\n   check_result<float>(boost::math::cyl_bessel_i_prime<float>(f, f));\r\n   check_result<double>(boost::math::cyl_bessel_i_prime<double>(d, d));\r\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\r\n   check_result<long double>(boost::math::cyl_bessel_i_prime<long double>(l, l));\r\n#endif\r\n\r\n   check_result<float>(boost::math::cyl_bessel_k_prime<float>(f, f));\r\n   check_result<double>(boost::math::cyl_bessel_k_prime<double>(d, d));\r\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\r\n   check_result<long double>(boost::math::cyl_bessel_k_prime<long double>(l, l));\r\n#endif\r\n\r\n   check_result<float>(boost::math::sph_bessel_prime<float>(u, f));\r\n   check_result<double>(boost::math::sph_bessel_prime<double>(u, d));\r\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\r\n   check_result<long double>(boost::math::sph_bessel_prime<long double>(u, l));\r\n#endif\r\n\r\n   check_result<float>(boost::math::sph_neumann_prime<float>(u, f));\r\n   check_result<double>(boost::math::sph_neumann_prime<double>(u, d));\r\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\r\n   check_result<long double>(boost::math::sph_neumann_prime<long double>(u, l));\r\n#endif\r\n}\r\n", "meta": {"hexsha": "b8bd02b1d7223756f0bd9f2eebe20ff51b40190b", "size": 2311, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/math/test/compile_test/sf_bessel_deriv_incl_test.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": 85.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T20:36:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T20:38:31.000Z", "max_issues_repo_path": "libs/boost/libs/math/test/compile_test/sf_bessel_deriv_incl_test.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/test/compile_test/sf_bessel_deriv_incl_test.cpp", "max_forks_repo_name": "flingone/frameworks_base_cmds_remoted", "max_forks_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2015-01-28T16:33:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-12T05:04:39.000Z", "avg_line_length": 42.7962962963, "max_line_length": 82, "alphanum_fraction": 0.7459974037, "num_tokens": 589, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.4741822249985658}}
{"text": "/*\n * dynamics_structure.cpp\n *\n *  Created on: Jan 20, 2021\n *      Author: talhakavuncu\n */\n\n\n\n#include <iostream>\n#include <unsupported/Eigen/AdolcForward>\n#include <adolc/adolc.h>\n#include <Eigen/Dense>\n#include \"dynamics_structure.h\"\nnamespace Unicycle_Dynamics\n{\n\tunicycle_state_tensor dynamics(const unicycle_state_tensor & x,const unicycle_input_tensor & u)\n\t{\n\t\tunicycle_state_tensor x_dot;\n\n\t//\tstd::cout<<\"no issues\"<<std::endl;\n\t//\tstd::cout<<x.rows()<<std::endl;\n\t\tadouble px,py,theta,v,omega,a;\n\t//\tpx=x[0];\n\t//\tpy=x[1];\n\t//\n\t//\ttheta=x[2];\n\t//\n\t//\tv=x[3];\n\t//\n\t//\tomega=u[0];\n\t//\ta=u[1];\n\t//\n\t//\tx_dot[0]=v*cos(theta);\n\t//\tx_dot[1]=v*sin(theta);\n\t//\tx_dot[2]=omega;\n\t//\tx_dot[3]=a;\n\n\t//\tpx=x[0];\n\t//\tpy=x[1];\n\t//\n\t//\ttheta=x[2];\n\t//\n\t//\tv=x[3];\n\t//\n\t//\tomega=u[0];\n\t//\ta=u[1];\n\n\t\tx_dot[0]=x[3]*cos(x[2]);\n\t\tx_dot[1]=x[3]*sin(x[2]);\n\t\tx_dot[2]=u[0];\n\t\tx_dot[3]=u[1];\n\n\t\treturn x_dot;\n\n\t};\n\tunicycle2_state_tensor dynamics_2(const unicycle2_state_tensor & x,const unicycle2_input_tensor & u)\n\t{\n\t\tunicycle2_state_tensor x_dot;\n\n\t\tfor(int i=0;i<2;++i)\n\t\t\tx_dot.segment(4*i,4)=dynamics(x.segment(4*i,4),u.segment(2*i,2));\n\n\t\treturn x_dot;\n\t};\n\tunicycle4_state_tensor dynamics_4(const unicycle4_state_tensor & x,const unicycle4_input_tensor & u)\n\t{\n\t\tunicycle4_state_tensor x_dot;\n\n\t\tfor(int i=0;i<4;++i)\n\t\t\tx_dot.segment(4*i,4)=dynamics(x.segment(4*i,4),u.segment(2*i,2));\n\n\t\treturn x_dot;\n\t};\n\n\tunicycle3_state_tensor dynamics_3(const unicycle3_state_tensor & x,const unicycle3_input_tensor & u)\n\t{\n\t\tunicycle3_state_tensor x_dot;\n\t\tfor(int i=0;i<3;++i)\n\t\t\tx_dot.segment(4*i,4)=dynamics(x.segment(4*i,4),u.segment(2*i,2));\n//\t//\tstd::cout<<\"no issues\"<<std::endl;\n//\t//\tstd::cout<<x.rows()<<std::endl;\n//\t\tadouble px1,py1,theta1,v1,omega1,a1;\n//\t\tadouble px2,py2,theta2,v2,omega2,a2;\n//\t\tadouble px3,py3,theta3,v3,omega3,a3;\n//\t\tpx1=x[0];\n//\t\tpy1=x[1];\n//\t\ttheta1=x[2];\n//\t\tv1=x[3];\n//\t\tomega1=u[0];\n//\t\ta1=u[1];\n//\n//\t\tpx2=x[4];\n//\t\tpy2=x[5];\n//\t\ttheta2=x[6];\n//\t\tv2=x[7];\n//\t\tomega2=u[2];\n//\t\ta2=u[3];\n//\n//\n//\t\tpx3=x[8];\n//\t\tpy3=x[9];\n//\t\ttheta3=x[10];\n//\t\tv3=x[11];\n//\t\tomega3=u[4];\n//\t\ta3=u[5];\n//\n//\t\tx_dot[0]=v1*cos(theta1);\n//\t\tx_dot[1]=v1*sin(theta1);\n//\t\tx_dot[2]=omega1;\n//\t\tx_dot[3]=a1;\n//\n//\t\tx_dot[4]=v2*cos(theta2);\n//\t\tx_dot[5]=v2*sin(theta2);\n//\t\tx_dot[6]=omega2;\n//\t\tx_dot[7]=a2;\n//\n//\t\tx_dot[8]=v3*cos(theta3);\n//\t\tx_dot[9]=v3*sin(theta3);\n//\t\tx_dot[10]=omega3;\n//\t\tx_dot[11]=a3;\n\n\t\treturn x_dot;\n\n\t};\n\n\tunicycle6_state_tensor dynamics_6(const unicycle6_state_tensor & x,const unicycle6_input_tensor & u)\n\t{\n\t\tunicycle6_state_tensor x_dot;\n\t\tfor(int i=0;i<6;++i)\n\t\t\tx_dot.segment(4*i,4)=dynamics(x.segment(4*i,4),u.segment(2*i,2));\n\n\t\treturn x_dot;\n\t}\n}\n\nnamespace Drone_Dynamics{\n\ndrone_state_tensor dynamics(const drone_state_tensor & X,const drone_input_tensor & u)\n{\n\tdrone_state_tensor X_dot;\n\tadouble x,y,z,phi,theta,psi,x_d,y_d,z_d,phi_d,theta_d,psi_d,w1,w2,w3,w4,thrust;\n\tx=X[0];\n\ty=X[1];\n\tz=X[2];\n\tphi=X[3];\n\ttheta=X[4];\n\tpsi=X[5];\n\tx_d=X[6];\n\ty_d=X[7];\n\tz_d=X[8];\n\tphi_d=X[9];\n\ttheta_d=X[10];\n\tpsi_d=X[11];\n\n\tw1=u[0];\n\tw2=u[1];\n\tw3=u[2];\n\tw4=u[3];\n\n\tEigen::Matrix<adouble,3,3> Rsb,mat,mat_inv,I,I_inv;\n\n\tRsb<<cos(theta)*cos(psi), cos(theta)*sin(psi), -sin(theta),\n\t\t-cos(phi)*sin(psi)+sin(theta)*cos(psi)*sin(phi), cos(psi)*cos(phi)+sin(theta)*sin(psi)*sin(phi), sin(phi)*cos(theta),\n\t\tsin(phi)*sin(psi)+cos(phi)*sin(theta)*cos(psi), -sin(phi)*cos(psi)+cos(phi)*sin(theta)*sin(psi), cos(theta)*cos(phi);\n\n\tmat<<1,0,-sin(theta),\n\t\t 0,cos(phi),sin(phi)*cos(theta),\n\t\t 0,-sin(phi),cos(theta)*cos(phi);\n\n\tmat_inv<<1,sin(phi)*tan(theta),cos(phi)*tan(theta),\n\t\t\t0,cos(phi),-sin(phi),\n\t\t\t0,sin(phi)/cos(theta),cos(phi)/cos(theta);\n\n\n\tI<<I_xx,0,0,\n\t\t0,I_yy,0,\n\t\t0,0,I_zz;\n\n\tI_inv<<1/I_xx,0,0,\n\t\t0,1/I_yy,0,\n\t\t0,0,1/I_zz;\n\n\n\n\n\n\tthrust=C_T*(w1*w1 + w2*w2 + w3*w3 + w4*w4);\n\n\tEigen::Matrix<adouble,3,1> angle_dots,Omega_in,v_dots,gravity_term,thrust_term,pos_dots,Omega_b,L_b,Moments,angle_ddots,temp;\n\tEigen::Matrix<adouble,3,3> skew1,skew2;\n\tpos_dots<<x_d,y_d,z_d;\n\tgravity_term<<0,0,g;\n\tthrust_term<<0,0,thrust/mass;\n\tangle_dots<<phi_d,theta_d,psi_d;\n\tOmega_in=Rsb*(mat*angle_dots);\n//\ttemp=Omega_in.cross(pos_dots);\n\tskew1<<0,-Omega_in[2],Omega_in[1],\n\t\t\tOmega_in[2],0,-Omega_in[0],\n\t\t\t-Omega_in[1],Omega_in[0],0;\n\tv_dots=Rsb*thrust_term-gravity_term-skew1*pos_dots;//Omega_in.cross(pos_dots);\n\n\tX_dot[0]=x_d;\n\tX_dot[1]=y_d;\n\tX_dot[2]=z_d;\n\tX_dot[3]=phi_d;\n\tX_dot[4]=theta_d;\n\tX_dot[5]=psi_d;\n\tX_dot[6]=v_dots[0];\n\tX_dot[7]=v_dots[1];\n\tX_dot[8]=v_dots[2];\n\n\tOmega_b=mat*angle_dots;\n\n\tL_b=I*Omega_b;\n\n\tMoments<<d*C_T/sqrt(2)*(-w1*w1-w2*w2+w3*w3+w4*w4),\n\t\t\td*C_T/sqrt(2)*(-w1*w1+w2*w2+w3*w3-w4*w4),\n\t\t\tC_D*(-w1*w1+w2*w2-w3*w3+w4*w4);\n\n\tskew2<<0,-Omega_b[2],Omega_b[1],\n\t\t\tOmega_b[2],0,-Omega_b[0],\n\t\t\t-Omega_b[1],Omega_b[0],0;\n\n\tangle_ddots=mat_inv*(I_inv*(Moments-skew2*L_b));//mat_inv*(I_inv*(Moments-Omega_b.cross(L_b))); //Euler's eqn.\n\n\tX_dot[9]=angle_ddots[0];\n\tX_dot[10]=angle_ddots[1];\n\tX_dot[11]=angle_ddots[2];\n\n\treturn X_dot;\n\n};\n\ndrone2_state_tensor dynamics_2(const drone2_state_tensor & X,const drone2_input_tensor & u)\n{\n\tdrone2_state_tensor X_dot;\n\tdrone_state_tensor X_dot1,X_dot2;\n\tX_dot1=dynamics(X.segment(0, 12),u.segment(0,4));\n\tX_dot2=dynamics(X.segment(12, 12),u.segment(4,4));\n\tX_dot<<X_dot1,X_dot2;\n\treturn X_dot;\n\n//\tdrone2_state_tensor X_dot;\n//\tadouble x1,y1,z1,phi1,theta1,psi1,x_d1,y_d1,z_d1,phi_d1,theta_d1,psi_d1,w11,w21,w31,w41,thrust1;\n//\tadouble x2,y2,z2,phi2,theta2,psi2,x_d2,y_d2,z_d2,phi_d2,theta_d2,psi_d2,w12,w22,w32,w42,thrust2;\n//\tx1=X[0];\n//\ty1=X[1];\n//\tz1=X[2];\n//\tphi1=X[3];\n//\ttheta1=X[4];\n//\tpsi1=X[5];\n//\tx_d1=X[6];\n//\ty_d1=X[7];\n//\tz_d1=X[8];\n//\tphi_d1=X[9];\n//\ttheta_d1=X[10];\n//\tpsi_d1=X[11];\n//\n//\tw11=u[0];\n//\tw21=u[1];\n//\tw31=u[2];\n//\tw41=u[3];\n//\n//\tx2=X[12];\n//\ty2=X[13];\n//\tz2=X[14];\n//\tphi2=X[15];\n//\ttheta2=X[16];\n//\tpsi2=X[17];\n//\tx_d2=X[18];\n//\ty_d2=X[19];\n//\tz_d2=X[20];\n//\tphi_d2=X[21];\n//\ttheta_d2=X[22];\n//\tpsi_d2=X[23];\n//\n//\tw12=u[4];\n//\tw22=u[5];\n//\tw32=u[6];\n//\tw42=u[7];\n//\n//\tEigen::Matrix<adouble,3,3> Rsb1,mat1,mat_inv1,I,I_inv,\n//\tRsb2,mat2,mat_inv2;\n//\n//\tRsb1<<cos(theta1)*cos(psi1), cos(theta1)*sin(psi1), -sin(theta1),\n//\t\t-cos(phi1)*sin(psi1)+sin(theta1)*cos(psi1)*sin(phi1), cos(psi1)*cos(phi1)+sin(theta1)*sin(psi1)*sin(phi1), sin(phi1)*cos(theta1),\n//\t\tsin(phi1)*sin(psi1)+cos(phi1)*sin(theta1)*cos(psi1), -sin(phi1)*cos(psi1)+cos(phi1)*sin(theta1)*sin(psi1), cos(theta1)*cos(phi1);\n//\n//\tmat1<<1,0,-sin(theta1),\n//\t\t 0,cos(phi1),sin(phi1)*cos(theta1),\n//\t\t 0,-sin(phi1),cos(theta1)*cos(phi1);\n//\n//\tmat_inv1<<1,sin(phi1)*tan(theta1),cos(phi1)*tan(theta1),\n//\t\t\t0,cos(phi1),-sin(phi1),\n//\t\t\t0,sin(phi1)/cos(theta1),cos(phi1)/cos(theta1);\n//\n//\n//\n//\tRsb2<<cos(theta2)*cos(psi2), cos(theta2)*sin(psi2), -sin(theta2),\n//\t\t-cos(phi2)*sin(psi2)+sin(theta2)*cos(psi2)*sin(phi2), cos(psi2)*cos(phi2)+sin(theta2)*sin(psi2)*sin(phi2), sin(phi2)*cos(theta2),\n//\t\tsin(phi2)*sin(psi2)+cos(phi2)*sin(theta2)*cos(psi2), -sin(phi2)*cos(psi2)+cos(phi2)*sin(theta2)*sin(psi2), cos(theta2)*cos(phi2);\n//\n//\tmat2<<1,0,-sin(theta2),\n//\t\t 0,cos(phi2),sin(phi2)*cos(theta2),\n//\t\t 0,-sin(phi2),cos(theta2)*cos(phi2);\n//\n//\tmat_inv2<<1,sin(phi2)*tan(theta2),cos(phi2)*tan(theta2),\n//\t\t\t0,cos(phi2),-sin(phi2),\n//\t\t\t0,sin(phi2)/cos(theta2),cos(phi2)/cos(theta2);\n//\n//\n//\tI<<I_xx,0,0,\n//\t\t0,I_yy,0,\n//\t\t0,0,I_zz;\n//\n//\tI_inv<<1/I_xx,0,0,\n//\t\t0,1/I_yy,0,\n//\t\t0,0,1/I_zz;\n//\n//\n//\n//\n//\n//\tthrust1=C_T*(w11*w11 + w21*w21 + w31*w31 + w41*w41);\n//\tthrust2=C_T*(w12*w12 + w22*w22 + w32*w32 + w42*w42);\n//\n//\tEigen::Matrix<adouble,3,1> angle_dots1,Omega_in1,v_dots1,gravity_term1,thrust_term1,pos_dots1,Omega_b1,L_b1,Moments1,angle_ddots1,temp1;\n//\tEigen::Matrix<adouble,3,1> angle_dots2,Omega_in2,v_dots2,gravity_term2,thrust_term2,pos_dots2,Omega_b2,L_b2,Moments2,angle_ddots2,temp2;\n//\tEigen::Matrix<adouble,3,3> skew11,skew21,skew12,skew22;\n//\tpos_dots1<<x_d1,y_d1,z_d1;\n//\tgravity_term1<<0,0,g;\n//\tthrust_term1<<0,0,thrust1/mass;\n//\tangle_dots1<<phi_d1,theta_d1,psi_d1;\n//\tOmega_in1=Rsb1*(mat1*angle_dots1);\n////\ttemp=Omega_in.cross(pos_dots);\n//\tskew11<<0,-Omega_in1[2],Omega_in1[1],\n//\t\t\tOmega_in1[2],0,-Omega_in1[0],\n//\t\t\t-Omega_in1[1],Omega_in1[0],0;\n//\tv_dots1=Rsb1*thrust_term1-gravity_term1-skew11*pos_dots1;//Omega_in.cross(pos_dots);\n//\n//\tpos_dots2<<x_d2,y_d2,z_d2;\n//\tgravity_term2<<0,0,g;\n//\tthrust_term2<<0,0,thrust2/mass;\n//\tangle_dots2<<phi_d2,theta_d2,psi_d2;\n//\tOmega_in2=Rsb2*(mat2*angle_dots2);\n////\ttemp=Omega_in.cross(pos_dots);\n//\tskew12<<0,-Omega_in2[2],Omega_in2[1],\n//\t\t\tOmega_in2[2],0,-Omega_in2[0],\n//\t\t\t-Omega_in2[1],Omega_in2[0],0;\n//\tv_dots2=Rsb2*thrust_term2-gravity_term2-skew12*pos_dots2;//Omega_in.cross(pos_dots);\n//\n//\n//\n//\n//\n//\tX_dot[0]=x_d1;\n//\tX_dot[1]=y_d1;\n//\tX_dot[2]=z_d1;\n//\tX_dot[3]=phi_d1;\n//\tX_dot[4]=theta_d1;\n//\tX_dot[5]=psi_d1;\n//\tX_dot[6]=v_dots1[0];\n//\tX_dot[7]=v_dots1[1];\n//\tX_dot[8]=v_dots1[2];\n//\n//\tX_dot[12]=x_d2;\n//\tX_dot[13]=y_d2;\n//\tX_dot[14]=z_d2;\n//\tX_dot[15]=phi_d2;\n//\tX_dot[16]=theta_d2;\n//\tX_dot[17]=psi_d2;\n//\tX_dot[18]=v_dots2[0];\n//\tX_dot[19]=v_dots2[1];\n//\tX_dot[20]=v_dots2[2];\n//\n//\tOmega_b1=mat1*angle_dots1;\n//\tOmega_b2=mat2*angle_dots2;\n//\n//\tL_b1=I*Omega_b1;\n//\tL_b2=I*Omega_b2;\n//\n//\tMoments1<<d*C_T/sqrt(2)*(-w11*w11-w21*w21+w31*w31+w41*w41),\n//\t\t\td*C_T/sqrt(2)*(-w11*w11+w21*w21+w31*w31-w41*w41),\n//\t\t\tC_D*(-w11*w11+w21*w21-w31*w31+w41*w41);\n//\n//\tMoments2<<d*C_T/sqrt(2)*(-w12*w12-w22*w22+w32*w32+w42*w42),\n//\t\t\td*C_T/sqrt(2)*(-w12*w12+w22*w22+w32*w32-w42*w42),\n//\t\t\tC_D*(-w12*w12+w22*w22-w32*w32+w42*w42);\n//\n//\tskew21<<0,-Omega_b1[2],Omega_b1[1],\n//\t\t\tOmega_b1[2],0,-Omega_b1[0],\n//\t\t\t-Omega_b1[1],Omega_b1[0],0;\n//\n//\tskew22<<0,-Omega_b2[2],Omega_b2[1],\n//\t\t\tOmega_b2[2],0,-Omega_b2[0],\n//\t\t\t-Omega_b2[1],Omega_b2[0],0;\n//\n//\n//\tangle_ddots1=mat_inv1*(I_inv*(Moments1-skew21*L_b1));//mat_inv*(I_inv*(Moments-Omega_b.cross(L_b))); //Euler's eqn.\n//\n//\n//\tangle_ddots2=mat_inv2*(I_inv*(Moments2-skew22*L_b2));\n//\n//\n//\tX_dot[9]=angle_ddots1[0];\n//\tX_dot[10]=angle_ddots1[1];\n//\tX_dot[11]=angle_ddots1[2];\n//\n//\tX_dot[21]=angle_ddots2[0];\n//\tX_dot[22]=angle_ddots2[1];\n//\tX_dot[23]=angle_ddots2[2];\n//\n//\treturn X_dot;\n\n\n\n\n\n}\n\n}\n\nnamespace Single_Integrator_3D\n{\n\tstate_tensor dynamics(const state_tensor & x, const input_tensor & u)\n\t{\n\t\treturn u;\n\t};\n\n\tstate_tensor2 dynamics2(const state_tensor2 & x, const input_tensor2 & u)\n\t{\n\t\treturn u;\n\t}\n}\nnamespace Double_Integrator_3D\n{\n\tstate_tensor dynamics(const state_tensor & x, const input_tensor & u)\n\t{\n\t\tstate_tensor x_dot;\n\t\tx_dot[0]=x[3];\n\t\tx_dot[1]=x[4];\n\t\tx_dot[2]=x[5];\n\t\tx_dot[3]=u[0]/mb;\n\t\tx_dot[4]=u[1]/mb;\n\t\tx_dot[5]=u[2]/mb;\n\n\t\treturn x_dot;\n\t};\n//\n//\tstate_tensor2 dynamics2(const state_tensor2 & x, const input_tensor2 & u)\n//\t{\n//\t\treturn u;\n//\t}\n}\nnamespace Drone_First_Order_Dynamics\n{\n\ttypedef Eigen::Matrix<adouble,6,1> drone_state_tensor;\n\ttypedef Eigen::Matrix<adouble,6,1> drone_input_tensor;\n\n\ttypedef Eigen::Matrix<adouble,6*2,1> drone2_state_tensor;\n\ttypedef Eigen::Matrix<adouble,6*2,1> drone2_input_tensor;\n\n//\tconst double C_T=3.1582*1e-10;\n//\tconst double C_D=7.9379*1e-12;\n//\tconst double g=9.80665;\n//\tconst double d=39.73*1e-3;\n//\tconst double I_xx=1.395*1e-5;\n//\tconst double I_yy=1.436*1e-5;\n//\tconst double I_zz=2.173*1e-5;\n//\tconst double mass=0.033;\n\tdrone_state_tensor dynamics(const drone_state_tensor & X,const drone_input_tensor & input)\n\t{\n\t\tadouble x,y,z,phi,theta,psi,u,v,w,p,q,r,x_d,y_d,z_d,phi_d,theta_d,psi_d;\n\t\tdrone_state_tensor x_dot;\n\t\tu=input[0];\n\t\tv=input[1];\n\t\tw=input[2];\n\t\tp=input[3];\n\t\tq=input[4];\n\t\tr=input[5];\n\t\tEigen::Matrix<adouble,3,3> Rsb,mat,mat_inv;\n\t\tEigen::Matrix<adouble,3,1> v_b,w_b,v_i,euler_d;\n\n\t\tv_b<<u,v,w;\n\t\tw_b<<p,q,r;\n\n\t\tRsb<<cos(theta)*cos(psi), cos(theta)*sin(psi), -sin(theta),\n\t\t\t\t-cos(phi)*sin(psi)+sin(theta)*cos(psi)*sin(phi), cos(psi)*cos(phi)+sin(theta)*sin(psi)*sin(phi), sin(phi)*cos(theta),\n\t\t\t\tsin(phi)*sin(psi)+cos(phi)*sin(theta)*cos(psi), -sin(phi)*cos(psi)+cos(phi)*sin(theta)*sin(psi), cos(theta)*cos(phi);\n\n//\t\tmat<<1,0,-sin(theta),\n//\t\t\t 0,cos(phi),sin(phi)*cos(theta),\n//\t\t\t 0,-sin(phi),cos(theta)*cos(phi);\n\n\t\tmat_inv<<1,sin(phi)*tan(theta),cos(phi)*tan(theta),\n\t\t\t\t0,cos(phi),-sin(phi),\n\t\t\t\t0,sin(phi)/cos(theta),cos(phi)/cos(theta);\n\n\t\tv_i=Rsb*v_b;\n\t\teuler_d=mat_inv*w_b;\n\n\t\tx_d=v_i[0];\n\t\ty_d=v_i[1];\n\t\tz_d=v_i[2];\n\n\t\tphi_d=euler_d[0];\n\t\ttheta_d=euler_d[1];\n\t\tpsi_d=euler_d[2];\n\n//\t\tx_d=w*(sin(phi)*sin(psi)+cos(phi)*cos(psi)*sin(theta))-\n//\t\t\t\tv*(cos(phi)*sin(psi)-cos(psi)*sin(phi)*sin(theta))+\n//\t\t\t\tu*(cos(psi)*cos(theta));\n//\n//\t\ty_d=v*(cos(phi)*cos(psi)+sin(phi)*sin(psi)*sin(theta))-\n//\t\t\t\tw*(cos(psi)*sin(phi)-cos(phi)*sin(psi)*sin(theta))+\n//\t\t\t\tu*(cos(theta)*sin(psi));\n//\t\tz_d=w*(cos(phi)*cos(theta))-u*(sin(theta))+v*(cos(theta)*sin(phi));\n//\n//\t\tphi_d=p+r*(cos(phi)*tan(theta))+q*(sin(phi)*tan(theta));\n//\t\ttheta_d=q*cos(phi)-r*sin(phi);\n//\t\tpsi_d=r*cos(phi)/cos(theta)+q*sin(phi)/cos(theta);\n//\n\t\tx_dot<<x_d,y_d,z_d,phi_d,theta_d,psi_d;\n\n\t\treturn x_dot;\n\t}\n\n\tdrone2_state_tensor dynamics_2(const drone2_state_tensor & x,const drone2_input_tensor & u)\n\t{\n\t\tdrone2_state_tensor X_dot;\n\t\tdrone_state_tensor X_dot1,X_dot2;\n\t\tX_dot1=dynamics(x.segment(0, 6),u.segment(0,6));\n\t\tX_dot2=dynamics(x.segment(6, 6),u.segment(6,6));\n\t\tX_dot<<X_dot1,X_dot2;\n\t\treturn X_dot;\n\t}\n\n}\n", "meta": {"hexsha": "87b02b772661136b5b7694707c54f8a84be871df", "size": 13206, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ros_ws/src/iconlab/src/iLQR_node/dynamics_structure.cpp", "max_stars_repo_name": "labicon/crazyswarm-labicon", "max_stars_repo_head_hexsha": "32a1cd553093a31ed86058c5a9868b5a6a59dfe6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ros_ws/src/iconlab/src/iLQR_node/dynamics_structure.cpp", "max_issues_repo_name": "labicon/crazyswarm-labicon", "max_issues_repo_head_hexsha": "32a1cd553093a31ed86058c5a9868b5a6a59dfe6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ros_ws/src/iconlab/src/iLQR_node/dynamics_structure.cpp", "max_forks_repo_name": "labicon/crazyswarm-labicon", "max_forks_repo_head_hexsha": "32a1cd553093a31ed86058c5a9868b5a6a59dfe6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.4555555556, "max_line_length": 139, "alphanum_fraction": 0.6426624262, "num_tokens": 5492, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.6513548714339144, "lm_q1q2_score": 0.474170354929199}}
{"text": "#ifndef INCLUDED_STDDEFX\n#include \"stddefx.h\"\n#define INCLUDED_STDDEFX\n#endif\n\n#ifndef INCLUDED_COM_RIMAP\n#include \"com_rimap.h\"\n#define INCLUDED_COM_RIMAP\n#endif\n\n#ifndef INCLUDED_BOOST_MATH_SPECIAL_FUNCTIONS_ROUND\n#include <boost/math/special_functions/round.hpp>\n#define INCLUDED_BOOST_MATH_SPECIAL_FUNCTIONS_ROUND\n#endif\n\n/*!\n  \\file\n  brief\n\n  more elaborated\n*/\n\n\n\n//------------------------------------------------------------------------------\n// DEFINITION OF STATIC CLASS MEMBERS\n//------------------------------------------------------------------------------\n\n\n\n//------------------------------------------------------------------------------\n// DEFINITION OF CLASS MEMBERS \n//------------------------------------------------------------------------------\n\ncom::RIMap::RIMap()\n\n  : d_r1(0.0), d_r2(0.0), d_i1(0), d_i2(0), d_conv(0.0)\n\n{\n}\n\n\n\ncom::RIMap::RIMap(REAL8 r1, REAL8 r2, int i1, int i2)\n{\n  setRealRange(r1, r2);\n  setIntRange(i1, i2);\n}\n\n\n\ncom::RIMap::~RIMap()\n{\n}\n\n\n\nvoid com::RIMap::recalc()\n{\n  if(d_r1 != d_r2)\n    d_conv = static_cast<REAL8>(d_i2 - d_i1) / (d_r2 - d_r1);\n  else\n    d_conv = 0.0;\n}\n\n\n\nvoid com::RIMap::setRealRange(REAL8 r1, REAL8 r2)\n{\n  d_r1 = r1;\n  d_r2 = r2;\n  recalc();\n}\n\n\n\nvoid com::RIMap::setIntRange(int i1, int i2)\n{\n  d_i1 = i1;\n  d_i2 = i2;\n  recalc();\n}\n\n\n\nREAL8 com::RIMap::r1() const\n{\n  return d_r1;\n}\n\n\n\nREAL8 com::RIMap::r2() const\n{\n  return d_r2;\n}\n\n\n\nint com::RIMap::i1() const\n{\n  return d_i1;\n}\n\n\n\nint com::RIMap::i2() const\n{\n  return d_i2;\n}\n\n\n\nint com::RIMap::transform(REAL8 v) const\n{\n  return d_i1 + boost::math::iround((v - d_r1) * d_conv);\n}\n\n\n\nREAL8 com::RIMap::transform(int v) const\n{\n  if(d_conv == 0.0)\n    return 0.0;\n  else\n    return d_r1 + static_cast<double>(v - d_i1) / d_conv;\n}\n\n\n\nbool com::RIMap::inRange(REAL8 r) const\n{\n  return d_r1 <= r && r <= d_r2;\n}\n\n\n\nbool com::RIMap::inRange(int i) const\n{\n  return d_i1 <= i && i <= d_i2;\n}\n\n\n\n//------------------------------------------------------------------------------\n// DEFINITION OF FREE OPERATORS \n//------------------------------------------------------------------------------\n\n\n\n//------------------------------------------------------------------------------\n// DEFINITION OF FREE FUNCTIONS \n//------------------------------------------------------------------------------\n\n\n\n//------------------------------------------------------------------------------\n// DOCUMENTATION OF ENUMERATIONS\n//------------------------------------------------------------------------------\n\n\n\n//------------------------------------------------------------------------------\n// DOCUMENTATION OF INLINE FUNCTIONS\n//------------------------------------------------------------------------------\n\n\n\n//------------------------------------------------------------------------------\n// DOCUMENTATION OF PURE VIRTUAL FUNCTIONS\n//------------------------------------------------------------------------------\n\n\n", "meta": {"hexsha": "af10d42dd862b77df5afce004db204298261a26e", "size": 2930, "ext": "cc", "lang": "C++", "max_stars_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcrcom/com_rimap.cc", "max_stars_repo_name": "quanpands/wflow", "max_stars_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcrcom/com_rimap.cc", "max_issues_repo_name": "quanpands/wflow", "max_issues_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcrcom/com_rimap.cc", "max_forks_repo_name": "quanpands/wflow", "max_forks_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.8390804598, "max_line_length": 80, "alphanum_fraction": 0.3993174061, "num_tokens": 667, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.4741703500023631}}
{"text": "//==================================================================================================\n/*!\n\n  Copyright 2015 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#include <boost/simd/constant/sqrt_2.hpp>\n#include <boost/simd/constant/two.hpp>\n#include <boost/simd/as.hpp>\n#include <simd_test.hpp>\n\nSTF_CASE_TPL( \"Check sqrt_2 behavior for integral types\"\n            , (std::uint8_t)(std::uint16_t)(std::uint32_t)(std::uint64_t)\n              (std::int8_t)(std::int16_t)(std::int32_t)(std::int64_t)\n            )\n{\n  using boost::simd::as;\n  using boost::simd::detail::sqrt_2;\n  using boost::simd::Sqrt_2;\n\n  STF_TYPE_IS(decltype(Sqrt_2<T>()), T);\n  STF_EQUAL(Sqrt_2<T>(), T(1));\n  STF_EQUAL(sqrt_2( as(T{}) ),T(1));\n}\n\nSTF_CASE_TPL( \"Check sqrt_2 behavior for floating types\"\n            , (double)(float)\n            )\n{\n  using boost::simd::as;\n  using boost::simd::detail::sqrt_2;\n  using boost::simd::Sqrt_2;\n  using boost::simd::Two;\n\n  STF_TYPE_IS(decltype(Sqrt_2<T>()), T);\n  auto z1 = Sqrt_2<T>();\n  STF_ULP_EQUAL(z1*z1, Two<T>(), 0.5);\n  auto z2 = sqrt_2( as(T{}) );\n  STF_ULP_EQUAL(z2*z2, Two<T>(), 0.5);\n\n}\n", "meta": {"hexsha": "679f3d14db06d3f156c490185a6fb4e38bd3132c", "size": 1340, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/constant/scalar/sqrt_2.cpp", "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": "test/constant/scalar/sqrt_2.cpp", "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": "test/constant/scalar/sqrt_2.cpp", "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": 29.7777777778, "max_line_length": 100, "alphanum_fraction": 0.5455223881, "num_tokens": 385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754371026367, "lm_q2_score": 0.6513548714339144, "lm_q1q2_score": 0.4741703472410355}}
{"text": "// -*- C++ -*-\n\n// The MIT License (MIT)\n//\n// Copyright (c) 2021 Alexander Samoilov\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n#pragma once\n\n#include <pybind11/pybind11.h>\n#include <pybind11/eigen.h>\n#include <pybind11/stl.h>\n#include <pybind11/stl_bind.h>\n#include <pybind11/numpy.h>\n#include <Eigen/Dense>\n\n/**  \n *  @brief Contains fundamental type defintions used by the project. \n *  \n */\n\nnamespace py = pybind11;\n\nnamespace detail {\n\ntemplate <typename T> inline T sqr(T a) { return a*a; }\n\ninline double id(size_t i, size_t j) { return i==j ? 1.0 : 0.0; }\n\ninline bool is_odd(size_t i) { return i&1; }\n\ninline bool is_even(size_t i) { return !is_odd(i); }\n\n}\n\nusing RowVectorXd = Eigen::RowVectorXd;\n\nusing RowMatrixXd = Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;\n// Use RowMatrixXd instead of MatrixXd\n// see https://pybind11.readthedocs.io/en/stable/advanced/cast/eigen.html#storage-orders for more details\n\n", "meta": {"hexsha": "afb415fe6f7db242945bca2f70a2041bec61bda5", "size": 1981, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "chebyshev_pseudospectral/src/math.hpp", "max_stars_repo_name": "alsam/cpp-samples", "max_stars_repo_head_hexsha": "abb14634b32dec9cfdfa8090ebee3df5e8479e6a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-04-14T15:42:59.000Z", "max_stars_repo_stars_event_max_datetime": "2017-08-18T10:51:29.000Z", "max_issues_repo_path": "chebyshev_pseudospectral/src/math.hpp", "max_issues_repo_name": "alsam/cpp-samples", "max_issues_repo_head_hexsha": "abb14634b32dec9cfdfa8090ebee3df5e8479e6a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chebyshev_pseudospectral/src/math.hpp", "max_forks_repo_name": "alsam/cpp-samples", "max_forks_repo_head_hexsha": "abb14634b32dec9cfdfa8090ebee3df5e8479e6a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-29T13:57:21.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-29T13:57:21.000Z", "avg_line_length": 33.5762711864, "max_line_length": 105, "alphanum_fraction": 0.7375063099, "num_tokens": 478, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548646660542, "lm_q2_score": 0.7279754371026367, "lm_q1q2_score": 0.4741703423141996}}
{"text": "#include <cstdlib>\n#include <algorithm>\n#include <iostream>\n#include <vector>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <gtest/gtest.h>\n#include \"arpaca.hpp\"\n\nnamespace arpaca {\n\ntemplate<typename T> struct PrecisionThreshold;\n\ntemplate<> struct PrecisionThreshold<float> { static const float value; };\ntemplate<> struct PrecisionThreshold<double> { static const double value; };\n\nconst float PrecisionThreshold<float>::value = 1e-3f;\nconst double PrecisionThreshold<double>::value = 1e-10;\n\n\nstd::vector<int> MakeRandomSequence(int n, int k)\n{\n  std::vector<int> seq;\n  seq.reserve(n);\n  for (int i = 0; i < n; ++i) seq.push_back(i);\n  std::random_shuffle(seq.begin(), seq.end());\n  seq.resize(k);\n  return seq;\n}\n\ndouble GetRandomValue(double range)\n{\n  return 2 * range * std::rand() / RAND_MAX - range;\n}\n\ntemplate<typename Scalar>\nEigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>\nMakeSymmetrixRandomMatrix(int n, int k, Scalar range)\n{\n  Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic> X(n, n);\n  X.setZero();\n\n  std::vector<int> idx = MakeRandomSequence(n*n, 2*k);\n  for (size_t i = 0; i < idx.size(); ++i)\n    X(idx[i]/n, idx[i]%n) = GetRandomValue(range);\n\n  return (X + X.transpose()) / 2;\n}\n\ntemplate<typename Scalar>\nEigen::SparseMatrix<Scalar, Eigen::RowMajor>\nMakeSparse(const Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>& X)\n{\n  Eigen::SparseMatrix<Scalar, Eigen::RowMajor> S(X.rows(), X.cols());\n\n  for (int i = 0; i < S.rows(); ++i) {\n    S.startVec(i);\n    for (int j = 0; j < S.cols(); ++j)\n      if (X(i, j) != 0)\n        S.insertBack(i, j) = X(i, j);\n  }\n\n  S.finalize();\n  return S;\n}\n\nstruct RandomMatrixTestParameter {\n  int n;\n  int k;\n  int num_eigenvalues;\n  int num_lanczos_vectors;\n};\n\nRandomMatrixTestParameter MakeParameter(int n, int k, int ne, int nlv)\n{\n  RandomMatrixTestParameter p = { n, k, ne, nlv };\n  return p;\n}\n\nclass RandomMatrixTest\n    : public testing::TestWithParam<RandomMatrixTestParameter> {\n protected:\n  template<typename Scalar>\n  void TestOfScalar()\n  {\n    typedef Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic> Matrix;\n    typedef Eigen::SparseMatrix<Scalar, Eigen::RowMajor> SparseMatrix;\n    typedef Eigen::Matrix<Scalar, Eigen::Dynamic, 1> Vector;\n\n    RandomMatrixTestParameter p = GetParam();\n\n    Matrix X = MakeSymmetrixRandomMatrix(p.n, p.k, Scalar(10.0));\n    SparseMatrix S = MakeSparse(X);\n\n    Eigen::SelfAdjointEigenSolver<Matrix> X_eigen(S);\n    SymmetricEigenSolver<Scalar> S_eigen =\n        Solve(S, p.num_eigenvalues, ALGEBRAIC_LARGEST, p.num_lanczos_vectors);\n\n    Vector X_eigenvalues = X_eigen.eigenvalues().bottomRows(p.num_eigenvalues);\n    Matrix X_eigenvectors =\n        X_eigen.eigenvectors().rightCols(p.num_eigenvalues);\n    Vector S_eigenvalues = S_eigen.MoveEigenvalues();\n    Matrix S_eigenvectors = S_eigen.MoveEigenvectors();\n\n    {\n      const Scalar diff_mean =\n          (X_eigenvalues - S_eigenvalues).cwiseAbs().mean();\n      EXPECT_TRUE(diff_mean < PrecisionThreshold<Scalar>::value)\n          << \"eigenvalues diff_mean: \" << diff_mean;\n    }\n\n    {\n      Scalar diff_sum = 0.0;\n      for (int i = 0; i < p.num_eigenvalues; ++i) {\n        // Since each eigenvector given by X and S may have different signs,\n        // we have to check either same or opposite.\n        const Scalar diff1 =\n            (X_eigenvectors.col(i) - S_eigenvectors.col(i)).cwiseAbs().mean();\n        const Scalar diff2 =\n            (X_eigenvectors.col(i) + S_eigenvectors.col(i)).cwiseAbs().mean();\n        diff_sum += std::min(diff1, diff2);\n      }\n      const Scalar diff_mean = diff_sum / p.num_eigenvalues;\n\n      EXPECT_TRUE(diff_mean < PrecisionThreshold<Scalar>::value)\n          << \"eigenvectors diff_mean: \" << diff_mean;\n    }\n\n    std::cout << \"info: \" << S_eigen.GetInfo() << std::endl;\n    std::cout << \"# actual iterations: \"\n              << S_eigen.num_actual_iterations() << std::endl;\n    std::cout << \"# converged eigenvalues: \"\n              << S_eigen.num_converged_eigenvalues() << std::endl;\n  }\n};\n\nTEST_P(RandomMatrixTest, Double)\n{\n  TestOfScalar<double>();\n}\n\nTEST_P(RandomMatrixTest, Float)\n{\n  TestOfScalar<float>();\n}\n\nINSTANTIATE_TEST_CASE_P(\n    SizeTest,\n    RandomMatrixTest,\n    testing::Values(MakeParameter(100, 1000, 10, 50),\n                    MakeParameter(1000, 10000, 100, 500),\n                    MakeParameter(100, 1000, 50, 0)));\n\n}  // namespace arpaca\n", "meta": {"hexsha": "cc8a8abcee10c8ee7177a9b32e983564fb35e47a", "size": 4414, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "arpaca_test.cpp", "max_stars_repo_name": "meznom/arpaca", "max_stars_repo_head_hexsha": "91af2357a73ed7f5cd0d300e40283a59244c7c25", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-09-05T17:29:06.000Z", "max_stars_repo_stars_event_max_datetime": "2015-09-05T17:29:06.000Z", "max_issues_repo_path": "arpaca_test.cpp", "max_issues_repo_name": "meznom/arpaca", "max_issues_repo_head_hexsha": "91af2357a73ed7f5cd0d300e40283a59244c7c25", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "arpaca_test.cpp", "max_forks_repo_name": "meznom/arpaca", "max_forks_repo_head_hexsha": "91af2357a73ed7f5cd0d300e40283a59244c7c25", "max_forks_repo_licenses": ["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.4774193548, "max_line_length": 79, "alphanum_fraction": 0.6617580426, "num_tokens": 1210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059775, "lm_q2_score": 0.6513548511303336, "lm_q1q2_score": 0.4741703401486908}}
{"text": "#include <Eigen/Core>\n#include \"densecrf.h\"\n#include \"pairwise.h\"\n#include \"densecrf_wrapper.h\"\n\nDenseCRFWrapper::DenseCRFWrapper(int npixels, int nlabels, int nrank)\n: m_npixels(npixels), m_nlabels(nlabels), m_nrank(nrank) {\n\tm_crf = new DenseCRF(npixels, nlabels);\n}\n\nDenseCRFWrapper::~DenseCRFWrapper() {\n\tdelete m_crf;\n}\n\nint DenseCRFWrapper::npixels() { return m_npixels; }\nint DenseCRFWrapper::nlabels() { return m_nlabels; }\n\nvoid DenseCRFWrapper::add_pairwise_energy(float* pairwise_costs_ptr, float* features_ptr, int nfeatures) {\n\tm_crf->addPairwiseEnergy(\n\t\tEigen::Map<const Eigen::MatrixXf>(features_ptr, nfeatures, m_npixels),\n\t\tnew MatrixCompatibility(\n\t\t\tEigen::Map<const Eigen::MatrixXf>(pairwise_costs_ptr, m_nlabels, m_nlabels)\n\t\t),\n\t\tDIAG_KERNEL,\n\t\tNORMALIZE_SYMMETRIC\n\t);\n}\n\nvoid DenseCRFWrapper::add_comparison_energy(float* pair_comp_ptr, float* label_comp_ptr) {\n\t\n\tPairwisePotential* comp_potential_ptr = new PairwisePotential(new MatrixCompatibility( \n\t\tEigen::Map<const Eigen::MatrixXf>(label_comp_ptr, m_nlabels, m_nlabels) ), \n\t\tEigen::Map<const Eigen::MatrixXf>(pair_comp_ptr, m_npixels, m_npixels));\n\tm_crf->addPairwiseEnergy(comp_potential_ptr);\n}\n\nvoid DenseCRFWrapper::add_comparison_energy_nystrom(float* ns_left_ptr, float* ns_right_ptr, float* label_comp_ptr) {\n\t\n\tPairwisePotential* comp_potential_ns_ptr = new PairwisePotential(new MatrixCompatibility( \n\t\tEigen::Map<const Eigen::MatrixXf>(label_comp_ptr, m_nlabels, m_nlabels) ), \n\t\tEigen::Map<const Eigen::MatrixXf>(ns_left_ptr, m_npixels, m_nrank), \n\t\tEigen::Map<const Eigen::MatrixXf>(ns_right_ptr, m_nrank, m_npixels) );\n\tm_crf->addPairwiseEnergy(comp_potential_ns_ptr);\n}\n\nvoid DenseCRFWrapper::set_unary_energy(float* unary_costs_ptr) {\n\tm_crf->setUnaryEnergy(\n\t\tEigen::Map<const Eigen::MatrixXf>(\n\t\t\tunary_costs_ptr, m_nlabels, m_npixels)\n\t);\n}\n\nvoid DenseCRFWrapper::map(int n_iters, int* labels) {\n\tVectorXs labels_vec = m_crf->map(n_iters);\n\tfor (int i = 0; i < m_npixels; i ++)\n\t\tlabels[i] = labels_vec(i);\n}\n\nvoid DenseCRFWrapper::inference(int n_iters, float* Q) {\n\tMatrixXf Q_vec = m_crf->inference(n_iters);\n\tmemcpy(Q, Q_vec.data(), Q_vec.cols()*Q_vec.rows()*sizeof(float));\n}\n", "meta": {"hexsha": "f7772c021f7b30ce0759c8cadfaa6dce8320133a", "size": 2181, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bell2014/krahenbuhl2013/src/densecrf_wrapper.cpp", "max_stars_repo_name": "tinghuiz/learn-reflectance", "max_stars_repo_head_hexsha": "31ab326d344834e9cd8bb042551176bcf3114a9c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 33.0, "max_stars_repo_stars_event_min_datetime": "2016-02-08T21:07:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-09T10:35:04.000Z", "max_issues_repo_path": "bell2014/krahenbuhl2013/src/densecrf_wrapper.cpp", "max_issues_repo_name": "tinghuiz/learn-reflectance", "max_issues_repo_head_hexsha": "31ab326d344834e9cd8bb042551176bcf3114a9c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-05-08T06:56:46.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-08T06:56:46.000Z", "max_forks_repo_path": "bell2014/krahenbuhl2013/src/densecrf_wrapper.cpp", "max_forks_repo_name": "tinghuiz/learn-reflectance", "max_forks_repo_head_hexsha": "31ab326d344834e9cd8bb042551176bcf3114a9c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2016-02-10T19:17:11.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-06T22:53:08.000Z", "avg_line_length": 34.619047619, "max_line_length": 117, "alphanum_fraction": 0.7661623109, "num_tokens": 653, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936537604181, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4741675194490312}}
{"text": "//---------------------------------------------------------------------------//\r\n// Copyright (c) 2013 Kyle Lutz <kyle.r.lutz@gmail.com>\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://boostorg.github.com/compute for more information.\r\n//---------------------------------------------------------------------------//\r\n\r\n#ifndef BOOST_COMPUTE_ALGORITHM_DETAIL_RANDOM_FILL_HPP\r\n#define BOOST_COMPUTE_ALGORITHM_DETAIL_RANDOM_FILL_HPP\r\n\r\n#include <iterator>\r\n\r\n#include <boost/compute/command_queue.hpp>\r\n#include <boost/compute/random/default_random_engine.hpp>\r\n#include <boost/compute/random/uniform_real_distribution.hpp>\r\n\r\nnamespace boost {\r\nnamespace compute {\r\nnamespace detail {\r\n\r\ntemplate<class OutputIterator, class Generator>\r\ninline void random_fill(OutputIterator first,\r\n                        OutputIterator last,\r\n                        Generator &g,\r\n                        command_queue &queue)\r\n{\r\n    g.fill(first, last, queue);\r\n}\r\n\r\ntemplate<class OutputIterator>\r\ninline void\r\nrandom_fill(OutputIterator first,\r\n            OutputIterator last,\r\n            typename std::iterator_traits<OutputIterator>::value_type lo,\r\n            typename std::iterator_traits<OutputIterator>::value_type hi,\r\n            command_queue &queue)\r\n{\r\n    typedef typename\r\n        std::iterator_traits<OutputIterator>::value_type value_type;\r\n    typedef typename\r\n        boost::compute::default_random_engine engine_type;\r\n    typedef typename\r\n        boost::compute::uniform_real_distribution<value_type> distribution_type;\r\n\r\n    engine_type engine(queue);\r\n    distribution_type generator(lo, hi);\r\n    generator.fill(first, last, engine, queue);\r\n}\r\n\r\n} // end detail namespace\r\n} // end compute namespace\r\n} // end boost namespace\r\n\r\n#endif // BOOST_COMPUTE_ALGORITHM_DETAIL_RANDOM_FILL_HPP\r\n", "meta": {"hexsha": "eda8dc0ede48a48e04b8b73e7c8657be529b0a54", "size": 1937, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ios/Pods/boost-for-react-native/boost/compute/algorithm/detail/random_fill.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/compute/algorithm/detail/random_fill.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/compute/algorithm/detail/random_fill.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.3965517241, "max_line_length": 81, "alphanum_fraction": 0.6479091378, "num_tokens": 355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.766293653760418, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4741675194490311}}
{"text": "/* boost random/geometric_distribution.hpp header file\n *\n * Copyright Jens Maurer 2000-2001\n * Permission to use, copy, modify, sell, and distribute this software\n * is hereby granted without fee provided that the above copyright notice\n * appears in all copies and that both that copyright notice and this\n * permission notice appear in supporting documentation,\n *\n * Jens Maurer makes no representations about the suitability of this\n * software for any purpose. It is provided \"as is\" without express or\n * implied warranty.\n *\n * See http://www.boost.org for most recent version including documentation.\n *\n * $Id: geometric_distribution.hpp 11696 2001-11-14 21:53:38Z jmaurer $\n *\n * Revision history\n *  2001-02-18  moved to individual header files\n */\n\n#ifndef BOOST_RANDOM_GEOMETRIC_DISTRIBUTION_HPP\n#define BOOST_RANDOM_GEOMETRIC_DISTRIBUTION_HPP\n\n#include <cmath>          // std::log\n#include <cassert>\n#include <boost/random/uniform_01.hpp>\n\nnamespace boost {\n\n#if defined(__GNUC__) && (__GNUC__ < 3)\n// Special gcc workaround: gcc 2.95.x ignores using-declarations\n// in template classes (confirmed by gcc author Martin v. Loewis)\n  using std::log;\n#endif\n\n// geometric distribution: p(i) = (1-p) * pow(p, i-1)   (integer)\ntemplate<class UniformRandomNumberGenerator, class IntType = int>\nclass geometric_distribution\n{\npublic:\n  typedef UniformRandomNumberGenerator base_type;\n  typedef IntType result_type;\n\n  geometric_distribution(base_type & rng, double p)\n    : _rng(rng)\n  {\n    assert(0.0 < p && p < 1.0);\n#ifndef BOOST_NO_STDC_NAMESPACE\n    using std::log;\n#endif\n    _log_p = log(p);\n  }\n  // compiler-generated copy ctor is fine\n  // uniform_01 cannot be assigned, neither can this class\n\n  result_type operator()()\n  {\n#ifndef BOOST_NO_STDC_NAMESPACE\n    using std::log;\n#endif\n    return IntType (log(1-_rng()) / _log_p) + 1;\n  }\n\n#ifndef BOOST_NO_OPERATORS_IN_NAMESPACE\n  friend bool operator==(const geometric_distribution& x, \n                         const geometric_distribution& y)\n  { return x._log_p == y._log_p && x._rng == y._rng; }\n#else\n  // Use a member function\n  bool operator==(const geometric_distribution& rhs) const\n  { return _log_p == rhs._log_p && _rng == rhs._rng;  }\n#endif\nprivate:\n  uniform_01<base_type> _rng;\n  typename uniform_01<base_type>::result_type _log_p;\n};\n\n} // namespace boost\n\n#endif // BOOST_RANDOM_GEOMETRIC_DISTRIBUTION_HPP\n\n", "meta": {"hexsha": "f7a2851f7c0ae2264ee0a40e8825abe0cf3665c5", "size": 2396, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "vegastrike/boost/1_28/boost/random/geometric_distribution.hpp", "max_stars_repo_name": "Ezeer/VegaStrike_win32FR", "max_stars_repo_head_hexsha": "75891b9ccbdb95e48e15d3b4a9cd977955b97d1f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "vegastrike/boost/1_28/boost/random/geometric_distribution.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/random/geometric_distribution.hpp", "max_forks_repo_name": "Ezeer/VegaStrike_win32FR", "max_forks_repo_head_hexsha": "75891b9ccbdb95e48e15d3b4a9cd977955b97d1f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.2195121951, "max_line_length": 76, "alphanum_fraction": 0.7291318865, "num_tokens": 603, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6187804407739559, "lm_q1q2_score": 0.4741675182310106}}
{"text": "/*\nAuthor: Andrej Karpathy (http://cs.stanford.edu/~karpathy/)\n1 May 2012\nBSD licence\n*/\n\n#include <string>\n#include <vector>\n#include <stdlib.h>\n\n#include <Eigen/Eigen>\n#include <eigenlibsvm/svm_utils.h>\n#include <eigenlibsvm/eigen_extensions.h>\n\nusing namespace std;\nusing namespace esvm;\n\n// run from build folder of the project (see path below)\nint main (int argc, char** argv) {\n  \n  Eigen::MatrixXf X;\n  Eigen::MatrixXf y;\n  eigen_extensions::loadASCII(\"../test/svmtestx.eig.txt\", &X);\n  eigen_extensions::loadASCII(\"../test/svmtesty.eig.txt\", &y);\n  \n  // Classify\n  cout << X.topRows(5) << endl;\n  cout << y.topRows(5) << endl;\n  vector<int> yhat;\n  SVMClassifier svm;\n  svm.train(X, y);\n  svm.test(X, yhat);\n  \n  Eigen::MatrixXf w;\n  float b;\n  svm.getw(w, b);\n  Eigen::MatrixXf margin= ((X * w).array() + b).matrix(); // ahh eigen...\n  \n  // Evaluate accuracy and print results\n  int match=0;\n  for(int i=0;i<yhat.size();i++) {\n    if(yhat[i]==(int)y(i)) match++; else printf(\"WRONG! \");\n    printf(\"y= %d, yhat= %d margin= %f\\n\", (int)y(i), yhat[i], margin(i));\n  }\n  printf(\"MATLAB cross-check: last margin should be around -3.107\\n\");\n  printf(\"Accuracy= %f. From MATLAB cross-check, expect this to be around 0.945\\n\", 1.0*match/yhat.size());\n  \n  // Save the model\n  svm.saveModel(\"temp.svmmodel\");\n  \n  // Test loading model in new instance of SVMClassifier\n  SVMClassifier svm2;\n  svm2.loadModel(\"temp.svmmodel\");\n  yhat.clear();\n  svm2.test(X, yhat);\n  match=0; \n  for(int i=0;i<yhat.size();i++) if(yhat[i]==(int)y(i)) match++;\n  printf(\"Accuracy= %f from loaded model. Should be 0.945 again.\\n\", 1.0*match/yhat.size());\n  \n  \n  printf(\"you may want to rm the temporary file temp.svmmodel\\n\");\n}\n  \n", "meta": {"hexsha": "61b1b215cd4c653efa51f3263b7f052740232e72", "size": 1716, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "thirdparty/EigenLibSVM/test/svm_test.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": "thirdparty/EigenLibSVM/test/svm_test.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": "thirdparty/EigenLibSVM/test/svm_test.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": 26.8125, "max_line_length": 107, "alphanum_fraction": 0.648018648, "num_tokens": 540, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4741675128438852}}
{"text": "#include <boost/test/unit_test.hpp>\n\n#include <smtrat-modules/SATModule/mcsat/BaseBackend.h>\n#include <smtrat-common/smtrat-common.h>\n\n#include <carl-model/evaluation/ModelEvaluation.h>\n#include <smtrat-mcsat/assignments/arithmetic/AssignmentFinder.h>\n#include <smtrat-mcsat/explanations/nlsat/Explanation.h>\n\nusing namespace smtrat;\n\nBOOST_AUTO_TEST_SUITE(Test_AssignmentFinder);\n\n/**\n * Tests Example 3 from the NLSAT-Paper\n */\nBOOST_AUTO_TEST_CASE(Test_NLSATPaper_Ex3)\n{\n\t\n\tcarl::Variable x = carl::freshRealVariable(\"x\");\n\tcarl::Variable y = carl::freshRealVariable(\"y\");\n\t\n\t// Original constraints\n\tFormulaT c1(Poly(x)+Rational(1), carl::Relation::LEQ);\n\tFormulaT c2(Poly(x)-Rational(1), carl::Relation::GEQ);\n\tFormulaT c3(Poly(x)+y, carl::Relation::GREATER);\n\tFormulaT c4(Poly(x)-y, carl::Relation::GREATER);\n\t// Learnt from first conflict\n\tFormulaT c5(Poly(x), carl::Relation::LESS);\n\t\n\t// Explanation for first conflict\n\tFormulaT ex1(carl::FormulaType::OR, { c3.negated(), c4.negated(), c5.negated() });\n\t// Explanation for second conflict\n\tFormulaT ex2(carl::FormulaType::OR, { c1.negated(), c5 });\n\t\n\tmcsat::MCSATBackend<mcsat::MCSATSettingsNL> nlsat;\n\t\n\t// Decide x+1<=0\n\tSMTRAT_LOG_INFO(\"smtrat.test.nlsat\", \"Decide \" << c1);\n\tnlsat.pushConstraint(c1);\n\t\n\t// T-Decide\n\tSMTRAT_LOG_INFO(\"smtrat.test.nlsat\", \"T-Decide \" << x << \" = -2\");\n\t{\n\t\tauto res = nlsat.findAssignment(x);\n\t\tBOOST_CHECK(carl::variant_is_type<mcsat::ModelValues>(res));\n\t\tauto value = boost::get<mcsat::ModelValues>(res);\n\t\tBOOST_CHECK(value.size() == 1);\n\t\tBOOST_CHECK(value[0].first == x);\n\t\tBOOST_CHECK(value[0].second == ModelValue(Rational(-1)));\n\t}\n\tFormulaT fx(Poly(x) + Rational(2), carl::Relation::EQ);\n\tnlsat.pushAssignment(x, Rational(-2), fx);\n\t\n\t// Propagate x+y>0\n\tSMTRAT_LOG_INFO(\"smtrat.test.nlsat\", \"Propagate \" << c3);\n\tnlsat.pushConstraint(c3);\n\t\n\t// Check whether x-y>0 is feasible, propagate x-y<=0\n\tSMTRAT_LOG_INFO(\"smtrat.test.nlsat\", \"T-Propagate \" << c4.negated());\n\t{\n\t\tauto res = nlsat.isInfeasible(y, c4);\n\t\tBOOST_CHECK(carl::variant_is_type<FormulasT>(res));\n\t\tauto r = boost::get<FormulasT>(res);\n\t\tauto explanation = nlsat.explain(y, r);\n\t\tBOOST_CHECK(boost::get<FormulaT>(&explanation) != nullptr);\n\t\tBOOST_CHECK(ex1 == boost::get<FormulaT>(explanation));\n\t}\n\tnlsat.pushConstraint(c4.negated());\n\t\n\t// Backtrack assignment\n\tSMTRAT_LOG_INFO(\"smtrat.test.nlsat\", \"Backtrack \" << x);\n\tnlsat.popAssignment(x);\n\t\n\t// Check whether x>0 is feasible, propagate x<=0\n\tSMTRAT_LOG_INFO(\"smtrat.test.nlsat\", \"T-Propagate \" << c5);\n\t{\n\t\tauto res = nlsat.isInfeasible(x, c5.negated());\n\t\tBOOST_CHECK(carl::variant_is_type<FormulasT>(res));\n\t\tauto r = boost::get<FormulasT>(res);\n\t\tauto explanation = nlsat.explain(x, r);\n\t\tBOOST_CHECK(boost::get<FormulaT>(&explanation) != nullptr);\n\t\tBOOST_CHECK(ex2 == boost::get<FormulaT>(explanation));\n\t}\n}\n\nBOOST_AUTO_TEST_CASE(CoverComputation)\n{\n\tcarl::Variable a = carl::freshRealVariable(\"a\");\n\tcarl::Variable b = carl::freshRealVariable(\"b\");\n\tPoly p = Poly(20)*a*a*b - Poly(a)*a*a*a*b - Poly(120)*b;\n\tcarl::UnivariatePolynomial<Rational> q(a, {\n\t\tRational(900),\n\t\tRational(0),\n\t\tRational(-2550),\n\t\tRational(0),\n\t\tRational(1055)/2,\n\t\tRational(0),\n\t\tRational(-40),\n\t\tRational(0),\n\t\tRational(1)\n\t});\n\tcarl::Interval<Rational> i(Rational(633)/1025, carl::BoundType::STRICT, Rational(2533)/4096, carl::BoundType::STRICT);\n\tFormulaT f(p, carl::Relation::LESS);\n\t\n\tstd::cout << \"Constructing RAN on \" << q << \" / \" << i << std::endl;\n\tcarl::RealAlgebraicNumber<Rational> ran(q, i);\n\tstd::cout << \"-> \" << ran << std::endl;\n\t\n\tModel model;\n\tmodel.assign(a, ran);\n\tmodel.assign(b, Rational(-3));\n\t\n\tauto res = carl::model::evaluate(f, model);\n\tstd::cout << f << \" on \" << model << \" -> \" << res << std::endl;\n\t\n\tmodel.assign(b, Rational(1));\n\tres = carl::model::evaluate(f, model);\n\tstd::cout << f << \" on \" << model << \" -> \" << res << std::endl;\n}\n\nBOOST_AUTO_TEST_CASE(AssignmentFinderBug) {\n\t// assign variable b with constraints (a ! > rootExpr(1 + 3*__z^3 + -3*b^3 + 3*__z^6 + -6*__z^3*b^3 + 3*b^6 + __z^9 + -3*__z^6*b^3 + 3*__z^3*b^6 + -1*b^9, 1, __z)) under a = 2\n\t\n\tcarl::Variable a = carl::freshRealVariable(\"a\");\n\tcarl::Variable b = carl::freshRealVariable(\"b\");\n\n\tModel model;\n\tmodel.assign(a, Rational(2));\n\n\tconst carl::Variable& z = MultivariateRootT::var();\n\tPoly poly = Poly(Rational(1)) + Rational(3)*z*z*z - Rational(3)*b*b*b + Rational(3)*z*z*z*z*z*z - Rational(6)*z*z*z*b*b*b\n\t\t\t\t+ Rational(3)*b*b*b*b*b*b + z*z*z*z*z*z*z*z*z - Rational(3)*z*z*z*z*z*z*b*b*b + Rational(3)*z*z*z*b*b*b*b*b*b\n\t\t\t\t- b*b*b*b*b*b*b*b*b;\n\tMultivariateRootT mvroot(poly, 1);\n\tVariableComparisonT varcomp(a, mvroot, carl::Relation::GREATER, true);\n\tFormulaT formula(varcomp);\n\tstd::cout << \"Looking at \" << varcomp << std::endl;\n\n\t// proof that an assignment for b exist\n\tModel model2 = model;\n\tmodel2.assign(b, Rational(3));\n\tauto res = carl::model::evaluate(formula, model2);\n\tBOOST_CHECK(res.isBool());\n\tBOOST_CHECK(res.asBool());\n\n\t// call assignment finder\n\tmcsat::Bookkeeping bookkeeping;\n\tbookkeeping.pushConstraint(formula);\n\tbookkeeping.pushAssignment(a, Rational(2), FormulaT(carl::FormulaType::TRUE));\n\tmcsat::arithmetic::AssignmentFinder af;\n\tauto afres = af(bookkeeping, b);\n\tBOOST_CHECK(afres);\n\tBOOST_CHECK(carl::variant_is_type<mcsat::ModelValues>(*afres));\n\t\n\tFormulaT tmp;\n\t{\n\t\tbookkeeping.pushAssignment(b, Rational(0), FormulaT(carl::FormulaType::TRUE));\n\t\tmcsat::nlsat::Explanation expl;\n\t\tauto ex = expl(bookkeeping, b, { formula });\n\t\tassert(ex);\n\t\tstd::cout << *ex << std::endl;\n\t\ttmp = boost::get<FormulaT>(*ex).subformulas()[2];\n\t\tbookkeeping.popAssignment(b);\n\t}\n\tstd::cout << \"tmp = \" << tmp << std::endl;\n\tbookkeeping.pushConstraint(tmp);\n\t{\n\t\tmcsat::arithmetic::AssignmentFinder af;\n\t\tauto afres = af(bookkeeping, b);\n\t\tBOOST_CHECK(afres);\n\t\tBOOST_CHECK(carl::variant_is_type<mcsat::ModelValues>(*afres));\n\t\tstd::cout << *afres << std::endl;\n\t}\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "d5bcf3f5588571f05cf93f8df8f52a405375650d", "size": 5939, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tests/nlsat/Test_AssignmentFinder.cpp", "max_stars_repo_name": "ths-rwth/smtrat", "max_stars_repo_head_hexsha": "efd83021d5b5fb0e2903b38cd3148a953a1972c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-03-21T23:02:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-22T15:15:13.000Z", "max_issues_repo_path": "src/tests/nlsat/Test_AssignmentFinder.cpp", "max_issues_repo_name": "ths-rwth/smtrat", "max_issues_repo_head_hexsha": "efd83021d5b5fb0e2903b38cd3148a953a1972c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 15.0, "max_issues_repo_issues_event_min_datetime": "2021-03-16T11:00:37.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-22T14:51:57.000Z", "max_forks_repo_path": "src/tests/nlsat/Test_AssignmentFinder.cpp", "max_forks_repo_name": "ths-rwth/smtrat", "max_forks_repo_head_hexsha": "efd83021d5b5fb0e2903b38cd3148a953a1972c0", "max_forks_repo_licenses": ["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.3651685393, "max_line_length": 176, "alphanum_fraction": 0.6795756861, "num_tokens": 1935, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4741675128438852}}
{"text": "/**\n *           c++11-only implementation of the L-BFGS-B algorithm\n *\n * Copyright (c) 2014 Patrick Wieschollek\n *               https://github.com/PatWie/LBFGSB\n * All rights reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n\n * The above copyright notice and this permission notice shall be included in 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 LBFGSB_H_\n#define LBFGSB_H_\n\n#include \"meta.h\"\n\n#include <list>\n#include <stdio.h>\n#include <iostream>\n#include <functional>\n#include <vector>\n#include <armadillo>\n\n/* coded from scratch !!!\n * based on the paper\n * A LIMITED MEMORY ALGORITHM FOR BOUND CONSTRAINED OPTIMIZATION\n * (Byrd, Lu, Nocedal, Zhu)\n */\n\nclass LBFGSB {\n\n  // contains options for optimization process\n  Options Options_;\n\n  // oracles for function value and gradient\n  FunctionOracleType FunctionObjectiveOracle_;\n  GradientOracleType FunctionGradientOracle_;\n\n  arma::mat W, M;\n  arma::vec lb, ub;\n  double theta;\n  int DIM;\n\n  std::list<arma::vec> xHistory;\n\npublic:\n\n  arma::vec XOpt;\n\n  LBFGSB(const arma::vec & l, const arma::vec & u) :\n      lb(l), ub(u), theta(1.0), DIM(l.n_rows) {\n    lb = l;\n    ub = u;\n    theta = 1.0;\n    DIM = l.n_rows;\n    W = arma::zeros(DIM, 0);\n    M = arma::zeros(0, 0);\n  }\n\n  LBFGSB(Options & Options, const arma::vec & l, const arma::vec & u) {\n    Options_ = Options;\n    lb = l;\n    ub = u;\n    theta = 1.0;\n    DIM = l.n_rows;\n    W = arma::zeros(DIM, 0);\n    M = arma::zeros(0, 0);\n\n  }\n\n  /// <summary>\n  /// find cauchy point in x\n  /// </summary>\n  /// <parameter name=\"x\">start in x</parameter>\n  void\n  GetGeneralizedCauchyPoint(arma::vec & x, arma::vec & g, arma::vec & x_cauchy,\n                            arma::vec & c) {\n    const int DIM = x.n_rows;\n    // PAGE 8\n    // Algorithm CP: Computation of the generalized Cauchy point\n    // Given x,l,u,g, and B = \\theta I-WMW\n\n    // {all t_i} = { (idx,value), ... }\n    // TODO: use \"std::set\" ?\n    std::vector<std::pair<int, double> > SetOfT;\n    // the feasible set is implicitly given by \"SetOfT - {t_i==0}\"\n    arma::vec d = arma::zeros(DIM);\n\n    // n operations\n    for (int j = 0; j < DIM; j++) {\n      if (g(j) == 0) {\n        SetOfT.push_back(std::make_pair(j, INF));\n      } else {\n        double tmp = 0;\n        if (g(j) < 0) {\n          tmp = (x(j) - ub(j)) / g(j);\n        } else {\n          tmp = (x(j) - lb(j)) / g(j);\n        }\n        d(j) = -g(j);\n        SetOfT.push_back(std::make_pair(j, tmp));\n      }\n\n    }Debug(d.transpose());\n\n    // paper: using heapsort\n    // sortedindices [1,0,2] means the minimal element is on the 1th entry\n    std::vector<int> SortedIndices = sort_indexes(SetOfT);\n\n    x_cauchy = x;\n    // Initialize\n    // p := \tW^T*p\n    arma::vec p = (W.t() * d);            // (2mn operations)\n    // c := \t0\n    c = arma::zeros(M.n_rows);\n    // f' := \tg^T*d = -d^Td\n    double f_prime = arma::dot(-d, d);              // (n operations)\n    // f'' :=\t\\theta*d^T*d-d^T*W*M*W^T*d = -\\theta*f' - p^T*M*p\n    double f_doubleprime = (double) (-1.0 * theta) * f_prime -\n                           arma::dot(p, M * p);// (O(m^2) operations)\n    // \\delta t_min :=\t-f'/f''\n    double dt_min = -f_prime / f_doubleprime;\n    // t_old := \t0\n    double t_old = 0;\n    // b := \targmin {t_i , t_i >0}\n    int i = 0;\n    for (int j = 0; j < DIM; j++) {\n      i = j;\n      if (SetOfT[SortedIndices[j]].second != 0)\n        break;\n    }\n    int b = SortedIndices[i];\n    // see below\n    // t        \t\t\t:= \tmin{t_i : i in F}\n    double t = SetOfT[b].second;\n    // \\delta t \t\t\t:= \tt - 0\n    double dt = t - t_old;\n\n    // examination of subsequent segments\n    while ((dt_min >= dt) && (i < DIM)) {\n      if (d(b) > 0)\n        x_cauchy(b) = ub(b);\n      else if (d(b) < 0)\n        x_cauchy(b) = lb(b);\n\n      // z_b = x_p^{cp} - x_b\n      double zb = x_cauchy(b) - x(b);\n      // c   :=  c +\\delta t*p\n      c += dt * p;\n      // cache\n      arma::rowvec wbt = W.row(b);\n\n      f_prime += dt * f_doubleprime + g(b) * g(b)\n                 + theta * g(b) * zb\n                 - g(b) * arma::dot(wbt.t(), (M * c));\n      f_doubleprime += -1.0 * theta * g(b) * g(b);\n      f_doubleprime += 2.0 * g(b) * arma::dot(wbt.t(), M * p);\n      // TODO Check M * wbt.t() is correct\n      f_doubleprime += -g(b) * g(b) * arma::dot(wbt.t(), M * wbt.t());\n      p += g(b) * wbt.t();\n      d(b) = 0;\n      dt_min = -f_prime / f_doubleprime;\n      t_old = t;\n      ++i;\n      if (i < DIM) {\n        b = SortedIndices[i];\n        t = SetOfT[b].second;\n        dt = t - t_old;\n      }\n\n    }\n\n    dt_min = max(dt_min, 0);\n    t_old += dt_min;\n\n    Debug(SortedIndices[0] << \" \" << SortedIndices[1]);\n\n    for (int ii = i; ii < x_cauchy.n_rows; ii++) {\n      x_cauchy(SortedIndices[ii]) = x(SortedIndices[ii])\n                                    + t_old * d(SortedIndices[ii]);\n    }Debug(x_cauchy.transpose());\n\n    c += dt_min * p;\n    Debug(c.transpose());\n\n  }\n\n  /// <summary>\n  /// find valid alpha for (8.5)\n  /// </summary>\n  /// <parameter name=\"x_cp\">cauchy point</parameter>\n  /// <parameter name=\"du\">unconstrained solution of subspace minimization</parameter>\n  /// <parameter name=\"FreeVariables\">flag (1 if is free variable and 0 if is not free variable)</parameter>\n  double FindAlpha(arma::vec & x_cp, arma::vec & du,\n                   std::vector<int> & FreeVariables) {\n    /* this returns\n     * a* = max {a : a <= 1 and  l_i-xc_i <= a*d_i <= u_i-xc_i}\n     */\n    double alphastar = 1;\n    const unsigned int n = FreeVariables.size();\n    for (unsigned int i = 0; i < n; i++) {\n      if (du(i) > 0) {\n        alphastar = min(alphastar,\n                        (ub(FreeVariables[i]) - x_cp(FreeVariables[i]))\n                        / du(i));\n      } else {\n        alphastar = min(alphastar,\n                        (lb(FreeVariables[i]) - x_cp(FreeVariables[i]))\n                        / du(i));\n      }\n    }\n    return alphastar;\n  }\n\n  /// <summary>\n  /// using linesearch to determine step width\n  /// </summary>\n  /// <parameter name=\"x\">start in x</parameter>\n  /// <parameter name=\"dx\">direction</parameter>\n  /// <parameter name=\"f\">current value of objective (will be changed)</parameter>\n  /// <parameter name=\"g\">current gradient of objective (will be changed)</parameter>\n  /// <parameter name=\"t\">step width (will be changed)</parameter>\n  void LineSearch(arma::vec & x, arma::vec dx, double & f, arma::vec & g,\n                  double & t) {\n\n    const double alpha = 0.2;\n    const double beta = 0.8;\n\n    const double f_in = f;\n    const arma::vec g_in = g;\n    const double Cache = alpha * arma::dot(g_in, dx);\n\n    t = 1.0;\n    f = FunctionObjectiveOracle_(x + t * dx);\n    while (f > f_in + t * Cache) {\n      t *= beta;\n      f = FunctionObjectiveOracle_(x + t * dx);\n    }\n    FunctionGradientOracle_(x + t * dx, g);\n    x += t * dx;\n\n  }\n\n  /// <summary>\n  /// direct primal approach\n  /// </summary>\n  /// <parameter name=\"x\">start in x</parameter>\n  void SubspaceMinimization(arma::vec & x_cauchy, arma::vec & x, arma::vec & c,\n                            arma::vec & g,\n                            arma::vec & SubspaceMin) {\n\n    // cached value: ThetaInverse=1/theta;\n    double theta_inverse = 1 / theta;\n\n    // size of \"t\"\n    std::vector<int> FreeVariablesIndex;\n    Debug(x_cauchy.transpose());\n\n    //std::cout << \"free vars \" << FreeVariables.rows() << std::endl;\n    for (int i = 0; i < x_cauchy.n_rows; i++) {\n      Debug(x_cauchy(i) << \" \" << ub(i) << \" \" << lb(i));\n      if ((x_cauchy(i) != ub(i)) && (x_cauchy(i) != lb(i))) {\n        FreeVariablesIndex.push_back(i);\n      }\n    }\n    const int FreeVarCount = FreeVariablesIndex.size();\n\n    arma::mat WZ = arma::zeros(W.n_cols, FreeVarCount);\n\n    for (int i = 0; i < FreeVarCount; i++)\n      WZ.col(i) = W.row(FreeVariablesIndex[i]).t();\n\n    Debug(WZ);\n\n    // r=(g+theta*(x_cauchy-x)-W*(M*c));\n    Debug(g);Debug(x_cauchy);Debug(x);\n    arma::vec rr = (g + theta * (x_cauchy - x) - W * (M * c));\n    // r=r(FreeVariables);\n    arma::vec r = arma::zeros(FreeVarCount);\n    for (int i = 0; i < FreeVarCount; i++)\n      r.row(i) = rr.row(FreeVariablesIndex[i]);\n\n    Debug(r.transpose());\n\n    // STEP 2: \"v = w^T*Z*r\" and STEP 3: \"v = M*v\"\n    arma::vec v = M * (WZ * r);\n    // STEP 4: N = 1/theta*W^T*Z*(W^T*Z)^T\n    arma::mat N = theta_inverse * WZ * WZ.t();\n    // N = I - MN\n    N = arma::eye(N.n_rows, N.n_rows) - M * N;\n    // STEP: 5\n    // v = N^{-1}*v\n    v = arma::inv(N) * v;\n    // STEP: 6\n    // HERE IS A MISTAKE IN THE ORIGINAL PAPER!\n    arma::vec du = -theta_inverse * r\n                   - theta_inverse * theta_inverse * WZ.t() * v;\n    Debug(du.transpose());\n    // STEP: 7\n    double alpha_star = FindAlpha(x_cauchy, du, FreeVariablesIndex);\n\n    // STEP: 8\n    arma::vec dStar = alpha_star * du;\n\n    SubspaceMin = x_cauchy;\n    for (int i = 0; i < FreeVarCount; i++) {\n      SubspaceMin(FreeVariablesIndex[i]) = SubspaceMin(\n          FreeVariablesIndex[i]) + dStar(i);\n    }\n  }\n\n  void Solve(arma::vec & x0, const FunctionOracleType & FunctionValue,\n             const GradientOracleType & FunctionGradient) {\n    FunctionObjectiveOracle_ = FunctionValue;\n    FunctionGradientOracle_ = FunctionGradient;\n\n    Assert(x0.n_rows == lb.n_rows, \"lower bound size incorrect\");\n    Assert(x0.n_rows == ub.n_rows, \"upper bound size incorrect\");\n\n\n    Assert(arma::all(x0 >= lb),\n           \"seed is not feasible (violates lower bound)\");\n    Assert(arma::all(x0 <= ub),\n           \"seed is not feasible (violates upper bound)\");\n\n    const int DIM = x0.n_rows;\n\n    xHistory.push_back(x0);\n\n    arma::mat yHistory = arma::zeros(DIM, 0);\n    arma::mat sHistory = arma::zeros(DIM, 0);\n\n    arma::vec x = x0, g;\n    int k = 0;\n\n    double f = FunctionObjectiveOracle_(x);\n    FunctionGradientOracle_(x, g);\n\n    theta = 1.0;\n\n    W = arma::zeros(DIM, 0);\n    M = arma::zeros(0, 0);\n\n    auto noConvergence =\n        [&](arma::vec & x, arma::vec & g) -> bool {\n            arma::vec clamped = x - g;\n            const auto too_big = arma::find(clamped > lb);\n            clamped(too_big) = lb(too_big);\n            const auto too_small = arma::find(clamped < ub);\n            clamped(too_small) = ub(too_small);\n            return (arma::norm(clamped - x, \"inf\") >= Options_.tol);\n        };\n\n    while (noConvergence(x, g) && (k < Options_.maxIter)) {\n      Debug(\"iteration \" << k)\n      double f_old = f;\n      arma::vec x_old = x;\n      arma::vec g_old = g;\n\n      // STEP 2: compute the cauchy point by algorithm CP\n      arma::vec CauchyPoint = arma::zeros(DIM);\n      arma::vec c = arma::zeros(DIM);\n      GetGeneralizedCauchyPoint(x, g, CauchyPoint, c);\n      // STEP 3: compute a search direction d_k by the primal method\n      arma::vec SubspaceMin;\n      SubspaceMinimization(CauchyPoint, x, c, g, SubspaceMin);\n\n      arma::mat H;\n      double Length = 0;\n\n      // STEP 4: perform linesearch and STEP 5: compute gradient\n      LineSearch(x, SubspaceMin - x, f, g, Length);\n\n      xHistory.push_back(x);\n\n      // prepare for next iteration\n      arma::vec newY = g - g_old;\n      arma::vec newS = x - x_old;\n\n      // STEP 6:\n      double test = arma::dot(newS, newY);\n      test = (test < 0) ? -1.0 * test : test;\n\n      if (test > EPS * arma::norm(newY, 2)) {\n        if (k < Options_.m) {\n          yHistory.resize(DIM, k + 1);\n          sHistory.resize(DIM, k + 1);\n        } else {\n\n          yHistory.head_cols(Options_.m - 1) = yHistory.tail_cols(\n              Options_.m - 1);\n          sHistory.head_cols(Options_.m - 1) = sHistory.tail_cols(\n              Options_.m - 1);\n        }\n        yHistory.tail_cols(1) = newY;\n        sHistory.tail_cols(1) = newS;\n\n        // STEP 7:\n        theta = arma::dot(newY, newY)\n                / arma::dot(newY, newS);\n\n        W = arma::zeros(yHistory.n_rows,\n                        yHistory.n_cols + sHistory.n_cols);\n\n        W(0, 0, arma::size(yHistory)) = yHistory;\n\n        W(0, yHistory.n_cols, arma::size(sHistory)) = theta * sHistory;\n\n        arma::mat A = sHistory.t() * yHistory;\n        arma::mat L = arma::trimatl(A);\n        arma::mat MM(A.n_rows + L.n_rows, A.n_rows + L.n_cols);\n        arma::mat D = -arma::diagmat(A);\n        MM(0, 0, arma::size(D)) = D;\n        MM(0, D.n_cols, arma::size(L.t())) = L.t();\n        MM(D.n_rows, 0, arma::size(L)) = L;\n        arma::mat bottom_right = (sHistory.t() * sHistory)\n                                 * theta;\n        MM(D.n_rows, D.n_cols, arma::size(bottom_right)) = bottom_right;\n\n        M = arma::inv(MM);\n      }\n\n      arma::vec ttt = arma::zeros(1);\n      ttt(0) = f_old - f;\n      Debug(\"--> \" << arma::norm(ttt));\n      if (arma::norm(ttt) < Options_.tol) {\n        // successive function values too similar\n        break;\n      }\n      k++;\n\n    }\n\n    XOpt = x;\n    x0 = x;\n\n  }\n};\n\n#endif /* LBFGSB_H_ */\n", "meta": {"hexsha": "6efb5e2e1ff055e5d155ae67cbaa73d4d9e52bce", "size": 13727, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lbfgsb.hpp", "max_stars_repo_name": "peterbygrave/LBFGSB", "max_stars_repo_head_hexsha": "a1f7164a2e37bd350c10d81f41c594c58f14deeb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lbfgsb.hpp", "max_issues_repo_name": "peterbygrave/LBFGSB", "max_issues_repo_head_hexsha": "a1f7164a2e37bd350c10d81f41c594c58f14deeb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lbfgsb.hpp", "max_forks_repo_name": "peterbygrave/LBFGSB", "max_forks_repo_head_hexsha": "a1f7164a2e37bd350c10d81f41c594c58f14deeb", "max_forks_repo_licenses": ["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.1030701754, "max_line_length": 108, "alphanum_fraction": 0.5506665695, "num_tokens": 4136, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.47416750623873904}}
{"text": "#pragma once\n\n#include <boost/math/constants/constants.hpp>\n#include <cmath>\n\n#include \"GNAObject.hh\"\n#include \"ParametricLazy.hpp\"\n#include \"TypesFunctions.hh\"\n\nclass GaussianPeakWithBackground: public GNAObject,\n                                  public TransformationBind<GaussianPeakWithBackground> {\npublic:\n  GaussianPeakWithBackground(double n=1) {\n    variable_(&m_b, \"BackgroundRate\");\n    variable_(&m_mu, \"Mu\");\n    variable_(&m_E0, \"E0\");\n    variable_(&m_w, \"Width\");\n    using namespace ParametricLazyOps;\n\n    m_w_scaled = mkdep(m_w*std::sqrt( n ));\n    m_E0_scaled = mkdep(m_E0*n);\n\n    transformation_(\"rate\")\n      .input(\"E\")\n      .output(\"rate\")\n      .types(TypesFunctions::pass<0,0>)\n      .func(&GaussianPeakWithBackground::calcRate)\n      ;\n  }\n\n  void calcRate(FunctionArgs fargs) {\n    const double pi = boost::math::constants::pi<double>();\n    const auto &E = fargs.args[0].arr;\n    fargs.rets[0].arr = m_b + m_mu*(1./std::sqrt(2*pi)/m_w_scaled)*(-(E-m_E0_scaled).square()/(2*m_w_scaled*m_w_scaled)).exp();\n  }\nprotected:\n  variable<double> m_b, m_mu, m_E0, m_w;\n  dependant<double> m_w_scaled, m_E0_scaled;\n};\n", "meta": {"hexsha": "aba56837cb04e6f3cebde3704c70000e81df4cad", "size": 1139, "ext": "hh", "lang": "C++", "max_stars_repo_path": "examples/GaussianPeakWithBackground.hh", "max_stars_repo_name": "gnafit/gna", "max_stars_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-10-14T01:06:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-02T16:33:06.000Z", "max_issues_repo_path": "examples/GaussianPeakWithBackground.hh", "max_issues_repo_name": "gnafit/gna", "max_issues_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_issues_repo_licenses": ["MIT"], "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/GaussianPeakWithBackground.hh", "max_forks_repo_name": "gnafit/gna", "max_forks_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_forks_repo_licenses": ["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.475, "max_line_length": 127, "alphanum_fraction": 0.6637401229, "num_tokens": 320, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213718636754, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.4741215559074202}}
{"text": "#include <transwarp.h>\n#include <iostream>\n#include <boost/math/constants/constants.hpp>\n#include <parallel/numeric>\n\nnamespace daq\n{\n    constexpr double f = 15.0;       // Hz\n    constexpr double rate = 95000.0; // Hz\n\n    int ricker_filter_size(double f_, double rate_, double width = 5.0) noexcept\n    {\n        constexpr double ricker_coefficient = 2.2508;\n        return static_cast<int>(lround (width / ricker_coefficient / f_ * rate_ + 0.5));\n    }\n\n    // TODO: Improve make_odd(), align_by_ten(), ricker_filter_size() functions to do a simmetrical filter without sly tricks\n    int align_by_ten(int sz) noexcept\n    {\n        return sz / 10 * 10 + 10;\n    }\n\n    int make_odd(int sz) noexcept\n    {\n        return (sz % 2) ? sz : (sz + 1);\n    }\n\n    constexpr size_t ricker_filter_max_size = 20000;\n    using ricker_filter_data_type = std::array<double, ricker_filter_max_size + 1>;\n\n    struct ricker_filter {\n        ricker_filter_data_type& data;\n        size_t& sz;\n    };\n\n    void create_filter(int dots, ricker_filter & rfd) noexcept\n    {\n        assert (rfd.data.size() > dots);\n\n        auto const tricky_dots = (dots - 1) / 10;\n        double const c = 2 / ((sqrt (3)) * pow (boost::math::constants::pi<double>(), 0.25));\n        double const one_per_mh_dots = 1.0 / tricky_dots;\n        double t = -5.0;\n\n        for (int i = 0; i < dots; ++i)\n        {\n            const double pow_t_2 = pow (t, 2);\n            rfd.data[i] = c * exp(-pow_t_2 / 2) * (1 - pow_t_2);\n            t += one_per_mh_dots;\n        }\n\n        rfd.sz = dots;\n    }\n\n    using sample_type = int32_t;\n    using signal_sequence_type = std::vector<sample_type>;\n    using transform_result_type = double;\n\n    using sample_quantity_type = int;\n    using prepare_type = std::tuple<sample_quantity_type, const signal_sequence_type &>;\n    using output_type = std::shared_ptr<std::vector<transform_result_type>>;\n\n    output_type partial_task(prepare_type input, uint8_t part_index, uint8_t part_number, ricker_filter const & rfd)\n    {\n        auto const sample_quantity = std::get<0>(input);\n        auto const & signal_sequence = std::get<1>(input);\n\n        auto const default_iteration_number = sample_quantity / part_number;\n        auto const begin_iter = std::begin(signal_sequence) + ((part_index - 1) * default_iteration_number);\n        auto const end_iter = (part_index != part_number) ? (std::begin(signal_sequence) + ((part_index) * default_iteration_number + rfd.sz)) : std::end(signal_sequence);\n\n        sample_type signal_subsequence [std::distance(begin_iter, end_iter)];\n        ricker_filter_data_type::value_type filter [rfd.sz];\n\n        std::copy (begin_iter, end_iter, signal_subsequence);\n        std::copy (std::begin(rfd.data), std::begin(rfd.data) + rfd.sz, filter);\n\n        auto const total_iterations = (part_index != part_number) ? (sample_quantity / part_number) : (sample_quantity / part_number + (sample_quantity % part_number));\n        auto const data = std::make_shared<std::vector<transform_result_type>>(total_iterations);\n\n        auto curr = std::begin(*data);\n        auto const end = curr + total_iterations;\n\n        auto pure_s_iter = signal_subsequence;\n\n        while (curr != end)\n        {\n            *curr++ = static_cast<transform_result_type>(std::inner_product(filter, filter + rfd.sz, pure_s_iter++, 0.0) / rfd.sz);\n        }\n\n        return data;\n    }\n\n    namespace tw = transwarp;\n    constexpr int hardware_threads = 8; /*std::thread::hardware_concurrency();*/\n    tw::parallel & get_executor()\n    {\n        static tw::parallel executor(hardware_threads);\n        return executor;\n    }\n\n    static std::shared_ptr<tw::task<output_type>> make_task_by_index (uint8_t index, signal_sequence_type const & ss, size_t from, size_t to, ricker_filter const & fd)\n    {\n        return tw::make_task(tw::consume, [&] (prepare_type input, uint8_t index)\n                             {\n                                 return partial_task(input, index, hardware_threads, fd);\n                             },\n                             tw::make_value_task (std::make_tuple(to - from, ss)), tw::make_value_task(index)\n        );\n    }\n\n    static std::shared_ptr<tw::task<void>> gather_task(signal_sequence_type const & ss, size_t from, size_t to,\n                                                       transform_result_type * const result, ricker_filter const & filter_data) {\n\n        std::vector<std::shared_ptr<tw::task<output_type>>> vec (hardware_threads);\n        uint8_t task_idx = 1;\n        for (auto & elem : vec)\n        {\n            elem = make_task_by_index(static_cast<uint8_t>(task_idx++), ss, from, to, filter_data);\n        }\n\n        // capture by value\n        return tw::make_task(tw::consume, [=](std::vector<output_type> const & parents) {\n            size_t copy_pos = 0;\n            for (auto & elem : parents)\n            {\n                std::copy (elem->begin(), elem->begin()+elem->size(), &result[copy_pos]);\n                copy_pos += elem->size();\n            }\n        }, vec);\n\n    }\n\n    auto inner_product_lambda = [](auto&&... args){return std::inner_product(decltype(args)(args)...);};\n    auto parallel_inner_product_lambda = [](auto&&... args){return __gnu_parallel::inner_product(decltype(args)(args)...);};\n\n    template <typename L>\n    inline void seq_transform(signal_sequence_type const & ss, transform_result_type * const result, ricker_filter const & filter_data, L const & lambda)\n    {\n        auto const iterations = static_cast<size_t>(rate);\n        int curr_iteration = 0;\n        while (curr_iteration < iterations)\n        {\n            result[curr_iteration] = static_cast<transform_result_type> (\n                    lambda(std::begin(filter_data.data), std::begin(filter_data.data) + filter_data.sz, std::begin(ss) + curr_iteration, 0.0) / filter_data.sz\n            );\n            ++curr_iteration;\n        }\n    }\n\n    void transform_uni(signal_sequence_type const & ss, transform_result_type * const result, ricker_filter const & filter_data)\n    {\n        seq_transform (ss, result, filter_data, inner_product_lambda);\n    }\n\n    void transform_omp (signal_sequence_type const & ss, transform_result_type * const result, ricker_filter const & filter_data)\n    {\n        seq_transform (ss, result, filter_data, parallel_inner_product_lambda);\n    }\n\n    void transform_tw(signal_sequence_type const & ss, transform_result_type * const result, ricker_filter const & filter_data)\n    {\n        auto final_task = gather_task(ss, 0, static_cast<size_t>(rate), result, filter_data);\n        final_task->schedule_all(get_executor());\n        final_task->get();\n    }\n}\n\ntemplate <typename F, typename ...T>\nvoid measure_it(char const* f_name, F const & f, T &&... arguments)\n{\n    auto const time_point1 = std::chrono::high_resolution_clock::now();\n    f (std::forward<T>(arguments)...);\n    auto const time_point2 = std::chrono::high_resolution_clock::now();\n    std::cout << f_name << std::chrono::duration_cast<std::chrono::milliseconds>(time_point2-time_point1).count() << std::endl;\n}\n\nstd::array<daq::transform_result_type, static_cast<size_t>(daq::rate)> transform_uni_result{};\nstd::array<daq::transform_result_type, static_cast<size_t>(daq::rate)> transform_omp_result{};\nstd::array<daq::transform_result_type, static_cast<size_t>(daq::rate)> transform_tw_result{};\n\n\n#ifndef MAIN_IS_ABSENT\nint main()\n{\n    using namespace daq;\n\n    ricker_filter_data_type filter_data {};\n    size_t filter_size {};\n    ricker_filter filter {filter_data, filter_size};\n\n    create_filter (make_odd(align_by_ten(ricker_filter_size(f, rate))), filter);\n\n    signal_sequence_type ss (static_cast<size_t>(rate) + filter.sz);\n    std::iota(std::begin(ss), std::end(ss), -rate/2);\n\n    measure_it(\"transform_uni: \", transform_uni, ss, std::addressof(transform_uni_result[0]), filter);\n    measure_it(\"transform_omp: \", transform_omp, ss, std::addressof(transform_omp_result[0]), filter);\n    measure_it(\"transform_tw:  \", transform_tw, ss, std::addressof(transform_tw_result[0]), filter);\n    return 0;\n}\n#endif\n", "meta": {"hexsha": "e342e619cd4c28e8c145b6eb79ec2fcb4decd340", "size": 8101, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "wiluite/RWT", "max_stars_repo_head_hexsha": "87a47bca3863f50b46cc6efc1e06cdf6806db60a", "max_stars_repo_licenses": ["MIT"], "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": "wiluite/RWT", "max_issues_repo_head_hexsha": "87a47bca3863f50b46cc6efc1e06cdf6806db60a", "max_issues_repo_licenses": ["MIT"], "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": "wiluite/RWT", "max_forks_repo_head_hexsha": "87a47bca3863f50b46cc6efc1e06cdf6806db60a", "max_forks_repo_licenses": ["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.9064039409, "max_line_length": 171, "alphanum_fraction": 0.647450932, "num_tokens": 1983, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402812, "lm_q2_score": 0.5660185351961016, "lm_q1q2_score": 0.4741084292856284}}
{"text": "#include \"libsnark/common/data_structures/merkle_tree.hpp\"  //for the merkle_authentication_node\n#include \"libsnark/common/default_types/r1cs_ppzksnark_pp.hpp\"  //for the default_r1cs_ppzksnark_pp\n#include \"libsnark/gadgetlib1/gadgets/hashes/sha256/sha256_gadget.hpp\"   // for the sha256_two_to_one_hash_gadget\n#include \"libsnark/common/utils.hpp\"  //for the bit_vector\n#include \"libsnark/gadgetlib1/gadgets/merkle_tree/merkle_tree_check_read_gadget.hpp\" // for the merkle_tree_check_read_gadget\n#include \"libsnark/gadgetlib1/gadgets/basic_gadgets.hpp\"\n#include \"libsnark/zk_proof_systems/ppzksnark/r1cs_ppzksnark/r1cs_ppzksnark.hpp\"\n#include \"algebra/fields/field_utils.hpp\"\n#include \"libsnark/common/utils.hpp\"\n#include <boost/optional.hpp>\n#include \"gadget.hpp\"\n\nusing namespace libsnark;\nusing namespace std;\n\ntemplate<typename HashT>\nvoid generate_merkle_and_branch(bit_vector &prev_leaf, bit_vector &leaf, bit_vector &root,\n                                size_t &address, bit_vector &address_bits,\n                                std::vector<merkle_authentication_node> &path) {\n\n    bit_vector prev_hash = leaf;\n    path = std::vector<merkle_authentication_node> (tree_depth);\n\n    for (long level = tree_depth - 1; level >= 0; --level) {\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        bit_vector other(sha256_digest_len);\n        std::generate(other.begin(), other.end(), [&](){return std::rand()%2;});\n        bit_vector block = prev_hash;\n        block.insert(computed_is_right ? block.begin() : block.end(), other.begin(), other.end());\n        bit_vector h = HashT::get_hash(block);\n\n        path[level] = other;\n        prev_hash = h;\n    }\n\n    root = prev_hash;\n}\n\ntemplate<typename ppzksnark_ppT, typename HashT>\nr1cs_ppzksnark_keypair<ppzksnark_ppT> generate_keypair()\n{\n    typedef Fr<ppzksnark_ppT> FieldT;\n\n    protoboard<FieldT> pb;\n    toy_gadget<FieldT, HashT> g(pb);\n    g.generate_r1cs_constraints();\n    const r1cs_constraint_system<FieldT> constraint_system = pb.get_constraint_system();\n\n    cout << \"Number of R1CS constraints: \" << constraint_system.num_constraints() << endl;\n    cout << \"auxiliary input size : \" << constraint_system.auxiliary_input_size << endl;\n    cout << \"primary_input size : \" << constraint_system.primary_input_size << endl;\n\n    return r1cs_ppzksnark_generator<ppzksnark_ppT>(constraint_system);\n}\n\ntemplate<typename ppzksnark_ppT, typename HashT>\nboost::optional<r1cs_ppzksnark_proof<ppzksnark_ppT>> generate_proof(r1cs_ppzksnark_proving_key<ppzksnark_ppT> proving_key,\n                                                                   const bit_vector &prev_leaf,\n                                                                   const bit_vector &leaf,\n                                                                   const bit_vector &root,\n                                                                   const size_t address,\n                                                                   const bit_vector &address_bits,\n                                                                   const std::vector<merkle_authentication_node> &path\n                                                                   )\n{\n    typedef Fr<ppzksnark_ppT> FieldT;\n\n    protoboard<FieldT> pb;\n    toy_gadget<FieldT, HashT> g(pb);\n    g.generate_r1cs_constraints();\n    g.generate_r1cs_witness(prev_leaf, leaf, root, address, address_bits, path);\n\n    if (!pb.is_satisfied()) {\n        return boost::none;\n    }\n\n    return r1cs_ppzksnark_prover<ppzksnark_ppT>(proving_key, pb.primary_input(), pb.auxiliary_input());\n}\n\ntemplate<typename ppzksnark_ppT>\nbool verify_proof(r1cs_ppzksnark_verification_key<ppzksnark_ppT> verification_key,\n                  r1cs_ppzksnark_proof<ppzksnark_ppT> proof,\n                  const bit_vector &prev_leaf,\n                  const bit_vector &root\n                 )\n{\n    typedef Fr<ppzksnark_ppT> FieldT;\n    /*\n    r1cs_primary_input<FieldT> input;\n    input.insert(input.end(), prev_leaf.begin(), prev_leaf.end());\n    input.insert(input.end(), root.begin(), root.end());\n    */\n    const r1cs_primary_input<FieldT> input = l_input_map<FieldT>(prev_leaf, root);\n    return r1cs_ppzksnark_verifier_strong_IC<ppzksnark_ppT>(verification_key, input, proof);\n}\n", "meta": {"hexsha": "e05edb557fb0d4582ea95ca989b889f10009e6b0", "size": 4399, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/snark.hpp", "max_stars_repo_name": "Federico2014/zkSNARK-toy", "max_stars_repo_head_hexsha": "3237e079913c52ca177f1560491ca0641de727ad", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 56.0, "max_stars_repo_stars_event_min_datetime": "2017-05-01T14:28:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T15:21:54.000Z", "max_issues_repo_path": "src/snark.hpp", "max_issues_repo_name": "wanzhiguo/zksnark-toy", "max_issues_repo_head_hexsha": "33ea2186af1b5f9fc7f6ee3be54b0b15ee5a8b31", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2018-02-08T09:26:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T14:45:58.000Z", "max_forks_repo_path": "src/snark.hpp", "max_forks_repo_name": "wanzhiguo/zksnark-toy", "max_forks_repo_head_hexsha": "33ea2186af1b5f9fc7f6ee3be54b0b15ee5a8b31", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2018-04-18T07:25:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-27T03:01:54.000Z", "avg_line_length": 44.887755102, "max_line_length": 125, "alphanum_fraction": 0.6474198682, "num_tokens": 1087, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.47410842469692055}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2015 NumScale SAS\n  @copyright 2015 J.T. Lapreste\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_COMMON_FUNCTION_GENERIC_ACOTD_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_FUNCTION_GENERIC_ACOTD_HPP_INCLUDED\n\n#ifndef BOOST_SIMD_NO_INFINITIES\n#include <boost/simd/function/simd/is_inf.hpp>\n#endif\n#include <boost/simd/constant/ratio.hpp>\n#include <boost/simd/function/abs.hpp>\n#include <boost/simd/function/atand.hpp>\n#include <boost/simd/function/bitofsign.hpp>\n#include <boost/simd/function/bitwise_or.hpp>\n#include <boost/simd/function/if_else_zero.hpp>\n#include <boost/simd/function/if_zero_else.hpp>\n#include <boost/simd/function/is_nez.hpp>\n#include <boost/simd/function/minus.hpp>\n#include <boost/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 ( acotd_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::generic_<bd::floating_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() ( A0 const& a0) const BOOST_NOEXCEPT\n    {\n      A0 z = Ratio<A0, 90>()-if_else_zero(is_nez(a0),atand(bs::abs(a0)));\n      #ifndef BOOST_SIMD_NO_INFINITIES\n      z = if_zero_else(is_inf(a0),z);\n      #endif\n      return bitwise_or(z, bitofsign(a0));\n    }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "9c4ec648c2fe579b50c28a09ec4744a0eaa441df", "size": 1748, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arch/common/generic/function/acotd.hpp", "max_stars_repo_name": "yaeldarmon/boost.simd", "max_stars_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/simd/arch/common/generic/function/acotd.hpp", "max_issues_repo_name": "yaeldarmon/boost.simd", "max_issues_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/arch/common/generic/function/acotd.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": 32.9811320755, "max_line_length": 100, "alphanum_fraction": 0.6127002288, "num_tokens": 403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4741084201082126}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n\n// EigenML includes\n#include <eigenml/decision_tree/decision_tree.hpp>\n#include <eigenml/core/eigenml.hpp>\n\nusing namespace std;\nusing namespace eigenml;\n\nint main() {\n\n    logging::init_cerr_log(logging::severity_level::info);\n\n    logging::Logger logger(\"MAIN\");\n\n    std::srand((unsigned int) time(0));\n\n    size_t N = 100000;\n    size_t P = 1;\n    Matrix X = Matrix::Random(N, P);\n    Matrix c = Matrix::Random(P, 1);\n    Vector Y(N);\n\n    c << 1;\n    Y = (X.array()).matrix();\n\n    Vector I(X.rows());\n    Matrix XY(X.rows(), I.cols() + X.cols()+Y.cols());\n    std::iota(I.data(), I.data() + I.size(), 0);\n    XY << I, X, Y;\n\n    LOG_DEBUG << XY;\n\n    // // Declare a tree\n    LOG_INFO << \"Fitting a tree\";\n    decision_tree::DecisionTreeParams params;\n\n    params.max_depth = 6;\n    params.criterion = decision_tree::SplitCriterion::kMSECriterion;\n\n    decision_tree::DecisionTree<ModelType::kSupervisedRegressor> tree(params);\n    tree.fit(X, Y);\n\n    std::cout << (tree.transform(X)-Y).squaredNorm() << std::endl << \"*****\" << std::endl;\n}\n", "meta": {"hexsha": "c062391421a91152bd888484307ad6d76538727e", "size": 1092, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/examples/main_tree_regressor.cpp", "max_stars_repo_name": "guillempalou/eigenml", "max_stars_repo_head_hexsha": "3991ddbfd01032cbbe698f6ec35eecbfe127e9b4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/examples/main_tree_regressor.cpp", "max_issues_repo_name": "guillempalou/eigenml", "max_issues_repo_head_hexsha": "3991ddbfd01032cbbe698f6ec35eecbfe127e9b4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/examples/main_tree_regressor.cpp", "max_forks_repo_name": "guillempalou/eigenml", "max_forks_repo_head_hexsha": "3991ddbfd01032cbbe698f6ec35eecbfe127e9b4", "max_forks_repo_licenses": ["Apache-2.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.2340425532, "max_line_length": 90, "alphanum_fraction": 0.6227106227, "num_tokens": 306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.47404152901881436}}
{"text": "#include <cstdio>\n#include <string>\n#include <cstdlib>\n#include <cmath>\n#include <iostream>\n#include <fstream>\n#include <Eigen/Dense>\n#include <vector>\n\n#include \"global.h\"\n#include \"uDGP.h\"\n#include \"SED.h\"\n\nusing namespace std;\nusing namespace Eigen;\n\nusing std::ifstream;\nusing std::string;\n\nvoid process_cmdline(char *argv[], char **data_file, char **option_file, char **output_file) {\n\t\n\t*data_file\t    = argv[1];\n\t*option_file\t= argv[2];\n\t*output_file\t= argv[3];\n}\n\nint main(int argc, char *argv[]){\n\n\tchar *data_file, *option_file, *output_file;\n\tif (argc==4) {\n\t\tprocess_cmdline(argv, &data_file, &option_file, &output_file);\n\t} else {\n\t\tcout<<\"Command line error!\"<<endl;\n\t\tabort();\n\t}\n\n\tDataReader data_input(option_file);\n\tdata_input.SetParameters();\n    data_input.ReadData(data_file);\n\n\tuDGP *udgp_gd = new SED();\n    udgp_gd->SetOutputFile(output_file);\n    udgp_gd->SetData(&data_input);\n    udgp_gd->SetMeasureMatrix();\n    udgp_gd->Initialization();\n    udgp_gd->GradientDescent();\n    \n    VectorXd smp_pos_out = udgp_gd->GetSamplePos();\n\n    ofstream write_result(output_file, ios_base::trunc);\n    for (int i=0; i<smp_pos_out.size(); i++) {\n        write_result<<smp_pos_out(i)<<\" \";\n    }\n    write_result<<\"\\n\";\n    write_result.close();\n    \n    delete udgp_gd;\n\n\texit(0);\n}\n", "meta": {"hexsha": "f5d84568b313c35717f5e66c7ef88d36d86ac196", "size": 1298, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "turnpike/src/main.cpp", "max_stars_repo_name": "shuai-huang/turnpike-beltway", "max_stars_repo_head_hexsha": "20b68a48b68c2daad02346b1c076c0dce99c4431", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "turnpike/src/main.cpp", "max_issues_repo_name": "shuai-huang/turnpike-beltway", "max_issues_repo_head_hexsha": "20b68a48b68c2daad02346b1c076c0dce99c4431", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "turnpike/src/main.cpp", "max_forks_repo_name": "shuai-huang/turnpike-beltway", "max_forks_repo_head_hexsha": "20b68a48b68c2daad02346b1c076c0dce99c4431", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-01-06T17:17:17.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-06T17:17:17.000Z", "avg_line_length": 21.2786885246, "max_line_length": 94, "alphanum_fraction": 0.6741140216, "num_tokens": 364, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825007, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.47397296443097925}}
{"text": "#include <algorithm>\n#include <boost/optional.hpp>\n#include <climits>\n#include <cmath>\n#include <cstdio>\n#include <cstring>\n#include <functional>\n#include <iostream>\n#include <limits>\n#include <list>\n#include <map>\n#include <numeric>\n#include <queue>\n#include <set>\n#include <sstream>\n#include <string>\n#include <tuple>\n#include <type_traits>\n#include <unordered_map>\n#include <unordered_set>\n#include <utility>\n#include <vector>\n\n#define REP(i, n) for(int i = 0, i##_MACRO = (n); i < i##_MACRO; i++)\n#define RANGE(i, a, b) for(int i = (a), i##_MACRO = (b); i < i##_MACRO; i++)\n#define EACH(e, a) for(auto&& e : a)\n#define ALL(a) std::begin(a), std::end(a)\n#define RALL(a) std::rbegin(a), std::rend(a)\n#define FILL(a, n) memset((a), n, sizeof(a))\n#define FILLZ(a) FILL(a, 0)\n#define INT(x) (static_cast<int>(x))\n\nusing namespace std;\n\nusing ll = long long;\nusing VI = vector<int>;\nusing VI2D = vector<vector<int>>;\n\nconstexpr int INF = 2e9;\nconstexpr double EPS = 1e-10;\nconstexpr double PI = acos(-1.0);\n\nconstexpr int dx[] = {-1, 0, 1, 0};\nconstexpr int dy[] = {0, -1, 0, 1};\n\ntemplate <typename T>\nconstexpr int sign(T x) {\n\treturn x < 0 ? -1 : x > 0 ? 1 : 0;\n}\n\ntemplate <>\nconstexpr int sign(double x) {\n\treturn x < -EPS ? -1 : x > EPS ? 1 : 0;\n}\n\ntemplate <typename T, typename U>\nconstexpr void chmax(T& m, U x) {\n\tm = max(m, x);\n}\n\ntemplate <typename T, typename U>\nconstexpr void chmin(T& m, U x) {\n\tm = min(m, x);\n}\n\ntemplate <typename T>\nconstexpr T square(T x) {\n\treturn x * x;\n}\n\nstruct LoopInfo {\n\tll dist_begin_loop;\n\tll loop_begin_node;\n\tll loop_size;\n\tLoopInfo(ll d, ll n, ll s)\n\t\t: dist_begin_loop(d), loop_begin_node(n), loop_size(s) {}\n};\n\n// loop\u306e\u59cb\u70b9\u307e\u3067\u306e\u8ddd\u96e2, loop\u306e\u59cb\u70b9, loop\u306e\u30b5\u30a4\u30ba\nLoopInfo find_loop(vector<ll>& a) {\n\tll n = a.size();\n\tvector<ll> dist(n, 0);\n\tll node = 0;\n\tll prev_node = 0;\n\tll i = 0;\n\tdist[0] = -1;\n\twhile(true) {\n\t\t// cout << \"node: \" << node << endl;\n\t\tdist[node] = dist[prev_node] + 1;\n\t\tprev_node = node;\n\t\tnode = a[node] - 1;\n\t\tif(dist[node] != 0 || (i != 0 && node == 0)) {\n\t\t\t// cout << \"node: \" << node << \", prev: \" << prev_node\n\t\t\t//\t << \", dist[node]: \" << dist[node] << endl;\n\t\t\treturn LoopInfo(dist[node], node, dist[prev_node] - dist[node] + 1);\n\t\t}\n\t\ti++;\n\t}\n}\n\nll find_node(vector<ll>& a, ll count) {\n\tll node = 0;\n\tREP(i, count) { node = a[node] - 1; }\n\treturn node;\n}\n\nint main() {\n\tll n, k;\n\tcin >> n >> k;\n\tvector<ll> a(n);\n\tREP(i, n) { cin >> a[i]; }\n\tLoopInfo li = find_loop(a);\n\t// cout << \"dist: \" << li.dist_begin_loop << \", size: \" << li.loop_size\n\t//\t << endl;\n\tif(k < li.dist_begin_loop) {\n\t\tcout << find_node(a, k) + 1 << endl;\n\t} else {\n\t\tcout << find_node(a,\n\t\t\t\t\t\t  li.dist_begin_loop +\n\t\t\t\t\t\t\t  (k - li.dist_begin_loop) % li.loop_size) +\n\t\t\t\t\t1\n\t\t\t << endl;\n\t}\n\treturn 0;\n}\n", "meta": {"hexsha": "9e9e0bfd5097dc37b4278e34039cf79f1a9ae53a", "size": 2740, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AtCoder/ABC167/D.cpp", "max_stars_repo_name": "arlechann/atcoder", "max_stars_repo_head_hexsha": "1af08efa6d3a0e8c75e4eaf13e1eda994820b9e2", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AtCoder/ABC167/D.cpp", "max_issues_repo_name": "arlechann/atcoder", "max_issues_repo_head_hexsha": "1af08efa6d3a0e8c75e4eaf13e1eda994820b9e2", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AtCoder/ABC167/D.cpp", "max_forks_repo_name": "arlechann/atcoder", "max_forks_repo_head_hexsha": "1af08efa6d3a0e8c75e4eaf13e1eda994820b9e2", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.746031746, "max_line_length": 76, "alphanum_fraction": 0.598540146, "num_tokens": 909, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825006, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4739729644309792}}
{"text": "#define BOOST_TEST_MODULE \"test_lennard_jones_potential\"\n\n#ifdef BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n#else\n#include <boost/test/included/unit_test.hpp>\n#endif\n\n#include <mjolnir/forcefield/global/LennardJonesPotential.hpp>\n#include <mjolnir/core/BoundaryCondition.hpp>\n#include <mjolnir/core/SimulatorTraits.hpp>\n\nBOOST_AUTO_TEST_CASE(LennardJones_double)\n{\n    using traits_type = mjolnir::SimulatorTraits<double, mjolnir::UnlimitedBoundary>;\n    using real_type   = typename traits_type::real_type;\n    using molecule_id_type = mjolnir::Topology::molecule_id_type;\n    using group_id_type    = mjolnir::Topology::group_id_type;\n    using potential_type   = mjolnir::LennardJonesPotential<traits_type>;\n    using parameter_type   = potential_type::parameter_type;\n\n    constexpr static std::size_t N = 10000;\n    constexpr static real_type   h = 1e-6;\n\n    const real_type sigma   = 3.0;\n    const real_type epsilon = 1.0;\n    const parameter_type param{sigma, epsilon};\n    potential_type lj{\n        potential_type::default_cutoff(),\n        {{0, param}, {1, param}}, {},\n        mjolnir::IgnoreMolecule<molecule_id_type>(\"Nothing\"),\n        mjolnir::IgnoreGroup   <group_id_type   >({})\n    };\n\n    const real_type x_min = 0.8 * sigma;\n    const real_type x_max = lj.cutoff_ratio() * sigma;\n    const real_type dx = (x_max - x_min) / N;\n\n    for(std::size_t i=0; i<N; ++i)\n    {\n        const real_type x    = x_min + i * dx;\n        const real_type pot1 = lj.potential(0, 1, x + h);\n        const real_type pot2 = lj.potential(0, 1, x - h);\n        const real_type dpot = (pot1 - pot2) / (2 * h);\n        const real_type deri = lj.derivative(0, 1, x);\n\n        BOOST_TEST(dpot == deri, boost::test_tools::tolerance(h));\n    }\n}\n\nBOOST_AUTO_TEST_CASE(LennardJones_float)\n{\n    using traits_type = mjolnir::SimulatorTraits<float, mjolnir::UnlimitedBoundary>;\n    using real_type   = typename traits_type::real_type;\n    using molecule_id_type = mjolnir::Topology::molecule_id_type;\n    using group_id_type    = mjolnir::Topology::group_id_type;\n    using potential_type   = mjolnir::LennardJonesPotential<traits_type>;\n    using parameter_type   = potential_type::parameter_type;\n    constexpr std::size_t N = 1000;\n    constexpr real_type   h = 0.002f;\n    constexpr real_type tol = 0.005f;\n\n    const real_type sigma   = 3.0f;\n    const real_type epsilon = 1.0f;\n    const parameter_type param{sigma, epsilon};\n    potential_type lj{potential_type::default_cutoff(),\n        {{0, param}, {1, param}}, {},\n        mjolnir::IgnoreMolecule<molecule_id_type>(\"Nothing\"),\n        mjolnir::IgnoreGroup   <group_id_type   >({})\n    };\n    const real_type cutoff = lj.cutoff_ratio();\n\n    const real_type x_min = 0.8f   * sigma;\n    const real_type x_max = cutoff * sigma;\n    const real_type dx = (x_max - x_min) / N;\n\n    for(std::size_t i=0; i<N; ++i)\n    {\n        const real_type x    = x_min + i * dx;\n        const real_type pot1 = lj.potential(0, 1, x + h);\n        const real_type pot2 = lj.potential(0, 1, x - h);\n        const real_type dpot = (pot1 - pot2) / (2 * h);\n        const real_type deri = lj.derivative(0, 1, x);\n\n        BOOST_TEST(dpot == deri, boost::test_tools::tolerance(tol));\n    }\n}\n\n\n", "meta": {"hexsha": "3371a9a14efce00db3e3b974e4ccf544f4c465ec", "size": 3232, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/core/test_lennard_jones_potential.cpp", "max_stars_repo_name": "yutakasi634/Mjolnir", "max_stars_repo_head_hexsha": "ab7a29a47f994111e8b889311c44487463f02116", "max_stars_repo_licenses": ["MIT"], "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/core/test_lennard_jones_potential.cpp", "max_issues_repo_name": "yutakasi634/Mjolnir", "max_issues_repo_head_hexsha": "ab7a29a47f994111e8b889311c44487463f02116", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-07T11:41:45.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-08T10:01:38.000Z", "max_forks_repo_path": "test/core/test_lennard_jones_potential.cpp", "max_forks_repo_name": "yutakasi634/Mjolnir", "max_forks_repo_head_hexsha": "ab7a29a47f994111e8b889311c44487463f02116", "max_forks_repo_licenses": ["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.9111111111, "max_line_length": 85, "alphanum_fraction": 0.6695544554, "num_tokens": 930, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.779992900254107, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.47397295821556107}}
{"text": "#include \"house.hpp\"\n#include \"ukf.hpp\"\n#include \"dyn.hpp\"\n#include \"filter_aux.hpp\"\n#include \"pearsonator.hpp\"\n#include \"timer.hpp\"\n#include \"eigen_csv.hpp\"\n\n#include <Eigen/Dense>\n\n#include <cmath>\n#include <ctime>\n#include <functional>\n#include <iostream>\n#include <random>\n#include <vector>\n\nusing namespace Eigen;\nusing namespace std;\n\nvoid run(bool gauss) {\n\n    Matrix3d I;\n\n    I << 500+400, 0, 0,\n         0, 500+300, 0,\n         0, 0, 400+300;\n\n    DynamicModel::stf g = [&I] (double t, const Vector3d& w, const Vector3d& Td)\n        -> VectorXd {\n            return I.inverse() * (Td - w.cross(I * w));\n        };\n\n    DynamicModel f(g, 3, 1E-9, 1E-9);\n\n    UKF::meas_model h = [] (double t, const Vector3d& w)\n        -> VectorXd {\n            return w.head(1);\n        };\n\n    HOUSE::meas_model hh = [] (double t, const VectorXd& w, const VectorXd& v)\n        -> VectorXd {\n            return w.head(1) + v;\n        };\n\n    double stdx0, stdw, stdn, dt;\n\n    stdx0 = 0.01;\n    stdw  = 0.001;\n    stdn  = 0.001;\n\n    dt = 0.1;\n\n    Matrix3d Pxx0, Pww;\n    MatrixXd Pnn(1,1);\n\n    Pxx0 = Matrix3d::Identity() * stdx0 * stdx0;\n    Pww  = Matrix3d::Identity() * stdw  * stdw;\n    Pnn(0,0) = stdn * stdn;\n\n    Vector3d wm0;\n    wm0 << 0, 0, 0;\n\n    Vector3d w0;\n\n    int trials = 100;\n    int steps = 6001;\n\n    VectorXd t;\n    t.setLinSpaced(steps, 0, (steps-1)*dt);\n\n    vector<vector<VectorXd>> xtru, xest_ukf, xest_cut4, xest_cut6, xest_cut8,\n        xest_house;\n\n    double skew0, skeww, skewn, kurt0, kurtw, kurtn;\n\n    if (gauss) {\n\n        skew0 = 0;\n        kurt0 = 3;\n\n        skeww = 0;\n        kurtw = 3;\n\n        skewn = 0;\n        kurtn = 3;\n\n    } else {\n\n        skew0 = -1;\n        kurt0 = 30;\n\n        skeww = -1;\n        kurtw = 30;\n\n        skewn = -1;\n        kurtn = 30;\n\n    }\n\n    Pearsonator::TypeIV gen0_p(0, stdx0, skew0, kurt0), genw_p(0, stdw, skeww, kurtw),\n        genn_p(0, stdn, skewn, kurtn);\n\n    normal_distribution<double> gen0_g(0, stdx0), genw_g(0, stdw), genn_g(0, stdn);\n\n    mt19937_64 mt(0);\n\n    typedef function<double(void)> noisemaker;\n\n    noisemaker gen0 = [&] () -> double {return gauss ? gen0_g(mt) : gen0_p(mt);};\n    noisemaker genw = [&] () -> double {return gauss ? genw_g(mt) : genw_p(mt);};\n    noisemaker genn = [&] () -> double {return gauss ? genn_g(mt) : genn_p(mt);};\n\n    UKF::cut_dir = \"../CUT/\";\n\n    UKF ukf (f, h, false, 0, wm0, Pxx0, Pww, Pnn, UKF::sig_type::JU,   1);\n    UKF cut4(f, h, false, 0, wm0, Pxx0, Pww, Pnn, UKF::sig_type::CUT4, 1);\n    UKF cut6(f, h, false, 0, wm0, Pxx0, Pww, Pnn, UKF::sig_type::CUT6, 1);\n    UKF cut8(f, h, false, 0, wm0, Pxx0, Pww, Pnn, UKF::sig_type::CUT8, 1);\n\n    HOUSE::Dist distx0(Pxx0), distw(Pww), distn(Pnn);\n\n    distx0.mean = wm0;\n\n    distx0.skew.setConstant(skew0);\n    distx0.kurt.setConstant(kurt0);\n\n    distw.skew.setConstant(skeww);\n    distw.kurt.setConstant(kurtw);\n\n    distn.skew.setConstant(skewn);\n    distn.kurt.setConstant(kurtn);\n\n    HOUSE house(f, hh, 1, 0, distx0, distw, distn, 0);\n\n    MatrixXd run_times(trials,5);\n    Timer timer;\n\n    for (int j = 0; j < trials; j++) {\n\n        ukf. reset(0, wm0, Pxx0);\n        cut4.reset(0, wm0, Pxx0);\n        cut6.reset(0, wm0, Pxx0);\n        cut8.reset(0, wm0, Pxx0);\n        house.reset(0, distx0);\n\n        cout << \"Running Trial \" << j+1 << endl;\n\n        MatrixXd T(3, steps), v(1, steps);\n        for (int k = 0; k < steps; k++) {\n            v(k) = genn();\n            T(0,k) = genw();\n            T(1,k) = genw();\n            T(2,k) = genw();\n        }\n\n        w0 = wm0;\n        w0(0) += gen0();\n        w0(1) += gen0();\n        w0(2) += gen0();\n\n        vector<VectorXd> xtruk;\n        VectorXd w = w0;\n        for (int k = 0; k < steps; k++) {\n            xtruk.push_back(w);\n            if (k < steps-1)\n                w = f(t(k), t(k+1), xtruk.back(), T.col(k));\n        }\n        xtru.push_back(xtruk);\n\n        MatrixXd Z(1, steps);\n        for (int k = 0; k < steps; k++)\n            Z.col(k) = h(t(k), xtruk[k]) + v.col(k);\n\n        cout << \"   HOUSE\" << endl;\n        timer.tick();\n        house.run(t, Z);\n        run_times(j, 0) = timer.tock();\n        vector<VectorXd> xest_house_trial;\n        for (int k = 0; k < steps; k++)\n            xest_house_trial.push_back(house.distx[k].mean);\n        xest_house.push_back(xest_house_trial);\n\n        cout << \"   UKF\" << endl;\n        timer.tick();\n        ukf.run(t, Z);\n        run_times(j, 1) = timer.tock();\n        xest_ukf.push_back(ukf.xest);\n\n        cout << \"   CUT4\" << endl;\n        timer.tick();\n        cut4.run(t, Z);\n        run_times(j, 2) = timer.tock();\n        xest_cut4.push_back(cut4.xest);\n\n        cout << \"   CUT6\" << endl;\n        timer.tick();\n        cut6.run(t, Z);\n        run_times(j, 3) = timer.tock();\n        xest_cut6.push_back(cut6.xest);\n\n        cout << \"   CUT8\" << endl;\n        timer.tick();\n        cut8.run(t, Z);\n        run_times(j, 4) = timer.tock();\n        xest_cut8.push_back(cut8.xest);\n\n    }\n\n    string dist = gauss ? \"gauss\" : \"pearson\";\n\n    save_rmse(t, xtru, xest_house, \"out/house_rmse_\" + dist + \".csv\");\n    save_rmse(t, xtru, xest_ukf,   \"out/ukf_rmse_\"   + dist + \".csv\");\n    save_rmse(t, xtru, xest_cut4,  \"out/cut4_rmse_\"  + dist + \".csv\");\n    save_rmse(t, xtru, xest_cut6,  \"out/cut6_rmse_\"  + dist + \".csv\");\n    save_rmse(t, xtru, xest_cut8,  \"out/cut8_rmse_\"  + dist + \".csv\");\n\n    save_abs_err_lump(t, xtru, xest_house, \"out/house_err_\" + dist + \".csv\");\n    save_abs_err_lump(t, xtru, xest_ukf,   \"out/ukf_err_\"   + dist + \".csv\");\n    save_abs_err_lump(t, xtru, xest_cut4,  \"out/cut4_err_\"  + dist + \".csv\");\n    save_abs_err_lump(t, xtru, xest_cut6,  \"out/cut6_err_\"  + dist + \".csv\");\n    save_abs_err_lump(t, xtru, xest_cut8,  \"out/cut8_err_\"  + dist + \".csv\");\n\n    vector<string> filters;\n    filters.push_back(\"house\");\n    filters.push_back(\"ukf\");\n    filters.push_back(\"cut4\");\n    filters.push_back(\"cut6\");\n    filters.push_back(\"cut8\");\n\n    string time_file = \"out/run_time_\";\n    time_file += dist;\n    time_file += \".csv\";\n\n    EigenCSV::write(run_times, filters, time_file);\n\n}\n\nint main() {\n\n    cout << \"--- Gaussian Distributions ---\" << endl;\n    run(true);\n\n    cout << \"--- Pearson Type IV Distributions ---\" << endl;\n    run(false);\n\n    return 0;\n\n}\n\n", "meta": {"hexsha": "0c7621817789cbf7b1a0517cafe3836afaeca3e8", "size": 6294, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rigid_body/rigid_body.cpp", "max_stars_repo_name": "SIOSlab/HOUSE", "max_stars_repo_head_hexsha": "81381a2384bd84be1afc49cace288c0606ee480f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "rigid_body/rigid_body.cpp", "max_issues_repo_name": "SIOSlab/HOUSE", "max_issues_repo_head_hexsha": "81381a2384bd84be1afc49cace288c0606ee480f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rigid_body/rigid_body.cpp", "max_forks_repo_name": "SIOSlab/HOUSE", "max_forks_repo_head_hexsha": "81381a2384bd84be1afc49cace288c0606ee480f", "max_forks_repo_licenses": ["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.0756972112, "max_line_length": 86, "alphanum_fraction": 0.5362249762, "num_tokens": 2186, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.473972958215561}}
{"text": "#include \"exception.hh\"\n#include \"network.hh\"\n#include \"timer.hh\"\n\n#include <Eigen/Dense>\n#include <iostream>\n#include <utility>\n\n#include <sys/resource.h>\n#include <sys/time.h>\n\nusing namespace std;\nusing namespace Eigen;\n\nconstexpr size_t batch_size = 1;\nconstexpr size_t input_size = 1024;\n\nvoid program_body( const unsigned int num_iterations )\n{\n  /* remove limit on stack size */\n  const rlimit limits { RLIM_INFINITY, RLIM_INFINITY };\n  CheckSystemCall( \"setrlimit\", setrlimit( RLIMIT_STACK, &limits ) );\n\n  /* seed C RNG for Eigen random weight initialization */\n  srand( Timer::timestamp_ns() );\n\n  /* construct neural network on heap */\n  // auto nn = make_unique<Network<float, batch_size, input_size, 4096, 1>>();\n  // auto nn = make_unique<Network<float, batch_size, input_size, 2048, 2048, 1>>();\n  auto nn = make_unique<Network<float, batch_size, input_size, 1024, 1024, 1024, 1024, 1024, 1024, 1024, 1>>();\n  // auto nn = make_unique<Network<float, batch_size, input_size, 5, 3, 2, 1>>();\n  nn->initializeWeightsRandomly();\n\n  /* initialize inputs */\n  vector<Matrix<float, batch_size, input_size>> inputs;\n  for ( unsigned int i = 0; i < num_iterations; i++ ) {\n    inputs.emplace_back( Matrix<float, batch_size, input_size>::Random() );\n  }\n\n  /* run forward prop benchmark */\n  const uint64_t f_start = Timer::timestamp_ns();\n  for ( unsigned int i = 0; i < num_iterations; i++ ) {\n    /* forward prop */\n    nn->apply( inputs[i] );\n  }\n  const uint64_t f_end = Timer::timestamp_ns();\n\n  /* run backprop benchmark */\n  const uint64_t b_start = Timer::timestamp_ns();\n  for ( unsigned int i = 0; i < num_iterations; i++ ) {\n    /* forward prop */\n    nn->apply( inputs[i] );\n    /* back prop*/\n    nn->computeDeltas();\n    nn->evaluateGradients( inputs[i] );\n  }\n\n  const uint64_t b_end = Timer::timestamp_ns();\n\n  cout << \"Average back propagation time (over \" << num_iterations << \" iterations, batch size=\" << batch_size\n       << \"): \";\n  Timer::pp_ns( cout, ( ( b_end - b_start ) - ( f_end - f_start ) ) / float( num_iterations ) );\n  cout << \" per iteration\\n\";\n  cout << \"Back Propagation time / forward propagation time: \"\n       << ( ( b_end - b_start ) * 1.0 / ( f_end - f_start ) - 1 ) << \" x\\n\";\n}\n\nint main( int argc, char* argv[] )\n{\n  try {\n    if ( argc <= 0 ) {\n      abort();\n    }\n\n    if ( argc != 2 ) {\n      cerr << \"Usage: \" << argv[0] << \" NUM_ITERATIONS\\n\";\n      return EXIT_FAILURE;\n    }\n\n    program_body( stoi( argv[1] ) );\n\n    return EXIT_SUCCESS;\n  } catch ( const exception& e ) {\n    cerr << e.what() << \"\\n\";\n    return EXIT_FAILURE;\n  }\n}\n", "meta": {"hexsha": "28ebf99a4b79dad41c6c2eca48ceaf15f005374c", "size": 2594, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/frontend/back_propagation.cc", "max_stars_repo_name": "stanford-stagecast/nnfun", "max_stars_repo_head_hexsha": "14300c4320b9b90b4f54d8fc49f66166a490c257", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2022-01-04T23:08:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-10T06:57:30.000Z", "max_issues_repo_path": "src/frontend/back_propagation.cc", "max_issues_repo_name": "stanford-stagecast/nnfun", "max_issues_repo_head_hexsha": "14300c4320b9b90b4f54d8fc49f66166a490c257", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/frontend/back_propagation.cc", "max_forks_repo_name": "stanford-stagecast/nnfun", "max_forks_repo_head_hexsha": "14300c4320b9b90b4f54d8fc49f66166a490c257", "max_forks_repo_licenses": ["Apache-2.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.4772727273, "max_line_length": 111, "alphanum_fraction": 0.632999229, "num_tokens": 729, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.473972958215561}}
{"text": "/*\n * Copyright 2018 Autoware Foundation. 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 * v1.0 Yukihiro Saito\n */\n\n#pragma once\n#include <autoware_perception_msgs/DynamicObjectWithFeatureArray.h>\n#include <list>\n#include <unordered_map>\n#include <vector>\n#include \"multi_object_tracker/tracker/tracker.hpp\"\n#define EIGEN_MPL2_ONLY\n#include <Eigen/Core>\n#include <Eigen/Geometry>\nclass DataAssociation\n{\nprivate:\n  double getDistance(\n    const geometry_msgs::Point & measurement, const geometry_msgs::Point & tracker);\n  Eigen::MatrixXi can_assign_matrix_;\n  Eigen::MatrixXd max_dist_matrix_;\n  Eigen::MatrixXd max_area_matrix_;\n  Eigen::MatrixXd min_area_matrix_;\n  const double score_threshold_;\n\npublic:\n  DataAssociation(\n    std::vector<int> can_assign_vector, std::vector<double> max_dist_vector,\n    std::vector<double> max_area_vector, std::vector<double> min_area_vector);\n  bool assign(\n    const Eigen::MatrixXd & src, std::unordered_map<int, int> & direct_assignment,\n    std::unordered_map<int, int> & reverse_assignment);\n  Eigen::MatrixXd calcScoreMatrix(\n    const autoware_perception_msgs::DynamicObjectWithFeatureArray & measurements,\n    const std::list<std::shared_ptr<Tracker>> & trackers);\n  virtual ~DataAssociation(){};\n};\n", "meta": {"hexsha": "fe6acb6effe988af63d1bb1f529e661d413197fc", "size": 1784, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "perception/object_recognition/tracking/multi_object_tracker/include/multi_object_tracker/data_association/data_association.hpp", "max_stars_repo_name": "hamlinzheng/AutowareArchitectureProposal.iv", "max_stars_repo_head_hexsha": "8a1343019aca3a648754fa50e6cab72b98db2df5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "perception/object_recognition/tracking/multi_object_tracker/include/multi_object_tracker/data_association/data_association.hpp", "max_issues_repo_name": "hamlinzheng/AutowareArchitectureProposal.iv", "max_issues_repo_head_hexsha": "8a1343019aca3a648754fa50e6cab72b98db2df5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2021-08-09T14:15:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-19T07:56:14.000Z", "max_forks_repo_path": "perception/object_recognition/tracking/multi_object_tracker/include/multi_object_tracker/data_association/data_association.hpp", "max_forks_repo_name": "hamlinzheng/AutowareArchitectureProposal.iv", "max_forks_repo_head_hexsha": "8a1343019aca3a648754fa50e6cab72b98db2df5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-09T01:24:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-09T01:24:13.000Z", "avg_line_length": 34.9803921569, "max_line_length": 84, "alphanum_fraction": 0.7617713004, "num_tokens": 409, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.473972958215561}}
{"text": "/*\nLICENSE: see isogeometric_application/LICENSE.txt\n*/\n\n//\n//   Project Name:        Kratos\n//   Last modified by:    $Author: hbui $\n//   Date:                $Date: Jan 9, 2013 $\n//   Revision:            $Revision: 1.1 $\n//\n//\n\n\n// System includes\n#include <string>\n\n// External includes\n#include <boost/foreach.hpp>\n#include <boost/python.hpp>\n#include <boost/python/stl_iterator.hpp>\n#include <boost/python/operators.hpp>\n\n// Project includes\n#include \"includes/define.h\"\n#include \"includes/model_part.h\"\n#include \"custom_utilities/iga_define.h\"\n#include \"custom_utilities/bspline_utils.h\"\n#include \"custom_utilities/isogeometric_post_utility.h\"\n#include \"custom_utilities/bezier_classical_post_utility.h\"\n#include \"custom_utilities/bezier_post_utility.h\"\n#include \"custom_utilities/isogeometric_test_utils.h\"\n#include \"custom_utilities/bezier_test_utils.h\"\n#include \"custom_utilities/isogeometric_merge_utility.h\"\n#include \"custom_python/add_utilities_to_python.h\"\n\n#ifdef ISOGEOMETRIC_USE_HDF5\n#include \"custom_utilities/hdf5_post_utility.h\"\n#endif\n\n#ifdef ISOGEOMETRIC_USE_GISMO\n#include \"custom_utilities/gismo/gismo_mesh.h\"\n#endif\n\nnamespace Kratos\n{\n\nnamespace Python\n{\n\nusing namespace boost::python;\n\nint BSplineUtils_FindSpan(\n    BSplineUtils& dummy,\n    const int rN,\n    const int rP,\n    const double rXi,\n    const Vector& rU\n)\n{\n    return dummy.FindSpan(rN, rP, rXi, rU);\n}\n\nvoid BSplineUtils_BasisFuns(\n    BSplineUtils& dummy,\n    Vector& rS,\n    const int rI,\n    const double rXi,\n    const int rP,\n    const Vector& rU\n)\n{\n    dummy.BasisFuns(rS, rI, rXi, rP, rU);\n}\n\nvoid BezierUtils_Bernstein(\n    BezierUtils& dummy,\n    BezierUtils::ValuesContainerType& rS,\n    const int p,\n    const double x\n)\n{\n    dummy.bernstein(rS, p, x);\n}\n\nvoid BezierUtils_Bernstein_der(\n    BezierUtils& dummy,\n    BezierUtils::ValuesContainerType& rS,\n    BezierUtils::ValuesContainerType& rD,\n    const int p,\n    const double x\n)\n{\n    dummy.bernstein(rS, rD, p, x);\n}\n\nvoid BezierUtils_DumpShapeFunctionsIntegrationPointsValuesAndLocalGradients(\n    BezierUtils& dummy,\n    ModelPart::Pointer pModelPart,\n    std::string FileName\n)\n{\n    dummy.DumpShapeFunctionsIntegrationPointsValuesAndLocalGradients(pModelPart, FileName);\n}\n\ntemplate<class T>\nvoid BezierUtils_ComputeCentroid(\n    BezierUtils& dummy,\n    typename T::Pointer& pElem,\n    typename T::GeometryType::PointType& P\n)\n{\n    dummy.ComputeCentroid<T>(pElem, P);\n}\n\ntemplate<typename TEntityType>\nvoid IsogeometricTestUtils_ProbeGlobalCoordinates1(\n    IsogeometricTestUtils& dummy,\n    typename TEntityType::Pointer pElement,\n    double X\n)\n{\n    dummy.ProbeGlobalCoordinates(pElement->GetGeometry(), X, 0.0, 0.0);\n}\n\ntemplate<typename TEntityType>\nvoid IsogeometricTestUtils_ProbeGlobalCoordinates2(\n    IsogeometricTestUtils& dummy,\n    typename TEntityType::Pointer pElement,\n    double X, double Y\n)\n{\n    dummy.ProbeGlobalCoordinates(pElement->GetGeometry(), X, Y, 0.0);\n}\n\ntemplate<typename TEntityType>\nvoid IsogeometricTestUtils_ProbeGlobalCoordinates3(\n    IsogeometricTestUtils& dummy,\n    typename TEntityType::Pointer pElement,\n    double X, double Y, double Z\n)\n{\n    dummy.ProbeGlobalCoordinates(pElement->GetGeometry(), X, Y, Z);\n}\n\ntemplate<typename TEntityType>\nvoid IsogeometricTestUtils_ProbeShapeFunctionValues1(\n    IsogeometricTestUtils& dummy,\n    typename TEntityType::Pointer pElement,\n    double X\n)\n{\n    dummy.ProbeShapeFunctionValues(pElement->GetGeometry(), X, 0.0, 0.0);\n}\n\ntemplate<typename TEntityType>\nvoid IsogeometricTestUtils_ProbeShapeFunctionValues2(\n    IsogeometricTestUtils& dummy,\n    typename TEntityType::Pointer pElement,\n    double X, double Y\n)\n{\n    dummy.ProbeShapeFunctionValues(pElement->GetGeometry(), X, Y, 0.0);\n}\n\ntemplate<typename TEntityType>\nvoid IsogeometricTestUtils_ProbeShapeFunctionValues3(\n    IsogeometricTestUtils& dummy,\n    typename TEntityType::Pointer pElement,\n    double X, double Y, double Z\n)\n{\n    dummy.ProbeShapeFunctionValues(pElement->GetGeometry(), X, Y, Z);\n}\n\ntemplate<typename TEntityType>\nvoid IsogeometricTestUtils_ProbeShapeFunctionDerivatives1(\n    IsogeometricTestUtils& dummy,\n    typename TEntityType::Pointer pElement,\n    double X\n)\n{\n    dummy.ProbeShapeFunctionDerivatives(pElement->GetGeometry(), X, 0.0, 0.0);\n}\n\ntemplate<typename TEntityType>\nvoid IsogeometricTestUtils_ProbeShapeFunctionDerivatives2(\n    IsogeometricTestUtils& dummy,\n    typename TEntityType::Pointer pElement,\n    double X, double Y\n)\n{\n    dummy.ProbeShapeFunctionDerivatives(pElement->GetGeometry(), X, Y, 0.0);\n}\n\ntemplate<typename TEntityType>\nvoid IsogeometricTestUtils_ProbeShapeFunctionDerivatives3(\n    IsogeometricTestUtils& dummy,\n    typename TEntityType::Pointer pElement,\n    double X, double Y, double Z\n)\n{\n    dummy.ProbeShapeFunctionDerivatives(pElement->GetGeometry(), X, Y, Z);\n}\n\ntemplate<typename TEntityType>\nvoid IsogeometricTestUtils_ProbeJacobian1(\n    IsogeometricTestUtils& dummy,\n    typename TEntityType::Pointer pElement,\n    double X\n)\n{\n    dummy.ProbeJacobian(pElement->GetGeometry(), X, 0.0, 0.0);\n}\n\ntemplate<typename TEntityType>\nvoid IsogeometricTestUtils_ProbeJacobian2(\n    IsogeometricTestUtils& dummy,\n    typename TEntityType::Pointer pElement,\n    double X, double Y\n)\n{\n    dummy.ProbeJacobian(pElement->GetGeometry(), X, Y, 0.0);\n}\n\ntemplate<typename TEntityType>\nvoid IsogeometricTestUtils_ProbeJacobian3(\n    IsogeometricTestUtils& dummy,\n    typename TEntityType::Pointer pElement,\n    double X, double Y, double Z\n)\n{\n    dummy.ProbeJacobian(pElement->GetGeometry(), X, Y, Z);\n}\n\ntemplate<typename TEntityType>\nvoid IsogeometricTestUtils_ProbeShapeFunctionSecondDerivatives1(\n    IsogeometricTestUtils& dummy,\n    typename TEntityType::Pointer pElement,\n    double X\n)\n{\n    dummy.ProbeShapeFunctionSecondDerivatives(pElement->GetGeometry(), X, 0.0, 0.0);\n}\n\ntemplate<typename TEntityType>\nvoid IsogeometricTestUtils_ProbeShapeFunctionSecondDerivatives2(\n    IsogeometricTestUtils& dummy,\n    typename TEntityType::Pointer pElement,\n    double X, double Y\n)\n{\n    dummy.ProbeShapeFunctionSecondDerivatives(pElement->GetGeometry(), X, Y, 0.0);\n}\n\ntemplate<typename TEntityType>\nvoid IsogeometricTestUtils_ProbeShapeFunctionSecondDerivatives3(\n    IsogeometricTestUtils& dummy,\n    typename TEntityType::Pointer pElement,\n    double X, double Y, double Z\n)\n{\n    dummy.ProbeShapeFunctionSecondDerivatives(pElement->GetGeometry(), X, Y, Z);\n}\n\ntemplate<typename TEntityType>\nvoid IsogeometricTestUtils_ProbeShapeFunctionThirdDerivatives1(\n    IsogeometricTestUtils& dummy,\n    typename TEntityType::Pointer pElement,\n    double X\n)\n{\n    dummy.ProbeShapeFunctionThirdDerivatives(pElement->GetGeometry(), X, 0.0, 0.0);\n}\n\ntemplate<typename TEntityType>\nvoid IsogeometricTestUtils_ProbeShapeFunctionThirdDerivatives2(\n    IsogeometricTestUtils& dummy,\n    typename TEntityType::Pointer pElement,\n    double X, double Y\n)\n{\n    dummy.ProbeShapeFunctionThirdDerivatives(pElement->GetGeometry(), X, Y, 0.0);\n}\n\ntemplate<typename TEntityType>\nvoid IsogeometricTestUtils_ProbeShapeFunctionThirdDerivatives3(\n    IsogeometricTestUtils& dummy,\n    typename TEntityType::Pointer pElement,\n    double X, double Y, double Z\n)\n{\n    dummy.ProbeShapeFunctionThirdDerivatives(pElement->GetGeometry(), X, Y, Z);\n}\n\n//////////////////////////////////////////////////////////\n\nModelPart::ElementsContainerType IsogeometricPostUtility_TransferElements(IsogeometricPostUtility& rDummy, ModelPart::ElementsContainerType& pElements,\n    ModelPart& r_other_model_part, const std::string& sample_element_name, Properties::Pointer pProperties, const bool& retain_prop_id)\n{\n    std::size_t last_element_id = IsogeometricPostUtility::GetLastElementId(r_other_model_part);\n    if (!KratosComponents<Element>::Has(sample_element_name))\n        KRATOS_THROW_ERROR(std::logic_error, sample_element_name, \"is not registered to the Kratos kernel\")\n    Element const& r_clone_element = KratosComponents<Element>::Get(sample_element_name);\n    ModelPart::ElementsContainerType pNewElements = IsogeometricPostUtility::CreateEntities(pElements, r_other_model_part, r_clone_element, last_element_id, pProperties, retain_prop_id);\n\n    for(ModelPart::ElementsContainerType::ptr_iterator it = pNewElements.ptr_begin(); it != pNewElements.ptr_end(); ++it)\n        r_other_model_part.Elements().push_back(*it);\n\n    std::cout << \"Transfer mesh completed, \"\n              << pNewElements.size() << \" elements of type \" << sample_element_name\n              << \" was added to model_part\" << r_other_model_part.Name() << std::endl;\n\n    return pNewElements;\n}\n\nModelPart::ConditionsContainerType IsogeometricPostUtility_TransferConditions(IsogeometricPostUtility& rDummy, ModelPart::ConditionsContainerType& pConditions,\n    ModelPart& r_other_model_part, const std::string& sample_condition_name, Properties::Pointer pProperties, const bool& retain_prop_id)\n{\n    std::size_t last_condition_id = IsogeometricPostUtility::GetLastConditionId(r_other_model_part);\n    if (!KratosComponents<Condition>::Has(sample_condition_name))\n        KRATOS_THROW_ERROR(std::logic_error, sample_condition_name, \"is not registered to the Kratos kernel\")\n    Condition const& r_clone_condition = KratosComponents<Condition>::Get(sample_condition_name);\n    ModelPart::ConditionsContainerType pNewConditions = IsogeometricPostUtility::CreateEntities(pConditions, r_other_model_part, r_clone_condition, last_condition_id, pProperties, retain_prop_id);\n\n    for(ModelPart::ConditionsContainerType::ptr_iterator it = pNewConditions.ptr_begin(); it != pNewConditions.ptr_end(); ++it)\n        r_other_model_part.Conditions().push_back(*it);\n\n    std::cout << \"Transfer mesh completed, \"\n              << pNewConditions.size() << \" conditions of type \" << sample_condition_name\n              << \" was added to model_part\" << r_other_model_part.Name() << std::endl;\n\n    return pNewConditions;\n}\n\nModelPart::ElementsContainerType IsogeometricPostUtility_FindElements(IsogeometricPostUtility& rDummy,\n    ModelPart::ElementsContainerType& pElements, const std::string& sample_element_name)\n{\n    if (!KratosComponents<Element>::Has(sample_element_name))\n        KRATOS_THROW_ERROR(std::logic_error, sample_element_name, \"is not registered to the Kratos kernel\")\n    Element const& r_clone_element = KratosComponents<Element>::Get(sample_element_name);\n    return IsogeometricPostUtility::FindEntities(pElements, r_clone_element);\n}\n\nModelPart::ConditionsContainerType IsogeometricPostUtility_FindConditions(IsogeometricPostUtility& rDummy,\n    ModelPart::ConditionsContainerType& pConditions, const std::string& sample_condition_name)\n{\n    if (!KratosComponents<Condition>::Has(sample_condition_name))\n        KRATOS_THROW_ERROR(std::logic_error, sample_condition_name, \"is not registered to the Kratos kernel\")\n    Condition const& r_clone_condition = KratosComponents<Condition>::Get(sample_condition_name);\n    return IsogeometricPostUtility::FindEntities(pConditions, r_clone_condition);\n}\n\ntemplate<typename TCoordinatesType, typename TPatchType>\nboost::python::list IsogeometricPostUtility_CreateConditionsByTriangulation(IsogeometricPostUtility& rDummy,\n    const boost::python::list& list_physical_points,\n    const Vector& center, const Vector& normal, const Vector& t1, const Vector& t2,\n    const boost::python::list& list_local_points, const std::size_t& nrefine,\n    typename TPatchType::Pointer pPatch, ModelPart& r_model_part,\n    const std::string& sample_condition_name,\n    const std::size_t& last_node_id, const std::size_t& last_condition_id,\n    Properties::Pointer pProperties)\n{\n    if (!KratosComponents<Condition>::Has(sample_condition_name))\n        KRATOS_THROW_ERROR(std::logic_error, sample_condition_name, \"is not registered to the Kratos kernel\")\n    Condition const& r_clone_condition = KratosComponents<Condition>::Get(sample_condition_name);\n\n    typedef boost::python::stl_input_iterator<array_1d<double, 3> > iterator_value_type;\n\n    std::vector<TCoordinatesType> physical_points;\n    BOOST_FOREACH(const iterator_value_type::value_type& p,\n                std::make_pair(iterator_value_type(list_physical_points), // begin\n                iterator_value_type() ) ) // end\n    {\n        physical_points.push_back(p);\n    }\n\n    std::vector<TCoordinatesType> local_points;\n    BOOST_FOREACH(const iterator_value_type::value_type& p,\n                std::make_pair(iterator_value_type(list_local_points), // begin\n                iterator_value_type() ) ) // end\n    {\n        local_points.push_back(p);\n    }\n\n    std::size_t offset = last_node_id + 1;\n    std::pair<std::vector<TCoordinatesType>, std::vector<std::vector<std::size_t> > >\n    points_and_connectivities = IsogeometricPostUtility::GenerateTriangleGrid(physical_points, center, normal, t1, t2, local_points, offset, nrefine);\n\n    boost::python::list new_nodes;\n    boost::python::list new_local_points;\n    std::size_t starting_node_id = last_node_id + 1;\n    for (std::size_t i = 0; i < points_and_connectivities.first.size(); ++i)\n    {\n        new_local_points.append(points_and_connectivities.first[i]);\n        ModelPart::NodeType::Pointer pNewNode = IsogeometricPostUtility::CreateNode(points_and_connectivities.first[i], *pPatch, r_model_part, starting_node_id++);\n        new_nodes.append(pNewNode);\n        // std::cout << \"node \" << pNewNode->Id() << \" (\" << pNewNode->X0() << \" \" << pNewNode->Y0() << \" \" << pNewNode->Z0() << \") is created at \" << points_and_connectivities.first[i] << std::endl;\n    }\n\n    // std::cout << \"connectivities:\" << std::endl;\n    // for (std::size_t i = 0; i < points_and_connectivities.second.size(); ++i)\n    // {\n    //     std::cout << \" \";\n    //     for (std::size_t j = 0; j < points_and_connectivities.second[i].size(); ++j)\n    //         std::cout << \" \" << points_and_connectivities.second[i][j];\n    //     std::cout << std::endl;\n    // }\n\n    std::size_t last_condition_id_new = last_condition_id;\n    const std::string NodeKey = std::string(\"Node\");\n    ModelPart::ConditionsContainerType pNewConditions = IsogeometricPostUtility::CreateEntities<std::vector<std::vector<std::size_t> >, Condition, ModelPart::ConditionsContainerType>(\n        points_and_connectivities.second, r_model_part, r_clone_condition, last_condition_id_new, pProperties, NodeKey);\n\n    boost::python::list output;\n    output.append(new_local_points);\n    output.append(new_nodes);\n    output.append(pNewConditions);\n    return output;\n}\n\ntemplate<typename TCoordinatesType, typename TPatchType>\nboost::python::list IsogeometricPostUtility_CreateConditionsByQuadrilateralization(IsogeometricPostUtility& rDummy,\n    const TCoordinatesType& p1, const TCoordinatesType& p2,\n    const TCoordinatesType& p3, const TCoordinatesType& p4,\n    const std::size_t& num_div_1, const std::size_t& num_div_2,\n    typename TPatchType::Pointer pPatch, ModelPart& r_model_part,\n    const std::string& sample_condition_name,\n    const std::size_t& last_node_id, const std::size_t& last_condition_id,\n    Properties::Pointer pProperties)\n{\n    if (!KratosComponents<Condition>::Has(sample_condition_name))\n        KRATOS_THROW_ERROR(std::logic_error, sample_condition_name, \"is not registered to the Kratos kernel\")\n    Condition const& r_clone_condition = KratosComponents<Condition>::Get(sample_condition_name);\n\n    std::size_t starting_node_id = last_node_id + 1;\n    std::pair<std::vector<TCoordinatesType>, std::vector<std::vector<std::size_t> > >\n    points_and_connectivities = IsogeometricPostUtility::GenerateQuadGrid(p1, p2, p3, p4, starting_node_id, num_div_1, num_div_2);\n\n    boost::python::list new_nodes;\n    boost::python::list new_local_points;\n    for (std::size_t i = 0; i < points_and_connectivities.first.size(); ++i)\n    {\n        new_local_points.append(points_and_connectivities.first[i]);\n        ModelPart::NodeType::Pointer pNewNode = IsogeometricPostUtility::CreateNode(points_and_connectivities.first[i], *pPatch, r_model_part, starting_node_id++);\n        new_nodes.append(pNewNode);\n        // std::cout << \"node \" << pNewNode->Id() << \" (\" << pNewNode->X0() << \" \" << pNewNode->Y0() << \" \" << pNewNode->Z0() << \") is created at \" << points_and_connectivities.first[i] << std::endl;\n    }\n\n    // std::cout << \"connectivities:\" << std::endl;\n    // for (std::size_t i = 0; i < points_and_connectivities.second.size(); ++i)\n    // {\n    //     std::cout << \" \";\n    //     for (std::size_t j = 0; j < points_and_connectivities.second[i].size(); ++j)\n    //         std::cout << \" \" << points_and_connectivities.second[i][j];\n    //     std::cout << std::endl;\n    // }\n\n    std::size_t last_condition_id_new = last_condition_id;\n    const std::string NodeKey = std::string(\"Node\");\n    ModelPart::ConditionsContainerType pNewConditions = IsogeometricPostUtility::CreateEntities<std::vector<std::vector<std::size_t> >, Condition, ModelPart::ConditionsContainerType>(\n        points_and_connectivities.second, r_model_part, r_clone_condition, last_condition_id_new, pProperties, NodeKey);\n\n    boost::python::list output;\n    output.append(new_local_points);\n    output.append(new_nodes);\n    output.append(pNewConditions);\n    return output;\n}\n\ntemplate<class TPatchType>\nvoid IsogeometricPostUtility_TransferValuesToNodes(IsogeometricPostUtility& rDummy, Element::GeometryType::PointType& rNode, const TPatchType& rPatch)\n{\n    rDummy.TransferValuesToNodes(rNode, rPatch);\n}\n\ntemplate<class TEntityType, typename TVariableType, class TPatchType>\nvoid IsogeometricPostUtility_TransferValuesToGaussPoints(IsogeometricPostUtility& rDummy, TEntityType& rElement,\n    const TVariableType& rVariable, const TPatchType& rPatch, const ProcessInfo& rProcessInfo)\n{\n    rDummy.TransferValuesToGaussPoints(rElement, rVariable, rPatch, rProcessInfo);\n}\n\n//////////////////////////////////////////////////////////\n\nboost::python::list BezierClassicalPostUtility_GenerateConditions(BezierClassicalPostUtility& dummy,\n        ModelPart& rModelPart,\n        Condition& rCondition,\n        const std::string& sample_condition_name,\n        const std::size_t& starting_node_id,\n        const std::size_t& starting_condition_id)\n{\n    if (!KratosComponents<Condition>::Has(sample_condition_name))\n        KRATOS_THROW_ERROR(std::logic_error, sample_condition_name, \"is not registered to the Kratos kernel\")\n    Condition const& r_clone_condition = KratosComponents<Condition>::Get(sample_condition_name);\n    std::size_t NodeCounter = starting_node_id;\n    std::size_t NodeCounter_old = NodeCounter;\n    std::size_t ConditionCounter = starting_condition_id;\n    const std::string NodeKey = std::string(\"Node\");\n    std::vector<std::size_t> node_ids;\n    std::vector<std::size_t> element_ids;\n    dummy.GenerateForOneEntity<Condition, ModelPart::ConditionsContainerType, 2>(rModelPart, rCondition,\n            r_clone_condition, NodeCounter_old, NodeCounter, ConditionCounter, NodeKey, false,\n            node_ids, element_ids, true);\n\n    boost::python::list list_nodes;\n    boost::python::list list_elements;\n    for (std::size_t i = 0; i < node_ids.size(); ++i) list_nodes.append(node_ids[i]);\n    for (std::size_t i = 0; i < element_ids.size(); ++i) list_elements.append(element_ids[i]);\n    boost::python::list Output;\n    Output.append(list_nodes);\n    Output.append(list_elements);\n    return Output;\n}\n\nboost::python::list BezierClassicalPostUtility_GenerateConditionsWithNodalVariables(BezierClassicalPostUtility& dummy,\n        ModelPart& rModelPart,\n        Condition& rCondition,\n        const std::string& sample_condition_name,\n        const std::size_t& starting_node_id,\n        const std::size_t& starting_condition_id)\n{\n    if (!KratosComponents<Condition>::Has(sample_condition_name))\n        KRATOS_THROW_ERROR(std::logic_error, sample_condition_name, \"is not registered to the Kratos kernel\")\n    Condition const& r_clone_condition = KratosComponents<Condition>::Get(sample_condition_name);\n    std::size_t NodeCounter = starting_node_id;\n    std::size_t NodeCounter_old = NodeCounter;\n    std::size_t ConditionCounter = starting_condition_id;\n    const std::string NodeKey = std::string(\"Node\");\n    std::vector<std::size_t> node_ids;\n    std::vector<std::size_t> element_ids;\n    dummy.GenerateForOneEntity<Condition, ModelPart::ConditionsContainerType, 2>(rModelPart, rCondition,\n            r_clone_condition, NodeCounter_old, NodeCounter, ConditionCounter, NodeKey, true,\n            node_ids, element_ids, true);\n\n    boost::python::list list_nodes;\n    boost::python::list list_elements;\n    for (std::size_t i = 0; i < node_ids.size(); ++i) list_nodes.append(node_ids[i]);\n    for (std::size_t i = 0; i < element_ids.size(); ++i) list_elements.append(element_ids[i]);\n    boost::python::list Output;\n    Output.append(list_nodes);\n    Output.append(list_elements);\n    return Output;\n}\n\nboost::python::list BezierClassicalPostUtility_GenerateElements(BezierClassicalPostUtility& dummy,\n        ModelPart& rModelPart,\n        Element& rElement,\n        const std::string& sample_element_name,\n        const std::size_t& starting_node_id,\n        const std::size_t& starting_element_id)\n{\n    if (!KratosComponents<Element>::Has(sample_element_name))\n        KRATOS_THROW_ERROR(std::logic_error, sample_element_name, \"is not registered to the Kratos kernel\")\n    Element const& r_clone_element = KratosComponents<Element>::Get(sample_element_name);\n    std::size_t NodeCounter = starting_node_id;\n    std::size_t NodeCounter_old = NodeCounter;\n    std::size_t ElementCounter = starting_element_id;\n    const std::string NodeKey = std::string(\"Node\");\n    std::vector<std::size_t> node_ids;\n    std::vector<std::size_t> element_ids;\n    dummy.GenerateForOneEntity<Element, ModelPart::ElementsContainerType, 2>(rModelPart, rElement,\n            r_clone_element, NodeCounter_old, NodeCounter, ElementCounter, NodeKey, false,\n            node_ids, element_ids, true);\n\n    boost::python::list list_nodes;\n    boost::python::list list_elements;\n    for (std::size_t i = 0; i < node_ids.size(); ++i) list_nodes.append(node_ids[i]);\n    for (std::size_t i = 0; i < element_ids.size(); ++i) list_elements.append(element_ids[i]);\n    boost::python::list Output;\n    Output.append(list_nodes);\n    Output.append(list_elements);\n    return Output;\n}\n\nboost::python::list BezierClassicalPostUtility_GenerateElementsWithNodalVariables(BezierClassicalPostUtility& dummy,\n        ModelPart& rModelPart,\n        Element& rElement,\n        const std::string& sample_element_name,\n        const std::size_t& starting_node_id,\n        const std::size_t& starting_element_id)\n{\n    if (!KratosComponents<Element>::Has(sample_element_name))\n        KRATOS_THROW_ERROR(std::logic_error, sample_element_name, \"is not registered to the Kratos kernel\")\n    Element const& r_clone_element = KratosComponents<Element>::Get(sample_element_name);\n    std::size_t NodeCounter = starting_node_id;\n    std::size_t NodeCounter_old = NodeCounter;\n    std::size_t ElementCounter = starting_element_id;\n    const std::string NodeKey = std::string(\"Node\");\n    std::vector<std::size_t> node_ids;\n    std::vector<std::size_t> element_ids;\n    dummy.GenerateForOneEntity<Element, ModelPart::ElementsContainerType, 2>(rModelPart, rElement,\n            r_clone_element, NodeCounter_old, NodeCounter, ElementCounter, NodeKey, true,\n            node_ids, element_ids, true);\n\n    boost::python::list list_nodes;\n    boost::python::list list_elements;\n    for (std::size_t i = 0; i < node_ids.size(); ++i) list_nodes.append(node_ids[i]);\n    for (std::size_t i = 0; i < element_ids.size(); ++i) list_elements.append(element_ids[i]);\n    boost::python::list Output;\n    Output.append(list_nodes);\n    Output.append(list_elements);\n    return Output;\n}\n\nvoid BezierClassicalPostUtility_GenerateModelPart2WithCondition(BezierClassicalPostUtility& dummy, ModelPart::Pointer pModelPartPost)\n{\n    dummy.GenerateModelPart2(pModelPartPost, true);\n}\n\nvoid BezierClassicalPostUtility_GenerateModelPart2(BezierClassicalPostUtility& dummy, ModelPart::Pointer pModelPartPost, const bool& generate_for_condition)\n{\n    dummy.GenerateModelPart2(pModelPartPost, generate_for_condition);\n}\n\n//////////////////////////////////////////////////////////\n\ntemplate<typename TVariableType>\nvoid BezierPostUtility_TransferVariablesToNodes_ModelPart(BezierPostUtility& rDummy,\n    const TVariableType& rThisVariable,\n    ModelPart& r_model_part,\n    BezierPostUtility::LinearSolverType::Pointer pSolver)\n{\n    rDummy.TransferVariablesToNodes(rThisVariable, r_model_part, pSolver);\n}\n\ntemplate<typename TVariableType>\nvoid BezierPostUtility_TransferVariablesToNodes_Elements(BezierPostUtility& rDummy,\n    const TVariableType& rThisVariable,\n    ModelPart& r_model_part, BezierPostUtility::ElementsArrayType& ElementsArray,\n    BezierPostUtility::LinearSolverType::Pointer pSolver)\n{\n    rDummy.TransferVariablesToNodes(rThisVariable, r_model_part, ElementsArray, pSolver);\n}\n\n//////////////////////////////////////////////////////////\n\nvoid IsogeometricApplication_AddBackendUtilitiesToPython()\n{\n    enum_<PostElementType>(\"PostElementType\")\n    .value(\"Triangle\", _TRIANGLE_)\n    .value(\"Quadrilateral\", _QUADRILATERAL_)\n    .value(\"Tetrahedra\", _TETRAHEDRA_)\n    .value(\"Hexahedra\", _HEXAHEDRA_)\n    ;\n\n    class_<IsogeometricEcho, boost::noncopyable>(\"IsogeometricEcho\", init<>())\n    .def(\"SetEchoLevel\", &IsogeometricEcho::SetEchoLevel)\n    // .def(\"GetEchoLevel\", IsogeometricEcho_GetEchoLevel)\n    ;\n\n    class_<BSplineUtils, BSplineUtils::Pointer, boost::noncopyable>(\"BSplineUtils\", init<>())\n    .def(\"FindSpan\", BSplineUtils_FindSpan)\n    .def(\"BasisFuns\", BSplineUtils_BasisFuns)\n    .def(\"test_ComputeBsplinesKnotInsertionCoefficients1DLocal\", &BSplineUtils::test_ComputeBsplinesKnotInsertionCoefficients1DLocal)\n    ;\n\n    class_<BezierUtils, BezierUtils::Pointer, boost::noncopyable>(\"BezierUtils\", init<>())\n    .def(\"Bernstein\", BezierUtils_Bernstein)\n    .def(\"BernsteinDerivative\", BezierUtils_Bernstein_der)\n    .def(\"DumpShapeFunctionsIntegrationPointsValuesAndLocalGradients\", BezierUtils_DumpShapeFunctionsIntegrationPointsValuesAndLocalGradients)\n    .def(\"ComputeCentroid\", BezierUtils_ComputeCentroid<Element>)\n    .def(\"ComputeCentroid\", BezierUtils_ComputeCentroid<Condition>)\n//    .def(\"compute_extended_knot_vector\", &BezierUtils::compute_extended_knot_vector)\n//    .def(\"bezier_extraction_tsplines_1d\", &BezierUtils::bezier_extraction_tsplines_1d)\n    ;\n\n    class_<IsogeometricPostUtility, IsogeometricPostUtility::Pointer, boost::noncopyable>(\"IsogeometricPostUtility\", init<>())\n    .def(\"TransferElements\", &IsogeometricPostUtility_TransferElements)\n    .def(\"TransferConditions\", &IsogeometricPostUtility_TransferConditions)\n    .def(\"TransferValuesToNodes\", &IsogeometricPostUtility_TransferValuesToNodes<Patch<2> >)\n    .def(\"TransferValuesToNodes\", &IsogeometricPostUtility_TransferValuesToNodes<Patch<2> >)\n    .def(\"TransferValuesToGaussPoints\", &IsogeometricPostUtility_TransferValuesToGaussPoints<Element, Variable<double>, Patch<2> >)\n    .def(\"TransferValuesToGaussPoints\", &IsogeometricPostUtility_TransferValuesToGaussPoints<Element, Variable<array_1d<double, 3> >, Patch<2> >)\n    .def(\"TransferValuesToGaussPoints\", &IsogeometricPostUtility_TransferValuesToGaussPoints<Element, Variable<Vector>, Patch<2> >)\n    .def(\"TransferValuesToGaussPoints\", &IsogeometricPostUtility_TransferValuesToGaussPoints<Element, Variable<double>, Patch<3> >)\n    .def(\"TransferValuesToGaussPoints\", &IsogeometricPostUtility_TransferValuesToGaussPoints<Element, Variable<array_1d<double, 3> >, Patch<3> >)\n    .def(\"TransferValuesToGaussPoints\", &IsogeometricPostUtility_TransferValuesToGaussPoints<Element, Variable<Vector>, Patch<3> >)\n    .def(\"FindElements\", &IsogeometricPostUtility_FindElements)\n    .def(\"FindConditions\", &IsogeometricPostUtility_FindConditions)\n    .def(\"CreateConditions\", &IsogeometricPostUtility_CreateConditionsByTriangulation<array_1d<double, 3>, Patch<3> >)\n    .def(\"CreateConditions\", &IsogeometricPostUtility_CreateConditionsByQuadrilateralization<Vector, Patch<3> >)\n    .def(\"CreateConditions\", &IsogeometricPostUtility_CreateConditionsByQuadrilateralization<array_1d<double, 3>, Patch<3> >)\n    ;\n\n    class_<BezierClassicalPostUtility, BezierClassicalPostUtility::Pointer, boost::noncopyable>(\"BezierClassicalPostUtility\", init<ModelPart::Pointer>())\n    .def(\"GenerateConditions\", &BezierClassicalPostUtility_GenerateConditions)\n    .def(\"GenerateConditionsWithNodalVariables\", &BezierClassicalPostUtility_GenerateConditionsWithNodalVariables)\n    .def(\"GenerateElements\", &BezierClassicalPostUtility_GenerateElements)\n    .def(\"GenerateElementsWithNodalVariables\", &BezierClassicalPostUtility_GenerateElementsWithNodalVariables)\n    .def(\"GenerateModelPart\", &BezierClassicalPostUtility::GenerateModelPart)\n    .def(\"GenerateModelPart2\", &BezierClassicalPostUtility_GenerateModelPart2WithCondition)\n    .def(\"GenerateModelPart2\", &BezierClassicalPostUtility_GenerateModelPart2)\n    .def(\"GenerateModelPart2AutoCollapse\", &BezierClassicalPostUtility::GenerateModelPart2AutoCollapse)\n    .def(\"TransferNodalResults\", &BezierClassicalPostUtility::TransferNodalResults<Variable<double> >)\n    .def(\"TransferNodalResults\", &BezierClassicalPostUtility::TransferNodalResults<Variable<Vector> >)\n    .def(\"TransferNodalResults\", &BezierClassicalPostUtility::TransferNodalResults<Variable<array_1d<double, 3> > >)\n    .def(\"TransferIntegrationPointResults\", &BezierClassicalPostUtility::TransferIntegrationPointResults<Variable<double> >)\n    .def(\"TransferIntegrationPointResults\", &BezierClassicalPostUtility::TransferIntegrationPointResults<Variable<Vector> >)\n    .def(\"SynchronizeActivation\", &BezierClassicalPostUtility::SynchronizeActivation)\n    .def(\"TransferElementalData\", &BezierClassicalPostUtility::TransferElementalData<Variable<bool> >)\n    .def(\"TransferConditionalData\", &BezierClassicalPostUtility::TransferConditionalData<Variable<bool> >)\n    .def(\"TransferVariablesToNodes\", &BezierClassicalPostUtility::TransferVariablesToNodes<Variable<double> >)\n    .def(\"TransferVariablesToNodes\", &BezierClassicalPostUtility::TransferVariablesToNodes<Variable<Vector> >)\n    .def(\"GlobalNodalRenumbering\", &BezierClassicalPostUtility::GlobalNodalRenumbering)\n    ;\n\n    class_<BezierPostUtility, BezierPostUtility::Pointer, boost::noncopyable>(\"BezierPostUtility\", init<>())\n    .def(\"TransferNodalResults\", &BezierPostUtility::TransferNodalResults<Variable<double> >)\n    .def(\"TransferNodalResults\", &BezierPostUtility::TransferNodalResults<Variable<Vector> >)\n    .def(\"TransferNodalResults\", &BezierPostUtility::TransferNodalResults<Variable<array_1d<double, 3> > >)\n    .def(\"TransferIntegrationPointResults\", &BezierPostUtility::TransferIntegrationPointResults<Variable<double> >)\n    .def(\"TransferIntegrationPointResults\", &BezierPostUtility::TransferIntegrationPointResults<Variable<Vector> >)\n    .def(\"TransferIntegrationPointResults\", &BezierPostUtility::TransferIntegrationPointResults<Variable<array_1d<double, 3>> >)\n    .def(\"TransferVariablesToNodes\", &BezierPostUtility_TransferVariablesToNodes_ModelPart<Variable<double> >)\n    .def(\"TransferVariablesToNodes\", &BezierPostUtility_TransferVariablesToNodes_ModelPart<Variable<Vector> >)\n    .def(\"TransferVariablesToNodes\", &BezierPostUtility_TransferVariablesToNodes_ModelPart<Variable<array_1d<double, 3>> >)\n    .def(\"TransferVariablesToNodes\", &BezierPostUtility_TransferVariablesToNodes_Elements<Variable<double> >)\n    .def(\"TransferVariablesToNodes\", &BezierPostUtility_TransferVariablesToNodes_Elements<Variable<Vector> >)\n    .def(\"TransferVariablesToNodes\", &BezierPostUtility_TransferVariablesToNodes_Elements<Variable<array_1d<double, 3>> >)\n    ;\n\n    #ifdef ISOGEOMETRIC_USE_HDF5\n    class_<HDF5PostUtility, HDF5PostUtility::Pointer, boost::noncopyable>(\"HDF5PostUtility\", init<const std::string>())\n    .def(init<const std::string, const std::string>())\n    .def(\"WriteNodes\", &HDF5PostUtility::WriteNodes)\n    .def(\"WriteNodalResults\", &HDF5PostUtility::WriteNodalResults<double>)\n    .def(\"WriteNodalResults\", &HDF5PostUtility::WriteNodalResults<array_1d<double, 3> >)\n    .def(\"WriteNodalResults\", &HDF5PostUtility::WriteNodalResults<Vector>)\n    .def(\"WriteElementalData\", &HDF5PostUtility::WriteElementalData<bool>)\n    .def(\"ReadNodalResults\", &HDF5PostUtility::ReadNodalResults<double>)\n    .def(\"ReadNodalResults\", &HDF5PostUtility::ReadNodalResults<array_1d<double, 3> >)\n    .def(\"ReadNodalResults\", &HDF5PostUtility::ReadNodalResults<Vector>)\n    .def(\"ReadElementalData\", &HDF5PostUtility::ReadElementalData<bool>)\n    ;\n    #endif\n\n    class_<IsogeometricTestUtils, IsogeometricTestUtils::Pointer, boost::noncopyable>(\"IsogeometricTestUtils\", init<>())\n    .def(\"Test1\", &IsogeometricTestUtils::Test1)\n    .def(\"Test2\", &IsogeometricTestUtils::Test2)\n    .def(\"ProbeGlobalCoordinates\", &IsogeometricTestUtils_ProbeGlobalCoordinates1<Element>)\n    .def(\"ProbeGlobalCoordinates\", &IsogeometricTestUtils_ProbeGlobalCoordinates1<Condition>)\n    .def(\"ProbeGlobalCoordinates\", &IsogeometricTestUtils_ProbeGlobalCoordinates2<Element>)\n    .def(\"ProbeGlobalCoordinates\", &IsogeometricTestUtils_ProbeGlobalCoordinates2<Condition>)\n    .def(\"ProbeGlobalCoordinates\", &IsogeometricTestUtils_ProbeGlobalCoordinates3<Element>)\n    .def(\"ProbeGlobalCoordinates\", &IsogeometricTestUtils_ProbeGlobalCoordinates3<Condition>)\n    .def(\"ProbeShapeFunctionValues\", &IsogeometricTestUtils_ProbeShapeFunctionValues1<Element>)\n    .def(\"ProbeShapeFunctionValues\", &IsogeometricTestUtils_ProbeShapeFunctionValues1<Condition>)\n    .def(\"ProbeShapeFunctionValues\", &IsogeometricTestUtils_ProbeShapeFunctionValues2<Element>)\n    .def(\"ProbeShapeFunctionValues\", &IsogeometricTestUtils_ProbeShapeFunctionValues2<Condition>)\n    .def(\"ProbeShapeFunctionValues\", &IsogeometricTestUtils_ProbeShapeFunctionValues3<Element>)\n    .def(\"ProbeShapeFunctionValues\", &IsogeometricTestUtils_ProbeShapeFunctionValues3<Condition>)\n    .def(\"ProbeShapeFunctionDerivatives\", &IsogeometricTestUtils_ProbeShapeFunctionDerivatives1<Element>)\n    .def(\"ProbeShapeFunctionDerivatives\", &IsogeometricTestUtils_ProbeShapeFunctionDerivatives1<Condition>)\n    .def(\"ProbeShapeFunctionDerivatives\", &IsogeometricTestUtils_ProbeShapeFunctionDerivatives2<Element>)\n    .def(\"ProbeShapeFunctionDerivatives\", &IsogeometricTestUtils_ProbeShapeFunctionDerivatives2<Condition>)\n    .def(\"ProbeShapeFunctionDerivatives\", &IsogeometricTestUtils_ProbeShapeFunctionDerivatives3<Element>)\n    .def(\"ProbeShapeFunctionDerivatives\", &IsogeometricTestUtils_ProbeShapeFunctionDerivatives3<Condition>)\n    .def(\"ProbeShapeFunctionSecondDerivatives\", &IsogeometricTestUtils_ProbeShapeFunctionSecondDerivatives1<Element>)\n    .def(\"ProbeShapeFunctionSecondDerivatives\", &IsogeometricTestUtils_ProbeShapeFunctionSecondDerivatives1<Condition>)\n    .def(\"ProbeShapeFunctionSecondDerivatives\", &IsogeometricTestUtils_ProbeShapeFunctionSecondDerivatives2<Element>)\n    .def(\"ProbeShapeFunctionSecondDerivatives\", &IsogeometricTestUtils_ProbeShapeFunctionSecondDerivatives2<Condition>)\n    .def(\"ProbeShapeFunctionSecondDerivatives\", &IsogeometricTestUtils_ProbeShapeFunctionSecondDerivatives3<Element>)\n    .def(\"ProbeShapeFunctionSecondDerivatives\", &IsogeometricTestUtils_ProbeShapeFunctionSecondDerivatives3<Condition>)\n    .def(\"ProbeShapeFunctionThirdDerivatives\", &IsogeometricTestUtils_ProbeShapeFunctionThirdDerivatives1<Element>)\n    .def(\"ProbeShapeFunctionThirdDerivatives\", &IsogeometricTestUtils_ProbeShapeFunctionThirdDerivatives1<Condition>)\n    .def(\"ProbeShapeFunctionThirdDerivatives\", &IsogeometricTestUtils_ProbeShapeFunctionThirdDerivatives2<Element>)\n    .def(\"ProbeShapeFunctionThirdDerivatives\", &IsogeometricTestUtils_ProbeShapeFunctionThirdDerivatives2<Condition>)\n    .def(\"ProbeShapeFunctionThirdDerivatives\", &IsogeometricTestUtils_ProbeShapeFunctionThirdDerivatives3<Element>)\n    .def(\"ProbeShapeFunctionThirdDerivatives\", &IsogeometricTestUtils_ProbeShapeFunctionThirdDerivatives3<Condition>)\n    .def(\"ProbeJacobian\", &IsogeometricTestUtils_ProbeJacobian1<Element>)\n    .def(\"ProbeJacobian\", &IsogeometricTestUtils_ProbeJacobian1<Condition>)\n    .def(\"ProbeJacobian\", &IsogeometricTestUtils_ProbeJacobian2<Element>)\n    .def(\"ProbeJacobian\", &IsogeometricTestUtils_ProbeJacobian2<Condition>)\n    .def(\"ProbeJacobian\", &IsogeometricTestUtils_ProbeJacobian3<Element>)\n    .def(\"ProbeJacobian\", &IsogeometricTestUtils_ProbeJacobian3<Condition>)\n    .def(\"DumpNodalValues\", &IsogeometricTestUtils::DumpNodalValues<double>)\n    .def(\"DumpNodalValues\", &IsogeometricTestUtils::DumpNodalValues<array_1d<double, 3> >)\n    .def(\"DumpNodalValues\", &IsogeometricTestUtils::DumpNodalValues<Vector>)\n    ;\n\n    class_<IsogeometricMergeUtility, IsogeometricMergeUtility::Pointer, boost::noncopyable>(\n        \"IsogeometricMergeUtility\", init<>())\n    .def(\"Add\", &IsogeometricMergeUtility::Add)\n    .def(\"Export\", &IsogeometricMergeUtility::Export)\n    .def(\"DumpNodalVariablesList\", &IsogeometricMergeUtility::DumpNodalVariablesList)\n    ;\n\n    /////////////////////////////////////////////////////////////////\n    ///////////////////////GISMO/////////////////////////////////////\n    /////////////////////////////////////////////////////////////////\n\n    #ifdef ISOGEOMETRIC_USE_GISMO\n    class_<GismoMesh, GismoMesh::Pointer, boost::noncopyable>\n    (\"GismoMesh\", init<std::string>())\n    .def(\"SetEchoLevel\", &GismoMesh::SetEchoLevel)\n    .def(\"ReadMesh\", &GismoMesh::ReadMesh)\n    .def(self_ns::str(self))\n    ;\n    #endif\n\n}\n\n}  // namespace Python.\n\n} // Namespace Kratos\n\n", "meta": {"hexsha": "d52861683c6035aebd9bdcc71d5edcb57905f1c3", "size": 37693, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "custom_python/add_backend_utilities_to_python.cpp", "max_stars_repo_name": "rwilliams01/isogeometric_application", "max_stars_repo_head_hexsha": "e505061603b56b4f426220946da5ec551dc6c142", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "custom_python/add_backend_utilities_to_python.cpp", "max_issues_repo_name": "rwilliams01/isogeometric_application", "max_issues_repo_head_hexsha": "e505061603b56b4f426220946da5ec551dc6c142", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "custom_python/add_backend_utilities_to_python.cpp", "max_forks_repo_name": "rwilliams01/isogeometric_application", "max_forks_repo_head_hexsha": "e505061603b56b4f426220946da5ec551dc6c142", "max_forks_repo_licenses": ["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.70755886, "max_line_length": 199, "alphanum_fraction": 0.757753429, "num_tokens": 9441, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928951399099, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.4739729551078519}}
{"text": "#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE matrix\n#include <boost/test/unit_test.hpp>\n\n#include \"../include/matrix.hpp\"\n\nBOOST_AUTO_TEST_CASE(matrix_)\n{\n    auto m = matrix{{{ 1,0,0\n                     , 0,1,0\n                     , 0,0,1 }}};\n\n    BOOST_CHECK_EQUAL(m.value(0,0), 1);\n    BOOST_CHECK_EQUAL(m.value(0,1), 0);\n    BOOST_CHECK_EQUAL(m.value(0,2), 0);\n\n    BOOST_CHECK_EQUAL(m.value(1,0), 0);\n    BOOST_CHECK_EQUAL(m.value(1,1), 1);\n    BOOST_CHECK_EQUAL(m.value(1,2), 0);\n\n    BOOST_CHECK_EQUAL(m.value(2,0), 0);\n    BOOST_CHECK_EQUAL(m.value(2,1), 0);\n    BOOST_CHECK_EQUAL(m.value(2,2), 1);\n}\n\nBOOST_AUTO_TEST_CASE(addition)\n{\n    auto m0 = matrix{{{ 1,2,3\n                      , 4,5,6\n                      , 7,8,9 }}};\n    auto m1 = matrix{{{ 9,8,7\n                      , 6,5,4\n                      , 3,2,1 }}};\n\n    auto exp = m0 + m1;\n    matrix m = exp;\n\n    for (int i = 0; i != 3; ++i)\n    {\n        for (int j = 0; j != 3; ++j)\n        {\n            BOOST_CHECK_EQUAL(exp.value(i,j), 10);\n            BOOST_CHECK_EQUAL(m.value(i,j), 10);\n        }\n    }\n\n    auto exp2 = m0 + m1;\n    auto exp3 = exp + exp2;\n\n    for (int i = 0; i != 3; ++i)\n    {\n        for (int j = 0; j != 3; ++j)\n        {\n            BOOST_CHECK_EQUAL(exp3.value(i,j), 20);\n        }\n    }\n}\n", "meta": {"hexsha": "5afb10d51b16d71ebac204a1eb04549ea96c6e8e", "size": 1304, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "expression-templates/test/matrix.cpp", "max_stars_repo_name": "crazy-eddie/crazycpp", "max_stars_repo_head_hexsha": "d775042c98926b54e1faf24cbb32a8c390f4e86c", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-02-28T02:42:34.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-19T14:49:18.000Z", "max_issues_repo_path": "expression-templates/test/matrix.cpp", "max_issues_repo_name": "crazy-eddie/crazycpp", "max_issues_repo_head_hexsha": "d775042c98926b54e1faf24cbb32a8c390f4e86c", "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": "expression-templates/test/matrix.cpp", "max_forks_repo_name": "crazy-eddie/crazycpp", "max_forks_repo_head_hexsha": "d775042c98926b54e1faf24cbb32a8c390f4e86c", "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.4827586207, "max_line_length": 51, "alphanum_fraction": 0.486196319, "num_tokens": 427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410572017153, "lm_q2_score": 0.7122321903471562, "lm_q1q2_score": 0.47392682918793105}}
{"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_REMQUO_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_REMQUO_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n    @ingroup group-arithmetic\n\n    This function object  computes the remainder (rem) and a part of the quotient (quo) upon\n    division of @c x by @c y. By design, the value of the remainder is the same as that\n    computed by the @ref rem standard function. The value of the computed quotient has\n    the sign of @c x/y and agrees with the actual quotient in at least the low\n    order 3 bits.\n\n\n    @par Header <boost/simd/function/remquo.hpp>\n\n    @par semantic:\n\n    If T is the common type to @c x and @c y\n\n    @code\n      std::pair< T, as_integer_t<T> > p = remquo(x, y);\n    @endcode\n\n    computes the two values.\n\n    @par Note\n\n      - This function mimics a standard C library one that was mainly written in its time to\n        help computation of periodic trigonometric functions: three bits of @c quo allowing\n        to know the 'octant'\n\n      - This implementation differs from std::remquo as the quotient is not returned as a\n        pointer, and his type is not int but the signed integer type associated to the floating\n        one, to allow proper SIMD implementation.\n\n      - also note that the double implementation of std::remquo is flawed in GNU C\n        Library until version 2.21 (2.22 has been corrected).\n\n    @par Example:\n\n      @snippet remquo.cpp remquo\n\n    @par Possible output:\n\n      @snippet remquo.txt remquo\n\n  **/\n  std::pair<IEEEValue, as_integer_t<IEEEValue>> remquo(IEEEValue const& x, IEEEValue const& y);\n} }\n#endif\n\n#include <boost/simd/function/scalar/remquo.hpp>\n#include <boost/simd/function/simd/remquo.hpp>\n\n#endif\n", "meta": {"hexsha": "1f72f529eb60f958840ad9ec75ec99e2d33fc180", "size": 2128, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/remquo.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/remquo.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/remquo.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": 30.4, "max_line_length": 100, "alphanum_fraction": 0.6390977444, "num_tokens": 489, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321964553657, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.47392682852661694}}
{"text": "\n/* Test program to test find functions of triagular matrices\n *\n * author: Gunter Winkler ( guwi17 at gmx dot de )\n */\n\n\n// ublas headers\n\n#include <boost/numeric/ublas/experimental/sparse_view.hpp>\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_sparse.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n#include <boost/numeric/ublas/traits/c_array.hpp>\n\n// other boost headers\n\n// headers for testcase\n\n#define BOOST_TEST_MODULE SparseMatrixErasureTest\n#include <boost/test/included/unit_test.hpp>\n\n// standard and system headers\n\n#include <iostream>\n#include <string>\n\nnamespace ublas = boost::numeric::ublas;\n\n    /*\n      sparse input matrix:\n\n      1 2 0 0\n      0 3 9 0\n      0 1 4 0\n    */\n\n    static const std::string inputMatrix = \"[3,4]((1,2,0,0),(0,3,9,0),(0,1,4,0))\\n\";\n\n    const unsigned int NNZ  = 6;\n    const unsigned int IB   = 1;\n    const double VA[]       = { 1.0, 2.0, 3.0, 9.0, 1.0, 4.0 };\n    const unsigned int IA[] = { 1, 3, 5, 7 };\n    const unsigned int JA[] = { 1, 2, 2, 3, 2, 3 };\n\nBOOST_AUTO_TEST_CASE( test_construction_and_basic_operations )\n{\n\n    typedef ublas::matrix<double> DENSE_MATRIX;\n    \n    // prepare data\n\n    DENSE_MATRIX A;\n\n    std::istringstream iss(inputMatrix);\n    iss >> A;\n\n    std::cout << A << std::endl;\n\n    std::cout << ( ublas::make_compressed_matrix_view<ublas::row_major,IB>(3,4,NNZ,IA,JA,VA) ) << std::endl;\n\n    typedef ublas::compressed_matrix_view<ublas::row_major, IB, unsigned int [4], unsigned int [NNZ], double[NNZ]> COMPMATVIEW;\n\n    COMPMATVIEW viewA(3,4,NNZ,IA,JA,VA);\n\n    std::cout << viewA << std::endl;\n\n}\n\n\n\nBOOST_AUTO_TEST_CASE( test_construction_from_pointers )\n{\n\n    std::cout << ( ublas::make_compressed_matrix_view<ublas::column_major,IB>(4,3,NNZ\n                                                                              , ublas::c_array_view<const unsigned int>(4,&(IA[0]))\n                                                                              , ublas::c_array_view<const unsigned int>(6,&(JA[0]))\n                                                                              , ublas::c_array_view<const double>(6,&(VA[0]))) ) << std::endl;\n\n    unsigned int * ia = new unsigned int[4]();\n    unsigned int * ja = new unsigned int[6]();\n    double * va = new double[6]();\n\n    std::copy(&(IA[0]),&(IA[4]),ia);\n    std::copy(&(JA[0]),&(JA[6]),ja);\n    std::copy(&(VA[0]),&(VA[6]),va);\n\n    typedef ublas::compressed_matrix_view<ublas::column_major\n      , IB\n      , ublas::c_array_view<unsigned int>\n      , ublas::c_array_view<unsigned int>\n      , ublas::c_array_view<double> > COMPMATVIEW;\n\n    COMPMATVIEW viewA(4,3,NNZ\n                      , ublas::c_array_view<unsigned int>(4,ia)\n                      , ublas::c_array_view<unsigned int>(6,ja)\n                      , ublas::c_array_view<double>(6,va));\n\n    std::cout << viewA << std::endl;\n\n    delete[] va;\n    delete[] ja;\n    delete[] ia;\n\n}\n", "meta": {"hexsha": "ce4602c6d37b92315ee5333954179deab60f2a97", "size": 2930, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/numeric/ublas/test/sparse_view_test.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2016-04-12T16:29:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-28T11:01:57.000Z", "max_issues_repo_path": "boost/libs/numeric/ublas/test/sparse_view_test.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-10-31T19:35:14.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-04T17:11:27.000Z", "max_forks_repo_path": "boost/libs/numeric/ublas/test/sparse_view_test.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-09-09T02:38:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-30T00:24:24.000Z", "avg_line_length": 27.1296296296, "max_line_length": 142, "alphanum_fraction": 0.5788395904, "num_tokens": 854, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321964553657, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.4739268190750541}}
{"text": "#include <deal.II/base/logstream.h>\n#include <deal.II/base/parameter_handler.h>\n#include <fstream>\n#include <step_50.h>\n\nusing namespace dealii;\nusing namespace Step50;\n\ntemplate <int dim>\nclass Test_LaplaceProblem : public Step50::LaplaceProblem<dim>\n{\n  protected:\n    using Step50::LaplaceProblem<dim>::read_lammps_input_file;\n    using Step50::LaplaceProblem<dim>::refine_grid;\n    using Step50::LaplaceProblem<dim>::setup_system;\n    using Step50::LaplaceProblem<dim>::rhs_assembly_optimization;\n    using Step50::LaplaceProblem<dim>::assemble_system;\n    void charge_density_test(const std::vector<Point<dim> > & , double * ,\n                             const std::map<typename parallel::distributed::Triangulation<dim>::cell_iterator, std::set<unsigned int> > &, bool & );\n\n    const unsigned int degree;\n    ParameterHandler &prm;\n    unsigned int number_of_global_refinement , number_of_adaptive_refinement_cycles;\n    double domain_size_left , domain_size_right;\n    std::string Problemtype, PreconditionerType, LammpsInputFilename;\n    double r_c, nonzero_density_radius_parameter;\n\n  public:\n    Test_LaplaceProblem (const unsigned int Degree , ParameterHandler &prm,\n                         std::string &Problemtype, std::string &PreconditionerType, std::string &LammpsInputFile,\n                         double &domain_size_left, double &domain_size_right, unsigned int &number_of_global_refinement, unsigned int &number_of_adaptive_refinement_cycles,\n                         double &r_c, double &nonzero_density_radius_parameter) : Step50::LaplaceProblem<dim> (Degree , prm ,Problemtype, PreconditionerType, LammpsInputFile,\n                                                                                                               domain_size_left, domain_size_right, number_of_global_refinement,\n                                                                                                               number_of_adaptive_refinement_cycles, r_c, nonzero_density_radius_parameter),\n        degree(Degree),\n        prm(prm),\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        Problemtype(Problemtype),\n        PreconditionerType(PreconditionerType),\n        LammpsInputFilename(LammpsInputFile),\n        r_c(r_c),\n        nonzero_density_radius_parameter(nonzero_density_radius_parameter)\n    { }\n\n    void run (bool &);\n    ~Test_LaplaceProblem(){}\n\n};\n\ntemplate class Test_LaplaceProblem<2>;\ntemplate class Test_LaplaceProblem<3>;\n\ntemplate <int dim>\nvoid Test_LaplaceProblem<dim>::run(bool &flag_rhs_assembly)\n{\n    Timer timer;\n    Step50::LaplaceProblem<dim>::flag_rhs_assembly = flag_rhs_assembly;\n    Step50::LaplaceProblem<dim>::read_lammps_input_file(LammpsInputFilename);\n    for (unsigned int cycle=0; cycle<number_of_adaptive_refinement_cycles; ++cycle)\n        // first mesh size 4^2 = 16*16*16 and then 2 refinements\n    {\n        timer.start();\n\n        Step50::LaplaceProblem<dim>::pcout << \"Cycle \" << cycle << ':' << std::endl;\n\n        if (cycle == 0)\n        {\n            GridGenerator::hyper_cube (Step50::LaplaceProblem<dim>::triangulation,domain_size_left,domain_size_right);\n\n            Step50::LaplaceProblem<dim>::triangulation.refine_global (number_of_global_refinement);  //eg. first mesh size 4^2 = 16*16*16\n        }\n        else\n            Step50::LaplaceProblem<dim>::refine_grid ();\n\n        Step50::LaplaceProblem<dim>::pcout << \"   Number of active cells:       \"<< Step50::LaplaceProblem<dim>::triangulation.n_global_active_cells() << std::endl;\n\n        Step50::LaplaceProblem<dim>::setup_system ();\n\n        Step50::LaplaceProblem<dim>::pcout << \"   Number of degrees of freedom: \" << Step50::LaplaceProblem<dim>::mg_dof_handler.n_dofs() << \" (by level: \";\n        for (unsigned int level=0; level<Step50::LaplaceProblem<dim>::triangulation.n_global_levels(); ++level)\n            Step50::LaplaceProblem<dim>::pcout << Step50::LaplaceProblem<dim>::mg_dof_handler.n_dofs(level) << (level == Step50::LaplaceProblem<dim>::triangulation.n_global_levels()-1 ? \")\" : \", \");\n        Step50::LaplaceProblem<dim>::pcout << std::endl;\n\n        if(flag_rhs_assembly != 0)\n            Step50::LaplaceProblem<dim>::rhs_assembly_optimization(Step50::LaplaceProblem<dim>::atom_positions);\n\n        Step50::LaplaceProblem<dim>::assemble_system (Step50::LaplaceProblem<dim>::atom_positions, Step50::LaplaceProblem<dim>::charges, Step50::LaplaceProblem<dim>::charges_list_for_each_cell\n                                                      ,flag_rhs_assembly);\n        charge_density_test(Step50::LaplaceProblem<dim>::atom_positions, Step50::LaplaceProblem<dim>::charges, Step50::LaplaceProblem<dim>::charges_list_for_each_cell\n        ,flag_rhs_assembly);\n\n        timer.stop();\n        //std::cout << \"   Elapsed CPU time: \" << timer() << \" seconds.\"<<std::endl;\n        //std::cout << \"   Elapsed wall time: \" << timer.wall_time() << \" seconds.\"<<std::endl;\n        timer.reset();\n\n        // Print the charges densities i.e. system rhs norms to compare with rhs optimization\n        Step50::LaplaceProblem<dim>::pcout << \"   L2 rhs norm \" << std::setprecision(10) << std::scientific << Step50::LaplaceProblem<dim>::system_rhs.l2_norm() << std::endl;\n        Step50::LaplaceProblem<dim>::pcout << \"   LInfinity rhs norm \" << std::setprecision(10) << std::scientific << Step50::LaplaceProblem<dim>::system_rhs.linfty_norm() << std::endl;\n    }\n}\n\n//Integrate for each cell the charge density for associated atom list\n//Add all cell contribution charge sensities to check if some error due to rhs assembly optimization\n//Ideally we consider Charge neutral system\ntemplate <int dim>\nvoid Test_LaplaceProblem<dim>::charge_density_test(const std::vector<Point<dim> > & atom_positions, double * charges,\n                                                   const std::map<typename parallel::distributed::Triangulation<dim>::cell_iterator, std::set<unsigned int> > &charges_list_for_each_cell\n                                                   , bool & flag_rhs_assembly)\n{\n    const QGauss<dim>  quadrature_formula(degree+1);\n\n    FEValues<dim> fe_values (Step50::LaplaceProblem<dim>::fe, quadrature_formula,\n                             update_values    |  update_gradients |\n                             update_quadrature_points  |  update_JxW_values);\n\n    const unsigned int   dofs_per_cell = Step50::LaplaceProblem<dim>::fe.dofs_per_cell;\n    const unsigned int   n_q_points    = quadrature_formula.size();\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    std::vector<double>    coefficient_values (n_q_points);\n    std::vector<double>    density_values (n_q_points);\n\n    double r = 0.0, r_squared = 0.0;\n    const double r_c_squared_inverse = 1.0 / (r_c * r_c);\n\n    const double constant_value = 4.0 * (numbers::PI)  / (std::pow(r_c, 3) * std::pow(numbers::PI, 1.5));\n\n    std::set<unsigned int> set_atom_indices;\n    typedef LA::MPI::Vector vector_t;\n    vector_t total_charge_densities;\n    total_charge_densities.reinit(Step50::LaplaceProblem<dim>::mg_dof_handler.locally_owned_dofs(), MPI_COMM_WORLD);\n\n    typename DoFHandler<dim>::active_cell_iterator\n    cell = Step50::LaplaceProblem<dim>::mg_dof_handler.begin_active(),\n    endc = Step50::LaplaceProblem<dim>::mg_dof_handler.end();\n    for (; cell!=endc; ++cell)\n        if (cell->is_locally_owned())\n        {\n            cell_rhs = 0;\n\n            fe_values.reinit (cell);\n\n            Step50::LaplaceProblem<dim>::coeff_func->value_list (fe_values.get_quadrature_points(),\n                                    coefficient_values);\n\n                    const std::vector<Point<dim> > & quadrature_points = fe_values.get_quadrature_points();\n                    set_atom_indices =  charges_list_for_each_cell.at(cell);\n\n                    for(unsigned int q_points = 0; q_points < n_q_points; ++q_points)\n                        {\n                            density_values[q_points] = 0.0;\n                                {\n                                //With rhs assembly optimization\n                                //If flag != 0 iterate only over the neighouring atoms and apply rhs optimization\n                                if(flag_rhs_assembly != 0)\n                                    {\n                                            for(const auto & a : set_atom_indices)\n                                            {\n                                                //std::cout<< *iter << \" \";\n                                                r = 0.0;\n                                                r_squared = 0.0;\n\n                                                const Point<dim> Xi = atom_positions[a];\n                                                r = Xi.distance(quadrature_points[q_points]);\n                                                r_squared = r * r;\n\n                                                density_values[q_points] +=  constant_value *\n                                                                             exp(-r_squared * r_c_squared_inverse) *\n                                                                             charges[a];\n                                            }\n                                    }\n                                //Without optimization\n                                //If flag == 0 iterate over all the atoms in the domain, i.e. do not optimize the assembly\n                                if(flag_rhs_assembly == 0)\n                                    {\n                                        for(unsigned int k = 0; k < atom_positions.size(); ++k)\n                                            {\n                                                r = 0.0;\n                                                r_squared = 0.0;\n\n                                                const Point<dim> Xi = atom_positions[k];\n                                                r = Xi.distance(quadrature_points[q_points]);\n                                                r_squared = r * r;\n\n                                                density_values[q_points] +=  constant_value *\n                                                        exp(-r_squared * r_c_squared_inverse) *\n                                                        charges[k];\n                                            }\n                                    }\n                                }\n                        }\n                    set_atom_indices.clear();\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                        cell_rhs(i) += (density_values[q_point]* fe_values.JxW(q_point));\n                }\n\n            cell->get_dof_indices (local_dof_indices);\n            Step50::LaplaceProblem<dim>::constraints.distribute_local_to_global (cell_rhs, local_dof_indices, total_charge_densities);\n        }\n\n    total_charge_densities.compress(VectorOperation::add);\n    Step50::LaplaceProblem<dim>::pcout << \"Total charge density over the domain after rhs assembly optimization \" << std::setprecision(10) << std::scientific\n                                        << total_charge_densities.l2_norm() << std::endl;\n}\n\nvoid check ()\n{\n  ParameterHandler prm;\n  ParameterReader param(prm);\n  param.declare_parameters();\n\n  //Here create dynamically the list of all parameters required from the prm file for test purpose\n  std::ostringstream oss;\n  oss << \"subsection Geometry\" << std::endl\n         <<\"    set Number of global refinement = 4 \"<< std::endl\n        << \"    set Domain limit left = -2.5\" << std::endl\n        << \"    set Domain limit right = 2.5\" << std::endl\n        <<\"end\" <<std::endl\n       <<\"subsection Misc\"<<std::endl\n        << \"    set Number of Adaptive Refinement = 1\" << std::endl\n        << \"    set smoothing length = 0.5\" << std::endl\n//        << \"    set Nonzero Density radius parameter around each charge = 3\" << std::endl\n        <<\"end\"<<std::endl\n        << \"    set Polynomial degree = 1\" << std::endl\n        <<\"subsection Solver input data\"<<std::endl\n        << \"    set Preconditioner = GMG\" << std::endl\n        <<\"end\"<<std::endl\n       <<\"subsection Problem Selection\"<<std::endl\n        << \"    set Problem = GaussianCharges\" << std::endl\n        << \"    set Dimension = 3\" << std::endl\n        <<\"end\"<<std::endl\n       <<\"subsection Lammps data\"<<std::endl\n      << \"  set Lammps input file = \" << SOURCE_DIR << \"/atom_2.data\" << std::endl\n      <<\"end\"<<std::endl;\n\n  prm.parse_input_from_string(oss.str().c_str());\n\n  prm.enter_subsection (\"Geometry\");\n  unsigned int number_of_global_refinement =prm.get_integer(\"Number of global refinement\");\n  double domain_size_left     = prm.get_double (\"Domain limit left\");\n  double domain_size_right     = prm.get_double (\"Domain limit right\");\n  prm.leave_subsection ();\n\n  prm.enter_subsection (\"Misc\");\n  unsigned int number_of_adaptive_refinement_cycles      = prm.get_integer (\"Number of Adaptive Refinement\");\n  double r_c = prm.get_double (\"smoothing length\");\n  double nonzero_density_radius_parameter ;//= prm.get_double(\"Nonzero Density radius parameter around each charge\");\n  prm.leave_subsection ();\n\n  const unsigned int Degree = prm.get_integer(\"Polynomial degree\");\n\n  prm.enter_subsection(\"Solver input data\");\n  std::string PreconditionerType = (prm.get(\"Preconditioner\"));\n  prm.leave_subsection();\n\n  prm.enter_subsection(\"Problem Selection\");\n  std::string Problemtype= (prm.get(\"Problem\"));\n  const unsigned int d = prm.get_integer(\"Dimension\");\n  prm.leave_subsection();\n\n  prm.enter_subsection(\"Lammps data\");\n  std::string LammpsInputFile = (prm.get(\"Lammps input file\"));\n  prm.leave_subsection();\n\n  bool flag_rhs_assembly;\n  std::vector<double> r_c_variation {2.0,2.25,2.5,2.75,3.0,3.25,3.5,3.75,4.0,4.25,4.5,4.75,5.0,5.25,5.5,5.75,6.0};\n  for(const auto & i : r_c_variation)\n      {\n          nonzero_density_radius_parameter = i;\n          if(Utilities::MPI::this_mpi_process(MPI_COMM_WORLD) == 0)\n              std::cout<<\"cutoff radius: \"<<std::fixed<<std::setprecision(2)<<nonzero_density_radius_parameter<<std::endl;\n\n          if (d == 2)\n          {\n                Test_LaplaceProblem<2> test_laplace_problem(Degree , prm ,Problemtype, PreconditionerType, LammpsInputFile, domain_size_left, domain_size_right,\n                                                            number_of_global_refinement, number_of_adaptive_refinement_cycles, r_c, nonzero_density_radius_parameter);\n//                test_laplace_problem.run();\n                flag_rhs_assembly = 0;\n                std::cout << \"Without rhs assembly optimization\" <<std::endl;\n                test_laplace_problem.run(flag_rhs_assembly);\n//                test_laplace_problem.~Test_LaplaceProblem();\n\n                Test_LaplaceProblem<2> test_laplace_problem_with_rhs_optimiation(Degree , prm ,Problemtype, PreconditionerType, LammpsInputFile, domain_size_left, domain_size_right,\n                                                            number_of_global_refinement, number_of_adaptive_refinement_cycles, r_c, nonzero_density_radius_parameter);\n                flag_rhs_assembly = 1;\n                std::cout << \"Rhs assembly optimization ENABLED\" <<std::endl;\n                test_laplace_problem_with_rhs_optimiation.run(flag_rhs_assembly);\n\n          }\n          else if (d == 3)\n          {\n                  Test_LaplaceProblem<3> test_laplace_problem(Degree , prm ,Problemtype, PreconditionerType, LammpsInputFile, domain_size_left, domain_size_right,\n                                                              number_of_global_refinement, number_of_adaptive_refinement_cycles, r_c, nonzero_density_radius_parameter);\n//                  test_laplace_problem.run();\n                  flag_rhs_assembly = 0;\n                  std::cout << \"Without rhs assembly optimization\" <<std::endl;\n                  test_laplace_problem.run(flag_rhs_assembly);\n//                  test_laplace_problem.~Test_LaplaceProblem();\n\n                  Test_LaplaceProblem<3> test_laplace_problem_with_rhs_optimiation(Degree , prm ,Problemtype, PreconditionerType, LammpsInputFile, domain_size_left, domain_size_right,\n                                                              number_of_global_refinement, number_of_adaptive_refinement_cycles, r_c, nonzero_density_radius_parameter);\n                  flag_rhs_assembly = 1;\n                  std::cout << \"Rhs assembly optimization ENABLED\" <<std::endl;\n                  test_laplace_problem_with_rhs_optimiation.run(flag_rhs_assembly);\n\n          }\n          else if (d != 2 && d != 3)\n          {\n              AssertThrow(false, ExcMessage(\"Only 2d and 3d dimensions are supported.\"));\n          }\n      }\n\n\n}\n\n\nint main (int argc, char *argv[])\n{\n\n  dealii::Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv, 1);\n\n  check ();\n\n  return 0;\n}\n", "meta": {"hexsha": "0af55161bfdf1a2f7b67f9084acb15189ca63ebb", "size": 17152, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tests_rhs_rc_variation/rc_variation.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": "tests_rhs_rc_variation/rc_variation.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": "tests_rhs_rc_variation/rc_variation.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": 51.0476190476, "max_line_length": 198, "alphanum_fraction": 0.589610541, "num_tokens": 3764, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.6654105521116445, "lm_q1q2_score": 0.47392681094612016}}
{"text": "#include <big_random.h>\n#include <big_types.h>\n#include <big_generate_random.h>\n#include <big_is_orthonormal.h>\n#include <big_gram_schmidt.h>\n\n#include <big_generate_PD.h>\n#include <big_generate_PSD.h>\n#include <big_is_symmetric.h>\n\n#include <big_matlab_write.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n\nBOOST_AUTO_TEST_SUITE(big_modified_gram_schmidt);\n\nBOOST_AUTO_TEST_CASE(random_test_case)\n{\n  typedef ublas::compressed_matrix<double> matrix_type;\n\n  matrix_type A;\n\n  for(size_t tst=0;tst<5;++tst)\n  {\n    big::generate_random(10, 10, A);\n\n    bool not_ortho = !big::is_orthonormal( A );\n    BOOST_CHECK(not_ortho);\n\n    big::gram_schmidt(A);\n\n    bool did_it = big::is_orthonormal( A );\n    BOOST_CHECK(did_it);\n  }\n\n\n  {\n    using namespace big;\n    big::fast_generate_PD( 10, A );\n\n    bool is_ok = big::is_symmetric( A );\n    BOOST_CHECK(is_ok);\n\n    big::generate_PSD( 10, A, 0.5 );\n\n    bool is_also_ok = big::is_symmetric( A );\n    BOOST_CHECK(is_also_ok);\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "0275f13c1f78bd2d6e79bedf502c3bba6680730d", "size": 1167, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/FOUNDATION/BIG/unit_tests/big_gram_schmidt/unit_big_gram_schmidt.cpp", "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/FOUNDATION/BIG/unit_tests/big_gram_schmidt/unit_big_gram_schmidt.cpp", "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/FOUNDATION/BIG/unit_tests/big_gram_schmidt/unit_big_gram_schmidt.cpp", "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": 20.8392857143, "max_line_length": 55, "alphanum_fraction": 0.7232219366, "num_tokens": 324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152325073083131, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.47389717609203513}}
{"text": "#include \"FiniteElementTetrahedronMesh.h\"\n\n#include <Eigen/Dense>\n\n#include <map>\n\ntemplate<class T>\nstruct TetrahedralMesh : public FiniteElementTetrahedronMesh<T>\n{\n\tusing Base = FiniteElementTetrahedronMesh<T>;\n\n\t// from FiniteElementTetrahedonMesh\n\tusing Base::m_meshElements;\n\tusing Base::m_particleX;\n\tusing Base::initializeUSD;\n\tusing Base::initializeTopology;\n\tusing Base::initializeParticles;\n\tusing Vector3 = typename Base::Vector3;\n\n\tstd::array<int, 3> m_cellSize; // dimensions in grid cells\n\tint m_radius; // radius of sphere in grid cells\n\tT m_gridDX;\n\n\tstd::vector<std::array<int, 3>> m_activeCells; // Marks the \"active\" cells in the lattice\n\tstd::map<std::array<int, 3>, int> m_activeNodes; // Maps the \"active\" nodes to their particle index\n\n\tstd::vector<Vector3> m_particleUndeformedX;\n\tstd::vector<int> m_leftSquish;\n\tstd::vector<int> m_rightSquish;\n\n\tTetrahedralMesh()\n\t\t:Base(1.e2, .2, 5., .05)\n\t{\n\t}\n\n\tvoid initialize()\n\t{\n\t\tinitializeUSD(\"tetrahedral.usda\");\n\n\t\t// Activate cells within a sphere of radius m_radius (in cells)\n\n\t\tfor (int cell_i = 0; cell_i < m_cellSize[0]; cell_i++)\n\t\t\tfor (int cell_j = 0; cell_j < m_cellSize[1]; cell_j++)\n\t\t\t\tfor (int cell_k = 0; cell_k < m_cellSize[1]; cell_k++) {\n\n\t\t\t\t\tint r = (cell_i - m_cellSize[0] / 2) * (cell_i - m_cellSize[0] / 2) +\n\t\t\t\t\t\t(cell_j - m_cellSize[1] / 2) * (cell_j - m_cellSize[1] / 2) +\n\t\t\t\t\t\t(cell_k - m_cellSize[2] / 2) * (cell_k - m_cellSize[2] / 2);\n\n\t\t\t\t\tif (r <= m_radius * m_radius)\n\t\t\t\t\t\tm_activeCells.push_back(std::array<int, 3>{cell_i, cell_j, cell_k});\n\n\t\t\t\t}\n\n\t\tstd::cout << \"Created a model including \" << m_activeCells.size() << \" lattice cells\" << std::endl;\n\n\t\t// Create (uniquely numbered) particles at the node corners of active cells\n\n\t\tfor (const auto& cell : m_activeCells) {\n\t\t\tstd::array<int, 3> node;\n\t\t\tfor (node[0] = cell[0]; node[0] <= cell[0] + 1; node[0]++)\n\t\t\t\tfor (node[1] = cell[1]; node[1] <= cell[1] + 1; node[1]++)\n\t\t\t\t\tfor (node[2] = cell[2]; node[2] <= cell[2] + 1; node[2]++) {\n\t\t\t\t\t\tauto search = m_activeNodes.find(node);\n\t\t\t\t\t\tif (search == m_activeNodes.end()) { // Particle not yet created at this lattice node location -> make one\n\t\t\t\t\t\t\tm_activeNodes.insert({ node, m_particleX.size() });\n\t\t\t\t\t\t\tm_particleX.emplace_back(m_gridDX * T(node[0]), m_gridDX * T(node[1]), m_gridDX * T(node[2]));\n\t\t\t\t\t\t\tm_particleUndeformedX.emplace_back(m_gridDX * T(node[0]), m_gridDX * T(node[1]), m_gridDX * T(node[2]));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t}\n\t\tstd::cout << \"Model contains \" << m_particleX.size() << \" particles\" << std::endl;\n\n\t\t// Make tetrahedra out of all active cells (6 tetrahedra per cell)\n\n\t\tfor (const auto& cell : m_activeCells) {\n\t\t\tint vertexIndices[2][2][2];\n\t\t\tfor (int i = 0; i <= 1; i++)\n\t\t\t\tfor (int j = 0; j <= 1; j++)\n\t\t\t\t\tfor (int k = 0; k <= 1; k++) {\n\t\t\t\t\t\tstd::array<int, 3> node{ cell[0] + i, cell[1] + j, cell[2] + k };\n\t\t\t\t\t\tauto search = m_activeNodes.find(node);\n\t\t\t\t\t\tif (search != m_activeNodes.end())\n\t\t\t\t\t\t\tvertexIndices[i][j][k] = search->second;\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tthrow std::logic_error(\"particle at cell vertex not found\");\n\t\t\t\t\t}\n\n\t\t\tm_meshElements.push_back(std::array<int, 4>{ vertexIndices[0][0][0], vertexIndices[1][0][0], vertexIndices[1][1][0], vertexIndices[1][1][1]});\n\t\t\tm_meshElements.push_back(std::array<int, 4>{ vertexIndices[0][0][0], vertexIndices[1][0][0], vertexIndices[1][1][1], vertexIndices[1][0][1]});\n\t\t\tm_meshElements.push_back(std::array<int, 4>{ vertexIndices[0][0][0], vertexIndices[1][0][1], vertexIndices[1][1][1], vertexIndices[0][0][1]});\n\t\t\tm_meshElements.push_back(std::array<int, 4>{ vertexIndices[0][0][0], vertexIndices[1][1][1], vertexIndices[0][1][1], vertexIndices[0][0][1]});\n\t\t\tm_meshElements.push_back(std::array<int, 4>{ vertexIndices[0][0][0], vertexIndices[1][1][1], vertexIndices[0][1][0], vertexIndices[0][1][1]});\n\t\t\tm_meshElements.push_back(std::array<int, 4>{ vertexIndices[0][0][0], vertexIndices[1][1][0], vertexIndices[0][1][0], vertexIndices[1][1][1]});\n\t\t}\n\n\t\t// Perform the USD-specific initialization of topology & particles\n\t\t// (this will also create a boundary *surface* to visualuze\n\n\t\tinitializeTopology();\n\t\tinitializeParticles();\n\t\tinitializeUndeformedConfiguration();\n\n\t\t// Check particle indexing in mesh\n\n\t\tfor (const auto& element : m_meshElements)\n\t\t\tfor (const auto vertex : element)\n\t\t\t\tif (vertex < 0 || vertex >= m_particleX.size())\n\t\t\t\t\tthrow std::logic_error(\"mismatch between mesh vertex and particle array\");\n\n\t\tfor (int e = 0; e < m_particleX.size(); e++)\n\t\t{\n\t\t\tfloat leftThreshold = 1.3 - m_gridDX * (m_radius - 1);\n\t\t\tfloat rightThreshold = 1.25 + m_gridDX * (m_radius - 1);\n\t\t\t// Left side\n\t\t\tif (m_particleUndeformedX[e][0] < leftThreshold) {\n\t\t\t\tstd::cout << \"Particles...  \" << m_particleUndeformedX[e][0] << std::endl;\n\t\t\t\tm_leftSquish.push_back(e);\n\t\t\t}\n\t\t\t// Right side\n\t\t\tif (m_particleUndeformedX[e][0] > rightThreshold) {\n\t\t\t\tstd::cout << \"XXXParticles...  \" << m_particleUndeformedX[e][0] << std::endl;\n\t\t\t\tm_rightSquish.push_back(e);\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid clearConstrainedParticles(std::vector<Vector3>& x) override\n\t{\n\t\tfor (const auto v : m_leftSquish)\n\t\t\tx[v] = Vector3::Zero();\n\t\tfor (const auto v : m_rightSquish)\n\t\t\tx[v] = Vector3::Zero();\n\t}\n\n\tvoid setBoundaryConditions() override\n\t{\n\t\tstd::cout << \"Setting boundary conditions\" << std::endl;\n\t\tT effectiveTime = std::min<T>(m_stepEndTime, 1.5);\n\n\t\tfor (const auto v : m_leftSquish) {\n\t\t\tm_particleX[v] = m_particleUndeformedX[v] + effectiveTime * Vector3(-.5, .5, 0);\n\t\t}\n\t\tfor (const auto v : m_rightSquish) {\n\t\t\tm_particleX[v] = m_particleUndeformedX[v] + effectiveTime * Vector3(.5, -.5, 0);\n\t\t}\n\n\t\tstd::cout << \"Boundary conditions set\" << std::endl;\n\t}\n};\n\nint main(int argc, char *argv[])\n{\n\tTetrahedralMesh<float> simulationMesh;\n\tsimulationMesh.m_cellSize = { 50, 50, 50 };\n\tsimulationMesh.m_radius = 20;\n\tsimulationMesh.m_gridDX = 0.05;\n\tsimulationMesh.m_nFrames = 75;\n\tsimulationMesh.m_subSteps = 1;\n\tsimulationMesh.m_frameDt = 0.02;\n\n\t// Initialize the simulation example\n\tsimulationMesh.initialize();\n\n\t// Output the initial shape of the mesh\n\tsimulationMesh.writeFrame(0);\n\n\tfor (int frame = 1; frame <= simulationMesh.m_nFrames; frame++) {\n\t\tsimulationMesh.simulateFrame(frame);\n\t\tsimulationMesh.writeFrame(frame);\n\t}\n\n\t// Write the entire timeline to USD\n\tsimulationMesh.writeUSD();\n\n\treturn 0;\n}\n\n", "meta": {"hexsha": "206bc7493dc68c89ad5ba13d9471c4b68e2a7b91", "size": 6307, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "projects/tests/squishCubeSim/main.cpp", "max_stars_repo_name": "tjwilder/cs839-p2", "max_stars_repo_head_hexsha": "fd92f4dc09ba71deb87341a964cfd8ded771b941", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "projects/tests/squishCubeSim/main.cpp", "max_issues_repo_name": "tjwilder/cs839-p2", "max_issues_repo_head_hexsha": "fd92f4dc09ba71deb87341a964cfd8ded771b941", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "projects/tests/squishCubeSim/main.cpp", "max_forks_repo_name": "tjwilder/cs839-p2", "max_forks_repo_head_hexsha": "fd92f4dc09ba71deb87341a964cfd8ded771b941", "max_forks_repo_licenses": ["BSD-3-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.2346368715, "max_line_length": 145, "alphanum_fraction": 0.6595845886, "num_tokens": 1990, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324803738429, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.47389716043494434}}
{"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#include <opengv/relative_pose/methods.hpp>\n#include <opengv/Indices.hpp>\n\n#include <Eigen/NonLinearOptimization>\n#include <Eigen/NumericalDiff>\n#include <Eigen/KroneckerProduct>\n#include <Eigen/QR>\n\n#include <opengv/OptimizationFunctor.hpp>\n#include <opengv/math/arun.hpp>\n#include <opengv/math/cayley.hpp>\n#include <opengv/relative_pose/modules/main.hpp>\n#include <opengv/triangulation/methods.hpp>\n\n#include <iostream>\n\nopengv::translation_t\nopengv::relative_pose::twopt(\n    const RelativeAdapterBase & adapter,\n    bool unrotate,\n    const std::vector<int> & indices )\n{\n  assert(indices.size()>1);\n  return twopt( adapter, unrotate, indices[0], indices[1] );\n};\n\nopengv::translation_t\nopengv::relative_pose::twopt(\n    const RelativeAdapterBase & adapter,\n    bool unrotate,\n    size_t index0,\n    size_t index1 )\n{\n  bearingVector_t f1 = adapter.getBearingVector1(index0);\n  bearingVector_t f1prime = adapter.getBearingVector2(index0);\n  bearingVector_t f2 = adapter.getBearingVector1(index1);\n  bearingVector_t f2prime = adapter.getBearingVector2(index1);\n\n  if(unrotate)\n  {\n    rotation_t R12 = adapter.getR12();\n    f1prime = R12 * f1prime;\n    f2prime = R12 * f2prime;\n  }\n\n  Eigen::Vector3d normal1 = f1.cross(f1prime);\n  Eigen::Vector3d normal2 = f2.cross(f2prime);\n\n  translation_t translation = normal1.cross(normal2);\n  translation = translation/translation.norm();\n\n  Eigen::Vector3d opticalFlow = f1 - f1prime;\n  if( opticalFlow.dot(translation) < 0 )\n    translation = -translation;\n\n  return translation;\n};\n\nopengv::rotation_t\nopengv::relative_pose::twopt_rotationOnly(\n    const RelativeAdapterBase & adapter,\n    const std::vector<int> & indices )\n{\n  assert(indices.size() > 1);\n  return twopt_rotationOnly( adapter, indices[0], indices[1] );\n};\n\nopengv::rotation_t\nopengv::relative_pose::twopt_rotationOnly(\n    const RelativeAdapterBase & adapter,\n    size_t index0,\n    size_t index1)\n{\n  Eigen::Vector3d pointsCenter1 =\n      adapter.getBearingVector1(index0) + adapter.getBearingVector1(index1);\n  Eigen::Vector3d pointsCenter2 =\n      adapter.getBearingVector2(index0) + adapter.getBearingVector2(index1);\n  pointsCenter1 = pointsCenter1/3.0;\n  pointsCenter2 = pointsCenter2/3.0;\n\n  Eigen::MatrixXd Hcross(3,3);\n  Hcross = Eigen::Matrix3d::Zero();\n\n  Eigen::Vector3d f = adapter.getBearingVector1(index0) - pointsCenter1;\n  Eigen::Vector3d fprime = adapter.getBearingVector2(index0) - pointsCenter2;\n  Hcross += fprime * f.transpose();\n  f = adapter.getBearingVector1(index1) - pointsCenter1;\n  fprime = adapter.getBearingVector2(index1) - pointsCenter2;\n  Hcross += fprime * f.transpose();\n\n  return math::arun(Hcross);\n};\n\nnamespace opengv\n{\nnamespace relative_pose\n{\n\nrotation_t rotationOnly(\n    const RelativeAdapterBase & adapter,\n    const Indices & indices )\n{\n  size_t numberCorrespondences = indices.size();\n  assert(numberCorrespondences > 2);\n\n  Eigen::Vector3d pointsCenter1 = Eigen::Vector3d::Zero();\n  Eigen::Vector3d pointsCenter2 = Eigen::Vector3d::Zero();\n\n  for( size_t i = 0; i < numberCorrespondences; i++ )\n  {\n    pointsCenter1 += adapter.getBearingVector1(indices[i]);\n    pointsCenter2 += adapter.getBearingVector2(indices[i]);\n  }\n\n  pointsCenter1 = pointsCenter1 / numberCorrespondences;\n  pointsCenter2 = pointsCenter2 / numberCorrespondences;\n\n  Eigen::MatrixXd Hcross(3,3);\n  Hcross = Eigen::Matrix3d::Zero();\n\n  for( size_t i = 0; i < numberCorrespondences; i++ )\n  {\n    Eigen::Vector3d f = adapter.getBearingVector1(indices[i]) - pointsCenter1;\n    Eigen::Vector3d fprime =\n        adapter.getBearingVector2(indices[i]) - pointsCenter2;\n    Hcross += fprime * f.transpose();\n  }\n\n  return math::arun(Hcross);\n};\n\n}\n}\n\nopengv::rotation_t\nopengv::relative_pose::rotationOnly( const RelativeAdapterBase & adapter )\n{\n  Indices idx(adapter.getNumberCorrespondences());\n  return rotationOnly(adapter,idx);\n};\n\nopengv::rotation_t\nopengv::relative_pose::rotationOnly(\n    const RelativeAdapterBase & adapter,\n    const std::vector<int> & indices )\n{\n  Indices idx(indices);\n  return rotationOnly(adapter,idx);\n};\n\nnamespace opengv\n{\nnamespace relative_pose\n{\n\ncomplexEssentials_t fivept_stewenius(\n    const RelativeAdapterBase & adapter,\n    const Indices & indices )\n{\n  size_t numberCorrespondences = indices.size();\n  assert(numberCorrespondences > 4);\n\n  Eigen::MatrixXd Q(numberCorrespondences,9);\n  for( size_t i = 0; i < numberCorrespondences; i++ )\n  {\n    //bearingVector_t f = adapter.getBearingVector1(indices[i]);\n    //bearingVector_t fprime = adapter.getBearingVector2(indices[i]);\n    //Stewenius' algorithm is computing the inverse transformation, so we simply\n    //invert the input here\n    bearingVector_t f = adapter.getBearingVector2(indices[i]);\n    bearingVector_t fprime = adapter.getBearingVector1(indices[i]);\n    Eigen::Matrix<double,1,9> row;\n    row <<  f[0]*fprime[0], f[1]*fprime[0], f[2]*fprime[0],\n        f[0]*fprime[1], f[1]*fprime[1], f[2]*fprime[1],\n        f[0]*fprime[2], f[1]*fprime[2], f[2]*fprime[2];\n    Q.row(i) = row;\n  }\n\n  Eigen::JacobiSVD< Eigen::MatrixXd > SVD(Q, Eigen::ComputeFullV );\n  Eigen::Matrix<double,9,4> EE = SVD.matrixV().block(0,5,9,4);\n  complexEssentials_t complexEssentials;\n  modules::fivept_stewenius_main(EE,complexEssentials);\n  return complexEssentials;\n};\n\n}\n}\n\nopengv::complexEssentials_t\nopengv::relative_pose::fivept_stewenius( const RelativeAdapterBase & adapter )\n{\n  Indices idx(adapter.getNumberCorrespondences());\n  return fivept_stewenius(adapter,idx);\n};\n\nopengv::complexEssentials_t\nopengv::relative_pose::fivept_stewenius(\n    const RelativeAdapterBase & adapter,\n    const std::vector<int> & indices )\n{\n  Indices idx(indices);\n  return fivept_stewenius(adapter,idx);\n};\n\nnamespace opengv\n{\nnamespace relative_pose\n{\n\nessentials_t fivept_nister(\n    const RelativeAdapterBase & adapter,\n    const Indices & indices )\n{\n  size_t numberCorrespondences = indices.size();\n  assert(numberCorrespondences > 4);\n\n  Eigen::MatrixXd Q(numberCorrespondences,9);\n  for( size_t i = 0; i < numberCorrespondences; i++ )\n  {\n    //bearingVector_t f = adapter.getBearingVector1(indices[i]);\n    //bearingVector_t fprime = adapter.getBearingVector2(indices[i]);\n    //Nister's algorithm is computing the inverse transformation, so we simply\n    //invert the input here\n    bearingVector_t f = adapter.getBearingVector2(indices[i]);\n    bearingVector_t fprime = adapter.getBearingVector1(indices[i]);\n    Eigen::Matrix<double,1,9> row;\n    row <<  f[0]*fprime[0], f[1]*fprime[0], f[2]*fprime[0],\n        f[0]*fprime[1], f[1]*fprime[1], f[2]*fprime[1],\n        f[0]*fprime[2], f[1]*fprime[2], f[2]*fprime[2];\n    Q.row(i) = row;\n  }\n\n  Eigen::JacobiSVD< Eigen::MatrixXd > SVD(Q, Eigen::ComputeFullV );\n  Eigen::Matrix<double,9,4> EE = SVD.matrixV().block(0,5,9,4);\n  essentials_t essentials;\n  modules::fivept_nister_main(EE,essentials);\n\n  return essentials;\n};\n\n}\n}\n\nopengv::essentials_t\nopengv::relative_pose::fivept_nister( const RelativeAdapterBase & adapter )\n{\n  Indices idx(adapter.getNumberCorrespondences());\n  return fivept_nister(adapter,idx);\n};\n\nopengv::essentials_t\nopengv::relative_pose::fivept_nister(\n    const RelativeAdapterBase & adapter,\n    const std::vector<int> & indices )\n{\n  Indices idx(indices);\n  return fivept_nister(adapter,idx);\n};\n\nopengv::rotations_t\nopengv::relative_pose::fivept_kneip(\n    const RelativeAdapterBase & adapter,\n    const std::vector<int> & indices )\n{\n  size_t numberCorrespondences = indices.size();\n  assert(numberCorrespondences == 5);\n\n  Eigen::Matrix<double,3,5> f1;\n  Eigen::Matrix<double,3,5> f2;\n\n  for(size_t i = 0; i < numberCorrespondences; i++)\n  {\n    f1.col(i) = adapter.getBearingVector1(indices[i]);\n    f2.col(i) = adapter.getBearingVector2(indices[i]);\n  }\n\n  rotations_t rotations;\n  modules::fivept_kneip_main( f1, f2, rotations );\n  return rotations;\n}\n\nnamespace opengv\n{\nnamespace relative_pose\n{\n\nessentials_t sevenpt(\n    const RelativeAdapterBase & adapter,\n    const Indices & indices )\n{\n  size_t numberCorrespondences = indices.size();\n  assert(numberCorrespondences > 6);\n\n  Eigen::MatrixXd A(numberCorrespondences,9);\n\n  for( size_t i = 0; i < numberCorrespondences; i++ )\n  {\n    //bearingVector_t f1 = adapter.getBearingVector1(indices[i]);\n    //bearingVector_t f2 = adapter.getBearingVector2(indices[i]);\n    //The seven-point is computing the inverse transformation, which is why we\n    //invert the input\n    bearingVector_t f1 = adapter.getBearingVector2(indices[i]);\n    bearingVector_t f2 = adapter.getBearingVector1(indices[i]);\n\n    A.block<1,3>(i,0) = f2[0] * f1.transpose();\n    A.block<1,3>(i,3) = f2[1] * f1.transpose();\n    A.block<1,3>(i,6) = f2[2] * f1.transpose();\n  }\n\n  Eigen::JacobiSVD< Eigen::MatrixXd > SVD(\n      A,\n      Eigen::ComputeFullU | Eigen::ComputeFullV );\n\n  Eigen::Matrix<double,9,1> f1 = SVD.matrixV().col(8);\n  Eigen::Matrix<double,9,1> f2 = SVD.matrixV().col(7);\n\n  Eigen::MatrixXd F1_temp(3,3);\n  F1_temp.col(0) = f1.block<3,1>(0,0);\n  F1_temp.col(1) = f1.block<3,1>(3,0);\n  F1_temp.col(2) = f1.block<3,1>(6,0);\n  essential_t F1 = F1_temp.transpose();\n\n  Eigen::MatrixXd F2_temp(3,3);\n  F2_temp.col(0) = f2.block<3,1>(0,0);\n  F2_temp.col(1) = f2.block<3,1>(3,0);\n  F2_temp.col(2) = f2.block<3,1>(6,0);\n  essential_t F2 = F2_temp.transpose();\n\n  double eps = 0.00000001;\n  essentials_t essentials;\n  \n  if( fabs(F1.determinant()) < eps || numberCorrespondences > 7 )\n  {\n    essentials.push_back(F1);\n  }\n  else\n  {\n    essential_t M = F2.inverse() * F1;\n    Eigen::EigenSolver< essential_t > Eig(M,true);\n    Eigen::Matrix< std::complex<double>,3,1 > D = Eig.eigenvalues();\n\n    double val1 = fabs(D(0,0).imag());\n    double val2 = fabs(D(1,0).imag());\n    double val3 = fabs(D(2,0).imag());\n\n    if( val1 < eps && val2 < eps && val3 < eps )\n    {\n      essentials.push_back( F1 - D(0,0).real() * F2 );\n      essentials.push_back( F1 - D(1,0).real() * F2 );\n      essentials.push_back( F1 - D(2,0).real() * F2 );\n    }\n    else\n    {\n      double min = val1;\n      int minIndex = 0;\n      if( val2 < min )\n      {\n        min = val2;\n        minIndex = 1;\n      }\n      if( val3 < min )\n        minIndex = 2;\n      \n      essentials.push_back( F1 - D(minIndex,0).real() * F2 );\n    }\n  }\n\n  return essentials;\n}\n\n}\n}\n\nopengv::essentials_t\nopengv::relative_pose::sevenpt( const RelativeAdapterBase & adapter )\n{\n  Indices idx(adapter.getNumberCorrespondences());\n  return sevenpt(adapter,idx);\n}\n\nopengv::essentials_t\nopengv::relative_pose::sevenpt(\n    const RelativeAdapterBase & adapter,\n    const std::vector<int> & indices )\n{\n  Indices idx(indices);\n  return sevenpt(adapter,idx);\n}\n\nnamespace opengv\n{\nnamespace relative_pose\n{\n\nessential_t eightpt(\n    const RelativeAdapterBase & adapter,\n    const Indices & indices )\n{\n  size_t numberCorrespondences = indices.size();\n  assert(numberCorrespondences > 7);\n\n  Eigen::MatrixXd A(numberCorrespondences,9);\n\n  for( size_t i = 0; i < numberCorrespondences; i++ )\n  {\n    //bearingVector_t f1 = adapter.getBearingVector1(indices[i]);\n    //bearingVector_t f2 = adapter.getBearingVector2(indices[i]);\n    //The eight-point essentially computes the inverse transformation, which is\n    //why we invert the input here\n    bearingVector_t f1 = adapter.getBearingVector2(indices[i]);\n    bearingVector_t f2 = adapter.getBearingVector1(indices[i]);\n\n    A.block<1,3>(i,0) = f2[0] * f1.transpose();\n    A.block<1,3>(i,3) = f2[1] * f1.transpose();\n    A.block<1,3>(i,6) = f2[2] * f1.transpose();\n  }\n\n  Eigen::JacobiSVD< Eigen::MatrixXd > SVD(\n      A,\n      Eigen::ComputeFullU | Eigen::ComputeFullV );\n  Eigen::Matrix<double,9,1> f = SVD.matrixV().col(8);\n\n  Eigen::MatrixXd F_temp(3,3);\n  F_temp.col(0) = f.block<3,1>(0,0);\n  F_temp.col(1) = f.block<3,1>(3,0);\n  F_temp.col(2) = f.block<3,1>(6,0);\n  essential_t F = F_temp.transpose();\n\n  Eigen::JacobiSVD< Eigen::MatrixXd > SVD2(\n      F,\n      Eigen::ComputeFullU | Eigen::ComputeFullV );\n  Eigen::Matrix3d S = Eigen::Matrix3d::Zero();\n  S(0,0) = SVD2.singularValues()[0];\n  S(1,1) = SVD2.singularValues()[1];\n\n  Eigen::Matrix3d U = SVD2.matrixU();\n  Eigen::Matrix3d Vtr = SVD2.matrixV().transpose();\n\n  essential_t essential = U * S * Vtr;\n  return essential;\n}\n\n}\n}\n\nopengv::essential_t\nopengv::relative_pose::eightpt( const RelativeAdapterBase & adapter )\n{\n  Indices idx(adapter.getNumberCorrespondences());\n  return eightpt(adapter,idx);\n}\n\nopengv::essential_t\nopengv::relative_pose::eightpt(\n    const RelativeAdapterBase & adapter,\n    const std::vector<int> & indices )\n{\n  Indices idx(indices);\n  return eightpt(adapter,idx);\n}\n\nnamespace opengv\n{\nnamespace relative_pose\n{\n\nrotation_t eigensolver(\n    const RelativeAdapterBase & adapter,\n    const Indices & indices,\n    eigensolverOutput_t & output,\n    bool useWeights )\n{\n  size_t numberCorrespondences = indices.size();\n  assert(numberCorrespondences > 4);\n\n  Eigen::Matrix3d xxF = Eigen::Matrix3d::Zero();\n  Eigen::Matrix3d yyF = Eigen::Matrix3d::Zero();\n  Eigen::Matrix3d zzF = Eigen::Matrix3d::Zero();\n  Eigen::Matrix3d xyF = Eigen::Matrix3d::Zero();\n  Eigen::Matrix3d yzF = Eigen::Matrix3d::Zero();\n  Eigen::Matrix3d zxF = Eigen::Matrix3d::Zero();\n\n  //compute the norm of all the scores\n  double norm = 0.0;\n  for(size_t i=0; i < numberCorrespondences; i++)\n    norm += pow(adapter.getWeight(indices[i]),2);\n  norm = sqrt(norm);\n\n  //Fill summation terms\n  for(size_t i=0; i < numberCorrespondences; i++)\n  {\n    bearingVector_t f1 = adapter.getBearingVector1(indices[i]);\n    bearingVector_t f2 = adapter.getBearingVector2(indices[i]);\n    Eigen::Matrix3d F = f2*f2.transpose();\n    \n    double weight = 1.0;\n    if( useWeights )\n      weight = adapter.getWeight(indices[i])/norm;\n\n    xxF = xxF + weight*f1[0]*f1[0]*F;\n    yyF = yyF + weight*f1[1]*f1[1]*F;\n    zzF = zzF + weight*f1[2]*f1[2]*F;\n    xyF = xyF + weight*f1[0]*f1[1]*F;\n    yzF = yzF + weight*f1[1]*f1[2]*F;\n    zxF = zxF + weight*f1[2]*f1[0]*F;\n  }\n\n  //Do minimization\n  modules::eigensolver_main(xxF,yyF,zzF,xyF,yzF,zxF,output);\n\n  //Correct the translation\n  bearingVector_t f1 = adapter.getBearingVector1(indices[0]);\n  bearingVector_t f2 = adapter.getBearingVector2(indices[0]);\n  f2 = output.rotation * f2;\n  Eigen::Vector3d opticalFlow = f1 - f2;\n  if( opticalFlow.dot(output.translation) < 0.0 )\n    output.translation = -output.translation;\n\n  return output.rotation;\n}\n\n}\n}\n\nopengv::rotation_t\nopengv::relative_pose::eigensolver(\n    const RelativeAdapterBase & adapter,\n    eigensolverOutput_t & output,\n    bool useWeights )\n{\n  Indices idx(adapter.getNumberCorrespondences());\n  return eigensolver(adapter,idx,output,useWeights);\n}\n\nopengv::rotation_t\nopengv::relative_pose::eigensolver(\n    const RelativeAdapterBase & adapter,\n    const std::vector<int> & indices,\n    eigensolverOutput_t & output,\n    bool useWeights )\n{\n  Indices idx(indices);\n  return eigensolver(adapter,idx,output,useWeights);\n}\n\nopengv::rotation_t\nopengv::relative_pose::eigensolver(\n    const RelativeAdapterBase & adapter,\n    bool useWeights )\n{\n  eigensolverOutput_t output;\n  output.rotation = adapter.getR12();\n  return eigensolver(adapter,output,useWeights);\n}\n\nopengv::rotation_t\nopengv::relative_pose::eigensolver(\n    const RelativeAdapterBase & adapter,\n    const std::vector<int> & indices,\n    bool useWeights )\n{\n  eigensolverOutput_t output;\n  output.rotation = adapter.getR12();\n  return eigensolver(adapter,indices,output,useWeights);\n}\n\nnamespace opengv\n{\nnamespace relative_pose\n{\n\nrotations_t sixpt(\n    const RelativeAdapterBase & adapter,\n    const Indices & indices )\n{\n  size_t numberCorrespondences = indices.size();\n  assert(numberCorrespondences == 6);\n\n  Eigen::Matrix<double,6,6> L1;\n  Eigen::Matrix<double,6,6> L2;\n\n  for(size_t i = 0; i < numberCorrespondences; i++)\n  {\n    bearingVector_t f1 =\n        adapter.getCamRotation1(indices[i]) * adapter.getBearingVector1(indices[i]);\n    bearingVector_t f2 =\n        adapter.getCamRotation2(indices[i]) * adapter.getBearingVector2(indices[i]);\n        \n    L1.block<3,1>(0,i) = f1;\n    L2.block<3,1>(0,i) = f2;\n    \n    L1.block<3,1>(3,i) = f1.cross(adapter.getCamOffset1(indices[i]));\n    L2.block<3,1>(3,i) = f2.cross(adapter.getCamOffset2(indices[i]));\n  }\n\n  rotations_t solutions;\n  modules::sixpt_main( L1, L2, solutions );  \n  return solutions;\n}\n\n}\n}\n\nopengv::rotations_t\nopengv::relative_pose::sixpt(\n    const RelativeAdapterBase & adapter )\n{\n  Indices idx(adapter.getNumberCorrespondences());\n  return sixpt(adapter,idx);\n}\n\nopengv::rotations_t\nopengv::relative_pose::sixpt(\n    const RelativeAdapterBase & adapter,\n    const std::vector<int> & indices )\n{\n  Indices idx(indices);\n  return sixpt(adapter,idx);\n}\n\nnamespace opengv\n{\nnamespace relative_pose\n{\n\ntransformation_t ge(\n    const RelativeAdapterBase & adapter,\n    const Indices & indices,\n    geOutput_t & output,\n    bool useWeights )\n{ \n  size_t numberCorrespondences = indices.size();\n  assert(numberCorrespondences > 5);\n\n  Eigen::Matrix3d xxF = Eigen::Matrix3d::Zero();\n  Eigen::Matrix3d yyF = Eigen::Matrix3d::Zero();\n  Eigen::Matrix3d zzF = Eigen::Matrix3d::Zero();\n  Eigen::Matrix3d xyF = Eigen::Matrix3d::Zero();\n  Eigen::Matrix3d yzF = Eigen::Matrix3d::Zero();\n  Eigen::Matrix3d zxF = Eigen::Matrix3d::Zero();\n  \n  Eigen::Matrix<double,3,9> x1P = Eigen::Matrix<double,3,9>::Zero();\n  Eigen::Matrix<double,3,9> y1P = Eigen::Matrix<double,3,9>::Zero();\n  Eigen::Matrix<double,3,9> z1P = Eigen::Matrix<double,3,9>::Zero();\n  Eigen::Matrix<double,3,9> x2P = Eigen::Matrix<double,3,9>::Zero();\n  Eigen::Matrix<double,3,9> y2P = Eigen::Matrix<double,3,9>::Zero();\n  Eigen::Matrix<double,3,9> z2P = Eigen::Matrix<double,3,9>::Zero();\n  \n  Eigen::Matrix<double,9,9> m11P = Eigen::Matrix<double,9,9>::Zero();\n  Eigen::Matrix<double,9,9> m12P = Eigen::Matrix<double,9,9>::Zero();\n  Eigen::Matrix<double,9,9> m22P = Eigen::Matrix<double,9,9>::Zero();\n\n  //compute the norm of all the scores\n  double norm = 0.0;\n  for(size_t i=0; i < numberCorrespondences; i++)\n    norm += pow(adapter.getWeight(indices[i]),2);\n  norm = sqrt(norm);\n\n  //Fill summation terms\n  for(size_t i=0; i < numberCorrespondences; i++)\n  {\n    //get the weight of this feature\n    double weight = 1.0;\n    if( useWeights )\n      weight = adapter.getWeight(indices[i])/norm;\n    \n    //unrotate the bearing vectors\n    bearingVector_t f1 = adapter.getCamRotation1(indices[i]) *\n        adapter.getBearingVector1(indices[i]);\n    bearingVector_t f2 = adapter.getCamRotation2(indices[i]) *\n        adapter.getBearingVector2(indices[i]);\n    \n    //compute the standard summation terms\n    Eigen::Matrix3d F = f2*f2.transpose();\n\n    xxF = xxF + weight*f1[0]*f1[0]*F;\n    yyF = yyF + weight*f1[1]*f1[1]*F;\n    zzF = zzF + weight*f1[2]*f1[2]*F;\n    xyF = xyF + weight*f1[0]*f1[1]*F;\n    yzF = yzF + weight*f1[1]*f1[2]*F;\n    zxF = zxF + weight*f1[2]*f1[0]*F;\n    \n    //now compute the \"cross\"-summation terms    \n    Eigen::Vector3d t1 = adapter.getCamOffset1(indices[i]);\n    Eigen::Vector3d t2 = adapter.getCamOffset2(indices[i]);\n    \n    Eigen::Matrix<double,1,9> f2_19;\n    double temp = f1[1]*t1[2]-f1[2]*t1[1];\n    f2_19(0,0) = f2[0] * temp;\n    f2_19(0,1) = f2[1] * temp;\n    f2_19(0,2) = f2[2] * temp;\n    temp = f1[2]*t1[0]-f1[0]*t1[2];\n    f2_19(0,3) = f2[0] * temp;\n    f2_19(0,4) = f2[1] * temp;\n    f2_19(0,5) = f2[2] * temp;\n    temp = f1[0]*t1[1]-f1[1]*t1[0];\n    f2_19(0,6) = f2[0] * temp;\n    f2_19(0,7) = f2[1] * temp;\n    f2_19(0,8) = f2[2] * temp;\n    \n    Eigen::Matrix<double,1,9> f1_19;\n    temp = f2[1]*t2[2]-f2[2]*t2[1];\n    f1_19(0,0) = f1[0] * temp;\n    f1_19(0,1) = f1[1] * temp;\n    f1_19(0,2) = f1[2] * temp;\n    temp = f2[2]*t2[0]-f2[0]*t2[2];\n    f1_19(0,3) = f1[0] * temp;\n    f1_19(0,4) = f1[1] * temp;\n    f1_19(0,5) = f1[2] * temp;\n    temp = f2[0]*t2[1]-f2[1]*t2[0];\n    f1_19(0,6) = f1[0] * temp;\n    f1_19(0,7) = f1[1] * temp;\n    f1_19(0,8) = f1[2] * temp;\n    \n    if( useWeights )\n    {\n      x1P = x1P + ( (weight * f1[0]) * f2 ) * f1_19;\n      y1P = y1P + ( (weight * f1[1]) * f2 ) * f1_19;\n      z1P = z1P + ( (weight * f1[2]) * f2 ) * f1_19;\n      \n      x2P = x2P + ( (weight * f1[0]) * f2 ) * f2_19;\n      y2P = y2P + ( (weight * f1[1]) * f2 ) * f2_19;\n      z2P = z2P + ( (weight * f1[2]) * f2 ) * f2_19;\n      \n      m11P = m11P - ( weight * f1_19.transpose() ) * f1_19;\n      m22P = m22P - ( weight * f2_19.transpose() ) * f2_19;\n      m12P = m12P - ( weight * f2_19.transpose() ) * f1_19;\n    }\n    else\n    {\n      x1P = x1P + ( f1[0] * f2 ) * f1_19;\n      y1P = y1P + ( f1[1] * f2 ) * f1_19;\n      z1P = z1P + ( f1[2] * f2 ) * f1_19;\n      \n      x2P = x2P + ( f1[0]) * f2 * f2_19;\n      y2P = y2P + ( f1[1]) * f2 * f2_19;\n      z2P = z2P + ( f1[2]) * f2 * f2_19;\n      \n      m11P = m11P - f1_19.transpose() * f1_19;\n      m22P = m22P - f2_19.transpose() * f2_19;\n      m12P = m12P - f2_19.transpose() * f1_19;\n    }\n  }\n\n  Eigen::Vector3d pointsCenter1 = Eigen::Vector3d::Zero();\n  Eigen::Vector3d pointsCenter2 = Eigen::Vector3d::Zero();\n\n  for( size_t i = 0; i < numberCorrespondences; i++ )\n  {\n    pointsCenter1 += adapter.getCamRotation1(indices[i]) *\n        adapter.getBearingVector1(indices[i]);\n    pointsCenter2 += adapter.getCamRotation2(indices[i]) *\n        adapter.getBearingVector2(indices[i]);\n  }\n\n  pointsCenter1 = pointsCenter1 / numberCorrespondences;\n  pointsCenter2 = pointsCenter2 / numberCorrespondences;\n\n  Eigen::MatrixXd Hcross(3,3);\n  Hcross = Eigen::Matrix3d::Zero();\n\n  for( size_t i = 0; i < numberCorrespondences; i++ )\n  {\n    Eigen::Vector3d f =      adapter.getCamRotation1(indices[i]) *\n        adapter.getBearingVector1(indices[i]) - pointsCenter1;\n    Eigen::Vector3d fprime = adapter.getCamRotation2(indices[i]) *\n        adapter.getBearingVector2(indices[i]) - pointsCenter2;\n    Hcross += fprime * f.transpose();\n  }\n\n  rotation_t startingRotation = math::arun(Hcross);\n\n  //Do minimization\n  modules::ge_main2(\n      xxF, yyF, zzF, xyF, yzF, zxF,\n      x1P, y1P, z1P, x2P, y2P, z2P,\n      m11P, m12P, m22P, math::rot2cayley(startingRotation), output);\n\n  transformation_t transformation;\n  transformation.block<3,3>(0,0) = output.rotation;\n  transformation.col(3) = output.translation.block<3,1>(0,0);\n  return transformation;\n}\n\n}\n}\n\nopengv::transformation_t\nopengv::relative_pose::ge(\n    const RelativeAdapterBase & adapter,\n    geOutput_t & output,\n    bool useWeights )\n{\n  Indices idx(adapter.getNumberCorrespondences());\n  return ge(adapter,idx,output,useWeights);\n}\n\nopengv::transformation_t\nopengv::relative_pose::ge(\n    const RelativeAdapterBase & adapter,\n    const std::vector<int> & indices,\n    geOutput_t & output,\n    bool useWeights )\n{\n  Indices idx(indices);\n  return ge(adapter,idx,output,useWeights);\n}\n\nopengv::transformation_t\nopengv::relative_pose::ge( const RelativeAdapterBase & adapter, bool useWeights )\n{\n  geOutput_t output;\n  //output.rotation = adapter.getR12(); //finding starting value using arun\n  return ge(adapter,output,useWeights);\n}\n\nopengv::transformation_t\nopengv::relative_pose::ge(\n    const RelativeAdapterBase & adapter,\n    const std::vector<int> & indices,\n    bool useWeights )\n{\n  geOutput_t output;\n  //output.rotation = adapter.getR12(); //finding starting value using arun\n  return ge(adapter,indices,output,useWeights);\n}\n\nnamespace opengv\n{\nnamespace relative_pose\n{\n\ntransformation_t seventeenpt(\n    const RelativeAdapterBase & adapter,\n    const Indices & indices )\n{\n  size_t numberCorrespondences = indices.size();\n  assert(numberCorrespondences > 16);\n\n  Eigen::MatrixXd AE(numberCorrespondences,9);\n  Eigen::MatrixXd AR(numberCorrespondences,9);\n\n  for( size_t i = 0; i < numberCorrespondences; i++ )\n  {\n    bearingVector_t d1 = adapter.getBearingVector1(indices[i]);\n    bearingVector_t d2 = adapter.getBearingVector2(indices[i]);\n    translation_t v1 = adapter.getCamOffset1(indices[i]);\n    translation_t v2 = adapter.getCamOffset2(indices[i]);\n    rotation_t R1 = adapter.getCamRotation1(indices[i]);\n    rotation_t R2 = adapter.getCamRotation2(indices[i]);\n\n    //unrotate the bearing-vectors to express everything in the body frame\n    d1 = R1*d1;\n    d2 = R2*d2;\n\n    //generate the Pl\u00fccker line coordinates\n    Eigen::Matrix<double,6,1> l1;\n    l1.block<3,1>(0,0) = d1;\n    l1.block<3,1>(3,0) = v1.cross(d1);\n    Eigen::Matrix<double,6,1> l2;\n    l2.block<3,1>(0,0) = d2;\n    l2.block<3,1>(3,0) = v2.cross(d2);\n\n    //fill line of matrix A\n    AE(i,0) = l2[0]*l1[0];\n    AE(i,1) = l2[0]*l1[1];\n    AE(i,2) = l2[0]*l1[2];\n    AE(i,3) = l2[1]*l1[0];\n    AE(i,4) = l2[1]*l1[1];\n    AE(i,5) = l2[1]*l1[2];\n    AE(i,6) = l2[2]*l1[0];\n    AE(i,7) = l2[2]*l1[1];\n    AE(i,8) = l2[2]*l1[2];\n\n    AR(i,0) = l2[0]*l1[3]+l2[3]*l1[0];\n    AR(i,1) = l2[0]*l1[4]+l2[3]*l1[1];\n    AR(i,2) = l2[0]*l1[5]+l2[3]*l1[2];\n    AR(i,3) = l2[1]*l1[3]+l2[4]*l1[0];\n    AR(i,4) = l2[1]*l1[4]+l2[4]*l1[1];\n    AR(i,5) = l2[1]*l1[5]+l2[4]*l1[2];\n    AR(i,6) = l2[2]*l1[3]+l2[5]*l1[0];\n    AR(i,7) = l2[2]*l1[4]+l2[5]*l1[1];\n    AR(i,8) = l2[2]*l1[5]+l2[5]*l1[2];\n  }\n\n  Eigen::JacobiSVD< Eigen::MatrixXd > SVDARP(\n      AR,\n      Eigen::ComputeThinU | Eigen::ComputeThinV );\n\n  Eigen::VectorXd sigma_ = SVDARP.singularValues();\n  double pinvtoler_ =\n      sigma_(0)*numberCorrespondences*NumTraits<double>::epsilon();\n  Eigen::MatrixXd SigmaInverse_(9,9);\n  SigmaInverse_ = Eigen::MatrixXd::Zero(9,9);\n  for ( size_t i=0; i < 9; ++i)\n  {\n    double temp = sigma_(i);\n    if( temp > pinvtoler_ )\n      SigmaInverse_(i,i) = 1.0/temp;\n  }\n  \n  Eigen::MatrixXd ARP(9,numberCorrespondences);\n  ARP = SVDARP.matrixV()*SigmaInverse_*SVDARP.matrixU().transpose();\n\n  Eigen::MatrixXd B(numberCorrespondences,numberCorrespondences);\n  B = -Eigen::MatrixXd::Identity(numberCorrespondences,numberCorrespondences);\n  B = B + AR*ARP;\n\n  Eigen::MatrixXd C = B*AE;\n  \n  Eigen::JacobiSVD< Eigen::MatrixXd > SVDE(\n      C,\n      Eigen::ComputeThinU | Eigen::ComputeThinV );\n  Eigen::Matrix<double,9,1> e = SVDE.matrixV().col(8);\n\n  Eigen::MatrixXd E_temp(3,3);\n  E_temp.col(0) = e.block<3,1>(0,0);\n  E_temp.col(1) = e.block<3,1>(3,0);\n  E_temp.col(2) = e.block<3,1>(6,0);\n  essential_t E = E_temp.transpose();\n\n  Eigen::JacobiSVD< Eigen::MatrixXd > SVDR(\n      E,\n      Eigen::ComputeFullV | Eigen::ComputeFullU );\n\n  Eigen::Matrix3d W = Eigen::Matrix3d::Zero();\n  W(0,1) = -1.0;\n  W(1,0) = 1.0;\n  W(2,2) = 1.0;\n\n  // get possible rotation and translation vectors\n  rotation_t Ra = SVDR.matrixU() * W * SVDR.matrixV().transpose();\n  rotation_t Rb = SVDR.matrixU() * W.transpose() * SVDR.matrixV().transpose();\n\n  // change sign if det = -1\n  if( Ra.determinant() < 0 ) Ra = -Ra;\n  if( Rb.determinant() < 0 ) Rb = -Rb;\n\n  Ra.transposeInPlace();\n  Rb.transposeInPlace();\n\n  Eigen::MatrixXd A_tra(numberCorrespondences,3);\n  Eigen::MatrixXd A_trb(numberCorrespondences,3);\n  Eigen::VectorXd b_tra(numberCorrespondences);\n  Eigen::VectorXd b_trb(numberCorrespondences);\n\n  for( size_t i = 0; i < numberCorrespondences; i++ )\n  {\n    bearingVector_t d1 = adapter.getBearingVector1(indices[i]);\n    bearingVector_t d2 = adapter.getBearingVector2(indices[i]);\n    translation_t v1 = adapter.getCamOffset1(indices[i]);\n    translation_t v2 = adapter.getCamOffset2(indices[i]);\n    rotation_t R1 = adapter.getCamRotation1(indices[i]);\n    rotation_t R2 = adapter.getCamRotation2(indices[i]);\n\n    //unrotate the bearing-vectors to express everything in the body frame\n    d1 = R1*d1;\n    d2 = R2*d2;\n\n    A_tra(i,0) = d1[2]*d2[0]*Ra(1,0)+d1[2]*d2[1]*Ra(1,1)+d1[2]*d2[2]*Ra(1,2)\n                -d1[1]*d2[0]*Ra(2,0)-d1[1]*d2[1]*Ra(2,1)-d1[1]*d2[2]*Ra(2,2);\n    A_tra(i,1) = d1[0]*d2[0]*Ra(2,0)+d1[0]*d2[1]*Ra(2,1)+d1[0]*d2[2]*Ra(2,2)\n                -d1[2]*d2[0]*Ra(0,0)-d1[2]*d2[1]*Ra(0,1)-d1[2]*d2[2]*Ra(0,2);\n    A_tra(i,2) = d1[1]*d2[0]*Ra(0,0)+d1[1]*d2[1]*Ra(0,1)+d1[1]*d2[2]*Ra(0,2)\n                -d1[0]*d2[0]*Ra(1,0)-d1[0]*d2[1]*Ra(1,1)-d1[0]*d2[2]*Ra(1,2);\n\n    A_trb(i,0) = d1[2]*d2[0]*Rb(1,0)+d1[2]*d2[1]*Rb(1,1)+d1[2]*d2[2]*Rb(1,2)\n                -d1[1]*d2[0]*Rb(2,0)-d1[1]*d2[1]*Rb(2,1)-d1[1]*d2[2]*Rb(2,2);\n    A_trb(i,1) = d1[0]*d2[0]*Rb(2,0)+d1[0]*d2[1]*Rb(2,1)+d1[0]*d2[2]*Rb(2,2)\n                -d1[2]*d2[0]*Rb(0,0)-d1[2]*d2[1]*Rb(0,1)-d1[2]*d2[2]*Rb(0,2);\n    A_trb(i,2) = d1[1]*d2[0]*Rb(0,0)+d1[1]*d2[1]*Rb(0,1)+d1[1]*d2[2]*Rb(0,2)\n                -d1[0]*d2[0]*Rb(1,0)-d1[0]*d2[1]*Rb(1,1)-d1[0]*d2[2]*Rb(1,2);\n\n    Eigen::Vector3d temp1 = v1.cross(d1);\n    Eigen::Vector3d temp2 = v2.cross(d2);\n    b_tra(i) = -d1.dot(Ra*temp2) -temp1.dot(Ra*d2);\n    b_trb(i) = -d1.dot(Rb*temp2) -temp1.dot(Rb*d2);\n  }\n  \n  Eigen::JacobiSVD< Eigen::MatrixXd > SVDa(\n      A_tra,\n      Eigen::ComputeThinU | Eigen::ComputeThinV );\n\n  Eigen::VectorXd sigma = SVDa.singularValues();\n  double pinvtoler =\n      numberCorrespondences*sigma(0)*NumTraits<double>::epsilon();\n  Eigen::MatrixXd SigmaInverse(3,3);\n  SigmaInverse = Eigen::MatrixXd::Zero(3,3);\n  for ( size_t i=0; i < 3; ++i)\n  {\n    double temp = sigma(i);\n    if( temp > pinvtoler )\n      SigmaInverse(i,i) = 1.0/temp;\n  }\n\n  Eigen::MatrixXd PI(3,numberCorrespondences);\n  PI = SVDa.matrixV()*SigmaInverse*SVDa.matrixU().transpose();\n  Eigen::Vector3d ta = PI*b_tra;\n\n  Eigen::JacobiSVD< Eigen::MatrixXd > SVDb(\n      A_trb,\n      Eigen::ComputeThinU | Eigen::ComputeThinV );\n\n  sigma = SVDb.singularValues();\n  pinvtoler = numberCorrespondences*sigma(0)*NumTraits<double>::epsilon();\n  SigmaInverse = Eigen::MatrixXd::Zero(3,3);\n  for ( size_t i=0; i < 3; ++i)\n  {\n    double temp = sigma(i);\n    if( temp > pinvtoler )\n      SigmaInverse(i,i) = 1.0/temp;\n  }\n\n  PI = SVDb.matrixV()*SigmaInverse*SVDb.matrixU().transpose();\n  Eigen::Vector3d tb = PI*b_trb;\n\n  Eigen::VectorXd fita = A_tra * ta - b_tra;\n  Eigen::VectorXd fitb = A_trb * tb - b_trb;\n\n  transformation_t transformation;\n  if( fita.norm() < fitb.norm() )\n  {\n    transformation.block<3,3>(0,0) = Ra;\n    transformation.col(3) = ta;\n  }\n  else\n  {\n    transformation.block<3,3>(0,0) = Rb;\n    transformation.col(3) = tb;\n  }\n\n  return transformation;\n}\n\n}\n}\n\nopengv::transformation_t\nopengv::relative_pose::seventeenpt( const RelativeAdapterBase & adapter )\n{\n  Indices idx(adapter.getNumberCorrespondences());\n  return seventeenpt(adapter,idx);\n}\n\nopengv::transformation_t\nopengv::relative_pose::seventeenpt(\n    const RelativeAdapterBase & adapter,\n    const std::vector<int> & indices )\n{\n  Indices idx(indices);\n  return seventeenpt(adapter,idx);\n}\n\nnamespace opengv\n{\nnamespace relative_pose\n{\n\nstruct OptimizeNonlinearFunctor1 : OptimizationFunctor<double>\n{\n  RelativeAdapterBase & _adapter;\n  const Indices & _indices;\n\n  OptimizeNonlinearFunctor1(\n      RelativeAdapterBase & adapter,\n      const Indices & indices ) :\n      OptimizationFunctor<double>(6,indices.size()),\n      _adapter(adapter),\n      _indices(indices) {}\n\n  int operator()(const VectorXd &x, VectorXd &fvec) const\n  {\n    assert( x.size() == 6 );\n    assert( (unsigned int) fvec.size() == _indices.size());\n\n    //compute the current position\n    translation_t translation = x.block<3,1>(0,0);\n    cayley_t cayley = x.block<3,1>(3,0);\n    rotation_t rotation = math::cayley2rot(cayley);\n\n    Eigen::Matrix<double,4,1> p_hom;\n    p_hom[3] = 1.0;\n\n    for( size_t i = 0; i < _indices.size(); i++ )\n    {\n      translation_t cam1Offset = _adapter.getCamOffset1(_indices[i]);\n      rotation_t cam1Rotation = _adapter.getCamRotation1(_indices[i]);\n      translation_t cam2Offset = _adapter.getCamOffset2(_indices[i]);\n      rotation_t cam2Rotation = _adapter.getCamRotation2(_indices[i]);\n\n      translation_t directTranslation =\n          cam1Rotation.transpose() *\n          ((translation - cam1Offset) + rotation * cam2Offset);\n      rotation_t directRotation =\n          cam1Rotation.transpose() * rotation * cam2Rotation;\n\n      _adapter.sett12(directTranslation);\n      _adapter.setR12(directRotation);\n\n      transformation_t inverseSolution;\n      inverseSolution.block<3,3>(0,0) = directRotation.transpose();\n      inverseSolution.col(3) =\n          -inverseSolution.block<3,3>(0,0)*directTranslation;\n\n      p_hom.block<3,1>(0,0) =\n          opengv::triangulation::triangulate2(_adapter,_indices[i]);\n      bearingVector_t reprojection1 = p_hom.block<3,1>(0,0);\n      bearingVector_t reprojection2 = inverseSolution * p_hom;\n      reprojection1 = reprojection1 / reprojection1.norm();\n      reprojection2 = reprojection2 / reprojection2.norm();\n      bearingVector_t f1 = _adapter.getBearingVector1(_indices[i]);\n      bearingVector_t f2 = _adapter.getBearingVector2(_indices[i]);\n\n      //bearing-vector based outlier criterium (select threshold accordingly):\n      //1-(f1'*f2) = 1-cos(alpha) \\in [0:2]\n      double reprojError1 = 1.0 - (f1.transpose() * reprojection1);\n      double reprojError2 = 1.0 - (f2.transpose() * reprojection2);\n      double factor = 1.0;\n      fvec[i] = factor*(reprojError1 + reprojError2);\n    }\n\n    return 0;\n  }\n};\n\ntransformation_t optimize_nonlinear(\n    RelativeAdapterBase & adapter,\n    const Indices & indices )\n{\n  const int n=6;\n  VectorXd x(n);\n\n  x.block<3,1>(0,0) = adapter.gett12();\n  x.block<3,1>(3,0) = math::rot2cayley(adapter.getR12());\n\n  OptimizeNonlinearFunctor1 functor( adapter, indices );\n  NumericalDiff<OptimizeNonlinearFunctor1> numDiff(functor);\n  LevenbergMarquardt< NumericalDiff<OptimizeNonlinearFunctor1> >\n      lm(numDiff);\n\n  lm.resetParameters();\n  lm.parameters.ftol = 1.E1*NumTraits<double>::epsilon();\n  lm.parameters.xtol = 1.E1*NumTraits<double>::epsilon();\n  lm.parameters.maxfev = 1000;\n  lm.minimize(x);\n\n  transformation_t transformation;\n  transformation.col(3) = x.block<3,1>(0,0);\n  transformation.block<3,3>(0,0) = math::cayley2rot(x.block<3,1>(3,0));\n  return transformation;\n}\n\n}\n}\n\nopengv::transformation_t\nopengv::relative_pose::optimize_nonlinear( RelativeAdapterBase & adapter )\n{\n  Indices idx(adapter.getNumberCorrespondences());\n  return optimize_nonlinear(adapter,idx);\n}\n\nopengv::transformation_t\nopengv::relative_pose::optimize_nonlinear(\n    RelativeAdapterBase & adapter,\n    const std::vector<int> & indices )\n{\n  Indices idx(indices);\n  return optimize_nonlinear(adapter,idx);\n}\n\nEigen::MatrixXd opengv::relative_pose::block_matrix(const RelativeAdapterBase& adapter, Eigen::MatrixXd &L1, Eigen::MatrixXd &L2,\n\t\t\t\t\t\t    int numberCorrespondences)\n{\n  //std::cout << \"Enters block matrix function: \" << std::endl;\n  Eigen::MatrixXd M = Eigen::MatrixXd::Constant(36,36, 0.0);\n  L1 = Eigen::MatrixXd::Constant(6, numberCorrespondences, 0.0);\n  L2 = Eigen::MatrixXd::Constant(6, numberCorrespondences, 0.0);\n  Eigen::Matrix<double, 6, 1> l1 = Eigen::MatrixXd::Constant(6,1, 0.0);\n  Eigen::Matrix<double, 6, 1> l2 = Eigen::MatrixXd::Constant(6,1, 0.0);\n  Eigen::MatrixXd M1 = Eigen::MatrixXd::Constant(6,6, 0.0);\n  Eigen::MatrixXd M2 = Eigen::MatrixXd::Constant(6,6, 0.0);\n  for( size_t i = 0; i < (unsigned) numberCorrespondences; i++ )\n    {\n      bearingVector_t d1 = adapter.getBearingVector1(i);\n      bearingVector_t d2 = adapter.getBearingVector2(i);\n      translation_t v1 = adapter.getCamOffset1(i);\n      translation_t v2 = adapter.getCamOffset2(i);\n      rotation_t R1 = adapter.getCamRotation1(i);\n      rotation_t R2 = adapter.getCamRotation2(i);\n      //unrotate the bearing-vectors to express everything in the body frame\n      d1 = R1*d1;\n      d2 = R2*d2;\n      //generate the Plucker line coordinates\n      l1.block<3,1>(0,0) = d1;\n      l1.block<3,1>(3,0) = v1.cross(d1);\n      l2.block<3,1>(0,0) = d2;\n      l2.block<3,1>(3,0) = v2.cross(d2);\n      L1.block<6,1>(0,i) = l1;\n      L2.block<6,1>(0,i) = l2;\n      M1 = l1 * l1.transpose();\n      M2 = l2 * l2.transpose();\n      M = M + Eigen::kroneckerProduct(M2,M1);\n    }\n  Eigen::MatrixXd A(36,18);\n  A.block<36,3>(0,0) = M.block<36,3>(0,0);\n  A.block<36,3>(0,3) = M.block<36,3>(0,6);\n  A.block<36,3>(0,6) = M.block<36,3>(0,12);\n  A.block<36,3>(0,9) = M.block<36,3>(0,3) + M.block<36,3>(0,18);\n  A.block<36,3>(0,12) = M.block<36,3>(0,9) + M.block<36,3>(0,24);\n  A.block<36,3>(0,15) = M.block<36,3>(0,15) + M.block<36,3>(0,30);\n  Eigen::MatrixXd AE(A.block<36,9>(0,0));\n  Eigen::MatrixXd AR(A.block<36,9>(0,9));\n  Eigen::MatrixXd AE_inv_aux(AE.transpose() * AE);\n  AE_inv_aux = AE_inv_aux.inverse() * AE.transpose() * (-1.0);\n  Eigen::MatrixXd blockM(AE_inv_aux * AR);\n  //std::cout << \"\\nMatrix at the end of block matrix function\" << std::endl << blockM << std::endl;\n  return blockM;\n\n}\n\nEigen::Matrix3d opengv::relative_pose::exp_R( Eigen::Matrix3d & X )\n{\n\n  double phi = X.norm()/std::sqrt(2);\n  Eigen::Matrix3d X1 = X/phi;\n  Eigen::Matrix3d I = Eigen::Matrix< double, 3, 3 >::Identity();\n  I = I + std::sin(phi)*X1 + ( 1 - std::cos(phi) )*X1*X1;\n  return I;\n\n}\n\ndouble opengv::relative_pose::f_obj( Eigen::Matrix3d & essential_matrix, const Eigen::Matrix3d & R, const Eigen::MatrixXd & M,\n\t\t\t\t     const Eigen::MatrixXd & L1, const Eigen::MatrixXd & L2)\n{\n  Eigen::Matrix3d A11 = M.block<3,3>(0,0);Eigen::Matrix3d A12 = M.block<3,3>(0,3);Eigen::Matrix3d A13 = M.block<3,3>(0,6);\n  Eigen::Matrix3d A21 = M.block<3,3>(3,0);Eigen::Matrix3d A22 = M.block<3,3>(3,3);Eigen::Matrix3d A23 = M.block<3,3>(3,6);\n  Eigen::Matrix3d A31 = M.block<3,3>(6,0);Eigen::Matrix3d A32 = M.block<3,3>(6,3);Eigen::Matrix3d A33 = M.block<3,3>(6,6);\n\n  Eigen::Matrix3d M11 = Matrix<double, 3, 3 >::Constant(3,3,0.0);M11(0,0) = 1;\n  Eigen::Matrix3d M12 = Matrix<double, 3, 3 >::Constant(3,3,0.0);M12(1,0) = 1;\n  Eigen::Matrix3d M13 = Matrix<double, 3, 3 >::Constant(3,3,0.0);M13(2,0) = 1;\n  Eigen::Matrix3d M21 = Matrix<double, 3, 3 >::Constant(3,3,0.0);M21(0,1) = 1;\n  Eigen::Matrix3d M22 = Matrix<double, 3, 3 >::Constant(3,3,0.0);M22(1,1) = 1;\n  Eigen::Matrix3d M23 = Matrix<double, 3, 3 >::Constant(3,3,0.0);M23(2,1) = 1;\n  Eigen::Matrix3d M31 = Matrix<double, 3, 3 >::Constant(3,3,0.0);M31(0,2) = 1;\n  Eigen::Matrix3d M32 = Matrix<double, 3, 3 >::Constant(3,3,0.0);M32(1,2) = 1;\n  Eigen::Matrix3d M33 = Matrix<double, 3, 3 >::Constant(3,3,0.0);M33(2,2) = 1;\n\n\n  essential_matrix = A11 * R * M11 + A12 * R * M12 + A13 * R * M13 + A21 * R * M21 + A22 * R * M22 + A23 * R * M23 + A31 * R * M31 + A32 * R * M32 + A33 * R * M33;\n\n  int points = L1.cols();\n  Vector3d d1(0.0, 0.0, 0.0);\n  Vector3d m1(0.0, 0.0, 0.0);\n  Vector3d d2(0.0, 0.0, 0.0);\n  Vector3d m2(0.0, 0.0, 0.0);\n  Eigen::Matrix<double, 1, 1> epsilon = Eigen::MatrixXd::Constant(1,1,0.0);\n  double f = 0;\n  for(int i = 0; i < points; ++i){\n    d1 = L1.block<3,1>(0,i);\n    m1 = L1.block<3,1>(3,i);\n    d2 = L2.block<3,1>(0,i);\n    m2 = L2.block<3,1>(3,i);\n\n    epsilon = d1.transpose() * essential_matrix * d2 + d1.transpose() * R * m2 + m1.transpose() * R * d2;\n    epsilon = epsilon * epsilon;\n    f = f + epsilon(0,0);\n  }\n  return f;\n}\n\nEigen::Matrix3d opengv::relative_pose::D_x(const Eigen::Matrix3d & R, const Eigen::MatrixXd & M, const Eigen::MatrixXd & L1, const Eigen::MatrixXd & L2)\n{\n  Eigen::Matrix3d A11 = M.block<3,3>(0,0);Eigen::Matrix3d A12 = M.block<3,3>(0,3);Eigen::Matrix3d A13 = M.block<3,3>(0,6);\n  Eigen::Matrix3d A21 = M.block<3,3>(3,0);Eigen::Matrix3d A22 = M.block<3,3>(3,3);Eigen::Matrix3d A23 = M.block<3,3>(3,6);\n  Eigen::Matrix3d A31 = M.block<3,3>(6,0);Eigen::Matrix3d A32 = M.block<3,3>(6,3);Eigen::Matrix3d A33 = M.block<3,3>(6,6);\n\n  Eigen::Matrix3d M11 = Matrix<double, 3, 3 >::Constant(3,3,0.0);M11(0,0) = 1;\n  Eigen::Matrix3d M12 = Matrix<double, 3, 3 >::Constant(3,3,0.0);M12(1,0) = 1;\n  Eigen::Matrix3d M13 = Matrix<double, 3, 3 >::Constant(3,3,0.0);M13(2,0) = 1;\n  Eigen::Matrix3d M21 = Matrix<double, 3, 3 >::Constant(3,3,0.0);M21(0,1) = 1;\n  Eigen::Matrix3d M22 = Matrix<double, 3, 3 >::Constant(3,3,0.0);M22(1,1) = 1;\n  Eigen::Matrix3d M23 = Matrix<double, 3, 3 >::Constant(3,3,0.0);M23(2,1) = 1;\n  Eigen::Matrix3d M31 = Matrix<double, 3, 3 >::Constant(3,3,0.0);M31(0,2) = 1;\n  Eigen::Matrix3d M32 = Matrix<double, 3, 3 >::Constant(3,3,0.0);M32(1,2) = 1;\n  Eigen::Matrix3d M33 = Matrix<double, 3, 3 >::Constant(3,3,0.0);M33(2,2) = 1;\n\n  int points = L1.cols();\n  Vector3d d1(0.0, 0.0, 0.0);\n  Vector3d m1(0.0, 0.0, 0.0);\n  Vector3d d2(0.0, 0.0, 0.0);\n  Vector3d m2(0.0, 0.0, 0.0);\n\n  Eigen::Vector3d d1_11(0.0, 0.0, 0.0);\n  Eigen::Vector3d d1_12(0.0, 0.0, 0.0);\n  Eigen::Vector3d d1_13(0.0, 0.0, 0.0);\n  Eigen::Vector3d d1_21(0.0, 0.0, 0.0);\n  Eigen::Vector3d d1_22(0.0, 0.0, 0.0);\n  Eigen::Vector3d d1_23(0.0, 0.0, 0.0);\n  Eigen::Vector3d d1_31(0.0, 0.0, 0.0);\n  Eigen::Vector3d d1_32(0.0, 0.0, 0.0);\n  Eigen::Vector3d d1_33(0.0, 0.0, 0.0);\n\n  Eigen::Vector3d d2_11(0.0, 0.0, 0.0);\n  Eigen::Vector3d d2_12(0.0, 0.0, 0.0);\n  Eigen::Vector3d d2_13(0.0, 0.0, 0.0);\n  Eigen::Vector3d d2_21(0.0, 0.0, 0.0);\n  Eigen::Vector3d d2_22(0.0, 0.0, 0.0);\n  Eigen::Vector3d d2_23(0.0, 0.0, 0.0);\n  Eigen::Vector3d d2_31(0.0, 0.0, 0.0);\n  Eigen::Vector3d d2_32(0.0, 0.0, 0.0);\n  Eigen::Vector3d d2_33(0.0, 0.0, 0.0);\n  Eigen::Matrix3d devEpsilon = Eigen::Matrix3d::Constant(3,3,0.0);\n  Eigen::Matrix<double, 1, 1> epsilon = Eigen::MatrixXd::Constant(1,1,0.0);\n  Eigen::Matrix3d euclidean_gradient = Eigen::Matrix3d::Constant(3,3, 0.0);\n  Eigen::Matrix3d essential_matrix = A11 * R * M11 + A12 * R * M12 + A13 * R * M13 + A21 * R * M21 + A22 * R * M22 + A23 * R * M23 + A31 * R * M31 + A32 * R * M32 + A33 * R * M33;\n  for(int i = 0; i < points; ++i){\n    d1 = L1.block<3,1>(0,i);\n    m1 = L1.block<3,1>(3,i);\n    d2 = L2.block<3,1>(0,i);\n    m2 = L2.block<3,1>(3,i);\n\n    d1_11 = A11.transpose() * d1; d1_12 = A12.transpose() * d1; d1_13 = A13.transpose() * d1;\n    d1_21 = A21.transpose() * d1; d1_22 = A22.transpose() * d1; d1_23 = A23.transpose() * d1;\n    d1_31 = A31.transpose() * d1; d1_32 = A32.transpose() * d1; d1_33 = A33.transpose() * d1;\n\n    d2_11 = M11 * d2; d2_12 = M12 * d2; d2_13 = M13 * d2;\n    d2_21 = M21 * d2; d2_22 = M22 * d2; d2_23 = M23 * d2;\n    d2_31 = M31 * d2; d2_32 = M32 * d2; d2_33 = M33 * d2;\n\n    devEpsilon = d1_11 * d2_11.transpose() + d1_12 * d2_12.transpose() + d1_13 * d2_13.transpose() + d1_21 * d2_21.transpose() + d1_22 * d2_22.transpose() + d1_23 * d2_23.transpose() + d1_31 * d2_31.transpose() + d1_32 * d2_32.transpose() + d1_33 * d2_33.transpose() + d1 * m2.transpose() + m1 * d2.transpose();\n    epsilon = (d1.transpose() * essential_matrix * d2 ) + (d1.transpose() * R * m2) + (m1.transpose() * R * d2);\n    euclidean_gradient = euclidean_gradient + epsilon(0,0) * devEpsilon;\n  }\n  euclidean_gradient = 2 * euclidean_gradient;\n  return euclidean_gradient;\n}\n\n\nEigen::MatrixXd opengv::relative_pose::egea(const RelativeAdapterBase & adapter, double & tol, Eigen::Matrix3d & initial_guess, int numberCorrespondences)\n{\n\n  Eigen::MatrixXd L1 = Eigen::MatrixXd::Constant(3,3,0.0);\n  Eigen::MatrixXd L2 = Eigen::MatrixXd::Constant(3,3,0.0);\n  Eigen::MatrixXd M = block_matrix(adapter, L1, L2, numberCorrespondences);\n  Eigen::Matrix3d essential_matrix = Eigen::Matrix3d::Identity(3,3);\n  //std::cout << \"L1: \" << std::endl << L1 << std::endl;\n  //std::cout << \"L2: \" << std::endl << L2 << std::endl;\n  // Initial Gess\n  double g = 1.0;\n  double erro = 1.0;\n  int k = 0;\n\n  // temp variables\n  Eigen::MatrixXd GE = Eigen::MatrixXd::Constant(3, 4, 0.0);\n  Eigen::Matrix3d Xf0, Xf1, DX, Z, P, Pt, Q, Qt, Y, S, R;\n  double zz;\n  Eigen::Matrix3d X = initial_guess;\n  //std::cout << \"\\n\\nInitial guess\" << std::endl << X << std::endl;\n  while( erro > tol && k < 1e5 )\n    {\n      Xf0 = X;\n      DX  = D_x( X, M, L1, L2 );\n      Z   = DX*X.transpose() - X*DX.transpose();\n      zz  = 0.5*( Z*Z.transpose() ).trace();\n      Pt  = -g*Z;\n      P   = exp_R( Pt );\n      Q   = P*P; // this seems strange\n      Qt  = Q*X;\n\n      while( ( f_obj( essential_matrix, X, M, L1, L2 ) - f_obj( essential_matrix, Qt, M, L1, L2 ) ) >= g*zz  )\n\t{\n\n\t  g   = 2*g;\n\t  P   = Q;\n\t  Q   = P*P; // this seems strange\n\t  Qt  = Q*X;\n\n\t}\n      Qt = P*X;\n      while( f_obj( essential_matrix, X, M, L1, L2) - f_obj(essential_matrix, Qt, M, L1, L2 ) < 0.5*g*zz)\n\t{\n\n\t  //   if ( f_obj( M, N, X, beta) - f_obj( M, N, Qt, beta ) < tol )\n\t  //     break;\n\n\t  g  = 0.5*g;\n\t  Pt = -g*Z;\n\t  P  = exp_R( Pt );\n\t  Qt = P*X;\n\n\t}\n      double f = f_obj( essential_matrix, X, M, L1, L2);\n      X    = P*X;\n      Xf1  = X;\n      erro = ( Xf1 - Xf0 ).norm();\n      /*std::cout << \"\\nIteration: \" << k << std::endl;\n\tstd::cout << \"Rotation: \"    << std::endl << X << std::endl;\n\tstd::cout << \"Euclidean grad: \" << std::endl << DX << std::endl;\n\tstd::cout << \"Function value: \" << f << std::endl;\n\tstd::cout << \"Essential matrix: \" << essential_matrix << std::endl;*/\n      k++;\n    }\n\n  R=X;\n  double fobj = f_obj(essential_matrix, R, M, L1, L2);\n\n  Eigen::Matrix3d skew = essential_matrix * R.transpose();\n  // double fobj = f_obj( M, N, X, beta );\n  // std::cout << \"objective function result: \" << fobj << \", for the number of iterations: \" << k << std::endl << \"     and error: \" << erro << std::endl;\n  //std::cout << \"Rotation matrix obtained: \" << std::endl << R << std::endl;\n  GE(0,0) = R(0,0); GE(0,1) = R(0,1); GE(0,2) = R(0,2);\n  GE(1,0) = R(1,0); GE(1,1) = R(1,1); GE(1,2) = R(1,2);\n  GE(2,0) = R(2,0); GE(2,1) = R(2,1); GE(2,2) = R(2,2);\n  GE(0,3) = skew(2,1);\n  GE(1,3) = skew(0,2);\n  GE(2,3) = skew(1,0);\n\n  return GE;\n\n}\n", "meta": {"hexsha": "25a647230dac26ecb1e787b2a95cda23751d8a03", "size": 47408, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/relative_pose/methods.cpp", "max_stars_repo_name": "joaobcampos/article", "max_stars_repo_head_hexsha": "931fc014051a035e883eb922b4393985b68d9183", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-04-03T12:28:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-03T12:28:34.000Z", "max_issues_repo_path": "src/relative_pose/methods.cpp", "max_issues_repo_name": "joaobcampos/article", "max_issues_repo_head_hexsha": "931fc014051a035e883eb922b4393985b68d9183", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/relative_pose/methods.cpp", "max_forks_repo_name": "joaobcampos/article", "max_forks_repo_head_hexsha": "931fc014051a035e883eb922b4393985b68d9183", "max_forks_repo_licenses": ["BSD-3-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.6052269601, "max_line_length": 311, "alphanum_fraction": 0.6389006075, "num_tokens": 16169, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324713956856, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.47389715521591375}}
{"text": "\n/*************************************************************************\\\nLicense\n    Copyright (c) 2017 Kavvadias Ioannis.\n    \n    This file is part of SPHSimulator.\n    \n    Licensed under the MIT License. See LICENSE file in the project root for \n    full license information.  \n\n\\************************************************************************/\n\n#include <iostream>\n#include <glm/glm.hpp>\n#include <glm/gtx/norm.hpp>\n#include <numeric>\n\n#include \"SPHSolver.hpp\"\n#include \"Settings.hpp\"\n#include \"Kernels.hpp\"\n#include \"Reorderer.hpp\"\n#include \"Statistics/Statistics.hpp\"\n\n#include \"Parallel/Parallel.hpp\"\n\n#include <boost/range/combine.hpp>\n#include <boost/range/algorithm/for_each.hpp>\n\n//********************************************************************************\nvoid SPHSolver::init()\n//********************************************************************************\n{\n  neibhs_.setHashTable(BoundaryConditions::bndBox.minPos(),BoundaryConditions::bndBox.delta());\n  //neibhs_.writeGridRAW(\"neiGrid\");\n\n  cloud_.reserve(SPHSettings::NParticles);\n\n  if (SPHSettings::SPHstep==SPHSettings::Solver::PCISPH)\n  {\n    //calculate delta\n    glm::dvec2 cntParticle(0.0);\n    glm::dvec2 offParticle(0.0);\n    glm::dvec2 gradWij(0.0);\n    double     dotGradWij(0.0);\n    for (int i=-2;i<=2;i++)\n    {\n      for (int j=-2;j<=2;j++)\n      {\n        if (i==0&&j==0) continue;\n        offParticle = glm::dvec2(i*SPHSettings::initDx,j*SPHSettings::initDx);\n        glm::dvec2 rij = cntParticle-offParticle;\n        double dist = glm::length(rij);\n        glm::dvec2 tmpGradWij = Kernel::poly6::gradW(rij,dist)\n          *Kernel::poly6::gradW_coeff();\n        gradWij += tmpGradWij;\n        dotGradWij += glm::dot(tmpGradWij,tmpGradWij);\n      }\n    }\n    double beta = SPHSettings::particleMass * SimulationSettings::dt * SPHSettings::dParticleDensity;\n    beta *= beta;\n    beta *= 2.0;\n\n    delta_ =  - 1./(beta*(-glm::dot(gradWij,gradWij)-dotGradWij));\n  }\n\n  if (InitialConditions::particleGeneration==InitialConditions::ALLIN)\n  {\n    //initialize field Particles\n    unsigned nPart = 0;\n    unsigned i = 0;\n    while (nPart<SPHSettings::NParticles)\n    {\n      for (unsigned j=0;j<SPHSettings::LParticles;j++)\n      {\n        if (cloud_.size()>=SPHSettings::NParticles) break;\n        Particle p;\n        p.get<Attr::ePosition>() = glm::dvec2\n          (\n           InitialConditions::particleInitPos.x+(SPHSettings::initDx*(double(j)+0.5)),\n           InitialConditions::particleInitPos.y+SPHSettings::initDx*(double(i)+0.5)\n          ); \n        p.get<Attr::eVelocity>() = InitialConditions::particleInitVel; \n        p.get<Attr::eDensErr>()  = SPHSettings::particleDensity;\n        p.get<Attr::eDDensity>() = SPHSettings::dParticleDensity;\n        p.get<Attr::eMass>()     = SPHSettings::particleMass;\n        nPart++;\n        cloud_.push_back(p);\n      }\n      i++;\n    }\n  }\n  else\n  {\n    //particles will be generated in generateParticles()\n  }\n\n  neibhs_.clear();\n  neibhs_.findNei(cloud_);\n  updateNei();\n  calcDensity();\n}\n\n//********************************************************************************\nvoid SPHSolver::WCSPHStep() \n//********************************************************************************\n{\n  calcDensity();\n  calcPressure();\n  calcNormal();\n\n  //calc forces\n  calcPressForces();\n  calcViscForces();\n  calcSurfForces();\n  calcOtherForces();\n\n  //combine forces and update values\n  {\n    static auto updatePosTimerID  = Statistics::createTimer(\"SPHSolver::WCSPH::updatePosTimer\");\n    Statistics::TimerGuard g(updatePosTimerID);\n\n    auto& particlePos = cloud_.get<Attr::ePosition>();\n    auto& particleVel = cloud_.get<Attr::eVelocity>();\n    const auto& particleFPress = cloud_.get<Attr::ePressForce>();\n    const auto& particleFVisc  = cloud_.get<Attr::eViscForce >();\n    const auto& particleFSurf  = cloud_.get<Attr::eSurfForce >();\n    const auto& particleFOther = cloud_.get<Attr::eOtherForce>();\n    const auto& particleDDens  = cloud_.get<Attr::eDDensity  >();\n\n    auto& particleFTotal = cloud_.get<Attr::eTotalForce>();\n\n    Parallel::For (cloud_.size(), [ &particlePos,   &particleVel,    &particleFPress, &particleFVisc,\n                                    &particleFSurf, &particleFOther, &particleDDens,  &particleFTotal\n                                  ] (size_t iPart)\n    {\n      particleFTotal[iPart] = particleFPress[iPart] + particleFVisc [iPart]\n                            + particleFSurf [iPart] + particleFOther[iPart];\n\n      particleVel[iPart] += SimulationSettings::dt*particleDDens[iPart]*particleFTotal[iPart];\n      particlePos[iPart] += SimulationSettings::dt*particleVel[iPart];\n    });\n  }\n}\n\n//********************************************************************************\nvoid SPHSolver::PCISPHStep() \n//********************************************************************************\n{\n  auto& particlePos = cloud_.get<Attr::ePosition>();\n  auto& particleVel = cloud_.get<Attr::eVelocity>();\n  auto& particleFTot = cloud_.get<Attr::eTotalForce>();\n  const auto& particleFPress  = cloud_.get<Attr::ePressForce>();\n  const auto& particleDDens   = cloud_.get<Attr::eDDensity>();\n  const auto& particleDensErr = cloud_.get<Attr::eDensErr>();\n\n  calcDensity();\n  calcNormal();\n  \n  //calc forces\n  calcViscForces();\n  calcSurfForces();\n  calcOtherForces();\n\n  const size_t nPart = cloud_.size();\n  {\n    static auto updatePosTimerID  = Statistics::createTimer(\"SPHSolver::PCISPH::updatePosTimer\");\n    Statistics::TimerGuard g(updatePosTimerID);\n\n    const auto& particleFVisc  = cloud_.get<Attr::eViscForce >();\n    const auto& particleFSurf  = cloud_.get<Attr::eSurfForce >();\n    const auto& particleFOther = cloud_.get<Attr::eOtherForce>();\n\n    auto& particleFTotal = cloud_.get<Attr::eTotalForce>();\n\n    Parallel::For (nPart, [ &particleFTotal, &particleVel,    &particlePos, &particleFVisc,\n                            &particleFSurf,  &particleFOther, &particleDDens\n                          ](size_t iPart){\n      particleFTotal[iPart] = particleFVisc [iPart]\n                            + particleFSurf [iPart]\n                            + particleFOther[iPart];\n\n      particleVel[iPart] += SimulationSettings::dt*particleDDens[iPart]*particleFTotal[iPart];\n      particlePos[iPart] += SimulationSettings::dt*particleVel[iPart];\n    });\n  }\n\n  double densErr=SPHSettings::particleDensity;\n  int iter=0;\n\n  {\n    static auto pressForceTimerID = Statistics::createTimer(\"SPHSolver::PCISPH::pressForceTimer\");\n    Statistics::TimerGuard g(pressForceTimerID);\n\n    //calculate pressure and pressure force\n    initPressure();\n    const double targetDensErr = SPHSettings::densityErr*SPHSettings::particleDensity;\n    while(densErr>targetDensErr && iter<500)\n    {\n      updateNei();\n      calcDensity();\n      calcDensityErr();\n      updatePressure();\n\n      auto itMax = std::max_element(particleDensErr.begin(), particleDensErr.end());\n      densErr = (itMax != particleDensErr.end()) ? (*itMax) : 0.;\n\n      if (iter==0)\n      iter++;\n\n      calcPressForces();\n\n      const double dt = SimulationSettings::dt;\n\n      Parallel::For (nPart, [ &particleFTot, &particleFPress, &particleVel,\n                              &particlePos,  &particleDDens, dt\n                            ] (size_t iPart){\n        const glm::dvec2 iPress = particleFPress[iPart];\n        particleFTot[iPart] += iPress;\n\n        glm::dvec2 update = dt*particleDDens[iPart]*iPress;\n        particleVel[iPart] += update;\n        particlePos[iPart] += dt*update;\n      });\n    }\n  }\n}\n\n//********************************************************************************\nbool SPHSolver::step() \n//********************************************************************************\n{\n  static int iReorder = 0;\n  iReorder++;\n\n  auto& particleNei = cloud_.get<Attr::eNei>();\n  boost::for_each(particleNei, [](auto& v){ v.clear();});\n\n  if(iReorder == 100)\n  {\n    Reorderer::reorderCloud(cloud_);\n    iReorder = 0;\n  }\n\n  generateParticles();\n\n  neibhs_.clear();\n\n  neibhs_.findNei(cloud_);\n\n  updateNei();\n\n  {\n    static auto stepTimerID      = Statistics::createTimer(\"SPHSolver::Step::SPHsolver\");\n    Statistics::TimerGuard g(stepTimerID);\n\n    switch (SPHSettings::SPHstep)\n    {\n      case (SPHSettings::Solver::WCSPH):\n        {\n          WCSPHStep();\n          break;\n        }\n      case (SPHSettings::Solver::PCISPH):\n        {\n          PCISPHStep();\n          break;\n        }\n      default:\n        {\n          std::cerr<<\"Invalid SPHSettings::Solver\"<<std::endl;\n          exit(1);\n        }\n    }\n    SimulationSettings::updateSimTime();\n  }\n\n  return (!SimulationSettings::breakLoop());\n}\n\n//********************************************************************************\nvoid SPHSolver::generateParticles()\n//********************************************************************************\n{\n  static double genTime = 0;\n  static double dtGenFaucet = 0.51*Kernel::SmoothingLength::h\n                   /(glm::length(InitialConditions::particleInitVel)+1.e-8);\n\n  if (cloud_.size()>=SPHSettings::NParticles) return;\n   \n  switch(InitialConditions::particleGeneration)\n  {\n    case (InitialConditions::FAUCET):\n    {\n      if (SimulationSettings::simTime-genTime>=dtGenFaucet)\n      {\n        glm::dvec2 initVelNormalized = glm::normalize(InitialConditions::particleInitVel);\n        glm::dvec2 generationDirection = glm::dvec2(-initVelNormalized.y,initVelNormalized.x);\n        //std::cout<<\"generating\"<<std::endl;\n        if (cloud_.size()<SPHSettings::NParticles)\n        {\n          for (unsigned i=0;i<SPHSettings::LParticles;i++)\n          {\n            if (cloud_.size()>=SPHSettings::NParticles) break;\n            Particle active;\n            active.get<Attr::ePosition>() = InitialConditions::particleInitPos + i*SPHSettings::initDx*generationDirection;\n            active.get<Attr::eVelocity>() = InitialConditions::particleInitVel;\n            active.get<Attr::eMass>()     = SPHSettings::particleMass;\n            cloud_.push_back(active);\n          }\n        }\n        genTime = SimulationSettings::simTime;\n      }\n      break;\n    }\n    case (InitialConditions::DRIPPING):\n    {\n      if (SimulationSettings::simTime-genTime>=InitialConditions::particleGenTime)\n      {\n        //std::cout<<\"generating\"<<std::endl;\n        if (cloud_.size()<SPHSettings::NParticles)\n        {\n          //double     radius = 0.3*double(SPHSettings::LParticles)*SPHSettings::initDx; \n          double     radius = 0.4*double(SPHSettings::LParticles)*SPHSettings::initDx; \n          double     offset = 0.5*SPHSettings::initDx*double(SPHSettings::LParticles-1);\n          glm::dvec2 center = InitialConditions::particleInitPos + glm::dvec2(offset,offset);\n\n          for (unsigned i=0;i<SPHSettings::LParticles;i++)\n          {\n            for (unsigned j=0;j<SPHSettings::LParticles;j++)\n            {\n              if (cloud_.size()>=SPHSettings::NParticles) break;\n              glm::dvec2 pos(InitialConditions::particleInitPos + glm::dvec2(SPHSettings::initDx*i,SPHSettings::initDx*j));\n              double dist = glm::length(pos-center);\n              if (dist>radius) continue;\n              Particle active;\n              active.get<Attr::ePosition>() = pos;\n              active.get<Attr::eVelocity>() = InitialConditions::particleInitVel;\n              active.get<Attr::eMass    >() = SPHSettings::particleMass;\n              cloud_.push_back(active);\n            }\n          }\n        }\n        genTime = SimulationSettings::simTime;\n      }\n      break;\n    }\n    case (InitialConditions::ALLIN):\n    {\n      std::cerr<<\"SPHSolver::generateParticles::ALLIN - Should be in here!!\"<<std::endl;\n      exit(1);\n    }\n    default: {}\n  }\n}\n\n//********************************************************************************\nvoid SPHSolver::updateNei()\n//********************************************************************************\n{\n  static auto updateNeiTimerID = Statistics::createTimer(\"SPHSolver::updateNeiTime\");\n  Statistics::TimerGuard updateNeiTimerGuard(updateNeiTimerID);\n\n  const auto& particlePos = cloud_.get<Attr::ePosition>();\n  auto& particleNei = cloud_.get<Attr::eNei>();\n\n  Parallel::For (cloud_.size(), [ &particlePos, &particleNei ] (size_t iPart) {\n    const glm::dvec2 iPos = particlePos[iPart];\n    for ( Neigbhor& iPartNeiI :  particleNei[iPart] )\n    {\n        const glm::dvec2 dir = iPos-particlePos[iPartNeiI.ID];\n        iPartNeiI.dir  = dir;\n        iPartNeiI.dist = glm::length(dir);\n    }\n  });\n}\n\n//********************************************************************************\nvoid SPHSolver::calcDensity()\n//********************************************************************************\n{\n  static auto densCalcTimerID   = Statistics::createTimer(\"SPHSolver::densCalcTimer\");\n  Statistics::TimerGuard densGuard(densCalcTimerID);\n\n  const auto& particleMass = cloud_.get<Attr::eMass>();\n  const auto& particleNei  = cloud_.get<Attr::eNei>();\n\n  auto& particleDens  = cloud_.get<Attr::eDensity>();\n  auto& particleDDens = cloud_.get<Attr::eDDensity>();\n\n  const double Wcoeff = Kernel::poly6::W_coeff();\n\n  Parallel::For (cloud_.size(), [ &particleMass, &particleNei,\n                                  &particleDens, &particleDDens, Wcoeff\n                                ] (size_t iPart) {\n    const auto& iNei = particleNei[iPart];\n\n    double dens = 0.0;\n\n    for (const Neigbhor& nei : iNei)\n    {\n        unsigned jPart = nei.ID;\n\n        dens += particleMass[jPart]*Kernel::poly6::W(nei.dist);\n    }\n    dens*=Wcoeff;\n\n    particleDens[iPart]  = dens;\n    particleDDens[iPart] = 1./dens;\n  });\n}\n\n//********************************************************************************\nvoid SPHSolver::calcDensityErr()\n//********************************************************************************\n{\n  static auto densErrCalcTimerID   = Statistics::createTimer(\"SPHSolver::densErrCalcTimer\");\n  Statistics::TimerGuard densErrGuard(densErrCalcTimerID);\n\n  const auto& particleDens = cloud_.get<Attr::eDensity>();\n  auto& particleDensErr = cloud_.get<Attr::eDensErr>();\n\n  const double pDens = SPHSettings::particleDensity;\n\n  Parallel::For (cloud_.size(), [ &particleDensErr, &particleDens, pDens ] (size_t iPart) {\n    particleDensErr[iPart] = particleDens[iPart] - pDens;\n  });\n}\n\n//********************************************************************************\nvoid SPHSolver::initPressure()\n//********************************************************************************\n{\n  auto& particlePress = cloud_.get<Attr::ePressure>();\n  Parallel::For (cloud_.size(), [ &particlePress ] (size_t iPart) {\n    particlePress[iPart]=0.0;\n  });\n}\n\n//********************************************************************************\nvoid SPHSolver::calcPressure()\n//********************************************************************************\n{\n  static auto pressCalcTimerID   = Statistics::createTimer(\"SPHSolver::pressureCalcTimer\");\n  Statistics::TimerGuard pressGuard(pressCalcTimerID);\n\n  const auto& particleDens = cloud_.get<Attr::eDensity>();\n  auto& particlePress = cloud_.get<Attr::ePressure>();\n\n  const double stiff = SPHSettings::stiffness;\n  const double pDens = SPHSettings::particleDensity;\n\n  Parallel::For (cloud_.size(), [ &particlePress, &particleDens, stiff, pDens ] (size_t iPart) {\n    //p = k(rho-rho0)\n    particlePress[iPart] = fmax(stiff*(particleDens[iPart] - pDens), 0.0);\n  });\n}\n\n//********************************************************************************\nvoid SPHSolver::calcNormal()\n//********************************************************************************\n{\n  static auto normalCalcTimerID   = Statistics::createTimer(\"SPHSolver::normalCalcTimer\");\n  Statistics::TimerGuard normalGuard(normalCalcTimerID);\n\n  const auto& particleMass  = cloud_.get<Attr::eMass>();\n  const auto& particleDDens = cloud_.get<Attr::eDDensity>();\n  const auto& particleNei  = cloud_.get<Attr::eNei>();\n  auto& particleNormal = cloud_.get<Attr::eNormal>();\n\n  Parallel::For (cloud_.size(), [ &particleMass, &particleDDens, &particleNei, &particleNormal] (size_t iPart) {\n    const auto& iNei = particleNei[iPart];\n\n    glm::dvec2 norm (0.0);\n\n    for (const Neigbhor& nei : iNei)\n    {\n        unsigned jPart = nei.ID;\n\n        norm += particleMass[jPart]*particleDDens[jPart]\n              *Kernel::poly6::gradW(nei.dir, nei.dist);\n    }\n    norm *= Kernel::poly6::gradW_coeff()*Kernel::SmoothingLength::h;\n    particleNormal[iPart] = norm;\n  });\n}\n\n\n//********************************************************************************\nvoid SPHSolver::updatePressure()\n//********************************************************************************\n{\n  static auto updatePressTimerID   = Statistics::createTimer(\"SPHSolver::updatePressure\");\n  Statistics::TimerGuard updatePressGuard(updatePressTimerID);\n\n  const auto& particleDensErr = cloud_.get<Attr::eDensErr>();\n  auto& particlePress = cloud_.get<Attr::ePressure>();\n\n  const double delta = delta_;\n\n  Parallel::For (cloud_.size(), [ &particlePress, &particleDensErr, delta] (size_t iPart) {\n    particlePress[iPart] = fmax(delta*particleDensErr[iPart],0.0);\n    //particlePress[iPart] = delta*particleDensErr[iPart];\n  });\n}\n\n\n//********************************************************************************\nvoid SPHSolver::calcOtherForces()\n//********************************************************************************\n{\n  static auto otherForceTimerID = Statistics::createTimer(\"SPHSolver::otherForceTimer\");\n  Statistics::TimerGuard otherForceGuard(otherForceTimerID);\n\n  const auto& particlePos = cloud_.get<Attr::ePosition>();\n  const auto& particleDens = cloud_.get<Attr::eDensity>();\n  auto& particleVel = cloud_.get<Attr::eVelocity>();\n  auto& particleFOther = cloud_.get<Attr::eOtherForce>();\n\n  const glm::dvec2 grav = SPHSettings::grav;\n\n  Parallel::For (cloud_.size(), [ &particlePos, &particleDens, &particleVel, &particleFOther, grav] (size_t iPart) {\n    //gravity\n    particleFOther[iPart] = grav;\n\n    //boundary forces\n    glm::dvec2 iPos = particlePos[iPart];\n    glm::dvec2 bndPos(0.0,0.0);\n    glm::dvec2 tmpiPos(0.0,0.0);\n    double W0 = Kernel::poly6::W(0.0)*Kernel::poly6::W_coeff();\n    double mult = 2.0;\n    double scaledh  = mult*Kernel::SmoothingLength::h;\n    double dScaledh = 1./scaledh;\n    if (iPos.x-BoundaryConditions::bndBox.minX()<scaledh)\n    {\n      if (iPos.x>BoundaryConditions::bndBox.minX())\n      {\n        tmpiPos = glm::dvec2(iPos.x,0.0)*dScaledh;\n        bndPos  = glm::dvec2(BoundaryConditions::bndBox.minX(),0.0)*dScaledh;\n        double dist = glm::length(tmpiPos-bndPos);\n        particleFOther[iPart].x+=BoundaryConditions::bndCoeff\n                                *Kernel::poly6::W(dist)\n                                *Kernel::poly6::W_coeff();\n      }\n      else\n      {\n        particleVel[iPart].x=0.;\n        particleFOther[iPart].x+=BoundaryConditions::bndCoeff*W0;\n      }\n    }\n    else if (BoundaryConditions::bndBox.maxX()-iPos.x<scaledh)\n    {\n      if (iPos.x<BoundaryConditions::bndBox.maxX())\n      {\n        tmpiPos = glm::dvec2(iPos.x,0.0)*dScaledh;\n        bndPos  = glm::dvec2(BoundaryConditions::bndBox.maxX(),0.0)*dScaledh;\n        double dist = glm::length(tmpiPos-bndPos);\n        particleFOther[iPart].x-=BoundaryConditions::bndCoeff\n                                *Kernel::poly6::W(dist)\n                                *Kernel::poly6::W_coeff();\n      }\n      else\n      {\n        particleVel[iPart].x=0.;\n        particleFOther[iPart].x-=BoundaryConditions::bndCoeff*W0;\n      }\n    }\n    if (iPos.y-BoundaryConditions::bndBox.minY()<scaledh)\n    {\n      if (iPos.y>BoundaryConditions::bndBox.minY())\n      {\n        tmpiPos = glm::dvec2(0.0,iPos.y)*dScaledh;\n        bndPos  = glm::dvec2(0.0,BoundaryConditions::bndBox.minY())*dScaledh;\n        double dist = glm::length(tmpiPos-bndPos);\n        particleFOther[iPart].y+=BoundaryConditions::bndCoeff\n                               *Kernel::poly6::W(dist)\n                               *Kernel::poly6::W_coeff();\n      }\n      else\n      {\n        particleVel[iPart].y=0.;\n        particleFOther[iPart].y+=BoundaryConditions::bndCoeff*W0;\n      }\n    }\n    else if (BoundaryConditions::bndBox.maxY()-iPos.y<scaledh)\n    {\n      if (iPos.y>BoundaryConditions::bndBox.maxY())\n      {\n        tmpiPos = glm::dvec2(0.0,iPos.y)*dScaledh;\n        bndPos  = glm::dvec2(0.0,BoundaryConditions::bndBox.maxY())*dScaledh;\n        double dist = glm::length(tmpiPos-bndPos);\n        particleFOther[iPart].y-=BoundaryConditions::bndCoeff\n                                *Kernel::poly6::W(dist)\n                                *Kernel::poly6::W_coeff();\n      }\n      else\n      {\n        particleVel[iPart].y=0.;\n        particleFOther[iPart].y-=BoundaryConditions::bndCoeff*W0;\n      }\n    }\n\n    particleFOther[iPart] *= particleDens[iPart];\n  });\n}\n\n//********************************************************************************\nvoid SPHSolver::calcPressForces()\n//********************************************************************************\n{\n  static auto pressForceTimerID = Statistics::createTimer(\"SPHSolver::pressForceTimer\");\n  Statistics::TimerGuard pressForceGuard(pressForceTimerID);\n\n  const auto& particleMass  = cloud_.get<Attr::eMass>();\n  const auto& particleDDens = cloud_.get<Attr::eDDensity>();\n  const auto& particlePress = cloud_.get<Attr::ePressure>();\n  const auto& particleNei   = cloud_.get<Attr::eNei>();\n  auto& particleFPress = cloud_.get<Attr::ePressForce>();\n\n  Parallel::For (cloud_.size(), [ &particleMass,  &particleDDens, &particlePress,\n                                  &particleNei, &particleFPress\n                                ] (size_t iPart) {\n    const auto& iNei = particleNei[iPart];\n\n    glm::dvec2 Fp = glm::dvec2(0.0);\n    const double iPress = particlePress[iPart];\n\n    for (const Neigbhor& nei : iNei)\n    {\n      unsigned jPart = nei.ID;\n      if (iPart==jPart) continue;\n\n      Fp+=particleMass[jPart]*particleDDens[jPart]\n         *(iPress + particlePress[jPart])\n         *Kernel::spiky::gradW(nei.dir,nei.dist);\n    }\n\n    Fp*=-0.5*Kernel::spiky::gradW_coeff();\n    \n    particleFPress[iPart] = Fp;\n  });\n}\n\n//********************************************************************************\nvoid SPHSolver::calcViscForces()\n//********************************************************************************\n{\n  static auto viscForceTimerID  = Statistics::createTimer(\"SPHSolver::viscForceTimer\");\n  Statistics::TimerGuard viscForceGuard(viscForceTimerID);\n  \n  const auto& particleVel   = cloud_.get<Attr::eVelocity>();\n  const auto& particleMass  = cloud_.get<Attr::eMass>();\n  const auto& particleDDens = cloud_.get<Attr::eDDensity>();\n  const auto& particleNei   = cloud_.get<Attr::eNei>();\n  auto& particleFVisc = cloud_.get<Attr::eViscForce>();\n  \n  Parallel::For (cloud_.size(), [ &particleVel, &particleMass, &particleDDens,\n                                  &particleNei, &particleFVisc\n                                ] (size_t iPart) {\n    glm::dvec2 Fv = glm::dvec2(0.0);\n  \n    glm::dvec2 iVel = particleVel[iPart];\n    const auto& iNei = particleNei[iPart];\n  \n    for (const Neigbhor& nei : iNei)\n    {\n      unsigned jPart = nei.ID;\n      if (iPart==jPart) continue;\n  \n      Fv+= particleMass[jPart]\n         *particleDDens[jPart]\n         *(particleVel[jPart]-iVel)\n         *Kernel::visc::laplW(nei.dist);\n    }\n    Fv*=SPHSettings::viscosity*Kernel::visc::laplW_coeff();\n  \n    particleFVisc[iPart] = Fv;\n  });\n}\n\n//********************************************************************************\nvoid SPHSolver::calcSurfForces()\n//********************************************************************************\n{\n  static auto surfForceTimerID  = Statistics::createTimer(\"SPHSolver::surfForceTimer\");\n  Statistics::TimerGuard surfForceGuard(surfForceTimerID);\n\n  const auto& particleNormal = cloud_.get<Attr::eNormal>();\n  const auto& particleMass = cloud_.get<Attr::eMass>();\n  const auto& particleDens = cloud_.get<Attr::eDensity>();\n  const auto& particleNei  = cloud_.get<Attr::eNei>();\n  auto& particleFSurf = cloud_.get<Attr::eSurfForce>();\n\n  Parallel::For (cloud_.size(), [ &particleNormal, &particleMass, &particleDens,\n                                  &particleNei, &particleFSurf\n                                ] (size_t iPart) {\n    glm::dvec2 Fcohesion  = glm::dvec2(0.0);\n    glm::dvec2 Fcurvature = glm::dvec2(0.0);\n    double correction = 0.0;\n\n    const glm::dvec2 iNorm = particleNormal[iPart];\n    const double iMass = particleMass[iPart];\n    const double iDens = particleDens[iPart];\n    const auto&  iNei  = particleNei[iPart];\n\n    for (const Neigbhor& nei : iNei)\n    {\n      const unsigned jPart = nei.ID;\n      //std::cout<<\" \"<<jPart;\n      if (iPart==jPart) continue;\n\n      correction = 2.*SPHSettings::particleDensity/(iDens + particleDens[jPart]);\n\n      Fcohesion+= correction\n             *iMass*particleMass[jPart]\n             *Kernel::surface::C(nei.dist)\n             *nei.dir/nei.dist;\n\n      Fcurvature+= correction\n             *iMass\n             *(iNorm - particleNormal[jPart]);\n    }\n\n    Fcohesion *= Kernel::surface::C_coeff();\n\n    particleFSurf[iPart] = -SPHSettings::surfTension\n                         * iDens\n                         * (Fcohesion+Fcurvature);\n  });\n}\n\n//********************************************************************************\ndouble SPHSolver::calcCFL() const\n//********************************************************************************\n{\n  static auto clfTimerID  = Statistics::createTimer(\"SPHSolver::calcCFL\");\n  Statistics::TimerGuard clfGuard(clfTimerID);\n\n  const auto& particleVel = cloud_.get<Attr::eVelocity>();\n\n  double vMax = 0.0;\n\n  for (size_t iPart = 0, nPart = cloud_.size(); iPart<nPart; ++iPart) \n  {\n    double vLen2 = glm::length2(particleVel[iPart]);\n    if (vLen2 > vMax) vMax = vLen2;\n  }\n\n  double maxDt = 0.4*Kernel::SmoothingLength::h/(sqrt(vMax)+1.e-5);\n  double CFL = SimulationSettings::dt/maxDt;\n  return CFL;\n}\n\n//********************************************************************************\ndouble SPHSolver::calcKineticEnergy() const\n//********************************************************************************\n{\n  static auto kineticTimerID  = Statistics::createTimer(\"SPHSolver::calcKineticEnergy\");\n  Statistics::TimerGuard kinetickGuard(kineticTimerID);\n\n  const auto& particleVel  = cloud_.get<Attr::eVelocity>();\n  const auto& particleMass = cloud_.get<Attr::eMass>();\n  auto accumRange = boost::combine(particleMass, particleVel);\n\n  double kEnergy = 0.5*std::accumulate(accumRange.begin(), accumRange.end(), 0.,\n    [](double k, const auto& elem) {\n      const double mass = boost::get<0>(elem);\n      const glm::dvec2& vel = boost::get<1>(elem);\n      return k + mass*glm::dot(vel, vel);\n    }\n  );\n\n  return kEnergy;\n}\n\n", "meta": {"hexsha": "e475f49541bb6cd85fae6910adcaffc9e532c416", "size": 26893, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Simulation/SPHSolver.cpp", "max_stars_repo_name": "DLancer999/SPHSimulator", "max_stars_repo_head_hexsha": "4f2f3a29d9769e62a9cae3d036b3e09dac99e305", "max_stars_repo_licenses": ["MIT"], "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/SPHSolver.cpp", "max_issues_repo_name": "DLancer999/SPHSimulator", "max_issues_repo_head_hexsha": "4f2f3a29d9769e62a9cae3d036b3e09dac99e305", "max_issues_repo_licenses": ["MIT"], "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/SPHSolver.cpp", "max_forks_repo_name": "DLancer999/SPHSimulator", "max_forks_repo_head_hexsha": "4f2f3a29d9769e62a9cae3d036b3e09dac99e305", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-03T08:21:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-03T08:21:46.000Z", "avg_line_length": 34.7006451613, "max_line_length": 123, "alphanum_fraction": 0.5589930465, "num_tokens": 6868, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.831143060406073, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.47362907667687765}}
{"text": "#include \"drake/examples/kuka_iiwa_arm/kuka_torque_controller.h\"\n\n#include <Eigen/Dense>\n#include <gtest/gtest.h>\n\n#include \"drake/common/test_utilities/eigen_matrix_compare.h\"\n#include \"drake/examples/kuka_iiwa_arm/iiwa_common.h\"\n#include \"drake/multibody/parsing/parser.h\"\n\nnamespace drake {\nnamespace examples {\nnamespace kuka_iiwa_arm {\n\nusing drake::systems::BasicVector;\n\nnamespace {\nEigen::VectorXd CalcGravityCompensationTorque(\n    const multibody::MultibodyPlant<double>& plant,\n    const Eigen::VectorXd& q,\n    Eigen::MatrixXd* H = nullptr) {\n\n  // Compute gravity compensation torque.\n  std::unique_ptr<systems::Context<double>> plant_context =\n      plant.CreateDefaultContext();\n  Eigen::VectorXd zero_velocity = Eigen::VectorXd::Zero(kIiwaArmNumJoints);\n  plant.SetPositions(plant_context.get(), q);\n  plant.SetVelocities(plant_context.get(), zero_velocity);\n\n  if (H) {\n    plant.CalcMassMatrixViaInverseDynamics(*plant_context, H);\n  }\n\n  multibody::MultibodyForces<double> external_forces(plant);\n  plant.CalcForceElementsContribution(*plant_context, &external_forces);\n  return plant.CalcInverseDynamics(*plant_context, zero_velocity,\n                                   external_forces);\n}\n\n}  // namespace\n\nGTEST_TEST(KukaTorqueControllerTest, GravityCompensationTest) {\n  const std::string kIiwaUrdf =\n    \"manipulation/models/iiwa_description/urdf/\"\n    \"iiwa14_polytope_collision.urdf\";\n  multibody::MultibodyPlant<double> plant(0.0);\n  multibody::Parser(&plant).AddModelFromFile(kIiwaUrdf);\n  plant.WeldFrames(plant.world_frame(), plant.GetFrameByName(\"base\"));\n  plant.Finalize();\n\n  // Set stiffness and damping to zero.\n  VectorX<double> stiffness(kIiwaArmNumJoints);\n  stiffness.setZero();\n  VectorX<double> damping(kIiwaArmNumJoints);\n  damping.setZero();\n\n  // Choose an arbitrary state.\n  VectorX<double> q(7);\n  q << 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7;\n  VectorX<double> v(7);\n  v << 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1;\n  VectorX<double> q_des(7);\n  q_des << -0.1, -0.2, -0.3, -0.4, -0.5, -0.6, -0.7;\n  VectorX<double> v_des(7);\n  v_des << -0.7, -0.6, -0.5, -0.4, -0.3, -0.2, -0.1;\n  VectorX<double> torque_des(kIiwaArmNumJoints);\n  torque_des.setZero();\n\n  // Compute controller output.\n  KukaTorqueController<double> controller(plant, stiffness, damping);\n\n  std::unique_ptr<systems::Context<double>> context =\n      controller.CreateDefaultContext();\n  std::unique_ptr<systems::SystemOutput<double>> output =\n      controller.AllocateOutput();\n\n  VectorX<double> estimated_state_input(2 * kIiwaArmNumJoints);\n  estimated_state_input << q, v;\n\n  VectorX<double> desired_state_input(2 * kIiwaArmNumJoints);\n  desired_state_input << q_des, v_des;\n\n  VectorX<double> desired_torque_input(kIiwaArmNumJoints);\n  desired_torque_input << torque_des;\n\n  controller.get_input_port_estimated_state().FixValue(context.get(),\n                                                       estimated_state_input);\n  controller.get_input_port_desired_state().FixValue(context.get(),\n                                                     desired_state_input);\n  controller.get_input_port_commanded_torque().FixValue(context.get(),\n                                                        desired_torque_input);\n\n  Eigen::VectorXd expected_torque =\n      CalcGravityCompensationTorque(plant, q);\n\n  // Check output.\n  controller.CalcOutput(*context, output.get());\n  const BasicVector<double>* output_vector = output->get_vector_data(0);\n  EXPECT_TRUE(CompareMatrices(expected_torque, output_vector->get_value(),\n                              1e-10, MatrixCompareType::absolute));\n}\n\nGTEST_TEST(KukaTorqueControllerTest, SpringTorqueTest) {\n  const std::string kIiwaUrdf =\n    \"manipulation/models/iiwa_description/urdf/\"\n    \"iiwa14_polytope_collision.urdf\";\n  multibody::MultibodyPlant<double> plant(0.0);\n  multibody::Parser(&plant).AddModelFromFile(kIiwaUrdf);\n  plant.WeldFrames(plant.world_frame(), plant.GetFrameByName(\"base\"));\n  plant.Finalize();\n\n  // Set nonzero stiffness and zero damping.\n  VectorX<double> stiffness(kIiwaArmNumJoints);\n  stiffness << 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7;\n  VectorX<double> damping(kIiwaArmNumJoints);\n  damping.setZero();\n\n  // Choose an arbitrary state\n  VectorX<double> q(7);\n  q << 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7;\n  VectorX<double> v(7);\n  v << 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1;\n  VectorX<double> q_des(7);\n  q_des << -0.1, -0.2, -0.3, -0.4, -0.5, -0.6, -0.7;\n  VectorX<double> v_des(7);\n  v_des << -0.7, -0.6, -0.5, -0.4, -0.3, -0.2, -0.1;\n  VectorX<double> torque_des(kIiwaArmNumJoints);\n  torque_des.setZero();\n\n  // Compute controller output.\n  KukaTorqueController<double> controller(plant, stiffness, damping);\n\n  std::unique_ptr<systems::Context<double>> context =\n      controller.CreateDefaultContext();\n  std::unique_ptr<systems::SystemOutput<double>> output =\n      controller.AllocateOutput();\n\n  VectorX<double> estimated_state_input(2 * kIiwaArmNumJoints);\n  estimated_state_input << q, v;\n\n  VectorX<double> desired_state_input(2 * kIiwaArmNumJoints);\n  desired_state_input << q_des, v_des;\n\n  VectorX<double> desired_torque_input(kIiwaArmNumJoints);\n  desired_torque_input << torque_des;\n\n  controller.get_input_port_estimated_state().FixValue(context.get(),\n                                                       estimated_state_input);\n  controller.get_input_port_desired_state().FixValue(context.get(),\n                                                     desired_state_input);\n  controller.get_input_port_commanded_torque().FixValue(context.get(),\n                                                        desired_torque_input);\n\n  // Compute gravity compensation torque.\n  Eigen::VectorXd expected_torque =\n      CalcGravityCompensationTorque(plant, q);\n\n  // Compute spring torque.\n  expected_torque += -((q - q_des).array() * stiffness.array()).matrix();\n\n  // Check output.\n  controller.CalcOutput(*context, output.get());\n  const BasicVector<double>* output_vector = output->get_vector_data(0);\n  EXPECT_TRUE(CompareMatrices(expected_torque, output_vector->get_value(),\n                              1e-10, MatrixCompareType::absolute));\n}\n\nGTEST_TEST(KukaTorqueControllerTest, DampingTorqueTest) {\n  const std::string kIiwaUrdf =\n    \"manipulation/models/iiwa_description/urdf/\"\n    \"iiwa14_polytope_collision.urdf\";\n  multibody::MultibodyPlant<double> plant(0.0);\n  multibody::Parser(&plant).AddModelFromFile(kIiwaUrdf);\n  plant.WeldFrames(plant.world_frame(), plant.GetFrameByName(\"base\"));\n  plant.Finalize();\n\n  // Set arbitrary stiffness and damping.\n  VectorX<double> stiffness(kIiwaArmNumJoints);\n  stiffness << 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7;\n  VectorX<double> damping(kIiwaArmNumJoints);\n  damping << 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7;\n\n  // Choose an arbitrary state\n  VectorX<double> q(7);\n  q << 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7;\n  VectorX<double> v(7);\n  v << 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1;\n  VectorX<double> q_des(7);\n  q_des << -0.1, -0.2, -0.3, -0.4, -0.5, -0.6, -0.7;\n  VectorX<double> v_des(7);\n  v_des << -0.7, -0.6, -0.5, -0.4, -0.3, -0.2, -0.1;\n  VectorX<double> torque_des(kIiwaArmNumJoints);\n  torque_des.setZero();\n\n  // Compute controller output.\n  KukaTorqueController<double> controller(plant, stiffness, damping);\n\n  std::unique_ptr<systems::Context<double>> context =\n      controller.CreateDefaultContext();\n  std::unique_ptr<systems::SystemOutput<double>> output =\n      controller.AllocateOutput();\n\n  VectorX<double> estimated_state_input(2 * kIiwaArmNumJoints);\n  estimated_state_input << q, v;\n\n  VectorX<double> desired_state_input(2 * kIiwaArmNumJoints);\n  desired_state_input << q_des, v_des;\n\n  VectorX<double> desired_torque_input(kIiwaArmNumJoints);\n  desired_torque_input << torque_des;\n\n  controller.get_input_port_estimated_state().FixValue(context.get(),\n                                                       estimated_state_input);\n  controller.get_input_port_desired_state().FixValue(context.get(),\n                                                     desired_state_input);\n  controller.get_input_port_commanded_torque().FixValue(context.get(),\n                                                        desired_torque_input);\n\n  // Compute gravity compensation torque and mass matrix.\n  Eigen::MatrixXd H(kIiwaArmNumJoints, kIiwaArmNumJoints);\n  Eigen::VectorXd expected_torque =\n      CalcGravityCompensationTorque(plant, q, &H);\n\n  // Compute spring torque.\n  expected_torque += -((q - q_des).array() * stiffness.array()).matrix();\n\n  // Compute damping torque.\n  Eigen::VectorXd damping_torque(7);\n  for (int i = 0; i < kIiwaArmNumJoints; i++) {\n    damping_torque(i) =\n        -v(i) * damping(i) * 2 * std::sqrt(H(i, i) * stiffness(i));\n  }\n  expected_torque += damping_torque;\n\n  // Check output.\n  controller.CalcOutput(*context, output.get());\n  const BasicVector<double>* output_vector = output->get_vector_data(0);\n  EXPECT_TRUE(CompareMatrices(expected_torque, output_vector->get_value(),\n                              1e-10, MatrixCompareType::absolute));\n}\n\n}  // namespace kuka_iiwa_arm\n}  // namespace examples\n}  // namespace drake\n", "meta": {"hexsha": "9f6d946fbd947ca583aef5a2f400ec298ff1807e", "size": 9084, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/kuka_iiwa_arm/test/kuka_torque_controller_test.cc", "max_stars_repo_name": "RobotLocomotion/drake-python3.7", "max_stars_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-02-25T02:01:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-17T04:52:04.000Z", "max_issues_repo_path": "examples/kuka_iiwa_arm/test/kuka_torque_controller_test.cc", "max_issues_repo_name": "RobotLocomotion/drake-python3.7", "max_issues_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/kuka_iiwa_arm/test/kuka_torque_controller_test.cc", "max_forks_repo_name": "RobotLocomotion/drake-python3.7", "max_forks_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-13T12:05:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-13T12:05:39.000Z", "avg_line_length": 37.2295081967, "max_line_length": 78, "alphanum_fraction": 0.6785557023, "num_tokens": 2620, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234877, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4736290742934203}}
{"text": "// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\n#include \"distancetopathfeature.h\"\n#include \"utils.h\"\n#include <vespa/searchlib/fef/matchdata.h>\n#include <vespa/searchlib/fef/properties.h>\n#include <vespa/document/datatype/positiondatatype.h>\n#include <vespa/vespalib/geo/zcurve.h>\n#include <boost/algorithm/string/split.hpp>\n#include <boost/algorithm/string/classification.hpp>\n#include <cmath>\n#include <sstream>\n\n#include <vespa/log/log.h>\nLOG_SETUP(\".features.distancetopathfeature\");\n\nnamespace search {\nnamespace features {\n\nconst feature_t DistanceToPathExecutor::DEFAULT_DISTANCE(6400000000.0);\n\nDistanceToPathExecutor::DistanceToPathExecutor(std::vector<Vector2> &path,\n                                               const search::attribute::IAttributeVector *pos) :\n    search::fef::FeatureExecutor(),\n    _intBuf(),\n    _path(),\n    _pos(pos)\n{\n    if (_pos != NULL) {\n        _intBuf.allocate(_pos->getMaxValueCount());\n    }\n    _path.swap(path); // avoid copy\n}\n\nvoid\nDistanceToPathExecutor::execute(uint32_t docId)\n{\n    if (_path.size() > 1 && _pos != NULL) {\n        double pos = -1, trip = 0, product = 0;\n        double minSqDist = std::numeric_limits<double>::max();\n        _intBuf.fill(*_pos, docId);\n\n        // For each line segment, do\n        for (uint32_t seg = 1; seg < _path.size(); ++seg) {\n            const Vector2 &p1 = _path[seg - 1];\n            const Vector2 &p2 = _path[seg];\n            double len2 = (p2.x - p1.x) * (p2.x - p1.x) + (p2.y - p1.y) * (p2.y - p1.y);\n            double len = std::sqrt(len2);\n\n            // For each document location, do\n            for (uint32_t loc = 0; loc < _intBuf.size(); ++loc) {\n                int32_t x = 0, y = 0;\n                vespalib::geo::ZCurve::decode(_intBuf[loc], &x, &y);\n\n                double u = 0, dx, dy;\n                if (len < 1e-6) {\n                    dx = p1.x - x; // process as point\n                    dy = p1.y - y;\n                } else {\n                    u = std::min(1.0, std::max(0.0, (((x - p1.x) * (p2.x - p1.x)) + ((y - p1.y) * (p2.y - p1.y))) / len2));\n                    if (u == 0) {\n                        dx = p1.x - x; // intersection before segment\n                        dy = p1.y - y;\n                    } else if (u == 1) {\n                        dx = p2.x - x; // intersection after segment\n                        dy = p2.y - y;\n                    } else {\n                        dx = p1.x + u * (p2.x - p1.x) - x;\n                        dy = p1.y + u * (p2.y - p1.y) - y;\n                    }\n                }\n\n                double sqDist = dx * dx + dy * dy;\n                if (sqDist < minSqDist) {\n                    minSqDist = sqDist;\n                    pos = trip + u * len;\n                    product = (p2.x - p1.x) * dy - (p2.y - p1.y) * dx;\n                }\n            }\n            trip += len;\n        }\n\n        outputs().set_number(0, static_cast<feature_t>(std::sqrt(static_cast<feature_t>(minSqDist))));\n        outputs().set_number(1, static_cast<feature_t>(pos > -1 ? (trip > 0 ? pos / trip : 0) : 1));\n        outputs().set_number(2, static_cast<feature_t>(product));\n    } else {\n        outputs().set_number(0, DEFAULT_DISTANCE);\n        outputs().set_number(1, 1);\n        outputs().set_number(2, 0);\n    }\n}\n\nDistanceToPathBlueprint::DistanceToPathBlueprint() :\n    Blueprint(\"distanceToPath\"),\n    _posAttr()\n{\n}\n\nDistanceToPathBlueprint::~DistanceToPathBlueprint()\n{\n}\n\nvoid\nDistanceToPathBlueprint::visitDumpFeatures(const search::fef::IIndexEnvironment &,\n                                           search::fef::IDumpFeatureVisitor &) const\n{\n}\n\nsearch::fef::Blueprint::UP\nDistanceToPathBlueprint::createInstance() const\n{\n    return Blueprint::UP(new DistanceToPathBlueprint());\n}\n\nbool\nDistanceToPathBlueprint::setup(const search::fef::IIndexEnvironment & env,\n                               const search::fef::ParameterList & params)\n{\n    _posAttr = params[0].getValue();\n    describeOutput(\"distance\", \"The euclidian distance from the query path.\");\n    describeOutput(\"traveled\", \"The normalized distance traveled along the path before intersection.\");\n    describeOutput(\"product\",  \"The cross-product of the intersecting line segment and the intersection-to-document vector.\");\n    env.hintAttributeAccess(_posAttr);\n    env.hintAttributeAccess(document::PositionDataType::getZCurveFieldName(_posAttr));\n    return true;\n}\n\nsearch::fef::FeatureExecutor &\nDistanceToPathBlueprint::createExecutor(const search::fef::IQueryEnvironment &env, vespalib::Stash &stash) const\n{\n    // Retrieve path from query using the name of this and \"path\" as property.\n    std::vector<Vector2> path;\n    search::fef::Property pro = env.getProperties().lookup(getName(), \"path\");\n    if (pro.found()) {\n        vespalib::string str = pro.getAt(0);\n        uint32_t len = str.size();\n        if (str[0] == '(' && len > 1 && str[len - 1] == ')') {\n            str = str.substr(1, len - 1); // remove braces\n            std::vector<vespalib::string> arr;\n            boost::split(arr, str, boost::is_any_of(\",\"));\n            len = arr.size() - 1;\n            for (uint32_t i = 0; i < len; i += 2) {\n                double x = util::strToNum<double>(arr[i]);\n                double y = util::strToNum<double>(arr[i + 1]);\n                path.push_back(Vector2(x, y));\n            }\n        }\n    }\n\n    // Lookup the attribute vector that holds document positions.\n    const search::attribute::IAttributeVector *pos = NULL;\n    if (path.size() > 1) {\n        pos = env.getAttributeContext().getAttribute(_posAttr);\n        if (pos == NULL) {\n            pos = env.getAttributeContext().getAttribute(document::PositionDataType::getZCurveFieldName(_posAttr));\n        }\n        if (pos != NULL) {\n            if (!pos->isIntegerType()) {\n                LOG(warning, \"The position attribute '%s' is not an integer attribute. Will use default distance.\",\n                    pos->getName().c_str());\n                pos = NULL;\n            } else if (pos->getCollectionType() == attribute::CollectionType::WSET) {\n                LOG(warning, \"The position attribute '%s' is a weighted set attribute. Will use default distance.\",\n                    pos->getName().c_str());\n                pos = NULL;\n            }\n        } else {\n            LOG(warning, \"The position attribute '%s' was not found. Will use default distance.\", _posAttr.c_str());\n        }\n    } else {\n        LOG(warning, \"No path given in query. Will use default distance.\");\n    }\n\n    // Create and return a compatible executor.\n    return stash.create<DistanceToPathExecutor>(path, pos);\n}\n\n} // namespace features\n} // namespace search\n", "meta": {"hexsha": "4f4491327e77569017ceaa71b53dfa6f380cfbc9", "size": 6748, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "searchlib/src/vespa/searchlib/features/distancetopathfeature.cpp", "max_stars_repo_name": "atveit/vespa", "max_stars_repo_head_hexsha": "545898728f29a9ed7fcae223bfb0c85f24227af8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "searchlib/src/vespa/searchlib/features/distancetopathfeature.cpp", "max_issues_repo_name": "atveit/vespa", "max_issues_repo_head_hexsha": "545898728f29a9ed7fcae223bfb0c85f24227af8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-01-21T01:37:37.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-21T01:37:37.000Z", "max_forks_repo_path": "searchlib/src/vespa/searchlib/features/distancetopathfeature.cpp", "max_forks_repo_name": "atveit/vespa", "max_forks_repo_head_hexsha": "545898728f29a9ed7fcae223bfb0c85f24227af8", "max_forks_repo_licenses": ["Apache-2.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.4888888889, "max_line_length": 126, "alphanum_fraction": 0.5616478957, "num_tokens": 1707, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234877, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4736290742934203}}
{"text": "#ifndef PROP_HPP\n# define PROP_HPP\n\n#include <Eigen/Dense>\n\nusing Eigen::Matrix;\nusing Eigen::Vector3d;\nusing Eigen::Matrix3d;\nusing Eigen::DiagonalMatrix;\n\n#include \"frames.hpp\"\n#include \"gravity.hpp\"\n#include \"vector_math.hpp\"\n#include \"nav_types.hpp\"\n\n\nclass Prop {\npublic:\n  /* State */\n  double time;\n  Vector3d r_imu_inrtl;\n  Vector3d v_imu_inrtl;\n  Vector3d b_acc;\n  Vector3d b_gyro;\n\n  /* Attitude State */\n  Matrix3d T_inrtl_to_body; /* (--) rotation matrix from inrtl frame to body frame */\n\n  /* State Transition */\n  Matrix<double,9,9>  Phi_xx_dot; /* (--) product of dynamics matrix and state transition\n\t\t\t\t   *      matrix */\n  Matrix<double,9,21> Phi_xb_dot;\n  \n  Matrix<double,9,9>  Phi_xx;     /* (--) state transition matrix from previous update to\n\t\t                   *      present */\n  Matrix<double,9,21> Phi_xb;\n  DiagonalMatrix<double,21> Phi_bb; /* (--) ECRV portion of the state transition matrix */\n\n\n  /** @brief Initialize propagation from a previous update cycle.\n   *\n   */\n  Prop(const double& kf_time,\n       const State& X_posterior)\n    : time(kf_time)\n    , Phi_xx_dot(Matrix9d::Zero())\n    , Phi_xb_dot(Matrix<double,9,21>::Zero())\n    , Phi_xx(Matrix9d::Identity())\n    , Phi_xb(Matrix<double,9,21>::Zero())\n  {\n    for (size_t ii = 0; ii < 21; ++ii) {\n      Phi_bb.diagonal()(ii) = 1 / -TAU;\n    }\n\n    // Perform reset\n    T_inrtl_to_body = rotvec_to_matrix(X_posterior.block<3,1>(6,0)) * T_inrtl_to_body;\n\n    // Copy out states for propagation\n    for (size_t ii = 0; ii < 3; ++ii) {\n      r_imu_inrtl[ii] = X_posterior[ii];\n      v_imu_inrtl[ii] = X_posterior[ii+3];\n      b_acc[ii]       = X_posterior[ii+9];\n      b_gyro[ii]      = X_posterior[ii+12];\n    }\n  }\n  \n\n  /** @brief Propagation method for incorporating IMU measurements\n   **        into the predicted state and covariance\n   *\n   * References:\n   *\n   * 1. D\u2019Souza, C., & Hanak, C. (2011). The state transition and\n   *    process noise matrices in the Orion FILTNAV and EKF. Houston,\n   *    TX, US.\n   *\n   * @param[in]  dv_meas      (m/s) IMU acceleration measurement\n   * @param[in]  dtheta_meas  (r) IMU angular velocity measurement\n   */\n  void propagate(const Vector3d& dv_meas,\n\t\t const Vector3d& dtheta_meas,\n\t\t const GravBody& planet,\n\t\t const Vector3d& w_planet)\n  {\n    Matrix3d T_inrtl_to_pcpf = compute_T_inrtl_to_pcpf(time, w_planet);\n    Vector3d r_imu_pcpf = T_inrtl_to_pcpf * r_imu_inrtl;\n    \n    // Compute gravitational acceleration and gravity gradient.\n    Vector3d a_imu_pcpf;\n    Matrix3d G_pcpf;\n    planet.accel(r_imu_pcpf, a_imu_pcpf, G_pcpf);\n    Matrix3d G = T_inrtl_to_pcpf.transpose() * G_pcpf;\n    Vector3d a_grav_imu = T_inrtl_to_pcpf.transpose() * a_imu_pcpf;\n    Vector3d a_nongrav_imu = T_inrtl_to_body.transpose() * (dv_meas / PROP_DT - b_acc);\n    Vector3d a_total_imu = a_grav_imu + a_nongrav_imu;\n\n    // Discretized attitude propagation\n    Vector3d dtheta = (dtheta_meas / PROP_DT - b_gyro);\n    Matrix3d T_inrtl_to_bodynext = rotvec_to_matrix(dtheta) * T_inrtl_to_body;\n    \n    // State propagation\n    r_imu_inrtl += v_imu_inrtl * PROP_DT + a_total_imu * 0.5 * PROP_DT*PROP_DT + T_inrtl_to_body.transpose() * (Matrix3d::Identity() + skew(dtheta / 3.0)) * a_nongrav_imu * 0.5;\n    v_imu_inrtl += a_total_imu * PROP_DT + T_inrtl_to_body.transpose() * (Matrix3d::Identity() + skew(dtheta * 0.5)) * a_nongrav_imu / PROP_DT;\n    \n\n    Matrix3d dvdot_dphi = Matrix3d::Zero(); // FIXME: Moment arm needed\n\n    Matrix3d wx = skew(dtheta_meas / PROP_DT);\n\n    \n\n    // The four pieces of Phi_dot are:\n    // Axx Phixb     Axx Phixb + Axb Phibb\n    // 0             Abb Phibb\n\n    // XX component of Phi_dot\n    \n    // Set first row\n    Phi_xx_dot.block<3,9>(0,0) = Phi_xx.block<3,9>(3,0) * PROP_DT; // rr, rv, rphi\n\n    // Set second row\n    Phi_xx_dot.block<3,3>(3,0) = G * Phi_xx.block<3,3>(0,0) * PROP_DT;\n    Phi_xx_dot.block<3,3>(3,3) = G * Phi_xx.block<3,3>(0,3) * PROP_DT;\n    Phi_xx_dot.block<3,3>(3,6) = (G * Phi_xx.block<3,3>(0,6) + dvdot_dphi * Phi_xx.block<3,3>(6,6)) * PROP_DT;\n\n    // Set third row\n    Phi_xx_dot.block<3,3>(6,6) = wx * Phi_xx.block<3,3>(6,6) * PROP_DT;\n    \n\n\n    Matrix3d Phi_bb_gyro;\n    Phi_bb_gyro << Phi_bb.diagonal()(3), 0.0, 0.0,\n      0.0, Phi_bb.diagonal()(4), 0.0,\n      0.0, 0.0, Phi_bb.diagonal()(5);\n\n    // XB component of Phi_dot\n\n    // Set first row\n    Phi_xb_dot.block<3,6>(0,0) = Phi_xb.block<3,6>(3,0) * PROP_DT;\n\n    // Set second row\n    Phi_xb_dot.block<3,3>(3,0) = (G * Phi_xb.block<3,3>(0,0) + dvdot_dphi * Phi_xb.block<3,3>(6,0)) * PROP_DT;\n    Phi_xb_dot.block<3,3>(3,3) = (G * Phi_xb.block<3,3>(0,3) + dvdot_dphi * Phi_xb.block<3,3>(6,3)) * PROP_DT;\n\n    // Set third row\n    Phi_xb_dot.block<3,3>(6,0) = -wx * Phi_xb.block<3,3>(6,0) * PROP_DT;\n    Phi_xb_dot.block<3,3>(6,3) = (-wx * Phi_xb.block<3,3>(6,3) - Phi_bb_gyro) * PROP_DT;\n    \n\n    // Update state transition matrix\n    Phi_xx += Phi_xx_dot;\n    Phi_xb += Phi_xb_dot;\n\n    // Prepare attitude for next propagation\n    T_inrtl_to_body = T_inrtl_to_bodynext;\n\n    // Update the time\n    time += PROP_DT;\n    \n  }\n  \n};\n\n#endif\n", "meta": {"hexsha": "4679c04abf73db5889aa509ef298fe30ed24b02a", "size": 5097, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/prop.hpp", "max_stars_repo_name": "openlunar/nav", "max_stars_repo_head_hexsha": "37240000c542f4d42979a83ac5bebb3ab2c01fe4", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/prop.hpp", "max_issues_repo_name": "openlunar/nav", "max_issues_repo_head_hexsha": "37240000c542f4d42979a83ac5bebb3ab2c01fe4", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/prop.hpp", "max_forks_repo_name": "openlunar/nav", "max_forks_repo_head_hexsha": "37240000c542f4d42979a83ac5bebb3ab2c01fe4", "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.8909090909, "max_line_length": 177, "alphanum_fraction": 0.6395919168, "num_tokens": 1725, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.5698526514141572, "lm_q1q2_score": 0.4736290647595906}}
{"text": "/* Copyright (C) 2010 Ion Torrent Systems, Inc. All Rights Reserved */\n#include <Eigen/Dense>\n#include <Eigen/LU>\n#include \"ZeromerMatDiff.h\"\n#include \"IonH5Eigen.h\"\n#include \"SampleStats.h\"\n#include \"SampleQuantiles.h\"\n\nvoid ZeromerMatDiff::ShiftReference(int n_frames, size_t n_flow_wells, float shift,\n                                    float *orig_data, float *shifted_data) {\n  if (shift == 0.0f) {\n    memcpy(shifted_data, orig_data, sizeof(float) * n_flow_wells * n_frames);\n    return;\n  }\n  Eigen::Map<Eigen::MatrixXf, Eigen::Aligned> orig(orig_data, n_flow_wells, n_frames);\n  Eigen::Map<Eigen::MatrixXf, Eigen::Aligned> shifted(shifted_data, n_flow_wells, n_frames);\n  for (int frame_ix = 0; frame_ix < n_frames; frame_ix++) {\n    int start_frame = floor(frame_ix + shift);\n    int end_frame = ceil(frame_ix + shift);\n    //    if (shift < 0) { std::swap(start_frame, end_frame); }\n    if (start_frame >= 0 && end_frame < n_frames) { \n      //interpolate...\n      float mult = shift - floor(shift);\n      shifted.col(frame_ix).array() = (orig.col(end_frame).array() - orig.col(start_frame).array()) * mult;\n      shifted.col(frame_ix).array() += orig.col(start_frame).array();\n    }\n    else {\n      // extrapolate backwards\n      if (shift < 0) {\n        // calculate slope\n        shifted.col(frame_ix).array() = (orig.col(1).array() - orig.col(0).array());\n        shifted.col(frame_ix).array() = orig.col(0).array() + shifted.col(frame_ix).array() * (frame_ix + shift);\n      }\n      // extrapolate forwards\n      else if (shift > 0) {\n        shifted.col(frame_ix).array() = (orig.col(n_frames - 1).array() - orig.col(n_frames - 2).array());\n        shifted.col(frame_ix).array() = orig.col(n_frames - 1).array() + shifted.col(frame_ix).array() * (frame_ix + shift - (n_frames - 1));\n      }\n      else {\n        assert(0);\n      }\n    }\n  }\n}\n\nvoid ZeromerMatDiff::PredictZeromersSignal(const float *time, int n_frames,\n                                           float *trace, float *ref, float *zeromer,\n                                           size_t n_wells, size_t n_flows, \n                                           size_t n_flow_wells, \n                                           float taue_est, float *__restrict taub,\n                                           const std::string &h5_dump) {\n  Eigen::Map<Eigen::MatrixXf, Eigen::Aligned> trace_data(trace, n_flow_wells, n_frames);\n  Eigen::Map<Eigen::MatrixXf, Eigen::Aligned> ref_data(ref, n_flow_wells, n_frames);\n  Eigen::Map<Eigen::MatrixXf, Eigen::Aligned> zeromer_est(zeromer, n_flow_wells, n_frames);\n  zeromer_est.setZero();\n  Eigen::Map<Eigen::VectorXf, Eigen::Aligned> taub_v(taub, n_flow_wells);\n  Eigen::VectorXf cdelta(n_flow_wells);\n  cdelta.setZero();\n  // column based operations vectorized by eigen for speed\n  for (int f_ix = 1; f_ix < trace_data.cols(); f_ix++) {\n    float dtime = time[f_ix] - time[f_ix -1];\n    zeromer_est.col(f_ix).array() = ref_data.col(f_ix).array() * (taue_est + dtime);\n    zeromer_est.col(f_ix) = zeromer_est.col(f_ix) + cdelta;\n    zeromer_est.col(f_ix).array() = zeromer_est.col(f_ix).array() / (taub_v.array() + dtime);\n    cdelta.array() += ref_data.col(f_ix).array() - zeromer_est.col(f_ix).array();\n  }\n  if (!h5_dump.empty()) {\n    H5File h5(h5_dump);\n    h5.Open(true);\n    Eigen::MatrixXf trace_data_tmp = trace_data;\n    Eigen::MatrixXf ref_data_tmp = ref_data;\n    Eigen::MatrixXf zeromer_est_tmp = zeromer_est;\n    H5Eigen::WriteMatrix(h5, \"/traces\", trace_data_tmp);\n    H5Eigen::WriteMatrix(h5, \"/ref\", ref_data_tmp);\n    H5Eigen::WriteMatrix(h5, \"/shifted_ref\", ref_data_tmp);\n    H5Eigen::WriteMatrix(h5, \"/zeromer\", zeromer_est_tmp);\n    h5.Close();\n  }\n  //  zeromer_est = trace_data - zeromer_est;\n}\n\nvoid ZeromerMatDiff::ZeromerMadError(const int *zero_flows, size_t n_zero_flows, \n                                     float *signal_data, \n                                     size_t n_wells, size_t n_flows, \n                                     size_t n_flow_wells, size_t n_frames, \n                                     float &mad) {\n  // Calculate basics per well for integral, mad, max for each well/flow\n  SampleStats<double> mad_mean;\n  for (size_t z_ix = 0; z_ix < n_zero_flows; z_ix++) {\n    size_t flow_ix = zero_flows[z_ix];\n    for (size_t col_ix = 0; col_ix < n_frames; col_ix++) {\n      float *__restrict signal_start = signal_data + n_wells * flow_ix + n_flow_wells * col_ix;\n      float *__restrict signal_end = signal_start + n_wells;\n      while (signal_start != signal_end) {\n        mad_mean.AddValue(fabs(*signal_start));\n        signal_start++;\n      }\n    }\n  }\n  mad = mad_mean.GetMean();\n}\n\n\nvoid ZeromerMatDiff::ZeromerSumSqErrorTrim(const int *zero_flows, size_t n_zero_flows, \n                                           const char *bad_wells,\n                                           float *signal_data, float *predict_data, \n                                           size_t n_wells, size_t n_flows, \n                                           size_t n_flow_wells, size_t n_frames, \n                                           double &ssq) {\n  double ssq_sum = 0;\n  size_t bad_count = 0;\n  float max_value = 1000.0f;\n  for (size_t z_ix = 0; z_ix < n_zero_flows; z_ix++) {\n    size_t flow_ix = zero_flows[z_ix];\n    for (size_t col_ix = 0; col_ix < n_frames; col_ix++) {\n      float *__restrict signal_start = signal_data + n_wells * flow_ix + n_flow_wells * col_ix;\n      float *__restrict signal_end = signal_start + n_wells;\n      float *__restrict predict_start = predict_data + n_wells * flow_ix + n_flow_wells * col_ix;\n      const char *__restrict bad_start = bad_wells;\n      while (signal_start != signal_end) {\n        double value = *signal_start - *predict_start; //*signal_start * *signal_start;\n        if (*bad_start == 0 && isfinite(value) && fabs(value) <= max_value) {\n          ssq_sum += value * value;\n        }\n        else if (*bad_start == 0) {\n          *predict_start = *signal_start + max_value;\n          ssq_sum += max_value;\n          bad_count++;\n        }\n        // levmar has it's own version of residual calculation so have to sub in the nan values\n        if (!isfinite(value) || std::isnan(value) || value > max_value) {\n          *predict_start = *signal_start + max_value;\n        }\n        bad_start++;\n        signal_start++;\n        predict_start++;\n      }\n    }\n  }\n  ssq = ssq_sum;\n}\n\nvoid ZeromerMatDiff::FitTauB(const int *zero_flows, size_t n_zero_flows, \n                             const float *trace_data, const float *ref_data, \n                             size_t n_wells, size_t n_flows, size_t n_flow_wells,\n                             size_t n_frames, float taue_est, float *__restrict taub) {\n  Eigen::Map<Eigen::VectorXf, Eigen::Aligned> taub_v(taub, n_flow_wells);\n  Eigen::VectorXf vec_sum_x2(n_wells), vec_sum_xy(n_wells), \n    vec_previous(n_wells), taub_sum(n_wells);\n  taub_sum.setZero();  \n  taub_v.setZero();\n  for (size_t flow_ix = 0; flow_ix < n_zero_flows; flow_ix++) {\n    int z_ix = zero_flows[flow_ix];\n\n    vec_sum_x2.setZero();\n    vec_sum_xy.setZero();\n    vec_previous.setZero();\n    for (size_t frame_ix = 0; frame_ix < n_frames; frame_ix++) {\n      size_t offset = frame_ix * n_flow_wells + n_wells * z_ix;\n      const float * __restrict trace_ptr_start = trace_data + offset;\n      const float * __restrict trace_ptr_end = trace_ptr_start + n_wells;\n      const float * __restrict ref_ptr = ref_data + offset;\n      float * __restrict previous_ptr = vec_previous.data();\n      float * __restrict xx_ptr = vec_sum_x2.data();\n      float * __restrict xy_ptr = vec_sum_xy.data();\n      while (trace_ptr_start != trace_ptr_end) {\n        float diff = *ref_ptr - *trace_ptr_start;\n        float taues = *ref_ptr * taue_est;\n        float y = *previous_ptr + diff + taues;\n        *previous_ptr += diff;\n        float x = *trace_ptr_start;\n        *xx_ptr += x * x;\n        *xy_ptr += x * y;\n\n        trace_ptr_start++;\n        ref_ptr++;\n        previous_ptr++;\n        xx_ptr++;\n        xy_ptr++;\n      }\n    }\n    float *__restrict tau_b_start = taub_sum.data();\n    float *__restrict tau_b_end = tau_b_start + n_wells;\n    float *__restrict xx_ptr = vec_sum_x2.data();\n    float *__restrict xy_ptr = vec_sum_xy.data();\n    while (tau_b_start != tau_b_end) {\n      *tau_b_start++ += *xy_ptr++ / *xx_ptr++;\n    }\n  }\n\n  /* for now same taub estimate per nuc, just copy for each flow. */\n  for (size_t flow_ix = 0; flow_ix < n_flows; flow_ix++) {\n    float *__restrict tau_b_start = taub + flow_ix * n_wells;\n    float *__restrict tau_b_end = tau_b_start + n_wells;\n    float *__restrict tau_b_sum_start = taub_sum.data();\n    while (tau_b_start != tau_b_end) {\n      *tau_b_start++ = *tau_b_sum_start++ / n_zero_flows;\n    }\n  }\n\n}\n\nvoid ZeromerMatDiff::FitTauBNuc(const int *zero_flows, size_t n_zero_flows, \n                                const float *trace_data, const float *ref_data, \n                                int *nuc_flows,\n                                size_t n_wells, size_t n_flows, size_t n_flow_wells,\n                                size_t n_frames, float taue_est, float *__restrict taub) {\n  float nuc_weight_mult = .3;\n  float combo_weight_mult = .7;\n     \n  Eigen::Map<Eigen::VectorXf, Eigen::Aligned> taub_v(taub, n_flow_wells);\n  Eigen::VectorXf vec_sum_x2(n_wells), vec_sum_xy(n_wells), \n    vec_previous(n_wells), taub_sum(n_wells);\n  Eigen::MatrixXf taub_nuc(n_wells, 4);\n  int nuc_counts[4] = {0,0,0,0};\n  taub_nuc.setZero();\n  taub_v.setZero();\n  taub_sum.setZero();    \n  for (size_t flow_ix = 0; flow_ix < n_zero_flows; flow_ix++) {\n    int z_ix = zero_flows[flow_ix];\n    vec_sum_x2.setZero();\n    vec_sum_xy.setZero();\n    vec_previous.setZero();\n    for (size_t frame_ix = 0; frame_ix < n_frames; frame_ix++) {\n      size_t offset = frame_ix * n_flow_wells + n_wells * z_ix;\n      const float * __restrict trace_ptr_start = trace_data + offset;\n      const float * __restrict trace_ptr_end = trace_ptr_start + n_wells;\n      const float * __restrict ref_ptr = ref_data + offset;\n      float * __restrict previous_ptr = vec_previous.data();\n      float * __restrict xx_ptr = vec_sum_x2.data();\n      float * __restrict xy_ptr = vec_sum_xy.data();\n      while (trace_ptr_start != trace_ptr_end) {\n        float diff = *ref_ptr - *trace_ptr_start;\n        float taues = *ref_ptr * taue_est;\n        float y = *previous_ptr + diff + taues;\n        *previous_ptr += diff;\n        float x = *trace_ptr_start;\n        *xx_ptr += x * x;\n        *xy_ptr += x * y;\n\n        trace_ptr_start++;\n        ref_ptr++;\n        previous_ptr++;\n        xx_ptr++;\n        xy_ptr++;\n      }\n    }\n    int nuc_ix = nuc_flows[z_ix];\n    nuc_counts[nuc_ix]++;\n    float *__restrict tau_b_nuc_start = taub_nuc.col(nuc_ix).data();\n    float *__restrict tau_b_start = taub_sum.data();\n    float *__restrict tau_b_end = tau_b_start + n_wells;\n    float *__restrict xx_ptr = vec_sum_x2.data();\n    float *__restrict xy_ptr = vec_sum_xy.data();\n    while (tau_b_start != tau_b_end) {\n      float value = *xy_ptr++ / *xx_ptr++;\n      if (!isfinite(value)) {\n        value = 0;\n      }\n      *tau_b_start++ += value;\n      *tau_b_nuc_start++ += value;\n    }\n  }\n\n  /* for now same taub estimate per nuc, just copy for each flow. */\n  for (size_t flow_ix = 0; flow_ix < n_flows; flow_ix++) {\n    int nuc_ix = nuc_flows[flow_ix];\n    float *__restrict tau_b_start = taub + flow_ix * n_wells;\n    float *__restrict tau_b_end = tau_b_start + n_wells;\n    float *__restrict tau_b_sum_start = taub_sum.data();\n    float *__restrict tau_b_nuc_sum_start = taub_nuc.col(nuc_ix).data();\n    // little awkward as we mult weight by number of observances but then divide out for average but more readable to keep calc\n    float nuc_div = nuc_counts[nuc_ix];\n    float nuc_weight = nuc_counts[nuc_ix] * nuc_weight_mult;\n    float nuc_mult = nuc_div > 0.0f ? nuc_weight / nuc_div : 0.0f;\n    float total_weight = nuc_weight + combo_weight_mult;\n    float combo_mult = combo_weight_mult/n_zero_flows;\n    while (tau_b_start != tau_b_end) {\n      // weighted average of nuc specific and overall for this well taub\n      *tau_b_start = ((*tau_b_sum_start * combo_mult) + (*tau_b_nuc_sum_start * nuc_mult)) / total_weight;\n      tau_b_start++;\n      tau_b_sum_start++;\n      tau_b_nuc_sum_start++;\n    }\n  }\n}\n", "meta": {"hexsha": "c7519446ca0a907c08f723c9223567238dfc54f9", "size": 12347, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Analysis/Separator/ZeromerMatDiff.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/ZeromerMatDiff.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/ZeromerMatDiff.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": 43.0209059233, "max_line_length": 141, "alphanum_fraction": 0.6186927999, "num_tokens": 3364, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4736290647595905}}
{"text": "/*\n * Copyright 2010, 2011, 2012\n * Nicolas Mansard,\n * Fran\u00e7ois Bleibel,\n * Olivier Stasse,\n * Florent Lamiraux\n *\n * CNRS/AIST\n *\n */\n\n#ifndef __SOT_KALMAN_H\n#define __SOT_KALMAN_H\n\n/* -------------------------------------------------------------------------- */\n/* --- INCLUDE -------------------------------------------------------------- */\n/* -------------------------------------------------------------------------- */\n\n#include <Eigen/LU>\n#include <dynamic-graph/all-signals.h>\n#include <dynamic-graph/entity.h>\n#include <dynamic-graph/linear-algebra.h>\n#include <sot/core/constraint.hh>\n\n/* -------------------------------------------------------------------------- */\n/* --- API ------------------------------------------------------------------ */\n/* -------------------------------------------------------------------------- */\n\n#if defined(WIN32)\n#if defined(kalman_EXPORTS)\n#define SOT_KALMAN_EXPORT __declspec(dllexport)\n#else\n#define SOT_KALMAN_EXPORT __declspec(dllimport)\n#endif\n#else\n#define SOT_KALMAN_EXPORT\n#endif\n\n/* -------------------------------------------------------------------------- */\n/* --- CLASSE --------------------------------------------------------------- */\n/* -------------------------------------------------------------------------- */\n\nnamespace dynamicgraph {\nnamespace sot {\n\nclass SOT_KALMAN_EXPORT Kalman : public Entity {\npublic:\n  static const std::string CLASS_NAME;\n  virtual const std::string &getClassName(void) const { return CLASS_NAME; }\n\nprotected:\n  unsigned int size_state;\n  unsigned int size_measure;\n  double dt;\n\npublic:\n  SignalPtr<Vector, int> measureSIN;         // y\n  SignalPtr<Matrix, int> modelTransitionSIN; // F\n  SignalPtr<Matrix, int> modelMeasureSIN;    // H\n  SignalPtr<Matrix, int> noiseTransitionSIN; // Q\n  SignalPtr<Matrix, int> noiseMeasureSIN;    // R\n\n  SignalPtr<Vector, int> statePredictedSIN;            // x_{k|k-1}\n  SignalPtr<Vector, int> observationPredictedSIN;      // y_pred = h (x_{k|k-1})\n  SignalTimeDependent<Matrix, int> varianceUpdateSOUT; // P\n  SignalTimeDependent<Vector, int> stateUpdateSOUT;    // X_est\n\n  SignalTimeDependent<Matrix, int> gainSINTERN;       // K\n  SignalTimeDependent<Matrix, int> innovationSINTERN; // S\n\npublic:\n  virtual std::string getDocString() const {\n    return \"Implementation of extended Kalman filter     \\n\"\n           \"\\n\"\n           \"  Dynamics of the system:                    \\n\"\n           \"\\n\"\n           \"    x = f (x   , u   ) + w       (state)      \\n\"\n           \"     k      k-1   k-1     k-1                 \\n\"\n           \"\\n\"\n           \"    y = h (x ) + v               (observation)\\n\"\n           \"     k      k     k                           \\n\"\n           \"\\n\"\n           \"  Prediction:\\n\"\n           \"\\n\"\n           \"    ^          ^                       \\n\"\n           \"    x     = f (x       , u   )     (state) \\n\"\n           \"     k|k-1      k-1|k-1   k-1          \\n\"\n           \"\\n\"\n           \"                           T           \\n\"\n           \"    P     = F    P        F    + Q (covariance)\\n\"\n           \"     k|k-1   k-1  k-1|k-1  k-1         \\n\"\n           \"\\n\"\n           \"  with\\n\"\n           \"           \\\\                         \\n\"\n           \"           d f  ^                         \\n\"\n           \"    F    = --- (x       , u   )           \\n\"\n           \"     k-1   \\\\     k-1|k-1   k-1            \\n\"\n           \"           d x                         \\n\"\n           \"\\n\"\n           \"         \\\\                             \\n\"\n           \"         d h  ^                          \\n\"\n           \"    H  = --- (x       )                     \\n\"\n           \"     k   \\\\     k-1|k-1                      \\n\"\n           \"         d x                             \\n\"\n\n           \"  Update:\\n\"\n           \"\\n\"\n           \"                ^                            \\n\"\n           \"    z = y  - h (x     )             (innovation)\\n\"\n           \"     k   k       k|k-1                       \\n\"\n           \"                   T                          \\n\"\n           \"    S = H  P      H  + R            (innovation covariance)\\n\"\n           \"     k   k  k|k-1  k                          \\n\"\n           \"                T  -1                         \\n\"\n           \"    K = P      H  S                 (Kalman gain)\\n\"\n           \"     k   k|k-1  k  k                          \\n\"\n           \"    ^     ^                                   \\n\"\n           \"    x   = x      + K  z             (state)   \\n\"\n           \"     k|k   k|k-1    k  k                      \\n\"\n           \"\\n\"\n           \"    P   =(I - K  H ) P                        \\n\"\n           \"     k|k       k  k   k|k-1                   \\n\"\n           \"\\n\"\n           \"  Signals\\n\"\n           \"    - input(vector)::x_pred:  state prediction\\n\"\n           \"                                                         ^\\n\"\n           \"    - input(vector)::y_pred:  observation prediction: h (x     )\\n\"\n           \"                                                          k|k-1\\n\"\n           \"    - input(matrix)::F:       partial derivative wrt x of f\\n\"\n           \"    - input(vector)::y:       measure         \\n\"\n           \"    - input(matrix)::H:       partial derivative wrt x of h\\n\"\n           \"    - input(matrix)::Q:       variance of noise w\\n\"\n           \"                                                 k-1\\n\"\n           \"    - input(matrix)::R:       variance of noise v\\n\"\n           \"                                                 k\\n\"\n           \"    - output(matrix)::P_pred: variance of prediction\\n\"\n           \"                                               ^\\n\"\n           \"    - output(vector)::x_est:  state estimation x\\n\"\n           \"                                                k|k\\n\";\n  }\n\nprotected:\n  Matrix &computeVarianceUpdate(Matrix &P_k_k, const int &time);\n  Vector &computeStateUpdate(Vector &x_est, const int &time);\n\n  void setStateEstimation(const Vector &x0) {\n    stateEstimation_ = x0;\n    stateUpdateSOUT.recompute(0);\n  }\n\n  void setStateVariance(const Matrix &P0) {\n    stateVariance_ = P0;\n    varianceUpdateSOUT.recompute(0);\n  }\n  // Current state estimation\n  // ^\n  // x\n  //  k-1|k-1\n  Vector stateEstimation_;\n  // Variance of current state estimation\n  // P\n  //  k-1|k-1\n  Matrix stateVariance_;\n\n  //                          ^\n  // Innovation: z  = y  - H  x\n  //              k    k    k  k|k-1\n  Vector z_;\n\n  // F    P\n  //  k-1  k-1|k-1\n  Matrix FP_;\n\n  // Variance prediction\n  // P\n  //  k|k-1\n  Matrix Pk_k_1_;\n\n  // Innovation covariance\n  Matrix S_;\n\n  // Kalman Gain\n  Matrix K_;\n\npublic:\n  Kalman(const std::string &name);\n  /* --- Entity --- */\n  void display(std::ostream &os) const;\n};\n\n} // namespace sot\n} // namespace dynamicgraph\n\n/*!\n  \\file Kalman.h\n  \\brief  Extended kalman filter implementation\n*/\n\n#endif\n", "meta": {"hexsha": "5180f3b0ffc04308ab74661bce0f4dfb035a43e2", "size": 6842, "ext": "hh", "lang": "C++", "max_stars_repo_path": "include/sot/core/kalman.hh", "max_stars_repo_name": "florent-lamiraux/sot-core", "max_stars_repo_head_hexsha": "bf6998f1f76ad46c22aa1f350273fac484b3ae7d", "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/sot/core/kalman.hh", "max_issues_repo_name": "florent-lamiraux/sot-core", "max_issues_repo_head_hexsha": "bf6998f1f76ad46c22aa1f350273fac484b3ae7d", "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/sot/core/kalman.hh", "max_forks_repo_name": "florent-lamiraux/sot-core", "max_forks_repo_head_hexsha": "bf6998f1f76ad46c22aa1f350273fac484b3ae7d", "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.21, "max_line_length": 80, "alphanum_fraction": 0.3588132125, "num_tokens": 1657, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.831143031127974, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4736290599926753}}
{"text": "//==================================================================================================\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_AVX_SIMD_FUNCTION_NBTRUE_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_X86_AVX_SIMD_FUNCTION_NBTRUE_HPP_INCLUDED\n\n#include <boost/simd/detail/overload.hpp>\n#include <boost/simd/function/is_nez.hpp>\n#include <boost/simd/function/popcnt.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n   namespace bd = boost::dispatch;\n   namespace bs = boost::simd;\n\n   BOOST_DISPATCH_OVERLOAD( nbtrue_\n                          , (typename A0)\n                          , bs::avx_\n                          , bs::pack_<bd::double_<A0>, bs::avx_>\n                          )\n   {\n      BOOST_FORCEINLINE std::size_t operator()( const A0& a0) const BOOST_NOEXCEPT\n      {\n        int r = _mm256_movemask_pd(is_nez(a0));\n        return  popcnt(r);\n      }\n   };\n\n   BOOST_DISPATCH_OVERLOAD( nbtrue_\n                          , (typename A0)\n                          , bs::avx_\n                          , bs::pack_<bd::single_<A0>, bs::avx_>\n                          )\n   {\n      BOOST_FORCEINLINE std::size_t operator()( const A0& a0) const BOOST_NOEXCEPT\n      {\n        int r = _mm256_movemask_ps(is_nez(a0));\n        return popcnt(r);\n      }\n   };\n\n   BOOST_DISPATCH_OVERLOAD( nbtrue_\n                          , (typename A0)\n                          , bs::avx_\n                          , bs::pack_<bd::integer_<A0>, bs::avx_>\n                          )\n   {\n      BOOST_FORCEINLINE std::size_t operator()( const A0& a0) const BOOST_NOEXCEPT\n      {\n        auto const s = slice(a0);\n        return nbtrue(s[0]) + nbtrue(s[1]);\n      }\n   };\n} } }\n\n#endif\n", "meta": {"hexsha": "bc812a1d1f4c7e28353ce596275c9da36671e11b", "size": 1959, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/x86/avx/simd/function/nbtrue.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/x86/avx/simd/function/nbtrue.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/x86/avx/simd/function/nbtrue.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": 31.5967741935, "max_line_length": 100, "alphanum_fraction": 0.4946401225, "num_tokens": 445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125848754472, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.4735984408540818}}
{"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 VANLEEUWEN2009WNTSWATCELLCYCLEODESYSTEM_HPP_\n#define VANLEEUWEN2009WNTSWATCELLCYCLEODESYSTEM_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#include \"MathsCustomFunctions.hpp\"\n\n/**\n * Represents the van Leeuwen et al. (2007) system of ODEs\n * [doi:10.1016/j.jtbi.2007.01.019]\n * coupled to the Swat et al. cell-cycle model equations.\n * [doi:10.1093/bioinformatics/bth110]\n *\n * The variables are\n *\n *   0. r = pRb\n *   1. e = E2F1 (This is the S-phase indicator)\n *   2. i = CycD (inactive)\n *   3. j = CycD (active)\n *   4. p = pRb-p\n *   5. D = APC destruction complex\n *   6. X = Axin\n *   7. Cu = Beta Cat marked for ubiquitination\n *   8. Co = Open form Beta Cat\n *   9. Cc = Closed form Beta Cat\n *   10. Mo = Open form Mutant Beta Cat\n *   11. Mc = Closed form Mutant Beta Cat\n *   12. A = Free Adhesion molecules\n *   13. Ca = BetaCat/Adhesion\n *   14. Ma = Mutant BetaCat/Adhesion\n *   15. T = free TCF\n *   16. Cot = Open BetaCat/TCF\n *   17. Cct = Closed BetaCat/TCF\n *   18. Mot = Open Mutant BetaCat/TCF\n *   19. Mct = Closed Mutant BetaCat/TCF\n *   20. Y = Wnt Target protein\n *   21. Wnt level\n */\nclass VanLeeuwen2009WntSwatCellCycleOdeSystem : 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 k_16. */\n    double mk16d;\n    /** Dimensional parameter k_61. */\n    double mk61d;\n    /** Dimensionless parameter phi_E2F1. */\n    double mPhiE2F1;\n\n    /**\n     * Parameters for the Van Leeuwen et al. (2007) model\n     */\n\n    /** Dimensionless parameter s_A. */\n    double mSa;\n    /** Dimensionless parameter s_CA. */\n    double mSca;\n    /** Dimensionless parameter s_C. */\n    double mSc;\n    /** Dimensionless parameter s_CT. */\n    double mSct;\n    /** Dimensionless parameter s_D. */\n    double mSd;\n    /** Dimensionless parameter s_T. */\n    double mSt;\n    /** Dimensionless parameter s_X. */\n    double mSx;\n    /** Dimensionless parameter s_Y. */\n    double mSy;\n    /** Dimensionless parameter d_A. */\n    double mDa;\n    /** Dimensionless parameter d_CA. */\n    double mDca;\n    /** Dimensionless parameter d_C. */\n    double mDc;\n    /** Dimensionless parameter d_CT. */\n    double mDct;\n    /** Dimensionless parameter d_D. */\n    double mDd;\n    /** Dimensionless parameter d_Dx. */\n    double mDdx;\n    /** Dimensionless parameter d_T. */\n    double mDt;\n    /** Dimensionless parameter d_U. */\n    double mDu;\n    /** Dimensionless parameter d_X. */\n    double mDx;\n    /** Dimensionless parameter d_Y. */\n    double mDy;\n    /** Dimensionless parameter K_c. */\n    double mKc;\n    /** Dimensionless parameter K_D. */\n    double mKd;\n    /** Dimensionless parameter K_T. */\n    double mKt;\n    /** Dimensionless parameter p_c. */\n    double mPc;\n    /** Dimensionless parameter p_u. */\n    double mPu;\n    /** Dimensionless parameter xi_D. */\n    double mXiD;\n    /** Dimensionless parameter xi_Dx. */\n    double mXiDx;\n    /** Dimensionless parameter xi_X. */\n    double mXiX;\n    /** Dimensionless parameter xi_C. */\n    double mXiC;\n\n    /** The mutation state of the cell. */\n    boost::shared_ptr<AbstractCellMutationState> mpMutationState;\n\n    /**\n     * The hypothesis we are using\n     *  = 1u for Van Leeuwen Hypothesis I\n     *  = 2u for Van Leeuwen Hypothesis II\n     */\n    unsigned mHypothesis;\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 hypothesis takes the value 1 or 2 and affects the ODE system.\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 cell mutation; some affect the ODE system\n     * @param stateVariables optional initial conditions for state variables (only used in archiving)\n     */\n    VanLeeuwen2009WntSwatCellCycleOdeSystem(unsigned hypothesis,\n                                            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    ~VanLeeuwen2009WntSwatCellCycleOdeSystem();\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 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 van Leeuwen et al. (2007) 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     * 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 How close we are to the root of the stopping condition\n     */\n    double CalculateRootFunction(double time, const std::vector<double>& rY);\n\n    /**\n     * @return #mWntLevel.\n     */\n    double GetWntLevel() const;\n\n    /**\n     * @return #mHypothesis.\n     */\n    unsigned GetHypothesis() const;\n};\n\n// Declare identifier for the serializer\n#include \"SerializationExportWrapper.hpp\"\nCHASTE_CLASS_EXPORT(VanLeeuwen2009WntSwatCellCycleOdeSystem)\n\nnamespace boost\n{\nnamespace serialization\n{\n/**\n * Serialize information required to construct a VanLeeuwen2009WntSwatCellCycleOdeSystem.\n */\ntemplate<class Archive>\ninline void save_construct_data(\n    Archive & ar, const VanLeeuwen2009WntSwatCellCycleOdeSystem * t, const unsigned int file_version)\n{\n    // Save data required to construct instance\n    const unsigned hypothesis = t->GetHypothesis();\n    ar & hypothesis;\n\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 VanLeeuwen2009WntSwatCellCycleOdeSystem.\n */\ntemplate<class Archive>\ninline void load_construct_data(\n    Archive & ar, VanLeeuwen2009WntSwatCellCycleOdeSystem * t, const unsigned int file_version)\n{\n    // Retrieve data from archive required to construct new instance\n    unsigned hypothesis;\n    ar & hypothesis;\n\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)VanLeeuwen2009WntSwatCellCycleOdeSystem(hypothesis, wnt_level, p_mutation_state, state_variables);\n}\n}\n} // namespace ...\n\n#endif /*VANLEEUWEN2009WNTSWATCELLCYCLEODESYSTEM_HPP_*/\n", "meta": {"hexsha": "e91583e638fd75c8dff2408bd96b468167c457fb", "size": 11691, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "crypt/src/odes/VanLeeuwen2009WntSwatCellCycleOdeSystem.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": "crypt/src/odes/VanLeeuwen2009WntSwatCellCycleOdeSystem.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": "crypt/src/odes/VanLeeuwen2009WntSwatCellCycleOdeSystem.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": 32.56545961, "max_line_length": 151, "alphanum_fraction": 0.6832606278, "num_tokens": 2966, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.629774621301746, "lm_q1q2_score": 0.47359843385372763}}
{"text": "/*\n * Copyright (C) 2014, Computing Systems Laboratory (CSLab), NTUA.\n * Copyright (C) 2014, Vasileios Karakasis\n * All rights reserved.\n *\n * This file is distributed under the BSD License. See LICENSE.txt for details.\n */\n\n/**\n * \\file Utility.hpp\n * \\brief Several generic utility functions\n *\n * \\author Computing Systems Laboratory (CSLab), NTUA\n * \\date 2011&ndash;2014\n * \\copyright This file is distributed under the BSD License. See LICENSE.txt\n * for details.\n */\n\n#ifndef SPARSEX_INTERNALS_UTILITY_HPP\n#define SPARSEX_INTERNALS_UTILITY_HPP\n\n#include <boost/type_traits.hpp>\n\nusing namespace std;\n\nnamespace sparsex {\n  namespace utilities {\n\n    template<bool property>\n    struct math_impl\n    {\n      template<typename T>\n      static T do_gcd(T a, T b);\n\n      template <typename T>\n      static T do_abs(T a);\n\n      template <typename T>\n      static T do_iceil(T a, T b);\n    };\n\n    template<typename T>\n    T gcd(T a, T b)\n    {\n      return math_impl<boost::is_integral<T>::value>::do_gcd(a, b);\n    }\n\n    // Integer ceiling\n    template<typename T>\n    T iceil(T a, T b)\n    {\n      return math_impl<boost::is_integral<T>::value>::do_iceil(a, b);\n    }\n\n    template<typename T>\n    T abs(T a)\n    {\n      return math_impl<boost::is_arithmetic<T>::value>::do_abs(a);\n    }\n\n    template<typename T>\n    T lcm(T a, T b)\n    {\n      return abs(a*b) / gcd(a, b);\n    }\n\n    template<>\n    struct math_impl<true> \n    {\n      template<typename T>\n      static T do_gcd(T a, T b)\n      {\n        while (b) {\n\t  T t = b;\n\t  b = a % b;\n\t  a = t;\n        }\n\n        return a;\n      }\n\n      template<typename T>\n      static T do_iceil(T a, T b)\n      {\n        return a / b + (a % b != 0);\n      }\n\n      template<typename T>\n      static T do_abs(T a)\n      {\n        return (a < 0) ? -a : a;\n      }\n    };\n\n    template<bool is_pointer>\n    struct iterator_checker\n    {\n      template<typename Iterator>\n      static void do_check(const Iterator &) {}\n    };\n\n    template<typename Iterator>\n    void check_iterator(const Iterator &i)\n    {\n      iterator_checker<boost::is_pointer<Iterator>::value>::do_check(i);\n    }\n\n    template<>\n    struct iterator_checker<true>\n    {\n      template<typename Iterator>\n      static void do_check(const Iterator &i)\n      {\n        if (!i)\n\t  throw invalid_argument(\"invalid iterator\");\n      }\n    };\n\n  } // end of namespace utilities\n} // end of namespace sparsex\n\n#endif  // SPARSEX_INTERNALS_UTILITY_HPP\n", "meta": {"hexsha": "fd4e1d92b1daf6643a15efa8c652424b0caf00f5", "size": 2468, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/sparsex/internals/Utility.hpp", "max_stars_repo_name": "Baltoli/sparsex", "max_stars_repo_head_hexsha": "36145d9c47e40dbd7da71ba5a75b7644e2eda5d8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 28.0, "max_stars_repo_stars_event_min_datetime": "2015-02-03T13:19:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T15:46:11.000Z", "max_issues_repo_path": "include/sparsex/internals/Utility.hpp", "max_issues_repo_name": "Baltoli/sparsex", "max_issues_repo_head_hexsha": "36145d9c47e40dbd7da71ba5a75b7644e2eda5d8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-06-19T06:41:47.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-10T09:51:17.000Z", "max_forks_repo_path": "include/sparsex/internals/Utility.hpp", "max_forks_repo_name": "Baltoli/sparsex", "max_forks_repo_head_hexsha": "36145d9c47e40dbd7da71ba5a75b7644e2eda5d8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T16:06:59.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-01T12:30:04.000Z", "avg_line_length": 20.0650406504, "max_line_length": 79, "alphanum_fraction": 0.5980551053, "num_tokens": 638, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125848754471, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.4735984304031128}}
{"text": "#include \"SMPSInput.hpp\"\n#include \"ClpBALPInterface.hpp\"\n#include <boost/scoped_ptr.hpp>\n#include <cstdlib>\n\nusing boost::scoped_ptr; // replace with unique_ptr for C++11\nusing namespace std;\n\nint main(int argc, char **argv) {\n\t\n\tMPI_Init(&argc, &argv);\n\n\tint mype;\n\tMPI_Comm_rank(MPI_COMM_WORLD,&mype);\n\n\tif (argc != 2) {\n\t\tif (mype == 0) printf(\"Usage: %s [SMPS root name]\\n\",argv[0]);\n\t\treturn 1;\n\t}\t\n\n\tstring smpsrootname(argv[1]);\n\n\tSMPSInput input(smpsrootname+\".cor\",smpsrootname+\".tim\",smpsrootname+\".sto\");\n\n\tBAContext ctx(MPI_COMM_WORLD);\n\tctx.initializeAssignment(input.nScenarios());\n\n\tClpBALPInterface solver(input, ctx, ClpBALPInterface::useDual);\n\tif (argc == 5) {\n\t\tsolver.loadStatus(argv[4]);\n\t}\n\t//solver.setDumpFrequency(5000,argv[3]);\t\n\tsolver.setPrimalTolerance(1e-6);\n\tsolver.setDualTolerance(1e-6);\n\tsolver.go();\n\n\n\tif (argc >= 4 && argv[3][0] != '-') {\n\t\tif (mype == 0) printf(\"Writing solution\\n\");\n\t\tsolver.writeStatus(argv[3]);\n\t\tif (mype == 0) printf(\"Finished writing solution\\n\");\n\t}\n\n\tMPI_Finalize();\n\n\treturn 0;\n}\n\n", "meta": {"hexsha": "8e5462d1360800ab65e13bb846593a92dae07769", "size": 1047, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PIPS-S/Drivers/clpSMPS.cpp", "max_stars_repo_name": "jalving/PIPS", "max_stars_repo_head_hexsha": "62f664237447c7ce05a62552952c86003d90e68f", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 65.0, "max_stars_repo_stars_event_min_datetime": "2016-02-04T18:03:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T08:59:38.000Z", "max_issues_repo_path": "PIPS-S/Drivers/clpSMPS.cpp", "max_issues_repo_name": "jalving/PIPS", "max_issues_repo_head_hexsha": "62f664237447c7ce05a62552952c86003d90e68f", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": 34.0, "max_issues_repo_issues_event_min_datetime": "2015-11-17T04:26:51.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-24T16:00:22.000Z", "max_forks_repo_path": "PIPS-S/Drivers/clpSMPS.cpp", "max_forks_repo_name": "jalving/PIPS", "max_forks_repo_head_hexsha": "62f664237447c7ce05a62552952c86003d90e68f", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2015-10-15T20:27:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-14T08:13:34.000Z", "avg_line_length": 21.3673469388, "max_line_length": 78, "alphanum_fraction": 0.6809933142, "num_tokens": 325, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597974, "lm_q2_score": 0.6297746074044135, "lm_q1q2_score": 0.47359842340275893}}
{"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_DETAIL_CONSTANT_MEDIUM_PI_HPP_INCLUDED\n#define BOOST_SIMD_DETAIL_CONSTANT_MEDIUM_PI_HPP_INCLUDED\n\n#include <boost/simd/config.hpp>\n#include <boost/simd/detail/brigand.hpp>\n#include <boost/simd/detail/dispatch.hpp>\n#include <boost/simd/detail/constant_traits.hpp>\n#include <boost/simd/detail/dispatch/function/make_callable.hpp>\n#include <boost/simd/detail/dispatch/hierarchy/functions.hpp>\n#include <boost/simd/detail/dispatch/as.hpp>\n\n/*\n\n\n    @ingroup group-constant\n\n    Constant used in trigonometric reductions\n\n    @par Semantic:\n\n    For type T:\n\n    @code\n    T r = Medium_pi<T>();\n    @endcode\n\n    is similar to:\n\n    @code\n    if T is double\n      r = Pi<T>()*pow2(18);\n    else if T is float\n      r = Pi<T>()*pow2(6);\n    else\n      r =  201\n    @endcode\n\n    @return a value of type T\n\n*/\n\nnamespace boost { namespace simd\n{\n  namespace tag\n  {\n    struct medium_pi_ : boost::dispatch::constant_value_<medium_pi_>\n    {\n      BOOST_DISPATCH_MAKE_CALLABLE(ext,medium_pi_,boost::dispatch::constant_value_<medium_pi_>);\n      BOOST_SIMD_REGISTER_CONSTANT(201, 0X43490FDB, 0X412921FB54442D18LL); //2^6/pi, //2^{18}/pi;\n    };\n  }\n\n  namespace ext\n  {\n    BOOST_DISPATCH_FUNCTION_DECLARATION(tag,medium_pi_);\n  }\n\n  namespace detail\n  {\n    BOOST_DISPATCH_CALLABLE_DEFINITION(tag::medium_pi_,medium_pi);\n  }\n\n  template<typename T> BOOST_FORCEINLINE auto Medium_pi()\n  BOOST_NOEXCEPT_DECLTYPE(detail::medium_pi( boost::dispatch::as_<T>{}))\n  {\n    return detail::medium_pi( boost::dispatch::as_<T>{} );\n  }\n} }\n\n#include <boost/simd/arch/common/scalar/constant/constant_value.hpp>\n#include <boost/simd/arch/common/simd/constant/constant_value.hpp>\n\n#endif\n", "meta": {"hexsha": "0d083ecae6577d5217b6cb4d7964aabd21b271fa", "size": 2076, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/detail/constant/medium_pi.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/detail/constant/medium_pi.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/detail/constant/medium_pi.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": 24.7142857143, "max_line_length": 100, "alphanum_fraction": 0.6454720617, "num_tokens": 503, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125848754472, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.47359841995214375}}
{"text": "#include <boost/numeric/odeint/stepper/generation/generation_dense_output_runge_kutta.hpp>\n", "meta": {"hexsha": "0341d74e5b966d9a8d469b3c1833a679b31d674f", "size": 91, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_numeric_odeint_stepper_generation_generation_dense_output_runge_kutta.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_numeric_odeint_stepper_generation_generation_dense_output_runge_kutta.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_numeric_odeint_stepper_generation_generation_dense_output_runge_kutta.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 45.5, "max_line_length": 90, "alphanum_fraction": 0.8791208791, "num_tokens": 23, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.6297746004557471, "lm_q1q2_score": 0.4735984181772743}}
{"text": "#include <Eigen/Core>\n#include <aslam/common/pose-types.h>\n#include <ceres-error-terms/parameterization/pose-param-jpl.h>\n#include <ceres/ceres.h>\n#include <eigen-checks/gtest.h>\n#include <glog/logging.h>\n#include <gtest/gtest.h>\n#include <maplab-common/quaternion-math.h>\n#include <maplab-common/test/testing-entrypoint.h>\n#include <maplab-common/test/testing-predicates.h>\n\n#include <ceres-error-terms/common.h>\n#include <ceres-error-terms/six-dof-block-pose-error-term-autodiff.h>\n\nclass SixDofBlockPoseErrorTerms : public ::testing::Test {\n public:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n protected:\n  virtual void SetUp() {\n    prior_position_A_ << 1, 2, 3;\n    prior_position_B_ << 4, 5, 6;\n    prior_orientation_A_.coeffs() << sqrt(2) / 2, 0, 0, sqrt(2) / 2;\n    prior_orientation_B_.coeffs() << 0.15496688, -0.60676538, 0.30722298,\n        0.71654385;\n    prior_orientation_B_.coeffs().normalize();\n\n    pose_A_ << prior_orientation_A_.coeffs(), prior_position_A_;\n    pose_B_ << prior_orientation_B_.coeffs(), prior_position_B_;\n\n    covariance_matrix_.setIdentity();\n  }\n\n  void addResidual(const aslam::Transformation& T_A_B);\n  void solve();\n\n  void fixA();\n  void fixB();\n\n  ceres::Problem problem_;\n  ceres::Solver::Summary summary_;\n\n  Eigen::Vector3d prior_position_A_;\n  Eigen::Vector3d prior_position_B_;\n  Eigen::Quaterniond prior_orientation_A_;\n  Eigen::Quaterniond prior_orientation_B_;\n\n  Eigen::Matrix<double, 7, 1> pose_A_;\n  Eigen::Matrix<double, 7, 1> pose_B_;\n  Eigen::Matrix<double, 6, 6> covariance_matrix_;\n};\n\nvoid SixDofBlockPoseErrorTerms::addResidual(\n    const aslam::Transformation& T_A_B) {\n  ceres::LocalParameterization* pose_parameterization =\n      new ceres_error_terms::JplPoseParameterization;\n\n  ceres::CostFunction* relative_pose_cost = new ceres::AutoDiffCostFunction<\n      ceres_error_terms::SixDoFBlockPoseErrorTerm,\n      ceres_error_terms::SixDoFBlockPoseErrorTerm::residualBlockSize,\n      ceres_error_terms::poseblocks::kPoseSize,\n      ceres_error_terms::poseblocks::kPoseSize>(\n      new ceres_error_terms::SixDoFBlockPoseErrorTerm(\n          T_A_B, covariance_matrix_));\n\n  problem_.AddResidualBlock(\n      relative_pose_cost, NULL, pose_A_.data(), pose_B_.data());\n\n  problem_.SetParameterization(pose_A_.data(), pose_parameterization);\n  problem_.SetParameterization(pose_B_.data(), pose_parameterization);\n}\n\nvoid SixDofBlockPoseErrorTerms::fixA() {\n  problem_.SetParameterBlockConstant(pose_A_.data());\n}\n\nvoid SixDofBlockPoseErrorTerms::fixB() {\n  problem_.SetParameterBlockConstant(pose_B_.data());\n}\n\nvoid SixDofBlockPoseErrorTerms::solve() {\n  ceres::Solver::Options options;\n  options.linear_solver_type = ceres::DENSE_SCHUR;\n  options.minimizer_progress_to_stdout = false;\n  options.parameter_tolerance = 1e-14;\n  options.gradient_tolerance = 1e-14;\n  options.function_tolerance = 1e-14;\n  options.max_num_iterations = 30u;\n  LOG(INFO) << \"Solving...\";\n  ceres::Solve(options, &problem_, &summary_);\n\n  LOG(INFO) << summary_.BriefReport() << std::endl;\n  LOG(INFO) << summary_.message << std::endl;\n}\n\nTEST_F(SixDofBlockPoseErrorTerms, TestPosePriorErrorTermZeroCost) {\n  aslam::Transformation T_G_A(prior_orientation_A_, prior_position_A_);\n  aslam::Transformation T_G_B(prior_orientation_B_, prior_position_B_);\n\n  addResidual(T_G_A.inverse() * T_G_B);\n  fixA();\n  solve();\n\n  EXPECT_NEAR(summary_.initial_cost, 0.0, 1e-12);\n  EXPECT_NEAR(summary_.final_cost, 0.0, 1e-12);\n  EXPECT_EQ(summary_.iterations.size(), 1u);\n}\n\nTEST_F(SixDofBlockPoseErrorTerms, TestPosePriorErrorTermIdentityPoseA) {\n  aslam::Transformation T_G_A(prior_orientation_A_, prior_position_A_);\n\n  addResidual(aslam::Transformation());\n  fixA();\n  solve();\n\n  aslam::Transformation T_G_B_est(\n      Eigen::Quaterniond(pose_B_.head(4).data()), pose_B_.tail(3));\n\n  EXPECT_NEAR(summary_.final_cost, 0.0, 1e-12);\n  EXPECT_TRUE(\n      EIGEN_MATRIX_NEAR(\n          T_G_B_est.getTransformationMatrix(), T_G_A.getTransformationMatrix(),\n          1e-8));\n}\n\nTEST_F(SixDofBlockPoseErrorTerms, TestPosePriorErrorTermIdentityPoseB) {\n  aslam::Transformation T_G_B(prior_orientation_B_, prior_position_B_);\n\n  addResidual(aslam::Transformation());\n  fixB();\n  solve();\n\n  aslam::Transformation T_G_A_est(\n      Eigen::Quaterniond(pose_A_.head(4).data()), pose_A_.tail(3));\n\n  EXPECT_NEAR(summary_.final_cost, 0.0, 1e-12);\n  EXPECT_TRUE(\n      EIGEN_MATRIX_NEAR(\n          T_G_A_est.getTransformationMatrix(), T_G_B.getTransformationMatrix(),\n          1e-8));\n}\n\nTEST_F(SixDofBlockPoseErrorTerms, TestPosePriorErrorTermNonIdentity) {\n  aslam::Transformation T_G_A(prior_orientation_A_, prior_position_A_);\n\n  Eigen::Vector3d q_A_B_axis_angle_vec;\n  q_A_B_axis_angle_vec << 0.2, -1.2, 0.4;\n  Eigen::Vector3d q_A_B_axis = q_A_B_axis_angle_vec;\n  q_A_B_axis.normalize();\n  aslam::AngleAxis q_A_B_angle_axis(q_A_B_axis_angle_vec.norm(), q_A_B_axis);\n  aslam::Quaternion q_A_B(q_A_B_angle_axis);\n  Eigen::Vector3d p_A_B;\n  p_A_B << 12.4, 423.3, -341.423;\n  aslam::Transformation T_A_B(q_A_B, p_A_B);\n\n  addResidual(T_A_B);\n  fixA();\n  solve();\n\n  aslam::Transformation T_G_B_est(\n      Eigen::Quaterniond(pose_B_.head(4).data()), pose_B_.tail(3));\n\n  EXPECT_NEAR(summary_.final_cost, 0.0, 1e-12);\n  EXPECT_TRUE(\n      EIGEN_MATRIX_NEAR(\n          T_G_B_est.getTransformationMatrix(),\n          (T_G_A * T_A_B).getTransformationMatrix(), 1e-8));\n}\n\nMAPLAB_UNITTEST_ENTRYPOINT\n", "meta": {"hexsha": "7377259b54867eee37b04e7aa465266c78a9b120", "size": 5396, "ext": "cc", "lang": "C++", "max_stars_repo_path": "algorithms/ceres-error-terms/test/test_six_dof_block_transformation_error_term.cc", "max_stars_repo_name": "AdronTech/maplab", "max_stars_repo_head_hexsha": "1340e01466fc1c02994860723b8117daf9ad226d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1936.0, "max_stars_repo_stars_event_min_datetime": "2017-11-27T23:11:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T14:24:14.000Z", "max_issues_repo_path": "algorithms/ceres-error-terms/test/test_six_dof_block_transformation_error_term.cc", "max_issues_repo_name": "AdronTech/maplab", "max_issues_repo_head_hexsha": "1340e01466fc1c02994860723b8117daf9ad226d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 353.0, "max_issues_repo_issues_event_min_datetime": "2017-11-29T18:40:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T15:53:46.000Z", "max_forks_repo_path": "algorithms/ceres-error-terms/test/test_six_dof_block_transformation_error_term.cc", "max_forks_repo_name": "AdronTech/maplab", "max_forks_repo_head_hexsha": "1340e01466fc1c02994860723b8117daf9ad226d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 661.0, "max_forks_repo_forks_event_min_datetime": "2017-11-28T07:20:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T08:06:29.000Z", "avg_line_length": 31.5555555556, "max_line_length": 79, "alphanum_fraction": 0.7436990363, "num_tokens": 1548, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597971, "lm_q2_score": 0.6297746004557471, "lm_q1q2_score": 0.47359841817727427}}
{"text": "#include \"NeuralNet.hpp\" \n#include <string>\n#include <fstream>\n#include <iostream>\n#include <boost/range/irange.hpp>\n#include <typeinfo>\n\nint main() {\n    std::cout << \"Hello World\" << std::endl;\n\n    // test softmax forward - OK\n    // ActivationSoftmax activation_softmax;\n    // Eigen::MatrixXd test_in(2, 3);\n    // Eigen::MatrixXd test_out;\n    // test_in.row(0) << 1, 2, 3;\n    // test_in.row(1) << 4, 5, 6;\n    // // std::cout << \"test_in\" << test_in << std::endl;\n    // activation_softmax.forward(test_in);\n    // test_out = activation_softmax.output;\n    // std::cout << \"test_out\" << \"\\n\" << test_out << std::endl;\n\n    // test softmax backward - OK\n    // ActivationSoftmax activation_softmax;\n    // Eigen::MatrixXd test_in(2, 3);\n    // Eigen::MatrixXd output(2, 3);\n    // Eigen::MatrixXd test_out;\n    // test_in.row(0) << 1, 2, 3;\n    // test_in.row(1) << 4, 5, 6;\n    // std::cout << \"test_in\" << \"\\n\" << test_in << std::endl;\n    // output.row(0) << 1, 2, 3;\n    // output.row(1) << 4, 5, 6;\n    // activation_softmax.output = output;\n    // std::cout << \"activation_softmax.output\" << \"\\n\" << activation_softmax.output << std::endl;\n    // activation_softmax.backward(test_in);\n    // test_out = activation_softmax.dinputs;\n    // std::cout << \"test_out\" << \"\\n\" << test_out << std::endl;\n\n    // test dense backward - OK\n    // LayerDense dense1(2, 3);\n    // Eigen::MatrixXd test_in(2, 3);\n    // Eigen::MatrixXd test_out;\n    // test_in.row(0) << 1, 2, 3;\n    // test_in.row(1) << 4, 5, 6;\n    // Eigen::MatrixXd inputs(2, 3);\n    // inputs.row(0) << 1, 2, 3;\n    // inputs.row(1) << 4, 5, 6;\n    // dense1.inputs = inputs;\n    // dense1.backward(test_in);\n    // test_out = dense1.dweights;\n    // std::cout << \"test_out\" << \"\\n\" << test_out << std::endl;\n\n    // test dense forward - OK\n    // LayerDense dense1(2, 3);\n    // Eigen::MatrixXd test_in(2, 3);\n    // Eigen::MatrixXd test_out;\n    // test_in.row(0) << 1, 2, 3;\n    // test_in.row(1) << 4, 5, 6;\n    // std::cout << \"dense1.biases is of size \" << dense1.biases.rows() << \"x\" << dense1.biases.cols() << std::endl;\n    // Eigen::MatrixXd weights(2, 3);\n    // weights.row(0) << 1.0, -1.0, 0.5;\n    // weights.row(1) << 0.5, -0.1, 2.0;\n    // dense1.weights = weights;\n    // dense1.forward(test_in.transpose());\n    // test_out = dense1.output;\n    // std::cout << \"dense1.weights\" << \"\\n\" << dense1.weights << std::endl;\n    // std::cout << \"test_out\" << \"\\n\" << test_out << std::endl;\n\n    // test relu backward - OK\n    // ActivationRelu activation_relu;\n    // Eigen::MatrixXd test_in(2, 3);\n    // Eigen::MatrixXd test_out;\n    // test_in.row(0) << 1, 2, 3;\n    // test_in.row(1) << 4.1, -5, 6;\n    // Eigen::MatrixXd inputs(2, 3);\n    // inputs.row(0) << 1, 2, 0;\n    // inputs.row(1) << 0, 5, -6;\n    // activation_relu.inputs = inputs;\n    // activation_relu.backward(test_in);\n    // test_out = activation_relu.dinputs;\n    // std::cout << \"test_out\" << \"\\n\" << test_out << std::endl;\n\n    // test relu forward - OK\n    // ActivationRelu activation_relu;\n    // Eigen::MatrixXd test_in(2, 3);\n    // Eigen::MatrixXd test_out;\n    // test_in.row(0) << 1, 2, -3;\n    // test_in.row(1) << 4.1, -5, 6;\n    // activation_relu.forward(test_in);\n    // test_out = activation_relu.output;\n    // std::cout << \"test_out\" << \"\\n\" << test_out << std::endl;\n\n    // test loss forward - OK\n    // CrossEntropyLoss loss_categorical_crossentropy;\n    // Eigen::MatrixXd y_pred(4, 3);\n    // Eigen::VectorXd y_true(4);\n    // Eigen::MatrixXd test_out;\n    // y_pred.row(0) << 0.8, 0.1, 0.1;\n    // y_pred.row(1) << 0.4, 0.6, 0.9;\n    // y_pred.row(2) << 0.6, 0.1, 0.3;\n    // y_pred.row(3) << 0.5, 0.4, 0.1;\n    // std::cout << \"y_pred\" << \"\\n\" << y_pred << std::endl;\n    // y_true << 2, 2, 0, 1;\n    // std::cout << \"y_true\" << \"\\n\" << y_true << std::endl;\n    // test_out = loss_categorical_crossentropy.forward(y_pred, y_true);\n    // std::cout << \"test_out\" << \"\\n\" << test_out << std::endl;\n    // std::cout << \"test_out\" << \"\\n\" << test_out.rows()<< \"x\" << test_out.cols() << std::endl;\n\n    // test loss calculate - OK\n    // CrossEntropyLoss loss_categorical_crossentropy;\n    // Eigen::MatrixXd y_pred(4, 3);\n    // Eigen::VectorXd y_true(4);\n    // double test_out;\n    // y_pred.row(0) << 0.8, 0.1, 0.1;\n    // y_pred.row(1) << 0.4, 0.6, 0.9;\n    // y_pred.row(2) << 0.6, 0.1, 0.3;\n    // y_pred.row(3) << 0.5, 0.4, 0.1;\n    // std::cout << \"y_pred\" << \"\\n\" << y_pred << std::endl;\n    // y_true << 2, 2, 0, 1;\n    // std::cout << \"y_true\" << \"\\n\" << y_true << std::endl;\n    // test_out = loss_categorical_crossentropy.calculate(y_pred, y_true);\n    // std::cout << \"test_out\" << \"\\n\" << test_out << std::endl;\n\n    // test loss backward - OK\n    // CrossEntropyLoss loss_categorical_crossentropy;\n    // Eigen::MatrixXd dvalues(4, 3);\n    // Eigen::VectorXd y_true(4);\n    // Eigen::MatrixXd test_out;\n    // dvalues.row(0) << 0.8, 0.1, 0.1;\n    // dvalues.row(1) << 0.4, 0.6, 0.9;\n    // dvalues.row(2) << 0.6, 0.1, 0.3;\n    // dvalues.row(3) << 0.5, 0.4, 0.1;\n    // std::cout << \"dvalues\" << dvalues.rows()<< \"x\" << dvalues.cols() << std::endl;\n    // std::cout << \"dvalues\" << \"\\n\" << dvalues << std::endl;\n    // y_true << 2, 2, 0, 1;\n    // std::cout << \"y_true\" << \"\\n\" << y_true << std::endl;\n    // loss_categorical_crossentropy.backward(dvalues, y_true);\n    // test_out = loss_categorical_crossentropy.dinputs;\n    // std::cout << \"test_out\" << \"\\n\" << test_out << std::endl;\n\n    // test optimizer pre_update_params - OK\n    // StochasticGradientDescent optimizer_SGD(1.0, 1e-3, 0.9);\n    // double test_out;\n    // optimizer_SGD.iterations = 500;\n    // optimizer_SGD.pre_update_params(1.0);\n    // test_out = optimizer_SGD.learning_rate;\n    // std::cout << \"test_out\" << \"\\n\" << test_out << std::endl;\n\n    // test optimizer post_update_params - OK\n    // StochasticGradientDescent optimizer_SGD(1.0, 1e-3, 0.9);\n    // double test_out;\n    // optimizer_SGD.iterations = 500;\n    // optimizer_SGD.post_update_params();\n    // test_out = optimizer_SGD.iterations;\n    // std::cout << \"test_out\" << \"\\n\" << test_out << std::endl;\n\n    // test optimizer update_params - OK\n    // LayerDense dense1(2, 3);\n    // Eigen::MatrixXd test_in(2, 3);\n    // Eigen::MatrixXd test_out_w;\n    // Eigen::VectorXd test_out_b;\n    // test_in.row(0) << 1, 2, 3;\n    // test_in.row(1) << 4, 5, 6;\n\n    // Eigen::MatrixXd weights(2, 3);\n    // weights.row(0) << 1.0, -1.0, 0.5;\n    // weights.row(1) << 0.5, -0.1, 2.0;\n    // dense1.weights = weights;\n\n    // Eigen::MatrixXd dweights(2, 3);\n    // dweights.row(0) << 0.1, -0.1, 0.5;\n    // dweights.row(1) << 0.7, -0.2, 1.1;\n    // dense1.dweights = dweights;\n\n    // Eigen::VectorXd biases(3);\n    // biases << 0.02, -0.3, 0.56;\n    // dense1.biases = biases;\n\n    // Eigen::VectorXd dbiases(3);\n    // dbiases << 1.3, -1.6, 0.44;\n    // dense1.dbiases = dbiases;\n\n    // StochasticGradientDescent optimizer_SGD(1.0, 1e-3, 0.9);\n    // Eigen::MatrixXd test_out;\n    // optimizer_SGD.iterations = 500;\n    // optimizer_SGD.update_params(dense1);\n    // test_out_w = dense1.weights;\n    // std::cout << \"test_out_w\" << \"\\n\" << test_out_w << std::endl;\n    // test_out_b = dense1.biases;\n    // std::cout << \"test_out_b\" << \"\\n\" << test_out_b << std::endl;\n\n}   \n", "meta": {"hexsha": "ec4817990a2fc45b1a2e7ed9f6026208150ef4c2", "size": 7299, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test.cpp", "max_stars_repo_name": "ekloberdanz/Neural-Net-Implementation", "max_stars_repo_head_hexsha": "937dbd2edf695192fb8afcedfe05b1f4ffcdc5ce", "max_stars_repo_licenses": ["MIT"], "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.cpp", "max_issues_repo_name": "ekloberdanz/Neural-Net-Implementation", "max_issues_repo_head_hexsha": "937dbd2edf695192fb8afcedfe05b1f4ffcdc5ce", "max_issues_repo_licenses": ["MIT"], "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.cpp", "max_forks_repo_name": "ekloberdanz/Neural-Net-Implementation", "max_forks_repo_head_hexsha": "937dbd2edf695192fb8afcedfe05b1f4ffcdc5ce", "max_forks_repo_licenses": ["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.015625, "max_line_length": 116, "alphanum_fraction": 0.5625428141, "num_tokens": 2518, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585903489891, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.473578452046657}}
{"text": "#include <catch2/catch.hpp>\n\n#include <Toucan/LinAlg.h>\n\n#include <iostream>\n#include <cmath>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\ntemplate<typename scalar_type> using EigenVector2 = Eigen::Matrix<scalar_type, 2, 1>;\ntemplate<typename scalar_type> using EigenVector3 = Eigen::Matrix<scalar_type, 3, 1>;\ntemplate<typename scalar_type> using EigenVector4 = Eigen::Matrix<scalar_type, 4, 1>;\n\n\n// Toucan-Eigen matrix equality operator\ntemplate<typename scalar_type, int rows, int columns>\nbool operator==(const Toucan::Matrix<scalar_type, rows, columns>& toucan_matrix, const Eigen::Matrix<scalar_type, rows, columns>& eigen_matrix) {\n\t\n\tfor (int row_index = 0; row_index < rows; ++row_index) {\n\t\tfor (int column_index = 0; column_index < columns; ++column_index) {\n\t\t\tif (toucan_matrix(row_index, column_index) != eigen_matrix(row_index, column_index)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\t\n\treturn true;\n}\n\n// Toucan-Eigen matrix inequality operator\ntemplate<typename scalar_type, int rows, int columns>\nbool operator!=(const Toucan::Matrix<scalar_type, rows, columns>& toucan_matrix, const Eigen::Matrix<scalar_type, rows, columns>& eigen_matrix) {\n\t\n\tfor (int row_index = 0; row_index < rows; ++row_index) {\n\t\tfor (int column_index = 0; column_index < columns; ++column_index) {\n\t\t\tif (toucan_matrix(row_index, column_index) != eigen_matrix(row_index, column_index)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\t\n\treturn false;\n}\n\nTEMPLATE_TEST_CASE(\"Matrix static constructors\", \"[matrix][static_constructor]\", float, double, int) {\n\t\n\tSECTION(\"Zero\") {\n\t\tToucan::Matrix4<TestType> matrix_zero_toucan = Toucan::Matrix4<TestType>::Zero();\n\t\tEigen::Matrix<TestType, 4, 4> matrix_zero_eigen = Eigen::Matrix<TestType, 4, 4>::Zero();\n\t\tREQUIRE((matrix_zero_toucan == matrix_zero_eigen));\n\t}\n\t\n\tSECTION(\"Ones\") {\n\t\tToucan::Matrix4<TestType> matrix_ones_toucan = Toucan::Matrix4<TestType>::Ones();\n\t\tEigen::Matrix<TestType, 4, 4> matrix_ones_eigen = Eigen::Matrix<TestType, 4, 4>::Ones();\n\t\t\n\t\tREQUIRE((matrix_ones_toucan == matrix_ones_eigen));\n\t}\n\t\n\tSECTION(\"Identity\") {\n\t\tToucan::Matrix4<TestType> matrix_identity_toucan = Toucan::Matrix4<TestType>::Identity();\n\t\tEigen::Matrix<TestType, 4, 4> matrix_identity_eigen = Eigen::Matrix<TestType, 4, 4>::Identity();\n\t\t\n\t\tREQUIRE((matrix_identity_toucan == matrix_identity_eigen));\n\t}\n\t\n\tSECTION(\"UnitX\") {\n\t\tToucan::Vector2<TestType> v2 = Toucan::Vector2<TestType>::UnitX();\n\t\tREQUIRE(v2.x() == Approx(1));\n\t\tREQUIRE(v2.y() == Approx(0));\n\t\t\n\t\tToucan::Vector3<TestType> v3 = Toucan::Vector3<TestType>::UnitX();\n\t\tREQUIRE(v3.x() == Approx(1));\n\t\tREQUIRE(v3.y() == Approx(0));\n\t\tREQUIRE(v3.z() == Approx(0));\n\t}\n\t\n\tSECTION(\"UnitX RowVector\") {\n\t\tToucan::RowVector2<TestType> v2 = Toucan::RowVector2<TestType>::UnitX();\n\t\tREQUIRE(v2.x() == Approx(1));\n\t\tREQUIRE(v2.y() == Approx(0));\n\t\t\n\t\tToucan::RowVector3<TestType> v3 = Toucan::RowVector3<TestType>::UnitX();\n\t\tREQUIRE(v3.x() == Approx(1));\n\t\tREQUIRE(v3.y() == Approx(0));\n\t\tREQUIRE(v3.z() == Approx(0));\n\t}\n\t\n\tSECTION(\"UnitY\") {\n\t\tToucan::Vector2<TestType> v2 = Toucan::Vector2<TestType>::UnitY();\n\t\tREQUIRE(v2.x() == Approx(0));\n\t\tREQUIRE(v2.y() == Approx(1));\n\t\t\n\t\tToucan::Vector3<TestType> v3 = Toucan::Vector3<TestType>::UnitY();\n\t\tREQUIRE(v3.x() == Approx(0));\n\t\tREQUIRE(v3.y() == Approx(1));\n\t\tREQUIRE(v3.z() == Approx(0));\n\t}\n\t\n\tSECTION(\"UnitY RowVector\") {\n\t\tToucan::RowVector2<TestType> v2 = Toucan::RowVector2<TestType>::UnitY();\n\t\tREQUIRE(v2.x() == Approx(0));\n\t\tREQUIRE(v2.y() == Approx(1));\n\t\t\n\t\tToucan::RowVector3<TestType> v3 = Toucan::RowVector3<TestType>::UnitY();\n\t\tREQUIRE(v3.x() == Approx(0));\n\t\tREQUIRE(v3.y() == Approx(1));\n\t\tREQUIRE(v3.z() == Approx(0));\n\t}\n\t\n\tSECTION(\"UnitZ\") {\n\t\tToucan::Vector3<TestType> v3 = Toucan::Vector3<TestType>::UnitZ();\n\t\tREQUIRE(v3.x() == Approx(0));\n\t\tREQUIRE(v3.y() == Approx(0));\n\t\tREQUIRE(v3.z() == Approx(1));\n\t}\n\t\n\tSECTION(\"UnitZ RowVector\") {\n\t\tToucan::RowVector3<TestType> v3 = Toucan::RowVector3<TestType>::UnitZ();\n\t\tREQUIRE(v3.x() == Approx(0));\n\t\tREQUIRE(v3.y() == Approx(0));\n\t\tREQUIRE(v3.z() == Approx(1));\n\t}\n\t\n\tSECTION(\"UnitN\") {\n\t\tToucan::Matrix<TestType, 32, 1> v = Toucan::Matrix<TestType, 32, 1>::UnitN(10);\n\t\tfor (int index = 0; index < 32; ++index) {\n\t\t\tif (index == 10) {\n\t\t\t\tREQUIRE(v(index) == Approx(1));\n\t\t\t} else {\n\t\t\t\tREQUIRE(v(index) == Approx(0));\n\t\t\t}\n\t\t}\n\t}\n\t\n\tSECTION(\"UnitN RowVector\") {\n\t\tToucan::Matrix<TestType, 1, 32> v = Toucan::Matrix<TestType, 1, 32>::UnitN(10);\n\t\tfor (int index = 0; index < 32; ++index) {\n\t\t\tif (index == 10) {\n\t\t\t\tREQUIRE(v(index) == Approx(1));\n\t\t\t} else {\n\t\t\t\tREQUIRE(v(index) == Approx(0));\n\t\t\t}\n\t\t}\n\t}\n}\n\nTEMPLATE_TEST_CASE(\"Matrix default constructor\", \"[matrix][constructor]\", float, double, int) {\n\tToucan::Vector3<TestType> v3;\n\tREQUIRE(v3.x() == Approx(0));\n\tREQUIRE(v3.y() == Approx(0));\n\tREQUIRE(v3.z() == Approx(0));\n}\n\n\nTEMPLATE_TEST_CASE(\"Matrix constructors\", \"[matrix][constructor]\", float, double, int) {\n\t\n\tToucan::Matrix3<TestType> matrix_toucan(\n\t\tTestType(1), TestType(2), TestType(3),\n\t\tTestType(4), TestType(5), TestType(6),\n\t\tTestType(7), TestType(8), TestType(9)\n\t);\n\tEigen::Matrix<TestType, 3, 3> matrix_eigen;\n\tmatrix_eigen << TestType(1), TestType(2), TestType(3),\n\t                TestType(4), TestType(5), TestType(6),\n\t                TestType(7), TestType(8), TestType(9);\n\t\n\tREQUIRE((matrix_toucan == matrix_eigen));\n\t\n\t// TODO(Matias): Check that a invalid number of parameters to a Toucan Matrix constructor fails at compile time.\n}\n\nTEMPLATE_TEST_CASE(\"Matrix constructors 2\", \"[matrix][constructor]\", float, double, int) {\n\tToucan::Matrix<TestType, 2, 2> m2_zero(\n\t\t\tTestType(0), TestType(0),\n\t\t\tTestType(0), TestType(0)\n\t);\n\t\n\tToucan::Matrix<TestType, 2, 2> m2_ones(\n\t\t\tTestType(1), TestType(1),\n\t\t\tTestType(1), TestType(1)\n\t);\n\t\n\tToucan::Matrix<TestType, 2, 2> m2_identity(\n\t\t\tTestType(1), TestType(0),\n\t\t\tTestType(0), TestType(1)\n\t);\n\t\n\t\n\tSECTION(\"Zero\") {\n\t\tREQUIRE(Toucan::Matrix<TestType, 2, 2>::Zero() == m2_zero);\n\t\tREQUIRE_FALSE(Toucan::Matrix<TestType, 2, 2>::Zero() != m2_zero);\n\t\t\n\t\tREQUIRE_FALSE(Toucan::Matrix<TestType, 2, 2>::Zero() == m2_ones);\n\t\tREQUIRE(Toucan::Matrix<TestType, 2, 2>::Zero() != m2_ones);\n\t\t\n\t\tREQUIRE_FALSE(Toucan::Matrix<TestType, 2, 2>::Zero() == m2_identity);\n\t\tREQUIRE(Toucan::Matrix<TestType, 2, 2>::Zero() != m2_identity);\n\t}\n\tSECTION(\"Ones\") {\n\t\tREQUIRE_FALSE(Toucan::Matrix<TestType, 2, 2>::Ones() == m2_zero);\n\t\tREQUIRE(Toucan::Matrix<TestType, 2, 2>::Ones() != m2_zero);\n\t\t\n\t\tREQUIRE(Toucan::Matrix<TestType, 2, 2>::Ones() == m2_ones);\n\t\tREQUIRE_FALSE(Toucan::Matrix<TestType, 2, 2>::Ones() != m2_ones);\n\t\t\n\t\tREQUIRE_FALSE(Toucan::Matrix<TestType, 2, 2>::Ones() == m2_identity);\n\t\tREQUIRE(Toucan::Matrix<TestType, 2, 2>::Ones() != m2_identity);\n\t}\n\tSECTION(\"Identity\") {\n\t\tREQUIRE_FALSE(Toucan::Matrix<TestType, 2, 2>::Identity() == m2_zero);\n\t\tREQUIRE(Toucan::Matrix<TestType, 2, 2>::Identity() != m2_zero);\n\t\t\n\t\tREQUIRE_FALSE(Toucan::Matrix<TestType, 2, 2>::Identity() == m2_ones);\n\t\tREQUIRE(Toucan::Matrix<TestType, 2, 2>::Identity() != m2_ones);\n\t\t\n\t\tREQUIRE(Toucan::Matrix<TestType, 2, 2>::Identity() == m2_identity);\n\t\tREQUIRE_FALSE(Toucan::Matrix<TestType, 2, 2>::Identity() != m2_identity);\n\t\t\n\t}\n}\n\nTEMPLATE_TEST_CASE(\"Matrix shape\", \"[matrix][shape]\", float, double, int) {\n\tToucan::Vector2<TestType> v2;\n\tSTATIC_REQUIRE(v2.number_of_rows() == 2);\n\tSTATIC_REQUIRE(v2.number_of_columns() == 1);\n\tSTATIC_REQUIRE(v2.number_of_elements() == 2);\n\t\n\tToucan::Vector3<TestType> v3;\n\tSTATIC_REQUIRE(v3.number_of_rows() == 3);\n\tSTATIC_REQUIRE(v3.number_of_columns() == 1);\n\tSTATIC_REQUIRE(v3.number_of_elements() == 3);\n\t\n\tToucan::Vector4<TestType> v4;\n\tSTATIC_REQUIRE(v4.number_of_rows() == 4);\n\tSTATIC_REQUIRE(v4.number_of_columns() == 1);\n\tSTATIC_REQUIRE(v4.number_of_elements() == 4);\n\t\n\tToucan::RowVector2<TestType> v2_row;\n\tSTATIC_REQUIRE(v2_row.number_of_rows() == 1);\n\tSTATIC_REQUIRE(v2_row.number_of_columns() == 2);\n\tSTATIC_REQUIRE(v2_row.number_of_elements() == 2);\n\t\n\tToucan::RowVector3<TestType> v3_row;\n\tSTATIC_REQUIRE(v3_row.number_of_rows() == 1);\n\tSTATIC_REQUIRE(v3_row.number_of_columns() == 3);\n\tSTATIC_REQUIRE(v3_row.number_of_elements() == 3);\n\t\n\tToucan::RowVector4<TestType> v4_row;\n\tSTATIC_REQUIRE(v4_row.number_of_rows() == 1);\n\tSTATIC_REQUIRE(v4_row.number_of_columns() == 4);\n\tSTATIC_REQUIRE(v4_row.number_of_elements() == 4);\n\t\n\tToucan::Matrix<TestType, 4, 8> m1;\n\tSTATIC_REQUIRE(m1.number_of_rows() == 4);\n\tSTATIC_REQUIRE(m1.number_of_columns() == 8);\n\tSTATIC_REQUIRE(m1.number_of_elements() == 32);\n}\n\nTEMPLATE_TEST_CASE(\"Matrix norms\", \"[matrix][norm]\", float, double) {\n\tToucan::Vector2<TestType> v2_ones = Toucan::Vector2<TestType>::Ones();\n\tREQUIRE(v2_ones.norm() == Approx(std::sqrt(2)));\n\t\n\tToucan::Vector3<TestType> v3_ones = Toucan::Vector3<TestType>::Ones();\n\tREQUIRE(v3_ones.norm() == Approx(std::sqrt(3)));\n\t\n\tToucan::Matrix<TestType, 2, 2> m2_ones = Toucan::Matrix<TestType, 2, 2>::Ones();\n\tREQUIRE(m2_ones.norm() == Approx(std::sqrt(4)));\n\t\n\tToucan::Vector4<TestType> v4(TestType(1), TestType(2), TestType(3), TestType(4));\n\tconst TestType v4_squared_sum = 1+4+9+16;\n\tconst TestType v4_sum = std::sqrt(v4_squared_sum);\n\tREQUIRE(v4.norm() == Approx(std::sqrt(v4_squared_sum)));\n\t\n\tToucan::Vector4<TestType> v4_normalized = v4.normalized();\n\tREQUIRE(v4_normalized(0) == Approx(1.0/v4_sum));\n\tREQUIRE(v4_normalized(1) == Approx(2.0/v4_sum));\n\tREQUIRE(v4_normalized(2) == Approx(3.0/v4_sum));\n\tREQUIRE(v4_normalized(3) == Approx(4.0/v4_sum));\n\t\n\tv4.normalize();\n\tREQUIRE(v4(0) == Approx(1.0/v4_sum));\n\tREQUIRE(v4(1) == Approx(2.0/v4_sum));\n\tREQUIRE(v4(2) == Approx(3.0/v4_sum));\n\tREQUIRE(v4(3) == Approx(4.0/v4_sum));\n}\n\nTEMPLATE_TEST_CASE(\"Matrix squared norms\", \"[matrix][norms]\", float, double, int) {\n\tToucan::Vector2<TestType> v2_ones = Toucan::Vector2<TestType>::Ones();\n\tREQUIRE(v2_ones.squared_norm() == Approx(2));\n\t\n\tToucan::Vector3<TestType> v3_ones = Toucan::Vector3<TestType>::Ones();\n\tREQUIRE(v3_ones.squared_norm() == Approx(3));\n\t\n\tToucan::Matrix<TestType, 2, 2> m2_ones = Toucan::Matrix<TestType, 2, 2>::Ones();\n\tREQUIRE(m2_ones.squared_norm() == Approx(4));\n\t\n\tToucan::Vector4<TestType> v4(TestType(1), TestType(2), TestType(3), TestType(4));\n\tconst TestType v4_squared_sum = 1+4+9+16;\n\tREQUIRE(v4.squared_norm() == Approx(v4_squared_sum));\n}\n\nTEMPLATE_TEST_CASE(\"Matrix math functions\", \"[matrix][math]\", float, double, int) {\n\t\n\tSECTION(\"Trace\") {\n\t\tToucan::Matrix<TestType, 4, 4> m4(\n\t\t\t\tTestType(1), TestType(2), TestType(3), TestType(4),\n\t\t\t\tTestType(5), TestType(6), TestType(7), TestType(8),\n\t\t\t\tTestType(9), TestType(10), TestType(11), TestType(12),\n\t\t\t\tTestType(13), TestType(14), TestType(15), TestType(16)\n\t\t);\n\t\t\n\t\tREQUIRE(m4.trace() == Approx(1+6+11+16));\n\t}\n\t\n\tToucan::Vector3<TestType> v1(TestType(1), TestType(2), TestType(3));\n\tToucan::Vector3<TestType> v2(TestType(4), TestType(5), TestType(6));\n\t\n\tSECTION(\"Dot product\") {\n\t\tTestType dot_product = v1.dot_product(v2);\n\t\tREQUIRE(dot_product == Approx(32));\n\t}\n\t\n\tSECTION(\"Cross product\") {\n\t\tToucan::Vector3<TestType> cross_product = v1.cross_product(v2);\n\t\tREQUIRE(cross_product.x() == Approx(-3));\n\t\tREQUIRE(cross_product.y() == Approx(6));\n\t\tREQUIRE(cross_product.z() == Approx(-3));\n\t}\n}\n\nTEMPLATE_TEST_CASE(\"Vector accessors\", \"[matrix][accessor]\", float, double, int) {\n\tToucan::Vector2<TestType> v2;\n\tv2.x() = TestType(1);\n\tv2.y() = TestType(2);\n\t\n\tREQUIRE(v2.x() == TestType(1));\n\tREQUIRE(v2.y() == TestType(2));\n\t\n\tToucan::Vector3<TestType> v3;\n\tv3.x() = TestType(1);\n\tv3.y() = TestType(2);\n\tv3.z() = TestType(3);\n\t\n\tREQUIRE(v3.x() == TestType(1));\n\tREQUIRE(v3.y() == TestType(2));\n\tREQUIRE(v3.z() == TestType(3));\n}\n\nTEMPLATE_TEST_CASE(\"Vector const accessors\", \"[matrix][accessor]\", float, double, int) {\n\tconst Toucan::Vector2<TestType> v2(TestType(1), TestType(2));\n\t\n\tREQUIRE(v2.x() == TestType(1));\n\tREQUIRE(v2.y() == TestType(2));\n\t\n\tconst Toucan::Vector3<TestType> v3(TestType(1), TestType(2), TestType(3));\n\t\n\tREQUIRE(v3.x() == TestType(1));\n\tREQUIRE(v3.y() == TestType(2));\n\tREQUIRE(v3.z() == TestType(3));\n}\n\nTEMPLATE_TEST_CASE(\"Row Vector accessors\", \"[matrix][accessor]\", float, double, int) {\n\tToucan::RowVector2<TestType> v2;\n\tv2.x() = TestType(1);\n\tv2.y() = TestType(2);\n\t\n\tREQUIRE(v2.x() == TestType(1));\n\tREQUIRE(v2.y() == TestType(2));\n\t\n\tToucan::RowVector3<TestType> v3;\n\tv3.x() = TestType(1);\n\tv3.y() = TestType(2);\n\tv3.z() = TestType(3);\n\t\n\tREQUIRE(v3.x() == TestType(1));\n\tREQUIRE(v3.y() == TestType(2));\n\tREQUIRE(v3.z() == TestType(3));\n}\n\nTEMPLATE_TEST_CASE(\"Row Vector const accessors\", \"[matrix][accessor]\", float, double, int) {\n\tconst Toucan::RowVector2<TestType> v2(TestType(1), TestType(2));\n\t\n\tREQUIRE(v2.x() == TestType(1));\n\tREQUIRE(v2.y() == TestType(2));\n\t\n\tconst Toucan::RowVector3<TestType> v3(TestType(1), TestType(2), TestType(3));\n\t\n\tREQUIRE(v3.x() == TestType(1));\n\tREQUIRE(v3.y() == TestType(2));\n\tREQUIRE(v3.z() == TestType(3));\n}\n\n\nTEMPLATE_TEST_CASE(\"Rotation matrices\", \"[matrix]\", float, double) {\n\tconstexpr TestType angle_1 = TestType(7)*M_PI/TestType(3);\n\tconstexpr TestType angle_2 = TestType(5)*M_PI/TestType(3);\n\tconstexpr TestType angle_3 = TestType(4)*M_PI/TestType(3);\n\t\n\tconst Eigen::Matrix<TestType, 3, 3> r1_eigen =\n\t\t\t(Eigen::AngleAxis<TestType>(angle_1, EigenVector3<TestType>::UnitX()) *\n\t\t\t Eigen::AngleAxis<TestType>(angle_2, EigenVector3<TestType>::UnitY()) *\n\t\t\t Eigen::AngleAxis<TestType>(angle_3, EigenVector3<TestType>::UnitZ())).toRotationMatrix();\n\t\n\tconst EigenVector3<TestType> v1_eigen(TestType(1), TestType(2), TestType(3));\n\tconst EigenVector3<TestType> v1_eigen_transformed = r1_eigen * v1_eigen;\n\t\n\tconst Toucan::Matrix3<TestType> r1_toucan =\n\t\t\tToucan::create_3d_rotation_matrix_x(angle_1) *\n\t\t\tToucan::create_3d_rotation_matrix_y(angle_2) *\n\t\t\tToucan::create_3d_rotation_matrix_z(angle_3);\n\t\n\tconst Toucan::Vector3<TestType> v1_toucan(TestType(1), TestType(2), TestType(3));\n\tconst Toucan::Vector3<TestType> v1_toucan_transformed = r1_toucan * v1_toucan;\n\t\n\tREQUIRE(v1_toucan_transformed.x() == Approx(v1_eigen_transformed.x()));\n\tREQUIRE(v1_toucan_transformed.y() == Approx(v1_eigen_transformed.y()));\n\tREQUIRE(v1_toucan_transformed.z() == Approx(v1_eigen_transformed.z()));\n}\n\nTEMPLATE_TEST_CASE(\"Diagonal Matrix constructor\", \"[matrix]\", float, double, int) {\n\tconst Toucan::DiagonalMatrix3<TestType> d1;\n\tREQUIRE(d1(0) == Approx(0));\n\tREQUIRE(d1(1) == Approx(0));\n\tREQUIRE(d1(2) == Approx(0));\n\t\n\tconst Toucan::DiagonalMatrix3<TestType> d2(TestType(1), TestType(2), TestType(3));\n\tREQUIRE(d2(0) == Approx(1));\n\tREQUIRE(d2(1) == Approx(2));\n\tREQUIRE(d2(2) == Approx(3));\n}\n\nTEMPLATE_TEST_CASE(\"Diagonal Matrix shape functions\", \"[matrix]\", float, double, int) {\n\tconst Toucan::DiagonalMatrix2<TestType> d2;\n\tREQUIRE(d2.number_of_rows() == 2);\n\tREQUIRE(d2.number_of_columns() == 2);\n\tREQUIRE(d2.number_of_elements() == 2*2);\n\t\n\tconst Toucan::DiagonalMatrix3<TestType> d3;\n\tREQUIRE(d3.number_of_rows() == 3);\n\tREQUIRE(d3.number_of_columns() == 3);\n\tREQUIRE(d3.number_of_elements() == 3*3);\n\t\n\tconst Toucan::DiagonalMatrix4<TestType> d4;\n\tREQUIRE(d4.number_of_rows() == 4);\n\tREQUIRE(d4.number_of_columns() == 4);\n\tREQUIRE(d4.number_of_elements() == 4*4);\n}\n\nTEMPLATE_TEST_CASE(\"Diagonal Matrix get diagonal functions\", \"[matrix]\", float, double, int) {\n\t//const Toucan::DiagonalMatrix2<TestType> d2(TestType(1), TestType(2));\n}\n\nTEMPLATE_TEST_CASE(\"Quaternion default constructor\", \"[quaternion][constructor]\", float, double) {\n\tconst Toucan::Quaternion<TestType> q;\n\tREQUIRE(q.w == Approx(1));\n\tREQUIRE(q.x == Approx(0));\n\tREQUIRE(q.y == Approx(0));\n\tREQUIRE(q.z == Approx(0));\n}\n\nTEMPLATE_TEST_CASE(\"Quaternion 4 scalar constructor\", \"[quaternion][constructor]\", float, double) {\n\tconst Toucan::Quaternion<TestType> q(TestType(1), TestType(2), TestType(3), TestType(4));\n\tREQUIRE(q.w == Approx(1));\n\tREQUIRE(q.x == Approx(2));\n\tREQUIRE(q.y == Approx(3));\n\tREQUIRE(q.z == Approx(4));\n}\n\nTEMPLATE_TEST_CASE(\"Quaternion parameter vector constructor\", \"[quaternion][constructor]\", float, double) {\n\tconst Toucan::Vector4<TestType> v4(TestType(1), TestType(2), TestType(3), TestType(4));\n\tconst Toucan::Quaternion<TestType> q(v4);\n\tREQUIRE(q.w == Approx(1));\n\tREQUIRE(q.x == Approx(2));\n\tREQUIRE(q.y == Approx(3));\n\tREQUIRE(q.z == Approx(4));\n}\n\nTEMPLATE_TEST_CASE(\"Quaternion axis angle constructor\", \"[quaternion][constructor]\", float, double) {\n\tconst Toucan::Vector3<TestType> axis1(TestType(0.506979), TestType(0.253490), TestType(0.823842));\n\tconst TestType angle1 = 1.845;\n\t\n\tconst Toucan::Quaternion<TestType> q1(axis1, angle1);\n\tREQUIRE(q1.w == Approx(0.6038293));\n\tREQUIRE(q1.x == Approx(0.4041198));\n\tREQUIRE(q1.y == Approx(0.2020603));\n\tREQUIRE(q1.z == Approx(0.6566956));\n\t\n\tconst Toucan::Vector3<TestType> axis2(TestType(0.857921), TestType(-0.509391), TestType(-0.067025));\n\tconst TestType angle2 = -2.271;\n\t\n\tconst Toucan::Quaternion<TestType> q2(axis2, angle2);\n\tREQUIRE(q2.w == Approx(0.4216791));\n\tREQUIRE(q2.x == Approx(-0.7779157));\n\tREQUIRE(q2.y == Approx(0.4618878));\n\tREQUIRE(q2.z == Approx(0.0607746));\n}\n\nTEMPLATE_TEST_CASE(\"Quaternion rotation matrix constructor\", \"[quaternion][constructor]\", float, double) {\n\tconst Toucan::Matrix3<TestType> rotation_matrix1(\n\t\t\tTestType(0.0558452), TestType(-0.6297508), TestType(0.7747872),\n\t\t\tTestType(0.9563771), TestType(-0.1891237), TestType(-0.2226545),\n\t\t\tTestType(0.2867475), TestType(0.7534229), TestType(0.5917177)\n\t);\n\t\n\tconst Toucan::Quaternion<TestType> q1(rotation_matrix1);\n\tREQUIRE(q1.w == Approx(0.6038293));\n\tREQUIRE(q1.x == Approx(0.4041198));\n\tREQUIRE(q1.y == Approx(0.2020603));\n\tREQUIRE(q1.z == Approx(0.6566956));\n\t\n\tconst Toucan::Matrix3<TestType> rotation_matrix2(\n\t\t\tTestType(0.5659322), TestType(-0.7698743), TestType(0.2949819),\n\t\t\tTestType(-0.6673648), TestType(-0.2176927), TestType(0.7122037),\n\t\t\tTestType(-0.4840919), TestType(-0.5999195), TestType(-0.6369864)\n\t);\n\t\n\tconst Toucan::Quaternion<TestType> q2(rotation_matrix2);\n\tREQUIRE(q2.w == Approx(0.4216791));\n\tREQUIRE(q2.x == Approx(-0.7779157));\n\tREQUIRE(q2.y == Approx(0.4618878));\n\tREQUIRE(q2.z == Approx(0.0607746));\n}\n\n\nTEMPLATE_TEST_CASE(\"Quaternion operators\", \"[quaternion][operator]\", float, double) {\n\tconst Toucan::Quaternion<TestType> q1(0.6038293, 0.4041198, 0.2020603, 0.6566956);\n\tconst Toucan::Quaternion<TestType> q2(0.4216791, -0.7779157, 0.4618878, 0.0607746);\n\t\n\tconstexpr TestType eps = 1e-4;\n\t\n\tSECTION(\"Quaternion-Quaternion composition\") {\n\t\tconst Toucan::Quaternion<TestType> q_1_2 = q1*q2;\n\t\tREQUIRE(q_1_2.w == Approx(0.435754).epsilon(eps));\n\t\tREQUIRE(q_1_2.x == Approx(-0.590359).epsilon(eps));\n\t\tREQUIRE(q_1_2.y == Approx(-0.17130).epsilon(eps));\n\t\tREQUIRE(q_1_2.z == Approx(0.657456).epsilon(eps));\n\t\t\n\t\tconst Toucan::Quaternion<TestType> q_2_1 = q2*q1;\n\t\tREQUIRE(q_2_1.w == Approx(0.435754).epsilon(eps));\n\t\tREQUIRE(q_2_1.x == Approx(-0.00827987).epsilon(eps));\n\t\tREQUIRE(q_2_1.y == Approx(0.89952).epsilon(eps));\n\t\tREQUIRE(q_2_1.z == Approx(-0.0302316).epsilon(eps));\n\t}\n\t\n\tSECTION(\"Quaternion-Point composition\") {\n\t\tconst Eigen::Quaternion<TestType> q1_eig(q2.w, q2.x, q2.y, q2.z);\n\t\t\n\t\tconst Toucan::Vector3<TestType> p(TestType(8.91), TestType(-42.8), TestType(0.25));\n\t\t\n\t\tconst Toucan::Vector3<TestType> p1 = q1 * p;\n\t\tREQUIRE(p1.x() == Approx(27.6446).epsilon(eps));\n\t\tREQUIRE(p1.y() == Approx(16.5602).epsilon(eps));\n\t\tREQUIRE(p1.z() == Approx(-29.5437).epsilon(eps));\n\t\t\n\t\tconst Toucan::Vector3<TestType> p2 = q2 * p;\n\t\tREQUIRE(p2.x() == Approx(38.0668).epsilon(eps));\n\t\tREQUIRE(p2.y() == Approx(3.54908).epsilon(eps));\n\t\tREQUIRE(p2.z() == Approx(21.204).epsilon(eps));\n\t}\n}\n\nTEMPLATE_TEST_CASE(\"Scaled Transform 2D inverse\", \"\", float, double) {\n\tToucan::ScaledTransform2D<TestType> t(\n\t\t\tTestType(0.123),\n\t\t\tToucan::Vector2<TestType>(TestType(1.0), TestType(2.0)),\n\t\t\tToucan::Vector2<TestType>(TestType(0.5), TestType(2.0))\n\t);\n\t\n\tSECTION(\"3x3 Transformation matrix\") {\n\t\tconst Toucan::Matrix3<TestType> t_matrix = t.transformation_matrix();\n\t\tconst Toucan::Matrix3<TestType> t_matrix_inverse = t.transformation_matrix_inverse();\n\t\tconst Toucan::Matrix3<TestType> identity_1 = t_matrix * t_matrix_inverse;\n\t\tconst Toucan::Matrix3<TestType> identity_2 = t_matrix_inverse * t_matrix;\n\t\t\n\t\tREQUIRE(identity_1(0, 0) == Approx(1));\n\t\tREQUIRE(identity_1(0, 1) == Approx(0));\n\t\tREQUIRE(identity_1(0, 2) == Approx(0));\n\t\tREQUIRE(identity_1(1, 0) == Approx(0));\n\t\tREQUIRE(identity_1(1, 1) == Approx(1));\n\t\tREQUIRE(identity_1(1, 2) == Approx(0));\n\t\tREQUIRE(identity_1(2, 0) == Approx(0));\n\t\tREQUIRE(identity_1(2, 1) == Approx(0));\n\t\tREQUIRE(identity_1(2, 2) == Approx(1));\n\t\t\n\t\tREQUIRE(identity_2(0, 0) == Approx(1));\n\t\tREQUIRE(identity_2(0, 1) == Approx(0));\n\t\tREQUIRE(identity_2(0, 2) == Approx(0));\n\t\tREQUIRE(identity_2(1, 0) == Approx(0));\n\t\tREQUIRE(identity_2(1, 1) == Approx(1));\n\t\tREQUIRE(identity_2(1, 2) == Approx(0));\n\t\tREQUIRE(identity_2(2, 0) == Approx(0));\n\t\tREQUIRE(identity_2(2, 1) == Approx(0));\n\t\tREQUIRE(identity_2(2, 2) == Approx(1));\n\t}\n\t\n\tSECTION(\"4x4 Transformation matrix\") {\n\t\tconst Toucan::Matrix4<TestType> t_matrix = t.transformation_matrix_3d();\n\t\tconst Toucan::Matrix4<TestType> t_matrix_inverse = t.transformation_matrix_inverse_3d();\n\t\tconst Toucan::Matrix4<TestType> identity_1 = t_matrix * t_matrix_inverse;\n\t\tconst Toucan::Matrix4<TestType> identity_2 = t_matrix_inverse * t_matrix;\n\t\t\n\t\tREQUIRE(identity_1(0, 0) == Approx(1));\n\t\tREQUIRE(identity_1(0, 1) == Approx(0));\n\t\tREQUIRE(identity_1(0, 2) == Approx(0));\n\t\tREQUIRE(identity_1(0, 3) == Approx(0));\n\t\tREQUIRE(identity_1(1, 0) == Approx(0));\n\t\tREQUIRE(identity_1(1, 1) == Approx(1));\n\t\tREQUIRE(identity_1(1, 2) == Approx(0));\n\t\tREQUIRE(identity_1(1, 3) == Approx(0));\n\t\tREQUIRE(identity_1(2, 0) == Approx(0));\n\t\tREQUIRE(identity_1(2, 1) == Approx(0));\n\t\tREQUIRE(identity_1(2, 2) == Approx(1));\n\t\tREQUIRE(identity_1(2, 3) == Approx(0));\n\t\tREQUIRE(identity_1(3, 0) == Approx(0));\n\t\tREQUIRE(identity_1(3, 1) == Approx(0));\n\t\tREQUIRE(identity_1(3, 2) == Approx(0));\n\t\tREQUIRE(identity_1(3, 3) == Approx(1));\n\t\t\n\t\tREQUIRE(identity_2(0, 0) == Approx(1));\n\t\tREQUIRE(identity_2(0, 1) == Approx(0));\n\t\tREQUIRE(identity_2(0, 2) == Approx(0));\n\t\tREQUIRE(identity_2(0, 3) == Approx(0));\n\t\tREQUIRE(identity_2(1, 0) == Approx(0));\n\t\tREQUIRE(identity_2(1, 1) == Approx(1));\n\t\tREQUIRE(identity_2(1, 2) == Approx(0));\n\t\tREQUIRE(identity_2(1, 3) == Approx(0));\n\t\tREQUIRE(identity_2(2, 0) == Approx(0));\n\t\tREQUIRE(identity_2(2, 1) == Approx(0));\n\t\tREQUIRE(identity_2(2, 2) == Approx(1));\n\t\tREQUIRE(identity_2(2, 3) == Approx(0));\n\t\tREQUIRE(identity_2(3, 0) == Approx(0));\n\t\tREQUIRE(identity_2(3, 1) == Approx(0));\n\t\tREQUIRE(identity_2(3, 2) == Approx(0));\n\t\tREQUIRE(identity_2(3, 3) == Approx(1));\n\t}\n\t\n}\nTEMPLATE_TEST_CASE(\"Scaled Transform 3D inverse\", \"\", float, double) {\n\tToucan::ScaledTransform3D<TestType> t(\n\t\t\tToucan::Quaternion<TestType>(Toucan::Vector3<TestType>(TestType(1), TestType(2), TestType(3)).normalized(), TestType(2*M_PI/3)),\n\t\t\tToucan::Vector3<TestType>(TestType(1.0), TestType(2.0), TestType(3.0)),\n\t\t\tToucan::Vector3<TestType>(TestType(0.5), TestType(2.0), TestType(3.25))\n\t);\n\t\n\tconst Toucan::Matrix4<TestType> t_matrix = t.transformation_matrix();\n\tconst Toucan::Matrix4<TestType> t_matrix_inverse = t.transformation_matrix_inverse();\n\tconst Toucan::Matrix4<TestType> identity_1 = t_matrix * t_matrix_inverse;\n\tconst Toucan::Matrix4<TestType> identity_2 = t_matrix_inverse * t_matrix;\n\t\n\tREQUIRE(identity_1(0, 0) == Approx(1));\n\tREQUIRE(identity_1(0, 1) == Approx(0));\n\tREQUIRE(identity_1(0, 2) == Approx(0));\n\tREQUIRE(identity_1(0, 3) == Approx(0));\n\tREQUIRE(identity_1(1, 0) == Approx(0));\n\tREQUIRE(identity_1(1, 1) == Approx(1));\n\tREQUIRE(identity_1(1, 2) == Approx(0));\n\tREQUIRE(identity_1(1, 3) == Approx(0));\n\tREQUIRE(identity_1(2, 0) == Approx(0));\n\tREQUIRE(identity_1(2, 1) == Approx(0));\n\tREQUIRE(identity_1(2, 2) == Approx(1));\n\tREQUIRE(identity_1(2, 3) == Approx(0));\n\tREQUIRE(identity_1(3, 0) == Approx(0));\n\tREQUIRE(identity_1(3, 1) == Approx(0));\n\tREQUIRE(identity_1(3, 2) == Approx(0));\n\tREQUIRE(identity_1(3, 3) == Approx(1));\n\t\n\tREQUIRE(identity_2(0, 0) == Approx(1));\n\tREQUIRE(identity_2(0, 1) == Approx(0));\n\tREQUIRE(identity_2(0, 2) == Approx(0));\n\tREQUIRE(identity_2(0, 3) == Approx(0));\n\tREQUIRE(identity_2(1, 0) == Approx(0));\n\tREQUIRE(identity_2(1, 1) == Approx(1));\n\tREQUIRE(identity_2(1, 2) == Approx(0));\n\tREQUIRE(identity_2(1, 3) == Approx(0));\n\tREQUIRE(identity_2(2, 0) == Approx(0));\n\tREQUIRE(identity_2(2, 1) == Approx(0));\n\tREQUIRE(identity_2(2, 2) == Approx(1));\n\tREQUIRE(identity_2(2, 3) == Approx(0));\n\tREQUIRE(identity_2(3, 0) == Approx(0));\n\tREQUIRE(identity_2(3, 1) == Approx(0));\n\tREQUIRE(identity_2(3, 2) == Approx(0));\n\tREQUIRE(identity_2(3, 3) == Approx(1));\n\t\n}\n", "meta": {"hexsha": "27ad52568a6fcd271e297722a46aea4dc0b0efb2", "size": 24682, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit-tests/LinAlg_test.cpp", "max_stars_repo_name": "VVingerfly/Toucan", "max_stars_repo_head_hexsha": "3ca3cd9c7152905ba8b75eadb110e9d2dcb0f4b1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2020-12-14T10:07:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T04:32:56.000Z", "max_issues_repo_path": "test/unit-tests/LinAlg_test.cpp", "max_issues_repo_name": "VVingerfly/Toucan", "max_issues_repo_head_hexsha": "3ca3cd9c7152905ba8b75eadb110e9d2dcb0f4b1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-06-21T12:13:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-21T12:13:06.000Z", "max_forks_repo_path": "test/unit-tests/LinAlg_test.cpp", "max_forks_repo_name": "VVingerfly/Toucan", "max_forks_repo_head_hexsha": "3ca3cd9c7152905ba8b75eadb110e9d2dcb0f4b1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-02T16:19:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-02T16:19:38.000Z", "avg_line_length": 35.9272197962, "max_line_length": 145, "alphanum_fraction": 0.678105502, "num_tokens": 8135, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585669110203, "lm_q2_score": 0.6477982315512488, "lm_q1q2_score": 0.4735784468053493}}
{"text": "#ifndef __GLM_LINK_H__\n#define __GLM_LINK_H__\n\n#include <armadillo>\n\nclass glm_link\n{\npublic:\n    /**\n     * Constructor.\n     *\n     * @param name The name of link function.\n     */\n    glm_link(const std::string &name)\n        : m_name( name )\n    {\n    }\n\n    /**\n     * Destructor.\n     */\n    virtual ~glm_link(){ };\n\n    /**\n     * Returns the name of this link function.\n     *\n     * @return the name of this link function.\n     */\n    std::string get_name() const\n    {\n        return m_name;\n    }\n\n    /**\n     * Compute eta from the mean value parameter (the link function).\n     *\n     * @param mu The mean value parameter.\n     *\n     * @return The linearized parameter eta.\n     */\n    virtual arma::vec eta(const arma::vec &mu) const = 0;\n    \n    /**\n     * The derivative of mu with respect to eta. It is often good to\n     * use the relationship dmu/deta = (deta/dmu)^-1.\n     *\n     * @param mu The mean value parameter.\n     *\n     * @return The derivative of mu with respect to eta.\n     */\n    virtual arma::vec mu_eta(const arma::vec &mu) const = 0;\n\n    /**\n     * Compute the mean value parameter from the linearized parameter.\n     *\n     * @param eta The linearized parameter.\n     *\n     * @return The mean value parameter.\n     */\n    virtual arma::vec mu(const arma::vec &eta) const = 0;\n\nprivate:\n    std::string m_name;\n};\n\n/**\n * Creates a link function from the given name.\n *\n * The following links are avaiable:\n * - \"identity\" g(mu) = mu\n * - \"log\" g(mu) = log(mu)\n * - \"logc\" g(mu) = log(1-mu)\n * - \"logit\" g(mu) = log(mu/(1-mu))\n * - \"odds\" g(mu) = mu/(1-mu)\n *\n * @param link_name The name of the link function.\n *\n * @return The link if found, or null otherwise.\n */\nglm_link *make_link(const std::string &link_name);\n\n#endif /* End of __GLM_LINK_H__ */\n", "meta": {"hexsha": "e0db8754511360876b75059ee63697396b2d98c9", "size": 1796, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/glm/models/links/glm_link.hpp", "max_stars_repo_name": "hoehleatsu/besiq", "max_stars_repo_head_hexsha": "94959e2819251805e19311ce377919e6bccb7bf9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-10-21T14:22:12.000Z", "max_stars_repo_stars_event_max_datetime": "2015-10-21T14:22:12.000Z", "max_issues_repo_path": "libs/glm/models/links/glm_link.hpp", "max_issues_repo_name": "hoehleatsu/besiq", "max_issues_repo_head_hexsha": "94959e2819251805e19311ce377919e6bccb7bf9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-05-26T20:52:31.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-28T16:19:49.000Z", "max_forks_repo_path": "libs/glm/models/links/glm_link.hpp", "max_forks_repo_name": "hoehleatsu/besiq", "max_forks_repo_head_hexsha": "94959e2819251805e19311ce377919e6bccb7bf9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2016-11-06T14:58:37.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-26T14:03:13.000Z", "avg_line_length": 21.6385542169, "max_line_length": 70, "alphanum_fraction": 0.5812917595, "num_tokens": 488, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.47357844445511993}}
{"text": "#ifdef MEX\n// Force header only version\n#ifdef IGL_STATIC_LIBRARY\n#undef IGL_STATIC_LIBRARY\n#endif\n#include <mex.h>\n\n#include <igl/matlab/mexErrMsgTxt.h>\n#include <igl/STR.h>\n#undef assert\n#define assert( isOK ) ( (isOK) ? (void)0 : (void) mexErrMsgTxt(C_STR(__FILE__<<\":\"<<__LINE__<<\": failed assertion `\"<<#isOK<<\"'\"<<std::endl) ) )\n#include <igl/matlab/MexStream.h>\n#include <igl/matlab/prepare_lhs.h>\n\n#include <igl/xml/serialize_xml.h>\n#include <Eigen/Core>\n#include <CGAL/Exact_predicates_exact_constructions_kernel.h>\n#include <wordexp.h>\n#include <iostream>\n\n// http://www.alecjacobson.com/weblog/?p=4477\ntypedef CGAL::Epeck::FT EScalar;\ntypedef Eigen::Matrix<EScalar,Eigen::Dynamic,Eigen::Dynamic> MatrixXE;\nnamespace igl\n{\n  namespace xml\n  {\n    namespace serialization_xml\n    {\n      template <> inline void serialize(\n        const MatrixXE & obj,\n        tinyxml2::XMLDocument* doc,\n        tinyxml2::XMLElement* element,\n        const std::string& name)\n      {\n        const std::function<std::string(const MatrixXE::Scalar &) > to_string = \n          [](const MatrixXE::Scalar & v)->std::string\n          {\n            return\n              STR(CGAL::exact(v));\n          };\n        serialize(obj,name,to_string,doc,element);\n      }\n      template <> inline void deserialize(\n        MatrixXE & obj,\n        const tinyxml2::XMLDocument* doc,\n        const tinyxml2::XMLElement* element,\n        const std::string& name)\n      {\n        const std::function<void(const std::string &,MatrixXE::Scalar &)> & \n          from_string = \n          [](const std::string & s, MatrixXE::Scalar & v)\n          {\n            std::stringstream(s)>>v;\n          };\n        deserialize(doc,element,name,from_string,obj);\n      }\n    }\n  }\n}\n\nvoid mexFunction(\n  int nlhs, mxArray *plhs[], \n  int nrhs, const mxArray *prhs[])\n{\n  using namespace std;\n  using namespace Eigen;\n  using namespace igl;\n  using namespace igl::matlab;\n  igl::matlab::MexStream mout;        \n  std::streambuf *outbuf = cout.rdbuf(&mout);\n\n  mexErrMsgTxt(nrhs >= 1, \"The number of input arguments must be >=1.\");\n  mexErrMsgTxt(mxIsChar(prhs[0]),\"File name should be string\");\n  string filename;\n  {\n    wordexp_t exp_result;\n    wordexp(mxArrayToString(prhs[0]), &exp_result, 0);\n    filename = exp_result.we_wordv[0];\n  }\n\n\n\n  MatrixXE V;\n  MatrixXi F;\n\n  // Read mesh\n  igl::xml::deserialize_xml(V,\"vertices\",filename);\n  igl::xml::deserialize_xml(F,\"faces\",    filename);\n\n  plhs[0] = mxCreateDoubleMatrix(V.rows(),V.cols(), mxREAL);\n  double * Vp = mxGetPr(plhs[0]);\n  switch(nlhs)\n  {\n    default:\n    {\n      mexErrMsgTxt(false,\"Too many output parameters.\");\n    }\n    case 2:\n    {\n      prepare_lhs_index(F,plhs+1);\n      // fall through\n    }\n    case 1:\n    {\n      const int m = V.rows();\n      const int n = V.cols();\n      plhs[0] = mxCreateDoubleMatrix(m,n, mxREAL);\n      double * Vp = mxGetPr(plhs[0]);\n      for(int i = 0;i<m;i++)\n      {\n        for(int j = 0;j<n;j++)\n        {\n          Vp[i+m*j] = CGAL::to_double(V(i,j));\n        }\n      }\n      // fall through\n    }\n    case 0: break;\n  }\n\n}\n#endif\n", "meta": {"hexsha": "616a3834558a19f2911d8b62aaab342c4e303888", "size": 3102, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Geometry_Processing_Toolbox/src/cppmex/read_mesh_from_xml.cpp", "max_stars_repo_name": "sidgairo18/SCILAB_MEX_TOOLBOX", "max_stars_repo_head_hexsha": "fc679f6d226c03b992b632823a5e57abea05cefa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Geometry_Processing_Toolbox/src/cppmex/read_mesh_from_xml.cpp", "max_issues_repo_name": "sidgairo18/SCILAB_MEX_TOOLBOX", "max_issues_repo_head_hexsha": "fc679f6d226c03b992b632823a5e57abea05cefa", "max_issues_repo_licenses": ["MIT"], "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_Processing_Toolbox/src/cppmex/read_mesh_from_xml.cpp", "max_forks_repo_name": "sidgairo18/SCILAB_MEX_TOOLBOX", "max_forks_repo_head_hexsha": "fc679f6d226c03b992b632823a5e57abea05cefa", "max_forks_repo_licenses": ["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.0161290323, "max_line_length": 145, "alphanum_fraction": 0.6044487427, "num_tokens": 864, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585669110203, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.4735784368635826}}
{"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_CONSTANT_TWOTONMB_HPP_INCLUDED\n#define BOOST_SIMD_CONSTANT_TWOTONMB_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n  /*!\n    @ingroup group-constant\n\n    Generate two to the number of mantissa bits.\n\n\n    @par Header <boost/simd/constant/twotonmb.hpp>\n\n    @par Semantic:\n\n    @code\n    T r = Twotonmb<T>();\n    @endcode\n\n    is similar to:\n\n    @code\n    T r = pow(2, Nbmantissabits<T>());\n    @endcode\n\n    @return The Twotonmb constant for the proper type\n  **/\n  template<typename T> T Twotonmb();\n\n  namespace functional\n  {\n    /*!\n      @ingroup group-callable-constant\n      Generate the  constant twotonmb.\n\n      @return The Twotonmb constant for the proper type\n    **/\n    Value Twotonmb();\n  }\n} }\n#endif\n\n#include <boost/simd/constant/scalar/twotonmb.hpp>\n#include <boost/simd/constant/simd/twotonmb.hpp>\n\n#endif\n", "meta": {"hexsha": "0491ccc59c94bb6a76ff2a4276b46ad89b50ba16", "size": 1266, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/constant/twotonmb.hpp", "max_stars_repo_name": "TobiasLudwig/boost.simd", "max_stars_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/simd/constant/twotonmb.hpp", "max_issues_repo_name": "TobiasLudwig/boost.simd", "max_issues_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/constant/twotonmb.hpp", "max_forks_repo_name": "TobiasLudwig/boost.simd", "max_forks_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-02-16T09:58:18.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:22:43.000Z", "avg_line_length": 21.8275862069, "max_line_length": 100, "alphanum_fraction": 0.579778831, "num_tokens": 293, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585669110202, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.47357843686358253}}
{"text": "#pragma once\n\n#include <complex>\n#include <mpreal.h>\n#include <Eigen/MPRealSupport>\n#include <Eigen/CXX11/Tensor>\n\n#include \"piecewise_polynomial.hpp\"\n#include \"detail/gauss_legendre.hpp\"\n#include \"detail/legendre_polynomials.hpp\"\n\nnamespace irlib {\n    inline bool python_runtime_check(bool b, const std::string& message) {\n#ifdef SWIGPYTHON\n        if (!b) {\n            throw std::runtime_error(message);\n        }\n#endif\n        return b;\n    }\n\n    namespace statistics {\n        enum statistics_type {\n            BOSONIC = 0,\n            FERMIONIC = 1\n        };\n    }\n\n    using std::abs;\n    using std::sqrt;\n    using std::pow;\n    using std::cosh;\n    using std::sinh;\n    using std::asin;\n    using std::acos;\n    using std::atan;\n\n    using mpfr::mpreal;\n    using mpfr::abs;\n    using mpfr::sqrt;\n    using mpfr::pow;\n    using mpfr::cosh;\n    using mpfr::sinh;\n    using mpfr::asin;\n    using mpfr::acos;\n    using mpfr::atan;\n\n    //using boost::multiprecision::float128;\n\n    namespace detail {\n        template<typename S> inline S sqrt(const S& s);\n        template<> inline double sqrt<double>(const double& s) {return std::sqrt(s);};\n        template<> inline long double sqrt<long double>(const long double& s) {return std::sqrt(s);};\n        template<> inline mpfr::mpreal sqrt<mpreal>(const mpreal& s) {return mpfr::sqrt(s);};\n\n        template<typename S> inline S pow(const S& s, const S& p);\n        template<> inline double pow<double>(const double& s, const double& p) {return std::pow(s, p);};\n        template<> inline long double pow<long double>(const long double& s, const long double& p) {return std::pow(s, p);};\n        template<> inline mpfr::mpreal pow<mpreal>(const mpreal& s, const mpreal& p) {return mpfr::pow(s, p);};\n    }\n\n    using pp_type = piecewise_polynomial<mpreal,mpreal>;\n\n    using MatrixXmp = Eigen::Matrix<mpfr::mpreal,Eigen::Dynamic,Eigen::Dynamic>;\n    using MatrixXc = Eigen::Matrix<std::complex<double>,Eigen::Dynamic,Eigen::Dynamic>;\n\n    template<typename ScalarType>\n    inline void ir_set_default_prec(mp_prec_t prec);\n\n    template<typename ScalarType>\n    inline mp_prec_t ir_get_default_prec();\n\n    template<>\n    inline\n    void\n    ir_set_default_prec<mpfr::mpreal>(mp_prec_t prec) {\n        mpfr::mpreal::set_default_prec(prec);\n    }\n\n    template<>\n    inline void ir_set_default_prec<double>(mp_prec_t prec) {}\n\n    template<>\n    inline void ir_set_default_prec<long double>(mp_prec_t prec) {}\n\n    template<>\n    inline mp_prec_t ir_get_default_prec<mpfr::mpreal>() {\n        return mpfr::mpreal::get_default_prec();\n    }\n\n    template<>\n    inline mp_prec_t ir_get_default_prec<double>() {\n        return 15;\n    }\n\n    template<>\n    inline mp_prec_t ir_get_default_prec<long double>() {\n        return 20;//extended double?\n    }\n\n    inline mp_prec_t ir_digits2bits(mp_prec_t prec) {\n        return mpfr::digits2bits(prec);\n    }\n\n    inline std::complex<double>\n    to_dcomplex(const std::complex<mpreal>& mp) {\n        return std::complex<double>(\n                static_cast<double>(mp.real()), static_cast<double>(mp.imag())\n        );\n    }\n\n}\n\n", "meta": {"hexsha": "ffa4ac62e23ffd87ac221e852d58103bf4742459", "size": 3131, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "c++/include/irlib/common.hpp", "max_stars_repo_name": "dombrno/irlib", "max_stars_repo_head_hexsha": "c081ac6af6d0f80424e6f3651f02ce5028942e0e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2017-11-09T09:04:40.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-23T20:16:05.000Z", "max_issues_repo_path": "c++/include/irlib/common.hpp", "max_issues_repo_name": "dombrno/irlib", "max_issues_repo_head_hexsha": "c081ac6af6d0f80424e6f3651f02ce5028942e0e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-05-31T10:35:09.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-31T13:04:25.000Z", "max_forks_repo_path": "c++/include/irlib/common.hpp", "max_forks_repo_name": "dombrno/irlib", "max_forks_repo_head_hexsha": "c081ac6af6d0f80424e6f3651f02ce5028942e0e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-05-30T19:31:07.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-13T21:52:47.000Z", "avg_line_length": 27.4649122807, "max_line_length": 124, "alphanum_fraction": 0.6429255829, "num_tokens": 793, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300048, "lm_q2_score": 0.6477982043529716, "lm_q1q2_score": 0.47357843451335285}}
{"text": "/*\n * Taken from http://www.andrew.cmu.edu/user/vanhoeve/mdd/ with the notice:\n * \"The software can be freely used but comes with no warranty\"\n * --------------------------------------------------------\n * Ordering class\n * --------------------------------------------------------\n */\n\n#ifndef ORDERING_HPP_\n#define ORDERING_HPP_\n\n#include <cassert>\n#include <cstdio>\n#include \"instance.hpp\"\n#include \"bdd.hpp\"\n#include <vector>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_int_distribution.hpp>\n\n\nstruct IntComparator {\n\tvector<int> &v;\n\tIntComparator(vector<int> &_v) : v(_v) { }\n\tbool operator()(int i, int j) {\n\t\treturn (v[i] > v[j]);\n\t}\n};\n\n\nusing namespace std;\n\nenum OrderType {\n  MinState, RandMinState, MaximalPath, Random, CutVertexGen, CutVertex, Fixed,\n  MinDegree\n};\n\n// Class representing a general ordering\nstruct IS_Ordering {\n\n\tIndepSetInst   *inst;\n\tchar           name[256];\n\tOrderType\t   order_type;\n\n\tIS_Ordering(IndepSetInst* _inst, OrderType _order_type) : inst(_inst), order_type(_order_type) { }\n\n\t// returns vertex corresponding to particular layer\n\tvirtual int vertex_in_layer(BDD* bdd, int layer) = 0;\n};\n\n\n// Vertex that it is in the least number of states\nstruct MinInState : IS_Ordering {\n\n\tvector<bool> avail_v;   // available vertices\n\n\tMinInState(IndepSetInst *_inst) : IS_Ordering(_inst, MinState) {\n\t\tavail_v.resize(inst->graph->n_vertices, true);\n\t\tsprintf(name, \"min_in_state\");\n\t}\n\n\tint vertex_in_layer(BDD* bdd, int layer);\n};\n\n\n// Vertex that it is in the least number of states - randomized!!\nstruct RandomizedMinInState : IS_Ordering {\n\n\tvector<bool> avail_v;   // available vertices\n\tdouble prob;\t\t\t// probability\n\n\tboost::random::mt19937 gen;\n\n\tRandomizedMinInState(IndepSetInst *_inst, double _prob) : IS_Ordering(_inst, RandMinState), prob(_prob) {\n\t\tavail_v.resize(inst->graph->n_vertices, true);\n\t\tsprintf(name, \"rand_min\");\n\n\t\tgen.seed(inst->graph->n_vertices + inst->graph->n_edges);\n\t}\n\n\tint vertex_in_layer(BDD* bdd, int layer);\n};\n\n\n// Maximal Path Decomposition\nstruct MaximalPathDecomp : IS_Ordering {\n\n\tvector<int> v_in_layer;   // vertex at each layer\n\n\tMaximalPathDecomp(IndepSetInst *_inst) : IS_Ordering(_inst, MaximalPath) {\n\t\tsprintf(name, \"maxpath\");\n\t\tconstruct_ordering();\n\t}\n\n\tint vertex_in_layer(BDD* bdd, int layer) {\n\t\tassert( layer >= 0 && layer < inst->graph->n_vertices);\n\t\treturn v_in_layer[layer];\n\t}\n\nprivate:\n\tvoid construct_ordering();\n};\n\n\n\n// Minimum degree ordering\nstruct MinDegreeOrdering : IS_Ordering {\n\n  vector<int> v_in_layer;   // vertex at each layer\n\n  MinDegreeOrdering(IndepSetInst *_inst) : IS_Ordering(_inst, MinDegree) {\n    sprintf(name, \"mindegree\");\n    construct_ordering();\n  }\n\n  int vertex_in_layer(BDD* bdd, int layer) {\n    assert( layer >= 0 && layer < inst->graph->n_vertices);\n    return v_in_layer[layer];\n  }\n  \nprivate:\n  void construct_ordering();\n};\n\n\n// Random ordering\nstruct RandomOrdering : IS_Ordering {\n\n\tvector<int> v_in_layer;   // vertex at each layer\n\tRandomOrdering(IndepSetInst *_inst) : IS_Ordering(_inst, Random) {\n\t\tsprintf(name, \"random\");\n\t\tv_in_layer.resize(inst->graph->n_vertices);\n\t\tconstruct_ordering();\n\t}\n\n\tint vertex_in_layer(BDD* bdd, int layer) {\n\t\tassert( layer >= 0 && layer < inst->graph->n_vertices);\n\t\treturn v_in_layer[layer];\n\t}\n\nprivate:\n\tvoid construct_ordering();\n};\n\n\n\n// FixedOrdering: read from a file\nstruct FixedOrdering : IS_Ordering {\n\n\tvector<int> v_in_layer;   // vertex at each layer\n\tFixedOrdering(IndepSetInst *_inst, char* filename) : IS_Ordering(_inst, Fixed) {\n\n\t\tsprintf(name, \"fixed\");\n\t\tv_in_layer.resize(inst->graph->n_vertices);\n\t\tread_ordering(filename);\n\t}\n\n\tint vertex_in_layer(BDD* bdd, int layer) {\n\t\tassert( layer >= 0 && layer < inst->graph->n_vertices);\n\t\treturn v_in_layer[layer];\n\t}\n\nprivate:\n\tvoid read_ordering(char* filename);\n};\n\n// FixedOrdering: read from a file\nstruct FixedOrderingFromSeq : IS_Ordering {\n\n\tvector<int> v_in_layer;   // vertex at each layer\n\tFixedOrderingFromSeq(IndepSetInst *_inst, vector<int> action_list) : IS_Ordering(_inst, Fixed) {\n\n\t\tsprintf(name, \"fixed\");\n\t\tv_in_layer.resize(inst->graph->n_vertices);\n\n\t\tint i = 0;\n\t\tfor(auto& a : action_list) {\n\t\t\tv_in_layer[i] = inst->node_mapping.at(a);\n\t\t\ti++;\n\t\t}\n\t}\n\n\tint vertex_in_layer(BDD* bdd, int layer) {\n\t\tassert( layer >= 0 && layer < inst->graph->n_vertices);\n\t\treturn v_in_layer[layer];\n\t}\n\n};\n\n// FixedOrdering: read from a file\nstruct OnlineOrdering : IS_Ordering {\n\n\tvector<int> v_in_layer;   // vertex at each layer\n\tOnlineOrdering(IndepSetInst *_inst) : IS_Ordering(_inst, Fixed) {\n\t\tsprintf(name, \"online\");\n\t\tv_in_layer.resize(inst->graph->n_vertices);\n\n\t}\n\n\tint vertex_in_layer(BDD* bdd, int layer) {\n\t\tassert( layer >= 0 && layer < inst->graph->n_vertices);\n\t\treturn v_in_layer[layer];\n\t}\n\n};\n\n// Cut vertex decomposition\nstruct CutVertexDecompositionGeneralGraph : IS_Ordering {\n\n\tvector<int> v_in_layer;      // vertex at each layer\n\tbool** original_adj_matrix;\n\n\tCutVertexDecompositionGeneralGraph(IndepSetInst *_inst) : IS_Ordering(_inst, CutVertexGen) {\n\t\tsprintf(name, \"cut-vertex-gen\");\n\t\tv_in_layer.resize(inst->graph->n_vertices);\n\n\t\trestrict_graph();\n\t\tconstruct_ordering();\n\t\tregenerate_graph();\n\t}\n\n\tint vertex_in_layer(BDD* bdd, int layer) {\n\t\tassert( layer >= 0 && layer < inst->graph->n_vertices);\n\t\treturn v_in_layer[layer];\n\t}\n\nprivate:\n\tvoid        restrict_graph();\n\tvoid        regenerate_graph();\n\tvoid        construct_ordering();\n\tvoid        identify_components(vector< vector<int> > &comps, vector<bool> &is_in_graph);\n\tvector<int> find_ordering(vector<bool> is_in_graph);\n};\n\n\n// Cut vertex decomposition\nstruct CutVertexDecomposition : IS_Ordering {\n\n\tvector<int> v_in_layer;   // vertex at each layer\n\n\tCutVertexDecomposition(IndepSetInst *_inst) : IS_Ordering(_inst, CutVertex) {\n\t\tsprintf(name, \"cut-vertex\");\n\t\tv_in_layer.resize(inst->graph->n_vertices);\n\t\tconstruct_ordering();\n\t}\n\n\tint vertex_in_layer(BDD* bdd, int layer) {\n\t\tassert( layer >= 0 && layer < inst->graph->n_vertices);\n\t\treturn v_in_layer[layer];\n\t}\n\nprivate:\n\tvoid        construct_ordering();\n\tvoid        identify_components(vector< vector<int> > &comps, vector<bool> &is_in_graph);\n\tvector<int> find_ordering(vector<bool> is_in_graph);\n};\n\n\n\n\n\n\n#endif\n", "meta": {"hexsha": "54216fd092a5628a97e99134512640c01eae103e", "size": 6258, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "models/misp-random/code/include/dd/orderings.hpp", "max_stars_repo_name": "qcappart/learning-DD", "max_stars_repo_head_hexsha": "93094c450f8f0929168b303b4d0680889deeb9b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2018-09-18T20:04:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T19:31:36.000Z", "max_issues_repo_path": "models/misp-random/code/include/dd/orderings.hpp", "max_issues_repo_name": "qcappart/learning-DD", "max_issues_repo_head_hexsha": "93094c450f8f0929168b303b4d0680889deeb9b0", "max_issues_repo_licenses": ["MIT"], "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/misp-random/code/include/dd/orderings.hpp", "max_forks_repo_name": "qcappart/learning-DD", "max_forks_repo_head_hexsha": "93094c450f8f0929168b303b4d0680889deeb9b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-07-26T01:22:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-10T13:48:18.000Z", "avg_line_length": 23.7946768061, "max_line_length": 106, "alphanum_fraction": 0.6967082135, "num_tokens": 1669, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.4735784345133528}}
{"text": "// This file is part of the dune-stuff project:\n//   https://github.com/wwu-numerik/dune-stuff/\n// Copyright holders: Rene Milk, Felix Schindler\n// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)\n\n#ifndef DUNE_STUFF_FUNCTIONS_ESV2007_HH\n#define DUNE_STUFF_FUNCTIONS_ESV2007_HH\n\n#include <cmath>\n\n#include <type_traits>\n\n#if HAVE_EIGEN\n#include <Eigen/Eigenvalues>\n#endif\n\n#include <dune/geometry/referenceelements.hh>\n\n#include <dune/stuff/common/configuration.hh>\n#include <dune/stuff/common/debug.hh>\n#include <dune/stuff/common/ranges.hh>\n#include <dune/stuff/la/container/eigen.hh>\n\n#include \"interfaces.hh\"\n\nnamespace Dune {\nnamespace Stuff {\nnamespace Functions {\nnamespace ESV2007 {\n\ntemplate <class E, class D, size_t d, class R, size_t r, size_t rC = 1>\nclass Testcase1Force : public LocalizableFunctionInterface<E, D, d, R, r, rC>\n{\n  Testcase1Force() { static_assert(AlwaysFalse<E>::value, \"Not available for these dimensions!\"); }\n};\n\ntemplate <class EntityImp, class DomainFieldImp, class RangeFieldImp>\nclass Testcase1Force<EntityImp, DomainFieldImp, 2, RangeFieldImp, 1, 1>\n    : public GlobalFunctionInterface<EntityImp, DomainFieldImp, 2, RangeFieldImp, 1>\n{\n  typedef Testcase1Force<EntityImp, DomainFieldImp, 2, RangeFieldImp, 1, 1> ThisType;\n  typedef GlobalFunctionInterface<EntityImp, DomainFieldImp, 2, RangeFieldImp, 1, 1> BaseType;\n\npublic:\n  using typename BaseType::DomainFieldType;\n  using typename BaseType::DomainType;\n  using typename BaseType::RangeType;\n  using typename BaseType::JacobianRangeType;\n\n  static const bool available = true;\n\n  static std::string static_id() { return BaseType::static_id() + \".ESV2007.testcase1.force\"; }\n\n  static Common::Configuration default_config(const std::string sub_name = \"\")\n  {\n    Common::Configuration config;\n    config[\"integration_order\"] = \"3\";\n    config[\"name\"] = static_id();\n    if (sub_name.empty())\n      return config;\n    else {\n      Common::Configuration tmp;\n      tmp.add(config, sub_name);\n      return tmp;\n    }\n  } // ... default_config(...)\n\n  static std::unique_ptr<ThisType> create(const Common::Configuration config = default_config(),\n                                          const std::string sub_name = static_id())\n  {\n    // get correct config\n    const Common::Configuration cfg         = config.has_sub(sub_name) ? config.sub(sub_name) : config;\n    const Common::Configuration default_cfg = default_config();\n    // create\n    return Common::make_unique<ThisType>(cfg.get(\"integration_order\", default_cfg.get<size_t>(\"integration_order\")),\n                                         cfg.get(\"name\", default_cfg.get<std::string>(\"name\")));\n  } // ... create(...)\n\n  Testcase1Force(const size_t ord = default_config().get<size_t>(\"integration_order\"),\n                 const std::string nm = static_id())\n    : order_(ord), name_(nm)\n  {\n  }\n\n  Testcase1Force(const ThisType& /*other*/) = default;\n\n  ThisType& operator=(const ThisType& /*other*/) = delete;\n\n  virtual std::string type() const override final { return BaseType::static_id() + \".ESV2007.testcase1.force\"; }\n\n  virtual std::string name() const override final { return name_; }\n\n  virtual size_t order() const override final { return order_; }\n\n  /**\n   * \\brief \"0.5 * pi * pi * cos(0.5 * pi * x[0]) * cos(0.5 * pi * x[1])\"\n   */\n  virtual void evaluate(const DomainType& xx, RangeType& ret) const override final\n  {\n    ret[0] = M_PI_2l * M_PIl * cos(M_PI_2l * xx[0]) * cos(M_PI_2l * xx[1]);\n  }\n\n  /**\n   * \\brief [\"-0.25 * pi * pi * pi * sin(0.5 * pi * x[0]) * cos(0.5 * pi * x[1])\"\n   *         \"-0.25 * pi * pi * pi * cos(0.5 * pi * x[0]) * sin(0.5 * pi * x[1])\"]\n   */\n  virtual void jacobian(const DomainType& xx, JacobianRangeType& ret) const override final\n  {\n    const DomainFieldType pre   = -0.25 * M_PIl * M_PIl * M_PIl;\n    const DomainFieldType x_arg = M_PI_2l * xx[0];\n    const DomainFieldType y_arg = M_PI_2l * xx[1];\n    ret[0][0]                   = pre * sin(x_arg) * cos(y_arg);\n    ret[0][1]                   = pre * cos(x_arg) * sin(y_arg);\n  } // ... jacobian(...)\n\nprivate:\n  const size_t order_;\n  const std::string name_;\n}; // class Testcase1Force\n\ntemplate <class E, class D, size_t d, class R, size_t r, size_t rC = 1>\nclass Testcase1ExactSolution : public LocalizableFunctionInterface<E, D, d, R, r, rC>\n{\n  Testcase1ExactSolution() { static_assert(AlwaysFalse<E>::value, \"Not available for these dimensions!\"); }\n};\n\ntemplate <class EntityImp, class DomainFieldImp, class RangeFieldImp>\nclass Testcase1ExactSolution<EntityImp, DomainFieldImp, 2, RangeFieldImp, 1, 1>\n    : public GlobalFunctionInterface<EntityImp, DomainFieldImp, 2, RangeFieldImp, 1, 1>\n{\n  typedef Testcase1ExactSolution<EntityImp, DomainFieldImp, 2, RangeFieldImp, 1, 1> ThisType;\n  typedef GlobalFunctionInterface<EntityImp, DomainFieldImp, 2, RangeFieldImp, 1, 1> BaseType;\n\npublic:\n  using typename BaseType::DomainFieldType;\n  using typename BaseType::DomainType;\n  using typename BaseType::RangeType;\n  using typename BaseType::JacobianRangeType;\n\n  static const bool available = true;\n\n  static std::string static_id() { return BaseType::static_id() + \".ESV2007.testcase1.exactsolution\"; }\n\n  static Common::Configuration default_config(const std::string sub_name = \"\")\n  {\n    Common::Configuration config;\n    config[\"integration_order\"] = \"3\";\n    config[\"name\"] = static_id();\n    if (sub_name.empty())\n      return config;\n    else {\n      Common::Configuration tmp;\n      tmp.add(config, sub_name);\n      return tmp;\n    }\n  } // ... default_config(...)\n\n  static std::unique_ptr<ThisType> create(const Common::Configuration config = default_config(),\n                                          const std::string sub_name = static_id())\n  {\n    // get correct config\n    const Common::Configuration cfg         = config.has_sub(sub_name) ? config.sub(sub_name) : config;\n    const Common::Configuration default_cfg = default_config();\n    // create\n    return Common::make_unique<ThisType>(cfg.get(\"integration_order\", default_cfg.get<size_t>(\"integration_order\")),\n                                         cfg.get(\"name\", default_cfg.get<std::string>(\"name\")));\n  } // ... create(...)\n\n  Testcase1ExactSolution(const size_t ord = default_config().get<size_t>(\"integration_order\"),\n                         const std::string nm = static_id())\n    : order_(ord), name_(nm)\n  {\n  }\n\n  Testcase1ExactSolution(const ThisType& /*other*/) = default;\n\n  ThisType& operator=(const ThisType& /*other*/) = delete;\n\n  virtual std::string type() const override final { return BaseType::static_id() + \".ESV2007.testcase1.exactsolution\"; }\n\n  virtual std::string name() const override final { return name_; }\n\n  virtual size_t order() const override final { return order_; }\n\n  /**\n   * \\brief \"cos(0.5 * pi * x[0]) * cos(0.5 * pi * x[1])\"\n   */\n  virtual void evaluate(const DomainType& xx, RangeType& ret) const override final\n  {\n    ret[0] = cos(M_PI_2l * xx[0]) * cos(M_PI_2l * xx[1]);\n  }\n\n  /**\n   * \\brief [\"-0.5 * pi * sin(0.5 * pi * x[0]) * cos(0.5 * pi * x[1])\"\n   *         \"-0.5 * pi * cos(0.5 * pi * x[0]) * sin(0.5 * pi * x[1])\"]\n   */\n  virtual void jacobian(const DomainType& xx, JacobianRangeType& ret) const override final\n  {\n    const DomainFieldType pre   = -0.5 * M_PIl;\n    const DomainFieldType x_arg = M_PI_2l * xx[0];\n    const DomainFieldType y_arg = M_PI_2l * xx[1];\n    ret[0][0]                   = pre * sin(x_arg) * cos(y_arg);\n    ret[0][1]                   = pre * cos(x_arg) * sin(y_arg);\n  } // ... jacobian(...)\n\nprivate:\n  const size_t order_;\n  const std::string name_;\n}; // class Testcase1ExactSolution\n\ntemplate <class DiffusionFactorType, class DiffusionTensorType = void>\nclass Cutoff;\n\ntemplate <class DiffusionType>\nclass Cutoff<DiffusionType, void>\n    : public LocalizableFunctionInterface<typename DiffusionType::EntityType, typename DiffusionType::DomainFieldType,\n                                          DiffusionType::dimDomain, typename DiffusionType::RangeFieldType, 1, 1>\n{\n  static_assert(std::is_base_of<Tags::LocalizableFunction, DiffusionType>::value,\n                \"DiffusionType has to be tagged as a LocalizableFunction!\");\n  typedef typename DiffusionType::EntityType E_;\n  typedef typename DiffusionType::DomainFieldType D_;\n  static const size_t d_ = DiffusionType::dimDomain;\n  typedef typename DiffusionType::RangeFieldType R_;\n  typedef LocalizableFunctionInterface<E_, D_, d_, R_, 1> BaseType;\n  typedef Cutoff<DiffusionType> ThisType;\n\n  class Localfunction : public LocalfunctionInterface<E_, D_, d_, R_, 1, 1>\n  {\n    typedef LocalfunctionInterface<E_, D_, d_, R_, 1, 1> BaseType;\n\n  public:\n    typedef typename BaseType::EntityType EntityType;\n\n    typedef typename BaseType::DomainFieldType DomainFieldType;\n    static const size_t dimDomain = BaseType::dimDomain;\n    typedef typename BaseType::DomainType DomainType;\n\n    typedef typename BaseType::RangeFieldType RangeFieldType;\n    static const size_t dimRange     = BaseType::dimRange;\n    static const size_t dimRangeCols = BaseType::dimRangeCols;\n    typedef typename BaseType::RangeType RangeType;\n\n    typedef typename BaseType::JacobianRangeType JacobianRangeType;\n\n  private:\n    template <class D, int r, int rR>\n    struct Compute\n    {\n      static_assert(AlwaysFalse<D>::value, \"Not implemented for these dimensions!\");\n    };\n\n    template <class D>\n    struct Compute<D, 1, 1>\n    {\n      static RangeFieldType min_eigenvalue_of(const D& diffusion, const EntityType& ent)\n      {\n        const auto local_diffusion = diffusion.local_function(ent);\n        assert(local_diffusion->order() == 0);\n        const auto& reference_element = ReferenceElements<DomainFieldType, dimDomain>::general(ent.type());\n        return local_diffusion->evaluate(reference_element.position(0, 0))[0];\n      } // ... min_eigenvalue_of_(...)\n    };  // class Compute< ..., 1, 1 >\n\n  public:\n    Localfunction(const EntityType& ent, const DiffusionType& diffusion, const RangeFieldType poincare_constant)\n      : BaseType(ent), value_(0)\n    {\n      const RangeFieldType min_eigen_value =\n          Compute<DiffusionType, DiffusionType::dimRange, DiffusionType::dimRangeCols>::min_eigenvalue_of(diffusion,\n                                                                                                          ent);\n      assert(min_eigen_value > 0.0);\n      const DomainFieldType hh = compute_diameter_of_(ent);\n      value_                   = (poincare_constant * hh * hh) / min_eigen_value;\n    }\n\n    Localfunction(const Localfunction& /*other*/) = delete;\n\n    Localfunction& operator=(const Localfunction& /*other*/) = delete;\n\n    virtual size_t order() const override final { return 0; }\n\n    virtual void evaluate(const DomainType& UNUSED_UNLESS_DEBUG(xx), RangeType& ret) const override final\n    {\n      assert(this->is_a_valid_point(xx));\n      ret[0] = value_;\n    }\n\n    virtual void jacobian(const DomainType& UNUSED_UNLESS_DEBUG(xx), JacobianRangeType& ret) const override final\n    {\n      assert(this->is_a_valid_point(xx));\n      ret *= RangeFieldType(0);\n    }\n\n  private:\n    static DomainFieldType compute_diameter_of_(const EntityType& ent)\n    {\n      DomainFieldType ret(0);\n      for (auto cc : DSC::valueRange(ent.template count<dimDomain>())) {\n        const auto vertex = ent.template subEntity<dimDomain>(cc)->geometry().center();\n        for (auto dd : DSC::valueRange(cc + 1, ent.template count<dimDomain>())) {\n          const auto other_vertex = ent.template subEntity<dimDomain>(dd)->geometry().center();\n          const auto diff         = vertex - other_vertex;\n          ret                     = std::max(ret, diff.two_norm());\n        }\n      }\n      return ret;\n    } // ... compute_diameter_of_(...)\n\n    RangeFieldType value_;\n  }; // class Localfunction\n\npublic:\n  typedef typename BaseType::EntityType EntityType;\n  typedef typename BaseType::LocalfunctionType LocalfunctionType;\n  typedef typename BaseType::RangeFieldType RangeFieldType;\n\n  static std::string static_id() { return BaseType::static_id() + \".ESV2007.cutoff\"; }\n\n  Cutoff(const DiffusionType& diffusion, const RangeFieldType poincare_constant = 1.0 / (M_PIl * M_PIl),\n         const std::string nm = static_id())\n    : diffusion_(diffusion), poincare_constant_(poincare_constant), name_(nm)\n  {\n  }\n\n  Cutoff(const ThisType& other) = default;\n\n  ThisType& operator=(const ThisType& other) = delete;\n\n  virtual std::string name() const override final { return name_; }\n\n  virtual std::unique_ptr<LocalfunctionType> local_function(const EntityType& entity) const override final\n  {\n    return std::unique_ptr<Localfunction>(new Localfunction(entity, diffusion_, poincare_constant_));\n  }\n\nprivate:\n  const DiffusionType& diffusion_;\n  const RangeFieldType poincare_constant_;\n  std::string name_;\n}; // class Cutoff\n\ntemplate <class DiffusionFactorType, class DiffusionTensorType>\nclass Cutoff\n    : public LocalizableFunctionInterface<typename DiffusionFactorType::EntityType,\n                                          typename DiffusionFactorType::DomainFieldType, DiffusionFactorType::dimDomain,\n                                          typename DiffusionFactorType::RangeFieldType, 1, 1>\n{\n  static_assert(std::is_base_of<Tags::LocalizableFunction, DiffusionFactorType>::value,\n                \"DiffusionFactorType has to be tagged as a LocalizableFunction!\");\n  static_assert(std::is_base_of<Tags::LocalizableFunction, DiffusionTensorType>::value,\n                \"DiffusionTensorType has to be tagged as a LocalizableFunction!\");\n  typedef typename DiffusionFactorType::EntityType E_;\n  typedef typename DiffusionFactorType::DomainFieldType D_;\n  static const size_t d_ = DiffusionFactorType::dimDomain;\n  typedef typename DiffusionFactorType::RangeFieldType R_;\n  typedef LocalizableFunctionInterface<E_, D_, d_, R_, 1> BaseType;\n  typedef Cutoff<DiffusionFactorType, DiffusionTensorType> ThisType;\n\n  static_assert(DiffusionFactorType::dimRange == 1, \"The diffusion factor has to be scalar!\");\n  static_assert(DiffusionFactorType::dimRangeCols == 1, \"The diffusion factor has to be scalar!\");\n\n  static_assert(std::is_same<typename DiffusionTensorType::EntityType, E_>::value, \"Types do not match!\");\n  static_assert(std::is_same<typename DiffusionTensorType::DomainFieldType, D_>::value, \"Types do not match!\");\n  static_assert(DiffusionTensorType::dimDomain == d_, \"Dimensions do not match!\");\n  static_assert(std::is_same<typename DiffusionTensorType::RangeFieldType, R_>::value, \"Types do not match!\");\n\n  static_assert(DiffusionTensorType::dimRange == d_, \"The diffusion tensor has to be a matrix!\");\n  static_assert(DiffusionTensorType::dimRangeCols == d_, \"The diffusion tensor has to be a matrix!\");\n\n  class Localfunction : public LocalfunctionInterface<E_, D_, d_, R_, 1, 1>\n  {\n    typedef LocalfunctionInterface<E_, D_, d_, R_, 1, 1> BaseType;\n\n  public:\n    typedef typename BaseType::EntityType EntityType;\n\n    typedef typename BaseType::DomainFieldType DomainFieldType;\n    static const size_t dimDomain = BaseType::dimDomain;\n    typedef typename BaseType::DomainType DomainType;\n\n    typedef typename BaseType::RangeFieldType RangeFieldType;\n    static const size_t dimRange     = BaseType::dimRange;\n    static const size_t dimRangeCols = BaseType::dimRangeCols;\n    typedef typename BaseType::RangeType RangeType;\n\n    typedef typename BaseType::JacobianRangeType JacobianRangeType;\n\n  private:\n    template <class DF, size_t r, size_t rR>\n    struct ComputeDiffusionFactor\n    {\n      static_assert(AlwaysFalse<DF>::value, \"Not implemented for these dimensions!\");\n    };\n\n    template <class DF>\n    struct ComputeDiffusionFactor<DF, 1, 1>\n    {\n      /**\n       * We try to find the minimum of a polynomial of given order by evaluating it at the points of a quadrature that\n       * would integrate this polynomial exactly.\n       * \\todo These are just some heuristics and should be replaced by something proper.\n       */\n      static RangeFieldType min_of(const DF& diffusion_factor, const EntityType& ent)\n      {\n        typename DF::RangeType tmp_value(0);\n        RangeFieldType minimum            = std::numeric_limits<RangeFieldType>::max();\n        const auto local_diffusion_factor = diffusion_factor.local_function(ent);\n        const size_t ord = local_diffusion_factor->order();\n        const auto& quadrature =\n            QuadratureRules<DomainFieldType, dimDomain>::rule(ent.type(), boost::numeric_cast<int>(ord));\n        const auto quad_point_it_end = quadrature.end();\n        for (auto quad_point_it = quadrature.begin(); quad_point_it != quad_point_it_end; ++quad_point_it) {\n          local_diffusion_factor->evaluate(quad_point_it->position(), tmp_value);\n          minimum = std::min(minimum, tmp_value[0]);\n        }\n        return minimum;\n      } // ... min_of(...)\n    };  // class ComputeDiffusionFactor< ..., 1, 1 >\n\n    template <class DT, size_t r, size_t rR>\n    struct ComputeDiffusionTensor\n    {\n      static_assert(AlwaysFalse<DT>::value, \"Not implemented for these dimensions!\");\n    };\n\n    template <class DT, size_t d>\n    struct ComputeDiffusionTensor<DT, d, d>\n    {\n      static RangeFieldType min_eigenvalue_of(const DT& diffusion_tensor, const EntityType& ent)\n      {\n#if !HAVE_EIGEN\n        static_assert(AlwaysFalse<DT>::value, \"You are missing eigen!\");\n#else\n        const auto local_diffusion_tensor = diffusion_tensor.local_function(ent);\n        assert(local_diffusion_tensor->order() == 0);\n        const auto& reference_element = ReferenceElements<DomainFieldType, dimDomain>::general(ent.type());\n        const Stuff::LA::EigenDenseMatrix<RangeFieldType> tensor =\n            local_diffusion_tensor->evaluate(reference_element.position(0, 0));\n        ::Eigen::EigenSolver<typename Stuff::LA::EigenDenseMatrix<RangeFieldType>::BackendType> eigen_solver(\n            tensor.backend());\n        assert(eigen_solver.info() == ::Eigen::Success);\n        const auto eigenvalues = eigen_solver.eigenvalues(); // <- this should be an Eigen vector of std::complex\n        RangeFieldType min_ev = std::numeric_limits<RangeFieldType>::max();\n        for (size_t ii = 0; ii < boost::numeric_cast<size_t>(eigenvalues.size()); ++ii) {\n          // assert this is real\n          assert(std::abs(eigenvalues[ii].imag()) < 1e-15);\n          // assert that this eigenvalue is positive\n          const RangeFieldType eigenvalue = eigenvalues[ii].real();\n          assert(eigenvalue > 1e-15);\n          min_ev = std::min(min_ev, eigenvalue);\n        }\n        return min_ev;\n#endif  // HAVE_EIGEN\n      } // ... min_eigenvalue_of_(...)\n    };  // class Compute< ..., d, d >\n\n  public:\n    Localfunction(const EntityType& ent, const DiffusionFactorType& diffusion_factor,\n                  const DiffusionTensorType& diffusion_tensor, const RangeFieldType poincare_constant)\n      : BaseType(ent), value_(0)\n    {\n      const RangeFieldType min_diffusion_factor =\n          ComputeDiffusionFactor<DiffusionFactorType,\n                                 DiffusionFactorType::dimRange,\n                                 DiffusionFactorType::dimRangeCols>::min_of(diffusion_factor, ent);\n      const RangeFieldType min_eigen_value_diffusion_tensor =\n          ComputeDiffusionTensor<DiffusionTensorType,\n                                 DiffusionTensorType::dimRange,\n                                 DiffusionTensorType::dimRangeCols>::min_eigenvalue_of(diffusion_tensor, ent);\n      assert(min_diffusion_factor > RangeFieldType(0));\n      assert(min_eigen_value_diffusion_tensor > RangeFieldType(0));\n      const DomainFieldType hh = compute_diameter_of_(ent);\n      value_                   = (poincare_constant * hh * hh) / (min_diffusion_factor * min_eigen_value_diffusion_tensor);\n    } // Localfunction(...)\n\n    Localfunction(const Localfunction& /*other*/) = delete;\n\n    Localfunction& operator=(const Localfunction& /*other*/) = delete;\n\n    virtual size_t order() const override final { return 0; }\n\n    virtual void evaluate(const DomainType& UNUSED_UNLESS_DEBUG(xx), RangeType& ret) const override final\n    {\n      assert(this->is_a_valid_point(xx));\n      ret[0] = value_;\n    }\n\n    virtual void jacobian(const DomainType& UNUSED_UNLESS_DEBUG(xx), JacobianRangeType& ret) const override final\n    {\n      assert(this->is_a_valid_point(xx));\n      ret *= RangeFieldType(0);\n    }\n\n  private:\n    static DomainFieldType compute_diameter_of_(const EntityType& ent)\n    {\n      DomainFieldType ret(0);\n      for (auto cc : DSC::valueRange(ent.template count<dimDomain>())) {\n        const auto vertex = ent.template subEntity<dimDomain>(cc)->geometry().center();\n        for (auto dd : DSC::valueRange(cc + 1, ent.template count<dimDomain>())) {\n          const auto other_vertex = ent.template subEntity<dimDomain>(dd)->geometry().center();\n          const auto diff         = vertex - other_vertex;\n          ret                     = std::max(ret, diff.two_norm());\n        }\n      }\n      return ret;\n    } // ... compute_diameter_of_(...)\n\n    RangeFieldType value_;\n  }; // class Localfunction\n\npublic:\n  typedef typename BaseType::EntityType EntityType;\n  typedef typename BaseType::LocalfunctionType LocalfunctionType;\n\n  typedef typename BaseType::DomainFieldType DomainFieldType;\n  static const size_t dimDomain = BaseType::dimDomain;\n  typedef typename BaseType::DomainType DomainType;\n\n  typedef typename BaseType::RangeFieldType RangeFieldType;\n  static const size_t dimRange     = BaseType::dimRange;\n  static const size_t dimRangeCols = BaseType::dimRangeCols;\n  typedef typename BaseType::RangeType RangeType;\n\n  static std::string static_id() { return BaseType::static_id() + \".ESV2007.cutoff\"; }\n\n  Cutoff(const DiffusionFactorType& diffusion_factor, const DiffusionTensorType& diffusion_tensor,\n         const RangeFieldType poincare_constant = 1.0 / (M_PIl * M_PIl), const std::string nm = static_id())\n    : diffusion_factor_(diffusion_factor)\n    , diffusion_tensor_(diffusion_tensor)\n    , poincare_constant_(poincare_constant)\n    , name_(nm)\n  {\n  }\n\n  Cutoff(const ThisType& other) = default;\n\n  ThisType& operator=(const ThisType& other) = delete;\n\n  virtual std::string name() const override final { return name_; }\n\n  virtual std::unique_ptr<LocalfunctionType> local_function(const EntityType& entity) const override final\n  {\n    return std::unique_ptr<Localfunction>(\n        new Localfunction(entity, diffusion_factor_, diffusion_tensor_, poincare_constant_));\n  }\n\nprivate:\n  const DiffusionFactorType& diffusion_factor_;\n  const DiffusionTensorType& diffusion_tensor_;\n  const RangeFieldType poincare_constant_;\n  std::string name_;\n}; // class Cutoff\n\n} // namespace ESV2007\n} // namespace Functions\n} // namespace Stuff\n} // namespace Dune\n\n#endif // DUNE_STUFF_FUNCTIONS_ESV2007_HH\n", "meta": {"hexsha": "e4a5fd002213ae233ae780b1a62b3128270c16d2", "size": 22834, "ext": "hh", "lang": "C++", "max_stars_repo_path": "dune/stuff/functions/ESV2007.hh", "max_stars_repo_name": "ftalbrecht/dune-stuff-simplified", "max_stars_repo_head_hexsha": "fc1f80dedaa78fae6e6d67e8f5424a6b3ec86b5d", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dune/stuff/functions/ESV2007.hh", "max_issues_repo_name": "ftalbrecht/dune-stuff-simplified", "max_issues_repo_head_hexsha": "fc1f80dedaa78fae6e6d67e8f5424a6b3ec86b5d", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dune/stuff/functions/ESV2007.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": 40.6298932384, "max_line_length": 123, "alphanum_fraction": 0.6837172637, "num_tokens": 5513, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.4735784345133528}}
{"text": "#include <boost/python/class.hpp>\n#include <boost/python/def.hpp>\n\n#include <scitbx/matrix/eigensystem.h>\n\nnamespace scitbx { namespace matrix { namespace boost_python {\n\n  struct eigensystem_real_symmetric_wrappers\n  {\n    typedef eigensystem::real_symmetric<> w_t;\n\n    static void\n    wrap()\n    {\n      using namespace boost::python;\n      class_<w_t>(\"eigensystem_real_symmetric\", no_init)\n        .def(init<\n          af::const_ref<double, af::c_grid<2> > const&, double, double>((\n            arg(\"m\"),\n            arg(\"relative_epsilon\")=1.e-10,\n            arg(\"absolute_epsilon\")=0)))\n        .def(init<\n          scitbx::sym_mat3<double> const&, double, double>((\n            arg(\"m\"),\n            arg(\"relative_epsilon\")=1.e-10,\n            arg(\"absolute_epsilon\")=0)))\n        .def(\"min_abs_pivot\", &w_t::min_abs_pivot)\n        .def(\"vectors\", &w_t::vectors)\n        .def(\"values\", &w_t::values)\n        .def(\"generalized_inverse_as_packed_u\",\n          &w_t::generalized_inverse_as_packed_u)\n      ;\n    }\n  };\n\n  // simlar to time_dsyev_*()\n  vec3<double>\n  time_eigensystem_real_symmetric(\n    sym_mat3<double> const& m, std::size_t n_repetitions)\n  {\n    SCITBX_ASSERT(n_repetitions % 2 == 0);\n    vec3<double> result(0,0,0);\n    for(std::size_t i=0;i<n_repetitions/2;i++) {\n      result += vec3<double>(\n        eigensystem::real_symmetric<>(m).values().begin());\n      result -= vec3<double>(\n        eigensystem::real_symmetric<>(m).values().begin());\n    }\n    return result / static_cast<double>(n_repetitions);\n  }\n\n  void wrap_eigensystem() {\n    using namespace boost::python;\n    eigensystem_real_symmetric_wrappers::wrap();\n    def(\"time_eigensystem_real_symmetric\", time_eigensystem_real_symmetric);\n  }\n\n}}}\n", "meta": {"hexsha": "67e0a09f45ed911172ec21cdaf3be2a836a69d24", "size": 1737, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "scitbx/linalg/boost_python/eigensystem.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/linalg/boost_python/eigensystem.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/linalg/boost_python/eigensystem.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": 29.4406779661, "max_line_length": 76, "alphanum_fraction": 0.6280944157, "num_tokens": 484, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.47356631789161235}}
{"text": "#pragma once\n#include <QObject>\n#include <opencv2/opencv.hpp>\n#include <NTL/mat_ZZ.h>\n\nstruct Lattice {\n  NTL::vec_ZZ origin;\n  NTL::mat_ZZ bases;\n  double total_error;\n};\n\ninline bool operator==(const Lattice& lhs, const Lattice& rhs)\n{\n  return lhs.origin == rhs.origin &&\n         lhs.bases == rhs.bases &&\n         lhs.total_error == rhs.total_error;\n}\n\ninline bool operator!=(const Lattice& lhs, const Lattice& rhs)\n{\n  return !(lhs == rhs);\n}\n\nclass LatticeFitter : public QObject\n{\n  Q_OBJECT\n\npublic:\n  explicit LatticeFitter(QObject* parent = 0);\n\n  Lattice best_lattice;\n\nsignals:\n  void latticeFittingStarted();\n  void progressUpdated(int);\n  void foundBestLattice(const Lattice&);\n\npublic slots:\n  void findBestLattice(const std::vector<cv::Point2f>& points);\n\nprivate:\n  Lattice bestLatticeForOrigin\n  (const cv::Point2f& origin, const std::vector<cv::Point2f>& points) const;\n\n  void calculateErrorForLattice\n  (Lattice& lattice, const std::vector<NTL::vec_ZZ>& points) const;\n\n  NTL::vec_ZZ cvPoint2fToNTLVec(const cv::Point2f& point) const;\n  double sq(double value) const;\n};\n\ninline NTL::vec_ZZ LatticeFitter::cvPoint2fToNTLVec(const cv::Point2f& point) const\n{\n  NTL::vec_ZZ result;\n  result.append(NTL::to_ZZ(point.x));\n  result.append(NTL::to_ZZ(point.y));\n  return result;\n}\n\ninline double LatticeFitter::sq(double value) const\n{\n  return value * value;\n}\n", "meta": {"hexsha": "66171fa8e091b35229a95f7c1ce5cb4ea9f8b909", "size": 1378, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/LatticeFitter.hpp", "max_stars_repo_name": "ZoltanDalmadi/lattice-fitting", "max_stars_repo_head_hexsha": "e72f2e7a702a2797ada9401e9d5c017e7fbb4659", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/LatticeFitter.hpp", "max_issues_repo_name": "ZoltanDalmadi/lattice-fitting", "max_issues_repo_head_hexsha": "e72f2e7a702a2797ada9401e9d5c017e7fbb4659", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/LatticeFitter.hpp", "max_forks_repo_name": "ZoltanDalmadi/lattice-fitting", "max_forks_repo_head_hexsha": "e72f2e7a702a2797ada9401e9d5c017e7fbb4659", "max_forks_repo_licenses": ["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.53125, "max_line_length": 83, "alphanum_fraction": 0.7169811321, "num_tokens": 398, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.47356631152883316}}
{"text": "#include \"LinearMuscleConstraint.h\"\n#include <Eigen/SVD>\n#include <Eigen/Sparse>\n#include <Eigen/Geometry>\n#include <Eigen/Eigenvalues>\n#include <iostream>\nusing namespace FEM;\n\nLinearMuscleConstraint::\nLinearMuscleConstraint(const double& stiffness,\n\t\tconst Eigen::Vector3d& fiber_direction,\n\t\tconst double& activation_level, \n\t\tint i0,int i1,int i2,int i3,\n\t\tdouble vol,const Eigen::Matrix3d& invDm,\n\t\t// const Eigen::Vector4d& barycentric1,const Eigen::Vector4d& barycentric2,\n\t\tdouble weight)\n\t:Constraint(stiffness),\n\tmi0(i0),mi1(i1),mi2(i2),mi3(i3),\n\tmStiffness(stiffness),mFiberDirection(fiber_direction),\n\tmVol(vol),mInvDm(invDm),mDs(Eigen::Matrix3d::Zero()),\n\tmActivationLevel(activation_level),mWeight(weight)\n{\n\tmF.setZero();\n\t// mBarycentric.clear();\n\t// mBarycentric.push_back(barycentric1);\n\t// mBarycentric.push_back(barycentric2);\n\n\tmStiffness *= mWeight;\n}\nvoid\nLinearMuscleConstraint:: \nComputeF\n(const Eigen::VectorXd& x)\n{\n\tEigen::Vector3d x0(x.block<3,1>(mi0*3,0));\n\n\tEigen::Matrix3d Ds;\n\n\tDs.block<3,1>(0,0) = x.block<3,1>(mi1*3,0)-x0;\n\tDs.block<3,1>(0,1) = x.block<3,1>(mi2*3,0)-x0;\n\tDs.block<3,1>(0,2) = x.block<3,1>(mi3*3,0)-x0;\n\n\tmDs = Ds;\n\tmF = mDs * mInvDm;\n}\nvoid\nLinearMuscleConstraint::\nComputeP\n(Eigen::Matrix3d& P)\n{\n\tP = mStiffness*(mF*mFiberDirection*mFiberDirection.transpose() - mp0*mFiberDirection.transpose());\n}\t\nvoid\t\nLinearMuscleConstraint::\nComputedPdF\n(Tensor3333& dPdF)\n{\n\tTensor3333 dFdF;\n\tdFdF.SetIdentity();\n\n\tfor(int i=0; i<3;i++)\n\t\tfor(int j=0;j<3;j++)\n\t\t\tdPdF(i,j) = mStiffness*dFdF(i,j)*mFiberDirection*mFiberDirection.transpose();\n}\nvoid\nLinearMuscleConstraint::\t\nEvaluateJMatrix(int index, std::vector<Eigen::Triplet<double>>& J_triplets)\n{\n\tEigen::MatrixXd Ai(3,12);\n\n\tEigen::Vector3d v = mInvDm*mFiberDirection;\n\n\tdouble a,b,c;\n\ta = v[0];\n\tb = v[1];\n\tc = v[2];\n\n\tAi<<\n\t\t-(a+b+c),0,0,a,0,0,b,0,0,c,0,0,\n\t\t0,-(a+b+c),0,0,a,0,0,b,0,0,c,0,\n\t\t0,0,-(a+b+c),0,0,a,0,0,b,0,0,c;\n\n\tEigen::MatrixXd MuAiT = mVol*mStiffness*Ai.transpose();\n\n\tJ_triplets.push_back(Eigen::Triplet<double>(3*mi0+0,3*index+0,MuAiT(3*0+0,3*0+0)));\n\tJ_triplets.push_back(Eigen::Triplet<double>(3*mi0+0,3*index+1,MuAiT(3*0+0,3*0+1)));\n\tJ_triplets.push_back(Eigen::Triplet<double>(3*mi0+0,3*index+2,MuAiT(3*0+0,3*0+2)));\n\tJ_triplets.push_back(Eigen::Triplet<double>(3*mi0+1,3*index+0,MuAiT(3*0+1,3*0+0)));\n\tJ_triplets.push_back(Eigen::Triplet<double>(3*mi0+1,3*index+1,MuAiT(3*0+1,3*0+1)));\n\tJ_triplets.push_back(Eigen::Triplet<double>(3*mi0+1,3*index+2,MuAiT(3*0+1,3*0+2)));\n\tJ_triplets.push_back(Eigen::Triplet<double>(3*mi0+2,3*index+0,MuAiT(3*0+2,3*0+0)));\n\tJ_triplets.push_back(Eigen::Triplet<double>(3*mi0+2,3*index+1,MuAiT(3*0+2,3*0+1)));\n\tJ_triplets.push_back(Eigen::Triplet<double>(3*mi0+2,3*index+2,MuAiT(3*0+2,3*0+2)));\n\n\tJ_triplets.push_back(Eigen::Triplet<double>(3*mi1+0,3*index+0,MuAiT(3*1+0,3*0+0)));\n\tJ_triplets.push_back(Eigen::Triplet<double>(3*mi1+0,3*index+1,MuAiT(3*1+0,3*0+1)));\n\tJ_triplets.push_back(Eigen::Triplet<double>(3*mi1+0,3*index+2,MuAiT(3*1+0,3*0+2)));\n\tJ_triplets.push_back(Eigen::Triplet<double>(3*mi1+1,3*index+0,MuAiT(3*1+1,3*0+0)));\n\tJ_triplets.push_back(Eigen::Triplet<double>(3*mi1+1,3*index+1,MuAiT(3*1+1,3*0+1)));\n\tJ_triplets.push_back(Eigen::Triplet<double>(3*mi1+1,3*index+2,MuAiT(3*1+1,3*0+2)));\n\tJ_triplets.push_back(Eigen::Triplet<double>(3*mi1+2,3*index+0,MuAiT(3*1+2,3*0+0)));\n\tJ_triplets.push_back(Eigen::Triplet<double>(3*mi1+2,3*index+1,MuAiT(3*1+2,3*0+1)));\n\tJ_triplets.push_back(Eigen::Triplet<double>(3*mi1+2,3*index+2,MuAiT(3*1+2,3*0+2)));\n\n\tJ_triplets.push_back(Eigen::Triplet<double>(3*mi2+0,3*index+0,MuAiT(3*2+0,3*0+0)));\n\tJ_triplets.push_back(Eigen::Triplet<double>(3*mi2+0,3*index+1,MuAiT(3*2+0,3*0+1)));\n\tJ_triplets.push_back(Eigen::Triplet<double>(3*mi2+0,3*index+2,MuAiT(3*2+0,3*0+2)));\n\tJ_triplets.push_back(Eigen::Triplet<double>(3*mi2+1,3*index+0,MuAiT(3*2+1,3*0+0)));\n\tJ_triplets.push_back(Eigen::Triplet<double>(3*mi2+1,3*index+1,MuAiT(3*2+1,3*0+1)));\n\tJ_triplets.push_back(Eigen::Triplet<double>(3*mi2+1,3*index+2,MuAiT(3*2+1,3*0+2)));\n\tJ_triplets.push_back(Eigen::Triplet<double>(3*mi2+2,3*index+0,MuAiT(3*2+2,3*0+0)));\n\tJ_triplets.push_back(Eigen::Triplet<double>(3*mi2+2,3*index+1,MuAiT(3*2+2,3*0+1)));\n\tJ_triplets.push_back(Eigen::Triplet<double>(3*mi2+2,3*index+2,MuAiT(3*2+2,3*0+2)));\n\n\tJ_triplets.push_back(Eigen::Triplet<double>(3*mi3+0,3*index+0,MuAiT(3*3+0,3*0+0)));\n\tJ_triplets.push_back(Eigen::Triplet<double>(3*mi3+0,3*index+1,MuAiT(3*3+0,3*0+1)));\n\tJ_triplets.push_back(Eigen::Triplet<double>(3*mi3+0,3*index+2,MuAiT(3*3+0,3*0+2)));\n\tJ_triplets.push_back(Eigen::Triplet<double>(3*mi3+1,3*index+0,MuAiT(3*3+1,3*0+0)));\n\tJ_triplets.push_back(Eigen::Triplet<double>(3*mi3+1,3*index+1,MuAiT(3*3+1,3*0+1)));\n\tJ_triplets.push_back(Eigen::Triplet<double>(3*mi3+1,3*index+2,MuAiT(3*3+1,3*0+2)));\n\tJ_triplets.push_back(Eigen::Triplet<double>(3*mi3+2,3*index+0,MuAiT(3*3+2,3*0+0)));\n\tJ_triplets.push_back(Eigen::Triplet<double>(3*mi3+2,3*index+1,MuAiT(3*3+2,3*0+1)));\n\tJ_triplets.push_back(Eigen::Triplet<double>(3*mi3+2,3*index+2,MuAiT(3*3+2,3*0+2)));\n}\nvoid\nLinearMuscleConstraint::\t\nEvaluateLMatrix(std::vector<Eigen::Triplet<double>>& L_triplets)\n{\n\tEigen::MatrixXd Ai(3,12);\n\tEigen::Vector3d v = mInvDm*mFiberDirection;\n\n\tdouble a,b,c;\n\ta = v[0];\n\tb = v[1];\n\tc = v[2];\n\n\tAi<<\n\t\t-(a+b+c),0,0,a,0,0,b,0,0,c,0,0,\n\t\t0,-(a+b+c),0,0,a,0,0,b,0,0,c,0,\n\t\t0,0,-(a+b+c),0,0,a,0,0,b,0,0,c;\n\n\tauto MuAiTAi = mVol*mStiffness*((Ai.transpose())*Ai);\n\n\tint idx[4] = {mi0,mi1,mi2,mi3};\n\n\tfor(int i =0;i<4;i++)\n\t{\n\t\tfor(int j=0;j<4;j++)\n\t\t{\n\t\t\tL_triplets.push_back(Eigen::Triplet<double>(3*idx[i]+0,3*idx[j]+0,MuAiTAi(3*i+0,3*j+0)));\n\t\t\tL_triplets.push_back(Eigen::Triplet<double>(3*idx[i]+0,3*idx[j]+1,MuAiTAi(3*i+0,3*j+1)));\n\t\t\tL_triplets.push_back(Eigen::Triplet<double>(3*idx[i]+0,3*idx[j]+2,MuAiTAi(3*i+0,3*j+2)));\n\t\t\tL_triplets.push_back(Eigen::Triplet<double>(3*idx[i]+1,3*idx[j]+0,MuAiTAi(3*i+1,3*j+0)));\n\t\t\tL_triplets.push_back(Eigen::Triplet<double>(3*idx[i]+1,3*idx[j]+1,MuAiTAi(3*i+1,3*j+1)));\n\t\t\tL_triplets.push_back(Eigen::Triplet<double>(3*idx[i]+1,3*idx[j]+2,MuAiTAi(3*i+1,3*j+2)));\n\t\t\tL_triplets.push_back(Eigen::Triplet<double>(3*idx[i]+2,3*idx[j]+0,MuAiTAi(3*i+2,3*j+0)));\n\t\t\tL_triplets.push_back(Eigen::Triplet<double>(3*idx[i]+2,3*idx[j]+1,MuAiTAi(3*i+2,3*j+1)));\n\t\t\tL_triplets.push_back(Eigen::Triplet<double>(3*idx[i]+2,3*idx[j]+2,MuAiTAi(3*i+2,3*j+2)));\n\t\t}\n\t}\n}\nvoid\nLinearMuscleConstraint::\t\nEvaluateDVector(const Eigen::VectorXd& x)\n{\n\tComputeF(x);\n\tComputep0();\n}\nvoid\nLinearMuscleConstraint::\nGetDVector(int& index,Eigen::VectorXd& d)\n{\n\td.block<3,1>(3*index,0) = mp0;\n\tindex++;\n}\nvoid\nLinearMuscleConstraint::\nComputep0()\n{\n\tmp0 = (1.0-mActivationLevel)*mF*mFiberDirection;\n}\t\nint\nLinearMuscleConstraint::\nGetDof()\n{\n\treturn 1;\n}\nConstraintType\nLinearMuscleConstraint::\nGetType()\n{\n\treturn ConstraintType::LINEAR_MUSCLE;\n}\nvoid \nLinearMuscleConstraint::\nSetActivationLevel(const double& a) \n{\n\tmActivationLevel = a;\n}\nconst double& \nLinearMuscleConstraint::\nGetActivationLevel() \n{\n\treturn mActivationLevel;\n}\nconst Eigen::Vector3d&\nLinearMuscleConstraint::\nGetFiberDirection()\n{\n\treturn mFiberDirection;\n}\nvoid \nLinearMuscleConstraint::\nSetActivationIndex(const int& i)\n{\n\tmActivationIndex = i;\n}", "meta": {"hexsha": "5c1f280d10736fb0db98461a822cc836e583e84c", "size": 7208, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sim/fem/Constraint/LinearMuscleConstraint.cpp", "max_stars_repo_name": "liusida/SoftCon", "max_stars_repo_head_hexsha": "39adcb1e2364dd7583b01966af7038d77977e083", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 140.0, "max_stars_repo_stars_event_min_datetime": "2019-09-05T03:24:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-18T13:44:48.000Z", "max_issues_repo_path": "sim/fem/Constraint/LinearMuscleConstraint.cpp", "max_issues_repo_name": "liusida/SoftCon", "max_issues_repo_head_hexsha": "39adcb1e2364dd7583b01966af7038d77977e083", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-03-15T14:23:02.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-15T14:23:02.000Z", "max_forks_repo_path": "sim/fem/Constraint/LinearMuscleConstraint.cpp", "max_forks_repo_name": "liusida/SoftCon", "max_forks_repo_head_hexsha": "39adcb1e2364dd7583b01966af7038d77977e083", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 23.0, "max_forks_repo_forks_event_min_datetime": "2019-09-08T02:51:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T12:49:05.000Z", "avg_line_length": 33.2165898618, "max_line_length": 99, "alphanum_fraction": 0.6964483907, "num_tokens": 3061, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118221, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4734845963538519}}
{"text": "//#include <boost/multiprecision/cpp_int.hpp>\n\n//using namespace boost::multiprecision;\n\n//int main() {\n//boost::uint64_t i = (std::numeric_limits<boost::uint64_t>::max)();\n//boost::uint64_t j = 1;\n\n//uint128_t ui128, x;\n//uint256_t ui256;\n////\n//// Start by performing arithmetic on 64-bit integers to yield 128-bit results:\n////\n//x = add(ui128, i, j);\n//std::cout << std::hex << std::showbase << i << std::endl;\n//std::cout << std::hex << std::showbase << add(ui128, i, j) << std::endl;\n//std::cout << std::hex << std::showbase << multiply(ui128, i, i) << std::endl;\n//std::cout << \"\\n\" << x << std::endl;\n////\n//// The try squaring a 128-bit integer to yield a 256-bit result:\n////\n//ui128 = (std::numeric_limits<uint128_t>::max)();\n//std::cout << std::hex << std::showbase << multiply(ui256, ui128, ui128) << std::endl;\n//return 0;\n//}\n\n\n//// independent_bits_engine constructor\n//#include <iostream>\n//#include <chrono>\n//#include <cstdint>\n//#include <random>\n\n//int main ()\n//{\n  //typedef std::independent_bits_engine<std::mt19937,64,std::uint_fast64_t> generator_type;\n\n  //generator_type g1;\n\n  //generator_type g2(g1.base());\n\n  //std::mt19937 temp;\n  //generator_type g3(std::move(temp));\n\n  //unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();\n  //generator_type g4(seed);\n\n  //std::seed_seq sseq ({2,16,77});\n  //generator_type g5(sseq);\n\n  //std::cout << \"g1(): \" << g1() << std::endl;\n  //std::cout << \"g2(): \" << g2() << std::endl;\n  //std::cout << \"g3(): \" << g3() << std::endl;\n  //std::cout << \"g4(): \" << g4() << std::endl;\n  //std::cout << \"g5(): \" << g5() << std::endl;\n\n  //return 0;\n//}\n\n#include <stdlib.h>\n#include <iostream>\n#include <fstream>\n#include <cmath>\n#include <ctime>\n#include <chrono>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/random.hpp>\n#include <gmp.h>\n\nusing namespace boost::multiprecision;\nusing namespace boost::random;\nusing namespace std;\n\nuint256_t rand_gen(){\n\ttypedef independent_bits_engine<mt19937, 256, uint256_t> generator_type;\n    unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();\n    //srand(time(0));\n    generator_type gen(seed);\n    return gen();\n}\n\nint main()\n{\n\n   uint256_t x = rand_gen();\n   \n   //std::cout << x << std::endl;\n   \n   ofstream keyfile;\n   keyfile.open(\"privatekeys.csv\");\n   \n   for(int i = 0; i < 10; i++)\n        keyfile << rand_gen() << \"\\n\" ;\n   keyfile.close();\n   cout << sizeof(mpz_t);\n  //// Read the data file\n  //vector<uint256_t> row;\n  //vector<uint256_t> keys;\n  //uint256_t line;\n  ////string line, word, temp;\n  //ifstream fin(\"privatekeys.csv\");\n  ////int k = 0;\n  //while(!fin.eof())\n\t//{\n\t\t//row.clear();\n\t\t//fin >> line;\n\t\t////stringstream s(line);\n\t\t//cout << line << \"\\n\";\n\t\t//keys.push_back(line);\n     //}\n     \n\t//cout << \"\\n\" << \"The private keys are as follows\\n\";\n\t//for(int i=0; i < 10; i++)\n\t\t//cout << keys[i] << \"\\n\";\n   //\n   \n   \n   // Declare our random number generator type, the underlying generator\n   // is the Mersenne twister mt19937 engine, and we'll generate 256 bit\n   // random values, independent_bits_engine will make multiple calls\n   // to the underlying engine until we have the requested number of bits:\n   //\n   //\n   // Alternatively if we wish to generate random values in a fixed-precision\n   // type, then we must use an unsigned type in order to adhere to the\n   // conceptual requirements of the generator:\n   //\n   //typedef independent_bits_engine<mt19937, 512, uint512_t> generator512_type;\n   //generator512_type gen512;\n   //\n   // Generate some 1024-bit unsigned values:\n   //\n   //std::cout << std::hex << std::showbase;\n   //for(unsigned i = 0; i < 10; ++i)\n    //  std::cout << gen512() << std::endl;\n      return 0;\n}\n", "meta": {"hexsha": "ff7d8e4a271ec98d5a8cb459448ee3e2bf464ef0", "size": 3738, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/random.cpp", "max_stars_repo_name": "SwaroopReddyBasireddy/Proof-of-Assets", "max_stars_repo_head_hexsha": "011ee85ad4e7941c2bfbf53c1872fbaa40038cf5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/random.cpp", "max_issues_repo_name": "SwaroopReddyBasireddy/Proof-of-Assets", "max_issues_repo_head_hexsha": "011ee85ad4e7941c2bfbf53c1872fbaa40038cf5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/random.cpp", "max_forks_repo_name": "SwaroopReddyBasireddy/Proof-of-Assets", "max_forks_repo_head_hexsha": "011ee85ad4e7941c2bfbf53c1872fbaa40038cf5", "max_forks_repo_licenses": ["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.0869565217, "max_line_length": 92, "alphanum_fraction": 0.6187800963, "num_tokens": 1089, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289836, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.47347410329849804}}
{"text": "//\n// Copyright (c) 2018 Sergey Panov.\n// Copyright (c) 2018 Second Star Algonumerix LLC\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#include <complex>\n#include <iostream>\n\n#include <vector>\n#include <iterator>\n#include <numeric>\n#include <fstream>\n#include <cmath>\n\n#include <boost/lexical_cast.hpp>\n\n\n#include \"octio.hpp\"\n\nusing boost::lexical_cast;\nusing namespace ssan::octio;\n\ntemplate<typename T>\nvoid print_matrix(const std::vector<std::vector<T>> &matrix,\n        const std::string & name) {\n    if (!matrix.empty()) {\n        std::cout << name << \"[\"\n                  << matrix.size() << \",\"\n                  << matrix[0].size() << \"]: [\" << std::endl;\n        for (const auto & row : matrix) {\n            for (auto element : row) {\n                std::cout << \" \" << lexical_cast<std::string>(element);\n            }\n            std::cout << std::endl;\n        }\n        std::cout << \"]\" << std::endl;\n    }\n}\n\ntemplate<typename T>\nvoid print_vector(const std::vector<T> &vector, const std::string & name) {\n    if (!vector.empty()) {\n        std::cout << name << \"[\"\n                  << vector.size() << \"]: [\";\n        for (auto element : vector) {\n                std::cout << \" \" << lexical_cast<std::string>(element);\n        }\n        std::cout << \"]\" << std::endl;\n    }\n}\n\n\n\nint main() {\n    int int_var = -1;\n    float float_var(nanf(\"\"));\n    double double_var(nan(\"\"));\n    long double ldouble_var(nanl(\"\"));\n    std::complex<float> cfloat_var(nanf(\"\"), nanf(\"\"));\n    std::complex<double> cdouble_var(nan(\"\"), nan(\"\"));\n    std::complex<long double> cldouble_var(nanl(\"\"), nanl(\"\"));\n    std::vector<int8_t> int8_vect;\n    std::vector<int16_t> int16_vect;\n    std::vector<int32_t> int32_vect;\n    std::vector<int64_t> int64_vect;\n    std::vector<uint8_t> uint8_vect;\n    std::vector<uint16_t> uint16_vect;\n    std::vector<uint32_t> uint32_vect;\n    std::vector<uint64_t> uint64_vect;\n    std::vector<float> float_vect;\n    std::vector<double> double_vect;\n    std::vector<long double> ldouble_vect;\n    std::vector<int> int_covect;\n    std::vector<float> float_covect;\n    std::vector<double> double_covect;\n    std::vector<long double> ldouble_covect;\n    std::vector<std::complex<int>> cint_vect;\n    std::vector<std::complex<float>> cfloat_vect;\n    std::vector<std::complex<double>> cdouble_vect;\n    std::vector<std::complex<long double>> cldouble_vect;\n    std::vector<std::complex<float>> cfloat_covect;\n    std::vector<std::complex<double>> cdouble_covect;\n    std::vector<std::complex<long double>> cldouble_covect;\n    std::vector<std::vector<int>> int_mat;\n    std::vector<std::vector<float>> float_mat;\n    std::vector<std::vector<double>> double_mat;\n    std::vector<std::vector<long double>> ldouble_mat;\n    std::vector<std::vector<std::complex<float>>> cfloat_mat;\n    std::vector<std::vector<std::complex<double>>> cdouble_mat;\n    std::vector<std::vector<std::complex<long double>>> cldouble_mat;\n\n    const std::string file_name = \"test_octio.mat\";\n    const std::string file_name_out = \"test_octio_out.mat\";\n\n    std::ifstream file(file_name);\n    reader input(&file);\n    std::ofstream ofile(file_name_out);\n    writer output(&ofile, \"Test file\");\n\n    std::cout << input.title() << std::endl;\n    do {\n        bool consumed = false;\n        // std::cout << input.next_name() << std::endl;\n        // std::cout << input.next_type() << std::endl;\n        if (input.next_type() == SCALAR) {\n            if (input.next_name() == \"int_var\") {\n                consumed = input.read(int_var);\n                output.write(int_var, \"int_var\");\n            } else if (input.next_name() == \"float_var\") {\n                consumed = input.read(float_var);\n                output.write(float_var, \"float_var\");\n            } else if (input.next_name() == \"double_var\") {\n                consumed = input.read(double_var);\n                output.write(double_var, \"double_var\");\n            } else if (input.next_name() == \"ldouble_var\") {\n                consumed = input.read(ldouble_var);\n                output.write(ldouble_var, \"ldouble_var\");\n            }\n        } else if (input.next_type() == COMPLEX_SCALAR) {\n            if (input.next_name() == \"cfloat_var\") {\n                consumed = input.read(cfloat_var);\n                output.write(cfloat_var, \"cfloat_var\");\n            } else if (input.next_name() == \"cdouble_var\") {\n                consumed = input.read(cdouble_var);\n                output.write(cdouble_var, \"cdouble_var\");\n            } else if (input.next_name() == \"cldouble_var\") {\n                consumed = input.read(cldouble_var);\n                output.write(cldouble_var, \"cldouble_var\");\n            }\n        } else if (input.next_type() == VECTOR\n                   || input.next_type() == COVECTOR) {\n            if (input.next_name() == \"int8_vect\") {\n                consumed = input.read(int8_vect);\n                output.write(int8_vect, \"int8_vect\");\n            } else if (input.next_name() == \"int16_vect\") {\n                consumed = input.read(int16_vect);\n                output.write(int16_vect, \"int16_vect\");\n            } else if (input.next_name() == \"int32_vect\") {\n                consumed = input.read(int32_vect);\n                output.write(int32_vect, \"int32_vect\");\n            } else if (input.next_name() == \"int64_vect\") {\n                consumed = input.read(int64_vect);\n                output.write(int64_vect, \"int64_vect\");\n            } else if (input.next_name() == \"uint8_vect\") {\n                consumed = input.read(uint8_vect);\n                output.write(uint8_vect, \"uint8_vect\");\n            } else if (input.next_name() == \"uint16_vect\") {\n                consumed = input.read(uint16_vect);\n                output.write(uint16_vect, \"uint16_vect\");\n            } else if (input.next_name() == \"uint32_vect\") {\n                consumed = input.read(int32_vect);\n                output.write(uint32_vect, \"uint32_vect\");\n            } else if (input.next_name() == \"uint64_vect\") {\n                consumed = input.read(uint64_vect);\n                output.write(uint64_vect, \"uint64_vect\");\n            } else if (input.next_name() == \"float_vect\") {\n                consumed = input.read(float_vect);\n                output.write(float_vect, \"float_vect\");\n            } else if (input.next_name() == \"double_vect\") {\n                consumed = input.read(double_vect);\n            } else if (input.next_name() == \"ldouble_vect\") {\n                consumed = input.read(ldouble_vect);\n            } else if (input.next_name() == \"int_covect\") {\n                consumed = input.read(int_covect);\n            } else if (input.next_name() == \"float_covect\") {\n                consumed = input.read(float_covect);\n                output.write_covec(float_covect, \"float_covect\");\n            } else if (input.next_name() == \"double_covect\") {\n                consumed = input.read(double_covect);\n            } else if (input.next_name() == \"ldouble_covect\") {\n                consumed = input.read(ldouble_covect);\n            }\n        } else if (input.next_type() == COMPLEX_VECTOR\n                   || input.next_type() == COMPLEX_COVECTOR) {\n            if (input.next_name() == \"cint_vect\") {\n                consumed = input.read(cint_vect);\n                output.write(cint_vect, \"cint_vect\");\n            } else if (input.next_name() == \"cfloat_vect\") {\n                consumed = input.read(cfloat_vect);\n                output.write(cfloat_vect, \"cfloat_vect\");\n            } else if (input.next_name() == \"cdouble_vect\") {\n                consumed = input.read(cdouble_vect);\n            } else if (input.next_name() == \"cldouble_vect\") {\n                consumed = input.read(cldouble_vect);\n            } else if (input.next_name() == \"cfloat_covect\") {\n                consumed = input.read(cfloat_covect);\n                output.write_covec(cfloat_covect, \"cfloat_covect\");\n            } else if (input.next_name() == \"cdouble_covect\") {\n                consumed = input.read(cdouble_covect);\n            } else if (input.next_name() == \"cldouble_covect\") {\n                consumed = input.read(cldouble_covect);\n            }\n        } else if (input.next_type() == MATRIX) {\n            if (input.next_name() == \"int_mat\") {\n                consumed = input.read(int_mat);\n            } else if (input.next_name() == \"float_mat\") {\n                consumed = input.read(float_mat);\n                output.write(float_mat, \"float_mat\");\n            } else if (input.next_name() == \"double_mat\") {\n                consumed = input.read(double_var);\n            } else if (input.next_name() == \"ldouble_mat\") {\n                consumed = input.read(ldouble_var);\n            }\n        } else if (input.next_type() == COMPLEX_MATRIX) {\n            if (input.next_name() == \"cfloat_mat\") {\n                consumed = input.read(cfloat_mat);\n                output.write(cfloat_mat, \"cfloat_mat\");\n            } else if (input.next_name() == \"cdouble_mat\") {\n                consumed = input.read(cdouble_mat);\n            } else if (input.next_name() == \"cldouble_mat\") {\n                consumed = input.read(cldouble_mat);\n            }\n        }\n\n\n        if (!consumed) {\n            input.skip_one();\n        }\n\n    } while (input.next_type() != INVALID);\n\n\n    std::cout << \"int_var: \" << int_var << std::endl;\n    std::cout << \"float_var: \" << lexical_cast<std::string>(float_var)\n              << std::endl;\n    std::cout << \"double_var: \" << lexical_cast<std::string>(double_var)\n              << std::endl;\n    std::cout << \"ldouble_var: \" << lexical_cast<std::string>(ldouble_var)\n              << std::endl;\n    std::cout << \"cfloat_var: (\"\n              << lexical_cast<std::string>(cfloat_var.real()) << \",\"\n              << lexical_cast<std::string>(cfloat_var.imag()) << \")\"\n              << std::endl;\n    std::cout << \"cdouble_var: (\"\n              << lexical_cast<std::string>(cdouble_var.real()) << \",\"\n              << lexical_cast<std::string>(cdouble_var.imag()) << \")\"\n              << std::endl;\n    std::cout << \"cldouble_var: (\"\n              << lexical_cast<std::string>(cldouble_var.real()) << \",\"\n              << lexical_cast<std::string>(cldouble_var.imag()) << \")\"\n              << std::endl;\n    print_vector(float_vect, \"float_vect\");\n    print_vector(float_covect, \"float_covect\");\n    print_vector(cint_vect, \"cint_vect\");\n    print_vector(cfloat_vect, \"cfloat_vect\");\n    print_vector(cfloat_covect, \"cfloat_covect\");\n    print_matrix(float_mat, \"float_mat\");\n    print_matrix(cfloat_mat, \"cfloat_mat\");\n\n    return 0;\n}", "meta": {"hexsha": "5012aac35cc4df999a51a73db2d93262e2d41ab9", "size": 10710, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "octio_test.cpp", "max_stars_repo_name": "sipanov/lightio", "max_stars_repo_head_hexsha": "22b7c3ccd26d63029fa8e64dfc6c80fcc5b67fec", "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": "octio_test.cpp", "max_issues_repo_name": "sipanov/lightio", "max_issues_repo_head_hexsha": "22b7c3ccd26d63029fa8e64dfc6c80fcc5b67fec", "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": "octio_test.cpp", "max_forks_repo_name": "sipanov/lightio", "max_forks_repo_head_hexsha": "22b7c3ccd26d63029fa8e64dfc6c80fcc5b67fec", "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.3320158103, "max_line_length": 79, "alphanum_fraction": 0.5569561158, "num_tokens": 2545, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289836, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.47347410329849804}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// Unit Test\n\n// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.\n// Copyright (c) 2017 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\n#include <geometry_test_common.hpp>\n\n#include <boost/core/ignore_unused.hpp>\n\n#include <boost/geometry/arithmetic/cross_product.hpp>\n\n#include <boost/geometry/algorithms/assign.hpp>\n\n#include <boost/geometry/geometries/point.hpp>\n#include <boost/geometry/geometries/adapted/c_array.hpp>\n#include <boost/geometry/geometries/adapted/boost_tuple.hpp>\n#include <test_common/test_point.hpp>\n\n\ntemplate <typename P>\nvoid test_2d()\n{\n    P p1;\n    bg::assign_values(p1, 20, 30);\n    P p2;\n    bg::assign_values(p2, 45, 70);\n    P c = bg::cross_product(p1, p2);\n\n    typedef typename bg::coordinate_type<P>::type scalar_type;\n    BOOST_CHECK_EQUAL(bg::get<0>(c), scalar_type(50));\n}\n\ntemplate <typename P>\nvoid test_3d()\n{\n    P p1;\n    bg::assign_values(p1, 20, 30, 10);\n    P p2;\n    bg::assign_values(p2, 45, 70, 20);\n    P c = bg::cross_product(p1, p2);\n\n    typedef typename bg::coordinate_type<P>::type scalar_type;\n    BOOST_CHECK_EQUAL(bg::get<0>(c), scalar_type(-100));\n    BOOST_CHECK_EQUAL(bg::get<1>(c), scalar_type(50));\n    BOOST_CHECK_EQUAL(bg::get<2>(c), scalar_type(50));\n}\n\n#ifdef TEST_FAIL_CROSS_PRODUCT\ntemplate <typename P>\nvoid test_4d()\n{\n    P p1;\n    bg::assign_values(p1, 20, 30, 10);\n    bg::set<3>(p1, 15);\n    P p2;\n    bg::assign_values(p2, 45, 70, 20);\n    bg::set<3>(p2, 35);\n    P c = bg::cross_product(p1, p2);\n    boost::ignore_unused(c);\n}\n#endif\n\nint test_main(int, char* [])\n{\n    test_2d<bg::model::point<int, 2, bg::cs::cartesian> >();\n    test_2d<bg::model::point<float, 2, bg::cs::cartesian> >();\n    test_2d<bg::model::point<double, 2, bg::cs::cartesian> >();\n\n    test_3d<bg::model::point<int, 3, bg::cs::cartesian> >();\n    test_3d<bg::model::point<float, 3, bg::cs::cartesian> >();\n    test_3d<bg::model::point<double, 3, bg::cs::cartesian> >();\n\n#ifdef TEST_FAIL_CROSS_PRODUCT\n    test_4d<bg::model::point<int, 4, bg::cs::cartesian> >();\n    test_4d<bg::model::point<float, 4, bg::cs::cartesian> >();\n    test_4d<bg::model::point<double, 4, bg::cs::cartesian> >();\n#endif\n\n    return 0;\n}\n\n", "meta": {"hexsha": "cb1ddf61771c4e8c7acb831fb0346b5dabc63ec4", "size": 2395, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/libs/geometry/test/arithmetic/cross_product.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/geometry/test/arithmetic/cross_product.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/geometry/test/arithmetic/cross_product.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": 27.2159090909, "max_line_length": 79, "alphanum_fraction": 0.6668058455, "num_tokens": 786, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4734740965437591}}
{"text": "#include <iostream>\n#include <vector>\n#include <random>\n#include <fstream>\n#include <omp.h>\n#include <boost/numeric/odeint.hpp>\n#include \"cahnhilliard_thermal_nodiffusion.h\"\n#include \"utils_ch.h\"\n\n  /*\n  Cahn-Hilliard:\n  \n  dc/dt = laplacian( u*c^3 - b*c ) - eps_2*biharm(c) - sigma*(c - m) + sigma_noise * N(0,1^2)\n  \n  expanding out RHS into individual differentials:\n  D*laplacian( u*c^3 - b*c) - D*eps_2*biharm(c)\n  assuming constant eps_2.\n\n  need a d^4 and a d^2 operator.\n  */\n\nCahnHilliard2DRHS_thermal_nodiffusion::CahnHilliard2DRHS_thermal_nodiffusion(CHparamsScalar& chp , SimInfo& info)\n  : noise_dist_(0.0,1.0) , info_(info)\n  {    \n    chpV_.eps_2    = std::vector<double>( info_.nx*info_.ny , chp.eps_2     );\n    chpV_.b        = std::vector<double>( info_.nx*info_.ny , chp.b         );\n    chpV_.u        = std::vector<double>( info_.nx*info_.ny , chp.u         );\n    chpV_.sigma    = std::vector<double>( info_.nx*info_.ny , chp.sigma     );\n    chpV_.m        = std::vector<double>( info_.nx*info_.ny , chp.m  );\n    chpV_.DT       = std::vector<double>( info_.nx*info_.ny , chp.DT  );\n    chpV_.f_T      = std::vector<double>( info_.nx*info_.ny , chp.f_T  );\n    chpV_.sigma_noise    = chp.sigma_noise;\n    chpV_.T_const        = std::vector<double>( info_.nx*info_.ny , chp.T_const  );\n\n    if ( info.bc.compare(\"dirichlet\") == 0) {\n      ch_rhs_ = &compute_ch_nonlocal_stationary_boundaries;\n      std::cout << \"Initialized Cahn-Hilliard equation: scalar parameters, dirichlet BCs, thermal coefficient dependence, no thermal diffusion\" << std::endl;\n    }\n    else if ( info.bc.compare(\"neumann\") == 0) {\n      ch_rhs_ = &compute_ch_nonlocal_neumannBC;\n      std::cout << \"Initialized Cahn-Hilliard equation: scalar parameters, neumann BCs, thermal coefficient dependence, no thermal diffusion\" << std::endl;\n    }\n    else {\n      ch_rhs_ = &compute_ch_nonlocal;\n      std::cout << \"Initialized Cahn-Hilliard equation: scalar parameters, periodic BCs, thermal coefficient dependence, no thermal diffusion\" << std::endl;\n    }\n    \n  }\n\nCahnHilliard2DRHS_thermal_nodiffusion::CahnHilliard2DRHS_thermal_nodiffusion(CHparamsVector& chp , SimInfo& info)\n  : noise_dist_(0.0,1.0) , chpV_(chp) , info_(info)\n  {\n\n    if ( info.bc.compare(\"dirichlet\") == 0) {\n      ch_rhs_ = &compute_ch_nonlocal_stationary_boundaries;\n      std::cout << \"Initialized Cahn-Hilliard equation: spatial-field parameters, dirichlet BCs, thermal coefficient dependence, no thermal diffusion\" << std::endl;\n    }\n    else if ( info.bc.compare(\"neumann\") == 0) {\n      ch_rhs_ = &compute_ch_nonlocal_neumannBC;\n      std::cout << \"Initialized Cahn-Hilliard equation: spatial-field parameters, neumann BCs, thermal coefficient dependence, no thermal diffusion\" << std::endl;\n    }\n    else {\n      ch_rhs_ = &compute_ch_nonlocal;\n      std::cout << \"Initialized Cahn-Hilliard equation: spatial-field parameters, periodic BCs, thermal coefficient dependence, no thermal diffusion\" << std::endl;\n    }\n    \n  }\n\nCahnHilliard2DRHS_thermal_nodiffusion::~CahnHilliard2DRHS_thermal_nodiffusion() { };\n\nvoid CahnHilliard2DRHS_thermal_nodiffusion::rhs(const std::vector<double> &c, std::vector<double> &dcdt, const double t)\n  {\n    dcdt.resize(info_.nx*info_.ny);\n    \n    // evaluate CH parameter dependencies on temperature\n    //chpV_ = compute_chparams_using_temperature( chpV_ , info_ , chpV_.T_const );\n    chpV_ = compute_eps2_and_sigma_from_polymer_params( chpV_ , info_ , chpV_.T_const );\n    \n    // evaluate deterministic nonlocal dynamics\n    compute_ch_nonlocal(c, dcdt, t, chpV_, info_);\n        \n  }\n\n\nvoid CahnHilliard2DRHS_thermal_nodiffusion::setInitialConditions(std::vector<double> &x)\n  {\n    x.resize(info_.nx * info_.ny);\n\n    std::default_random_engine generator;\n    std::uniform_real_distribution<double> distribution(-1.0,1.0);\n\n    for (int i = 0; i < info_.ny; ++i) {\n      for (int j = 0; j < info_.nx; ++j) {\n        x[info_.idx2d(i,j)]   = distribution(generator) * 0.005;\n      }\n    }\n\n    // Set BCs if needed\n    if ( info_.bc.compare(\"dirichlet\") == 0) {\n      x = apply_dirichlet_bc( x , info_ );\n    }\n    else if ( info_.bc.compare(\"neumann\") == 0 ) {\n      x = apply_neumann_bc( x , info_ );\n    }\n\n  }\n\n\nvoid CahnHilliard2DRHS_thermal_nodiffusion::write_state(const std::vector<double> &x , const int idx , const int nx , const int ny , std::string& outdir)\n{\n  if ( outdir.back() != '/' )\n    outdir += '/';\n  std::ofstream outC;\n  outC.open( outdir + \"C_\" + std::to_string(idx) + \".out\" );\n  outC.precision(16);\n  \n  for (int i = 0; i < ny; ++i){\n    for (int j = 0; j < nx; ++j){\n      outC << x[i * ny + j] << \" \";\n    }\n  }\n\n  outC.close();\n};\n", "meta": {"hexsha": "a340d21564f6ed0b002fd83f8341dfbc5de6927b", "size": 4678, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/src/cahnhilliard_thermal_nodiffusion.cpp", "max_stars_repo_name": "exalearn/cahnhilliard_2d", "max_stars_repo_head_hexsha": "cbf272bbac8080ff97c1cc93e7e7246bee04e075", "max_stars_repo_licenses": ["0BSD"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-04-23T23:53:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T06:16:24.000Z", "max_issues_repo_path": "cpp/src/cahnhilliard_thermal_nodiffusion.cpp", "max_issues_repo_name": "exalearn/cahnhilliard_2d", "max_issues_repo_head_hexsha": "cbf272bbac8080ff97c1cc93e7e7246bee04e075", "max_issues_repo_licenses": ["0BSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp/src/cahnhilliard_thermal_nodiffusion.cpp", "max_forks_repo_name": "exalearn/cahnhilliard_2d", "max_forks_repo_head_hexsha": "cbf272bbac8080ff97c1cc93e7e7246bee04e075", "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": 37.424, "max_line_length": 164, "alphanum_fraction": 0.6566908935, "num_tokens": 1456, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4734740965437591}}
{"text": "#include <boost/math/quaternion.hpp>\n", "meta": {"hexsha": "8bc5f733f70b7a6ddec52fcbe8daa796f43b5d90", "size": 37, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_quaternion.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_quaternion.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_quaternion.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 18.5, "max_line_length": 36, "alphanum_fraction": 0.7837837838, "num_tokens": 8, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517044, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.47346940116477004}}
{"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_CONSTANT_RATIO_HPP_INCLUDED\n#define BOOST_SIMD_CONSTANT_RATIO_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n  /*!\n    @ingroup group-constant\n    @brief Generate a constant from a static rational number representation.\n\n    @tparam Type        Type of the generated constant\n    @tparam Numerator   Numerator of the generated constant\n    @tparam Denominator Denominator of the generated constant\n  **/\n  template<typename Type, std::uintmax_t Numerator, std::uintmax_t Denumerator> auto Ratio();\n} }\n#endif\n\n#include <boost/simd/constant/scalar/ratio.hpp>\n#include <boost/simd/constant/simd/ratio.hpp>\n\n#endif\n", "meta": {"hexsha": "16ac1e3443043e61a43931f22473e2609c0e5804", "size": 1051, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/constant/ratio.hpp", "max_stars_repo_name": "TobiasLudwig/boost.simd", "max_stars_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/simd/constant/ratio.hpp", "max_issues_repo_name": "TobiasLudwig/boost.simd", "max_issues_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/constant/ratio.hpp", "max_forks_repo_name": "TobiasLudwig/boost.simd", "max_forks_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-02-16T09:58:18.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:22:43.000Z", "avg_line_length": 31.8484848485, "max_line_length": 100, "alphanum_fraction": 0.6127497621, "num_tokens": 206, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743168019989179, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.473420924448416}}
{"text": "#include \"problemes.h\"\n#include \"arithmetique.h\"\n\n#include <boost/date_time/date_defs.hpp>\n#include <boost/date_time/gregorian/gregorian.hpp>\n\ntypedef unsigned long long nombre;\n\nENREGISTRER_PROBLEME(19, \"Counting Sundays\") {\n    // You are given the following information, but you may prefer to do some research for yourself.\n    // \n    // 1 Jan 1900 was a Monday.\n    // Thirty days has September,\n    // April, June and November.\n    // All the rest have thirty-one,\n    // Saving February alone,\n    // Which has twenty-eight, rain or shine.\n    // And on leap years, twenty-nine.\n    // A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.\n    //\n    // How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?\n    boost::gregorian::month_iterator start(boost::gregorian::date(1901, 1, 1), 1);\n    boost::gregorian::date end(2000, 12, 31);\n    nombre resultat = 0;\n    while (start <= end) {\n        if (start->day_of_week() == boost::date_time::Sunday) {\n            // std::cout << *start << std::endl;\n            ++resultat;\n        }\n        ++start;\n    }\n    return std::to_string(resultat);\n}\n", "meta": {"hexsha": "3ddb1289271f30666119abf7907c7395dc3ce7c3", "size": 1209, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problemes/probleme0xx/probleme019.cpp", "max_stars_repo_name": "ZongoForSpeed/ProjectEuler", "max_stars_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-10-13T17:07:21.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-08T11:50:22.000Z", "max_issues_repo_path": "problemes/probleme0xx/probleme019.cpp", "max_issues_repo_name": "ZongoForSpeed/ProjectEuler", "max_issues_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problemes/probleme0xx/probleme019.cpp", "max_forks_repo_name": "ZongoForSpeed/ProjectEuler", "max_forks_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.5588235294, "max_line_length": 112, "alphanum_fraction": 0.6492969396, "num_tokens": 319, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743168019989179, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.47342091420612}}
{"text": "//  Boost static_min_max.hpp test program  -----------------------------------//\n\n//  (C) Copyright Daryle Walker 2001.\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//  Revision History\n//  23 Sep 2001  Initial version (Daryle Walker)\n\n#define  BOOST_INCLUDE_MAIN\n#include <boost/test/test_tools.hpp>  // for main, BOOST_CHECK\n\n#include <boost/cstdlib.hpp>                 // for boost::exit_success\n#include <boost/integer/static_min_max.hpp>  // for boost::static_signed_min, etc.\n\n#include <iostream>  // for std::cout (std::endl indirectly)\n\n\n// Main testing function\nint\ntest_main\n(\n    int         ,   // \"argc\" is unused\n    char *      []  // \"argv\" is unused\n)\n{    \n    using std::cout;\n    using std::endl;\n    using boost::static_signed_min;\n    using boost::static_signed_max;\n    using boost::static_unsigned_min;\n    using boost::static_unsigned_max;\n\n    // Two positives\n    cout << \"Doing tests with two positive values.\" << endl;\n\n    BOOST_CHECK( (static_signed_min< 9, 14>::value) ==  9 );\n    BOOST_CHECK( (static_signed_max< 9, 14>::value) == 14 );\n    BOOST_CHECK( (static_signed_min<14,  9>::value) ==  9 );\n    BOOST_CHECK( (static_signed_max<14,  9>::value) == 14 );\n\n    BOOST_CHECK( (static_unsigned_min< 9, 14>::value) ==  9 );\n    BOOST_CHECK( (static_unsigned_max< 9, 14>::value) == 14 );\n    BOOST_CHECK( (static_unsigned_min<14,  9>::value) ==  9 );\n    BOOST_CHECK( (static_unsigned_max<14,  9>::value) == 14 );\n\n    // Two negatives\n    cout << \"Doing tests with two negative values.\" << endl;\n\n    BOOST_CHECK( (static_signed_min<  -8, -101>::value) == -101 );\n    BOOST_CHECK( (static_signed_max<  -8, -101>::value) ==   -8 );\n    BOOST_CHECK( (static_signed_min<-101,   -8>::value) == -101 );\n    BOOST_CHECK( (static_signed_max<-101,   -8>::value) ==   -8 );\n\n    // With zero\n    cout << \"Doing tests with zero and a positive or negative value.\" << endl;\n\n    BOOST_CHECK( (static_signed_min< 0, 14>::value) ==  0 );\n    BOOST_CHECK( (static_signed_max< 0, 14>::value) == 14 );\n    BOOST_CHECK( (static_signed_min<14,  0>::value) ==  0 );\n    BOOST_CHECK( (static_signed_max<14,  0>::value) == 14 );\n\n    BOOST_CHECK( (static_unsigned_min< 0, 14>::value) ==  0 );\n    BOOST_CHECK( (static_unsigned_max< 0, 14>::value) == 14 );\n    BOOST_CHECK( (static_unsigned_min<14,  0>::value) ==  0 );\n    BOOST_CHECK( (static_unsigned_max<14,  0>::value) == 14 );\n\n    BOOST_CHECK( (static_signed_min<   0, -101>::value) == -101 );\n    BOOST_CHECK( (static_signed_max<   0, -101>::value) ==    0 );\n    BOOST_CHECK( (static_signed_min<-101,    0>::value) == -101 );\n    BOOST_CHECK( (static_signed_max<-101,    0>::value) ==    0 );\n\n    // With identical\n    cout << \"Doing tests with two identical values.\" << endl;\n\n    BOOST_CHECK( (static_signed_min<0, 0>::value) == 0 );\n    BOOST_CHECK( (static_signed_max<0, 0>::value) == 0 );\n    BOOST_CHECK( (static_unsigned_min<0, 0>::value) == 0 );\n    BOOST_CHECK( (static_unsigned_max<0, 0>::value) == 0 );\n\n    BOOST_CHECK( (static_signed_min<14, 14>::value) == 14 );\n    BOOST_CHECK( (static_signed_max<14, 14>::value) == 14 );\n    BOOST_CHECK( (static_unsigned_min<14, 14>::value) == 14 );\n    BOOST_CHECK( (static_unsigned_max<14, 14>::value) == 14 );\n\n    BOOST_CHECK( (static_signed_min< -101, -101>::value) == -101 );\n    BOOST_CHECK( (static_signed_max< -101, -101>::value) == -101 );\n\n    return boost::exit_success;\n}\n", "meta": {"hexsha": "ed081f73c9914f4aa9187efa2972c09ceb702b0b", "size": 3600, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/integer/test/static_min_max_test.cpp", "max_stars_repo_name": "mike-code/boost_1_38_0", "max_stars_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-07-31T02:19:48.000Z", "max_stars_repo_stars_event_max_datetime": "2017-07-31T02:19:48.000Z", "max_issues_repo_path": "libs/integer/test/static_min_max_test.cpp", "max_issues_repo_name": "boost-cmake/vintage", "max_issues_repo_head_hexsha": "dcfb7da3177134eddaee6789d6f582259cb0d6ee", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/integer/test/static_min_max_test.cpp", "max_forks_repo_name": "boost-cmake/vintage", "max_forks_repo_head_hexsha": "dcfb7da3177134eddaee6789d6f582259cb0d6ee", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-07T05:20:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-07T05:20:43.000Z", "avg_line_length": 38.2978723404, "max_line_length": 82, "alphanum_fraction": 0.6286111111, "num_tokens": 1077, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743168019989179, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.47342091420612}}
{"text": "#ifndef HOOKE_LINEAR_ELASTICITY_HPP\n#define HOOKE_LINEAR_ELASTICITY_HPP\n\n#include <polyfem/Common.hpp>\n#include <polyfem/ElasticityUtils.hpp>\n\n#include <polyfem/ElementAssemblyValues.hpp>\n#include <polyfem/ElementBases.hpp>\n\n#include <polyfem/AutodiffTypes.hpp>\n\n#include <Eigen/Dense>\n#include <array>\n\n//local assembler for HookeLinearElasticity C : (F+F^T)/2, see linear elasticity\nnamespace polyfem\n{\n\tclass HookeLinearElasticity\n\t{\n\tpublic:\n\t\tHookeLinearElasticity();\n\n\t\t// res is R^{dim\u00b2}\n\t\tEigen::Matrix<double, Eigen::Dynamic, 1, 0, 9, 1>\n\t\tassemble(const ElementAssemblyValues &vals, const int i, const int j, 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\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\tinline int size() const { return size_; }\n\n\t\tvoid set_size(const int size);\n\n\t\t//sets the elasticty tensor\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\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\n#endif //HOOKE_LINEAR_ELASTICITY_HPP\n", "meta": {"hexsha": "4e72ee15d4ce4d10d1f40f2379a7b72a41178536", "size": 1730, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/assembler/HookeLinearElasticity.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/HookeLinearElasticity.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/HookeLinearElasticity.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": 34.6, "max_line_length": 281, "alphanum_fraction": 0.7670520231, "num_tokens": 487, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.6370308013713525, "lm_q1q2_score": 0.473420912079961}}
{"text": "// Copyright (c) 2015-2018, CNRS\n// Authors: Justin Carpentier <jcarpent@laas.fr>\n\n#ifndef __multicontact_api_geometry_ellipsoid_hpp__\n#define __multicontact_api_geometry_ellipsoid_hpp__\n\n#include <Eigen/Dense>\n#include <iostream>\n\n#include \"multicontact-api/geometry/fwd.hpp\"\n\nnamespace multicontact_api {\n  namespace geometry\n  {\n    template<typename _Scalar, int _dim, int _Options>\n    struct Ellipsoid\n    {\n      EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n      typedef _Scalar Scalar;\n      enum { dim = _dim };\n      enum { Options = _Options };\n\n      typedef Eigen::Matrix<Scalar,dim,dim,Options> Matrix;\n      typedef Eigen::Matrix<Scalar,dim,1,Options> Vector;\n\n      Ellipsoid(const Matrix & A, const Vector & center)\n      : m_A(A)\n      , m_center(center)\n      {}\n\n      Scalar lhsValue(const Vector & point) const { return (m_A*(point-m_center)).norm(); }\n\n      const Matrix & A() const { return m_A; }\n      Matrix & A() { return m_A; }\n      const Vector & center() const { return m_center; }\n      Vector & center() { return m_center; }\n\n      void disp(std::ostream & os) const\n      {\n        os\n        << \"A:\\n\" << m_A << std::endl\n        << \"center: \" << m_center.transpose() << std::endl;\n      }\n\n      friend std::ostream & operator << (std::ostream & os,const Ellipsoid & E)\n      {\n        E.disp(os);\n        return os;\n      }\n\n    protected:\n      /// \\brief\n      Matrix m_A;\n\n      /// \\brief Center of the ellipsoid expressed in the global frame.\n      Vector m_center;\n    };\n  }\n}\n\n#endif // ifndef __multicontact_api_geometry_ellipsoid_hpp__\n", "meta": {"hexsha": "30b4179f0667715ae784cef6f7b837e8f435d80c", "size": 1573, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/multicontact-api/geometry/ellipsoid.hpp", "max_stars_repo_name": "pFernbach/multicontact-api", "max_stars_repo_head_hexsha": "efe4cf25d37aba9184875df6036a864d7aa34b88", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-17T09:19:05.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-17T09:19:05.000Z", "max_issues_repo_path": "include/multicontact-api/geometry/ellipsoid.hpp", "max_issues_repo_name": "pFernbach/multicontact-api", "max_issues_repo_head_hexsha": "efe4cf25d37aba9184875df6036a864d7aa34b88", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/multicontact-api/geometry/ellipsoid.hpp", "max_forks_repo_name": "pFernbach/multicontact-api", "max_forks_repo_head_hexsha": "efe4cf25d37aba9184875df6036a864d7aa34b88", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.3709677419, "max_line_length": 91, "alphanum_fraction": 0.6261919898, "num_tokens": 402, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.4734209069588131}}
{"text": "// Copyright PinaPL\n//\n// functions.cpp\n// PinaPL\n//\n#include <stdlib.h>\n#include <math.h>\n#include <Eigen/Dense>\n#include <string>\n#include <sstream>\n#include <iostream>\n#include <map>\n\ndouble sigmoid(double x) {\n    return (1/(1+exp(-x)));\n}\n\ndouble sigmoid_derivative(double x) {\n    return x*(1-x);\n}\n\ndouble tanh_derivative(double x) {\n    return 1-tanh(x)*tanh(x);\n}\n\ndouble tanhyp(double x) {\n    return tanh(x);\n}\n", "meta": {"hexsha": "f4c33792642e36316a3847deab4d5ef4c46f803a", "size": 422, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "functions.cpp", "max_stars_repo_name": "supelec-lstm/PinaPL_lstm", "max_stars_repo_head_hexsha": "96462ed2f8f880ccfc33424eb6a273522b90b049", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "functions.cpp", "max_issues_repo_name": "supelec-lstm/PinaPL_lstm", "max_issues_repo_head_hexsha": "96462ed2f8f880ccfc33424eb6a273522b90b049", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "functions.cpp", "max_forks_repo_name": "supelec-lstm/PinaPL_lstm", "max_forks_repo_head_hexsha": "96462ed2f8f880ccfc33424eb6a273522b90b049", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.5517241379, "max_line_length": 37, "alphanum_fraction": 0.6516587678, "num_tokens": 117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.47342090695881306}}
{"text": "#ifndef FAST_GICP_FAST_VGICP_VOXEL_HPP\n#define FAST_GICP_FAST_VGICP_VOXEL_HPP\n\n#include <unordered_map>\n#include <boost/functional/hash.hpp>\n#include <fast_gicp/gicp/gicp_settings.hpp>\n\nnamespace fast_gicp {\n\nstatic std::vector<Eigen::Vector3i, Eigen::aligned_allocator<Eigen::Vector3i>> neighbor_offsets(NeighborSearchMethod search_method) {\n  switch(search_method) {\n      // clang-format off\n    default:\n      std::cerr << \"unsupported neighbor search method\" << std::endl;\n      abort();\n    case NeighborSearchMethod::DIRECT1:\n      return std::vector<Eigen::Vector3i, Eigen::aligned_allocator<Eigen::Vector3i>>{\n        Eigen::Vector3i(0, 0, 0)\n      };\n    case NeighborSearchMethod::DIRECT7:\n      return std::vector<Eigen::Vector3i, Eigen::aligned_allocator<Eigen::Vector3i>>{\n        Eigen::Vector3i(0, 0, 0),\n        Eigen::Vector3i(1, 0, 0),\n        Eigen::Vector3i(-1, 0, 0),\n        Eigen::Vector3i(0, 1, 0),\n        Eigen::Vector3i(0, -1, 0),\n        Eigen::Vector3i(0, 0, 1),\n        Eigen::Vector3i(0, 0, -1)\n      };\n    case NeighborSearchMethod::DIRECT27:\n      break;\n      // clang-format on\n  }\n\n  std::vector<Eigen::Vector3i, Eigen::aligned_allocator<Eigen::Vector3i>> offsets27;\n  for(int i = 0; i < 3; i++) {\n    for(int j = 0; j < 3; j++) {\n      for(int k = 0; k < 3; k++) {\n        offsets27.push_back(Eigen::Vector3i(i - 1, j - 1, k - 1));\n      }\n    }\n  }\n  return offsets27;\n}\n\nclass Vector3iHash {\npublic:\n  size_t operator()(const Eigen::Vector3i& x) const {\n    size_t seed = 0;\n    boost::hash_combine(seed, x[0]);\n    boost::hash_combine(seed, x[1]);\n    boost::hash_combine(seed, x[2]);\n    return seed;\n  }\n};\n\nstruct GaussianVoxel {\npublic:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n  using Ptr = std::shared_ptr<GaussianVoxel>;\n\n  GaussianVoxel() {\n    num_points = 0;\n    mean.setZero();\n    cov.setZero();\n  }\n  virtual ~GaussianVoxel() {}\n\n  virtual void append(const Eigen::Vector4d& mean_, const Eigen::Matrix4d& cov_) = 0;\n\n  virtual void finalize() = 0;\n\npublic:\n  int num_points;\n  Eigen::Vector4d mean;\n  Eigen::Matrix4d cov;\n};\n\nstruct MultiplicativeGaussianVoxel : GaussianVoxel {\npublic:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n  MultiplicativeGaussianVoxel() : GaussianVoxel() {}\n  virtual ~MultiplicativeGaussianVoxel() {}\n\n  virtual void append(const Eigen::Vector4d& mean_, const Eigen::Matrix4d& cov_) override {\n    num_points++;\n    Eigen::Matrix4d cov_inv = cov_;\n    cov_inv(3, 3) = 1;\n    cov_inv = cov_inv.inverse().eval();\n\n    cov += cov_inv;\n    mean += cov_inv * mean_;\n  }\n\n  virtual void finalize() override {\n    cov(3, 3) = 1;\n    mean[3] = 1;\n\n    cov = cov.inverse().eval();\n    mean = (cov * mean).eval();\n  }\n};\n\nstruct AdditiveGaussianVoxel : GaussianVoxel {\npublic:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n  AdditiveGaussianVoxel() : GaussianVoxel() {}\n  virtual ~AdditiveGaussianVoxel() {}\n\n  virtual void append(const Eigen::Vector4d& mean_, const Eigen::Matrix4d& cov_) override {\n    num_points++;\n    mean += mean_;\n    cov += cov_;\n  }\n\n  virtual void finalize() override {\n    mean /= num_points;\n    cov /= num_points;\n  }\n};\n\ntemplate<typename PointT>\nclass GaussianVoxelMap {\npublic:\n  GaussianVoxelMap(double resolution, VoxelAccumulationMode mode) : voxel_resolution_(resolution), voxel_mode_(mode) {}\n\n  void create_voxelmap(const pcl::PointCloud<PointT>& cloud, const std::vector<Eigen::Matrix4d, Eigen::aligned_allocator<Eigen::Matrix4d>>& covs) {\n    voxels_.clear();\n    for(int i = 0; i < cloud.size(); i++) {\n      Eigen::Vector3i coord = voxel_coord(cloud.at(i).getVector4fMap().template cast<double>());\n\n      auto found = voxels_.find(coord);\n      if(found == voxels_.end()) {\n        GaussianVoxel::Ptr voxel;\n        switch(voxel_mode_) {\n          case VoxelAccumulationMode::ADDITIVE:\n          case VoxelAccumulationMode::ADDITIVE_WEIGHTED:\n            voxel = std::shared_ptr<AdditiveGaussianVoxel>(new AdditiveGaussianVoxel);\n            break;\n          case VoxelAccumulationMode::MULTIPLICATIVE:\n            voxel = std::shared_ptr<MultiplicativeGaussianVoxel>(new MultiplicativeGaussianVoxel);\n            break;\n        }\n        found = voxels_.insert(found, std::make_pair(coord, voxel));\n      }\n\n      auto& voxel = found->second;\n      voxel->append(cloud.at(i).getVector4fMap().template cast<double>(), covs[i]);\n    }\n\n    for(auto& voxel : voxels_) {\n      voxel.second->finalize();\n    }\n  }\n\n  Eigen::Vector3i voxel_coord(const Eigen::Vector4d& x) const {\n    return (x.array() / voxel_resolution_ - 0.5).floor().template cast<int>().template head<3>();\n  }\n\n  Eigen::Vector4d voxel_origin(const Eigen::Vector3i& coord) const {\n    Eigen::Vector3d origin = (coord.template cast<double>().array() + 0.5) * voxel_resolution_;\n    return Eigen::Vector4d(origin[0], origin[1], origin[2], 1.0f);\n  }\n\n  GaussianVoxel::Ptr lookup_voxel(const Eigen::Vector3i& coord) const {\n    auto found = voxels_.find(coord);\n    if(found == voxels_.end()) {\n      return nullptr;\n    }\n\n    return found->second;\n  }\n\nprivate:\n  double voxel_resolution_;\n  VoxelAccumulationMode voxel_mode_;\n\n  using VoxelMap = std::unordered_map<Eigen::Vector3i, GaussianVoxel::Ptr, Vector3iHash, std::equal_to<Eigen::Vector3i>, Eigen::aligned_allocator<std::pair<const Eigen::Vector3i, GaussianVoxel::Ptr>>>;\n  VoxelMap voxels_;\n};\n\n}  // namespace fast_gicp\n\n#endif", "meta": {"hexsha": "3315c0bb0456a1e2d5811fe2291e80bbc04a43ee", "size": 5341, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/fast_gicp/gicp/fast_vgicp_voxel.hpp", "max_stars_repo_name": "Gatsby23/fast_gicp", "max_stars_repo_head_hexsha": "2e9fd0b342b02b65e92142e9971f2e342f40a20a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2111.0, "max_stars_repo_stars_event_min_datetime": "2019-01-29T07:01:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T06:48:14.000Z", "max_issues_repo_path": "include/fast_gicp/gicp/fast_vgicp_voxel.hpp", "max_issues_repo_name": "Gatsby23/fast_gicp", "max_issues_repo_head_hexsha": "2e9fd0b342b02b65e92142e9971f2e342f40a20a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 131.0, "max_issues_repo_issues_event_min_datetime": "2019-02-18T10:56:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-27T12:07:00.000Z", "max_forks_repo_path": "include/fast_gicp/gicp/fast_vgicp_voxel.hpp", "max_forks_repo_name": "Gatsby23/fast_gicp", "max_forks_repo_head_hexsha": "2e9fd0b342b02b65e92142e9971f2e342f40a20a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 421.0, "max_forks_repo_forks_event_min_datetime": "2019-02-12T07:59:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T05:22:01.000Z", "avg_line_length": 28.7150537634, "max_line_length": 201, "alphanum_fraction": 0.6626099981, "num_tokens": 1535, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.47342090695881306}}
{"text": "#include <iostream>\nusing namespace std;\n\n#include <mtl/mtl.h>\n#include <mtl/matrix.h>\n#include <mtl/dense1D.h>\n#include <mtl/utils.h>\n\nnamespace mtl {\n\ntemplate <class MatA>\ninline void\nsimple_print(const MatA& A)\n{\n  typedef typename matrix_traits<MatA>::size_type Int;\n  typename MatA::const_iterator A_k;\n  typename MatA::OneD::const_iterator A_ki;\n\n  A_k = A.begin();\n  while (not_at(A_k, A.end())) {\n    const typename MatA::OneDRef A_k_ = *A_k;\n    A_ki = A_k_.begin();\n    while (not_at(A_ki, A_k_.end())) {\n      Int k = A_ki.column();\n      Int i = A_ki.row();\n      std::cout << \"A(\" << i << \",\" << k << \")\" << *A_ki << std::endl;\n      ++A_ki;\n    }\n    ++A_k;\n  }\n}\n\n}\n\n\nint\nmain()\n{\n  typedef mtl::matrix<double,\n                  mtl::diagonal<>,\n                  mtl::banded<mtl::external>, \n                   mtl::column_major>::type DiagMatE;\n\n  typedef mtl::matrix<double, \n                 mtl::rectangle<>, \n                 mtl::dense<mtl::external>, \n                 mtl::column_major>::type MatrixE;\n\n  typedef mtl::matrix<double, \n                 mtl::rectangle<>, \n                 mtl::dense<mtl::internal>, \n                 mtl::column_major>::type MatrixI;\n\n  int N = 3;\n  double da [] = { 1, 3, 2, 2, 1, 2, 2, 2, 1 };\n  double dc [] = { 1, 3, 2};\n\n  MatrixE A(da, N, N);\n  DiagMatE C(dc, N, N, 0, 0);\n  MatrixI AxC(N,N);\n\n  cout << \"Full A:\" << endl;\n  mtl::print_all_matrix(A);\n  cout << \"Diag C:\" << endl;\n  mtl::print_all_banded(C,0,0);\n  mtl::simple_print(C);\n  cout << \"Output AxC:\" << endl;\n\n  //put C as the first parameter in mult \n  //since C is a banded matrix\n  mtl::mult(C,A,AxC);\n  mtl::print_all_matrix(AxC);\n\n\n  return 0;\n}\n", "meta": {"hexsha": "771d4461781ca829cee7af1a0b1062414e94dc18", "size": 1674, "ext": "cc", "lang": "C++", "max_stars_repo_path": "stapl_release/tools/mtl-2.0/contrib/examples/banded_matmat.cc", "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/tools/mtl-2.0/contrib/examples/banded_matmat.cc", "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/tools/mtl-2.0/contrib/examples/banded_matmat.cc", "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": 21.7402597403, "max_line_length": 70, "alphanum_fraction": 0.5495818399, "num_tokens": 551, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431679972357831, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.47342089971150614}}
{"text": "// Copyright (c) 2021 Graphcore Ltd. All rights reserved.\n#include \"poplin/Cholesky.hpp\"\n#include \"poplin/MatMul.hpp\"\n#include \"poplin/TriangularSolve.hpp\"\n#include <boost/assign/list_of.hpp>\n#include <boost/optional.hpp>\n#include <boost/optional/optional_io.hpp>\n#include <boost/program_options.hpp>\n#include <boost/random.hpp>\n#include <boost/version.hpp>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <poplibs_support/TestDevice.hpp>\n#include <poplibs_support/VectorUtils.hpp>\n#include <poplibs_test/GeneralMatrixMultiply.hpp>\n#include <poplibs_test/Util.hpp>\n#include <poplin/MatMul.hpp>\n#include <poplin/codelets.hpp>\n#include <popops/codelets.hpp>\n#include <poputil/TileMapping.hpp>\n#include <sstream>\n\nusing namespace poplibs_support;\n\nvoid printArray(std::string name, boost::multi_array<double, 3> a) {\n  std::cout << name << \": \" << std::endl;\n  std::size_t ng = a.shape()[0];\n  std::size_t nr = a.shape()[1];\n  std::size_t nc = a.shape()[2];\n\n  for (std::size_t g = 0; g < ng; g++) {\n    std::cout << g << std::endl;\n    for (std::size_t r = 0; r < nr; r++) {\n      std::cout << \" \";\n      for (std::size_t c = 0; c < nc; c++) {\n        std::cout << std::setw(10) << a[g][r][c];\n      }\n      std::cout << std::endl;\n    }\n    std::cout << std::endl;\n  }\n}\n\nboost::multi_array<double, 3> createPositiveDefiniteMatrix(std::size_t batches,\n                                                           std::size_t rank) {\n  boost::multi_array<double, 3> l(boost::extents[batches][rank][rank]);\n  boost::multi_array<double, 3> pd(boost::extents[batches][rank][rank]);\n\n  std::mt19937 randomEngine;\n  boost::random::uniform_real_distribution<> dist(0.01, 1.0);\n\n  for (std::size_t b = 0; b < batches; b++) {\n    for (std::size_t r = 0; r < rank; r++) {\n      for (std::size_t c = 0; c < rank; c++) {\n        double v = dist(randomEngine);\n        l[b][r][c] = v;\n      }\n    }\n  }\n\n  poplibs_test::gemm::generalGroupedMatrixMultiply(l, l, pd, false, true);\n\n  for (std::size_t b = 0; b < batches; b++) {\n    for (std::size_t r = 0; r < rank; r++) {\n      pd[b][r][r] += rank;\n    }\n  }\n\n  return pd;\n}\n\nconst boost::multi_array<double, 3>\nmaskTriangularMatrix(const boost::multi_array<double, 3> &m,\n                     bool lower = true) {\n  std::size_t batches = m.shape()[0];\n  std::size_t rank = m.shape()[1];\n  boost::multi_array<double, 3> tm(boost::extents[batches][rank][rank]);\n\n  for (std::size_t b = 0; b < batches; b++) {\n    for (std::size_t r = 0; r < rank; r++) {\n      for (std::size_t c = 0; c < rank; c++) {\n        if ((lower && c <= r) || (!lower && c >= r))\n          tm[b][r][c] = m[b][r][c];\n        else\n          tm[b][r][c] = 0;\n      }\n    }\n  }\n\n  return tm;\n}\n\nint main(int argc, char **argv) try {\n  namespace po = boost::program_options;\n\n  DeviceType deviceType;\n  boost::optional<unsigned> tilesPerIPU;\n\n  po::options_description desc(\"Options\");\n\n  unsigned numBatches = 1;\n  unsigned aRank;\n  unsigned bRank = -1;\n  bool leftSide = true;\n  poplar::Type dataType;\n  boost::optional<unsigned> blockSizeParam;\n  bool lower = true;\n  bool unitDiagonal = true;\n  boost::optional<std::string> profileDir;\n\n  // clang-format off\n  desc.add_options()\n    (\"help,h\", \"produce help message\")\n    (\"compile-only\", \"Stop after compilation; don't run the program\")\n    (\"device-type\",\n      po::value<DeviceType>(&deviceType)->default_value(DeviceType::IpuModel2),\n      deviceTypeHelp)\n    (\"profile\", \"Output profiling report to standard output\")\n    (\"profile-dir\",\n     po::value<decltype(profileDir)>(&profileDir)\n      ->default_value(boost::none),\n     \"Write profile files to the specified directory.\")\n    (\"cholesky\", \"Run cholesky solver\")\n    (\"ignore-data\", \"Don't upload and download the results from the device. \"\n     \"Note that this means the result is not validated against the model.\")\n    (\"tiles-per-ipu\", po::value(&tilesPerIPU), \"Number of tiles per IPU\")\n    (\"data-type\",\n     po::value(&dataType)->required(),\n     \"Data Type\")\n    (\"a-rank\",\n     po::value(&aRank)->required(),\n     \"Rank of the A matrix.\")\n    (\"b-rank\",\n     po::value(&bRank),\n     \"Rank of the B matrix.\")\n    (\"batches\",\n     po::value(&numBatches)->default_value(numBatches),\n     \"Number of batch dimensions.\")\n    (\"left-side\",\n     po::value(&leftSide)->default_value(leftSide),\n     \"Left side - solve AX = B, XA = B overwise.\")\n    (\"lower\",\n     po::value(&lower)->default_value(lower),\n     \"Generate lower A, upper A overwise.\")\n    (\"unit-diagonal\",\n     po::value(&unitDiagonal)->default_value(unitDiagonal),\n     \"Assume A has unit diagonal.\")\n    (\"block-size\",\n     po::value(&blockSizeParam),\n     \"Solver block size if specified, no block solver overwise.\")\n    ;\n  // clang-format on\n\n  po::variables_map vm;\n  try {\n    const po::positional_options_description p;\n    po::store(\n        po::command_line_parser(argc, argv).options(desc).positional(p).run(),\n        vm);\n    po::notify(vm);\n\n    if (vm.count(\"help\")) {\n      std::cout << desc << \"\\n\";\n      return 1;\n    }\n  } catch (const boost::program_options::error &e) {\n    std::cerr << e.what() << std::endl;\n    return 1;\n  }\n\n  poplar::OptionFlags engineOptions;\n  if (vm.count(\"profile\") || profileDir) {\n    engineOptions.set(\"debug.instrumentCompute\", \"true\");\n    if (profileDir) {\n      engineOptions.set(\"autoReport.all\", \"true\");\n      engineOptions.set(\"autoReport.directory\", *profileDir);\n    }\n  }\n\n  const bool runCholesky = vm.count(\"cholesky\");\n\n  const bool ignoreData = vm.count(\"ignore-data\");\n\n  const unsigned numIPUs = 1;\n  const bool compileIPUCode = true;\n  auto device =\n      tilesPerIPU\n          ? createTestDevice(deviceType, numIPUs, *tilesPerIPU, compileIPUCode)\n          : createTestDeviceFullSize(deviceType, numIPUs, compileIPUCode);\n\n  const auto &target = device.getTarget();\n  poplar::Graph graph(target);\n  poplin::addCodelets(graph);\n  popops::addCodelets(graph);\n\n  poplin::matmul::PlanningCache cache;\n  poplar::program::Sequence uploadProg, prog, downloadProg;\n  poplar::OptionFlags options;\n\n  poplar::DebugContext debugContext;\n\n  if (blockSizeParam) {\n    options.set(\"blockSize\", std::to_string(*blockSizeParam));\n  }\n\n  if (runCholesky) {\n    bRank = 0;\n    unitDiagonal = false;\n\n    if (!leftSide)\n      throw poplar::poplar_error(\n          \"left-side must be true when using the cholesky solver.\");\n  } else if (bRank < 0) {\n    throw poplar::poplar_error(\n        \"--b-rank is mandatory option for triangular solver\");\n  }\n\n  std::vector<std::size_t> inputAShape{numBatches, aRank, aRank};\n  std::vector<std::size_t> inputBShape{numBatches, leftSide ? aRank : bRank,\n                                       leftSide ? bRank : aRank};\n\n  std::vector<std::pair<poplin::MatMulParams, poplar::OptionFlags>>\n      matmulOptPairs;\n  if (runCholesky) {\n    matmulOptPairs = poplin::getCholeskyMatMulPrePlanParameters(\n        dataType, inputAShape, lower, options);\n  } else {\n    matmulOptPairs = poplin::getTriangularSolveMatMulPrePlanParameters(\n        dataType, dataType, inputAShape, inputBShape, leftSide, lower, options);\n  }\n\n  std::set<poplin::MatMulPlanParams> params;\n  for (auto &pair : matmulOptPairs)\n    params.emplace(&target, pair.first, &pair.second);\n  preplanMatMuls(params, cache);\n\n  poplar::Tensor inputA;\n  if (runCholesky) {\n    inputA = poplin::createCholeskyInput(graph, dataType, inputAShape, lower,\n                                         debugContext, options, &cache);\n  } else {\n    inputA = poplin::createTriangularSolveInputLHS(\n        graph, dataType, dataType, inputAShape, inputBShape, leftSide,\n        debugContext, options, &cache);\n  }\n\n  poplar::Tensor inputB;\n  if (!runCholesky) {\n    inputB = poplin::createTriangularSolveInputRHS(\n        graph, dataType, dataType, inputAShape, inputBShape, leftSide,\n        debugContext, options, &cache);\n  }\n\n  poplar::Tensor out;\n  if (runCholesky) {\n    poplin::choleskyInPlace(graph, inputA, lower, prog, debugContext, options,\n                            &cache);\n    out = inputA;\n  } else {\n    out = poplin::triangularSolve(graph, inputA, inputB, leftSide, lower,\n                                  unitDiagonal, prog, debugContext, options,\n                                  &cache);\n  }\n\n  std::vector<std::pair<std::string, char *>> tmap;\n  std::unique_ptr<char[]> rawHostInputA, rawHostInputB, rawHostOutput,\n      rawHostOutputT;\n  if (!ignoreData) {\n    rawHostInputA = poplibs_test::util::allocateHostMemoryForTensor(\n        inputA, \"A\", graph, uploadProg, boost::none, tmap);\n\n    if (!runCholesky) {\n      rawHostInputB = poplibs_test::util::allocateHostMemoryForTensor(\n          inputB, \"B\", graph, uploadProg, boost::none, tmap);\n    }\n\n    rawHostOutput = poplibs_test::util::allocateHostMemoryForTensor(\n        out, \"X\", graph, boost::none, downloadProg, tmap);\n\n    rawHostOutputT = poplibs_test::util::allocateHostMemoryForTensor(\n        poplin::transposeGroupedMatrix(out), \"XT\", graph, boost::none,\n        downloadProg, tmap);\n  }\n\n  poplar::Engine engine(graph, {uploadProg, prog, downloadProg}, engineOptions);\n\n  if (vm.count(\"compile-only\"))\n    return 0;\n\n  boost::multi_array<double, 3> hostInputA;\n  boost::multi_array<double, 3> hostInputAFilled;\n  boost::multi_array<double, 3> hostInputB;\n  if (!ignoreData) {\n    std::mt19937 randomEngine;\n    boost::random::uniform_real_distribution<> dist(0.01, 1.0);\n    boost::random::uniform_real_distribution<> diagonalDist(0.95, 1.05);\n\n    poplibs_test::util::attachStreams(engine, tmap);\n\n    if (runCholesky) {\n      hostInputAFilled.resize(boost::extents[numBatches][aRank][aRank]);\n      hostInputA.resize(boost::extents[numBatches][aRank][aRank]);\n\n      hostInputAFilled = createPositiveDefiniteMatrix(numBatches, aRank);\n      hostInputA = maskTriangularMatrix(hostInputAFilled, lower);\n    } else {\n\n      hostInputA.resize(boost::extents[numBatches][aRank][aRank]);\n      for (std::size_t g = 0; g < numBatches; ++g) {\n        auto matrix = hostInputA[g];\n        for (std::size_t i = 0; i < aRank; ++i) {\n          auto rows = matrix[i];\n          for (std::size_t j = 0; j < aRank; ++j) {\n            double value;\n            if (i == j) {\n              value = unitDiagonal ? 1.0 : diagonalDist(randomEngine);\n            } else if ((i <= j && !lower) || (j <= i && lower)) {\n              value = dist(randomEngine);\n            } else {\n              value = 0.0;\n            }\n            rows[j] = value;\n          }\n        }\n      }\n    }\n    poplibs_test::util::copy(target, hostInputA, dataType, rawHostInputA.get());\n\n    if (!runCholesky) {\n      hostInputB.resize(\n          boost::extents[numBatches][inputBShape[1]][inputBShape[2]]);\n      poplibs_test::util::writeRandomValues(target, dataType, hostInputB, -1.0,\n                                            1.0, randomEngine);\n      poplibs_test::util::copy(target, hostInputB, dataType,\n                               rawHostInputB.get());\n    }\n  }\n\n  device.bind([&](const poplar::Device &d) {\n    engine.load(d);\n    if (!ignoreData) {\n      // upload\n      engine.run(0);\n    }\n\n    // convolve\n    engine.run(1);\n\n    if (!ignoreData) {\n      // download\n      engine.run(2);\n    }\n  });\n\n  bool matchesModel = true;\n  if (!ignoreData) {\n    uint64_t dim1, dim2;\n    if (runCholesky) {\n      dim1 = inputAShape[1];\n      dim2 = inputAShape[2];\n    } else {\n      dim1 = inputBShape[1];\n      dim2 = inputBShape[2];\n    }\n\n    boost::multi_array<double, 3> hostOutput(\n        boost::extents[numBatches][dim1][dim2]);\n    poplibs_test::util::copy(target, dataType, rawHostOutput.get(), hostOutput);\n\n    boost::multi_array<double, 3> hostOutputT(\n        boost::extents[numBatches][dim1][dim2]);\n    poplibs_test::util::copy(target, dataType, rawHostOutputT.get(),\n                             hostOutputT);\n\n    boost::multi_array<double, 3> modelOutput(\n        boost::extents[numBatches][dim1][dim2]);\n\n    boost::multi_array<double, 3> *testOutput;\n\n    if (runCholesky) {\n      testOutput = &hostInputAFilled;\n\n      if (lower)\n        poplibs_test::gemm::generalGroupedMatrixMultiply(\n            hostOutput, hostOutputT, modelOutput);\n      else\n        poplibs_test::gemm::generalGroupedMatrixMultiply(\n            hostOutputT, hostOutput, modelOutput);\n    } else {\n      testOutput = &hostInputB;\n\n      if (leftSide) {\n        poplibs_test::gemm::generalGroupedMatrixMultiply(hostInputA, hostOutput,\n                                                         modelOutput);\n      } else {\n        poplibs_test::gemm::generalGroupedMatrixMultiply(hostOutput, hostInputA,\n                                                         modelOutput);\n      }\n    }\n\n    const auto tolerance = dataType == poplar::HALF ? 0.3 : 0.001;\n    matchesModel = poplibs_test::util::checkIsClose(\n        \"AX vs B: \", *testOutput, modelOutput, tolerance, tolerance);\n  }\n\n  if (deviceType != DeviceType::Cpu && vm.count(\"profile\")) {\n    engine.printProfileSummary(\n        std::cout, poplar::OptionFlags{{\"showExecutionSteps\", \"true\"}});\n  }\n\n  if (!matchesModel) {\n    std::cerr << \"Validation failed\\n\";\n    return 1;\n  }\n\n  return 0;\n} catch (const poplar::graph_memory_allocation_error &e) {\n  std::cerr << e.what() << std::endl;\n\n  // this exit code has been marked as a \"skip\" for ctest.\n  return 77;\n}\n", "meta": {"hexsha": "77280576be1497b1d657048e9936f4b47b1f996c", "size": 13316, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tools/matrix_solver.cpp", "max_stars_repo_name": "graphcore/poplibs", "max_stars_repo_head_hexsha": "3fe5a3ecafe995eddb72675d1b4a7af8a622009e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 95.0, "max_stars_repo_stars_event_min_datetime": "2020-07-06T17:11:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T14:42:28.000Z", "max_issues_repo_path": "tools/matrix_solver.cpp", "max_issues_repo_name": "graphcore/poplibs", "max_issues_repo_head_hexsha": "3fe5a3ecafe995eddb72675d1b4a7af8a622009e", "max_issues_repo_licenses": ["MIT"], "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/matrix_solver.cpp", "max_forks_repo_name": "graphcore/poplibs", "max_forks_repo_head_hexsha": "3fe5a3ecafe995eddb72675d1b4a7af8a622009e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2020-07-15T12:32:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T14:58:45.000Z", "avg_line_length": 31.4056603774, "max_line_length": 80, "alphanum_fraction": 0.6167017122, "num_tokens": 3685, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.4734208967165172}}
{"text": "/*\n * IRIS Localization and Mapping (LaMa)\n *\n * Copyright (c) 2019-today, Eurico Pedrosa, University of Aveiro - Portugal\n * All rights reserved.\n * License: New BSD\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 University of Aveiro 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#include <Eigen/Cholesky>\n\n#include \"lama/nlls/gauss_newton.h\"\n\nlama::GaussNewton::Options::Options()\n{\n    eps1 = 1e-4;\n    eps2 = 1e-4;\n}\n\nlama::GaussNewton::GaussNewton(const Options& options)\n    : opt_(options)\n{}\n\nvoid lama::GaussNewton::reset()\n{\n    stop_ = false;\n}\n\nEigen::VectorXd lama::GaussNewton::step(const VectorXd& residuals, const MatrixXd& J)\n{\n    VectorXd g = J.transpose() * residuals;\n    chi2_ = residuals.squaredNorm();\n\n    double max_abs_g = g.lpNorm<Eigen::Infinity>();\n    if (max_abs_g < opt_.eps1){\n        stop_ = true;\n        return VectorXd::Zero(J.cols());\n    }\n\n    MatrixXd A = J.transpose() * J;\n    // Solve the system\n    VectorXd h = A.selfadjointView<Eigen::Lower>().ldlt().solve(-g);\n\n    double max_abs_h = h.lpNorm<Eigen::Infinity>();\n    if (max_abs_h < opt_.eps2)\n        stop_ = true;\n\n    return h;\n}\n\nbool lama::GaussNewton::valid(const VectorXd& residuals)\n{\n    if (stop_) return true;\n\n    double dF  = chi2_ - residuals.squaredNorm();\n    if (dF > 0){\n        return true;\n    }\n\n    stop_ = true;\n    return false;\n}\n\nbool lama::GaussNewton::stop()\n{\n    return stop_;\n}\n\n", "meta": {"hexsha": "19d8267c97aa969f4bc5764b377dc547088973a9", "size": 2842, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ros/src/iris_lama/src/nlls/gauss_newton.cpp", "max_stars_repo_name": "Legoho/PlatypOUs-Mobile-Robot-Platform", "max_stars_repo_head_hexsha": "449c84c515b418de8245edcdb7de0d248dd92e29", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 297.0, "max_stars_repo_stars_event_min_datetime": "2019-10-07T14:09:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T10:45:23.000Z", "max_issues_repo_path": "src/nlls/gauss_newton.cpp", "max_issues_repo_name": "lllray/iris_lama", "max_issues_repo_head_hexsha": "2e665154fc08b55b56302c89cfb76fef034d2a65", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 30.0, "max_issues_repo_issues_event_min_datetime": "2019-10-07T16:07:19.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T09:43:28.000Z", "max_forks_repo_path": "src/nlls/gauss_newton.cpp", "max_forks_repo_name": "lllray/iris_lama", "max_forks_repo_head_hexsha": "2e665154fc08b55b56302c89cfb76fef034d2a65", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 66.0, "max_forks_repo_forks_event_min_datetime": "2019-10-07T14:28:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T10:45:24.000Z", "avg_line_length": 30.5591397849, "max_line_length": 85, "alphanum_fraction": 0.699859254, "num_tokens": 684, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.4734208967165172}}
{"text": "/* ---------------------------------------------------------------------\n *\n * Copyright (C) 2018 - 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\n// Solve Laplacian using SIPG + mesh_loop + ScratchData\n\n#include <deal.II/numerics/data_out.h>\n#include <deal.II/base/function_parser.h>\n#include <deal.II/base/patterns.h>\n#include <deal.II/base/thread_management.h>\n\n#include <deal.II/dofs/dof_tools.h>\n\n#include <deal.II/fe/fe_dgq.h>\n\n#include <deal.II/grid/grid_generator.h>\n#include <deal.II/grid/grid_out.h>\n#include <deal.II/grid/grid_tools.h>\n#include <deal.II/grid/grid_tools_cache.h>\n#include <deal.II/grid/tria.h>\n#include <deal.II/grid/tria_accessor.h>\n#include <deal.II/grid/tria_iterator.h>\n\n#include <deal.II/lac/affine_constraints.h>\n#include <deal.II/lac/sparse_direct.h>\n\n#include <deal.II/meshworker/copy_data.h>\n#include <deal.II/meshworker/mesh_loop.h>\n#include <deal.II/meshworker/scratch_data.h>\n\n#include <deal.II/numerics/data_out.h>\n#include <deal.II/numerics/vector_tools.h>\n\n#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <unordered_map>\n\nusing namespace dealii;\nusing namespace MeshWorker;\n\ntemplate <int dim, int spacedim>\nvoid test()\n{\n  Triangulation<dim, spacedim> tria;\n  FE_DGQ<dim, spacedim> fe(1);\n  DoFHandler<dim, spacedim> dh(tria);\n\n  FunctionParser<spacedim> rhs_function(\"1\");\n  FunctionParser<spacedim> boundary_function(\"0\");\n\n  AffineConstraints<double> constraints;\n  constraints.close();\n\n  GridGenerator::hyper_cube(tria);\n  tria.refine_global(4);\n  tria.execute_coarsening_and_refinement();\n  dh.distribute_dofs(fe);\n\n  SparsityPattern sparsity;\n\n  {\n    DynamicSparsityPattern dsp(dh.n_dofs(), dh.n_dofs());\n    DoFTools::make_flux_sparsity_pattern(dh, dsp);\n    sparsity.copy_from(dsp);\n  }\n\n  SparseMatrix<double> matrix;\n  matrix.reinit(sparsity);\n\n  Vector<double> solution(dh.n_dofs());\n  Vector<double> rhs(dh.n_dofs());\n\n  QGauss<dim> quad(3);\n  QGauss<dim - 1> face_quad(3);\n\n  UpdateFlags cell_flags = update_values | update_gradients |\n                           update_quadrature_points | update_JxW_values;\n  UpdateFlags face_flags = update_values | update_gradients |\n                           update_quadrature_points |\n                           update_face_normal_vectors | update_JxW_values;\n\n  // Stabilization for SIPG\n  double gamma = 1;\n\n  using ScratchData = MeshWorker::ScratchData<dim, spacedim>;\n  using CopyData = MeshWorker::CopyData<1 + GeometryInfo<dim>::faces_per_cell,\n                                        1,\n                                        1 + GeometryInfo<dim>::faces_per_cell>;\n\n  ScratchData scratch(fe, quad, cell_flags, face_quad, face_flags);\n  CopyData copy(fe.dofs_per_cell);\n\n  auto cell = dh.begin_active();\n  auto endc = dh.end();\n\n  typedef decltype(cell) Iterator;\n\n  auto cell_worker =\n      [&rhs_function](const Iterator &cell, ScratchData &s, CopyData &c) {\n        const auto &fev = s.reinit(cell);\n        const auto &JxW = s.get_JxW_values();\n        const auto &p = s.get_quadrature_points();\n\n        c.local_dof_indices[0] = s.get_local_dof_indices();\n\n        for (unsigned int q = 0; q < p.size(); ++q)\n          for (unsigned int i = 0; i < fev.dofs_per_cell; ++i)\n          {\n            for (unsigned int j = 0; j < fev.dofs_per_cell; ++j)\n            {\n              c.matrices[0](i, j) +=\n                  fev.shape_grad(i, q) * fev.shape_grad(j, q) * JxW[q];\n            }\n            c.vectors[0](i) +=\n                fev.shape_value(i, q) * rhs_function.value(p[q]) * JxW[q];\n          }\n      };\n\n  auto boundary_worker = [gamma, &boundary_function](const Iterator &cell,\n                                                     const unsigned int &f,\n                                                     ScratchData &s,\n                                                     CopyData &c) {\n    const auto &fev = s.reinit(cell, f);\n    const auto &JxW = s.get_JxW_values();\n    const auto &p = s.get_quadrature_points();\n    const auto &n = s.get_normal_vectors();\n\n    for (unsigned int q = 0; q < p.size(); ++q)\n      for (unsigned int i = 0; i < fev.dofs_per_cell; ++i)\n      {\n        for (unsigned int j = 0; j < fev.dofs_per_cell; ++j)\n        {\n          c.matrices[0](i, j) +=\n              (-fev.shape_grad(i, q) * n[q] * fev.shape_value(j, q) +\n               -fev.shape_grad(j, q) * n[q] * fev.shape_value(i, q) +\n               gamma / cell->face(f)->diameter() * fev.shape_value(i, q) *\n                   fev.shape_value(j, q)) *\n              JxW[q];\n        }\n        c.vectors[0](i) +=\n            ((gamma / cell->face(f)->diameter() * fev.shape_value(i, q) -\n              fev.shape_grad(i, q) * n[q]) *\n             boundary_function.value(p[q])) *\n            JxW[q];\n      }\n  };\n\n  auto face_worker = [gamma](const Iterator &cell,\n                             const unsigned int &f,\n                             const unsigned int &sf,\n                             const Iterator &ncell,\n                             const unsigned int &nf,\n                             const unsigned int &nsf,\n                             ScratchData &s,\n                             CopyData &c) {\n    const auto &fev = s.reinit(cell, f, sf);\n    const auto &JxW = s.get_JxW_values();\n    const auto &nfev = s.reinit_neighbor(ncell, nf, nsf);\n\n    c.local_dof_indices[f + 1] = s.get_neighbor_dof_indices();\n\n    const auto &p = s.get_quadrature_points();\n    const auto &n = s.get_normal_vectors();\n    const auto &nn = s.get_neighbor_normal_vectors();\n\n    const double gh = gamma / cell->face(f)->diameter();\n\n    for (unsigned int q = 0; q < p.size(); ++q)\n      for (unsigned int i = 0; i < fev.dofs_per_cell; ++i)\n        for (unsigned int j = 0; j < fev.dofs_per_cell; ++j)\n        {\n          c.matrices[0](i, j) +=\n              (-.5 * fev.shape_grad(i, q) * n[q] * fev.shape_value(j, q) +\n               -.5 * fev.shape_value(i, q) * n[q] * fev.shape_grad(j, q) +\n               gh * fev.shape_value(i, q) * fev.shape_value(j, q)) *\n              JxW[q];\n\n          c.matrices[f + 1](i, j) +=\n              (-.5 * fev.shape_grad(i, q) * nn[q] * nfev.shape_value(j, q) +\n               -.5 * fev.shape_value(i, q) * n[q] * nfev.shape_grad(j, q) -\n               gh * fev.shape_value(i, q) * nfev.shape_value(j, q)) *\n              JxW[q];\n        }\n  };\n\n  auto copier = [&constraints, &matrix, &rhs](const CopyData &c) {\n    constraints.distribute_local_to_global(\n        c.matrices[0], c.vectors[0], c.local_dof_indices[0], matrix, rhs);\n\n    for (unsigned int f = 0; f < GeometryInfo<dim>::faces_per_cell; ++f)\n      constraints.distribute_local_to_global(c.matrices[1 + f],\n                                             c.local_dof_indices[0],\n                                             c.local_dof_indices[1 + f],\n                                             matrix);\n  };\n\n  mesh_loop(cell,\n            endc,\n            cell_worker,\n            copier,\n            scratch,\n            copy,\n            assemble_own_cells | assemble_boundary_faces |\n                assemble_own_interior_faces_both,\n            boundary_worker,\n            face_worker);\n\n  SparseDirectUMFPACK inv;\n  inv.initialize(matrix);\n\n  inv.vmult(solution, rhs);\n  constraints.distribute(solution);\n\n  {\n    DataOut<dim> data_out;\n    data_out.attach_dof_handler(dh);\n    data_out.add_data_vector(solution, \"solution\");\n    data_out.build_patches();\n    std::ofstream output(\"solution.vtu\");\n    data_out.write_vtu(output);\n  }\n  deallog << \"Linfty norm of solution \" << solution.linfty_norm() << std::endl;\n}\n\nint main()\n{\n  test<2, 2>();\n}", "meta": {"hexsha": "5d15d38b26d21f07b7695239c927f6552ee5bf1c", "size": 8081, "ext": "cc", "lang": "C++", "max_stars_repo_path": "cpp/06_second_strang_lemma_SIPG/sipg.cc", "max_stars_repo_name": "luca-heltai/advanced-fem", "max_stars_repo_head_hexsha": "7dc5416db07ee67410819e4f9680471548c6641a", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-03-13T22:07:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-12T07:59:37.000Z", "max_issues_repo_path": "cpp/06_second_strang_lemma_SIPG/sipg.cc", "max_issues_repo_name": "luca-heltai/advanced-fem", "max_issues_repo_head_hexsha": "7dc5416db07ee67410819e4f9680471548c6641a", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp/06_second_strang_lemma_SIPG/sipg.cc", "max_forks_repo_name": "luca-heltai/advanced-fem", "max_forks_repo_head_hexsha": "7dc5416db07ee67410819e4f9680471548c6641a", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.531120332, "max_line_length": 79, "alphanum_fraction": 0.5692364806, "num_tokens": 2087, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637612961506, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.4733371988533892}}
{"text": "#ifndef DEMO\n#define DEMO\n\n#include <Eigen/Dense>\n#include <algorithm>\n#include <iostream>\n\n#include \"MiniDnn/layer.h\"\n#include \"MiniDnn/layer/conv.h\"\n#include \"MiniDnn/layer/identity_block.h\"\n#include \"MiniDnn/layer/conv_block.h\"\n#include \"MiniDnn/layer/fully_connected.h\"\n#include \"MiniDnn/layer/ave_pooling.h\"\n#include \"MiniDnn/layer/max_pooling.h\"\n#include \"MiniDnn/layer/relu.h\"\n#include \"MiniDnn/layer/sigmoid.h\"\n#include \"MiniDnn/layer/softmax.h\"\n#include \"MiniDnn/loss.h\"\n#include \"MiniDnn/loss/mse_loss.h\"\n#include \"MiniDnn/loss/cross_entropy_loss.h\"\n#include \"MiniDnn/mnist.h\"\n#include \"MiniDnn/network.h\"\n#include \"MiniDnn/optimizer.h\"\n#include \"MiniDnn/optimizer/sgd.h\"\n#include \"Enclave.h\"\n#include \"Enclave_t.h\"  /* print_string */\n//#include <time.h>\n\n\nusing namespace std;\n\nclass RandData {\npublic:\n    Matrix train_data;\n    Matrix train_labels;\n    Matrix test_data;\n    Matrix test_labels;\n\n    RandData(int size) {\n        train_data = Matrix::Ones(224 * 224 * 3, size);\n        train_labels = Matrix::Ones(1, size);\n        test_data = Matrix::Ones(224 * 224 * 3, size);\n        test_labels = Matrix::Ones(1, size);\n    }\n};\n\nvoid ecall_ml_resnet50() {\n    // data\n//    MNIST dataset(\"/Users/rc/Study/Projects/mini-dnn/data/mnist/\");\n//    dataset.read();\n//    int n_train = dataset.train_data.cols();\n//    int dim_in = dataset.train_data.rows();\n//    std::cout << \"mnist train number: \" << n_train << std::endl;\n//    std::cout << \"mnist test number: \" << dataset.test_labels.cols() << std::endl;\n    RandData dataset(100);\n//    dataset.read();\n    int n_train = dataset.train_data.cols();\n    int dim_in = dataset.train_data.rows();\n    // dnn\n    Network dnn;\n\n//    // Conv\n//    // int channel_in, int height_in, int width_in, int channel_out, int height_kernel,\n//    // int width_kernel, int stride = 1, int pad_w = 0, int pad_h = 0\n\n\n    Layer *input_conv1 = new Conv(3, 224, 224, 64, 7, 7, 2, 3, 3);\n    Layer *input_relu1 = new ReLU;\n\n\n    Layer *b1_pool = new MaxPooling(64, 112, 112, 2, 2, 2);\n\n    dnn.add_layer(input_conv1);\n    dnn.add_layer(input_relu1);\n    dnn.add_layer(b1_pool);\n\n    //------------------------------------------------------------\n    Layer *s1_conv_block = new ConvBlock(64, 56, 56, 64,\n                                         64, 256, 3, 3, 1);\n    Layer *s1_id_block1 = new IdentityBlock(256, 56, 56, 64, 64, 3, 3);\n    Layer *s1_id_block2 = new IdentityBlock(256, 56, 56, 64, 64, 3, 3);\n\n    dnn.add_layer(s1_conv_block);\n    dnn.add_layer(s1_id_block1);\n    dnn.add_layer(s1_id_block2);\n\n    //------------------------------------------------------------\n\n    Layer *s2_conv_block = new ConvBlock(256, 56, 56, 128,\n                                         128, 512, 3, 3, 2);\n    Layer *s2_id_block1 = new IdentityBlock(512, 28, 28, 128, 128, 3, 3);\n    Layer *s2_id_block2 = new IdentityBlock(512, 28, 28, 128, 128, 3, 3);\n\n    dnn.add_layer(s2_conv_block);\n    dnn.add_layer(s2_id_block1);\n    dnn.add_layer(s2_id_block2);\n\n    //------------------------------------------------------------\n\n    Layer *s3_conv_block = new ConvBlock(512, 28, 28, 256,\n                                         256, 1024, 3, 3, 2);\n    Layer *s3_id_block1 = new IdentityBlock(1024, 14, 14, 256, 256, 3, 3);\n    Layer *s3_id_block2 = new IdentityBlock(1024, 14, 14, 256, 256, 3, 3);\n\n    dnn.add_layer(s3_conv_block);\n    dnn.add_layer(s3_id_block1);\n    dnn.add_layer(s3_id_block2);\n    //------------------------------------------------------------\n\n    Layer *s4_conv_block = new ConvBlock(1024, 14, 14, 512,\n                                         512, 2048, 3, 3, 2);\n    Layer *s4_id_block1 = new IdentityBlock(2048, 7, 7, 512, 512, 3, 3);\n    Layer *s4_id_block2 = new IdentityBlock(2048, 7, 7, 512, 512, 3, 3);\n\n\n    dnn.add_layer(s4_conv_block);\n    dnn.add_layer(s4_id_block1);\n    dnn.add_layer(s4_id_block2);\n    //------------------------------------------------------------\n\n\n    Layer *out_pool = new MaxPooling(2048, 7, 7, 7, 7, 1);\n\n//    Layer *b1_pool = new MaxPooling(64, 28, 28, 2, 2, 2);\n    Layer *fc_fc1 = new FullyConnected(out_pool->output_dim(), 1000);\n    Layer *softmax = new Softmax;\n\n    dnn.add_layer(out_pool);\n    dnn.add_layer(fc_fc1);\n    dnn.add_layer(softmax);\n    \n\n    // loss\n    Loss *loss = new CrossEntropy;\n    dnn.add_loss(loss);\n    // train & test\n    SGD opt(0.001, 5e-4, 0.9, true);\n    // SGD opt(0.001);\n    // const int n_epoch = 5;\n    const int total_rounds[4] = {1, 2, 3, 4};\n    const int batch_size = 20;\n    for (int idx = 0; idx < 4; idx++) {\n        int n_epoch = total_rounds[idx];\n        printf(\"total_rounds: %d\\n\", 5 * n_epoch);\n        ocall_start_clock();\n        for (int epoch = 0; epoch < n_epoch; epoch++) {\n            shuffle_data(dataset.train_data, dataset.train_labels);\n            for (int start_idx = 0; start_idx < n_train; start_idx += batch_size) {\n            // for(int start_idx=0, rounds=0; rounds < total_rounds; start_idx += batch_size){\n                int ith_batch = start_idx / batch_size;\n                Matrix x_batch = dataset.train_data.block(0, start_idx, dim_in,\n                                                          std::min(batch_size, n_train - start_idx));\n                Matrix label_batch = dataset.train_labels.block(0, start_idx, 1,\n                                                                std::min(batch_size, n_train - start_idx));\n                Matrix target_batch = one_hot_encode(label_batch, 1000);\n                // if (false && ith_batch % 10 == 1) {\n                //     std::cout << ith_batch << \"-th grad: \" << std::endl;\n                //     dnn.check_gradient(x_batch, target_batch, 10);\n                // }\n                \n                dnn.forward(x_batch);\n                // ocall_end_clock(\"Forward: %f   \");\n                \n                // ocall_start_clock();\n                dnn.backward(x_batch, target_batch);\n\n                \n    //            // display\n    //            if (ith_batch % 2 == 0) {\n    //                //std::cout << ith_batch << \"-th batch, loss: \" << dnn.get_loss() << std::endl;\n    //                printf(\"%d-th batch, loss: %f\\n\", ith_batch, dnn.get_loss());\n    //            }\n                // optimize\n                dnn.update(opt);\n                // rounds++;\n            }\n        }\n        ocall_end_clock(\"total: %f\\n\");\n\n// //        // test\n//         dnn.forward(dataset.test_data);\n//         float acc = compute_accuracy(dnn.output(), dataset.test_labels);\n        // std::cout << std::endl;\n        // std::cout << epoch + 1 << \"-th epoch, test acc: \" << acc << std::endl;\n        // std::cout << std::endl;\n    }\n}\n\n\n\n#endif", "meta": {"hexsha": "4c946010a4a62a7e1929b9a70b29e28a4421afa2", "size": 6680, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Enclave/resnet50.cpp", "max_stars_repo_name": "zeyu-zh/TrustFL", "max_stars_repo_head_hexsha": "9e05a7e160bbf4fa1e7a426767f69158ea89b22d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2020-09-11T18:06:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T11:16:59.000Z", "max_issues_repo_path": "Enclave/resnet50.cpp", "max_issues_repo_name": "zeyu-zh/TrustFL", "max_issues_repo_head_hexsha": "9e05a7e160bbf4fa1e7a426767f69158ea89b22d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Enclave/resnet50.cpp", "max_forks_repo_name": "zeyu-zh/TrustFL", "max_forks_repo_head_hexsha": "9e05a7e160bbf4fa1e7a426767f69158ea89b22d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-01-29T02:52:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-22T09:10:56.000Z", "avg_line_length": 34.9738219895, "max_line_length": 107, "alphanum_fraction": 0.5431137725, "num_tokens": 1919, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.47333719291440945}}
{"text": "#include <iostream>\n#include <armadillo>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <math.h>\n#include <iomanip>\n\n\nusing namespace std;\nusing namespace arma;\n\nstruct GMS\n{\n    int G,M,S;\n\n    GMS(int,int,int);\n    double gdec();\n    double rad();\n};\n\nstruct topoPoint\n{\n    double Hz,Ze,Di;\n    vec3 XYZ;\n    bool rad;\n\n    topoPoint(double,double,double,bool);\n    void cart();\n    void translate(vec3 tvec);\n    void Rotate(mat R);\n\n};\n\n\nGMS::GMS (int g,int m,int s)\n{\n    G=g;\n    M=m;\n    S=s;\n}\n\ndouble GMS::gdec ()\n{\n    return double(G)+ (double(M)/60) + (double(S)/3600);\n}\n\ndouble GMS::rad()\n{\n    double radd = gdec()  * (datum::pi/180);\n    return radd;\n}\n\nstruct SMMTleverARM\n{\n//to handle with the base from the file\n    vector<vector<string>> data;\n    vector<vector<GMS>>  hor,zen;\n    vector<vector<double>> dists;\n\n//the arbitrary-frame surveyed points\n    vector<vector<topoPoint>> points;\n\n//the planes of the process (coefficients a,b,c,d)\n    vec4 Hplan,Vplan;\n    vec4 CEin,CEout,CDin,CDout;\n//aux1 is parallel to Hplan\n\n//matrices containing points\n    mat ptsH,ptsV; //at the sides of the IMU\n    mat ptsCEin,ptsCEout,ptsCDin,ptsCDout; //points on the parallel circular patterns, on the lens of the cameras\n    mat ptsOnCEin,ptsOnCEout,ptsOnCDin,ptsOnCDout; //adjusted points\n\n//rotation matrices\n    mat Rot1 = eye<mat>(3,3);\n\n//the principal vectors, to define the cannonical system\n    vec3 u,v,w; //u for x,v for y,w for z\n\n//the axis direction of each camera system, in the same convention of the IMU\n    vec3 xE,yE,zE,xD,yD,zD;\n\n//the axis of each camera system, with the z axis pointing backwards\n    vec3 Xe,Ye,Ze,Xd,Yd,Zd;\n\n//the difference between the antena top and the center of phase\n    vec3 PhC = {0,0,-0.0071};\n\n//the lever-arm vectors\n    vec3 antLA,LcamLA,RcamLA;\n\n//temporary, and auxiliar vectors\n    vec3 tempE,tempD,aux1e,aux1d,aux_E0,aux_D0;\n\n//the boresight matrices\n    mat Rimu_LC = eye(3,3),Rimu_RC = eye(3,3),Rimu_LC2 = eye(3,3),Rimu_RC2 = eye(3,3),Rimu_LC3 = eye(3,3),Rimu_RC3 = eye(3,3);\n\n//center of the IMU, the mark on the H plane, the mark on the v plane\n    vec3 imuC,Hm,Vm;\n\n\n    double planesAngle;\n\n    SMMTleverARM (string fileName);\n\n\n    vector<vector<string>> readLAFile(string filename);\n\n//the member functions\n    void horiz();\n    void zenit();\n    void distanc();\n    void avgOBS();\n    void pointsPrint(string filename);\n    void translateAll(vec3 tvec);\n    void rotAll (mat R);\n    void report();\n\n};\n\nvec3 onPlanePoint(vec4 plCoef,double x,double y);\n\n//all the function propotypes:\ndouble pdpiH(double,double);\ndouble pdpiV(double,double);\nvoid TptMat (mat *M,vec Tvec);\nvoid RptMat (mat *M,mat R);\n\nvec4 plane3points(vec3 u,vec3 v,vec3 w);\n\nmat topoPointsMat (vector<topoPoint> points,uword first,uword last);\n\nvec4 parallelPlane(vec4 plane1,vec3 pointOnPlane);\n\nvec3 ProjPtOrtPlane(vec3 pt2Proj,vec3 plNorm,vec3 ptOnPlane);\n\nvec4 leasqPlane2(vector<topoPoint> pointList,mat *ptOnPlane,string repNam,uword ijpt=0)\n{\n    vec4 res,Xo;\n    mat data,P,Pinf,A,B,M,mvcXa,mvcLa,mvcV,mvcW;\n    vec Lb,W,X,Xa,K,V,La;\n    double vp;\n\n    if (pointList.size() >= 3)\n    {\n        Xo = plane3points(pointList.at(0).XYZ,pointList.at(1).XYZ,pointList.at(2).XYZ);\n    }\n\n\n    Pinf = eye(3,3)*10000;\n\n    if (pointList.size() < 3)\n    {\n        res = {0,0,1,0};\n    }\n    else if (pointList.size() == 3)\n    {\n        res = Xo;\n    }\n    else\n    {\n        ofstream out(repNam);\n\n\n        //vetor Lb\n        data = ones(pointList.size(),3);\n\n        for (uword i0 = 0; i0 < pointList.size(); i0++)\n        {\n            data.row(i0) = pointList.at(i0).XYZ.t();\n        }\n\n        Lb = vectorise(data.t());\n\n        //matriz dos pesos\n        P = eye(Lb.n_elem,Lb.n_elem);\n        if (ijpt != 0)\n        {\n            //em caso de que haja um ponto a ser injuncionado\n//        P.submat(ijpt*3-2,ijpt*3-2,ijpt*3,ijpt*3) = Pinf;\n            P.submat(ijpt*3-3,ijpt*3-3,ijpt*3-1,ijpt*3-1) = Pinf;\n        }\n        //matriz jacobiana A (parametros)\n\n        A = ones<mat>(pointList.size(),4);\n\n        for (uword i = 0; i < pointList.size(); i++)\n        {\n            A(i,0)=data(i,0);\n            A(i,1)=data(i,1);\n            A(i,2)=data(i,2);\n        }\n\n        //matriz jacobiana B (observacoes)\n\n        B = zeros<mat>(pointList.size(),Lb.n_elem);\n\n        uword j = 0;\n        for (uword i2 = 0; i2 < pointList.size(); i2++)\n        {\n            B(i2,0+j)=Xo(0);\n            B(i2,1+j)=Xo(1);\n            B(i2,2+j)=Xo(2);\n\n            j += 3;\n        }\n\n        W = zeros<vec>(pointList.size());\n\n        for (uword i3 = 0; i3 < pointList.size(); i3++)\n        {\n            W(i3) = dot(A.row(i3),Xo);\n        }\n\n        M = B * P.i() * B.t();\n\n        X = - inv(A.t()*M.i()*A)*(A.t()*M.i()*W);\n\n        Xa = Xo + X;\n\n        K = -M.i()*(A*X+W);\n\n        V = P.i() * B.t() * K;\n\n        La = Lb+V;\n\n        *ptOnPlane = trans(reshape(La,3,pointList.size()));\n\n        vp = as_scalar( V.t() * P * V / (Lb.n_elem - Xo.n_elem) );\n\n        mvcXa = vp * inv(A.t()*M.i()*A);\n\n        mvcLa = vp*(inv(P)+inv(P)*B.t()*inv(M)*A*inv(A.t()*inv(M)*A)*A.t()*inv(M)*B*inv(P)-inv(P)*B.t()*inv(M)*B*inv(P));\n\n        mvcV  = vp*P.i()-mvcLa;\n\n        mvcW  = vp*M;\n\n        out.precision(30);\n\n\n        res = Xa;\n\n//        Xo.raw_print(out,\"Xo\");\n//        X.raw_print(out,\"X\");\n//        Xa.raw_print(out,\"Xa:\");\n//        res.raw_print(out,\" b \");\n\n//        out <<\"Xo+X: \"<<endl<<std::setprecision(30)<< Xo+X<<endl;\n        //normalizing the plane equations\n        res.rows(0,2) = normalise(Xa.rows(0,2));\n        res(3) = - dot(normalise(Xa.rows(0,2)),La.rows(0,2));\n\n//            res.print(out,\" a \");\n\n        data.print(out,\"dados de entrada: \");\n        out<<endl;\n\n        res.print(out,\"coeficientes do plano estimado: \");\n        out<<endl;\n\n        V.print(out,\"res\u00edduos: \");\n        out<<endl;\n\n        La.print(out,\"La:\");\n        out<<endl;\n\n        out << \"var. posteriori: \" << vp << endl<<endl;\n\n        mvcXa.print(out,\"MVC dos parametros ajustados\");\n        out<<endl;\n\n        mvcLa.print(out,\"MVC das observa\u00e7\u00f5es ajustadas\");\n        out<<endl;\n\n    }\n//cout<< res<<endl;\n    return res;\n}\n\nvoid leasq2ParallelPlanes(vec4 *plane1,vec4 *plane2,mat points1,mat points2,mat *ptOnPlane1,mat *ptOnPlane2,string repNam,uword n=5,double e=.000001)\n{\n    vec5 Xo,X,Xa;\n    mat data,P,A,B,M,mvcXa,mvcLa,mvcV,mvcW,ptsOnPlanes;\n    vec Lb,W,K,V,La,temp5,temp6;\n    double vp;\n    vec4 temp1,temp2,temp3,temp4;\n    temp1.ones();\n    temp2.zeros();\n    uword iter;\n\n    ofstream out(repNam);\n\n    Xo.rows(0,3) = plane3points(trans(points1.row(0)),trans(points1.row(1)),trans(points1.row(2)) );\n    Xo(4) = - dot(Xo.rows(0,2),points2.row(0));\n\n    //vetor Lb\n\n    data = join_vert(points1,points2);\n\n    Lb = vectorise(data.t());\n\n    //matriz dos pesos\n    P = eye(Lb.n_elem,Lb.n_elem);\n\n    //matriz jacobiana A (parametros)\n\n    A = zeros<mat>(data.n_rows,Xo.n_elem);\n    B = zeros<mat>(data.n_rows,Lb.n_elem);\n    W = zeros<vec>(data.n_rows);\n\n    A.submat(0,0,data.n_rows-1,data.n_cols-1) = data;\n\n\n    for (uword i = 0; i < data.n_rows; i++)\n    {\n        if (i < points1.n_rows)\n        {\n            A(i,3) = 1;\n        }\n        else\n        {\n            A(i,4) = 1;\n        }\n    }\n\n    for(uword it = 0; it < n; it ++)\n    {\n\n\n        uword j = 0;\n        for (uword i2 = 0; i2 < data.n_rows; i2++)\n        {\n            B(i2,0+j)=Xo(0);\n            B(i2,1+j)=Xo(1);\n            B(i2,2+j)=Xo(2);\n\n            j += 3;\n\n            temp1.rows(0,2) = trans( data.row(i2) );\n            temp2.rows(0,2) = Xo.rows(0,2);\n\n            if(i2 < points1.n_rows)\n            {\n                temp2(3)=Xo(3);\n            }\n            else\n            {\n                temp2(3)=Xo(4);\n            }\n\n            W(i2) = dot(temp1,temp2);\n        }\n\n        M = B * P.i() * B.t();\n\n        X = - inv(A.t()*M.i()*A)*(A.t()*M.i()*W);\n\n        Xa = Xo + X;\n\n        Xo = Xa;\n\n        iter = it;\n\n        if (arma::max(arma::abs(X)) < e)\n        {\n            break;\n        }\n\n    }\n\n    K = -M.i()*(A*X+W);\n\n    V = P.i() * B.t() * K;\n\n    La = Lb+V;\n\n    ptsOnPlanes = trans(reshape(La,data.n_cols,data.n_rows));\n\n    *ptOnPlane1 = ptsOnPlanes.rows(0,points1.n_rows-1);\n\n    *ptOnPlane2 = ptsOnPlanes.rows(points1.n_rows,data.n_rows-1);\n\n    temp3.rows(0,2) =   normalise(Xa.rows(0,2));\n    temp3(3)= - dot(La.rows(0,2),normalise(Xa.rows(0,2)));\n\n    temp4 = temp3;\n    temp4(3)= - dot(La.rows(La.n_elem-3,La.n_elem-1),normalise(Xa.rows(0,2)));\n\n    *plane1 = temp3;\n    *plane2 = temp4;\n\n    vp = as_scalar( V.t() * P * V / (Lb.n_elem - Xo.n_elem) );\n\n    mvcXa = vp * inv(A.t()*M.i()*A);\n\n    mvcLa = vp*(inv(P)+inv(P)*B.t()*inv(M)*A*inv(A.t()*inv(M)*A)*A.t()*inv(M)*B*inv(P)-inv(P)*B.t()*inv(M)*B*inv(P));\n\n    mvcV  = vp*P.i()-mvcLa;\n\n    mvcW  = vp*M;\n\n    out.precision(20);\n\n    points1.raw_print(out,\"dados de entrada (primeiro plano): \");\n    out<<endl;\n\n    points2.raw_print(out,\"dados de entrada (segundo plano): \");\n    out<<endl;\n\n    out << iter <<\" itera\u00e7\u00f5es necess\u00e1rias\" <<endl<<endl;\n\n    Xa.raw_print(out,\" vetor Xa (pr\u00e9-normaliza\u00e7\u00e3o)\");\n    out<<endl;\n\n    temp3.raw_print(out,\"coeficientes do primeiro plano estimado: \");\n    out<<endl;\n\n    temp4.raw_print(out,\"coeficientes do segundo plano estimado: \");\n    out<<endl;\n\n    V.raw_print(out,\"res\u00edduos: \");\n    out<<endl;\n\n    ptsOnPlanes.raw_print(out,\"La:\");\n    out<<endl;\n\n    out << \"var. posteriori: \" << vp << endl<<endl;\n\n    mvcXa.raw_print(out,\"MVC dos parametros ajustados\");\n    out<<endl;\n\n    mvcLa.raw_print(out,\"MVC das observa\u00e7\u00f5es ajustadas\");\n    out<<endl;\n\n\n}\n\nstruct Sphere\n{\n    vec3 center;\n    double r;\n    mat onSpherePts;\n\n    Sphere(mat points,string repNam,uword n=20,double e=.000001);\n};\n\nSphere::Sphere(mat data,string repNam,uword n,double e)\n{\n    vec4 Xo,X,Xa;\n    mat P,A,B,M,mvcXa,mvcLa,mvcV,mvcW,ptsOnPlanes;\n    vec Lb,W,K,V,La,temp5,temp6,aux;\n    double vp;\n    vec4 temp1,temp2,temp3,temp4;\n    temp1.ones();\n    temp2.zeros();\n    uword iter;\n\n    ofstream out(repNam);\n\n    aux=zeros(data.n_rows);\n\n    for (uword i = 0; i < aux.n_rows; i++)\n    {\n        aux(i) = norm(data.row(i) - mean(data));\n    }\n\n\n    Xo.rows(1,3) = trans(mean(data));\n    Xo(0) = mean(aux);\n\n    //vetor Lb\n\n    Lb = vectorise(data.t());\n\n    //matriz dos pesos\n    P = eye(Lb.n_elem,Lb.n_elem);\n\n    //matriz jacobiana A (parametros)\n\n    A = zeros<mat>(data.n_rows,Xo.n_elem);\n    B = zeros<mat>(data.n_rows,Lb.n_elem);\n    W = zeros<vec>(data.n_rows);\n\n    for(uword it = 0; it < n; it ++)\n    {\n\n\n        uword j = 0;\n        for (uword i2 = 0; i2 < data.n_rows; i2++)\n        {\n            A(i2,0) = - 2 * Xo(0);\n\n            A(i2,1) = 2 * (Xo(1) - data(i2,0));\n            A(i2,2) = 2 * (Xo(2) - data(i2,1));\n            A(i2,3) = 2 * (Xo(3) - data(i2,2));\n\n            B(i2,j)  = - 2 * (Xo(1) - data(i2,0));\n            B(i2,1+j)= - 2 * (Xo(2) - data(i2,1));\n            B(i2,2+j)= - 2 * (Xo(3) - data(i2,2));\n\n            j += 3;\n\n\n            W(i2) = std::pow((data(i2,0) - Xo(1)),2) + std::pow((data(i2,1) - Xo(2)),2) +\n                    std::pow((data(i2,2) - Xo(3)),2) - std::pow(Xo(0),2);\n        }\n\n        M = B * P.i() * B.t();\n\n        X = - inv(A.t()*M.i()*A)*(A.t()*M.i()*W);\n\n        Xa = Xo + X;\n\n        Xo = Xa;\n\n        iter = it;\n\n        if (arma::max(arma::abs(X)) < e)\n        {\n            break;\n        }\n\n    }\n\n    K = -M.i()*(A*X+W);\n\n    V = P.i() * B.t() * K;\n\n    La = Lb+V;\n\n    onSpherePts = trans(reshape(La,data.n_cols,data.n_rows));\n\n    vp = as_scalar( V.t() * P * V / (Lb.n_elem - Xo.n_elem) );\n\n    mvcXa = vp * inv(A.t()*M.i()*A);\n\n    mvcLa = vp*(inv(P)+inv(P)*B.t()*inv(M)*A*inv(A.t()*inv(M)*A)*A.t()*inv(M)*B*inv(P)-inv(P)*B.t()*inv(M)*B*inv(P));\n\n    mvcV  = vp*P.i()-mvcLa;\n\n    mvcW  = vp*M;\n\n    out.precision(20);\n\n    data.raw_print(out,\"dados de entrada :\");\n    out<<endl;\n\n    out << iter <<\" itera\u00e7\u00f5es necess\u00e1rias\" <<endl<<endl;\n\n    Xa.raw_print(out,\"parametros ajustados (r,XC,YC,ZC)\");\n    out<<endl;\n\n    V.raw_print(out,\"res\u00edduos: \");\n    out<<endl;\n\n    La.raw_print(out,\"La:\");\n    out<<endl;\n\n    out << \"var. posteriori: \" << vp << endl<<endl;\n\n    mvcXa.raw_print(out,\"MVC dos parametros ajustados\");\n    out<<endl;\n\n    mvcLa.raw_print(out,\"MVC das observa\u00e7\u00f5es ajustadas\");\n    out<<endl;\n\n    //assignment to the object variables\n    r = Xo(0);\n    center = Xo.rows(1,3);\n}\n\nvector<vector<string>> SMMTleverARM::readLAFile(string filename)\n{\n//to read a file of the raw data of the Lever Arm surveying\n    ifstream in(filename);\n    vector<vector<string>> res;\n    vector<string> A,B,C,D,E;\n//to control\n    int state = 0;\n    string line;\n\n    while (std::getline(in,line))\n    {\n        if (line.find(\"COD:[A\") != -1)\n        {\n            state = 1;\n            continue;\n        }\n        if (line.find(\"COD:[B\") != -1)\n        {\n            state = 2;\n            continue;\n        }\n        if (line.find(\"COD:[C\") != -1)\n        {\n            state =3 ;\n            continue;\n        }\n        if (line.find(\"COD:[D\") != -1)\n        {\n            state =4 ;\n            continue;\n        }\n        if (line.find(\"COD:[E\") != -1)\n        {\n            state =5 ;\n            continue;\n        }\n\n        if (state == 1)\n        {\n            A.push_back(line);\n            //cout << stoi(line.substr(23,3))<<endl;\n        }\n        if (state == 2)\n        {\n            B.push_back(line);\n        }\n        if (state == 3)\n        {\n            C.push_back(line);\n        }\n        if (state ==4 )\n        {\n            D.push_back(line);\n        }\n        if (state == 5)\n        {\n            E.push_back(line);\n        }\n    }\n\n    res.push_back(A);\n    res.push_back(B);\n    res.push_back(C);\n    res.push_back(D);\n    res.push_back(E);\n    //cout<<A.size()<<\" \"<< B.size()<<\" \"<<C.size()<<\" \"<<D.size()<<\" \"<<E.size()<<endl;\n    //cout<<res.size();\n\n    return res;\n}\n\nSMMTleverARM::SMMTleverARM (string fileName)\n{\n// the constructor, all the modifying functions must have their calls here.\n    data = readLAFile(fileName);\n    horiz();\n    zenit();\n    distanc();\n    avgOBS();\n\n//the two planes\n    Vplan = leasqPlane2(points.at(1),&ptsV,\"plano_vert.txt\",2);\n    Hplan = leasqPlane2(points.at(2),&ptsH,\"plano_hor.txt\",2);\n//the angle between them\n    planesAngle = std::acos(dot(Vplan.rows(0,2),Hplan.rows(0,2))) * (180/datum::pi);\n\n//the marks on the IMU surface\n    Hm = trans(ptsH.row(2));\n    Vm = trans(ptsV.row(2));\n\n//the normal of the Hplan, is also the third direction (w),\n//but at first, is needed some test\n    w = Hplan.rows(0,2);\n    if(w(2)<0) //the z component, needs to be positive, due to the z axis of the total station\n    {\n        w *= -1;\n    }\n\n//the aux1 plane\n//aux1.rows(0,2) = w;\n//aux1(3) = - dot(w,Vm);\n\n//IMU center with the intersection of the plane (aux1) and the line (point Hm and direction w)\n//imuC = Hm + (dot(w,(Vm-Hm)))* w; //do not delete the old implementation\n    imuC = ProjPtOrtPlane(Hm,w,Vm);\n\n//the first principal direction (u)\n    u = normalise(Vm - imuC);\n\n//the second principal direction(v)\n    v = normalise(cross(w,u));\n\n//first, translating the origin to the calculated center of the IMU\n    TptMat(&ptsH,-imuC);\n    TptMat(&ptsV,-imuC);\n    translateAll(-imuC);\n    pointsPrint(\"points1.txt\");\n\n//composing the first rotation matrice\n    Rot1.col(0)=u;\n    Rot1.col(1)=v;\n    Rot1.col(2)=w;\n    Rot1 = Rot1.t();\n\n//rotating all to the imu BF\n    RptMat(&ptsH,Rot1);\n    RptMat(&ptsV,Rot1);\n    rotAll(Rot1);\n    pointsPrint(\"points2.txt\");\n\n//imuC += -imuC;\n\n//creating matrices with the points, from topoPoints;\n    ptsCDin  = topoPointsMat(points.at(3),0,4);\n    ptsCDout = topoPointsMat(points.at(3),5,9);\n    ptsCEin  = topoPointsMat(points.at(4),0,4);\n    ptsCEout = topoPointsMat(points.at(4),5,9);\n\n//the pair of parallel planes, one for each camera\n    leasq2ParallelPlanes(&CDin,&CDout,ptsCDin,ptsCDout,&ptsOnCDin,&ptsOnCDout,\"RcamPlanes.txt\");\n    leasq2ParallelPlanes(&CEin,&CEout,ptsCEin,ptsCEout,&ptsOnCEin,&ptsOnCEout,\"LcamPlanes.txt\");\n\n//creating a sphere for each camera, to measure the center\n    Sphere Rsphere(join_vert(ptsOnCDin,ptsOnCDout),\"Rsphere.txt\");\n    Sphere Lsphere(join_vert(ptsOnCEin,ptsOnCEout),\"Lsphere.txt\");\n\n//Y of each camera direction (with same convention)\n//due to the IMU bf and the cameras position, the y component needs to be positive\n// to point forward the camera axis\n\n    yE = normalise(CEin.rows(0,2));\n    if (yE(1) < 0 )\n    {\n        yE *= -1;\n    }\n\n    yD = normalise(CDin.rows(0,2));\n    if (yD(1) < 0 )\n    {\n        yD *= -1;\n    }\n\n//yD.print();cout<<endl;\n//yE.print();cout<<endl;\n\n//we'll need points perfectly on the plane, and to have this guarantee:\n//each one are obtained by the plane equation, with z=f(x,y)\n    aux1d = onPlanePoint(CDin,ptsOnCDin(ptsOnCDin.n_rows-1,0),ptsOnCDin(ptsOnCDin.n_rows-1,1));\n    aux1e = onPlanePoint(CEin,ptsOnCEin(ptsOnCEin.n_rows-1,0),ptsOnCEin(ptsOnCEin.n_rows-1,1));\n\n    aux_D0 = onPlanePoint(CDin,ptsOnCDin(0,0),ptsOnCDin(0,1));\n    aux_E0 = onPlanePoint(CEin,ptsOnCEin(0,0),ptsOnCEin(0,1));\n\n//projecting the center of spheres on the inner plane of the rings on the camera lenses\n    tempD = ProjPtOrtPlane(Rsphere.center,yD,aux1d);\n    tempE = ProjPtOrtPlane(Lsphere.center,yE,aux1e);\n\n//calculating the z direction, for each camera\n    zE = normalise(aux_E0 - tempE);\n    zD = normalise(aux_D0 - tempD);\n\n//and, finally the x direction\n    xE = normalise(cross(yE,zE));\n    xD = normalise(cross(yD,zD));\n\n    vec3 Xe2,Ye2,Ze2,Xd2,Yd2,Zd2;\n\n//////formerly:\n//////we can describe the axes in the camera conventional convention (z axis pointing from the CP to the focal plane)\n////Xe = xE;Ye = zE;Ze = -yE;\n////Xd = xD;Yd = zD;Zd = -yD;\n\n//we can describe the axes in the camera modern convention (z axis pointing from the principle point to CP)\n    Xe = xE;\n    Ye = -zE;\n    Ze = yE;\n\n    Xd = xD;\n    Yd = -zD;\n    Zd = yD;\n\n    //conventional convention\n    Xe2 = xE;Ye2 = zE;Ze2 = -yE;\n    Xd2 = xD;Yd2 = zD;Zd2 = -yD;\n\n\n//with the axis, we can have the boresight matrices:\n    //first with the same convention of the IMU:\n    Rimu_LC2.row(0) = trans(xE);\n    Rimu_LC2.row(1) = trans(yE);\n    Rimu_LC2.row(2) = trans(zE);\n\n    Rimu_RC2.row(0) = trans(xD);\n    Rimu_RC2.row(1) = trans(yD);\n    Rimu_RC2.row(2) = trans(zD);\n\n    //with the camera modern convention\n    Rimu_LC.row(0) = trans(Xe);\n    Rimu_LC.row(1) = trans(Ye);\n    Rimu_LC.row(2) = trans(Ze);\n\n    Rimu_RC.row(0) = trans(Xd);\n    Rimu_RC.row(1) = trans(Yd);\n    Rimu_RC.row(2) = trans(Zd);\n\n    //then with the camera conventional convention\n    Rimu_LC3.row(0) = trans(Xe2);\n    Rimu_LC3.row(1) = trans(Ye2);\n    Rimu_LC3.row(2) = trans(Ze2);\n\n    Rimu_RC3.row(0) = trans(Xd2);\n    Rimu_RC3.row(1) = trans(Yd2);\n    Rimu_RC3.row(2) = trans(Zd2);\n\n//now, the lever-arm\n\n    //antenna lever-arm: just the point at the antena top, and the offset from there to the PhC\n    antLA = (points.at(0).at(0).XYZ) + PhC;\n\n    //the lever-arm of the two cameras:\n    RcamLA = Rsphere.center;\n    LcamLA = Lsphere.center;\n\n    report();\n}\n\n\nvoid SMMTleverARM::avgOBS()\n{\n    vector<topoPoint> temp;\n\n    double hA,zA,dA=0,hB,zB,dB,hC,zC,dC,hD,zD,dD,hE,zE,dE,hF,zF,dF,hG,zG,dG,hH,zH,dH,hI,zI,dI,hJ,zJ,dJ;\n\n//std::setprecision(8);\n    for (unsigned int i = 0; i < hor.size(); i++)\n    {\n        if (i == 0)\n        {\n            hA = (pdpiH(hor[i][0].gdec(),hor[i][1].gdec()) +\n                  pdpiH(hor[i][2].gdec(),hor[i][3].gdec()) +\n                  pdpiH(hor[i][4].gdec(),hor[i][5].gdec())) / 3;\n\n            zA = (pdpiV(zen[i][0].gdec(),zen[i][1].gdec()) +\n                  pdpiV(zen[i][2].gdec(),zen[i][3].gdec()) +\n                  pdpiV(zen[i][4].gdec(),zen[i][5].gdec())) / 3;\n\n            for (unsigned int j = 0; j < dists[i].size(); j++)\n            {\n                dA += dists[i][j]/6;\n            }\n\n            topoPoint ANT(hA,zA,dA,false);\n            temp.push_back(ANT);\n\n            //cout <<hA<<\" \"<<zA<<\" \"<<dA<<endl;\n            //cout <<hA<<\" \"<<zA<<\" \"<<dA<<endl;\n        }\n        if (i == 1)\n        {\n            hA = (pdpiH(hor[i][0].gdec(),hor[i][5].gdec()) +\n                  pdpiH(hor[i][10].gdec(),hor[i][15].gdec())) / 2;\n\n            hB = (pdpiH(hor[i][1].gdec(),hor[i][6].gdec()) +\n                  pdpiH(hor[i][11].gdec(),hor[i][16].gdec())) / 2;\n\n            hC = (pdpiH(hor[i][2].gdec(),hor[i][7].gdec()) +\n                  pdpiH(hor[i][12].gdec(),hor[i][17].gdec())) / 2;\n\n            hD = (pdpiH(hor[i][3].gdec(),hor[i][8].gdec()) +\n                  pdpiH(hor[i][13].gdec(),hor[i][18].gdec())) / 2;\n\n            hE = (pdpiH(hor[i][4].gdec(),hor[i][9].gdec()) +\n                  pdpiH(hor[i][14].gdec(),hor[i][19].gdec())) / 2;\n\n\n\n            zA = (pdpiV(zen[i][0].gdec(),zen[i][5].gdec()) +\n                  pdpiV(zen[i][10].gdec(),zen[i][15].gdec())) / 2;\n\n            zB = (pdpiV(zen[i][1].gdec(),zen[i][6].gdec()) +\n                  pdpiV(zen[i][11].gdec(),zen[i][16].gdec())) / 2;\n\n            zC = (pdpiV(zen[i][2].gdec(),zen[i][7].gdec()) +\n                  pdpiV(zen[i][12].gdec(),zen[i][17].gdec())) / 2;\n\n            zD = (pdpiV(zen[i][3].gdec(),zen[i][8].gdec()) +\n                  pdpiV(zen[i][13].gdec(),zen[i][18].gdec())) / 2;\n\n            zE = (pdpiV(zen[i][4].gdec(),zen[i][9].gdec()) +\n                  pdpiV(zen[i][14].gdec(),zen[i][19].gdec())) / 2;\n\n\n            dA = (dists[i][0]+dists[i][5]+dists[i][10]+dists[i][15]) / 4;\n\n            dB = (dists[i][1]+dists[i][6]+dists[i][11]+dists[i][16]) / 4;\n\n            dC = (dists[i][2]+dists[i][7]+dists[i][12]+dists[i][17]) / 4;\n\n            dD = (dists[i][3]+dists[i][8]+dists[i][13]+dists[i][18]) / 4;\n\n            dE = (dists[i][4]+dists[i][9]+dists[i][14]+dists[i][19]) / 4;\n\n\n            topoPoint A(hA,zA,dA,false);\n            temp.push_back(A);\n            topoPoint B(hB,zB,dB,false);\n            temp.push_back(B);\n            topoPoint C(hC,zC,dC,false);\n            temp.push_back(C);\n            topoPoint D(hD,zD,dD,false);\n            temp.push_back(D);\n            topoPoint E(hE,zE,dE,false);\n            temp.push_back(E);\n\n//                                cout <<hA<<\" \"<<zA<<\" \"<<dA<<endl;\n\n\n        }\n        if (i == 2)\n        {\n            hA = (pdpiH(hor[i][0].gdec(),hor[i][5].gdec()) +\n                  pdpiH(hor[i][10].gdec(),hor[i][15].gdec())) / 2;\n\n            hB = (pdpiH(hor[i][1].gdec(),hor[i][6].gdec()) +\n                  pdpiH(hor[i][11].gdec(),hor[i][16].gdec())) / 2;\n\n            hC = (pdpiH(hor[i][2].gdec(),hor[i][7].gdec()) +\n                  pdpiH(hor[i][12].gdec(),hor[i][17].gdec())) / 2;\n\n            hD = (pdpiH(hor[i][3].gdec(),hor[i][8].gdec()) +\n                  pdpiH(hor[i][13].gdec(),hor[i][18].gdec())) / 2;\n\n            hE = (pdpiH(hor[i][4].gdec(),hor[i][9].gdec()) +\n                  pdpiH(hor[i][14].gdec(),hor[i][19].gdec())) / 2;\n\n\n\n            zA = (pdpiV(zen[i][0].gdec(),zen[i][5].gdec()) +\n                  pdpiV(zen[i][10].gdec(),zen[i][15].gdec())) / 2;\n\n            zB = (pdpiV(zen[i][1].gdec(),zen[i][6].gdec()) +\n                  pdpiV(zen[i][11].gdec(),zen[i][16].gdec())) / 2;\n\n            zC = (pdpiV(zen[i][2].gdec(),zen[i][7].gdec()) +\n                  pdpiV(zen[i][12].gdec(),zen[i][17].gdec())) / 2;\n\n            zD = (pdpiV(zen[i][3].gdec(),zen[i][8].gdec()) +\n                  pdpiV(zen[i][13].gdec(),zen[i][18].gdec())) / 2;\n\n            zE = (pdpiV(zen[i][4].gdec(),zen[i][9].gdec()) +\n                  pdpiV(zen[i][14].gdec(),zen[i][19].gdec())) / 2;\n\n\n            dA = (dists[i][0]+dists[i][5]+dists[i][10]+dists[i][15]) / 4;\n\n            dB = (dists[i][1]+dists[i][6]+dists[i][11]+dists[i][16]) / 4;\n\n            dC = (dists[i][2]+dists[i][7]+dists[i][12]+dists[i][17]) / 4;\n\n            dD = (dists[i][3]+dists[i][8]+dists[i][13]+dists[i][18]) / 4;\n\n            dE = (dists[i][4]+dists[i][9]+dists[i][14]+dists[i][19]) / 4;\n\n\n            topoPoint A(hA,zA,dA,false);\n            temp.push_back(A);\n            topoPoint B(hB,zB,dB,false);\n            temp.push_back(B);\n            topoPoint C(hC,zC,dC,false);\n            temp.push_back(C);\n            topoPoint D(hD,zD,dD,false);\n            temp.push_back(D);\n            topoPoint E(hE,zE,dE,false);\n            temp.push_back(E);\n\n//                                cout <<hA<<\" \"<<zA<<\" \"<<dA<<endl;\n\n        }\n        if (i == 3)\n        {\n            topoPoint EXTRA(hor[i][0].gdec(),zen[i][0].gdec(),dists[i][0],false);\n\n            hA = pdpiH(hor[i][1].gdec(),hor[i][11].gdec());\n            hB = pdpiH(hor[i][2].gdec(),hor[i][12].gdec());\n            hC = pdpiH(hor[i][3].gdec(),hor[i][13].gdec());\n            hD = pdpiH(hor[i][4].gdec(),hor[i][14].gdec());\n            hE = pdpiH(hor[i][5].gdec(),hor[i][15].gdec());\n            hF = pdpiH(hor[i][6].gdec(),hor[i][16].gdec());\n            hG = pdpiH(hor[i][7].gdec(),hor[i][17].gdec());\n            hH = pdpiH(hor[i][8].gdec(),hor[i][18].gdec());\n            hI = pdpiH(hor[i][9].gdec(),hor[i][19].gdec());\n            hJ = pdpiH(hor[i][10].gdec(),hor[i][20].gdec());\n\n            zA = pdpiV(zen[i][1].gdec(),zen[i][11].gdec());\n            zB = pdpiV(zen[i][2].gdec(),zen[i][12].gdec());\n            zC = pdpiV(zen[i][3].gdec(),zen[i][13].gdec());\n            zD = pdpiV(zen[i][4].gdec(),zen[i][14].gdec());\n            zE = pdpiV(zen[i][5].gdec(),zen[i][15].gdec());\n            zF = pdpiV(zen[i][6].gdec(),zen[i][16].gdec());\n            zG = pdpiV(zen[i][7].gdec(),zen[i][17].gdec());\n            zH = pdpiV(zen[i][8].gdec(),zen[i][18].gdec());\n            zI = pdpiV(zen[i][9].gdec(),zen[i][19].gdec());\n            zJ = pdpiV(zen[i][10].gdec(),zen[i][20].gdec());\n\n            dA = (dists[i][1]+dists[i][11]) / 2;\n            dB = (dists[i][2]+dists[i][12]) / 2;\n            dC = (dists[i][3]+dists[i][13]) / 2;\n            dD = (dists[i][4]+dists[i][14]) / 2;\n            dE = (dists[i][5]+dists[i][15]) / 2;\n            dF = (dists[i][6]+dists[i][16]) / 2;\n            dG = (dists[i][7]+dists[i][17]) / 2;\n            dH = (dists[i][8]+dists[i][18]) / 2;\n            dI = (dists[i][9]+dists[i][19]) / 2;\n            dJ = (dists[i][10]+dists[i][20]) / 2;\n\n            topoPoint A(hA,zA,dA,false);\n            temp.push_back(A);\n            topoPoint B(hB,zB,dB,false);\n            temp.push_back(B);\n            topoPoint C(hC,zC,dC,false);\n            temp.push_back(C);\n            topoPoint D(hD,zD,dD,false);\n            temp.push_back(D);\n            topoPoint E(hE,zE,dE,false);\n            temp.push_back(E);\n            topoPoint F(hF,zF,dF,false);\n            temp.push_back(F);\n            topoPoint G(hG,zG,dG,false);\n            temp.push_back(G);\n            topoPoint H(hH,zH,dH,false);\n            temp.push_back(H);\n            topoPoint I(hI,zI,dI,false);\n            temp.push_back(I);\n            topoPoint J(hJ,zJ,dJ,false);\n            temp.push_back(J);\n\n            temp.push_back(EXTRA);\n\n//                               cout <<hA<<\" \"<<zA<<\" \"<<dA<<endl;\n\n\n        }\n        if (i == 4)\n        {\n            topoPoint EXTRA(hor[i][0].gdec(),zen[i][0].gdec(),dists[i][0],false);\n\n            hA = pdpiH(hor[i][1].gdec(),hor[i][11].gdec());\n            hB = pdpiH(hor[i][2].gdec(),hor[i][12].gdec());\n            hC = pdpiH(hor[i][3].gdec(),hor[i][13].gdec());\n            hD = pdpiH(hor[i][4].gdec(),hor[i][14].gdec());\n            hE = pdpiH(hor[i][5].gdec(),hor[i][15].gdec());\n            hF = pdpiH(hor[i][6].gdec(),hor[i][16].gdec());\n            hG = pdpiH(hor[i][7].gdec(),hor[i][17].gdec());\n            hH = pdpiH(hor[i][8].gdec(),hor[i][18].gdec());\n            hI = pdpiH(hor[i][9].gdec(),hor[i][19].gdec());\n            hJ = pdpiH(hor[i][10].gdec(),hor[i][20].gdec());\n\n            zA = pdpiV(zen[i][1].gdec(),zen[i][11].gdec());\n            zB = pdpiV(zen[i][2].gdec(),zen[i][12].gdec());\n            zC = pdpiV(zen[i][3].gdec(),zen[i][13].gdec());\n            zD = pdpiV(zen[i][4].gdec(),zen[i][14].gdec());\n            zE = pdpiV(zen[i][5].gdec(),zen[i][15].gdec());\n            zF = pdpiV(zen[i][6].gdec(),zen[i][16].gdec());\n            zG = pdpiV(zen[i][7].gdec(),zen[i][17].gdec());\n            zH = pdpiV(zen[i][8].gdec(),zen[i][18].gdec());\n            zI = pdpiV(zen[i][9].gdec(),zen[i][19].gdec());\n            zJ = pdpiV(zen[i][10].gdec(),zen[i][20].gdec());\n\n            dA = (dists[i][1]+dists[i][11]) / 2;\n            dB = (dists[i][2]+dists[i][12]) / 2;\n            dC = (dists[i][3]+dists[i][13]) / 2;\n            dD = (dists[i][4]+dists[i][14]) / 2;\n            dE = (dists[i][5]+dists[i][15]) / 2;\n            dF = (dists[i][6]+dists[i][16]) / 2;\n            dG = (dists[i][7]+dists[i][17]) / 2;\n            dH = (dists[i][8]+dists[i][18]) / 2;\n            dI = (dists[i][9]+dists[i][19]) / 2;\n            dJ = (dists[i][10]+dists[i][20]) / 2;\n\n            topoPoint A(hA,zA,dA,false);\n            temp.push_back(A);\n            topoPoint B(hB,zB,dB,false);\n            temp.push_back(B);\n            topoPoint C(hC,zC,dC,false);\n            temp.push_back(C);\n            topoPoint D(hD,zD,dD,false);\n            temp.push_back(D);\n            topoPoint E(hE,zE,dE,false);\n            temp.push_back(E);\n            topoPoint F(hF,zF,dF,false);\n            temp.push_back(F);\n            topoPoint G(hG,zG,dG,false);\n            temp.push_back(G);\n            topoPoint H(hH,zH,dH,false);\n            temp.push_back(H);\n            topoPoint I(hI,zI,dI,false);\n            temp.push_back(I);\n            topoPoint J(hJ,zJ,dJ,false);\n            temp.push_back(J);\n\n            temp.push_back(EXTRA);\n\n//                               cout <<hA<<\" \"<<zA<<\" \"<<dA<<endl;\n\n        }\n\n\n        points.push_back(temp);\n        temp.clear();\n    }\n\n    pointsPrint(\"points0.txt\");\n}\n\nvoid SMMTleverARM::pointsPrint(string filename)\n{\n    ofstream outFile(filename);\n\n    for (unsigned ii = 0; ii < points.size(); ii++)\n    {\n        for (unsigned jj = 0; jj < points[ii].size(); jj++)\n        {\n            outFile << points[ii][jj].XYZ(0) <<\" \";\n            outFile << points[ii][jj].XYZ(1) <<\" \";\n            outFile << points[ii][jj].XYZ(2) << endl;\n        }\n    }\n\n    outFile.close();\n}\n\n\nvoid SMMTleverARM::horiz()\n{\n    vector<GMS> temp;\n    int g,m,s;\n\n    for (unsigned int i = 0; i < data.size() ; i++)\n    {\n\n        for (unsigned int j = 0; j < data[i].size(); j++)\n        {\n\n            g = stoi(data[i][j].substr(23,3));\n            m = stoi(data[i][j].substr(27,2));\n            s = stoi(data[i][j].substr(29,2));\n            GMS temp2(g,m,s);\n\n            temp.push_back(temp2);\n        }\n        hor.push_back(temp);\n        temp.clear();\n    }\n\n}\n\nvoid SMMTleverARM::zenit()\n{\n    vector<GMS> temp;\n    int g,m,s;\n\n    for (unsigned int i = 0; i < data.size() ; i++)\n    {\n\n        for (unsigned int j = 0; j < data[i].size(); j++)\n        {\n\n            g = stoi(data[i][j].substr(35,3));\n            m = stoi(data[i][j].substr(39,2));\n            s = stoi(data[i][j].substr(41,2));\n            GMS temp2(g,m,s);\n//            cout<<temp2.gdec()<<endl;\n\n            temp.push_back(temp2);\n        }\n        zen.push_back(temp);\n        temp.clear();\n    }\n\n}\n\nvoid SMMTleverARM::distanc()\n{\n    vector<double> temp;\n    double temp2;\n\n    for (unsigned int i = 0; i < data.size() ; i++)\n    {\n\n        for (unsigned int j = 0; j < data[i].size(); j++)\n        {\n\n            temp2 = stod(data[i][j].substr(47,10));\n//            cout<<temp2<<endl;\n\n            temp.push_back(temp2);\n        }\n        dists.push_back(temp);\n        temp.clear();\n    }\n\n}\n\ntopoPoint::topoPoint(double h,double z,double di,bool isRad)\n{\n    Hz=h;\n    Ze=z;\n    Di=di;\n    rad = isRad;\n    cart();\n}\n\nvoid topoPoint::cart()\n{\n    double X,Y,Z;\n\n    if (rad)\n    {\n        X = std::sin(Ze) * std::sin(Hz) * Di;\n        Y = std::sin(Ze) * std::cos(Hz) * Di;\n        Z = std::cos(Ze) * Di;\n    }\n    else\n    {\n        X = std::sin(Ze*(datum::pi/180)) * std::sin(Hz*(datum::pi/180)) * Di;\n        Y = std::sin(Ze*(datum::pi/180)) * std::cos(Hz*(datum::pi/180)) * Di;\n        Z = std::cos(Ze*(datum::pi/180)) * Di;\n    }\n\n    vec3 temp = {X,Y,Z};\n\n    XYZ = temp;\n}\n\ndouble pdpiH(double h1,double h2)\n{\n    if (h1 > h2)\n    {\n        return (h1+h2+180)/2;\n    }\n    else\n    {\n        return (h1+h2-180)/2;\n    }\n}\n\ndouble pdpiV(double v1,double v2)\n{\n    if (v1 < v2)\n    {\n        return (v1-v2+360)/2;\n    }\n    else\n    {\n        return (v2-v1+360)/2;\n    }\n}\n\nvec4 plane3points(vec3 u,vec3 v,vec3 w)\n{\n//the function returns a 4-vector with the plane equation coefficients\n//assuming the form  ax + by + cz + d = 0\n    vec4 res;\n    vec3 p1,p2,n;\n    vec d;\n    p1 = normalise(v - u);\n    p2 = normalise(w - u);\n    n  = normalise(cross(p1,p2));\n    d = - dot(n,u);\n\n    res = join_vert(n,d);\n\n//cout << res <<endl;\n    return res;\n}\n\nvoid topoPoint::translate(vec3 tvec)\n{\n    XYZ += tvec;\n}\n\nvoid topoPoint::Rotate(mat R)\n{\n    XYZ = R * XYZ;\n}\n\nvoid TptMat (mat *M,vec Tvec)\n{\n    mat temp = *M;\n\n    if(temp.n_cols == Tvec.n_elem)\n    {\n        for (uword i = 0; i < temp.n_rows; i++)\n        {\n            temp.row(i) = trans(trans(temp.row(i)) + Tvec );\n        }\n    }\n    else\n    {\n        cout << \"nada realizado, tamanho de colunas da matriz diferente do numero de elementos do vetor dado\"<<endl;\n    }\n\n    *M = temp;\n}\n\nvoid RptMat (mat *M,mat R)\n{\n    mat temp = *M;\n\n    if( (temp.n_cols == R.n_cols) & (R.n_cols == R.n_rows) )\n    {\n        for (uword i = 0; i < temp.n_rows; i++)\n        {\n            temp.row(i) = trans(R*trans(temp.row(i)));\n        }\n    }\n    else\n    {\n        cout << \"nada realizado, tamanho de colunas da matriz diferente do numero de colunas da matriz dada\"<<endl;\n        cout<<\"ou a matriz fornecida n\u00e3o \u00e9 quadrada\"<<endl;\n    }\n\n    *M = temp;\n}\n\nvoid SMMTleverARM::translateAll(vec3 tvec)\n{\n    for (unsigned int i = 0; i < points.size(); i++)\n    {\n        for (unsigned int j = 0; j < points[i].size(); j++)\n        {\n            points[i][j].translate(tvec);\n        }\n    }\n}\n\nvoid SMMTleverARM::rotAll (mat R)\n{\n    for (unsigned int i = 0; i < points.size(); i++)\n    {\n        for (unsigned int j = 0; j < points[i].size(); j++)\n        {\n            points[i][j].Rotate(R);\n        }\n    }\n}\n\nmat topoPointsMat (vector<topoPoint> points,uword first,uword last)\n{\n    mat res;\n\n    uword nlin = last - first + 1;\n\n    res.zeros(nlin,3);\n\n    for (uword i = first; i < last+1; i++)\n    {\n        res.row(i-first) = trans(points.at(i).XYZ);\n//        cout << i <<endl;\n    }\n\n//    cout<<res<<endl;\n\n    return res;\n}\n\nvec4 parallelPlane(vec4 plane1,vec3 pointOnPlane)\n{\n    vec4 res;\n    vec3 n = normalise(plane1.rows(0,2));\n\n    res.rows(0,2) = n;\n    res(3) = - dot(n,pointOnPlane);\n\n    return res;\n}\n\nvec3 ProjPtOrtPlane(vec3 pt2Proj,vec3 plNorm,vec3 ptOnPlane)\n{\n    return pt2Proj + (dot(normalise(plNorm),ptOnPlane-pt2Proj)) * normalise(plNorm);\n}\n\nvec3 onPlanePoint(vec4 plCoef,double x,double y)\n{\n    vec3 res;\n\n    res(0) = x;\n    res(1) = y;\n    res(2) = - (plCoef(0)*x+plCoef(1)*y+plCoef(3))/plCoef(2);\n\n    return res;\n}\n\nvoid SMMTleverARM::report()\n{\n    ofstream out(\"report.txt\");\n    out.precision(8);\n\n    out << \"Relat\u00f3rio de Sa\u00edda do Processamento da \";\n    out<< \"determina\u00e7\u00e3o dos par\u00e2metros de orienta\u00e7\u00e3o relativa\"   <<endl;\n    out<<\"do Sistema de Mapeamento M\u00f3vel Terrestre do LAPE\"<<endl<<endl<<endl;\n\n    out << \"Lever Arm (no body-frame da IMU) --------------------------------\"<<endl<<endl;\n\n    out<< \"IMU -> Antena\"<<endl;\n    out << \"X(m): \" <<antLA(0)<< \" | Y(m): \" <<antLA(1)<< \" | Z(m): \" <<antLA(2)<<endl<<endl;\n\n    out<< \"IMU -> C\u00e2mera Esquerda\"<<endl;\n    out << \"X(m): \" <<LcamLA(0)<< \" | Y(m): \" <<LcamLA(1)<< \" | Z(m): \" <<LcamLA(2)<<endl<<endl;\n\n    out<< \"IMU -> C\u00e2mera Direita\"<<endl;\n    out << \"X(m): \" <<RcamLA(0)<< \" | Y(m): \" <<RcamLA(1)<< \" | Z(m): \" <<RcamLA(2)<<endl<<endl<<endl;\n\n    out<<\"Distancias:\"<<endl;\n    out<<\"Entre c\u00e2meras: \"<<arma::norm(LcamLA-RcamLA)<<endl;\n    out<<\"IMU - Antena: \"<<arma::norm(antLA)<<endl;\n    out<<\"IMU - Cam Esq. : \"<<arma::norm(LcamLA)<<endl;\n    out<<\"IMU - Cam Dir. : \"<<arma::norm(RcamLA)<<endl;\n\n\n    out<< \"Matrizes do Boresight (cossenos diretores): \"<<endl<<endl;\n    Rimu_LC.raw_print(out,\"IMU (BF) -> C\u00e2mera Esquerda (BF)\");\n    out<<endl;\n    Rimu_RC.raw_print(out,\"IMU (BF) -> C\u00e2mera Direita (BF)\");\n    out<<endl<<endl;\n\n    out<< \"Matrizes do Boresight (cossenos diretores, mesma conven\u00e7\u00e3o da IMU): \"<<endl<<endl;\n    Rimu_LC2.raw_print(out,\"IMU (BF) -> C\u00e2mera Esquerda (BF)\");\n    out<<endl;\n    Rimu_RC2.raw_print(out,\"IMU (BF) -> C\u00e2mera Direita (BF)\");\n    out<<endl<<endl;\n\n    out<<\"no \u00faltimo caso, os angulos formados com os eixos do BF da IMU: \"<<endl<<endl;\n\n    out<<\"IMU (BF) -> C\u00e2mera Esquerda (BF)\"<<endl<<arma::acos(Rimu_LC2)*(180/datum::pi)<<endl<<endl;\n    out<<\"IMU (BF) -> C\u00e2mera Direita (BF)\"<<endl<<arma::acos(Rimu_RC2)*(180/datum::pi)<<endl;\n\n    out<<endl<<\"testes de consist\u00eancia dos resultados\"<<endl;\n    out<<\"as matrizes de rota\u00e7\u00e3o dever\u00e3o, ao ser multiplicadas por sua transposta, serem iguais a matriz identidade\"<<endl<<endl;\n\n    out<<\"Rtopo_imu * Rtopo_imu.t()\"<<endl<<Rot1 * Rot1.t()<<endl;\n\n    out<<\"Rimu_LC * Rimu_LC.t()\"<<endl<<Rimu_LC * Rimu_LC.t()<<endl;\n    out<<\"Rimu_RC * Rimu_RC.t()\"<<endl<<Rimu_RC * Rimu_RC.t()<<endl;\n\n    out<<\"Rimu_LC2 * Rimu_LC2.t()\"<<endl<<Rimu_LC2 * Rimu_LC2.t()<<endl;\n    out<<\"Rimu_RC2 * Rimu_RC2.t()\"<<endl<<Rimu_RC2 * Rimu_RC2.t()<<endl;\n\n}\n\n", "meta": {"hexsha": "c2461a4f8cba588d02eed9ef5d1e0431ea4bdf0f", "size": 37440, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "or_relativ.hpp", "max_stars_repo_name": "kauevestena/smmt", "max_stars_repo_head_hexsha": "17e63e5b995f75e8b58e75d3d3a49049b0cf92eb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-04T21:47:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-04T21:47:42.000Z", "max_issues_repo_path": "or_relativ.hpp", "max_issues_repo_name": "kauevestena/smmt", "max_issues_repo_head_hexsha": "17e63e5b995f75e8b58e75d3d3a49049b0cf92eb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "or_relativ.hpp", "max_forks_repo_name": "kauevestena/smmt", "max_forks_repo_head_hexsha": "17e63e5b995f75e8b58e75d3d3a49049b0cf92eb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9279778393, "max_line_length": 149, "alphanum_fraction": 0.509909188, "num_tokens": 12783, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256631249076, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.47325460565142713}}
{"text": "#ifndef YANNQ_HYPERCUBECONVLAYER_HH\n#define YANNQ_HYPERCUBECONVLAYER_HH\n\n#include <time.h>\n#include <Eigen/Dense>\n#include <algorithm>\n#include <complex>\n#include <fstream>\n#include <memory>\n#include <random>\n#include <vector>\n\n//oneDnn\n#include <mkldnn.hpp>\n#include <dnnl.hpp>\n\n//Yannq\n#include <Utilities/Utility.hpp>\n#include <Utilities/Exceptions.hpp>\n#include \"AbstractLayer.hpp\"\n#include \"Machines/DNNEngine.hpp\"\n\nnamespace yannq {\n/** Convolutional layer with spin 1/2 hidden units.\n Important: In order for this to work correctly, Vector and Matrix must\n be column major.\n */\n\ntemplate<typename T>\nclass Conv1D;\n\ntemplate<>\nclass Conv1D<float>\n\t: public AbstractLayer<float> \n{\npublic:\n\tusing T = float;\n\tusing Vector = Eigen::Matrix<T, Eigen::Dynamic, 1>;\n\tusing Matrix = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>;\n\tusing VectorRef = Eigen::Ref<Vector>;\n\tusing VectorConstRef = Eigen::Ref<const Vector>;\n\nprivate:\n\tconst bool useBias_;  // boolean to turn or off bias\n\tconst uint32_t stride_;         // convolution stride\n\tconst uint32_t npar_;          // number of parameters in layer\n\n\tdnnl::memory::dims weightDims_; //dimension of weights OC x IC x W\n\tdnnl::memory::desc weightMd_; //memory description\n\tdnnl::memory weight_; \n\n\tdnnl::memory::dims biasDims_; //dimension of bias OC\n\tdnnl::memory::desc biasMd_; //memory description\n\tdnnl::memory bias_; \n\t\n\tconst dnnl::memory::data_type dtype = dnnl::memory::data_type::f32;\n\n\tstatic uint32_t numParams(bool useBias, const uint32_t inChannels,\n\t\t\tconst uint32_t outChannels, const uint32_t kernelSize)\n\t{\n\t\tuint32_t np = inChannels * outChannels * kernelSize;\n\t\tif(useBias)\n\t\t\tnp += outChannels;\n\t\treturn np;\n\t}\n\npublic:\n\t/// Constructor\n\tConv1D(\tconst uint32_t inChannels, const uint32_t outChannels,\n\t\t\tconst uint32_t kernelSize, const uint32_t stride = 1,\n\t\t\tconst bool useBias = false)\n\t\t: useBias_(useBias), stride_(stride),\n\t\tnpar_(numParams(useBias, inChannels, outChannels, kernelSize)),\n\t\tweightDims_{outChannels, inChannels, kernelSize},\n\t\tbiasDims_{outChannels}\n\t{\n\t\tusing namespace dnnl;\n\n\t\tauto& engine = DNNEngine::getEngine();\n\n\t\tweightMd_ = memory::desc({weightDims_}, dtype, memory::format_tag::oiw);\n\t\tweight_ = memory(weightMd_, engine);\n\n\t\tbiasMd_ = memory::desc({biasDims_}, dtype, memory::format_tag::a);\n\t\tbias_ = memory(biasMd_, engine);\n\n\t\tif(!useBias_)\n\t\t{\n\t\t\tT* p = static_cast<T*>(bias_.get_data_handle());\n\t\t\tfor(int i = 0; i < biasDims_[0]; ++i)\n\t\t\t{\n\t\t\t\tp[i] = T(0.0);\n\t\t\t}\n\t\t}\n\t}\n\n\tConv1D(const Conv1D& rhs) = default;\n\tConv1D(Conv1D&& rhs) = default;\n\n\tConv1D& operator=(const Conv1D& rhs) = delete;\n\n\tConv1D& operator=(Conv1D&& rhs) = delete;\n\n\tbool operator==(const Conv1D& rhs) const\n\t{\n\t\tbool sameShape = (useBias_ == rhs.useBias_) &&\n\t\t\t(weightDims_ == rhs.weightDims_) &&\n\t\t\t(stride_ == rhs.stride_);\n\n\t\tif(!sameShape)\n\t\t\treturn false;\n\t\t\n\t\tbool sameWeight = (std::memcmp(weight_.get_data_handle(),\n\t\t\t\t\trhs.weight_.get_data_handle(),\n\t\t\t\t\tsizeof(T)*weightSize()) == 0);\n\n\t\tif(!useBias_)\n\t\t\treturn sameWeight;\n\n\t\tif(sameWeight)\n\t\t\treturn std::memcmp(bias_.get_data_handle(), \n\t\t\t\t\trhs.bias_.get_data_handle(), \n\t\t\t\t\tsizeof(T)*biasDims_[0]);\n\n\t\treturn false;\n\t}\n\n\tuint32_t weightSize() const\n\t{\n\t\tuint32_t prod = 1;\n\t\tfor(auto dim: weightDims_)\n\t\t\tprod *= dim;\n\t\treturn prod;\n\t}\n\n\tstd::string name() const override { return \"Convolutional 1D Layer\"; }\n\n\ttemplate<class RandomEngine>\n\tvoid randomizeParams(RandomEngine&& re, double sigma)\n\t{\n\t\tsetParams(randomVector<T>(std::forward<RandomEngine>(re), sigma, npar_));\n\t}\n\n\tuint32_t paramDim() const override { return npar_; }\n\n\tuint32_t outputDim(uint32_t inputDim) const override \n\t{\n\t\treturn (inputDim / stride_ / weightDims_[1]) * weightDims_[0]; \n\t}\n\n\tVector getParams() const override \n\t{\n\t\tVector pars(npar_);\n\t\tpars.head(weightSize()) = \n\t\t\tEigen::Map<const Vector>((const T*)weight_.get_data_handle(),\n\t\t\t\t\tweightSize());\n\t\tif(useBias_)\n\t\t{\n\t\t\tpars.tail(biasDims_[0]) = \n\t\t\t\tEigen::Map<const Vector>((const T*)bias_.get_data_handle(),\n\t\t\t\t\t\tbiasDims_[0]);\n\t\t}\n\t\treturn pars;\n\t}\n\n\tvoid setParams(VectorConstRef pars) override \n\t{\n\t\tEigen::Map<Vector>((T*)weight_.get_data_handle()) =\n\t\t\tpars.head(weightSize());\n\t\tif(useBias_)\n\t\t{\n\t\t\tEigen::Map<Vector>((T*)bias_.get_data_handle(), biasDims_[0]) =\n\t\t\t\tpars.tail(biasDims_[0]);\n\t\t}\n\t}\n\n\tvoid updateParams(VectorConstRef ups) override\n\t{\n\t\tEigen::Map<Vector>((T*)weight_.get_data_handle()) +=\n\t\t\tups.head(weightSize());\n\t\tif(useBias_)\n\t\t{\n\t\t\tEigen::Map<Vector>((T*)bias_.get_data_handle(), biasDims_[0]) +=\n\t\t\t\tups.tail(biasDims_[0]);\n\t\t}\n\t}\n\n\t/**\n\t * Feedforward for batch 1\n\t * @param input inChannels*size\n\t * @param output outChannels*size\n\t */\n\tvoid forward(const VectorConstRef& input, VectorRef output) override \n\t{\n\t\tusing namespace dnnl;\n\t\tassert(input.size() % inChannels_ == 0);\n\n\n\t\tuint32_t inSize = input.size() / weightDims_[1];\n\t\tuint32_t outSize = inSize / stride_;\n\n\t\toutput.setZero();\n\n\t\tauto& engine = DNNEngine::getEngine();\n\n\t\tauto srcMd = memory::desc({1, weightDims_[1] /*inChannel*/,\n\t\t\t\tinSize}, dtype, memory::format_tag::ncw);\n\t\tauto src = memory(srcMd, engine);\n\n\t\tauto dstMd = \n\t}\n\n\tvoid backprop(const VectorConstRef& prev_layer_output,\n\t\t\tconst VectorConstRef& this_layer_output,\n\t\t\tconst VectorConstRef& dout, \n\t\t\tVectorRef din,\n\t\t\tVectorRef der) override\n\t{\n\t\tassert(prev_layer_output.size() % inChannels_ == 0);\n\t\tuint32_t inSize = prev_layer_output.size() / inChannels_;\n\t\tuint32_t outSize = inSize / stride_;\n\n\t\tdin.resize(inSize*inChannels_);\n\t\tdin.setZero();\n\t\tder.setZero();\n\n\t\t// propagate delta to prev-layer\n\t\tfor (uint32_t oc = 0; oc < outChannels_; oc++)\n\t\tfor (uint32_t r = 0; r < outSize; r ++) \n\t\tfor (uint32_t ic = 0; ic < inChannels_; ic++)\n\t\tfor (uint32_t ki = 0; ki < kernelSize_; ki++)\n\t\t{\n\t\t\tdin(((r*stride_+ki-kernelSize_/2+inSize)%inSize) + ic*inSize) \n\t\t\t\t+= kernel_(ki + ic*kernelSize_, oc)*dout[r + oc*outSize];\n\t\t}\n\t\t\n\t\tuint32_t k = 0;\n\t\tif(useBias_)// accumulate bias difference\n\t\t{\n\t\t\tfor (uint32_t oc = 0; oc < outChannels_; oc++)\n\t\t\tfor (uint32_t r = 0; r < outSize; r ++) \n\t\t\t{\n\t\t\t\tder(oc) += dout(r + oc*outSize);\n\t\t\t}\n\t\t\tk += outChannels_;\n\t\t}\n\n\t\tMatrix dw(inChannels_*kernelSize_, outChannels_);\n\t\tdw.setZero();\n\n\t\t// accumulate weight difference\n\t\tfor (uint32_t oc = 0; oc < outChannels_; oc++)\n\t\tfor (uint32_t r = 0; r < outSize; r ++) \n\t\t{\n\t\t\tfor (uint32_t ic = 0; ic < inChannels_; ic++)\n\t\t\tfor (uint32_t ki = 0; ki < kernelSize_; ki++)\n\t\t\t{\n\t\t\t\tdw(ki + ic*kernelSize_, oc) += \n\t\t\t\t\tprev_layer_output(((r*stride_+ki-kernelSize_/2+inSize)%inSize) + ic*inSize)*\n\t\t\t\t\tdout[r + oc*outSize];\n\t\t\t}\n\t\t}\n\t\tdw.resize(dw.rows()*dw.cols(),1);\n\t\tder.segment(k, kernel_.rows()*kernel_.cols()) = std::move(dw);\n\t}\n\n\tuint32_t fanIn() override\n\t{\n\t\treturn inChannels_*kernelSize_;\n\t}\n\tuint32_t fanOut() override\n\t{\n\t\treturn outChannels_*kernelSize_;\n\t}\n\n\tnlohmann::json desc() const override {\n\t\tnlohmann::json layerpar;\n\t\tlayerpar[\"name\"] = name();\n\t\tlayerpar[\"use_bias\"] = useBias_;\n\t\tlayerpar[\"input_channels\"] = inChannels_;\n\t\tlayerpar[\"output_channels\"] = outChannels_;\n\t\tlayerpar[\"kernel_size\"] = kernelSize_;\n\t\tlayerpar[\"stride\"] = stride_;\n\t\treturn layerpar;\n\t}\n};\n\n\ntemplate<typename T>\nclass Conv1D\n\t: public AbstractLayer<T> \n{\n\tstatic_assert(!AbstractLayer<T>::Matrix::IsRowMajor, \"Matrix must be column-major\");\n\npublic:\n\tusing Scalar = T;\n\tusing Vector = Eigen::Matrix<T, Eigen::Dynamic, 1>;\n\tusing Matrix = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>;\n\tusing VectorRef = Eigen::Ref<Vector>;\n\tusing VectorConstRef = Eigen::Ref<const Vector>;\n\nprivate:\n\tconst bool useBias_;  // boolean to turn or off bias\n\n\tconst uint32_t inChannels_;   // number of input channels\n\tconst uint32_t outChannels_;  // number of output channels\n\n\tconst uint32_t kernelSize_;\n\tconst uint32_t stride_;         // convolution stride\n\t\n\tconst uint32_t npar_;          // number of parameters in layer\n\n\t\n\n\tMatrix kernel_;  // Weight parameters, W((inChannels_ * kernelSize)x(outChannels))\n\tVector bias_;     // Bias parameters, b(outChannels)\n\n\tstatic uint32_t numParams(bool useBias, const uint32_t inChannels,\n\t\t\tconst uint32_t outChannels, const uint32_t kernelSize)\n\t{\n\t\tuint32_t np = inChannels * outChannels * kernelSize;\n\t\tif(useBias)\n\t\t\tnp += outChannels;\n\t\treturn np;\n\t}\n\npublic:\n\t/// Constructor\n\tConv1D(\tconst uint32_t inChannels, const uint32_t outChannels,\n\t\t\tconst uint32_t kernelSize, const uint32_t stride = 1,\n\t\t\tconst bool useBias = false)\n\t\t: useBias_(useBias), inChannels_(inChannels), outChannels_(outChannels),\n\t\tkernelSize_(kernelSize), stride_(stride),\n\t\tnpar_(numParams(useBias, inChannels, outChannels, kernelSize)),\n\t\tkernel_(inChannels*kernelSize, outChannels), bias_(outChannels)\n\t{\n\t}\n\n\tConv1D(const Conv1D& rhs) = default;\n\tConv1D(Conv1D&& rhs) = default;\n\n\tConv1D& operator=(const Conv1D& rhs) = default;\n\tConv1D& operator=(Conv1D&& rhs) = default;\n\n\tbool operator==(const Conv1D& rhs) const\n\t{\n\t\tif(useBias_ != rhs.useBias_)\n\t\t\treturn false;\n\n\t\tbool res = (inChannels_ == rhs.inChannels_) && \n\t\t\t\t(outChannels_ == rhs.outChannels_) &&\n\t\t\t\t(kernelSize_ == rhs.kernelSize_) &&\n\t\t\t\t(stride_ == rhs.stride_) &&\n\t\t\t\t(kernel_ == rhs.kernel_);\n\n\t\tif(!useBias_)\n\t\t\treturn res;\n\t\telse\n\t\t\treturn res && (bias_ == rhs.bias_);\n\t}\n\n\tstd::string name() const override { return \"Convolutional 1D Layer\"; }\n\n\ttemplate<class RandomEngine>\n\tvoid randomizeParams(RandomEngine&& re, remove_complex_t<Scalar> sigma)\n\t{\n\t\tsetParams(randomVector<T>(std::forward<RandomEngine>(re), sigma, npar_));\n\t}\n\n\tuint32_t paramDim() const override { return npar_; }\n\tuint32_t outputDim(uint32_t inputDim) const override {\n\t\treturn (inputDim / stride_ / inChannels_) * outChannels_; \n\t}\n\n\tVector getParams() const override \n\t{\n\t\tVector pars(npar_);\n\t\tpars.head(kernel_.size()) = Eigen::Map<const Vector>(kernel_.data(), kernel_.size());\n\t\tif(useBias_)\n\t\t{\n\t\t\tpars.tail(outChannels_) = bias_;\n\t\t}\n\t\treturn pars;\n\t}\n\n\tvoid setParams(VectorConstRef pars) override \n\t{\n\t\tEigen::Map<Vector>(kernel_.data(), kernel_.size()) = pars.head(kernel_.size());\n\t\tif(useBias_)\n\t\t{\n\t\t\tbias_ = pars.segment(kernel_.size(), outChannels_);\n\t\t}\n\t\telse\n\t}\n\n\tvoid updateParams(VectorConstRef ups) override\n\t{\n\t\tEigen::Map<Vector>(kernel_.data(), kernel_.size()) += ups.head(kernel_.size());\n\t\tif(useBias_)\n\t\t{\n\t\t\tbias_ += ups.segment(kernel_.size(), outChannels_);\n\t\t}\n\t}\n\n\n\n\tuint32_t fanIn() override\n\t{\n\t\treturn inChannels_*kernelSize_;\n\t}\n\n\tuint32_t fanOut() override\n\t{\n\t\treturn outChannels_*kernelSize_;\n\t}\n\n\tnlohmann::json desc() const override {\n\t\tnlohmann::json layerpar;\n\t\tlayerpar[\"name\"] = name();\n\t\tlayerpar[\"use_bias\"] = useBias_;\n\t\tlayerpar[\"input_channels\"] = inChannels_;\n\t\tlayerpar[\"output_channels\"] = outChannels_;\n\t\tlayerpar[\"kernel_size\"] = kernelSize_;\n\t\tlayerpar[\"stride\"] = stride_;\n\t\treturn layerpar;\n\t}\n};\n}// namespace yannq\n\n#endif\n", "meta": {"hexsha": "c313b8c34ecffbbf99bbc8bb7ae013a068c44273", "size": 10802, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Yannq/Machines/layers/Conv1Dnd.hpp", "max_stars_repo_name": "cecri/yannq", "max_stars_repo_head_hexsha": "b78c1f86a255059f06b34dd5e538449e7261d0ee", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Yannq/Machines/layers/Conv1Dnd.hpp", "max_issues_repo_name": "cecri/yannq", "max_issues_repo_head_hexsha": "b78c1f86a255059f06b34dd5e538449e7261d0ee", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Yannq/Machines/layers/Conv1Dnd.hpp", "max_forks_repo_name": "cecri/yannq", "max_forks_repo_head_hexsha": "b78c1f86a255059f06b34dd5e538449e7261d0ee", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.0626450116, "max_line_length": 87, "alphanum_fraction": 0.6874652842, "num_tokens": 3166, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515684, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4732545967278089}}
{"text": "/**\n * \\file ChamberlinFilter.cpp\n */\n\n#include \"ChamberlinFilter.h\"\n\n#include <boost/math/constants/constants.hpp>\n\nnamespace ATK\n{\n  template<typename DataType>\n  ChamberlinFilter<DataType>::ChamberlinFilter()\n  :TypedBaseFilter<DataType>(1, 1), numerical_frequency(0), numerical_attenuation(1), yh(0), yb(0), yl(0), selected(0), attenuation(1), cutoff_frequency(0)\n  {\n  }\n  \n  template<typename DataType_>\n  void ChamberlinFilter<DataType_>::set_cut_frequency(DataType_ cutoff_frequency)\n  {\n    this->cutoff_frequency = cutoff_frequency;\n    setup();\n  }\n\n  template<typename DataType_>\n  DataType_ ChamberlinFilter<DataType_>::get_cut_frequency() const\n  {\n    return cutoff_frequency;\n  }\n  \n  template<typename DataType_>\n  void ChamberlinFilter<DataType_>::set_attenuation(DataType_ attenuation)\n  {\n    this->attenuation = attenuation;\n    setup();\n  }\n\n  template<typename DataType_>\n  DataType_ ChamberlinFilter<DataType_>::get_attenuation() const\n  {\n    return attenuation;\n  }\n  \n  template<typename DataType>\n  void ChamberlinFilter<DataType>::select(int selection)\n  {\n    this->selected = selection;\n  }\n  \n  template<typename DataType>\n  int ChamberlinFilter<DataType>::get_selected() const\n  {\n    return selected;\n  }\n  \n  template<typename DataType>\n  void ChamberlinFilter<DataType>::setup()\n  {\n    numerical_frequency = 2 * std::sin(boost::math::constants::pi<DataType>() * cutoff_frequency / input_sampling_rate);\n    numerical_attenuation = 2 * attenuation;\n  }\n\n  template<typename DataType>\n  void ChamberlinFilter<DataType>::process_impl(int64_t size) const\n  {\n    const DataType* ATK_RESTRICT input = converted_inputs[0];\n    DataType* ATK_RESTRICT output = outputs[0];\n    for(int64_t i = 0; i < size; ++i)\n    {\n      yh = input[i] - yl - numerical_attenuation * yb;\n      yb = numerical_frequency * yh + yb;\n      yl = numerical_frequency * yb + yl;\n      if(selected == 0)\n      {\n        output[i] = yl;\n      }\n      else if(selected == 1)\n      {\n        output[i] = yb;\n      }\n      else\n      {\n        output[i] = yh;\n      }\n    }\n  }\n  \n  template class ChamberlinFilter<float>;\n  template class ChamberlinFilter<double>;\n}\n", "meta": {"hexsha": "bb13ae63cf79ce0fbc97ce17a40541786b238f44", "size": 2169, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ATK/EQ/ChamberlinFilter.cpp", "max_stars_repo_name": "apohl79/AudioTK", "max_stars_repo_head_hexsha": "05ac241b0bc6a8f841d93257b4d81e5961b1f627", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-05-17T15:29:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T22:26:08.000Z", "max_issues_repo_path": "ATK/EQ/ChamberlinFilter.cpp", "max_issues_repo_name": "apohl79/AudioTK", "max_issues_repo_head_hexsha": "05ac241b0bc6a8f841d93257b4d81e5961b1f627", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ATK/EQ/ChamberlinFilter.cpp", "max_forks_repo_name": "apohl79/AudioTK", "max_forks_repo_head_hexsha": "05ac241b0bc6a8f841d93257b4d81e5961b1f627", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-04-21T13:43:57.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-28T19:10:14.000Z", "avg_line_length": 24.1, "max_line_length": 155, "alphanum_fraction": 0.6777316736, "num_tokens": 552, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4732545967278088}}
{"text": "/*\n * Bayes++ the Bayesian Filtering Library\n * Copyright (c) 2002 Michael Stevens\n * See accompanying Bayes++.htm for terms and conditions of use.\n *\n * $Id$\n */\n\n/*\n * Good random numbers from Boost\n *  Provides a common class  for all random number requirements to test Bayes++\n */\n\n#include <boost/version.hpp>\n#include <boost/random.hpp>\n\n\nnamespace Bayesian_filter_test\n{\n\nnamespace\n{\n\ttemplate<class Engine, class Distribution>\n\tclass simple_generator\n\t{\n\tpublic:\n\t\ttypedef typename Distribution::result_type result_type;\n\t\tsimple_generator(Engine& e, Distribution& d)\n\t\t\t: _eng(e), _dist(d)\n\t\t{}\n\t\tresult_type operator()()\n\t\t{\treturn _dist(_eng);\n\t\t }\n\tprivate:\n\t\tEngine& _eng;\n\t\tDistribution& _dist;\n\t};\n}//namespace\n\nclass Boost_random\n{\npublic:\n\ttypedef Bayesian_filter_matrix::Float Float;\n\ttypedef boost::mt19937 URng;\n\tBoost_random() : dist_uniform_01(), dist_normal_01()\n\t{}\n\tBayesian_filter_matrix::Float normal(const Float mean, const Float sigma)\n\t{\n\t\tboost::normal_distribution<Float> dist(mean, sigma);\n\t\treturn dist(rng);\n\t}\n\tvoid normal(Bayesian_filter_matrix::DenseVec& v, const Float mean, const Float sigma)\n\t{\n\t\tboost::normal_distribution<Float> dist(mean, sigma);\n\t\tsimple_generator<URng, boost::normal_distribution<Float> > gen(rng, dist);\n\t\tstd::generate (v.begin(), v.end(), gen);\n\t}\n\tvoid normal(Bayesian_filter_matrix::DenseVec& v)\n\t{\n\t\tsimple_generator<URng, boost::normal_distribution<Float> > gen(rng, dist_normal_01);\n\t\tstd::generate (v.begin(), v.end(), gen);\n\t}\n\tvoid uniform_01(Bayesian_filter_matrix::DenseVec& v)\n\t{\n\t\tsimple_generator<URng, boost::uniform_01<Float> > gen(rng, dist_uniform_01);\n\t\tstd::generate (v.begin(), v.end(), gen);\n\t}\n#ifdef BAYES_FILTER_GAPPY\n\tvoid normal(Bayesian_filter_matrix::Vec& v, const Float mean, const Float sigma)\n\t{\n\t\tboost::normal_distribution<Float> dist(mean, sigma);\n\t\tsimple_generator_01<URng, boost::normal_distribution<Float> > gen(rng, dist);\n\t\tfor (std::size_t i = 0, iend=v.size(); i < iend; ++i)\n\t\t\tv[i] = gen();\n\t}\n\tvoid normal(Bayesian_filter_matrix::Vec& v)\n\t{\n\t\tsimple_generator_01<URng, boost::normal_distribution<Float> > gen(rng, dist_normal_01);\n\t\tfor (std::size_t i = 0, iend=v.size(); i < iend; ++i)\n\t\t\tv[i] = gen();\n\t}\n\tvoid uniform_01(Bayesian_filter_matrix::Vec& v)\n\t{\n\t\tsimple_generator<URng, boost::uniform_01<Float> > gen(rng, dist_uniform_01);\n\t\tfor (std::size_t i = 0, iend=v.size(); i < iend; ++i)\n\t\t\tv[i] = gen();\n\t}\n#endif\n\tvoid seed()\n\t{\n\t\trng.seed();\n\t}\nprivate:\n\tURng rng;\n\tboost::uniform_01<Float> dist_uniform_01;\n\tboost::normal_distribution<Float> dist_normal_01;\n};\n\n\n}//namespace\n", "meta": {"hexsha": "c2de69a8d3a52278d87cb9df7e45f6e32c7d696c", "size": 2597, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Test/random.hpp", "max_stars_repo_name": "Exadios/Bayes-", "max_stars_repo_head_hexsha": "a1cd9efe2e840506d887bec9b246fd936f2b71e5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-04-02T21:45:49.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-19T01:59:02.000Z", "max_issues_repo_path": "Test/random.hpp", "max_issues_repo_name": "Exadios/Bayes-", "max_issues_repo_head_hexsha": "a1cd9efe2e840506d887bec9b246fd936f2b71e5", "max_issues_repo_licenses": ["MIT"], "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/random.hpp", "max_forks_repo_name": "Exadios/Bayes-", "max_forks_repo_head_hexsha": "a1cd9efe2e840506d887bec9b246fd936f2b71e5", "max_forks_repo_licenses": ["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.7128712871, "max_line_length": 89, "alphanum_fraction": 0.7088948787, "num_tokens": 732, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185944046238981, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.4731351318100777}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// Unit Test\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#include <iostream>\n#include <sstream>\n\n\n#include <geometry_test_common.hpp>\n\n#include <boost/geometry/algorithms/equals.hpp>\n#include <boost/geometry/algorithms/make.hpp>\n#include <boost/geometry/algorithms/transform.hpp>\n#include <boost/geometry/geometries/geometries.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/io/wkt/wkt.hpp>\n#include <boost/geometry/strategies/strategies.hpp>\n#include <boost/variant/variant.hpp>\n\n#include <test_common/test_point.hpp>\n\ntemplate <typename Geometry1, typename Geometry2>\nvoid check_transform(Geometry1 const& geometry1,\n                     Geometry2 const& expected)\n{\n    Geometry2 geometry2;\n    BOOST_CHECK(bg::transform(geometry1, geometry2));\n\n    std::ostringstream result_wkt, expected_wkt;\n    result_wkt << bg::wkt(geometry2);\n    expected_wkt << bg::wkt(expected);\n    BOOST_CHECK_EQUAL(result_wkt.str(), expected_wkt.str());\n}\n\ntemplate <typename P1, typename P2, typename Value>\nvoid test_transform_point(Value value)\n{\n    P1 p1;\n    bg::set<0>(p1, 1);\n    bg::set<1>(p1, 2);\n    boost::variant<P1> v(p1);\n\n    P2 expected;\n    bg::assign(expected, p1);\n    bg::multiply_value(expected, value);\n\n    check_transform(p1, expected);\n    check_transform(v, expected);\n}\n\ntemplate <typename P1, typename P2, typename Value>\nvoid test_transform_linestring(Value value)\n{\n    typedef bg::model::linestring<P1> line1_type;\n    typedef bg::model::linestring<P2> line2_type;\n\n    line1_type line1;\n    line1.push_back(bg::make<P1>(1, 1));\n    line1.push_back(bg::make<P1>(2, 2));\n    boost::variant<line1_type> v(line1);\n\n    line2_type expected;\n    for (BOOST_AUTO(p, line1.begin()); p != line1.end(); ++p)\n    {\n        P2 new_point;\n        bg::assign(new_point, *p);\n        bg::multiply_value(new_point, value);\n        expected.push_back(new_point);\n    }\n\n    check_transform(line1, expected);\n    check_transform(v, expected);\n}\n\n\ntemplate <typename P1, typename P2, typename Value>\nvoid test_all(Value value)\n{\n    test_transform_point<P1, P2>(value);\n    test_transform_linestring<P1, P2>(value);\n}\n\ntemplate <typename T, typename DegreeOrRadian>\nvoid test_transformations(double phi, double theta, double r)\n{\n    typedef bg::model::point<T, 3, bg::cs::cartesian> cartesian_type;\n    cartesian_type p;\n\n    // 1: using spherical coordinates\n    {\n        typedef bg::model::point<T, 3, bg::cs::spherical<DegreeOrRadian> >  spherical_type;\n        spherical_type sph1;\n        assign_values(sph1, phi, theta, r);\n        BOOST_CHECK(transform(sph1, p));\n\n        spherical_type sph2;\n        BOOST_CHECK(transform(p, sph2));\n\n        BOOST_CHECK_CLOSE(bg::get<0>(sph1), bg::get<0>(sph2), 0.001);\n        BOOST_CHECK_CLOSE(bg::get<1>(sph1), bg::get<1>(sph2), 0.001);\n    }\n\n    // 2: using spherical coordinates on unit sphere\n    {\n        typedef bg::model::point<T, 2, bg::cs::spherical<DegreeOrRadian> >  spherical_type;\n        spherical_type sph1, sph2;\n        assign_values(sph1, phi, theta);\n        BOOST_CHECK(transform(sph1, p));\n        BOOST_CHECK(transform(p, sph2));\n\n        BOOST_CHECK_CLOSE(bg::get<0>(sph1), bg::get<0>(sph2), 0.001);\n        BOOST_CHECK_CLOSE(bg::get<1>(sph1), bg::get<1>(sph2), 0.001);\n    }\n}\n\nint test_main(int, char* [])\n{\n    typedef bg::model::d2::point_xy<double > P;\n    test_all<P, P>(1.0);\n    test_all<bg::model::d2::point_xy<int>, bg::model::d2::point_xy<float> >(1.0);\n\n    test_all<bg::model::point<double, 2, bg::cs::spherical<bg::degree> >,\n        bg::model::point<double, 2, bg::cs::spherical<bg::radian> > >(bg::math::d2r);\n    test_all<bg::model::point<double, 2, bg::cs::spherical<bg::radian> >,\n        bg::model::point<double, 2, bg::cs::spherical<bg::degree> > >(bg::math::r2d);\n\n    test_all<bg::model::point<int, 2, bg::cs::spherical<bg::degree> >,\n        bg::model::point<float, 2, bg::cs::spherical<bg::radian> > >(bg::math::d2r);\n\n    test_transformations<float, bg::degree>(4, 52, 1);\n    test_transformations<double, bg::degree>(4, 52, 1);\n\n    test_transformations<float, bg::radian>(3 * bg::math::d2r, 51 * bg::math::d2r, 1);\n    test_transformations<double, bg::radian>(3 * bg::math::d2r, 51 * bg::math::d2r, 1);\n\n#if defined(HAVE_TTMATH)\n    typedef bg::model::d2::point_xy<ttmath_big > PT;\n    test_all<PT, PT>();\n    test_transformations<ttmath_big, bg::degree>(4, 52, 1);\n    test_transformations<ttmath_big, bg::radian>(3 * bg::math::d2r, 51 * bg::math::d2r, 1);\n#endif\n\n    return 0;\n}\n", "meta": {"hexsha": "1746c7d23694fa18825adb8401bd27b7d52683a7", "size": 5046, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/boost_1_56_0/libs/geometry/test/algorithms/transform.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": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-11-02T07:15:32.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-15T19:56:59.000Z", "max_issues_repo_path": "boost/boost_1_56_0/libs/geometry/test/algorithms/transform.cpp", "max_issues_repo_name": "cooparation/caffe-android", "max_issues_repo_head_hexsha": "cd91078d1f298c74fca4c242531989d64a32ba03", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-11-18T21:24:03.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-11T12:39:57.000Z", "max_forks_repo_path": "boost/boost_1_56_0/libs/geometry/test/algorithms/transform.cpp", "max_forks_repo_name": "cooparation/caffe-android", "max_forks_repo_head_hexsha": "cd91078d1f298c74fca4c242531989d64a32ba03", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-01-02T14:11:37.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-20T13:42:13.000Z", "avg_line_length": 32.5548387097, "max_line_length": 91, "alphanum_fraction": 0.6728101467, "num_tokens": 1505, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943805178139, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.4731351255711952}}
{"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    testNonlinearFactorGraph.cpp\n * @brief   Unit tests for Non-Linear Factor NonlinearFactorGraph\n * @brief   testNonlinearFactorGraph\n * @author  Carlos Nieto\n * @author  Christian Potthast\n */\n\n#include <gtsam/base/Testable.h>\n#include <gtsam/base/Matrix.h>\n#include <tests/smallExample.h>\n#include <gtsam/inference/FactorGraph.h>\n#include <gtsam/inference/Symbol.h>\n#include <gtsam/symbolic/SymbolicFactorGraph.h>\n#include <gtsam/nonlinear/NonlinearFactorGraph.h>\n#include <gtsam/geometry/Pose2.h>\n#include <gtsam/geometry/Pose3.h>\n#include <gtsam/sam/RangeFactor.h>\n#include <gtsam/slam/BetweenFactor.h>\n\n#include <CppUnitLite/TestHarness.h>\n\n#include <boost/assign/std/list.hpp>\n#include <boost/assign/std/set.hpp>\nusing namespace boost::assign;\n\n/*STL/C++*/\n#include <iostream>\n\nusing namespace std;\nusing namespace gtsam;\nusing namespace example;\n\nusing symbol_shorthand::X;\nusing symbol_shorthand::L;\n\n/* ************************************************************************* */\nTEST( NonlinearFactorGraph, equals )\n{\n  NonlinearFactorGraph fg = createNonlinearFactorGraph();\n  NonlinearFactorGraph fg2 = createNonlinearFactorGraph();\n  CHECK( fg.equals(fg2) );\n}\n\n/* ************************************************************************* */\nTEST( NonlinearFactorGraph, error )\n{\n  NonlinearFactorGraph fg = createNonlinearFactorGraph();\n  Values c1 = createValues();\n  double actual1 = fg.error(c1);\n  DOUBLES_EQUAL( 0.0, actual1, 1e-9 );\n\n  Values c2 = createNoisyValues();\n  double actual2 = fg.error(c2);\n  DOUBLES_EQUAL( 5.625, actual2, 1e-9 );\n}\n\n/* ************************************************************************* */\nTEST( NonlinearFactorGraph, keys )\n{\n  NonlinearFactorGraph fg = createNonlinearFactorGraph();\n  KeySet actual = fg.keys();\n  LONGS_EQUAL(3, (long)actual.size());\n  KeySet::const_iterator it = actual.begin();\n  LONGS_EQUAL((long)L(1), (long)*(it++));\n  LONGS_EQUAL((long)X(1), (long)*(it++));\n  LONGS_EQUAL((long)X(2), (long)*(it++));\n}\n\n/* ************************************************************************* */\nTEST( NonlinearFactorGraph, GET_ORDERING)\n{\n  Ordering expected; expected += L(1), X(2), X(1); // For starting with l1,x1,x2\n  NonlinearFactorGraph nlfg = createNonlinearFactorGraph();\n  Ordering actual = Ordering::Colamd(nlfg);\n  EXPECT(assert_equal(expected,actual));\n\n  // Constrained ordering - put x2 at the end\n  Ordering expectedConstrained; expectedConstrained += L(1), X(1), X(2);\n  FastMap<Key, int> constraints;\n  constraints[X(2)] = 1;\n  Ordering actualConstrained = Ordering::ColamdConstrained(nlfg, constraints);\n  EXPECT(assert_equal(expectedConstrained, actualConstrained));\n}\n\n/* ************************************************************************* */\nTEST( NonlinearFactorGraph, probPrime )\n{\n  NonlinearFactorGraph fg = createNonlinearFactorGraph();\n  Values cfg = createValues();\n\n  // evaluate the probability of the factor graph\n  double actual = fg.probPrime(cfg);\n  double expected = 1.0;\n  DOUBLES_EQUAL(expected,actual,0);\n}\n\n/* ************************************************************************* */\nTEST( NonlinearFactorGraph, linearize )\n{\n  NonlinearFactorGraph fg = createNonlinearFactorGraph();\n  Values initial = createNoisyValues();\n  GaussianFactorGraph linearFG = *fg.linearize(initial);\n  GaussianFactorGraph expected = createGaussianFactorGraph();\n  CHECK(assert_equal(expected,linearFG)); // Needs correct linearizations\n}\n\n/* ************************************************************************* */\nTEST( NonlinearFactorGraph, clone )\n{\n  NonlinearFactorGraph fg = createNonlinearFactorGraph();\n  NonlinearFactorGraph actClone = fg.clone();\n  EXPECT(assert_equal(fg, actClone));\n  for (size_t i=0; i<fg.size(); ++i)\n    EXPECT(fg[i] != actClone[i]);\n}\n\n/* ************************************************************************* */\nTEST( NonlinearFactorGraph, rekey )\n{\n  NonlinearFactorGraph init = createNonlinearFactorGraph();\n  map<Key,Key> rekey_mapping;\n  rekey_mapping.insert(make_pair(L(1), L(4)));\n  NonlinearFactorGraph actRekey = init.rekey(rekey_mapping);\n\n  // ensure deep clone\n  LONGS_EQUAL((long)init.size(), (long)actRekey.size());\n  for (size_t i=0; i<init.size(); ++i)\n      EXPECT(init[i] != actRekey[i]);\n\n  NonlinearFactorGraph expRekey;\n  // original measurements\n  expRekey.push_back(init[0]);\n  expRekey.push_back(init[1]);\n\n  // updated measurements\n  Point2 z3(0, -1),  z4(-1.5, -1.);\n  SharedDiagonal sigma0_2 = noiseModel::Isotropic::Sigma(2,0.2);\n  expRekey += simulated2D::Measurement(z3, sigma0_2, X(1), L(4));\n  expRekey += simulated2D::Measurement(z4, sigma0_2, X(2), L(4));\n\n  EXPECT(assert_equal(expRekey, actRekey));\n}\n\n/* ************************************************************************* */\nTEST( NonlinearFactorGraph, symbolic )\n{\n  NonlinearFactorGraph graph = createNonlinearFactorGraph();\n\n  SymbolicFactorGraph expected;\n  expected.push_factor(X(1));\n  expected.push_factor(X(1), X(2));\n  expected.push_factor(X(1), L(1));\n  expected.push_factor(X(2), L(1));\n\n  SymbolicFactorGraph actual = *graph.symbolic();\n\n  EXPECT(assert_equal(expected, actual));\n}\n\n/* ************************************************************************* */\nTEST(NonlinearFactorGraph, UpdateCholesky) {\n  NonlinearFactorGraph fg = createNonlinearFactorGraph();\n  Values initial = createNoisyValues();\n\n  // solve conventionally\n  GaussianFactorGraph linearFG = *fg.linearize(initial);\n  auto delta = linearFG.optimizeDensely();\n  auto expected = initial.retract(delta);\n\n  // solve with new method\n  EXPECT(assert_equal(expected, fg.updateCholesky(initial)));\n\n  // solve with Ordering\n  Ordering ordering;\n  ordering += L(1), X(2), X(1);\n  EXPECT(assert_equal(expected, fg.updateCholesky(initial, ordering)));\n\n  // solve with new method, heavily damped\n  auto dampen = [](const HessianFactor::shared_ptr& hessianFactor) {\n    auto iterator = hessianFactor->begin();\n    for (; iterator != hessianFactor->end(); iterator++) {\n      const auto index = std::distance(hessianFactor->begin(), iterator);\n      auto block = hessianFactor->info().diagonalBlock(index);\n      for (int j = 0; j < block.rows(); j++) {\n        block(j, j) += 1e9;\n      }\n    }\n  };\n  EXPECT(assert_equal(initial, fg.updateCholesky(initial, dampen), 1e-6));\n}\n\n/* ************************************************************************* */\n// Example from issue #452 which threw an ILS error. The reason was a very \n// weak prior on heading, which was tightened, and the ILS disappeared.\nTEST(testNonlinearFactorGraph, eliminate) {\n  // Linearization point\n  Pose2 T11(0, 0, 0);\n  Pose2 T12(1, 0, 0);\n  Pose2 T21(0, 1, 0);\n  Pose2 T22(1, 1, 0);\n\n  // Factor graph\n  auto graph = NonlinearFactorGraph();\n\n  // Priors\n  auto prior = noiseModel::Isotropic::Sigma(3, 1);\n  graph.addPrior(11, T11, prior);\n  graph.addPrior(21, T21, prior);\n\n  // Odometry\n  auto model = noiseModel::Diagonal::Sigmas(Vector3(0.01, 0.01, 0.3));\n  graph.add(BetweenFactor<Pose2>(11, 12, T11.between(T12), model));\n  graph.add(BetweenFactor<Pose2>(21, 22, T21.between(T22), model));\n\n  // Range factor\n  auto model_rho = noiseModel::Isotropic::Sigma(1, 0.01);\n  graph.add(RangeFactor<Pose2>(12, 22, 1.0, model_rho));\n\n  Values values;\n  values.insert(11, T11.retract(Vector3(0.1,0.2,0.3)));\n  values.insert(12, T12);\n  values.insert(21, T21);\n  values.insert(22, T22);\n  auto linearized = graph.linearize(values);\n\n  // Eliminate\n  Ordering ordering;\n  ordering += 11, 21, 12, 22;\n  auto bn = linearized->eliminateSequential(ordering);\n  EXPECT_LONGS_EQUAL(4, bn->size());\n}\n\n/* ************************************************************************* */\nTEST(testNonlinearFactorGraph, addPrior) {\n  Key k(0);\n\n  // Factor graph.\n  auto graph = NonlinearFactorGraph();\n\n  // Add a prior factor for key k.\n  auto model_double = noiseModel::Isotropic::Sigma(1, 1);\n  graph.addPrior<double>(k, 10, model_double);\n\n  // Assert the graph has 0 error with the correct values.\n  Values values;\n  values.insert(k, 10.0);\n  EXPECT_DOUBLES_EQUAL(0, graph.error(values), 1e-16);\n\n  // Assert the graph has some error with incorrect values.\n  values.clear();\n  values.insert(k, 11.0);\n  EXPECT(0 != graph.error(values));\n\n  // Clear the factor graph and values.\n  values.clear();\n  graph.erase(graph.begin(), graph.end());\n\n  // Add a Pose3 prior to the factor graph. Use a gaussian noise model by\n  // providing the covariance matrix.\n  Eigen::DiagonalMatrix<double, 6, 6> covariance_pose3;\n  covariance_pose3.setIdentity();\n  Pose3 pose{Rot3(), Point3(0, 0, 0)};\n  graph.addPrior(k, pose, covariance_pose3);\n\n  // Assert the graph has 0 error with the correct values.\n  values.insert(k, pose);\n  EXPECT_DOUBLES_EQUAL(0, graph.error(values), 1e-16);\n\n  // Assert the graph has some error with incorrect values.\n  values.clear();\n  Pose3 pose_incorrect{Rot3::RzRyRx(-M_PI, M_PI, -M_PI / 8), Point3(1, 2, 3)};\n  values.insert(k, pose_incorrect);\n  EXPECT(0 != graph.error(values));\n}\n\nTEST(NonlinearFactorGraph, printErrors)\n{\n  const NonlinearFactorGraph fg = createNonlinearFactorGraph();\n  const Values c = createValues();\n\n  // Test that it builds with default parameters.\n  // We cannot check the output since (at present) output is fixed to std::cout.\n  fg.printErrors(c);\n\n  // Second round: using callback filter to check that we actually visit all factors:\n  std::vector<bool> visited;\n  visited.assign(fg.size(), false);\n  const auto testFilter =\n      [&](const gtsam::Factor *f, double error, size_t index) {\n        EXPECT(f!=nullptr);\n        EXPECT(error>=.0);\n        visited.at(index)=true;\n        return false; // do not print\n      };\n  fg.printErrors(c,\"Test graph: \", gtsam::DefaultKeyFormatter,testFilter);\n\n  for (bool visit : visited) EXPECT(visit==true);\n}\n\n/* ************************************************************************* */\nint main() { TestResult tr; return TestRegistry::runAllTests(tr); }\n/* ************************************************************************* */\n", "meta": {"hexsha": "fdb080a63b3c031f90b253f007457f0b81cabc3d", "size": 10407, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/testNonlinearFactorGraph.cpp", "max_stars_repo_name": "zwn/gtsam", "max_stars_repo_head_hexsha": "3422c3bb66bef319d66a950857bb6ec073b43703", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1402.0, "max_stars_repo_stars_event_min_datetime": "2017-03-28T00:18:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T10:28:32.000Z", "max_issues_repo_path": "tests/testNonlinearFactorGraph.cpp", "max_issues_repo_name": "zwn/gtsam", "max_issues_repo_head_hexsha": "3422c3bb66bef319d66a950857bb6ec073b43703", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 851.0, "max_issues_repo_issues_event_min_datetime": "2017-11-27T15:09:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T22:26:38.000Z", "max_forks_repo_path": "tests/testNonlinearFactorGraph.cpp", "max_forks_repo_name": "zwn/gtsam", "max_forks_repo_head_hexsha": "3422c3bb66bef319d66a950857bb6ec073b43703", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 565.0, "max_forks_repo_forks_event_min_datetime": "2017-11-30T16:15:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T02:53:04.000Z", "avg_line_length": 33.0380952381, "max_line_length": 85, "alphanum_fraction": 0.6231382723, "num_tokens": 2643, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6584175005616829, "lm_q2_score": 0.7185943925708562, "lm_q1q2_score": 0.4731351238741439}}
{"text": "//////////////////////////////////////////////////////////////////////////////\n// distribution::toolkit::map_pdf::ratio_pdf::ratio_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_RATIO_PDF_RATIO_PDF_HPP_ER_2009\n#define BOOST_STATISTICS_DETAIL_DISTRIBUTION_TOOLKIT_MAP_PDF_RATIO_PDF_RATIO_PDF_HPP_ER_2009\n#include <boost/call_traits.hpp>\n#include <boost/statistics/detail/distribution_toolkit/map_pdf/inverse_pdf/inverse_pdf.hpp>\n#include <boost/statistics/detail/distribution_toolkit/map_pdf/product_pdf/product_pdf.hpp>\n\nnamespace boost{\nnamespace statistics{\nnamespace detail{\nnamespace distribution{\nnamespace toolkit{\n\n\n    template<typename A,typename B>\n    struct meta_ratio_pdf{\n        typedef inverse_pdf<B> inv_;\n        typedef product_pdf<A, inv_ > type;\n        static type call(const A& a,const B& b){\n            return type(\n                a,\n                inv_(b)\n            );\n         } \n    };\n\n    template<typename A,typename B>\n    typename meta_ratio_pdf<A,B>::type\n    make_ratio_pdf(const A& a, const B& b)\n    {\n        typedef meta_ratio_pdf<A,B> meta_;\n        return meta_::call(a,b);\n    }\n\n}// distribution\n}// toolkit\n}// detail\n}// statistics\n}// boost\n\n#endif\n", "meta": {"hexsha": "4aeed6299241be7fa6d70dd13dadd9883fce0798", "size": 1715, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "distribution_toolkit/boost/statistics/detail/distribution_toolkit/map_pdf/ratio_pdf/ratio_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/ratio_pdf/ratio_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/ratio_pdf/ratio_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": 35.0, "max_line_length": 92, "alphanum_fraction": 0.5714285714, "num_tokens": 344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185944046238981, "lm_q2_score": 0.6584174871563662, "lm_q1q2_score": 0.473135122177092}}
{"text": "/* \n * Copyright (c) 2021, Tetsuro Nagai\n */\n\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n#include <cmath>\n#include <cstring>\n#include <cassert>\n#include <string>\n#include <iomanip>\n#include <boost/program_options.hpp>\n#include <boost/format.hpp>\n#include <prettyprint.hpp>\n#include \"time_string.hpp\"\n\nconstexpr double kB=1.380649e-23  ;\nconstexpr double NA=6.02214076e23 ;\nconstexpr double kB_kJ_per_mol=kB*NA/1000 ;\nconstexpr int BUF_MAX=100000;\n\nconstexpr int DIM_HIST=1 ;\n\nusing std::string;\nusing std::vector;\nusing std::array;\nusing std::cout;\nusing std::cerr;\nusing std::endl;\nnamespace po=boost::program_options;\n\n\nint main(int argc, char *argv[])\n{\n\n  string starting_date;\n  misc::put_string_of_time(starting_date);\n  cout << \"Execution start at \" << starting_date <<endl;\n  \n  //get command line argments\n  double min,max,dx, T;\n  string fout_prefix;\n  bool bStrict;\n  \n  // making command line options\n  po::options_description opt(\"generic histogram and free energy. Data should be supplemented from the standard input; the first column will be analysed.\");\n  opt.add_options()\n    (\"help,h\" ,                                                   \"show help\")\n    (\"dx\"     ,      po::value<double>()->default_value(0.1),    \"dx, width of histogram\")\n    (\"min\"     ,     po::value<double>()->default_value(-10),    \"min of histogram\")\n    (\"max\"     ,     po::value<double>()->default_value(10),     \"max of histogram\")\n    (\"T\"     ,       po::value<double>()->default_value(300),     \"temperature for free energy convertion\")\n    (\"bStrictOutOfRange\"   , po::value<bool>()->default_value(false),     \"if true, abort when a sample out of min and max is found\")\n    (\"fout_prefix\",  po::value<string>(),                         \"fout_prefix, a number of files will be made with this prefix\");\n  \n  // analyze argc and argv and results are stored in vm\n  try{\n    po::variables_map vm;\n    store(parse_command_line(argc, argv, opt), vm);\n    notify(vm);\n    if(vm.count(\"help\")){\n      cout << opt << endl; // show help\n      exit(1);\n    }\n    else if(!vm.count(\"fout_prefix\")){\n      cerr << vm.count(\"fout_prefix\") << endl;\n      cerr << \"fout_prefix is mandatory \" << endl;\n      cerr << \"exit!!\" << endl;\n      exit(1);\n    }\n    else\n    {\n      dx = vm[\"dx\"].as<double>();\n      min = vm[\"min\"].as<double>();\n      max = vm[\"max\"].as<double>();\n      T = vm[\"T\"].as<double>();\n      bStrict = vm[\"bStrictOutOfRange\"].as<bool>();\n      fout_prefix = vm[\"fout_prefix\"].as<string>();\n\t\t}\n\t}\t\n  catch (boost::bad_any_cast &e) {\n    cout << e.what() << endl;\n  \tcout <<\"something wrong and buggy happend!!\"  << endl;\n  \tcout <<\"exit!!\"  << endl;\n  \texit(1);\n  }\n  catch (std::exception  &e) {\n    cout << e.what() << endl;\n    cout <<\"exit!!\"  << endl;\n    exit(2);\n  }\n\n  cout << \"**** Input parameters ****\"  << endl;\n  cout << \"dx: \" << dx << endl;\n  cout << \"min: \" << min << endl;\n  cout << \"max: \" << max << endl;\n  cout << \"T: \" << T << endl;\n  cout << \"bStrictOutOfRange: \" << bStrict << endl;\n  cout << \"fout_prefix: \" << fout_prefix << endl;\n  cout << \"*************************\\n\"  << endl;\n\n\tconst string fname_hist = fout_prefix+\"_hist.dat\";\n\tconst string fname_FE   = fout_prefix+\"_free_energy.dat\";\n\n  cout << \"Files to be created: \" << fname_hist << endl;\n  cout << \"Files to be created: \" << fname_FE  << endl;\n\n  std::ofstream ofs_hist(fname_hist.c_str());\n  std::ofstream ofs_FE(fname_FE.c_str());\n\n  if(!ofs_hist){\n    cerr << \"cannot open \" << fname_hist << endl;\n    return -1;\n  }\n  if(!ofs_FE){\n    cerr << \"cannot open \" << fname_FE << endl;\n    return -1;\n  }\n\n\n  if(max<=min){\n    cout << \"ERROR: max < min\" <<endl;\n    cerr << \"ERROR: max < min\" <<endl;\n    return -1;\n  }\n\n  const int  nbins = std::ceil((max-min)/dx);\n  vector<double>  edges(nbins+1,0);\n  vector<int>     counts(nbins);\n  vector<double>  pdf(nbins);\n  vector<double>  pdferr(nbins);\n  vector<double>  free_energy(nbins);\n  \n  for (int i = 0 ; i < nbins+1; i++){\n    edges[i] = min + dx*i ;\n  }\n\n\n  cout << \"**** parameters determined ****\"  << endl;\n  cout << \"nbins: \" << nbins <<endl;\n  cout << \"edges: \" << edges <<endl;\n  cout << \"*******************************\"  << endl;\n\n  double val;\n  string buf;\n  char tmp[BUF_MAX];\n  char* err;\n\n  auto get_ibin = [](double val,double min, double dx){return std::floor((val-min)/dx);};\n  int ibin;\n\n  while (std::getline(std::cin, buf))\n  {\n    auto bsscanf = std::sscanf(buf.c_str(), \"%s\" , tmp );\n    if(bsscanf != DIM_HIST){\n        cout << \"ERROR: not enough columns\\n\" << \"Exit!!\" <<endl;\n        cerr << \"ERROR: not enough columns\\n\" << \"Exit!!\" <<endl;\n        return -1;\n    }\n\n\n    val=std::strtod(tmp, &err);\n    if(*err!='\\0'){\n      cout << \"ERROR: error to convert: \" << tmp << \"\\nExit!!\" <<endl;\n      cerr << \"ERROR: error to convert: \" << tmp << \"\\nExit!!\" <<endl;\n      //continue;\n      return -1;\n    }\n    \n    ibin = get_ibin(val, min, dx);\n    if(val < min){\n      cout << \"min is too large: set min such that min < \" << val << endl;\n      cerr << \"min is too large: set min such that min < \" << val << endl;\n      ibin = 0;\n      if(bStrict){\n        cout << \"Abort at parsing: \" << buf << endl;\n        cerr << \"Abort at parsing: \" << buf << endl;\n        return -1;\n      }\n    }\n    if(val >= max){\n      cout << \"max is too small: set max such that max> \" << val << endl;\n      cerr << \"max is too small: set max such that max> \" << val << endl;\n      ibin = nbins-1;\n      if(bStrict){\n        cout << \"As bStrictOutOfRange is on, abort at parsing: \" << buf << endl;\n        cerr << \"As bStrictOutOfRange is on, abort at parsing: \" << buf << endl;\n        return -1;\n      }\n    }\n    counts[ibin]++;\n  }\n\n  int ncounts = std::accumulate(counts.begin(), counts.end(), 0);\n  cout << boost::format(\"In total, %d samples have been considered.\") % ncounts << endl;\n\n  for(int i=0; i < nbins; i++){\n    pdf[i] = counts[i]/double(ncounts)/dx;\n    pdferr[i] = std::sqrt((counts[i]/double(ncounts))*(1.0-counts[i]/double(ncounts))/double(ncounts)); //based on binary dist\n    pdferr[i] /= dx; \n    free_energy[i] = -kB_kJ_per_mol*T*std::log(pdf[i]);\n  }\n\n  double min_free_energy = *std::min_element(free_energy.begin(),free_energy.end());\n\n  for(auto  &v1: free_energy){\n    v1 -= min_free_energy;\n  }\n\n  cout << counts << endl;\n  cout << free_energy << endl;\n\n\n  for(int i= 0; i<nbins;i++){\n  ofs_hist << boost::format(\"%10.5f %12.6g %12.6g %12d\\n\") % (edges[i]+0.5*dx) % pdf[i]  %pdferr[i] %counts[i] ;\n  ofs_FE << boost::format(\"%10.5f %12.6g\\n\") % (edges[i]+0.5*dx) % free_energy[i] ;\n  }\n  ofs_hist.close();\n  ofs_FE.close();\n\n  return EXIT_SUCCESS ;\n}\n", "meta": {"hexsha": "05a3eb316067c4cfde0f4ade7abd1672ab1bd2d4", "size": 6687, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/histogram1d.cpp", "max_stars_repo_name": "tnagai-github/histogram", "max_stars_repo_head_hexsha": "89fc5427374a587958c636e208830f70578452d0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-31T03:32:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-31T03:32:49.000Z", "max_issues_repo_path": "src/histogram1d.cpp", "max_issues_repo_name": "tnagai-github/histogram", "max_issues_repo_head_hexsha": "89fc5427374a587958c636e208830f70578452d0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/histogram1d.cpp", "max_forks_repo_name": "tnagai-github/histogram", "max_forks_repo_head_hexsha": "89fc5427374a587958c636e208830f70578452d0", "max_forks_repo_licenses": ["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.5884955752, "max_line_length": 156, "alphanum_fraction": 0.5697622252, "num_tokens": 1927, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185944046238982, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.473135122177092}}
{"text": "#ifndef STAN_OPTIMIZATION_BFGS_UPDATE_HPP\n#define STAN_OPTIMIZATION_BFGS_UPDATE_HPP\n\n#include <Eigen/Dense>\n\nnamespace stan {\n  namespace optimization {\n    template<typename Scalar = double,\n             int DimAtCompile = Eigen::Dynamic>\n    class BFGSUpdate_HInv {\n    public:\n      typedef Eigen::Matrix<Scalar, DimAtCompile, 1> VectorT;\n      typedef Eigen::Matrix<Scalar, DimAtCompile, DimAtCompile> HessianT;\n\n      /**\n       * Update the inverse Hessian approximation.\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 approximation which is useful for predicting\n       * step-sizes.\n       **/\n      inline Scalar update(const VectorT &yk, const VectorT &sk,\n                           bool reset = false) {\n        Scalar rhok, skyk, B0fact;\n        HessianT Hupd;\n\n        skyk = yk.dot(sk);\n        rhok = 1.0/skyk;\n\n        Hupd.noalias() = HessianT::Identity(yk.size(), yk.size())\n                                        - rhok * sk * yk.transpose();\n        if (reset) {\n          B0fact = yk.squaredNorm()/skyk;\n          _Hk.noalias() = ((1.0/B0fact)*Hupd)*Hupd.transpose();\n        } else {\n          B0fact = 1.0;\n          _Hk = Hupd*_Hk*Hupd.transpose();\n        }\n        _Hk.noalias() += rhok*sk*sk.transpose();\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        pk.noalias() = -(_Hk*gk);\n      }\n\n    private:\n      HessianT _Hk;\n    };\n  }\n}\n\n#endif\n", "meta": {"hexsha": "86e0f114511015e8fabe54cf1dd7c24b2b55c31e", "size": 2056, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/stan/optimization/bfgs_update.hpp", "max_stars_repo_name": "drezap/stan", "max_stars_repo_head_hexsha": "9b319ed125e2a7d14d0c9c246d2f462dad668537", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-07-05T01:40:40.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-05T01:40:40.000Z", "max_issues_repo_path": "src/stan/optimization/bfgs_update.hpp", "max_issues_repo_name": "drezap/stan", "max_issues_repo_head_hexsha": "9b319ed125e2a7d14d0c9c246d2f462dad668537", "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/optimization/bfgs_update.hpp", "max_forks_repo_name": "drezap/stan", "max_forks_repo_head_hexsha": "9b319ed125e2a7d14d0c9c246d2f462dad668537", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-08-28T12:09:08.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-28T12:09:08.000Z", "avg_line_length": 31.1515151515, "max_line_length": 80, "alphanum_fraction": 0.594844358, "num_tokens": 509, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.473058649381661}}
{"text": "#include <CGAL/point_generators_2.h>\n#include <CGAL/Periodic_4_hyperbolic_Delaunay_triangulation_2.h>\n#include <CGAL/Periodic_4_hyperbolic_Delaunay_triangulation_traits_2.h>\n#include <CGAL/Hyperbolic_octagon_translation.h>\n#include <CGAL/Cartesian.h>\n#include <boost/tuple/tuple.hpp>\n#include <boost/random/linear_congruential.hpp>\n#include <boost/random/uniform_smallint.hpp>\n#include <boost/random/variate_generator.hpp>\n\n#include <iostream>\n\ntypedef CGAL::Periodic_4_hyperbolic_Delaunay_triangulation_traits_2<>               Traits;\ntypedef CGAL::Periodic_4_hyperbolic_Delaunay_triangulation_2<Traits>                Triangulation;\ntypedef Triangulation::Face_iterator                                                Face_iterator;\ntypedef Triangulation::Vertex_handle                                                Vertex_handle;\ntypedef Triangulation::Point                                                        Point;\ntypedef Triangulation::Vertex_iterator                                              Iter;\ntypedef Traits::Side_of_original_octagon                                            Side_of_original_octagon;\n\ntypedef CGAL::Cartesian<double>                                                     DKernel;\ntypedef DKernel::Point_2                                                            DPoint;\ntypedef CGAL::Creator_uniform_2<double, DPoint >                                    Creator;\n\nint main(int argc, char** argv)\n{\n  int N;\n  if(argc < 2)\n  {\n    std::cout << \"usage: \" << argv[0] << \" [number of points]\" << std::endl;\n    std::cout << \"generating 1000 points (default)!\" << std::endl;\n    N = 1000;\n  }\n  else\n  {\n    N = atoi(argv[1]);\n  }\n\n  int iters = 1;\n  if(argc == 3)\n    iters = atoi(argv[2]);\n\n\n  for(int itr = 0; itr < iters; ++itr)\n  {\n    Triangulation tr;\n\n    CGAL::Random_points_in_disc_2<DPoint, Creator> g(0.85);\n    Side_of_original_octagon pred;\n\n    int cnt = 0;\n    do {\n      DPoint pt = *g;\n      ++g;\n      if(pred(pt) != CGAL::ON_UNBOUNDED_SIDE) {\n        tr.insert(Point(pt.x(), pt.y()));\n        cnt++;\n      }\n    }\n    while(cnt < N);\n\n    tr.try_to_remove_dummy_vertices();\n    assert(tr.is_valid());\n\n    cnt = 0;\n    for(Iter it = tr.vertices_begin(); it != tr.vertices_end(); ++it) {\n      tr.remove(it);\n    }\n\n    std::cout << \"Final count of vertices: \" << tr.number_of_vertices() << std::endl;\n    assert(tr.is_valid());\n  }\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "3897bf513c783f222bcf9e3603aa05aefd40a9a0", "size": 2414, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Periodic_4_hyperbolic_triangulation_2/test/Periodic_4_hyperbolic_triangulation_2/test_p4ht2_removal.cpp", "max_stars_repo_name": "ffteja/cgal", "max_stars_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 3227.0, "max_stars_repo_stars_event_min_datetime": "2015-03-05T00:19:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:20:35.000Z", "max_issues_repo_path": "Periodic_4_hyperbolic_triangulation_2/test/Periodic_4_hyperbolic_triangulation_2/test_p4ht2_removal.cpp", "max_issues_repo_name": "ffteja/cgal", "max_issues_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 5574.0, "max_issues_repo_issues_event_min_datetime": "2015-03-05T00:01:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:08:11.000Z", "max_forks_repo_path": "Periodic_4_hyperbolic_triangulation_2/test/Periodic_4_hyperbolic_triangulation_2/test_p4ht2_removal.cpp", "max_forks_repo_name": "ffteja/cgal", "max_forks_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1274.0, "max_forks_repo_forks_event_min_datetime": "2015-03-05T00:01:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:47:56.000Z", "avg_line_length": 31.7631578947, "max_line_length": 109, "alphanum_fraction": 0.5737365369, "num_tokens": 591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186787341014, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4730586493816609}}
{"text": "\ufeff// SingleEyeFitter.cpp : Defines the entry point for the console application.\n//\n\n#include <boost/math/special_functions/sign.hpp>\n\n#include <Eigen/StdVector>\n\n#include <ceres/ceres.h>\n#include <ceres/problem.h>\n#include <ceres/autodiff_cost_function.h>\n#include <ceres/solver.h>\n#include <ceres/jet.h>\n\n#include <singleeyefitter/singleeyefitter.h>\n\n#include <singleeyefitter/utils.h>\n#include <singleeyefitter/cvx.h>\n#include <singleeyefitter/Conic.h>\n#include <singleeyefitter/Ellipse.h>\n#include <singleeyefitter/Circle.h>\n#include <singleeyefitter/Conicoid.h>\n#include <singleeyefitter/Sphere.h>\n#include <singleeyefitter/solve.h>\n#include <singleeyefitter/intersect.h>\n#include <singleeyefitter/projection.h>\n#include <singleeyefitter/fun.h>\n#include <singleeyefitter/math.h>\n\n#include \"distance.h\"\n\n#include <spii/spii.h>\n#include <spii/term.h>\n#include <spii/function.h>\n#include <spii/solver.h>\n\n#define _USE_MATH_DEFINES\n#include <math.h>\n\n\n\nnamespace ceres {\n    using singleeyefitter::math::sq;\n\n    template<typename T, int N>\n    inline Jet<T,N> sq(Jet<T,N> val) {\n        val.v *= 2*val.a;\n        val.a *= val.a;\n        return val;\n    }\n}\n\nnamespace singleeyefitter {\n\nstruct scalar_tag{};\nstruct ceres_jet_tag{};\n\ntemplate<typename T, typename Enabled=void>\nstruct ad_traits;\n\ntemplate<typename T>\nstruct ad_traits<T, typename std::enable_if< std::is_arithmetic<T>::value >::type >\n{\n    typedef scalar_tag ad_tag;\n    typedef T scalar;\n    static inline scalar value(const T& x) { return x; }\n};\n\ntemplate<typename T, int N>\nstruct ad_traits<::ceres::Jet<T,N>>\n{\n    typedef ceres_jet_tag ad_tag;\n    typedef T scalar;\n    static inline scalar get(const ::ceres::Jet<T,N>& x) { return x.a; }\n};\n\ntemplate<typename T>\nstruct ad_traits<T, typename std::enable_if< !std::is_same<T, typename std::decay<T>::type>::value >::type >\n    : public ad_traits<typename std::decay<T>::type>\n{\n};\n\ntemplate<typename T>\ninline T smootherstep(T edge0, T edge1, T x, scalar_tag)\n{\n    if (x >= edge1)\n        return T(1);\n    else if (x <= edge0)\n        return T(0);\n    else {\n        x = (x - edge0)/(edge1 - edge0);\n        return x*x*x*(x*(x*T(6) - T(15)) + T(10));\n    }\n}\ntemplate<typename T, int N>\ninline ::ceres::Jet<T,N> smootherstep(T edge0, T edge1, const ::ceres::Jet<T,N>& f, ceres_jet_tag)\n{\n    if (f.a >= edge1)\n        return ::ceres::Jet<T,N>(1);\n    else if (f.a <= edge0)\n        return ::ceres::Jet<T,N>(0);\n    else {\n        T x = (f.a - edge0)/(edge1 - edge0);\n\n        // f is referenced by this function, so create new value for return.\n        ::ceres::Jet<T,N> g;\n        g.a = x*x*x*(x*(x*T(6) - T(15)) + T(10));\n        g.v = f.v * (x*x*(x*(x*T(30) - T(60)) + T(30))/(edge1 - edge0));\n        return g;\n    }\n}\ntemplate<typename T, int N>\ninline ::ceres::Jet<T,N> smootherstep(T edge0, T edge1, ::ceres::Jet<T,N>&& f, ceres_jet_tag)\n{\n    if (f.a >= edge1)\n        return ::ceres::Jet<T,N>(1);\n    else if (f.a <= edge0)\n        return ::ceres::Jet<T,N>(0);\n    else {\n        T x = (f.a - edge0)/(edge1 - edge0);\n\n        // f is moved into this function, so reuse it.\n        f.a = x*x*x*(x*(x*T(6) - T(15)) + T(10));\n        f.v *= (x*x*(x*(x*T(30) - T(60)) + T(30))/(edge1 - edge0));\n        return f;\n    }\n}\ntemplate<typename T>\ninline auto smootherstep(typename ad_traits<T>::scalar edge0, typename ad_traits<T>::scalar edge1, T&& val)\n    -> decltype(smootherstep(edge0, edge1, std::forward<T>(val), typename ad_traits<T>::ad_tag()))\n{\n    return smootherstep(edge0, edge1, std::forward<T>(val), typename ad_traits<T>::ad_tag());\n}\n\ntemplate<typename T>\ninline T norm(T x, T y, scalar_tag) {\n    using std::sqrt;\n    using math::sq;\n\n    return sqrt(sq(x) + sq(y));\n}\ntemplate<typename T, int N>\ninline ::ceres::Jet<T,N> norm(const ::ceres::Jet<T,N>& x, const ::ceres::Jet<T,N>& y, ceres_jet_tag) {\n    T anorm = norm<T>(x.a, y.a, scalar_tag());\n\n    ::ceres::Jet<T,N> g;\n    g.a = anorm;\n    g.v = (x.a/anorm)*x.v + (y.a/anorm)*y.v;\n\n    return g;\n}\ntemplate<typename T>\ninline typename std::decay<T>::type norm(T&& x, T&& y) {\n    return norm(std::forward<T>(x), std::forward<T>(y), typename ad_traits<T>::ad_tag());\n}\n\ntemplate<typename T>\ninline auto Heaviside(T&& val, typename ad_traits<T>::scalar epsilon) -> decltype(smootherstep(-epsilon, epsilon, std::forward<T>(val))) {\n    return smootherstep(-epsilon, epsilon, std::forward<T>(val));\n}\n\ntemplate<typename Scalar>\ncv::Rect bounding_box(const Ellipse2D<Scalar>& ellipse) {\n    using std::sin;\n    using std::cos;\n    using std::sqrt;\n    using std::floor;\n    using std::ceil;\n\n    Scalar ux = ellipse.major_radius * cos(ellipse.angle);\n    Scalar uy = ellipse.major_radius * sin(ellipse.angle);\n    Scalar vx = ellipse.minor_radius * cos(ellipse.angle + PI/2);\n    Scalar vy = ellipse.minor_radius * sin(ellipse.angle + PI/2);\n\n    Scalar bbox_halfwidth = sqrt(ux*ux + vx*vx);\n    Scalar bbox_halfheight = sqrt(uy*uy + vy*vy);\n\n    return cv::Rect((int)floor(ellipse.centre[0] - bbox_halfwidth), (int)floor(ellipse.centre[1] - bbox_halfheight),\n\t\t(int)(2.0 * ceil(bbox_halfwidth) + 1.0),\n\t\t(int)(2.0 * ceil(bbox_halfheight) + 1.0));\n}\n\n// Calculates:\n//     r * (1 - ||A(p - t)||)\n//\n//          ||A(p - t)||   maps the ellipse to a unit circle\n//      1 - ||A(p - t)||   measures signed distance from unit circle edge\n// r * (1 - ||A(p - t)||)  scales this to major radius of ellipse, for (roughly) pixel distance\n//\n// Actually use (r - ||rAp - rAt||) and precalculate r, rA and rAt.\ntemplate<typename T>\nclass EllipseDistCalculator {\npublic:\n    typedef typename ad_traits<T>::scalar Const;\n\n    EllipseDistCalculator(const Ellipse2D<T>& ellipse) : r(ellipse.major_radius)\n    {\n        using std::sin;\n        using std::cos;\n        rA << r*cos(ellipse.angle)/ellipse.major_radius, r*sin(ellipse.angle)/ellipse.major_radius,\n             -r*sin(ellipse.angle)/ellipse.minor_radius, r*cos(ellipse.angle)/ellipse.minor_radius;\n        rAt = rA*ellipse.centre;\n    }\n    template<typename U>\n    T operator()(U&& x, U&& y) {\n        return calculate(std::forward<U>(x), std::forward<U>(y), typename ad_traits<T>::ad_tag(), typename ad_traits<U>::ad_tag());\n    }\n\n    template<typename U>\n    T calculate(U&& x, U&& y, scalar_tag, scalar_tag) {\n        T rAxt((rA(0,0) * x + rA(0,1) * y) - rAt[0]);\n        T rAyt((rA(1,0) * x + rA(1,1) * y) - rAt[1]);\n\n        T xy_dist = norm(rAxt, rAyt);\n\n        return (r - xy_dist);\n    }\n\n    // Expanded versions for Jet calculations so that Eigen can do some of its expression magic\n    template<typename U>\n    T calculate(U&& x, U&& y, scalar_tag, ceres_jet_tag) {\n        T rAxt(rA(0,0) * x.a + rA(0,1) * y.a - rAt[0],\n            rA(0,0) * x.v + rA(0,1) * y.v);\n        T rAyt(rA(1,0) * x.a + rA(1,1) * y.a - rAt[1],\n            rA(1,0) * x.v + rA(1,1) * y.v);\n\n        T xy_dist = norm(rAxt, rAyt);\n\n        return (r - xy_dist);\n    }\n    template<typename U>\n    T calculate(U&& x, U&& y, ceres_jet_tag, scalar_tag) {\n        T rAxt(rA(0,0).a * x + rA(0,1).a * y - rAt[0].a,\n            rA(0,0).v * x + rA(0,1).v * y - rAt[0].v);\n        T rAyt(rA(1,0).a * x + rA(1,1).a * y - rAt[1].a,\n            rA(1,0).v * x + rA(1,1).v * y - rAt[1].v);\n\n        T xy_dist = norm(rAxt, rAyt);\n\n        return (r - xy_dist);\n    }\n    template<typename U>\n    T calculate(U&& x, U&& y, ceres_jet_tag, ceres_jet_tag) {\n        T rAxt(rA(0,0).a * x.a + rA(0,1).a * y.a - rAt[0].a,\n            rA(0,0).v * x.a + rA(0,0).a * x.v + rA(0,1).v * y.a + rA(0,1).a * y.v - rAt[0].v);\n        T rAyt(rA(1,0).a * x.a + rA(1,1).a * y.a - rAt[1].a,\n            rA(1,0).v * x.a + rA(1,0).a * x.v + rA(1,1).v * y.a + rA(1,1).a * y.v - rAt[1].v);\n\n        T xy_dist = norm(rAxt, rAyt);\n\n        return (r - xy_dist);\n    }\nprivate:\n    Eigen::Matrix<T, 2, 2> rA;\n    Eigen::Matrix<T, 2, 1> rAt;\n    T r;\n};\n\n// Calculates the x crossings of a conic at a given y value. Returns the number of crossings (0, 1 or 2)\ntemplate<typename Scalar>\nint getXCrossing(const Conic<Scalar>& conic, Scalar y, Scalar& x1, Scalar& x2) {\n    using std::sqrt;\n\n    Scalar a = conic.A;\n    Scalar b = conic.B*y + conic.D;\n    Scalar c = conic.C*y*y + conic.E*y + conic.F;\n\n    Scalar det = b*b - 4*a*c;\n    if (det == 0) {\n        x1 = -b/(2*a);\n        return 1;\n    } else if (det < 0) {\n        return 0;\n    } else {\n        Scalar sqrtdet = sqrt(det);\n        x1 = (-b - sqrtdet)/(2*a);\n        x2 = (-b + sqrtdet)/(2*a);\n        return 2;\n    }\n}\n\ntemplate<template<class, int> class Jet, class T, int N>\ntypename std::enable_if<std::is_same<typename ad_traits<Jet<T,N>>::ad_tag, ceres_jet_tag>::value, Ellipse2D<T>>::type\ntoConst(const Ellipse2D<Jet<T,N>>& ellipse) {\n    return Ellipse2D<T>(\n        ellipse.centre[0].a,\n        ellipse.centre[1].a,\n        ellipse.major_radius.a,\n        ellipse.minor_radius.a,\n        ellipse.angle.a);\n}\n\ntemplate<class T>\nEllipse2D<T> scaledMajorRadius(const Ellipse2D<T>& ellipse, const T& target_radius) {\n    return Ellipse2D<T>(\n        ellipse.centre[0],\n        ellipse.centre[1],\n        target_radius,\n        target_radius * ellipse.minor_radius/ellipse.major_radius,\n        ellipse.angle);\n};\n\nnamespace internal {\n    template<class T> T ellipseGoodness(const Ellipse2D<T>& ellipse, const cv::Mat_<uint8_t>& eye, T band_width, T step_epsilon, scalar_tag);\n    template<class T> T ellipseGoodness(const Ellipse2D<T>& ellipse, const cv::Mat_<uint8_t>& eye, typename ad_traits<T>::scalar band_width, typename ad_traits<T>::scalar step_epsilon, ceres_jet_tag);\n}\n\n// Calculates the \"goodness\" of an ellipse.\n//\n// This is defined as the difference in region means:\n//\n//    \u03bc\u207b - \u03bc\u207a\n//\n// where\n//         \u03a3_p (H(d(p)+w) - H(d(p))) I(p)\n//    \u03bc\u207b = ------------------------------\n//           \u03a3_p (H(d(p)+w) - H(d(p)))\n//\n//         \u03a3_p (H(d(p)+w) - H(d(p))) I(p)\n//    \u03bc\u207a = ------------------------------\n//           \u03a3_p (H(d(p)+w) - H(d(p)))\n//\n// (see eqs 16, 20, 21 in the PETMEI paper)\n//\n// The ellipse distance d(p) is defined as\n//\n//    d(p) = r * (1 - ||A(p - t)||)\n//\n// with r as the major radius and A as the matrix that transforms the ellipse to a unit circle.\n//\n//          ||A(p - t)||   maps the ellipse to a unit circle\n//      1 - ||A(p - t)||   measures signed distance from unit circle edge\n// r * (1 - ||A(p - t)||)  scales this to major radius of ellipse, for (roughly) pixel distance\n//\ntemplate<class T>\ninline T ellipseGoodness(const Ellipse2D<T>& ellipse, const cv::Mat_<uint8_t>& eye, typename ad_traits<T>::scalar band_width, typename ad_traits<T>::scalar step_epsilon) {\n    // band_width     The width of each band (inner and outer)\n    // step_epsilon   The epsilon of the soft step function\n\n    return internal::ellipseGoodness<T>(ellipse, eye, band_width, step_epsilon, typename ad_traits<T>::ad_tag());\n}\n\n//#define DEBUG_ELLIPSE_GOODNESS\n//#define USE_INLINED_ELLIPSE_DIST\n\n#ifdef USE_INLINED_ELLIPSE_DIST\n#define IF_INLINED_ELLIPSE_DIST(...) __VA_ARGS__\n#else\n#define IF_INLINED_ELLIPSE_DIST(...)\n#endif\n\nnamespace internal {\n// Non autodiff version of ellipse goodness calculation\ntemplate<class T>\nT ellipseGoodness(const Ellipse2D<T>& ellipse, const cv::Mat_<uint8_t>& eye, T band_width, T step_epsilon, scalar_tag) {\n    using std::max;\n    using std::min;\n    using std::ceil;\n    using std::floor;\n    using std::sin;\n    using std::cos;\n\n    // Ellipses (and corresponding conics) delimiting the region in which the band masks will be non-zero\n    Ellipse2D<T> outerEllipse = scaledMajorRadius(ellipse, ellipse.major_radius + ((band_width + step_epsilon) + 0.5));\n    Ellipse2D<T> innerEllipse = scaledMajorRadius(ellipse, ellipse.major_radius - ((band_width + step_epsilon) + 0.5));\n    Conic<T> outerConic(outerEllipse);\n    Conic<T> innerConic(innerEllipse);\n\n    // Variables for calculating the mean\n    T sum_inner = T(0), count_inner = T(0), sum_outer = T(0), count_outer = T(0);\n\n    // Only iterate over pixels within the outer ellipse's bounding box\n    cv::Rect bb = bounding_box(outerEllipse);\n    bb &= cv::Rect(-eye.cols/2,-eye.rows/2,eye.cols,eye.rows);\n\n\n#ifndef USE_INLINED_ELLIPSE_DIST\n    // Ellipse distance calculator\n    EllipseDistCalculator<T> ellipDist(ellipse);\n#else\n    // Instead of calculating\n    //     r * (1 - ||A(p - t)||)\n    // we use\n    //     (r - ||rAp - rAt||)\n    // and precalculate r, rA and rAt.\n    Eigen::Matrix<T, 2, 2> rA;\n    T r = ellipse.major_radius;\n    rA << r*cos(ellipse.angle)/ellipse.major_radius, r*sin(ellipse.angle)/ellipse.major_radius,\n        -r*sin(ellipse.angle)/ellipse.minor_radius, r*cos(ellipse.angle)/ellipse.minor_radius;\n    Eigen::Matrix<T, 2, 1> rAt = rA*ellipse.centre;\n\n    // Actually,\n    ///    rAp - rAt = rA(0,y) + rA(x,0) - rAt\n    // So, can perform a strength reduction to calculate rAp iteratively.\n\n    // rA(0,y) - rAt, with y_0 = bb.y\n    Eigen::Matrix<T, 2, 1> rA0yrAt(rA(0,1) * bb.y - rAt[0], rA(1,1) * bb.y - rAt[1]);\n    // rA(1,0), for incrementing x\n    Eigen::Matrix<T, 2, 1> rA10 = rA.col(0);\n    // rA(0,1), for incrementing y\n    Eigen::Matrix<T, 2, 1> rA01 = rA.col(1);\n#endif\n\n    for (int i = bb.y; i < bb.y + bb.height; ++i IF_INLINED_ELLIPSE_DIST(, rA0yrAt += rA01)) {\n        // Image row pointer -- (0,0) is centre of image, so shift accordingly\n        const uint8_t* eye_i = eye[i + eye.rows/2];\n\n        // Only iterate over pixels between the inner and outer ellipse\n        T ox1, ox2;\n        int outerCrossings = getXCrossing<T>(outerConic, i, ox1, ox2);\n        if (outerCrossings < 2) {\n            // If we don't cross the outer ellipse at all, exit early\n            continue;\n        }\n        T ix1, ix2;\n        int innerCrossings = innerEllipse.minor_radius > 0 ? getXCrossing<T>(innerConic, i, ix1, ix2) : 0;\n\n        // Define pairs of x values to iterate between\n        std::vector<std::pair<int,int>> xpairs;\n        if (innerCrossings < 2) {\n            // If we don't cross the inner ellipse, iterate between the two crossings of the outer ellipse\n            xpairs.emplace_back(max<int>((int)floor(ox1),bb.x), min<int>((int)ceil(ox2), bb.x+bb.width-1));\n        } else {\n            // Otherwise, iterate between outer-->inner, then inner-->outer.\n            xpairs.emplace_back(max<int>((int)floor(ox1),bb.x), min<int>((int)ceil(ix1), bb.x+bb.width-1));\n            xpairs.emplace_back(max<int>((int)floor(ix2),bb.x), min<int>((int)ceil(ox2), bb.x+bb.width-1));\n        }\n\n        // Go over x pairs (that is, outer-->outer or outer-->inner,inner-->outer)\n        for (const auto& xpair : xpairs) {\n            // Pixel pointer, shifted accordingly\n            const uint8_t* eye_ij = eye_i + xpair.first + eye.cols/2;\n\n#ifdef USE_INLINED_ELLIPSE_DIST\n            // rA(0,y) + rA(x,0) - rAt, with x_0 = xpair.first\n            Eigen::Matrix<T, 2, 1> rApt(rA0yrAt(0) + rA(0,0)*xpair.first, rA0yrAt(1) + rA(1,0)*xpair.first);\n#endif\n\n            for (int j = xpair.first; j <= xpair.second; ++j, ++eye_ij IF_INLINED_ELLIPSE_DIST(, rApt += rA10)) {\n                auto eye_ij_val = *eye_ij;\n                if (eye_ij_val > 200) {\n                    // Ignore bright areas (i.e. glints)\n                    continue;\n                }\n\n#ifdef USE_INLINED_ELLIPSE_DIST\n                T dist = (r - norm(rApt(0), rApt(1)));\n#else\n                T dist = ellipDist(T(j), T(i));\n#endif\n\n                // Calculate mask values for each band\n                T Hellip = Heaviside(dist, step_epsilon);\n                T Houter = Heaviside(dist+band_width, step_epsilon);\n                T Hinner = Heaviside(dist-band_width, step_epsilon);\n\n                T outer_weight = (Houter - Hellip);\n                T inner_weight = (Hellip - Hinner);\n\n                sum_outer += outer_weight * eye_ij_val;\n                count_outer += outer_weight;\n\n                sum_inner += inner_weight * eye_ij_val;\n                count_inner += inner_weight;\n            }\n        }\n    }\n\n    // Get mean values, defaulting to 255 and 0 if count_inner/count_outer are 0 (respectively)\n    // Using 255 and 0 because these are the \"worst\" values, so some pixels will be preferred over none.\n    T mu_inner = (count_inner==0 ? 255 : sum_inner/count_inner);\n    T mu_outer = (count_outer==0 ? 0 : sum_outer/count_outer);\n\n    // If count < 100 pixels, interpolate between mean value and \"worst\" value. This will push the\n    // gradient away from small pixel counts in a vaguely smooth way.\n    if (count_outer < 100) {\n        mu_outer = math::lerp<T>(0, mu_outer, count_outer/100.0);\n    }\n    if (count_inner < 100) {\n        mu_inner = math::lerp<T>(255, mu_inner, count_inner/100.0);\n    }\n\n    // Return difference of mean values\n    return mu_outer - mu_inner;\n}\n\n// Autodiff version of ellipse goodness calculation\ntemplate<class Jet>\nJet ellipseGoodness(const Ellipse2D<Jet>& ellipse, const cv::Mat_<uint8_t>& eye, typename ad_traits<Jet>::scalar band_width, typename ad_traits<Jet>::scalar step_epsilon, ceres_jet_tag) {\n    using std::max;\n    using std::min;\n    using std::ceil;\n    using std::floor;\n\n#ifdef DEBUG_ELLIPSE_GOODNESS\n    cv::Mat_<cv::Vec3b> eye_proc = cv::Mat_<cv::Vec3b>::zeros(eye.rows, eye.cols);\n    cv::Mat_<cv::Vec3b> eye_H = cv::Mat_<cv::Vec3b>::zeros(eye.rows, eye.cols);\n#endif\n\n    typedef typename ad_traits<Jet>::scalar T;\n    typedef Jet Jet_t;\n\n    // A constant version of the ellipse\n    Ellipse2D<T> constEllipse = toConst(ellipse);\n\n    // Ellipses (and corresponding conics) delimiting the region in which the band masks will be non-zero\n    Ellipse2D<T> constOuterEllipse = scaledMajorRadius(constEllipse, constEllipse.major_radius + ((band_width + step_epsilon) + 0.5));\n    Ellipse2D<T> constInnerEllipse = scaledMajorRadius(constEllipse, constEllipse.major_radius - ((band_width + step_epsilon) + 0.5));\n    Conic<T> constOuterConic(constOuterEllipse);\n    Conic<T> constInnerConic(constInnerEllipse);\n\n    // Variables for calculating the mean\n    Jet_t sum_inner = Jet_t(0), count_inner = Jet_t(0), sum_outer = Jet_t(0), count_outer = Jet_t(0);\n\n    // Only iterate over pixels within the outer ellipse's bounding box\n    cv::Rect bb = bounding_box(constOuterEllipse);\n    bb &= cv::Rect(-eye.cols/2,-eye.rows/2,eye.cols,eye.rows);\n\n\n#ifndef USE_INLINED_ELLIPSE_DIST\n    // Ellipse distance calculator\n    EllipseDistCalculator<Jet_t> ellipDist(ellipse);\n    EllipseDistCalculator<T> constEllipDist(constEllipse);\n#else\n    // Instead of calculating\n    //     r * (1 - ||A(p - t)||)\n    // we use\n    //     (r - ||rAp - rAt||)\n    // and precalculate r, rA and rAt.\n    Eigen::Matrix<T, 2, 2> rA;\n    T r = constEllipse.major_radius;\n    rA << r*cos(constEllipse.angle)/constEllipse.major_radius, r*sin(constEllipse.angle)/constEllipse.major_radius,\n         -r*sin(constEllipse.angle)/constEllipse.minor_radius, r*cos(constEllipse.angle)/constEllipse.minor_radius;\n    Eigen::Matrix<T, 2, 1> rAt = rA*constEllipse.centre;\n\n    // And non-constant versions of the above\n    Eigen::Matrix<Jet_t, 2, 2> rA_jet;\n    Jet_t r_jet = ellipse.major_radius;\n    rA_jet << r_jet*cos(ellipse.angle)/ellipse.major_radius, r_jet*sin(ellipse.angle)/ellipse.major_radius,\n             -r_jet*sin(ellipse.angle)/ellipse.minor_radius, r_jet*cos(ellipse.angle)/ellipse.minor_radius;\n    Eigen::Matrix<Jet_t, 2, 1> rAt_jet = rA_jet*ellipse.centre;\n\n    // Actually,\n    ///    rAp - rAt = rA(0,y) + rA(x,0) - rAt\n    // So, can perform a strength reduction to calculate rAp iteratively.\n\n    // rA(0,y) - rAt, with y_0 = bb.y\n    Eigen::Matrix<T, 2, 1> rA0yrAt(rA(0,1) * bb.y - rAt[0], rA(1,1) * bb.y - rAt[1]);\n    // rA(1,0), for incrementing x\n    Eigen::Matrix<T, 2, 1> rA10 = rA.col(0);\n    // rA(0,1), for incrementing y\n    Eigen::Matrix<T, 2, 1> rA01 = rA.col(1);\n#endif\n\n    for (int i = bb.y; i < bb.y + bb.height; ++i IF_INLINED_ELLIPSE_DIST(, rA0yrAt += rA01)) {\n        // Image row pointer -- (0,0) is centre of image, so shift accordingly\n        const uint8_t* eye_i = eye[i + eye.rows/2];\n\n        // Only iterate over pixels between the inner and outer ellipse\n        T ox1, ox2;\n        int outerCrossings = getXCrossing<T>(constOuterConic, i, ox1, ox2);\n        if (outerCrossings < 2) {\n            // If we don't cross the outer ellipse at all, exit early\n            continue;\n        }\n        T ix1, ix2;\n        int innerCrossings = constInnerEllipse.major_radius > 0 ? getXCrossing<T>(constInnerConic, i, ix1, ix2) : 0;\n\n        // Define pairs of x values to iterate between\n        std::vector<std::pair<int,int>> xpairs;\n        if (innerCrossings < 2) {\n            // If we don't cross the inner ellipse, iterate between the two crossings of the outer ellipse\n            xpairs.emplace_back(max<int>((int)floor(ox1),bb.x), min<int>((int)ceil(ox2), bb.x+bb.width-1));\n        } else {\n            // Otherwise, iterate between outer-->inner, then inner-->outer.\n            xpairs.emplace_back(max<int>((int)floor(ox1),bb.x), min<int>((int)ceil(ix1), bb.x+bb.width-1));\n            xpairs.emplace_back(max<int>((int)floor(ix2),bb.x), min<int>((int)ceil(ox2), bb.x+bb.width-1));\n        }\n\n#ifdef USE_INLINED_ELLIPSE_DIST\n        // Precalculate the gradient of\n        //     rA(y,0) - rAt\n        auto rAy0rAt_x_v = (rA_jet(0,1).v * i - rAt_jet(0).v).eval();\n        auto rAy0rAt_y_v = (rA_jet(1,1).v * i - rAt_jet(1).v).eval();\n#endif\n\n        // Go over x pairs (that is, outer-->outer or outer-->inner,inner-->outer)\n        for (const auto& xpair : xpairs) {\n\n            // Pixel pointer, shifted accordingly\n            const uint8_t* eye_ij = eye_i + xpair.first + eye.cols/2;\n\n#ifdef USE_INLINED_ELLIPSE_DIST\n            // rA(0,y) + rA(x,0) - rAt, with x_0 = xpair.first\n            Eigen::Matrix<T, 2, 1> rApt(rA0yrAt(0) + rA(0,0)*xpair.first, rA0yrAt(1) + rA(1,0)*xpair.first);\n#endif\n\n            for (int j = xpair.first; j <= xpair.second; ++j, ++eye_ij IF_INLINED_ELLIPSE_DIST(, rApt += rA10)) {\n\n                T eye_ij_val = *eye_ij;\n                if (eye_ij_val > 200) {\n                    // Ignore bright areas (i.e. glints)\n                    continue;\n                }\n\n                // Calculate signed ellipse distance without gradient first, in case the gradient is 0\n#ifdef USE_INLINED_ELLIPSE_DIST\n                T dist_const = (r - norm(rApt(0), rApt(1)));\n#else\n                T dist_const = constEllipDist(T(j), T(i));\n#endif\n\n                // Check if we are within step_epsilon of the edges of the bands. If yes, calculate\n                // the gradient. Otherwise, the gradient is known to be 0.\n                if (abs(dist_const) < step_epsilon\n                    || abs(dist_const-band_width) < step_epsilon\n                    || abs(dist_const+band_width) < step_epsilon) {\n\n#ifdef USE_INLINED_ELLIPSE_DIST\n                    // Calculate the gradients of rApt, and use those to get the dist\n                    Jet_t rAxt_jet(rApt(0),\n                        rA_jet(0,0).v * j + rAy0rAt_x_v);\n                    Jet_t rAyt_jet(rApt(1),\n                        rA_jet(1,0).v * j + rAy0rAt_y_v);\n\n                    //Eigen::Matrix<Jet,2,1> rApt_jet2 = rA_jet*Eigen::Matrix<Jet,2,1>(Jet(j),Jet(i)) - rAt_jet;\n\n                    Jet_t dist = (r_jet - norm(rAxt_jet, rAyt_jet));\n                    //Jet_t dist2 = ellipDist(T(j), T(i));\n#else\n                    Jet_t dist = ellipDist(T(j), T(i));\n#endif\n\n                    // Calculate mask values and derivatives for each band\n                    Jet_t Hellip = Heaviside(dist, step_epsilon);\n                    Jet_t Houter = Heaviside(dist+band_width, step_epsilon);\n                    Jet_t Hinner = Heaviside(dist-band_width, step_epsilon);\n\n                    Jet_t outer_weight = (Houter - Hellip);\n                    Jet_t inner_weight = (Hellip - Hinner);\n\n                    // Inline the Jet operator+= to allow eigen expression and noalias magic.\n                    sum_outer.a += outer_weight.a * eye_ij_val;\n                    sum_outer.v.noalias() += outer_weight.v * eye_ij_val;\n                    count_outer.a += outer_weight.a;\n                    count_outer.v.noalias() += outer_weight.v;\n\n                    sum_inner.a += inner_weight.a * eye_ij_val;\n                    sum_inner.v.noalias() += inner_weight.v * eye_ij_val;\n                    count_inner.a += inner_weight.a;\n                    count_inner.v.noalias() += inner_weight.v;\n\n                    #ifdef DEBUG_ELLIPSE_GOODNESS\n                        eye_H(i + eye.rows/2,j + eye.cols/2)[2] = outer_weight.a*255;\n                        eye_H(i + eye.rows/2,j + eye.cols/2)[1] = inner_weight.a*255;\n                        eye_H(i + eye.rows/2,j + eye.cols/2)[0] = 255;\n\n                        eye_proc(i + eye.rows/2,j + eye.cols/2)[2] = outer_weight.a * eye_ij_val;\n                        eye_proc(i + eye.rows/2,j + eye.cols/2)[1] = inner_weight.a * eye_ij_val;\n                        eye_proc(i + eye.rows/2,j + eye.cols/2)[0] = 255;\n                    #endif\n\n                } else {\n                    // Calculate mask values for each band\n                    T Hellip = Heaviside(dist_const, step_epsilon);\n                    T Houter = Heaviside(dist_const+band_width, step_epsilon);\n                    T Hinner = Heaviside(dist_const-band_width, step_epsilon);\n\n                    T outer_weight = (Houter - Hellip);\n                    T inner_weight = (Hellip - Hinner);\n\n                    sum_outer.a += outer_weight * eye_ij_val;\n                    count_outer.a += outer_weight;\n\n                    sum_inner.a += inner_weight * eye_ij_val;\n                    count_inner.a += inner_weight;\n\n                    #ifdef DEBUG_ELLIPSE_GOODNESS\n                    eye_H(i + eye.rows/2,j + eye.cols/2)[2] = outer_weight*255;\n                    eye_H(i + eye.rows/2,j + eye.cols/2)[1] = inner_weight*255;\n                    eye_H(i + eye.rows/2,j + eye.cols/2)[0] = 0;\n\n                    eye_proc(i + eye.rows/2,j + eye.cols/2)[2] = outer_weight * eye_ij_val;\n                    eye_proc(i + eye.rows/2,j + eye.cols/2)[1] = inner_weight * eye_ij_val;\n                    eye_proc(i + eye.rows/2,j + eye.cols/2)[0] = 255;\n                    #endif\n                }\n            }\n        }\n    }\n\n    // Get mean values, defaulting to 255 and 0 if count_inner/count_outer are 0 (respectively)\n    // Using 255 and 0 because these are the \"worst\" values, so some pixels will be preferred over none.\n    Jet mu_inner = (count_inner.a==0 ? Jet(255) : sum_inner/count_inner);\n    Jet mu_outer = (count_outer.a==0 ? Jet(0) : sum_outer/count_outer);\n\n    // If count < 100 pixels, interpolate between mean value and \"worst\" value. This will push the\n    // gradient away from small pixel counts in a vaguely smooth way.\n    if (count_outer.a < 100) {\n        mu_outer = math::lerp<Jet>(Jet(0), mu_outer, count_outer/100.0);\n    }\n    if (count_inner.a < 100) {\n        mu_inner = math::lerp<Jet>(Jet(255), mu_inner, count_inner/100.0);\n    }\n\n    // Return difference of mean values\n    return mu_outer - mu_inner;\n}\n}\n\ntemplate<typename T>\nEigen::Matrix<T,3,1> sph2cart(T r, T theta, T psi) {\n    using std::sin;\n    using std::cos;\n\n    return r * Eigen::Matrix<T,3,1>(sin(theta)*cos(psi), cos(theta), sin(theta)*sin(psi));\n}\n\ntemplate<typename T>\nT angleDiffGoodness(T theta1, T psi1, T theta2, T psi2, typename ad_traits<T>::scalar sigma) {\n    using std::sin;\n    using std::cos;\n    using std::acos;\n    using std::asin;\n    using std::atan2;\n    using std::sqrt;\n\n    if (theta1 == theta2 && psi1 == psi2) {\n        return T(1);\n    }\n\n    // Haversine distance\n    auto dist = T(2)*asin(sqrt(sq(sin((theta1-theta2)/T(2))) + cos(theta1)*cos(theta2)*sq(sin((psi1-psi2)/T(2)))));\n    return exp(-sq(dist)/sq(sigma));\n}\n\ntemplate<typename T>\nCircle3D<T> circleOnSphere(const Sphere<T>& sphere, T theta, T psi, T circle_radius) {\n    typedef Eigen::Matrix<T,3,1> Vector3;\n\n    Vector3 radial = sph2cart<T>(T(1), theta, psi);\n    return Circle3D<T>(sphere.centre + sphere.radius * radial,\n        radial,\n        circle_radius);\n}\n\ntemplate<typename T>\nstruct EllipseGoodnessFunction {\n    T operator()(const Sphere<T>& eye, T theta, T psi, T pupil_radius, T focal_length, typename ad_traits<T>::scalar band_width, typename ad_traits<T>::scalar step_epsilon, const cv::Mat& mEye) {\n        typedef Eigen::Matrix<T,3,1> Vector3;\n        typedef typename ad_traits<T>::scalar Const;\n\n        static const Vector3 camera_centre(T(0),T(0),T(0));\n\n        // Check for bounds. The worst possible value of ellipseGoodness is -255, so use that as a starting point for out-of-bounds pupils\n\n        // Pupil radius must be positive\n        if (pupil_radius <= Const(0))\n        {\n            // Return -255 for radius == 0, and even lower values for\n            // radius < 0\n            // This should push the gradient towards positive radius,\n            // rather than just returning flat -255\n            return Const(-255.0) + pupil_radius;\n        }\n\n        Circle3D<T> pupil_circle = circleOnSphere(eye, theta, psi, pupil_radius);\n\n        // Ellipse normal must point towards camera\n        T normalDotPos = pupil_circle.normal.dot(camera_centre - pupil_circle.centre);\n        if (normalDotPos <= Const(0))\n        {\n            // Return -255 for normalDotPos == 0, and even lower values for\n            // normalDotPos < 0\n            // This should push the gradient towards positive normalDotPos,\n            // rather than just returning flat -255\n            return Const(-255.0) + normalDotPos;\n        }\n\n        // Angles should be in the range\n        //    theta: 0 -> pi\n        //      psi: -pi -> 0\n        // If we're outside of this range AND radialDotEye > 0, then we must\n        // have gone all the way around, so just return worst case (i.e as bad\n        // as radialDotEye == -1) with additional penalty for how far out we\n        // are, again to push the gradient back inwards.\n        if (theta < Const(0) || theta > Const(PI) || psi < Const(-PI) || psi > Const(0))\n        {\n            T ret = Const(-255.0) - (camera_centre - pupil_circle.centre).norm();\n            if (theta < Const(0))\n                ret -= (Const(0) - theta);\n            else if (theta > Const(PI))\n                ret -= (theta - Const(PI));\n            if (psi < Const(-PI))\n                ret -= (Const(-PI) - psi);\n            else if (psi > Const(0))\n                ret -= (psi - Const(0));\n        }\n\n        // Ok, everything looks good so far, calculate the actual goodness.\n\n        Ellipse2D<T> pupil_ellipse(project(pupil_circle, focal_length));\n\n        return ellipseGoodness<T>(pupil_ellipse, mEye, band_width, step_epsilon);\n    }\n};\n\n\n\n\n\ntemplate<typename Scalar>\nclass EllipseDistanceResidualFunction {\npublic:\n    EllipseDistanceResidualFunction(const cv::Mat& eye_image, const std::vector<cv::Point2f>& pupil_inliers, const Scalar& eye_radius, const Scalar& focal_length) :\n        eye_image(eye_image), pupil_inliers(pupil_inliers), eye_radius(eye_radius), focal_length(focal_length) {}\n\n    template <typename T>\n    bool operator()(const T* const eye_param, const T* const pupil_param, T* e) const {\n        typedef typename ad_traits<T>::scalar Const;\n\n        Eigen::Matrix<T,3,1> eye_pos(eye_param[0], eye_param[1], eye_param[2]);\n        Sphere<T> eye(eye_pos, T(eye_radius));\n\n        Ellipse2D<T> pupil_ellipse(project(circleOnSphere(eye, pupil_param[0], pupil_param[1], pupil_param[2]), T(focal_length)));\n\n        EllipseDistCalculator<T> ellipDist(pupil_ellipse);\n\n        for (int i = 0; i < pupil_inliers.size(); ++i) {\n            const cv::Point2f& inlier = pupil_inliers[i];\n            e[i] = ellipDist(Const(inlier.x), Const(inlier.y));\n        }\n\n        return true;\n    }\nprivate:\n    const cv::Mat& eye_image;\n    const std::vector<cv::Point2f>& pupil_inliers;\n    const Scalar& eye_radius;\n    const Scalar& focal_length;\n};\n\n\ntemplate<typename Scalar>\nstruct EllipsePointDistanceFunction {\n    EllipsePointDistanceFunction(const Ellipse2D<Scalar>& el, Scalar x, Scalar y) : el(el), x(x), y(y) {}\n\n    template <typename T>\n    bool operator()(const T* const t, T* e) const\n    {\n        using std::sin;\n        using std::cos;\n\n        auto&& pt = pointAlongEllipse(el, t[0]);\n        e[0] = norm(x - pt.x(), y - pt.y());\n\n        return true;\n    }\n\n    const Ellipse2D<Scalar>& el;\n    Scalar x, y;\n};\n\ntemplate<bool has_eye_var=true>\nstruct PupilContrastTerm : public spii::Term {\n    const Sphere<double>& init_eye;\n    double focal_length;\n    const cv::Mat eye_image;\n    double band_width;\n    double step_epsilon;\n\n    int eye_var_idx() const { return has_eye_var ? 0 : -1; }\n    int pupil_var_idx() const { return has_eye_var ? 1 : 0; }\n\n    PupilContrastTerm(const Sphere<double>& eye, double focal_length, cv::Mat eye_image, double band_width, double step_epsilon) :\n        init_eye(eye),\n        focal_length(focal_length),\n        eye_image(eye_image),\n        band_width(band_width),\n        step_epsilon(step_epsilon)\n    {}\n\n    virtual int number_of_variables() const override {\n        int nvars = 1; // This pupil params\n        if (has_eye_var)\n            nvars++; // Eye params\n\n        return nvars;\n    }\n    virtual int variable_dimension(int var) const override {\n        if (var == eye_var_idx()) // Eye params (x,y,z)\n            return 3;\n        if (var == pupil_var_idx()) // This pupil params (theta, psi, r)\n            return 3;\n        return -1;\n    };\n    virtual double evaluate(double * const * const vars) const override\n    {\n        auto& pupil_vars = vars[pupil_var_idx()];\n\n        auto eye = init_eye;\n        if (has_eye_var) {\n            auto& eye_vars = vars[eye_var_idx()];\n            eye.centre = Sphere<double>::Vector(eye_vars[0], eye_vars[1], eye_vars[2]);\n        }\n\n        EllipseGoodnessFunction<double> goodnessFunction;\n        auto theta = pupil_vars[0];\n        auto psi = pupil_vars[1];\n        auto r = pupil_vars[2];\n        auto goodness = goodnessFunction(eye,\n            theta, psi, r,\n            focal_length,\n            band_width, step_epsilon,\n            eye_image);\n\n        return -goodness;\n    }\n    virtual double evaluate(double * const * const vars, std::vector<Eigen::VectorXd>* gradient) const override\n    {\n        auto& pupil_vars = vars[pupil_var_idx()];\n\n        double contrast_goodness_a;\n        Eigen::Matrix<double,3,1> eye_contrast_goodness_v;\n        Eigen::Matrix<double,3,1> pupil_contrast_goodness_v;\n\n        // Get region contrast goodness using EllipseGoodnessFunction.\n        if (has_eye_var) {\n            // If varying the eye parameters, calculate the gradient wrt. to 6 params (3 eye + 3 pupil)\n            typedef ceres::Jet<double, 6> EyePupilJet;\n\n            auto& eye_vars = vars[eye_var_idx()];\n            Eigen::Matrix<EyePupilJet,3,1> eye_pos(EyePupilJet(eye_vars[0], 0), EyePupilJet(eye_vars[1], 1), EyePupilJet(eye_vars[2], 2));\n            Sphere<EyePupilJet> eye(eye_pos, EyePupilJet(init_eye.radius));\n\n            EyePupilJet contrast_goodness;\n            {\n                EllipseGoodnessFunction<EyePupilJet> goodnessFunction;\n                auto theta = EyePupilJet(pupil_vars[0], 3);\n                auto psi = EyePupilJet(pupil_vars[1], 4);\n                auto r = EyePupilJet(pupil_vars[2], 5);\n                contrast_goodness = goodnessFunction(eye,\n                    theta, psi, r,\n                    EyePupilJet(focal_length),\n                    band_width, step_epsilon,\n                    eye_image);\n            }\n\n            contrast_goodness_a = contrast_goodness.a;\n            eye_contrast_goodness_v = contrast_goodness.v.segment<3>(0);\n            pupil_contrast_goodness_v = contrast_goodness.v.segment<3>(3);\n        } else {\n            // Otherwise, calculate the gradient wrt. to the 3 pupil params\n            typedef ::ceres::Jet<double,3> PupilJet;\n\n            Eigen::Matrix<PupilJet,3,1> eye_pos(PupilJet(init_eye.centre[0]), PupilJet(init_eye.centre[1]), PupilJet(init_eye.centre[2]));\n            ::Sphere<PupilJet> eye(eye_pos, PupilJet(init_eye.radius));\n\n            PupilJet contrast_goodness;\n            {\n                EllipseGoodnessFunction<PupilJet> goodnessFunction;\n                auto theta = PupilJet(pupil_vars[0], 0);\n                auto psi = PupilJet(pupil_vars[1], 1);\n                auto r = PupilJet(pupil_vars[2], 2);\n                contrast_goodness = goodnessFunction(eye,\n                    theta, psi, r,\n                    PupilJet(focal_length),\n                    band_width, step_epsilon,\n                    eye_image);\n            }\n\n            contrast_goodness_a = contrast_goodness.a;\n            pupil_contrast_goodness_v = contrast_goodness.v;\n        }\n\n        double goodness;\n        auto& eye_gradient = (*gradient)[eye_var_idx()];\n        auto& pupil_gradient = (*gradient)[pupil_var_idx()];\n\n        // No smoothness term, goodness and gradient are based only on frame goodness\n        goodness = contrast_goodness_a;\n        if (has_eye_var)\n            eye_gradient = eye_contrast_goodness_v;\n        pupil_gradient = pupil_contrast_goodness_v;\n\n        // Flip sign to change goodness into cost (i.e. maximising into minimising)\n        auto cost = -goodness;\n        for (int i = 0; i < number_of_variables(); ++i) {\n            (*gradient)[i] = -(*gradient)[i];\n        }\n        return cost;\n    }\n    virtual double evaluate(double * const * const variables,\n        std::vector<Eigen::VectorXd>* gradient,\n        std::vector< std::vector<Eigen::MatrixXd> >* hessian) const override {\n            throw std::runtime_error(\"Not implemented\");\n    }\n\n};\n\n// Anthropomorphic term\nstruct PupilAnthroTerm : public spii::Term {\n    double mean;\n    double sigma;\n    double scale;\n\n    PupilAnthroTerm(double mean, double sigma, double scale) : mean(mean), sigma(sigma), scale(scale)\n    {}\n\n    virtual int number_of_variables() const override {\n        int nvars = 1; // This pupil params\n        return nvars;\n    }\n    virtual int variable_dimension(int var) const override {\n        if (var == 0) // This pupil params (r)\n            return 3;\n        return -1;\n    }\n    virtual double evaluate(double * const * const vars) const override\n    {\n        using math::sq;\n\n        auto r = vars[0][2];\n        auto radius_anthro_goodness = exp(-sq(r - mean)/sq(sigma));\n\n        double goodness = radius_anthro_goodness;\n\n        // Flip sign to change goodness into cost (i.e. maximising into minimising)\n        auto cost = -goodness*scale;\n        return cost;\n    }\n    virtual double evaluate(double * const * const vars, std::vector<Eigen::VectorXd>* gradient) const override\n    {\n        using math::sq;\n\n        auto r = ceres::Jet<double,1>(vars[0][2], 0);\n        auto radius_anthro_goodness = exp(-sq(r - mean)/sq(sigma));\n\n        double goodness = radius_anthro_goodness.a;\n        (*gradient)[0].segment<1>(2) = radius_anthro_goodness.v;\n\n        // Flip sign to change goodness into cost (i.e. maximising into minimising)\n        auto cost = -goodness*scale;\n        for (int i = 0; i < number_of_variables(); ++i) {\n            (*gradient)[i] = -(*gradient)[i]*scale;\n        }\n        return cost;\n    }\n    virtual double evaluate(double * const * const variables,\n        std::vector<Eigen::VectorXd>* gradient,\n        std::vector< std::vector<Eigen::MatrixXd> >* hessian) const override {\n            throw std::runtime_error(\"Not implemented\");\n    }\n\n};\n\nconst EyeModelFitter::Vector3 EyeModelFitter::camera_centre = EyeModelFitter::Vector3::Zero();\n\n\nEyeModelFitter::Pupil::Pupil(Observation observation) : observation(observation), params(0, 0, 0)\n{\n\n}\n\nEyeModelFitter::Pupil::Pupil()\n{\n\n}\n\n\nEyeModelFitter::PupilParams::PupilParams(double theta, double psi, double radius) : theta(theta), psi(psi), radius(radius)\n{\n\n}\n\nEyeModelFitter::PupilParams::PupilParams() : theta(0), psi(0), radius(0)\n{\n\n}\n\n\nEyeModelFitter::Observation::Observation(cv::Mat image, Ellipse ellipse, std::vector<cv::Point2f> inliers) : image(std::move(image)), ellipse(std::move(ellipse)), inliers(std::move(inliers))\n{\n\n}\n\nEyeModelFitter::Observation::Observation()\n{\n\n}\n\n}\n\n\nsingleeyefitter::EyeModelFitter::EyeModelFitter() : region_band_width(5), region_step_epsilon(0.5), region_scale(1)\n{\n\n}\nsingleeyefitter::EyeModelFitter::EyeModelFitter(double focal_length, double region_band_width, double region_step_epsilon) : focal_length(focal_length), region_band_width(region_band_width), region_step_epsilon(region_step_epsilon), region_scale(1)\n{\n\n}\n\nsingleeyefitter::EyeModelFitter::Index singleeyefitter::EyeModelFitter::add_observation(cv::Mat image, Ellipse pupil, int n_pseudo_inliers /*= 0*/)\n{\n    std::vector<cv::Point2f> pupil_inliers;\n    for (int i = 0; i < n_pseudo_inliers; ++i) {\n        auto p = pointAlongEllipse(pupil, i * 2 * M_PI / n_pseudo_inliers);\n        pupil_inliers.emplace_back(static_cast<float>(p[0]), static_cast<float>(p[1]));\n    }\n    return add_observation(std::move(image), std::move(pupil), std::move(pupil_inliers));\n}\n\nsingleeyefitter::EyeModelFitter::Index singleeyefitter::EyeModelFitter::add_observation(cv::Mat image, Ellipse pupil, std::vector<cv::Point2f> pupil_inliers)\n{\n    assert(image.channels() == 1 && image.depth() == CV_8U);\n\n    std::lock_guard<std::mutex> lock_model(model_mutex);\n\n    pupils.emplace_back(\n        Observation(std::move(image), std::move(pupil), std::move(pupil_inliers))\n        );\n    return pupils.size() - 1;\n}\n\nvoid EyeModelFitter::reset()\n{\n    std::lock_guard<std::mutex> lock_model(model_mutex);\n    pupils.clear();\n    eye = Sphere::Null;\n    model_version++;\n}\n\nsingleeyefitter::EyeModelFitter::Circle singleeyefitter::EyeModelFitter::circleFromParams(const Sphere& eye, const PupilParams& params)\n{\n    if (params.radius == 0)\n        return Circle::Null;\n\n    Vector3 radial = sph2cart<double>(double(1), params.theta, params.psi);\n    return Circle(eye.centre + eye.radius * radial,\n        radial,\n        params.radius);\n}\n\nsingleeyefitter::EyeModelFitter::Circle singleeyefitter::EyeModelFitter::circleFromParams(const PupilParams& params) const\n{\n    return circleFromParams(eye, params);\n}\n\nvoid singleeyefitter::EyeModelFitter::print_single_contrast_metric(const Pupil& pupil) const\n{\n    if (!pupil.circle) {\n        std::cout << \"No pupil\" << std::endl;\n        return;\n    }\n\n    double params[3];\n    params[0] = pupil.params.theta;\n    params[1] = pupil.params.psi;\n    params[2] = pupil.params.radius;\n    double* vars[1];\n    vars[0] = params;\n\n    std::vector<Eigen::VectorXd> gradient;\n    gradient.push_back(Eigen::VectorXd::Zero(3));\n\n    PupilContrastTerm<false> contrast_term(\n        eye,\n        focal_length * region_scale,\n        cvx::resize(pupil.observation.image, region_scale),\n        region_band_width,\n        region_step_epsilon);\n\n    double contrast_val = contrast_term.evaluate(vars, &gradient);\n\n    std::cout << \"Contrast term: \" << contrast_val << std::endl;\n    std::cout << \"     gradient: [ \" << gradient[0].transpose() << \" ]\" << std::endl;\n}\n\nvoid singleeyefitter::EyeModelFitter::print_single_contrast_metric(Index id) const\n{\n    print_single_contrast_metric(pupils[id]);\n}\n\ndouble singleeyefitter::EyeModelFitter::single_contrast_metric(const Pupil& pupil) const\n{\n    if (!pupil.circle) {\n        std::cout << \"No pupil\" << std::endl;\n        return 0;\n    }\n\n    double params[3];\n    params[0] = pupil.params.theta;\n    params[1] = pupil.params.psi;\n    params[2] = pupil.params.radius;\n    double* vars[1];\n    vars[0] = params;\n\n    PupilContrastTerm<false> contrast_term(\n        eye,\n        focal_length * region_scale,\n        cvx::resize(pupil.observation.image, region_scale),\n        region_band_width,\n        region_step_epsilon);\n\n    double contrast_val = contrast_term.evaluate(vars);\n\n    return contrast_val;\n}\n\ndouble singleeyefitter::EyeModelFitter::single_contrast_metric(Index id) const\n{\n    return single_contrast_metric(pupils[id]);\n}\n\nconst singleeyefitter::EyeModelFitter::Circle& singleeyefitter::EyeModelFitter::refine_single_with_contrast(Pupil& pupil)\n{\n    if (!pupil.circle)\n        return pupil.circle;\n\n    double params[3];\n    params[0] = pupil.params.theta;\n    params[1] = pupil.params.psi;\n    params[2] = pupil.params.radius;\n\n    spii::Function f;\n    f.add_variable(&params[0], 3);\n    f.add_term(std::make_shared<PupilContrastTerm<false>>(\n        eye,\n        focal_length * region_scale,\n        cvx::resize(pupil.observation.image, region_scale),\n        region_band_width,\n        region_step_epsilon), &params[0]);\n\n    spii::LBFGSSolver solver;\n\t\n\t// Commented out due to Visual Studio 2015 error\n\t//solver.log_function = [](const std::string&) {};\n\n\t//solver.function_improvement_tolerance = 1e-5;\n    spii::SolverResults results;\n    solver.solve(f, &results);\n    //std::cout << results << std::endl;\n\n    pupil.params = PupilParams(params[0], params[1], params[2]);\n    pupil.circle = circleFromParams(pupil.params);\n\n    return pupil.circle;\n}\n\nconst singleeyefitter::EyeModelFitter::Circle& singleeyefitter::EyeModelFitter::refine_single_with_contrast(Index id)\n{\n    return refine_single_with_contrast(pupils[id]);\n}\n\nconst singleeyefitter::EyeModelFitter::Circle& singleeyefitter::EyeModelFitter::initialise_single_observation(Pupil& pupil)\n{\n    // Ignore the pupil circle normal, and intersect the pupil circle\n    // centre projection line with the eyeball sphere\n    try {\n        auto pupil_centre_sphere_intersect = intersect(Line3(camera_centre, pupil.circle.centre.normalized()),\n            eye);\n        auto new_pupil_centre = pupil_centre_sphere_intersect.first;\n\n        // Now that we have 3D positions for the pupil (rather than just a\n        // projection line), recalculate the pupil radius at that position.\n        auto pupil_radius_at_1 = pupil.circle.radius / pupil.circle.centre.z();\n        auto new_pupil_radius = pupil_radius_at_1 * new_pupil_centre.z();\n\n        // Parametrise this new pupil position using spherical coordinates\n        Vector3 centre_to_pupil = new_pupil_centre - eye.centre;\n        double r = centre_to_pupil.norm();\n        pupil.params.theta = acos(centre_to_pupil[1] / r);\n        pupil.params.psi = atan2(centre_to_pupil[2], centre_to_pupil[0]);\n        pupil.params.radius = new_pupil_radius;\n\n        // Update pupil circle to match parameters\n        pupil.circle = circleFromParams(pupil.params);\n    }\n    catch (no_intersection_exception&) {\n        pupil.circle = Circle::Null;\n        pupil.params.theta = 0;\n        pupil.params.psi = 0;\n        pupil.params.radius = 0;\n    }\n\n    return pupil.circle;\n}\n\nconst singleeyefitter::EyeModelFitter::Circle& singleeyefitter::EyeModelFitter::initialise_single_observation(Index id)\n{\n    initialise_single_observation(pupils[id]);\n\n    /*if (id > 0 && pupils[id-1].circle) {\n    // Try previous circle in case of bad fits\n    EllipseGoodnessFunction<double> goodnessFunction;\n    auto& pupil = pupils[id];\n    auto& prevPupil = pupils[id-1];\n\n    double currentGoodness, prevGoodness;\n    if (pupil.circle) {\n    currentGoodness = goodnessFunction(eye, pupil.params.theta, pupil.params.psi, pupil.params.radius, focal_length, pupil.observation.image);\n    prevGoodness = goodnessFunction(eye, prevPupil.params.theta, prevPupil.params.psi, prevPupil.params.radius, focal_length, pupil.observation.image);\n    }\n\n    if (!pupil.circle || prevGoodness > currentGoodness) {\n    pupil.circle = prevPupil.circle;\n    pupil.params = prevPupil.params;\n    }\n    }*/\n\n    return pupils[id].circle;\n}\n\nconst singleeyefitter::EyeModelFitter::Circle& singleeyefitter::EyeModelFitter::unproject_single_observation(Pupil& pupil, double pupil_radius /*= 1*/) const\n{\n    if (eye == Sphere::Null) {\n        throw std::runtime_error(\"Need to get eye centre estimate first (by unprojecting multiple observations)\");\n    }\n\n    // Single pupil version of \"unproject_observations\"\n\n    auto unprojection_pair = unproject(pupil.observation.ellipse, pupil_radius, focal_length);\n\t\n    const Vector3& c = unprojection_pair.first.centre;\n    const Vector3& v = unprojection_pair.first.normal;\n\n    Vector2 c_proj = project(c, focal_length);\n    Vector2 v_proj = project(v + c, focal_length) - c_proj;\n\n    v_proj.normalize();\n\n    Vector2 eye_centre_proj = project(eye.centre, focal_length);\n\n    if ((c_proj - eye_centre_proj).dot(v_proj) >= 0) {\n        pupil.circle = std::move(unprojection_pair.first);\n    }\n    else {\n        pupil.circle = std::move(unprojection_pair.second);\n    }\n\n    return pupil.circle;\n}\n\nconst singleeyefitter::EyeModelFitter::Circle& singleeyefitter::EyeModelFitter::unproject_single_observation(Index id, double pupil_radius /*= 1*/)\n{\n    return unproject_single_observation(pupils[id], pupil_radius);\n}\n\nvoid singleeyefitter::EyeModelFitter::refine_with_inliers(const CallbackFunction& callback /*= CallbackFunction()*/)\n{\n    int current_model_version;\n    Eigen::Matrix<double, Eigen::Dynamic, 1> x;\n    {\n        std::lock_guard<std::mutex> lock_model(model_mutex);\n\n        current_model_version = model_version;\n\n        x = Eigen::Matrix<double, Eigen::Dynamic, 1>(3 + 3 * pupils.size());\n        x.segment<3>(0) = eye.centre;\n        for (int i = 0; i < pupils.size(); ++i) {\n            const PupilParams& pupil_params = pupils[i].params;\n            x.segment<3>(3 + 3 * i)[0] = pupil_params.theta;\n            x.segment<3>(3 + 3 * i)[1] = pupil_params.psi;\n            x.segment<3>(3 + 3 * i)[2] = pupil_params.radius;\n        }\n    }\n\n    ceres::Problem problem;\n    for (int i = 0; i < pupils.size(); ++i) {\n        const cv::Mat& eye_image = pupils[i].observation.image;\n        const auto& pupil_inliers = pupils[i].observation.inliers;\n\n        problem.AddResidualBlock(\n            new ceres::AutoDiffCostFunction<EllipseDistanceResidualFunction<double>, ceres::DYNAMIC, 3, 3>(\n            new EllipseDistanceResidualFunction<double>(eye_image, pupil_inliers, eye.radius, focal_length),\n            (int)pupil_inliers.size()\n            ),\n            NULL, &x[0], &x[3 + 3 * i]);\n    }\n\n    ceres::Solver::Options options;\n    options.linear_solver_type = ceres::DENSE_SCHUR;\n    options.max_num_iterations = 1000;\n    options.function_tolerance = 1e-10;\n    options.minimizer_progress_to_stdout = true;\n    options.update_state_every_iteration = true;\n    if (callback) {\n        struct CallCallbackWrapper : public ceres::IterationCallback\n        {\n            double eye_radius;\n            const CallbackFunction& callback;\n            const Eigen::Matrix<double, Eigen::Dynamic, 1>& x;\n\n            CallCallbackWrapper(const EyeModelFitter& fitter, const CallbackFunction& callback, const Eigen::Matrix<double, Eigen::Dynamic, 1>& x)\n                : eye_radius(fitter.eye.radius), callback(callback), x(x) {}\n\n            virtual ceres::CallbackReturnType operator() (const ceres::IterationSummary& summary) {\n                Eigen::Matrix<double, 3, 1> eye_pos(x[0], x[1], x[2]);\n                Sphere eye(eye_pos, eye_radius);\n\n                std::vector<Circle> pupils;\n                for (int i = 0; i < (x.size() - 3)/3; ++i) {\n                    auto&& pupil_param_v = x.segment<3>(3 + 3 * i);\n                    pupils.push_back(EyeModelFitter::circleFromParams(eye, PupilParams(pupil_param_v[0], pupil_param_v[1], pupil_param_v[2])));\n                }\n\n                callback(eye, pupils);\n\n                return ceres::SOLVER_CONTINUE;\n            }\n        };\n        options.callbacks.push_back(new CallCallbackWrapper(*this, callback, x));\n    }\n    ceres::Solver::Summary summary;\n    ceres::Solve(options, &problem, &summary);\n    std::cout << summary.BriefReport() << \"\\n\";\n\n    {\n        std::lock_guard<std::mutex> lock_model(model_mutex);\n\n        if (current_model_version != model_version)    {\n            std::cout << \"Old model, not applying refined parameters\" << std::endl;\n            return;\n        }\n\n        eye.centre = x.segment<3>(0);\n\n        for (int i = 0; i < pupils.size(); ++i) {\n            auto&& pupil_param = x.segment<3>(3 + 3 * i);\n            pupils[i].params = PupilParams(pupil_param[0], pupil_param[1], pupil_param[2]);\n            pupils[i].circle = circleFromParams(eye, pupils[i].params);\n        }\n    }\n}\n\nvoid singleeyefitter::EyeModelFitter::refine_with_region_contrast(const CallbackFunction& callback /*= CallbackFunction()*/)\n{\n    int current_model_version;\n    Eigen::Matrix<double, Eigen::Dynamic, 1> x0;\n    spii::Function f;\n    {\n        std::lock_guard<std::mutex> lock_model(model_mutex);\n\n        current_model_version = model_version;\n\n        x0 = Eigen::Matrix<double, Eigen::Dynamic, 1>(3 + 3 * pupils.size());\n        x0.segment<3>(0) = eye.centre;\n        for (int i = 0; i < pupils.size(); ++i) {\n            const PupilParams& pupil_params = pupils[i].params;\n            x0.segment<3>(3 + 3 * i)[0] = pupil_params.theta;\n            x0.segment<3>(3 + 3 * i)[1] = pupil_params.psi;\n            x0.segment<3>(3 + 3 * i)[2] = pupil_params.radius;\n        }\n\n        f.add_variable(&x0[0], 3);\n        for (int i = 0; i < pupils.size(); ++i) {\n            if (pupils[i].circle) {\n                f.add_variable(&x0[3 + 3 * i], 3);\n\n                f.add_term(\n                    std::make_shared<PupilContrastTerm<true>>(\n                    eye,\n                    focal_length * region_scale,\n                    cvx::resize(pupils[i].observation.image, region_scale),\n                    region_band_width,\n                    region_step_epsilon),\n                    &x0[0], &x0[3 + 3 * i]);\n                //f.add_term(std::make_shared<PupilAnthroTerm>(2.5, 1, 0.001), &x0[3+3*i]);\n\n                /*if (i == 0 || !pupils[i-1].circle) {\n                } else {\n                vars.push_back(&x0[3+3*(i-1)]);\n                f.add_term(std::make_shared<SinglePupilTerm<true,true,true>>(*this, pupils[i].observation.image), vars);\n                }*/\n            }\n        }\n    }\n\n    spii::LBFGSSolver solver;\n    solver.maximum_iterations = 1000;\n    solver.function_improvement_tolerance = 1e-5;\n    spii::SolverResults results;\n\n#if 0 // Turned off due to Visual Studio 2015 error\n    if (callback) {\n        double eye_radius = eye.radius;\n        solver.callback_function = [eye_radius, &callback](const spii::CallbackInformation& info) {\n            auto& x = *info.x;\n\n            Eigen::Matrix<double, 3, 1> eye_pos(x(0), x(1), x(2));\n            Sphere eye(eye_pos, eye_radius);\n\n            std::vector<Circle> pupils;\n            for (int i = 0; i < (x.size() - 3) / 3; ++i) {\n                pupils.push_back(EyeModelFitter::circleFromParams(eye, PupilParams(x(3 + 3 * i + 0), x(3 + 3 * i + 1), x(3 + 3 * i + 2))));\n            }\n\n            callback(eye, pupils);\n\n            return true;\n        };\n    }\n#endif\n    solver.solve(f, &results);\n    std::cout << results << std::endl;\n\n    {\n        std::lock_guard<std::mutex> lock_model(model_mutex);\n\n        if (current_model_version != model_version)    {\n            std::cout << \"Old model, not applying refined parameters\" << std::endl;\n            return;\n        }\n\n        eye.centre = x0.segment<3>(0);\n\n        for (int i = 0; i < (x0.size() - 3) / 3; ++i) {\n            auto pupil_param = x0.segment<3>(3 + 3 * i);\n            pupils[i].params = PupilParams(pupil_param[0], pupil_param[1], pupil_param[2]);\n            pupils[i].circle = circleFromParams(pupils[i].params);\n        }\n    }\n}\n\nvoid singleeyefitter::EyeModelFitter::initialise_model()\n{\n    std::lock_guard<std::mutex> lock_model(model_mutex);\n\n    if (eye == Sphere::Null) {\n        return;\n    }\n\n    // Find pupil positions on eyeball to get radius\n    //\n    // For each image, calculate the 'most likely' position of the pupil\n    // circle given the eyeball sphere estimate and gaze vector. Re-estimate\n    // the gaze vector to be consistent with this position.\n\n    // First estimate of pupil centre, used only to get an estimate of eye radius\n\n    double eye_radius_acc = 0;\n    int eye_radius_count = 0;\n\n    for (const auto& pupil : pupils) {\n        if (!pupil.circle) {\n            continue;\n        }\n        if (!pupil.init_valid) {\n            continue;\n        }\n\n        // Intersect the gaze from the eye centre with the pupil circle\n        // centre projection line (with perfect estimates of gaze, eye\n        // centre and pupil circle centre, these should intersect,\n        // otherwise find the nearest point to both lines)\n\n        Vector3 pupil_centre = nearest_intersect(Line3(eye.centre, pupil.circle.normal),\n            Line3(camera_centre, pupil.circle.centre.normalized()));\n\n        auto distance = (pupil_centre - eye.centre).norm();\n\n        eye_radius_acc += distance;\n        ++eye_radius_count;\n    }\n\n    // Set the eye radius as the mean distance from pupil centres to eye centre\n    eye.radius = eye_radius_acc / eye_radius_count;\n\n    // Second estimate of pupil radius, used to get position of pupil on eye\n\n    for (auto& pupil : pupils) {\n        initialise_single_observation(pupil);\n    }\n\n    // Scale eye to anthropomorphic average radius of 12mm\n    auto scale = 12.0 / eye.radius;\n    eye.radius = 12.0;\n    eye.centre *= scale;\n    for (auto& pupil : pupils) {\n        pupil.params.radius *= scale;\n        pupil.circle = circleFromParams(pupil.params);\n    }\n\n    model_version++;\n\n    // Try previous circle in case of bad fits\n    /*EllipseGoodnessFunction<double> goodnessFunction;\n    for (int i = 1; i < pupils.size(); ++i) {\n    auto& pupil = pupils[i];\n    auto& prevPupil = pupils[i-1];\n\n    if (prevPupil.circle) {\n    double currentGoodness, prevGoodness;\n    if (pupil.circle) {\n    currentGoodness = goodnessFunction(eye, pupil.params.theta, pupil.params.psi, pupil.params.radius, focal_length, pupil.observation.image);\n    prevGoodness = goodnessFunction(eye, prevPupil.params.theta, prevPupil.params.psi, prevPupil.params.radius, focal_length, pupil.observation.image);\n    }\n\n    if (!pupil.circle || prevGoodness > currentGoodness) {\n    pupil.circle = prevPupil.circle;\n    pupil.params = prevPupil.params;\n    }\n    }\n    }*/\n}\n\nvoid singleeyefitter::EyeModelFitter::unproject_observations(double pupil_radius /*= 1*/, double eye_z /*= 20*/, bool use_ransac /*= true*/)\n{\n    using math::sq;\n\n    std::lock_guard<std::mutex> lock_model(model_mutex);\n\n    if (pupils.size() < 2) {\n        throw std::runtime_error(\"Need at least two observations\");\n    }\n\n    std::vector<std::pair<Circle, Circle>> pupil_unprojection_pairs;\n    std::vector<Line> pupil_gazelines_proj;\n\n    for (const auto& pupil : pupils) {\n        // Get pupil circles (up to depth)\n        //\n        // Do a per-image unprojection of the pupil ellipse into the two fixed\n        // size circles that would project onto it. The size of the circles\n        // doesn't matter here, only their centre and normal does.\n        auto unprojection_pair = unproject(pupil.observation.ellipse,\n            pupil_radius, focal_length);\n\n        // Get projected circles and gaze vectors\n        //\n        // Project the circle centres and gaze vectors down back onto the image\n        // plane. We're only using them as line parametrisations, so it doesn't\n        // matter which of the two centres/gaze vectors we use, as the\n        // two gazes are parallel and the centres are co-linear.\n\n        const auto& c = unprojection_pair.first.centre;\n        const auto& v = unprojection_pair.first.normal;\n\n        Vector2 c_proj = project(c, focal_length);\n        Vector2 v_proj = project(v + c, focal_length) - c_proj;\n\n        v_proj.normalize();\n\n        pupil_unprojection_pairs.push_back(std::move(unprojection_pair));\n        pupil_gazelines_proj.emplace_back(c_proj, v_proj);\n    }\n\n\n    // Get eyeball centre\n    //\n    // Find a least-squares 'intersection' (point nearest to all lines) of\n    // the projected 2D gaze vectors. Then, unproject that circle onto a\n    // point a fixed distance away.\n    //\n    // For robustness, use RANSAC to eliminate stray gaze lines\n    //\n    // (This has to be done here because it's used by the pupil circle\n    // disambiguation)\n\n    Vector2 eye_centre_proj;\n    bool valid_eye;\n\n    if (use_ransac) {\n        auto indices = fun::range_<std::vector<size_t>>(pupil_gazelines_proj.size());\n\n        const int n = 2;\n        double w = 0.3;\n        double p = 0.9999;\n        int k = (int)ceil(log(1 - p) / log(1 - pow(w, n)));\n\n        double epsilon = 10;\n        auto huber_error = [&](const Vector2& point, const Line& line) {\n            double dist = euclidean_distance(point, line);\n            if (sq(dist) < sq(epsilon))\n                return sq(dist) / 2;\n            else\n                return epsilon*(abs(dist) - epsilon / 2);\n        };\n        auto m_error = [&](const Vector2& point, const Line& line) {\n            double dist = euclidean_distance(point, line);\n            if (sq(dist) < sq(epsilon))\n                return sq(dist);\n            else\n                return sq(epsilon);\n        };\n        auto error = m_error;\n\n        auto best_inlier_indices = decltype(indices)();\n        Vector2 best_eye_centre_proj;// = nearest_intersect(pupil_gazelines_proj);\n        double best_line_distance_error = std::numeric_limits<double>::infinity();// = fun::sum(LAMBDA(const Line& line)(error(best_eye_centre_proj,line)), pupil_gazelines_proj);\n\n        for (int i = 0; i < k; ++i) {\n            auto index_sample = singleeyefitter::randomSubset(indices, n);\n            auto sample = fun::map([&](size_t i){ return pupil_gazelines_proj[i]; }, index_sample);\n\n            auto sample_centre_proj = nearest_intersect(sample);\n\n            auto index_inliers = fun::filter(\n                [&](size_t i){ return euclidean_distance(sample_centre_proj, pupil_gazelines_proj[i]) < epsilon; },\n                indices);\n            auto inliers = fun::map([&](size_t i){ return pupil_gazelines_proj[i]; }, index_inliers);\n\n            if (inliers.size() <= w*pupil_gazelines_proj.size()) {\n                continue;\n            }\n\n            auto inlier_centre_proj = nearest_intersect(inliers);\n\n            double line_distance_error = fun::sum(\n                [&](size_t i){ return error(inlier_centre_proj, pupil_gazelines_proj[i]); },\n                indices);\n\n            if (line_distance_error < best_line_distance_error) {\n                best_eye_centre_proj = inlier_centre_proj;\n                best_line_distance_error = line_distance_error;\n                best_inlier_indices = std::move(index_inliers);\n            }\n        }\n\n        std::cout << \"Inliers: \" << best_inlier_indices.size()\n            << \" (\" << (100.0*best_inlier_indices.size() / pupil_gazelines_proj.size()) << \"%)\"\n            << \" = \" << best_line_distance_error\n            << std::endl;\n\n        for (auto& pupil : pupils) {\n            pupil.init_valid = false;\n        }\n        for (auto& i : best_inlier_indices) {\n            pupils[i].init_valid = true;\n        }\n\n        if (best_inlier_indices.size() > 0) {\n            eye_centre_proj = best_eye_centre_proj;\n            valid_eye = true;\n        }\n        else {\n            valid_eye = false;\n        }\n    }\n    else {\n        for (auto& pupil : pupils) {\n            pupil.init_valid = true;\n        }\n        eye_centre_proj = nearest_intersect(pupil_gazelines_proj);\n        valid_eye = true;\n    }\n\n    if (valid_eye) {\n        eye.centre << eye_centre_proj * eye_z / focal_length,\n            eye_z;\n        eye.radius = 1;\n\n        // Disambiguate pupil circles using projected eyeball centre\n        //\n        // Assume that the gaze vector points away from the eye centre, and\n        // so projected gaze points away from projected eye centre. Pick the\n        // solution which satisfies this assumption\n        for (size_t i = 0; i < pupils.size(); ++i) {\n            const auto& pupil_pair = pupil_unprojection_pairs[i];\n            const auto& line = pupil_gazelines_proj[i];\n\n            const auto& c_proj = line.origin();\n            const auto& v_proj = line.direction();\n\n            // Check if v_proj going away from est eye centre. If it is, then\n            // the first circle was correct. Otherwise, take the second one.\n            // The two normals will point in opposite directions, so only need\n            // to check one.\n            if ((c_proj - eye_centre_proj).dot(v_proj) >= 0) {\n                pupils[i].circle = std::move(pupil_pair.first);\n            }\n            else {\n                pupils[i].circle = std::move(pupil_pair.second);\n            }\n        }\n    }\n    else {\n        // No inliers, so no eye\n        eye = Sphere::Null;\n\n        // Arbitrarily pick first circle\n        for (size_t i = 0; i < pupils.size(); ++i) {\n            const auto& pupil_pair = pupil_unprojection_pairs[i];\n            pupils[i].circle = std::move(pupil_pair.first);\n        }\n    }\n\n    model_version++;\n}\n", "meta": {"hexsha": "25135aacb9dcabf98eba931edbcfcc8709d2e3a3", "size": 64974, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "singleeyefitter/SingleEyeFitter.cpp", "max_stars_repo_name": "i170005/Eyetracker", "max_stars_repo_head_hexsha": "891bde7e1f8cfc3d3dfd8695e8510ad31cc5ceb8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 198.0, "max_stars_repo_stars_event_min_datetime": "2016-10-08T03:13:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T16:43:15.000Z", "max_issues_repo_path": "singleeyefitter/SingleEyeFitter.cpp", "max_issues_repo_name": "i170005/Eyetracker", "max_issues_repo_head_hexsha": "891bde7e1f8cfc3d3dfd8695e8510ad31cc5ceb8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 28.0, "max_issues_repo_issues_event_min_datetime": "2016-10-07T13:31:08.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-05T06:40:40.000Z", "max_forks_repo_path": "singleeyefitter/SingleEyeFitter.cpp", "max_forks_repo_name": "i170005/Eyetracker", "max_forks_repo_head_hexsha": "891bde7e1f8cfc3d3dfd8695e8510ad31cc5ceb8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 77.0, "max_forks_repo_forks_event_min_datetime": "2016-10-07T07:14:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-06T07:24:40.000Z", "avg_line_length": 36.2983240223, "max_line_length": 248, "alphanum_fraction": 0.6117831748, "num_tokens": 17540, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.5926665999540697, "lm_q1q2_score": 0.4730586493816609}}
{"text": "#include <iostream>\n#include <boost/random.hpp>\n#include <boost/random/normal_distribution.hpp>\n\nusing namespace std;\n\n\n// Simulation function of the gaussian model\nvoid gaussian_model(double* result, unsigned int k, double mu, double sigma, int seed) {\n  boost::mt19937 rng(seed);\n  boost::normal_distribution<> nd(mu, sigma);\n  boost::variate_generator<boost::mt19937, boost::normal_distribution<> > sampler(rng, nd);\n  \n  for (int i=0; i<k; ++i) {\n    result[i] = sampler();\n  }\n}\n\n\n// main function to run the simulation of the Gaussian model\nint main() {\n  int k = 10;\n  double samples[k];\n  gaussian_model(samples, 0.0, 1.0, k, 1);\n  \n  for (int i=0; i<k; ++i) {\n    std::cout << samples[i] << \" \";\n    std::cout << std::endl;\n  }\n  \n  return 0;\n}\n", "meta": {"hexsha": "46b3aff0ddd8a5af1c8efbef23c7e57a5a675159", "size": 754, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/extensions/models/gaussian_cpp/gaussian_model_simple.cpp", "max_stars_repo_name": "vishalbelsare/abcpy", "max_stars_repo_head_hexsha": "72d0d31ae3fa531b69ea3fef39c96af6628ee76f", "max_stars_repo_licenses": ["BSD-3-Clause-Clear"], "max_stars_count": 89.0, "max_stars_repo_stars_event_min_datetime": "2017-02-23T23:34:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T20:35:17.000Z", "max_issues_repo_path": "examples/extensions/models/gaussian_cpp/gaussian_model_simple.cpp", "max_issues_repo_name": "vishalbelsare/abcpy", "max_issues_repo_head_hexsha": "72d0d31ae3fa531b69ea3fef39c96af6628ee76f", "max_issues_repo_licenses": ["BSD-3-Clause-Clear"], "max_issues_count": 35.0, "max_issues_repo_issues_event_min_datetime": "2017-03-31T13:24:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-09T11:31:38.000Z", "max_forks_repo_path": "examples/extensions/models/gaussian_cpp/gaussian_model_simple.cpp", "max_forks_repo_name": "vishalbelsare/abcpy", "max_forks_repo_head_hexsha": "72d0d31ae3fa531b69ea3fef39c96af6628ee76f", "max_forks_repo_licenses": ["BSD-3-Clause-Clear"], "max_forks_count": 32.0, "max_forks_repo_forks_event_min_datetime": "2017-03-22T06:27:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-17T15:50:42.000Z", "avg_line_length": 22.8484848485, "max_line_length": 91, "alphanum_fraction": 0.6538461538, "num_tokens": 214, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.5926665999540697, "lm_q1q2_score": 0.4730586493816609}}
{"text": "#include <CMDParser.hpp>\n#include <FileBuffer.hpp>\n#include <calibvolume.hpp>\n#include <rgbdsensor.hpp>\n#include <DataTypes.hpp>\n#include <NearestNeighbourSearch.hpp>\n\n#include <squish.h>\n#include <boost/thread/thread.hpp>\n#include <boost/bind.hpp>\n\n#include <iostream>\n#include <fstream>\n#include <sstream>\n\n\nnamespace{\n\n  // bilateral filter\n  ////////////////////////////////////////////////////////////////////\n  int kernel_size = 6; // in pixel\n  int kernel_end = kernel_size + 1;\n  float dist_space_max_inv = 1.0/float(kernel_size);\n\n\n  float computeGaussSpace(float dist_space){\n    float gauss_coord = dist_space * dist_space_max_inv;\n    return 1.0 - gauss_coord;\n  }\n\n  float dist_range_max = 0.05; // in meter\n  float dist_range_max_inv = 1.0/dist_range_max;\n\n  float computeGaussRange(float dist_range){\n    float gauss_coord = std::min(dist_range, dist_range_max) * dist_range_max_inv;\n    return 1.0 - gauss_coord;\n  }\n\n  bool is_outside(const float d, const unsigned s_num, const std::vector<CalibVolume*> cvs){\n    return (d < cvs[s_num]->min_d) || (d > cvs[s_num]->max_d);\n  }\n\n  float look_up_depth(const int x, const int y, const unsigned s_num, const RGBDSensor& sensor){\n\n    if( (x < 0) ||\n\t(x > (sensor.config.size_d.x - 1)) ||\n\t(y < 0) ||\n\t(x > (sensor.config.size_d.y - 1))\n\t){\n      return 0.0;\n    }\n    const unsigned d_idx = y* sensor.config.size_d.x + x;\n    return s_num == 0 ? sensor.frame_d[d_idx] : sensor.slave_frames_d[s_num - 1][d_idx];\n  }\n\n\n\n  float bilateral_filter(const int x, const int y, const RGBDSensor& sensor, const unsigned s_num, const std::vector<CalibVolume*> cvs){\n    float filtered_depth = 0.0;\n\n    float depth = look_up_depth(x, y, s_num, sensor);\n    if(is_outside(depth, s_num, cvs)){\n      return 0.0;\n    }\n\n\n    // the valid range scales with depth\n    float max_depth = 4.5; // Kinect V2\n    float d_dmax = depth/max_depth;\n    dist_range_max = 0.35 * d_dmax; // threshold around \n    dist_range_max_inv = 1.0/dist_range_max;\n\n    float depth_bf = 0.0;\n\n    float w = 0.0;\n    float w_range = 0.0;\n    float border_samples = 0.0;\n    float num_samples = 0.0;\n    \n    for(int y_s = -kernel_size; y_s < kernel_end; ++y_s){\n      for(int x_s = -kernel_size; x_s < kernel_end; ++x_s){\n\tnum_samples += 1.0;\n\t\t\n\tconst float depth_s = look_up_depth(x + x_s, y + y_s, s_num, sensor);\n\n\tconst float depth_range = std::abs(depth_s - depth);\n\tif(is_outside(depth_s, s_num, cvs) || (depth_range > dist_range_max)){\n\t  border_samples += 1.0;\n\t  continue;\n\t}\n\t\n\tfloat gauss_space = computeGaussSpace(glm::length(glm::vec2(x_s,y_s)));\n\tfloat gauss_range = computeGaussRange(depth_range);\n\tfloat w_s = gauss_space * gauss_range;\n\tdepth_bf += w_s * depth_s;\n\tw += w_s;\n\tw_range += gauss_range;\n      }\n    }\n    \n    const float lateral_quality  = 1.0 - border_samples/num_samples;\n    \n    if(w > 0.0)\n      filtered_depth = depth_bf/w;\n    else\n      filtered_depth = 0.0;\n    \n    \n    if(w_range < (num_samples * 0.65)){\n      filtered_depth = 0.0;\n    }\n\n    return filtered_depth;\n\n  }\n\n\n\n\n  template <class T>\n  inline std::string\n  toStringP(T value, unsigned p)\n  {\n    std::ostringstream stream;\n    stream << std::setw(p) << std::setfill('0') << value;\n    return stream.str();\n  }\n\n\n  float calcAvgDist(const std::vector<nniSample>& neighbours, const nniSample& s){\n    float avd = 0.0;\n    for(const auto& n : neighbours){\n      const float dist = glm::length(glm::vec3(s.s_pos.x - n.s_pos.x,s.s_pos.y - n.s_pos.y,s.s_pos.z - n.s_pos.z));\n      avd += dist;\n    }\n    avd /= neighbours.size();\n    return avd;\n  }\n\n\n  glm::vec3 bbx_min = glm::vec3(-1.2, -0.05, -1.2);\n  glm::vec3 bbx_max = glm::vec3( 1.2, 2.4,  1.2);\n  \n  bool clip(const glm::vec3& p){\n    if(p.x < bbx_min.x ||\n       p.y < bbx_min.y ||\n       p.z < bbx_min.z ||\n       p.x > bbx_max.x ||\n       p.y > bbx_max.y ||\n       p.z > bbx_max.z){\n      return true;\n    }\n    return false;\n  }\n\n  float filter_pass_1_max_avg_dist_in_meter = 0.025;\n  float filter_pass_2_sd_fac = 1.0;\n  unsigned filter_pass_1_k = 50;\n  unsigned filter_pass_2_k = 50;\n\n  void filterPerThread(NearestNeighbourSearch* nns, std::vector<nniSample>* nnisamples, std::vector<std::vector<nniSample> >* results, const unsigned tid, const unsigned num_threads){\n\n    \n    for(unsigned sid = tid; sid < nnisamples->size(); sid += num_threads){\n      \n      nniSample s = (*nnisamples)[sid];\n      \n      if(filter_pass_1_k > 2){      \n\tstd::vector<nniSample> neighbours = nns->search(s,filter_pass_1_k);\n\tif(neighbours.empty()){\n\t  continue;\n\t}\n\t\n\tconst float avd = calcAvgDist(neighbours, s);\n\tif(avd > filter_pass_1_max_avg_dist_in_meter){\n\t  continue;\n\t}\n      }\n\n      if(filter_pass_2_k > 2){\n\tstd::vector<nniSample> neighbours = nns->search(s,filter_pass_2_k);\n\tconst float avd = calcAvgDist(neighbours, s);\n\tstd::vector<float> dists;\n\tfor(const auto& n : neighbours){\n\t  std::vector<nniSample> local_neighbours = nns->search(n,filter_pass_2_k);\n\t  if(!local_neighbours.empty()){\n\t    dists.push_back(calcAvgDist(local_neighbours, n));\n\t  }\n\t}\n\tdouble mean;\n\tdouble sd;\n\tcalcMeanSD(dists, mean, sd);\n\tif((avd - mean) > filter_pass_2_sd_fac * sd){\n\t  continue;\n\t}\n      }\n      (*results)[tid].push_back(s);\n    }\n\n  }\n\n}\n\n\n\nint main(int argc, char* argv[]){\n\n\n  unsigned num_threads = 16;\n  bool rgb_is_compressed = false;\n  std::string stream_filename;\n  CMDParser p(\"basefilename_cv .... basefilename_for_output\");\n  p.addOpt(\"s\",1,\"stream_filename\", \"specify the stream filename which should be converted\");\n  p.addOpt(\"n\",1,\"num_threads\", \"specify how many threads should be used, default 16\");\n  p.addOpt(\"c\",-1,\"rgb_is_compressed\", \"enable compressed support for rgb stream, default: false (not compressed)\");\n\n  p.addOpt(\"p1d\",1,\"filter_pass_1_max_avg_dist_in_meter\", \"filter pass 1 skips points which have an average distance of more than this to it k neighbors, default 0.025\");\n  p.addOpt(\"p1k\",1,\"filter_pass_1_k\", \"filter pass 1 number of neighbors, default 50\");\n  p.addOpt(\"p2s\",1,\"filter_pass_2_sd_fac\", \"filter pass 2, specify how many times a point's distance should be above (values higher than 1.0) / below (values smaller than 1.0) is allowed to be compared to standard deviation of its k neighbors, default 1.0\");\n  p.addOpt(\"p2k\",1,\"filter_pass_2_k\", \"filter pass 2 number of neighbors (the higher the more to process), default 50\");\n\n  p.addOpt(\"bbx\",6,\"bounding_box\", \"specify the bounding box x_min y_min z_min x_max y_max z_max in meters, default -1.2 -0.05 -1.2 1.2 2.4 1.2\");\n\n  p.addOpt(\"b\",1,\"bil_filter_depth_kernel\", \"specify the kernel size of the bilateral depth filter, e.g. -b 6, default 0 (no bilateral filter ist applied)\");\n\n  p.addOpt(\"f\",1,\"frames\", \"specify how many frames should be processed at maximum, e.g. -f 1, default 0 (all frames in the stream will be processed)\");\n\n  p.init(argc,argv);\n\n\n  if(p.isOptSet(\"bbx\")){\n    bbx_min = glm::vec3(p.getOptsFloat(\"bbx\")[0], p.getOptsFloat(\"bbx\")[1], p.getOptsFloat(\"bbx\")[2]);\n    bbx_max = glm::vec3(p.getOptsFloat(\"bbx\")[3], p.getOptsFloat(\"bbx\")[4], p.getOptsFloat(\"bbx\")[5]);\n    std::cout << \"setting bounding box to min: \" << bbx_min << \" -> max: \" << bbx_max << std::endl;\n  }\n\n\n  if(p.isOptSet(\"p1d\")){\n    filter_pass_1_max_avg_dist_in_meter = p.getOptsFloat(\"p1d\")[0];\n    std::cout << \"setting filter_pass_1_max_avg_dist_in_meter to \" << filter_pass_1_max_avg_dist_in_meter << std::endl;\n  }\n  if(p.isOptSet(\"p1k\")){\n    filter_pass_1_k = p.getOptsInt(\"p1k\")[0];\n    std::cout << \"setting filter_pass_1_k to \" << filter_pass_1_k << std::endl;\n  }\n  if(p.isOptSet(\"p2s\")){\n    filter_pass_2_sd_fac = p.getOptsFloat(\"p2s\")[0];\n    std::cout << \"setting filter_pass_2_sd_fac to \" << filter_pass_2_sd_fac << std::endl;\n  }\n  if(p.isOptSet(\"p2k\")){\n    filter_pass_2_k = p.getOptsInt(\"p2k\")[0];\n    std::cout << \"setting filter_pass_2_k to \" << filter_pass_2_k << std::endl;\n  }\n  \n\n\n  if(p.isOptSet(\"s\")){\n    stream_filename = p.getOptsString(\"s\")[0];\n  }\n  else{\n    std::cerr << \"ERROR, please specify stream filename with flag -s, see \" << argv[0] << \" -h for help\" << std::endl;\n    return 0;\n  }\n\n  if(p.isOptSet(\"n\")){\n    num_threads = p.getOptsInt(\"n\")[0];\n  }\n\n  if(p.isOptSet(\"c\")){\n    rgb_is_compressed = true;\n  }\n\n  bool using_bf = false;\n  if(p.isOptSet(\"b\")){\n    kernel_size = std::max(0, p.getOptsInt(\"b\")[0]);\n    kernel_end = kernel_size + 1;\n    dist_space_max_inv = 1.0/float(kernel_size);\n    using_bf = true;\n    std::cout << \"performing bilateral filtering with kernel size of: \" << kernel_size << std::endl;\n  }\n\n\n\n  const unsigned num_streams(p.getArgs().size() - 1);\n  const std::string basefilename_for_output = p.getArgs()[num_streams];\n\t\n  std::vector<CalibVolume*> cvs;\n  for(unsigned i = 0; i < num_streams; ++i){\n    std::string basefilename = p.getArgs()[i];\n    std::string filename_xyz(basefilename + \"_xyz\");\n    std::string filename_uv(basefilename + \"_uv\");\n    cvs.push_back(new CalibVolume(filename_xyz.c_str(), filename_uv.c_str()));\n  }\n\n\t\n  RGBDConfig cfg;\n  cfg.size_rgb = glm::uvec2(1280, 1080);\n  cfg.size_d   = glm::uvec2(512, 424);\n  RGBDSensor sensor(cfg, num_streams - 1);\t\n\n  unsigned char* tmp_rgb = 0;\n  unsigned char* tmp_rgba = 0;\n  const unsigned colorsize_tmp = cfg.size_rgb.x * cfg.size_rgb.y * 3;\n  const unsigned colorsize_tmpa = cfg.size_rgb.x * cfg.size_rgb.y * 4;\n  if(rgb_is_compressed){\n    tmp_rgb = new unsigned char [colorsize_tmp];\n    tmp_rgba = new unsigned char [colorsize_tmpa];\n  }\t\n  const unsigned colorsize = rgb_is_compressed ? 691200 : cfg.size_rgb.x * cfg.size_rgb.y * 3;\n  const unsigned depthsize = cfg.size_d.x * cfg.size_d.y * sizeof(float);\n\n  FileBuffer fb(stream_filename.c_str());\n  if(!fb.open(\"r\")){\n    std::cerr << \"ERROR, while opening \" << stream_filename << \" exiting...\" << std::endl;\n    return 1;\n  }\n\n  unsigned num_frames = fb.calcNumFrames(num_streams * (colorsize + depthsize));\n  if(p.isOptSet(\"f\")){\n    num_frames = std::min(std::max(0u, (unsigned) p.getOptsInt(\"f\")[0]), num_frames);\n    std::cout << \"processing \" << num_frames << \" frames of the stream\" << std::endl;\n  }\n  double curr_frame_time = 0.0;\n\n  unsigned frame_num = 0;\n  while(frame_num < num_frames){\n    ++frame_num;\n\n    for(unsigned s_num = 0; s_num < num_streams; ++s_num){\n      fb.read((unsigned char*) (s_num == 0 ? sensor.frame_rgb : sensor.slave_frames_rgb[s_num - 1]), colorsize);\n\n      if(s_num == 0){\n\tmemcpy((char*) &curr_frame_time, (const char*) sensor.frame_rgb, sizeof(double));\n\tstd::cout << \"curr_frame_time: \" << curr_frame_time << std::endl;\n      }\n\n      if(rgb_is_compressed){\n         // uncompress to rgb_tmp from (unsigned char*) (s_num == 0 ? sensor.frame_rgb : sensor.slave_frames_rgb[s_num - 1]) to tmp_rgba\n         squish::DecompressImage (tmp_rgba, cfg.size_rgb.x, cfg.size_rgb.y,\n                                  (unsigned char*) (s_num == 0 ? sensor.frame_rgb : sensor.slave_frames_rgb[s_num - 1]), squish::kDxt1);\n         // copy back rgbsensor\n         unsigned buffida = 0;\n         unsigned buffid = 0;\n         for(unsigned y = 0; y < cfg.size_rgb.y; ++y){\n\t   for(unsigned x = 0; x < cfg.size_rgb.x; ++x){\n\t     tmp_rgb[buffid++] = tmp_rgba[buffida++];\n\t     tmp_rgb[buffid++] = tmp_rgba[buffida++];\n\t     tmp_rgb[buffid++] = tmp_rgba[buffida++];\n\t     buffida++;\n           }\n         }\n         memcpy((unsigned char*) (s_num == 0 ? sensor.frame_rgb : sensor.slave_frames_rgb[s_num - 1]), tmp_rgb, colorsize_tmp);\n      }\n\n\n      fb.read((unsigned char*) (s_num == 0 ? sensor.frame_d : sensor.slave_frames_d[s_num - 1]), depthsize);\n    }\n\n\n\n    std::vector<nniSample> nnisamples;\n    for(unsigned s_num = 0; s_num < num_streams; ++s_num){\n      // do 3D reconstruction for each depth pixel\n      for(unsigned y = 0; y < sensor.config.size_d.y; ++y){\n\tfor(unsigned x = 0; x < (sensor.config.size_d.x - 3); ++x){\n\n\t  float d = 0.0;\n\t  if(!using_bf){\n\t    const unsigned d_idx = y* sensor.config.size_d.x + x;\n\t    d = s_num == 0 ? sensor.frame_d[d_idx] : sensor.slave_frames_d[s_num - 1][d_idx];\n\t  }\n\t  else{\n\t    d = bilateral_filter(x, y, sensor, s_num, cvs);\n\t  }\n\n\t  if(d < cvs[s_num]->min_d || d > cvs[s_num]->max_d){\n\t    continue;\n\t  }\n\n\t  glm::vec3 pos3D;\n\t  glm::vec2 pos2D_rgb;\n\t  \n\t  pos3D = cvs[s_num]->lookupPos3D( x * 1.0/sensor.config.size_d.x,\n\t\t\t\t\t   y * 1.0/sensor.config.size_d.y, d);\n\n\t  if(clip(pos3D)){\n\t    continue;\n\t  }\n\n\t  nniSample nnis;\n\t  nnis.s_pos.x = pos3D.x;\n\t  nnis.s_pos.y = pos3D.y;\n\t  nnis.s_pos.z = pos3D.z;\t\t\n\t\t\n\t  glm::vec2 pos2D_rgb_norm = cvs[s_num]->lookupPos2D_normalized( x * 1.0/sensor.config.size_d.x, \n\t\t\t\t\t\t\t\t\t y * 1.0/sensor.config.size_d.y, d);\n\t  pos2D_rgb = glm::vec2(pos2D_rgb_norm.x * sensor.config.size_rgb.x,\n\t\t\t\tpos2D_rgb_norm.y * sensor.config.size_rgb.y);\n\t  \n\t  glm::vec3 rgb = sensor.get_rgb_bilinear_normalized(pos2D_rgb, s_num);\n\n          \n\t  nnis.s_pos_off.x = rgb.x;\n\t  nnis.s_pos_off.y = rgb.y;\n\t  nnis.s_pos_off.z = rgb.z;\n\n\n          nnisamples.push_back(nnis);\n\n\t}\n      }\n    }\n    \n\n\n    \n    std::cout << \"start building acceleration structure for filtering \" << nnisamples.size() << \" points...\" << std::endl;\n    NearestNeighbourSearch nns(nnisamples);\n    std::vector<std::vector<nniSample> > results;\n    for(unsigned tid = 0; tid < num_threads; ++tid){\n      results.push_back(std::vector<nniSample>() );\n    }\n\n    std::cout << \"start filtering frame \" << frame_num << \" using \" << num_threads << \" threads.\" << std::endl;\n\n\n\n    boost::thread_group threadGroup;\n    for (unsigned tid = 0; tid < num_threads; ++tid){\n      threadGroup.create_thread(boost::bind(&filterPerThread, &nns, &nnisamples, &results, tid, num_threads));\n    }\n    threadGroup.join_all();\n#if 0\n    unsigned tid = 0;\n    for(unsigned sid = 0; sid < nnisamples.size(); ++sid){\n\n      nniSample s = nnisamples[sid];\n      \n      \n      std::vector<nniSample> neighbours = nns.search(s,filter_pass_1_k);\n      if(neighbours.empty()){\n\tcontinue;\n      }\n\n      const float avd = calcAvgDist(neighbours, s);\n      if(avd > filter_pass_1_max_avg_dist_in_meter){\n\tcontinue;\n      }\n      \n      std::vector<float> dists;\n      for(const auto& n : neighbours){\n\tstd::vector<nniSample> local_neighbours = nns.search(n,filter_pass_2_k);\n\tif(!local_neighbours.empty()){\n\t  dists.push_back(calcAvgDist(local_neighbours, n));\n\t}\n      }\n      double mean;\n      double sd;\n      calcMeanSD(dists, mean, sd);\n      if((avd - mean) > filter_pass_2_sd_fac * sd){\n\tcontinue;\n      }\n      results[tid].push_back(s);\n    }\n#endif\n\n    const std::string pcfile_name(basefilename_for_output + \"_\" + toStringP(frame_num, 5 /*fill*/) + \".xyz\");\n    std::ofstream pcfile(pcfile_name.c_str());\n    std::cout << \"start writing to file \" << pcfile_name << \" ...\" << std::endl;\n    for(unsigned tid = 0; tid < num_threads; ++tid){\n      for(const auto& s : results[tid]){\n\n\tint red   = (int) std::max(0.0f , std::min(255.0f, s.s_pos_off.x * 255.0f));\n\tint green = (int) std::max(0.0f , std::min(255.0f, s.s_pos_off.y * 255.0f));\n\tint blue  = (int) std::max(0.0f , std::min(255.0f, s.s_pos_off.z * 255.0f));\n\tpcfile << s.s_pos.x << \" \" << s.s_pos.y << \" \" << s.s_pos.z << \" \"\n\t       << red << \" \"\n\t       << green << \" \"\n\t       << blue << std::endl;\n\t\n      }\n      \n    }\n\n    pcfile.close();\n\n    const std::string tsfile_name(basefilename_for_output + \"_\" + toStringP(frame_num, 5 /*fill*/) + \".timestamp\");\n    std::ofstream tsfile(tsfile_name.c_str());\n    tsfile << curr_frame_time << std::endl;\n    tsfile.close();\n\n    std::cout << frame_num\n\t      << \" from \"\n\t      << num_frames\n\t      << \" processed and saved to: \"\n\t      << pcfile_name << std::endl << std::endl;\n\n  }\n  \n  return 0;\n}\n", "meta": {"hexsha": "6dfd8118a7f0fbfc37f9c3721f2daf7fd72c0f65", "size": 15645, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/convert_recording_to_point_cloud.cpp", "max_stars_repo_name": "aosterthun/rgbdri", "max_stars_repo_head_hexsha": "8e513172f512c902f7d6d8631c7580b5b62277c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/convert_recording_to_point_cloud.cpp", "max_issues_repo_name": "aosterthun/rgbdri", "max_issues_repo_head_hexsha": "8e513172f512c902f7d6d8631c7580b5b62277c4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/convert_recording_to_point_cloud.cpp", "max_forks_repo_name": "aosterthun/rgbdri", "max_forks_repo_head_hexsha": "8e513172f512c902f7d6d8631c7580b5b62277c4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.1653386454, "max_line_length": 258, "alphanum_fraction": 0.6347075743, "num_tokens": 4708, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4730586436912361}}
{"text": "//  Boost integer/static_min_max.hpp header file  ----------------------------//\r\n\r\n//  (C) Copyright Daryle Walker 2001.  Permission to copy, use, modify, sell\r\n//  and distribute this software is granted provided this copyright notice\r\n//  appears in all copies.  This software is provided \"as is\" without\r\n//  express or implied warranty, and with no claim as to its suitability\r\n//  for any purpose. \r\n\r\n//  See http://www.boost.org for updates, documentation, and revision history. \r\n\r\n#ifndef BOOST_INTEGER_STATIC_MIN_MAX_HPP\r\n#define BOOST_INTEGER_STATIC_MIN_MAX_HPP\r\n\r\n#include <boost/integer_fwd.hpp>  // self include\r\n\r\n#include <boost/config.hpp>  // for BOOST_STATIC_CONSTANT\r\n\r\n\r\nnamespace boost\r\n{\r\n\r\n\r\n//  Compile-time extrema class declarations  ---------------------------------//\r\n//  Get the minimum or maximum of two values, signed or unsigned.\r\n\r\ntemplate < long Value1, long Value2 >\r\nstruct static_signed_min\r\n{\r\n    BOOST_STATIC_CONSTANT( long, value = (Value1 > Value2) ? Value2 : Value1 );\r\n};\r\n\r\ntemplate < long Value1, long Value2 >\r\nstruct static_signed_max\r\n{\r\n    BOOST_STATIC_CONSTANT( long, value = (Value1 < Value2) ? Value2 : Value1 );\r\n};\r\n\r\ntemplate < unsigned long Value1, unsigned long Value2 >\r\nstruct static_unsigned_min\r\n{\r\n    BOOST_STATIC_CONSTANT( unsigned long, value\r\n     = (Value1 > Value2) ? Value2 : Value1 );\r\n};\r\n\r\ntemplate < unsigned long Value1, unsigned long Value2 >\r\nstruct static_unsigned_max\r\n{\r\n    BOOST_STATIC_CONSTANT( unsigned long, value\r\n     = (Value1 < Value2) ? Value2 : Value1 );\r\n};\r\n\r\n\r\n}  // namespace boost\r\n\r\n\r\n#endif  // BOOST_INTEGER_STATIC_MIN_MAX_HPP\r\n", "meta": {"hexsha": "b320f627882fbce62cfdac33ad095c321e5857e5", "size": 1632, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sdk/boost_1_30_0/boost/integer/static_min_max.hpp", "max_stars_repo_name": "acidicMercury8/xray-1.0", "max_stars_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2021-05-04T06:40:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T20:24:28.000Z", "max_issues_repo_path": "sdk/boost_1_30_0/boost/integer/static_min_max.hpp", "max_issues_repo_name": "acidicMercury8/xray-1.0", "max_issues_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_issues_repo_licenses": ["Linux-OpenIB"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sdk/boost_1_30_0/boost/integer/static_min_max.hpp", "max_forks_repo_name": "acidicMercury8/xray-1.0", "max_forks_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-11-07T16:57:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-05T13:17:12.000Z", "avg_line_length": 28.6315789474, "max_line_length": 81, "alphanum_fraction": 0.6819852941, "num_tokens": 371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867585368343, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.47305863231038564}}
{"text": "//  Created by xufeiwang on 21/12/19.\n#include <cstdlib>\n#include <iostream>\n#include <RcppArmadillo.h>\n#define _USE_MATH_DEFINES\n#include <cmath>\n#include <ctime>\n#include <vector>\n#include <fstream>\n#include <sstream>\n#include <algorithm>\n#include <utility>\n#include <armadillo>\nusing namespace std;\nusing namespace Rcpp;\nusing namespace arma;\n\ndouble log_res(float m, mat xx, colvec xy, double yy)\n{\n  if (det(xx) < 1e-10)\n    return (log(yy));\n  double res = yy - as_scalar(trans(xy) * solve(xx, xy));\n  return (log(res) - log(m));\n}\n\ndouble compute_loss(mat xx, colvec xy, double yy, colvec beta) \n{\n  return (yy - 2 * as_scalar(trans(xy) * beta) + as_scalar(trans(beta) * (xx * beta)));\n}\n\ndouble index(int n, int i, int j)\n{\n  int ind = (2*n-i+1)*i/2+j-i-1;\n  return (ind);\n}\n\nvoid M_cal(NumericVector* F, vector<int>* S, int p, double gamma)\n{ \n  NumericVector M(p+1,0.0);\n  for (int i=1; i<p+1; i++)\n  {\n    M[i] = gamma +(*F)[i-1];\n  }\n  \n  for (int i=2;i<p+1; i++)\n  {\n    for (int k=1; k<i; k++)\n    {\n      double temp = gamma + M[k] +(*F)[index(p,k,i)];\n      if (temp > M[i])\n      {\n        M[i] = temp;\n        (*S)[i] = k;\n      }\n    }\n  }\n  \n  return;\n}\n\n// [[Rcpp::export]]\nNumericVector knots_selection_cpp(NumericMatrix X, NumericVector y, int m, double lam0, NumericVector Knots, NumericVector u)\n{\n  int n = X.nrow();\n  int l = X.ncol();\n  \n  NumericMatrix SXX(n+1, l*l);\n  NumericMatrix SXy(n+1, l);\n  NumericVector Syy(n+1);\n  \n  for (int j=0; j<l*l; j++)\n    SXX(0, j) = 0;\n  for (int j=0; j<l; j++)\n    SXy(0, j) = 0;\n  Syy[0] = 0;\n  for (int i=1; i<n+1; i++)\n  {\n    SXy(i, 0) = SXy(i-1, 0) + y[i-1];\n    Syy[i] = Syy[i-1] + y[i-1] * y[i-1];\n    for (int j=0; j<l; j++) {\n      SXy(i, j) = SXy(i-1, j) + X(i-1, j) * y[i-1];\n      for (int k=0; k<l; k++) \n        SXX(i, j*l+k) = SXX(i-1, j*l+k) + X(i-1, j) * X(i-1, k);\n    }\n  }\n  \n  int p;\n  if (m == 0)\n    p = Knots.size() + 1;\n  else  \n    p = n / m;\n  NumericVector num(p+1, 0.0);\n  if (m == 0) {\n    int ind = 0;\n    for (int i=0; i<n; i++) {\n      if (u[i] > Knots[ind]) {\n        num[ind] = i;\n        ind = ind + 1;\n      }\n      num[p] = n;\n    }\n  } else {\n    int r = n - p * m;\n    int ind = 0 ;\n    for (int i=1;i<p+1;i++) {\n      if (i <= r)\n        ind += m+1;\n      else\n        ind += m;\n      num[i] = ind;\n    }\n  }\n  \n  int len = p*(p+1)/2;\n  NumericVector *ls = new NumericVector(len, 0.0);\n  vector<int> *S = new vector<int>(p+1, 0);\n  \n  NumericMatrix SXX_simple(p+1, l*l);\n  NumericMatrix SXy_simple(p+1, l);\n  NumericVector Syy_simple(p+1);\n  \n  for (int i=1;i<p+1;i++) {\n    int ind = int(num[i]);\n    for (int k=0; k<l*l; k++)\n      SXX_simple(i,k) = SXX(ind,k);\n    for (int k=0; k<l; k++)\n      SXy_simple(i,k) = SXy(ind,k);\n    Syy_simple[i] = Syy[ind];\n  }\n  \n  for (int i=0; i<p; i++) {\n    for (int j=i+1; j<p+1; j++){\n      mat xx(l, l);\n      colvec xy(l);\n      for (int k=0; k<l; k++) \n        xy[k] = SXy_simple(j, k) - SXy_simple(i, k);\n      for (int k1=0; k1<l; k1++) \n        for (int k2=0;k2<l; k2++)\n          xx(k1, k2) = SXX_simple(j, k1*l+k2) - SXX_simple(i, k1*l+k2);\n      (*ls)[index(p,i,j)] = -(num[j]-num[i])/2.0*log_res(num[j]-num[i], xx, xy, Syy_simple[j] - Syy_simple[i]);\n    }\n  }\n  double lam = -lam0*log(n)/2;\n  M_cal(ls, S, p, lam);\n  int slice = 1;\n  int temp = (*S)[p];\n  NumericVector knots(1);\n  knots[0] = n;\n  while (temp != 0)\n  {\n    knots.push_back(num[temp]);\n    temp = (*S)[temp];\n    slice += 1;\n  }\n  delete ls;\t\n  delete S;\n  return (knots);\n}", "meta": {"hexsha": "000040ce24070e3a3148d386fa45436a46a98f74", "size": 3500, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/knots_selection.cpp", "max_stars_repo_name": "wangxf0106/vcmasf", "max_stars_repo_head_hexsha": "55f2b09a4d4d290a90d08fb12bcccf45c599bd37", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/knots_selection.cpp", "max_issues_repo_name": "wangxf0106/vcmasf", "max_issues_repo_head_hexsha": "55f2b09a4d4d290a90d08fb12bcccf45c599bd37", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/knots_selection.cpp", "max_forks_repo_name": "wangxf0106/vcmasf", "max_forks_repo_head_hexsha": "55f2b09a4d4d290a90d08fb12bcccf45c599bd37", "max_forks_repo_licenses": ["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.1518987342, "max_line_length": 125, "alphanum_fraction": 0.5077142857, "num_tokens": 1350, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867585368344, "lm_q2_score": 0.5926665999540697, "lm_q1q2_score": 0.47305863231038564}}
{"text": "\ufeff#include \"rigid_body.hpp\"\n\n#include <Eigen/Eigenvalues>\n#include <Eigen/Geometry>\n\n#include <autodiff/autodiff_types.hpp>\n#include <finitediff.hpp>\n#include <logger.hpp>\n#include <physics/mass.hpp>\n#include <profiler.hpp>\n#include <utils/eigen_ext.hpp>\n#include <utils/flatten.hpp>\n#include <utils/not_implemented_error.hpp>\n\nnamespace ipc::rigid {\n\nvoid center_vertices(\n    Eigen::MatrixXd& vertices,\n    const Eigen::MatrixXi& edges,\n    const Eigen::MatrixXi& faces,\n    PoseD& pose)\n{\n    int dim = vertices.cols();\n\n    vertices.rowwise() += pose.position.transpose();\n\n    // compute the center of mass several times to get more accurate\n    pose.position.setZero(dim);\n    for (int i = 0; i < 10; i++) {\n        double mass;\n        VectorMax3d com;\n        MatrixMax3d inertia;\n        compute_mass_properties(\n            vertices, dim == 2 || faces.size() == 0 ? edges : faces, mass, com,\n            inertia);\n        vertices.rowwise() -= com.transpose();\n        pose.position += com;\n        if (com.squaredNorm() < 1e-8) {\n            break;\n        }\n    }\n}\n\nRigidBody::RigidBody(\n    const Eigen::MatrixXd& vertices,\n    const Eigen::MatrixXi& edges,\n    const Eigen::MatrixXi& faces,\n    const PoseD& pose,\n    const PoseD& velocity,\n    const PoseD& force,\n    const double density,\n    const VectorMax6b& is_dof_fixed,\n    const bool oriented,\n    const int group_id,\n    const RigidBodyType type,\n    const double kinematic_max_time,\n    const std::deque<PoseD>& kinematic_poses)\n    : group_id(group_id)\n    , type(type)\n    , vertices(vertices)\n    , edges(edges)\n    , faces(faces)\n    , is_dof_fixed(is_dof_fixed)\n    , is_oriented(oriented)\n    , mesh_selector(vertices.rows(), edges, faces)\n    , pose(pose)\n    , velocity(velocity)\n    , force(force)\n    , kinematic_max_time(kinematic_max_time)\n    , kinematic_poses(kinematic_poses)\n{\n    assert(dim() == pose.dim());\n    assert(dim() == velocity.dim());\n    assert(dim() == force.dim());\n    assert(edges.size() == 0 || edges.cols() == 2);\n    assert(faces.size() == 0 || faces.cols() == 3);\n\n    if (type == RigidBodyType::STATIC) {\n        this->is_dof_fixed.setOnes(this->is_dof_fixed.size());\n    } else if (this->is_dof_fixed.array().all()) {\n        this->type = RigidBodyType::STATIC;\n    }\n\n    center_vertices(this->vertices, edges, faces, this->pose);\n    VectorMax3d center_of_mass;\n    MatrixMax3d I;\n    compute_mass_properties(\n        this->vertices,\n        dim() == 2 || faces.size() == 0 ? edges : faces, //\n        mass, center_of_mass, I);\n    // assert(center_of_mass.squaredNorm() < 1e-8);\n\n    // Mass above is actually volume in m\u00b3 and density is Kg/m\u00b3\n    mass *= density;\n    if (dim() == 3) {\n        // Got this from Chrono: https://bit.ly/2RpbTl1\n        Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> es;\n        double threshold = I.lpNorm<Eigen::Infinity>() * 1e-16;\n        I = (threshold < I.array().abs()).select(I, 0.0);\n        es.compute(I);\n        if (es.info() != Eigen::Success) {\n            spdlog::error(\"Eigen decompostion of the inertia tensor failed!\");\n        }\n        moment_of_inertia = density * es.eigenvalues();\n        if ((moment_of_inertia.array() < 0).any()) {\n            spdlog::warn(\n                \"Negative moment of inertia ({}), inverting.\",\n                fmt_eigen(moment_of_inertia));\n            // Avoid negative epsilon inertias\n            moment_of_inertia =\n                (moment_of_inertia.array() < 0)\n                    .select(-moment_of_inertia, moment_of_inertia);\n        }\n        R0 = es.eigenvectors();\n        // Ensure that we have an orientation preserving transform\n        if (R0.determinant() < 0.0) {\n            R0.col(0) *= -1.0;\n        }\n        assert(R0.isUnitary(1e-9));\n        assert(fabs(R0.determinant() - 1.0) <= 1.0e-9);\n        int num_rot_dof_fixed =\n            is_dof_fixed.tail(PoseD::dim_to_rot_ndof(dim())).count();\n        if (num_rot_dof_fixed == 2) {\n            // Convert moment of inertia to world coordinates\n            // https://physics.stackexchange.com/a/268812\n            moment_of_inertia = -I.diagonal().array() + I.diagonal().sum();\n            R0.setIdentity();\n        } else if (num_rot_dof_fixed == 1) {\n            spdlog::warn(\"Rigid body dynamics with two rotational DoF has \"\n                         \"not been tested thoroughly.\");\n        }\n        // R = R\u1d62R\u2080\n        Eigen::AngleAxisd r = Eigen::AngleAxisd(\n            Eigen::Matrix3d(this->pose.construct_rotation_matrix() * R0));\n        this->pose.rotation = r.angle() * r.axis();\n        // v = Rv\u2080 + p = R\u1d62R\u2080v\u2080 + p = R\u1d62R\u2080R\u2080\u1d40v\u2080 + p\n        this->vertices = this->vertices * R0; // R\u2080\u1d40 * V\u2080\u1d40 = V\u2080 * R\u2080\n        // \u03c9 = R\u2080\u1d40\u03c9\u2080 (\u03c9\u2080 expressed in body coordinates)\n        this->velocity.rotation = R0.transpose() * this->velocity.rotation;\n        Eigen::Matrix3d Q_t0 = this->pose.construct_rotation_matrix();\n        this->Qdot = Q_t0 * Hat(this->velocity.rotation);\n        // \u03c4 = R\u2080\u1d40\u03c4\u2080 (\u03c4\u2080 expressed in body coordinates)\n        // NOTE: this transformation will be done later\n        // this->force.rotation = R0.transpose() * this->force.rotation;\n    } else {\n        moment_of_inertia = density * I.diagonal();\n        R0 = Eigen::Matrix<double, 1, 1>::Identity();\n    }\n\n    // Zero out the velocity and forces of fixed dof\n    this->velocity.zero_dof(is_dof_fixed, R0);\n    this->force.zero_dof(is_dof_fixed, R0);\n\n    // Update the previous pose and velocity to reflect the changes made\n    // here\n    this->pose_prev = this->pose;\n    this->velocity_prev = this->velocity;\n\n    this->acceleration = PoseD::Zero(dim());\n    this->Qddot.setZero();\n\n    // Compute and construct some useful constants\n    mass_matrix.resize(ndof());\n    mass_matrix.diagonal().head(pos_ndof()).setConstant(mass);\n    mass_matrix.diagonal().tail(rot_ndof()) = moment_of_inertia;\n\n    r_max = this->vertices.rowwise().norm().maxCoeff();\n\n    average_edge_length = 0;\n    for (long i = 0; i < edges.rows(); i++) {\n        average_edge_length +=\n            (this->vertices.row(edges(i, 0)) - this->vertices.row(edges(i, 1)))\n                .norm();\n    }\n    if (edges.rows() > 0) {\n        average_edge_length /= edges.rows();\n    }\n    assert(std::isfinite(average_edge_length));\n\n    init_bvh();\n}\n\nvoid RigidBody::init_bvh()\n{\n    PROFILE_POINT(\"RigidBody::init_bvh\");\n    PROFILE_START();\n\n    // heterogenous bounding boxes\n    std::vector<std::array<Eigen::Vector3d, 2>> aabbs(\n        num_codim_vertices() + num_codim_edges() + num_faces());\n\n    for (size_t i = 0; i < num_codim_vertices(); i++) {\n        size_t vi = mesh_selector.codim_vertices_to_vertices(i);\n        if (dim() == 2) {\n            aabbs[i][0][2] = 0;\n            aabbs[i][1][2] = 0;\n        }\n        aabbs[i][0].head(dim()) = vertices.row(i);\n        aabbs[i][1].head(dim()) = vertices.row(i);\n    }\n\n    size_t start_i = num_codim_vertices();\n    for (size_t i = 0; i < num_codim_edges(); i++) {\n        size_t ei = mesh_selector.codim_edges_to_edges(i);\n        const auto& e0 = vertices.row(edges(ei, 0));\n        const auto& e1 = vertices.row(edges(ei, 1));\n\n        if (dim() == 2) {\n            aabbs[start_i + i][0][2] = 0;\n            aabbs[start_i + i][1][2] = 0;\n        }\n        aabbs[start_i + i][0].head(dim()) = e0.cwiseMin(e1);\n        aabbs[start_i + i][1].head(dim()) = e0.cwiseMax(e1);\n    }\n\n    start_i += num_codim_edges();\n    for (size_t i = 0; i < num_faces(); i++) {\n        assert(dim() == 3);\n        const auto& f0 = vertices.row(faces(i, 0));\n        const auto& f1 = vertices.row(faces(i, 1));\n        const auto& f2 = vertices.row(faces(i, 2));\n        aabbs[start_i + i][0] = f0.cwiseMin(f1).cwiseMin(f2);\n        aabbs[start_i + i][1] = f0.cwiseMax(f1).cwiseMax(f2);\n    }\n\n    bvh.init(aabbs);\n\n    PROFILE_END();\n}\n\nEigen::MatrixXd RigidBody::world_velocities() const\n{\n    // compute x\u0307 = Q\u0307 * x_B + q\u0307\n    // where Q\u0307 = Q\u03c9\u0302\n    if (dim() == 2) {\n        MatrixMax3d Q_dt =\n            pose.construct_rotation_matrix() * Hat(velocity.rotation);\n        return (vertices * Q_dt.transpose()).rowwise()\n            + velocity.position.transpose();\n    }\n    return (vertices * Qdot.transpose()).rowwise()\n        + velocity.position.transpose();\n}\n\nvoid RigidBody::compute_bounding_box(\n    const PoseD& pose_t0,\n    const PoseD& pose_t1,\n    VectorMax3d& box_min,\n    VectorMax3d& box_max) const\n{\n    PROFILE_POINT(\"RigidBody::compute_bounding_box\");\n    PROFILE_START();\n\n    // If the body is not rotating then just use the linearized\n    // trajectory\n    if (type == RigidBodyType::STATIC\n        || (pose_t0.rotation.array() == pose_t1.rotation.array()).all()) {\n        Eigen::MatrixXd V0 = world_vertices(pose_t0);\n        box_min = V0.colwise().minCoeff();\n        box_max = V0.colwise().maxCoeff();\n        Eigen::MatrixXd V1 = world_vertices(pose_t1);\n        box_min = box_min.cwiseMin(V1.colwise().minCoeff().transpose());\n        box_max = box_max.cwiseMax(V1.colwise().maxCoeff().transpose());\n    } else {\n        // Use the maximum radius of the body to bound all rotations\n        box_min = pose_t0.position.cwiseMin(pose_t1.position).array() - r_max;\n        box_max = pose_t0.position.cwiseMax(pose_t1.position).array() + r_max;\n    }\n\n    PROFILE_END();\n}\n\n} // namespace ipc::rigid\n", "meta": {"hexsha": "b9b9028fe5634888046ad6f58446f074a46194a2", "size": 9289, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/physics/rigid_body.cpp", "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/physics/rigid_body.cpp", "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/physics/rigid_body.cpp", "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": 33.901459854, "max_line_length": 79, "alphanum_fraction": 0.5966196577, "num_tokens": 2564, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.47305191373962224}}
{"text": "/*\n################################################################################\n#                                                                              #\n#                                                                              #\n#                                                                              #\n################################################################################\n*/\n#include \"MolecularModelCVode.h\"\n#include \"ODE_system.h\"\n#include \"Param.h\"\n\n#include <boost/archive/xml_iarchive.hpp>\n#include <boost/archive/xml_oarchive.hpp>\n#include <boost/serialization/nvp.hpp>\n\n/*\n-------------------------------\n Main Program\n-------------------------------\n*/\n\n#define TASK_SIM 0\n#define TASK_SERIALIZATION 1  // example code for saving and loading a simulation\n\n//#define TASK TASK_SIM\n#define TASK TASK_SERIALIZATION \n\n#define SEC_PER_DAY 86400\n\nint main()\n{\n\tCancerQSP::Param param;\n\n\tstd::ostream &os = std::cout;\n\n\tparam.initializeParams(\"CancerQSP_params.xml\");\n\n\tdouble tStart = param.getVal(0);\n\tdouble stepInterval = 1.0 * SEC_PER_DAY * param.getVal(1);\n\tint nrStep = int(param.getVal(2));\n\n\t// class parameters\n\tCancerQSP::ODE_system::setup_class_parameters(param);\n\n\tMolecularModelCVode<CancerQSP::ODE_system> tmodel;\n\ttmodel.getSystem()->setup_instance_tolerance(param);\n\n\ttmodel.getSystem()->setup_instance_varaibles(param);\n\ttmodel.getSystem()->eval_init_assignment();\n\n#if TASK == TASK_SIM\n\t//------------------------------ simulation ------------------------------//\n\n\tstd::ofstream fs;\n\tfs.open(\"sim_results.csv\", std::ios::trunc);\n\n\t// header\n\tfs << \"t\" << tmodel.getSystem()->getHeader() << std::endl;\n\n\t// t = 0\n\tfs << tStart << tmodel << std::endl;\n\t// simulation: t: [0:360:1] days\n\tfor (auto i = 0; i < nrStep; i++)\n\t{\n\t\ttmodel.solve(tStart, stepInterval);\n\t\ttStart += stepInterval;\n\t\tfs << tStart << tmodel << std::endl;\n\t}\n\tfs.close();\n\n#elif TASK == TASK_SERIALIZATION\n\t//------------------------------  serialization ------------------------------//\n\ttypedef boost::archive::xml_iarchive iax;\n\ttypedef boost::archive::xml_oarchive oax;\n\tstd::ofstream fs0, fs1, out_save;\n\tstd::ifstream in_save;\n\n\t// simulation: t: [0:180:1] days\n\tfor (auto i = 0; i < nrStep/2; i++)\n\t{\n\t\ttmodel.solve(tStart, stepInterval);\n\t\ttStart += stepInterval;\n\t}\n\n\tdouble tPause = tStart;\n\n\t// save data\n\tout_save.open(\"save.xml\", std::ios::trunc);\n\toax oaState(out_save);\n\toaState << BOOST_SERIALIZATION_NVP(tmodel);\n\tCancerQSP::ODE_system::classSerialize(oaState, 0);\n\tout_save.close();\n\n\n\t// change class parameter to test class serialization\n\tCancerQSP::ODE_system::set_class_param(47, 250 * SEC_PER_DAY);\n\n\t// simulation: t: [180:360:1] days\n\tfs0.open(\"sim_results_0.csv\", std::ios::trunc);\n\tfs0 << \"t\" << tmodel.getSystem()->getHeader() << std::endl;\n\ttStart = tPause;\n\tfor (auto i = nrStep/2; i < nrStep; i++)\n\t{\n\t\ttmodel.solve(tStart, stepInterval);\n\t\ttStart += stepInterval;\n\t\tfs0 << tStart << tmodel << std::endl;\n\t}\n\tfs0.close();\n\n\n\t// load save\n\tMolecularModelCVode<CancerQSP::ODE_system> tmodel_2;\n\ttmodel_2.getSystem()->setup_instance_tolerance(param);\n\tin_save.open(\"save.xml\");\n\tiax iaState(in_save);\n\tiaState >> BOOST_SERIALIZATION_NVP(tmodel_2);\n\tCancerQSP::ODE_system::classSerialize(iaState, 0);\n\tin_save.close();\n\n\t// simulation: t: [180:360:1] days (load save)\n\tfs1.open(\"sim_results_1.csv\", std::ios::trunc);\n\tfs1 << \"t\" << tmodel_2.getSystem()->getHeader() << std::endl;\n\ttStart = tPause;\n\tfor (auto i = nrStep/2; i < nrStep; i++)\n\t{\n\t\ttmodel_2.solve(tStart, stepInterval);\n\t\ttStart += stepInterval;\n\t\tfs1 << tStart << tmodel_2 << std::endl;\n\t}\n\tfs1.close();\n\n#endif\n\n\treturn 0;\n}", "meta": {"hexsha": "e07d4d9edad777be8ac40ba5da167b97902ee0dc", "size": 3641, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sbml_cvode/example/cpp/single_simulation/QSP_single.cpp", "max_stars_repo_name": "popellab/SPQSP_IO", "max_stars_repo_head_hexsha": "eca3ea55ec2f75b0db5d58da09500ddffabc001d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sbml_cvode/example/cpp/single_simulation/QSP_single.cpp", "max_issues_repo_name": "popellab/SPQSP_IO", "max_issues_repo_head_hexsha": "eca3ea55ec2f75b0db5d58da09500ddffabc001d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sbml_cvode/example/cpp/single_simulation/QSP_single.cpp", "max_forks_repo_name": "popellab/SPQSP_IO", "max_forks_repo_head_hexsha": "eca3ea55ec2f75b0db5d58da09500ddffabc001d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9703703704, "max_line_length": 81, "alphanum_fraction": 0.5808843724, "num_tokens": 930, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4730519137396222}}
{"text": "#ifndef STAN_MATH_PRIM_SCAL_PROB_EXPONENTIAL_LPDF_HPP\n#define STAN_MATH_PRIM_SCAL_PROB_EXPONENTIAL_LPDF_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_not_nan.hpp>\n#include <stan/math/prim/scal/err/check_positive_finite.hpp>\n#include <stan/math/prim/scal/fun/value_of.hpp>\n#include <stan/math/prim/scal/meta/length.hpp>\n#include <stan/math/prim/scal/meta/scalar_seq_view.hpp>\n#include <stan/math/prim/scal/meta/VectorBuilder.hpp>\n#include <stan/math/prim/scal/meta/partials_return_type.hpp>\n#include <stan/math/prim/scal/meta/return_type.hpp>\n#include <stan/math/prim/scal/fun/constants.hpp>\n#include <stan/math/prim/scal/meta/include_summand.hpp>\n#include <boost/random/exponential_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <cmath>\n\nnamespace stan {\n  namespace math {\n\n    /**\n     * The log of an exponential density for y with the specified\n     * inverse scale parameter.\n     * Inverse scale parameter must be greater than 0.\n     * y must be greater than or equal to 0.\n     *\n     \\f{eqnarray*}{\n     y\n     &\\sim&\n     \\mbox{\\sf{Expon}}(\\beta) \\\\\n     \\log (p (y \\, |\\, \\beta) )\n     &=&\n     \\log \\left( \\beta \\exp^{-\\beta y} \\right) \\\\\n     &=&\n     \\log (\\beta) - \\beta y \\\\\n     & &\n     \\mathrm{where} \\; y > 0\n     \\f}\n     *\n     * @param y A scalar variable.\n     * @param beta Inverse scale parameter.\n     * @throw std::domain_error if beta is not greater than 0.\n     * @throw std::domain_error if y is not greater than or equal to 0.\n     * @tparam T_y Type of scalar.\n     * @tparam T_inv_scale Type of inverse scale.\n     */\n    template <bool propto, typename T_y, typename T_inv_scale>\n    typename return_type<T_y, T_inv_scale>::type\n    exponential_lpdf(const T_y& y, const T_inv_scale& beta) {\n      static const char* function(\"exponential_lpdf\");\n      typedef typename stan::partials_return_type<T_y, T_inv_scale>::type\n        T_partials_return;\n\n      if (!(stan::length(y) && stan::length(beta)))\n        return 0.0;\n\n      using std::log;\n\n      T_partials_return logp(0.0);\n      check_nonnegative(function, \"Random variable\", y);\n      check_positive_finite(function, \"Inverse scale parameter\", beta);\n      check_consistent_sizes(function,\n                             \"Random variable\", y,\n                             \"Inverse scale parameter\", beta);\n\n      scalar_seq_view<T_y> y_vec(y);\n      scalar_seq_view<T_inv_scale> beta_vec(beta);\n      size_t N = max_size(y, beta);\n\n      VectorBuilder<include_summand<propto, T_inv_scale>::value,\n                    T_partials_return, T_inv_scale> log_beta(length(beta));\n      for (size_t i = 0; i < length(beta); i++)\n        if (include_summand<propto, T_inv_scale>::value)\n          log_beta[i] = log(value_of(beta_vec[i]));\n\n      operands_and_partials<T_y, T_inv_scale>\n        ops_partials(y, beta);\n\n      for (size_t n = 0; n < N; n++) {\n        const T_partials_return beta_dbl = value_of(beta_vec[n]);\n        const T_partials_return y_dbl = value_of(y_vec[n]);\n        if (include_summand<propto, T_inv_scale>::value)\n          logp += log_beta[n];\n        if (include_summand<propto, T_y, T_inv_scale>::value)\n          logp -= beta_dbl * y_dbl;\n\n        if (!is_constant_struct<T_y>::value)\n          ops_partials.edge1_.partials_[n] -= beta_dbl;\n        if (!is_constant_struct<T_inv_scale>::value)\n          ops_partials.edge2_.partials_[n] += 1 / beta_dbl - y_dbl;\n      }\n      return ops_partials.build(logp);\n    }\n\n    template <typename T_y, typename T_inv_scale>\n    inline\n    typename return_type<T_y, T_inv_scale>::type\n    exponential_lpdf(const T_y& y, const T_inv_scale& beta) {\n      return exponential_lpdf<false>(y, beta);\n    }\n\n  }\n}\n#endif\n", "meta": {"hexsha": "3a48a85e0d790f0378a027e4b4a8c681467b70a3", "size": 3931, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/scal/prob/exponential_lpdf.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/prim/scal/prob/exponential_lpdf.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/prim/scal/prob/exponential_lpdf.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": 36.0642201835, "max_line_length": 75, "alphanum_fraction": 0.6639531926, "num_tokens": 1046, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4730519137396222}}
{"text": "// Copyright Michael Drexl 2005, 2006.\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt or copy at\n// http://boost.org/LICENSE_1_0.txt)\n\n// Example use of the resource-constrained shortest paths algorithm.\n#include <boost/config.hpp>\n\n#ifdef BOOST_MSVC\n#pragma warning(disable : 4267)\n#endif\n\n#include <boost/graph/adjacency_list.hpp>\n\n#include <boost/graph/r_c_shortest_paths.hpp>\n#include <iostream>\n\nusing namespace boost;\n\nstruct SPPRC_Example_Graph_Vert_Prop\n{\n    SPPRC_Example_Graph_Vert_Prop(int n = 0, int e = 0, int l = 0)\n    : num(n), eat(e), lat(l)\n    {\n    }\n    int num;\n    // earliest arrival time\n    int eat;\n    // latest arrival time\n    int lat;\n};\n\nstruct SPPRC_Example_Graph_Arc_Prop\n{\n    SPPRC_Example_Graph_Arc_Prop(int n = 0, int c = 0, int t = 0)\n    : num(n), cost(c), time(t)\n    {\n    }\n    int num;\n    // traversal cost\n    int cost;\n    // traversal time\n    int time;\n};\n\ntypedef adjacency_list< vecS, vecS, directedS, SPPRC_Example_Graph_Vert_Prop,\n    SPPRC_Example_Graph_Arc_Prop >\n    SPPRC_Example_Graph;\n\n// data structures for spp without resource constraints:\n// ResourceContainer model\nstruct spp_no_rc_res_cont\n{\n    spp_no_rc_res_cont(int c = 0) : cost(c) {};\n    spp_no_rc_res_cont& operator=(const spp_no_rc_res_cont& other)\n    {\n        if (this == &other)\n            return *this;\n        this->~spp_no_rc_res_cont();\n        new (this) spp_no_rc_res_cont(other);\n        return *this;\n    }\n    int cost;\n};\n\nbool operator==(\n    const spp_no_rc_res_cont& res_cont_1, const spp_no_rc_res_cont& res_cont_2)\n{\n    return (res_cont_1.cost == res_cont_2.cost);\n}\n\nbool operator<(\n    const spp_no_rc_res_cont& res_cont_1, const spp_no_rc_res_cont& res_cont_2)\n{\n    return (res_cont_1.cost < res_cont_2.cost);\n}\n\n// ResourceExtensionFunction model\nclass ref_no_res_cont\n{\npublic:\n    inline bool operator()(const SPPRC_Example_Graph& g,\n        spp_no_rc_res_cont& new_cont, const spp_no_rc_res_cont& old_cont,\n        graph_traits< SPPRC_Example_Graph >::edge_descriptor ed) const\n    {\n        new_cont.cost = old_cont.cost + g[ed].cost;\n        return true;\n    }\n};\n\n// DominanceFunction model\nclass dominance_no_res_cont\n{\npublic:\n    inline bool operator()(const spp_no_rc_res_cont& res_cont_1,\n        const spp_no_rc_res_cont& res_cont_2) const\n    {\n        // must be \"<=\" here!!!\n        // must NOT be \"<\"!!!\n        return res_cont_1.cost <= res_cont_2.cost;\n        // this is not a contradiction to the documentation\n        // the documentation says:\n        // \"A label $l_1$ dominates a label $l_2$ if and only if both are\n        // resident at the same vertex, and if, for each resource, the resource\n        // consumption of $l_1$ is less than or equal to the resource\n        // consumption of $l_2$, and if there is at least one resource where\n        // $l_1$ has a lower resource consumption than $l_2$.\" one can think of\n        // a new label with a resource consumption equal to that of an old label\n        // as being dominated by that old label, because the new one will have a\n        // higher number and is created at a later point in time, so one can\n        // implicitly use the number or the creation time as a resource for\n        // tie-breaking\n    }\n};\n// end data structures for spp without resource constraints:\n\n// data structures for shortest path problem with time windows (spptw)\n// ResourceContainer model\nstruct spp_spptw_res_cont\n{\n    spp_spptw_res_cont(int c = 0, int t = 0) : cost(c), time(t) {}\n    spp_spptw_res_cont& operator=(const spp_spptw_res_cont& other)\n    {\n        if (this == &other)\n            return *this;\n        this->~spp_spptw_res_cont();\n        new (this) spp_spptw_res_cont(other);\n        return *this;\n    }\n    int cost;\n    int time;\n};\n\nbool operator==(\n    const spp_spptw_res_cont& res_cont_1, const spp_spptw_res_cont& res_cont_2)\n{\n    return (res_cont_1.cost == res_cont_2.cost\n        && res_cont_1.time == res_cont_2.time);\n}\n\nbool operator<(\n    const spp_spptw_res_cont& res_cont_1, const spp_spptw_res_cont& res_cont_2)\n{\n    if (res_cont_1.cost > res_cont_2.cost)\n        return false;\n    if (res_cont_1.cost == res_cont_2.cost)\n        return res_cont_1.time < res_cont_2.time;\n    return true;\n}\n\n// ResourceExtensionFunction model\nclass ref_spptw\n{\npublic:\n    inline bool operator()(const SPPRC_Example_Graph& g,\n        spp_spptw_res_cont& new_cont, const spp_spptw_res_cont& old_cont,\n        graph_traits< SPPRC_Example_Graph >::edge_descriptor ed) const\n    {\n        const SPPRC_Example_Graph_Arc_Prop& arc_prop = get(edge_bundle, g)[ed];\n        const SPPRC_Example_Graph_Vert_Prop& vert_prop\n            = get(vertex_bundle, g)[target(ed, g)];\n        new_cont.cost = old_cont.cost + arc_prop.cost;\n        int& i_time = new_cont.time;\n        i_time = old_cont.time + arc_prop.time;\n        i_time < vert_prop.eat ? i_time = vert_prop.eat : 0;\n        return i_time <= vert_prop.lat ? true : false;\n    }\n};\n\n// DominanceFunction model\nclass dominance_spptw\n{\npublic:\n    inline bool operator()(const spp_spptw_res_cont& res_cont_1,\n        const spp_spptw_res_cont& res_cont_2) const\n    {\n        // must be \"<=\" here!!!\n        // must NOT be \"<\"!!!\n        return res_cont_1.cost <= res_cont_2.cost\n            && res_cont_1.time <= res_cont_2.time;\n        // this is not a contradiction to the documentation\n        // the documentation says:\n        // \"A label $l_1$ dominates a label $l_2$ if and only if both are\n        // resident at the same vertex, and if, for each resource, the resource\n        // consumption of $l_1$ is less than or equal to the resource\n        // consumption of $l_2$, and if there is at least one resource where\n        // $l_1$ has a lower resource consumption than $l_2$.\" one can think of\n        // a new label with a resource consumption equal to that of an old label\n        // as being dominated by that old label, because the new one will have a\n        // higher number and is created at a later point in time, so one can\n        // implicitly use the number or the creation time as a resource for\n        // tie-breaking\n    }\n};\n// end data structures for shortest path problem with time windows (spptw)\n\n// example graph structure and cost from\n// http://www.boost.org/libs/graph/example/dijkstra-example.cpp\nenum nodes\n{\n    A,\n    B,\n    C,\n    D,\n    E\n};\nchar name[] = \"ABCDE\";\n\nint main()\n{\n    SPPRC_Example_Graph g;\n\n    add_vertex(SPPRC_Example_Graph_Vert_Prop(A, 0, 0), g);\n    add_vertex(SPPRC_Example_Graph_Vert_Prop(B, 5, 20), g);\n    add_vertex(SPPRC_Example_Graph_Vert_Prop(C, 6, 10), g);\n    add_vertex(SPPRC_Example_Graph_Vert_Prop(D, 3, 12), g);\n    add_vertex(SPPRC_Example_Graph_Vert_Prop(E, 0, 100), g);\n\n    add_edge(A, C, SPPRC_Example_Graph_Arc_Prop(0, 1, 5), g);\n    add_edge(B, B, SPPRC_Example_Graph_Arc_Prop(1, 2, 5), g);\n    add_edge(B, D, SPPRC_Example_Graph_Arc_Prop(2, 1, 2), g);\n    add_edge(B, E, SPPRC_Example_Graph_Arc_Prop(3, 2, 7), g);\n    add_edge(C, B, SPPRC_Example_Graph_Arc_Prop(4, 7, 3), g);\n    add_edge(C, D, SPPRC_Example_Graph_Arc_Prop(5, 3, 8), g);\n    add_edge(D, E, SPPRC_Example_Graph_Arc_Prop(6, 1, 3), g);\n    add_edge(E, A, SPPRC_Example_Graph_Arc_Prop(7, 1, 5), g);\n    add_edge(E, B, SPPRC_Example_Graph_Arc_Prop(8, 1, 4), g);\n\n    // the unique shortest path from A to E in the dijkstra-example.cpp is\n    // A -> C -> D -> E\n    // its length is 5\n    // the following code also yields this result\n\n    // with the above time windows, this path is infeasible\n    // now, there are two shortest paths that are also feasible with respect to\n    // the vertex time windows:\n    // A -> C -> B -> D -> E and\n    // A -> C -> B -> E\n    // however, the latter has a longer total travel time and is therefore not\n    // pareto-optimal, i.e., it is dominated by the former path\n    // therefore, the code below returns only the former path\n\n    // spp without resource constraints\n    graph_traits< SPPRC_Example_Graph >::vertex_descriptor s = A;\n    graph_traits< SPPRC_Example_Graph >::vertex_descriptor t = E;\n\n    std::vector<\n        std::vector< graph_traits< SPPRC_Example_Graph >::edge_descriptor > >\n        opt_solutions;\n    std::vector< spp_no_rc_res_cont > pareto_opt_rcs_no_rc;\n\n    r_c_shortest_paths(g, get(&SPPRC_Example_Graph_Vert_Prop::num, g),\n        get(&SPPRC_Example_Graph_Arc_Prop::num, g), s, t, opt_solutions,\n        pareto_opt_rcs_no_rc, spp_no_rc_res_cont(0), ref_no_res_cont(),\n        dominance_no_res_cont(),\n        std::allocator< r_c_shortest_paths_label< SPPRC_Example_Graph,\n            spp_no_rc_res_cont > >(),\n        default_r_c_shortest_paths_visitor());\n\n    std::cout << \"SPP without resource constraints:\" << std::endl;\n    std::cout << \"Number of optimal solutions: \";\n    std::cout << static_cast< int >(opt_solutions.size()) << std::endl;\n    for (int i = 0; i < static_cast< int >(opt_solutions.size()); ++i)\n    {\n        std::cout << \"The \" << i << \"th shortest path from A to E is: \";\n        std::cout << std::endl;\n        for (int j = static_cast< int >(opt_solutions[i].size()) - 1; j >= 0;\n             --j)\n            std::cout << name[source(opt_solutions[i][j], g)] << std::endl;\n        std::cout << \"E\" << std::endl;\n        std::cout << \"Length: \" << pareto_opt_rcs_no_rc[i].cost << std::endl;\n    }\n    std::cout << std::endl;\n\n    // spptw\n    std::vector<\n        std::vector< graph_traits< SPPRC_Example_Graph >::edge_descriptor > >\n        opt_solutions_spptw;\n    std::vector< spp_spptw_res_cont > pareto_opt_rcs_spptw;\n\n    r_c_shortest_paths(g, get(&SPPRC_Example_Graph_Vert_Prop::num, g),\n        get(&SPPRC_Example_Graph_Arc_Prop::num, g), s, t, opt_solutions_spptw,\n        pareto_opt_rcs_spptw, spp_spptw_res_cont(0, 0), ref_spptw(),\n        dominance_spptw(),\n        std::allocator< r_c_shortest_paths_label< SPPRC_Example_Graph,\n            spp_spptw_res_cont > >(),\n        default_r_c_shortest_paths_visitor());\n\n    std::cout << \"SPP with time windows:\" << std::endl;\n    std::cout << \"Number of optimal solutions: \";\n    std::cout << static_cast< int >(opt_solutions.size()) << std::endl;\n    for (int i = 0; i < static_cast< int >(opt_solutions.size()); ++i)\n    {\n        std::cout << \"The \" << i << \"th shortest path from A to E is: \";\n        std::cout << std::endl;\n        for (int j = static_cast< int >(opt_solutions_spptw[i].size()) - 1;\n             j >= 0; --j)\n            std::cout << name[source(opt_solutions_spptw[i][j], g)]\n                      << std::endl;\n        std::cout << \"E\" << std::endl;\n        std::cout << \"Length: \" << pareto_opt_rcs_spptw[i].cost << std::endl;\n        std::cout << \"Time: \" << pareto_opt_rcs_spptw[i].time << std::endl;\n    }\n\n    // utility function check_r_c_path example\n    std::cout << std::endl;\n    bool b_is_a_path_at_all = false;\n    bool b_feasible = false;\n    bool b_correctly_extended = false;\n    spp_spptw_res_cont actual_final_resource_levels(0, 0);\n    graph_traits< SPPRC_Example_Graph >::edge_descriptor ed_last_extended_arc;\n    check_r_c_path(g, opt_solutions_spptw[0], spp_spptw_res_cont(0, 0), true,\n        pareto_opt_rcs_spptw[0], actual_final_resource_levels, ref_spptw(),\n        b_is_a_path_at_all, b_feasible, b_correctly_extended,\n        ed_last_extended_arc);\n    if (!b_is_a_path_at_all)\n        std::cout << \"Not a path.\" << std::endl;\n    if (!b_feasible)\n        std::cout << \"Not a feasible path.\" << std::endl;\n    if (!b_correctly_extended)\n        std::cout << \"Not correctly extended.\" << std::endl;\n    if (b_is_a_path_at_all && b_feasible && b_correctly_extended)\n    {\n        std::cout << \"Actual final resource levels:\" << std::endl;\n        std::cout << \"Length: \" << actual_final_resource_levels.cost\n                  << std::endl;\n        std::cout << \"Time: \" << actual_final_resource_levels.time << std::endl;\n        std::cout << \"OK.\" << std::endl;\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "2d759e73d5beda39b055b6958f6b4e7aeb0a46c5", "size": 11975, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/graph/example/r_c_shortest_paths_example.cpp", "max_stars_repo_name": "uosorio/heroku_face", "max_stars_repo_head_hexsha": "7d6465e71dba17a15d8edaef520adb2fcd09d91e", "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": "3rdparty/boost_1_73_0/libs/graph/example/r_c_shortest_paths_example.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 130.0, "max_issues_repo_issues_event_min_datetime": "2016-06-22T22:11:25.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-29T20:24:09.000Z", "max_forks_repo_path": "3rdparty/boost_1_73_0/libs/graph/example/r_c_shortest_paths_example.cpp", "max_forks_repo_name": "qingkouwei/mediaones", "max_forks_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2015-07-08T19:18:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-14T16:39:56.000Z", "avg_line_length": 35.960960961, "max_line_length": 80, "alphanum_fraction": 0.6531941545, "num_tokens": 3455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851919, "lm_q2_score": 0.6150878555160666, "lm_q1q2_score": 0.4730519072285875}}
{"text": "#include <boost/mp11/mpl.hpp>\n#include <tuple>\n#include <type_traits>\n\ntemplate <int I>\nusing int_ = std::integral_constant<int, I>;\n\nint main()\n{\n    using v1 = boost::mp11::mp_list_c<int, 5, 2, 3, 1, 4>;\n    using index1 = boost::mp11::mp_find<v1, int_<3>>;\n    using size1 = boost::mp11::mp_size<v1>;\n    using in_v1 = boost::mp11::mp_less<index1, size1>;\n    constexpr int r1{ boost::mp11::mp_if<in_v1, index1, int_<-1>>::value };\n    static_assert(r1 == 2);\n\n    using v2 = std::tuple<int_<5>, int_<2>, int_<3>>;\n    using index2 = boost::mp11::mp_find<v2, int_<6>>;\n    using size2 = boost::mp11::mp_size<v2>;\n    using in_v2 = boost::mp11::mp_less<index2, size2>;\n    constexpr int r2{ boost::mp11::mp_if<in_v2, index2, int_<-1>>::value };\n    static_assert(r2 == -1);\n}\n", "meta": {"hexsha": "1927f17300b774435c5b2fc505b51ecfa8a2ab23", "size": 778, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "13_boost_mp11_find_minus_one/13_boost_mp11_find_minus_one.cpp", "max_stars_repo_name": "BorisSchaeling/boost-meta-programming", "max_stars_repo_head_hexsha": "efdd64c8fdbc394bf6572fc10a84a9020581b6d5", "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": "13_boost_mp11_find_minus_one/13_boost_mp11_find_minus_one.cpp", "max_issues_repo_name": "BorisSchaeling/boost-meta-programming", "max_issues_repo_head_hexsha": "efdd64c8fdbc394bf6572fc10a84a9020581b6d5", "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": "13_boost_mp11_find_minus_one/13_boost_mp11_find_minus_one.cpp", "max_forks_repo_name": "BorisSchaeling/boost-meta-programming", "max_forks_repo_head_hexsha": "efdd64c8fdbc394bf6572fc10a84a9020581b6d5", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-06-03T08:29:22.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-29T08:42:49.000Z", "avg_line_length": 32.4166666667, "max_line_length": 75, "alphanum_fraction": 0.6362467866, "num_tokens": 272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851919, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4730519072285874}}
{"text": "#include <frovedis.hpp>\n#include <frovedis/ml/clustering/shrink_kmeans.hpp>\n\n#include <boost/program_options.hpp>\n\nusing namespace boost;\nusing namespace frovedis;\nusing namespace std;\n\nvoid do_kmeans(const string& input, bool dense, const string& output, int k,\n               int num_iteration, double eps, bool binary) {\n  if(binary) {\n    if(dense) {\n      time_spent t(DEBUG);\n      auto mat = make_rowmajor_matrix_loadbinary<double>(input);\n      t.show(\"load matrix: \");\n      auto r = kmeans(mat, k, num_iteration, eps);\n      t.show(\"kmeans time: \");\n      r.transpose().savebinary(output);\n      t.show(\"save centroid time: \");\n    } else {\n      time_spent t(DEBUG);\n      auto mat = make_crs_matrix_loadbinary<double>(input);\n      t.show(\"load matrix: \");\n      auto r = kmeans(std::move(mat), k, num_iteration, eps);\n      t.show(\"kmeans time: \");\n      r.transpose().savebinary(output);\n      t.show(\"save centroid time: \");\n    }\n  } else {\n    if(dense) {\n      time_spent t(DEBUG);\n      auto mat = make_rowmajor_matrix_load<double>(input);\n      t.show(\"load matrix: \");\n      auto r = kmeans(mat, k, num_iteration, eps);\n      t.show(\"kmeans time: \");\n      r.transpose().save(output);\n      t.show(\"save model time: \");\n    } else {\n      time_spent t(DEBUG);\n      auto mat = make_crs_matrix_load<double>(input);\n      t.show(\"load matrix: \");\n      auto r = kmeans(std::move(mat), k, num_iteration, eps);\n      t.show(\"kmeans time: \");\n      r.transpose().save(output);\n      t.show(\"save model time: \");\n    }\n  }\n}\n\nvoid do_assign(const string& input, bool dense, const string& input_centroid,\n               const string& output, bool binary) {\n  if(binary) {\n    if(dense) {\n      time_spent t(DEBUG);\n      auto mat = make_rowmajor_matrix_local_loadbinary<double>(input);\n      t.show(\"load matrix: \");\n      auto c = make_rowmajor_matrix_local_loadbinary<double>(input_centroid);\n      t.show(\"load centroid: \");\n      auto ct = c.transpose();\n      auto r = kmeans_assign_cluster(mat, ct);\n      make_dvector_scatter(r).savebinary(output);    \n    } else {\n      time_spent t(DEBUG);\n      auto mat = make_crs_matrix_local_loadbinary<double>(input);\n      t.show(\"load matrix: \");\n      auto c = make_rowmajor_matrix_local_loadbinary<double>(input_centroid);\n      t.show(\"load centroid: \");\n      auto ct = c.transpose();\n      auto r = kmeans_assign_cluster(mat, ct);\n      make_dvector_scatter(r).savebinary(output);    \n    }\n  } else {\n    if(dense) {\n      time_spent t(DEBUG);\n      auto mat = make_rowmajor_matrix_local_load<double>(input);\n      t.show(\"load matrix: \");\n      auto c = make_rowmajor_matrix_local_load<double>(input_centroid);\n      t.show(\"load centroid: \");\n      auto ct = c.transpose();\n      auto r = kmeans_assign_cluster(mat, ct);\n      make_dvector_scatter(r).saveline(output);    \n    } else {\n      time_spent t(DEBUG);\n      auto mat = make_crs_matrix_local_load<double>(input);\n      t.show(\"load matrix: \");\n      auto c = make_rowmajor_matrix_local_load<double>(input_centroid);\n      t.show(\"load centroid: \");\n      auto ct = c.transpose();\n      auto r = kmeans_assign_cluster(mat, ct);\n      make_dvector_scatter(r).saveline(output);    \n    }\n  }\n}\n\nint main(int argc, char* argv[]) {\n  use_frovedis use(argc, argv);\n\n  using namespace boost::program_options;\n\n  options_description opt(\"option\");\n  opt.add_options()\n    (\"help,h\", \"print help\")\n    (\"assign,a\", \"assign data to cluster mode\")\n    (\"input,i\", value<string>(), \"input matrix\")\n    (\"centroid,c\", value<string>(), \"input centroid for assignment\")\n    (\"output,o\", value<string>(), \"output centroids or cluster\")\n    (\"k,k\", value<int>(), \"number of clusters\")\n    (\"num-iteration,n\", value<int>(), \"number of max iteration\")\n    (\"eps,e\", value<double>(), \"epsilon to stop the iteration\")\n    (\"sparse,s\", \"use sparse matrix [default]\")\n    (\"dense,d\", \"use dense matrix\")\n    (\"verbose\", \"set loglevel to DEBUG\")\n    (\"verbose2\", \"set loglevel to TRACE\")\n    (\"binary,b\", \"use binary input/output\");\n\n  variables_map argmap;\n  store(command_line_parser(argc,argv).options(opt).allow_unregistered().\n        run(), argmap);\n  notify(argmap);\n\n  string input, output, input_centroid;\n  int num_iteration = 100;\n  int k;\n  double eps = 0.01;\n  bool assign = false;\n  bool dense = false;\n  bool binary = false;\n  \n  if(argmap.count(\"help\")){\n    cerr << opt << endl;\n    exit(1);\n  }\n\n  if(argmap.count(\"input\")){\n    input = argmap[\"input\"].as<string>();\n  } else {\n    cerr << \"input is not specified\" << endl;\n    cerr << opt << endl;\n    exit(1);\n  }\n\n  if(argmap.count(\"output\")){\n    output = argmap[\"output\"].as<string>();\n  } else {\n    cerr << \"output is not specified\" << endl;\n    cerr << opt << endl;\n    exit(1);\n  }\n\n  if(argmap.count(\"assign\")){\n    assign = true;\n  }\n\n  if(argmap.count(\"centroid\")){\n    input_centroid = argmap[\"centroid\"].as<string>();\n  } else {\n    if(assign == true) {\n      cerr << \"output is not specified\" << endl;\n      cerr << opt << endl;\n      exit(1);\n    }\n  }\n\n  if(argmap.count(\"k\")){\n    k = argmap[\"k\"].as<int>();\n  } else {\n    if(assign == false) {\n      cerr << \"number of cluster is not specified\" << endl;\n      cerr << opt << endl;\n      exit(1);\n    }\n  }\n\n  if(argmap.count(\"num-iteration\")){\n    num_iteration = argmap[\"num-iteration\"].as<int>();\n  }\n\n  if(argmap.count(\"epsilon\")){\n    eps = argmap[\"epsilon\"].as<double>();\n  }\n\n  if(argmap.count(\"sparse\")){\n    dense = false;\n  }\n\n  if(argmap.count(\"dense\")){\n    dense = true;\n  }\n\n  if(argmap.count(\"binary\")){\n    binary = true;\n  }\n\n  if(argmap.count(\"verbose\")){\n    set_loglevel(DEBUG);\n  }\n\n  if(argmap.count(\"verbose2\")){\n    set_loglevel(TRACE);\n  }\n\n  if(assign) do_assign(input, dense, input_centroid, output, binary);\n  else do_kmeans(input, dense, output, k, num_iteration, eps, binary);\n}\n", "meta": {"hexsha": "363461c4505c1e3c7ef2b2e2d4d8e8f0cb0be2f1", "size": 5853, "ext": "cc", "lang": "C++", "max_stars_repo_path": "samples/kmeans/shrink_kmeans.cc", "max_stars_repo_name": "wmeddie/frovedis", "max_stars_repo_head_hexsha": "c134e5e64114799cc7c265c72525ff98d06b49c1", "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": "samples/kmeans/shrink_kmeans.cc", "max_issues_repo_name": "wmeddie/frovedis", "max_issues_repo_head_hexsha": "c134e5e64114799cc7c265c72525ff98d06b49c1", "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": "samples/kmeans/shrink_kmeans.cc", "max_forks_repo_name": "wmeddie/frovedis", "max_forks_repo_head_hexsha": "c134e5e64114799cc7c265c72525ff98d06b49c1", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4126213592, "max_line_length": 77, "alphanum_fraction": 0.6113104391, "num_tokens": 1510, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851918, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.47305190722858736}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n\n#include \"core/volumetric/VolumetricOptimization.h\"\n\nfloat count_dist(float *r) {\n    float dist = 0;\n    for (int i = 0; i < 6891; i++)\n        dist += r[i] * r[i];\n    return sqrt(dist);\n}\n\nvoid surfelwarp::VolumetricOptimization::Solve(\n        DeviceArrayView<float4> &live_vertex,\n        cudaStream_t stream\n) {\n    CheckPoints(live_vertex, stream);\n    for (auto i = 0; i < Constants::kNumGaussNewtonIterations; i++) {\n        float r[6891], j[6891 * 72];\n        ComputeJacobian(live_vertex, j, stream);\n        ComputeResidual(live_vertex, r, stream);\n\n        Eigen::MatrixXf J = Eigen::Map<Eigen::Matrix<float, 6891, 72>>(j);\n        Eigen::VectorXf R(Eigen::Map<Eigen::VectorXf>(r, 6891));\n        Eigen::MatrixXf Jt = J.transpose();\n        Eigen::MatrixXf JtJ = Jt * J; // A\n        Eigen::VectorXf b = -1 * Jt * R;\n\n        Eigen::LeastSquaresConjugateGradient<Eigen::MatrixXf> lscg;\n        lscg.compute(JtJ);\n        auto x = lscg.solve(b);\n\n        std::vector<float> v;\n        for (int p = 0; p < 72; p++)\n            v.push_back(0.5 * x(p));\n        m_smpl_handler->AddTheta(v);\n\n        ComputeResidual(live_vertex, r, stream);\n        float dist1 = count_dist(r);\n\n        m_smpl_handler->SubTheta(v);\n        m_smpl_handler->SubTheta(v);\n\n        ComputeResidual(live_vertex, r, stream);\n        float dist2 = count_dist(r);\n        if (dist2 > dist1) {\n            m_smpl_handler->AddTheta(v);\n            m_smpl_handler->AddTheta(v);\n        }\n    }\n}", "meta": {"hexsha": "fddb145f94701ae2f5e2cf4738172971aa96f241", "size": 1521, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "core/volumetric/VolumetricOptimization.cpp", "max_stars_repo_name": "NataliaPonomarevaMM/DoubleSurfelFusion", "max_stars_repo_head_hexsha": "34b6a8f60f2bbdf133bd7262da5a48f49c85a8cc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-09-15T15:08:54.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-15T15:08:54.000Z", "max_issues_repo_path": "core/volumetric/VolumetricOptimization.cpp", "max_issues_repo_name": "NataliaPonomarevaMM/DoubleSurfelFusion", "max_issues_repo_head_hexsha": "34b6a8f60f2bbdf133bd7262da5a48f49c85a8cc", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/volumetric/VolumetricOptimization.cpp", "max_forks_repo_name": "NataliaPonomarevaMM/DoubleSurfelFusion", "max_forks_repo_head_hexsha": "34b6a8f60f2bbdf133bd7262da5a48f49c85a8cc", "max_forks_repo_licenses": ["BSD-3-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.8235294118, "max_line_length": 74, "alphanum_fraction": 0.5877712032, "num_tokens": 455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.4730510159607555}}
{"text": "#include <NTL/mat_GF2.h>\n#include <NTL/matrix.h>\n#include <NTL/GF2.h>\n#include <NTL/version.h>\n\nusing namespace NTL;\nusing namespace std;\n\nint main(int argc, char * argv[])\n{\n    Mat<GF2> mat;\n    mat.SetDims(2, 2);\n    for (int i = 0; i < 2; i++) {\n        for (int j = 0; j < 2; j++) {\n            cout << \"mat.put(i, j, 1)\" << endl;\n            mat.put(i, j, 1);\n            cout << \"mat.get(i, j) = \" << mat.get(i, j) << endl;\n            cout << \"mat.put(i, j, 0)\" << endl;\n            mat.put(i, j, 0);\n            cout << \"mat.get(i, j) = \" << mat.get(i, j) << endl;\n        }\n    }\n    mat.put(0,0,1);\n    mat.put(0,1,1);\n    mat.put(1,0,1);\n    mat.put(1,1,1);\n    cout << mat << endl;\n}\n", "meta": {"hexsha": "2e7750b07b4f53c0634722fde96a86e9d77fe955", "size": 697, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test_mat.cpp", "max_stars_repo_name": "MSaito/ntl-test1", "max_stars_repo_head_hexsha": "e9aed985dad50a49510c435007c610ac7066df21", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/test_mat.cpp", "max_issues_repo_name": "MSaito/ntl-test1", "max_issues_repo_head_hexsha": "e9aed985dad50a49510c435007c610ac7066df21", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/test_mat.cpp", "max_forks_repo_name": "MSaito/ntl-test1", "max_forks_repo_head_hexsha": "e9aed985dad50a49510c435007c610ac7066df21", "max_forks_repo_licenses": ["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.0344827586, "max_line_length": 64, "alphanum_fraction": 0.4490674319, "num_tokens": 252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.47303467778593833}}
{"text": "#include <iostream>\n#include <vector>\n#include <thread>\n#include <pcl/point_types.h>\n#include <pcl/io/pcd_io.h>\n#include <pcl/search/search.h>\n#include <pcl/search/kdtree.h>\n#include <pcl/features/normal_3d.h>\n#include <pcl/visualization/cloud_viewer.h>\n#include <pcl/filters/passthrough.h>\n#include <pcl/segmentation/region_growing.h>\n#include <pcl/filters/voxel_grid.h>\n#include <pcl_conversions/pcl_conversions.h>\n#include <pcl/segmentation/sac_segmentation.h>\n//#include <pcl/ModelCoefficients.h>\n//#include <pcl/sample_consensus/method_types.h>\n//#include <pcl/sample_consensus/model_types.h>\n\n#include <ros/ros.h>\n#include <geometry_msgs/PointStamped.h>\n#include <sensor_msgs/PointCloud2.h>\n#include <visualization_msgs/Marker.h>\n#include <visualization_msgs/MarkerArray.h>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <dynamic_reconfigure/server.h>\n#include \"region_growing_segmentation/TutorialsConfig.h\"\n#define PI 3.14\npcl::PointXYZ click_point;\nbool new_point = false;\nEigen::Vector3f marker_normal(0, 1, 0);\nfloat bias_x, bias_y, bias_z = 0;\nfloat bias_s_x, bias_s_z = 0;\nfloat bias_roll = 0, bias_pitch = 0, bias_yaw = 0;\nfloat bias_q_x, bias_q_y, bias_q_z, bias_q_w = 0;\n//pcl::visualization::CloudViewer viewer(\"Cluster viewer\");\nvisualization_msgs::MarkerArray marker_array;\npcl::PointCloud<pcl::PointXYZ>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>);\nvoid callback(region_growing_segmentation::TutorialsConfig &config, uint32_t level) {\n  ROS_INFO(\"Reconfigure Request: %f %f\",\n           config.position_x, config.position_y\n  );\n  bias_roll = config.roll * PI / 180;\n  bias_pitch = config.pitch * PI / 180;\n  bias_yaw = config.yaw * PI / 180;\n  Eigen::Quaternionf quaternionf;\n  Eigen::Vector3f euler_angle(bias_yaw, bias_pitch, bias_roll);\n  quaternionf = Eigen::AngleAxisf(euler_angle[0], Eigen::Vector3f::UnitZ()) *\n      Eigen::AngleAxisf(euler_angle[1], Eigen::Vector3f::UnitY()) *\n      Eigen::AngleAxisf(euler_angle[2], Eigen::Vector3f::UnitX());\n\n  bias_x = config.position_x;\n  bias_y = config.position_y;\n  bias_z = config.position_z;\n  bias_q_x = quaternionf.x();\n  bias_q_y = quaternionf.y();\n  bias_q_z = quaternionf.z();\n//  bias_q_w = quaternionf.w();\n//  cout << \"quaternionf x: \" << quaternionf.x() << endl;\n//  cout << \"quaternionf y: \" << quaternionf.y() << endl;\n//  cout << \"quaternionf z: \" << quaternionf.z() << endl;\n//  cout << \"quaternionf w: \" << quaternionf.w() << endl;\n\n  bias_s_x = config.scale_x;\n  bias_s_z = config.scale_z;\n}\n\nvoid pointCallback(const geometry_msgs::PointStampedPtr &msg) {\n  std::cout << \"new point\" << std::endl;\n  click_point.x = msg->point.x;\n  click_point.y = msg->point.y;\n  click_point.z = msg->point.z;\n  new_point = true;\n}\n\nvoid cloudCallback(const sensor_msgs::PointCloud2ConstPtr &input) {\n  //cout << \"I RECEIVED INPUT !\" << endl;\n  //std::lock_guard<std::mutex> lock(cloud_lock_);\n  pcl::fromROSMsg(*input, *cloud);\n}\n//void runViewer(){\n//  while (!viewer.wasStopped()) {\n//  }\n//}\nEigen::Vector3f crossProduct(Eigen::Vector3f a, Eigen::Vector3f b) {\n  Eigen::Vector3f c;\n\n  c[0] = a[1] * b[2] - a[2] * b[1];\n  c[1] = a[2] * b[0] - a[0] * b[2];\n  c[2] = a[0] * b[1] - a[1] * b[0];\n\n  return c;\n}\n\nfloat dotProduct(Eigen::Vector3f a, Eigen::Vector3f b) {\n  float result;\n  result = a[0] * b[0] + a[1] * b[1] + a[2] * b[2];\n  return result;\n}\n\nfloat normalize(Eigen::Vector3f v) {\n  float result;\n  result = sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]);\n  return result;\n}\n\nEigen::Matrix3f rotationMatrix(float angle, Eigen::Vector3f u) {\n  float norm = normalize(u);\n  Eigen::Matrix3f rotatinMatrix;\n\n  u(0) = u(0) / norm;\n  u(1) = u(1) / norm;\n  u(2) = u(2) / norm;\n\n  rotatinMatrix(0, 0) = cos(angle) + u(0) * u(0) * (1 - cos(angle));\n  rotatinMatrix(0, 1) = u(0) * u(1) * (1 - cos(angle)) - u(2) * sin(angle);\n  rotatinMatrix(0, 2) = u(1) * sin(angle) + u(0) * u(2) * (1 - cos(angle));\n\n  rotatinMatrix(1, 0) = u(2) * sin(angle) + u(0) * u(1) * (1 - cos(angle));\n  rotatinMatrix(1, 1) = cos(angle) + u(1) * u(1) * (1 - cos(angle));\n  rotatinMatrix(1, 2) = -u(0) * sin(angle) + u(1) * u(2) * (1 - cos(angle));\n\n  rotatinMatrix(2, 0) = -u(1) * sin(angle) + u(0) * u(2) * (1 - cos(angle));\n  rotatinMatrix(2, 1) = u(0) * sin(angle) + u(1) * u(2) * (1 - cos(angle));\n  rotatinMatrix(2, 2) = cos(angle) + u(2) * u(2) * (1 - cos(angle));\n\n  return rotatinMatrix;\n}\nEigen::Matrix3f calculationNormalRotation(Eigen::Vector3f plane_normal) {\n  Eigen::Vector3f rotation_axis;\n  float rotation_angle;\n  Eigen::Matrix3f rotation_matrix;\n  rotation_axis = crossProduct(marker_normal, plane_normal);\n  rotation_angle = acos(dotProduct(marker_normal, plane_normal) / normalize(marker_normal) / normalize(plane_normal));\n  rotation_matrix = rotationMatrix(rotation_angle, rotation_axis);\n  return rotation_matrix;\n}\n\nvisualization_msgs::MarkerArray drawMarker(Eigen::Vector3f plane_normal, pcl::PointXYZ min_point) {\n  Eigen::Matrix3f rotation_matrix = calculationNormalRotation(plane_normal);\n  Eigen::Quaternionf q(rotation_matrix);\n  visualization_msgs::Marker marker;\n  marker.header.frame_id = \"livox_frame\";\n  marker.header.stamp = ros::Time();\n  marker.ns = \"/\";\n  marker.id = 0;\n  marker.type = visualization_msgs::Marker::CUBE;\n  marker.action = visualization_msgs::Marker::ADD;\n  marker.pose.position.x = min_point.x + bias_x;\n  marker.pose.position.y = min_point.y + bias_y;\n  marker.pose.position.z = min_point.z + bias_z;\n  marker.pose.orientation.x = q.x() + bias_q_x;\n  marker.pose.orientation.y = q.y() + bias_q_y;\n  marker.pose.orientation.z = q.z() + bias_q_z;\n  marker.pose.orientation.w = q.w() + bias_q_w;\n  //std::cout << \"quaternion x y z :\" << q.x() << \" \" << q.y() << \" \" << q.z() << std::endl;\n  marker.scale.x = 10 + bias_s_x;\n  marker.scale.y = 0.1;\n  marker.scale.z = 10 + bias_s_z;\n  marker.color.a = 1.0; // Don't forget to set the alpha!\n  marker.color.r = 0.0;\n  marker.color.g = 1.0;\n  marker.color.b = 0.0;\n  marker_array.markers.push_back(marker);\n  return marker_array;\n}\n\npcl::PointXYZ minDisPoint(pcl::PointCloud<pcl::PointXYZ> result_point) {\n  int min_dis = 5000;\n  int temp_dis = 0;\n  int point_index = 0;\n  for (int i = 0; i < result_point.points.size(); i++) {\n    temp_dis = abs(0.099276 * result_point.points[i].x - 0.994441 * result_point.points[i].y\n                       + 0.03509592 * result_point.points[i].z + 14.3107);\n    if (temp_dis < min_dis) {\n      min_dis = temp_dis;\n      point_index = i;\n    }\n  }\n  std::cout << \"min distance: \" << min_dis << std::endl;\n  return result_point.points[point_index];\n}\n\nint\nmain(int argc, char **argv) {\n  ros::init(argc, argv, \"region_growing_segmention\");\n\n  dynamic_reconfigure::Server<region_growing_segmentation::TutorialsConfig> server;\n  dynamic_reconfigure::Server<region_growing_segmentation::TutorialsConfig>::CallbackType f;\n\n  f = boost::bind(&callback, _1, _2);\n  server.setCallback(f);\n\n  ros::NodeHandle nh;\n  ros::Subscriber point_sub = nh.subscribe(\"/clicked_point\", 1, pointCallback);\n  ros::Publisher seg_cloud_pub = nh.advertise<sensor_msgs::PointCloud2>(\"/seg_pointcloud\", 1);\n  ros::Publisher cloud_pub = nh.advertise<sensor_msgs::PointCloud2>(\"/pointcloud\", 1);\n  ros::Publisher vis_pub = nh.advertise<visualization_msgs::MarkerArray>(\"visualization_marker\", 0);\n  ros::Subscriber cloud_sub = nh.subscribe(\"/trans_pointcloud\",1,cloudCallback);\n//  if (pcl::io::loadPCDFile<pcl::PointXYZ>(\"/home/hjx/Documents/sub_map.pcd\", *cloud) == -1) {\n//    std::cout << \"Cloud reading failed.\" << std::endl;\n//    return (-1);\n//  }\n\n  pcl::PointCloud<pcl::PointXYZ>::Ptr downsampled(new pcl::PointCloud<pcl::PointXYZ>());\n  pcl::VoxelGrid<pcl::PointXYZ> voxelgrid;\n  voxelgrid.setLeafSize(0.1f, 0.1f, 0.1f);\n//  voxelgrid.setInputCloud(cloud);\n//  voxelgrid.filter(*downsampled);\n//  *cloud = *downsampled;\n\n//  sensor_msgs::PointCloud2 out_pointcloud;\n//  pcl::toROSMsg(*cloud, out_pointcloud);\n//  out_pointcloud.header.frame_id = \"livox_frame\";\n  //cloud_pub.publish(out_pointcloud);\n\n  pcl::search::Search<pcl::PointXYZ>::Ptr tree(new pcl::search::KdTree<pcl::PointXYZ>);\n  pcl::PointCloud<pcl::Normal>::Ptr normals(new pcl::PointCloud<pcl::Normal>);\n  pcl::NormalEstimation<pcl::PointXYZ, pcl::Normal> normal_estimator;\n  normal_estimator.setSearchMethod(tree);\n//  normal_estimator.setInputCloud(cloud);\n//  normal_estimator.setKSearch(50);\n//  normal_estimator.compute(*normals);\n\n//  pcl::IndicesPtr indices(new std::vector<int>);\n//  pcl::PassThrough<pcl::PointXYZ> pass;\n//  pass.setInputCloud(cloud);\n//  pass.setFilterFieldName(\"z\");\n//  pass.setFilterLimits(0.0, 1.0);\n//  pass.filter(*indices);\n\n  pcl::RegionGrowing<pcl::PointXYZ, pcl::Normal> reg;\n  reg.setMinClusterSize(50);\n  reg.setMaxClusterSize(1000000);\n  reg.setSearchMethod(tree);\n  reg.setNumberOfNeighbours(30);\n//  reg.setInputCloud(cloud);\n//  //reg.setIndices (indices);\n//  reg.setInputNormals(normals);\n  reg.setSmoothnessThreshold(3.0 / 180.0 * M_PI);\n  reg.setCurvatureThreshold(1.0);\n  pcl::PointIndices point_cluster;\n\n  std::vector<int> index;\n  std::vector<float> sqr_distance;\n  pcl::PointCloud<pcl::PointXYZRGB>::Ptr colored_cloud(new pcl::PointCloud<pcl::PointXYZRGB>);\n  pcl::PointCloud<pcl::PointXYZ> result_point;\n  sensor_msgs::PointCloud2 seg_out_pointcloud;\n  visualization_msgs::MarkerArray marker;\n  pcl::PointXYZ min_point = click_point;\n  Eigen::Vector3f plane_normal(0, 1, 0);\n  ros::Rate sleep_rate(10);\n  while (ros::ok()) {\n    //cloud_pub.publish(out_pointcloud);\n    if (new_point) {\n      voxelgrid.setInputCloud(cloud);\n      voxelgrid.filter(*downsampled);\n      *cloud = *downsampled;\n\n      normal_estimator.setInputCloud(cloud);\n      normal_estimator.setKSearch(50);\n      normal_estimator.compute(*normals);\n\n      reg.setInputCloud(cloud);\n      //reg.setIndices (indices);\n      reg.setInputNormals(normals);\n\n      tree->nearestKSearch(click_point, 1, index, sqr_distance);\n      reg.getSegmentFromPoint(index[0], point_cluster);\n      result_point.clear();\n      for (std::vector<int>::iterator it = point_cluster.indices.begin(); it != point_cluster.indices.end(); it++) {\n        result_point.points.push_back(cloud->points[*it]);\n      }\n\n      pcl::ModelCoefficients::Ptr coefficients(new pcl::ModelCoefficients);\n      pcl::PointIndices::Ptr inliers(new pcl::PointIndices);\n\n      pcl::SACSegmentation<pcl::PointXYZ> seg;\n\n      seg.setOptimizeCoefficients(true);\n\n      seg.setModelType(pcl::SACMODEL_PLANE);\n      seg.setMethodType(pcl::SAC_RANSAC);\n      seg.setDistanceThreshold(0.01);\n      seg.setInputCloud(result_point.makeShared());\n      seg.segment(*inliers, *coefficients);\n      if (inliers->indices.size() == 0) {\n        PCL_ERROR (\"Could not estimate a planar model for the given dataset.\");\n        return (-1);\n      }\n      std::cerr << \"Model coefficients: \" << coefficients->values[0] << \" \"\n                << coefficients->values[1] << \" \"\n                << coefficients->values[2] << \" \"\n                << coefficients->values[3] << std::endl;\n      plane_normal << coefficients->values[0], coefficients->values[1], coefficients->values[2];\n      min_point = minDisPoint(result_point);\n\n\n//      std::vector<pcl::PointIndices> clusters;\n//      reg.extract(clusters);\n//\n//      std::cout << \"Number of clusters is equal to \" << clusters.size() << std::endl;\n//      std::cout << \"First cluster has \" << clusters[0].indices.size() << \" points.\" << std::endl;\n//      std::cout << \"These are the indices of the points of the initial\" <<\n//                std::endl << \"cloud that belong to the first cluster:\" << std::endl;\n//      int counter = 0;\n//      while (counter < clusters[0].indices.size()) {\n//        std::cout << clusters[0].indices[counter] << \", \";\n//        counter++;\n//        if (counter % 10 == 0)\n//          std::cout << std::endl;\n//      }\n//      std::cout << std::endl;\n\n//      pcl::PointCloud<pcl::PointXYZRGB>::Ptr colored_cloud = reg.getColoredCloud();\n      //colored_cloud = reg.getColoredCloud();\n      //pcl::io::savePCDFileASCII(\"colored_cloud.pcd\", result_point);\n      new_point = false;\n    }\n    marker = drawMarker(plane_normal, min_point);\n\n    vis_pub.publish(marker);\n\n//    pcl::visualization::CloudViewer viewer(\"Cluster viewer\");\n    if (!result_point.empty()) {\n      pcl::toROSMsg(result_point, seg_out_pointcloud);\n      seg_out_pointcloud.header.frame_id = \"livox_frame\";\n      seg_cloud_pub.publish(seg_out_pointcloud);\n    }\n    ros::spinOnce();\n    sleep_rate.sleep();\n\n  }\n//  while (!viewer.wasStopped()) {\n//  }\n\n  return (0);\n}\n", "meta": {"hexsha": "3c031a3c0a5d876bdc2ff55a476f83986a85e7d0", "size": 12526, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/plane_seg_clickpoint.cpp", "max_stars_repo_name": "hjxwhy/tools-for-pointcloud", "max_stars_repo_head_hexsha": "5cdc6d5b7a01fd9652fe2ec115744bf63b141769", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/plane_seg_clickpoint.cpp", "max_issues_repo_name": "hjxwhy/tools-for-pointcloud", "max_issues_repo_head_hexsha": "5cdc6d5b7a01fd9652fe2ec115744bf63b141769", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/plane_seg_clickpoint.cpp", "max_forks_repo_name": "hjxwhy/tools-for-pointcloud", "max_forks_repo_head_hexsha": "5cdc6d5b7a01fd9652fe2ec115744bf63b141769", "max_forks_repo_licenses": ["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.9498525074, "max_line_length": 118, "alphanum_fraction": 0.6716429826, "num_tokens": 3593, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.47303467778593833}}
{"text": "\n# pragma once\n//#define EIGEN_USE_MKL_ALL\n#include\"basis.hpp\"\n#include<cmath>\n\n#include <Eigen/Sparse>\n#ifdef MOM\nusing ValType= std::complex<double>; \n#else\nusing ValType= double;\n#endif\nnamespace Operators{\n  using Many_Body::pi;\n  using  Many_Body::GetLattice;\n  using  Many_Body::Translate;\n  using  Many_Body::Position;\n  //   using  Many_Body::State();\n  using Many_Body::RightId;\n  using Many_Body::LeftId;\n  \n  using Mat= Eigen::SparseMatrix<ValType,Eigen::RowMajor>;\n\n\n    template<typename T>\n    size_t CheckSign(const T& state, size_t i, size_t j)\n  {\n    size_t m=0;\n    if(i>j)\n      {\n  \tfor(size_t l=j+1; l<i; l++)\n  \t  {\n  \t    m+=size_t(state[l]);\n  \t  }\n\n      }\n    else\n      \tfor(size_t l=i+1; l<j; l++)\n  \t  {\n  \t    m+=size_t(state[l]);\n  \t  }\n    return m;\n  }\n    template<typename TotalBasis, typename State, typename Lattice>\n  void Act(int i, int j, TotalBasis& totalBasis, State& tpState, Lattice state, Mat& op, double var)\n  {\n    if(state[i]==state[j])\n      {\t\n    \t\t  \n      }\n    else{\n      Lattice temp=state;\n      //  std::cout<< \"i,jx \"<< i << \", \"<< j << std::endl;\n       state.flip(i);\n       //setPartNr(j, temp[i]);\n      state.flip(j);\n\t\t     \t\t \n      size_t signControl=CheckSign(temp, i, j);\n    \n\t\t    auto it2 = totalBasis.find(state.GetId());\n\t\t    \n\t  \t    \n\t\t     \n\t\t     size_t newStateNr= Position(*it2);\n\t\t     //\t         std::cout<< \"old \"<< temp << \" at \"<< Position(tpState)<< std::endl;\n      \n\t\t     // std::cout<< \"new \"<< state <<\" at  \"<<newStateNr<<  std::endl;\n\t   \t              if(signControl%2==0)\n   \t   \t    \t {\n\t   \t\t   op.coeffRef(newStateNr, Position(tpState))-= ValType{var};}\n   \t   \t       else\n   \t   \t    \t { op.coeffRef(newStateNr, Position(tpState))+= ValType{var};}\n\t\t    }\n\n\n\n  }\n\n\n\n  // carefull with changes, making one for cdag and one for ccdag\n    template<typename T>\n    size_t CheckSign2(const T& state, size_t i, size_t j)\n  {\n    size_t m=0;\n    if(i>j)\n      {\n  \tfor(size_t l=j; l<i; l++)\n  \t  {\n  \t    m+=size_t(state[l]);\n  \t  }\n\n      }\n    else\n      \tfor(size_t l=i; l<j; l++)\n  \t  {\n  \t    m+=size_t(state[l]);\n  \t  }\n    return m;\n  }\n  \n  size_t NextWithBC(size_t i, size_t sites, bool PB=true, size_t steps=1)\n  {\n    if(PB)\n      {return (i+steps)%sites;}\n    else{return (i+steps);}\n  }\n  size_t Length( size_t sites, bool PB=true)\n  {\n    if(PB)\n      {return sites;}\n    else{return sites-1;}\n  }\n    template<class TotalBasis>\n  Mat CdagOperator(const TotalBasis& totalBasis, int i,   const bool& PB=true)\n{\n  \n   using BasisIt= typename TotalBasis::BasisIt;     \n\n\n\n using Lattice=typename TotalBasis::Lattice;   \n    size_t dim=totalBasis.dim;\n    \n    Mat op(dim, dim);\n       op.setZero();\n for( auto& tpState :totalBasis)\n\t     {\n\t  \t \n\t    \n\t       BasisIt it2=totalBasis.find(Id(tpState));\t     \n\n\t       Lattice state=GetLattice(*it2);\n\t       //\t       std::cout << \" stat \"<< totalBasis.totalmaxPar << \"\\n\";\n\t       //std::cout << \" i \"<< i<< \"  has \"<< state[i]<< std::endl;\n\t       \n\t       if(state[i]==0 )\n\t         \t {\n\t\t\t   \n\t\t\t   auto temp=state;\n\t         \t   state.setPartNr(i, 1);\n\t\t\t   size_t signControl=CheckSign2(temp, i, 0);\n\t\t\t   // std::cout << \"at i=\"<< i <<\" changed to  \"<< state << \"\\n\"<< \"with aign cont \"<< signControl<< '\\n';\n\t         \t   it2= totalBasis.find(state.GetId());\n\t        \t   \n\t     \t\t   size_t newStateNr= Position(*it2);\n\t      \t\t              if(signControl%2==0)\n   \t      \t    \t {\n\t      \t\t   op.coeffRef(newStateNr, Position(tpState))+= ValType{1};}\n   \t      \t       else\n   \t      \t    \t { op.coeffRef(newStateNr, Position(tpState))-= ValType{1};}\n\t      \t    }\n\t         \n   \t         \t     \n\t\t \n\t      }\n      return op;\n      \n       }\n  template<class TotalBasis>\n  Mat COperator(const TotalBasis& totalBasis, int i,   const bool& PB=true)\n{\n  \n   using BasisIt= typename TotalBasis::BasisIt;     \n\n\n\n using Lattice=typename TotalBasis::Lattice;   \n    size_t dim=totalBasis.dim;\n    \n    Mat op(dim, dim);\n       op.setZero();\n for( auto& tpState :totalBasis)\n\t     {\n\t  \t \n\t    \n\t        BasisIt it2=totalBasis.find(Id(tpState));\t     \n\n\t       Lattice state=GetLattice(*it2);\n\t       // std::cout << \" stat \"<< state << \"\\n\";\n\t       //std::cout << \" i \"<< i<< \"  has \"<< state[i]<< std::endl;\n\t       \n\t       if(state[i]==1)\n\t         \t {\n\t\t\t   \n\t\t\t   auto temp=state;\n\t         \t   state.setPartNr(i, 0);\n\t\t\t   size_t signControl=CheckSign2(temp, i, 0);\n\t\t\t   // std::cout << \"at i=\"<< i <<\" changed to  \"<< state << \"\\n\"<< \"with aign cont \"<< signControl<< '\\n';\n\t         \t   it2= totalBasis.find(state.GetId());\n\n\t     \t\t   size_t newStateNr= Position(*it2);\n\t      \t\t              if(signControl%2==0)\n   \t      \t    \t {\n\t      \t\t   op.coeffRef(newStateNr, Position(tpState))+= ValType{1};}\n   \t      \t       else\n   \t      \t    \t { op.coeffRef(newStateNr, Position(tpState))-= ValType{1};}\n\t      \t    }\n\t         \n   \t         \t     \n\t\t \n\t      }\n      return op;\n      \n       }\n  template<class TotalBasis>\n  Mat NumberOperatorE(const TotalBasis& totalBasis, const double omega=1., bool PB=0, int start=0, int stop=0)\n {\n   \n \n    size_t dim=totalBasis.dim;\n    size_t sites=totalBasis.sites;\n    Mat op(dim, dim);\n      op.setZero();\n stop = (stop!=0) ? stop : sites;    \n\n\n      for(const auto& tpState : totalBasis)\n\t{\n\n\t \n\t  for(size_t i=start; i<stop; i++)\n\t    {\n\t      \n\t      \n  op.coeffRef(Position(tpState), Position(tpState))+=ValType(omega*totalBasis.particlesAt(Id(tpState), i));\n       \n\t   \n\t  }\n\t}\n      return op;\n      \n       }\n  template<class TotalBasis, class Functor>\n  Mat EKinLongRangeOperator(const TotalBasis& totalBasis,Functor f, int lmx=1, double var=1. , bool PB=0 )\n     {\n\nusing Lattice=typename TotalBasis::Lattice;     \n\n \n   size_t dim=totalBasis.dim;\n    size_t sites=totalBasis.sites;\n    Mat op(dim, dim);\n      op.setZero();\n    int  stop = Operators::Length( sites, PB);       \n\n   for( auto& tpState : totalBasis)\n\t     {\n\t       \t    for(int i=0; i<stop; i++)\n                 {                     \n\t\t   for(int j=1; j<=lmx; j++)\n                 {\nLattice state_1=GetLattice(tpState);\n\t\t   Lattice state_2=GetLattice(tpState);\n\t\t   int j_1=(i+j)%sites;\n\n\n\t   \t    \t\t    if(state_1[i]==state_1[j_1])\n   \t       \t     {\n\t  // \t     \n    \t\t  \n   \t   \t     }\n   \t   \t    else{\n\n\t\t      Lattice temp=state_1;\n\t\t      state_1.switchPartNr(i, temp[j_1], j_1, temp[i]);\n\n  size_t signControl=CheckSign(temp, i, j_1);\n\n\n\t\t    auto it2_1 = totalBasis.find(state_1.GetId());\n\t     \t\t   size_t newStateNr_1= Position(*it2_1);\n\t\t\n\t\t\t   \t\t\n\t   \t               if(signControl%2==0)\n   \t   \t    \t  {\n\t\t\t    op.coeffRef(newStateNr_1, Position(tpState))-= ValType{var}*f(i,j_1);}\n\n\t\t   \t       \t   \t       else\n\t\t   \t    {\n\t\t\t      op.coeffRef(newStateNr_1, Position(tpState))+= ValType{var}*f(i,j_1);\n}\n\t\t   \n\n\t   \t     \n\t\t    }    \t\t  \n\n\n\t\t }\t   \n\n   \t  }\n\t     }    \n  return op;\n  }\n  template<class TotalBasis>\n  Mat EKinOperator(const TotalBasis& totalBasis, double var=1. , bool PB=0, int start=0, int stop=0 )\n     {\n\nusing Lattice=typename TotalBasis::Lattice;     \n\n \n   size_t dim=totalBasis.dim;\n    size_t sites=totalBasis.sites;\n    Mat op(dim, dim);\n      op.setZero();\n      stop = (stop!=0) ? stop : Operators::Length( sites, PB);       \n\n   for( auto& tpState : totalBasis)\n\t     {\n\n\t       \t    for(size_t i=start; i<stop; i++)\n                 {\n\n\t       \n\n\t\t   Lattice state=GetLattice(tpState);\n                     size_t j=Operators::NextWithBC(i, sites, PB);\n\t   \t    \t\t    if(state[i]==state[j])\n   \t       \t     {\n\t  // \t     \n    \t\t  \n   \t   \t     }\n   \t   \t    else{\n\n\t\t      \n\n\t\t      Lattice temp=state;\n\t\t      \n\t\t       state.setPartNr(j, temp[i]);\n\t\t      state.setPartNr(i, temp[j]);\n\t\t     \t\t \n\t  \t     size_t signControl=CheckSign(temp, i, j);\n\t\t       \n\t\t    auto it2 = totalBasis.find(state.GetId());\n\t\t     \n\t  \t      \n\t\t     \n\t\t     size_t newStateNr= Position(*it2);\n\t\t     \n\t   \t              if(signControl%2==0)\n   \t   \t    \t {\n\t   \t\t   op.coeffRef(newStateNr, Position(tpState))-= ValType{var};}\n   \t   \t       else\n   \t   \t    \t { op.coeffRef(newStateNr, Position(tpState))+= ValType{var};}\n\t\t    }\n\n\t   \t     }\n\t   \n\n   \t  }\n    \n  return op;\n  }\n\n\nMat EKinOperator(const Many_Body::OneElectronBasis& totalBasis, double var=1. , bool PB=0, int start=0, int stop=0 )\n     {\n\n       using Lattice=typename Many_Body::OneElectronBasis::Lattice;     \n\n \n   size_t dim=totalBasis.dim;\n    size_t sites=totalBasis.sites;\n    Mat op(dim, dim);\n      op.setZero();\n      stop = (stop!=0) ? stop : Operators::Length( sites, PB);       \n\n   for( auto& tpState : totalBasis)\n   \t     {\n\n   \t       \t    for(size_t i=start; i<stop; i++)\n                 {\n\n\t       \n\n   \t\t   Lattice state=GetLattice(tpState);\n                     size_t j=Operators::NextWithBC(i, sites, PB);\n   \t   \t    \t\t    if(state[i]==state[j])\n   \t       \t     {\n   \t  // \t     \n    \t\t  \n   \t   \t     }\n   \t   \t    else{\n\n\t\t      \n\n   \t\t    Act(i, j, totalBasis, tpState, state, op, var);\n   \t\t    }\n\n   \t   \t     }\n\t   \n\n   \t  }\n    \n  return op;\n  }\n\n\n   template<class TotalBasis>\n  Mat CurrOperator(const TotalBasis& totalBasis, double var=1. , bool PB=0, int start=0, int stop=0)\n     {\n\nusing Lattice=typename TotalBasis::Lattice;     \n\n \n   size_t dim=totalBasis.dim;\n    size_t sites=totalBasis.sites;\n    Mat op(dim, dim);\n      op.setZero();\n      stop = (stop!=0) ? stop : Operators::Length( sites, PB);       \n\n   for( auto& tpState : totalBasis)\n\t     {\n\n\t       \t    for(size_t i=start; i<stop; i++)\n                 {\n\n\t       \n\n\t\t   Lattice state=GetLattice(tpState);\n                     size_t j=Operators::NextWithBC(i, sites, PB);\n\t   \t    \t\t    if(state[i]==state[j])\n   \t       \t     {\n\t  // \t     \n    \t\t  \n   \t   \t     }\n   \t   \t    else{\n\t\t      \n\n\t\t      Lattice temp=state;\n\t\t      \n\t\t       state.setPartNr(j, temp[i]);\n\t\t      state.setPartNr(i, temp[j]);\n\t\t     \t\t \n\t  \t     size_t signControl=CheckSign(temp, i, j);\n\t\t       \n\t\t    auto it2 = totalBasis.find(state.GetId());\n\t\t     \n\t\t    double otherSign=(state[j]==1)?+1:-1;\n\n\t\t      \n\t\t      \n\t\t     \n\t\t     size_t newStateNr= Position(*it2);\n\t\t     \n\t   \t              if(signControl%2==0)\n   \t   \t    \t {\n\t   \t\t   op.coeffRef(newStateNr, Position(tpState))-= otherSign*ValType{var};}\n   \t   \t       else\n   \t   \t    \t { op.coeffRef(newStateNr, Position(tpState))+= otherSign*ValType{var};}\n\t\t    }\n\n\t   \t     }\n\t   \n\n   \t  }\n    \n  return op;\n  }\n\n\n\n\n    \n  Mat CurrOperator(const  Many_Body::OneElectronBasis& totalBasis, double var=1. , bool PB=0, int start=0, int stop=0)\n     {\n\nusing Lattice=typename  Many_Body::OneElectronBasis::Lattice;     \n\n \n   size_t dim=totalBasis.dim;\n    size_t sites=totalBasis.sites;\n    Mat op(dim, dim);\n      op.setZero();\n      stop = (stop!=0) ? stop : Operators::Length( sites, PB);       \n\n   for( auto& tpState : totalBasis)\n\t     {\n\n\t       \t    for(size_t i=start; i<stop; i++)\n                 {\n\n\t       \n\n\t\t   Lattice state=GetLattice(tpState);\n                     size_t j=Operators::NextWithBC(i, sites, PB);\n\t   \t    \t\t    if(state[i]==state[j])\n   \t       \t     {\n\t  // \t     \n    \t\t  \n   \t   \t     }\n   \t   \t    else{\n\t\t      \n\n\t\t   Lattice temp=state;\n\n\t\t          state.flip(i);\n      \n\t\t\t  state.flip(j);\n\t  \t     size_t signControl=CheckSign(temp, i, j);\n\t\t       \n\t\t    auto it2 = totalBasis.find(state.GetId());\n\t\t     \n\t\t    double otherSign=(temp[j]==1)?+1:-1;\n\n\t\t      \n\t\t      \n\t\t     \n\t\t     size_t newStateNr= Position(*it2);\n\t\t     \n\t   \t              if(signControl%2==0)\n   \t   \t    \t {\n\t   \t\t   op.coeffRef(newStateNr, Position(tpState))-= otherSign*ValType{var};}\n   \t   \t       else\n   \t   \t    \t { op.coeffRef(newStateNr, Position(tpState))+= otherSign*ValType{var};}\n\t\t    }\n\n\t   \t     }\n\t   \n\n   \t  }\n    \n  return op;\n\n  }\n\n    template<class TotalBasis>\n    Mat totalHetOperator(const TotalBasis& totalBasis, double tint, double t0, double tl, double V, int Llead1,  int Llead2,  int Lchain )\n     {\n       bool PB=0;\n\nusing Lattice=typename TotalBasis::Lattice;     \n\n \n   size_t dim=totalBasis.dim;\n    size_t sites=totalBasis.sites;\n    Mat op(dim, dim);\n      op.setZero();\n int L_x=Llead1+(Lchain+1)/2;\n double E=0;\n if(Lchain>1)\n   {\n\n   E=V/(Lchain+1);\n\n   }\n std::cout<< \"L x \"<<L_x<< \" E \"<<E<<std::endl;  \n   for( auto& tpState : totalBasis)\n\t     {\nconst Lattice state=GetLattice(tpState);\n\t       \t    for(size_t i=0; i<Llead1-1; i++)\n                 {\n\t\n\t\t   if(state[i]==1)\n\t\t     {\n\n\t       op.coeffRef(Position(tpState), Position(tpState))-= ValType{V/2};\n\n\n\t\t     }\n\t\t   size_t j=Operators::NextWithBC(i, sites, PB);\n\t\t   //\t   std::cout<< \"i,j \"<< i << \", \"<< j << std::endl;\n\t\t     // first lead\n\n\n\n\t\t      Act(i, j, totalBasis, tpState, state, op, tl);\n\n\n\t\t }\n\t\t     for(size_t i=Llead1+Lchain; i<Llead1+Lchain+Llead2-1; i++)\n                 {\n\t\t   if(state[i]==1)\n\t\t     {\n\t\t       // std::cout<<\" i \"<<i+1<< \" V \"<< V <<std::endl;\n\n\n\t\t       op.coeffRef(Position(tpState), Position(tpState))+= ValType{V/2};\n\n\n\t\t     }\n\t\t   \t\t  \n\t\t\t\t   size_t j=Operators::NextWithBC(i, sites, PB);\n\t\t     // second lead\n\n\t\t     Act(i, j, totalBasis, tpState, state, op, tl);\n\n\t   \t     }\n\t\t    \t   if(state[Llead1+Llead2+Lchain-1]==1)\n\t\t     {\n\n\n\t\t       op.coeffRef(Position(tpState), Position(tpState))+= ValType{V/2};\n\n\n\t\t     }\n\t\t\t   if(state[Llead1-1]==1)\n\t\t     {\n\t\t       \n\n\n\t\t       op.coeffRef(Position(tpState), Position(tpState))-= ValType{V/2};\n\n\n\t\t     }\n\t\t    // chain\n\t\t    \t       \t    for(size_t i=Llead1; i<Llead1+Lchain-1; i++)\n                 {\n\t\t   Lattice state=GetLattice(tpState);\n\t\t  \n                     size_t j=Operators::NextWithBC(i, sites, PB);\n\t\t     // first lead\n\t\t     Act(i, j, totalBasis, tpState, state, op, t0);\n\t\t     \t   if(state[i]==1)\n\t\t     {\n\n\t\t       \t\t         op.coeffRef(Position(tpState), Position(tpState))+= (static_cast<double>((i+1))-L_x)*E;\n\n\n\t\t     }\n\t   \t     }\n\t\t\t\t      \t   if(state[Llead1+Lchain-1]==1)\n\t\t     {\n\n\t\t       \t       op.coeffRef(Position(tpState), Position(tpState))+=(static_cast<double>(Llead1+Lchain)-L_x)*E;\n\t     }\n\t\t\t\t    Act(Llead1-1, Llead1, totalBasis, tpState, state, op, tint);\n\t\t\t\t    Act(Llead1+Lchain-1, Llead1+Lchain, totalBasis, tpState, state, op, tint);\t  }\n    \n  return op;\n  }\ntemplate<class TotalBasis>\nMat totCurrOperator(const TotalBasis& totalBasis, double var ,  int Llead1, int Llead2, int Lchain)\n     {\n\n       using Lattice=typename TotalBasis::Lattice;     \n\n \n   size_t dim=totalBasis.dim;\n   size_t sites=totalBasis.sites;\n    Mat op(dim, dim);\n      op.setZero();\n   for( auto& tpState : totalBasis)\n\t     {\n\n\n\t       int i=Llead1-1;\n\n\t       int j=i+1;\n\t       \n\n\t\t   Lattice state=GetLattice(tpState);\n          \n\t   \t    \t\t    if(state[i]==state[j])\n   \t       \t     {\n\n    \t\t  \n   \t   \t     }\n   \t   \t    else{\n\t\t      \n\n\t\t      Lattice temp=state;\n\n\t\t          state.flip(i);\n      \n\t\t\t  state.flip(j);\n\t  \t     size_t signControl=CheckSign(temp, i, j);\n\t\t       \n\t\t    auto it2 = totalBasis.find(state.GetId());\n\t\t     \n\t\t    double otherSign=(temp[j]==1)?+1:-1;\n\n\t\t      \n\t\t      \n\t\t     \n\t\t     size_t newStateNr= Position(*it2);\n\t\t     \n\t   \t              if(signControl%2==0)\n   \t   \t    \t {\n\t   \t\t   op.coeffRef(newStateNr, Position(tpState))-= otherSign*ValType{var};}\n   \t   \t       else\n   \t   \t    \t { op.coeffRef(newStateNr, Position(tpState))+= otherSign*ValType{var};}\n\t\t    }\n\t\t\t\t    state=GetLattice(tpState);\n\n\t i=Lchain+Llead1-1;\n\n    j=i+1;\n\n\t\tif(state[i]==state[j])\n   \t       \t     {\n\t  // \t     \n    \t\t  \n   \t   \t     }\n   \t   \t    else{\n\t\t      \n\n\t\t      Lattice temp=state;\n\t\t    state.flip(i);\n       //setPartNr(j, temp[i]);\n      state.flip(j);\n\t\t     \t\t \n\t  \t     size_t signControl=CheckSign(temp, i, j);\n\t\t       \n\t\t    auto it2 = totalBasis.find(state.GetId());\n\t\t     \n\t\t    double otherSign=(temp[j]==1)?+1:-1;\n\n\t\t      \n\t\t      \n\t\t     \n\t\t     size_t newStateNr= Position(*it2);\n\t\t     \n\t   \t              if(signControl%2==0)\n   \t   \t    \t {\n\t   \t\t   op.coeffRef(newStateNr, Position(tpState))-= otherSign*ValType{var};}\n   \t   \t       else\n   \t   \t    \t { op.coeffRef(newStateNr, Position(tpState))+= otherSign*ValType{var};}\n\t\t    }\n\n\t   \t     \n\t   \n\n   \t  }\n\n   op*=0.5;   \n\n  return op;\n  }\n}\n", "meta": {"hexsha": "a23d3f62e28d1de8f19c1e50a4efafaa1509f7f6", "size": 16239, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/operators.hpp", "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": "include/operators.hpp", "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": "include/operators.hpp", "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": 22.2147742818, "max_line_length": 138, "alphanum_fraction": 0.5008929121, "num_tokens": 4669, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.47303467778593833}}
{"text": "/**\n * \\ file fmath.cpp\n */\n\n#include <cmath>\n\n#include <ATK/Utility/fmath.h>\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_NO_MAIN\n#include <boost/test/unit_test.hpp>\n\nBOOST_AUTO_TEST_CASE(fmath_exp_float_test)\n{\n  for (int i = 0; i < 10; ++i)\n  {\n    BOOST_REQUIRE_CLOSE(std::exp(float(i)), fmath::exp(float(i)), 0.0001);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(fmath_exp_double_test)\n{\n  for (int i = 0; i < 100; ++i)\n  {\n    BOOST_REQUIRE_CLOSE(std::exp(double(i)), fmath::exp(double(i)), 0.0001);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(fmath_log_float_test)\n{\n  for (int i = 1; i < 100; ++i)\n  {\n    BOOST_REQUIRE_CLOSE(std::log(float(i)), fmath::log(float(i)), 0.0001);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(fmath_log_double_test)\n{\n  for (int i = 1; i < 100; ++i)\n  {\n    BOOST_REQUIRE_CLOSE(std::log(double(i)), fmath::log(double(i)), 0.0001);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(fmath_log10_float_test)\n{\n  for (int i = 1; i < 100; ++i)\n  {\n    BOOST_REQUIRE_CLOSE(std::log10(float(i)), fmath::log10(float(i)), 0.0001);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(fmath_log10_double_test)\n{\n  for (int i = 1; i < 100; ++i)\n  {\n    BOOST_REQUIRE_CLOSE(std::log10(double(i)), fmath::log10(double(i)), 0.0001);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(fmath_pow_float_test)\n{\n  for (int i = 1; i < 10; ++i)\n  {\n    BOOST_REQUIRE_CLOSE(std::pow(10, float(i)), fmath::pow(10, float(i)), 0.001);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(fmath_pow_double_test)\n{\n  for (int i = 1; i < 100; ++i)\n  {\n    BOOST_REQUIRE_CLOSE(std::pow(10, double(i)), fmath::pow(10, double(i)), 0.0001);\n  }\n}", "meta": {"hexsha": "fade3e62a714ce82d5e82eb5d205e61857859725", "size": 1510, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/Utility/fmath.cpp", "max_stars_repo_name": "D-J-Roberts/AudioTK", "max_stars_repo_head_hexsha": "accf009d7238f32702eb1d5ee23c5148fc68e3bd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 249.0, "max_stars_repo_stars_event_min_datetime": "2015-01-05T13:36:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T18:47:46.000Z", "max_issues_repo_path": "tests/Utility/fmath.cpp", "max_issues_repo_name": "D-J-Roberts/AudioTK", "max_issues_repo_head_hexsha": "accf009d7238f32702eb1d5ee23c5148fc68e3bd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 22.0, "max_issues_repo_issues_event_min_datetime": "2015-07-28T15:20:24.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-11T14:18:19.000Z", "max_forks_repo_path": "tests/Utility/fmath.cpp", "max_forks_repo_name": "D-J-Roberts/AudioTK", "max_forks_repo_head_hexsha": "accf009d7238f32702eb1d5ee23c5148fc68e3bd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 48.0, "max_forks_repo_forks_event_min_datetime": "2015-08-15T12:08:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-07T02:33:07.000Z", "avg_line_length": 20.1333333333, "max_line_length": 84, "alphanum_fraction": 0.6470198675, "num_tokens": 509, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4730346777859383}}
{"text": "/**\n * File: testing.cpp\n * Date: Apr 16 2021\n * Author: Open Risk  (www.openriskmanagement.com)\n *\n */\n\n#include \"stats.hpp\"\n#include <armadillo>\n#include \"random_var.h\"\n\n\nint main(int argc, char *argv[]) {\n\n\n    int SampleSize = 100;\n    int DataType = 1;\n    RandomVar myR(SampleSize, DataType);\n\n    cout << \"Testing\" << endl;\n    for (int i = 0; i < myR.size(); i++) {\n        double rval = stats::rt(30);\n        myR.setS(i, rval);\n    }\n\n    myR.Print();\n\n}\n", "meta": {"hexsha": "4eaa6611171ac4f122df9d213ac7404493dbcbe3", "size": 465, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "testing.cpp", "max_stars_repo_name": "open-risk/tailRisk", "max_stars_repo_head_hexsha": "209113f48b9d3ac0a98537b1b3eeea97e20bae17", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-26T07:25:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-26T07:25:15.000Z", "max_issues_repo_path": "testing.cpp", "max_issues_repo_name": "open-risk/tailRisk", "max_issues_repo_head_hexsha": "209113f48b9d3ac0a98537b1b3eeea97e20bae17", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "testing.cpp", "max_forks_repo_name": "open-risk/tailRisk", "max_forks_repo_head_hexsha": "209113f48b9d3ac0a98537b1b3eeea97e20bae17", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-05T11:47:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-05T11:47:13.000Z", "avg_line_length": 16.0344827586, "max_line_length": 50, "alphanum_fraction": 0.5698924731, "num_tokens": 139, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7931059414036511, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.47303467195254734}}
{"text": "#include <boost/geometry/formulas/thomas_inverse.hpp>\n", "meta": {"hexsha": "765928c98b462e252e72220293d6e1eb924600d4", "size": 54, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_geometry_formulas_thomas_inverse.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_geometry_formulas_thomas_inverse.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_geometry_formulas_thomas_inverse.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 27.0, "max_line_length": 53, "alphanum_fraction": 0.8333333333, "num_tokens": 12, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105941403651, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.47303467195254717}}
{"text": "/*\n    BSD 3-Clause License\n\n    Copyright (c) 2018, Roboy\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    author: Simon Trendel ( simon.trendel@tum.de ), 2018\n    description: helper class for handling triangulation from lighthouse angles\n*/\n\n#pragma once\n\n// Eigen\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include \"darkroom/Sensor.hpp\"\n\nstruct LighthouseCalibration{\n    double phase = 0;\n    double curve = 0;\n    double tilt = 0;\n    double gibmag = 0;\n    double gibphase = 0;\n    void reset(){ phase = 0; curve = 0; tilt = 0; gibmag = 0; gibphase = 0; }\n};\n\n// offset from center of laser rotation\n#define AXIS_OFFSET 0.015\n\nusing namespace Eigen;\n\nclass Triangulation{\npublic:\n    /**\n   * get the 3D minimum distance between 2 lines\n   * following http://geomalgorithms.com/a07-_distance.html#Distance-between-Lines\n   * @param pos0 origin line0\n   * @param dir1 direction line0\n   * @param pos1 origin line1\n   * @param dir2 direction line1\n   * @param tri0 point on line0 closest to line1\n   * @param tri1 point on line1 closest to line0\n   * @return distance between the lines\n   */\n    double dist3D_Line_to_Line( Vector3d &pos0, Vector3d &dir1,\n                                Vector3d &pos1, Vector3d &dir2,\n                                Vector3d &tri0, Vector3d &tri1);\n\n/**\n    * This function triangulates the position of a sensor using the horizontal and vertical angles from two ligthouses\n    * @param angles0 vertical/horizontal angles form first lighthouse\n    * @param angles1 vertical/horizontal angles form second lighthouse\n    * @param RT_0 pose matrix of first lighthouse\n    * @param RT_1 pose matrix of second lighthouses\n    * @param triangulated_position the triangulated position\n    * @param ray0 ligthhouse ray\n    * @param ray1 ligthhouse ray\n    */\n    double triangulateFromLighthouseAngles(Vector2d &angles0, Vector2d &angles1, Matrix4d &RT_0, Matrix4d &RT_1,\n                                           Vector3d &triangulated_position, Vector3d &ray0, Vector3d &ray1);\n\n    double triangulateFromRays(Vector3d &ray0, Vector3d &ray1, Matrix4d &RT_0, Matrix4d &RT_1, Vector3d &triangulated_position);\n\n    void rayFromLighthouseAngles(Vector2d &angles, Vector3d &ray, int lighthouse);\n    void rayFromLighthouseAngles(double elevation, double azimuth, Vector3d &ray, int lighthouse);\n\n    // for each motor and each lighthouse\n    LighthouseCalibration calibration[2][2];\n};", "meta": {"hexsha": "8b7fb93a887ac284708960b77972a5ae07dda52a", "size": 3962, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "darkroom/include/darkroom/Triangulation.hpp", "max_stars_repo_name": "Roboy/roboy_darkroom", "max_stars_repo_head_hexsha": "ed9572dc92f27c8b40265a1d3369bf270e1fbc30", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2018-03-10T04:32:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-10T10:55:44.000Z", "max_issues_repo_path": "darkroom/include/darkroom/Triangulation.hpp", "max_issues_repo_name": "Roboy/roboy_darkroom", "max_issues_repo_head_hexsha": "ed9572dc92f27c8b40265a1d3369bf270e1fbc30", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "darkroom/include/darkroom/Triangulation.hpp", "max_forks_repo_name": "Roboy/roboy_darkroom", "max_forks_repo_head_hexsha": "ed9572dc92f27c8b40265a1d3369bf270e1fbc30", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-05-04T09:51:01.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-04T09:51:01.000Z", "avg_line_length": 42.1489361702, "max_line_length": 128, "alphanum_fraction": 0.7155477032, "num_tokens": 937, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105941403651, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.47303467195254717}}
{"text": "#include <algorithm>\n\n#include <boost/math/special_functions/fpclassify.hpp>\n\n#include \"StakeStats.h\"\n#include \"bignum.h\"\n#include \"types.h\"\n\nStakeStats::StakeStats(void)\n{\n    m_ProbabilitiesNotToMint = 1;\n}\n\nvoid StakeStats::PushChancesToMint(CBigNum bnChancesToMint)\n{\n    CBigNum bnMaxValue = CBigNum(~uint256(0));\n\n    if (bnChancesToMint > bnMaxValue)\n        bnChancesToMint = bnMaxValue;\n\n    uint64_t precision = 1000000000000000000;\n\n    CBigNum bnExtendedChancesToMint = bnChancesToMint * precision;\n    CBigNum bnExtendedProbabilitiesToMint = bnExtendedChancesToMint / bnMaxValue;\n\n    double probabilitiesToMint = static_cast<double>(bnExtendedProbabilitiesToMint.getuint64()) / precision;\n    double probabilitiesNotToMint = 1 - probabilitiesToMint;\n\n    m_ProbabilitiesNotToMint *= probabilitiesNotToMint;\n\n    /* Just add a '/' before the '/*' to uncomment this whole block\n    //\n    printf(\"---\\n\");\n    printf(\"bnChancesToMint               : %-100s\\n\", bnChancesToMint.ToString().c_str());\n    printf(\"bnMaxValue                    : %-100s\\n\", bnMaxValue.ToString().c_str());\n    printf(\"bnExtendedChancesToMint       : %-100s\\n\", bnExtendedChancesToMint.ToString().c_str());\n    printf(\"bnExtendedProbabilitiesToMint : %-100s\\n\", bnExtendedProbabilitiesToMint.ToString().c_str());\n    printf(\"extendedProbabilitiesToMint   : %.17g\\n\", static_cast<double>(bnExtendedProbabilitiesToMint.getuint64()));\n    printf(\"probabilitiesToMint           : %.17g\\n\", probabilitiesToMint);\n    printf(\"probabilitiesNotToMint        : %.17g\\n\", probabilitiesNotToMint);\n    printf(\"---\\n\");\n    //*/\n}\n\ntimestamp_t StakeStats::GetEstimatedStakeTime(double expectedChancesToMint)\n{\n    double expectedChancesNotToMint = std::max(0., 1. - expectedChancesToMint);\n    double expectedEventCount = log(expectedChancesNotToMint) / log(m_ProbabilitiesNotToMint);\n\n    if (boost::math::isinf(expectedEventCount))\n        return -1;\n\n    return static_cast<timestamp_t>(expectedEventCount);\n}\n", "meta": {"hexsha": "69a674e7bd06511f744df75145277fef005ab059", "size": 1991, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/StakeStats.cpp", "max_stars_repo_name": "redfish64/nomiccoin", "max_stars_repo_head_hexsha": "e2df2a829b3e0f5f7bab82297d529d04644a1f8e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-05-22T17:39:27.000Z", "max_stars_repo_stars_event_max_datetime": "2017-11-25T23:13:57.000Z", "max_issues_repo_path": "src/StakeStats.cpp", "max_issues_repo_name": "redfish64/nomiccoin", "max_issues_repo_head_hexsha": "e2df2a829b3e0f5f7bab82297d529d04644a1f8e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-12-23T00:38:18.000Z", "max_issues_repo_issues_event_max_datetime": "2015-12-23T02:47:08.000Z", "max_forks_repo_path": "src/StakeStats.cpp", "max_forks_repo_name": "redfish64/nomiccoin", "max_forks_repo_head_hexsha": "e2df2a829b3e0f5f7bab82297d529d04644a1f8e", "max_forks_repo_licenses": ["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.2, "max_line_length": 118, "alphanum_fraction": 0.7172275239, "num_tokens": 555, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795403, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.472980324341005}}
{"text": "#include \"drake/solvers/fbstab/components/dense_linear_solver.h\"\n\n#include <cmath>\n\n#include <Eigen/Dense>\n\n#include \"drake/solvers/fbstab/components/dense_data.h\"\n#include \"drake/solvers/fbstab/components/dense_residual.h\"\n#include \"drake/solvers/fbstab/components/dense_variable.h\"\n\nnamespace drake {\nnamespace solvers {\nnamespace fbstab {\nnamespace {\n// Solves the system A*A' x = b in place\n// where A is lower triangular and invertible.\nvoid CholeskySolve(const Eigen::MatrixXd& A, Eigen::VectorXd* b) {\n  A.triangularView<Eigen::Lower>().solveInPlace(*b);\n  A.triangularView<Eigen::Lower>().transpose().solveInPlace(*b);\n}\n}  //  namespace\n\nDenseLinearSolver::DenseLinearSolver(int nz, int nv) {\n  if (nz <= 0 || nv <= 0) {\n    throw std::runtime_error(\n        \"In DenseLinearSolver::DenseLinearSolver: inputs must be positive.\");\n  }\n  nz_ = nz;\n  nv_ = nv;\n\n  K_.resize(nz_, nz_);\n  r1_.resize(nz_);\n  r2_.resize(nv_);\n  Gamma_.resize(nv_);\n  mus_.resize(nv_);\n  gamma_.resize(nv_);\n  B_.resize(nv_, nz_);\n}\n\nvoid DenseLinearSolver::SetAlpha(double alpha) { alpha_ = alpha; }\n\nbool DenseLinearSolver::Initialize(const DenseVariable& x,\n                                   const DenseVariable& xbar, double sigma) {\n  const DenseData* const data = x.data();\n  if (xbar.data() != data) {\n    throw std::runtime_error(\n        \"In DenseLinearSolver::Factor: x and xbar have mismatched problem \"\n        \"data.\");\n  }\n  if (xbar.nz_ != x.nz_ || xbar.nv_ != x.nv_) {\n    throw std::runtime_error(\n        \"In DenseLinearSolver::Factor: inputs must be the same size\");\n  }\n  if (xbar.nz_ != nz_ || xbar.nv_ != nv_) {\n    throw std::runtime_error(\n        \"In DenseLinearSolver::Factor: inputs must match object size.\");\n  }\n  if (sigma <= 0) {\n    throw std::runtime_error(\n        \"In DenseLinearSolver::Factor: sigma must be positive.\");\n  }\n  const Eigen::MatrixXd& H = data->H();\n  const Eigen::MatrixXd& A = data->A();\n\n  K_ = H + sigma * Eigen::MatrixXd::Identity(nz_, nz_);\n\n  // K <- K + A'*diag(Gamma(x))*A\n  Eigen::Vector2d pfb_gradient;\n  for (int i = 0; i < nv_; i++) {\n    const double ys = x.y()(i) + sigma * (x.v()(i) - xbar.v()(i));\n    pfb_gradient = PFBGradient(ys, x.v()(i));\n    gamma_(i) = pfb_gradient(0);\n    mus_(i) = pfb_gradient(1) + sigma * pfb_gradient(0);\n    Gamma_(i) = gamma_(i) / mus_(i);\n  }\n  // B is used to avoid temporaries\n  B_.noalias() = Gamma_.asDiagonal() * A;\n  K_.noalias() += A.transpose() * B_;\n\n  // Factor K = LL' in place\n  Eigen::LLT<Eigen::Ref<Eigen::MatrixXd> > L(K_);\n\n  Eigen::ComputationInfo status = L.info();\n  if (status != Eigen::Success) {\n    return false;\n  } else {\n    return true;\n  }\n}\n\nbool DenseLinearSolver::Solve(const DenseResidual& r, DenseVariable* x) const {\n  if (x == nullptr) {\n    throw std::runtime_error(\"In DenseLinearSolver::Solve: x cannot be null.\");\n  }\n  if (r.nz_ != x->nz_ || r.nv_ != x->nv_) {\n    throw std::runtime_error(\n        \"In DenseLinearSolver::Solve residual and variable objects must be the \"\n        \"same size\");\n  }\n  if (x->nz_ != nz_ || x->nv_ != nv_) {\n    throw std::runtime_error(\n        \"In DenseLinearSolver::Factor: inputs must match object size.\");\n  }\n  const DenseData* const data = x->data();\n  const Eigen::MatrixXd& A = data->A();\n  const Eigen::VectorXd& b = data->b();\n\n  // This method solves the system:\n  // KK'z = rz - A'*diag(1/mus)*rv\n  // diag(mus) v = rv + diag(gamma)*A*z\n  // Where K has been precomputed by the factor routine.\n  // See (28) and (29) in https://arxiv.org/pdf/1901.04046.pdf\n\n  // Compute rz - A'*(rv./mus) and store it in r1_.\n  r2_ = r.v_.cwiseQuotient(mus_);\n  r1_.noalias() = r.z_ - A.transpose() * r2_;\n\n  // Solve KK'*z = rz - A'*(rv./mus)\n  // where K = chol(H + sigma*I + A'*Gamma*A)\n  // is assumed to have been computed during the factor phase.\n  x->z() = r1_;\n  CholeskySolve(K_, x->z_);\n\n  // Compute v = diag(1/mus) * (rv + diag(gamma)*A*z)\n  // written so as to avoid temporary creation\n  r2_.noalias() = A * x->z();\n  r2_.noalias() = gamma_.asDiagonal() * r2_;\n  r2_.noalias() += r.v_;\n\n  // v = r2./mus\n  x->v() = r2_.cwiseQuotient(mus_);\n\n  // y = b - Az\n  x->y() = b - A * x->z();\n\n  return true;\n}\n\nEigen::Vector2d DenseLinearSolver::PFBGradient(double a, double b) const {\n  const double r = sqrt(a * a + b * b);\n  const double d = 1.0 / sqrt(2.0);\n\n  Eigen::Vector2d v;\n  if (r < zero_tolerance_) {\n    v(0) = alpha_ * (1.0 - d);\n    v(1) = alpha_ * (1.0 - d);\n\n  } else if ((a > 0) && (b > 0)) {\n    v(0) = alpha_ * (1.0 - a / r) + (1.0 - alpha_) * b;\n    v(1) = alpha_ * (1.0 - b / r) + (1.0 - alpha_) * a;\n\n  } else {\n    v(0) = alpha_ * (1.0 - a / r);\n    v(1) = alpha_ * (1.0 - b / r);\n  }\n\n  return v;\n}\n\n}  // namespace fbstab\n}  // namespace solvers\n}  // namespace drake\n", "meta": {"hexsha": "16a71d3fc2346b633f90e6f9581a749e68da5289", "size": 4751, "ext": "cc", "lang": "C++", "max_stars_repo_path": "solvers/fbstab/components/dense_linear_solver.cc", "max_stars_repo_name": "RobotLocomotion/drake-python3.7", "max_stars_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-02-25T02:01:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-17T04:52:04.000Z", "max_issues_repo_path": "solvers/fbstab/components/dense_linear_solver.cc", "max_issues_repo_name": "RobotLocomotion/drake-python3.7", "max_issues_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "solvers/fbstab/components/dense_linear_solver.cc", "max_forks_repo_name": "RobotLocomotion/drake-python3.7", "max_forks_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-13T12:05:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-13T12:05:39.000Z", "avg_line_length": 29.1472392638, "max_line_length": 80, "alphanum_fraction": 0.6080825089, "num_tokens": 1550, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795403, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.472980324341005}}
{"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/video/tracking.hpp>\n#include <opencv2/opencv.hpp>\n\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\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\nusing namespace std;\nusing namespace cv;\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\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\n\nint main ( int argc, char** argv )\n{\n    if ( argc != 5 )\n    {\n        cout<<\" usage: pose_estimation_3d2d img1 img2 depth1 depth2\"<<endl;\n        return 1;\n    }\n    //-- \u8bfb\u53d6\u56fe\u50cf\n    Mat img_1 = imread ( argv[1], CV_LOAD_IMAGE_COLOR );\n    Mat img_2 = imread ( argv[2], CV_LOAD_IMAGE_COLOR );\n\n    vector<KeyPoint> keypoints_1, keypoints_2;\n    vector<DMatch> matches;\n    find_feature_matches ( img_1, img_2, keypoints_1, keypoints_2, matches );\n\n    cout<<\"\u4e00\u5171\u627e\u5230\u4e86\"<<matches.size() <<\"\u7ec4\u5339\u914d\u70b9\"<<endl;\n\n\n    // \u5efa\u7acb3D\u70b9\n    Mat d1 = imread ( argv[3], CV_LOAD_IMAGE_UNCHANGED );       // \u6df1\u5ea6\u56fe\u4e3a16\u4f4d\u65e0\u7b26\u53f7\u6570\uff0c\u5355\u901a\u9053\u56fe\u50cf\n    Mat K = ( Mat_<double> ( 3,3 ) << 520.9, 0, 325.1, 0, 521.0, 249.7, 0, 0, 1 );\n    vector<Point3f> pts_3d;\n    vector<Point2f> pts_2d;\n    for ( DMatch m:matches )\n    {\n        //\u8ba1\u7b973D\u5750\u6807\n        ushort d = d1.ptr<unsigned short> (int ( keypoints_1[m.queryIdx].pt.y )) [ int ( keypoints_1[m.queryIdx].pt.x ) ];\n\n        if ( d == 0 )   // bad depth\n            continue;\n        float dd = d/5000.0;\n        //\u8c03\u7528\u8ba1\u6570\u5750\u6807\u51fd\u6570\n        Point2d p1 = pixel2cam ( keypoints_1[m.queryIdx].pt, K );\n\n        pts_3d.push_back ( Point3f ( p1.x*dd, p1.y*dd, dd ) );\n        pts_2d.push_back ( keypoints_2[m.trainIdx].pt );\n    }\n\n    cout<<\"3d-2d pairs: \"<<pts_3d.size() <<endl;\n\n    Mat r, t;\n\n    solvePnP ( pts_3d, pts_2d, K, Mat(), r, t, false ); // \u8c03\u7528OpenCV \u7684 PnP \u6c42\u89e3\uff0c\u53ef\u9009\u62e9EPNP\uff0cDLS\u7b49\u65b9\u6cd5\n    //solvePnPRansac ( pts_3d, pts_2d, K, Mat(), r, t, false );\n    Mat R;\n    //\u65cb\u8f6c\u5411\u91cf\u5230\u65cb\u8f6c\u77e9\u9635\n    cv::Rodrigues ( r, R ); // r\u4e3a\u65cb\u8f6c\u5411\u91cf\u5f62\u5f0f\uff0c\u7528Rodrigues\u516c\u5f0f\u8f6c\u6362\u4e3a\u77e9\u9635\n\n    cout<<\"R=\"<<endl<<R<<endl;\n    cout<<\"t=\"<<endl<<t<<endl;\n\n\n    vector<cv::Point2f> next_keypoints;\n    vector<cv::Point3f> prev_keypoints_3d;\n    vector<cv::Point2f> prev_keypoints;\n   // list< cv::Point2f > keypoints;      // \u56e0\u4e3a\u8981\u5220\u9664\u8ddf\u8e2a\u5931\u8d25\u7684\u70b9\uff0c\u4f7f\u7528list\n    vector<cv::KeyPoint> kps;\n    cv::Ptr<cv::FastFeatureDetector> detector = cv::FastFeatureDetector::create();\n    detector->detect( img_1, kps );\n    for ( auto kp:kps )\n    {\n        prev_keypoints.push_back( kp.pt ); //\u5c06\u5750\u6807\u653e\u5165keypoints\u94fe\u8868\u4e2d\n    }\n\n\n//    for ( auto kp:keypoints )\n//    {\n//        prev_keypoints.push_back(kp); //prev_keypoints \u8d4b\u503c\u4e3akeypoints\n//    }\n    vector<unsigned char> status;\n    vector<float> error;\n\n    chrono::steady_clock::time_point t1 = chrono::steady_clock::now();\n\n    cv::calcOpticalFlowPyrLK( img_1, img_2, prev_keypoints, next_keypoints, status, error );\n\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<<\"LK Flow use time\uff1a\"<<time_used.count()<<\" seconds.\"<<endl;\n\n    cout<<\"prev:\"<<prev_keypoints.size() <<\"  next:\"<<next_keypoints.size()<<endl;\n\n    vector<cv::KeyPoint> n_Keypoints;\n    KeyPoint::convert(next_keypoints, n_Keypoints, 1, 1, 0, -1);\n\n\n    Ptr<DescriptorMatcher> matcher  = DescriptorMatcher::create ( \"BruteForce-Hamming\" );\n    vector<DMatch> match;\n    // BFMatcher matcher ( NORM_HAMMING );\n    matcher->match ( kps, n_Keypoints, match );\n\n\n\n\n    // \u628a\u8ddf\u4e22\u7684\u70b9\u5220\u6389\uff0ckeypoint \u653e\u5f53\u524d\u5e27\n\n//    int i=0;\n//    for ( auto iter=keypoints.begin(); iter!=keypoints.end(); i++)\n//    {\n//        if ( status[i] == 0 ) //\u8868\u793a\u72b6\u6001\n//        {\n//            iter = keypoints.erase(iter);\n//            continue;\n//        }\n//        *iter = next_keypoints[i];\n//        iter++;\n//    }\n//    for ( Point2f m:prev_keypoints )\n//    {\n//        //\u8ba1\u7b973D\u5750\u6807\n//        ushort d = d1.ptr<unsigned short> (int (m.y)) [ int (m.x) ];\n//        if ( d == 0 )   // bad depth\n//            continue;\n//        float dd = d/5000.0;\n//        //\u8c03\u7528\u8ba1\u6570\u5750\u6807\u51fd\u6570\n//        prev_keypoints_3d.push_back ( Point3f ( m.x*dd, m.y*dd, dd ) );\n//    }\n//\n//\n//    Mat r2, t22;\n//\n//    solvePnP ( prev_keypoints_3d, next_keypoints, K, Mat(), r2, t22, false ); // \u8c03\u7528OpenCV \u7684 PnP \u6c42\u89e3\uff0c\u53ef\u9009\u62e9EPNP\uff0cDLS\u7b49\u65b9\u6cd5\n//    //solvePnPRansac ( pts_3d, pts_2d, K, Mat(), r, t, false );\n//    Mat R2;\n//    //\u65cb\u8f6c\u5411\u91cf\u5230\u65cb\u8f6c\u77e9\u9635\n//    cv::Rodrigues ( r2, R2 ); // r\u4e3a\u65cb\u8f6c\u5411\u91cf\u5f62\u5f0f\uff0c\u7528Rodrigues\u516c\u5f0f\u8f6c\u6362\u4e3a\u77e9\u9635\n//\n//    cout<<\"R=\"<<endl<<R2<<endl;\n//    cout<<\"t=\"<<endl<<t22<<endl;\n    return 0;\n\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    //-- \u521d\u59cb\u5316\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    //-- \u7b2c\u4e00\u6b65:\u68c0\u6d4b Oriented FAST \u89d2\u70b9\u4f4d\u7f6e\n    detector->detect ( img_1,keypoints_1 );\n    detector->detect ( img_2,keypoints_2 );\n\n    //-- \u7b2c\u4e8c\u6b65:\u6839\u636e\u89d2\u70b9\u4f4d\u7f6e\u8ba1\u7b97 BRIEF \u63cf\u8ff0\u5b50\n    descriptor->compute ( img_1, keypoints_1, descriptors_1 );\n    descriptor->compute ( img_2, keypoints_2, descriptors_2 );\n\n    //-- \u7b2c\u4e09\u6b65:\u5bf9\u4e24\u5e45\u56fe\u50cf\u4e2d\u7684BRIEF\u63cf\u8ff0\u5b50\u8fdb\u884c\u5339\u914d\uff0c\u4f7f\u7528 Hamming \u8ddd\u79bb\n    vector<DMatch> match;\n    // BFMatcher matcher ( NORM_HAMMING );\n    matcher->match ( descriptors_1, descriptors_2, match );\n\n    //-- \u7b2c\u56db\u6b65:\u5339\u914d\u70b9\u5bf9\u7b5b\u9009\n    double min_dist=10000, max_dist=0;\n\n    //\u627e\u51fa\u6240\u6709\u5339\u914d\u4e4b\u95f4\u7684\u6700\u5c0f\u8ddd\u79bb\u548c\u6700\u5927\u8ddd\u79bb, \u5373\u662f\u6700\u76f8\u4f3c\u7684\u548c\u6700\u4e0d\u76f8\u4f3c\u7684\u4e24\u7ec4\u70b9\u4e4b\u95f4\u7684\u8ddd\u79bb\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    //\u5f53\u63cf\u8ff0\u5b50\u4e4b\u95f4\u7684\u8ddd\u79bb\u5927\u4e8e\u4e24\u500d\u7684\u6700\u5c0f\u8ddd\u79bb\u65f6,\u5373\u8ba4\u4e3a\u5339\u914d\u6709\u8bef.\u4f46\u6709\u65f6\u5019\u6700\u5c0f\u8ddd\u79bb\u4f1a\u975e\u5e38\u5c0f,\u8bbe\u7f6e\u4e00\u4e2a\u7ecf\u9a8c\u503c30\u4f5c\u4e3a\u4e0b\u9650.\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}\n\n\n", "meta": {"hexsha": "d26b1530274e88aa9d1f43ca1484148e42443522", "size": 6956, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch7/LK_pose_estimation_3d2d.cpp", "max_stars_repo_name": "MrCocoaCat/slambook", "max_stars_repo_head_hexsha": "1eb2c3b081c6f668f342ae8d3fa536748bedc77d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-02-13T05:39:05.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-15T17:35:25.000Z", "max_issues_repo_path": "ch7/LK_pose_estimation_3d2d.cpp", "max_issues_repo_name": "MrCocoaCat/slambook", "max_issues_repo_head_hexsha": "1eb2c3b081c6f668f342ae8d3fa536748bedc77d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch7/LK_pose_estimation_3d2d.cpp", "max_forks_repo_name": "MrCocoaCat/slambook", "max_forks_repo_head_hexsha": "1eb2c3b081c6f668f342ae8d3fa536748bedc77d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-12-21T13:59:20.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-21T13:59:20.000Z", "avg_line_length": 30.7787610619, "max_line_length": 122, "alphanum_fraction": 0.6020701553, "num_tokens": 2401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795402, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.47298032434100495}}
{"text": "\n#include <boost/test/unit_test.hpp>\n#include \"ray.h\"\n#include \"aabb.h\"\n\nBOOST_AUTO_TEST_SUITE(aabb)\n\nBOOST_AUTO_TEST_CASE(trace_through_corners)\n{\n\tmath::aabb<3> b(math::vec<3>(0, 0, 0), 20.0f);\n\tmath::ray<3> r(math::vec<3>(-20, -20, -20), math::vec<3>(40, 40, 40));\n\n\tmath::scalar t0, t1;\n\n\tb.trace(r, &t0, &t1);\n\n\tBOOST_REQUIRE (math::abs(t0 - 0.25f) < math::EPSILON);\n\tBOOST_REQUIRE (math::abs(t1 - 0.75f) < math::EPSILON);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n", "meta": {"hexsha": "7085cf4a6785429b2a0174d5f036f36de04b9772", "size": 460, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/math/test_aabb.cc", "max_stars_repo_name": "mnvl/scratch", "max_stars_repo_head_hexsha": "7717772e0b9a85c8feb73fdc3562425f48b4a727", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-08-15T11:55:32.000Z", "max_stars_repo_stars_event_max_datetime": "2016-08-15T11:55:32.000Z", "max_issues_repo_path": "src/math/test_aabb.cc", "max_issues_repo_name": "mnvl/scratch", "max_issues_repo_head_hexsha": "7717772e0b9a85c8feb73fdc3562425f48b4a727", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/math/test_aabb.cc", "max_forks_repo_name": "mnvl/scratch", "max_forks_repo_head_hexsha": "7717772e0b9a85c8feb73fdc3562425f48b4a727", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.0, "max_line_length": 71, "alphanum_fraction": 0.6586956522, "num_tokens": 173, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4729803187921155}}
{"text": "#include <vector>\n#include <tuple>\n#include <iostream>\n#include <fstream>\n#include <cmath>\n#include <string>\n#include <random>\n#include <nlopt.hpp>\n#include <Eigen/Dense>\n#include <boost/math/special_functions/binomial.hpp>\n\n#define MAXBUFSIZE  ((int) 1e6)\n\nunsigned int function_calls =0;\nunsigned long int mcmc_steps = 10000;\n\nstd::vector< std::pair<int,std::vector<double> > > read_prior(const char*\n\tfilename)\n\t{\n\t\tstd::ifstream infile;\n\t\tinfile.open(filename);\n\n\t\tstd::vector< std::pair<int,std::vector<double> > > acc;\n\n\t\twhile(!infile.eof())\n\t\t{\n\t\t\tstd::string line;\n\t\t\tstd::getline(infile,line);\n\n\t\t\tstd::stringstream stream(line);\n\t\t\tint size_household;\n\t\t\tstream >> size_household;\n\n\t\t\tstd::vector<double> priors;\n\t\t\tdouble probab;\n\t\t\twhile(stream >> probab)\n\t\t\t{\n\t\t\t\tpriors.push_back(probab);\n\t\t\t}\n\t\t\tacc.push_back(std::make_pair(size_household,priors));\n\t\t}\n\t\treturn acc;\n\t}\n\nint find_maximum(const std::vector< std::pair<int,\n\tstd::vector<double> > > &priors)\n{\n\tint curr_max = 0;\n\tfor(auto household : priors)\n\t{\n\t\tint temp = household.first;\n\t\tif(temp > curr_max) curr_max = temp;\n\t}\n\treturn curr_max;\n}\n\nEigen::MatrixXd proposal(const std::vector< std::pair<int,\n\tstd::vector<double> > > &priors,int max_n,std::mt19937 &rng)\n\t{\n\t\tEigen::MatrixXd final_sizes = Eigen::MatrixXd::Zero(max_n+1,max_n);\n\n\t\tfor(auto household : priors)\n\t\t{\n\t\t\tint number_sick=0;\n\n\t\t\tfor(double ind_prob : household.second) // We go through all members\n\t\t\t\t// of the household and assign them an individual status\n\t\t\t{\n\t\t\t\tstd::bernoulli_distribution sick(ind_prob);\n\t\t\t\tif(sick(rng))\n\t\t\t\t{\n\t\t\t\t\tnumber_sick++;\n\t\t\t\t}\n\t\t\t}\n\n\t\tfinal_sizes(number_sick,household.first-1)++;\n\t\t}\n\t\treturn final_sizes;\n\t}\n\nEigen::MatrixXd readMatrix(const char *filename)\n    {\n    int cols = 0, rows = 0;\n    double buff[MAXBUFSIZE];\n\n    // Read numbers from file into buffer.\n    std::ifstream infile;\n    infile.open(filename);\n    while (! infile.eof())\n        {\n        std::string line;\n        std::getline(infile, line);\n\n        int temp_cols = 0;\n        std::stringstream stream(line);\n        while(! stream.eof())\n            stream >> buff[cols*rows+temp_cols++];\n\n        if (temp_cols == 0)\n            continue;\n\n        if (cols == 0)\n            cols = temp_cols;\n\n        rows++;\n        }\n\n    infile.close();\n\n    // rows--;\n\n    // Populate matrix with numbers.\n    Eigen::MatrixXd result(rows,cols);\n    for (int i = 0; i < rows; i++)\n        for (int j = 0; j < cols; j++)\n            result(i,j) = buff[ cols*i+j ];\n\n    return result;\n    }\n\ndouble Phi(const double &x, const double &alpha, const double &beta, const\n\tdouble &k, const int n)\n{\n\tdouble mean = beta/pow(n,alpha);\n\treturn pow(k/(k+x*mean),k);\n}\n\n/* Returns a (n+1)*(n+1) matrix such that F(i,j) = F_i^{n,j}. Columns correspond\nto different values of s0, rows are the m values. As such, F is upper \ntriangular, and F(i,j) for i>j is undefined. */\n\nstd::pair<Eigen::MatrixXd,Eigen::MatrixXd> solve_triangular(const\n\tstd::vector<double> &v, const int n)\n\t{\n\t\tEigen::MatrixXd result1(n+1,n+1);\n\t\tEigen::MatrixXd result2(n+1,n+1);\t\t\n\t\tfor (int s0=0; s0 <= n; ++s0)\n\t\t{\n\t\t\tEigen::MatrixXd A1(s0+1,s0+1);\n\t\t\tEigen::MatrixXd A2(s0+1,s0+1);\t\t\t\n\t\t\tEigen::VectorXd B(s0+1);\n\t\t\tfor(int i=0; i<=s0; ++i)\n\t\t\t{\n\t\t\t\tB(i) = boost::math::binomial_coefficient<double>(s0,i);\n\t\t\t\tfor (int j = 0; j <= i; ++j)\n\t\t\t\t{\n\t\t\t\t\tA1(i,j) = boost::math::binomial_coefficient<double>\n\t\t\t\t\t(s0-j,i-j)\n\t\t\t\t\t/(pow(Phi(s0-i,v[6],v[5],v[4],n),j)*(pow(v[0],s0-i)));\n\t\t\t\t\tA2(i,j) = boost::math::binomial_coefficient<double>\n\t\t\t\t\t(s0-j,i-j)\n\t\t\t\t\t/(pow(Phi(s0-i,v[6],v[5],v[4],n),j)*(pow(v[3],s0-i)));\n\t\t\t\t}\n\t\t\t}\n\t\t\tEigen::VectorXd sol1 = A1.triangularView<Eigen::Lower>().solve(B);\n\t\t\tsol1.conservativeResize(n+1);\n\t\t\tresult1.col(s0)=sol1;\n\t\t\tEigen::VectorXd sol2 = A2.triangularView<Eigen::Lower>().solve(B);\n\t\t\tsol2.conservativeResize(n+1);\n\t\t\tresult2.col(s0)=sol2;\t\t\t\n\t\t}\n\n\t\tfor (int i = 0; i <= n; ++i)\n\t\t{\n\t\t\tfor (int j = 0; j < i; ++j)\n\t\t\t{\n\t\t\t\tresult1(i,j)=1;\n\t\t\t\tresult2(i,j)=0;\n\t\t\t}\n\t\t}\n \t\treturn std::pair<Eigen::MatrixXd,Eigen::MatrixXd> {result1, result2};\n\t}\n\n/* Returns the value of T_{(m,n)}, the expected frequency of households of size \nn with m infected individuals. Arguments are a tuple (n,m), the running \nparameter vector and the precomputed matrix containing the F_m^{n,s0}. */\ndouble expected_prob(const std::tuple<int,int> &sizes, const\n\tstd::vector<double> &parameters, const\n\tstd::pair<Eigen::MatrixXd,Eigen::MatrixXd> &distributions)\n\t{\n\tconst double n = std::get<0>(sizes); // n \\ge 1\n\tconst double m = std::get<1>(sizes); // 0 \\le m \\le s0\n\n\tdouble pasx = parameters[1];\n\tdouble ppr = parameters[2];\n\n\tEigen::MatrixXd dis_current = distributions.first;\n\tEigen::MatrixXd dis_prior = distributions.second;\n\n\tdouble sum=0.;\n\n\tfor(int t=0; t<=(n-m); ++t)\n\t{\n\t\tfor(int r=0; r<=(n-m-t); ++r)\n\t\t{\n\t\t\tfor (int l = 0; l<= (n-m-r-t); ++l)\n\t\t\t{\n\t\t\t\tdouble prob1 = boost::math::binomial_coefficient<double>\n\t\t\t\t(m+t,t)*pow(pasx,t)*pow(1-pasx,m);\n\t\t\t\tdouble prob2 = boost::math::binomial_coefficient<double>\n\t\t\t\t(n,r)*pow(ppr,r)*pow(1-ppr,n-r);\n\t\t\t\tif(m+t>n-r-l) std::cout << \"n=\" << n << \" m=\" << m << \" t=\" << t\n\t\t\t\t\t<< \" r=\" << r << \" l=\" << l << std::endl;\n\t\t\t\tdouble expected_prob1 = dis_current(m+t,n-r-l);\n\t\t\t\tdouble expected_prob2 = dis_prior(l,n-r);\t\t\t\t\n\t\t\t\tsum += prob1*prob2*expected_prob1*expected_prob2;\n\t\t\t}\n\t\t}\n\t}\n\treturn sum;\n}\t\n\ndouble Dev(const std::vector<double> &v, std::vector<double> &grad, void* \n\tmy_func_data)\n\t{\n\t\t/* Contains the observed final sizes k_{(m,n)}. Be careful : \n\t\thouseholds(i,j) contains k_{(i,j+1)}. Also, households(i,j)=0 \n\t\tif i>j. */\n\t\tconst Eigen::MatrixXd *households =\n\t\t\tstatic_cast<Eigen::MatrixXd *>(my_func_data); \n\n\t\tint max_n = (*households).cols();\n\n\t\tstd::vector< std::pair<Eigen::MatrixXd,Eigen::MatrixXd > >\n\t\tdistribution_matrices;\n\n\t\t/*\tComputes the expected final size distributions F(n; s0,m) for 1\n\t\t\\le n \\le n_max and m\\le s0 \\le n. Output is a vector whose (n+1)-th\n\t\telement contains the matrix of the F(n;s0,m) for a fixed n. */\n\n\t\tfor (int n = 1; n <= max_n; ++n)\n\t\t{\n\t\t\tstd::pair<Eigen::MatrixXd,Eigen::MatrixXd> temp = solve_triangular\n\t\t\t(v,n);\n\t\t\tdistribution_matrices.push_back(temp);\n\t\t}\n\n\t\tdouble sum = 0.;\n\n\t\tauto colSums = (*households).colwise().sum();\n\n\t\tfor (int n = 1; n <= max_n; ++n)\n\t\t{\n\t\t\tdouble col_sum = colSums(n-1);\n\t\t\tfor(int m=0; m<=n; ++m)\n\t\t\t{\n\t\t\t\tdouble observed = (*households)(m,n-1);\n\t\t\t\tif(observed==0.) continue;\n\t\t\t\tstd::tuple<int,int> obs_tuple {n,m};\n\t\t\t\tdouble expected = expected_prob(obs_tuple, v,\n\t\t\t\t\tdistribution_matrices[n-1]);\n\t\t\t\tsum += observed*(std::log10(observed/col_sum)-\n\t\t\t\t\tstd::log10(expected));\n\t\t\t}\n\t\t}\n\t\treturn sum; \n\t}\n\nint main(int argc, char const *argv[])\n{\n\tconst auto priors = read_prior(\"test_prior.txt\");\n\n\tconst int max_n = find_maximum(priors);\n\n\tstd::vector<Eigen::MatrixXd> households; /* Contiendra les valeurs de \n\ttailles finales */\n\n\tnlopt::opt opt(nlopt::LN_BOBYQA, 7);\n\n\tvoid* f_data;\n\n\topt.set_min_objective(Dev,f_data); // D\u00e9finit Dev comme fonction \u00e0 minimiser\n\n\t/* Les param\u00e8tres sont dans l'ordre (cf Fraser et al. 2011) :\n\n\t- La proba d'\u00e9chappement Q\n\t- La proba d'infection asymptomatique et infectieuse p_asx\n\t- La proba d'infection asymptomatique et non-infectieuse p_r\n\t- La proba d'\u00e9chappement \u00e0 une infection ant\u00e9rieure Q_prior\n\t- H\u00e9t\u00e9rog\u00e9n\u00e9it\u00e9 des infectivit\u00e9s k\n\t- Facteur de taille du domicile beta\n\t- Exposant de la taille du domicile alpha\n\n\t*/\n\n\tstd::vector<double> lb { 0.,0.,0.,0.,0.,0.,0. };\n\tstd::vector<double> ub { 1.,1.,1.,1.,5.,5.,5. };\n\topt.set_lower_bounds(lb);\n\topt.set_upper_bounds(ub);\n\n\tstd::vector<std::string> var_names\n\t\t{\"Q\",\"p_asx\",\"p_pr\",\"Q_prior\",\"k\",\"beta\",\"alpha\"};\n\tstd::vector<double> init_guess { 0.5,0.5,0.5,0.5,1.,1.,1. } ;\n\n\tEigen::MatrixXd test_matrix = readMatrix(\"sim_matrix.txt\");\n\n\tstd::vector<std::vector<double> > variables;\n\n\t// Eigen::MatrixXd prop = proposal(priors,max_n,rd);\n\t// std::cout << prop << std::endl;\n\tvoid* my_func_data = static_cast<void *>(&test_matrix);\n\topt.set_min_objective(Dev,my_func_data);\n\tdouble minf =0.;\n\ttry\n\t{\n\t\tnlopt::result result = opt.optimize(init_guess,minf);\n\t}\tcatch(const nlopt::roundoff_limited& e)\n\t{\n\t\tfor(int i=0; i<7; ++i)\n\t\t{\n\t\t\tstd::cout << var_names[i] << \" : \" << init_guess[i] << std::endl;\n\t\t}\n\t\tstd::cout << \"Vraisemblance : \" << minf << std::endl;\n\t}\n\n\t// std::random_device rd;\n\t// std::mt19937 rng(rd());\t\t\n\n\t// for (unsigned long int i = 0; i < mcmc_steps; ++i)\n\t// {\n\t// \tEigen::MatrixXd prop = proposal(priors,max_n,rng);\n\t// \tstd::vector<double> init_guess { 0.5,0.5,0.5,0.5,1.,1.,1. } ;\n\t// \tvoid* my_func_data = static_cast<void *>(&prop);\n\t// \topt.set_min_objective(Dev,my_func_data);\n\t// \topt.set_maxeval(10000);\n\t// \tdouble minf = 0.;\n\t// \ttry\n\t// \t{\n\t// \t\tnlopt::result result = opt.optimize(init_guess,minf);\n\t// \t}\tcatch(const nlopt::roundoff_limited& e)\n\t// \t{\n\t// \t\tif(isnan(minf)) \n\t// \t\t{\n\t// \t\t\tstd::cout << prop << std::endl;\n\t// \t\t\tbreak;\n\t// \t\t}\n\t// \t\tinit_guess.push_back(minf);\n\t// \t\tvariables.push_back(init_guess);\n\t// \t}\t\t\n\t// }\n\n\t// std::ofstream outfile(\"mcmc_output.csv\");\n //    std::ostream_iterator<double> output_iterator(outfile, \" \");\n //    for(auto iteration : variables)\n //    {\n\t// \tstd::copy(iteration.begin(),iteration.end(),output_iterator);\n\t// \toutfile << \"\\n\";\n //    }\n\n\treturn 0;\n}", "meta": {"hexsha": "18c280a8255917d3f83a9cea55ba3b7a59004173", "size": 9321, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/fraser_model_optim/fraser_model.cpp", "max_stars_repo_name": "phoscheit/reed_frost", "max_stars_repo_head_hexsha": "17555bb1808c5068047f28f431882a389215517a", "max_stars_repo_licenses": ["MIT"], "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/fraser_model_optim/fraser_model.cpp", "max_issues_repo_name": "phoscheit/reed_frost", "max_issues_repo_head_hexsha": "17555bb1808c5068047f28f431882a389215517a", "max_issues_repo_licenses": ["MIT"], "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/fraser_model_optim/fraser_model.cpp", "max_forks_repo_name": "phoscheit/reed_frost", "max_forks_repo_head_hexsha": "17555bb1808c5068047f28f431882a389215517a", "max_forks_repo_licenses": ["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.5555555556, "max_line_length": 80, "alphanum_fraction": 0.625254801, "num_tokens": 2981, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4729803187921154}}
{"text": "/*\n * eval_basic.cpp\n * Date: 2013-05-10\n * Author: Karsten Ahnert (karsten.ahnert@gmx.de)\n */\n\n#define FUSION_MAX_VECTOR_SIZE 20\n\n#include \"parser.hpp\"\n#include \"generate_data.hpp\"\n\n#include <gpcxx/eval/static_eval.hpp>\n#include <gpcxx/generate/basic_generate_strategy.hpp>\n#include <gpcxx/generate/uniform_symbol.hpp>\n#include <gpcxx/io/simple.hpp>\n#include <gpcxx/tree/basic_tree.hpp>\n#include <gpcxx/app/timer.hpp>\n#include <gpcxx/stat/node_statistics.hpp>\n\n#include <boost/fusion/include/make_vector.hpp>\n\n#include <iostream>\n#include <functional>\n#include <fstream>\n#include <vector>\n#include <random>\n#include <cmath>\n#include <array>\n\nusing namespace std;\nnamespace fusion = boost::fusion;\n\ntypedef double value_type;\ntypedef std::vector< value_type > vector_type;\ntypedef std::array< double , 3 > context_type;\ntypedef char symbol_type;\ntypedef std::mt19937 rng_type ;\n\n\nconst std::string tab = \"\\t\";\n\ninline value_type my_log( value_type v )\n{\n    return ( std::abs( v ) < 1.0e-20 ) ? 0.0 : std::log( std::abs( v ) );\n}\n\nstruct my_div\n{\n    template< typename T >\n    inline T operator()( T const& t1 , T const &t2 ) const\n    {\n        if( t2 == 0.0 ) return 1.0;\n        else return t1 / t2;\n    }\n};\n\ndouble objective_function( double x1 , double x2 , double x3 )\n{\n    return  1.0 / ( 1.0 + pow( x1 , -4.0 ) ) + 1.0 / ( 1.0 + pow( x2 , -4.0 ) ) + 1.0 / ( 1.0 + pow( x3 , -4.0 ) );\n}\n\nstruct eval_cursor1\n{\n    template< typename Cursor >\n    static inline value_type eval_cursor( Cursor const& c , context_type const &context )\n    {\n        switch( *c )\n        {\n            case 'x' : return context[0]; break;\n            case 'y' : return context[1]; break;\n            case 'z' : return context[2]; break;\n            case 'e' : return exp( eval_cursor( c.children(0) , context ) ); break;\n            case 'l' : return my_log( eval_cursor( c.children(0) , context ) ); break;\n            case 's' : return sin( eval_cursor( c.children(0) , context ) ); break;\n            case 'c' : return cos( eval_cursor( c.children(0) , context ) ); break;\n            case '+' : return eval_cursor( c.children(0) , context ) + eval_cursor( c.children(1) , context ); break;\n            case '-' : return eval_cursor( c.children(0) , context ) - eval_cursor( c.children(1) , context ); break;\n            case '*' : return eval_cursor( c.children(0) , context ) * eval_cursor( c.children(1) , context ); break;\n            case '/' : return my_div()( eval_cursor( c.children(0) , context ) , eval_cursor( c.children(1) , context ) ); break;\n        }\n        return value_type( 0.0 );\n    }\n    \n    template< typename Tree >\n    inline value_type operator()( Tree const &t , context_type const &context ) const\n    {\n        return eval_cursor1::eval_cursor( t.root() , context );\n    }\n};\n\n\n\nstruct eval_cursor2\n{\n    template< typename Cursor >\n    inline static value_type eval_cursor( Cursor const &c , context_type const &context )\n    {\n        if( c.size() == 0 )\n        {\n            switch( *c )\n            {\n                case 'x' : return context[0]; break;\n                case 'y' : return context[1]; break;\n                case 'z' : return context[2]; break;\n            }\n        }\n        else if( c.size() == 1 )\n        {\n            switch( *c )\n            {\n                case 'e' : return exp( eval_cursor( c.children(0) , context ) ); break;\n                case 'l' : return my_log( eval_cursor( c.children(0) , context ) ); break;\n                case 's' : return sin( eval_cursor( c.children(0) , context ) ); break;\n                case 'c' : return cos( eval_cursor( c.children(0) , context ) ); break;\n            }\n        }\n        else if( c.size() == 2 )\n        {\n            switch( *c )\n            {\n                case '+' : return eval_cursor( c.children(0) , context ) + eval_cursor( c.children(1) , context ); break;\n                case '-' : return eval_cursor( c.children(0) , context ) - eval_cursor( c.children(1) , context ); break;\n                case '*' : return eval_cursor( c.children(0) , context ) * eval_cursor( c.children(1) , context ); break;\n                case '/' : return eval_cursor( c.children(0) , context ) / eval_cursor( c.children(1) , context ); break;\n            }\n        }\n\n    }\n    \n    template< typename Tree >\n    inline value_type operator()( Tree const &t , context_type const &context ) const\n    {\n        return eval_cursor( t.root() , context );\n    }\n};\n\n\n\ntemplate< typename Cursor >\nstruct eval_cursor3\n{\n    typedef Cursor cursor_type;\n    typedef eval_cursor3< cursor_type > evaluator;\n    \n    \n    static inline double eval_x( cursor_type const &c , context_type const& context ) { return context[0]; }\n    static inline double eval_y( cursor_type const &c , context_type const& context ) { return context[0]; }\n    static inline double eval_z( cursor_type const &c , context_type const& context ) { return context[0]; }\n    static inline double eval_sin( cursor_type const &c , context_type const& context ) { return sin( eval_cursor( c.children(0) , context ) ); }\n    static inline double eval_cos( cursor_type const &c , context_type const& context ) { return cos( eval_cursor( c.children(0) , context ) ); }\n    static inline double eval_exp( cursor_type const &c , context_type const& context ) { return exp( eval_cursor( c.children(0) , context ) ); }\n    static inline double eval_log( cursor_type const &c , context_type const& context ) { return my_log( eval_cursor( c.children(0) , context ) ); }\n    static inline double eval_plus( cursor_type const &c , context_type const& context )\n    { return  eval_cursor( c.children(0) , context ) + eval_cursor( c.children(1) , context ); }\n    static inline double eval_minus( cursor_type const &c , context_type const& context )\n    { return eval_cursor( c.children(0) , context ) - eval_cursor( c.children(1) , context ); }\n    static inline double eval_multiplies( cursor_type const &c , context_type const& context )\n    { return eval_cursor( c.children(0) , context ) * eval_cursor( c.children(1) , context ); }\n    static inline double eval_divides( cursor_type const &c , context_type const& context )\n    { return eval_cursor( c.children(0) , context ) / eval_cursor( c.children(1) , context ); }\n    \n    typedef double( *func_type )( cursor_type const& , context_type const& );\n    typedef std::array< func_type , 128 > lookup_table_type;\n    static lookup_table_type const& get_table( void )\n    {\n        static lookup_table_type tbl;\n        std::fill( tbl.begin() , tbl.end() , nullptr );\n        tbl[ size_t( 'x' ) ] = &evaluator::eval_x;\n        tbl[ size_t( 'y' ) ] = &evaluator::eval_y;\n        tbl[ size_t( 'z' ) ] = &evaluator::eval_z;\n        tbl[ size_t( 's' ) ] = &evaluator::eval_sin;\n        tbl[ size_t( 'c' ) ] = &evaluator::eval_cos;\n        tbl[ size_t( 'e' ) ] = &evaluator::eval_exp;\n        tbl[ size_t( 'l' ) ] = &evaluator::eval_log;\n        tbl[ size_t( '+' ) ] = &evaluator::eval_plus;\n        tbl[ size_t( '-' ) ] = &evaluator::eval_minus;\n        tbl[ size_t( '*' ) ] = &evaluator::eval_multiplies;\n        tbl[ size_t( '/' ) ] = &evaluator::eval_divides;\n        return tbl;\n    }\n    \n    static double eval_cursor( cursor_type const &cursor , context_type const& c ) \n    {\n        lookup_table_type const& tbl = get_table();\n        func_type f = tbl[ size_t( *cursor ) ];\n        return (*f)( cursor , c );\n    }\n    \n    template< typename Tree >\n    double operator()( Tree const& t , context_type const & c ) const\n    {\n        return eval_cursor( t.root() , c );\n    }\n};\n\n\nauto eval_cursor4 = gpcxx::make_static_eval< value_type , symbol_type , context_type >(\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        , fusion::make_vector( 'e' , []( double v ) -> double { return std::exp( v ); } )\n        , fusion::make_vector( 'l' , []( double v ) -> double { return my_log( 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\n\n\n\n\n\n/// \\return time for evaluation of tree, result sum\ntemplate< typename Evaluator , typename Trees >\nstd::tuple< double , double > run_test( Evaluator const &eval , Trees const &trees , const vector_type &x1 , const vector_type &x2 , const vector_type &x3 , std::vector< double > &fitness )\n{\n    std::tuple< double , double > res;\n\n    size_t number_of_datapoints = x1.size();\n    size_t number_of_trees = trees.size();\n    std::vector< vector_type > y( number_of_trees );\n    for( size_t t=0 ; t<number_of_trees ; ++t ) y[t] = vector_type( number_of_datapoints );\n\n    // \n    // EVALUATION\n    //\n    gpcxx::timer timer;\n    for( size_t t=0 ; t<number_of_trees ; ++t )\n    {\n        for( size_t i=0 ; i<number_of_datapoints ; ++i )\n        {\n            context_type c { { x1[i] , x2[i] , x3[i] } };\n            y[t][i] = eval( trees[t] , c );\n        }\n    }\n    std::get< 0 >( res ) = timer.seconds();\n\n    double sum = 0.0;\n    \n    for( size_t t=0 ; t<number_of_trees ; ++t )\n    {\n        double chi2 = 0.0;\n        for( size_t i=0 ; i<number_of_datapoints ; ++i )\n        {\n            sum += y[t][i];\n            double diff = y[t][i] - objective_function( x1[i] , x2[i] , x3[i] );\n            chi2 += std::abs( diff );\n        }\n        chi2 /= double( x1.size() );\n        fitness.push_back( 1.0 / ( 1.0 + chi2 ) );\n    }\n    std::get< 1 >( res ) = sum;\n\n    return res;\n}\n\ntemplate< typename Tree , typename Evaluator >\nvoid run_tree_type( std::string const &name , Evaluator const& eval , vector_type const &x1 , vector_type const &x2 , vector_type const &x3 , std::string const & filename )\n{\n    std::vector< Tree > trees;\n\n    // read trees\n    ifstream fin( filename );\n    std::string line;\n    while( std::getline( fin , line ) )\n    {\n        Tree tree;\n        trees.push_back( tree );\n        parser::tree_transformator< Tree > trafo( trees.back() , trees.back().root() );\n        parser::parse_tree( line , trafo );\n    }\n    \n    std::vector< double > fitness;\n\n    cout.precision( 14 );\n    cout << \"Starting test \" << name << endl;\n    auto times = run_test( eval , trees , x1 , x2 , x3 , fitness );\n    cout << tab << \"Finished!\" << endl;\n    cout << tab << \"Evaluation time \" << std::get< 0 >( times ) << endl;\n    cout << tab << \"Result sum \" << std::get< 1 >( times ) << endl << endl;\n    \n    std::ofstream fout( std::string( \"eval_\" ) + name + \".dat\" );\n    fout.precision( 14 );\n    for( size_t i=0 ; i<fitness.size() ; ++i )\n    {\n        gpcxx::node_statistics stat = gpcxx::calc_node_statistics_tree( trees[i] );\n        \n        fout << i;\n        fout << tab << fitness[i];\n        fout << tab << trees[i].root().height();\n        fout << tab << stat.num_nodes;\n        fout << tab << gpcxx::simple( trees[i] );\n        fout << \"\\n\";\n    }\n}\n\n\nint main( int argc , char *argv[] )\n{\n    if( argc != 2 )\n    {\n        cerr << \"usage : \" << argv[0] << \" infile\" << endl;\n        return -1;\n    }\n\n    // generate test data\n    vector_type x1, x2 , x3;\n    // generate_test_data( x1 , x2 , x3 , -5.0 , 5.0 + 0.1 , 1.0 );\n    generate_test_data( x1 , x2 , x3 , -5.0 , 5.0 + 0.1 , 0.4 );\n\n    // run test for several tree tests\n    run_tree_type< gpcxx::basic_tree< char > >( \"basic_tree_eval1\" , eval_cursor1() , x1 , x2 , x3 , argv[1] );\n//     run_tree_type< gpcxx::basic_tree< char > >( \"basic_tree_eval2\" , eval_cursor2() , x1 , x2 , x3 , argv[1] );\n//     run_tree_type< gpcxx::basic_tree< char > >( \"basic_tree_eval3\" , eval_cursor3< gpcxx::basic_tree< char >::const_cursor >() , x1 , x2 , x3 , argv[1] );\n//     run_tree_type< gpcxx::basic_tree< char > >( \"basic_tree_eval4\" , eval_cursor4 , x1 , x2 , x3 , argv[1] );\n\n    return 0;\n}\n", "meta": {"hexsha": "089de8340c1acefa33d32fde7d2e1ba4aad56d24", "size": 12329, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "performance/eval_basic/eval_basic.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": "performance/eval_basic/eval_basic.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": "performance/eval_basic/eval_basic.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": 37.7033639144, "max_line_length": 189, "alphanum_fraction": 0.5813934626, "num_tokens": 3446, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.803173791645582, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4729803160176706}}
{"text": "#pragma once\n\n// system includes --------------------------------------------------\n#include <Eigen/Dense>\n\n// own includes -----------------------------------------------------\n#include <ridgelet/ridgelet_cell_array.hpp>\n#include <ridgelet/rt.hpp>\n\n\ntemplate <typename FRAME>\nstd::vector<double>\nmake_inv_diagonal_preconditioner(const FRAME &frame, double vx, double vy)\n{\n  auto &lambdas = frame.lambdas();\n  unsigned int N = lambdas.size();\n  std::vector<double> d(N);\n\n  Eigen::Vector2d sjk;\n  Eigen::Vector2d v;\n  v(0) = vx;\n  v(1) = vy;\n\n  for (unsigned int i = 0; i < N; ++i) {\n    int j = lambdas[i].j;\n    double p2mn = std::pow(2., j - 1);\n    int k = lambdas[i].k;\n    if (lambdas[i].t == rt_type::S) {\n      d[i] = 1.0;\n    } else if (lambdas[i].t == rt_type::X) {\n      sjk(0) = 1;\n      sjk(1) = double(k) / p2mn;\n      sjk.normalize();\n      d[i] = 1 + std::pow(2., j) * std::abs(sjk.dot(v));\n    } else if (lambdas[i].t == rt_type::Y) {\n      sjk(0) = double(k) / p2mn;\n      sjk(1) = 1;\n      sjk.normalize();\n      d[i] = 1 + std::pow(2., j) * std::abs(sjk.dot(v));\n    } else if (lambdas[i].t == rt_type::D) {\n      k = (k < 0) ? -1 : 1;\n      sjk(0) = 1;\n      sjk(1) = k;\n      sjk.normalize();\n      d[i] = 1 + std::pow(2., j) * std::abs(sjk.dot(v));\n    } else {\n      assert(false);\n    }\n  }\n\n  return d;\n}\n\ntemplate <typename ARRAY_T>\nclass DiagonalOperator\n{\n private:\n  typedef RidgeletCellArray<ARRAY_T> rca_t;\n\n public:\n  DiagonalOperator(const std::vector<double> &d)\n      : d_(d)\n  { /* empty  */\n  }\n\n  DiagonalOperator() {}\n\n  DiagonalOperator &operator=(const DiagonalOperator &other) { d_ = other.d_; }\n\n  DiagonalOperator(std::vector<double> &&d)\n      : d_(std::forward<std::vector<double>>(d))\n  { /* empty  */\n  }\n\n  void apply(rca_t &dst) const;\n  void apply(rca_t &dst, const rca_t &src) const;\n\n  void invert();\n\n private:\n  std::vector<double> d_;\n};\n\ntemplate <typename ARRAY_T>\nvoid\nDiagonalOperator<ARRAY_T>::apply(rca_t &dst) const\n{\n  assert(d_.size() == dst.coeffs().size());\n\n  for (unsigned int i = 0; i < d_.size(); ++i) {\n    dst[i] *= d_[i];\n  }\n}\n\ntemplate <typename ARRAY_T>\nvoid\nDiagonalOperator<ARRAY_T>::apply(rca_t &dst, const rca_t &src) const\n{\n  assert(d_.size() == dst.coeffs().size());\n  assert(d_.size() == src.coeffs().size());\n\n  for (unsigned int i = 0; i < d_.size(); ++i) {\n    dst[i] = d_[i] * src[i];\n  }\n}\n\ntemplate <typename ARRAY_T>\nvoid\nDiagonalOperator<ARRAY_T>::invert()\n{\n  for (unsigned int i = 0; i < d_.size(); ++i) {\n    d_[i] = 1. / d_[i];\n  }\n}\n\n// ================================================================================\n// ================================================================================\n// ================================================================================\nclass TransportOperator\n{\n protected:\n  typedef Eigen::ArrayXXcd complex_array_t;\n  typedef Eigen::ArrayXd col_t;  // (column vector)\n\n public:\n  TransportOperator(double vx, double vy, double Lx, double Ly, int Nx, int Ny, double dt = 1.0)\n      : vx_(vx)\n      , vy_(vy)\n      , Lx_(Lx)\n      , Ly_(Ly)\n      , Nx_(Nx)\n      , Ny_(Ny)\n      , dt_(dt)\n  {\n    Eigen::Vector2d v;\n    v(0) = vx;\n    v(1) = vy;\n\n    // init xi_x\n    if (Nx % 2 == 0)\n      xi_x_ = col_t::LinSpaced(Nx, -Nx / 2, Nx / 2 - 1) / Lx;\n    else\n      xi_x_ = col_t::LinSpaced(Nx, -Nx / 2, Nx / 2) / Lx;\n\n    // init xi_y\n    if (Ny % 2 == 0)\n      xi_y_ = col_t::LinSpaced(Ny, -Ny / 2, Ny / 2 - 1) / Ly;\n    else\n      xi_y_ = col_t::LinSpaced(Ny, -Ny / 2, Ny / 2) / Ly;\n  }\n\n  template <typename COMPLEX_ARRAY>\n  void apply(COMPLEX_ARRAY &dst, const COMPLEX_ARRAY &src, bool conj = false) const;\n\n  template <typename COMPLEX_ARRAY>\n  void apply_bckwrd_euler(COMPLEX_ARRAY &dst) const;\n\n protected:\n  double vx_;\n  double vy_;\n  double Lx_;\n  double Ly_;\n  unsigned int Nx_;\n  unsigned int Ny_;\n\n  col_t xi_x_;\n  col_t xi_y_;\n  const double twoPI = 2 * 3.141592653589793238462643;\n  const std::complex<double> I = std::complex<double>(0, 1);\n  double dt_;\n};\n\ntemplate <typename COMPLEX_ARRAY>\nvoid\nTransportOperator::apply(COMPLEX_ARRAY &dst, const COMPLEX_ARRAY &src, bool conj) const\n{\n  typedef typename COMPLEX_ARRAY::Scalar numeric_t;\n\n  const double f = conj ? -1 : 1;\n  dst = src +\n        f * (twoPI * dt_ * I) *\n            (vx_ * xi_x_.transpose().replicate(Ny_, 1) + vy_ * xi_y_.replicate(1, Nx_))\n                .cast<numeric_t>()\n                .array() *\n            src.array();\n}\n\ntemplate <typename COMPLEX_ARRAY>\nvoid\nTransportOperator::apply_bckwrd_euler(COMPLEX_ARRAY &dst) const\n{\n  typedef typename COMPLEX_ARRAY::Scalar numeric_t;\n  dst = dst.cwiseQuotient(\n      COMPLEX_ARRAY::Ones(Ny_, Nx_) +\n      twoPI * dt_ * I *\n          (vx_ * xi_x_.transpose().replicate(Ny_, 1) + vy_ * xi_y_.replicate(1, Nx_))\n              .cast<numeric_t>()\n              .array());\n}\n\n// ================================================================================\n/**\n *   @brief \\f$ T' T  \\f$\n */\nclass AhAOp : public TransportOperator\n{\n private:\n  typedef Eigen::ArrayXXcd complex_array_t;\n  typedef Eigen::ArrayXd col_t;\n\n public:\n  AhAOp(double vx, double vy, double Lx, double Ly, int Nx, int Ny, double dt = 1.0)\n      : TransportOperator(vx, vy, Lx, Ly, Nx, Ny, dt)\n  {\n    dt2_ = dt_ * dt_;\n  }\n\n  template <typename DERIVED1, typename DERIVED2>\n  void apply(Eigen::ArrayBase<DERIVED1> &dst, const Eigen::ArrayBase<DERIVED2> &src) const;\n\n private:\n  using TransportOperator::xi_x_;\n  using TransportOperator::xi_y_;\n  double dt2_;\n};\n\ntemplate <typename DERIVED1, typename DERIVED2>\nvoid\nAhAOp::apply(Eigen::ArrayBase<DERIVED1> &dst, const Eigen::ArrayBase<DERIVED2> &src) const\n{\n  static_assert(std::is_same<typename DERIVED1::Scalar, typename DERIVED2::Scalar>::value,\n                \"type mismatch\");\n  typedef typename DERIVED1::Scalar numeric_t;\n\n  dst = src +\n        twoPI * twoPI * dt2_ *\n            (vx_ * xi_x_.transpose().replicate(Ny_, 1) + vy_ * xi_y_.replicate(1, Nx_))\n                .cwiseAbs2()\n                .cast<numeric_t>()\n                .array() *\n            src;\n}\n\n// ================================================================================\n// ================================================================================\n// ================================================================================\n// transport operator with boundary conditions\nclass TransportOperatorBC : public TransportOperator\n{\n public:\n  template <typename DERIVED>\n  TransportOperatorBC(const Eigen::DenseBase<DERIVED> &sigma,\n                      double vx,\n                      double vy,\n                      double Lx,\n                      double Ly,\n                      int Nx,\n                      int Ny,\n                      double dt = 1.0)\n      : TransportOperator(vx, vy, Lx, Ly, Nx, Ny, dt)\n  {\n    sigma_ = sigma;\n  }\n\n  template <typename COMPLEX_ARRAY>\n  void apply(COMPLEX_ARRAY &dst, const COMPLEX_ARRAY &src, bool conj = false) const;\n\n private:\n#ifdef USE_PLANNED_FFT\n  typedef FFTr2c<PlannerR2C> fft_t;\n#else\n  typedef FFTr2c<PlannerR2COD> fft_t;\n#endif\n\n  typedef Eigen::Array<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> array_t;\n\n private:\n  Eigen::ArrayXXd sigma_;\n};\n\ntemplate <typename COMPLEX_ARRAY>\nvoid\nTransportOperatorBC::apply(COMPLEX_ARRAY &dst, const COMPLEX_ARRAY &src, bool conj) const\n{\n  typedef COMPLEX_ARRAY complex_array_t;\n  typedef typename complex_array_t::Scalar numeric_t;\n  const double f = conj ? -1 : 1;\n\n  // TODO: (inefficient) memory allocation\n  array_t fn(src.rows(), src.cols());\n  double r = std::sqrt(vx_ * vx_ + vy_ * vy_);\n  fft_t fft;\n  fft.ift(fn, src);\n  fn *= sigma_ * r;\n  fft.ft(dst, fn, false);\n  dst *= dt_;\n  dst += src +\n         f * (twoPI * dt_ * I) *\n             (vx_ * xi_x_.transpose().replicate(Ny_, 1) + vy_ * xi_y_.replicate(1, Nx_))\n                 .cast<numeric_t>()\n                 .array() *\n             src.array();\n}\n\n/**\n * @brief \\f$ T'T \\f$  * where T is of type \\a TransportOperatorBC an absorption\n * term (otherwise\n * identical to \\a AhAOp)\n *\n *\n */\nclass AhAOpsigma : public TransportOperatorBC\n{\n private:\n  typedef TransportOperatorBC transport_op_t;\n\n public:\n  template <typename DERIVED>\n  AhAOpsigma(const Eigen::DenseBase<DERIVED> &sigma,\n             double vx,\n             double vy,\n             double Lx,\n             double Ly,\n             int Nx,\n             int Ny,\n             double dt = 1.0)\n      : TransportOperatorBC(sigma, vx, vy, Lx, Ly, Nx, Ny, dt)\n  { /* empty  */\n  }\n\n  template <typename COMPLEX_ARRAY>\n  void apply(COMPLEX_ARRAY &dst, const COMPLEX_ARRAY &src) const\n  {\n    typedef COMPLEX_ARRAY complex_array_t;\n    typedef typename complex_array_t::Scalar numeric_t;\n\n    complex_array_t tmp(dst.rows(), dst.cols());\n\n    transport_op_t::apply(tmp, src);\n    transport_op_t::apply(dst, tmp, true);\n  }\n};\n\n// ================================================================================\n// ================================================================================\n// ================================================================================\n/// Preconditioned transport operator \\f$ D^{-1} T D\\f$\ntemplate <typename RT_TYPE, typename OP_T>\nclass PTransportOp_Base\n{\n private:\n  typedef RT_TYPE rt_t;\n  typedef typename rt_t::complex_array_t complex_array_t;\n  typedef OP_T op_t;\n  typedef typename rt_t::rt_coeff_t rt_coeff_t;\n\n public:\n  /**\n   *\n   * @param rt    ridgelet transform object\n   * @param aha   A^T A\n   * @param vx    velocity in x direction\n   * @param vy    velocity in y direction\n   */\n  PTransportOp_Base(const rt_t &rt, const op_t &aha, double vx, double vy)\n      : rt_(rt)\n      , aha_(aha)\n      , D_(make_inv_diagonal_preconditioner(rt.frame(), vx, vy))\n      , rt_coeffs_(rt.frame())\n  {\n    fi.resize(rt.frame().Ny(), rt.frame().Nx());\n    fo.resize(rt.frame().Ny(), rt.frame().Nx());\n\n    // prepare preconditioner\n    D_.invert();\n  }\n\n  void apply(RidgeletCellArray<rt_coeff_t> &dst, const RidgeletCellArray<rt_coeff_t> &src) const\n  {\n    // apply D_\n    D_.apply(rt_coeffs_, src);\n    rt_.irt(fi, rt_coeffs_.coeffs());\n    assert(!fi.hasNaN());\n    aha_.apply(fo, fi);\n    assert(!fo.hasNaN());\n    rt_.rt(dst.coeffs(), fo);\n    D_.apply(dst);\n  }\n\n private:\n  const rt_t &rt_;\n  const op_t &aha_;\n  DiagonalOperator<rt_coeff_t> D_;\n\n  mutable RidgeletCellArray<rt_coeff_t> rt_coeffs_;\n  mutable complex_array_t fi;\n  mutable complex_array_t fo;\n};\n\ntemplate <typename RT_TYPE = RT<>>\nusing PTransportOp = PTransportOp_Base<RT_TYPE, AhAOp>;\n\ntemplate <typename RT_TYPE = RT<>>\nusing PTransportOpBC = PTransportOp_Base<RT_TYPE, AhAOpsigma>;\n\n// ================================================================================\n/// Preconditioned transport operator \\f$ D^{-1} T D\\f$\ntemplate <typename RT_TYPE, typename OP_T>\nclass PTransportOp_BaseId\n{\n private:\n  typedef RT_TYPE rt_t;\n  typedef typename rt_t::complex_array_t complex_array_t;\n  typedef OP_T op_t;\n  typedef typename rt_t::rt_coeff_t rt_coeff_t;\n\n public:\n  /**\n   *\n   * @param rt    ridgelet transform object\n   * @param aha   A^T A\n   * @param vx    velocity in x direction\n   * @param vy    velocity in y direction\n   */\n  PTransportOp_BaseId(const rt_t &rt, const op_t &aha, double vx, double vy)\n      : rt_(rt)\n      , aha_(aha)\n  {\n    fi.resize(rt.frame().Ny(), rt.frame().Nx());\n    fo.resize(rt.frame().Ny(), rt.frame().Nx());\n  }\n\n  void apply(RidgeletCellArray<rt_coeff_t> &dst, const RidgeletCellArray<rt_coeff_t> &src) const\n  {\n    rt_.irt(fi, src.coeffs());\n    assert(!fi.hasNaN());\n    aha_.apply(fo, fi);\n    assert(!fo.hasNaN());\n    rt_.rt(dst.coeffs(), fo);\n  }\n\n private:\n  const rt_t &rt_;\n  const op_t &aha_;\n  mutable complex_array_t fi;\n  mutable complex_array_t fo;\n};\n\ntemplate <typename RT_TYPE = RT<>>\nusing PTransportOpId = PTransportOp_BaseId<RT_TYPE, AhAOp>;\n", "meta": {"hexsha": "bb7eb7a8b3beb917482002553b0dd1d931ed62e9", "size": 11875, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "operators/operators.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": "operators/operators.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": "operators/operators.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": 26.3303769401, "max_line_length": 96, "alphanum_fraction": 0.5651368421, "num_tokens": 3341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.47298031324322565}}
{"text": "/*\n * NormalVectorsFilter.cpp\n *\n *  Created on: May 05, 2015\n *      Author: Peter Fankhauser, Martin Wermelinger\n *   Institute: ETH Zurich, ANYbotics\n */\n\n#include <grid_map_filters/NormalVectorsFilter.hpp>\n\n#include <grid_map_core/grid_map_core.hpp>\n#include <pluginlib/class_list_macros.h>\n\n#include <Eigen/Dense>\n#include <stdexcept>\n\nusing namespace filters;\n\nnamespace grid_map {\n\ntemplate<typename T>\nNormalVectorsFilter<T>::NormalVectorsFilter()\n    : method_(Method::Raster),\n      estimationRadius_(0.0)\n{\n}\n\ntemplate<typename T>\nNormalVectorsFilter<T>::~NormalVectorsFilter()\n{\n}\n\ntemplate<typename T>\nbool NormalVectorsFilter<T>::configure()\n{\n  if (!FilterBase<T>::getParam(std::string(\"radius\"), estimationRadius_)) {\n    ROS_DEBUG(\"Normal vectors filter did not find parameter `radius`.\");\n    method_ = Method::Raster;\n  } else {\n    method_ = Method::Area;\n    if (estimationRadius_ < 0.0) {\n      ROS_ERROR(\"Normal vectors filter estimation radius must be greater than zero.\");\n      return false;\n    }\n    ROS_DEBUG(\"Normal vectors estimation radius = %f\", estimationRadius_);\n  }\n\n  std::string normalVectorPositiveAxis;\n  if (!FilterBase<T>::getParam(std::string(\"normal_vector_positive_axis\"), normalVectorPositiveAxis)) {\n    ROS_ERROR(\"Normal vectors filter did not find parameter `normal_vector_positive_axis`.\");\n    return false;\n  }\n  if (normalVectorPositiveAxis == \"z\") {\n    normalVectorPositiveAxis_ = Vector3::UnitZ();\n  } else if (normalVectorPositiveAxis == \"y\") {\n    normalVectorPositiveAxis_ = Vector3::UnitY();\n  } else if (normalVectorPositiveAxis == \"x\") {\n    normalVectorPositiveAxis_ = Vector3::UnitX();\n  } else {\n    ROS_ERROR(\"The normal vector positive axis '%s' is not valid.\", normalVectorPositiveAxis.c_str());\n    return false;\n  }\n\n  if (!FilterBase < T > ::getParam(std::string(\"input_layer\"), inputLayer_)) {\n    ROS_ERROR(\"Normal vectors filter did not find parameter `input_layer`.\");\n    return false;\n  }\n  ROS_DEBUG(\"Normal vectors filter input layer is = %s.\", inputLayer_.c_str());\n\n  if (!FilterBase < T > ::getParam(std::string(\"output_layers_prefix\"), outputLayersPrefix_)) {\n    ROS_ERROR(\"Normal vectors filter did not find parameter `output_layers_prefix`.\");\n    return false;\n  }\n  ROS_DEBUG(\"Normal vectors filter output_layer = %s.\", outputLayersPrefix_.c_str());\n\n  return true;\n}\n\ntemplate<typename T>\nbool NormalVectorsFilter<T>::update(const T& mapIn, T& mapOut)\n{\n  std::vector<std::string> normalVectorsLayers;\n  normalVectorsLayers.push_back(outputLayersPrefix_ + \"x\");\n  normalVectorsLayers.push_back(outputLayersPrefix_ + \"y\");\n  normalVectorsLayers.push_back(outputLayersPrefix_ + \"z\");\n\n  mapOut = mapIn;\n  for (const auto& layer : normalVectorsLayers) mapOut.add(layer);\n  switch (method_) {\n    case Method::Area:\n      computeWithArea(mapOut, inputLayer_, outputLayersPrefix_);\n      break;\n    case Method::Raster:\n      computeWithRaster(mapOut, inputLayer_, outputLayersPrefix_);\n      break;\n  }\n\n  return true;\n}\n\ntemplate<typename T>\nvoid NormalVectorsFilter<T>::computeWithArea(GridMap& map, const std::string& inputLayer, const std::string& outputLayersPrefix)\n{\n  // For each cell in requested area.\n  for (GridMapIterator iterator(map);\n      !iterator.isPastEnd(); ++iterator) {\n    // Check if this is an empty cell (hole in the map).\n    if (!map.isValid(*iterator, inputLayer_)) continue;\n\n    // Requested position (center) of circle in map.\n    Position center;\n    map.getPosition(*iterator, center);\n\n    // Prepare data computation.\n    const int maxNumberOfCells = pow(ceil(2 * estimationRadius_ / map.getResolution()), 2);\n    Eigen::MatrixXd points(3, maxNumberOfCells);\n\n    // Gather surrounding data.\n    size_t nPoints = 0;\n    for (CircleIterator iterator(map, center, estimationRadius_); !iterator.isPastEnd(); ++iterator) {\n      if (!map.isValid(*iterator, inputLayer_)) continue;\n      Position3 point;\n      map.getPosition3(inputLayer_, *iterator, point);\n      points.col(nPoints) = point;\n      nPoints++;\n    }\n    points.conservativeResize(3, nPoints); // TODO Eigen version?\n\n    // Compute Eigenvectors.\n    const Position3 mean = points.leftCols(nPoints).rowwise().sum() / nPoints;\n    const Eigen::MatrixXd NN = points.leftCols(nPoints).colwise() - mean;\n\n    const Eigen::Matrix3d covarianceMatrix(NN * NN.transpose());\n    Vector3 eigenvalues = Vector3::Ones();\n    Eigen::Matrix3d eigenvectors = Eigen::Matrix3d::Identity();\n    // Ensure that the matrix is suited for eigenvalues calculation.\n    if (covarianceMatrix.fullPivHouseholderQr().rank() >= 3) {\n      const Eigen::EigenSolver<Eigen::MatrixXd> solver(covarianceMatrix);\n      eigenvalues = solver.eigenvalues().real();\n      eigenvectors = solver.eigenvectors().real();\n    } else {\n      ROS_DEBUG(\"Covariance matrix needed for eigen decomposition is degenerated. Expected cause: no noise in data (nPoints = %i)\", (int) nPoints);\n      // Use z-axis as default surface normal. // TODO Make dependend on surfaceNormalPositiveAxis_;\n      eigenvalues.z() = 0.0;\n    }\n    // Keep the smallest Eigenvector as normal vector.\n    int smallestId(0);\n    double smallestValue(std::numeric_limits<double>::max());\n    for (int j = 0; j < eigenvectors.cols(); j++) {\n      if (eigenvalues(j) < smallestValue) {\n        smallestId = j;\n        smallestValue = eigenvalues(j);\n      }\n    }\n    Vector3 eigenvector = eigenvectors.col(smallestId);\n    if (eigenvector.dot(normalVectorPositiveAxis_) < 0.0) eigenvector = -eigenvector;\n    map.at(outputLayersPrefix_ + \"x\", *iterator) = eigenvector.x();\n    map.at(outputLayersPrefix_ + \"y\", *iterator) = eigenvector.y();\n    map.at(outputLayersPrefix_ + \"z\", *iterator) = eigenvector.z();\n  }\n}\n\ntemplate<typename T>\nvoid NormalVectorsFilter<T>::computeWithRaster(GridMap& map, const std::string& inputLayer, const std::string& outputLayersPrefix)\n{\n  throw std::runtime_error(\"NormalVectorsFilter::computeWithRaster() is not yet implemented!\");\n  // TODO: http://www.flipcode.com/archives/Calculating_Vertex_Normals_for_Height_Maps.shtml\n}\n\n} /* namespace */\n\nPLUGINLIB_EXPORT_CLASS(grid_map::NormalVectorsFilter<grid_map::GridMap>, filters::FilterBase<grid_map::GridMap>)\n", "meta": {"hexsha": "a3a367e1e3da395740bcc36b5ccfeb17550a46fa", "size": 6206, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "grid_map_filters/src/NormalVectorsFilter.cpp", "max_stars_repo_name": "jcmayoral/grid_map", "max_stars_repo_head_hexsha": "c4a16b71d40c2c6df8d60b1c91cd78616f9db672", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-09-11T02:32:16.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-28T10:59:20.000Z", "max_issues_repo_path": "grid_map_filters/src/NormalVectorsFilter.cpp", "max_issues_repo_name": "jcmayoral/grid_map", "max_issues_repo_head_hexsha": "c4a16b71d40c2c6df8d60b1c91cd78616f9db672", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "grid_map_filters/src/NormalVectorsFilter.cpp", "max_forks_repo_name": "jcmayoral/grid_map", "max_forks_repo_head_hexsha": "c4a16b71d40c2c6df8d60b1c91cd78616f9db672", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-07-05T17:48:18.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-11T07:55:44.000Z", "avg_line_length": 35.8728323699, "max_line_length": 147, "alphanum_fraction": 0.707863358, "num_tokens": 1534, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.47298031324322565}}
{"text": "// ========================================================================================\n//  ApproxMVBB\n//  Copyright (C) 2014 by Gabriel N\u00fctzi <nuetzig (at) imes (d0t) mavt (d0t) ethz\n//  (d\u00f8t) ch>\n//\n//  This Source Code Form is subject to the terms of the Mozilla Public\n//  License, v. 2.0. If a copy of the MPL was not distributed with this\n//  file, You can obtain one at http://mozilla.org/MPL/2.0/.\n// ========================================================================================\n\n#ifndef ApproxMVBB_Common_MyMatrixTypeDefs_hpp\n#define ApproxMVBB_Common_MyMatrixTypeDefs_hpp\n\n#include \"ApproxMVBB/Common/Platform.hpp\"\n\n//#define EIGEN_DONT_VECTORIZE\n//#define EIGEN_DISABLE_UNALIGNED_ARRAY_ASSERT\n\n#include <Eigen/Dense>\n\nnamespace ApproxMVBB\n{\n    // ================================================================================================\n    /*! @brief This\n     \tThese are some small matrix definitions.\n    */\n\n    namespace MyMatrix\n    {\n        template<typename Scalar>\n        using Matrix44 = Eigen::Matrix<Scalar, 4, 4>;\n        template<typename Scalar>\n        using Matrix43 = Eigen::Matrix<Scalar, 4, 3>;\n        template<typename Scalar>\n        using Matrix34 = Eigen::Matrix<Scalar, 3, 4>;\n        template<typename Scalar>\n        using Matrix33 = Eigen::Matrix<Scalar, 3, 3>;\n        template<typename Scalar>\n        using Matrix32 = Eigen::Matrix<Scalar, 3, 2>;\n        template<typename Scalar>\n        using Matrix23 = Eigen::Matrix<Scalar, 2, 3>;\n        template<typename Scalar>\n        using Matrix22 = Eigen::Matrix<Scalar, 2, 2>;\n        template<typename Scalar>\n        using Vector3 = Eigen::Matrix<Scalar, 3, 1>;\n        template<typename Scalar>\n        using Vector2 = Eigen::Matrix<Scalar, 2, 1>;\n\n        template<typename Scalar>\n        using Quaternion = Eigen::Quaternion<Scalar>;\n        template<typename Scalar>\n        using AngleAxis = Eigen::AngleAxis<Scalar>;\n\n        template<typename Scalar>\n        using Vector4 = Eigen::Matrix<Scalar, 4, 1>;\n        template<typename Scalar>\n        using Vector6 = Eigen::Matrix<Scalar, 6, 1>;\n        template<typename Scalar>\n        using VectorDyn = Eigen::Matrix<Scalar, Eigen::Dynamic, 1>;\n\n        template<typename Scalar>\n        using MatrixDynDyn = Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>;\n        template<typename Scalar>\n        using MatrixDiagDyn = Eigen::DiagonalMatrix<Scalar, Eigen::Dynamic>;\n        template<typename Scalar>\n        using MatrixDynDynRow = Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;\n\n        template<typename Scalar, int M>\n        using MatrixStatDyn = Eigen::Matrix<Scalar, M, Eigen::Dynamic>;\n        template<typename Scalar, int N>\n        using MatrixDynStat = Eigen::Matrix<Scalar, Eigen::Dynamic, N>;\n        template<typename Scalar, int M, int N>\n        using MatrixStatStat = Eigen::Matrix<Scalar, M, N>;\n        template<typename Scalar, int M>\n        using VectorStat = Eigen::Matrix<Scalar, M, 1>;\n\n        template<typename Scalar>\n        using AffineTrafo = Eigen::Transform<Scalar, 3, Eigen::TransformTraits::Affine>;\n        template<typename Scalar>\n        using AffineTrafo2d = Eigen::Transform<Scalar, 2, Eigen::TransformTraits::Affine>;\n\n        template<typename Scalar, int M>\n        using ArrayStatDyn = Eigen::Array<Scalar, M, Eigen::Dynamic>;\n        template<typename Scalar, int N>\n        using ArrayDynStat = Eigen::Array<Scalar, Eigen::Dynamic, N>;\n        template<typename Scalar, int M, int N>\n        using ArrayStatStat = Eigen::Array<Scalar, M, N>;\n        template<typename Scalar, int M>\n        using ArrayStat = Eigen::Array<Scalar, M, 1>;\n\n        template<typename Scalar>\n        using Array3 = Eigen::Array<Scalar, 3, 1>;\n        template<typename Scalar>\n        using Array2 = Eigen::Array<Scalar, 2, 1>;\n    }  // namespace MyMatrix\n\n    namespace MyMatrix\n    {\n        template<typename Derived>\n        using MatrixBase = Eigen::MatrixBase<Derived>;\n        template<typename Derived>\n        using ArrayBase = Eigen::ArrayBase<Derived>;\n\n        template<typename Derived>\n        using VectorBDyn = Eigen::VectorBlock<Derived, Eigen::Dynamic>;\n        template<typename Derived, int M>\n        using VectorBStat = Eigen::VectorBlock<Derived, M>;\n\n        template<typename Derived>\n        using MatrixBDynDyn = Eigen::Block<Derived>;\n        template<typename Derived, int M>\n        using MatrixBStatDyn = Eigen::Block<Derived, M, Eigen::Dynamic>;\n        template<typename Derived, int N>\n        using MatrixBDynStat = Eigen::Block<Derived, Eigen::Dynamic, N>;\n\n        template<typename EigenType>\n        using MatrixRef = Eigen::Ref<EigenType>;\n\n        template<typename EigenType>\n        using MatrixMap = Eigen::Map<EigenType>;\n    }  // namespace MyMatrix\n\n    struct APPROXMVBB_EXPORT MyMatrixIOFormat\n    {\n        static const Eigen::IOFormat Matlab;\n        static const Eigen::IOFormat CommaSep;\n        static const Eigen::IOFormat SpaceSep;\n    };\n}  // namespace ApproxMVBB\n\n#    define ApproxMVBB_DEFINE_MATRIX_SPECIALTYPES                                \\\n        template<typename Derived>                                               \\\n        using MatrixBase = ApproxMVBB::MyMatrix::MatrixBase<Derived>;            \\\n        template<typename Derived>                                               \\\n        using ArrayBase = ApproxMVBB::MyMatrix::ArrayBase<Derived>;              \\\n                                                                                 \\\n        template<typename Derived>                                               \\\n        using VectorBDyn = ApproxMVBB::MyMatrix::VectorBDyn<Derived>;            \\\n        template<typename Derived, int M>                                        \\\n        using VectorBStat = ApproxMVBB::MyMatrix::VectorBStat<Derived, M>;       \\\n                                                                                 \\\n        template<typename Derived>                                               \\\n        using MatrixBDynDyn = ApproxMVBB::MyMatrix::MatrixBDynDyn<Derived>;      \\\n        template<typename Derived, int N>                                        \\\n        using MatrixBDynStat = ApproxMVBB::MyMatrix::MatrixBDynStat<Derived, N>; \\\n        template<typename Derived, int M>                                        \\\n        using MatrixBStatDyn = ApproxMVBB::MyMatrix::MatrixBStatDyn<Derived, M>; \\\n                                                                                 \\\n        template<typename EigenType>                                             \\\n        using MatrixRef = ApproxMVBB::MyMatrix::MatrixRef<EigenType>;            \\\n        template<typename EigenType>                                             \\\n        using MatrixMap = ApproxMVBB::MyMatrix::MatrixMap<EigenType>\n\n/**\n     * @brief This macro is used to typedef all custom matrix types which have\n     * nothing to do with the system.\n     */\n#    define ApproxMVBB_DEFINE_MATRIX_TYPES_OF(_PREC_)                              \\\n        using Matrix44        = ApproxMVBB::MyMatrix::Matrix44<_PREC_>;            \\\n        using Matrix33        = ApproxMVBB::MyMatrix::Matrix33<_PREC_>;            \\\n        using Matrix22        = ApproxMVBB::MyMatrix::Matrix22<_PREC_>;            \\\n        using Matrix32        = ApproxMVBB::MyMatrix::Matrix32<_PREC_>;            \\\n        using Matrix23        = ApproxMVBB::MyMatrix::Matrix23<_PREC_>;            \\\n        using Matrix43        = ApproxMVBB::MyMatrix::Matrix43<_PREC_>;            \\\n        using Matrix34        = ApproxMVBB::MyMatrix::Matrix34<_PREC_>;            \\\n        using Vector3         = ApproxMVBB::MyMatrix::Vector3<_PREC_>;             \\\n        using Vector2         = ApproxMVBB::MyMatrix::Vector2<_PREC_>;             \\\n        using Vector4         = ApproxMVBB::MyMatrix::Vector4<_PREC_>;             \\\n        using Vector6         = ApproxMVBB::MyMatrix::Vector6<_PREC_>;             \\\n        using Quaternion      = ApproxMVBB::MyMatrix::Quaternion<_PREC_>;          \\\n        using AngleAxis       = ApproxMVBB::MyMatrix::AngleAxis<_PREC_>;           \\\n        using VectorDyn       = ApproxMVBB::MyMatrix::VectorDyn<_PREC_>;           \\\n        using MatrixDynDyn    = ApproxMVBB::MyMatrix::MatrixDynDyn<_PREC_>;        \\\n        using MatrixDiagDyn   = ApproxMVBB::MyMatrix::MatrixDiagDyn<_PREC_>;       \\\n        using MatrixDynDynRow = ApproxMVBB::MyMatrix::MatrixDynDynRow<_PREC_>;     \\\n                                                                                   \\\n        template<int M>                                                            \\\n        using MatrixStatDyn = ApproxMVBB::MyMatrix::MatrixStatDyn<_PREC_, M>;      \\\n        template<int N>                                                            \\\n        using MatrixDynStat = ApproxMVBB::MyMatrix::MatrixDynStat<_PREC_, N>;      \\\n        template<int M, int N>                                                     \\\n        using MatrixStatStat = ApproxMVBB::MyMatrix::MatrixStatStat<_PREC_, M, N>; \\\n        template<int M>                                                            \\\n        using VectorStat = ApproxMVBB::MyMatrix::VectorStat<_PREC_, M>;            \\\n                                                                                   \\\n        using AffineTrafo   = ApproxMVBB::MyMatrix::AffineTrafo<_PREC_>;           \\\n        using AffineTrafo2d = ApproxMVBB::MyMatrix::AffineTrafo2d<_PREC_>;         \\\n                                                                                   \\\n        template<int M>                                                            \\\n        using ArrayStatDyn = ApproxMVBB::MyMatrix::ArrayStatDyn<_PREC_, M>;        \\\n        template<int N>                                                            \\\n        using ArrayDynStat = ApproxMVBB::MyMatrix::ArrayDynStat<_PREC_, N>;        \\\n        template<int M, int N>                                                     \\\n        using ArrayStatStat = ApproxMVBB::MyMatrix::ArrayStatStat<_PREC_, M, N>;   \\\n        template<int M>                                                            \\\n        using ArrayStat = ApproxMVBB::MyMatrix::ArrayStat<_PREC_, M>;              \\\n        using Array3    = ApproxMVBB::MyMatrix::Array3<_PREC_>;                    \\\n        using Array2    = ApproxMVBB::MyMatrix::Array2<_PREC_>;                    \\\n                                                                                   \\\n        ApproxMVBB_DEFINE_MATRIX_SPECIALTYPES\n\n#endif\n", "meta": {"hexsha": "7f38ba9d4c8c9a34db370d4ea2eed9594ac156d0", "size": 10623, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "LetsGo/ThirdParty/ApproxMVBB/Includes/ApproxMVBB/Common/MyMatrixTypeDefs.hpp", "max_stars_repo_name": "wis1906/letsgo-ar-space-generation", "max_stars_repo_head_hexsha": "02d888a44bb9eb112f308356ab42720529349338", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "LetsGo/ThirdParty/ApproxMVBB/Includes/ApproxMVBB/Common/MyMatrixTypeDefs.hpp", "max_issues_repo_name": "wis1906/letsgo-ar-space-generation", "max_issues_repo_head_hexsha": "02d888a44bb9eb112f308356ab42720529349338", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LetsGo/ThirdParty/ApproxMVBB/Includes/ApproxMVBB/Common/MyMatrixTypeDefs.hpp", "max_forks_repo_name": "wis1906/letsgo-ar-space-generation", "max_forks_repo_head_hexsha": "02d888a44bb9eb112f308356ab42720529349338", "max_forks_repo_licenses": ["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.3300492611, "max_line_length": 103, "alphanum_fraction": 0.5232043679, "num_tokens": 2191, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028205, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4729760098776326}}
{"text": "#pragma once\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <cmath>\n#include <iostream>\n#include <limits>\n\n#define DBG_MACRO_NO_WARNING\n#include <dbg.h>\n\nnamespace addn {\nstruct DN {\n  double v;\n  double a;\n\n  DN(double _v, double _a) : v(_v), a(_a) {}\n  DN(double _v) : DN(_v, 0.0) {}\n  DN(const DN& x) : DN(x.v, x.a) {}\n  DN() : DN(0.0, 0.0) {}\n  inline DN& operator=(const DN& x) {\n    v = x.v;\n    a = x.a;\n    return *this;\n  }\n\n  inline DN& operator=(const double x) {\n    v = x;\n    a = 0;\n    return *this;\n  }\n\n  inline DN& operator+=(const DN& x) {\n    v += x.v;\n    a += x.a;\n    return *this;\n  }\n\n  inline DN& operator/=(const DN& x) {\n    a = (a * x.v - x.a * v) / std::pow(x.v, 2.0);\n    v /= x.v;\n    return *this;\n  }\n\n  operator double() const { return v; }\n};\n\ninline std::ostream& operator<<(std::ostream& out, const DN& n) {\n  out << \"(\" << n.v << \", \" << n.a << \")\";\n  return out;\n}\n\ninline DN operator-(const DN& x) { return DN{-x.v, -x.a}; }\ninline DN operator+(const DN& x, const DN& y) { return DN{x.v + y.v, x.a + y.a}; }\ninline DN operator-(const DN& x, const DN& y) { return DN{x.v - y.v, x.a - y.a}; }\ninline DN operator*(const DN& x, const DN& y) { return DN{x.v * y.v, x.a * y.v + y.a * x.v}; }\ninline DN operator/(const DN& x, const DN& y) {\n  return DN{x.v / y.v, (x.a * y.v - y.a * x.v) / std::pow(y.v, 2.0)};\n}\n\ninline bool operator==(const DN& x, const DN& y) { return x.v == y.v && x.a == y.a; }\ninline bool operator==(const DN& x, const double y) { return x.v == y && x.a == 0.0; }\ninline bool operator==(const double x, const DN& y) { return x == y.v && 0.0 == y.a; }\ninline bool operator!=(const DN& x, const DN& y) { return x.v != y.v || x.a != y.a; }\ninline bool operator!=(const DN& x, const double y) { return x.v != y || x.a != 0.0; }\ninline bool operator!=(const double x, const DN& y) { return x != y.v || 0.0 != y.a; }\ninline bool operator<(const DN& x, const DN& y) { return x.v < y.v; }\ninline bool operator<(const DN& x, const double y) { return x.v < y; }\ninline bool operator<(const double x, const DN& y) { return x < y; }\ninline bool operator>(const DN& x, const DN& y) { return x.v > y.v; }\ninline bool operator>(const DN& x, const double y) { return x.v > y; }\ninline bool operator>(const double x, const DN& y) { return x > y.v; }\ninline bool operator<=(const DN& x, const DN& y) { return x.v <= y.v; }\ninline bool operator<=(const DN& x, const double y) { return x.v <= y; }\ninline bool operator<=(const double x, const DN& y) { return x <= y.v; }\ninline bool operator>=(const DN& x, const DN& y) { return x.v >= y.v; }\ninline bool operator>=(const DN& x, const double y) { return x.v >= y; }\ninline bool operator>=(const double x, const DN& y) { return x >= y.v; }\n\ninline DN pow(const DN& x, const DN& y) {\n  const auto powv = std::pow(x.v, y.v);\n  return DN{powv, powv * (std::log(x.v) * y.a + y.v / x.v * x.a)};\n}\n\ninline DN pow(const DN& x, const double y) {\n  return DN{std::pow(x.v, y), y * std::pow(x.v, y - 1.0) * x.a};\n}\n\ninline DN pow(const double x, const DN& y) {\n  const auto powv = std::pow(x, y.v);\n  return DN{powv, powv * std::log(x) * y.a};\n}\n\ninline DN sin(const DN& x) { return DN{std::sin(x.v), x.a * std::cos(x.v)}; }\ninline DN cos(const DN& x) { return DN{std::cos(x.v), -x.a * std::sin(x.v)}; }\ninline DN tan(const DN& x) {\n  const auto tanv = std::tan(x.v);\n  return DN{tanv, x.a * (1 + std::pow(tanv, 2.0))};\n}\n\ninline DN asin(const DN& x) { return DN{std::asin(x.v), x.a / std::sqrt(1 - std::pow(x.v, 2.0))}; }\n\ninline DN acos(const DN& x) {\n  return DN{std::acos(x.v), -x.a / std::sqrt(1 - std::pow(x.v, 2.0))};\n}\n\ninline DN atan(const DN& x) {\n  return DN{std::atan(x.v), x.a * (1 - std::pow(std::tanh(x.v), 2.0))};\n}\n\ninline DN atan2(const DN& y, const DN& x) {\n  const DN q = y / x;\n  return DN{std::atan2(y.v, x.v), q.a * (1 - std::pow(std::tanh(q.v), 2.0))};\n}\n\ninline DN atan2(const DN& y, const double x) {\n  return DN{std::atan2(y.v, x), y.a * (1 - std::pow(std::tanh(y.v / x), 2.0))};\n}\n\ninline DN atan2(const double x, const DN& y) { return atan2(y, x); }\n\ninline DN exp(const DN& x) { return DN{std::exp(x.v), x.a * std::exp(x.v)}; }\ninline DN log(const DN& x) { return DN{std::log(x.v), x.a / x.v}; }\ninline DN sqrt(const DN& x) {\n  const double v_sqrt = std::sqrt(x.v);\n  const double denom  = 2 * v_sqrt;\n  return DN{v_sqrt, denom == 0 ? 0.0 : x.a / denom};\n}\n\ninline DN abs(const DN& x) { return DN{std::fabs(x.v), std::copysign(x.a, x.v)}; }\ninline DN abs2(const DN& x) { return x * x; }\ninline DN min(const DN& x, const DN& y) {\n  if (std::max(std::fabs(x.v), std::fabs(y.v)) == std::numeric_limits<double>::infinity()) {\n    return x <= y ? x : y;\n  }\n\n  const auto z = x >= y ? 1.0 : 0.0;\n  return DN{z * y.v + (1.0 - z) * x.v, z * y.a + (1.0 - z) * x.a};\n}\n\ninline DN max(const DN& x, const DN& y) {\n  if (std::max(std::fabs(x.v), std::fabs(y.v)) == std::numeric_limits<double>::infinity()) {\n    return x >= y ? x : y;\n  }\n\n  const auto z = y >= x ? 1.0 : 0.0;\n  return DN{z * y.v + (1.0 - z) * x.v, z * y.a + (1.0 - z) * x.a};\n}\n\ninline DN operator+(const DN& x, const double y) { return DN{x.v + y, x.a}; }\ninline DN operator+(const double x, const DN& y) { return DN{x + y.v, y.a}; }\ninline DN operator-(const DN& x, const double y) { return DN{x.v - y, x.a}; }\ninline DN operator-(const double x, const DN& y) { return DN{x - y.v, -y.a}; }\ninline DN operator*(const DN& x, const double y) { return DN{x.v * y, x.a * y}; }\ninline DN operator*(const double x, const DN& y) { return DN{x * y.v, y.a * x}; }\ninline DN operator/(const DN& x, const double y) {\n  return DN{x.v / y, (x.a * y) / std::pow(y, 2.0)};\n}\n\ninline DN operator/(const double x, const DN& y) {\n  return DN{x / y.v, (-y.a * x) / std::pow(y.v, 2.0)};\n}\n\ninline DN ceil(const DN& x) { return DN{std::ceil(x.v), 0.0}; }\ninline DN floor(const DN& x) { return DN{std::floor(x.v), 0.0}; }\n\ninline DN cosh(const DN& x) { return DN{std::cosh(x.v), x.a * std::sinh(x.v)}; }\ninline DN sinh(const DN& x) { return DN{std::sinh(x.v), x.a * std::cosh(x.v)}; }\ninline DN tanh(const DN& x) {\n  return DN{std::tanh(x.v), x.a * (1.0 - std::pow(std::tanh(x.v), 2))};\n}\n}  // namespace addn\n\nnamespace Eigen {\ntemplate <> struct NumTraits<addn::DN> : NumTraits<double> {\n  using Real       = addn::DN;\n  using NonInteger = addn::DN;\n  using Literal    = addn::DN;\n  using Nested     = addn::DN;\n\n  enum {\n    IsComplex             = 0,\n    IsInteger             = 0,\n    IsSigned              = 1,\n    RequireInitialization = 1,\n    ReadCost              = 1,\n    AddCost               = 2,\n    MulCost               = 4\n  };\n};\n}  // namespace Eigen\n", "meta": {"hexsha": "bd733b9c35c85b51cfe3fb6bd1d0dcaee9ab803b", "size": 6621, "ext": "hh", "lang": "C++", "max_stars_repo_path": "common/autodiff.hh", "max_stars_repo_name": "MiaoDragon/planet", "max_stars_repo_head_hexsha": "54238a892ddf78ac3327665f4c6859681c6d4142", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2020-10-11T08:23:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T10:23:55.000Z", "max_issues_repo_path": "common/autodiff.hh", "max_issues_repo_name": "MiaoDragon/planet", "max_issues_repo_head_hexsha": "54238a892ddf78ac3327665f4c6859681c6d4142", "max_issues_repo_licenses": ["MIT"], "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/autodiff.hh", "max_forks_repo_name": "MiaoDragon/planet", "max_forks_repo_head_hexsha": "54238a892ddf78ac3327665f4c6859681c6d4142", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-06-17T21:03:46.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-17T21:03:46.000Z", "avg_line_length": 34.664921466, "max_line_length": 99, "alphanum_fraction": 0.5653224588, "num_tokens": 2338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.47293824042004434}}
{"text": "/**\n * @file solver_builder.hpp\n * @author Fran\u00e7ois Hamonic (francois.hamonic@gmail.com)\n * @brief OSI_Builder class declaration\n * @version 0.1\n * @date 2020-10-27\n *\n * @copyright Copyright (c) 2020\n */\n#ifndef SOLVER_BUILDER_HPP\n#define SOLVER_BUILDER_HPP\n\n#include <cmath>\n#include <functional>\n#include <memory>\n#include <numeric>\n#include <string>\n#include <vector>\n\n#include <boost/iterator/zip_iterator.hpp>\n#include <boost/range/algorithm.hpp>\n#include <boost/range/combine.hpp>\n\n#include <range/v3/all.hpp>\n\nnamespace SolverBuilder_Utils {\nenum InequalitySense { LESS = -1, EQUAL = 0, GREATER = 1 };\nenum OptimizationSense { MIN = -1, MAX = 1 };\nconstexpr double INFTY = std::numeric_limits<double>::max();\n\nclass LinearExpression {\nprivate:\n    double _constant;\n    std::vector<int> _indices;\n    std::vector<double> _coefficients;\n\npublic:\n    LinearExpression() : _constant{0} {}\n\n    void add(double c) { _constant += c; }\n    void add(int id, double coef = 1) {\n        _indices.push_back(id);\n        _coefficients.push_back(coef);\n    }\n\n    double getConstant() const { return _constant; }\n    int getNbTerms() const { return _indices.size(); }\n    int * getIndicesData() { return _indices.data(); }\n    double * getCoefficientsData() { return _coefficients.data(); }\n    const std::vector<int> & getIndices() const { return _indices; }\n    const std::vector<double> & getCoefficients() const {\n        return _coefficients;\n    }\n\n    LinearExpression & simplify() {\n        auto zip_view = ranges::view::zip(_indices, _coefficients);\n        ranges::sort(zip_view,\n                     [](auto p1, auto p2) { return p1.first < p2.first; });\n\n        const auto begin = zip_view.begin();\n        auto first = begin;\n        const auto end = zip_view.end();\n        for(auto next = first + 1; next != end; ++next) {\n            if((*first).first != (*next).first) {\n                if((*first).second != 0.0) ++first;\n                *first = *next;\n                continue;\n            }\n            (*first).second += (*next).second;\n        }\n        const std::size_t new_length = std::distance(begin, first + 1);\n        _indices.resize(new_length);\n        _coefficients.resize(new_length);\n        return *this;\n    }\n};\n\nstruct linear_ineq_constraint {\n    InequalitySense sense;\n    LinearExpression linear_expression;\n    linear_ineq_constraint() = default;\n};\n\nclass linear_ineq_constraint_rhs_easy_init {\nprivate:\n    linear_ineq_constraint constraint_data;\n\npublic:\n    linear_ineq_constraint_rhs_easy_init(linear_ineq_constraint && data)\n        : constraint_data(std::move(data)) {}\n    linear_ineq_constraint_rhs_easy_init & operator()(double c) {\n        constraint_data.linear_expression.add(-c);\n        return *this;\n    }\n    linear_ineq_constraint_rhs_easy_init & operator()(int id, double coef = 1) {\n        constraint_data.linear_expression.add(id, -coef);\n        return *this;\n    }\n};\n\nclass linear_ineq_constraint_lhs_easy_init {\nprivate:\n    linear_ineq_constraint constraint_data;\n\npublic:\n    linear_ineq_constraint_lhs_easy_init() {}\n    linear_ineq_constraint_lhs_easy_init & operator()(double c) {\n        constraint_data.linear_expression.add(c);\n        return *this;\n    }\n    linear_ineq_constraint_lhs_easy_init & operator()(int id, double coef = 1) {\n        constraint_data.linear_expression.add(id, coef);\n        return *this;\n    }\n\n    linear_ineq_constraint_rhs_easy_init less() {\n        constraint_data.sense = LESS;\n        return linear_ineq_constraint_rhs_easy_init(std::move(constraint_data));\n    }\n    linear_ineq_constraint_rhs_easy_init equal() {\n        constraint_data.sense = EQUAL;\n        return linear_ineq_constraint_rhs_easy_init(std::move(constraint_data));\n    }\n    linear_ineq_constraint_rhs_easy_init greater() {\n        constraint_data.sense = GREATER;\n        return linear_ineq_constraint_rhs_easy_init(std::move(constraint_data));\n    }\n};\n\nstruct linear_range_constraint {\n    double lower_bound, upper_bound;\n    LinearExpression linear_expression;\n    linear_range_constraint()\n        : lower_bound{std::numeric_limits<double>::min()}\n        , upper_bound{std::numeric_limits<double>::max()} {}\n};\n\nclass linear_range_constraint_lhs_easy_init {\nprivate:\n    linear_range_constraint constraint_data;\n\npublic:\n    linear_range_constraint_lhs_easy_init() {}\n    linear_range_constraint_lhs_easy_init & lower(double c) {\n        constraint_data.lower_bound = c;\n        return *this;\n    }\n    linear_range_constraint_lhs_easy_init & upper(double c) {\n        constraint_data.upper_bound = c;\n        return *this;\n    }\n    linear_range_constraint_lhs_easy_init & operator()(int id,\n                                                       double coef = 1) {\n        constraint_data.linear_expression.add(id, coef);\n        return *this;\n    }\n\n    linear_range_constraint take_data() { return std::move(constraint_data); }\n};\n\nclass QuadraticExpression {\nprivate:\n    LinearExpression _linear_expression;\n    std::vector<int> _quad_indices_1;\n    std::vector<int> _quad_indices_2;\n    std::vector<double> quad_coefficients;\n\npublic:\n    void add(double c) { _linear_expression.add(c); }\n    void add(int id, double coef = 1) { _linear_expression.add(id, coef); }\n    void add(int id_1, int id_2, double coef = 1) {\n        _quad_indices_1.push_back(id_1);\n        _quad_indices_2.push_back(id_2);\n        quad_coefficients.push_back(coef);\n    }\n\n    const LinearExpression & getLineraExpression() const {\n        return _linear_expression;\n    }\n\n    double getConstant() const { return _linear_expression.getConstant(); }\n\n    int getNbLinearTerms() const { return _linear_expression.getNbTerms(); }\n    int * getLinearIndicesData() { return _linear_expression.getIndicesData(); }\n    double * getLinearCoefficientsData() {\n        return _linear_expression.getCoefficientsData();\n    }\n    const std::vector<int> & getLinearIndices() const {\n        return _linear_expression.getIndices();\n    }\n    const std::vector<double> & getLinearCoefficients() const {\n        return _linear_expression.getCoefficients();\n    }\n\n    int getNbQuadTerms() const { return _quad_indices_1.size(); }\n    int * getQuadIndices1Data() { return _quad_indices_1.data(); }\n    int * getQuadIndices2Data() { return _quad_indices_2.data(); }\n    double * getQuadCoefficientsData() { return quad_coefficients.data(); }\n    const std::vector<int> & getQuadIndices1() const { return _quad_indices_1; }\n    const std::vector<int> & getQuadIndices2() const { return _quad_indices_2; }\n    const std::vector<double> & getQuadCoefficients() const {\n        return quad_coefficients;\n    }\n\n    bool isLinear() const { return _quad_indices_1.empty(); }\n\n    QuadraticExpression & simplify() {\n        _linear_expression.simplify();\n        return *this;\n    }\n};\n\nstruct quadratic_ineq_constraint {\n    InequalitySense sense;\n    QuadraticExpression quadratic_expression;\n    quadratic_ineq_constraint() = default;\n};\n\nclass quadratic_ineq_constraint_rhs_easy_init {\nprivate:\n    quadratic_ineq_constraint constraint_data;\n\npublic:\n    quadratic_ineq_constraint_rhs_easy_init(quadratic_ineq_constraint && data)\n        : constraint_data(std::move(data)) {}\n    quadratic_ineq_constraint_rhs_easy_init & operator()(double c) {\n        constraint_data.quadratic_expression.add(-c);\n        return *this;\n    }\n    quadratic_ineq_constraint_rhs_easy_init & operator()(int id,\n                                                         double coef = 1) {\n        constraint_data.quadratic_expression.add(id, -coef);\n        return *this;\n    }\n    quadratic_ineq_constraint_rhs_easy_init & operator()(int id_1, int id_2,\n                                                         double coef = 1) {\n        constraint_data.quadratic_expression.add(id_1, id_2, -coef);\n        return *this;\n    }\n\n    quadratic_ineq_constraint take_data() { return std::move(constraint_data); }\n};\n\nclass quadratic_ineq_constraint_lhs_easy_init {\nprivate:\n    quadratic_ineq_constraint constraint_data;\n\npublic:\n    quadratic_ineq_constraint_lhs_easy_init() {}\n    quadratic_ineq_constraint_lhs_easy_init & operator()(double c) {\n        constraint_data.quadratic_expression.add(c);\n        return *this;\n    }\n    quadratic_ineq_constraint_lhs_easy_init & operator()(int id,\n                                                         double coef = 1) {\n        constraint_data.quadratic_expression.add(id, coef);\n        return *this;\n    }\n    quadratic_ineq_constraint_lhs_easy_init & operator()(int id_1, int id_2,\n                                                         double coef = 1) {\n        constraint_data.quadratic_expression.add(id_1, id_2, coef);\n        return *this;\n    }\n\n    quadratic_ineq_constraint_rhs_easy_init less() {\n        constraint_data.sense = LESS;\n        return quadratic_ineq_constraint_rhs_easy_init(\n            std::move(constraint_data));\n    }\n    quadratic_ineq_constraint_rhs_easy_init equal() {\n        constraint_data.sense = EQUAL;\n        return quadratic_ineq_constraint_rhs_easy_init(\n            std::move(constraint_data));\n    }\n    quadratic_ineq_constraint_rhs_easy_init greater() {\n        constraint_data.sense = GREATER;\n        return quadratic_ineq_constraint_rhs_easy_init(\n            std::move(constraint_data));\n    }\n};\n\n}  // namespace SolverBuilder_Utils\n\n// using namespace SolverBuilder_Utils;\n\n// /**\n//  * @brief A practical class for building OsiSolver instances\n//  */\n// class SolverBuilder {\n//     public:\n//         class VarType {\n//             protected:\n//                 int begin_id;\n//                 int end_id;\n//                 double _default_lb;\n//                 double _default_ub;\n//                 bool _integer;\n//                 VarType(int number, double lb=0, double ub=INFTY, bool\n//                 integer=false) : begin_id(0), end_id(number),\n//                 _default_lb(lb), _default_ub(ub), _integer(integer) {}\n//                 VarType() : VarType(0) {}\n//             public:\n//                 void offsetIds(int offset) { begin_id += offset; end_id+=\n//                 offset; } int getNumber() const { return end_id - begin_id; }\n//                 double getDefaultLB() { return _default_lb; }\n//                 double getDefaultUB() { return _default_ub; }\n//                 bool isInteger() { return _integer; }\n//         };\n//     private:\n//         int nb_vars;\n//         std::vector<VarType*> varTypes;\n\n//         std::unique_ptr<double[]> objective;\n//         std::unique_ptr<double[]> col_lb;\n//         std::unique_ptr<double[]> col_ub;\n//         std::unique_ptr<std::string[]> col_names;\n\n//         std::vector<int> starts;\n//         std::vector<int> indices;\n//         std::vector<double> coefficients;\n\n//         std::vector<double> row_lb;\n//         std::vector<double> row_ub;\n\n//         std::vector<int> integers_variables;\n//     public:\n//         // OSI_Builder();\n//         // ~OSI_Builder();\n\n//         // OSI_Builder & addVarType(VarType * var_type);\n//         // void init();\n//         // OSI_Builder & setObjective(int  var_id, double coef);\n//         // OSI_Builder & setBounds(int  var_id, double lb, double ub);\n//         // OSI_Builder & buffEntry(int  var_id, double coef);\n//         // OSI_Builder & popEntryBuffer();\n//         // OSI_Builder & clearEntryBuffer();\n//         // OSI_Builder & pushRowWithoutClearing(double lb, double ub);\n//         // OSI_Builder & pushRow(double lb, double ub);\n//         // OSI_Builder & setColName(int var_id, std::string name);\n\n//         // OSI_Builder & setContinuous(int var_id);\n//         // OSI_Builder & setInteger(int var_id);\n\n//         template <class OsiSolver>\n//         OsiSolver * buildSolver(int sense, bool relaxed=false) {\n//             OsiSolver * solver = new OsiSolver();\n//             solver->loadProblem(*matrix, col_lb, col_ub, objective,\n//             row_lb.data(), row_ub.data()); solver->setObjSense(sense);\n//             if(relaxed)\n//                 return solver;\n//             for(int i : integers_variables)\n//                 solver->setInteger(i);\n//             solver->setColNames(colNames, 0, nb_vars, 0);\n//             return solver;\n//         }\n\n//         static int nb_pairs(int n) {\n//             return n*(n-1)/2;\n//         };\n//         static int nb_couples(int n) {\n//             return 2*nb_pairs(n);\n//         };\n\n//         static int compose_pair(int i, int j) {\n//             assert(i != j);\n//             if(i > j) std::swap(i,j);\n//             return nb_pairs(j)+i;\n//         };\n//         static std::pair<int,int> retrieve_pair(int id) {\n//             const int j = std::round(std::sqrt(2*id+1));\n//             const int i = id - nb_pairs(j);\n//             return std::make_pair(i,j);\n//         };\n//         static int compose_couple(int i, int j) {\n//             return 2*compose_pair(i, j) + (i < j ? 0 : 1);\n//         };\n//         static std::pair<int,int> retrieve_couple(int id) {\n//             std::pair<int,int> p = retrieve_pair(id / 2);\n//             if(id % 2 == 1) std::swap(p.first, p.second);\n//             return p;\n//         };\n\n//         const std::vector<VarType*> & getVarTypes() { return varTypes; }\n\n//         int getNbVars() const { return nb_vars; };\n\n//         int getNbNonZeroVars() const {\n//             std::vector<int> non_zero(nb_vars, 0);\n//             const int * indices = matrix->getIndices();\n//             for(int i=0; i<matrix->getNumElements(); ++i)\n//                 non_zero[indices[i]] = 1;\n//             return std::accumulate(non_zero.begin(), non_zero.end(), 0);\n//         };\n//         int getNbConstraints() const { return matrix->getNumRows(); };\n\n//         int getNbElems() const { return nb_entries; };\n\n//         double * getObjective() { return objective; }\n//         CoinPackedMatrix * getMatrix() { return matrix; }\n\n//         double * getColLB() { return col_lb; }\n//         double * getColUB() { return col_ub; }\n\n//         double * getRowLB() { return row_lb.data(); }\n//         double * getRowUB() { return row_ub.data(); }\n// };\n\n#endif  // OSICLPSOLVER_BUILDER_HPP", "meta": {"hexsha": "0ee83b8714381c4bda511392469450c8f68ba929", "size": 14175, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/utils/solver_builder.hpp", "max_stars_repo_name": "fhamonic/landscape_opt", "max_stars_repo_head_hexsha": "7f32749336590c8d8b5875300228196a05137267", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-23T11:56:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-23T11:56:09.000Z", "max_issues_repo_path": "include/utils/solver_builder.hpp", "max_issues_repo_name": "fhamonic/landscape_opt", "max_issues_repo_head_hexsha": "7f32749336590c8d8b5875300228196a05137267", "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/utils/solver_builder.hpp", "max_forks_repo_name": "fhamonic/landscape_opt", "max_forks_repo_head_hexsha": "7f32749336590c8d8b5875300228196a05137267", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-27T16:58:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T16:58:19.000Z", "avg_line_length": 34.7426470588, "max_line_length": 80, "alphanum_fraction": 0.6155202822, "num_tokens": 3307, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.734119526900183, "lm_q2_score": 0.6442251133170356, "lm_q1q2_score": 0.47293823540551894}}
{"text": "/*\n * Copyright Nick Thompson, 2018\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_QUADRATURE_NAIVE_MONTE_CARLO_HPP\n#define BOOST_MATH_QUADRATURE_NAIVE_MONTE_CARLO_HPP\n#include <sstream>\n#include <algorithm>\n#include <vector>\n#include <atomic>\n#include <memory>\n#include <functional>\n#include <future>\n#include <thread>\n#include <initializer_list>\n#include <utility>\n#include <random>\n#include <chrono>\n#include <map>\n#include <type_traits>\n#include <boost/math/policies/error_handling.hpp>\n\nnamespace boost { namespace math { namespace quadrature {\n\nnamespace detail {\n  enum class limit_classification {FINITE,\n                                   LOWER_BOUND_INFINITE,\n                                   UPPER_BOUND_INFINITE,\n                                   DOUBLE_INFINITE};\n}\n\ntemplate<class Real, class F, class RandomNumberGenerator = std::mt19937_64, class Policy = boost::math::policies::policy<>,\n         typename std::enable_if<std::is_trivially_copyable<Real>::value, bool>::type = true>\nclass naive_monte_carlo\n{\npublic:\n    naive_monte_carlo(const F& integrand,\n                      std::vector<std::pair<Real, Real>> const & bounds,\n                      Real error_goal,\n                      bool singular = true,\n                      uint64_t threads = std::thread::hardware_concurrency(),\n                      uint64_t seed = 0) noexcept : m_num_threads{threads}, m_seed{seed}\n    {\n        using std::numeric_limits;\n        using std::sqrt;\n        uint64_t n = bounds.size();\n        m_lbs.resize(n);\n        m_dxs.resize(n);\n        m_limit_types.resize(n);\n        m_volume = 1;\n        static const char* function = \"boost::math::quadrature::naive_monte_carlo<%1%>\";\n        for (uint64_t i = 0; i < n; ++i)\n        {\n            if (bounds[i].second <= bounds[i].first)\n            {\n                boost::math::policies::raise_domain_error(function, \"The upper bound is <= the lower bound.\\n\", bounds[i].second, Policy());\n                return;\n            }\n            if (bounds[i].first == -numeric_limits<Real>::infinity())\n            {\n                if (bounds[i].second == numeric_limits<Real>::infinity())\n                {\n                    m_limit_types[i] = detail::limit_classification::DOUBLE_INFINITE;\n                }\n                else\n                {\n                    m_limit_types[i] = detail::limit_classification::LOWER_BOUND_INFINITE;\n                    // Ok ok this is bad to use the second bound as the lower limit and then reflect.\n                    m_lbs[i] = bounds[i].second;\n                    m_dxs[i] = numeric_limits<Real>::quiet_NaN();\n                }\n            }\n            else if (bounds[i].second == numeric_limits<Real>::infinity())\n            {\n                m_limit_types[i] = detail::limit_classification::UPPER_BOUND_INFINITE;\n                if (singular)\n                {\n                    // I've found that it's easier to sample on a closed set and perturb the boundary\n                    // than to try to sample very close to the boundary.\n                    m_lbs[i] = std::nextafter(bounds[i].first, (std::numeric_limits<Real>::max)());\n                }\n                else\n                {\n                    m_lbs[i] = bounds[i].first;\n                }\n                m_dxs[i] = numeric_limits<Real>::quiet_NaN();\n            }\n            else\n            {\n                m_limit_types[i] = detail::limit_classification::FINITE;\n                if (singular)\n                {\n                    if (bounds[i].first == 0)\n                    {\n                        m_lbs[i] = std::numeric_limits<Real>::epsilon();\n                    }\n                    else\n                    {\n                        m_lbs[i] = std::nextafter(bounds[i].first, (std::numeric_limits<Real>::max)());\n                    }\n\n                    m_dxs[i] = std::nextafter(bounds[i].second, std::numeric_limits<Real>::lowest()) - m_lbs[i];\n                }\n                else\n                {\n                    m_lbs[i] = bounds[i].first;\n                    m_dxs[i] = bounds[i].second - bounds[i].first;\n                }\n                m_volume *= m_dxs[i];\n            }\n        }\n\n        m_integrand = [this, &integrand](std::vector<Real> & x)->Real\n        {\n            Real coeff = m_volume;\n            for (uint64_t i = 0; i < x.size(); ++i)\n            {\n                // Variable transformation are listed at:\n                // https://en.wikipedia.org/wiki/Numerical_integration\n                // However, we've made some changes to these so that we can evaluate on a compact domain.\n                if (m_limit_types[i] == detail::limit_classification::FINITE)\n                {\n                    x[i] = m_lbs[i] + x[i]*m_dxs[i];\n                }\n                else if (m_limit_types[i] == detail::limit_classification::UPPER_BOUND_INFINITE)\n                {\n                    Real t = x[i];\n                    Real z = 1/(1 + numeric_limits<Real>::epsilon() - t);\n                    coeff *= (z*z)*(1 + numeric_limits<Real>::epsilon());\n                    x[i] = m_lbs[i] + t*z;\n                }\n                else if (m_limit_types[i] == detail::limit_classification::LOWER_BOUND_INFINITE)\n                {\n                    Real t = x[i];\n                    Real z = 1/(t+sqrt((numeric_limits<Real>::min)()));\n                    coeff *= (z*z);\n                    x[i] = m_lbs[i] + (t-1)*z;\n                }\n                else\n                {\n                    Real t1 = 1/(1+numeric_limits<Real>::epsilon() - x[i]);\n                    Real t2 = 1/(x[i]+numeric_limits<Real>::epsilon());\n                    x[i] = (2*x[i]-1)*t1*t2/4;\n                    coeff *= (t1*t1+t2*t2)/4;\n                }\n            }\n            return coeff*integrand(x);\n        };\n\n        // If we don't do a single function call in the constructor,\n        // we can't do a restart.\n        std::vector<Real> x(m_lbs.size());\n\n        // If the seed is zero, that tells us to choose a random seed for the user:\n        if (seed == 0)\n        {\n            std::random_device rd;\n            seed = rd();\n        }\n\n        RandomNumberGenerator gen(seed);\n        Real inv_denom = 1/static_cast<Real>(((gen.max)()-(gen.min)()));\n\n        m_num_threads = (std::max)(m_num_threads, (uint64_t) 1);\n        m_thread_calls.reset(new std::atomic<uint64_t>[threads]);\n        m_thread_Ss.reset(new std::atomic<Real>[threads]);\n        m_thread_averages.reset(new std::atomic<Real>[threads]);\n\n        Real avg = 0;\n        for (uint64_t i = 0; i < m_num_threads; ++i)\n        {\n            for (uint64_t j = 0; j < m_lbs.size(); ++j)\n            {\n                x[j] = (gen()-(gen.min)())*inv_denom;\n            }\n            Real y = m_integrand(x);\n            m_thread_averages[i] = y; // relaxed store\n            m_thread_calls[i] = 1;\n            m_thread_Ss[i] = 0;\n            avg += y;\n        }\n        avg /= m_num_threads;\n        m_avg = avg; // relaxed store\n\n        m_error_goal = error_goal; // relaxed store\n        m_start = std::chrono::system_clock::now();\n        m_done = false; // relaxed store\n        m_total_calls = m_num_threads;  // relaxed store\n        m_variance = (numeric_limits<Real>::max)();\n    }\n\n    std::future<Real> integrate()\n    {\n        // Set done to false in case we wish to restart:\n        m_done.store(false); // relaxed store, no worker threads yet\n        m_start = std::chrono::system_clock::now();\n        return std::async(std::launch::async,\n                          &naive_monte_carlo::m_integrate, this);\n    }\n\n    void cancel()\n    {\n        // If seed = 0 (meaning have the routine pick the seed), this leaves the seed the same.\n        // If seed != 0, then the seed is changed, so a restart doesn't do the exact same thing.\n        m_seed = m_seed*m_seed;\n        m_done = true; // relaxed store, worker threads will get the message eventually\n        // Make sure the error goal is infinite, because otherwise we'll loop when we do the final error goal check:\n        m_error_goal = (std::numeric_limits<Real>::max)();\n    }\n\n    Real variance() const\n    {\n        return m_variance.load();\n    }\n\n    Real current_error_estimate() const\n    {\n        using std::sqrt;\n        //\n        // There is a bug here: m_variance and m_total_calls get updated asynchronously\n        // and may be out of synch when we compute the error estimate, not sure if it matters though...\n        //\n        return sqrt(m_variance.load()/m_total_calls.load());\n    }\n\n    std::chrono::duration<Real> estimated_time_to_completion() const\n    {\n        auto now = std::chrono::system_clock::now();\n        std::chrono::duration<Real> elapsed_seconds = now - m_start;\n        Real r = this->current_error_estimate()/m_error_goal.load(); // relaxed load\n        if (r*r <= 1) {\n            return 0*elapsed_seconds;\n        }\n        return (r*r - 1)*elapsed_seconds;\n    }\n\n    void update_target_error(Real new_target_error)\n    {\n        m_error_goal = new_target_error;  // relaxed store\n    }\n\n    Real progress() const\n    {\n        Real r = m_error_goal.load()/this->current_error_estimate();  // relaxed load\n        if (r*r >= 1)\n        {\n            return 1;\n        }\n        return r*r;\n    }\n\n    Real current_estimate() const\n    {\n        return m_avg.load();\n    }\n\n    uint64_t calls() const\n    {\n        return m_total_calls.load();  // relaxed load\n    }\n\nprivate:\n\n   Real m_integrate()\n   {\n      uint64_t seed;\n      // If the user tells us to pick a seed, pick a seed:\n      if (m_seed == 0)\n      {\n         std::random_device rd;\n         seed = rd();\n      }\n      else // use the seed we are given:\n      {\n         seed = m_seed;\n      }\n      RandomNumberGenerator gen(seed);\n      int max_repeat_tries = 5;\n      do{\n\n         if (max_repeat_tries < 5)\n         {\n            m_done = false;\n\n#ifdef BOOST_NAIVE_MONTE_CARLO_DEBUG_FAILURES\n            std::cout << \"Failed to achieve required tolerance first time through..\\n\";\n            std::cout << \"  variance =    \" << m_variance << std::endl;\n            std::cout << \"  average =     \" << m_avg << std::endl;\n            std::cout << \"  total calls = \" << m_total_calls << std::endl;\n\n            for (std::size_t i = 0; i < m_num_threads; ++i)\n               std::cout << \"  thread_calls[\" << i << \"] = \" << m_thread_calls[i] << std::endl;\n            for (std::size_t i = 0; i < m_num_threads; ++i)\n               std::cout << \"  thread_averages[\" << i << \"] = \" << m_thread_averages[i] << std::endl;\n            for (std::size_t i = 0; i < m_num_threads; ++i)\n               std::cout << \"  thread_Ss[\" << i << \"] = \" << m_thread_Ss[i] << std::endl;\n#endif\n         }\n\n         std::vector<std::thread> threads(m_num_threads);\n         for (uint64_t i = 0; i < threads.size(); ++i)\n         {\n            threads[i] = std::thread(&naive_monte_carlo::m_thread_monte, this, i, gen());\n         }\n         do {\n            std::this_thread::sleep_for(std::chrono::milliseconds(100));\n            uint64_t total_calls = 0;\n            for (uint64_t i = 0; i < m_num_threads; ++i)\n            {\n               uint64_t t_calls = m_thread_calls[i].load(std::memory_order_consume);\n               total_calls += t_calls;\n            }\n            Real variance = 0;\n            Real avg = 0;\n            for (uint64_t i = 0; i < m_num_threads; ++i)\n            {\n               uint64_t t_calls = m_thread_calls[i].load(std::memory_order_consume);\n               // Will this overflow? Not hard to remove . . .\n               avg += m_thread_averages[i].load(std::memory_order_relaxed)*((Real)t_calls / (Real)total_calls);\n               variance += m_thread_Ss[i].load(std::memory_order_relaxed);\n            }\n            m_avg.store(avg, std::memory_order_release);\n            m_variance.store(variance / (total_calls - 1), std::memory_order_release);\n            m_total_calls = total_calls; // relaxed store, it's just for user feedback\n            // Allow cancellation:\n            if (m_done) // relaxed load\n            {\n               break;\n            }\n         } while (m_total_calls < 2048 || this->current_error_estimate() > m_error_goal.load(std::memory_order_consume));\n         // Error bound met; signal the threads:\n         m_done = true; // relaxed store, threads will get the message in the end\n         std::for_each(threads.begin(), threads.end(),\n            std::mem_fn(&std::thread::join));\n         if (m_exception)\n         {\n            std::rethrow_exception(m_exception);\n         }\n         // Incorporate their work into the final estimate:\n         uint64_t total_calls = 0;\n         for (uint64_t i = 0; i < m_num_threads; ++i)\n         {\n            uint64_t t_calls = m_thread_calls[i].load(std::memory_order_consume);\n            total_calls += t_calls;\n         }\n         Real variance = 0;\n         Real avg = 0;\n\n         for (uint64_t i = 0; i < m_num_threads; ++i)\n         {\n            uint64_t t_calls = m_thread_calls[i].load(std::memory_order_consume);\n            // Averages weighted by the number of calls the thread made:\n            avg += m_thread_averages[i].load(std::memory_order_relaxed)*((Real)t_calls / (Real)total_calls);\n            variance += m_thread_Ss[i].load(std::memory_order_relaxed);\n         }\n         m_avg.store(avg, std::memory_order_release);\n         m_variance.store(variance / (total_calls - 1), std::memory_order_release);\n         m_total_calls = total_calls; // relaxed store, this is just user feedback\n\n         // Sometimes, the master will observe the variance at a very \"good\" (or bad?) moment,\n         // Then the threads proceed to find the variance is much greater by the time they hear the message to stop.\n         // This *WOULD* make sure that the final error estimate is within the error bounds.\n      }\n      while ((--max_repeat_tries >= 0) && (this->current_error_estimate() > m_error_goal));\n\n      return m_avg.load(std::memory_order_consume);\n    }\n\n    void m_thread_monte(uint64_t thread_index, uint64_t seed)\n    {\n        using std::numeric_limits;\n        try\n        {\n            std::vector<Real> x(m_lbs.size());\n            RandomNumberGenerator gen(seed);\n            Real inv_denom = (Real) 1/(Real)( (gen.max)() - (gen.min)()  );\n            Real M1 = m_thread_averages[thread_index].load(std::memory_order_consume);\n            Real S = m_thread_Ss[thread_index].load(std::memory_order_consume);\n            // Kahan summation is required or the value of the integrand will go on a random walk during long computations.\n            // See the implementation discussion.\n            // The idea is that the unstabilized additions have error sigma(f)/sqrt(N) + epsilon*N, which diverges faster than it converges!\n            // Kahan summation turns this to sigma(f)/sqrt(N) + epsilon^2*N, and the random walk occurs on a timescale of 10^14 years (on current hardware)\n            Real compensator = 0;\n            uint64_t k = m_thread_calls[thread_index].load(std::memory_order_consume);\n            while (!m_done) // relaxed load\n            {\n                int j = 0;\n                // If we don't have a certain number of calls before an update, we can easily terminate prematurely\n                // because the variance estimate is way too low. This magic number is a reasonable compromise, as 1/sqrt(2048) = 0.02,\n                // so it should recover 2 digits if the integrand isn't poorly behaved, and if it is, it should discover that before premature termination.\n                // Of course if the user has 64 threads, then this number is probably excessive.\n                int magic_calls_before_update = 2048;\n                while (j++ < magic_calls_before_update)\n                {\n                    for (uint64_t i = 0; i < m_lbs.size(); ++i)\n                    {\n                        x[i] = (gen() - (gen.min)())*inv_denom;\n                    }\n                    Real f = m_integrand(x);\n                    using std::isfinite;\n                    if (!isfinite(f))\n                    {\n                        // The call to m_integrand transform x, so this error message states the correct node.\n                        std::stringstream os;\n                        os << \"Your integrand was evaluated at {\";\n                        for (uint64_t i = 0; i < x.size() -1; ++i)\n                        {\n                             os << x[i] << \", \";\n                        }\n                        os << x[x.size() -1] << \"}, and returned \" << f << std::endl;\n                        static const char* function = \"boost::math::quadrature::naive_monte_carlo<%1%>\";\n                        boost::math::policies::raise_domain_error(function, os.str().c_str(), /*this is a dummy arg to make it compile*/ 7.2, Policy());\n                    }\n                    ++k;\n                    Real term = (f - M1)/k;\n                    Real y1 = term - compensator;\n                    Real M2 = M1 + y1;\n                    compensator = (M2 - M1) - y1;\n                    S += (f - M1)*(f - M2);\n                    M1 = M2;\n                }\n                m_thread_averages[thread_index].store(M1, std::memory_order_release);\n                m_thread_Ss[thread_index].store(S, std::memory_order_release);\n                m_thread_calls[thread_index].store(k, std::memory_order_release);\n            }\n        }\n        catch (...)\n        {\n            // Signal the other threads that the computation is ruined:\n            m_done = true; // relaxed store\n            std::lock_guard<std::mutex> lock(m_exception_mutex); // Scoped lock to prevent race writing to m_exception\n            m_exception = std::current_exception();\n        }\n    }\n\n    std::function<Real(std::vector<Real> &)> m_integrand;\n    uint64_t m_num_threads;\n    std::atomic<uint64_t> m_seed;\n    std::atomic<Real> m_error_goal;\n    std::atomic<bool> m_done;\n    std::vector<Real> m_lbs;\n    std::vector<Real> m_dxs;\n    std::vector<detail::limit_classification> m_limit_types;\n    Real m_volume;\n    std::atomic<uint64_t> m_total_calls;\n    // I wanted these to be vectors rather than maps,\n    // but you can't resize a vector of atomics.\n    std::unique_ptr<std::atomic<uint64_t>[]> m_thread_calls;\n    std::atomic<Real> m_variance;\n    std::unique_ptr<std::atomic<Real>[]> m_thread_Ss;\n    std::atomic<Real> m_avg;\n    std::unique_ptr<std::atomic<Real>[]> m_thread_averages;\n    std::chrono::time_point<std::chrono::system_clock> m_start;\n    std::exception_ptr m_exception;\n    std::mutex m_exception_mutex;\n};\n\n}}}\n#endif\n", "meta": {"hexsha": "4135d6895325ee3631abc403cb012548d9863280", "size": 18808, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/math/quadrature/naive_monte_carlo.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/quadrature/naive_monte_carlo.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/quadrature/naive_monte_carlo.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": 40.70995671, "max_line_length": 155, "alphanum_fraction": 0.5367928541, "num_tokens": 4399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195152660687, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.47293823292505555}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2015 NumScale SAS\n  @copyright 2015 J.T. Lapreste\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_CONSTANT_SQRT_2PI_HPP_INCLUDED\n#define BOOST_SIMD_CONSTANT_SQRT_2PI_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n  /*!\n\n    @ingroup group-constant\n\n    Constant \\f$\\sqrt{2\\pi}\\f$.\n\n    @par Semantic:\n\n    For type T:\n\n    @code\n    T r = Sqrt_2pi<T>();\n    @endcode\n\n    is similar to:\n\n    @code\n    T r = sqrt(Pix2<T>();\n    @endcode\n\n    @return a value of type T\n\n**/\n  template<typename T> T Sqrt_2pi();\n\n  namespace functional\n  {\n    /*!\n      @ingroup group-callable-constant\n\n\n      Constant \\f$\\sqrt{2\\pi}\\f$.\n\n      Generate the  constant sqrt_2pi.\n\n      @return The Sqrt_2pi constant for the proper type\n    **/\n    const boost::dispatch::functor<tag::sqrt_2pi_> sqrt_2pi = {};\n  }\n} }\n#endif\n\n#include <boost/simd/constant/definition/sqrt_2pi.hpp>\n#include <boost/simd/arch/common/scalar/constant/constant_value.hpp>\n#include <boost/simd/arch/common/simd/constant/constant_value.hpp>\n\n#endif\n", "meta": {"hexsha": "90673141407e07631747ab9927927934fdaa06c5", "size": 1380, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/constant/sqrt_2pi.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/constant/sqrt_2pi.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/constant/sqrt_2pi.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": 21.2307692308, "max_line_length": 100, "alphanum_fraction": 0.581884058, "num_tokens": 345, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.734119526900183, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.4729382303909937}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// numeric::algorithm::min_element.hpp                                       //\n//                                                                           //\n//  Copyright 2009 Erwann Rogard. Distributed under the Boost                //\n//  Software License, Version 1.0. (See accompanying file                    //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)         //\n///////////////////////////////////////////////////////////////////////////////\n#ifndef BOOST_STATISTICS_DETAIL_NUMERIC_ALGORITHM_MIN_ELEMENT_HPP_ER_2009\n#define BOOST_STATISTICS_DETAIL_NUMERIC_ALGORITHM_MIN_ELEMENT_HPP_ER_2009\n#include <limits>\n#include <boost/iterator/iterator_traits.hpp>\n#include <boost/numeric/conversion/bounds.hpp>\n#include <boost/limits.hpp>\n#include <boost/concept_check.hpp>\n#include <boost/concept/assert.hpp>\n#include <iostream>\n\nnamespace boost{\nnamespace statistics{\nnamespace detail{\nnamespace numeric{\nnamespace algorithm{\n\n// This is a rewrite of std::min_element with one additional argument, m, which\n// is assigned the min value of *i over [first,last).\n//\n// Rationale: saves one dereferencing operation,\n// which may be worthwhile if dereferencing is expensive. \ntemplate <typename It,typename V>\nIt min_element(It first, It last,V& min_value) {\n    typedef typename iterator_value<It>::type value_type;\n\n    // TODO see about enable_if/disable_if\n    static bool has_inf = std::numeric_limits<V>::has_infinity;\n    static V inf_if = std::numeric_limits<V>::infinity(); \n    static V highest = boost::numeric::bounds<V>::highest();\n    static V inf_ = has_inf? inf_if : highest;\n    \n    BOOST_CONCEPT_ASSERT((\n        boost::IncrementableIterator<It>\n    ));\n    \n    min_value = inf_;\n    value_type value;\n    It result = first;\n    while (first != last){\n        value = (*first);\n        if (value < min_value){\n            min_value = value;\n            result = first;\n        }\n\n        ++first;\n    }\n    return result;\n}\n\n}// algorithm\n}// numeric\n}// detail\n}// statistics\n}// boost\n\n#endif", "meta": {"hexsha": "e46b0bf0c189181fe04638772a1d6b871b49891a", "size": 2120, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "detail/numeric/boost/statistics/detail/numeric/algorithm/min_element.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": "detail/numeric/boost/statistics/detail/numeric/algorithm/min_element.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": "detail/numeric/boost/statistics/detail/numeric/algorithm/min_element.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.125, "max_line_length": 79, "alphanum_fraction": 0.5990566038, "num_tokens": 432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195385342972, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.4729382278569313}}
{"text": "/* Copyright (C) 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 <NTL/ZZ.h>\n#include <algorithm>\n\n#include <helib/helib.h>\n#include <helib/debugging.h>\n\n#include \"gtest/gtest.h\"\n#include \"test_common.h\"\n\nnamespace {\nstruct Parameters\n{\n  Parameters(unsigned m,\n             unsigned p,\n             unsigned r,\n             unsigned bits,\n             const std::vector<long>& gens = {},\n             const std::vector<long>& ords = {}) :\n      m(m), p(p), r(r), bits(bits), gens(gens), ords(ords){};\n\n  const unsigned m;\n  const unsigned p;\n  const unsigned r;\n  const unsigned bits;\n  const std::vector<long> gens;\n  const std::vector<long> ords;\n\n  friend std::ostream& operator<<(std::ostream& os, const Parameters& params)\n  {\n    return os << \"{\"\n              << \"m = \" << params.m << \", \"\n              << \"p = \" << params.p << \", \"\n              << \"r = \" << params.r << \", \"\n              << \"gens = \" << helib::vecToStr(params.gens) << \", \"\n              << \"ords = \" << helib::vecToStr(params.ords) << \", \"\n              << \"bits = \" << params.bits << \"}\";\n  }\n};\n\nclass TestBGV : public ::testing::TestWithParam<Parameters>\n{\nprotected:\n  const unsigned long m;\n  const unsigned long p;\n  const unsigned long r;\n  const unsigned long bits;\n  helib::Context context;\n  helib::SecKey secretKey;\n  const helib::PubKey publicKey;\n  const helib::EncryptedArray& ea;\n\n  TestBGV() :\n      m(GetParam().m),\n      p(GetParam().p),\n      r(GetParam().r),\n      bits(GetParam().bits),\n      context(helib::ContextBuilder<helib::BGV>()\n                  .m(m)\n                  .p(p)\n                  .r(r)\n                  .bits(bits)\n                  .build()),\n      secretKey(context),\n      publicKey((secretKey.GenSecKey(),\n                 helib::addSome1DMatrices(secretKey),\n                 secretKey)),\n      ea(context.getEA())\n  {}\n\n  virtual void SetUp() override\n  {\n    if (helib_test::verbose) {\n      ea.getPAlgebra().printout();\n      std::cout << \"r = \" << context.getAlMod().getR() << std::endl;\n      std::cout << \"ctxtPrimes=\" << context.getCtxtPrimes()\n                << \", specialPrimes=\" << context.getSpecialPrimes() << \"\\n\"\n                << std::endl;\n    }\n\n    helib::setupDebugGlobals(&secretKey, context.shareEA());\n  }\n\n  virtual void TearDown() override { helib::cleanupDebugGlobals(); }\n};\n\nTEST_P(TestBGV, negatingCiphertextWorks)\n{\n  helib::PtxtArray p1(ea), p2(ea);\n  p1.random();\n\n  helib::Ctxt c1(publicKey);\n  p1.encrypt(c1);\n\n  c1.negate();\n  p1.negate();\n\n  p2.decrypt(c1, secretKey);\n\n  EXPECT_EQ(p1, p2);\n}\n\nTEST_P(TestBGV, addingPolyConstantToCiphertextWorks)\n{\n  helib::PtxtArray p1(ea), p2(ea), const1(ea);\n  p1.random();\n  const1.random();\n\n  helib::Ctxt c1(publicKey);\n  p1.encrypt(c1);\n\n  c1.addConstant(const1);\n  p1 += const1;\n\n  p2.decrypt(c1, secretKey);\n\n  EXPECT_EQ(p1, p2);\n}\n\nTEST_P(TestBGV, addingNegatedPolyConstantToCiphertextWorks)\n{\n  helib::PtxtArray p1(ea), p2(ea), const1(ea);\n  p1.random();\n  const1.random();\n\n  helib::Ctxt c1(publicKey);\n  p1.encrypt(c1);\n\n  p1 -= const1;\n  const1.negate();\n  c1.addConstant(const1);\n\n  p2.decrypt(c1, secretKey);\n\n  EXPECT_EQ(p1, p2);\n}\n\nTEST_P(TestBGV, multiplyingPolyConstantToCiphertextWorks)\n{\n  helib::PtxtArray p1(ea), p2(ea), const1(ea);\n  p1.random();\n  const1.random();\n\n  helib::Ctxt c1(publicKey);\n  p1.encrypt(c1);\n\n  c1.multByConstant(const1);\n  p1 *= const1;\n\n  p2.decrypt(c1, secretKey);\n\n  EXPECT_EQ(p1, p2);\n}\n\nTEST_P(TestBGV, addingLongToCiphertextWorks)\n{\n  long const1 = 1;\n  helib::PtxtArray p1(ea), p2(ea);\n  p1.random();\n\n  helib::Ctxt c1(publicKey);\n  p1.encrypt(c1);\n\n  c1.addConstant(const1);\n  p1 += const1;\n\n  p2.decrypt(c1, secretKey);\n\n  EXPECT_EQ(p1, p2);\n}\n\nTEST_P(TestBGV, multiplyingLongToCiphertextWorks)\n{\n  long const1 = 2;\n  helib::PtxtArray p1(ea), p2(ea);\n  p1.random();\n\n  helib::Ctxt c1(publicKey);\n  p1.encrypt(c1);\n\n  c1.multByConstant(const1);\n  p1 *= const1;\n\n  p2.decrypt(c1, secretKey);\n\n  EXPECT_EQ(p1, p2);\n}\n\nTEST_P(TestBGV, rotatingCiphertextWorks)\n{\n  helib::PtxtArray p1(ea), p2(ea);\n  p1.random();\n\n  helib::Ctxt c1(publicKey);\n  p1.encrypt(c1);\n\n  ea.rotate(c1, 3);\n  rotate(p1, 3);\n\n  p2.decrypt(c1, secretKey);\n\n  EXPECT_EQ(p1, p2);\n}\n\nTEST_P(TestBGV, addingCiphertextsWorks)\n{\n  helib::PtxtArray p1(ea), p2(ea), p3(ea);\n  p1.random();\n  p2.random();\n\n  helib::Ctxt c1(publicKey), c2(publicKey);\n  p1.encrypt(c1);\n  p2.encrypt(c2);\n\n  c1 += c2;\n  p1 += p2;\n\n  p3.decrypt(c1, secretKey);\n\n  EXPECT_EQ(p1, p3);\n}\n\nTEST_P(TestBGV, subtractingCiphertextsWorks)\n{\n  helib::PtxtArray p1(ea), p2(ea), p3(ea);\n  p1.random();\n  p2.random();\n\n  helib::Ctxt c1(publicKey), c2(publicKey);\n  p1.encrypt(c1);\n  p2.encrypt(c2);\n\n  c1 -= c2;\n  p1 -= p2;\n\n  p3.decrypt(c1, secretKey);\n\n  EXPECT_EQ(p1, p3);\n}\n\nTEST_P(TestBGV, timesEqualsOfCiphertextsWorks)\n{\n  helib::PtxtArray p1(ea), p2(ea), p3(ea);\n  p1.random();\n  p2.random();\n\n  helib::Ctxt c1(publicKey), c2(publicKey);\n  p1.encrypt(c1);\n  p2.encrypt(c2);\n\n  c1 *= c2;\n  p1 *= p2;\n\n  p3.decrypt(c1, secretKey);\n\n  EXPECT_EQ(p1, p3);\n  // Check that relinearization has occurred\n  EXPECT_TRUE(c1.inCanonicalForm());\n}\n\nTEST_P(TestBGV, rawMultiplicationOfCiphertextsWorks)\n{\n  helib::PtxtArray p1(ea), p2(ea), p3(ea);\n  p1.random();\n  p2.random();\n\n  helib::Ctxt c1(publicKey), c2(publicKey);\n  p1.encrypt(c1);\n  p2.encrypt(c2);\n\n  c1.multLowLvl(c2);\n  p1 *= p2;\n\n  p3.decrypt(c1, secretKey);\n\n  EXPECT_EQ(p1, p3);\n  // Check that relinearization has not occurred\n  EXPECT_FALSE(c1.inCanonicalForm());\n}\n\nTEST_P(TestBGV, highLevelMultiplicationOfCiphertextsWorks)\n{\n  helib::PtxtArray p1(ea), p2(ea), p3(ea);\n  p1.random();\n  p2.random();\n\n  helib::Ctxt c1(publicKey), c2(publicKey);\n  p1.encrypt(c1);\n  p2.encrypt(c2);\n\n  c1.multiplyBy(c2);\n  p1 *= p2;\n\n  p3.decrypt(c1, secretKey);\n\n  EXPECT_EQ(p1, p3);\n  // Check that relinearization has not occurred\n  EXPECT_TRUE(c1.inCanonicalForm());\n}\n\nTEST_P(TestBGV, squaringCiphertextWorks)\n{\n  helib::PtxtArray p1(ea), p2(ea);\n  p1.random();\n\n  helib::Ctxt c1(publicKey);\n  p1.encrypt(c1);\n\n  c1.square();\n  p1 *= p1;\n\n  p2.decrypt(c1, secretKey);\n\n  EXPECT_EQ(p1, p2);\n  // Check that relinearization has not occurred\n  EXPECT_TRUE(c1.inCanonicalForm());\n}\n\nTEST_P(\n    TestBGV,\n    multiplyingCiphertextByNegativeConstantAndThenAddingToOtherCiphertextWorks)\n{\n  helib::PtxtArray p1(ea), p2(ea), p3(ea), const1(ea, -1);\n  p1.random();\n  p2.random();\n\n  helib::Ctxt c1(publicKey), c2(publicKey);\n  p1.encrypt(c1);\n  p2.encrypt(c2);\n\n  c1.multByConstant(const1);\n  c1 += c2;\n  p1 *= const1;\n  p1 += p2;\n\n  p3.decrypt(c1, secretKey);\n\n  EXPECT_EQ(p1, p3);\n}\n\nINSTANTIATE_TEST_SUITE_P(typicalParameters,\n                         TestBGV,\n                         ::testing::Values(\n                             // FAST\n                             Parameters(257, 2, 1, 150)\n                             // SLOW\n                             // Parameters(2049, 2, 1, 150)\n                             ));\n\n} // namespace\n", "meta": {"hexsha": "3134475368e5d3eea6ea3dfca99a54ae9cfe6a36", "size": 7547, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/TestBGV.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": "tests/TestBGV.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": "tests/TestBGV.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": 20.8480662983, "max_line_length": 79, "alphanum_fraction": 0.6137538095, "num_tokens": 2329, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.6442250996557035, "lm_q1q2_score": 0.4729382253764684}}
{"text": "#include \"dnnl.hpp\"\r\n#include \"dnnl_debug.h\"\r\n#include \"bfloat16.hpp\"\r\n\r\n#include \"dnnl.h\"\r\n\r\n#include <iostream>\r\n#include <iomanip>\r\n#include <chrono>\r\n\r\n#include <mkl.h>\r\n\r\n#define EIGEN_USE_MKL_ALL\r\n#include <Eigen/Dense>\r\n\r\n//#define XBYAK_NO_OP_NAMES\r\n//#include <xbyak.h>\r\n\r\n#include \"dnnl_common.h\"\r\n#include \"dnnl_inner_product.h\"\r\n#include \"dnnl_matmul.h\"\r\n\r\nvoid init_param(int m, int n, int k, float *A, float *B, float *C, bfloat16 *A_bf16, bfloat16 *B_bf16, bfloat16 *C_bf16, Eigen::MatrixXf& A_mat, Eigen::MatrixXf& B_mat, Eigen::MatrixXf& C_mat);\r\n\r\ndouble test_eigen_sgemm(Eigen::MatrixXf& A_mat, Eigen::MatrixXf& B_mat, Eigen::MatrixXf& C_mat, int m, int n, int k);\r\ndouble test_mkl_sgemm(float *A, float *B, float *C, int m, int n, int k);\r\ndouble test_mkl_sgemm_transB(float *A, float *B, float *C, int m, int n, int k);\r\ndouble test_dnnl_sgemm(float *A, float *B, float *C, int m, int n, int k);\r\ndouble test_dnnl_gemm_bf16bf16f32(float *A, float *B, float *C, int m, int n, int k, bfloat16 *A_bf16, bfloat16 *B_bf16, bfloat16 *C_bf16);\r\ndouble test_dnnl_gemm_bf16bf16f32_transB(float *A, float *B, float *C, int m, int n, int k, bfloat16 *A_bf16, bfloat16 *B_bf16, bfloat16 *C_bf16);\r\ndouble test_dnnl_gemm_bf16bf16f32_cvt(float *A, float *B, float *C, int m, int n, int k, bfloat16 *A_bf16, bfloat16 *B_bf16, bfloat16 *C_bf16);\r\ndouble test_dnnl_gemm_bf16bf16f32_transB_cvt(float *A, float *B, float *C, int m, int n, int k, bfloat16 *A_bf16, bfloat16 *B_bf16, bfloat16 *C_bf16);\r\ndouble test_dnnl_gemm_bf16bf16f32_omp_cvt(float *A, float *B, float *C, int m, int n, int k, bfloat16 *A_bf16, bfloat16 *B_bf16, bfloat16 *C_bf16);\r\ndouble test_dnnl_gemm_bf16bf16f32_transB_omp_cvt(float *A, float *B, float *C, int m, int n, int k, bfloat16 *A_bf16, bfloat16 *B_bf16, bfloat16 *C_bf16);\r\ndouble test_dnnl_cvt_float_to_bfloat16(float *A, float *B, float *C, int m, int n, int k, bfloat16 *A_bf16, bfloat16 *B_bf16, bfloat16 *C_bf16);\r\ndouble test_dnnl_omp_cvt_float_to_bfloat16(float *A, float *B, float *C, int m, int n, int k, bfloat16 *A_bf16, bfloat16 *B_bf16, bfloat16 *C_bf16);\r\n//double test_jit_cvt_float_to_bfloat16(float *A, float *B, float *C, int m, int n, int k, bfloat16 *A_bf16, bfloat16 *B_bf16, bfloat16 *C_bf16);\r\ndouble test_dnnl_cvt_bfloat16_to_float(float *A, float *B, float *C, int m, int n, int k, bfloat16 *A_bf16, bfloat16 *B_bf16, bfloat16 *C_bf16);\r\ndouble test_dnnl_omp_cvt_bfloat16_to_float(float *A, float *B, float *C, int m, int n, int k, bfloat16 *A_bf16, bfloat16 *B_bf16, bfloat16 *C_bf16);\r\n\r\ntemplate <typename T_A, typename T_B, typename T_bias, typename T_C>\r\ndouble test_dnnl_inner_product(engine eng, stream stm, T_A* A_buf, T_B* B_buf, T_bias* bias_buf, T_C* C_buf, int m, int n, int k);\r\ntemplate <typename T_A, typename T_B, typename T_bias, typename T_C>\r\ndouble test_dnnl_inner_product_v2(engine eng, stream stm, T_A* A_buf, T_B* B_buf, T_bias* bias_buf, T_C* C_buf, int m, int n, int k);\r\ntemplate <typename T_A, typename T_B, typename T_bias, typename T_C>\r\ndouble test_dnnl_inner_product_eltwise(engine eng, stream stm, T_A* A_buf, T_B* B_buf, T_bias* bias_buf, T_C* C_buf, int m, int n, int k);\r\n\r\ntemplate <typename T_A, typename T_B, typename T_bias, typename T_C>\r\ndouble test_dnnl_matmul(engine eng, stream stm, T_A* A_buf, T_B* B_buf, T_bias* bias_buf, T_C* C_buf, int m, int n, int k);\r\ntemplate <typename T_A, typename T_B, typename T_C>\r\ndouble test_dnnl_matmul2(engine eng, stream stm, T_A* A_buf, T_B* B_buf, T_C* C_buf, int m, int n, int k);\r\ntemplate <typename T_A, typename T_B, typename T_C>\r\ndouble test_dnnl_matmul2_eltwise(engine eng, stream stm, T_A* A_buf, T_B* B_buf, T_C* C_buf, int m, int n, int k);\r\n\r\ntemplate <typename T_A, typename T_B, typename T_C>\r\ndouble test_dnnl_batchmatmul(engine eng, stream stm, T_A* A_buf, T_B* B_buf, T_C* C_buf, int mb, int m, int n, int k);\r\n\r\n\r\nint main(int argc, char *argv[])\r\n{\r\n    printf(\"./gemmbench_dnnl m n k\\nargc = %d\\n\", argc);\r\n    for(int ndx = 0; ndx != argc; ++ndx)\r\n        printf(\"argv[%d] --> %s\\n\", ndx, argv[ndx]);\r\n\r\n    int m = atoi(argv[1]);\r\n    int n = atoi(argv[2]);\r\n    int k = atoi(argv[3]);\r\n\r\n    bfloat16 *A_bf16 = new bfloat16[m*k];\r\n    bfloat16 *B_bf16 = new bfloat16[k*n];\r\n    bfloat16 *C_bf16 = new bfloat16[m*n];\r\n\r\n    float *A = new float[m*k];\r\n    float *B = new float[k*n];\r\n    float *C = new float[m*n];\r\n\r\n    Eigen::MatrixXf A_mat(m, k);\r\n    Eigen::MatrixXf B_mat(k, n);\r\n    Eigen::MatrixXf C_mat(m, n);\r\n\r\n    init_param(m, n, k, A, B, C, A_bf16, B_bf16, C_bf16, A_mat, B_mat, C_mat);\r\n    std::cout << \"\\nstarting...\" << std::endl;\r\n\r\n    double t_eigen_sgemm  = test_eigen_sgemm(A_mat, B_mat, C_mat, m, n, k);\r\n\r\n    double t_mkl_sgemm    = test_mkl_sgemm(A, B, C, m, n, k);\r\n    double t_mkl_sgemm_tB = test_mkl_sgemm_transB(A, B, C, m, n, k);\r\n\r\n    double t_dnnl_sgemm = test_dnnl_sgemm(A, B, C, m, n, k);\r\n    double t_dnnl_gemm_bf16 = test_dnnl_gemm_bf16bf16f32(A, B, C, m, n, k, A_bf16, B_bf16, C_bf16);\r\n    double t_dnnl_gemm_bf16_tB = test_dnnl_gemm_bf16bf16f32_transB(A, B, C, m, n, k, A_bf16, B_bf16, C_bf16);\r\n    double t_dnnl_gemm_bf16_cvt = test_dnnl_gemm_bf16bf16f32_cvt(A, B, C, m, n, k, A_bf16, B_bf16, C_bf16);\r\n    double t_dnnl_gemm_bf16_tB_cvt = test_dnnl_gemm_bf16bf16f32_transB_cvt(A, B, C, m, n, k, A_bf16, B_bf16, C_bf16);\r\n    double t_dnnl_gemm_bf16_omp_cvt = test_dnnl_gemm_bf16bf16f32_omp_cvt(A, B, C, m, n, k, A_bf16, B_bf16, C_bf16);\r\n    double t_dnnl_gemm_bf16_tB_omp_cvt = test_dnnl_gemm_bf16bf16f32_transB_omp_cvt(A, B, C, m, n, k, A_bf16, B_bf16, C_bf16);\r\n    double t_dnnl_cvt_f2b     = test_dnnl_cvt_float_to_bfloat16(A, B, C, m, n, k, A_bf16, B_bf16, C_bf16);\r\n    double t_dnnl_omp_cvt_f2b = test_dnnl_omp_cvt_float_to_bfloat16(A, B, C, m, n, k, A_bf16, B_bf16, C_bf16);\r\n    //double t_dnnl_jit_cvt = test_jit_cvt_float_to_bfloat16(A, B, C, m, n, k, A_bf16, B_bf16, C_bf16);\r\n    double t_dnnl_cvt_b2f     = test_dnnl_cvt_bfloat16_to_float(A, B, C, m, n, k, A_bf16, B_bf16, C_bf16);\r\n    double t_dnnl_omp_cvt_b2f = test_dnnl_omp_cvt_bfloat16_to_float(A, B, C, m, n, k, A_bf16, B_bf16, C_bf16);\r\n\r\n    engine cpu_engine;\r\n    stream cpu_stream;\r\n\r\n    stream stream(eng);\r\n    cpu_engine = eng;\r\n    cpu_stream = stream;\r\n\r\n    float *bias = new float[n];\r\n    bfloat16 *bias_bf16 = new bfloat16[n];\r\n    for (int i = 0; i < n; ++i) {\r\n        bias[i] = 1.1;\r\n        bias_bf16[i] = (bfloat16)1.1;\r\n    }\r\n\r\n    double t_dnnl_ip_ffff  = test_dnnl_inner_product(cpu_engine, cpu_stream, A, B, bias, C, m, n, k);\r\n    double t_dnnl_ip2_ffff = test_dnnl_inner_product_v2(cpu_engine, cpu_stream, A, B, bias, C, m, n, k);\r\n    double t_dnnl_ip2_fffb = test_dnnl_inner_product_v2(cpu_engine, cpu_stream, A, B, bias, C_bf16, m, n, k);\r\n    double t_dnnl_ip2_fbbb = test_dnnl_inner_product_v2(cpu_engine, cpu_stream, A, B_bf16, bias_bf16, C_bf16, m, n, k);\r\n    double t_dnnl_ip_bbbb  = test_dnnl_inner_product(cpu_engine, cpu_stream, A_bf16, B_bf16, bias_bf16, C_bf16, m, n, k);\r\n    double t_dnnl_ip_bbbb_e= test_dnnl_inner_product_eltwise(cpu_engine, cpu_stream, A_bf16, B_bf16, bias_bf16, C_bf16, m, n, k);\r\n    double t_dnnl_ip_bbbf  = test_dnnl_inner_product(cpu_engine, cpu_stream, A_bf16, B_bf16, bias_bf16, C, m, n, k);\r\n    double t_dnnl_ip_bbff  = test_dnnl_inner_product(cpu_engine, cpu_stream, A_bf16, B_bf16, bias, C, m, n, k);\r\n\r\n    double t_dnnl_mm_ffff  = test_dnnl_matmul(cpu_engine, cpu_stream, A, B, bias, C, m, n, k);\r\n    double t_dnnl_mm_bbbb  = test_dnnl_matmul(cpu_engine, cpu_stream, A_bf16, B_bf16, bias_bf16, C_bf16, m, n, k);\r\n    double t_dnnl_mm_bbbf  = test_dnnl_matmul(cpu_engine, cpu_stream, A_bf16, B_bf16, bias_bf16, C, m, n, k);\r\n    double t_dnnl_mm_fff  = test_dnnl_matmul2(cpu_engine, cpu_stream, A, B, C, m, n, k);\r\n    double t_dnnl_mm_bbb  = test_dnnl_matmul2(cpu_engine, cpu_stream, A_bf16, B_bf16, C_bf16, m, n, k);\r\n    double t_dnnl_mm_bbb_e= test_dnnl_matmul2_eltwise(cpu_engine, cpu_stream, A_bf16, B_bf16, C_bf16, m, n, k);\r\n    double t_dnnl_mm_bbf  = test_dnnl_matmul2(cpu_engine, cpu_stream, A_bf16, B_bf16, C, m, n, k);\r\n\r\n    int mb = 10;\r\n    bfloat16 *BA_bf16 = new bfloat16[mb*m*k];\r\n    bfloat16 *BB_bf16 = new bfloat16[mb*k*n];\r\n    bfloat16 *BC_bf16 = new bfloat16[mb*m*n];\r\n\r\n    for (int i = 0; i < mb*m*k; ++i)\r\n        BA_bf16[i] = (bfloat16)1.1;\r\n    for (int i = 0; i < mb*k*n; ++i)\r\n        BB_bf16[i] = (bfloat16)1.1;\r\n    for (int i = 0; i < mb*m*n; ++i)\r\n        BC_bf16[i] = (bfloat16)1.1;\r\n\r\n    double t_dnnl_bmm_bbb = test_dnnl_batchmatmul(cpu_engine, cpu_stream, BA_bf16, BB_bf16, BC_bf16, mb, m, n, k);\r\n\r\n    del_dnnl();\r\n\r\n    printf(\"\\n>> omp num_procs: %d\\n\", omp_get_num_procs());\r\n    printf(\"eigen sgemm:               \\t%.6f\\n\", t_eigen_sgemm);\r\n    printf(\"mkl sgemm:                 \\t%.6f ms --> baseline\\n\", t_mkl_sgemm);\r\n    printf(\"mkl sgemm+transB:          \\t%.6f \\t+%.3fX\\n\", t_mkl_sgemm_tB,              t_mkl_sgemm/t_mkl_sgemm_tB);\r\n    printf(\"dnnl sgemm:                \\t%.6f \\t+%.3fX\\n\", t_dnnl_sgemm,                t_mkl_sgemm/t_dnnl_sgemm);\r\n    printf(\"dnnl bgemm:                \\t%.6f \\t+%.3fX\\n\", t_dnnl_gemm_bf16,            t_mkl_sgemm/t_dnnl_gemm_bf16);\r\n    printf(\"dnnl bgemm+transB:         \\t%.6f \\t+%.3fX\\n\", t_dnnl_gemm_bf16_tB,         t_mkl_sgemm/t_dnnl_gemm_bf16_tB);\r\n    printf(\"dnnl bgemm+cvt:            \\t%.6f \\t+%.3fX\\n\", t_dnnl_gemm_bf16_cvt,        t_mkl_sgemm/t_dnnl_gemm_bf16_cvt);\r\n    printf(\"dnnl bgemm+transB+cvt:     \\t%.6f \\t+%.3fX\\n\", t_dnnl_gemm_bf16_tB_cvt,     t_mkl_sgemm/t_dnnl_gemm_bf16_tB_cvt);\r\n    printf(\"dnnl bgemm+omp_cvt:        \\t%.6f \\t+%.3fX\\n\", t_dnnl_gemm_bf16_omp_cvt,    t_mkl_sgemm/t_dnnl_gemm_bf16_omp_cvt);\r\n    printf(\"dnnl bgemm+transB+omp_cvt: \\t%.6f \\t+%.3fX\\n\", t_dnnl_gemm_bf16_tB_omp_cvt, t_mkl_sgemm/t_dnnl_gemm_bf16_tB_omp_cvt);\r\n    printf(\"dnnl cvt f2b:              \\t%.6f \\tt/bgemm:   %.3f%\\n\", t_dnnl_cvt_f2b,     t_dnnl_cvt_f2b/t_dnnl_gemm_bf16*100);\r\n    printf(\"dnnl omp_cvt f2b:          \\t%.6f \\tt/bgemm:   %.3f%\\n\", t_dnnl_omp_cvt_f2b, t_dnnl_omp_cvt_f2b/t_dnnl_gemm_bf16*100);\r\n    //printf(\"dnnl jit_cvt: \\t%.6f \\tt/bgemm:   %.3f%\\n\", t_dnnl_jit_cvt, t_dnnl_jit_cvt/t_dnnl_gemm_bf16*100);\r\n    printf(\"dnnl cvt b2f:              \\t%.6f \\tt/bgemm:   %.3f%\\n\", t_dnnl_cvt_b2f,     t_dnnl_cvt_b2f/t_dnnl_gemm_bf16*100);\r\n    printf(\"dnnl omp_cvt b2f:          \\t%.6f \\tt/bgemm:   %.3f%\\n\", t_dnnl_omp_cvt_b2f, t_dnnl_omp_cvt_b2f/t_dnnl_gemm_bf16*100);\r\n\r\n    printf(\">> inner_product, f: fp32, b: bf16, elw: eltwise\\n\");\r\n    printf(\"dnnl inner_product  ffff:     \\t%.6f \\t+%.3fX\\n\", t_dnnl_ip_ffff,   t_mkl_sgemm/t_dnnl_ip_ffff);\r\n    printf(\"dnnl inner_product2 ffff:     \\t%.6f \\t+%.3fX\\n\", t_dnnl_ip2_ffff,  t_mkl_sgemm/t_dnnl_ip2_ffff);\r\n    printf(\"dnnl inner_product2 fffb:     \\t%.6f \\t+%.3fX\\n\", t_dnnl_ip2_fffb,  t_mkl_sgemm/t_dnnl_ip2_fffb);\r\n    printf(\"dnnl inner_product2 fbbb:     \\t%.6f \\t+%.3fX\\n\", t_dnnl_ip2_fbbb,  t_mkl_sgemm/t_dnnl_ip2_fbbb);\r\n    printf(\"dnnl inner_product  bbbb:     \\t%.6f \\t+%.3fX\\n\", t_dnnl_ip_bbbb,   t_mkl_sgemm/t_dnnl_ip_bbbb);\r\n    printf(\"dnnl inner_product  bbbb+elw: \\t%.6f \\t+%.3fX\\n\", t_dnnl_ip_bbbb_e, t_mkl_sgemm/t_dnnl_ip_bbbb_e);\r\n    printf(\"dnnl inner_product  bbbf:     \\t%.6f \\t+%.3fX\\n\", t_dnnl_ip_bbbf,   t_mkl_sgemm/t_dnnl_ip_bbbf);\r\n    printf(\"dnnl inner_product  bbff:     \\t%.6f \\t+%.3fX\\n\", t_dnnl_ip_bbff,   t_mkl_sgemm/t_dnnl_ip_bbff);\r\n\r\n    printf(\">> matmul, f: fp32, b: bf16, elw: eltwise\\n\");\r\n    printf(\"dnnl matmul ffff:          \\t%.6f \\t+%.3fX\\n\", t_dnnl_mm_ffff,   t_mkl_sgemm/t_dnnl_mm_ffff);\r\n    printf(\"dnnl matmul bbbb:          \\t%.6f \\t+%.3fX\\n\", t_dnnl_mm_bbbb,   t_mkl_sgemm/t_dnnl_mm_bbbb);\r\n    printf(\"dnnl matmul bbbf:          \\t%.6f \\t+%.3fX\\n\", t_dnnl_mm_bbbf,   t_mkl_sgemm/t_dnnl_mm_bbbf);\r\n    printf(\"dnnl matmul2 fff:          \\t%.6f \\t+%.3fX\\n\", t_dnnl_mm_fff,    t_mkl_sgemm/t_dnnl_mm_fff);\r\n    printf(\"dnnl matmul2 bbb:          \\t%.6f \\t+%.3fX\\n\", t_dnnl_mm_bbb,    t_mkl_sgemm/t_dnnl_mm_bbb);\r\n    printf(\"dnnl matmul2 bbb+elw:      \\t%.6f \\t+%.3fX\\n\", t_dnnl_mm_bbb_e,  t_mkl_sgemm/t_dnnl_mm_bbb_e);\r\n    printf(\"dnnl matmul2 bbf:          \\t%.6f \\t+%.3fX\\n\", t_dnnl_mm_bbf,    t_mkl_sgemm/t_dnnl_mm_bbf);\r\n    printf(\"dnnl 10 batch matmul bbb:  \\t%.6f \\t+%.3fX\\n\", t_dnnl_bmm_bbb/10,t_mkl_sgemm/t_dnnl_bmm_bbb*10);\r\n\r\n    delete[] A_bf16;\r\n    delete[] B_bf16;\r\n    delete[] C_bf16;\r\n    delete[] bias_bf16;\r\n\r\n    delete[] A;\r\n    delete[] B;\r\n    delete[] C;\r\n\r\n    return 0;\r\n}\r\n\r\n\r\nvoid init_param(int m, int n, int k, float *A, float *B, float *C, bfloat16 *A_bf16, bfloat16 *B_bf16, bfloat16 *C_bf16, Eigen::MatrixXf& A_mat, Eigen::MatrixXf& B_mat, Eigen::MatrixXf& C_mat)\r\n{\r\n    for (int i = 0; i < m; ++i) {\r\n        for (int j = 0; j < k; ++j) {\r\n            A_bf16[i*k+j] = (bfloat16)1.1;\r\n            A[i*k+j] = 1.1;\r\n            A_mat.row(i).col(j) << 1.1;\r\n        }\r\n    }\r\n\r\n    for (int i = 0; i < k; ++i) {\r\n        for (int j = 0; j < n; ++j) {\r\n            B_bf16[i*n+j] = (bfloat16)1.1;\r\n            B[i*n+j] = 1.1;\r\n            B_mat.row(i).col(j) << 1.1;\r\n        }\r\n    }\r\n\r\n    for (int i = 0; i < m; ++i) {\r\n        for (int j = 0; j < n; ++j) {\r\n            C_bf16[i*n+j] = (bfloat16)1.1;\r\n            C[i*n+j] = 1.1;\r\n            C_mat.row(i).col(j) << 1.1;\r\n        }\r\n    }\r\n}\r\n\r\ndouble test_eigen_sgemm(Eigen::MatrixXf& A_mat, Eigen::MatrixXf& B_mat, Eigen::MatrixXf& C_mat, int m, int n, int k)\r\n{\r\n    C_mat = A_mat * B_mat;\r\n\r\n    auto tag_1 = std::chrono::high_resolution_clock::now();\r\n    for (int i = 0; i < 1000; ++i) {\r\n        C_mat = A_mat * B_mat;\r\n    }\r\n\r\n    auto tag_2 = std::chrono::high_resolution_clock::now();\r\n    auto tag_diff = std::chrono::duration<double>(tag_2 - tag_1).count();\r\n    std::cout << \"result: \" << C_mat(0, 0) << \",\" << C_mat(m-1, n-1) << std::endl;\r\n\r\n    return tag_diff;\r\n}\r\n\r\ndouble test_mkl_sgemm(float *A, float *B, float *C, int m, int n, int k)\r\n{\r\n    cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, m, n, k, 1.0, A, k, B, n, 0.0, C, n);\r\n\r\n    auto tag_1 = std::chrono::high_resolution_clock::now();\r\n    for (int i = 0; i < 1000; ++i) {\r\n        cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, m, n, k, 1.0, A, k, B, n, 0.0, C, n);\r\n    }\r\n\r\n    auto tag_2 = std::chrono::high_resolution_clock::now();\r\n    auto tag_diff = std::chrono::duration<double>(tag_2 - tag_1).count();\r\n    std::cout << \"result: \" << C[0] << \",\" << C[m*n-1] << std::endl;\r\n\r\n    return tag_diff;\r\n}\r\n\r\ndouble test_mkl_sgemm_transB(float *A, float *B, float *C, int m, int n, int k)\r\n{\r\n    cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans, m, n, k, 1.0, A, k, B, k, 0.0, C, n);\r\n\r\n    auto tag_1 = std::chrono::high_resolution_clock::now();\r\n    for (int i = 0; i < 1000; ++i) {\r\n        cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans, m, n, k, 1.0, A, k, B, k, 0.0, C, n);\r\n    }\r\n\r\n    auto tag_2 = std::chrono::high_resolution_clock::now();\r\n    auto tag_diff = std::chrono::duration<double>(tag_2 - tag_1).count();\r\n    std::cout << \"result: \" << C[0] << \",\" << C[m*n-1] << std::endl;\r\n\r\n    return tag_diff;\r\n}\r\n\r\ndouble test_dnnl_sgemm(float *A, float *B, float *C, int m, int n, int k)\r\n{\r\n    dnnl_sgemm('N', 'N', m, n, k, 1.0, A, k, B, n, 0.0, C, n);\r\n\r\n    auto tag_1 = std::chrono::high_resolution_clock::now();\r\n    for (int i = 0; i < 1000; ++i) {\r\n        dnnl_sgemm('N', 'N', m, n, k, 1.0, A, k, B, n, 0.0, C, n);\r\n    }\r\n\r\n    auto tag_2 = std::chrono::high_resolution_clock::now();\r\n    auto tag_diff = std::chrono::duration<double>(tag_2 - tag_1).count();\r\n    std::cout << \"result: \" << C[0] << \",\" << C[m*n-1] << std::endl;\r\n\r\n    return tag_diff;\r\n}\r\n\r\ndouble test_dnnl_gemm_bf16bf16f32(float *A, float *B, float *C, int m, int n, int k, bfloat16 *A_bf16, bfloat16 *B_bf16, bfloat16 *C_bf16)\r\n{\r\n    dnnl_gemm_bf16bf16f32('N', 'N', m, n, k, 1.0, A_bf16, k, B_bf16, n, 0.0, C, n);\r\n\r\n    auto tag_1 = std::chrono::high_resolution_clock::now();\r\n    for (int i = 0; i < 1000; ++i) {\r\n        dnnl_gemm_bf16bf16f32('N', 'N', m, n, k, 1.0, A_bf16, k, B_bf16, n, 0.0, C, n);\r\n    }\r\n\r\n    auto tag_2 = std::chrono::high_resolution_clock::now();\r\n    auto tag_diff = std::chrono::duration<double>(tag_2 - tag_1).count();\r\n    std::cout << \"result: \" << C[0] << \",\" << C[m*n-1] << std::endl;\r\n\r\n    return tag_diff;\r\n}\r\n\r\ndouble test_dnnl_gemm_bf16bf16f32_transB(float *A, float *B, float *C, int m, int n, int k, bfloat16 *A_bf16, bfloat16 *B_bf16, bfloat16 *C_bf16)\r\n{\r\n    dnnl_gemm_bf16bf16f32('N', 'T', m, n, k, 1.0, A_bf16, k, B_bf16, k, 0.0, C, n);\r\n    auto tag_1 = std::chrono::high_resolution_clock::now();\r\n    for (int i = 0; i < 1000; ++i) {\r\n        dnnl_gemm_bf16bf16f32('N', 'T', m, n, k, 1.0, A_bf16, k, B_bf16, k, 0.0, C, n);\r\n    }\r\n    auto tag_2 = std::chrono::high_resolution_clock::now();\r\n    auto tag_diff = std::chrono::duration<double>(tag_2 - tag_1).count();\r\n    std::cout << \"result: \" << C[0] << \",\" << C[m*n-1] << std::endl;\r\n\r\n    return tag_diff;\r\n}\r\n\r\ndouble test_dnnl_gemm_bf16bf16f32_cvt(float *A, float *B, float *C, int m, int n, int k, bfloat16 *A_bf16, bfloat16 *B_bf16, bfloat16 *C_bf16)\r\n{\r\n    dnnl::impl::cvt_float_to_bfloat16(A_bf16, A, m*k);\r\n    dnnl_gemm_bf16bf16f32('N', 'N', m, n, k, 1.0, A_bf16, k, B_bf16, n, 0.0, C, n);\r\n\r\n    auto tag_1 = std::chrono::high_resolution_clock::now();\r\n    for (int i = 0; i < 1000; ++i) {\r\n        dnnl::impl::cvt_float_to_bfloat16(A_bf16, A, m*k);\r\n        dnnl_gemm_bf16bf16f32('N', 'N', m, n, k, 1.0, A_bf16, k, B_bf16, n, 0.0, C, n);\r\n    }\r\n\r\n    auto tag_2 = std::chrono::high_resolution_clock::now();\r\n    auto tag_diff = std::chrono::duration<double>(tag_2 - tag_1).count();\r\n    std::cout << \"result: \" << C[0] << \",\" << C[m*n-1] << std::endl;\r\n\r\n    return tag_diff;\r\n}\r\n\r\ndouble test_dnnl_gemm_bf16bf16f32_transB_cvt(float *A, float *B, float *C, int m, int n, int k, bfloat16 *A_bf16, bfloat16 *B_bf16, bfloat16 *C_bf16)\r\n{\r\n\r\n    dnnl::impl::cvt_float_to_bfloat16(A_bf16, A, m*k);\r\n    dnnl_gemm_bf16bf16f32('N', 'T', m, n, k, 1.0, A_bf16, k, B_bf16, k, 0.0, C, n);\r\n\r\n    auto tag_1 = std::chrono::high_resolution_clock::now();\r\n    for (int i = 0; i < 1000; ++i) {\r\n        dnnl::impl::cvt_float_to_bfloat16(A_bf16, A, m*k);\r\n        dnnl_gemm_bf16bf16f32('N', 'T', m, n, k, 1.0, A_bf16, k, B_bf16, k, 0.0, C, n);\r\n    }\r\n\r\n    auto tag_2 = std::chrono::high_resolution_clock::now();\r\n    auto tag_diff = std::chrono::duration<double>(tag_2 - tag_1).count();\r\n    std::cout << \"result: \" << C[0] << \",\" << C[m*n-1] << std::endl;\r\n\r\n    return tag_diff;\r\n}\r\n\r\ndouble test_dnnl_gemm_bf16bf16f32_omp_cvt(float *A, float *B, float *C, int m, int n, int k, bfloat16 *A_bf16, bfloat16 *B_bf16, bfloat16 *C_bf16)\r\n{\r\n    #pragma omp parallel for num_threads(omp_get_num_procs())\r\n    for (int i = 0; i < m; ++i)\r\n        dnnl::impl::cvt_float_to_bfloat16(A_bf16+i*k, A+i*k, k);\r\n    dnnl_gemm_bf16bf16f32('N', 'N', m, n, k, 1.0, A_bf16, k, B_bf16, n, 0.0, C, n);\r\n\r\n    auto tag_1 = std::chrono::high_resolution_clock::now();\r\n    for (int i = 0; i < 1000; ++i) {\r\n        #pragma omp parallel for num_threads(omp_get_num_procs())\r\n        for (int i = 0; i < m; ++i)\r\n            dnnl::impl::cvt_float_to_bfloat16(A_bf16+i*k, A+i*k, k);\r\n\tdnnl_gemm_bf16bf16f32('N', 'N', m, n, k, 1.0, A_bf16, k, B_bf16, n, 0.0, C, n);\r\n    }\r\n\r\n    auto tag_2 = std::chrono::high_resolution_clock::now();\r\n    auto tag_diff = std::chrono::duration<double>(tag_2 - tag_1).count();\r\n    std::cout << \"result: \" << C[0] << \",\" << C[m*n-1] << std::endl;\r\n\r\n    return tag_diff;\r\n}\r\n\r\ndouble test_dnnl_gemm_bf16bf16f32_transB_omp_cvt(float *A, float *B, float *C, int m, int n, int k, bfloat16 *A_bf16, bfloat16 *B_bf16, bfloat16 *C_bf16)\r\n{\r\n    #pragma omp parallel for num_threads(omp_get_num_procs())\r\n    for (int i = 0; i < m; ++i)\r\n        dnnl::impl::cvt_float_to_bfloat16(A_bf16+i*k, A+i*k, k);\r\n    dnnl_gemm_bf16bf16f32('N', 'T', m, n, k, 1.0, A_bf16, k, B_bf16, k, 0.0, C, n);\r\n\r\n    auto tag_1 = std::chrono::high_resolution_clock::now();\r\n    for (int i = 0; i < 1000; ++i) {\r\n        #pragma omp parallel for num_threads(omp_get_num_procs())\r\n        for (int i = 0; i < m; ++i)\r\n            dnnl::impl::cvt_float_to_bfloat16(A_bf16+i*k, A+i*k, k);\r\n\tdnnl_gemm_bf16bf16f32('N', 'T', m, n, k, 1.0, A_bf16, k, B_bf16, k, 0.0, C, n);\r\n    }\r\n\r\n    auto tag_2 = std::chrono::high_resolution_clock::now();\r\n    auto tag_diff = std::chrono::duration<double>(tag_2 - tag_1).count();\r\n    std::cout << \"result: \" << C[0] << \",\" << C[m*n-1] << std::endl;\r\n\r\n    return tag_diff;\r\n}\r\n\r\ndouble test_dnnl_cvt_float_to_bfloat16(float *A, float *B, float *C, int m, int n, int k, bfloat16 *A_bf16, bfloat16 *B_bf16, bfloat16 *C_bf16)\r\n{\r\n    dnnl::impl::cvt_float_to_bfloat16(A_bf16, A, m*k);\r\n\r\n    auto tag_1 = std::chrono::high_resolution_clock::now();\r\n    for (int i = 0; i < 1000; ++i) {\r\n        dnnl::impl::cvt_float_to_bfloat16(A_bf16, A, m*k);\r\n    }\r\n\r\n    auto tag_2 = std::chrono::high_resolution_clock::now();\r\n    auto tag_diff = std::chrono::duration<double>(tag_2 - tag_1).count();\r\n    std::cout << \"result: \" << C[0] << \",\" << C[m*n-1] << std::endl;\r\n\r\n    return tag_diff;\r\n}\r\n\r\ndouble test_dnnl_omp_cvt_float_to_bfloat16(float *A, float *B, float *C, int m, int n, int k, bfloat16 *A_bf16, bfloat16 *B_bf16, bfloat16 *C_bf16)\r\n{\r\n    #pragma omp parallel for num_threads(omp_get_num_procs())\r\n    for (int i = 0; i < m; ++i)\r\n        dnnl::impl::cvt_float_to_bfloat16(A_bf16+i*k, A+i*k, k);\r\n\r\n    auto tag_1 = std::chrono::high_resolution_clock::now();\r\n    for (int i = 0; i < 1000; ++i) {\r\n        #pragma omp parallel for num_threads(omp_get_num_procs())\r\n        for (int i = 0; i < m; ++i)\r\n            dnnl::impl::cvt_float_to_bfloat16(A_bf16+i*k, A+i*k, k);\r\n    }\r\n\r\n    auto tag_2 = std::chrono::high_resolution_clock::now();\r\n    auto tag_diff = std::chrono::duration<double>(tag_2 - tag_1).count();\r\n    std::cout << \"result: \" << C[0] << \",\" << C[m*n-1] << std::endl;\r\n\r\n    return tag_diff;\r\n}\r\n\r\ndouble test_dnnl_cvt_bfloat16_to_float(float *A, float *B, float *C, int m, int n, int k, bfloat16 *A_bf16, bfloat16 *B_bf16, bfloat16 *C_bf16)\r\n{\r\n    dnnl::impl::cvt_bfloat16_to_float(A, A_bf16, m*k);\r\n\r\n    auto tag_1 = std::chrono::high_resolution_clock::now();\r\n    for (int i = 0; i < 1000; ++i) {\r\n        dnnl::impl::cvt_bfloat16_to_float(A, A_bf16, m*k);\r\n    }\r\n\r\n    auto tag_2 = std::chrono::high_resolution_clock::now();\r\n    auto tag_diff = std::chrono::duration<double>(tag_2 - tag_1).count();\r\n    std::cout << \"result: \" << C[0] << \",\" << C[m*n-1] << std::endl;\r\n\r\n    return tag_diff;\r\n}\r\n\r\ndouble test_dnnl_omp_cvt_bfloat16_to_float(float *A, float *B, float *C, int m, int n, int k, bfloat16 *A_bf16, bfloat16 *B_bf16, bfloat16 *C_bf16)\r\n{\r\n    #pragma omp parallel for num_threads(omp_get_num_procs())\r\n    for (int i = 0; i < m; ++i)\r\n        dnnl::impl::cvt_bfloat16_to_float(A+i*k, A_bf16+i*k, k);\r\n\r\n    auto tag_1 = std::chrono::high_resolution_clock::now();\r\n    for (int i = 0; i < 1000; ++i) {\r\n        #pragma omp parallel for num_threads(omp_get_num_procs())\r\n        for (int i = 0; i < m; ++i)\r\n            dnnl::impl::cvt_bfloat16_to_float(A+i*k, A_bf16+i*k, k);\r\n    }\r\n\r\n    auto tag_2 = std::chrono::high_resolution_clock::now();\r\n    auto tag_diff = std::chrono::duration<double>(tag_2 - tag_1).count();\r\n    std::cout << \"result: \" << C[0] << \",\" << C[m*n-1] << std::endl;\r\n\r\n    return tag_diff;\r\n}\r\n\r\ntemplate <typename T_A, typename T_B, typename T_bias, typename T_C>\r\ndouble test_dnnl_inner_product(engine eng, stream stm, T_A* A_buf, T_B* B_buf, T_bias* bias_buf, T_C* C_buf, int m, int n, int k)\r\n{\r\n    InnerProduct(eng, stm, A_buf, B_buf, bias_buf, C_buf, m, n, k);\r\n\r\n    auto tag_1 = std::chrono::high_resolution_clock::now();\r\n    for (int i = 0; i < 1000; ++i) {\r\n        InnerProduct(eng, stm, A_buf, B_buf, bias_buf, C_buf, m, n, k);\r\n    }\r\n\r\n    auto tag_2 = std::chrono::high_resolution_clock::now();\r\n    auto tag_diff = std::chrono::duration<double>(tag_2 - tag_1).count();\r\n    std::cout << \"result: \" << C_buf[0] << \",\" << C_buf[m*n-1] << std::endl;\r\n\r\n    return tag_diff;\r\n}\r\n\r\ntemplate <typename T_A, typename T_B, typename T_bias, typename T_C>\r\ndouble test_dnnl_inner_product_v2(engine eng, stream stm, T_A* A_buf, T_B* B_buf, T_bias* bias_buf, T_C* C_buf, int m, int n, int k)\r\n{\r\n    InnerProduct_v2(eng, stm, A_buf, B_buf, bias_buf, C_buf, m, n, k);\r\n\r\n    auto tag_1 = std::chrono::high_resolution_clock::now();\r\n    for (int i = 0; i < 1000; ++i) {\r\n        InnerProduct_v2(eng, stm, A_buf, B_buf, bias_buf, C_buf, m, n, k);\r\n    }\r\n\r\n    auto tag_2 = std::chrono::high_resolution_clock::now();\r\n    auto tag_diff = std::chrono::duration<double>(tag_2 - tag_1).count();\r\n    std::cout << \"result: \" << C_buf[0] << \",\" << C_buf[m*n-1] << std::endl;\r\n    // std::cout << \"result: \" << (bfloat16)933.023 << std::endl;\r\n\r\n    return tag_diff;\r\n}\r\n\r\ntemplate <typename T_A, typename T_B, typename T_bias, typename T_C>\r\ndouble test_dnnl_inner_product_eltwise(engine eng, stream stm, T_A* A_buf, T_B* B_buf, T_bias* bias_buf, T_C* C_buf, int m, int n, int k)\r\n{\r\n    InnerProduct_eltwise(eng, stm, A_buf, B_buf, bias_buf, C_buf, m, n, k);\r\n\r\n    auto tag_1 = std::chrono::high_resolution_clock::now();\r\n    for (int i = 0; i < 1000; ++i) {\r\n        InnerProduct_eltwise(eng, stm, A_buf, B_buf, bias_buf, C_buf, m, n, k);\r\n    }\r\n\r\n    auto tag_2 = std::chrono::high_resolution_clock::now();\r\n    auto tag_diff = std::chrono::duration<double>(tag_2 - tag_1).count();\r\n    std::cout << \"result: \" << C_buf[0] << \",\" << C_buf[m*n-1] << std::endl;\r\n\r\n    return tag_diff;\r\n}\r\n\r\ntemplate <typename T_A, typename T_B, typename T_bias, typename T_C>\r\ndouble test_dnnl_matmul(engine eng, stream stm, T_A* A_buf, T_B* B_buf, T_bias* bias_buf, T_C* C_buf, int m, int n, int k)\r\n{\r\n    MatMul(eng, stm, A_buf, B_buf, bias_buf, C_buf, m, n, k);\r\n\r\n    auto tag_1 = std::chrono::high_resolution_clock::now();\r\n    for (int i = 0; i < 1000; ++i) {\r\n        MatMul(eng, stm, A_buf, B_buf, bias_buf, C_buf, m, n, k);\r\n    }\r\n\r\n    auto tag_2 = std::chrono::high_resolution_clock::now();\r\n    auto tag_diff = std::chrono::duration<double>(tag_2 - tag_1).count();\r\n    std::cout << \"result: \" << C_buf[0] << \",\" << C_buf[m*n-1] << std::endl;\r\n\r\n    return tag_diff;\r\n}\r\n\r\ntemplate <typename T_A, typename T_B, typename T_C>\r\ndouble test_dnnl_matmul2(engine eng, stream stm, T_A* A_buf, T_B* B_buf, T_C* C_buf, int m, int n, int k)\r\n{\r\n    MatMul2(eng, stm, A_buf, B_buf, C_buf, m, n, k);\r\n\r\n    auto tag_1 = std::chrono::high_resolution_clock::now();\r\n    for (int i = 0; i < 1000; ++i) {\r\n        MatMul2(eng, stm, A_buf, B_buf, C_buf, m, n, k);\r\n    }\r\n\r\n    auto tag_2 = std::chrono::high_resolution_clock::now();\r\n    auto tag_diff = std::chrono::duration<double>(tag_2 - tag_1).count();\r\n    std::cout << \"result: \" << C_buf[0] << \",\" << C_buf[m*n-1] << std::endl;\r\n\r\n    return tag_diff;\r\n}\r\n\r\ntemplate <typename T_A, typename T_B, typename T_C>\r\ndouble test_dnnl_matmul2_eltwise(engine eng, stream stm, T_A* A_buf, T_B* B_buf, T_C* C_buf, int m, int n, int k)\r\n{\r\n    MatMul2_eltwise(eng, stm, A_buf, B_buf, C_buf, m, n, k);\r\n\r\n    auto tag_1 = std::chrono::high_resolution_clock::now();\r\n    for (int i = 0; i < 1000; ++i) {\r\n        MatMul2_eltwise(eng, stm, A_buf, B_buf, C_buf, m, n, k);\r\n    }\r\n\r\n    auto tag_2 = std::chrono::high_resolution_clock::now();\r\n    auto tag_diff = std::chrono::duration<double>(tag_2 - tag_1).count();\r\n    std::cout << \"result: \" << C_buf[0] << \",\" << C_buf[m*n-1] << std::endl;\r\n\r\n    return tag_diff;\r\n}\r\n\r\ntemplate <typename T_A, typename T_B, typename T_C>\r\ndouble test_dnnl_batchmatmul(engine eng, stream stm, T_A* A_buf, T_B* B_buf, T_C* C_buf, int mb, int m, int n, int k)\r\n{\r\n    BatchMatMul(eng, stm, A_buf, B_buf, C_buf, mb, m, n, k);\r\n\r\n    auto tag_1 = std::chrono::high_resolution_clock::now();\r\n    for (int i = 0; i < 1000; ++i) {\r\n        BatchMatMul(eng, stm, A_buf, B_buf, C_buf, mb, m, n, k);\r\n    }\r\n\r\n    auto tag_2 = std::chrono::high_resolution_clock::now();\r\n    auto tag_diff = std::chrono::duration<double>(tag_2 - tag_1).count();\r\n    std::cout << \"result: \" << C_buf[0] << \",\" << C_buf[m*n-1] << std::endl;\r\n\r\n    return tag_diff;\r\n}\r\n\r\n/*\r\nstruct Code : Xbyak::CodeGenerator {\r\n    const Xbyak::Reg64& src;\r\n    const Xbyak::Reg64& dst;\r\n    const Xbyak::Reg32& loop;\r\n    Code()\r\n        : src(rsi)\r\n        , dst(rdi)\r\n        , loop(edx)\r\n    {\r\n        Xbyak::Label l0;\r\n        L(l0);\r\n\r\n        vcvtneps2bf16(ymm0, zword[src]);\r\n        vmovups(yword[dst], ymm0);\r\n        add(src, 64);\r\n        add(dst, 32);\r\n\r\n        dec(loop);\r\n        jg(l0, T_NEAR);\r\n\r\n        mov(eax, loop);\r\n        ret();\r\n    }\r\n};\r\n\r\ndouble test_jit_cvt_float_to_bfloat16(float *A, float *B, float *C, int m, int n, int k, bfloat16 *A_bf16, bfloat16 *B_bf16, bfloat16 *C_bf16)\r\n{\r\n    Code c;\r\n    int (*f)(void*, void*, int) = c.getCode<int (*)(void*, void*, int)>();\r\n    int num = m*k/16;\r\n    int ret = f(A_bf16, A, num);\r\n\r\n    auto tag_1 = std::chrono::high_resolution_clock::now();\r\n    for (int i = 0; i < 1000; ++i) {\r\n        f(A_bf16, A, num);\r\n    }\r\n\r\n    auto tag_2 = std::chrono::high_resolution_clock::now();\r\n    auto tag_diff = std::chrono::duration<double>(tag_2 - tag_1).count();\r\n    std::cout << \"result: \" << C[0] << \",\" << C[m*n-1] << std::endl;\r\n\r\n    return tag_diff;\r\n}\r\n*/\r\n", "meta": {"hexsha": "91bb178e1ed2f126389f2b5972684c0a63032d39", "size": 29411, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tools/gemm_bench/gemmbench_dnnl.cc", "max_stars_repo_name": "yao-matrix/mProto", "max_stars_repo_head_hexsha": "e5fecce2693056ac53f7d34d00801829ea1094c3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2016-11-06T04:55:11.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-18T06:56:10.000Z", "max_issues_repo_path": "tools/gemm_bench/gemmbench_dnnl.cc", "max_issues_repo_name": "yao-matrix/mProto", "max_issues_repo_head_hexsha": "e5fecce2693056ac53f7d34d00801829ea1094c3", "max_issues_repo_licenses": ["Apache-2.0"], "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/gemm_bench/gemmbench_dnnl.cc", "max_forks_repo_name": "yao-matrix/mProto", "max_forks_repo_head_hexsha": "e5fecce2693056ac53f7d34d00801829ea1094c3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2016-11-27T01:08:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-11T05:32:04.000Z", "avg_line_length": 46.0987460815, "max_line_length": 194, "alphanum_fraction": 0.6219101697, "num_tokens": 11386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.47293822036194305}}
{"text": "/*\n@copyright Louis Dionne 2014\nDistributed under the Boost Software License, Version 1.0.\n(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n */\n\n#include <boost/hana/foldable/mcd.hpp>\n\n#include <boost/hana/detail/assert.hpp>\n#include <boost/hana/detail/minimal/foldable.hpp>\n#include <boost/hana/integral.hpp>\nusing namespace boost::hana;\n\n\ntemplate <typename mcd>\nvoid test() {\n    constexpr auto foldable = detail::minimal::foldable<mcd>;\n\n    BOOST_HANA_CONSTANT_ASSERT(product(foldable()) == int_<1>);\n    BOOST_HANA_CONSTANT_ASSERT(product(foldable(int_<2>)) == int_<2>);\n    BOOST_HANA_CONSTANT_ASSERT(product(foldable(int_<2>, int_<3>)) == int_<2 * 3>);\n    BOOST_HANA_CONSTANT_ASSERT(product(foldable(int_<2>, int_<3>, int_<4>)) == int_<2 * 3 * 4>);\n    BOOST_HANA_CONSTANT_ASSERT(product(foldable(int_<2>, int_<3>, int_<4>, int_<5>)) == int_<2 * 3 * 4 * 5>);\n\n    BOOST_HANA_CONSTEXPR_ASSERT(product(foldable(2)) == 2);\n    BOOST_HANA_CONSTEXPR_ASSERT(product(foldable(2, 3)) == 2 * 3);\n    BOOST_HANA_CONSTEXPR_ASSERT(product(foldable(2, 3, 4)) == 2 * 3 * 4);\n    BOOST_HANA_CONSTEXPR_ASSERT(product(foldable(2, 3, 4, 5)) == 2 * 3 * 4 * 5);\n}\n\nint main() {\n    test<Foldable::mcd>();\n    test<Foldable::unpack_mcd>();\n}\n", "meta": {"hexsha": "812959d2f886f5919d5dad7a30fc431c26d98236", "size": 1260, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/foldable/product.cpp", "max_stars_repo_name": "rbock/hana", "max_stars_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-05-07T14:29:13.000Z", "max_stars_repo_stars_event_max_datetime": "2015-07-04T10:59:46.000Z", "max_issues_repo_path": "test/foldable/product.cpp", "max_issues_repo_name": "rbock/hana", "max_issues_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/foldable/product.cpp", "max_forks_repo_name": "rbock/hana", "max_forks_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.0, "max_line_length": 109, "alphanum_fraction": 0.6944444444, "num_tokens": 391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879312056025699, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.47290713750052166}}
{"text": "#include <boost/graph/sloan_ordering.hpp>\n", "meta": {"hexsha": "627ff47bc9254050eb2e8d558bac49b0620b6523", "size": 42, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_graph_sloan_ordering.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_graph_sloan_ordering.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_graph_sloan_ordering.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 21.0, "max_line_length": 41, "alphanum_fraction": 0.8095238095, "num_tokens": 10, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.47290713152284053}}
{"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 kahalesmilesection.hpp\n    \\brief Arbitrage free smile section using a C^1 inter- and extrapolation\n   method proposed by Kahale, see\n   http://www.risk.net/data/Pay_per_view/risk/technical/2004/0504_tech_option2.pdf\n   Exponential extrapolation for high strikes can be used alternatively to avoid\n   a too slowly decreasing call price function. Note that in the leftmost\n   interval and right from the last grid point the input smile is always\n   replaced by the extrapolating functional forms, so if you are sure that the\n   input smile is globally arbitrage free and you do not want to change it in\n   these strike regions you should not use this class at all.\n   Input smile sections with a shift are handled accordingly, normal input\n   smile section are not possible though.\n*/\n\n#ifndef quantlib_kahale_smile_section_hpp\n#define quantlib_kahale_smile_section_hpp\n\n#include <ql/termstructures/volatility/smilesection.hpp>\n#include <ql/pricingengines/blackformula.hpp>\n#include <ql/math/solvers1d/brent.hpp>\n#include <ql/termstructures/volatility/smilesectionutils.hpp>\n#if defined(__GNUC__) && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 8)) || (__GNUC__ > 4))\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wunused-local-typedefs\"\n#endif\n#include <boost/math/distributions/normal.hpp>\n#if defined(__GNUC__) && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 8)) || (__GNUC__ > 4))\n#pragma GCC diagnostic pop\n#endif\n#include <vector>\n#include <utility>\n\n// numerical constants, still experimental\n#define QL_KAHALE_FMAX QL_MAX_REAL\n#define QL_KAHALE_SMAX 5.0\n#define QL_KAHALE_ACC 1E-12\n#define QL_KAHALE_EPS QL_EPSILON\n\nnamespace QuantLib {\n\n    class KahaleSmileSection : public SmileSection {\n\n      public:\n        struct cFunction {\n            // this is just a helper class where we do not want virtual\n            // functions\n            cFunction(Real f, Real s, Real a, Real b)\n                : f_(f), s_(s), a_(a), b_(b), exponential_(false) {}\n            cFunction(Real a, Real b) : a_(a), b_(b), exponential_(true) {}\n            Real operator()(Real k) {\n                if (exponential_)\n                    return std::exp(-a_ * k + b_);\n                if (s_ < QL_EPSILON)\n                    return std::max(f_ - k, 0.0) + a_ * k + b_;\n                boost::math::normal normal;\n                Real d1 = std::log(f_ / k) / s_ + s_ / 2.0;\n                Real d2 = d1 - s_;\n                return f_ * boost::math::cdf(normal, d1) -\n                       k * boost::math::cdf(normal, d2) + a_ * k + b_;\n            }\n            Real f_, s_, a_, b_;\n            const bool exponential_;\n        };\n\n        struct aHelper {\n            aHelper(Real k0, Real k1, Real c0, Real c1, Real c0p, Real c1p)\n                : k0_(k0), k1_(k1), c0_(c0), c1_(c1), c0p_(c0p), c1p_(c1p) {}\n            Real operator()(Real a) const {\n                boost::math::normal normal;\n                Real d20 = boost::math::quantile(normal, -c0p_ + a);\n                Real d21 = boost::math::quantile(normal, -c1p_ + a);\n                Real alpha = (d20 - d21) / (std::log(k0_) - std::log(k1_));\n                Real beta = d20 - alpha * std::log(k0_);\n                s_ = -1.0 / alpha;\n                f_ = std::exp(s_ * (beta + s_ / 2.0));\n                QL_REQUIRE(f_ < QL_KAHALE_FMAX, \"dummy\"); // this is caught\n                cFunction cTmp(f_, s_, a, 0.0);\n                b_ = c0_ - cTmp(k0_);\n                cFunction c(f_, s_, a, b_);\n                return c(k1_) - c1_;\n            }\n            Real k0_, k1_, c0_, c1_, c0p_, c1p_;\n            mutable Real s_, f_, b_;\n        };\n\n        struct sHelper {\n            sHelper(Real k0, Real c0, Real c0p) : k0_(k0), c0_(c0), c0p_(c0p) {}\n            Real operator()(Real s) const {\n                s = std::max(s, 0.0);\n                boost::math::normal normal;\n                Real d20 = boost::math::quantile(normal, -c0p_);\n                f_ = k0_ * std::exp(s * d20 + s * s / 2.0);\n                QL_REQUIRE(f_ < QL_KAHALE_FMAX, \"dummy\"); // this is caught\n                cFunction c(f_, s, 0.0, 0.0);\n                return c(k0_) - c0_;\n            }\n            Real k0_, c0_, c0p_;\n            mutable Real f_;\n        };\n\n        struct sHelper1 {\n            sHelper1(Real k1, Real c0, Real c1, Real c1p)\n                : k1_(k1), c0_(c0), c1_(c1), c1p_(c1p) {}\n            Real operator()(Real s) const {\n                s = std::max(s, 0.0);\n                boost::math::normal normal;\n                Real d21 = boost::math::quantile(normal, -c1p_);\n                f_ = k1_ * std::exp(s * d21 + s * s / 2.0);\n                QL_REQUIRE(f_ < QL_KAHALE_FMAX, \"dummy\"); // this is caught\n                b_ = c0_ - f_;\n                cFunction c(f_, s, 0.0, b_);\n                return c(k1_) - c1_;\n            }\n            Real k1_, c0_, c1_, c1p_;\n            mutable Real f_, b_;\n        };\n\n        KahaleSmileSection(const boost::shared_ptr<SmileSection> source,\n                           const Real atm = Null<Real>(),\n                           const bool interpolate = false,\n                           const bool exponentialExtrapolation = false,\n                           const bool deleteArbitragePoints = false,\n                           const std::vector<Real> &moneynessGrid =\n                               std::vector<Real>(),\n                           const Real gap = 1.0E-5,\n                           const int forcedLeftIndex = -1,\n                           const int forcedRightIndex = QL_MAX_INTEGER);\n\n        Real minStrike() const { return 0.0; }\n        Real maxStrike() const { return QL_MAX_REAL; }\n        Real atmLevel() const { return f_; }\n        const Date& exerciseDate() const { return source_->exerciseDate(); }\n        Time exerciseTime() const { return source_->exerciseTime(); }\n        const DayCounter& dayCounter() const { return source_->dayCounter(); }\n        const Date& referenceDate() const { return source_->referenceDate(); }\n        const VolatilityType volatilityType() const {\n            return source_->volatilityType();\n        }\n        const Real shift() const { return source_->shift(); }\n\n        Real leftCoreStrike() const { return k_[leftIndex_]; }\n        Real rightCoreStrike() const { return k_[rightIndex_]; }\n\n        std::pair<Size, Size> coreIndices() const {\n            return std::make_pair(leftIndex_, rightIndex_);\n        }\n\n        Real optionPrice(Rate strike, Option::Type type = Option::Call,\n                         Real discount = 1.0) const;\n\n      protected:\n        Volatility volatilityImpl(Rate strike) const;\n\n      private:\n        Size index(Rate strike) const;\n        void compute();\n        boost::shared_ptr<SmileSection> source_;\n        std::vector<Real> moneynessGrid_, k_, c_;\n        Real f_;\n        const Real gap_;\n        Size leftIndex_, rightIndex_;\n        std::vector<boost::shared_ptr<cFunction> > cFunctions_;\n        const bool interpolate_, exponentialExtrapolation_;\n        int forcedLeftIndex_, forcedRightIndex_;\n        boost::shared_ptr<SmileSectionUtils> ssutils_;\n    };\n}\n\n#endif\n", "meta": {"hexsha": "43085453706f5f9b7bd09dde76dba7b20eb55332", "size": 7919, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "QuantLib/ql/termstructures/volatility/kahalesmilesection.hpp", "max_stars_repo_name": "txu2014/quantlib", "max_stars_repo_head_hexsha": "95c7d94906c30d0c3c4e0758a2ebfe2a62b075ec", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "QuantLib/ql/termstructures/volatility/kahalesmilesection.hpp", "max_issues_repo_name": "txu2014/quantlib", "max_issues_repo_head_hexsha": "95c7d94906c30d0c3c4e0758a2ebfe2a62b075ec", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "QuantLib/ql/termstructures/volatility/kahalesmilesection.hpp", "max_forks_repo_name": "txu2014/quantlib", "max_forks_repo_head_hexsha": "95c7d94906c30d0c3c4e0758a2ebfe2a62b075ec", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.8994708995, "max_line_length": 87, "alphanum_fraction": 0.5799974744, "num_tokens": 2061, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.47290713152284053}}
{"text": "/*\n   For more information, please see: http://software.sci.utah.edu\n\n   The MIT License\n\n   Copyright (c) 2020 Scientific Computing and Imaging Institute,\n   University of Utah.\n\n   Permission is hereby granted, free of charge, to any person obtaining a\n   copy of this software and associated documentation files (the \"Software\"),\n   to deal in the Software without restriction, including without limitation\n   the rights to use, copy, modify, merge, publish, distribute, sublicense,\n   and/or sell copies of the Software, and to permit persons to whom the\n   Software is furnished to do so, subject to the following conditions:\n\n   The above copyright notice and this permission notice shall be included\n   in all copies or substantial portions of the Software.\n\n   THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n   DEALINGS IN THE SOFTWARE.\n*/\n\n\n/*\n*  BuildBEMatrix.cc:  class to build Boundary Elements matrix\n*\n*  Written by:\n*   Saeed Babaeizadeh\n*   Northeastern University\n*   January 2006\n*/\n\n#include <Core/Algorithms/Legacy/Forward/BuildBEMatrixAlgo.h>\n\n#include <algorithm>\n#include <map>\n#include <iostream>\n#include <string>\n#include <fstream>\n#include <numeric>\n#include <boost/range/adaptors.hpp>\n#include <boost/range/algorithm/copy.hpp>\n\n#include <Core/Datatypes/DenseMatrix.h>\n#include <Core/Datatypes/BlockMatrix.h>\n#include <Core/Basis/TriLinearLgn.h>\n#include <Core/Datatypes/Legacy/Field/Field.h>\n#include <Core/Datatypes/Legacy/Field/TriSurfMesh.h>\n#include <Core/GeometryPrimitives/Vector.h>\n#include <Core/GeometryPrimitives/Point.h>\n#include <Core/GeometryPrimitives/PointVectorOperators.h>\n\nusing namespace SCIRun;\nusing namespace SCIRun::Core::Algorithms::Forward;\nusing namespace SCIRun::Core::Datatypes;\nusing namespace SCIRun::Core::Geometry;\n\nALGORITHM_PARAMETER_DEF(Forward, FieldNameList);\nALGORITHM_PARAMETER_DEF(Forward, FieldTypeList);\nALGORITHM_PARAMETER_DEF(Forward, BoundaryConditionList);\nALGORITHM_PARAMETER_DEF(Forward, InsideConductivityList);\nALGORITHM_PARAMETER_DEF(Forward, OutsideConductivityList);\n\nvoid BuildBEMatrixBase::getOmega(\n  const Vector& y1,\n  const Vector& y2,\n  const Vector& y3,\n  DenseMatrix& coef)\n{\n  /*\n  This function deals with the analytical solutions of the various integrals in the stiffness matrix\n  The function is concerned with the integrals of the linear interpolations functions over the triangles\n  and takes care of the solid spherical angle. As in most cases not all values are needed the computation\n  is split up in integrals from one surface to another one\n\n  The computational scheme follows the analytical formulas derived by the\n  de Munck 1992 (IEEE Trans Biomed Engng, 39-9, pp 986-90)\n  */\n  const double epsilon  = 1e-12;\n  Vector y21 = y2 - y1;\n  Vector y32 = y3 - y2;\n  Vector y13 = y1 - y3;\n\n  Vector Ny( y1.length() , y2.length() , y3.length() );\n\n  Vector Nyij( y21.length() , y32.length() , y13.length() );\n\n  Vector gamma( 0 , 0 , 0 );\n  double NomGamma , DenomGamma;\n\n  NomGamma = Ny[0]*Nyij[0] + Dot(y1,y21);\n  DenomGamma = Ny[1]*Nyij[0] + Dot(y2,y21);\n  if (fabs(DenomGamma-NomGamma) > epsilon && (DenomGamma != 0) && NomGamma != 0 ){\n    gamma[0] = -1/Nyij[0] * log(NomGamma/DenomGamma);\n  }\n  NomGamma = Ny[1]*Nyij[1] + Dot(y2,y32);\n  DenomGamma = Ny[2]*Nyij[1] + Dot(y3,y32);\n  if (fabs(DenomGamma-NomGamma) > epsilon && (DenomGamma != 0) && NomGamma != 0 ){\n    gamma[1] = -1/Nyij[1] * log(NomGamma/DenomGamma);\n  }\n  NomGamma = Ny[2]*Nyij[2] + Dot(y3,y13);\n  DenomGamma = Ny[0]*Nyij[2] + Dot(y1,y13);\n  if (fabs(DenomGamma-NomGamma) > epsilon && (DenomGamma != 0) && NomGamma != 0 ){\n    gamma[2] = -1/Nyij[2] * log(NomGamma/DenomGamma);\n  }\n\n  double d = Dot( y1, Cross(y2, y3) );\n\n  Vector OmegaVec = (gamma[2]-gamma[0])*y1 + (gamma[0]-gamma[1])*y2 + (gamma[1]-gamma[2])*y3;\n\n\n\n  /*\n  In order to avoid problems with the arctan used in de Muncks paper\n  the result is tested. A problem is that his formula under certain\n  circumstances leads to unexpected changes of signs. Hence to avoid\n  this, the denominator is checked and 2*pi is added if necessary.\n  The problem without the two pi results in the following situation in\n  which division of the triangle into three pieces results into\n  an opposite sign compared to the spherical angle of the total\n  triangle. These cases are rare but existing.\n  */\n\n  double Nn=0 , Omega=0 ;\n  Nn = Ny[0]*Ny[1]*Ny[2] + Ny[0]*Dot(y2,y3) + Ny[2]*Dot(y1,y2) + Ny[1]*Dot(y3,y1);\n\n  if (Nn > 0)  Omega = 2 * atan( d / Nn );\n  if (Nn < 0)  Omega = 2 * atan( d / Nn ) + 2*M_PI ;\n  if (Nn == 0)\n  {\n    if ( d > 0 )\n      Omega = M_PI;\n    else\n      Omega = -M_PI;\n  }\n\n  Vector N = Cross(y21, -y13);\n  double Zn1 = Dot(Cross(y2, y3) , N);\n  double Zn2 = Dot(Cross(y3, y1) , N);\n  double Zn3 = Dot(Cross(y1, y2) , N);\n\n  double A2 = N.length2();\n  coef(0,0) = (1/A2) * ( Zn1*Omega + d * Dot(y32, OmegaVec) );\n  coef(0,1) = (1/A2) * ( Zn2*Omega + d * Dot(y13, OmegaVec) );\n  coef(0,2) = (1/A2) * ( Zn3*Omega + d * Dot(y21, OmegaVec) );\n\n}\n\nvoid  BuildBEMatrixBase::get_cruse_weights(\n  const Vector& p1,\n  const Vector& p2,\n  const Vector& p3,\n  double s,\n  double r,\n  double area,\n  DenseMatrix& cruse_weights)\n{\n  /*\n  Inputs: p1,p2,p3= cartesian coordiantes of the triangle vertices ;\n  area = triangle area\n  Output: cruse_weights = The weighting factors for the 7 Radon points of the triangle\n  Format of the cruse_weights matrix\n  Radon point 1       Radon Point 2    ...     Radon Point 7\n  Vertex 1 ->\n  Vertex 2 ->\n  Vertex 3 ->\n\n  Set up the local coordinate system around the triangle. This is a 2-D system and\n  for ease of use, the x-axis is chosen as the line between the first and second vertex\n  of the triangle. From that the vertex of the third point is found in local coordinates.\n  */\n\n  // The angle between the F2 and F3, at vertex 1 is (pi - 'alpha').\n  Vector fg2 = p1 - p3;\n  double fg2_length = fg2.length();\n\n  Vector fg3 = p2 - p1;\n  double fg3_length = fg3.length();\n\n  double cos_alpha = - Dot(fg3,fg2) / (fg2_length * fg3_length);\n  double sin_alpha = sqrt(1 - cos_alpha * cos_alpha);\n\n  // Now the vertices in local coordinates\n  Vector locp1(0 , 0 , 0);\n  Vector locp2(fg3_length , 0 , 0);\n  Vector locp3(fg2_length * cos_alpha , fg2_length * sin_alpha , 0);\n\n  DenseMatrix Fx(3, 1);\n  Fx << locp3[0] - locp2[0],\n    locp1[0] - locp3[0],\n    locp2[0] - locp1[0];\n\n  DenseMatrix Fy(3, 1);\n  Fy << locp3[1] - locp2[1],\n    locp1[1] - locp3[1],\n    locp2[1] - locp1[1];\n\n  Vector centroid = (locp1 + locp2 + locp3) / 3;\n  DenseMatrix loc_radpt_x(1, 7);\n  DenseMatrix loc_radpt_y(1, 7);\n  loc_radpt_x(0,0) = centroid[0];\n  loc_radpt_y(0,0) = centroid[1];\n  Vector temp = (1-s) * centroid;\n  loc_radpt_x(0,1) = temp[0] + locp1[0]*s;\n  loc_radpt_y(0,1) = temp[1] + locp1[1]*s;\n  loc_radpt_x(0,2) = temp[0] + locp2[0]*s;\n  loc_radpt_y(0,2) = temp[1] + locp2[1]*s;\n  loc_radpt_x(0,3) = temp[0] + locp3[0]*s;\n  loc_radpt_y(0,3) = temp[1] + locp3[1]*s;\n  temp = (1-r) * centroid;\n  loc_radpt_x(0,4) = temp[0] + locp1[0]*r;\n  loc_radpt_y(0,4) = temp[1] + locp1[1]*r;\n  loc_radpt_x(0,5) = temp[0] + locp2[0]*r;\n  loc_radpt_y(0,5) = temp[1] + locp2[1]*r;\n  loc_radpt_x(0,6) = temp[0] + locp3[0]*r;\n  loc_radpt_y(0,6) = temp[1] + locp3[1]*r;\n\n  auto A = (0.5/area) * (Fy * loc_radpt_x - Fx * loc_radpt_y);\n\n  DenseMatrix ones(1, 7, 1.0);\n  DenseMatrix E(3, 1);\n  /*\n  E is a 1X3 matrix: [1st vertex  ;  2nd vertex  ;  3rd vertex]\n  E = [1/3 ; 1/3 ; 1/3] + (0.5/area)*(Fy*xmid - Fx*ymid);\n  but there is no need to compute the E because by our choice of the\n  local coordinates, it is easy to show that the E is always [1 ; 0 ; 0]!\n  */\n  E << 1,0,0;\n  cruse_weights = (E * ones) - A;\n}\n\nvoid BuildBEMatrixBase::get_g_coef(\n  const Vector& p1,\n  const Vector& p2,\n  const Vector& p3,\n  const Vector& op,\n  double s,\n  double r,\n  const Vector& centroid,\n  DenseMatrix& g_coef)\n{\n  // Inputs: p1,p2,p3= cartesian coordiantes of the triangle vertices ; op= Observation Point\n  // Output: g_coef = G Values (Coefficients) at 7 Radon's points = 1/r\n  Vector radpt = centroid - op;\n  g_coef(0,0) = 1 / radpt.length();\n\n  Vector temp = centroid * (1-s) - op;\n  radpt = temp + p1 * s;\n  g_coef(0,1) = 1 / radpt.length();\n  radpt = temp + p2 * s;\n  g_coef(0,2) = 1 / radpt.length();\n  radpt = temp + p3 * s;\n  g_coef(0,3) = 1 / radpt.length();\n\n  temp = centroid * (1-r) - op;\n  radpt = temp + p1 * r;\n  g_coef(0,4) = 1 / radpt.length();\n  radpt = temp + p2 * r;\n  g_coef(0,5) = 1 / radpt.length();\n  radpt = temp + p3 * r;\n  g_coef(0,6) = 1 / radpt.length();\n}\n\nvoid BuildBEMatrixBase::bem_sing(\n  const Vector& p1,\n  const Vector& p2,\n  const Vector& p3,\n  unsigned int op_n,\n  DenseMatrix& g_values,\n  double s,\n  double r,\n  DenseMatrix& R_W)\n{\n  /*\n  This is Jeroen's method, converted from his Matlab code, for dealing with weightings corresponding to singular triangles\n  */\n  Vector A,B,C,P,BC,BA,AC,AP;\n  DenseMatrix WAPB(3,1);\n  DenseMatrix WAPC(3,1);\n  int one=0,two=1,three=2;\n\n  switch(op_n)\n  {\n  case 0:\n    A = p1; B=p2; C=p3;\n    one=0; two=1; three=2;\n    break;\n  case 1:\n    A = p2; B=p3; C=p1;\n    one=1; two=2; three=0;\n    break;\n  case 2:\n    A = p3; B=p1; C=p2;\n    one=2; two=0; three=1;\n    break;\n  default:;\n  }\n\n  BC=C-B; BA=A-B; AC=C-A;\n  double RL = Dot(BA,BC/BC.length())/BC.length();\n  P=RL*BC+B;\n  AP=A-P;\n  double lAP=AP.length();\n  double lBC=BC.length();\n  double lBP=fabs(RL)*lBC;\n  double lCP=fabs(1-RL)*lBC;\n  double lAB=BA.length();\n  double lAC=AC.length();\n  double a,b,c,w,log_term;\n\n  if(fabs(RL) > 0)\n  {\n    a=lAP; b=lBP; c=lAB;\n    log_term=log( (b+c)/a );\n    WAPB(0,0)=a/2 * log_term;\n    w=1-RL;\n    WAPB(1,0)=a* (( a-c)*(-1+w) + b*w*log_term )/(2*b);\n    w=RL;\n    WAPB(2,0)=a*w *( a-c  +  b*log_term )/(2*b);\n  }\n  else\n  {\n    WAPB(0,0)=0; WAPB(1,0)=0; WAPB(2,0)=0;\n  }\n\n  if(fabs(RL-1) > 0)\n  {\n    a = lAP; b = lCP; c = lAC;\n    log_term = log( (b+c)/a );\n    WAPC(0,0)=a/2 * log_term;\n    w = 1-RL;\n    WAPC(1,0)=a*w *( a-c  +  b*log_term )/(2*b);\n    w = RL;\n    WAPC(2,0)=a* (( a-c)*(-1+w) + b*w*log_term )/(2*b);\n  }\n  else\n  {\n    WAPC(0,0)=0; WAPC(1,0)=0; WAPC(2,0)=0;\n  }\n\n  if(RL<0)\n  {\n    WAPB(0,0)*=-1.0; WAPB(1,0)*=-1.0; WAPB(2,0)*=-1.0;\n  }\n  if(RL>1)\n  {\n    WAPC(0,0)*=-1.0; WAPC(1,0)*=-1.0; WAPC(2,0)*=-1.0;\n  }\n\n  g_values(one,0) = WAPB(0,0) + WAPC(0,0);\n  g_values(two,0) = WAPB(1,0) + WAPC(1,0);\n  g_values(three,0) = WAPB(2,0) + WAPC(2,0);\n}\n\nvoid BuildBEMatrixBase::get_auto_g(\n  const Vector& p1,\n  const Vector& p2,\n  const Vector& p3,\n  unsigned int op_n,\n  DenseMatrix& g_values,\n  double s,\n  double r,\n  DenseMatrix& R_W)\n{\n  /*\n  A routine to solve the Auto G-parameter integral for a triangle from\n  a \"closed\" observation point.\n  The scheme is the standard one for all the BEM routines.\n  Input are the observation point and triangle co-ordinates\n  Input:\n  op_n = observation point number (1, 2 or 3)\n  p1,p2,p3 = triangle co-ordinates (REAL)\n\n  Output:\n  g_values\n  = the total values for the 1/r integral for\n  each of the subtriangles associated with each\n  integration triangle vertex about the observation\n  point defined by the calling\n  program.\n  */\n\n  Vector p5 = (p1 + p2) / 2;\n  Vector p6 = (p2 + p3) / 2;\n  Vector p4 = (p1 + p3) / 2;\n  Vector ctroid = (p1 + p2 + p3) / 3;\n  Vector op;\n\n  switch(op_n)\n  {\n  case 0:\n    op = p1;\n    g_values(0,0) = get_new_auto_g(op, p5, p4) + do_radon_g(p5, ctroid, p4, op, s, r, R_W);\n    g_values(1,0) = do_radon_g(p2, p6, p5, op, s, r, R_W) + do_radon_g(p5, p6, ctroid, op, s, r, R_W);\n    g_values(2,0) = do_radon_g(p3, p4, p6, op, s, r, R_W) + do_radon_g(p4, ctroid, p6, op, s, r, R_W);\n    break;\n  case 1:\n    op = p2;\n    g_values(0,0) = do_radon_g(p1, p5, p4, op, s, r, R_W) + do_radon_g(p5, ctroid, p4, op, s, r, R_W);\n    g_values(1,0) = get_new_auto_g(op, p6, p5) + do_radon_g(p5, p6, ctroid, op, s, r, R_W);\n    g_values(2,0) = do_radon_g(p3, p4, p6, op, s, r, R_W) + do_radon_g(p4, ctroid, p6, op, s, r, R_W);\n    break;\n  case 2:\n    op = p3;\n    g_values(0,0) = do_radon_g(p1, p5, p4, op, s, r, R_W) + do_radon_g(p5, ctroid, p4, op, s, r, R_W);\n    g_values(1,0) = do_radon_g(p2, p6, p5, op, s, r, R_W) + do_radon_g(p5, p6, ctroid, op, s, r, R_W);\n    g_values(2,0) = get_new_auto_g(op, p4, p6) + do_radon_g(p4, ctroid, p6, op, s, r, R_W);\n    break;\n  }\n}\n\ndouble BuildBEMatrixBase::get_new_auto_g(\n  const Vector& op,\n  const Vector& p2,\n  const Vector& p3)\n{\n  //  Inputs: op,p2,p3= cartesian coordiantes of the triangle vertices ; op= Observation Point\n  //  Output: g1 = G value for the triangle for \"auto_g\"\n  //  This function is called from get_auto_g.m\n\n  double delta_min = 0.00001;\n  unsigned int max_number_of_divisions = 256;\n\n  Vector a = p2 - op; double a_mag = a.length();\n  Vector b = p3 - p2; double b_mag = b.length();\n  Vector c = op - p3; double c_mag = c.length();\n\n  Vector aV = Cross(p2 - op, p3 - p2)*0.5;\n  double area = aV.length();\n  double area2 = 2.0*area;\n  double h = (area2) / b_mag;\n  double alfa=0;  if (h<a_mag) alfa = acos(h/a_mag);\n  double AC = a_mag*c_mag;\n  double teta = 0; if (area2<=AC) teta = asin( area2 / AC );\n\n  unsigned int nod = 1;\n  double sai_old = sqrt(area2 * teta);\n  double delta = 1;\n\n  double gama, gama_j, rhoj_1, rhoj, sum, sai_new=0;\n\n  while( (delta >= delta_min) && (nod <= max_number_of_divisions) )\n  {\n    nod = 2*nod;\n    gama = teta / nod;\n    sum = 0;\n    gama_j = 0;\n    rhoj_1 = a_mag;\n    for ( unsigned int j = 1; j <= nod; j++)\n    {\n      gama_j = gama_j + gama;\n      rhoj = h / cos(alfa - gama_j);\n      sum = sum + sqrt( std::fabs(rhoj * rhoj_1) );\n      rhoj_1 = rhoj;\n    }\n    sai_new = sum * sqrt(std::fabs(gama * sin(gama)));\n    delta = 0;\n    if (sai_new + sai_old)\n      delta = std::fabs((sai_new - sai_old) / (sai_new + sai_old));\n    sai_old = sai_new;\n  }\n  return sai_new;\n}\n\n\ndouble BuildBEMatrixBase::do_radon_g(\n  const Vector& p1,\n  const Vector& p2,\n  const Vector& p3,\n  const Vector& op,\n  double s,\n  double r,\n  DenseMatrix& R_W)\n{\n  //  Inputs: p1,p2,p3= cartesian coordiantes of the triangle vertices ; op= Observation Point\n  //  Output: g2 = G value for the triangle for \"auto_g\"\n  //  This function is called from get_auto_g.m\n\n  Vector centroid = (p1 + p2 + p3) / 3;\n\n  DenseMatrix g_coef(1, 7);\n  get_g_coef(p1, p2, p3, op, s, r, centroid, g_coef);\n\n  double g2 = 0;\n  for (int i=0; i<7; i++)   g2 = g2 + g_coef(0,i)*R_W(0,i);\n\n  Vector aV = Cross(p2 - p1, p3 - p2)*0.5;\n\n  return g2 * aV.length();\n}\n\nclass BuildBEMatrixBaseCompute : public BuildBEMatrixBase\n{\npublic:\n  template <class MatrixType>\n  static void make_auto_P_compute(VMesh* hsurf, MatrixType& auto_P, double in_cond, double out_cond, double op_cond);\n\n  template <class MatrixType>\n  static void make_cross_P_compute(VMesh* hsurf1, VMesh* hsurf2, MatrixType& cross_P, double in_cond, double out_cond, double op_cond);\n\n  template <class MatrixType>\n  static void make_auto_G_compute(VMesh* hsurf, MatrixType& auto_G, double in_cond, double out_cond, double op_cond, const std::vector<double>& avInn);\n\n  template <class MatrixType>\n  static void make_cross_G_compute( VMesh*,\n  VMesh*,\n  MatrixType&,\n  double,\n  double,\n  double,\n  const std::vector<double>& );\n};\n\nvoid BuildBEMatrixBase::make_auto_G_allocate(VMesh* hsurf, DenseMatrixHandle &h_GG_)\n{\n  auto nnodes = numNodes(hsurf);\n  h_GG_.reset(new DenseMatrix(nnodes, nnodes, 0.0));\n}\n\nvoid BuildBEMatrixBase::make_auto_G(VMesh* hsurf, DenseMatrixHandle &h_GG_,\ndouble in_cond, double out_cond, double op_cond, const std::vector<double>& avInn)\n{\n  make_auto_G_allocate(hsurf, h_GG_);\n  BuildBEMatrixBaseCompute::make_auto_G_compute(hsurf, *h_GG_, in_cond, out_cond, op_cond, avInn);\n}\n\ntemplate <class MatrixType>\nvoid BuildBEMatrixBaseCompute::make_auto_G_compute(VMesh* hsurf, MatrixType& auto_G,\n  double in_cond, double out_cond, double op_cond, const std::vector<double>& avInn)\n{\n  //const double mult = 1/(2*M_PI)*((out_cond - in_cond)/op_cond);  // op_cond=out_cond for all the surfaces but the outermost surface which in op_cond=in_cond\n  const double mult = 1/(4*M_PI)*(out_cond - in_cond);  // op_cond=out_cond for all the surfaces but the outermost surface which in op_cond=in_cond\n\n  VMesh::Node::array_type nodes;\n\n  VMesh::Node::iterator ni, nie;\n  VMesh::Face::iterator fi, fie;\n  DenseMatrix cruse_weights(3, 7);\n  DenseMatrix g_coef(1, 7);\n  DenseMatrix R_W(1,7); // Radon Points Weights\n  DenseMatrix temp(1,7);\n  DenseMatrix g_values(3, 1);\n\n  double area;\n\n  double sqrt15 = sqrt(15.0);\n  //R_W(0,0) = 9/40; // <- Burak! FIX ME!\n  R_W(0,0) = 9.0/40.0;\n  R_W(0,1) = (155 + sqrt15) / 1200;\n  R_W(0,2) = R_W(0,1);\n  R_W(0,3) = R_W(0,1);\n  R_W(0,4) = (155 - sqrt15) / 1200;\n  R_W(0,5) = R_W(0,4);\n  R_W(0,6) = R_W(0,4);\n\n  double s = (1 - sqrt15) / 7;\n  double r = (1 + sqrt15) / 7;\n\n\n  hsurf->begin(fi); hsurf->end(fie);\n  for (; fi != fie; ++fi)\n  { //! find contributions from every triangle\n    hsurf->get_nodes(nodes, *fi);\n    Vector p1(hsurf->get_point(nodes[0]));\n    Vector p2(hsurf->get_point(nodes[1]));\n    Vector p3(hsurf->get_point(nodes[2]));\n\n    area = avInn[*fi];\n\n    get_cruse_weights(p1, p2, p3, s, r, area, cruse_weights);\n    Vector centroid = (p1 + p2 + p3) / 3.0;\n    hsurf->begin(ni); hsurf->end(nie);\n    for (; ni != nie; ++ni)\n    { //! for every node\n      VMesh::Node::index_type ppi = *ni;\n      Vector op(hsurf->get_point(ppi));\n\n      if (ppi == nodes[0])       bem_sing(p1, p2, p3, 0, g_values, s, r, R_W);\n      else if (ppi == nodes[1])       bem_sing(p1, p2, p3, 1, g_values, s, r, R_W);\n      else if (ppi == nodes[2])       bem_sing(p1, p2, p3, 2, g_values, s, r, R_W);\n      else\n      {\n        get_g_coef(p1, p2, p3, op, s, r, centroid, g_coef);\n\n        for (int i=0; i<7; i++)  temp(0,i) = g_coef(0,i)*R_W(0,i);\n\n        g_values = area * (cruse_weights * temp.transpose());\n      } // else\n\n      for (int i=0; i<3; ++i)\n        auto_G(ppi, nodes[i])+=g_values(i,0)*mult;\n    }\n  }\n}\n\nvoid BuildBEMatrixBase::make_cross_G_allocate(VMesh* hsurf1, VMesh* hsurf2, DenseMatrixHandle &h_GG_)\n{\n  h_GG_.reset(new DenseMatrix(numNodes(hsurf1), numNodes(hsurf2), 0.0));\n}\n\nvoid BuildBEMatrixBase::make_cross_G(VMesh* hsurf1, VMesh* hsurf2, DenseMatrixHandle &h_GG_,\n  double in_cond, double out_cond, double op_cond, const std::vector<double>& avInn)\n{\n  make_cross_G_allocate(hsurf1, hsurf2, h_GG_);\n  BuildBEMatrixBaseCompute::make_cross_G_compute(hsurf1, hsurf2, *h_GG_, in_cond, out_cond, op_cond, avInn);\n}\n\ntemplate <class MatrixType>\nvoid BuildBEMatrixBaseCompute::make_cross_G_compute(VMesh* hsurf1, VMesh* hsurf2, MatrixType& cross_G,\n  double in_cond, double out_cond, double op_cond, const std::vector<double>& avInn)\n{\n  const double mult = 1/(4*M_PI)*(out_cond - in_cond);\n  //   out_cond and in_cond belong to hsurf2 and op_cond is the out_cond of hsurf1 for all the surfaces but the outermost surface which in op_cond=in_cond\n\n  VMesh::Node::array_type nodes;\n\n  VMesh::Node::iterator  ni, nie;\n  VMesh::Face::iterator  fi, fie;\n\n  DenseMatrix cruse_weights(3, 7);\n  DenseMatrix g_coef(1, 7);\n  DenseMatrix R_W(1,7); // Radon Points Weights\n  DenseMatrix temp(1,7);\n  DenseMatrix g_values(3, 1);\n\n  double area;\n\n  double sqrt15 = sqrt(15.0);\n  //R_W(0,0) = 9/40; // <- Burak! FIX ME!\n  R_W(0,0) = 9.0/40.0;\n  R_W(0,1) = (155 + sqrt15) / 1200;\n  R_W(0,2) = R_W(0,1);\n  R_W(0,3) = R_W(0,1);\n  R_W(0,4) = (155 - sqrt15) / 1200;\n  R_W(0,5) = R_W(0,4);\n  R_W(0,6) = R_W(0,4);\n\n  double s = (1 - sqrt15) / 7;\n  double r = (1 + sqrt15) / 7;\n\n  hsurf2->begin(fi); hsurf2->end(fie);\n  for (; fi != fie; ++fi)\n  { //! find contributions from every triangle\n    hsurf2->get_nodes(nodes, *fi);\n    Vector p1(hsurf2->get_point(nodes[0]));\n    Vector p2(hsurf2->get_point(nodes[1]));\n    Vector p3(hsurf2->get_point(nodes[2]));\n\n    area = avInn[*fi];\n\n    get_cruse_weights(p1, p2, p3, s, r, area, cruse_weights);\n    Vector centroid = (p1 + p2 + p3) / 3.0;\n\n    hsurf1->begin(ni); hsurf1->end(nie);\n    for (; ni != nie; ++ni)\n    { //! for every node\n      VMesh::Node::index_type ppi = *ni;\n      Vector op(hsurf1->get_point(ppi));\n      get_g_coef(p1, p2, p3, op, s, r, centroid, g_coef);\n\n      for (int i=0; i<7; i++)  temp(0,i) = g_coef(0,i)*R_W(0,i);\n\n      g_values = area * (cruse_weights * temp.transpose());\n\n      for (int i=0; i<3; ++i)\n        cross_G(ppi, nodes[i])+=g_values(i,0)*mult;\n    }\n  }\n}\n\nvoid BuildBEMatrixBase::make_cross_P_allocate(VMesh* hsurf1, VMesh* hsurf2, DenseMatrixHandle &h_PP_)\n{\n  h_PP_.reset(new DenseMatrix(numNodes(hsurf1), numNodes(hsurf2), 0.0));\n}\n\nvoid BuildBEMatrixBase::make_cross_P(VMesh* hsurf1, VMesh* hsurf2, DenseMatrixHandle &h_PP_,\n  double in_cond, double out_cond, double op_cond)\n{\n  make_cross_P_allocate(hsurf1, hsurf2, h_PP_);\n  BuildBEMatrixBaseCompute::make_cross_P_compute(hsurf1, hsurf2, *h_PP_, in_cond, out_cond, op_cond);\n}\n\ntemplate <class MatrixType>\nvoid BuildBEMatrixBaseCompute::make_cross_P_compute(VMesh* hsurf1, VMesh* hsurf2, MatrixType& cross_P, double in_cond, double out_cond, double op_cond)\n{\n  const double mult = 1/(4*M_PI)*(out_cond - in_cond);\n  //   out_cond and in_cond belong to hsurf2 and op_cond is the out_cond of hsurf1 for all the surfaces but the outermost surface which in op_cond=in_cond\n  VMesh::Node::array_type nodes;\n  DenseMatrix coef(1, 3);\n  int i;\n\n  VMesh::Node::iterator  ni, nie;\n  VMesh::Face::iterator  fi, fie;\n\n  hsurf1->begin(ni); hsurf1->end(nie);\n  for (; ni != nie; ++ni){ //! for every node\n    VMesh::Node::index_type ppi = *ni;\n    Point pp = hsurf1->get_point(ppi);\n\n    hsurf2->begin(fi); hsurf2->end(fie);\n    for (; fi != fie; ++fi){ //! find contributions from every triangle\n\n      hsurf2->get_nodes(nodes, *fi);\n      Vector v1 = hsurf2->get_point(nodes[0]) - pp;\n      Vector v2 = hsurf2->get_point(nodes[1]) - pp;\n      Vector v3 = hsurf2->get_point(nodes[2]) - pp;\n\n      getOmega(v1, v2, v3, coef);\n\n      for (i=0; i<3; ++i)\n        cross_P(ppi, nodes[i])-=coef(0,i)*mult;\n    }\n  }\n}\n\nvoid BuildBEMatrixBase::make_auto_P_allocate(VMesh* hsurf, DenseMatrixHandle &h_PP_)\n{\n  auto nnodes = numNodes(hsurf);\n  h_PP_.reset(new DenseMatrix(nnodes, nnodes, 0.0));\n}\n\nint BuildBEMatrixBase::numNodes(FieldHandle f)\n{\n  return numNodes(f->vmesh());\n}\n\nint BuildBEMatrixBase::numNodes(VMesh* hsurf)\n{\n  VMesh::Node::size_type nsize;\n  hsurf->size(nsize);\n  return static_cast<int>(nsize);\n}\n\ntemplate <class MatrixType>\nvoid BuildBEMatrixBaseCompute::make_auto_P_compute(VMesh* hsurf, MatrixType& auto_P, double in_cond, double out_cond, double op_cond)\n{\n  auto nnodes = auto_P.rows();\n\n\n\n  //const double mult = 1/(2*M_PI)*((out_cond - in_cond)/op_cond);  // op_cond=out_cond for all the surfaces but the outermost surface which in op_cond=in_cond\n  const double mult = 1/(4*M_PI)*(out_cond - in_cond);\n\n  VMesh::Node::array_type nodes;\n  DenseMatrix coef(1, 3);\n\n  VMesh::Node::iterator ni, nie;\n  VMesh::Face::iterator fi, fie;\n\n  unsigned int i;\n\n  hsurf->begin(ni); hsurf->end(nie);\n\n  for (; ni != nie; ++ni){ //! for every node\n    VMesh::Node::index_type ppi = *ni;\n    Point pp = hsurf->get_point(ppi);\n\n    hsurf->begin(fi); hsurf->end(fie);\n\n    for (; fi != fie; ++fi) { //! find contributions from every triangle\n\n      hsurf->get_nodes(nodes, *fi);\n      if (ppi!=nodes[0] && ppi!=nodes[1] && ppi!=nodes[2]){\n        Vector v1 = hsurf->get_point(nodes[0]) - pp;\n        Vector v2 = hsurf->get_point(nodes[1]) - pp;\n        Vector v3 = hsurf->get_point(nodes[2]) - pp;\n\n        getOmega(v1, v2, v3, coef);\n\n        for (i=0; i<3; ++i)\n          auto_P(ppi, nodes[i])-=coef(0,i)*mult;\n      }\n    }\n  }\n\n  //! accounting for autosolid angle\n  auto sumOfRows = auto_P.rowwise().sum().eval();\n  for (i=0; i<nnodes; ++i)\n  {\n    auto_P(i,i) = out_cond - sumOfRows(i);\n  }\n}\n\nvoid BuildBEMatrixBase::make_auto_P(VMesh* hsurf, DenseMatrixHandle &h_PP_,\n  double in_cond, double out_cond, double op_cond)\n{\n  make_auto_P_allocate(hsurf, h_PP_);\n  BuildBEMatrixBaseCompute::make_auto_P_compute(hsurf, *h_PP_, in_cond, out_cond, op_cond);\n}\n\n// precalculate triangles area\nvoid BuildBEMatrixBase::pre_calc_tri_areas(VMesh* hsurf, std::vector<double>& areaV){\n\n  VMesh::Face::iterator  fi, fie;\n\n  hsurf->begin(fi);\n  hsurf->end(fie);\n  for (; fi != fie; ++fi)\n    areaV.push_back(hsurf->get_area(*fi));\n}\n\n// C++ized MollerTrumbore97 Ray Triangle intersection test.\nbool BuildBEMatrixBase::ray_triangle_intersect(double &t,\n  const Point &point,\n  const Vector &dir,\n  const Point &p0,\n  const Point &p1,\n  const Point &p2)\n{\n  // Find vectors for two edges sharing p0.\n  const Vector edge1 = p1 - p0;\n  const Vector edge2 = p2 - p0;\n\n  // begin calculating determinant - also used to calculate U parameter.\n  const Vector pvec = Cross(dir, edge2);\n\n  // if determinant is near zero, ray lies in plane of triangle.\n  const double det = Dot(edge1, pvec);\n  const double EPSILON = 1.0e-6;\n  if (det > -EPSILON && det < EPSILON)\n  {\n    return false;\n  }\n  const double inv_det = 1.0 / det;\n\n  // Calculate distance from vert0 to ray origin.\n  const Vector tvec = point - p0;\n\n  // Calculate U parameter and test bounds.\n  const double u = Dot(tvec, pvec) * inv_det;\n  if (u < 0.0 || u > 1.0)\n  {\n    return false;\n  }\n\n  // Prepare to test V parameter.\n  const Vector qvec = Cross(tvec, edge1);\n\n  // Calculate V parameter and test bounds.\n  const double v = Dot(dir, qvec) * inv_det;\n  if (v < 0.0 || u + v > 1.0)\n  {\n    return false;\n  }\n\n  // Calculate t, ray intersects triangle.\n  t = Dot(edge2, qvec) * inv_det;\n\n  return true;\n}\n\nvoid BuildBEMatrixBase::compute_intersections(std::vector<std::pair<double, int> >\n  &results,\n  const VMesh* mesh,\n  const Point &p, const Vector &v,\n  int marker)\n{\n  VMesh::Face::iterator itr, eitr;\n  mesh->begin(itr);\n  mesh->end(eitr);\n  double t;\n  while (itr != eitr)\n  {\n    VMesh::Node::array_type nodes;\n    mesh->get_nodes(nodes, *itr);\n    Point p0, p1, p2;\n    mesh->get_center(p0, nodes[0]);\n    mesh->get_center(p1, nodes[1]);\n    mesh->get_center(p2, nodes[2]);\n    if (ray_triangle_intersect(t, p, v, p0, p1, p2))\n    {\n      results.push_back(std::make_pair(t, marker));\n    }\n    ++itr;\n  }\n}\n\nstatic bool\n  pair_less(const std::pair<double, int> &a,\n  const std::pair<double, int> &b)\n{\n  return a.first < b.first;\n}\n\nint BuildBEMatrixBase::compute_parent(const std::vector<VMesh*> &meshes, int index)\n{\n  Point point;\n  meshes[index]->get_center(point, VMesh::Node::index_type(0));\n  Vector dir(1.0, 1.0, 1.0);\n  std::vector<std::pair<double, int> > intersections;\n\n  unsigned int i;\n  for (i = 0; i < (unsigned int)meshes.size(); i++)\n  {\n    compute_intersections(intersections, meshes[i], point, dir, i);\n  }\n\n  std::sort(intersections.begin(), intersections.end(), pair_less);\n\n  std::vector<int> counts(meshes.size(), 0);\n  for (i = 0; i < intersections.size(); i++)\n  {\n    if (intersections[i].second == index)\n    {\n      // First odd count is parent.\n      for (int j = i-1; j >= 0; j--)\n      {\n        // TODO: unusual odd/even number test?\n        if (counts[intersections[j].second] & 1)\n        {\n          return intersections[j].second;\n        }\n      }\n      // No odd parent, is outside.\n      return static_cast<int>( meshes.size() );\n    }\n    counts[intersections[i].second]++;\n  }\n\n  // Indeterminate, we should intersect with ourselves.\n  return static_cast<int>( meshes.size() );\n}\n\nbool BuildBEMatrixBase::compute_nesting(std::vector<int> &nesting, const std::vector<VMesh*> &meshes)\n{\n  nesting.resize(meshes.size());\n\n  unsigned int i;\n  for (i = 0; i < (unsigned int)meshes.size(); i++)\n  {\n    nesting[i] = compute_parent(meshes, i);\n  }\n\n  return true;\n}\n\nclass SurfaceAndPoints : public BEMAlgoImpl, public BuildBEMatrixBaseCompute\n{\npublic:\n  MatrixHandle compute(const bemfield_vector& fields) const override;\n};\n\nclass SurfaceToSurface : public BEMAlgoImpl, public BuildBEMatrixBaseCompute\n{\npublic:\n  MatrixHandle compute(const bemfield_vector& fields) const override;\n};\n\nBEMAlgoPtr BEMAlgoImplFactory::create(const bemfield_vector& fields)\n{\n  ///////////////////////////////////////////////////////////////////////////////////////////////////\n  // Check for special case where the potentials need to be evaluated at the nodes of a lead\n  // This case assumes the first input is the surface mesh and the second is the location of the\n  // nodes\n\n  const bemfield_vector::size_type SPECIAL_CASE_LEN = 2;\n\n  if ( fields.size() == SPECIAL_CASE_LEN )\n  {\n    VMesh *surface, *nodes;\n    int surfcount=0, pointcloudcount=0;\n\n    bool meets_conditions = true;\n\n    for (bemfield_vector::size_type i = 0; i < SPECIAL_CASE_LEN; i++)\n    {\n      if (fields[i].surface)\n      {\n        surface = fields[i].field_->vmesh();\n        if (! surface->is_trisurfmesh() ) meets_conditions = false;\n        surfcount++;\n      }\n      else\n      {\n        nodes = fields[i].field_->vmesh();\n        if (! ( nodes->is_pointcloudmesh() ) || nodes->is_curvemesh() )\n        {\n          meets_conditions = false;\n        }\n        pointcloudcount++;\n      }\n    }\n\n    if ( (surfcount == 0) || (pointcloudcount == 0) )\n    {\n      meets_conditions = false;\n    }\n\n    // If all of the checks above don't flag meets_conditions as false,\n    // return a value that indicates the algorithm to use is the surface-to-nodes case\n    if ( meets_conditions )\n      return boost::make_shared<SurfaceAndPoints>();\n  }\n\n  //////////////////////////////////////////////////////////////////////////////////////////////////\n  // Check for case where all inputs are triangle surfaces, and there is at least one source and\n  // one measurement surface\n\n  bool allsurfaces=true, hasmeasurementsurf=false, hassourcesurf=false;\n\n  for (bemfield_vector::size_type i = 0; i < fields.size(); i++)\n  {\n    // if the current field is not marked to be used as a surface OR it's not of trisurfmesh type, this algorithm does not apply\n    if ( (! fields[i].field_->vmesh()->is_trisurfmesh()) || (! fields[i].surface) )\n    {\n      allsurfaces=false;\n      break;\n    }\n\n    if (fields[i].measurement) hasmeasurementsurf = true;\n    if (fields[i].source) hassourcesurf = true;\n  }\n\n  // if all fields are surfaces, there exists a measurement and a source surface, then use the surface-to-surface algorithm... else fail\n  if (allsurfaces && hasmeasurementsurf && hassourcesurf)\n  {\n    return boost::make_shared<SurfaceToSurface>();\n  }\n  else\n  {\n    return nullptr;\n  }\n}\n\nstatic void printInfo(const DenseMatrix& m, const std::string& name)\n{\n#if 0\n  std::cout << name << \": \" << m.rows() << \" x \" << m.cols() << std::endl;\n  std::cout << name << \" min: \" << m.minCoeff() << std::endl;\n  std::cout << name << \" max: \" << m.maxCoeff() << std::endl;\n#endif\n}\n\nMatrixHandle SurfaceToSurface::compute(const bemfield_vector& fields) const\n{\n  // Math for surface-to-surface BEM algorithm (based on Jeroen Stinstra's BEM Matlab code that's part of SCIRun)\n  // -------------------------------------------------------------------------------------------------------------\n  // EE = matrix relating potentials on surfaces to potentials on other surfaces\n  // EJ = matrix relating current density on surfaces (normal to surface) to potentials on surfaces\n  // u  = potentials on the surfaces\n  // j  = current density normal to the surfaces\n  //\n  // General equation: EE*u + EJ*j = (dipolar sources not on the surfaces)\n  // Assuming all sources are on surfaces: EE*u + EJ*j = 0\n  // (below assumes that measurement=Neumann boundary conditions and source=Dirichlet boundary conditions)\n  //\n  // s = source indices\n  // m = measurement indices\n  //\n  // Pmm = EE(m,m)\n  // Pss = EE(s,s)\n  // Pms = EE(m,s)\n  // Psm = EE(s,m)\n  //\n  // Gms = EJ(m,s)\n  // Gss = EJ(s,s)\n  //\n  // After some block-matrix math to eliminate j from the equation and find T s.t. u(m)=T*u(s), we get:\n  // iGss = inv(Gss)\n  // T = inv(Pmm - Gms*iGss*Psm)*(Gms*iGss*Pss - Pms)\n  //\n\n  const size_t Nfields = fields.size();\n  double op_cond=0.0; // op_cond is not used in this formulation -- someone needs to check this math and make a better decision about how to handle this value below\n\n  // Count the number of fields that have been specified as being \"sources\" or \"measurements\" (and keep track of indices)\n  int Nsources = 0;\n  std::vector<int> sourcefieldindices;\n  int Nmeasurements = 0;\n  std::vector<int> measurementfieldindices;\n\n  for(int i=0; i < Nfields; i++)\n  {\n    if(fields[i].source)\n    {\n      Nsources++;\n      sourcefieldindices.push_back(i);\n    }\n    else if(fields[i].measurement)\n    {\n      Nmeasurements++;\n      measurementfieldindices.push_back(i);\n    }\n  }\n\n  std::vector<int> fieldNodeSize(fields.size());\n  std::transform(fields.begin(), fields.end(), fieldNodeSize.begin(), [](const bemfield& f) { return numNodes(f.field_); } );\n  DenseBlockMatrix EE(fieldNodeSize, fieldNodeSize);\n\n  // Calculate EE in block matrix form\n  for(int i = 0; i < Nfields; i++)\n  {\n    for(int j = 0; j < Nfields; j++)\n    {\n      if (i == j)\n      {\n        auto block = EE.blockRef(i, j);\n        make_auto_P_compute(fields[i].field_->vmesh(), block, fields[i].insideconductivity, fields[i].outsideconductivity, op_cond);\n      }\n      else\n      {\n        auto block = EE.blockRef(i, j);\n        make_cross_P_compute(fields[i].field_->vmesh(), fields[j].field_->vmesh(), block, fields[j].insideconductivity, fields[j].outsideconductivity, op_cond);\n      }\n    }\n  }\n\n  printInfo(EE.matrix(), \"EE\");\n\n  std::vector<int> sourceFieldNodeSize(sourcefieldindices.size());\n  auto sourceFields = fields | boost::adaptors::filtered([](const bemfield& f) { return f.source; });\n  //following doesn't compile in VS2010, but does in clang: enable it after upgrading to 2013\n  //auto transformer = [this](const bemfield& f) -> int { return numNodes(f.field_); };\n  //auto trans = filt | boost::adaptors::transformed(transformer);\n  //boost::copy(trans, sourceFieldNodeSize.begin());\n  std::transform(sourceFields.begin(), sourceFields.end(), sourceFieldNodeSize.begin(), [](const bemfield& f) { return numNodes(f.field_); } );\n\n  DenseBlockMatrix EJ(fieldNodeSize, sourceFieldNodeSize);\n\n  // Calculate EJ(:,s) in block matrix form\n  // ***NOTE THE CHANGE IN INDEXING!!!***\n  // (The indices of block columns of EJ correspond to field indices according to \"sourcefieldindices\", and this affects everything with EJ below this point too!)\n  for(int j = 0; j < Nsources; j++)\n  {\n    // Precalculate triangle areas for this source field/surface\n    std::vector<double> triangleareas;\n    pre_calc_tri_areas(fields[sourcefieldindices[j]].field_->vmesh(), triangleareas);\n\n    for(int i = 0; i < Nfields; i++)\n    {\n      if (i == sourcefieldindices[j])\n      {\n        auto block = EJ.blockRef(i,j);\n        make_auto_G_compute(fields[i].field_->vmesh(), block, fields[i].insideconductivity, fields[i].outsideconductivity, op_cond, triangleareas);\n      }\n      else\n      {\n        auto block = EJ.blockRef(i,j);\n        make_cross_G_compute(fields[i].field_->vmesh(), fields[sourcefieldindices[j]].field_->vmesh(), block, fields[j].insideconductivity, fields[j].outsideconductivity, op_cond, triangleareas);\n      }\n    }\n  }\n\n  printInfo(EJ.matrix(), \"EJ\");\n\n  // This needs to be checked.  It was taken out because the deflation was producing errors\n  // Jeroen's matlab code, which was the basis of this code, only does a defation in test cases.\n\n  // Perform deflation on EE matrix\n  //const double deflationconstant = 1.0/EE.matrix().ncols();\n  //EE.matrix() = EE.matrix().array() + deflationconstant;\n\n  std::vector<int> measurementNodeSize(measurementfieldindices.size());\n  auto measFields = fields | boost::adaptors::filtered([](const bemfield& f) { return f.measurement; });\n  //following doesn't compile in VS2010, but does in clang: enable it after upgrading to 2013\n  //auto transformer = [this](const bemfield& f) -> int { return numNodes(f.field_); };\n  //auto trans = filt | boost::adaptors::transformed(transformer);\n  //boost::copy(trans, sourceFieldNodeSize.begin());\n  std::transform(measFields.begin(), measFields.end(), measurementNodeSize.begin(), [](const bemfield& f) { return numNodes(f.field_); } );\n\n  // Split EE apart into Pmm, Pss, Pms, and Psm\n  // -----------------------------------------------\n  // Pmm:\n  DenseBlockMatrix Pmm(measurementNodeSize, measurementNodeSize);\n  for(int i = 0; i < Nmeasurements; i++)\n  {\n    for(int j = 0; j < Nmeasurements; j++)\n    {\n      Pmm.blockRef(i,j) = EE.blockRef(measurementfieldindices[i], measurementfieldindices[j]);\n    }\n  }\n  printInfo(Pmm.matrix(), \"Pmm\");\n\n  // Pss:\n  DenseBlockMatrix Pss(sourceFieldNodeSize, sourceFieldNodeSize);\n  for(int i = 0; i < Nsources; i++)\n  {\n    for(int j = 0; j < Nsources; j++)\n    {\n      Pss.blockRef(i,j) = EE.blockRef(sourcefieldindices[i],sourcefieldindices[j]);\n    }\n  }\n  printInfo(Pss.matrix(), \"Pss\");\n\n  // Pms:\n  DenseBlockMatrix Pms(measurementNodeSize, sourceFieldNodeSize);\n  for(int i = 0; i < Nmeasurements; i++)\n  {\n    for(int j = 0; j < Nsources; j++)\n    {\n      Pms.blockRef(i,j) = EE.blockRef(measurementfieldindices[i],sourcefieldindices[j]);\n    }\n  }\n  printInfo(Pms.matrix(), \"Pms\");\n\n\n  // Psm:\n  DenseBlockMatrix Psm(sourceFieldNodeSize, measurementNodeSize);\n  for(int i = 0; i < Nsources; i++)\n  {\n    for(int j = 0; j < Nmeasurements; j++)\n    {\n      Psm.blockRef(i,j) = EE.blockRef(sourcefieldindices[i],measurementfieldindices[j]);\n    }\n  }\n  printInfo(Psm.matrix(), \"Psm\");\n\n  // Split EJ apart into Gms and Gss (see ALL-CAPS note above about differences in block row vs column indexing in EJ matrix)\n  // -----------------------------------------------\n  // Gms:\n  DenseBlockMatrix Gms(measurementNodeSize, sourceFieldNodeSize);\n  for(int i = 0; i < Nmeasurements; i++)\n  {\n    for(int j = 0; j < Nsources; j++)\n    {\n      Gms.blockRef(i,j) = EJ.blockRef(measurementfieldindices[i],j);\n    }\n  }\n  printInfo(Gms.matrix(), \"Gms\");\n\n  // Gss:\n  DenseBlockMatrix Gss(sourceFieldNodeSize, sourceFieldNodeSize);\n  for(int i = 0; i < Nsources; i++)\n  {\n    for(int j = 0; j < Nsources; j++)\n    {\n      Gss.blockRef(i,j) = EJ.blockRef(sourcefieldindices[i],j);\n    }\n  }\n  printInfo(Gss.matrix(), \"Gss\");\n\n  // TODO: add deflation step\n\n  // Compute T here (see math in comments above)\n  // TransferMatrix = T = inv(Pmm - Gms*iGss*Psm)*(Gms*iGss*Pss - Pms) = inv(C)*D\n\n  auto Y = Gms.matrix() * Gss.matrix().inverse();\n  auto C = Pmm.matrix() - Y * Psm.matrix();\n  auto D = Y * Pss.matrix() - Pms.matrix();\n\n  auto T = C.inverse() * D; // T = inv(C)*D\n  return boost::make_shared<DenseMatrix>(T);\n\n  //This could be done on one line (see below), but Y (see above) would need to be calculated twice:\n  //MatrixHandle TransferMatrix1 = inv(Pmm - Gms * Gss * Psm) * (Gms * Gss * Pss - Pms);\n}\n\n\nMatrixHandle SurfaceAndPoints::compute(const bemfield_vector& fields) const\n{\n  // NOTE: This is Jeroen's code that has been adapted to fit the new module structure\n  //\n  // Math:\n  // The boundary element formulation is based on Matlab code\n  // bemMatrixPP2.m, which can be found in the matlab package\n\n  // The BEM formulation assumes the following matrix equations\n  // P_surf_surf * PHI_surf + G_surf_surf * J_surf =  sources_in_volume\n  //\n  // PHI_surf are the potentials on the surface\n  // J_surf are the currents passing perpendicular to the surface\n  // sources_in_volume is empty in this case\n  //\n  // P_surf_surf is the matrix that connects the potentials at the nodes to the integral over the\n  // potential at the surface. Its terms consist of Green's function ( 1/ ( 4pi*||r-r'|| ) ) over\n  // the surface of each element. As this integral becomes singular for a node and a triangle that\n  // share a corner node, we use a trick to avoid computing this integral as we know that the\n  // the system should reference potential invariant. Hence the rows of the matrix need to sum to\n  // to zero\n  //\n  // G_surf_surf is the matrix that connects the potentials at the nodes to the integral over the\n  // currents flowing through the surface.\n  //\n  // The second equation that we use is the expression of the potentials at an arbitrary point\n  // to the potentials at the surface and the current flowing through the surface\n  //\n  // PHI_nodes = P_nodes_surf * PHI_surf + G_nodes_surf * J_surf\n  //\n  // Here matrix P_nodes_surf is the matrix that projects the contribution of the potentials of the\n  // surface to the nodes within the volume\n  //\n  // Here G_nodes_surf is the matrix that projects the contribution of the currents flowing through\n  // the surface to the nodes within the volume\n  //\n  // Adding both equations together will result in\n  //\n  // PHI_nodes = P_nodes_surf* PHI_surf - G_nodes_surf * inv( G_surf_surf) * P_surf_surf * PHI_surf\n  //\n  // In other words the transfer matrix is\n  // P_nodes_surf - G_nodes_surf * inv( G_surf_surf) * P_surf_surf\n\n  VMesh *nodes = nullptr;\n  VMesh *surface = nullptr;\n\n  for (int i=0; i<2; i++)\n  {\n    if (fields[i].surface)\n      surface = fields[i].field_->vmesh();\n    else\n      nodes = fields[i].field_->vmesh();\n  }\n\n  DenseMatrixHandle Pss;\n  DenseMatrixHandle Gss;\n  DenseMatrixHandle Pns;\n  DenseMatrixHandle Gns;\n  make_auto_P( surface, Pss, 1.0, 0.0, 1.0 );\n  make_cross_P( nodes, surface, Pns, 1.0, 0.0, 1.0 );\n\n  std::vector<double> area;\n  pre_calc_tri_areas( surface, area );\n\n  make_auto_G( surface, Gss, 1.0, 0.0, 1.0, area );\n  make_cross_G( nodes, surface, Gns, 1.0, 0.0, 1.0, area );\n\n  return boost::make_shared<DenseMatrix>(*Pns - (*Gns * Gss->inverse() * *Pss));\n}\n", "meta": {"hexsha": "a35bdfe631693fbd51748d4623ab1995a4c03cc8", "size": 41851, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/Core/Algorithms/Legacy/Forward/BuildBEMatrixAlgo.cc", "max_stars_repo_name": "mckees/SCIRun", "max_stars_repo_head_hexsha": "40c2c5b17925181bd2581ab8e11b325d58618165", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Core/Algorithms/Legacy/Forward/BuildBEMatrixAlgo.cc", "max_issues_repo_name": "mckees/SCIRun", "max_issues_repo_head_hexsha": "40c2c5b17925181bd2581ab8e11b325d58618165", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Core/Algorithms/Legacy/Forward/BuildBEMatrixAlgo.cc", "max_forks_repo_name": "mckees/SCIRun", "max_forks_repo_head_hexsha": "40c2c5b17925181bd2581ab8e11b325d58618165", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.6334089191, "max_line_length": 195, "alphanum_fraction": 0.6477503524, "num_tokens": 13481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.47290713152284053}}
{"text": "/*\n * statistics.cc\n *\n *  Created on: Aug 30, 2016\n *      Author: egilad\n */\n\n#include \"statistics.h\"\n\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/mean.hpp>\n#include <boost/accumulators/statistics/density.hpp>\n#include <boost/accumulators/statistics/rolling_mean.hpp>\n\n#include <iostream>\n\nusing namespace boost::accumulators;\n\nnamespace ycsbc\n{\n\nconstexpr size_t WindowsNum = 100;\n\nstruct Statistics::State\n{\n\taccumulator_set<double,\n\t\tstats<\n\t\t\ttag::mean,\n\t\t\ttag::rolling_mean\n\t\t>\n\t> acc;\n\tsize_t expectingEvents;\n\n\tState(size_t expectedEvents) :\n\t\tacc(tag::rolling_window::window_size = expectedEvents / WindowsNum),\n\t\texpectingEvents(expectedEvents)\n\t{\n\n\t}\n};\n\nStatistics::Statistics(size_t expectedEvents) : eventCtr(0)\n{\n\tstate.reset(new State(expectedEvents));\n\tpartMeans.reserve(expectedEvents / WindowsNum);\n}\n\nStatistics::Statistics(const Statistics& other) : eventCtr(other.eventCtr)\n{\n\tstate.reset(new State(other.state->expectingEvents));\n\tpartMeans.reserve(other.partMeans.capacity());\n}\n\nStatistics::~Statistics()\n{\n}\n\nvoid Statistics::addEvent(double time)\n{\n\tstate->acc(time);\n\tif (++eventCtr % WindowsNum == 0)\n\t{\n\t\tpartMeans.push_back(rolling_mean(state->acc));\n\t}\n}\n\nvoid Statistics::getMeans(double& total, std::vector<double>& partials) const\n{\n\ttotal = mean(state->acc);\n\tpartials = partMeans;\n}\n\n} /* namespace ycsbc */\n", "meta": {"hexsha": "b1a7527070c9adf3f4ba83ab479e72d25794a1ae", "size": 1440, "ext": "cc", "lang": "C++", "max_stars_repo_path": "core/statistics.cc", "max_stars_repo_name": "yonigottesman/ycsbc", "max_stars_repo_head_hexsha": "f9216b23eebd038e39a9a1f4589306343cfea6d1", "max_stars_repo_licenses": ["Apache-2.0"], "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/statistics.cc", "max_issues_repo_name": "yonigottesman/ycsbc", "max_issues_repo_head_hexsha": "f9216b23eebd038e39a9a1f4589306343cfea6d1", "max_issues_repo_licenses": ["Apache-2.0"], "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/statistics.cc", "max_forks_repo_name": "yonigottesman/ycsbc", "max_forks_repo_head_hexsha": "f9216b23eebd038e39a9a1f4589306343cfea6d1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.2, "max_line_length": 77, "alphanum_fraction": 0.7361111111, "num_tokens": 348, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.47290713152284053}}
{"text": "#include <stan/math/mix.hpp>\n#include <gtest/gtest.h>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/math/distributions.hpp>\n#include <vector>\n\nusing Eigen::Dynamic;\nusing Eigen::Matrix;\n\nTEST(ProbDistributionsCategorical, fvar_var) {\n  using stan::math::fvar;\n  using stan::math::var;\n  Matrix<fvar<var>, Dynamic, 1> theta(3, 1);\n  theta << 0.3, 0.5, 0.2;\n  for (int i = 0; i < 3; i++)\n    theta(i).d_ = 1.0;\n\n  EXPECT_FLOAT_EQ(std::log(0.3),\n                  stan::math::categorical_log(1, theta).val_.val());\n  EXPECT_FLOAT_EQ(std::log(0.5),\n                  stan::math::categorical_log(2, theta).val_.val());\n  EXPECT_FLOAT_EQ(std::log(0.2),\n                  stan::math::categorical_log(3, theta).val_.val());\n  EXPECT_FLOAT_EQ(1.0 / 0.3, stan::math::categorical_log(1, theta).d_.val());\n  EXPECT_FLOAT_EQ(1.0 / 0.5, stan::math::categorical_log(2, theta).d_.val());\n  EXPECT_FLOAT_EQ(1.0 / 0.2, stan::math::categorical_log(3, theta).d_.val());\n}\nTEST(ProbDistributionsCategorical, fvar_var_vector) {\n  using stan::math::fvar;\n  using stan::math::var;\n  Matrix<fvar<var>, Dynamic, 1> theta(3, 1);\n  theta << 0.3, 0.5, 0.2;\n  for (int i = 0; i < 3; i++)\n    theta(i).d_ = 1.0;\n\n  std::vector<int> xs(3);\n  xs[0] = 1;\n  xs[1] = 3;\n  xs[2] = 1;\n\n  EXPECT_FLOAT_EQ(log(0.3) + log(0.2) + log(0.3),\n                  stan::math::categorical_log(xs, theta).val_.val());\n  EXPECT_FLOAT_EQ(1.0 / 0.3 + 1.0 / 0.2 + 1.0 / 0.3,\n                  stan::math::categorical_log(xs, theta).d_.val());\n}\n\nTEST(ProbDistributionsCategorical, fvar_fvar_var) {\n  using stan::math::fvar;\n  using stan::math::var;\n  Matrix<fvar<fvar<var> >, Dynamic, 1> theta(3, 1);\n  theta << 0.3, 0.5, 0.2;\n  for (int i = 0; i < 3; i++)\n    theta(i).d_.val_ = 1.0;\n\n  EXPECT_FLOAT_EQ(std::log(0.3),\n                  stan::math::categorical_log(1, theta).val_.val_.val());\n  EXPECT_FLOAT_EQ(std::log(0.5),\n                  stan::math::categorical_log(2, theta).val_.val_.val());\n  EXPECT_FLOAT_EQ(std::log(0.2),\n                  stan::math::categorical_log(3, theta).val_.val_.val());\n  EXPECT_FLOAT_EQ(1.0 / 0.3,\n                  stan::math::categorical_log(1, theta).d_.val_.val());\n  EXPECT_FLOAT_EQ(1.0 / 0.5,\n                  stan::math::categorical_log(2, theta).d_.val_.val());\n  EXPECT_FLOAT_EQ(1.0 / 0.2,\n                  stan::math::categorical_log(3, theta).d_.val_.val());\n}\nTEST(ProbDistributionsCategorical, fvar_fvar_var_vector) {\n  using stan::math::fvar;\n  using stan::math::var;\n  Matrix<fvar<fvar<var> >, Dynamic, 1> theta(3, 1);\n  theta << 0.3, 0.5, 0.2;\n  for (int i = 0; i < 3; i++)\n    theta(i).d_.val_ = 1.0;\n\n  std::vector<int> xs(3);\n  xs[0] = 1;\n  xs[1] = 3;\n  xs[2] = 1;\n\n  EXPECT_FLOAT_EQ(log(0.3) + log(0.2) + log(0.3),\n                  stan::math::categorical_log(xs, theta).val_.val_.val());\n  EXPECT_FLOAT_EQ(1.0 / 0.3 + 1.0 / 0.2 + 1.0 / 0.3,\n                  stan::math::categorical_log(xs, theta).d_.val_.val());\n}\n", "meta": {"hexsha": "402e4dabee2b6a9ec6e3a059365dc9f04f76afd8", "size": 2939, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/mix/prob/categorical_test.cpp", "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": "test/unit/math/mix/prob/categorical_test.cpp", "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": "test/unit/math/mix/prob/categorical_test.cpp", "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": 34.1744186047, "max_line_length": 77, "alphanum_fraction": 0.5927186118, "num_tokens": 1076, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.47290713152284053}}
{"text": "#ifndef INCLUDE_SWIFT_VIO_EPIPOLAR_JACOBIAN_HPP_\n#define INCLUDE_SWIFT_VIO_EPIPOLAR_JACOBIAN_HPP_\n#include <Eigen/Geometry>\n\n#include <swift_vio/ProjParamOptModels.hpp>\n#include <okvis/cameras/CameraBase.hpp>\n#include <okvis/kinematics/operators.hpp>\n\nnamespace swift_vio {\n/**\n * @brief obsDirectionJacobian compute the Jacobian of the obsDirection\n *     relative to the camera parameters and its covariance.\n * @param obsDirection [x/z, y/z, 1] backprojected undistorted coordinates.\n * @param cameraGeometry\n * @param imageObservationCov covariance of image observation.\n * @param dfj_dXcam\n * @param cov_fj cov([x/z, y/z, 1])\n * @return false if backprojected direction failed to project onto image.\n */\ninline bool obsDirectionJacobian(\n    const Eigen::Vector3d& obsDirection,\n    std::shared_ptr<const okvis::cameras::CameraBase> cameraGeometry,\n    int projOptModelId, const Eigen::Matrix2d& imageObservationCov,\n    Eigen::Matrix<double, 3, Eigen::Dynamic>* dfj_dXcam,\n    Eigen::Matrix3d* cov_fj) {\n  const Eigen::Vector3d& fj = obsDirection;\n  Eigen::Vector2d imagePoint;\n  Eigen::Matrix<double, 2, 3> pointJacobian;\n  Eigen::Matrix2Xd intrinsicsJacobian;\n  okvis::cameras::CameraBase::ProjectionStatus projectOk =\n      cameraGeometry->project(fj, &imagePoint, &pointJacobian, &intrinsicsJacobian);\n  if (projectOk != okvis::cameras::CameraBase::ProjectionStatus::Successful)\n    return false;\n  ProjectionOptMinimalIntrinsicJacobian(projOptModelId, &intrinsicsJacobian);\n  Eigen::Matrix2d dz_df12 = pointJacobian.topLeftCorner<2, 2>();\n  Eigen::Matrix2d df12_dz = dz_df12.inverse();\n  int cols = intrinsicsJacobian.cols();\n  dfj_dXcam->resize(3, cols);\n  dfj_dXcam->topLeftCorner(2, cols) = -df12_dz * intrinsicsJacobian;\n  dfj_dXcam->row(2).setZero();\n  cov_fj->setZero();\n  cov_fj->topLeftCorner<2, 2>() = df12_dz * imageObservationCov *\n                                  df12_dz.transpose();\n  return true;\n}\n\nclass EpipolarJacobian {\n public:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n  inline EpipolarJacobian(const Eigen::Matrix3d& R_CjCk,\n                          const Eigen::Vector3d& t_CjCk,\n                          const Eigen::Vector3d& fj, const Eigen::Vector3d& fk);\n  inline double evaluate() const;\n  inline void de_dtheta_CjCk(Eigen::Matrix<double, 1, 3>* jac) const;\n  inline void de_dfj(Eigen::Matrix<double, 1, 3>* jac) const;\n  inline void de_dt_CjCk(Eigen::Matrix<double, 1, 3>* jac) const;\n  inline void de_dfk(Eigen::Matrix<double, 1, 3>* jac) const;\n\n private:\n  const Eigen::Matrix3d R_CjCk_;\n  const Eigen::Vector3d t_CjCk_;\n  const Eigen::Vector3d fj_;  // z = 1\n  const Eigen::Vector3d fk_;  // z = 1\n};\n\ninline EpipolarJacobian::EpipolarJacobian(const Eigen::Matrix3d& R_CjCk,\n                                          const Eigen::Vector3d& t_CjCk,\n                                          const Eigen::Vector3d& fj,\n                                          const Eigen::Vector3d& fk)\n    : R_CjCk_(R_CjCk), t_CjCk_(t_CjCk), fj_(fj), fk_(fk) {}\n\ninline double EpipolarJacobian::evaluate() const {\n  // variants of the below expression does not change the Jacobians\n  return (R_CjCk_ * fk_).dot(t_CjCk_.cross(fj_));\n}\n\ninline void EpipolarJacobian::de_dtheta_CjCk(\n    Eigen::Matrix<double, 1, 3>* jac) const {\n  *jac = (R_CjCk_ * fk_).transpose() *\n         okvis::kinematics::crossMx(t_CjCk_.cross(fj_));\n}\n\ninline void EpipolarJacobian::de_dfj(Eigen::Matrix<double, 1, 3>* jac) const {\n  *jac = (R_CjCk_ * fk_).transpose() * okvis::kinematics::crossMx(t_CjCk_);\n}\n\ninline void EpipolarJacobian::de_dt_CjCk(\n    Eigen::Matrix<double, 1, 3>* jac) const {\n  *jac = -(R_CjCk_ * fk_).transpose() * okvis::kinematics::crossMx(fj_);\n}\n\ninline void EpipolarJacobian::de_dfk(Eigen::Matrix<double, 1, 3>* jac) const {\n  *jac = (t_CjCk_.cross(fj_)).transpose() * R_CjCk_;\n}\n}  // namespace swift_vio\n#endif  // INCLUDE_SWIFT_VIO_EPIPOLAR_JACOBIAN_HPP_\n", "meta": {"hexsha": "a304fa0df3d5ed559973c2565f43e8c96c8edd63", "size": 3886, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "okvis_ceres/include/swift_vio/EpipolarJacobian.hpp", "max_stars_repo_name": "JzHuai0108/okvis", "max_stars_repo_head_hexsha": "d0cc5b93115d980365a6f826e6dc4bfba97f2d75", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-26T15:31:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T15:31:53.000Z", "max_issues_repo_path": "okvis_ceres/include/swift_vio/EpipolarJacobian.hpp", "max_issues_repo_name": "JzHuai0108/okvis", "max_issues_repo_head_hexsha": "d0cc5b93115d980365a6f826e6dc4bfba97f2d75", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "okvis_ceres/include/swift_vio/EpipolarJacobian.hpp", "max_forks_repo_name": "JzHuai0108/okvis", "max_forks_repo_head_hexsha": "d0cc5b93115d980365a6f826e6dc4bfba97f2d75", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-08-01T16:49:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-14T09:00:03.000Z", "avg_line_length": 39.6530612245, "max_line_length": 84, "alphanum_fraction": 0.6984045291, "num_tokens": 1211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4729071315228405}}
{"text": "#include <Eigen/Dense>\n#include \"ukf.h\"\n\nusing Eigen::MatrixXd;\n\nint main() {\n\n  // Create a UKF instance\n  UKF ukf;\n\n  /**\n   * Programming assignment calls\n   */\n  MatrixXd Xsig_pred = MatrixXd(5, 15); // Swapped dimensions - error from original code\n  ukf.SigmaPointPrediction(&Xsig_pred);\n\n  return 0;\n}", "meta": {"hexsha": "6d41a76dfdc7f5d5720b74880441a4af2cba07e7", "size": 307, "ext": "cc", "lang": "C++", "max_stars_repo_path": "SFND_Kalman_Filter/UKF_Prep/ukf_augmentation_predict/main.cc", "max_stars_repo_name": "KU-AIRS-SPARK/Udacity_Sensor_Fusion_Nanodegree", "max_stars_repo_head_hexsha": "2c6d26bee670abe2c63034d26556f99f6d77925b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2020-11-12T07:13:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T18:42:13.000Z", "max_issues_repo_path": "SFND_Kalman_Filter/UKF_Prep/ukf_augmentation_predict/main.cc", "max_issues_repo_name": "KU-AIRS-SPARK/Udacity_Sensor_Fusion_Nanodegree", "max_issues_repo_head_hexsha": "2c6d26bee670abe2c63034d26556f99f6d77925b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SFND_Kalman_Filter/UKF_Prep/ukf_augmentation_predict/main.cc", "max_forks_repo_name": "KU-AIRS-SPARK/Udacity_Sensor_Fusion_Nanodegree", "max_forks_repo_head_hexsha": "2c6d26bee670abe2c63034d26556f99f6d77925b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2020-09-29T05:27:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-02T18:26:53.000Z", "avg_line_length": 17.0555555556, "max_line_length": 88, "alphanum_fraction": 0.67752443, "num_tokens": 88, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4729071315228405}}
{"text": "//    Copyright 2017 Rainer Gemulla\n// \n//    Licensed under the Apache License, Version 2.0 (the \"License\");\n//    you may not use this file except in compliance with the License.\n//    You may obtain a copy of the License at\n// \n//        http://www.apache.org/licenses/LICENSE-2.0\n// \n//    Unless required by applicable law or agreed to in writing, software\n//    distributed under the License is distributed on an \"AS IS\" BASIS,\n//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//    See the License for the specific language governing permissions and\n//    limitations under the License.\n/** \\file\n *\n * Illustrates matrix factorization with GNMF. */\n#include <iostream>\n\n#include <boost/math/distributions/normal.hpp>\n#include <boost/math/distributions/binomial.hpp>\n#include <boost/random/uniform_real.hpp>\n\n#include <util/evaluation.h>\n#include <util/io.h>\n\n#include <mf/mf.h>\n\n\nusing namespace std;\nusing namespace mf;\nusing namespace rg;\nusing namespace boost::numeric::ublas;\n\nlog4cxx::LoggerPtr logger(log4cxx::Logger::getLogger(\"main\"));\n\nint main(int argc, char* argv[]) {\n#ifndef NDEBUG\n\tLOG4CXX_WARN(logger, \"Warning: Debug mode activated (runtimes may be slow).\");\n#endif\n\n\t// parameters for the factorization\n\tmf_size_type size1 = 100; //10000;\n\tmf_size_type size2 = 100; //10000;\n\tmf_size_type nnz = 50; //5000000;\n\tmf_size_type r = 2; // 10\n\n\t// parameters for GNMF\n\tunsigned epochs = 1600;\n\tmf_size_type testNnz = nnz/100;\n\n\tBalanceType type = BALANCE_L2;;\n\tBalanceMethod method = BALANCE_OPTIMAL;\n\n\t// generate original factors by sampling from a uniform[0,1] distribution\n\tRandom32 random; // note: this takes a default seed (not randomized!)\n\tDenseMatrix wIn(size1, r);\n\tDenseMatrixCM hIn(r, size2);\n\tgenerateRandom(wIn, random, boost::uniform_real<>(0,1));\n\tgenerateRandom(hIn, random, boost::uniform_real<>(0,1));\n\n\t// clear one row\n\tfor (mf_size_type k=0; k<r; k++) {\n\t\twIn(0,k) = 0;\n\t}\n\n\t// generate a sparse matrix by selecting random entries from the generated factors\n\t// and add small Gaussian noise\n\tSparseMatrix v;\n\tgenerateRandom(v, nnz, wIn, hIn, random);\n\t//addRandom(v, random, boost::normal_distribution<>(0, 0.1));\n\tLOG4CXX_INFO(logger, \"Data matrix: \"\n\t\t<< v.size1() << \" x \" << v.size2() << \", \" << v.nnz() << \" nonzeros\");\n\tv.sort();\n\t//LOG4CXX_INFO(logger, \"Loss with original factors: \" << loss((FactorizationData<>(v, wIn, hIn))));\n\tSparseMatrixCM vc;\n\tcopyCm(v, vc);\n\n\t// create a test matrix (without noise)\n\tSparseMatrix vTest;\n\tgenerateRandom(vTest, testNnz, wIn, hIn, random);\n\tLOG4CXX_INFO(logger, \"Test matrix: \"\n\t\t<< v.size1() << \" x \" << v.size2() << \", \" << vTest.nnz() << \" nonzeros\");\n\n\t// generate initial factors by sampling from a uniform[0,1] distribution\n\tDenseMatrix w(size1, r);\n\tDenseMatrixCM h(r, size2);\n\tgenerateRandom(w, random, boost::uniform_real<>(0,1));\n\tLOG4CXX_INFO(logger, \"Row factors: \" << w.size1() << \" x \" << w.size2());\n\tgenerateRandom(h, random, boost::uniform_real<>(0,1));\n\tLOG4CXX_INFO(logger, \"Column factors: \" << h.size1() << \" x \" << h.size2());\n\n\n\t// initialize\n\tFactorizationData<> data(v, w, h, 1, &vc);\n\tFactorizationData<> testJob(vTest,w,h);\n\tTrace trace;\n\tTimer t;\n\n\tLOG4CXX_INFO(logger, \"Start\");\n\t// run GNMF to try to reconstruct the original factors\n\tt.start();\n\tgnmf(data, epochs, trace, type, method, &testJob);\n\tt.stop();\n\tLOG4CXX_INFO(logger, \"Total time: \" << t);\n\n\t// write trace to an R file\n\tLOG4CXX_INFO(logger, \"Writing trace to \" << \"/tmp/gnmf-trace.R\");\n\ttrace.toRfile(\"/tmp/gnmf-trace.R\", \"gnmf\");\n\n\treturn 0;\n}\n\n", "meta": {"hexsha": "65bb9c9c89a12e72fc1c8204d3cdb5e7e1e991f5", "size": 3559, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/mf/gnmf.cc", "max_stars_repo_name": "Hui-Li/DSGDPP", "max_stars_repo_head_hexsha": "0ce5b115bfbed81cee1c39fbfa4a8f67a5e1b72e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2017-01-10T11:39:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-02T23:03:55.000Z", "max_issues_repo_path": "examples/mf/gnmf.cc", "max_issues_repo_name": "Hui-Li/DSGDPP", "max_issues_repo_head_hexsha": "0ce5b115bfbed81cee1c39fbfa4a8f67a5e1b72e", "max_issues_repo_licenses": ["Apache-2.0"], "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/mf/gnmf.cc", "max_forks_repo_name": "Hui-Li/DSGDPP", "max_forks_repo_head_hexsha": "0ce5b115bfbed81cee1c39fbfa4a8f67a5e1b72e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-10-27T18:40:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-05T15:10:56.000Z", "avg_line_length": 31.4955752212, "max_line_length": 100, "alphanum_fraction": 0.689519528, "num_tokens": 1024, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.6001883592602049, "lm_q1q2_score": 0.4729071315228405}}
{"text": "#define BOOST_TEST_MODULE MultivectorArithmetics\n#include <boost/test/unit_test.hpp>\n#include <vexcl/constants.hpp>\n#include <vexcl/multivector.hpp>\n#include <vexcl/reductor.hpp>\n#include <vexcl/element_index.hpp>\n#include <vexcl/function.hpp>\n#include \"context_setup.hpp\"\n\nBOOST_AUTO_TEST_CASE(arithmetics)\n{\n    typedef std::array<double, 4> elem_t;\n\n    const size_t n = 1024;\n\n    vex::multivector<double, 4> x(ctx, n);\n    vex::multivector<double, 4> y(ctx, random_vector<double>(n * 4));\n    vex::multivector<double, 4> z(ctx, random_vector<double>(n * 4));\n\n    vex::Reductor<double,vex::MIN> min(ctx);\n    vex::Reductor<double,vex::MAX> max(ctx);\n\n    elem_t v = {{0, 1, 2, 3}};\n    x = v;\n\n    BOOST_CHECK(min(x) == v);\n    BOOST_CHECK(max(x) == v);\n\n    x = std::make_tuple(1, 2, 3, 4) * y + z;\n\n    check_sample(x, y, z, [](size_t, elem_t a, elem_t b, elem_t c) {\n            for(size_t i = 0; i < 4; ++i)\n                BOOST_CHECK_CLOSE(a[i], (i + 1) * b[i] + c[i], 1e-8);\n            });\n}\n\nBOOST_AUTO_TEST_CASE(multivector_multiexpressions)\n{\n    typedef std::array<double, 2> elem_t;\n\n    const size_t n = 1024;\n\n    vex::multivector<double, 2> x(ctx, n);\n    vex::multivector<double, 2> y(ctx, random_vector<double>(n * 2));\n\n    x = std::tie(\n            sin( y(0) ) + cos( y(1) ),\n            cos( y(0) ) + sin( y(1) )\n            );\n\n    check_sample(x, y, [](size_t, elem_t a, elem_t b) {\n            BOOST_CHECK_CLOSE(a[0], sin(b[0]) + cos(b[1]), 1e-8);\n            BOOST_CHECK_CLOSE(a[1], cos(b[0]) + sin(b[1]), 1e-8);\n            });\n}\n\nBOOST_AUTO_TEST_CASE(tied_vectors)\n{\n    const size_t n = 1024;\n\n    vex::vector<double> X(ctx, random_vector<double>(n));\n    vex::vector<double> Y(ctx, random_vector<double>(n));\n\n    vex::vector<double> A(ctx, n);\n    vex::vector<double> B(ctx, n);\n\n    vex::tie(A, B) = std::tie(X + Y, X - Y);\n\n    check_sample(A, X, Y, [](size_t, double a, double x, double y) {\n            BOOST_CHECK(a == x + y);\n            });\n\n    check_sample(B, X, Y, [](size_t, double b, double x, double y) {\n            BOOST_CHECK(b == x - y);\n            });\n}\n\nBOOST_AUTO_TEST_CASE(builtin_functions)\n{\n    typedef std::array<double, 2> elem_t;\n    const size_t n = 1024;\n\n    vex::multivector<double, 2> x(ctx, random_vector<double>(n * 2));\n    vex::multivector<double, 2> y(ctx, n);\n\n    y = pow(sin(x), 2.0) + pow(cos(x), 2.0);\n\n    check_sample(y, [](size_t, elem_t a) {\n            BOOST_CHECK_CLOSE(a[0], 1, 1e-8);\n            BOOST_CHECK_CLOSE(a[1], 1, 1e-8);\n            });\n}\n\nBOOST_AUTO_TEST_CASE(user_defined_functions)\n{\n    typedef std::array<double, 2> elem_t;\n\n    const size_t n = 1024;\n    const size_t m = 2;\n\n    vex::multivector<double, m> x(ctx, n);\n    vex::multivector<double, m> y(ctx, n);\n\n    elem_t v1 = {{1, 2}};\n    elem_t v2 = {{2, 1}};\n\n    VEX_FUNCTION(size_t, greater, (double, x)(double, y), return x > y;);\n\n    x = v1;\n    y = v2;\n\n    x = greater(x, y);\n\n    check_sample(x, [](size_t, elem_t a) {\n            BOOST_CHECK(a[0] == 0);\n            BOOST_CHECK(a[1] == 1);\n            });\n}\n\nBOOST_AUTO_TEST_CASE(reduction)\n{\n    typedef std::array<double, 2> elem_t;\n\n    const size_t n = 1024;\n\n    std::vector<double> x = random_vector<double>(n);\n    std::vector<double> y = random_vector<double>(n);\n\n    vex::multivector<double, 2> m(ctx, n);\n    copy(x, m(0));\n    copy(y, m(1));\n\n    vex::Reductor<double, vex::SUM> sum(ctx);\n    vex::Reductor<double, vex::MIN> min(ctx);\n    vex::Reductor<double, vex::MAX> max(ctx);\n\n    elem_t summ = sum(m);\n    elem_t minm = min(m);\n    elem_t maxm = max(m);\n\n    BOOST_CHECK_CLOSE(summ[0], std::accumulate(x.begin(), x.end(), 0.0), 1e-6);\n    BOOST_CHECK_CLOSE(summ[1], std::accumulate(y.begin(), y.end(), 0.0), 1e-6);\n\n    BOOST_CHECK_CLOSE(minm[0], *std::min_element(x.begin(), x.end()), 1e-12);\n    BOOST_CHECK_CLOSE(minm[1], *std::min_element(y.begin(), y.end()), 1e-12);\n\n    BOOST_CHECK_CLOSE(maxm[0], *std::max_element(x.begin(), x.end()), 1e-12);\n    BOOST_CHECK_CLOSE(maxm[1], *std::max_element(y.begin(), y.end()), 1e-12);\n}\n\nBOOST_AUTO_TEST_CASE(element_index)\n{\n    typedef std::array<double, 2> elem_t;\n\n    const size_t N = 1024;\n\n    vex::multivector<double, 2> x(ctx, N);\n\n    x = 0.5 * vex::element_index();\n\n    check_sample(x, [](size_t idx, elem_t a) {\n            BOOST_CHECK_CLOSE(a[0], 0.5 * idx, 1e-12);\n            BOOST_CHECK_CLOSE(a[1], 0.5 * idx, 1e-12);\n            });\n\n    x = std::tie(\n            sin(0.5 * vex::element_index()),\n            cos(0.5 * vex::element_index())\n            );\n\n    check_sample(x, [](size_t idx, elem_t a) {\n            BOOST_CHECK_CLOSE(a[0], sin(0.5 * idx), 1e-6);\n            BOOST_CHECK_CLOSE(a[1], cos(0.5 * idx), 1e-6);\n            });\n}\n\nBOOST_AUTO_TEST_CASE(compound_assignment)\n{\n    const size_t n = 1024;\n    const size_t m = 2;\n\n    typedef std::array<double, m> elem_t;\n\n    vex::multivector<double, m> x(ctx, n);\n    vex::multivector<double, m> y(ctx, random_vector<double>(n * m));\n\n    x = 0;\n\n    x += sin(2 * y);\n\n    check_sample(x, y, [&](size_t, elem_t a, elem_t b) {\n            for(size_t i = 0; i < m; ++i)\n                BOOST_CHECK_CLOSE(a[i], sin(2 * b[i]), 1e-8);\n            });\n\n    x = 0;\n    x -= sin(2 * y);\n\n    check_sample(x, y, [&](size_t, elem_t a, elem_t b) {\n            for(size_t i = 0; i < m; ++i)\n                BOOST_CHECK_CLOSE(a[i], -sin(2 * b[i]), 1e-8);\n            });\n\n    x = 1;\n    x *= std::tie(y(1), sin(y(0)));\n\n    check_sample(x, y, [](size_t, elem_t a, elem_t b) {\n            BOOST_CHECK_CLOSE(a[0], b[1], 1e-8);\n            BOOST_CHECK_CLOSE(a[1], sin(b[0]), 1e-8);\n            });\n}\n\nBOOST_AUTO_TEST_CASE(integral_constants)\n{\n    typedef std::array<double, 4> elem_t;\n\n    const size_t n = 1024;\n\n    vex::multivector<double, 4> x(ctx, n);\n\n    x = std::integral_constant<int, 42>();\n    check_sample(x, [](size_t, elem_t a) {\n            for(size_t i = 0; i < 4; ++i) BOOST_CHECK_EQUAL(a[i], 42);\n            });\n\n    x = sin( vex::constants::e() * vex::element_index() );\n    check_sample(x, [](size_t idx, elem_t a) {\n            for(size_t i = 0; i < 4; ++i)\n                BOOST_CHECK_CLOSE(a[i], sin(boost::math::constants::e<double>() * idx), 1e-8);\n            });\n}\n\n#if (VEXCL_CHECK_SIZES > 0)\nBOOST_AUTO_TEST_CASE(expression_size_check)\n{\n    vex::multivector<int, 2> x(ctx, 16);\n    vex::multivector<int, 2> y(ctx, 32);\n\n    BOOST_CHECK_THROW(x = y, std::runtime_error);\n}\n#endif\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "6aea29c42081896b27d1ca3cdc7b3c80e2a44ca5", "size": 6479, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "external_libraries/vexcl/tests/multivector_arithmetics.cpp", "max_stars_repo_name": "lkusch/Kratos", "max_stars_repo_head_hexsha": "e8072d8e24ab6f312765185b19d439f01ab7b27b", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": 778.0, "max_stars_repo_stars_event_min_datetime": "2017-01-27T16:29:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T03:01:51.000Z", "max_issues_repo_path": "external_libraries/vexcl/tests/multivector_arithmetics.cpp", "max_issues_repo_name": "lkusch/Kratos", "max_issues_repo_head_hexsha": "e8072d8e24ab6f312765185b19d439f01ab7b27b", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": 6634.0, "max_issues_repo_issues_event_min_datetime": "2017-01-15T22:56:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:03:36.000Z", "max_forks_repo_path": "external_libraries/vexcl/tests/multivector_arithmetics.cpp", "max_forks_repo_name": "lkusch/Kratos", "max_forks_repo_head_hexsha": "e8072d8e24ab6f312765185b19d439f01ab7b27b", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": 224.0, "max_forks_repo_forks_event_min_datetime": "2017-02-07T14:12:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-06T23:09:34.000Z", "avg_line_length": 26.5532786885, "max_line_length": 94, "alphanum_fraction": 0.5604259917, "num_tokens": 2100, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311856832191, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4729071255451592}}
{"text": "#include <boost/chrono.hpp>\n\n#include <sstream>\n#include <fstream>\n#include <iostream>\n#include <vector>\n#include <cstdlib>\n\n\n#include <Snap.h>\n#include <boost/lexical_cast.hpp>\n\nnamespace timens = boost::chrono;\nusing namespace std;\n\nint main(int argc, const char** argv) {\n\n\n    //Input Graph\n    const TStr InFNm = TStr(argv[1]);\n    //Output file\n    const TStr OutFNm = TStr(argv[2]);\n    //File with list of nodes\n    const TStr argsMod = TStr(argv[3]);\n    //File with list of pairs of nodes\n    const TStr pairNodes = TStr(argv[4]);\n\n    printf(\"Loading %s...\", InFNm.CStr());\n    TIntFltH BtwH, EigH, PRankH, CcfH, CloseH, HubH, AuthH;\n\n    std::chrono::milliseconds durationPR;\n    PNGraph Graph = TSnap::LoadEdgeList<PNGraph>(InFNm);\n    PUNGraph UGraph = TSnap::ConvertGraph<PUNGraph>(Graph);\n\n    std::chrono::system_clock::time_point start = std::chrono::system_clock::now();\n    TSnap::GetPageRank(Graph, PRankH, 0.85, 0, 100);\n    durationPR = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - start);\n    cout << endl << \"Runtime PR: \" << durationPR.count() << \" ms.\" << endl;\n\n    start = std::chrono::system_clock::now();\n    TSnap::GetHits(Graph, HubH, AuthH);\n    std::chrono::milliseconds durationHits = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - start);\n    cout << endl << \"Runtime Hits: \" << durationHits.count() << \" ms.\" << endl;\n\n    //start = std::chrono::system_clock::now();\n    //TSnap::GetEigenVectorCentr(UGraph, EigH);\n    //std::chrono::milliseconds durationEV = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - start);\n    //cout << endl << \"Runtime EigenVector: \" << durationEV.count() << \" ms.\" << endl;\n\n    start = std::chrono::system_clock::now();\n    TSnap::GetNodeClustCf_scala(UGraph, CcfH);\n    std::chrono::milliseconds durationCF = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - start);\n    cout << endl << \"Runtime ClusterCoeff: \" << durationCF.count() << \" ms.\" << endl;\n\n    start = std::chrono::system_clock::now();\n    long c = TSnap::CountTriangles(Graph);\n    std::chrono::milliseconds durationTriangles = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - start);\n    cout << endl << \"Runtime Triangles: \" << durationTriangles.count() << \" ms.\" << c << endl;\n\n    start = std::chrono::system_clock::now();\n    long output = TSnap::GetBfsFullDiam(Graph, 1000, true);\n    std::chrono::milliseconds durationDiam = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - start);\n    cout << endl << \"Runtime Diameter: \" << durationDiam.count() << \" ms.\" << output << endl;\n\n    start = std::chrono::system_clock::now();\n    double outputWcc = TSnap::GetMxWccSz(Graph);\n    std::chrono::milliseconds durationMaxWcc = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - start);\n    cout << endl << \"Runtime MaxWcc: \" << durationMaxWcc.count() << \" ms.\" << outputWcc << endl;\n\n    start = std::chrono::system_clock::now();\n    double outputScc = TSnap::GetMxSccSz(Graph);\n    std::chrono::milliseconds durationMaxScc = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - start);\n    cout << endl << \"Runtime MaxScc: \" << durationMaxScc.count() << \" ms.\" << outputScc << endl;\n\n    TIntV Values;\n    std::vector<long> InputNodes;\n    std::ifstream ifs(string(argsMod.CStr()));\n    std::string line;\n    while (std::getline(ifs, line)) {\n        int v = boost::lexical_cast<int>(line);\n        Values.Add(v);\n        InputNodes.push_back(v);\n    }\n    ifs.close();\n    long len = 3;\n    start = std::chrono::system_clock::now();\n    auto randWalk = TSnap::randomWalk2(Graph, InputNodes, len);\n    std::chrono::milliseconds durationRW = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - start);\n    cout << endl << \"Runtime RandomWalk: \" << durationRW.count() << \" ms.\" << randWalk.size() << endl;\n\n    std::ifstream ifs2(string(pairNodes.CStr()));\n    std::vector<std::pair<long, long>> pairs;\n    while (std::getline(ifs2, line)) {\n        auto pos = line.find('\\t');\n        long v1 = boost::lexical_cast<long>(line.substr(0, pos));\n        long v2 = boost::lexical_cast<long>(line.substr(pos+1, line.size()));\n        pairs.push_back(std::make_pair(v1, v2));\n    }\n    ifs2.close();\n    start = std::chrono::system_clock::now();\n    auto bfsoutput = TSnap::GetShortPath(Graph, pairs);\n    std::chrono::milliseconds durationBFS = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - start);\n    cout << endl << \"Runtime BFS: \" << durationBFS.count() << \" ms. \" << bfsoutput.size() << endl;\n\n\n    const int edges = Graph->GetEdges();\n    start = std::chrono::system_clock::now();\n    double outputMod = TSnap::GetModularity(Graph, Values, edges);\n    std::chrono::milliseconds durationMod = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - start);\n    cout << endl << \"Runtime Mod: \" << durationMod.count() << \" ms. \" << outputMod << endl;\n\n    start = std::chrono::system_clock::now();\n    TSnap::GetBetweennessCentr(Graph, BtwH);\n    std::chrono::milliseconds durationBetCentr = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - start);\n    cout << endl << \"Runtime BetCentr: \" << durationBetCentr.count() << \" ms.\" << endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "339464e5ab30bc1c7b97e218c215bb8197b8ba1f", "size": 5558, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_snap.cpp", "max_stars_repo_name": "jrbn/trident", "max_stars_repo_head_hexsha": "e56a4977054eea01cb3f716db92bde5d6a49bfb7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/test_snap.cpp", "max_issues_repo_name": "jrbn/trident", "max_issues_repo_head_hexsha": "e56a4977054eea01cb3f716db92bde5d6a49bfb7", "max_issues_repo_licenses": ["Apache-2.0"], "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/test_snap.cpp", "max_forks_repo_name": "jrbn/trident", "max_forks_repo_head_hexsha": "e56a4977054eea01cb3f716db92bde5d6a49bfb7", "max_forks_repo_licenses": ["Apache-2.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.7058823529, "max_line_length": 146, "alphanum_fraction": 0.6550917596, "num_tokens": 1505, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.787931185683219, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.47290712554515907}}
{"text": "#include <cstdlib>\n#include <iostream>\n#include <complex>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/bindings/ublas/vector.hpp>\n#include <boost/numeric/bindings/ublas/matrix.hpp>\n#include <boost/numeric/bindings/blas/level1.hpp>\n#include <boost/numeric/bindings/blas/level2.hpp>\n#include <boost/numeric/bindings/lapack/driver.hpp>\n#include <boost/numeric/bindings/lower.hpp>\n#include <boost/numeric/bindings/upper.hpp>\n#include \"random.hpp\"\n\nnamespace ublas=boost::numeric::ublas;\nnamespace blas=boost::numeric::bindings::blas;\nnamespace lapack=boost::numeric::bindings::lapack;\n\nint main(int argc, char *argv[]) {\n  typedef std::complex<double> complex;\n  typedef ublas::vector<complex> vector;\n  typedef ublas::matrix<complex, ublas::column_major> matrix;\n  typedef typename vector::size_type size_type;\n\n  rand_normal<complex>::reset();\n  int n=128;\n  // generate a random unitary matrix\n  matrix U(n, n);\n  for (size_type j=0; j<n; ++j)\n    for (size_type i=0; i<n; ++i)\n      U(i, j)=i==j ? complex(1) : complex(0);\n  for (int k=0; k<n*n; ++k) {\n    // generate a random 2x2 unitary matrix\n    double phi(rand_uniform<double>::get(0, 1.5707963267948966192));\n    double alpha(rand_uniform<double>::get(0, 6.2831853071795864770));\n    double psi(rand_uniform<double>::get(0, 6.2831853071795864770));\n    double chi(rand_uniform<double>::get(0, 6.2831853071795864770));\n    matrix u(2, 2);\n    u(0, 0)=complex(std::cos(alpha+psi), std::sin(alpha+psi))*std::cos(phi);\n    u(1, 0)=-complex(std::cos(alpha-chi), std::sin(alpha-chi))*std::sin(phi);\n    u(0, 1)=complex(std::cos(alpha+chi), std::sin(alpha+chi))*std::sin(phi);\n    u(1, 1)=complex(std::cos(alpha-psi), std::sin(alpha-psi))*std::cos(phi);\n    int j0, j1;\n    j0=static_cast<int>(rand_uniform<double>::get(0, n));\n    do {\n      j1=static_cast<int>(rand_uniform<double>::get(0, n));\n    } while (j0==j1);\n    for (size_type i=0; i<n; ++i) {\n      vector Uc(2);\n      Uc(0)=U(j0, i);\n      Uc(1)=U(j1, i);\n      Uc=ublas::prod(u, Uc);\n      U(j0, i)=Uc(0);\n      U(j1, i)=Uc(1);\n    }\n  }\n  matrix R(ublas::prod(ublas::trans(ublas::conj(U)), U));\n  // generate random positive definite hermitian matrix\n  matrix A(n, n);\n  for (size_type j=0; j<n; ++j)\n    for (size_type i=0; i<n; ++i)\n      if (i==j)\n\t// eigenvalues drawn from the positive half of the normal distribution\n\tdo {\n\t  A(i, j)=std::abs(rand_normal<complex>::get());\n\t} while (A(i, j)==complex(0));\n      else\n\tA(i, j)=complex(0);\n  // apply a random unitary transform to A\n  A=ublas::prod(ublas::trans(ublas::conj(U)), A);\n  A=ublas::prod(A, U);\n  matrix A_bak(A);\n  vector b(n);\n  for (size_type i=0; i<n; ++i)\n    b(i)=rand_normal<complex>::get();\n  vector x(b);\n  int info=lapack::posv(lapack::upper(A), x); // solve\n  if (info==0) {\n    // res <- A*x - b\n    vector res(b);\n    blas::gemv(complex(1, 0), A_bak, x, complex(-1, 0), res);\n    std::cout << \"norm of residual : \" << blas::nrm2(res) << '\\n';\n  } else\n    if (info>0)\n      std::cout << \"singular matrix\\n\";\n    else \n      std::cout << \"illegal arguments\\n\";\n  return EXIT_SUCCESS;\n}\n\n", "meta": {"hexsha": "bf0c955d716204b4a6f2851363b815089bcba898", "size": 3141, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/lapack/posv.cc", "max_stars_repo_name": "rabauke/numeric_bindings", "max_stars_repo_head_hexsha": "f4de93bd7a01a8b31c9367fad35c81d086768f99", "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/lapack/posv.cc", "max_issues_repo_name": "rabauke/numeric_bindings", "max_issues_repo_head_hexsha": "f4de93bd7a01a8b31c9367fad35c81d086768f99", "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/lapack/posv.cc", "max_forks_repo_name": "rabauke/numeric_bindings", "max_forks_repo_head_hexsha": "f4de93bd7a01a8b31c9367fad35c81d086768f99", "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.5164835165, "max_line_length": 77, "alphanum_fraction": 0.6389684814, "num_tokens": 1040, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961425, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4728991724889683}}
{"text": "/******************************************************************************\n * Copyright (C) 2014 by Jerome Maye                                          *\n * jerome.maye@gmail.com                                                      *\n ******************************************************************************/\n\n/** \\file analyzer.cpp\n    \\brief This file analyzes realworld data.\n  */\n\n#include <cmath>\n\n#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <algorithm>\n#include <string>\n#include <vector>\n\n#include <Eigen/Core>\n\n#include <rosbag/bag.h>\n#include <rosbag/view.h>\n#include <rosbag/message_instance.h>\n\n#include <sm/kinematics/Transformation.hpp>\n#include <sm/kinematics/rotations.hpp>\n#include <sm/kinematics/EulerAnglesYawPitchRoll.hpp>\n#include <sm/kinematics/quaternion_algebra.hpp>\n\n#include <sm/BoostPropertyTree.hpp>\n\n#include <sm/timing/TimestampCorrector.hpp>\n#include <sm/timing/NsecTimeUtilities.hpp>\n\n#include <poslv/VehicleNavigationSolutionMsg.h>\n#include <poslv/VehicleNavigationPerformanceMsg.h>\n#include <poslv/TimeTaggedDMIDataMsg.h>\n\n#include <can_prius/FrontWheelsSpeedMsg.h>\n#include <can_prius/RearWheelsSpeedMsg.h>\n#include <can_prius/Steering1Msg.h>\n\n#include \"aslam/calibration/car/algo/CarCalibrator.h\"\n#include \"aslam/calibration/car/algo/splinesToFile.h\"\n#include \"aslam/calibration/car/data/WheelSpeedsMeasurement.h\"\n#include \"aslam/calibration/car/data/SteeringMeasurement.h\"\n#include \"aslam/calibration/car/data/DMIMeasurement.h\"\n#include \"aslam/calibration/car/data/PoseMeasurement.h\"\n#include \"aslam/calibration/car/data/VelocitiesMeasurement.h\"\n#include \"aslam/calibration/car/geo/geodetic.h\"\n\nusing namespace sm;\nusing namespace sm::timing;\nusing namespace sm::kinematics;\nusing namespace aslam::calibration;\n\nint main(int argc, char** argv) {\n\n  if (argc != 3) {\n    std::cerr << \"Usage: \" << argv[0] << \" <bag_file> <conf_file>\" << std::endl;\n    return -1;\n  }\n\n  BoostPropertyTree config;\n  config.loadXml(argv[2]);\n\n  const bool useDMI =\n    config.getBool(\"car/calibrator/odometry/sensors/dmi/active\");\n  const bool useFw =\n    config.getBool(\"car/calibrator/odometry/sensors/fws/active\");\n  const bool useRw =\n    config.getBool(\"car/calibrator/odometry/sensors/rws/active\");\n  const bool useSt =\n    config.getBool(\"car/calibrator/odometry/sensors/st/active\");\n\n  CarCalibrator calibrator(PropertyTree(config, \"car/calibrator\"));\n\n  std::ofstream rwDataFile(\"rwData.txt\");\n  rwDataFile << std::fixed << std::setprecision(18);\n  std::ofstream fwDataFile(\"fwData.txt\");\n  fwDataFile << std::fixed << std::setprecision(18);\n  std::ofstream stDataFile(\"stData.txt\");\n  stDataFile << std::fixed << std::setprecision(18);\n  std::ofstream dmiDataFile(\"dmiData.txt\");\n  dmiDataFile << std::fixed << std::setprecision(18);\n  std::ofstream poseDataFile(\"poseData.txt\");\n  poseDataFile << std::fixed << std::setprecision(18);\n  std::ofstream velDataFile(\"velData.txt\");\n  velDataFile << std::fixed << std::setprecision(18);\n\n  rosbag::Bag bag(argv[1]);\n  std::vector<std::string> topics;\n  topics.push_back(config.getString(\n    \"car/calibrator/odometry/sensors/fws/topic\"));\n  topics.push_back(config.getString(\n    \"car/calibrator/odometry/sensors/rws/topic\"));\n  topics.push_back(config.getString(\n    \"car/calibrator/odometry/sensors/st/topic\"));\n  topics.push_back(config.getString(\n    \"car/calibrator/odometry/sensors/dmi/topic\"));\n  topics.push_back(config.getString(\n    \"car/calibrator/applanix/vns/topic\"));\n  topics.push_back(config.getString(\n    \"car/calibrator/applanix/vnp/topic\"));\n  rosbag::View view(bag, rosbag::TopicQuery(topics));\n  TimestampCorrector<double> timestampCorrectorVns;\n  TimestampCorrector<double> timestampCorrectorDmi;\n  TimestampCorrector<double> timestampCorrectorFw;\n  TimestampCorrector<double> timestampCorrectorRw;\n  TimestampCorrector<double> timestampCorrectorSt;\n  double lastDMITimestamp = -1;\n  double lastDMIDistance = -1;\n  bool firstVns = true;\n  poslv::VehicleNavigationPerformanceMsgConstPtr lastVnp;\n  Transformation m_T_e;\n  const EulerAnglesYawPitchRoll ypr;\n  Transformation m_T_r_0;\n  for (auto it = view.begin(); it != view.end(); ++it) {\n    if (it->getTopic() == config.getString(\n        \"car/calibrator/applanix/vnp/topic\")) {\n      poslv::VehicleNavigationPerformanceMsgConstPtr vnp(\n        it->instantiate<poslv::VehicleNavigationPerformanceMsg>());\n      lastVnp = vnp;\n    }\n    if (it->getTopic() == config.getString(\n        \"car/calibrator/applanix/vns/topic\")) {\n      if (!lastVnp)\n        continue;\n      poslv::VehicleNavigationSolutionMsgConstPtr vns(\n        it->instantiate<poslv::VehicleNavigationSolutionMsg>());\n      double x_ecef, y_ecef, z_ecef;\n      wgs84ToEcef(deg2rad(vns->latitude), deg2rad(vns->longitude),\n        vns->altitude, x_ecef, y_ecef, z_ecef);\n      if (firstVns) {\n        m_T_e = ecef2enu(x_ecef, y_ecef, z_ecef, deg2rad(vns->latitude),\n          deg2rad(vns->longitude));\n      }\n      PoseMeasurement pose;\n      pose.m_r_mr = m_T_e * Eigen::Vector3d(x_ecef, y_ecef, z_ecef);\n      const Eigen::Matrix3d l_ned_R_r = ypr.parametersToRotationMatrix(\n        Eigen::Vector3d(deg2rad(vns->heading), deg2rad(vns->pitch),\n        deg2rad(vns->roll)));\n      const Transformation e_T_l_ned = ned2ecef(x_ecef, y_ecef, z_ecef,\n        deg2rad(vns->latitude), deg2rad(vns->longitude));\n      pose.m_R_r = ypr.rotationMatrixToParameters(m_T_e.C() * e_T_l_ned.C() *\n        l_ned_R_r);\n      pose.sigma2_m_r_mr = Eigen::Vector3d(lastVnp->northPositionRMSError *\n        lastVnp->northPositionRMSError, lastVnp->eastPositionRMSError *\n        lastVnp->eastPositionRMSError, lastVnp->downPositionRMSError *\n        lastVnp->downPositionRMSError).asDiagonal();\n      pose.sigma2_m_R_r = Eigen::Vector3d(deg2rad(lastVnp->headingRMSError) *\n        deg2rad(lastVnp->headingRMSError), deg2rad(lastVnp->pitchRMSError) *\n        deg2rad(lastVnp->pitchRMSError), deg2rad(lastVnp->rollRMSError) *\n        deg2rad(lastVnp->rollRMSError)).asDiagonal();\n      poseDataFile << vns->header.stamp.toSec() << \" \" <<\n        pose.m_r_mr.transpose() << \" \" << pose.m_R_r.transpose() <<\n        \" \" << pose.sigma2_m_r_mr.diagonal().transpose() << \" \" <<\n        pose.sigma2_m_R_r.diagonal().transpose() << std::endl;\n      if (firstVns) {\n        m_T_r_0 = Transformation(\n          r2quat(ypr.parametersToRotationMatrix(pose.m_R_r)), pose.m_r_mr);\n        firstVns = false;\n      }\n      VelocitiesMeasurement vel;\n      vel.r_v_mr = l_ned_R_r.transpose() * Eigen::Vector3d(vns->northVelocity,\n        vns->eastVelocity, vns->downVelocity);\n      vel.sigma2_r_v_mr = Eigen::Vector3d(lastVnp->northVelocityRMSError *\n        lastVnp->northVelocityRMSError, lastVnp->eastVelocityRMSError *\n        lastVnp->eastVelocityRMSError, lastVnp->downVelocityRMSError *\n        lastVnp->downVelocityRMSError).asDiagonal();\n      vel.r_om_mr = Eigen::Vector3d(deg2rad(vns->angularRateLong),\n        deg2rad(vns->angularRateTrans), deg2rad(vns->angularRateDown));\n      vel.sigma2_r_om_mr = Eigen::Vector3d(deg2rad(lastVnp->rollRMSError) *\n        deg2rad(lastVnp->rollRMSError), deg2rad(lastVnp->pitchRMSError) *\n        deg2rad(lastVnp->pitchRMSError), deg2rad(lastVnp->headingRMSError) *\n        deg2rad(lastVnp->headingRMSError)).asDiagonal();\n      velDataFile << vns->header.stamp.toSec() << \" \" <<\n        vel.r_v_mr.transpose() << \" \" << vel.r_om_mr.transpose() <<\n        \" \" << vel.sigma2_r_v_mr.diagonal().transpose() << \" \" <<\n        vel.sigma2_r_om_mr.diagonal().transpose() << std::endl;\n      auto timestamp = std::round(timestampCorrectorVns.correctTimestamp(\n        secToNsec(vns->timeDistance.time1), vns->header.stamp.toNSec()));\n      calibrator.addPoseMeasurement(pose, timestamp);\n      calibrator.addVelocitiesMeasurement(vel, timestamp);\n    }\n    if (it->getTopic() == config.getString(\n        \"car/calibrator/odometry/sensors/fws/topic\") && useFw) {\n      can_prius::FrontWheelsSpeedMsgConstPtr fws(\n        it->instantiate<can_prius::FrontWheelsSpeedMsg>());\n      WheelSpeedsMeasurement data;\n      data.left = fws->Left;\n      data.right = fws->Right;\n      auto timestamp = std::round(timestampCorrectorFw.correctTimestamp(\n        fws->header.seq, fws->header.stamp.toNSec()));\n      calibrator.addFrontWheelsMeasurement(data, timestamp);\n      fwDataFile << fws->header.stamp.toSec() << \" \" << data.left << \" \"\n        << data.right << std::endl;\n    }\n    if (it->getTopic() == config.getString(\n        \"car/calibrator/odometry/sensors/rws/topic\") && useRw) {\n      can_prius::RearWheelsSpeedMsgConstPtr rws(\n        it->instantiate<can_prius::RearWheelsSpeedMsg>());\n      WheelSpeedsMeasurement data;\n      data.left = rws->Left;\n      data.right = rws->Right;\n      auto timestamp = std::round(timestampCorrectorRw.correctTimestamp(\n        rws->header.seq, rws->header.stamp.toNSec()));\n      calibrator.addRearWheelsMeasurement(data, timestamp);\n      rwDataFile << rws->header.stamp.toSec() << \" \" << data.left << \" \"\n        << data.right << std::endl;\n    }\n    if (it->getTopic() == config.getString(\n        \"car/calibrator/odometry/sensors/st/topic\") && useSt) {\n      can_prius::Steering1MsgConstPtr st(\n        it->instantiate<can_prius::Steering1Msg>());\n      SteeringMeasurement data;\n      data.value = st->value;\n      auto timestamp = std::round(timestampCorrectorSt.correctTimestamp(\n        st->header.seq, st->header.stamp.toNSec()));\n      calibrator.addSteeringMeasurement(data, timestamp);\n      stDataFile << st->header.stamp.toSec() << \" \" << data.value << std::endl;\n    }\n    if (it->getTopic() == config.getString(\n        \"car/calibrator/odometry/sensors/dmi/topic\") && useDMI) {\n      poslv::TimeTaggedDMIDataMsgConstPtr dmi(\n        it->instantiate<poslv::TimeTaggedDMIDataMsg>());\n      if (lastDMITimestamp != -1) {\n        DMIMeasurement data;\n        data.wheelSpeed = (dmi->signedDistanceTraveled - lastDMIDistance) /\n          (dmi->timeDistance.time1 - lastDMITimestamp);\n        calibrator.addDMIMeasurement(data,\n          std::round(timestampCorrectorDmi.correctTimestamp(\n          secToNsec(dmi->timeDistance.time1), dmi->header.stamp.toNSec())));\n        dmiDataFile << dmi->header.stamp.toSec() << \" \" << data.wheelSpeed\n          << std::endl;\n      }\n      lastDMITimestamp = dmi->timeDistance.time1;\n      lastDMIDistance = dmi->signedDistanceTraveled;\n    }\n  }\n\n  if (calibrator.unprocessedMeasurements())\n    calibrator.predict();\n\n  std::ofstream m_T_v_estFile(\"m_T_v.txt\");\n  m_T_v_estFile << std::fixed << std::setprecision(18);\n  writeSplines(calibrator.getEstimator(), 0.01, m_T_v_estFile);\n\n  std::ofstream rwDataPredFile(\"rwDataPred.txt\");\n  rwDataPredFile << std::fixed << std::setprecision(18);\n  std::for_each(calibrator.getRearWheelsPredictions().cbegin(),\n    calibrator.getRearWheelsPredictions().cend(), [&](decltype(\n    *calibrator.getRearWheelsPredictions().cbegin()) x) {rwDataPredFile\n    << nsecToSec(x.first) << \" \" << x.second.left << \" \" << x.second.right <<\n    std::endl;});\n  std::ofstream rwPredError(\"rwPredError.txt\");\n  rwPredError << std::fixed << std::setprecision(18);\n  std::for_each(calibrator.getRearWheelsPredictionErrors().cbegin(),\n    calibrator.getRearWheelsPredictionErrors().cend(), [&](decltype(\n    *calibrator.getRearWheelsPredictionErrors().cbegin()) x) {rwPredError\n    << x.transpose() << std::endl;});\n  std::ofstream fwDataPredFile(\"fwDataPred.txt\");\n  fwDataPredFile << std::fixed << std::setprecision(18);\n  std::for_each(calibrator.getFrontWheelsPredictions().cbegin(),\n    calibrator.getFrontWheelsPredictions().cend(), [&](decltype(\n    *calibrator.getFrontWheelsPredictions().cbegin()) x) {fwDataPredFile\n    << nsecToSec(x.first) << \" \" << x.second.left << \" \" << x.second.right <<\n    std::endl;});\n  std::ofstream fwPredError(\"fwPredError.txt\");\n  fwPredError << std::fixed << std::setprecision(18);\n  std::for_each(calibrator.getFrontWheelsPredictionErrors().cbegin(),\n    calibrator.getFrontWheelsPredictionErrors().cend(), [&](decltype(\n    *calibrator.getFrontWheelsPredictionErrors().cbegin()) x) {fwPredError\n    << x.transpose() << std::endl;});\n  std::ofstream stDataPredFile(\"stDataPred.txt\");\n  stDataPredFile << std::fixed << std::setprecision(18);\n  std::for_each(calibrator.getSteeringPredictions().cbegin(),\n    calibrator.getSteeringPredictions().cend(), [&](decltype(\n    *calibrator.getSteeringPredictions().cbegin()) x) {stDataPredFile\n    << nsecToSec(x.first) << \" \" << x.second.value <<std::endl;});\n  std::ofstream stPredError(\"stPredError.txt\");\n  stPredError << std::fixed << std::setprecision(18);\n  std::for_each(calibrator.getSteeringPredictionErrors().cbegin(),\n    calibrator.getSteeringPredictionErrors().cend(), [&](decltype(\n    *calibrator.getSteeringPredictionErrors().cbegin()) x) {stPredError\n    << x.transpose() << std::endl;});\n  std::ofstream dmiDataPredFile(\"dmiDataPred.txt\");\n  dmiDataPredFile << std::fixed << std::setprecision(18);\n  std::for_each(calibrator.getDMIPredictions().cbegin(),\n    calibrator.getDMIPredictions().cend(), [&](decltype(\n    *calibrator.getDMIPredictions().cbegin()) x) {dmiDataPredFile\n    << nsecToSec(x.first) << \" \" << x.second.wheelSpeed << std::endl;});\n  std::ofstream dmiPredError(\"dmiPredError.txt\");\n  dmiPredError << std::fixed << std::setprecision(18);\n  std::for_each(calibrator.getDMIPredictionErrors().cbegin(),\n    calibrator.getDMIPredictionErrors().cend(), [&](decltype(\n    *calibrator.getDMIPredictionErrors().cbegin()) x) {dmiPredError\n    << x.transpose() << std::endl;});\n  std::ofstream poseDataPredFile(\"poseDataPred.txt\");\n  poseDataPredFile << std::fixed << std::setprecision(18);\n  std::for_each(calibrator.getPosePredictions().cbegin(),\n    calibrator.getPosePredictions().cend(), [&](decltype(\n    *calibrator.getPosePredictions().cbegin()) x) {poseDataPredFile\n    << nsecToSec(x.first) << \" \" << x.second.m_r_mr.transpose() << \" \"\n    << x.second.m_R_r.transpose() << std::endl;});\n  std::ofstream posePredError(\"posePredError.txt\");\n  posePredError << std::fixed << std::setprecision(18);\n  std::for_each(calibrator.getPosePredictionErrors().cbegin(),\n    calibrator.getPosePredictionErrors().cend(), [&](decltype(\n    *calibrator.getPosePredictionErrors().cbegin()) x) {posePredError\n    << x.transpose() << std::endl;});\n  std::ofstream velDataPredFile(\"velDataPred.txt\");\n  velDataPredFile << std::fixed << std::setprecision(18);\n  std::for_each(calibrator.getVelocitiesPredictions().cbegin(),\n    calibrator.getVelocitiesPredictions().cend(), [&](decltype(\n    *calibrator.getVelocitiesPredictions().cbegin()) x) {velDataPredFile\n    << nsecToSec(x.first) << \" \" << x.second.r_v_mr.transpose() << \" \"\n    << x.second.r_om_mr.transpose() << std::endl;});\n  std::ofstream velPredError(\"velPredError.txt\");\n  velPredError << std::fixed << std::setprecision(18);\n  std::for_each(calibrator.getVelocitiesPredictionErrors().cbegin(),\n    calibrator.getVelocitiesPredictionErrors().cend(), [&](decltype(\n    *calibrator.getVelocitiesPredictionErrors().cbegin()) x) {velPredError\n    << x.transpose() << std::endl;});\n\n  return 0;\n}\n", "meta": {"hexsha": "73f1a620c8a4153482e5afc1649dda7a807b30c8", "size": 15114, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "incremental_calibration_examples/incremental_calibration_examples_car/src/realworld/analyzer.cpp", "max_stars_repo_name": "ethz-asl/aslam_incremental_calibration", "max_stars_repo_head_hexsha": "16a44b86b6e7eb5ae4ee247f10c429494697ae0b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2017-08-23T06:29:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-17T16:56:29.000Z", "max_issues_repo_path": "incremental_calibration_examples/incremental_calibration_examples_car/src/realworld/analyzer.cpp", "max_issues_repo_name": "ethz-asl/aslam_incremental_calibration", "max_issues_repo_head_hexsha": "16a44b86b6e7eb5ae4ee247f10c429494697ae0b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-02-14T16:02:18.000Z", "max_issues_repo_issues_event_max_datetime": "2017-02-14T16:02:18.000Z", "max_forks_repo_path": "incremental_calibration_examples/incremental_calibration_examples_car/src/realworld/analyzer.cpp", "max_forks_repo_name": "ethz-asl/aslam_incremental_calibration", "max_forks_repo_head_hexsha": "16a44b86b6e7eb5ae4ee247f10c429494697ae0b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2017-01-23T09:01:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-10T05:13:23.000Z", "avg_line_length": 46.0792682927, "max_line_length": 80, "alphanum_fraction": 0.6841339156, "num_tokens": 4112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034369, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4728991678517451}}
{"text": "\r\n// Copyright Aleksey Gurtovoy 2004\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/mpl for documentation.\r\n\r\n// $Id: partition.cpp 49268 2008-10-11 06:26:17Z agurtovoy $\r\n// $Date: 2008-10-10 23:26:17 -0700 (Fri, 10 Oct 2008) $\r\n// $Revision: 49268 $\r\n\r\n#include <boost/mpl/partition.hpp>\r\n#include <boost/mpl/vector.hpp>\r\n#include <boost/mpl/vector_c.hpp>\r\n#include <boost/mpl/range_c.hpp>\r\n#include <boost/mpl/back_inserter.hpp>\r\n#include <boost/mpl/equal.hpp>\r\n#include <boost/mpl/modulus.hpp>\r\n#include <boost/mpl/int.hpp>\r\n#include <boost/mpl/aux_/test.hpp>\r\n\r\ntemplate< typename N > struct is_odd\r\n    : modulus< N, int_<2> > \r\n{\r\n    BOOST_MPL_AUX_LAMBDA_SUPPORT(1, is_odd, (N))\r\n};\r\n\r\n\r\nMPL_TEST_CASE()\r\n{\r\n    typedef partition<\r\n          range_c<int,0,10> \r\n        , is_odd<_1>\r\n        , mpl::back_inserter< vector<> >\r\n        , mpl::back_inserter< vector<> >\r\n        >::type r;\r\n\r\n    MPL_ASSERT(( equal< r::first, vector_c<int,1,3,5,7,9> > ));\r\n    MPL_ASSERT(( equal< r::second, vector_c<int,0,2,4,6,8> > ));\r\n}\r\n", "meta": {"hexsha": "33bdf6069bdd0cc95522c358ffa9620914c6a313", "size": 1188, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/mpl/test/partition.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/mpl/test/partition.cpp", "max_issues_repo_name": "xiaoliang2121/Boost", "max_issues_repo_head_hexsha": "fc90c3fde129c62565c023f091eddc4a7ed9902b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-03-19T08:23:23.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-24T07:48:47.000Z", "max_forks_repo_path": "libs/mpl/test/partition.cpp", "max_forks_repo_name": "xiaoliang2121/Boost", "max_forks_repo_head_hexsha": "fc90c3fde129c62565c023f091eddc4a7ed9902b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 27.6279069767, "max_line_length": 65, "alphanum_fraction": 0.6372053872, "num_tokens": 372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494678483918, "lm_q2_score": 0.6893056295505783, "lm_q1q2_score": 0.47282882977511986}}
{"text": "//==================================================================================================\n/*!\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#include <boost/simd/function/scalar/plus.hpp>\n#include <scalar_test.hpp>\n#include <boost/simd/detail/dispatch/meta/as_integer.hpp>\n#include <boost/simd/constant/inf.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/zero.hpp>\n#include <boost/simd/constant/valmin.hpp>\n#include <boost/simd/constant/valmax.hpp>\n#include <boost/simd/constant/mtwo.hpp>\n#include <boost/simd/constant/two.hpp>\n\n//saturated_TODO\nSTF_CASE_TPL (\" plus signed int\",  STF_SIGNED_INTEGRAL_TYPES)\n{\n  namespace bs = boost::simd;\n\n  using bs::plus;\n  using r_t = decltype(bs::saturated_(plus)(T(),T()));\n  typedef T wished_r_t;\n\n\n  // return type conformity test\n  STF_TYPE_IS(r_t, wished_r_t);\n\n  // specific values tests\n  STF_EQUAL(bs::saturated_(plus)(bs::Mone<T>(), bs::Mone<T>()), bs::Mtwo<T>());\n  STF_EQUAL(bs::saturated_(plus)(bs::One<T>(), bs::One<T>()), bs::Two<T>());\n  STF_EQUAL(bs::saturated_(plus)(bs::Valmax<T>(),bs::One<T>()), bs::Valmax<T>());\n  STF_EQUAL(bs::saturated_(plus)(bs::Valmin<T>(),bs::Mone<T>()), bs::Valmin<T>());\n  STF_EQUAL(bs::saturated_(plus)(bs::Zero<T>(), bs::Zero<T>()), bs::Zero<T>());\n} // end of test for signed_int_\n\nSTF_CASE_TPL (\" plus unsigned int\",  STF_UNSIGNED_INTEGRAL_TYPES)\n{\n  namespace bs = boost::simd;\n\n  using bs::plus;\n  using r_t = decltype(bs::saturated_(plus)(T(),T()));\n  typedef T wished_r_t;\n  // return type conformity test\n  STF_TYPE_IS(r_t, wished_r_t);\n\n  // specific values tests\n  STF_EQUAL(bs::saturated_(plus)(bs::One<T>(), bs::One<T>()), bs::Two<T>());\n  STF_EQUAL(bs::saturated_(plus)(bs::Valmax<T>(),bs::One<T>()), bs::Valmax<T>());\n  STF_EQUAL(bs::saturated_(plus)(bs::Zero<T>(), bs::Zero<T>()), bs::Zero<T>());\n} // end of test for unsigned_int_\n\nSTF_CASE_TPL (\" plus real\",  STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n\n  using bs::plus;\n  using r_t = decltype(bs::saturated_(plus)(T(),T()));\n  typedef T wished_r_t;\n\n  // return type conformity test\n  STF_TYPE_IS(r_t, wished_r_t);\n\n  // specific values tests\n#ifndef BOOST_SIMD_NO_INVALIDS\n  STF_EQUAL(bs::saturated_(plus)(bs::Inf<T>(), bs::Inf<T>()), bs::Inf<T>());\n  STF_EQUAL(bs::saturated_(plus)(bs::Minf<T>(), bs::Minf<T>()), bs::Minf<T>());\n  STF_IEEE_EQUAL(bs::saturated_(plus)(bs::Nan<T>(), bs::Nan<T>()), bs::Nan<T>());\n#endif\n  STF_EQUAL(bs::saturated_(plus)(bs::Mone<T>(), bs::Mone<T>()), bs::Mtwo<T>());\n  STF_EQUAL(bs::saturated_(plus)(bs::One<T>(), bs::One<T>()), bs::Two<T>());\n  STF_EQUAL(bs::saturated_(plus)(bs::Zero<T>(), bs::Zero<T>()), bs::Zero<T>());\n} // end of test for floating_\n", "meta": {"hexsha": "a2b69f1986db0dc8b4b3848c7427d2c5134ac370", "size": 3034, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/scalar/plus.saturated.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": "test/function/scalar/plus.saturated.cpp", "max_issues_repo_name": "remymuller/boost.simd", "max_issues_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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/function/scalar/plus.saturated.cpp", "max_forks_repo_name": "remymuller/boost.simd", "max_forks_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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": 37.0, "max_line_length": 100, "alphanum_fraction": 0.6252471984, "num_tokens": 884, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494678483918, "lm_q2_score": 0.6893056104028797, "lm_q1q2_score": 0.47282881664076626}}
{"text": "/*\n\u63d0\u4f9b\u4e86\u4e24\u79cd\u5bfc\u5165\u6570\u636e(double)\u7684\u65b9\u6cd5\uff0c\u4e00\u79cd\u9700\u8981\u63d0\u524d\u77e5\u9053\u7684\u6570\u636e\u7684\u5c3a\u5bf8(m*n)\uff0c\u53e6\u4e00\u79cd\u4e0d\u9700\u8981\ndouble ** load(string filename, int m, int n)\nvoid load(string filename, vector<vector<double> > data)\n*/\n// #include <iostream>\n// #include <string>\n// #include <vector>\n// #include <fstream>\n// #include <sstream>\n// using namespace std;\n\n#include <Eigen/Dense>\n#include \"LoadData.hpp\"\n\nusing namespace Eigen;\n\n// \u9700\u8981\u6307\u5b9a\u6570\u636e\u7684\u884c\u548c\u5217\nMatrix<double, Dynamic, Dynamic> loadEigen(string filename, int m ,int n){\n    Matrix<double, Dynamic, Dynamic> ans(m,n);\n    ifstream inFile(filename, ios::in);\n\tstring lineStr; //\u6bcf\u4e00\u884c\u7684\u7ed3\u679c\n    for(int i=0;i<m;i++){\n        getline(inFile, lineStr);\n        stringstream ss(lineStr);\n        string str;\n        for(int j=0;j<n;j++){\n            getline(ss, str, ',');\n            ans(i,j) = atof(str.c_str());\n        }\n    }\n    return ans;\n}\n\ndouble** load(string filename, int m, int n){\n    // \u521d\u59cb\u5316\u6570\u7ec4\n    double** ans = (double **)malloc(m * sizeof(double *));\n    for(int i=0;i<m;i++)\n        ans[i] = (double *)malloc(n * sizeof(double));\n    \n    ifstream inFile(filename, ios::in);\n\tstring lineStr; //\u6bcf\u4e00\u884c\u7684\u7ed3\u679c\n    for(int i=0;i<m;i++){\n        getline(inFile, lineStr);\n        stringstream ss(lineStr);\n        string str;\n        for(int j=0;j<n;j++){\n            getline(ss, str, ',');\n            ans[i][j] = atof(str.c_str());\n        }\n    }\n    return ans;\n}\n\nvoid load(string filename, vector<vector<double> >& data){\n    ifstream inFile(filename, ios::in);\n\tstring lineStr; //\u6bcf\u4e00\u884c\u7684\u7ed3\u679c\n\n    // \u6bcf\u884c\u7684\u7ed3\u679c\u4f1a\u5b58\u5728lineStr\u4e2d\n\twhile (getline(inFile, lineStr))\n\t{\n\t\t// \u5b58\u6210\u4e8c\u7ef4\u8868\u7ed3\u6784\n\t\tstringstream ss(lineStr);\n\t\tstring str;\n        vector<double> doubleArray;\n\t\t// \u6309\u7167\u9017\u53f7\u5206\u9694\n\t\twhile (getline(ss, str, ',')){\n            doubleArray.push_back(atof(str.c_str()));\n        }\n        data.push_back(doubleArray);\n\t}\n\n}\n\n// \u6d4b\u8bd5\u7528\nvoid test(){\n    // \u7b2c\u4e00\u79cd\u5bfc\u5165\u65b9\u6cd5\u6d4b\u8bd5\n    // vector<vector<double> > data;\n    // LoadData::load(\"testX.csv\",data);\n    // for(int i=0;i<data.size();i++){\n    //     for(int j=0;j<data.at(0).size();j++){\n    //         cout << data.at(i).at(j) << \" \";\n    //     }\n    //     cout << \"\\n\";\n    // }\n\n    // \u7b2c\u4e8c\u79cd\uff1a\u5bfc\u5165m\u884cn\u5217\u7684\u6570\u636e\n    // int m=3,n=1;\n    // double ** ans = load(\"testX.csv\",m,n);\n    // for(int i=0;i<m;i++){\n    //     for(int j=0;j<n;j++){\n    //         cout << ans[i][j] << \" \";\n    //     }\n    //     cout << \"\\n\";\n    // }\n    \n    // \u7b2c\u4e09\u79cd\uff1a\u5bfc\u5165\u4e3aMatrix\u7684\u5f62\u5f0f\n    int m = 100, n = 1;\n    Matrix<double,Dynamic,Dynamic> ans = loadEigen(\"testX.csv\",m,n);\n    // ans.resize(m,n);\n    cout << ans << endl;\n    cout << \"Shape \" << \"( \" << ans.rows() << \", \" << ans.cols() << \" )\" << endl;\n}\n\nint main(){\n    cout << \"Hello World\" << endl;\n    test();\n    return -1;\n}", "meta": {"hexsha": "b832f7351acbce570083a77f1a9673ea5448b9c5", "size": 2646, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "5.1/Machine Learning Algo/C++/LoadData.cpp", "max_stars_repo_name": "Coding4AJob/INF442-Anonymization", "max_stars_repo_head_hexsha": "0c7f07de4e912ca567256db578d5bdc36c0d5767", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "5.1/Machine Learning Algo/C++/LoadData.cpp", "max_issues_repo_name": "Coding4AJob/INF442-Anonymization", "max_issues_repo_head_hexsha": "0c7f07de4e912ca567256db578d5bdc36c0d5767", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "5.1/Machine Learning Algo/C++/LoadData.cpp", "max_forks_repo_name": "Coding4AJob/INF442-Anonymization", "max_forks_repo_head_hexsha": "0c7f07de4e912ca567256db578d5bdc36c0d5767", "max_forks_repo_licenses": ["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.2752293578, "max_line_length": 81, "alphanum_fraction": 0.5313681028, "num_tokens": 824, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081926, "lm_q2_score": 0.6893056231680121, "lm_q1q2_score": 0.47282881654618053}}
{"text": "#include <boost/test/unit_test.hpp>\n#include \"algorithms/math/valid_perfect_square.hpp\"\n\nBOOST_AUTO_TEST_SUITE(TestValidPerfectSquare)\n\nBOOST_AUTO_TEST_CASE(test_vps_check)\n{\n    ValidPerfectSquare::Solution solution;\n    BOOST_CHECK(false == solution.isPerfectSquare(0));\n    BOOST_CHECK(true == solution.isPerfectSquare(1));\n    BOOST_CHECK(false == solution.isPerfectSquare(2));\n    BOOST_CHECK(false == solution.isPerfectSquare(3));\n    BOOST_CHECK(true == solution.isPerfectSquare(4));\n    BOOST_CHECK(false == solution.isPerfectSquare(7));\n    BOOST_CHECK(true == solution.isPerfectSquare(9));\n    BOOST_CHECK(false == solution.isPerfectSquare(15));\n    BOOST_CHECK(true == solution.isPerfectSquare(16));\n    BOOST_CHECK(true == solution.isPerfectSquare(256));\n    BOOST_CHECK(false == solution.isPerfectSquare(257));\n    BOOST_CHECK(false == solution.isPerfectSquare(125348));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "0979afe0a6e6a95dfbfc910549edb8459ba846c1", "size": 915, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/algorithms/math/test_valid_perfect_square.cpp", "max_stars_repo_name": "iamantony/CppNotes", "max_stars_repo_head_hexsha": "2707db6560ad80b0e5e286a04b2d46e5c0280b3f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-07-31T14:13:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-03T09:51:43.000Z", "max_issues_repo_path": "test/algorithms/math/test_valid_perfect_square.cpp", "max_issues_repo_name": "iamantony/CppNotes", "max_issues_repo_head_hexsha": "2707db6560ad80b0e5e286a04b2d46e5c0280b3f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 28.0, "max_issues_repo_issues_event_min_datetime": "2015-09-22T07:38:21.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-02T11:00:58.000Z", "max_forks_repo_path": "test/algorithms/math/test_valid_perfect_square.cpp", "max_forks_repo_name": "iamantony/CppNotes", "max_forks_repo_head_hexsha": "2707db6560ad80b0e5e286a04b2d46e5c0280b3f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-10-11T14:10:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-27T08:53:50.000Z", "avg_line_length": 38.125, "max_line_length": 59, "alphanum_fraction": 0.7584699454, "num_tokens": 199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081925, "lm_q2_score": 0.6893056167854461, "lm_q1q2_score": 0.4728288121680627}}
{"text": "// Bring in gtest\n#include <gtest/gtest.h>\n#include <boost/cstdint.hpp>\n\n// Helpful functions from libasrl\n#include <sm/eigen/gtest.hpp>\n\n#include <sparse_block_matrix/linear_solver_cholmod.h>\n#include <sparse_block_matrix/linear_solver_dense.h>\n#include <sparse_block_matrix/linear_solver_spqr.h>\n\ntemplate<typename SOLVER_T>\nvoid randomSparseBlockMatrix(sparse_block_matrix::SparseBlockMatrix<typename SOLVER_T::matrix_t> * A,   Eigen::MatrixXd & Adense ) {\n\ttypedef typename SOLVER_T::matrix_t SparseMatrixBlock;\n\n\t// Fill in like this:\n\t  //   0  1   2\n\t  // 0 a\n\t  // 1    b   d\n\t  // 2        c\n\t  //\n\t  // where a,b,c are symmetric\n\t  // d is 3x5\n\n\t  SparseMatrixBlock * a = A->block(0,0,true);\n\t  ASSERT_TRUE(a != NULL);\n\t  ASSERT_EQ(a->rows(),3);\n\t  ASSERT_EQ(a->cols(),3);\n\t  a->setRandom();\n\t  *a = (*a * a->transpose()) + Eigen::Matrix3d::Identity();\n\t  Adense.block(0,0,3,3) = *a;\n\n\t  SparseMatrixBlock * b = A->block(1,1,true);\n\t  ASSERT_TRUE(b != NULL);\n\t  ASSERT_EQ(b->rows(),3);\n\t  ASSERT_EQ(b->cols(),3);\n\t  b->setRandom();\n\t  *b = (*b * b->transpose()) + Eigen::Matrix3d::Identity();\n\t  Adense.block(3,3,3,3) = *b;\n\n\t  SparseMatrixBlock * c = A->block(2,2,true);\n\t  ASSERT_TRUE(c != NULL);\n\t  ASSERT_EQ(c->rows(),5);\n\t  ASSERT_EQ(c->cols(),5);\n\t  c->setRandom();\n\t  *c = (*c * c->transpose()).eval() + Eigen::MatrixXd::Identity(5,5);\n\t  //std::cout << \"c:\\n\" << *c << std::endl;\n\t  Adense.block(6,6,5,5) = *c;\n\n\t  SparseMatrixBlock * d = A->block(1,2,true);\n\t  ASSERT_TRUE(d != NULL);\n\t  ASSERT_EQ(d->rows(),3);\n\t  ASSERT_EQ(d->cols(),5);\n\t  d->setRandom();\n\t  Adense.block(3,6,3,5) = *d;\n\n}\n\n\n\n\ntemplate<typename SOLVER_T>\nvoid testSolver(const std::string & solver_name)\n{  \n  // Build up a sparse matrix\n  // 3x3 3x3 3x5\n  // 3x3 3x3 3x5\n  // 5x3 5x3 5x5\n  int rows[] = {3,6,11};\n  int cols[] = {3,6,11};\n  sparse_block_matrix::SparseBlockMatrix<typename SOLVER_T::matrix_t> A(rows,cols,3,3);\n\n  Eigen::MatrixXd Adense(11,11);\n  Adense.setZero();\n\n  ASSERT_EQ(A.rows(),11);\n  ASSERT_EQ(A.cols(),11);\n\n  randomSparseBlockMatrix<SOLVER_T>(&A, Adense);\n\n\n\n  Eigen::VectorXd xx(A.rows());\n  xx.setZero();\n  Eigen::VectorXd xx2(A.rows());\n  xx2.setZero();\n\n\n  SOLVER_T solver;\n  ASSERT_TRUE(solver.init());\n    \n    Eigen::VectorXd bb(A.rows());\n    bb.setRandom();\n    \n  // virtual bool solve(const SparseBlockMatrix<MatrixType>& A, double* x, double* b) = 0;\n \tASSERT_TRUE( solver.solve(A,&xx[0],&bb[0]));\n \t// Solve dense\n \tEigen::VectorXd dx = Adense.selfadjointView<Eigen::Upper>().ldlt().solve(bb);\n\n \t//  always solve twice to make sure the value only copying is working for symbolic factorizations\n \trandomSparseBlockMatrix<SOLVER_T>(&A, Adense);\n \tASSERT_TRUE( solver.solve(A,&xx2[0],&bb[0]));\n\n \tEigen::VectorXd dx2 = Adense.selfadjointView<Eigen::Upper>().ldlt().solve(bb);\n\n \t// Solve dense\n\n\n \t// Make sure the solutions match.\n \tsm::eigen::assertNear(dx,xx,1e-10,SM_SOURCE_FILE_POS, \"A: dense solution, B: solution from \" + solver_name);\n \tsm::eigen::assertNear(dx2,xx2,1e-10,SM_SOURCE_FILE_POS, \"A: dense solution, B: solution from \" + solver_name);\n\n\n}\n\n// Check that the setup as a whole is correct\nTEST(g2oTestSuite, testCholmod)\n{\n\n//\n   testSolver< sparse_block_matrix::LinearSolverQr<Eigen::MatrixXd> >(\"sparseQR\");\n  \n  testSolver< sparse_block_matrix::LinearSolverCholmod<Eigen::MatrixXd> >(\"cholmod\");\n\n  testSolver< sparse_block_matrix::LinearSolverDense<Eigen::MatrixXd> >(\"dense\");\n\n\n}\n", "meta": {"hexsha": "b20dc327911ccbdd72ada5eb742c78022e7d1a08", "size": 3431, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "aslam_optimizer/sparse_block_matrix/test/solver_tests.cpp", "max_stars_repo_name": "PushyamiKaveti/kalibr", "max_stars_repo_head_hexsha": "d8bdfc59ee666ef854012becc93571f96fe5d80c", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": 2690.0, "max_stars_repo_stars_event_min_datetime": "2015-01-07T03:50:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T20:27:01.000Z", "max_issues_repo_path": "aslam_optimizer/sparse_block_matrix/test/solver_tests.cpp", "max_issues_repo_name": "PushyamiKaveti/kalibr", "max_issues_repo_head_hexsha": "d8bdfc59ee666ef854012becc93571f96fe5d80c", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": 481.0, "max_issues_repo_issues_event_min_datetime": "2015-01-27T10:21:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T14:02:41.000Z", "max_forks_repo_path": "aslam_optimizer/sparse_block_matrix/test/solver_tests.cpp", "max_forks_repo_name": "PushyamiKaveti/kalibr", "max_forks_repo_head_hexsha": "d8bdfc59ee666ef854012becc93571f96fe5d80c", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": 1091.0, "max_forks_repo_forks_event_min_datetime": "2015-01-26T21:21:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T01:55:33.000Z", "avg_line_length": 26.5968992248, "max_line_length": 132, "alphanum_fraction": 0.6572427864, "num_tokens": 1085, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081926, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.47282880778994496}}
{"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   testPose3.cpp\n * @brief  Unit tests for Pose3 class\n */\n\n#include <gtsam/geometry/Pose3.h>\n#include <gtsam/geometry/Pose2.h>\n#include <gtsam/base/testLie.h>\n#include <gtsam/base/lieProxies.h>\n\n#include <boost/assign/std/vector.hpp> // for operator +=\nusing namespace boost::assign;\n\n#include <CppUnitLite/TestHarness.h>\n#include <cmath>\n\nusing namespace std;\nusing namespace gtsam;\n\nGTSAM_CONCEPT_TESTABLE_INST(Pose3)\nGTSAM_CONCEPT_LIE_INST(Pose3)\n\nstatic const Point3 P(0.2,0.7,-2);\nstatic const Rot3 R = Rot3::Rodrigues(0.3,0,0);\nstatic const Point3 P2(3.5,-8.2,4.2);\nstatic const Pose3 T(R,P2);\nstatic const Pose3 T2(Rot3::Rodrigues(0.3,0.2,0.1),P2);\nstatic const Pose3 T3(Rot3::Rodrigues(-90, 0, 0), Point3(1, 2, 3));\nstatic const double tol=1e-5;\n\n/* ************************************************************************* */\nTEST( Pose3, equals)\n{\n  Pose3 pose2 = T3;\n  EXPECT(T3.equals(pose2));\n  Pose3 origin;\n  EXPECT(!T3.equals(origin));\n}\n\n/* ************************************************************************* */\nTEST( Pose3, constructors)\n{\n  Pose3 expected(Rot3::Rodrigues(0,0,3),Point3(1,2,0));\n  Pose2 pose2(1,2,3);\n  EXPECT(assert_equal(expected,Pose3(pose2)));\n}\n\n/* ************************************************************************* */\n#ifndef GTSAM_POSE3_EXPMAP\nTEST( Pose3, retract_first_order)\n{\n  Pose3 id;\n  Vector v = Z_6x1;\n  v(0) = 0.3;\n  EXPECT(assert_equal(Pose3(R, Point3(0,0,0)), id.retract(v),1e-2));\n  v(3)=0.2;v(4)=0.7;v(5)=-2;\n  EXPECT(assert_equal(Pose3(R, P),id.retract(v),1e-2));\n}\n#endif\n/* ************************************************************************* */\nTEST( Pose3, retract_expmap)\n{\n  Vector v = Z_6x1; v(0) = 0.3;\n  Pose3 pose = Pose3::Expmap(v);\n  EXPECT(assert_equal(Pose3(R, Point3(0,0,0)), pose, 1e-2));\n  EXPECT(assert_equal(v,Pose3::Logmap(pose),1e-2));\n}\n\n/* ************************************************************************* */\nTEST( Pose3, expmap_a_full)\n{\n  Pose3 id;\n  Vector v = Z_6x1;\n  v(0) = 0.3;\n  EXPECT(assert_equal(expmap_default<Pose3>(id, v), Pose3(R, Point3(0,0,0))));\n  v(3)=0.2;v(4)=0.394742;v(5)=-2.08998;\n  EXPECT(assert_equal(Pose3(R, P),expmap_default<Pose3>(id, v),1e-5));\n}\n\n/* ************************************************************************* */\nTEST( Pose3, expmap_a_full2)\n{\n  Pose3 id;\n  Vector v = Z_6x1;\n  v(0) = 0.3;\n  EXPECT(assert_equal(expmap_default<Pose3>(id, v), Pose3(R, Point3(0,0,0))));\n  v(3)=0.2;v(4)=0.394742;v(5)=-2.08998;\n  EXPECT(assert_equal(Pose3(R, P),expmap_default<Pose3>(id, v),1e-5));\n}\n\n/* ************************************************************************* */\nTEST(Pose3, expmap_b)\n{\n  Pose3 p1(Rot3(), Point3(100, 0, 0));\n  Pose3 p2 = p1.retract((Vector(6) << 0.0, 0.0, 0.1, 0.0, 0.0, 0.0).finished());\n  Pose3 expected(Rot3::Rodrigues(0.0, 0.0, 0.1), Point3(100.0, 0.0, 0.0));\n  EXPECT(assert_equal(expected, p2,1e-2));\n}\n\n/* ************************************************************************* */\n// test case for screw motion in the plane\nnamespace screwPose3 {\n  double a=0.3, c=cos(a), s=sin(a), w=0.3;\n  Vector xi = (Vector(6) << 0.0, 0.0, w, w, 0.0, 1.0).finished();\n  Rot3 expectedR(c, -s, 0, s, c, 0, 0, 0, 1);\n  Point3 expectedT(0.29552, 0.0446635, 1);\n  Pose3 expected(expectedR, expectedT);\n}\n\n/* ************************************************************************* */\n// Checks correct exponential map (Expmap) with brute force matrix exponential\nTEST(Pose3, expmap_c_full)\n{\n  EXPECT(assert_equal(screwPose3::expected, expm<Pose3>(screwPose3::xi),1e-6));\n  EXPECT(assert_equal(screwPose3::expected, Pose3::Expmap(screwPose3::xi),1e-6));\n}\n\n/* ************************************************************************* */\n// assert that T*exp(xi)*T^-1 is equal to exp(Ad_T(xi))\nTEST(Pose3, Adjoint_full)\n{\n  Pose3 expected = T * Pose3::Expmap(screwPose3::xi) * T.inverse();\n  Vector xiprime = T.Adjoint(screwPose3::xi);\n  EXPECT(assert_equal(expected, Pose3::Expmap(xiprime), 1e-6));\n\n  Pose3 expected2 = T2 * Pose3::Expmap(screwPose3::xi) * T2.inverse();\n  Vector xiprime2 = T2.Adjoint(screwPose3::xi);\n  EXPECT(assert_equal(expected2, Pose3::Expmap(xiprime2), 1e-6));\n\n  Pose3 expected3 = T3 * Pose3::Expmap(screwPose3::xi) * T3.inverse();\n  Vector xiprime3 = T3.Adjoint(screwPose3::xi);\n  EXPECT(assert_equal(expected3, Pose3::Expmap(xiprime3), 1e-6));\n}\n\n/* ************************************************************************* */\n// assert that T*wedge(xi)*T^-1 is equal to wedge(Ad_T(xi))\nTEST(Pose3, Adjoint_hat)\n{\n  auto hat = [](const Vector& xi) { return ::wedge<Pose3>(xi); };\n  Matrix4 expected = T.matrix() * hat(screwPose3::xi) * T.matrix().inverse();\n  Matrix4 xiprime = hat(T.Adjoint(screwPose3::xi));\n  EXPECT(assert_equal(expected, xiprime, 1e-6));\n\n  Matrix4 expected2 = T2.matrix() * hat(screwPose3::xi) * T2.matrix().inverse();\n  Matrix4 xiprime2 = hat(T2.Adjoint(screwPose3::xi));\n  EXPECT(assert_equal(expected2, xiprime2, 1e-6));\n\n  Matrix4 expected3 = T3.matrix() * hat(screwPose3::xi) * T3.matrix().inverse();\n  Matrix4 xiprime3 = hat(T3.Adjoint(screwPose3::xi));\n  EXPECT(assert_equal(expected3, xiprime3, 1e-6));\n}\n\n/* ************************************************************************* */\n/** Agrawal06iros version of exponential map */\nPose3 Agrawal06iros(const Vector& xi) {\n  Vector w = xi.head(3);\n  Vector v = xi.tail(3);\n  double t = w.norm();\n  if (t < 1e-5)\n    return Pose3(Rot3(), Point3(v));\n  else {\n    Matrix W = skewSymmetric(w/t);\n    Matrix A = I_3x3 + ((1 - cos(t)) / t) * W + ((t - sin(t)) / t) * (W * W);\n    return Pose3(Rot3::Expmap (w), Point3(A * v));\n  }\n}\n\n/* ************************************************************************* */\nTEST(Pose3, expmaps_galore_full)\n{\n  Vector xi; Pose3 actual;\n  xi = (Vector(6) << 0.1, 0.2, 0.3, 0.4, 0.5, 0.6).finished();\n  actual = Pose3::Expmap(xi);\n  EXPECT(assert_equal(expm<Pose3>(xi), actual,1e-6));\n  EXPECT(assert_equal(Agrawal06iros(xi), actual,1e-6));\n  EXPECT(assert_equal(xi, Pose3::Logmap(actual),1e-6));\n\n  xi = (Vector(6) << 0.1, -0.2, 0.3, -0.4, 0.5, -0.6).finished();\n  for (double theta=1.0;0.3*theta<=M_PI;theta*=2) {\n    Vector txi = xi*theta;\n    actual = Pose3::Expmap(txi);\n    EXPECT(assert_equal(expm<Pose3>(txi,30), actual,1e-6));\n    EXPECT(assert_equal(Agrawal06iros(txi), actual,1e-6));\n    Vector log = Pose3::Logmap(actual);\n    EXPECT(assert_equal(actual, Pose3::Expmap(log),1e-6));\n    EXPECT(assert_equal(txi,log,1e-6)); // not true once wraps\n  }\n\n  // Works with large v as well, but expm needs 10 iterations!\n  xi = (Vector(6) << 0.2, 0.3, -0.8, 100.0, 120.0, -60.0).finished();\n  actual = Pose3::Expmap(xi);\n  EXPECT(assert_equal(expm<Pose3>(xi,10), actual,1e-5));\n  EXPECT(assert_equal(Agrawal06iros(xi), actual,1e-9));\n  EXPECT(assert_equal(xi, Pose3::Logmap(actual),1e-9));\n}\n\n/* ************************************************************************* */\n// Check translation and its pushforward\nTEST(Pose3, translation) {\n  Matrix actualH;\n  EXPECT(assert_equal(Point3(3.5, -8.2, 4.2), T.translation(actualH), 1e-8));\n\n  Matrix numericalH = numericalDerivative11<Point3, Pose3>(\n      boost::bind(&Pose3::translation, _1, boost::none), T);\n  EXPECT(assert_equal(numericalH, actualH, 1e-6));\n}\n\n/* ************************************************************************* */\n// Check rotation and its pushforward\nTEST(Pose3, rotation) {\n  Matrix actualH;\n  EXPECT(assert_equal(R, T.rotation(actualH), 1e-8));\n\n  Matrix numericalH = numericalDerivative11<Rot3, Pose3>(\n      boost::bind(&Pose3::rotation, _1, boost::none), T);\n  EXPECT(assert_equal(numericalH, actualH, 1e-6));\n}\n\n/* ************************************************************************* */\nTEST(Pose3, Adjoint_compose_full)\n{\n  // To debug derivatives of compose, assert that\n  // T1*T2*exp(Adjoint(inv(T2),x) = T1*exp(x)*T2\n  const Pose3& T1 = T;\n  Vector x = (Vector(6) << 0.1, 0.1, 0.1, 0.4, 0.2, 0.8).finished();\n  Pose3 expected = T1 * Pose3::Expmap(x) * T2;\n  Vector y = T2.inverse().Adjoint(x);\n  Pose3 actual = T1 * T2 * Pose3::Expmap(y);\n  EXPECT(assert_equal(expected, actual, 1e-6));\n}\n\n/* ************************************************************************* */\n// Check compose and its pushforward\n// NOTE: testing::compose<Pose3>(t1,t2) = t1.compose(t2)  (see lieProxies.h)\nTEST( Pose3, compose )\n{\n  Matrix actual = (T2*T2).matrix();\n  Matrix expected = T2.matrix()*T2.matrix();\n  EXPECT(assert_equal(actual,expected,1e-8));\n\n  Matrix actualDcompose1, actualDcompose2;\n  T2.compose(T2, actualDcompose1, actualDcompose2);\n\n  Matrix numericalH1 = numericalDerivative21(testing::compose<Pose3>, T2, T2);\n  EXPECT(assert_equal(numericalH1,actualDcompose1,5e-3));\n  EXPECT(assert_equal(T2.inverse().AdjointMap(),actualDcompose1,5e-3));\n\n  Matrix numericalH2 = numericalDerivative22(testing::compose<Pose3>, T2, T2);\n  EXPECT(assert_equal(numericalH2,actualDcompose2,1e-4));\n}\n\n/* ************************************************************************* */\n// Check compose and its pushforward, another case\nTEST( Pose3, compose2 )\n{\n  const Pose3& T1 = T;\n  Matrix actual = (T1*T2).matrix();\n  Matrix expected = T1.matrix()*T2.matrix();\n  EXPECT(assert_equal(actual,expected,1e-8));\n\n  Matrix actualDcompose1, actualDcompose2;\n  T1.compose(T2, actualDcompose1, actualDcompose2);\n\n  Matrix numericalH1 = numericalDerivative21(testing::compose<Pose3>, T1, T2);\n  EXPECT(assert_equal(numericalH1,actualDcompose1,5e-3));\n  EXPECT(assert_equal(T2.inverse().AdjointMap(),actualDcompose1,5e-3));\n\n  Matrix numericalH2 = numericalDerivative22(testing::compose<Pose3>, T1, T2);\n  EXPECT(assert_equal(numericalH2,actualDcompose2,1e-5));\n}\n\n/* ************************************************************************* */\nTEST( Pose3, inverse)\n{\n  Matrix actualDinverse;\n  Matrix actual = T.inverse(actualDinverse).matrix();\n  Matrix expected = T.matrix().inverse();\n  EXPECT(assert_equal(actual,expected,1e-8));\n\n  Matrix numericalH = numericalDerivative11(testing::inverse<Pose3>, T);\n  EXPECT(assert_equal(numericalH,actualDinverse,5e-3));\n  EXPECT(assert_equal(-T.AdjointMap(),actualDinverse,5e-3));\n}\n\n/* ************************************************************************* */\nTEST( Pose3, inverseDerivatives2)\n{\n  Rot3 R = Rot3::Rodrigues(0.3,0.4,-0.5);\n  Point3 t(3.5,-8.2,4.2);\n  Pose3 T(R,t);\n\n  Matrix numericalH = numericalDerivative11(testing::inverse<Pose3>, T);\n  Matrix actualDinverse;\n  T.inverse(actualDinverse);\n  EXPECT(assert_equal(numericalH,actualDinverse,5e-3));\n  EXPECT(assert_equal(-T.AdjointMap(),actualDinverse,5e-3));\n}\n\n/* ************************************************************************* */\nTEST( Pose3, compose_inverse)\n{\n  Matrix actual = (T*T.inverse()).matrix();\n  Matrix expected = I_4x4;\n  EXPECT(assert_equal(actual,expected,1e-8));\n}\n\n/* ************************************************************************* */\nPoint3 transform_from_(const Pose3& pose, const Point3& point) { return pose.transform_from(point); }\nTEST( Pose3, Dtransform_from1_a)\n{\n  Matrix actualDtransform_from1;\n  T.transform_from(P, actualDtransform_from1, boost::none);\n  Matrix numerical = numericalDerivative21(transform_from_,T,P);\n  EXPECT(assert_equal(numerical,actualDtransform_from1,1e-8));\n}\n\nTEST( Pose3, Dtransform_from1_b)\n{\n  Pose3 origin;\n  Matrix actualDtransform_from1;\n  origin.transform_from(P, actualDtransform_from1, boost::none);\n  Matrix numerical = numericalDerivative21(transform_from_,origin,P);\n  EXPECT(assert_equal(numerical,actualDtransform_from1,1e-8));\n}\n\nTEST( Pose3, Dtransform_from1_c)\n{\n  Point3 origin(0,0,0);\n  Pose3 T0(R,origin);\n  Matrix actualDtransform_from1;\n  T0.transform_from(P, actualDtransform_from1, boost::none);\n  Matrix numerical = numericalDerivative21(transform_from_,T0,P);\n  EXPECT(assert_equal(numerical,actualDtransform_from1,1e-8));\n}\n\nTEST( Pose3, Dtransform_from1_d)\n{\n  Rot3 I;\n  Point3 t0(100,0,0);\n  Pose3 T0(I,t0);\n  Matrix actualDtransform_from1;\n  T0.transform_from(P, actualDtransform_from1, boost::none);\n  //print(computed, \"Dtransform_from1_d computed:\");\n  Matrix numerical = numericalDerivative21(transform_from_,T0,P);\n  //print(numerical, \"Dtransform_from1_d numerical:\");\n  EXPECT(assert_equal(numerical,actualDtransform_from1,1e-8));\n}\n\n/* ************************************************************************* */\nTEST( Pose3, Dtransform_from2)\n{\n  Matrix actualDtransform_from2;\n  T.transform_from(P, boost::none, actualDtransform_from2);\n  Matrix numerical = numericalDerivative22(transform_from_,T,P);\n  EXPECT(assert_equal(numerical,actualDtransform_from2,1e-8));\n}\n\n/* ************************************************************************* */\nPoint3 transform_to_(const Pose3& pose, const Point3& point) { return pose.transform_to(point); }\nTEST( Pose3, Dtransform_to1)\n{\n  Matrix computed;\n  T.transform_to(P, computed, boost::none);\n  Matrix numerical = numericalDerivative21(transform_to_,T,P);\n  EXPECT(assert_equal(numerical,computed,1e-8));\n}\n\n/* ************************************************************************* */\nTEST( Pose3, Dtransform_to2)\n{\n  Matrix computed;\n  T.transform_to(P, boost::none, computed);\n  Matrix numerical = numericalDerivative22(transform_to_,T,P);\n  EXPECT(assert_equal(numerical,computed,1e-8));\n}\n\n/* ************************************************************************* */\nTEST( Pose3, transform_to_with_derivatives)\n{\n  Matrix actH1, actH2;\n  T.transform_to(P,actH1,actH2);\n  Matrix expH1 = numericalDerivative21(transform_to_, T,P),\n       expH2 = numericalDerivative22(transform_to_, T,P);\n  EXPECT(assert_equal(expH1, actH1, 1e-8));\n  EXPECT(assert_equal(expH2, actH2, 1e-8));\n}\n\n/* ************************************************************************* */\nTEST( Pose3, transform_from_with_derivatives)\n{\n  Matrix actH1, actH2;\n  T.transform_from(P,actH1,actH2);\n  Matrix expH1 = numericalDerivative21(transform_from_, T,P),\n       expH2 = numericalDerivative22(transform_from_, T,P);\n  EXPECT(assert_equal(expH1, actH1, 1e-8));\n  EXPECT(assert_equal(expH2, actH2, 1e-8));\n}\n\n/* ************************************************************************* */\nTEST( Pose3, transform_to_translate)\n{\n    Point3 actual = Pose3(Rot3(), Point3(1, 2, 3)).transform_to(Point3(10.,20.,30.));\n    Point3 expected(9.,18.,27.);\n    EXPECT(assert_equal(expected, actual));\n}\n\n/* ************************************************************************* */\nTEST( Pose3, transform_to_rotate)\n{\n    Pose3 transform(Rot3::Rodrigues(0,0,-1.570796), Point3(0,0,0));\n    Point3 actual = transform.transform_to(Point3(2,1,10));\n    Point3 expected(-1,2,10);\n    EXPECT(assert_equal(expected, actual, 0.001));\n}\n\n/* ************************************************************************* */\nTEST( Pose3, transform_to)\n{\n    Pose3 transform(Rot3::Rodrigues(0,0,-1.570796), Point3(2,4, 0));\n    Point3 actual = transform.transform_to(Point3(3,2,10));\n    Point3 expected(2,1,10);\n    EXPECT(assert_equal(expected, actual, 0.001));\n}\n\nPose3 transform_pose_to_(const Pose3& pose, const Pose3& pose2) { return pose.transform_pose_to(pose2); }\n\n/* ************************************************************************* */\nTEST( Pose3, transform_pose_to)\n{\n  Pose3 origin = T.transform_pose_to(T);\n  EXPECT(assert_equal(Pose3{}, origin));\n}\n\n/* ************************************************************************* */\nTEST( Pose3, transform_pose_to_with_derivatives)\n{\n  Matrix actH1, actH2;\n  Pose3 res = T.transform_pose_to(T2,actH1,actH2);\n  EXPECT(assert_equal(res, T.inverse().compose(T2)));\n\n  Matrix expH1 = numericalDerivative21(transform_pose_to_, T, T2),\n       expH2 = numericalDerivative22(transform_pose_to_, T, T2);\n  EXPECT(assert_equal(expH1, actH1, 1e-8));\n  EXPECT(assert_equal(expH2, actH2, 1e-8));\n}\n\n/* ************************************************************************* */\nTEST( Pose3, transform_pose_to_with_derivatives2)\n{\n  Matrix actH1, actH2;\n  Pose3 res = T.transform_pose_to(T3,actH1,actH2);\n  EXPECT(assert_equal(res, T.inverse().compose(T3)));\n\n  Matrix expH1 = numericalDerivative21(transform_pose_to_, T, T3),\n       expH2 = numericalDerivative22(transform_pose_to_, T, T3);\n  EXPECT(assert_equal(expH1, actH1, 1e-8));\n  EXPECT(assert_equal(expH2, actH2, 1e-8));\n}\n\n/* ************************************************************************* */\nTEST( Pose3, transform_from)\n{\n    Point3 actual = T3.transform_from(Point3(0,0,0));\n    Point3 expected = Point3(1.,2.,3.);\n    EXPECT(assert_equal(expected, actual));\n}\n\n/* ************************************************************************* */\nTEST( Pose3, transform_roundtrip)\n{\n    Point3 actual = T3.transform_from(T3.transform_to(Point3(12., -0.11,7.0)));\n    Point3 expected(12., -0.11,7.0);\n    EXPECT(assert_equal(expected, actual));\n}\n\n/* ************************************************************************* */\nTEST( Pose3, transformPose_to_origin)\n{\n    // transform to origin\n    Pose3 actual = T3.transform_to(Pose3());\n    EXPECT(assert_equal(T3, actual, 1e-8));\n}\n\n/* ************************************************************************* */\nTEST( Pose3, transformPose_to_itself)\n{\n    // transform to itself\n    Pose3 actual = T3.transform_to(T3);\n    EXPECT(assert_equal(Pose3(), actual, 1e-8));\n}\n\n/* ************************************************************************* */\nTEST( Pose3, transformPose_to_translation)\n{\n    // transform translation only\n    Rot3 r = Rot3::Rodrigues(-1.570796,0,0);\n    Pose3 pose2(r, Point3(21.,32.,13.));\n    Pose3 actual = pose2.transform_to(Pose3(Rot3(), Point3(1,2,3)));\n    Pose3 expected(r, Point3(20.,30.,10.));\n    EXPECT(assert_equal(expected, actual, 1e-8));\n}\n\n/* ************************************************************************* */\nTEST( Pose3, transformPose_to_simple_rotate)\n{\n    // transform translation only\n    Rot3 r = Rot3::Rodrigues(0,0,-1.570796);\n    Pose3 pose2(r, Point3(21.,32.,13.));\n    Pose3 transform(r, Point3(1,2,3));\n    Pose3 actual = pose2.transform_to(transform);\n    Pose3 expected(Rot3(), Point3(-30.,20.,10.));\n    EXPECT(assert_equal(expected, actual, 0.001));\n}\n\n/* ************************************************************************* */\nTEST( Pose3, transformPose_to)\n{\n    // transform to\n    Rot3 r = Rot3::Rodrigues(0,0,-1.570796); //-90 degree yaw\n    Rot3 r2 = Rot3::Rodrigues(0,0,0.698131701); //40 degree yaw\n    Pose3 pose2(r2, Point3(21.,32.,13.));\n    Pose3 transform(r, Point3(1,2,3));\n    Pose3 actual = pose2.transform_to(transform);\n    Pose3 expected(Rot3::Rodrigues(0,0,2.26892803), Point3(-30.,20.,10.));\n    EXPECT(assert_equal(expected, actual, 0.001));\n}\n\n/* ************************************************************************* */\nTEST(Pose3, Retract_LocalCoordinates)\n{\n  Vector6 d;\n  d << 1,2,3,4,5,6; d/=10;\n  const Rot3 R = Rot3::Retract(d.head<3>());\n  Pose3 t = Pose3::Retract(d);\n  EXPECT(assert_equal(d, Pose3::LocalCoordinates(t)));\n}\n/* ************************************************************************* */\nTEST(Pose3, retract_localCoordinates)\n{\n  Vector6 d12;\n  d12 << 1,2,3,4,5,6; d12/=10;\n  Pose3 t1 = T, t2 = t1.retract(d12);\n  EXPECT(assert_equal(d12, t1.localCoordinates(t2)));\n}\n/* ************************************************************************* */\nTEST(Pose3, expmap_logmap)\n{\n  Vector d12 = Vector6::Constant(0.1);\n  Pose3 t1 = T, t2 = t1.expmap(d12);\n  EXPECT(assert_equal(d12, t1.logmap(t2)));\n}\n\n/* ************************************************************************* */\nTEST(Pose3, retract_localCoordinates2)\n{\n  Pose3 t1 = T;\n  Pose3 t2 = T3;\n  Pose3 origin;\n  Vector d12 = t1.localCoordinates(t2);\n  EXPECT(assert_equal(t2, t1.retract(d12)));\n  Vector d21 = t2.localCoordinates(t1);\n  EXPECT(assert_equal(t1, t2.retract(d21)));\n  // TODO(hayk): This currently fails!\n  // EXPECT(assert_equal(d12, -d21));\n}\n/* ************************************************************************* */\nTEST(Pose3, manifold_expmap)\n{\n  Pose3 t1 = T;\n  Pose3 t2 = T3;\n  Pose3 origin;\n  Vector d12 = t1.logmap(t2);\n  EXPECT(assert_equal(t2, t1.expmap(d12)));\n  Vector d21 = t2.logmap(t1);\n  EXPECT(assert_equal(t1, t2.expmap(d21)));\n\n  // Check that log(t1,t2)=-log(t2,t1)\n  EXPECT(assert_equal(d12,-d21));\n}\n\n/* ************************************************************************* */\nTEST(Pose3, subgroups)\n{\n  // Frank - Below only works for correct \"Agrawal06iros style expmap\n  // lines in canonical coordinates correspond to Abelian subgroups in SE(3)\n   Vector d = (Vector(6) << 0.1, 0.2, 0.3, 0.4, 0.5, 0.6).finished();\n  // exp(-d)=inverse(exp(d))\n   EXPECT(assert_equal(Pose3::Expmap(-d),Pose3::Expmap(d).inverse()));\n  // exp(5d)=exp(2*d+3*d)=exp(2*d)exp(3*d)=exp(3*d)exp(2*d)\n   Pose3 T2 = Pose3::Expmap(2*d);\n   Pose3 T3 = Pose3::Expmap(3*d);\n   Pose3 T5 = Pose3::Expmap(5*d);\n   EXPECT(assert_equal(T5,T2*T3));\n   EXPECT(assert_equal(T5,T3*T2));\n}\n\n/* ************************************************************************* */\nTEST( Pose3, between )\n{\n  Pose3 expected = T2.inverse() * T3;\n  Matrix actualDBetween1,actualDBetween2;\n  Pose3 actual = T2.between(T3, actualDBetween1,actualDBetween2);\n  EXPECT(assert_equal(expected,actual));\n\n  Matrix numericalH1 = numericalDerivative21(testing::between<Pose3> , T2, T3);\n  EXPECT(assert_equal(numericalH1,actualDBetween1,5e-3));\n\n  Matrix numericalH2 = numericalDerivative22(testing::between<Pose3> , T2, T3);\n  EXPECT(assert_equal(numericalH2,actualDBetween2,1e-5));\n}\n\n/* ************************************************************************* */\n// some shared test values - pulled from equivalent test in Pose2\nPoint3 l1(1, 0, 0), l2(1, 1, 0), l3(2, 2, 0), l4(1, 4,-4);\nPose3 x1, x2(Rot3::Ypr(0.0, 0.0, 0.0), l2), x3(Rot3::Ypr(M_PI/4.0, 0.0, 0.0), l2);\nPose3\n    xl1(Rot3::Ypr(0.0, 0.0, 0.0), Point3(1, 0, 0)),\n    xl2(Rot3::Ypr(0.0, 1.0, 0.0), Point3(1, 1, 0)),\n    xl3(Rot3::Ypr(1.0, 0.0, 0.0), Point3(2, 2, 0)),\n    xl4(Rot3::Ypr(0.0, 0.0, 1.0), Point3(1, 4,-4));\n\n/* ************************************************************************* */\ndouble range_proxy(const Pose3& pose, const Point3& point) {\n  return pose.range(point);\n}\nTEST( Pose3, range )\n{\n  Matrix expectedH1, actualH1, expectedH2, actualH2;\n\n  // establish range is indeed zero\n  EXPECT_DOUBLES_EQUAL(1,x1.range(l1),1e-9);\n\n  // establish range is indeed sqrt2\n  EXPECT_DOUBLES_EQUAL(sqrt(2.0),x1.range(l2),1e-9);\n\n  // Another pair\n  double actual23 = x2.range(l3, actualH1, actualH2);\n  EXPECT_DOUBLES_EQUAL(sqrt(2.0),actual23,1e-9);\n\n  // Check numerical derivatives\n  expectedH1 = numericalDerivative21(range_proxy, x2, l3);\n  expectedH2 = numericalDerivative22(range_proxy, x2, l3);\n  EXPECT(assert_equal(expectedH1,actualH1));\n  EXPECT(assert_equal(expectedH2,actualH2));\n\n  // Another test\n  double actual34 = x3.range(l4, actualH1, actualH2);\n  EXPECT_DOUBLES_EQUAL(5,actual34,1e-9);\n\n  // Check numerical derivatives\n  expectedH1 = numericalDerivative21(range_proxy, x3, l4);\n  expectedH2 = numericalDerivative22(range_proxy, x3, l4);\n  EXPECT(assert_equal(expectedH1,actualH1));\n  EXPECT(assert_equal(expectedH2,actualH2));\n}\n\n/* ************************************************************************* */\ndouble range_pose_proxy(const Pose3& pose, const Pose3& point) {\n  return pose.range(point);\n}\nTEST( Pose3, range_pose )\n{\n  Matrix expectedH1, actualH1, expectedH2, actualH2;\n\n  // establish range is indeed zero\n  EXPECT_DOUBLES_EQUAL(1,x1.range(xl1),1e-9);\n\n  // establish range is indeed sqrt2\n  EXPECT_DOUBLES_EQUAL(sqrt(2.0),x1.range(xl2),1e-9);\n\n  // Another pair\n  double actual23 = x2.range(xl3, actualH1, actualH2);\n  EXPECT_DOUBLES_EQUAL(sqrt(2.0),actual23,1e-9);\n\n  // Check numerical derivatives\n  expectedH1 = numericalDerivative21(range_pose_proxy, x2, xl3);\n  expectedH2 = numericalDerivative22(range_pose_proxy, x2, xl3);\n  EXPECT(assert_equal(expectedH1,actualH1));\n  EXPECT(assert_equal(expectedH2,actualH2));\n\n  // Another test\n  double actual34 = x3.range(xl4, actualH1, actualH2);\n  EXPECT_DOUBLES_EQUAL(5,actual34,1e-9);\n\n  // Check numerical derivatives\n  expectedH1 = numericalDerivative21(range_pose_proxy, x3, xl4);\n  expectedH2 = numericalDerivative22(range_pose_proxy, x3, xl4);\n  EXPECT(assert_equal(expectedH1,actualH1));\n  EXPECT(assert_equal(expectedH2,actualH2));\n}\n\n/* ************************************************************************* */\nUnit3 bearing_proxy(const Pose3& pose, const Point3& point) {\n  return pose.bearing(point);\n}\nTEST(Pose3, Bearing) {\n  Matrix expectedH1, actualH1, expectedH2, actualH2;\n  EXPECT(assert_equal(Unit3(1, 0, 0), x1.bearing(l1, actualH1, actualH2), 1e-9));\n\n  // Check numerical derivatives\n  expectedH1 = numericalDerivative21(bearing_proxy, x1, l1);\n  expectedH2 = numericalDerivative22(bearing_proxy, x1, l1);\n  EXPECT(assert_equal(expectedH1, actualH1));\n  EXPECT(assert_equal(expectedH2, actualH2));\n}\n\nTEST(Pose3, Bearing2) {\n  Matrix expectedH1, actualH1, expectedH2, actualH2;\n  EXPECT(assert_equal(Unit3(0,0.6,-0.8), x2.bearing(l4, actualH1, actualH2), 1e-9));\n\n  // Check numerical derivatives\n  expectedH1 = numericalDerivative21(bearing_proxy, x2, l4);\n  expectedH2 = numericalDerivative22(bearing_proxy, x2, l4);\n  EXPECT(assert_equal(expectedH1, actualH1));\n  EXPECT(assert_equal(expectedH2, actualH2));\n}\n\nTEST(Pose3, PoseToPoseBearing) {\n  Matrix expectedH1, actualH1, expectedH2, actualH2, H2block;\n  EXPECT(assert_equal(Unit3(0,1,0), xl1.bearing(xl2, actualH1, actualH2), 1e-9));\n\n  // Check numerical derivatives\n  expectedH1 = numericalDerivative21(bearing_proxy, xl1, l2);\n\n  // Since the second pose is treated as a point, the value calculated by\n  // numericalDerivative22 only depends on the position of the pose. Here, we\n  // calculate the Jacobian w.r.t. the second pose's position, and then augment\n  // that with zeroes in the block that is w.r.t. the second pose's\n  // orientation.\n  H2block = numericalDerivative22(bearing_proxy, xl1, l2);\n  expectedH2 = Matrix(2, 6);\n  expectedH2.setZero();\n  expectedH2.block<2, 3>(0, 3) = H2block;\n\n  EXPECT(assert_equal(expectedH1, actualH1));\n  EXPECT(assert_equal(expectedH2, actualH2));\n}\n\n/* ************************************************************************* */\nTEST( Pose3, unicycle )\n{\n  // velocity in X should be X in inertial frame, rather than global frame\n  Vector x_step = Vector::Unit(6,3)*1.0;\n  EXPECT(assert_equal(Pose3(Rot3::Ypr(0,0,0), l1), expmap_default<Pose3>(x1, x_step), tol));\n  EXPECT(assert_equal(Pose3(Rot3::Ypr(0,0,0), Point3(2,1,0)), expmap_default<Pose3>(x2, x_step), tol));\n  EXPECT(assert_equal(Pose3(Rot3::Ypr(M_PI/4.0,0,0), Point3(2,2,0)), expmap_default<Pose3>(x3, sqrt(2.0) * x_step), tol));\n}\n\n/* ************************************************************************* */\nTEST( Pose3, adjointMap) {\n  Matrix res = Pose3::adjointMap(screwPose3::xi);\n  Matrix wh = skewSymmetric(screwPose3::xi(0), screwPose3::xi(1), screwPose3::xi(2));\n  Matrix vh = skewSymmetric(screwPose3::xi(3), screwPose3::xi(4), screwPose3::xi(5));\n  Matrix6 expected;\n  expected << wh, Z_3x3, vh, wh;\n  EXPECT(assert_equal(expected,res,1e-5));\n}\n\n/* ************************************************************************* */\nTEST(Pose3, Align1) {\n  Pose3 expected(Rot3(), Point3(10,10,0));\n\n  vector<Point3Pair> correspondences;\n  Point3Pair ab1(make_pair(Point3(10,10,0), Point3(0,0,0)));\n  Point3Pair ab2(make_pair(Point3(30,20,0), Point3(20,10,0)));\n  Point3Pair ab3(make_pair(Point3(20,30,0), Point3(10,20,0)));\n  correspondences += ab1, ab2, ab3;\n\n  boost::optional<Pose3> actual = Pose3::Align(correspondences);\n  EXPECT(assert_equal(expected, *actual));\n}\n\n/* ************************************************************************* */\nTEST(Pose3, Align2) {\n  Point3 t(20,10,5);\n  Rot3 R = Rot3::RzRyRx(0.3, 0.2, 0.1);\n  Pose3 expected(R, t);\n\n  vector<Point3Pair> correspondences;\n  Point3 p1(0,0,1), p2(10,0,2), p3(20,-10,30);\n  Point3 q1 = expected.transform_from(p1),\n         q2 = expected.transform_from(p2),\n         q3 = expected.transform_from(p3);\n  Point3Pair ab1(make_pair(q1, p1));\n  Point3Pair ab2(make_pair(q2, p2));\n  Point3Pair ab3(make_pair(q3, p3));\n  correspondences += ab1, ab2, ab3;\n\n  boost::optional<Pose3> actual = Pose3::Align(correspondences);\n  EXPECT(assert_equal(expected, *actual, 1e-5));\n}\n\n/* ************************************************************************* */\nTEST( Pose3, ExpmapDerivative1) {\n  Matrix6 actualH;\n  Vector6 w; w << 0.1, 0.2, 0.3, 4.0, 5.0, 6.0;\n  Pose3::Expmap(w,actualH);\n  Matrix expectedH = numericalDerivative21<Pose3, Vector6,\n      OptionalJacobian<6, 6> >(&Pose3::Expmap, w, boost::none);\n  EXPECT(assert_equal(expectedH, actualH));\n}\n\n/* ************************************************************************* */\nTEST(Pose3, ExpmapDerivative2) {\n  // Iserles05an (Lie-group Methods) says:\n  // scalar is easy: d exp(a(t)) / dt = exp(a(t)) a'(t)\n  // matrix is hard: d exp(A(t)) / dt = exp(A(t)) dexp[-A(t)] A'(t)\n  // where A(t): T -> se(3) is a trajectory in the tangent space of SE(3)\n  // and dexp[A] is a linear map from 4*4 to 4*4 derivatives of se(3)\n  // Hence, the above matrix equation is typed: 4*4 = SE(3) * linear_map(4*4)\n\n  // In GTSAM, we don't work with the Lie-algebra elements A directly, but with 6-vectors.\n  // xi is easy: d Expmap(xi(t)) / dt = ExmapDerivative[xi(t)] * xi'(t)\n\n  // Let's verify the above formula.\n\n  auto xi = [](double t) {\n    Vector6 v;\n    v << 2 * t, sin(t), 4 * t * t, 2 * t, sin(t), 4 * t * t;\n    return v;\n  };\n  auto xi_dot = [](double t) {\n    Vector6 v;\n    v << 2, cos(t), 8 * t, 2, cos(t), 8 * t;\n    return v;\n  };\n\n  // We define a function T\n  auto T = [xi](double t) { return Pose3::Expmap(xi(t)); };\n\n  for (double t = -2.0; t < 2.0; t += 0.3) {\n    const Matrix expected = numericalDerivative11<Pose3, double>(T, t);\n    const Matrix actual = Pose3::ExpmapDerivative(xi(t)) * xi_dot(t);\n    CHECK(assert_equal(expected, actual, 1e-7));\n  }\n}\n\n/* ************************************************************************* */\nTEST( Pose3, LogmapDerivative) {\n  Matrix6 actualH;\n  Vector6 w; w << 0.1, 0.2, 0.3, 4.0, 5.0, 6.0;\n  Pose3 p = Pose3::Expmap(w);\n  EXPECT(assert_equal(w, Pose3::Logmap(p,actualH), 1e-5));\n  Matrix expectedH = numericalDerivative21<Vector6, Pose3,\n      OptionalJacobian<6, 6> >(&Pose3::Logmap, p, boost::none);\n  EXPECT(assert_equal(expectedH, actualH));\n}\n\n/* ************************************************************************* */\nVector6 testDerivAdjoint(const Vector6& xi, const Vector6& v) {\n  return Pose3::adjointMap(xi) * v;\n}\n\nTEST( Pose3, adjoint) {\n  Vector expected = testDerivAdjoint(screwPose3::xi, screwPose3::xi);\n\n  Matrix actualH;\n  Vector actual = Pose3::adjoint(screwPose3::xi, screwPose3::xi, actualH);\n\n  Matrix numericalH = numericalDerivative21<Vector6, Vector6, Vector6>(\n      testDerivAdjoint, screwPose3::xi, screwPose3::xi, 1e-5);\n\n  EXPECT(assert_equal(expected,actual,1e-5));\n  EXPECT(assert_equal(numericalH,actualH,1e-5));\n}\n\n/* ************************************************************************* */\nVector6 testDerivAdjointTranspose(const Vector6& xi, const Vector6& v) {\n  return Pose3::adjointMap(xi).transpose() * v;\n}\n\nTEST( Pose3, adjointTranspose) {\n  Vector xi = (Vector(6) << 0.01, 0.02, 0.03, 1.0, 2.0, 3.0).finished();\n  Vector v = (Vector(6) << 0.04, 0.05, 0.06, 4.0, 5.0, 6.0).finished();\n  Vector expected = testDerivAdjointTranspose(xi, v);\n\n  Matrix actualH;\n  Vector actual = Pose3::adjointTranspose(xi, v, actualH);\n\n  Matrix numericalH = numericalDerivative21<Vector6, Vector6, Vector6>(\n      testDerivAdjointTranspose, xi, v, 1e-5);\n\n  EXPECT(assert_equal(expected,actual,1e-15));\n  EXPECT(assert_equal(numericalH,actualH,1e-5));\n}\n\n/* ************************************************************************* */\nTEST( Pose3, stream)\n{\n  Pose3 T;\n  std::ostringstream os;\n  os << T;\n  EXPECT(os.str() == \"\\n|1, 0, 0|\\n|0, 1, 0|\\n|0, 0, 1|\\n\\n[0, 0, 0]';\\n\");\n}\n\n//******************************************************************************\nTEST(Pose3 , Invariants) {\n  Pose3 id;\n\n  EXPECT(check_group_invariants(id,id));\n  EXPECT(check_group_invariants(id,T3));\n  EXPECT(check_group_invariants(T2,id));\n  EXPECT(check_group_invariants(T2,T3));\n\n  EXPECT(check_manifold_invariants(id,id));\n  EXPECT(check_manifold_invariants(id,T3));\n  EXPECT(check_manifold_invariants(T2,id));\n  EXPECT(check_manifold_invariants(T2,T3));\n}\n\n//******************************************************************************\nTEST(Pose3 , LieGroupDerivatives) {\n  Pose3 id;\n\n  CHECK_LIE_GROUP_DERIVATIVES(id,id);\n  CHECK_LIE_GROUP_DERIVATIVES(id,T2);\n  CHECK_LIE_GROUP_DERIVATIVES(T2,id);\n  CHECK_LIE_GROUP_DERIVATIVES(T2,T3);\n}\n\n//******************************************************************************\nTEST(Pose3 , ChartDerivatives) {\n  Pose3 id;\n  if (ROT3_DEFAULT_COORDINATES_MODE == Rot3::EXPMAP) {\n    CHECK_CHART_DERIVATIVES(id,id);\n//    CHECK_CHART_DERIVATIVES(id,T2);\n//    CHECK_CHART_DERIVATIVES(T2,id);\n//    CHECK_CHART_DERIVATIVES(T2,T3);\n  }\n}\n\n/* ************************************************************************* */\nTEST(Pose3, interpolate) {\n  EXPECT(assert_equal(T2, interpolate(T2,T3, 0.0)));\n  EXPECT(assert_equal(T3, interpolate(T2,T3, 1.0)));\n}\n\n/* ************************************************************************* */\nTEST(Pose3, Create) {\n  Matrix63 actualH1, actualH2;\n  Pose3 actual = Pose3::Create(R, P2, actualH1, actualH2);\n  EXPECT(assert_equal(T, actual));\n  boost::function<Pose3(Rot3,Point3)> create = boost::bind(Pose3::Create,_1,_2,boost::none,boost::none);\n  EXPECT(assert_equal(numericalDerivative21<Pose3,Rot3,Point3>(create, R, P2), actualH1, 1e-9));\n  EXPECT(assert_equal(numericalDerivative22<Pose3,Rot3,Point3>(create, R, P2), actualH2, 1e-9));\n}\n\n/* ************************************************************************* */\nint main() {\n  TestResult tr;\n  return TestRegistry::runAllTests(tr);\n}\n/* ************************************************************************* */\n", "meta": {"hexsha": "d516ddc8b6f0034312781355617bf657f7fcdc4f", "size": 34400, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/geometry/tests/testPose3.cpp", "max_stars_repo_name": "karamach/gtsam", "max_stars_repo_head_hexsha": "35f9b710163a1d14d8dc4fcf50b8dce6e0bf7e5b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2019-12-11T18:33:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T04:52:45.000Z", "max_issues_repo_path": "gtsam/geometry/tests/testPose3.cpp", "max_issues_repo_name": "yfcube/gtsam", "max_issues_repo_head_hexsha": "5cbb9dfd6c5bc6a38edd230fd0b9d9c7e5006b0b", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/geometry/tests/testPose3.cpp", "max_forks_repo_name": "yfcube/gtsam", "max_forks_repo_head_hexsha": "5cbb9dfd6c5bc6a38edd230fd0b9d9c7e5006b0b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T16:24:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-24T11:10:49.000Z", "avg_line_length": 35.6476683938, "max_line_length": 122, "alphanum_fraction": 0.5836627907, "num_tokens": 10182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081926, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.47282880778994496}}
{"text": "// test_nc_beta.cpp\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//\n// This must appear *before* any #includes, and precludes pch usage:\n//\n#define BOOST_MATH_ASSERT_UNDEFINED_POLICY false\n\n#ifdef _MSC_VER\n#pragma warning (disable:4127 4512)\n#endif\n\n#if !defined(TEST_FLOAT) && !defined(TEST_DOUBLE) && !defined(TEST_LDOUBLE) && !defined(TEST_REAL_CONCEPT)\n#  define TEST_FLOAT\n#  define TEST_DOUBLE\n#  define TEST_LDOUBLE\n#  define TEST_REAL_CONCEPT\n#endif\n\n#include <boost/math/concepts/real_concept.hpp> // for real_concept\n#include <boost/math/distributions/non_central_beta.hpp> // for chi_squared_distribution\n#include <boost/math/distributions/poisson.hpp> // for poisson_distribution\n#define BOOST_TEST_MAIN\n#include <boost/test/unit_test.hpp> // for test_main\n#include <boost/test/results_collector.hpp>\n#include <boost/test/unit_test.hpp>\n#include <boost/test/tools/floating_point_comparison.hpp> // for BOOST_CHECK_CLOSE\n\n#include \"functor.hpp\"\n#include \"handle_test_result.hpp\"\n#include \"test_ncbeta_hooks.hpp\"\n#include \"table_type.hpp\"\n#include \"test_nc_beta.hpp\"\n\n#include <iostream>\nusing std::cout;\nusing std::endl;\n#include <limits>\nusing std::numeric_limits;\n\nvoid expected_results()\n{\n   //\n   // Define the max and mean errors expected for\n   // various compilers and platforms.\n   //\n   const char* largest_type;\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   if(boost::math::policies::digits<double, boost::math::policies::policy<> >() == boost::math::policies::digits<long double, boost::math::policies::policy<> >())\n   {\n      largest_type = \"(long\\\\s+)?double|real_concept\";\n   }\n   else\n   {\n      largest_type = \"long double|real_concept\";\n   }\n#else\n   largest_type = \"(long\\\\s+)?double|real_concept\";\n#endif\n\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   if(boost::math::tools::digits<long double>() == 64)\n   {\n      //\n      // Allow a small amount of error leakage from long double to double:\n      //\n      add_expected_result(\n         \"[^|]*\",                          // compiler\n         \"[^|]*\",                          // stdlib\n         \"[^|]*\",                          // platform\n         \"double\",                         // test type(s)\n         \"[^|]*large[^|]*\",                // test data group\n         \"[^|]*\", 5, 5);                   // test function\n   }\n\n   if(boost::math::tools::digits<long double>() == 64)\n   {\n      add_expected_result(\n         \"[^|]*\",                          // compiler\n         \"[^|]*\",                          // stdlib\n         \"[^|]*\",                          // platform\n         largest_type,                     // test type(s)\n         \"[^|]*medium[^|]*\",               // test data group\n         \"[^|]*\", 1200, 500);               // test function\n      add_expected_result(\n         \"[^|]*\",                          // compiler\n         \"[^|]*\",                          // stdlib\n         \"[^|]*\",                          // platform\n         largest_type,                     // test type(s)\n         \"[^|]*large[^|]*\",                // test data group\n         \"[^|]*\", 40000, 6000);            // test function\n   }\n#endif\n   //\n   // Catch all cases come last:\n   //\n   add_expected_result(\n      \"[^|]*\",                          // compiler\n      \"[^|]*\",                          // stdlib\n      \"[^|]*\",                          // platform\n      largest_type,                     // test type(s)\n      \"[^|]*medium[^|]*\",               // test data group\n      \"[^|]*\", 1500, 500);               // test function\n   add_expected_result(\n      \"[^|]*\",                          // compiler\n      \"[^|]*\",                          // stdlib\n      \"[^|]*\",                          // platform\n      \"real_concept\",                   // test type(s)\n      \"[^|]*large[^|]*\",                // test data group\n      \"[^|]*\", 30000, 4000);             // test function\n   add_expected_result(\n      \"[^|]*\",                          // compiler\n      \"[^|]*\",                          // stdlib\n      \"[^|]*\",                          // platform\n      largest_type,                     // test type(s)\n      \"[^|]*large[^|]*\",                // test data group\n      \"[^|]*\", 20000, 2000);             // test function\n   //\n   // Finish off by printing out the compiler/stdlib/platform names,\n   // we do this to make it easier to mark up expected error rates.\n   //\n   std::cout << \"Tests run with \" << BOOST_COMPILER << \", \" \n      << BOOST_STDLIB << \", \" << BOOST_PLATFORM << std::endl;\n}\n\ntemplate <class RealType>\nRealType naive_pdf(RealType a, RealType b, RealType lam, RealType x)\n{\n   using namespace boost::math;\n\n   RealType term = pdf(poisson_distribution<RealType>(lam/2), 0)\n      * ibeta_derivative(a, b, x);\n   RealType sum = term;\n\n   int i = 1;\n   while(term / sum > tools::epsilon<RealType>())\n   {\n      term = pdf(poisson_distribution<RealType>(lam/2), i)\n      * ibeta_derivative(a + i, b, x);\n      ++i;\n      sum += term;\n   }\n   return sum;\n}\n\ntemplate <class RealType>\nvoid test_spot(\n     RealType a,     // alpha\n     RealType b,     // beta\n     RealType ncp,   // non-centrality param\n     RealType cs,    // Chi Square statistic\n     RealType P,     // CDF\n     RealType Q,     // Complement of CDF\n     RealType D,     // PDF\n     RealType tol)   // Test tolerance\n{\n   boost::math::non_central_beta_distribution<RealType> dist(a, b, ncp);\n   BOOST_CHECK_CLOSE(\n      cdf(dist, cs), P, tol);\n   //\n   // Sanity checking using the naive PDF calculation above fails at\n   // float precision:\n   //\n   if(!boost::is_same<float, RealType>::value)\n   {\n      BOOST_CHECK_CLOSE(\n         pdf(dist, cs), naive_pdf(dist.alpha(), dist.beta(), ncp, cs), tol);\n   }\n   BOOST_CHECK_CLOSE(\n      pdf(dist, cs), D, tol);\n\n   if((P < 0.99) && (Q < 0.99))\n   {\n      //\n      // We can only check this if P is not too close to 1,\n      // so that we can guarantee Q is reasonably free of error:\n      //\n      BOOST_CHECK_CLOSE(\n         cdf(complement(dist, cs)), Q, tol);\n      BOOST_CHECK_CLOSE(\n            quantile(dist, P), cs, tol * 10);\n      BOOST_CHECK_CLOSE(\n            quantile(complement(dist, Q)), cs, tol * 10);\n   }\n}\n\ntemplate <class RealType> // Any floating-point type RealType.\nvoid test_spots(RealType)\n{\n   RealType tolerance = (std::max)(\n      boost::math::tools::epsilon<RealType>() * 100,\n      (RealType)1e-6) * 100;\n   RealType abs_tolerance = boost::math::tools::epsilon<RealType>() * 100;\n\n   cout << \"Tolerance = \" << tolerance << \"%.\" << endl;\n\n   //\n   // Spot tests use values computed by the R statistical\n   // package and the pbeta and dbeta functions:\n   //\n   test_spot(\n     RealType(2),                   // alpha\n     RealType(5),                   // beta\n     RealType(1),                   // non-centrality param\n     RealType(0.25),                // Chi Square statistic\n     RealType(0.3658349),           // CDF\n     RealType(1-0.3658349),         // Complement of CDF\n     RealType(2.184465),            // PDF\n     RealType(tolerance));\n   test_spot(\n     RealType(20),                  // alpha\n     RealType(15),                  // beta\n     RealType(35),                  // non-centrality param\n     RealType(0.75),                // Chi Square statistic\n     RealType(0.6994175),           // CDF\n     RealType(1-0.6994175),         // Complement of CDF\n     RealType(5.576146),            // PDF\n     RealType(tolerance));\n   test_spot(\n     RealType(100),                 // alpha\n     RealType(3),                   // beta\n     RealType(63),                  // non-centrality param\n     RealType(0.95),                // Chi Square statistic\n     RealType(0.03529306),          // CDF\n     RealType(1-0.03529306),        // Complement of CDF\n     RealType(3.637894),            // PDF\n     RealType(tolerance));\n   test_spot(\n     RealType(0.25),                // alpha\n     RealType(0.75),                // beta\n     RealType(150),                 // non-centrality param\n     RealType(0.975),               // Chi Square statistic\n     RealType(0.09752216),          // CDF\n     RealType(1-0.09752216),        // Complement of CDF\n     RealType(8.020935),            // PDF\n     RealType(tolerance));\n\n   BOOST_MATH_STD_USING\n   boost::math::non_central_beta_distribution<RealType> dist(100, 3, 63);\n   BOOST_CHECK_CLOSE(mean(dist), RealType(4.82280451915522329944315287538684030781836554279474240490936e13L) * exp(-RealType(31.5)) * 100 / 103, tolerance);\n   // Variance only guarantees small absolute error:\n   BOOST_CHECK_SMALL(variance(dist) \n      - static_cast<RealType>(RealType(4.85592267707818899235900237275021938334418424134218087127572e13L)\n      * exp(RealType(-31.5)) * 100 * 101 / (103 * 104) - \n      RealType(4.82280451915522329944315287538684030781836554279474240490936e13L) * RealType(4.82280451915522329944315287538684030781836554279474240490936e13L) \n      * exp(RealType(-63)) * 10000 / (103 * 103)), abs_tolerance);\n   BOOST_MATH_CHECK_THROW(skewness(dist), boost::math::evaluation_error);\n   BOOST_MATH_CHECK_THROW(kurtosis(dist), boost::math::evaluation_error);\n   BOOST_MATH_CHECK_THROW(kurtosis_excess(dist), boost::math::evaluation_error);\n} // template <class RealType>void test_spots(RealType)\n\n\nBOOST_AUTO_TEST_CASE( test_main )\n{\n   BOOST_MATH_CONTROL_FP;\n   // Basic sanity-check spot values.\n    expected_results();\n   // (Parameter value, arbitrarily zero, only communicates the floating point type).\n#ifdef TEST_FLOAT\n   test_spots(0.0F); // Test float.\n#endif\n#ifdef TEST_DOUBLE\n   test_spots(0.0); // Test double.\n#endif\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n#ifdef TEST_LDOUBLE\n   test_spots(0.0L); // Test long double.\n#endif\n#if !BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x582))\n#ifdef TEST_REAL_CONCEPT\n   test_spots(boost::math::concepts::real_concept(0.)); // Test real concept.\n#endif\n#endif\n#endif\n\n#ifdef TEST_FLOAT\n   test_accuracy(0.0F, \"float\"); // Test float.\n#endif\n#ifdef TEST_DOUBLE\n   test_accuracy(0.0, \"double\"); // Test double.\n#endif\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n#ifdef TEST_LDOUBLE\n   test_accuracy(0.0L, \"long double\"); // Test long double.\n#endif\n#if !BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x582))\n#ifdef TEST_REAL_CONCEPT\n   test_accuracy(boost::math::concepts::real_concept(0.), \"real_concept\"); // Test real concept.\n#endif\n#endif\n#endif\n   \n} // BOOST_AUTO_TEST_CASE( test_main )\n\n", "meta": {"hexsha": "81b80fa1f783bb0df3da7845984f6ae9227b4e4f", "size": 10575, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/math/test/test_nc_beta.cpp", "max_stars_repo_name": "uosorio/heroku_face", "max_stars_repo_head_hexsha": "7d6465e71dba17a15d8edaef520adb2fcd09d91e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-12T04:55:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T04:55:21.000Z", "max_issues_repo_path": "3rdparty/boost_1_73_0/libs/math/test/test_nc_beta.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-13T08:54:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-17T17:25:14.000Z", "max_forks_repo_path": "3rdparty/boost_1_73_0/libs/math/test/test_nc_beta.cpp", "max_forks_repo_name": "qingkouwei/mediaones", "max_forks_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2022-02-27T14:00:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T06:24:22.000Z", "avg_line_length": 35.1328903654, "max_line_length": 162, "alphanum_fraction": 0.5726713948, "num_tokens": 2770, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056167854461, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.47282880774265196}}
{"text": "// Copyright Louis Dionne 2013-2017\r\n// Distributed under the Boost Software License, Version 1.0.\r\n// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\r\n\r\n#include <boost/hana/assert.hpp>\r\n#include <boost/hana/equal.hpp>\r\n#include <boost/hana/ext/std/integral_constant.hpp>\r\n#include <boost/hana/integral_constant.hpp>\r\n#include <boost/hana/not_equal.hpp>\r\n\r\n#include <type_traits>\r\nnamespace hana = boost::hana;\r\n\r\n\r\nstatic_assert(hana::value(std::integral_constant<int, 3>{}) == 3, \"\");\r\nstatic_assert(std::integral_constant<int, 3>::value == 3, \"\");\r\n\r\nBOOST_HANA_CONSTANT_CHECK(hana::equal(std::integral_constant<int, 3>{}, hana::int_c<3>));\r\nBOOST_HANA_CONSTANT_CHECK(hana::equal(std::integral_constant<int, 3>{}, hana::long_c<3>));\r\nBOOST_HANA_CONSTANT_CHECK(hana::not_equal(std::integral_constant<int, 3>{}, hana::int_c<0>));\r\n\r\nint main() { }\r\n", "meta": {"hexsha": "8b38e787ee996bc6514f18059aba0cee8b2b2642", "size": 882, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/hana/example/ext/std/integral_constant.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": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/hana/example/ext/std/integral_constant.cpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-04T18:00:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-04T18:00:00.000Z", "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/hana/example/ext/std/integral_constant.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 38.347826087, "max_line_length": 94, "alphanum_fraction": 0.7244897959, "num_tokens": 237, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.689305616785446, "lm_q2_score": 0.6859494485880927, "lm_q1q2_score": 0.4728288077426518}}
{"text": "//yqq\n\n#include <iostream>\n#include <algorithm>\n#include <string>\n#include <boost/lockfree/spsc_queue.hpp>\n#include <boost/thread/thread.hpp>\n#include <boost/container/vector.hpp>\n#include <boost/thread/future.hpp>\n#include <boost/random.hpp>\n#include <boost/move/move.hpp>\n#include <boost/container/deque.hpp>\n// #include <boost/thread/a\n#include <boost/thread/mutex.hpp>\n\nusing namespace std;\n\n// void foo()\n// {\n//     for (int i = 0; i < 10; i++)\n//     {\n//         std::cout << \"sub thread\" << std::endl;\n//     }\n// }\n\n\nint main()\n{\n    using boost::thread;\n    using boost::container::vector;\n    // using boost::\n    // using boost::lockfree::queue ;\n    using boost::lockfree::spsc_queue;\n    // using boost::move;\n    // using boost::random;\n\n    spsc_queue<double> lockfreeQueue(100000000);\n    // boost::container::deque<double> lockfreeQueue;\n    const int cnProducer = 10, cnConsumer = 10;\n\n    boost::mutex  mtx;\n\n    vector<thread> vctProducer;\n    const double pi = 3.14159261314;\n\n    for (int i = 0; i < cnProducer; i++)\n    {\n        vctProducer.push_back( boost::move( thread([&pi, &lockfreeQueue, &mtx]() {\n            for (int i = 0; i < 10000000; i++)\n            {\n                // std::cout << \"sub thread\" << std::endl;\n                lockfreeQueue.push( pow(i, 3) * pi / 2  );\n\n                // boost::lock_guard<boost::mutex>  lock(mtx);\n                // lockfreeQueue.push_back( pow(i, 3) * pi / 2  );\n            }\n        })));\n    }\n\n    for(auto &thd : vctProducer)\n    {\n        thd.join();\n    }\n\n\n    return 0;\n}\n\n\n// g++ 7_5_boost_lockfree_queue.cpp -lpthread -lboost_thread", "meta": {"hexsha": "abc65f1e7d2b37f3709cfb5e14d331bcafed5135", "size": 1620, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "C++/moderncpp/7_5_boost_lockfree_queue.cpp", "max_stars_repo_name": "youngqqcn/QBlockChainNotes", "max_stars_repo_head_hexsha": "85122049024dc5555705bf016312491a51966621", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2018-11-01T03:36:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T08:20:30.000Z", "max_issues_repo_path": "C++/moderncpp/7_5_boost_lockfree_queue.cpp", "max_issues_repo_name": "songning4/QBlockChainNotes", "max_issues_repo_head_hexsha": "d65ede073f5a20f728f41cc6850409693820cdb1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 57.0, "max_issues_repo_issues_event_min_datetime": "2019-12-04T08:26:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-08T07:35:15.000Z", "max_forks_repo_path": "C++/moderncpp/7_5_boost_lockfree_queue.cpp", "max_forks_repo_name": "youngqqcn/QBlockChainNotes", "max_forks_repo_head_hexsha": "85122049024dc5555705bf016312491a51966621", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2019-01-04T08:41:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T03:51:36.000Z", "avg_line_length": 23.1428571429, "max_line_length": 82, "alphanum_fraction": 0.5765432099, "num_tokens": 451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081925, "lm_q2_score": 0.6893056040203135, "lm_q1q2_score": 0.472828803411827}}
{"text": "#ifndef PYBNESIAN_UTIL_VECH_OPS_HPP\n#define PYBNESIAN_UTIL_VECH_OPS_HPP\n\n#include <Eigen/Dense>\n\nusing Eigen::VectorXd, Eigen::MatrixXd;\n\nnamespace util {\n\nVectorXd vech(const MatrixXd& m);\nMatrixXd invvech(const VectorXd& m);\nMatrixXd invvech_triangular(const VectorXd& v);\n\n}  // namespace util\n\n#endif  // PYBNESIAN_VECH_OPS_HPP", "meta": {"hexsha": "81308f91f4c514c71bac170c20ea4f01e7bfe43a", "size": 331, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pybnesian/util/vech_ops.hpp", "max_stars_repo_name": "vishalbelsare/PyBNesian", "max_stars_repo_head_hexsha": "0190cd4cf6d133746741e2750004ccf0a9061fbd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2021-06-22T19:21:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T13:08:05.000Z", "max_issues_repo_path": "pybnesian/util/vech_ops.hpp", "max_issues_repo_name": "vishalbelsare/PyBNesian", "max_issues_repo_head_hexsha": "0190cd4cf6d133746741e2750004ccf0a9061fbd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pybnesian/util/vech_ops.hpp", "max_forks_repo_name": "vishalbelsare/PyBNesian", "max_forks_repo_head_hexsha": "0190cd4cf6d133746741e2750004ccf0a9061fbd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-08-20T13:44:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T02:57:02.000Z", "avg_line_length": 20.6875, "max_line_length": 47, "alphanum_fraction": 0.7915407855, "num_tokens": 91, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.685949442167993, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.47282880331724103}}
{"text": "/*\n@copyright Louis Dionne 2015\nDistributed under the Boost Software License, Version 1.0.\n(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n */\n\n#include <boost/hana/integral_constant.hpp>\n\n#include <boost/hana/assert.hpp>\n#include <boost/hana/core/datatype.hpp>\n#include <boost/hana/tuple.hpp>\n#include <boost/hana/type.hpp>\n\n#include <cstddef>\n#include <type_traits>\nusing namespace boost::hana;\n\n\nint main() {\n    //////////////////////////////////////////////////////////////////////////\n    // IntegralConstant's API (like std::integral_constant)\n    //////////////////////////////////////////////////////////////////////////\n    {\n        // operator()\n        static_assert(size_t<0>() == 0, \"\");\n        static_assert(size_t<1>() == 1, \"\");\n        static_assert(int_<-3>() == -3, \"\");\n\n        // decltype(operator())\n        BOOST_HANA_CONSTANT_CHECK(decltype_(size_t<0>()) == type<std::size_t>);\n        BOOST_HANA_CONSTANT_CHECK(decltype_(int_<-3>()) == type<int>);\n\n        // conversions\n        constexpr std::size_t a = size_t<0>, b = size_t<1>;\n        static_assert(a == 0 && b == 1, \"\");\n\n        constexpr int c = int_<0>, d = int_<-3>;\n        static_assert(c == 0 && d == -3, \"\");\n\n        // nested ::value\n        static_assert(decltype(int_<1>)::value == 1, \"\");\n\n        // nested ::type\n        static_assert(std::is_same<\n            decltype(int_<1>)::type,\n            std::remove_cv_t<decltype(int_<1>)>\n        >{}, \"\");\n\n        // nested ::value_type\n        static_assert(std::is_same<decltype(int_<1>)::value_type, int>{}, \"\");\n    }\n\n    //////////////////////////////////////////////////////////////////////////\n    // Make sure we can inherit _integral_constant and retain the same\n    // data type.\n    //////////////////////////////////////////////////////////////////////////\n    {\n        struct derived : _integral_constant<int, 10> { };\n        static_assert(std::is_same<datatype_t<derived>, IntegralConstant<int>>{}, \"\");\n    }\n\n    //////////////////////////////////////////////////////////////////////////\n    // Extensions to std::integral_constant\n    //////////////////////////////////////////////////////////////////////////\n    {\n        // times member function (the other ones are tested in the examples)\n        {\n            int counter = 0;\n            int_<3>.times([&] { ++counter; });\n            BOOST_HANA_RUNTIME_CHECK(counter == 3);\n        }\n\n        // Arithmetic operators\n        {\n            BOOST_HANA_CONSTANT_CHECK(+int_<1> == int_<1>);\n            BOOST_HANA_CONSTANT_CHECK(-int_<1> == int_<-1>);\n            BOOST_HANA_CONSTANT_CHECK(int_<1> + int_<2> == int_<3>);\n            BOOST_HANA_CONSTANT_CHECK(int_<1> - int_<2> == int_<-1>);\n            BOOST_HANA_CONSTANT_CHECK(int_<3> * int_<2> == int_<6>);\n            BOOST_HANA_CONSTANT_CHECK(int_<6> / int_<3> == int_<2>);\n            BOOST_HANA_CONSTANT_CHECK(int_<6> % int_<4> == int_<2>);\n            BOOST_HANA_CONSTANT_CHECK(~int_<6> == int_<~6>);\n            BOOST_HANA_CONSTANT_CHECK((int_<6> & int_<3>) == int_<6 & 3>);\n            BOOST_HANA_CONSTANT_CHECK((int_<4> | int_<2>) == int_<4 | 2>);\n            BOOST_HANA_CONSTANT_CHECK((int_<6> ^ int_<3>) == int_<6 ^ 3>);\n            BOOST_HANA_CONSTANT_CHECK((int_<6> << int_<3>) == int_<(6 << 3)>);\n            BOOST_HANA_CONSTANT_CHECK((int_<6> >> int_<3>) == int_<(6 >> 3)>);\n        }\n\n        // Comparison operators\n        {\n            BOOST_HANA_CONSTANT_CHECK(int_<0> == int_<0>);\n            BOOST_HANA_CONSTANT_CHECK(int_<1> != int_<0>);\n            BOOST_HANA_CONSTANT_CHECK(int_<0> < int_<1>);\n            BOOST_HANA_CONSTANT_CHECK(int_<0> <= int_<1>);\n            BOOST_HANA_CONSTANT_CHECK(int_<0> <= int_<0>);\n            BOOST_HANA_CONSTANT_CHECK(int_<1> > int_<0>);\n            BOOST_HANA_CONSTANT_CHECK(int_<1> >= int_<0>);\n            BOOST_HANA_CONSTANT_CHECK(int_<0> >= int_<0>);\n        }\n\n        // Logical operators\n        {\n            BOOST_HANA_CONSTANT_CHECK(int_<3> || int_<0>);\n            BOOST_HANA_CONSTANT_CHECK(int_<3> && int_<1>);\n            BOOST_HANA_CONSTANT_CHECK(!int_<0>);\n            BOOST_HANA_CONSTANT_CHECK(!!int_<3>);\n        }\n\n        // Creation with user-defined literals\n        {\n            using namespace boost::hana::literals;\n\n            BOOST_HANA_CONSTANT_CHECK(0_c == llong<0>);\n            BOOST_HANA_CONSTANT_CHECK(1_c == llong<1>);\n            BOOST_HANA_CONSTANT_CHECK(12_c == llong<12>);\n            BOOST_HANA_CONSTANT_CHECK(123_c == llong<123>);\n            BOOST_HANA_CONSTANT_CHECK(1234567_c == llong<1234567>);\n            BOOST_HANA_CONSTANT_CHECK(-34_c == llong<-34>);\n\n            BOOST_HANA_CONSTANT_CHECK(decltype_(-1234_c) == decltype_(llong<-1234>));\n            BOOST_HANA_CONSTANT_CHECK(-12_c < 0_c);\n        }\n    }\n}\n", "meta": {"hexsha": "fb8c47b7a29153ba2b14cfe8c0b2d35f483aacec", "size": 4818, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/integral_constant/api.cpp", "max_stars_repo_name": "josephwinston/hana", "max_stars_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/integral_constant/api.cpp", "max_issues_repo_name": "josephwinston/hana", "max_issues_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/integral_constant/api.cpp", "max_forks_repo_name": "josephwinston/hana", "max_forks_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.2380952381, "max_line_length": 86, "alphanum_fraction": 0.5197177252, "num_tokens": 1140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737473266735, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.47277923398405547}}
{"text": "// g++ -O3 -DNDEBUG -I.. -L /usr/lib64/atlas/ benchBlasGemm.cpp -o benchBlasGemm -lrt -lcblas\n// possible options:\n//    -DEIGEN_DONT_VECTORIZE\n//    -msse2\n\n// #define EIGEN_DEFAULT_TO_ROW_MAJOR\n#define _FLOAT\n\n#include <iostream>\n\n#include <Eigen/Core>\n#include \"BenchTimer.h\"\n\n// include the BLAS headers\nextern \"C\" {\n#include <cblas.h>\n}\n#include <string>\n\n#ifdef _FLOAT\ntypedef float Scalar;\n#define CBLAS_GEMM cblas_sgemm\n#else\ntypedef double Scalar;\n#define CBLAS_GEMM cblas_dgemm\n#endif\n\n\ntypedef Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic> MyMatrix;\nvoid bench_eigengemm(MyMatrix& mc, const MyMatrix& ma, const MyMatrix& mb, int nbloops);\nvoid check_product(int M, int N, int K);\nvoid check_product(void);\n\nint main(int argc, char *argv[])\n{\n  // disable SSE exceptions\n  #ifdef __GNUC__\n  {\n    int aux;\n    asm(\n    \"stmxcsr   %[aux]           \\n\\t\"\n    \"orl       $32832, %[aux]   \\n\\t\"\n    \"ldmxcsr   %[aux]           \\n\\t\"\n    : : [aux] \"m\" (aux));\n  }\n  #endif\n\n  int nbtries=1, nbloops=1, M, N, K;\n\n  if (argc==2)\n  {\n    if (std::string(argv[1])==\"check\")\n      check_product();\n    else\n      M = N = K = atoi(argv[1]);\n  }\n  else if ((argc==3) && (std::string(argv[1])==\"auto\"))\n  {\n    M = N = K = atoi(argv[2]);\n    nbloops = 1000000000/(M*M*M);\n    if (nbloops<1)\n      nbloops = 1;\n    nbtries = 6;\n  }\n  else if (argc==4)\n  {\n    M = N = K = atoi(argv[1]);\n    nbloops = atoi(argv[2]);\n    nbtries = atoi(argv[3]);\n  }\n  else if (argc==6)\n  {\n    M = atoi(argv[1]);\n    N = atoi(argv[2]);\n    K = atoi(argv[3]);\n    nbloops = atoi(argv[4]);\n    nbtries = atoi(argv[5]);\n  }\n  else\n  {\n    std::cout << \"Usage: \" << argv[0] << \" size  \\n\";\n    std::cout << \"Usage: \" << argv[0] << \" auto size\\n\";\n    std::cout << \"Usage: \" << argv[0] << \" size nbloops nbtries\\n\";\n    std::cout << \"Usage: \" << argv[0] << \" M N K nbloops nbtries\\n\";\n    std::cout << \"Usage: \" << argv[0] << \" check\\n\";\n    std::cout << \"Options:\\n\";\n    std::cout << \"    size       unique size of the 2 matrices (integer)\\n\";\n    std::cout << \"    auto       automatically set the number of repetitions and tries\\n\";\n    std::cout << \"    nbloops    number of times the GEMM routines is executed\\n\";\n    std::cout << \"    nbtries    number of times the loop is benched (return the best try)\\n\";\n    std::cout << \"    M N K      sizes of the matrices: MxN  =  MxK * KxN (integers)\\n\";\n    std::cout << \"    check      check eigen product using cblas as a reference\\n\";\n    exit(1);\n  }\n\n  double nbmad = double(M) * double(N) * double(K) * double(nbloops);\n\n  if (!(std::string(argv[1])==\"auto\"))\n    std::cout << M << \" x \" << N << \" x \" << K << \"\\n\";\n\n  Scalar alpha, beta;\n  MyMatrix ma(M,K), mb(K,N), mc(M,N);\n  ma = MyMatrix::Random(M,K);\n  mb = MyMatrix::Random(K,N);\n  mc = MyMatrix::Random(M,N);\n\n  Eigen::BenchTimer timer;\n\n  // we simply compute c += a*b, so:\n  alpha = 1;\n  beta = 1;\n\n  // bench cblas\n  // ROWS_A, COLS_B, COLS_A, 1.0,  A, COLS_A, B, COLS_B, 0.0, C, COLS_B);\n  if (!(std::string(argv[1])==\"auto\"))\n  {\n    timer.reset();\n    for (uint k=0 ; k<nbtries ; ++k)\n    {\n        timer.start();\n        for (uint j=0 ; j<nbloops ; ++j)\n              #ifdef EIGEN_DEFAULT_TO_ROW_MAJOR\n              CBLAS_GEMM(CblasRowMajor, CblasNoTrans, CblasNoTrans, M, N, K, alpha, ma.data(), K, mb.data(), N, beta, mc.data(), N);\n              #else\n              CBLAS_GEMM(CblasColMajor, CblasNoTrans, CblasNoTrans, M, N, K, alpha, ma.data(), M, mb.data(), K, beta, mc.data(), M);\n              #endif\n        timer.stop();\n    }\n    if (!(std::string(argv[1])==\"auto\"))\n      std::cout << \"cblas: \" << timer.value() << \" (\" << 1e-3*floor(1e-6*nbmad/timer.value()) << \" GFlops/s)\\n\";\n    else\n        std::cout << M << \" : \" << timer.value() << \" ; \" << 1e-3*floor(1e-6*nbmad/timer.value()) << \"\\n\";\n  }\n\n  // clear\n  ma = MyMatrix::Random(M,K);\n  mb = MyMatrix::Random(K,N);\n  mc = MyMatrix::Random(M,N);\n\n  // eigen\n//   if (!(std::string(argv[1])==\"auto\"))\n  {\n      timer.reset();\n      for (uint k=0 ; k<nbtries ; ++k)\n      {\n          timer.start();\n          bench_eigengemm(mc, ma, mb, nbloops);\n          timer.stop();\n      }\n      if (!(std::string(argv[1])==\"auto\"))\n        std::cout << \"eigen : \" << timer.value() << \" (\" << 1e-3*floor(1e-6*nbmad/timer.value()) << \" GFlops/s)\\n\";\n      else\n        std::cout << M << \" : \" << timer.value() << \" ; \" << 1e-3*floor(1e-6*nbmad/timer.value()) << \"\\n\";\n  }\n\n  std::cout << \"l1: \" << Eigen::l1CacheSize() << std::endl;\n  std::cout << \"l2: \" << Eigen::l2CacheSize() << std::endl;\n\n\n  return 0;\n}\n\nusing namespace Eigen;\n\nvoid bench_eigengemm(MyMatrix& mc, const MyMatrix& ma, const MyMatrix& mb, int nbloops)\n{\n  for (uint j=0 ; j<nbloops ; ++j)\n      mc.noalias() += ma * mb;\n}\n\n#define MYVERIFY(A,M) if (!(A)) { \\\n    std::cout << \"FAIL: \" << M << \"\\n\"; \\\n  }\nvoid check_product(int M, int N, int K)\n{\n  MyMatrix ma(M,K), mb(K,N), mc(M,N), maT(K,M), mbT(N,K), meigen(M,N), mref(M,N);\n  ma = MyMatrix::Random(M,K);\n  mb = MyMatrix::Random(K,N);\n  maT = ma.transpose();\n  mbT = mb.transpose();\n  mc = MyMatrix::Random(M,N);\n\n  MyMatrix::Scalar eps = 1e-4;\n\n  meigen = mref = mc;\n  CBLAS_GEMM(CblasColMajor, CblasNoTrans, CblasNoTrans, M, N, K, 1, ma.data(), M, mb.data(), K, 1, mref.data(), M);\n  meigen += ma * mb;\n  MYVERIFY(meigen.isApprox(mref, eps),\". * .\");\n\n  meigen = mref = mc;\n  CBLAS_GEMM(CblasColMajor, CblasTrans, CblasNoTrans, M, N, K, 1, maT.data(), K, mb.data(), K, 1, mref.data(), M);\n  meigen += maT.transpose() * mb;\n  MYVERIFY(meigen.isApprox(mref, eps),\"T * .\");\n\n  meigen = mref = mc;\n  CBLAS_GEMM(CblasColMajor, CblasTrans, CblasTrans, M, N, K, 1, maT.data(), K, mbT.data(), N, 1, mref.data(), M);\n  meigen += (maT.transpose()) * (mbT.transpose());\n  MYVERIFY(meigen.isApprox(mref, eps),\"T * T\");\n\n  meigen = mref = mc;\n  CBLAS_GEMM(CblasColMajor, CblasNoTrans, CblasTrans, M, N, K, 1, ma.data(), M, mbT.data(), N, 1, mref.data(), M);\n  meigen += ma * mbT.transpose();\n  MYVERIFY(meigen.isApprox(mref, eps),\". * T\");\n}\n\nvoid check_product(void)\n{\n  int M, N, K;\n  for (uint i=0; i<1000; ++i)\n  {\n    M = internal::random<int>(1,64);\n    N = internal::random<int>(1,768);\n    K = internal::random<int>(1,768);\n    M = (0 + M) * 1;\n    std::cout << M << \" x \" << N << \" x \" << K << \"\\n\";\n    check_product(M, N, K);\n  }\n}\n", "meta": {"hexsha": "e91d0ae6eec9077a7db892234e7e7ef23a24ea40", "size": 6310, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "simulator/external/habitat-sim-geodesic/habitat_sim_geodesic/csrc/eigen/bench/benchBlasGemm.cpp", "max_stars_repo_name": "eundersander/bps-nav", "max_stars_repo_head_hexsha": "a33bac7d10dc077baa596a76790b4fc829d332f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2021-03-15T01:49:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-11T23:17:14.000Z", "max_issues_repo_path": "simulator/external/habitat-sim-geodesic/habitat_sim_geodesic/csrc/eigen/bench/benchBlasGemm.cpp", "max_issues_repo_name": "eundersander/bps-nav", "max_issues_repo_head_hexsha": "a33bac7d10dc077baa596a76790b4fc829d332f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-06-27T21:41:25.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-18T21:46:40.000Z", "max_forks_repo_path": "simulator/external/habitat-sim-geodesic/habitat_sim_geodesic/csrc/eigen/bench/benchBlasGemm.cpp", "max_forks_repo_name": "eundersander/bps-nav", "max_forks_repo_head_hexsha": "a33bac7d10dc077baa596a76790b4fc829d332f7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2021-03-27T17:17:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-19T12:00:06.000Z", "avg_line_length": 28.8127853881, "max_line_length": 132, "alphanum_fraction": 0.5497622821, "num_tokens": 2196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737214979745, "lm_q2_score": 0.6926419894793248, "lm_q1q2_score": 0.4727792204246636}}
{"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_POLYNOMIALS_FUNCTIONS_SIMD_COMMON_PLEVL_HPP_INCLUDED\n#define NT2_POLYNOMIALS_FUNCTIONS_SIMD_COMMON_PLEVL_HPP_INCLUDED\n\n#include <nt2/polynomials/functions/plevl.hpp>\n#include <nt2/include/functions/simd/fma.hpp>\n#include <nt2/include/functions/simd/tofloat.hpp>\n#include <nt2/include/functions/simd/splat.hpp>\n#include <nt2/include/functions/simd/plus.hpp>\n#include <boost/fusion/adapted/array.hpp>\n#include <nt2/sdk/meta/as_floating.hpp>\n\n/////////////////////////////////////////////////////////////////////////////\n// Implementation when type A0 is arithmetic_\n/////////////////////////////////////////////////////////////////////////////\nnamespace nt2 { namespace ext\n{\n  NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::plevl_, tag::cpu_\n                            , (A0)(A1)(X)\n                            , ((simd_<arithmetic_<A0>,X>))(fusion_sequence_<A1>)\n                            )\n  {\n\n    typedef typename meta::as_floating<A0>::type result_type;\n\n    NT2_FUNCTOR_CALL(2)\n    {\n      return plevl(tofloat(a0), a1);\n    }\n  };\n} }\n\n\n/////////////////////////////////////////////////////////////////////////////\n// Implementation when type A0 is floating_\n/////////////////////////////////////////////////////////////////////////////\nnamespace nt2 { namespace ext\n{\n  NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::plevl_, tag::cpu_\n                            , (A0)(A1)(X)\n                            , ((simd_<floating_<A0>,X>))(fusion_sequence_<A1>)\n                            )\n  {\n\n    typedef A0 result_type;\n\n    NT2_FUNCTOR_CALL(2)\n    {\n      typename A1::const_iterator p = a1.begin();\n      A0 ans = a0+nt2::splat<A0>(*p++);\n      do\n      ans = fma(ans, a0, nt2::splat<A0>(*p));\n      while( ++p !=  a1.end());\n      return ans;\n    }\n  };\n} }\n\n\n#endif\n", "meta": {"hexsha": "81f2c2ac552ec5ab3c7ca1e8c54409b88a101743", "size": 2277, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/polynomials/include/nt2/polynomials/functions/simd/common/plevl.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/polynomials/include/nt2/polynomials/functions/simd/common/plevl.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/polynomials/include/nt2/polynomials/functions/simd/common/plevl.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": 33.4852941176, "max_line_length": 80, "alphanum_fraction": 0.4822134387, "num_tokens": 504, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419704455588, "lm_q2_score": 0.6825737214979745, "lm_q1q2_score": 0.47277920743271507}}
{"text": "/* Author: Wolfgang Bangerth, University of Heidelberg, 1999 */\n\n/*    $Id: step-2.cc 27657 2012-11-21 13:19:08Z bangerth $       */\n/*                                                                */\n/*    Copyright (C) 1999-2003, 2006, 2008-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// The first few includes are just like in the previous program, so do not\n// require additional comments:\n#include <deal.II/grid/tria.h>\n#include <deal.II/grid/tria_accessor.h>\n#include <deal.II/grid/tria_iterator.h>\n#include <deal.II/grid/grid_generator.h>\n#include <deal.II/grid/tria_boundary_lib.h>\n\n// However, the next file is new. We need this include file for the\n// association of degrees of freedom (\"DoF\"s) to vertices, lines, and cells:\n#include <deal.II/dofs/dof_handler.h>\n\n// The following include contains the description of the bilinear finite\n// element, including the facts that it has one degree of freedom on each\n// vertex of the triangulation, but none on faces and none in the interior of\n// the cells.\n//\n// (In fact, the file contains the description of Lagrange elements in\n// general, i.e. also the quadratic, cubic, etc versions, and not only for 2d\n// but also 1d and 3d.)\n#include <deal.II/fe/fe_q.h>\n// In the following file, several tools for manipulating degrees of freedom\n// can be found:\n#include <deal.II/dofs/dof_tools.h>\n// We will use a sparse matrix to visualize the pattern of nonzero entries\n// resulting from the distribution of degrees of freedom on the grid. That\n// class can be found here:\n#include <deal.II/lac/sparse_matrix.h>\n// We will also need to use an intermediate sparsity patter structure, which\n// is found in this file:\n#include <deal.II/lac/compressed_sparsity_pattern.h>\n\n// We will want to use a special algorithm to renumber degrees of freedom. It\n// is declared here:\n#include <deal.II/dofs/dof_renumbering.h>\n\n// And this is again needed for C++ output:\n#include <fstream>\n\n// Finally, as in step-1, we import the deal.II namespace into the global\n// scope:\nusing namespace dealii;\n\n// @sect3{Mesh generation}\n\n// This is the function that produced the circular grid in the previous step-1\n// example program. The sole difference is that it returns the grid it\n// produces via its argument.\n//\n// The details of what the function does are explained in step-1. The only\n// thing we would like to comment on is this:\n//\n// Since we want to export the triangulation through this function's\n// parameter, we need to make sure that the boundary object lives at least as\n// long as the triangulation does. However, in step-1, the boundary object is\n// a local variable, and it would be deleted at the end of the function, which\n// is too early. We avoid the problem by declaring it 'static' which makes\n// sure that the object is initialized the first time control the program\n// passes this point, but at the same time assures that it lives until the end\n// of the program.\nvoid make_grid (Triangulation<2> &triangulation)\n{\n  const Point<2> center (1,0);\n  const double inner_radius = 0.5,\n               outer_radius = 1.0;\n  GridGenerator::hyper_shell (triangulation,\n                              center, inner_radius, outer_radius,\n                              10);\n\n  static const HyperShellBoundary<2> boundary_description(center);\n  triangulation.set_boundary (0, boundary_description);\n\n  for (unsigned int step=0; step<5; ++step)\n    {\n      Triangulation<2>::active_cell_iterator\n      cell = triangulation.begin_active(),\n      endc = triangulation.end();\n\n      for (; cell!=endc; ++cell)\n        for (unsigned int v=0;\n             v < GeometryInfo<2>::vertices_per_cell;\n             ++v)\n          {\n            const double distance_from_center\n              = center.distance (cell->vertex(v));\n\n            if (std::fabs(distance_from_center - inner_radius) < 1e-10)\n              {\n                cell->set_refine_flag ();\n                break;\n              }\n          }\n\n      triangulation.execute_coarsening_and_refinement ();\n    }\n}\n\n// @sect3{Creation of a DoFHandler}\n\n// Up to now, we only have a grid, i.e. some geometrical (the position of the\n// vertices) and some topological information (how vertices are connected to\n// lines, and lines to cells, as well as which cells neighbor which other\n// cells). To use numerical algorithms, one needs some logic information in\n// addition to that: we would like to associate degree of freedom numbers to\n// each vertex (or line, or cell, in case we were using higher order elements)\n// to later generate matrices and vectors which describe a finite element\n// field on the triangulation.\n//\n// This function shows how to do this. The object to consider is the\n// <code>DoFHandler</code> class template.  Before we do so, however, we first\n// need something that describes how many degrees of freedom are to be\n// associated to each of these objects. Since this is one aspect of the\n// definition of a finite element space, the finite element base class stores\n// this information. In the present context, we therefore create an object of\n// the derived class <code>FE_Q</code> that describes Lagrange elements. Its\n// constructor takes one argument that states the polynomial degree of the\n// element, which here is one (indicating a bi-linear element); this then\n// corresponds to one degree of freedom for each vertex, while there are none\n// on lines and inside the quadrilateral. A value of, say, three given to the\n// constructor would instead give us a bi-cubic element with one degree of\n// freedom per vertex, two per line, and four inside the cell. In general,\n// <code>FE_Q</code> denotes the family of continuous elements with complete\n// polynomials (i.e. tensor-product polynomials) up to the specified order.\n//\n// We first need to create an object of this class and then pass it on to the\n// <code>DoFHandler</code> object to allocate storage for the degrees of\n// freedom (in deal.II lingo: we <code>distribute degrees of\n// freedom</code>). Note that the DoFHandler object will store a reference to\n// this finite element object, so we have to make sure its lifetime is at\n// least as long as that of the <code>DoFHandler</code>; one way to make sure\n// this is so is to make it static as well, in order to prevent its preemptive\n// destruction. (However, the library would warn us if we forgot about this\n// and abort the program if that occured. You can check this, if you want, by\n// removing the 'static' declaration.)\nvoid distribute_dofs (DoFHandler<2> &dof_handler)\n{\n  // As described above, let us first create a finite element object, and then\n  // use it to allocate degrees of freedom on the triangulation with which the\n  // dof_handler object is associated:\n  static const FE_Q<2> finite_element(1);\n  dof_handler.distribute_dofs (finite_element);\n\n  // Now that we have associated a degree of freedom with a global number to\n  // each vertex, we wonder how to visualize this?  There is no simple way to\n  // directly visualize the DoF number associated with each vertex. However,\n  // such information would hardly ever be truly important, since the\n  // numbering itself is more or less arbitrary. There are more important\n  // factors, of which we will demonstrate one in the following.\n  //\n  // Associated with each vertex of the triangulation is a shape\n  // function. Assume we want to solve something like Laplace's equation, then\n  // the different matrix entries will be the integrals over the gradient of\n  // each pair of such shape functions. Obviously, since the shape functions\n  // are nonzero only on the cells adjacent to the vertex they are associated\n  // with, matrix entries will be nonzero only if the supports of the shape\n  // functions associated to that column and row %numbers intersect. This is\n  // only the case for adjacent shape functions, and therefore only for\n  // adjacent vertices. Now, since the vertices are numbered more or less\n  // randomly by the above function (DoFHandler::distribute_dofs), the pattern\n  // of nonzero entries in the matrix will be somewhat ragged, and we will\n  // take a look at it now.\n  //\n  // First we have to create a structure which we use to store the places of\n  // nonzero elements. This can then later be used by one or more sparse\n  // matrix objects that store the values of the entries in the locations\n  // stored by this sparsity pattern. The class that stores the locations is\n  // the SparsityPattern class. As it turns out, however, this class has some\n  // drawbacks when we try to fill it right away: its data structures are set\n  // up in such a way that we need to have an estimate for the maximal number\n  // of entries we may wish to have in each row. In two space dimensions,\n  // reasonable values for this estimate are available through the\n  // DoFHandler::max_couplings_between_dofs() function, but in three\n  // dimensions the function almost always severely overestimates the true\n  // number, leading to a lot of wasted memory, sometimes too much for the\n  // machine used, even if the unused memory can be released immediately after\n  // computing the sparsity pattern. In order to avoid this, we use an\n  // intermediate object of type CompressedSparsityPattern that uses a\n  // different %internal data structure and that we can later copy into the\n  // SparsityPattern object without much overhead. (Some more information on\n  // these data structures can be found in the @ref Sparsity module.) In order\n  // to initialize this intermediate data structure, we have to give it the\n  // size of the matrix, which in our case will be square with as many rows\n  // and columns as there are degrees of freedom on the grid:\n  CompressedSparsityPattern compressed_sparsity_pattern(dof_handler.n_dofs(),\n                                                        dof_handler.n_dofs());\n\n  // We then fill this object with the places where nonzero elements will be\n  // located given the present numbering of degrees of freedom:\n  DoFTools::make_sparsity_pattern (dof_handler, compressed_sparsity_pattern);\n\n  // Now we are ready to create the actual sparsity pattern that we could\n  // later use for our matrix. It will just contain the data already assembled\n  // in the CompressedSparsityPattern.\n  SparsityPattern sparsity_pattern;\n  sparsity_pattern.copy_from (compressed_sparsity_pattern);\n\n  // With this, we can now write the results to a file:\n  std::ofstream out (\"sparsity_pattern.1\");\n  sparsity_pattern.print_gnuplot (out);\n  // The result is in GNUPLOT format, where in each line of the output file,\n  // the coordinates of one nonzero entry are listed. The output will be shown\n  // below.\n  //\n  // If you look at it, you will note that the sparsity pattern is\n  // symmetric. This should not come as a surprise, since we have not given\n  // the <code>DoFTools::make_sparsity_pattern</code> any information that\n  // would indicate that our bilinear form may couple shape functions in a\n  // non-symmetric way. You will also note that it has several distinct\n  // region, which stem from the fact that the numbering starts from the\n  // coarsest cells and moves on to the finer ones; since they are all\n  // distributed symmetrically around the origin, this shows up again in the\n  // sparsity pattern.\n}\n\n\n// @sect3{Renumbering of DoFs}\n\n// In the sparsity pattern produced above, the nonzero entries extended quite\n// far off from the diagonal. For some algorithms, for example for incomplete\n// LU decompositions or Gauss-Seidel preconditioners, this is unfavorable, and\n// we will show a simple way how to improve this situation.\n//\n// Remember that for an entry $(i,j)$ in the matrix to be nonzero, the\n// supports of the shape functions i and j needed to intersect (otherwise in\n// the integral, the integrand would be zero everywhere since either the one\n// or the other shape function is zero at some point). However, the supports\n// of shape functions intersected only if they were adjacent to each other, so\n// in order to have the nonzero entries clustered around the diagonal (where\n// $i$ equals $j$), we would like to have adjacent shape functions to be\n// numbered with indices (DoF numbers) that differ not too much.\n//\n// This can be accomplished by a simple front marching algorithm, where one\n// starts at a given vertex and gives it the index zero. Then, its neighbors\n// are numbered successively, making their indices close to the original\n// one. Then, their neighbors, if not yet numbered, are numbered, and so on.\n//\n// One algorithm that adds a little bit of sophistication along these lines is\n// the one by Cuthill and McKee. We will use it in the following function to\n// renumber the degrees of freedom such that the resulting sparsity pattern is\n// more localized around the diagonal. The only interesting part of the\n// function is the first call to <code>DoFRenumbering::Cuthill_McKee</code>,\n// the rest is essentially as before:\nvoid renumber_dofs (DoFHandler<2> &dof_handler)\n{\n  DoFRenumbering::Cuthill_McKee (dof_handler);\n\n  CompressedSparsityPattern compressed_sparsity_pattern(dof_handler.n_dofs(),\n                                                        dof_handler.n_dofs());\n  DoFTools::make_sparsity_pattern (dof_handler, compressed_sparsity_pattern);\n\n  SparsityPattern sparsity_pattern;\n  sparsity_pattern.copy_from (compressed_sparsity_pattern);\n\n  std::ofstream out (\"sparsity_pattern.2\");\n  sparsity_pattern.print_gnuplot (out);\n}\n\n// Again, the output is shown below. Note that the nonzero entries are\n// clustered far better around the diagonal than before. This effect is even\n// more distinguished for larger matrices (the present one has 1260 rows and\n// columns, but large matrices often have several 100,000s).\n\n// It is worth noting that the <code>DoFRenumbering</code> class offers a\n// number of other algorithms as well to renumber degrees of freedom. For\n// example, it would of course be ideal if all couplings were in the lower or\n// upper triangular part of a matrix, since then solving the linear system\n// would among to only forward or backward substitution. This is of course\n// unachievable for symmetric sparsity patterns, but in some special\n// situations involving transport equations, this is possible by enumerating\n// degrees of freedom from the inflow boundary along streamlines to the\n// outflow boundary. Not surprisingly, <code>DoFRenumbering</code> also has\n// algorithms for this.\n\n\n// @sect3{The main function}\n\n// Finally, this is the main program. The only thing it does is to allocate\n// and create the triangulation, then create a <code>DoFHandler</code> object\n// and associate it to the triangulation, and finally call above two functions\n// on it:\nint main ()\n{\n  Triangulation<2> triangulation;\n  make_grid (triangulation);\n\n  DoFHandler<2> dof_handler (triangulation);\n\n  distribute_dofs (dof_handler);\n  renumber_dofs (dof_handler);\n}\n", "meta": {"hexsha": "98da7b32d884c6c787df2d5b0fa632c619d8b0c8", "size": 15226, "ext": "cc", "lang": "C++", "max_stars_repo_path": "MHD/examples/step-2/step-2.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-2/step-2.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-2/step-2.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": 50.417218543, "max_line_length": 78, "alphanum_fraction": 0.7292788651, "num_tokens": 3542, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6791787121629466, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.47268007463227746}}
{"text": "#include <iostream>\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/moment.hpp>\n\n/***********extract **********/\n#include <boost/accumulators/statistics/min.hpp>\n#include <boost/accumulators/statistics/max.hpp>\n\nusing namespace boost::accumulators;\n\nint main()\n{\n\t///\n\taccumulator_set<double, stats<tag::mean, tag::moment<2> > > acc;\n\n\t//push in some data\n\n\tacc(1.2);\n\tacc(2.3);acc(3.4);\n\tacc(4.5);acc(5.6);\n\n\tstd::cout << \"Mean: \" << mean(acc) << std::endl;\n\t//we do need't accumulator field descriptor for ----accumulators::moment or\n\t/// boost namespace \n\tstd::cout << \"Moment: \" << moment<2>(acc) << std::endl;\n\n\t/*********extract************/\n\taccumulator_set<int, features<tag::min, tag::max> > iacc;\n\tiacc(2);iacc(-1);iacc(1);\n\tstd::cout << \"min: \" << min(iacc) << \", max: \" << max(iacc) << std::endl;\n\n\t//extract_result be more convenient\n\tstd::cout << \"extract result min: \" << extract_result<tag::min>(iacc) \\\n\t<< \", extract result max: \" << extract_result<tag::max>(iacc) << std::endl;\n\n\n\t//more interesting that we can define extractor\n\n\textractor<tag::min> _min;\n\textractor<tag::max> _max;\n\t//now call defined \n\tstd::cout << \"defined. min: \" << _min(iacc) << \", max: \" << _max(iacc) << std::endl;\n\n\treturn 0;\n}\n", "meta": {"hexsha": "9d631986011822ea85fd1db172e413719ad735ba", "size": 1364, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/Boost/accumulate/acc1.cpp", "max_stars_repo_name": "yanrong/book_demo", "max_stars_repo_head_hexsha": "20cd13f3c3507a11e826ebbf22bd1c7bcb36e06f", "max_stars_repo_licenses": ["Apache-2.0"], "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/Boost/accumulate/acc1.cpp", "max_issues_repo_name": "yanrong/book_demo", "max_issues_repo_head_hexsha": "20cd13f3c3507a11e826ebbf22bd1c7bcb36e06f", "max_issues_repo_licenses": ["Apache-2.0"], "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/Boost/accumulate/acc1.cpp", "max_forks_repo_name": "yanrong/book_demo", "max_forks_repo_head_hexsha": "20cd13f3c3507a11e826ebbf22bd1c7bcb36e06f", "max_forks_repo_licenses": ["Apache-2.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.4166666667, "max_line_length": 85, "alphanum_fraction": 0.6451612903, "num_tokens": 398, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.6791786861878392, "lm_q1q2_score": 0.47268006083770947}}
{"text": "/// \n/// @file maximumClique.hpp\n/// @author Jxtopher\n/// @version 0.1\n/// @date 2020-02-16\n/// @brief Probl\u00e8me de la clique maximale\n///        see : https://fr.wikipedia.org/wiki/Probl\u00e8me_de_la_clique\n///              http://www.csplib.org/Problems/prob074/\n/// compilation g++ -Os maximumClique.cpp\n/// \n///\n\n#include <cstdlib>\n#include <iostream>\n#include <string>\n#include <istream>\n#include <sstream>\n#include <fstream>      // std::filebuf\n\n#include <boost/graph/graph_utility.hpp> // print_graph\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/properties.hpp>\n#include <boost/graph/graphviz.hpp>\n\nusing namespace std;\nusing namespace boost;\n\n\n//-----------------------------------------------------------------------------\n// D\u00e9finitions des types pour le graphe\n//-----------------------------------------------------------------------------\n\n///\n/// @brief D\u00e9finition du type pour les noeuds graphe\n///\nstruct VertexProperties {\n    float d;\n    int predecessor;\n    VertexProperties() : d(std::numeric_limits<float>::infinity()), predecessor(-1) {}\n    VertexProperties(float d, int predecessor) : d(d), predecessor(-1) {}\n};\n\n///\n/// @brief D\u00e9finition du type pour les liens graphe\n///\nstruct EdgeProperties {\n    int weight;\n    EdgeProperties() : weight(0) { }\n    EdgeProperties(int weight) : weight(weight) { }\n};\n\nstruct EdgeInfoPropertyTag {\n    typedef edge_property_tag kind;\n    static std::size_t const num; // ???\n};\n\nstd::size_t const EdgeInfoPropertyTag::num = (std::size_t)&EdgeInfoPropertyTag::num;\ntypedef property<EdgeInfoPropertyTag, EdgeProperties> edge_info_prop_type;\n\n///\n/// @brief Type de graphe\n///\ntypedef adjacency_list<\n    boost::vecS, boost::vecS, boost::undirectedS,\n    VertexProperties,                               // Type vertex\n    edge_info_prop_type                             // Type edge\n> Graph;\n\n\n//-----------------------------------------------------------------------------\n// \n//-----------------------------------------------------------------------------\n\n/// \n/// @brief source https://stackoverflow.com/questions/30415388/how-to-read-dimacs-vertex-coloring-graphs-in-c\n/// \n/// @param dimacs \n/// @param g \n/// @return true \n/// @return false \n///\nbool read_dimacs(std::istream& dimacs, Graph& g) {\n    size_t vertices = 0, edges = 0;\n\n    std::string line;\n    while (getline(dimacs, line))\n    {\n        std::istringstream iss(line);\n        char ch;\n        if (iss >> ch)\n        {\n            size_t from, to;\n            std::string format;\n\n            switch(ch) {\n                case 'c': break;\n                case 'p': \n                    if (vertices||edges) return false;\n                    if (iss >> format >> vertices >> edges) {\n                        if (\"edge\" != format && \"col\" != format ) return false;\n                    }\n                    break;\n                case 'e': \n                    if (edges-- && (iss >> from >> to) && (add_edge(from-1, to-1, g).second))\n                        break;\n                default: \n                    return false;\n            }\n        }\n    }\n    return !(edges || !dimacs.eof());\n}\n\n// // Algorithme naif\n// bool is_clique(const Graph& g, const unsigned int num_main_node) {\n//     // Returns the number of edges leaving vertex u.\n//     // unsigned int number_of_edges = boost::out_degree(num_main_node, g);\n\n//     // Pas terrible\n//     vector<unsigned int> list;\n//     auto main_neighbours = boost::adjacent_vertices(num_main_node, g);\n//     for (auto v : make_iterator_range(main_neighbours))\n//         list.push_back(v);\n//     list.push_back(num_main_node);\n\n//     std::cout<<num_main_node<<\" \"<<list.size()<<std::endl;\n\n//     //\n//     for (unsigned int i = 0 ; i < list.size() ; i++) {\n//         for (unsigned int j = i+1 ; j < list.size() ; j++) {\n//             // check edge beteween list[i] and list[j]\n//             auto neighbours = boost::adjacent_vertices(list[i], g);\n//             auto x = make_iterator_range(neighbours);\n//             auto p = std::find (x.begin(), x.end(), list[j]);\n//             if (p == x.end()) {// Element not found\n//                 return false;\n//             }\n//         }\n//     }\n//     return true;\n// }\n\n// void find_clique(const Graph& g) {\n//     unsigned int degree_vertex =  0;\n//     unsigned int num_vertex = -1;\n//     for (unsigned int i = 0 ; i < boost::num_vertices(g) ; i++) {\n//         if (is_clique(g, i) && degree_vertex < out_degree(i, g)) {\n//             degree_vertex = out_degree(i, g);\n//             num_vertex = i;\n//         }\n//     }\n\n//     if (degree_vertex != 0) {\n//         std::cout<<\"Noeud principale : \"<<num_vertex<<std::endl;\n//         std::cout<<\"Taille de la clique : \"<<degree_vertex + 1<<std::endl;\n//     } else {\n//         cout<<\"Not found clique\"<<endl;\n//     }\n    \n// }\n\nbool is_clique(const Graph& g, const vector<unsigned int> &list_of_nodes) {\n    for (unsigned int i = 0 ; i < list_of_nodes.size() ; i++) {\n        for (unsigned int j = i+1 ; j < list_of_nodes.size() ; j++) {\n            // check edge beteween list[i] and list[j]\n            auto neighbours = boost::adjacent_vertices(list_of_nodes[i], g);\n            auto x = make_iterator_range(neighbours);\n            auto p = std::find (x.begin(), x.end(), list_of_nodes[j]);\n            if (p == x.end()) {// Element not found\n                return false;\n            }\n        }\n    }\n    return true;\n}\n\n\nclass CombinationGenerator {\n  public:\n\tvoid operator()(const unsigned int nbDigit, unsigned int len_string, void (*f)(unsigned int, unsigned int *, unsigned int)) {\n\t\tunsigned int nbCall = 0;\n\t\tunsigned int *string = new unsigned int[len_string];\n\n\t\tfor (unsigned int i = 0; i < len_string; i++)\n\t\t\tstring[i] = 0;\n\n\t\tbool x = false;\n\t\tunsigned int i = 0;\n\n\t\tf(nbCall++, string, len_string);\n\n\t\twhile (string[i] == (nbDigit - 1)) {\n\t\t\ti++;\n\t\t\tx = true;\n\t\t}\n\n\t\twhile (i < (len_string)) {\n\t\t\tstring[i]++;\n\n\t\t\tif (x) {\n\t\t\t\tfor (unsigned int j = 0; j < i; j++)\n\t\t\t\t\tstring[j] = 0;\n\t\t\t\ti = 0;\n\t\t\t}\n\n\t\t\tf(nbCall++, string, len_string);\n\n\t\t\twhile (string[i] == (nbDigit - 1)) {\n\t\t\t\ti++;\n\t\t\t\tx = true;\n\t\t\t}\n\t\t}\n\n\t\tdelete[] string;\n\t}\n\n\tstatic void f(unsigned int nbCall, unsigned int *string, unsigned int size) {\n\t\tstd::cout << nbCall << \" \";\n\t\tfor (unsigned int i = 0; i < size; i++)\n\t\t\tstd::cout << string[i] << \" \";\n\t\tstd::cout << std::endl;\n\t}\n};\n\n\nvoid find_clique(const Graph& g) {\n    unsigned int degree_vertex =  0;\n    unsigned int num_vertex = -1;\n\n    vector<unsigned int> clique;\n    vector<unsigned int> list_of_nodes;\n\n\n    for (unsigned int i = 0 ; i < boost::num_vertices(g) ; i++) {\n        clique.push_back(i);\n    }\n}\n\n\nvoid sec(std::vector<unsigned int> s) {\n    for (unsigned int i = 0 ; i < s.size() ; i++) {\n        for (unsigned int j = i+1 ; j < s.size() ; j++) {\n            \n        }\n    }\n}\n\nint main(int argc, char **argv) {\n    string path_file = \"benchmark-perso/c6.clq\";\n    if (argc == 2) {\n        path_file = string(argv[1]);\n    }\n    // Cr\u00e9e un graphe g\n    Graph g;\n\n    // Chargement du graphe depuis un ficher\n    std::cout<<\"[+] Loading file : \"<<path_file<<std::endl;\n    std::filebuf fb;\n    if (fb.open (path_file,std::ios::in)) {\n        std::istream is(&fb);\n        read_dimacs(is, g);\n        fb.close();\n    } else {\n        std::cerr<<\"ERROR\"<<std::endl;\n        return EXIT_FAILURE;\n    }\n\n    std::cout<<\"[+] Nombre de noeuds : \"<<boost::num_vertices(g)<<std::endl;\n\n\n\n    // find_clique(g);\n    // std::cout<<edge(0, 4, g).first<<std::endl;\n    \n    // cout<<boost::out_degree(0, g)<<endl;\n\n    // auto neighbours = boost::adjacent_vertices(0, g);\n\n    // auto p = std::find (make_iterator_range(neighbours).begin(), make_iterator_range(neighbours).end(), 3);\n    // if (p != make_iterator_range(neighbours).end()) {\n    //     std::cout << \"Element found in myints: \";\n    // } else {\n    //     std::cout << \"Element not found in myints\\n\";\n    // }\n\n    // // View\n    // print_graph(g);\n\n    /// dot -Tpdf filename.dot -o outfile.pdf\n    // std::ofstream f(\"filename.dot\");\n    // boost::write_graphviz(f, g);\n    // f.close();\n    // boost::write_graphviz(std::cout, g);\n    return EXIT_SUCCESS;\n}", "meta": {"hexsha": "0303de4438eacd9a7dfedd43c52023d7e6919ef7", "size": 8192, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "maximum-clique/maximumClique.cpp", "max_stars_repo_name": "david-sk/problem-solving", "max_stars_repo_head_hexsha": "728898fcc2883181d8f05c30351e436360f883a7", "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": "maximum-clique/maximumClique.cpp", "max_issues_repo_name": "david-sk/problem-solving", "max_issues_repo_head_hexsha": "728898fcc2883181d8f05c30351e436360f883a7", "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": "maximum-clique/maximumClique.cpp", "max_forks_repo_name": "david-sk/problem-solving", "max_forks_repo_head_hexsha": "728898fcc2883181d8f05c30351e436360f883a7", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7694915254, "max_line_length": 126, "alphanum_fraction": 0.5341796875, "num_tokens": 2103, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6791786861878392, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.47268006083770947}}
{"text": "// Copyright (c) 2019 Vsevolod Vlaskine\n\n/// @author vsevolod vlaskine\n\n#include <iostream>\n#include <sstream>\n#include <type_traits>\n#include <Eigen/Core>\n#include <opencv2/core/core.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#include <opencv2/core/version.hpp>\n#if defined( CV_VERSION_EPOCH ) && CV_VERSION_EPOCH == 2\n#include <opencv2/calib3d/calib3d.hpp>\n#else\n#include <opencv2/calib3d.hpp>\n#endif\n#include <tbb/parallel_for.h>\n#include <boost/date_time/posix_time/posix_time.hpp>\n#include <boost/tuple/tuple.hpp>\n#include <comma/base/exception.h>\n#include <comma/csv/ascii.h>\n#include <comma/visiting/traits.h>\n#include \"../../../math/range_bearing_elevation.h\"\n#include \"../../../visiting/eigen.h\"\n#include \"../../equirectangular.h\"\n#include \"equirectangular_map.h\"\n\nnamespace snark { namespace cv_calc { namespace equirectangular_map {\n    \nstatic cv::Mat rotation_matrix( double x,double y,double z ) // quick and dirty\n{\n    cv::Mat r_x = ( cv::Mat_<double>(3,3) <<\n        1,            0,            0,\n        0,  std::cos(x), -std::sin(x),\n        0,  std::sin(x),  std::cos(x) );\n    cv::Mat r_y = ( cv::Mat_<double>(3,3) <<\n        std::cos(y),    0,  std::sin(y),\n                  0,    1,            0,\n       -std::sin(y),    0,  std::cos(y) );\n    cv::Mat r_z = ( cv::Mat_<double>(3,3) <<\n        std::cos(z), -std::sin(z),      0,\n        std::sin(z),  std::cos(z),      0,\n                  0,            0,      1 );\n    return r_z * r_y * r_x;\n}\n\n// see: inverse formula for spherical projection, Szeliski, \"Computer Vision: Algorithms and Applications\" p439.\nstruct calculator\n{\n    calculator( const Eigen::Vector3d& orientation, cv::Mat K, unsigned int w, unsigned int h )\n        : RK( rotation_matrix( orientation.y(), orientation.z(), orientation.x() ) * K.inv() ) // todo: validate euler angle order\n        , w( w )\n        , h( h )\n    {\n        xyz = ( cv::Mat_< double >( 3, 1 ) << 0, 0, 1 );\n    }\n\n    std::pair< double, double > projected_pixel( unsigned int x, unsigned int y )\n    {\n        xyz.at< double >( 0, 0 ) = x;\n        xyz.at< double >( 1, 0 ) = y;\n        cv::Mat ray3d = RK * ( xyz / cv::norm( xyz ) ); \n        double xp = ray3d.at< double >( 0, 0 );\n        double yp = ray3d.at< double >( 0, 1 );\n        double zp = ray3d.at< double >( 0, 2 );    \n        double phi = std::atan2( xp, zp );\n        double sx = ( phi / ( M_PI * 2 ) + 0.5 ) * w;\n        if( sx >= w - 0.00001 ) { sx = 0; }\n        double theta = std::atan2( yp, std::sqrt( xp * xp + zp * zp ) );\n        double sy = ( theta / M_PI + 0.5 ) * h;\n        return std::make_pair( sx, sy );\n    };\n    \n    cv::Mat RK;\n    cv::Mat xyz;\n    unsigned int w;\n    unsigned int h;\n};\n\nstd::string options()\n{\n    std::ostringstream oss;\n    oss << \"        --cubes,--cube-size=[<width>]:\" << std::endl;\n    oss << \"            direct: output map width for top,back,left,front,right,bottom cubes with a given original orientation\" << std::endl;\n    oss << \"            reverse: cube size\" << std::endl;\n    oss << \"        --focal-length=<pixels>; camera focal length\" << std::endl;\n    oss << \"        --map-size,--size=[<width>,<height>]; output map size\" << std::endl;\n    oss << \"        --orientation=<roll>,<pitch>,<yaw>; default=0,0,0; orientation in radians\" << std::endl;\n    oss << \"        --reverse,--from-cubes; generate reverse map, i.e. mapping cubes to spherical images; if no --cube-size given, spherical width / 4 used\" << std::endl;\n    oss << \"        --spherical-size=<width>[,<height>]; spherical image size\" << std::endl;\n    oss << std::endl;\n    return oss.str();\n}\n\nint run( const comma::command_line_options& options )\n{\n    static_assert( sizeof( float ) == 4, \"expected float of size 4\" );\n    options.assert_mutually_exclusive( \"--reverse\", \"--focal-length,--map-size,--size,--orientation\" );\n    unsigned int spherical_width, spherical_height; // todo? make doubles?\n    const auto& s = comma::split( options.value< std::string >( \"--spherical-size\" ), ',' );\n    switch( s.size() )\n    {\n        case 1: spherical_width = boost::lexical_cast< unsigned int >( s[0] ); spherical_height = spherical_width / 2; break;\n        case 2: spherical_width = boost::lexical_cast< unsigned int >( s[0] ); spherical_height = boost::lexical_cast< unsigned int >( s[1] ); break;\n        default: std::cerr << \"cv-calc: equirectangular-map: expected spherical size as <width>[,<height>]; got '\" << comma::join( s, ',' ) << \"'\" << std::endl; return 1;\n    }\n    if( spherical_width != spherical_height * 2 ) { std::cerr << \"cv-calc: equirectangular-map: expected spherical height half of width; got width: \" << spherical_width << \" height: \" << spherical_height << std::endl; }\n    if( options.exists( \"--reverse\" ) )\n    {\n        unsigned int cube_size = options.value< unsigned int >( \"--cubes,--cube-size\", spherical_width / 4 ); // quick and dirty\n        cv::Mat x( spherical_height, spherical_width, CV_32F );\n        cv::Mat y( spherical_height, spherical_width, CV_32F );\n        tbb::parallel_for( tbb::blocked_range< std::size_t >( 0, spherical_height ), [&]( const tbb::blocked_range< std::size_t >& r )\n        {\n            for( unsigned int v = r.begin(); v < r.end(); ++v )\n            {\n                for( unsigned int u = 0; u < spherical_width; ++u )\n                {\n                    auto pixel = snark::equirectangular::to_cube( Eigen::Vector2d( u, v ), spherical_width );\n                    pixel.first.y() += pixel.second; // quick and dirty\n                    pixel.first *= cube_size;\n                    x.at< float >( v, u ) = pixel.first.x();\n                    y.at< float >( v, u ) = pixel.first.y();\n                }\n            }\n        } );\n        std::cout.write( reinterpret_cast< const char* >( x.datastart ), x.dataend - x.datastart );\n        std::cout.write( reinterpret_cast< const char* >( y.datastart ), y.dataend - y.datastart );\n        std::cout.flush();\n    }\n    else // todo? reimplement using equirectangular::... methods, which potentially may speed it up 2-3 times\n    {\n        options.assert_mutually_exclusive( \"--focal-length\", \"--cubes,--cube-size\" ); // quick and dirty for now\n        auto focal_length = options.optional< double >( \"--focal-length\" );\n        unsigned int map_width, map_height;\n        bool cubes = options.exists( \"--cubes,--cube-size\" );\n        if( cubes ) { map_width = map_height = options.value< unsigned int >( \"--cubes\" ); }\n        else { boost::tie( map_width, map_height ) = comma::csv::ascii< std::pair< unsigned int, unsigned int > >().get( options.value< std::string >( \"--map-size,--size\" ) ); }\n        if( !focal_length )\n        {\n            if( map_width != map_height ) { std::cerr << \"cv-calc: equirectangular-map: please specify --focal-length\" << std::endl; return 1; }\n            focal_length = map_width / 2;\n        }\n        cv::Mat camera = ( cv::Mat_< double >( 3, 3 ) << *focal_length,             0,  map_width / 2,\n                                                                        0, *focal_length, map_height / 2,\n                                                                        0,             0,              1 );\n        auto orientation = comma::csv::ascii< Eigen::Vector3d >().get( options.value< std::string >( \"--orientation\", \"0,0,0\" ) );\n        auto make_map = [&]( const Eigen::Vector3d& o ) -> std::pair< cv::Mat, cv::Mat >\n        {\n            cv::Mat x( map_height, map_width, CV_32F ); // quick and dirty; if output to stdout has problems, use serialisation class\n            cv::Mat y( map_height, map_width, CV_32F ); // quick and dirty; if output to stdout has problems, use serialisation class\n            tbb::parallel_for( tbb::blocked_range< std::size_t >( 0, map_height ), [&]( const tbb::blocked_range< std::size_t >& r )\n            {\n                calculator calc( o, camera, spherical_width, spherical_height );\n                for( unsigned int v = r.begin(); v < r.end(); ++v )\n                {\n                    for( unsigned int u = 0; u < map_width; ++u )\n                    {\n                        boost::tie( x.at< float >( v, u ), y.at< float >( v, u ) ) = calc.projected_pixel( u, v );\n                    }\n                }\n            } );\n            return std::make_pair( x, y );\n        };\n        auto face = make_map( orientation );\n        if( !cubes )\n        {\n            std::cout.write( reinterpret_cast< const char* >( face.first.datastart ), face.first.dataend - face.first.datastart );\n            std::cout.write( reinterpret_cast< const char* >( face.second.datastart ), face.second.dataend - face.second.datastart );\n            std::cout.flush();\n            return 0;\n        }\n        if( orientation != Eigen::Vector3d::Zero() ) { std::cerr << \"cv-calc: equirectangular-map: for --cubes, expected --orientation 0,0,0; got: \" << options.value< std::string >( \"--orientation\" ) << \" (not supported)\" << std::endl; return 1; }\n        cv::Mat x( map_height * 6, map_width, CV_32F ); // quick and dirty; if output to stdout has problems, use serialisation class\n        cv::Mat y( map_height * 6, map_width, CV_32F ); // quick and dirty; if output to stdout has problems, use serialisation class\n        tbb::parallel_for( tbb::blocked_range< std::size_t >( 0, 6 ), [&]( const tbb::blocked_range< std::size_t >& r )\n        {\n            for( unsigned int face = r.begin(); face < r.end(); ++face )\n            {\n                unsigned int offset = face * map_width;\n                for( unsigned int v = 0; v < map_width; ++v )\n                {\n                    for( unsigned int u = 0; u < map_width; ++u )\n                    {\n                        auto p = snark::equirectangular::from_cube( Eigen::Vector2d( u, v ) / map_width\n                                                                  , static_cast< equirectangular::cube::faces::values >( face ) ) * spherical_width;\n                        x.at< float >( v + offset, u ) = p.x();\n                        y.at< float >( v + offset, u ) = p.y();\n                    }\n                }\n            }\n        } );\n        std::cout.write( reinterpret_cast< const char* >( x.datastart ), x.dataend - x.datastart );\n        std::cout.write( reinterpret_cast< const char* >( y.datastart ), y.dataend - y.datastart );\n    }\n//     auto top = make_map( Eigen::Vector3d( 0, M_PI / 2, orientation.z() ) );\n//     auto bottom = make_map( Eigen::Vector3d( 0, -M_PI / 2, orientation.z() ) );\n//     std::cout.write( reinterpret_cast< const char* >( top.first.datastart ), top.first.dataend - top.first.datastart );\n//     int width = spherical_width / 4;\n//     for( int i = -2; i < 2; ++i )\n//     {\n//         cv::Mat f = face.first + width * i; // todo? waste to allocate it each time (currently, the only reason for it is the back face\n//         if( i == -2 ) { cv::Mat( f, cv::Rect( 0, 0, f.cols / 2, f.rows ) ) += spherical_width; }\n//         std::cout.write( reinterpret_cast< const char* >( f.datastart ), f.dataend - f.datastart );\n//     }\n//     std::cout.write( reinterpret_cast< const char* >( bottom.first.datastart ), bottom.first.dataend - bottom.first.datastart );\n//     std::cout.write( reinterpret_cast< const char* >( top.second.datastart ), top.second.dataend - top.second.datastart );\n//     for( unsigned int i = 0; i < 4; ++i ) { std::cout.write( reinterpret_cast< const char* >( face.second.datastart ), face.second.dataend - face.second.datastart ); }\n//     std::cout.write( reinterpret_cast< const char* >( bottom.second.datastart ), bottom.second.dataend - bottom.second.datastart );\n//     std::cout.flush();\n    return 0;\n}\n\n} } } // namespace snark { namespace cv_calc { namespace equirectangular_map {\n", "meta": {"hexsha": "7ab5dec8c9e047c1c9f171f6e59a0b379e05937a", "size": 11728, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "imaging/applications/cv_calc/equirectangular_map.cpp", "max_stars_repo_name": "mission-systems-pty-ltd/snark", "max_stars_repo_head_hexsha": "2bc8a20292ee3684d3a9897ba6fee43fed8d89ae", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-27T00:24:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T00:24:37.000Z", "max_issues_repo_path": "imaging/applications/cv_calc/equirectangular_map.cpp", "max_issues_repo_name": "NEU-LC/snark", "max_issues_repo_head_hexsha": "db890f73f4c4bbe679405f3a607fd9ea373deb2c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "imaging/applications/cv_calc/equirectangular_map.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": 54.5488372093, "max_line_length": 247, "alphanum_fraction": 0.5564461119, "num_tokens": 3150, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.782662489091802, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4726747922257349}}
{"text": "#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE DegreeTwoReducerTests\n#include <boost/test/unit_test.hpp>\n\n#include <vector>\n#include <set>\n\n#include \"graph/PBQPGraph.hpp\"\n#include \"graph/Vector.hpp\"\n#include \"graph/PBQPNode.hpp\"\n#include \"graph/PBQPEdge.hpp\"\n#include \"reduction/PBQPReduction.hpp\"\n#include \"reduction/degree/DegreeTwoReducer.hpp\"\n#include \"graph/PBQPSolution.hpp\"\n\n#include \"util/TestUtils.hpp\"\n\nnamespace pbqppapa {\n\nBOOST_AUTO_TEST_CASE(emptyGraphTest) {\n\t//make sure this doesnt explode\n\tPBQPGraph<int> graph;\n\tDegreeTwoReducer<int> twoReducer(&graph);\n\tstd::vector<PBQPGraph<int>*> result = twoReducer.reduce();\n}\n\nBOOST_AUTO_TEST_CASE(simpleCalculation) {\n\tPBQPGraph<int> graph = PBQPGraph<int>();\n\tint node1Arr[] { 1, 2 };\n\tint node2Arr[] { 5, 3 };\n\tint node3Arr[] { 10, 2 };\n\tVector<int> vek1(2, node1Arr);\n\tVector<int> vek2(2, node2Arr);\n\tVector<int> vek3(2, node3Arr);\n\tPBQPNode<int>* first = graph.addNode(vek1);\n\tPBQPNode<int>* second = graph.addNode(vek2);\n\tPBQPNode<int>* third = graph.addNode(vek3);\n\tunsigned long firstIndex = first->getIndex();\n\tunsigned long secondIndex = second->getIndex();\n\tunsigned long thirdIndex = third->getIndex();\n\tint edge1Arr[] { 3, 1, 8, 5 };\n\tMatrix<int> mat1(2, 2, edge1Arr);\n\tint edge2Arr[] { 0, 7, 2, 8 };\n\tMatrix<int> mat2(2, 2, edge2Arr);\n\tgraph.addEdge(first, second, mat1);\n\tgraph.addEdge(second, third, mat2);\n\t//second one gets removed\n\tDegreeTwoReducer<int> twoReducer(&graph);\n\tstd::vector<PBQPGraph<int>*> result = twoReducer.reduce();\n\tBOOST_CHECK_EQUAL(result.size(), 1);\n\tPBQPGraph<int>* resultGraph = result[0];\n\tBOOST_CHECK_EQUAL(resultGraph->getNodeCount(), 2);\n\tBOOST_CHECK_EQUAL(resultGraph->getEdgeCount(), 1);\n\tPBQPEdge<int>* edge = *(resultGraph->getEdgeBegin());\n\tBOOST_CHECK_EQUAL(edge->getMatrix().get(0, 0), 6);\n\tBOOST_CHECK_EQUAL(edge->getMatrix().get(0, 1), 12);\n\tBOOST_CHECK_EQUAL(edge->getMatrix().get(1, 0), 10);\n\tBOOST_CHECK_EQUAL(edge->getMatrix().get(1, 1), 16);\n\tPBQPSolution<int> sol(3);\n\tsol.setSolution(firstIndex, 0);\n\tsol.setSolution(thirdIndex, 0);\n\ttwoReducer.solve(sol);\n\tBOOST_CHECK_EQUAL(sol.getSolution(secondIndex), 1);\n}\n\n}\n", "meta": {"hexsha": "30d3bd0a51758a476504ad7fae7f33f4d8649330", "size": 2144, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/reduction/DegreeTwoReducerTests.cpp", "max_stars_repo_name": "sgraf812/pbqp-papa", "max_stars_repo_head_hexsha": "b5ae6fcb0842cb66956cccc4663f6fd9e6f6ae07", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-08-10T04:18:11.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-10T04:18:11.000Z", "max_issues_repo_path": "test/reduction/DegreeTwoReducerTests.cpp", "max_issues_repo_name": "sgraf812/pbqp-papa", "max_issues_repo_head_hexsha": "b5ae6fcb0842cb66956cccc4663f6fd9e6f6ae07", "max_issues_repo_licenses": ["MIT"], "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/reduction/DegreeTwoReducerTests.cpp", "max_forks_repo_name": "sgraf812/pbqp-papa", "max_forks_repo_head_hexsha": "b5ae6fcb0842cb66956cccc4663f6fd9e6f6ae07", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-03-07T10:20:50.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-07T10:20:50.000Z", "avg_line_length": 32.0, "max_line_length": 59, "alphanum_fraction": 0.7285447761, "num_tokens": 642, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.782662489091802, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.47267479222573483}}
{"text": "// Functions for reading, encoding and normalizeing image features\n//\n// @author: Bingqing Qu\n//\n// For implentation details, refer to:\n//\n// Jinjun Wang; Jianchao Yang; Kai Yu; Fengjun Lv; Huang, T.;\n// Yihong Gong, \"Locality-constrained Linear Coding for image\n// classification, \" Computer Vision and Pattern Recognition (CVPR),\n// 2010 IEEE Conference on , vol., no., pp.3360,3367, 13-18 June 2010\n//\n// Copyright (C) 2014-2015  Bingqing Qu <sylar.qu@gmail.com>\n//\n// @license: See LICENSE at root directory\n\n#ifndef SIREEN_IMAGE_FEATURE_EXTRACT_H_\n#define SIREEN_IMAGE_FEATURE_EXTRACT_H_\n#include <fstream>\n#include <string.h>\n#include <queue>\n#include <stdexcept>\n#include <algorithm>\n\n// opencv header\n#include <opencv2/opencv.hpp>\n\n// Eigen Linear Algebra\n#include <Eigen/Dense>\n\nusing namespace cv;\nusing namespace std;\nusing namespace Eigen;\n\nextern \"C\" {\n#include <vl/generic.h>\n#include <vl/sift.h>\n#include <vl/dsift.h>\n};\n\n// Image Coder Class\n// Sample Usage:\n//    ImageCoder icoder;\n//    Mat src_image = cv::imread(path_to_image,0);\n//    std::string result = icoder.LLCDescriptor(src_image);\nclass ImageCoder\n{\n\nprivate:\n    /** DSIFT MEMBERS */\n    // standard resize width\n    int std_width_;\n    // standard resize height\n    int std_height_;\n    // sift sampleing step size\n    unsigned int step_;\n    // sift bin size\n    unsigned int bin_size_;\n    // dsift filter\n    VlDsiftFilter* dsift_filter_;\n\n    // image data buffer, in vlfeat, vl_sift_pix is general used\n    // vl_sift_pix is infact a symbolic link to float\n    // the buffer always contains current image pixel values\n    float* image_data_;\n\n    /** SIFT MEMBERS */\n    // sift filter\n    VlSiftFilt* sift_filter_;\n\n    /**\n     * set parameters for ImageCoder\n     *\n     * @param std_width  standard image resize frame width\n     * @param std_height standard image resize frame height\n     * @param step       VlDsiftFilter step parameter\n     * @param bin_size   VlDsiftFilter binSize parameter\n     */\n    void set_params(int, int, int, int);\n    /**\n     * decode image to graylevel resized values by row-order.\n     *\n     * @param src_image opencv Mat image\n     *\n     * @return image data values\n     */\n    float* decode_image(Mat);\n    /**\n     * compute linear local constraint coding descriptor from dsift\n     * descriptors\n     *\n     * @param dsift_descr dsift descriptors\n     * @param codebook    codebook from sift-kmeans\n     * @param ncb         dimension of codebook\n     * @param k           get top k nearest codes\n     * @param out         output vector will take the llc result\n     *\n     * @return Eigen vector take the llc valuex\n     */\n    VectorXf llc_process(float*, float*, const int, const int, const int, const int);\n\n\npublic:\n    /** Default Constructor*/\n    ImageCoder(void);\n    /**\n     * Constructor Overloading\n     * @param std_width  standard image resize frame width\n     * @param std_height standard image resize frame height\n     * @param step       VlDsiftFilter step parameter\n     * @param bin_size   VlDsiftFilter binSize parameter\n     */\n    ImageCoder(int,int,int,int);\n    /**\n     * Constructor Overloading\n     * @param dsift_filter VlDsiftFilter*\n     */\n    ImageCoder(VlDsiftFilter*);\n    /** Destructor */\n    ~ImageCoder(void);\n    /**\n     * encode dense-sift descriptors\n     *\n     * @param image pixel values in row-major order\n     * @return the dense sift float-point descriptors\n     */\n    float* dsift_descriptor(float*);\n    void sift_descriptor(float*, int&, vector<float>&);\n    /**\n     * compute linear local constraint coding descriptor\n     *\n     * @param dsift_descr dsift descriptors\n     * @param codebook  codebook from sift-kmeans\n     * @param ncb       dimension of codebook\n     * @param k         get top k nearest codes\n     * @param out       output vector will take the llc result\n     *\n     * @return a conversion from llc feature to string\n     */\n    string llc_dense_sift(float* , float*, const int, const int, vector<float> &);\n    /**\n     * compute linear local constraint coding descriptor\n     *\n     * @param src_image source image in opencv mat format\n     * @param codebook  codebook from sift-kmeans\n     * @param ncb       dimension of codebook\n     * @param k         get top k nearest codes\n     *\n     * @return a conversion from llc feature to string\n     */\n    string llc_dense_sift(Mat, float*, const int, const int);\n    string llc_sift(Mat, float*, const int, const int);\n\n    /**\n     * Optimized sift feature improvement and normalization\n     *\n     * @param descriptors sift descriptors\n     * @param row         number of rows\n     * @param col         number of column\n     * @param normalized  flag for normalized input\n     *\n     * @return MatrixXf normalized dsift descripters in Eigen::MatrixXf form\n     */\n    Eigen::MatrixXf norm_sift(float *, int, int, const bool);\n\n};\n#endif //SIREEN_IMAGE_FEATURE_EXTRACT_H_\n", "meta": {"hexsha": "f2e6dfd8959dfa7ef5b766c3c8aa32653b991a3e", "size": 4930, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/sireen/image_feature_extract.hpp", "max_stars_repo_name": "Jetpie/SiReen", "max_stars_repo_head_hexsha": "00365023117bec88391bfb37d9549fdca75ac10b", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2015-03-18T15:00:38.000Z", "max_stars_repo_stars_event_max_datetime": "2016-01-04T13:09:59.000Z", "max_issues_repo_path": "include/sireen/image_feature_extract.hpp", "max_issues_repo_name": "Jetpie/SiReen", "max_issues_repo_head_hexsha": "00365023117bec88391bfb37d9549fdca75ac10b", "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/sireen/image_feature_extract.hpp", "max_forks_repo_name": "Jetpie/SiReen", "max_forks_repo_head_hexsha": "00365023117bec88391bfb37d9549fdca75ac10b", "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.5209580838, "max_line_length": 85, "alphanum_fraction": 0.6588235294, "num_tokens": 1226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529376, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4726747861025518}}
{"text": "#ifndef __earthenvironment_HH__\n#define __earthenvironment_HH__\n/********************************* TRICK HEADER *******************************\nPURPOSE:\n      (Describe the EarthEnvironment Module Variables and Algorithm)\nLIBRARY DEPENDENCY:\n      ((../src/EarthEnvironment.cpp))\nPROGRAMMERS:\n      (((Chun-Hsu Lai) () () () ))\n*******************************************************************************/\n#include <armadillo>\n#include <functional>\n#include \"Module.hh\"\n#include \"aux.hh\"\n#include \"global_constants.hh\"\n\n#include \"env/atmosphere.hh\"\n#include \"env/atmosphere76.hh\"\n#include \"env/atmosphere_nasa2002.hh\"\n#include \"env/atmosphere_weatherdeck.hh\"\n\n#include \"env/wind.hh\"\n#include \"env/wind_constant.hh\"\n#include \"env/wind_no.hh\"\n#include \"env/wind_tabular.hh\"\n\n#include \"Time_management.hh\"\n#include \"dm_delta_ut.hh\"\n\nclass EarthEnvironment : public Dynamics {\n  TRICK_INTERFACE(EarthEnvironment);\n\n public:\n  EarthEnvironment(Data_exchang& input);\n\n  EarthEnvironment(const EarthEnvironment& other);\n  ~EarthEnvironment();\n\n  EarthEnvironment& operator=(const EarthEnvironment& other);\n\n  void atmosphere_use_public();\n  void atmosphere_use_nasa();\n  void atmosphere_use_weather_deck(char* filename);\n\n  void set_no_wind();\n  void set_constant_wind(double dvae, double dir, double twind,\n                         double vertical_wind);\n  void set_tabular_wind(char* filename, double twind, double vertical_wind);\n\n  void set_no_wind_turbulunce();\n  void set_wind_turbulunce(double turb_length, double turb_sigma, double taux1,\n                           double taux1d, double taux2, double taux2d,\n                           double tau, double gauss_value);\n\n  virtual void init();\n  virtual void algorithm(double int_step);\n\n  void set_RNP();\n\n  // double get_rho();\n  // double get_vmach();\n  // double get_pdynmc();\n  // double get_tempk();\n  // double get_dvba();\n  // double get_grav();\n  // double get_press();\n\n  // arma::vec3 get_GRAVG();\n  // arma::vec3 get_VAED();\n  // arma::mat33 get_TEI();\n\n\n private:\n  time_management* time;\n\n  /* Constants */\n  cad::Atmosphere* atmosphere;\n  cad::Wind* wind;\n\n  /* Variable declaration */\n  VECTOR(GRAVG, 3);  /* *o (m/s2) Earth gravity acceleration in inertia frame */\n  VECTOR(VBAB, 3);   /* *o (m/s)  Vehicle speed wrt air speed in body frame */\n  MATRIX(TEI, 3, 3); /* *o (--)  T.M. from ECI to ECEF */\n\n  double vmach;            /* *o (--)  vehicle mach number */\n  double pdynmc;           /* *o (pa)  Dynamic pressure */\n  double dvba;             /* *o (m/s) Vehicle air speed magnitude */\n  double gravg;            /* *o (m/s2)  Earth gravity acceleration magnitude */\n  double tempc;            /* *o (c)  Atmosphere temperature in Celsius */\n  double DM_sidereal_time; /* *o  (--)  Sidereal time */\n  double DM_Julian_century; /* *o  (--)  Julian_century */\n\n  /* Function declaration */\n  void RNP();\n  arma::vec AccelHarmonic(arma::vec3 SBII, int n_max, int m_max);\n};\n\n#endif  // __earthenvironment_HH__\n", "meta": {"hexsha": "c96c745e4984ac5dbc7e63ac3a65fc2335ac82d9", "size": 2986, "ext": "hh", "lang": "C++", "max_stars_repo_path": "models/dm/include/EarthEnvironment.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/EarthEnvironment.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/EarthEnvironment.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": 30.1616161616, "max_line_length": 80, "alphanum_fraction": 0.6393168118, "num_tokens": 742, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529376, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4726747861025518}}
{"text": "#include <iostream>\n\n#include <boost/graph/grid_graph.hpp>\n\n#include \"NearestNeighbor/topological_search.hpp\"\n\nint main(int argc, char *argv[])\n{\n  typedef boost::grid_graph<2> GraphType;\n\n  const unsigned int dimension = 5;\n  boost::array<std::size_t, 2> lengths = { { dimension, dimension } };\n  GraphType graph(lengths);\n\n  typedef boost::graph_traits<GraphType>::vertex_descriptor VertexDescriptor;\n\n  VertexDescriptor v = { { 0, 1 } };\n\n  typedef boost::hypercube_topology<6, boost::minstd_rand> TopologyType;\n  TopologyType myTopology;\n  typedef TopologyType::point_type PointType;\n\n  std::vector<PointType> vertexData(dimension * dimension);\n\n  // This is an \"exterior property\" of the grid_graph\n  typedef boost::property_map<GraphType, boost::vertex_index_t>::const_type IndexMapType;\n\n  IndexMapType indexMap(get(boost::vertex_index, graph));\n\n  typedef boost::iterator_property_map<std::vector<PointType>::iterator, IndexMapType> MapType;\n  MapType myMap(vertexData.begin(), indexMap);\n\n  typedef linear_neighbor_search<> SearchType;\n\n  // Add vertices to the graph and corresponding points increasin integer points to the tree.\n  // The experiment here is to query the nearest neighbor of a point like (5.2, 5.2, 5.1, 5.3, 5.2, 5.1)\n  // and ensure we get back (5,5,5,5,5,5)\n  unsigned int numberOfVertices = 100;\n  for(unsigned int vertexId = 0; vertexId < numberOfVertices; ++vertexId)\n  {\n    PointType p;\n    for(unsigned int dim = 0; dim < dimension; ++dim)\n      {\n      p[dim] = vertexId;\n      }\n    boost::put(myMap, v, p);\n  };\n\n  PointType queryPoint;\n  for(unsigned int dim = 0; dim < dimension; ++dim)\n    {\n    queryPoint[dim] = 5.2;\n    }\n\n  SearchType search;\n\n  //VertexDescriptor nearestNeighbor = search(queryPoint, graph, myTopology, myMap);\n  VertexDescriptor nearestNeighbor = search.operator()<GraphType, TopologyType, MapType>(queryPoint, graph, myTopology, myMap);\n  std::cout << \"nearestNeighbor[0]: \" << nearestNeighbor[0] << std::endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "04e92e8d1599101bc89a2c2e8ed2fb2c5c531376", "size": 1991, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "NearestNeighbor/Tests/TestLinearNeighborSearchSubset.cpp", "max_stars_repo_name": "jingtangliao/ff", "max_stars_repo_head_hexsha": "d308fe62045e241a4822bb855df97ee087420d9b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 39.0, "max_stars_repo_stars_event_min_datetime": "2015-01-01T07:59:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-01T18:11:46.000Z", "max_issues_repo_path": "NearestNeighbor/Tests/TestLinearNeighborSearchSubset.cpp", "max_issues_repo_name": "jingtangliao/ff", "max_issues_repo_head_hexsha": "d308fe62045e241a4822bb855df97ee087420d9b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-24T09:56:15.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-24T14:45:46.000Z", "max_forks_repo_path": "NearestNeighbor/Tests/TestLinearNeighborSearchSubset.cpp", "max_forks_repo_name": "jingtangliao/ff", "max_forks_repo_head_hexsha": "d308fe62045e241a4822bb855df97ee087420d9b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2015-01-11T15:10:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T20:02:10.000Z", "avg_line_length": 31.6031746032, "max_line_length": 127, "alphanum_fraction": 0.7137117027, "num_tokens": 536, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.47267478610255176}}
{"text": "#include <boost/random/poisson_distribution.hpp>\n", "meta": {"hexsha": "5cf46d879ed063f9d40c4061a4475a24f8f56082", "size": 49, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_random_poisson_distribution.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_random_poisson_distribution.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_random_poisson_distribution.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 24.5, "max_line_length": 48, "alphanum_fraction": 0.8367346939, "num_tokens": 10, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.47267478610255176}}
{"text": "#include \"cellogram/image_reader.h\"\n\n#include <Eigen/Dense>\n#include <iostream>\n\nint main(int argc, char** argv)\n{\n\tEigen::MatrixXd img;\n\tcellogram::read_image(\".../detection_test.tif\", img);\n\n\tstd::cout<<img<<std::endl;\n\n\treturn 0;\n}\n", "meta": {"hexsha": "155dc3276210452451f5a3e24e30791fb06c0ab5", "size": 235, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "misc/image_test.cpp", "max_stars_repo_name": "cellogram/cellogram", "max_stars_repo_head_hexsha": "d378e9b87e56b879b2fb352b08b0fed714481968", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-09-25T15:04:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-20T08:17:44.000Z", "max_issues_repo_path": "misc/image_test.cpp", "max_issues_repo_name": "cellogram/cellogram", "max_issues_repo_head_hexsha": "d378e9b87e56b879b2fb352b08b0fed714481968", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "misc/image_test.cpp", "max_forks_repo_name": "cellogram/cellogram", "max_forks_repo_head_hexsha": "d378e9b87e56b879b2fb352b08b0fed714481968", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-10-14T01:36:20.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-11T20:27:57.000Z", "avg_line_length": 15.6666666667, "max_line_length": 54, "alphanum_fraction": 0.6893617021, "num_tokens": 67, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.47267477997936863}}
{"text": "/*\n   For more information, please see: http://software.sci.utah.edu\n\n   The MIT License\n\n   Copyright (c) 2020 Scientific Computing and Imaging Institute,\n   University of Utah.\n\n   Permission is hereby granted, free of charge, to any person obtaining a\n   copy of this software and associated documentation files (the \"Software\"),\n   to deal in the Software without restriction, including without limitation\n   the rights to use, copy, modify, merge, publish, distribute, sublicense,\n   and/or sell copies of the Software, and to permit persons to whom the\n   Software is furnished to do so, subject to the following conditions:\n\n   The above copyright notice and this permission notice shall be included\n   in all copies or substantial portions of the Software.\n\n   THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n   DEALINGS IN THE SOFTWARE.\n*/\n\n\n#include <Core/Algorithms/Math/ComputeTensorUncertaintyAlgorithm.h>\n#include <Core/Algorithms/Base/AlgorithmPreconditions.h>\n#include <Core/Datatypes/Dyadic3DTensor.h>\n#include <Core/Datatypes/Legacy/Field/FieldInformation.h>\n#include <Core/Datatypes/Mesh/MeshFacade.h>\n#include <Core/Datatypes/DenseMatrix.h>\n#include <Core/Datatypes/Legacy/Field/VMesh.h>\n#include <Core/Datatypes/Legacy/Field/VField.h>\n#include <Core/GeometryPrimitives/Point.h>\n#include <boost/tuple/tuple.hpp>\n#include <unsupported/Eigen/MatrixFunctions>\n\nusing namespace SCIRun;\nusing namespace Core;\nusing namespace Core::Datatypes;\nusing namespace Core::Algorithms;\nusing namespace Core::Algorithms::Math;\nusing namespace Core::Geometry;\n\nAlgorithmOutputName ComputeTensorUncertaintyAlgorithm::MeanTensorField(\"MeanTensorField\");\nAlgorithmOutputName ComputeTensorUncertaintyAlgorithm::CovarianceMatrix(\"CovarianceMatrix\");\n\nALGORITHM_PARAMETER_DEF(Math, MeanInvariantMethod);\nALGORITHM_PARAMETER_DEF(Math, MeanOrientationMethod);\n\n// TODO move helpers\nDyadic3DTensor scirunTensorToEigenTensor(const Geometry::Tensor& t)\n{\n  Dyadic3DTensor newTensor(t.xx(), t.xy(), t.xz(), t.yy(), t.yz(), t.zz());\n  return newTensor;\n}\n\nTensor eigenTensorToScirunTensor(const Dyadic3DTensor& t)\n{\n  return Tensor(t(0, 0), t(1, 0), t(2, 0), t(1, 1), t(2, 1), t(2, 2));\n}\n\n// TODO move to separate algo\nenum FieldDataType\n{ node, edge, face, cell };\n\nclass ComputeTensorUncertaintyAlgorithmImpl\n{\npublic:\n  ComputeTensorUncertaintyAlgorithmImpl();\n  void run(const FieldList& fields);\n  void setInvariantMethod(AlgoOption method);\n  void setOrientationMethod(AlgoOption method);\n  void getPoints(const FieldList& fields);\n  void getPointsForFields(FieldHandle field, std::vector<int>& indices, std::vector<Point>& points);\n  FieldHandle getMeanTensors() const;\n  MatrixHandle getCovarianceMatrices() const;\nprivate:\n  size_t fieldCount_ = 0;\n  size_t fieldSize_ = 0;\n  std::vector<std::vector<Point>> points_;\n  std::vector<std::vector<int>> indices_;\n  std::vector<std::vector<Dyadic3DTensor>> tensors_;\n  std::vector<Dyadic3DTensor> meanTensors_;\n  std::vector<DyadicTensor<6>> covarianceMatrices_;\n  AlgoOption invariantMethod_;\n  AlgoOption orientationMethod_;\n\n  void verifyData(const FieldList& fields);\n  void getTensors(const FieldList& fields);\n  void computeCovarianceMatrices();\n  void computeMeanTensors();\n  Dyadic3DTensor computeMeanMatrixAverage(int index) const;\n  Dyadic3DTensor computeMeanLinearInvariant(int t) const;\n  Dyadic3DTensor computeMeanLogEuclidean(int t) const;\n  void computeMeanTensorsSameMethod();\n  void computeMeanTensorsDifferentMethod();\n};\n\nvoid ComputeTensorUncertaintyAlgorithmImpl::setInvariantMethod(AlgoOption method)\n{\n  invariantMethod_ = method;\n}\n\nvoid ComputeTensorUncertaintyAlgorithmImpl::setOrientationMethod(AlgoOption method)\n{\n  orientationMethod_ = method;\n}\n\nFieldHandle ComputeTensorUncertaintyAlgorithmImpl::getMeanTensors() const\n{\n  FieldInformation ofinfo(\"PointCloudMesh\", 0, \"Tensor\");\n  auto ofield = CreateField(ofinfo);\n  auto mesh = ofield->vmesh();\n  auto field = ofield->vfield();\n\n  std::vector<VMesh::index_type> meshIndices(fieldSize_);\n  for (size_t i = 0; i < fieldSize_; ++i)\n    meshIndices[i] = mesh->add_point(points_[0][i]);\n\n  field->resize_fdata();\n\n  for (size_t i = 0; i < fieldSize_; ++i)\n    field->set_value(eigenTensorToScirunTensor(meanTensors_[i]), meshIndices[i]);\n\n  return ofield;\n}\n\nvoid ComputeTensorUncertaintyAlgorithmImpl::computeMeanTensorsSameMethod()\n{\n  if (orientationMethod_.option_ == \"Matrix Average\")\n  {\n    for (size_t t = 0; t < fieldSize_; ++t)\n      meanTensors_[t] = computeMeanMatrixAverage(t);\n  }\n  else if (orientationMethod_.option_ == \"Log-Euclidean\")\n  {\n    for (size_t t = 0; t < fieldSize_; ++t)\n      meanTensors_[t] = computeMeanLogEuclidean(t);\n  }\n}\n\nvoid ComputeTensorUncertaintyAlgorithmImpl::computeMeanTensorsDifferentMethod()\n{\n  std::vector<Dyadic3DTensor> orientationTensors(fieldSize_);\n  std::vector<Dyadic3DTensor> invariantTensors(fieldSize_);\n  if (orientationMethod_.option_ == \"Matrix Average\")\n  {\n    for (size_t t = 0; t < fieldSize_; ++t)\n      orientationTensors[t] = computeMeanMatrixAverage(t);\n  }\n  else if (orientationMethod_.option_ == \"Log-Euclidean\")\n  {\n    for (size_t t = 0; t < fieldSize_; ++t)\n      orientationTensors[t] = computeMeanLogEuclidean(t);\n  }\n\n  if (invariantMethod_.option_ == \"Matrix Average\")\n  {\n    for (size_t t = 0; t < fieldSize_; ++t)\n      invariantTensors[t] = computeMeanMatrixAverage(t);\n  }\n  else if (invariantMethod_.option_ == \"Log-Euclidean\")\n  {\n    for (size_t t = 0; t < fieldSize_; ++t)\n      invariantTensors[t] = computeMeanLogEuclidean(t);\n  }\n  else if (invariantMethod_.option_ == \"Linear Invariant\")\n  {\n    for (size_t t = 0; t < fieldSize_; ++t)\n      invariantTensors[t] = computeMeanLinearInvariant(t);\n  }\n\n  for (size_t t = 0; t < fieldSize_; ++t)\n  {\n    invariantTensors[t].setDescendingRHSOrder();\n    orientationTensors[t].setDescendingRHSOrder();\n    meanTensors_[t] = Dyadic3DTensor(orientationTensors[t].getEigenvectors(),\n                                     invariantTensors[t].getEigenvalues());\n    meanTensors_[t].setDescendingRHSOrder();\n  }\n}\n\nvoid ComputeTensorUncertaintyAlgorithmImpl::computeMeanTensors()\n{\n  meanTensors_ = std::vector<Dyadic3DTensor>(fieldSize_);\n  if (invariantMethod_.option_ == orientationMethod_.option_)\n    computeMeanTensorsSameMethod();\n  else\n    computeMeanTensorsDifferentMethod();\n}\n\nDyadic3DTensor ComputeTensorUncertaintyAlgorithmImpl::computeMeanMatrixAverage(int t) const\n{\n  Dyadic3DTensor sum = Dyadic3DTensor();\n  for (size_t f = 0; f < fieldCount_; ++f) {\n    sum += tensors_[f][t];\n  }\n  sum = sum / (double)fieldCount_;\n\n  return sum;\n}\n\n// Mean calculation using Linear Invariant interpolation\nDyadic3DTensor ComputeTensorUncertaintyAlgorithmImpl::computeMeanLinearInvariant(int t) const\n{\n  const static double oneThird = 1.0 / 3.0;\n  const static double sqrtThreeHalves = sqrt(1.5);\n  const static double threeSqrtSix = 3.0 * sqrt(6.0);\n\n  const static Dyadic3DTensor identity = Dyadic3DTensor(Eigen::Vector3d(1, 0, 0),\n                                                        Eigen::Vector3d(0, 1, 0),\n                                                        Eigen::Vector3d(0, 0, 1));\n  const static Dyadic3DTensor identityThird = oneThird * identity;\n\n  double K1 = 0.0;\n  double R2 = 0.0;\n  double R3 = 0.0;\n\n  for (size_t f = 0; f < fieldCount_; ++f)\n  {\n    const double trace = tensors_[f][t].trace();\n    Dyadic3DTensor trThird = trace * identityThird;\n    K1 += trace;\n\n    const double fro = tensors_[f][t].frobeniusNorm();\n    Dyadic3DTensor anisotropicDeviation = tensors_[f][t] - trThird;\n    anisotropicDeviation.setDescendingRHSOrder();\n    const double anisotropicDeviationFro = anisotropicDeviation.frobeniusNorm();\n\n    R2 += sqrtThreeHalves * anisotropicDeviationFro / fro;\n    R3 += threeSqrtSix * (anisotropicDeviation / anisotropicDeviationFro).asMatrix().determinant();\n  }\n\n  // Equally weight all of the coeffecients\n  K1 /= static_cast<double>(fieldCount_);\n  R2 /= static_cast<double>(fieldCount_);\n  R3 /= static_cast<double>(fieldCount_);\n\n  // Clamp to avoid nan results with acos\n  if (R3 > 1.0) R3 = 1.0;\n  if (R3 < -1.0) R3 = -1.0;\n\n  \n  const double arccosR3 = std::acos(R3);\n  Eigen::Vector3d eigvals;\n  const double x = oneThird * K1;\n  const double y = (2.0 * K1 * R2) / (3.0 * sqrt(3.0 - 2.0 * std::pow(R2, 2.0)));\n  eigvals(0) = x + y * std::cos(arccosR3 * oneThird);\n  eigvals(1) = x + y * std::cos((arccosR3 - 2.0 * M_PI) * oneThird);\n  eigvals(2) = x + y * std::cos((arccosR3 + 2.0 * M_PI) * oneThird);\n\n  // Using axis aligned orientation because this mean method is only for invariants\n  Dyadic3DTensor ret = Dyadic3DTensor({Eigen::Vector3d({1,0,0}), Eigen::Vector3d({0,1,0}), Eigen::Vector3d({0,0,1})}, eigvals);\n  return ret;\n}\n\nDyadic3DTensor ComputeTensorUncertaintyAlgorithmImpl::computeMeanLogEuclidean(int t) const\n{\n  Eigen::Matrix3d sum = Eigen::Matrix3d::Zero();\n  for (size_t f = 0; f < fieldCount_; ++f)\n  {\n    Dyadic3DTensor tensor = tensors_[f][t];\n    tensor.setDescendingRHSOrder();\n    Eigen::Vector3d eigvalsLog = tensor.getEigenvalues();\n    Eigen::Matrix3d rotation = tensor.getEigenvectorsAsMatrix();\n    for (size_t i = 0; i < eigvalsLog.size(); ++i)\n      eigvalsLog[i] = std::log(eigvalsLog[i]);\n    sum += rotation * eigvalsLog.asDiagonal() * rotation.transpose();\n  }\n  sum /= (double)fieldCount_;\n  Eigen::Matrix3d mean = sum.exp();\n  Dyadic3DTensor ret = Dyadic3DTensor(mean);\n  return ret;\n}\n\nComputeTensorUncertaintyAlgorithmImpl::ComputeTensorUncertaintyAlgorithmImpl()\n{}\n\nvoid ComputeTensorUncertaintyAlgorithmImpl::computeCovarianceMatrices()\n{\n  covarianceMatrices_ = std::vector<DyadicTensor<6>>(fieldSize_);\n\n  Eigen::Matrix<double, 6, 6> covarianceMat;\n  for (size_t t = 0; t < fieldSize_; ++t)\n  {\n    covarianceMat.fill(0.0);\n    for (size_t f = 0; f < fieldCount_; ++f)\n    {\n      Eigen::Matrix<double, 6, 1> diffTensor = (tensors_[f][t] - meanTensors_[t]).mandel();\n      covarianceMat += diffTensor * diffTensor.transpose();\n    }\n    covarianceMat /= static_cast<double>(fieldCount_);\n    covarianceMatrices_[t] = DyadicTensor<6>(covarianceMat);\n  }\n}\n\nvoid ComputeTensorUncertaintyAlgorithmImpl::getPointsForFields(\n    FieldHandle field, std::vector<int>& indices, std::vector<Point>& points)\n{\n  // Collect indices and points from facades\n  FieldDataType fieldLocation;\n  FieldInformation finfo(field);\n  if (finfo.is_point() || finfo.is_linear())\n    fieldLocation = FieldDataType::node;\n  else if (finfo.is_line())\n    fieldLocation = FieldDataType::edge;\n  else if (finfo.is_surface())\n    fieldLocation = FieldDataType::face;\n  else\n    fieldLocation = FieldDataType::cell;\n\n  auto mesh = field->vmesh();\n  auto primaryFacade = field->mesh()->getFacade();\n  switch (fieldLocation)\n  {\n  case FieldDataType::node:\n    for (const auto& node : primaryFacade->nodes())\n    {\n      indices.push_back(node.index());\n      Point p;\n      mesh->get_center(p, node.index());\n      points.push_back(p);\n    }\n    break;\n  case FieldDataType::edge:\n    for (const auto& edge : primaryFacade->edges())\n    {\n      indices.push_back(edge.index());\n      Point p;\n      mesh->get_center(p, edge.index());\n      points.push_back(p);\n    }\n    break;\n  case FieldDataType::face:\n    for (const auto& face : primaryFacade->faces())\n    {\n      indices.push_back(face.index());\n      Point p;\n      mesh->get_center(p, face.index());\n      points.push_back(p);\n    }\n    break;\n  case FieldDataType::cell:\n    for (const auto& cell : primaryFacade->cells())\n    {\n      indices.push_back(cell.index());\n      Point p;\n      mesh->get_center(p, cell.index());\n      points.push_back(p);\n    }\n    break;\n  }\n}\n\nvoid ComputeTensorUncertaintyAlgorithmImpl::getPoints(const FieldList& fields)\n{\n  fieldCount_ = fields.size();\n\n  indices_ = std::vector<std::vector<int>>(fieldCount_);\n  points_ = std::vector<std::vector<Point>>(fieldCount_);\n\n  for (size_t f = 0; f < fieldCount_; ++f)\n    getPointsForFields(fields[f], indices_[f], points_[f]);\n}\n\nvoid ComputeTensorUncertaintyAlgorithmImpl::verifyData(const FieldList& fields)\n{\n  fieldSize_ = indices_[0].size();\n  for (size_t f = 1; f < fieldCount_; ++f)\n    if (indices_[f].size() != fieldSize_)\n      THROW_ALGORITHM_INPUT_ERROR_SIMPLE(\"All field inputs must have the same size.\");\n\n  // Verify all are tensors\n  for (auto field : fields)\n  {\n    FieldInformation finfo(field);\n    if (!finfo.is_tensor())\n      THROW_ALGORITHM_INPUT_ERROR_SIMPLE(\"This module only supports tensor fields.\");\n  }\n}\n\nvoid ComputeTensorUncertaintyAlgorithmImpl::getTensors(const FieldList& fields)\n{\n  tensors_ = std::vector<std::vector<Dyadic3DTensor>>(fieldCount_);\n  for (size_t f = 0; f < fieldCount_; ++f)\n  {\n    tensors_[f] = std::vector<Dyadic3DTensor>(fieldSize_);\n    auto vfield = fields[f]->vfield();\n    Tensor temp;\n    for (size_t v = 0; v < fieldSize_; ++v)\n    {\n      vfield->get_value(temp, v);\n      tensors_[f][v] = scirunTensorToEigenTensor(temp);\n      tensors_[f][v].setDescendingRHSOrder();\n    }\n  }\n}\n\nMatrixHandle ComputeTensorUncertaintyAlgorithmImpl::getCovarianceMatrices() const\n{\n  auto m = std::make_shared<DenseMatrix>(21, fieldSize_);\n  for (size_t i = 0; i < fieldSize_; ++i)\n  {\n    m->col(i) = covarianceMatrices_[i].mandel();\n    Eigen::Matrix<double,21,1> recov_m = m->col(i);\n    DyadicTensor<6> recov = DyadicTensor<6>(recov_m);\n  }\n  return m;\n}\n\nvoid ComputeTensorUncertaintyAlgorithmImpl::run(const FieldList& fields)\n{\n  getPoints(fields);\n  verifyData(fields);\n  getTensors(fields);\n  computeMeanTensors();\n  computeCovarianceMatrices();\n}\n\nComputeTensorUncertaintyAlgorithm::ComputeTensorUncertaintyAlgorithm()\n{\n  addOption(Parameters::MeanInvariantMethod, \"Linear Invariant\",\n            \"Linear Invariant|Log-Euclidean|Matrix Average\");\n  addOption(Parameters::MeanOrientationMethod, \"Log-Euclidean\",\n            \"Log-Euclidean|Matrix Average\");\n}\n\nAlgorithmOutput ComputeTensorUncertaintyAlgorithm::run(const AlgorithmInput& input) const\n{\n  auto fields = input.getList<Field>(Variables::InputFields);\n  auto invariantMethod = get(Parameters::MeanInvariantMethod).toOption();\n  auto orientMethod = get(Parameters::MeanOrientationMethod).toOption();\n  auto data = runImpl(fields, invariantMethod, orientMethod);\n\n  AlgorithmOutput output;\n  output[MeanTensorField] = data.get<0>();\n  output[CovarianceMatrix] = data.get<1>();\n  return output;\n}\n\nboost::tuple<FieldHandle, MatrixHandle> ComputeTensorUncertaintyAlgorithm::runImpl(const FieldList& fields, const AlgoOption& invariantMethod, const AlgoOption& orientationOption) const\n{\n  if (fields.empty())\n    THROW_ALGORITHM_INPUT_ERROR(\"No input fields given\");\n\n  auto impl = ComputeTensorUncertaintyAlgorithmImpl();\n  impl.setInvariantMethod(invariantMethod);\n  impl.setOrientationMethod(orientationOption);\n  impl.run(fields);\n\n  return boost::make_tuple(impl.getMeanTensors(), impl.getCovarianceMatrices());\n}\n", "meta": {"hexsha": "b37b5c0780b1eeae5f7d3fcc00a22b1a1005ea44", "size": 15303, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/Core/Algorithms/Math/ComputeTensorUncertaintyAlgorithm.cc", "max_stars_repo_name": "kimjohn1/SCIRun", "max_stars_repo_head_hexsha": "62ae6cb632100371831530c755ef0b133fb5c978", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 92.0, "max_stars_repo_stars_event_min_datetime": "2015-02-09T22:42:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T09:14:50.000Z", "max_issues_repo_path": "src/Core/Algorithms/Math/ComputeTensorUncertaintyAlgorithm.cc", "max_issues_repo_name": "kimjohn1/SCIRun", "max_issues_repo_head_hexsha": "62ae6cb632100371831530c755ef0b133fb5c978", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1618.0, "max_issues_repo_issues_event_min_datetime": "2015-01-05T19:39:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T20:28:45.000Z", "max_forks_repo_path": "src/Core/Algorithms/Math/ComputeTensorUncertaintyAlgorithm.cc", "max_forks_repo_name": "kimjohn1/SCIRun", "max_forks_repo_head_hexsha": "62ae6cb632100371831530c755ef0b133fb5c978", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 64.0, "max_forks_repo_forks_event_min_datetime": "2015-02-20T17:51:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-19T07:08:08.000Z", "avg_line_length": 33.4857768053, "max_line_length": 185, "alphanum_fraction": 0.7147618114, "num_tokens": 4151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.47267477997936863}}
{"text": "#include \"worldengine/images/simple_elevation_image.h\"\n\n#include <boost/log/trivial.hpp>\n\nnamespace WorldEngine\n{\nSimpleElevationImage::SimpleElevationImage(const World& world) :\n    Image(world, false)\n{\n}\nSimpleElevationImage::~SimpleElevationImage() {}\n\nvoid SimpleElevationImage::DrawImage(boost::gil::rgb8_image_t::view_t& target)\n{\n   const ElevationArrayType& e     = world_.GetElevationData();\n   const OceanArrayType&     ocean = world_.GetOceanData();\n\n   float seaLevel    = world_.oceanLevel();\n   bool  hasOcean    = (seaLevel != NAN) && (!ocean.empty());\n   float minElevLand = 10.0f;\n   float maxElevLand = -10.0f;\n   float minElevSea  = 10.0f;\n   float maxElevSea  = -10.0f;\n\n   for (uint32_t y = 0; y < world_.height(); y++)\n   {\n      for (uint32_t x = 0; x < world_.width(); x++)\n      {\n         if (hasOcean && ocean[y][x])\n         {\n            if (minElevSea > e[y][x])\n            {\n               minElevSea = e[y][x];\n            }\n            if (maxElevSea < e[y][x])\n            {\n               maxElevSea = e[y][x];\n            }\n         }\n         else\n         {\n\n            if (minElevLand > e[y][x])\n            {\n               minElevLand = e[y][x];\n            }\n            if (maxElevLand < e[y][x])\n            {\n               maxElevLand = e[y][x];\n            }\n         }\n      }\n   }\n\n   if (hasOcean)\n   {\n      BOOST_LOG_TRIVIAL(debug) << \"minElevSea = \" << minElevSea;\n      BOOST_LOG_TRIVIAL(debug) << \"maxElevSea = \" << maxElevSea;\n   }\n\n   BOOST_LOG_TRIVIAL(debug) << \"minElevLand = \" << minElevLand;\n   BOOST_LOG_TRIVIAL(debug) << \"maxElevLand = \" << maxElevLand;\n\n   float elevDeltaLand = (maxElevLand - minElevLand) / 11.0f;\n   float elevDeltaSea  = (maxElevSea - minElevSea);\n   float elevation;\n\n   for (uint32_t y = 0; y < world_.height(); y++)\n   {\n      for (uint32_t x = 0; x < world_.width(); x++)\n      {\n         if (hasOcean && ocean[y][x])\n         {\n            elevation = ((e[y][x] - minElevSea) / elevDeltaSea);\n         }\n         else\n         {\n            elevation = ((e[y][x] - minElevLand) / elevDeltaLand) + 1;\n         }\n\n         target(x, y) = ElevationColor(elevation, seaLevel);\n      }\n   }\n}\n\nboost::gil::rgb8_pixel_t SimpleElevationImage::ElevationColor(float elevation,\n                                                              float seaLevel)\n{\n   float r, g, b;\n   std::tie(r, g, b) = ElevationColorF(elevation, seaLevel);\n   SatureColorComponent(r);\n   SatureColorComponent(g);\n   SatureColorComponent(b);\n\n   boost::gil::rgb8_pixel_t color(static_cast<uint8_t>(r * 255),\n                                  static_cast<uint8_t>(g * 255),\n                                  static_cast<uint8_t>(b * 255));\n\n   return color;\n}\n\nstd::tuple<float, float, float>\nSimpleElevationImage::ElevationColorF(float elevation, float seaLevel)\n{\n   float colorStep = 1.5f;\n\n   if (seaLevel == NAN)\n   {\n      seaLevel = -1.0f;\n   }\n\n   if (elevation < seaLevel / 2.0f)\n   {\n      elevation /= seaLevel;\n      return std::make_tuple(0.0f, 0.0f, 0.75f + 0.5f * elevation);\n   }\n   if (elevation < seaLevel)\n   {\n      elevation /= seaLevel;\n      return std::make_tuple(0.0f, 2.0f * (elevation - 0.5f), 1.0f);\n   }\n\n   elevation -= seaLevel;\n\n   if (elevation < 1.0f * colorStep)\n   {\n      return std::make_tuple(0.0f, 0.5f + 0.5f * elevation / colorStep, 0.0f);\n   }\n   if (elevation < 1.5f * colorStep)\n   {\n      return std::make_tuple(\n         2.0f * (elevation - 1.0f * colorStep) / colorStep, 1.0f, 0.0f);\n   }\n   if (elevation < 2.0f * colorStep)\n   {\n      return std::make_tuple(\n         1.0f, 1.0f - (elevation - 1.5f * colorStep) / colorStep, 0.0f);\n   }\n   if (elevation < 3.0f * colorStep)\n   {\n      return std::make_tuple(\n         1.0f - 0.5f * (elevation - 2.0f * colorStep) / colorStep,\n         0.5f - 0.25f * (elevation - 2.0f * colorStep) / colorStep,\n         0.0f);\n   }\n   if (elevation < 5.0f * colorStep)\n   {\n      return std::make_tuple(\n         0.5f - 0.125f * (elevation - 3.0f * colorStep) / (2.0f * colorStep),\n         0.25f + 0.125f * (elevation - 3.0f * colorStep) / (2.0f * colorStep),\n         0.375f * (elevation - 3.0f * colorStep) / 2.0f * colorStep);\n   }\n   if (elevation < 8.0f * colorStep)\n   {\n      return std::make_tuple(\n         0.375f + 0.625f * (elevation - 5.0f * colorStep) / (3.0f * colorStep),\n         0.375f + 0.625f * (elevation - 5.0f * colorStep) / (3.0f * colorStep),\n         0.375f + 0.625f * (elevation - 5.0f * colorStep) / (3.0f * colorStep));\n   }\n\n   elevation -= 8.0f * colorStep;\n   while (elevation > 2.0f * colorStep)\n   {\n      elevation -= 2.0f * colorStep;\n   }\n   return std::make_tuple(1.0f, 1.0f - elevation / 4.0f, 1.0f);\n}\n\nvoid SimpleElevationImage::SatureColorComponent(float& component)\n{\n   if (component < 0.0f)\n   {\n      component = 0.0f;\n   }\n   if (component > 1.0f)\n   {\n      component = 1.0f;\n   }\n}\n} // namespace WorldEngine", "meta": {"hexsha": "52cc6054018155763a167ed96197337336812a65", "size": 4900, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "worldengine/source/images/simple_elevation_image.cpp", "max_stars_repo_name": "dpaulat/worldengine-cpp", "max_stars_repo_head_hexsha": "9f7961aaf62db2633fc9d44b6018384812a6704e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-06-09T12:44:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T21:52:10.000Z", "max_issues_repo_path": "worldengine/source/images/simple_elevation_image.cpp", "max_issues_repo_name": "dpaulat/worldengine-cpp", "max_issues_repo_head_hexsha": "9f7961aaf62db2633fc9d44b6018384812a6704e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-06-09T12:49:33.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-17T15:28:37.000Z", "max_forks_repo_path": "worldengine/source/images/simple_elevation_image.cpp", "max_forks_repo_name": "dpaulat/worldengine-cpp", "max_forks_repo_head_hexsha": "9f7961aaf62db2633fc9d44b6018384812a6704e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.2222222222, "max_line_length": 80, "alphanum_fraction": 0.5436734694, "num_tokens": 1627, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149978955811, "lm_q2_score": 0.6261241842048092, "lm_q1q2_score": 0.472670537201346}}
{"text": "/**\n * @file NetTests.cpp\n *\n * @breif High level tests of the Net class\n *\n * @date 12/17/17\n * @author Ben Caine\n */\n\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE NetTests\n\n#include <boost/test/unit_test.hpp>\n#include <chrono>\n#include \"Net.h\"\n\n\nBOOST_AUTO_TEST_CASE(test_relu) {\n    std::cout << \"Testing Relu\" << std::endl;\n    nn::Relu<float, 2> relu;\n\n    int dim1 = 1;\n    int dim2 = 10;\n    Eigen::Tensor<float, 2> input(dim1, dim2);\n    input.setRandom();\n    input = input * input.constant(-1.0f);\n\n    Eigen::Tensor<float, 2> result = relu.forward(input);\n    for (unsigned int ii = 0; ii < dim1; ++ii) {\n        for (unsigned int jj = 0; jj < dim2; ++jj) {\n            BOOST_REQUIRE_MESSAGE(result(ii, jj) == 0, \"Element in result does not equal zero\");\n        }\n    }\n\n    // Make a few elements positive\n    input(0, 5) = 10.0;\n    input(0, 3) = 150.0;\n\n    result = relu.forward(input);\n    for (unsigned int ii = 0; ii < dim1; ++ii) {\n        for (unsigned int jj = 0; jj < dim2; ++jj) {\n            BOOST_REQUIRE_MESSAGE(result(ii, jj) >= 0, \"Element in result does is negative\");\n        }\n    }\n}\n\nBOOST_AUTO_TEST_CASE(test_relu_back) {\n    std::cout << \"Testing Relu backwards\" << std::endl;\n    nn::Relu<float, 2> relu;\n\n    int dim1 = 1;\n    int dim2 = 10;\n    Eigen::Tensor<float, 2> input(dim1, dim2);\n    input.setValues({{-10, -7, -5, -3, 0, 1, 3, 5, 7, 10}});\n\n    Eigen::Tensor<float, 2> accumulatedGrad(dim1, dim2);\n    accumulatedGrad.setValues({{1, -4, 7, -10, 13, -16, 19, -22, 25, -28}});\n\n    Eigen::Tensor<float, 2> forwardResult = relu.forward(input);\n    Eigen::Tensor<float, 2> backwardResult = relu.backward(accumulatedGrad);\n\n    std::vector<float> expectedOutput({0, 0, 0, 0, 0, -16, 19, -22, 25, -28});\n    for (unsigned ii = 0; ii < dim2; ++ii) {\n        BOOST_REQUIRE_MESSAGE(backwardResult(0, ii) == expectedOutput[ii], \"Output of relu.backward did not match\");\n    }\n}\n\nBOOST_AUTO_TEST_CASE(test_softmax) {\n    std::cout << \"Testing Softmax\" << std::endl;\n    nn::Softmax<float, 2> softmax;\n\n    int inputBatchSize = 2;\n    Eigen::Tensor<float, 2> input(inputBatchSize, 2);\n    input.setValues({{5, 5},\n                     {-100, 100}});\n\n    Eigen::Tensor<float, 2> result = softmax.forward(input);\n\n    BOOST_REQUIRE_MESSAGE(result(0, 0) == 0.5, \"Result(0, 0) did not match\");\n    BOOST_REQUIRE_MESSAGE(result(0, 1) == 0.5, \"Result(0, 1) did not match\");\n    BOOST_REQUIRE_MESSAGE(result(1, 0) == 0, \"Result (1, 0) did not match\");\n    BOOST_REQUIRE_MESSAGE(result(1, 1) == 1, \"Result (1, 1) did not match\");\n\n\n    inputBatchSize = 1;\n    int inputSize = 100;\n    Eigen::Tensor<float, 2> input2(inputBatchSize, inputSize);\n    input2.setRandom();\n\n    Eigen::Tensor<float, 2> result2 = softmax.forward(input2);\n\n    float sum = 0;\n    for (unsigned int ii = 0; ii < inputSize; ++ii) {\n        sum += result2(0, ii);\n    }\n\n    BOOST_REQUIRE_CLOSE(sum, 1.0, 1e-3);\n}\n\nBOOST_AUTO_TEST_CASE(test_softmax_back) {\n    std::cout << \"Testing Softmax backwards\" << std::endl;\n    nn::Softmax<float, 2> softmax;\n\n    int inputBatchSize = 2;\n    Eigen::Tensor<float, 2> input(inputBatchSize, 2);\n    input.setValues({{5, 7},\n                     {-100, 100}});\n\n    Eigen::Tensor<float, 2> result = softmax.forward(input);\n\n    Eigen::Tensor<float, 2> labels(inputBatchSize, 2);\n    labels.setValues({{0, 1},\n                      {0, 1}});\n\n    // Already has state from forward\n    Eigen::Tensor<float, 2> backwardsResult = softmax.backward(labels);\n    // TODO: Add actual tests. Test against TF/Pytorch?\n}\n\nBOOST_AUTO_TEST_CASE(test_net1) {\n    std::cout << \"Testing net creation\" << std::endl;\n    nn::Net<float> net;\n\n    // TODO: output of previous should match input of next. Can we auto-infer in some nice way?\n    int batchSize = 1;\n    net.add(new nn::Dense<float, 2>(batchSize, 28 * 28, 100, true))\n       .add(new nn::Dense<float, 2>(batchSize, 100, 100, true))\n       .add(new nn::Dense<float, 2>(batchSize, 100, 10, true));\n\n    Eigen::Tensor<float, 2> input(batchSize, 28 * 28);\n    input.setRandom();\n    Eigen::Tensor<float, 2> result = net.forward<2, 2>(input);\n    BOOST_REQUIRE_MESSAGE(result.dimensions()[0] == batchSize, \"Result dimension 0 did not match batch size\");\n    BOOST_REQUIRE_MESSAGE(result.dimensions()[1] == 10, \"Result dimension 1 did not match last dense layer\");\n}\n\nBOOST_AUTO_TEST_CASE(test_net2) {\n    std::cout << \"Testing net creation\" << std::endl;\n    nn::Net<> net;\n\n    int batchSize = 64;\n    int inputX = 28;\n    int inputY = 28;\n    int numClasses = 10;\n    bool useBias = true;\n    // Basic MLP for testing MNSIT\n    net.add(new nn::Dense<>(batchSize, inputX * inputY, 100, useBias))\n       .add(new nn::Relu<>())\n       .add(new nn::Dense<>(batchSize, 100, 100, useBias))\n       .add(new nn::Relu<>())\n       .add(new nn::Dense<>(batchSize, 100, 10, useBias))\n       .add(new nn::Relu<>())\n       .add(new nn::Softmax<>());\n\n    Eigen::Tensor<float, 2> input(batchSize, 28 * 28);\n    input.setRandom();\n\n    auto startTime = std::chrono::system_clock::now();\n    Eigen::Tensor<float, 2> result = net.forward<2, 2>(input);\n    auto endTime = std::chrono::system_clock::now();\n\n    std::chrono::duration<double> duration = endTime - startTime;\n    std::cout << \"A single forward of size: [\" << batchSize << \", 28, 28] took: \" << duration.count() << \"s\"\n              << std::endl;\n\n    Eigen::Tensor<float, 2> fakeLabels(batchSize, numClasses);\n    fakeLabels.setZero();\n    fakeLabels.setValues({{0, 0, 0, 1, 0, 0, 0, 0, 0, 0},\n                          {0, 1, 0, 0, 0, 0, 0, 0, 0, 1}});\n\n    net.backward<2>(fakeLabels);\n}\n\nBOOST_AUTO_TEST_CASE(test_regression) {\n    std::cout << \"Testing linear regression\" << std::endl;\n    nn::Net<> net;\n\n    net.add(new nn::Dense<float, 2>(1, 1, 10, true));\n    net.add(new nn::Relu<float, 2>());\n    net.add(new nn::Dense<float, 2>(1, 10, 1, true));\n\n    Eigen::Tensor<float, 2> input(1, 1);\n    input.setRandom();\n\n    auto startTime = std::chrono::system_clock::now();\n    auto result = net.forward<2, 2>(input);\n    auto endTime = std::chrono::system_clock::now();\n\n    std::chrono::duration<double> duration = endTime - startTime;\n    std::cout << \"Regression took: \" << duration.count() << \"s\" << std::endl;\n}", "meta": {"hexsha": "c063771ce8911c882751430e9c66d4d31f2fa587", "size": 6256, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/NetTests.cpp", "max_stars_repo_name": "bcaine/nn_cpp", "max_stars_repo_head_hexsha": "447ffa49f591e1c1c6dad0a1ab8b4f72411385b3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2018-05-17T03:52:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-06T14:32:49.000Z", "max_issues_repo_path": "tests/NetTests.cpp", "max_issues_repo_name": "bcaine/nn_cpp", "max_issues_repo_head_hexsha": "447ffa49f591e1c1c6dad0a1ab8b4f72411385b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-08-10T09:32:21.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-10T09:32:21.000Z", "max_forks_repo_path": "tests/NetTests.cpp", "max_forks_repo_name": "bcaine/nn_cpp", "max_forks_repo_head_hexsha": "447ffa49f591e1c1c6dad0a1ab8b4f72411385b3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2018-05-17T04:06:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-25T09:42:35.000Z", "avg_line_length": 32.5833333333, "max_line_length": 116, "alphanum_fraction": 0.6066176471, "num_tokens": 1944, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.4726705355631468}}
{"text": "// Copyright (C) 2015  Davis E. King (davis@dlib.net)\r\n// License: Boost Software License   See LICENSE.txt for the full license.\r\n\r\n\r\n#include <dlib/matrix.h>\r\n#include <sstream>\r\n#include <string>\r\n#include <cstdlib>\r\n#include <ctime>\r\n#include <vector>\r\n#include \"../dnn/tensor_tools.h\"\r\n\r\n#include \"tester.h\"\r\n\r\n// We only do these tests if CUDA is available to test in the first place.\r\n#ifdef DLIB_USE_CUDA\r\n\r\nnamespace  \r\n{\r\n\r\n    using namespace test;\r\n    using namespace dlib;\r\n    using namespace std;\r\n\r\n    logger dlog(\"test.cublas\");\r\n\r\n\r\n    void test_inv()\r\n    {\r\n        tt::tensor_rand rnd;\r\n        dlib::tt::inv tinv;\r\n        dlib::cuda::inv cinv;\r\n        resizable_tensor minv1, minv2;\r\n        for (int n = 1; n < 20; ++n)\r\n        {\r\n            print_spinner();\r\n            resizable_tensor m(n,n);\r\n            rnd.fill_uniform(m);\r\n\r\n            tinv(m, minv1);\r\n            cinv(m, minv2);\r\n            matrix<float> mref = inv(mat(m));\r\n            DLIB_TEST_MSG(mean(abs(mref-mat(minv1)))/mean(abs(mref)) < 1e-5, mean(abs(mref-mat(minv1)))/mean(abs(mref)) <<\"  n: \" << n);\r\n            DLIB_TEST_MSG(mean(abs(mref-mat(minv2)))/mean(abs(mref)) < 1e-5, mean(abs(mref-mat(minv2)))/mean(abs(mref)) <<\"  n: \" << n);\r\n        }\r\n    }\r\n\r\n\r\n    class cublas_tester : public tester\r\n    {\r\n    public:\r\n        cublas_tester (\r\n        ) :\r\n            tester (\"test_cublas\",\r\n                    \"Runs tests on the cuBLAS bindings.\")\r\n        {}\r\n\r\n        void perform_test (\r\n        )\r\n        {\r\n            test_inv();\r\n            {\r\n                resizable_tensor a(4,3), b(3,4), c(3,3);\r\n\r\n                c = 1;\r\n                a = matrix_cast<float>(gaussian_randm(a.num_samples(),a.size()/a.num_samples()));\r\n                b = matrix_cast<float>(gaussian_randm(b.num_samples(),b.size()/b.num_samples()));\r\n\r\n                matrix<float> truth = 2*mat(c)+trans(mat(a))*trans(mat(b));\r\n\r\n                a.async_copy_to_device(); b.async_copy_to_device(); c.async_copy_to_device();\r\n                cuda::gemm(2, c, 1, a, true, b, true);\r\n                DLIB_TEST(max(abs(truth-mat(c))) < 1e-6);\r\n            }\r\n            {\r\n                resizable_tensor a(4,3), b(4,3), c(3,3);\r\n\r\n                c = 1;\r\n                a = matrix_cast<float>(gaussian_randm(a.num_samples(),a.size()/a.num_samples()));\r\n                b = matrix_cast<float>(gaussian_randm(b.num_samples(),b.size()/b.num_samples()));\r\n\r\n                matrix<float> truth = 2*mat(c)+trans(mat(a))*mat(b);\r\n\r\n                a.async_copy_to_device(); b.async_copy_to_device(); c.async_copy_to_device();\r\n                cuda::gemm(2, c, 1, a, true, b, false);\r\n                DLIB_TEST(max(abs(truth-mat(c))) < 1e-6);\r\n            }\r\n            {\r\n                resizable_tensor a(3,4), b(3,4), c(3,3);\r\n\r\n                c = 1;\r\n                a = matrix_cast<float>(gaussian_randm(a.num_samples(),a.size()/a.num_samples()));\r\n                b = matrix_cast<float>(gaussian_randm(b.num_samples(),b.size()/b.num_samples()));\r\n\r\n                matrix<float> truth = 2*mat(c)+mat(a)*trans(mat(b));\r\n\r\n                a.async_copy_to_device(); b.async_copy_to_device(); c.async_copy_to_device();\r\n                cuda::gemm(2, c, 1, a, false, b, true);\r\n                DLIB_TEST(max(abs(truth-mat(c))) < 1e-6);\r\n            }\r\n            {\r\n                resizable_tensor a(3,4), b(3,4), c(3,3);\r\n\r\n                c = 1;\r\n                a = matrix_cast<float>(gaussian_randm(a.num_samples(),a.size()/a.num_samples()));\r\n                b = matrix_cast<float>(gaussian_randm(b.num_samples(),b.size()/b.num_samples()));\r\n\r\n                matrix<float> truth = mat(c)+mat(a)*trans(mat(b));\r\n\r\n                a.async_copy_to_device(); b.async_copy_to_device(); c.async_copy_to_device();\r\n                cuda::gemm(1, c, 1, a, false, b, true);\r\n                DLIB_TEST(max(abs(truth-mat(c))) < 1e-6);\r\n            }\r\n            {\r\n                resizable_tensor a(3,4), b(4,3), c(3,3);\r\n\r\n                c = 1;\r\n                a = matrix_cast<float>(gaussian_randm(a.num_samples(),a.size()/a.num_samples()));\r\n                b = matrix_cast<float>(gaussian_randm(b.num_samples(),b.size()/b.num_samples()));\r\n\r\n                matrix<float> truth = 2*mat(c)+mat(a)*mat(b);\r\n\r\n                a.async_copy_to_device(); b.async_copy_to_device(); c.async_copy_to_device();\r\n                cuda::gemm(2, c, 1, a, false, b, false);\r\n                DLIB_TEST(max(abs(truth-mat(c))) < 1e-6);\r\n            }\r\n            {\r\n                resizable_tensor a(3,4), b(4,3), c(3,3);\r\n\r\n                c = std::numeric_limits<float>::infinity();\r\n                a = matrix_cast<float>(gaussian_randm(a.num_samples(),a.size()/a.num_samples()));\r\n                b = matrix_cast<float>(gaussian_randm(b.num_samples(),b.size()/b.num_samples()));\r\n                a.async_copy_to_device(); b.async_copy_to_device(); c.async_copy_to_device();\r\n\r\n                matrix<float> truth = mat(a)*mat(b);\r\n\r\n                cuda::gemm(0, c, 1, a, false, b, false);\r\n                DLIB_TEST(max(abs(truth-mat(c))) < 1e-6);\r\n            }\r\n            {\r\n                resizable_tensor a(3,4), b(4,4), c(3,4);\r\n\r\n                c = 1;\r\n                a = matrix_cast<float>(gaussian_randm(a.num_samples(),a.size()/a.num_samples()));\r\n                b = matrix_cast<float>(gaussian_randm(b.num_samples(),b.size()/b.num_samples()));\r\n\r\n                matrix<float> truth = 2*mat(c)+mat(a)*mat(b);\r\n\r\n                cuda::gemm(2, c, 1, a, false, b, false);\r\n                DLIB_TEST(get_rect(truth) == get_rect(mat(c)));\r\n                DLIB_TEST(max(abs(truth-mat(c))) < 1e-6);\r\n            }\r\n            {\r\n                resizable_tensor a(4,3), b(4,4), c(3,4);\r\n\r\n                c = 1;\r\n                a = matrix_cast<float>(gaussian_randm(a.num_samples(),a.size()/a.num_samples()));\r\n                b = matrix_cast<float>(gaussian_randm(b.num_samples(),b.size()/b.num_samples()));\r\n\r\n                matrix<float> truth = 2*mat(c)+trans(mat(a))*mat(b);\r\n\r\n                cuda::gemm(2, c, 1, a, true, b, false);\r\n                DLIB_TEST(get_rect(truth) == get_rect(mat(c)));\r\n                DLIB_TEST(max(abs(truth-mat(c))) < 1e-6);\r\n            }\r\n            {\r\n                resizable_tensor a(4,3), b(4,5), c(3,5);\r\n\r\n                c = 1;\r\n                a = matrix_cast<float>(gaussian_randm(a.num_samples(),a.size()/a.num_samples()));\r\n                b = matrix_cast<float>(gaussian_randm(b.num_samples(),b.size()/b.num_samples()));\r\n\r\n                matrix<float> truth = 2*mat(c)+trans(mat(a))*mat(b);\r\n\r\n                cuda::gemm(2, c, 1, a, true, b, false);\r\n                DLIB_TEST(get_rect(truth) == get_rect(mat(c)));\r\n                DLIB_TEST(max(abs(truth-mat(c))) < 1e-6);\r\n            }\r\n            {\r\n                resizable_tensor a(4,3), b(4,5), c(3,5);\r\n\r\n                c = std::numeric_limits<float>::infinity();\r\n                a = matrix_cast<float>(gaussian_randm(a.num_samples(),a.size()/a.num_samples()));\r\n                b = matrix_cast<float>(gaussian_randm(b.num_samples(),b.size()/b.num_samples()));\r\n\r\n                matrix<float> truth = trans(mat(a))*mat(b);\r\n\r\n                cuda::gemm(0, c, 1, a, true, b, false);\r\n                DLIB_TEST(get_rect(truth) == get_rect(mat(c)));\r\n                DLIB_TEST(max(abs(truth-mat(c))) < 1e-6);\r\n            }\r\n        }\r\n    } a;\r\n\r\n}\r\n\r\n#endif // DLIB_USE_CUDA\r\n\r\n", "meta": {"hexsha": "d6739aa4da6b16e41cdd56095f4e0b2f17a55423", "size": 7498, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dlib/test/cublas.cpp", "max_stars_repo_name": "ckproc/dlib-19.7", "max_stars_repo_head_hexsha": "0ca40f5e85de2436e557bee9a805d3987d2d9507", "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": "dlib/test/cublas.cpp", "max_issues_repo_name": "ckproc/dlib-19.7", "max_issues_repo_head_hexsha": "0ca40f5e85de2436e557bee9a805d3987d2d9507", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2018-02-27T15:44:25.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-28T01:26:03.000Z", "max_forks_repo_path": "dlib/test/cublas.cpp", "max_forks_repo_name": "ckproc/dlib-19.7", "max_forks_repo_head_hexsha": "0ca40f5e85de2436e557bee9a805d3987d2d9507", "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.6783919598, "max_line_length": 137, "alphanum_fraction": 0.493464924, "num_tokens": 1937, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.4726705355631468}}
{"text": "/*********************************************************************\n * Software License Agreement (BSD License)\n *\n *  Copyright (c) 2019, University of Stuttgart\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions\n *  are met:\n *\n *   * Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *   * Redistributions in binary form must reproduce the above\n *     copyright notice, this list of conditions and the following\n *     disclaimer in the documentation and/or other materials provided\n *     with the distribution.\n *   * Neither the name of the University of Stuttgart nor the names\n *     of its contributors may be used to endorse or promote products\n *     derived from this software without specific prior written\n *     permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n *  \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n *  POSSIBILITY OF SUCH DAMAGE.\n *********************************************************************/\n\n/* Author: Andreas Orthey */\n\n#include <ompl/base/spaces/SE3StateSpace.h>\n#include <ompl/base/spaces/SO3StateSpace.h>\n#include <ompl/base/spaces/RealVectorStateSpace.h>\n#include <ompl/base/SpaceInformation.h>\n#include <ompl/base/StateSpace.h>\n#include <ompl/multilevel/planners/qrrt/QRRT.h>\n#include <iostream>\n#include <boost/math/constants/constants.hpp>\n\nnamespace ob = ompl::base;\nnamespace og = ompl::geometric;\nnamespace om = ompl::multilevel;\n\nusing SE3State = ob::ScopedState<ob::SE3StateSpace>;\nusing SO3State = ob::ScopedState<ob::SO3StateSpace>;\nusing R3State = ob::ScopedState<ob::RealVectorStateSpace>;\nconst double pi = boost::math::constants::pi<double>();\n\n// Path Planning on fiber bundle SE3 \\rightarrow R3\n\nbool isInCollision(double *val)\n{\n    const double &x = val[0] - 0.5;\n    const double &y = val[1] - 0.5;\n    const double &z = val[2] - 0.5;\n    double d = sqrt(x * x + y * y + z * z);\n    return (d > 0.2);\n}\n\nbool isStateValid_SE3(const ob::State *state)\n{\n    static auto SO3(std::make_shared<ob::SO3StateSpace>());\n    static SO3State SO3id(SO3);\n    SO3id->setIdentity();\n\n    const auto *SE3state = state->as<ob::SE3StateSpace::StateType>();\n    const auto *R3state = SE3state->as<ob::RealVectorStateSpace::StateType>(0);\n    const ob::State *SO3state = SE3state->as<ob::SO3StateSpace::StateType>(1);\n    const ob::State *SO3stateIdentity = SO3id->as<ob::SO3StateSpace::StateType>();\n\n    double d = SO3->distance(SO3state, SO3stateIdentity);\n    return isInCollision(R3state->values) && (d < pi / 4.0);\n}\n\nbool isStateValid_R3(const ob::State *state)\n{\n    const auto *R3 = state->as<ob::RealVectorStateSpace::StateType>();\n    return isInCollision(R3->values);\n}\n\nint main()\n{\n    //############################################################################\n    // Step 1: Setup planning problem using several quotient-spaces\n    //############################################################################\n    // Setup SE3\n    auto SE3(std::make_shared<ob::SE3StateSpace>());\n    ob::RealVectorBounds bounds(3);\n    bounds.setLow(0);\n    bounds.setHigh(1);\n    SE3->setBounds(bounds);\n    ob::SpaceInformationPtr si_SE3(std::make_shared<ob::SpaceInformation>(SE3));\n    si_SE3->setStateValidityChecker(isStateValid_SE3);\n\n    // Setup Quotient-Space R2\n    auto R3(std::make_shared<ob::RealVectorStateSpace>(3));\n    R3->setBounds(0, 1);\n    ob::SpaceInformationPtr si_R3(std::make_shared<ob::SpaceInformation>(R3));\n    si_R3->setStateValidityChecker(isStateValid_R3);\n\n    // Create vector of spaceinformationptr (last one is original cspace)\n    std::vector<ob::SpaceInformationPtr> si_vec;\n    si_vec.push_back(si_R3);\n    si_vec.push_back(si_SE3);\n\n    // Define Planning Problem\n    SE3State start_SE3(SE3);\n    SE3State goal_SE3(SE3);\n    start_SE3->setXYZ(0, 0, 0);\n    start_SE3->rotation().setIdentity();\n    goal_SE3->setXYZ(1, 1, 1);\n    goal_SE3->rotation().setIdentity();\n\n    ob::ProblemDefinitionPtr pdef = std::make_shared<ob::ProblemDefinition>(si_SE3);\n    pdef->setStartAndGoalStates(start_SE3, goal_SE3);\n\n    //############################################################################\n    // Step 2: Do path planning as usual but with a sequence of\n    // spaceinformationptr\n    //############################################################################\n    auto planner = std::make_shared<ompl::multilevel::QRRT>(si_vec);\n\n    // Planner can be used as any other OMPL algorithm\n    planner->setProblemDefinition(pdef);\n    planner->setup();\n\n    ob::PlannerStatus solved = planner->ob::Planner::solve(1.0);\n\n    if (solved)\n    {\n        std::cout << std::string(80, '-') << std::endl;\n        std::cout << \"Bundle-Space Path (SE3):\" << std::endl;\n        std::cout << std::string(80, '-') << std::endl;\n        pdef->getSolutionPath()->print(std::cout);\n\n        std::cout << std::string(80, '-') << std::endl;\n        std::cout << \"Base-Space Path (R3)   :\" << std::endl;\n        std::cout << std::string(80, '-') << std::endl;\n        const ob::ProblemDefinitionPtr pdefR3 = planner->getProblemDefinition(0);\n        pdefR3->getSolutionPath()->print(std::cout);\n    }\n    return 0;\n}\n", "meta": {"hexsha": "1363d7ccbf3f1956864a9070f0a7944b834f91fd", "size": 5981, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "demos/multilevel/MultiLevelPlanningRigidBody3D.cpp", "max_stars_repo_name": "orthez/ompl", "max_stars_repo_head_hexsha": "f8aa02485d27e30b4ecfb364ef3178356d42d94a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-28T07:59:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-28T07:59:11.000Z", "max_issues_repo_path": "demos/multilevel/MultiLevelPlanningRigidBody3D.cpp", "max_issues_repo_name": "orthez/ompl", "max_issues_repo_head_hexsha": "f8aa02485d27e30b4ecfb364ef3178356d42d94a", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/multilevel/MultiLevelPlanningRigidBody3D.cpp", "max_forks_repo_name": "orthez/ompl", "max_forks_repo_head_hexsha": "f8aa02485d27e30b4ecfb364ef3178356d42d94a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-08-13T12:41:36.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-25T22:57:38.000Z", "avg_line_length": 39.6092715232, "max_line_length": 84, "alphanum_fraction": 0.6410299281, "num_tokens": 1516, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.4726705250298093}}
{"text": "#ifndef MUSE_MCL_2D_GRIDMAPS_LASER_CONVEX_HULL_HPP\n#define MUSE_MCL_2D_GRIDMAPS_LASER_CONVEX_HULL_HPP\n\n\n#include <cslibs_plugins_data/types/laserscan.hpp>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n#include <boost/geometry/geometries/register/point.hpp>\n#include <boost/geometry/geometries/adapted/boost_tuple.hpp>\nBOOST_GEOMETRY_REGISTER_BOOST_TUPLE_CS(cs::cartesian)\n\n\nnamespace muse_mcl_2d_gridmaps {\nnamespace utilty {\nnamespace bg = boost::geometry;\n\n\nstruct Point\n{\n    Point(double x = 0, double y = 0, std::size_t index = 0) :\n        x(x),\n        y(y),\n        index(index)\n    {\n    }\n\n    Point(const Eigen::Vector2d &p, const std::size_t index) :\n      x(p(0)),\n      y(p(1)),\n      index(index)\n    {\n    }\n\n    double      x;\n    double      y;\n    std::size_t index;\n} __attribute__ ((aligned (32)));\n\nusing polygon_t = boost::geometry::model::polygon<Point>;\nusing rays_t    = cslibs_plugins_data::types::Laserscan2::rays_t;\nusing ray_t     = cslibs_plugins_data::types::Laserscan2::Ray;\nusing laserscan_t = cslibs_plugins_data::types::Laserscan2;\n\ninline void convexHull(const laserscan_t& scan,\n                       std::vector<std::size_t> &indices)\n{\n    const rays_t rays = scan.getRays();\n    const std::size_t size = rays.size();\n    const double range_min = scan.getLinearMin();\n    const double range_max = scan.getLinearMax();\n    const double angle_min = scan.getAngularMin();\n    const double angle_max = scan.getAngularMax();\n\n\n    auto valid = [range_min, range_max, angle_min, angle_max](const ray_t &r){\n        return r.valid()\n            && r.angle >= angle_min && r.angle <= angle_max\n            && r.range >= range_min && r.range <= range_max;\n    };\n\n    polygon_t scan_poly;\n    polygon_t hull_poly;\n    scan_poly.outer().reserve(size);\n    for(std::size_t i = 0 ; i < size ; ++i) {\n        const auto &r = rays[i];\n        if(valid(r)) {\n            scan_polygon.outer().emplace_back(Point(r.end_point(), i));\n        }\n    }\n    boost::geometry::convex_hull(scan_poly, hull_poly);\n\n    indices.reserve(hull_poly.outer().size());\n    for(const auto &p : hull_poly.outer()) {\n      indices.emplace_back(p.index);\n    }\n}\n}\n\n#endif // MUSE_MCL_2D_GRIDMAPS_LASER_CONVEX_HULL_HPP\n", "meta": {"hexsha": "645af32c271a8a1b856e3fe07d062bbd77d18aeb", "size": 2257, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "muse_mcl_2d_gridmaps/include/muse_mcl_2d_gridmaps/utility/laser_convex_hull.hpp", "max_stars_repo_name": "doge-of-the-day/muse_mcl_2d", "max_stars_repo_head_hexsha": "4cb53120e78780ccc7a7a62d40278fd075d2a54d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-06-01T14:08:29.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-07T02:01:53.000Z", "max_issues_repo_path": "muse_mcl_2d_gridmaps/include/muse_mcl_2d_gridmaps/utility/laser_convex_hull.hpp", "max_issues_repo_name": "cogsys-tuebingen/muse_mcl_2d", "max_issues_repo_head_hexsha": "dc053c61208a6ec740b70cea81aaf3c466c1c3b4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "muse_mcl_2d_gridmaps/include/muse_mcl_2d_gridmaps/utility/laser_convex_hull.hpp", "max_forks_repo_name": "cogsys-tuebingen/muse_mcl_2d", "max_forks_repo_head_hexsha": "dc053c61208a6ec740b70cea81aaf3c466c1c3b4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2019-03-04T01:46:02.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-30T01:58:22.000Z", "avg_line_length": 27.8641975309, "max_line_length": 78, "alphanum_fraction": 0.6606114311, "num_tokens": 603, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.4726705250298093}}
{"text": "//\n// Created by huangkun on 2020/8/11.\n//\n\n#include <Eigen/Eigen>\n#include <opencv2/core/eigen.hpp>\n#include <opencv2/opencv.hpp>\n#include <nanoflann.hpp>\n#include <KDTreeVectorOfVectorsAdaptor.h>\n\n#include <opengv2/sensor/PinholeCamera.hpp>\n#include <opengv2/utility/utility.hpp>\n\nopengv2::PinholeCamera::PinholeCamera(const Eigen::Ref<const Eigen::Vector2d> &size,\n                                      const Eigen::Ref<const Eigen::Matrix3d> &K,\n                                      const Eigen::Ref<const Eigen::VectorXd> &distCoeffs,\n                                      cv::Mat mask) :\n        CameraBase(size, mask), K_(K), invK_(K.inverse()), distCoeffs_(distCoeffs),\n        inverseRadialPoly_(Eigen::VectorXd()) {}\n\ninline Eigen::Vector2d opengv2::PinholeCamera::project(const Eigen::Ref<const Eigen::Vector3d> &Xc) const {\n    if (distCoeffs_.size() == 0) {\n        Eigen::Vector3d p = K_ * Xc;\n        p /= p(2);\n        return p.block<2, 1>(0, 0);\n    } else {\n        // TODO: implement using Eigen\n        std::vector<cv::Point3f> objectPoints(1, cv::Point3f(Xc[0], Xc[1], Xc[2]));\n        cv::Mat tvec = cv::Mat::zeros(3, 1, CV_32F), rvec, distCoeffs, cameraMatrix;\n        cv::Rodrigues(cv::Mat::eye(3, 3, CV_32F), rvec);\n        cv::eigen2cv(distCoeffs_, distCoeffs);\n        cv::eigen2cv(K_, cameraMatrix);\n        std::vector<cv::Point2f> imagePoints;\n        cv::projectPoints(objectPoints, rvec, tvec, cameraMatrix, distCoeffs, imagePoints);\n        return Eigen::Vector2d(imagePoints[0].x, imagePoints[0].y);\n    }\n}\n\ninline Eigen::Vector3d opengv2::PinholeCamera::invProject(const Eigen::Ref<const Eigen::Vector2d> &p) const {\n    Eigen::Vector3d Xc;\n    if (inverseRadialPoly_.size() != 0) {\n        Xc = invK_ * Eigen::Vector3d(p(0), p(1), 1);\n        Xc /= Xc[2];\n\n        Eigen::VectorXd r_coeff(inverseRadialPoly_.size());\n        r_coeff[0] = Xc[0] * Xc[0] + Xc[1] * Xc[1];\n        for (int i = 1; i < inverseRadialPoly_.size(); ++i) {\n            r_coeff[i] = r_coeff[i - 1] * r_coeff[0];\n        }\n        Xc[0] *= 1 + r_coeff.transpose() * inverseRadialPoly_;\n        Xc[1] *= 1 + r_coeff.transpose() * inverseRadialPoly_;\n    } else if (distCoeffs_.size() != 0) {\n        // TODO: implement using Eigen\n        std::vector<cv::Point2f> src, dst;\n        src.emplace_back(p[0], p[1]);\n        cv::Mat cameraMatrix, distCoeffs;\n        cv::eigen2cv(K_, cameraMatrix);\n        cv::eigen2cv(distCoeffs_, distCoeffs);\n        cv::undistortPoints(src, dst, cameraMatrix, distCoeffs);\n        Xc = Eigen::Vector3d(dst[0].x, dst[0].y, 1);\n    } else {\n        Xc = invK_ * Eigen::Vector3d(p(0), p(1), 1);\n    }\n\n    Xc.normalize();\n    return Xc;\n}\n\nEigen::VectorXd\nopengv2::PinholeCamera::inverseRadialDistortion(const Eigen::Ref<const Eigen::Vector4d> &radialDistortion) {\n    const Eigen::Ref<const Eigen::VectorXd> &k = radialDistortion;\n    Eigen::VectorXd b(5);\n\n    double k00 = k[0] * k[0];\n    double k000 = k[0] * k00;\n    double k0000 = k[0] * k000;\n    double k00000 = k[0] * k0000;\n    double k01 = k[0] * k[1];\n    double k001 = k[0] * k01;\n    double k0001 = k[0] * k001;\n    double k11 = k[1] * k[1];\n    double k011 = k[0] * k11;\n    double k02 = k[0] * k[2];\n    double k002 = k[0] * k02;\n    double k12 = k[1] * k[2];\n    double k03 = k[0] * k[3];\n\n    b[0] = -k[0];\n    b[1] = 3 * k00 - k[1];\n    b[2] = -12 * k000 + 8 * k01 - k[2];\n    b[3] = 55 * k0000 - 55 * k001 + 5 * k11 + 10 * k02 - k[3];\n    b[4] = -273 * k00000 + 364 * k0001 - 78 * k011 - 78 * k002 + 12 * k12 + 12 * k03;\n\n    return b;\n}\n\nEigen::Vector2d opengv2::PinholeCamera::undistortPoint(const Eigen::Ref<const Eigen::Vector2d> &p) const {\n    Eigen::Vector3d Xc;\n    if (inverseRadialPoly_.size() != 0) {\n        Xc = invK_ * Eigen::Vector3d(p(0), p(1), 1);\n        Xc /= Xc[2];\n\n        Eigen::VectorXd r_coeff(inverseRadialPoly_.size());\n        r_coeff[0] = Xc[0] * Xc[0] + Xc[1] * Xc[1];\n        for (int i = 1; i < inverseRadialPoly_.size(); ++i) {\n            r_coeff[i] = r_coeff[i - 1] * r_coeff[0];\n        }\n        Xc[0] *= 1 + r_coeff.transpose() * inverseRadialPoly_;\n        Xc[1] *= 1 + r_coeff.transpose() * inverseRadialPoly_;\n    } else if (distCoeffs_.size() != 0) {\n        // TODO: implement using Eigen\n        std::vector<cv::Point2f> src, dst;\n        src.emplace_back(p[0], p[1]);\n        cv::Mat cameraMatrix, distCoeffs;\n        cv::eigen2cv(K_, cameraMatrix);\n        cv::eigen2cv(distCoeffs_, distCoeffs);\n        cv::undistortPoints(src, dst, cameraMatrix, distCoeffs);\n        Xc = Eigen::Vector3d(dst[0].x, dst[0].y, 1);\n    } else {\n        return p;\n    }\n\n    Eigen::Vector3d p_c = K_ * Xc;\n    p_c /= p_c[2];\n    return p_c.block<2, 1>(0, 0);\n}\n\ncv::Mat opengv2::PinholeCamera::undistortImage(cv::Mat src) {\n    if (inverseRadialPoly_.size() != 0) {\n        if (undistortMap_.empty()) {\n            // Initialization\n            int dstRows = std::round(size_[1] * 1.2);\n            int dstCols = std::round(size_[0] * 1.2);\n            int emptyEdge_r = std::round(size_[1] * 0.1);\n            int emptyEdge_c = std::round(size_[0] * 0.1);\n            undistortMap_.assign(dstRows, std::vector(dstCols, std::pair(std::vector<std::pair<int, int>>(),\n                                                                         std::vector<double>())));\n\n            vectorofEigenMatrix<Eigen::Vector2d> correctedSet;\n            correctedSet.reserve(size_[0] * size_[1]);\n            const int step = size_[0]; // width\n            for (int idx = 0; idx < size_[0] * size_[1]; ++idx) { // index of cv::Mat, row major\n                int row = idx / step; // y\n                int col = idx % step; // x\n                correctedSet.push_back(\n                        undistortPoint(Eigen::Vector2d(col, row)) + Eigen::Vector2d(emptyEdge_c, emptyEdge_r));\n            }\n\n            KDTreeVectorOfVectorsAdaptor<vectorofEigenMatrix<Eigen::Vector2d>, double, 2, nanoflann::metric_L2_Simple>\n                    kdTree(2, correctedSet, 10);\n            std::vector<std::pair<size_t, double>> indicesDists;\n            for (int i = 0; i < dstRows; ++i) { // y, height\n                for (int j = 0; j < dstCols; ++j) { // x, width\n                    Eigen::Vector2d p(j, i);\n                    kdTree.index->radiusSearch(p.data(), 2 * 2 /*square pixel unit*/,\n                                               indicesDists, nanoflann::SearchParams(32, 0, false));\n                    for (const auto &pair: indicesDists) {\n                        int idx = pair.first;\n                        double d = pair.second;\n                        int row = idx / step;\n                        int col = idx % step;\n                        if (d < 100 * std::numeric_limits<double>::epsilon()) {\n                            d = 100 * std::numeric_limits<double>::epsilon();\n                        }\n                        undistortMap_[i][j].first.emplace_back(row, col);\n                        undistortMap_[i][j].second.push_back(1 / d);\n                    }\n                }\n            }\n        }\n\n        if (src.type() != CV_8UC3) {\n            throw std::logic_error(\"only support CV_8UC3 for now.\");\n        }\n        cv::Mat dst(undistortMap_.size(), undistortMap_[0].size(), CV_32FC3, cv::Vec3f(0, 0, 0));\n        for (int i = 0; i < dst.rows; ++i) {\n            for (int j = 0; j < dst.cols; ++j) {\n                int len = undistortMap_[i][j].first.size();\n                double w_sum = 0;\n                for (int k = 0; k < len; ++k) {\n                    int row = undistortMap_[i][j].first[k].first;\n                    int col = undistortMap_[i][j].first[k].second;\n                    double w = undistortMap_[i][j].second[k];\n                    // convert to float, since opencv didn't do that(uchar * double, return uchar).\n                    cv::Vec3f temp = src.at<cv::Vec3b>(row, col);\n                    dst.at<cv::Vec3f>(i, j) += w * temp;\n                    w_sum += w;\n                }\n                if (len != 0) {\n                    dst.at<cv::Vec3f>(i, j) /= w_sum;\n                }\n            }\n        }\n\n        cv::normalize(dst, dst, 0, 255, cv::NORM_MINMAX, CV_8UC3);\n        return dst;\n    } else if (distCoeffs_.size() != 0) {\n        if (map1_.empty()) {\n            cv::Size imageSize(size_[0], size_[1]);\n            cv::Mat cameraMatrix, distCoeffs;\n            cv::eigen2cv(K_, cameraMatrix);\n            cv::eigen2cv(distCoeffs_, distCoeffs);\n            cv::initUndistortRectifyMap(\n                    cameraMatrix, distCoeffs, cv::Mat(),\n                    getOptimalNewCameraMatrix(cameraMatrix, distCoeffs, imageSize, 1, imageSize, 0),\n                    imageSize, CV_32FC1, map1_, map2_);\n        }\n        cv::Mat dst;\n        remap(src, dst, map1_, map2_, cv::INTER_LINEAR);\n        return dst;\n    } else {\n        return src;\n    }\n}\n\nopengv2::PinholeCamera::PinholeCamera(const cv::FileNode &sensorNode) : CameraBase(sensorNode) {\n    std::vector<double> v;\n    cv::FileNode data;\n\n    data = sensorNode[\"principal_point\"];\n    if (!data.isSeq())\n        throw std::invalid_argument(sensorNode.name() + \": principal_point\");\n    for (cv::FileNodeIterator dataItr = data.begin(); dataItr != data.end(); dataItr++) {\n        v.push_back(*dataItr);\n    }\n    if (v.size() != 2)\n        throw std::invalid_argument(sensorNode.name() + \": principal_point\");\n    Eigen::Vector2d principal_point(v.data());\n    std::cout << \"principal_point: \" << principal_point.transpose() << std::endl;\n\n    v.clear();\n    data = sensorNode[\"distortion_type\"];\n    if (!data.isString())\n        throw std::invalid_argument(sensorNode.name() + \": distortion_type\");\n    std::string distortion_type = data.string();\n    std::cout << \"distortion_type: \" << distortion_type << std::endl;\n\n    v.clear();\n    data = sensorNode[\"distortion\"];\n    if (!data.isSeq())\n        throw std::invalid_argument(sensorNode.name() + \": distortion\");\n    for (cv::FileNodeIterator dataItr = data.begin(); dataItr != data.end(); dataItr++) {\n        v.push_back(*dataItr);\n    }\n    Eigen::Map<Eigen::VectorXd, Eigen::Unaligned> distortion_tmp(v.data(), v.size());\n    Eigen::VectorXd distortion(distortion_tmp);\n    std::cout << \"distortion: \" << distortion.transpose() << std::endl;\n\n    v.clear();\n    data = sensorNode[\"focal_length\"];\n    if (!data.isSeq())\n        throw std::invalid_argument(sensorNode.name() + \": focal_length\");\n    for (cv::FileNodeIterator dataItr = data.begin(); dataItr != data.end(); dataItr++) {\n        v.push_back(*dataItr);\n    }\n    if (v.size() != 2)\n        throw std::invalid_argument(sensorNode.name() + \": focal_length\");\n    Eigen::Vector2d focal_length(v.data());\n    std::cout << \"focal_length: \" << focal_length.transpose() << std::endl;\n\n    K_ << focal_length[0], 0, principal_point[0], 0, focal_length[1], principal_point[1], 0, 0, 1;\n    invK_ = K_.inverse();\n    if (distortion_type == \"OpenCV\") {\n        distCoeffs_ = distortion;\n        inverseRadialPoly_ = Eigen::VectorXd();\n    } else {\n        distCoeffs_ = Eigen::VectorXd();\n        inverseRadialPoly_ = distortion;\n    }\n}", "meta": {"hexsha": "7062009380ad83bfeb972203adf99dd8426568ff", "size": 11107, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/core/sensor/src/PinholeCamera.cpp", "max_stars_repo_name": "MobilePerceptionLab/EventCameraCalibration", "max_stars_repo_head_hexsha": "debd774ac989674b500caf27641b7ad4e94681e9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2021-08-06T03:21:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T03:40:54.000Z", "max_issues_repo_path": "modules/core/sensor/src/PinholeCamera.cpp", "max_issues_repo_name": "MobilePerceptionLab/MultiCamCalib", "max_issues_repo_head_hexsha": "2f0e94228c2c4aea7f20c26e3e8daa6321ce8022", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-02-25T02:55:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-25T15:18:45.000Z", "max_forks_repo_path": "modules/core/sensor/src/PinholeCamera.cpp", "max_forks_repo_name": "MobilePerceptionLab/MultiCamCalib", "max_forks_repo_head_hexsha": "2f0e94228c2c4aea7f20c26e3e8daa6321ce8022", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2021-08-11T12:29:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-25T03:41:01.000Z", "avg_line_length": 41.137037037, "max_line_length": 118, "alphanum_fraction": 0.5444314396, "num_tokens": 3298, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.4726705250298092}}
{"text": "/* Copyright (C) 2012-2017 IBM Corp.\n * This program is Licensed under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *   http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License. See accompanying LICENSE file.\n */\n#include <cassert>\n#include <string>\n#include <sstream>\n#include <NTL/ZZ.h>\n#include \"NumbTh.h\"\n#include \"FHEContext.h\"\n#include \"debugging.h\"\n\n#include \"gtest/gtest.h\"\n#include \"test_common.h\"\n\nnamespace {\nstruct Parameters {\n    Parameters(long m, long p, long r, std::vector<long> gens, std::vector<long> ords) :\n        m(m), // Cyclotomic index\n              // e.g., m=1024, m=2047\n        p(p), // plaintext base\n              // use p=-1 for the complex field (CKKS)\n        r(r), // lifting\n        gens(gens), // use specified vector of generators\n        ords(ords) // use specified vector of orders\n    {};\n\n    const long m;\n    const long p;\n    const long r;\n    const std::vector<long> gens;\n    const std::vector<long> ords;\n    \n    // Let googletest know how to print the Parameters\n    friend std::ostream& operator<<(std::ostream& os, const Parameters& params) {\n        return os << \"{\"\n            << \"m=\" << params.m << \",\"\n            << \"p=\" << params.p << \",\"\n            << \"r=\" << params.r << \",\"\n            << \"gens=\" << params.gens << \",\"\n            << \"ords=\" << params.ords\n            << \"}\";\n    };\n};\n\nclass GTest_PAlgebra : public ::testing::TestWithParam<Parameters> {\n    protected:\n        GTest_PAlgebra() :\n            m(GetParam().m),\n            p(GetParam().p),\n            r(GetParam().r),\n            gens(GetParam().gens),\n            ords(GetParam().ords),\n            context(m, p, r, gens, ords)\n    {};\n\n        const long m;\n        const long p;\n        const long r;\n        const std::vector<long> gens;\n        const std::vector<long> ords;\n        FHEcontext context;\n\n        static void printPrimeFactors(long m, const FHEcontext& context)\n        {\n            std::vector<long> f;\n            factorize(f,m);\n            std::cout << \"factoring \"<<m<<\" gives [\";\n            for (const auto& factor : f)\n                std::cout << factor << \" \";\n            std::cout << \"]\" << std::endl;\n            context.zMStar.printout();\n            std::cout << std::endl;\n        }\n\n        virtual void SetUp() override {\n            buildModChain(context, 5, 2);\n            if(!helib_test::noPrint) {\n                printPrimeFactors(m, context);\n            }\n        };\n\n        virtual void TearDown() override\n        {\n            cleanupGlobals();\n        }\n};\n\nTEST_P(GTest_PAlgebra, reads_and_writes_contexts_as_strings)\n{\n  std::stringstream s1;\n  writeContextBase(s1, context);\n  s1 << context;\n\n  std::string s2 = s1.str();\n\n  if(!helib_test::noPrint) {\n      std::cout << s2;\n  }\n\n  std::stringstream s3(s2);\n\n  unsigned long m1, p1, r1;\n  std::vector<long> gens, ords;\n  readContextBase(s3, m1, p1, r1, gens, ords);\n\n  FHEcontext c1(m1, p1, r1, gens, ords);\n  s3 >> c1;\n\n  EXPECT_EQ(context, c1);\n};\n\nINSTANTIATE_TEST_SUITE_P(small_parameters, GTest_PAlgebra, ::testing::Values(\n            //FAST\n            Parameters(91, 2, 1, std::vector<long>{}, std::vector<long>{})\n            ));\n\n} // namespace\n", "meta": {"hexsha": "a7fda63ea407d8943aada356150034f71ca64d8f", "size": 3615, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tests/GTest_PAlgebra.cpp", "max_stars_repo_name": "leekt216/HElib", "max_stars_repo_head_hexsha": "d2700ba62d2399213b5293686e715d01ad65e6c0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-04T04:55:29.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-04T04:55:29.000Z", "max_issues_repo_path": "src/tests/GTest_PAlgebra.cpp", "max_issues_repo_name": "PNIDEMOOO/HElib", "max_issues_repo_head_hexsha": "7427ed3709bb9872835324dd0007a97b3ca3baca", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-05-16T09:26:15.000Z", "max_issues_repo_issues_event_max_datetime": "2017-05-16T09:26:15.000Z", "max_forks_repo_path": "src/tests/GTest_PAlgebra.cpp", "max_forks_repo_name": "PNIDEMOOO/HElib", "max_forks_repo_head_hexsha": "7427ed3709bb9872835324dd0007a97b3ca3baca", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-02-01T11:34:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-27T14:49:27.000Z", "avg_line_length": 28.6904761905, "max_line_length": 88, "alphanum_fraction": 0.5690179806, "num_tokens": 927, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.6261241702517975, "lm_q1q2_score": 0.4726705197631404}}
{"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_ACOS_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_ACOS_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 inverse cosine in radian.\n\n\n    @par Header <boost/simd/function/acos.hpp>\n\n    @par Call\n\n    For every parameter of floating type\n\n    @code\n    auto r = acos(x);\n    @endcode\n\n    Returns the arc @c r in the interval\n    \\f$[0, \\pi[\\f$ such that <tt>cos(r) == x</tt>.\n    If @c x is outside \\f$[-1, 1[\\f$ the result is @ref Nan.\n\n    @par Decorators\n\n    - std_           entries provides access to std::acos\n\n    - pedantic_      is accurate on the full \\f$[-1, 1[\\f$ range\n\n    - the regular version (no decorator) is less accurate around for x < 0.9\n      (up to circa 256 ulp), but is faster by a factor 2 than the pedantic version.\n\n    @see acosd, acospi, cos\n\n\n    @par Example:\n\n      @snippet acos.cpp acos\n\n    @par Possible output:\n\n      @snippet acos.txt acos\n\n  **/\n  IEEEValue acos(IEEEValue const & x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/acos.hpp>\n#include <boost/simd/function/simd/acos.hpp>\n\n#endif\n", "meta": {"hexsha": "ca4cd6ac01d4f8a1a54b1cb18f950b4f55d74ade", "size": 1559, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/acos.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/acos.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/acos.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 23.6212121212, "max_line_length": 100, "alphanum_fraction": 0.5824246312, "num_tokens": 383, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.47267051812494115}}
{"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//// Solver\n// Build AIC matrices and solve iteratively the \"body\" and the \"field\"\n// Body module: compute impermeability condition and solve linear system of equations (corresponding to the\n// Linear Potential Equation)\n// Field module: compute through AIC and FD the variables in the field, as well as the field sources (source term in\n// the Full Potential Equation)\n//\n// I/O:\n// - numC: list of numerical parameters (structure)\n// - symY: defines symmetry about Y axis\n// - sRef: reference surface of the full wing\n// - alpha: freestream angle of attack\n// - vInf: freestream velocity vector\n// - Minf: freestream Mach number\n// - bPan: (network of) body panels (structure)\n// - wPan: (network of) wake panels (structure)\n// - fPan: field panels (structure)\n// - sp: sub-panels (structure)\n// - cL: lift coefficient\n// - cD: drag coefficient\n//\n// Output:\n// Outputs:\n// - 0, if function succeeded\n// - 1, if function failed\n\n#include <iostream>\n#include <Eigen/Dense>\n#include \"solver.h\"\n#include \"id_subpanel.h\"\n#include \"build_AIC.h\"\n#include \"solve_body.h\"\n#include \"solve_field.h\"\n#include \"compute_sVars.h\"\n\n#define ANSI_COLOR_RED     \"\\x1b[1;31m\"\n#define ANSI_COLOR_GREEN   \"\\x1b[1;32m\"\n#define ANSI_COLOR_YELLOW  \"\\x1b[1;33m\"\n#define ANSI_COLOR_BLUE    \"\\x1b[1;34m\"\n#define ANSI_COLOR_MAGENTA \"\\x1b[1;35m\"\n#define ANSI_COLOR_CYAN    \"\\x1b[1;36m\"\n#define ANSI_COLOR_WHITE   \"\\e[1;37m\"\n#define ANSI_COLOR_RESET   \"\\x1b[0m\"\n\n#define NDIM 3\n\nusing namespace std;\nusing namespace Eigen;\n\nint solver(Numerical_CST &numC, bool symY, double sRef, double alpha, Vector3d &vInf, double Minf,\n           Network &bPan, Network &wPan, Field &fPan, Subpanel &sp, double &cL, double &cD) {\n\n\n    //// Begin solver\n    cout << ANSI_COLOR_BLUE;\n    cout << \"*********************\" << endl;\n    cout << \"*Beginning solver...*\" << endl;\n    cout << \"*********************\";\n    cout << ANSI_COLOR_RESET << endl;\n\n    //// Initialization\n    // AIC matrices\n    Body_AIC b2bAIC = {}, b2fAIC = {}; // body to body and body to field\n    Field2field_AIC f2fAIC = {}; // field to field\n    Field2body_AIC f2bAIC = {}; // field to field and field to body\n    Subpanel_AIC spAIC = {}; // body to field (sub-panel)\n\n    // Singularities\n    bPan.tau.resize(bPan.nP);\n    bPan.mu.resize(bPan.nP);\n    fPan.sigma = VectorXd::Zero(fPan.nF);\n    // Flow variables // TODO check if initialization is useful\n    fPan.phi = VectorXd::Zero(fPan.nF);\n    fPan.M = VectorXd::Zero(fPan.nF);\n    fPan.U = MatrixX3d::Zero(fPan.nF, NDIM);\n    fPan.rho = VectorXd::Zero(fPan.nF);\n    fPan.dRho = MatrixX3d::Zero(fPan.nF, NDIM);\n    fPan.a = VectorXd::Zero(fPan.nF);\n    // Numerics\n    fPan.epsilon = VectorXd::Zero(fPan.nF);\n\n\n    // Temporary variables\n    int itCnt = 0; // Global iteration counter\n    double deltaSigma0 = 0; // Initial sigma change\n    VectorXd sigmaTmp, deltaSigma; // To store sigma and delta sigma during iteration\n    deltaSigma.resize(fPan.nF);\n    sigmaTmp.resize(fPan.nF);\n    VectorXd RHS; // Right hand side\n    RHS.resize(bPan.nP);\n\n    MatrixX3d vSigma; // Velocity induced by field sources on body\n    vSigma = MatrixXd::Zero(bPan.nP, NDIM);\n\n    //// Identify sub-panels\n    id_subpanel(bPan, fPan, sp, spAIC);\n\n    //// Build AIC matrices\n    build_AIC(symY, bPan, wPan, fPan, b2bAIC, b2fAIC, f2fAIC, f2bAIC, sp, spAIC);\n\n    //// Solver\n    // Field Panel Method\n    if (Minf != 0) {\n        cout << \"|\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af|\" << endl;\n        cout << \"|Compressible computation.|\" << endl;\n        cout << \" \u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af \" << endl << endl;\n        do {\n            // Store new field sources\n            sigmaTmp = fPan.sigma;\n            // Panel prediction and boundary condition\n            solve_body(vInf, RHS, vSigma, bPan, b2bAIC);\n            // Field correction\n            solve_field(Minf, vInf, bPan, fPan, sp, b2fAIC, f2fAIC, spAIC);\n            // Source induced velocity (to recompute B.C.)\n            vSigma.col(0) = f2bAIC.Cu * fPan.sigma;\n            vSigma.col(1) = f2bAIC.Cv * fPan.sigma;\n            vSigma.col(2) = f2bAIC.Cw * fPan.sigma;\n            // Stop criterion\n            for (int i = 0; i < fPan.nF; ++i)\n                deltaSigma(i) = abs(fPan.sigma(i) - sigmaTmp(i));\n            if (!itCnt)\n                deltaSigma0 = deltaSigma.norm();\n            if (isnan(deltaSigma.norm())) {\n                break;\n            }\n            cout << ANSI_COLOR_CYAN;\n            cout << \"Relative source change at iteration \" << itCnt << \": \" << log10(deltaSigma.norm()/deltaSigma0) << endl;\n            cout << \"FPE global residual at iteration \" << itCnt << \": \" << log10(fPan.epsilon.norm());\n            cout << ANSI_COLOR_RESET << endl << endl;\n            itCnt++;\n        } while(log10(deltaSigma.norm()/deltaSigma0) > -numC.RRED);\n        //TODO Consider using true residual (div(U) - sigma -> 0). Currently impossible since accuracy.\n        if (isnan(deltaSigma.norm())) {\n            cout << ANSI_COLOR_RED;\n            cout << \"\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\" << endl;\n            cout << \">> Process diverged at iteration #\" << itCnt + 1 << \"!\" << endl;\n            cout << \"\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\";\n            cout << ANSI_COLOR_RESET << endl << endl;\n        }\n        else {\n            cout << ANSI_COLOR_GREEN;\n            cout << \"\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\u2228\" << endl;\n            cout << \">> Process converged in \" << itCnt << \" iteration(s)!\" << endl;\n            cout << \"\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\u2227\";\n            cout << ANSI_COLOR_RESET << endl << endl;\n        }\n    }\n    // Panel Method\n    else {\n        cout << \"|\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af|\" << endl;\n        cout << \"|Incompressible computation.|\" << endl;\n        cout << \" \u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af\u00af \" << endl << endl;\n        solve_body(vInf, RHS, vSigma, bPan, b2bAIC);\n    }\n\n    // Surface velocity and pressure computation\n    compute_sVars(symY, sRef, alpha, Minf, vInf, vSigma, bPan, cL, cD);\n\n    //// End solver\n    cout << ANSI_COLOR_BLUE;\n    cout << \"********************\" << endl;\n    cout << \"*Solver successful!*\" << endl;\n    cout << \"********************\";\n    cout << ANSI_COLOR_RESET << endl;\n    return 0;\n}", "meta": {"hexsha": "d61c794950707ea5840b689a3f2918c08511b855", "size": 6861, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/solver.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/solver.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/solver.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": 37.0864864865, "max_line_length": 124, "alphanum_fraction": 0.5787786037, "num_tokens": 2164, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.754914975839675, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.47267051812494104}}
{"text": "#pragma once\n\n#include <initializer_list> // std::initializer_list\n#include <map>              // std::map\n#include <sstream>          // std::ostringstream\n\n#include <boost/optional.hpp>\n\n#include \"monomial.hpp\"\n\nnamespace math {\n\ntemplate <typename E, typename N>\nclass Polynomial final {\n  private:\n    // A class invariant is that this map cannot have a zero coefficient in it.\n    // We do this by keeping this private and ensuring the public API maintains this invariant.\n    std::map<Monomial<E, N>, N> terms;\n\n  public:\n    using value_type = typename decltype(terms)::value_type;\n\n    // In a map, the elements are ordered from smallest to largest.\n    // However, when iterating over a polynomial, we want to go from largest to smallest.\n    using iterator = typename decltype(terms)::reverse_iterator;\n    using const_iterator = typename decltype(terms)::const_reverse_iterator;\n\n    using reverse_iterator = typename decltype(terms)::iterator;\n    using const_reverse_iterator = typename decltype(terms)::const_iterator;\n\n    explicit Polynomial(const std::initializer_list<value_type>& init)\n        : terms{init} {}\n\n    iterator begin() {\n        return std::rbegin(terms);\n    }\n\n    iterator end() {\n        return std::rend(terms);\n    }\n\n    const_iterator begin() const {\n        return std::rbegin(terms);\n    }\n\n    const_iterator end() const {\n        return std::rend(terms);\n    }\n\n    reverse_iterator rbegin() {\n        return std::begin(terms);\n    }\n\n    reverse_iterator rend() {\n        return std::end(terms);\n    }\n\n    const_reverse_iterator rbegin() const {\n        return std::begin(terms);\n    }\n\n    const_reverse_iterator rend() const {\n        return std::end(terms);\n    }\n\n    boost::optional<std::pair<Monomial<E, N>, N>> leading_term() const {\n        const auto loc = begin();\n        if (loc == end()) {\n            return boost::none;\n        } else {\n            return std::make_pair(loc->first, loc->second);\n        }\n    }\n\n    void add(const Polynomial<E, N>& other) {\n        for (const auto& kv : other) {\n            add(kv.second, kv.first);\n        }\n    }\n\n    void sub(const Polynomial<E, N>& other) {\n        for (const auto& kv : other) {\n            sub(kv.second, kv.first);\n        }\n    }\n\n    void add(const Monomial<E, N>& mono, const N coeff = 1) {\n\n        const auto it = terms.find(mono);\n\n        if (it == std::end(terms)) {\n            // mono not in the map\n            if (coeff != 0) {\n                terms.emplace(mono, coeff);\n            }\n        } else {\n            // mono in the map\n\n            const auto sum = it->second + coeff;\n            if (sum == 0) {\n                terms.erase(it);\n            } else {\n                it->second = sum;\n            }\n        }\n    }\n\n    void sub(const Monomial<E, N>& mono, const N coeff = 1) {\n\n        const auto it = terms.find(mono);\n\n        if (it == std::end(terms)) {\n            // mono not in the map\n            if (coeff != 0) {\n                terms.emplace(mono, -coeff);\n            }\n        } else {\n            // mono in the map\n\n            const auto diff = it->second - coeff;\n            if (diff == 0) {\n                terms.erase(it);\n            } else {\n                it->second = diff;\n            }\n        }\n    }\n\n    void scale(const N scale) {\n\n        if (scale == 0) {\n            terms.clear();\n        } else {\n            for (auto& kv : terms) {\n                kv.second *= scale;\n            }\n        }\n    }\n\n    bool is_zero() const {\n        return terms.empty();\n    }\n\n    size_t size() const {\n        return terms.size();\n    }\n\n    N coeff(const Monomial<E, N>& mono) const {\n\n        const auto it = terms.find(mono);\n\n        if (it == std::end(terms)) {\n            // default to 0 for things we can't find\n            return 0;\n        } else {\n            return it->second;\n        }\n    }\n\n    friend bool operator==(const Polynomial<E, N>& lhs, const Polynomial<E, N>& rhs) {\n        return lhs.terms == rhs.terms;\n    }\n\n    friend bool operator<(const Polynomial<E, N>& lhs, const Polynomial<E, N>& rhs) {\n        return lhs.terms < rhs.terms;\n    }\n\n    friend std::ostream& operator<<(std::ostream& os, const Polynomial<E, N>& poly) {\n\n        // the sum of no elements is 0\n        if (poly.is_zero()) {\n            return os << '0';\n        }\n\n        // Set to false once we add the first coefficient\n        bool front = true;\n\n        for (const auto& kv : poly) {\n\n            const auto& monom = kv.first;\n            const auto coeff = kv.second;\n\n            // add a positive sign if it is positive and not at the front\n            if ((coeff > 0) && !front) {\n                os << '+';\n            }\n\n            if (coeff == 1) {\n                os << monom;\n            } else if (coeff == -1) {\n                os << '-' << monom;\n            } else if (coeff != 0) {\n                os << coeff;\n                if (!monom.is_one()) {\n                    os << '*' << monom;\n                }\n            } else {\n                std::ostringstream err{};\n                err << monom << \" has zero coefficient in Polynomial\";\n                throw std::runtime_error(err.str());\n            }\n\n            front = false;\n        }\n\n        return os;\n    }\n};\n}\n", "meta": {"hexsha": "aa5fc5f1c4aa457e5669ef476d257925368fd8b9", "size": 5278, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/backend/headers/math/polynomial.hpp", "max_stars_repo_name": "wadymwadim/normandeau", "max_stars_repo_head_hexsha": "2995a3293b22df269b88c3486e4f4009a1a5d76f", "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": "src/backend/headers/math/polynomial.hpp", "max_issues_repo_name": "wadymwadim/normandeau", "max_issues_repo_head_hexsha": "2995a3293b22df269b88c3486e4f4009a1a5d76f", "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": "src/backend/headers/math/polynomial.hpp", "max_forks_repo_name": "wadymwadim/normandeau", "max_forks_repo_head_hexsha": "2995a3293b22df269b88c3486e4f4009a1a5d76f", "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": 25.1333333333, "max_line_length": 95, "alphanum_fraction": 0.5030314513, "num_tokens": 1216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432182679956, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.4726658293656121}}
{"text": "/********************************************************/\n/*                Laurent H\u00e9bert-Dufresne               */\n/* Age of edges or nodes by OD of an undirected network */\n/* \t\t\t     based on arXiv:1510.08542              */\n/*                   Santa Fe Institute                 */\n/********************************************************/\n#include <iostream>\n#include <cmath>\n#include <fstream>\n#include <string>\n#include <cstdlib>\n#include <vector>\n#include <sstream>\n#include <iomanip>\n#include <algorithm>\n#include <stdio.h>\n#include <time.h>\n#include <set>\n//#include <boost/filesystem/operations.hpp>\n//#include <boost/filesystem/fstream.hpp>\n//#include <boost/filesystem/path.hpp>\nusing namespace std;\n\n//COMPARISON (to order set of [node tag,degree] object by degree\nstruct classcomp {\n  bool operator() (const pair<int,int>& lhs, const pair<int,int>& rhs) const\n  {return lhs.second<rhs.second;}\n};\n\n//COMPARISON (to order set of [node tag,degree] object by degree\nstruct classcomp2 {\n  bool operator() (const pair< pair<int,int> ,int>& lhs, const pair< pair<int,int> ,int>& rhs) const\n  {return lhs.second<rhs.second;}\n};\n\n//GLOBAL VARIABLES DEFINITION\nvector< vector<int> > adjmat; //[neighbours]\nvector<int> degree; //[degree]\nmultiset< pair<int,int>, classcomp> tags; //[tag,degree]\nmultiset< pair<int,int> > edges; //[node1, node2]\nmultiset< pair< pair<int,int> ,int>, classcomp2> ranked_edges; //[tag,degree]\n\n//MAIN\nint main(int argc, const char *argv[])\n{\n  //NETWORK\n  std::string name = argv[1]; //path to edgelist\n  int nodes = 0;\n  if(argc>2) nodes = atoi(argv[2]); //rank output for: 0==edges, 1==nodes\n\n//INPUT AND CONSTRUCTION OF STRUCTURES\n//PREPARES INPUT & OUTPUT\nstd::ifstream input(name.c_str());\nstring line;\nifstream input0(name.c_str());\nint temp = 0;\nint MAX = 0;\nint node1;\nint node2;\nif (!input0.is_open()) {\n\tcerr<<\"error in filenames of input directory!\"<<endl;;\n \treturn EXIT_FAILURE;\n} //end if\nelse {\n\twhile ( input0 >> temp ) if(temp > MAX) MAX = temp;\n}\nMAX = MAX+1;\nint link=0;\n//cout << \"Number of nodes: \" << MAX << endl;\nadjmat.resize(MAX);\ndegree.resize(MAX);\nif (!input.is_open()) {\n\tcerr<<\"error in filenames of input directory!\"<<endl;;\n \treturn EXIT_FAILURE;\n} //end if\nelse {\n    string line_buffer;\n    while (getline(input, line_buffer))\n    {\n      \tstringstream ls(line_buffer);\n      \tls >> node1;\n      \tls >> node2;\n\t// while ( input >> node1 >> std::ws >> node2 >> std::ws >> tmp >> std::ws ) {\n\t\t//if(find(adjmat[node1].begin(),adjmat[node1].end(),node2)==adjmat[node1].end() && node1 != node2) {\n\t\tadjmat[node1].push_back(node2);\n\t\tadjmat[node2].push_back(node1);\n\t\tedges.insert(make_pair(node1,node2)); \n\t\t++degree[node1];\n\t\t++degree[node2];\n\t\tlink = link+2;\n\t\t//}\n\t} //end while\n} //end else\ninput.close();\nfor(int el=0; el<MAX; ++el) tags.insert(make_pair(el,degree[el]));\n\nvector<int> realindegree = degree;\n\n//ALGORITHM\nvector<int> core(MAX,-1);\nvector<int> pass(MAX,-1);\nvector<int> age(MAX,-1);\nmultiset< pair<int,int>, classcomp>::iterator v;\nmultiset< pair<int,int>, classcomp>::iterator it1;\nmultiset< pair<int,int>, classcomp>::iterator it2;\npair<multiset< pair<int,int>, classcomp>::iterator,multiset< pair<int,int>, classcomp>::iterator> ret_intern;\npair<multiset< pair<int,int>, classcomp>::iterator,multiset< pair<int,int>, classcomp>::iterator> ret_pass;\nint source;\nint newguy;\nint neighbour;\nint currentpass=1;\nv = tags.begin();\nint maxcore = 0; int t=0;\nwhile(tags.size()>0) {\n\tnewguy = (*v).first;\n\tif(degree[newguy]>maxcore) maxcore = degree[newguy];//keeping track of the number of cores\n\tret_pass = tags.equal_range(make_pair(0,degree[newguy]));//all nodes in the next layer\n\tint number = tags.count(make_pair(0,degree[newguy]));//number of nodes in next layer\n\tit1=ret_pass.first;\n\tfor(int tmp=0; tmp<number; ++tmp,++it1) {//loops around everyone in the same layer\n\t\tsource = (*it1).first; //node in the layer\n\t\tcore[source] = degree[source]; //core for that node\n\t\tpass[source] = currentpass; //layer for that node\n\t\tage[source] = t;\n\t\tfor(int u=0; u<adjmat[source].size(); ++u) {\n\t\t\tneighbour = adjmat[source][u];\n\t\t\tif(degree[neighbour] > degree[source]) {\n\t\t\t\tret_intern = tags.equal_range(make_pair(neighbour,degree[neighbour]));\n\t\t\t\tfor(it2=ret_intern.first; it2!=ret_intern.second; ++it2) {\n\t\t\t\t\tif((*it2).first==neighbour) {\n\t\t\t\t\t\ttags.erase(it2);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t--degree[neighbour];\n\t\t\t\ttags.insert(make_pair(neighbour,degree[neighbour]));\n\t\t\t}\n\t\t}\n\t}\n\tt+=number;\n\tit1=ret_pass.first;\n\tfor(int tmp=0; tmp<number; ++tmp,++it1) tags.erase(it1);\n\tv = tags.begin(); ++currentpass;\n}\n\nif(nodes==0) {//output edges\n\n\tfor(multiset< pair<int,int> >::iterator e = edges.begin(); e!=edges.end(); ++e) {\n\t\tint age0=t-age[(*e).first];\n\t\tif(t-age[(*e).second]>age0) age0=t-age[(*e).second];\n\t\tranked_edges.insert(make_pair((*e),age0));\n\t}\n\n\tint time = 0;\n \tint\tclass_id = 0;\n \tint class_base_time = 0;\n\tmultiset< pair<int,int> > class_content;\n\n\tfor(multiset< pair< pair<int,int>,int> >::iterator e = ranked_edges.begin(); e!=ranked_edges.end(); ++e) {\n\t\tif (e->second != class_id)\n\t\t{\n\t\t\tpair<int,int> last_out_edge = make_pair(class_content.begin()->first, class_content.begin()->second);\n\t\t\tint out_edge_tag = -1;\n\t\t\tfor (multiset< pair<int,int> >::iterator e2 = class_content.begin(); e2 != class_content.end(); ++e2)\n\t\t\t{\n\t\t\t\tif (e2->first == last_out_edge.first && e2->second == last_out_edge.second)\n\t\t\t\t{\n\t\t\t\t\t++out_edge_tag;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tout_edge_tag = 0;\n\t\t\t\t\tlast_out_edge = make_pair(e2->first, e2->second);\n\t\t\t\t}\n\t\t\t\tcout << e2->first << \" \" << e2->second << \" \" << out_edge_tag << \" \" << class_base_time + float(class_content.size() + 1)/2 -1 << \"\\n\";\n\t\t\t}\n\t\t\tclass_content.clear();\n\t\t\tclass_id = (*e).second;\n\t\t\tclass_base_time = time;\n\t\t}\n\t\tclass_content.insert(e->first);\n\t\t++time;\n\t}\n\tpair<int,int> last_out_edge = make_pair(class_content.begin()->first, class_content.begin()->second);\n\tint out_edge_tag = -1;\n\tfor (multiset< pair<int,int> >::iterator e2 = class_content.begin(); e2 != class_content.end(); ++e2)\n\t{\n\t\tif (e2->first == last_out_edge.first && e2->second == last_out_edge.second)\n\t\t{\n\t\t\t++out_edge_tag;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tout_edge_tag = 0;\n\t\t\tlast_out_edge = make_pair(e2->first, e2->second);\n\t\t}\n\t\tcout << e2->first << \" \" << e2->second << \" \" << out_edge_tag << \" \" << class_base_time + float(class_content.size() + 1)/2 -1 << \"\\n\";\n\t}\n}\nelse {//output nodes\n\t\n\tfor(int dummy=0; dummy<core.size(); ++dummy) cout << dummy << \" \" << pass[dummy] << \"\\n\";\n\n}\n\n\nreturn 0;\n} //end main\n", "meta": {"hexsha": "5e7497e3628a2de3fab098a3b5507332b5a5b96f", "size": 6532, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tools/bins/OD.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": "tools/bins/OD.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": "tools/bins/OD.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": 31.2535885167, "max_line_length": 139, "alphanum_fraction": 0.6356399265, "num_tokens": 1918, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432182679956, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.4726658293656121}}
{"text": "//==================================================================================================\n/**\n  EVE - Expressive Vector Engine\n  Copyright : EVE Contributors & Maintainers\n  SPDX-License-Identifier: MIT\n**/\n//==================================================================================================\n#include <eve/function/ellint_d.hpp>\n#include <boost/math/special_functions/ellint_d.hpp>\n#include <eve/function/next.hpp>\n#include <eve/function/prev.hpp>\n#include <eve/function/is_denormal.hpp>\n#include <eve/constant/nan.hpp>\n#include <eve/constant/inf.hpp>\n#include <eve/constant/minf.hpp>\n#include <eve/constant/minlog.hpp>\n#include <eve/platform.hpp>\n\n#include <cmath>\n\nTTS_CASE_TPL(\"Check eve::ellint_d return type\", EVE_TYPE)\n{\n  TTS_EXPR_IS(eve::ellint_d(T(0)), T);\n}\n\nTTS_CASE_TPL(\"Check eve::ellint_d behavior one parameter\", EVE_TYPE)\n{\n  using v_t = eve::element_type_t<T>;\n\n  if constexpr( eve::platform::supports_invalids )\n  {\n    TTS_IEEE_EQUAL(eve::ellint_d(eve::nan(eve::as<T>())) , eve::nan(eve::as<T>()) );\n    TTS_IEEE_EQUAL(eve::ellint_d(T(1)) , eve::nan(eve::as<T>()) );\n    TTS_IEEE_EQUAL(eve::ellint_d(T(-1)), eve::nan(eve::as<T>()) );\n  }\n\n  TTS_ULP_EQUAL( eve::ellint_d(T( 0.)), T(boost::math::ellint_d(v_t(0))), 0.5);\n  TTS_ULP_EQUAL( eve::ellint_d(T( 0.5)), T(boost::math::ellint_d(v_t(0.5))), 0.5);\n  TTS_ULP_EQUAL( eve::ellint_d(T( 0.9)), T(boost::math::ellint_d(v_t(0.9))), 1.0);\n\n}\n\nTTS_CASE_TPL(\"Check eve::ellint_d behavior two parameter\", EVE_TYPE)\n{\n  using v_t = eve::element_type_t<T>;\n  using eve::as;\n  if constexpr( eve::platform::supports_invalids )\n  {\n    TTS_IEEE_EQUAL(eve::ellint_d(eve::pio_2(as<T>()), eve::nan(eve::as<T>())) , eve::nan(eve::as<T>()) );\n  }\n\n  TTS_ULP_EQUAL( eve::ellint_d(eve::pio_2(as<T>()), T( 0.)),  T(boost::math::ellint_d(v_t(0)  , eve::pio_2(as<v_t>()))), 0.5);\n  TTS_ULP_EQUAL( eve::ellint_d(eve::pio_2(as<T>()), T( 0.5)), T(boost::math::ellint_d(v_t(0.5), eve::pio_2(as<v_t>()))), 1.5);\n  TTS_ULP_EQUAL( eve::ellint_d(eve::pio_2(as<T>()), T( 0.9)), T(boost::math::ellint_d(v_t(0.9), eve::pio_2(as<v_t>()))), 2.5);\n  TTS_ULP_EQUAL( eve::ellint_d(eve::pio_4(as<T>()), T( 0.)),  T(boost::math::ellint_d(v_t(0)  , eve::pio_4(as<v_t>()))), 1.5);\n  TTS_ULP_EQUAL( eve::ellint_d(eve::pio_4(as<T>()), T( 0.5)), T(boost::math::ellint_d(v_t(0.5), eve::pio_4(as<v_t>()))), 1.5);\n  TTS_ULP_EQUAL( eve::ellint_d(eve::pio_4(as<T>()), T( 0.9)), T(boost::math::ellint_d(v_t(0.9), eve::pio_4(as<v_t>()))), 4.0);\n  TTS_ULP_EQUAL( eve::ellint_d(3*eve::pio_4(as<T>()), T( 0.)),  T(boost::math::ellint_d(v_t(0)  , 3*eve::pio_4(as<v_t>()))), 0.5);\n  TTS_ULP_EQUAL( eve::ellint_d(3*eve::pio_4(as<T>()), T( 0.5)), T(boost::math::ellint_d(v_t(0.5), 3*eve::pio_4(as<v_t>()))), 1);\n  TTS_ULP_EQUAL( eve::ellint_d(3*eve::pio_4(as<T>()), T( 0.9)), T(boost::math::ellint_d(v_t(0.9), 3*eve::pio_4(as<v_t>()))), 1.0);\n  TTS_ULP_EQUAL( eve::ellint_d(T(100), T( 0.)),  T(boost::math::ellint_d(v_t(0)  , v_t(100))), 0.5);\n  TTS_ULP_EQUAL( eve::ellint_d(T(100), T( 0.5)), T(boost::math::ellint_d(v_t(0.5), v_t(100))), 0.5);\n  TTS_ULP_EQUAL( eve::ellint_d(T(100), T( 0.9)), T(boost::math::ellint_d(v_t(0.9), v_t(100))), 2.0);\n  TTS_ULP_EQUAL( eve::ellint_d(T(1.5), T(1)),    T(boost::math::ellint_d(v_t(1)  , v_t(1.5))), 7.0);\n}\n", "meta": {"hexsha": "557f3858f49f27d3bc3220913e6c4dc261c495f1", "size": 3286, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/unit/module/real/elliptic/ellint_d/regular/ellint_d.hpp", "max_stars_repo_name": "orao/eve", "max_stars_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_stars_repo_licenses": ["MIT"], "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/unit/module/real/elliptic/ellint_d/regular/ellint_d.hpp", "max_issues_repo_name": "orao/eve", "max_issues_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_issues_repo_licenses": ["MIT"], "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/unit/module/real/elliptic/ellint_d/regular/ellint_d.hpp", "max_forks_repo_name": "orao/eve", "max_forks_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_forks_repo_licenses": ["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.7878787879, "max_line_length": 130, "alphanum_fraction": 0.5967741935, "num_tokens": 1258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.47266582638760063}}
{"text": "/*\n * test_STD.cpp\n *\n *  Created on: 2013-4-18\n *      Author: fasiondog\n */\n\n#ifdef TEST_ALL_IN_ONE\n    #include <boost/test/unit_test.hpp>\n#else\n    #define BOOST_TEST_MODULE test_hikyuu_indicator_suite\n    #include <boost/test/unit_test.hpp>\n#endif\n\n#include <hikyuu/StockManager.h>\n#include <hikyuu/indicator/crt/STDEV.h>\n#include <hikyuu/indicator/crt/PRICELIST.h>\n\nusing namespace hku;\n\n/**\n * @defgroup test_indicator_STDEV test_indicator_STDEV\n * @ingroup test_hikyuu_indicator_suite\n * @{\n */\n\n/** @par \u68c0\u6d4b\u70b9 */\nBOOST_AUTO_TEST_CASE( test_STDEV ) {\n    /** @arg n > 1 \u7684\u6b63\u5e38\u60c5\u51b5 */\n    PriceList d;\n    for (size_t i = 0; i < 15; ++i) {\n        d.push_back(i+1);\n    }\n    d[5] = 4.0;\n    d[7] = 4.0;\n    d[11] = 6.0;\n\n    Indicator ind = PRICELIST(d);\n    Indicator dev = STDEV(ind, 10);\n    BOOST_CHECK(dev.size() == 15);\n    BOOST_CHECK(dev[8] == Null<price_t>());\n    BOOST_CHECK(std::fabs(dev[9] - 2.923088) < 0.000001 );\n    BOOST_CHECK(std::fabs(dev[10] - 3.142893) < 0.000001 );\n    BOOST_CHECK(std::fabs(dev[11] - 2.830390) < 0.000001 );\n    BOOST_CHECK(std::fabs(dev[12] - 3.267686) < 0.000001 );\n    BOOST_CHECK(std::fabs(dev[13] - 3.653004) < 0.000001 );\n    BOOST_CHECK(std::fabs(dev[14] - 4.001388) < 0.000001 );\n\n    /** @arg n = 1\u65f6 */\n    dev = STDEV(ind, 1);\n    BOOST_CHECK(dev.size() == 15);\n    for (size_t i = 0; i < dev.size(); ++i) {\n        BOOST_CHECK(dev[i] == Null<price_t>());\n    }\n\n    /** @arg operator() */\n    Indicator expect = STDEV(ind, 10);\n    dev = STDEV(10);\n    Indicator result = dev(ind);\n    BOOST_CHECK(result.size() == expect.size());\n    for (size_t i = 0; i < expect.size(); ++i) {\n        BOOST_CHECK(result[i] == expect[i]);\n    }\n}\n\n/** @} */\n\n\n", "meta": {"hexsha": "cfe798c2d7b8790b186ae3f4863ca1ee68b2b5b0", "size": 1699, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/libs/hikyuu/indicator/test_STDEV.cpp", "max_stars_repo_name": "CodingNowNow/jiaoyi", "max_stars_repo_head_hexsha": "57513f8cf0d282fa70ac9e8e76ff785d7a2a019c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-03-29T05:38:37.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-29T05:38:37.000Z", "max_issues_repo_path": "test/libs/hikyuu/indicator/test_STDEV.cpp", "max_issues_repo_name": "CodingNowNow/jiaoyi", "max_issues_repo_head_hexsha": "57513f8cf0d282fa70ac9e8e76ff785d7a2a019c", "max_issues_repo_licenses": ["MIT"], "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/libs/hikyuu/indicator/test_STDEV.cpp", "max_forks_repo_name": "CodingNowNow/jiaoyi", "max_forks_repo_head_hexsha": "57513f8cf0d282fa70ac9e8e76ff785d7a2a019c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-31T16:45:23.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-31T16:45:23.000Z", "avg_line_length": 24.6231884058, "max_line_length": 59, "alphanum_fraction": 0.5915244261, "num_tokens": 579, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217431943271999, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.47266582340958885}}
{"text": "/* Boost interval/transc.hpp template implementation file\n *\n * Copyright 2000 Jens Maurer\n * Copyright 2002 Herv\u00e9 Br\u00f6nnimann, Guillaume Melquiond, Sylvain Pion\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_INTERVAL_TRANSC_HPP\n#define BOOST_NUMERIC_INTERVAL_TRANSC_HPP\n\n#include <boost/config.hpp>\n#include <boost/numeric/interval/detail/interval_prototype.hpp>\n#include <boost/numeric/interval/detail/bugs.hpp>\n#include <boost/numeric/interval/detail/test_input.hpp>\n#include <boost/numeric/interval/rounding.hpp>\n#include <boost/numeric/interval/constants.hpp>\n#include <boost/numeric/interval/arith.hpp>\n#include <boost/numeric/interval/arith2.hpp>\n#include <algorithm>\n\nnamespace boost {\nnamespace numeric {\n\ntemplate<class T, class Policies> inline\ninterval<T, Policies> exp(const interval<T, Policies>& x)\n{\n  typedef interval<T, Policies> I;\n  if (interval_lib::detail::test_input(x))\n    return I::empty();\n  typename Policies::rounding rnd;\n  return I(rnd.exp_down(x.lower()), rnd.exp_up(x.upper()), true);\n}\n\ntemplate<class T, class Policies> inline\ninterval<T, Policies> log(const interval<T, Policies>& x)\n{\n  typedef interval<T, Policies> I;\n  if (interval_lib::detail::test_input(x) ||\n      !interval_lib::user::is_pos(x.upper()))\n    return I::empty();\n  typename Policies::rounding rnd;\n  typedef typename Policies::checking checking;\n  T l = !interval_lib::user::is_pos(x.lower())\n             ? checking::neg_inf() : rnd.log_down(x.lower());\n  return I(l, rnd.log_up(x.upper()), true);\n}\n\ntemplate<class T, class Policies> inline\ninterval<T, Policies> cos(const interval<T, Policies>& x)\n{\n  if (interval_lib::detail::test_input(x))\n    return interval<T, Policies>::empty();\n  typename Policies::rounding rnd;\n  typedef interval<T, Policies> I;\n  typedef typename interval_lib::unprotect<I>::type R;\n\n  // get lower bound within [0, pi]\n  const R pi2 = interval_lib::pi_twice<R>();\n  R tmp = fmod((const R&)x, pi2);\n  if (width(tmp) >= pi2.lower())\n    return I(static_cast<T>(-1), static_cast<T>(1), true); // we are covering a full period\n  if (tmp.lower() >= interval_lib::constants::pi_upper<T>())\n    return -cos(tmp - interval_lib::pi<R>());\n  T l = tmp.lower();\n  T u = tmp.upper();\n\n  BOOST_USING_STD_MIN();\n  // separate into monotone subintervals\n  if (u <= interval_lib::constants::pi_lower<T>())\n    return I(rnd.cos_down(u), rnd.cos_up(l), true);\n  else if (u <= pi2.lower())\n    return I(static_cast<T>(-1), rnd.cos_up(min BOOST_PREVENT_MACRO_SUBSTITUTION(rnd.sub_down(pi2.lower(), u), l)), true);\n  else\n    return I(static_cast<T>(-1), static_cast<T>(1), true);\n}\n\ntemplate<class T, class Policies> inline\ninterval<T, Policies> sin(const interval<T, Policies>& x)\n{\n  typedef interval<T, Policies> I;\n  if (interval_lib::detail::test_input(x))\n    return I::empty();\n  typename Policies::rounding rnd;\n  typedef typename interval_lib::unprotect<I>::type R;\n  I r = cos((const R&)x - interval_lib::pi_half<R>());\n  (void)&rnd;\n  return r;\n}\n\ntemplate<class T, class Policies> inline\ninterval<T, Policies> tan(const interval<T, Policies>& x)\n{\n  typedef interval<T, Policies> I;\n  if (interval_lib::detail::test_input(x))\n    return I::empty();\n  typename Policies::rounding rnd;\n  typedef typename interval_lib::unprotect<I>::type R;\n\n  // get lower bound within [-pi/2, pi/2]\n  const R pi = interval_lib::pi<R>();\n  R tmp = fmod((const R&)x, pi);\n  const T pi_half_d = interval_lib::constants::pi_half_lower<T>();\n  if (tmp.lower() >= pi_half_d)\n    tmp -= pi;\n  if (tmp.lower() <= -pi_half_d || tmp.upper() >= pi_half_d)\n    return I::whole();\n  return I(rnd.tan_down(tmp.lower()), rnd.tan_up(tmp.upper()), true);\n}\n\ntemplate<class T, class Policies> inline\ninterval<T, Policies> asin(const interval<T, Policies>& x)\n{\n  typedef interval<T, Policies> I;\n  if (interval_lib::detail::test_input(x)\n     || x.upper() < static_cast<T>(-1) || x.lower() > static_cast<T>(1))\n    return I::empty();\n  typename Policies::rounding rnd;\n  T l = (x.lower() <= static_cast<T>(-1))\n             ? -interval_lib::constants::pi_half_upper<T>()\n             : rnd.asin_down(x.lower());\n  T u = (x.upper() >= static_cast<T>(1) )\n             ?  interval_lib::constants::pi_half_upper<T>()\n             : rnd.asin_up  (x.upper());\n  return I(l, u, true);\n}\n\ntemplate<class T, class Policies> inline\ninterval<T, Policies> acos(const interval<T, Policies>& x)\n{\n  typedef interval<T, Policies> I;\n  if (interval_lib::detail::test_input(x)\n     || x.upper() < static_cast<T>(-1) || x.lower() > static_cast<T>(1))\n    return I::empty();\n  typename Policies::rounding rnd;\n  T l = (x.upper() >= static_cast<T>(1) )\n          ? static_cast<T>(0)\n          : rnd.acos_down(x.upper());\n  T u = (x.lower() <= static_cast<T>(-1))\n          ? interval_lib::constants::pi_upper<T>()\n          : rnd.acos_up  (x.lower());\n  return I(l, u, true);\n}\n\ntemplate<class T, class Policies> inline\ninterval<T, Policies> atan(const interval<T, Policies>& x)\n{\n  typedef interval<T, Policies> I;\n  if (interval_lib::detail::test_input(x))\n    return I::empty();\n  typename Policies::rounding rnd;\n  return I(rnd.atan_down(x.lower()), rnd.atan_up(x.upper()), true);\n}\n\ntemplate<class T, class Policies> inline\ninterval<T, Policies> sinh(const interval<T, Policies>& x)\n{\n  typedef interval<T, Policies> I;\n  if (interval_lib::detail::test_input(x))\n    return I::empty();\n  typename Policies::rounding rnd;\n  return I(rnd.sinh_down(x.lower()), rnd.sinh_up(x.upper()), true);\n}\n\ntemplate<class T, class Policies> inline\ninterval<T, Policies> cosh(const interval<T, Policies>& x)\n{\n  typedef interval<T, Policies> I;\n  if (interval_lib::detail::test_input(x))\n    return I::empty();\n  typename Policies::rounding rnd;\n  if (interval_lib::user::is_neg(x.upper()))\n    return I(rnd.cosh_down(x.upper()), rnd.cosh_up(x.lower()), true);\n  else if (!interval_lib::user::is_neg(x.lower()))\n    return I(rnd.cosh_down(x.lower()), rnd.cosh_up(x.upper()), true);\n  else\n    return I(static_cast<T>(1), rnd.cosh_up(-x.lower() > x.upper() ? x.lower() : x.upper()), true);\n}\n\ntemplate<class T, class Policies> inline\ninterval<T, Policies> tanh(const interval<T, Policies>& x)\n{\n  typedef interval<T, Policies> I;\n  if (interval_lib::detail::test_input(x))\n    return I::empty();\n  typename Policies::rounding rnd;\n  return I(rnd.tanh_down(x.lower()), rnd.tanh_up(x.upper()), true);\n}\n\ntemplate<class T, class Policies> inline\ninterval<T, Policies> asinh(const interval<T, Policies>& x)\n{\n  typedef interval<T, Policies> I;\n  if (interval_lib::detail::test_input(x))\n    return I::empty();\n  typename Policies::rounding rnd;\n  return I(rnd.asinh_down(x.lower()), rnd.asinh_up(x.upper()), true);\n}\n\ntemplate<class T, class Policies> inline\ninterval<T, Policies> acosh(const interval<T, Policies>& x)\n{\n  typedef interval<T, Policies> I;\n  if (interval_lib::detail::test_input(x) || x.upper() < static_cast<T>(1))\n    return I::empty();\n  typename Policies::rounding rnd;\n  T l = x.lower() <= static_cast<T>(1) ? static_cast<T>(0) : rnd.acosh_down(x.lower());\n  return I(l, rnd.acosh_up(x.upper()), true);\n}\n\ntemplate<class T, class Policies> inline\ninterval<T, Policies> atanh(const interval<T, Policies>& x)\n{\n  typedef interval<T, Policies> I;\n  if (interval_lib::detail::test_input(x)\n      || x.upper() < static_cast<T>(-1) || x.lower() > static_cast<T>(1))\n    return I::empty();\n  typename Policies::rounding rnd;\n  typedef typename Policies::checking checking;\n  T l = (x.lower() <= static_cast<T>(-1))\n             ? checking::neg_inf() : rnd.atanh_down(x.lower());\n  T u = (x.upper() >= static_cast<T>(1) )\n             ? checking::pos_inf() : rnd.atanh_up  (x.upper());\n  return I(l, u, true);\n}\n\n} // namespace numeric\n} // namespace boost\n\n#endif // BOOST_NUMERIC_INTERVAL_TRANSC_HPP\n", "meta": {"hexsha": "b9b7e60c4e7863ad22e8fafdf9f9b8d65e5e0bd7", "size": 7915, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/numeric/interval/transc.hpp", "max_stars_repo_name": "Harshitha91/Tmdb-react-native-node", "max_stars_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/numeric/interval/transc.hpp", "max_issues_repo_name": "Harshitha91/Tmdb-react-native-node", "max_issues_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/numeric/interval/transc.hpp", "max_forks_repo_name": "Harshitha91/Tmdb-react-native-node", "max_forks_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 33.9699570815, "max_line_length": 122, "alphanum_fraction": 0.6741629817, "num_tokens": 2125, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217431943271999, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.47266582340958885}}
{"text": "#include <fstream>\n#include \"multiindex.hpp\"\n#include \"potgen.hpp\"\n#include \"dynamic_grid.hpp\"\n#include \"randomize.hpp\"\n\n#include <boost/test/unit_test.hpp>\n\nBOOST_AUTO_TEST_SUITE(potgen_internals_test)\n\nBOOST_AUTO_TEST_CASE( randomize_error_test )\n{\n    DynamicGrid<complex_t> dgrid(2, 8, TransformationType::FFT_INDEX);\n    auto rg = []() { return 0.5; };\n    // uninitialized multi index\n    BOOST_CHECK_THROW(randomize_generic( dgrid, rg, MultiIndex(1)), std::invalid_argument);\n}\n\nBOOST_AUTO_TEST_CASE( randomize_phases_area_check )\n{\n\tDynamicGrid<complex_t> dgrid(2, 8, TransformationType::FFT_INDEX);\n\tfor( auto& f : dgrid )\n\t\tf = 1;\n\n\t// multiply with -1, so twice (or never) will raise an error\n\tauto rg = []() { return pi; };\n    randomize_generic( dgrid, rg, fft_indexing(dgrid) );\n\tfor( auto& f : dgrid ) {\n        BOOST_REQUIRE_EQUAL(std::real(f), -1);\n    }\n}\n\nBOOST_AUTO_TEST_CASE( randomize_phases_symmetry_check )\n{\n\tDynamicGrid<complex_t> dgrid(2, 8, TransformationType::FFT_INDEX);\n\tfor( auto& f : dgrid )\n\t\tf = 1;\n\n\trandomizePhases( dgrid, 0 );\n\n\tMultiIndex index = fft_indexing(dgrid);\n\n\t/// \\todo cannot use multi index here, because [] assignment not possible right now\n\tstd::vector<int> inverted( 2 );\n\n\tfor( ;index.valid(); ++index)\n\t{\n\t\t// set inverted index\n\t\tfor(int i = 0; i < 2; ++i)\n\t\t\tinverted[i] = -index[i];\n\n\t\tBOOST_CHECK_EQUAL( std::conj(dgrid(index)), dgrid(inverted));\n\t}\n\n}\n\n/// \\todo randomize precondition exceptions check\n\n/// \\todo generate potential in k space test\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "458078bee0343cb3d4aba2e85c9bd256e6689368", "size": 1538, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/potgen/test/potgen_internals_test.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/potgen/test/potgen_internals_test.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/potgen/test/potgen_internals_test.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": 25.2131147541, "max_line_length": 91, "alphanum_fraction": 0.7022106632, "num_tokens": 431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.47266582152626174}}
{"text": "\n\n/* --------------------------------------------------------------------- \n * \n * Copyright (C) 2006 - 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: Wolfgang Bangerth, Texas A&M University, 2006, 2007; \n *          Denis Davydov, University of Erlangen-Nuremberg, 2016; \n *          Marc Fehling, Colorado State University, 2020. \n */ \n\n\n// @sect3{Include files}  \n\n// \u524d\u9762\u51e0\u4e2a\u6587\u4ef6\u5df2\u7ecf\u5728\u524d\u9762\u7684\u4f8b\u5b50\u4e2d\u8bb2\u8fc7\u4e86\uff0c\u56e0\u6b64\u4e0d\u518d\u505a\u8fdb\u4e00\u6b65\u7684\u8bc4\u8bba\u3002\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/utilities.h> \n#include <deal.II/lac/dynamic_sparsity_pattern.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/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_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// \u8fd9\u4e9b\u662f\u6211\u4eec\u9700\u8981\u7684\u65b0\u6587\u4ef6\u3002\u7b2c\u4e00\u4e2a\u548c\u7b2c\u4e8c\u4e2a\u63d0\u4f9b\u4e86FECollection\u548c<i>hp</i>\u7248\u672c\u7684FEValues\u7c7b\uff0c\u5982\u672c\u7a0b\u5e8f\u4ecb\u7ecd\u4e2d\u6240\u8ff0\u3002\u4e0b\u4e00\u4e2a\u6587\u4ef6\u63d0\u4f9b\u4e86\u81ea\u52a8 $hp$ \u9002\u5e94\u7684\u529f\u80fd\uff0c\u4e3a\u6b64\u6211\u4eec\u5c06\u4f7f\u7528\u57fa\u4e8e\u8870\u51cf\u7cfb\u5217\u6269\u5c55\u7cfb\u6570\u7684\u4f30\u8ba1\u7b97\u6cd5\uff0c\u8fd9\u662f\u6700\u540e\u4e24\u4e2a\u6587\u4ef6\u7684\u4e00\u90e8\u5206\u3002\n\n#include <deal.II/hp/fe_collection.h> \n#include <deal.II/hp/fe_values.h> \n#include <deal.II/hp/refinement.h> \n#include <deal.II/fe/fe_series.h> \n#include <deal.II/numerics/smoothness_estimator.h> \n\n// \u6700\u540e\u4e00\u7ec4\u5305\u542b\u6587\u4ef6\u662f\u6807\u51c6\u7684C++\u5934\u6587\u4ef6\u3002\n\n#include <fstream> \n#include <iostream> \n\n// \u6700\u540e\uff0c\u8fd9\u548c\u4ee5\u524d\u7684\u7a0b\u5e8f\u4e00\u6837\u3002\n\nnamespace Step27 \n{ \n  using namespace dealii; \n// @sect3{The main class}  \n\n// \u8fd9\u4e2a\u7a0b\u5e8f\u7684\u4e3b\u7c7b\u770b\u8d77\u6765\u975e\u5e38\u50cf\u524d\u51e0\u4e2a\u6559\u7a0b\u7a0b\u5e8f\u4e2d\u5df2\u7ecf\u4f7f\u7528\u8fc7\u7684\uff0c\u4f8b\u5982  step-6  \u4e2d\u7684\u90a3\u4e2a\u3002\u4e3b\u8981\u7684\u533a\u522b\u662f\u6211\u4eec\u5c06refine_grid\u548coutput_results\u51fd\u6570\u5408\u5e76\u4e3a\u4e00\u4e2a\uff0c\u56e0\u4e3a\u6211\u4eec\u8fd8\u60f3\u8f93\u51fa\u4e00\u4e9b\u7528\u4e8e\u51b3\u5b9a\u5982\u4f55\u7ec6\u5316\u7f51\u683c\u7684\u91cf\uff08\u7279\u522b\u662f\u4f30\u8ba1\u7684\u89e3\u51b3\u65b9\u6848\u7684\u5e73\u6ed1\u5ea6\uff09\u3002\n\n// \u5c31\u6210\u5458\u53d8\u91cf\u800c\u8a00\uff0c\u6211\u4eec\u4f7f\u7528\u4e0e step-6 \u4e2d\u76f8\u540c\u7684\u7ed3\u6784\uff0c\u4f46\u6211\u4eec\u9700\u8981\u96c6\u5408\u6765\u4ee3\u66ff\u5355\u4e2a\u7684\u6709\u9650\u5143\u3001\u6b63\u4ea4\u548c\u9762\u72b6\u6b63\u4ea4\u5bf9\u8c61\u3002\u6211\u4eec\u5c06\u5728\u7c7b\u7684\u6784\u9020\u51fd\u6570\u4e2d\u586b\u5145\u8fd9\u4e9b\u96c6\u5408\u3002\u6700\u540e\u4e00\u4e2a\u53d8\u91cf\uff0c <code>max_degree</code> \uff0c\u8868\u793a\u6240\u7528\u5f62\u72b6\u51fd\u6570\u7684\u6700\u5927\u591a\u9879\u5f0f\u7a0b\u5ea6\u3002\n\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 postprocess(const unsigned int cycle); \n\n    Triangulation<dim> triangulation; \n\n \n    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    AffineConstraints<double> 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//  @sect3{Equation data}  \n\n// \u63a5\u4e0b\u6765\uff0c\u8ba9\u6211\u4eec\u4e3a\u8fd9\u4e2a\u95ee\u9898\u5b9a\u4e49\u53f3\u624b\u8fb9\u7684\u51fd\u6570\u3002\u5b83\u57281d\u4e2d\u662f $x+1$ \uff0c\u57282d\u4e2d\u662f $(x+1)(y+1)$ \uff0c\u4ee5\u6b64\u7c7b\u63a8\u3002\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    double product = 1; \n    for (unsigned int d = 0; d < dim; ++d) \n      product *= (p[d] + 1); \n    return product; \n  } \n\n//  @sect3{Implementation of the main class}  \n// @sect4{LaplaceProblem::LaplaceProblem constructor}  \n\n// \u8fd9\u4e2a\u7c7b\u7684\u6784\u9020\u51fd\u6570\u662f\u76f8\u5f53\u76f4\u63a5\u7684\u3002\u5b83\u5c06DoFHandler\u5bf9\u8c61\u4e0e\u4e09\u89d2\u5f62\u76f8\u5173\u8054\uff0c\u7136\u540e\u5c06\u6700\u5927\u591a\u9879\u5f0f\u5ea6\u6570\u8bbe\u7f6e\u4e3a7\uff08\u57281d\u548c2d\u4e2d\uff09\u62165\uff08\u57283d\u53ca\u4ee5\u4e0a\uff09\u3002\u6211\u4eec\u8fd9\u6837\u505a\u662f\u56e0\u4e3a\u4f7f\u7528\u9ad8\u9636\u591a\u9879\u5f0f\u5ea6\u6570\u4f1a\u53d8\u5f97\u975e\u5e38\u6602\u8d35\uff0c\u5c24\u5176\u662f\u5728\u66f4\u9ad8\u7684\u7a7a\u95f4\u7ef4\u5ea6\u4e0a\u3002\n\n// \u5728\u8fd9\u4e4b\u540e\uff0c\u6211\u4eec\u586b\u5145\u6709\u9650\u5143\u3001\u5355\u5143\u548c\u9762\u7684\u56db\u5206\u6cd5\u5bf9\u8c61\u96c6\u5408\u3002\u6211\u4eec\u4ece\u4e8c\u6b21\u5143\u5f00\u59cb\uff0c\u6bcf\u4e2a\u6b63\u4ea4\u516c\u5f0f\u7684\u9009\u62e9\u90fd\u662f\u4e3a\u4e86\u9002\u5408 hp::FECollection \u5bf9\u8c61\u4e2d\u7684\u5339\u914d\u6709\u9650\u5143\u3002\n\n  template <int dim> \n  LaplaceProblem<dim>::LaplaceProblem() \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// @sect4{LaplaceProblem::~LaplaceProblem destructor}  \n\n// \u89e3\u6784\u5668\u4e0e\u6211\u4eec\u5728  step-6  \u4e2d\u5df2\u7ecf\u505a\u8fc7\u7684\u6ca1\u6709\u53d8\u5316\u3002\n\n  template <int dim> \n  LaplaceProblem<dim>::~LaplaceProblem() \n  { \n    dof_handler.clear(); \n  } \n// @sect4{LaplaceProblem::setup_system}  \n\n// \u8fd9\u4e2a\u51fd\u6570\u53c8\u662f\u5bf9\u6211\u4eec\u5728  step-6  \u4e2d\u5df2\u7ecf\u505a\u8fc7\u7684\u4e8b\u60c5\u7684\u9010\u5b57\u590d\u5236\u3002\u5c3d\u7ba1\u51fd\u6570\u8c03\u7528\u7684\u540d\u79f0\u548c\u53c2\u6570\u5b8c\u5168\u76f8\u540c\uff0c\u4f46\u5185\u90e8\u4f7f\u7528\u7684\u7b97\u6cd5\u5728\u67d0\u4e9b\u65b9\u9762\u662f\u4e0d\u540c\u7684\uff0c\u56e0\u4e3a\u8fd9\u91cc\u7684dof_handler\u53d8\u91cf\u662f\u5728  $hp$  -mode\u3002\n\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, constraints); \n    VectorTools::interpolate_boundary_values(dof_handler, \n                                             0, \n                                             Functions::ZeroFunction<dim>(), \n                                             constraints); \n    constraints.close(); \n\n    DynamicSparsityPattern dsp(dof_handler.n_dofs(), dof_handler.n_dofs()); \n    DoFTools::make_sparsity_pattern(dof_handler, dsp, constraints, false); \n    sparsity_pattern.copy_from(dsp); \n\n    system_matrix.reinit(sparsity_pattern); \n  } \n\n//  @sect4{LaplaceProblem::assemble_system}  \n\n// \u8fd9\u662f\u4e00\u4e2a\u4ece\u6bcf\u4e2a\u5355\u5143\u7684\u5c40\u90e8\u8d21\u732e\u4e2d\u96c6\u5408\u5168\u5c40\u77e9\u9635\u548c\u53f3\u4fa7\u5411\u91cf\u7684\u51fd\u6570\u3002\u5b83\u7684\u4e3b\u8981\u5de5\u4f5c\u4e0e\u4e4b\u524d\u8bb8\u591a\u6559\u7a0b\u4e2d\u63cf\u8ff0\u7684\u4e00\u6837\u3002\u91cd\u8981\u7684\u5dee\u5f02\u662f<i>hp</i>\u6709\u9650\u5143\u65b9\u6cd5\u6240\u9700\u8981\u7684\u3002\u7279\u522b\u662f\uff0c\u6211\u4eec\u9700\u8981\u4f7f\u7528FEValues\u5bf9\u8c61\u7684\u96c6\u5408\uff08\u901a\u8fc7 hp::FEValues \u7c7b\u5b9e\u73b0\uff09\uff0c\u5e76\u4e14\u5728\u5c06\u5c40\u90e8\u8d21\u732e\u590d\u5236\u5230\u5168\u5c40\u5bf9\u8c61\u65f6\uff0c\u6211\u4eec\u5fc5\u987b\u6d88\u9664\u53d7\u9650\u81ea\u7531\u5ea6\u3002\u8fd9\u4e24\u70b9\u5728\u672c\u7a0b\u5e8f\u7684\u4ecb\u7ecd\u4e2d\u90fd\u6709\u8be6\u7ec6\u89e3\u91ca\u3002\n\n// \u8fd8\u6709\u4e00\u4e2a\u5c0f\u95ee\u9898\u662f\uff0c\u7531\u4e8e\u6211\u4eec\u5728\u4e0d\u540c\u7684\u5355\u5143\u683c\u4e2d\u4f7f\u7528\u4e86\u4e0d\u540c\u7684\u591a\u9879\u5f0f\u5ea6\u6570\uff0c\u6301\u6709\u5c40\u90e8\u8d21\u732e\u7684\u77e9\u9635\u548c\u5411\u91cf\u5728\u6240\u6709\u5355\u5143\u683c\u4e2d\u7684\u5927\u5c0f\u4e0d\u5c3d\u76f8\u540c\u3002\u56e0\u6b64\uff0c\u5728\u6240\u6709\u5355\u5143\u7684\u5faa\u73af\u5f00\u59cb\u65f6\uff0c\u6211\u4eec\u6bcf\u6b21\u90fd\u5fc5\u987b\u5c06\u5b83\u4eec\u7684\u5927\u5c0f\u8c03\u6574\u5230\u6b63\u786e\u7684\u5927\u5c0f\uff08\u7531 <code>dofs_per_cell</code> \u7ed9\u51fa\uff09\u3002\u56e0\u4e3a\u8fd9\u4e9b\u7c7b\u7684\u5b9e\u73b0\u65b9\u5f0f\u662f\u51cf\u5c11\u77e9\u9635\u6216\u5411\u91cf\u7684\u5927\u5c0f\u4e0d\u4f1a\u91ca\u653e\u5f53\u524d\u5206\u914d\u7684\u5185\u5b58\uff08\u9664\u975e\u65b0\u7684\u5927\u5c0f\u4e3a\u96f6\uff09\uff0c\u6240\u4ee5\u5728\u5faa\u73af\u5f00\u59cb\u65f6\u8c03\u6574\u5927\u5c0f\u7684\u8fc7\u7a0b\u53ea\u9700\u8981\u5728\u6700\u521d\u51e0\u6b21\u8fed\u4ee3\u4e2d\u91cd\u65b0\u5206\u914d\u5185\u5b58\u3002\u4e00\u65e6\u6211\u4eec\u5728\u4e00\u4e2a\u5355\u5143\u4e2d\u627e\u5230\u4e86\u6700\u5927\u7684\u6709\u9650\u5143\u5ea6\uff0c\u5c31\u4e0d\u4f1a\u518d\u53d1\u751f\u91cd\u65b0\u5206\u914d\uff0c\u56e0\u4e3a\u6240\u6709\u540e\u7eed\u7684 <code>reinit</code> \u8c03\u7528\u53ea\u4f1a\u5c06\u5927\u5c0f\u8bbe\u7f6e\u4e3a\u9002\u5408\u5f53\u524d\u5206\u914d\u7684\u5185\u5b58\u3002\u8fd9\u4e00\u70b9\u5f88\u91cd\u8981\uff0c\u56e0\u4e3a\u5206\u914d\u5185\u5b58\u662f\u5f88\u6602\u8d35\u7684\uff0c\u800c\u4e14\u6bcf\u6b21\u6211\u4eec\u8bbf\u95ee\u4e00\u4e2a\u65b0\u7684\u5355\u5143\u65f6\u90fd\u8fd9\u6837\u505a\u4f1a\u82b1\u8d39\u5927\u91cf\u7684\u8ba1\u7b97\u65f6\u95f4\u3002\n\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 | \n                                     update_JxW_values); \n\n    RightHandSide<dim> rhs_function; \n\n    FullMatrix<double> cell_matrix; \n    Vector<double>     cell_rhs; \n\n    std::vector<types::global_dof_index> local_dof_indices; \n\n    for (const auto &cell : dof_handler.active_cell_iterators()) \n      { \n        const unsigned int dofs_per_cell = cell->get_fe().n_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(), rhs_values); \n\n        for (unsigned int q_point = 0; 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) += \n                  (fe_values.shape_grad(i, q_point) * // grad phi_i(x_q) \n                   fe_values.shape_grad(j, q_point) * // grad phi_j(x_q) \n                   fe_values.JxW(q_point));           // dx \n\n              cell_rhs(i) += (fe_values.shape_value(i, q_point) * // phi_i(x_q) \n                              rhs_values[q_point] *               // f(x_q) \n                              fe_values.JxW(q_point));            // dx \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( \n          cell_matrix, cell_rhs, local_dof_indices, system_matrix, system_rhs); \n      } \n  } \n\n//  @sect4{LaplaceProblem::solve}  \n\n// \u89e3\u51b3\u7ebf\u6027\u7cfb\u7edf\u7684\u51fd\u6570\u4e0e\u4e4b\u524d\u7684\u4f8b\u5b50\u5b8c\u5168\u6ca1\u6709\u53d8\u5316\u3002\u6211\u4eec\u53ea\u662f\u8bd5\u56fe\u5c06\u521d\u59cb\u6b8b\u5dee\uff08\u76f8\u5f53\u4e8e\u53f3\u624b\u8fb9\u7684 $l_2$ \u51c6\u5219\uff09\u51cf\u5c11\u4e00\u5b9a\u7684\u7cfb\u6570\u3002\n\n  template <int dim> \n  void LaplaceProblem<dim>::solve() \n  { \n    SolverControl            solver_control(system_rhs.size(), \n                                 1e-12 * system_rhs.l2_norm()); \n    SolverCG<Vector<double>> cg(solver_control); \n\n    PreconditionSSOR<SparseMatrix<double>> preconditioner; \n    preconditioner.initialize(system_matrix, 1.2); \n\n    cg.solve(system_matrix, solution, system_rhs, preconditioner); \n\n    constraints.distribute(solution); \n  } \n\n//  @sect4{LaplaceProblem::postprocess}  \n\n// \u89e3\u5b8c\u7ebf\u6027\u7cfb\u7edf\u540e\uff0c\u6211\u4eec\u8981\u5bf9\u89e3\u8fdb\u884c\u540e\u5904\u7406\u3002\u5728\u8fd9\u91cc\uff0c\u6211\u4eec\u6240\u505a\u7684\u5c31\u662f\u4f30\u8ba1\u8bef\u5dee\uff0c\u4f30\u8ba1\u89e3\u7684\u5c40\u90e8\u5e73\u6ed1\u5ea6\uff0c\u5982\u4ecb\u7ecd\u4e2d\u6240\u8ff0\uff0c\u7136\u540e\u5199\u51fa\u56fe\u5f62\u8f93\u51fa\uff0c\u6700\u540e\u6839\u636e\u4e4b\u524d\u8ba1\u7b97\u7684\u6307\u6807\u7ec6\u5316 $h$ \u548c $p$ \u4e2d\u7684\u7f51\u683c\u3002\u6211\u4eec\u5728\u540c\u4e00\u4e2a\u51fd\u6570\u4e2d\u5b8c\u6210\u8fd9\u4e00\u5207\uff0c\u56e0\u4e3a\u6211\u4eec\u5e0c\u671b\u4f30\u8ba1\u7684\u8bef\u5dee\u548c\u5e73\u6ed1\u5ea6\u6307\u6807\u4e0d\u4ec5\u7528\u4e8e\u7ec6\u5316\uff0c\u800c\u4e14\u8fd8\u5305\u62ec\u5728\u56fe\u5f62\u8f93\u51fa\u4e2d\u3002\n\n  template <int dim> \n  void LaplaceProblem<dim>::postprocess(const unsigned int cycle) \n  { \n\n// \u8ba9\u6211\u4eec\u5f00\u59cb\u8ba1\u7b97\u4f30\u8ba1\u7684\u8bef\u5dee\u548c\u5e73\u6ed1\u5ea6\u6307\u6807\uff0c\u8fd9\u4e24\u4e2a\u6307\u6807\u5bf9\u4e8e\u6211\u4eec\u4e09\u89d2\u6d4b\u91cf\u7684\u6bcf\u4e2a\u6d3b\u52a8\u5355\u5143\u6765\u8bf4\u90fd\u662f\u4e00\u4e2a\u6570\u5b57\u3002\u5bf9\u4e8e\u8bef\u5dee\u6307\u6807\uff0c\u6211\u4eec\u4e00\u5982\u65e2\u5f80\u5730\u4f7f\u7528KellyErrorEstimator\u7c7b\u3002\n\n    Vector<float> estimated_error_per_cell(triangulation.n_active_cells()); \n    KellyErrorEstimator<dim>::estimate( \n      dof_handler, \n      face_quadrature_collection, \n      std::map<types::boundary_id, const Function<dim> *>(), \n      solution, \n      estimated_error_per_cell); \n\n// \u4f30\u8ba1\u5e73\u6ed1\u5ea6\u662f\u7528\u4ecb\u7ecd\u4e2d\u6240\u8ff0\u7684\u8870\u51cf\u81a8\u80c0\u7cfb\u6570\u7684\u65b9\u6cd5\u8fdb\u884c\u7684\u3002\u6211\u4eec\u9996\u5148\u9700\u8981\u521b\u5efa\u4e00\u4e2a\u5bf9\u8c61\uff0c\u80fd\u591f\u5c06\u6bcf\u4e00\u4e2a\u5355\u5143\u4e0a\u7684\u6709\u9650\u5143\u89e3\u8f6c\u5316\u4e3a\u4e00\u4e32\u5085\u91cc\u53f6\u7ea7\u6570\u7cfb\u6570\u3002SmoothnessEstimator\u547d\u540d\u7a7a\u95f4\u4e3a\u8fd9\u6837\u4e00\u4e2a FESeries::Fourier \u5bf9\u8c61\u63d0\u4f9b\u4e86\u4e00\u4e2a\u5de5\u5382\u51fd\u6570\uff0c\u5b83\u4e3a\u4f30\u8ba1\u5e73\u6ed1\u5ea6\u7684\u8fc7\u7a0b\u8fdb\u884c\u4e86\u4f18\u5316\u3002\u7136\u540e\u5728\u6700\u540e\u4e00\u4e2a\u51fd\u6570\u4e2d\u5b9e\u9645\u786e\u5b9a\u6bcf\u4e2a\u5355\u72ec\u5355\u5143\u4e0a\u7684\u5085\u91cc\u53f6\u7cfb\u6570\u7684\u8870\u51cf\u60c5\u51b5\u3002\n\n    Vector<float> smoothness_indicators(triangulation.n_active_cells()); \n    FESeries::Fourier<dim> fourier = \n      SmoothnessEstimator::Fourier::default_fe_series(fe_collection); \n    SmoothnessEstimator::Fourier::coefficient_decay(fourier, \n                                                    dof_handler, \n                                                    solution, \n                                                    smoothness_indicators); \n\n// \u63a5\u4e0b\u6765\u6211\u4eec\u8981\u751f\u6210\u56fe\u5f62\u8f93\u51fa\u3002\u9664\u4e86\u4e0a\u9762\u5f97\u51fa\u7684\u4e24\u4e2a\u4f30\u8ba1\u91cf\u4e4b\u5916\uff0c\u6211\u4eec\u8fd8\u60f3\u8f93\u51fa\u7f51\u683c\u4e0a\u6bcf\u4e2a\u5143\u7d20\u6240\u4f7f\u7528\u7684\u6709\u9650\u5143\u7684\u591a\u9879\u5f0f\u7a0b\u5ea6\u3002\n\n// \u8981\u505a\u5230\u8fd9\u4e00\u70b9\uff0c\u6211\u4eec\u9700\u8981\u5728\u6240\u6709\u5355\u5143\u4e0a\u5faa\u73af\uff0c\u7528  <code>cell-@>active_fe_index()</code>  \u8f6e\u8be2\u5b83\u4eec\u7684\u6d3b\u52a8\u6709\u9650\u5143\u7d22\u5f15\u3002\u7136\u540e\u6211\u4eec\u4f7f\u7528\u8fd9\u4e2a\u64cd\u4f5c\u7684\u7ed3\u679c\uff0c\u5728\u6709\u9650\u5143\u96c6\u5408\u4e2d\u67e5\u8be2\u5177\u6709\u8be5\u7d22\u5f15\u7684\u6709\u9650\u5143\uff0c\u6700\u540e\u786e\u5b9a\u8be5\u5143\u7d20\u7684\u591a\u9879\u5f0f\u7a0b\u5ea6\u3002\u6211\u4eec\u5c06\u7ed3\u679c\u653e\u5165\u4e00\u4e2a\u77e2\u91cf\uff0c\u6bcf\u4e2a\u5355\u5143\u6709\u4e00\u4e2a\u5143\u7d20\u3002DataOut\u7c7b\u8981\u6c42\u8fd9\u662f\u4e00\u4e2a <code>float</code> or <code>double</code> \u7684\u5411\u91cf\uff0c\u5c3d\u7ba1\u6211\u4eec\u7684\u503c\u90fd\u662f\u6574\u6570\uff0c\u6240\u4ee5\u6211\u4eec\u5c31\u7528\u8fd9\u4e2a\u5411\u91cf\u3002\n\n    { \n      Vector<float> fe_degrees(triangulation.n_active_cells()); \n      for (const auto &cell : dof_handler.active_cell_iterators()) \n        fe_degrees(cell->active_cell_index()) = \n          fe_collection[cell->active_fe_index()].degree; \n\n// \u73b0\u5728\u6709\u4e86\u6240\u6709\u7684\u6570\u636e\u5411\u91cf--\u89e3\u51b3\u65b9\u6848\u3001\u4f30\u8ba1\u8bef\u5dee\u548c\u5e73\u6ed1\u5ea6\u6307\u6807\u4ee5\u53ca\u6709\u9650\u5143\u5ea6--\u6211\u4eec\u521b\u5efa\u4e00\u4e2a\u7528\u4e8e\u56fe\u5f62\u8f93\u51fa\u7684DataOut\u5bf9\u8c61\u5e76\u9644\u52a0\u6240\u6709\u6570\u636e\u3002\n\n      DataOut<dim> data_out; \n\n      data_out.attach_dof_handler(dof_handler); \n      data_out.add_data_vector(solution, \"solution\"); \n      data_out.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// \u751f\u6210\u8f93\u51fa\u7684\u6700\u540e\u4e00\u6b65\u662f\u786e\u5b9a\u4e00\u4e2a\u6587\u4ef6\u540d\uff0c\u6253\u5f00\u6587\u4ef6\uff0c\u5e76\u5c06\u6570\u636e\u5199\u5165\u5176\u4e2d\uff08\u8fd9\u91cc\uff0c\u6211\u4eec\u4f7f\u7528VTK\u683c\u5f0f\uff09\u3002\n\n      const std::string filename = \n        \"solution-\" + Utilities::int_to_string(cycle, 2) + \".vtk\"; \n      std::ofstream output(filename); \n      data_out.write_vtk(output); \n    } \n\n// \u5728\u8fd9\u4e4b\u540e\uff0c\u6211\u4eec\u60f3\u5728 $h$ \u548c $p$ \u4e24\u4e2a\u5730\u65b9\u5b9e\u9645\u7ec6\u5316\u7f51\u683c\u3002\u6211\u4eec\u8981\u505a\u7684\u662f\uff1a\u9996\u5148\uff0c\u6211\u4eec\u7528\u4f30\u8ba1\u7684\u8bef\u5dee\u6765\u6807\u8bb0\u90a3\u4e9b\u8bef\u5dee\u6700\u5927\u7684\u5355\u5143\uff0c\u4ee5\u4fbf\u8fdb\u884c\u7ec6\u5316\u3002\u8fd9\u5c31\u662f\u6211\u4eec\u4e00\u76f4\u4ee5\u6765\u7684\u505a\u6cd5\u3002\n\n    { \n      GridRefinement::refine_and_coarsen_fixed_number(triangulation, \n                                                      estimated_error_per_cell, \n                                                      0.3, \n                                                      0.03); \n\n// \u63a5\u4e0b\u6765\u6211\u4eec\u8981\u5f04\u6e05\u695a\u54ea\u4e9b\u88ab\u6807\u8bb0\u4e3a\u7ec6\u5316\u7684\u5355\u5143\u683c\u5b9e\u9645\u4e0a\u5e94\u8be5\u589e\u52a0 $p$ \u800c\u4e0d\u662f\u51cf\u5c11 $h$ \u3002\u6211\u4eec\u5728\u8fd9\u91cc\u9009\u62e9\u7684\u7b56\u7565\u662f\uff0c\u6211\u4eec\u67e5\u770b\u90a3\u4e9b\u88ab\u6807\u8bb0\u4e3a\u7ec6\u5316\u7684\u5355\u5143\u683c\u7684\u5e73\u6ed1\u5ea6\u6307\u6807\uff0c\u5e76\u4e3a\u90a3\u4e9b\u5e73\u6ed1\u5ea6\u5927\u4e8e\u67d0\u4e2a\u76f8\u5bf9\u9608\u503c\u7684\u5355\u5143\u683c\u589e\u52a0 $p$ \u3002\u6362\u53e5\u8bdd\u8bf4\uff0c\u5bf9\u4e8e\u6bcf\u4e00\u4e2a(i)\u7ec6\u5316\u6807\u5fd7\u88ab\u8bbe\u7f6e\uff0c(ii)\u5e73\u6ed1\u5ea6\u6307\u6807\u5927\u4e8e\u9608\u503c\uff0c\u4ee5\u53ca(iii)\u6211\u4eec\u5728\u6709\u9650\u5143\u96c6\u5408\u4e2d\u4ecd\u6709\u4e00\u4e2a\u591a\u9879\u5f0f\u5ea6\u6570\u9ad8\u4e8e\u5f53\u524d\u5ea6\u6570\u7684\u6709\u9650\u5143\u7684\u5355\u5143\uff0c\u6211\u4eec\u5c06\u5206\u914d\u4e00\u4e2a\u672a\u6765\u7684FE\u6307\u6570\uff0c\u5bf9\u5e94\u4e8e\u4e00\u4e2a\u6bd4\u5f53\u524d\u5ea6\u6570\u9ad8\u4e00\u7684\u591a\u9879\u5f0f\u3002\u4e0b\u9762\u7684\u51fd\u6570\u6b63\u662f\u80fd\u591f\u505a\u5230\u8fd9\u4e00\u70b9\u3002\u5728\u6ca1\u6709\u66f4\u597d\u7684\u7b56\u7565\u7684\u60c5\u51b5\u4e0b\uff0c\u6211\u4eec\u5c06\u901a\u8fc7\u5728\u6807\u8bb0\u4e3a\u7ec6\u5316\u7684\u5355\u5143\u4e0a\u7684\u6700\u5c0f\u548c\u6700\u5927\u5e73\u6ed1\u5ea6\u6307\u6807\u4e4b\u95f4\u8fdb\u884c\u63d2\u503c\u6765\u8bbe\u7f6e\u9608\u503c\u3002\u7531\u4e8e\u89d2\u90e8\u5947\u70b9\u5177\u6709\u5f88\u5f3a\u7684\u5c40\u90e8\u6027\uff0c\u6211\u4eec\u5c06\u652f\u6301 $p$ \u3002\n\n// - \u800c\u4e0d\u662f $h$  - \u7cbe\u7ec6\u5316\u7684\u6570\u91cf\u3002\u6211\u4eec\u901a\u8fc7\u8bbe\u7f6e0.2\u7684\u5c0f\u63d2\u503c\u7cfb\u6570\uff0c\u4ee5\u4f4e\u95e8\u69db\u5b9e\u73b0\u8fd9\u4e00\u70b9\u3002\u7528\u540c\u6837\u7684\u65b9\u6cd5\uff0c\u6211\u4eec\u5904\u7406\u90a3\u4e9b\u8981\u88ab\u7c97\u5316\u7684\u5355\u5143\uff0c\u5f53\u5b83\u4eec\u7684\u5e73\u6ed1\u5ea6\u6307\u6807\u4f4e\u4e8e\u5728\u8981\u7c97\u5316\u7684\u5355\u5143\u4e0a\u786e\u5b9a\u7684\u76f8\u5e94\u9608\u503c\u65f6\uff0c\u51cf\u5c11\u5b83\u4eec\u7684\u591a\u9879\u5f0f\u7a0b\u5ea6\u3002\n\n      hp::Refinement::p_adaptivity_from_relative_threshold( \n        dof_handler, smoothness_indicators, 0.2, 0.2); \n\n// \u4e0a\u9762\u7684\u51fd\u6570\u53ea\u51b3\u5b9a\u4e86\u591a\u9879\u5f0f\u7a0b\u5ea6\u662f\u5426\u4f1a\u901a\u8fc7\u672a\u6765\u7684FE\u6307\u6570\u53d1\u751f\u53d8\u5316\uff0c\u4f46\u5e76\u6ca1\u6709\u64cd\u4f5c $h$  -\u7ec6\u5316\u6807\u5fd7\u3002\u56e0\u6b64\uff0c\u5bf9\u4e8e\u88ab\u6807\u8bb0\u4e3a\u4e24\u4e2a\u7ec6\u5316\u7c7b\u522b\u7684\u5355\u5143\u683c\uff0c\u6211\u4eec\u66f4\u503e\u5411\u4e8e $p$  \u3002\n\n// \u800c\u4e0d\u662f $h$  -\u7ec6\u5316\u3002\u4e0b\u9762\u7684\u51fd\u6570\u8c03\u7528\u786e\u4fdd\u53ea\u6709 $p$ \u4e2d\u7684\u4e00\u4e2a\n\n// - \u6216  $h$  - \u7cbe\u70bc\u4e2d\u7684\u4e00\u79cd\uff0c\u800c\u4e0d\u662f\u540c\u65f6\u5b9e\u65bd\u4e24\u79cd\u3002\n\n      hp::Refinement::choose_p_over_h(dof_handler); \n\n// \u5bf9\u4e8e\u7f51\u683c\u81ea\u9002\u5e94\u7ec6\u5316\uff0c\u6211\u4eec\u901a\u8fc7\u8c03\u7528 Triangulation::prepare_coarsening_and_refinement(). \u5c06\u76f8\u90bb\u5355\u5143\u7684\u7ec6\u5316\u6c34\u5e73\u5dee\u9650\u5236\u4e3a1\u6765\u786e\u4fdd2:1\u7684\u7f51\u683c\u5e73\u8861\u3002 \u6211\u4eec\u5e0c\u671b\u5bf9\u76f8\u90bb\u5355\u5143\u7684p\u6c34\u5e73\u5b9e\u73b0\u7c7b\u4f3c\u7684\u6548\u679c\uff1a\u672a\u6765\u6709\u9650\u5143\u7684\u6c34\u5e73\u5dee\u4e0d\u5141\u8bb8\u8d85\u8fc7\u6307\u5b9a\u7684\u5dee\u3002\u901a\u8fc7\u5176\u9ed8\u8ba4\u53c2\u6570\uff0c\u8c03\u7528 hp::Refinement::limit_p_level_difference() \u53ef\u4ee5\u786e\u4fdd\u5b83\u4eec\u7684\u7ea7\u5dee\u88ab\u9650\u5236\u57281\u4ee5\u5185\u3002\u8fd9\u4e0d\u4e00\u5b9a\u4f1a\u51cf\u5c11\u57df\u4e2d\u7684\u60ac\u6302\u8282\u70b9\u7684\u6570\u91cf\uff0c\u4f46\u53ef\u4ee5\u786e\u4fdd\u9ad8\u9636\u591a\u9879\u5f0f\u4e0d\u4f1a\u88ab\u9650\u5236\u5728\u9762\u7684\u4f4e\u5f97\u591a\u7684\u591a\u9879\u5f0f\u4e0a\uff0c\u4f8b\u5982\u4e94\u9636\u591a\u9879\u5f0f\u5230\u4e8c\u9636\u591a\u9879\u5f0f\u3002\n\n      triangulation.prepare_coarsening_and_refinement(); \n      hp::Refinement::limit_p_level_difference(dof_handler); \n\n// \u5728\u8fd9\u4e2a\u8fc7\u7a0b\u7ed3\u675f\u540e\uff0c\u6211\u4eec\u518d\u7ec6\u5316\u7f51\u683c\u3002\u5728\u8fd9\u4e2a\u8fc7\u7a0b\u4e2d\uff0c\u6b63\u5728\u8fdb\u884c\u5206\u5272\u7684\u5355\u5143\u7684\u5b50\u5355\u5143\u4f1a\u7ee7\u627f\u5176\u6bcd\u5355\u5143\u7684\u6709\u9650\u5143\u7d22\u5f15\u3002\u6b64\u5916\uff0c\u672a\u6765\u7684\u6709\u9650\u5143\u6307\u6570\u5c06\u53d8\u6210\u6d3b\u52a8\u7684\uff0c\u56e0\u6b64\u65b0\u7684\u6709\u9650\u5143\u5c06\u5728\u4e0b\u4e00\u6b21\u8c03\u7528 DoFHandler::distribute_dofs(). \u540e\u88ab\u5206\u914d\u7ed9\u5355\u5143\u3002\n      triangulation.execute_coarsening_and_refinement(); \n    } \n  } \n// @sect4{LaplaceProblem::create_coarse_grid}  \n\n// \u5728\u521b\u5efa\u521d\u59cb\u7f51\u683c\u65f6\uff0c\u4f1a\u7528\u5230\u4e0b\u9762\u8fd9\u4e2a\u51fd\u6570\u3002\u6211\u4eec\u60f3\u8981\u521b\u5efa\u7684\u7f51\u683c\u5b9e\u9645\u4e0a\u4e0e step-14 \u4e2d\u7684\u7f51\u683c\u7c7b\u4f3c\uff0c\u5373\u4e2d\u95f4\u6709\u65b9\u5b54\u7684\u65b9\u5f62\u57df\u3002\u5b83\u53ef\u4ee5\u7531\u5b8c\u5168\u76f8\u540c\u7684\u51fd\u6570\u751f\u6210\u3002\u7136\u800c\uff0c\u7531\u4e8e\u5b83\u7684\u5b9e\u73b0\u53ea\u662f2d\u60c5\u51b5\u4e0b\u7684\u4e00\u79cd\u7279\u6b8a\u5316\uff0c\u6211\u4eec\u5c06\u4ecb\u7ecd\u4e00\u79cd\u4e0d\u540c\u7684\u65b9\u6cd5\u6765\u521b\u5efa\u8fd9\u4e2a\u57df\uff0c\u5b83\u662f\u72ec\u7acb\u4e8e\u7ef4\u5ea6\u7684\u3002\n\n// \u6211\u4eec\u9996\u5148\u521b\u5efa\u4e00\u4e2a\u6709\u8db3\u591f\u5355\u5143\u7684\u8d85\u7acb\u65b9\u4f53\u4e09\u89d2\u5f62\uff0c\u8fd9\u6837\u5b83\u5c31\u5df2\u7ecf\u5305\u542b\u4e86\u6211\u4eec\u60f3\u8981\u7684\u57df $[-1,1]^d$ \uff0c\u5e76\u7ec6\u5206\u4e3a $4^d$ \u5355\u5143\u3002\u7136\u540e\uff0c\u6211\u4eec\u901a\u8fc7\u6d4b\u8bd5\u6bcf\u4e2a\u5355\u5143\u4e0a\u9876\u70b9\u7684\u5750\u6807\u503c\u6765\u79fb\u9664\u57df\u4e2d\u5fc3\u7684\u90a3\u4e9b\u5355\u5143\u3002\u6700\u540e\uff0c\u6211\u4eec\u50cf\u5f80\u5e38\u4e00\u6837\u5bf9\u5982\u6b64\u521b\u5efa\u7684\u7f51\u683c\u8fdb\u884c\u5168\u5c40\u7ec6\u5316\u3002\n\n  template <int dim> \n  void LaplaceProblem<dim>::create_coarse_grid() \n  { \n    Triangulation<dim> cube; \n    GridGenerator::subdivided_hyper_cube(cube, 4, -1., 1.); \n\n    std::set<typename Triangulation<dim>::active_cell_iterator> cells_to_remove; \n    for (const auto &cell : cube.active_cell_iterators()) \n      for (unsigned int v = 0; v < GeometryInfo<dim>::vertices_per_cell; ++v) \n        if (cell->vertex(v).square() < .1) \n          cells_to_remove.insert(cell); \n\n    GridGenerator::create_triangulation_with_removed_cells(cube, \n                                                           cells_to_remove, \n                                                           triangulation); \n\n    triangulation.refine_global(3); \n  } \n\n//  @sect4{LaplaceProblem::run}  \n\n// \u8fd9\u4e2a\u51fd\u6570\u5b9e\u73b0\u4e86\u7a0b\u5e8f\u7684\u903b\u8f91\uff0c\u5c31\u50cf\u4ee5\u524d\u5927\u591a\u6570\u7a0b\u5e8f\u4e2d\u7684\u76f8\u5e94\u51fd\u6570\u4e00\u6837\uff0c\u4f8b\u5982\u89c1  step-6  \u3002\n\n// \u57fa\u672c\u4e0a\uff0c\u5b83\u5305\u542b\u4e86\u81ea\u9002\u5e94\u5faa\u73af\uff1a\u5728\u7b2c\u4e00\u6b21\u8fed\u4ee3\u4e2d\u521b\u5efa\u4e00\u4e2a\u7c97\u7565\u7684\u7f51\u683c\uff0c\u7136\u540e\u5efa\u7acb\u7ebf\u6027\u7cfb\u7edf\uff0c\u5bf9\u5176\u8fdb\u884c\u7ec4\u5408\uff0c\u6c42\u89e3\uff0c\u5e76\u5bf9\u89e3\u8fdb\u884c\u540e\u5904\u7406\uff0c\u5305\u62ec\u7f51\u683c\u7ec6\u5316\u3002\u7136\u540e\u518d\u91cd\u65b0\u5f00\u59cb\u3002\u540c\u65f6\uff0c\u4e5f\u4e3a\u90a3\u4e9b\u76ef\u7740\u5c4f\u5e55\u8bd5\u56fe\u5f04\u6e05\u695a\u7a0b\u5e8f\u662f\u5e72\u4ec0\u4e48\u7684\u4eba\u8f93\u51fa\u4e00\u4e9b\u4fe1\u606f\u3002\n\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() << std::endl \n                  << \"   Number of degrees of freedom: \" << dof_handler.n_dofs() \n                  << std::endl \n                  << \"   Number of constraints       : \" \n                  << constraints.n_constraints() << std::endl; \n\n        assemble_system(); \n        solve(); \n        postprocess(cycle); \n      } \n  } \n} // namespace Step27 \n// @sect3{The main function}  \n\n// \u4e3b\u51fd\u6570\u4ecd\u7136\u662f\u6211\u4eec\u4e4b\u524d\u7684\u7248\u672c\uff1a\u5c06\u521b\u5efa\u548c\u8fd0\u884c\u4e00\u4e2a\u4e3b\u7c7b\u7684\u5bf9\u8c61\u5305\u88c5\u6210\u4e00\u4e2a <code>try</code> \u5757\uff0c\u5e76\u6355\u6349\u4efb\u4f55\u629b\u51fa\u7684\u5f02\u5e38\uff0c\u4ece\u800c\u5728\u51fa\u73b0\u95ee\u9898\u65f6\u4ea7\u751f\u6709\u610f\u4e49\u7684\u8f93\u51fa\u3002\n\nint main() \n{ \n  try \n    { \n      using namespace Step27; \n\n      LaplaceProblem<2> laplace_problem; \n      laplace_problem.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  return 0; \n} \n\n", "meta": {"hexsha": "d74f6002691e16ad2865ed25707e3b3d63bc1eb4", "size": 16346, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-27/step-27.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-27/step-27.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-27/step-27.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": 36.0044052863, "max_line_length": 338, "alphanum_fraction": 0.6369142298, "num_tokens": 6411, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.721743200312399, "lm_q1q2_score": 0.47266581760658655}}
{"text": "#include <memory>\n#include <vector>\n\n#include <boost/multiprecision/cpp_int.hpp>\n\n#include \"block_system.hpp\"\n#include \"bsgs.hpp\"\n#include \"dbg.hpp\"\n#include \"perm.hpp\"\n#include \"perm_group.hpp\"\n#include \"perm_set.hpp\"\n\nnamespace mpsym\n{\n\nnamespace internal\n{\n\nstd::vector<PermGroup> PermGroup::wreath_decomposition() const\n{\n  DBG(DEBUG) << \"Finding wreath product decomposition for\";\n  DBG(DEBUG) << *this;\n\n  for (BlockSystem const &block_system : BlockSystem::non_trivial(*this)) {\n    DBG(TRACE) << \"Considering block system:\";\n    DBG(TRACE) << block_system;\n\n    // determine block permuter subgroup\n    PermGroup block_permuter(block_system.size(),\n                             block_system.block_permuter(generators()));\n\n    DBG(TRACE) << \"Block permuter is:\";\n    DBG(TRACE) << block_permuter;\n\n    // determine block stabilizer subgroups\n    auto stabilizers(wreath_decomp_find_stabilizers(\n      block_system, block_permuter));\n\n    if (stabilizers.empty())\n      continue;\n\n    // check if a monomorphism can be found heuristically\n    auto block_permuter_image(wreath_decomp_construct_block_permuter_image(\n      block_system, block_permuter));\n\n    bool found_monomorphism(wreath_decomp_reconstruct_block_permuter(\n      block_system, block_permuter, block_permuter_image));\n\n    if (!found_monomorphism)\n      break;\n\n    // construct the wreath decomposition\n    std::vector<PermGroup> decomposition(block_system.size() + 1u);\n\n    decomposition[0] = PermGroup(degree(), block_permuter_image);\n    for (unsigned i = 0u; i < block_system.size(); ++i)\n      decomposition[i + 1u] = stabilizers[i];\n\n    DBG(DEBUG) << \"=> Found wreath product decomposition:\";\n#ifndef NDEBUG\n    for (PermGroup const &pg : decomposition)\n      DBG(DEBUG) << pg;\n#endif\n\n    return decomposition;\n  }\n\n  DBG(DEBUG) << \"=> No wreath product decomposition found\";\n  return {};\n}\n\nstd::vector<PermGroup> PermGroup::wreath_decomp_find_stabilizers(\n  BlockSystem const &block_system,\n  PermGroup const &block_permuter) const\n{\n  using boost::multiprecision::pow;\n\n  std::vector<PermGroup> stabilizers(block_system.size());\n\n  auto create_stabilizer = [&](unsigned i) {\n    auto block(block_system[i]);\n\n    // find stabilizer subgroup generators\n    auto stabilizer_generators(\n      BlockSystem::block_stabilizers(generators(), block));\n\n    // restrict stabilizer subgroup generators to block\n    PermSet stabilizer_generators_restricted;\n    for (Perm const &gen : stabilizer_generators) {\n      auto gen_restricted(gen.restricted(block.begin(), block.end()));\n\n      if (!gen_restricted.id())\n        stabilizer_generators_restricted.insert(gen_restricted);\n    }\n\n    // construct stabilizer subgroup\n    stabilizers[i] = PermGroup(degree(), stabilizer_generators_restricted);\n\n    DBG(TRACE) << \"Block stabilizer of \" << block_system[i] << \":\";\n    DBG(TRACE) << stabilizers[i];\n  };\n\n  // determine stabilizer subgroup of first block\n  create_stabilizer(0);\n\n  // skip blocksystem if order equality not fullfilled\n  BSGS::order_type expected_order = pow(\n    stabilizers[0].order(), block_system.size()) * block_permuter.order();\n\n  if (_order != expected_order) {\n    DBG(TRACE) << \"Group order equality not satisfied\";\n    return {};\n  }\n\n  // determine stabilizers subgroups of remaining blocks\n  for (unsigned i = 1u; i < block_system.size(); ++i)\n    create_stabilizer(i);\n\n  return stabilizers;\n}\n\nPermSet PermGroup::wreath_decomp_construct_block_permuter_image(\n  BlockSystem const &block_system,\n  PermGroup const &block_permuter) const\n{\n  PermSet block_permuter_image;\n\n  for (Perm const &gen : block_permuter.generators()) {\n    std::vector<unsigned> perm(degree());\n\n    for (unsigned i = 0u; i < block_system.size(); ++i) {\n      auto block(block_system[i]);\n\n      for (auto j = 0u; j < block.size(); ++j)\n        perm[block[j] - 1u] = block_system[gen[i + 1u] - 1u][j];\n    }\n\n    block_permuter_image.insert(Perm(perm));\n  }\n\n  DBG(TRACE) << \"Heuristic monomorphism image generators:\";\n  DBG(TRACE) << block_permuter_image;\n\n  return block_permuter_image;\n}\n\nbool PermGroup::wreath_decomp_reconstruct_block_permuter(\n  BlockSystem const &block_system,\n  PermGroup const &block_permuter,\n  PermSet const &block_permuter_image) const\n{\n  bool found_monomorphism = true;\n\n  PermSet block_permuter_reconstruction;\n\n  for (Perm const &gen : block_permuter_image) {\n    std::vector<unsigned> perm(block_system.size());\n\n    for (unsigned i = 0u; i < block_system.size(); ++i)\n      perm[i] = block_system.block_index(gen[block_system[i][0]]) + 1u;\n\n    Perm reconstructed_gen(perm);\n\n    if (!block_permuter.contains_element(reconstructed_gen)) {\n      found_monomorphism = false;\n      break;\n    }\n\n    block_permuter_reconstruction.insert(reconstructed_gen);\n  }\n\n  DBG(TRACE) << \"Block permuter reconstruction yields generators:\";\n  DBG(TRACE) << block_permuter_reconstruction;\n\n  if (found_monomorphism) {\n    if (PermGroup(block_system.size(), block_permuter_reconstruction).order()\n        != block_permuter.order())\n      found_monomorphism = false;\n  }\n\n  if (!found_monomorphism) {\n    DBG(WARN) << \"Wreath decomposition exists but was not found by heuristic\";\n  }\n\n  return found_monomorphism;\n}\n\n} // namespace internal\n\n} // namespace mpsym\n", "meta": {"hexsha": "b7891b23e40556647599d3c7170078638dca408d", "size": 5263, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/perm_group_wreath_decomp.cpp", "max_stars_repo_name": "goens/TUD_computational_group_theory", "max_stars_repo_head_hexsha": "3f4703cae1ac049089db23eafc321e8daca2d99d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-09-10T09:31:17.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-14T15:19:20.000Z", "max_issues_repo_path": "source/perm_group_wreath_decomp.cpp", "max_issues_repo_name": "goens/TUD_computational_group_theory", "max_issues_repo_head_hexsha": "3f4703cae1ac049089db23eafc321e8daca2d99d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2020-06-11T07:25:08.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-19T09:07:50.000Z", "max_forks_repo_path": "source/perm_group_wreath_decomp.cpp", "max_forks_repo_name": "goens/TUD_computational_group_theory", "max_forks_repo_head_hexsha": "3f4703cae1ac049089db23eafc321e8daca2d99d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-09-10T19:31:57.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-09T13:17:50.000Z", "avg_line_length": 27.554973822, "max_line_length": 78, "alphanum_fraction": 0.7043511305, "num_tokens": 1304, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.6334102775181399, "lm_q1q2_score": 0.4726121066427135}}
{"text": "#include \"TestScheme.h\"\n\n#include <NTL/BasicThreadPool.h>\n#include <NTL/RR.h>\n#include <NTL/ZZ.h>\n\n#include \"Common.h\"\n#include \"Ciphertext.h\"\n#include \"EvaluatorUtils.h\"\n#include \"NumUtils.h\"\n#include \"Scheme.h\"\n#include \"SchemeAlgo.h\"\n#include \"SecretKey.h\"\n#include \"StringUtils.h\"\n#include \"TimeUtils.h\"\n#include \"Context.h\"\n#include \"SerializationUtils.h\"\n\nusing namespace std;\nusing namespace NTL;\n\n\n//----------------------------------------------------------------------------------\n//   STANDARD TESTS\n//----------------------------------------------------------------------------------\n\n\nvoid TestScheme::testEncodeBatch(long logN, long logQ, long logp, long logSlots) {\n\tcout << \"!!! START TEST ENCODE BATCH !!!\" << endl;\n\t//-----------------------------------------\n\tTimeUtils timeutils;\n\tContext context(logN, logQ);\n\tSecretKey secretKey(logN);\n\tScheme scheme(secretKey, context);\n\t//-----------------------------------------\n\tsrand(time(NULL));\n\t//-----------------------------------------\n\tlong slots = (1 << logSlots);\n\tcomplex<double>* mvec = EvaluatorUtils::randomComplexArray(slots);\n\n\ttimeutils.start(\"Encrypt batch\");\n\tCiphertext cipher = scheme.encrypt(mvec, slots, logp, logQ);\n\ttimeutils.stop(\"Encrypt batch\");\n\n\ttimeutils.start(\"Decrypt batch\");\n\tcomplex<double>* dvec = scheme.decrypt(secretKey, cipher);\n\ttimeutils.stop(\"Decrypt batch\");\n\n\tStringUtils::showcompare(mvec, dvec, slots, \"val\");\n\n\tcout << \"!!! END TEST ENCODE BATCH !!!\" << endl;\n}\n\nvoid TestScheme::testEncodeSingle(long logN, long logQ, long logp, bool isComplex) {\n\tcout << \"!!! START TEST ENCODE SINGLE !!!\" << endl;\n\t//-----------------------------------------\n\tTimeUtils timeutils;\n\tContext context(logN, logQ);\n\tSecretKey secretKey(logN);\n\tScheme scheme(secretKey, context);\n\t//-----------------------------------------\n\tsrand(time(NULL));\n\t//-----------------------------------------\n\tcomplex<double> mval = EvaluatorUtils::randomComplex();\n\n\ttimeutils.start(\"Encrypt Single\");\n\tCiphertext cipher = scheme.encryptSingle(mval, logp, logQ);\n\ttimeutils.stop(\"Encrypt Single\");\n\n\ttimeutils.start(\"Decrypt Single\");\n\tcomplex<double> dval = scheme.decryptSingle(secretKey, cipher);\n\ttimeutils.stop(\"Decrypt Single\");\n\n\tStringUtils::showcompare(mval, dval, \"val\");\n\n\tcout << \"!!! END TEST ENCODE SINGLE !!!\" << endl;\n}\n\nvoid TestScheme::testBasic(long logN, long logQ, long logp, long logSlots) {\n\tcout << \"!!! START TEST BASIC !!!\" << endl;\n\t//-----------------------------------------\n\tTimeUtils timeutils;\n\tContext context(logN, logQ);\n\tSecretKey secretKey(logN);\n\tScheme scheme(secretKey, context);\n\t//-----------------------------------------\n\tsrand(time(NULL));\n\t//-----------------------------------------\n\tlong slots = (1 << logSlots);\n\tcomplex<double>* mvec1 = EvaluatorUtils::randomComplexArray(slots);\n\tcomplex<double>* mvec2 = EvaluatorUtils::randomComplexArray(slots);\n\tcomplex<double>* mvecAdd = new complex<double>[slots];\n\tcomplex<double>* mvecMult = new complex<double>[slots];\n\tfor(long i = 0; i < slots; i++) {\n\t\tmvecAdd[i] = mvec1[i] + mvec2[i];\n\t\tmvecMult[i] = mvec1[i] * mvec2[i];\n\t}\n\n\ttimeutils.start(\"Encrypt two batch\");\n\tCiphertext cipher1 = scheme.encrypt(mvec1, slots, logp, logQ);\n\tCiphertext cipher2 = scheme.encrypt(mvec2, slots, logp, logQ);\n\ttimeutils.stop(\"Encrypt two batch\");\n\n\ttimeutils.start(\"Homomorphic Addition\");\n\tCiphertext addCipher = scheme.add(cipher1, cipher2);\n\ttimeutils.stop(\"Homomorphic Addition\");\n\n\ttimeutils.start(\"Homomorphic Multiplication\");\n\tCiphertext multCipher = scheme.mult(cipher1, cipher2);\n\ttimeutils.stop(\"Homomorphic Multiplication\");\n\n\ttimeutils.start(\"Decrypt batch\");\n\tcomplex<double>* dvecAdd = scheme.decrypt(secretKey, addCipher);\n\tcomplex<double>* dvecMult = scheme.decrypt(secretKey, multCipher);\n\ttimeutils.stop(\"Decrypt batch\");\n\n\tStringUtils::showcompare(mvecAdd, dvecAdd, slots, \"add\");\n\tStringUtils::showcompare(mvecMult, dvecMult, slots, \"mult\");\n}\n\n//-----------------------------------------\n\nvoid TestScheme::testConjugateBatch(long logN, long logQ, long logp, long logSlots) {\n\tcout << \"!!! START TEST CONJUGATE BATCH !!!\" << endl;\n\tTimeUtils timeutils;\n\tContext context(logN, logQ);\n\tSecretKey secretKey(logN);\n\tScheme scheme(secretKey, context);\n\tscheme.addConjKey(secretKey);\n\t//-----------------------------------------\n\tsrand(time(NULL));\n\t//-----------------------------------------\n\tlong slots = (1 << logSlots);\n\tcomplex<double>* mvec = EvaluatorUtils::randomComplexArray(slots);\n\tcomplex<double>* mvecconj = new complex<double>[slots];\n\tfor (long i = 0; i < slots; ++i) {\n\t\tmvecconj[i] = conj(mvec[i]);\n\t}\n\n\tCiphertext cipher = scheme.encrypt(mvec, slots, logp, logQ);\n\n\ttimeutils.start(\"Conjugate batch\");\n\tCiphertext cconj = scheme.conjugate(cipher);\n\ttimeutils.stop(\"Conjugate batch\");\n\n\tcomplex<double>* dvecconj = scheme.decrypt(secretKey, cconj);\n\n\tStringUtils::showcompare(mvecconj, dvecconj, slots, \"conj\");\n\n\tcout << \"!!! END TEST CONJUGATE BATCH !!!\" << endl;\n}\n\nvoid TestScheme::testimultBatch(long logN, long logQ, long logp, long logSlots) {\n\tcout << \"!!! START TEST i MULTIPLICATION BATCH !!!\" << endl;\n\tTimeUtils timeutils;\n\tContext context(logN, logQ);\n\tSecretKey secretKey(logN);\n\tScheme scheme(secretKey, context);\n\t//-----------------------------------------\n\tsrand(time(NULL));\n\t//-----------------------------------------\n\tlong slots = (1 << logSlots);\n\tcomplex<double>* mvec = EvaluatorUtils::randomComplexArray(slots);\n\tcomplex<double>* imvec = new complex<double>[slots];\n\tfor (long i = 0; i < slots; ++i) {\n\t\timvec[i].real(-mvec[i].imag());\n\t\timvec[i].imag(mvec[i].real());\n\t}\n\n\tCiphertext cipher = scheme.encrypt(mvec, slots, logp, logQ);\n\n\ttimeutils.start(\"Multiplication by i batch\");\n\tCiphertext icipher = scheme.imult(cipher);\n\ttimeutils.stop(\"Multiplication by i batch\");\n\n\tcomplex<double>* idvec = scheme.decrypt(secretKey, icipher);\n\n\tStringUtils::showcompare(imvec, idvec, slots, \"imult\");\n\n\tcout << \"!!! END TEST i MULTIPLICATION BATCH !!!\" << endl;\n}\n\nvoid TestScheme::testRotateByPo2Batch(long logN, long logQ, long logp, long logRotSlots, long logSlots, bool isLeft) {\n\tcout << \"!!! START TEST ROTATE BY POWER OF 2 BATCH !!!\" << endl;\n\t//-----------------------------------------\n\tTimeUtils timeutils;\n\tContext context(logN, logQ);\n\tSecretKey secretKey(logN);\n\tScheme scheme(secretKey, context);\n\tscheme.addLeftRotKeys(secretKey);\n\t//-----------------------------------------\n\tsrand(time(NULL));\n\t//-----------------------------------------\n\tlong slots = (1 << logSlots);\n\tlong rotSlots = (1 << logRotSlots);\n\tcomplex<double>* mvec = EvaluatorUtils::randomComplexArray(slots);\n\tCiphertext cipher = scheme.encrypt(mvec, slots, logp, logQ);\n\n\tif(isLeft) {\n\t\ttimeutils.start(\"Left Rotate by power of 2 batch\");\n\t\tscheme.leftRotateByPo2AndEqual(cipher, logRotSlots);\n\t\ttimeutils.stop(\"Left Rotate by power of 2 batch\");\n\t} else {\n\t\ttimeutils.start(\"Right Rotate by power of 2 batch\");\n\t\tscheme.rightRotateByPo2AndEqual(cipher, logRotSlots);\n\t\ttimeutils.stop(\"Right Rotate by power of 2 batch\");\n\t}\n\n\tcomplex<double>* dvec = scheme.decrypt(secretKey, cipher);\n\n\tif(isLeft) {\n\t\tEvaluatorUtils::leftRotateAndEqual(mvec, slots, rotSlots);\n\t} else {\n\t\tEvaluatorUtils::rightRotateAndEqual(mvec, slots, rotSlots);\n\t}\n\n\tStringUtils::showcompare(mvec, dvec, slots, \"rot\");\n\t//-----------------------------------------\n\tcout << \"!!! END TEST ROTATE BY POWER OF 2 BATCH !!!\" << endl;\n}\n\nvoid TestScheme::testRotateBatch(long logN, long logQ, long logp, long rotSlots, long logSlots, bool isLeft) {\n\tcout << \"!!! START TEST ROTATE BATCH !!!\" << endl;\n\t//-----------------------------------------\n\tTimeUtils timeutils;\n\tContext context(logN, logQ);\n\tSecretKey secretKey(logN);\n\tScheme scheme(secretKey, context);\n\tscheme.addLeftRotKeys(secretKey);\n\tscheme.addRightRotKeys(secretKey);\n\t//-----------------------------------------\n\tsrand(time(NULL));\n\t//-----------------------------------------\n\tlong slots = (1 << logSlots);\n\tcomplex<double>* mvec = EvaluatorUtils::randomComplexArray(slots);\n\tCiphertext cipher = scheme.encrypt(mvec, slots, logp, logQ);\n\n\tif(isLeft) {\n\t\ttimeutils.start(\"Left rotate batch\");\n\t\tscheme.leftRotateAndEqual(cipher, rotSlots);\n\t\ttimeutils.stop(\"Left rotate batch\");\n\t} else {\n\t\ttimeutils.start(\"Right rotate batch\");\n\t\tscheme.rightRotateAndEqual(cipher, rotSlots);\n\t\ttimeutils.stop(\"Right rotate batch\");\n\t}\n\n\tcomplex<double>* dvec = scheme.decrypt(secretKey, cipher);\n\n\tif(isLeft) {\n\t\tEvaluatorUtils::leftRotateAndEqual(mvec, slots, rotSlots);\n\t} else {\n\t\tEvaluatorUtils::rightRotateAndEqual(mvec, slots, rotSlots);\n\t}\n\n\tStringUtils::showcompare(mvec, dvec, slots, \"rot\");\n\n\tcout << \"!!! END TEST ROTATE BATCH !!!\" << endl;\n}\n\nvoid TestScheme::testSlotsSum(long logN, long logQ, long logp, long logSlots) {\n\tcout << \"!!! START TEST SLOTS SUM !!!\" << endl;\n\t//-----------------------------------------\n\tTimeUtils timeutils;\n\tContext context(logN, logQ);\n\tSecretKey secretKey(logN);\n\tScheme scheme(secretKey, context);\n\tSchemeAlgo algo(scheme);\n\tscheme.addLeftRotKeys(secretKey);\n\t//-----------------------------------------\n\tsrand(time(NULL));\n\t//-----------------------------------------\n\tlong slots = (1 << logSlots);\n\tcomplex<double>* mvec = EvaluatorUtils::randomComplexArray(slots);\n\tCiphertext cipher = scheme.encrypt(mvec, slots, logp, logQ);\n\n\ttimeutils.start(\"slots sum\");\n\talgo.partialSlotsSumAndEqual(cipher, slots);\n\ttimeutils.stop(\"slots sum\");\n\n\tcomplex<double>* dvec = scheme.decrypt(secretKey, cipher);\n\n\tcomplex<double> msum;\n\tfor (long i = 0; i < slots; ++i) {\n\t\tmsum += mvec[i];\n\t}\n\n\tStringUtils::showcompare(msum, dvec, slots, \"slotsum\");\n\n\tcout << \"!!! END TEST SLOTS SUM !!!\" << endl;\n}\n\n\n//----------------------------------------------------------------------------------\n//   POWER & PRODUCT TESTS\n//----------------------------------------------------------------------------------\n\n\nvoid TestScheme::testPowerOf2Batch(long logN, long logQ, long logp, long logDegree, long logSlots) {\n\tcout << \"!!! START TEST POWER OF 2 BATCH !!!\" << endl;\n\t//-----------------------------------------\n\tTimeUtils timeutils;\n\tContext context(logN, logQ);\n\tSecretKey secretKey(logN);\n\tScheme scheme(secretKey, context);\n\tSchemeAlgo algo(scheme);\n\t//-----------------------------------------\n\tsrand(time(NULL));\n\t//-----------------------------------------\n\tlong slots = 1 << logSlots;\n\tlong degree = 1 << logDegree;\n\tcomplex<double>* mvec = new complex<double>[slots];\n\tcomplex<double>* mpow = new complex<double>[slots];\n\n\tfor (long i = 0; i < slots; ++i) {\n\t\tmvec[i] = EvaluatorUtils::randomCircle();\n\t\tmpow[i] = pow(mvec[i], degree);\n\t}\n\n\tCiphertext cipher = scheme.encrypt(mvec, slots, logp, logQ);\n\n\ttimeutils.start(\"Power of 2 batch\");\n\tCiphertext cpow = algo.powerOf2(cipher, logp, logDegree);\n\ttimeutils.stop(\"Power of 2 batch\");\n\n\tcomplex<double>* dpow = scheme.decrypt(secretKey, cpow);\n\n\tStringUtils::showcompare(mpow, dpow, slots, \"pow2\");\n\n\tcout << \"!!! END TEST POWER OF 2 BATCH !!!\" << endl;\n}\n\n//-----------------------------------------\n\nvoid TestScheme::testPowerBatch(long logN, long logQ, long logp, long degree, long logSlots) {\n\tcout << \"!!! START TEST POWER BATCH !!!\" << endl;\n\t//-----------------------------------------\n\tTimeUtils timeutils;\n\tContext context(logN, logQ);\n\tSecretKey secretKey(logN);\n\tScheme scheme(secretKey, context);\n\tSchemeAlgo algo(scheme);\n\t//-----------------------------------------\n\tsrand(time(NULL));\n\t//-----------------------------------------\n\tlong slots = 1 << logSlots;\n\tcomplex<double>* mvec = EvaluatorUtils::randomCircleArray(slots);\n\tcomplex<double>* mpow = new complex<double>[slots];\n\tfor (long i = 0; i < slots; ++i) {\n\t\tmpow[i] = pow(mvec[i], degree);\n\t}\n\n\tCiphertext cipher = scheme.encrypt(mvec, slots, logp, logQ);\n\n\ttimeutils.start(\"Power batch\");\n\tCiphertext cpow = algo.power(cipher, logp, degree);\n\ttimeutils.stop(\"Power batch\");\n\n\tcomplex<double>* dpow = scheme.decrypt(secretKey, cpow);\n\n\tStringUtils::showcompare(mpow, dpow, slots, \"pow\");\n\n\tcout << \"!!! END TEST POWER BATCH !!!\" << endl;\n}\n\n//-----------------------------------------\n\nvoid TestScheme::testProdOfPo2Batch(long logN, long logQ, long logp, long logDegree, long logSlots) {\n\tcout << \"!!! START TEST PROD OF POWER OF 2 BATCH !!!\" << endl;\n\t//-----------------------------------------\n\tTimeUtils timeutils;\n\tContext context(logN, logQ);\n\tSecretKey secretKey(logN);\n\tScheme scheme(secretKey, context);\n\tSchemeAlgo algo(scheme);\n\t//-----------------------------------------\n\tSetNumThreads(4);\n\t//-----------------------------------------\n\tsrand(time(NULL));\n\t//-----------------------------------------\n\tlong slots = 1 << logSlots;\n\tlong degree = 1 << logDegree;\n\n\tcomplex<double>** mvec = new complex<double>*[degree];\n\tfor (long i = 0; i < degree; ++i) {\n\t\tmvec[i] = EvaluatorUtils::randomCircleArray(slots);\n\t}\n\n\tcomplex<double>* pvec = new complex<double>[slots];\n\tfor (long j = 0; j < slots; ++j) {\n\t\tpvec[j] = mvec[0][j];\n\t\tfor (long i = 1; i < degree; ++i) {\n\t\t\tpvec[j] *= mvec[i][j];\n\t\t}\n\t}\n\n\tCiphertext* cvec = new Ciphertext[degree];\n\tfor (long i = 0; i < degree; ++i) {\n\t\tcvec[i] = scheme.encrypt(mvec[i], slots, logp, logQ);\n\t}\n\n\ttimeutils.start(\"Product of power of 2 batch\");\n\tCiphertext cprod = algo.prodOfPo2(cvec, logp, logDegree);\n\ttimeutils.stop(\"Product of power of 2 batch\");\n\n\tcomplex<double>* dvec = scheme.decrypt(secretKey, cprod);\n\n\tStringUtils::showcompare(pvec, dvec, slots, \"prod\");\n\n\tcout << \"!!! END TEST PROD OF POWER OF 2 BATCH !!!\" << endl;\n}\n\nvoid TestScheme::testProdBatch(long logN, long logQ, long logp, long degree, long logSlots) {\n\tcout << \"!!! START TEST PROD BATCH !!!\" << endl;\n\t//-----------------------------------------\n\tTimeUtils timeutils;\n\tContext context(logN, logQ);\n\tSecretKey secretKey(logN);\n\tScheme scheme(secretKey, context);\n\tSchemeAlgo algo(scheme);\n\t//-----------------------------------------\n\tSetNumThreads(4);\n\t//-----------------------------------------\n\tsrand(time(NULL));\n\t//-----------------------------------------\n\tlong slots = 1 << logSlots;\n\tcomplex<double>** mvec = new complex<double>*[degree];\n\tfor (long i = 0; i < degree; ++i) {\n\t\tmvec[i] = EvaluatorUtils::randomCircleArray(slots);\n\t}\n\n\tcomplex<double>* pvec = new complex<double>[slots];\n\tfor (long j = 0; j < slots; ++j) {\n\t\tpvec[j] = mvec[0][j];\n\t\tfor (long i = 1; i < degree; ++i) {\n\t\t\tpvec[j] *= mvec[i][j];\n\t\t}\n\t}\n\n\tCiphertext* cvec = new Ciphertext[degree];\n\tfor (long i = 0; i < degree; ++i) {\n\t\tcvec[i] = scheme.encrypt(mvec[i], slots, logp, logQ);\n\t}\n\n\ttimeutils.start(\"Product batch\");\n\tCiphertext cprod = algo.prod(cvec, logp, degree);\n\ttimeutils.stop(\"Product batch\");\n\n\tcomplex<double>* dvec = scheme.decrypt(secretKey, cprod);\n\n\tStringUtils::showcompare(pvec, dvec, slots, \"prod\");\n\n\tcout << \"!!! END TEST PROD BATCH !!!\" << endl;\n}\n\n\n//----------------------------------------------------------------------------------\n//   FUNCTION TESTS\n//----------------------------------------------------------------------------------\n\n\nvoid TestScheme::testInverseBatch(long logN, long logQ, long logp, long invSteps, long logSlots) {\n\tcout << \"!!! START TEST INVERSE BATCH !!!\" << endl;\n\t//-----------------------------------------\n\tTimeUtils timeutils;\n\tContext context(logN, logQ);\n\tSecretKey secretKey(logN);\n\tScheme scheme(secretKey, context);\n\tSchemeAlgo algo(scheme);\n\t//-----------------------------------------\n\tsrand(time(NULL));\n\t//-----------------------------------------\n\tlong slots = 1 << logSlots;\n\tcomplex<double>* mvec = EvaluatorUtils::randomCircleArray(slots, 0.1);\n\tcomplex<double>* minv = new complex<double>[slots];\n\tfor (long i = 0; i < slots; ++i) {\n\t\tminv[i] = 1. / mvec[i];\n\t}\n\n\tCiphertext cipher = scheme.encrypt(mvec, slots, logp, logQ);\n\n\ttimeutils.start(\"Inverse batch\");\n\tCiphertext cinv = algo.inverse(cipher, logp, invSteps);\n\ttimeutils.stop(\"Inverse batch\");\n\n\tcomplex<double>* dinv = scheme.decrypt(secretKey, cinv);\n\n\tStringUtils::showcompare(minv, dinv, slots, \"inv\");\n\n\tcout << \"!!! END TEST INVERSE BATCH !!!\" << endl;\n}\n\nvoid TestScheme::testLogarithmBatch(long logN, long logQ, long logp, long degree, long logSlots) {\n\tcout << \"!!! START TEST LOGARITHM BATCH !!!\" << endl;\n\t//-----------------------------------------\n\tTimeUtils timeutils;\n\tContext context(logN, logQ);\n\tSecretKey secretKey(logN);\n\tScheme scheme(secretKey, context);\n\tSchemeAlgo algo(scheme);\n\t//-----------------------------------------\n\tsrand(time(NULL));\n\t//-----------------------------------------\n\tlong slots = 1 << logSlots;\n\tcomplex<double>* mvec = EvaluatorUtils::randomComplexArray(slots, 0.1);\n\tcomplex<double>* mlog = new complex<double>[slots];\n\tfor (long i = 0; i < slots; ++i) {\n\t\tmlog[i] = log(mvec[i] + 1.);\n\t}\n\n\tCiphertext cipher = scheme.encrypt(mvec, slots, logp, logQ);\n\n\ttimeutils.start(LOGARITHM + \" batch\");\n\tCiphertext clog = algo.function(cipher, LOGARITHM, logp, degree);\n\ttimeutils.stop(LOGARITHM + \" batch\");\n\n\tcomplex<double>* dlog = scheme.decrypt(secretKey, clog);\n\n\tStringUtils::showcompare(mlog, dlog, slots, LOGARITHM);\n\n\tcout << \"!!! END TEST LOGARITHM BATCH !!!\" << endl;\n}\n\nvoid TestScheme::testExponentBatch(long logN, long logQ, long logp, long degree, long logSlots) {\n\tcout << \"!!! START TEST EXPONENT BATCH !!!\" << endl;\n\t//-----------------------------------------\n\tTimeUtils timeutils;\n\tContext context(logN, logQ);\n\tSecretKey secretKey(logN);\n\tScheme scheme(secretKey, context);\n\tSchemeAlgo algo(scheme);\n\t//-----------------------------------------\n\tsrand(time(NULL));\n\t//-----------------------------------------\n\tlong slots = 1 << logSlots;\n\tcomplex<double>* mvec = EvaluatorUtils::randomComplexArray(slots);\n\tcomplex<double>* mexp = new complex<double>[slots];\n\tfor (long i = 0; i < slots; ++i) {\n\t\tmexp[i] = exp(mvec[i]);\n\t}\n\n\tCiphertext cipher = scheme.encrypt(mvec, slots, logp, logQ);\n\n\ttimeutils.start(EXPONENT + \" batch\");\n\tCiphertext cexp = algo.function(cipher, EXPONENT, logp, degree);\n\ttimeutils.stop(EXPONENT + \" batch\");\n\n\tcomplex<double>* dexp = scheme.decrypt(secretKey, cexp);\n\n\tStringUtils::showcompare(mexp, dexp, slots, EXPONENT);\n\n\tcout << \"!!! END TEST EXPONENT BATCH !!!\" << endl;\n}\n\nvoid TestScheme::testExponentBatchLazy(long logN, long logQ, long logp, long degree, long logSlots) {\n\tcout << \"!!! START TEST EXPONENT LAZY !!!\" << endl;\n\t//-----------------------------------------\n\tTimeUtils timeutils;\n\tContext context(logN, logQ);\n\tSecretKey secretKey(logN);\n\tScheme scheme(secretKey, context);\n\tSchemeAlgo algo(scheme);\n\t//-----------------------------------------\n\tsrand(time(NULL));\n\t//-----------------------------------------\n\tlong slots = 1 << logSlots;\n\tcomplex<double>* mvec = EvaluatorUtils::randomComplexArray(slots);\n\tcomplex<double>* mexp = new complex<double>[slots];\n\tfor (long i = 0; i < slots; ++i) {\n\t\tmexp[i] = exp(mvec[i]);\n\t}\n\tCiphertext cipher = scheme.encrypt(mvec, slots, logp, logQ);\n\n\ttimeutils.start(EXPONENT + \" lazy\");\n\tCiphertext cexp = algo.functionLazy(cipher, EXPONENT, logp, degree);\n\ttimeutils.stop(EXPONENT + \" lazy\");\n\n\tcomplex<double>* dexp = scheme.decrypt(secretKey, cexp);\n\n\tStringUtils::showcompare(mexp, dexp, slots, EXPONENT);\n\n\tcout << \"!!! END TEST EXPONENT LAZY !!!\" << endl;\n}\n\n//-----------------------------------------\n\nvoid TestScheme::testSigmoidBatch(long logN, long logQ, long logp, long degree, long logSlots) {\n\tcout << \"!!! START TEST SIGMOID BATCH !!!\" << endl;\n\t//-----------------------------------------\n\tTimeUtils timeutils;\n\tContext context(logN, logQ);\n\tSecretKey secretKey(logN);\n\tScheme scheme(secretKey, context);\n\tSchemeAlgo algo(scheme);\n\t//-----------------------------------------\n\tsrand(time(NULL));\n\t//-----------------------------------------\n\tlong slots = 1 << logSlots;\n\n\tcomplex<double>* mvec = EvaluatorUtils::randomComplexArray(slots);\n\tcomplex<double>* msig = new complex<double>[slots];\n\tfor (long i = 0; i < slots; ++i) {\n\t\tmsig[i] = exp(mvec[i]) / (1. + exp(mvec[i]));\n\t}\n\n\tCiphertext cipher = scheme.encrypt(mvec, slots, logp, logQ);\n\n\ttimeutils.start(SIGMOID + \" batch\");\n\tCiphertext csig = algo.function(cipher, SIGMOID, logp, degree);\n\ttimeutils.stop(SIGMOID + \" batch\");\n\n\tcomplex<double>* dsig = scheme.decrypt(secretKey, csig);\n\n\tStringUtils::showcompare(msig, dsig, slots, SIGMOID);\n\n\tcout << \"!!! END TEST SIGMOID BATCH !!!\" << endl;\n}\n\nvoid TestScheme::testSigmoidBatchLazy(long logN, long logQ, long logp, long degree, long logSlots) {\n\tcout << \"!!! START TEST SIGMOID LAZY !!!\" << endl;\n\t//-----------------------------------------\n\tTimeUtils timeutils;\n\tContext context(logN, logQ);\n\tSecretKey secretKey(logN);\n\tScheme scheme(secretKey, context);\n\tSchemeAlgo algo(scheme);\n\t//-----------------------------------------\n\tsrand(time(NULL));\n\t//-----------------------------------------\n\tlong slots = 1 << logSlots;\n\tcomplex<double>* mvec = EvaluatorUtils::randomComplexArray(slots);\n\tcomplex<double>* msig = new complex<double>[slots];\n\tfor (long i = 0; i < slots; ++i) {\n\t\tmsig[i] = exp(mvec[i]) / (1. + exp(mvec[i]));\n\t}\n\n\tCiphertext cipher = scheme.encrypt(mvec, slots, logp, logQ);\n\n\ttimeutils.start(SIGMOID + \" lazy\");\n\tCiphertext csig = algo.functionLazy(cipher, SIGMOID, logp, degree);\n\ttimeutils.stop(SIGMOID + \" lazy\");\n\n\tcomplex<double>* dsig = scheme.decrypt(secretKey, csig);\n\n\tStringUtils::showcompare(msig, dsig, slots, SIGMOID);\n\n\tcout << \"!!! END TEST SIGMOID LAZY !!!\" << endl;\n}\n\n\n//----------------------------------------------------------------------------------\n//   FFT TESTS\n//----------------------------------------------------------------------------------\n\n\nvoid TestScheme::testFFTBatch(long logN, long logQ, long logp, long logSlots, long logfftdim) {\n\tcout << \"!!! START TEST FFT BATCH !!!\" << endl;\n\t//-----------------------------------------\n\tTimeUtils timeutils;\n\tContext context(logN, logQ);\n\tSecretKey secretKey(logN);\n\tScheme scheme(secretKey, context);\n\tSchemeAlgo algo(scheme);\n\t//-----------------------------------------\n\tSetNumThreads(8);\n\t//-----------------------------------------\n\tsrand(time(NULL));\n\t//-----------------------------------------\n\tlong fftdim = 1 << logfftdim;\n\tlong slots = 1 << logSlots;\n\tcomplex<double>** mvec1 = new complex<double>*[slots];\n\tcomplex<double>** mvec2 = new complex<double>*[slots];\n\tfor (long i = 0; i < slots; ++i) {\n\t\tmvec1[i] = EvaluatorUtils::randomComplexArray(fftdim);\n\t\tmvec2[i] = EvaluatorUtils::randomComplexArray(fftdim);\n\t}\n\n\tCiphertext* cvec1 = new Ciphertext[fftdim];\n\tCiphertext* cvec2 = new Ciphertext[fftdim];\n\tfor (long j = 0; j < fftdim; ++j) {\n\t\tcomplex<double>* mvals1 = new complex<double>[slots];\n\t\tcomplex<double>* mvals2\t= new complex<double>[slots];\n\t\tfor (long i = 0; i < slots; ++i) {\n\t\t\tmvals1[i] = mvec1[i][j];\n\t\t\tmvals2[i] = mvec2[i][j];\n\t\t}\n\t\tcvec1[j] = scheme.encrypt(mvals1, slots, logp, logQ);\n\t\tcvec2[j] = scheme.encrypt(mvals2, slots, logp, logQ);\n\t\tdelete[] mvals1;\n\t\tdelete[] mvals2;\n\t}\n\n\tfor (long i = 0; i < slots; ++i) {\n\t\tcontext.fft(mvec1[i], fftdim);\n\t\tcontext.fft(mvec2[i], fftdim);\n\t\tfor (long j = 0; j < fftdim; ++j) {\n\t\t\tmvec1[i][j] *= mvec2[i][j];\n\t\t}\n\t\tcontext.fftInv(mvec1[i], fftdim);\n\t}\n\n\ttimeutils.start(\"ciphers fft 1 batch\");\n\talgo.fft(cvec1, fftdim);\n\ttimeutils.stop(\"ciphers fft 1 batch\");\n\n\ttimeutils.start(\"ciphers fft 2 batch\");\n\talgo.fft(cvec2, fftdim);\n\ttimeutils.stop(\"ciphers fft 2 batch\");\n\n\ttimeutils.start(\"ciphers hadamard mult batch\");\n\talgo.multModSwitchAndEqualVec(cvec1, cvec2, logp, fftdim);\n\ttimeutils.stop(\"ciphers hadamard mult batch\");\n\n\tdelete[] cvec2;\n\n\ttimeutils.start(\"ciphers fft inverse batch\");\n\talgo.fftInv(cvec1, fftdim);\n\ttimeutils.stop(\"ciphers fft inverse batch\");\n\n\tcomplex<double>** dvec1 = new complex<double>*[fftdim];\n\tfor (long j = 0; j < fftdim; ++j) {\n\t\tdvec1[j] = scheme.decrypt(secretKey, cvec1[j]);\n\t}\n\n\tfor (long i = 0; i < slots; ++i) {\n\t\tfor (long j = 0; j < fftdim; ++j) {\n\t\t\tStringUtils::showcompare(mvec1[i][j], dvec1[j][i], \"fft\");\n\t\t}\n\t}\n\n\tcout << \"!!! END TEST FFT BATCH !!!\" << endl;\n}\n\nvoid TestScheme::testFFTBatchLazy(long logN, long logQ, long logp, long logSlots, long logfftdim) {\n\tcout << \"!!! START TEST FFT BATCH LAZY !!!\" << endl;\n\t//-----------------------------------------\n\tTimeUtils timeutils;\n\tContext context(logN, logQ);\n\tSecretKey secretKey(logN);\n\tScheme scheme(secretKey, context);\n\tSchemeAlgo algo(scheme);\n\t//-----------------------------------------\n\tSetNumThreads(8);\n\t//-----------------------------------------\n\tsrand(time(NULL));\n\t//-----------------------------------------\n\tlong fftdim = 1 << logfftdim;\n\tlong slots = 1 << logSlots;\n\tcomplex<double>** mvec1 = new complex<double>*[slots];\n\tcomplex<double>** mvec2 = new complex<double>*[slots];\n\tfor (long i = 0; i < slots; ++i) {\n\t\tmvec1[i] = EvaluatorUtils::randomComplexArray(fftdim);\n\t\tmvec2[i] = EvaluatorUtils::randomComplexArray(fftdim);\n\t}\n\n\tCiphertext* cvec1 = new Ciphertext[fftdim];\n\tCiphertext* cvec2 = new Ciphertext[fftdim];\n\tfor (long j = 0; j < fftdim; ++j) {\n\t\tcomplex<double>* mvals1 = new complex<double>[slots];\n\t\tcomplex<double>* mvals2\t= new complex<double>[slots];\n\t\tfor (long i = 0; i < slots; ++i) {\n\t\t\tmvals1[i] = mvec1[i][j];\n\t\t\tmvals2[i] = mvec2[i][j];\n\t\t}\n\t\tcvec1[j] = scheme.encrypt(mvals1, slots, logp, logQ);\n\t\tcvec2[j] = scheme.encrypt(mvals2, slots, logp, logQ);\n\t\tdelete[] mvals1;\n\t\tdelete[] mvals2;\n\t}\n\n\tfor (long i = 0; i < slots; ++i) {\n\t\tcontext.fft(mvec1[i], fftdim);\n\t\tcontext.fft(mvec2[i], fftdim);\n\t\tfor (long j = 0; j < fftdim; ++j) {\n\t\t\tmvec1[i][j] *= mvec2[i][j];\n\t\t}\n\t\tcontext.fftInvLazy(mvec1[i], fftdim);\n\t}\n\n\ttimeutils.start(\"ciphers fft 1\");\n\talgo.fft(cvec1, fftdim);\n\ttimeutils.stop(\"ciphers fft 1\");\n\n\ttimeutils.start(\"ciphers fft 2\");\n\talgo.fft(cvec2, fftdim);\n\ttimeutils.stop(\"ciphers fft 2\");\n\n\ttimeutils.start(\"ciphers hadamard mult\");\n\talgo.multModSwitchAndEqualVec(cvec1, cvec2, logp, fftdim);\n\ttimeutils.stop(\"ciphers hadamard mult\");\n\n\tdelete[] cvec2;\n\n\ttimeutils.start(\"ciphers fft inverse lazy\");\n\talgo.fftInvLazy(cvec1, fftdim);\n\ttimeutils.stop(\"ciphers fft inverse lazy\");\n\n\tcomplex<double>** dvec1 = new complex<double>*[fftdim];\n\tfor (long j = 0; j < fftdim; ++j) {\n\t\tdvec1[j] = scheme.decrypt(secretKey, cvec1[j]);\n\t}\n\n\tfor (long i = 0; i < slots; ++i) {\n\t\tfor (long j = 0; j < fftdim; ++j) {\n\t\t\tStringUtils::showcompare(mvec1[i][j], dvec1[j][i], \"fft\");\n\t\t}\n\t}\n\n\tcout << \"!!! END TEST FFT BATCH LAZY !!!\" << endl;\n}\n\nvoid TestScheme::testFFTBatchLazyMultipleHadamard(long logN, long logQ, long logp, long logSlots, long logfftdim, long logHdim) {\n\tcout << \"!!! START TEST FFT BATCH LAZY MULTIPLE HADAMARD !!!\" << endl;\n\t//-----------------------------------------\n\tTimeUtils timeutils;\n\tContext context(logN, logQ);\n\tSecretKey secretKey(logN);\n\tScheme scheme(secretKey, context);\n\tSchemeAlgo algo(scheme);\n\t//-----------------------------------------\n\tSetNumThreads(8);\n\t//-----------------------------------------\n\tsrand(time(NULL));\n\t//-----------------------------------------\n\tlong fftdim = 1 << logfftdim;\n\tlong hdim = 1 << logHdim;\n\tlong slots = 1 << logSlots;\n\tcomplex<double>*** mvecs = new complex<double>**[hdim];\n\tCiphertext** cvecs = new Ciphertext*[hdim];\n\tfor (long h = 0; h < hdim; ++h) {\n\t\tmvecs[h] = new complex<double>*[slots];\n\t\tfor (long i = 0; i < slots; ++i) {\n\t\t\tmvecs[h][i] = EvaluatorUtils::randomComplexArray(fftdim);\n\t\t}\n\n\t\tcvecs[h] = new Ciphertext[fftdim];\n\t\tfor (long j = 0; j < fftdim; ++j) {\n\t\t\tcomplex<double>* mvals = new complex<double>[slots];\n\t\t\tfor (long i = 0; i < slots; ++i) {\n\t\t\t\tmvals[i] = mvecs[h][i][j];\n\t\t\t}\n\t\t\tcvecs[h][j] = scheme.encrypt(mvals, slots, logp, logQ);\n\t\t\tdelete[] mvals;\n\t\t}\n\t\tfor (long i = 0; i < slots; ++i) {\n\t\t\tcontext.fft(mvecs[h][i], fftdim);\n\t\t}\n\t}\n\n\tfor (long i = 0; i < slots; ++i) {\n\t\tfor (long j = 0; j < fftdim; ++j) {\n\t\t\tfor (long s = logHdim - 1; s >= 0; --s) {\n\t\t\t\tlong spow = 1 << s;\n\t\t\t\tfor (long h = 0; h < spow; ++h) {\n\t\t\t\t\tmvecs[h][i][j] *= mvecs[h+spow][i][j];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfor (long i = 0; i < slots; ++i) {\n\t\tcontext.fftInvLazy(mvecs[0][i], fftdim);\n\t}\n\n\tfor (long h = 1; h < hdim; ++h) {\n\t\tfor (long i = 0; i < slots; ++i) {\n\t\t\tdelete[] mvecs[h][i];\n\t\t}\n\t\tdelete[] mvecs[h];\n\t}\n\n\tfor (long h = 0; h < hdim; ++h) {\n\t\ttimeutils.start(\"fft\");\n\t\talgo.fft(cvecs[h], fftdim);\n\t\ttimeutils.stop(\"fft\");\n\t}\n\n\tfor (long s = logHdim - 1; s >= 0; --s) {\n\t\tlong spow = 1 << s;\n\t\tfor (long h = 0; h < spow; ++h) {\n\t\t\ttimeutils.start(\"hadamard mult\");\n\t\t\talgo.multModSwitchAndEqualVec(cvecs[h], cvecs[h+spow], logp, fftdim);\n\t\t\ttimeutils.stop(\"hadamard mult\");\n\t\t\tdelete[] cvecs[h+spow];\n\t\t}\n\t}\n\n\ttimeutils.start(\"fft inverse lazy\");\n\talgo.fftInvLazy(cvecs[0], fftdim);\n\ttimeutils.stop(\"fft inverse lazy\");\n\n\tcomplex<double>** dvec = new complex<double>*[fftdim];\n\tfor (long j = 0; j < fftdim; ++j) {\n\t\tdvec[j] = scheme.decrypt(secretKey, cvecs[0][j]);\n\t}\n\n\tfor (long i = 0; i < slots; ++i) {\n\t\tfor (long j = 0; j < fftdim; ++j) {\n\t\t\tStringUtils::showcompare(mvecs[0][i][j], dvec[j][i], \"fft\");\n\t\t}\n\t}\n\n\tcout << \"!!! END TEST FFT BATCH LAZY MULTIPLE HADAMARD !!!\" << endl;\n}\n\nvoid TestScheme::testWriteAndRead(long logN, long logQ, long logp, long logSlots) {\n\tcout << \"!!! START TEST WRITE AND READ !!!\" << endl;\n\t//-----------------------------------------\n\tTimeUtils timeutils;\n\tContext context(logN, logQ);\n\tSecretKey secretKey(logN);\n\tScheme scheme(secretKey, context);\n\tSchemeAlgo algo(scheme);\n\t//-----------------------------------------\n\tsrand(time(NULL));\n\t//-----------------------------------------\n\tlong slots = (1 << logSlots);\n\tcomplex<double>* mvec = EvaluatorUtils::randomComplexArray(slots);\n\n\tCiphertext cipher = scheme.encrypt(mvec, slots, logp, logQ);\n\n\tstring cipherPath = \"testCiphertext.txt\";\n\ttimeutils.start(\"Write Ciphertext\");\n\tSerializationUtils::writeCiphertext(cipher, cipherPath);\n\ttimeutils.stop(\"Write Ciphertext\");\n\n\ttimeutils.start(\"Read Ciphertext\");\n\tCiphertext newcipher = SerializationUtils::readCiphertext(cipherPath);\n\ttimeutils.stop(\"Read Ciphertext\");\n\n\tif(newcipher.ax != cipher.ax || newcipher.bx != cipher.bx || newcipher.logq != cipher.logq || newcipher.slots != cipher.slots || newcipher.logp != cipher.logp) {\n\t\tcerr << \"Write and Read for ciphertext does not work\" << endl;\n\t\tcout << \"difference ax = \" << newcipher.ax - cipher.ax << endl;\n\t\tcout << \"difference bx = \" << newcipher.ax - cipher.bx << endl;\n\t} else {\n\t\tcout << \"Write and Read for ciphertext works well\" << endl;\n\t}\n\n\tstring secretKeyPath = \"testSecretKey.txt\";\n\ttimeutils.start(\"Write SecretKey\");\n\tSerializationUtils::writeSecretKey(secretKey, secretKeyPath);\n\ttimeutils.stop(\"Write SecretKey\");\n\n\ttimeutils.start(\"Read SecretKey\");\n\tSecretKey newsecretKey = SerializationUtils::readSecretKey(secretKeyPath);\n\ttimeutils.stop(\"Read SecretKey\");\n\tif(secretKey.sx != newsecretKey.sx) {\n\t\tcout << \"Write and Read for sk does not work\" << endl;\n\t} else {\n\t\tcout << \"Write and Read for sk works well\" << endl;\n\t}\n\n//\tscheme.addLeftRotKeys(secretKey);\n\tscheme.addConjKey(secretKey);\n\n\tstring schemeKeysPath = \"testSchemeKeys.txt\";\n\ttimeutils.start(\"Write Scheme\");\n\tSerializationUtils::writeSchemeKeys(scheme, schemeKeysPath);\n\ttimeutils.stop(\"Write Scheme\");\n\n\tstring contextPath = \"testContext.txt\";\n\ttimeutils.start(\"Write Context\");\n\tSerializationUtils::writeContext(context, contextPath);\n\ttimeutils.stop(\"Write Context\");\n\n\ttimeutils.start(\"Read Context\");\n\tContext newcontext = SerializationUtils::readContext(contextPath);\n\ttimeutils.stop(\"Read Context\");\n\n\tScheme newscheme(newcontext);\n\n\ttimeutils.start(\"Read Scheme\");\n\tSerializationUtils::readSchemeKeys(newscheme, schemeKeysPath);\n\ttimeutils.stop(\"Read Scheme\");\n\n\tcomplex<double>* dvec = scheme.decrypt(secretKey, cipher);\n\tcomplex<double>* newdvec = newscheme.decrypt(newsecretKey, newcipher);\n\n\tStringUtils::showcompare(dvec, newdvec, slots, \"r&w\");\n\n\tcout << \"!!! END TEST WRITE AND READ !!!\" << endl;\n}\n", "meta": {"hexsha": "cac76cbe5e2f2e7e9c942cad8f8101afa20e5711", "size": 31693, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/TestScheme.cpp", "max_stars_repo_name": "pwnmelife/HEMat", "max_stars_repo_head_hexsha": "1ce4fdfa0ed83ebf59709ddc3e2e7cd6215666d9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2019-03-20T03:49:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T06:30:51.000Z", "max_issues_repo_path": "src/TestScheme.cpp", "max_issues_repo_name": "pwnmelife/HEMat", "max_issues_repo_head_hexsha": "1ce4fdfa0ed83ebf59709ddc3e2e7cd6215666d9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2018-08-29T13:21:32.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-15T12:16:09.000Z", "max_forks_repo_path": "src/TestScheme.cpp", "max_forks_repo_name": "pwnmelife/HEMat", "max_forks_repo_head_hexsha": "1ce4fdfa0ed83ebf59709ddc3e2e7cd6215666d9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2020-05-21T10:58:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T08:47:07.000Z", "avg_line_length": 32.2410986775, "max_line_length": 162, "alphanum_fraction": 0.5969772505, "num_tokens": 8410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.4726121034671592}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// Unit Test\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#include <iostream>\n#include <iterator>\n#include <string>\n\n\n#include <geometry_test_common.hpp>\n\n#include <boost/geometry/algorithms/num_points.hpp>\n#include <boost/geometry/extensions/algorithms/remove_holes_if.hpp>\n#include <boost/geometry/algorithms/make.hpp>\n#include <boost/geometry/geometries/geometries.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/io/wkt/read.hpp>\n\n#include <boost/geometry/strategies/strategies.hpp>\n\n\n\ntemplate <typename G, typename Predicate>\nvoid test_remove_holes_if(std::string const& wkt, Predicate const& predicate,\n            int expected_points)\n{\n    G g;\n    bg::read_wkt(wkt, g);\n    bg::remove_holes_if(g, predicate);\n    BOOST_CHECK_EQUAL(bg::num_points(g), expected_points);\n}\n\ntemplate <typename P>\nvoid test_all()\n{\n    bg::elongated_hole<bg::model::ring<P> > elongated(0.05);\n\n    // No holes\n    test_remove_holes_if<bg::model::polygon<P> >(\"POLYGON((0 0,0 4,4 4,4 0,0 0))\", elongated, 5);\n\n    // Square hole (ratio 1/4), kept\n    test_remove_holes_if<bg::model::polygon<P> >(\"POLYGON((0 0,0 4,4 4,4 0,0 0), (1 1,1 2,2 2,2 1,1 1))\", elongated, 10);\n\n    // Elongated hole\n    test_remove_holes_if<bg::model::polygon<P> >(\"POLYGON((0 0,0 4,4 4,4 0,0 0), (1 1,1 2,1.02 2,1.02 1,1 1))\", elongated, 5);\n\n    // Invalid hole - removed by \"elongated\" predicate as well\n    test_remove_holes_if<bg::model::polygon<P> >(\"POLYGON((0 0,0 4,4 4,4 0,0 0), (1 1,1 2))\", elongated, 5);\n\n    // Invalid hole\n    bg::invalid_hole<bg::model::ring<P> > invalid;\n    test_remove_holes_if<bg::model::polygon<P> >(\"POLYGON((0 0,0 4,4 4,4 0,0 0), (1 1,1 2))\", invalid, 5);\n\n    // Valid hole\n    test_remove_holes_if<bg::model::polygon<P> >(\"POLYGON((0 0,0 4,4 4,4 0,0 0), (1 1,1 2,1.02 2,1.02 1,1 1))\", invalid, 10);\n\n}\n\nint test_main(int, char* [])\n{\n    //test_all<bg::model::d2::point_xy<float> >();\n    test_all<bg::model::d2::point_xy<double> >();\n\n    return 0;\n}\n", "meta": {"hexsha": "8ccab54c3d7ec098e430002d7cc810dd635548aa", "size": 2523, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "extensions/test/algorithms/remove_holes_if.cpp", "max_stars_repo_name": "jkerkela/geometry", "max_stars_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 326.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T13:47:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T02:13:59.000Z", "max_issues_repo_path": "extensions/test/algorithms/remove_holes_if.cpp", "max_issues_repo_name": "jkerkela/geometry", "max_issues_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 623.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T23:45:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T11:15:23.000Z", "max_forks_repo_path": "extensions/test/algorithms/remove_holes_if.cpp", "max_forks_repo_name": "jkerkela/geometry", "max_forks_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-01-14T15:50:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T03:58:36.000Z", "avg_line_length": 33.1973684211, "max_line_length": 126, "alphanum_fraction": 0.6845025763, "num_tokens": 860, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.6334102705979902, "lm_q1q2_score": 0.4726121014793199}}
{"text": "/*=========================================================================\n\n  Library   : Image Registration Toolkit (IRTK)\n  Module    : $Id$\n  Copyright : Imperial College, Department of Computing\n              Visual Information Processing (VIP), 2008 onwards\n  Date      : $Date$\n  Version   : $Revision$\n  Changes   : $Author$\n\nCopyright (c) 1999-2014 and onwards, Imperial College London\nAll rights reserved.\nSee LICENSE for details\n\n=========================================================================*/\n\n#include <irtkImage.h>\n\n#include <irtkNoise.h>\n\n#include <boost/random.hpp>\n#include <boost/random/normal_distribution.hpp>\n\n\ntemplate <class VoxelType> irtkGaussianNoise<VoxelType>::irtkGaussianNoise() : irtkNoise<VoxelType>()\n{\n  _Mean   = 0;\n  _Sigma  = 1;\n  _MinVal = VoxelType(MIN_GREY);\n  _MaxVal = VoxelType(MAX_GREY);\n\n  long temp = -1 * this->_Init;\n\n  boost::mt19937 rng;\n  rng.seed(temp);\n\n  boost::normal_distribution<> nd(0, 1);\n  boost::variate_generator<boost::mt19937&,\n                           boost::normal_distribution<> > var_nor(rng, nd);\n  (void) var_nor();\n}\n\ntemplate <class VoxelType> irtkGaussianNoise<VoxelType>::irtkGaussianNoise(double Mean, double Sigma, VoxelType MinVal, VoxelType MaxVal) : irtkNoise<VoxelType>()\n{\n  this->_Mean   = Mean;\n  this->_Sigma  = Sigma;\n  this->_MinVal = MinVal;\n  this->_MaxVal = MaxVal;\n\n  long temp = -1 * this->_Init;\n\n  boost::mt19937 rng;\n  rng.seed(temp);\n\n  boost::normal_distribution<> nd(0, 1);\n  boost::variate_generator<boost::mt19937&,\n                           boost::normal_distribution<> > var_nor(rng, nd);\n  (void) var_nor();\n}\n\n\ntemplate <class VoxelType> const char *irtkGaussianNoise<VoxelType>::NameOfClass()\n{\n  return \"irtkGaussianNoise\";\n}\n\ntemplate <class VoxelType> double irtkGaussianNoise<VoxelType>::Run(int x, int y, int z, int t)\n{\n  boost::mt19937 rng;\n  rng.seed(this->_Init);\n\n  boost::normal_distribution<> nd(0, 1);\n  boost::variate_generator<boost::mt19937&,\n                           boost::normal_distribution<> > var_nor(rng, nd);\n\n  double tmp = this->_input->Get(x, y, z, t) + this->_Sigma * var_nor() + this->_Mean;\n  if (tmp < this->_MinVal) return this->_MinVal;\n  if (tmp > this->_MaxVal) return this->_MaxVal;\n  return tmp;\n}\n\ntemplate class irtkGaussianNoise<irtkBytePixel>;\ntemplate class irtkGaussianNoise<irtkGreyPixel>;\ntemplate class irtkGaussianNoise<irtkRealPixel>;\n\n", "meta": {"hexsha": "5327a2313dc79ab158cf15b1ff1d64cefc15938a", "size": 2405, "ext": "cc", "lang": "C++", "max_stars_repo_path": "source/IRTKSimple2/image++/src/irtkGaussianNoise.cc", "max_stars_repo_name": "gordon-n-stevenson/fetalReconstruction", "max_stars_repo_head_hexsha": "6a1e4a15bdf92e86439791d836d1b20ede793293", "max_stars_repo_licenses": ["Zlib", "Unlicense", "Intel", "MIT"], "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/IRTKSimple2/image++/src/irtkGaussianNoise.cc", "max_issues_repo_name": "gordon-n-stevenson/fetalReconstruction", "max_issues_repo_head_hexsha": "6a1e4a15bdf92e86439791d836d1b20ede793293", "max_issues_repo_licenses": ["Zlib", "Unlicense", "Intel", "MIT"], "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/IRTKSimple2/image++/src/irtkGaussianNoise.cc", "max_forks_repo_name": "gordon-n-stevenson/fetalReconstruction", "max_forks_repo_head_hexsha": "6a1e4a15bdf92e86439791d836d1b20ede793293", "max_forks_repo_licenses": ["Zlib", "Unlicense", "Intel", "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.9651162791, "max_line_length": 162, "alphanum_fraction": 0.6407484407, "num_tokens": 656, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389817407017, "lm_q2_score": 0.6334102775181399, "lm_q1q2_score": 0.4726120994914802}}
{"text": "#include <boost/integer/common_factor.hpp>\n", "meta": {"hexsha": "454b5414f7a24ff5fcea71688ac55ca93d3af405", "size": 43, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_integer_common_factor.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_integer_common_factor.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_integer_common_factor.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 21.5, "max_line_length": 42, "alphanum_fraction": 0.8139534884, "num_tokens": 9, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.4726120963159262}}
{"text": "/* vim: set tabstop=4 expandtab shiftwidth=4 softtabstop=4: */\n\n/**\n * \\file libs/numeric/ublasx/test/trace.cpp\n *\n * \\brief Test suite for the \\c trace operation.\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n *\n * <hr/>\n *\n * Copyright (c) 2010, Marco Guazzone\n *\n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#include <boost/numeric/ublas/fwd.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublasx/detail/debug.hpp>\n#include <boost/numeric/ublasx/operation/trace.hpp>\n#include <complex>\n#include <cstddef>\n#include \"libs/numeric/ublasx/test/utils.hpp\"\n\n\nnamespace ublas = boost::numeric::ublas;\nnamespace ublasx = boost::numeric::ublasx;\n\n\nconst double tol = 1.0e-5;\n\n\nBOOST_UBLASX_TEST_DEF( real_square_col_major )\n{\n    BOOST_UBLASX_DEBUG_TRACE(\"Test Case: Real Type - Square Matrix - Column-Major\");\n\n    typedef double value_type;\n    typedef ublas::matrix<value_type,ublas::column_major> matrix_type;\n\n    const std::size_t n = 3;\n\n    matrix_type A(n,n);\n    A(0,0) = 1; A(0,1) = 2; A(0,2) = 3;\n    A(1,0) = 4; A(1,1) = 5; A(1,2) = 6;\n    A(2,0) = 7; A(2,1) = 8; A(2,2) = 9;\n\n    value_type expect_tr = A(0,0)+A(1,1)+A(2,2);\n    value_type tr = ublasx::trace(A);\n    BOOST_UBLASX_DEBUG_TRACE( \"A = \" << A );\n    BOOST_UBLASX_DEBUG_TRACE( \"tr(A) = \" << tr );\n    BOOST_UBLASX_TEST_CHECK_CLOSE( tr, expect_tr, tol );\n}\n\n\nBOOST_UBLASX_TEST_DEF( real_square_row_major )\n{\n    BOOST_UBLASX_DEBUG_TRACE(\"Test Case: Real Type - Square Matrix - Row-Major\");\n\n    typedef double value_type;\n    typedef ublas::matrix<value_type,ublas::row_major> matrix_type;\n\n    const std::size_t n = 3;\n\n    matrix_type A(n,n);\n    A(0,0) = 1; A(0,1) = 2; A(0,2) = 3;\n    A(1,0) = 4; A(1,1) = 5; A(1,2) = 6;\n    A(2,0) = 7; A(2,1) = 8; A(2,2) = 9;\n\n    value_type expect_tr = A(0,0)+A(1,1)+A(2,2);\n    value_type tr = ublasx::trace(A);\n    BOOST_UBLASX_DEBUG_TRACE( \"A = \" << A );\n    BOOST_UBLASX_DEBUG_TRACE( \"tr(A) = \" << tr );\n    BOOST_UBLASX_TEST_CHECK_CLOSE( tr, expect_tr, tol );\n}\n\n\nBOOST_UBLASX_TEST_DEF( complex_square_col_major )\n{\n    BOOST_UBLASX_DEBUG_TRACE(\"Test Case: Complex Type - Square Matrix - Column-Major\");\n\n    typedef double real_type;\n    typedef std::complex<real_type> value_type;\n    typedef ublas::matrix<value_type,ublas::column_major> matrix_type;\n\n    const std::size_t n = 3;\n\n    matrix_type A(n,n);\n    A(0,0) = value_type(1,-5); A(0,1) = value_type(2, 3); A(0,2) = value_type(3,-9);\n    A(1,0) = value_type(4, 4); A(1,1) = value_type(5,-2); A(1,2) = value_type(6, 8);\n    A(2,0) = value_type(7,-3); A(2,1) = value_type(8, 1); A(2,2) = value_type(9,-7);\n\n    value_type expect_tr = A(0,0)+A(1,1)+A(2,2);\n    value_type tr = ublasx::trace(A);\n    BOOST_UBLASX_DEBUG_TRACE( \"A = \" << A );\n    BOOST_UBLASX_DEBUG_TRACE( \"tr(A) = \" << tr );\n    BOOST_UBLASX_TEST_CHECK_CLOSE( tr, expect_tr, tol );\n}\n\n\nBOOST_UBLASX_TEST_DEF( complex_square_row_major )\n{\n    BOOST_UBLASX_DEBUG_TRACE(\"Test Case: Complex Type - Square Matrix - Row-Major\");\n\n    typedef double real_type;\n    typedef std::complex<real_type> value_type;\n    typedef ublas::matrix<value_type,ublas::row_major> matrix_type;\n\n    const std::size_t n = 3;\n\n    matrix_type A(n,n);\n    A(0,0) = value_type(1,-5); A(0,1) = value_type(2, 3); A(0,2) = value_type(3,-9);\n    A(1,0) = value_type(4, 4); A(1,1) = value_type(5,-2); A(1,2) = value_type(6, 8);\n    A(2,0) = value_type(7,-3); A(2,1) = value_type(8, 1); A(2,2) = value_type(9,-7);\n\n    value_type expect_tr = A(0,0)+A(1,1)+A(2,2);\n    value_type tr = ublasx::trace(A);\n    BOOST_UBLASX_DEBUG_TRACE( \"A = \" << A );\n    BOOST_UBLASX_DEBUG_TRACE( \"tr(A) = \" << tr );\n    BOOST_UBLASX_TEST_CHECK_CLOSE( tr, expect_tr, tol );\n}\n\n\nBOOST_UBLASX_TEST_DEF( real_recth_col_major )\n{\n    BOOST_UBLASX_DEBUG_TRACE(\"Test Case: Real Type - Rectangular Horizontal Matrix - Column-Major\");\n\n    typedef double value_type;\n    typedef ublas::matrix<value_type,ublas::column_major> matrix_type;\n\n    const std::size_t n = 3;\n    const std::size_t m = 5;\n\n    matrix_type A(n,m);\n    A(0,0) =  1; A(0,1) =  2; A(0,2) =  3; A(0,3) =  4; A(0,4) =  5;\n    A(1,0) =  6; A(1,1) =  7; A(1,2) =  8; A(1,3) =  9; A(1,4) = 10;\n    A(2,0) = 11; A(2,1) = 12; A(2,2) = 13; A(2,3) = 14; A(2,4) = 15;\n\n    value_type expect_tr = A(0,0)+A(1,1)+A(2,2);\n    value_type tr = ublasx::trace(A);\n    BOOST_UBLASX_DEBUG_TRACE( \"A = \" << A );\n    BOOST_UBLASX_DEBUG_TRACE( \"tr(A) = \" << tr );\n    BOOST_UBLASX_TEST_CHECK_CLOSE( tr, expect_tr, tol );\n}\n\n\nBOOST_UBLASX_TEST_DEF( real_recth_row_major )\n{\n    BOOST_UBLASX_DEBUG_TRACE(\"Test Case: Real Type - Rectangular Horizontal Matrix - Row-Major\");\n\n    typedef double value_type;\n    typedef ublas::matrix<value_type,ublas::row_major> matrix_type;\n\n    const std::size_t n = 3;\n    const std::size_t m = 5;\n\n    matrix_type A(n,m);\n    A(0,0) =  1; A(0,1) =  2; A(0,2) =  3; A(0,3) =  4; A(0,4) =  5;\n    A(1,0) =  6; A(1,1) =  7; A(1,2) =  8; A(1,3) =  9; A(1,4) = 10;\n    A(2,0) = 11; A(2,1) = 12; A(2,2) = 13; A(2,3) = 14; A(2,4) = 15;\n\n\n    value_type expect_tr = A(0,0)+A(1,1)+A(2,2);\n    value_type tr = ublasx::trace(A);\n    BOOST_UBLASX_DEBUG_TRACE( \"A = \" << A );\n    BOOST_UBLASX_DEBUG_TRACE( \"tr(A) = \" << tr );\n    BOOST_UBLASX_TEST_CHECK_CLOSE( tr, expect_tr, tol );\n}\n\n\nBOOST_UBLASX_TEST_DEF( complex_recth_col_major )\n{\n    BOOST_UBLASX_DEBUG_TRACE(\"Test Case: Complex Type - Rectangular Horizontal Matrix - Column-Major\");\n\n    typedef double real_type;\n    typedef std::complex<real_type> value_type;\n    typedef ublas::matrix<value_type,ublas::column_major> matrix_type;\n\n    const std::size_t n = 3;\n    const std::size_t m = 5;\n\n    matrix_type A(n,m);\n    A(0,0) = value_type( 1,-11); A(0,1) = value_type( 2, 12); A(0,2) = value_type( 3,-13); A(0,3) = value_type( 4, 14); A(0,4) = value_type( 5, -15);\n    A(1,0) = value_type( 6,  6); A(1,1) = value_type( 7,- 7); A(1,2) = value_type( 8,  8); A(1,3) = value_type( 9,- 9); A(1,4) = value_type(10,  10);\n    A(2,0) = value_type(11,- 1); A(2,1) = value_type(12,  2); A(2,2) = value_type(13,- 3); A(2,3) = value_type(14,  4); A(2,4) = value_type(15, - 5);\n\n    value_type expect_tr = A(0,0)+A(1,1)+A(2,2);\n    value_type tr = ublasx::trace(A);\n    BOOST_UBLASX_DEBUG_TRACE( \"A = \" << A );\n    BOOST_UBLASX_DEBUG_TRACE( \"tr(A) = \" << tr );\n    BOOST_UBLASX_TEST_CHECK_CLOSE( tr, expect_tr, tol );\n}\n\n\nBOOST_UBLASX_TEST_DEF( complex_recth_row_major )\n{\n    BOOST_UBLASX_DEBUG_TRACE(\"Test Case: Complex Type - Rectangular Horizontal Matrix - Row-Major\");\n\n    typedef double real_type;\n    typedef std::complex<real_type> value_type;\n    typedef ublas::matrix<value_type,ublas::row_major> matrix_type;\n\n    const std::size_t n = 3;\n    const std::size_t m = 5;\n\n    matrix_type A(n,m);\n    A(0,0) = value_type( 1,-11); A(0,1) = value_type( 2, 12); A(0,2) = value_type( 3,-13); A(0,3) = value_type( 4, 14); A(0,4) = value_type( 5,-15);\n    A(1,0) = value_type( 6,  6); A(1,1) = value_type( 7,- 7); A(1,2) = value_type( 8,  8); A(1,3) = value_type( 9,- 9); A(1,4) = value_type(10, 10);\n    A(2,0) = value_type(11,- 1); A(2,1) = value_type(12,  2); A(2,2) = value_type(13,- 3); A(2,3) = value_type(14,  4); A(2,4) = value_type(15,- 5);\n\n    value_type expect_tr = A(0,0)+A(1,1)+A(2,2);\n    value_type tr = ublasx::trace(A);\n    BOOST_UBLASX_DEBUG_TRACE( \"A = \" << A );\n    BOOST_UBLASX_DEBUG_TRACE( \"tr(A) = \" << tr );\n    BOOST_UBLASX_TEST_CHECK_CLOSE( tr, expect_tr, tol );\n}\n\n\nBOOST_UBLASX_TEST_DEF( real_rectv_col_major )\n{\n    BOOST_UBLASX_DEBUG_TRACE(\"Test Case: Real Type - Rectangular Vertical Matrix - Column-Major\");\n\n    typedef double value_type;\n    typedef ublas::matrix<value_type,ublas::column_major> matrix_type;\n\n    const std::size_t n = 5;\n    const std::size_t m = 3;\n\n    matrix_type A(n,m);\n    A(0,0) =  1; A(0,1) =  2; A(0,2) =  3;\n    A(1,0) =  4; A(1,1) =  5; A(1,2) =  6;\n    A(2,0) =  7; A(2,1) =  8; A(2,2) =  9;\n    A(3,0) = 10; A(3,1) = 11; A(3,2) = 12;\n    A(4,0) = 13; A(4,1) = 14; A(4,2) = 15;\n\n    value_type expect_tr = A(0,0)+A(1,1)+A(2,2);\n    value_type tr = ublasx::trace(A);\n    BOOST_UBLASX_DEBUG_TRACE( \"A = \" << A );\n    BOOST_UBLASX_DEBUG_TRACE( \"tr(A) = \" << tr );\n    BOOST_UBLASX_TEST_CHECK_CLOSE( tr, expect_tr, tol );\n}\n\n\nBOOST_UBLASX_TEST_DEF( real_rectv_row_major )\n{\n    BOOST_UBLASX_DEBUG_TRACE(\"Test Case: Real Type - Rectangular Vertical Matrix - Row-Major\");\n\n    typedef double value_type;\n    typedef ublas::matrix<value_type,ublas::row_major> matrix_type;\n\n    const std::size_t n = 5;\n    const std::size_t m = 3;\n\n    matrix_type A(n,m);\n    A(0,0) =  1; A(0,1) =  2; A(0,2) =  3;\n    A(1,0) =  4; A(1,1) =  5; A(1,2) =  6;\n    A(2,0) =  7; A(2,1) =  8; A(2,2) =  9;\n    A(3,0) = 10; A(3,1) = 11; A(3,2) = 12;\n    A(4,0) = 13; A(4,1) = 14; A(4,2) = 15;\n\n    value_type expect_tr = A(0,0)+A(1,1)+A(2,2);\n    value_type tr = ublasx::trace(A);\n    BOOST_UBLASX_DEBUG_TRACE( \"A = \" << A );\n    BOOST_UBLASX_DEBUG_TRACE( \"tr(A) = \" << tr );\n    BOOST_UBLASX_TEST_CHECK_CLOSE( tr, expect_tr, tol );\n}\n\n\nBOOST_UBLASX_TEST_DEF( complex_rectv_col_major )\n{\n    BOOST_UBLASX_DEBUG_TRACE(\"Test Case: Complex Type - Rectangular Vertical Matrix - Column-Major\");\n\n    typedef double real_type;\n    typedef std::complex<real_type> value_type;\n    typedef ublas::matrix<value_type,ublas::column_major> matrix_type;\n\n    const std::size_t n = 5;\n    const std::size_t m = 3;\n\n    matrix_type A(n,m);\n    A(0,0) = value_type( 1,-13); A(0,1) = value_type( 2, 14); A(0,2) = value_type( 3,-15);\n    A(1,0) = value_type( 4, 10); A(1,1) = value_type( 5,-11); A(1,2) = value_type( 6, 12);\n    A(2,0) = value_type( 7,- 7); A(2,1) = value_type( 8,  8); A(2,2) = value_type( 9,- 9);\n    A(3,0) = value_type(10,  4); A(3,1) = value_type(11,- 5); A(3,2) = value_type(12,  6);\n    A(4,0) = value_type(13,- 1); A(4,1) = value_type(14,  2); A(4,2) = value_type(15,  3);\n\n    value_type expect_tr = A(0,0)+A(1,1)+A(2,2);\n    value_type tr = ublasx::trace(A);\n    BOOST_UBLASX_DEBUG_TRACE( \"A = \" << A );\n    BOOST_UBLASX_DEBUG_TRACE( \"tr(A) = \" << tr );\n    BOOST_UBLASX_TEST_CHECK_CLOSE( tr, expect_tr, tol );\n}\n\n\nBOOST_UBLASX_TEST_DEF( complex_rectv_row_major )\n{\n    BOOST_UBLASX_DEBUG_TRACE(\"Test Case: Complex Type - Vertical Horizontal Matrix - Row-Major\");\n\n    typedef double real_type;\n    typedef std::complex<real_type> value_type;\n    typedef ublas::matrix<value_type,ublas::row_major> matrix_type;\n\n    const std::size_t n = 5;\n    const std::size_t m = 3;\n\n    matrix_type A(n,m);\n    A(0,0) = value_type( 1,-13); A(0,1) = value_type( 2, 14); A(0,2) = value_type( 3,-15);\n    A(1,0) = value_type( 4, 10); A(1,1) = value_type( 5,-11); A(1,2) = value_type( 6, 12);\n    A(2,0) = value_type( 7,- 7); A(2,1) = value_type( 8,  8); A(2,2) = value_type( 9,- 9);\n    A(3,0) = value_type(10,  4); A(3,1) = value_type(11,- 5); A(3,2) = value_type(12,  6);\n    A(4,0) = value_type(13,- 1); A(4,1) = value_type(14,  2); A(4,2) = value_type(15,  3);\n\n\n    value_type expect_tr = A(0,0)+A(1,1)+A(2,2);\n    value_type tr = ublasx::trace(A);\n    BOOST_UBLASX_DEBUG_TRACE( \"A = \" << A );\n    BOOST_UBLASX_DEBUG_TRACE( \"tr(A) = \" << tr );\n    BOOST_UBLASX_TEST_CHECK_CLOSE( tr, expect_tr, tol );\n}\n\n\nint main()\n{\n    BOOST_UBLASX_TEST_BEGIN();\n\n    BOOST_UBLASX_TEST_DO( real_square_col_major );\n    BOOST_UBLASX_TEST_DO( real_square_row_major );\n    BOOST_UBLASX_TEST_DO( complex_square_col_major );\n    BOOST_UBLASX_TEST_DO( complex_square_row_major );\n    BOOST_UBLASX_TEST_DO( real_recth_col_major );\n    BOOST_UBLASX_TEST_DO( real_recth_row_major );\n    BOOST_UBLASX_TEST_DO( complex_recth_col_major );\n    BOOST_UBLASX_TEST_DO( complex_recth_row_major );\n    BOOST_UBLASX_TEST_DO( real_rectv_col_major );\n    BOOST_UBLASX_TEST_DO( real_rectv_row_major );\n    BOOST_UBLASX_TEST_DO( complex_rectv_col_major );\n    BOOST_UBLASX_TEST_DO( complex_rectv_row_major );\n\n    BOOST_UBLASX_TEST_END();\n}\n", "meta": {"hexsha": "8ef969a50a44272e85057ccb0650e7a97df7182d", "size": 12017, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/ublasx/test/trace.cpp", "max_stars_repo_name": "sguazt/boost-ublasx", "max_stars_repo_head_hexsha": "21c9b393d33a6ec2a8071ba8d48680073d766409", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2016-05-14T11:08:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-05T14:22:20.000Z", "max_issues_repo_path": "libs/numeric/ublasx/test/trace.cpp", "max_issues_repo_name": "sguazt/boost-ublasx", "max_issues_repo_head_hexsha": "21c9b393d33a6ec2a8071ba8d48680073d766409", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-12-28T18:36:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-06T11:28:51.000Z", "max_forks_repo_path": "libs/numeric/ublasx/test/trace.cpp", "max_forks_repo_name": "sguazt/boost-ublasx", "max_forks_repo_head_hexsha": "21c9b393d33a6ec2a8071ba8d48680073d766409", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-12-23T02:53:27.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-23T02:53:27.000Z", "avg_line_length": 35.0349854227, "max_line_length": 149, "alphanum_fraction": 0.6271115919, "num_tokens": 4705, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.47261209314037156}}
{"text": "#include <boost/config.hpp>\n#include <iostream>\n#include <string>\n#include <boost/graph/push_relabel_max_flow.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/read_dimacs.hpp>\n#include \"../src/stopwatch/stopwatch.h\"\n\nint main()\n{\n\n    Stopwatch S;\n    S.set_mode(REAL_TIME);\n\n    S.start(\"TOTAL\");\n    S.start(\"READ\");\n    using namespace boost;\n\n    typedef adjacency_list_traits<vecS, vecS, directedS> Traits;\n    typedef adjacency_list<\n        vecS, vecS, directedS, property<vertex_name_t, std::string>,\n        property<edge_capacity_t, long, property<edge_residual_capacity_t, long, property<edge_reverse_t, Traits::edge_descriptor> > > > Graph;\n\n    Graph g;\n    long flow;\n\n    property_map<Graph, edge_capacity_t>::type capacity = get(edge_capacity, g);\n    property_map<Graph, edge_reverse_t>::type rev = get(edge_reverse, g);\n    property_map<Graph, edge_residual_capacity_t>::type residual_capacity = get(edge_residual_capacity, g);\n\n    Traits::vertex_descriptor s, t;\n    read_dimacs_max_flow(g, capacity, rev, s, t);\n    S.stop(\"READ\");\n\n    S.start(\"BST\");\n    flow = push_relabel_max_flow(g, s, t);\n    S.stop(\"BST\");\n    S.stop(\"TOTAL\");\n\n    std::cout << \"Vertices   : \" << t + 1 << std::endl;\n    std::cout << \"Edges      : \" << -1 << std::endl;\n    // std::cout << \"\\n\";\n    std::cout << \"BST Flow   : \" << flow << std::endl;\n    // std::cout << \"Sta Flow : \" << flowS << std::endl;\n    // std::cout << \"FF  Flow : \" << FF.E.getFlow() << std::endl;\n    // std::cout << \"\\n\";\n    std::cout << \"BST Time   : \" << S.get_total_time(\"BST\") << std::endl;\n    std::cout << \"READ Time  : \" << S.get_total_time(\"READ\") << std::endl;\n    std::cout << \"TOTAL Time : \" << S.get_total_time(\"TOTAL\") << std::endl;\n    // std::cout << \"Sta Time : \" << S.get_total_time(\"S\") << endl;\n    // std::cout << \"FF  Time : \" << S.get_total_time(\"FF\") << endl;\n    // std::cout << \"\\n\";\n    // std::cout << \"FF Paths : \" << FF.IterationsCount << endl;\n    // std::cout << \"\\n\";\n    // std::cout << \"Push     : \" << RTF.PushCount << endl;\n    // std::cout << \"Relabel  : \" << RTF.RelabelCount << endl;\n    // std::cout << \"Discharge: \" << RTF.DischargeCount << endl;\n\n\n    // std::cout << \"c  The total flow:\" << std::endl;\n    // std::cout << \"s \" << flow << std::endl << std::endl;\n\n    // std::cout << \"c flow values:\" << std::endl;\n    // graph_traits<Graph>::vertex_iterator u_iter, u_end;\n    // graph_traits<Graph>::out_edge_iterator ei, e_end;\n    // for (tie(u_iter, u_end) = vertices(g); u_iter != u_end; ++u_iter)\n    //     for (tie(ei, e_end) = out_edges(*u_iter, g); ei != e_end; ++ei)\n    //         if (capacity[*ei] > 0)\n    //             std::cout << \"f \" << *u_iter << \" \" << target(*ei, g) << \" \" << (capacity[*ei] - residual_capacity[*ei]) << std::endl;\n    return 0;\n}\n", "meta": {"hexsha": "b1f487558b0fcd9c7443371789b76cc96049a3c7", "size": 2809, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "utils/bst.cpp", "max_stars_repo_name": "FamousCake/flow", "max_stars_repo_head_hexsha": "77f134f74996225f679a1b9d796b7328ad6e1867", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "utils/bst.cpp", "max_issues_repo_name": "FamousCake/flow", "max_issues_repo_head_hexsha": "77f134f74996225f679a1b9d796b7328ad6e1867", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "utils/bst.cpp", "max_forks_repo_name": "FamousCake/flow", "max_forks_repo_head_hexsha": "77f134f74996225f679a1b9d796b7328ad6e1867", "max_forks_repo_licenses": ["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.0138888889, "max_line_length": 143, "alphanum_fraction": 0.5806336775, "num_tokens": 828, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389817407017, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.4726120788379057}}
{"text": "/**\n * @author Eric Cousineau <eacousineau@gmail.com>, member of Dr. Aaron\n * Ames's AMBER Lab\n */\n#ifndef EIGEN_OPERATOR_UTILITIES_H\n    #define EIGEN_OPERTAOR_UTILITIES_h\n\n#include <Eigen/Dense>\n\nnamespace Eigen\n{\n\ntemplate<typename Derived>\nEigen::MatrixBase<Derived>& operator-=(Eigen::MatrixBase<Derived> &X, const typename Derived::Scalar &a)\n{\n    // Acceptably inefficient\n    X -= a * Matrix<typename Derived::Scalar, -1, -1>::Ones(X.rows(), X.cols());\n    return X;\n}\n\ntemplate<typename Derived>\nEigen::MatrixBase<Derived>& operator+=(Eigen::MatrixBase<Derived> &X, const typename Derived::Scalar &a)\n{\n    X += a * Matrix<typename Derived::Scalar, -1, -1>::Ones(X.rows(), X.cols());\n    return X;\n}\n\n}\n\n#endif // EIGEN_OPERTAOR_UTILITIES_h\n", "meta": {"hexsha": "ee556cc9be253e5df345dabc7c8a9e6fa457855d", "size": 751, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "eigen_utilities/include/eigen_utilities/operator_utilities.hpp", "max_stars_repo_name": "noelc-s/amber_developer_stack", "max_stars_repo_head_hexsha": "dda28b1b79f8df6eb56c41a0e1b5c1d167631176", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-18T04:36:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-18T04:36:22.000Z", "max_issues_repo_path": "eigen_utilities/include/eigen_utilities/operator_utilities.hpp", "max_issues_repo_name": "noelc-s/amber_developer_stack", "max_issues_repo_head_hexsha": "dda28b1b79f8df6eb56c41a0e1b5c1d167631176", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "eigen_utilities/include/eigen_utilities/operator_utilities.hpp", "max_forks_repo_name": "noelc-s/amber_developer_stack", "max_forks_repo_head_hexsha": "dda28b1b79f8df6eb56c41a0e1b5c1d167631176", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-04T21:22:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-04T21:22:48.000Z", "avg_line_length": 24.2258064516, "max_line_length": 104, "alphanum_fraction": 0.6964047936, "num_tokens": 209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544335934766, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.4725313933280958}}
{"text": "// Bring in gtest\n#include <gtest/gtest.h>\n#include <boost/cstdint.hpp>\n\n// Helpful functions from libasrl\n#include <sm/eigen/gtest.hpp>\n\n#include <sparse_block_matrix/linear_solver_cholmod.h>\n#include <sparse_block_matrix/linear_solver_dense.h>\n#include <sparse_block_matrix/linear_solver_spqr.h>\n\ntemplate <typename SOLVER_T>\nvoid randomSparseBlockMatrix(sparse_block_matrix::SparseBlockMatrix<typename SOLVER_T::matrix_t>* A,\n                             Eigen::MatrixXd& Adense) {\n    typedef typename SOLVER_T::matrix_t SparseMatrixBlock;\n\n    // Fill in like this:\n    //   0  1   2\n    // 0 a\n    // 1    b   d\n    // 2        c\n    //\n    // where a,b,c are symmetric\n    // d is 3x5\n\n    SparseMatrixBlock* a = A->block(0, 0, true);\n    ASSERT_TRUE(a != NULL);\n    ASSERT_EQ(a->rows(), 3);\n    ASSERT_EQ(a->cols(), 3);\n    a->setRandom();\n    *a = (*a * a->transpose()) + Eigen::Matrix3d::Identity();\n    Adense.block(0, 0, 3, 3) = *a;\n\n    SparseMatrixBlock* b = A->block(1, 1, true);\n    ASSERT_TRUE(b != NULL);\n    ASSERT_EQ(b->rows(), 3);\n    ASSERT_EQ(b->cols(), 3);\n    b->setRandom();\n    *b = (*b * b->transpose()) + Eigen::Matrix3d::Identity();\n    Adense.block(3, 3, 3, 3) = *b;\n\n    SparseMatrixBlock* c = A->block(2, 2, true);\n    ASSERT_TRUE(c != NULL);\n    ASSERT_EQ(c->rows(), 5);\n    ASSERT_EQ(c->cols(), 5);\n    c->setRandom();\n    *c = (*c * c->transpose()).eval() + Eigen::MatrixXd::Identity(5, 5);\n    // std::cout << \"c:\\n\" << *c << std::endl;\n    Adense.block(6, 6, 5, 5) = *c;\n\n    SparseMatrixBlock* d = A->block(1, 2, true);\n    ASSERT_TRUE(d != NULL);\n    ASSERT_EQ(d->rows(), 3);\n    ASSERT_EQ(d->cols(), 5);\n    d->setRandom();\n    Adense.block(3, 6, 3, 5) = *d;\n}\n\ntemplate <typename SOLVER_T>\nvoid testSolver(const std::string& solver_name) {\n    // Build up a sparse matrix\n    // 3x3 3x3 3x5\n    // 3x3 3x3 3x5\n    // 5x3 5x3 5x5\n    int rows[] = {3, 6, 11};\n    int cols[] = {3, 6, 11};\n    sparse_block_matrix::SparseBlockMatrix<typename SOLVER_T::matrix_t> A(rows, cols, 3, 3);\n\n    Eigen::MatrixXd Adense(11, 11);\n    Adense.setZero();\n\n    ASSERT_EQ(A.rows(), 11);\n    ASSERT_EQ(A.cols(), 11);\n\n    randomSparseBlockMatrix<SOLVER_T>(&A, Adense);\n\n    Eigen::VectorXd xx(A.rows());\n    xx.setZero();\n    Eigen::VectorXd xx2(A.rows());\n    xx2.setZero();\n\n    SOLVER_T solver;\n    ASSERT_TRUE(solver.init());\n\n    Eigen::VectorXd bb(A.rows());\n    bb.setRandom();\n\n    // virtual bool solve(const SparseBlockMatrix<MatrixType>& A, double* x, double* b) = 0;\n    ASSERT_TRUE(solver.solve(A, &xx[0], &bb[0]));\n    // Solve dense\n    Eigen::VectorXd dx = Adense.selfadjointView<Eigen::Upper>().ldlt().solve(bb);\n\n    //  always solve twice to make sure the value only copying is working for symbolic factorizations\n    randomSparseBlockMatrix<SOLVER_T>(&A, Adense);\n    ASSERT_TRUE(solver.solve(A, &xx2[0], &bb[0]));\n\n    Eigen::VectorXd dx2 = Adense.selfadjointView<Eigen::Upper>().ldlt().solve(bb);\n\n    // Solve dense\n\n    // Make sure the solutions match.\n    sm::eigen::assertNear(dx, xx, 1e-10, SM_SOURCE_FILE_POS, \"A: dense solution, B: solution from \" + solver_name);\n    sm::eigen::assertNear(dx2, xx2, 1e-10, SM_SOURCE_FILE_POS, \"A: dense solution, B: solution from \" + solver_name);\n}\n\n// Check that the setup as a whole is correct\nTEST(g2oTestSuite, testCholmod) {\n    //\n    testSolver<sparse_block_matrix::LinearSolverQr<Eigen::MatrixXd> >(\"sparseQR\");\n\n    testSolver<sparse_block_matrix::LinearSolverCholmod<Eigen::MatrixXd> >(\"cholmod\");\n\n    testSolver<sparse_block_matrix::LinearSolverDense<Eigen::MatrixXd> >(\"dense\");\n}\n", "meta": {"hexsha": "7d932b413b44ce88852d4e4c3ef50acb88652c6d", "size": 3582, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "aslam_optimizer/sparse_block_matrix/test/solver_tests.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_optimizer/sparse_block_matrix/test/solver_tests.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_optimizer/sparse_block_matrix/test/solver_tests.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": 31.147826087, "max_line_length": 117, "alphanum_fraction": 0.6295365717, "num_tokens": 1122, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587586, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.4725313802915215}}
{"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\u00e4nkt), 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_INVERSE_INCLUDE\n#define MATH_INVERSE_INCLUDE\n\n#include <boost/numeric/linear_algebra/operators.hpp>\n#include <boost/numeric/linear_algebra/identity.hpp>\n\nnamespace math {\n\ntemplate <typename Operation, typename Element>\nstruct inverse_t {} ;\n\n\ntemplate <typename Element>\nstruct inverse_t< add<Element>, Element >\n  : public binary_function<add<Element>, Element, Element>\n{ \n    Element operator()(const add<Element>&, const Element& v) const\n    { \n\treturn -v; \n    } \n};\n\n\ntemplate <typename Element>\nstruct inverse_t< mult<Element>, Element >\n  : public binary_function<mult<Element>, Element, Element>\n{ \n    Element operator()(const mult<Element>&, const Element& v) const\n    { \n\treturn one(v) / v ; \n    } \n};\n\n\n// Function is shorter than typetrait-like functor\ntemplate <typename Operation, typename Element>\ninline Element inverse(const Operation& op, const Element& v)\n{\n    return inverse_t<Operation, Element>() (op, v);\n}\n\n\n// Short-cut for multiplicative inverse\ntemplate <typename Element>\ninline Element reciprocal(const Element& v)\n{\n    return inverse(math::mult<Element>(), v);\n}\n\n} // namespace math\n\n#endif // MATH_INVERSE_INCLUDE\n", "meta": {"hexsha": "1f828ead4a7a9160000d2a9b49ab0d12dea9048a", "size": 1680, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/linear_algebra/inverse.hpp", "max_stars_repo_name": "shikharvashistha/mtl4", "max_stars_repo_head_hexsha": "09d8523d59baf5fdec29f3509a63babc2763af4a", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "boost/numeric/linear_algebra/inverse.hpp", "max_issues_repo_name": "shikharvashistha/mtl4", "max_issues_repo_head_hexsha": "09d8523d59baf5fdec29f3509a63babc2763af4a", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "boost/numeric/linear_algebra/inverse.hpp", "max_forks_repo_name": "shikharvashistha/mtl4", "max_forks_repo_head_hexsha": "09d8523d59baf5fdec29f3509a63babc2763af4a", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 25.4545454545, "max_line_length": 94, "alphanum_fraction": 0.7232142857, "num_tokens": 395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673359709796, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4725222946837398}}
{"text": "#ifndef _mpipyp_hh\n#define _mpipyp_hh\n\n#include <math.h>\n#include <map>\n#include <tr1/unordered_map>\n//#include <google/sparse_hash_map>\n\n#include <boost/random/uniform_real.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/tuple/tuple.hpp>\n#include <boost/serialization/map.hpp>\n#include <boost/mpi.hpp>\n#include <boost/mpi/environment.hpp>\n#include <boost/mpi/communicator.hpp>\n#include <boost/mpi/operations.hpp>\n\n\n#include \"pyp.hh\"\n\n//\n// Pitman-Yor process with customer and table tracking\n//\n\ntemplate <typename Dish, typename Hash=std::tr1::hash<Dish> >\nclass MPIPYP : public PYP<Dish, Hash> {\npublic:\n  typedef std::map<Dish, int> dish_delta_type;\n\n  MPIPYP(double a, double b, Hash hash=Hash());\n\n  template < typename Uniform01 >\n    int increment(Dish d, double p0, Uniform01& rnd);\n  template < typename Uniform01 >\n    int decrement(Dish d, Uniform01& rnd);\n\n  void clear();\n  void reset_deltas();\n\n  void synchronise(dish_delta_type* result);\n\nprivate:\n  typedef std::map<Dish, typename PYP<Dish,Hash>::TableCounter> table_delta_type;\n\n  dish_delta_type m_count_delta;\n  table_delta_type m_table_delta;\n};\n\ntemplate <typename Dish, typename Hash>\nMPIPYP<Dish,Hash>::MPIPYP(double a, double b, Hash h)\n: PYP<Dish,Hash>(a, b, 0, h) {}\n\ntemplate <typename Dish, typename Hash>\n  template <typename Uniform01>\nint \nMPIPYP<Dish,Hash>::increment(Dish dish, double p0, Uniform01& rnd) {\n  //std::cerr << \"-----INCREMENT DISH \" << dish << std::endl;\n  int delta = 0;\n  int table_joined=-1;\n  typename PYP<Dish,Hash>::TableCounter &tc = PYP<Dish,Hash>::_dish_tables[dish];\n\n  // seated on a new or existing table?\n  int c = PYP<Dish,Hash>::count(dish); \n  int t = PYP<Dish,Hash>::num_tables(dish); \n  int T = PYP<Dish,Hash>::num_tables();\n  double& a = PYP<Dish,Hash>::_a;\n  double& b = PYP<Dish,Hash>::_b;\n  double pshare = (c > 0) ? (c - a*t) : 0.0;\n  double pnew = (b + a*T) * p0;\n  if (pshare < 0.0) {\n    std::cerr << pshare << \" \" << c << \" \" << a << \" \" << t << std::endl;\n    assert(false);\n  }\n\n  if (rnd() < pnew / (pshare + pnew)) {\n    // assign to a new table\n    tc.tables += 1;\n    tc.table_histogram[1] += 1;\n    PYP<Dish,Hash>::_total_tables += 1;\n    delta = 1;\n    table_joined = 1;\n  }\n  else {\n    // randomly assign to an existing table\n    // remove constant denominator from inner loop\n    double r = rnd() * (c - a*t);\n    for (std::map<int,int>::iterator\n         hit = tc.table_histogram.begin();\n         hit != tc.table_histogram.end(); ++hit) {\n      r -= ((hit->first - a) * hit->second);\n      if (r <= 0) {\n        tc.table_histogram[hit->first+1] += 1;\n        hit->second -= 1;\n        table_joined = hit->first+1;\n        if (hit->second == 0)\n          tc.table_histogram.erase(hit);\n        break;\n      }\n    }\n    if (r > 0) {\n      std::cerr << r << \" \" << c << \" \" << a << \" \" << t << std::endl;\n      assert(false);\n    }\n    delta = 0;\n  }\n\n  std::tr1::unordered_map<Dish,int,Hash>::operator[](dish) += 1;\n  //google::sparse_hash_map<Dish,int,Hash>::operator[](dish) += 1;\n  PYP<Dish,Hash>::_total_customers += 1;\n\n  // MPI Delta handling\n  // track the customer entering\n  typename dish_delta_type::iterator customer_it; \n  bool customer_insert_result; \n  boost::tie(customer_it, customer_insert_result) \n    = m_count_delta.insert(std::make_pair(dish,0)); \n\n  customer_it->second += 1;\n  if (customer_it->second == 0)\n    m_count_delta.erase(customer_it);\n\n  // increment the histogram bar for the table joined\n  /*\n  typename PYP<Dish,Hash>::TableCounter &delta_tc = m_table_delta[dish];\n\n  std::map<int,int> &histogram = delta_tc.table_histogram;\n  assert (table_joined > 0);\n\n  typename std::map<int,int>::iterator table_it; bool table_insert_result; \n  boost::tie(table_it, table_insert_result) = histogram.insert(std::make_pair(table_joined,0)); \n  table_it->second += 1;\n  if (delta == 0) {\n    // decrement the histogram bar for the table left \n    typename std::map<int,int>::iterator left_table_it; \n    boost::tie(left_table_it, table_insert_result) \n      = histogram.insert(std::make_pair(table_joined-1,0)); \n    left_table_it->second -= 1;\n    if (left_table_it->second == 0) histogram.erase(left_table_it);\n  }\n  else delta_tc.tables += 1;\n\n  if (table_it->second == 0) histogram.erase(table_it);\n\n    //std::cerr << \"Added (\" << delta << \") \" << dish << \" to table \" << table_joined << \"\\n\"; \n    //std::cerr << \"Dish \" << dish << \" has \" << count(dish) << \" customers, and is sitting at \" << PYP<Dish,Hash>::num_tables(dish) << \" tables.\\n\"; \n    //for (std::map<int,int>::const_iterator \n    //     hit = delta_tc.table_histogram.begin();\n    //     hit != delta_tc.table_histogram.end(); ++hit) {\n    //  std::cerr << \"    \" << hit->second << \" tables with \" << hit->first << \" customers.\" << std::endl; \n    //}\n    //std::cerr << \"Added (\" << delta << \") \" << dish << \" to table \" << table_joined << \"\\n\"; \n    //std::cerr << \"Dish \" << dish << \" has \" << count(dish) << \" customers, and is sitting at \" << PYP<Dish,Hash>::num_tables(dish) << \" tables.\\n\"; \n    int x_num_customers=0, x_num_table=0;\n    for (std::map<int,int>::const_iterator \n         hit = delta_tc.table_histogram.begin();\n         hit != delta_tc.table_histogram.end(); ++hit) {\n      x_num_table += hit->second;\n      x_num_customers += (hit->second*hit->first);\n    }\n    int tmp_c = PYP<Dish,Hash>::count(dish);\n    int tmp_t = PYP<Dish,Hash>::num_tables(dish);\n    assert (x_num_customers <= tmp_c); \n    assert (x_num_table <= tmp_t); \n\n  if (delta_tc.table_histogram.empty()) {\n    assert (delta_tc.tables == 0);\n    m_table_delta.erase(dish);\n  }\n  */\n\n  //PYP<Dish,Hash>::debug_info(std::cerr);\n  //std::cerr << \"   Dish \" << dish << \" has count \" << PYP<Dish,Hash>::count(dish) << \" tables \" << PYP<Dish,Hash>::num_tables(dish) << std::endl;\n\n  return delta;\n}\n\ntemplate <typename Dish, typename Hash>\n  template <typename Uniform01>\nint \nMPIPYP<Dish,Hash>::decrement(Dish dish, Uniform01& rnd)\n{\n  //std::cerr << \"-----DECREMENT DISH \" << dish << std::endl;\n  typename std::tr1::unordered_map<Dish, int>::iterator dcit = find(dish);\n  //typename google::sparse_hash_map<Dish, int>::iterator dcit = find(dish);\n  if (dcit == PYP<Dish,Hash>::end()) {\n    std::cerr << dish << std::endl;\n    assert(false);\n  } \n\n  int delta = 0, table_left=-1;\n\n  typename std::tr1::unordered_map<Dish, typename PYP<Dish,Hash>::TableCounter>::iterator dtit \n    = PYP<Dish,Hash>::_dish_tables.find(dish);\n  //typename google::sparse_hash_map<Dish, TableCounter>::iterator dtit = _dish_tables.find(dish);\n  if (dtit == PYP<Dish,Hash>::_dish_tables.end()) {\n    std::cerr << dish << std::endl;\n    assert(false);\n  } \n  typename PYP<Dish,Hash>::TableCounter &tc = dtit->second;\n\n  double r = rnd() * PYP<Dish,Hash>::count(dish);\n  for (std::map<int,int>::iterator hit = tc.table_histogram.begin();\n       hit != tc.table_histogram.end(); ++hit) {\n    r -= (hit->first * hit->second);\n    if (r <= 0) {\n      table_left = hit->first;\n      if (hit->first > 1) {\n        tc.table_histogram[hit->first-1] += 1;\n      }\n      else {\n        delta = -1;\n        tc.tables -= 1;\n        PYP<Dish,Hash>::_total_tables -= 1;\n      }\n\n      hit->second -= 1;\n      if (hit->second == 0) tc.table_histogram.erase(hit);\n      break;\n    }\n  }\n  if (r > 0) {\n    std::cerr << r << \" \" << PYP<Dish,Hash>::count(dish) << \" \" << PYP<Dish,Hash>::_a << \" \" \n      << PYP<Dish,Hash>::num_tables(dish) << std::endl;\n    assert(false);\n  }\n\n  // remove the customer\n  dcit->second -= 1;\n  PYP<Dish,Hash>::_total_customers -= 1;\n  assert(dcit->second >= 0);\n  if (dcit->second == 0) {\n    PYP<Dish,Hash>::erase(dcit);\n    PYP<Dish,Hash>::_dish_tables.erase(dtit);\n  }\n\n  // MPI Delta processing\n  typename dish_delta_type::iterator it; \n  bool insert_result; \n  boost::tie(it, insert_result) = m_count_delta.insert(std::make_pair(dish,0)); \n  it->second -= 1;\n  if (it->second == 0) m_count_delta.erase(it);\n\n  assert (table_left > 0);\n  typename PYP<Dish,Hash>::TableCounter& delta_tc = m_table_delta[dish];\n  if (table_left > 1) {\n    std::map<int,int>::iterator tit;\n    boost::tie(tit, insert_result) = delta_tc.table_histogram.insert(std::make_pair(table_left-1,0));\n    tit->second += 1;\n    if (tit->second == 0) delta_tc.table_histogram.erase(tit);\n  }\n  else delta_tc.tables -= 1;\n\n  std::map<int,int>::iterator tit;\n  boost::tie(tit, insert_result) = delta_tc.table_histogram.insert(std::make_pair(table_left,0));\n  tit->second -= 1;\n  if (tit->second == 0) delta_tc.table_histogram.erase(tit);\n\n  //  std::cerr << \"Dish \" << dish << \" has \" << count(dish) << \" customers, and is sitting at \" << PYP<Dish,Hash>::num_tables(dish) << \" tables.\\n\"; \n  //  for (std::map<int,int>::const_iterator \n  //       hit = delta_tc.table_histogram.begin();\n  //       hit != delta_tc.table_histogram.end(); ++hit) {\n  //    std::cerr << \"    \" << hit->second << \" tables with \" << hit->first << \" customers.\" << std::endl; \n  //  }\n    int x_num_customers=0, x_num_table=0;\n    for (std::map<int,int>::const_iterator \n         hit = delta_tc.table_histogram.begin();\n         hit != delta_tc.table_histogram.end(); ++hit) {\n      x_num_table += hit->second;\n      x_num_customers += (hit->second*hit->first);\n    }\n    int tmp_c = PYP<Dish,Hash>::count(dish);\n    int tmp_t = PYP<Dish,Hash>::num_tables(dish);\n    assert (x_num_customers <= tmp_c); \n    assert (x_num_table <= tmp_t); \n\n  if (delta_tc.table_histogram.empty()) {\n  //  std::cerr << \"   DELETING \" << dish << std::endl;\n    assert (delta_tc.tables == 0);\n    m_table_delta.erase(dish);\n  }\n\n  //PYP<Dish,Hash>::debug_info(std::cerr);\n  //std::cerr << \"   Dish \" << dish << \" has count \" << PYP<Dish,Hash>::count(dish) << \" tables \" << PYP<Dish,Hash>::num_tables(dish) << std::endl;\n  return delta;\n}\n\ntemplate <typename Dish, typename Hash>\nvoid \nMPIPYP<Dish,Hash>::clear() {\n  PYP<Dish,Hash>::clear();\n  reset_deltas();\n}\n\ntemplate <typename Dish, typename Hash>\nvoid \nMPIPYP<Dish,Hash>::reset_deltas() { \n  m_count_delta.clear(); \n  m_table_delta.clear();\n}\n\ntemplate <typename Dish>\nstruct sum_maps {\n  typedef std::map<Dish,int> map_type;\n  map_type& operator() (map_type& l, map_type const & r) const {\n    for (typename map_type::const_iterator it=r.begin(); it != r.end(); it++)\n      l[it->first] += it->second;\n    return l;\n  }\n};\n\ntemplate <typename Dish>\nstruct subtract_maps {\n  typedef std::map<Dish,int> map_type;\n  map_type& operator() (map_type& l, map_type const & r) const {\n    for (typename map_type::const_iterator it=r.begin(); it != r.end(); it++)\n      l[it->first] -= it->second;\n    return l;\n  }\n};\n\n// Needed Boost definitions\nnamespace boost { \n  namespace mpi {\n    template <>\n    struct is_commutative< sum_maps<int>, std::map<int,int> > : mpl::true_ {};\n  }\n\n  namespace serialization {\n    template<class Archive>\n    void serialize(Archive & ar, PYP<int>::TableCounter& t, const unsigned int version) {\n      ar & t.table_histogram;\n      ar & t.tables;\n    }\n\n  } // namespace serialization\n} // namespace boost\n\ntemplate <typename A, typename B, typename C>\nstruct triple {\n  triple() {}\n  triple(const A& a, const B& b, const C& c) : first(a), second(b), third(c) {}\n  A first;\n  B second;\n  C third;\n\n  template<class Archive>\n  void serialize(Archive &ar, const unsigned int version){\n      ar & first;\n      ar & second;\n      ar & third;\n  }\n};\n\nBOOST_IS_BITWISE_SERIALIZABLE(MPIPYP<int>::dish_delta_type)\nBOOST_CLASS_TRACKING(MPIPYP<int>::dish_delta_type,track_never)\n\ntemplate <typename Dish, typename Hash>\nvoid \nMPIPYP<Dish,Hash>::synchronise(dish_delta_type* result) {\n  boost::mpi::communicator world; \n  //int rank = world.rank(), size = world.size();\n\n  boost::mpi::all_reduce(world, m_count_delta, *result, sum_maps<Dish>());\n  subtract_maps<Dish>()(*result, m_count_delta);\n \n/*\n  // communicate the customer count deltas\n  dish_delta_type global_dish_delta;\n  boost::mpi::all_reduce(world, m_count_delta, global_dish_delta, sum_maps<Dish>());\n\n  // update this restaurant\n  for (typename dish_delta_type::const_iterator it=global_dish_delta.begin(); \n       it != global_dish_delta.end(); ++it) {\n    int global_delta = it->second - m_count_delta[it->first];\n    if (global_delta == 0) continue;\n    typename std::tr1::unordered_map<Dish,int,Hash>::iterator dit; bool inserted;\n    boost::tie(dit, inserted) \n      = std::tr1::unordered_map<Dish,int,Hash>::insert(std::make_pair(it->first, 0));\n    dit->second += global_delta;\n    assert(dit->second >= 0);\n    if (dit->second == 0) {\n      std::tr1::unordered_map<Dish,int,Hash>::erase(dit);\n    }\n\n    PYP<Dish,Hash>::_total_customers += (it->second - m_count_delta[it->first]);\n    int tmp = PYP<Dish,Hash>::_total_customers;\n    assert(tmp >= 0);\n    //std::cerr << \"Process \" << rank << \" adding \" <<  (it->second - m_count_delta[it->first]) << \" of customer \" << it->first << std::endl;\n  }\n*/\n/*\n  // communicate the table count deltas\n  for (int process = 0; process < size; ++process) {\n    typename std::vector< triple<Dish, int, int> > message;\n    if (rank == process) {\n      // broadcast deltas\n      for (typename table_delta_type::const_iterator dish_it=m_table_delta.begin(); \n           dish_it != m_table_delta.end(); ++dish_it) {\n        //assert (dish_it->second.tables > 0);\n        for (std::map<int,int>::const_iterator it=dish_it->second.table_histogram.begin(); \n             it != dish_it->second.table_histogram.end(); ++it) {\n          triple<Dish, int, int> m(dish_it->first, it->first, it->second);\n          message.push_back(m);\n        }\n        // append a special message with the total table delta for this dish\n        triple<Dish, int, int> m(dish_it->first, -1, dish_it->second.tables);\n        message.push_back(m);\n      }\n      boost::mpi::broadcast(world, message, process);\n    }\n    else {\n      // receive deltas\n      boost::mpi::broadcast(world, message, process);\n      for (typename std::vector< triple<Dish, int, int> >::const_iterator it=message.begin(); it != message.end(); ++it) {\n        typename PYP<Dish,Hash>::TableCounter& tc = PYP<Dish,Hash>::_dish_tables[it->first];\n        if (it->second >= 0) {\n          std::map<int,int>::iterator tit; bool inserted;\n          boost::tie(tit, inserted) = tc.table_histogram.insert(std::make_pair(it->second, 0));\n          tit->second += it->third;\n          if (tit->second < 0) {\n            std::cerr << tit->first << \" \" << tit->second << \" \" << it->first << \" \" << it->second << \" \" << it->third << std::endl;\n            assert(tit->second >= 0);\n          }\n          if (tit->second == 0) {\n            tc.table_histogram.erase(tit);\n          }\n        }\n        else {\n          tc.tables += it->third;\n          PYP<Dish,Hash>::_total_tables += it->third;\n          assert(tc.tables >= 0);\n          if (tc.tables == 0) assert(tc.table_histogram.empty());\n          if (tc.table_histogram.empty()) {\n            assert (tc.tables == 0);\n            PYP<Dish,Hash>::_dish_tables.erase(it->first);\n          }\n        }\n      }\n    }\n  }\n*/\n\n//  reset_deltas();\n}\n\n#endif\n", "meta": {"hexsha": "c2341b9e36d900b7cdff33a4d7ebdab417744286", "size": 15123, "ext": "hh", "lang": "C++", "max_stars_repo_path": "gi/pyp-topics/src/mpi-pyp.hh", "max_stars_repo_name": "agesmundo/FasterCubePruning", "max_stars_repo_head_hexsha": "f80150140b5273fd1eb0dfb34bdd789c4cbd35e6", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL", "Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-06-03T00:44:01.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-03T00:44:01.000Z", "max_issues_repo_path": "gi/pyp-topics/src/mpi-pyp.hh", "max_issues_repo_name": "jhclark/cdec", "max_issues_repo_head_hexsha": "237ddc67ffa61da310e19710f902d4771dc323c2", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL", "Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gi/pyp-topics/src/mpi-pyp.hh", "max_forks_repo_name": "jhclark/cdec", "max_forks_repo_head_hexsha": "237ddc67ffa61da310e19710f902d4771dc323c2", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL", "Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-19T12:44:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-19T12:44:54.000Z", "avg_line_length": 33.7566964286, "max_line_length": 150, "alphanum_fraction": 0.6183296965, "num_tokens": 4375, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673359709795, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.47252229468373974}}
{"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 <iostream>\n#include \"vision-precomp.h\"  // Precompiled headers\n\n//#include <mrpt/math/types_math.h>  // Eigen must be included first via MRPT to\n// enable the plugin system\n#include <Eigen/Dense>\n#include <Eigen/SVD>\n#include <Eigen/StdVector>\n\n#include \"lhm.h\"\nusing namespace mrpt::vision::pnp;\n\nlhm::lhm(\n\tEigen::MatrixXd obj_pts_, Eigen::MatrixXd img_pts_, Eigen::MatrixXd cam_,\n\tint n0)\n\t: F(n0)\n{\n\tobj_pts = obj_pts_;\n\timg_pts = img_pts_;\n\tcam_intrinsic = cam_;\n\tn = n0;\n\n\t// Store obj_pts as 3XN and img_projections as 2XN matrices\n\tP = obj_pts.transpose();\n\tQ = Eigen::MatrixXd::Ones(3, n);\n\n\tQ = img_pts.transpose();\n\n\tt.setZero();\n}\n\nvoid lhm::estimate_t()\n{\n\tEigen::Vector3d sum_;\n\tsum_.setZero();\n\tfor (int i = 0; i < n; i++) sum_ += F[i] * R * P.col(i);\n\tt = G * sum_;\n}\n\nvoid lhm::xform()\n{\n\tfor (int i = 0; i < n; i++) Q.col(i) = R * P.col(i) + t;\n}\n\nEigen::Matrix4d lhm::qMatQ(Eigen::VectorXd q)\n{\n\tEigen::Matrix4d Q_(4, 4);\n\n\tQ_ << q(0), -q(1), -q(2), -q(3), q(1), q(0), -q(3), q(2), q(2), q(3), q(0),\n\t\t-q(1), q(3), -q(2), q(1), q(0);\n\n\treturn Q_;\n}\n\nEigen::Matrix4d lhm::qMatW(Eigen::VectorXd q)\n{\n\tEigen::Matrix4d Q_(4, 4);\n\n\tQ_ << q(0), -q(1), -q(2), -q(3), q(1), q(0), q(3), -q(2), q(2), -q(3), q(0),\n\t\tq(1), q(3), q(2), -q(1), q(0);\n\n\treturn Q_;\n}\n\nvoid lhm::absKernel()\n{\n\tfor (int i = 0; i < n; i++) Q.col(i) = F[i] * Q.col(i);\n\n\tEigen::Vector3d P_bar, Q_bar;\n\tP_bar = P.rowwise().mean();\n\tQ_bar = Q.rowwise().mean();\n\n\tfor (int i = 0; i < n; i++)\n\t{\n\t\tP.col(i) = P.col(i) - P_bar;\n\t\tQ.col(i) = Q.col(i) - Q_bar;\n\t}\n\n\t//<------------------- Use SVD Solution ------------------->//\n\t/*\n\tEigen::Matrix3d M;\n\tM.setZero();\n\n\tfor (i = 0; i < n; i++)\n\t\tM += P.col(i)*Q.col(i).transpose();\n\n\tEigen::JacobiSVD<Eigen::MatrixXd> svd(M, Eigen::ComputeThinU |\n\tEigen::ComputeThinV);\n\n\tR = svd.matrixV()*svd.matrixU().transpose();\n\n\tEigen::Matrix3d dummy;\n\tdummy.col(0) = -svd.matrixV().col(0);\n\tdummy.col(1) = -svd.matrixV().col(1);\n\tdummy.col(2) = svd.matrixV().col(2);\n\n\tif (R.determinant() == 1)\n\t{\n\t\testimate_t();\n\t\tif (t(2) < 0)\n\t\t{\n\t\t\tR = dummy*svd.matrixU().transpose();\n\t\t\testimate_t();\n\t\t}\n\t}\n\telse\n\t{\n\t\tR = -dummy*svd.matrixU().transpose();\n\t\testimate_t();\n\t\tif (t(2) < 0)\n\t\t{\n\t\t\tR = -svd.matrixV()*svd.matrixU().transpose();\n\t\t\testimate_t();\n\t\t}\n\t}\n\n\terr2 = 0;\n\txform();\n\n\tEigen::Vector3d vec;\n\tEigen::Matrix3d I3 = Eigen::MatrixXd::Identity(3, 3);\n\n\tfor (i = 0; i < n; i++)\n\t{\n\t\tvec = (I3 - F[i])*Q.col(i);\n\t\terr2 += vec.squaredNorm();\n\t}\n\t*/\n\t//<------------------- Use QTN Solution ------------------->//\n\n\tEigen::Matrix4d A;\n\tA.setZero();\n\n\tfor (int i = 0; i < n; i++)\n\t{\n\t\tEigen::Vector4d q1, q2;\n\t\tq1 << 1, Q.col(i);\n\t\tq2 << 1, P.col(i);\n\t\tA += qMatQ(q1).transpose() * qMatW(q2);\n\t}\n\n\tEigen::EigenSolver<Eigen::Matrix4d> es(A);\n\n\tconst Eigen::Matrix4d Ae = es.pseudoEigenvalueMatrix();\n\tEigen::Vector4d D;  // Ae.diagonal(); for some reason this leads to an\n\t// internal compiler error in MSVC11... (sigh)\n\tfor (int i = 0; i < 4; i++) D[i] = Ae(i, i);\n\n\tEigen::Matrix4d V_mat = es.pseudoEigenvectors();\n\n\tEigen::Vector4d::Index max_index;\n\n\tD.maxCoeff(&max_index);\n\n\tEigen::Vector4d V;\n\n\tV = V_mat.col(max_index);\n\n\tEigen::Quaterniond q(V(0), V(1), V(2), V(3));\n\n\tR = q.toRotationMatrix();\n\n\testimate_t();\n\n\terr2 = 0;\n\txform();\n\n\tEigen::Vector3d vec;\n\tEigen::Matrix3d I3 = Eigen::MatrixXd::Identity(3, 3);\n\n\tfor (int i = 0; i < n; i++)\n\t{\n\t\tvec = (I3 - F[i]) * Q.col(i);\n\t\terr2 += vec.squaredNorm();\n\t}\n}\n\nbool lhm::compute_pose(\n\tEigen::Ref<Eigen::Matrix3d> R_, Eigen::Ref<Eigen::Vector3d> t_)\n{\n\tint i, j = 0;\n\n\tEigen::VectorXd p_bar;\n\tEigen::Matrix3d sum_F, I3;\n\tI3 = Eigen::MatrixXd::Identity(3, 3);\n\tsum_F.setZero();\n\n\tp_bar = P.rowwise().mean();\n\n\tfor (i = 0; i < n; i++)\n\t{\n\t\tP.col(i) -= p_bar;\n\t\tF[i] = Q.col(i) * Q.col(i).transpose() / Q.col(i).squaredNorm();\n\t\tsum_F = sum_F + F[i];\n\t}\n\n\tG = (I3 - sum_F / n).inverse() / n;\n\n\terr = 0;\n\terr2 = 1000;\n\tabsKernel();\n\n\twhile (std::abs(err2 - err) > TOL_LHM && err2 > EPSILON_LHM)\n\t{\n\t\terr = err2;\n\n\t\tabsKernel();\n\n\t\tj += 1;\n\t\tif (j > 100) break;\n\t}\n\n\tR_ = R;\n\tt_ = t - R * p_bar;\n\n\treturn true;\n}\n", "meta": {"hexsha": "1406de2798c39a32a6fa42099bba06066254b323", "size": 4720, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/vision/src/pnp/lhm.cpp", "max_stars_repo_name": "zarmomin/mrpt", "max_stars_repo_head_hexsha": "1baff7cf8ec9fd23e1a72714553bcbd88c201966", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-10T06:24:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-10T06:24:08.000Z", "max_issues_repo_path": "libs/vision/src/pnp/lhm.cpp", "max_issues_repo_name": "gao-ouyang/mrpt", "max_issues_repo_head_hexsha": "4af5fdf7e45b00be4a64c3d4f009acb9ef415ec7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/vision/src/pnp/lhm.cpp", "max_forks_repo_name": "gao-ouyang/mrpt", "max_forks_repo_head_hexsha": "4af5fdf7e45b00be4a64c3d4f009acb9ef415ec7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-09-11T02:55:04.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-11T02:55:04.000Z", "avg_line_length": 20.7929515419, "max_line_length": 80, "alphanum_fraction": 0.5281779661, "num_tokens": 1667, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4725222841427347}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*!\n Copyright (C) 2005, 2006 Theo Boafo\n Copyright (C) 2006, 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// the only header you need to use QuantLib\n#include <ql/quantlib.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\n#define LENGTH(a) (sizeof(a)/sizeof(a[0]))\n\nusing namespace QuantLib;\n\n#if defined(QL_ENABLE_SESSIONS)\nnamespace QuantLib {\n\n    Integer sessionId() { return 0; }\n\n}\n#endif\n\n\nint main(int, char* []) {\n\n    try {\n\n        boost::timer timer;\n        std::cout << std::endl;\n\n        Option::Type type(Option::Put);\n        Real underlying = 36.0;\n        Real spreadRate = 0.005;\n\n        Spread dividendYield = 0.02;\n        Rate riskFreeRate = 0.06;\n        Volatility volatility = 0.20;\n\n        Integer settlementDays = 3;\n        Integer length = 5;\n        Real redemption = 100.0;\n        Real conversionRatio = redemption/underlying; // at the money\n\n        // set up dates/schedules\n        Calendar calendar = TARGET();\n        Date today = calendar.adjust(Date::todaysDate());\n\n        Settings::instance().evaluationDate() = today;\n        Date settlementDate = calendar.advance(today, settlementDays, Days);\n        Date exerciseDate = calendar.advance(settlementDate, length, Years);\n        Date issueDate = calendar.advance(exerciseDate, -length, Years);\n\n        BusinessDayConvention convention = ModifiedFollowing;\n\n        Frequency frequency = Annual;\n\n        Schedule schedule(issueDate, exerciseDate,\n                          Period(frequency), calendar,\n                          convention, convention,\n                          DateGeneration::Backward, false);\n\n        DividendSchedule dividends;\n        CallabilitySchedule callability;\n\n        std::vector<Real> coupons(1, 0.05);\n\n        DayCounter bondDayCount = Thirty360();\n\n        Integer callLength[] = { 2, 4 };  // Call dates, years 2, 4.\n        Integer putLength[] = { 3 }; // Put dates year 3\n\n        Real callPrices[] = { 101.5, 100.85 };\n        Real putPrices[]= { 105.0 };\n\n        // Load call schedules\n        for (Size i=0; i<LENGTH(callLength); i++) {\n            callability.push_back(\n                   boost::shared_ptr<Callability>(\n                       new SoftCallability(Callability::Price(\n                                                   callPrices[i],\n                                                   Callability::Price::Clean),\n                                           schedule.date(callLength[i]),\n                                           1.20)));\n        }\n\n        for (Size j=0; j<LENGTH(putLength); j++) {\n            callability.push_back(\n                   boost::shared_ptr<Callability>(\n                           new Callability(Callability::Price(\n                                                   putPrices[j],\n                                                   Callability::Price::Clean),\n                                           Callability::Put,\n                                           schedule.date(putLength[j]))));\n        }\n\n        // Assume dividends are paid every 6 months.\n        for (Date d = today + 6*Months; d < exerciseDate; d += 6*Months) {\n            dividends.push_back(\n                      boost::shared_ptr<Dividend>(new FixedDividend(1.0, d)));\n        }\n\n        DayCounter dayCounter = Actual365Fixed();\n        Time maturity = dayCounter.yearFraction(settlementDate,\n                                                exerciseDate);\n\n        std::cout << \"option type = \"  << type << std::endl;\n        std::cout << \"Time to maturity = \"        << maturity\n                  << std::endl;\n        std::cout << \"Underlying price = \"        << underlying\n                  << std::endl;\n        std::cout << \"Risk-free interest rate = \" << io::rate(riskFreeRate)\n                  << std::endl;\n        std::cout << \"Dividend yield = \" << io::rate(dividendYield)\n                  << std::endl;\n        std::cout << \"Volatility = \" << io::volatility(volatility)\n                  << std::endl;\n        std::cout << std::endl;\n\n        std::string method;\n        std::cout << std::endl ;\n\n        // write column headings\n        Size widths[] = { 35, 14, 14 };\n        Size totalWidth = widths[0] + widths[1] + widths[2];\n        std::string rule(totalWidth, '-'), dblrule(totalWidth, '=');\n\n        std::cout << dblrule << std::endl;\n        std::cout << \"Tsiveriotis-Fernandes method\" << std::endl;\n        std::cout << dblrule << std::endl;\n        std::cout << std::setw(widths[0]) << std::left << \"Tree type\"\n                  << std::setw(widths[1]) << std::left << \"European\"\n                  << std::setw(widths[1]) << std::left << \"American\"\n                  << std::endl;\n        std::cout << rule << std::endl;\n\n        boost::shared_ptr<Exercise> exercise(\n                                          new EuropeanExercise(exerciseDate));\n        boost::shared_ptr<Exercise> amExercise(\n                                          new AmericanExercise(settlementDate,\n                                                               exerciseDate));\n\n        Handle<Quote> underlyingH(\n            boost::shared_ptr<Quote>(new SimpleQuote(underlying)));\n\n        Handle<YieldTermStructure> flatTermStructure(\n            boost::shared_ptr<YieldTermStructure>(\n                new FlatForward(settlementDate, riskFreeRate, dayCounter)));\n\n        Handle<YieldTermStructure> flatDividendTS(\n            boost::shared_ptr<YieldTermStructure>(\n                new FlatForward(settlementDate, dividendYield, dayCounter)));\n\n        Handle<BlackVolTermStructure> flatVolTS(\n            boost::shared_ptr<BlackVolTermStructure>(\n                new BlackConstantVol(settlementDate, calendar,\n                                     volatility, dayCounter)));\n\n\n        boost::shared_ptr<BlackScholesMertonProcess> stochasticProcess(\n                              new BlackScholesMertonProcess(underlyingH,\n                                                            flatDividendTS,\n                                                            flatTermStructure,\n                                                            flatVolTS));\n\n        Size timeSteps = 801;\n\n        Handle<Quote> creditSpread(\n                       boost::shared_ptr<Quote>(new SimpleQuote(spreadRate)));\n\n        boost::shared_ptr<Quote> rate(new SimpleQuote(riskFreeRate));\n\n        Handle<YieldTermStructure> discountCurve(\n                boost::shared_ptr<YieldTermStructure>(\n                    new FlatForward(today, Handle<Quote>(rate), dayCounter)));\n\n        boost::shared_ptr<PricingEngine> engine(\n                  new BinomialConvertibleEngine<JarrowRudd>(stochasticProcess,\n                                                            timeSteps));\n\n        ConvertibleFixedCouponBond europeanBond(\n                            exercise, conversionRatio, dividends, callability,\n                            creditSpread, issueDate, settlementDays,\n                            coupons, bondDayCount, schedule, redemption);\n        europeanBond.setPricingEngine(engine);\n\n        ConvertibleFixedCouponBond americanBond(\n                          amExercise, conversionRatio, dividends, callability,\n                          creditSpread, issueDate, settlementDays,\n                          coupons, bondDayCount, schedule, redemption);\n        americanBond.setPricingEngine(engine);\n\n        method = \"Jarrow-Rudd\";\n        europeanBond.setPricingEngine(boost::shared_ptr<PricingEngine>(\n                  new BinomialConvertibleEngine<JarrowRudd>(stochasticProcess,\n                                                            timeSteps)));\n        americanBond.setPricingEngine(boost::shared_ptr<PricingEngine>(\n                  new BinomialConvertibleEngine<JarrowRudd>(stochasticProcess,\n                                                            timeSteps)));\n        std::cout << std::setw(widths[0]) << std::left << method\n                  << std::fixed\n                  << std::setw(widths[1]) << std::left << europeanBond.NPV()\n                  << std::setw(widths[2]) << std::left << americanBond.NPV()\n                  << std::endl;\n\n        method = \"Cox-Ross-Rubinstein\";\n        europeanBond.setPricingEngine(boost::shared_ptr<PricingEngine>(\n           new BinomialConvertibleEngine<CoxRossRubinstein>(stochasticProcess,\n                                                            timeSteps)));\n        americanBond.setPricingEngine(boost::shared_ptr<PricingEngine>(\n           new BinomialConvertibleEngine<CoxRossRubinstein>(stochasticProcess,\n                                                            timeSteps)));\n        std::cout << std::setw(widths[0]) << std::left << method\n                  << std::fixed\n                  << std::setw(widths[1]) << std::left << europeanBond.NPV()\n                  << std::setw(widths[2]) << std::left << americanBond.NPV()\n                  << std::endl;\n\n        method = \"Additive equiprobabilities\";\n        europeanBond.setPricingEngine(boost::shared_ptr<PricingEngine>(\n                   new BinomialConvertibleEngine<AdditiveEQPBinomialTree>(\n                                                            stochasticProcess,\n                                                            timeSteps)));\n        americanBond.setPricingEngine(boost::shared_ptr<PricingEngine>(\n                   new BinomialConvertibleEngine<AdditiveEQPBinomialTree>(\n                                                            stochasticProcess,\n                                                            timeSteps)));\n        std::cout << std::setw(widths[0]) << std::left << method\n                  << std::fixed\n                  << std::setw(widths[1]) << std::left << europeanBond.NPV()\n                  << std::setw(widths[2]) << std::left << americanBond.NPV()\n                  << std::endl;\n\n        method = \"Trigeorgis\";\n        europeanBond.setPricingEngine(boost::shared_ptr<PricingEngine>(\n                  new BinomialConvertibleEngine<Trigeorgis>(stochasticProcess,\n                                                            timeSteps)));\n        americanBond.setPricingEngine(boost::shared_ptr<PricingEngine>(\n                  new BinomialConvertibleEngine<Trigeorgis>(stochasticProcess,\n                                                            timeSteps)));\n        std::cout << std::setw(widths[0]) << std::left << method\n                  << std::fixed\n                  << std::setw(widths[1]) << std::left << europeanBond.NPV()\n                  << std::setw(widths[2]) << std::left << americanBond.NPV()\n                  << std::endl;\n\n        method = \"Tian\";\n        europeanBond.setPricingEngine(boost::shared_ptr<PricingEngine>(\n                        new BinomialConvertibleEngine<Tian>(stochasticProcess,\n                                                            timeSteps)));\n        americanBond.setPricingEngine(boost::shared_ptr<PricingEngine>(\n                        new BinomialConvertibleEngine<Tian>(stochasticProcess,\n                                                            timeSteps)));\n        std::cout << std::setw(widths[0]) << std::left << method\n                  << std::fixed\n                  << std::setw(widths[1]) << std::left << europeanBond.NPV()\n                  << std::setw(widths[2]) << std::left << americanBond.NPV()\n                  << std::endl;\n\n        method = \"Leisen-Reimer\";\n        europeanBond.setPricingEngine(boost::shared_ptr<PricingEngine>(\n                new BinomialConvertibleEngine<LeisenReimer>(stochasticProcess,\n                                                            timeSteps)));\n        americanBond.setPricingEngine(boost::shared_ptr<PricingEngine>(\n                new BinomialConvertibleEngine<LeisenReimer>(stochasticProcess,\n                                                            timeSteps)));\n        std::cout << std::setw(widths[0]) << std::left << method\n                  << std::fixed\n                  << std::setw(widths[1]) << std::left << europeanBond.NPV()\n                  << std::setw(widths[2]) << std::left << americanBond.NPV()\n                  << std::endl;\n\n        method = \"Joshi\";\n        europeanBond.setPricingEngine(boost::shared_ptr<PricingEngine>(\n                      new BinomialConvertibleEngine<Joshi4>(stochasticProcess,\n                                                            timeSteps)));\n        americanBond.setPricingEngine(boost::shared_ptr<PricingEngine>(\n                      new BinomialConvertibleEngine<Joshi4>(stochasticProcess,\n                                                            timeSteps)));\n        std::cout << std::setw(widths[0]) << std::left << method\n                  << std::fixed\n                  << std::setw(widths[1]) << std::left << europeanBond.NPV()\n                  << std::setw(widths[2]) << std::left << americanBond.NPV()\n                  << std::endl;\n\n        std::cout << dblrule << std::endl;\n\n        double seconds = timer.elapsed();\n        Integer hours = int(seconds/3600);\n        seconds -= hours * 3600;\n        Integer minutes = int(seconds/60);\n        seconds -= minutes * 60;\n        std::cout << \" \\nRun completed in \";\n        if (hours > 0)\n            std::cout << hours << \" h \";\n        if (hours > 0 || minutes > 0)\n            std::cout << minutes << \" m \";\n        std::cout << std::fixed << std::setprecision(0)\n                  << seconds << \" s\\n\" << std::endl;\n\n        return 0;\n    } catch (std::exception& e) {\n        std::cerr << e.what() << std::endl;\n        return 1;\n    } catch (...) {\n        std::cerr << \"unknown error\" << std::endl;\n        return 1;\n    }\n\n}\n\n", "meta": {"hexsha": "c847870c8f1fe140bc0456a087760f43c13f1201", "size": 14764, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QuantLib/Examples/ConvertibleBonds/ConvertibleBonds.cpp", "max_stars_repo_name": "txu2014/quantlib", "max_stars_repo_head_hexsha": "95c7d94906c30d0c3c4e0758a2ebfe2a62b075ec", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-09-13T22:40:22.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-18T12:51:41.000Z", "max_issues_repo_path": "QuantLib/Examples/ConvertibleBonds/ConvertibleBonds.cpp", "max_issues_repo_name": "txu2014/quantlib", "max_issues_repo_head_hexsha": "95c7d94906c30d0c3c4e0758a2ebfe2a62b075ec", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "QuantLib/Examples/ConvertibleBonds/ConvertibleBonds.cpp", "max_forks_repo_name": "txu2014/quantlib", "max_forks_repo_head_hexsha": "95c7d94906c30d0c3c4e0758a2ebfe2a62b075ec", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-06-27T19:25:30.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-27T19:25:30.000Z", "avg_line_length": 43.5516224189, "max_line_length": 79, "alphanum_fraction": 0.5221484692, "num_tokens": 3003, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4725222841427347}}
{"text": "\n#include <cassert>\n\n// Before doing anything else, grab in the definitions of the test\n// space and trial spaces that make up the finite element system.\n#include <qdove/base/test_space.h>\n#include <qdove/base/trial_space.h>\n#include <qdove/materials/constants.h>\n\n// Use the *solution* to a fick equation as a material function\n#include <qdove/models/fick.h>\n\n// Start by solving Schroedinger's problem\n#include <qdove/models/schroedinger.h>\n\n// and next by solving Poissons's problem\n#include <qdove/models/poisson.h>\n\n// Fermi-Dirac statistic play a role later here\n#include <qdove/models/statistics.h>\n\n// Also make use of the predefined generalised eigenspectrum system -\n// we need this for the Schroedinger problem.\n#include <qdove/generic_linear_algebra/eigenspectrum_system.h>\n\n// Also make use of the predefined linear algebra system - we need\n// this for the Poisson problem.\n#include <qdove/generic_linear_algebra/linear_algebra_system.h>\n\n// Next up are some deal.II objects that have not been generalised\n// away yet...\n#include <deal.II/grid/tria.h>\n#include <deal.II/grid/grid_generator.h>\n#include <deal.II/numerics/data_out.h>\n\n// The purpose of this example is to have a working (dimensionless)\n// Schroedinger-Poisson solver that can be generalised piecewise to\n// the qdove library.\n//\ntemplate<int dim>\nclass SelfConsistentProblem\n{\npublic:\n  SelfConsistentProblem (dealii::Triangulation<dim> &triangulation);\n  ~SelfConsistentProblem ();\n\n  void write_gnuplot (const dealii::PETScWrappers::Vector &vector,\n          const std::string                   &name,\n          const unsigned int                   cycle);\n  void run ();\n\nprivate:\n  // The description of the finite element basis\n  qdove::TrialSpace<dim> trial_space;\n\n  // Geometry description and boundary constraints\n  qdove::TestSpace<dim> test_space;\n\n  // Fick's problem, which is used to obtain a material profile.\n  qdove::Fick::Solution<1> fick_solution;\n\n  // The eigenspectrum system that will be solved by SLEPc\n  qdove::Schroedinger::Problem<dim> schroedinger_problem;\n\n  // The system of equations that will be solved by PETSc\n  qdove::Poisson::Problem<dim> poisson_problem;\n\n  // The eigenpairs from schroedinger's problem\n  std::vector<dealii::PETScWrappers::Vector> eigenvectors;\n  std::vector<double>                        eigenvalues;\n\n  // The solution from poisson's problem\n  dealii::PETScWrappers::Vector solution;\n\n};\n\ntemplate<int dim>\nSelfConsistentProblem<dim>::SelfConsistentProblem (dealii::Triangulation<dim> &triangulation)\n  :\n  trial_space (triangulation),\n  test_space (trial_space),\n  fick_solution (trial_space, test_space),\n  schroedinger_problem (trial_space, test_space, 10),\n  poisson_problem (trial_space, test_space)\n{}\n\ntemplate<int dim>\nSelfConsistentProblem<dim>::~SelfConsistentProblem ()\n{}\n\ntemplate<int dim>\nvoid\nSelfConsistentProblem<dim>::write_gnuplot (const dealii::PETScWrappers::Vector &vector,\n             const std::string                   &name,\n             const unsigned int                   cycle)\n{\n  // Output a vector to gnuplot style file.\n  std::ostringstream filename;\n  filename << \"solution-\" << name << \"-\" << cycle << \".gpl\";\n  std::ofstream output (filename.str ().c_str ());\n\n  dealii::DataOut<dim> data_out;\n  data_out.attach_dof_handler (test_space.dofs ());\n  data_out.add_data_vector (vector, name);\n\n  // generate default patches and output.\n  data_out.build_patches ();\n  data_out.write_gnuplot (output);\n}\n\n\ntemplate<int dim>\nvoid\nSelfConsistentProblem<dim>::run ()\n{\n  std::cout << \"Test space:\" << std::endl\n      << \"   Finite element type:          \"\n      << test_space.fe ().get_name ()\n      << std::endl\n      << \"   Number of degrees of freedom: \"\n      << test_space.n_dofs ()\n      << std::endl;\n\n  const double radius       = 50e-10;\n  const double band_edge    = 0.5 * qdove::E0;\n  const double fermi_energy = band_edge * 0.95; //for simplicity we take the bond energy to be 5% below the band edge\n  const double doping       = 1e25;\n\n  // Setup a material function:\n  fick_solution.reinit ();\n  fick_solution.set_initial_length (0.5*radius);\n  fick_solution.set_initial_height (1.);\n  fick_solution.set_initial_rate(1e-10);\n\n  dealii::PETScWrappers::Vector material_function (test_space.n_dofs ());\n  fick_solution.interpolate_analytic_solution (material_function);\n\n  // Setup an initial potential based on the material function:\n  dealii::PETScWrappers::Vector initial_potential (test_space.n_dofs ());\n  for (std::size_t i=0; i<initial_potential.size(); ++i)\n    initial_potential[i] = -material_function[i] * band_edge + band_edge;\n  write_gnuplot (initial_potential, \"initial_potential\", 0);\n\n  // set up the effective mass, to keep things simple assume a constant effective mass\n  dealii::PETScWrappers::Vector eff_mass (test_space.n_dofs ());\n  for (std::size_t i=0; i<eff_mass.size(); ++i)\n    eff_mass[i] = qdove::mstar_GaAs;\n  write_gnuplot (eff_mass, \"effective_mass\", 0);\n\n  // Setup the kinetic energy term\n  dealii::PETScWrappers::Vector kinetic (test_space.n_dofs ());\n  for (std::size_t i=0; i<eff_mass.size(); ++i)\n    kinetic[i] = (qdove::HBAR*qdove::HBAR) / (2.*eff_mass[i]*qdove::M0);\n  write_gnuplot (kinetic, \"kinetic\", 0);\n\n  // set up the initial guess for the electron potential (i.e. electrostatic potential multiplied by elementary charge)\n  dealii::PETScWrappers::Vector potential (test_space.n_dofs ());\n  potential = initial_potential;\n  potential *= 0.9; //start with no space charge region\n\n  //\n  // Main iteration Schroedinger <-> Poisson\n  //\n  for (std::size_t cycle = 0; cycle < 100; ++cycle)\n  {\n    write_gnuplot (potential, \"potential\", cycle);\n\n    // Get started on Schroedinger's problem\n    std::cout << \"Schroedinger's problem:\" << std::endl;\n    schroedinger_problem.reinit ();\n    schroedinger_problem.assemble (kinetic, potential);\n    schroedinger_problem.solve ();\n    schroedinger_problem.get_solution_eigenpairs (eigenvalues, eigenvectors);\n    write_gnuplot (eigenvectors[0], \"electron_function\", cycle);\n\n    // output\n    std::cout << \"   Eigenvalues:                  \";\n    for (unsigned int i=0; i<eigenvalues.size (); ++i)\n      std::cout << eigenvalues[i] << \" \";\n    std::cout << std::endl;\n\n    std::cout << \"   Scaled values (meV):           \";\n    for (unsigned int i=0; i<eigenvalues.size (); ++i)\n      std::cout << eigenvalues[i]/(1e-03*qdove::E0) << \" \";\n    std::cout << std::endl;\n\n    // Make the density of states (dos)\n    dealii::PETScWrappers::Vector dos (test_space.n_dofs ());\n    qdove::FermiDirac::compute_density_of_states (eff_mass, dos);\n\n    // and then the density\n    dealii::PETScWrappers::Vector density (test_space.n_dofs());\n    qdove::FermiDirac::compute_number_density (eigenvectors, eigenvalues, fermi_energy, dos, density);\n    write_gnuplot (density, \"density\", cycle);\n\n    // Set up RHS for Poisson's equation.\n    //\n    // First copy the density over, add the doping profile, and thten\n    // multiply by 4*\\pi*e*e/permittivity\n    dealii::PETScWrappers::Vector rho (density);\n    for (std::size_t i=0; i<solution.size (); ++i)\n      if (potential[i] > fermi_energy)\n        rho[i] = -doping;\n    rho *= 4.0 * qdove::PI * qdove::E0 * qdove::E0 / (qdove::permittivity_GaAs);\n    write_gnuplot (rho, \"rho\", cycle);\n\n    // Solve Poisson:\n    std::cout << \"Poisson's problem:\" << std::endl;\n    poisson_problem.reinit ();\n    poisson_problem.assemble (rho);\n    poisson_problem.solve ();\n    poisson_problem.get_solution_vector (solution);\n    write_gnuplot (solution, \"poisson_solution\", cycle);\n\n    // Update potential:\n    double max_update = 0;\n    for (std::size_t i=0; i<solution.size(); ++i)\n    {\n      double old_value = potential[i] - initial_potential[i];\n      max_update = std::max(max_update, std::fabs(solution[i] - old_value));\n    }\n\n    double cutoff_update_value = 0.02 * qdove::E0;\n    double alpha = (max_update > cutoff_update_value) \n      ? cutoff_update_value / max_update \n      : 1.0; // update by at most 10 mV for stability reasons\n\n    alpha = 0.1;\n    std::cout << \"alpha: \" << alpha << std::endl;\n\n    for (std::size_t i=0; i<potential.size(); ++i)\n    {\n      double old_value = potential[i] - 0.9 * initial_potential[i];\n      double update    = solution[i] - old_value;\n\n      potential[i] += alpha * update;\n    }\n  }\n}\n\nint main (int argc, char **argv)\n{\n  try\n    {\n      dealii::Utilities::MPI::MPI_InitFinalize mpi_initialization (argc, argv, 1);\n      {\n  // Create a grid\n  dealii::Triangulation<1> triangulation;\n  dealii::GridGenerator::hyper_cube (triangulation, -50e-10, 50e-10);\n  triangulation.refine_global (9);\n\n  // Run Schroedinger's problem on that grid\n  SelfConsistentProblem<1> self_consistent_problem (triangulation);\n  self_consistent_problem.run ();\n      }\n    }\n  catch (std::exception &exc)\n    {\n      std::cerr << std::endl << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      std::cerr << \"Exception on processing: \" << std::endl\n                << exc.what() << std::endl\n                << \"Aborting!\" << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n\n      return 1;\n    }\n  catch (...)\n    {\n      std::cerr << std::endl << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      std::cerr << \"Unknown exception!\" << std::endl\n                << \"Aborting!\" << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      return 1;\n    }\n\n  return 0;\n}\n", "meta": {"hexsha": "c04babf1389df03d0588f42c1060d6a263a1ed10", "size": 9659, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/step-1/step-1.cc", "max_stars_repo_name": "QuantumDove/QuantumDove", "max_stars_repo_head_hexsha": "6220570364d953fdecd0173a35a6b59976239cbb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-09-03T01:56:17.000Z", "max_stars_repo_stars_event_max_datetime": "2016-09-03T01:56:17.000Z", "max_issues_repo_path": "examples/step-1/step-1.cc", "max_issues_repo_name": "QuantumDove/QuantumDove", "max_issues_repo_head_hexsha": "6220570364d953fdecd0173a35a6b59976239cbb", "max_issues_repo_licenses": ["MIT"], "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/step-1/step-1.cc", "max_forks_repo_name": "QuantumDove/QuantumDove", "max_forks_repo_head_hexsha": "6220570364d953fdecd0173a35a6b59976239cbb", "max_forks_repo_licenses": ["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.0105633803, "max_line_length": 119, "alphanum_fraction": 0.6489284605, "num_tokens": 2579, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4725222841427347}}
{"text": "#include <ceres/ceres.h>\n#include <Eigen/Core>\n#include <unsupported/Eigen/MatrixFunctions>\n\n#include \"wave/optimization/ceres/odom_gp/point_to_plane_gp.hpp\"\n#include \"wave/optimization/ceres/odom_gp/point_to_line_gp.hpp\"\n#include \"wave/wave_test.hpp\"\n#include \"wave/utils/math.hpp\"\n#include \"wave/geometry_og/transformation.hpp\"\n#include \"wave/kinematics/constant_velocity_gp_prior.hpp\"\n\n// This is a numerical check for some residuals where ceres gradient checker is not helpful\n\nnamespace wave {\n\nTEST(point_to_line, jacobian) {\n\n    double ptA[3] = {1, 1, 0};\n    double ptB[3] = {1, 3, -4};\n    double pt[3] = {1, 2, -4};\n\n    const double delta_T = 0.5;\n    const double **params;\n    params = new const double *[4];\n\n    Transformation<Eigen::Matrix<double, 3, 4>, false> T_k, T_kp1;\n    Vec6 vel_k, vel_kp1;\n\n    params[0] = T_k.storage.data();\n    params[1] = T_kp1.storage.data();\n    params[2] = vel_k.data();\n    params[3] = vel_kp1.data();\n\n    T_k.setIdentity();\n    vel_k << 0.1, -0.1, 0.1, 5, 1, -1;\n    vel_kp1 = vel_k;\n    T_kp1 = T_k;\n    T_kp1.manifoldPlus(delta_T * vel_k);\n\n    double zero = 0;\n    double tau = 0.34;\n    Mat6 Qc = Mat6::Identity();\n    Mat6 inv_Qc = Qc.inverse();\n\n    wave_kinematics::ConstantVelocityPrior motion_prior(zero, delta_T, &tau, Qc, inv_Qc);\n\n    Eigen::Matrix<double, 12, 12> hat, candle;\n\n    SE3PointToLineGPObjects objects;\n\n    motion_prior.calculateStuff(hat, candle);\n\n    objects.hat = hat;\n    objects.candle = candle;\n\n    ceres::CostFunction *cost_function = new SE3PointToLineGP(pt,\n                                                              ptA,\n                                                              ptB,\n                                                              objects,\n                                                              Mat3::Identity(),\n                                                              true);\n    double **jacobian;\n    jacobian = new double *[4];\n    jacobian[0] = new double[24];\n    jacobian[1] = new double[24];\n    jacobian[2] = new double[12];\n    jacobian[3] = new double[12];\n\n    Vec2 op_result;\n\n    cost_function->Evaluate(params, op_result.data(), jacobian);\n\n    double const step_size = 1e-9;\n    Transformation<Eigen::Matrix<double, 3, 4>, false> Tk_perturbed, Tkp1_perturbed;\n    Vec6 vel_k_perturbed, vel_kp1_perturbed;\n\n    Tk_perturbed = T_k;\n    Tkp1_perturbed = T_kp1;\n    vel_k_perturbed = vel_k;\n    vel_kp1_perturbed = vel_kp1;\n\n    params[0] = Tk_perturbed.storage.data();\n    params[1] = Tkp1_perturbed.storage.data();\n    params[2] = vel_k_perturbed.data();\n    params[3] = vel_kp1_perturbed.data();\n\n    std::vector<Eigen::Matrix<double, 2, 6>> an_jacs, num_jacs;\n    an_jacs.resize(4);\n    num_jacs.resize(4);\n\n    Vec6 delta;\n    delta.setZero();\n\n    Vec2 result;\n    Vec2 diff;\n\n    double inv_step = 1.0 / step_size;\n\n    for (uint32_t i = 0; i < 6; i++) {\n        delta(i) = step_size;\n        // First parameter\n        Tk_perturbed.manifoldPlus(delta);\n        cost_function->Evaluate(params, result.data(), nullptr);\n        diff = result - op_result;\n        num_jacs.at(0).block<2,1>(0,i) = inv_step * diff;\n        Tk_perturbed = (T_k);\n        // Second parameter\n        Tkp1_perturbed.manifoldPlus(delta);\n        cost_function->Evaluate(params, result.data(), nullptr);\n        diff = result - op_result;\n        num_jacs.at(1).block<2,1>(0,i) = inv_step * diff;\n        Tkp1_perturbed = (T_kp1);\n        // Third parameter\n        vel_k_perturbed = vel_k_perturbed + delta;\n        cost_function->Evaluate(params, result.data(), nullptr);\n        diff = result - op_result;\n        num_jacs.at(2).block<2,1>(0,i) = inv_step * diff;\n        vel_k_perturbed = vel_k;\n        // Fourth parameter\n        vel_kp1_perturbed = vel_kp1_perturbed + delta;\n        cost_function->Evaluate(params, result.data(), nullptr);\n        diff = result - op_result;\n        num_jacs.at(3).block<2,1>(0,i) = inv_step * diff;\n        vel_kp1_perturbed = vel_kp1;\n\n        delta.setZero();\n    }\n\n    // now get the analytical jacobians\n    Eigen::Map<Eigen::Matrix<double, 2, 12, Eigen::RowMajor>> an_jac_1(jacobian[0], 2, 12);\n    an_jacs.at(0) = an_jac_1.block<2,6>(0,0);\n\n    Eigen::Map<Eigen::Matrix<double, 2, 12, Eigen::RowMajor>> an_jac_2(jacobian[1], 2, 12);\n    an_jacs.at(1) = an_jac_2.block<2,6>(0,0);\n\n    Eigen::Map<Eigen::Matrix<double, 2, 6, Eigen::RowMajor>> an_jac_3(jacobian[2], 2, 6);\n    an_jacs.at(2) = an_jac_3;\n\n    Eigen::Map<Eigen::Matrix<double, 2, 6, Eigen::RowMajor>> an_jac_4(jacobian[3], 2, 6);\n    an_jacs.at(3) = an_jac_4;\n\n    for (uint32_t i = 0; i < 4; i++) {\n        double err = (num_jacs.at(i) - an_jacs.at(i)).norm();\n        if (err > 1e-10) {\n            std::cout << \"Index \" << i << \" with error = \" << err << std::endl\n                     << \"Numerical: \" << std::endl << num_jacs.at(i) << std::endl\n                     << \"Analytical:\" << std::endl << an_jacs.at(i) << std::endl << std::endl;\n        }\n        EXPECT_NEAR(err, 0.0, 1e-6);\n    }\n}\n\nTEST(point_to_plane, jacobian) {\n\n    double ptA[3] = {1, 1, 0};\n    double ptB[3] = {1, 3, -4};\n    double ptC[3] = {4, -1, 0};\n    double pt[3] = {1, 2, -4};\n\n    const double delta_T = 0.5;\n    const double **params;\n    params = new const double *[4];\n\n    Transformation<Eigen::Matrix<double, 3, 4>, false> T_k, T_kp1;\n    Vec6 vel_k, vel_kp1;\n\n    params[0] = T_k.storage.data();\n    params[1] = T_kp1.storage.data();\n    params[2] = vel_k.data();\n    params[3] = vel_kp1.data();\n\n    T_k.setIdentity();\n    vel_k << 0.1, -0.1, 0.2, 5, 1, -1;\n    vel_kp1 = vel_k;\n    T_kp1 = (T_k);\n    T_kp1.manifoldPlus(delta_T * vel_k);\n\n    double zero = 0;\n    double tau = 0.34;\n    Mat6 Qc = Mat6::Identity();\n    Mat6 inv_Qc = Qc.inverse();\n\n    wave_kinematics::ConstantVelocityPrior motion_prior(zero, delta_T, &tau, Qc, inv_Qc);\n\n    Eigen::Matrix<double, 12, 12> hat, candle;\n\n    motion_prior.calculateStuff(hat, candle);\n\n    SE3PointToPlaneGPObjects objects;\n    objects.hat = hat;\n    objects.candle = candle;\n\n    ceres::CostFunction *cost_function = new SE3PointToPlaneGP(pt,\n                                                              ptA,\n                                                              ptB,\n                                                              ptC,\n                                                              objects,\n                                                              Mat3::Identity(),\n                                                              false);\n    double **jacobian;\n    jacobian = new double *[4];\n    jacobian[0] = new double[12];\n    jacobian[1] = new double[12];\n    jacobian[2] = new double[6];\n    jacobian[3] = new double[6];\n\n    Eigen::Matrix<double, 1, 1> op_result;\n\n    cost_function->Evaluate(params, op_result.data(), jacobian);\n\n    double const step_size = 1e-9;\n    Transformation<Eigen::Matrix<double, 3, 4>> Tk_perturbed, Tkp1_perturbed;\n    Vec6 vel_k_perturbed, vel_kp1_perturbed;\n\n    Tk_perturbed = (T_k);\n    Tkp1_perturbed = (T_kp1);\n    vel_k_perturbed = vel_k;\n    vel_kp1_perturbed = vel_kp1;\n\n    params[0] = Tk_perturbed.storage.data();\n    params[1] = Tkp1_perturbed.storage.data();\n    params[2] = vel_k_perturbed.data();\n    params[3] = vel_kp1_perturbed.data();\n\n    std::vector<Eigen::Matrix<double, 1, 6>> an_jacs, num_jacs;\n    an_jacs.resize(4);\n    num_jacs.resize(4);\n\n    Vec6 delta;\n    delta.setZero();\n\n    Eigen::Matrix<double, 1, 1> diff, result;\n\n    double inv_step = 1.0 / step_size;\n\n    for (uint32_t i = 0; i < 6; i++) {\n        delta(i) = step_size;\n        // First parameter\n        Tk_perturbed.manifoldPlus(delta);\n        cost_function->Evaluate(params, result.data(), nullptr);\n        diff = result - op_result;\n        num_jacs.at(0).block<1,1>(0,i) = inv_step * diff;\n        Tk_perturbed = (T_k);\n        // Second parameter\n        Tkp1_perturbed.manifoldPlus(delta);\n        cost_function->Evaluate(params, result.data(), nullptr);\n        diff = result - op_result;\n        num_jacs.at(1).block<1,1>(0,i) = inv_step * diff;\n        Tkp1_perturbed = (T_kp1);\n        // Third parameter\n        vel_k_perturbed = vel_k_perturbed + delta;\n        cost_function->Evaluate(params, result.data(), nullptr);\n        diff = result - op_result;\n        num_jacs.at(2).block<1,1>(0,i) = inv_step * diff;\n        vel_k_perturbed = vel_k;\n        // Fourth parameter\n        vel_kp1_perturbed = vel_kp1_perturbed + delta;\n        cost_function->Evaluate(params, result.data(), nullptr);\n        diff = result - op_result;\n        num_jacs.at(3).block<1,1>(0,i) = inv_step * diff;\n        vel_kp1_perturbed = vel_kp1;\n\n        delta.setZero();\n    }\n\n    // now get the analytical jacobians\n    Eigen::Map<Eigen::Matrix<double, 1, 12, Eigen::RowMajor>> an_jac_1(jacobian[0], 1, 12);\n    an_jacs.at(0) = an_jac_1.block<1,6>(0,0);\n\n    Eigen::Map<Eigen::Matrix<double, 1, 12, Eigen::RowMajor>> an_jac_2(jacobian[1], 1, 12);\n    an_jacs.at(1) = an_jac_2.block<1,6>(0,0);\n\n    Eigen::Map<Eigen::Matrix<double, 1, 6, Eigen::RowMajor>> an_jac_3(jacobian[2], 1, 6);\n    an_jacs.at(2) = an_jac_3;\n\n    Eigen::Map<Eigen::Matrix<double, 1, 6, Eigen::RowMajor>> an_jac_4(jacobian[3], 1, 6);\n    an_jacs.at(3) = an_jac_4;\n\n    for (uint32_t i = 0; i < 4; i++) {\n        double err = (num_jacs.at(i) - an_jacs.at(i)).norm();\n        std::cout << \"Index \" << i << \" has error: \" << err << std::endl\n                  << \"Numerical: \" << std::endl << num_jacs.at(i) << std::endl\n                  << \"Analytical:\" << std::endl << an_jacs.at(i) << std::endl << std::endl;\n        EXPECT_NEAR(err, 0.0, 1e-6);\n    }\n}\n\n}", "meta": {"hexsha": "ab0b9e971b0dd7a694c3b26376c301cb94a28100", "size": 9648, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "wave_optimization/tests/ceres/gp_jacobian_test.cpp", "max_stars_repo_name": "Jebediah/libwave", "max_stars_repo_head_hexsha": "c04998c964f0dc7d414783c6e8cf989a2716ad54", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-06-13T13:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-13T14:54:35.000Z", "max_issues_repo_path": "wave_optimization/tests/ceres/gp_jacobian_test.cpp", "max_issues_repo_name": "Jebediah/libwave", "max_issues_repo_head_hexsha": "c04998c964f0dc7d414783c6e8cf989a2716ad54", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "wave_optimization/tests/ceres/gp_jacobian_test.cpp", "max_forks_repo_name": "Jebediah/libwave", "max_forks_repo_head_hexsha": "c04998c964f0dc7d414783c6e8cf989a2716ad54", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-13T02:27:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-13T02:27:29.000Z", "avg_line_length": 33.5, "max_line_length": 94, "alphanum_fraction": 0.5706882255, "num_tokens": 2964, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4725222841427347}}
{"text": "#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <limits>\n#include <mimkl/data_structures.hpp>\n#include <mimkl/definitions.hpp>\n#include <mimkl/io.hpp>\n#include <mimkl/kernels.hpp>\n#include <mimkl/linear_algebra.hpp>\n#include <mimkl/models/umkl_knn.hpp>\n#include <spdlog/spdlog.h>\n//#include <mimkl/models.hpp>\n#include <mimkl/kernels_handler.hpp>\n#include <mimkl/utilities.hpp>\n#include <numeric>\n#include <spdlog/fmt/ostr.h>\n\nusing dlib::mat;\nusing mimkl::data_structures::DataFrame;\nusing mimkl::data_structures::indexing_from_vector;\nusing mimkl::data_structures::range;\nusing mimkl::definitions::Indexing;\nusing mimkl::utilities::check_invocable;\nusing mimkl::utilities::print_type;\n\nusing mimkl::kernels_handler::KernelsHandler;\nusing mimkl::models::UMKLKNN;\n\n//#define SPDLOG_DEBUG_ON\n//#define SPDLOG_TRACE_ON\n\n// Compile time log levels\n// define SPDLOG_DEBUG_ON or SPDLOG_TRACE_ON\n// SPDLOG_TRACE(console, \"Enabled only #ifdef SPDLOG_TRACE_ON..{} ,{}\",\n// 1, 3.23);  SPDLOG_DEBUG(console, \"Enabled only #ifdef SPDLOG_DEBUG_ON.. {}\n// ,{}\", 1, 3.23);\n\ntypedef std::function<MATRIX(double)(const MATRIX(double) &, const MATRIX(double) &)>\nInducedFunction;\ntypedef std::vector<InducedFunction> Function_vec;\ntypedef std::vector<MATRIX(double)> Matrix_vec;\n\nMATRIX(double)\ntest_umkl_knn(const Function_vec function_vec,\n              const Matrix_vec matrix_vec,\n              const Matrix_vec matrix_vec_test,\n              const bool precompute,\n              const bool trace_normalization,\n              std::shared_ptr<spdlog::logger> console,\n              MATRIX(double) X,\n              MATRIX(double) Y)\n{\n    console->info(\"\\nRun with precompute = {} an trace_normalization = {}\\n\\n\",\n                  precompute, trace_normalization);\n\n    console->info(\"rows X,Y : {},{}\", X.rows(), Y.rows());\n    console->info(\"sizes matric_vec : {},{}, sizes matric_vec_test : {},{}\",\n                  matrix_vec[0].rows(), matrix_vec[0].cols(),\n                  matrix_vec_test[0].rows(), matrix_vec_test[0].cols());\n\n    console->info(\"\\nMatricial construction\\n\");\n\n    UMKLKNN<double, InducedFunction> umkl_mat =\n    UMKLKNN<double, InducedFunction>(matrix_vec, precompute, trace_normalization);\n    console->info(\"constructor of umkl_mat done\");\n\n    umkl_mat.set_k(5);\n    umkl_mat.fit(matrix_vec);\n    MATRIX(double) beta_mat_1 = umkl_mat.get_beta();\n    try\n    {\n        umkl_mat.fit(matrix_vec_test);\n        MATRIX(double) beta_mat_2 = umkl_mat.get_beta();\n        console->error(\"not caught error on matricial non-squared.\");\n    }\n    catch (const std::exception &e)\n    {\n        console->warn(\"caught error on matricial non-squared. message: \\n{}\",\n                      e.what());\n    };\n    try\n    {\n        umkl_mat.fit(X);\n        MATRIX(double) beta_mat_fun = umkl_mat.get_beta();\n        console->error(\"not caught error on matricial set_lhs.\");\n    }\n    catch (const std::exception &e)\n    {\n        console->warn(\"caught error on matricial set_lhs. message: \\n{}\",\n                      e.what());\n    };\n    // retrain\n    umkl_mat.fit(matrix_vec);\n\n    console->info(\"\\nFunctional construction\\n\");\n    UMKLKNN<double, InducedFunction> umkl(function_vec, precompute,\n                                          trace_normalization);\n    console->info(\"constructor of umkl_fun done\");\n\n    umkl.set_k(5);\n    umkl.fit(matrix_vec);\n    MATRIX(double) beta_fun_mat = umkl.get_beta();\n    umkl.fit(X);\n    MATRIX(double) beta_fun_1 = umkl.get_beta();\n    // retrain\n    umkl.fit(Y);\n    MATRIX(double) beta_fun_2 = umkl.get_beta();\n    try\n    {\n        umkl_mat.fit(matrix_vec_test);\n        MATRIX(double) beta_fun_mat_2 = umkl_mat.get_beta();\n        console->error(\n        \"not caught error on functional with non-squared matricial.\");\n    }\n    catch (const std::exception &e)\n    {\n        console->warn(\"caught error on functional with non-squared matricial. \"\n                      \"message: \\n{}\",\n                      e.what());\n    };\n\n    assert(((beta_mat_1 - beta_fun_mat).norm() == 0) && \"beta_mat_1\");\n    assert(((beta_fun_1 - beta_fun_mat).norm() == 0) && \"beta_fun_1\");\n\n    return beta_fun_mat;\n}\n\nint main(int argc, char **argv)\n{\n\n    // Runtime log levels\n    spdlog::set_level(spdlog::level::debug); // Set global log level to info\n    auto console = spdlog::stdout_color_mt(\"console\");\n\n    const Index rows = 6; // 3 to reproduce single member in class  error\n    const Index dims = 2;\n\n    //\n    //  ////\n    //  MATRIX(double) X; //(rows, 2)\n\n    //  std::string path = \"../../data/simple_csv2.csv\";\n    //  console->info(\"path: {}\",path);\n    //  X = mimkl::io::eigen_matrix_from_csv<MATRIX(double)>(path, ','); //\n    //  weird\n    //  bug maybe here: floating point error that doesn't throw??\n    //  ///////\n\n    MATRIX(double) X(rows, dims);\n    //  //\tX << 1., 1., 3., 1., 1., 2.;\n    //  X << 1., 1., 3., 1., 1., 4., 3., 2.;\n    X << 1., 1., 3., 1., 1., 4., 3., 2., 1., -1., 3., -1.;\n    //  ///////\n    console->info(\"X\\n{}\", X);\n\n    std::vector<std::string> labels;\n    labels.reserve(rows);\n    labels.push_back(\"a\");\n    labels.push_back(\"b\");\n    labels.push_back(\"a\");\n    labels.push_back(\"b\");\n    labels.push_back(\"c\");\n    labels.push_back(\"c\");\n\n    Eigen::SparseMatrix<double> L(2, 2);\n    mimkl::linear_algebra::fill_sparse_diagonal(L, 1.0);\n\n    Eigen::SparseMatrix<double> L1(dims, dims);\n    typedef Eigen::Triplet<double> TripletDouble; // (row,col,coef)\n    std::vector<TripletDouble> triplet_list;\n    triplet_list.reserve(4);\n    triplet_list.push_back(TripletDouble(0, 1, 1.));\n    //  triplet_list.push_back(TripletDouble(1, 2, 1.));\n    triplet_list.push_back(TripletDouble(1, 0, 1.));\n    //  triplet_list.push_back(TripletDouble(2, 1, 1.));\n    L1.setFromTriplets(triplet_list.begin(), triplet_list.end());\n\n    std::vector<Eigen::SparseMatrix<double>> inducer_vec;\n    inducer_vec.reserve(2);\n    inducer_vec.push_back(L);\n    inducer_vec.push_back(L1);\n\n    typedef std::function<MATRIX(double)(const MATRIX(double) &, const MATRIX(double) &,\n                                         const Eigen::SparseMatrix<double>)>\n    InducerFunction;\n    typedef std::function<MATRIX(double)(const MATRIX(double) &,\n                                         const MATRIX(double) &)>\n    InducedFunction;\n\n    const double degree = 1.;\n    const double offset = 0.;\n\n    auto lambda_logger = spdlog::stdout_color_mt(\"lambda\");\n    InducerFunction k_poly =\n    [degree, offset](const MATRIX(double) & lhs, const MATRIX(double) & rhs,\n                     const Eigen::SparseMatrix<double> inducer) {\n        //\t spdlog::get(\"lambda\")->debug(\"before actual inducer function\n        // call\" \t\t\t \"lhs rows {}  cols {} \\n\"\n        //\t\t\t \"rhs rows {}  cols {} \\n\"\n        //\t\t\t \"kernel rows {}  cols {} \\n\"\n        //\t\t\t \"inducer rows {}  cols {} \\n\",\n        //\t\t\t lhs.rows(), lhs.cols(),\n        //\t\t\t rhs.rows(), rhs.cols(),\n        //\t\t\t kernel_matrix.rows(), kernel_matrix.cols(),\n        //\t\t\t inducer.rows(), inducer.cols()\n        //\t\t\t );\n        return mimkl::induction::induce_polynomial_kernel<MATRIX(double)>(\n        lhs, rhs, inducer, degree, offset);\n    };\n\n    std::vector<InducedFunction> function_vec =\n    mimkl::induction::inducer_combination(k_poly, inducer_vec);\n    //// \t==inducer_combination:\n    //\t  for (Eigen::SparseMatrix<double> inducer : inducer_vec) {\n    //\t\t  function_vec.push_back(\n    //\t\t\t[&,inducer](const MATRIX(double) &lhs,\n    //\t\t\t\t\t  const MATRIX(double)&rhs,\n    //\t\t\t\t\t  const MATRIX(double) &kernel_matrix) {\n    //\t\t\t  k_poly(lhs, rhs, kernel_matrix, inducer);\n    //\t\t\t});\n    //\n    //\t  }\n    //\n    //  MATRIX(double) K2(rows, rows);\n    //  function_vec[0](X, X, K2);\n    //  console->info(\"a kernel from function:\\n{}\", K2);\n    //\n    //  MATRIX(double) K3(rows, rows);\n    //  function_vec[1](X, X, K3);\n    //  console->info(\"another kernel from function:\\n{}\", K3);\n\n    //  COLUMN(bool) all_true_I_swear = COLUMN(bool)::Constant(rows, true);\n    //  console->info(\"bool:\\n{}\",all_true_I_swear);\n    //  COLUMN(double) double_trouble = all_true_I_swear.cast<double>();\n    //  console->info(\"double:\\n{}\",double_trouble);\n    //\n    //  console->info(\"mult by\n    //  bool:\\n{}\",all_true_I_swear.cast<double>().array()\n    //  * X.col(0).array());\n    ////  console->info(\"mult by bool:\\n{}\",all_true_I_swear.cast<int>().array()\n    ///*\n    /// X.col(0).array());\n\n    //////////\n    MATRIX(double) K2 = function_vec[0](X, X);\n    console->info(\"a kernel from function:\\n{}\", K2);\n\n    MATRIX(double) K3 = function_vec[1](X, X);\n    console->info(\"another kernel from function:\\n{}\", K3);\n\n    std::vector<MATRIX(double)> matrix_vec(2);\n    matrix_vec[0] = K2;\n    matrix_vec[1] = K3;\n\n    MATRIX(double) Y(7, 2);\n    Y << 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12., 13., 14.;\n    console->info(\"Y\\n{}\", Y);\n    std::vector<MATRIX(double)> matrix_vec_test(2);\n\n    matrix_vec_test[0] = function_vec[0](X, Y);\n    matrix_vec_test[1] = function_vec[1](X, Y);\n\n    //////////\n    //  UMKLKNN<double, InducedFunction> umkl_mat(matrix_vec,true, true);\n    //  UMKLKNN<double, InducedFunction> umkl_mfun(function_vec,true, true);\n\n    MATRIX(double)\n    tt = test_umkl_knn(function_vec, matrix_vec, matrix_vec_test, true, true,\n                       console, X, Y);\n    MATRIX(double)\n    tf = test_umkl_knn(function_vec, matrix_vec, matrix_vec_test, true, false,\n                       console, X, Y);\n    MATRIX(double)\n    ft = test_umkl_knn(function_vec, matrix_vec, matrix_vec_test, false, true,\n                       console, X, Y);\n    MATRIX(double)\n    ff = test_umkl_knn(function_vec, matrix_vec, matrix_vec_test, false, false,\n                       console, X, Y);\n\n    assert(((tt - ft).norm() == 0) && \"trace_normalization true\");\n    assert(((ff - tf).norm() == 0) && \"trace_normalization false\");\n\n    console->info(\"trace_normalization true: \\n{}\", tt);\n    console->info(\"trace_normalization false: \\n{}\", tf);\n    return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "6c2ae9fa31b794d21fc9e38c41e40d6da3db4b01", "size": 10006, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/umkl_knn/main.cpp", "max_stars_repo_name": "vishalbelsare/mimkl", "max_stars_repo_head_hexsha": "53a5a9db5aa09c6e8808ba5b845601c5768d23e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2019-05-28T23:18:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T20:00:03.000Z", "max_issues_repo_path": "test/umkl_knn/main.cpp", "max_issues_repo_name": "vishalbelsare/mimkl", "max_issues_repo_head_hexsha": "53a5a9db5aa09c6e8808ba5b845601c5768d23e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2019-05-18T13:21:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T22:20:55.000Z", "max_forks_repo_path": "test/umkl_knn/main.cpp", "max_forks_repo_name": "vishalbelsare/mimkl", "max_forks_repo_head_hexsha": "53a5a9db5aa09c6e8808ba5b845601c5768d23e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2019-07-24T09:39:41.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-29T14:40:27.000Z", "avg_line_length": 34.986013986, "max_line_length": 88, "alphanum_fraction": 0.6053367979, "num_tokens": 2752, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174789, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4724288210285613}}
{"text": "#include <iostream>\n#include <opencv2/opencv.hpp>\n#include <pangolin/pangolin.h>\n#include <Eigen/Core>\n#include <vector>\n\n\nusing namespace std;\nusing namespace cv;\n\n// \u76f8\u673a\u5185\u53c2\n#define L_FX 7.188560000000e+02\n#define L_FY 7.188560000000e+02\n#define L_CX 6.071928000000e+02\n#define L_CY 1.852157000000e+02\n\n#define R_FX 7.188560000000e+02\n#define R_FY 7.188560000000e+02\n#define R_CX 6.071928000000e+02\n#define R_CY 1.852157000000e+02\n\n#define FB   3.861448000000e+02\n\n#define IMG_W 1024.0\n#define IMG_H 768.0\n\n\n\n\nvoid prefilterXSobel(const cv::Mat& src, cv::Mat& dst, int ftzero);\n\ntemplate <typename T> void filterSpecklesImpl(cv::Mat& img, int newVal, int maxSpeckleSize, int maxDiff, cv::Mat& _buf);\n\nvoid initColor(void);\n\n\ntypedef struct _Color\n{\n//public:\n    unsigned char r;\n    unsigned char g;\n    unsigned char b;\n\n    /*\n    _Color(unsigned char _r,unsigned char _g,unsigned char _b)\n    {    r=_r;g=_g;b=_b;  }\n    */\n\n}Color;\n\nvector<Color> HueCircle;\n\n\nint main(int argc, char* argv[])\n{\n    cout<<\"Kitti Streo Test.\"<<endl;\n    cout<<\"Complied at \"<<__TIME__<<\", \"<<__DATE__<<\".\"<<endl;\n\n    if(argc!=4)\n    {\n        cout<<\"Usage: \"<<argv[0]<<\" img_left img_right img_dis\"<<endl;\n        return 1;\n    }\n\n    // \u8bfb\u5165\u5de6\u53f3\u53cc\u76ee\u56fe\u50cf\n    Mat imgLeft =imread(argv[1],IMREAD_GRAYSCALE);\n    Mat imgRight=imread(argv[2],IMREAD_GRAYSCALE);\n\n    if(imgLeft.empty())\n    {\n        cout<<\"Error: img_left \"<<argv[1]<<\" is empty!\"<<endl;\n        return 2;\n    }\n\n    if(imgRight.empty())\n    {\n        cout<<\"Error: img_left \"<<argv[1]<<\" is empty!\"<<endl;\n        return 2;\n    }\n\n    imshow(\"img_left\",imgLeft);\n    imshow(\"img_right\",imgRight);\n\n    waitKey(100);\n\n    Mat imgLefted,imgRighted;\n\n    \n\n    // \u6700\u5c0f\u89c6\u5dee\n    int mindisparity = 0;\n    // \u89c6\u5dee\u641c\u7d22\u8303\u56f4\u957f\u5ea6\n\tint ndisparities = 64;  \n    // SAD\u4ee3\u4ef7\u8ba1\u7b97\u7a97\u53e3\u5927\u5c0f\n\tint SADWindowSize = 11; \n\t//SGBM\n\tcv::Ptr<cv::StereoSGBM> sgbm = cv::StereoSGBM::create(mindisparity, ndisparities, SADWindowSize);\n\n    // \u80fd\u91cf\u51fd\u6570\u53c2\u6570\n\tint P1 = 8 * imgLeft.channels() * SADWindowSize* SADWindowSize;\n    // \u80fd\u91cf\u51fd\u6570\u53c2\u6570\n\tint P2 = 32 * imgRight.channels() * SADWindowSize* SADWindowSize;\n\n    // \u4e0b\u9762\u5c31\u662f\u5404\u79cd\u914d\u7f6e\u4e86\n\tsgbm->setP1(P1);\n\tsgbm->setP2(P2);\n\tsgbm->setPreFilterCap(15);\n\tsgbm->setUniquenessRatio(10);\n\tsgbm->setSpeckleRange(2);\n\tsgbm->setSpeckleWindowSize(100);\n\tsgbm->setDisp12MaxDiff(1);\n\t//sgbm->setMode(cv::StereoSGBM::MODE_HH);\n\n    // \u5bf9\u539f\u59cb\u56fe\u50cf\u8fdb\u884c\u9884\u5904\u7406\n    // imgLeft.copyTo(imgLefted);\n    // imgRight.copyTo(imgRighted);\n    // prefilterXSobel(imgLeft, imgLefted, sgbm->getPreFilterCap());\n    // prefilterXSobel(imgRight, imgRighted, sgbm->getPreFilterCap());\n\n    // imshow(\"img_left\",imgLefted);\n    // imshow(\"img_right\",imgRighted);\n\n    // waitKey(0);\n\n    // \n    Mat disp;\n\tsgbm->compute(imgLeft, imgRight, disp);\n\tdisp.convertTo(disp, CV_32F, 1.0 / 16);                //\u9664\u4ee516\u5f97\u5230\u771f\u5b9e\u89c6\u5dee\u503c\n\tMat disp8U = Mat(disp.rows, disp.cols, CV_8UC1);       //\u663e\u793a\n\tnormalize(disp, disp8U, 0, 255, NORM_MINMAX, CV_8UC1);\n\n    // display\n    imshow(\"dis\",disp8U);\n\n    waitKey(100);\n\n\timwrite(argv[3], disp8U);\n\n    // \u751f\u6210\u76f8\u673a\u5185\u53c2\u6570\u77e9\u9635\n    Eigen::Matrix3d K;\n    K<<L_FX,    0.0,    L_CX,\n       0.0,     L_FY,   L_CY,\n       0.0,     0.0,    1.0;\n    Eigen::Matrix3d K_inv=K.inverse();\n\n    // \u51c6\u5907\u6df1\u5ea6\u7740\u8272\n    double min_d,max_d;\n    int max_id[2],min_id[2];\n    minMaxIdx(disp,&min_d,&max_d,min_id,max_id);\n\n    min_d=min_d<5 ? 5:min_d;\n\n    double max_z=FB/min_d,min_z=FB/max_d;\n\n    double factor=1.0*1536/(max_z-min_z);\n\n\n    initColor();\n\n\n    // ================================== \u51c6\u5907\u53ef\u89c6\u5316 =================================\n    pangolin::CreateWindowAndBind(\n        \"PointClouds\",     //\u7a97\u53e3\u6807\u9898\n        IMG_W,        //\u7a97\u53e3\u5c3a\u5bf8\n        IMG_H);       //\u7a97\u53e3\u5c3a\u5bf8\n    glEnable(GL_DEPTH_TEST);\n\n    // Define Projection and initial ModelView matrix\n    pangolin::OpenGlRenderState s_cam(\n        pangolin::ProjectionMatrix(\n            IMG_W,IMG_H,            //\u76f8\u673a\u56fe\u50cf\u7684\u957f\u548c\u5bbd\n            L_FX,L_FY,L_CX,L_CY,    //\u76f8\u673a\u7684\u5185\u53c2,fu fv u0 v0\n            0.2,1000),           //\u76f8\u673a\u6240\u80fd\u591f\u770b\u5230\u7684\u6700\u6d45\u548c\u6700\u6df1\u7684\u50cf\u7d20\n        pangolin::ModelViewLookAt(\n            -2,2,-2,            //\u76f8\u673a\u5149\u5fc3\u4f4d\u7f6e,NOTICE z\u8f74\u4e0d\u8981\u8bbe\u7f6e\u4e3a0\n            0,0,0,              //\u76f8\u673a\u8981\u770b\u7684\u4f4d\u7f6e\n            pangolin::AxisY)    //\u548c\u89c2\u5bdf\u7684\u65b9\u5411\u6709\u5173\n    );\n\n    // Create Interactive View in window\n    pangolin::Handler3D handler(s_cam);\n    pangolin::View& d_cam = pangolin::CreateDisplay()\n            .SetBounds(\n                0.0, 1.0, 0.0, 1.0,     //\u8868\u793a\u6574\u4e2a\u7a97\u53e3\u90fd\u53ef\u4ee5\u89c2\u6d4b\u5230\n                -IMG_W/IMG_H)         //\u7a97\u53e3\u7684\u6bd4\u4f8b\n            .SetHandler(&handler);\n\n    while( !pangolin::ShouldQuit() )\n    {\n        // Clear screen and activate view to render into\n        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n        d_cam.Activate(s_cam);\n\n        glClearColor(1,1,1,0.0);\n\n        // Render OpenGL Cube\n        //pangolin::glDrawColouredCube();\n\n        //\u5c1d\u8bd5\u6309\u7167\u8c22\u6653\u4f73\u7684\u89c6\u9891\u4e2d\u7ed9\u51fa\u7684\u4ee3\u7801\u7ed8\u5236\n        // pangolin::glDrawAxis(3);\n\n        glPointSize(1.0f);\n        glBegin(GL_POINTS);\n        \n\n        // \u7ed8\u5236\u5f53\u524d\u5e27\u70b9\u4e91\n        for(int x=0;x<disp.rows;++x)\n        {\n            for(int y=0;y<disp.cols;++y)\n            {\n                float d=disp.at<float>(x,y);\n\n                if(d>=min_d)\n                {\n                    double z=FB/d;\n                    \n                    Eigen::Vector3d position=z*K_inv*Eigen::Vector3d(y,x,1);\n                    // cout<<\"Debug: disp8U.at<uint8_t>(x,y)=\"<<(int)(disp8U.at<uint8_t>(x,y))<<endl;\n                    // Color c=HueCircle[(int)(disp8U.at<char>(x,y))];\n                    // if((size_t)(z*1000)<1535)\n                    {\n                        // cout<<\"debug: z=\"<<z<<endl;\n                        // Color c=HueCircle[(size_t)(z*10)];\n                        // cout<<\"debug: r=\"<<(int)c.r<<\"\\tg=\"<<(int)c.g<<\"\\tb=\"<<(int)c.b<<\"\\t(size_t)(z*10)=\"<<(size_t)(z*10)<<endl;\n                        size_t index=(z-min_z)*factor;\n                        Color c=HueCircle[index];\n\n\n                        // \u753b\u70b9\n                        glColor3f(0,0,0);\n                        // glColor3f(c.r/255.0,c.g/255.0,c.b/255.0);\n                        // glColor3f(c.r,c.g,c.b);\n                        glVertex3f(-position[0],-position[1],position[2]);\n                    }\n                    \n                }\n                \n            }\n        }\n\n        glEnd();\n        //\u4e0d\u8981\u5fd8\u8bb0\u4e86\u8fd9\u4e2a\u4e1c\u897f!!!\n        glFlush();\n\n\n        // Swap frames and Process Events\n        pangolin::FinishFrame();\n\n        waitKey(1);\n\n    }\n    \n\n    return 0;\n}\n\n\nvoid initColor(void)\n{\n    \n\n     //\u989c\u8272\u73af\u521d\u59cb\u5316\n    HueCircle.reserve(1536);\n    HueCircle.resize(1536);\n\n    for (int i = 0;i < 255;i++)\n\t{\n\t\tHueCircle[i].r = 255;\n\t\tHueCircle[i].g = i;\n\t\tHueCircle[i].b = 0;\n\n\t\tHueCircle[i+255].r = 255-i;\n\t\tHueCircle[i+255].g = 255;\n\t\tHueCircle[i+255].b = 0;\n\n\t\tHueCircle[i+511].r = 0;\n\t\tHueCircle[i+511].g = 255;\n\t\tHueCircle[i+511].b = i;\n\n\t\tHueCircle[i+767].r = 0;\n\t\tHueCircle[i+767].g = 255-i;\n\t\tHueCircle[i+767].b = 255;\n\n\t\tHueCircle[i+1023].r = i;\n\t\tHueCircle[i+1023].g = 0;\n\t\tHueCircle[i+1023].b = 255;\n\n\t\tHueCircle[i+1279].r = 255;\n\t\tHueCircle[i+1279].g = 0;\n\t\tHueCircle[i+1279].b = 255-i;\n\t}\n\n\tHueCircle[1534].r = 0;\n\tHueCircle[1534].g = 0;\n\tHueCircle[1534].b = 0;\n\n\tHueCircle[1535].r = 255;\n\tHueCircle[1535].g = 255;\n\tHueCircle[1535].b = 255;\n\n    // while(1)\n    // {\n    //     int index;\n    //     cout<<\"Index? \";\n    //     cin>>index;\n    //     cout<<\"\\tr=\"<<()HueCircle[index].r\n    //         <<\"\\tg=\"<<HueCircle[index].g\n    //         <<\"\\tb=\"<<HueCircle[index].b<<endl;\n    // }\n\n \n\n\n  \n\n\n}", "meta": {"hexsha": "dadbd657a1c906b9c9a292f7d4822c28f2a7adbd", "size": 7408, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "029_KITTI_Stereo_Test/src/main.cpp", "max_stars_repo_name": "DreamWaterFound/Codes", "max_stars_repo_head_hexsha": "e7d80eb8bfd7d6f104abd18724cb4bface419233", "max_stars_repo_licenses": ["WTFPL"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2019-02-28T14:28:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-04T04:55:19.000Z", "max_issues_repo_path": "029_KITTI_Stereo_Test/src/main.cpp", "max_issues_repo_name": "DreamWaterFound/Codes", "max_issues_repo_head_hexsha": "e7d80eb8bfd7d6f104abd18724cb4bface419233", "max_issues_repo_licenses": ["WTFPL"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-09-07T09:00:50.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-04T02:13:25.000Z", "max_forks_repo_path": "029_KITTI_Stereo_Test/src/main.cpp", "max_forks_repo_name": "DreamWaterFound/Codes", "max_forks_repo_head_hexsha": "e7d80eb8bfd7d6f104abd18724cb4bface419233", "max_forks_repo_licenses": ["WTFPL"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-11T16:47:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-11T16:47:31.000Z", "avg_line_length": 23.3690851735, "max_line_length": 134, "alphanum_fraction": 0.5395518359, "num_tokens": 2540, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174789, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4724288210285613}}
{"text": "#ifndef ADAGRAD_HPP\n#define ADAGRAD_HPP\n\n#define EIGEN_MPL2_ONLY\n\n#include <Eigen/Dense>\n#include <vector>\n\nusing namespace Eigen;\nusing namespace std;\n\nclass Adagrad{\nprivate:\n  int N;\n  int d;\n  MatrixXd X;\n  VectorXd label;  \n  double C;\n  double eta;\n  int iteration;\n  VectorXd E;\n  double sigma(const MatrixXd& _x, int i);\n  double sigmoid(double z);\n\npublic:\n  VectorXd w;\n  vector<double> iterscores;\n  Adagrad(int _N,int _d,MatrixXd _x,VectorXd _label,double _C,double _eta,int iter);\n  double Acc(vector<double>& pred,VectorXd &l);\n  void train();\n  void predict(MatrixXd& _x,VectorXd& _l,vector<double>& ret);\n};\n\n#endif\n", "meta": {"hexsha": "cbbc39dfac91efd48299708e59067a4d143828a4", "size": 632, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Adagrad.hpp", "max_stars_repo_name": "saiias/Adadelta", "max_stars_repo_head_hexsha": "2a8d94ec32b887d078409b5252170d4e9ffeb402", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2015-08-27T10:49:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-01T07:42:49.000Z", "max_issues_repo_path": "Adagrad.hpp", "max_issues_repo_name": "huangpingchun/Adadelta", "max_issues_repo_head_hexsha": "2a8d94ec32b887d078409b5252170d4e9ffeb402", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2016-02-20T12:33:39.000Z", "max_issues_repo_issues_event_max_datetime": "2017-06-23T08:12:09.000Z", "max_forks_repo_path": "Adagrad.hpp", "max_forks_repo_name": "huangpingchun/Adadelta", "max_forks_repo_head_hexsha": "2a8d94ec32b887d078409b5252170d4e9ffeb402", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2015-08-27T10:49:48.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-08T08:36:07.000Z", "avg_line_length": 18.0571428571, "max_line_length": 84, "alphanum_fraction": 0.7183544304, "num_tokens": 180, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.6187804407739559, "lm_q1q2_score": 0.47242881973588374}}
{"text": "/* ============================================================================\n * Copyright 2021 The University of Utah\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, the University of Utah nor the names of its contributors may be used to endorse or promote products derived from this software without\n * specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 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 SERVICES; 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 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY\n * OF SUCH DAMAGE.\n *\n * The code contained herein was partially funded by the following contracts:\n *\n *\n * This code contained herein is based upon work supported by the following grants:\n *    DOE Office of Nuclear Energy's Nuclear Energy University Program Grant No.: DE-NE0008799\n *    DOD Office of Economic Adjustment Grant No.: ST1605-19-03\n *\n * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */\n\n#include \"ComputeFeatureEigenstrains.h\"\n\n#include <cmath>\n\n#include <QtCore/QTextStream>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Eigen>\n\n#include \"EbsdLib/Core/Orientation.hpp\"\n#include \"EbsdLib/Core/OrientationTransformation.hpp\"\n\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/DataArraySelectionFilterParameter.h\"\n#include \"SIMPLib/FilterParameters/FloatFilterParameter.h\"\n#include \"SIMPLib/FilterParameters/LinkedBooleanFilterParameter.h\"\n#include \"SIMPLib/FilterParameters/LinkedPathCreationFilterParameter.h\"\n#include \"SIMPLib/FilterParameters/SeparatorFilterParameter.h\"\n#include \"SIMPLib/Geometry/ImageGeom.h\"\n#include \"SIMPLib/Math/SIMPLibMath.h\"\n\n#include \"DREAM3DReview/DREAM3DReviewConstants.h\"\n#include \"DREAM3DReview/DREAM3DReviewVersion.h\"\n\n#include \"DREAM3DReview/DREAM3DReviewFilters/util/EigenstrainsHelper.hpp\"\n\nnamespace SIMPLMath = SIMPLib::Constants;\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nComputeFeatureEigenstrains::ComputeFeatureEigenstrains() = default;\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nComputeFeatureEigenstrains::~ComputeFeatureEigenstrains() = default;\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nvoid ComputeFeatureEigenstrains::initialize()\n{\n  clearErrorCode();\n  clearWarningCode();\n  setCancel(false);\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nvoid ComputeFeatureEigenstrains::setupFilterParameters()\n{\n  FilterParameterVectorType parameters;\n\n  // Poisson's ratio user input\n  parameters.push_back(SIMPL_NEW_FLOAT_FP(\"Poisson's Ratio\", PoissonRatio, FilterParameter::Category::Parameter, ComputeFeatureEigenstrains));\n\n  std::vector<QString> linkedProps;\n  linkedProps.push_back(\"AxisLengthsArrayPath\");\n  linkedProps.push_back(\"AxisEulerAnglesArrayPath\");\n\n  parameters.push_back(\n      SIMPL_NEW_LINKED_BOOL_FP(\"Use Ellipsoidal Grains (versus spherical assumption)\", UseEllipsoidalGrains, FilterParameter::Category::Parameter, ComputeFeatureEigenstrains, linkedProps));\n\n  // Correctional matrix beta user inputs\n  linkedProps.clear();\n  linkedProps.push_back(\"Beta11\");\n  linkedProps.push_back(\"Beta22\");\n  linkedProps.push_back(\"Beta33\");\n  linkedProps.push_back(\"Beta23\");\n  linkedProps.push_back(\"Beta13\");\n  linkedProps.push_back(\"Beta12\");\n  parameters.push_back(SIMPL_NEW_LINKED_BOOL_FP(\"Use Correctional Matrix\", UseCorrectionalMatrix, FilterParameter::Category::Parameter, ComputeFeatureEigenstrains, linkedProps));\n\n  parameters.push_back(SIMPL_NEW_FLOAT_FP(\"Beta11\", Beta11, FilterParameter::Category::Parameter, ComputeFeatureEigenstrains));\n  parameters.push_back(SIMPL_NEW_FLOAT_FP(\"Beta22\", Beta22, FilterParameter::Category::Parameter, ComputeFeatureEigenstrains));\n  parameters.push_back(SIMPL_NEW_FLOAT_FP(\"Beta33\", Beta33, FilterParameter::Category::Parameter, ComputeFeatureEigenstrains));\n  parameters.push_back(SIMPL_NEW_FLOAT_FP(\"Beta23\", Beta23, FilterParameter::Category::Parameter, ComputeFeatureEigenstrains));\n  parameters.push_back(SIMPL_NEW_FLOAT_FP(\"Beta13\", Beta13, FilterParameter::Category::Parameter, ComputeFeatureEigenstrains));\n  parameters.push_back(SIMPL_NEW_FLOAT_FP(\"Beta12\", Beta12, FilterParameter::Category::Parameter, ComputeFeatureEigenstrains));\n\n  // Axis lengths and euler angles 3xN feature arrays\n  parameters.push_back(SeparatorFilterParameter::Create(\"Cell Feature Data\", FilterParameter::Category::RequiredArray));\n\n  {\n    DataArraySelectionFilterParameter::RequirementType req =\n        DataArraySelectionFilterParameter::CreateRequirement(SIMPL::TypeNames::Float, 3, AttributeMatrix::Type::CellFeature, IGeometry::Type::Image);\n    parameters.push_back(SIMPL_NEW_DA_SELECTION_FP(\"Axis Lengths\", AxisLengthsArrayPath, FilterParameter::Category::RequiredArray, ComputeFeatureEigenstrains, req));\n  }\n\n  {\n    DataArraySelectionFilterParameter::RequirementType req =\n        DataArraySelectionFilterParameter::CreateRequirement(SIMPL::TypeNames::Float, 3, AttributeMatrix::Type::CellFeature, IGeometry::Type::Image);\n    parameters.push_back(SIMPL_NEW_DA_SELECTION_FP(\"Axis Euler Angles\", AxisEulerAnglesArrayPath, FilterParameter::Category::RequiredArray, ComputeFeatureEigenstrains, req));\n  }\n\n  // Elastic strain 6xN feature array\n  {\n    DataArraySelectionFilterParameter::RequirementType req =\n        DataArraySelectionFilterParameter::CreateRequirement(SIMPL::TypeNames::Float, 6, AttributeMatrix::Type::CellFeature, IGeometry::Type::Image);\n    parameters.push_back(SIMPL_NEW_DA_SELECTION_FP(\"Elastic Strains (Voigt Notation)\", ElasticStrainsArrayPath, FilterParameter::Category::RequiredArray, ComputeFeatureEigenstrains, req));\n  }\n\n  // Output 6xN eigenstrain feature array\n  parameters.push_back(SeparatorFilterParameter::Create(\"Cell Feature Data\", FilterParameter::Category::CreatedArray));\n  parameters.push_back(\n      SIMPL_NEW_DA_WITH_LINKED_AM_FP(\"Eigenstrains\", EigenstrainsArrayName, ElasticStrainsArrayPath, ElasticStrainsArrayPath, FilterParameter::Category::CreatedArray, ComputeFeatureEigenstrains));\n\n  setFilterParameters(parameters);\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nvoid ComputeFeatureEigenstrains::dataCheck()\n{\n  clearErrorCode();\n  clearWarningCode();\n  initialize();\n  DataArrayPath tempPath;\n\n  // Negative Poisson's ratio works in the calculations but warn\n  if(getPoissonRatio() < 0.0f)\n  {\n    QString ss = QObject::tr(\"Poisson's ratio is negative\");\n    setWarningCondition(-94001, ss);\n  }\n\n  // Incompressible v=0.5 results in singular matrix\n  if(getPoissonRatio() > 0.49999999f)\n  {\n    QString ss = QObject::tr(\"Poisson's ratio cannot be 0.5 or greater\");\n    setErrorCondition(-94002, ss);\n  }\n\n  // Check correction values and warn if they are large (potential typos)\n  if(m_UseCorrectionalMatrix)\n  {\n    if(getBeta11() < 0.5f || getBeta11() > 2.0f)\n    {\n      QString ss = QObject::tr(\"Beta11 correction is pretty large; this may be a typo\");\n      setWarningCondition(-94003, ss);\n    }\n\n    if(getBeta22() < 0.5f || getBeta22() > 2.0f)\n    {\n      QString ss = QObject::tr(\"Beta22 correction is pretty large; this may be a typo\");\n      setWarningCondition(-94004, ss);\n    }\n\n    if(getBeta33() < 0.5f || getBeta33() > 2.0f)\n    {\n      QString ss = QObject::tr(\"Beta33 correction is pretty large; this may be a typo\");\n      setWarningCondition(-94005, ss);\n    }\n\n    if(getBeta23() < 0.5f || getBeta23() > 2.0f)\n    {\n      QString ss = QObject::tr(\"Beta23 correction is pretty large; this may be a typo\");\n      setWarningCondition(-94006, ss);\n    }\n\n    if(getBeta13() < 0.5f || getBeta13() > 2.0f)\n    {\n      QString ss = QObject::tr(\"Beta13 correction is pretty large; this may be a typo\");\n      setWarningCondition(-94007, ss);\n    }\n\n    if(getBeta12() < 0.5f || getBeta12() > 2.0f)\n    {\n      QString ss = QObject::tr(\"Beta12 correction is pretty large; this may be a typo\");\n      setWarningCondition(-94008, ss);\n    }\n  }\n\n  // Check Required Objects\n  std::vector<size_t> cDims(1, 1);\n  if(m_UseEllipsoidalGrains)\n  {\n    cDims[0] = 3;\n    m_AxisLengthsPtr = getDataContainerArray()->getPrereqArrayFromPath<FloatArrayType>(this, getAxisLengthsArrayPath(), cDims);\n    if(getErrorCode() < 0)\n    {\n      return;\n    }\n\n    cDims[0] = 3;\n    m_AxisEulerAnglesPtr = getDataContainerArray()->getPrereqArrayFromPath<FloatArrayType>(this, getAxisEulerAnglesArrayPath(), cDims);\n    if(getErrorCode() < 0)\n    {\n      return;\n    }\n  }\n\n  cDims[0] = 6;\n  m_ElasticStrainsPtr = getDataContainerArray()->getPrereqArrayFromPath<FloatArrayType>(this, getElasticStrainsArrayPath(), cDims);\n  if(getErrorCode() < 0)\n  {\n    return;\n  }\n\n  // Check Eigenstrain output\n  cDims[0] = 6;\n  tempPath.update(getElasticStrainsArrayPath().getDataContainerName(), getElasticStrainsArrayPath().getAttributeMatrixName(), getEigenstrainsArrayName());\n  m_EigenstrainsPtr = getDataContainerArray()->createNonPrereqArrayFromPath<FloatArrayType>(this, tempPath, 0, cDims, \"\", 1);\n  if(getErrorCode() < 0)\n  {\n    return;\n  }\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nvoid ComputeFeatureEigenstrains::execute()\n{\n  initialize();\n  dataCheck();\n  if(getErrorCode() < 0)\n  {\n    return;\n  }\n\n  if(getCancel())\n  {\n    return;\n  }\n\n  find_eigenstrains();\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nvoid ComputeFeatureEigenstrains::find_eigenstrains()\n{\n  size_t numfeatures = m_ElasticStrainsPtr.lock()->getNumberOfTuples();\n\n  double phi1 = 0.0;\n  double theta = 0.0;\n  double phi2 = 0.0;\n\n  double semiAxisA = 0.0;\n  double semiAxisB = 0.0;\n  double semiAxisC = 0.0;\n\n  double E11 = 0.0;\n  double E22 = 0.0;\n  double E33 = 0.0;\n  double E23 = 0.0;\n  double E13 = 0.0;\n  double E12 = 0.0;\n\n  Eigen::Matrix<double, 3, 3> beta;\n  beta.setOnes(3, 3); // Default no correction\n  if(m_UseCorrectionalMatrix)\n  {\n    // clang-format off\n    beta << m_Beta11, m_Beta12, m_Beta13,\n            m_Beta12, m_Beta22, m_Beta23,\n            m_Beta13, m_Beta23, m_Beta33;\n    // clang-format on\n  }\n\n  OrientationD orientationMatrix;\n  Eigen::Matrix<double, 3, 3> OM;\n  Eigen::Matrix<double, 3, 3> OMT;\n  OM.setIdentity(3, 3); // Defaults to no orientation identity\n  OMT.setIdentity(3, 3);\n\n  Eigen::Matrix<double, 3, 3> elasticStrainTensor;\n  Eigen::Matrix<double, 3, 3> elasticStrainTensorRot;\n\n  EigenstrainsHelper::Tensor4DType eshelbyTensor;\n  EigenstrainsHelper::Tensor4DType eshelbyInverse;\n\n  Eigen::Matrix<double, 9, 9> eshelbyTensor99;\n  Eigen::Matrix<double, 9, 9> eshelbyInverse99;\n  Eigen::Matrix<double, 9, 9> I9;\n  I9.setIdentity(9, 9);\n\n  Eigen::Matrix<double, 3, 3> eigenstrainTensorRot;\n  Eigen::Matrix<double, 3, 3> eigenstrainTensor;\n  Eigen::Matrix<double, 3, 3> eigenstrainTensorCorrected;\n\n  FloatArrayType& axisEulerAngles = *(m_AxisEulerAnglesPtr.lock().get());\n  FloatArrayType& axisLengths = *(m_AxisLengthsPtr.lock().get());\n  FloatArrayType& elasticStrains = *(m_ElasticStrainsPtr.lock().get());\n  FloatArrayType& eigenstrains = *(m_EigenstrainsPtr.lock().get());\n\n  // small eps term added to euler angle bounds check as FindFeatureShapes has some small noise outside the bounds\n  double eps = 0.001;\n  double eulerPhiMax = 2 * SIMPLMath::k_PiD + eps;\n  double eulerThetaMax = SIMPLMath::k_PiD + eps;\n  double eulerMin = 0 - eps;\n\n  for(size_t feature = 0; feature < numfeatures; feature++)\n  {\n    if(m_UseEllipsoidalGrains)\n    {\n      phi1 = axisEulerAngles[feature * 3 + 0];\n      theta = axisEulerAngles[feature * 3 + 1];\n      phi2 = axisEulerAngles[feature * 3 + 2];\n\n      if(std::isnan(phi1) || std::isnan(theta) || std::isnan(phi2))\n      {\n        QString ss = QObject::tr(\"NaN Axis Euler angle found in feature ID #%1, skipping\").arg(feature);\n        notifyStatusMessage(ss);\n        eigenstrains[feature * 6 + 0] = 0;\n        eigenstrains[feature * 6 + 1] = 0;\n        eigenstrains[feature * 6 + 2] = 0;\n        eigenstrains[feature * 6 + 3] = 0;\n        eigenstrains[feature * 6 + 4] = 0;\n        eigenstrains[feature * 6 + 5] = 0;\n        continue;\n      }\n\n      if(phi1 > eulerPhiMax || phi1 < eulerMin)\n      {\n        QString ss = QObject::tr(\"Feature %1 euler angle phi1=%2 out of bounds 2pi >= phi1 >= 0. Euler angles may be in degrees\").arg(feature).arg(phi1);\n        setErrorCondition(-94000, ss);\n        return;\n      }\n\n      if(theta > eulerThetaMax || theta < eulerMin)\n      {\n        QString ss = QObject::tr(\"Feature %1 euler angle theta=%2 out of bounds pi >= theta >= 0. Euler angles may be in degrees\").arg(feature).arg(theta);\n        setErrorCondition(-94000, ss);\n        return;\n      }\n\n      if(phi2 > eulerPhiMax || phi2 < eulerMin)\n      {\n        QString ss = QObject::tr(\"Feature %1 euler angle phi2=%2 out of bounds 2pi >= phi2 >= 0. Euler angles may be in degrees\").arg(feature).arg(phi2);\n        setErrorCondition(-94000, ss);\n        return;\n      }\n\n      semiAxisA = axisLengths[feature * 3 + 0];\n      semiAxisB = axisLengths[feature * 3 + 1];\n      semiAxisC = axisLengths[feature * 3 + 2];\n\n      if(std::isnan(semiAxisA) || std::isnan(semiAxisB) || std::isnan(semiAxisC))\n      {\n        QString ss = QObject::tr(\"NaN Axis length found in feature ID #%1, skipping\").arg(feature);\n        notifyStatusMessage(ss);\n        eigenstrains[feature * 6 + 0] = 0;\n        eigenstrains[feature * 6 + 1] = 0;\n        eigenstrains[feature * 6 + 2] = 0;\n        eigenstrains[feature * 6 + 3] = 0;\n        eigenstrains[feature * 6 + 4] = 0;\n        eigenstrains[feature * 6 + 5] = 0;\n        continue;\n      }\n\n      if(semiAxisB > semiAxisA)\n      {\n        QString ss = QObject::tr(\"Feature %1 semi-axis b=%2 is greater than semi-axis a=%3. Criteria a>=b>=c must be satisfied\").arg(feature).arg(semiAxisB).arg(semiAxisA);\n        setErrorCondition(-94000, ss);\n        return;\n      }\n\n      if(semiAxisC > semiAxisB)\n      {\n        QString ss = QObject::tr(\"Feature %1 semi-axis c=%2 is greater than semi-axis b=%3. Criteria a>=b>=c must be satisfied\").arg(feature).arg(semiAxisC).arg(semiAxisB);\n        setErrorCondition(-94000, ss);\n        return;\n      }\n    }\n\n    E11 = elasticStrains[feature * 6 + 0];\n    E22 = elasticStrains[feature * 6 + 1];\n    E33 = elasticStrains[feature * 6 + 2];\n    E23 = elasticStrains[feature * 6 + 3];\n    E13 = elasticStrains[feature * 6 + 4];\n    E12 = elasticStrains[feature * 6 + 5];\n\n    // clang-format off\n    elasticStrainTensor << E11, E12, E13,\n                           E12, E22, E23,\n                           E13, E23, E33;\n    // clang-format on\n\n    // Check if the elastic strains are zero (or negligible) then so are the eigenstrains\n    if(elasticStrainTensor.isMuchSmallerThan(1e-10))\n    {\n      eigenstrains[feature * 6 + 0] = 0;\n      eigenstrains[feature * 6 + 1] = 0;\n      eigenstrains[feature * 6 + 2] = 0;\n      eigenstrains[feature * 6 + 3] = 0;\n      eigenstrains[feature * 6 + 4] = 0;\n      eigenstrains[feature * 6 + 5] = 0;\n      continue;\n    }\n\n    if(m_UseEllipsoidalGrains)\n    {\n      orientationMatrix = OrientationTransformation::eu2om<OrientationD, OrientationD>({phi1, theta, phi2});\n\n      // clang-format off\n      OM << orientationMatrix[0], orientationMatrix[1], orientationMatrix[2],\n            orientationMatrix[3], orientationMatrix[4], orientationMatrix[5],\n            orientationMatrix[6], orientationMatrix[7], orientationMatrix[8];\n      OMT = OM.transpose();\n      // clang-format on\n    }\n\n    // Change basis into ellipsoid reference frame | e' = Q e Q^T\n    elasticStrainTensorRot = OM * elasticStrainTensor * OMT;\n\n    // Calculate Eshelby tensor | S = f(a, b, c, nu)\n    eshelbyTensor = EigenstrainsHelper::find_eshelby(semiAxisA, semiAxisB, semiAxisC, m_PoissonRatio, m_UseEllipsoidalGrains);\n\n    // Map Eshelby tensor into 9x9 matrix\n    size_t col = 0;\n    size_t row = 0;\n    for(size_t i = 0; i < 3; i++)\n    {\n      for(size_t j = 0; j < 3; j++)\n      {\n        for(size_t k = 0; k < 3; k++)\n        {\n          for(size_t l = 0; l < 3; l++)\n          {\n            eshelbyTensor99(col, row) = eshelbyTensor(i, j, k, l);\n            col++;\n          }\n        }\n        row++;\n        col = 0;\n      }\n    }\n\n    // Calculate inverse | (S-I)^-1\n    eshelbyInverse99 = (eshelbyTensor99 - I9).inverse();\n\n    // Remap inverse back into a 3x3x3x3 tensor\n    col = 0;\n    row = 0;\n    for(size_t i = 0; i < 3; i++)\n    {\n      for(size_t j = 0; j < 3; j++)\n      {\n        for(size_t k = 0; k < 3; k++)\n        {\n          for(size_t l = 0; l < 3; l++)\n          {\n            eshelbyInverse(i, j, k, l) = eshelbyInverse99(col, row);\n            col++;\n          }\n        }\n        row++;\n        col = 0;\n      }\n    }\n\n    // Calculate eigenstrain tensor | e*' = (S-I)^-1 e'\n    eigenstrainTensorRot.setZero(3, 3);\n    for(size_t i = 0; i < 3; i++)\n    {\n      for(size_t j = 0; j < 3; j++)\n      {\n        for(size_t k = 0; k < 3; k++)\n        {\n          for(size_t l = 0; l < 3; l++)\n          {\n            eigenstrainTensorRot(i, j) += eshelbyInverse(i, j, k, l) * elasticStrainTensorRot(k, l);\n          }\n        }\n      }\n    }\n\n    // Change basis back to global reference frame | e* = Q^T e*' Q\n    eigenstrainTensor = OMT * eigenstrainTensorRot * OM;\n\n    // Add correction | e*c = B e*\n    eigenstrainTensorCorrected = eigenstrainTensor.cwiseProduct(beta);\n\n    eigenstrains[feature * 6 + 0] = eigenstrainTensorCorrected(0, 0);\n    eigenstrains[feature * 6 + 1] = eigenstrainTensorCorrected(1, 1);\n    eigenstrains[feature * 6 + 2] = eigenstrainTensorCorrected(2, 2);\n    eigenstrains[feature * 6 + 3] = eigenstrainTensorCorrected(1, 2);\n    eigenstrains[feature * 6 + 4] = eigenstrainTensorCorrected(0, 2);\n    eigenstrains[feature * 6 + 5] = eigenstrainTensorCorrected(0, 1);\n  }\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nAbstractFilter::Pointer ComputeFeatureEigenstrains::newFilterInstance(bool copyFilterParameters) const\n{\n  ComputeFeatureEigenstrains::Pointer filter = ComputeFeatureEigenstrains::New();\n  if(copyFilterParameters)\n  {\n    copyFilterParameterInstanceVariables(filter.get());\n  }\n  return filter;\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nQString ComputeFeatureEigenstrains::getCompiledLibraryName() const\n{\n  return DREAM3DReviewConstants::DREAM3DReviewBaseName;\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nQString ComputeFeatureEigenstrains::getBrandingString() const\n{\n  return \"DREAM3DReview\";\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nQString ComputeFeatureEigenstrains::getFilterVersion() const\n{\n  QString version;\n  QTextStream vStream(&version);\n  vStream << DREAM3DReview::Version::Major() << \".\" << DREAM3DReview::Version::Minor() << \".\" << DREAM3DReview::Version::Patch();\n  return version;\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nQString ComputeFeatureEigenstrains::getGroupName() const\n{\n  return DREAM3DReviewConstants::FilterGroups::DREAM3DReviewFilters;\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nQString ComputeFeatureEigenstrains::getSubGroupName() const\n{\n  return DREAM3DReviewConstants::FilterSubGroups::RegistrationFilters;\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nQString ComputeFeatureEigenstrains::getHumanLabel() const\n{\n  return \"Compute Eigenstrains by Feature (Grain/Inclusion)\";\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nQUuid ComputeFeatureEigenstrains::getUuid() const\n{\n  return QUuid(\"{879e1eb8-40dc-5a5b-abe5-7e0baa77ed73}\");\n}\n\n// -----------------------------------------------------------------------------\nComputeFeatureEigenstrains::Pointer ComputeFeatureEigenstrains::NullPointer()\n{\n  return Pointer(static_cast<Self*>(nullptr));\n}\n\n// -----------------------------------------------------------------------------\nstd::shared_ptr<ComputeFeatureEigenstrains> ComputeFeatureEigenstrains::New()\n{\n  struct make_shared_enabler : public ComputeFeatureEigenstrains\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 ComputeFeatureEigenstrains::getNameOfClass() const\n{\n  return QString(\"ComputeFeatureEigenstrains\");\n}\n\n// -----------------------------------------------------------------------------\nQString ComputeFeatureEigenstrains::ClassName()\n{\n  return QString(\"ComputeFeatureEigenstrains\");\n}\n\n// -----------------------------------------------------------------------------\nvoid ComputeFeatureEigenstrains::setPoissonRatio(float value)\n{\n  m_PoissonRatio = value;\n}\n\n// -----------------------------------------------------------------------------\nfloat ComputeFeatureEigenstrains::getPoissonRatio() const\n{\n  return m_PoissonRatio;\n}\n\n// -----------------------------------------------------------------------------\nvoid ComputeFeatureEigenstrains::setUseEllipsoidalGrains(bool value)\n{\n  m_UseEllipsoidalGrains = value;\n}\n\n// -----------------------------------------------------------------------------\nbool ComputeFeatureEigenstrains::getUseEllipsoidalGrains() const\n{\n  return m_UseEllipsoidalGrains;\n}\n\n// -----------------------------------------------------------------------------\nvoid ComputeFeatureEigenstrains::setUseCorrectionalMatrix(bool value)\n{\n  m_UseCorrectionalMatrix = value;\n}\n\n// -----------------------------------------------------------------------------\nbool ComputeFeatureEigenstrains::getUseCorrectionalMatrix() const\n{\n  return m_UseCorrectionalMatrix;\n}\n\n// -----------------------------------------------------------------------------\nvoid ComputeFeatureEigenstrains::setBeta11(float value)\n{\n  m_Beta11 = value;\n}\n\n// -----------------------------------------------------------------------------\nfloat ComputeFeatureEigenstrains::getBeta11() const\n{\n  return m_Beta11;\n}\n\n// -----------------------------------------------------------------------------\nvoid ComputeFeatureEigenstrains::setBeta22(float value)\n{\n  m_Beta22 = value;\n}\n\n// -----------------------------------------------------------------------------\nfloat ComputeFeatureEigenstrains::getBeta22() const\n{\n  return m_Beta22;\n}\n\n// -----------------------------------------------------------------------------\nvoid ComputeFeatureEigenstrains::setBeta33(float value)\n{\n  m_Beta33 = value;\n}\n\n// -----------------------------------------------------------------------------\nfloat ComputeFeatureEigenstrains::getBeta33() const\n{\n  return m_Beta33;\n}\n\n// -----------------------------------------------------------------------------\nvoid ComputeFeatureEigenstrains::setBeta23(float value)\n{\n  m_Beta23 = value;\n}\n\n// -----------------------------------------------------------------------------\nfloat ComputeFeatureEigenstrains::getBeta23() const\n{\n  return m_Beta23;\n}\n\n// -----------------------------------------------------------------------------\nvoid ComputeFeatureEigenstrains::setBeta13(float value)\n{\n  m_Beta13 = value;\n}\n\n// -----------------------------------------------------------------------------\nfloat ComputeFeatureEigenstrains::getBeta13() const\n{\n  return m_Beta13;\n}\n\n// -----------------------------------------------------------------------------\nvoid ComputeFeatureEigenstrains::setBeta12(float value)\n{\n  m_Beta12 = value;\n}\n\n// -----------------------------------------------------------------------------\nfloat ComputeFeatureEigenstrains::getBeta12() const\n{\n  return m_Beta12;\n}\n\n// -----------------------------------------------------------------------------\nvoid ComputeFeatureEigenstrains::setAxisLengthsArrayPath(const DataArrayPath& value)\n{\n  m_AxisLengthsArrayPath = value;\n}\n\n// -----------------------------------------------------------------------------\nDataArrayPath ComputeFeatureEigenstrains::getAxisLengthsArrayPath() const\n{\n  return m_AxisLengthsArrayPath;\n}\n\n// -----------------------------------------------------------------------------\nvoid ComputeFeatureEigenstrains::setAxisEulerAnglesArrayPath(const DataArrayPath& value)\n{\n  m_AxisEulerAnglesArrayPath = value;\n}\n\n// -----------------------------------------------------------------------------\nDataArrayPath ComputeFeatureEigenstrains::getAxisEulerAnglesArrayPath() const\n{\n  return m_AxisEulerAnglesArrayPath;\n}\n\n// -----------------------------------------------------------------------------\nvoid ComputeFeatureEigenstrains::setElasticStrainsArrayPath(const DataArrayPath& value)\n{\n  m_ElasticStrainsArrayPath = value;\n}\n\n// -----------------------------------------------------------------------------\nDataArrayPath ComputeFeatureEigenstrains::getElasticStrainsArrayPath() const\n{\n  return m_ElasticStrainsArrayPath;\n}\n\n// -----------------------------------------------------------------------------\nvoid ComputeFeatureEigenstrains::setEigenstrainsArrayName(const QString& value)\n{\n  m_EigenstrainsArrayName = value;\n}\n\n// -----------------------------------------------------------------------------\nQString ComputeFeatureEigenstrains::getEigenstrainsArrayName() const\n{\n  return m_EigenstrainsArrayName;\n}\n", "meta": {"hexsha": "c88ec6195d43a0dd2ee14fc3f62ed62c8080140c", "size": 27847, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "DREAM3DReviewFilters/ComputeFeatureEigenstrains.cpp", "max_stars_repo_name": "VKUDRI/DREAM3DReview", "max_stars_repo_head_hexsha": "5b7c869e2a1a1fc43b28c0b55d4be2c62eda0906", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/ComputeFeatureEigenstrains.cpp", "max_issues_repo_name": "VKUDRI/DREAM3DReview", "max_issues_repo_head_hexsha": "5b7c869e2a1a1fc43b28c0b55d4be2c62eda0906", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 18.0, "max_issues_repo_issues_event_min_datetime": "2017-09-01T23:13:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-02T12:58:57.000Z", "max_forks_repo_path": "DREAM3DReviewFilters/ComputeFeatureEigenstrains.cpp", "max_forks_repo_name": "VKUDRI/DREAM3DReview", "max_forks_repo_head_hexsha": "5b7c869e2a1a1fc43b28c0b55d4be2c62eda0906", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2017-09-01T23:15:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-21T13:24:19.000Z", "avg_line_length": 35.6555697823, "max_line_length": 200, "alphanum_fraction": 0.5798470212, "num_tokens": 6423, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4724288143685121}}
{"text": "#include <ros/ros.h>\n#include <iostream>\n#include <sensor_msgs/PointCloud2.h>\n#include <std_msgs/String.h>  \n#include <pcl_ros/point_cloud.h>\n#include <pcl/point_types.h>\n#include <pcl/conversions.h>\n#include <pcl_ros/transforms.h>\n#include <boost/foreach.hpp>\n#include <pcl/console/parse.h>\n#include <pcl/filters/extract_indices.h>\n#include <pcl/io/pcd_io.h>\n#include <pcl/sample_consensus/ransac.h>\n#include <pcl/sample_consensus/sac_model_sphere.h>\n#include <pcl/sample_consensus/sac_model_cylinder.h>\n#include <pcl/segmentation/sac_segmentation.h>\n\nusing std::cout;\nusing std::endl;\n\nstd_msgs::String str;\nros::Publisher pub;\nint found;\n\nvoid callback(const sensor_msgs::PointCloud2ConstPtr& cloud)\n{\n  ///Detection part was inspired from here -> http://answers.ros.org/question/229784/detecting-spheres-using-ransac-in-pcl/\n  pcl::PCLPointCloud2 pcl_pc2;\n  pcl_conversions::toPCL(*cloud,pcl_pc2); \n  pcl::PointCloud<pcl::PointXYZRGB>::Ptr temp_cloud(new pcl::PointCloud<pcl::PointXYZRGB>);\n  pcl::fromPCLPointCloud2(pcl_pc2,*temp_cloud); \n \n  pcl::ModelCoefficients::Ptr coefficients(new pcl::ModelCoefficients);\n  pcl::SACSegmentation<pcl::PointXYZRGB> segmentation;\n  segmentation.setInputCloud(temp_cloud);\n  ///Shapes that are available for RANSAC -> http://docs.pointclouds.org/1.7.0/group__sample__consensus.html\n  segmentation.setModelType(pcl::SACMODEL_SPHERE);\n  segmentation.setMethodType(pcl::SAC_RANSAC);\n  segmentation.setDistanceThreshold(1000); \n  segmentation.setOptimizeCoefficients(true);\n  segmentation.setRadiusLimits(0.4, 1);\n  segmentation.setMaxIterations(1000);\n   \n  pcl::PointIndices inlierIndices;\n  segmentation.segment(inlierIndices, *coefficients);\n   \n  if (inlierIndices.indices.size() != 0)    \n  {\n    ROS_INFO(\"RANSAC found shape with [%d] points\", (int)inlierIndices.indices.size());\n    cout << \"SPHERE!\" << endl;\n    str.data = \"found\";\n    int size = inlierIndices.indices.size();\n    if((int)temp_cloud->points[inlierIndices.indices[size/2]].r>(int)temp_cloud->points[inlierIndices.indices[size/2]].g && (int)temp_cloud->points[inlierIndices.indices[size/2]].r>(int)temp_cloud->points[inlierIndices.indices[size/2]].g)\n    {\n      cout << \"RED SPHERE!\" << endl;\n      str.data = \"found red\";\n      found = 1;\n      }\n    }\n \n    std_msgs::String nstr;\n    nstr.data = str.data;\n    pub.publish(nstr);        \n}\n\nvoid callback2(const sensor_msgs::PointCloud2ConstPtr& cloud)\n{\n  pcl::PCLPointCloud2 pcl_pc2;\n  pcl_conversions::toPCL(*cloud,pcl_pc2); \n  pcl::PointCloud<pcl::PointXYZRGB>::Ptr temp_cloud(new pcl::PointCloud<pcl::PointXYZRGB>);\n  pcl::fromPCLPointCloud2(pcl_pc2,*temp_cloud); \n\n  pcl::ModelCoefficients::Ptr coefficients(new pcl::ModelCoefficients);\n  pcl::SACSegmentation<pcl::PointXYZRGB> segmentation; \n  segmentation.setOptimizeCoefficients(true); \n  segmentation.setModelType(pcl::SACMODEL_PLANE); \n  segmentation.setMethodType(pcl::SAC_RANSAC); \n  segmentation.setDistanceThreshold(0.01);\n  segmentation.setMaxIterations(200); \n  segmentation.setInputCloud(temp_cloud);\n  segmentation.setEpsAngle (0.1);\n\n  pcl::PointIndices inlierIndices;\n  segmentation.segment(inlierIndices, *coefficients);\n  \n  if (inlierIndices.indices.size() != 0)    \n  {\n    int size = (int)inlierIndices.indices.size();\n    ROS_INFO(\"RANSAC found shape with [%d] points\", size);\n    float y1 = temp_cloud->points[inlierIndices.indices[0]].y;\n    float z1 = temp_cloud->points[inlierIndices.indices[0]].z;\n    float y2 =temp_cloud->points[inlierIndices.indices[size/2]].y;\n    float z2 =temp_cloud->points[inlierIndices.indices[size/2]].z;\n    float transformedy1 = y1*cos(-1)-z1*sin(-1);\n    float transformedy2 = y2*cos(-1)-z2*sin(-1);\n   \n    cout << temp_cloud->points[inlierIndices.indices[0]].x << \"  \" << y1 << \"  \" << temp_cloud->points[inlierIndices.indices[0]].z << endl;\n    cout << temp_cloud->points[inlierIndices.indices[size/2]].x << \"  \" << y2 << \"  \" << temp_cloud->points[inlierIndices.indices[size/2]].z << endl;\n    cout << transformedy1 << endl;\n    cout << transformedy2 << endl;\n    cout << (int)temp_cloud->points[inlierIndices.indices[size/2]].r << endl;\n    cout << (int)temp_cloud->points[inlierIndices.indices[size/2]].g << endl;\n    cout << (int)temp_cloud->points[inlierIndices.indices[size/2]].b << endl;\n    \n    if(fabs(transformedy2- transformedy1) < 0.1 && transformedy1 < 1.3)\n    {\n      cout << \"CUBE!\" << endl;\n      str.data = \"found cube\";\n      cout << \"blabla\" << endl;\n      if((int)temp_cloud->points[inlierIndices.indices[size/2]].g>(int)temp_cloud->points[inlierIndices.indices[size/2]].b && (int)temp_cloud->points[inlierIndices.indices[size/2]].g>(int)temp_cloud->points[inlierIndices.indices[size/2]].r)\n      {\n        cout << \"GREEN CUBE!\" << endl;\n        str.data = \"found green\";\n      }     \n    }  \n  }\n}\n\nvoid callback0(const sensor_msgs::PointCloud2ConstPtr& cloud)\n{\n  callback(cloud);\n  callback2(cloud);\n  std_msgs::String nstr;\n  nstr.data = str.data;\n  pub.publish(nstr);     \n}\n\nint main(int argc, char **argv) \n{ \n  ros::init(argc, argv, \"subscribed\");\n  ros::NodeHandle nh(\"/\");\n  ros::Subscriber sub;  \n  str.data = \"nothing\";\n  found = 0;\n \n  sub =nh.subscribe<sensor_msgs::PointCloud2>(\"/camera/depth/points\", 1, callback0);\n  \n  ros::init(argc, argv, \"publish\");\n  pub = nh.advertise<std_msgs::String>(\"detectionresult\", 1000);\n  \n  ros::Rate spin_rate(1);\n  while(ros::ok())\n    ros::spin();\n \n  return 0;    \n}\n", "meta": {"hexsha": "9f46e41553b3af550992f678f12942323d8ef4ef", "size": 5424, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/point_cloud_package/src/pointcloud_subs.cpp", "max_stars_repo_name": "itu-kubot-team/kubot", "max_stars_repo_head_hexsha": "43e850ee327312cd9fb98ae76402e6933740a61f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-01-04T21:35:15.000Z", "max_stars_repo_stars_event_max_datetime": "2017-01-04T21:35:15.000Z", "max_issues_repo_path": "src/point_cloud_package/src/pointcloud_subs.cpp", "max_issues_repo_name": "itu-kubot-team/kubot", "max_issues_repo_head_hexsha": "43e850ee327312cd9fb98ae76402e6933740a61f", "max_issues_repo_licenses": ["MIT"], "max_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_cloud_package/src/pointcloud_subs.cpp", "max_forks_repo_name": "itu-kubot-team/kubot", "max_forks_repo_head_hexsha": "43e850ee327312cd9fb98ae76402e6933740a61f", "max_forks_repo_licenses": ["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.8979591837, "max_line_length": 240, "alphanum_fraction": 0.7005899705, "num_tokens": 1504, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4724288143685121}}
{"text": "/*\n * This example reproduces one of the tests with Eigen in the\n * Boost odeint repository.\n *\n * Check here: https://github.com/boostorg/odeint/blob/develop/test_external/eigen/runge_kutta4.cpp\n */\n\n#include <iostream>\n#include <Eigen/Core>\n#include <boost/numeric/odeint.hpp>\n\n#include <boost/numeric/odeint/algebra/vector_space_algebra.hpp>\n#include <boost/numeric/odeint/external/eigen/eigen_resize.hpp>\n\nusing namespace boost::numeric::odeint;\nusing namespace Eigen;\n\ntypedef Matrix< double , Dynamic , 1 > state_type;\n\n// System to be solved\nstruct sys\n{\n    template<class State, class Deriv>\n    void operator()(const State& x, Deriv& dxdt, double t) const\n    {\n        dxdt[0] = 1.0;\n    }\n};\n\nint main()\n{\n    state_type x( 1 );\n    x[0] = 10.0;\n    runge_kutta4< state_type , double , state_type , double , vector_space_algebra > rk4;\n    rk4.do_step( sys() , x , 0.0 , 0.1 );\n\n    std::cout << x << std::endl;\n}", "meta": {"hexsha": "2837769bdeeef55910580c3c6fcff43d9190894b", "size": 925, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/boost/standalones/dynamic_eigen_2.cpp", "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": "examples/boost/standalones/dynamic_eigen_2.cpp", "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": "examples/boost/standalones/dynamic_eigen_2.cpp", "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": 24.3421052632, "max_line_length": 99, "alphanum_fraction": 0.6843243243, "num_tokens": 266, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.6187804267137442, "lm_q1q2_score": 0.4724288090011404}}
{"text": "/**\n * File: BRIEF.cpp\n * Author: Dorian Galvez\n * Date: September 2010\n * Description: implementation of BRIEF (Binary Robust Independent \n *   Elementary Features) descriptor by \n *   Michael Calonder, Vincent Lepetitand Pascal Fua\n *   + close binary tests (by Dorian Galvez-Lopez)\n * License: see the LICENSE.txt file\n *\n */\n\n#include \"BRIEF.h\"\n#include \"../src/DUtils.h\"\n#include <boost/dynamic_bitset.hpp>\n#include <vector>\n\nusing namespace std;\nusing namespace DVision;\n\n// ----------------------------------------------------------------------------\n\nBRIEF::BRIEF(int nbits, int patch_size, Type type):\n  m_bit_length(nbits), m_patch_size(patch_size), m_type(type)\n{\n  assert(patch_size > 1);\n  assert(nbits > 0);\n  generateTestPoints();\n}\n\n// ----------------------------------------------------------------------------\n\nBRIEF::~BRIEF()\n{\n}\n\n// ---------------------------------------------------------------------------\n\nvoid BRIEF::compute(const cv::Mat &image, \n    const std::vector<cv::KeyPoint> &points,\n    vector<bitset> &descriptors,\n    bool treat_image) const\n{\n  const float sigma = 2.f;\n  const cv::Size ksize(9, 9);\n  \n  cv::Mat im;\n  if(treat_image)\n  {\n    cv::Mat aux;\n    if(image.depth() == 3)\n    {\n      cv::cvtColor(image, aux, CV_RGB2GRAY);\n      //cv::cvtColor(image, aux, cv::COLOR_RGB2GRAY);\n    }\n    else\n    {\n      aux = image;\n    }\n\n    cv::GaussianBlur(aux, im, ksize, sigma, sigma);\n    \n  }\n  else\n  {\n    im = image;\n  }\n  \n  assert(im.type() == CV_8UC1);\n  assert(im.isContinuous());\n  \n  // use im now\n  const int W = im.cols;\n  const int H = im.rows;\n  \n  descriptors.resize(points.size());\n  std::vector<bitset>::iterator dit;\n\n  std::vector<cv::KeyPoint>::const_iterator kit;\n  \n  int x1, y1, x2, y2;\n  \n  dit = descriptors.begin();\n  for(kit = points.begin(); kit != points.end(); ++kit, ++dit)\n  {\n    dit->resize(m_bit_length);\n    dit->reset();\n\n    for(unsigned int i = 0; i < m_x1.size(); ++i)\n    {\n      x1 = (int)(kit->pt.x + m_x1[i]);\n      y1 = (int)(kit->pt.y + m_y1[i]);\n      x2 = (int)(kit->pt.x + m_x2[i]);\n      y2 = (int)(kit->pt.y + m_y2[i]);\n      \n      if(x1 >= 0 && x1 < W && y1 >= 0 && y1 < H \n        && x2 >= 0 && x2 < W && y2 >= 0 && y2 < H)\n      {\n        if( im.ptr<unsigned char>(y1)[x1] < im.ptr<unsigned char>(y2)[x2] )\n        {\n          dit->set(i);\n        }        \n      } // if (x,y)_1 and (x,y)_2 are in the image\n            \n    } // for each (x,y)\n  } // for each keypoint\n}\n\n// ---------------------------------------------------------------------------\n\nvoid BRIEF::generateTestPoints()\n{  \n  m_x1.resize(m_bit_length);\n  m_y1.resize(m_bit_length);\n  m_x2.resize(m_bit_length);\n  m_y2.resize(m_bit_length);\n\n  const float g_mean = 0.f;\n  const float g_sigma = 0.2f * (float)m_patch_size;\n  const float c_sigma = 0.08f * (float)m_patch_size;\n  \n  float sigma2;\n  if(m_type == RANDOM)\n    sigma2 = g_sigma;\n  else\n    sigma2 = c_sigma;\n  \n  const int max_v = m_patch_size / 2;\n  \n  DUtils::Random::SeedRandOnce();\n  \n  for(int i = 0; i < m_bit_length; ++i)\n  {\n    int x1, y1, x2, y2;\n    \n    do\n    {\n      x1 = DUtils::Random::RandomGaussianValue(g_mean, g_sigma);\n    } while( x1 > max_v || x1 < -max_v);\n    \n    do\n    {\n      y1 = DUtils::Random::RandomGaussianValue(g_mean, g_sigma);\n    } while( y1 > max_v || y1 < -max_v);\n    \n    float meanx, meany;\n    if(m_type == RANDOM)\n      meanx = meany = g_mean;\n    else\n    {\n      meanx = x1;\n      meany = y1;\n    }\n    \n    do\n    {\n      x2 = DUtils::Random::RandomGaussianValue(meanx, sigma2);\n    } while( x2 > max_v || x2 < -max_v);\n    \n    do\n    {\n      y2 = DUtils::Random::RandomGaussianValue(meany, sigma2);\n    } while( y2 > max_v || y2 < -max_v);\n    \n    m_x1[i] = x1;\n    m_y1[i] = y1;\n    m_x2[i] = x2;\n    m_y2[i] = y2;\n  }\n\n}\n\n// ----------------------------------------------------------------------------\n\n\n", "meta": {"hexsha": "a341232d8ac0d480378f99e40ecceb85e769070e", "size": 3879, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "deprecated/software/scene_retrieving/loop_closing/DBow3/src/BRIEF.cpp", "max_stars_repo_name": "mfkiwl/GAAS", "max_stars_repo_head_hexsha": "29ab17d3e8a4ba18edef3a57c36d8db6329fac73", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2111.0, "max_stars_repo_stars_event_min_datetime": "2019-01-29T07:01:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T06:48:14.000Z", "max_issues_repo_path": "software/scene_retrieving/loop_closing/DBow3/src/BRIEF.cpp", "max_issues_repo_name": "Wayne-xixi/GAAS", "max_issues_repo_head_hexsha": "308ff4267ccc6fcad77eef07e21fa006cc2cdd5f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 131.0, "max_issues_repo_issues_event_min_datetime": "2019-02-18T10:56:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-27T12:07:00.000Z", "max_forks_repo_path": "software/scene_retrieving/loop_closing/DBow3/src/BRIEF.cpp", "max_forks_repo_name": "Wayne-xixi/GAAS", "max_forks_repo_head_hexsha": "308ff4267ccc6fcad77eef07e21fa006cc2cdd5f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 421.0, "max_forks_repo_forks_event_min_datetime": "2019-02-12T07:59:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T05:22:01.000Z", "avg_line_length": 22.0397727273, "max_line_length": 79, "alphanum_fraction": 0.5073472544, "num_tokens": 1168, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911056, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4724288077084627}}
{"text": "#include \"Tudat/Astrodynamics/Relativity/jw_acceleration.h\"\n\n#include <iostream>\n\n#include <Eigen/Geometry>\n\nnamespace tudat {\n\nnamespace gnv {\n\n    Eigen::Vector3d ext_pot_acceleration(\n        const Eigen::Vector3d& relativePosition,\n        const Eigen::Vector3d& relativePosition_cb_wrt_primary,\n        const double commonCorrectionTerm,\n        const double mu_primary\n    ) {\n        double rab = relativePosition_cb_wrt_primary.norm();\n        return (commonCorrectionTerm*mu_primary/rab)*relativePosition;\n    }\n\n    Eigen::Vector3d kinetic_acceleration(\n        Eigen::Vector6d state_subject,\n        Eigen::Vector6d state_actor,\n        double mu_actor\n    ) {\n        Eigen::Vector6d state_sa = state_subject - state_actor;\n        Eigen::Vector3d pos_sa   = state_sa.segment(0,3);\n\n        Eigen::Vector3d vel_a    = state_actor.segment(3,3);\n\n        const double c = tudat::physical_constants::SPEED_OF_LIGHT;\n\n        double beta_a = vel_a.norm()/c;\n\n        double r = pos_sa.norm();\n\n        return -(2.0*beta_a*beta_a*mu_actor/(r*r*r))*pos_sa;\n\n    }\n\n    Eigen::Vector3d schwarzschild_acceleration(\n        Eigen::Vector6d state_subject,\n        Eigen::Vector6d state_actor,\n        double mu_actor,\n        double ppn_gamma\n    ) {\n        Eigen::Vector6d state_sa = state_subject - state_actor;\n        Eigen::Vector3d pos_sa = state_sa.segment(0,3);\n        Eigen::Vector3d vel_sa = state_sa.segment(3,3);\n\n        const double c = tudat::physical_constants::SPEED_OF_LIGHT;\n        double r = pos_sa.norm();\n\n        double mu_c2_r3 = mu_actor / (c*c*r*r*r);\n\n        return mu_c2_r3 * (\n            (4.0*mu_actor/r - vel_sa.dot(vel_sa)) * pos_sa +\n            4*(pos_sa.dot(vel_sa)) * vel_sa\n        );\n\n//        Eigen::Vector3d output_vector;\n//        output_vector.setZero();\n//        return output_vector;\n    }\n\n    Eigen::Vector3d cb_velocity_acceleration(\n        Eigen::Vector6d state_subject,\n        Eigen::Vector6d state_actor,\n        double mu_actor\n    ) {\n        Eigen::Vector6d state_sa = state_subject - state_actor;\n        Eigen::Vector3d pos_sa = state_sa.segment(0,3);\n        //Eigen::Vector3d vel_sa = state_sa.segment(3,3);\n        Eigen::Vector3d vel_a  = state_actor.segment(3,3);\n\n        double r = pos_sa.norm();\n        double r_dot_v = pos_sa.dot(vel_a);\n        double c = tudat::physical_constants::SPEED_OF_LIGHT;\n        double pre_factor = (mu_actor*r_dot_v)/(2.0*c*c*r*r*r);\n\n        return pre_factor * ( ((3.0*r_dot_v)/(r*r)) * pos_sa - 2.0*vel_a);\n    }\n\n    Eigen::Vector3d lense_thirring_acceleration(\n        Eigen::Vector6d state_subject,\n        Eigen::Vector6d state_actor,\n        Eigen::Vector3d angular_momentum_actor\n    ) {\n//        std::cout << __FILE__ << \"\\n Line \" << __LINE__ << std::endl;\n//        throw std::runtime_error(\"Lense Thirring function not implemented\");\n//        return Eigen::Vector3d::Zero();\n\n        Eigen::Vector6d state_sa = state_subject - state_actor;\n        Eigen::Vector3d pos_sa = state_sa.segment(0,3);\n        Eigen::Vector3d vel_sa = state_sa.segment(3,3);\n\n        double r = pos_sa.norm();\n\n        double G = tudat::physical_constants::GRAVITATIONAL_CONSTANT;\n        double c = tudat::physical_constants::SPEED_OF_LIGHT;\n\n        return (2*G/(c*c*r*r*r)) * (\n            (3.0/(r*r)) * pos_sa.dot(angular_momentum_actor) * pos_sa.cross(vel_sa) +\n            vel_sa.cross(angular_momentum_actor)\n        );\n    }\n\n    Eigen::Vector3d wavi_acceleration(\n        Eigen::Vector6d state_subject,\n        Eigen::Vector6d state_actor,\n        double mu_actor\n    ) {\n//        std::cout << __FILE__ << \"\\n Line \" << __LINE__ << std::endl;\n//        throw std::runtime_error(\"Wavi function not implemented\");\n//        return Eigen::Vector3d::Zero();\n\n        Eigen::Vector6d state_sa = state_subject - state_actor;\n        Eigen::Vector3d pos_sa   = state_sa.segment(0,3);\n        Eigen::Vector3d vel_sa   = state_sa.segment(3,3);\n        Eigen::Vector3d vel_a    = state_actor.segment(3,3);\n\n        const double c = tudat::physical_constants::SPEED_OF_LIGHT;\n\n        double r = pos_sa.norm();\n\n        return 4*mu_actor / (c*c*r*r*r) * (\n            vel_a.dot(vel_sa) * pos_sa -\n            pos_sa.dot(vel_sa) * vel_a\n        );\n    }\n\n    Eigen::Vector3d de_sitter_acceleration(\n        Eigen::Vector6d state_subject,\n        Eigen::Vector6d state_actor,\n        Eigen::Vector6d state_primary,\n        double mu_primary\n    ) {\n//        std::cout << __FILE__ << \"\\n Line \" << __LINE__ << std::endl;\n//        throw std::runtime_error(\"de Sitter function not implemented\");\n//        return Eigen::Vector3d::Zero();\n        Eigen::Vector6d state_sa = state_subject - state_actor;\n        Eigen::Vector6d state_ap = state_actor - state_primary;\n\n        Eigen::Vector3d v_sa = state_sa.segment(3,3);\n        Eigen::Vector3d r_ap = state_ap.segment(0,3);\n        Eigen::Vector3d v_ap = state_ap.segment(3,3);\n\n        double c = tudat::physical_constants::SPEED_OF_LIGHT;\n\n        //double r = r_sa.norm();\n        double R = r_ap.norm();\n\n        double pre_factor = 3.0*mu_primary/(c*c*R*R*R);\n\n        return pre_factor * (\n            (v_ap.cross(r_ap)).cross(v_sa)\n        );\n    }\n\n}\n\n}\n", "meta": {"hexsha": "ec4d09362262d0cf5340f4a5138d2e533a187d8e", "size": 5207, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/Relativity/jw_acceleration.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/Relativity/jw_acceleration.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/Relativity/jw_acceleration.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": 31.9447852761, "max_line_length": 85, "alphanum_fraction": 0.6189744575, "num_tokens": 1382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528132451417, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.4723826724843778}}
{"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    double T{};\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 star{};\n  std::string sT{};\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=\"exT\";\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      (\"T\", value(&T)->default_value(0.1), \"T\")\n      (\"M,m\", value(&M)->default_value(2), \"M\")\n      (\"t0\", value(&t0)->default_value(1.), \"t0\")\n      (\"gam\", value(&gamma)->default_value(std::sqrt(2)), \"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(\"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 if (vm.count(\"T\"))\n      // {      std::cout << \"T: \" << vm[\"T\"].as<double>() << '\\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  double dt=0.1;\n  ElectronState estate1(L, 1);\n  ElectronBasis e( L, 1);\n  std::cout<< e<<std::endl;\n  \n  PhononBasis ph(L, M);\n  //                 std::cout<< ph<<std::endl;\n      HolsteinBasis TP(e, ph);\n      std::cout<< TP.dim << std::endl;             \n         Eigen::VectorXcd inistate(TP.dim);\n\n   \t Mat O=Operators::NumberOperator(TP, ph, 1,  PB);\n   inistate.setZero();\n\n   inistate[0]=1;\n   \t          Eigen::VectorXcd i0=inistate;\n      \n   \t\t  std::cout<< TP.dim << std::endl;     \n      Mat E1=Operators::EKinOperatorL(TP, e, t0,PB);\n       Mat Ebdag=Operators::NBosonCOperator(TP, ph, gamma, PB);\n       Mat Eb=Operators::NBosonDOperator(TP, ph, gamma, PB);\n      Mat Eph=Operators::NumberOperator(TP, ph, omega,  PB);\n\n      Eigen::VectorXd eigenVals(TP.dim);\n      Mat H=E1+Eb+Eph+Ebdag;\n   auto J=Operators::CurOperatorL(TP, e, t0, PB);    \nEigen::MatrixXcd Jcp=J*std::complex<double>(0,1);      \n\n    Eigen::MatrixXd HH=Eigen::MatrixXd(H);\n   \n\n    //Eigen::MatrixXcd HHcp=HH;\n    Eigen::MatrixXcd HHcp=Eigen::MatrixXd(HH);\n             Eigen::MatrixXcd M2=HHcp*Jcp;\n             Eigen::MatrixXcd M1=Jcp*HHcp;\n\t     Eigen::MatrixXcd COMM=M1-M2;\n\t     //                  std::cout<< M1<<std::endl;\n\t     //           std::cout<< COMM<<std::endl;\n\t     //   std::cout<< M2<<std::endl;\n\t       COMM*=Jcp;\n\t\t  \n\t\t  //           std::cout<< HHcp<<std::endl;\n\t\t  //           std::cout<< Jcp<<std::endl;\n        Eigen::MatrixXd N=Eigen::MatrixXd(Eph);\n\t  Many_Body::diagMat(HH, eigenVals);\n     std::cout<<\"MIN E \"<<std::setprecision(15)<< eigenVals(0)<< std::endl;\n     std::cout<< \"MAX \"<<eigenVals(eigenVals.size()-1)<< std::endl;\n    \t\t      std::cout<<endl<<eigenVals.mean()-mean<<std::endl;\n         Eigen::VectorXd energy(TP.dim);\n    \t   std::vector<double> obs(TP.dim);\n    \t   std::vector<double> obs2(TP.dim);\n\t   std::vector<double> obs3(TP.dim);\n\t   std::vector<double> obs4(TP.dim);\n\t   std::vector<double> obs5(TP.dim);\n\t   std::vector<double> obs6(TP.dim);\n\t   //std::vector<double> obs(TP.dim);\n    \t   std::vector<double> ensvec(TP.dim);\n\t     \n\t   Eigen::MatrixXd PHD2=HH.adjoint()*N*HH;\n\t   Eigen::MatrixXd EKIN=HH.adjoint()*E1*HH;\n\t   Eigen::MatrixXd EC=HH.adjoint()*(Ebdag+Eb)*HH;\n\t   Eigen::MatrixXcd Jmat=HH.adjoint()*(Jcp*HH);\n\t   Eigen::MatrixXcd JJmat=Jmat*Jmat;\n\t   Eigen::MatrixXcd COMMmat=HH.adjoint()*(COMM*HH);\n\t   //\t   std::complex<double> J_in=(newIn.adjoint()*(Jcp*newIn))(0);\n\t   // std::complex<double> JJsq_in=(newIn.adjoint()*(Jcp*Jcp*newIn))(0);\n\t    Eigen::VectorXd v=PHD2.diagonal();\n\t    Eigen::VectorXd v2=EKIN.diagonal();\n\t    Eigen::VectorXd v3=EC.diagonal();\n\t    Eigen::VectorXd v4=(JJmat.diagonal().real());\n\t     Eigen::VectorXd v5=(Jmat.diagonal().real());\n\t     Eigen::VectorXd v6=(COMMmat.diagonal().real());\n\t    std::cout<< \"GS \"<<eigenVals(0)<<std::endl;\n    \t   for(int i=0; i<energy.size(); i++)\n    {\n      //obs[i]=real(obstot[i]);\n      \n      ensvec[i]=eigenVals(i);\n      obs[i]=v(i);\n      obs2[i]=v2(i);\n      obs3[i]=v3(i);\n      obs4[i]=v4(i);\n      obs5[i]=v5(i);\n      obs6[i]=v6(i);\n      std::cout<< COMMmat(i,i)<<std::endl;\n      if(gamma!=0)\n\t{\tobs3[i]/=gamma;}\n\n      //std::cout<< ensvec[i]<<'\\n';\n    }// \t   \t    std::cout<< \"gS \"<<   eigenVals[0] <<std::endl;\n    \t\t    std::cout<< \"mean \"<<   eigenVals.mean() <<std::endl;\n    \t   std::vector<double> Ovec;\n\t    std::vector<double> Ovec2;\n\t     std::vector<double> Ovec3;\n\t     std::vector<double> Ovec4;\n\t     \t     std::vector<double> Ovec5;\n\n   \t    \t   std::vector<double> Evec;\n   \t    \t   //\t\t   std::vector<double> Tr={0.01, 0.05, 0.1, 0.15, 0.2, 0.25};\n   \t    \t   \t\t   std::vector<double> Tr;\n   \t    \t   for(int i=1; i<22; i++)\n   \t    \t     {\n   \t    \t       Tr.push_back(i*0.05);\n\t\t       \n   \t    \t     }\n\n\t\t   \n   \t    \t  \t  for(auto t: Tr){\n\t     \n   \t    \t // //\t      std::cout<< l<<std::endl;\n   \t         // bin_write(filename, l);\n   \t    \t // n++;\n\t\t\t    double e1=expvalCan(ensvec, ensvec,  t);\n\t\t\t    double o=expvalCan(ensvec, obs,  t);\n\t\t\t    double o2=expvalCan(ensvec, obs2,  t);\n\t\t\t    double o3=expvalCan(ensvec, obs3,  t);\n\t\t\t    double o4=expvalCan(ensvec, obs4,  t);\n\t\t\t     double o5=expvalCan(ensvec, obs5,  t);\n\t\t\t     double o6=expvalCan(ensvec, obs6,  t);\n   \t    \t\t    std::cout<< \" at T \"<< t<<std::endl;\n\t\t\t    std::cout<<std::setprecision(15)<<e1 <<\"  \"<< o+o2+o3*gamma <<\" Nph \"<<o << \" JJ \" <<o4 << \"o 6 2 \"<< o6<< std::endl;\n\t\t\t    Ovec.push_back(o);\n\t\t\t    Ovec2.push_back(o2);\n\t\t\t    Ovec3.push_back(o3);\n\t\t\t    Ovec4.push_back(o4);\n\t\t\t    \t\t\t    Ovec5.push_back(o5);\n\t\t\t    Evec.push_back(e1);\n\n   \t    }\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(\"JJ\"+filename, Ovec4);\n\t\t      bin_write(\"J\"+filename, Ovec5);\n\t\t      bin_write(\"temp\"+filename, Tr);\n  return 0;\n}\n \n", "meta": {"hexsha": "8ea66ba04b269e0330f69ea3952189291f96f21d", "size": 8201, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/holstFTexact.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/holstFTexact.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/holstFTexact.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": 32.4150197628, "max_line_length": 124, "alphanum_fraction": 0.5376173637, "num_tokens": 2636, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528057272544, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.47238266831593134}}
{"text": "/*\n * Copyright 2010,2019\n *  CNRS/AIST\n * Fran\u00e7ois Bleibel, Olivier Stasse, Fran\u00e7ois Bailly\n *\n */\n\n#ifndef __SOT_MATRIX_GEOMETRY_H__\n#define __SOT_MATRIX_GEOMETRY_H__\n\n/* --- Matrix --- */\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <dynamic-graph/eigen-io.h>\n#include <dynamic-graph/linear-algebra.h>\n#include <sot/core/api.hh>\n\n#define MRAWDATA(x) x.data()\n\n/* --------------------------------------------------------------------- */\n/* --------------------------------------------------------------------- */\n/* --------------------------------------------------------------------- */\n\nnamespace dynamicgraph {\nnamespace sot {\n\n#define EIGEN_MAKE_TYPEDEFS(Type, TypeSuffix, Size, SizeSuffix)                \\\n  /** \\ingroup matrixtypedefs */                                               \\\n  typedef Eigen::Matrix<Type, Size, Size> Matrix##SizeSuffix##TypeSuffix;      \\\n  /** \\ingroup matrixtypedefs */                                               \\\n  typedef Eigen::Matrix<Type, Size, 1> Vector##SizeSuffix##TypeSuffix;         \\\n  /** \\ingroup matrixtypedefs */                                               \\\n  typedef Eigen::Matrix<Type, 1, Size> RowVector##SizeSuffix##TypeSuffix;\n\n#define EIGEN_MAKE_FIXED_TYPEDEFS(Type, TypeSuffix, Size)                      \\\n  /** \\ingroup matrixtypedefs */                                               \\\n  typedef Eigen::Matrix<Type, Size, Eigen::Dynamic>                            \\\n      Matrix##Size##X##TypeSuffix;                                             \\\n  /** \\ingroup matrixtypedefs */                                               \\\n  typedef Eigen::Matrix<Type, Eigen::Dynamic, Size> Matrix##X##Size##TypeSuffix;\n\n#define EIGEN_MAKE_TYPEDEFS_ALL_SIZES(Type, TypeSuffix)                        \\\n  EIGEN_MAKE_TYPEDEFS(Type, TypeSuffix, 1, 1)                                  \\\n  EIGEN_MAKE_TYPEDEFS(Type, TypeSuffix, 5, 5)                                  \\\n  EIGEN_MAKE_TYPEDEFS(Type, TypeSuffix, 6, 6)                                  \\\n  EIGEN_MAKE_TYPEDEFS(Type, TypeSuffix, 7, 7)                                  \\\n  EIGEN_MAKE_FIXED_TYPEDEFS(Type, TypeSuffix, 1)                               \\\n  EIGEN_MAKE_FIXED_TYPEDEFS(Type, TypeSuffix, 5)                               \\\n  EIGEN_MAKE_FIXED_TYPEDEFS(Type, TypeSuffix, 6)                               \\\n  EIGEN_MAKE_FIXED_TYPEDEFS(Type, TypeSuffix, 7)\n\nEIGEN_MAKE_TYPEDEFS_ALL_SIZES(int, i)\nEIGEN_MAKE_TYPEDEFS_ALL_SIZES(float, f)\nEIGEN_MAKE_TYPEDEFS_ALL_SIZES(double, d)\nEIGEN_MAKE_TYPEDEFS_ALL_SIZES(std::complex<float>, cf)\nEIGEN_MAKE_TYPEDEFS_ALL_SIZES(std::complex<double>, cd)\n\n#undef EIGEN_MAKE_TYPEDEFS_ALL_SIZES\n#undef EIGEN_MAKE_TYPEDEFS\n\ntypedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>\n    MatrixRXd;\ntypedef Eigen::Map<MatrixRXd> SigMatrixXd;\ntypedef Eigen::Map<Eigen::VectorXd> SigVectorXd;\ntypedef const Eigen::Map<const MatrixRXd> const_SigMatrixXd;\ntypedef const Eigen::Map<const Eigen::VectorXd> const_SigVectorXd;\n\ntypedef Eigen::Ref<Eigen::VectorXd> RefVector;\ntypedef const Eigen::Ref<const Eigen::VectorXd> &ConstRefVector;\ntypedef Eigen::Ref<Eigen::MatrixXd> RefMatrix;\ntypedef const Eigen::Ref<const Eigen::MatrixXd> ConstRefMatrix;\n\ntypedef Eigen::Transform<double, 3, Eigen::Affine> SOT_CORE_EXPORT\n    MatrixHomogeneous;\ntypedef Eigen::Matrix<double, 3, 3> SOT_CORE_EXPORT MatrixRotation;\ntypedef Eigen::AngleAxis<double> SOT_CORE_EXPORT VectorUTheta;\ntypedef Eigen::Quaternion<double> SOT_CORE_EXPORT VectorQuaternion;\ntypedef Eigen::Vector3d SOT_CORE_EXPORT VectorRotation;\ntypedef Eigen::Vector3d SOT_CORE_EXPORT VectorRollPitchYaw;\ntypedef Eigen::Matrix<double, 6, 6> SOT_CORE_EXPORT MatrixForce;\ntypedef Eigen::Matrix<double, 6, 6> SOT_CORE_EXPORT MatrixTwist;\n\ntypedef Eigen::Matrix<double, 7, 1> SOT_CORE_EXPORT Vector7;\ntypedef Eigen::Quaternion<double> SOT_CORE_EXPORT Quaternion;\ntypedef Eigen::Map<Quaternion> SOT_CORE_EXPORT QuaternionMap;\n\ninline void buildFrom(const MatrixHomogeneous &MH, MatrixTwist &MT) {\n\n  Eigen::Vector3d _t = MH.translation();\n  MatrixRotation R(MH.linear());\n  Eigen::Matrix3d Tx;\n  Tx << 0, -_t(2), _t(1), _t(2), 0, -_t(0), -_t(1), _t(0), 0;\n  Eigen::Matrix3d sk;\n  sk = Tx * R;\n\n  MT.block<3, 3>(0, 0) = R;\n  MT.block<3, 3>(0, 3) = sk;\n  MT.block<3, 3>(3, 0).setZero();\n  MT.block<3, 3>(3, 3) = R;\n}\n\n} // namespace sot\n} // namespace dynamicgraph\n\n#endif /* #ifndef __SOT_MATRIX_GEOMETRY_H__ */\n", "meta": {"hexsha": "52046447aebcebf522b94aef7aa46dc87bd99b98", "size": 4433, "ext": "hh", "lang": "C++", "max_stars_repo_path": "include/sot/core/matrix-geometry.hh", "max_stars_repo_name": "Rascof/sot-core", "max_stars_repo_head_hexsha": "281ed2a1b40b7945b5a3d5735f785b9004b19f87", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2016-03-28T07:15:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-05T13:41:06.000Z", "max_issues_repo_path": "include/sot/core/matrix-geometry.hh", "max_issues_repo_name": "Rascof/sot-core", "max_issues_repo_head_hexsha": "281ed2a1b40b7945b5a3d5735f785b9004b19f87", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 121.0, "max_issues_repo_issues_event_min_datetime": "2015-02-17T08:38:25.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-01T10:54:05.000Z", "max_forks_repo_path": "include/sot/core/matrix-geometry.hh", "max_forks_repo_name": "Rascof/sot-core", "max_forks_repo_head_hexsha": "281ed2a1b40b7945b5a3d5735f785b9004b19f87", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2015-07-01T16:25:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-08T15:06:58.000Z", "avg_line_length": 41.820754717, "max_line_length": 80, "alphanum_fraction": 0.6120009023, "num_tokens": 1126, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.472382666231708}}
{"text": "#include <iostream>\n#include <NTL/RR.h>\n#include \"ring.h\"\n#include \"she.h\"\n#include \"util.h\"\n#include \"params.h\"\n\nusing namespace std;\nusing namespace NTL;\n\nvoid encode_test (param& prm) {\n  cout << \"--- encode_test for \" << prm.label << \" ---\" << endl;\n\n  long test_num = 5;\n  for (long cnt = 0; cnt < test_num; ++cnt) {\n    PlainText x(prm);\n    x.uniform();\n\n    PlainText z(prm);\n    encode_pt(prm, z, x);\n\n    PlainText x1(prm);\n    decode_pt(prm, x1, z);\n\n    if (x != x1) {\n      cout << \"NG: encode_test: (\" << cnt << \")\" << endl;\n      cout << \" x = \" << x << endl;\n      cout << \" z = \" << z << endl;\n      cout << \"x1 = \" << x1 << endl;\n      exit(-1);\n    }\n  }\n\n  cout << \"OK: encode_test\" << endl;\n}\n\nvoid dec_test (param& prm, const SKey& s) {\n  cout << \"--- dec_test for \" << prm.label << \" ---\" << endl;\n\n  for (long i = 0; i < 5; ++i) {\n    PlainText m(prm), m1(prm);\n    m.uniform();\n\n    CipherText ct(prm);\n    encrypt(prm, ct, s, m);\n\n    if (dec_ng(prm, m1, s, ct, m)) {\n      cout << \"NG: dec\" << endl;\n      cout << \"m  = \" << m << endl;\n      cout << \"m1 = \" << m1 << endl;\n      exit(-1);\n    }\n  }\n\n  cout << \"OK: dec_test\" << endl;\n}\n\nvoid div_by_2_test (param& prm, const SKey& s) {\n  cout << \"--- div_by_2_test for \" << prm.label << \" ---\" << endl;\n\n  long test_num = 5;\n  for (long cnt = 0; cnt < test_num; ++cnt) {\n    PlainText m(prm), m1(prm), m2(prm);\n    m.uniform();\n    for (long i = 0; i < prm.rg.gR; ++i) m[i] = m[i] - (m[i] % 2);\n    for (long i = 0; i < prm.rg.gR; ++i) m2[i] = m[i]/2;\n\n    CipherText ct(prm);\n    encrypt(prm, ct, s, m);\n\n    CipherText dt(prm);\n    div_by_2(dt, ct);\n\n    ZZ v = decrypt(prm, m1, s, dt);\n    for (long i = 0; i < dt.dim; ++i) {\n      if (((m2[i] - m1[i]) % (ct.t/2)) != 0) {\n\tcout << \"NG: div_by_2\" << endl;\n\tcout << \"be: \" << VectorCopy(m2.data, 10) << endl;\n\tcout << \"is: \" << VectorCopy(m1.data, 10) << endl;\n\texit(-1);\n      }\n    }\n  }  \n\n  cout << \"OK: div_by_2_test\" << endl;\n}\n\nvoid add_test (param& prm, const SKey& s) {\n  cout << \"--- add_test for \" << prm.label << \" ---\" << endl;\n\n  long test_num = 5;\n  for (long cnt = 0; cnt < test_num; ++cnt) {\n    PlainText m1(prm), m2(prm), m3(prm), _m(prm);\n    m1.uniform();\n    m2.uniform();\n    add(m3, m1, m2);\n\n    CipherText ct1(prm), ct2(prm), ct3(prm);\n    encrypt(prm, ct1, s, m1);\n    encrypt(prm, ct2, s, m2);\n\n    add_ct(ct3, ct1, ct2);\n    if (dec_ng(prm, _m, s, ct3, m3)) {\n      cout << \"NG: add\" << endl;\n      cout << \"  be: \" << m3 << endl;\n      cout << \"  is: \" << _m << endl;\n      exit(-1);\n    }\n  }\n\n  cout << \"OK: add_test\" << endl;\n}\n\nvoid plain_add_test (param& prm, const SKey& s) {\n  cout << \"--- plain_add_test for \" << prm.label << \" ---\" << endl;\n\n  long test_num = 5;\n  for (long cnt = 0; cnt < test_num; ++cnt) {\n    PlainText m1(prm), m2(prm), m3(prm), _m(prm);\n    m1.uniform();\n    m2.uniform();\n    add(m3, m1, m2);\n\n    CipherText ct2(prm), ct3(prm);\n    encrypt(prm, ct2, s, m2);\n    \n    plain_add_ct(ct3, m1, ct2);\n    if (dec_ng(prm, _m, s, ct3, m3)) {\n      cout << \"NG: plain_add_test\" << endl;\n      cout << \"  be: \" << VectorCopy(m3.data, 10) << endl;\n      cout << \"  is: \" << VectorCopy(_m.data, 10)  << endl;\n      exit(-1);\n    }\n  }\n\n  cout << \"OK: plain_add_test\" << endl;  \n}\n\nvoid plain_mult_test (param& prm, const SKey& s) {\n  cout << \"--- plain_mult_test for \" << prm.label << \" ---\" << endl;\n\n  long test_num = 5;\n  for (long cnt = 0; cnt < test_num; ++cnt) {\n    PlainText m1(prm), m2(prm), m3(prm), _m(prm);\n    m1.uniform();\n    m2.uniform();\n    mult(m3, m1, m2);\n\n    CipherText ct2(prm), ct3(prm);\n    encrypt(prm, ct2, s, m2);\n    \n    plain_mult_ct(ct3, m1, ct2);\n    if (dec_ng(prm, _m, s, ct3, m3)) {\n      cout << \"NG: plain_mult_test\" << endl;\n      cout << \"  be: \" << m3 << endl;\n      cout << \"  is: \" << _m << endl;\n      exit(-1);\n    }\n  }\n\n  cout << \"OK: plain_mult_test\" << endl;  \n}\n\nvoid hint_gen_test (param& prm, const SKey& s) {\n  cout << \"--- hint_gen_test for \" << prm.label << \" ---\" << endl;\n  ZZ_p::init(prm.qq);\n  ZZ& sq = prm.sR;\n\n  long test_num = 1;\n  for (long cnt = 0; cnt < test_num; ++cnt) {\n    ZZ w(1);\n    for (long j = 0; j < prm.lw; ++j) {\n      cout << \"-- \" << j << \" ------\" << endl;\n      vec_ZZ_p e;\n      e.SetLength(prm.rg.gR);\n\n      // e = H[j][0] + H[j][1] s.x\n      mult(e, conv<vec_ZZ_p>(s.Hint.H[j][1]), conv<vec_ZZ_p>(s.x));\n      add(e, conv<vec_ZZ_p>(s.Hint.H[j][0]), e);\n      //prm.applyGammaInv(e, e);\n      prm.applyOmegaInv(e, e);\n\n      // f = sR s2 g^T\n      vec_ZZ_p f =  conv<ZZ_p>(w) * conv<vec_ZZ_p>(s.s2);\n      f = conv<ZZ_p>(sq) * f;\n\n      e = e - f;\n\n      vec_ZZ ee;\n      ee.SetLength(prm.rg.gR);\n      center_lift(ee, e);\n      cout << \"|e| = \" << inf_norm(ee) << endl;\n      \n      w *= prm.w;\n    }\n  }\n\n  //cout << \"OK: hint_gen_test\" << endl;\n}\n\nvoid hint_gen_test2 (param& prm, const SKey& s) {\n  cout << \"--- hint_gen_test2 for \" << prm.label << \" ---\" << endl;\n  ZZ& q0 = prm.qq;\n  ZZ& q = prm.q;\n  \n  long test_num = 1;\n  for (long cnt = 0; cnt < test_num; ++cnt) {\n    ZZ w(1);\n    for (long j = 0; j < prm.lw; ++j) {\n      cout << \"-- \" << j << \" ------\" << endl;\n\n      ZZ_p::init(q0);\n      \n      vec_ZZ_p _e;\n      _e.SetLength(prm.rg.gR);\n\n      // e = H[j][0] + H[j][1] s.x\n      mult(_e, conv<vec_ZZ_p>(s.Hint.H[j][1]), conv<vec_ZZ_p>(s.x));\n      add(_e, conv<vec_ZZ_p>(s.Hint.H[j][0]), _e);\n      //prm.applyGammaInv(_e, _e);\n      prm.applyOmegaInv(_e, _e);\n\n      vec_ZZ e;\n      e.SetLength(prm.rg.gR);\n      rescale(e, conv<vec_ZZ>(_e), q0, q);\n\n\n      ZZ_p::init(q);\n      \n      // f = s2 g^T\n      vec_ZZ_p f =  conv<ZZ_p>(w) * conv<vec_ZZ_p>(s.s2);\n\n      vec_ZZ_p e1 = conv<vec_ZZ_p>(e) - f;\n      vec_ZZ ee;\n      ee.SetLength(prm.rg.gR);\n      center_lift(ee, e1);\n      cout << \"|e| = \" << inf_norm(ee) << endl;\n      \n      w *= prm.w;\n    }\n  }\n\n  //cout << \"OK: hint_gen_test2\" << endl;\n}\n\nvoid decomp_test (param& prm) {\n  cout << \"--- decomp_test for \" << prm.label << \" ---\" << endl;\n\n  ZZ& q = prm.qq;\n  ZZ_p::init(q);\n  \n  long test_num = 5;\n  for (long cnt = 0; cnt < test_num; ++cnt) {\n    vec_ZZ c;\n    c.SetLength(prm.rg.gR);\n    for (long i = 0; i < c.length(); ++i) c[i] = RandomBnd(q);\n\n    Vec<vec_ZZ> d;\n    d.SetLength(prm.lw);\n    for (long l = 0; l < d.length(); ++l) d[l].SetLength(prm.rg.gR);\n    Decomp(prm, d, c);\n\n    vec_ZZ_p y;\n    y.SetLength(prm.rg.gR);\n    \n    ZZ w(1);\n    for (long l = 0; l < prm.lw; ++l) {\n      vec_ZZ_p dd = conv<ZZ_p>(w) * conv<vec_ZZ_p>(d[l]);\n      y += dd;\n      w *= prm.w;\n    }\n    \n    if (conv<vec_ZZ>(y) != c) {\n      cout << \"NG: decomp\" << endl;\n      cout << \"  be: \" << c[0] << endl;\n      cout << \"  is: \" << (conv<vec_ZZ>(y))[0] << endl;\n      exit(-1);\n    }\n  }\n\n  cout << \"OK: decomp_test\" << endl;\n}\n\n// Typically, sin = s2x (s2=s^2), sout = sx\n// -- H : encryption of sin\n// -- d = apply_hint(H, c)  --> d(sout) ~ sin c\nvoid hint_apply_test (param& prm, const hint Hint, const vec_ZZ& sin, const vec_ZZ& sout) {\n  cout << \"--- hint_apply_test for \" << prm.label << \" ---\" << endl;\n  long test_num = 3;\n  for (long cnt = 0; cnt < test_num; ++cnt) {\n    ZZ& q = prm.q;\n    ZZ_p::init(q);\n\n    vec_ZZ a, b, c;\n    c.SetLength(prm.rg.gR);\n    for (long i = 0; i < c.length(); ++i) c[i] = RandomBnd(q);\n    \n    apply_hint(prm, a, b, Hint, c, q);\n\n    vec_ZZ_p _a, _b, _e;\n    _e.SetLength(prm.rg.gR);\n    \n    //prm.applyGamma(_a, conv<vec_ZZ_p>(a));\n    prm.applyOmega(_a, conv<vec_ZZ_p>(a));\n    prm.applyOmega(_b, conv<vec_ZZ_p>(b));\n    mult(_e, _b, conv<vec_ZZ_p>(sout));\n    _e = _a + _e;\n\n    vec_ZZ_p _c;\n    prm.applyOmega(_c, conv<vec_ZZ_p>(c));\n    mult(_c, conv<vec_ZZ_p>(sin), _c);\n\n    _c = _c - _e;\n    //prm.applyGammaInv(_c, _c);\n    prm.applyOmegaInv(_c, _c);\n\n    center_lift(c, _c);\n    cout << \"inf_norm(noise) = \" << inf_norm(c) << endl;\n  }\n  \n  //cout << \"OK: hint_apply_test\" << endl;\n}\n\nvoid key_switch_test (param& prm, const SKey& s, const SKey& t, const hint& Hint) {\n  cout << \"--- key_switch_test for \" << prm.label << \" ---\" << endl;\n  \n  long test_num = 3;\n  for (long cnt = 0; cnt < test_num; ++cnt) {\n    PlainText m(prm), m1(prm);\n    m.uniform();\n    CipherText ct(prm);\n    encrypt(prm, ct, t, m);\n\n    // ct/t --> dt/s\n    CipherText dt(prm);\n    key_switch(dt, Hint, ct);\n   \n    if (dec_ng(prm, m1, s, dt, m)) {\n      cout << \"NG: dec\" << endl;\n      cout << \"be: \" << VectorCopy(m.data, 10) << endl;\n      cout << \"is: \" << VectorCopy(m1.data, 10) << endl;\n      exit(-1);\n    }\n  }\n  \n  cout << \"OK: key_switch_test\" << endl;\n}\n\nvoid direct_mult_test (param& prm, const SKey& s) {\n  cout << \"--- direct_mult_test for \" << prm.label << \" ---\" << endl;\n  \n  long test_num = 5;\n  for (long cnt = 0; cnt < test_num; ++cnt) {\n    PlainText m1(prm), m2(prm), m3(prm), _m(prm);\n    m1.uniform();\n    m2.uniform();\n    mult(m3, m1, m2);\n\n    CipherText ct1(prm), ct2(prm);\n    encrypt(prm, ct1, s, m1);\n    encrypt(prm, ct2, s, m2);\n\n    CipherText2 dt(prm);\n    direct_mult_ct(dt, ct1, ct2);\n\n    if (dec_ng2(prm, _m, s, dt, m3)) {\n      cout << \"NG: direct_mult_test\" << endl;\n      cout << \"  be: \" << m3 << endl;\n      cout << \"  is: \" << _m << endl;\n      exit(-1);\n    }    \n  }\n\n  cout << \"OK: direct_mult_test\" << endl;\n}\n\nvoid mult_test (param& prm, const hint& Hint, const SKey& s) {\n  cout << \"--- mult_test for \" << prm.label << \" ---\" << endl;\n  \n  long test_num = 5;\n  for (long cnt = 0; cnt < test_num; ++cnt) {\n    PlainText m1(prm), m2(prm), m3(prm), _m(prm);\n    m1.uniform();\n    m2.uniform();\n    mult(m3, m1, m2);\n\n    CipherText ct1(prm), ct2(prm);\n    encrypt(prm, ct1, s, m1);\n    encrypt(prm, ct2, s, m2);\n\n    CipherText dt(prm);\n    mult_ct(dt, Hint, ct1, ct2);\n\n    if (dec_ng(prm, _m, s, dt, m3)) {\n      cout << \"NG: mult_test\" << endl;\n      cout << \"  be: \" << VectorCopy(m3.data, 10) << endl;\n      cout << \"  is: \" << VectorCopy(_m.data, 10) << endl;\n      exit(-1);\n    }    \n  }\n\n  cout << \"OK: mult_test\" << endl;\n}\n\nvoid square_test (param& prm, const hint& Hint, const SKey& s) {\n  cout << \"--- square_test for \" << prm.label << \" ---\" << endl;\n  \n  long test_num = 5;\n  for (long cnt = 0; cnt < test_num; ++cnt) {\n    PlainText m1(prm), m3(prm), _m(prm);\n    m1.uniform();\n    mult(m3, m1, m1);\n\n    CipherText ct1(prm);\n    encrypt(prm, ct1, s, m1);\n\n    CipherText dt(prm);\n    //square_ct(dt, Hint, ct1);\n    square_ct_debug(dt, Hint, ct1, s);\n  \n    if (dec_ng(prm, _m, s, dt, m3)) {\n      cout << \"NG: square_test\" << endl;\n      cout << \"  be: \" << VectorCopy(m3.data, 10) << endl;\n      cout << \"  is: \" << VectorCopy(_m.data, 10) << endl;\n      exit(-1);\n    }    \n  }\n\n  cout << \"OK: square_test\" << endl;\n}\n\nvoid power_test (param& prm, const hint& Hint, const SKey& s, const long n) {\n  cout << \"--- power_test for \" << prm.label << \" ---\" << endl;\n  \n  long test_num = 3;\n  for (long cnt = 0; cnt < test_num; ++cnt) {\n    cout << \"[\" << cnt << \"]-----------------------\" << endl;\n    \n    Vec<PlainText> m;\n    for (long i = 0; i < n + 1; ++i) {\n      PlainText _m(prm);\n      append(m, _m);\n    }\n\n    Vec<CipherText> ct;\n    for (long i = 0; i < n + 1; ++i) {\n      CipherText _ct(prm);\n      append(ct, _ct);\n    }\n\n    m[0].uniform();\n    encrypt(prm, ct[0], s, m[0]);\n\n    PlainText _m(prm);\n    if (dec_ng(prm, _m, s, ct[0], m[0])) {\n      cout << \"NG: power_test\" << endl;\n      cout << \"  be: \" << VectorCopy(m[0].data,10) << endl;\n      cout << \"  is: \" << VectorCopy(_m.data,10) << endl;\n      exit(-1);\n    }\n\n    for (long k = 1; k < n+1; ++k) {\n      cout << \"-- \" << k << \" --------------------\" << endl;\n      mult(m[k], m[k-1], m[k-1]);\n      //cout << \"m[\" << k << \"] = \" << VectorCopy(m[k].data,10) << endl;\n\n      //square_ct_debug(ct[k], Hint, ct[k-1], s);\n      square_ct(ct[k], Hint, ct[k-1]);\n      if (dec_ng(prm, _m, s, ct[k], m[k])) {\n\tcout << \"NG: power_test\" << endl;\n\tcout << \"  be: \" << VectorCopy(m[k].data,10) << endl;\n\tcout << \"  is: \" << VectorCopy(_m.data,10) << endl;\n\texit(-1);\n      }\n    }\n  }\n\n  cout << \"OK: power_test\" << endl;\n}\n\nvoid hom_test (param& prm, const hint& Hint, const SKey& s, long L) {\n  cout << \"--- hom_test for \" << prm.label << \" --- : level = \" << L << endl;\n  \n  long test_num = 1;\n  for (long cnt = 0; cnt < test_num; ++cnt) {\n    cout << \"[\" << cnt << \"]-----------------------\" << endl;\n    \n    Vec<Vec<long>> op;\n    op.SetLength(L+1);\n    for (long j = 0; j < L + 1; ++j) op[j].SetLength(pow(2,L));\n\n    // plain computation\n    Vec<Vec<PlainText>> m;\n    for (long j = 0; j < L + 1; ++j) {\n      Vec<PlainText> _mm;\n      for (long i = 0; i < pow(2,L); ++i) {\n\tPlainText _m(prm);\n\tappend(_mm, _m);\n      }\n      append(m, _mm);\n    }\n\n    for (long i = 0; i < pow(2,L); ++i) m[0][i].uniform();\n\n    for (long j = 1; j < L + 1; ++j) {\n      for (long i = 0; i < pow(2,L-j); ++i) {\n\top[j][i] = RandomBnd(2);\n\tif (op[j][i]) add(m[j][i], m[j-1][2*i], m[j-1][2*i+1]);\n\telse mult(m[j][i], m[j-1][2*i], m[j-1][2*i+1]);\n      }\n    }\n\n    // homomorphic computation\n    Vec<Vec<CipherText>> ct;\n    for (long j = 0; j < L + 1; ++j) {\n      Vec<CipherText> _cc;\n      for (long i = 0; i < pow(2,L); ++i) {\n\tCipherText _ct(prm);\n\tappend(_cc, _ct);\n      }\n      append(ct, _cc);\n    }\n\n    for (long i = 0; i < pow(2,L); ++i) encrypt(prm, ct[0][i], s, m[0][i]);\n    \n    for (long j = 1; j < L + 1; ++j) {\n      cout << \"-- level \" << j << endl;\n      for (long i = 0; i < pow(2,L-j); ++i) {\n\tif (op[j][i]) {\n\t  cout << \"ct[\" << j-1 << \"][\" << 2*i << \"] + ct[\" << j-1 << \"][\" << 2*i+1 << \"]\" << endl;\n\t  add_ct(ct[j][i], ct[j-1][2*i], ct[j-1][2*i+1]);\n\t}\n\telse {\n\t  cout << \"ct[\" << j-1 << \"][\" << 2*i << \"] * ct[\" << j-1 << \"][\" << 2*i+1 << \"]\" << endl;\n\t  mult_ct(ct[j][i], Hint, ct[j-1][2*i], ct[j-1][2*i+1]);\n\t}\n\n\tPlainText _m(prm);\n\tif (dec_ng(prm, _m, s, ct[j][i], m[j][i])) {\n\t  cout << \"NG: hom_test\" << endl;\n\t  cout << \"  be: \" << m[j][i] << endl;\n\t  cout << \"  is: \" << _m << endl;\n\t  exit(-1);\n\t}\n      }\n    }\n  }\n  \n  cout << \"OK: hom_test\" << endl;\n}\n\nvoid she_test (param& prm) {\n  cout << \"--- she_test for \" << prm << \" ---\" << endl;\n\n  cout << \"generating a secret key...\" << flush;\n  SKey s(prm);\n  KeyGen(prm, s);\n  cout << \"done\" << endl;\n\n  encode_test(prm);\n  dec_test(prm, s);\n  \n  div_by_2_test(prm, s);\n  \n  add_test(prm, s);\n  plain_add_test(prm, s);\n\n  if (prm.level > 1) {\n    plain_mult_test(prm, s);\n  \n    hint_gen_test(prm, s);\n    hint_gen_test2(prm, s);\n    decomp_test(prm);\n\n    hint_apply_test(prm, s.Hint, s.s2x, s.x);\n  \n    SKey t(prm);\n    KeyGen(prm, t);\n\n    hint Hint;\n    Hint.hint_gen(prm, t.data, s.x);\n    hint_apply_test(prm, Hint, t.x, s.x);\n    key_switch_test(prm, s, t, Hint);\n\n    direct_mult_test(prm, s);\n    mult_test(prm, s.Hint, s);\n    square_test(prm, s.Hint, s);\n\n    //hom_test(prm, s.Hint, s, prm.level-1);\n    power_test(prm, s.Hint, s, prm.level-1);\n  }\n}\n\nvoid check_modulus_switch (param& prm, param& prm_tmp) {\n  cout << \"check_modulus_switch: \" << flush;\n\n  // the original secret key\n  SKey s(prm);\n  KeyGen(prm, s);\n\n  // the corresponding secret key in prm_tmp\n  SKey s_tmp(prm_tmp);\n  KeyGen(prm_tmp, s_tmp, s.data);  // sx = s_tmp.x\n  \n  PlainText m(prm);\n  CipherText ct(prm), dt(prm_tmp);\n\n  m.uniform();\n  encrypt(prm, ct, s, m);\n\n  modulus_switch(dt, prm_tmp, prm_tmp.q, prm, ct);\n\n  // check the result\n  PlainText _m(prm_tmp);\n  if (dec_ng(prm_tmp, _m, s_tmp, dt, m)) {\n    cout << \"NG: check_modulus_switch: \" << endl;\n    cout << \"  be: \" << VectorCopy(m.data,10) << endl;\n    cout << \"  is: \" << VectorCopy(_m.data,10) << endl;\n    exit(-1); \n  }\n  cout << \"-- OK\" << endl;\n}\n\nint main (int argc, char *argv[]) {\n  /* Do Test */\n  //long prec = 2*left_param_big.r - left_param_big.l;\n  //long prec = 2*right_param_big.r - right_param_big.l;\n  long prec = 2*composed_param_big.r - composed_param_big.l;\n  \n  // left_param.init(prec);\n  // she_test(left_param);\n\n  // left_param_tmp.init(prec);\n  // she_test(left_param_tmp);\n\n  // left_param_big.init(prec);\n  // she_test(left_param_big);\n  \n  // right_param.init(prec);\n  // she_test(right_param);\n\n  // right_param_tmp.init(prec);\n  // she_test(right_param_tmp);\n\n  // right_param_big.init(prec);\n  // she_test(right_param_big);\n\n  composed_param.init(prec);\n  she_test(composed_param);\n\n  composed_param_tmp.init(prec);\n  she_test(composed_param_tmp);\n\n  composed_param_big.init(prec);\n  she_test(composed_param_big);\n\n  check_modulus_switch(composed_param, composed_param_tmp);\n}\n", "meta": {"hexsha": "366962ecead71db7c64bdf1ebbf26e96b8d2c4d6", "size": 16434, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sheTest.cpp", "max_stars_repo_name": "aritalab/SRHE", "max_stars_repo_head_hexsha": "38161f1e62edc72a6d0afa638d057579f7005095", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sheTest.cpp", "max_issues_repo_name": "aritalab/SRHE", "max_issues_repo_head_hexsha": "38161f1e62edc72a6d0afa638d057579f7005095", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sheTest.cpp", "max_forks_repo_name": "aritalab/SRHE", "max_forks_repo_head_hexsha": "38161f1e62edc72a6d0afa638d057579f7005095", "max_forks_repo_licenses": ["Apache-2.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.937784522, "max_line_length": 91, "alphanum_fraction": 0.5060240964, "num_tokens": 5990, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527982093666, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.4723826641474846}}
{"text": "//****************************************************************************\n// (c) 2012 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#ifndef openOR_HistogramProbabilityAnalyser_hpp\n#define openOR_HistogramProbabilityAnalyser_hpp\n\n#include <openOR/Callable.hpp> //basic\n#include <openOR/DataSettable.hpp> // basic\n#include <openOR/Utility/Types.hpp> //openOR_core\n#include <openOR/Math/vector.hpp> //openOR_core\n\n#include <string>\n#include <memory>\n\n#include <openOR/Image/Image1DData.hpp>\n\n#include <boost/shared_array.hpp>\n\n#include <openOR/Defs/Image_Utility.hpp>\n\nnamespace openOR {\n\tnamespace Image {\n\n\t\t\n\t\tclass OPENOR_IMAGE_UTILITY_API HistogramProbabilityAnalyser : public Callable, public DataSettable {\n\n\t\tpublic:\n\t\t\tHistogramProbabilityAnalyser();\n\t\t\tvirtual ~HistogramProbabilityAnalyser();\n\n\t\t\tvoid operator()() const;\n\t\t\tvoid setData(const AnyPtr& data, const std::string& name = \"\");\n\t\t\tvoid setHighDensityMaterialSearch(bool b){ m_bProbabilityBasedHighDensityMaterialSearch = b; };\n\n\t\tprivate:\n\t\t\t\n\t\t\tstd::tr1::shared_ptr<Image1DData<Triple<size_t> > > m_pRegions;\n\t\t\tstd::tr1::shared_ptr<Image1DData<Quad<double> > > m_pResult;\n\t\t\tstd::tr1::shared_ptr<Image1DDataUI64> m_pHistogram;\n\t\t\tbool m_bProbabilityBasedHighDensityMaterialSearch;\n\n\t\t\t\n\t\t\tstruct HistogramProbabilityAnalyserImpl {\n\t\t\t\tHistogramProbabilityAnalyserImpl() {};\n\t\t\t\t~HistogramProbabilityAnalyserImpl() {};\n\n\t\t\t\tstd::vector <Math::Vector4d> getSplittedNormalDistributions(boost::shared_array<long long> Histogram, uint nHistogramDataSize,std::vector<Math::Vector3ui>& vecDensityIntervals,bool bProbabilityBasedHighDensityMaterialSearch = true,bool bLog10Normalization=false,uint nNumOfRefinements = 0);\n\n\t\t\tprivate:\n\n\t\t\t\tMath::Vector4d getSplittedNormalDistributionOfAHistogram(boost::shared_array<long long> vecData, uint m_nHistogramDataSize, uint nBeginIndex, uint nEndIndex, uint nPeak,bool bLog10Normalization);\n\t\t\t\tMath::Vector4d refineSplittedNormalDistributionOfAHistogram(boost::shared_array<long long> vecData,boost::shared_array<long long> vecDummyData,uint nHistogramDataSize, Math::Vector4d vecPre,Math::Vector4d vecCurrent,Math::Vector4d vecPost,bool bLog10Normalization);\n\t\t\t\tMath::Vector4d probabilityBasedHighDensityMaterialSearch(boost::shared_array<long long> pHistogram, uint nHistogramDataSize, uint nLeftBorder, uint nRightBorder, uint nPeak,bool bLog10Normalization,std::vector<Math::Vector3ui>& vecDensityIntervals,Math::Vector4d& vecCurrentLastMaterial);\n\t\t\t\tdouble computeNormalDistributedProbability(double mean,double stddev,double x);\n\t\t\t\tMath::Vector2d getNormalDistributionOfAHistogram(std::vector<long long>& vecData,bool bLog10Normalization);\n\t\t\t};\n\t\t};\n\t}\n}\n#endif //openOR_HistogramAnalyser_hpp", "meta": {"hexsha": "14fe9d837856dabc7a94c1e8dc5b316ed3f99e97", "size": 3055, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/plugins/Image/Utility/include/openOR/Image/HistogramProbabilityAnalyser.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/plugins/Image/Utility/include/openOR/Image/HistogramProbabilityAnalyser.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/plugins/Image/Utility/include/openOR/Image/HistogramProbabilityAnalyser.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": 46.2878787879, "max_line_length": 294, "alphanum_fraction": 0.7342062193, "num_tokens": 709, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.4723364975520795}}
{"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_RECTIFICATION_HPP\n#define PIC_COMPUTER_VISION_RECTIFICATION_HPP\n\n#include <vector>\n#include <cmath>\n#include <stdlib.h>\n\n#include \"../base.hpp\"\n\n#include \"../image.hpp\"\n\n#include \"../image_vec.hpp\"\n\n#include \"../filtering/filter_warp_2d.hpp\"\n#include \"../filtering/filter_rotation.hpp\"\n\n#include \"../computer_vision/camera_matrix.hpp\"\n\n#include \"../util/eigen_util.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 computeImageRectificationWarp\n * @param img0 is the first image to rectify\n * @param img1 is the second image to rectify\n * @param T0 is the homography for img0\n * @param T1 is the homography for img0\n * @param out is the output as an ImageVec with two images; i.e., rectified versions of img0 and img1\n * @return\n */\nPIC_INLINE ImageVec *computeImageRectificationWarp(Image *img0,\n                                                   Image *img1,\n                                                   Eigen::Matrix3d &T0,\n                                                   Eigen::Matrix3d &T1,\n                                                   ImageVec *out,\n                                                   bool bPartial = true)\n{\n    if(img0 == NULL || img1 == NULL) {\n        return out;\n    }\n\n    if(out == NULL) {\n        out = new ImageVec();\n    }\n\n    auto H0 = MatrixConvert(T0);\n    auto H1 = MatrixConvert(T1);\n    FilterWarp2D warp0(H0);\n    FilterWarp2D warp1(H1);\n\n    int bmin0[2], bmin1[2], bmax0[2], bmax1[2];\n\n    FilterWarp2D::computeBoundingBox(H0, warp0.getBCentroid(), img0->widthf, img0->heightf, bmin0, bmax0);\n    FilterWarp2D::computeBoundingBox(H1, warp1.getBCentroid(), img1->widthf, img1->heightf, bmin1, bmax1);\n\n    if(bPartial) {\n        bmin0[1] = MIN(bmin0[1], bmin1[1]);\n        bmax0[1] = MAX(bmax0[1], bmax1[1]);\n\n        bmin1[1] = bmin0[1];\n        bmax1[1] = bmax0[1];\n    } else {\n        for(int i = 0; i < 2; i++) {\n            bmin0[i] = MIN(bmin0[i], bmin1[i]);\n            bmin1[i] = bmin0[i];\n\n            bmax0[i] = MAX(bmax0[i], bmax1[i]);\n            bmax1[i] = bmax0[i];\n        }\n    }\n\n    warp0.setBoundingBox(bmin0, bmax0);\n    warp1.setBoundingBox(bmin1, bmax1);\n\n    Image *img0_r = NULL;\n    Image *img1_r = NULL;\n\n    bool bTest = out->size() == 2;\n    if(bTest) {\n        img0_r = out->at(0);\n        img1_r = out->at(1);\n    }\n\n    img0_r = warp0.Process(Single(img0), img0_r);\n    img1_r = warp1.Process(Single(img1), img1_r);\n\n    if(!bTest) {\n        out->push_back(img0_r);\n        out->push_back(img1_r);\n    }\n\n    return out;\n}\n\n/**\n * @brief computeImageRectification this function rectifies two images\n * @param img0 is the first image to rectify\n * @param img1 is the second image to rectify\n * @param M0 is the camera matrix (3x4) of img0\n * @param M1 is the camera matrix (3x4) of img1\n * @param out is the output as an ImageVec with two images; i.e., rectified versions of img0 and img1\n * @return is the output as an ImageVec with two images; i.e., rectified versions of img0 and img1\n\n */\nPIC_INLINE ImageVec *computeImageRectification(Image *img0,\n                                               Image *img1,\n                                               Eigen::Matrix34d &M0,\n                                               Eigen::Matrix34d &M1,\n                                               ImageVec *out = NULL,\n                                               bool bPartial = true)\n{\n    //NOTE: we should check that img0 and img1 are valid...\n    if(img0 == NULL || img1 == NULL) {\n        return out;\n    }\n\n    if(out == NULL) {\n        out = new ImageVec();\n    }\n\n    Eigen::Matrix34d M0_r, M1_r;\n    Eigen::Matrix3d T0, T1;\n\n    cameraRectify(M0, M1, M0_r, M1_r, T0, T1);\n\n    //check if the trasform is correct!\n    Eigen::Vector3d corners[4], corners_T0[4];\n    corners[0] = Eigen::Vector3d(0.0, 0.0, 1.0);\n    corners[1] = Eigen::Vector3d(img0->widthf, 0.0, 1.0);\n    corners[2] = Eigen::Vector3d(img0->widthf, img0->heightf, 1.0);\n    corners[3] = Eigen::Vector3d(img0->heightf, 0.0, 1.0);\n\n    for(int i = 0; i < 4; i ++) {\n        corners_T0[i] = T0 * corners[i];\n        corners_T0[i] /= corners_T0[i][2];\n    }\n\n    auto d_c   = corners[2] - corners[0];\n    auto d_c_T0 = corners_T0[2] - corners_T0[0];\n\n    bool b_x = std::signbit(d_c[0]) == std::signbit(d_c_T0[0]);\n    bool b_y = std::signbit(d_c[1]) == std::signbit(d_c_T0[1]);\n\n    double f_x = b_x ? 1.0 : -1.0;\n    double f_y = b_y ? 1.0 : -1.0;\n\n\n    auto H = DiagonalMatrix(Eigen::Vector3d(f_x, f_y, 1));\n    T0 = H * T0;\n    T1 = H * T1;\n\n    out = computeImageRectificationWarp(img0, img1, T0, T1, out, bPartial);\n\n    return out;\n}\n\n/**\n * @brief computeImageRectification this function rectifies two images\n * @param img0 is the first image to rectify\n * @param img1 is the second image to rectify\n * @param K0 is the intrisic matrix of img0\n * @param R0 is the rotation matrix of img0\n * @param t0 is the translation vector of img0\n * @param K1 is the intrisic matrix of im1\n * @param R1 is the rotation matrix of img1\n * @param t1 is the translation vector of img1\n * @param out is the output as an ImageVec with two images; i.e., rectified versions of img0 and img1\n * @return is the output as an ImageVec with two images; i.e., rectified versions of img0 and img1\n */\nPIC_INLINE ImageVec *computeImageRectification(Image *img0,\n                                               Image *img1,\n                                               Eigen::Matrix3d &K0,\n                                               Eigen::Matrix3d &R0,\n                                               Eigen::Vector3d &t0,\n                                               Eigen::Matrix3d &K1,\n                                               Eigen::Matrix3d &R1,\n                                               Eigen::Vector3d &t1,\n                                               ImageVec *out = NULL,\n                                               bool bPartial = true)\n{\n    //NOTE: we should check that img0 and img1 are valid...\n    if(img0 == NULL || img1 == NULL) {\n        return out;\n    }\n\n    if(out == NULL) {\n        out = new ImageVec();\n    }\n\n    Eigen::Matrix34d M0_r, M1_r;\n    Eigen::Matrix3d T0, T1;\n\n    cameraRectify(K0, R0, t0, K1, R1, t1, M0_r, M1_r, T0, T1);\n\n    out = computeImageRectificationWarp(img0, img1, T0, T1, out, bPartial);\n\n    return out;\n}\n\n/**\n * @brief alignPanoramicLL\n * @param R0\n * @param t0\n * @param R1\n * @param t1\n * @param R01\n * @param t01\n */\nPIC_INLINE void alignPanoramicLL(Eigen::Matrix3d &R0, Eigen::Vector3d &t0,\n                                 Eigen::Matrix3d &R1, Eigen::Vector3d &t1,\n                                 Eigen::Matrix3d &R01, Eigen::Vector3d &t01)\n{\n    t01 = t1 - t0;\n    Eigen::Matrix3d R0_t = Eigen::Transpose< Eigen::Matrix3d >(R0);\n\n    //R0 --> I\n    //t0 --> 0\n\n    R01 = R0_t * R1;\n    t01 = R0_t * t01;\n}\n\n/**\n * @brief computeImageRectificationPanoramicLL\n * @param img0\n * @param img1\n * @param R01\n * @param t01\n * @param out\n * @return\n */\nPIC_INLINE ImageVec *computeImageRectificationPanoramicLL(\n                                               Image *img0,\n                                               Image *img1,\n                                               Eigen::Matrix3d &R01,\n                                               Eigen::Vector3d &t01,\n                                               ImageVec *out = NULL)\n{\n    //NOTE: we should check that img0 and img1 are valid...\n    if(img0 == NULL || img1 == NULL) {\n        return out;\n    }\n\n    if(out == NULL) {\n        out = new ImageVec();\n    }\n\n    //rotation 1\n    Eigen::Matrix3d R01_t = Eigen::Transpose< Eigen::Matrix3d >(R01);\n\n    //rotation 2\n    Eigen::Vector3d X(0.0, 1.0, 0.0);\n    Eigen::Vector3d n;\n    n = t01.cross(X);\n    n.normalize();\n\n    double alpha = std::acos(t01.dot(X));\n    Eigen::Matrix3d rot, rotation1;\n\n    rot = Eigen::AngleAxisd(alpha, n);\n    rotation1 = rot * R01_t;\n\n    Eigen::Matrix3f rotation0f, rotation1f;\n    rotation0f = rot.cast<float>();\n    rotation1f = rotation1.cast<float>();\n\n    out->push_back(FilterRotation::execute(img0, NULL, rotation0f));\n    out->push_back(FilterRotation::execute(img1, NULL, rotation1f));\n    return out;\n}\n\n#endif // PIC_DISABLE_EIGEN\n\n} // end namespace pic\n\n#endif // PIC_COMPUTER_VISION_RECTIFICATION_HPP\n", "meta": {"hexsha": "cacf682457d97e875502b760576293d495481fa9", "size": 8991, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/computer_vision/rectification.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/rectification.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/rectification.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": 28.9099678457, "max_line_length": 106, "alphanum_fraction": 0.5571126682, "num_tokens": 2578, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4723364975520794}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2015 NumScale SAS\n  @copyright 2015 J.T. Lapreste\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_COMMON_GENERIC_FUNCTION_MEANOF_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_GENERIC_FUNCTION_MEANOF_HPP_INCLUDED\n\n#include <boost/simd/constant/half.hpp>\n#include <boost/simd/function/average.hpp>\n#include <boost/simd/function/bitwise_and.hpp>\n#include <boost/simd/function/bitwise_xor.hpp>\n#include <boost/simd/function/if_else.hpp>\n#include <boost/simd/function/is_finite.hpp>\n#include <boost/simd/function/logical_and.hpp>\n#include <boost/simd/function/max.hpp>\n#include <boost/simd/function/min.hpp>\n#include <boost/simd/function/minus.hpp>\n#include <boost/simd/function/plus.hpp>\n#include <boost/simd/function/shift_right.hpp>\n#include <boost/dispatch/function/overload.hpp>\n#include <boost/config.hpp>\n//no overflow average for floating numbers\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  BOOST_DISPATCH_OVERLOAD ( meanof_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::generic_< bd::floating_<A0> >\n                          , bd::generic_< bd::floating_<A0> >\n                          )\n  {\n    using result_type = A0;\n    BOOST_FORCEINLINE A0 operator() ( A0 const& a0, A0 const& a1) const BOOST_NOEXCEPT\n    {\n      A0 m = min(a0, a1);\n      return if_else( bitwise_and(is_finite(a0), is_finite(a1)),//is_finite(a0) && is_finite(a1),\n                      m + (max(a0, a1)-m)*Half<result_type>(),\n                      average(a0, a1)\n                    );\n    }\n  };\n  BOOST_DISPATCH_OVERLOAD ( meanof_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::generic_< bd::integer_<A0> >\n                          , bd::generic_< bd::integer_<A0> >\n                          )\n  {\n    using result_type = A0;\n    BOOST_FORCEINLINE A0 operator() ( A0 const& a0, A0 const& a1) const BOOST_NOEXCEPT\n    {\n      return (a0 & a1) + ((a0 ^ a1) >> 1);\n    }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "8a58c98d7e6f6703fd57a88a5810f74c5793ed03", "size": 2394, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arch/common/generic/function/meanof.hpp", "max_stars_repo_name": "yaeldarmon/boost.simd", "max_stars_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/simd/arch/common/generic/function/meanof.hpp", "max_issues_repo_name": "yaeldarmon/boost.simd", "max_issues_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/arch/common/generic/function/meanof.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": 35.2058823529, "max_line_length": 100, "alphanum_fraction": 0.5588972431, "num_tokens": 557, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4723364975520794}}
{"text": "//==================================================================================================\n/*!\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#include <boost/simd/function/scalar/div.hpp>\n#include <scalar_test.hpp>\n#include <boost/simd/detail/dispatch/meta/as_integer.hpp>\n#include <boost/simd/constant/inf.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/zero.hpp>\n\nSTF_CASE_TPL (\" div real\",  STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  using bs::div;\n  using r_t = decltype(div(bs::nearbyint, T(), T()));\n\n  STF_IEEE_EQUAL(div(bs::nearbyint, bs::Inf<T>(), bs::Inf<T>()), bs::Nan<r_t>());\n  STF_IEEE_EQUAL(div(bs::nearbyint, bs::Minf<T>(), bs::Minf<T>()), bs::Nan<r_t>());\n  STF_EQUAL(div(bs::nearbyint, bs::Mone<T>(), bs::Mone<T>()), bs::One<r_t>());\n  STF_IEEE_EQUAL(div(bs::nearbyint, bs::Nan<T>(), bs::Nan<T>()), bs::Nan<r_t>());\n  STF_EQUAL(div(bs::nearbyint, bs::One<T>(), bs::One<T>()), bs::One<r_t>());\n} // end of test for floating_\n\nSTF_CASE_TPL (\" div unsigned_int\",  STF_UNSIGNED_INTEGRAL_TYPES)\n{\n  namespace bs = boost::simd;\n\n  using bs::div;\n  using r_t = decltype(div(bs::nearbyint, T(), T()));\n\n  STF_EQUAL(div(bs::nearbyint, bs::One<T>(), bs::One<T>()), bs::One<r_t>());\n  STF_EQUAL(div(bs::nearbyint, T(5), T(2)), T(2));\n  STF_EQUAL(div(bs::nearbyint, T(7), T(2)), T(4));\n  STF_EQUAL(div(bs::nearbyint, T(9), T(3)), T(3));\n  STF_EQUAL(div(bs::nearbyint, T(10), T(3)), T(3));\n  STF_EQUAL(div(bs::nearbyint, T(11), T(3)), T(4));\n  STF_EQUAL(div(bs::nearbyint, T(12), T(3)), T(4));\n  STF_EQUAL(div(bs::nearbyint, T(18), T(6)), T(3));\n  STF_EQUAL(div(bs::nearbyint, T(20), T(6)), T(3));\n  STF_EQUAL(div(bs::nearbyint, T(22), T(6)), T(4));\n  STF_EQUAL(div(bs::nearbyint, T(24), T(6)), T(4));\n  STF_EQUAL(div(bs::nearbyint, bs::Valmax<T>(),bs::Two<T>()), bs::Valmax<T>()/bs::Two<T>()+bs::One<T>());\n\n} // end of test for unsigned_int_\n\nSTF_CASE_TPL (\" div signed_int\", STF_SIGNED_INTEGRAL_TYPES)\n{\n  namespace bs = boost::simd;\n  using bs::div;\n  using r_t = decltype(div(T(), T()));\n\n  STF_EQUAL(div(bs::nearbyint, bs::Mone<T>(), bs::Mone<T>()), bs::One<r_t>());\n  STF_EQUAL(div(bs::nearbyint, bs::One<T>(), bs::One<T>()), bs::One<r_t>());\n  STF_EQUAL(div(bs::nearbyint, T(5), T(2)), T(2));\n  STF_EQUAL(div(bs::nearbyint, T(7), T(2)), T(4));\n  STF_EQUAL(div(bs::nearbyint, T(-5), T(2)), T(-2));\n  STF_EQUAL(div(bs::nearbyint, T(-7), T(2)), T(-4));\n  STF_EQUAL(div(bs::nearbyint, T(-4),T(0)), bs::Valmin<r_t>());\n  STF_EQUAL(div(bs::nearbyint, T(4),T(0)), bs::Valmax<r_t>());\n  STF_EQUAL(div(bs::nearbyint, T(4),T(3)), T(1));\n  STF_EQUAL(div(bs::nearbyint, T(-4),T(-3)), T(1));\n  STF_EQUAL(div(bs::nearbyint, T(4),T(-3)), T(-1));\n  STF_EQUAL(div(bs::nearbyint, T(-4),T(3)), T(-1));\n  STF_EQUAL(div(bs::nearbyint, T(5),T(3)), T(2));\n  STF_EQUAL(div(bs::nearbyint, T(-5),T(-3)), T(2));\n  STF_EQUAL(div(bs::nearbyint, T(5),T(-3)), T(-2));\n  STF_EQUAL(div(bs::nearbyint, T(-5),T(3)), T(-2));\n\n  STF_EQUAL(div(bs::nearbyint, T(5),T(4)), T(1));\n  STF_EQUAL(div(bs::nearbyint, T(-5),T(-4)), T(1));\n  STF_EQUAL(div(bs::nearbyint, T(5),T(-4)), T(-1));\n  STF_EQUAL(div(bs::nearbyint, T(-5),T(4)), T(-1));\n  STF_EQUAL(div(bs::nearbyint, T(6),T(4)), T(2));\n  STF_EQUAL(div(bs::nearbyint, T(-6),T(-4)), T(2));\n  STF_EQUAL(div(bs::nearbyint, T(6),T(-4)), T(-2));\n  STF_EQUAL(div(bs::nearbyint, T(-6),T(4)), T(-2));\n  STF_EQUAL(div(bs::nearbyint, T(8),T(4)), T(2));\n  STF_EQUAL(div(bs::nearbyint, T(-8),T(-4)), T(2));\n  STF_EQUAL(div(bs::nearbyint, T(8),T(-4)), T(-2));\n  STF_EQUAL(div(bs::nearbyint, T(-8),T(4)), T(-2));\n  STF_EQUAL(div(bs::nearbyint, T(9),T(4)), T(2));\n  STF_EQUAL(div(bs::nearbyint, T(-9),T(-4)), T(2));\n  STF_EQUAL(div(bs::nearbyint, T(9),T(-4)), T(-2));\n  STF_EQUAL(div(bs::nearbyint, T(-9),T(4)), T(-2));\n  STF_EQUAL(div(bs::nearbyint, T(10),T(4)), T(2));\n  STF_EQUAL(div(bs::nearbyint, T(-10),T(-4)), T(2));\n  STF_EQUAL(div(bs::nearbyint, T(10),T(-4)), T(-2));\n  STF_EQUAL(div(bs::nearbyint, T(-10),T(4)), T(-2));\n\n} // end of test for signed_int_\n\n", "meta": {"hexsha": "9c8c386de1439507c1c92c85f05e0cb419361be7", "size": 4365, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/scalar/div/div.nearbyint.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": "test/function/scalar/div/div.nearbyint.cpp", "max_issues_repo_name": "remymuller/boost.simd", "max_issues_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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/function/scalar/div/div.nearbyint.cpp", "max_forks_repo_name": "remymuller/boost.simd", "max_forks_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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": 43.2178217822, "max_line_length": 105, "alphanum_fraction": 0.5798396334, "num_tokens": 1619, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4723364975520794}}
{"text": "//\n//  IntervalChecks.h\n//  YRoots\n//\n//  Created by Erik Hales Parkinson on 7/7/20.\n//  Copyright \u00a9 2020 Erik Hales Parkinson. All rights reserved.\n//\n\n#ifndef IntervalChecker_h\n#define IntervalChecker_h\n\n#include \"Approximation/ChebyshevApproximation.hpp\"\n#include \"SolutionTracking/IntervalTracker.hpp\"\n#include \"Utilities/MultiPool.hpp\"\n#include \"Utilities/ConcurrentStack.hpp\"\n#include \"Utilities/Timer.hpp\"\n#include \"Utilities/utilities.hpp\"\n#include \"IntervalChecking/IntervalBounder.hpp\"\n#include <Eigen/Dense>\n\nenum EvalSign {\n    //If we & to signs together as a bool, we get true if we can throw out an interval\n    Zero = 0,\n    Positive = 1,\n    Negative = 2\n};\n\ntemplate <int Rank>\nclass IntervalChecker {\npublic:\n    IntervalChecker(size_t _rank, IntervalTracker& _intervalTracker, size_t _threadNum, ConcurrentStack<SolveParameters>& _intervalsToRun, ObjectPool<SolveParameters>&        _solveParametersPool);\n    \n    bool runIntervalChecks(ChebyshevApproximation<Rank>& _approximation, Interval& _currentInterval);\n    void runSubintervalChecks(std::vector<ChebyshevApproximation<Rank> >& _chebyshevApproximations, SolveParameters* _currentParameters, size_t _numGoodApproximations);\n    \nprotected:\n    bool runConstantTermCheck(ChebyshevApproximation<Rank>& _approximation);\n    void runQuadraticCheck(ChebyshevApproximation<Rank>& _approximation);\n    void pushIntervalToSolve(SolveParameters* _currentParameters, const Interval& _newInterval);\n    \n    inline EvalSign getEvalSign(double _eval, double _error) {\n        if(_eval > _error) {\n            return EvalSign::Positive;\n        }\n        else if (_eval < -_error) {\n            return EvalSign::Negative;\n        }\n        else {\n            return EvalSign::Zero;\n        }\n    }\n\nprotected:\n    size_t                  m_rank;\n    IntervalTracker&        m_intervalTracker;\n    static constexpr double m_randomIntervalDivider = 0.5139303900908738;\n    std::vector<Interval>   m_scaledSubIntervals;\n    std::vector<bool>       m_intervalMask;\n    std::vector<bool>       m_throwOutMask;\n    Interval                m_tempInterval;\n    std::vector<bool>       m_allowedToReduceDimension;\n\n    //Multithreading objects\n    size_t                              m_threadNum;\n    ConcurrentStack<SolveParameters>&   m_intervalsToRun;\n    ObjectPool<SolveParameters>&        m_solveParametersPool;\n    \n    //For Bounding Intervals\n    IntervalBounder<Rank>               m_intervalBounder;\n    \n    //For Timing\n    static size_t           m_timerBoundingIntervalIndex;\n    static size_t           m_timerQuadraticCheckIndex;\n    Timer&                  m_timer = Timer::getInstance();\n};\n\ntemplate<int Rank>\nsize_t IntervalChecker<Rank>::m_timerBoundingIntervalIndex = -1;\ntemplate<int Rank>\nsize_t IntervalChecker<Rank>::m_timerQuadraticCheckIndex = -1;\n\n#include \"BoundingIntervalUtilities.hpp\"\n#include \"IntervalChecker1D.ipp\"\n#include \"IntervalChecker2D.ipp\"\n#include \"IntervalChecker3D.ipp\"\n#include \"IntervalCheckerND.ipp\"\n\n#endif /* IntervalChecker_h */\n", "meta": {"hexsha": "20adf5870214c9d0e4fb245c8be60e6539a2765a", "size": 3039, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "YRoots/include/IntervalChecking/IntervalChecker.hpp", "max_stars_repo_name": "erikhparkinson/YRoots", "max_stars_repo_head_hexsha": "7907a7245ac37b38a06bc5cc94ad26c7cf5e5905", "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": "YRoots/include/IntervalChecking/IntervalChecker.hpp", "max_issues_repo_name": "erikhparkinson/YRoots", "max_issues_repo_head_hexsha": "7907a7245ac37b38a06bc5cc94ad26c7cf5e5905", "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": "YRoots/include/IntervalChecking/IntervalChecker.hpp", "max_forks_repo_name": "erikhparkinson/YRoots", "max_forks_repo_head_hexsha": "7907a7245ac37b38a06bc5cc94ad26c7cf5e5905", "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": 34.1460674157, "max_line_length": 197, "alphanum_fraction": 0.7110891741, "num_tokens": 718, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568417, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4723364912823023}}
{"text": "#include <iostream>\n#include <typeinfo>\r\n#define BOOST_TEST_MODULE MixedMIAAssignTests\n#include \"MIAConfig.h\"\r\n#ifdef MIA_USE_HEADER_ONLY_TESTS\r\n#include <boost/test/included/unit_test.hpp>\r\n#else\r\n#include <boost/test/unit_test.hpp>\r\n#endif\r\n\n#include \"SparseMIA.h\"\r\n#include \"DenseMIA.h\"\n#include \"Index.h\"\n\n\n\n\n\r\ntemplate<class _data_type>\r\nvoid mult_work(size_t dim1, size_t dim2){\r\n\r\n    LibMIA::MIAINDEX i;\n    LibMIA::MIAINDEX j;\n    LibMIA::MIAINDEX k;\r\n    LibMIA::MIAINDEX l;\r\n\n\n    LibMIA::DenseMIA<_data_type,4> original_dense_a(dim1,dim2,dim1,dim2);\r\n    original_dense_a.randu(0,10);\r\n    for(auto it=original_dense_a.data_begin();it<original_dense_a.data_end();++it){\r\n        if(*it<7)\r\n            *it=0;\r\n    }\r\n    LibMIA::DenseMIA<_data_type,4> dense_a=original_dense_a;\r\n    LibMIA::DenseMIA<_data_type,4> dense_temp;\r\n    LibMIA::SparseMIA<_data_type,4> original_sparse_a(dim1,dim2,dim1,dim2);\r\n    LibMIA::SparseMIA<_data_type,4> sparse_a;\r\n    LibMIA::SparseMIA<_data_type,4> sparse_temp;\r\n    original_sparse_a.resize(original_sparse_a.dimensionality()/2);\r\n\r\n    original_sparse_a.randu(-50,50);\r\n    original_sparse_a.rand_indices();\r\n    original_sparse_a.collect_duplicates();\r\n\r\n\r\n    sparse_a=original_dense_a;\r\n\r\n    BOOST_CHECK_MESSAGE(sparse_a==original_dense_a,std::string(\"Straight dense to sparse assign for \")+typeid(_data_type).name());\r\n\r\n\r\n    sparse_a=original_sparse_a;\r\n    dense_a=sparse_a;\r\n    //sparse_a.print();\r\n    //dense_a.print();\r\n    BOOST_CHECK_MESSAGE(sparse_a==dense_a,std::string(\"Straight sparse to dense assign for \")+typeid(_data_type).name());\r\n\r\n\r\n    //now try with indices\r\n    sparse_a(i,j,k,l)=original_dense_a(i,j,k,l);\r\n\r\n    BOOST_CHECK_MESSAGE(sparse_a==original_dense_a,std::string(\"Straight dense to sparse assign with indices for \")+typeid(_data_type).name());\r\n\r\n\r\n    sparse_a=original_sparse_a;\r\n    dense_a(i,j,k,l)=sparse_a(i,j,k,l);\r\n\r\n    BOOST_CHECK_MESSAGE(sparse_a==dense_a,std::string(\"Straight sparse to dense assign with indices for \")+typeid(_data_type).name());\r\n\r\n    sparse_temp(i,j,k,l)=original_dense_a(k,j,l,i);\r\n    sparse_a(k,j,l,i)=sparse_temp(i,j,k,l);\r\n\r\n\r\n    BOOST_CHECK_MESSAGE(sparse_a==original_dense_a,std::string(\"Dense to sparse assign with shuffled indices for \")+typeid(_data_type).name());\r\n\r\n    dense_temp(i,j,k,l)=original_sparse_a(k,j,l,i);\r\n    dense_a(k,j,l,i)=dense_temp(i,j,k,l);\r\n//    original_sparse_a.print();\r\n//    dense_a.print();\r\n\r\n    BOOST_CHECK_MESSAGE(dense_a==original_sparse_a,std::string(\"Sparse to dense assign with shuffled indices for \")+typeid(_data_type).name());\r\n\r\n\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE( MixedMIAAssignTests )\n{\n\n    //mult_work<double>(3,3);\n    //mult_work<float>(3,3);\r\n    //mult_work<int>(3,3);\r\n    //mult_work<long>(3,3);\r\n//\r\n//\r\n\r\n\r\n    mult_work<double>(8,5);\n    mult_work<float>(8,5);\r\n    mult_work<int>(8,5);\r\n    mult_work<long>(8,5);\r\n//\r\n//\r\n//\r\n//    mult_work<double>(5,8);\n//    mult_work<float>(5,8);\r\n//    mult_work<int>(5,8);\r\n//    mult_work<long>(5,8);\r\n\n\n}\n", "meta": {"hexsha": "f069708955d763e524ef503b9f5e7c94c0930dfb", "size": 3032, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tests/MIA/mixed_mia_assign_test.cpp", "max_stars_repo_name": "extragoya/LibNT", "max_stars_repo_head_hexsha": "60372bf4e3c5d6665185358c4756da4fe547f093", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-26T05:11:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-26T05:11:32.000Z", "max_issues_repo_path": "src/tests/MIA/mixed_mia_assign_test.cpp", "max_issues_repo_name": "extragoya/LibNT", "max_issues_repo_head_hexsha": "60372bf4e3c5d6665185358c4756da4fe547f093", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/MIA/mixed_mia_assign_test.cpp", "max_forks_repo_name": "extragoya/LibNT", "max_forks_repo_head_hexsha": "60372bf4e3c5d6665185358c4756da4fe547f093", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-09-21T15:38:23.000Z", "max_forks_repo_forks_event_max_datetime": "2017-09-21T15:38:23.000Z", "avg_line_length": 27.5636363636, "max_line_length": 144, "alphanum_fraction": 0.6823878628, "num_tokens": 836, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300698514777, "lm_q2_score": 0.6723316991792861, "lm_q1q2_score": 0.4723332355877866}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n#include <cmath>\n\n\n/**\n * @brief shift zero frequency component to the center of the spectrum\n *\n * @param dst\n * @param src\n * @param dim (default both directions), 0: shift along rows, 1: shift along\n * columns\n */\ntemplate <typename DERIVED1, typename DERIVED2>\ninline void\nfftshift(Eigen::DenseBase<DERIVED1> &dst, const Eigen::DenseBase<DERIVED2> &src, int dim = -1)\n{\n  // nx, ny: position of the smallest negative frequency\n  unsigned int nx = std::ceil(src.cols() / 2.);\n  unsigned int ny = std::ceil(src.rows() / 2.);\n\n  unsigned int Nx = src.cols();\n  unsigned int Ny = src.rows();\n\n  assert(dst.rows() == src.rows() && dst.cols() == src.cols());\n\n  if (dim == -1 && dst.cols() > 1 && dst.rows() > 1) {\n    // diagonal blocks\n    dst.block(0, 0, Ny - ny, Nx - nx) = src.bottomRightCorner(Ny - ny, Nx - nx);\n    dst.bottomRightCorner(ny, nx) = src.block(0, 0, ny, nx);\n\n    // off-diagonal blocks\n    dst.topRightCorner(Ny - ny, nx) = src.bottomLeftCorner(Ny - ny, nx);\n    dst.bottomLeftCorner(ny, Nx - nx) = src.topRightCorner(ny, Nx - nx);\n  } else if (dim == 0) {\n    assert(Ny > 1);\n    /*  shift along rows  */\n    // 2d, shift along rows (y-dim)\n    dst.topRows(Ny - ny) = src.bottomRows(Ny - ny);\n    dst.bottomRows(ny) = src.topRows(ny);\n  } else if (dim == 1) {\n    assert(Nx > 1);\n    /* shift along columns  */\n    // 2d, shift along columns (x-dim)\n    // negative frequencies\n    dst.leftCols(Nx - nx) = src.rightCols(Nx - nx);\n    // positive frequencies\n    dst.rightCols(nx) = src.leftCols(nx);\n  } else {\n    assert(false);\n  }\n}\n\n/**\n * @brief undoes the effect of fftshift\n *\n * @param dst\n * @param src\n * @param dim\n */\ntemplate <typename DERIVED1, typename DERIVED2>\ninline void\nifftshift(Eigen::DenseBase<DERIVED1> &dst, const Eigen::DenseBase<DERIVED2> &src, int dim = -1)\n{\n  // nx, ny: position of the smallest negative frequency\n  unsigned int nx = std::floor(src.cols() / 2.);\n  unsigned int ny = std::floor(src.rows() / 2.);\n\n  unsigned int Nx = src.cols();\n  unsigned int Ny = src.rows();\n\n  assert(dst.rows() == src.rows() && dst.cols() == src.cols());\n\n  if (dim == -1 && dst.cols() > 1 && dst.rows() > 1) {\n    // diagonal blocks\n    dst.block(0, 0, Ny - ny, Nx - nx) = src.bottomRightCorner(Ny - ny, Nx - nx);\n    dst.bottomRightCorner(ny, nx) = src.block(0, 0, ny, nx);\n\n    // off-diagonal blocks\n    dst.topRightCorner(Ny - ny, nx) = src.bottomLeftCorner(Ny - ny, nx);\n    dst.bottomLeftCorner(ny, Nx - nx) = src.topRightCorner(ny, Nx - nx);\n  } else if (dim == 0) {\n    // 2d, shift along rows (y-dim)\n    dst.topRows(Ny - ny) = src.bottomRows(Ny - ny);\n    dst.bottomRows(ny) = src.topRows(ny);\n  } else if (dim == 1) {\n    // 2d, shift along columns (x-dim)\n    // negative frequencies\n    dst.leftCols(Nx - nx) = src.rightCols(Nx - nx);\n    // positive frequencies\n    dst.rightCols(nx) = src.leftCols(nx);\n  }\n}\n", "meta": {"hexsha": "e971e8bbadd12412536911087bd3086663c20aba", "size": 2901, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "fft/shift.hpp", "max_stars_repo_name": "simonpp/2dRidgeletBTE", "max_stars_repo_head_hexsha": "5d08cbb5c57fc276c7a528f128615d23c37ef6a0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-08T03:15:56.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-08T03:15:56.000Z", "max_issues_repo_path": "fft/shift.hpp", "max_issues_repo_name": "simonpp/2dRidgeletBTE", "max_issues_repo_head_hexsha": "5d08cbb5c57fc276c7a528f128615d23c37ef6a0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fft/shift.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.5368421053, "max_line_length": 95, "alphanum_fraction": 0.6128921062, "num_tokens": 916, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300698514778, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.47233323097532204}}
{"text": "// -----------------------------------------------------------------------------\n// Fern \u00a9 Geoneric\n//\n// This file is part of Geoneric Fern which is available under the terms of\n// the GNU General Public License (GPL), version 2. If you do not want to\n// be bound by the terms of the GPL, you may purchase a proprietary license\n// from Geoneric (http://www.geoneric.eu/contact).\n// -----------------------------------------------------------------------------\n#define BOOST_TEST_MODULE fern algorithm convolution convolve\n#include <boost/test/unit_test.hpp>\n#include \"fern/core/data_customization_point/scalar.h\"\n#include \"fern/core/types.h\"\n#include \"fern/feature/core/data_customization_point/array.h\"\n#include \"fern/feature/core/data_customization_point/masked_array.h\"\n#include \"fern/algorithm/algebra/elementary/equal.h\"\n#include \"fern/algorithm/statistic/count.h\"\n#include \"fern/algorithm/convolution/neighborhood.h\"\n#include \"fern/algorithm/convolution/convolve.h\"\n#include \"fern/algorithm/convolution/replace_no_data_by_focal_average.h\"\n#include \"fern/algorithm/core/test/test_utils.h\"\n\n\nnamespace fa = fern::algorithm;\n\n\nvoid compare_result1(\n    fern::Array<double, 2> const& result)\n{\n    // Compare results.\n    // Upper left corner. ------------------------------------------------------\n    // 0, 0:\n    // +----+----+----+\n    // |  0 |  1 |  2 |\n    // +----+----+----+\n    // |  6 |  7 |  8 |\n    // +----+----+----+\n    // | 12 | 13 | 14 |\n    // +----+----+----+\n    BOOST_CHECK_CLOSE(result[0][0], 63.0 / 9.0, 1e-6);\n\n    // 0, 1:\n    // +----+----+----+----+\n    // |  0 |  1 |  2 |  3 |\n    // +----+----+----+----+\n    // |  6 |  7 |  8 |  9 |\n    // +----+----+----+----+\n    // | 12 | 13 | 14 | 15 |\n    // +----+----+----+----+\n    BOOST_CHECK_CLOSE(result[0][1], 90.0 / 12.0, 1e-6);\n\n    // 1, 1:\n    // +----+----+----+----+\n    // |  0 |  1 |  2 |  3 |\n    // +----+----+----+----+\n    // |  6 |  7 |  8 |  9 |\n    // +----+----+----+----+\n    // | 12 | 13 | 14 | 15 |\n    // +----+----+----+----+\n    // | 18 | 19 | 20 | 21 |\n    // +----+----+----+----+\n    BOOST_CHECK_CLOSE(result[1][1], 168.0 / 16.0, 1e-6);\n\n    // Upper right corner. -----------------------------------------------------\n    // 0, 4:\n    // +----+----+----+----+\n    // |  2 |  3 |  4 |  5 |\n    // +----+----+----+----+\n    // |  8 |  9 | 10 | 11 |\n    // +----+----+----+----+\n    // | 14 | 15 | 16 | 17 |\n    // +----+----+----+----+\n    BOOST_CHECK_CLOSE(result[0][4], 114.0 / 12.0, 1e-6);\n\n    // Lower left corner. ------------------------------------------------------\n    // 6, 1:\n    // +----+----+----+----+\n    // | 24 | 25 | 26 | 27 |\n    // +----+----+----+----+\n    // | 30 | 31 | 32 | 33 |\n    // +----+----+----+----+\n    // | 36 | 37 | 38 | 39 |\n    // +----+----+----+----+\n    BOOST_CHECK_CLOSE(result[6][1], 378 / 12.0, 1e-6);\n\n    // Lower right corner. -----------------------------------------------------\n    // 6, 5\n    // +----+----+----+\n    // | 27 | 28 | 29 |\n    // +----+----+----+\n    // | 33 | 34 | 35 |\n    // +----+----+----+\n    // | 39 | 40 | 41 |\n    // +----+----+----+\n    BOOST_CHECK_CLOSE(result[6][5], 306 / 9.0, 1e-6);\n\n    // North side. -------------------------------------------------------------\n    // 0, 2\n    // +----+----+----+----+----+\n    // |  0 |  1 |  2 |  3 |  4 |\n    // +----+----+----+----+----+\n    // |  6 |  7 |  8 |  9 | 10 |\n    // +----+----+----+----+----+\n    // | 12 | 13 | 14 | 15 | 16 |\n    // +----+----+----+----+----+\n    BOOST_CHECK_CLOSE(result[0][2], 120 / 15.0, 1e-6);\n\n    // West side. --------------------------------------------------------------\n    // 4, 0\n    // +----+----+----+\n    // | 12 | 13 | 14 |\n    // +----+----+----+\n    // | 18 | 19 | 20 |\n    // +----+----+----+\n    // | 24 | 25 | 26 |\n    // +----+----+----+\n    // | 30 | 31 | 32 |\n    // +----+----+----+\n    // | 36 | 37 | 38 |\n    // +----+----+----+\n    BOOST_CHECK_CLOSE(result[4][0], 375 / 15.0, 1e-6);\n\n    // East side. --------------------------------------------------------------\n    // 2, 4\n    // +----+----+----+----+\n    // |  2 |  3 |  4 |  5 |\n    // +----+----+----+----+\n    // |  8 |  9 | 10 | 11 |\n    // +----+----+----+----+\n    // | 14 | 15 | 16 | 17 |\n    // +----+----+----+----+\n    // | 20 | 21 | 22 | 23 |\n    // +----+----+----+----+\n    // | 26 | 27 | 28 | 29 |\n    // +----+----+----+----+\n    BOOST_CHECK_CLOSE(result[2][4], 310 / 20.0, 1e-6);\n\n    // South side.\n    // 6, 3\n    // +----+----+----+----+----+\n    // | 25 | 26 | 27 | 28 | 29 |\n    // +----+----+----+----+----+\n    // | 31 | 32 | 33 | 34 | 35 |\n    // +----+----+----+----+----+\n    // | 37 | 38 | 39 | 40 | 41 |\n    // +----+----+----+----+----+\n    BOOST_CHECK_CLOSE(result[6][3], 495 / 15.0, 1e-6);\n\n    // Inner part.\n    // 3, 2\n    // +----+----+----+----+----+\n    // |  6 |  7 |  8 |  9 | 10 |\n    // +----+----+----+----+----+\n    // | 12 | 13 | 14 | 15 | 16 |\n    // +----+----+----+----+----+\n    // | 18 | 19 | 20 | 21 | 22 |\n    // +----+----+----+----+----+\n    // | 24 | 25 | 26 | 27 | 28 |\n    // +----+----+----+----+----+\n    // | 30 | 31 | 32 | 33 | 34 |\n    // +----+----+----+----+----+\n    BOOST_CHECK_CLOSE(result[3][2], 500 / 25.0, 1e-6);\n\n    // Make sure all cells in the result have a new value.\n    BOOST_CHECK_EQUAL(std::count(result.data(), result.data() +\n        result.num_elements(), 0), 0);\n}\n\n\nvoid compare_result2(\n    fern::Array<double, 2> const& result)\n{\n    // Upper left corner. ----------------------------------------------\n    BOOST_CHECK_CLOSE(result[0][0], (63.0 + 24.5) / (9.0 + 7.0), 1e-6);\n    BOOST_CHECK_CLOSE(result[0][1], (90.0 + 27.5) / (12.0 + 8.0), 1e-6);\n    BOOST_CHECK_CLOSE(result[1][1], (168.0 + 45.5) / (16.0 + 9.0),\n        1e-6);\n\n    // Upper right corner. ---------------------------------------------\n    BOOST_CHECK_CLOSE(result[0][4], (114.0 + 54.5) / (12.0 + 8.0),\n        1e-6);\n\n    // Lower left corner. ----------------------------------------------\n    // Out of image values:\n    //     (18 + 24 + 30) / 3 ->  72 / 3\n    //     (24 + 30 + 36) / 3 ->  90 / 3\n    //     (30 + 36     ) / 2 ->  66 / 2\n    //     (36          ) / 1 ->  36 / 1\n    //     (36 + 37     ) / 2 ->  73 / 2\n    //     (36 + 37 + 38) / 3 -> 111 / 3\n    //     (37 + 38 + 39) / 3 -> 114 / 3\n    //     (38 + 39 + 40) / 3 -> 117 / 3\n    BOOST_CHECK_CLOSE(result[6][1], (378.0 + 273.5) / (12.0 + 8.0),\n        1e-6);\n\n    // Lower right corner. ---------------------------------------------\n    // Out of image values:\n    //     (38 + 39 + 40) / 3 -> 117 / 3\n    //     (39 + 40 + 41) / 3 -> 120 / 3\n    //     (40 + 41     ) / 2 ->  81 / 2\n    //     (41          ) / 1 ->  41 / 1\n    //     (41 + 35     ) / 2 ->  76 / 2\n    //     (29 + 35 + 41) / 3 -> 105 / 3\n    //     (23 + 29 + 35) / 3 ->  87 / 3\n    BOOST_CHECK_CLOSE(result[6][5], (306.0 + 262.5) / (9.0 + 7.0),\n        1e-6);\n\n    // North side. -----------------------------------------------------\n    // Out of image values:\n    // (0 + 1    ) / 2\n    // (0 + 1 + 2) / 3\n    // (1 + 2 + 3) / 3\n    // (2 + 3 + 4) / 3\n    // (3 + 4 + 5) / 3\n    BOOST_CHECK_CLOSE(result[0][2], (120.0 + 10.5) / (15.0 + 5.0),\n        1e-6);\n\n    // West side. ------------------------------------------------------\n    // Out of image values:\n    // ( 6 + 12 + 18) / 3 -> 36 / 3\n    // (12 + 18 + 24) / 3 -> 54 / 3\n    // (18 + 24 + 30) / 3 -> 72 / 3\n    // (24 + 30 + 36) / 3 -> 90 / 3\n    // (30 + 36     ) / 2 -> 66 / 2\n    BOOST_CHECK_CLOSE(result[4][0], (375.0 + 117.0) / (15.0 + 5.0),\n        1e-6);\n\n    // East side. ------------------------------------------------------\n    // Out of image values:\n    // ( 5 + 11     ) / 2\n    // ( 5 + 11 + 17) / 3\n    // (11 + 17 + 23) / 3\n    // (17 + 23 + 29) / 3\n    // (23 + 29 + 35) / 3\n    BOOST_CHECK_CLOSE(result[2][4], (310.0 + 88.0) / (20.0 + 5.0),\n        1e-6);\n\n    // South side. -----------------------------------------------------\n    // Out of image values:\n    // (36 + 37 + 38) / 3\n    // (37 + 38 + 39) / 3\n    // (38 + 39 + 40) / 3\n    // (39 + 40 + 41) / 3\n    // (40 + 41     ) / 2\n    BOOST_CHECK_CLOSE(result[6][3], (495.0 + 194.5) / (15.0 + 5.0),\n        1e-6);\n\n    // Inner part. -----------------------------------------------------\n    // No out of image values.\n    BOOST_CHECK_CLOSE(result[3][2], 500 / 25.0, 1e-6);\n\n    // Make sure all cells in the result have a new value.\n    BOOST_CHECK_EQUAL(std::count(result.data(), result.data() +\n        result.num_elements(), 0), 0);\n}\n\n\nvoid compare_result3(\n    fern::Array<double, 2> const& result)\n{\n    // +----+----+\n    // |  0 |  1 |\n    // +----+----+\n    // |  6 |  7 |\n    // +----+----+\n    BOOST_CHECK_CLOSE(result[0][0], (0 + 1 + 6) / 3.0, 1e-6);\n\n    // +----+----+\n    // | 34 | 35 |\n    // +----+----+\n    // | 40 | 41 |\n    // +----+----+\n    BOOST_CHECK_CLOSE(result[6][5], (35 + 40 + 41) / 3.0, 1e-6);\n\n    // +----+----+----+\n    // |  0 |  1 |  2 |\n    // +----+----+----+\n    // |  6 |  7 |  8 |\n    // +----+----+----+\n    // | 12 | 13 | 14 |\n    // +----+----+----+\n    BOOST_CHECK_CLOSE(result[1][1], (1 + 6 + 7 + 8 + 13) / 5.0, 1e-6);\n\n    // +----+----+\n    // | 18 | 19 |\n    // +----+----+\n    // | 24 | 25 |\n    // +----+----+\n    // | 30 | 31 |\n    // +----+----+\n    BOOST_CHECK_CLOSE(result[4][0], (18 + 24 + 25 + 30) / 4.0, 1e-6);\n\n    // +----+----+----+\n    // |  1 |  2 |  3 |\n    // +----+----+----+\n    // |  7 |  8 |  9 |\n    // +----+----+----+\n    // | 13 | 14 | 15 |\n    // +----+----+----+\n    BOOST_CHECK_CLOSE(result[1][2], (2 + 7 + 8 + 9 + 14) / 5.0, 1e-6);\n}\n\n\nvoid compare_result4(\n    fern::MaskedArray<double, 2> const& result)\n{\n    // +----+----+----+\n    // | 10 |  7 |  6 |\n    // +----+----+----+\n    // |  2 | 18 | -1 |\n    // +----+----+----+\n    // | 12 | -6 |  8 |\n    // +----+----+----+\n    BOOST_CHECK(!result.mask()[0][0]);\n    BOOST_CHECK_CLOSE(result[0][0], 6 + 4, 1e-6);\n\n    BOOST_CHECK(!result.mask()[0][1]);\n    BOOST_CHECK_CLOSE(result[0][1], 8 + -2 + 1, 1e-6);\n\n    BOOST_CHECK(!result.mask()[0][2]);\n    BOOST_CHECK_CLOSE(result[0][2], 6 + 0, 1e-6);\n\n    BOOST_CHECK(!result.mask()[1][0]);\n    BOOST_CHECK_CLOSE(result[1][0], 8 + 1 + -7, 1e-6);\n\n    BOOST_CHECK(!result.mask()[1][1]);\n    BOOST_CHECK_CLOSE(result[1][1], 6 + 4 + 0 + 8, 1e-6);\n\n    BOOST_CHECK(!result.mask()[1][2]);\n    BOOST_CHECK_CLOSE(result[1][2], -2 + 1, 1e-6);\n\n    BOOST_CHECK(!result.mask()[2][0]);\n    BOOST_CHECK_CLOSE(result[2][0], 4 + 8, 1e-6);\n\n    BOOST_CHECK(!result.mask()[2][1]);\n    BOOST_CHECK_CLOSE(result[2][1], 1 + -7, 1e-6);\n\n    BOOST_CHECK(!result.mask()[2][2]);\n    BOOST_CHECK_CLOSE(result[2][2], 0 + 8, 1e-6);\n}\n\n\nvoid compare_result5(\n    fern::MaskedArray<double, 2> const& result)\n{\n    // +----+----+----+----+-----+-----+\n    // |  7 |  7 |  1 |  4 |  15 |  15 |\n    // +----+----+----+----+-----+-----+\n    // | 19 | 20 |  7 | 10 |  15 |  15 |\n    // +----+----+----+----+-----+-----+\n    // | 37 | 38 | 13 |  X |  32 |  34 |\n    // +----+----+----+----+-----+-----+\n    // | 55 | 56 | 19 | 22 |  51 |  51 |\n    // +----+----+----+----+-----+-----+\n    // | 73 | 74 | 25 | 28 |  85 |  86 |\n    // +----+----+----+----+-----+-----+\n    // | 91 | 92 | 31 | 34 | 103 | 104 |\n    // +----+----+----+----+-----+-----+\n    // | 67 | 67 | 37 | 40 |  75 |  75 |\n    // +----+----+----+----+-----+-----+\n\n    size_t const nr_cols = 6;\n\n    size_t row_id = 0;\n    std::vector<double> values = { 7, 7, 1, 4, 15, 15 };\n    std::vector<bool> no_data = { false, false, false, false, false, false };\n\n    BOOST_REQUIRE_EQUAL_COLLECTIONS(no_data.begin(), no_data.end(),\n        result.mask().data() + row_id * nr_cols,\n        result.mask().data() + row_id * nr_cols + nr_cols);\n    BOOST_CHECK_EQUAL_COLLECTIONS(values.begin(), values.end(),\n        result.data() + row_id * nr_cols,\n        result.data() + row_id * nr_cols + nr_cols);\n\n\n    ++row_id;\n    values = { 19, 20, 7, 10, 15, 15 };\n    no_data = { false, false, false, false, false, false };\n\n    BOOST_REQUIRE_EQUAL_COLLECTIONS(no_data.begin(), no_data.end(),\n        result.mask().data() + row_id * nr_cols,\n        result.mask().data() + row_id * nr_cols + nr_cols);\n    BOOST_CHECK_EQUAL_COLLECTIONS(values.begin(), values.end(),\n        result.data() + row_id * nr_cols,\n        result.data() + row_id * nr_cols + nr_cols);\n\n\n    ++row_id;\n    no_data = { false, false, false, true, false, false };\n\n    BOOST_REQUIRE_EQUAL_COLLECTIONS(no_data.begin(), no_data.end(),\n        result.mask().data() + row_id * nr_cols,\n        result.mask().data() + row_id * nr_cols + nr_cols);\n\n    BOOST_CHECK_CLOSE(result[2][0], 37, 1e-6);\n    BOOST_CHECK_CLOSE(result[2][1], 38, 1e-6);\n    BOOST_CHECK_CLOSE(result[2][2], 13, 1e-6);\n    BOOST_CHECK_CLOSE(result[2][4], 32, 1e-6);\n    BOOST_CHECK_CLOSE(result[2][5], 34, 1e-6);\n\n\n    ++row_id;\n    values = { 55, 56, 19, 22, 51, 51 };\n    no_data = { false, false, false, false, false, false };\n\n    BOOST_REQUIRE_EQUAL_COLLECTIONS(no_data.begin(), no_data.end(),\n        result.mask().data() + row_id * nr_cols,\n        result.mask().data() + row_id * nr_cols + nr_cols);\n    BOOST_CHECK_EQUAL_COLLECTIONS(values.begin(), values.end(),\n        result.data() + row_id * nr_cols,\n        result.data() + row_id * nr_cols + nr_cols);\n\n\n    ++row_id;\n    values = { 73, 74, 25, 28, 85, 86 };\n    no_data = { false, false, false, false, false, false };\n\n    BOOST_REQUIRE_EQUAL_COLLECTIONS(no_data.begin(), no_data.end(),\n        result.mask().data() + row_id * nr_cols,\n        result.mask().data() + row_id * nr_cols + nr_cols);\n    BOOST_CHECK_EQUAL_COLLECTIONS(values.begin(), values.end(),\n        result.data() + row_id * nr_cols,\n        result.data() + row_id * nr_cols + nr_cols);\n\n\n    ++row_id;\n    values = { 91, 92, 31, 34, 103, 104 };\n    no_data = { false, false, false, false, false, false };\n\n    BOOST_REQUIRE_EQUAL_COLLECTIONS(no_data.begin(), no_data.end(),\n        result.mask().data() + row_id * nr_cols,\n        result.mask().data() + row_id * nr_cols + nr_cols);\n    BOOST_CHECK_EQUAL_COLLECTIONS(values.begin(), values.end(),\n        result.data() + row_id * nr_cols,\n        result.data() + row_id * nr_cols + nr_cols);\n\n\n    ++row_id;\n    values = { 67, 67, 37, 40, 75, 75 };\n    no_data = { false, false, false, false, false, false };\n\n    BOOST_REQUIRE_EQUAL_COLLECTIONS(no_data.begin(), no_data.end(),\n        result.mask().data() + row_id * nr_cols,\n        result.mask().data() + row_id * nr_cols + nr_cols);\n    BOOST_CHECK_EQUAL_COLLECTIONS(values.begin(), values.end(),\n        result.data() + row_id * nr_cols,\n        result.data() + row_id * nr_cols + nr_cols);\n}\n\n\nvoid compare_result6(\n    fern::MaskedArray<double, 2> const& result)\n{\n    // +----+----\u064d+-----+-----+----+----+\n    // |  X |  X |   8 |   9 |  X |  X |\n    // +----+----\u064d+-----+-----+----+----+\n    // |  X | 21 |  23 |  23 | 25 |  X |\n    // +----+----\u064d+-----+-----+----+----+\n    // | 31 | 33 |  56 |  60 | 37 | 39 |\n    // +----+----\u064d+-----+-----+----+----+\n    // | 19 | 76 |  80 |  84 | 88 | 22 |\n    // +----+----\u064d+-----+-----+----+----+\n    // | 43 | 45 | 104 | 108 | 49 | 51 |\n    // +----+----\u064d+-----+-----+----+----+\n    // |  X | 57 |  97 |  59 | 61 |  X |\n    // +----+----\u064d+-----+-----+----+----+\n    // |  X | 38 |  32 |  71 |  X |  X |\n    // +----+----\u064d+-----+-----+----+----+\n\n    size_t const nr_cols = 6;\n    size_t row_id = 0;\n    std::vector<double> values;\n    std::vector<bool> no_data;\n\n    no_data = { true, true, false, false, true, true };\n\n    BOOST_REQUIRE_EQUAL_COLLECTIONS(no_data.begin(), no_data.end(),\n        result.mask().data() + row_id * nr_cols,\n        result.mask().data() + row_id * nr_cols + nr_cols);\n    BOOST_CHECK_CLOSE(result[0][2], 8.0, 1e-6);\n    BOOST_CHECK_CLOSE(result[0][3], 9.0, 1e-6);\n\n\n    ++row_id;\n    no_data = { true, false, false, false, false, true };\n\n    BOOST_REQUIRE_EQUAL_COLLECTIONS(no_data.begin(), no_data.end(),\n        result.mask().data() + row_id * nr_cols,\n        result.mask().data() + row_id * nr_cols + nr_cols);\n    BOOST_CHECK_CLOSE(result[1][1], 21.0, 1e-6);\n    BOOST_CHECK_CLOSE(result[1][2], 23.0, 1e-6);\n    BOOST_CHECK_CLOSE(result[1][3], 23.0, 1e-6);\n    BOOST_CHECK_CLOSE(result[1][4], 25.0, 1e-6);\n\n\n    ++row_id;\n    no_data = { false, false, false, false, false, false };\n    values = { 31, 33,  56,  60, 37, 39 };\n\n    BOOST_REQUIRE_EQUAL_COLLECTIONS(no_data.begin(), no_data.end(),\n        result.mask().data() + row_id * nr_cols,\n        result.mask().data() + row_id * nr_cols + nr_cols);\n    BOOST_CHECK_CLOSE(result[2][0], 31.0, 1e-6);\n    BOOST_CHECK_CLOSE(result[2][1], 33.0, 1e-6);\n    BOOST_CHECK_CLOSE(result[2][2], 56.0, 1e-6);\n    BOOST_CHECK_CLOSE(result[2][3], 60.0, 1e-6);\n    BOOST_CHECK_CLOSE(result[2][4], 37.0, 1e-6);\n    BOOST_CHECK_CLOSE(result[2][5], 39.0, 1e-6);\n\n\n    ++row_id;\n    no_data = { false, false, false, false, false, false };\n    values = { 19, 76,  80,  84, 88, 22 };\n\n    BOOST_REQUIRE_EQUAL_COLLECTIONS(no_data.begin(), no_data.end(),\n        result.mask().data() + row_id * nr_cols,\n        result.mask().data() + row_id * nr_cols + nr_cols);\n    BOOST_CHECK_CLOSE(result[3][0], 19.0, 1e-6);\n    BOOST_CHECK_CLOSE(result[3][1], 76.0, 1e-6);\n    BOOST_CHECK_CLOSE(result[3][2], 80.0, 1e-6);\n    BOOST_CHECK_CLOSE(result[3][3], 84.0, 1e-6);\n    BOOST_CHECK_CLOSE(result[3][4], 88.0, 1e-6);\n    BOOST_CHECK_CLOSE(result[3][5], 22.0, 1e-6);\n\n\n    ++row_id;\n    no_data = { false, false, false, false, false, false };\n    values = { 43, 45, 104, 108, 49, 51 };\n\n    BOOST_REQUIRE_EQUAL_COLLECTIONS(no_data.begin(), no_data.end(),\n        result.mask().data() + row_id * nr_cols,\n        result.mask().data() + row_id * nr_cols + nr_cols);\n    BOOST_CHECK_CLOSE(result[4][0], 43.0, 1e-6);\n    BOOST_CHECK_CLOSE(result[4][1], 45.0, 1e-6);\n    BOOST_CHECK_CLOSE(result[4][2], 104.0, 1e-6);\n    BOOST_CHECK_CLOSE(result[4][3], 108.0, 1e-6);\n    BOOST_CHECK_CLOSE(result[4][4], 49.0, 1e-6);\n    BOOST_CHECK_CLOSE(result[4][5], 51.0, 1e-6);\n\n\n    ++row_id;\n    no_data = { true, false, false, false, false, true };\n\n    BOOST_REQUIRE_EQUAL_COLLECTIONS(no_data.begin(), no_data.end(),\n        result.mask().data() + row_id * nr_cols,\n        result.mask().data() + row_id * nr_cols + nr_cols);\n    BOOST_CHECK_CLOSE(result[5][1], 57.0, 1e-6);\n    BOOST_CHECK_CLOSE(result[5][2], 97.0, 1e-6);\n    BOOST_CHECK_CLOSE(result[5][3], 59.0, 1e-6);\n    BOOST_CHECK_CLOSE(result[5][4], 61.0, 1e-6);\n\n\n    ++row_id;\n    no_data = { true, false, false, false, true, true };\n    BOOST_REQUIRE_EQUAL_COLLECTIONS(no_data.begin(), no_data.end(),\n        result.mask().data() + row_id * nr_cols,\n        result.mask().data() + row_id * nr_cols + nr_cols);\n    BOOST_CHECK_CLOSE(result[6][1], 38.0, 1e-6);\n    BOOST_CHECK_CLOSE(result[6][2], 32.0, 1e-6);\n    BOOST_CHECK_CLOSE(result[6][3], 71.0, 1e-6);\n}\n\n\nBOOST_AUTO_TEST_CASE(convolve)\n{\n    using Weights = std::initializer_list<std::initializer_list<int>>;\n\n    fa::ParallelExecutionPolicy parallel;\n    fa::SequentialExecutionPolicy sequential;\n\n    // Kernel with radius 2.\n    {\n        // Create input array:\n        // +----+----+----+----+----+----+\n        // |  0 |  1 |  2 |  3 |  4 |  5 |\n        // +----+----+----+----+----+----+\n        // |  6 |  7 |  8 |  9 | 10 | 11 |\n        // +----+----+----+----+----+----+\n        // | 12 | 13 | 14 | 15 | 16 | 17 |\n        // +----+----+----+----+----+----+\n        // | 18 | 19 | 20 | 21 | 22 | 23 |\n        // +----+----+----+----+----+----+\n        // | 24 | 25 | 26 | 27 | 28 | 29 |\n        // +----+----+----+----+----+----+\n        // | 30 | 31 | 32 | 33 | 34 | 35 |\n        // +----+----+----+----+----+----+\n        // | 36 | 37 | 38 | 39 | 40 | 41 |\n        // +----+----+----+----+----+----+\n        size_t const nr_rows = 7;\n        size_t const nr_cols = 6;\n        auto extents = fern::extents[nr_rows][nr_cols];\n        fern::Array<double, 2> argument(extents);\n        std::iota(\n            argument.data(), argument.data() + argument.num_elements(), 0);\n\n        // Calculate local average.\n        // Define kernel shape and weights.\n\n        Weights weights{\n            {1, 1, 1, 1, 1},\n            {1, 1, 1, 1, 1},\n            {1, 1, 1, 1, 1},\n            {1, 1, 1, 1, 1},\n            {1, 1, 1, 1, 1}\n        };\n\n        fern::Square<int, 2> compile_time_kernel(weights);\n        fern::Kernel<int> runtime_kernel(2, weights);\n\n        // Convolute while skipping out-of-image cells.\n        {\n            // Sequential, compile-time kernel\n            {\n                fern::Array<double, 2> result(extents);\n                fa::convolution::convolve(\n                    sequential, argument, compile_time_kernel, result);\n                compare_result1(result);\n            }\n\n            // Sequential, runtime kernel\n            {\n                fern::Array<double, 2> result(extents);\n                fa::convolution::convolve(\n                    sequential, argument, runtime_kernel, result);\n                compare_result1(result);\n            }\n\n            // Parallel, compile-time kernel\n            {\n                fern::Array<double, 2> result(extents);\n                fa::convolution::convolve(\n                    parallel, argument, compile_time_kernel, result);\n                compare_result1(result);\n            }\n\n            // Parallel, runtime kernel\n            {\n                fern::Array<double, 2> result(extents);\n                fa::convolution::convolve(\n                    parallel, argument, runtime_kernel, result);\n                compare_result1(result);\n            }\n        }\n\n        // Convolute while calculating values for out-of-image cells.\n        {\n            using AlternativeForNoDataPolicy=fa::convolve::SkipNoData;\n            using NormalizePolicy=fa::convolve::DivideByWeights;\n            using OutOfImagePolicy=\n                fa::convolve::ReplaceOutOfImageByFocalAverage;\n            using NoDataFocusElementPolicy=fa::convolve::KeepNoDataFocusElement;\n            using InputNoDataPolicy=fa::InputNoDataPolicies<fa::SkipNoData>;\n            using OutputNoDataPolicy=fa::DontMarkNoData;\n\n            OutputNoDataPolicy output_no_data_policy;\n\n            // Sequential, compile-time kernel\n            {\n                fern::Array<double, 2> result(extents);\n                fa::convolution::convolve<\n                    AlternativeForNoDataPolicy,\n                    NormalizePolicy,\n                    OutOfImagePolicy,\n                    NoDataFocusElementPolicy,\n                    fa::unary::DiscardRangeErrors,\n                    InputNoDataPolicy,\n                    OutputNoDataPolicy>(\n                        InputNoDataPolicy{{}}, output_no_data_policy,\n                        sequential, argument, compile_time_kernel, result);\n                compare_result2(result);\n            }\n\n            // Sequential, runtime kernel\n            {\n                fern::Array<double, 2> result(extents);\n                fa::convolution::convolve<\n                    AlternativeForNoDataPolicy,\n                    NormalizePolicy,\n                    OutOfImagePolicy,\n                    NoDataFocusElementPolicy,\n                    fa::unary::DiscardRangeErrors,\n                    InputNoDataPolicy,\n                    OutputNoDataPolicy>(\n                        InputNoDataPolicy{{}}, output_no_data_policy,\n                        sequential, argument, runtime_kernel, result);\n                compare_result2(result);\n            }\n\n            // Parallel, compile-time kernel\n            {\n                fern::Array<double, 2> result(extents);\n                fa::convolution::convolve<\n                    AlternativeForNoDataPolicy,\n                    NormalizePolicy,\n                    OutOfImagePolicy,\n                    NoDataFocusElementPolicy,\n                    fa::unary::DiscardRangeErrors,\n                    InputNoDataPolicy,\n                    OutputNoDataPolicy>(\n                        InputNoDataPolicy{{}}, output_no_data_policy,\n                        parallel, argument, compile_time_kernel, result);\n                compare_result2(result);\n            }\n\n            // Parallel, runtime kernel\n            {\n                fern::Array<double, 2> result(extents);\n                fa::convolution::convolve<\n                    AlternativeForNoDataPolicy,\n                    NormalizePolicy,\n                    OutOfImagePolicy,\n                    NoDataFocusElementPolicy,\n                    fa::unary::DiscardRangeErrors,\n                    InputNoDataPolicy,\n                    OutputNoDataPolicy>(\n                        InputNoDataPolicy{{}}, output_no_data_policy,\n                        parallel, argument, runtime_kernel, result);\n                compare_result2(result);\n            }\n        }\n    }\n\n    // Kernel with radius 1.\n    // This used to crash.\n    {\n        // Create input array:\n        // +----+----+----+----+----+----+\n        // |  0 |  1 |  2 |  3 |  4 |  5 |\n        // +----+----+----+----+----+----+\n        // |  6 |  7 |  8 |  9 | 10 | 11 |\n        // +----+----+----+----+----+----+\n        // | 12 | 13 | 14 | 15 | 16 | 17 |\n        // +----+----+----+----+----+----+\n        // | 18 | 19 | 20 | 21 | 22 | 23 |\n        // +----+----+----+----+----+----+\n        // | 24 | 25 | 26 | 27 | 28 | 29 |\n        // +----+----+----+----+----+----+\n        // | 30 | 31 | 32 | 33 | 34 | 35 |\n        // +----+----+----+----+----+----+\n        // | 36 | 37 | 38 | 39 | 40 | 41 |\n        // +----+----+----+----+----+----+\n        size_t const nr_rows = 7;\n        size_t const nr_cols = 6;\n        auto extents = fern::extents[nr_rows][nr_cols];\n        fern::Array<double, 2> argument(extents);\n        std::iota(argument.data(), argument.data() + argument.num_elements(),\n            0);\n\n        // Calculate local average.\n        // Define kernel shape and weights.\n        Weights weights{\n            {1, 1, 1},\n            {1, 1, 1},\n            {1, 1, 1}\n        };\n\n        fern::Square<int, 1> compile_time_kernel(weights);\n        fern::Kernel<int> runtime_kernel(1, weights);\n\n        // Sequential, compile-time kernel\n        {\n            fern::Array<double, 2> result(extents);\n            fa::convolution::convolve(\n                sequential, argument, compile_time_kernel, result);\n        }\n\n        // Sequential, runtime kernel\n        {\n            fern::Array<double, 2> result(extents);\n            fa::convolution::convolve(\n                sequential, argument, runtime_kernel, result);\n        }\n\n        // Parallel, compile-time kernel\n        {\n            fern::Array<double, 2> result(extents);\n            fa::convolution::convolve(\n                parallel, argument, compile_time_kernel, result);\n        }\n\n        // Parallel, runtime kernel\n        {\n            fern::Array<double, 2> result(extents);\n            fa::convolution::convolve(\n                parallel, argument, runtime_kernel, result);\n        }\n    }\n}\n\n\n// TODO Test Small image with out of image policy with larger kernel.\n// TODO Test Focal Sum, with kernel that doesn't weigh.\n\n\ntemplate<\n    class Value,\n    class Result>\nusing OutOfRangePolicy = fa::convolve::OutOfRangePolicy<Value, Result>;\n\n\nBOOST_AUTO_TEST_CASE(out_of_range_policy)\n{\n    // Make sure that out of range can be detected and that no-data can be\n    // written when it happens.\n\n    {\n        auto min_float32 = fern::min<fern::f32>();\n        auto max_float32 = fern::max<fern::f32>();\n\n        OutOfRangePolicy<fern::f32, fern::f32> policy;\n        BOOST_CHECK(policy.within_range(5.0));\n        BOOST_CHECK(policy.within_range(-5.0));\n        BOOST_CHECK(policy.within_range(0.0));\n        BOOST_CHECK(policy.within_range(min_float32));\n        BOOST_CHECK(policy.within_range(max_float32));\n        BOOST_CHECK(!policy.within_range(2 * max_float32));\n    }\n}\n\n\nBOOST_AUTO_TEST_CASE(no_data_policies)\n{\n    using Weights = std::initializer_list<std::initializer_list<int>>;\n\n    // Make sure that input no-data is detected and handled correctly.\n    using InputNoDataPolicy = fa::InputNoDataPolicies<\n        fa::DetectNoDataByValue<fern::Mask<2>>>;\n    using OutputNoDataPolicy = fa::MarkNoDataByValue<fern::Mask<2>>;\n\n    fa::SequentialExecutionPolicy sequential;\n\n    size_t const nr_rows = 3;\n    size_t const nr_cols = 3;\n    auto extents = fern::extents[nr_rows][nr_cols];\n\n    // Local average kernel.\n    Weights weights_1{\n        {1, 1, 1},\n        {1, 1, 1},\n        {1, 1, 1}\n    };\n    Weights weights_2{\n        {2, 2, 2},\n        {2, 2, 2},\n        {2, 2, 2}\n    };\n\n    fern::Kernel<int> kernel_1(1, weights_1);\n    fern::Kernel<int> kernel_2(1, weights_2);\n\n\n    // Source image with a few masked values.\n    {\n        // +---+---+---+\n        // | 0 | 1 | 2 |\n        // +---+---+---+\n        // | 3 | X | 5 |\n        // +---+---+---+\n        // | X | 7 | 8 |\n        // +---+---+---+\n        fern::MaskedArray<double, 2> source(extents);\n        std::iota(source.data(), source.data() + source.num_elements(), 0);\n        source.mask()[1][1] = true;\n        source.mask()[2][0] = true;\n        fern::MaskedArray<double, 2> destination(extents);\n\n        // Skip no-data.\n        {\n            fern::MaskedArray<double, 2> destination(extents);\n            destination.fill(999.9);\n            OutputNoDataPolicy output_no_data_policy(destination.mask(), true);\n            fa::convolution::convolve<\n                fa::convolve::SkipNoData,\n                fa::convolve::DivideByWeights,\n                fa::convolve::SkipOutOfImage,\n                fa::convolve::KeepNoDataFocusElement,\n                fa::unary::DiscardRangeErrors>(\n                    InputNoDataPolicy{{source.mask(), true}},\n                    output_no_data_policy,\n                    sequential,\n                    source, kernel_1, destination);\n\n            // Verify mask.\n            uint64_t nr_masked_cells{0};\n            fa::statistic::count(sequential, destination.mask(),\n                true, nr_masked_cells);\n            BOOST_CHECK_EQUAL(nr_masked_cells, 2u);\n            BOOST_CHECK(destination.mask()[1][1]);\n            BOOST_CHECK(destination.mask()[2][0]);\n\n            // Verify values.\n            fern::Array<double, 2> result_we_want({\n                { 4.0/3.0, 11.0/5.0,  8.0/3.0},\n                {11.0/4.0,    999.9, 23.0/5.0},\n                {   999.9, 23.0/4.0, 20.0/3.0}\n            });\n            fern::Array<bool, 2> equal_cells(extents);\n            fa::algebra::equal(sequential, destination, result_we_want,\n                equal_cells);\n\n            uint64_t nr_equal_cells{0};\n            fa::statistic::count(sequential, equal_cells, true,\n                nr_equal_cells);\n            BOOST_CHECK_EQUAL(nr_equal_cells, 9u);\n        }\n\n        // TODO Remove this, replacing no-data is pre-processing.\n        /// // Replace no-data by focal average.\n        /// {\n        ///     // Focal average of the no-data cells is\n        ///     // - 26/7\n        ///     // - 10/2\n        ///     // +-----+--------+---+\n        ///     // |  0  |     1  | 2 |\n        ///     // +-----+--------+---+\n        ///     // |  3  | (26/7) | 5 |\n        ///     // +-----+--------+---+\n        ///     // | (5) |     7  | 8 |\n        ///     // +-----+--------+---+\n        ///     fern::MaskedArray<double, 2> destination(extents);\n        ///     destination.fill(999.9);\n        ///     fa::convolution::convolve<\n        ///         fa::convolve::DivideByWeights,\n        ///         fa::convolve::SkipOutOfImage,\n        ///         fern::unary::DiscardRangeErrors>(\n        ///         fa::convolve::ReplaceNoDataByFocalAverage,\n        ///             sequential,\n        ///             InputNoDataPolicy{{source.mask(), true}},\n        ///             OutputNoDataPolicy(destination.mask(), true),\n        ///             source, kernel_1, destination);\n\n        ///     // Verify mask.\n        ///     size_t nr_masked_cells{0};\n        ///     fa::statistic::count(destination.mask(), true, nr_masked_cells);\n        ///     BOOST_CHECK_EQUAL(nr_masked_cells, 2);\n        ///     BOOST_CHECK(destination.mask()[1][1]);\n        ///     BOOST_CHECK(destination.mask()[2][0]);\n\n        ///     // Verify values.\n        ///     double const v1 = 26.0 / 7.0;\n        ///     double const v2 = 10.0 / 2.0;\n        ///     fern::Array<double, 2> result_we_want({\n        ///         {       (4.0 + v1)/4.0,      (11.0 + v1)/6.0,   (8.0 + v1)/4.0},\n        ///         { (11.0 + v1 + v2)/6.0,                999.9,  (23.0 + v1)/6.0},\n        ///         {                999.9, (23.0 + v1 + v2)/6.0,  (20.0 + v1)/4.0}\n        ///     });\n\n        ///     fern::Array<bool, 2> equal_cells(extents);\n        ///     fa::algebra::equal(destination, result_we_want, equal_cells);\n\n        ///     size_t nr_equal_cells{0};\n        ///     fa::statistic::count(equal_cells, true, nr_equal_cells);\n        ///     BOOST_CHECK_EQUAL(nr_equal_cells, 9);\n        /// }\n    }\n\n\n    // Source image with lots of masked values.\n    {\n        fern::MaskedArray<double, 2> source(extents);\n        std::iota(source.data(), source.data() + source.num_elements(), 0);\n        source.mask_all();\n        fern::MaskedArray<double, 2> destination(extents);\n        OutputNoDataPolicy output_no_data_policy(destination.mask(), true);\n\n        fa::convolution::convolve<\n            fa::convolve::SkipNoData,\n            fa::convolve::DivideByWeights,\n            fa::convolve::SkipOutOfImage,\n            fa::convolve::KeepNoDataFocusElement,\n            fa::unary::DiscardRangeErrors>(\n                InputNoDataPolicy{{source.mask(), true}},\n                output_no_data_policy,\n                sequential, source, kernel_1, destination);\n\n        uint64_t nr_masked_cells;\n        fa::statistic::count(sequential, destination.mask(), true,\n            nr_masked_cells);\n        BOOST_CHECK_EQUAL(nr_masked_cells, nr_rows * nr_cols);\n    }\n\n    // Source image with very large values. Convolving these should result\n    // in out-\u043ef-range values. It must be possible to detect these and mark\n    // them as no-data in the result.\n    {\n        fern::MaskedArray<double, 2> source(extents);\n        std::fill(source.data(), source.data() + source.num_elements(),\n            fern::max<double>());\n        fern::MaskedArray<double, 2> destination(extents);\n        OutputNoDataPolicy output_no_data_policy(destination.mask(), true);\n\n        fa::convolution::convolve<\n            fa::convolve::SkipNoData,\n            fa::convolve::DivideByWeights,\n            fa::convolve::SkipOutOfImage,\n            fa::convolve::KeepNoDataFocusElement,\n            fa::convolve::OutOfRangePolicy>(\n                InputNoDataPolicy{{source.mask(), true}},\n                output_no_data_policy,\n                sequential, source, kernel_2, destination);\n\n        uint64_t nr_masked_cells;\n        fa::statistic::count(sequential, destination.mask(), true,\n            nr_masked_cells);\n        BOOST_CHECK_EQUAL(nr_masked_cells, nr_rows * nr_cols);\n    }\n}\n\n\nBOOST_AUTO_TEST_CASE(boolean_kernel_weights)\n{\n    using Weights = std::initializer_list<std::initializer_list<bool>>;\n\n    fa::ParallelExecutionPolicy parallel;\n    fa::SequentialExecutionPolicy sequential;\n\n    // Kernel with radius 1 and boolean weights.\n    {\n        // Create input array:\n        // +----+----+----+----+----+----+\n        // |  0 |  1 |  2 |  3 |  4 |  5 |\n        // +----+----+----+----+----+----+\n        // |  6 |  7 |  8 |  9 | 10 | 11 |\n        // +----+----+----+----+----+----+\n        // | 12 | 13 | 14 | 15 | 16 | 17 |\n        // +----+----+----+----+----+----+\n        // | 18 | 19 | 20 | 21 | 22 | 23 |\n        // +----+----+----+----+----+----+\n        // | 24 | 25 | 26 | 27 | 28 | 29 |\n        // +----+----+----+----+----+----+\n        // | 30 | 31 | 32 | 33 | 34 | 35 |\n        // +----+----+----+----+----+----+\n        // | 36 | 37 | 38 | 39 | 40 | 41 |\n        // +----+----+----+----+----+----+\n        size_t const nr_rows = 7;\n        size_t const nr_cols = 6;\n        auto extents = fern::extents[nr_rows][nr_cols];\n        fern::Array<double, 2> argument(extents);\n        std::iota(argument.data(), argument.data() + argument.num_elements(),\n            0);\n\n        // Define kernel shape and weights.\n        Weights weights{\n            {false, true, false},\n            {true , true, true },\n            {false, true, false}\n        };\n        fern::Square<bool, 1> compile_time_kernel{weights};\n        fern::Kernel<bool> runtime_kernel{1, weights};\n\n        // Sequential, compile-time kernel\n        {\n            fern::Array<double, 2> result(extents);\n            fa::convolution::convolve(\n                sequential, argument, compile_time_kernel, result);\n            compare_result3(result);\n        }\n\n        // Sequential, runtime kernel\n        {\n            fern::Array<double, 2> result(extents);\n            fa::convolution::convolve(\n                sequential, argument, runtime_kernel, result);\n            compare_result3(result);\n        }\n\n        // Parallel, compile-time kernel\n        {\n            fern::Array<double, 2> result(extents);\n            fa::convolution::convolve(\n                parallel, argument, compile_time_kernel, result);\n            compare_result3(result);\n        }\n\n        // Parallel, runtime kernel\n        {\n            fern::Array<double, 2> result(extents);\n            fa::convolution::convolve(\n                parallel, argument, runtime_kernel, result);\n            compare_result3(result);\n        }\n    }\n}\n\n\nBOOST_AUTO_TEST_CASE(no_data_focus_element_policy)\n{\n    using InputNoDataPolicy = fa::InputNoDataPolicies<\n        fa::DetectNoDataByValue<fern::Mask<2>>>;\n    using OutputNoDataPolicy = fa::MarkNoDataByValue<fern::Mask<2>>;\n\n    fa::ParallelExecutionPolicy parallel;\n    fa::SequentialExecutionPolicy sequential;\n\n    // PCRaster window4total example\n    {\n        // Create input array:\n        // +----+----+----+\n        // |  8 |  6 | -2 |\n        // +----+----+----+\n        // |  4 |  1 |  0 |\n        // +----+----+----+\n        // | -7 |  8 |  X |\n        // +----+----+----+\n        size_t const nr_rows = 3;\n        size_t const nr_cols = 3;\n        auto extents = fern::extents[nr_rows][nr_cols];\n        fern::MaskedArray<double, 2> argument(extents);\n\n        argument[0][0] = 8;\n        argument[0][1] = 6;\n        argument[0][2] = -2;\n        argument[1][0] = 4;\n        argument[1][1] = 1;\n        argument[1][2] = 0;\n        argument[2][0] = -7;\n        argument[2][1] = 8;\n        argument.mask()[2][2] = true;\n\n        // Define kernel shape and weights.\n        // Similar to PCRaster's window4total algorithm.\n        fern::Square<bool, 1> kernel({\n            {false, true, false},\n            {true , false, true },\n            {false, true, false}\n        });\n\n\n        // Sequential.\n        {\n            fern::MaskedArray<double, 2> result(extents);\n            OutputNoDataPolicy output_no_data_policy(result.mask(), true);\n\n            fa::convolution::convolve<\n                fa::convolve::SkipNoData,\n                fa::convolve::DontDivideByWeights,\n                fa::convolve::SkipOutOfImage,\n                fa::convolve::ReplaceNoDataFocusElement,\n                fa::unary::DiscardRangeErrors>(\n                    InputNoDataPolicy{{argument.mask(), true}},\n                    output_no_data_policy,\n                    sequential,\n                    argument, kernel, result);\n\n            compare_result4(result);\n        }\n\n        // Parallel.\n        {\n            fern::MaskedArray<double, 2> result(extents);\n            OutputNoDataPolicy output_no_data_policy(result.mask(), true);\n\n            fa::convolution::convolve<\n                fa::convolve::SkipNoData,\n                fa::convolve::DontDivideByWeights,\n                fa::convolve::SkipOutOfImage,\n                fa::convolve::ReplaceNoDataFocusElement,\n                fa::unary::DiscardRangeErrors>(\n                    InputNoDataPolicy{{argument.mask(), true}},\n                    output_no_data_policy,\n                    parallel,\n                    argument, kernel, result);\n\n            compare_result4(result);\n        }\n    }\n\n    {\n        // Create input array:\n        // +----+----+---+---+----+----+\n        // |  0 |  1 | X | X |  4 |  5 |\n        // +----+----+---+---+----+----+\n        // |  6 |  7 | X | X | 10 | 11 |\n        // +----+----+---+---+----+----+\n        // | 12 | 13 | X | X |  X |  X |\n        // +----+----+---+---+----+----+\n        // | 18 | 19 | X | X | 22 | 23 |\n        // +----+----+---+---+----+----+\n        // | 24 | 25 | X | X | 28 | 29 |\n        // +----+----+---+---+----+----+\n        // | 30 | 31 | X | X | 34 | 35 |\n        // +----+----+---+---+----+----+\n        // | 36 | 37 | X | X | 40 | 41 |\n        // +----+----+---+---+----+----+\n\n        size_t const nr_rows = 7;\n        size_t const nr_cols = 6;\n        auto extents = fern::extents[nr_rows][nr_cols];\n        fern::MaskedArray<double, 2> argument(extents);\n\n        std::iota(argument.data(), argument.data() + argument.num_elements(),\n            0);\n\n        argument.mask()[0][2] = true;\n        argument.mask()[0][3] = true;\n        argument.mask()[1][2] = true;\n        argument.mask()[1][3] = true;\n        argument.mask()[2][2] = true;\n        argument.mask()[2][3] = true;\n        argument.mask()[2][4] = true;\n        argument.mask()[2][5] = true;\n        argument.mask()[3][2] = true;\n        argument.mask()[3][3] = true;\n        argument.mask()[4][2] = true;\n        argument.mask()[4][3] = true;\n        argument.mask()[5][2] = true;\n        argument.mask()[5][3] = true;\n        argument.mask()[6][2] = true;\n        argument.mask()[6][3] = true;\n\n\n        // Define kernel shape and weights.\n        // Similar to PCRaster's window4total algorithm.\n        fern::Square<bool, 1> kernel({\n            {false, true, false},\n            {true , false, true },\n            {false, true, false}\n        });\n\n\n        // Sequential.\n        {\n            fern::MaskedArray<double, 2> result(extents);\n            fa::convolution::convolve(sequential, argument, kernel,\n                result);\n            OutputNoDataPolicy output_no_data_policy(result.mask(), true);\n\n            fa::convolution::convolve<\n                fa::convolve::SkipNoData,\n                fa::convolve::DontDivideByWeights,\n                fa::convolve::SkipOutOfImage,\n                fa::convolve::ReplaceNoDataFocusElement,\n                fa::unary::DiscardRangeErrors>(\n                    InputNoDataPolicy{{argument.mask(), true}},\n                    output_no_data_policy,\n                    sequential,\n                    argument, kernel, result);\n\n            compare_result5(result);\n        }\n\n        // Parallel.\n        {\n            fern::MaskedArray<double, 2> result(extents);\n            fa::convolution::convolve(sequential, argument, kernel,\n                result);\n            OutputNoDataPolicy output_no_data_policy(result.mask(), true);\n\n            fa::convolution::convolve<\n                fa::convolve::SkipNoData,\n                fa::convolve::DontDivideByWeights,\n                fa::convolve::SkipOutOfImage,\n                fa::convolve::ReplaceNoDataFocusElement,\n                fa::unary::DiscardRangeErrors>(\n                    InputNoDataPolicy{{argument.mask(), true}},\n                    output_no_data_policy,\n                    parallel,\n                    argument, kernel, result);\n\n            compare_result5(result);\n        }\n    }\n\n    {\n        // Create input array:\n        // +----+----+----+----+----+----+\n        // |  X |  X |  X |  X |  X |  X |\n        // +----+----+----+----+----+----+\n        // |  X |  X |  8 |  9 |  X |  X |\n        // +----+----+----+----+----+----+\n        // |  X | 13 | 14 | 15 | 16 |  X |\n        // +----+----+----+----+----+----+\n        // | 18 | 19 | 20 | 21 | 22 | 23 |\n        // +----+----+----+----+----+----+\n        // |  X | 25 | 26 | 27 | 28 |  X |\n        // +----+----+----+----+----+----+\n        // |  X |  X | 32 | 33 |  X |  X |\n        // +----+----+----+----+----+----+\n        // |  X |  X | 38 |  X |  X |  X |\n        // +----+----+----+----+----+----+\n\n        size_t const nr_rows = 7;\n        size_t const nr_cols = 6;\n        auto extents = fern::extents[nr_rows][nr_cols];\n        fern::MaskedArray<double, 2> argument(extents);\n\n        std::iota(argument.data(), argument.data() + argument.num_elements(),\n            0);\n        argument.mask() = {\n            {  true,  true,  true,  true,  true,  true },\n            {  true,  true, false, false,  true,  true },\n            {  true, false, false, false, false,  true },\n            { false, false, false, false, false, false },\n            {  true, false, false, false, false,  true },\n            {  true,  true, false, false,  true,  true },\n            {  true,  true, false,  true,  true,  true }\n        };\n\n\n        // Define kernel shape and weights.\n        // Similar to PCRaster's window4total algorithm.\n        fern::Square<bool, 1> kernel({\n            { false,  true, false },\n            {  true, false,  true },\n            { false,  true, false }\n        });\n\n        // Sequential.\n        {\n            fern::MaskedArray<double, 2> result(extents);\n            // fa::convolution::convolve(sequential, argument, kernel,\n            //     result);\n            OutputNoDataPolicy output_no_data_policy(result.mask(), true);\n\n            fa::convolution::convolve<\n                fa::convolve::SkipNoData,\n                fa::convolve::DontDivideByWeights,\n                fa::convolve::SkipOutOfImage,\n                fa::convolve::ReplaceNoDataFocusElement,\n                fa::unary::DiscardRangeErrors>(\n                    InputNoDataPolicy{{argument.mask(), true}},\n                    output_no_data_policy,\n                    sequential,\n                    argument, kernel, result);\n\n            compare_result6(result);\n        }\n\n        // Parallel.\n        {\n            fern::MaskedArray<double, 2> result(extents);\n            OutputNoDataPolicy output_no_data_policy(result.mask(), true);\n\n            fa::convolution::convolve<\n                fa::convolve::SkipNoData,\n                fa::convolve::DontDivideByWeights,\n                fa::convolve::SkipOutOfImage,\n                fa::convolve::ReplaceNoDataFocusElement,\n                fa::unary::DiscardRangeErrors>(\n                    InputNoDataPolicy{{argument.mask(), true}},\n                    output_no_data_policy,\n                    parallel,\n                    argument, kernel, result);\n\n            compare_result6(result);\n        }\n    }\n}\n\n\ntemplate<\n    typename T>\nvoid compare_result_use_case1(\n    fern::MaskedArray<T, 2> const& result)\n{\n    // +-----+-----+-----+\n    // | 0.0 | 0.0 | 0.0 |\n    // +-----+-----+-----+\n    // | 0.0 | 0.0 | 0.0 |\n    // +-----+-----+-----+\n    // | 0.0 | 0.0 | 0.0 |\n    // +-----+-----+-----+\n\n    std::vector<bool> no_data = {\n        false, false, false,\n        false, false, false,\n        false, false, false\n    };\n\n    BOOST_REQUIRE_EQUAL_COLLECTIONS(no_data.begin(), no_data.end(),\n        result.mask().data(), result.mask().data() +\n            result.mask().num_elements());\n\n\n    std::vector<T> values = {\n        0.0, 0.0, 0.0,\n        0.0, 0.0, 0.0,\n        0.0, 0.0, 0.0\n    };\n\n    BOOST_REQUIRE_EQUAL_COLLECTIONS(values.begin(), values.end(),\n        result.data(), result.data() + result.num_elements());\n}\n\n\ntemplate<\n    typename T>\nvoid test_use_case1(\n    T const& value)\n{\n    using InputNoDataPolicy = fa::InputNoDataPolicies<\n        fa::DetectNoDataByValue<fern::Mask<2>>>;\n    using OutputNoDataPolicy = fa::MarkNoDataByValue<fern::Mask<2>>;\n\n    fa::ParallelExecutionPolicy parallel;\n    fa::SequentialExecutionPolicy sequential;\n\n    // +-------+-------+-------+\n    // | value | value | value |\n    // +-------+-------+-------+\n    // | value | value | value |\n    // +-------+-------+-------+\n    // | value | value | value |\n    // +-------+-------+-------+\n\n    size_t const nr_rows = 3;\n    size_t const nr_cols = 3;\n    auto extents = fern::extents[nr_rows][nr_cols];\n    fern::MaskedArray<T, 2> argument(extents);\n\n    std::fill(argument.data(), argument.data() + argument.num_elements(),\n        value);\n\n    fern::Square<T, 1> kernel({\n        {1, 0, -1},\n        {2, 0, -2},\n        {1, 0, -1}\n    });\n\n\n    // Sequential.\n    {\n        fern::MaskedArray<T, 2> result(extents);\n        OutputNoDataPolicy output_no_data_policy(result.mask(), true);\n\n        fa::convolution::convolve<\n            fa::convolve::ReplaceNoDataByFocalAverage,\n            fa::convolve::DontDivideByWeights,\n            fa::convolve::ReplaceOutOfImageByFocalAverage,\n            fa::convolve::KeepNoDataFocusElement,\n            fa::unary::DiscardRangeErrors>(\n                InputNoDataPolicy{{argument.mask(), true}},\n                output_no_data_policy,\n                sequential,\n                argument, kernel, result);\n\n        compare_result_use_case1(result);\n    }\n\n    // Parallel.\n    {\n        fern::MaskedArray<T, 2> result(extents);\n        OutputNoDataPolicy output_no_data_policy(result.mask(), true);\n\n        fa::convolution::convolve<\n            fa::convolve::ReplaceNoDataByFocalAverage,\n            fa::convolve::DontDivideByWeights,\n            fa::convolve::ReplaceOutOfImageByFocalAverage,\n            fa::convolve::KeepNoDataFocusElement,\n            fa::unary::DiscardRangeErrors>(\n                InputNoDataPolicy{{argument.mask(), true}},\n                output_no_data_policy,\n                parallel,\n                argument, kernel, result);\n\n        compare_result_use_case1(result);\n    }\n}\n\n\nBOOST_AUTO_TEST_CASE(use_case1)\n{\n    for(auto const& value: {0.0, 0.055, 0.0925, 0.1, 0.1225, 0.17, 1.0}) {\n        test_use_case1<float>(value);\n    }\n}\n", "meta": {"hexsha": "d224a29807095a0ab23056b40454744fa4885a0d", "size": 49976, "ext": "cc", "lang": "C++", "max_stars_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/fern/source/fern/algorithm/convolution/test/convolve_test.cc", "max_stars_repo_name": "quanpands/wflow", "max_stars_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/fern/source/fern/algorithm/convolution/test/convolve_test.cc", "max_issues_repo_name": "quanpands/wflow", "max_issues_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/fern/source/fern/algorithm/convolution/test/convolve_test.cc", "max_forks_repo_name": "quanpands/wflow", "max_forks_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.0900409277, "max_line_length": 84, "alphanum_fraction": 0.4614414919, "num_tokens": 14778, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.4723332226005753}}
{"text": "#include <SDL.h> // Needed because it messes with main()\n\n#include <iostream>\n#include <string>\n#include <math.h>\n\n#include <boost/thread.hpp> \n#include <boost/date_time/posix_time/posix_time.hpp>\n#include \"asynch_serial/buffered_async_serial.h\"\n\n#include \"sdl_joystick.h\"\n\nusing namespace boost;\nusing boost::posix_time::ptime;\nusing boost::posix_time::time_duration;\n//using boost::posix_time::microsec_clock::local_time;\n\n//Analog joystick dead zone\nconst double JOYSTICK_DEAD_ZONE = 0.15;\n#define PI 3.14159265\n\nstring mecanum_control() {\n  char command[100];\n\n  // Input 0: X -left +right\n  // Input 1: Y -up +down\n  // Input 2: R -left + right\n\n  double x = (double)controller_state[0][0] / 32768;\n  double y = (double)controller_state[0][1] / 32768;\n\n  double r = (double)controller_state[0][2] / 32768;\n\n  double theta;\n  double magnitude;\n\n  // Clamp input within the dead zone\n  if(x > -JOYSTICK_DEAD_ZONE && x < JOYSTICK_DEAD_ZONE && y > -JOYSTICK_DEAD_ZONE && y < JOYSTICK_DEAD_ZONE) {\n    x = 0.0;\n    y = 0.0;\n    theta = 0.0;\n    magnitude = 0.0;\n  } else {\n    // Turn x and y into polar coordinate (angle, magnitude clamped to 1.0)\n    theta = atan2(x, -y);\n    if(theta < 0.0) theta += 2*PI;\n    magnitude = sqrt(x*x + y*y);\n    if(magnitude > 1.0) magnitude = 1.0;\n  }\n\n  if(r > -JOYSTICK_DEAD_ZONE && r < JOYSTICK_DEAD_ZONE) r = 0.0;\n\n\n  // Original wheel positions\n  /*\n  // wheels: 1: RF 2: RR 3: LR 4: LF\n  // forward  =  1  1  1  1  (theta = 0)\n  // right    =  1 -1  1 -1  (theta = pi/2)\n  // backward = -1 -1 -1 -1  (theta = pi)\n  // left     = -1  1 -1  1  (theta = 3 pi/2)\n\n  // Desired motor movement for translation commands at full speed. (Forward/backward, left/right)\n  double m1, m2, m3, m4;\n\n  if(theta >= 0.0 && theta < PI/2) {\n    m1 = m3 =  1.0;\n    m2 = m4 =  1.0 - 4*theta/PI;\n  } else if(theta >= PI/2 && theta < PI) {\n    m1 = m3 = 1.0 - 4*(theta - PI/2)/PI;\n    m2 = m4 = -1.0;\n  } else if(theta >= PI && theta < 3*PI/2) {\n    m1 = m3 = -1.0;\n    m2 = m4 = -1.0 + 4*(theta - PI)/PI;\n  } else {\n    m1 = m3 = -1.0 + 4*(theta - 3*PI/2)/PI;\n    m2 = m4 = 1.0;\n  }\n  */\n\n  // Swapped wheel positions\n  // wheels: 1: RF 2: RR 3: LR 4: LF\n  // forward  =  1  1  1  1  (theta = 0)\n  // right    = -1  1 -1  1  (theta = pi/2)\n  // backward = -1 -1 -1 -1  (theta = pi)\n  // left     =  1 -1  1 -1  (theta = 3 pi/2)\n\n  // Desired motor movement for translation commands at full speed. (Forward/backward, left/right)\n  double m1, m2, m3, m4;\n\n  if(theta >= 0.0 && theta < PI/2) {\n    m1 = m3 =  1.0 - 4*theta/PI;\n    m2 = m4 =  1.0;\n  } else if(theta >= PI/2 && theta < PI) {\n    m1 = m3 = -1.0;\n    m2 = m4 = 1.0 - 4*(theta - PI/2)/PI;\n  } else if(theta >= PI && theta < 3*PI/2) {\n    m1 = m3 = -1.0 + 4*(theta - PI)/PI;\n    m2 = m4 = -1.0;\n  } else {\n    m1 = m3 = 1.0;\n    m2 = m4 = -1.0 + 4*(theta - 3*PI/2)/PI;\n  }\n\n\n  // Scale by the magnitude of the control vector\n  m1 *= magnitude;\n  m2 *= magnitude;\n  m3 *= magnitude;\n  m4 *= magnitude;\n\n  // Desired motor movement for rotation commands. (Left/right)\n  double r1, r2, r3, r4;\n  double r_mag = abs(r);\n\n  r1 = -r;\n  r2 = -r;\n  r3 = r;\n  r4 = r;\n\n  // Weighted average the translation and rotation desired movements\n  // Avoid the possibility of inflated commands from small inputs\n  if(magnitude + r_mag > JOYSTICK_DEAD_ZONE) {\n    m1 = (m1 * magnitude + r1 * r_mag) / (magnitude + r_mag);\n    m2 = (m2 * magnitude + r2 * r_mag) / (magnitude + r_mag);\n    m3 = (m3 * magnitude + r3 * r_mag) / (magnitude + r_mag);\n    m4 = (m4 * magnitude + r4 * r_mag) / (magnitude + r_mag);\n  }\n\n  cout << \"                         \" << x << \" \" << y << \" \" << theta << \" \"  << magnitude << \" \" << r << \" \" << r1 << \" \" << r2 << \" \" << r3 << \" \" << r4 << endl;\n  sprintf(command, \"M %d %d %d %d \\r\\n\", (int)(m1 * 255), (int)(m2 * 255), (int)(m3 * 255), (int)(m4 * 255));\n  //cout << command << endl;\n\n  //return \"M 0 0 0 0\\r\\n\";\n  return command;\n  \n}\n\n\n\nint main(int argc, char* argv[]) {\n  string port = \"COM8\";\n  if(argc > 1) {\n    port = argv[1];\n  }\n  cout << \"Using port: \" << port.c_str() << endl;\n  try {\n\n    BufferedAsyncSerial serial(port.c_str(),115200);\n    this_thread::sleep(posix_time::seconds(2)); // Let the serial port finish initializing\n\n    if(!init_stl()) {\n      cout << \"Failed to initialize STL.\" << endl;\n    } else {\n      ptime now(boost::posix_time::microsec_clock::local_time());\n      ptime last_msg(boost::posix_time::microsec_clock::local_time());\n      time_duration dt;\n\n      string response;\n      string last_command = \"M 0 0 0 0\\r\\n\"; // Record last command to avoid spamming the serial line with duplicates.\n\n      serial.writeString(last_command.c_str());\n      this_thread::sleep(posix_time::seconds(2));\n      cout << \"Initial command response: \" << serial.readStringUntil(\"\\r\\n\") << endl;\n\n      bool done = false;\n      bool event_happened = false;\n      while(!done) {\n        // Check for a message from the rover.\n        response = serial.readStringUntil(\"\\r\\n\");\n        if(response.length() > 0) {\n          cout << \"Response: \" << response << endl;\n        }\n        // Check for controller input.\n        stl_event_wait(done, event_happened);\n        if(!done && event_happened) {\n          //cout << \"event!\" << endl;\n          now = boost::posix_time::microsec_clock::local_time();\n          dt = now - last_msg;\n          if(dt.total_milliseconds() > 20) {\n            string command = mecanum_control();\n            if(command != last_command) {\n              last_msg = now;\n              serial.writeString(command.c_str());\n              cout << command;\n              last_command = command;\n            }\n          }\n        }\n      }\n    }\n\n    close_stl(); // Free resources and close SDL\n    serial.close();\n  } catch(boost::system::system_error& e) {\n    cout << \"Error: \" << e.what() << endl;\n    return -1;\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "71f00f3dc5e7700c6d1a9b9e6cf851632b975b37", "size": 5873, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Mecanum Wheel Rover/PC Controller Software/mecanum_drive.cpp", "max_stars_repo_name": "gchristopher/3dprinting", "max_stars_repo_head_hexsha": "8fdb722ced4222dcd4c2eab56f08b1f3aade0aaf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2016-01-31T20:36:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T13:05:44.000Z", "max_issues_repo_path": "Mecanum Wheel Rover/PC Controller Software/mecanum_drive.cpp", "max_issues_repo_name": "gchristopher/3dprinting", "max_issues_repo_head_hexsha": "8fdb722ced4222dcd4c2eab56f08b1f3aade0aaf", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Mecanum Wheel Rover/PC Controller Software/mecanum_drive.cpp", "max_forks_repo_name": "gchristopher/3dprinting", "max_forks_repo_head_hexsha": "8fdb722ced4222dcd4c2eab56f08b1f3aade0aaf", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-09-13T03:45:45.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-13T03:45:45.000Z", "avg_line_length": 29.2189054726, "max_line_length": 164, "alphanum_fraction": 0.5610420569, "num_tokens": 1958, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424528443251, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.4723125070772663}}
{"text": "#include <iostream>\n#include <fstream>\n#include <algorithm>\n#include <vector>\n#include <tuple>\n#include <random>\n#include <iterator>\n#include <numeric>\n\n#include <boost/numeric/ublas/storage.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n#include \"VNS.hpp\"\n#include \"MODI.hpp\"\n#include \"Solution.hpp\"\n#include \"Helper.hpp\"\n\nusing namespace std;\nusing namespace t_simplex;\nnamespace ublas = boost::numeric::ublas;\n\n/*********************************************************************************/\n/*                            UPDATE XIJ PROCEDURES                              */\n/*********************************************************************************/\n\n// CFLP with Modi procedure (gets optimal solution in deterministic time)\nbool VNS::updateXij(\n\tublas::matrix<double> &cij,\n\tconst vector<double> &dj,\n\tconst vector<double> &bi,\n\tconst vector<bool> &yi,\n\tconst unsigned int &update_xij_mode,\n\tdouble &fx)\n{\n\tif (!canUpdateXij(bi, yi, m_sum_dj))\n\t\treturn false;\n\n\tunsigned int open_facilities = 0, i_out = 0, flow_vars = 0;\n\tdouble transportation_cost = 0.0, gap = 0.0, sum_bi = 0.0;\n\tbool check = false;\n\n\topen_facilities = accumulate(yi.begin(), yi.end(), 0);\n\n\tublas::matrix<double> custom_cij(open_facilities, m_customerNumber, 0.0);\n\n\tint *customers = new int[m_customerNumber];\n\tdouble *demand = new double[m_customerNumber];\n\tint *facilities = new int[open_facilities];\n\tdouble *capacity = new double[open_facilities];\n\n\tfor (size_t j = 0; j != cij.size2(); ++j)\n\t{\n\t\tcustomers[j] = j;\n\t\tdemand[j] = dj[j];\n\t}\n\n\tfor (size_t i = 0; i != cij.size1(); ++i)\n\t{\n\t\tif (yi[i] == 1)\n\t\t{\n\t\t\tfacilities[i_out] = i;\n\t\t\tcapacity[i_out] = bi[i];\n\t\t\tsum_bi += bi[i];\n\n\t\t\tublas::matrix_row<ublas::matrix<double>> row_custom_cij(custom_cij, i_out);\n\t\t\tublas::matrix_row<ublas::matrix<double>> row_cij(cij, i);\n\t\t\trow_custom_cij = row_cij;\n\n\t\t\ti_out++;\n\t\t}\n\t}\n\n\t// Signature of Facilities and Customers\n\tTsSignature *facility = new TsSignature(open_facilities, facilities, capacity);\n\tTsSignature *customer = new TsSignature(m_customerNumber, customers, demand);\n\t// Save Stepping Stone Path\n\tTsFlow *flow = new TsFlow[open_facilities + m_customerNumber - 1];\n\n\t// Result value\n\ttransportation_cost = t_simplex::transportSimplex(update_xij_mode, custom_cij, flow, \n\t\t&flow_vars, facility, customer ,m_sum_dj, sum_bi, dj);\n\n\t// f(x) and Return Value\n\tfx = f(yi, m_fi, transportation_cost);\n\n\t// Flow Xij for checkSolution\n\tm_flow_tpl.resize(flow_vars);\n\tfor (size_t i = 0; i < flow_vars; ++i)\n\t\tm_flow_tpl[i] = make_tuple(facilities[flow[i].from], flow[i].to, flow[i].amount);\n\n\tcheck = checkSolution(yi, m_flow_tpl, flow_vars, cij, bi, dj, m_sum_dj);\n\n\tdelete[] capacity;\n\tcapacity = NULL;\n\tdelete[] demand;\n\tdemand = NULL;\n\tdelete[] facilities;\n\tfacilities = NULL;\n\tdelete[] customers;\n\tcustomers = NULL;\n\tdelete facility;\n\tfacility = NULL;\n\tdelete customer;\n\tcustomer = NULL;\n\n\treturn check;\n}", "meta": {"hexsha": "cae8ba23e4c236a425e2163b221e920f64f157ac", "size": 2987, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "VNS Implementierung/VNS Implementierung/UpdateXij.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/UpdateXij.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/UpdateXij.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.4036697248, "max_line_length": 86, "alphanum_fraction": 0.6551724138, "num_tokens": 814, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406087, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.4723124940661724}}
{"text": "/*\n * \n * Copyright (c) Kresimir Fresl 2002 \n *\n * Permission to copy, modify, use and distribute this software \n * for any non-commercial or commercial purpose is granted provided \n * that this license appear on all copies of the software source code.\n *\n * Author assumes no responsibility whatsoever for its use and makes \n * no guarantees about its quality, correctness or reliability.\n *\n * Author acknowledges the support of the Faculty of Civil Engineering, \n * University of Zagreb, Croatia.\n *\n */\n\n#ifndef BOOST_NUMERIC_BINDINGS_CLAPACK_HPP\n#define BOOST_NUMERIC_BINDINGS_CLAPACK_HPP\n\n#include <cassert>\n#include <new>\n\n#include <boost/numeric/bindings/traits/traits.hpp>\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n#  include <boost/numeric/bindings/traits/detail/symm_herm_traits.hpp>\n#endif \n#include <boost/numeric/bindings/atlas/cblas_enum.hpp>\n\n// see libs/numeric/bindings/atlas/doc/index.html, section 2.5.2\n//#define BOOST_NUMERIC_BINDINGS_ATLAS_POTRF_BUG\n\n#include <boost/numeric/bindings/atlas/clapack_overloads.hpp>\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n#  include <boost/static_assert.hpp>\n#  include <boost/type_traits/same_traits.hpp>\n#endif\n\n\nnamespace boost { namespace numeric { namespace bindings { \n\n  namespace atlas {\n\n    /////////////////////////////////////////////////////////////////////\n    //\n    // general system of linear equations A * X = B\n    // \n    /////////////////////////////////////////////////////////////////////\n\n    // gesv(): 'driver' function \n    //\n    // [comments from 'clapack_dgesv.c':]\n    /* clapack_xgesv computes the solution to a system of linear equations\n     *   A * X = B,\n     * where A is an N-by-N matrix and X and B are N-by-NRHS matrices.\n     */\n    // [but ATLAS FAQ says:]\n    /* What's the deal with the RHS in the row-major factorization/solves?\n     * Most users are confused by the row major factorization and related \n     * solves. The right-hand side vectors are probably the biggest source \n     * of confusion. The RHS array does not represent a matrix in the \n     * mathematical sense, it is instead a pasting together of the various \n     * RHS into one array for calling convenience. As such, RHS vectors are \n     * always stored contiguously, regardless of the row/col major that is \n     * chosen. This means that ldb/ldx is always independent of NRHS, and \n     * dependant on N, regardless of the row/col major setting. \n     */ \n    // That is, it seems that, if B is row-major, it should be NRHS-by-N, \n    // and RHS vectors should be its rows, not columns. \n    //\n    // [comments from 'clapack_dgesv.c':]\n    /* The LU factorization used to factor A is dependent on the Order \n     * parameter, as detailed in the leading comments of clapack_dgetrf.\n     * The factored form of A is then used to solve the system of equations \n     *   A * X = B.\n     * A is overwritten with the appropriate LU factorization, and B [...]\n     * is overwritten with the solution X on output.\n     */\n    // If B is row-major, solution vectors are its rows. \n    template <typename MatrA, typename MatrB, typename IVec>\n    inline\n    int gesv (MatrA& a, IVec& ipiv, MatrB& b) {\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrA>::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\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrA>::ordering_type,\n        typename traits::matrix_traits<MatrB>::ordering_type\n      >::value)); \n#endif \n\n      CBLAS_ORDER const stor_ord\n        = enum_cast<CBLAS_ORDER const>\n        (storage_order<\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n           typename traits::matrix_traits<MatrA>::ordering_type\n#else\n           typename MatrA::orientation_category \n#endif \n         >::value); \n\n      int const n = traits::matrix_size1 (a);\n      int const nrhs = stor_ord == CblasColMajor\n        ? traits::matrix_size2 (b)\n        : traits::matrix_size1 (b); \n      assert (n == traits::matrix_size2 (a)); \n      assert (n == (stor_ord == CblasColMajor\n                    ? traits::matrix_size1 (b)\n                    : traits::matrix_size2 (b))); \n      assert (n == traits::vector_size (ipiv)); \n\n      return detail::gesv (stor_ord, n, nrhs, \n                           traits::matrix_storage (a), \n                           traits::leading_dimension (a),\n                           traits::vector_storage (ipiv),  \n                           traits::matrix_storage (b),\n                           traits::leading_dimension (b));\n    }\n\n    template <typename MatrA, typename MatrB>\n    inline\n    int gesv (MatrA& a, MatrB& b) {\n      // with 'internal' pivot vector\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrA>::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\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrA>::ordering_type,\n        typename traits::matrix_traits<MatrB>::ordering_type\n      >::value)); \n#endif \n\n      CBLAS_ORDER const stor_ord\n        = enum_cast<CBLAS_ORDER const>\n        (storage_order<\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n           typename traits::matrix_traits<MatrA>::ordering_type\n#else\n           typename MatrA::orientation_category \n#endif \n         >::value); \n\n      int const n = traits::matrix_size1 (a);\n      int const nrhs = stor_ord == CblasColMajor\n        ? traits::matrix_size2 (b)\n        : traits::matrix_size1 (b); \n      assert (n == traits::matrix_size2 (a)); \n      assert (n == (stor_ord == CblasColMajor\n                    ? traits::matrix_size1 (b)\n                    : traits::matrix_size2 (b))); \n\n      int *ipiv = new (std::nothrow) int[n]; \n      int ierr = -101;  \n      // clapack_dgesv() errors: \n      //   if (ierr == 0), successful\n      //   if (ierr < 0), the -ierr argument had an illegal value\n      //   -- we will use -101 if allocation fails\n      //   if (ierr > 0), U(i-1,i-1) (or L(i-1,i-1)) is exactly zero \n \n      if (ipiv) {\n        ierr = detail::gesv (stor_ord, n, nrhs, \n                             traits::matrix_storage (a), \n                             traits::leading_dimension (a),\n                             ipiv,  \n                             traits::matrix_storage (b),\n                             traits::leading_dimension (b));\n        delete[] ipiv; \n      }\n      return ierr; \n    }\n\n    template <typename MatrA, typename MatrB>\n    inline\n    int lu_solve (MatrA& a, MatrB& b) {\n      return gesv (a, b); \n    }\n\n\n    // getrf(): LU factorization of A\n    // [comments from 'clapack_dgetrf.c':]\n    /* Computes one of two LU factorizations based on the setting of \n     * the Order parameter, as follows:\n     * ---------------------------------------------------------------\n     *                     Order == CblasColMajor\n     * Column-major factorization of form\n     *   A = P * L * U\n     * where P is a row-permutation matrix, L is lower triangular with\n     * unit diagonal elements (lower trapezoidal if M > N), and U is \n     * upper triangular (upper trapezoidal if M < N).\n     * ---------------------------------------------------------------\n     *                     Order == CblasRowMajor\n     * Row-major factorization of form\n     *   A = P * L * U\n     * where P is a column-permutation matrix, L is lower triangular \n     * (lower trapezoidal if M > N), and U is upper triangular with \n     * unit diagonals (upper trapezoidal if M < N).\n     */\n    template <typename MatrA, typename IVec> \n    inline\n    int getrf (MatrA& a, IVec& ipiv) {\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrA>::matrix_structure, \n        traits::general_t\n      >::value)); \n#endif \n\n      CBLAS_ORDER const stor_ord\n        = enum_cast<CBLAS_ORDER const>\n        (storage_order<\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n           typename traits::matrix_traits<MatrA>::ordering_type\n#else\n           typename MatrA::orientation_category \n#endif \n         >::value); \n\n      int const m = traits::matrix_size1 (a);\n      int const n = traits::matrix_size2 (a); \n      assert (traits::vector_size (ipiv) == (m < n ? m : n)); \n\n      return detail::getrf (stor_ord, m, n, \n                            traits::matrix_storage (a), \n                            traits::leading_dimension (a),\n                            traits::vector_storage (ipiv)); \n    }\n\n    template <typename MatrA, typename IVec> \n    inline\n    int lu_factor (MatrA& a, IVec& ipiv) {\n      return getrf (a, ipiv); \n    }\n\n\n    // getrs(): solves a system of linear equations\n    //          A * X = B  or  A' * X = B\n    //          using the LU factorization previously computed by getrf()\n    template <typename MatrA, typename MatrB, typename IVec>\n    inline\n    int getrs (CBLAS_TRANSPOSE const Trans, \n               MatrA const& a, IVec const& ipiv, MatrB& b) \n    {\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrA>::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\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrA>::ordering_type,\n        typename traits::matrix_traits<MatrB>::ordering_type\n      >::value)); \n#endif \n\n      assert (Trans == CblasNoTrans \n              || Trans == CblasTrans \n              || Trans == CblasConjTrans); \n\n      CBLAS_ORDER const stor_ord\n        = enum_cast<CBLAS_ORDER const>\n        (storage_order<\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n           typename traits::matrix_traits<MatrA>::ordering_type\n#else\n           typename MatrA::orientation_category \n#endif \n         >::value); \n\n      int const n = traits::matrix_size1 (a);\n      int const nrhs = stor_ord == CblasColMajor\n        ? traits::matrix_size2 (b)\n        : traits::matrix_size1 (b); \n      assert (n == traits::matrix_size2 (a)); \n      assert (n == (stor_ord == CblasColMajor\n                    ? traits::matrix_size1 (b)\n                    : traits::matrix_size2 (b))); \n      assert (n == traits::vector_size (ipiv)); \n      \n      return detail::getrs (stor_ord, Trans, n, nrhs, \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 (ipiv),  \n#else\n                            traits::vector_storage_const (ipiv),  \n#endif\n                            traits::matrix_storage (b),\n                            traits::leading_dimension (b)); \n    }\n\n    // getrs(): solves A * X = B (after getrf())\n    template <typename MatrA, typename MatrB, typename IVec>\n    inline\n    int getrs (MatrA const& a, IVec const& ipiv, MatrB& b) {\n      return getrs (CblasNoTrans, a, ipiv, b); \n    }\n\n    template <typename MatrA, typename MatrB, typename IVec>\n    inline\n    int lu_substitute (MatrA const& a, IVec const& ipiv, MatrB& b) {\n      return getrs (CblasNoTrans, a, ipiv, b); \n    }\n\n\n    // getri(): computes the inverse of a matrix A \n    //          using the LU factorization previously computed by getrf() \n    template <typename MatrA, typename IVec> \n    inline\n    int getri (MatrA& a, IVec const& ipiv) {\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrA>::matrix_structure, \n        traits::general_t\n      >::value)); \n#endif \n\n      CBLAS_ORDER const stor_ord\n        = enum_cast<CBLAS_ORDER const>\n        (storage_order<\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n           typename traits::matrix_traits<MatrA>::ordering_type\n#else\n           typename MatrA::orientation_category \n#endif \n         >::value); \n\n      int const n = traits::matrix_size1 (a);\n      assert (n == traits::matrix_size2 (a)); \n      assert (traits::vector_size (ipiv) == n); \n\n      return detail::getri (stor_ord, n, \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                            ); \n    }\n\n    template <typename MatrA, typename IVec> \n    inline\n    int lu_invert (MatrA& a, IVec& ipiv) {\n      return getri (a, ipiv); \n    }\n\n\n\n    /////////////////////////////////////////////////////////////////////\n    //\n    // system of linear equations A * X = B\n    // with A symmetric or Hermitian positive definite matrix\n    //\n    /////////////////////////////////////////////////////////////////////\n\n#ifndef BOOST_NUMERIC_BINDINGS_ATLAS_POTRF_BUG\n    // posv(): 'driver' function \n    //\n    // [from 'dposv.f' (slightly edited):]\n    /* XPOSV computes the solution to a system of linear equations\n     *    A * X = B,\n     * where A is an N-by-N symmetric/Hermitian positive definite matrix \n     * and X and B are N-by-NRHS matrices. [See also comments of gesv().]\n     *\n     * A -- On entry, the symmetric/Hermitian matrix A.  \n     * If UPLO = 'U', the leading N-by-N upper triangular part of A \n     * contains the upper triangular part of the matrix A, and the \n     * strictly lower triangular part of A is not referenced.  \n     * If UPLO = 'L', the leading N-by-N lower triangular part of A \n     * contains the lower triangular part of the matrix A, and the \n     * strictly upper triangular part of A is not referenced.\n     *\n     * On exit, if INFO = 0, the factor U or L from the Cholesky\n     * factorization A = U**T*U or A = L*L**T\n     * [or A = U**H*U or A = L*L**H]. \n     *\n     * B -- On entry, the right hand side matrix B.\n     * On exit, if INFO = 0, the solution matrix X.\n     */\n    namespace detail {\n\n      template <typename SymmA, typename MatrB>\n      inline\n      int posv (CBLAS_UPLO const uplo, SymmA& a, MatrB& b) {\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n        BOOST_STATIC_ASSERT((boost::is_same<\n          typename traits::matrix_traits<SymmA>::ordering_type,\n          typename traits::matrix_traits<MatrB>::ordering_type\n        >::value)); \n#endif \n\n        CBLAS_ORDER const stor_ord\n          = enum_cast<CBLAS_ORDER const>\n          (storage_order<\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n            typename traits::matrix_traits<SymmA>::ordering_type\n#else\n            typename SymmA::orientation_category \n#endif \n           >::value); \n\n        int const n = traits::matrix_size1 (a);\n        int const nrhs = stor_ord == CblasColMajor\n          ? traits::matrix_size2 (b)\n          : traits::matrix_size1 (b); \n        assert (n == traits::matrix_size2 (a)); \n        assert (n == (stor_ord == CblasColMajor\n                      ? traits::matrix_size1 (b)\n                      : traits::matrix_size2 (b))); \n\n        return posv (stor_ord, uplo, n, nrhs, \n                     traits::matrix_storage (a), \n                     traits::leading_dimension (a),\n                     traits::matrix_storage (b),\n                     traits::leading_dimension (b));\n      }\n\n    } // detail \n\n    template <typename SymmA, typename MatrB>\n    inline\n    int posv (CBLAS_UPLO const uplo, SymmA& a, MatrB& b) {\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      assert (uplo == CblasUpper || uplo == CblasLower); \n      return detail::posv (uplo, a, b); \n    }\n\n    template <typename SymmA, typename MatrB>\n    inline\n    int posv (SymmA& a, MatrB& b) {\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n      typedef typename traits::matrix_traits<SymmA>::value_type val_t;\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<SymmA>::matrix_structure, \n        typename traits::detail::symm_herm_t<val_t>::type\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      CBLAS_UPLO const uplo\n        = enum_cast<CBLAS_UPLO const>\n        (uplo_triang<\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n          typename traits::matrix_traits<SymmA>::uplo_type\n#else\n          typename SymmA::packed_category \n#endif \n         >::value); \n      \n      return detail::posv (uplo, a, b); \n    }\n\n    template <typename SymmA, typename MatrB>\n    inline\n    int cholesky_solve (SymmA& a, MatrB& b) { return posv (a, b); }\n#endif // BOOST_NUMERIC_BINDINGS_ATLAS_POTRF_BUG\n\n\n    // potrf(): Cholesky factorization of A \n    namespace detail {\n\n      template <typename SymmA>\n      inline\n      int potrf (CBLAS_UPLO const uplo, SymmA& a) {\n\n        CBLAS_ORDER const stor_ord\n          = enum_cast<CBLAS_ORDER const>\n          (storage_order<\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n            typename traits::matrix_traits<SymmA>::ordering_type\n#else\n            typename SymmA::orientation_category \n#endif \n           >::value); \n\n        int const n = traits::matrix_size1 (a);\n        assert (n == traits::matrix_size2 (a)); \n\n        return potrf (stor_ord, uplo, n, \n                      traits::matrix_storage (a), \n                      traits::leading_dimension (a));\n      }\n\n    } // detail \n\n    template <typename SymmA>\n    inline\n    int potrf (CBLAS_UPLO const uplo, SymmA& a) {\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 (uplo == CblasUpper || uplo == CblasLower); \n      return detail::potrf (uplo, a); \n    } \n\n    template <typename SymmA>\n    inline\n    int potrf (SymmA& a) {\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n      typedef typename traits::matrix_traits<SymmA>::value_type val_t;\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<SymmA>::matrix_structure, \n        typename traits::detail::symm_herm_t<val_t>::type\n      >::value)); \n#endif \n\n      CBLAS_UPLO const uplo\n        = enum_cast<CBLAS_UPLO const>\n        (uplo_triang<\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n          typename traits::matrix_traits<SymmA>::uplo_type\n#else\n          typename SymmA::packed_category \n#endif \n         >::value); \n      \n      return detail::potrf (uplo, a); \n    }\n\n    template <typename SymmA>\n    inline\n    int cholesky_factor (SymmA& a) { return potrf (a); }\n\n\n    // potrs(): solves a system of linear equations A * X = B\n    //          using the Cholesky factorization computed by potrf()\n    namespace detail {\n\n      template <typename SymmA, typename MatrB>\n      inline\n      int potrs (CBLAS_UPLO const uplo, SymmA const& a, MatrB& b) {\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n        BOOST_STATIC_ASSERT((boost::is_same<\n          typename traits::matrix_traits<SymmA>::ordering_type,\n          typename traits::matrix_traits<MatrB>::ordering_type\n        >::value)); \n#endif \n\n        CBLAS_ORDER const stor_ord\n          = enum_cast<CBLAS_ORDER const>\n          (storage_order<\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n            typename traits::matrix_traits<SymmA>::ordering_type\n#else\n            typename SymmA::orientation_category \n#endif \n           >::value); \n\n        int const n = traits::matrix_size1 (a);\n        int const nrhs = stor_ord == CblasColMajor\n          ? traits::matrix_size2 (b)\n          : traits::matrix_size1 (b); \n        assert (n == traits::matrix_size2 (a)); \n        assert (n == (stor_ord == CblasColMajor\n                      ? traits::matrix_size1 (b)\n                      : traits::matrix_size2 (b))); \n\n#ifndef BOOST_NUMERIC_BINDINGS_ATLAS_POTRF_BUG\n        return potrs (stor_ord, uplo, n, nrhs, \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                      traits::matrix_storage (b),\n                      traits::leading_dimension (b));\n#else // BOOST_NUMERIC_BINDINGS_ATLAS_POTRF_BUG\n        int ierr; \n        if (stor_ord == CblasColMajor)\n          ierr = potrs (stor_ord, uplo, n, nrhs, \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                        traits::matrix_storage (b),\n                        traits::leading_dimension (b));\n        else // ATLAS bug with CblasRowMajor \n          ierr = potrs_bug (stor_ord, uplo, n, nrhs, \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                            traits::matrix_storage (b),\n                            traits::leading_dimension (b));\n        return ierr; \n#endif // BOOST_NUMERIC_BINDINGS_ATLAS_POTRF_BUG\n      }\n\n    } // detail \n\n    template <typename SymmA, typename MatrB>\n    inline\n    int potrs (CBLAS_UPLO const uplo, SymmA const& a, MatrB& b) {\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      assert (uplo == CblasUpper || uplo == CblasLower); \n      return detail::potrs (uplo, a, b); \n    }\n\n    template <typename SymmA, typename MatrB>\n    inline\n    int potrs (SymmA const& a, MatrB& b) {\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n      typedef typename traits::matrix_traits<SymmA>::value_type val_t;\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<SymmA>::matrix_structure, \n        typename traits::detail::symm_herm_t<val_t>::type\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      CBLAS_UPLO const uplo\n        = enum_cast<CBLAS_UPLO const>\n        (uplo_triang<\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n          typename traits::matrix_traits<SymmA>::uplo_type\n#else\n          typename SymmA::packed_category \n#endif \n         >::value); \n      \n      return detail::potrs (uplo, a, b); \n    }\n\n    template <typename SymmA, typename MatrB>\n    inline \n    int cholesky_substitute (SymmA const& a, MatrB& b) { return potrs (a, b); }\n\n\n#ifdef BOOST_NUMERIC_BINDINGS_ATLAS_POTRF_BUG\n    // posv(): 'driver' function \n    template <typename SymmA, typename MatrB>\n    inline\n    int posv (CBLAS_UPLO const uplo, SymmA& a, MatrB& b) {\n      int ierr = potrf (uplo, a); \n      if (ierr == 0)\n        ierr = potrs (uplo, a, b);\n      return ierr; \n    }\n\n    template <typename SymmA, typename MatrB>\n    inline\n    int posv (SymmA& a, MatrB& b) {\n      int ierr = potrf (a); \n      if (ierr == 0)\n        ierr = potrs (a, b);\n      return ierr; \n    }\n\n    template <typename SymmA, typename MatrB>\n    inline\n    int cholesky_solve (SymmA& a, MatrB& b) {\n      return posv (a, b); \n    }\n#endif // BOOST_NUMERIC_BINDINGS_ATLAS_POTRF_BUG \n\n\n    // potri(): computes the inverse of a symmetric or Hermitian positive \n    //          definite matrix A using the Cholesky factorization \n    //          previously computed by potrf() \n    namespace detail {\n\n      template <typename SymmA>\n      inline\n      int potri (CBLAS_UPLO const uplo, SymmA& a) {\n\n        CBLAS_ORDER const stor_ord\n          = enum_cast<CBLAS_ORDER const>\n          (storage_order<\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n            typename traits::matrix_traits<SymmA>::ordering_type\n#else\n            typename SymmA::orientation_category \n#endif \n           >::value); \n\n        int const n = traits::matrix_size1 (a);\n        assert (n == traits::matrix_size2 (a)); \n\n        return potri (stor_ord, uplo, n, \n                      traits::matrix_storage (a), \n                      traits::leading_dimension (a));\n      }\n\n    } // detail \n\n    template <typename SymmA>\n    inline\n    int potri (CBLAS_UPLO const uplo, SymmA& a) {\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 (uplo == CblasUpper || uplo == CblasLower); \n      return detail::potri (uplo, a); \n    } \n\n    template <typename SymmA>\n    inline\n    int potri (SymmA& a) {\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n      typedef typename traits::matrix_traits<SymmA>::value_type val_t;\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<SymmA>::matrix_structure, \n        typename traits::detail::symm_herm_t<val_t>::type\n      >::value)); \n#endif \n\n      CBLAS_UPLO const uplo\n        = enum_cast<CBLAS_UPLO const>\n        (uplo_triang<\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n          typename traits::matrix_traits<SymmA>::uplo_type\n#else\n          typename SymmA::packed_category \n#endif \n         >::value); \n      \n      return detail::potri (uplo, a); \n    }\n\n    template <typename SymmA>\n    inline\n    int cholesky_invert (SymmA& a) { return potri (a); }\n\n\n  } // namespace atlas\n\n}}} \n\n#endif // BOOST_NUMERIC_BINDINGS_CLAPACK_HPP\n", "meta": {"hexsha": "1e0b6704155af0a3fd9819e7de9037ae1befe6f3", "size": 26755, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "applications/mkl_solvers_application/external_includes/boost/numeric/bindings/atlas/clapack.hpp", "max_stars_repo_name": "jiaqiwang969/Kratos-test", "max_stars_repo_head_hexsha": "ed082abc163e7b627f110a1ae1da465f52f48348", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "applications/mkl_solvers_application/external_includes/boost/numeric/bindings/atlas/clapack.hpp", "max_issues_repo_name": "jiaqiwang969/Kratos-test", "max_issues_repo_head_hexsha": "ed082abc163e7b627f110a1ae1da465f52f48348", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "applications/mkl_solvers_application/external_includes/boost/numeric/bindings/atlas/clapack.hpp", "max_forks_repo_name": "jiaqiwang969/Kratos-test", "max_forks_repo_head_hexsha": "ed082abc163e7b627f110a1ae1da465f52f48348", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.9530456853, "max_line_length": 79, "alphanum_fraction": 0.6078863764, "num_tokens": 6661, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.737158174177441, "lm_q2_score": 0.6406358617010351, "lm_q1q2_score": 0.4722499621241267}}
{"text": "//\n// Copyright 2005-2007 Adobe Systems Incorporated\n//\n// Distributed under the Boost Software License, Version 1.0\n// See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt\n//\n#include <boost/gil/extension/io/jpeg_dynamic_io.hpp>\n\n// Example to demonstrate a way to compute gradients along x-axis\n\nusing namespace boost::gil;\n\ntemplate <typename Out>\nstruct halfdiff_cast_channels {\n    template <typename T> Out operator()(const T& in1, const T& in2) const {\n        return Out((in2-in1)/2);\n    }\n};\n\n\ntemplate <typename SrcView, typename DstView>\nvoid x_gradient(const SrcView& src, const DstView& dst) {\n    typedef typename channel_type<DstView>::type dst_channel_t;\n\n    for (int y=0; y<src.height(); ++y) {\n        typename SrcView::x_iterator src_it = src.row_begin(y);\n        typename DstView::x_iterator dst_it = dst.row_begin(y);\n\n        for (int x=1; x<src.width()-1; ++x) {\n            static_transform(src_it[x-1], src_it[x+1], dst_it[x],\n                             halfdiff_cast_channels<dst_channel_t>());\n        }\n    }\n}\n\ntemplate <typename SrcView, typename DstView>\nvoid x_luminosity_gradient(const SrcView& src, const DstView& dst) {\n    typedef pixel<typename channel_type<SrcView>::type, gray_layout_t> gray_pixel_t;\n    x_gradient(color_converted_view<gray_pixel_t>(src), dst);\n}\n\nint main() {\n    rgb8_image_t img;\n    jpeg_read_image(\"test.jpg\",img);\n\n    gray8s_image_t img_out(img.dimensions());\n    fill_pixels(view(img_out),int8_t(0));\n\n    x_luminosity_gradient(const_view(img), view(img_out));\n    jpeg_write_view(\"out-x_gradient.jpg\",color_converted_view<gray8_pixel_t>(const_view(img_out)));\n\n    return 0;\n}\n", "meta": {"hexsha": "db85e7b20695134734ffadba14560b1da618ee2b", "size": 1684, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "deps/boost/libs/gil/example/x_gradient.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/gil/example/x_gradient.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/gil/example/x_gradient.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.6181818182, "max_line_length": 99, "alphanum_fraction": 0.6983372922, "num_tokens": 435, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.4722499547255783}}
{"text": "// Copyright (c) 2009-2019 The Bitcoin Core developers\n// Copyright (c) 2014-2019 The DigiByte Core developers\n// Distributed under the MIT software license, see the accompanying\n// file COPYING or http://www.opensource.org/licenses/mit-license.php.\n\n#include <chainparams.h>\n#include <validation.h>\n#include <net.h>\n\n#include <test/test_digibyte.h>\n\n#include <boost/signals2/signal.hpp>\n#include <boost/test/unit_test.hpp>\n\n#define END_OF_SUPPLY_CURVE 110579600\n\n// Set OUTPUT_SUPPLY_SAMPLES_ENABLED to 1 to output\n// sampled Supply-curve data points (SAMPLE_INTERVAL)\n#ifndef OUTPUT_SUPPLY_SAMPLES_ENABLED\n    #define OUTPUT_SUPPLY_SAMPLES_ENABLED 0\n#endif\n\n#ifndef SAMPLE_INTERVAL\n    #define SAMPLE_INTERVAL 100\n#endif\n\n#ifndef WHOLE_COIN\n    #define WHOLE_COIN false\n#endif\n\n#define CALC_COIN(amount) (WHOLE_COIN ? (amount / COIN) : (amount))\n\n#if OUTPUT_SUPPLY_SAMPLES_ENABLED \n    #define DEBUG(x,y) if (x % SAMPLE_INTERVAL == 0) { \\\n        std::cerr << x << ';' << CALC_COIN(y) << std::endl; \\\n    }\n#else\n    #define DEBUG(x,y) (void) (x)\n#endif\n\n#ifndef BLOCK_TIME_SECONDS\n    #define BLOCK_TIME_SECONDS 15\n#endif\n\n#ifndef SECONDS_PER_MONTH\n    #define SECONDS_PER_MONTH (60 * 60 * 24 * 365 / 12)\n#endif    \n\n#ifndef ENABLE_TESTNET_SUBSIDY_TESTS\n    #define ENABLE_TESTNET_SUBSIDY_TESTS 0\n#endif\n\nBOOST_FIXTURE_TEST_SUITE(main_tests, TestingSetup)\n\nstatic void TestBlockSubsidy(const Consensus::Params& consensusParams, int nMaxBlocks, CAmount* nSumOut)\n{\n    CAmount nSum = 0;\n    CAmount nInitialSubsidy = 72000 * COIN;\n\n    CAmount nPreviousSubsidy = nInitialSubsidy * 2; // for height == 0\n    BOOST_CHECK_EQUAL(nPreviousSubsidy, nInitialSubsidy * 2);\n\n    /* Before first hard fork */\n\n    // 72000 reward for the first 1440 blocks\n    for (int nBlocks = 0; nBlocks < 1440 && nBlocks < consensusParams.nDiffChangeTarget; ++nBlocks)\n    {\n        int nHeight = nBlocks;\n        CAmount nSubsidy = GetBlockSubsidy(nHeight, consensusParams);\n        BOOST_CHECK_EQUAL(nSubsidy, nInitialSubsidy);\n\n        nSum += nSubsidy;\n        DEBUG(nBlocks, nSubsidy);\n    }\n\n    // 16000 rewards until block height 5760\n    for (int nBlocks = 1440; nBlocks < 5760 && nBlocks < consensusParams.nDiffChangeTarget; ++nBlocks)\n    {\n        int nHeight = nBlocks;\n        CAmount nSubsidy = GetBlockSubsidy(nHeight, consensusParams);\n        BOOST_CHECK_EQUAL(nSubsidy, 16000 * COIN);\n\n        nSum += nSubsidy;\n        DEBUG(nBlocks, nSubsidy);\n    }\n\n    // 8000 mining rewards until block height 67,200\n    for (int nBlocks = 5760; nBlocks < consensusParams.nDiffChangeTarget; ++nBlocks)\n    {\n        int nHeight = nBlocks;\n        CAmount nSubsidy = GetBlockSubsidy(nHeight, consensusParams);\n        BOOST_CHECK_EQUAL(nSubsidy, 8000 * COIN);  \n\n        nSum += nSubsidy;\n        DEBUG(nBlocks, nSubsidy);\n    }\n\n    // Dynamic mining rewards from block height 67,200 to block height 400,000 \n    for (int nBlocks = consensusParams.nDiffChangeTarget; nBlocks < consensusParams.alwaysUpdateDiffChangeTarget; ++nBlocks)\n    {\n        int nHeight = nBlocks;\n        CAmount nSubsidy = GetBlockSubsidy(nHeight, consensusParams);\n\n        CAmount nExpectedSubsidy = 8000 * COIN;\n        int nHeightWithinFork = (nHeight - consensusParams.nDiffChangeTarget);\n\n        for (int i = 0; i < (nHeightWithinFork / consensusParams.patchBlockRewardDuration) + 1; ++i) {\n            nExpectedSubsidy -= nExpectedSubsidy / 200; // dec by 0.5%\n        }\n\n        BOOST_CHECK_EQUAL(nSubsidy, nExpectedSubsidy);\n\n        nSum += nSubsidy;\n        DEBUG(nBlocks, nSubsidy);\n    }\n\n    // Updated dynamic mining rewards from block height 400,000 to block height 1,430,000\n    for (int nBlocks = consensusParams.alwaysUpdateDiffChangeTarget; nBlocks < consensusParams.workComputationChangeTarget; ++nBlocks)\n    {\n        int nHeight = nBlocks;\n        CAmount nSubsidy = GetBlockSubsidy(nHeight, consensusParams);\n\n        CAmount nExpectedSubsidy = 2459 * COIN;\n        int nHeightWithinFork = (nHeight - consensusParams.alwaysUpdateDiffChangeTarget);\n\n        for (int i = 0; i < (nHeightWithinFork / consensusParams.patchBlockRewardDuration2) + 1; ++i) {\n            nExpectedSubsidy -= nExpectedSubsidy / 100; // dec by 1% per month\n        }\n\n        BOOST_CHECK_EQUAL(nSubsidy, nExpectedSubsidy);\n\n        nSum += nSubsidy;\n        DEBUG(nBlocks, nSubsidy);\n    }\n\n    {\n        // Updated dynamic mining rewards from block height 1,430,000 to max block height.\n        // Intended blockheight: 41.6 million\n        // Actual blockheight: 110.5 million\n        CAmount nExpectedSubsidyStart = 2157 * COIN / 2;\n        CAmount nExpectedSubsidy = nExpectedSubsidyStart;\n        int nMonthsConsidered = 0;\n\n        for (int nBlocks = consensusParams.workComputationChangeTarget; nBlocks < nMaxBlocks; ++nBlocks) {\n            int nHeight = nBlocks;\n            CAmount nSubsidy = GetBlockSubsidy(nHeight, consensusParams);\n\n            int nHeightWithinFork = (nHeight - consensusParams.workComputationChangeTarget);\n            int nMonths = nHeightWithinFork * BLOCK_TIME_SECONDS / SECONDS_PER_MONTH;\n\n            if (nMonthsConsidered < nMonths) {\n                // Calculate new subsidy for number of months `nMonths`.\n                // This is a major optimization in order to reduce the\n                // number of inner loops\n\n                // Recalculate subsidy\n                for (int i = nMonthsConsidered; i < nMonths; ++i) {\n                    // Decay factor: 98884/100000\n                    nExpectedSubsidy *= 98884; \n                    nExpectedSubsidy /= 100000; \n                    ++nMonthsConsidered;\n                }\n            }\n\n            if (nExpectedSubsidy < COIN) { // ToDo: Alter consensus\n                nExpectedSubsidy = COIN;\n            }\n\n            BOOST_CHECK_EQUAL(nSubsidy, nExpectedSubsidy);\n\n            nSum += nSubsidy;\n            DEBUG(nBlocks, nSubsidy);\n        }\n    }\n\n    CAmount nSubsidy = GetBlockSubsidy(nMaxBlocks, consensusParams);\n    CAmount nExpectedSubsidy = 1 * COIN;\n\n    BOOST_CHECK_EQUAL(nSubsidy, nExpectedSubsidy);\n\n    if (nSumOut != NULL) {\n        *nSumOut = nSum;\n    }\n}\n\nBOOST_AUTO_TEST_CASE(block_subsidy_test)\n{\n    CAmount sum;\n    const auto chainParams = CreateChainParams(CBaseChainParams::MAIN);\n    const auto testChainParams = CreateChainParams(CBaseChainParams::TESTNET);\n    TestBlockSubsidy(chainParams->GetConsensus(), END_OF_SUPPLY_CURVE, &sum); // Mainnet\n\n    CAmount nExpectedTotalSupply = 2239167398214795680ULL;\n    BOOST_CHECK_EQUAL(sum, nExpectedTotalSupply);\n\n#if OUTPUT_SUPPLY_SAMPLES_ENABLED\n    // Output the accumulated supply until END_OF_SUPPLY_CURVE\n    std::cout << \"(mainnet): MAXIMUM SUPPLY: \" << sum << \" dgbSATS (\" << (sum / COIN) << \" DGB)\";\n#elif ENABLE_TESTNET_SUBSIDY_TESTS != 0\n    // Only perform test on TESTNET too if requested so.\n    TestBlockSubsidy(testChainParams->GetConsensus(), END_OF_SUPPLY_CURVE, NULL); // Testnet\n#endif\n}\n\nstatic bool ReturnFalse() { return false; }\nstatic bool ReturnTrue() { return true; }\n\nBOOST_AUTO_TEST_CASE(test_combiner_all)\n{\n    boost::signals2::signal<bool (), CombinerAll> Test;\n    BOOST_CHECK(Test());\n    Test.connect(&ReturnFalse);\n    BOOST_CHECK(!Test());\n    Test.connect(&ReturnTrue);\n    BOOST_CHECK(!Test());\n    Test.disconnect(&ReturnFalse);\n    BOOST_CHECK(Test());\n    Test.disconnect(&ReturnTrue);\n    BOOST_CHECK(Test());\n}\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "db655515a38fc2fe3369fe1b6cd5d34428d32209", "size": 7424, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/main_tests.cpp", "max_stars_repo_name": "ycagel/digibyte", "max_stars_repo_head_hexsha": "a8c0d21a47b49e45dc2504fdcf179b07a95cfad9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 431.0, "max_stars_repo_stars_event_min_datetime": "2015-01-21T03:57:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T17:17:18.000Z", "max_issues_repo_path": "src/test/main_tests.cpp", "max_issues_repo_name": "ycagel/digibyte", "max_issues_repo_head_hexsha": "a8c0d21a47b49e45dc2504fdcf179b07a95cfad9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 140.0, "max_issues_repo_issues_event_min_datetime": "2015-02-04T07:15:14.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-07T03:37:28.000Z", "max_forks_repo_path": "src/test/main_tests.cpp", "max_forks_repo_name": "ycagel/digibyte", "max_forks_repo_head_hexsha": "a8c0d21a47b49e45dc2504fdcf179b07a95cfad9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 249.0, "max_forks_repo_forks_event_min_datetime": "2015-01-03T19:48:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T09:46:33.000Z", "avg_line_length": 33.4414414414, "max_line_length": 134, "alphanum_fraction": 0.6736260776, "num_tokens": 1981, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.4722499496678352}}
{"text": "#pragma once\n#include <Eigen/Core>\n\nnamespace mdk {\n    using Vector = Eigen::Vector3d;\n    using VRef = Vector const&;\n\n    using VectorBase = Eigen::Matrix<double, 3, Eigen::Dynamic, Eigen::ColMajor>;\n\n    /**\n     * This class is a sort of a decorator over standard Eigen::Matrix3Xd. The\n     * chief difference is that this class offers an interface more appropriate\n     * for dealing with it as though it were a list of vectors (for example, one\n     * needs not use m.col(i) to get t'th vector in the matrix. Also, now size()\n     * corresponds to the number of vectors and not the elements of the array.\n     * The array itself is not (easily) resizeable.\n     */\n    class Vectors: public VectorBase {\n    public:\n        Vectors() = default;\n\n        /**\n         * Create an unitialized list of n vectors.\n         * @param n Number of vectors\n         */\n        explicit Vectors(int n):\n            VectorBase(3, n) {};\n\n        /**\n         * Create an initialized list of n vectors.\n         * @param n Number of vectors\n         * @param init Initial value\n         */\n        Vectors(int n, Vector const& init) {\n            resize(3, n);\n            colwise() = init;\n        }\n\n        /**\n         * Returns an iterator over constituent vectors.\n         * @return An interator over constituent vectors.\n         */\n        auto vectorwise() {\n            return colwise();\n        }\n\n        /**\n         * Returns a const iterator over constituent vectors.\n         * @return A const interator over constituent vectors.\n         */\n        auto vectorwise() const {\n            return colwise();\n        }\n\n        /**\n         *\n         * @return A number of vectors.\n         */\n        int size() const {\n            return cols();\n        }\n\n        /**\n         * Access to vector.\n         * @param i Index of a vector to access\n         * @return A slice of a matrix corresponding to i'th vector.\n         */\n        inline auto operator[](int i) {\n            return col(i);\n        }\n\n        /**\n         * Const access to vector.\n         * @param i Index of a vector to access\n         * @return A const slice of a matrix corresponding to i'th vector.\n         */\n        inline auto operator[](int i) const {\n            return col(i);\n        }\n    };\n}\n", "meta": {"hexsha": "db459c916e536eeef99b7ebc25b8470388df764a", "size": 2291, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "mdk/include/mdk/data/Vectors.hpp", "max_stars_repo_name": "if-pan-zpp/mdk", "max_stars_repo_head_hexsha": "a66575ae2160b3d8408fe4dceb971706f650bd05", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mdk/include/mdk/data/Vectors.hpp", "max_issues_repo_name": "if-pan-zpp/mdk", "max_issues_repo_head_hexsha": "a66575ae2160b3d8408fe4dceb971706f650bd05", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mdk/include/mdk/data/Vectors.hpp", "max_forks_repo_name": "if-pan-zpp/mdk", "max_forks_repo_head_hexsha": "a66575ae2160b3d8408fe4dceb971706f650bd05", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-19T09:24:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-19T09:24:34.000Z", "avg_line_length": 27.9390243902, "max_line_length": 81, "alphanum_fraction": 0.5386294195, "num_tokens": 502, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286833, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.4722499496678351}}
{"text": "#pragma once\n\n#include <boost/range/irange.hpp>\n\nnamespace km\n{\ntemplate <typename T>\nauto range(T end)\n{\n  return boost::irange(static_cast<T>(0), end);\n}\n\ntemplate <typename T>\nauto range(T start, T end)\n{\n  return boost::irange(start, end);\n}\n\ntemplate <typename T, typename U>\nauto range(T start, T end, U step)\n{\n  return boost::irange(start, end, step);\n}\n}\n", "meta": {"hexsha": "9d28268cb2691b2248fc2fae301aa1611c00c720", "size": 364, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/km_utils/range.hpp", "max_stars_repo_name": "kartikmohta/km_utils", "max_stars_repo_head_hexsha": "41fa812f3cfddcf214653081c8e4183f2b3fa543", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-03-26T23:21:22.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-26T23:21:22.000Z", "max_issues_repo_path": "include/km_utils/range.hpp", "max_issues_repo_name": "kartikmohta/km_utils", "max_issues_repo_head_hexsha": "41fa812f3cfddcf214653081c8e4183f2b3fa543", "max_issues_repo_licenses": ["Apache-2.0"], "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/km_utils/range.hpp", "max_forks_repo_name": "kartikmohta/km_utils", "max_forks_repo_head_hexsha": "41fa812f3cfddcf214653081c8e4183f2b3fa543", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.56, "max_line_length": 47, "alphanum_fraction": 0.6868131868, "num_tokens": 102, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6406358411176238, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.4722499432516228}}
{"text": "#include \"my_pearce.cpp\"\n#include <boost/graph/erdos_renyi_generator.hpp>\n#include <boost/random/linear_congruential.hpp>\n#include <boost/graph/graphml.hpp>\n#include <boost/property_map/dynamic_property_map.hpp>\n#include <boost/graph/transitive_closure.hpp>\n\nusing namespace boost;\n\n#ifndef TYPEDEF\n#define TYPEDEF\n\ntypedef adjacency_list <vecS, vecS, directedS> Graph;\ntypedef typename graph_traits<Graph>::vertex_descriptor Vertex;\ntypedef typename graph_traits<Graph>::vertex_iterator vertex_iter;\ntypedef graph_traits<adjacency_list<vecS, vecS, directedS> >::vertex_descriptor Vertex;\ntypedef typename property_map<Graph, vertex_index_t>::type IndexMap;\n\n#endif\n\nint main(int, char*[])\n{\n    \n    //This function takes a graph formatted by graphml fashion from the stdin\n    Graph g;\n    dynamic_properties dp;\n    read_graphml(std::cin, g, dp);\n    \n    //Printing the graph\n    std::cout << \"A directed graph:\" << std::endl;\n    print_graph(g, get(vertex_index,g));\n    std::cout << std::endl;\n\n    //PearceClass object\n    PearceClass<typeInt> pearce(&g);\n    std::vector<int>* rindex = pearce.pearce_scc();\n\n    //Printing the result\n    IndexMap index=get(vertex_index,g);\n    for (int i = 0; i != num_vertices(g); ++i){\n        std::cout << index[i] << \" -> \" << (*rindex)[i] << std::endl;\n    }\n    return 0;\n}\n", "meta": {"hexsha": "581e6ae08a33f22d4fd391978dbff902e925fcb4", "size": 1322, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main_pearce.cpp", "max_stars_repo_name": "phisco/advance_algorithms_project", "max_stars_repo_head_hexsha": "2961959cf6036ed4c85d479dd14389315df55ee1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-07-04T13:46:31.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-28T16:42:31.000Z", "max_issues_repo_path": "main_pearce.cpp", "max_issues_repo_name": "phisco/advance_algorithms_project", "max_issues_repo_head_hexsha": "2961959cf6036ed4c85d479dd14389315df55ee1", "max_issues_repo_licenses": ["MIT"], "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_pearce.cpp", "max_forks_repo_name": "phisco/advance_algorithms_project", "max_forks_repo_head_hexsha": "2961959cf6036ed4c85d479dd14389315df55ee1", "max_forks_repo_licenses": ["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.3777777778, "max_line_length": 87, "alphanum_fraction": 0.7072617247, "num_tokens": 339, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286833, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.4722499395523487}}
{"text": "\n#include <iostream>\n#include <iomanip>\n#include <algorithm>\n#include <numeric>\n#include <functional>\n#include <limits>\n#include <ctime>\n#include <cmath>\n#include <cassert>\n\n#include <boost/timer.hpp>\n#include <boost/random.hpp>\n#include <boost/math/tr1.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <boost/lambda/lambda.hpp>\n\n#include \"FunctionMinimization.h\"\n\nusing namespace boost::lambda;\n\nnamespace Grante {\n\ndouble FunctionMinimization::BarzilaiBorweinMinimize(\n\tFunctionMinimizationProblem& prob,\n\tstd::vector<double>& x_opt, double conv_tol,\n\tunsigned int max_iter, bool verbose) {\n\tunsigned int dim = prob.Dimensions();\n\n\t// Gradient, last gradient and alpha value required for BB iteration\n\tstd::vector<double> grad(dim, 0.0);\n\tstd::vector<double> grad_last(dim, 0.0);\n\tdouble alpha_last = std::numeric_limits<double>::infinity();\n\n\t// Initialize x\n\tstd::vector<double> x(dim);\n\tprob.ProvideStartingPoint(x);\n\n\tboost::timer total_timer;\n\tdouble obj = std::numeric_limits<double>::signaling_NaN();\n\tfor (unsigned int iter = 0; max_iter == 0 || iter < max_iter; ++iter) {\n\t\tobj = prob.Eval(x, grad);\n\n\t\t// Convergence check\n\t\tdouble grad_norm = EuclideanNorm(grad);\n\t\tif (verbose && (iter % 20 == 0)) {\n\t\t\tstd::cout << std::endl;\n\t\t\tstd::cout << \"  iter     time      objective      |grad|\" << std::endl;\n\t\t}\n\t\tif (verbose) {\n\t\t\tstd::ios_base::fmtflags original_format = std::cout.flags();\n\t\t\tstd::streamsize original_prec = std::cout.precision();\n\n\t\t\t// Iteration\n\t\t\tstd::cout << std::setiosflags(std::ios::left)\n\t\t\t\t<< std::setiosflags(std::ios::adjustfield)\n\t\t\t\t<< std::setw(6) << iter << \"  \";\n\t\t\t// Total runtime\n\t\t\tstd::cout << std::setiosflags(std::ios::left)\n\t\t\t\t<< std::resetiosflags(std::ios::scientific)\n\t\t\t\t<< std::setiosflags(std::ios::fixed)\n\t\t\t\t<< std::setiosflags(std::ios::adjustfield)\n\t\t\t\t<< std::setprecision(1)\n\t\t\t\t<< std::setw(6) << total_timer.elapsed() << \"s  \";\n\t\t\tstd::cout << std::resetiosflags(std::ios::fixed);\n\n\t\t\t// Objective function\n\t\t\tstd::cout << std::setiosflags(std::ios::scientific)\n\t\t\t\t<< std::setprecision(5)\n\t\t\t\t<< std::setiosflags(std::ios::left)\n\t\t\t\t<< std::setiosflags(std::ios::showpos)\n\t\t\t\t<< std::setw(7) << obj << \"   \";\n\t\t\t// Gradient norm\n\t\t\tstd::cout << std::setiosflags(std::ios::scientific)\n\t\t\t\t<< std::setprecision(2)\n\t\t\t\t<< std::resetiosflags(std::ios::showpos)\n\t\t\t\t<< std::setiosflags(std::ios::left) << grad_norm;\n\t\t\tstd::cout << std::endl;\n\n\t\t\tstd::cout.precision(original_prec);\n\t\t\tstd::cout.flags(original_format);\n\t\t}\n\n\t\tif (grad_norm < conv_tol) {\n\t\t\tx_opt = x;\n\t\t\treturn (obj);\n\t\t}\n\n\t\t// Choose alpha\n\t\tdouble alpha = grad_norm;\t// Initialization heuristic\n\t\tif (iter == 0) {\n\t\t\t// First iteration: assert feasibility by line search\n\t\t\tWolfeLineSearch linesearch(&prob, x, grad, grad, obj, 1e-4, 0.9);\n\t\t\tlinesearch.ComputeStepLength(alpha);\n\t\t\talpha = 1.0 / alpha;\n\t\t}\n\t\tif (iter >= 1) {\n\t\t\tdouble anom = 0.0;\n\t\t\tdouble adenom = 0.0;\n\t\t\tfor (unsigned int d = 0; d < dim; ++d) {\n\t\t\t\tanom += -grad_last[d]*(grad[d] - grad_last[d]);\n\t\t\t\tadenom += grad_last[d]*grad_last[d];\n\t\t\t}\n\t\t\talpha = alpha_last * (anom / adenom);\n#if 0\n\t\t\tstd::cout << \"   alpha = alpha_last(\" << alpha_last\n\t\t\t\t<< \") * (anom(\" << anom << \") / adenom(\" << adenom << \")\"\n\t\t\t\t<< \" = \" << alpha << std::endl;\n#endif\n\t\t}\n\t\tassert(alpha > 0.0);\n\n\t\t// Update x\n\t\tfor (unsigned int d = 0; d < dim; ++d)\n\t\t\tx[d] -= grad[d] / alpha;\n\n\t\t// Keep iterates of the gradient and stepsize\n\t\talpha_last = alpha;\n\t\tgrad_last = grad;\n\t}\n\n\t// Iteration limit reached\n\tx_opt = x;\n\treturn (prob.Eval(x, grad));\n}\n\ndouble FunctionMinimization::LimitedMemoryBFGSMinimize(\n\tFunctionMinimizationProblem& prob,\n\tstd::vector<double>& x_opt, double conv_tol, unsigned int max_iter,\n\tbool verbose, unsigned int lbfgs_m) {\n\tunsigned int dim = prob.Dimensions();\n\n\t// Gradient, last gradient and alpha value required for BB iteration\n\tstd::vector<double> grad(dim, 0.0);\n\tstd::vector<double> grad_last(dim, 0.0);\n\n\t// Initialize x\n\tstd::vector<double> x(dim);\n\tprob.ProvideStartingPoint(x);\n\tstd::vector<double> xprev(dim);\n\tstd::vector<double> gradprev(dim);\n\n\t// List of previous s,y,rho_i\n\tlbfgs_mem_type lbfgs_mem;\n\n\tboost::timer total_timer;\n\tdouble obj = std::numeric_limits<double>::signaling_NaN();\n\tbool is_valid = false;\n\tbool is_restart = false;\n\tunsigned int ls_evals = 0;\n\tunsigned int iter = 0;\n\tfor ( ; max_iter == 0 || iter < max_iter; ++iter) {\n\t\t// If no information about current query point has been computed, do\n\t\t// so now\n\t\tif (is_valid == false) {\n\t\t\tobj = prob.Eval(x, grad);\n\t\t\tis_valid = true;\n\t\t}\n\t\tdouble grad_norm = EuclideanNorm(grad);\n\n\t\tif (verbose && (iter % 20 == 0)) {\n\t\t\tstd::cout << std::endl;\n\t\t\tstd::cout << \"  iter     time      objective      |grad|   \"\n\t\t\t\t<< \"mem     ls#\" << std::endl;\n\t\t}\n\t\tif (verbose) {\n\t\t\tstd::ios_base::fmtflags original_format = std::cout.flags();\n\t\t\tstd::streamsize original_prec = std::cout.precision();\n\n\t\t\t// Iteration\n\t\t\tstd::cout << std::setiosflags(std::ios::left)\n\t\t\t\t<< std::setiosflags(std::ios::adjustfield)\n\t\t\t\t<< std::setw(6) << iter << \"  \";\n\t\t\t// Total runtime\n\t\t\tstd::cout << std::setiosflags(std::ios::left)\n\t\t\t\t<< std::resetiosflags(std::ios::scientific)\n\t\t\t\t<< std::setiosflags(std::ios::fixed)\n\t\t\t\t<< std::setiosflags(std::ios::adjustfield)\n\t\t\t\t<< std::setprecision(1)\n\t\t\t\t<< std::setw(6) << total_timer.elapsed() << \"s  \";\n\t\t\tstd::cout << std::resetiosflags(std::ios::fixed);\n\n\t\t\t// Objective function\n\t\t\tstd::cout << std::setiosflags(std::ios::scientific)\n\t\t\t\t<< std::setprecision(5)\n\t\t\t\t<< std::setiosflags(std::ios::left)\n\t\t\t\t<< std::setiosflags(std::ios::showpos)\n\t\t\t\t<< std::setw(7) << obj << \"   \";\n\t\t\t// Gradient norm\n\t\t\tstd::cout << std::setiosflags(std::ios::scientific)\n\t\t\t\t<< std::setprecision(2)\n\t\t\t\t<< std::resetiosflags(std::ios::showpos)\n\t\t\t\t<< std::setiosflags(std::ios::left) << grad_norm;\n\t\t\t// LBFGS memory size\n\t\t\tstd::cout << std::setiosflags(std::ios::left)\n\t\t\t\t<< std::setiosflags(std::ios::adjustfield)\n\t\t\t\t<< std::setw(6) << lbfgs_mem.size() << \"  \";\n\t\t\tstd::cout << std::setiosflags(std::ios::left)\n\t\t\t\t<< std::setiosflags(std::ios::adjustfield)\n\t\t\t\t<< std::setw(6) << ls_evals << \"  \";\n\t\t\tstd::cout << std::endl;\n\n\t\t\tstd::cout.precision(original_prec);\n\t\t\tstd::cout.flags(original_format);\n\t\t}\n\n\t\t// Convergence check based on gradient norm\n\t\tif (prob.HasConverged(x, grad, conv_tol))\n\t\t\tbreak;\t// converged\n\n\t\t// Insert differential information into Hessian approximation\n\t\tif (iter > 0 && is_restart == false) {\n\t\t\t// xprev: s_k\n\t\t\tstd::transform(x.begin(), x.end(), xprev.begin(),\n\t\t\t\txprev.begin(), _1 - _2);\n\t\t\t// gradprev: y_k\n\t\t\tstd::transform(grad.begin(), grad.end(), gradprev.begin(),\n\t\t\t\tgradprev.begin(), _1 - _2);\n\n\t\t\t// Heuristically ensure stability by ignoring unstable updates.\n\t\t\t// As to what entails 'unstable' there exist different opinions.\n\t\t\t// TODO: replace with true damped-Newton update (in inverse H\n\t\t\t// form used by L-BFGS)\n\t\t\tdouble ys_p = std::inner_product(xprev.begin(), xprev.end(),\n\t\t\t\tgradprev.begin(), 0.0);\n\t\t\tdouble yy_p = std::inner_product(gradprev.begin(), gradprev.end(),\n\t\t\t\tgradprev.begin(), 0.0);\n//\t\t\tif (ys_p >= 1.0e-12) {\n\t\t\tif (ys_p >= 1.0e-12*yy_p) {\n#if 0\n\t\t\t\tstd::cout << \"    lbfgs update with ys_p \" << ys_p\n\t\t\t\t\t<< std::endl;\n#endif\n\t\t\t\tdouble rho = 1.0 / ys_p;\n\t\t\t\tlbfgs_mem.push_front(lbfgs_mem_type::value_type(\n\t\t\t\t\txprev, gradprev, rho));\n\n\t\t\t\t// Remove old element from the lbfgs memory, if necessary\n\t\t\t\tif (lbfgs_mem.size() > lbfgs_m)\n\t\t\t\t\tlbfgs_mem.pop_back();\n\t\t\t} else {\n\t\t\t\tstd::cout << \"    LBFGS update too large (ys \"\n\t\t\t\t\t<< ys_p << \", yy \" << yy_p << \")\" << std::endl;\n\t\t\t}\n\t\t}\n\t\t// Save current iterate for next update\n\t\tstd::copy(x.begin(), x.end(), xprev.begin());\n\t\tstd::copy(grad.begin(), grad.end(), gradprev.begin());\n\n\t\t// Compute new ascent direction H_k \\nabla_x f(x_k)\n\t\t// Recent-to-oldest\n\t\tstd::list<double> alpha_list;\n\t\tfor (lbfgs_mem_type::const_iterator li = lbfgs_mem.begin();\n\t\t\tli != lbfgs_mem.end(); ++li) {\n\t\t\t// alpha_i = rho_i s_i' q\n\t\t\tdouble alpha_i = li->get<2>() * std::inner_product(\n\t\t\t\tgrad.begin(), grad.end(), li->get<0>().begin(), 0.0);\n\t\t\t// q <= q - alpha_i y_i\n\t\t\tstd::transform(grad.begin(), grad.end(), li->get<1>().begin(),\n\t\t\t\tgrad.begin(), _1 - alpha_i * _2);\n\t\t\talpha_list.push_back(alpha_i);\n\t\t}\n\t\t// Diagonal scaling: q = H^0 q\n\t\tdouble gamma = 1.0;\n\t\tif (iter > 0 && is_restart == false && lbfgs_mem.empty() == false) {\n\t\t\tlbfgs_mem_type::const_iterator li_last = lbfgs_mem.begin();\n\n\t\t\t// gamma = (s_{k-1}' y_{k-1}) / (y_{k-1}' y_{k-1})\n\t\t\tgamma = std::inner_product(li_last->get<0>().begin(),\n\t\t\t\tli_last->get<0>().end(), li_last->get<1>().begin(), 0.0);\n\t\t\tgamma /= std::inner_product(li_last->get<1>().begin(),\n\t\t\t\tli_last->get<1>().end(), li_last->get<1>().begin(), 0.0);\n\t\t}\n\t\tstd::transform(grad.begin(), grad.end(), grad.begin(), gamma * _1);\n\t\t// Reverse: oldest-to-recent\n\t\tstd::list<double>::const_reverse_iterator ai = alpha_list.rbegin();\n\t\tfor (lbfgs_mem_type::const_reverse_iterator li = lbfgs_mem.rbegin();\n\t\t\tli != lbfgs_mem.rend(); ++li, ++ai) {\n\t\t\t// beta = rho_i y_i' q\n\t\t\tdouble beta = li->get<2>() * std::inner_product(\n\t\t\t\tgrad.begin(), grad.end(), li->get<1>().begin(), 0.0);\n\n\t\t\t// q <- q + (alpha_i-beta)*s_i\n\t\t\tstd::transform(grad.begin(), grad.end(), li->get<0>().begin(),\n\t\t\t\tgrad.begin(), _1 + (*ai-beta)*_2);\n\t\t}\n\t\t// Now 'grad' contains an adjusted gradient direction\n\t\tis_restart = false;\n\n\t\t// Check cosine angle between gradient and transformed gradient\n\t\tdouble x0_phi_grad = std::inner_product(grad.begin(), grad.end(),\n\t\t\tgradprev.begin(), 0.0);\n\t\tdouble cos_a = x0_phi_grad /\n\t\t\t(EuclideanNorm(gradprev) * EuclideanNorm(grad));\n\t\tif (cos_a <= -1.0e-8) {\n\t\t\tstd::cout << \"### FATAL: LBFGS approximation lost psd, angle \"\n\t\t\t\t<< cos_a << std::endl;\n\t\t\tassert(0);\n\t\t} else if (cos_a <= 1.0e-7) {\n\t\t\t// Numerical issues, degenerate true Hessian or converged.\n\t\t\tstd::cout << \"### WARNING: LBFGS gradient orthogonality issue, \"\n\t\t\t\t<< \"aborting.\" << std::endl;\n\t\t\tbreak;\n\t\t}\n\n\t\tif ((boost::math::isnan)(x0_phi_grad)) {\n\t\t\tstd::cout << \"### WARNING: LBFGS gradient or perturbed gradient NaN, \"\n\t\t\t\t<< \"aborting.\" << std::endl;\n\t\t\tbreak;\n\t\t}\n\t\t// Check it is a descent direction\n\t\tif (x0_phi_grad <= -1.0e-8) {\n\t\t\tstd::cout << \"### FATAL: LBFGS approximation lost psd, x0_phi_grad \"\n\t\t\t\t<< x0_phi_grad << std::endl;\n\t\t\tassert(0);\n\t\t} else if (x0_phi_grad <= 1.0e-10) {\n#if 0\n\t\t\tstd::cout << \"### WARNING: LBFGS gradient, numerical issue, \"\n\t\t\t\t<< \"phi'(0) = \" << x0_phi_grad << std::endl;\n#endif\n\t\t\t// Numerical issues, degenerate true Hessian or converged.\n\t\t\tbreak;\n\t\t}\n\n\t\t// Perform linesearch in descent direction\n\t\tWolfeLineSearch linesearch(&prob, x, gradprev, grad, obj, 1e-4, 0.9);\n\t\t//SimpleLineSearch linesearch(&prob, x, gradprev, grad, obj);\n\t\tdouble alpha = 1.0;\n\t\t// Be very careful on the first step\n\t\tif (iter == 0) {\n//\t\t\talpha = 1.0e-5;\n\t\t\tif (EuclideanNorm(grad) >= 1.0)\n\t\t\t\talpha = 1.0 / EuclideanNorm(grad);\n\t\t\talpha = std::max(1.0e-12, alpha);\n\t\t}\n\n\t\tls_evals = linesearch.ComputeStepLengthUpdate(x, grad, obj, alpha);\n#if 0\n\t\tstd::cout << \"   step size \" << alpha\n\t\t\t<< \" in \" << eval << \" evaluations\" << std::endl;\n#endif\n\n\t\tif ((boost::math::isnan)(alpha)) {\n\t\t\tstd::cout << \"   * Line search failed (alpha=\"\n\t\t\t\t<< alpha << \")\" << std::endl;\n\t\t\tstd::copy(xprev.begin(), xprev.end(), x.begin());\n\t\t\tbreak;\n\t\t}\n\t\tif (alpha <= 1.0e-12) {\n\t\t\tstd::cout << \"   * Line search yielded step size alpha=\"\n\t\t\t\t<< alpha << std::endl;\n\t\t\tif (iter > 0) {\n\t\t\t\tstd::cout << \"   * Assuming convergence.\" << std::endl;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t// Successful line search with up-to-date step\n\t\tis_valid = true;\n\t}\n\n\t// Iteration limit reached\n\tx_opt = x;\n\treturn (prob.Eval(x, grad));\n}\n\ndouble FunctionMinimization::SubgradientMethodMinimize(\n\tFunctionMinimizationProblem& prob,\n\tstd::vector<double>& x_opt, double conv_tol, unsigned int max_iter,\n\tbool verbose) {\n\tunsigned int dim = prob.Dimensions();\n\tstd::vector<double> grad(dim, 0.0);\n\n\t// Initialize x\n\tstd::vector<double> x(dim);\n\tprob.ProvideStartingPoint(x);\n\n\tboost::timer total_timer;\n\tfor (unsigned int iter = 0; (max_iter == 0) || iter < max_iter; ++iter) {\n\t\tdouble obj = prob.Eval(x, grad);\n\n\t\t// Convergence check\n\t\tdouble grad_norm = EuclideanNorm(grad);\n\t\tif (verbose && (iter % 20 == 0)) {\n\t\t\tstd::cout << std::endl;\n\t\t\tstd::cout << \"  iter     time      objective      |grad|\" << std::endl;\n\t\t}\n\t\tif (verbose) {\n\t\t\tstd::ios_base::fmtflags original_format = std::cout.flags();\n\t\t\tstd::streamsize original_prec = std::cout.precision();\n\n\t\t\t// Iteration\n\t\t\tstd::cout << std::setiosflags(std::ios::left)\n\t\t\t\t<< std::setiosflags(std::ios::adjustfield)\n\t\t\t\t<< std::setw(6) << iter << \"  \";\n\t\t\t// Total runtime\n\t\t\tstd::cout << std::setiosflags(std::ios::left)\n\t\t\t\t<< std::resetiosflags(std::ios::scientific)\n\t\t\t\t<< std::setiosflags(std::ios::fixed)\n\t\t\t\t<< std::setiosflags(std::ios::adjustfield)\n\t\t\t\t<< std::setprecision(1)\n\t\t\t\t<< std::setw(6) << total_timer.elapsed() << \"s  \";\n\t\t\tstd::cout << std::resetiosflags(std::ios::fixed);\n\n\t\t\t// Objective function\n\t\t\tstd::cout << std::setiosflags(std::ios::scientific)\n\t\t\t\t<< std::setprecision(5)\n\t\t\t\t<< std::setiosflags(std::ios::left)\n\t\t\t\t<< std::setiosflags(std::ios::showpos)\n\t\t\t\t<< std::setw(7) << obj << \"   \";\n\t\t\t// Gradient norm\n\t\t\tstd::cout << std::setiosflags(std::ios::scientific)\n\t\t\t\t<< std::setprecision(2)\n\t\t\t\t<< std::resetiosflags(std::ios::showpos)\n\t\t\t\t<< std::setiosflags(std::ios::left) << grad_norm;\n\t\t\tstd::cout << std::endl;\n\n\t\t\tstd::cout.precision(original_prec);\n\t\t\tstd::cout.flags(original_format);\n\t\t}\n\n\t\tif (grad_norm < conv_tol) {\n\t\t\tx_opt = x;\n\t\t\treturn (obj);\n\t\t}\n\n\t\t// Choose step size\n\t\tdouble alpha_m = 200.0;\n\t\tdouble alpha = (1.0 + alpha_m) /\n\t\t\t(static_cast<double>(iter + 1) + alpha_m);\n\t\talpha /= grad_norm * grad_norm;\n\n\t\t// Update\n\t\tfor (unsigned int d = 0; d < dim; ++d)\n\t\t\tx[d] -= alpha * grad[d];\n\t}\n\n\t// Iteration limit reached\n\tx_opt = x;\n\treturn (prob.Eval(x, grad));\n}\n\ndouble FunctionMinimization::GradientMethodMinimize(\n\tFunctionMinimizationProblem& prob,\n\tstd::vector<double>& x_opt, double conv_tol, unsigned int max_iter,\n\tbool verbose) {\n\tunsigned int dim = prob.Dimensions();\n\tstd::vector<double> grad(dim, 0.0);\n\tstd::vector<double> grad_prev(dim, 0.0);\n\n\t// Initialize x\n\tstd::vector<double> x(dim);\n\tprob.ProvideStartingPoint(x);\n\n\tboost::timer total_timer;\n\tdouble alpha = -1.0;\n\tdouble beta = 0.5;\n\tfor (unsigned int iter = 0; (max_iter == 0) || iter < max_iter; ++iter) {\n\t\tdouble obj = prob.Eval(x, grad);\n\n\t\t// Convergence check\n\t\tdouble grad_norm = EuclideanNorm(grad);\n\t\tif (verbose && (iter % 20 == 0)) {\n\t\t\tstd::cout << std::endl;\n\t\t\tstd::cout << \"  iter     time      objective      |grad|       alpha\"\n\t\t\t\t<< std::endl;\n\t\t}\n\t\tif (verbose) {\n\t\t\tstd::ios_base::fmtflags original_format = std::cout.flags();\n\t\t\tstd::streamsize original_prec = std::cout.precision();\n\n\t\t\t// Iteration\n\t\t\tstd::cout << std::setiosflags(std::ios::left)\n\t\t\t\t<< std::setiosflags(std::ios::adjustfield)\n\t\t\t\t<< std::setw(6) << iter << \"  \";\n\t\t\t// Total runtime\n\t\t\tstd::cout << std::setiosflags(std::ios::left)\n\t\t\t\t<< std::resetiosflags(std::ios::scientific)\n\t\t\t\t<< std::setiosflags(std::ios::fixed)\n\t\t\t\t<< std::setiosflags(std::ios::adjustfield)\n\t\t\t\t<< std::setprecision(1)\n\t\t\t\t<< std::setw(6) << total_timer.elapsed() << \"s  \";\n\t\t\tstd::cout << std::resetiosflags(std::ios::fixed);\n\n\t\t\t// Objective function\n\t\t\tstd::cout << std::setiosflags(std::ios::scientific)\n\t\t\t\t<< std::setprecision(5)\n\t\t\t\t<< std::setiosflags(std::ios::left)\n\t\t\t\t<< std::setiosflags(std::ios::showpos)\n\t\t\t\t<< std::setw(7) << obj << \"   \";\n\t\t\t// Gradient norm\n\t\t\tstd::cout << std::setiosflags(std::ios::scientific)\n\t\t\t\t<< std::setprecision(2)\n\t\t\t\t<< std::resetiosflags(std::ios::showpos)\n\t\t\t\t<< std::setiosflags(std::ios::left) << grad_norm\n\t\t\t\t<< \"   \";\n\t\t\t// alpha\n\t\t\tstd::cout << std::setiosflags(std::ios::scientific)\n\t\t\t\t<< std::setprecision(2)\n\t\t\t\t<< std::resetiosflags(std::ios::showpos)\n\t\t\t\t<< std::setw(5)\n\t\t\t\t<< std::setiosflags(std::ios::left) << alpha;\n\t\t\tstd::cout << std::endl;\n\n\t\t\tstd::cout.precision(original_prec);\n\t\t\tstd::cout.flags(original_format);\n\t\t}\n\n\t\tif (grad_norm < conv_tol) {\n\t\t\tx_opt = x;\n\t\t\treturn (obj);\n\t\t}\n\n\t\t// Choose step size\n\t\tif (alpha < 0.0) {\n\t\t\talpha = 1.0 / (grad_norm * grad_norm);\n\t\t} else {\n\t\t\tif (std::inner_product(grad.begin(), grad.end(),\n\t\t\t\tgrad_prev.begin(), 0.0) < 0.0) {\n\t\t\t\talpha *= beta;\n\t\t\t}\n\t\t}\n\t\tstd::copy(grad.begin(), grad.end(), grad_prev.begin());\n\n\t\t// Update\n\t\tfor (unsigned int d = 0; d < dim; ++d)\n\t\t\tx[d] -= alpha * grad[d];\n\t}\n\n\t// Iteration limit reached\n\tx_opt = x;\n\treturn (prob.Eval(x, grad));\n}\n\nbool FunctionMinimization::CheckDerivative(FunctionMinimizationProblem& prob,\n\tdouble x_range, unsigned int test_count, double dim_eps, double grad_tol) {\n\tassert(dim_eps > 0.0);\n\tassert(grad_tol > 0.0);\n\n\t// Random number generation, for random perturbations\n\tboost::mt19937 rgen(static_cast<const boost::uint32_t>(std::time(0))+1);\n\tboost::uniform_real<double> rdestu;\t// range [0,1]\n\tboost::variate_generator<boost::mt19937,\n\t\tboost::uniform_real<double> > rand_perturb(rgen, rdestu);\n\n\t// Random number generation, for random dimensions\n\tunsigned int dim = prob.Dimensions();\n\tboost::mt19937 rgen2(static_cast<const boost::uint32_t>(std::time(0))+2);\n\tboost::uniform_int<unsigned int> rdestd(0, dim-1);\n\tboost::variate_generator<boost::mt19937,\n\t\tboost::uniform_int<unsigned int> > rand_dim(rgen2, rdestd);\n\n\t// Get base\n\tstd::vector<double> x0(dim);\n\tprob.ProvideStartingPoint(x0);\n\tstd::vector<double> xtest(dim);\n\tstd::vector<double> grad(dim);\n\tstd::vector<double> grad_d(dim);\t// dummy\n\n\tfor (unsigned int test_id = 0; test_id < test_count; ++test_id) {\n\t\txtest = x0;\n\t\tfor (unsigned int d = 0; d < dim; ++d)\n\t\t\txtest[d] += 2.0*x_range*rand_perturb() - x_range;\n\n\t\t// Get exact derivative\n\t\tdouble xtest_fval = prob.Eval(xtest, grad);\n\n\t\t// Compute first-order finite difference approximation\n\t\tunsigned int test_dim = rand_dim();\n\t\txtest[test_dim] += dim_eps;\n\t\tdouble xtest_d_fval = prob.Eval(xtest, grad_d);\n\t\tdouble deriv_fd = (xtest_d_fval - xtest_fval) / dim_eps;\n\n\t\t// Check accuracy\n\t\tif (fabs(deriv_fd - grad[test_dim]) > grad_tol) {\n\t\t\tstd::ios_base::fmtflags original_format = std::cout.flags();\n\t\t\tstd::streamsize original_prec = std::cout.precision();\n\n\t\t\tstd::cout << std::endl;\n\t\t\tstd::cout << \"### DERIVATIVE CHECKER WARNING\" << std::endl;\n\t\t\tstd::cout << \"### during test \" << (test_id+1) << \" a violation \"\n\t\t\t\t<< \"in gradient computation was found:\" << std::endl;\n\t\t\tstd::cout << std::setprecision(6)\n\t\t\t\t<< std::setiosflags(std::ios::scientific);\n\t\t\tstd::cout << \"### dim \" << test_dim << \", exact \" << grad[test_dim]\n\t\t\t\t<< \", finite-diff \" << deriv_fd\n\t\t\t\t<< \", absdiff \" << fabs(deriv_fd - grad[test_dim])\n\t\t\t\t<< std::endl;\n\t\t\tstd::cout << std::endl;\n\n\t\t\tstd::cout.precision(original_prec);\n\t\t\tstd::cout.flags(original_format);\n\n\t\t\treturn (false);\n\t\t}\n\t}\n\treturn (true);\n}\n\ndouble FunctionMinimization::EuclideanNorm(const std::vector<double>& vec) {\n\tdouble rs = 0.0;\n\tfor (std::vector<double>::const_iterator vi = vec.begin();\n\t\tvi != vec.end(); ++vi) {\n\t\trs += (*vi) * (*vi);\n\t}\n\treturn (sqrt(rs));\n}\n\n// Wolfe line-search method, see [Nocedal&Wright], page 60.\nFunctionMinimization::WolfeLineSearch::WolfeLineSearch(\n\tFunctionMinimizationProblem* prob, const std::vector<double>& x0,\n\tconst std::vector<double>& x0_grad,\n\tconst std::vector<double>& H_grad, double x0_fval,\n\tdouble c1, double c2)\n\t: prob(prob), x0(x0), x0_grad(x0_grad), H_grad(H_grad),\n\t\tx0_fval(x0_fval), x0_phi_grad(0),\n\t\tevaluation_count(0),\n\t\txalpha_val(std::numeric_limits<double>::signaling_NaN()),\n\t\tc1(c1), c2(c2)\n{\n\tassert(x0.size() > 0);\n\txalpha.resize(x0.size());\n\txalphagrad.resize(x0.size());\n\n\t// phi'(0) = - p' \\nabla_x f(x_k)\n\tx0_phi_grad = -std::inner_product(x0_grad.begin(), x0_grad.end(),\n\t\tH_grad.begin(), 0.0);\n\tassert(x0_phi_grad < 0.0);\n}\n\nunsigned int FunctionMinimization::WolfeLineSearch::ComputeStepLength(\n\tdouble& alpha) {\n\t// Previous alpha\n\tdouble alpha_prev = 0.0;\n\tdouble alpha_prev_fval = x0_fval;\n\tdouble alpha_prev_grad = x0_phi_grad;\n\tdouble alpha_max = 1e6;\n//\talpha = 1.0;\n\n#if 0\n\tfor (double bf = 0.0; bf < 1.0; bf += 0.01) {\n\t\tdouble tfval, tfgrad;\n\t\tEvaluate(bf, tfval, tfgrad);\n\t\tstd::cout << bf << \" \" << tfval << \" \" << tfgrad << \" # TEST\" << std::endl;\n\t}\n#endif\n\n\t// Current alpha\n\tdouble phi_alpha_fval;\n\tdouble phi_alpha_grad;\n\n\t// Find a stepsize interval satisfying the strong Wolfe conditions for a\n\t// given iterate x and gradient gx and descent direction d:\n\t//   1. Armijo: f(x + alpha d) <= f(x) + c1 alpha gx' d,\n\t//   2. Curvature: |nabla_alpha f(x + alpha d)| <= c2 |gx' d|.\n\tfor (unsigned int n = 0; true; ++n) {\n\t\tEvaluate(alpha, phi_alpha_fval, phi_alpha_grad);\n\n\t\t// If Armijo condition is violated: zoom, as a point satisfying the\n\t\t// Wolfe condition must exist in [alpha_{i-1}, alpha_i].\n\t\tif (phi_alpha_fval > (x0_fval + c1*alpha*x0_phi_grad)) {\n\t\t\tif (n == 0) {\n\t\t\t\talpha = Zoom(0.0, alpha, x0_fval, phi_alpha_fval, x0_phi_grad);\n\t\t\t} else {\n\t\t\t\talpha = Zoom(alpha_prev, alpha, alpha_prev_fval,\n\t\t\t\t\tphi_alpha_fval, alpha_prev_grad);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tif (n > 0 && phi_alpha_fval >= alpha_prev_fval) {\n\t\t\talpha = Zoom(alpha_prev, alpha, alpha_prev_fval,\n\t\t\t\tphi_alpha_fval, alpha_prev_grad);\n\t\t\tbreak;\n\t\t}\n\n\t\t// The Armijo condition is satisfied.  If in addition the curvature\n\t\t// condition (\"function must be flat around alpha\") is satisfied, then\n\t\t// we found a point satisfying the Wolfe conditions.\n#if 0\n\t\t// STRONG\n\t\tif (std::fabs(phi_alpha_grad) <= -c2*x0_phi_grad)\n\t\t\tbreak;\n#endif\n\t\tif (phi_alpha_grad >= c2*x0_phi_grad)\n\t\t\tbreak;\n\n\t\t// If the gradient increases again, then a point satisfying the Wolfe\n\t\t// condition must exist in [alpha_{i-1}, alpha_i].\n\t\tif (phi_alpha_grad >= 0) {\n\t\t\talpha = Zoom(alpha_prev, alpha, alpha_prev_fval,\n\t\t\t\tphi_alpha_fval, alpha_prev_grad);\n\t\t\tbreak;\n\t\t}\n\n\t\t// Further progress can be made, scale step size up by a factor\n\t\talpha_prev = alpha;\n\t\talpha_prev_fval = phi_alpha_fval;\n\t\talpha_prev_grad = phi_alpha_grad;\n\t\talpha *= std::sqrt(2.0);\n\t\tassert(alpha <= alpha_max);\n\t}\n\n#if 0\n\t// If line search failed: try fall back to backtracking line search\n\tif ((boost::math::isnan)(alpha)) {\n\t\talpha = 1.0;\n\t\tfor (unsigned int bt_try = 0; bt_try < 20; ++bt_try) {\n\t\t\talpha *= 0.25;\n\t\t\tEvaluate(alpha, phi_alpha_fval, phi_alpha_grad);\n\t\t\tstd::cout << \"    backtrack, alpha \" << alpha\n\t\t\t\t<< \", phi(a) \" << phi_alpha_fval\n\t\t\t\t<< \", phi'(a) \" << phi_alpha_grad << std::endl;\n\t\t\tstd::cout << \"    phi(a) = \" << phi_alpha_fval\n\t\t\t\t<< \" <= \" << x0_fval << \" + \" << c1*alpha*x0_phi_grad\n\t\t\t\t<< \"?\" << std::endl;\n\t\t\tif (phi_alpha_fval <= (x0_fval + c1*alpha*x0_phi_grad))\n\t\t\t\treturn (evaluation_count);\n\t\t}\n\t\tstd::cout << \"  Backtracking line search failed.\" << std::endl;\n\t\talpha = std::numeric_limits<double>::signaling_NaN();\n\t}\n#endif\n\n\treturn (evaluation_count);\n}\n\nunsigned int FunctionMinimization::WolfeLineSearch::ComputeStepLengthUpdate(\n\tstd::vector<double>& x_out, std::vector<double>& grad_out,\n\tdouble& fval_out, double& alpha) {\n//\talpha = 0.0;\n\tunsigned int ecount = ComputeStepLength(alpha);\n\n\tif ((boost::math::isnan)(alpha))\n\t\treturn (ecount);\n\n\t// A valid step size has been computed\n\tif (xalpha_val != alpha) {\n\t\t// Is not up-to-date, update\n\t\tdouble d1;\t// dummy\n\t\tdouble d2;\n\t\tEvaluate(alpha, d1, d2);\n\t}\n\tassert(xalpha_val == alpha);\n\tx_out = xalpha;\n\tgrad_out = xalphagrad;\n\tfval_out = xalphaobj;\n\n\treturn (ecount);\n}\n\n// phi(alpha), alpha >= 0\nvoid FunctionMinimization::WolfeLineSearch::Evaluate(\n\tdouble alpha, double& phi_fval, double& phi_grad) {\n\t// x(alpha) = x - alpha*p\n\tstd::transform(x0.begin(), x0.end(), H_grad.begin(),\n\t\txalpha.begin(), _1 - alpha * _2);\n\tstd::fill(xalphagrad.begin(), xalphagrad.end(), 0.0);\n\n\t// Evaluate phi(alpha) and derivative phi'(alpha)\n\t// phi(alpha) = f(x_k - alpha H_grad)\n\t// phi'(alpha) = -H_grad' \\nabla_x f(x_k - alpha H_grad)\n\tphi_fval = prob->Eval(xalpha, xalphagrad);\n\txalphaobj = phi_fval;\t// save phi(alpha)\n\txalpha_val = alpha;\t// save alpha\n\n\t// Univariate derivative is projection onto ascent direction\n\tphi_grad = -std::inner_product(xalphagrad.begin(), xalphagrad.end(),\n\t\tH_grad.begin(), 0.0);\n\tevaluation_count += 1;\n#if 0\n\tstd::cout << \"   phi(\" << alpha << \") = \" << phi_fval << \", grad \"\n\t\t<< phi_grad << std::endl;\n#endif\n}\n\ndouble FunctionMinimization::WolfeLineSearch::Zoom(double alpha_lo,\n\tdouble alpha_hi, double alpha_lo_fval, double alpha_hi_fval,\n\tdouble alpha_lo_grad) {\n\tdouble phi_trial_fval;\n\tdouble phi_trial_grad;\n\n#if 0\n\tdouble tfval, tfgrad;\n\tEvaluate(0.0, tfval, tfgrad);\n\tstd::cout << \"  phi(0) = \" << tfval << \", grad \" << tfgrad << std::endl;\n#endif\n#if 0\n\tfor (double bf = alpha_lo; bf < alpha_hi; bf += 0.01) {\n\t\tdouble tfval, tfgrad;\n\t\tEvaluate(bf, tfval, tfgrad);\n\t\tstd::cout << bf << \" \" << tfval << \" \" << tfgrad << \" # TEST\" << std::endl;\n\t}\n#endif\n\n\tunsigned int tries_max = 150;\n\tunsigned int tries = 0;\n\tfor (; tries < tries_max; ++tries) {\n\t\tif ((alpha_hi - alpha_lo) < 1.0e-14) {\n\t\t\tstd::cout << \"   * Wolfe line search, too small bracket: [\"\n\t\t\t\t<< alpha_lo << \"; \" << alpha_hi << \"]\" << std::endl;\n\t\t\t//return (std::numeric_limits<double>::signaling_NaN());\n\t\t\treturn (alpha_hi);\n\t\t}\n#if 0\n\t\t{\t// check preconditions: alpha_lo satisfies Armijo cond\n\t\t\tdouble tfval_lo, tfgrad_lo;\n\t\t\tEvaluate(alpha_lo, tfval_lo, tfgrad_lo);\n\t\t\tstd::cout << \"      ### lo: alpha = \" << alpha_lo\n\t\t\t\t<< \", phi(a) = \" << tfval_lo\n\t\t\t\t<< \", phi'(a) = \" << tfgrad_lo << std::endl;\n\t\t\tassert(tfval_lo <= (x0_fval + c1*alpha_lo*x0_phi_grad));\n\n\t\t\tdouble tfval_hi, tfgrad_hi;\n\t\t\tEvaluate(alpha_hi, tfval_hi, tfgrad_hi);\n\t\t\tstd::cout << \"      ### hi: alpha = \" << alpha_hi\n\t\t\t\t<< \", phi(a) = \" << tfval_hi\n\t\t\t\t<< \", phi'(a) = \" << tfgrad_hi << std::endl;\n\n\t\t\t// Check derivative\n\t\t\tdouble cd_fval, cd_grad;\n\t\t\tEvaluate(alpha_lo + 1e-8, cd_fval, cd_grad);\n\t\t\tdouble cd_apx = (cd_fval - tfval_lo) / 1e-8;\n\t\t\tstd::cout << \"        # lo deriv: \" << tfgrad_lo\n\t\t\t\t<< \" (exa) vs \" << cd_apx << \" (apx)\"\n\t\t\t\t<< \", phi(0) \" << x0_phi_grad\n\t\t\t\t<< std::endl;\n\t\t\tEvaluate(alpha_hi + 1e-8, cd_fval, cd_grad);\n\t\t\tcd_apx = (cd_fval - tfval_hi) / 1e-8;\n\t\t\tstd::cout << \"        # hi deriv: \" << tfgrad_hi\n\t\t\t\t<< \" (exa) vs \" << cd_apx << \" (apx)\"\n\t\t\t\t<< \", phi(hi) \" << tfval_hi\n\t\t\t\t<< std::endl;\n\n#if 1\n\t\t\tif (std::fabs(cd_apx - tfgrad_hi) >= 1.0) {\n\t\t\t\tfor (double bf = alpha_lo; bf < alpha_hi; bf +=\n0.01*(alpha_hi-alpha_lo)) {\n\t\t\t\t\tdouble tfval, tfgrad;\n\t\t\t\t\tEvaluate(bf, tfval, tfgrad);\n\t\t\t\t\tstd::cout << bf << \" \" << tfval << \" \" << tfgrad << \" # TEST\" << std::endl;\n\t\t\t\t}\n\t\t\t}\n#endif\n\t\t}\n#endif\n\t\tdouble alpha_trial = std::numeric_limits<double>::signaling_NaN();\n\t\tif ((boost::math::isinf)(alpha_hi_fval)) {\n\t\t\talpha_trial = 0.9*alpha_lo + 0.1*alpha_hi;\n\t\t\tstd::cout << \"   * Warning: phi(\" << alpha_hi << \") is NaN, \"\n\t\t\t\t<< \"trying bisection.\" << std::endl;\n\t\t} else {\n\t\t\t// Interpolation by quadratic, fixing\n\t\t\t// phi(alpha_lo), phi'(alpha_lo), phi(alpha_hi)\n\t\t\tdouble q_a = (alpha_lo_fval - alpha_hi_fval +\n\t\t\t\talpha_lo_grad*(alpha_hi-alpha_lo)) /\n\t\t\t\t(-alpha_lo*alpha_lo - alpha_hi*alpha_hi +\n\t\t\t\t\t2.0*alpha_lo*alpha_hi);\n\t\t\tdouble q_b = alpha_lo_grad - 2.0*q_a*alpha_lo;\n\t\t\t// double q_c = alpha_hi_fval - q_a*alpha_hi*alpha_hi\n\t\t\t//    - alpha_lo_grad*alpha_hi + 2.0*q_a*alpha_lo*alpha_hi;\n\t\t\tif (q_a <= 1.0e-15) {\n\t\t\t\tstd::cout << \"   * Wolfe line search failed due to small \"\n\t\t\t\t\t<< \"quadratic coefficient (q_a=\" << q_a << \").\" << std::endl;\n\t\t\t\tstd::cout << \"     alpha_lo/hi \" << alpha_lo << \", \"\n\t\t\t\t\t<< alpha_hi << std::endl;\n\t\t\t\tstd::cout << \"     alpha_lo/hi fval \" << alpha_lo_fval << \", \"\n\t\t\t\t\t<< alpha_hi_fval << std::endl;\n\t\t\t\tstd::cout << \"     alpha_lo grad \" << alpha_lo_grad << std::endl;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\talpha_trial = - q_b / (2.0*q_a);\n\t\t}\n#if 0\n\t\tstd::cout << \"        # alpha_trial: \" << alpha_trial\n\t\t\t<< std::endl;\n#endif\n\t\tEvaluate(alpha_trial, phi_trial_fval, phi_trial_grad);\n\n#if 0\n\t\tstd::cout << \"        # Armijo (c1): \"\n\t\t\t<< ((phi_trial_fval <= x0_fval + c1*alpha_trial*x0_phi_grad) ?\n\t\t\t\t\"SATISFIED\" : \"NOT SATISFIED\") << std::endl;\n\t\tstd::cout << \"        # Curvature (c2): \"\n\t\t\t<< ((phi_trial_grad >= c2*x0_phi_grad) ? \"SATISFIED\"\n\t\t\t\t: \"NOT SATISFIED\") << std::endl;\n\t\tstd::cout << \"        #   phi'(a) = \" << phi_trial_grad\n\t\t\t<< \" >= c2*\" << x0_phi_grad\n\t\t\t<< \" = \" << (c2*x0_phi_grad) << std::endl;\n#endif\n\n\t\t// Check Armijo condition:\n\t\t// phi(alpha) <= phi(0) + c1 alpha phi'(0)\n\t\tif (phi_trial_fval > (x0_fval + c1*alpha_trial*x0_phi_grad) ||\n\t\t\tphi_trial_fval >= alpha_lo_fval) {\n\t\t\t// Decrease upper bracket\n\t\t\talpha_hi = alpha_trial;\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Found a point satisfying the Wolfe conditions\n#if 0\n\t\t// Strong Wolfe\n\t\tif (std::fabs(phi_trial_grad) <= -c2*x0_phi_grad)\n\t\t\treturn (alpha_trial);\n#endif\n\t\tif (phi_trial_grad >= c2*x0_phi_grad)\n\t\t\treturn (alpha_trial);\n\n\t\t// Flip bracket\n\t\tif (phi_trial_grad*(alpha_hi - alpha_lo) >= 0.0)\n\t\t\talpha_hi = alpha_lo;\n\n\t\t// Increase lower bracket\n\t\talpha_lo = alpha_trial;\n\t\talpha_lo_fval = phi_trial_fval;\n\t}\n\n\tif (tries >= tries_max) {\n\t\tstd::cout << \"   * Wolfe line search exhausted function evaluation \"\n\t\t\t<< \"budget (\" << tries_max << \").\" << std::endl;\n\t}\n\treturn (std::numeric_limits<double>::signaling_NaN());\n}\n\nFunctionMinimization::SimpleLineSearch::SimpleLineSearch(\n\tFunctionMinimizationProblem* prob, const std::vector<double>& x0,\n\tconst std::vector<double>& x0_grad,\n\tconst std::vector<double>& H_grad, double x0_fval)\n\t: prob(prob), x0(x0), x0_grad(x0_grad), H_grad(H_grad),\n\t\tx0_fval(x0_fval), x0_phi_grad(0),\n\t\tevaluation_count(0),\n\t\txalpha_val(std::numeric_limits<double>::signaling_NaN())\n{\n\tassert(x0.size() > 0);\n\txalpha.resize(x0.size());\n\txalphagrad.resize(x0.size());\n\n\t// phi'(0) = - p' \\nabla_x f(x_k)\n\tx0_phi_grad = -std::inner_product(x0_grad.begin(), x0_grad.end(),\n\t\tH_grad.begin(), 0.0);\n\tassert(x0_phi_grad < 0.0);\n}\n\nunsigned int FunctionMinimization::SimpleLineSearch::ComputeStepLength(\n\tdouble& alpha) {\n\t// Previous alpha\n\tdouble alpha_min = 1.0e-12;\n\tdouble alpha_max = 1e6;\n\n\tdouble fa_enlarge = 1.7;\n\tdouble fa_shrink = 0.5;\n\n\t// Current alpha\n\tdouble phi_alpha_fval;\n\tdouble phi_alpha_grad;\n\n\t// Find a stepsize interval satisfying the strong Wolfe conditions for a\n\t// given iterate x and gradient gx and descent direction d:\n\t//   1. Armijo: f(x + alpha d) <= f(x) + c1 alpha gx' d,\n\t//   2. Curvature: |nabla_alpha f(x + alpha d)| <= c2 |gx' d|.\n\tunsigned int max_test = 200;\n\tfor (unsigned int n = 0; true; ++n) {\n#if 0\n\t\tstd::cout << \"SL n \" << n << \", alpha \" << alpha << std::endl;\n#endif\n\t\tif (alpha <= alpha_min) {\n\t\t\tbreak;\n\t\t} else if (alpha >= alpha_max || n >= max_test) {\n\t\t\tif (n >= max_test)\n\t\t\t\tstd::cout << \"### WARNING: line search count exceeded, alpha \"\n<< alpha << std::endl;\n\t\t\talpha = std::numeric_limits<double>::signaling_NaN();\n\t\t\tbreak;\n\t\t}\n\t\tEvaluate(alpha, phi_alpha_fval, phi_alpha_grad);\n\n\t\t// If Armijo condition is violated, shrink.\n\t\tif (phi_alpha_fval > (x0_fval + 1.0e-4*alpha*x0_phi_grad)) {\n\t\t\talpha *= fa_shrink;\n#if 0\n\t\t\tstd::cout << \"    armijo fail, shrink to \" << alpha << std::endl;\n#endif\n\t\t\tcontinue;\n\t\t}\n\n\t\t// The Armijo condition is satisfied.  If in addition the curvature\n\t\t// condition (\"function must be flat around alpha\") is satisfied, then\n\t\t// we found a point satisfying the Wolfe conditions.\n\t\t// Otherwise, enlarge alpha.\n\t\tif (phi_alpha_grad < 0.9*x0_phi_grad) {\n\t\t\talpha *= fa_enlarge;\n#if 0\n\t\t\tstd::cout << \"    wolfe fail, increase to \" << alpha << std::endl;\n#endif\n\t\t\tcontinue;\n\t\t}\n\n\t\tbreak;\n\t}\n\n\treturn (evaluation_count);\n}\n\nunsigned int FunctionMinimization::SimpleLineSearch::ComputeStepLengthUpdate(\n\tstd::vector<double>& x_out, std::vector<double>& grad_out,\n\tdouble& fval_out, double& alpha) {\n\tunsigned int ecount = ComputeStepLength(alpha);\n\n\tif ((boost::math::isnan)(alpha))\n\t\treturn (ecount);\n\n\t// A valid step size has been computed\n\tif (xalpha_val != alpha) {\n\t\t// Is not up-to-date, update\n\t\tdouble d1;\t// dummy\n\t\tdouble d2;\n\t\tEvaluate(alpha, d1, d2);\n\t}\n\tassert(xalpha_val == alpha);\n\tx_out = xalpha;\n\tgrad_out = xalphagrad;\n\tfval_out = xalphaobj;\n\n\treturn (ecount);\n}\n\nvoid FunctionMinimization::SimpleLineSearch::Evaluate(\n\tdouble alpha, double& phi_fval, double& phi_grad) {\n\t// x(alpha) = x - alpha*p\n\tstd::transform(x0.begin(), x0.end(), H_grad.begin(),\n\t\txalpha.begin(), _1 - alpha * _2);\n\tstd::fill(xalphagrad.begin(), xalphagrad.end(), 0.0);\n\n\t// Evaluate phi(alpha) and derivative phi'(alpha)\n\t// phi(alpha) = f(x_k - alpha H_grad)\n\t// phi'(alpha) = -H_grad' \\nabla_x f(x_k - alpha H_grad)\n\tphi_fval = prob->Eval(xalpha, xalphagrad);\n\txalphaobj = phi_fval;\t// save phi(alpha)\n\txalpha_val = alpha;\t// save alpha\n\n\t// Univariate derivative is projection onto ascent direction\n\tphi_grad = -std::inner_product(xalphagrad.begin(), xalphagrad.end(),\n\t\tH_grad.begin(), 0.0);\n\tevaluation_count += 1;\n#if 0\n\tstd::cout << \"   phi(\" << alpha << \") = \" << phi_fval << \", grad \"\n\t\t<< phi_grad << std::endl;\n#endif\n}\n\n}\n\n", "meta": {"hexsha": "09d5b3f56275683080f615ed763156fa0ed6c38c", "size": 32944, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "grante/FunctionMinimization.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/FunctionMinimization.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/FunctionMinimization.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.3155893536, "max_line_length": 80, "alphanum_fraction": 0.6333778533, "num_tokens": 10425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799253, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.4722499321538004}}
{"text": "// The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt\n/*\n    This is an example illustrating the use of the kcentroid object \n    from the dlib C++ Library.\n\n    The kcentroid object is an implementation of an algorithm that recursively\n    computes the centroid (i.e. average) of a set of points.  The interesting\n    thing about dlib::kcentroid is that it does so in a kernel induced feature\n    space.  This means that you can use it as a non-linear one-class classifier.\n    So you might use it to perform online novelty detection (although, it has\n    other uses, see the svm_pegasos or kkmeans examples for example).  \n    \n    This example will train an instance of it on points from the sinc function.\n\n*/\n\n#include <iostream>\n#include <vector>\n\n#include <dlib/svm.h>\n#include <dlib/statistics.h>\n\nusing namespace std;\nusing namespace dlib;\n\n// Here is the sinc function we will be trying to learn with the kcentroid \n// object.\ndouble sinc(double x)\n{\n    if (x == 0)\n        return 1;\n    return sin(x)/x;\n}\n\nint main()\n{\n    // Here we declare that our samples will be 2 dimensional column vectors.  \n    // (Note that if you don't know the dimensionality of your vectors at compile time\n    // you can change the 2 to a 0 and then set the size at runtime)\n    typedef matrix<double,2,1> sample_type;\n\n    // Now we are making a typedef for the kind of kernel we want to use.  I picked the\n    // radial basis kernel because it only has one parameter and generally gives good\n    // results without much fiddling.\n    typedef radial_basis_kernel<sample_type> kernel_type;\n\n    // Here we declare an instance of the kcentroid object.  The kcentroid has 3 parameters \n    // you need to set.  The first argument to the constructor is the kernel we wish to \n    // use.  The second is a parameter that determines the numerical accuracy with which \n    // the object will perform the centroid estimation.  Generally, smaller values \n    // give better results but cause the algorithm to attempt to use more dictionary vectors \n    // (and thus run slower and use more memory).  The third argument, however, is the \n    // maximum number of dictionary vectors a kcentroid is allowed to use.  So you can use\n    // it to control the runtime complexity.  \n    kcentroid<kernel_type> test(kernel_type(0.1),0.01, 15);\n\n\n    // now we train our object on a few samples of the sinc function.\n    sample_type m;\n    for (double x = -15; x <= 8; x += 1)\n    {\n        m(0) = x;\n        m(1) = sinc(x);\n        test.train(m);\n    }\n\n    running_stats<double> rs;\n\n    // Now lets output the distance from the centroid to some points that are from the sinc function.\n    // These numbers should all be similar.  We will also calculate the statistics of these numbers\n    // by accumulating them into the running_stats object called rs.  This will let us easily\n    // find the mean and standard deviation of the distances for use below.\n    cout << \"Points that are on the sinc function:\\n\";\n    m(0) = -1.5; m(1) = sinc(m(0)); cout << \"   \" << test(m) << endl;  rs.add(test(m));\n    m(0) = -1.5; m(1) = sinc(m(0)); cout << \"   \" << test(m) << endl;  rs.add(test(m));\n    m(0) = -0;   m(1) = sinc(m(0)); cout << \"   \" << test(m) << endl;  rs.add(test(m));\n    m(0) = -0.5; m(1) = sinc(m(0)); cout << \"   \" << test(m) << endl;  rs.add(test(m));\n    m(0) = -4.1; m(1) = sinc(m(0)); cout << \"   \" << test(m) << endl;  rs.add(test(m));\n    m(0) = -1.5; m(1) = sinc(m(0)); cout << \"   \" << test(m) << endl;  rs.add(test(m));\n    m(0) = -0.5; m(1) = sinc(m(0)); cout << \"   \" << test(m) << endl;  rs.add(test(m));\n\n    cout << endl;\n    // Lets output the distance from the centroid to some points that are NOT from the sinc function.\n    // These numbers should all be significantly bigger than previous set of numbers.  We will also\n    // use the rs.scale() function to find out how many standard deviations they are away from the \n    // mean of the test points from the sinc function.  So in this case our criterion for \"significantly bigger\"\n    // is > 3 or 4 standard deviations away from the above points that actually are on the sinc function.\n    cout << \"Points that are NOT on the sinc function:\\n\";\n    m(0) = -1.5; m(1) = sinc(m(0))+4;   cout << \"   \" << test(m) << \" is \" << rs.scale(test(m)) << \" standard deviations from sinc.\" << endl;\n    m(0) = -1.5; m(1) = sinc(m(0))+3;   cout << \"   \" << test(m) << \" is \" << rs.scale(test(m)) << \" standard deviations from sinc.\" << endl;\n    m(0) = -0;   m(1) = -sinc(m(0));    cout << \"   \" << test(m) << \" is \" << rs.scale(test(m)) << \" standard deviations from sinc.\" << endl;\n    m(0) = -0.5; m(1) = -sinc(m(0));    cout << \"   \" << test(m) << \" is \" << rs.scale(test(m)) << \" standard deviations from sinc.\" << endl;\n    m(0) = -4.1; m(1) = sinc(m(0))+2;   cout << \"   \" << test(m) << \" is \" << rs.scale(test(m)) << \" standard deviations from sinc.\" << endl;\n    m(0) = -1.5; m(1) = sinc(m(0))+0.9; cout << \"   \" << test(m) << \" is \" << rs.scale(test(m)) << \" standard deviations from sinc.\" << endl;\n    m(0) = -0.5; m(1) = sinc(m(0))+1;   cout << \"   \" << test(m) << \" is \" << rs.scale(test(m)) << \" standard deviations from sinc.\" << endl;\n\n    // And finally print out the mean and standard deviation of points that are actually from sinc().  \n    cout << \"\\nmean: \" << rs.mean() << endl;\n    cout << \"standard deviation: \" << rs.stddev() << endl;\n\n    // The output is as follows:\n    /*\n        Points that are on the sinc function:\n            0.869913\n            0.869913\n            0.873408\n            0.872807\n            0.870432\n            0.869913\n            0.872807\n\n        Points that are NOT on the sinc function:\n            1.06366 is 119.65 standard deviations from sinc.\n            1.02212 is 93.8106 standard deviations from sinc.\n            0.921382 is 31.1458 standard deviations from sinc.\n            0.918439 is 29.3147 standard deviations from sinc.\n            0.931428 is 37.3949 standard deviations from sinc.\n            0.898018 is 16.6121 standard deviations from sinc.\n            0.914425 is 26.8183 standard deviations from sinc.\n\n            mean: 0.871313\n            standard deviation: 0.00160756\n    */\n\n    // So we can see that in this example the kcentroid object correctly indicates that \n    // the non-sinc points are definitely not points from the sinc function.\n}\n\n\n", "meta": {"hexsha": "6f52cdabf4ce99fdcac4d38db2ce818230937e89", "size": 6416, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "DynamicGestures/dlib-18.5/examples/kcentroid_ex.cpp", "max_stars_repo_name": "uiuyuty/vsfh", "max_stars_repo_head_hexsha": "49f83a7bf043f7ae872dd759a0d32336d90cf1b4", "max_stars_repo_licenses": ["MIT"], "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": "DynamicGestures/dlib-18.5/examples/kcentroid_ex.cpp", "max_issues_repo_name": "uiuyuty/vsfh", "max_issues_repo_head_hexsha": "49f83a7bf043f7ae872dd759a0d32336d90cf1b4", "max_issues_repo_licenses": ["MIT"], "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": "DynamicGestures/dlib-18.5/examples/kcentroid_ex.cpp", "max_forks_repo_name": "uiuyuty/vsfh", "max_forks_repo_head_hexsha": "49f83a7bf043f7ae872dd759a0d32336d90cf1b4", "max_forks_repo_licenses": ["MIT"], "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": 49.3538461538, "max_line_length": 141, "alphanum_fraction": 0.6203241895, "num_tokens": 1791, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548646660543, "lm_q2_score": 0.7248702821204019, "lm_q1q2_score": 0.472147784510979}}
{"text": "#pragma once\n#include <mtao/types.hpp>\n#include <Eigen/Sparse>\n#include <mtao/iterator/enumerate.hpp>\n#include <variant>\n\nclass Curve {\n    public:\n        enum class InterpMode {\n            Wachpress, MeanValue, GaussianRBF, SplineGaussianRBF,\n            DesbrunSplineRBF\n        };\n        template <InterpMode>\n        struct InterpParameters {};\n        class CurveEvaluator;\n        mtao::vector<mtao::Vec2d> points;\n        void clear() ;\n        mtao::ColVecs2d edge_normals() const;\n        mtao::ColVecs2d area_edge_normals() const;\n\n        mtao::ColVecs2d V() const;\n        mtao::ColVecs2i E() const;\n\n\n\n\n\n        bool inside(const mtao::Vec2d& V) const;\n        double winding_number(const mtao::Vec2d& V) const;\n\n        size_t vertex_size() const { return points.size(); }\n        size_t edge_size() const { return points.size(); }\n\n        CurveEvaluator evaluator(InterpMode = InterpMode::MeanValue) const;\n\n        template <InterpMode Mode>\n        CurveEvaluator evaluator(const InterpParameters<Mode>& p = {}) const;\n\n};\ntemplate <>\nstruct Curve::InterpParameters<Curve::InterpMode::GaussianRBF> {double radius = 1.;};\ntemplate <>\nstruct Curve::InterpParameters<Curve::InterpMode::SplineGaussianRBF> {double radius = 1.;};\ntemplate <>\nstruct Curve::InterpParameters<Curve::InterpMode::DesbrunSplineRBF> {double radius = 1.;};\n\nclass Curve::CurveEvaluator {\n    public:\n        using PermutationMat = Eigen::PermutationMatrix<Eigen::Dynamic,Eigen::Dynamic, int>;\n\n        template <InterpMode Mode>\n        CurveEvaluator(const Curve& c, const InterpParameters<Mode>& params): curve(c), vertices(c.V()), interp_params(params) {}\n        mtao::MatXd distances(const mtao::ColVecs2d& Vs) const;\n\n        mtao::VecXd operator()(const mtao::VecXd& f, const mtao::ColVecs2d& V) const;\n        mtao::VecXd from_coefficients(const mtao::VecXd& coeffs, const mtao::ColVecs2d& V) const;\n        mtao::ColVecs2d grad(const mtao::VecXd& f, const mtao::ColVecs2d& V) const;\n        mtao::ColVecs2d grad_from_coefficients(const mtao::VecXd& coeffs, const mtao::ColVecs2d& V) const;\n\n        int size() const { return vertices.cols(); }\n        int vertex_size() const { return curve.vertex_size(); }\n        auto& V() const { return vertices; }\n    private:\n        const Curve& curve;\n\n        mtao::ColVecs2d vertices;\n        std::variant<\n            InterpParameters<InterpMode::MeanValue>\n            ,InterpParameters<InterpMode::Wachpress>\n            ,InterpParameters<InterpMode::GaussianRBF>\n            ,InterpParameters<InterpMode::SplineGaussianRBF>\n            ,InterpParameters<InterpMode::DesbrunSplineRBF>\n            > interp_params;\n};\n\n        template <Curve::InterpMode Mode>\n        Curve::CurveEvaluator Curve::evaluator(const InterpParameters<Mode>& p ) const {\n            return CurveEvaluator(*this, p);\n        }\n", "meta": {"hexsha": "bb5384c6b376427b109ad67c288475c46e4b4368", "size": 2852, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "examples/interpolation2d/curve.hpp", "max_stars_repo_name": "mtao/core", "max_stars_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_stars_repo_licenses": ["MIT"], "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/interpolation2d/curve.hpp", "max_issues_repo_name": "mtao/core", "max_issues_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-04-18T16:16:05.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-18T16:17:36.000Z", "max_forks_repo_path": "examples/interpolation2d/curve.hpp", "max_forks_repo_name": "mtao/core", "max_forks_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_forks_repo_licenses": ["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.65, "max_line_length": 129, "alphanum_fraction": 0.6588359046, "num_tokens": 783, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702642896702, "lm_q2_score": 0.6513548714339145, "lm_q1q2_score": 0.4721477778026657}}
{"text": "#include \"DelaunayTriangulation.h\"\n\n#include <Eigen/Dense>\n\n#include \"SIMPLib/Math/MatrixMath.h\"\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nDelaunayTriangulation::DelaunayTriangulation(TriMesh::VertexCoordList vertices, double offset, double tolerance, double alpha, Observable* observable)\n: m_Vertices(vertices)\n, m_Offset(offset)\n, m_Tolerance(tolerance)\n, m_Alpha(alpha)\n, m_Observer(observable)\n{\n  initialize();\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nDelaunayTriangulation::~DelaunayTriangulation()\n{\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nvoid DelaunayTriangulation::initialize()\n{\n  m_PointBounds[0] = std::numeric_limits<double>::max();\n  m_PointBounds[1] = std::numeric_limits<double>::lowest();\n  m_PointBounds[2] = std::numeric_limits<double>::max();\n  m_PointBounds[3] = std::numeric_limits<double>::lowest();\n  m_PointBounds[4] = std::numeric_limits<double>::max();\n  m_PointBounds[5] = std::numeric_limits<double>::lowest();\n\n  m_NumDuplicatePoints = 0;\n  m_NumDegeneracies = 0;\n\n  m_Delaunay = TriMesh::NullPointer();\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nTriangleGeom::Pointer DelaunayTriangulation::triangulate()\n{\n  initialize();\n\n  if(m_Observer)\n  {\n    connect(this, SIGNAL(filterGeneratedMessage(const PipelineMessage&)), m_Observer, SLOT(broadcastPipelineMessage(const PipelineMessage&)));\n  }\n\n  Eigen::Transform<double, 3, Eigen::Affine> transform = findProjectionPlane();\n\n  TriMesh::VertexCoordList projectedVertices(m_Vertices);\n\n  auto numVerts = m_Vertices.size();\n\n  for(size_t v = 0; v < numVerts; v++)\n  {\n    Eigen::Vector3d point(m_Vertices[v][0], m_Vertices[v][1], m_Vertices[v][2]);\n    // Eigen::Vector3d transformedPoint = transform * point;\n    // projectedVertices[v][0] = transformedPoint(0);\n    // projectedVertices[v][1] = transformedPoint(1);\n    // projectedVertices[v][2] = transformedPoint(2);\n    projectedVertices[v][0] = point(0);\n    projectedVertices[v][1] = point(1);\n    projectedVertices[v][2] = point(2);\n  }\n\n  findPointBounds(projectedVertices);\n\n  double center[3];\n  center[0] = (m_PointBounds[0] + m_PointBounds[1]) / 2.0;\n  center[1] = (m_PointBounds[2] + m_PointBounds[3]) / 2.0;\n  center[2] = (m_PointBounds[4] + m_PointBounds[5]) / 2.0;\n\n  double diff = 0.0;\n  double l = 0.0;\n\n  for(size_t i = 0; i < 3; i++)\n  {\n    diff = static_cast<double>(m_PointBounds[2 * i + 1]) - static_cast<double>(m_PointBounds[2 * i]);\n    l += diff * diff;\n  }\n  double tol = sqrt(l);\n  double radius = m_Offset * tol;\n  tol *= m_Tolerance;\n\n  double x[3];\n\n  for(size_t ptId = 0; ptId < 8; ptId++)\n  {\n    x[0] = center[0] + radius * cos(ptId * 45.0 * SIMPLib::Constants::k_PiOver180);\n    x[1] = center[1] + radius * sin(ptId * 45.0 * SIMPLib::Constants::k_PiOver180);\n    x[2] = center[2];\n    projectedVertices.emplace_back(std::initializer_list<float>{float(x[0]), float(x[1]), float(x[2])});\n  }\n\n  m_Delaunay = TriMesh::New(projectedVertices);\n  m_Delaunay->addTriangle(numVerts + 0, numVerts + 1, numVerts + 2);\n  m_Delaunay->addTriangle(numVerts + 2, numVerts + 3, numVerts + 4);\n  m_Delaunay->addTriangle(numVerts + 4, numVerts + 5, numVerts + 6);\n  m_Delaunay->addTriangle(numVerts + 6, numVerts + 7, numVerts + 0);\n  m_Delaunay->addTriangle(numVerts + 0, numVerts + 2, numVerts + 6);\n  m_Delaunay->addTriangle(numVerts + 2, numVerts + 4, numVerts + 6);\n\n  int64_t nei[3];\n  int64_t neiPts[3];\n  int64_t tri[4];\n  int64_t pts[3];\n  int64_t nodes[4][3];\n  int64_t p1;\n  int64_t p2;\n\n  tri[0] = 0;\n\n  int64_t progIncrement = static_cast<int64_t>(numVerts / 100);\n  int64_t prog = 1;\n  int64_t progressInt = 0;\n  int64_t counter = 0;\n\n  for(int64_t ptId = 0; ptId < int64_t(numVerts); ptId++)\n  {\n    x[0] = projectedVertices[ptId][0];\n    x[1] = projectedVertices[ptId][1];\n    x[2] = projectedVertices[ptId][2];\n\n    nei[0] = (-1); // where we are coming from...nowhere initially\n\n    if((tri[0] = findTriangle(x, tri[0], tol, nei, pts)) >= 0)\n    {\n      if(nei[0] < 0) // in triangle\n      {\n        // delete this triangle; create three new triangles\n        // first triangle is replaced with one of the new ones\n\n        nodes[0][0] = ptId;\n        nodes[0][1] = pts[0];\n        nodes[0][2] = pts[1];\n        m_Delaunay->removeLinkFromTriangle(pts[2], tri[0]);\n        m_Delaunay->replaceTriangleVertices(nodes[0][0], nodes[0][1], nodes[0][2], tri[0]);\n        m_Delaunay->addLinkToTriangle(ptId, tri[0]);\n\n        nodes[1][0] = ptId;\n        nodes[1][1] = pts[1];\n        nodes[1][2] = pts[2];\n        tri[1] = m_Delaunay->addTriangle(nodes[1][0], nodes[1][1], nodes[1][2]);\n\n        nodes[2][0] = ptId;\n        nodes[2][1] = pts[2];\n        nodes[2][2] = pts[0];\n        tri[2] = m_Delaunay->addTriangle(nodes[2][0], nodes[2][1], nodes[2][2]);\n\n        // Check edge neighbors for Delaunay criterion. If not satisfied, flip\n        // edge diagonal. (This is done recursively.)\n        checkEdge(ptId, x, pts[0], pts[1], tri[0], true);\n        checkEdge(ptId, x, pts[1], pts[2], tri[1], true);\n        checkEdge(ptId, x, pts[2], pts[0], tri[2], true);\n      }\n\n      else // on triangle edge\n      {\n        // update cell list\n        m_Delaunay->getTriangleVertices(nei[0], neiPts);\n        for(size_t i = 0; i < 3; i++)\n        {\n          if(neiPts[i] != nei[1] && neiPts[i] != nei[2])\n          {\n            p1 = neiPts[i];\n          }\n          if(pts[i] != nei[1] && pts[i] != nei[2])\n          {\n            p2 = pts[i];\n          }\n        }\n\n        m_Delaunay->removeLinkFromTriangle(nei[2], tri[0]);\n        m_Delaunay->removeLinkFromTriangle(nei[2], nei[0]);\n\n        nodes[0][0] = ptId;\n        nodes[0][1] = p2;\n        nodes[0][2] = nei[1];\n        m_Delaunay->replaceTriangleVertices(nodes[0][0], nodes[0][1], nodes[0][2], tri[0]);\n\n        nodes[1][0] = ptId;\n        nodes[1][1] = p1;\n        nodes[1][2] = nei[1];\n        m_Delaunay->replaceTriangleVertices(nodes[1][0], nodes[1][1], nodes[1][2], nei[0]);\n\n        m_Delaunay->addLinkToTriangle(ptId, tri[0]);\n        m_Delaunay->addLinkToTriangle(ptId, nei[0]);\n\n        tri[1] = nei[0];\n\n        nodes[2][0] = ptId;\n        nodes[2][1] = p2;\n        nodes[2][2] = nei[2];\n        tri[2] = m_Delaunay->addTriangle(nodes[2][0], nodes[2][1], nodes[2][2]);\n\n        nodes[3][0] = ptId;\n        nodes[3][1] = p1;\n        nodes[3][2] = nei[2];\n        tri[3] = m_Delaunay->addTriangle(nodes[3][0], nodes[3][1], nodes[3][2]);\n\n        // Check edge neighbors for Delaunay criterion.\n        for(size_t i = 0; i < 4; i++)\n        {\n          checkEdge(ptId, x, nodes[i][1], nodes[i][2], tri[i], true);\n        }\n      }\n    } // if triangle found\n\n    else\n    {\n      tri[0] = 0; // no triangle found\n    }\n\n    if(counter > prog)\n    {\n      progressInt = static_cast<int64_t>((static_cast<float>(counter) / numVerts) * 100.0f);\n      QString ss = m_MessageTitle + QObject::tr(\" || %1% Complete\").arg(progressInt);\n      (m_MessagePrefix, \"\", ss);\n      prog = prog + progIncrement;\n    }\n    counter++;\n  } // for all points\n\n  std::vector<int64_t> triUse(m_Delaunay->getNumberOfTriangles(), 1);\n\n  for(int64_t ptId = numVerts; ptId < int64_t((numVerts + 8)); ptId++)\n  {\n    std::vector<int64_t> neighborTris = m_Delaunay->getTrianglesToVertex(ptId);\n    for(auto&& neighbor : neighborTris)\n    {\n      triUse[neighbor] = 0;\n    }\n  }\n\n  ////alpha begin\n  // if(m_Alpha > 0.0)\n  //{\n  //  double alpha2 = m_Alpha * m_Alpha;\n  //  double x1[3], x2[3], x3[3];\n  //  double xx1[3], xx2[3], xx3[3];\n  //  int64_t cellId, numNei, ap1, ap2, neighbor;\n\n  //  TriMesh::Pointer alphaVert = TriMesh::New(projectedVertices);\n\n  //  vtkCellArray *alphaVerts = vtkCellArray::New();\n  //  alphaVerts->Allocate(numPoints);\n  //  vtkCellArray *alphaLines = vtkCellArray::New();\n  //  alphaLines->Allocate(numPoints);\n\n  //  char *pointUse = new char[numPoints + 8];\n  //  for(ptId = 0; ptId < (numPoints + 8); ptId++)\n  //  {\n  //    pointUse[ptId] = 0;\n  //  }\n\n  //  //traverse all triangles; evaluating Delaunay criterion\n  //  for(i = 0; i < numTriangles; i++)\n  //  {\n  //    if(triUse[i] == 1)\n  //    {\n  //      this->Mesh->GetCellPoints(i, npts, triPts);\n\n  //      // if any point is one of the bounding points that was added\n  //      // at the beginning of the algorithm, then grab the points\n  //      // from the variable \"points\" (this list has the boundary\n  //      // points and the original points have been transformed by the\n  //      // input transform).  if none of the points are bounding points,\n  //      // then grab the points from the variable \"inPoints\" so the alpha\n  //      // criterion is applied in the nontransformed space.\n  //      if(triPts[0]<numPoints && triPts[1]<numPoints && triPts[2]<numPoints)\n  //      {\n  //        inPoints->GetPoint(triPts[0], x1);\n  //        inPoints->GetPoint(triPts[1], x2);\n  //        inPoints->GetPoint(triPts[2], x3);\n  //      }\n  //      else\n  //      {\n  //        points->GetPoint(triPts[0], x1);\n  //        points->GetPoint(triPts[1], x2);\n  //        points->GetPoint(triPts[2], x3);\n  //      }\n\n  //      // evaluate the alpha criterion in 3D\n  //      vtkTriangle::ProjectTo2D(x1, x2, x3, xx1, xx2, xx3);\n  //      if(vtkTriangle::Circumcircle(xx1, xx2, xx3, center) > alpha2)\n  //      {\n  //        triUse[i] = 0;\n  //      }\n  //      else\n  //      {\n  //        for(int j = 0; j<3; j++)\n  //        {\n  //          pointUse[triPts[j]] = 1;\n  //        }\n  //      }\n  //    }//if non-deleted triangle\n  //  }//for all triangles\n\n  //  //traverse all edges see whether we need to create some\n  //  for(cellId = 0, triangles->InitTraversal();\n  //      triangles->GetNextCell(npts, triPts); cellId++)\n  //  {\n  //    if(!triUse[cellId])\n  //    {\n  //      for(i = 0; i < npts; i++)\n  //      {\n  //        ap1 = triPts[i];\n  //        ap2 = triPts[(i + 1) % npts];\n\n  //        if(this->BoundingTriangulation || (ap1<numPoints && ap2<numPoints))\n  //        {\n  //          this->Mesh->GetCellEdgeNeighbors(cellId, ap1, ap2, neighbors);\n  //          numNei = neighbors->GetNumberOfIds();\n\n  //          if(numNei < 1 || ((neighbor = neighbors->GetId(0)) > cellId\n  //            && !triUse[neighbor]))\n  //          {//see whether edge is shorter than Alpha\n\n  //            // same argument as above, if one is a boundary point, get\n  //            // it using this->GetPoint() which are transformed points. if\n  //            // neither of the points are boundary points, get the from\n  //            // inPoints (untransformed points) so alpha comparison done\n  //            // untransformed space\n  //            if(ap1 < numPoints && ap2 < numPoints)\n  //            {\n  //              inPoints->GetPoint(ap1, x1);\n  //              inPoints->GetPoint(ap2, x2);\n  //            }\n  //            else\n  //            {\n  //              this->GetPoint(ap1, x1);\n  //              this->GetPoint(ap2, x2);\n  //            }\n  //            if((vtkMath::Distance2BetweenPoints(x1, x2)*0.25) <= alpha2)\n  //            {\n  //              pointUse[ap1] = 1; pointUse[ap2] = 1;\n  //              pts[0] = ap1;\n  //              pts[1] = ap2;\n  //              alphaLines->InsertNextCell(2, pts);\n  //            }//if passed test\n  //          }//test edge\n  //        }//if valid edge\n  //      }//for all edges of this triangle\n  //    }//if triangle not output\n  //  }//for all triangles\n\n  //  //traverse all points, create vertices if none used\n  //  for(ptId = 0; ptId<(numPoints + 8); ptId++)\n  //  {\n  //    if((ptId < numPoints || this->BoundingTriangulation)\n  //       && !pointUse[ptId])\n  //    {\n  //      pts[0] = ptId;\n  //      alphaVerts->InsertNextCell(1, pts);\n  //    }\n  //  }\n\n  //  // update output\n  //  delete[] pointUse;\n  //  output->SetVerts(alphaVerts);\n  //  alphaVerts->Delete();\n  //  output->SetLines(alphaLines);\n  //  alphaLines->Delete();\n  //}\n  ////alpha end\n\n  fixupBoundaryTriangles(numVerts, projectedVertices, triUse);\n\n  // Remove the 8 bounding triangle vertices\n  TriMesh::VertexList delVerts = m_Delaunay->getVertices();\n  for(size_t i = numVerts; i < 8; i++)\n  {\n    delVerts.pop_back();\n  }\n\n  // std::vector<int64_t> vertsToRemove(8);\n  // std::iota(vertsToRemove.begin(), vertsToRemove.end(), numVerts);\n  // m_Delaunay->removeVertices(vertsToRemove);\n\n  size_t numGoodTris = 0;\n\n  for(size_t i = 0; i < triUse.size(); i++)\n  {\n    if(triUse[i])\n    {\n      numGoodTris++;\n    }\n  }\n\n  std::vector<std::vector<float>> untransformedVerts;\n  for(auto i = 0; i < numVerts; i++)\n  {\n    untransformedVerts.push_back(delVerts[i].vert);\n  }\n\n  SharedVertexList::Pointer vertices = TriangleGeom::CreateSharedVertexList(untransformedVerts.size());\n  TriangleGeom::Pointer triangles = TriangleGeom::CreateGeometry(numGoodTris, vertices, SIMPL::Geometry::TriangleGeometry);\n  float* vertPtr = triangles->getVertexPointer(0);\n  int64_t* triPtr = triangles->getTriPointer(0);\n\n  TriMesh::TriList triList = m_Delaunay->getTriangles();\n\n  size_t triIter = 0;\n  int64_t triVerts[3];\n\n  for(int64_t i = 0; i < int64_t(triList.size()); i++)\n  {\n    if(triUse[i])\n    {\n      m_Delaunay->getTriangleVertices(i, triVerts);\n      triPtr[3 * triIter + 0] = triVerts[0];\n      triPtr[3 * triIter + 1] = triVerts[1];\n      triPtr[3 * triIter + 2] = triVerts[2];\n      triIter++;\n    }\n  }\n\n  for(auto i = 0; i < untransformedVerts.size(); i++)\n  {\n    Eigen::Vector3d point(untransformedVerts[i][0], untransformedVerts[i][1], untransformedVerts[i][2]);\n    // Eigen::Vector3d transformedPoint = transform.inverse() * point;\n    // vertPtr[3 * i + 0] = transformedPoint(0);\n    // vertPtr[3 * i + 1] = transformedPoint(1);\n    // vertPtr[3 * i + 2] = transformedPoint(2);\n    vertPtr[3 * i + 0] = point(0);\n    vertPtr[3 * i + 1] = point(1);\n    vertPtr[3 * i + 2] = point(2);\n  }\n\n  return triangles;\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nint64_t DelaunayTriangulation::findTriangle(double x[3], int64_t tri, double tol, int64_t nei[3], int64_t pts[3])\n{\n  int i, j, ir, ic, inside, i2, i3;\n  int64_t newNei;\n  double p[3][3], n[2], vp[2], vx[2], dp, minProj;\n\n  m_Delaunay->getTriangleVertices(tri, pts);\n  m_Delaunay->getVertexCoordinates(pts[0], p[0]);\n  m_Delaunay->getVertexCoordinates(pts[1], p[1]);\n  m_Delaunay->getVertexCoordinates(pts[2], p[2]);\n\n  srand(tri);\n  ir = rand() % 3;\n  const double del2D_tolerance = 1.0e-014;\n\n  for(inside = 1, minProj = del2D_tolerance, ic = 0; ic < 3; ic++)\n  {\n    i = (ir + ic) % 3;\n    i2 = (i + 1) % 3;\n    i3 = (i + 2) % 3;\n\n    // create a 2D edge normal to define a \"half-space\"; evaluate points (i.e.,\n    // candidate point and other triangle vertex not on this edge).\n    n[0] = -(p[i2][1] - p[i][1]);\n    n[1] = p[i2][0] - p[i][0];\n    Normalize2x1(n);\n\n    // compute local vectors\n    for(j = 0; j < 2; j++)\n    {\n      vp[j] = p[i3][j] - p[i][j];\n      vx[j] = x[j] - p[i][j];\n    }\n\n    // check for duplicate point\n    Normalize2x1(vp);\n    if(Normalize2x1(vx) <= tol)\n    {\n      m_NumDuplicatePoints++;\n      return -1;\n    }\n\n    // see if two points are in opposite half spaces\n    dp = Dot2D(n, vx) * (Dot2D(n, vp) < 0 ? -1.0 : 1.0);\n    if(dp < del2D_tolerance)\n    {\n      if(dp < minProj) // track edge most orthogonal to point direction\n      {\n        inside = 0;\n        nei[1] = pts[i];\n        nei[2] = pts[i2];\n        minProj = dp;\n      }\n    } // outside this edge\n  }   // for each edge\n\n  if(inside) // all edges have tested positive\n  {\n    nei[0] = (-1);\n    return tri;\n  }\n\n  else if(!inside && (fabs(minProj) < del2D_tolerance)) // on edge\n  {\n    nei[0] = m_Delaunay->getTriangleEdgeNeighbor(nei[1], nei[2], tri);\n    return tri;\n  }\n\n  else // walk towards point\n  {\n    newNei = m_Delaunay->getTriangleEdgeNeighbor(nei[1], nei[2], tri);\n    if(newNei == nei[0])\n    {\n      m_NumDegeneracies++;\n      return -1;\n    }\n    else\n    {\n      nei[0] = tri;\n      return findTriangle(x, newNei, tol, nei, pts);\n    }\n  }\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nvoid DelaunayTriangulation::checkEdge(int64_t point, double x[3], int64_t p1, int64_t p2, int64_t tri, bool recursive)\n{\n  double x1[3], x2[3], x3[3];\n  int64_t neighbor;\n\n  m_Delaunay->getVertexCoordinates(p1, x1);\n  m_Delaunay->getVertexCoordinates(p2, x2);\n\n  neighbor = m_Delaunay->getTriangleEdgeNeighbor(p1, p2, tri);\n\n  if(neighbor > 0) // i.e., not a boundary edge\n  {\n    // get neighbor info including opposite point\n    int64_t oppositeVert = m_Delaunay->getOppositeVertex(p1, p2, neighbor);\n    if(oppositeVert < 0)\n    {\n      return;\n    }\n    m_Delaunay->getVertexCoordinates(oppositeVert, x3);\n\n    // see whether point is in circumcircle\n    if(inCircumcircle(x3, x, x1, x2))\n    { // swap diagonal\n      m_Delaunay->removeLinkFromTriangle(p1, tri);\n      m_Delaunay->removeLinkFromTriangle(p2, neighbor);\n      m_Delaunay->addLinkToTriangle(point, neighbor);\n      m_Delaunay->addLinkToTriangle(oppositeVert, tri);\n\n      m_Delaunay->replaceTriangleVertices(point, oppositeVert, p2, tri);\n      m_Delaunay->replaceTriangleVertices(point, p1, oppositeVert, neighbor);\n\n      if(recursive)\n      {\n        // two new edges become suspect\n        checkEdge(point, x, oppositeVert, p2, tri, true);\n        checkEdge(point, x, p1, oppositeVert, neighbor, true);\n      }\n    } // in circle\n  }   // interior edge\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nvoid DelaunayTriangulation::findPointBounds(TriMesh::VertexCoordList& vertices)\n{\n  for(auto&& vert : vertices)\n  {\n    if(vert[0] < m_PointBounds[0])\n    {\n      m_PointBounds[0] = static_cast<double>(vert[0]);\n    }\n    if(vert[0] > m_PointBounds[1])\n    {\n      m_PointBounds[1] = static_cast<double>(vert[0]);\n    }\n    if(vert[1] < m_PointBounds[2])\n    {\n      m_PointBounds[2] = static_cast<double>(vert[1]);\n    }\n    if(vert[1] > m_PointBounds[3])\n    {\n      m_PointBounds[3] = static_cast<double>(vert[1]);\n    }\n    if(vert[2] < m_PointBounds[4])\n    {\n      m_PointBounds[4] = static_cast<double>(vert[2]);\n    }\n    if(vert[2] > m_PointBounds[5])\n    {\n      m_PointBounds[5] = static_cast<double>(vert[2]);\n    }\n  }\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nvoid DelaunayTriangulation::fixupBoundaryTriangles(int64_t numVerts, TriMesh::VertexCoordList& points, std::vector<int64_t>& triUse)\n{\n  bool isConnected;\n  int64_t numSwaps = 0;\n  int64_t p1;\n  int64_t p2;\n  int64_t p3;\n  int64_t triPts[3];\n  int64_t neiPts[3];\n  int64_t pts[3];\n  int64_t swapPts[3];\n  double n1[3];\n  double n2[3];\n\n  for(int64_t ptId = 0; ptId < numVerts; ptId++)\n  {\n    // check if point is only connected to triangles scheduled for\n    // removal\n    std::vector<int64_t> neighbors = m_Delaunay->getTrianglesToVertex(ptId);\n    auto ncells = neighbors.size();\n\n    isConnected = false;\n\n    for(size_t i = 0; i < ncells; i++)\n    {\n      if(triUse[neighbors[i]])\n      {\n        isConnected = true;\n        break;\n      }\n    }\n\n    // this point will be connected in the output\n    if(isConnected)\n    {\n      // point is connected: continue\n      continue;\n    }\n\n    // This point is only connected to triangles scheduled for removal.\n    // Therefore it will not be connected in the output triangulation.\n    // Let's swap edges to create a triangle with 3 inner points.\n    // - inner points have an id < numPoints\n    // - boundary point ids are, numPoints <= id < numPoints+8.\n\n    // visit every edge connected to that point.\n    // check the 2 triangles touching at that edge.\n    // if one triangle is connected to 2 non-boundary points\n\n    for(auto i = 0; i < ncells; i++)\n    {\n      int64_t tri1 = neighbors[i];\n      m_Delaunay->getTriangleVertices(tri1, triPts);\n\n      if(triPts[0] == ptId)\n      {\n        p1 = triPts[1];\n        p2 = triPts[2];\n      }\n      else if(triPts[1] == ptId)\n      {\n        p1 = triPts[2];\n        p2 = triPts[0];\n      }\n      else\n      {\n        p1 = triPts[0];\n        p2 = triPts[1];\n      }\n\n      // if both p1 & p2 are boundary points,\n      // we skip them.\n      if(p1 >= numVerts && p2 >= numVerts)\n      {\n        continue;\n      }\n\n      int64_t tri2 = m_Delaunay->getTriangleEdgeNeighbor(p1, p2, tri1);\n\n      // get the 3 points of the neighbor triangle\n      m_Delaunay->getTriangleVertices(tri2, neiPts);\n\n      // locate the point different from p1 and p2\n      if(neiPts[0] != p1 && neiPts[0] != p2)\n      {\n        p3 = neiPts[0];\n      }\n      else if(neiPts[1] != p1 && neiPts[1] != p2)\n      {\n        p3 = neiPts[1];\n      }\n      else\n      {\n        p3 = neiPts[2];\n      }\n\n      // create the two new triangles.\n      // we just need to replace their pt ids.\n      pts[0] = ptId;\n      pts[1] = p1;\n      pts[2] = p3;\n\n      swapPts[0] = ptId;\n      swapPts[1] = p3;\n      swapPts[2] = p2;\n\n      findTriangleNormal(pts, n1);\n      findTriangleNormal(swapPts, n2);\n\n      // the normals must be along the same direction,\n      // or one triangle is upside down.\n      if(MatrixMath::DotProduct3x1(n1, n2) < 0.0)\n      {\n        // do not swap diagonal\n        continue;\n      }\n\n      // swap edge [p1 p2] and diagonal [ptId p3]\n\n      // it's ok to swap the diagonal\n      m_Delaunay->removeLinkFromTriangle(p1, tri2);\n      m_Delaunay->removeLinkFromTriangle(p2, tri1);\n      m_Delaunay->addLinkToTriangle(ptId, tri2);\n      m_Delaunay->addLinkToTriangle(p3, tri1);\n\n      m_Delaunay->replaceTriangleVertices(pts[0], pts[1], pts[2], tri1);\n      m_Delaunay->replaceTriangleVertices(swapPts[0], swapPts[1], swapPts[2], tri2);\n\n      triUse[tri1] = (p1 < numVerts && p3 < numVerts);\n      triUse[tri2] = (p3 < numVerts && p2 < numVerts);\n\n      // update the 'scheduled for removal' flag of the first triangle.\n      // The second triangle was not scheduled for removal anyway.\n      numSwaps++;\n    }\n  }\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\ndouble DelaunayTriangulation::circumcircle(double a[2], double b[2], double c[2], double center[2])\n{\n  double n12[2] = {0.0, 0.0};\n  double n13[2] = {0.0, 0.0};\n  double x12[2] = {0.0, 0.0};\n  double x13[2] = {0.0, 0.0};\n  double sum = 0.0;\n  double diff = 0.0;\n  size_t i;\n\n  for(i = 0; i < 2; i++)\n  {\n    n12[i] = b[i] - a[i];\n    n13[i] = c[i] - a[i];\n    x12[i] = (b[i] + a[i]) / 2.0;\n    x13[i] = (c[i] + a[i]) / 2.0;\n  }\n\n  Eigen::Matrix2d A;\n  A << n12[0], n12[1], n13[0], n13[1];\n  Eigen::Vector2d rhs;\n  rhs << Dot2D(n12, x12), Dot2D(n13, x13);\n  Eigen::Vector2d solution = A.colPivHouseholderQr().solve(rhs);\n\n  center[0] = solution(0);\n  center[1] = solution(1);\n\n  for(sum = 0, i = 0; i < 2; i++)\n  {\n    diff = a[i] - center[i];\n    sum += diff * diff;\n    diff = b[i] - center[i];\n    sum += diff * diff;\n    diff = c[i] - center[i];\n    sum += diff * diff;\n  }\n\n  if((sum /= 3.0) > std::numeric_limits<double>::max())\n  {\n    return std::numeric_limits<double>::max();\n  }\n  else\n  {\n    return sum;\n  }\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nint32_t DelaunayTriangulation::inCircumcircle(double p[3], double a[3], double b[3], double c[3])\n{\n  double radius2 = 0.0;\n  double center[2] = {0.0, 0.0};\n  double dist2 = 0.0;\n\n  radius2 = circumcircle(a, b, c, center);\n\n  dist2 = (p[0] - center[0]) * (p[0] - center[0]) + (p[1] - center[1]) * (p[1] - center[1]);\n\n  if(dist2 < (0.999999999999 * radius2))\n  {\n    return 1;\n  }\n  else\n  {\n    return 0;\n  }\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\ndouble DelaunayTriangulation::Determinant3x3(double g[3][3])\n{\n  return (g[0][0] * (g[1][1] * g[2][2] - g[1][2] * g[2][1])) - (g[0][1] * (g[1][0] * g[2][2] - g[1][2] * g[2][0])) + (g[0][2] * (g[1][0] * g[2][1] - g[1][1] * g[2][0]));\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\ndouble DelaunayTriangulation::Dot2D(double a[2], double b[2])\n{\n  return (a[0] * b[0] + a[1] * b[1]);\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\ndouble DelaunayTriangulation::Normalize2x1(double n[2])\n{\n  double denom;\n  denom = sqrt(((n[0] * n[0]) + (n[1] * n[1])));\n  if(denom != 0)\n  {\n    n[0] /= denom;\n    n[1] /= denom;\n  }\n  return denom;\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nvoid DelaunayTriangulation::findTriangleNormal(int64_t triPoints[3], double n[3])\n{\n  double length;\n\n  double ax, ay, az, bx, by, bz;\n\n  double a[3];\n  double b[3];\n  double c[3];\n\n  m_Delaunay->getVertexCoordinates(triPoints[0], a);\n  m_Delaunay->getVertexCoordinates(triPoints[1], b);\n  m_Delaunay->getVertexCoordinates(triPoints[2], c);\n\n  // order is important!!! maintain consistency with triangle vertex order\n  ax = c[0] - b[0];\n  ay = c[1] - b[1];\n  az = c[2] - b[2];\n  bx = a[0] - b[0];\n  by = a[1] - b[1];\n  bz = a[2] - b[2];\n\n  n[0] = (ay * bz - az * by);\n  n[1] = (az * bx - ax * bz);\n  n[2] = (ax * by - ay * bx);\n\n  if((length = sqrt((n[0] * n[0] + n[1] * n[1] + n[2] * n[2]))) != 0.0)\n  {\n    n[0] /= length;\n    n[1] /= length;\n    n[2] /= length;\n  }\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nEigen::Transform<double, 3, Eigen::Affine> DelaunayTriangulation::findProjectionPlane()\n{\n  auto numVertices = m_Vertices.size();\n  double matrix[3][3] = {{0.0, 0.0, 0.0}, {0.0, 0.0, 0.0}, {0.0, 0.0, 0.0}};\n  double normal[3] = {0.0, 0.0, 0.0};\n  double origin[3] = {0.0, 0.0, 0.0};\n  double v[3] = {0.0, 0.0, 0.0};\n\n  double m[9];\n  double *c1, *c2, *c3, det;\n\n  const double tolerance = 1.0e-03;\n\n  for(auto&& vert : m_Vertices)\n  {\n    v[0] += vert[0] * vert[2];\n    v[1] += vert[1] * vert[2];\n    v[2] += vert[2];\n\n    matrix[0][0] += vert[0] * vert[0];\n    matrix[0][1] += vert[0] * vert[1];\n    matrix[0][2] += vert[0];\n\n    matrix[1][0] += vert[0] * vert[1];\n    matrix[1][1] += vert[1] * vert[1];\n    matrix[1][2] += vert[1];\n\n    matrix[2][0] += vert[0];\n    matrix[2][1] += vert[1];\n  }\n\n  matrix[2][2] = numVertices;\n\n  origin[0] = matrix[0][2] / numVertices;\n  origin[1] = matrix[1][2] / numVertices;\n  origin[2] = v[2] / numVertices;\n\n  c1 = m;\n  c2 = m + 3;\n  c3 = m + 6;\n\n  double tmpMatrixInv[3][3] = {{matrix[0][0], matrix[1][0], matrix[2][0]}, {matrix[0][1], matrix[1][1], matrix[2][1]}, {matrix[0][2], matrix[1][2], matrix[2][2]}};\n\n  double tmpMatrix0[3][3] = {{v[0], matrix[1][0], matrix[2][0]}, {v[1], matrix[1][1], matrix[2][1]}, {v[2], matrix[1][2], matrix[2][2]}};\n\n  double tmpMatrix1[3][3] = {{matrix[0][0], v[0], matrix[2][0]}, {matrix[0][1], v[1], matrix[2][1]}, {matrix[0][2], v[2], matrix[2][2]}};\n\n  if((det = Determinant3x3(tmpMatrixInv)) > tolerance)\n  {\n    normal[0] = Determinant3x3(tmpMatrix0) / det;\n    normal[1] = Determinant3x3(tmpMatrix1) / det;\n    normal[2] = -1.0;\n  }\n\n  double zAxis[3] = {0.0, 0.0, 1.0};\n  double rotationAxis[3] = {0.0, 0.0, 0.0};\n\n  MatrixMath::Normalize3x1(normal);\n  MatrixMath::CrossProduct(normal, zAxis, rotationAxis);\n  MatrixMath::Normalize3x1(rotationAxis);\n\n  double rotationAngle = acos(MatrixMath::DotProduct3x1(zAxis, normal));\n\n  Eigen::Transform<double, 3, Eigen::Affine> transform =\n      Eigen::AngleAxisd(rotationAngle, Eigen::Vector3d(rotationAxis[0], rotationAxis[1], rotationAxis[2])) * Eigen::Translation3d(-origin[0], -origin[1], -origin[2]);\n\n  return transform;\n}\n", "meta": {"hexsha": "b408291dc119de323ec633e4ba2035a43982bb61", "size": 28718, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "DREAM3DReviewFilters/util/PrintRiteHelpers.cpp", "max_stars_repo_name": "JDuffeyBQ/DREAM3DReview", "max_stars_repo_head_hexsha": "098ddc60d1c53764e09e21e08d4636233071be31", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/util/PrintRiteHelpers.cpp", "max_issues_repo_name": "JDuffeyBQ/DREAM3DReview", "max_issues_repo_head_hexsha": "098ddc60d1c53764e09e21e08d4636233071be31", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 18.0, "max_issues_repo_issues_event_min_datetime": "2017-09-01T23:13:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-02T12:58:57.000Z", "max_forks_repo_path": "DREAM3DReviewFilters/util/PrintRiteHelpers.cpp", "max_forks_repo_name": "JDuffeyBQ/DREAM3DReview", "max_forks_repo_head_hexsha": "098ddc60d1c53764e09e21e08d4636233071be31", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2017-09-01T23:15:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-21T13:24:19.000Z", "avg_line_length": 29.9145833333, "max_line_length": 169, "alphanum_fraction": 0.5274044153, "num_tokens": 8984, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834649, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.4721454758298775}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2017 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\n#include \"utilities.hpp\"\n#include \"squarerootclvmodel.hpp\"\n#include <ql/quotes/simplequote.hpp>\n#include <ql/time/daycounters/actualactual.hpp>\n#include <ql/time/daycounters/actual365fixed.hpp>\n#include <ql/time/calendars/nullcalendar.hpp>\n#include <ql/instruments/impliedvolatility.hpp>\n#include <ql/instruments/forwardvanillaoption.hpp>\n#include <ql/math/statistics/statistics.hpp>\n#include <ql/math/integrals/gausslobattointegral.hpp>\n#include <ql/math/randomnumbers/rngtraits.hpp>\n#include <ql/math/randomnumbers/sobolbrownianbridgersg.hpp>\n#include <ql/math/optimization/constraint.hpp>\n#include <ql/math/optimization/simplex.hpp>\n#include <ql/processes/squarerootprocess.hpp>\n#include <ql/methods/montecarlo/multipathgenerator.hpp>\n#include <ql/pricingengines/blackcalculator.hpp>\n#include <ql/pricingengines/vanilla/analytichestonengine.hpp>\n#include <ql/pricingengines/vanilla/analyticeuropeanengine.hpp>\n#include <ql/pricingengines/forward/forwardengine.hpp>\n#include <ql/methods/montecarlo/pathgenerator.hpp>\n#include <ql/termstructures/volatility/equityfx/hestonblackvolsurface.hpp>\n#include <ql/termstructures/volatility/equityfx/noexceptlocalvolsurface.hpp>\n#include <ql/experimental/models/squarerootclvmodel.hpp>\n#include <ql/experimental/models/hestonslvfdmmodel.hpp>\n#include <ql/experimental/processes/hestonslvprocess.hpp>\n#include <ql/experimental/finitedifferences/fdhestondoublebarrierengine.hpp>\n#include <ql/experimental/barrieroption/analyticdoublebarrierbinaryengine.hpp>\n#include <ql/experimental/volatility/sabrvoltermstructure.hpp>\n\n#if defined(__GNUC__) && !defined(__clang__) && BOOST_VERSION > 106300\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wmaybe-uninitialized\"\n#endif\n#include <boost/math/distributions/non_central_chi_squared.hpp>\n#if defined(__GNUC__) && !defined(__clang__) && BOOST_VERSION > 106300\n#pragma GCC diagnostic pop\n#endif\n\n#include <set>\n#include <utility>\n\nusing namespace QuantLib;\nusing namespace boost::unit_test_framework;\n\n\nnamespace square_root_clv_model {\n    class CLVModelPayoff : public PlainVanillaPayoff {\n      public:\n        CLVModelPayoff(Option::Type type, Real strike, ext::function<Real(Real)> g)\n        : PlainVanillaPayoff(type, strike), g_(std::move(g)) {}\n\n        Real operator()(Real x) const override { return PlainVanillaPayoff::operator()(g_(x)); }\n\n      private:\n        const ext::function<Real(Real)> g_;\n    };\n\n    typedef boost::math::non_central_chi_squared_distribution<Real>\n        chi_squared_type;\n}\n\n\nvoid SquareRootCLVModelTest::testSquareRootCLVVanillaPricing() {\n    BOOST_TEST_MESSAGE(\n        \"Testing vanilla option pricing with square-root kernel process...\");\n\n    using namespace square_root_clv_model;\n\n    SavedSettings backup;\n\n    const Date todaysDate(5, Oct, 2016);\n    Settings::instance().evaluationDate() = todaysDate;\n\n    const DayCounter dc = ActualActual(ActualActual::ISDA);\n    const Date maturityDate = todaysDate + Period(3, Months);\n    const Time maturity = dc.yearFraction(todaysDate, maturityDate);\n\n    const Real s0 = 100;\n    const Handle<Quote> spot(ext::make_shared<SimpleQuote>(s0));\n\n    const Rate r = 0.08;\n    const Rate q = 0.03;\n    const Volatility vol = 0.3;\n\n    const Handle<YieldTermStructure> rTS(flatRate(r, dc));\n    const Handle<YieldTermStructure> qTS(flatRate(q, dc));\n    const Handle<BlackVolTermStructure> volTS(flatVol(todaysDate, vol, dc));\n    const Real fwd = s0*qTS->discount(maturity)/rTS->discount(maturity);\n\n    const ext::shared_ptr<GeneralizedBlackScholesProcess> bsProcess(\n        ext::make_shared<GeneralizedBlackScholesProcess>(\n            spot, qTS, rTS, volTS));\n\n    const Real kappa       = 1.0;\n    const Real theta       = 0.06;\n    const Volatility sigma = 0.2;\n    const Real x0          = 0.09;\n\n    const ext::shared_ptr<SquareRootProcess> sqrtProcess(\n        ext::make_shared<SquareRootProcess>(theta, kappa, sigma, x0));\n\n    const std::vector<Date> maturityDates(1, maturityDate);\n\n    const SquareRootCLVModel model(\n        bsProcess, sqrtProcess, maturityDates, 14, 1-1e-14, 1e-14);\n\n    const Array x = model.collocationPointsX(maturityDate);\n    const Array y = model.collocationPointsY(maturityDate);\n\n    const LagrangeInterpolation g(x.begin(), x.end(), y.begin());\n\n    const Real df  = 4*theta*kappa/(sigma*sigma);\n    const Real ncp = 4*kappa*std::exp(-kappa*maturity)\n            / (sigma*sigma*(1-std::exp(-kappa*maturity)))*sqrtProcess->x0();\n\n    const chi_squared_type dist(df, ncp);\n        \n    const Real strikes[] = { 50, 75, 100, 125, 150, 200 };\n    for (double strike : strikes) {\n        const Option::Type optionType = (strike > fwd) ? Option::Call : Option::Put;\n\n        const Real expected = BlackCalculator(\n            optionType, strike, fwd,\n            std::sqrt(volTS->blackVariance(maturity, strike)),\n            rTS->discount(maturity)).value();\n\n        const CLVModelPayoff clvModelPayoff(optionType, strike, g);\n\n        const ext::function<Real(Real)> f = [&](Real xi) {\n            return clvModelPayoff(xi) * boost::math::pdf(dist, xi);\n        };\n\n        const Real calculated = GaussLobattoIntegral(1000, 1e-6)(\n            f, x.front(), x.back()) * rTS->discount(maturity);\n\n        const Real tol = 5e-3;\n        if (std::fabs(expected - calculated) > tol) {\n            BOOST_FAIL(\"failed to reproduce option SquaredCLVMOdel prices\"\n                    << \"\\n    time:       \" << maturityDate\n                    << \"\\n    strike:     \" << strike\n                    << \"\\n    expected:   \" << expected\n                    << \"\\n    calculated: \" << calculated);\n        }\n    }\n}\n\nvoid SquareRootCLVModelTest::testSquareRootCLVMappingFunction() {\n    BOOST_TEST_MESSAGE(\n        \"Testing mapping function of the square-root kernel process...\");\n\n    using namespace square_root_clv_model;\n\n    SavedSettings backup;\n\n    const Date todaysDate(16, Oct, 2016);\n    Settings::instance().evaluationDate() = todaysDate;\n    const Date maturityDate = todaysDate + Period(1, Years);\n\n    const DayCounter dc = Actual365Fixed();\n\n    const Real s0 = 100;\n    const Handle<Quote> spot(ext::make_shared<SimpleQuote>(s0));\n\n    const Rate r = 0.05;\n    const Rate q = 0.02;\n\n    const Handle<YieldTermStructure> rTS(flatRate(r, dc));\n    const Handle<YieldTermStructure> qTS(flatRate(q, dc));\n\n    //SABR\n    const Real beta =  0.95;\n    const Real alpha=  0.2;\n    const Real rho  = -0.9;\n    const Real gamma=  0.8;\n\n    const Handle<BlackVolTermStructure> sabrVol(\n        ext::make_shared<SABRVolTermStructure>(\n            alpha, beta, gamma, rho, s0, r, todaysDate, dc));\n\n    const ext::shared_ptr<GeneralizedBlackScholesProcess> bsProcess(\n        ext::make_shared<GeneralizedBlackScholesProcess>(\n            spot, qTS, rTS, sabrVol));\n\n    std::vector<Date> calibrationDates(1, todaysDate + Period(3, Months));\n    calibrationDates.reserve(Size(daysBetween(todaysDate, maturityDate)/7 + 1));\n    while (calibrationDates.back() < maturityDate)\n        calibrationDates.push_back(calibrationDates.back() + Period(1, Weeks));\n\n    // sqrt process\n    const Real kappa       = 1.0;\n    const Real theta       = 0.09;\n    const Volatility sigma = 0.2;\n    const Real x0          = 0.09;\n\n    const ext::shared_ptr<SquareRootProcess> sqrtProcess(\n        ext::make_shared<SquareRootProcess>(theta, kappa, sigma, x0));\n\n    const SquareRootCLVModel model(\n        bsProcess, sqrtProcess, calibrationDates, 14, 1-1e-10, 1e-10);\n\n    const ext::function<Real(Time, Real)> g = model.g();\n\n    const Real strikes[] = { 80, 100, 120 };\n    const Size offsets[] = { 92, 182, 183, 184, 185, 186, 365 };\n    for (unsigned long offset : offsets) {\n        const Date m = todaysDate + Period(offset, Days);\n        const Time t = dc.yearFraction(todaysDate, m);\n\n        const Real df  = 4*theta*kappa/(sigma*sigma);\n        const Real ncp = 4*kappa*std::exp(-kappa*t)\n                / (sigma*sigma*(1-std::exp(-kappa*t)))*sqrtProcess->x0();\n\n        const chi_squared_type dist(df, ncp);\n\n        const Real fwd = s0*qTS->discount(m)/rTS->discount(m);\n\n        for (double strike : strikes) {\n            const Option::Type optionType = (strike > fwd) ? Option::Call : Option::Put;\n\n            const Real expected = BlackCalculator(\n                optionType, strike, fwd,\n                std::sqrt(sabrVol->blackVariance(m, strike)),\n                rTS->discount(m)).value();\n\n            const CLVModelPayoff clvModelPayoff(optionType, strike, [&](Real x) { return g(t, x); });\n\n            const ext::function<Real(Real)> f = [&](Real xi) {\n                return clvModelPayoff(xi) * boost::math::pdf(dist, xi);\n            };\n\n            const Array x = model.collocationPointsX(m);\n            const Real calculated = GaussLobattoIntegral(1000, 1e-3)(\n                f, x.front(), x.back()) * rTS->discount(m);\n\n            const Real tol = 0.075;\n\n            if (std::fabs(expected) > 0.01\n                    && std::fabs((calculated - expected)/calculated) > tol) {\n                BOOST_FAIL(\"failed to reproduce option SquaredCLVMOdel prices\"\n                        << \"\\n    time:       \" << m\n                        << \"\\n    strike:     \" << strike\n                        << \"\\n    expected:   \" << expected\n                        << \"\\n    calculated: \" << calculated);\n            }\n        }\n    }\n}\n\nnamespace square_root_clv_model {\n    class SquareRootCLVCalibrationFunction : public CostFunction {\n      public:\n        SquareRootCLVCalibrationFunction(Array strikes,\n                                         const std::vector<Date>& resetDates,\n                                         const std::vector<Date>& maturityDates,\n                                         ext::shared_ptr<GeneralizedBlackScholesProcess> bsProcess,\n                                         Array refVols,\n                                         Size nScenarios = 10000)\n        : strikes_(std::move(strikes)), resetDates_(resetDates), maturityDates_(maturityDates),\n          bsProcess_(std::move(bsProcess)), refVols_(std::move(refVols)), nScenarios_(nScenarios) {\n            std::set<Date> c(resetDates.begin(), resetDates.end());\n            c.insert(maturityDates.begin(), maturityDates.end());\n            calibrationDates_.insert(\n                calibrationDates_.begin(), c.begin(), c.end());\n        }\n\n        Real value(const Array& params) const override {\n            const Array diff = values(params);\n\n            Real retVal = 0.0;\n            for (double i : diff)\n                retVal += i * i;\n\n            return retVal;\n        }\n\n        Disposable<Array> values(const Array& params) const override {\n            const Real theta = params[0];\n            const Real kappa = params[1];\n            const Real sigma = params[2];\n            const Real x0    = params[3];\n\n            const ext::shared_ptr<SimpleQuote> vol(\n                ext::make_shared<SimpleQuote>(0.1));\n\n            const Handle<YieldTermStructure> rTS(bsProcess_->riskFreeRate());\n            const Handle<YieldTermStructure> qTS(bsProcess_->dividendYield());\n            const Handle<Quote> spot(ext::make_shared<SimpleQuote>(\n                bsProcess_->x0()));\n\n            const ext::shared_ptr<PricingEngine> fwdEngine(\n                ext::make_shared<ForwardVanillaEngine<AnalyticEuropeanEngine> >(\n                    ext::make_shared<GeneralizedBlackScholesProcess>(\n                        spot, qTS, rTS,\n                        Handle<BlackVolTermStructure>(\n                            flatVol(rTS->referenceDate(), vol,\n                                    rTS->dayCounter())))));\n\n            const ext::shared_ptr<SquareRootProcess> sqrtProcess(\n                ext::make_shared<SquareRootProcess>(theta, kappa, sigma, x0));\n\n            const SquareRootCLVModel clvSqrtModel(\n                bsProcess_, sqrtProcess, calibrationDates_,\n                14, 1-1e-14, 1e-14);\n\n            const ext::function<Real(Time, Real)> gSqrt = clvSqrtModel.g();\n\n            Array retVal(resetDates_.size()*strikes_.size());\n\n            for (Size i=0, n=resetDates_.size(); i < n; ++i) {\n                const Date resetDate = resetDates_[i];\n                const Date maturityDate = maturityDates_[i];\n\n                const Time t0 = bsProcess_->time(resetDate);\n                const Time t1 = bsProcess_->time(maturityDate);\n\n                const Real df  = 4*theta*kappa/(sigma*sigma);\n                const Real ncp = 4*kappa*std::exp(-kappa*t0)\n                    / (sigma*sigma*(1-std::exp(-kappa*t0)))*x0;\n\n                typedef boost::math::non_central_chi_squared_distribution<Real>\n                    chi_squared_type;\n\n                const chi_squared_type dist(df, ncp);\n\n                const Real ncp1 = 4*kappa*std::exp(-kappa*(t1-t0))\n                    / (sigma*sigma*(1-std::exp(-kappa*(t1-t0))));\n\n                const LowDiscrepancy::ursg_type ursg = LowDiscrepancy::ursg_type(2, 1235UL);\n\n                std::vector<GeneralStatistics> stats(strikes_.size());\n\n                for (Size j=0; j < nScenarios_; ++j) {\n                    const std::vector<Real>& path = ursg.nextSequence().value;\n\n                    const Real x1 = boost::math::quantile(dist, path[0]);\n                    const Real u1 =\n                        sigma*sigma*(1-std::exp(-kappa*t0))/(4*kappa)*x1;\n\n                    const Real x2 = boost::math::quantile(\n                        chi_squared_type(df, ncp1*u1), path[1]);\n                    const Real u2 =\n                        sigma*sigma*(1-std::exp(-kappa*(t1-t0)))/(4*kappa)*x2;\n                    const Real X2 =\n                        u2*4*kappa/(sigma*sigma*(1-std::exp(-kappa*t1)));\n\n                    const Real s1 = gSqrt(t0, x1);\n                    const Real s2 = gSqrt(t1, X2);\n\n                    for (Size k=0; k < strikes_.size(); ++k) {\n                        const Real strike = strikes_[k];\n\n                        const Real payoff = (strike < 1.0)\n                            ?  s1 * std::max(0.0, strike - s2/s1)\n                            :  s1 * std::max(0.0, s2/s1 - strike);\n\n                        stats[k].add(payoff);\n                    }\n                }\n\n                const ext::shared_ptr<Exercise> exercise(\n                    ext::make_shared<EuropeanExercise>(maturityDate));\n\n                const DiscountFactor dF(\n                    bsProcess_->riskFreeRate()->discount(maturityDate));\n\n                for (Size k=0; k < strikes_.size(); ++k) {\n                    const Real strike = strikes_[k];\n                    const Real npv = stats[k].mean() * dF;\n\n                    const ext::shared_ptr<StrikedTypePayoff> payoff(\n                        ext::make_shared<PlainVanillaPayoff>(\n                            (strike < 1.0) ? Option::Put : Option::Call, strike));\n\n                    const ext::shared_ptr<ForwardVanillaOption> fwdOption(\n                        ext::make_shared<ForwardVanillaOption>(\n                            strike, resetDate, payoff, exercise));\n\n                    const Volatility implVol =\n                        QuantLib::detail::ImpliedVolatilityHelper::calculate(\n                            *fwdOption, *fwdEngine, *vol, npv, 1e-8, 200, 1e-4, 2.0);\n\n                    const Size idx = k + i*strikes_.size();\n                    retVal[idx] = implVol - refVols_[idx];\n                }\n            }\n\n            return retVal;\n        }\n\n\n      private:\n        const Array strikes_;\n        const std::vector<Date> resetDates_, maturityDates_;\n        const ext::shared_ptr<GeneralizedBlackScholesProcess> bsProcess_;\n        const Array refVols_;\n        const Size nScenarios_;\n\n        std::vector<Date> calibrationDates_;\n    };\n\n    class NonZeroConstraint : public Constraint {\n      private:\n        class Impl : public Constraint::Impl {\n          public:\n            bool test(const Array& params) const override {\n                const Real theta = params[0];\n                const Real kappa = params[1];\n                const Real sigma = params[2];\n                const Real x0    = params[3];\n\n                return (sigma >= 0.001 && kappa > 1e-6 && theta > 0.001\n                        && x0 > 1e-4);\n            }\n\n            Array upperBound(const Array& params) const override {\n                const Real upper[] = { 1.0, 1.0, 1.0, 2.0 };\n\n                return Array(upper, upper + 4);\n            }\n\n            Array lowerBound(const Array& params) const override {\n                const Real lower[] = { 0.001, 0.001, 0.001, 1e-4 };\n\n                return Array(lower, lower + 4);\n            }\n        };\n\n      public:\n        NonZeroConstraint()\n        : Constraint(ext::make_shared<NonZeroConstraint::Impl>()) {}\n    };\n}\n\nvoid SquareRootCLVModelTest::testForwardSkew() {\n    BOOST_TEST_MESSAGE(\n        \"Testing forward skew dynamics with square-root kernel process...\");\n\n    using namespace square_root_clv_model;\n\n    SavedSettings backup;\n\n    const Date todaysDate(16, Oct, 2016);\n    Settings::instance().evaluationDate() = todaysDate;\n    const Date endDate = todaysDate + Period(4, Years);\n\n    const DayCounter dc = Actual365Fixed();\n\n    // Heston model is used to generate an arbitrage free volatility surface\n    const Real s0    =  100;\n    const Real r     =  0.1;\n    const Real q     =  0.05;\n    const Real v0    =  0.09;\n    const Real kappa =  1.0;\n    const Real theta =  0.09;\n    const Real sigma =  0.3;\n    const Real rho   = -0.75;\n\n    const Handle<Quote> spot(ext::make_shared<SimpleQuote>(s0));\n    const Handle<YieldTermStructure> rTS(flatRate(r, dc));\n    const Handle<YieldTermStructure> qTS(flatRate(q, dc));\n\n    const ext::shared_ptr<HestonModel> hestonModel(\n        ext::make_shared<HestonModel>(\n            ext::make_shared<HestonProcess>(\n                rTS, qTS, spot, v0, kappa, theta, sigma, rho)));\n\n    const Handle<BlackVolTermStructure> blackVol(\n        ext::make_shared<HestonBlackVolSurface>(\n            Handle<HestonModel>(hestonModel)));\n\n    const Handle<LocalVolTermStructure> localVol(\n        ext::make_shared<NoExceptLocalVolSurface>(\n                blackVol, rTS, qTS, spot, std::sqrt(theta)));\n\n    const Real sTheta = 0.389302;\n    const Real sKappa = 0.1101849;\n    const Real sSigma = 0.275368;\n    const Real sX0    = 0.466809;\n\n    const ext::shared_ptr<SquareRootProcess> sqrtProcess(\n        ext::make_shared<SquareRootProcess>(\n            sTheta, sKappa, sSigma, sX0));\n\n    const ext::shared_ptr<GeneralizedBlackScholesProcess> bsProcess(\n        ext::make_shared<GeneralizedBlackScholesProcess>(\n            spot, qTS, rTS, blackVol));\n\n    std::vector<Date> calibrationDates(1, todaysDate + Period(6, Months));\n    while (calibrationDates.back() < endDate)\n        calibrationDates.push_back(calibrationDates.back() + Period(3, Months));\n\n    std::set<Date> clvCalibrationDates(\n        calibrationDates.begin(), calibrationDates.end());\n\n    Date tmpDate = todaysDate + Period(1, Days);\n    while (tmpDate < todaysDate + Period(1, Years)) {\n        clvCalibrationDates.insert(tmpDate);\n        tmpDate += Period(1, Weeks);\n    }\n\n    const SquareRootCLVModel clvSqrtModel(\n        bsProcess,\n        sqrtProcess,\n        std::vector<Date>(\n            clvCalibrationDates.begin(), clvCalibrationDates.end()),\n        14, 1-1e-14, 1e-14);\n\n    const ext::function<Real(Time, Real)> gSqrt = clvSqrtModel.g();\n\n    const ext::shared_ptr<SimpleQuote> vol(\n        ext::make_shared<SimpleQuote>(0.1));\n\n    const ext::shared_ptr<PricingEngine> fwdEngine(\n        ext::make_shared<ForwardVanillaEngine<AnalyticEuropeanEngine> >(\n            ext::make_shared<GeneralizedBlackScholesProcess>(\n                spot, qTS, rTS,\n                Handle<BlackVolTermStructure>(flatVol(todaysDate, vol, dc)))));\n\n\n    // forward skew of the Heston-SLV model\n    std::vector<Time> mandatoryTimes;\n    mandatoryTimes.reserve(calibrationDates.size());\n    for (auto& calibrationDate : calibrationDates)\n        mandatoryTimes.push_back(dc.yearFraction(todaysDate, calibrationDate));\n\n    const Size tSteps = 200;\n    const TimeGrid grid(mandatoryTimes.begin(), mandatoryTimes.end(), tSteps);\n\n    std::vector<Date> resetDates, maturityDates;\n    std::vector<Size> resetIndices, maturityIndices;\n    for (Size i=0, n = calibrationDates.size()-2; i < n; ++i) {\n        resetDates.push_back(calibrationDates[i]);\n        maturityDates.push_back(calibrationDates[i+2]);\n\n        const Time resetTime    = mandatoryTimes[i];\n        const Time maturityTime = mandatoryTimes[i+2];\n\n        resetIndices.push_back(grid.closestIndex(resetTime)-1);\n        maturityIndices.push_back(grid.closestIndex(maturityTime)-1);\n    }\n\n    const Real strikes[] = {\n        0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2,\n        1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0\n    };\n\n    const Size nScenarios = 20000;\n    Array refVols(resetIndices.size()*LENGTH(strikes));\n\n    // finite difference calibration of Heston SLV model\n\n    // define Heston Stochastic Local Volatility model\n    const Real eta = 0.25;\n    const Real corr = -0.0;\n\n    const ext::shared_ptr<HestonProcess> hestonProcess4slv(\n        ext::make_shared<HestonProcess>(\n            rTS, qTS, spot, v0, kappa, theta, eta*sigma, corr));\n\n    const Handle<HestonModel> hestonModel4slv(\n        ext::make_shared<HestonModel>(hestonProcess4slv));\n\n    const HestonSLVFokkerPlanckFdmParams logParams = {\n        301, 601, 1000, 30, 2.0, 0, 2,\n        0.1, 1e-4, 10000,\n        1e-5, 1e-5, 0.0000025, 1.0, 0.1, 0.9, 1e-5,\n        FdmHestonGreensFct::Gaussian,\n        FdmSquareRootFwdOp::Log,\n        FdmSchemeDesc::ModifiedCraigSneyd()\n    };\n\n    const ext::shared_ptr<LocalVolTermStructure> leverageFctFDM =\n        HestonSLVFDMModel(localVol, hestonModel4slv, endDate, logParams).\n            leverageFunction();\n\n    //  calibrating to forward volatility dynamics\n\n    const ext::shared_ptr<HestonSLVProcess> fdmSlvProcess(\n        ext::make_shared<HestonSLVProcess>(\n            hestonProcess4slv, leverageFctFDM));\n\n    std::vector<std::vector<GeneralStatistics> > slvStats(\n        calibrationDates.size()-2,\n            std::vector<GeneralStatistics>(LENGTH(strikes)));\n\n    typedef SobolBrownianBridgeRsg rsg_type;\n    typedef MultiPathGenerator<rsg_type>::sample_type sample_type;\n\n    const Size factors = fdmSlvProcess->factors();\n\n    const ext::shared_ptr<MultiPathGenerator<rsg_type> > pathGen(\n        ext::make_shared<MultiPathGenerator<rsg_type> >(\n            fdmSlvProcess, grid, rsg_type(factors, grid.size()-1), false));\n\n    for (Size k=0; k < nScenarios; ++k) {\n        const sample_type& path = pathGen->next();\n\n        for (Size i=0, n=resetIndices.size(); i < n; ++i) {\n            const Real S_t1 = path.value[0][resetIndices[i]];\n            const Real S_T1 = path.value[0][maturityIndices[i]];\n\n            for (Size j=0; j < LENGTH(strikes); ++j) {\n                const Real strike = strikes[j];\n                    slvStats[i][j].add((strike < 1.0)\n                        ? S_t1 * std::max(0.0, strike - S_T1/S_t1)\n                        : S_t1 * std::max(0.0, S_T1/S_t1 - strike));\n            }\n\n        }\n    }\n\n    for (Size i=0, n=resetIndices.size(); i < n; ++i) {\n        const Date resetDate = calibrationDates[i];\n        const Date maturityDate(calibrationDates[i+2]);\n        const DiscountFactor df = rTS->discount(maturityDate);\n\n        const ext::shared_ptr<Exercise> exercise(\n            ext::make_shared<EuropeanExercise>(maturityDate));\n\n        for (Size j=0; j < LENGTH(strikes); ++j) {\n            const Real strike = strikes[j];\n            const Real npv = slvStats[i][j].mean()*df;\n\n            const ext::shared_ptr<StrikedTypePayoff> payoff(\n                ext::make_shared<PlainVanillaPayoff>(\n                    (strike < 1.0) ? Option::Put : Option::Call, strike));\n\n            const ext::shared_ptr<ForwardVanillaOption> fwdOption(\n                ext::make_shared<ForwardVanillaOption>(\n                    strike, resetDate, payoff, exercise));\n\n            const Volatility implVol =\n                QuantLib::detail::ImpliedVolatilityHelper::calculate(\n                    *fwdOption, *fwdEngine, *vol, npv, 1e-8, 200, 1e-4, 2.0);\n\n            const Size idx = j + i*LENGTH(strikes);\n            refVols[idx] = implVol;\n        }\n    }\n\n    SquareRootCLVCalibrationFunction costFunction(\n        Array(strikes, strikes+LENGTH(strikes)),\n        resetDates,\n        maturityDates,\n        bsProcess,\n        refVols,\n        nScenarios);\n\n    NonZeroConstraint nonZeroConstraint;\n\n    CompositeConstraint constraint(\n        nonZeroConstraint,\n        HestonModel::FellerConstraint());\n\n    Array params(4);\n    params[0] = sTheta; params[1] = sKappa;\n    params[2] = sSigma; params[3] = sX0;\n\n\n    //    Optimization would take too long\n    //\n    //    Problem prob(costFunction, nonZeroConstraint, params);\n    //\n    //    Simplex simplex(0.05);\n    //    simplex.minimize(prob, EndCriteria(400, 40, 1.0e-8, 1.0e-8, 1.0e-8));\n\n    const Real tol = 0.5;\n    const Real costValue = costFunction.value(params);\n\n    if (costValue > tol) {\n        BOOST_FAIL(\"failed to reproduce small cost function value\"\n                << \"\\n    value:       \" << costValue\n                << \"\\n    tolerance:   \" << tol);\n    }\n\n    const Date maturityDate = todaysDate + Period(1, Years);\n    const Time maturityTime = bsProcess->time(maturityDate);\n\n    const ext::shared_ptr<Exercise> europeanExercise(\n        ext::make_shared<EuropeanExercise>(maturityDate));\n\n    VanillaOption vanillaATMOption(\n        ext::make_shared<PlainVanillaPayoff>(Option::Call,\n            s0*qTS->discount(maturityDate)/rTS->discount(maturityDate)),\n        europeanExercise);\n\n    vanillaATMOption.setPricingEngine(\n        ext::make_shared<AnalyticHestonEngine>(hestonModel));\n\n    const Volatility atmVol = vanillaATMOption.impliedVolatility(\n        vanillaATMOption.NPV(),\n        ext::make_shared<GeneralizedBlackScholesProcess>(spot, qTS, rTS,\n            Handle<BlackVolTermStructure>(flatVol(std::sqrt(theta), dc))));\n\n    const ext::shared_ptr<PricingEngine> analyticEngine(\n        ext::make_shared<AnalyticDoubleBarrierBinaryEngine>(\n            ext::make_shared<GeneralizedBlackScholesProcess>(\n                spot, qTS, rTS,\n                Handle<BlackVolTermStructure>(flatVol(atmVol, dc)))));\n\n    const ext::shared_ptr<PricingEngine> fdSLVEngine(\n        ext::make_shared<FdHestonDoubleBarrierEngine>(\n            hestonModel4slv.currentLink(),\n            51, 201, 51, 1,\n            FdmSchemeDesc::Hundsdorfer(), leverageFctFDM));\n\n    const Size n = 16;\n    Array barrier_lo(n), barrier_hi(n), bsNPV(n), slvNPV(n);\n\n    const ext::shared_ptr<CashOrNothingPayoff> payoff =\n        ext::make_shared<CashOrNothingPayoff>(Option::Call, 0.0, 1.0);\n\n    for (Size i=0; i < n; ++i) {\n        const Real dist = 20.0+5.0*i;\n\n        barrier_lo[i] = std::max(s0 - dist, 1e-2);\n        barrier_hi[i] = s0 + dist;\n        DoubleBarrierOption doubleBarrier(\n            DoubleBarrier::KnockOut, barrier_lo[i], barrier_hi[i], 0.0,\n            payoff,\n            europeanExercise);\n\n        doubleBarrier.setPricingEngine(analyticEngine);\n        bsNPV[i] = doubleBarrier.NPV();\n\n        doubleBarrier.setPricingEngine(fdSLVEngine);\n        slvNPV[i] = doubleBarrier.NPV();\n    }\n\n\n    const TimeGrid bGrid(maturityTime, tSteps);\n\n    const PseudoRandom::ursg_type ursg = PseudoRandom::ursg_type(tSteps, 1235UL);\n\n    std::vector<GeneralStatistics> stats(n);\n\n    const Real df = 4*sTheta*sKappa/(sSigma*sSigma);\n\n    for (Size i=0; i < nScenarios; ++i) {\n        std::vector<bool> touch(n, false);\n\n        const std::vector<Real>& path = ursg.nextSequence().value;\n\n        Real x = sX0;\n\n        for (Size j=0; j < tSteps; ++j) {\n            const Time t0 = bGrid.at(j);\n            const Time t1 = bGrid.at(j+1);\n\n            const Real ncp = 4*sKappa*std::exp(-sKappa*(t1-t0))\n                / (sSigma*sSigma*(1-std::exp(-sKappa*(t1-t0))))*x;\n\n            const boost::math::non_central_chi_squared_distribution<Real>\n                dist(df, ncp);\n\n            const Real u = boost::math::quantile(dist, path[j]);\n\n            x = sSigma*sSigma*(1-std::exp(-sKappa*(t1-t0)))/(4*sKappa) * u;\n\n            const Real X = x*4*sKappa/(sSigma*sSigma*(1-std::exp(-sKappa*t1)));\n\n            const Real s = gSqrt(t1, X);\n\n            if (t1 > 0.05) {\n                for (Size u=0; u < n; ++u) {\n                    if (s <= barrier_lo[u] || s >= barrier_hi[u]) {\n                        touch[u] = true;\n                    }\n                }\n            }\n        }\n        for (Size u=0; u < n; ++u) {\n            if (touch[u]) {\n                stats[u].add(0.0);\n            }\n            else {\n                stats[u].add(rTS->discount(maturityDate));\n            }\n        }\n    }\n\n\n    for (Size u=0; u < n; ++u) {\n        const Real calculated = stats[u].mean();\n        const Real error = stats[u].errorEstimate();\n        const Real expected = slvNPV[u];\n\n        const Real tol = 2.35*error;\n\n        if (std::fabs(calculated-expected) > tol) {\n            BOOST_FAIL(\"failed to reproduce CLV double no touch barrier price\"\n                    << \"\\n    CLV value:   \" << calculated\n                    << \"\\n    error    :   \" << error\n                    << \"\\n    SLV value: \" << expected);\n        }\n    }\n}\n\n \ntest_suite* SquareRootCLVModelTest::experimental() {\n    auto* suite = BOOST_TEST_SUITE(\"SquareRootCLVModel tests\");\n\n    suite->add(QUANTLIB_TEST_CASE(\n        &SquareRootCLVModelTest::testSquareRootCLVVanillaPricing));\n\n    suite->add(QUANTLIB_TEST_CASE(\n        &SquareRootCLVModelTest::testSquareRootCLVMappingFunction));\n\n//    this test takes very long\n//    suite->add(QUANTLIB_TEST_CASE(\n//        &SquareRootCLVModelTest::testForwardSkew));\n\n    return suite;\n}\n", "meta": {"hexsha": "617cdba10b367dc2ffb55441556b6865763311c6", "size": 30703, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test-suite/squarerootclvmodel.cpp", "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": "test-suite/squarerootclvmodel.cpp", "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": "test-suite/squarerootclvmodel.cpp", "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": 36.726076555, "max_line_length": 101, "alphanum_fraction": 0.6034263753, "num_tokens": 7978, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936438, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4721454706960471}}
{"text": "#ifndef __SCHEME_UTILITY_COMPLEXTYPE\n#define __SCHEME_UTILITY_COMPLEXTYPE\n\n#include \"rationaltype.hpp\"\n#include \"bigint.hpp\"\n#include <boost/operators.hpp>\n\nclass ComplexType:\n    public boost::equality_comparable<ComplexType, \n    boost::arithmetic<ComplexType>\n    >\n{\n    bool exact_;\n    RationalType realr_, imagr_;\n    long double reald_, imagd_;\n\n\n    public:\n        ComplexType();\n        ComplexType(const RationalType& a, const RationalType& b);\n        ComplexType(const RationalType& a);\n        ComplexType(const RationalType& a, const long double b);\n        ComplexType(const long double a);\n        ComplexType(const long double a, const RationalType& b);\n        ComplexType(const long double a, const long double b);\n        bool operator == (const ComplexType& b) const;\n        ComplexType& operator += (const ComplexType& b);\n        ComplexType& operator -= (const ComplexType& b);\n        ComplexType& operator *= (const ComplexType& b);\n        ComplexType& operator /= (const ComplexType& b);\n        friend std::istream& operator >>(std::istream& i, ComplexType& a);\n        friend std::ostream& operator <<(std::ostream& o, const ComplexType& a);\n        bool exact() const;\n        bool isReal() const;\n        bool isRational() const;\n        bool isInt() const;\n        BigInt toInt() const;\n        RationalType getRealR() const;\n        RationalType getImagR() const;\n        long double getRealD() const;\n        long double getImagD() const;\n        ComplexType& setRealR(const RationalType& b);\n        ComplexType& setImagR(const RationalType& b);\n        ComplexType& setRealD(const long double b);\n        ComplexType& setImagD(const long double d);\n        ComplexType operator -();\n        ComplexType& toexact();\n        ComplexType& toinexact();\n\n};\n\n\n#endif\n", "meta": {"hexsha": "d0d1048462e18bcd4c59684c9daee7c503cccc2a", "size": 1802, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "utility/complextype.hpp", "max_stars_repo_name": "htfy96/htscheme", "max_stars_repo_head_hexsha": "b44c9f9672f69d9b3c2eb1c80969bcfcfec9990f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2015-07-07T01:30:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-14T10:45:01.000Z", "max_issues_repo_path": "utility/complextype.hpp", "max_issues_repo_name": "htfy96/htscheme", "max_issues_repo_head_hexsha": "b44c9f9672f69d9b3c2eb1c80969bcfcfec9990f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "utility/complextype.hpp", "max_forks_repo_name": "htfy96/htscheme", "max_forks_repo_head_hexsha": "b44c9f9672f69d9b3c2eb1c80969bcfcfec9990f", "max_forks_repo_licenses": ["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.3703703704, "max_line_length": 80, "alphanum_fraction": 0.65427303, "num_tokens": 426, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038221, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4721454655622163}}
{"text": "//          Copyright Carl Philipp Reh 2009 - 2016.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n\n#include <fcppt/algorithm/set_difference.hpp>\n#include <fcppt/preprocessor/disable_gcc_warning.hpp>\n#include <fcppt/preprocessor/pop_warning.hpp>\n#include <fcppt/preprocessor/push_warning.hpp>\n#include <fcppt/config/external_begin.hpp>\n#include <boost/test/unit_test.hpp>\n#include <set>\n#include <fcppt/config/external_end.hpp>\n\n\n\nFCPPT_PP_PUSH_WARNING\nFCPPT_PP_DISABLE_GCC_WARNING(-Weffc++)\n\nBOOST_AUTO_TEST_CASE(\n\talgorithm_set_difference\n)\n{\nFCPPT_PP_POP_WARNING\n\n\ttypedef\n\tstd::set<\n\t\tint\n\t>\n\tint_set;\n\n\tBOOST_CHECK((\n\t\tfcppt::algorithm::set_difference(\n\t\t\tint_set{\n\t\t\t\t1, 2, 3\n\t\t\t},\n\t\t\tint_set{\n\t\t\t\t2, 3, 4\n\t\t\t}\n\t\t)\n\t\t==\n\t\tint_set{\n\t\t\t1\n\t\t}\n\t));\n}\n", "meta": {"hexsha": "b9061cae6a87a4e40f5d669206562e93701db2cd", "size": 875, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/algorithm/set_difference.cpp", "max_stars_repo_name": "vinzenz/fcppt", "max_stars_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "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": "test/algorithm/set_difference.cpp", "max_issues_repo_name": "vinzenz/fcppt", "max_issues_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "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/algorithm/set_difference.cpp", "max_forks_repo_name": "vinzenz/fcppt", "max_forks_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "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": 18.2291666667, "max_line_length": 61, "alphanum_fraction": 0.7131428571, "num_tokens": 260, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.705785040214066, "lm_q1q2_score": 0.4720856814643472}}
{"text": "// Copyright Louis Dionne 2013\n\n// Use, modification and distribution is subject to the Boost Software\n// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy\n// at http://www.boost.org/LICENSE_1_0.txt)\n\n#include <boost/assert.hpp>\n#include <boost/graph/directed_graph.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/hawick_circuits.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/next_prior.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <cstdlib>\n#include <iostream>\n#include <iterator>\n#include <map>\n\ntemplate < typename OutputStream > struct cycle_printer\n{\n    cycle_printer(OutputStream& stream) : os(stream) {}\n\n    template < typename Path, typename Graph >\n    void cycle(Path const& p, Graph const& g)\n    {\n        if (p.empty())\n            return;\n\n        // Get the property map containing the vertex indices\n        // so we can print them.\n        typedef typename boost::property_map< Graph,\n            boost::vertex_index_t >::const_type IndexMap;\n\n        IndexMap indices = get(boost::vertex_index, g);\n\n        // Iterate over path printing each vertex that forms the cycle.\n        typename Path::const_iterator i, before_end = boost::prior(p.end());\n        for (i = p.begin(); i != before_end; ++i)\n        {\n            os << get(indices, *i) << \" \";\n        }\n        os << get(indices, *i) << '\\n';\n    }\n    OutputStream& os;\n};\n\n// VertexPairIterator is an iterator over pairs of whitespace separated\n// vertices `u` and `v` representing a directed edge from `u` to `v`.\ntemplate < typename Graph, typename VertexPairIterator >\nvoid build_graph(Graph& graph, unsigned int const nvertices,\n    VertexPairIterator first, VertexPairIterator last)\n{\n    typedef boost::graph_traits< Graph > Traits;\n    typedef typename Traits::vertex_descriptor vertex_descriptor;\n    std::map< unsigned int, vertex_descriptor > vertices;\n\n    for (unsigned int i = 0; i < nvertices; ++i)\n        vertices[i] = add_vertex(graph);\n\n    for (; first != last; ++first)\n    {\n        unsigned int u = *first++;\n\n        BOOST_ASSERT_MSG(first != last,\n            \"there is a lonely vertex at the end of the edge list\");\n\n        unsigned int v = *first;\n\n        BOOST_ASSERT_MSG(vertices.count(u) == 1 && vertices.count(v) == 1,\n            \"specified a vertex over the number of vertices in the graph\");\n\n        add_edge(vertices[u], vertices[v], graph);\n    }\n    BOOST_ASSERT(num_vertices(graph) == nvertices);\n}\n\nint main(int argc, char const* argv[])\n{\n    if (argc < 2)\n    {\n        std::cout << \"usage: \" << argv[0] << \" num_vertices < input\\n\";\n        return EXIT_FAILURE;\n    }\n\n    unsigned int num_vertices = boost::lexical_cast< unsigned int >(argv[1]);\n    std::istream_iterator< unsigned int > first_vertex(std::cin), last_vertex;\n    boost::directed_graph<> graph;\n    build_graph(graph, num_vertices, first_vertex, last_vertex);\n\n    cycle_printer< std::ostream > visitor(std::cout);\n    boost::hawick_circuits(graph, visitor);\n\n    return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "68265603536705d5c6e66ffc6baa751c14942c0a", "size": 3041, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/graph/example/hawick_circuits.cpp", "max_stars_repo_name": "uosorio/heroku_face", "max_stars_repo_head_hexsha": "7d6465e71dba17a15d8edaef520adb2fcd09d91e", "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": "3rdparty/boost_1_73_0/libs/graph/example/hawick_circuits.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 130.0, "max_issues_repo_issues_event_min_datetime": "2016-06-22T22:11:25.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-29T20:24:09.000Z", "max_forks_repo_path": "3rdparty/boost_1_73_0/libs/graph/example/hawick_circuits.cpp", "max_forks_repo_name": "qingkouwei/mediaones", "max_forks_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2015-07-08T19:18:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-14T16:39:56.000Z", "avg_line_length": 32.0105263158, "max_line_length": 78, "alphanum_fraction": 0.6596514305, "num_tokens": 710, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.705785040214066, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.4720856768057408}}
{"text": "// Copyright (C) 2001-2003\r\n// William E. Kempf\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#include <boost/thread/thread.hpp>\r\n#include <boost/thread/once.hpp>\r\n#include <iostream>\r\nusing namespace std;\r\n\r\n\r\n\r\ntemplate <int n> struct F{\r\n  \r\n    enum {Result = n * F<n -1>::Result};   \r\n};\r\n\r\ntemplate <> struct F<1>{\r\n  \r\n    enum {Result = 1};   \r\n};\r\n\r\n\r\nint main(int argc, char* argv[])\r\n{\r\ncout<< F<3>::Result<<endl;\r\n}\r\n", "meta": {"hexsha": "d869cefd0526002e970689b10b76169b8249a5c4", "size": 548, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "templates/meta_prog.cpp", "max_stars_repo_name": "IgorHersht/proxygen_ih", "max_stars_repo_head_hexsha": "616a8eb899196d2a130e14c0fabcae1944e34b7d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2017-11-10T05:18:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-29T15:38:25.000Z", "max_issues_repo_path": "templates/meta_prog.cpp", "max_issues_repo_name": "IgorHersht/proxygen_ih", "max_issues_repo_head_hexsha": "616a8eb899196d2a130e14c0fabcae1944e34b7d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "templates/meta_prog.cpp", "max_forks_repo_name": "IgorHersht/proxygen_ih", "max_forks_repo_head_hexsha": "616a8eb899196d2a130e14c0fabcae1944e34b7d", "max_forks_repo_licenses": ["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.8965517241, "max_line_length": 82, "alphanum_fraction": 0.6149635036, "num_tokens": 151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.4720856731855796}}
{"text": "#include \"SPlisHSPlasH/Common.h\"\n#include <Eigen/Dense>\n#include <iostream>\n#include \"SPlisHSPlasH/Utilities/Timing.h\"\n#include \"Utilities/PartioReaderWriter.h\"\n#include \"Utilities/OBJLoader.h\"\n#include \"SPlisHSPlasH/Utilities/PoissonDiskSampling.h\"\n#include \"Utilities/FileSystem.h\"\n#include \"Utilities/StringTools.h\"\n\n// Enable memory leak detection\n#ifdef _DEBUG\n#ifndef EIGEN_ALIGN\n\t#define new DEBUG_NEW \n#endif\n#endif\n\nusing namespace SPH;\nusing namespace Eigen;\nusing namespace std;\n\nstring inputFile = \"\";\nstring outputFile = \"\";\nReal particleRadius = 0.025;\nVector3r scale = Vector3r::Ones();\n\n// main \nint main( int argc, char **argv )\n{\n\tREPORT_MEMORY_LEAKS;\n\n\tfor (int i = 1; i < argc; i++)\n\t{\n\t\tstring argStr = argv[i];\n\t\tstring type_str = argStr.substr(0, 2);\n\t\tif ((type_str == \"-r\") && (i+1 < argc))\n\t\t\tparticleRadius = stof(argv[++i]);\n\t\telse if ((type_str == \"-s\") && (i + 1 < argc))\n\t\t{\n\t\t\tvector<string> tokens;\n\t\t\tStringTools::tokenize(argv[++i], tokens, \",\");\n\t\t\tscale[0] = stof(tokens[0]);\n\t\t\tscale[1] = stof(tokens[1]);\n\t\t\tscale[2] = stof(tokens[2]);\n\t\t}\n\t\telse if (i + 1 < argc)\n\t\t{\n\t\t\tinputFile = argv[i];\n\t\t\toutputFile = argv[++i];\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstd::cerr << \"Not enough parameters!\\n\";\n\t\t\tstd::cerr << \"Usage: SurfaceSampling.exe [-r particle_radius] [-s scaleX,scaleY,scaleZ] in.obj out.bgeo\\n\";\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\tTriangleMesh mesh;\n\tOBJLoader::loadObj(inputFile, mesh, scale);\n\n\tstd::cout << \"Surface sampling of \" << inputFile << \"\\n\";\n\tSTART_TIMING(\"Poisson disk sampling\");\n\tPoissonDiskSampling sampling;\n\tstd::vector<Vector3r> samplePoints;\n\tsampling.sampleMesh(mesh.numVertices(), mesh.getVertices().data(), mesh.numFaces(), mesh.getFaces().data(), particleRadius, 10, 1, samplePoints);\n\tSTOP_TIMING_AVG;\n\tstd::cout << \"Number of sample points: \" << samplePoints.size() << \"\\n\";\n\n\n\tPartioReaderWriter::writeParticles(outputFile, (unsigned int) samplePoints.size(), samplePoints.data(), NULL, particleRadius);\n\n\tTiming::printAverageTimes();\n\tTiming::printTimeSums();\n\t\n\treturn 0;\n}\n\n", "meta": {"hexsha": "25010ed78560e6ffeb70f63a12ee54c01a48a92b", "size": 2026, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tools/SurfaceSampling/main.cpp", "max_stars_repo_name": "douysu/SPlisHSPlasH", "max_stars_repo_head_hexsha": "75088fbfd77d8d990d99d614b3f20000323284e7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-11-22T08:36:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-02T02:23:38.000Z", "max_issues_repo_path": "Tools/SurfaceSampling/main.cpp", "max_issues_repo_name": "HuangChunying/SPlisHSPlasH", "max_issues_repo_head_hexsha": "139e5fd0e4f0ace801f039ab065a2e5ee72f8f9f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-11-28T03:31:17.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-29T12:54:26.000Z", "max_forks_repo_path": "Tools/SurfaceSampling/main.cpp", "max_forks_repo_name": "HuangChunying/SPlisHSPlasH", "max_forks_repo_head_hexsha": "139e5fd0e4f0ace801f039ab065a2e5ee72f8f9f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-20T13:59:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-20T13:59:39.000Z", "avg_line_length": 25.6455696203, "max_line_length": 146, "alphanum_fraction": 0.6816386969, "num_tokens": 588, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850154599562, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.4720856555895994}}
{"text": "#include \"mex.h\"\n#include <Eigen/Dense>\n#include <Eigen/SparseCore>\n#include \"mexHelpers.cpp\"\n#include \"panozo/Param_State.h\"\n#include \"panozo/GlobalLocalParametrization.h\"\n#include \"panozo/StateManager.h\"\n#include <igl/components.h>\n#include <iostream>\n\nusing namespace std;\nusing namespace Eigen;\n\n\nvoid mexFunction(int nlhs, mxArray *plhs[],\n\tint nrhs, const mxArray*prhs[])\n{\n\t// assign input\n\tint n_tri = mxGetM(prhs[0]); // # rows of F\n\tint d_simplex = mxGetN(prhs[0]); // # cols of F\n\tint n_vert = mxGetM(prhs[1]); // # rows of V\n\tint dim = mxGetN(prhs[1]); // # cols of V\n\tconst Map<MatrixXd, Aligned> Fmatlab(mxGetPr(prhs[0]), n_tri, d_simplex);\n\tconst Map<MatrixXd, Aligned> V(mxGetPr(prhs[1]), n_vert, dim);\n\t\n\t// update index numbers to 0-base\n\tMatrixXd Fd (Fmatlab);\n\tFd = Fd.array() - 1;\n    MatrixXi F = MatrixXi::Zero(Fd.rows(), Fd.cols());\n    \n    for(int i = 0; i < Fd.rows(); i++)\n    {\n        for(int j = 0; j < Fd.cols(); j++)\n        {\n            F(i, j) = Fd(i, j);\n        }\n    }\n\n\t// compute\n    \n    Param_State state;\n    \n    state.method = Param_State::GLOBAL_ARAP_IRLS;\n    state.flips_linesearch = true;\n    state.update_all_energies = false;\n    state.proximal_p = 0.0001;\n    \n    state.V = V;\n    state.F = F;\n    state.v_num = state.V.rows();\n    state.f_num = state.F.rows();\n    \n    igl::doublearea(state.V,state.F, state.M); state.M /= 2.;\n\n    state.global_local_energy = Param_State::SYMMETRIC_DIRICHLET;\n    state.cnt_flips = false;\n    \n    state.mesh_area = state.M.sum();\n    //state.V /= sqrt(state.mesh_area);\n    //state.mesh_area = 1;\n    \n    StateManager state_manager;\n    GlobalLocalParametrization param(state_manager, &state);\n    \n    param.init_parametrization();\n    \n    MatrixXd UV = state.uv;\n\n\t// assign outputs\n\tmapDenseMatrixToMex(UV, &(plhs[0]));\n}", "meta": {"hexsha": "927aa19ef7fa76534329df1d483b3c6473251533", "size": 1817, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/2D/lib/mex/tutte_embedding_mex.cpp", "max_stars_repo_name": "MusheghShahinyan/BCQN", "max_stars_repo_head_hexsha": "40f301e963d8b1f7f81466190578d56ec5db88cd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2019-07-23T16:35:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-04T11:47:42.000Z", "max_issues_repo_path": "code/2D/lib/mex/tutte_embedding_mex.cpp", "max_issues_repo_name": "MusheghShahinyan/BCQN", "max_issues_repo_head_hexsha": "40f301e963d8b1f7f81466190578d56ec5db88cd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-07-10T12:12:18.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-10T12:12:18.000Z", "max_forks_repo_path": "code/2D/lib/mex/tutte_embedding_mex.cpp", "max_forks_repo_name": "MusheghShahinyan/BCQN", "max_forks_repo_head_hexsha": "40f301e963d8b1f7f81466190578d56ec5db88cd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-02-21T06:12:40.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-27T09:58:32.000Z", "avg_line_length": 25.5915492958, "max_line_length": 74, "alphanum_fraction": 0.6323610347, "num_tokens": 546, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938819, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4720787081305063}}
{"text": "\n#include <cmath>\n#include <map>\n#include <math.h>  // pow\n#include <sys/time.h>\n#include <sys/resource.h>   // check the memory usage\n\n#include <iostream>\n#include <stdio.h>\n#include <thread>\n#include <vector>\n\n#include <NTL/ZZ.h>\n#include <NTL/BasicThreadPool.h>\n \n\n#include <HELR/TestScheme.h>\n#include <HELR/Cipher.h>\n#include <HELR/CZZ.h>\n#include <HELR/EvaluatorUtils.h>\n#include <HELR/Message.h>\n#include <HELR/Params.h>\n#include <HELR/PubKey.h>\n#include <HELR/Scheme.h>\n#include <HELR/SchemeAlgo.h>\n#include <HELR/SchemeAux.h>\n#include <HELR/SecKey.h>\n#include <HELR/StringUtils.h>\n\n\n#include \"LRtest.h\"\n#include \"HELR.h\"\n\n#define debug 0\n\n\nlong LogReg::getctlvl(Cipher& ctxt){\n    long nBits = NumBits(ctxt.mod)-1;\n    return nBits;\n}\n\n\n\n//---------------------------------------------------------------------------------------------------\n\n//! @ output ztrain = (2*y[k]-1) * (1, x[k])  -> encryption: zTrainCipher\nvoid LogReg::EncryptData(Cipher*& zTrainCipher, dMat zTrain){\n    \n    //long slots = LRparams.n_training;\n    \n    CZZ**  mvec= new CZZ*[LRparams.dim1];\n    \n    // zTrainCipher = (2*y[k]-1) * (1, x[k])\n    for (long i = 0; i < LRparams.dim1; ++i){\n        mvec[i]= new CZZ[LRparams.nslots];\n        for(int k=0; k< LRparams.nslots; ++k){\n            if(zTrain[k][i]!=0){\n                mvec[i][k].r = scaleup(zTrain[k][i], LRparams.logp-3);  // logp/8\n            }\n            else{\n                mvec[i][k].r = to_ZZ(\"0\");\n            }\n            mvec[i][k].i = to_ZZ(\"0\");\n        }\n    }\n    \n    NTL_EXEC_RANGE(LRparams.dim1, first, last);\n    for (long i = first; i < last; ++i){\n        zTrainCipher[i] = scheme.encrypt(mvec[i], LRparams.nslots);\n    }\n    NTL_EXEC_RANGE_END;\n\n   \n    delete[] mvec;\n\n}\n\n\nvoid LogReg::show_and_compare(dVec& theta, dMat zTrain, CZZ*& dtheta){\n    \n    LR_poly(theta, zTrain, LRparams);\n    \n    double maxErrorBit = 0.0;\n    double minRelativeBit= 20.0;\n    \n    for(int i=0; i< LRparams.dim1; i++){\n        ZZ msg_scaleup= scaleup(theta[i], LRparams.logp);\n        \n        cout << \"m \" << i << \" : [\"  <<  msg_scaleup << \"], theta: \" << theta[i] << endl;   // unencrypted\n        \n        double theta;\n        conv(theta, dtheta[i].r);\n        theta = scaledown(theta, LRparams.logp);\n        \n        cout << \"d \" << i << \" : [\"  << dtheta[i].r << \"], (HE)theta: \" << theta << endl;      // encrypted\n        cout << \"e \" << i << \" : [\"  << (msg_scaleup - dtheta[i].r)  << \"],  \";    // error\n        \n        \n        // Msg-bit\n        ZZ msgbnd= dtheta[i].r;\n        double MsgBit = 0.0;\n        if(msgbnd!=0)\n            MsgBit= (log(abs(msgbnd))/log(2)) ;\n        cout << \"Msg: \" << MsgBit << \", \";\n        \n        // Error-bit\n        ZZ error = (msg_scaleup - dtheta[i].r);\n        double ErrorBit = 0.0;\n        if(error!=0)\n            ErrorBit= (log(abs(error))/log(2)) ;\n        cout << \"Error: \" << ErrorBit << endl;\n        \n        double RelativeBit= MsgBit- ErrorBit;\n        \n        if(maxErrorBit < ErrorBit) maxErrorBit= ErrorBit;\n        if(minRelativeBit > RelativeBit)  minRelativeBit= RelativeBit;\n        cout << \"-------------------------------------------------------------\" << endl;\n        \n    }\n    \n    cout << \"MAX error bit : \" << maxErrorBit << \", Min relative-error bit: \" << minRelativeBit<< endl;\n    cout << \"-------------------------------------------------------------\" << endl;\n \n    \n}\n\n\n\nvoid LogReg::HElogreg(Cipher*& thetaCipher, Cipher*& zTrainCipher,  dMat zTrain){\n    struct rusage usage;\n    auto start= chrono::steady_clock::now();\n    \n    // zSumCipher = 1/(n/polyscale) * sum (2y[k]-1) x[k] = 1/n * sum z[k]\n    // At the first round, we just take zTrainCipher as theta (lvl= 2)\n    Cipher* zSumCipher= new Cipher[LRparams.dim1];\n    \n    //! rot and sum\n    Cipher* ctemp= new Cipher[LRparams.dim1];\n    \n    \n    NTL_EXEC_RANGE(LRparams.dim1, first, last);\n    for (long i = first; i < last; ++i){\n        zSumCipher[i]= zTrainCipher[i];\n        \n        for(long j= 0; j< LRparams.logn; ++j){\n            int l = (1<<j);\n            ctemp[i] = scheme.leftRotate(zSumCipher[i], l);\n            scheme.addAndEqual(zSumCipher[i], ctemp[i]);\n        }\n    \n        \n        scheme.modSwitchAndEqual(zSumCipher[i], LRparams.logn - LRparams.log2polyscale);\n        thetaCipher[i] = zSumCipher[i];\n    }\n    NTL_EXEC_RANGE_END;\n    \n    \n    auto end = std::chrono::steady_clock::now();\n    auto diff = end - start;\n    double timeElapsed= chrono::duration <double, milli> (diff).count()/1000.0;\n    double totaltime = timeElapsed;\n    \n    int ret = getrusage(RUSAGE_SELF,&usage);\n    \n    cout << \"-------------------------------------------------------------\" << endl;\n    cout << \"1-iter : mod(theta)= \" << getctlvl(thetaCipher[0]) << \", running time= \"  << timeElapsed << \"s, \" ;\n    cout<<  \"Mem= \" << usage.ru_maxrss/(1024)  << \"MB\" << endl;\n    cout << \"-------------------------------------------------------------\" << endl;\n    \n    \n\n    dVec mtheta(LRparams.dim1, 0.0);\n    CZZ* dtheta = new CZZ[LRparams.dim1];\n    for(int i = 0; i< LRparams.dim1; ++i){\n        dtheta[i] = (scheme.decrypt(secretKey, thetaCipher[i]))[0];\n    }\n    \n    show_and_compare(mtheta, zTrain, dtheta);\n \n    \n    //--------------------------------------------------------------\n    double zlvl =  getctlvl(zSumCipher[0]);\n    \n    for(int j= 1; j< LRparams.max_iter; ++j){\n        auto start= chrono::steady_clock::now();\n        \n        Cipher* gradCipher= new Cipher[LRparams.dim1];\n        \n        switch(LRparams.polydeg){\n            case 3:\n                gradCipher= getgrad_deg3(thetaCipher, zTrainCipher);\n                break;\n            case 7:\n                gradCipher= getgrad_deg7(thetaCipher, zTrainCipher);\n                break;\n                \n        }\n        \n        double tlvl = getctlvl(thetaCipher[0]);\n        double glvl = getctlvl(gradCipher[0]);\n        \n        NTL_EXEC_RANGE(LRparams.dim1, first, last);\n        for (long i = first; i < last; ++i){\n            Cipher ztemp = scheme.modEmbed(zSumCipher[i], zlvl- tlvl);\n            scheme.addAndEqual(thetaCipher[i], ztemp);\n            \n            scheme.modEmbedAndEqual(thetaCipher[i], tlvl- glvl);\n            scheme.subAndEqual(thetaCipher[i], gradCipher[i]);\n        }\n        NTL_EXEC_RANGE_END;\n        \n        \n        auto end = std::chrono::steady_clock::now();\n        auto diff = end - start;\n        double timeElapsed= chrono::duration <double, milli> (diff).count()/1000.0;\n        totaltime += timeElapsed;\n        \n        ret = getrusage(RUSAGE_SELF,&usage);\n        \n        delete[] gradCipher;\n        \n        cout << \"-------------------------------------------------------------\" << endl;\n        cout << j+1 << \"-iter : mod(theta)= \" << getctlvl(thetaCipher[0]) << \", running time= \"  << timeElapsed << \"s, \" ;\n        cout<<  \"Mem= \" << usage.ru_maxrss/1024  << \"MB\" << endl;\n        cout << \"-------------------------------------------------------------\" << endl;\n        \n        \n        for(int i=0; i< LRparams.dim1; ++i){\n            dtheta[i] = (scheme.decrypt(secretKey, thetaCipher[i]))[0];\n        }\n        \n        show_and_compare(mtheta, zTrain, dtheta);\n    }\n    \n    \n    cout << \"Total Evaluation Time = \" << totaltime << \" s\" << endl;\n\n    delete[] zSumCipher;\n    delete[] ctemp;\n    delete[] dtheta;\n   \n    \n}\n\n\n\n \nCipher* LogReg::getgrad_deg7(Cipher*& thetaCipher, Cipher*& zTrainCipher){\n    \n    //! compute ztheta =  (p* z[k]/8) (p* theta)/p  : mod(theta)+ logp\n    double tlvl =  getctlvl(thetaCipher[0]);\n    double zlvl =  getctlvl(zTrainCipher[0]);\n    \n    Cipher* ctemp= new Cipher[LRparams.dim1];\n    \n    NTL_EXEC_RANGE(LRparams.dim1, first, last);\n    for (long i = first; i < last; i++){\n        ctemp[i] = scheme.modEmbed(zTrainCipher[i], zlvl - tlvl);\n        scheme.multAndEqual(ctemp[i], thetaCipher[i]);\n    }\n    NTL_EXEC_RANGE_END;\n    \n    Cipher ztheta = ctemp[0];\n    for (long i = 1; i < LRparams.dim1; i++){\n        scheme.addAndEqual(ztheta, ctemp[i]);\n    }\n     \n    scheme.modSwitchAndEqual(ztheta, LRparams.logp);  // ztheta.lvl : tlvl - logp\n\n    \n    \n    //-----------------------------------------------------------------------------------------\n    // ctemp  =  alpha * (ztheta) * (a7*ztheta^6 + a5*ztheta^4 +a3*ztheta^2 + a1) * z[i] for 0<=i<=dim\n    //        =  ((alpha*a7*z[i]) * (ztheta)) * (ztheta^6 + a5/a7*ztheta^4 +a3/a7*ztheta^2 + a1/a7)\n    //-----------------------------------------------------------------------------------------\n   \n\n    // zSquare = p * (theat*z[k]/8)^2  with  tlvl - 2*logp\n    Cipher zSquare= scheme.square(ztheta);\n    scheme.modSwitchAndEqual(zSquare, LRparams.logp);\n\n    // zQuartic = p * (theat*z[k]/8)^4 with  tlvl - 3*logp\n    Cipher zQuartic = scheme.square(zSquare);\n    scheme.modSwitchAndEqual(zQuartic, LRparams.logp);\n\n    // zQuartic = p * (a7*ztheta^4 + a5*ztheta^2 + a3)  with  tlvl - 3*logp\n    Cipher ctemp1= scheme.multByConst(zSquare, LRparams.evalcoeff[5]);\n    scheme.modSwitchAndEqual(ctemp1, LRparams.logp);     // lvl(theta)+3\n    scheme.addConstAndEqual(ctemp1, LRparams.evalcoeff[3]);\n    \n    scheme.multByConst(zQuartic, LRparams.evalcoeff[7]);\n    scheme.addAndEqual(zQuartic, ctemp1);\n   \n\n    Cipher* res= new Cipher[LRparams.dim1];\n    \n    NTL_EXEC_RANGE(LRparams.dim1, first, last);\n    for (long i = first; i < last; ++i){\n        res[i] = scheme.modEmbed(zTrainCipher[i], zlvl - tlvl + LRparams.logp);\n        scheme.multAndEqual(res[i], ztheta);      \n        scheme.modSwitchAndEqual(res[i], LRparams.logp);       // res: tlvl - logp\n    \n        ctemp[i]= scheme.multByConst(res[i], LRparams.evalcoeff[1]);\n        scheme.modSwitchAndEqual(ctemp[i], LRparams.logp);     // res: tlvl - 2*logp\n    \n        scheme.multAndEqual(res[i], zSquare);     \n        scheme.modSwitchAndEqual(res[i], LRparams.logp);      // res: tlvl - 3 *logp\n        \n\n        scheme.multAndEqual(res[i], zQuartic);     \n        scheme.modSwitchAndEqual(res[i], LRparams.logp);\n        scheme.multByConst(res[i], LRparams.evalcoeff[7]);    // res: tlvl - 4 *logp\n\n        scheme.addAndEqual(res[i], ctemp[i]);\n    }\n    NTL_EXEC_RANGE_END;\n    \n     \n    //! rot and sum\n   \n    NTL_EXEC_RANGE(LRparams.dim1, first, last);\n    for (long i = first; i < last; ++i){\n        for(long j= 0; j< LRparams.logn; ++j){\n            long l = (1<<j);\n            ctemp[i] = scheme.leftRotate(res[i], l);\n            scheme.addAndEqual(res[i], ctemp[i]);\n        }\n        scheme.modSwitchAndEqual(res[i], LRparams.logn - LRparams.log2polyscale);\n    }\n    NTL_EXEC_RANGE_END;\n\n    delete[] ctemp;\n    return res;\n}\n\n\n\n//-----------------------------------------------------------------------------------------\n// res[i]  =  1/n * sum_k (ztheta) * (a3*ztheta^3 + a1*ztheta) * z[i]/8 for 0<=i<=dim\n//         =  1/n * sum_k ((z[i]/8) * (ztheta)) * (ztheta^2 + a1/a3) * a3)\n//-----------------------------------------------------------------------------------------\n\nCipher* LogReg::getgrad_deg3(Cipher*& thetaCipher, Cipher*& zTrainCipher){\n    \n    double tlvl =  getctlvl(thetaCipher[0]);\n    double zlvl =  getctlvl(zTrainCipher[0]);\n    \n    Cipher* ctemp= new Cipher[LRparams.dim1];\n    \n    NTL_EXEC_RANGE(LRparams.dim1, first, last);\n    for (long i = first; i < last; i++){\n        ctemp[i] = scheme.modEmbed(zTrainCipher[i], zlvl - tlvl);\n        scheme.multAndEqual(ctemp[i], thetaCipher[i]);\n    }\n    NTL_EXEC_RANGE_END;\n    \n    Cipher ztheta = ctemp[0];\n    for (long i = 1; i < LRparams.dim1; i++){\n        scheme.addAndEqual(ztheta, ctemp[i]);\n    }\n    \n    scheme.modSwitchAndEqual(ztheta, LRparams.logp);  // ztheta.lvl : tlvl - logp\n\n \n    //---------------------------------------------------\n    //! zSquare= p * (theat*z[k]/8)^2 + p (a1/a3) with  tlvl - 2*logp\n    Cipher zSquare= scheme.square(ztheta);\n    scheme.modSwitchAndEqual(zSquare, LRparams.logp);\n    scheme.addConstAndEqual(zSquare, LRparams.evalcoeff[1]);\n    \n \n\n    //! res[i]= ((z[i]/8) * a3 ) * (ztheta)) * (ztheta^2 + a1/a3))\n    Cipher* res= new Cipher[LRparams.dim1];\n    \n    NTL_EXEC_RANGE(LRparams.dim1, first, last);\n    for (long i = first; i < last; ++i){\n        res[i]= scheme.multByConst(zTrainCipher[i], LRparams.evalcoeff[3]);\n        scheme.modSwitchAndEqual(res[i], LRparams.logp);  // ((z[i]/8) * a3 ) with zlvl - logp\n        \n        scheme.modEmbedAndEqual(res[i], zlvl - tlvl);\n        scheme.multAndEqual(res[i], ztheta);\n        scheme.modSwitchAndEqual(res[i], LRparams.logp);  // ((z[i]/8) * a3 ) * (ztheta)) with zlvl - 2*logp\n        \n        scheme.multAndEqual(res[i], zSquare);\n        scheme.modSwitchAndEqual(res[i], LRparams.logp);  // with zlvl - 3*logp\n    }\n    NTL_EXEC_RANGE_END;\n  \n    \n    \n    //! (sum res[i]) / (n/polyscale)\n\n    NTL_EXEC_RANGE(LRparams.dim1, first, last);\n    for (long i = first; i < last; ++i){\n        for(long j= 0; j< LRparams.logn; ++j){\n            long l = (1<<j);\n            ctemp[i] = scheme.leftRotate(res[i], l);\n            scheme.addAndEqual(res[i], ctemp[i]);\n        }\n       \n        scheme.modSwitchAndEqual(res[i], LRparams.logn - LRparams.log2polyscale);\n    }\n    NTL_EXEC_RANGE_END;\n    \n    delete[] ctemp;\n    return res;\n}\n\n\n", "meta": {"hexsha": "fa3609dbffffa71a74e3fbeb1dcab8ccff0e1d46", "size": 13234, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/HELR.cpp", "max_stars_repo_name": "YiJingGuo/HEBenchmark", "max_stars_repo_head_hexsha": "3154b4b638b32c97d307c598a2dd2fbf0a543de2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2019-07-27T10:32:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-17T12:32:30.000Z", "max_issues_repo_path": "src/HELR.cpp", "max_issues_repo_name": "YiJingGuo/HEBenchmark", "max_issues_repo_head_hexsha": "3154b4b638b32c97d307c598a2dd2fbf0a543de2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/HELR.cpp", "max_forks_repo_name": "YiJingGuo/HEBenchmark", "max_forks_repo_head_hexsha": "3154b4b638b32c97d307c598a2dd2fbf0a543de2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2019-07-28T03:57:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-27T09:24:52.000Z", "avg_line_length": 32.199513382, "max_line_length": 122, "alphanum_fraction": 0.5185884842, "num_tokens": 3730, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.839733955639775, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.4720786968565588}}
{"text": "#define BOOST_TEST_MODULE \"test_gocontact_potential\"\n\n#ifdef BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n#else\n#include <boost/test/included/unit_test.hpp>\n#endif\n\n#include <test/util/check_potential.hpp>\n#include <mjolnir/forcefield/local/GoContactPotential.hpp>\n\nBOOST_AUTO_TEST_CASE(GoContact_double)\n{\n    using real_type = double;\n    constexpr std::size_t N = 1000;\n    constexpr real_type   h = 1e-6;\n    constexpr real_type tol = 1e-6;\n\n    const real_type e  = 1.0;\n    const real_type r0 = 5.0;\n\n    mjolnir::GoContactPotential<real_type> potential(e, r0);\n\n    const real_type x_min = 0.8 * r0;\n    const real_type x_max = 5.0 * r0;\n\n    mjolnir::test::check_potential(potential, x_min, x_max, tol, h, N);\n}\n\nBOOST_AUTO_TEST_CASE(GoContact_float)\n{\n    using real_type = double;\n    constexpr std::size_t N = 100;\n    constexpr real_type   h = 1e-3;\n    constexpr real_type tol = 1e-3;\n\n    const real_type e  = 1.0;\n    const real_type r0 = 5.0;\n\n    mjolnir::GoContactPotential<real_type> potential(e, r0);\n\n    const real_type x_min = 0.8 * r0;\n    const real_type x_max = 5.0 * r0;\n\n    mjolnir::test::check_potential(potential, x_min, x_max, tol, h, N);\n}\n", "meta": {"hexsha": "c27ba5763cc657626a5ead2ba30788502b4d0d59", "size": 1184, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/core/test_go_contact_potential.cpp", "max_stars_repo_name": "ToruNiina/Mjolnir", "max_stars_repo_head_hexsha": "44435dd3afc12f5c8ea27a66d7ab282df3e588ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2017-02-01T08:28:38.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-25T15:47:51.000Z", "max_issues_repo_path": "test/core/test_go_contact_potential.cpp", "max_issues_repo_name": "Mjolnir-MD/Mjolnir", "max_issues_repo_head_hexsha": "043df4080720837042c6b67a5495ecae198bc2b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 60.0, "max_issues_repo_issues_event_min_datetime": "2019-01-14T08:11:33.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-29T08:26:36.000Z", "max_forks_repo_path": "test/core/test_go_contact_potential.cpp", "max_forks_repo_name": "Mjolnir-MD/Mjolnir", "max_forks_repo_head_hexsha": "043df4080720837042c6b67a5495ecae198bc2b3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2019-01-13T11:03:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-01T11:38:00.000Z", "avg_line_length": 25.1914893617, "max_line_length": 71, "alphanum_fraction": 0.7001689189, "num_tokens": 374, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435083355188, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4718912072004501}}
{"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 __MODULES_NUMERIC_AD_CD_ADCT_HPP__\n#define __MODULES_NUMERIC_AD_CD_ADCT_HPP__\n\n#include <Eigen/Core>\n#include <boost/type_traits/is_floating_point.hpp>\n#include <boost/utility/enable_if.hpp>\n\n#ifdef USE_TOON\n#include <TooN/TooN.h>\n#include <libv/lma/lm/container/tag.hpp>\n#endif\n#include <libv/lma/ttt/traits/naming.hpp>\n\nnamespace adct\n{\n  template<class T> struct Expr\n  {\n    T const& cast() const {return static_cast<T const &>(*this); }\n  };\n\n  template<class T, int N, class Default=void> class Ad : public Expr<Ad<T,N,Default>>\n  {\n    public:\n      typedef Eigen::Matrix<T, N, 1/*, Eigen::DontAlign*/> Array;\n      Ad(const T& val = T()):value_(val),infinite_(Array::Zero()) {}\n      Ad(const T& val , int i):value_(val),infinite_(Array::Zero()) { infinite_[i] = 1; }\n      template<class X> Ad(const Expr<X>& expr):value_(expr.cast().value()),infinite_(expr.cast().infinite()) {}\n      \n      const T&     value()    const { return value_; }\n      const Array& infinite() const { return infinite_; }\n\n    private:\n      T     value_;\n      Array infinite_;\n  };\n\n\n#ifdef USE_TOON\n  template<class T, int N> class Ad<T,N,lma::Toon> : public Expr<Ad<T,N,lma::Toon>>\n  {\n    public:\n      typedef TooN::Vector<N,T> Array;\n      Ad(const T& val = T()):value_(val),infinite_(TooN::Zeros) {}\n      Ad(const T& val , int i):value_(val),infinite_(TooN::Zeros) { infinite_[i] = 1; }\n      template<class X> Ad(const Expr<X>& expr):value_(expr.cast().value()),infinite_(expr.cast().infinite()) {}\n      \n      const T&     value()    const { return value_; }\n      const Array& infinite() const { return infinite_; }\n\n    private:\n      T     value_;\n      Array infinite_;\n  };\n#endif\n\n\n  template<class T, class = void> struct Traits { typedef const T& type; };\n\n  template<class A, class Op> struct Unary : Expr<Unary<A,Op>>\n  {\n    typename Traits<A>::type a;\n    Unary(const A& a_):a(a_){}\n    auto value()    const { return Op::value(a); }\n    auto infinite() const { return Op::infinite(a); }\n  };\n  \n  template<class A, class B, class Op> struct Binary : Expr<Binary<A,B,Op>>\n  {\n    typename Traits<A>::type a;\n    typename Traits<B>::type b;\n    Binary(const A& a_, const B& b_):a(a_),b(b_){}\n    auto value()    const { return Op::value(a,b); }\n    auto infinite() const { return Op::infinite(a,b); }\n  };\n\n  template<class T> struct Traits<T, typename boost::enable_if< boost::is_floating_point<T> >::type > { typedef T type; };\n  template<class A, class B, class Op>  struct Traits<Binary<A,B,Op>> { typedef Binary<A,B,Op> type; };\n  template<class A, class Op>           struct Traits<Unary<A,Op>>    { typedef Unary<A,Op> type; };\n  \n  struct Minus\n  {\n    template<class A> static auto value   (const A& a) { return - a.value();}\n    template<class A> static auto infinite(const A& a) { return - a.infinite();}\n  };\n  \n  struct Sqrt\n  {\n    template<class A> static auto value   (const A& a) { return sqrt(a.value()); }\n    template<class A> static auto infinite(const A& a) { return a.infinite() / (2.0 * sqrt(a.value())); }\n  };\n  \n  struct Cos\n  {\n    template<class A> static auto value   (const A& a) { return cos(a.value()); }\n    template<class A> static auto infinite(const A& a) { return - sin(a.value()) * a.infinite(); }\n  };\n  \n  struct Sin\n  {\n    template<class A> static auto value   (const A& a) { return sin(a.value()); }\n    template<class A> static auto infinite(const A& a) { return cos(a.value()) * a.infinite(); }\n  };\n  \n  struct Addition\n  {\n    template<class A, class B> static auto value   (const A& a, const B& b) { return a.value() + b.value() ;}\n    template<class A, class B> static auto infinite(const A& a, const B& b) { return a.infinite() + b.infinite() ;}\n  };\n  \n  struct Substract\n  {\n    template<class A, class B> static auto value   (const A& a, const B& b) { return a.value() - b.value() ;}\n    template<class A, class B> static auto infinite(const A& a, const B& b) { return a.infinite() - b.infinite() ;}\n  };\n\n  struct Multiply\n  {\n    template<class A, class B> static auto value   (const A& a, const B& b) { return a.value() * b.value() ;}\n    template<class A, class B> static auto infinite(const A& a, const B& b) { return a.value() * b.infinite() + a.infinite() * b.value(); }\n  };\n  \n  struct AdditionScalar\n  {\n    template<class A> static auto value   (const A& a, double b) { return a.value() + b ;}\n    template<class A> static auto infinite(const A& a, double  ) { return a.infinite() ;}\n  };\n  \n  struct SubstractScalar\n  {\n    template<class A> static auto value   (const A& a, double b) { return a.value() - b ;}\n    template<class A> static auto infinite(const A& a, double  ) { return a.infinite() ;}\n  };\n  \n  struct ScalarSubstract\n  {\n    template<class A> static auto value   (double b, const A& a) { return b - a.value() ;}\n    template<class A> static auto infinite(double  , const A& a) { return -a.infinite() ;}\n  };\n  \n  struct MultiplyScalar\n  {\n    template<class A> static auto value   (const A& a, double b) { return a.value() * b ;}\n    template<class A> static auto infinite(const A& a, double b) { return a.infinite() * b;}\n  };\n  \n  struct DivideScalar\n  {\n    template<class A> static auto value   (const A& a, double b) { return a.value() / b ;}\n    template<class A> static auto infinite(const A& a, double b) { return a.infinite() / b;}\n  };\n  \n  struct ScalarDivide\n  {\n    static auto sqr(double t) { return t * t; }\n    template<class B> static auto value   (double a, const B& b) { return a / b.value() ;}\n    template<class B> static auto infinite(double a, const B& b) { return - b.infinite() * a / sqr(b.value()); }\n  };\n\n  struct Divide\n  {\n    template<class A, class B> static auto value(const A& a, const B& b) { return a.value() / b.value() ; }\n    template<class A, class B> static auto infinite(const A& a, const B& b)\n    {\n      const double val_inv = 1.0 / b.value();\n      return (a.infinite() - a.value() * val_inv * b.infinite()) * val_inv;\n    }\n  };\n\n  template<class A, class B> auto operator+(const Expr<A>& a, const Expr<B>& b) { return Binary<A,B,Addition>(a.cast(),b.cast()); }\n  template<class A, class B> auto operator-(const Expr<A>& a, const Expr<B>& b) { return Binary<A,B,Substract>(a.cast(),b.cast()); }\n  template<class A, class B> auto operator*(const Expr<A>& a, const Expr<B>& b) { return Binary<A,B,Multiply>(a.cast(),b.cast()); }\n  template<class A, class B> auto operator/(const Expr<A>& a, const Expr<B>& b) { return Binary<A,B,Divide>(a.cast(),b.cast()); }\n\n  template<class A>          auto operator+(const Expr<A>& a, double b)         { return Binary<A,double,AdditionScalar>(a.cast(),b); }\n  template<class A>          auto operator+(double b, const Expr<A>& a)         { return a+b; }\n  template<class A>          auto operator-(const Expr<A>& a, double b)         { return Binary<A,double,SubstractScalar>(a.cast(),b); }\n  template<class A>          auto operator-(double b, const Expr<A>& a)         { return Binary<double,A,ScalarSubstract>(b,a.cast()); }\n\n  template<class A>          auto operator*(const Expr<A>& a, double b)         { return Binary<A,double,MultiplyScalar>(a.cast(),b); }\n  template<class A>          auto operator*(double b, const Expr<A>& a)         { return a*b; }\n  template<class A>          auto operator/(const Expr<A>& a, double b)         { return Binary<A,double,DivideScalar>(a.cast(),b); }\n  template<class B>          auto operator/(double a, const Expr<B>& b)         { return Binary<double,B,ScalarDivide>(a,b.cast()); }\n  \n  template<class A>          auto operator-(const Expr<A>& a)                   { return Unary<A,Minus>(a.cast()); }\n  template<class A>          auto sqrt     (const Expr<A>& a)                   { return Unary<A,Sqrt>(a.cast()); }\n  template<class A>          auto cos      (const Expr<A>& a)                   { return Unary<A,Cos>(a.cast()); }\n  template<class A>          auto sin      (const Expr<A>& a)                   { return Unary<A,Sin>(a.cast()); }\n  \n  template<class A, class B> bool operator>(const Expr<A>& a, const Expr<B>& b) { return a.cast().value() > b.cast().value() ; }\n  template<class A, class B> bool operator<(const Expr<A>& a, const Expr<B>& b) { return a.cast().value() < b.cast().value() ; }\n}\n\n#include <libv/lma/ttt/traits/naming.hpp>\n#include <libv/lma/string/string_utiliy.hpp>\n\nnamespace ttt\n{\n  template<class T, int N> struct Name<adct::Ad<T,N>>\n  {\n    static std::string name(){ return std::string(\"Ad<\") + ttt::name<T>() + \",\" + lma::to_string(N) + \">\"; }\n  };\n  \n}\n\n#endif\n", "meta": {"hexsha": "2dbad31d2de2aea17c1aa708309515488c7192a4", "size": 9006, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/libv/lma/numeric/ad/ct/adct.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/numeric/ad/ct/adct.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/numeric/ad/ct/adct.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.9363636364, "max_line_length": 139, "alphanum_fraction": 0.5986009327, "num_tokens": 2492, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435083355187, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.47189120720045}}
{"text": "/**\n * @file serialization_test.cpp\n * @author Ryan Curtin\n *\n * Test serialization of mlpack objects.\n */\n#include <mlpack/core.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"old_boost_test_definitions.hpp\"\n#include \"serialization.hpp\"\n\n#include <mlpack/core/dists/regression_distribution.hpp>\n#include <mlpack/core/tree/ballbound.hpp>\n#include <mlpack/core/tree/hrectbound.hpp>\n#include <mlpack/core/metrics/mahalanobis_distance.hpp>\n#include <mlpack/core/tree/binary_space_tree.hpp>\n#include <mlpack/methods/hoeffding_trees/hoeffding_tree.hpp>\n#include <mlpack/core/tree/cover_tree.hpp>\n#include <mlpack/core/tree/rectangle_tree.hpp>\n\n#include <mlpack/methods/perceptron/perceptron.hpp>\n#include <mlpack/methods/logistic_regression/logistic_regression.hpp>\n#include <mlpack/methods/neighbor_search/neighbor_search.hpp>\n#include <mlpack/methods/softmax_regression/softmax_regression.hpp>\n#include <mlpack/methods/det/dtree.hpp>\n#include <mlpack/methods/naive_bayes/naive_bayes_classifier.hpp>\n#include <mlpack/methods/rann/ra_search.hpp>\n#include <mlpack/methods/lsh/lsh_search.hpp>\n#include <mlpack/methods/decision_stump/decision_stump.hpp>\n#include <mlpack/methods/lars/lars.hpp>\n\nusing namespace mlpack;\nusing namespace mlpack::distribution;\nusing namespace mlpack::regression;\nusing namespace mlpack::bound;\nusing namespace mlpack::metric;\nusing namespace mlpack::tree;\nusing namespace mlpack::perceptron;\nusing namespace mlpack::regression;\nusing namespace mlpack::naive_bayes;\nusing namespace mlpack::neighbor;\nusing namespace mlpack::decision_stump;\n\nusing namespace arma;\nusing namespace boost;\nusing namespace boost::archive;\nusing namespace boost::serialization;\nusing namespace std;\n\nBOOST_AUTO_TEST_SUITE(SerializationTest);\n\n/**\n * Serialize a random cube.\n */\nBOOST_AUTO_TEST_CASE(CubeSerializeTest)\n{\n  arma::cube m;\n  m.randu(2, 50, 50);\n  TestAllArmadilloSerialization(m);\n}\n\n/**\n * Serialize an empty cube.\n */\nBOOST_AUTO_TEST_CASE(EmptyCubeSerializeTest)\n{\n  arma::cube c;\n  TestAllArmadilloSerialization(c);\n}\n\n\n/**\n * Can we load and save an Armadillo matrix?\n */\nBOOST_AUTO_TEST_CASE(MatrixSerializeXMLTest)\n{\n  arma::mat m;\n  m.randu(50, 50);\n  TestAllArmadilloSerialization(m);\n}\n\n/**\n * How about columns?\n */\nBOOST_AUTO_TEST_CASE(ColSerializeTest)\n{\n  arma::vec m;\n  m.randu(50, 1);\n  TestAllArmadilloSerialization(m);\n}\n\n/**\n * How about rows?\n */\nBOOST_AUTO_TEST_CASE(RowSerializeTest)\n{\n  arma::rowvec m;\n  m.randu(1, 50);\n  TestAllArmadilloSerialization(m);\n}\n\n// A quick test with an empty matrix.\nBOOST_AUTO_TEST_CASE(EmptyMatrixSerializeTest)\n{\n  arma::mat m;\n  TestAllArmadilloSerialization(m);\n}\n\n/**\n * Can we load and save a sparse Armadillo matrix?\n */\nBOOST_AUTO_TEST_CASE(SparseMatrixSerializeTest)\n{\n  arma::sp_mat m;\n  m.sprandu(50, 50, 0.3);\n  TestAllArmadilloSerialization(m);\n}\n\n/**\n * How about columns?\n */\nBOOST_AUTO_TEST_CASE(SparseColSerializeTest)\n{\n  arma::sp_vec m;\n  m.sprandu(50, 1, 0.3);\n  TestAllArmadilloSerialization(m);\n}\n\n/**\n * How about rows?\n */\nBOOST_AUTO_TEST_CASE(SparseRowSerializeTest)\n{\n  arma::sp_rowvec m;\n  m.sprandu(1, 50, 0.3);\n  TestAllArmadilloSerialization(m);\n}\n\n// A quick test with an empty matrix.\nBOOST_AUTO_TEST_CASE(EmptySparseMatrixSerializeTest)\n{\n  arma::sp_mat m;\n  TestAllArmadilloSerialization(m);\n}\n\n// Now, test mlpack objects.\nBOOST_AUTO_TEST_CASE(DiscreteDistributionTest)\n{\n  // I assume that I am properly saving vectors, so, this should be\n  // straightforward.\n  vec prob;\n  prob.randu(12);\n  DiscreteDistribution t(prob);\n\n  DiscreteDistribution xmlT, textT, binaryT;\n\n  // Load and save with all serializers.\n  SerializeObjectAll(t, xmlT, textT, binaryT);\n\n  for (size_t i = 0; i < 12; ++i)\n  {\n    vec obs(1);\n    obs[0] = i;\n    const double prob = t.Probability(obs);\n    if (prob == 0.0)\n    {\n      BOOST_REQUIRE_SMALL(xmlT.Probability(obs), 1e-8);\n      BOOST_REQUIRE_SMALL(textT.Probability(obs), 1e-8);\n      BOOST_REQUIRE_SMALL(binaryT.Probability(obs), 1e-8);\n    }\n    else\n    {\n      BOOST_REQUIRE_CLOSE(prob, xmlT.Probability(obs), 1e-8);\n      BOOST_REQUIRE_CLOSE(prob, textT.Probability(obs), 1e-8);\n      BOOST_REQUIRE_CLOSE(prob, binaryT.Probability(obs), 1e-8);\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE(GaussianDistributionTest)\n{\n  vec mean(10);\n  mean.randu();\n  // Generate a covariance matrix.\n  mat cov;\n  cov.randu(10, 10);\n  cov = (cov * cov.t());\n\n  GaussianDistribution g(mean, cov);\n  GaussianDistribution xmlG, textG, binaryG;\n\n  SerializeObjectAll(g, xmlG, textG, binaryG);\n\n  BOOST_REQUIRE_EQUAL(g.Dimensionality(), xmlG.Dimensionality());\n  BOOST_REQUIRE_EQUAL(g.Dimensionality(), textG.Dimensionality());\n  BOOST_REQUIRE_EQUAL(g.Dimensionality(), binaryG.Dimensionality());\n\n  // First, check the means.\n  CheckMatrices(g.Mean(), xmlG.Mean(), textG.Mean(), binaryG.Mean());\n\n  // Now, check the covariance.\n  CheckMatrices(g.Covariance(), xmlG.Covariance(), textG.Covariance(),\n      binaryG.Covariance());\n\n  // Lastly, run some observations through and make sure the probability is the\n  // same.  This should test anything cached internally.\n  arma::mat randomObs;\n  randomObs.randu(10, 500);\n\n  for (size_t i = 0; i < 500; ++i)\n  {\n    const double prob = g.Probability(randomObs.unsafe_col(i));\n\n    if (prob == 0.0)\n    {\n      BOOST_REQUIRE_SMALL(xmlG.Probability(randomObs.unsafe_col(i)), 1e-8);\n      BOOST_REQUIRE_SMALL(textG.Probability(randomObs.unsafe_col(i)), 1e-8);\n      BOOST_REQUIRE_SMALL(binaryG.Probability(randomObs.unsafe_col(i)), 1e-8);\n    }\n    else\n    {\n      BOOST_REQUIRE_CLOSE(prob, xmlG.Probability(randomObs.unsafe_col(i)),\n          1e-8);\n      BOOST_REQUIRE_CLOSE(prob, textG.Probability(randomObs.unsafe_col(i)),\n          1e-8);\n      BOOST_REQUIRE_CLOSE(prob, binaryG.Probability(randomObs.unsafe_col(i)),\n          1e-8);\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE(LaplaceDistributionTest)\n{\n  vec mean(20);\n  mean.randu();\n\n  LaplaceDistribution l(mean, 2.5);\n  LaplaceDistribution xmlL, textL, binaryL;\n\n  SerializeObjectAll(l, xmlL, textL, binaryL);\n\n  BOOST_REQUIRE_CLOSE(l.Scale(), xmlL.Scale(), 1e-8);\n  BOOST_REQUIRE_CLOSE(l.Scale(), textL.Scale(), 1e-8);\n  BOOST_REQUIRE_CLOSE(l.Scale(), binaryL.Scale(), 1e-8);\n\n  CheckMatrices(l.Mean(), xmlL.Mean(), textL.Mean(), binaryL.Mean());\n}\n\nBOOST_AUTO_TEST_CASE(MahalanobisDistanceTest)\n{\n  MahalanobisDistance<> d;\n  d.Covariance().randu(50, 50);\n\n  MahalanobisDistance<> xmlD, textD, binaryD;\n\n  SerializeObjectAll(d, xmlD, textD, binaryD);\n\n  // Check the covariance matrices.\n  CheckMatrices(d.Covariance(),\n                xmlD.Covariance(),\n                textD.Covariance(),\n                binaryD.Covariance());\n}\n\nBOOST_AUTO_TEST_CASE(LinearRegressionTest)\n{\n  // Generate some random data.\n  mat data;\n  data.randn(15, 800);\n  vec responses;\n  responses.randn(800, 1);\n\n  LinearRegression lr(data, responses, 0.05); // Train the model.\n  LinearRegression xmlLr, textLr, binaryLr;\n\n  SerializeObjectAll(lr, xmlLr, textLr, binaryLr);\n\n  BOOST_REQUIRE_CLOSE(lr.Lambda(), xmlLr.Lambda(), 1e-8);\n  BOOST_REQUIRE_CLOSE(lr.Lambda(), textLr.Lambda(), 1e-8);\n  BOOST_REQUIRE_CLOSE(lr.Lambda(), binaryLr.Lambda(), 1e-8);\n\n  CheckMatrices(lr.Parameters(), xmlLr.Parameters(), textLr.Parameters(),\n      binaryLr.Parameters());\n}\n\nBOOST_AUTO_TEST_CASE(RegressionDistributionTest)\n{\n  // Generate some random data.\n  mat data;\n  data.randn(15, 800);\n  vec responses;\n  responses.randn(800, 1);\n\n  RegressionDistribution rd(data, responses);\n  RegressionDistribution xmlRd, textRd, binaryRd;\n\n  // Okay, now save it and load it.\n  SerializeObjectAll(rd, xmlRd, textRd, binaryRd);\n\n  // Check the gaussian distribution.\n  CheckMatrices(rd.Err().Mean(),\n                xmlRd.Err().Mean(),\n                textRd.Err().Mean(),\n                binaryRd.Err().Mean());\n  CheckMatrices(rd.Err().Covariance(),\n                xmlRd.Err().Covariance(),\n                textRd.Err().Covariance(),\n                binaryRd.Err().Covariance());\n\n  // Check the regression function.\n  if (rd.Rf().Lambda() == 0.0)\n  {\n    BOOST_REQUIRE_SMALL(xmlRd.Rf().Lambda(), 1e-8);\n    BOOST_REQUIRE_SMALL(textRd.Rf().Lambda(), 1e-8);\n    BOOST_REQUIRE_SMALL(binaryRd.Rf().Lambda(), 1e-8);\n  }\n  else\n  {\n    BOOST_REQUIRE_CLOSE(rd.Rf().Lambda(), xmlRd.Rf().Lambda(), 1e-8);\n    BOOST_REQUIRE_CLOSE(rd.Rf().Lambda(), textRd.Rf().Lambda(), 1e-8);\n    BOOST_REQUIRE_CLOSE(rd.Rf().Lambda(), binaryRd.Rf().Lambda(), 1e-8);\n  }\n\n  CheckMatrices(rd.Rf().Parameters(),\n                xmlRd.Rf().Parameters(),\n                textRd.Rf().Parameters(),\n                binaryRd.Rf().Parameters());\n}\n\nBOOST_AUTO_TEST_CASE(BallBoundTest)\n{\n  BallBound<> b(100);\n  b.Center().randu();\n  b.Radius() = 14.0;\n\n  BallBound<> xmlB, textB, binaryB;\n\n  SerializeObjectAll(b, xmlB, textB, binaryB);\n\n  // Check the dimensionality.\n  BOOST_REQUIRE_EQUAL(b.Dim(), xmlB.Dim());\n  BOOST_REQUIRE_EQUAL(b.Dim(), textB.Dim());\n  BOOST_REQUIRE_EQUAL(b.Dim(), binaryB.Dim());\n\n  // Check the radius.\n  BOOST_REQUIRE_CLOSE(b.Radius(), xmlB.Radius(), 1e-8);\n  BOOST_REQUIRE_CLOSE(b.Radius(), textB.Radius(), 1e-8);\n  BOOST_REQUIRE_CLOSE(b.Radius(), binaryB.Radius(), 1e-8);\n\n  // Now check the vectors.\n  CheckMatrices(b.Center(), xmlB.Center(), textB.Center(), binaryB.Center());\n}\n\nBOOST_AUTO_TEST_CASE(MahalanobisBallBoundTest)\n{\n  BallBound<arma::vec, MahalanobisDistance<>> b(100);\n  b.Center().randu();\n  b.Radius() = 14.0;\n  b.Metric().Covariance().randu(100, 100);\n\n  BallBound<arma::vec, MahalanobisDistance<>> xmlB, textB, binaryB;\n\n  SerializeObjectAll(b, xmlB, textB, binaryB);\n\n  // Check the radius.\n  BOOST_REQUIRE_CLOSE(b.Radius(), xmlB.Radius(), 1e-8);\n  BOOST_REQUIRE_CLOSE(b.Radius(), textB.Radius(), 1e-8);\n  BOOST_REQUIRE_CLOSE(b.Radius(), binaryB.Radius(), 1e-8);\n\n  // Check the vectors.\n  CheckMatrices(b.Center(), xmlB.Center(), textB.Center(), binaryB.Center());\n  CheckMatrices(b.Metric().Covariance(),\n                xmlB.Metric().Covariance(),\n                textB.Metric().Covariance(),\n                binaryB.Metric().Covariance());\n}\n\nBOOST_AUTO_TEST_CASE(HRectBoundTest)\n{\n  HRectBound<> b(2);\n\n  arma::mat points(\"0.0, 1.1; 5.0, 2.2\");\n  points = points.t();\n  b |= points; // [0.0, 5.0]; [1.1, 2.2];\n\n  HRectBound<> xmlB, textB, binaryB;\n\n  SerializeObjectAll(b, xmlB, textB, binaryB);\n\n  // Check the dimensionality.\n  BOOST_REQUIRE_EQUAL(b.Dim(), xmlB.Dim());\n  BOOST_REQUIRE_EQUAL(b.Dim(), textB.Dim());\n  BOOST_REQUIRE_EQUAL(b.Dim(), binaryB.Dim());\n\n  // Check the bounds.\n  for (size_t i = 0; i < b.Dim(); ++i)\n  {\n    BOOST_REQUIRE_CLOSE(b[i].Lo(), xmlB[i].Lo(), 1e-8);\n    BOOST_REQUIRE_CLOSE(b[i].Hi(), xmlB[i].Hi(), 1e-8);\n    BOOST_REQUIRE_CLOSE(b[i].Lo(), textB[i].Lo(), 1e-8);\n    BOOST_REQUIRE_CLOSE(b[i].Hi(), textB[i].Hi(), 1e-8);\n    BOOST_REQUIRE_CLOSE(b[i].Lo(), binaryB[i].Lo(), 1e-8);\n    BOOST_REQUIRE_CLOSE(b[i].Hi(), binaryB[i].Hi(), 1e-8);\n  }\n\n  // Check the minimum width.\n  BOOST_REQUIRE_CLOSE(b.MinWidth(), xmlB.MinWidth(), 1e-8);\n  BOOST_REQUIRE_CLOSE(b.MinWidth(), textB.MinWidth(), 1e-8);\n  BOOST_REQUIRE_CLOSE(b.MinWidth(), binaryB.MinWidth(), 1e-8);\n}\n\ntemplate<typename TreeType>\nvoid CheckTrees(TreeType& tree,\n                TreeType& xmlTree,\n                TreeType& textTree,\n                TreeType& binaryTree)\n{\n  const typename TreeType::Mat* dataset = &tree.Dataset();\n\n  // Make sure that the data matrices are the same.\n  if (tree.Parent() == NULL)\n  {\n    CheckMatrices(*dataset,\n                  xmlTree.Dataset(),\n                  textTree.Dataset(),\n                  binaryTree.Dataset());\n\n    // Also ensure that the other parents are null too.\n    BOOST_REQUIRE_EQUAL(xmlTree.Parent(), (TreeType*) NULL);\n    BOOST_REQUIRE_EQUAL(textTree.Parent(), (TreeType*) NULL);\n    BOOST_REQUIRE_EQUAL(binaryTree.Parent(), (TreeType*) NULL);\n  }\n\n  // Make sure the number of children is the same.\n  BOOST_REQUIRE_EQUAL(tree.NumChildren(), xmlTree.NumChildren());\n  BOOST_REQUIRE_EQUAL(tree.NumChildren(), textTree.NumChildren());\n  BOOST_REQUIRE_EQUAL(tree.NumChildren(), binaryTree.NumChildren());\n\n  // Make sure the number of descendants is the same.\n  BOOST_REQUIRE_EQUAL(tree.NumDescendants(), xmlTree.NumDescendants());\n  BOOST_REQUIRE_EQUAL(tree.NumDescendants(), textTree.NumDescendants());\n  BOOST_REQUIRE_EQUAL(tree.NumDescendants(), binaryTree.NumDescendants());\n\n  // Make sure the number of points is the same.\n  BOOST_REQUIRE_EQUAL(tree.NumPoints(), xmlTree.NumPoints());\n  BOOST_REQUIRE_EQUAL(tree.NumPoints(), textTree.NumPoints());\n  BOOST_REQUIRE_EQUAL(tree.NumPoints(), binaryTree.NumPoints());\n\n  // Check that each point is the same.\n  for (size_t i = 0; i < tree.NumPoints(); ++i)\n  {\n    BOOST_REQUIRE_EQUAL(tree.Point(i), xmlTree.Point(i));\n    BOOST_REQUIRE_EQUAL(tree.Point(i), textTree.Point(i));\n    BOOST_REQUIRE_EQUAL(tree.Point(i), binaryTree.Point(i));\n  }\n\n  // Check that the parent distance is the same.\n  BOOST_REQUIRE_CLOSE(tree.ParentDistance(), xmlTree.ParentDistance(), 1e-8);\n  BOOST_REQUIRE_CLOSE(tree.ParentDistance(), textTree.ParentDistance(), 1e-8);\n  BOOST_REQUIRE_CLOSE(tree.ParentDistance(), binaryTree.ParentDistance(), 1e-8);\n\n  // Check that the furthest descendant distance is the same.\n  BOOST_REQUIRE_CLOSE(tree.FurthestDescendantDistance(),\n      xmlTree.FurthestDescendantDistance(), 1e-8);\n  BOOST_REQUIRE_CLOSE(tree.FurthestDescendantDistance(),\n      textTree.FurthestDescendantDistance(), 1e-8);\n  BOOST_REQUIRE_CLOSE(tree.FurthestDescendantDistance(),\n      binaryTree.FurthestDescendantDistance(), 1e-8);\n\n  // Check that the minimum bound distance is the same.\n  BOOST_REQUIRE_CLOSE(tree.MinimumBoundDistance(),\n      xmlTree.MinimumBoundDistance(), 1e-8);\n  BOOST_REQUIRE_CLOSE(tree.MinimumBoundDistance(),\n      textTree.MinimumBoundDistance(), 1e-8);\n  BOOST_REQUIRE_CLOSE(tree.MinimumBoundDistance(),\n      binaryTree.MinimumBoundDistance(), 1e-8);\n\n  // Recurse into the children.\n  for (size_t i = 0; i < tree.NumChildren(); ++i)\n  {\n    // Check that the child dataset is the same.\n    BOOST_REQUIRE_EQUAL(&xmlTree.Dataset(), &xmlTree.Child(i).Dataset());\n    BOOST_REQUIRE_EQUAL(&textTree.Dataset(), &textTree.Child(i).Dataset());\n    BOOST_REQUIRE_EQUAL(&binaryTree.Dataset(), &binaryTree.Child(i).Dataset());\n\n    // Make sure the parent link is right.\n    BOOST_REQUIRE_EQUAL(xmlTree.Child(i).Parent(), &xmlTree);\n    BOOST_REQUIRE_EQUAL(textTree.Child(i).Parent(), &textTree);\n    BOOST_REQUIRE_EQUAL(binaryTree.Child(i).Parent(), &binaryTree);\n\n    CheckTrees(tree.Child(i), xmlTree.Child(i), textTree.Child(i),\n        binaryTree.Child(i));\n  }\n}\n\nBOOST_AUTO_TEST_CASE(BinarySpaceTreeTest)\n{\n  arma::mat data;\n  data.randu(3, 100);\n  typedef KDTree<EuclideanDistance, EmptyStatistic, arma::mat> TreeType;\n  TreeType tree(data);\n\n  TreeType* xmlTree;\n  TreeType* textTree;\n  TreeType* binaryTree;\n\n  SerializePointerObjectAll(&tree, xmlTree, textTree, binaryTree);\n\n  CheckTrees(tree, *xmlTree, *textTree, *binaryTree);\n\n  delete xmlTree;\n  delete textTree;\n  delete binaryTree;\n}\n\nBOOST_AUTO_TEST_CASE(BinarySpaceTreeOverwriteTest)\n{\n  arma::mat data;\n  data.randu(3, 100);\n  typedef KDTree<EuclideanDistance, EmptyStatistic, arma::mat> TreeType;\n  TreeType tree(data);\n\n  arma::mat otherData;\n  otherData.randu(5, 50);\n  TreeType xmlTree(otherData);\n  TreeType textTree(xmlTree);\n  TreeType binaryTree(xmlTree);\n\n  SerializeObjectAll(tree, xmlTree, textTree, binaryTree);\n\n  CheckTrees(tree, xmlTree, textTree, binaryTree);\n}\n\nBOOST_AUTO_TEST_CASE(CoverTreeTest)\n{\n  arma::mat data;\n  data.randu(3, 100);\n  typedef StandardCoverTree<EuclideanDistance, EmptyStatistic, arma::mat>\n      TreeType;\n  TreeType tree(data);\n\n  TreeType* xmlTree;\n  TreeType* textTree;\n  TreeType* binaryTree;\n\n  SerializePointerObjectAll(&tree, xmlTree, textTree, binaryTree);\n\n  CheckTrees(tree, *xmlTree, *textTree, *binaryTree);\n\n  // Also check a few other things.\n  std::stack<TreeType*> stack, xmlStack, textStack, binaryStack;\n  stack.push(&tree);\n  xmlStack.push(xmlTree);\n  textStack.push(textTree);\n  binaryStack.push(binaryTree);\n  while (!stack.empty())\n  {\n    TreeType* node = stack.top();\n    TreeType* xmlNode = xmlStack.top();\n    TreeType* textNode = textStack.top();\n    TreeType* binaryNode = binaryStack.top();\n    stack.pop();\n    xmlStack.pop();\n    textStack.pop();\n    binaryStack.pop();\n\n    BOOST_REQUIRE_EQUAL(node->Scale(), xmlNode->Scale());\n    BOOST_REQUIRE_EQUAL(node->Scale(), textNode->Scale());\n    BOOST_REQUIRE_EQUAL(node->Scale(), binaryNode->Scale());\n\n    BOOST_REQUIRE_CLOSE(node->Base(), xmlNode->Base(), 1e-5);\n    BOOST_REQUIRE_CLOSE(node->Base(), textNode->Base(), 1e-5);\n    BOOST_REQUIRE_CLOSE(node->Base(), binaryNode->Base(), 1e-5);\n\n    for (size_t i = 0; i < node->NumChildren(); ++i)\n    {\n      stack.push(&node->Child(i));\n      xmlStack.push(&xmlNode->Child(i));\n      textStack.push(&textNode->Child(i));\n      binaryStack.push(&binaryNode->Child(i));\n    }\n  }\n\n  delete xmlTree;\n  delete textTree;\n  delete binaryTree;\n}\n\nBOOST_AUTO_TEST_CASE(CoverTreeOverwriteTest)\n{\n  arma::mat data;\n  data.randu(3, 100);\n  typedef StandardCoverTree<EuclideanDistance, EmptyStatistic, arma::mat>\n      TreeType;\n  TreeType tree(data);\n\n  arma::mat otherData;\n  otherData.randu(5, 50);\n  TreeType xmlTree(otherData);\n  TreeType textTree(xmlTree);\n  TreeType binaryTree(xmlTree);\n\n  SerializeObjectAll(tree, xmlTree, textTree, binaryTree);\n\n  CheckTrees(tree, xmlTree, textTree, binaryTree);\n\n  // Also check a few other things.\n  std::stack<TreeType*> stack, xmlStack, textStack, binaryStack;\n  stack.push(&tree);\n  xmlStack.push(&xmlTree);\n  textStack.push(&textTree);\n  binaryStack.push(&binaryTree);\n  while (!stack.empty())\n  {\n    TreeType* node = stack.top();\n    TreeType* xmlNode = xmlStack.top();\n    TreeType* textNode = textStack.top();\n    TreeType* binaryNode = binaryStack.top();\n    stack.pop();\n    xmlStack.pop();\n    textStack.pop();\n    binaryStack.pop();\n\n    BOOST_REQUIRE_EQUAL(node->Scale(), xmlNode->Scale());\n    BOOST_REQUIRE_EQUAL(node->Scale(), textNode->Scale());\n    BOOST_REQUIRE_EQUAL(node->Scale(), binaryNode->Scale());\n\n    BOOST_REQUIRE_CLOSE(node->Base(), xmlNode->Base(), 1e-5);\n    BOOST_REQUIRE_CLOSE(node->Base(), textNode->Base(), 1e-5);\n    BOOST_REQUIRE_CLOSE(node->Base(), binaryNode->Base(), 1e-5);\n\n    for (size_t i = 0; i < node->NumChildren(); ++i)\n    {\n      stack.push(&node->Child(i));\n      xmlStack.push(&xmlNode->Child(i));\n      textStack.push(&textNode->Child(i));\n      binaryStack.push(&binaryNode->Child(i));\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE(RectangleTreeTest)\n{\n  arma::mat data;\n  data.randu(3, 1000);\n  typedef RTree<EuclideanDistance, EmptyStatistic, arma::mat> TreeType;\n  TreeType tree(data);\n\n  TreeType* xmlTree;\n  TreeType* textTree;\n  TreeType* binaryTree;\n\n  SerializePointerObjectAll(&tree, xmlTree, textTree, binaryTree);\n\n  CheckTrees(tree, *xmlTree, *textTree, *binaryTree);\n\n  // Check a few other things too.\n  std::stack<TreeType*> stack, xmlStack, textStack, binaryStack;\n  stack.push(&tree);\n  xmlStack.push(xmlTree);\n  textStack.push(textTree);\n  binaryStack.push(binaryTree);\n  while (!stack.empty())\n  {\n    // Check more things...\n    TreeType* node = stack.top();\n    TreeType* xmlNode = xmlStack.top();\n    TreeType* textNode = textStack.top();\n    TreeType* binaryNode = binaryStack.top();\n    stack.pop();\n    xmlStack.pop();\n    textStack.pop();\n    binaryStack.pop();\n\n    BOOST_REQUIRE_EQUAL(node->MaxLeafSize(), xmlNode->MaxLeafSize());\n    BOOST_REQUIRE_EQUAL(node->MaxLeafSize(), textNode->MaxLeafSize());\n    BOOST_REQUIRE_EQUAL(node->MaxLeafSize(), binaryNode->MaxLeafSize());\n\n    BOOST_REQUIRE_EQUAL(node->MinLeafSize(), xmlNode->MinLeafSize());\n    BOOST_REQUIRE_EQUAL(node->MinLeafSize(), textNode->MinLeafSize());\n    BOOST_REQUIRE_EQUAL(node->MinLeafSize(), binaryNode->MinLeafSize());\n\n    BOOST_REQUIRE_EQUAL(node->MaxNumChildren(), xmlNode->MaxNumChildren());\n    BOOST_REQUIRE_EQUAL(node->MaxNumChildren(), textNode->MaxNumChildren());\n    BOOST_REQUIRE_EQUAL(node->MaxNumChildren(), binaryNode->MaxNumChildren());\n\n    BOOST_REQUIRE_EQUAL(node->MinNumChildren(), xmlNode->MinNumChildren());\n    BOOST_REQUIRE_EQUAL(node->MinNumChildren(), textNode->MinNumChildren());\n    BOOST_REQUIRE_EQUAL(node->MinNumChildren(), binaryNode->MinNumChildren());\n  }\n\n  delete xmlTree;\n  delete textTree;\n  delete binaryTree;\n}\n\nBOOST_AUTO_TEST_CASE(RectangleTreeOverwriteTest)\n{\n  arma::mat data;\n  data.randu(3, 1000);\n  typedef RTree<EuclideanDistance, EmptyStatistic, arma::mat> TreeType;\n  TreeType tree(data);\n\n  arma::mat otherData;\n  otherData.randu(5, 50);\n  TreeType xmlTree(otherData);\n  TreeType textTree(otherData);\n  TreeType binaryTree(textTree);\n\n  SerializeObjectAll(tree, xmlTree, textTree, binaryTree);\n\n  CheckTrees(tree, xmlTree, textTree, binaryTree);\n\n  // Check a few other things too.\n  std::stack<TreeType*> stack, xmlStack, textStack, binaryStack;\n  stack.push(&tree);\n  xmlStack.push(&xmlTree);\n  textStack.push(&textTree);\n  binaryStack.push(&binaryTree);\n  while (!stack.empty())\n  {\n    // Check more things...\n    TreeType* node = stack.top();\n    TreeType* xmlNode = xmlStack.top();\n    TreeType* textNode = textStack.top();\n    TreeType* binaryNode = binaryStack.top();\n    stack.pop();\n    xmlStack.pop();\n    textStack.pop();\n    binaryStack.pop();\n\n    BOOST_REQUIRE_EQUAL(node->MaxLeafSize(), xmlNode->MaxLeafSize());\n    BOOST_REQUIRE_EQUAL(node->MaxLeafSize(), textNode->MaxLeafSize());\n    BOOST_REQUIRE_EQUAL(node->MaxLeafSize(), binaryNode->MaxLeafSize());\n\n    BOOST_REQUIRE_EQUAL(node->MinLeafSize(), xmlNode->MinLeafSize());\n    BOOST_REQUIRE_EQUAL(node->MinLeafSize(), textNode->MinLeafSize());\n    BOOST_REQUIRE_EQUAL(node->MinLeafSize(), binaryNode->MinLeafSize());\n\n    BOOST_REQUIRE_EQUAL(node->MaxNumChildren(), xmlNode->MaxNumChildren());\n    BOOST_REQUIRE_EQUAL(node->MaxNumChildren(), textNode->MaxNumChildren());\n    BOOST_REQUIRE_EQUAL(node->MaxNumChildren(), binaryNode->MaxNumChildren());\n\n    BOOST_REQUIRE_EQUAL(node->MinNumChildren(), xmlNode->MinNumChildren());\n    BOOST_REQUIRE_EQUAL(node->MinNumChildren(), textNode->MinNumChildren());\n    BOOST_REQUIRE_EQUAL(node->MinNumChildren(), binaryNode->MinNumChildren());\n  }\n}\n\nBOOST_AUTO_TEST_CASE(PerceptronTest)\n{\n  // Create a perceptron.  Train it randomly.  Then check that it hasn't\n  // changed.\n  arma::mat data;\n  data.randu(3, 100);\n  arma::Row<size_t> labels(100);\n  for (size_t i = 0; i < labels.n_elem; ++i)\n  {\n    if (data(1, i) > 0.5)\n      labels[i] = 0;\n    else\n      labels[i] = 1;\n  }\n\n  Perceptron<> p(data, labels, 2, 15);\n\n  Perceptron<> pXml(2, 3), pText(2, 3), pBinary(2, 3);\n  SerializeObjectAll(p, pXml, pText, pBinary);\n\n  // Now check that things are the same.\n  CheckMatrices(p.Weights(), pXml.Weights(), pText.Weights(),\n      pBinary.Weights());\n  CheckMatrices(p.Biases(), pXml.Biases(), pText.Biases(), pBinary.Biases());\n\n  BOOST_REQUIRE_EQUAL(p.MaxIterations(), pXml.MaxIterations());\n  BOOST_REQUIRE_EQUAL(p.MaxIterations(), pText.MaxIterations());\n  BOOST_REQUIRE_EQUAL(p.MaxIterations(), pBinary.MaxIterations());\n}\n\nBOOST_AUTO_TEST_CASE(LogisticRegressionTest)\n{\n  arma::mat data;\n  data.randu(3, 100);\n  arma::Row<size_t> responses;\n  responses.randu(100);\n\n  LogisticRegression<> lr(data, responses, 0.5);\n\n  LogisticRegression<> lrXml(data, responses + 3, 0.3);\n  LogisticRegression<> lrText(data, responses + 1);\n  LogisticRegression<> lrBinary(3, 0.0);\n\n  SerializeObjectAll(lr, lrXml, lrText, lrBinary);\n\n  CheckMatrices(lr.Parameters(), lrXml.Parameters(), lrText.Parameters(),\n      lrBinary.Parameters());\n\n  BOOST_REQUIRE_CLOSE(lr.Lambda(), lrXml.Lambda(), 1e-5);\n  BOOST_REQUIRE_CLOSE(lr.Lambda(), lrText.Lambda(), 1e-5);\n  BOOST_REQUIRE_CLOSE(lr.Lambda(), lrBinary.Lambda(), 1e-5);\n}\n\nBOOST_AUTO_TEST_CASE(AllkNNTest)\n{\n  using neighbor::AllkNN;\n  arma::mat dataset = arma::randu<arma::mat>(5, 2000);\n\n  AllkNN allknn(dataset, false, false);\n\n  AllkNN knnXml, knnText, knnBinary;\n\n  SerializeObjectAll(allknn, knnXml, knnText, knnBinary);\n\n  // Now run nearest neighbor and make sure the results are the same.\n  arma::mat querySet = arma::randu<arma::mat>(5, 1000);\n\n  arma::mat distances, xmlDistances, textDistances, binaryDistances;\n  arma::Mat<size_t> neighbors, xmlNeighbors, textNeighbors, binaryNeighbors;\n\n  allknn.Search(querySet, 5, neighbors, distances);\n  knnXml.Search(querySet, 5, xmlNeighbors, xmlDistances);\n  knnText.Search(querySet, 5, textNeighbors, textDistances);\n  knnBinary.Search(querySet, 5, binaryNeighbors, binaryDistances);\n\n  CheckMatrices(distances, xmlDistances, textDistances, binaryDistances);\n  CheckMatrices(neighbors, xmlNeighbors, textNeighbors, binaryNeighbors);\n}\n\nBOOST_AUTO_TEST_CASE(SoftmaxRegressionTest)\n{\n  using regression::SoftmaxRegression;\n\n  arma::mat dataset = arma::randu<arma::mat>(5, 1000);\n  arma::Row<size_t> labels(1000);\n  for (size_t i = 0; i < 500; ++i)\n    labels[i] = 0;\n  for (size_t i = 500; i < 1000; ++i)\n    labels[i] = 1;\n\n  SoftmaxRegression<> sr(dataset, labels, 2);\n\n  SoftmaxRegression<> srXml(dataset.n_rows, 2);\n  SoftmaxRegression<> srText(dataset.n_rows, 2);\n  SoftmaxRegression<> srBinary(dataset.n_rows, 2);\n\n  SerializeObjectAll(sr, srXml, srText, srBinary);\n\n  CheckMatrices(sr.Parameters(), srXml.Parameters(), srText.Parameters(),\n      srBinary.Parameters());\n}\n\nBOOST_AUTO_TEST_CASE(DETTest)\n{\n  using det::DTree;\n\n  // Create a density estimation tree on a random dataset.\n  arma::mat dataset = arma::randu<arma::mat>(25, 5000);\n\n  DTree tree(dataset);\n\n  arma::mat otherDataset = arma::randu<arma::mat>(5, 100);\n  DTree xmlTree, binaryTree, textTree(otherDataset);\n\n  SerializeObjectAll(tree, xmlTree, binaryTree, textTree);\n\n  std::stack<DTree*> stack, xmlStack, binaryStack, textStack;\n  stack.push(&tree);\n  xmlStack.push(&xmlTree);\n  binaryStack.push(&binaryTree);\n  textStack.push(&textTree);\n\n  while (!stack.empty())\n  {\n    // Get the top node from the stack.\n    DTree* node = stack.top();\n    DTree* xmlNode = xmlStack.top();\n    DTree* binaryNode = binaryStack.top();\n    DTree* textNode = textStack.top();\n\n    stack.pop();\n    xmlStack.pop();\n    binaryStack.pop();\n    textStack.pop();\n\n    // Check that all the members are the same.\n    BOOST_REQUIRE_EQUAL(node->Start(), xmlNode->Start());\n    BOOST_REQUIRE_EQUAL(node->Start(), binaryNode->Start());\n    BOOST_REQUIRE_EQUAL(node->Start(), textNode->Start());\n\n    BOOST_REQUIRE_EQUAL(node->End(), xmlNode->End());\n    BOOST_REQUIRE_EQUAL(node->End(), binaryNode->End());\n    BOOST_REQUIRE_EQUAL(node->End(), textNode->End());\n\n    BOOST_REQUIRE_EQUAL(node->SplitDim(), xmlNode->SplitDim());\n    BOOST_REQUIRE_EQUAL(node->SplitDim(), binaryNode->SplitDim());\n    BOOST_REQUIRE_EQUAL(node->SplitDim(), textNode->SplitDim());\n\n    if (std::abs(node->SplitValue()) < 1e-5)\n    {\n      BOOST_REQUIRE_SMALL(xmlNode->SplitValue(), 1e-5);\n      BOOST_REQUIRE_SMALL(binaryNode->SplitValue(), 1e-5);\n      BOOST_REQUIRE_SMALL(textNode->SplitValue(), 1e-5);\n    }\n    else\n    {\n      BOOST_REQUIRE_CLOSE(node->SplitValue(), xmlNode->SplitValue(), 1e-5);\n      BOOST_REQUIRE_CLOSE(node->SplitValue(), binaryNode->SplitValue(), 1e-5);\n      BOOST_REQUIRE_CLOSE(node->SplitValue(), textNode->SplitValue(), 1e-5);\n    }\n\n    if (std::abs(node->LogNegError()) < 1e-5)\n    {\n      BOOST_REQUIRE_SMALL(xmlNode->LogNegError(), 1e-5);\n      BOOST_REQUIRE_SMALL(binaryNode->LogNegError(), 1e-5);\n      BOOST_REQUIRE_SMALL(textNode->LogNegError(), 1e-5);\n    }\n    else\n    {\n      BOOST_REQUIRE_CLOSE(node->LogNegError(), xmlNode->LogNegError(), 1e-5);\n      BOOST_REQUIRE_CLOSE(node->LogNegError(), binaryNode->LogNegError(), 1e-5);\n      BOOST_REQUIRE_CLOSE(node->LogNegError(), textNode->LogNegError(), 1e-5);\n    }\n\n    if (std::abs(node->SubtreeLeavesLogNegError()) < 1e-5)\n    {\n      BOOST_REQUIRE_SMALL(xmlNode->SubtreeLeavesLogNegError(), 1e-5);\n      BOOST_REQUIRE_SMALL(binaryNode->SubtreeLeavesLogNegError(), 1e-5);\n      BOOST_REQUIRE_SMALL(textNode->SubtreeLeavesLogNegError(), 1e-5);\n    }\n    else\n    {\n      BOOST_REQUIRE_CLOSE(node->SubtreeLeavesLogNegError(),\n          xmlNode->SubtreeLeavesLogNegError(), 1e-5);\n      BOOST_REQUIRE_CLOSE(node->SubtreeLeavesLogNegError(),\n          binaryNode->SubtreeLeavesLogNegError(), 1e-5);\n      BOOST_REQUIRE_CLOSE(node->SubtreeLeavesLogNegError(),\n          textNode->SubtreeLeavesLogNegError(), 1e-5);\n    }\n\n    BOOST_REQUIRE_EQUAL(node->SubtreeLeaves(), xmlNode->SubtreeLeaves());\n    BOOST_REQUIRE_EQUAL(node->SubtreeLeaves(), binaryNode->SubtreeLeaves());\n    BOOST_REQUIRE_EQUAL(node->SubtreeLeaves(), textNode->SubtreeLeaves());\n\n    if (std::abs(node->Ratio()) < 1e-5)\n    {\n      BOOST_REQUIRE_SMALL(xmlNode->Ratio(), 1e-5);\n      BOOST_REQUIRE_SMALL(binaryNode->Ratio(), 1e-5);\n      BOOST_REQUIRE_SMALL(textNode->Ratio(), 1e-5);\n    }\n    else\n    {\n      BOOST_REQUIRE_CLOSE(node->Ratio(), xmlNode->Ratio(), 1e-5);\n      BOOST_REQUIRE_CLOSE(node->Ratio(), binaryNode->Ratio(), 1e-5);\n      BOOST_REQUIRE_CLOSE(node->Ratio(), textNode->Ratio(), 1e-5);\n    }\n\n    if (std::abs(node->LogVolume()) < 1e-5)\n    {\n      BOOST_REQUIRE_SMALL(xmlNode->LogVolume(), 1e-5);\n      BOOST_REQUIRE_SMALL(binaryNode->LogVolume(), 1e-5);\n      BOOST_REQUIRE_SMALL(textNode->LogVolume(), 1e-5);\n    }\n    else\n    {\n      BOOST_REQUIRE_CLOSE(node->LogVolume(), xmlNode->LogVolume(), 1e-5);\n      BOOST_REQUIRE_CLOSE(node->LogVolume(), binaryNode->LogVolume(), 1e-5);\n      BOOST_REQUIRE_CLOSE(node->LogVolume(), textNode->LogVolume(), 1e-5);\n    }\n\n    if (node->Left() == NULL)\n    {\n      BOOST_REQUIRE(xmlNode->Left() == NULL);\n      BOOST_REQUIRE(binaryNode->Left() == NULL);\n      BOOST_REQUIRE(textNode->Left() == NULL);\n    }\n    else\n    {\n      BOOST_REQUIRE(xmlNode->Left() != NULL);\n      BOOST_REQUIRE(binaryNode->Left() != NULL);\n      BOOST_REQUIRE(textNode->Left() != NULL);\n\n      // Push children onto stack.\n      stack.push(node->Left());\n      xmlStack.push(xmlNode->Left());\n      binaryStack.push(binaryNode->Left());\n      textStack.push(textNode->Left());\n    }\n\n    if (node->Right() == NULL)\n    {\n      BOOST_REQUIRE(xmlNode->Right() == NULL);\n      BOOST_REQUIRE(binaryNode->Right() == NULL);\n      BOOST_REQUIRE(textNode->Right() == NULL);\n    }\n    else\n    {\n      BOOST_REQUIRE(xmlNode->Right() != NULL);\n      BOOST_REQUIRE(binaryNode->Right() != NULL);\n      BOOST_REQUIRE(textNode->Right() != NULL);\n\n      // Push children onto stack.\n      stack.push(node->Right());\n      xmlStack.push(xmlNode->Right());\n      binaryStack.push(binaryNode->Right());\n      textStack.push(textNode->Right());\n    }\n\n    BOOST_REQUIRE_EQUAL(node->Root(), xmlNode->Root());\n    BOOST_REQUIRE_EQUAL(node->Root(), binaryNode->Root());\n    BOOST_REQUIRE_EQUAL(node->Root(), textNode->Root());\n\n    if (std::abs(node->AlphaUpper()) < 1e-5)\n    {\n      BOOST_REQUIRE_SMALL(xmlNode->AlphaUpper(), 1e-5);\n      BOOST_REQUIRE_SMALL(binaryNode->AlphaUpper(), 1e-5);\n      BOOST_REQUIRE_SMALL(textNode->AlphaUpper(), 1e-5);\n    }\n    else\n    {\n      BOOST_REQUIRE_CLOSE(node->AlphaUpper(), xmlNode->AlphaUpper(), 1e-5);\n      BOOST_REQUIRE_CLOSE(node->AlphaUpper(), binaryNode->AlphaUpper(), 1e-5);\n      BOOST_REQUIRE_CLOSE(node->AlphaUpper(), textNode->AlphaUpper(), 1e-5);\n    }\n\n    BOOST_REQUIRE_EQUAL(node->MaxVals().n_elem, xmlNode->MaxVals().n_elem);\n    BOOST_REQUIRE_EQUAL(node->MaxVals().n_elem, binaryNode->MaxVals().n_elem);\n    BOOST_REQUIRE_EQUAL(node->MaxVals().n_elem, textNode->MaxVals().n_elem);\n    for (size_t i = 0; i < node->MaxVals().n_elem; ++i)\n    {\n      if (std::abs(node->MaxVals()[i]) < 1e-5)\n      {\n        BOOST_REQUIRE_SMALL(xmlNode->MaxVals()[i], 1e-5);\n        BOOST_REQUIRE_SMALL(binaryNode->MaxVals()[i], 1e-5);\n        BOOST_REQUIRE_SMALL(textNode->MaxVals()[i], 1e-5);\n      }\n      else\n      {\n        BOOST_REQUIRE_CLOSE(node->MaxVals()[i], xmlNode->MaxVals()[i], 1e-5);\n        BOOST_REQUIRE_CLOSE(node->MaxVals()[i], binaryNode->MaxVals()[i], 1e-5);\n        BOOST_REQUIRE_CLOSE(node->MaxVals()[i], textNode->MaxVals()[i], 1e-5);\n      }\n    }\n\n    BOOST_REQUIRE_EQUAL(node->MinVals().n_elem, xmlNode->MinVals().n_elem);\n    BOOST_REQUIRE_EQUAL(node->MinVals().n_elem, binaryNode->MinVals().n_elem);\n    BOOST_REQUIRE_EQUAL(node->MinVals().n_elem, textNode->MinVals().n_elem);\n    for (size_t i = 0; i < node->MinVals().n_elem; ++i)\n    {\n      if (std::abs(node->MinVals()[i]) < 1e-5)\n      {\n        BOOST_REQUIRE_SMALL(xmlNode->MinVals()[i], 1e-5);\n        BOOST_REQUIRE_SMALL(binaryNode->MinVals()[i], 1e-5);\n        BOOST_REQUIRE_SMALL(textNode->MinVals()[i], 1e-5);\n      }\n      else\n      {\n        BOOST_REQUIRE_CLOSE(node->MinVals()[i], xmlNode->MinVals()[i], 1e-5);\n        BOOST_REQUIRE_CLOSE(node->MinVals()[i], binaryNode->MinVals()[i], 1e-5);\n        BOOST_REQUIRE_CLOSE(node->MinVals()[i], textNode->MinVals()[i], 1e-5);\n      }\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE(NaiveBayesSerializationTest)\n{\n  // Train NBC randomly.  Make sure the model is the same after serializing and\n  // re-loading.\n  arma::mat dataset;\n  dataset.randu(10, 500);\n  arma::Row<size_t> labels(500);\n  for (size_t i = 0; i < 500; ++i)\n  {\n    if (dataset(0, i) > 0.5)\n      labels[i] = 0;\n    else\n      labels[i] = 1;\n  }\n\n  NaiveBayesClassifier<> nbc(dataset, labels, 2);\n\n  // Initialize some empty Naive Bayes classifiers.\n  NaiveBayesClassifier<> xmlNbc(0, 0), textNbc(0, 0), binaryNbc(0, 0);\n  SerializeObjectAll(nbc, xmlNbc, textNbc, binaryNbc);\n\n  BOOST_REQUIRE_EQUAL(nbc.Means().n_elem, xmlNbc.Means().n_elem);\n  BOOST_REQUIRE_EQUAL(nbc.Means().n_elem, textNbc.Means().n_elem);\n  BOOST_REQUIRE_EQUAL(nbc.Means().n_elem, binaryNbc.Means().n_elem);\n  for (size_t i = 0; i < nbc.Means().n_elem; ++i)\n  {\n    BOOST_REQUIRE_CLOSE(nbc.Means()[i], xmlNbc.Means()[i], 1e-5);\n    BOOST_REQUIRE_CLOSE(nbc.Means()[i], textNbc.Means()[i], 1e-5);\n    BOOST_REQUIRE_CLOSE(nbc.Means()[i], binaryNbc.Means()[i], 1e-5);\n  }\n\n  BOOST_REQUIRE_EQUAL(nbc.Variances().n_elem, xmlNbc.Variances().n_elem);\n  BOOST_REQUIRE_EQUAL(nbc.Variances().n_elem, textNbc.Variances().n_elem);\n  BOOST_REQUIRE_EQUAL(nbc.Variances().n_elem, binaryNbc.Variances().n_elem);\n  for (size_t i = 0; i < nbc.Variances().n_elem; ++i)\n  {\n    BOOST_REQUIRE_CLOSE(nbc.Variances()[i], xmlNbc.Variances()[i], 1e-5);\n    BOOST_REQUIRE_CLOSE(nbc.Variances()[i], textNbc.Variances()[i], 1e-5);\n    BOOST_REQUIRE_CLOSE(nbc.Variances()[i], binaryNbc.Variances()[i], 1e-5);\n  }\n\n  BOOST_REQUIRE_EQUAL(nbc.Probabilities().n_elem,\n      xmlNbc.Probabilities().n_elem);\n  BOOST_REQUIRE_EQUAL(nbc.Probabilities().n_elem,\n      textNbc.Probabilities().n_elem);\n  BOOST_REQUIRE_EQUAL(nbc.Probabilities().n_elem,\n      binaryNbc.Probabilities().n_elem);\n  for (size_t i = 0; i < nbc.Probabilities().n_elem; ++i)\n  {\n    BOOST_REQUIRE_CLOSE(nbc.Probabilities()[i], xmlNbc.Probabilities()[i],\n        1e-5);\n    BOOST_REQUIRE_CLOSE(nbc.Probabilities()[i], textNbc.Probabilities()[i],\n        1e-5);\n    BOOST_REQUIRE_CLOSE(nbc.Probabilities()[i], binaryNbc.Probabilities()[i],\n        1e-5);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(RASearchTest)\n{\n  using neighbor::AllkRANN;\n  using neighbor::AllkNN;\n  arma::mat dataset = arma::randu<arma::mat>(5, 200);\n  arma::mat otherDataset = arma::randu<arma::mat>(5, 100);\n\n  // Find nearest neighbors in the top 10, with accuracy 0.95.  So 95% of the\n  // results we get (at least) should fall into the top 10 of the true nearest\n  // neighbors.\n  AllkRANN allkrann(dataset, false, false, 5, 0.95);\n\n  AllkRANN krannXml(otherDataset, false, false);\n  AllkRANN krannText(otherDataset, true, false);\n  AllkRANN krannBinary(otherDataset, true, true);\n\n  SerializeObjectAll(allkrann, krannXml, krannText, krannBinary);\n\n  // Now run nearest neighbor and make sure the results are the same.\n  arma::mat querySet = arma::randu<arma::mat>(5, 100);\n\n  arma::mat distances, xmlDistances, textDistances, binaryDistances;\n  arma::Mat<size_t> neighbors, xmlNeighbors, textNeighbors, binaryNeighbors;\n\n  AllkNN allknn(dataset); // Exact search.\n  allknn.Search(querySet, 10, neighbors, distances);\n  krannXml.Search(querySet, 5, xmlNeighbors, xmlDistances);\n  krannText.Search(querySet, 5, textNeighbors, textDistances);\n  krannBinary.Search(querySet, 5, binaryNeighbors, binaryDistances);\n\n  BOOST_REQUIRE_EQUAL(xmlNeighbors.n_rows, 5);\n  BOOST_REQUIRE_EQUAL(xmlNeighbors.n_cols, 100);\n  BOOST_REQUIRE_EQUAL(textNeighbors.n_rows, 5);\n  BOOST_REQUIRE_EQUAL(textNeighbors.n_cols, 100);\n  BOOST_REQUIRE_EQUAL(binaryNeighbors.n_rows, 5);\n  BOOST_REQUIRE_EQUAL(binaryNeighbors.n_cols, 100);\n\n  size_t xmlCorrect = 0;\n  size_t textCorrect = 0;\n  size_t binaryCorrect = 0;\n  for (size_t i = 0; i < xmlNeighbors.n_cols; ++i)\n  {\n    // See how many are in the top 10.\n    for (size_t j = 0; j < xmlNeighbors.n_rows; ++j)\n    {\n      for (size_t k = 0; k < neighbors.n_rows; ++k)\n      {\n        if (neighbors(k, i) == xmlNeighbors(j, i))\n          xmlCorrect++;\n        if (neighbors(k, i) == textNeighbors(j, i))\n          textCorrect++;\n        if (neighbors(k, i) == binaryNeighbors(j, i))\n          binaryCorrect++;\n      }\n    }\n  }\n\n  // We need 95% of these to be correct.\n  BOOST_REQUIRE_GT(xmlCorrect, 95 * 5);\n  BOOST_REQUIRE_GT(binaryCorrect, 95 * 5);\n  BOOST_REQUIRE_GT(textCorrect, 95 * 5);\n}\n\n/**\n * Test that an LSH model can be serialized and deserialized.\n */\nBOOST_AUTO_TEST_CASE(LSHTest)\n{\n  // Since we still don't have good tests for LSH, basically what we're going to\n  // do is serialize an LSH model, and make sure we can deserialize it and that\n  // we still get results when we call Search().\n  arma::mat referenceData = arma::randu<arma::mat>(10, 100);\n\n  LSHSearch<> lsh(referenceData, 5, 10); // Arbitrary chosen parameters.\n\n  LSHSearch<> xmlLsh;\n  arma::mat textData = arma::randu<arma::mat>(5, 50);\n  LSHSearch<> textLsh(textData, 4, 5);\n  LSHSearch<> binaryLsh(referenceData, 15, 2);\n\n  // Now serialize.\n  SerializeObjectAll(lsh, xmlLsh, textLsh, binaryLsh);\n\n  // Check what we can about the serialized objects.\n  BOOST_REQUIRE_EQUAL(lsh.NumProjections(), xmlLsh.NumProjections());\n  BOOST_REQUIRE_EQUAL(lsh.NumProjections(), textLsh.NumProjections());\n  BOOST_REQUIRE_EQUAL(lsh.NumProjections(), binaryLsh.NumProjections());\n  for (size_t i = 0; i < lsh.NumProjections(); ++i)\n  {\n    CheckMatrices(lsh.Projection(i), xmlLsh.Projection(i),\n        textLsh.Projection(i), binaryLsh.Projection(i));\n  }\n\n  CheckMatrices(lsh.ReferenceSet(), xmlLsh.ReferenceSet(),\n      textLsh.ReferenceSet(), binaryLsh.ReferenceSet());\n  CheckMatrices(lsh.Offsets(), xmlLsh.Offsets(), textLsh.Offsets(),\n      binaryLsh.Offsets());\n  CheckMatrices(lsh.SecondHashWeights(), xmlLsh.SecondHashWeights(),\n      textLsh.SecondHashWeights(), binaryLsh.SecondHashWeights());\n\n  BOOST_REQUIRE_EQUAL(lsh.BucketSize(), xmlLsh.BucketSize());\n  BOOST_REQUIRE_EQUAL(lsh.BucketSize(), textLsh.BucketSize());\n  BOOST_REQUIRE_EQUAL(lsh.BucketSize(), binaryLsh.BucketSize());\n\n  CheckMatrices(lsh.SecondHashTable(), xmlLsh.SecondHashTable(),\n      textLsh.SecondHashTable(), binaryLsh.SecondHashTable());\n}\n\n// Make sure serialization works for the decision stump.\nBOOST_AUTO_TEST_CASE(DecisionStumpTest)\n{\n  // Generate dataset.\n  arma::mat trainingData = arma::randu<arma::mat>(4, 100);\n  arma::Row<size_t> labels(100);\n  for (size_t i = 0; i < 25; ++i)\n    labels[i] = 0;\n  for (size_t i = 25; i < 50; ++i)\n    labels[i] = 3;\n  for (size_t i = 50; i < 75; ++i)\n    labels[i] = 1;\n  for (size_t i = 75; i < 100; ++i)\n    labels[i] = 2;\n\n  DecisionStump<> ds(trainingData, labels, 4, 3);\n\n  arma::mat otherData = arma::randu<arma::mat>(3, 100);\n  arma::Row<size_t> otherLabels = arma::randu<arma::Row<size_t>>(100);\n  DecisionStump<> xmlDs(otherData, otherLabels, 2, 3);\n\n  DecisionStump<> textDs;\n  DecisionStump<> binaryDs(trainingData, labels, 4, 10);\n\n  SerializeObjectAll(ds, xmlDs, textDs, binaryDs);\n\n  // Make sure that everything is the same about the new decision stumps.\n  BOOST_REQUIRE_EQUAL(ds.SplitDimension(), xmlDs.SplitDimension());\n  BOOST_REQUIRE_EQUAL(ds.SplitDimension(), textDs.SplitDimension());\n  BOOST_REQUIRE_EQUAL(ds.SplitDimension(), binaryDs.SplitDimension());\n\n  CheckMatrices(ds.Split(), xmlDs.Split(), textDs.Split(), binaryDs.Split());\n  CheckMatrices(ds.BinLabels(), xmlDs.BinLabels(), textDs.BinLabels(),\n      binaryDs.BinLabels());\n}\n\n// Make sure serialization works for LARS.\nBOOST_AUTO_TEST_CASE(LARSTest)\n{\n  using namespace mlpack::regression;\n\n  // Create a dataset.\n  arma::mat X = arma::randn(75, 250);\n  arma::vec beta = arma::randn(75, 1);\n  arma::vec y = trans(X) * beta;\n\n  LARS lars(true, 0.1, 0.1);\n  arma::vec betaOpt;\n  lars.Train(X, y, betaOpt);\n\n  // Now, serialize.\n  LARS xmlLars(false, 0.5, 0.0), binaryLars(true, 1.0, 0.0),\n      textLars(false, 0.1, 0.1);\n\n  // Train textLars.\n  arma::mat textX = arma::randn(25, 150);\n  arma::vec textBeta = arma::randn(25, 1);\n  arma::vec textY = trans(textX) * textBeta;\n  arma::vec textBetaOpt;\n  textLars.Train(textX, textY, textBetaOpt);\n\n  SerializeObjectAll(lars, xmlLars, binaryLars, textLars);\n\n  // Now, check that predictions are the same.\n  arma::vec pred, xmlPred, textPred, binaryPred;\n  lars.Predict(X, pred);\n  xmlLars.Predict(X, xmlPred);\n  textLars.Predict(X, textPred);\n  binaryLars.Predict(X, binaryPred);\n\n  CheckMatrices(pred, xmlPred, textPred, binaryPred);\n}\n\n/**\n * Test serialization of the HoeffdingNumericSplit object after binning has\n * occured.\n */\nBOOST_AUTO_TEST_CASE(HoeffdingNumericSplitTest)\n{\n  using namespace mlpack::tree;\n\n  HoeffdingNumericSplit<GiniImpurity> split(3);\n  // Train until it bins.\n  for (size_t i = 0; i < 200; ++i)\n    split.Train(mlpack::math::Random(), mlpack::math::RandInt(3));\n\n  HoeffdingNumericSplit<GiniImpurity> xmlSplit(5);\n  HoeffdingNumericSplit<GiniImpurity> textSplit(7);\n  for (size_t i = 0; i < 200; ++i)\n    textSplit.Train(mlpack::math::Random() + 3, 0);\n  HoeffdingNumericSplit<GiniImpurity> binarySplit(2);\n\n  SerializeObjectAll(split, xmlSplit, textSplit, binarySplit);\n\n  // Ensure that everything is the same.\n  BOOST_REQUIRE_EQUAL(split.Bins(), xmlSplit.Bins());\n  BOOST_REQUIRE_EQUAL(split.Bins(), textSplit.Bins());\n  BOOST_REQUIRE_EQUAL(split.Bins(), binarySplit.Bins());\n\n  double bestSplit, secondBestSplit;\n  double baseBestSplit, baseSecondBestSplit;\n  split.EvaluateFitnessFunction(baseBestSplit, baseSecondBestSplit);\n  xmlSplit.EvaluateFitnessFunction(bestSplit, secondBestSplit);\n  BOOST_REQUIRE_CLOSE(bestSplit, baseBestSplit, 1e-5);\n  BOOST_REQUIRE_SMALL(secondBestSplit, 1e-10);\n\n  textSplit.EvaluateFitnessFunction(bestSplit, secondBestSplit);\n  BOOST_REQUIRE_CLOSE(bestSplit, baseBestSplit, 1e-5);\n  BOOST_REQUIRE_SMALL(secondBestSplit, 1e-10);\n\n  binarySplit.EvaluateFitnessFunction(bestSplit, secondBestSplit);\n  BOOST_REQUIRE_CLOSE(bestSplit, baseBestSplit, 1e-5);\n  BOOST_REQUIRE_SMALL(secondBestSplit, 1e-10);\n\n  arma::Col<size_t> children, xmlChildren, textChildren, binaryChildren;\n  NumericSplitInfo<double> splitInfo, xmlSplitInfo, textSplitInfo,\n      binarySplitInfo;\n\n  split.Split(children, splitInfo);\n  xmlSplit.Split(xmlChildren, xmlSplitInfo);\n  binarySplit.Split(binaryChildren, binarySplitInfo);\n  textSplit.Split(textChildren, textSplitInfo);\n\n  BOOST_REQUIRE_EQUAL(children.size(), xmlChildren.size());\n  BOOST_REQUIRE_EQUAL(children.size(), textChildren.size());\n  BOOST_REQUIRE_EQUAL(children.size(), binaryChildren.size());\n  for (size_t i = 0; i < children.size(); ++i)\n  {\n    BOOST_REQUIRE_EQUAL(children[i], xmlChildren[i]);\n    BOOST_REQUIRE_EQUAL(children[i], textChildren[i]);\n    BOOST_REQUIRE_EQUAL(children[i], binaryChildren[i]);\n  }\n\n  // Random checks.\n  for (size_t i = 0; i < 200; ++i)\n  {\n    const double random = mlpack::math::Random() * 1.5;\n    BOOST_REQUIRE_EQUAL(splitInfo.CalculateDirection(random),\n                        xmlSplitInfo.CalculateDirection(random));\n    BOOST_REQUIRE_EQUAL(splitInfo.CalculateDirection(random),\n                        textSplitInfo.CalculateDirection(random));\n    BOOST_REQUIRE_EQUAL(splitInfo.CalculateDirection(random),\n                        binarySplitInfo.CalculateDirection(random));\n  }\n}\n\n/**\n * Make sure serialization of the HoeffdingNumericSplit object before binning\n * occurs is successful.\n */\nBOOST_AUTO_TEST_CASE(HoeffdingNumericSplitBeforeBinningTest)\n{\n  using namespace mlpack::tree;\n\n  HoeffdingNumericSplit<GiniImpurity> split(3);\n  // Train but not until it bins.\n  for (size_t i = 0; i < 50; ++i)\n    split.Train(mlpack::math::Random(), mlpack::math::RandInt(3));\n\n  HoeffdingNumericSplit<GiniImpurity> xmlSplit(5);\n  HoeffdingNumericSplit<GiniImpurity> textSplit(7);\n  for (size_t i = 0; i < 200; ++i)\n    textSplit.Train(mlpack::math::Random() + 3, 0);\n  HoeffdingNumericSplit<GiniImpurity> binarySplit(2);\n\n  SerializeObjectAll(split, xmlSplit, textSplit, binarySplit);\n\n  // Ensure that everything is the same.\n  BOOST_REQUIRE_EQUAL(split.Bins(), xmlSplit.Bins());\n  BOOST_REQUIRE_EQUAL(split.Bins(), textSplit.Bins());\n  BOOST_REQUIRE_EQUAL(split.Bins(), binarySplit.Bins());\n\n  double baseBestSplit, baseSecondBestSplit;\n  double bestSplit, secondBestSplit;\n  split.EvaluateFitnessFunction(baseBestSplit, baseSecondBestSplit);\n  textSplit.EvaluateFitnessFunction(bestSplit, secondBestSplit);\n\n  BOOST_REQUIRE_SMALL(baseBestSplit, 1e-5);\n  BOOST_REQUIRE_SMALL(baseSecondBestSplit, 1e-5);\n\n  BOOST_REQUIRE_SMALL(bestSplit, 1e-5);\n  BOOST_REQUIRE_SMALL(secondBestSplit, 1e-5);\n\n  xmlSplit.EvaluateFitnessFunction(bestSplit, secondBestSplit);\n  BOOST_REQUIRE_SMALL(bestSplit, 1e-5);\n  BOOST_REQUIRE_SMALL(secondBestSplit, 1e-5);\n\n  binarySplit.EvaluateFitnessFunction(bestSplit, secondBestSplit);\n  BOOST_REQUIRE_SMALL(bestSplit, 1e-5);\n  BOOST_REQUIRE_SMALL(secondBestSplit, 1e-5);\n}\n\n/**\n * Make sure the HoeffdingCategoricalSplit object serializes correctly.\n */\nBOOST_AUTO_TEST_CASE(HoeffdingCategoricalSplitTest)\n{\n  using namespace mlpack::tree;\n\n  HoeffdingCategoricalSplit<GiniImpurity> split(10, 3);\n  for (size_t i = 0; i < 50; ++i)\n    split.Train(mlpack::math::RandInt(10), mlpack::math::RandInt(3));\n\n  HoeffdingCategoricalSplit<GiniImpurity> xmlSplit(3, 7);\n  HoeffdingCategoricalSplit<GiniImpurity> binarySplit(4, 11);\n  HoeffdingCategoricalSplit<GiniImpurity> textSplit(2, 2);\n  for (size_t i = 0; i < 10; ++i)\n    textSplit.Train(mlpack::math::RandInt(2), mlpack::math::RandInt(2));\n\n  SerializeObjectAll(split, xmlSplit, textSplit, binarySplit);\n\n  BOOST_REQUIRE_EQUAL(split.MajorityClass(), xmlSplit.MajorityClass());\n  BOOST_REQUIRE_EQUAL(split.MajorityClass(), textSplit.MajorityClass());\n  BOOST_REQUIRE_EQUAL(split.MajorityClass(), binarySplit.MajorityClass());\n\n  double bestSplit, secondBestSplit;\n  double baseBestSplit, baseSecondBestSplit;\n  split.EvaluateFitnessFunction(baseBestSplit, baseSecondBestSplit);\n  xmlSplit.EvaluateFitnessFunction(bestSplit, secondBestSplit);\n\n  BOOST_REQUIRE_CLOSE(bestSplit, baseBestSplit, 1e-5);\n  BOOST_REQUIRE_SMALL(secondBestSplit, 1e-10);\n\n  textSplit.EvaluateFitnessFunction(bestSplit, secondBestSplit);\n  BOOST_REQUIRE_CLOSE(bestSplit, baseBestSplit, 1e-5);\n  BOOST_REQUIRE_SMALL(secondBestSplit, 1e-10);\n\n  binarySplit.EvaluateFitnessFunction(bestSplit, secondBestSplit);\n  BOOST_REQUIRE_CLOSE(bestSplit, baseBestSplit, 1e-5);\n  BOOST_REQUIRE_SMALL(secondBestSplit, 1e-10);\n\n  arma::Col<size_t> children, xmlChildren, textChildren, binaryChildren;\n  CategoricalSplitInfo splitInfo(1); // I don't care about this.\n\n  split.Split(children, splitInfo);\n  xmlSplit.Split(xmlChildren, splitInfo);\n  binarySplit.Split(binaryChildren, splitInfo);\n  textSplit.Split(textChildren, splitInfo);\n\n  BOOST_REQUIRE_EQUAL(children.size(), xmlChildren.size());\n  BOOST_REQUIRE_EQUAL(children.size(), textChildren.size());\n  BOOST_REQUIRE_EQUAL(children.size(), binaryChildren.size());\n  for (size_t i = 0; i < children.size(); ++i)\n  {\n    BOOST_REQUIRE_EQUAL(children[i], xmlChildren[i]);\n    BOOST_REQUIRE_EQUAL(children[i], textChildren[i]);\n    BOOST_REQUIRE_EQUAL(children[i], binaryChildren[i]);\n  }\n}\n\n/**\n * Make sure the HoeffdingTree object serializes correctly before a split has\n * occured.\n */\nBOOST_AUTO_TEST_CASE(HoeffdingTreeBeforeSplitTest)\n{\n  data::DatasetInfo info(5);\n  info.MapString(\"0\", 2); // Dimension 1 is categorical.\n  info.MapString(\"1\", 2);\n  HoeffdingTree<> split(info, 2, 0.99, 15000, 1);\n\n  // Train for 2 samples.\n  split.Train(arma::vec(\"0.3 0.4 1 0.6 0.7\"), 0);\n  split.Train(arma::vec(\"-0.3 0.0 0 0.7 0.8\"), 1);\n\n  data::DatasetInfo wrongInfo(3);\n  wrongInfo.MapString(\"1\", 1);\n  HoeffdingTree<> xmlSplit(wrongInfo, 7, 0.1, 10, 1);\n\n  // Force the binarySplit to split.\n  data::DatasetInfo binaryInfo(2);\n  binaryInfo.MapString(\"cat0\", 0);\n  binaryInfo.MapString(\"cat1\", 0);\n  binaryInfo.MapString(\"cat0\", 1);\n\n  HoeffdingTree<> binarySplit(info, 2, 0.95, 5000, 1);\n\n  // Feed samples from each class.\n  for (size_t i = 0; i < 500; ++i)\n  {\n    binarySplit.Train(arma::Col<size_t>(\"0 0\"), 0);\n    binarySplit.Train(arma::Col<size_t>(\"1 0\"), 1);\n  }\n\n  HoeffdingTree<> textSplit(wrongInfo, 11, 0.75, 1000, 1);\n\n  SerializeObjectAll(split, xmlSplit, textSplit, binarySplit);\n\n  BOOST_REQUIRE_EQUAL(split.SplitDimension(), xmlSplit.SplitDimension());\n  BOOST_REQUIRE_EQUAL(split.SplitDimension(), binarySplit.SplitDimension());\n  BOOST_REQUIRE_EQUAL(split.SplitDimension(), textSplit.SplitDimension());\n\n  BOOST_REQUIRE_EQUAL(split.MajorityClass(), xmlSplit.MajorityClass());\n  BOOST_REQUIRE_EQUAL(split.MajorityClass(), binarySplit.MajorityClass());\n  BOOST_REQUIRE_EQUAL(split.MajorityClass(), textSplit.MajorityClass());\n\n  BOOST_REQUIRE_EQUAL(split.SplitCheck(), xmlSplit.SplitCheck());\n  BOOST_REQUIRE_EQUAL(split.SplitCheck(), binarySplit.SplitCheck());\n  BOOST_REQUIRE_EQUAL(split.SplitCheck(), textSplit.SplitCheck());\n}\n\n/**\n * Make sure the HoeffdingTree object serializes correctly after a split has\n * occurred.\n */\nBOOST_AUTO_TEST_CASE(HoeffdingTreeAfterSplitTest)\n{\n  // Force the split to split.\n  data::DatasetInfo info(2);\n  info.MapString(\"cat0\", 0);\n  info.MapString(\"cat1\", 0);\n  info.MapString(\"cat0\", 1);\n\n  HoeffdingTree<> split(info, 2, 0.95, 5000, 1);\n\n  // Feed samples from each class.\n  for (size_t i = 0; i < 500; ++i)\n  {\n    split.Train(arma::Col<size_t>(\"0 0\"), 0);\n    split.Train(arma::Col<size_t>(\"1 0\"), 1);\n  }\n  // Ensure a split has happened.\n  BOOST_REQUIRE_NE(split.SplitDimension(), size_t(-1));\n\n  data::DatasetInfo wrongInfo(3);\n  wrongInfo.MapString(\"1\", 1);\n  HoeffdingTree<> xmlSplit(wrongInfo, 7, 0.1, 10, 1);\n\n  data::DatasetInfo binaryInfo(5);\n  binaryInfo.MapString(\"0\", 2); // Dimension 2 is categorical.\n  binaryInfo.MapString(\"1\", 2);\n  HoeffdingTree<> binarySplit(binaryInfo, 2, 0.99, 15000, 1);\n\n  // Train for 2 samples.\n  binarySplit.Train(arma::vec(\"0.3 0.4 1 0.6 0.7\"), 0);\n  binarySplit.Train(arma::vec(\"-0.3 0.0 0 0.7 0.8\"), 1);\n\n  HoeffdingTree<> textSplit(wrongInfo, 11, 0.75, 1000, 1);\n\n  SerializeObjectAll(split, xmlSplit, textSplit, binarySplit);\n\n  BOOST_REQUIRE_EQUAL(split.SplitDimension(), xmlSplit.SplitDimension());\n  BOOST_REQUIRE_EQUAL(split.SplitDimension(), binarySplit.SplitDimension());\n  BOOST_REQUIRE_EQUAL(split.SplitDimension(), textSplit.SplitDimension());\n\n  // If splitting has already happened, then SplitCheck() should return 0.\n  BOOST_REQUIRE_EQUAL(split.SplitCheck(), 0);\n  BOOST_REQUIRE_EQUAL(split.SplitCheck(), xmlSplit.SplitCheck());\n  BOOST_REQUIRE_EQUAL(split.SplitCheck(), binarySplit.SplitCheck());\n  BOOST_REQUIRE_EQUAL(split.SplitCheck(), textSplit.SplitCheck());\n\n  BOOST_REQUIRE_EQUAL(split.MajorityClass(), xmlSplit.MajorityClass());\n  BOOST_REQUIRE_EQUAL(split.MajorityClass(), binarySplit.MajorityClass());\n  BOOST_REQUIRE_EQUAL(split.MajorityClass(), textSplit.MajorityClass());\n\n  BOOST_REQUIRE_EQUAL(split.CalculateDirection(arma::vec(\"0.3 0.4 1 0.6 0.7\")),\n      xmlSplit.CalculateDirection(arma::vec(\"0.3 0.4 1 0.6 0.7\")));\n  BOOST_REQUIRE_EQUAL(split.CalculateDirection(arma::vec(\"0.3 0.4 1 0.6 0.7\")),\n      binarySplit.CalculateDirection(arma::vec(\"0.3 0.4 1 0.6 0.7\")));\n  BOOST_REQUIRE_EQUAL(split.CalculateDirection(arma::vec(\"0.3 0.4 1 0.6 0.7\")),\n      textSplit.CalculateDirection(arma::vec(\"0.3 0.4 1 0.6 0.7\")));\n}\n\nBOOST_AUTO_TEST_CASE(EmptyHoeffdingTreeTest)\n{\n  using namespace mlpack::tree;\n\n  data::DatasetInfo info(6);\n  HoeffdingTree<> tree(info, 2);\n  HoeffdingTree<> xmlTree(info, 3);\n  HoeffdingTree<> binaryTree(info, 4);\n  HoeffdingTree<> textTree(info, 5);\n\n  SerializeObjectAll(tree, xmlTree, binaryTree, textTree);\n\n  BOOST_REQUIRE_EQUAL(tree.NumChildren(), 0);\n  BOOST_REQUIRE_EQUAL(xmlTree.NumChildren(), 0);\n  BOOST_REQUIRE_EQUAL(binaryTree.NumChildren(), 0);\n  BOOST_REQUIRE_EQUAL(textTree.NumChildren(), 0);\n}\n\n/**\n * Build a Hoeffding tree, then save it and make sure other trees can classify\n * as effectively.\n */\nBOOST_AUTO_TEST_CASE(HoeffdingTreeTest)\n{\n  using namespace mlpack::tree;\n\n  arma::mat dataset(2, 400);\n  arma::Row<size_t> labels(400);\n  for (size_t i = 0; i < 200; ++i)\n  {\n    dataset(0, 2 * i) = mlpack::math::RandInt(4);\n    dataset(1, 2 * i) = mlpack::math::RandInt(2);\n    dataset(0, 2 * i + 1) = mlpack::math::RandInt(4);\n    dataset(1, 2 * i + 1) = mlpack::math::RandInt(2) + 2;\n    labels[2 * i] = 0;\n    labels[2 * i + 1] = 1;\n  }\n  // Make the features categorical.\n  data::DatasetInfo info(2);\n  info.MapString(\"a\", 0);\n  info.MapString(\"b\", 0);\n  info.MapString(\"c\", 0);\n  info.MapString(\"d\", 0);\n  info.MapString(\"a\", 1);\n  info.MapString(\"b\", 1);\n  info.MapString(\"c\", 1);\n  info.MapString(\"d\", 1);\n\n  HoeffdingTree<> tree(dataset, info, labels, 2, false /* no batch mode */);\n\n  data::DatasetInfo xmlInfo(1);\n  HoeffdingTree<> xmlTree(xmlInfo, 1);\n  data::DatasetInfo binaryInfo(5);\n  HoeffdingTree<> binaryTree(binaryInfo, 6);\n  data::DatasetInfo textInfo(7);\n  HoeffdingTree<> textTree(textInfo, 100);\n\n  SerializeObjectAll(tree, xmlTree, textTree, binaryTree);\n\n  BOOST_REQUIRE_EQUAL(tree.NumChildren(), xmlTree.NumChildren());\n  BOOST_REQUIRE_EQUAL(tree.NumChildren(), textTree.NumChildren());\n  BOOST_REQUIRE_EQUAL(tree.NumChildren(), binaryTree.NumChildren());\n\n  BOOST_REQUIRE_EQUAL(tree.SplitDimension(), xmlTree.SplitDimension());\n  BOOST_REQUIRE_EQUAL(tree.SplitDimension(), textTree.SplitDimension());\n  BOOST_REQUIRE_EQUAL(tree.SplitDimension(), binaryTree.SplitDimension());\n\n  for (size_t i = 0; i < tree.NumChildren(); ++i)\n  {\n    BOOST_REQUIRE_EQUAL(tree.Child(i).NumChildren(), 0);\n    BOOST_REQUIRE_EQUAL(xmlTree.Child(i).NumChildren(), 0);\n    BOOST_REQUIRE_EQUAL(binaryTree.Child(i).NumChildren(), 0);\n    BOOST_REQUIRE_EQUAL(textTree.Child(i).NumChildren(), 0);\n\n    BOOST_REQUIRE_EQUAL(tree.Child(i).SplitDimension(),\n        xmlTree.Child(i).SplitDimension());\n    BOOST_REQUIRE_EQUAL(tree.Child(i).SplitDimension(),\n        textTree.Child(i).SplitDimension());\n    BOOST_REQUIRE_EQUAL(tree.Child(i).SplitDimension(),\n        binaryTree.Child(i).SplitDimension());\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "dc17bac1ce9e2da0c16b100eb593244adeb6b03d", "size": 54990, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/serialization_test.cpp", "max_stars_repo_name": "abhinvgpta/mlpack", "max_stars_repo_head_hexsha": "c5573b26c0f5c78037e4b82e75ccbcef6f254694", "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-08-17T11:59:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-17T11:59:20.000Z", "max_issues_repo_path": "src/mlpack/tests/serialization_test.cpp", "max_issues_repo_name": "decltypeme/mlpack", "max_issues_repo_head_hexsha": "e3b418918fffce382ce9d8ceee9d9349ca199611", "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/tests/serialization_test.cpp", "max_forks_repo_name": "decltypeme/mlpack", "max_forks_repo_head_hexsha": "e3b418918fffce382ce9d8ceee9d9349ca199611", "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": 32.7516378797, "max_line_length": 80, "alphanum_fraction": 0.6997454083, "num_tokens": 15431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435083355187, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.4718912072004499}}
{"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_FUNCTION_EXPRECNEGC_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_EXPRECNEGC_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-exponential\n    Function object implementing exprecnegc capabilities\n\n    Computes the  function: \\f$1-e^{-\\frac1x}\\f$\n\n    @par Semantic:\n\n    For every parameter of floating type T\n\n    @code\n    T r = exprecnegc(x);\n    @endcode\n\n    is equivalent to\n    @code\n    T r = oneminus(exp(-rec((x))));\n    @endcode\n\n    @see exp, exprecneg\n\n  **/\n  const boost::dispatch::functor<tag::exprecnegc_> exprecnegc = {};\n} }\n#endif\n\n#include <boost/simd/function/scalar/exprecnegc.hpp>\n#include <boost/simd/function/simd/exprecnegc.hpp>\n\n#endif\n", "meta": {"hexsha": "ce809f5d5e8d131aca691d17beb19c8a566d8487", "size": 1153, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/exprecnegc.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/function/exprecnegc.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/function/exprecnegc.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": 23.06, "max_line_length": 100, "alphanum_fraction": 0.5845620121, "num_tokens": 270, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.47189120078311336}}
{"text": "/*!\n * @file\n * An example of logistic regression training and testing.\n * The data is taken from:\n *\n * command to run:\n * ./bin/trajectory \"data/trajectory/traj.txt\"\n *\n * For running on some different data-set specify the columns etc. in `fromFile`\n * if needed and give the file(s) as command line argument.\n * */\n#include <array>\n#include <iostream>\n#include <stdexcept>\n#include <string>\n#include <tuple>\n#include <vector>\n#include <boost/mpi.hpp>\n\n#include <ezl.hpp>\n#include <ezl/algorithms/reduces.hpp>\n#include <ezl/algorithms/fromFile.hpp>\n\nusing namespace std;\n\nauto difference(const array<float, 3>& prev, const array<float, 3>& next) {\n  array<float, 3> diff;\n  for(auto i : {0, 1, 2}) {\n    diff[i] = next[i] - prev[i];\n  }\n  return diff;\n}\n\nauto crossProd(const array<float, 3>& v1, const array<float, 3>& v2) {\n  array<float, 3> prod;\n  prod[0] = v1[1]*v2[2] - v1[2]*v2[1];\n  prod[1] = v1[2]*v2[0] - v1[0]*v2[2];\n  prod[2] = v1[0]*v2[1] - v1[1]*v2[0];\n  return prod;\n}\n\nvoid trajectory(int argc, char* argv[]) {\n  const auto epsilon = 0.00001F;\n  const string outFile = \"data/output/traj.txt\";\n  std::string inFile = \"data/trajectory/traj.txt\";\n  if (argc > 1) inFile = std::string(argv[1]);\n\n  ezl::rise(ezl::fromFile<array<float, 3>>(inFile)\n                .cols({1, 2, 3})\n                .colSeparator(\" \\t\"))\n      .reduceAll([](const vector<array<float, 3>> & v) {\n        return difference(v[0], v[1]);\n      }).adjacent(2)\n      .reduceAll([](const vector<array<float, 3>> & v) {\n        return crossProd(v[0], v[1]);\n      }).adjacent(2)\n      .map([&epsilon](array<float, 3> prod) {\n        array<int, 3> res;\n        for (auto i : {0, 1, 2}) {\n          res[i] = (fabs(prod[i]) > epsilon) ? (prod[i] / fabs(prod[i])) : 0;\n        }\n        return res;\n      })\n      .reduce<2>(ezl::count(), 0).inprocess()\n      .reduceAll([](vector<tuple<array<int, 3>, int>> a) {\n        sort(a.begin(), a.end());\n        return a;\n      }).dump(outFile)\n      .run(1); // Always runs with single process\n}\n\nint main(int argc, char *argv[]) {\n  boost::mpi::environment env(argc, argv, false);\n  try {\n    trajectory(argc, argv);\n  } catch (const exception& ex) {\n    cerr<<\"error: \"<<ex.what()<<'\\n';\n    env.abort(1);  \n  } catch (...) {\n    cerr<<\"unknown exception\\n\";\n    env.abort(2);  \n  }\n  return 0;\n}\n", "meta": {"hexsha": "2292a314904fd907395df64bcbe3e0ecb0f1a89f", "size": 2325, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/trajectory.cpp", "max_stars_repo_name": "YcheParallelStudio/easyLambda", "max_stars_repo_head_hexsha": "e496a3e3070b806e8c48124d3454543c4cebc9b7", "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/trajectory.cpp", "max_issues_repo_name": "YcheParallelStudio/easyLambda", "max_issues_repo_head_hexsha": "e496a3e3070b806e8c48124d3454543c4cebc9b7", "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/trajectory.cpp", "max_forks_repo_name": "YcheParallelStudio/easyLambda", "max_forks_repo_head_hexsha": "e496a3e3070b806e8c48124d3454543c4cebc9b7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3529411765, "max_line_length": 80, "alphanum_fraction": 0.5789247312, "num_tokens": 734, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.47189120078311336}}
{"text": "#include <stan/math/mix/scal.hpp>\n#include <gtest/gtest.h>\n#include <boost/math/special_functions/gamma.hpp>\n#include <test/unit/math/rev/scal/fun/util.hpp>\n#include <test/unit/math/mix/scal/fun/nan_util.hpp>\n\n\nTEST(AgradFwdGammaQ, FvarVar_FvarVar_1stDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n\n  fvar<var> x(0.5,1.0);\n  fvar<var> z(1.0,1.0);\n  fvar<var> a = stan::math::gamma_q(x,z);\n\n  EXPECT_FLOAT_EQ(boost::math::gamma_q(0.5,1.0), a.val_.val());\n  EXPECT_FLOAT_EQ(0.18228334, a.d_.val());\n\n  AVEC y = createAVEC(x.val_,z.val_);\n  VEC g;\n  a.val_.grad(y,g);\n  EXPECT_FLOAT_EQ(0.38983709,g[0]);\n  EXPECT_FLOAT_EQ(-boost::math::gamma_p_derivative(0.5,1.0),g[1]);\n}\nTEST(AgradFwdGammaQ, Double_FvarVar_1stDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n\n  double x(0.5);\n  fvar<var> z(1.0,1.0);\n  fvar<var> a = stan::math::gamma_q(x,z);\n\n  EXPECT_FLOAT_EQ(boost::math::gamma_q(0.5,1.0), a.val_.val());\n  EXPECT_FLOAT_EQ(-boost::math::gamma_p_derivative(0.5,1.0), a.d_.val());\n\n  AVEC y = createAVEC(z.val_);\n  VEC g;\n  a.val_.grad(y,g);\n  EXPECT_FLOAT_EQ(-boost::math::gamma_p_derivative(0.5,1.0),g[0]);\n}\nTEST(AgradFwdGammaQ, FvarVar_Double_1stDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n\n  fvar<var> x(0.5,1.0);\n  double z(1.0);\n  fvar<var> a = stan::math::gamma_q(x,z);\n\n  EXPECT_FLOAT_EQ(boost::math::gamma_q(0.5,1.0), a.val_.val());\n  EXPECT_FLOAT_EQ(0.38983709, a.d_.val());\n\n  AVEC y = createAVEC(x.val_);\n  VEC g;\n  a.val_.grad(y,g);\n  EXPECT_FLOAT_EQ(0.38983709,g[0]);\n}\nTEST(AgradFwdGammaQ, FvarVar_FvarVar_2ndDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n\n  fvar<var> x(0.5,1.0);\n  fvar<var> z(1.0,1.0);\n  fvar<var> a = stan::math::gamma_q(x,z);\n\n  EXPECT_FLOAT_EQ(boost::math::gamma_q(0.5,1.0), a.val_.val());\n  EXPECT_FLOAT_EQ(0.18228334, a.d_.val());\n\n  AVEC y = createAVEC(x.val_,z.val_);\n  VEC g;\n  a.d_.grad(y,g);\n  EXPECT_FLOAT_EQ(-0.19403456,g[0]);\n  EXPECT_FLOAT_EQ(-0.096204743,g[1]);\n}\nTEST(AgradFwdGammaQ, Double_FvarVar_2ndDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n\n  double x(0.5);\n  fvar<var> z(1.0,1.0);\n  fvar<var> a = stan::math::gamma_q(x,z);\n\n  EXPECT_FLOAT_EQ(boost::math::gamma_q(0.5,1.0), a.val_.val());\n  EXPECT_FLOAT_EQ(-boost::math::gamma_p_derivative(0.5,1.0), a.d_.val());\n\n  AVEC y = createAVEC(z.val_);\n  VEC g;\n  a.d_.grad(y,g);\n  EXPECT_FLOAT_EQ(0.31133062,g[0]);\n}\nTEST(AgradFwdGammaQ, FvarVar_Double_2ndDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n\n  fvar<var> x(0.5,1.0);\n  double z(1.0);\n  fvar<var> a = stan::math::gamma_q(x,z);\n\n  EXPECT_FLOAT_EQ(boost::math::gamma_q(0.5,1.0), a.val_.val());\n  EXPECT_FLOAT_EQ(0.38983709, a.d_.val());\n\n  AVEC y = createAVEC(x.val_);\n  VEC g;\n  a.d_.grad(y,g);\n  EXPECT_FLOAT_EQ(0.21349931,g[0]);\n}\n\n\n\nTEST(AgradFwdGammaQ, FvarFvarVar_FvarFvarVar_1stDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using boost::math::gamma_q;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 0.5;\n  x.val_.d_ = 1.0;\n\n  fvar<fvar<var> > y;\n  y.val_.val_ = 1.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = gamma_q(x,y);\n\n  EXPECT_FLOAT_EQ(gamma_q(0.5,1.0), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(0.38983709, a.val_.d_.val());\n  EXPECT_FLOAT_EQ(-boost::math::gamma_p_derivative(0.5,1.0), a.d_.val_.val());\n  EXPECT_FLOAT_EQ(-0.40753385, a.d_.d_.val());\n\n  AVEC p = createAVEC(x.val_.val_,y.val_.val_);\n  VEC g;\n  a.val_.val_.grad(p,g);\n  EXPECT_FLOAT_EQ(0.38983709, g[0]);\n  EXPECT_FLOAT_EQ(-boost::math::gamma_p_derivative(0.5,1.0), g[1]);\n}\nTEST(AgradFwdGammaQ, Double_FvarFvarVar_1stDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using boost::math::gamma_q;\n\n  double x(0.5);\n\n  fvar<fvar<var> > y;\n  y.val_.val_ = 1.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = gamma_q(x,y);\n\n  EXPECT_FLOAT_EQ(gamma_q(0.5,1.0), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(0, a.val_.d_.val());\n  EXPECT_FLOAT_EQ(-boost::math::gamma_p_derivative(0.5,1.0), a.d_.val_.val());\n  EXPECT_FLOAT_EQ(0, a.d_.d_.val());\n\n  AVEC p = createAVEC(y.val_.val_);\n  VEC g;\n  a.val_.val_.grad(p,g);\n  EXPECT_FLOAT_EQ(-boost::math::gamma_p_derivative(0.5,1.0), g[0]);\n}\nTEST(AgradFwdGammaQ, FvarFvarVar_Double_1stDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using boost::math::gamma_q;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 0.5;\n  x.val_.d_ = 1.0;\n\n  double y(1.0);\n\n  fvar<fvar<var> > a = gamma_q(x,y);\n\n  EXPECT_FLOAT_EQ(gamma_q(0.5,1.0), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(0.38983709, a.val_.d_.val());\n  EXPECT_FLOAT_EQ(0, a.d_.val_.val());\n  EXPECT_FLOAT_EQ(0, a.d_.d_.val());\n\n  AVEC p = createAVEC(x.val_.val_);\n  VEC g;\n  a.val_.val_.grad(p,g);\n  EXPECT_FLOAT_EQ(0.38983709, g[0]);\n}\n\nTEST(AgradFwdGammaQ, FvarFvarVar_FvarFvarVar_2ndDeriv_x) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using boost::math::gamma_q;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 0.5;\n  x.val_.d_ = 1.0;\n\n  fvar<fvar<var> > y;\n  y.val_.val_ = 1.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = gamma_q(x,y);\n\n  EXPECT_FLOAT_EQ(gamma_q(0.5,1.0), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(0.38983709, a.val_.d_.val());\n  EXPECT_FLOAT_EQ(-boost::math::gamma_p_derivative(0.5,1.0), a.d_.val_.val());\n  EXPECT_FLOAT_EQ(-0.40753385, a.d_.d_.val());\n\n  AVEC p = createAVEC(x.val_.val_,y.val_.val_);\n  VEC g;\n  a.val_.d_.grad(p,g);\n  EXPECT_FLOAT_EQ(0.21349931, g[0]);\n  EXPECT_FLOAT_EQ(-0.40753537, g[1]);\n}\nTEST(AgradFwdGammaQ, FvarFvarVar_FvarFvarVar_2ndDeriv_y) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using boost::math::gamma_q;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 0.5;\n  x.val_.d_ = 1.0;\n\n  fvar<fvar<var> > y;\n  y.val_.val_ = 1.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = gamma_q(x,y);\n\n  EXPECT_FLOAT_EQ(gamma_q(0.5,1.0), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(0.38983709, a.val_.d_.val());\n  EXPECT_FLOAT_EQ(-boost::math::gamma_p_derivative(0.5,1.0), a.d_.val_.val());\n  EXPECT_FLOAT_EQ(-0.40753385, a.d_.d_.val());\n\n  AVEC p = createAVEC(x.val_.val_,y.val_.val_);\n  VEC g;\n  a.d_.val_.grad(p,g);\n  EXPECT_FLOAT_EQ(-0.40753385, g[0]);\n  EXPECT_FLOAT_EQ(0.31133062, g[1]);\n}\nTEST(AgradFwdGammaQ, Double_FvarFvarVar_2ndDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using boost::math::gamma_q;\n\n  double x(0.5);\n\n  fvar<fvar<var> > y;\n  y.val_.val_ = 1.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = gamma_q(x,y);\n\n  EXPECT_FLOAT_EQ(gamma_q(0.5,1.0), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(0, a.val_.d_.val());\n  EXPECT_FLOAT_EQ(-boost::math::gamma_p_derivative(0.5,1.0), a.d_.val_.val());\n  EXPECT_FLOAT_EQ(0, a.d_.d_.val());\n\n  AVEC p = createAVEC(y.val_.val_);\n  VEC g;\n  a.d_.val_.grad(p,g);\n  EXPECT_FLOAT_EQ(0.31133062, g[0]);\n}\nTEST(AgradFwdGammaQ, FvarFvarVar_Double_2ndDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using boost::math::gamma_q;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 0.5;\n  x.val_.d_ = 1.0;\n\n  double y(1.0);\n\n  fvar<fvar<var> > a = gamma_q(x,y);\n\n  EXPECT_FLOAT_EQ(gamma_q(0.5,1.0), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(0.38983709, a.val_.d_.val());\n  EXPECT_FLOAT_EQ(0, a.d_.val_.val());\n  EXPECT_FLOAT_EQ(0, a.d_.d_.val());\n\n  AVEC p = createAVEC(x.val_.val_);\n  VEC g;\n  a.val_.d_.grad(p,g);\n  EXPECT_FLOAT_EQ(0.21349931, g[0]);\n}\n\nTEST(AgradFwdGammaQ, FvarFvarVar_FvarFvarVar_3rdDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using boost::math::gamma_q;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 0.5;\n  x.val_.d_ = 1.0;\n\n  fvar<fvar<var> > y;\n  y.val_.val_ = 1.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = gamma_q(x,y);\n\n  EXPECT_FLOAT_EQ(gamma_q(0.5,1.0), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(0.38983709, a.val_.d_.val());\n  EXPECT_FLOAT_EQ(-boost::math::gamma_p_derivative(0.5,1.0), a.d_.val_.val());\n  EXPECT_FLOAT_EQ(-0.40753385, a.d_.d_.val());\n\n  AVEC p = createAVEC(x.val_.val_,y.val_.val_);\n  VEC g;\n  a.d_.d_.grad(p,g);\n  EXPECT_FLOAT_EQ(0.22403987, g[0]);\n  EXPECT_FLOAT_EQ(0.40374705, g[1]);\n}\nTEST(AgradFwdGammaQ, Double_FvarFvarVar_3rdDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using boost::math::gamma_q;\n\n  double x(0.5);\n\n  fvar<fvar<var> > y;\n  y.val_.val_ = 1.0;\n  y.d_.val_ = 1.0;\n  y.val_.d_ = 1.0;\n\n  fvar<fvar<var> > a = gamma_q(x,y);\n\n  AVEC p = createAVEC(y.val_.val_);\n  VEC g;\n  a.d_.d_.grad(p,g);\n  EXPECT_FLOAT_EQ(-0.57077283, g[0]);\n}\nTEST(AgradFwdGammaQ, FvarFvarVar_Double_3rdDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using boost::math::gamma_q;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 0.5;\n  x.val_.d_ = 1.0;\n  x.d_.val_ = 1.0;\n\n  double y(1.0);\n\n  fvar<fvar<var> > a = gamma_q(x,y);\n\n  AVEC p = createAVEC(x.val_.val_);\n  VEC g;\n  a.d_.d_.grad(p,g);\n  EXPECT_FLOAT_EQ(-0.5462361, g[0]);\n}\n\nstruct gamma_q_fun {\n  template <typename T0, typename T1>\n  inline \n  typename boost::math::tools::promote_args<T0,T1>::type\n  operator()(const T0 arg1,\n             const T1 arg2) const {\n    return gamma_q(arg1,arg2);\n  }\n};\n\nTEST(AgradFwdGammaQ, nan) {\n  gamma_q_fun gamma_q_;\n  test_nan_mix(gamma_q_,3.0,5.0,false);\n}\n", "meta": {"hexsha": "ee9d61d50dd9e831f1b77b009e70dcca94d89ccd", "size": 8916, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/mix/scal/fun/gamma_q_test.cpp", "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/test/unit/math/mix/scal/fun/gamma_q_test.cpp", "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/test/unit/math/mix/scal/fun/gamma_q_test.cpp", "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": 24.7666666667, "max_line_length": 78, "alphanum_fraction": 0.6532077165, "num_tokens": 3586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.47189120078311325}}
{"text": "#include <iostream>\n#include <stdexcept>\n// Boost random generator\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/normal_distribution.hpp>\n// Eigen dense matrices\n#include <Eigen/Dense>\n\n#include \"factory.h\"\n#include \"normal_multivar.h\"\n\nnamespace numeric_utils {\n\nNormalMultiVar::NormalMultiVar()\n  : RandomGenerator()\n{\n  generator_ = boost::random::mt19937(seed_);\n  distribution_ = boost::random::normal_distribution<double>();\n}\n\nNormalMultiVar::NormalMultiVar(int seed)\n  : RandomGenerator()\n{\n  seed_ = seed;\n  generator_ = boost::random::mt19937(seed_);\n  distribution_ = boost::random::normal_distribution<double>();\n}\n\nbool NormalMultiVar::generate(\n    Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>& random_numbers,\n    const Eigen::VectorXd& means, const Eigen::MatrixXd& cov,\n    unsigned int cases) {\n\n  bool success = true;\n  Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> lower_cholesky;\n  \n  try {\n    auto llt = cov.llt();\n    lower_cholesky = llt.matrixL();\n\n    if (llt.info() == Eigen::NumericalIssue) {\n      throw std::runtime_error(\n          \"\\nERROR: In NormalMultivar::generate method: Input covariance matrix is not \"\n          \"positive semi-definite\\n\");\n    }\n  } catch (const std::exception& e) {\n    std::cerr << \"\\nERROR: In normal multivariate random number generation: \"\n              << e.what() << std::endl;\n    success = false;\n  }\n\n  random_numbers.resize(cov.rows(), cases);\n\n  // Generate random numbers based on distribution and generator type for\n  // requested number of cases\n  for (unsigned int i = 0; i < random_numbers.cols(); ++i) {\n    for (unsigned int j = 0; j < random_numbers.rows(); ++j) {\n      random_numbers(j, i) = distribution_(generator_);\n    }\n  }\n\n  // Transform from unit normal distribution based on covariance and mean values\n  for (unsigned int i = 0; i < random_numbers.cols(); ++i) {\n    random_numbers.col(i) = lower_cholesky * random_numbers.col(i) + means;\n  }\n\n  return success;\n}\n\nstd::string NormalMultiVar::name() const {\n  return \"NormalMultiVar\";\n}\n}  // namespace numeric_utils\n", "meta": {"hexsha": "750adb63d262a68d00ded47eac14c1af9d9dce29", "size": 2096, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/normal_multivar.cc", "max_stars_repo_name": "charlesxwang/smelt", "max_stars_repo_head_hexsha": "da1f66ec857dd8ff8e9de104fbb3ecbd0ec84367", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-05-07T03:14:27.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-19T07:10:52.000Z", "max_issues_repo_path": "src/normal_multivar.cc", "max_issues_repo_name": "charlesxwang/smelt", "max_issues_repo_head_hexsha": "da1f66ec857dd8ff8e9de104fbb3ecbd0ec84367", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-04-11T19:29:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-11T19:29:47.000Z", "max_forks_repo_path": "src/normal_multivar.cc", "max_forks_repo_name": "charlesxwang/smelt", "max_forks_repo_head_hexsha": "da1f66ec857dd8ff8e9de104fbb3ecbd0ec84367", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-03-25T20:08:22.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-04T13:02:31.000Z", "avg_line_length": 28.3243243243, "max_line_length": 88, "alphanum_fraction": 0.6875, "num_tokens": 516, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426303, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.47189119436577637}}
{"text": "//  (C) Copyright 2006 Eric Niebler, Olivier Gygi.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n// Test case for tail_quantile.hpp\n\n#include <boost/random.hpp>\n#include <boost/test/unit_test.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/accumulators/numeric/functional/vector.hpp>\n#include <boost/accumulators/numeric/functional/complex.hpp>\n#include <boost/accumulators/numeric/functional/valarray.hpp>\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/tail_quantile.hpp>\n\nusing namespace boost;\nusing namespace unit_test;\nusing namespace boost::accumulators;\n\n///////////////////////////////////////////////////////////////////////////////\n// test_stat\n//\nvoid test_stat()\n{\n    // tolerance in %\n    double epsilon = 1;\n\n    std::size_t n = 100000; // number of MC steps\n    std::size_t c =  10000; // cache size\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    accumulator_t_right acc0( right_tail_cache_size = c );\n    accumulator_t_right acc1( right_tail_cache_size = c );\n    accumulator_t_left  acc2( left_tail_cache_size = c );\n    accumulator_t_left  acc3( left_tail_cache_size = c );\n\n    // two random number generators\n    boost::lagged_fibonacci607 rng;\n    boost::normal_distribution<> mean_sigma(0,1);\n    boost::variate_generator<boost::lagged_fibonacci607&, boost::normal_distribution<> > normal(rng, mean_sigma);\n\n    for (std::size_t i = 0; i < n; ++i)\n    {\n        double sample1 = rng();\n        double sample2 = normal();\n        acc0(sample1);\n        acc1(sample2);\n        acc2(sample1);\n        acc3(sample2);\n    }\n\n    // check uniform distribution\n    BOOST_CHECK_CLOSE( quantile(acc0, quantile_probability = 0.95 ), 0.95,  epsilon );\n    BOOST_CHECK_CLOSE( quantile(acc0, quantile_probability = 0.975), 0.975, epsilon );\n    BOOST_CHECK_CLOSE( quantile(acc0, quantile_probability = 0.99 ), 0.99,  epsilon );\n    BOOST_CHECK_CLOSE( quantile(acc0, quantile_probability = 0.999), 0.999, epsilon );\n    BOOST_CHECK_CLOSE( quantile(acc2, quantile_probability  = 0.05 ), 0.05,  2 );\n    BOOST_CHECK_CLOSE( quantile(acc2, quantile_probability  = 0.025), 0.025, 2 );\n    BOOST_CHECK_CLOSE( quantile(acc2, quantile_probability  = 0.01 ), 0.01,  3 );\n    BOOST_CHECK_CLOSE( quantile(acc2, quantile_probability  = 0.001), 0.001, 20 );\n\n    // check standard normal distribution\n    BOOST_CHECK_CLOSE( quantile(acc1, quantile_probability = 0.975),  1.959963, epsilon );\n    BOOST_CHECK_CLOSE( quantile(acc1, quantile_probability = 0.999),  3.090232, epsilon );\n    BOOST_CHECK_CLOSE( quantile(acc3, quantile_probability  = 0.025), -1.959963, epsilon );\n    BOOST_CHECK_CLOSE( quantile(acc3, quantile_probability  = 0.001), -3.090232, epsilon );\n\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// init_unit_test_suite\n//\ntest_suite* init_unit_test_suite( int argc, char* argv[] )\n{\n    test_suite *test = BOOST_TEST_SUITE(\"tail_quantile test\");\n\n    test->add(BOOST_TEST_CASE(&test_stat));\n\n    return test;\n}\n\n", "meta": {"hexsha": "3335157d0d6b3e55f9f6be85a0fc8d475856dbb1", "size": 3369, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/accumulators/test/tail_quantile.cpp", "max_stars_repo_name": "mike-code/boost_1_38_0", "max_stars_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-06-25T23:20:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-14T19:38:34.000Z", "max_issues_repo_path": "libs/accumulators/test/tail_quantile.cpp", "max_issues_repo_name": "boost-cmake/vintage", "max_issues_repo_head_hexsha": "dcfb7da3177134eddaee6789d6f582259cb0d6ee", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/accumulators/test/tail_quantile.cpp", "max_forks_repo_name": "boost-cmake/vintage", "max_forks_repo_head_hexsha": "dcfb7da3177134eddaee6789d6f582259cb0d6ee", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-07-26T08:07:09.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-25T23:20:21.000Z", "avg_line_length": 39.1744186047, "max_line_length": 113, "alphanum_fraction": 0.6853665776, "num_tokens": 874, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.709019146082187, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.4717888308611992}}
{"text": "#include <iostream>\n#include <functional>\n#include <cmath>\n#include <boost/mpi.hpp>\n\nnamespace mpi = boost::mpi;\n\nint main (int argc, char* argv[]) \n{\n    mpi::environment env(argc, argv);\n    mpi::communicator world;\n    int myrank= world.rank();\n\n    float vec[2];\n    vec[0]= 2*myrank; vec[1]= vec[0]+1;\n\n    // Local accumulation\n    float local= std::abs(vec[0]) + std::abs(vec[1]);\n\n    // Global accumulation\n    float global= mpi::all_reduce(world, local, std::plus<float>());\n    std::cout << \"Hello, I am process \" << world.rank() << \" and I know too that |v|_1 is \" << global << \".\\n\";\n\n    return 0 ;\n}\n", "meta": {"hexsha": "ea81e372b3dd040bd18292df76d17d444fe60dd0", "size": 615, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "DMCpp/GottschlingRepo/c++03/boost_mpi_collective_onenorm.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++03/boost_mpi_collective_onenorm.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++03/boost_mpi_collective_onenorm.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": 23.6538461538, "max_line_length": 111, "alphanum_fraction": 0.6048780488, "num_tokens": 178, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191460821871, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.471788826156737}}
{"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\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include <iostream>\n#include <boost/numeric/mtl/mtl.hpp>\n\nusing namespace std;  \n\ntemplate <typename Matrix, typename Indirect>\nvoid check(const Indirect& I, const char* error)\n{\n    Matrix C(3, 2);\n    C= 4, 2,\n       2, 0,\n       5, 3;\n\n    C-= I;\n    if (one_norm(C) > 0.01) throw error;\n}\n\ntemplate <typename Matrix>\nvoid test(Matrix& A, const char* name)\n{\n    hessian_setup(A, 1.0);\n    std::cout << \"\\n\" << name << \"\\nA is: \\n\" << A;\n    \n    mtl::iset rows, cols;\n    rows= 2, 0, 3;\n    cols= 2, 0;\n\n    cout << \"rows = \" << rows << \", cols = \" << cols << \"\\n\";\n    cout << \"A[rows][cols] is: \\n\" << A[rows][cols] << \"\\n\";\n\n    mtl::mat::indirect<Matrix> B(A[rows][cols]);\n    cout << \"B is\\n\" << B;\n    check<Matrix>(B, \"Wrong value after copy constructor\");\n\n    Matrix D(3, 2), E;\n    D= B;\n    check<Matrix>(D, \"Wrong value after assignment\");\n\n    E= D + B;\n    E/= 2;\n    check<Matrix>(D, \"Wrong value after addition\");\n}\n\n\nint main(int, char**)\n{\n    using namespace mtl;\n    const unsigned size= 5; \n\n    dense2D<double>                                  dc(size, size-2);\n    dense2D<double, mat::parameters<col_major> >  dcc(size, size-2);\n    dense2D<float>                                   fc(size, size-2);\n    morton_dense<double,  morton_mask>               mdc(size, size-2);\n    morton_dense<double, doppled_32_col_mask>        mcc(size, size-2);\n    compressed2D<double>                             cc(size, size-2);\n    compressed2D<double, mat::parameters<col_major> >  ccc(size, size-2);\n\n    test(dc, \"dense2D\");\n    test(dcc, \"dense2D col-major\");\n    test(fc, \"dense2D float\");\n\n    test(mdc, \"pure Morton\");\n    test(mcc, \"Hybrid col-major\");\n    test(cc, \"Compressed\");\n    test(ccc, \"Compresse col-majord\");\n\n    return 0;\n}\n", "meta": {"hexsha": "20f21c4fe9a7eb08da152d5f4140a4b3df4769a6", "size": 2204, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/matrix_indirect_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/matrix_indirect_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/matrix_indirect_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": 27.2098765432, "max_line_length": 94, "alphanum_fraction": 0.5766787659, "num_tokens": 662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850933, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.47178882267858313}}
{"text": "#include <vector>\n#include <random>\n\n#include <algorithm>\n#include <numeric>\n#include <execution>\n\n#define BOOST_TEST_MODULE TestNORM2\n#include <boost/test/unit_test.hpp>\n#include <boost/test/tools/floating_point_comparison.hpp>\n\n#include <generate_randoms.hpp>\n#include <norm2.hpp>\n\nBOOST_AUTO_TEST_CASE( NORM2_FLOAT_SEQ )\n{\n    std::vector<float> lv{ 2.0, 3.0, 4.0, 5.0 };\n\n    BOOST_CHECK_EQUAL(norm_2<int>(std::execution::seq, lv.begin(), lv.end()), 7);\n    BOOST_CHECK_CLOSE(norm_2(std::execution::seq, lv.begin(), lv.end()), 7.348469, 0.001);\n}\n\nBOOST_AUTO_TEST_CASE( NORM2_FLOAT_PAR_10K )\n{\n    std::vector<float> A(10000);\n\n    generate_randoms(std::execution::seq, A.begin(), 10000);\n\n    BOOST_CHECK_CLOSE(\n        norm_2<float>(std::execution::seq, A.begin(), A.begin() + 10000)\n    ,   norm_2<float>(std::execution::par, A.begin(), A.begin() + 10000)\n    ,   0.00001);\n}\n", "meta": {"hexsha": "923fa9289a68ea739718986e9d7cb7647053acb0", "size": 883, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_norm2.cpp", "max_stars_repo_name": "arminms/scalable_allocators", "max_stars_repo_head_hexsha": "ab2a419e636a660df72465d2b85346d63dc7eda5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-01T19:00:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T19:00:10.000Z", "max_issues_repo_path": "test/test_norm2.cpp", "max_issues_repo_name": "arminms/scalable_allocators", "max_issues_repo_head_hexsha": "ab2a419e636a660df72465d2b85346d63dc7eda5", "max_issues_repo_licenses": ["MIT"], "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_norm2.cpp", "max_forks_repo_name": "arminms/scalable_allocators", "max_forks_repo_head_hexsha": "ab2a419e636a660df72465d2b85346d63dc7eda5", "max_forks_repo_licenses": ["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.9705882353, "max_line_length": 90, "alphanum_fraction": 0.6862967157, "num_tokens": 262, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.4717561159613078}}
{"text": "#define BOOST_TEST_MODULE shperical harmonic transforms\n#define BOOST_TEST_DYN_LINK\n#include <cmath>\n#include <random>\n#include <vector>\n#include <chrono>\n#include <iostream>\n#include <boost/test/unit_test.hpp>\n#include <blackpearl/core/sht.hpp>\n\ntemplate<typename real_scalar_type>\nvoid test_sht(){\n    using namespace blackpearl::core;\n    size_t l_max(6143);\n    size_t m_max(l_max);\n    size_t n_side(2048);\n    size_t num_pixels = 12*n_side*n_side;\n    size_t num_fields(6);\n    sht<real_scalar_type> sht_test(l_max,m_max,num_pixels,num_fields);\n}\n\nBOOST_AUTO_TEST_CASE(shp_data){\n    test_sht<float>();\n    test_sht<double>();\n}\n\n", "meta": {"hexsha": "6e0e21094a2903a707b9a385db1320dae47d7897", "size": 636, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/core/sht.cpp", "max_stars_repo_name": "tbs1980/bpl", "max_stars_repo_head_hexsha": "a0c546ea08bfb9fce29df391894919a9f741879d", "max_stars_repo_licenses": ["MIT"], "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/core/sht.cpp", "max_issues_repo_name": "tbs1980/bpl", "max_issues_repo_head_hexsha": "a0c546ea08bfb9fce29df391894919a9f741879d", "max_issues_repo_licenses": ["MIT"], "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/core/sht.cpp", "max_forks_repo_name": "tbs1980/bpl", "max_forks_repo_head_hexsha": "a0c546ea08bfb9fce29df391894919a9f741879d", "max_forks_repo_licenses": ["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.5555555556, "max_line_length": 70, "alphanum_fraction": 0.7452830189, "num_tokens": 164, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.6297746143530797, "lm_q1q2_score": 0.47175611075615076}}
{"text": "//\n// $Id$\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#ifndef DETERMINEBINWIDTH_H\n#define DETERMINEBINWIDTH_H\n\n\n#include <cmath>\n#include <boost/assert.hpp>\n#include <boost/range/algorithm_ext.hpp>\n#include <boost/bind.hpp>\n#include <algorithm>\n\n#include \"pwiz/utility/findmf/base/base/diff.hpp\"\n#include \"pwiz/utility/findmf/base/resample/utilities/determinebinwidth.hpp\"\n\n\nnamespace ralab\n{\n\tnamespace base\n\t{\n\t\tnamespace resample\n\t\t{\n\t\t\ttemplate<typename TReal>\n\t\t\tstruct SquareRoot{\n\t\t\t\tTReal operator()(TReal x) const{\n\t\t\t\t\treturn(sqrt(x));\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tstruct SamplingWith{\n\t\t\t\tstd::vector<double> diff_;\n\t\t\t\tstd::vector<double> summ_;\n\t\t\t\tstd::vector<double> am_;\n\n\t\t\t\t//expects a sorted sequence\n\t\t\t\ttemplate<typename TRealI>\n\t\t\t\tdouble operator()(TRealI begin, TRealI end)\n\t\t\t\t{\n\t\t\t\t\t//BOOST_ASSERT(!boost::range::is_sorted(begin,end));\n\t\t\t\t\ttypedef typename std::iterator_traits<TRealI>::value_type TReal;\n\t\t\t\t\tstd::size_t N = std::distance(begin,end);\n\t\t\t\t\tdouble am;\n\t\t\t\t\tif(N > 1){\n\t\t\t\t\t\tdiff_.resize(N-1);\n\t\t\t\t\t\tsumm_.resize(N-1);\n\t\t\t\t\t\tam_.resize(N-1);\n\t\t\t\t\t\tralab::base::base::diff(begin,end,diff_.begin(),1);\n\n\t\t\t\t\t\tutilities::summ( begin , end, summ_.begin(),1);\n\t\t\t\t\t\t//square the sum\n\t\t\t\t\t\t//std::transform(summ_.begin(),summ_.end(),summ_.begin(),boost::bind(sqrt,_1));\n\t\t\t\t\t\tstd::transform(summ_.begin(),summ_.end(),summ_.begin(),SquareRoot<TReal>());\n\t\t\t\t\t\tstd::transform(diff_.begin(),diff_.end(),summ_.begin(),am_.begin(),std::divides<double>());\n\t\t\t\t\t\tstd::sort(am_.begin(),am_.end());\n\t\t\t\t\t\tam = utilities::determine(am_.begin(),am_.end());\n\t\t\t\t\t}else{\n\t\t\t\t\t\tam = 0.;\n\t\t\t\t\t}\n\t\t\t\t\treturn am;\n\t\t\t\t}\n\t\t\t};\n\n\t\t}\n\t}\n}\n\n\n#endif // DETERMINEBINWIDTH_H\n", "meta": {"hexsha": "4f81c57b50cc108a7b655a4d7ee459f0ec9b5c42", "size": 2286, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pwiz/utility/findmf/base/resample/determinebinwidth.hpp", "max_stars_repo_name": "austinkeller/pwiz", "max_stars_repo_head_hexsha": "aa8e575cb40fd5e97cc7d922e4d8da44c9277cca", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pwiz/utility/findmf/base/resample/determinebinwidth.hpp", "max_issues_repo_name": "austinkeller/pwiz", "max_issues_repo_head_hexsha": "aa8e575cb40fd5e97cc7d922e4d8da44c9277cca", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pwiz/utility/findmf/base/resample/determinebinwidth.hpp", "max_forks_repo_name": "austinkeller/pwiz", "max_forks_repo_head_hexsha": "aa8e575cb40fd5e97cc7d922e4d8da44c9277cca", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.275862069, "max_line_length": 97, "alphanum_fraction": 0.665791776, "num_tokens": 613, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.47175610555099373}}
{"text": "#include <gtest/gtest.h>\n\n#include \"scheme/kinematics/Scene_io.hh\"\n#include \"scheme/actor/ActorConcept_io.hh\"\n#include \"scheme/objective/ObjectiveFunction.hh\"\n#include \"scheme/objective/ObjectiveVisitor.hh\"\n#include \"scheme/numeric/X1dim.hh\"\n\n#include \"scheme/io/dump_pdb_atom.hh\"\n\n#include <boost/foreach.hpp>\n\n\n\n#include <stdint.h>\n#include <fstream>\n\n#include <Eigen/Geometry>\n\nnamespace scheme { namespace kinematics { namespace test_eigen {\n\nusing std::cout;\nusing std::endl;\nusing boost::tie;\n\ntypedef Eigen::AngleAxis<double> AA;\ntypedef Eigen::Vector3d Vec;\n\nVec UX(1,0,0);\nVec UY(0,1,0);\nVec UZ(0,0,1);\n\nstruct Xform : Eigen::Transform<double,3,Eigen::AffineCompact>{\n\ttypedef Eigen::Transform<double,3,Eigen::AffineCompact> BASE;\n\tXform(){}\n\tXform(Vec t, double a, Vec ax) : BASE(AA(a,ax)) { translation() = t; }\n\ttemplate<class T> Xform(T const & t) : BASE(t) {}\n};\n\n// Xform inverse(Xform const & x){ return x.inverse(); }\nstd::ostream & operator<<(std::ostream & out,Xform const & x){\n\treturn out << \"t(\"<<x.translation().transpose()<<\")\";\n}\n\n\nTEST(Scene_eigen,eigen_transform){\n\t// Xform x(Xform::Identity());\n\tAA aa(0,Vec(1,0,0));\n\tXform x(aa);\n\t//cout << x << endl;\n\tEigen::Vector3d v(0,0,0);\n\tx*v;\n\tEigen::RowVector3d rv(0,0,0);\t\n\t// x*rv; // not allowed\n\tEigen::Vector3f vf(0,0,0);\n\t// x*vf // not allowed\n\tx*vf.cast<double>();\n\tEigen::RowVector4d v4(0,0,0,0);\n\t// x*v4; // not allowed\n}\n\ntypedef size_t Index;\ntypedef std::pair<size_t,size_t> Index2;\ntypedef std::pair<Index2,Index2> Index4;\n\n\nstruct Xactor : actor::ActorConcept<Xform,int> {\n\tXactor() : actor::ActorConcept<Xform,int>() {}\n\tXactor(Position const & p, int d) : actor::ActorConcept<Xform,int>(p,d) {}\n\tXactor(Xactor const & a,Position const & moveby){ position_ = moveby*a.position(); data_ = a.data_; }\n};\n\n////////////// test scores ////////////////////////\n\n\tstruct ScoreX {\n\t\ttypedef double Result;\n\t\ttypedef Xactor Interaction;\n\t\tstatic std::string name(){ return \"ScoreADI\"; }\n\t\ttemplate<class Config>\n\t\tResult operator()(Interaction const & a, Config const& ) const {\n\t\t\treturn a.data_;\n\t\t}\n\t};\n\tstd::ostream & operator<<(std::ostream & out,ScoreX const& s){ return out << s.name(); }\n\n\tdouble distance( Xform const & a, Xform const & b ){\n\t\treturn (a.translation()-b.translation()).norm();\n\t}\n\n\tstruct ScoreXX {\n\t\tstatic size_t ncalls;\n\t\ttypedef double Result;\n\t\ttypedef Xactor Actor1;\n\t\ttypedef Xactor Actor2;\n\t\ttypedef std::pair<Xactor,Xactor> Interaction;\n\t\tstatic std::string name(){ return \"ScoreADIADI\"; }\n\t\ttemplate<class Config>\n\t\tResult operator()(Actor1 const & a1, Actor2 const & a2, Config const& ) const {\n\t\t\t++ncalls;\n\t\t\t// cout << a.first << \" \" << a.second << endl;\n\t\t\treturn distance(a1.position(),a2.position());\n\t\t}\n\t\ttemplate<class Config>\n\t\tResult operator()(Interaction const & i, Config const& c) const {\n\t\t\treturn this->template operator()<Config>(i.first,i.second,c);\n\t\t}\n\t};\n\tsize_t ScoreXX::ncalls = 0;\n\tstd::ostream & operator<<(std::ostream & out,ScoreXX const& s){ return out << s.name(); }\n\n\n\tstruct Config {};\n\n/////////////////// tests //////////////////////////\n\nXform rel(Xform a,Xform b){ return a.inverse()*b; }\nXform rel2(Xform a,Xform b){ return b*a.inverse(); }\n\nTEST(Scene_eigen,relative_relations_preserved){\n\ttypedef\tobjective::ObjectiveFunction<\n\t\tm::vector<\n\t\t\tScoreX,\n\t\t\tScoreXX\n\t\t>,\n\t\tConfig\n\t> ObjFun;\n\ttypedef ObjFun::Results Results;\n\tObjFun score;\n\n\ttypedef m::vector< Xactor > Actors;\n\ttypedef Scene<impl::Conformation<Actors>,Xform> Scene;\n\n\tScene scene(2);\n\tscene.set_position(0,Xform(Vec(10, 0, 0),2,UX));\n\tscene.set_position(1,Xform(Vec( 0,10, 0),2,UY));\n\n\tscene.mutable_conformation_asym(0).add_actor( Xactor(Xform(Vec(1,3,1),1,UY),7) );\n\n\tscene.mutable_conformation_asym(1).add_actor( Xactor(Xform(Vec(3,4,7),2,UZ),7) );\n\n\tXactor x1,x2,a1,a2,r1,r2;\n\n\tx1 = scene.get_actor<Xactor>(0,0);\n\tx2 = scene.get_actor<Xactor>(1,0);\t\n\n\ttie(a1,a2) = scene.get_interaction_absolute<std::pair<Xactor,Xactor> >(\n\t\tstd::make_pair(std::make_pair(0,1),std::make_pair(0,0)));\n\ttie(r1,r2) = scene.get_interaction<std::pair<Xactor,Xactor> >(\n\t\tstd::make_pair(std::make_pair(0,1),std::make_pair(0,0)));\n\n\tASSERT_TRUE( x1.position().isApprox(a1.position()) );\n\tASSERT_TRUE( x2.position().isApprox(a2.position()) );\t\n\t// cout << x1 << \" \" << x2 << endl;\n\t// cout << a1 << \" \" << a2 << endl;\n\t// cout << r1 << \" \" << r2 << endl;\t\t\n\n\tXform xa = a1.position().inverse() * a2.position();\n\tXform xr = r1.position().inverse() * r2.position();\n\tASSERT_TRUE( xa.isApprox(xr) );\n\n\t/// why ~a*b captures the relation of a to b\n\t/// rather than b * ~a?  b * ~a  * a  == b\n\t/// ~(c*a)*c*b = ~a*~c*c*b = ~a*b\n\t/// ~(a*c)*b*c = ~c*~a*b*c\n\t/// b*c*~(a*c) = b*c*~c*a = b*~a\n\tXform a = Xform(Vec(10, 0, 0),2,UX);\n\tXform b = Xform(Vec( 0,10, 0),2,UY);\n\tXform c = Xform(Vec( 0,10,10),1,UZ);\t\n\tASSERT_TRUE ( rel (a,b).isApprox( rel (c*a  ,c*b  ) )  );\n\tASSERT_FALSE( rel (a,b).isApprox( rel (  a*c,  b*c) )  );\t\n\tASSERT_FALSE( rel2(a,b).isApprox( rel2(c*a  ,c*b  ) )  );\n\tASSERT_TRUE ( rel2(a,b).isApprox( rel2(  a*c,  b*c) )  );\n\n\t// xa = a1.position() * a2.position().inverse();\n\t// xr = r1.position() * r2.position().inverse();\n\t// ASSERT_TRUE( xa.isApprox(xr) );\n}\n\n// TEST(Scene_eigen,symmetry){\n// \ttypedef\tobjective::ObjectiveFunction<\n// \t\tm::vector<\n// \t\t\tScoreADI,\n// \t\t\tScoreADC,\n// \t\t\tScoreADIADI,\n// \t\t\tScoreADCADI\n// \t\t>,\n// \t\tConfig\n// \t> ObjFun;\n// \ttypedef ObjFun::Results Results;\n\n// \tObjFun score;\n\n// \ttypedef m::vector< ADI, ADC > Actors;\n// \ttypedef Conformation<Actors> Conformation;\n// \ttypedef Scene<Conformation,X1dim,size_t> Scene;\n\n// \tScene scene(2);\n// \tscene.add_symframe(10);\n\n// \tASSERT_EQ( score(scene).sum(), 0 );\n\n// \tscene.mutable_conformation_asym(0).add_actor( ADI(0,1) );\n// \tscene.mutable_conformation_asym(1).add_actor( ADI(1,2) );\n// \t// check that symmetric interactiosn are downweighted by 0.5: 40/2 = 20\n// \tASSERT_EQ( score(scene), Results(3,0,1+20,0) ); \n\n// \tscene.mutable_conformation_asym(1).add_actor( ADI(0,1) );\n// \tscene.mutable_conformation_asym(1).add_actor( ADI(1,2) );\n// \t// check that symmetric interactiosn are downweighted by 0.5: 160/2 = 80\n// \tASSERT_EQ( score(scene), Results(6,0,2+80,0) );\n\n// \t// scene.mutable_conformation_asym(1).add_actor( ADC(0,'1') );\n// \t// scene.mutable_conformation_asym(1).add_actor( ADC(0,'2') );\n// \t// ASSERT_EQ( score(scene), Results(20,3,16,80) );\n\n// }\n\n\n\n\n\n\n\n// TEST(Scene_eigen, performance){\n// // TEST(Scene_eigen,performance){\n// \t// TODO: speed up SceneIter iteration \n// \t//       iteration seems to take about 100 cycles per score call overhead\n// \t//       much of this is probably all the conditions for symmetry checks\n// \t//       could template out these and have both sym and asym scenes?\n// \t// FIX with visitation pattern, seems at least 10x faster\n\n// \tstd::cout << \"This test performs 301.934M score calls, should \n\t// take about a second when compiled with optimizations.\" << std::endl;\n\n// \ttypedef\tobjective::ObjectiveFunction<\n// \t\tm::vector<\n// \t\t\tScoreADI,\n// \t\t\tScoreADC,\n// \t\t\tScoreADIADI,\n// \t\t\tScoreADCADI\n// \t\t>,\n// \t\tConfig\n// \t> ObjFun;\n// \ttypedef ObjFun::Results Results;\n\n// \tObjFun score;\n\n// \ttypedef m::vector< ADI, ADC > Actors;\n// \ttypedef Conformation<Actors> Conformation;\n// \ttypedef Scene<Conformation,X1dim,uint32_t> Scene;\n\n// \tScoreADIADI obj;\n// \tConfig c;\n// \tobjective::ObjectiveVisitor<ScoreADIADI,Config> visitor(obj,c);\n\n// \tScene scene; {\n// \t\tScene::Index const NBOD = 10;\n// \t\tScene::Index const NSYM = 20;\n// \t\tScene::Index const NACT = 400;\n// \t\tfor(Scene::Index i = 0; i < NBOD; ++i) scene.add_body();\t\t\n// \t\tfor(Scene::Index i = 0; i < NSYM-1; ++i) scene.add_symframe(i+1);\n// \t\tfor(Scene::Index i = 0; i < NBOD; ++i){\n// \t\t\tfor(Scene::Index j = 0; j < NACT; ++j){\n// \t\t\t\tscene.mutable_conformation_asym(i).add_actor( ADI(j,i) );\n// \t\t\t}\n// \t\t}\n// \t}\n\n// \tcout << score(scene).get<ScoreADIADI>() << \" \" << (double)ScoreADIADI::ncalls/1000000.0 << \"M\" << endl;\n// \tScoreADIADI::ncalls = 0;\n// \treturn;\n\n\n// \tif(false)\n// \t{\n// \t\t\t// typedef ADI Actor1;\n// \t\t\t// typedef ADI Actor2;\n// \t\t\t// typedef Scene::Position Position;\n// \t\t\t// Scene::Index const NBOD = scene.bodies_.size();\n// \t\t\t// Scene::Index const NSYM = scene.symframes_.size()+1;\n// \t\t\t// for(Scene::Index i1 = 0; i1 < NBOD*NSYM; ++i1){\n// \t\t\t// \tConformation const & c1 = scene.conformation(i1);\n// \t\t\t// \tPosition     const & p1 =     scene.position(i1);\n// \t\t\t// \tScene::Index const NACT1 = c1.get<Actor1>().size();\n// \t\t\t// \tfor(Scene::Index i2 = 0; i2 < NBOD*NSYM; ++i2){\n// \t\t\t// \t\tif( i1 >= NBOD && i2 >= NBOD ) continue;\n// \t\t\t// \t\tif( i2 <= i1 ) continue;\n// \t\t\t// \t\tConformation const & c2 = scene.conformation(i2);\n// \t\t\t// \t\tPosition     const & p2 =     scene.position(i2);\n// \t\t\t// \t\tScene::Index const NACT2 = c2.get<Actor2>().size();\t\t\t\t\t\n// \t\t\t// \t\tfor(Scene::Index j1 = 0; j1 < NACT1; ++j1){\n// \t\t\t// \t\t\tActor1 a1( c1.get<Actor1>()[j1], p1 );\n// \t\t\t// \t\t\tfor(Scene::Index j2 = 0; j2 < NACT2; ++j2){\n// \t\t\t// \t\t\t\tActor2 a2( c2.get<Actor2>()[j2], p2 );\n// \t\t\t// \t\t\t\tvisitor( a1, a2, i1<NBOD&&i2<NBOD?1.0:0.5 );\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\t// cout << visitor.result_ << \" \" << (double)ScoreADIADI::ncalls/1000000.0 << endl;\n// \t\t\t// ScoreADIADI::ncalls = 0;\n\n// \t}\n\n// \tif(false)\n// \t\tperformance_test_helper(scene,visitor);\n// \tScoreADIADI::ncalls = 0;\n\n\n// \tscene.visit(visitor);\n// \tcout << visitor.result_ << \" \" << (double)ScoreADIADI::ncalls/1000000.0 << \"M\" << endl;\n// \tScoreADIADI::ncalls = 0;\n\n// }\n\n}\n}\n}\n", "meta": {"hexsha": "646911e23fd69a8341b8cc5180d6e336eac04662", "size": 9489, "ext": "cc", "lang": "C++", "max_stars_repo_path": "schemelib/scheme/kinematics/Scene_test_eigen.gtest.cc", "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/kinematics/Scene_test_eigen.gtest.cc", "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/kinematics/Scene_test_eigen.gtest.cc", "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": 29.7460815047, "max_line_length": 107, "alphanum_fraction": 0.6217725788, "num_tokens": 3133, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.4717561055509936}}
{"text": "#ifndef BACKTRACKING_LINE_SEARCH_HPP\n#define BACKTRACKING_LINE_SEARCH_HPP\n\n#include <functional>\n#include <Eigen/Core>\n\nnamespace mathtoolbox\n{\n    namespace optimization\n    {\n        // Procedure 3.1: Backtracking Line Search\n        //\n        // This algoritmh tries to find an appropriate step size that satisfies\n        // the Armijo condition (i.e., the safficient decreasing condition).\n        // This algorithm runs faster than the line search algorithm for the\n        // strong Wolfe conditions, but it does not guarantee the curvature\n        // condition, which is required to stabilize the overall optimization.\n        inline double RunBacktrackingLineSearch(const std::function<double(const Eigen::VectorXd&)>& f,\n                                                const Eigen::VectorXd& grad,\n                                                const Eigen::VectorXd& x,\n                                                const Eigen::VectorXd& p,\n                                                const double alpha_init,\n                                                const double rho,\n                                                const double c)\n        {\n            constexpr unsigned int num_max_iterations = 50;\n\n            unsigned counter = 0;\n            double alpha = alpha_init;\n            while (true)\n            {\n                // Equation 3.6a\n                const bool armijo_condition = f(x + alpha * p) <= f(x) + c * alpha * grad.transpose() * p;\n\n                if (armijo_condition || counter == num_max_iterations) { break; }\n\n                alpha *= rho;\n\n                ++ counter;\n            }\n            return alpha;\n        }\n    }\n}\n\n#endif /* BACKTRACKING_LINE_SEARCH_HPP */\n", "meta": {"hexsha": "be366297fa2fbacaa78e881226aeb60c3ec0f361", "size": 1727, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mathtoolbox/backtracking-line-search.hpp", "max_stars_repo_name": "josefgraus/self_similiarity", "max_stars_repo_head_hexsha": "c032daa3009f60fdc8a52c437a07c6e3ba2efe4b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-25T09:35:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-25T09:35:14.000Z", "max_issues_repo_path": "include/mathtoolbox/backtracking-line-search.hpp", "max_issues_repo_name": "josefgraus/self_similiarity", "max_issues_repo_head_hexsha": "c032daa3009f60fdc8a52c437a07c6e3ba2efe4b", "max_issues_repo_licenses": ["MIT"], "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/mathtoolbox/backtracking-line-search.hpp", "max_forks_repo_name": "josefgraus/self_similiarity", "max_forks_repo_head_hexsha": "c032daa3009f60fdc8a52c437a07c6e3ba2efe4b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-09-22T13:02:45.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-08T00:21:36.000Z", "avg_line_length": 36.7446808511, "max_line_length": 106, "alphanum_fraction": 0.5182397221, "num_tokens": 306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.4717560951406794}}
{"text": "//  ================================================================\n//  Created by Gregory Kramida on 10/23/18.\n//  Copyright (c) 2018 Gregory Kramida\n//  Licensed under the Apache License, Version 2.0 (the \"License\");\n//  you may not use this file except in compliance with the License.\n//  You may obtain a copy of the License at\n\n//  http://www.apache.org/licenses/LICENSE-2.0\n\n//  Unless required by applicable law or agreed to in writing, software\n//  distributed under the License is distributed on an \"AS IS\" BASIS,\n//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//  See the License for the specific language governing permissions and\n//  limitations under the License.\n//  ================================================================\n#pragma once\n\n#include <Eigen/Eigen>\n\nnamespace eig = Eigen;\n\nnamespace math{\n\n\t/**\n\t * @param tsdf_value_a\n\t * @param tsdf_value_b\n\t * @param tolerance\n\t * @return whether both SDF values is within tolerance of the truncation thresholds -1.0f and 1.0f\n\t */\n    inline bool are_both_SDF_values_truncated_tolerance(float tsdf_value_a, float tsdf_value_b, float tolerance = 10e-6f){\n        return (1.0f - std::abs(tsdf_value_a) < tolerance && 1.0f - std::abs(tsdf_value_b) < tolerance);\n    }\n    /**\n     * @param tsdf_value_a\n     * @param tsdf_value_b\n     * @return whether both SDF values have absolute value of 1.0f\n     */\n    inline bool are_both_SDF_values_truncated(float tsdf_value_a, float tsdf_value_b){\n    \treturn std::abs(tsdf_value_a) == 1.0 && std::abs(tsdf_value_b) == 1.0;\n    }\n}// namespace math\n", "meta": {"hexsha": "f223b8faa38748bd8dc1672cdea7af714ad4f3b6", "size": 1594, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/math/boolean_operations.hpp", "max_stars_repo_name": "Algomorph/LevelSetFusionExperimentsCPP", "max_stars_repo_head_hexsha": "f56962f0ad5c62e6706f818062782a2e1660afda", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2019-01-07T14:12:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T01:48:03.000Z", "max_issues_repo_path": "src/math/boolean_operations.hpp", "max_issues_repo_name": "Algomorph/LevelSetFusionExperimentsCPP", "max_issues_repo_head_hexsha": "f56962f0ad5c62e6706f818062782a2e1660afda", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2018-12-19T16:43:33.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-06T19:50:22.000Z", "max_forks_repo_path": "src/math/boolean_operations.hpp", "max_forks_repo_name": "Algomorph/LevelSetFusionExperimentsCPP", "max_forks_repo_head_hexsha": "f56962f0ad5c62e6706f818062782a2e1660afda", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-01-07T14:12:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-06T06:30:24.000Z", "avg_line_length": 37.9523809524, "max_line_length": 122, "alphanum_fraction": 0.6518193225, "num_tokens": 407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6224593452091671, "lm_q1q2_score": 0.47169618814680525}}
{"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_PREDICATES_FUNCTIONS_TABLE_ISMATRIX_HPP_INCLUDED\n#define NT2_PREDICATES_FUNCTIONS_TABLE_ISMATRIX_HPP_INCLUDED\n\n#include <nt2/predicates/functions/ismatrix.hpp>\n#include <nt2/include/functions/numel.hpp>\n#include <nt2/include/functions/extent.hpp>\n#include <boost/fusion/include/at.hpp>\n\nnamespace nt2 { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT  ( ismatrix_, tag::cpu_\n                            , (A0)\n                            , (unspecified_<A0>)\n                            )\n  {\n    typedef bool result_type;\n\n    BOOST_FORCEINLINE\n    result_type operator()(const A0& a0) const\n    {\n      typename meta::call<tag::extent_(A0 const&)>::type ex = nt2::extent(a0);\n      std::size_t nz = nt2::numel(ex);\n\n      // 4x0x1x1 is matrix but I do not know if 4x0x4x1 is ?!\n      return (nz == 0) ||((nz > 0)\n                          &&  (boost::fusion::at_c<0>(ex)*boost::fusion::at_c<1>(ex) == nz));\n    }\n  };\n} }\n\n#endif\n", "meta": {"hexsha": "54b835561aa94ebc3da3b1c989db28e7dd4e090e", "size": 1447, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/container/table/include/nt2/predicates/functions/table/ismatrix.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/container/table/include/nt2/predicates/functions/table/ismatrix.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/container/table/include/nt2/predicates/functions/table/ismatrix.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.175, "max_line_length": 93, "alphanum_fraction": 0.5383552177, "num_tokens": 356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6224593382055109, "lm_q1q2_score": 0.471696182839474}}
{"text": "/*\n(**************************************************************************)\n(*                                                                        *)\n(*                                Schifra                                 *)\n(*                Reed-Solomon Error Correcting Code Library              *)\n(*                                                                        *)\n(* Release Version 0.0.1                                                  *)\n(* http://www.schifra.com                                                 *)\n(* Copyright (c) 2000-2018 Arash Partow, All Rights Reserved.             *)\n(*                                                                        *)\n(* The Schifra Reed-Solomon error correcting code library and all its     *)\n(* components are supplied under the terms of the General Schifra License *)\n(* agreement. The contents of the Schifra Reed-Solomon error correcting   *)\n(* code library and all its components may not be copied or disclosed     *)\n(* except in accordance with the terms of that agreement.                 *)\n(*                                                                        *)\n(* URL: http://www.schifra.com/license.html                               *)\n(*                                                                        *)\n(**************************************************************************)\n*/\n\n\n/*\n   Description: This example will demonstrate the use of the Reed-Solomon\n                encoder and decoder capabilities in a threaded context. One\n                must note that the number of threads should not exceed the\n                architecture's ability to efficiently and productively run the\n                threads. A simple limiting strategy would be not to have more\n                threads than the number of available cores on the processor.\n*/\n\n\n#include <cstddef>\n#include <iostream>\n#include <string>\n#include <limits>\n\n#include <boost/bind.hpp>\n#include <boost/shared_ptr.hpp>\n#include <boost/thread/thread.hpp>\n\n#include \"schifra_galois_field.hpp\"\n#include \"schifra_galois_field_polynomial.hpp\"\n#include \"schifra_sequential_root_generator_polynomial_creator.hpp\"\n#include \"schifra_reed_solomon_encoder.hpp\"\n#include \"schifra_reed_solomon_decoder.hpp\"\n#include \"schifra_reed_solomon_block.hpp\"\n#include \"schifra_error_processes.hpp\"\n#include \"schifra_ecc_traits.hpp\"\n#include \"schifra_utilities.hpp\"\n\n\nconst std::size_t round_count = 1000;\n\ntemplate <typename Encoder, typename Decoder>\nclass process\n{\npublic:\n\n   process(const unsigned int& process_id,\n           const Encoder& encoder,\n           const Decoder& decoder,\n           const std::vector<std::string>& message_list)\n   : process_id_(process_id),\n     total_time_(0.0),\n     encoder_(encoder),\n     decoder_(decoder),\n     message_list_(message_list)\n   {}\n\n   process& operator=(const process& proc)\n   {\n      process_id_ = proc.process_id_;\n      total_time_ = proc.total_time_;\n      return *this;\n   }\n\n   double time() { return total_time_; }\n\n   inline void execute()\n   {\n      schifra::traits::equivalent_encoder_decoder<Encoder,Decoder>();\n      typedef schifra::reed_solomon::block<Encoder::trait::code_length,Encoder::trait::fec_length> block_type;\n\n      std::vector<block_type> block_list(message_list_.size());\n\n      for (std::size_t i = 0; i < message_list_.size(); ++i)\n      {\n         if (!encoder_.encode(message_list_[i],block_list[i]))\n         {\n            std::cout << \"[\" << process_id_ << \"] (0)Error - Critical encoding failure!\" << std::endl;\n            return;\n         }\n         schifra::corrupt_message_all_errors00(block_list[i],0,3);\n      }\n\n      schifra::utils::timer timer;\n      timer.start();\n\n      for (std::size_t k = 0; k < round_count; ++k)\n      {\n         for (std::size_t i = 0; i < message_list_.size(); ++i)\n         {\n            if (!decoder_.decode(block_list[i]))\n            {\n               std::cout << \"[\" << process_id_ << \"] (1)Error - Critical decoding failure!\" << std::endl;\n               return;\n            }\n            else if (!schifra::is_block_equivelent(block_list[i],message_list_[i]))\n            {\n               std::cout << \"[\" << process_id_ << \"] (2)Error - Error correction failed!\" << std::endl;\n               return;\n            }\n         }\n      }\n\n      timer.stop();\n      total_time_ = timer.time();\n   }\n\nprivate:\n\n   unsigned int process_id_;\n   double total_time_;\n   const Encoder& encoder_;\n   const Decoder& decoder_;\n   const std::vector<std::string>& message_list_;\n};\n\nvoid generate_messages(const std::size_t data_length, std::vector<std::string>& message_list)\n{\n   for (unsigned int c = 0; c < 256; ++c)\n   {\n      message_list.push_back(std::string(data_length,static_cast<unsigned char>(c)));\n   }\n}\n\nint main()\n{\n   /* Reed Solomon Code Parameters */\n   const std::size_t code_length = 255;\n   const std::size_t fec_length  =  32;\n   const std::size_t data_length = code_length - fec_length;\n\n   /* Finite Field Parameters */\n   const std::size_t field_descriptor                =   8;\n   const std::size_t generator_polynomial_index      = 120;\n   const std::size_t generator_polynomial_root_count = fec_length;\n\n   /* Instantiate Finite Field and Generator Polynomials */\n   schifra::galois::field field(field_descriptor,\n                                schifra::galois::primitive_polynomial_size06,\n                                schifra::galois::primitive_polynomial06);\n\n   schifra::galois::field_polynomial generator_polynomial(field);\n\n   if (\n        !schifra::make_sequential_root_generator_polynomial(field,\n                                                            generator_polynomial_index,\n                                                            generator_polynomial_root_count,\n                                                            generator_polynomial)\n      )\n   {\n      std::cout << \"Error - Failed to create sequential root generator!\" << std::endl;\n      return 1;\n   }\n\n   typedef schifra::reed_solomon::encoder<code_length,fec_length> encoder_type;\n   typedef schifra::reed_solomon::decoder<code_length,fec_length> decoder_type;\n   typedef process<encoder_type,decoder_type>                     process_type;\n   typedef boost::shared_ptr<process_type>                        process_ptr_type;\n\n   /* Instantiate Encoder and Decoder (Codec) */\n   encoder_type encoder(field,generator_polynomial);\n   decoder_type decoder(field,generator_polynomial_index);\n\n   std::vector<std::string> message_list;\n\n   generate_messages(data_length,message_list);\n\n   const unsigned int max_thread_count = 4; // number of functional cores.\n   std::vector<process_ptr_type> process_list;\n\n   boost::thread_group threads;\n\n   for (unsigned int i = 0; i < max_thread_count; ++i)\n   {\n      process_list.push_back(process_ptr_type(new process_type(i,encoder,decoder,message_list)));\n      threads.create_thread(boost::bind(&process_type::execute,process_list[i]));\n   }\n\n   threads.join_all();\n\n   double time = -1.0;\n\n   /* Determine the process with the longest running time. */\n   for (std::size_t i = 0; i < process_list.size(); ++i)\n   {\n      time = ((time < process_list[i]->time()) ? process_list[i]->time() : time);\n   }\n\n   double mbps = (max_thread_count * round_count * message_list.size() * data_length * 8.0) / (1048576.0 * time);\n\n   std::cout << \"Blocks decoded: \" << max_thread_count * round_count * message_list.size() << \"\\tTime: \" << time <<\"sec\\tRate: \" << mbps << \"Mbps\" << std::endl;\n\n   return 0;\n}\n\n", "meta": {"hexsha": "242456e88d12b108d3ee9086efaf8a6b3aec2d31", "size": 7527, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "soapy/src/3rd/schifra/schifra_reed_solomon_threads_example01.cpp", "max_stars_repo_name": "siglabsoss/s-modem", "max_stars_repo_head_hexsha": "0a259b4f3207dd043c198b76a4bc18c8529bcf44", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "soapy/src/3rd/schifra/schifra_reed_solomon_threads_example01.cpp", "max_issues_repo_name": "siglabsoss/s-modem", "max_issues_repo_head_hexsha": "0a259b4f3207dd043c198b76a4bc18c8529bcf44", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "soapy/src/3rd/schifra/schifra_reed_solomon_threads_example01.cpp", "max_forks_repo_name": "siglabsoss/s-modem", "max_forks_repo_head_hexsha": "0a259b4f3207dd043c198b76a4bc18c8529bcf44", "max_forks_repo_licenses": ["BSD-3-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.014354067, "max_line_length": 160, "alphanum_fraction": 0.5751295337, "num_tokens": 1598, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.47169617753214266}}
{"text": "#pragma once\n#include <Eigen/Dense>\n#include <vector>\n#include <autd3.hpp>\n\nstd::vector<Eigen::Vector3f> cornersWorkspaceAll(const Eigen::Vector3f& corner0, const Eigen::Vector3f& corner1);\n\nstd::vector<float> range2Points(const Eigen::Vector3f & pos_self, const Eigen::Quaternionf &quo_self, std::vector<Eigen::Vector3f> const &points);\n\nnamespace dynaman {\n\n\tbool isInsideWorkspace(const Eigen::Vector3f& pos, const Eigen::Vector3f& lowerbound, const Eigen::Vector3f& upperbound);\n\n\tEigen::Matrix3f RotForDeviceId(int deviceId, autd::GeometryPtr geo);\n\n\tstd::vector<Eigen::Matrix3f> RotsAutd(autd::GeometryPtr geo);\n\n\tstd::vector<Eigen::Matrix3f> RotsAutd(std::shared_ptr<autd::Controller> pAupa);\n\n\tEigen::Vector3f CenterForDeviceId(int deviceId, autd::GeometryPtr geo);\n\n\tEigen::Matrix3Xf CentersAutd(autd::GeometryPtr geo);\n\n\tEigen::Matrix3Xf DirectionsAutd(autd::GeometryPtr geo);\n}", "meta": {"hexsha": "e60f8e08bd35a22f7935852f0fdc609fd8b3adbb", "size": 888, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "inc/geometryUtil.hpp", "max_stars_repo_name": "shinolab/dynamic-manipulation", "max_stars_repo_head_hexsha": "d43bae688cecf87e15605ed6a9dbc80a782d72fc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "inc/geometryUtil.hpp", "max_issues_repo_name": "shinolab/dynamic-manipulation", "max_issues_repo_head_hexsha": "d43bae688cecf87e15605ed6a9dbc80a782d72fc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "inc/geometryUtil.hpp", "max_forks_repo_name": "shinolab/dynamic-manipulation", "max_forks_repo_head_hexsha": "d43bae688cecf87e15605ed6a9dbc80a782d72fc", "max_forks_repo_licenses": ["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.52, "max_line_length": 146, "alphanum_fraction": 0.7747747748, "num_tokens": 258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4716771667813955}}
{"text": "#ifndef UTIL_VIEWPORT_HPP\n#define UTIL_VIEWPORT_HPP\n\n#include \"util/coordinate.hpp\"\n#include \"util/web_mercator.hpp\"\n\n#include <boost/assert.hpp>\n\n#include <cmath>\n#include <tuple>\n\n// Port of https://github.com/mapbox/geo-viewport\n\nnamespace osrm\n{\nnamespace util\n{\nnamespace viewport\n{\n\nnamespace detail\n{\nstatic constexpr unsigned MAX_ZOOM = 18;\nstatic constexpr unsigned MIN_ZOOM = 1;\n// this is an upper bound to current display sizes\nstatic constexpr double VIEWPORT_WIDTH = 8 * web_mercator::TILE_SIZE;\nstatic constexpr double VIEWPORT_HEIGHT = 5 * web_mercator::TILE_SIZE;\nstatic double INV_LOG_2 = 1. / std::log(2);\n}\n\ninline unsigned getFittedZoom(util::Coordinate south_west, util::Coordinate north_east)\n{\n    const auto min_x = web_mercator::degreeToPixel(toFloating(south_west.lon), detail::MAX_ZOOM);\n    const auto max_y = web_mercator::degreeToPixel(toFloating(south_west.lat), detail::MAX_ZOOM);\n    const auto max_x = web_mercator::degreeToPixel(toFloating(north_east.lon), detail::MAX_ZOOM);\n    const auto min_y = web_mercator::degreeToPixel(toFloating(north_east.lat), detail::MAX_ZOOM);\n    const double width_ratio = (max_x - min_x) / detail::VIEWPORT_WIDTH;\n    const double height_ratio = (max_y - min_y) / detail::VIEWPORT_HEIGHT;\n    const auto zoom = detail::MAX_ZOOM -\n                      std::max(std::log(width_ratio), std::log(height_ratio)) * detail::INV_LOG_2;\n\n    if (std::isfinite(zoom))\n        return std::max<unsigned>(detail::MIN_ZOOM, zoom);\n    else\n        return detail::MIN_ZOOM;\n}\n}\n}\n}\n\n#endif\n", "meta": {"hexsha": "211aa5745817eb2a46e0427ab6ad64f750f86174", "size": 1545, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/util/viewport.hpp", "max_stars_repo_name": "jhermsmeier/osrm-backend", "max_stars_repo_head_hexsha": "7b11cd3a11c939c957eeff71af7feddaa86e7f82", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2019-02-21T02:02:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-09T13:49:31.000Z", "max_issues_repo_path": "include/util/viewport.hpp", "max_issues_repo_name": "serarca/osrm-backend", "max_issues_repo_head_hexsha": "3b4e2e83ef85983df1381dbeacd0ea5d4b9bbbcb", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 288.0, "max_issues_repo_issues_event_min_datetime": "2019-02-21T01:34:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-27T12:19:10.000Z", "max_forks_repo_path": "include/util/viewport.hpp", "max_forks_repo_name": "serarca/osrm-backend", "max_forks_repo_head_hexsha": "3b4e2e83ef85983df1381dbeacd0ea5d4b9bbbcb", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-06-21T20:51:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-13T09:22:24.000Z", "avg_line_length": 29.7115384615, "max_line_length": 98, "alphanum_fraction": 0.7352750809, "num_tokens": 410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891479496523, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.47167216102049236}}
{"text": "\n// Copyright 2005-2009 Daniel James.\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// A general purpose hash function for non-zero floating point values.\n\n#if !defined(BOOST_FUNCTIONAL_HASH_DETAIL_HASH_FLOAT_GENERIC_HEADER)\n#define BOOST_FUNCTIONAL_HASH_DETAIL_HASH_FLOAT_GENERIC_HEADER\n\n#include <boost/functional/hash/detail/float_functions.hpp>\n#include <boost/integer/static_log2.hpp>\n#include <boost/functional/hash/detail/limits.hpp>\n\n#if defined(_MSC_VER) && (_MSC_VER >= 1020)\n# pragma once\n#endif\n\n#if defined(BOOST_MSVC)\n#pragma warning(push)\n#if BOOST_MSVC >= 1400\n#pragma warning(disable:6294) // Ill-defined for-loop: initial condition does\n                              // not satisfy test. Loop body not executed \n#endif\n#endif\n\nnamespace boost\n{\n    namespace hash_detail\n    {\n        inline void hash_float_combine(std::size_t& seed, std::size_t value)\n        {\n            seed ^= value + (seed<<6) + (seed>>2);\n        }\n\n        template <class T>\n        inline std::size_t float_hash_impl2(T v)\n        {\n            boost::hash_detail::call_frexp<T> frexp;\n            boost::hash_detail::call_ldexp<T> ldexp;\n        \n            int exp = 0;\n\n            v = frexp(v, &exp);\n\n            // A postive value is easier to hash, so combine the\n            // sign with the exponent and use the absolute value.\n            if(v < 0) {\n                v = -v;\n                exp += limits<T>::max_exponent -\n                    limits<T>::min_exponent;\n            }\n\n            v = ldexp(v, limits<std::size_t>::digits);\n            std::size_t seed = static_cast<std::size_t>(v);\n            v -= seed;\n\n            // ceiling(digits(T) * log2(radix(T))/ digits(size_t)) - 1;\n            std::size_t const length\n                = (limits<T>::digits *\n                        boost::static_log2<limits<T>::radix>::value\n                        + limits<std::size_t>::digits - 1)\n                / limits<std::size_t>::digits;\n\n            for(std::size_t i = 0; i != length; ++i)\n            {\n                v = ldexp(v, limits<std::size_t>::digits);\n                std::size_t part = static_cast<std::size_t>(v);\n                v -= part;\n                hash_float_combine(seed, part);\n            }\n\n            hash_float_combine(seed, exp);\n\n            return seed;\n        }\n\n        template <class T>\n        inline std::size_t float_hash_impl(T v)\n        {\n            typedef BOOST_DEDUCED_TYPENAME select_hash_type<T>::type type;\n            return float_hash_impl2(static_cast<type>(v));\n        }\n    }\n}\n\n#if defined(BOOST_MSVC)\n#pragma warning(pop)\n#endif\n\n#endif\n", "meta": {"hexsha": "fdbf53fe57a7cc1ff0693e0a62e0f4fdf8e9db78", "size": 2720, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "external/boost_1_44_0/boost/functional/hash/detail/hash_float_generic.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/functional/hash/detail/hash_float_generic.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/functional/hash/detail/hash_float_generic.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-02-05T19:34:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-01T08:46:34.000Z", "avg_line_length": 29.5652173913, "max_line_length": 79, "alphanum_fraction": 0.5727941176, "num_tokens": 637, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891479496521, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.47167216102049225}}
{"text": "#include <possumwood_sdk/node_implementation.h>\n\n#define EIGEN_STACK_ALLOCATION_LIMIT 0\n\n#include <actions/traits.h>\n#include <tbb/task_group.h>\n\n#include <Eigen/Sparse>\n#include <mutex>\n#include <opencv2/opencv.hpp>\n\n#include \"frame.h\"\n\nnamespace {\n\nclass Triplets;\n\nclass Row {\n  public:\n\tRow() = default;\n\n\tvoid addValue(int64_t row, int64_t col, double value) {\n\t\tif(value != 0.0)\n\t\t\tm_values[(row << 32) + col] += value;\n\t}\n\n  private:\n\tRow(const Row&) = delete;\n\tRow& operator=(const Row&) = delete;\n\n\tstd::map<int64_t, double> m_values;\n\n\tfriend class Triplets;\n};\n\nclass Triplets {\n  public:\n\tTriplets(int rows, int cols) : m_rowCount(0), m_rows(rows), m_cols(cols) {\n\t}\n\n\tvoid addRow(const Row& r) {\n\t\tfor(auto& v : r.m_values) {\n\t\t\tint32_t row = v.first >> 32;\n\t\t\tint32_t col = v.first & 0xffffffff;\n\n\t\t\tassert(row < m_rows);\n\t\t\tassert(col < m_cols);\n\n\t\t\tm_triplets.push_back(Eigen::Triplet<double>(m_rowCount, row * m_cols + col, v.second));\n\t\t}\n\n\t\t++m_rowCount;\n\t}\n\n\tstd::size_t rows() const {\n\t\treturn m_rowCount;\n\t}\n\n\tconst std::vector<Eigen::Triplet<double>>& triplets() const {\n\t\treturn m_triplets;\n\t}\n\n  private:\n\tstd::vector<Eigen::Triplet<double>> m_triplets;\n\n\tint m_rowCount, m_rows, m_cols;\n\n\tfriend class Row;\n};\n\nstatic const cv::Mat kernel = (cv::Mat_<double>(3, 3) << 0.0, -1.0, 0.0, -1.0, 4.0, -1.0, 0.0, -1.0, 0.0);\n\n// static const cv::Mat kernel = (cv::Mat_<double>(3,3) <<\n// \t-1.0, -1.0, -1.0,\n// \t-1.0,  8.0, -1.0,\n// \t-1.0, -1.0, -1.0\n// );\n\n// static const cv::Mat kernel = (cv::Mat_<double>(3,3) <<\n// \t-1.0, -2.0, -1.0,\n// \t-2.0, 12.0, -2.0,\n// \t-1.0, -2.0, -1.0\n// );\n\n// static const cv::Mat kernel = (cv::Mat_<double>(5,5) <<\n// \t 0.0,  0.0,  1.0,  0.0,  0.0,\n// \t 0.0,  2.0, -8.0,  2.0,  0.0,\n// \t 1.0, -8.0, 20.0, -8.0,  1.0,\n// \t 0.0,  2.0, -8.0,  2.0,  0.0,\n// \t 0.0,  0.0,  1.0,  0.0,  0.0\n// );\n\nfloat buildMatrices(const cv::Mat& image, const cv::Mat& mask, Eigen::SparseMatrix<double>& A, Eigen::VectorXd& b,\n                    const cv::Rect2i& roi) {\n\tTriplets triplets(roi.height, roi.width);\n\tstd::vector<double> values;\n\n\tstd::size_t validCtr = 0, interpolatedCtr = 0;\n\n\tfor(int y = roi.y; y < roi.y + roi.height; ++y)\n\t\tfor(int x = roi.x; x < roi.x + roi.width; ++x) {\n\t\t\tRow row;\n\n\t\t\t// masked and/or edge\n\t\t\tif(mask.at<unsigned char>(y, x) > 128) {\n\t\t\t\tvalues.push_back(0.0f);\n\n\t\t\t\t// convolution\n\t\t\t\tfor(int yi = 0; yi < kernel.rows; ++yi)\n\t\t\t\t\tfor(int xi = 0; xi < kernel.cols; ++xi) {\n\t\t\t\t\t\tint ypos = y + yi - kernel.rows / 2;\n\t\t\t\t\t\tint xpos = x + xi - kernel.cols / 2;\n\n\t\t\t\t\t\t// handling of edges - \"clip\" (or \"mirror\", commented out for now)\n\t\t\t\t\t\tif(ypos < roi.y)\n\t\t\t\t\t\t\t// ypos = -ypos;\n\t\t\t\t\t\t\typos = roi.y;\n\t\t\t\t\t\tif(ypos >= roi.y + roi.height)\n\t\t\t\t\t\t\t// ypos = (image.rows-1) - (ypos-image.rows);\n\t\t\t\t\t\t\typos = roi.y + roi.height - 1;\n\n\t\t\t\t\t\tif(xpos < roi.x)\n\t\t\t\t\t\t\t// xpos = -xpos;\n\t\t\t\t\t\t\txpos = roi.x;\n\t\t\t\t\t\tif(xpos >= roi.x + roi.width)\n\t\t\t\t\t\t\t// xpos = (image.cols-1) - (xpos-image.cols);\n\t\t\t\t\t\t\txpos = roi.x + roi.width - 1;\n\n\t\t\t\t\t\trow.addValue(ypos - roi.y, xpos - roi.x, kernel.at<double>(yi, xi));\n\t\t\t\t\t}\n\n\t\t\t\t++interpolatedCtr;\n\t\t\t}\n\n\t\t\t// non-masked\n\t\t\tif(mask.at<unsigned char>(y, x) <= 128) {\n\t\t\t\tvalues.push_back(image.at<float>(y, x));\n\t\t\t\trow.addValue(y - roi.y, x - roi.x, 1);\n\n\t\t\t\t++validCtr;\n\t\t\t}\n\n\t\t\ttriplets.addRow(row);\n\t\t}\n\n\t// initialise the sparse matrix\n\tA = Eigen::SparseMatrix<double>(triplets.rows(), roi.height * roi.width);\n\tA.setFromTriplets(triplets.triplets().begin(), triplets.triplets().end());\n\n\t// and the \"b\" vector\n\tassert(values.size() == triplets.rows());\n\tb = Eigen::VectorXd(values.size());\n\tfor(std::size_t i = 0; i < values.size(); ++i)\n\t\tb[i] = values[i];\n\n\treturn (float)validCtr / ((float)validCtr + (float)interpolatedCtr);\n}\n\ndependency_graph::InAttr<possumwood::opencv::Frame> a_inFrame, a_inMask;\ndependency_graph::InAttr<unsigned> a_mosaic;\ndependency_graph::OutAttr<possumwood::opencv::Frame> a_outFrame;\n\ndependency_graph::State compute(dependency_graph::Values& data) {\n\tdependency_graph::State state;\n\n\tconst cv::Mat& input = *data.get(a_inFrame);\n\tconst cv::Mat& mask = *data.get(a_inMask);\n\tconst unsigned mosaic = data.get(a_mosaic);\n\n\tif(input.depth() != CV_32F)\n\t\tthrow std::runtime_error(\"Laplacian inpainting - input image type has to be CV_32F.\");\n\tif(mask.type() != CV_8UC1 && mask.type() != CV_8UC3)\n\t\tthrow std::runtime_error(\"Laplacian inpainting - mask image type has to be CV_8UC1 or CV_8UC3.\");\n\tif(input.empty() || mask.empty())\n\t\tthrow std::runtime_error(\"Laplacian inpainting - empty input image and/or mask.\");\n\tif(input.size != mask.size)\n\t\tthrow std::runtime_error(\"Laplacian inpainting - input and mask image size have to match.\");\n\tif(input.cols % mosaic != 0 || input.rows % mosaic != 0)\n\t\tthrow std::runtime_error(\n\t\t    \"Laplacian inpainting - image size is not divisible by mosaic count - invalid mosaic?.\");\n\n\tstd::vector<std::vector<float>> x(input.channels(), std::vector<float>(input.rows * input.cols, 0.0f));\n\n\ttbb::task_group tasks;\n\tstd::mutex solve_mutex;\n\n\t// split the inputs and masks per channel\n\tstd::vector<cv::Mat> inputs, masks;\n\tcv::split(input, inputs);\n\tcv::split(mask, masks);\n\n\tassert((int)inputs.size() == input.channels());\n\tassert((int)masks.size() == mask.channels());\n\n\tconst unsigned mosaic_rows = input.rows / mosaic;\n\tconst unsigned mosaic_cols = input.cols / mosaic;\n\n\tfor(unsigned yi = 0; yi < mosaic; ++yi) {\n\t\tfor(unsigned xi = 0; xi < mosaic; ++xi) {\n\t\t\tcv::Rect2i roi;\n\t\t\troi.y = yi * mosaic_rows;\n\t\t\troi.x = xi * mosaic_cols;\n\t\t\troi.height = mosaic_rows;\n\t\t\troi.width = mosaic_cols;\n\n\t\t\tfor(int channel = 0; channel < input.channels(); ++channel) {\n\t\t\t\ttasks.run([channel, &inputs, &masks, &x, &state, &solve_mutex, roi]() {\n\t\t\t\t\tcv::Mat inTile = inputs[channel];\n\n\t\t\t\t\tcv::Mat inMask;\n\t\t\t\t\tif(masks.size() == 1)\n\t\t\t\t\t\tinMask = masks[0];\n\t\t\t\t\telse\n\t\t\t\t\t\tinMask = masks[channel];\n\n\t\t\t\t\tEigen::SparseMatrix<double> A;\n\t\t\t\t\tEigen::VectorXd b, tmp;\n\n\t\t\t\t\tconst float ratio = buildMatrices(inTile, inMask, A, b, roi);\n\n\t\t\t\t\tif(ratio > 0.003) {\n\t\t\t\t\t\tconst char* stage = \"solver construction\";\n\n\t\t\t\t\t\tEigen::SparseLU<Eigen::SparseMatrix<double> /*, Eigen::NaturalOrdering<int>*/> chol(A);\n\n\t\t\t\t\t\tif(chol.info() == Eigen::Success) {\n\t\t\t\t\t\t\tstage = \"analyze pattern\";\n\n\t\t\t\t\t\t\tchol.analyzePattern(A);\n\n\t\t\t\t\t\t\tif(chol.info() == Eigen::Success) {\n\t\t\t\t\t\t\t\tstage = \"factorize\";\n\n\t\t\t\t\t\t\t\tchol.factorize(A);\n\n\t\t\t\t\t\t\t\tif(chol.info() == Eigen::Success) {\n\t\t\t\t\t\t\t\t\tstage = \"solve\";\n\n\t\t\t\t\t\t\t\t\ttmp = chol.solve(b);\n\n\t\t\t\t\t\t\t\t\tassert(tmp.size() == roi.height * roi.width);\n\t\t\t\t\t\t\t\t\tfor(int i = 0; i < tmp.size(); ++i) {\n\t\t\t\t\t\t\t\t\t\tconst int row = i / roi.width;\n\t\t\t\t\t\t\t\t\t\tconst int col = i % roi.width;\n\t\t\t\t\t\t\t\t\t\tconst int index = (row + roi.y) * masks[0].cols + col + roi.x;\n\n\t\t\t\t\t\t\t\t\t\tassert((std::size_t)index < x[channel].size());\n\n\t\t\t\t\t\t\t\t\t\tx[channel][index] = tmp[i];\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tstd::lock_guard<std::mutex> guard(solve_mutex);\n\n\t\t\t\t\t\tif(chol.info() == Eigen::NumericalIssue)\n\t\t\t\t\t\t\tstate.addWarning(\"Decomposition failed - Eigen::NumericalIssue at stage \" +\n\t\t\t\t\t\t\t                 std::string(stage));\n\t\t\t\t\t\telse if(chol.info() == Eigen::NoConvergence)\n\t\t\t\t\t\t\tstate.addWarning(\"Decomposition failed - Eigen::NoConvergence at stage \" +\n\t\t\t\t\t\t\t                 std::string(stage));\n\t\t\t\t\t\telse if(chol.info() == Eigen::InvalidInput)\n\t\t\t\t\t\t\tstate.addWarning(\"Decomposition failed - Eigen::InvalidInput at stage \" +\n\t\t\t\t\t\t\t                 std::string(stage));\n\t\t\t\t\t\telse if(chol.info() != Eigen::Success)\n\t\t\t\t\t\t\tstate.addWarning(\"Decomposition failed - unknown error at stage \" + std::string(stage));\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\n\ttasks.wait();\n\n\tcv::Mat result = input.clone();\n\tfor(int yi = 0; yi < result.rows; ++yi)\n\t\tfor(int xi = 0; xi < result.cols; ++xi)\n\t\t\tfor(int c = 0; c < input.channels(); ++c)\n\t\t\t\tresult.ptr<float>(yi, xi)[c] = x[c][yi * result.cols + xi];\n\n\tdata.set(a_outFrame, possumwood::opencv::Frame(result));\n\n\treturn state;\n}\n\nvoid init(possumwood::Metadata& meta) {\n\tmeta.addAttribute(a_inFrame, \"frame\", possumwood::opencv::Frame(), possumwood::AttrFlags::kVertical);\n\tmeta.addAttribute(a_inMask, \"mask\", possumwood::opencv::Frame(), possumwood::AttrFlags::kVertical);\n\tmeta.addAttribute(a_mosaic, \"mosaic\", 1u);\n\tmeta.addAttribute(a_outFrame, \"out_frame\", possumwood::opencv::Frame(), possumwood::AttrFlags::kVertical);\n\n\tmeta.addInfluence(a_inFrame, a_outFrame);\n\tmeta.addInfluence(a_inMask, a_outFrame);\n\tmeta.addInfluence(a_mosaic, a_outFrame);\n\n\tmeta.setCompute(compute);\n}\n\npossumwood::NodeImplementation s_impl(\"opencv/inpaint_laplacian\", init);\n\n}  // namespace\n", "meta": {"hexsha": "b7aa50750c1eb140bb257efbec8d4dad66646272", "size": 8594, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/plugins/opencv/nodes/inpaint_laplacian.cpp", "max_stars_repo_name": "LIUJUN-liujun/possumwood", "max_stars_repo_head_hexsha": "745e48eb44450b0b7f078ece81548812ab1ccc63", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-10-06T08:40:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-06T08:40:10.000Z", "max_issues_repo_path": "src/plugins/opencv/nodes/inpaint_laplacian.cpp", "max_issues_repo_name": "LIUJUN-liujun/possumwood", "max_issues_repo_head_hexsha": "745e48eb44450b0b7f078ece81548812ab1ccc63", "max_issues_repo_licenses": ["MIT"], "max_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/opencv/nodes/inpaint_laplacian.cpp", "max_forks_repo_name": "LIUJUN-liujun/possumwood", "max_forks_repo_head_hexsha": "745e48eb44450b0b7f078ece81548812ab1ccc63", "max_forks_repo_licenses": ["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.3630363036, "max_line_length": 114, "alphanum_fraction": 0.6133348848, "num_tokens": 2665, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189121808099, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.47167214602364776}}
{"text": "\n#include <librealsense2/rs.hpp> \n#include <Eigen/Core>   \n#include <iostream>\n#include \"D435iCalibWriter.h\"\n\n\nint main(int argc, char *argv[]) try\n{\n    //ensure an output directory is supplied\n    if (argc != 2){ \n        std::cout<<\"usage: \"<< argv[0] <<\" <camera name>\\n\"<< \n        \"Intrisics file will be saved as <camera name>_intr.yaml\\n\";\n        return 0;\n    }\n\n    std::string cam_name(argv[1]);\n\n    ark::Recorder rec(cam_name);\n\n\n    //Set up realsense pipeline\n    rs2::config cfg;\n    cfg.enable_stream(RS2_STREAM_DEPTH,-1,640,480,RS2_FORMAT_Z16,30);\n    cfg.enable_stream(RS2_STREAM_INFRARED, 1, 640, 480, RS2_FORMAT_Y8, 30);\n    cfg.enable_stream(RS2_STREAM_INFRARED, 2, 640, 480, RS2_FORMAT_Y8, 30);\n    //rs2::config cfg2;\n    cfg.enable_stream(RS2_STREAM_ACCEL, RS2_FORMAT_MOTION_XYZ32F,250);\n    cfg.enable_stream(RS2_STREAM_GYRO, RS2_FORMAT_MOTION_XYZ32F,200);\n\n    cfg.enable_stream(RS2_STREAM_COLOR,-1,640,480,RS2_FORMAT_BGR8,30);\n\n    rs2::pipeline pipe;\n    //rs2::pipeline motion_pipe;\n\n    // Start streaming with default recommended configuration\n    rs2::pipeline_profile selection = pipe.start(cfg);\n\n    // Get image streams\n    auto depth_stream = selection.get_stream(RS2_STREAM_DEPTH)\n                             .as<rs2::video_stream_profile>();\n\n    auto ir1_stream = selection.get_stream(RS2_STREAM_INFRARED,1)\n                             .as<rs2::video_stream_profile>();\n\n    auto ir2_stream = selection.get_stream(RS2_STREAM_INFRARED,2)\n                             .as<rs2::video_stream_profile>();\n    auto color_stream = selection.get_stream(RS2_STREAM_COLOR)\n                             .as<rs2::video_stream_profile>();\n    // Get motion streams\n    auto gyro_stream =  selection.get_stream(RS2_STREAM_GYRO)\n                             .as<rs2::motion_stream_profile>();\n    auto accel_stream =  selection.get_stream(RS2_STREAM_ACCEL)\n                             .as<rs2::motion_stream_profile>();\n\n    //get extrinsics between cameras and imu\n    rs2_extrinsics extrinsics = ir1_stream.get_extrinsics_to(accel_stream);\n    Eigen::Vector3f T_12(extrinsics.translation[0], extrinsics.translation[1], extrinsics.translation[2]);\n    Eigen::Map<Eigen::Matrix3f>R_12(extrinsics.rotation);\n\n    Eigen::Matrix4f tf_ir1 = Eigen::Matrix4f::Identity();\n    tf_ir1.block<3,3>(0,0)=R_12;\n    tf_ir1.block<3,1>(0,3)=T_12;\n\n    rs2_extrinsics extrinsics2 = ir2_stream.get_extrinsics_to(accel_stream);\n    Eigen::Vector3f T2_12(extrinsics2.translation[0], extrinsics2.translation[1], extrinsics2.translation[2]);\n    Eigen::Map<Eigen::Matrix3f>R2_12(extrinsics2.rotation);\n    Eigen::Matrix4f tf_ir2 = Eigen::Matrix4f::Identity();\n    tf_ir2.block<3,3>(0,0)=R2_12;\n    tf_ir2.block<3,1>(0,3)=T2_12;\n\n    rs2_extrinsics extrinsics3 = depth_stream.get_extrinsics_to(accel_stream);\n    Eigen::Vector3f T3_12(extrinsics3.translation[0], extrinsics3.translation[1], extrinsics3.translation[2]);\n    Eigen::Map<Eigen::Matrix3f>R3_12(extrinsics3.rotation);\n    Eigen::Matrix4f tf_depth = Eigen::Matrix4f::Identity();\n    tf_depth.block<3,3>(0,0)=R3_12;\n    tf_depth.block<3,1>(0,3)=T3_12;\n\n    rs2_extrinsics extrinsics4 = color_stream.get_extrinsics_to(accel_stream);\n    Eigen::Vector3f T4_12(extrinsics4.translation[0], extrinsics4.translation[1], extrinsics4.translation[2]);\n    Eigen::Map<Eigen::Matrix3f>R4_12(extrinsics4.rotation);\n    Eigen::Matrix4f tf_color = Eigen::Matrix4f::Identity();\n    tf_color.block<3,3>(0,0)=R4_12;\n    tf_color.block<3,1>(0,3)=T4_12;\n\n    //get camera intrinsics\n    rs2_intrinsics rs_intr_ir1 = ir1_stream.get_intrinsics();\n    rs2_intrinsics rs_intr_ir2 = ir2_stream.get_intrinsics();\n    rs2_intrinsics rs_intr_depth = depth_stream.get_intrinsics();\n    rs2_intrinsics rs_intr_color = color_stream.get_intrinsics();\n\n\n    //compose calibration for slam cameras\n    ark::CameraCalibration ir1_calib(tf_ir1.transpose(),rs_intr_ir1);\n    ark::CameraCalibration ir2_calib(tf_ir2.transpose(),rs_intr_ir2);\n\n    std::vector<ark::CameraCalibration> camera_calibs;\n    camera_calibs.push_back(ir1_calib);\n    camera_calibs.push_back(ir2_calib);\n\n    //Write intrinsics to file\n    rec.write_camera_intrinsics_and_extrinsics(camera_calibs);\n\n    //compose calibration for additional cameras\n    ark::CameraCalibration depth_calib(tf_depth.transpose(),rs_intr_depth);\n    ark::CameraCalibration color_calib(tf_color.transpose(),rs_intr_color);\n\n    std::vector<ark::CameraCalibration> add_camera_calibs;\n    add_camera_calibs.push_back(depth_calib); \n    add_camera_calibs.push_back(color_calib); \n    rec.write_additional_intrinsics_and_extrinsics(add_camera_calibs);\n\n    rec.write_camera_params();\n    rec.write_imu_intrinsics();\n    rec.write_additional_parameters();\n\n    Eigen::Matrix3f cam_mat_ir1;\n    cam_mat_ir1(0,0) = rs_intr_ir1.fx;\n    cam_mat_ir1(0,2) = rs_intr_ir1.ppx;\n    cam_mat_ir1(1,1) = rs_intr_ir1.fy;\n    cam_mat_ir1(1,2) = rs_intr_ir1.ppy;\n    cam_mat_ir1(2,2) = 1;\n\n    Eigen::Matrix3f cam_mat_ir2;\n    cam_mat_ir2(0,0) = rs_intr_ir2.fx;\n    cam_mat_ir2(0,2) = rs_intr_ir2.ppx;\n    cam_mat_ir2(1,1) = rs_intr_ir2.fy;\n    cam_mat_ir2(1,2) = rs_intr_ir2.ppy;\n    cam_mat_ir2(2,2) = 1;\n\n    std::cout << \"IR1: \" << cam_mat_ir1.inverse() << std::endl;\n    std::cout << \"IR2: \" << cam_mat_ir2.inverse() <<  std::endl;\n\n\n    std::cout << \"----------------Camera 1----------------\\n\";\n    std::cout << \"Principal Point         : \" << rs_intr_ir1.ppx << \", \" << rs_intr_ir1.ppy << std::endl;\n    std::cout << \"Focal Length            : \" << rs_intr_ir1.fx << \", \" << rs_intr_ir1.fy << std::endl;\n    std::cout << \"Distortion Model        : \" << rs_intr_ir1.model << std::endl;\n    std::cout << \"Distortion Coefficients : [\" << rs_intr_ir1.coeffs[0] << \",\" << rs_intr_ir1.coeffs[1] << \",\" <<\n        rs_intr_ir1.coeffs[2] << \",\" << rs_intr_ir1.coeffs[3] << \",\" << rs_intr_ir1.coeffs[4] << \"]\" << std::endl;\n\n    std::cout << \"----------------Camera 2----------------\\n\";\n    std::cout << \"Principal Point         : \" << rs_intr_ir2.ppx << \", \" << rs_intr_ir2.ppy << std::endl;\n    std::cout << \"Focal Length            : \" << rs_intr_ir2.fx << \", \" << rs_intr_ir2.fy << std::endl;\n    std::cout << \"Distortion Model        : \" << rs_intr_ir2.model << std::endl;\n    std::cout << \"Distortion Coefficients : [\" << rs_intr_ir2.coeffs[0] << \",\" << rs_intr_ir2.coeffs[1] << \",\" <<\n        rs_intr_ir2.coeffs[2] << \",\" << rs_intr_ir2.coeffs[3] << \",\" << rs_intr_ir2.coeffs[4] << \"]\" << std::endl;\n    std::cout << \"----------------Depth----------------\\n\";\n    std::cout << \"Principal Point         : \" << rs_intr_depth.ppx << \", \" << rs_intr_depth.ppy << std::endl;\n    std::cout << \"Focal Length            : \" << rs_intr_depth.fx << \", \" << rs_intr_depth.fy << std::endl;\n    std::cout << \"Distortion Model        : \" << rs_intr_depth.model << std::endl;\n    std::cout << \"Distortion Coefficients : [\" << rs_intr_depth.coeffs[0] << \",\" << rs_intr_depth.coeffs[1] << \",\" <<\n        rs_intr_depth.coeffs[2] << \",\" << rs_intr_depth.coeffs[3] << \",\" << rs_intr_depth.coeffs[4] << \"]\" << std::endl;\n    std::cout << \"----------------Color----------------\\n\";\n    std::cout << \"Principal Point         : \" << rs_intr_color.ppx << \", \" << rs_intr_color.ppy << std::endl;\n    std::cout << \"Focal Length            : \" << rs_intr_color.fx << \", \" << rs_intr_color.fy << std::endl;\n    std::cout << \"Distortion Model        : \" << rs_intr_color.model << std::endl;\n    std::cout << \"Distortion Coefficients : [\" << rs_intr_color.coeffs[0] << \",\" << rs_intr_color.coeffs[1] << \",\" <<\n        rs_intr_color.coeffs[2] << \",\" << rs_intr_color.coeffs[3] << \",\" << rs_intr_color.coeffs[4] << \"]\" << std::endl;\n  \n\n    std::cout << \"---------------Extrinsics Cam1---------------\\n\";\n    std::cout << \"Translation Vector : [\" << extrinsics.translation[0] << \",\" << extrinsics.translation[1] << \",\" << extrinsics.translation[2] << \"]\\n\";\n    std::cout << \"Rotation Matrix    : [\" << extrinsics.rotation[0] << \",\" << extrinsics.rotation[3] << \",\" << extrinsics.rotation[6] << \"]\\n\";\n    std::cout << \"                   : [\" << extrinsics.rotation[1] << \",\" << extrinsics.rotation[4] << \",\" << extrinsics.rotation[7] << \"]\\n\";\n    std::cout << \"                   : [\" << extrinsics.rotation[2] << \",\" << extrinsics.rotation[5] << \",\" << extrinsics.rotation[8] << \"]\" << std::endl;\n\n    std::cout << \"---------------Extrinsics Cam2---------------\\n\";\n    std::cout << \"Translation Vector : [\" << extrinsics2.translation[0] << \",\" << extrinsics2.translation[1] << \",\" << extrinsics2.translation[2] << \"]\\n\";\n    std::cout << \"Rotation Matrix    : [\" << extrinsics2.rotation[0] << \",\" << extrinsics2.rotation[3] << \",\" << extrinsics2.rotation[6] << \"]\\n\";\n    std::cout << \"                   : [\" << extrinsics2.rotation[1] << \",\" << extrinsics2.rotation[4] << \",\" << extrinsics2.rotation[7] << \"]\\n\";\n    std::cout << \"                   : [\" << extrinsics2.rotation[2] << \",\" << extrinsics2.rotation[5] << \",\" << extrinsics2.rotation[8] << \"]\" << std::endl;\n    std::cout << \"---------------Extrinsics Depth---------------\\n\";\n    std::cout << \"Translation Vector : [\" << extrinsics3.translation[0] << \",\" << extrinsics3.translation[1] << \",\" << extrinsics3.translation[2] << \"]\\n\";\n    std::cout << \"Rotation Matrix    : [\" << extrinsics3.rotation[0] << \",\" << extrinsics3.rotation[3] << \",\" << extrinsics3.rotation[6] << \"]\\n\";\n    std::cout << \"                   : [\" << extrinsics3.rotation[1] << \",\" << extrinsics3.rotation[4] << \",\" << extrinsics3.rotation[7] << \"]\\n\";\n    std::cout << \"                   : [\" << extrinsics3.rotation[2] << \",\" << extrinsics3.rotation[5] << \",\" << extrinsics3.rotation[8] << \"]\" << std::endl;\n    std::cout << \"---------------Extrinsics Color---------------\\n\";\n    std::cout << \"Translation Vector : [\" << extrinsics4.translation[0] << \",\" << extrinsics4.translation[1] << \",\" << extrinsics4.translation[2] << \"]\\n\";\n    std::cout << \"Rotation Matrix    : [\" << extrinsics4.rotation[0] << \",\" << extrinsics4.rotation[3] << \",\" << extrinsics4.rotation[6] << \"]\\n\";\n    std::cout << \"                   : [\" << extrinsics4.rotation[1] << \",\" << extrinsics4.rotation[4] << \",\" << extrinsics4.rotation[7] << \"]\\n\";\n    std::cout << \"                   : [\" << extrinsics4.rotation[2] << \",\" << extrinsics4.rotation[5] << \",\" << extrinsics4.rotation[8] << \"]\" << std::endl;\n\n\n    std::cout << \"Closing Files...\" << std::flush << std::endl;\n    rec.close();\n    std::cout << \"Terminated.\" << std::flush << std::endl;\n\treturn 0;\n}catch(...)\n{\n    printf(\"Unhandled excepton occured'n\");\n    return EXIT_FAILURE;\n}\n", "meta": {"hexsha": "50381b49c47bf70df20d4356f995d48d4e814611", "size": 10606, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "D435iCalibWriter.cpp", "max_stars_repo_name": "lidiawu/OpenARK", "max_stars_repo_head_hexsha": "e98e29a3f1f7d5db7067d7ae6943f1775a936fc9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 280.0, "max_stars_repo_stars_event_min_datetime": "2017-04-12T06:14:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T15:09:47.000Z", "max_issues_repo_path": "D435iCalibWriter.cpp", "max_issues_repo_name": "lidiawu/OpenARK", "max_issues_repo_head_hexsha": "e98e29a3f1f7d5db7067d7ae6943f1775a936fc9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 33.0, "max_issues_repo_issues_event_min_datetime": "2017-06-02T04:32:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-18T20:18:35.000Z", "max_forks_repo_path": "D435iCalibWriter.cpp", "max_forks_repo_name": "lidiawu/OpenARK", "max_forks_repo_head_hexsha": "e98e29a3f1f7d5db7067d7ae6943f1775a936fc9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 122.0, "max_forks_repo_forks_event_min_datetime": "2017-03-29T17:49:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-12T21:01:12.000Z", "avg_line_length": 54.6701030928, "max_line_length": 157, "alphanum_fraction": 0.6064491797, "num_tokens": 3072, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267626522814, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.47165414888155643}}
{"text": "#ifndef MATHEVAL_IMPLEMENTATION\n#error \"Do not include ast.hpp directly!\"\n#endif\n\n#pragma once\n\n#include <boost/variant.hpp>\n\n#include <list>\n#include <string>\n\nnamespace matheval {\n\nnamespace ast {\n\nstruct nil {};\nstruct unary_op;\nstruct binary_op;\nstruct ternary_op;\nstruct expression;\n\n// clang-format off\ntypedef boost::variant<\n        nil // can't happen!\n        , double\n        , std::string\n        , boost::recursive_wrapper<unary_op>\n        , boost::recursive_wrapper<binary_op>\n        , boost::recursive_wrapper<ternary_op>\n        , boost::recursive_wrapper<expression>\n        >\noperand;\n// clang-format on\n\nstruct unary_op {\n    double (*op)(double);\n    operand rhs;\n    unary_op() {}\n    unary_op(double (*op)(double), operand const &rhs) : op(op), rhs(rhs) {}\n};\n\nstruct binary_op {\n    double (*op)(double, double);\n    operand lhs;\n    operand rhs;\n    binary_op() {}\n    binary_op(double (*op)(double, double), operand const &lhs,\n              operand const &rhs)\n        : op(op), lhs(lhs), rhs(rhs) {}\n};\n\nstruct ternary_op {\n    double (*op)(double, double, double);\n    operand p1, p2, p3;\n    ternary_op() {}\n    ternary_op(double (*op_)(double, double, double),\n\t       operand const &p1_,\n               operand const &p2_,\n\t       operand const &p3_)\n      : op(op_), p1(p1_), p2(p2_), p3(p3_) {}\n};\n\nstruct operation {\n    double (*op)(double, double);\n    operand rhs;\n    operation() {}\n    operation(double (*op)(double, double), operand const &rhs)\n        : op(op), rhs(rhs) {}\n};\n\nstruct expression {\n    operand lhs;\n    std::list<operation> rhs;\n    expression() {}\n    expression(operand const &lhs, std::list<operation> const &rhs)\n        : lhs(lhs), rhs(rhs) {}\n};\n\n} // namespace ast\n\n} // namespace matheval\n", "meta": {"hexsha": "1dd6ad280c23f19f55e13c9141d43d6fc3eff624", "size": 1756, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/qi/ast.hpp", "max_stars_repo_name": "doj/boost_matheval", "max_stars_repo_head_hexsha": "61c6b3cb450127612e4f531ded37f3dca54a1419", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/qi/ast.hpp", "max_issues_repo_name": "doj/boost_matheval", "max_issues_repo_head_hexsha": "61c6b3cb450127612e4f531ded37f3dca54a1419", "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/qi/ast.hpp", "max_forks_repo_name": "doj/boost_matheval", "max_forks_repo_head_hexsha": "61c6b3cb450127612e4f531ded37f3dca54a1419", "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.4146341463, "max_line_length": 76, "alphanum_fraction": 0.6138952164, "num_tokens": 440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754607093178, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.47158120616036264}}
{"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    testDecisionTree.cpp\n * @brief    Develop DecisionTree\n * @author  Frank Dellaert\n * @date  Mar 6, 2011\n */\n\n#include <gtsam/base/Testable.h>\n#include <gtsam/discrete/DiscreteKey.h> // make sure we have traits\n// headers first to make sure no missing headers\n//#define DT_NO_PRUNING\n#include <gtsam/discrete/AlgebraicDecisionTree.h>\n#include <gtsam/discrete/DecisionTree-inl.h> // for convert only\n#define DISABLE_TIMING\n\n#include <boost/timer.hpp>\n#include <boost/tokenizer.hpp>\n#include <boost/assign/std/map.hpp>\n#include <boost/assign/std/vector.hpp>\nusing namespace boost::assign;\n\n#include <CppUnitLite/TestHarness.h>\n#include <gtsam/discrete/Signature.h>\n\nusing namespace std;\nusing namespace gtsam;\n\n/* ******************************************************************************** */\ntypedef AlgebraicDecisionTree<Key> ADT;\n\n// traits\nnamespace gtsam {\ntemplate<> struct traits<ADT> : public Testable<ADT> {};\n}\n\n#define DISABLE_DOT\n\ntemplate<typename T>\nvoid dot(const T&f, const string& filename) {\n#ifndef DISABLE_DOT\n  f.dot(filename);\n#endif\n}\n\n/** I can't get this to work !\n class Mul: boost::function<double(const double&, const double&)> {\n inline double operator()(const double& a, const double& b) {\n return a * b;\n }\n };\n\n // If second argument of binary op is Leaf\n template<typename L>\n typename DecisionTree<L, double>::Node::Ptr DecisionTree<L, double>::Choice::apply_fC_op_gL(\n Cache& cache, const Leaf& gL, Mul op) const {\n Ptr h(new Choice(label(), cardinality()));\n for(const NodePtr& branch: branches_)\n h->push_back(branch->apply_f_op_g(cache, gL, op));\n return Unique(cache, h);\n }\n */\n\n/* ******************************************************************************** */\n// instrumented operators\n/* ******************************************************************************** */\nsize_t muls = 0, adds = 0;\nboost::timer timer;\nvoid resetCounts() {\n  muls = 0;\n  adds = 0;\n  timer.restart();\n}\nvoid printCounts(const string& s) {\n#ifndef DISABLE_TIMING\n  cout << boost::format(\"%s: %3d muls, %3d adds, %g ms.\") % s % muls % adds\n  % (1000 * timer.elapsed()) << endl;\n#endif\n  resetCounts();\n}\ndouble mul(const double& a, const double& b) {\n  muls++;\n  return a * b;\n}\ndouble add_(const double& a, const double& b) {\n  adds++;\n  return a + b;\n}\n\n/* ******************************************************************************** */\n// test ADT\nTEST(ADT, example3)\n{\n  // Create labels\n  DiscreteKey A(0,2), B(1,2), C(2,2), D(3,2), E(4,2);\n\n  // Literals\n  ADT a(A, 0.5, 0.5);\n  ADT notb(B, 1, 0);\n  ADT c(C, 0.1, 0.9);\n  ADT d(D, 0.1, 0.9);\n  ADT note(E, 0.9, 0.1);\n\n  ADT cnotb = c * notb;\n  dot(cnotb, \"ADT-cnotb\");\n\n//  a.print(\"a: \");\n//  cnotb.print(\"cnotb: \");\n  ADT acnotb = a * cnotb;\n//  acnotb.print(\"acnotb: \");\n//  acnotb.printCache(\"acnotb Cache:\");\n\n  dot(acnotb, \"ADT-acnotb\");\n\n\n  ADT big = apply(apply(d, note, &mul), acnotb, &add_);\n  dot(big, \"ADT-big\");\n}\n\n/* ******************************************************************************** */\n// Asia Bayes Network\n/* ******************************************************************************** */\n\n/** Convert Signature into CPT */\nADT create(const Signature& signature) {\n  ADT p(signature.discreteKeysParentsFirst(), signature.cpt());\n  static size_t count = 0;\n  const DiscreteKey& key = signature.key();\n  string dotfile = (boost::format(\"CPT-%03d-%d\") % ++count % key.first).str();\n  dot(p, dotfile);\n  return p;\n}\n\n/* ************************************************************************* */\n// test Asia Joint\nTEST(ADT, joint)\n{\n  DiscreteKey A(0, 2), S(1, 2), T(2, 2), L(3, 2), B(4, 2), E(5, 2), X(6, 2), D(7, 2);\n\n  resetCounts();\n  ADT pA = create(A % \"99/1\");\n  ADT pS = create(S % \"50/50\");\n  ADT pT = create(T | A = \"99/1 95/5\");\n  ADT pL = create(L | S = \"99/1 90/10\");\n  ADT pB = create(B | S = \"70/30 40/60\");\n  ADT pE = create((E | T, L) = \"F T T T\");\n  ADT pX = create(X | E = \"95/5 2/98\");\n  ADT pD = create((D | E, B) = \"9/1 2/8 3/7 1/9\");\n  printCounts(\"Asia CPTs\");\n\n  // Create joint\n  resetCounts();\n  ADT joint = pA;\n  dot(joint, \"Asia-A\");\n  joint = apply(joint, pS, &mul);\n  dot(joint, \"Asia-AS\");\n  joint = apply(joint, pT, &mul);\n  dot(joint, \"Asia-AST\");\n  joint = apply(joint, pL, &mul);\n  dot(joint, \"Asia-ASTL\");\n  joint = apply(joint, pB, &mul);\n  dot(joint, \"Asia-ASTLB\");\n  joint = apply(joint, pE, &mul);\n  dot(joint, \"Asia-ASTLBE\");\n  joint = apply(joint, pX, &mul);\n  dot(joint, \"Asia-ASTLBEX\");\n  joint = apply(joint, pD, &mul);\n  dot(joint, \"Asia-ASTLBEXD\");\n  EXPECT_LONGS_EQUAL(346, (long)muls);\n  printCounts(\"Asia joint\");\n\n  ADT pASTL = pA;\n  pASTL = apply(pASTL, pS, &mul);\n  pASTL = apply(pASTL, pT, &mul);\n  pASTL = apply(pASTL, pL, &mul);\n\n  // test combine\n  ADT fAa = pASTL.combine(L, &add_).combine(T, &add_).combine(S, &add_);\n  EXPECT(assert_equal(pA, fAa));\n  ADT fAb = pASTL.combine(S, &add_).combine(T, &add_).combine(L, &add_);\n  EXPECT(assert_equal(pA, fAb));\n}\n\n/* ************************************************************************* */\n// test Inference with joint\nTEST(ADT, inference)\n{\n  DiscreteKey A(0,2), D(1,2),//\n      B(2,2), L(3,2), E(4,2), S(5,2), T(6,2), X(7,2);\n\n  resetCounts();\n  ADT pA = create(A % \"99/1\");\n  ADT pS = create(S % \"50/50\");\n  ADT pT = create(T | A = \"99/1 95/5\");\n  ADT pL = create(L | S = \"99/1 90/10\");\n  ADT pB = create(B | S = \"70/30 40/60\");\n  ADT pE = create((E | T, L) = \"F T T T\");\n  ADT pX = create(X | E = \"95/5 2/98\");\n  ADT pD = create((D | E, B) = \"9/1 2/8 3/7 1/9\");\n  //  printCounts(\"Inference CPTs\");\n\n  // Create joint\n  resetCounts();\n  ADT joint = pA;\n  dot(joint, \"Joint-Product-A\");\n  joint = apply(joint, pS, &mul);\n  dot(joint, \"Joint-Product-AS\");\n  joint = apply(joint, pT, &mul);\n  dot(joint, \"Joint-Product-AST\");\n  joint = apply(joint, pL, &mul);\n  dot(joint, \"Joint-Product-ASTL\");\n  joint = apply(joint, pB, &mul);\n  dot(joint, \"Joint-Product-ASTLB\");\n  joint = apply(joint, pE, &mul);\n  dot(joint, \"Joint-Product-ASTLBE\");\n  joint = apply(joint, pX, &mul);\n  dot(joint, \"Joint-Product-ASTLBEX\");\n  joint = apply(joint, pD, &mul);\n  dot(joint, \"Joint-Product-ASTLBEXD\");\n  EXPECT_LONGS_EQUAL(370, (long)muls); // different ordering\n  printCounts(\"Asia product\");\n\n  ADT marginal = joint;\n  marginal = marginal.combine(X, &add_);\n  dot(marginal, \"Joint-Sum-ADBLEST\");\n  marginal = marginal.combine(T, &add_);\n  dot(marginal, \"Joint-Sum-ADBLES\");\n  marginal = marginal.combine(S, &add_);\n  dot(marginal, \"Joint-Sum-ADBLE\");\n  marginal = marginal.combine(E, &add_);\n  dot(marginal, \"Joint-Sum-ADBL\");\n  EXPECT_LONGS_EQUAL(161, (long)adds);\n  printCounts(\"Asia sum\");\n}\n\n/* ************************************************************************* */\nTEST(ADT, factor_graph)\n{\n  DiscreteKey B(0,2), L(1,2), E(2,2), S(3,2), T(4,2), X(5,2);\n\n  resetCounts();\n  ADT pS = create(S % \"50/50\");\n  ADT pT = create(T % \"95/5\");\n  ADT pL = create(L | S = \"99/1 90/10\");\n  ADT pE = create((E | T, L) = \"F T T T\");\n  ADT pX = create(X | E = \"95/5 2/98\");\n  ADT pD = create(B | E = \"1/8 7/9\");\n  ADT pB = create(B | S = \"70/30 40/60\");\n  //  printCounts(\"Create CPTs\");\n\n  // Create joint\n  resetCounts();\n  ADT fg = pS;\n  fg = apply(fg, pT, &mul);\n  fg = apply(fg, pL, &mul);\n  fg = apply(fg, pB, &mul);\n  fg = apply(fg, pE, &mul);\n  fg = apply(fg, pX, &mul);\n  fg = apply(fg, pD, &mul);\n  dot(fg, \"FactorGraph\");\n  EXPECT_LONGS_EQUAL(158, (long)muls);\n  printCounts(\"Asia FG\");\n\n  fg = fg.combine(X, &add_);\n  dot(fg, \"Marginalized-6X\");\n  fg = fg.combine(T, &add_);\n  dot(fg, \"Marginalized-5T\");\n  fg = fg.combine(S, &add_);\n  dot(fg, \"Marginalized-4S\");\n  fg = fg.combine(E, &add_);\n  dot(fg, \"Marginalized-3E\");\n  fg = fg.combine(L, &add_);\n  dot(fg, \"Marginalized-2L\");\n  EXPECT(adds = 54);\n  printCounts(\"marginalize\");\n\n  // BLESTX\n\n  // Eliminate X\n  ADT fE = pX;\n  dot(fE, \"Eliminate-01-fEX\");\n  fE = fE.combine(X, &add_);\n  dot(fE, \"Eliminate-02-fE\");\n  printCounts(\"Eliminate X\");\n\n  // Eliminate T\n  ADT fLE = pT;\n  fLE = apply(fLE, pE, &mul);\n  dot(fLE, \"Eliminate-03-fLET\");\n  fLE = fLE.combine(T, &add_);\n  dot(fLE, \"Eliminate-04-fLE\");\n  printCounts(\"Eliminate T\");\n\n  // Eliminate S\n  ADT fBL = pS;\n  fBL = apply(fBL, pL, &mul);\n  fBL = apply(fBL, pB, &mul);\n  dot(fBL, \"Eliminate-05-fBLS\");\n  fBL = fBL.combine(S, &add_);\n  dot(fBL, \"Eliminate-06-fBL\");\n  printCounts(\"Eliminate S\");\n\n  // Eliminate E\n  ADT fBL2 = fE;\n  fBL2 = apply(fBL2, fLE, &mul);\n  fBL2 = apply(fBL2, pD, &mul);\n  dot(fBL2, \"Eliminate-07-fBLE\");\n  fBL2 = fBL2.combine(E, &add_);\n  dot(fBL2, \"Eliminate-08-fBL2\");\n  printCounts(\"Eliminate E\");\n\n  // Eliminate L\n  ADT fB = fBL;\n  fB = apply(fB, fBL2, &mul);\n  dot(fB, \"Eliminate-09-fBL\");\n  fB = fB.combine(L, &add_);\n  dot(fB, \"Eliminate-10-fB\");\n  printCounts(\"Eliminate L\");\n}\n\n/* ************************************************************************* */\n// test equality\nTEST(ADT, equality_noparser)\n{\n  DiscreteKey A(0,2), B(1,2);\n  Signature::Table tableA, tableB;\n  Signature::Row rA, rB;\n  rA += 80, 20; rB += 60, 40;\n  tableA += rA; tableB += rB;\n\n  // Check straight equality\n  ADT pA1 = create(A % tableA);\n  ADT pA2 = create(A % tableA);\n  EXPECT(pA1 == pA2); // should be equal\n\n  // Check equality after apply\n  ADT pB = create(B % tableB);\n  ADT pAB1 = apply(pA1, pB, &mul);\n  ADT pAB2 = apply(pB, pA1, &mul);\n  EXPECT(pAB2 == pAB1);\n}\n\n/* ************************************************************************* */\n// test equality\nTEST(ADT, equality_parser)\n{\n  DiscreteKey A(0,2), B(1,2);\n  // Check straight equality\n  ADT pA1 = create(A % \"80/20\");\n  ADT pA2 = create(A % \"80/20\");\n  EXPECT(pA1 == pA2); // should be equal\n\n  // Check equality after apply\n  ADT pB = create(B % \"60/40\");\n  ADT pAB1 = apply(pA1, pB, &mul);\n  ADT pAB2 = apply(pB, pA1, &mul);\n  EXPECT(pAB2 == pAB1);\n}\n\n/* ******************************************************************************** */\n// Factor graph construction\n// test constructor from strings\nTEST(ADT, constructor)\n{\n  DiscreteKey v0(0,2), v1(1,3);\n  Assignment<Key> x00, x01, x02, x10, x11, x12;\n  x00[0] = 0, x00[1] = 0;\n  x01[0] = 0, x01[1] = 1;\n  x02[0] = 0, x02[1] = 2;\n  x10[0] = 1, x10[1] = 0;\n  x11[0] = 1, x11[1] = 1;\n  x12[0] = 1, x12[1] = 2;\n\n  ADT f1(v0 & v1, \"0 1 2 3 4 5\");\n  EXPECT_DOUBLES_EQUAL(0, f1(x00), 1e-9);\n  EXPECT_DOUBLES_EQUAL(1, f1(x01), 1e-9);\n  EXPECT_DOUBLES_EQUAL(2, f1(x02), 1e-9);\n  EXPECT_DOUBLES_EQUAL(3, f1(x10), 1e-9);\n  EXPECT_DOUBLES_EQUAL(4, f1(x11), 1e-9);\n  EXPECT_DOUBLES_EQUAL(5, f1(x12), 1e-9);\n\n  ADT f2(v1 & v0, \"0 1 2 3 4 5\");\n  EXPECT_DOUBLES_EQUAL(0, f2(x00), 1e-9);\n  EXPECT_DOUBLES_EQUAL(2, f2(x01), 1e-9);\n  EXPECT_DOUBLES_EQUAL(4, f2(x02), 1e-9);\n  EXPECT_DOUBLES_EQUAL(1, f2(x10), 1e-9);\n  EXPECT_DOUBLES_EQUAL(3, f2(x11), 1e-9);\n  EXPECT_DOUBLES_EQUAL(5, f2(x12), 1e-9);\n\n  DiscreteKey z0(0,5), z1(1,4), z2(2,3), z3(3,2);\n  vector<double> table(5 * 4 * 3 * 2);\n  double x = 0;\n  for(double& t: table)\n  t = x++;\n  ADT f3(z0 & z1 & z2 & z3, table);\n  Assignment<Key> assignment;\n  assignment[0] = 0;\n  assignment[1] = 0;\n  assignment[2] = 0;\n  assignment[3] = 1;\n  EXPECT_DOUBLES_EQUAL(1, f3(assignment), 1e-9);\n}\n\n/* ************************************************************************* */\n// test conversion to integer indices\n// Only works if DiscreteKeys are binary, as size_t has binary cardinality!\nTEST(ADT, conversion)\n{\n  DiscreteKey X(0,2), Y(1,2);\n  ADT fDiscreteKey(X & Y, \"0.2 0.5 0.3 0.6\");\n  dot(fDiscreteKey, \"conversion-f1\");\n\n  std::map<Key, Key> keyMap;\n  keyMap[0] = 5;\n  keyMap[1] = 2;\n\n  AlgebraicDecisionTree<Key> fIndexKey(fDiscreteKey, keyMap);\n  //  f1.print(\"f1\");\n  //  f2.print(\"f2\");\n  dot(fIndexKey, \"conversion-f2\");\n\n  Assignment<Key> x00, x01, x02, x10, x11, x12;\n  x00[5] = 0, x00[2] = 0;\n  x01[5] = 0, x01[2] = 1;\n  x10[5] = 1, x10[2] = 0;\n  x11[5] = 1, x11[2] = 1;\n  EXPECT_DOUBLES_EQUAL(0.2, fIndexKey(x00), 1e-9);\n  EXPECT_DOUBLES_EQUAL(0.5, fIndexKey(x01), 1e-9);\n  EXPECT_DOUBLES_EQUAL(0.3, fIndexKey(x10), 1e-9);\n  EXPECT_DOUBLES_EQUAL(0.6, fIndexKey(x11), 1e-9);\n}\n\n/* ******************************************************************************** */\n// test operations in elimination\nTEST(ADT, elimination)\n{\n  DiscreteKey A(0,2), B(1,3), C(2,2);\n  ADT f1(A & B & C, \"1 2  3 4  5 6    1 8  3 3  5 5\");\n  dot(f1, \"elimination-f1\");\n\n  {\n    // sum out lower key\n    ADT actualSum = f1.sum(C);\n    ADT expectedSum(A & B, \"3  7  11    9  6  10\");\n    CHECK(assert_equal(expectedSum,actualSum));\n\n    // normalize\n    ADT actual = f1 / actualSum;\n    vector<double> cpt;\n    cpt += 1.0 / 3, 2.0 / 3, 3.0 / 7, 4.0 / 7, 5.0 / 11, 6.0 / 11, //\n    1.0 / 9, 8.0 / 9, 3.0 / 6, 3.0 / 6, 5.0 / 10, 5.0 / 10;\n    ADT expected(A & B & C, cpt);\n    CHECK(assert_equal(expected,actual));\n  }\n\n  {\n    // sum out lower 2 keys\n    ADT actualSum = f1.sum(C).sum(B);\n    ADT expectedSum(A, 21, 25);\n    CHECK(assert_equal(expectedSum,actualSum));\n\n    // normalize\n    ADT actual = f1 / actualSum;\n    vector<double> cpt;\n    cpt += 1.0 / 21, 2.0 / 21, 3.0 / 21, 4.0 / 21, 5.0 / 21, 6.0 / 21, //\n    1.0 / 25, 8.0 / 25, 3.0 / 25, 3.0 / 25, 5.0 / 25, 5.0 / 25;\n    ADT expected(A & B & C, cpt);\n    CHECK(assert_equal(expected,actual));\n  }\n}\n\n/* ******************************************************************************** */\n// Test non-commutative op\nTEST(ADT, div)\n{\n  DiscreteKey A(0,2), B(1,2);\n\n  // Literals\n  ADT a(A, 8, 16);\n  ADT b(B, 2, 4);\n  ADT expected_a_div_b(A & B, \"4 2 8 4\"); // 8/2 8/4 16/2 16/4\n  ADT expected_b_div_a(A & B, \"0.25 0.5 0.125 0.25\"); // 2/8 4/8 2/16 4/16\n  EXPECT(assert_equal(expected_a_div_b, a / b));\n  EXPECT(assert_equal(expected_b_div_a, b / a));\n}\n\n/* ******************************************************************************** */\n// test zero shortcut\nTEST(ADT, zero)\n{\n  DiscreteKey A(0,2), B(1,2);\n\n  // Literals\n  ADT a(A, 0, 1);\n  ADT notb(B, 1, 0);\n  ADT anotb = a * notb;\n  //  GTSAM_PRINT(anotb);\n  Assignment<Key> x00, x01, x10, x11;\n  x00[0] = 0, x00[1] = 0;\n  x01[0] = 0, x01[1] = 1;\n  x10[0] = 1, x10[1] = 0;\n  x11[0] = 1, x11[1] = 1;\n  EXPECT_DOUBLES_EQUAL(0, anotb(x00), 1e-9);\n  EXPECT_DOUBLES_EQUAL(0, anotb(x01), 1e-9);\n  EXPECT_DOUBLES_EQUAL(1, anotb(x10), 1e-9);\n  EXPECT_DOUBLES_EQUAL(0, anotb(x11), 1e-9);\n}\n\n/* ************************************************************************* */\nint main() {\n  TestResult tr;\n  return TestRegistry::runAllTests(tr);\n}\n/* ************************************************************************* */\n", "meta": {"hexsha": "9c3f4bd631895b3eea378bbfef82a31069fa3683", "size": 14847, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/discrete/tests/testAlgebraicDecisionTree.cpp", "max_stars_repo_name": "kvmanohar22/gtsam", "max_stars_repo_head_hexsha": "8194b931fe07fb1bd346cdcf116a35f9c4e208ba", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 105.0, "max_stars_repo_stars_event_min_datetime": "2017-12-02T14:39:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-19T18:20:25.000Z", "max_issues_repo_path": "gtsam/discrete/tests/testAlgebraicDecisionTree.cpp", "max_issues_repo_name": "kvmanohar22/gtsam", "max_issues_repo_head_hexsha": "8194b931fe07fb1bd346cdcf116a35f9c4e208ba", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2018-09-04T15:15:59.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-08T08:51:02.000Z", "max_forks_repo_path": "gtsam/discrete/tests/testAlgebraicDecisionTree.cpp", "max_forks_repo_name": "kvmanohar22/gtsam", "max_forks_repo_head_hexsha": "8194b931fe07fb1bd346cdcf116a35f9c4e208ba", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 31.0, "max_forks_repo_forks_event_min_datetime": "2018-01-10T03:21:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T06:18:35.000Z", "avg_line_length": 28.28, "max_line_length": 93, "alphanum_fraction": 0.5402438203, "num_tokens": 5373, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982043529715, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.47158118479124916}}
{"text": "/*=============================================================================\n\n  PHAS0100ASSIGNMENT2: PHAS0100 Assignment 2 Gravitational N-body Simulation\n\n  Copyright (c) University College London (UCL). All rights reserved.\n\n  This software is distributed WITHOUT ANY WARRANTY; without even\n  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n  PURPOSE.\n\n  See LICENSE.txt in the top level directory for details.\n\n=============================================================================*/\n\n#include \"catch.hpp\"\n#include \"nbsimCatchMain.h\"\n#include \"nbsimMyFunctions.h\"\n#include \"nbsimParticle.h\"\n#include \"nbsimMassiveParticle.h\"\n#include <iostream>\n#include <vector>\n#include <Eigen/Dense>\n\n\nTEST_CASE( \"My first test\", \"[some group identifier]\" ) {\n  int a = 5;\n  REQUIRE( a < 6 );\n}\n\nTEST_CASE( \"My second test\", \"[some group identifier]\" ) {\n  std::vector<int> a;\n  REQUIRE( a.size() == 0 );\n}\n\nTEST_CASE( \"Simple add\", \"[MyFirstAddFunction]\") {\n  REQUIRE( nbsim::MyFirstAddFunction(1, 2) == 3);\n}\n\n// ------ //\n// Testing for Task 1:\nTEST_CASE( \"Test a: No acceleration\", \"[Particle]\") {\n\n  Eigen::Vector3d a(0,0,0);\n\n  Eigen::Vector3d p_test(0,0,0);\n  Eigen::Vector3d v_test(1,1,1);\n\n  Eigen::Vector3d p_expect(0.01,0.01,0.01);\n  Eigen::Vector3d v_expect(1,1,1);\n\n  nbsim::Particle particle_a(p_test,v_test);\n  double dt = 0.01;\n  \n  REQUIRE(particle_a.getPosition().isApprox(p_test));\n  REQUIRE(particle_a.getVelocity().isApprox(v_test));\n\n  particle_a.integrateTimestep(a,dt);\n  REQUIRE(particle_a.getPosition().isApprox(p_expect));\n  REQUIRE(particle_a.getVelocity().isApprox(v_expect));\n}\n\nTEST_CASE( \"Test b: Constant acceleration\", \"[Particle]\") {\n\n  Eigen::Vector3d a(1,1,1);\n\n  Eigen::Vector3d p_test(0,0,0);\n  Eigen::Vector3d v_test(1,1,1);\n\n  Eigen::Vector3d p_expect1(0.01,0.01,0.01);\n  Eigen::Vector3d v_expect1(1.01,1.01,1.01);\n\n  nbsim::Particle particle_b(p_test,v_test);\n  double dt = 0.01;\n\n  particle_b.integrateTimestep(a,dt);\n  REQUIRE(particle_b.getPosition().isApprox(p_expect1));\n  REQUIRE(particle_b.getVelocity().isApprox(v_expect1));\n\n  Eigen::Vector3d p_expect2(0.0201,0.0201,0.0201);\n  Eigen::Vector3d v_expect2(1.02,1.02,1.02);\n \n  particle_b.integrateTimestep(a,dt);\n  REQUIRE(particle_b.getPosition().isApprox(p_expect2));\n  REQUIRE(particle_b.getVelocity().isApprox(v_expect2));\n}\n\nTEST_CASE( \"Test c: Fictitious centripetal acceleration\", \"[Particle]\") {\n\n  Eigen::Vector3d p_test(0,0,0);\n  Eigen::Vector3d v_test(1,1,1);\n\n  nbsim::Particle particle_c(p_test,v_test);\n  double dt = 0.1;\n  double time = 0.3;\n\n  for(double i=0;i<time;i+=dt){\n    Eigen::Vector3d a = -particle_c.getPosition();\n    particle_c.integrateTimestep(a,dt);\n  }\n\n  Eigen::Vector3d p_expect(0.299,0.299,0.299);\n  Eigen::Vector3d v_expect(0.97,0.97,0.97);\n\n  REQUIRE(particle_c.getPosition().isApprox(p_expect));\n  REQUIRE(particle_c.getVelocity().isApprox(v_expect));\n\n}\n\nTEST_CASE( \"Test a: Still models linear motion correctly with no attractors\", \"[MassiveParticle]\") {\n\n  Eigen::Vector3d p_test(0,0,0);\n  Eigen::Vector3d v_test(1,1,1);\n\n  Eigen::Vector3d p_expect(0.1,0.1,0.1);\n  Eigen::Vector3d v_expect(1,1,1);\n\n  double mass = 1;\n  double dt = 0.1;\n\n  nbsim::MassiveParticle MassiveParticle_a(p_test,v_test,mass);\n  MassiveParticle_a.calculateAcceleration();\n  MassiveParticle_a.integrateTimestep(dt);\n\n  REQUIRE(MassiveParticle_a.getPosition().isApprox(p_expect));\n  REQUIRE(MassiveParticle_a.getVelocity().isApprox(v_expect));\n\n}\n\nTEST_CASE( \"Test b: With gravitationally attractors\", \"[MassiveParticle]\") {\n\n  Eigen::Vector3d p_1(1,0,0);\n  Eigen::Vector3d v_1(0,0.5,0);\n\n  Eigen::Vector3d p_2(-1,0,0);\n  Eigen::Vector3d v_2(0,-0.5,0);\n\n  double mu = 1;\n\n  std::shared_ptr<nbsim::MassiveParticle> attractor_ptr1(new nbsim::MassiveParticle(p_1,v_1,mu));\n  std::shared_ptr<nbsim::MassiveParticle> attractor_ptr2(new nbsim::MassiveParticle(p_2,v_2,mu));\n\n  attractor_ptr1 -> addAttractor(attractor_ptr2);\n  attractor_ptr2 -> addAttractor(attractor_ptr1);\n\n  double dt = 0.001;\n  double t = 1;\n\n  for (double i=0;i<=t;i+=dt){\n    attractor_ptr1->calculateAcceleration();\n    attractor_ptr1->integrateTimestep(dt);\n\n    attractor_ptr2->calculateAcceleration();\n    attractor_ptr2->integrateTimestep(dt);    \n  }\n\n  double distance = (attractor_ptr1->getPosition() - attractor_ptr2->getPosition()).norm();\n  double error_expect = std::abs(distance-2);\n  REQUIRE(error_expect <= 0.01);\n}", "meta": {"hexsha": "0f5d8c5fa66dd891ed707137bd40ded78638a874", "size": 4429, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Testing/nbsimBasicTest.cpp", "max_stars_repo_name": "NottingDuck/PHAS0100Assignment2", "max_stars_repo_head_hexsha": "d1b191f3133fe084c856ea15cefe1f1e536de50c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Testing/nbsimBasicTest.cpp", "max_issues_repo_name": "NottingDuck/PHAS0100Assignment2", "max_issues_repo_head_hexsha": "d1b191f3133fe084c856ea15cefe1f1e536de50c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Testing/nbsimBasicTest.cpp", "max_forks_repo_name": "NottingDuck/PHAS0100Assignment2", "max_forks_repo_head_hexsha": "d1b191f3133fe084c856ea15cefe1f1e536de50c", "max_forks_repo_licenses": ["BSD-3-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.8553459119, "max_line_length": 100, "alphanum_fraction": 0.6881914653, "num_tokens": 1347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.7956581049086031, "lm_q1q2_score": 0.47155998376208036}}
{"text": "// (C) 2014 Arek Olek\n\n#include <iostream>\n\n#include <boost/graph/adjacency_list.hpp>\n\n#include \"dfs.hpp\"\n#include \"range.hpp\"\n\nusing namespace std;\n\nboost::property<boost::edge_color_t,\n  boost::default_color_type>            typedef color;\nboost::adjacency_list<\n  boost::hash_setS, boost::vecS, boost::undirectedS,\n  boost::no_property, color>            typedef graph;\n\n\nint main() {\n  ios_base::sync_with_stdio(0);\n\n  int z, n, m, s, t;\n  int internal = 0;\n\n  cin >> z;\n\n  for(int Z = 0; Z < z; ++Z) {\n    cin >> n >> m;\n    graph g(n);\n    for(int i = 0; i < m; ++i) {\n      cin >> s >> t;\n      add_edge(s, t, g);\n    }\n    auto T = dfs_tree(g);\n    for(auto v : range(vertices(T)))\n      internal += degree(v, T) > 1;\n  }\n  cout << internal/(double)z << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "652565bdc3480d9eee57509d46482d5e882f0a41", "size": 783, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "prototype/speed.cpp", "max_stars_repo_name": "arekolek/MaxIST", "max_stars_repo_head_hexsha": "6a8b49152cfbf34c1c2728f64b1457a23824fe0d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "prototype/speed.cpp", "max_issues_repo_name": "arekolek/MaxIST", "max_issues_repo_head_hexsha": "6a8b49152cfbf34c1c2728f64b1457a23824fe0d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "prototype/speed.cpp", "max_forks_repo_name": "arekolek/MaxIST", "max_forks_repo_head_hexsha": "6a8b49152cfbf34c1c2728f64b1457a23824fe0d", "max_forks_repo_licenses": ["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.6428571429, "max_line_length": 54, "alphanum_fraction": 0.5759897829, "num_tokens": 244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4715599808903446}}
{"text": "#ifndef HMM_HPP\n#define HMM_HPP\n\n#include <Eigen/Dense>\n\nusing Matrix = Eigen::MatrixXd;\nusing Vector = Eigen::VectorXd;\nusing MatrixType = Eigen::Ref<const Eigen::MatrixXd>;\nusing VectorType = Eigen::Ref<const Eigen::VectorXd>;\n\n\nnamespace hmm {\n\n  class HMM {\n    \n  public:\n\n    HMM() = default;\n    \n    /**\n     * @brief Construct an HMM object \n     * given the sizes of hidden and observed states.\n     *\n     * Matrices of probabilities are initialized with the inverse of the\n     * matrix size so that all states and emissions have equal probability.\n     *\n     * @param num_hidden Number of hidden states.\n     * @param num_observed Number of observed states.\n     */\n    HMM(std::size_t num_hidden, std::size_t num_observed) noexcept;\n\n    /**\n     * @brief Construct an HMM object with given probability matrices.\n     *\n     * Invokes copy constructors for the Eigen data types.\n     *\n     * @param transition_matrix Matrix of transition probabilities of\n     * dimensions [num_hidden, num_hidden].\n     *\n     * @param emission_matrix Matrix of emission probabilities of\n     * dimensions [num_hidden, num_observed].\n     *\n     * @param initial_probs Vector of initial probabilities.\n     */\n    HMM(const MatrixType& transition_probs,\n        const MatrixType& emission_probs,\n        const VectorType& initial_probs);\n\n    HMM(const MatrixType& transition_probs,\n        const MatrixType& emission_probs);\n\n    /**\n     * @brief Calculate forward probabilities for a sequence of observed states.\n     *\n     * @param observations Vector of observed states as `int` values.\n     * @returns Matrix of forward probabilities.\n     */\n    Matrix forward(const VectorType& observations) noexcept;\n\n    \n    Matrix backward(const VectorType&) noexcept;\n\n    /**\n     * Calculate the Viterbi path for a sequence of observed states.\n     * \n     * @param Vector of observed states as `int` values.\n     *\n     * @return Vector of the most likely sequence of hidden states\n     * that gave rise to the sequence of observed states provided as argument.\n     */ \n    Vector viterbi(const VectorType&) noexcept;\n\n    // getters\n    Matrix transition_matrix() const noexcept;\n    Matrix emission_matrix() const noexcept;\n\n    // setters\n    void transition_matrix(const MatrixType&);\n    void emission_matrix(const MatrixType&);\n    \n  private:\n    std::size_t m_num_hidden = 1;\n    std::size_t m_num_observed = 1;\n\n    Matrix m_transition_probs =\n      Matrix::Constant(m_num_hidden,\n                       m_num_hidden,\n                       1.0 / m_num_hidden);\n    \n    Matrix m_emission_probs =\n      Matrix::Constant(m_num_hidden,\n                       m_num_observed,\n                       1.0 / m_num_observed);\n    \n    Vector m_initial_probs =\n      Vector::Constant(m_num_hidden,\n                       1.0 / m_num_observed);\n  };\n  \n} /* class HMM */\n\n#endif /* HMM_HPP */\n", "meta": {"hexsha": "dbafeedb879d076a5f627e9274822aeba6b5993e", "size": 2894, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/hmm.hpp", "max_stars_repo_name": "alindgupta/HMM-cpp", "max_stars_repo_head_hexsha": "0475341ff8059b6f8148a844cd6c61637af3bfc2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_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": "alindgupta/HMM-cpp", "max_issues_repo_head_hexsha": "0475341ff8059b6f8148a844cd6c61637af3bfc2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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": "alindgupta/HMM-cpp", "max_forks_repo_head_hexsha": "0475341ff8059b6f8148a844cd6c61637af3bfc2", "max_forks_repo_licenses": ["BSD-3-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.0970873786, "max_line_length": 80, "alphanum_fraction": 0.6506565308, "num_tokens": 629, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.795658090372256, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4715599751468729}}
{"text": "#include <cmath>\n#include <string>\n#include <utility>\n#include <numeric>\n#include <algorithm>\n\n#include <ros/ros.h>\n#include <cv_bridge/cv_bridge.h>\n#include <opencv2/imgproc/imgproc.hpp>\n#include <opencv2/highgui/highgui.hpp>\n\n#include <boost/bind.hpp>\n#include <boost/tuple/tuple.hpp>\n\n#include <tf/tf.h>\n#include <sensor_msgs/Image.h>\n#include <sensor_msgs/LaserScan.h>\n#include <sensor_msgs/image_encodings.h>\n#include <geometry_msgs/Twist.h>\n#include <nav_msgs/Odometry.h>\n\n#include \"LaserSubscriber.hpp\"\n#include \"ImageSubscriber.hpp\"\n\n\n// topic names\nconstexpr const char* kCmdVelocityTopic = \"/mobile_base/commands/velocity\";\n\nconstexpr const char* kLaserScanTopic   = \"/scan\";\nconstexpr const char* kImageRawTopic    = \"/camera/rgb/image_raw\";\n\n// OpenCV window names\nconstexpr const char* kCaptureWindow = \"Raw Video\";\nconstexpr const char* kHsvWindow     = \"HSV Video\";\n\n// HSV filter parameters\nconstexpr std::pair<int, int> kHue        = {35, 80};\nconstexpr std::pair<int, int> kValue      = {5, 55};\nconstexpr std::pair<int, int> kSaturation = {50, 125};\n\nusing RPY = boost::tuple<double, double, double>;\n\n\nRPY rpy_from(const geometry_msgs::Quaternion& q) {\n  tf::Quaternion q_tf(q.x, q.y, q.z, q.w);\n  double r, p, y;\n\n  tf::Matrix3x3 m(q_tf);\n  m.getRPY(r, p ,y);\n  \n  return {r, p, y};\n}\n\ncv::Point compute_centroid(const cv::Mat& binary_frame) {\n  auto moments = cv::moments(binary_frame, /* binary */ true);\n  // returns negative values in case if there are no white pixels\n  return cv::Point(int(moments.m10 / moments.m00), int(moments.m01 / moments.m00));\n}\n\nfloat compute_ratio(const cv::Mat& binary_frame) {\n  int max_horizontal = 0;\n  int max_vertical = 0;\n\n  for (int j = 0; j < binary_frame.cols; ++j) {\n    max_vertical = std::max(cv::countNonZero(binary_frame.col(j)), max_vertical);\n  }\n\n  for (int i = 0; i < binary_frame.rows; ++i) {\n    max_horizontal = std::max(cv::countNonZero(binary_frame.row(i)), max_horizontal);\n  }\n\n  return max_horizontal / static_cast<float>(max_vertical);\n}\n\nvoid image_callback(const sensor_msgs::ImageConstPtr& image, const float& scan_distance, cv::Mat& binary_frame, const geometry_msgs::Pose& pose) {\n  if (scan_distance < 0.0f) return;  // no scan message arrived\n\n  cv::Mat hsv_frame;\n\n  auto image_ptr = cv_bridge::toCvShare(image, sensor_msgs::image_encodings::BGR8);\n\n  cv::GaussianBlur(image_ptr->image, image_ptr->image, cv::Size(5, 5), 0, 0);\n\n  cv::cvtColor(image_ptr->image, hsv_frame, cv::COLOR_BGR2HSV);\n  cv::inRange(hsv_frame, cv::Scalar(kHue.first, kSaturation.first, kValue.first), cv::Scalar(kHue.second, kSaturation.second, kValue.second), binary_frame);\n\n  auto white_pixels_num = cv::countNonZero(binary_frame);\n  auto centroid = compute_centroid(binary_frame);\n  auto ratio = compute_ratio(binary_frame);\n\n  double roll, pitch, yaw;\n  float x = pose.position.x;\n  float y = pose.position.y;\n  boost::tie(roll, pitch, yaw) = rpy_from(pose.orientation);\n\n  cv::putText(image_ptr->image, std::string{\"Ratio: \"} + std::to_string(ratio), cv::Point(5, 15),\n            cv::FONT_HERSHEY_COMPLEX_SMALL, 1.0, cv::Scalar(255, 255, 255), 1);\n\n  cv::putText(image_ptr->image, std::string{\"Distance (mean): \"} + std::to_string(scan_distance), cv::Point(5, 35),\n          cv::FONT_HERSHEY_COMPLEX_SMALL, 1.0, cv::Scalar(255, 255, 255), 1);\n\n  cv::putText(image_ptr->image, std::string{\"White pixels: \"} + std::to_string(white_pixels_num), cv::Point(5, 55),\n          cv::FONT_HERSHEY_COMPLEX_SMALL, 1.0, cv::Scalar(255, 255, 255), 1);\n\n  cv::putText(image_ptr->image, std::string{\"Pixels/Distance: \"} + std::to_string(white_pixels_num / scan_distance), cv::Point(5, 75),\n          cv::FONT_HERSHEY_COMPLEX_SMALL, 1.0, cv::Scalar(255, 255, 255), 1);\n\n  cv::putText(image_ptr->image, std::string{\"Pose (x, y, theta): (\"} + std::to_string(x) + \", \" + std::to_string(y) + \", \" + std::to_string(yaw) + \")\",\n   cv::Point(5, 95), cv::FONT_HERSHEY_COMPLEX_SMALL, 1.0, cv::Scalar(255, 255, 255), 1);\n\n  if (centroid.x >= 0 && centroid.y >= 0) {\n    cv::circle(image_ptr->image, centroid, 5, cv::Scalar(0, 0, 255), -1);   \n  }\n\n  cv::imshow(kCaptureWindow, image_ptr->image);\n  cv::imshow(kHsvWindow, binary_frame);\n\n  cv::waitKey(33);\n}\n\nvoid laser_callback(const sensor_msgs::LaserScanConstPtr& scan, float& scan_distance) {\n  int max_idx = std::floor((scan->angle_max - scan->angle_min) / scan->angle_increment);\n\n  std::vector<float> filtered_ranges;\n\n  std::copy_if(scan->ranges.begin(), scan->ranges.end(),\n   std::back_inserter(filtered_ranges), [&scan](float range) {\n      return range > scan->range_min && range < scan->range_max;\n   });\n\n  float mean = 0.0f;\n\n  if (filtered_ranges.size() < 10) {\n    mean = std::accumulate(filtered_ranges.begin(), filtered_ranges.end(), 0.0) / filtered_ranges.size();\n  } else {\n    // distance around the middle\n    auto middle_it = filtered_ranges.begin() + filtered_ranges.size() / 2;\n    mean = std::accumulate(middle_it - 5, middle_it + 4, 0.0) / 10.0;\n  }\n\n  scan_distance = mean;  // update scan distance\n}\n\nvoid odom_callback(const nav_msgs::OdometryConstPtr& odom, geometry_msgs::Pose& pose) {\n  pose = odom->pose.pose;\n}\n\nvoid publish_cmd_vel(float x, float z, ros::Publisher& pub) {\n  geometry_msgs::Twist cmd;\n  cmd.linear.x = x;\n  cmd.angular.z = z;\n  pub.publish(cmd);\n}\n\n\nvoid turn_and_move_forward(ros::Publisher& pub, const geometry_msgs::Pose& pose, float& scan_distance) {  \n  double roll, pitch, yaw;\n  boost::tie(roll, pitch, yaw) = rpy_from(pose.orientation);\n\n  double desired_yaw = 0.0f;\n\n  if (yaw >= 0.0 && yaw <= M_PI_2) {  // 1st quarter\n    desired_yaw = yaw + M_PI_4;\n  \n  } else if (yaw >= M_PI_2 && yaw <= M_PI) {  // 2nd quarter\n    desired_yaw = yaw - M_PI_4;\n\n  } else if (yaw >= -M_PI && yaw <= -M_PI_2) {  // 3rd quarter\n    desired_yaw = yaw + M_PI_4;\n\n  } else { // 4th quarter\n    desired_yaw = yaw - M_PI_4;\n  }\n  \n  ROS_INFO(\"Reference yaw: %.6f, target: %.6f\", yaw, desired_yaw);\n\n  ros::Rate rate(30);\n\n  while(std::abs(boost::get<2>(rpy_from(pose.orientation)) - desired_yaw) > 0.2f) {\n    publish_cmd_vel(0.0f, 0.15f, pub);\n    \n    ros::spinOnce();\n    rate.sleep();\n  }\n\n  double ref_x = pose.position.x;\n  double ref_y = pose.position.y;\n\n  double desired_distance = 10.0f;  // meters^2\n\n  ROS_INFO(\"Reference (x, y) = (%.6f, %.6f)\", ref_x, ref_y);\n\n  while ((std::isnan(scan_distance) || scan_distance >= 0.2f) \n    && std::abs(std::pow(pose.position.x - ref_x, 2) + std::pow(pose.position.y - ref_y, 2) - desired_distance) > 1.0f)  \n  {\n    publish_cmd_vel(0.12f, 0.0f, pub);\n    \n    ros::spinOnce();\n    rate.sleep();\n  }\n}\n\nint main(int argc, char *argv[]) {\n  ros::init(argc, argv, \"algorithm_node\");\n\n  ros::NodeHandle nh;\n\n  float scan_distance = -1.0f;\n  geometry_msgs::Pose pose;\n  cv::Mat binary_frame;\n\n  ImageSubscriber img_subscriber(nh, kImageRawTopic, boost::bind(&image_callback, _1, boost::cref(scan_distance), boost::ref(binary_frame), boost::cref(pose)));\n  LaserSubscriber laser_subscriber(nh, kLaserScanTopic, boost::bind(&laser_callback, _1, boost::ref(scan_distance)));\n\n  auto odom_subscriber = nh.subscribe<nav_msgs::Odometry>(\"/odom\", 3, boost::bind(&odom_callback, _1, boost::ref(pose)));\n  auto cmd_vel_publisher = nh.advertise<geometry_msgs::Twist>(kCmdVelocityTopic, 1);\n\n  cv::namedWindow(kCaptureWindow);\n  cv::namedWindow(kHsvWindow);\n\n  ros::Rate rate(60);\n\n  while(nh.ok()) {\n\n    if (!binary_frame.empty() && (scan_distance > 0.0f || std::isnan(scan_distance))) {\n      auto centroid = compute_centroid(binary_frame);\n      auto white_pixels_num = cv::countNonZero(binary_frame);\n\n      float err = centroid.x - binary_frame.cols / 2;\n\n      if (std::abs(err) > 50 || white_pixels_num < 400) {\n        ROS_INFO(\"Searching for the container ...\");\n\n        if (white_pixels_num < 400) {\n          publish_cmd_vel(0.0f, -0.15f, cmd_vel_publisher);\n        } else {\n          publish_cmd_vel(0.0f, err < 0.0f? 0.15f : -0.15f, cmd_vel_publisher);          \n        }\n\n      } else {\n        if (std::isinf(scan_distance)) ROS_WARN(\"INFINITY distance is detected\");\n\n        // approach the container (to 2-3 meters from it)\n        if (scan_distance > 2.0f) {\n          publish_cmd_vel(0.15f, 0.0f, cmd_vel_publisher);\n        } else {\n          auto ratio = compute_ratio(binary_frame);\n          auto pixel_distance_ratio = white_pixels_num / scan_distance;\n          bool is_large_side = false;\n\n          if (ratio > 1.4f) {\n            is_large_side = true;\n\n          } else if (ratio > 1.18f && pixel_distance_ratio > 20 * 1E3f) {\n            is_large_side = true;\n\n          } else {\n            is_large_side = false;\n          }\n\n          if (is_large_side && scan_distance > 1.03f) {\n            ROS_INFO(\"Approaching container for 1 meter ...\");\n            publish_cmd_vel(0.1f, 0.0f, cmd_vel_publisher);\n          }\n\n          if (!is_large_side) {\n            // turn and move forward\n            turn_and_move_forward(cmd_vel_publisher, pose, scan_distance);\n          }\n        }\n      }\n\n    }\n\n    ros::spinOnce();\n    rate.sleep();\n  }\n\n  return 0;\n}", "meta": {"hexsha": "27668189f9f7b75ae0922d5becc49b2a3bd37c3c", "size": 9062, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/container_finder/src/algorithm_node.cpp", "max_stars_repo_name": "chupakabra1996/ros-courses-2018", "max_stars_repo_head_hexsha": "86872b5a9878255e535888be936b70312f82267f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-08T16:20:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-08T16:20:50.000Z", "max_issues_repo_path": "src/container_finder/src/algorithm_node.cpp", "max_issues_repo_name": "chupakabra1996/ros-courses-2018", "max_issues_repo_head_hexsha": "86872b5a9878255e535888be936b70312f82267f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-10-20T18:38:13.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-05T20:33:15.000Z", "max_forks_repo_path": "src/container_finder/src/algorithm_node.cpp", "max_forks_repo_name": "ramilsafnab1996/ros-courses-2018", "max_forks_repo_head_hexsha": "86872b5a9878255e535888be936b70312f82267f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-11-07T13:12:34.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-07T13:12:34.000Z", "avg_line_length": 32.3642857143, "max_line_length": 160, "alphanum_fraction": 0.6570293533, "num_tokens": 2674, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4715188171270417}}
{"text": "#ifndef __GTRANSFORM_H__\n#define __GTRANSFORM_H__\n#include <iostream>\n#include <boost/signals2.hpp>\n\n#include \"glm/vec3.hpp\"\n#include \"glm/mat4x4.hpp\"\n#include \"glm/gtx/quaternion.hpp\"\n\n#include \"GCom.hpp\"\n\nNS_G4Y_BEGIN\n\nclass G4Y_DLL GTransform : public GCom\n{\n    G_COM\npublic:\n\ttypedef boost::signals2::signal<void (float, float, float)> position_changed_sig_t;\n\ttypedef boost::signals2::signal<void (float, float, float, float)> rotation_changed_sig_t;\npublic:\n    GTransform();\n    virtual ~GTransform();\n\n    virtual void Start() override;\n\n    glm::vec3 Position();\n    glm::vec3 EulerAngles();\n    glm::quat Rotation();\n\n    void SetPosition(glm::vec3);\n    void SetRotation(glm::vec3 eulers);\n    void SetRotation(glm::quat q);\n    void RotateAround(glm::vec3 target, glm::vec3 axis, float euler);\n\n    glm::vec3 LocalPosition();\n    glm::vec3 LocalEulerAngles();\n    glm::quat LocalRotation();\n\n    void SetLocalPosition(glm::vec3);\n    void SetLocalRotation(glm::vec3);\n    void SetLocalRotation(glm::quat q);\n\n    void LookAt(glm::vec3 target, glm::vec3 wld_up = glm::vec3(0, 1, 0));\n\n    glm::vec3 Forward();\n    glm::vec3 Right();\n    glm::vec3 Up();\n\n    void Translate(glm::vec3 translation);\n    void Translate(float x, float y, float z);\n\n    glm::mat4 ToMat4();\n\n    glm::vec3 Scale();\n    void SetScale(glm::vec3);\n\n\tboost::signals2::connection connect(const position_changed_sig_t::slot_type &subscriber);\n\tboost::signals2::connection connect(const rotation_changed_sig_t::slot_type &subscriber);\n\n\tvirtual std::string Name() { return m_name; }\n\tvirtual void SetName(std::string name) { m_name = name; }\nprivate:\n    void UpdateTransform(std::shared_ptr<GObj> obj, bool update_local);\n    void UpdateGlobalTransform(std::shared_ptr<GObj> obj);\n\n    struct G4Y_DLL Transform{\n        glm::quat rot;\n        glm::vec3 pos;\n        glm::vec3 scale;\n\n        Transform();\n\n        Transform(const glm::vec3& _pos, const glm::quat& _rot, glm::vec3 _scale);\n\n        Transform(const Transform &trans);\n\n        Transform& operator=(const Transform &trans);\n\n        Transform Inverted() const;\n\n        Transform operator*(const Transform& rhs) const;\n\n        glm::mat4 ToMat4() const;\n    };\n\n    Transform local_trans;\n    Transform wld_trans;\n\tstd::string m_name;\n    std::weak_ptr<GTransform> m_parent_trans;\n\tposition_changed_sig_t m_position_changed_sig;\n\trotation_changed_sig_t m_rotation_changed_sig;\n};\n\nclass G4Y_DLL GTransformWarp : public GComWarp\n{\npublic:\n\tGTransformWarp();\n\tGTransformWarp(std::shared_ptr<GTransform> t);\n\tGTransformWarp(const GTransformWarp& o);\n\n\t~GTransformWarp();\n\n\tGTransformWarp& operator=(const GTransformWarp& o);\n\n\tstatic boost::python::object getMethodList();\n\n\tstatic std::string getMethodInfo(const std::string&);\n\n\tvoid setPosition(boost::python::object o);\n\tboost::python::object getPosition();\n\n\tvoid setEulerAngles(boost::python::object o);\n\n\tboost::python::object getEulerAngles();\n\n\tvoid setScale(boost::python::object o);\n\tboost::python::object getScale();\n\n\tboost::python::object getForward();\n\tboost::python::object getRight();\n\tboost::python::object getUp();\n\n\tvoid translate(boost::python::object o);\n};\n\nNS_G4Y_END\n\n#endif\n\n", "meta": {"hexsha": "68f2452351f3751685e53ebbe02232b2e87b9c67", "size": 3196, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "g4y/gcom/transform/GTransform.hpp", "max_stars_repo_name": "lkpworkspace/gfy", "max_stars_repo_head_hexsha": "123bd8631dd878207836ec3614aa35b5c35825a3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2020-03-21T12:02:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T01:21:36.000Z", "max_issues_repo_path": "g4y/gcom/transform/GTransform.hpp", "max_issues_repo_name": "lkpworkspace/g4y", "max_issues_repo_head_hexsha": "123bd8631dd878207836ec3614aa35b5c35825a3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "g4y/gcom/transform/GTransform.hpp", "max_forks_repo_name": "lkpworkspace/g4y", "max_forks_repo_head_hexsha": "123bd8631dd878207836ec3614aa35b5c35825a3", "max_forks_repo_licenses": ["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.5846153846, "max_line_length": 91, "alphanum_fraction": 0.7036921151, "num_tokens": 804, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4715188171270417}}
{"text": "//\n// Created by xetql on 12.03.18.\n//\n\n#ifndef LIBLJ_FITTEDMLP_HPP\n#define LIBLJ_FITTEDMLP_HPP\n\n#include <mlpack/core.hpp>\n\n#include <mlpack/core/optimizers/rmsprop/rmsprop.hpp>\n#include <mlpack/core/optimizers/sgd/update_policies/vanilla_update.hpp>\n#include <mlpack/methods/ann/layer/layer.hpp>\n#include <mlpack/methods/ann/ffn.hpp>\n\n#include <armadillo>\n\n#include <type_traits>\n#include <vector>\n\n#include \"FunctionApproximator.hpp\"\n#include \"MLP.hpp\"\n\nnamespace librl {\nnamespace approximator {\nnamespace action_value {\n/**\n * NeuralNet approximator\n * @tparam OptimizerType Optimizer Type\n * @tparam ParametersType Parameters type of the neural net. See mlpack.\n */\ntemplate<typename OptimizerType, class... ParametersType>\nclass FittedMLP : public MLP<OptimizerType, ParametersType...> {\n    const std::vector<int> actions;\npublic:\n    FittedMLP(const std::vector<int>& action_space, OptimizerType opt, ParametersType... params) : actions(action_space), MLP<OptimizerType, ParametersType...>(opt, params...) {}\n    FittedMLP(const std::vector<int>& action_space, OptimizerType opt) : actions(action_space), MLP<OptimizerType, ParametersType...>(opt)  {}\n\n    virtual int argmax(const arma::mat &state, const std::vector<int> &available_actions) const {\n        arma::mat response;\n        int argmax = -1;\n        double max=std::numeric_limits<double>::lowest();\n        for(const int& action : actions){\n            arma::mat in(state);\n            in.insert_rows(in.n_rows, 1);\n            in(in.n_rows - 1) = action;\n            this->model->Predict(in, response);\n            double tmp = response.at(0);\n            if(tmp > max){\n                max = tmp;\n                argmax = action;\n            }\n        }\n        assert(argmax >= 0);\n        return argmax;\n    }\n\n    virtual void Q(const arma::mat &state, const int &action, double value) {\n        arma::mat out = {0};\n        out(0) = value;\n        arma::mat in(state);\n        in.insert_rows(in.n_rows, 1);\n        in(in.n_rows - 1) = action;\n        this->model->Train(in, out);\n    }\n\n    virtual double max(const arma::mat &state) const {\n        arma::mat response;\n        double max=std::numeric_limits<double>::lowest();\n        for(const int& action : actions){\n            arma::mat in(state);\n            in.insert_rows(in.n_rows, 1);\n            in(in.n_rows - 1) = action;\n            this->model->Predict(in, response);\n            double tmp = response.at(0);\n            if(tmp > max){\n                max = tmp;\n            }\n        }\n        return max;\n    }\n\n    virtual double Q(const arma::mat &state, const int &action) const {\n        arma::mat response;\n        arma::mat in(state);\n        in.insert_rows(in.n_rows, 1);\n        in(in.n_rows - 1) = action;\n        this->model->Predict(in, response);\n        return response.at(0);\n    }\n};\n\n}}}\n\n\n#endif //LIBLJ_FITTEDMLP_HPP\n", "meta": {"hexsha": "b49fc1af5cedeb930d2938fb8ba83aed3122c146", "size": 2880, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "includes/librl/approximators/FittedMLP.hpp", "max_stars_repo_name": "xetqL/librl", "max_stars_repo_head_hexsha": "53a1ba0bec788a06f17562e7c98813748eff3720", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2017-03-03T14:03:36.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-10T12:18:39.000Z", "max_issues_repo_path": "includes/librl/approximators/FittedMLP.hpp", "max_issues_repo_name": "xetqL/librl", "max_issues_repo_head_hexsha": "53a1ba0bec788a06f17562e7c98813748eff3720", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-03-05T13:50:23.000Z", "max_issues_repo_issues_event_max_datetime": "2017-09-01T14:16:17.000Z", "max_forks_repo_path": "includes/librl/approximators/FittedMLP.hpp", "max_forks_repo_name": "xetqL/librl", "max_forks_repo_head_hexsha": "53a1ba0bec788a06f17562e7c98813748eff3720", "max_forks_repo_licenses": ["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.0, "max_line_length": 178, "alphanum_fraction": 0.6118055556, "num_tokens": 722, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.47151881152554775}}
{"text": "#ifndef STAN_MATH_PRIM_SCAL_PROB_SKEW_NORMAL_RNG_HPP\n#define STAN_MATH_PRIM_SCAL_PROB_SKEW_NORMAL_RNG_HPP\n\n#include <boost/random/variate_generator.hpp>\n#include <boost/math/distributions.hpp>\n#include <stan/math/prim/scal/err/check_finite.hpp>\n#include <stan/math/prim/scal/err/check_not_nan.hpp>\n#include <stan/math/prim/scal/err/check_positive.hpp>\n#include <stan/math/prim/scal/err/check_consistent_sizes.hpp>\n#include <stan/math/prim/scal/fun/owens_t.hpp>\n#include <stan/math/prim/scal/fun/value_of.hpp>\n#include <stan/math/prim/scal/fun/constants.hpp>\n#include <stan/math/prim/scal/prob/uniform_rng.hpp>\n#include <stan/math/prim/scal/meta/include_summand.hpp>\n\nnamespace stan {\n  namespace math {\n\n    template <class RNG>\n    inline double\n    skew_normal_rng(double mu,\n                    double sigma,\n                    double alpha,\n                    RNG& rng) {\n      boost::math::skew_normal_distribution<> dist(mu, sigma, alpha);\n\n      static const char* function(\"skew_normal_rng\");\n\n      check_finite(function, \"Location parameter\", mu);\n      check_finite(function, \"Shape parameter\", alpha);\n      check_positive(function, \"Scale parameter\", sigma);\n\n      return quantile(dist, uniform_rng(0.0, 1.0, rng));\n    }\n\n  }\n}\n#endif\n", "meta": {"hexsha": "2a0d087e1be5618dd4e11024e536896a9778db93", "size": 1252, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/scal/prob/skew_normal_rng.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/prim/scal/prob/skew_normal_rng.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/prim/scal/prob/skew_normal_rng.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": 32.1025641026, "max_line_length": 69, "alphanum_fraction": 0.7156549521, "num_tokens": 314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919830720203, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.47151880592405365}}
{"text": "/**********************************************************************\r\n*  Copyright (c) 2008-2013, Alliance for Sustainable Energy.  \r\n*  All rights reserved.\r\n*  \r\n*  This library is free software; you can redistribute it and/or\r\n*  modify it under the terms of the GNU Lesser General Public\r\n*  License as published by the Free Software Foundation; either\r\n*  version 2.1 of the License, or (at your option) any later version.\r\n*  \r\n*  This library is distributed in the hope that it will be useful,\r\n*  but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\r\n*  Lesser General Public License for more details.\r\n*  \r\n*  You should have received a copy of the GNU Lesser General Public\r\n*  License along with this library; if not, write to the Free Software\r\n*  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\r\n**********************************************************************/\r\n\r\n#include <utilities/geometry/Geometry.hpp>\r\n#include <utilities/geometry/Transformation.hpp>\r\n\r\n#include <utilities/core/Assert.hpp>\r\n\r\n#include <boost/math/constants/constants.hpp>\r\n\r\nnamespace openstudio{\r\n  /// convert degrees to radians\r\n  double degToRad(double degrees)\r\n  {\r\n    return degrees*boost::math::constants::pi<double>()/180.0;\r\n  }\r\n\r\n  /// convert radians to degrees\r\n  double radToDeg(double radians)\r\n  {\r\n    return radians*180.0/boost::math::constants::pi<double>();\r\n  }\r\n\r\n  /// compute area from surface as Point3dVector\r\n  boost::optional<double> getArea(const Point3dVector& points)\r\n  {\r\n    boost::optional<double> result;\r\n    OptionalVector3d newall = getNewallVector(points);\r\n    if (newall){\r\n      result = newall->length() / 2.0;\r\n    }\r\n    return result;\r\n  }\r\n\r\n  // compute Newall vector from Point3dVector, direction is same as outward normal\r\n  // magnitude is twice the area\r\n  OptionalVector3d getNewallVector(const Point3dVector& points)\r\n  {\r\n    OptionalVector3d result;\r\n    unsigned N = points.size();\r\n    if (N >= 3){\r\n      Vector3d vec;\r\n      for (unsigned i = 1; i < N-1; ++i){\r\n        Vector3d v1 = points[i] - points[0];\r\n        Vector3d v2 = points[i+1] - points[0];\r\n        vec += v1.cross(v2);\r\n      }\r\n     result = vec;\r\n   }\r\n   return result;\r\n  }\r\n\r\n  // compute outward normal from Point3dVector\r\n  OptionalVector3d getOutwardNormal(const Point3dVector& points)\r\n  {\r\n    OptionalVector3d result = getNewallVector(points);\r\n    if (result){\r\n      if (!result->normalize()){\r\n        result.reset();\r\n      }\r\n    }\r\n    return result;\r\n  }\r\n\r\n  /// compute centroid from surface as Point3dVector\r\n  OptionalPoint3d getCentroid(const Point3dVector& points)\r\n  {\r\n    OptionalPoint3d result;\r\n\r\n    if (points.size() >= 3){\r\n      // convert to face coordinates\r\n      Transformation alignFace = Transformation::alignFace(points);\r\n      Point3dVector surfacePoints = alignFace.inverse()*points;\r\n\r\n      unsigned N = surfacePoints.size();\r\n      double A = 0;\r\n      double cx = 0;\r\n      double cy = 0;\r\n      for (unsigned i = 0; i < N; ++i){\r\n        double x1, x2, y1, y2;\r\n        if (i == N-1){\r\n          x1 = surfacePoints[i].x();\r\n          x2 = surfacePoints[0].x();\r\n          y1 = surfacePoints[i].y();\r\n          y2 = surfacePoints[0].y();\r\n        }else{\r\n          x1 = surfacePoints[i].x();\r\n          x2 = surfacePoints[i+1].x();\r\n          y1 = surfacePoints[i].y();\r\n          y2 = surfacePoints[i+1].y();\r\n        }\r\n\r\n        double dA = (x1*y2-x2*y1);\r\n        A += 0.5*dA;\r\n        cx += (x1+x2)*dA;\r\n        cy += (y1+y2)*dA;\r\n      }\r\n\r\n      if (A > 0){\r\n        // centroid in face coordinates\r\n        Point3d surfaceCentroid(cx/(6.0*A), cy/(6.0*A), 0.0);\r\n\r\n        // centroid\r\n        result = alignFace*surfaceCentroid;\r\n      }\r\n    }\r\n    return result;\r\n  }\r\n\r\n  /// reorder points to upper-left-corner convention\r\n  Point3dVector reorderULC(const Point3dVector& points)\r\n  {\r\n    unsigned N = points.size();\r\n    if (N < 3){\r\n      return Point3dVector();\r\n    }\r\n\r\n    // transformation to align face\r\n    Transformation t = Transformation::alignFace(points);\r\n    Point3dVector facePoints = t.inverse()*points;\r\n\r\n    // find ulc index in face coordinates\r\n    double maxY = std::numeric_limits<double>::min();\r\n    double minX = std::numeric_limits<double>::max();\r\n    unsigned ulcIndex = 0;\r\n    for(unsigned i = 0; i < N; ++i){\r\n      OS_ASSERT(std::abs(facePoints[i].z()) < 0.001);\r\n      if ((maxY < facePoints[i].y()) || ((maxY < facePoints[i].y() + 0.00001) && (minX > facePoints[i].x()))){\r\n        ulcIndex = i;\r\n        maxY = facePoints[i].y();\r\n        minX = facePoints[i].x();\r\n      }\r\n    }\r\n\r\n    // no-op\r\n    if (ulcIndex == 0){\r\n      return points;\r\n    }\r\n\r\n    // create result\r\n    Point3dVector result;\r\n    std::copy (points.begin() + ulcIndex, points.end(), std::back_inserter(result));\r\n    std::copy (points.begin(), points.begin() + ulcIndex, std::back_inserter(result));\r\n    OS_ASSERT(result.size() == N);\r\n    return result;\r\n  }\r\n\r\n  std::vector<Point3d> removeColinear(const Point3dVector& points, double tol)\r\n  {\r\n    unsigned N = points.size();\r\n    if (N < 3){\r\n      return points;\r\n    }\r\n\r\n    std::vector<Point3d> result;\r\n    Point3d lastPoint = points[0];\r\n    result.push_back(lastPoint);\r\n\r\n    for (unsigned i = 1; i < N; ++i){\r\n      Point3d currentPoint = points[i];\r\n      Point3d nextPoint = points[0];\r\n      if (i < N-1){\r\n        nextPoint = points[i+1];\r\n      }\r\n\r\n      Vector3d a = (currentPoint - lastPoint);\r\n      Vector3d b = (nextPoint - currentPoint);\r\n\r\n      // if these fail to normalize we have zero length vectors (e.g. adjacent points)\r\n      if (a.normalize()){\r\n        if (b.normalize()){\r\n\r\n          Vector3d c = a.cross(b);\r\n          if (c.length() >= tol){\r\n            // cross product is significant\r\n            result.push_back(currentPoint);\r\n            lastPoint = currentPoint;\r\n          }else{\r\n            // see if dot product is near -1\r\n            double d = a.dot(b);\r\n            if (d <= -1.0 + tol){\r\n              // this is a line reversal\r\n              result.push_back(currentPoint);\r\n              lastPoint = currentPoint;\r\n            }\r\n          }\r\n        }\r\n      }\r\n    }\r\n\r\n    return result;\r\n  }\r\n\r\n  double getDistance(const Point3d& point1, const Point3d& point2) {\r\n    double dx = point1.x() - point2.x();\r\n    double dy = point1.y() - point2.y();\r\n    double dz = point1.z() - point2.z();\r\n    double result = std::sqrt(dx*dx + dy*dy + dz*dz);\r\n    return result;\r\n  }\r\n\r\n  double getAngle(const Vector3d& vector1, const Vector3d& vector2) {\r\n    Vector3d working1(vector1);\r\n    working1.normalize();\r\n    Vector3d working2(vector2);\r\n    working2.normalize();\r\n    return acos(working1.dot(working2));\r\n  }\r\n\r\n  /// compute distance in meters between two points on the Earth's surface\r\n  /// lat and lon are specified in degrees\r\n  double getDistanceLatLon(double lat1, double lon1, double lat2, double lon2)\r\n  {\r\n\r\n    // for more accuracy would want to use WGS-84 ellipsoid params and Vincenty formula\r\n\r\n    // Haversine formula \r\n    double R = 6371000; // Earth radius meters\r\n    double deltaLat = degToRad(lat2-lat1);\r\n    double deltaLon = degToRad(lon2-lon1); \r\n    double a = sin(deltaLat/2) * sin(deltaLat/2) +\r\n               cos(degToRad(lat1)) * cos(degToRad(lat2)) * \r\n               sin(deltaLon/2) * sin(deltaLon/2); \r\n    double c = 2 * atan2(sqrt(a), sqrt(1-a)); \r\n    double d = R * c;\r\n\r\n    return d;\r\n  }\r\n\r\n  bool circularEqual(const Point3dVector& points1, const Point3dVector& points2, double tol)\r\n  {\r\n    unsigned N = points1.size();\r\n    if (N != points2.size()){\r\n      return false;\r\n    }\r\n\r\n    if (N == 0){\r\n      return true;\r\n    }\r\n\r\n    bool result = false;\r\n\r\n    // look for a common starting point\r\n    for (unsigned i = 0; i < N; ++i){\r\n      if (getDistance(points1[0], points2[i]) <= tol){\r\n\r\n        result = true;\r\n\r\n        // check all other points\r\n        for (unsigned j = 0; j < N; ++j){\r\n          if (getDistance(points1[j], points2[(i + j) % N]) > tol){\r\n            result = false;\r\n            break;\r\n          }\r\n        }\r\n      }\r\n\r\n      if (result){\r\n        return result;\r\n      }\r\n    }\r\n\r\n    return result;\r\n  }\r\n\r\n} // openstudio\r\n", "meta": {"hexsha": "7b80965c0bb37f8ef5f7e563b9e1618da657ad6f", "size": 8331, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "openstudiocore/src/utilities/geometry/Geometry.cpp", "max_stars_repo_name": "bobzabcik/OpenStudio", "max_stars_repo_head_hexsha": "858321dc0ad8d572de15858d2ae487b029a8d847", "max_stars_repo_licenses": ["blessing"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "openstudiocore/src/utilities/geometry/Geometry.cpp", "max_issues_repo_name": "bobzabcik/OpenStudio", "max_issues_repo_head_hexsha": "858321dc0ad8d572de15858d2ae487b029a8d847", "max_issues_repo_licenses": ["blessing"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "openstudiocore/src/utilities/geometry/Geometry.cpp", "max_forks_repo_name": "bobzabcik/OpenStudio", "max_forks_repo_head_hexsha": "858321dc0ad8d572de15858d2ae487b029a8d847", "max_forks_repo_licenses": ["blessing"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4381625442, "max_line_length": 111, "alphanum_fraction": 0.5691993758, "num_tokens": 2147, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.6370308013713525, "lm_q1q2_score": 0.47151386700424414}}
{"text": "#define BOOST_TEST_MODULE factorial static test\n#include <boost/test/unit_test.hpp>\n#include \"../factorial.cpp\"\n\nBOOST_AUTO_TEST_CASE(Factorials_for_zero) {\n    BOOST_TEST( Factorial(0) == 1 );\n}\n\nBOOST_AUTO_TEST_CASE(Factorials_for_positive_numbers) {\n    BOOST_TEST( Factorial(1) == 1 );\n    BOOST_TEST( Factorial(2) == 2 );\n    BOOST_TEST( Factorial(3) == 6 );\n    BOOST_TEST( Factorial(10) == 3628800 );\n}", "meta": {"hexsha": "b4ad39ff0f0b5f005a9fb8c7304ec0931806c7bd", "size": 409, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/boost-static-tests-factorial.cpp", "max_stars_repo_name": "mekyas/Unit-Test-in-Cpp", "max_stars_repo_head_hexsha": "dabfc7f83380c2c056c421bbf9f71f54acca8a0c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-11-18T05:42:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-18T05:43:59.000Z", "max_issues_repo_path": "test/boost-static-tests-factorial.cpp", "max_issues_repo_name": "mekyas/Unit-Test-in-Cpp", "max_issues_repo_head_hexsha": "dabfc7f83380c2c056c421bbf9f71f54acca8a0c", "max_issues_repo_licenses": ["MIT"], "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/boost-static-tests-factorial.cpp", "max_forks_repo_name": "mekyas/Unit-Test-in-Cpp", "max_forks_repo_head_hexsha": "dabfc7f83380c2c056c421bbf9f71f54acca8a0c", "max_forks_repo_licenses": ["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.2142857143, "max_line_length": 55, "alphanum_fraction": 0.7114914425, "num_tokens": 114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.7401743563075447, "lm_q1q2_score": 0.47151385825260145}}
{"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 staticallycorrectedyieldtermstructure.hpp\n    \\brief Statically corrected yield term structure\n    \\ingroup termstructures\n*/\n\n#ifndef quantext_statically_corrected_yts_hpp\n#define quantext_statically_corrected_yts_hpp\n\n#include <qle/termstructures/dynamicstype.hpp>\n\n#include <ql/termstructures/yieldtermstructure.hpp>\n\n#include <boost/unordered_map.hpp>\n\nnamespace QuantExt {\nusing namespace QuantLib;\n\n//! Statically Corrected Yield Term Structure\n/*! This termstructure takes a floating reference date term structure\n    and two fixed reference date term structures, applying a static\n    correction to the floating ts implied by the two fixed ones.\n    Usually the floating term structure will coincide with\n    the first fixed at construction time. Also, the two fixed\n    termstructures should have the same reference date and all three\n    termstructures should have the same day counter.\n\n    \\ingroup termstructures\n */\nclass StaticallyCorrectedYieldTermStructure : public YieldTermStructure {\npublic:\n    StaticallyCorrectedYieldTermStructure(const Handle<YieldTermStructure>& floatingTermStructure,\n                                          const Handle<YieldTermStructure>& fixedSourceTermStructure,\n                                          const Handle<YieldTermStructure>& fixedTargetTermStructure,\n                                          const YieldCurveRollDown& rollDown = ForwardForward)\n        : YieldTermStructure(floatingTermStructure->dayCounter()), x_(floatingTermStructure),\n          source_(fixedSourceTermStructure), target_(fixedTargetTermStructure), rollDown_(rollDown) {\n        registerWith(floatingTermStructure);\n        registerWith(fixedSourceTermStructure);\n        registerWith(fixedTargetTermStructure);\n    }\n\n    Date maxDate() const { return x_->maxDate(); }\n    void update() {}\n    const Date& referenceDate() const { return x_->referenceDate(); }\n\n    Calendar calendar() const { return x_->calendar(); }\n    Natural settlementDays() const { return x_->settlementDays(); }\n\n    void flushCache() { cache_c_.clear(); }\n\nprotected:\n    Real discountImpl(Time t) const;\n\nprivate:\n    // FIXME: remove cache\n    // cache for source and target forwards\n    struct cache_key {\n        double t0, t;\n        bool operator==(const cache_key& o) const { return (t0 == o.t0) && (t == o.t); }\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.t0);\n            boost::hash_combine(seed, x.t);\n            return seed;\n        }\n    };\n    mutable boost::unordered_map<cache_key, Real, cache_hasher> cache_c_;\n    // end cache\n    const Handle<YieldTermStructure> x_, source_, target_;\n    const YieldCurveRollDown rollDown_;\n};\n\n// inline\n\ninline Real StaticallyCorrectedYieldTermStructure::discountImpl(Time t) const {\n    Real c = 1.0;\n    if (rollDown_ == ForwardForward) {\n        Real t0 = source_->timeFromReference(referenceDate());\n        // roll down = ForwardForward\n        // cache lookup\n        cache_key k = { t0, t };\n        boost::unordered_map<cache_key, Real>::const_iterator i = cache_c_.find(k);\n        if (i == cache_c_.end()) {\n            c = source_->discount(t0) / source_->discount(t0 + t) * target_->discount(t0 + t) / target_->discount(t0);\n            cache_c_.insert(std::make_pair(k, c));\n        } else {\n            c = i->second;\n        }\n    } else {\n        // roll down = ConstantDiscount\n        // cache lookup\n        cache_key k = { 0.0, t };\n        boost::unordered_map<cache_key, Real>::const_iterator i = cache_c_.find(k);\n        if (i == cache_c_.end()) {\n            c = target_->discount(t) / source_->discount(t);\n            cache_c_.insert(std::make_pair(k, c));\n        } else {\n            c = i->second;\n        }\n    }\n    return x_->discount(t) * c;\n}\n\n} // namespace QuantExt\n\n#endif\n", "meta": {"hexsha": "18b02909d5bbab09f4b42b2e10af789b5537954b", "size": 4706, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "QuantExt/qle/termstructures/staticallycorrectedyieldtermstructure.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/staticallycorrectedyieldtermstructure.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/staticallycorrectedyieldtermstructure.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": 37.0551181102, "max_line_length": 118, "alphanum_fraction": 0.6774330642, "num_tokens": 1059, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.4715138546014774}}
{"text": "#include <boost/static_assert.hpp>\n#include <iostream>\n\ntemplate <unsigned long N>\nstruct binary\n{\n  BOOST_STATIC_ASSERT((N % 10 < 2));\n\n  static unsigned const value = binary<N / 10>::value * 2 + N % 10;\n};\n\ntemplate <>\nstruct binary<0>\n{\n  static unsigned const value = 0;\n};\n\nint main(int argc, const char* argv[])\n{\n\n#define PRINT_AS_BINARY_AND_VALUE(theValue)                                    \\\n  {                                                                            \\\n    std::cout << theValue << \" is the binary representation of \"               \\\n              << binary<theValue>::value << std::endl;                         \\\n  }\n\n  PRINT_AS_BINARY_AND_VALUE(111);\n  PRINT_AS_BINARY_AND_VALUE(1011);\n  PRINT_AS_BINARY_AND_VALUE(1101);\n  PRINT_AS_BINARY_AND_VALUE(101010);\n\n#undef PRINT_AS_BINARY_AND_VALUE\n}\n", "meta": {"hexsha": "152df38fb888f9a0c22eac455e9a7f2d62cd0809", "size": 827, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "TemplatedBinary/TemplatedBinary.cpp", "max_stars_repo_name": "jbcoe/CppSandbox", "max_stars_repo_head_hexsha": "574dc31bbd3640a8cf1b7642c4a449bee687cce5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2015-01-18T13:30:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-21T19:50:26.000Z", "max_issues_repo_path": "TemplatedBinary/TemplatedBinary.cpp", "max_issues_repo_name": "jbcoe/CppSandbox", "max_issues_repo_head_hexsha": "574dc31bbd3640a8cf1b7642c4a449bee687cce5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-03-13T21:26:37.000Z", "max_issues_repo_issues_event_max_datetime": "2016-03-13T21:26:37.000Z", "max_forks_repo_path": "TemplatedBinary/TemplatedBinary.cpp", "max_forks_repo_name": "jbcoe/CppSandbox", "max_forks_repo_head_hexsha": "574dc31bbd3640a8cf1b7642c4a449bee687cce5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-02-16T04:56:25.000Z", "max_forks_repo_forks_event_max_datetime": "2016-02-16T04:56:25.000Z", "avg_line_length": 24.3235294118, "max_line_length": 80, "alphanum_fraction": 0.5659008464, "num_tokens": 181, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390162, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.47151385170268756}}
{"text": "//=============================================================================\n//\n//  CLASS ArpackSolver\n//\n//=============================================================================\n\n\n#ifndef COMISO_ARPACKSOLVER_HH\n#define COMISO_ARPACKSOLVER_HH\n\n//== COMPILE-TIME PACKAGE REQUIREMENTS ========================================\n#include <CoMISo/Config/config.hh>\n#if (COMISO_ARPACK_AVAILABLE && COMISO_SUITESPARSE_AVAILABLE && COMISO_EIGEN3_AVAILABLE)\n\n//== INCLUDES =================================================================\n#include <CoMISo/Config/CoMISoDefines.hh>\n\n#include <Eigen/Eigen>\n#include \"EigenArpackMatrixT.hh\"\n\n#include <arpack++/arssym.h>\n\n//== FORWARDDECLARATIONS ======================================================\n\n//== NAMESPACES ===============================================================\n\nnamespace COMISO {\n\n//== CLASS DEFINITION =========================================================\n\n\n\n\t      \n/** \\class ArpackSolver ArpackSolver.hh <COMISO/.../ArpackSolver.hh>\n\n    Brief Description.\n  \n    A more elaborate description follows.\n*/\n\n\nclass COMISODLLEXPORT ArpackSolver\n{\npublic:\n\n  // sparse matrix type\n  typedef EigenArpackMatrixT<double,Eigen::SparseMatrix<double,Eigen::ColMajor> > Matrix;\n\n\n  /// Constructor\n  ArpackSolver() {}\n \n  /// Destructor\n  ~ArpackSolver() {}\n\n  // solve eigenproblem\n  // number of desired eigenvalues -> _n_eigenvalues\n  // which eigenvalues -> one of {LA (largest algebraic), SA (smalles algebraic), LM (largest magnitude), SM(smallest magnitued), BE(both ends)}\n  template<class MatrixT,class MatrixT2>\n  void solve(const MatrixT&       _A,\n             std::vector<double>& _eigenvalues,\n             MatrixT2&            _eigenvectors,\n             const int            _n_eigvalues = 1,\n             const char*          _which_eigs = \"SM\");\n\n  // solve eigenproblem\n  // number of desired eigenvalues -> _n_eigenvalues\n  // which eigenvalues -> one of {LA (largest algebraic), SA (smalles algebraic), LM (largest magnitude), SM(smallest magnitued), BE(both ends)}\n  template<class MatrixT,class MatrixT2>\n  void solve_inverse(const MatrixT&       _A,\n                     std::vector<double>& _eigenvalues,\n                     MatrixT2&            _eigenvectors,\n                     const int            _n_eigvalues = 1,\n                     const char*          _which_eigs = \"LM\");\n\n\n  // check resulting eigenvalues/eigenvectors\n  template<class MatrixT,class MatrixT2>\n  void check_result(const MatrixT& _A, std::vector<double>& _eigenvalues, MatrixT2& _eigenvectors);\n\nprivate:\n  \n};\n\n\n//=============================================================================\n} // namespace ACG\n//=============================================================================\n#if defined(INCLUDE_TEMPLATES) && !defined(COMISO_ARPACKSOLVER_C)\n#define COMISO_ARPACKSOLVER_TEMPLATES\n#include \"ArpackSolver.cc\"\n#endif\n//=============================================================================\n#endif // COMISO_SUITESPARSE_AVAILABLE\n//=============================================================================\n#endif // ACG_ARPACKSOLVER_HH defined\n//=============================================================================\n\n", "meta": {"hexsha": "067916a60a1e2542857975d423ea5fbe0beeca6a", "size": 3219, "ext": "hh", "lang": "C++", "max_stars_repo_path": "3rdparty/meshlab-master/src/external/CoMISo/EigenSolver/ArpackSolver.hh", "max_stars_repo_name": "HoEmpire/slambook2", "max_stars_repo_head_hexsha": "96d360f32aa5d8b5c5dcbbf9ee7ba865e84409f4", "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": "3rdparty/meshlab-master/src/external/CoMISo/EigenSolver/ArpackSolver.hh", "max_issues_repo_name": "HoEmpire/slambook2", "max_issues_repo_head_hexsha": "96d360f32aa5d8b5c5dcbbf9ee7ba865e84409f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-11-14T23:14:58.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-14T23:14:58.000Z", "max_forks_repo_path": "3rdparty/meshlab-master/src/external/CoMISo/EigenSolver/ArpackSolver.hh", "max_forks_repo_name": "HoEmpire/slambook2", "max_forks_repo_head_hexsha": "96d360f32aa5d8b5c5dcbbf9ee7ba865e84409f4", "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": 32.5151515152, "max_line_length": 144, "alphanum_fraction": 0.5007766387, "num_tokens": 660, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397349, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4714984910685621}}
{"text": "/* pcmsolver_copyright_start */\n/*\n *     PCMSolver, an API for the Polarizable Continuum Model\n *     Copyright (C) 2013-2016 Roberto Di Remigio, Luca Frediani and contributors\n *     \n *     This file is part of PCMSolver.\n *     \n *     PCMSolver is free software: you can redistribute it and/or modify\n *     it under the terms of the GNU Lesser General Public License as published by\n *     the Free Software Foundation, either version 3 of the License, or\n *     (at your option) any later version.\n *     \n *     PCMSolver is distributed in the hope that it will be useful,\n *     but WITHOUT ANY WARRANTY; without even the implied warranty of\n *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *     GNU Lesser General Public License for more details.\n *     \n *     You should have received a copy of the GNU Lesser General Public License\n *     along with PCMSolver.  If not, see <http://www.gnu.org/licenses/>.\n *     \n *     For information on the complete list of contributors to the\n *     PCMSolver API, see: <http://pcmsolver.readthedocs.io/>\n */\n/* pcmsolver_copyright_end */\n\n#include \"Element.hpp\"\n\n#include <cmath>\n#include <vector>\n\n#include \"Config.hpp\"\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <Eigen/LU>\n\n#include <boost/math/special_functions/sign.hpp>\n\n#include \"utils/Sphere.hpp\"\n\nvoid Element::spherical_polygon(Eigen::Vector3d & t_, Eigen::Vector3d & b_,\n    std::vector<double> & theta, std::vector<double> & phi,\n    std::vector<double> & phinumb, std::vector<int> & numb) const\n{\n  Eigen::Vector3d sph_center = sphere_.center;\n  double radius = sphere_.radius;\n  // Calculate the azimuthal and polar angles for the tessera vertices:\n  // we use the normal, tangent and bitangent as a local reference frame\n  for (int i = 0; i < nVertices_; ++i) {\n    Eigen::Vector3d vertex_normal = vertices_.col(i) - sph_center;\n    // The cosine of the polar angle is given as the dot product of the normal at the vertex and the\n    // normal at the tessera center: R\\cos\\theta\n    double cos_theta = vertex_normal.dot(normal_) / radius;\n    if (cos_theta >=  1.0) cos_theta = 1.0;\n    if (cos_theta <= -1.0) cos_theta = -1.0;\n    theta[i] = std::acos(cos_theta);\n    // The cosine of the azimuthal angle is given as the dot product of the normal at the vertex and the\n    // tangent at the tessera center divided by the sine of the polar angle: R\\sin\\theta\\cos\\phi\n    double cos_phi = vertex_normal.dot(t_) / (radius * std::sin(theta[i]));\n    if (cos_phi >=  1.0) cos_phi = 1.0;\n    if (cos_phi <= -1.0) cos_phi = -1.0;\n    phi[i] = std::acos(cos_phi);\n    // The sine of the azimuthal angle is given as the dot product of the normal at the vertex and the\n    // bitangent at the tessera center divided by the sine of the polar angle: R\\sin\\theta\\sin\\phi\n    double sin_phi = vertex_normal.dot(b_) / (radius * std::sin(theta[i]));\n    if (sin_phi <= 0.0) phi[i] = 2 * M_PI - phi[i];\n  }\n  for (int i = 1; i < nVertices_; ++i) {\n    phi[i] = phi[i] - phi[0];\n    if (phi[i] < 0.0) phi[i] = 2 * M_PI + phi[i];\n  }\n  // Rewrite tangent as linear combination of original tangent and bitangent\n  // then recalculate bitangent so that it's orthogonal to the tangent\n  t_ = t_ * std::cos(phi[0]) + b_ * std::sin(phi[0]);\n  b_ = normal_.cross(t_);\n  // Populate numb and phinumb arrays\n  phi[0] = 0.0;\n  numb[0] = 0; numb[1] = 1;\n  phinumb[0] = phi[0]; phinumb[1] = phi[1];\n  for (int i = 2; i < nVertices_; ++i) {// This loop is 2-based\n    for (int j = 1; j < i; ++j) {// This loop is 1-based\n      if (phi[i] < phinumb[j]) {\n        for (int k = 0; k < (i - j); ++k) {\n          numb[i - k] = numb[i - k -1];\n          phinumb[i - k] = phinumb[i - k -1];\n        }\n        numb[j] = i;\n        phinumb[j] = phi[i];\n        goto jump;\n      }\n    }\n    numb[i] = i;\n    phinumb[i] = phi[i];\njump:\n    ; // Do nothing...\n  }\n  numb[nVertices_] = numb[0];\n  phinumb[nVertices_] = 2 * M_PI;\n}\n\nvoid tangent_and_bitangent(const Eigen::Vector3d & n_,\n    Eigen::Vector3d & t_, Eigen::Vector3d & b_)\n{\n  double rmin = 0.99;\n  double n0 = n_(0), n1 = n_(1), n2 = n_(2);\n  if (std::abs(n0) <= rmin) {\n    rmin = std::abs(n0);\n    t_(0) = 0.0;\n    t_(1) = - n2 / std::sqrt(1.0 - std::pow(n0, 2));\n    t_(2) =   n1 / std::sqrt(1.0 - std::pow(n0, 2));\n  }\n  if (std::abs(n1) <= rmin) {\n    rmin = std::abs(n1);\n    t_(0) =   n2 / std::sqrt(1.0 - std::pow(n1, 2));\n    t_(1) =   0.0;\n    t_(2) = - n0 / std::sqrt(1.0 - std::pow(n1, 2));\n  }\n  if (std::abs(n2) <= rmin) {\n    rmin = std::abs(n2);\n    t_(0) =  n1 / std::sqrt(1.0 - std::pow(n2, 2));\n    t_(1) = -n0 / std::sqrt(1.0 - std::pow(n2, 2));\n    t_(2) =  0.0;\n  }\n  b_ = n_.cross(t_);\n  // Check that the calculated Frenet-Serret frame is left-handed (levogiro)\n  // by checking that the determinant of the matrix whose columns are the normal,\n  // tangent and bitangent vectors has determinant 1 (the system is orthonormal!)\n  Eigen::Matrix3d M;\n  M.col(0) = n_;\n  M.col(1) = t_;\n  M.col(2) = b_;\n  if (boost::math::sign(M.determinant()) != 1) {\n    PCMSOLVER_ERROR(\"Frenet-Serret local frame is not left-handed!\", BOOST_CURRENT_FUNCTION);\n  }\n}\n", "meta": {"hexsha": "2105ca607b8815b5ad358e8784de2b7bcfcba113", "size": 5144, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "external/PCMSolver/PCMSolver-source/src/cavity/Element.cpp", "max_stars_repo_name": "robertodr/externalize", "max_stars_repo_head_hexsha": "c7b1dda2009dab329a6efb580c57ef8e1494cf3b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-02-15T22:16:34.000Z", "max_stars_repo_stars_event_max_datetime": "2017-02-15T22:16:34.000Z", "max_issues_repo_path": "external/PCMSolver/PCMSolver-source/src/cavity/Element.cpp", "max_issues_repo_name": "robertodr/externalize", "max_issues_repo_head_hexsha": "c7b1dda2009dab329a6efb580c57ef8e1494cf3b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "external/PCMSolver/PCMSolver-source/src/cavity/Element.cpp", "max_forks_repo_name": "robertodr/externalize", "max_forks_repo_head_hexsha": "c7b1dda2009dab329a6efb580c57ef8e1494cf3b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.8235294118, "max_line_length": 104, "alphanum_fraction": 0.6201399689, "num_tokens": 1650, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4714984851817311}}
{"text": "//\n// Created by a.kiryanenko on 3/26/20.\n//\n\n#include \"../SpuUltraGraphAdapter.h\"\n#include \"../SpuUltraGraphProperty.h\"\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/kruskal_min_spanning_tree.hpp>\n#include \"GraphPerformanceTest.h\"\n\n\nusing namespace SPU_GRAPH;\nusing namespace boost;\n\n\ntypedef boost::adjacency_list <\n        boost::vecS, // \u043a\u0430\u043a \u0445\u0440\u0430\u043d\u0438\u0442\u044c \u0432\u0435\u0440\u0448\u0438\u043d\u044b - \u0432 \u0432\u0435\u043a\u0442\u043e\u0440\u0435\n        boost::vecS, // \u043a\u0430\u043a \u0445\u0440\u0430\u043d\u0438\u0442\u044c \u0440\u0435\u0431\u0440\u0430 \u0438\u0437 \u043a\u0430\u0436\u0434\u043e\u0439 \u0432\u0435\u0440\u0448\u0438\u043d\u044b - \u0432 \u0432\u0435\u043a\u0442\u043e\u0440\u0435\n        boost::directedS,\n        no_property,\n        property < edge_weight_t, int >\n> AdjacencyListGraph;\n\n\n\ntemplate <class G>\npair<typename graph_traits<G>::edge_descriptor, bool>\nadd_weight_edge(typename graph_traits<G>::vertex_descriptor u, typename graph_traits<G>::vertex_descriptor v, G& g) {\n    auto weight = rand() % 16;\n    return add_edge(u, v, weight, g);\n}\n\ntemplate <>\npair<typename graph_traits<SpuUltraGraph>::edge_descriptor, bool>\nadd_weight_edge(typename graph_traits<SpuUltraGraph>::vertex_descriptor u, typename graph_traits<SpuUltraGraph>::vertex_descriptor v, SpuUltraGraph& g) {\n    auto weight = rand() % 16;\n    return {g.add_edge(g.get_free_edge_descriptor(weight), u, v), true};\n}\n\n\ntemplate <class G>\nvoid kruskal_test(G &g) {\n    typedef typename graph_traits<G>::vertex_descriptor vertex_t;\n    typedef typename graph_traits<G>::edge_descriptor edge_t;\n\n    std::vector < edge_t > spanning_tree;\n    // \u0412\u044b\u043f\u043e\u043b\u043d\u044f\u044e \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c \u041a\u0440\u0430\u0441\u043a\u0430\u043b\u0430 \u0434\u043b\u044f \u043f\u043e\u0441\u0442\u0440\u043e\u0435\u043d\u0438\u044f \u043c\u0438\u043d\u0438\u043c\u0430\u043b\u044c\u043d\u043e\u0433\u043e \u043e\u0441\u0442\u043e\u0432\u043d\u043e\u0433\u043e \u0434\u0435\u0440\u0435\u0432\u0430\n    kruskal_minimum_spanning_tree(g, std::back_inserter(spanning_tree));\n}\n\n\nint main()\n{\n    cout << \"SpuUltraGraph performance test\" << endl;\n    cout << \"==========================================\" << endl;\n    GraphPerformanceTest<SpuUltraGraph> spu_graph_test(kruskal_test, \"kruskal_test_SpuUltraGraph.csv\");\n    spu_graph_test.is_mutable_test = false;\n    spu_graph_test.add_edge_func = add_weight_edge;\n    spu_graph_test.start();\n\n    cout << \"adjacency_list performance test\" << endl;\n    cout << \"==========================================\" << endl;\n    GraphPerformanceTest<AdjacencyListGraph> adjacency_list_test(kruskal_test, \"kruskal_test_adjacency_list.csv\");\n    adjacency_list_test.is_mutable_test = false;\n    adjacency_list_test.add_edge_func = add_weight_edge;\n    adjacency_list_test.start();\n\n    cout << \"adjacency_matrix performance test\" << endl;\n    cout << \"==========================================\" << endl;\n    GraphPerformanceTest<AdjacencyMatrixGraph> adjacency_matrix_test(kruskal_test, \"kruskal_test_adjacency_matrix.csv\");\n    adjacency_matrix_test.is_mutable_test = false;\n    adjacency_matrix_test.add_edge_func = add_weight_edge;\n    adjacency_matrix_test.end_vertices_cnt = 20000;\n    adjacency_matrix_test.start();\n    return 0;\n}", "meta": {"hexsha": "0c4bec653906dc3b68a74f116a9a593763204d32", "size": 2745, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "performance_tests/kruskal.cpp", "max_stars_repo_name": "kiryanenko/graph-api", "max_stars_repo_head_hexsha": "43436b98189db58587a7cf779293dac8f4b5e39a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-29T19:42:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-29T19:42:34.000Z", "max_issues_repo_path": "performance_tests/kruskal.cpp", "max_issues_repo_name": "kiryanenko/graph-api", "max_issues_repo_head_hexsha": "43436b98189db58587a7cf779293dac8f4b5e39a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "performance_tests/kruskal.cpp", "max_forks_repo_name": "kiryanenko/graph-api", "max_forks_repo_head_hexsha": "43436b98189db58587a7cf779293dac8f4b5e39a", "max_forks_repo_licenses": ["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.1184210526, "max_line_length": 153, "alphanum_fraction": 0.7111111111, "num_tokens": 678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.4714984851817311}}
{"text": "#ifndef MPI_IMPL_DISTRIBUTED_DOT_HPP\n#define MPI_IMPL_DISTRIBUTED_DOT_HPP\n\n#include <unordered_map>\n\n#include <boost/mpi.hpp>\n#include <armadillo>\n\n#include \"types.hpp\"\n#include \"get_edge_values.hpp\"\n#include \"mpi_impl/Mesh.hpp\"\n\nnamespace schro_mpi\n{\n    template <std::floating_point real>\n    real dot(const Mesh<real>& mesh, const SparseData<matrix<real>>& a, const SparseData<matrix<real>>& b)\n    {\n        int n = mesh.N;\n\n        // compute dot for interior nodes\n        real p_interiors = 0;\n\n        auto interior = arma::span(1, n-2);\n        for (const auto& [el, u] : a)\n        {\n            const auto& v = b.at(el);\n            p_interiors += arma::dot(u.submat(interior, interior), v.submat(interior, interior));\n        }\n\n        // compute dot along edges\n        real p_edges = 0;\n\n        for (const auto& [id, edge] : mesh.edges)\n        {\n            const int e = edge.elements[0];\n            if (mesh.elements.contains(e)) {\n                const int s = std::abs(edge.element_sides[0]);\n                const auto& u = a.at(e);\n                const auto& v = b.at(e);\n\n                real pe = 0;\n                if (s == 2 or s == 4) {\n                    int i = mesh.smap(s);\n                    for (int j=1; j < mesh.N-1; ++j)\n                        pe += u.at(i,j) * v.at(i,j);\n                } else {\n                    int j = mesh.smap(s);\n                    for (int i=1; i < mesh.N-1; ++i)\n                        pe += u.at(i,j) * v.at(i,j);\n                }\n\n                p_edges += pe;\n            }\n        }\n\n        // compute dot on corners\n        real p_corners = 0;\n\n        for (const auto& [id, node] : mesh.nodes)\n        {\n            const auto& info = node.connected_elements[0];\n            if (mesh.elements.contains(info.element_id))\n                p_corners += a.at(info.element_id).at(info.i, info.j) * b.at(info.element_id).at(info.i, info.j);\n        }\n        \n        real p = p_interiors + p_edges + p_corners;\n\n        p = mpi::all_reduce(mesh.comm, p, std::plus<real>{});\n\n        return p;\n    }\n\n} // namespace schro_mpi\n\n#endif", "meta": {"hexsha": "3c870045022a5e705dbeda51a06948a9e39ff355", "size": 2109, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mpi_impl/dot.hpp", "max_stars_repo_name": "arotem3/SchrodingerSEM", "max_stars_repo_head_hexsha": "b1d5c5a959efe46cb8d473f284d150c3c7f0beb6", "max_stars_repo_licenses": ["Apache-2.0"], "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/mpi_impl/dot.hpp", "max_issues_repo_name": "arotem3/SchrodingerSEM", "max_issues_repo_head_hexsha": "b1d5c5a959efe46cb8d473f284d150c3c7f0beb6", "max_issues_repo_licenses": ["Apache-2.0"], "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/mpi_impl/dot.hpp", "max_forks_repo_name": "arotem3/SchrodingerSEM", "max_forks_repo_head_hexsha": "b1d5c5a959efe46cb8d473f284d150c3c7f0beb6", "max_forks_repo_licenses": ["Apache-2.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.12, "max_line_length": 113, "alphanum_fraction": 0.4959696539, "num_tokens": 533, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.47149848518173104}}
{"text": "#include <fstream>\n#include <sstream>\n#include <iostream>\n#include <iomanip>\n#include <fmt/format.h>\n#include <string>\n#include <iomanip>\n#include <boost/variant.hpp>\n#include <unordered_map>\n#include <range/v3/all.hpp>\nstruct Jio\n{\n};\nstruct Jie\n{\n};\nstruct Inc\n{\n};\nstruct Tpl\n{\n};\nstruct Hlf\n{\n};\nstruct Jmp\n{\n};\nstruct Machine\n{\n  Machine()\n  {\n    m[\"packages_\"] = 0;\n    m[\"b\"] = 0;\n  }\n  int pos_;\n  int minpos_ = 0;\n  int maxpos_ = 48;\n  std::unordered_map<std::string, int> m;\n  std::vector<std::string> ops_;\n  void Jio(const std::string &operand, int value)\n  {\n    int n = m[operand];\n    if (n == 1) {\n      pos_ += value;\n    } else {\n      ++pos_;\n    }\n  }\n  void Jie(const std::string &operand, int value)\n  {\n    int n = m[operand] % 2;\n    if (n == 0) {\n      pos_ += value;\n    } else {\n      ++pos_;\n    }\n  }\n\n  void Tpl(const std::string &operand)\n  {\n    m[operand] *= 3;\n    ++pos_;\n  }\n\n  void Hlf(const std::string &operand)\n  {\n    m[operand] /= 2;\n    ++pos_;\n  }\n  void Inc(const std::string &operand)\n  {\n    m[operand] += 1;\n    ++pos_;\n  }\n  void Jmp(int value)\n  {\n    pos_ += value;\n  }\n  bool valid() const\n  {\n    return (minpos_ <= pos_) && (pos_ < maxpos_);\n  }\n  void execute()\n  {\n    while (valid()) {\n      std::istringstream iss(ops_[pos_]);\n      std::string s;\n      std::string op, opand;\n      iss >> op;\n      int opint;\n      if (op == \"hlf\") {\n        iss >> opand;\n        Hlf(opand);\n      } else if (op == \"tpl\") {\n        iss >> opand;\n        Tpl(opand);\n      } else if (op == \"inc\") {\n        iss >> opand;\n        Inc(opand);\n      } else if (op == \"jmp\") {\n        iss >> opint;\n        Jmp(opint);\n      } else if (op == \"jie\") {\n        iss >> opand >> opint;\n        Jie(opand, opint);\n      } else if (op == \"jio\") {\n        iss >> opand >> opint;\n        Jio(opand, opint);\n      }\n    }\n  }\n};\nint main(int argc, char **argv)\n{\n  if (argc > 1) {\n    std::ifstream ifs(argv[1]);\n    Machine m;\n    //Jio jio;\n    //Jie jie;\n    //Jmp jmp;\n    //Inc inc;\n    //Hlf hlf;\n    //Tpl tpl;\n    std::string s;\n\n    for (; std::getline(ifs, s);) {\n      m.ops_.push_back(s);\n    }\n    m.execute();\n    fmt::print(\"{}\\n\", m.m[\"b\"]);\n  }\n}", "meta": {"hexsha": "4778dd0cdaba0790b84c9280a23d24fb692aa651", "size": 2194, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "aoc2015/aoc152301.cpp", "max_stars_repo_name": "jiayuehua/adventOfCode", "max_stars_repo_head_hexsha": "fd47ddefd286fe94db204a9850110f8d1d74d15b", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "aoc2015/aoc152301.cpp", "max_issues_repo_name": "jiayuehua/adventOfCode", "max_issues_repo_head_hexsha": "fd47ddefd286fe94db204a9850110f8d1d74d15b", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "aoc2015/aoc152301.cpp", "max_forks_repo_name": "jiayuehua/adventOfCode", "max_forks_repo_head_hexsha": "fd47ddefd286fe94db204a9850110f8d1d74d15b", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.4962406015, "max_line_length": 49, "alphanum_fraction": 0.4917958067, "num_tokens": 715, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996142, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.47149847929489985}}
{"text": "#include <boost/graph/rmat_graph_generator.hpp>\n", "meta": {"hexsha": "23179c2bf21f3775c677e63e2e5c6ea76602b69c", "size": 48, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_graph_rmat_graph_generator.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_graph_rmat_graph_generator.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_graph_rmat_graph_generator.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 24.0, "max_line_length": 47, "alphanum_fraction": 0.8333333333, "num_tokens": 10, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.47149847929489985}}
{"text": "#include <ros/ros.h>\n#include <iostream>\n#include <tf/transform_listener.h>\n#include <std_msgs/Float32MultiArray.h>\n#include <std_srvs/Empty.h>\n#include <Eigen/Eigen>\n#include <geometry_msgs/Twist.h>\n#include <crazyflie_controller/Mocap.h>\n\n\n#include \"pid.hpp\"\n\n\ndouble get(\n    const ros::NodeHandle& n,\n    const std::string& name) {\n    double value;\n    n.getParam(name, value);\n    return value;\n}\n\n\n\nclass Controller\n\n{\n\npublic:\n\n    Controller(\n        // const std::string& worldFrame,\n        // const std::string& frame,\n        const ros::NodeHandle& n)\n        : m_pubNav()\n        , m_pubCmdVtemp()\n        , m_pidX(\n            get(n, \"PIDs/X/kp\"),\n            get(n, \"PIDs/X/kd\"),\n            get(n, \"PIDs/X/ki\"),\n            get(n, \"PIDs/X/minOutput\"),\n            get(n, \"PIDs/X/maxOutput\"),\n            get(n, \"PIDs/X/integratorMin\"),\n            get(n, \"PIDs/X/integratorMax\"),\n            \"x\")\n        , m_pidY(\n            get(n, \"PIDs/Y/kp\"),\n            get(n, \"PIDs/Y/kd\"),\n            get(n, \"PIDs/Y/ki\"),\n            get(n, \"PIDs/Y/minOutput\"),\n            get(n, \"PIDs/Y/maxOutput\"),\n            get(n, \"PIDs/Y/integratorMin\"),\n            get(n, \"PIDs/Y/integratorMax\"),\n            \"y\")\n        , m_pidZ(\n            get(n, \"PIDs/Z/kp\"),\n            get(n, \"PIDs/Z/kd\"),\n            get(n, \"PIDs/Z/ki\"),\n            get(n, \"PIDs/Z/minOutput\"),\n            get(n, \"PIDs/Z/maxOutput\"),\n            get(n, \"PIDs/Z/integratorMin\"),\n            get(n, \"PIDs/Z/integratorMax\"),\n            \"z\")\n        , m_pidVx(\n            get(n, \"PIDs/Vx/kp\"),\n            get(n, \"PIDs/Vx/kd\"),\n            get(n, \"PIDs/Vx/ki\"),\n            get(n, \"PIDs/Vx/minOutput\"),\n            get(n, \"PIDs/Vx/maxOutput\"),\n            get(n, \"PIDs/Vx/integratorMin\"),\n            get(n, \"PIDs/Vx/integratorMax\"),\n            \"x\")\n        , m_pidVy(\n            get(n, \"PIDs/Vy/kp\"),\n            get(n, \"PIDs/Vy/kd\"),\n            get(n, \"PIDs/Vy/ki\"),\n            get(n, \"PIDs/Vy/minOutput\"),\n            get(n, \"PIDs/Vy/maxOutput\"),\n            get(n, \"PIDs/Vy/integratorMin\"),\n            get(n, \"PIDs/Vy/integratorMax\"),\n            \"x\")\n        , m_pidVz(\n            get(n, \"PIDs/Vz/kp\"),\n            get(n, \"PIDs/Vz/kd\"),\n            get(n, \"PIDs/Vz/ki\"),\n            get(n, \"PIDs/Vz/minOutput\"),\n            get(n, \"PIDs/Vz/maxOutput\"),\n            get(n, \"PIDs/Vz/integratorMin\"),\n            get(n, \"PIDs/Vz/integratorMax\"),\n            \"x\")                                \n        , m_pidYaw(\n            get(n, \"PIDs/Yaw/kp\"),\n            get(n, \"PIDs/Yaw/kd\"),\n            get(n, \"PIDs/Yaw/ki\"),\n            get(n, \"PIDs/Yaw/minOutput\"),\n            get(n, \"PIDs/Yaw/maxOutput\"),\n            get(n, \"PIDs/Yaw/integratorMin\"),\n            get(n, \"PIDs/Yaw/integratorMax\"),\n            \"yaw\")\n        , m_state(Idle)\n        , m_goal()\n        , m_cmdV()\n        , m_dronePositionWorld()\n        , m_droneVelocityWorld()\n        , m_droneEuler()\n        , m_pqrt()\n        , m_Cbe()\n        , m_subscribeGoal()\n        , m_subscribeCmdV()\n        , m_subscribeDroneState()\n        , m_subscribePQRT()\n        , m_serviceTakeoff()\n        , m_serviceLand()\n        , m_serviceGame()\n        , m_serviceAuto()\n        , m_serviceIdentRoll()\n        , m_serviceIdentPitch()\n        , m_serviceIdentYaw()\n        , m_serviceIdentThrust()\n        , m_thrust(0)\n        , m_startZ(0)\n        , m_trimThrust(43000)\n    {\n        ros::NodeHandle nh;\n        m_pubNav = nh.advertise<geometry_msgs::Twist>(\"cmd_vel\", 1);\n        m_pubCmdVtemp = nh.advertise<geometry_msgs::TwistStamped>(\"cmdVtemp\", 1);\n\n        m_subscribeGoal = nh.subscribe(\"goal\", 1, &Controller::goalChanged, this);\n        m_subscribeCmdV = nh.subscribe(\"cmdV\", 1, &Controller::cmdVChanged, this);\n        m_subscribeDroneState = nh.subscribe(\"mocap\", 1, &Controller::droneMoved, this);\n        m_subscribePQRT = nh.subscribe(\"pqrt\", 1, &Controller::pqrtChanged, this);\n\n        m_serviceTakeoff = nh.advertiseService(\"cftakeoff\", &Controller::takeoff, this);\n        m_serviceAuto = nh.advertiseService(\"cfauto\", &Controller::automatic, this);\n        m_serviceGame = nh.advertiseService(\"cfplay\", &Controller::play, this);\n        m_serviceLand = nh.advertiseService(\"cfland\", &Controller::land, this);\n\n        m_serviceIdentRoll   = nh.advertiseService(\"cmdroll\",   &Controller::cmdroll, this);\n        m_serviceIdentPitch  = nh.advertiseService(\"cmdpitch\",  &Controller::cmdpitch, this);\n        m_serviceIdentYaw    = nh.advertiseService(\"cmdyaw\",    &Controller::cmdyaw, this);\n        m_serviceIdentThrust = nh.advertiseService(\"cmdthrust\", &Controller::cmdthrust, this);\n    }\n\n    void run(double frequency)\n    {\n        ros::NodeHandle node;\n        ros::Timer timer = node.createTimer(ros::Duration(1.0/frequency), &Controller::iteration, this);\n        ros::spin();\n    }\n\n\nprivate:\n    void goalChanged(\n        const geometry_msgs::PoseStamped& msg)\n    {\n        m_goal[0] = msg.pose.position.x;\n        m_goal[1] = msg.pose.position.y;\n        m_goal[2] = msg.pose.position.z;\n    }\n\n    void cmdVChanged(\n        const geometry_msgs::Twist& msg)\n    {\n        m_cmdV[0] = msg.linear.x;\n        m_cmdV[1] = msg.linear.y;\n        m_cmdV[2] = msg.linear.z;\n    }\n\n    void droneMoved(\n        const crazyflie_controller::Mocap& msg)\n    {\n        m_dronePositionWorld[0] = msg.position[0];\n        m_dronePositionWorld[1] = msg.position[1];\n        m_dronePositionWorld[2] = msg.position[2];\n        m_droneVelocityWorld[0] = msg.velocity[0];\n        m_droneVelocityWorld[1] = msg.velocity[1];\n        m_droneVelocityWorld[2] = msg.velocity[2];\n        m_droneEuler = quaternion_to_euler_w(msg);\n        m_Cbe = quaternion_to_Cbe(msg);\n    }\n\n    void pqrtChanged(\n        const geometry_msgs::Twist& msg)\n    {\n        m_pqrt = msg;\n    }\n\n    bool takeoff(\n        std_srvs::Empty::Request& req,\n        std_srvs::Empty::Response& res)\n    {\n        ROS_INFO(\"Takeoff requested!\");\n        m_state = TakingOff;\n        m_startZ = m_dronePositionWorld[2];\n        return true;\n    }\n\n\n    bool land(\n        std_srvs::Empty::Request& req,\n        std_srvs::Empty::Response& res)\n    {\n        ROS_INFO(\"Landing requested!\");\n        m_state = Landing;\n        return true;\n    }\n\n    bool play(\n        std_srvs::Empty::Request& req,\n        std_srvs::Empty::Response& res)\n    {\n        ROS_INFO(\"playing requested!\");\n        m_state = Playing;\n        return true;\n    }\n\n    bool automatic(\n        std_srvs::Empty::Request& req,\n        std_srvs::Empty::Response& res)\n    {\n        ROS_INFO(\"automatic requested!\");\n        m_state = Automatic;\n        return true;\n    }\n\n    bool cmdroll(\n        std_srvs::Empty::Request& req,\n        std_srvs::Empty::Response& res)\n    {\n\n        ROS_INFO(\"roll model identification\");\n        m_state = IdentRoll;\n        return true;\n    }\n\n    bool cmdpitch(\n        std_srvs::Empty::Request& req,\n        std_srvs::Empty::Response& res)\n    {\n\n        ROS_INFO(\"pitch model identification\");\n        m_state = IdentPitch;\n        return true;\n    }\n\n    bool cmdyaw(\n        std_srvs::Empty::Request& req,\n        std_srvs::Empty::Response& res)\n    {\n\n        ROS_INFO(\"yaw model identification\");\n        m_state = IdentYaw;\n        return true;\n    }\n\n    bool cmdthrust(\n        std_srvs::Empty::Request& req,\n        std_srvs::Empty::Response& res)\n    {\n\n        ROS_INFO(\"thrust model identification\");\n        m_state = IdentThrust;\n        return true;\n    }\n\n    void pidXYZReset()\n    {\n        m_pidX.reset();\n        m_pidY.reset();\n        m_pidZ.reset();\n        m_pidYaw.reset();\n    }\n\n    void pidVReset()\n    {\n        m_pidVx.reset();\n        m_pidVy.reset();\n        m_pidVz.reset();\n    }\n\n    void pidReset()\n    {\n        pidXYZReset();\n        pidVReset();\n    }\n\n    Eigen::Vector3d quaternion_to_euler_w(const crazyflie_controller::Mocap& mocap)\n    {\n       float quat[4];\n       quat[0] = mocap.quaternion[0];\n       quat[1] = mocap.quaternion[1];\n       quat[2] = mocap.quaternion[2];\n       quat[3] = mocap.quaternion[3];\n       Eigen::Vector3d ans;\n       ans[0] = atan2(2.0 * (quat[3] * quat[2] + quat[0] * quat[1]), 1.0 - 2.0 * (quat[1] * quat[1] + quat[2] * quat[2]));\n       ans[1] = asin(2.0 * (quat[2] * quat[0] - quat[3] * quat[1]));\n       ans[2] = atan2(2.0 * (quat[3] * quat[0] + quat[1] * quat[2]), 1.0 - 2.0 * (quat[2] * quat[2] + quat[3] * quat[3]));\n       return ans;\n    }\n\n    Eigen::Matrix3d quaternion_to_Cbe(const crazyflie_controller::Mocap& mocap)\n    {\n        Eigen::Matrix3d m_Cbe;\n        Eigen::Matrix3d Ceb;\n        Eigen::Matrix<double, 3, 4> L;// Quaternion auxiliary matirx\n        Eigen::Matrix<double, 3, 4> R;// Quaternion auxiliary matirx\n        double q0, q1, q2, q3;\n        q0 = mocap.quaternion[0];\n        q1 = mocap.quaternion[1];\n        q2 = mocap.quaternion[2];\n        q3 = mocap.quaternion[3];\n         // update the auxiliary matrix\n        /*\n        L = [-q1 q0 q3 -q2;\n             -q2 -q3 q0 q1;\n             -q3 q2 -q1 q0]\n        R = [-q1 q0 -q3 q2;\n             -q2 q3 q0 -q1;\n             -q3 -q2 q1 q0]\n        R_IB = RL^T\n        */\n        L(0,0) = - q1;\n        L(1,0) = - q2;\n        L(2,0) = - q3;\n\n\n        L(0,1) = q0;\n        L(1,2) = q0;\n        L(2,3) = q0;\n\n        L(0,2) = q3;\n        L(0,3) = - q2;\n        L(1,1) = - q3;\n        L(1,3) = q1;\n        L(2,1) = q2;\n        L(2,2) = - q1;\n\n        R(0,0) = - q1;\n        R(1,0) = - q2;\n        R(2,0) = - q3;\n\n        R(0,1) = q0;\n        R(1,2) = q0;\n        R(2,3) = q0;\n\n        R(0,2) = - q3;\n        R(0,3) =  q2;\n        R(1,1) =  q3;\n        R(1,3) = - q1;\n        R(2,1) = - q2;\n        R(2,2) =  q1;\n\n        Ceb = R * L.transpose();\n        m_Cbe = Ceb.transpose();\n\n        return m_Cbe;\n    }\n\n    void iteration(const ros::TimerEvent& e)\n    {\n\n        float dt = e.current_real.toSec() - e.last_real.toSec();\n        switch(m_state)\n        {\n        case TakingOff:\n            {\n                if (m_dronePositionWorld[2] > m_startZ + 0.05 || m_thrust > m_trimThrust)\n                {\n                    pidReset();\n                    m_pidZ.setIntegral((m_thrust-m_trimThrust)/m_pidZ.ki());\n                    m_state = Automatic;\n                    m_thrust = m_trimThrust;\n                    ROS_INFO(\"Automatic!\");\n                }\n                else\n                {\n                    m_thrust += 12000 * dt;\n                    geometry_msgs::Twist msg;\n                    msg.linear.z = m_thrust;\n                    m_pubNav.publish(msg);\n                }\n\n            }\n            break;\n        case Landing:\n            {\n                 m_goal[0] = m_dronePositionWorld[0];\n                 m_goal[1] = m_dronePositionWorld[1];\n                 // m_goal[2] = m_startZ + 0.05;\n                 m_goal[2] = 0.1;\n                // if (m_dronePositionWorld[2] <= m_startZ + 0.1) {\n                if (m_dronePositionWorld[2] <= 0.15) {\n                    m_state = Idle;\n                    geometry_msgs::Twist msg;\n                    m_pubNav.publish(msg);\n                }\n            }\n\n            // intentional fall-thru\n        case Automatic:\n            {\n//                std::cout<<\"automatic\";\n//                pidVReset();\n                Eigen::Vector3d positionErr = m_goal - m_dronePositionWorld;\n                // std::cout<<\"cmdVz, dz\\t\"<<m_goal[2]<<\"\\t\\t\"<<positionErr[2]<<std::endl;\n\n                Eigen::Vector3d cmdV;\n                cmdV[0] = m_pidX.update(0.0, positionErr[0]);\n                cmdV[1] = m_pidY.update(0.0, positionErr[1]);\n                cmdV[2] = m_pidZ.update(0.0, positionErr[2]);\n                // std::cout<<\"cmdVz, dx\\t\"<<m_goal[0]*100<<\"\\t\\t\"<<m_dronePositionWorld[0]*100<<std::endl;\n                // std::cout<<\"cmdVz, dy\\t\"<<m_goal[1]*100<<\"\\t\\t\"<<m_dronePositionWorld[1]*100<<std::endl;\n                // std::cout<<\"cmdVz, dz\\t\"<<m_goal[2]*100<<\"\\t\\t\"<<m_dronePositionWorld[2]*100<<std::endl;\n\n                geometry_msgs::TwistStamped cmdVtemp;\n                cmdVtemp.header.stamp = ros::Time::now();\n                cmdVtemp.twist.linear.x = cmdV[0];\n                cmdVtemp.twist.linear.y = cmdV[1];\n                cmdVtemp.twist.linear.z = cmdV[2];\n//                ROS_INFO(\"publish intermeidate velocity cmd\");\n                m_pubCmdVtemp.publish(cmdVtemp);\n\n                Eigen::Vector3d velocityErrBody = m_Cbe*(cmdV - m_droneVelocityWorld);\n                geometry_msgs::Twist msg;\n                msg.linear.x = m_pidVx.update(0, velocityErrBody[0]);\n                msg.linear.y = m_pidVy.update(0, velocityErrBody[1]);\n                msg.linear.z =  m_pidVz.update(0, velocityErrBody[2]) + m_trimThrust;\n                msg.angular.z = m_pidYaw.update(0.0, m_droneEuler[2]);\n                m_pubNav.publish(msg);\n            }\n            break;\n\n        case Playing:\n            {\n                Eigen::Vector3d positionErr = m_goal - m_dronePositionWorld;\n                Eigen::Vector3d cmdV;\n                cmdV[0] = m_cmdV[0];\n                cmdV[1] = m_cmdV[1];\n                cmdV[2] = m_pidZ.update(0.0, positionErr[2]);\n\n                geometry_msgs::TwistStamped cmdVtemp;\n                cmdVtemp.header.stamp = ros::Time::now();\n                cmdVtemp.twist.linear.x = cmdV[0];\n                cmdVtemp.twist.linear.y = cmdV[1];\n                cmdVtemp.twist.linear.z = cmdV[2];\n//                ROS_INFO(\"publish intermeidate velocity cmd\");\n                m_pubCmdVtemp.publish(cmdVtemp);\n\n                Eigen::Vector3d velocityErrBody = m_Cbe*(cmdV - m_droneVelocityWorld);\n                geometry_msgs::Twist msg;\n                msg.linear.x = m_pidVx.update(0, velocityErrBody[0]);\n                msg.linear.y = m_pidVy.update(0, velocityErrBody[1]);\n                msg.linear.z = m_pidVz.update(0, velocityErrBody[2]) + m_trimThrust;\n                msg.angular.z = m_pidYaw.update(0.0, m_droneEuler[2]);\n                m_pubNav.publish(msg);                \n            }\n            break;\n\n        case IdentRoll:\n            {\n                Eigen::Vector3d positionErr = m_goal - m_dronePositionWorld;\n                Eigen::Vector3d cmdV;\n                cmdV[0] = m_pidX.update(0.0, positionErr[0]);\n                cmdV[1] = m_pidY.update(0.0, positionErr[1]);\n                cmdV[2] = m_pidZ.update(0.0, positionErr[2]);\n\n                Eigen::Vector3d velocityErrBody = m_Cbe*(cmdV - m_droneVelocityWorld);\n                geometry_msgs::Twist msg;\n                msg.linear.x = m_pidVx.update(0, velocityErrBody[0]);\n                msg.linear.y = m_pqrt.linear.y;\n                msg.linear.z = m_pidVz.update(0, velocityErrBody[2]) + m_trimThrust;\n                msg.angular.z = m_pidYaw.update(0.0, m_droneEuler[2]);\n                m_pubNav.publish(msg);\n            }\n            break;\n\n        case IdentPitch:\n            {\n                Eigen::Vector3d positionErr = m_goal - m_dronePositionWorld;\n                Eigen::Vector3d cmdV;\n                cmdV[0] = m_pidX.update(0.0, positionErr[0]);\n                cmdV[1] = m_pidY.update(0.0, positionErr[1]);\n                cmdV[2] = m_pidZ.update(0.0, positionErr[2]);\n\n                Eigen::Vector3d velocityErrBody = m_Cbe*(cmdV - m_droneVelocityWorld);\n                geometry_msgs::Twist msg;\n                msg.linear.x = m_pqrt.linear.x;\n                msg.linear.y = m_pidVy.update(0, velocityErrBody[1]);\n                msg.linear.z = m_pidVz.update(0, velocityErrBody[2]) + m_trimThrust;\n                msg.angular.z = m_pidYaw.update(0.0, m_droneEuler[2]);\n                m_pubNav.publish(msg);\n            }\n            break;\n\n        case IdentYaw:\n            {\n                Eigen::Vector3d positionErr = m_goal - m_dronePositionWorld;\n                Eigen::Vector3d cmdV;\n                cmdV[0] = m_pidX.update(0.0, positionErr[0]);\n                cmdV[1] = m_pidY.update(0.0, positionErr[1]);\n                cmdV[2] = m_pidZ.update(0.0, positionErr[2]);\n\n                Eigen::Vector3d velocityErrBody = m_Cbe*(cmdV - m_droneVelocityWorld);\n                geometry_msgs::Twist msg;\n                msg.linear.x = m_pidVx.update(0, velocityErrBody[0]);\n                msg.linear.y = m_pidVy.update(0, velocityErrBody[1]);\n                msg.linear.z =  m_pidVz.update(0, velocityErrBody[2]) + m_trimThrust;\n                msg.angular.z = m_pqrt.angular.z;\n                m_pubNav.publish(msg);\n            }\n            break;\n\n        case IdentThrust:\n            {\n                Eigen::Vector3d positionErr = m_goal - m_dronePositionWorld;\n                Eigen::Vector3d cmdV;\n                cmdV[0] = m_pidX.update(0.0, positionErr[0]);\n                cmdV[1] = m_pidY.update(0.0, positionErr[1]);\n                cmdV[2] = m_pidZ.update(0.0, positionErr[2]);\n\n                Eigen::Vector3d velocityErrBody = m_Cbe*(cmdV - m_droneVelocityWorld);\n                geometry_msgs::Twist msg;\n                msg.linear.x = m_pidVx.update(0, velocityErrBody[0]);\n                msg.linear.y = m_pidVy.update(0, velocityErrBody[1]);\n                msg.linear.z =  m_pqrt.linear.z + m_trimThrust;\n                msg.angular.z = m_pidYaw.update(0.0, m_droneEuler[2]);\n                m_pubNav.publish(msg);\n            }\n            break;\n\n        case Idle:\n            {\n                geometry_msgs::Twist msg;\n                m_pubNav.publish(msg);\n            }\n            break;\n        }\n    }\n\nprivate:\n    enum State\n    {\n        Idle = 0,\n        Automatic = 1,\n        TakingOff = 2,\n        Landing = 3,\n        Playing = 4,\n        IdentRoll = 5,\n        IdentPitch = 6,\n        IdentYaw = 7,\n        IdentThrust = 8,\n    };\n\nprivate:\n    ros::Publisher m_pubNav;\n    ros::Publisher m_pubCmdVtemp;\n    PID m_pidX;\n    PID m_pidY;\n    PID m_pidZ;\n    PID m_pidVx;\n    PID m_pidVy;\n    PID m_pidVz;\n    PID m_pidYaw;\n    State m_state;\n    Eigen::Vector3d m_goal;\n    Eigen::Vector3d m_cmdV;\n    Eigen::Vector3d m_dronePositionWorld;\n    Eigen::Vector3d m_droneVelocityWorld;\n    Eigen::Vector3d m_droneEuler;\n    Eigen::Matrix3d m_Cbe;\n    geometry_msgs::Twist m_pqrt;\n    ros::Subscriber m_subscribeGoal;\n    ros::Subscriber m_subscribeCmdV;\n    ros::Subscriber m_subscribeDroneState;\n    ros::Subscriber m_subscribePQRT;\n    ros::ServiceServer m_serviceTakeoff;\n    ros::ServiceServer m_serviceLand;\n    ros::ServiceServer m_serviceGame;\n    ros::ServiceServer m_serviceAuto;\n    ros::ServiceServer m_serviceIdentRoll;\n    ros::ServiceServer m_serviceIdentPitch;\n    ros::ServiceServer m_serviceIdentYaw;\n    ros::ServiceServer m_serviceIdentThrust;\n    float m_thrust;\n    float m_trimThrust;\n    float m_startZ;\n};\n\n\nint main(int argc, char **argv)\n{\n  ros::init(argc, argv, \"controller\");\n\n  // Read parameters\n  ros::NodeHandle n(\"~\");\n  // std::string worldFrame;\n  // n.param<std::string>(\"worldFrame\", worldFrame, \"/world\");\n  // std::string frame;\n  // n.getParam(\"frame\", frame);\n  double frequency;\n  n.param(\"frequency\", frequency, 50.0);\n\n  // Controller controller(worldFrame, frame, n);\n  Controller controller(n);\n  controller.run(frequency);\n\n  return 0;\n\n}\n", "meta": {"hexsha": "bc1212db8e7906c7708276c5a332b9549767eb62", "size": 19169, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "crazyflie_controller/src/controller.cpp", "max_stars_repo_name": "FloraHF/cfros", "max_stars_repo_head_hexsha": "95ef743500a123ef4a66526f7e9904f02484658e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "crazyflie_controller/src/controller.cpp", "max_issues_repo_name": "FloraHF/cfros", "max_issues_repo_head_hexsha": "95ef743500a123ef4a66526f7e9904f02484658e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "crazyflie_controller/src/controller.cpp", "max_forks_repo_name": "FloraHF/cfros", "max_forks_repo_head_hexsha": "95ef743500a123ef4a66526f7e9904f02484658e", "max_forks_repo_licenses": ["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.4761904762, "max_line_length": 122, "alphanum_fraction": 0.5211017789, "num_tokens": 5368, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996142, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.47149847929489974}}
{"text": "\n#include <iostream>\n#include <stack>\n#include <queue>\n\n#include <boost/graph/adjacency_list.hpp>\n\n#include \"dfs.hpp\"\n#include \"fifodfs.hpp\"\n#include \"rdfs.hpp\"\n\n#include \"options.hpp\"\n#include \"debug.hpp\"\n#include \"test_suite.hpp\"\n#include \"range.hpp\"\n\nusing namespace std;\n\nboost::property<boost::edge_color_t, boost::default_color_type> typedef color;\nboost::adjacency_list<boost::hash_setS, boost::vecS, boost::undirectedS,\n    boost::no_property, color> typedef graph;\n\ntypedef pair<int, int> node_pair;\n\ntemplate <class Graph>\nGraph dfs(Graph const & G, int v) {\n  Graph T;\n  int parent;\n  stack<node_pair> S;\n  vector<bool> V(num_vertices(G));\n  S.emplace(-1, v);\n  while(!S.empty()) {\n    tie(parent, v) = S.top();\n    S.pop();\n    if(!V[v]) {\n      V[v] = true;\n      if(parent > -1) add_edge(parent, v, T);\n      for(auto w : shuffled(adjacent_vertices(v, G))) {\n        S.emplace(v, w);\n      }\n    }\n  }\n  show(\"tree-dfs.dot\", G, T);\n  return T;\n}\n\ntemplate <class Graph>\nGraph dfs2(Graph const & G, int v) {\n  vector<bool> V(num_vertices(G));\n  stack<node_pair> E;\n  Graph T;\n  while(true) {\n    V[v] = true;\n\n    int x = -1, y = -1;\n    for(auto w : range(adjacent_vertices(v, G)))\n      if(!V[w]) {\n        tie(x, y) = tie(v, w);\n        E.emplace(v, w);\n      }\n\n    if(y == -1) {\n      while(!E.empty() && V[E.top().second]) E.pop();\n      if(E.empty()) break;\n      tie(x, y) = E.top();\n    } else {\n      E.pop();\n    }\n\n    add_edge(x, y, T);\n\n    v = y;\n  }\n  return T;\n}\n\ntemplate <class Graph>\nGraph dfs_fifo(Graph const & G, int v) {\n  int rank;\n  vector<int> V(num_vertices(G), rank = 0);\n  queue<node_pair> E;\n  Graph T;\n  while(true) {\n    V[v] = ++rank;\n\n    int x, y = -1;\n    for(auto w : range(adjacent_vertices(v, G)))\n      if(V[w] == 0) {\n        tie(x, y) = tie(v, w);\n        break;\n      }\n\n    if(y == -1) {\n      while(!E.empty() && V[E.front().second] != 0) E.pop();\n      if(E.empty()) break;\n      tie(x, y) = E.front();\n    }\n\n    for(int w : range(adjacent_vertices(x, G)))\n      if(w != y && V[w] == 0) {\n        E.emplace(x, w);\n      }\n\n    add_edge(x, y, T);\n\n    v = y;\n  }\n  show(\"tree-dfs-fifo.dot\", G, T);\n  return T;\n}\n\ntemplate <class Graph>\nGraph dfs_fifo2(Graph const & G, int v) {\n  vector<bool> V(num_vertices(G));\n  queue<node_pair> E;\n  Graph T;\n  while(true) {\n    V[v] = true;\n\n    int x = -1, y = -1;\n    for(auto w : range(adjacent_vertices(v, G)))\n      if(!V[w]) {\n        if(y == -1) tie(x, y) = tie(v, w);\n        else E.emplace(v, w);\n      }\n\n    if(y == -1) {\n      while(!E.empty() && V[E.front().second]) E.pop();\n      if(E.empty()) break;\n      tie(x, y) = E.front();\n    }\n\n    add_edge(x, y, T);\n\n    v = y;\n  }\n  return T;\n}\n\ntemplate <class Graph>\nGraph bfs(Graph const & G, int v) {\n  Graph T;\n  int parent;\n  queue<node_pair> Q;\n  vector<bool> V(num_vertices(G));\n  Q.emplace(-1, v);\n  V[v] = true;\n  while(!Q.empty()) {\n    tie(parent, v) = Q.front();\n    Q.pop();\n    for(auto w : range(adjacent_vertices(v, G))) {\n      if(!V[w]) {\n        V[w] = true;\n        add_edge(v, w, T);\n        Q.emplace(v, w);\n      }\n    }\n  }\n  show(\"tree-bfs.dot\", G, T);\n  return T;\n}\n\ntemplate<class Graph>\nbool isomorphic(Graph const & A, Graph const & B) {\n  if(num_vertices(A) != num_vertices(B))\n    return false;\n  if(num_edges(A) != num_edges(B))\n      return false;\n  for(auto e : range(edges(A)))\n    if(!edge(source(e, A), target(e, A), B).second)\n      return false;\n  return true;\n}\n\nint main(int argc, char** argv) {\n  options opt(argc, argv);\n  int z = opt.get<int>(\"-z\", 1);\n  int n = opt.get<int>(\"-n\", 20);\n  float p = opt.get<float>(\"-p\", 0.2);\n\n  std::srand ( unsigned ( std::time(0) ) );\n\n  ios_base::sync_with_stdio(0);\n\n  test_suite<graph> suite(\"gnp\", z, n, p);\n\n  for(auto G : suite) {\n    auto tree1 = rdfs_tree<graph, graph>(G);\n    auto tree2 = rdfs_tree<graph, graph>(G);\n    if(!isomorphic(tree1, tree2)) {\n      show(\"iso-12-1.dot\", G, tree1);\n      show(\"iso-12-2.dot\", G, tree2);\n      return 1;\n    }\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "b8ec16a2abf8f821e3d5d468a6a0deeb28afb6a9", "size": 4019, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "prototype/trees.cpp", "max_stars_repo_name": "arekolek/MaxIST", "max_stars_repo_head_hexsha": "6a8b49152cfbf34c1c2728f64b1457a23824fe0d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "prototype/trees.cpp", "max_issues_repo_name": "arekolek/MaxIST", "max_issues_repo_head_hexsha": "6a8b49152cfbf34c1c2728f64b1457a23824fe0d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "prototype/trees.cpp", "max_forks_repo_name": "arekolek/MaxIST", "max_forks_repo_head_hexsha": "6a8b49152cfbf34c1c2728f64b1457a23824fe0d", "max_forks_repo_licenses": ["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.1959798995, "max_line_length": 78, "alphanum_fraction": 0.5404329435, "num_tokens": 1274, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321964553657, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.4714427932507216}}
{"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_ENUMERATE_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_ENUMERATE_HPP_INCLUDED\n\nnamespace boost { namespace simd\n{\n#if defined(DOXYGEN_ONLY)\n  /*!\n    @ingroup group-swar\n    Generates a value containing sequentially increasing values, starting with @c seed and\n    repetitively evaluating @c seed+=step.\n\n    @par Scalar Semantic:\n    For any type @c T , the following code:\n    @code\n    auto r = enumerate<T>(seed, step);\n    @endcode\n    is equivalent to:\n    @code\n    T r{seed};\n    @endcode\n\n    @par SIMD Semantic:\n    For any type @c T and integral constant @c N, the following code:\n    @code\n    auto r = enumerate<boost::simd::pack<T,N>>(seed, step);\n    @endcode\n    is equivalent to:\n    @code\n    boost::simd::pack<T,N> r{seed, seed+step, ..., seed+(N-1)*step};\n    @endcode\n\n    @param seed Initial value of store, equals to @c 0 by default.\n    @param step Increment to apply on each subsequent generated value, equals to @c 1 by default.\n    @return A value containing the sequence of value generated from @c seed and @c step\n  **/\n  template<typename T, typename B, typename S> T enumerate(const B& seed = 0, const S& step = 1);\n#endif\n} }\n\n#include <boost/simd/function/scalar/enumerate.hpp>\n#include <boost/simd/function/simd/enumerate.hpp>\n\n#endif\n", "meta": {"hexsha": "62eacbc3ae33f8fcc47ebb0bb7ea180145ae8f54", "size": 1686, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/enumerate.hpp", "max_stars_repo_name": "nickporubsky/boost-simd-clone", "max_stars_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_stars_repo_licenses": ["BSL-1.0"], "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": "include/boost/simd/function/enumerate.hpp", "max_issues_repo_name": "nickporubsky/boost-simd-clone", "max_issues_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/function/enumerate.hpp", "max_forks_repo_name": "nickporubsky/boost-simd-clone", "max_forks_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_forks_repo_licenses": ["BSL-1.0"], "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": 31.2222222222, "max_line_length": 100, "alphanum_fraction": 0.6126927639, "num_tokens": 397, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.47144278375069376}}
{"text": "// The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt\r\n/*\r\n    This is an example illustrating the use of the kkmeans object \r\n    and spectral_cluster() routine from the dlib C++ Library.\r\n\r\n    The kkmeans object is an implementation of a kernelized k-means clustering \r\n    algorithm.  It is implemented by using the kcentroid object to represent \r\n    each center found by the usual k-means clustering algorithm.  \r\n\r\n    So this object allows you to perform non-linear clustering in the same way \r\n    a svm classifier finds non-linear decision surfaces.  \r\n    \r\n    This example will make points from 3 classes and perform kernelized k-means \r\n    clustering on those points.  It will also do the same thing using spectral \r\n    clustering.\r\n\r\n    The classes are as follows:\r\n        - points very close to the origin\r\n        - points on the circle of radius 10 around the origin\r\n        - points that are on a circle of radius 4 but not around the origin at all\r\n*/\r\n\r\n#include <iostream>\r\n#include <vector>\r\n\r\n#include <dlib/clustering.h>\r\n#include <dlib/rand.h>\r\n\r\nusing namespace std;\r\nusing namespace dlib;\r\n\r\nint main()\r\n{\r\n    // Here we declare that our samples will be 2 dimensional column vectors.  \r\n    // (Note that if you don't know the dimensionality of your vectors at compile time\r\n    // you can change the 2 to a 0 and then set the size at runtime)\r\n    typedef matrix<double,2,1> sample_type;\r\n\r\n    // Now we are making a typedef for the kind of kernel we want to use.  I picked the\r\n    // radial basis kernel because it only has one parameter and generally gives good\r\n    // results without much fiddling.\r\n    typedef radial_basis_kernel<sample_type> kernel_type;\r\n\r\n\r\n    // Here we declare an instance of the kcentroid object.  It is the object used to \r\n    // represent each of the centers used for clustering.  The kcentroid has 3 parameters \r\n    // you need to set.  The first argument to the constructor is the kernel we wish to \r\n    // use.  The second is a parameter that determines the numerical accuracy with which \r\n    // the object will perform part of the learning algorithm.  Generally, smaller values \r\n    // give better results but cause the algorithm to attempt to use more dictionary vectors \r\n    // (and thus run slower and use more memory).  The third argument, however, is the \r\n    // maximum number of dictionary vectors a kcentroid is allowed to use.  So you can use\r\n    // it to control the runtime complexity.  \r\n    kcentroid<kernel_type> kc(kernel_type(0.1),0.01, 8);\r\n\r\n    // Now we make an instance of the kkmeans object and tell it to use kcentroid objects\r\n    // that are configured with the parameters from the kc object we defined above.\r\n    kkmeans<kernel_type> test(kc);\r\n\r\n    std::vector<sample_type> samples;\r\n    std::vector<sample_type> initial_centers;\r\n\r\n    sample_type m;\r\n\r\n    dlib::rand rnd;\r\n\r\n    // we will make 50 points from each class\r\n    const long num = 50;\r\n\r\n    // make some samples near the origin\r\n    double radius = 0.5;\r\n    for (long i = 0; i < num; ++i)\r\n    {\r\n        double sign = 1;\r\n        if (rnd.get_random_double() < 0.5)\r\n            sign = -1;\r\n        m(0) = 2*radius*rnd.get_random_double()-radius;\r\n        m(1) = sign*sqrt(radius*radius - m(0)*m(0));\r\n\r\n        // add this sample to our set of samples we will run k-means \r\n        samples.push_back(m);\r\n    }\r\n\r\n    // make some samples in a circle around the origin but far away\r\n    radius = 10.0;\r\n    for (long i = 0; i < num; ++i)\r\n    {\r\n        double sign = 1;\r\n        if (rnd.get_random_double() < 0.5)\r\n            sign = -1;\r\n        m(0) = 2*radius*rnd.get_random_double()-radius;\r\n        m(1) = sign*sqrt(radius*radius - m(0)*m(0));\r\n\r\n        // add this sample to our set of samples we will run k-means \r\n        samples.push_back(m);\r\n    }\r\n\r\n    // make some samples in a circle around the point (25,25) \r\n    radius = 4.0;\r\n    for (long i = 0; i < num; ++i)\r\n    {\r\n        double sign = 1;\r\n        if (rnd.get_random_double() < 0.5)\r\n            sign = -1;\r\n        m(0) = 2*radius*rnd.get_random_double()-radius;\r\n        m(1) = sign*sqrt(radius*radius - m(0)*m(0));\r\n\r\n        // translate this point away from the origin\r\n        m(0) += 25;\r\n        m(1) += 25;\r\n\r\n        // add this sample to our set of samples we will run k-means \r\n        samples.push_back(m);\r\n    }\r\n\r\n    // tell the kkmeans object we made that we want to run k-means with k set to 3. \r\n    // (i.e. we want 3 clusters)\r\n    test.set_number_of_centers(3);\r\n\r\n    // You need to pick some initial centers for the k-means algorithm.  So here\r\n    // we will use the dlib::pick_initial_centers() function which tries to find\r\n    // n points that are far apart (basically).  \r\n    pick_initial_centers(3, initial_centers, samples, test.get_kernel());\r\n\r\n    // now run the k-means algorithm on our set of samples.  \r\n    test.train(samples,initial_centers);\r\n\r\n    // now loop over all our samples and print out their predicted class.  In this example\r\n    // all points are correctly identified.\r\n    for (unsigned long i = 0; i < samples.size()/3; ++i)\r\n    {\r\n        cout << test(samples[i]) << \" \";\r\n        cout << test(samples[i+num]) << \" \";\r\n        cout << test(samples[i+2*num]) << \"\\n\";\r\n    }\r\n\r\n    // Now print out how many dictionary vectors each center used.  Note that \r\n    // the maximum number of 8 was reached.  If you went back to the kcentroid \r\n    // constructor and changed the 8 to some bigger number you would see that these\r\n    // numbers would go up.  However, 8 is all we need to correctly cluster this dataset.\r\n    cout << \"num dictionary vectors for center 0: \" << test.get_kcentroid(0).dictionary_size() << endl;\r\n    cout << \"num dictionary vectors for center 1: \" << test.get_kcentroid(1).dictionary_size() << endl;\r\n    cout << \"num dictionary vectors for center 2: \" << test.get_kcentroid(2).dictionary_size() << endl;\r\n\r\n\r\n    // Finally, we can also solve the same kind of non-linear clustering problem with\r\n    // spectral_cluster().  The output is a vector that indicates which cluster each sample\r\n    // belongs to.  Just like with kkmeans, it assigns each point to the correct cluster.\r\n    std::vector<unsigned long> assignments = spectral_cluster(kernel_type(0.1), samples, 3);\r\n    cout << mat(assignments) << endl;\r\n\r\n}\r\n\r\n\r\n", "meta": {"hexsha": "ce08d2f8919e57f317fd9d4641c89289ac03956e", "size": 6396, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/kkmeans_ex.cpp", "max_stars_repo_name": "ckproc/dlib-19.7", "max_stars_repo_head_hexsha": "0ca40f5e85de2436e557bee9a805d3987d2d9507", "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/kkmeans_ex.cpp", "max_issues_repo_name": "ckproc/dlib-19.7", "max_issues_repo_head_hexsha": "0ca40f5e85de2436e557bee9a805d3987d2d9507", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2018-02-27T15:44:25.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-28T01:26:03.000Z", "max_forks_repo_path": "examples/kkmeans_ex.cpp", "max_forks_repo_name": "ckproc/dlib-19.7", "max_forks_repo_head_hexsha": "0ca40f5e85de2436e557bee9a805d3987d2d9507", "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.264516129, "max_line_length": 104, "alphanum_fraction": 0.6486866792, "num_tokens": 1567, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.4714427756643667}}
{"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\u00e4nkt), 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_MIN_POS_INCLUDE\n#define MTL_MIN_POS_INCLUDE\n\n#include <utility>\n\n#include <boost/numeric/linear_algebra/identity.hpp>\n#include <boost/numeric/mtl/concept/collection.hpp>\n#include <boost/numeric/mtl/utility/pos_type.hpp>\n#include <boost/numeric/mtl/utility/exception.hpp>\n#include <boost/numeric/mtl/operation/look_at_each_nonzero.hpp>\n\n\nnamespace mtl {\n\n    namespace vec {\n\t\n\ttemplate <typename Vector>\n\tstruct min_pos_functor\n\t{\n\t    typedef typename Collection<Vector>::value_type       value_type;\n\t    typedef typename mtl::traits::pos_type<Vector>::type  pos_type;\n\t    typedef std::pair<value_type, pos_type>               result_type;\n\n\t    // initialize with max value and max position\n\t    min_pos_functor() : value(math::identity(math::min<result_type>(), result_type())) {} \n\n\t    void operator()(const value_type& x, const pos_type& p)\n\t    {\n\t\tif (x < value.first)\n\t\t    value= std::make_pair(x, p);\n \t    }\n\n\t    bool unchanged() const { return value.second == math::identity(math::min<pos_type>(), pos_type()); }\n\n\t    result_type  value;\n\t};\n\t///Returns position of minimal entry of %vector v\n\ttemplate <typename Vector>\n\ttypename min_pos_functor<Vector>::pos_type\n\tinline min_pos(const Vector& v)\n\t{\n\t    min_pos_functor<Vector> f;\n\t    look_at_each_nonzero_pos(v, f);\n\n\t    MTL_DEBUG_THROW_IF(f.unchanged(), runtime_error(\"min_pos cannot be applied on empty container\"));\n\t    return f.value.second;\n\t}\n\n    } // namespace vector\n\n    namespace mat {\n\n\tusing mtl::vec::min_pos;\n    }\n\n\n} // namespace mtl\n\n#endif // MTL_MIN_POS_INCLUDE\n", "meta": {"hexsha": "33c2ed155c104be848066b7b7064cacbba512ef5", "size": 2013, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/mtl/operation/min_pos.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/min_pos.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/min_pos.hpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 27.9583333333, "max_line_length": 105, "alphanum_fraction": 0.7019374069, "num_tokens": 495, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.4714427756643667}}
{"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 file if you have any questions.\n// Author: Chris Sweeney (cmsweeney@cs.ucsb.edu)\n\n#include \"gtest/gtest.h\"\n#include <Eigen/Core>\n#include <glog/logging.h>\n#include <math.h>\n#include <random>\n\n#include \"theia/sfm/pose/five_point_focal_length_radial_distortion.h\"\n#include \"theia/test/test_utils.h\"\n\nnamespace theia {\n\nnamespace {\n\nusing Eigen::Array;\nusing Eigen::Map;\nusing Eigen::Matrix;\nusing Eigen::Matrix3d;\nusing Eigen::Vector2d;\nusing Eigen::Vector3d;\n\nvoid P5pfrTestWithNoise(const Matrix3d& gt_rotation,\n                        const Vector3d& gt_translation,\n                        const double focal_length,\n                        const double radial_distortion,\n                        const std::vector<Vector3d>& world_points_vector,\n                        const double noise,\n                        const double reproj_tolerance) {\n  Map<const Matrix<double, 3, 5> > world_points(world_points_vector[0].data());\n\n  // Camera intrinsics matrix.\n  const Matrix3d camera_matrix =\n      Eigen::DiagonalMatrix<double, 3>(1.0, 1.0, 1.0 / focal_length);\n  // Create the projection matrix P = K * [R t].\n  Matrix<double, 3, 4> gt_projection;\n  gt_projection << gt_rotation, gt_translation;\n  gt_projection = camera_matrix * gt_projection;\n\n  // Reproject 3D points to get undistorted image points.\n  Matrix<double, 2, 5> undistorted_image_point =\n      (gt_projection * world_points.colwise().homogeneous())\n          .colwise()\n          .hnormalized();\n\n  // Determine radius of undistorted points and use that to compute the radius\n  // of the distorted points.\n  Array<double, 1, 5> radius_undistorted =\n      undistorted_image_point.colwise().norm();\n  Array<double, 1, 5> radius_distorted =\n      (1.0 -\n       (1.0 - 4.0 * radial_distortion * radius_undistorted.square()).sqrt()) /\n      (2.0 * radial_distortion * radius_undistorted);\n  Array<double, 1, 5> distortion_vec = radius_distorted / radius_undistorted;\n\n  // Apply radial distortion.\n  std::vector<Vector2d> distorted_image_points_vector(5);\n  Map<Matrix<double, 2, 5> > distorted_image_point(\n      distorted_image_points_vector[0].data());\n  distorted_image_point = undistorted_image_point.cwiseProduct(\n      distortion_vec.matrix().replicate<2, 1>());\n\n  // Add noise to distorted image points.\n  if (noise) {\n    std::default_random_engine generator;\n    std::normal_distribution<double> distribution(0.0, noise);\n    for (int i = 0; i < 5; i++) {\n      distorted_image_point.col(i).x() += distribution(generator);\n      distorted_image_point.col(i).y() += distribution(generator);\n    }\n  }\n\n  // Run P5Pfr algorithm.\n  std::vector<Matrix<double, 3, 4> > soln_projection;\n  std::vector<std::vector<double> > soln_distortion;\n  CHECK(\n      theia::FivePointFocalLengthRadialDistortion(distorted_image_points_vector,\n                                                  world_points_vector,\n                                                  1,\n                                                  &soln_projection,\n                                                  &soln_distortion));\n\n  bool matched_transform = false;\n  for (int i = 0; i < 4; ++i) {\n    matched_transform = true;\n    // Check the reprojection error.\n    for (int n = 0; n < 5; n++) {\n      const double distortion_w =\n          1.0 +\n          soln_distortion[i][0] * distorted_image_point.col(n).squaredNorm();\n      Eigen::Vector2d undist_pt = distorted_image_point.col(n) / distortion_w;\n      Eigen::Vector3d reproj_pt =\n          soln_projection[i] * world_points.col(n).homogeneous();\n      const double reproj_error =\n          (undist_pt - reproj_pt.hnormalized()).squaredNorm();\n      if (reproj_error > reproj_tolerance) {\n        matched_transform = false;\n        break;\n      }\n    }\n\n    if (matched_transform) {\n      break;\n    }\n  }\n  // One of the solutions must have been a valid solution.\n  EXPECT_TRUE(matched_transform);\n}\n\nvoid BasicTest(const double noise, const double reproj_tolerance) {\n  // focal length (values used in the ICCV paper)\n  const double focal_length = 1.3;\n  // radial distortion (values used in the ICCV paper)\n  const double radial_distortion = -0.35;\n\n  const double x = -0.10;  // rotation of the view around x axis\n  const double y = -0.20;  // rotation of the view around y axis\n  const double z = 0.30;   // rotation of the view around z axis\n\n  // Create a ground truth pose.\n  Matrix3d Rz, Ry, Rx;\n  Rz << cos(z), sin(z), 0, -sin(z), cos(z), 0, 0, 0, 1;\n  Ry << cos(y), 0, -sin(y), 0, 1, 0, sin(y), 0, cos(y);\n  Rx << 1, 0, 0, 0, cos(x), sin(x), 0, -sin(x), cos(x);\n  const Matrix3d gt_rotation = Rz * Ry * Rx;\n  const Vector3d gt_translation =\n      Vector3d(-0.00950692, 000.0171496, 000.0508743);\n\n  // Create 3D world points that are viable based on the camera intrinsics and\n  // extrinsics.\n  std::vector<Vector3d> world_points_vector(5);\n  Map<Matrix<double, 3, 5> > world_points(world_points_vector[0].data());\n  world_points << -0.42941, 0.000621211, -0.350949, -1.45205, -1.294, 0.415794,\n      -0.556605, -1.92898, -1.89976, -1.12445, 1.4949, 0.838307, 1.41972,\n      1.25756, 0.805163;\n  P5pfrTestWithNoise(gt_rotation,\n                     gt_translation,\n                     focal_length,\n                     radial_distortion,\n                     world_points_vector,\n                     noise,\n                     reproj_tolerance);\n}\n\nvoid PlanarTestWithNoise(const double noise, const double reproj_tolerance) {\n  // focal length (values used in the ICCV paper)\n  const double focal_length = 1.3;\n  // radial distortion (values used in the ICCV paper)\n  const double radial_distortion = -0.35;\n  const double size = 100;\n  const double depth = 150;\n\n  const double x = -0.10;  // rotation of the view around x axis\n  const double y = -0.20;  // rotation of the view around y axis\n  const double z = 0.30;   // rotation of the view around z axis\n\n  // Create a ground truth pose.\n  Matrix3d Rz, Ry, Rx;\n  Rz << cos(z), sin(z), 0, -sin(z), cos(z), 0, 0, 0, 1;\n  Ry << cos(y), 0, -sin(y), 0, 1, 0, sin(y), 0, cos(y);\n  Rx << 1, 0, 0, 0, cos(x), sin(x), 0, -sin(x), cos(x);\n  const Matrix3d gt_rotation = Rz * Ry * Rx;\n  const Vector3d gt_translation =\n      Vector3d(-0.00950692, 000.0171496, 000.0508743);\n\n  // Create 3D world points that are viable based on the camera intrinsics and\n  // extrinsics.\n  std::vector<Vector3d> world_points_vector(5);\n  world_points_vector[0] = Eigen::Vector3d(-size / 2, -size / 2, depth);\n  world_points_vector[1] = Eigen::Vector3d(size / 2, -size / 2, depth);\n  world_points_vector[2] = Eigen::Vector3d(size / 2, size / 2, depth);\n  world_points_vector[3] = Eigen::Vector3d(-size / 2, size / 2, depth);\n  world_points_vector[4] = Eigen::Vector3d(0.0, 0.0, depth);\n\n  P5pfrTestWithNoise(gt_rotation,\n                     gt_translation,\n                     focal_length,\n                     radial_distortion,\n                     world_points_vector,\n                     noise,\n                     reproj_tolerance);\n}\n\nTEST(P5Pfr, BasicTest) { BasicTest(0.0, 1e-12); }\n\nTEST(P5Pfr, BasicNoiseTest) { BasicTest(0.5 / 800.0, 5 / 800.0); }\n\nTEST(P5Pfr, PlanarTestNoNoise) { PlanarTestWithNoise(0.0, 1e-12); }\n\nTEST(P5Pfr, PlanarTestWithNoise) {\n  PlanarTestWithNoise(0.5 / 800.0, 5 / 800.0);\n}\n\n}  // namespace\n}  // namespace theia\n", "meta": {"hexsha": "eb6df7919982d30ade7a55a1bc68949fe589abd6", "size": 9002, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/sfm/pose/five_point_focal_length_radial_distortion_test.cc", "max_stars_repo_name": "urbste/TheiaSfM", "max_stars_repo_head_hexsha": "a92fa27e90b6182e2a2511a46d24283afad1a995", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T03:01:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-04T08:08:45.000Z", "max_issues_repo_path": "src/theia/sfm/pose/five_point_focal_length_radial_distortion_test.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/five_point_focal_length_radial_distortion_test.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": 39.4824561404, "max_line_length": 80, "alphanum_fraction": 0.6545212175, "num_tokens": 2412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.4714427756643666}}
{"text": "#define BOOST_LOG_DYN_LINK 1\n#include <boost/scoped_ptr.hpp>\n#include <boost/log/trivial.hpp>\n\n#include <ros/ros.h>\n#include <ros/publisher.h>\n#include <signal.h>\n#include <camera_info_manager/camera_info_manager.h>\n#include <image_transport/image_transport.h>\n#include <image_transport/camera_publisher.h>\n#include <sensor_msgs/Image.h>\n#include <cv_bridge/cv_bridge.h>\n#include <dynamic_reconfigure/server.h>\n#include <driver_base/SensorLevels.h>\n#include <boost/filesystem.hpp>\n#include <std_msgs/String.h>\n\n\n#include <pix2image.h>\n\nnamespace POLPro\n{\n    std::vector<cv::Mat> raw2mat(const cv::Mat& origin, const bool show=true) {\n        // define the size of the output\n        cv::Size output_size(origin.cols / 2, origin.rows / 2);\n        // declare the vector containing the 4 angles images\n        const int nb_angles = 4;\n        std::vector<cv::Mat> output_img(nb_angles);\n        for (auto it = output_img.begin(); it != output_img.end(); ++it)\n            *it = cv::Mat::zeros(output_size, CV_8U);\n        \n        // copy the data in the new image\n        for (int angle = 0; angle < nb_angles; ++angle) {\n            int offset_row = angle / 2;\n            int offset_col = angle % 2;\n            BOOST_LOG_TRIVIAL(debug) << \"offset_row \" << offset_row\n                                     << \" offset_col \" << offset_col;\n\n            for (int row = 0; row < origin.rows/2; ++row)\n                for (int col = 0; col < origin.cols/2; ++col)\n                    output_img[angle].at<uchar>(row, col) = origin.at<uchar>(\n                        2 * row + offset_row, 2 * col + offset_col);\n        }\n\n        if (show)\n            imshow(output_img, false, false);\n\n        return output_img;\n    }\n\n    std::vector<cv::Mat> compute_stokes(const std::vector<cv::Mat>& angles_img,\n                                        const bool show=true) {\n        // define the number of images to have for Stokes\n        const int nb_stokes_img = 3;\n        // Create zeros images\n        std::vector<cv::Mat> output_img(nb_stokes_img);\n        for (auto it = output_img.begin(); it != output_img.end(); ++it)\n            *it = cv::Mat::zeros(angles_img[0].size(), CV_32F);\n\n        // compute the Stokes parameters maps\n        // S0: add the different angles\n        for (auto it = angles_img.begin(); it != angles_img.end(); ++it)\n            cv::add(output_img[0], *it, output_img[0], cv::noArray(),\n                    CV_32F);\n        output_img[0] /= 2.0;\n        BOOST_LOG_TRIVIAL(debug) << minmax(output_img[0], \"s0\");\n\n        // S1: subtract angles 0 and 90\n        cv::subtract(angles_img[0], angles_img[2], output_img[1],\n                     cv::noArray(), CV_32F);\n        BOOST_LOG_TRIVIAL(debug) << minmax(output_img[1], \"s1\");\n\n        // S2: subtract angles 45 and 135\n        cv::subtract(angles_img[1], angles_img[3], output_img[2],\n                     cv::noArray(), CV_32F);\n        BOOST_LOG_TRIVIAL(debug) << minmax(output_img[2], \"s2\");\n\n        if (show)\n            imshow(output_img, false, true);\n\n        return output_img;\n    }\n\n    std::vector<cv::Mat> compute_stokes(const cv::Mat& origin,\n                                        const bool show=true) {\n        // refactor the raw image\n        std::vector<cv::Mat> angles_img = raw2mat(origin, show);\n\n        return compute_stokes(angles_img, show);\n    }\n\n    std::vector<cv::Mat> compute_polar_params(\n        const std::vector<cv::Mat>& origin, const bool show=true) {\n        std::vector<cv::Mat> stokes_img;\n        // Check if we have the original data or the stokes\n        if (origin.size() == 4) {\n            stokes_img = compute_stokes(origin, show);\n        } else {\n            stokes_img = origin;\n        }\n\n        // define the number of maps\n        const int nb_params = 3;\n        // create the zeros images\n        std::vector<cv::Mat> output_img(nb_params);\n        for (auto it = output_img.begin(); it != output_img.end(); ++it)\n            *it = cv::Mat::zeros(stokes_img[0].size(), CV_32F);\n\n        // compute the polar coordinate in degrees\n        cv::cartToPolar(stokes_img[1], stokes_img[2],\n                        output_img[0], output_img[1],\n                        true);\n        // normalize the maps\n        // degree of polarization\n        output_img[0] /= stokes_img[0];\n        // angle of polarization\n        output_img[1] *= 0.5;\n        // copy s0\n        stokes_img[0].copyTo(output_img[2]);\n        if (show)\n            imshow(output_img, false, false);\n\n        return output_img;\n    }\n\n    std::vector<cv::Mat> compute_polar_params(const cv::Mat& origin,\n                                              const bool show=true) {\n        // compute the Stokes' parameters\n        std::vector<cv::Mat> stokes_img = compute_stokes(origin, show);\n\n        return compute_polar_params(stokes_img, show);\n    }\n\n    std::string minmax(const cv::Mat& img, const std::string& s) {\n        double min, max;\n        cv::Point idmin, idmax;\n        cv::minMaxLoc(img, &min, &max, &idmin, &idmax) ;\n\n        return \"Image \" + s\n            + \": min=\" + std::to_string(min)\n            + \" - max= \" + std::to_string(max);\n    }\n\n\n    void imshow(std::vector<cv::Mat> img, const bool as_hsv=false,\n                const bool is_stokes=true) {\n\n        // through an error if there is not 3d img and hsv is turned on\n        if ((img.size() != 3) && as_hsv)\n            throw std::invalid_argument(\"img needs to be a 3 channels images\"\n                                        \" if you need hsv support\");\n       \n        // Convert the data if Stokes or polarization parameters\n        if (img.size() == 3) {\n            if (is_stokes) {\n                // Stokes parameters normalization\n                img[0] /= 2.0;\n                img[1] = (img[1] + 255.0) / 2.0;\n                img[2] = (img[2] + 255.0) / 2.0;\n            } else {\n                // polarization parameters normalization\n                img[0] = img[0] * 255;\n                img[2] = img[2] / 2;\n            }\n            // Convert to uint8\n            for (int i = 0; i < img.size(); ++i){\n                img[i].convertTo(img[i], CV_8UC1);\n            }\n            \n        }\n        // Declare the output image\n        cv::Mat output_img;\n\n        if (as_hsv) {\n            // Merge the image together to have a 3 channels image\n\n            std::vector<cv::Mat> channels;\n            channels.push_back(img[1].clone()); \n            channels.push_back(img[0].clone()); \n            channels.push_back(img[2].clone());\n\n            cv::Mat bgr_img;\n            cv::merge(channels, bgr_img);\n            cv::cvtColor(bgr_img, output_img, CV_HLS2BGR);\n        } else {\n            // Concatenate the images available together\n            cv::Size img_size(img[0].cols, img[0].rows);\n            output_img = cv::Mat::zeros\n                (img[0].rows*2, img[0].cols*2, CV_8UC1);\n            int rows = img[0].rows; \n            int cols = img[0].cols;\n            \n    \n            for (int i = 0; i < img.size(); ++i) {\n                // we need to shift the image next to each other properly\n                int offset_col = i % 2;\n                int offset_row = i / 2;\n               \n                img[i].copyTo(output_img(\n                                  cv::Rect(img_size.width * offset_col,\n                                           img_size.height * offset_row,\n                                           img_size.width,\n                                           img_size.height)));\n\n            }\n        }\n\n        cv::imshow(\"Output image\", output_img);\n    }\n}  // Namespace POLPro\n\n", "meta": {"hexsha": "662a2c10e19f5b1d680d95e8f396c29d24619c41", "size": 7613, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/pix2image.cpp", "max_stars_repo_name": "WildGenie/pleora_polarcam", "max_stars_repo_head_hexsha": "62c255507f24a82223334e7efbb98b86b0b67926", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/pix2image.cpp", "max_issues_repo_name": "WildGenie/pleora_polarcam", "max_issues_repo_head_hexsha": "62c255507f24a82223334e7efbb98b86b0b67926", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pix2image.cpp", "max_forks_repo_name": "WildGenie/pleora_polarcam", "max_forks_repo_head_hexsha": "62c255507f24a82223334e7efbb98b86b0b67926", "max_forks_repo_licenses": ["BSD-3-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.9103773585, "max_line_length": 79, "alphanum_fraction": 0.5252856955, "num_tokens": 1891, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.7122321781307375, "lm_q1q2_score": 0.47144277162120307}}
{"text": "// A2DD.h\n#ifndef A2DD_H\n#define A2DD_H\n\n#include <armadillo>\n\nnamespace LLS {\n\nusing namespace arma;\n\nclass LLS_impl\n{\n\npublic:\n  //A2DD(auto& x_arr, auto& y_arr, int N);\n  LLS_impl(std::array<double, 4ul>& x_arr, std::array<double, 4ul>& y_arr, int N);\n  int getParams(double& B1, double& B2);\n\nprivate:\n  mat eq_mat;\n  colvec y_vec;\n  colvec parameter;\n\n};\n\n}\n\n#endif\n", "meta": {"hexsha": "74e32fefb5a1e6ad5ef071ab1f00ead6edd9234a", "size": 371, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "LLS/LLS_lib/Linear_LS.hpp", "max_stars_repo_name": "Wolframm74/armadillo_armanpy", "max_stars_repo_head_hexsha": "f716cc62f0ba7fd06976cf1f1977d89af268a371", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-10-31T15:56:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-28T09:43:49.000Z", "max_issues_repo_path": "LLS/LLS_lib/Linear_LS.hpp", "max_issues_repo_name": "Wolframm74/armadillo_armanpy", "max_issues_repo_head_hexsha": "f716cc62f0ba7fd06976cf1f1977d89af268a371", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2019-09-22T14:44:36.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-27T20:18:30.000Z", "max_forks_repo_path": "LLS/LLS_lib/Linear_LS.hpp", "max_forks_repo_name": "Wolframm74/armadillo_armanpy", "max_forks_repo_head_hexsha": "f716cc62f0ba7fd06976cf1f1977d89af268a371", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-10-03T14:31:42.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-03T14:31:42.000Z", "avg_line_length": 12.7931034483, "max_line_length": 82, "alphanum_fraction": 0.6765498652, "num_tokens": 125, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.4714427709143528}}
{"text": "//==================================================================================================\n/*!\n\n  Copyright 2015 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#include <boost/simd/function/scalar/compare_less_equal.hpp>\n#include <simd_test.hpp>\n#include <boost/dispatch/meta/as_integer.hpp>\n#include <boost/simd/constant/inf.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/zero.hpp>\n\n\nSTF_CASE_TPL (\" compare_less_equal\",  STF_NUMERIC_TYPES)\n{\n  namespace bs = boost::simd;\n  using bs::compare_less_equal;\n  using r_t = decltype(compare_less_equal(T(), T()));\n\n  // specific values tests\n  STF_LESS_EQUAL(compare_less_equal(bs::One<T>(), bs::One<T>()),  r_t(true));\n  STF_LESS_EQUAL(compare_less_equal(bs::One<T>(), bs::Zero<T>()), r_t(false));\n  STF_LESS_EQUAL(compare_less_equal(bs::Zero<T>(), bs::One<T>()), r_t(true));\n\n} // end of test for floating_\n", "meta": {"hexsha": "3bf8fad2b54880b7981756d1df007915159cea99", "size": 1224, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/scalar/compare_less_equal.cpp", "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": "test/function/scalar/compare_less_equal.cpp", "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": "test/function/scalar/compare_less_equal.cpp", "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.0909090909, "max_line_length": 100, "alphanum_fraction": 0.6111111111, "num_tokens": 279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321720225278, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.47144276282802555}}
{"text": "#include <iostream>\n#include <stdio.h>\n#include <fstream>\n#include <vector>\n//#include <map>\n//#include <set>\n#include <unordered_set>\n//#include <unordered_map>\n#include <cmath>\n#include <algorithm>\n\n// #include <gnuplot-iostream.h>\n#include <assert.h>\n#include <boost/program_options.hpp>\n#include <boost/filesystem.hpp>\n\n#include \"vector3d.hpp\"\n#include \"swiss_to_lat_lon.hpp\"\n#include \"height_map.hpp\"\n\nconst int horizon_angles = 360;\nconst int tile_size = 40;\n\n\nnamespace po = boost::program_options;\n\nstruct pos_hoz {\n    vector3d pos;\n    vector3d norm;\n    short elevation_angles[horizon_angles];\n    pos_hoz() : pos(0,0,0), norm(0,0,0) {\n        memset(elevation_angles, 0, sizeof(short) * horizon_angles);\n    }\n};\n\nbool EQ_DBL(double a, double b){\n    return std::abs(a-b)<EPS_DBL;\n}\n\nint main(int ac, char** av) {\n    \n    bool test = false;\n    //Variables to be assigned by program options\n    double height_map_resolution;\n    double north_bound;\n    double south_bound;\n    double east_bound;\n    double west_bound;\n    \n    double elevation_angles_tan[horizon_angles];\n    \n    std::string input_file;\n    std::string output_dir;\n    bool verbose = false;\n    \n    // Declare the supported options.\n    po::options_description op_desc(\"Allowed options\");\n    op_desc.add_options()\n    (\"help\", \"print options table\")\n    (\"input-file,i\", po::value<std::string>(&input_file), \"File containing height map data in x<space>y<space>z<newline> swiss coordinates format\")\n    (\"output-dir,o\", po::value<std::string>(&output_dir), \"Directory for output files (default data_out_<date_time>)\")\n    (\"resolution,R\", po::value<double>(&height_map_resolution)->default_value(25.0), \"resolution of data (default: 25.0)\")\n    (\"nmax\",po::value<double>(&north_bound)->default_value(1e100), \"maximum north coordinate to be treated (default 1e100)\")\n    (\"nmin\",po::value<double>(&south_bound)->default_value(-1e100), \"minimum north coordinate to be treated (default -1e100)\")\n    (\"emax\",po::value<double>(&east_bound)->default_value(1e100), \"maximum east coordinate to be treated (default 1e100)\")\n    (\"emin\",po::value<double>(&west_bound)->default_value(-1e100), \"minimum east coordinate to be treated (default -1e100)\")\n    (\"verbose, v\", \"Verbose: output lots of text\")\n    ;\n    \n    po::positional_options_description pd;\n    pd.add(\"input-file\", 1).add(\"output-file\", 1);\n    \n    po::variables_map vm;\n    po::store(po::parse_command_line(ac, av, op_desc), vm);\n    po::notify(vm);\n    \n    if (vm.count(\"help\")) {\n        std::cout <<\"ComputeHorizons [options] [input file] [output base]\"<<std::endl<< op_desc << std::endl;\n        return 1;\n    }\n    \n    if (vm.count(\"verbose\")){\n        verbose = true;\n    }\n    if(!vm.count(\"input-file\")){\n        std::cout << \"Input file must be specified\" << std::endl;\n        exit(255);\n    }\n    if(!vm.count(\"output-dir\")){\n        std::time_t now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());\n        std::string time_string(30, 0);\n        std::strftime(&time_string[0], time_string.size(), \"%Yx%mx%dT%Hx%Mx%S\", std::localtime(&now));\n        output_dir = std::string(\"hoz_out_\")+time_string;\n        std::cout << \"Output directory will be: \"+output_dir << std::endl;\n    }\n    \n    //create output directory\n    boost::filesystem::path dir(output_dir);\n    if(!boost::filesystem::create_directory(dir)) {\n        std::cout << \"Failed to creat output directory\" << \"\\n\";\n        exit(255);\n    }\n\n    std::ifstream ifs(input_file);\n    if (!ifs.is_open())\n        throw std::runtime_error(\"could not open file : \" + std::string(input_file));\n    \n    height_map grid_points(ifs, south_bound, north_bound, east_bound, west_bound);\n    \n    \n    //grid_points is a height_map, an unordered_set of all points in bounding box with\n    //the maximum and minimum x,y,h of all values stored.\n    \n    \n    std::pair<double,double> NE = swiss_to_lat_lon(grid_points.xmax()+height_map_resolution/2.0, grid_points.ymax()+height_map_resolution/2.0);\n    std::pair<double,double> SW = swiss_to_lat_lon(grid_points.xmin()-height_map_resolution/2.0, grid_points.ymin()-height_map_resolution/2.0);\n    \n    std::cout << \"NE: \" << grid_points.xmax() <<\", \" << grid_points.ymax() << \" SW: \"<< grid_points.xmin() << \" , \" << grid_points.ymin() <<  std::endl;\n    std::cout  << \"NE: \" << NE.first <<\", \" << NE.second << \" SW: \"<< SW.first << \", \" << SW.second <<  std::endl;\n    std::cout << \"Maximum height: \" << grid_points.hmax() << std::endl;\n    std::cout << \"Number of points in dataset: \" << grid_points.size() << std::endl;\n    \n    if(test){\n        double y_test = height_map_resolution*floor(601430.0/height_map_resolution);\n        double x_test = height_map_resolution*floor(126243.0/height_map_resolution);\n        auto it_v = grid_points.find_point(vector3d(x_test,y_test,0));      //get the gridpoint from the set\n        std::cout << \"Test point: \" << x_test <<\" \"<< y_test << std::endl;\n        std::cout << \"Resolution: \" << height_map_resolution << \", tile size: \"<< tile_size << std::endl;\n        vector3d v = *it_v;\n        double elevation_angles[360];\n        int theta_start = 0;\n        int theta_end = 360;\n        \n        //        time_t start_time  = time(NULL);\n        clock_t t = clock();\n        for(int theta = theta_start;theta<theta_end;theta++){\n            double phi = atan(grid_points.compute_elevation_angle(v,theta, height_map_resolution, 360.0/horizon_angles));\n            short phi_short = (short)((phi / M_PI_2) * std::numeric_limits<short>::max());\n            elevation_angles[theta] = phi_short;\n            \n        }\n        double run_time = ((double)(clock()-t))/CLOCKS_PER_SEC;\n        //        double run_time = difftime(time(NULL), start_time);\n        std::cout << \"phi = [\";\n        for(int theta = theta_start;theta<theta_end;theta++){\n            std::cout << elevation_angles[theta] << \";\";\n        }\n        std::cout << \"];\" << std::endl;\n        std::cout << \"runtime test point: \" << run_time << std::endl;\n        std::cout << \"estimated runtime all points: \" << run_time*grid_points.size() << std::endl;\n        \n        return 0;\n    }\n    \n    \n    \n    \n    std::string file_name;\n    std::ofstream ofs;\n    \n    time_t start_time  = time(NULL);\n    int N=0;\n    int NT=0;\n    \n    int first_tile_y = (int) floor(grid_points.ymin()/(tile_size*height_map_resolution));\n    first_tile_y = first_tile_y * (tile_size*height_map_resolution);\n    int first_tile_x = (int) floor(grid_points.xmin()/(tile_size*height_map_resolution));\n    first_tile_x = first_tile_x * (tile_size*height_map_resolution);\n    int last_tile_y = (int) floor(grid_points.ymax()/(tile_size*height_map_resolution));\n    last_tile_y = last_tile_y * (tile_size*height_map_resolution);\n    int last_tile_x = (int) floor(grid_points.xmax()/(tile_size*height_map_resolution));\n    last_tile_x = last_tile_x * (tile_size*height_map_resolution);\n    int N_tiles_x = (last_tile_x - first_tile_x )/(tile_size*height_map_resolution) + 1;\n    int N_tiles_y = (last_tile_y - first_tile_y )/(tile_size*height_map_resolution) + 1;\n    \n    std::cout << \"FTy \" << first_tile_y << \" LTy \" << last_tile_y << \" FTx \" << first_tile_x << \" LTx \" << last_tile_x << std::endl;\n    std::cout << \"calculating \" << N_tiles_x << \" x \" << N_tiles_y << \" tiles = \" << N_tiles_x*N_tiles_y << \" total\" << std::endl;\n\n    pos_hoz tile_points[tile_size*tile_size];\n    \n    for(int x_tile = 0;x_tile<N_tiles_x; x_tile++){\n        for(int y_tile = 0; y_tile<N_tiles_y;y_tile++){\n            double coord_x = (first_tile_x + height_map_resolution*tile_size*x_tile);\n            double coord_x_end = coord_x+height_map_resolution*tile_size;\n            int tile_point = 0;\n            bool tile_empty = true;\n            while(coord_x < coord_x_end){\n                double coord_y = (first_tile_y + height_map_resolution*tile_size*y_tile);\n                double coord_y_end = coord_y+height_map_resolution*tile_size;\n                while(coord_y < coord_y_end){\n                    \n                    //get point and points to the north, west, south and east\n                    vector3d v(coord_x, coord_y, 0.0);\n                    vector3d vN(v.x+height_map_resolution,v.y,0);\n                    vector3d vW(v.x,v.y+height_map_resolution,0);\n                    vector3d vS(v.x-height_map_resolution,v.y,0);\n                    vector3d vE(v.x,v.y-height_map_resolution,0);\n                    \n                    auto itv=grid_points.find_point(v);\n                    auto itE=grid_points.find_point(vE);\n                    auto itN=grid_points.find_point(vN);\n                    auto itW=grid_points.find_point(vW);\n                    auto itS=grid_points.find_point(vS);\n                    \n                    if (grid_points.is_end(itv) ||grid_points.is_end(itE) || grid_points.is_end(itN) || grid_points.is_end(itW) || grid_points.is_end(itS)){\n                        coord_y = coord_y + height_map_resolution;\n                        continue;\n                        //if one of the neighboring points are not found we continue with the next point\n                    }\n                    v = *itv;\n                    vE = *itE;\n                    vN = *itN;\n                    vW = *itW;\n                    vS = *itS;\n                    tile_points[tile_point].pos = v;\n                    \n                    vector3d Normal = ((((vE-v)^(vN-v))+((vW-v)^(vS-v)))/2).norm();       //normal is the crossproduct of two prependicular differences. Avgd.\n                    \n                    tile_points[tile_point].norm = Normal;\n                    \n/*                    for(int theta=0;theta<horizon_angles;theta++){\n                        double phi = atan(grid_points.compute_elevation_angle(v,theta, height_map_resolution, 360.0/horizon_angles));\n                        tile_points[tile_point].elevation_angles[theta] = (short)((phi / M_PI_2) * std::numeric_limits<short>::max());\n                    }\n */ //old crap for finding elevations for an angle\n\n                    //assign very negative tangent angle for the starting value\n                    for(int theta=0;theta<horizon_angles;theta++){\n                        elevation_angles_tan[theta] = -1e10;\n                    }\n                    //iterate over all points\n                    for (auto itr = grid_points.first_point(); itr != grid_points.last_point(); ++itr){\n                        vector3d v2 = *itr;\n                        int theta;\n                        if(EQ_DBL(v2.x,v.x)){\n                            if(v2.y>v.y){\n                                theta = 90;\n                            }\n                            else{\n                                theta = 270;\n                            }\n                            double hdiff = v2.z-v.z;\n                            double dxy = v.distxy(v2);\n                            elevation_angles_tan[theta] = hdiff / dxy;\n                        }\n                        if(EQ_DBL(v2.y,v.y)){\n                            if(v2.x>v.x){\n                                theta = 0;\n                            }\n                            else{\n                                theta = 180;\n                            }\n                            double hdiff = v2.z-v.z;\n                            double dxy = v.distxy(v2);\n                            elevation_angles_tan[theta] = hdiff / dxy;\n                        }\n                        // Find the four neighbours to our point\n                        vector3d v2N(v2.x+height_map_resolution,v2.y,0);\n                        vector3d v2W(v2.x,v2.y+height_map_resolution,0);\n                        vector3d v2S(v2.x-height_map_resolution,v2.y,0);\n                        vector3d v2E(v2.x,v2.y-height_map_resolution,0);\n                        auto itE=grid_points.find_point(v2E);\n                        auto itN=grid_points.find_point(v2N);\n                        auto itW=grid_points.find_point(v2W);\n                        auto itS=grid_points.find_point(v2S);\n                        v2E = *itE;\n                        v2N = *itN;\n                        v2W = *itW;\n                        v2S = *itS;\n\n                        //calculate the integral multiples of horizon_angles\n                        int v2th = ceil(horizon_angles*atan2(v2.y-v.y, v2.x-v.x)/(2*M_PI));\n                        int v2Nth = ceil(horizon_angles*atan2(v2N.y-v.y, v2N.x-v.x)/(2*M_PI));\n                        int v2Eth = ceil(horizon_angles*atan2(v2E.y-v.y, v2E.x-v.x)/(2*M_PI));\n                        int v2Sth = ceil(horizon_angles*atan2(v2S.y-v.y, v2S.x-v.x)/(2*M_PI));\n                        int v2Wth = ceil(horizon_angles*atan2(v2W.y-v.y, v2W.x-v.x)/(2*M_PI));\n                        for(int th=v2th;th<v2Nth;++th){\n                            \n                        }\n                        \n                        \n                    }\n                    \n                    \n                    tile_empty = false;\n                    N++;\n                    coord_y = coord_y + height_map_resolution;\n                    tile_point++;\n                }\n                \n                coord_x = coord_x + height_map_resolution;\n                \n                if (1) {\n                    double run_time = difftime(time(NULL), start_time);\n                    int rdays = (int)floor(run_time/86400.0);\n                    int rhours = (int)floor((run_time-rdays*86400)/3600.0);\n                    int rminutes = (int)floor((run_time-rdays*86400.0-rhours*3600.0)/60.0);\n                    int rseconds = (int)floor(run_time-rdays*86400.0-rhours*3600.0-rminutes*60.0);\n                    double remaining_time = ((grid_points.size() - N)*1.0)*run_time/(N*1.0);\n                    int days = (int)floor(remaining_time/86400.0);\n                    int hours = (int)floor((remaining_time-days*86400)/3600.0);\n                    int minutes = (int)floor((remaining_time-days*86400-hours*3600.0)/60.0);\n                    int seconds = (int)floor(remaining_time-days*86400-hours*3600.0-minutes*60.0);\n                    double progress = round(1000.0*100.0*(N*1.0)/(grid_points.size()*1.0))/1000.0;\n                    if(N > 0){\n                        std::cout <<\"   Progress: \"<< progress <<\" %  (\"<<N<<\", \"<<NT<<\")  time: \"<<rdays<<\"d\"<<rhours<<\":\"<<rminutes<<\":\"<<rseconds<<\" time left: \"<<days<<\"d\"<<hours<<\":\"<<minutes<<\":\"<<seconds<<\"      \\r\";\n                        std::cout.flush();\n                    }\n                }\n\n            }\n            if(tile_point > 0){\n                std::string tile_name;\n                int tile_x = (first_tile_x + height_map_resolution*tile_size*x_tile);\n                int tile_y = (first_tile_y + height_map_resolution*tile_size*y_tile);\n                tile_name = output_dir + std::string(\"/tile_\") + std::to_string(tile_x) + std::string(\"_\") + std::to_string(tile_y) + std::string(\".hoz\");\n                //            std::cout << std::endl << \"tile_name \" << tile_name << std::endl;\n                ofs.open(tile_name, std::iostream::out | std::iostream::binary);\n                //            std::cout << \"first point\" << tile_points[0].pos << \"norm: \" << tile_points[0].norm<< std::endl;\n                //open output file\n                if (!ofs.is_open()){\n                    std::cout << \"Can't open output file \" << tile_name << std::endl;\n                }\n                ofs.write((char*)&tile_points[0], sizeof(pos_hoz)*tile_point);\n                ofs.flush();\n                ofs.close();\n                if(NT%10==0)\n                    std::cout << std::endl;\n                NT++;\n            }\n            \n        }\n    }\n    return 0;\n}\n\n\n\n\n\n\n", "meta": {"hexsha": "f05484109c11b0d0aa152a73a5b55842d0abfaff", "size": 15761, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sources/compute_horizons.cpp", "max_stars_repo_name": "alexxxzzz/ValaisSun", "max_stars_repo_head_hexsha": "fca2610bf2f68df4c82a36e3f9464ca8f2de0b06", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sources/compute_horizons.cpp", "max_issues_repo_name": "alexxxzzz/ValaisSun", "max_issues_repo_head_hexsha": "fca2610bf2f68df4c82a36e3f9464ca8f2de0b06", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sources/compute_horizons.cpp", "max_forks_repo_name": "alexxxzzz/ValaisSun", "max_forks_repo_head_hexsha": "fca2610bf2f68df4c82a36e3f9464ca8f2de0b06", "max_forks_repo_licenses": ["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.0847953216, "max_line_length": 223, "alphanum_fraction": 0.5363872851, "num_tokens": 3820, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4713763236362081}}
{"text": "\n\n#include <boost/random/uniform_int.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/lognormal_distribution.hpp>\n#include <boost/random/binomial_distribution.hpp>\n#include <boost/shared_ptr.hpp>\n\n#include \"Random.h\"\n\nnamespace calc\n{\n\n  class UniformGen::Impl\n  {\n  public:\n    Impl( unsigned seed , int lower , int upper ) \n      :rgen_(seed),\n       udist_(lower,upper),\n       gen_(rgen_,udist_)\n    {}\n\n    int next() { return gen_(); }\n\n  public:\n    boost::mt19937       rgen_;\n    boost::uniform_int<> udist_;\n    boost::variate_generator< boost::mt19937 , boost::uniform_int<> > gen_;\n  };\n\n\n  class NormalGen::Impl\n  {\n  public:\n    Impl( unsigned seed , double mu , double sigma )\n      :rgen_(seed),\n       ndist_(mu,sigma),\n       gen_(rgen_,ndist_)\n    {}\n\n    double next() { return gen_(); }\n\n  public:\n    boost::mt19937       rgen_;\n    boost::normal_distribution<double>  ndist_;\n    boost::variate_generator< boost::mt19937 , boost::normal_distribution<double>  > gen_;\n  };\n\n  class LogNormalGen::Impl\n  {\n  public:\n    Impl( unsigned seed , double mu , double sigma )\n      :rgen_(seed),\n       ndist_(mu,sigma),\n       gen_(rgen_,ndist_)\n    {}\n\n    double next() { return gen_(); }\n\n  public:\n    boost::mt19937       rgen_;\n    boost::lognormal_distribution<double>  ndist_;\n    boost::variate_generator< boost::mt19937 , boost::lognormal_distribution<double>  > gen_;\n  };\n\n\n}\n\ncalc::UniformGen::UniformGen( unsigned seed , int lower , int upper )\n  :seed_(seed),lower_(lower),upper_(upper),\n   impl_( new Impl( seed , lower, upper ) )\n{}\n\nint calc::UniformGen::operator()() { return impl_->next(); }\n\n\ncalc::NormalGen::NormalGen( unsigned seed , double mu , double sigma )\n  :seed_(seed),mu_(mu),sigma_(sigma),\n   impl_( new Impl( seed , mu , sigma ) )\n{}\n\ndouble calc::NormalGen::operator()() { return impl_->next(); }\n\ncalc::LogNormalGen::LogNormalGen( unsigned seed , double mu , double sigma )\n  :seed_(seed),mu_(mu),sigma_(sigma),\n   impl_( new Impl( seed , mu , sigma ) )\n{}\n\ndouble calc::LogNormalGen::operator()() { return impl_->next(); }\n", "meta": {"hexsha": "82469a0f13c368f3b6ca9f968f79832d0ed4ee51", "size": 2193, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "c++/Random.cpp", "max_stars_repo_name": "jrrpanix/reference", "max_stars_repo_head_hexsha": "2d6774ca5aefee8d215279ee552a684a1d6a3906", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-27T16:21:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T16:21:49.000Z", "max_issues_repo_path": "c++/Random.cpp", "max_issues_repo_name": "jrrpanix/reference", "max_issues_repo_head_hexsha": "2d6774ca5aefee8d215279ee552a684a1d6a3906", "max_issues_repo_licenses": ["MIT"], "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++/Random.cpp", "max_forks_repo_name": "jrrpanix/reference", "max_forks_repo_head_hexsha": "2d6774ca5aefee8d215279ee552a684a1d6a3906", "max_forks_repo_licenses": ["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.8369565217, "max_line_length": 93, "alphanum_fraction": 0.6548107615, "num_tokens": 587, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812552, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.47137632363620807}}
{"text": "#pragma once\n#include <Eigen/Dense>\n#include <vector>\n#include <string>\n#include <opencv2/core.hpp>\n#include <boost/algorithm/string.hpp>\n\n#define CTS350 0\n#define CIR204 1\n\n/*!\n   \\brief Retrieves a vector of the (radar) file names in ascending order of time stamp\n   \\param datadir (absolute) path to the directory that contains (radar) files\n   \\param radar_files [out] A vector to be filled with a string for each file name\n   \\param extension Optional argument to specify the desired file extension. Files without this extension are rejected\n*/\nvoid get_file_names(std::string datadir, std::vector<std::string> &radar_files, std::string extension = \"\");\n\n/*!\n   \\brief Decode a single Oxford Radar RobotCar Dataset radar example\n   \\param path path to the radar image png file\n   \\param timestamps [out] Timestamp for each azimuth in int64 (UNIX time)\n   \\param azimuths [out] Rotation for each polar radar azimuth (radians)\n   \\param valid [out] Mask of whether azimuth data is an original sensor reasing or interpolated from adjacent azimuths\n   \\param fft_data [out] Radar power readings along each azimuth\n*/\nvoid load_radar(std::string path, std::vector<int64_t> &timestamps, std::vector<double> &azimuths,\n    std::vector<bool> &valid, cv::Mat &fft_data, int navtech_version = CTS350);\n\nvoid load_velodyne(std::string path, std::vector<int64_t> &timestamps, std::vector<double> &azimuths,\n    Eigen::MatrixXd &pc);\n\nvoid load_velodyne2(std::string path, Eigen::MatrixXd &pc);\n\nvoid load_velodyne3(std::string path, Eigen::MatrixXd &pc, Eigen::MatrixXd & intensities, std::vector<float> &times);\n\ndouble get_azimuth_index(std::vector<double> &azimuths, double azimuth);\n\n/*!\n   \\brief Decode a single Oxford Radar RobotCar Dataset radar example\n   \\param azimuths Rotation for each polar radar azimuth (radians)\n   \\param fft_data Radar power readings along each azimuth\n   \\param radar_resolution Resolution of the polar radar data (metres per pixel)\n   \\param cart_resolution Cartesian resolution (meters per pixel)\n   \\param cart_pixel_width Width and height of the returned square cartesian output (pixels).\n   \\param interpolate_crossover If true, interpolates between the end and start azimuth of the scan.\n   \\param cart_img [out] Cartesian radar power readings\n*/\nvoid radar_polar_to_cartesian(std::vector<double> &azimuths, cv::Mat &fft_data, float radar_resolution,\n    float cart_resolution, int cart_pixel_width, bool interpolate_crossover, cv::Mat &cart_img,\n    int output_type = CV_32F, int navtech_version = CTS350);\n\n/*!\n   \\brief Converts points from polar coordinates to cartesian coordinates\n   \\param azimuths The actual azimuth of each row in the fft data reported by the Navtech sensor\n   \\param polar_points Matrix of point locations (azimuth_bin, range_bin) x N\n   \\param radar_resolution Resolution of the polar radar data (metres per pixel)\n   \\param cart_points [out] Matrix of points in cartesian space (x, y) x N in metric\n*/\nvoid polar_to_cartesian_points(std::vector<double> azimuths, Eigen::MatrixXd polar_points, float radar_resolution,\n    Eigen::MatrixXd &cart_points);\n\nvoid polar_to_cartesian_points(std::vector<double> azimuths, std::vector<int64_t> times, Eigen::MatrixXd polar_points,\n    float radar_resolution, Eigen::MatrixXd &cart_points, std::vector<int64_t> &point_times);\n\n/*!\n   \\brief Converts points from metric cartesian coordinates to pixel coordinates in the BEV image\n   \\param cart_points Vector of points in metric cartesian space (x, y)\n   \\param cart_resolution Cartesian resolution (meters per pixel)\n   \\param cart_pixel_width: Width and height of the returned square cartesian output (pixels)\n   \\param bev_points [out] Vector of pixel locations in the BEV cartesian image (u, v)\n*/\n\nvoid convert_to_bev(Eigen::MatrixXd &cart_points, float cart_resolution, int cart_pixel_width,\n    std::vector<cv::Point2f> &bev_points);\n\nvoid convert_to_bev(Eigen::MatrixXd &cart_points, float cart_resolution, int cart_pixel_width, int patch_size,\n    std::vector<cv::KeyPoint> &bev_points, std::vector<int64_t> &point_times);\n\n/*!\n   \\brief Converts points from pixel coordinates in the BEV image to metric cartesian coordinates\n   \\param bev_points Vector of pixel locations in the BEV cartesian image (u, v)\n   \\param cart_resolution Cartesian resolution (meters per pixel)\n   \\param cart_pixel_width: Width and height of the returned square cartesian output (pixels)\n   \\param cart_points [out] Vector of points in metric cartesian space (x, y)\n*/\nvoid convert_from_bev(std::vector<cv::KeyPoint> bev_points, float cart_resolution, int cart_pixel_width,\n    Eigen::MatrixXd &cart_points);\n\n/*!\n   \\brief Draws a red dot for each feature on the top-down cartesian view of the radar image\n   \\param cart_img Cartesian radar power readings\n   \\param cart_targets Matrix of points in cartesian space (x, y) < N in metric\n   \\param cart_resolution Cartesian resolution (meters per pixel)\n   \\param cart_pixel_width Width and height of the square cartesian image.\n   \\param vis [out] Output image with the features drawn onto it\n*/\nvoid draw_points(cv::Mat cart_img, Eigen::MatrixXd cart_targets, float cart_resolution, int cart_pixel_width,\n    cv::Mat &vis, std::vector<uint> color = {0, 0, 255});\n\nvoid draw_points(cv::Mat &vis, Eigen::MatrixXd cart_targets, float cart_resolution, int cart_pixel_width,\n    std::vector<uint> color = {0, 0, 255});\n\n/*!\n   \\brief Retrieves the ground truth odometry between radar timestamps t1 and t2\n   \\param gtfile (absolute) file location of the radar_odometry.csv file\n   \\param t1\n   \\param t2\n   \\param gt [out] Vector of floats for the ground truth transform between radar timestamp t1 and t2 (x, y, z, r, p, y)\n*/\nbool get_groundtruth_odometry(std::string gtfile, int64 t1, int64 t2, std::vector<float> &gt);\n\nbool get_groundtruth_odometry2(std::string gtfile, int64_t t, std::vector<double> &gt);\n\nvoid draw_matches(cv::Mat &img, std::vector<cv::KeyPoint> kp1, std::vector<cv::KeyPoint> kp2,\n    std::vector<cv::DMatch> matches, int radius = 4);\n\nvoid getTimes(Eigen::MatrixXd cart_targets, std::vector<double> azimuths, std::vector<int64_t> times,\n    std::vector<int64_t> &tout);\n\n/*!\n   \\brief Load arguments from the command line and check their validity.\n*/\nint validateArgs(const int argc, const char *argv[], std::string &root, std::string &seq, std::string &app);\nint validateArgs(const int argc, const char *argv[], std::string &root);\n", "meta": {"hexsha": "cf6a337800a5dab514002ad305927927e9a52fd4", "size": 6446, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/radar_utils.hpp", "max_stars_repo_name": "carlschiller/yeti_radar_odometry", "max_stars_repo_head_hexsha": "339d37fd62b4895d87a0b9aed4aa1bc142d24670", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 72.0, "max_stars_repo_stars_event_min_datetime": "2020-11-13T01:22:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T02:34:48.000Z", "max_issues_repo_path": "include/radar_utils.hpp", "max_issues_repo_name": "carlschiller/yeti_radar_odometry", "max_issues_repo_head_hexsha": "339d37fd62b4895d87a0b9aed4aa1bc142d24670", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-12-27T08:02:12.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-29T01:36:55.000Z", "max_forks_repo_path": "include/radar_utils.hpp", "max_forks_repo_name": "carlschiller/yeti_radar_odometry", "max_forks_repo_head_hexsha": "339d37fd62b4895d87a0b9aed4aa1bc142d24670", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2020-12-20T08:48:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-17T07:32:52.000Z", "avg_line_length": 51.1587301587, "max_line_length": 119, "alphanum_fraction": 0.7593856655, "num_tokens": 1578, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478255, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4713763181752076}}
{"text": "#include <iomanip>\n#include <boost/timer/timer.hpp>\n#include <boost/simd/pack.hpp>\n#include <boost/simd/function/sum.hpp>\n#include <iacaMarks.h>\n\ntemplate< typename FType > FType calcPi();\n\nint main()\n{\n    boost::timer::cpu_timer timer;\n\n    timer.start();\n    double pi = calcPi<double>();\n    timer.stop();\n\n    std::cout << \"Pi: \" << std::setprecision( 20 ) << pi << std::endl;\n    std::cout << timer.format();\n\n    return 0;\n}\n\n\ntemplate< typename FType > FType calcPi()\n{\n    using dpack = boost::simd::pack<FType, 4*boost::simd::pack<FType>::static_size>;\n\n    dpack div;\n    dpack one;\n    dpack sum = dpack( 0 );\n    dpack step = dpack( 2 * dpack::static_size );\n\n    FType val = -1;\n    FType fac = 3;\n    for( size_t i = 0; i < dpack::static_size; ++i )\n    {\n        one[ i ] = val;\n        div[ i ] = fac;\n        val *= -1;\n        fac += 2;\n    }\n\n        IACA_START\n    for( size_t i = 0; i < 1024ull*1024ull*1024ull*16ull / dpack::static_size ; ++i )\n    {\n        sum += one / div;\n        div += step;\n    }\n        IACA_END\n\n    return 4 * (1 + boost::simd::sum( sum ) );\n}\n\n", "meta": {"hexsha": "73627dd13c47c651373c8efb34702842cb91e73e", "size": 1095, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "leibniz/main.cpp", "max_stars_repo_name": "andrelrt/memBound", "max_stars_repo_head_hexsha": "79a452b0ec9f34e75cf70b4e17ed5f5d9f21162d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "leibniz/main.cpp", "max_issues_repo_name": "andrelrt/memBound", "max_issues_repo_head_hexsha": "79a452b0ec9f34e75cf70b4e17ed5f5d9f21162d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "leibniz/main.cpp", "max_forks_repo_name": "andrelrt/memBound", "max_forks_repo_head_hexsha": "79a452b0ec9f34e75cf70b4e17ed5f5d9f21162d", "max_forks_repo_licenses": ["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.2777777778, "max_line_length": 85, "alphanum_fraction": 0.5506849315, "num_tokens": 345, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321703143954, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4713763127142068}}
{"text": "#include <cctbx/boost_python/flex_fwd.h>\n\n#include <cctbx/sgtbx/seminvariant.h>\n#include <cctbx/sgtbx/site_symmetry.h>\n#include <cctbx/sgtbx/operator_from_axis_direction.h>\n#include <scitbx/array_family/shared.h>\n#include <boost/python/module.hpp>\n#include <boost/python/scope.hpp>\n#include <boost/python/class.hpp>\n#include <boost/python/def.hpp>\n#include <boost/python/args.hpp>\n#include <scitbx/boost_python/container_conversions.h>\n\nnamespace cctbx { namespace sgtbx { namespace boost_python {\n\n  void wrap_brick();\n  void wrap_change_of_basis_op();\n  void wrap_find_affine();\n  void wrap_lattice_symmetry();\n  void wrap_phase_info();\n  void wrap_reciprocal_space_asu();\n  void wrap_rot_mx();\n  void wrap_rt_mx();\n  void wrap_search_symmetry();\n  void wrap_seminvariant();\n  void wrap_site_symmetry();\n  void wrap_space_group();\n  void wrap_space_group_type();\n  void wrap_sym_equiv_sites();\n  void wrap_symbols();\n  void wrap_tensor_rank_2();\n  void wrap_tr_vec();\n  void wrap_wyckoff();\n  void wrap_select_generators();\n\nnamespace {\n\n  struct parse_string_wrappers\n  {\n    typedef parse_string w_t;\n\n    static void\n    wrap()\n    {\n      using namespace boost::python;\n      class_<w_t>(\"parse_string\", no_init)\n        .def(init<std::string const&>((arg(\"str\"))))\n        .def(\"string\", &w_t::string)\n        .def(\"where\", &w_t::where)\n      ;\n    }\n  };\n\n  struct crystal_system_code_to_string\n  {\n    static PyObject* convert(crystal_system::code const& c)\n    {\n      using namespace boost::python;\n      return incref(object(crystal_system::label(c)).ptr());\n    }\n  };\n\n  struct matrix_group_code_to_string\n  {\n    static PyObject* convert(matrix_group::code const& c)\n    {\n      using namespace boost::python;\n      return incref(object(c.label()).ptr());\n    }\n  };\n\n  fractional<>\n  fractional_mod_positive(\n    fractional<> const& site)\n  {\n    return site.mod_positive();\n  }\n\n  fractional<>\n  fractional_mod_short(\n    fractional<> const& site)\n  {\n    return site.mod_short();\n  }\n\n  void register_tuple_mappings()\n  {\n    using namespace scitbx::boost_python::container_conversions;\n\n    tuple_mapping_variable_capacity<af::shared<site_symmetry_ops> >();\n    tuple_mapping_fixed_capacity<af::small<ss_vec_mod, 3> >();\n  }\n\n  void init_module()\n  {\n    using namespace boost::python;\n\n    sanity_check();\n\n    scope s;\n    s.attr(\"sg_t_den\") = sg_t_den;\n    s.attr(\"cb_r_den\") = cb_r_den;\n    s.attr(\"cb_t_den\") = cb_t_den;\n\n    register_tuple_mappings();\n\n    parse_string_wrappers::wrap();\n\n    to_python_converter<crystal_system::code, crystal_system_code_to_string>();\n    to_python_converter<matrix_group::code, matrix_group_code_to_string>();\n\n    def(\"fractional_mod_positive\", fractional_mod_positive, (arg(\"site\")));\n    def(\"fractional_mod_short\", fractional_mod_short, (arg(\"site\")));\n\n    wrap_brick();\n    wrap_change_of_basis_op();\n    wrap_find_affine();\n    wrap_lattice_symmetry();\n    wrap_phase_info();\n    wrap_reciprocal_space_asu();\n    wrap_rot_mx();\n    wrap_rt_mx();\n    wrap_search_symmetry();\n    wrap_seminvariant();\n    wrap_site_symmetry();\n    wrap_space_group();\n    wrap_space_group_type();\n    wrap_sym_equiv_sites();\n    wrap_symbols();\n    wrap_tensor_rank_2();\n    wrap_tr_vec();\n    wrap_wyckoff();\n    wrap_select_generators();\n\n    def(\"n_fold_operator_from_axis_direction\",\n      n_fold_operator_from_axis_direction, (\n        arg(\"ev_cart\"), arg(\"n\"), arg(\"sense\")=1));\n  }\n\n} // namespace <anonymous>\n}}} // namespace cctbx::sgtbx::boost_python\n\nBOOST_PYTHON_MODULE(cctbx_sgtbx_ext)\n{\n  cctbx::sgtbx::boost_python::init_module();\n}\n", "meta": {"hexsha": "1642787e7c1cf7cf53c1e21c147506cf98e4d5bd", "size": 3596, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cctbx/sgtbx/boost_python/sgtbx_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": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-03-18T12:31:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T06:27:06.000Z", "max_issues_repo_path": "cctbx/sgtbx/boost_python/sgtbx_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/sgtbx/boost_python/sgtbx_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": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-26T12:52:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-26T12:52:30.000Z", "avg_line_length": 24.462585034, "max_line_length": 79, "alphanum_fraction": 0.697163515, "num_tokens": 901, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085859124002, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4713330716917152}}
{"text": "#ifndef STAN_MATH_PRIM_MAT_FUN_MDIVIDE_RIGHT_TRI_HPP\n#define STAN_MATH_PRIM_MAT_FUN_MDIVIDE_RIGHT_TRI_HPP\n\n#include <stan/math/prim/mat/fun/Eigen.hpp>\n#include <stan/math/prim/mat/fun/mdivide_left_tri.hpp>\n#include <stan/math/prim/mat/fun/transpose.hpp>\n#include <stan/math/prim/mat/err/check_multiplicable.hpp>\n#include <stan/math/prim/mat/err/check_square.hpp>\n#include <stan/math/prim/scal/err/domain_error.hpp>\n#include <boost/math/tools/promotion.hpp>\n\nnamespace stan {\n  namespace math {\n\n    /**\n     * Returns the solution of the system Ax=b when A is triangular\n     * @param A Triangular matrix.  Specify upper or lower with TriView\n     * being Eigen::Upper or Eigen::Lower.\n     * @param b Right hand side matrix or vector.\n     * @return x = b A^-1, solution of the linear system.\n     * @throws std::domain_error if A is not square or the rows of b don't\n     * match the size of A.\n     */\n    template <int TriView, typename T1, typename T2,\n              int R1, int C1, int R2, int C2>\n    inline\n    Eigen::Matrix<typename boost::math::tools::promote_args<T1, T2>::type,\n                  R1, C2>\n    mdivide_right_tri(const Eigen::Matrix<T1, R1, C1> &b,\n                      const Eigen::Matrix<T2, R2, C2> &A) {\n      check_square(\"mdivide_right_tri\", \"A\", A);\n      check_multiplicable(\"mdivide_right_tri\", \"b\", b, \"A\", A);\n      // FIXME: This is nice and general but requires some extra memory\n      //        and copying.\n      if (TriView == Eigen::Lower) {\n        return transpose(mdivide_left_tri<Eigen::Upper>(transpose(A),\n                                                        transpose(b)));\n      } else if (TriView == Eigen::Upper) {\n        return transpose(mdivide_left_tri<Eigen::Lower>(transpose(A),\n                                                        transpose(b)));\n      }\n\n      domain_error(\"mdivide_left_tri\",\n                   \"triangular view must be Eigen::Lower or Eigen::Upper\",\n                   \"\", \"\");\n    }\n\n  }\n}\n#endif\n", "meta": {"hexsha": "827bd1744f023431adf42afd4fd621987088c800", "size": 1984, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/mat/fun/mdivide_right_tri.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/prim/mat/fun/mdivide_right_tri.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/prim/mat/fun/mdivide_right_tri.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.9019607843, "max_line_length": 74, "alphanum_fraction": 0.6139112903, "num_tokens": 490, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4713330686759835}}
{"text": "/* Copyright (C) 2010-2019, The Regents of The University of Michigan.\n All rights reserved.\n\n This software was developed as part of the The Vulcan project in the Intelligent Robotics Lab\n under the direction of Benjamin Kuipers, kuipers@umich.edu. Use of this code is governed by an\n MIT-style License that can be found at \"https://github.com/h2ssh/Vulcan\".\n*/\n\n\n/**\n * \\file     loops_and_trees.cpp\n * \\author   Collin Johnson\n *\n * Definition of label_loops_and_trees function.\n */\n\n#include \"hssh/local_topological/area_detection/labeling/loops_and_trees.h\"\n#include \"hssh/local_topological/area_detection/labeling/area_graph.h\"\n#include <boost/graph/breadth_first_search.hpp>\n#include <boost/graph/exterior_property.hpp>\n#include <boost/graph/johnson_all_pairs_shortest.hpp>\n#include <boost/graph/visitors.hpp>\n#include <boost/range/iterator_range.hpp>\n#include <cassert>\n#include <iostream>\n#include <stack>\n\n#define DEBUG_LOOPS\n// #define DEBUG_CONNECTED\n\nnamespace vulcan\n{\nnamespace hssh\n{\n\nusing namespace boost;\n\nusing Vertex = graph_traits<LoopGraph>::vertex_descriptor;\nusing Edge = graph_traits<LoopGraph>::edge_descriptor;\n\n// Define property map for storing the distances between nodes\nusing DistProperty = exterior_vertex_property<LoopGraph, double>;\nusing DistVec = DistProperty::container_type;\nusing DistMatrix = DistProperty::matrix_type;\nusing DistMap = DistProperty::matrix_map_type;\n\n/*\n * LoopLabellingVisitor is a DFSVisitor for BGL.\n */\nstruct LoopLabellingVisitor : public default_bfs_visitor\n{\n    LoopLabellingVisitor(std::vector<Vertex>& pred, std::vector<Vertex>& source, std::vector<Vertex>& target)\n    : predecessors(pred)\n    , sourcePath(source)\n    , targetPath(target)\n    {\n    }\n\n    // DFSVisitor concept interface\n    void initialize_vertex(Vertex v, const LoopGraph& graph);\n    void tree_edge(Edge e, const LoopGraph& graph);\n    void non_tree_edge(Edge e, const LoopGraph& graph);\n\n    std::vector<Vertex>& predecessors;\n    std::vector<Vertex>& sourcePath;\n    std::vector<Vertex>& targetPath;\n};\n\n\nvoid construct_loop_graph(AreaGraph& areaGraph, LoopGraph& loopGraph)\n{\n    std::unordered_map<AreaNode*, Vertex> nodeToVertex;\n\n    std::for_each(areaGraph.beginNodes(), areaGraph.endNodes(), [&](const auto& node) {\n        auto v = add_vertex(loopGraph);\n        nodeToVertex[node.get()] = v;\n        loopGraph[v].node = node.get();\n    });\n\n    std::vector<std::pair<AreaNode*, AreaNode*>> addedEdges;\n\n    std::for_each(areaGraph.beginEdges(), areaGraph.endEdges(), [&](const auto& edge) {\n        auto endpoints = edge->getEndpoints();\n\n        for (auto& added : addedEdges) {\n            // Ignore previously added edges\n            if ((added.first == endpoints[0].get()) && (added.second == endpoints[1].get())) {\n                return;\n            }\n        }\n\n        auto e = add_edge(nodeToVertex[endpoints[0].get()], nodeToVertex[endpoints[1].get()], loopGraph);\n        loopGraph[e.first].length = edge->getLength();\n        addedEdges.emplace_back(endpoints[0].get(), endpoints[1].get());\n        addedEdges.emplace_back(endpoints[1].get(), endpoints[0].get());\n    });\n}\n\n\nvoid label_loops_and_trees(AreaGraph& graph)\n{\n    LoopGraph loopGraph;\n    construct_loop_graph(graph, loopGraph);\n    label_loops_and_trees(loopGraph);\n}\n\n\nvoid label_loops_and_trees(LoopGraph& graph)\n{\n    std::vector<Vertex> predecessors(num_vertices(graph), num_vertices(graph));\n    // storage for extracting the loops\n    std::vector<Vertex> sourcePath;\n    std::vector<Vertex> targetPath;\n    LoopLabellingVisitor vis(predecessors, sourcePath, targetPath);\n    predecessors[0] = 0;   // point root to itself\n\n    breadth_first_search(graph, vertex(0, graph), visitor(vis));\n    //     undirected_dfs(graph, visitor(vis).edge_color_map(get(&LoopGraphEdge::color, graph)));\n}\n\n\nvoid compute_node_distances(AreaGraph& graph, const LoopGraph& loopGraph)\n{\n    DistMatrix distances(graph.sizeNodes());\n    DistMap distMap(distances, loopGraph);\n    johnson_all_pairs_shortest_paths(loopGraph, distMap, weight_map(get(&LoopGraphEdge::length, loopGraph)));\n\n    for (std::size_t n = 0, end = graph.sizeNodes(); n < end; ++n) {\n        AreaNode* startNode = loopGraph[n].node;\n\n        for (std::size_t m = n + 1; m < end; ++m) {\n            AreaNode* endNode = loopGraph[m].node;\n            graph.setNodeDistance(startNode, endNode, distances[n][m]);\n        }\n    }\n}\n\n\nvoid LoopLabellingVisitor::initialize_vertex(Vertex v, const LoopGraph& graph)\n{\n    // For each vertex, ensure it doesn't have any loops specified\n    graph[v].node->setLoop(false);\n}\n\n\nvoid LoopLabellingVisitor::tree_edge(Edge e, const LoopGraph& graph)\n{\n    predecessors[target(e, graph)] = source(e, graph);\n}\n\n\nvoid LoopLabellingVisitor::non_tree_edge(Edge e, const LoopGraph& graph)\n{\n    // A back edge was found to the target of the edge\n    // Go through the predecessors until target the is found.\n    // Each node along the way back should be marked as part of a Loop\n\n    auto targetVertex = target(e, graph);\n\n    // Ignore this case. It arises from the BFS just looking at all outedges in the undirected graph, so it\n    // sees back to the parent in the search tree when expanded.\n    if (predecessors[source(e, graph)] == targetVertex) {\n        return;\n    }\n\n    auto prevVertex = predecessors[targetVertex];\n    auto vertex = targetVertex;\n\n    // Extract the source and target paths\n    targetPath.clear();\n    while (prevVertex != vertex) {\n        targetPath.push_back(vertex);\n        prevVertex = vertex;\n        vertex = predecessors[vertex];\n    }\n\n    vertex = source(e, graph);\n    prevVertex = predecessors[vertex];\n    sourcePath.clear();\n    while (prevVertex != vertex) {\n        sourcePath.push_back(vertex);\n        prevVertex = vertex;\n        vertex = predecessors[vertex];\n    }\n\n    // Find the first shared vertex between the two\n    auto targetIt = std::find_first_of(targetPath.begin(), targetPath.end(), sourcePath.begin(), sourcePath.end());\n    assert(targetIt != targetPath.end());\n    auto sourceIt = std::find(sourcePath.begin(), sourcePath.end(), *targetIt);\n    assert(sourceIt != sourcePath.end());\n\n    // Turn begin, targetIt into a valid half-open range for a for-loop\n    std::size_t targetEnd = std::distance(targetPath.begin(), targetIt) + 1;\n    std::size_t sourceEnd = std::distance(sourcePath.begin(), sourceIt) + 1;\n\n    double loopDist = 0.0;\n    for (std::size_t n = 1; n < targetEnd; ++n) {\n        loopDist += graph[edge(targetPath[n - 1], targetPath[n], graph).first].length;\n    }\n\n    for (std::size_t n = 1; n < sourceEnd; ++n) {\n        loopDist += graph[edge(sourcePath[n - 1], sourcePath[n], graph).first].length;\n    }\n\n#ifdef DEBUG_LOOPS\n    std::cout << \"DEBUG:label_loops_and_trees: Found a loop with distance \" << loopDist << \" : \\n\";\n#endif\n\n    for (std::size_t n = 0; n < targetEnd; ++n) {\n        graph[targetPath[n]].node->setLoop(true);\n        graph[targetPath[n]].node->setLoopDistance(loopDist);\n\n#ifdef DEBUG_LOOPS\n        std::cout << graph[targetPath[n]].node->getPosition() << '\\n';\n#endif   // DEBUG_LOOPS\n    }\n\n    for (std::size_t n = 0; n < sourceEnd; ++n) {\n        graph[sourcePath[n]].node->setLoop(true);\n        graph[sourcePath[n]].node->setLoopDistance(loopDist);\n\n#ifdef DEBUG_LOOPS\n        std::cout << graph[sourcePath[n]].node->getPosition() << '\\n';\n#endif   // DEBUG_LOOPS\n    }\n}\n\n}   // namespace hssh\n}   // namespace vulcan\n", "meta": {"hexsha": "4d22839fd15812e811962524efae87affcff70ae", "size": 7447, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/hssh/local_topological/area_detection/labeling/loops_and_trees.cpp", "max_stars_repo_name": "anuranbaka/Vulcan", "max_stars_repo_head_hexsha": "56339f77f6cf64b5fda876445a33e72cd15ce028", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-03-05T23:56:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-17T19:06:50.000Z", "max_issues_repo_path": "src/hssh/local_topological/area_detection/labeling/loops_and_trees.cpp", "max_issues_repo_name": "anuranbaka/Vulcan", "max_issues_repo_head_hexsha": "56339f77f6cf64b5fda876445a33e72cd15ce028", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-03-07T01:23:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-07T01:23:47.000Z", "max_forks_repo_path": "src/hssh/local_topological/area_detection/labeling/loops_and_trees.cpp", "max_forks_repo_name": "anuranbaka/Vulcan", "max_forks_repo_head_hexsha": "56339f77f6cf64b5fda876445a33e72cd15ce028", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-03T07:54:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-03T07:54:16.000Z", "avg_line_length": 32.3782608696, "max_line_length": 115, "alphanum_fraction": 0.6826910165, "num_tokens": 1830, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4713330686759835}}
{"text": "//\n//  Copyright Toon Knapen, Karl Meerbergen\n//  Copyright Thomas Klimpel 2008\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#include \"ublas_heev.hpp\"\n\n#include <boost/numeric/bindings/lapack/driver/heevx.hpp>\n#include <boost/numeric/bindings/lapack/driver/syevx.hpp>\n#include <boost/numeric/bindings/ublas/matrix.hpp>\n#include <boost/numeric/bindings/ublas/matrix_proxy.hpp>\n#include <boost/numeric/bindings/ublas/vector.hpp>\n#include <boost/numeric/bindings/ublas/vector_proxy.hpp>\n#include <boost/numeric/bindings/ublas/hermitian.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/bindings/remove_imaginary.hpp>\n#include <boost/type_traits/is_complex.hpp>\n#include <boost/mpl/if.hpp>\n\n#include <iostream>\n\n\nnamespace ublas = boost::numeric::ublas;\nnamespace lapack = boost::numeric::bindings::lapack;\nnamespace bindings = boost::numeric::bindings;\n\ntemplate <typename T, typename W, typename UPLO>\nint do_memory_uplo(int n, W& workspace)\n{\n  typedef typename bindings::remove_imaginary<T>::type real_type ;\n\n  typedef ublas::matrix<T, ublas::column_major>     matrix_type ;\n  typedef ublas::vector<real_type>                  vector_type ;\n\n  typedef ublas::hermitian_adaptor<matrix_type, UPLO> hermitian_type;\n\n  // Set matrix\n  matrix_type a(n, n);\n  a.clear();\n  vector_type e1(n);\n  vector_type e2(n);\n\n  fill(a);\n  matrix_type a2(a);\n  matrix_type z(a);\n\n  // Compute Schur decomposition.\n  fortran_int_t m;\n  ublas::vector<fortran_int_t> ifail(n);\n\n  hermitian_type h_a(a);\n  lapack::heevx('V', 'A', h_a, real_type(0.0), real_type(1.0), 2, n-1, real_type(1e-28), m,\n                e1, z, ifail, workspace) ;\n\n  if(check_residual(a2, e1, z)) return 255 ;\n\n  hermitian_type h_a2(a2);\n  lapack::heevx('N', 'A', h_a2, real_type(0.0), real_type(1.0), 2, n-1, real_type(1e-28), m,\n                e2, z, ifail, workspace) ;\n  if(norm_2(e1 - e2) > n * norm_2(e1) * std::numeric_limits< real_type >::epsilon()) return 255 ;\n\n  // Test for a matrix range\n  fill(a);\n  a2.assign(a);\n\n  typedef ublas::matrix_range< matrix_type > matrix_range ;\n  typedef ublas::hermitian_adaptor<matrix_range, UPLO> hermitian_range_type;\n\n  ublas::range r(1,n-1) ;\n  matrix_range a_r(a, r, r);\n  matrix_range z_r(z, r, r);\n  ublas::vector_range< vector_type> e_r(e1, r);\n  ublas::vector<fortran_int_t> ifail_r(n-2);\n\n  hermitian_range_type h_a_r(a_r);\n  lapack::heevx('V', 'A', h_a_r, real_type(0.0), real_type(1.0), 2, n-1, real_type(1e-28), m,\n                e_r, z_r, ifail_r, workspace);\n\n  matrix_range a2_r(a2, r, r);\n  if(check_residual(a2_r, e_r, z_r)) return 255 ;\n\n  return 0 ;\n} // do_memory_uplo()\n\n\ntemplate <typename T, typename W>\nint do_memory_type(int n, W workspace)\n{\n  std::cout << \"  upper\\n\" ;\n  if(do_memory_uplo<T,W,ublas::upper>(n, workspace)) return 255 ;\n  std::cout << \"  lower\\n\" ;\n  if(do_memory_uplo<T,W,ublas::lower>(n, workspace)) return 255 ;\n  return 0 ;\n}\n\n\ntemplate <typename T>\nstruct Workspace\n{\n  typedef ublas::vector< T >                                       array_type ;\n  typedef ublas::vector< fortran_int_t >                               int_array_type ;\n  typedef lapack::detail::workspace2< array_type, int_array_type > type ;\n\n  Workspace(size_t n)\n    : work_(8*n)\n    , iwork_(5*n)\n  {}\n\n  type operator()()\n  {\n    return lapack::workspace(work_, iwork_) ;\n  }\n\n  array_type work_ ;\n  int_array_type iwork_ ;\n};\n\ntemplate <typename T>\nstruct Workspace< std::complex<T> >\n{\n  typedef ublas::vector< std::complex<T> >                 complex_array_type ;\n  typedef ublas::vector< T >                               real_array_type ;\n  typedef ublas::vector< fortran_int_t >                       int_array_type ;\n  typedef lapack::detail::workspace3<\n  complex_array_type, real_array_type, int_array_type > type ;\n\n  Workspace(size_t n)\n    : work_(2*n)\n    , rwork_(7*n)\n    , iwork_(5*n)\n  {}\n\n  type operator()()\n  {\n    return lapack::workspace(work_, rwork_, iwork_) ;\n  }\n\n  complex_array_type work_ ;\n  real_array_type    rwork_ ;\n  int_array_type     iwork_ ;\n};\n\n\ntemplate <typename T>\nint do_value_type()\n{\n  const int n = 8 ;\n\n  std::cout << \" optimal workspace\\n\";\n  if(do_memory_type<T,lapack::optimal_workspace>(n, lapack::optimal_workspace())) return 255 ;\n\n  std::cout << \" minimal workspace\\n\";\n  if(do_memory_type<T,lapack::minimal_workspace>(n, lapack::minimal_workspace())) return 255 ;\n\n  std::cout << \" workspace array\\n\";\n  Workspace<T> work(n);\n  if(do_memory_type<T,typename Workspace<T>::type >(n, work())) return 255 ;\n  return 0;\n} // do_value_type()\n\n\nint main()\n{\n  // Run tests for different value_types\n  std::cout << \"float\\n\" ;\n  if(do_value_type< float >()) return 255;\n\n  std::cout << \"double\\n\" ;\n  if(do_value_type< double >()) return 255;\n\n  std::cout << \"complex<float>\\n\" ;\n  if(do_value_type< std::complex<float> >()) return 255;\n\n  std::cout << \"complex<double>\\n\" ;\n  if(do_value_type< std::complex<double> >()) return 255;\n\n  std::cout << \"Regression test succeeded\\n\" ;\n  return 0;\n}\n\n", "meta": {"hexsha": "c01cfca3483c51d308e6cd984009ac6bd395c255", "size": 5100, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "externals/numeric_bindings/libs/numeric/bindings/lapack/test/ublas_heevx.cpp", "max_stars_repo_name": "fperignon/sandbox", "max_stars_repo_head_hexsha": "649f09d6db7bbd84c2418de74eb9453c0131f070", "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/lapack/test/ublas_heevx.cpp", "max_issues_repo_name": "fperignon/sandbox", "max_issues_repo_head_hexsha": "649f09d6db7bbd84c2418de74eb9453c0131f070", "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/lapack/test/ublas_heevx.cpp", "max_forks_repo_name": "fperignon/sandbox", "max_forks_repo_head_hexsha": "649f09d6db7bbd84c2418de74eb9453c0131f070", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 30.0, "max_forks_repo_forks_event_min_datetime": "2015-08-06T22:57:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T20:30:20.000Z", "avg_line_length": 27.5675675676, "max_line_length": 97, "alphanum_fraction": 0.6662745098, "num_tokens": 1515, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.47133306867598346}}
{"text": "#include <cassert>\n\n#include <dlib/random_forest.h>\n#include <dlib/global_optimization.h>\n\n#include \"common.hpp\"\n#include \"data.hpp\"\n\nnamespace SAMPML_NAMESPACE {\n    namespace trainer {\n        template <class sample_type>\n        class random_forest {\n        public:\n            random_forest() { }\n\n            template <class SamplesContainer, class LabelsContainer>\n            void set_samples(const SamplesContainer& _samples, const LabelsContainer& _labels) {\n                samples.clear();\n                samples.insert(samples.end(), _samples.cbegin(), _samples.cend());\n                labels.clear();\n                labels.insert(labels.end(), _labels.end(), _labels.size());\n            }\n            \n            template <class SamplesContainer>\n            void set_samples(const SamplesContainer& positives, const SamplesContainer& negatives) {\n                static_assert(std::is_same<typename SamplesContainer::value_type, sample_type>());\n\n                samples.clear();\n                samples.insert(samples.end(), positives.cbegin(), positives.cend());\n                samples.insert(samples.end(), negatives.cbegin(), negatives.cend());\n                labels.clear();\n                labels.insert(labels.end(), positives.size(), 1.0);\n                labels.insert(labels.end(), negatives.size(), 0.0);\n            }\n            \n            void cross_validate(double min_trees = 10, double max_trees = 1000,\n                                double min_frac = 0.9, double max_frac = 1.0,\n                                double min_min_per_leaf = 5, double max_min_per_leaf = 50,\n                                int folds = 10,\n                                int max_function_calls = 50) {\n                if(samples.size() == 0) {\n                    throw bad_input(\"Bad Input: no samples were provided for training\");\n                }\n                assert(labels.size() == samples.size());\n                \n                dlib::vector_normalizer<sample_type> normalizer;\n                normalizer.train(samples);\n                for(auto& vector : samples)\n                    vector = normalizer(vector);\n\n                dlib::randomize_samples(samples, labels);\n\n                auto cross_validation_score = \n                [this, folds](int trees, double subsample_frac, int min_sampels_per_leaf) {\n                    dlib::random_forest_regression_trainer<dlib::dense_feature_extractor> trainer;\n                    trainer.set_num_trees(trees);\n                    trainer.set_feature_subsampling_fraction(subsample_frac);\n                    trainer.set_min_samples_per_leaf(min_sampels_per_leaf);\n\n                    dlib::matrix<double> result = dlib::cross_validate_regression_trainer(trainer, this->samples, this->labels, folds);\n                    std::cout << \"trees: \" << trees << \", cross validation accuracy: \" << result << '\\n';\n\n                    return result(0);\n                };\n\n                auto result = dlib::find_min_global(dlib::default_thread_pool(), \n                                                    cross_validation_score, \n                                                    {min_trees, min_frac, min_min_per_leaf},\n                                                    {max_trees, max_frac, max_min_per_leaf},\n                                                    dlib::max_function_calls(max_function_calls));\n\n                best_num_trees = result.x(0);\n                best_subsample_fraction = result.x(1);\n                best_min_samples_per_leaf = result.x(2);\n                std::cout << result.x << '\\n';\n            }\n\n            void train () {                \n                dlib::random_forest_regression_trainer<feature_extractor_type> trainer;\n                trainer.set_num_trees(best_num_trees);\n                trainer.set_feature_subsampling_fraction(best_subsample_fraction);\n                trainer.set_min_samples_per_leaf(best_min_samples_per_leaf);\n\n                classifier = trainer.train(samples, labels, oobs);\n            }\n\n            void serialize(std::string classifier) {\n                dlib::serialize(classifier) << this->classifier;\n            }\n\n            void deserialize(std::string classifier) {\n                dlib::deserialize(classifier) >> this->classifier;\n            }\n\n            double test(const sample_type& sample) {\n                return classifier(sample);\n            }\n\n        protected:\n            std::vector<dlib::matrix<double, 0, 1>> samples;\n            std::vector<double> labels;\n            std::vector<double> oobs;\n\n            using feature_extractor_type = dlib::dense_feature_extractor;\n            using decision_funct_type = dlib::random_forest_regression_function<feature_extractor_type>;\n            //using normalized_decision_funct_type = dlib::normalized_function<decision_funct_type>;\n            decision_funct_type classifier;\n        \n            double best_num_trees = 100;\n            double best_subsample_fraction = 0.25;\n            double best_min_samples_per_leaf = 5;\n        };\n    }\n}", "meta": {"hexsha": "a6f04893187e9082b96f40c22f27ab7029a6b0e5", "size": 5081, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sampml/sampml/random_forest.hpp", "max_stars_repo_name": "YashasSamaga/sampml", "max_stars_repo_head_hexsha": "dc84110b53b120caeeb4c0234fcfd6ab16793c59", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2018-12-01T18:30:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-08T21:53:36.000Z", "max_issues_repo_path": "sampml/sampml/random_forest.hpp", "max_issues_repo_name": "YashasSamaga/sampml", "max_issues_repo_head_hexsha": "dc84110b53b120caeeb4c0234fcfd6ab16793c59", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-08-21T17:52:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-17T03:28:11.000Z", "max_forks_repo_path": "sampml/sampml/random_forest.hpp", "max_forks_repo_name": "YashasSamaga/sampml", "max_forks_repo_head_hexsha": "dc84110b53b120caeeb4c0234fcfd6ab16793c59", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-09-04T14:53:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T17:53:33.000Z", "avg_line_length": 44.5701754386, "max_line_length": 135, "alphanum_fraction": 0.5506790002, "num_tokens": 924, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384736, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4713330626445199}}
{"text": "// clang: MatousFormat\n\n// Include the LKF header\n#include <mrs_lib/geometry/cyclic.h>\n#include <iostream>\n#include <iomanip>\n#include <chrono>\n#include <complex>\n#include <Eigen/Dense>\n\nusing namespace mrs_lib::geometry;\nusing cx = std::complex<double>;\n\ndouble wrap(double r)\n{\n  return std::arg(std::polar<double>(1, r));\n}\n\ndouble diff(const double a, const double b)\n{\n  return std::arg(std::polar<double>(1, a) * std::conj(std::polar<double>(1, b)));\n}\n\nstatic double dist(const double a, const double b)\n{\n  return std::abs(diff(a, b));\n}\n\n/* interpolateAngles() //{ */\n\ndouble interpolateAngles(const double& a1, const double& a2, const double& coeff)\n{\n\n  // interpolate the yaw\n  Eigen::Vector3d axis = Eigen::Vector3d(0, 0, 1);\n\n  Eigen::Quaterniond quat1 = Eigen::Quaterniond(Eigen::AngleAxis<double>(a1, axis));\n  Eigen::Quaterniond quat2 = Eigen::Quaterniond(Eigen::AngleAxis<double>(a2, axis));\n\n  Eigen::Quaterniond new_quat = quat1.slerp(coeff, quat2);\n\n  Eigen::Vector3d vecx = new_quat * Eigen::Vector3d(1, 0, 0);\n\n  return atan2(vecx[1], vecx[0]);\n}\n\n//}\n\nint main()\n{\n  std::function correct(interpolateAngles);\n  auto totest = std::bind<double(double, double,double)>(sradians::interpUnwrapped, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);\n\n  const std::vector<double> tst {-0.0, 0.0, 1, -1, M_PI, -M_PI, 2*M_PI, -2*M_PI};\n  std::cout <<\n    \"\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\\n\"\n    \"\u2502  correct   \u2502  mrs_lib   \u2502 difference \u2502\\n\"\n    \"\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\\n\"\n    ;\n  for (const auto& a : tst)\n  {\n    for (const auto& b : tst)\n    {\n      for (const auto& c : tst)\n      {\n        const auto cor = correct(a, b, c);\n        const auto res = totest(a, b, c);\n        const auto dif = dist(cor, res);\n        const bool ok = dif < 1e-9;\n        if (!ok)\n          std::cout << \"\\033[1;31m\";\n        std::cout << std::left << std::showpos << std::setprecision(4)\n        << \"\u2502 \" << std::setw(10) << cor << \" \u2502 \" << std::setw(10) << res << \" \u2502 \" << std::setw(10) << dif << \" |\";\n        if (!ok)\n          std::cout << \"\\tfor values: \" << std::left << std::showpos << std::setprecision(4) << a << \"\\tand\\t\" << b << \"\\tand\\t\" << c << \"\\033[0m\";\n        std::cout << std::endl;\n      }\n    }\n  }\n  std::cout <<\n  \"\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\" << std::endl;\n\n  constexpr int N = 1e4;\n  const auto start1 = std::chrono::high_resolution_clock::now();\n  for (int it = 0; it < N; it++)\n  {\n    for (const auto& a : tst)\n    {\n      for (const auto& b : tst)\n      {\n        for (const auto& c : tst)\n        {\n          [[maybe_unused]] volatile auto cor = correct(a, b, c);\n        }\n      }\n    }\n  }\n  const auto stop1 = std::chrono::high_resolution_clock::now();\n\n  const auto start2 = std::chrono::high_resolution_clock::now();\n  for (int it = 0; it < N; it++)\n  {\n    for (const auto& a : tst)\n    {\n      for (const auto& b : tst)\n      {\n        for (const auto& c : tst)\n        {\n          [[maybe_unused]] volatile auto cor = totest(a, b, c);\n        }\n      }\n    }\n  }\n  const auto stop2 = std::chrono::high_resolution_clock::now();\n\n  std::cout << \"dur1: \" << std::chrono::duration_cast<std::chrono::microseconds>(stop1-start1).count()/double(N) << \"us\" << std::endl;\n  std::cout << \"dur2: \" << std::chrono::duration_cast<std::chrono::microseconds>(stop2-start2).count()/double(N) << \"us\" << std::endl;\n\n  return 0;\n}\n\n\n\n\n", "meta": {"hexsha": "6b39e9dca3f34741cc63dbb1a7f5c9ada6a844f3", "size": 3411, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/geometry/tests.cpp", "max_stars_repo_name": "ctu-mrs/mrs_lib", "max_stars_repo_head_hexsha": "1df4282d71c2944904676adbb7289ce45004432a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-17T17:42:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T17:42:09.000Z", "max_issues_repo_path": "src/geometry/tests.cpp", "max_issues_repo_name": "ctu-mrs/mrs_lib", "max_issues_repo_head_hexsha": "1df4282d71c2944904676adbb7289ce45004432a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2020-10-20T09:36:36.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-08T19:17:26.000Z", "max_forks_repo_path": "src/geometry/tests.cpp", "max_forks_repo_name": "ctu-mrs/mrs_lib", "max_forks_repo_head_hexsha": "1df4282d71c2944904676adbb7289ce45004432a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-04-02T08:47:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-05T12:54:05.000Z", "avg_line_length": 27.288, "max_line_length": 153, "alphanum_fraction": 0.5529170331, "num_tokens": 1059, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384736, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4713330626445199}}
{"text": "#include <boost/graph/circle_layout.hpp>\n", "meta": {"hexsha": "1a1f8e4351fd2b638c0a83f982421bca8d6c089e", "size": 41, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_graph_circle_layout.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_graph_circle_layout.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_graph_circle_layout.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 20.5, "max_line_length": 40, "alphanum_fraction": 0.8048780488, "num_tokens": 9, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7853085708384735, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.47133306264451985}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2015 NumScale SAS\n  @copyright 2015 J.T. Lapreste\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_COMMON_FUNCTION_GENERIC_INDEG_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_FUNCTION_GENERIC_INDEG_HPP_INCLUDED\n\n#include <boost/simd/constant/radindeg.hpp>\n#include <boost/simd/constant/radindegr.hpp>\n#include <boost/simd/function/minus.hpp>\n#include <boost/simd/function/multiplies.hpp>\n#include <boost/simd/function/indeg.hpp>\n#include <boost/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 ( indeg_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::generic_< bd::floating_<A0> >\n                          )\n  {\n    using result_t = A0;\n    A0 operator() ( A0 const& a0) const\n    {\n      return (a0*Radindeg<result_t>())-(a0*Radindegr<result_t>());\n    }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "f8bbf029d53f861a373d8338d82850b2128a8099", "size": 1340, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arch/common/generic/function/indeg.hpp", "max_stars_repo_name": "yaeldarmon/boost.simd", "max_stars_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/simd/arch/common/generic/function/indeg.hpp", "max_issues_repo_name": "yaeldarmon/boost.simd", "max_issues_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/arch/common/generic/function/indeg.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": 31.1627906977, "max_line_length": 100, "alphanum_fraction": 0.5664179104, "num_tokens": 293, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583695, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.4712839171842327}}
{"text": "#include <iostream>\n#include <fstream>\n#include <Eigen/Dense>\n\n#include <ompl/base/spaces/RealVectorStateSpace.h>\n#include \"ompl/base/SpaceInformation.h\"\n#include <ompl/geometric/planners/GSE/GSE.h>\n#include \"ompl/base/spaces/RealVectorStateProjections.h\"\n\nusing namespace std;\nnamespace ob = ompl::base;\nnamespace og = ompl::geometric;\n\nvoid genSphere(Eigen::MatrixXd &sphere);\nbool isStateValid(const ob::State *state);\n\nint main()\n{\n    // construct the state space we are planning in\n    auto space(std::make_shared<ob::RealVectorStateSpace>(3));\n    \n    // set the bounds for the R^3 part of SE(3)\n    space->setBounds(-2.1,2.1);\n    \n    // construct an instance of  space information from this state space\n    auto si(std::make_shared<ob::SpaceInformation>(space));\n    // set state validity checking for this space\n    si->setStateValidityChecker(isStateValid);\n    \n    // create a start state and goal state\n    ob::ScopedState<> start(space),goal(space);\n    start = {-2.0,-2.0,-2.0};\n    goal  = {2.0,2.0,2.0};\n    \n    // create a problem instance, set the start and goal states\n    auto pdef(std::make_shared<ob::ProblemDefinition>(si));\n    pdef->setStartAndGoalStates(start, goal);\n\n    // create a GSE planner for the defined space\n    auto planner(std::make_shared<og::GSE>(si,3));\n    planner->setProblemDefinition(pdef);\n\n    // Add obstacles to planner for planning\n    Eigen::MatrixXd sphere(1000,3);\n    genSphere(sphere); // generate a sphere obstacle\n    vector<vector<double>> obs{ {0,0,0},\n                            {0,-2,0},\n                            {0,2,0},\n                            {-2,0,0},\n                            {2,0,0},\n                            {0,0,-2},\n                            {0,0,2},\n                            {1,1,1}}; // Locations where we want to place the spherical obstacle\n    for(auto row:obs){\n        Eigen::VectorXd centre = Eigen::Map<Eigen::VectorXd>(row.data(),row.size());\n        Eigen::MatrixXd obsi = (0.5*sphere.transpose()).colwise()+centre;\n        planner->addObstacle(obsi);\n    }\n\n    // Set the Projector to extract an Eigen::Vector state from base::state \n    std::vector<uint> projectionDimensions{0,1,2};\n    auto projector(std::make_shared<ob::RealVectorOrthogonalProjectionEvaluator>(space,projectionDimensions));\n    planner->setProjector(projector);\n    \n    // Setup the planner\n    planner->setup();\n\n    // attempt to solve the problem within one second of planning time\n    ob::PlannerStatus solved = planner->ob::Planner::solve(1);\n\n    if (solved)\n    {\n        ob::PathPtr path = pdef->getSolutionPath();\n        cout << \"Found solution:\" << std::endl;\n\n        // print the path to screen\n        path->as<og::PathGeometric>()->printAsMatrix(cout);\n    }\n    else\n        cout << \"No solution found\" << std::endl;\n\n    return 0;\n}\n\n// generate Uniform randomn Points on a sphere of raidius 1\n// http://corysimon.github.io/articles/uniformdistn-on-sphere/ \nvoid genSphere(Eigen::MatrixXd &sphere){\n    int N = sphere.rows();\n    auto theta = 2*M_PI*(Eigen::ArrayXd::Random(N)*0.5+0.5);\n    auto phi = Eigen::ArrayXd::Random(N).acos();\n\n    Eigen::VectorXd x = phi.sin()*theta.cos();\n    Eigen::VectorXd y = phi.sin()*theta.sin();\n    Eigen::VectorXd z = phi.cos();\n\n    sphere<<x,y,z;\n}\n\nbool isStateValid(const ob::State *state)\n{\n    // return a value that is always true but uses the argument, so we avoid compiler warnings\n    return state;\n}", "meta": {"hexsha": "c7af64ac288921789c34f5c9008941fa45e9fbdf", "size": 3445, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "demos/RigidBodyPlanning.cpp", "max_stars_repo_name": "nikhilprakash99/Generalised-Shape-Expansion-GSE", "max_stars_repo_head_hexsha": "fbce216271a28727a3c37707f410de7ae34e2b65", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-09T13:54:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-09T13:54:00.000Z", "max_issues_repo_path": "demos/RigidBodyPlanning.cpp", "max_issues_repo_name": "nikhilprakash99/Generalised-Shape-Expansion-GSE", "max_issues_repo_head_hexsha": "fbce216271a28727a3c37707f410de7ae34e2b65", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/RigidBodyPlanning.cpp", "max_forks_repo_name": "nikhilprakash99/Generalised-Shape-Expansion-GSE", "max_forks_repo_head_hexsha": "fbce216271a28727a3c37707f410de7ae34e2b65", "max_forks_repo_licenses": ["BSD-3-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.4466019417, "max_line_length": 110, "alphanum_fraction": 0.6284470247, "num_tokens": 892, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138365, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.4712379412731077}}
{"text": "#include <cstdlib>\n#include <iostream>\n#include <complex>\n#include <type_traits>\n#include <algorithm>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/banded.hpp>\n#include <boost/numeric/bindings/ublas/vector.hpp>\n#include <boost/numeric/bindings/ublas/banded.hpp>\n#include <boost/numeric/bindings/blas/level1.hpp>\n#include <boost/numeric/bindings/blas/level2.hpp>\n#include <boost/numeric/bindings/lapack/driver.hpp>\n#include \"random.hpp\"\n\nnamespace ublas=boost::numeric::ublas;\nnamespace blas=boost::numeric::bindings::blas;\nnamespace lapack=boost::numeric::bindings::lapack;\n\nint main(int argc, char *argv[]) {\n  typedef std::complex<double> complex;\n  typedef ublas::vector<complex> vector;\n  typedef ublas::vector<double> d_vector;\n  typedef ublas::banded_matrix<complex, ublas::column_major> matrix;\n  typedef ublas::matrix<complex, ublas::column_major> dense_matrix;\n  typedef typename std::make_signed<vector::size_type>::type size_type;\n\n  rand_normal<complex>::reset();\n  size_type n=1024;\n  matrix A(n, n, 1, 1);\n  for (size_type i=0; i<n; ++i)\n    A(i, i)=std::abs(rand_normal<complex>::get())+1;\n  for (size_type i=0; i<n-1; ++i) {\n    A(i+1, i)=complex(0);\n    A(i, i+1)=complex(0);\n  }\n  for (int k=0; k<n-1; ++k) {\n    // generate a random 2x2 unitary matrix\n    double phi(rand_uniform<double>::get(0, 1.5707963267948966192));\n    double alpha(rand_uniform<double>::get(0, 6.2831853071795864770));\n    double psi(rand_uniform<double>::get(0, 6.2831853071795864770));\n    double chi(rand_uniform<double>::get(0, 6.2831853071795864770));\n    dense_matrix u(2, 2);\n    u(0, 0)=complex(std::cos(alpha+psi), std::sin(alpha+psi))*std::cos(phi);\n    u(1, 0)=-complex(std::cos(alpha-chi), std::sin(alpha-chi))*std::sin(phi);\n    u(0, 1)=complex(std::cos(alpha+chi), std::sin(alpha+chi))*std::sin(phi);\n    u(1, 1)=complex(std::cos(alpha-psi), std::sin(alpha-psi))*std::cos(phi);\n    dense_matrix a(2, 2);\n    a(0, 0)=A(k, k);\n    a(1, 0)=A(k+1, k);\n    a(0, 1)=A(k, k+1);\n     a(1, 1)=A(k+1, k+1);\n    a=ublas::prod(ublas::trans(ublas::conj(u)), a);\n    a=ublas::prod(a, u);\n    A(k, k)=a(0, 0);\n    A(k+1, k)=a(1, 0);\n    A(k, k+1)=a(0, 1);\n    A(k+1, k+1)=a(1, 1);\n  }\n  vector b(n);\n  for (size_type i=0; i<n; ++i)\n    b(i)=rand_normal<complex>::get();\n  vector x(b);\n  d_vector d(n);\n  vector e(n-1);\n  for (size_type i=0; i<n; ++i)\n    d(i)=A(i ,i).real();\n  for (size_type i=0; i<n-1; ++i)\n    e(i)=A(i+1, i);\n  int info=lapack::ptsv(d, e, x); // solve\n  if (info==0) {\n    // res <- A*x - b\n    vector res(b);\n    blas::gbmv(complex(1, 0), A, x, complex(-1, 0), res);\n    std::cout << \"norm of residual : \" << blas::nrm2(res) << '\\n';\n  } else\n    if (info>0)\n      std::cout << \"singular matrix\\n\";\n    else \n      std::cout << \"illegal arguments\\n\";\n  return EXIT_SUCCESS;\n}\n\n", "meta": {"hexsha": "a6d8f122e52c9956af65e90f40a7311450aaf848", "size": 2858, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/lapack/ptsv.cc", "max_stars_repo_name": "rabauke/numeric_bindings", "max_stars_repo_head_hexsha": "f4de93bd7a01a8b31c9367fad35c81d086768f99", "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/lapack/ptsv.cc", "max_issues_repo_name": "rabauke/numeric_bindings", "max_issues_repo_head_hexsha": "f4de93bd7a01a8b31c9367fad35c81d086768f99", "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/lapack/ptsv.cc", "max_forks_repo_name": "rabauke/numeric_bindings", "max_forks_repo_head_hexsha": "f4de93bd7a01a8b31c9367fad35c81d086768f99", "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.0238095238, "max_line_length": 77, "alphanum_fraction": 0.6319104269, "num_tokens": 1003, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.4711694161436203}}
{"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/xva/gaussian1dscenariogenerator.hpp>\n#include <ql/experimental/models/gaussian1dyieldtermstructure.hpp>\n#include <ql/processes/forwardmeasureprocess.hpp>\n#include <boost/make_shared.hpp>\n\nnamespace QuantLib {\n\nGaussian1dSingleCurveScenarioGenerator::Gaussian1dSingleCurveScenarioGenerator(\n    const boost::shared_ptr<Gaussian1dModel> &model, const unsigned long seed)\n    : ScenarioGenerator<YieldTermStructure>(\n          model->termStructure()->calendar(),\n          model->termStructure()->dayCounter()),\n      model_(model) {\n    modelTime_ = time();\n    modelState_ = model_->stateProcess()->x0();\n    mt_ = boost::make_shared<MersenneTwisterUniformRng>(seed);\n    icrng_ = boost::make_shared<InverseCumulativeRng<MersenneTwisterUniformRng,\n                                                     InverseCumulativeNormal> >(\n        *mt_);\n}\n\nbool Gaussian1dSingleCurveScenarioGenerator::nextPath() {\n    ScenarioGenerator<YieldTermStructure>::nextPath();\n    modelTime_ = time();\n    return true;\n}\n\nconst Date\nGaussian1dSingleCurveScenarioGenerator::advance(const Period &suggestedStep) {\n    ScenarioGenerator<YieldTermStructure>::advance(suggestedStep);\n    Real newModelTime_ = time();\n    boost::shared_ptr<ForwardMeasureProcess> fmp =\n        boost::dynamic_pointer_cast<ForwardMeasureProcess>(\n            model_->stateProcess());\n    if (fmp != NULL)\n        if (newModelTime_ > fmp->getForwardMeasureTime())\n            validHorizonDate_ = false;\n    if (validHorizonDate_) {\n        Real dt = newModelTime_ - modelTime_;\n        Real dw = std::sqrt(dt) * icrng_->next().value;\n        modelState_ =\n            model_->stateProcess()->evolve(modelTime_, modelState_, dt, dw);\n    }\n    modelTime_ = newModelTime_;\n    return horizonDate();\n}\n\nconst boost::shared_ptr<YieldTermStructure>\nGaussian1dSingleCurveScenarioGenerator::state() const {\n    return boost::make_shared<Gaussian1dYieldTermStructure>(\n        model_, modelTime_, model_->y(modelState_, modelTime_));\n}\n} // namespace QuantLib\n", "meta": {"hexsha": "9fbd78120a388b324c4e9b54c439dc26723d0be1", "size": 2835, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ql/experimental/xva/gaussian1dscenariogenerator.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/xva/gaussian1dscenariogenerator.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/xva/gaussian1dscenariogenerator.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": 38.8356164384, "max_line_length": 80, "alphanum_fraction": 0.7199294533, "num_tokens": 669, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.47113389983417586}}
{"text": "// ---------------------------------------------------------------------\n//\n// Copyright (c) 2014 - 2019 by the IBAMR developers\n// All rights reserved.\n//\n// This file is part of IBAMR.\n//\n// IBAMR is free software and is distributed under the 3-clause BSD\n// license. The full text of the license can be found in the file\n// COPYRIGHT at the top level directory of IBAMR.\n//\n// ---------------------------------------------------------------------\n\n// Test that we get the same thing with the boost version of Gauss-Kronrod\n// quadrature that we did with the GSL version.\n//\n// This test doesn't actually use IBAMR.\n\n#include <boost/math/quadrature/gauss_kronrod.hpp>\n\n#include <cassert>\n#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <numeric>\n#include <utility>\n#include <vector>\n\n// Set Fish Related Parameters.\nstatic const double PII = 3.1415926535897932384626433832795;\nstatic const double LENGTH_FISH = 1.0;\nstatic const double WIDTH_HEAD = 0.04 * LENGTH_FISH;\nstatic const double LENGTH_TILLHEAD = 0.04 * LENGTH_FISH;\nstatic const double MAJOR_AXIS = 0.51 * LENGTH_FISH;\nstatic const double MINOR_AXIS = 0.08 * LENGTH_FISH;\n\ndouble\nxPosition(double s, void* params)\n{\n    double* input = static_cast<double*>(params);\n    double a0 = input[0];\n    double a1 = input[1];\n    double a2 = input[2];\n    double a3 = input[3];\n    double tau = input[4];\n    double t = input[5];\n    double T = input[6];\n\n    double x =\n        std::cos((1 / (8 * std::pow(PII * tau, 4))) * (std::tanh(PII * t / T)) *\n                 (2 * PII * tau * (a2 - 2 * a0 * std::pow(PII * tau, 2)) * std::cos((2 * PII * t) / T) +\n                  2 * PII * tau * (-a2 - 3 * a3 * s + 2 * PII * PII * (a0 + s * (a1 + s * (a2 + a3 * s))) * tau * tau) *\n                      cos((2 * PII * (t - s * T * tau)) / T) +\n                  (3 * a3 - 2 * a1 * std::pow(PII * tau, 2)) * sin((2 * PII * t) / T) +\n                  (-3 * a3 + 2 * PII * PII * (a1 + 2 * a2 * s + 3 * a3 * s * s) * tau * tau) *\n                      std::sin((2 * PII * (t - s * T * tau)) / T)));\n\n    return x;\n\n} // xposition\n\ndouble\nyPosition(double s, void* params)\n{\n    double* input = static_cast<double*>(params);\n    double a0 = input[0];\n    double a1 = input[1];\n    double a2 = input[2];\n    double a3 = input[3];\n    double tau = input[4];\n    double t = input[5];\n    double T = input[6];\n\n    double y =\n        std::sin((1 / (8 * std::pow(PII * tau, 4))) * (std::tanh(PII * t / T)) *\n                 (2 * PII * tau * (a2 - 2 * a0 * std::pow(PII * tau, 2)) * std::cos((2 * PII * t) / T) +\n                  2 * PII * tau * (-a2 - 3 * a3 * s + 2 * PII * PII * (a0 + s * (a1 + s * (a2 + a3 * s))) * tau * tau) *\n                      cos((2 * PII * (t - s * T * tau)) / T) +\n                  (3 * a3 - 2 * a1 * std::pow(PII * tau, 2)) * sin((2 * PII * t) / T) +\n                  (-3 * a3 + 2 * PII * PII * (a1 + 2 * a2 * s + 3 * a3 * s * s) * tau * tau) *\n                      std::sin((2 * PII * (t - s * T * tau)) / T)));\n\n    return y;\n\n} // yPosition\n\nint\nmain()\n{\n    const double Lx = 8;\n    const double Ly = 4;\n    const double Lz = 1;\n    const int Nx = 16 * 4 * 4 * 2;\n    const int Ny = 8 * 4 * 4 * 2;\n    const int Nz = 4 * 4 * 4 * 2;\n\n    const double dx = Lx / Nx;\n    const double dy = Ly / Ny;\n    const double dz = Lz / Nz;\n\n    const double tau_tail = 1.52;\n    const double a0 = 1.29, a1 = -22.57, a2 = 78.39, a3 = -52.83;\n    const double t = 0.0;\n    const double time_period = 1.0;\n\n    double interp_coefs[4];\n    interp_coefs[0] = a0;\n    interp_coefs[1] = a1;\n    interp_coefs[2] = a2;\n    interp_coefs[3] = a3;\n\n    // No. of points on the backbone and till head.\n    const int headNs = static_cast<int>(ceil(LENGTH_TILLHEAD / dx));\n    const int tailNs = static_cast<int>(ceil((LENGTH_FISH - LENGTH_TILLHEAD) / dx));\n    const int bodyNs = headNs + tailNs + 1;\n\n    std::vector<std::pair<int, int> > immersedBodyData(bodyNs);\n    std::vector<std::pair<double, double> > immersedBodyWidthHeight(bodyNs);\n\n    for (int i = 1; i <= headNs + 1; ++i)\n    {\n        const double s = (i - 1) * dx;\n        const double section = sqrt(2 * WIDTH_HEAD * s - s * s);\n        const double height = MINOR_AXIS * std::sqrt(1 - pow((s - MAJOR_AXIS) / MAJOR_AXIS, 2));\n        const int numPtsInSection = static_cast<int>(ceil(section / dy));\n        const int numPtsInHeight = static_cast<int>(ceil(height / dz));\n        immersedBodyData[i - 1] = std::make_pair(numPtsInSection, numPtsInHeight);\n        immersedBodyWidthHeight[i - 1] = std::make_pair(section, height);\n    }\n\n    for (int i = headNs + 2; i <= bodyNs; ++i)\n    {\n        const double s = (i - 1) * dx;\n        const double section = WIDTH_HEAD * (LENGTH_FISH - s) / (LENGTH_FISH - LENGTH_TILLHEAD);\n        const double height = MINOR_AXIS * std::sqrt(1 - pow((s - MAJOR_AXIS) / MAJOR_AXIS, 2));\n        const int numPtsInSection = static_cast<int>(ceil(section / dy));\n        const int numPtsInHeight = static_cast<int>(ceil(height / dz));\n        immersedBodyData[i - 1] = std::make_pair(numPtsInSection, numPtsInHeight);\n        immersedBodyWidthHeight[i - 1] = std::make_pair(section, height);\n    }\n\n    int total_lag_pts = 0;\n\n    double input[7];\n    input[0] = interp_coefs[0];\n    input[1] = interp_coefs[1];\n    input[2] = interp_coefs[2];\n    input[3] = interp_coefs[3];\n    input[4] = tau_tail;\n    input[5] = t;\n    input[6] = time_period;\n\n    // Find the deformed shape. Rotate the shape about center of mass.\n    std::vector<std::vector<double> > shape_new(3);\n    for (int i = 1; i <= bodyNs; ++i)\n    {\n        const int numPtsInSection = immersedBodyData[i - 1].first;\n        const int numPtsInHeight = immersedBodyData[i - 1].second;\n        const double width = immersedBodyWidthHeight[i - 1].first;\n        const double depth = immersedBodyWidthHeight[i - 1].second;\n        const double s = (i - 1) * dx;\n\n        auto f_x = [&](const double x) { return xPosition(x, input); };\n\n        auto f_y = [&](const double y) { return yPosition(y, input); };\n\n        namespace bmq = boost::math::quadrature;\n        const double xbase = bmq::gauss_kronrod<double, 15>::integrate(f_x, 0.0, s, 15, 1e-12, nullptr);\n        const double ybase = bmq::gauss_kronrod<double, 15>::integrate(f_y, 0.0, s, 15, 1e-12, nullptr);\n\n        if (numPtsInSection && numPtsInHeight)\n        {\n            // Fill the middle line first.\n            for (int k = -numPtsInHeight; k <= numPtsInHeight; ++k)\n            {\n                shape_new[0].push_back(xbase);\n                shape_new[1].push_back(ybase);\n                shape_new[2].push_back(k * dz);\n            } // middle line filled.\n\n            total_lag_pts += 2 * numPtsInHeight + 1;\n\n            // Fill the rest of the cross section next.\n            for (int j = 1; j <= numPtsInSection; ++j)\n            {\n                const double y = j * dy;\n                for (int k = -numPtsInHeight; k <= numPtsInHeight; ++k)\n                {\n                    const double z = k * dz;\n                    if ((std::pow(y / width, 2) + std::pow(z / depth, 2)) <= 1) // use elliptical cross sections\n                    {\n                        shape_new[0].push_back(xbase); // right side.\n                        shape_new[1].push_back(ybase + y);\n                        shape_new[2].push_back(z);\n\n                        shape_new[0].push_back(xbase); // left side.\n                        shape_new[1].push_back(ybase - y);\n                        shape_new[2].push_back(z);\n\n                        total_lag_pts += 2;\n                    }\n                }\n            } // cross section filled\n        }\n    }\n    std::ofstream eelstream(\"output\");\n    eelstream.precision(12);\n    assert(static_cast<std::size_t>(total_lag_pts) == shape_new[0].size());\n    eelstream << total_lag_pts << \"\\n\";\n\n    for (int k = 1; k <= total_lag_pts; ++k)\n        eelstream << shape_new[0][k - 1] + 5.5 << \"\\t\" << shape_new[1][k - 1] << \"\\t\" << shape_new[2][k - 1] << \"\\n\";\n\n    return 0;\n}\n", "meta": {"hexsha": "c6a743e36269158c377b618123e5ef2c68c65582", "size": 8018, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/external/eelgenerator3d.cpp", "max_stars_repo_name": "jabrown893/IBAMR", "max_stars_repo_head_hexsha": "5fb055bd04d0c76c217c1b051f0a696d4892aa81", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/external/eelgenerator3d.cpp", "max_issues_repo_name": "jabrown893/IBAMR", "max_issues_repo_head_hexsha": "5fb055bd04d0c76c217c1b051f0a696d4892aa81", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/external/eelgenerator3d.cpp", "max_forks_repo_name": "jabrown893/IBAMR", "max_forks_repo_head_hexsha": "5fb055bd04d0c76c217c1b051f0a696d4892aa81", "max_forks_repo_licenses": ["BSD-3-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.1203703704, "max_line_length": 120, "alphanum_fraction": 0.5325517585, "num_tokens": 2474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257653, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4711338998341758}}
{"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 *    References\n *      An example of a heritage code which uses such a mesh is found in:\n *          The Mark IV Supersonic-Hypersonic Arbitrary Body Program, Volume\n *          II-Program Formulation, Douglas Aircraft Company, AFFDL-TR-73-159,\n *          Volume II.\n *\n *    Notes\n *      The numberOfLines_ and numberOfPoints_ member variables denote the number of mesh points.\n *      The number of panels in the mesh will be numberOfLines_ - 1 by numberOfPoints_ - 1.\n *\n */\n\n#include <boost/multi_array.hpp>\n#include <iostream>\n#include <limits>\n#include <Eigen/Geometry>\n\n#include \"Tudat/Mathematics/GeometricShapes/quadrilateralMeshedSurfaceGeometry.h\"\n\nnamespace tudat\n{\nnamespace geometric_shapes\n{\n\n//! Calculate panel characteristics.\nvoid QuadrilateralMeshedSurfaceGeometry::performPanelCalculations( )\n{\n    // Allocate memory for panel properties.\n    panelCentroids_.resize(boost::extents[ numberOfLines_ - 1 ][ numberOfPoints_ - 1 ]);\n    panelSurfaceNormals_.resize(boost::extents[ numberOfLines_ - 1 ][ numberOfPoints_ - 1 ]);\n    panelAreas_.resize(boost::extents[ numberOfLines_ - 1 ][ numberOfPoints_ - 1 ]);\n\n    // Declare local variables for normal and area determination.\n    Eigen::Vector3d crossVector1;\n    Eigen::Vector3d crossVector2;\n\n    // Reset total area.\n    totalArea_ = 0.0;\n\n    // Loop over all panels to determine properties.\n    for ( int i = 0; i < numberOfLines_ - 1; i++ )\n    {\n        for ( int j = 0; j < numberOfPoints_ - 1; j++ )\n        {\n            // Set panel centroid.\n            panelCentroids_[ i ][ j ] = ( meshPoints_[ i ][ j ] +\n                                          meshPoints_[ i + 1 ][ j ] +\n                                          meshPoints_[ i ][ j + 1 ] +\n                                          meshPoints_[ i + 1 ][ j + 1 ] ) / 4;\n\n            // Set panel cross vectors.\n            crossVector1 = meshPoints_[ i + 1 ][ j + 1 ] - meshPoints_[ i ][ j ];\n            crossVector2 = meshPoints_[ i + 1 ][ j ] - meshPoints_[ i ][ j + 1 ];\n\n            // Set panel normal (not yet normalized).\n            panelSurfaceNormals_[ i ][ j ] = crossVector1.cross( crossVector2 );\n\n            // Set panel area (not yet correct size).\n            panelAreas_[ i ][ j ] = panelSurfaceNormals_[ i ][ j ].norm( );\n            if ( panelAreas_[ i ][ j ] < std::numeric_limits< double >::epsilon( ) )\n            {\n                std::cerr << \"Warning, panel area is zero in part at panel\" << i\n                          << \", \" << j << std::endl;\n            }\n\n            // Normalize panel normal and, if necessary, invert normal direction.\n            panelSurfaceNormals_[ i ][ j ] *= reversalOperator_;\n            panelSurfaceNormals_[ i ][ j ].normalize( );\n\n            // Set panel area to correct size.\n            panelAreas_[ i ][ j ] *= 0.5;\n\n            // Add panel area to total area.\n            totalArea_ += panelAreas_[ i ][ j ];\n        }\n    }\n}\n\n//! Set reversal operator.\nvoid QuadrilateralMeshedSurfaceGeometry::setReversalOperator( const bool isMeshInverted )\n{\n    if ( isMeshInverted == 0 )\n    {\n        reversalOperator_ = 1;\n    }\n\n    else\n    {\n        reversalOperator_ = -1;\n    }\n}\n\n//! Get boolean denoting if the mesh is inverted.\nbool QuadrilateralMeshedSurfaceGeometry::getReversalOperator( )\n{\n    bool isMeshInverted;\n    if ( reversalOperator_ == 1 )\n    {\n        isMeshInverted = 0;\n    }\n\n    else\n    {\n        isMeshInverted = 1;\n    }\n\n    return isMeshInverted;\n}\n\n//! Overload ostream to print class information.\nstd::ostream& operator << ( std::ostream& stream,\n                          QuadrilateralMeshedSurfaceGeometry& quadrilateralMeshedSurfaceGeometry )\n{\n    stream << \"This is a quadrilateral meshed surface geometry\"\n           << \" of a single part.\" << std::endl;\n    stream << \"The number of lines ( contours ) is: \"\n           << quadrilateralMeshedSurfaceGeometry.numberOfLines_ << std::endl;\n    stream << \"The number of points per line is: \"\n           << quadrilateralMeshedSurfaceGeometry.numberOfPoints_ << std::endl;\n\n    // Return stream.\n    return stream;\n}\n\n} // namespace geometric_shapes\n} // namespace tudat\n", "meta": {"hexsha": "b4413dd4400343bf57f9defc4dce11e14948cc9f", "size": 4589, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Mathematics/GeometricShapes/quadrilateralMeshedSurfaceGeometry.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/Mathematics/GeometricShapes/quadrilateralMeshedSurfaceGeometry.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/Mathematics/GeometricShapes/quadrilateralMeshedSurfaceGeometry.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": 33.7426470588, "max_line_length": 98, "alphanum_fraction": 0.6057964698, "num_tokens": 1104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.5813030906443134, "lm_q1q2_score": 0.47113389451208865}}
{"text": "#include <path_follower/controller/robotcontroller_ackermann_inputscaling.h>\n\n\n#include <ros/ros.h>\n#include <geometry_msgs/Twist.h>\n#include <path_follower/utils/pose_tracker.h>\n#include <path_follower/utils/visualizer.h>\n#include <cslibs_navigation_utilities/MathHelper.h>\n#include <deque>\n#include <limits>\n#include <boost/algorithm/clamp.hpp>\n#include <time.h>\n#include <path_follower/factory/controller_factory.h>\n\nREGISTER_ROBOT_CONTROLLER(RobotController_Ackermann_Inputscaling, ackermann_inputscaling, ackermann);\n\nRobotController_Ackermann_Inputscaling::RobotController_Ackermann_Inputscaling() :\n    RobotController(),\n    phi_(0.),\n\tv1_(0.), v2_(0.)\n{\n\n\tconst double k = params_.k_forward();\n\tsetTuningParameters(k);\n\n\tROS_INFO(\"Parameters: k_forward=%f, k_backward=%f\\n\"\n\t\t\t\t\"factor_k1=%f, k2=%f, k3=%f\\n\"\n\t\t\t\t\"vehicle_length=%f\\n\"\n\t\t\t\t\"factor_steering_angle=%f\\n\"\n\t\t\t\t\"goal_tolerance=%f\\nmax_steering_angle=%f\",\n\t\t\t\tparams_.k_forward(), params_.k_backward(),\n\t\t\t\tparams_.factor_k1(), params_.factor_k2(), params_.factor_k3(),\n\t\t\t\tparams_.vehicle_length(),\n\t\t\t\tparams_.factor_steering_angle(),\n\t\t\t\tparams_.goal_tolerance(), params_.max_steering_angle());\n\n}\n\nvoid RobotController_Ackermann_Inputscaling::setTuningParameters(const double k) {\n\tk1_ = params_.factor_k1() * k * k * k;\n\tk2_ = params_.factor_k2() * k * k;\n\tk3_ = params_.factor_k3() * k;\n}\n\nvoid RobotController_Ackermann_Inputscaling::stopMotion() {\n\n\tmove_cmd_.setVelocity(0.f);\n\tmove_cmd_.setDirection(0.f);\n\n\tphi_ = 0.;\n\n\tMoveCommand cmd = move_cmd_;\n\tpublishMoveCommand(cmd);\n}\n\nvoid RobotController_Ackermann_Inputscaling::start() {\n\n}\n\nvoid RobotController_Ackermann_Inputscaling::reset() {\n\told_time_ = ros::Time::now();\n\n\tv1_ = v2_ = 0.;\n\n\ts_prim_ = 0.001; // TODO: good starting value\n\n\n    RobotController::reset();\n}\n\nvoid RobotController_Ackermann_Inputscaling::setPath(Path::Ptr path)\n{\n    RobotController::setPath(path);\n}\n\nRobotController::MoveCommandStatus RobotController_Ackermann_Inputscaling::computeMoveCommand(\n        MoveCommand* cmd)\n{\n\tif(path_interpol.n() <= 2)\n\t\treturn RobotController::MoveCommandStatus::ERROR;\n\n    const Eigen::Vector3d pose = pose_tracker_->getRobotPose();\n    const geometry_msgs::Twist velocity_measured = pose_tracker_->getVelocity();\n\n\tROS_DEBUG(\"velocity_measured: x=%f, y=%f, z=%f\", velocity_measured.linear.x,\n\t\t\t\tvelocity_measured.linear.y, velocity_measured.linear.z);\n\n    RobotController::findOrthogonalProjection();\n    double d = orth_proj_;\n\n    if(RobotController::isGoalReached(cmd)){\n       return RobotController::MoveCommandStatus::REACHED_GOAL;\n    }\n\n\t// draw a line to the orthogonal projection\n\tgeometry_msgs::Point from, to;\n    from.x = pose[0]; from.y = pose[1];\n    to.x = path_interpol.p(proj_ind_); to.y = path_interpol.q(proj_ind_);\n    visualizer_->drawLine(12341234, from, to, getFixedFrame(), \"Inputscaling\", 1, 0, 0, 1, 0.01);\n\n\t// theta_e = theta_vehicle - theta_path (orientation error)\n    double theta_e = MathHelper::AngleDelta(path_interpol.theta_p(proj_ind_), pose[2]);\n\n\t// if dir_sign is negative we drive backwards and set theta_e to the complementary angle\n    if (getDirSign() < 0.) {\n        d = -d;\n\t\tsetTuningParameters(params_.k_backward());\n        theta_e = theta_e > 0.? M_PI - theta_e : -M_PI - theta_e;\n\t} else {\n\t\tsetTuningParameters(params_.k_forward());\n\t}\n\n\t// curvature and first two derivations\n    const double c = path_interpol.curvature(proj_ind_);\n    const double c_prim = path_interpol.curvature_prim(proj_ind_);\n    const double c_sek = path_interpol.curvature_sek(proj_ind_);\n\n\t// 1 - dc(s)\n\tconst double _1_dc = 1. - d * c;\n\tconst double _1_dc_2 = _1_dc * _1_dc;\n\n\n\t// cos, sin, tan of theta_e and phi\n\tconst double cos_theta_e = cos(theta_e);\n\tconst double cos_theta_e_2 = cos_theta_e * cos_theta_e;\n\tconst double cos_theta_e_3 = cos_theta_e_2 * cos_theta_e;\n\n\tconst double sin_theta_e = sin(theta_e);\n\tconst double sin_theta_e_2 = sin_theta_e * sin_theta_e;\n\n\tconst double tan_theta_e = tan(theta_e);\n\tconst double tan_theta_e_2 = tan_theta_e * tan_theta_e;\n\n\tconst double tan_phi = tan(phi_);\n\tconst double tan_phi_2 = tan_phi * tan_phi;\n\n\n\tconst double time_passed = (ros::Time::now() - old_time_).toSec();\n\told_time_ = ros::Time::now();\n\n\tv1_ = abs(velocity_measured.linear.x);\n\n\ts_prim_ = cos_theta_e / _1_dc;\n\n\tconst double dd_ds = sin_theta_e * v1_ / s_prim_;\n\n    //theta_e_prim_ = (theta_e - old_theta_e_) * delta_s_inverse;\n\tconst double dtheta_e_ds = ((tan_phi / params_.vehicle_length() - c * cos_theta_e / _1_dc) * v1_)\n\t\t\t/ s_prim_;\n\n    // follows from: phi_prim = phi / t, s_prim = s / t, v2 = phi / t\n\tconst double dphi_ds = v2_ / s_prim_;\n\n\tROS_DEBUG(\"s_prim=%f, delta_s=%f\", s_prim_, s_prim_ * time_passed);\n\tROS_DEBUG(\"d'=%f, theta_e'=%f, phi'=%f\", dd_ds, dtheta_e_ds, dphi_ds);\n\n\t//\n\t// actual controller formulas begin here\n\t//\n\n\t// x1 - x4\n\t//\tconst double x1 = s;\n\tconst double x2 = -c_prim * d * tan_theta_e\n\t\t\t- c * _1_dc * (1. + sin_theta_e_2) / cos_theta_e_2\n\t\t\t+ _1_dc_2 * tan_phi / (params_.vehicle_length() * cos_theta_e_3);\n\n\tconst double x3 = _1_dc * tan_theta_e;\n\tconst double x4 = d;\n\n\t// u1, u2\n\t// u1 is taken from \"Feedback control for a path following robotic car\" by Mellodge,\n\t// p. 108 (u1_actual)\n\n\t// TODO: use measured velocity\n\tconst double u1 = velocity_ * cos_theta_e / _1_dc;\n\tconst double u2 =\n            - k1_ * u1 * x4\n            - k2_ * u1 * x3\n            - k3_ * u1 * x2;\n\n\t// derivations of x2 (for alpha1)\n\tconst double dx2_dd = -c_prim * tan_theta_e\n\t\t\t+ c * c * (1 + sin_theta_e_2) / cos_theta_e_2\n\t\t\t- 2. * _1_dc * c * tan_phi / (params_.vehicle_length() * cos_theta_e_3);\n\n\tconst double dx2_dtheta_p = -c_prim * (tan_theta_e_2 + 1.)\n\t\t\t- 4. * c * _1_dc * tan_theta_e / cos_theta_e_2\n            + 3. * _1_dc_2 * tan_phi * tan_theta_e / (params_.vehicle_length() * cos_theta_e_3);\n\n\tconst double dx2_ds =\n\t\t\t-tan_theta_e * (c_sek * d + c_prim * dd_ds)\n\t\t\t- c_prim * d * dtheta_e_ds * (1. + tan_theta_e_2)\n\t\t\t+ ((1. + sin_theta_e_2) / cos_theta_e_2) * (c_prim * _1_dc + c * (dd_ds * c + d * c_prim))\n\t\t\t- 4. * c * _1_dc * tan_theta_e / cos_theta_e_2\n\t\t\t+ (cos_theta_e * _1_dc * (-2. * (dd_ds * c + d * c_prim) * tan_phi\n\t\t\t\t\t\t\t\t\t\t\t  +_1_dc * (1. + tan_phi_2) * dphi_ds)\n\t\t\t\t- 3. * dtheta_e_ds * sin_theta_e * _1_dc_2 * tan_phi)\n\t\t\t/ (params_.vehicle_length() * pow(cos_theta_e_2, 2)); // OK\n\n\t// alpha1\n\tconst double alpha1 =\n\t\t\tdx2_ds\n\t\t\t+ dx2_dd * _1_dc * tan_theta_e\n\t\t\t+ dx2_dtheta_p * (tan_phi * _1_dc / (params_.vehicle_length() * cos_theta_e) - c);\n\n\t// alpha2\n\tconst double alpha2 =\n\t\t\tparams_.vehicle_length() * cos_theta_e_3 * pow(cos(phi_), 2) / _1_dc_2;\n\n\n\t// longitudinal velocity\n    v1_ = velocity_;\n\n\t// steering angle velocity\n\tv2_ = alpha2 * (u2 - alpha1 * u1);\n\n\t// limit steering angle velocity\n\tv2_ = boost::algorithm::clamp(v2_, -params_.max_steering_angle_speed(), params_.max_steering_angle_speed());\n\n\t// update delta according to the time that has passed since the last update\n\tphi_ += v2_ * time_passed;\n\n\t// also limit the steering angle\n\tphi_ = boost::algorithm::clamp(phi_, -params_.max_steering_angle(), params_.max_steering_angle());\n\n\tROS_DEBUG(\"d=%f, thetaP=%f, c=%f, c'=%f, c''=%f\", d, theta_e, c, c_prim, c_sek);\n\tROS_DEBUG(\"d'=%f, thetaP'=%f\", dd_ds, dtheta_e_ds);\n\tROS_DEBUG(\"1 - dc(s)=%f\", _1_dc);\n\tROS_DEBUG(\"dx2dd=%f, dx2dthetaP=%f, dx2ds=%f\", dx2_dd, dx2_dtheta_p, dx2_ds);\n\tROS_DEBUG(\"alpha1=%f, alpha2=%f, u1=%f, u2=%f\", alpha1, alpha2, u1, u2);\n\tROS_DEBUG(\"Time passed: %fs, command: v1=%f, v2=%f, phi_=%f\",\n\t\t\t\t time_passed, v1_, v2_, phi_);\n\n\t// This is the accurate steering angle for 4 wheel steering (TODO: wrong!!!)\n\tconst float delta = (float) asin(params_.factor_steering_angle() * sin(phi_));\n\n    double exp_factor = RobotController::exponentialSpeedControl();\n\tmove_cmd_.setDirection(delta);\n    move_cmd_.setVelocity(getDirSign() * (float) v1_ * exp_factor);\n\t*cmd = move_cmd_;\n\n\treturn RobotController::MoveCommandStatus::OKAY;\n}\n\nvoid RobotController_Ackermann_Inputscaling::publishMoveCommand(\n\t\tconst MoveCommand& cmd) const {\n\n\tgeometry_msgs::Twist msg;\n\tmsg.linear.x  = cmd.getVelocity();\n\tmsg.linear.y  = 0;\n\tmsg.angular.z = cmd.getDirectionAngle();\n\n\tcmd_pub_.publish(msg);\n}\n", "meta": {"hexsha": "98bc9a8bc638c9f95fdb98983d851503455c6952", "size": 8198, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "path_follower/src/controller/robotcontroller_ackermann_inputscaling.cpp", "max_stars_repo_name": "cyy1991/gerona", "max_stars_repo_head_hexsha": "1860158f082e3f5e0dd1418dcb9d2fa43a5aa191", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "path_follower/src/controller/robotcontroller_ackermann_inputscaling.cpp", "max_issues_repo_name": "cyy1991/gerona", "max_issues_repo_head_hexsha": "1860158f082e3f5e0dd1418dcb9d2fa43a5aa191", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "path_follower/src/controller/robotcontroller_ackermann_inputscaling.cpp", "max_forks_repo_name": "cyy1991/gerona", "max_forks_repo_head_hexsha": "1860158f082e3f5e0dd1418dcb9d2fa43a5aa191", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-04-21T02:24:17.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-21T02:24:17.000Z", "avg_line_length": 32.1490196078, "max_line_length": 109, "alphanum_fraction": 0.6988289827, "num_tokens": 2512, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4711338945120886}}
{"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_NTHROOT_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_NTHROOT_HPP_INCLUDED\n#include <boost/simd/function/raw.hpp>\n\n#ifndef BOOST_SIMD_NO_INFINITIES\n#include <boost/simd/function/is_inf.hpp>\n#endif\n#ifndef BOOST_SIMD_NO_INVALID\n#include <boost/simd/function/is_nan.hpp>\n#endif\n#include <boost/simd/constant/nan.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/raw.hpp>\n#include <boost/simd/function/is_ltz.hpp>\n#include <boost/simd/function/is_odd.hpp>\n#include <boost/simd/function/dec.hpp>\n#include <boost/simd/function/pow_abs.hpp>\n#include <boost/simd/function/rec.hpp>\n#include <boost/simd/function/sign.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\n  BOOST_DISPATCH_OVERLOAD ( nthroot_\n                          , (typename A0, typename A1)\n                          , bd::cpu_\n                          , bd::scalar_< bd::floating_<A0> >\n                          , bd::scalar_< bd::integer_<A1> >\n                          )\n  {\n    inline A0 operator() ( A0 a0, A1 a1) const BOOST_NOEXCEPT\n    {\n#ifndef BOOST_SIMD_NO_INVALID\n      if (is_nan(a0)) return a0;\n#endif\n      auto is_ltza0 = is_ltz(a0);\n      auto is_odda1 = is_odd(a1);\n      if (is_ltza0 && !is_odda1) return Nan<A0>();\n      A0 x = bs::abs(a0);\n      if (x == One<A0>()) return a0;\n      if (!a1) return (x < One<A0>()) ? Zero<A0>() : sign(a0)*Inf<A0>();\n      if (!a0) return Zero<A0>();\n#ifndef BOOST_SIMD_NO_INFINITIES\n      if (is_inf(a0)) return (a1) ? a0 : One<A0>();\n#endif\n      A0 aa1 = static_cast<A0>(a1);\n      A0 y = bs::raw_(bs::pow_abs)(x,rec(aa1));\n      // Correct numerical errors (since, e.g., 64^(1/3) is not exactly 4)\n      // by one iteration of Newton's method\n      if (y)\n      {\n       A0 p = raw_(bs::pow_abs)(y, aa1);\n       y -= (p - x) / (aa1*p/y);\n      }\n\n      return (is_ltza0 && is_odda1)? -y : y;\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( nthroot_\n                          , (typename A0, typename A1)\n                          , bd::cpu_\n                          , boost::simd::raw_tag\n                          , bd::scalar_< bd::floating_<A0> >\n                          , bd::scalar_< bd::integer_<A1> >\n                          )\n  {\n    inline A0 operator() (const raw_tag &,  A0 a0, A1 a1\n                         ) const BOOST_NOEXCEPT\n    {\n       auto is_ltza0 = is_ltz(a0);\n       auto is_odda1 = is_odd(a1);\n       if (is_ltza0 && !is_odda1) return Nan<A0>();\n       A0 x = bs::abs(a0);\n      if (x == One<A0>()) return a0;\n      if (!a1) return (x < One<A0>()) ? Zero<A0>() : sign(a0)*Inf<A0>();\n      if (!a0) return Zero<A0>();\n      A0 aa1 = static_cast<A0>(a1);\n      A0 y = raw_(bs::pow_abs)(x,rec(aa1));\n      return (is_ltza0 && is_odda1)? -y : y;\n    }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "30fb7540251f934fbbb451801400109e6953a133", "size": 3427, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/scalar/function/nthroot.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/nthroot.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/nthroot.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 33.2718446602, "max_line_length": 100, "alphanum_fraction": 0.5500437701, "num_tokens": 933, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788995148792, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4711338891900011}}
{"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_FIND_CHECKER_BOARD_HPP\n#define PIC_COMPUTER_VISION_FIND_CHECKER_BOARD_HPP\n\n#include \"../filtering/filter_luminance.hpp\"\n#include \"../filtering/filter_bilateral_2ds.hpp\"\n\n#include \"../computer_vision/iterative_closest_point_2D.hpp\"\n#include \"../computer_vision/nelder_mead_opt_ICP_2D.hpp\"\n\n#include \"../features_matching/harris_corner_detector.hpp\"\n#include \"../features_matching/orb_descriptor.hpp\"\n\n#include \"../util/rasterizer.hpp\"\n#include \"../util/eigen_util.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/**\n * @brief getMinDistance\n * @param points\n * @return\n */\n#ifndef PIC_DISABLE_EIGEN\n\nPIC_INLINE float getMinDistance(std::vector< Eigen::Vector2f > &points)\n{\n    float ret = FLT_MAX;\n    for(unsigned int i = 0; i < points.size(); i++) {\n\n        auto p_i = points[i];\n\n        for(unsigned int j = 0; j < points.size(); j++) {\n            if(j == i) {\n                continue;\n            }\n\n            auto delta_ij = p_i - points[j];\n            float dist = delta_ij.norm();\n\n            if(dist < ret) {\n                ret = dist;\n            }\n        }\n    }\n\n    return ret;\n}\n\n/**\n * @brief estimateCheckerBoardSize\n * @param points\n * @return\n */\nPIC_INLINE float estimateCheckerBoardSize(std::vector< Eigen::Vector2f > &points)\n{\n    if(points.size() < 2) {\n        return -1.0f;\n    }\n\n    float ret = 0.0f;\n\n    int n = int(points.size());\n\n    std::vector<float> m_d;\n    for(int i = 0; i < n; i++) {\n        auto p_i = points[i];\n\n        float closest = FLT_MAX;\n\n        for(int j = 0; j < n; j++) {\n            if(j == i) {\n                continue;\n            }\n\n            auto delta_ij = p_i - points[j];\n\n            float dist = delta_ij.norm();\n\n            if(dist < closest) {\n                closest = dist;\n            }\n        }\n\n        if(closest < FLT_MAX) {\n            m_d.push_back(closest);\n        }\n    }\n\n    if(!m_d.empty()) {\n        std::sort(m_d.begin(), m_d.end());\n\n        ret = m_d[m_d.size() / 2];\n    }\n\n    return ret;\n}\n\n/**\n * @brief estimateCheckerBoardSizeCross\n * @param points\n * @return\n */\nPIC_INLINE float estimateCheckerBoardSizeCross(std::vector< Eigen::Vector2f > &points)\n{\n    if(points.size() < 2) {\n        return -1.0f;\n    }\n\n    float ret = 0.0f;\n\n    int n = int(points.size());\n\n    std::vector<float> m_d;\n    for(int i = 0; i < n; i++) {\n        auto p_i = points[i];\n\n        float c[] = {FLT_MAX, FLT_MAX, FLT_MAX};\n        int ci[] = {-1, -1, -1};\n\n        for(int j = 0; j < n; j++) {\n            if(j == i) {\n                continue;\n            }\n\n            auto delta_ij = p_i - points[j];\n\n            float dist = delta_ij.norm();\n\n            if(dist < c[0]) {\n                c[0] = dist;\n                ci[0] = j;\n            } else {\n                if(dist < c[1]) {\n                    c[1] = dist;\n                    ci[1] = j;\n                } else {\n                    if(dist < c[2]) {\n                        c[2] = dist;\n                        ci[2] = j;\n                    }\n                }\n            }\n        }\n\n        Eigen::Vector2f v0 = (points[ci[0]] - p_i) / c[0];\n        Eigen::Vector2f v1 = (points[ci[1]] - p_i) / c[1];\n        Eigen::Vector2f v2 = (points[ci[2]] - p_i) / c[2];\n\n        float v01 = fabsf(v0.dot(v1));\n        float v02 = fabsf(v0.dot(v2));\n        float v12 = fabsf(v1.dot(v2));\n\n        if((v01 < 0.1f) || (v02 < 0.1f) || (v12 < 0.1f))\n        {\n            m_d.push_back(c[0]);\n        }\n    }\n\n    if(!m_d.empty()) {\n        std::sort(m_d.begin(), m_d.end());\n\n        ret = m_d[m_d.size() / 2];\n    }\n\n    return ret;\n}\n\n/**\n * @brief getCheckerBoardModel\n * @param chekers_x\n * @param checkers_y\n * @param checkers_size\n * @param out\n * @return\n */\nPIC_INLINE Image *getCheckerBoardModel(int checkers_x, int checkers_y, int checkers_size, std::vector< Eigen::Vector2f > &out)\n{\n    Image *ret = new Image(1, (checkers_x + 1) * checkers_size, (checkers_y + 1) * checkers_size, 1);\n    *ret = 1.0f;\n\n    for(int i = 1; i <= checkers_y; i++) {\n        Eigen::Vector2f point;\n\n        int y = i * checkers_size;\n        point[1] = float(y);\n\n        for(int j = 1; j <= checkers_x; j++) {\n\n            int x = j * checkers_size;\n            point[0] = float(x);\n\n            bool bDraw = false;\n            if(j < checkers_x) {\n                if(((j % 2) == 0) && ((i % 2) == 0)) {\n                    bDraw = true;\n                }\n            }\n\n            if(i < checkers_y) {\n                if(((j % 2) == 1) && ((i % 2) == 1)) {\n                    bDraw = true;\n                }\n            }\n\n            if(bDraw) {\n                for(int yy = y; yy < (y + checkers_size); yy++) {\n                    for(int xx = x; xx < (x + checkers_size); xx++) {\n                        float *pixel_value = (*ret)(xx, yy);\n                        pixel_value[0] = 0.0f;\n                    }\n                }\n            }\n\n            out.push_back(point);\n        }\n    }\n\n    return ret;\n}\n\n/**\n * @brief findCheckerBoard\n * @param img\n * @param corners_model\n * @param checkerBoardSizeX\n * @param checkerBoardSizeY\n */\nPIC_INLINE void findCheckerBoard(Image *img, std::vector< Eigen::Vector2f > &corners_model, int checkerBoardSizeX = 4, int checkerBoardSizeY = 7)\n{\n     corners_model.clear();\n\n    //get corners\n#ifdef PIC_DEBUG\n    printf(\"Extracting corners...\\n\");\n#endif\n\n    //compute the luminance images\n    HarrisCornerDetector hcd(2.5f, 5);\n    std::vector< Eigen::Vector2f > corners_from_img;\n    hcd.execute(img, &corners_from_img);\n\n    #ifdef PIC_DEBUG\n        //automatic white balance\n        float *col_mu = img->getMeanVal(NULL, NULL);\n        float *scaling = FilterWhiteBalance::getScalingFactors(col_mu, img->channels);\n        FilterWhiteBalance fwb(scaling, img->channels, true);\n\n        Image *img_wb = fwb.Process(Single(img), NULL);\n\n        float red[] = {1.0f, 0.0f, 0.0f};\n        float green[] = {0.0f, 1.0f, 0.0f};\n        float blue[] = {1.0f, 0.0f, 1.0f};\n        float yellow[] = {1.0f, 1.0f, 0.0f};\n\n        (*img_wb) *= 0.125f;\n    #endif\n\n    std::vector< Eigen::Vector2f > cfi_out;\n    GeneralCornerDetector::removeClosestCorners(&corners_from_img, &cfi_out, 16.0f, 64);\n\n    //compute checkerboard size\n    float checker_size = estimateCheckerBoardSize(corners_from_img);\n\n    #ifdef PIC_DEBUG\n        //drawPoints(img_wb, cfi_out, blue);\n    #endif\n\n    //\n    // remove very closed points\n    //\n\n    std::vector< Eigen::Vector2f > cfi_valid2;\n    auto n =  cfi_out.size();\n    for(unsigned int i = 0; i < n; i++) {\n        auto p_i = cfi_out[i];\n\n        bool bFlag = true;\n\n        for(unsigned int j = 0; j < n; j++) {\n            if(j != i) {\n                auto delta_ij = p_i - cfi_out[j];\n                float dist = delta_ij.norm();\n\n                if(dist < (checker_size)) {\n                    bFlag = false;\n                    break;\n                }\n            }\n        }\n\n        if(bFlag) {\n            cfi_valid2.push_back(p_i);\n        }\n    }\n\n    //\n    // remove very far away points\n    //\n\n    std::vector< Eigen::Vector2f > cfi_valid;\n    n =  cfi_valid2.size();\n    for(unsigned int i = 0; i < n; i++) {\n        auto p_i = cfi_valid2[i];\n\n        float dist = 1e32f;\n        for(unsigned int j = 0; j < n; j++) {\n            if(j != i) {\n                auto delta_ij = p_i - cfi_valid2[j];\n                float t_dist = delta_ij.norm();\n\n                if(t_dist < dist) {\n                    dist = t_dist;\n                }\n            }\n        }\n\n        if(dist < (checker_size * 3)) {\n            cfi_valid.push_back(p_i);\n        }\n    }\n\n    #ifdef PIC_DEBUG\n        printf(\"Checker size: %f\\n\", checker_size);\n        drawPoints(img_wb, cfi_valid, green);\n    #endif\n\n    checker_size = estimateCheckerBoardSizeCross(cfi_valid);\n\n#ifdef PIC_DEBUG\n    printf(\"Re-fit Checker size: %f\\n\", checker_size);\n#endif\n    //pattern image\n\n    int checkers_size = 32;\n    Image *img_pattern = getCheckerBoardModel(checkerBoardSizeX, checkerBoardSizeY, checkers_size, corners_model);\n//    corners_model.erase(corners_model.begin() + 3);\n//    corners_model.erase(corners_model.begin());\n\n    ORBDescriptor b_desc(checkers_size, 256);\n\n    std::vector< unsigned int *> descs_model, descs_cfi_valid;\n    b_desc.getAll(img_pattern, corners_model, descs_model);\n    b_desc.getAll(img, cfi_valid, descs_cfi_valid);\n\n    //scale the model using the checker size\n    float min_dist = getMinDistance(corners_model);\n    float scaling_factor = checker_size / min_dist;\n\n    ICP2DTransform t_init;\n    t_init.scale = scaling_factor;\n    t_init.applyC(corners_model);\n\n    //run 2D ICP\n    iterativeClosestPoints2D(corners_model, cfi_valid, descs_model, descs_cfi_valid, b_desc.getDescriptorSize(), 3000);\n\n#ifdef PIC_DEBUG\n    drawPoints(img_wb, corners_model, red);\n#endif\n\n    //At this point, the rotation may be wrong so\n    //this brute-force trick does the job.\n    NelderMeadOptICP2D opt(corners_model, cfi_valid);\n\n    float prev_err = FLT_MAX;\n    float *x = new float[3];\n    int nSample = 72;\n\n    float *tmp = new float[4];\n    for(float i = 0; i < nSample; i++) {\n        float angle = float(i) * C_PI_2 / float(nSample);\n        float start[] = {0.0f, 0.0f, angle};\n        opt.run(start, 3, 1e-9f, 100, tmp);\n\n        if(opt.output_error < prev_err) {\n            memcpy(x, tmp, sizeof(float) * 3);\n            prev_err = opt.output_error;\n        }\n    }\n\n    #ifdef PIC_DEBUG\n        for(int i = 0; i < 4; i++) {\n            printf(\"%f\\n\", x[i]);\n        }\n    #endif\n\n    float start[] = {x[0], x[1], x[2], 1.0f};\n    opt.run(start, 4, 1e-12f, 100, tmp);\n    ICP2DTransform t2(tmp[0], tmp[1], tmp[2], tmp[3]);\n\n    #ifdef PIC_DEBUG\n        for(int i = 0; i < 4; i++) {\n            printf(\"%f\\n\", tmp[i]);\n        }\n    #endif\n\n    t2.applyC(corners_model);\n\n    #ifdef PIC_DEBUG\n        drawPoints(img_wb, corners_model, yellow);\n        img_wb->Write(\"../data/output/img_wb.bmp\");\n\n        if(img_wb != NULL) {\n            delete img_wb;\n        }\n    #endif\n}\n\n/**\n * @brief estimateLengthInPixelOfCheckers\n * @param corners_model\n * @param p0\n * @param p1\n * @return\n */\nPIC_INLINE float estimateLengthOfCheckers(std::vector< Eigen::Vector2f > &corners_model, Eigen::Vector2f &p0, Eigen::Vector2f &p1)\n{\n    if(corners_model.size() < 8) {\n        return -1.0f;\n    }\n\n    int selected = 5;\n    auto p_0 = corners_model[selected];\n\n    int closest = -1;\n    float ret = FLT_MAX;\n    for(auto j = 0; j < corners_model.size(); j++) {\n        if(j != selected) {\n            auto delta_ij = p_0 - corners_model[j];\n            float dist = delta_ij.norm();\n\n            if(dist < ret) {\n                ret = dist;\n                closest = j;\n            }\n        }\n    }\n\n    p0 = p_0;\n    p1 = corners_model[closest];\n\n    return ret;\n}\n\n/**\n * @brief estimateCoordinatesWhitePointFromCheckerBoard\n * @param img\n * @param corners_model\n * @param checkerBoardSizeX\n * @param checkerBoardSizeY\n * @return\n */\nPIC_INLINE Eigen::Vector2f estimateCoordinatesWhitePointFromCheckerBoard(Image *img, std::vector< Eigen::Vector2f > &corners_model, int checkerBoardSizeX = 4, int checkerBoardSizeY = 6)\n{\n    Eigen::Vector2f ret(-1.0f, -1.0f);\n\n    if(img == NULL || corners_model.empty()) {\n        return ret;\n    }\n\n    float maxVal = 0.0f;\n\n    for(int i = 0; i < (checkerBoardSizeY -1) ; i++) {\n        for(int j = 0; j < (checkerBoardSizeX - 1); j++) {\n\n            int ind0 = (i * checkerBoardSizeX) + j;\n            int ind1 = (i + 1) * checkerBoardSizeX + j + 1;\n\n            auto p0 = corners_model[ind0];\n            auto p1 = corners_model[ind1];\n\n            auto pMid = (p0 + p1) / 2.0f;\n\n            int x = int(pMid[0]);\n            int y = int(pMid[1]);\n            float *color = (*img)(x, y);\n\n            float meanColor = 0.0f;\n            for(auto c = 0; c < img->channels; c++) {\n                meanColor += color[c];\n            }\n\n            if(meanColor > maxVal) {\n                maxVal = meanColor;\n                ret = pMid;\n            }\n        }\n    }\n\n    return ret;\n}\n\n/**\n * @brief estimateWhitePointFromCheckerBoard\n * @param img\n * @param corners_model\n * @param checkerBoardSizeX\n * @param checkerBoardSizeY\n * @return\n */\nPIC_INLINE float *estimateWhitePointFromCheckerBoard(Image *img, std::vector< Eigen::Vector2f > &corners_model, int checkerBoardSizeX = 4, int checkerBoardSizeY = 6)\n{\n    Eigen::Vector2f point = estimateCoordinatesWhitePointFromCheckerBoard(img, corners_model, checkerBoardSizeX, checkerBoardSizeY);\n\n    if(point[0] >= 0.0f && point[1] >= 0.0f) {\n\n        float *ret = new float[img->channels];\n        float *color = (*img)(int(point[0]), int(point[1]));\n        memcpy(ret, color, img->channels * sizeof(float));\n\n        return ret;\n    } else {\n        return NULL;\n    }\n}\n\n#endif\n\n} // end namespace pic\n\n#endif // PIC_COMPUTER_VISION_FIND_CHECKER_BOARD_HPP\n", "meta": {"hexsha": "1cc519fb53b1327e67d4f5ced51f3c09d69a4b67", "size": 13553, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/computer_vision/find_checker_board.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/find_checker_board.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/find_checker_board.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": 24.5525362319, "max_line_length": 185, "alphanum_fraction": 0.5432007674, "num_tokens": 3844, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788903594354, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.47113388386791333}}
{"text": "#ifndef MLT_MODELS_TRANSFORMERS_SPARSE_AUTOENCODER_HPP\n#define MLT_MODELS_TRANSFORMERS_SPARSE_AUTOENCODER_HPP\n\n#include <cmath>\n#include <tuple>\n#include <type_traits>\n\n#include <Eigen/Core>\n\n#include \"transformer.hpp\"\n#include \"../implementations/autoencoder.hpp\"\n#include \"../../utils/eigen.hpp\"\n\nnamespace mlt {\nnamespace models {\nnamespace transformers {\n\tusing namespace utils::eigen;\n\t\n\ttemplate <class HiddenActivation, class ReconstructionActivation, class Optimizer>\n\tclass SparseAutoencoder : public Transformer<SparseAutoencoder<HiddenActivation, ReconstructionActivation, Optimizer>> {\n\tpublic:\n\t\ttemplate <typename H, typename R, typename O,\n\t\t\tclass = enable_if<is_convertible<decay_t<H>, HiddenActivation>::value\n\t\t\t&& is_convertible<decay_t<R>, ReconstructionActivation>::value\n\t\t\t&& is_convertible<decay_t<O>, Optimizer>::value>>\n\t\texplicit SparseAutoencoder(int hidden_units, H&& hidden_activation, R&& reconstruction_activation, O&& optimizer, double regularization,\n\t\tdouble sparsity, double sparsity_weight) : _hidden_units(hidden_units), _hidden_activation(forward<H>(hidden_activation)),\n\t\t\t_reconstruction_activation(forward<R>(reconstruction_activation)), _optimizer(forward<O>(optimizer)), _regularization(regularization),\n\t\t\t_sparsity(sparsity), _sparsity_weight(sparsity_weight) {}\n\n\t\tResult transform(Features input) const {\n\t\t\tassert(_fitted);\n\t\t\treturn _hidden_activation.compute((_hidden_weights * input).colwise() + _hidden_intercepts);\n\t\t}\n\n\t\tSelf& fit(Features input, bool cold_start = true) {\n\t\t\tVectorXd init(_hidden_units * input.rows() + _hidden_units + input.rows() * _hidden_units + input.rows());\n\n\t\t\tif (_fitted && !cold_start) {\t\n\t\t\t\tinit.block(0, 0, _hidden_weights.size(), 1) = ravel(_hidden_weights);\n\t\t\t\tinit.block(_hidden_weights.size(), 0, _hidden_intercepts.size(), 1) = _hidden_intercepts;\n\n\t\t\t\tinit.block(_hidden_weights.size() + _hidden_intercepts.size(), 0, _reconstruction_weights.size(), 1) =\n\t\t\t\t\travel(_reconstruction_weights);\n\t\t\t\tinit.block(_hidden_weights.size() + _hidden_intercepts.size() + _reconstruction_weights.size(),\n\t\t\t\t\t0, _reconstruction_intercepts.size(), 1) = _reconstruction_intercepts;\n\t\t\t} else {\n\t\t\t\tinit = (init.setRandom() * 4 / sqrt(6.0 / (_hidden_units + input.rows())));\n\t\t\t}\n\n\t\t\tVectorXd coeffs = _optimizer(*this, input, input, init, cold_start);\n\n\t\t\t_hidden_weights = unravel(coeffs.block(0, 0, _hidden_units * input.rows(), 1), _hidden_units, input.rows());\n\t\t\t_hidden_intercepts = coeffs.block(_hidden_units * input.rows(), 0, _hidden_units, 1);\n\t\t\t_reconstruction_weights = unravel(coeffs.block(_hidden_units * input.rows() + _hidden_units, 0, _hidden_units * input.rows(), 1), input.rows(), _hidden_units);\n\t\t\t_reconstruction_intercepts = coeffs.block(_hidden_units * input.rows() + _hidden_units + input.rows() * _hidden_units, 0, input.rows(), 1);\n\n\t\t\t_fitted = true;\n\n\t\t\treturn *this;\n\t\t}\n\n\t\tusing Transformer<Self>::fit;\n\n\t\tauto loss(VectorXdRef coeffs, Features input, MatrixXdRef target) const {\n\t\t\tauto hidden_weights = unravel(coeffs.block(0, 0, _hidden_units * input.rows(), 1), _hidden_units, input.rows());\n\t\t\tauto hidden_intercepts = coeffs.block(_hidden_units * input.rows(), 0, _hidden_units, 1);\n\t\t\tauto reconstruction_weights = unravel(coeffs.block(_hidden_units * input.rows() + _hidden_units, 0, input.rows() * _hidden_units, 1), input.rows(), _hidden_units);\n\t\t\tauto reconstruction_intercepts = coeffs.block(_hidden_units * input.rows() + _hidden_units + input.rows() * _hidden_units, 0, input.rows(), 1);\n\n\t\t\treturn implementations::autoencoder::sparse_loss(_hidden_activation, _reconstruction_activation, hidden_weights, hidden_intercepts,\n\t\t\t\treconstruction_weights, reconstruction_intercepts, _regularization, _sparsity, _sparsity_weight, input, target);\n\t\t}\n\n\t\tauto gradient(VectorXdRef coeffs, Features input, MatrixXdRef target) const {\n\t\t\tauto hidden_weights = unravel(coeffs.block(0, 0, _hidden_units * input.rows(), 1), _hidden_units, input.rows());\n\t\t\tauto hidden_intercepts = coeffs.block(_hidden_units * input.rows(), 0, _hidden_units, 1);\n\t\t\tauto reconstruction_weights = unravel(coeffs.block(_hidden_units * input.rows() + _hidden_units, 0, input.rows() * _hidden_units, 1), input.rows(), _hidden_units);\n\t\t\tauto reconstruction_intercepts = coeffs.block(_hidden_units * input.rows() + _hidden_units + input.rows() * _hidden_units, 0, input.rows(), 1);\n\n\t\t\tMatrixXd hid_weights_grad, rec_weights_grad;\n\t\t\tVectorXd hid_inter_grad, rec_inter_grad;\n\n\t\t\ttie(hid_weights_grad, hid_inter_grad, rec_weights_grad, rec_inter_grad) = implementations::autoencoder::sparse_gradient(_hidden_activation,\n\t\t\t\t_reconstruction_activation, hidden_weights, hidden_intercepts, reconstruction_weights, reconstruction_intercepts, _regularization,\n\t\t\t\t_sparsity, _sparsity_weight, input, target);\n\n\t\t\tVectorXd gradient(coeffs.rows());\n\n\t\t\tgradient.block(0, 0, hid_weights_grad.size(), 1) = ravel(hid_weights_grad);\n\t\t\tgradient.block(hid_weights_grad.size(), 0, hid_inter_grad.size(), 1) = hid_inter_grad;\n\n\t\t\tgradient.block(hid_weights_grad.size() + hid_inter_grad.size(), 0, rec_weights_grad.size(), 1) =\n\t\t\t\t\travel(rec_weights_grad);\n\t\t\tgradient.block(hid_weights_grad.size() + hid_inter_grad.size() + rec_weights_grad.size(),\n\t\t\t\t\t0, rec_inter_grad.size(), 1) = rec_inter_grad;\n\n\t\t\treturn gradient;\n\t\t}\n\n\t\ttuple<double, VectorXd> loss_and_gradient(VectorXdRef coeffs, Features input, MatrixXdRef target) const {\n\t\t\tauto hidden_weights = unravel(coeffs.block(0, 0, _hidden_units * input.rows(), 1), _hidden_units, input.rows());\n\t\t\tauto hidden_intercepts = coeffs.block(_hidden_units * input.rows(), 0, _hidden_units, 1);\n\t\t\tauto reconstruction_weights = unravel(coeffs.block(_hidden_units * input.rows() + _hidden_units, 0, input.rows() * _hidden_units, 1), input.rows(), _hidden_units);\n\t\t\tauto reconstruction_intercepts = coeffs.block(_hidden_units * input.rows() + _hidden_units + input.rows() * _hidden_units, 0, input.rows(), 1);\n\n\t\t\tdouble loss;\n\t\t\tMatrixXd hid_weights_grad, rec_weights_grad;\n\t\t\tVectorXd hid_inter_grad, rec_inter_grad;\n\n\t\t\ttie(loss, hid_weights_grad, hid_inter_grad, rec_weights_grad, rec_inter_grad) = implementations::autoencoder::sparse_loss_and_gradient(_hidden_activation,\n\t\t\t\t_reconstruction_activation, hidden_weights, hidden_intercepts, reconstruction_weights, reconstruction_intercepts, _regularization,\n\t\t\t\t_sparsity, _sparsity_weight, input, target);\n\n\t\t\tVectorXd gradient(coeffs.rows());\n\n\t\t\tgradient.block(0, 0, hid_weights_grad.size(), 1) = ravel(hid_weights_grad);\n\t\t\tgradient.block(hid_weights_grad.size(), 0, hid_inter_grad.size(), 1) = hid_inter_grad;\n\n\t\t\tgradient.block(hid_weights_grad.size() + hid_inter_grad.size(), 0, rec_weights_grad.size(), 1) =\n\t\t\t\travel(rec_weights_grad);\n\t\t\tgradient.block(hid_weights_grad.size() + hid_inter_grad.size() + rec_weights_grad.size(),\n\t\t\t\t0, rec_inter_grad.size(), 1) = rec_inter_grad;\n\n\t\t\treturn { loss, gradient };\n\t\t}\n\n\tprotected:\n\t\tint _hidden_units;\n\t\tHiddenActivation _hidden_activation;\n\t\tReconstructionActivation _reconstruction_activation;\n\t\tOptimizer _optimizer;\n\t\tdouble _regularization;\n\t\tdouble _sparsity;\n\t\tdouble _sparsity_weight;\n\n\t\tMatrixXd _hidden_weights;\n\t\tVectorXd _hidden_intercepts;\n\t\tMatrixXd _reconstruction_weights;\n\t\tVectorXd _reconstruction_intercepts;\n\t};\n\n\ttemplate <class HiddenActivation, class ReconstructionActivation, class Optimizer>\n\tauto create_sparse_autoencoder(int hidden_units, HiddenActivation&& hidden_activation,\n\tReconstructionActivation&& reconstruction_activation, Optimizer&& optimizer,\n\tdouble regularization, double sparsity, double sparsity_weight) {\n\t\treturn SparseAutoencoder<HiddenActivation, ReconstructionActivation, Optimizer>(\n\t\t\thidden_units,\n\t\t\tforward<HiddenActivation>(hidden_activation),\n\t\t\tforward<ReconstructionActivation>(reconstruction_activation),\n\t\t\tforward<Optimizer>(optimizer),\n\t\t\tregularization, sparsity, sparsity_weight);\n\t}\n}\n}\n}\n#endif", "meta": {"hexsha": "e46dd8c470766284f11c18bfbc3c6d188606bef4", "size": 7900, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/mlt/models/transformers/sparse_autoencoder.hpp", "max_stars_repo_name": "fedeallocati/MachineLearningToolkit", "max_stars_repo_head_hexsha": "8614ee2c8c5211a3eefceb10a50576e0485cefd9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-08-31T11:43:19.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-22T11:03:47.000Z", "max_issues_repo_path": "src/mlt/models/transformers/sparse_autoencoder.hpp", "max_issues_repo_name": "fedeallocati/MachineLearningToolkit", "max_issues_repo_head_hexsha": "8614ee2c8c5211a3eefceb10a50576e0485cefd9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mlt/models/transformers/sparse_autoencoder.hpp", "max_forks_repo_name": "fedeallocati/MachineLearningToolkit", "max_forks_repo_head_hexsha": "8614ee2c8c5211a3eefceb10a50576e0485cefd9", "max_forks_repo_licenses": ["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.3184713376, "max_line_length": 166, "alphanum_fraction": 0.7660759494, "num_tokens": 1917, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317473, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4711039029405982}}
{"text": "#include \"wave/optimization/ceres/odom_linear/point_to_line_interpolated_transform.hpp\"\n#include <Eigen/QR>\n\nnamespace wave {\n\nSE3PointToLine::SE3PointToLine(const double *const p, const double *const pA, const double *const pB, const double *const scal, const Mat3 &CovZ, bool calculate_weight)\n        : pt(p), ptA(pA), ptB(pB), scale(scal) {\n    Eigen::Matrix<double, 3, 12> JP_T;\n    Eigen::Matrix<double, 3, 3> Jres_P;\n\n    JP_T << this->pt[0], 0, 0, this->pt[1], 0, 0, this->pt[2], 0, 0, 1, 0, 0, //\n            0, this->pt[0], 0, 0, this->pt[1], 0, 0, this->pt[2], 0, 0, 1, 0, //\n            0, 0, this->pt[0], 0, 0, this->pt[1], 0, 0, this->pt[2], 0, 0, 1;\n\n    this->diff[0] = this->ptB[0] - this->ptA[0];\n    this->diff[1] = this->ptB[1] - this->ptA[1];\n    this->diff[2] = this->ptB[2] - this->ptA[2];\n    this->bottom = diff[0] * diff[0] + diff[1] * diff[1] + diff[2] * diff[2];\n\n    if (this->bottom < 1e-10) {\n        // The points defining the line are too close to each other\n        throw std::out_of_range(\"Points defining line are too close!\");\n    }\n\n    Jres_P(0,0) = 1 - (diff[0] * diff[0] / bottom);\n    Jres_P(0,1) = -(diff[0] * diff[1] / bottom);\n    Jres_P(0,2) = -(diff[0] * diff[2] / bottom);\n    Jres_P(1,0) = -(diff[1] * diff[0] / bottom);\n    Jres_P(1,1) = 1 - (diff[1] * diff[1] / bottom);\n    Jres_P(1,2) = -(diff[1] * diff[2] / bottom);\n    Jres_P(2,0) = -(diff[2] * diff[0] / bottom);\n    Jres_P(2,1) = -(diff[2] * diff[1] / bottom);\n    Jres_P(2,2) = 1 -(diff[2] * diff[2] / bottom);\n\n    Eigen::Vector3d unitdiff;\n    double invlength = 1.0/sqrt(this->bottom);\n    if(this->diff[2] > 0) {\n        unitdiff[0] = this->diff[0] * invlength;\n        unitdiff[1] = this->diff[1] * invlength;\n        unitdiff[2] = this->diff[2] * invlength;\n    } else {\n        unitdiff[0] = -this->diff[0] * invlength;\n        unitdiff[1] = -this->diff[1] * invlength;\n        unitdiff[2] = -this->diff[2] * invlength;\n    }\n\n    Eigen::Vector3d unitz;\n    unitz << 0, 0, 1;\n\n    auto v = unitdiff.cross(unitz);\n    auto s = v.norm();\n    auto c = unitz.dot(unitdiff);\n    Mat3 skew;\n    Transformation<>::skewSymmetric3(v, skew);\n    this->rotation = Eigen::Matrix3d::Identity() + skew + skew*skew*((1-c)/(s*s));\n\n    this->Jres_T = this->rotation * Jres_P * JP_T;\n\n    if(calculate_weight) {\n        auto rotated = (this->rotation * Jres_P * CovZ * Jres_P.transpose() * this->rotation.transpose());\n        this->weight_matrix = rotated.block<2,2>(0,0).inverse().sqrt();\n    } else {\n        this->weight_matrix.setIdentity();\n    }\n}\n\nbool SE3PointToLine::Evaluate(double const *const *parameters, double *residuals, double **jacobians) const {\n    Eigen::Map<const Mat34> Tmap(parameters[0], 3, 4);\n    Transformation<Eigen::Map<const Mat34>> Tk(Tmap);\n\n    Transformation<Eigen::Matrix<double, 3, 4>> interpolated;\n\n    Eigen::Map<const Vec3> PT(pt, 3, 1);\n    auto twist = Tk.logMap();\n    interpolated.setFromExpMap(*(this->scale) * twist);\n    Vec3 POINT = interpolated.transform(PT);\n    double point[3];\n    Eigen::Map<Vec3>(point, 3, 1) = POINT;\n\n    double p_A[3] = {point[0] - this->ptA[0], point[1] - this->ptA[1], point[2] - this->ptA[2]};\n\n    double scaling = ceres::DotProduct(p_A, diff);\n    // point on line closest to point\n    double p_Tl[3] = {this->ptA[0] + (scaling / bottom) * diff[0],\n                      this->ptA[1] + (scaling / bottom) * diff[1],\n                      this->ptA[2] + (scaling / bottom) * diff[2]};\n\n    double residual_o[3];\n    residual_o[0] = point[0] - p_Tl[0];\n    residual_o[1] = point[1] - p_Tl[1];\n    residual_o[2] = point[2] - p_Tl[2];\n    Eigen::Map<Vec3> res(residual_o, 3, 1);\n    Eigen::Vector2d reduced = (this->rotation * res).block<2,1>(0,0);\n    reduced = this->weight_matrix * reduced;\n    Eigen::Map<Eigen::Vector2d>(residuals, 2, 1) = reduced;\n\n    if (jacobians != NULL) {\n        // Have to apply the \"lift\" jacobian to the Interpolation Jacobian because\n        // of Ceres local parameterization\n        Transformation<>::Jinterpolated(twist, *(this->scale), this->J_int);\n        interpolated.J_lift(this->J_lift);\n        Tk.J_lift(this->J_lift_full);\n\n        this->J_lift_full_pinv = (this->J_lift_full.transpose() * this->J_lift_full).inverse() * this->J_lift_full.transpose();\n\n        this->Jr_T = this->Jres_T * this->J_lift * this->J_int * this->J_lift_full_pinv;\n        this->Jr_T_reduced = this->weight_matrix * this->Jr_T.block<2,12>(0,0);\n\n        Eigen::Map<Eigen::Matrix<double, 2, 12, Eigen::RowMajor>>(jacobians[0], 2, 12) = this->Jr_T_reduced;\n    }\n\n    return true;\n}\n\n}  // namespace wave\n", "meta": {"hexsha": "ba8cbf0a9e2e39f589792004a1abae200e165c9a", "size": 4601, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "wave_optimization/src/ceres/odom_linear/point_to_line_interpolated_transform.cpp", "max_stars_repo_name": "Jebediah/libwave", "max_stars_repo_head_hexsha": "c04998c964f0dc7d414783c6e8cf989a2716ad54", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-06-13T13:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-13T14:54:35.000Z", "max_issues_repo_path": "wave_optimization/src/ceres/odom_linear/point_to_line_interpolated_transform.cpp", "max_issues_repo_name": "Jebediah/libwave", "max_issues_repo_head_hexsha": "c04998c964f0dc7d414783c6e8cf989a2716ad54", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "wave_optimization/src/ceres/odom_linear/point_to_line_interpolated_transform.cpp", "max_forks_repo_name": "Jebediah/libwave", "max_forks_repo_head_hexsha": "c04998c964f0dc7d414783c6e8cf989a2716ad54", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-13T02:27:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-13T02:27:29.000Z", "avg_line_length": 39.6637931034, "max_line_length": 168, "alphanum_fraction": 0.5900891111, "num_tokens": 1620, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4710625425436913}}
{"text": "#include <iostream>\r\n#include <vector>\r\n#include <numeric>\r\n#include <Eigen/Dense>\r\n#include \"mex.h\"\r\n#include \"matrix.h\"\r\n\r\n#if $(use_sparse_template)\r\n#include <Eigen/Sparse>\r\n#endif\r\n#if $(use_sturm_eigensolver)\r\n#define MAX_DEG  $(num_basis)\r\n#include \"sturm.h\"\r\n#include \"charpoly.h\"\r\n#endif\r\n#if $(use_sturm_dani_eigensolver)\r\n#define MAX_DEG  $(num_basis)\r\n// #include \"sturm.h\"\r\n#define DEG  $(num_basis)\r\n#include \"sturm_mart.h\"\r\n#include \"charpoly.h\"\r\n#endif\r\n\r\nusing namespace Eigen;\r\n\r\n#if $(use_reduced_eigenvector_solver)\r\nvoid fast_eigenvector_solver(double * eigv, int neig, Eigen::Matrix<double,$(num_basis),$(num_basis)> &AM, MatrixXcd &sols);\r\n#endif\r\n\r\nvoid solver_$(solv_name)($(function_param_declaration))\r\n{\r\n    // Compute coefficients\r\n    \r\n$(code_compute_coefficients)\r\n\r\n    // Setup elimination template\r\n    static const int coeffs0_ind[] = { $(coeffs0_ind) };\r\n    static const int coeffs1_ind[] = { $(coeffs1_ind) };\r\n        \r\n\r\n$(code_setup_template)\r\n\r\n\r\n    // Setup action matrix\r\n    Matrix<double,$(num_available), $(num_basis)> RR;\r\n    RR << -C12.bottomRows($(num_reducible)), Matrix<double,$(num_basis),$(num_basis)>::Identity($(num_basis), $(num_basis));\r\n\r\n    static const int AM_ind[] = { $(AM_ind) };\r\n    Matrix<double, $(num_basis), $(num_basis)> AM;\r\n    for (int i = 0; i < $(num_basis); i++) {\r\n        AM.row(i) = RR.row(AM_ind[i]);\r\n    }\r\n\r\n    MatrixXcd sols($(num_vars), $(num_basis));\r\n    sols.setZero();\r\n\r\n    // Solve eigenvalue problem\r\n#if $(use_standard_eigensolver)\r\n    EigenSolver<Matrix<double, $(num_basis), $(num_basis)> > es(AM);\r\n    ArrayXcd D = es.eigenvalues();    \r\n    ArrayXXcd V = es.eigenvectors();\r\n\r\n    $(code_normalize_eigenvectors)\r\n    $(code_extract_solutions)\r\n#endif\r\n#if $(use_eigsonly_eigensolver)\r\n\r\n    EigenSolver<MatrixXd> es(AM, false);\r\n    ArrayXcd D = es.eigenvalues();\r\n\r\n    int nroots = 0;\r\n    double eigv[$(num_basis)];\r\n    for (int i = 0; i < $(num_basis); i++) {\r\n        if (std::abs(D(i).imag()) < 1e-6)\r\n            eigv[nroots++] = D(i).real();\r\n    }\r\n\r\n    fast_eigenvector_solver(eigv, nroots, AM, sols);\r\n#endif\r\n#if $(use_sturm_eigensolver)\r\n    double p[1+$(num_basis)];\r\n    Matrix<double, $(num_basis), $(num_basis)> AMp = AM;\r\n    charpoly_$(charpoly_method)(AMp, p);    \r\n    double roots[$(num_basis)];\r\n    int nroots;\r\n    find_real_roots_sturm(p, $(num_basis), roots, &nroots, 8, 0);\r\n    fast_eigenvector_solver(roots, nroots, AM, sols);\r\n#endif\r\n\r\n#if $(use_sturm_dani_eigensolver)\r\n\r\n    double p[1 + $(num_basis)];\r\n    Matrix<double, $(num_basis), $(num_basis)> T;\r\n    charpoly_danilevsky_piv_T(AM, p, T);\r\n    double roots[$(num_basis)];\r\n    int nroots;\r\n    // find_real_roots_sturm(p, $(num_basis), roots, &nroots, 8, 0);\r\n    nroots = realRoots(p, roots);\r\n    sols.resize($(num_vars), nroots);\r\n\r\n    Eigen::MatrixXd V($(num_basis), nroots);\r\n    Eigen::Map<Eigen::MatrixXd> D(roots, 1, nroots);\r\n    V.bottomRows(1).setConstant(1);\r\n    for (int j = $(num_basis) - 2; j >= 0; j--) {\r\n        V.row(j) = V.row(j + 1).array() * D.array();\r\n    }\r\n    V = T * V;\r\n    Eigen::RowVectorXd row = V.row(0);\r\n    V.array().rowwise() /= row.array();\r\n\r\n    D.transposeInPlace();\r\n    $(code_extract_solutions)\r\n\r\n#endif\r\n    $(code_pack_outputs)\r\n\r\n}\r\n$(debug_comments)\r\n\r\n#if $(use_reduced_eigenvector_solver)\r\n    void fast_eigenvector_solver(double * eigv, int neig, Eigen::Matrix<double,$(num_basis),$(num_basis)> &AM, MatrixXcd &sols) {\r\n    static const int ind[] = { $(ind_non_trivial) };    \r\n    // Truncated action matrix containing non-trivial rows\r\n    Matrix<double, $(length_ind_non_trivial), $(num_basis)> AMs;\r\n    double zi[$(max_power)];\r\n    \r\n    for (int i = 0; i < $(length_ind_non_trivial); i++)    {\r\n        AMs.row(i) = AM.row(ind[i]);\r\n    }\r\n    for (int i = 0; i < neig; i++) {\r\n        zi[0] = eigv[i];\r\n        for (int j = 1; j < $(max_power); j++)\r\n        {\r\n            zi[j] = zi[j - 1] * eigv[i];\r\n        }\r\n        Matrix<double, $(AA_sz)> AA;\r\n$(code_setup_reduced_eigenvalue_eq)\r\n\r\n        Matrix<double, $(ind_unit), 1>  s = AA.leftCols($(ind_unit)).colPivHouseholderQr().solve(-AA.col($(ind_unit)));\r\n$(code_extract_solutions)\r\n    }\r\n}\r\n#endif\r\n\r\nmxArray* convertToMatlabCell(std::vector<Eigen::MatrixXcd> const& sols) {\r\n    mxArray* cell = mxCreateCellMatrix(1, sols.size());\r\n    for (int i = 0; i < sols.size(); ++i) {\r\n        Eigen::MatrixXcd sol = sols.at(i);\r\n        mxArray* mat = mxCreateDoubleMatrix(sol.rows(), sol.cols(), mxCOMPLEX);\r\n        memcpy(mxGetComplexDoubles(mat), sol.data(), sizeof(mxComplexDouble) * sol.size());\r\n        // double* mat_r = mxGetPr(mat);\r\n        // double* mat_i = mxGetPi(mat);\r\n        // for (int r = 0; r < sol.rows(); ++r) {\r\n        //     for (int c = 0; c < sol.cols(); ++c) {\r\n        //         mat_r[c * sol.rows() + r] = sol(r, c).real();\r\n        //         mat_i[c * sol.rows() + r] = sol(r, c).imag();\r\n        //     }\r\n        // }\r\n        mxSetCell(cell, i, mat);\r\n    }\r\n    return cell;\r\n}\r\n\r\nvoid mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])\r\n{\r\n    std::ios_base::sync_with_stdio(false);\r\n    if (nrhs != $(input_size)) {\r\n        mexErrMsgIdAndTxt(\"automatic_generator_cvpr:$(solv_name):nrhs\", \"One input required.\");\r\n    }\r\n    if (nlhs != $(output_size)) {\r\n        mexErrMsgIdAndTxt(\"automatic_generator_cvpr:$(solv_name):nlhs\", \"One output required.\");\r\n    }    \r\n    if (!mxIsDouble(prhs[0]) || mxIsComplex(prhs[0])) {\r\n        mexErrMsgIdAndTxt(\"automatic_generator_cvpr:$(solv_name):notDouble\", \"Input data must be type double.\");\r\n    }\r\n    $(code_mex_function_body)\r\n}\r\n\r\n", "meta": {"hexsha": "f4f3ce80dfd0d69cb8bba8aedf590a8ced7a8328", "size": 5656, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "generator/code_generation_cpp/templates/template_solver.cpp", "max_stars_repo_name": "prclibo/gaps", "max_stars_repo_head_hexsha": "120832a89b559d0f854ee310c7577ad9edb59827", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2020-01-20T10:16:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T09:37:02.000Z", "max_issues_repo_path": "generator/code_generation_cpp/templates/template_solver.cpp", "max_issues_repo_name": "prclibo/gaps", "max_issues_repo_head_hexsha": "120832a89b559d0f854ee310c7577ad9edb59827", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-04-30T22:26:44.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-07T00:39:54.000Z", "max_forks_repo_path": "generator/code_generation_cpp/templates/template_solver.cpp", "max_forks_repo_name": "prclibo/gaps", "max_forks_repo_head_hexsha": "120832a89b559d0f854ee310c7577ad9edb59827", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-04-30T19:26:50.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-20T05:27:32.000Z", "avg_line_length": 31.5977653631, "max_line_length": 130, "alphanum_fraction": 0.5958274399, "num_tokens": 1645, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4710625425436912}}
{"text": "#include \"PriorityQueue.h\"\n#include <vector>\n#include <ctime>\n#include <cstdlib>\n#include <utility>\n#include <iostream>\n#include <string>\n#include <sstream>\n#include <cmath>\n#include <algorithm>\n#include <boost/bind.hpp>\n\ndouble temperature(unsigned long t) {\n\treturn 100.0*std::exp((-8.0*t*t) / (2600.0*2600.0)) + 0.1;//0.1 is an offset\n\t//\t^\n\t//\t|\n\t//make this large\n}\n\nint selectAction(PriorityQueue<int, double>& a_queue, unsigned long iterations) {\n\t\n\ttypedef std::vector<std::pair<int, double> > VecPair ; \n\t\n\t//turn priority queue into a vector of pairs\n\tVecPair vec = a_queue.saveOrderedQueueAsVector();\n\n    //sum for partition function \n\tdouble sum = 0.0;\n\n\t// calculate partition function by iterating over action-values\n\tfor (VecPair::iterator iter = vec.begin(), end = vec.end(); iter < end; ++iter) {\n\t\tsum += std::exp((iter->second) / temperature(iterations));\n\t}\n\n\t// compute Boltzmann factors for action-values and enqueue to vec\n\tfor (VecPair::iterator iter = vec.begin(); iter < vec.end(); ++iter) {\n\t\titer->second = std::exp(iter->second / temperature(iterations)) / sum;\n\t}\n\n\t// calculate cumulative probability distribution\n\tfor (VecPair::iterator iter = vec.begin()++, end = vec.end(); iter < end; ++iter) {\n        //second member of pair becomes addition of its current value\n        //and that of the index before it\n\t\titer->second += (iter-1)->second;\n\t}\n\n\t//generate RN between 0 and 1\n\tdouble rand_num = static_cast<double>(rand()) / RAND_MAX;\n\n\t// choose action based on random number relation to priorities within action queue\n\tfor (VecPair::iterator iter = vec.begin(), end = vec.end(); iter < end; ++iter) {\n\t\tif (rand_num < iter->second)\n\t\t\treturn iter->first;\n\t}\n\t\n\treturn -1; //note that this line should never be reached\t\n}\nint main(){\n    std::vector< std::pair<int, double> > vec;\n    std::pair<int, double> pear;\n    //size of vector\n    int size = 10;\n    std::vector< int > vec2(size, 0);\n\n    //make priority queue full of zeroes \n    //except for one optimal action \n    for(int i = 0; i < size; i++)\n    {   \n        pear = std::make_pair(i, 0.0);\n        //optimal action\n        if(i ==3){pear = std::make_pair(i, 100);}\n        vec.push_back(pear);\n    } \n    \n    unsigned long i = 0;\n    int chosen_action;\n    \n    //coinstruct PQ from vector of pairs\n    PriorityQueue<int, double> a_queue(vec, MAX);\n    \n    //choses action many times\n\tfor(int j=0; j < 1000; j++){\n\t    //finds action\n\t\tchosen_action = selectAction(a_queue, i);\n\t\t//increases value of vec2 in bin corresponding \n\t\t//to chosen action\n\t\tvec2[chosen_action] ++;\n\t\ti++;\n\t}\n\tstd::cout<< \"action\" << \"\\tNumber of times selected\" << std::endl;\n\t//prints contents of vector\n\tint j = 0;\n\tfor(std::vector< int >::iterator it = vec2.begin(); it < vec2.end(); it++)\n\t{\n\t    std::cout << j << \"\\t\" << (*it) << std::endl;\n\t    j++;\n\t}\n\n    return 0;\n}", "meta": {"hexsha": "ea3ac6e5375ef5114146cbe0ec396dec3439d8e3", "size": 2858, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sdk/machinelearning/test2.cpp", "max_stars_repo_name": "philj56/robot-swing", "max_stars_repo_head_hexsha": "eb2527c9dabdb02dd7e4a8bb7240417479d50b1d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-01-19T16:49:24.000Z", "max_stars_repo_stars_event_max_datetime": "2016-01-19T16:58:34.000Z", "max_issues_repo_path": "sdk/machinelearning/test2.cpp", "max_issues_repo_name": "philj56/robot-swing", "max_issues_repo_head_hexsha": "eb2527c9dabdb02dd7e4a8bb7240417479d50b1d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sdk/machinelearning/test2.cpp", "max_forks_repo_name": "philj56/robot-swing", "max_forks_repo_head_hexsha": "eb2527c9dabdb02dd7e4a8bb7240417479d50b1d", "max_forks_repo_licenses": ["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.58, "max_line_length": 84, "alphanum_fraction": 0.6382085374, "num_tokens": 794, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257127, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.47106253636643847}}
{"text": "/*\n *  MIT License\n *\n *  Copyright (c) 2017 Piotr Dobrowolski\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 * Author: Piotr Dobrowolski\n * dobrypd[at]gmail[dot]com\n *\n */\n#include \"HDRCreator.hpp\"\n\n#include <boost/shared_ptr.hpp>\n#include <boost/math/special_functions.hpp>\n#include <vector>\n#include <cmath>\n\nnamespace HDRCreation\n{\n\nusing namespace std;\n\nHDRCreator::HDRCreator(const GlobalArgs_t & globalArgs)\n    : globalArgs(globalArgs)\n{\n    // TODO Auto-generated constructor stub\n}\n\ntypedef float(*luminanceCorrection_t)(float);\n\nfloat logLumiCorrection(float value) {\n    double base = 10; // TODO:\n\n    double baseFraction = log(base);\n    double logValue = log1p(value);\n\n    return logValue / baseFraction;\n}\n\nfloat powLumiCorrection(float value) {\n    double power = 3.3; // TODO:\n\n    double powValue = pow(value + 1, power);\n\n    return powValue;\n}\n\nvoid correctLuminocity(luminanceCorrection_t lumiCorrection, pfs::FramePtr frame) {\n    using namespace pfs;\n    pfs::Channel *X, *Y, *Z;\n    frame->getXYZChannels(X, Y, Z);\n    for (auto itX = X->begin(), itY = Y->begin(), itZ = Z->begin();\n            itX != X->end(); itX++, itY++, itZ++) {\n        (*itX) = lumiCorrection(*itX);\n        (*itY) = lumiCorrection(*itY);\n        (*itZ) = lumiCorrection(*itZ);\n    }\n}\n\ntypedef float(*agrFun_t)(pfs::FramePtr);\n\nfloat avgAgr(pfs::FramePtr frame) {\n    using namespace pfs;\n    pfs::Channel *X, *Y, *Z;\n    frame->getXYZChannels(X, Y, Z);\n    double sumX=0, sumY=0, sumZ=0;\n    for (auto itX = X->begin(), itY = Y->begin(), itZ = Z->begin();\n            itX != X->end(); itX++, itY++, itZ++) {\n        sumX += *itX;\n        sumY += *itY;\n        sumZ += *itZ;\n    }\n    sumX /= frame->getWidth() * frame->getHeight();\n    sumY /= frame->getWidth() * frame->getHeight();\n    sumZ /= frame->getWidth() * frame->getHeight();\n\n    return (sumX + sumY + sumZ) / 3; // dummy heuristic, use colorspace characteristic\n}\n\nfloat heuristicRelativeEV(agrFun_t aggregation, pfs::FramePtr frame)\n{\n    return aggregation(frame);\n}\n\nvoid getChannelsIterators(pfs::Channel *X, pfs::Channel *Y, pfs::Channel *Z,\n        pfs::Channel::iterator & itX, pfs::Channel::iterator & itY, pfs::Channel::iterator & itZ)\n{\n    itX = X->begin();\n    itY = Y->begin();\n    itZ = Z->begin();\n}\n\nvoid getChannelsIterators(pfs::FramePtr frame,\n        pfs::Channel::iterator & itX, pfs::Channel::iterator & itY, pfs::Channel::iterator & itZ)\n{\n    using pfs::Channel;\n    Channel *X, *Y, *Z;\n    frame->getXYZChannels(X, Y, Z);\n    getChannelsIterators(X, Y, Z, itX, itY, itZ);\n}\n\nvoid getChannelsIterators(pfs::FramePtr frame,\n        pfs::Channel::iterator & itX, pfs::Channel::iterator & itY, pfs::Channel::iterator & itZ,\n        pfs::Channel::iterator & endX)\n{\n    using pfs::Channel;\n    Channel *X, *Y, *Z;\n    frame->getXYZChannels(X, Y, Z);\n    getChannelsIterators(X, Y, Z, itX, itY, itZ);\n    endX = X->end();\n}\n\nvoid createBeginIterators(vector<pfs::FramePtr> & frames,\n        vector<pfs::Channel::iterator> & XChannelsIt,\n        vector<pfs::Channel::iterator> & YChannelsIt,\n        vector<pfs::Channel::iterator> & ZChannelsIt)\n{\n    XChannelsIt.resize(frames.size());\n    YChannelsIt.resize(frames.size());\n    ZChannelsIt.resize(frames.size());\n    int expNo = 0;\n    for (auto frameIt = frames.begin(); frameIt != frames.end(); ++frameIt, ++expNo)\n    {\n        pfs::Channel::iterator itX, itY, itZ;\n        getChannelsIterators(*frameIt, itX, itY, itZ);\n        XChannelsIt[expNo] = itX;\n        YChannelsIt[expNo] = itY;\n        ZChannelsIt[expNo] = itZ;\n    }\n}\n\n/**\n * Assumptions:\n * 1 - all frames are aligned, with fixed size.\n * 2 - frames are exposure value ordered\n */\nbool HDRCreator::create(kernel::GenericFramePtr output, std::vector<kernel::GenericFramePtr> & framesGeneric)\n{\n    /**\n     * Assertions\n     */\n    debug_print(LVL_INFO, \"Found %d frame(s) to process.\\n\", framesGeneric.size());\n    if (output == 0) {\n    \treturn false;\n    }\n\n    if (!output->isValid()) {\n    \tif (framesGeneric.front()->isValid())\n    \t{\n    \t\tif (!output->setEmptyFrameFrom(framesGeneric.front()->getRawFramePFS())) {\n    \t\t    return false;\n    \t\t}\n    \t} else {\n    \t\treturn false;\n    \t}\n    }\n    assert(output->isValid());\n    pfs::FramePtr outputFrame = output->getRawFramePFS();\n\n    /**\n     * Create pointers.\n     * Map luminocity in each frame.\n     */\n    int noOfExposures = framesGeneric.size();\n    size_t frameSize = outputFrame->getWidth() * outputFrame->getHeight();\n    vector<pfs::FramePtr> frames;\n    vector<double> framesRelativeEVComputed; // X translation\n    vector<double> avgLuminocityRelativeFractionX, avgLuminocityRelativeFractionY,avgLuminocityRelativeFractionZ; // Y translation, than frame 1\n    for (auto frameGenIt = framesGeneric.begin(); frameGenIt != framesGeneric.end(); frameGenIt++) {\n        pfs::FramePtr frame = (*frameGenIt)->getRawFramePFS();\n        frames.push_back(frame);\n        correctLuminocity(&logLumiCorrection, frame);\n        framesRelativeEVComputed.push_back(heuristicRelativeEV(&avgAgr, frame));\n\n        avgLuminocityRelativeFractionX.push_back(0.0f);\n        avgLuminocityRelativeFractionY.push_back(0.0f);\n        avgLuminocityRelativeFractionZ.push_back(0.0f);\n    }\n\n\n    /**\n     * Prepare vectors of channels. Channel data iterators.\n     */\n    pfs::Channel::iterator itX, itY, itZ, endX;\n\n\n    /**\n     *\n     */\n    vector<pfs::Channel::iterator> XChannelsIt, YChannelsIt, ZChannelsIt;\n    createBeginIterators(frames, XChannelsIt, YChannelsIt, ZChannelsIt);\n    float relativeX = **XChannelsIt.begin(), relativeY = **YChannelsIt.begin(), relativeZ = **ZChannelsIt.begin();\n    int expNo = 1;\n    for (auto XChannelsDataIt = ++XChannelsIt.begin(), YChannelsDataIt = ++YChannelsIt.begin(), ZChannelsDataIt = ++ZChannelsIt.begin();\n            XChannelsDataIt != XChannelsIt.end();\n            XChannelsDataIt++, YChannelsDataIt++, ZChannelsDataIt++, expNo++)\n    {\n        auto XValueIt = *XChannelsDataIt, YValueIt = *YChannelsDataIt, ZValueIt = *ZChannelsDataIt;\n        for (size_t pixel = 0; pixel < frameSize;\n                ++pixel, ++XValueIt, ++YValueIt, ++ZValueIt)\n        {\n            auto XValue = *XValueIt, YValue = *YValueIt, ZValue = *ZValueIt;\n            avgLuminocityRelativeFractionX[expNo] += XValue - relativeX;\n            avgLuminocityRelativeFractionY[expNo] += YValue - relativeY;\n            avgLuminocityRelativeFractionZ[expNo] += ZValue - relativeZ;\n        }\n    }\n    // Normalize\n    for(auto avgLRFXIt = avgLuminocityRelativeFractionX.begin(), avgLRFYIt = avgLuminocityRelativeFractionY.begin(),\n            avgLRFZIt = avgLuminocityRelativeFractionZ.begin();\n            avgLRFXIt != avgLuminocityRelativeFractionX.end();\n            avgLRFXIt++, avgLRFYIt++, avgLRFZIt++)\n    {\n        (*avgLRFXIt) /= frameSize;\n        (*avgLRFYIt) /= frameSize;\n        (*avgLRFZIt) /= frameSize;\n        if (boost::math::isnan((*avgLRFXIt))) { debug_print(LVL_LOW, \"*avgLRFXIt isn't a number = %f\\n\", *avgLRFXIt); }\n        if (boost::math::isnan((*avgLRFYIt))) { debug_print(LVL_LOW, \"*avgLRFYIt isn't a number = %f\\n\", *avgLRFYIt); }\n        if (boost::math::isnan((*avgLRFZIt))) { debug_print(LVL_LOW, \"*avgLRFZIt isn't a number = %f\\n\", *avgLRFZIt); }\n    }\n\n    /**\n     * Translate vector.\n     */\n    createBeginIterators(frames, XChannelsIt, YChannelsIt, ZChannelsIt);\n    expNo = 0;\n    for (auto XChannelsDataIt = XChannelsIt.begin(), YChannelsDataIt = YChannelsIt.begin(), ZChannelsDataIt = ZChannelsIt.begin();\n            XChannelsDataIt != XChannelsIt.end();\n            XChannelsDataIt++, YChannelsDataIt++, ZChannelsDataIt++, expNo++)\n    {\n        auto & XValueIt = *XChannelsDataIt, & YValueIt = *YChannelsDataIt, & ZValueIt = *ZChannelsDataIt;\n        auto expLumin = avgLuminocityRelativeFractionX[expNo];\n        auto frameRelEV = framesRelativeEVComputed[expNo];\n        auto pixelFraction = expLumin + frameRelEV;\n        if (boost::math::isnan(pixelFraction)) { debug_print(LVL_LOW, \"pixelFraction isn't a number = %f\\n\", pixelFraction); }\n        for (size_t pixel = 0; pixel < frameSize;\n                ++pixel, ++XValueIt, ++YValueIt, ++ZValueIt)\n        {\n            auto & XValue = *XValueIt, YValue = *YValueIt, ZValue = *ZValueIt;\n            XValue += pixelFraction;\n            YValue += pixelFraction;\n            ZValue += pixelFraction;\n        }\n    }\n\n\n    // Create HDR Image\n    int it = 0;\n    createBeginIterators(frames, XChannelsIt, YChannelsIt, ZChannelsIt);\n    auto XChannelsDataIt = XChannelsIt.begin(), YChannelsDataIt = YChannelsIt.begin(), ZChannelsDataIt = ZChannelsIt.begin();\n    float minXV = 1000, minYV = 1000, minZV = 1000;\n    float maxXV = -1, maxYV = -1, maxZV = -1;\n    pfs::Channel *X, *Y, *Z;\n    outputFrame->createXYZChannels(X, Y, Z);\n    endX = X->end();\n    for(getChannelsIterators(X, Y, Z, itX, itY, itZ); itX != endX;\n            ++itX, ++itY, ++itZ, it++) {\n        auto & XOutputVal = *itX, & YOutputVal = *itY, & ZOutputVal = *itZ;\n        XOutputVal = 0, YOutputVal = 0, ZOutputVal = 0;\n        XChannelsDataIt = XChannelsIt.begin(), YChannelsDataIt = YChannelsIt.begin(), ZChannelsDataIt = ZChannelsIt.begin();\n        for (int expNo = 0; expNo < noOfExposures; XChannelsDataIt++, YChannelsDataIt++, ZChannelsDataIt++, expNo++)\n        {\n            auto & XValueIt = *XChannelsDataIt, & YValueIt = *YChannelsDataIt, & ZValueIt = *ZChannelsDataIt;\n            auto XValue = *XValueIt, YValue = *YValueIt, ZValue = *ZValueIt;\n\n            XOutputVal += XValue;\n            YOutputVal += YValue;\n            ZOutputVal += ZValue;\n\n            ++XValueIt;\n            ++YValueIt;\n            ++ZValueIt;\n        }\n        if (minXV > XOutputVal) minXV = XOutputVal;\n        if (minYV > YOutputVal) minYV = YOutputVal;\n        if (minZV > ZOutputVal) minZV = ZOutputVal;\n        if (maxXV < XOutputVal) maxXV = XOutputVal;\n        if (maxYV < YOutputVal) maxYV = YOutputVal;\n        if (maxZV < ZOutputVal) maxZV = ZOutputVal;\n        //debug_print(LVL_LOW, \"X = %f, Y = %f, Z = %f,\\n\", XOutputVal, YOutputVal, ZOutputVal);\n        if (boost::math::isnan(XOutputVal)) { debug_print(LVL_LOW, \"XOutputVal isn't a number = %f\\n\", XOutputVal); }\n        if (boost::math::isnan(YOutputVal)) { debug_print(LVL_LOW, \"YOutputVal isn't a number = %f\\n\", YOutputVal); }\n        if (boost::math::isnan(ZOutputVal)) { debug_print(LVL_LOW, \"ZOutputVal isn't a number = %f\\n\", ZOutputVal); }\n    }\n\n    float rangeX = abs(maxXV - minXV), rangeY = abs(maxYV - minYV), rangeZ = abs(maxZV - minZV);\n    debug_print(LVL_DEBUG, \"rangeX=(%f - %f) rangeY=(%f - %f) rangeZ=(%f - %f)\\n\", minXV, maxXV, minYV, maxYV, minZV, maxZV);\n    long nanX = 0, nanY = 0, nanZ = 0;\n\n    // Normalize output (TONE MAP)\n    for(getChannelsIterators(outputFrame, itX, itY, itZ, endX); itX != endX;\n            ++itX, ++itY, ++itZ) {\n        auto & XOutputVal = *itX, & YOutputVal = *itY, & ZOutputVal = *itZ;\n        XOutputVal = (XOutputVal - minXV) / rangeX;\n        YOutputVal = (YOutputVal - minYV) / rangeY;\n        ZOutputVal = (ZOutputVal - minZV) / rangeZ;\n\n        if (boost::math::isnan(XOutputVal)) {\n            XOutputVal = 0;\n            nanX++;\n        }\n        if (boost::math::isnan(YOutputVal)) {\n            YOutputVal = 0;\n            nanY++;\n        }\n        if (boost::math::isnan(ZOutputVal)) {\n            ZOutputVal = 0;\n            nanZ++;\n        }\n    }\n    debug_print(LVL_DEBUG, \"NanX = %f, NanY = %f, NanZ = %f\\n\", (float)nanX / (float)frameSize,(float)nanY / (float)frameSize,(float)nanZ / (float)frameSize);\n\n    // Create output.\n    return true; // XXX\n}\n\n} /* namespace HDRCreation */\n", "meta": {"hexsha": "8c09cec6f15d0591e0a383feb6d84412a6721219", "size": 12714, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/kernel/HdrCreation/HDRCreator-version_1.cpp", "max_stars_repo_name": "dobrypd/HDR-Simple-Framework", "max_stars_repo_head_hexsha": "d2e83979cf5b2aa56a25cc8f9e8f8bdd346689dd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kernel/HdrCreation/HDRCreator-version_1.cpp", "max_issues_repo_name": "dobrypd/HDR-Simple-Framework", "max_issues_repo_head_hexsha": "d2e83979cf5b2aa56a25cc8f9e8f8bdd346689dd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kernel/HdrCreation/HDRCreator-version_1.cpp", "max_forks_repo_name": "dobrypd/HDR-Simple-Framework", "max_forks_repo_head_hexsha": "d2e83979cf5b2aa56a25cc8f9e8f8bdd346689dd", "max_forks_repo_licenses": ["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.7270029674, "max_line_length": 158, "alphanum_fraction": 0.6317445336, "num_tokens": 3716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257126, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4710625363664383}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n#include <glm/glm.hpp>\n\nnamespace draw::transform {\n\n/**\n * Contains the decomposed parts of a transformation\n */\nstruct Decomposed {\n  /**\n   * The rotation angle\n   */\n  double theta;\n\n  /**\n   * The scaling in x and y directions\n   */\n  Eigen::Vector2f scaling;\n\n  /**\n   * The translation in x and y directions\n   */\n  Eigen::Vector2f translation;\n};\n\n/**\n * Represents a transformation that can be applied to a shape\n */\nclass Transformation {\n public:\n  /**\n   * Constructs a transformation that does nothing. The identity.\n   */\n  Transformation();\n\n  /**\n   * Constructs a scaling transformation\n   */\n  static Transformation scaling(double x, double y);\n\n  /**\n   * Constructs a translation transformation\n   */\n  static Transformation translation(double x, double y);\n\n  /**\n   * Constructs a rotation transformation\n   */\n  static Transformation rotation(double theta);\n\n  /**\n   * Adds translation to the transformation\n   */\n  Transformation &translate(double x, double y);\n  Transformation &translate_x(double x);\n  Transformation &translate_y(double y);\n\n  /**\n   * Adds scaling to the transformation\n   */\n  Transformation &scale(double x, double y);\n  Transformation &scale_x(double x);\n  Transformation &scale_y(double y);\n\n  /**\n   * Adds rotation to the transformation\n   */\n  Transformation &rotate(double theta);\n\n  /**\n   * Returns the decomposed transformation\n   */\n  [[nodiscard]] Decomposed decompose() const;\n\n  /**\n   * Returns the raw transformation matrix\n   */\n  [[nodiscard]] const Eigen::Matrix3d &get() const;\n\n  /**\n   * Returns the inverse of the transformation matrix\n   */\n  [[nodiscard]] Eigen::Matrix3d get_inverse() const;\n\n  /**\n   * Returns the A-submatrix as a glm type\n   */\n  [[nodiscard]] glm::mat2 get_A_glm() const;\n\n  /**\n   * Returns the b-subvector as a glm type\n   */\n  [[nodiscard]] glm::vec2 get_b_glm() const;\n\n  /**\n   * Composes two transformations\n   */\n  friend Transformation operator*(const Transformation &lhs, const Transformation &rhs);\n\n private:\n  explicit Transformation(Eigen::Matrix3d A_prime);\n  Eigen::Matrix3d A_prime;\n};\n\n}  // namespace draw::transform", "meta": {"hexsha": "6d6bbb9d2549aa97c5dfff808f3f365d7dea8690", "size": 2165, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "transformation.hpp", "max_stars_repo_name": "maje91/draw", "max_stars_repo_head_hexsha": "59207fd3aad6c121dd0a08dee76cfd11f745a1d2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "transformation.hpp", "max_issues_repo_name": "maje91/draw", "max_issues_repo_head_hexsha": "59207fd3aad6c121dd0a08dee76cfd11f745a1d2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "transformation.hpp", "max_forks_repo_name": "maje91/draw", "max_forks_repo_head_hexsha": "59207fd3aad6c121dd0a08dee76cfd11f745a1d2", "max_forks_repo_licenses": ["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.2336448598, "max_line_length": 88, "alphanum_fraction": 0.6734411085, "num_tokens": 486, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834732, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.47104768873609165}}
{"text": "//=========================================================================\n//\n// Copyright 2018 Kitware, Inc.\n// Author: Guilbert Pierre (spguilbert@gmail.com)\n// Date: 03-27-2018\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// This slam algorithm is inspired by the LOAM algorithm:\n// J. Zhang and S. Singh. LOAM: Lidar Odometry and Mapping in Real-time.\n// Robotics: Science and Systems Conference (RSS). Berkeley, CA, July 2014.\n\n// The algorithm is composed of three sequential steps:\n//\n// - Keypoints extraction: this step consists of extracting keypoints over\n// the points clouds. To do that, the laser lines / scans are trated indepently.\n// The laser lines are projected onto the XY plane and are rescale depending on\n// their vertical angle. Then we compute their curvature and create two class of\n// keypoints. The edges keypoints which correspond to points with a hight curvature\n// and planar points which correspond to points with a low curvature.\n//\n// - Ego-Motion: this step consists of recovering the motion of the lidar\n// sensor between two frames (two sweeps). The motion is modelized by a constant\n// velocity and angular velocity between two frames (i.e null acceleration).\n// Hence, we can parameterize the motion by a rotation and translation per sweep / frame\n// and interpolate the transformation inside a frame using the timestamp of the points.\n// Since the points clouds generated by a lidar are sparses we can't design a\n// pairwise match between keypoints of two successive frames. Hence, we decided to use\n// a closest-point matching between the keypoints of the current frame\n// and the geometrics features derived from the keypoints of the previous frame.\n// The geometrics features are lines or planes and are computed using the edges keypoints\n// and planar keypoints of the previous frame. Once the matching is done, a keypoint\n// of the current frame is matched with a plane / line (depending of the\n// nature of the keypoint) from the previous frame. Then, we recover R and T by\n// minimizing the function f(R, T) = sum(d(point, line)^2) + sum(d(point, plane)^2).\n// Which can be writen f(R, T) = sum((R*X+T-P).t*A*(R*X+T-P)) where:\n// - X is a keypoint of the current frame\n// - P is a point of the corresponding line / plane\n// - A = (n*n.t) with n being the normal of the plane\n// - A = (I - n*n.t).t * (I - n*n.t) with n being a director vector of the line\n// Since the function f(R, T) is a non-linear mean square error function\n// we decided to use the Levenberg-Marquardt algorithm to recover its argmin.\n//\n// - Mapping: This step consists of refining the motion recovered in the Ego-Motion\n// step and to add the new frame in the environment map. Thanks to the ego-motion\n// recovered at the previous step it is now possible to estimate the new position of\n// the sensor in the map. We use this estimation as an initial point (R0, T0) and we\n// perform an optimization again using the keypoints of the current frame and the matched\n// keypoints of the map (and not only the previous frame this time!). Once the position in the\n// map has been refined from the first estimation it is then possible to update the map by\n// adding the keypoints of the current frame into the map.\n//\n// In the following programs : \"slam\" and \"slam.cxx\" the lidar\n// coordinate system {L} is a 3D coordinate system with its origin at the\n// geometric center of the lidar. The world coordinate system {W} is a 3D\n// coordinate system which coinciding with {L] at the initial position. The\n// points will be denoted by the ending letter L or W if they belong to\n// the corresponding coordinate system\n\n// LOCAL\n#include \"Slam.h\"\n#include \"CeresCostFunctions.h\"\n#include \"vtkEigenTools.h\"\n// STD\n#include <sstream>\n#include <algorithm>\n#include <cmath>\n#include <ctime>\n// EIGEN\n#include <Eigen/Dense>\n// PCL\n#include <pcl/filters/voxel_grid.h>\n// CERES\n#include <ceres/ceres.h>\n// NANOFLANN\n#include <nanoflann.hpp>\n\nnamespace {\n//-----------------------------------------------------------------------------\nEigen::Matrix3d GetRotationMatrix(Eigen::Matrix<double, 6, 1> T)\n{\n  return Eigen::Matrix3d(\n          Eigen::AngleAxisd(T(2), Eigen::Vector3d::UnitZ())     /* rotation around Z-axis */\n        * Eigen::AngleAxisd(T(1), Eigen::Vector3d::UnitY())     /* rotation around Y-axis */\n        * Eigen::AngleAxisd(T(0), Eigen::Vector3d::UnitX()));   /* rotation around X-axis */\n}\n\n//-----------------------------------------------------------------------------\nstd::clock_t startTime;\n\n//-----------------------------------------------------------------------------\nvoid InitTime()\n{\n  startTime = std::clock();\n}\n\n//-----------------------------------------------------------------------------\nvoid StopTimeAndDisplay(std::string functionName)\n{\n  std::clock_t endTime = std::clock();\n  double dt = static_cast<double>(endTime - startTime) / CLOCKS_PER_SEC;\n  std::cout << \"  -time elapsed in function <\" << functionName << \"> : \" << dt << \" sec\" << std::endl;\n}\n\n//-----------------------------------------------------------------------------\ndouble Rad2Deg(double val)\n{\n  return val / M_PI * 180;\n}\n}\n\n// The map reconstructed from the slam algorithm is stored in a voxel grid\n// which split the space in differents region. From this voxel grid it is possible\n// to only load the parts of the map which are pertinents when we run the mapping\n// optimization algorithm. Morevover, when a a region of the space is too far from\n// the current sensor position it is possible to remove the points stored in this region\n// and to move the voxel grid in a closest region of the sensor position. This is used\n// to decrease the memory used by the algorithm\nclass RollingGrid {\n\npublic:\n  RollingGrid() {}\n\n  RollingGrid(double posX, double posY, double posZ)\n  {\n    // should initialize using Tworld + size / 2\n    this->VoxelGridPosition[0] = static_cast<int>(posX);\n    this->VoxelGridPosition[1] = static_cast<int>(posY);\n    this->VoxelGridPosition[2] = static_cast<int>(posZ);;\n  }\n\n  // roll the grid to enable adding new point cloud\n  void Roll(Eigen::Matrix<double, 6, 1> &T)\n  {\n    // Very basic implementation where the grid is not circular\n\n    // compute the position of the new frame center in the grid\n    int frameCenterX = std::floor(T[3] / this->VoxelSize) - this->VoxelGridPosition[0];\n    int frameCenterY = std::floor(T[4] / this->VoxelSize) - this->VoxelGridPosition[1];\n    int frameCenterZ = std::floor(T[5] / this->VoxelSize) - this->VoxelGridPosition[2];\n\n    // shift the voxel grid to the left\n    while (frameCenterX - std::ceil(this->PointCloudSize / 2) <= 0)\n    {\n      for (int j = 0; j < this->VoxelSize; j++)\n      {\n        for (int k = 0; k < this->VoxelSize; k++)\n        {\n          for (int i = this->VoxelSize - 1; i > 0; i--)\n          {\n            this->grid[i][j][k] = this->grid[i-1][j][k];\n          }\n          this->grid[0][j][k].reset(new pcl::PointCloud<Slam::Point>());\n        }\n      }\n      frameCenterX++;\n      this->VoxelGridPosition[0]--;\n    }\n\n    // shift the voxel grid to the right\n    while (frameCenterX + std::ceil(this->PointCloudSize / 2) >= this->VoxelSize - 1)\n    {\n      for (int j = 0; j < this->VoxelSize; j++)\n      {\n        for (int k = 0; k < this->VoxelSize; k++)\n        {\n          for (int i = 0; i < this->VoxelSize - 1; i++)\n          {\n            this->grid[i][j][k] = this->grid[i+1][j][k];\n          }\n          this->grid[VoxelSize-1][j][k].reset(new pcl::PointCloud<Slam::Point>());\n        }\n      }\n      frameCenterX--;\n      this->VoxelGridPosition[0]++;\n    }\n\n    // shift the voxel grid to the bottom\n    while (frameCenterY - std::ceil(this->PointCloudSize / 2) <= 0)\n    {\n      for (int i = 0; i < this->VoxelSize; i++)\n      {\n        for (int k = 0; k < this->VoxelSize; k++)\n        {\n          for (int j = this->VoxelSize - 1; j > 0; j--)\n          {\n            this->grid[i][j][k] = this->grid[i][j-1][k];\n          }\n          this->grid[i][0][k].reset(new pcl::PointCloud<Slam::Point>());\n        }\n      }\n      frameCenterY++;\n      this->VoxelGridPosition[1]--;\n//      cout << \"bottom\";\n    }\n\n    // shift the voxel grid to the top\n    while (frameCenterY + std::ceil(this->PointCloudSize / 2) >= this->VoxelSize - 1)\n    {\n      for (int i = 0; i < this->VoxelSize; i++)\n      {\n        for (int k = 0; k < this->VoxelSize; k++)\n        {\n          for (int j = 0; j < this->VoxelSize - 1; j++)\n          {\n            this->grid[i][j][k] = this->grid[i][j+1][k];\n          }\n          this->grid[i][VoxelSize-1][k].reset(new pcl::PointCloud<Slam::Point>());\n        }\n      }\n      frameCenterY--;\n      this->VoxelGridPosition[1]++;\n    }\n\n    // shift the voxel grid to the \"camera\"\n    while (frameCenterZ - std::ceil(this->PointCloudSize / 2) <= 0)\n    {\n      for (int i = 0; i < this->VoxelSize; i++)\n      {\n        for (int j = 0; j < this->VoxelSize; j++)\n        {\n          for (int k = this->VoxelSize - 1; k > 0; k--)\n          {\n            this->grid[i][j][k] = this->grid[i][j][k-1];\n          }\n          this->grid[i][j][0].reset(new pcl::PointCloud<Slam::Point>());\n        }\n      }\n      frameCenterZ++;\n      this->VoxelGridPosition[2]--;\n    }\n\n    // shift the voxel grid to the \"horizon\"\n    while (frameCenterZ + std::ceil(this->PointCloudSize  / 2) >= this->VoxelSize - 1)\n    {\n      for (int i = 0; i < this->VoxelSize; i++)\n      {\n        for (int j = 0; j < this->VoxelSize; j++)\n        {\n          for (int k = 0; k < this->VoxelSize - 1; k++)\n          {\n            this->grid[i][j][k] = this->grid[i][j][k+1];\n          }\n          this->grid[i][j][VoxelSize-1].reset(new pcl::PointCloud<Slam::Point>());\n        }\n      }\n      frameCenterZ--;\n      this->VoxelGridPosition[2]++;\n    }\n  }\n\n  // get points arround T\n  pcl::PointCloud<Slam::Point>::Ptr Get(Eigen::Matrix<double, 6, 1> &T)\n  {\n    // compute the position of the new frame center in the grid\n    int frameCenterX = std::floor(T[3] / this->VoxelSize) - this->VoxelGridPosition[0];\n    int frameCenterY = std::floor(T[4] / this->VoxelSize) - this->VoxelGridPosition[1];\n    int frameCenterZ = std::floor(T[5] / this->VoxelSize) - this->VoxelGridPosition[2];\n\n    pcl::PointCloud<Slam::Point>::Ptr intersection(new pcl::PointCloud<Slam::Point>);\n\n    // Get all voxel in intersection should use ceil here\n    for (int i = frameCenterX - std::ceil(this->PointCloudSize / 2); i <= frameCenterX + std::ceil(this->PointCloudSize / 2); i++)\n    {\n      for (int j = frameCenterY - std::ceil(this->PointCloudSize / 2); j <= frameCenterY + std::ceil(this->PointCloudSize / 2); j++)\n      {\n        for (int k = frameCenterZ - std::ceil(this->PointCloudSize / 2); k <= frameCenterZ + std::ceil(this->PointCloudSize / 2); k++)\n        {\n          if (i < 0 || i > (this->VoxelSize - 1) ||\n              j < 0 || j > (this->VoxelSize - 1) ||\n              k < 0 || k > (this->VoxelSize - 1))\n          {\n            continue;\n          }\n          pcl::PointCloud<Slam::Point>:: Ptr voxel = this->grid[i][j][k];\n          for (unsigned int l = 0; l < voxel->size(); l++)\n          {\n            intersection->push_back(voxel->at(l));\n          }\n        }\n      }\n    }\n    return intersection;\n  }\n\n  // get all points\n  pcl::PointCloud<Slam::Point>::Ptr Get()\n  {\n    pcl::PointCloud<Slam::Point>::Ptr intersection(new pcl::PointCloud<Slam::Point>);\n\n    // Get all voxel in intersection should use ceil here\n    for (int i = 0; i < VoxelSize; i++)\n    {\n      for (int j = 0; j < VoxelSize; j++)\n      {\n        for (int k = 0; k < VoxelSize; k++)\n        {\n          pcl::PointCloud<Slam::Point>:: Ptr voxel = this->grid[i][j][k];\n          for (unsigned int l = 0; l < voxel->size(); l++)\n          {\n            intersection->push_back(voxel->at(l));\n          }\n        }\n      }\n    }\n    return intersection;\n  }\n\n  // add some points to the grid\n  void Add(pcl::PointCloud<Slam::Point>::Ptr pointcloud)\n  {\n    if (pointcloud->size() == 0)\n    {\n      std::cout << \"Pointcloud empty, voxel grid not updated\" << std::endl;\n      return;\n    }\n\n    // Voxel to filte because new points were add\n    std::vector<std::vector<std::vector<int> > > voxelToFilter(VoxelSize, std::vector<std::vector<int> >(VoxelSize, std::vector<int>(VoxelSize, 0)));\n\n    // Add points in the rolling grid\n    int outlier = 0; // point who are not in the rolling grid\n    for (unsigned int i = 0; i < pointcloud->size(); i++)\n    {\n      Slam::Point pts = pointcloud->points[i];\n      // find the closest coordinate\n      int cubeIdxX = std::floor(pts.x / this->VoxelSize) - this->VoxelGridPosition[0];\n      int cubeIdxY = std::floor(pts.y / this->VoxelSize) - this->VoxelGridPosition[1];\n      int cubeIdxZ = std::floor(pts.z / this->VoxelSize) - this->VoxelGridPosition[2];\n\n\n      if (cubeIdxX >= 0 && cubeIdxX < this->VoxelSize &&\n        cubeIdxY >= 0 && cubeIdxY < this->VoxelSize &&\n        cubeIdxZ >= 0 && cubeIdxZ < this->VoxelSize)\n      {\n        voxelToFilter[cubeIdxX][cubeIdxY][cubeIdxZ] = 1;\n        grid[cubeIdxX][cubeIdxY][cubeIdxZ]->push_back(pts);\n      }\n      else\n      {\n        outlier++;\n      }\n    }\n\n    // Filter the modified pointCloud\n    pcl::VoxelGrid<Slam::Point> downSizeFilter;\n    downSizeFilter.setLeafSize(this->LeafSize, this->LeafSize, this->LeafSize);\n    for (int i = 0; i < this->VoxelSize; i++)\n    {\n      for (int j = 0; j < this->VoxelSize; j++)\n      {\n        for (int k = 0; k < this->VoxelSize; k++)\n        {\n          if (voxelToFilter[i][j][k] == 1)\n          {\n            pcl::PointCloud<Slam::Point>::Ptr tmp(new pcl::PointCloud<Slam::Point>());\n            downSizeFilter.setInputCloud(grid[i][j][k]);\n            downSizeFilter.filter(*tmp);\n            grid[i][j][k] = tmp;\n          }\n        }\n      }\n    }\n  }\n\n\n  void SetPointCoudMaxRange(const double maxdist)\n  {\n    this->PointCloudSize = 2.0 * std::ceil(maxdist / this->VoxelResolution);\n  }\n\n  void SetSize(int size)\n  {\n    this->VoxelSize = size;\n    grid.resize(this->VoxelSize);\n    for (int i = 0; i < this->VoxelSize; i++)\n    {\n      grid[i].resize(this->VoxelSize);\n      for (int j = 0; j < this->VoxelSize; j++)\n      {\n        grid[i][j].resize(this->VoxelSize);\n        for (int k = 0; k < this->VoxelSize; k++)\n        {\n          grid[i][j][k].reset(new pcl::PointCloud<Slam::Point>());\n        }\n      }\n    }\n  }\n\n  void SetResolution(double resolution) { this->VoxelResolution = resolution; }\n\n  void SetLeafSize(double size) { this->LeafSize = size; }\n\nprivate:\n  //! Size of the voxel grid: n*n*n voxels\n  int VoxelSize = 50;\n\n  //! Resolution of a voxel\n  double VoxelResolution = 10;\n\n  //! Size of a pointcloud in voxel\n  int PointCloudSize = 25;\n\n  //! Size of the leaf use to downsample the pointcloud\n  double LeafSize = 0.2;\n\n  //! VoxelGrid of pointcloud\n  std::vector<std::vector<std::vector<pcl::PointCloud<Slam::Point>::Ptr> > > grid;\n\n  // Position of the VoxelGrid\n  int VoxelGridPosition[3] = {0,0,0};\n};\n\n//-----------------------------------------------------------------------------\nSlam::Slam()\n{\n  this->Reset();\n}\n\n//-----------------------------------------------------------------------------\nvoid Slam::Reset()\n{\n  this->EdgesPointsLocalMap = std::make_shared<RollingGrid>();\n  this->PlanarPointsLocalMap = std::make_shared<RollingGrid>();\n  this->BlobsPointsLocalMap = std::make_shared<RollingGrid>();\n\n  this->EdgesPointsLocalMap->SetResolution(10);\n  this->PlanarPointsLocalMap->SetResolution(10);\n  this->BlobsPointsLocalMap->SetResolution(10);\n\n  this->EdgesPointsLocalMap->SetSize(50);\n  this->PlanarPointsLocalMap->SetSize(50);\n  this->BlobsPointsLocalMap->SetSize(50);\n\n  this->NbrFrameProcessed = 0;\n\n  // n-DoF parameters\n  this->Tworld = Eigen::Matrix<double, 6, 1>::Zero();\n  this->Trelative = Eigen::Matrix<double, 6, 1>::Zero();\n  this->MotionParametersEgoMotion = Eigen::VectorXd::Zero(12, 1);\n  this->MotionParametersMapping = Eigen::VectorXd::Zero(12, 1);\n\n  this->SetVoxelGridLeafSizeEdges(0.45);\n  this->SetVoxelGridLeafSizePlanes(0.6);\n  this->SetVoxelGridLeafSizeBlobs(0.12);\n}\n\n//-----------------------------------------------------------------------------\nTransform Slam::GetWorldTransform()\n{\n  Transform t;\n\n  t.x = this->Tworld(3);\n  t.y = this->Tworld(4);\n  t.z = this->Tworld(5);\n\n  Eigen::Matrix3d Rw = GetRotationMatrix(this->Tworld);\n  t.rx = std::atan2(Rw(2, 1), Rw(2, 2));\n  t.ry = -std::asin(Rw(2, 0));\n  t.rz = std::atan2(Rw(1, 0), Rw(0, 0));\n\n  return t;\n}\n\n//-----------------------------------------------------------------------------\nstd::vector<double> Slam::GetTransformCovariance()\n{\n  std::vector<double> cov(36);\n  std::copy(this->TworldCovariance.data(), this->TworldCovariance.data() + 36, cov.data());\n  return cov;\n}\n\n//-----------------------------------------------------------------------------\nstd::unordered_map<std::string, double> Slam::GetDebugInformation()\n{\n  std::unordered_map<std::string, double> map;\n  map[\"EgoMotion: edges used\"] = this->EgoMotionEdgesPointsUsed;\n  map[\"EgoMotion: planes used\"] = this->EgoMotionPlanesPointsUsed;\n  map[\"Mapping: edges used\"] = this->MappingEdgesPointsUsed;\n  map[\"Mapping: planes used\"] = this->MappingPlanesPointsUsed;\n  map[\"Mapping: blobs used\"] = this->MappingBlobsPointsUsed;\n  map[\"Mapping: variance error\"] = this->MappingVarianceError;\n  return map;\n}\n\n//-----------------------------------------------------------------------------\npcl::PointCloud<PointXYZTIId>::Ptr Slam::GetEdgesMap()\n{\n  return this->EdgesPointsLocalMap->Get();\n}\n\n//-----------------------------------------------------------------------------\npcl::PointCloud<Slam::Point>::Ptr Slam::GetPlanarsMap()\n{\n  return this->PlanarPointsLocalMap->Get();\n}\n\n//-----------------------------------------------------------------------------\npcl::PointCloud<Slam::Point>::Ptr Slam::GetBlobsMap()\n{\n  return this->BlobsPointsLocalMap->Get();\n}\n\n//-----------------------------------------------------------------------------\nvoid Slam::AddFrame(pcl::PointCloud<Slam::Point>::Ptr pc, std::vector<size_t> laserIdMapping)\n{\n  if (pc->size() == 0)\n  {\n    std::cout << \"Slam entry is an empty pointcloud\" << std::endl;\n    return;\n  }\n\n  std::cout << \"#########################################################\" << std::endl\n            << \"Processing frame : \" << this->NbrFrameProcessed << std:: endl\n            << \"#########################################################\" << std::endl\n            << std::endl;\n\n  double time = pc->points[0].time;\n\n  // If the new frame is the first one we just add the\n  // extracted keypoints into the map without running\n  // odometry and mapping steps\n  if (this->NbrFrameProcessed == 0)\n  {\n    // Compute the edges and planars keypoints\n    this->KeyPointsExtractor->ComputeKeyPoints(pc, laserIdMapping);\n    this->CurrentEdgesPoints = this->KeyPointsExtractor->GetEdgePoints();\n    this->CurrentPlanarsPoints = this->KeyPointsExtractor->GetPlanarPoints();\n    this->CurrentBlobsPoints = this->KeyPointsExtractor->GetBlobPoints();\n\n    // update map using tworld\n    this->UpdateMapsUsingTworld();\n\n    // Current keypoints become previous ones\n    this->PreviousEdgesPoints = this->CurrentEdgesPoints;\n    this->PreviousPlanarsPoints = this->CurrentPlanarsPoints;\n    this->PreviousBlobsPoints = this->CurrentBlobsPoints;\n    this->NbrFrameProcessed++;\n    return;\n  }\n\n  // Compute the edges and planars keypoints\n  InitTime();\n  this->KeyPointsExtractor->ComputeKeyPoints(pc, laserIdMapping);\n  this->CurrentEdgesPoints = this->KeyPointsExtractor->GetEdgePoints();\n  this->CurrentPlanarsPoints = this->KeyPointsExtractor->GetPlanarPoints();\n  this->CurrentBlobsPoints = this->KeyPointsExtractor->GetBlobPoints();\n  StopTimeAndDisplay(\"Keypoints extraction\");\n\n  // Perfom EgoMotion\n  InitTime();\n  this->ComputeEgoMotion();\n  StopTimeAndDisplay(\"Ego-Motion\");\n\n  // Transform the current keypoints to the\n  // referential of the sensor at the end of\n  // frame acquisition\n  InitTime();\n  //this->TransformCurrentKeypointsToEnd();\n  StopTimeAndDisplay(\"Undistortion\");\n\n  // Perform Mapping\n  InitTime();\n  this->Mapping();\n  StopTimeAndDisplay(\"Mapping\");\n\n  // Current keypoints become previous ones\n  this->PreviousEdgesPoints = this->CurrentEdgesPoints;\n  this->PreviousPlanarsPoints = this->CurrentPlanarsPoints;\n  this->NbrFrameProcessed++;\n\n  // Motion and localization parameters estimation information display\n  Eigen::Vector3d angles, trans;\n  angles << Rad2Deg(this->Trelative(0)), Rad2Deg(this->Trelative(1)), Rad2Deg(this->Trelative(2));\n  trans << this->Trelative(3), this->Trelative(4), this->Trelative(5);\n  std::cout << \"Ego-Motion estimation: angles = [\" << angles.transpose() << \"] translation: [\" << trans.transpose() << \"]\" << std::endl;\n  angles << Rad2Deg(this->Tworld(0)), Rad2Deg(this->Tworld(1)), Rad2Deg(this->Tworld(2));\n  trans << this->Tworld(3), this->Tworld(4), this->Tworld(5);\n  std::cout << \"Localiazion estimation: angles = [\" << angles.transpose() << \"] translation: [\" << trans.transpose() << \"]\"\n            << std::endl << std::endl << std::endl;\n\n  // Update Trajectory\n  this->Trajectory.emplace_back(Transform(time, this->Tworld));\n}\n\n//-----------------------------------------------------------------------------\nvoid Slam::TransformToWorld(Point& p)\n{\n  if (this->Undistortion)\n  {\n    this->ExpressPointInOtherReferencial(p);\n  }\n  else\n  {\n    // Rotation and translation and points\n    Eigen::Matrix3d Rw;\n    Eigen::Vector3d Tw;\n    Eigen::Vector3d P;\n\n    Rw = GetRotationMatrix(this->Tworld);\n    Tw << this->Tworld(3), this->Tworld(4), this->Tworld(5);\n    P << p.x, p.y, p.z;\n\n    P = Rw * P + Tw;\n\n    p.x = P(0);\n    p.y = P(1);\n    p.z = P(2);\n  }\n}\n\n//-----------------------------------------------------------------------------\nint Slam::ComputeLineDistanceParameters(KDTreePCLAdaptor& kdtreePreviousEdges, Eigen::Matrix3d& R,\n                                           Eigen::Vector3d& dT, Point p, MatchingMode matchingMode)\n{\n  // number of neighbors edge points required to approximate\n  // the corresponding egde line\n  unsigned int requiredNearest;\n  unsigned int eigenValuesRatio;\n  std::vector<int> nearestIndex;\n  std::vector<float> nearestDist;\n\n  // maximum distance between keypoints\n  // and their computed line\n  double squaredMaxDist;\n\n  // Transform the point using the current pose estimation\n  Eigen::Vector3d P0(p.x, p.y, p.z);\n  Eigen::Vector3d P, n;\n  Eigen::Matrix3d A;\n  // Time continious motion model to take\n  // into account the rolling shutter distortion\n  if (this->Undistortion)\n  {\n    this->ExpressPointInOtherReferencial(p);\n  }\n  // Rigid transform\n  else\n  {\n    P = R * P0 + dT;\n    p.x = P(0); p.y = P(1); p.z = P(2);\n  }\n\n  if (matchingMode == MatchingMode::EgoMotion)\n  {\n    requiredNearest = this->EgoMotionLineDistanceNbrNeighbors;\n    eigenValuesRatio = this->EgoMotionLineDistancefactor;\n    squaredMaxDist = std::pow(this->EgoMotionMaxLineDistance, 2);\n    GetEgoMotionLineSpecificNeighbor(nearestIndex, nearestDist, requiredNearest, kdtreePreviousEdges, p);\n    if (nearestIndex.size() < this->EgoMotionMinimumLineNeighborRejection)\n    {\n      return 0;\n    }\n    requiredNearest = nearestIndex.size();\n  }\n  else if (matchingMode == MatchingMode::Mapping)\n  {\n    requiredNearest = this->MappingLineDistanceNbrNeighbors;\n    eigenValuesRatio = this->MappingLineDistancefactor;\n    squaredMaxDist = std::pow(this->MappingMaxLineDistance, 2);\n    GetMappingLineSpecificNeigbbor(nearestIndex, nearestDist, this->MappingLineMaxDistInlier, requiredNearest, kdtreePreviousEdges, p);\n    if (nearestIndex.size() < this->MappingMinimumLineNeighborRejection)\n    {\n      return 0;\n    }\n    requiredNearest = nearestIndex.size();\n  }\n  else\n  {\n    throw \"ComputeLineDistanceParameters function got invalide step parameter\";\n  }\n\n  // if the nearest edges are too far from the\n  // current edge keypoint we skip this point.\n  if (nearestDist[requiredNearest - 1] > this->MaxDistanceForICPMatching)\n  {\n    return 1;\n  }\n\n  // Compute PCA to determine best line approximation\n  // of the requiredNearest nearest edges points extracted\n  // Thans to the PCA we will check the shape of the neighborhood\n  // and keep it if it is distributed along a line\n  Eigen::MatrixXd data(requiredNearest, 3);\n  for (unsigned int k = 0; k < requiredNearest; k++)\n  {\n    Point pt = kdtreePreviousEdges.getInputCloud()->points[nearestIndex[k]];\n    data.row(k) << pt.x, pt.y, pt.z;\n  }\n\n  Eigen::Vector3d mean = data.colwise().mean();\n  Eigen::MatrixXd centered = data.rowwise() - mean.transpose();\n  Eigen::Matrix3d varianceCovariance = centered.transpose() * centered;\n  Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> eig(varianceCovariance);\n\n  // Eigen values\n  Eigen::MatrixXd D = eig.eigenvalues();\n\n  // if the first eigen value is significantly higher than\n  // the second one, it means the sourrounding points are\n  // distributed on a edge line\n  if (D(2) > eigenValuesRatio * D(1))\n  {\n    // n is the director vector of the line\n    n = eig.eigenvectors().col(2);\n  }\n  else\n  {\n    return 2;\n  }\n\n  // A = (I-n*n.t).t * (I-n*n.t) = (I - n*n.t)^2\n  // since (I-n*n.t) is a symmetric matrix\n  // Then it comes A (I-n*n.t)^2 = (I-n*n.t) since\n  // A is the matrix of a projection endomorphism\n  A = (this->I3 - n * n.transpose());\n\n  // it would be the case if P1 = P2 For instance\n  // if the sensor has some dual returns that hit the same point\n  if (!std::isfinite(A(0, 0)))\n  {\n    return 3;\n  }\n\n  // Evaluate the distance from the fitted line distribution\n  // of the neighborhood\n  Eigen::Vector3d Xtemp;\n  Point pt;\n  double meanSquaredDist = 0;\n  for (unsigned int k = 0; k < requiredNearest; ++k)\n  {\n    pt = kdtreePreviousEdges.getInputCloud()->points[nearestIndex[k]];\n    Xtemp(0) = pt.x; Xtemp(1) = pt.y; Xtemp(2) = pt.z;\n    double squaredDist = (Xtemp - mean).transpose() * A * (Xtemp - mean);\n    if (squaredDist > squaredMaxDist)\n    {\n      return 4;\n    }\n    meanSquaredDist += squaredDist;\n  }\n  meanSquaredDist /= static_cast<double>(requiredNearest);\n  double fitQualityCoeff = 1.0 - std::sqrt(std::abs(meanSquaredDist) / squaredMaxDist);\n\n  // s represents the quality of the match\n  double s = fitQualityCoeff;\n\n  // store the distance parameters values\n  this->Avalues.emplace_back(A);\n  this->Pvalues.emplace_back(mean);\n  this->Xvalues.emplace_back(P0);\n  this->TimeValues.emplace_back(p.intensity);\n  this->residualCoefficient.emplace_back(s);\n  return 6;\n}\n\n//-----------------------------------------------------------------------------\nint Slam::ComputePlaneDistanceParameters(KDTreePCLAdaptor& kdtreePreviousPlanes, Eigen::Matrix3d& R,\n                                            Eigen::Vector3d& dT, Point p, MatchingMode matchingMode)\n{\n  // number of neighbors edge points required to approximate\n  // the corresponding egde line\n  unsigned int requiredNearest;\n  unsigned int significantlyFactor1, significantlyFactor2;\n\n  // maximum distance between keypoints\n  // and their computed plane\n  double squaredMaxDist;\n\n  if (matchingMode == MatchingMode::EgoMotion)\n  {\n    significantlyFactor1 = this->EgoMotionPlaneDistancefactor1;\n    significantlyFactor2 = this->EgoMotionPlaneDistancefactor2;\n    requiredNearest = this->EgoMotionPlaneDistanceNbrNeighbors;\n    squaredMaxDist = std::pow(this->EgoMotionMaxPlaneDistance, 2);\n  }\n  else if (matchingMode == MatchingMode::Mapping)\n  {\n    significantlyFactor1 = this->MappingPlaneDistancefactor1;\n    significantlyFactor2 = this->MappingPlaneDistancefactor2;\n    requiredNearest = this->MappingPlaneDistanceNbrNeighbors;\n    squaredMaxDist = std::pow(this->MappingMaxPlaneDistance, 2);\n  }\n  else\n  {\n    throw \"ComputeLineDistanceParameters function got invalide step parameter\";\n  }\n\n  Eigen::Vector3d P, n;\n  Eigen::Matrix3d A;\n\n  // Transform the point using the current pose estimation\n  Eigen::Vector3d P0(p.x, p.y, p.z);\n\n  // Time continious motion model to take\n  // into account the rolling shutter distortion\n  if (this->Undistortion)\n  {\n    this->ExpressPointInOtherReferencial(p);\n  }\n  // Rigid transform\n  else\n  {\n    P = R * P0 + dT;\n    p.x = P(0); p.y = P(1); p.z = P(2);\n  }\n\n  std::vector<int> nearestIndex(requiredNearest, -1);\n  std::vector<double> nearestDist(requiredNearest, -1.0);\n  kdtreePreviousPlanes.query(p, requiredNearest, nearestIndex.data(), nearestDist.data());\n\n  // It means that there is not enought keypoints in the neighbohood\n  if (nearestIndex[requiredNearest - 1] == -1)\n  {\n    return 0;\n  }\n\n  // if the nearest planars are too far from the\n  // current planar keypoint we skip this point.\n  if (nearestDist[requiredNearest - 1] > this->MaxDistanceForICPMatching)\n  {\n    return 1;\n  }\n\n  // Compute PCA to determine best line approximation\n  // of the requiredNearest nearest edges points extracted\n  // Thanks to the PCA we will check the shape of the neighborhood\n  // and keep it if it is distributed along a line\n  Eigen::MatrixXd data(requiredNearest,3);\n  for (unsigned int k = 0; k < requiredNearest; k++)\n  {\n    Point pt = kdtreePreviousPlanes.getInputCloud()->points[nearestIndex[k]];\n    data.row(k) << pt.x, pt.y, pt.z;\n  }\n  Eigen::Vector3d mean = data.colwise().mean();\n  Eigen::MatrixXd centered = data.rowwise() - mean.transpose();\n  Eigen::Matrix3d varianceCovariance = centered.transpose() * centered;\n  Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> eig(varianceCovariance);\n\n  // Eigenvalues\n  Eigen::VectorXd D = eig.eigenvalues();\n\n  // if the second eigen value is close to the highest one\n  // and bigger than the smallest one it means that the points\n  // are distributed among a plane\n  if ( (significantlyFactor2 * D(1) > D(2)) && (D(1) > significantlyFactor1 * D(0)) )\n  {\n    n = eig.eigenvectors().col(0);\n  }\n  else\n  {\n    return 2;\n  }\n\n  // A = n*n.t\n  A = n * n.transpose();\n\n  // it would be the case if P1 = P2, P1 = P3\n  // or P3 = P2. For instance if the sensor has\n  // some dual returns that hit the same point\n  if (!std::isfinite(A(0, 0)))\n  {\n    return 3;\n  }\n\n  Eigen::Vector3d Xtemp;\n  Point pt;\n  double meanSquaredDist = 0;\n  for (unsigned int k = 0; k < requiredNearest; ++k)\n  {\n    pt = kdtreePreviousPlanes.getInputCloud()->points[nearestIndex[k]];\n    Xtemp(0) = pt.x; Xtemp(1) = pt.y; Xtemp(2) = pt.z;\n    double squaredDist = (Xtemp - mean).transpose() * A * (Xtemp - mean);\n    if (squaredDist > squaredMaxDist)\n    {\n      return 4;\n    }\n    meanSquaredDist += squaredDist;\n  }\n  meanSquaredDist /= static_cast<double>(requiredNearest);\n  double fitQualityCoeff = 1.0 - std::sqrt(std::abs(meanSquaredDist) / squaredMaxDist);\n\n  // s represents the quality of the match\n  double s = fitQualityCoeff;\n\n  // store the distance parameters values\n  this->Avalues.emplace_back(A);\n  this->Pvalues.emplace_back(mean);\n  this->Xvalues.emplace_back(P0);\n  this->residualCoefficient.emplace_back(s);\n  this->TimeValues.emplace_back(p.intensity);\n  return 6;\n}\n\n//-----------------------------------------------------------------------------\nint Slam::ComputeBlobsDistanceParameters(pcl::KdTreeFLANN<Slam::Point>::Ptr kdtreePreviousBlobs, Eigen::Matrix3d& R,\n                                            Eigen::Vector3d& dT, Point p, MatchingMode /*matchingMode*/)\n{\n  // number of neighbors blobs points required to approximate\n  // the corresponding ellipsoide\n  unsigned int requiredNearest = 25;\n\n  // maximum distance between keypoints\n  // and its neighbor\n  double maxDist = this->MaxDistanceForICPMatching;\n  float maxDiameterTol = std::pow(4.0, 2);\n\n  // Usefull variables\n  Eigen::Vector3d P0, P, n;\n  Eigen::Matrix3d A;\n\n  // Transform the point using the current pose estimation\n  P << p.x, p.y, p.z;\n  P0 = P;\n  P = R * P + dT;\n  p.x = P(0); p.y = P(1); p.z = P(2);\n\n  std::vector<int> nearestIndex;\n  std::vector<float> nearestDist;\n  kdtreePreviousBlobs->nearestKSearch(p, requiredNearest, nearestIndex, nearestDist);\n\n  // It means that there is not enought keypoints in the neighbohood\n  if (nearestIndex.size() < requiredNearest)\n  {\n    return 0;\n  }\n\n  // if the nearest blobs is too far from the\n  // current blob keypoint we skip this point.\n  if (nearestDist[requiredNearest - 1] > maxDist)\n  {\n    return 1;\n  }\n\n  // check the diameter of the neighborhood\n  // if the diameter is too big we don't want\n  // to keep this blobs. We must do that since\n  // the blobs fitted ellipsoide is assume to\n  // encode the local neighborhood shape.\n  float maxDiameter = 0;\n  for (unsigned int i = 0; i < requiredNearest; ++i)\n  {\n    for (unsigned int j = 0; j < requiredNearest; ++j)\n    {\n      Point pt1 = kdtreePreviousBlobs->getInputCloud()->points[nearestIndex[i]];\n      Point pt2 = kdtreePreviousBlobs->getInputCloud()->points[nearestIndex[j]];\n      float neighborhoodDiameter = std::pow(pt1.x - pt2.x, 2) + std::pow(pt1.y - pt2.y, 2) + std::pow(pt1.z - pt2.z, 2);\n      maxDiameter = std::max(maxDiameter, neighborhoodDiameter);\n    }\n  }\n  if (maxDiameter > maxDiameterTol)\n  {\n    return 2;\n  }\n\n  // Compute PCA to determine best ellipsoide approximation\n  // of the requiredNearest nearest blobs points extracted\n  // Thanks to the PCA we will check the shape of the neighborhood\n  // tune a distance function adapter to the distribution\n  // (Mahalanobis distance)\n  Eigen::MatrixXd data(requiredNearest, 3);\n\n  for (unsigned int k = 0; k < requiredNearest; k++)\n  {\n    Point pt = kdtreePreviousBlobs->getInputCloud()->points[nearestIndex[k]];\n    data.row(k) << pt.x, pt.y, pt.z;\n  }\n\n  Eigen::Vector3d mean = data.colwise().mean();\n  Eigen::MatrixXd centered = data.rowwise() - mean.transpose();\n  Eigen::Matrix3d varianceCovariance = centered.transpose() * centered;\n\n  // Sigma is the inverse of the covariance\n  // Matrix encoding the mahalanobis distance\n  // check that the covariance matrix is inversible\n  if (std::abs(varianceCovariance.determinant()) < 1e-6)\n  {\n    return 3;\n  }\n  Eigen::Matrix3d sigma = varianceCovariance.inverse();\n  Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> eig(sigma);\n\n  // rescale the variance covariance matrix to preserve the\n  // shape of the mahalanobis distance but removing the\n  // variance values scaling\n  Eigen::MatrixXd D = eig.eigenvalues();\n  Eigen::MatrixXd U = eig.eigenvectors();\n  D = D / D(2);\n  Eigen::Matrix3d diagD = Eigen::Matrix3d::Zero();\n  diagD(0, 0) = D(0); diagD(1, 1) = D(1); diagD(2, 2) = D(2);\n  A = U * diagD * U.transpose();\n\n  if (!std::isfinite(A.determinant()))\n  {\n    return 4;\n  }\n\n  // Coefficient the distance\n  // using the distance between the point\n  // and its matching blob; The aim is to prevent\n  // wrong matching to pull the point cloud in the\n  // bad direction\n  double s = 1.0;//1.0 - nearestDist[requiredNearest - 1] / maxDist;\n\n  // store the distance parameters values\n  this->Avalues.emplace_back(A);\n  this->Pvalues.emplace_back(mean);\n  this->Xvalues.emplace_back(P0);\n  this->residualCoefficient.emplace_back(s);\n  return 5;\n}\n\n//-----------------------------------------------------------------------------\nvoid Slam::GetEgoMotionLineSpecificNeighbor(std::vector<int>& nearestValid, std::vector<float>& nearestValidDist,\n                                               unsigned int nearestSearch, KDTreePCLAdaptor& kdtreePreviousEdges, Point p)\n{\n  // clear vector\n  nearestValid.clear();\n  nearestValid.resize(0);\n  nearestValidDist.clear();\n  nearestValidDist.resize(0);\n\n  // get nearest neighbor of the query point\n  std::vector<int> nearestIndex(nearestSearch, -1);\n  std::vector<double> nearestDist(nearestSearch, -1.0);\n  kdtreePreviousEdges.query(p, nearestSearch, nearestIndex.data(), nearestDist.data());\n\n  // take the closest point\n  std::vector<int> idAlreadyTook(this->KeyPointsExtractor->GetNLasers(), 0);\n  Point closest = kdtreePreviousEdges.getInputCloud()->points[nearestIndex[0]];\n  nearestValid.push_back(nearestIndex[0]);\n  nearestValidDist.push_back(nearestDist[0]);\n\n  // invalid all possible points that\n  // are on the same scan line than the\n  // closest one\n  idAlreadyTook[(int)closest.laserId] = 1;\n\n  // invalid all possible points from scan\n  // lines that are too far from the closest one\n  for (int k = 0; k < this->KeyPointsExtractor->GetNLasers(); ++k)\n  {\n    if (std::abs(int(closest.laserId) - k) > 4.0)\n    {\n      idAlreadyTook[k] = 1;\n    }\n  }\n\n  // Make a selection among the neighborhood\n  // of the query point. We can only take one edge\n  // per scan line\n  int id;\n  for (unsigned int k = 1; k < nearestIndex.size(); ++k)\n  {\n    id = kdtreePreviousEdges.getInputCloud()->points[nearestIndex[k]].laserId;\n    if ( (idAlreadyTook[id] < 1) && (nearestDist[k] < this->MaxDistanceForICPMatching))\n    {\n      idAlreadyTook[id] = 1;\n      nearestValid.push_back(nearestIndex[k]);\n      nearestValidDist.push_back(nearestDist[k]);\n    }\n  }\n}\n\n//-----------------------------------------------------------------------------\nvoid Slam::GetMappingLineSpecificNeigbbor(std::vector<int>& nearestValid, std::vector<float>& nearestValidDist, double maxDistInlier,\n                                             unsigned int nearestSearch, KDTreePCLAdaptor& kdtreePreviousEdges, Point p)\n{\n  // reset vectors\n  nearestValid.clear();\n  nearestValid.resize(0);\n  nearestValidDist.clear();\n  nearestValidDist.resize(0);\n\n  // to prevent square root when making camparisons\n  maxDistInlier = std::pow(maxDistInlier, 2);\n\n  // Take the neighborhood of the query point\n  // get nearest neighbor of the query point\n  std::vector<int> nearestIndex(nearestSearch, -1);\n  std::vector<double> nearestDist(nearestSearch, -1.0);\n  kdtreePreviousEdges.query(p, nearestSearch, nearestIndex.data(), nearestDist.data());\n\n  // take the closest point\n  std::vector<std::vector<int> > inliersList;\n  Point closest = kdtreePreviousEdges.getInputCloud()->points[nearestIndex[0]];\n  nearestValid.push_back(nearestIndex[0]);\n  nearestValidDist.push_back(nearestDist[0]);\n\n  Eigen::Vector3d P1, P2, dir, Pcdt;\n  Eigen::Matrix3d D;\n  P1 << closest.x, closest.y, closest.z;\n  Point pclP2;\n  Point inlierCandidate;\n\n  // Loop over other neighbors of the neighborhood. For each of them\n  // compute the line between closest point and current point and\n  // compute the number of inlier that fit this line. Keep the line and its\n  // inliers with the most inliers\n  for (unsigned int ptIndex = 1; ptIndex < nearestIndex.size(); ++ptIndex)\n  {\n    std::vector<int> inlierIndex;\n    pclP2 = kdtreePreviousEdges.getInputCloud()->points[nearestIndex[ptIndex]];\n    P2 << pclP2.x, pclP2.y, pclP2.z;\n    dir = (P2 - P1).normalized();\n    D = this->I3 - dir * dir.transpose();\n    D = D.transpose() * D;\n\n    for (unsigned int candidateIndex = 1; candidateIndex < nearestIndex.size(); ++candidateIndex)\n    {\n      inlierCandidate = kdtreePreviousEdges.getInputCloud()->points[nearestIndex[candidateIndex]];\n      Pcdt << inlierCandidate.x, inlierCandidate.y, inlierCandidate.z;\n      if ( (Pcdt - P1).transpose() * D * (Pcdt - P1) < maxDistInlier)\n      {\n        inlierIndex.push_back(candidateIndex);\n      }\n    }\n    inliersList.push_back(inlierIndex);\n  }\n\n  std::size_t maxInliers = 0;\n  int indexMaxInliers = -1;\n  for (unsigned int k = 0; k < inliersList.size(); ++k)\n  {\n    if (inliersList[k].size() > maxInliers)\n    {\n      maxInliers = inliersList[k].size();\n      indexMaxInliers = k;\n    }\n  }\n\n  // fill\n  for (unsigned int k = 0; k < inliersList[indexMaxInliers].size(); ++k)\n  {\n    nearestValid.push_back(nearestIndex[inliersList[indexMaxInliers][k]]);\n    nearestValidDist.push_back(nearestDist[inliersList[indexMaxInliers][k]]);\n  }\n\n  return;\n}\n\n//-----------------------------------------------------------------------------\nvoid Slam::ComputeEgoMotion()\n{\n  // Initialize the IsKeypointUsed vectors\n  this->EdgePointRejectionEgoMotion.clear(); this->EdgePointRejectionEgoMotion.resize(this->CurrentEdgesPoints->size());\n  this->PlanarPointRejectionEgoMotion.clear(); this->PlanarPointRejectionEgoMotion.resize(this->CurrentPlanarsPoints->size());\n  // Check that there is enought points to compute the EgoMotion\n  if ((this->CurrentEdgesPoints->size() == 0 || this->PreviousEdgesPoints->size() == 0) &&\n      (this->CurrentPlanarsPoints->size() == 0 || this->PreviousPlanarsPoints->size() == 0))\n  {\n    this->EgoMotionEdgesPointsUsed = 0;\n    this->EgoMotionPlanesPointsUsed = 0;\n    std::cout << \"Not enought keypoints, EgoMotion skipped for this frame\" << std::endl;\n    return;\n  }\n\n  // reset the relative transform\n  this->Trelative = Eigen::Matrix<double, 6, 1>::Zero();\n  this->MotionParametersEgoMotion = Eigen::VectorXd::Zero(12, 1);\n\n  // kd-tree to process fast nearest neighbor\n  // among the keypoints of the previous pointcloud\n  KDTreePCLAdaptor kdtreePreviousEdges(this->PreviousEdgesPoints);\n  KDTreePCLAdaptor kdtreePreviousPlanes(this->PreviousPlanarsPoints);\n\n  std::cout << \"========== Ego-Motion ==========\" << std::endl;\n  std::cout << \"previous edges: \" << this->PreviousEdgesPoints->size() << \" current edges: \" << this->CurrentEdgesPoints->size() << std::endl;\n  std::cout << \"previous planes: \" << this->PreviousPlanarsPoints->size() << \" current planes: \" << this->CurrentPlanarsPoints->size() << std::endl;\n\n  unsigned int usedEdges = 0;\n  unsigned int usedPlanes = 0;\n  Point currentPoint;\n\n  unsigned int toReserve =   this->CurrentEdgesPoints->size()\n                           + this->CurrentPlanarsPoints->size();\n  this->Xvalues.reserve(toReserve);\n  this->Avalues.resize(toReserve);\n  this->Pvalues.resize(toReserve);\n  this->TimeValues.resize(toReserve);\n  this->residualCoefficient.resize(toReserve);\n\n\n\n  // ICP - Levenberg-Marquardt loop:\n  // At each step of this loop an ICP matching is performed\n  // Once the keypoints matched, we estimate the the 6-DOF\n  // parameters by minimizing a non-linear least square cost\n  // function using a Levenberg-Marquardt algorithm\n  for (unsigned int icpCount = 0; icpCount < this->EgoMotionICPMaxIter; ++icpCount)\n  {\n    // Rotation and translation at this step\n    Eigen::Matrix3d R = GetRotationMatrix(this->Trelative);\n    Eigen::Vector3d T(this->Trelative(3), this->Trelative(4), this->Trelative(5));\n\n    // clear all keypoints matching data\n    this->ResetDistanceParameters();\n\n    // Init the undistortion interpolator\n    if (this->Undistortion)\n    {\n      this->CreateWithinFrameTrajectory(this->WithinFrameTrajectory, WithinFrameTrajMode::EgoMotionTraj);\n    }\n\n    // loop over edges if there is engought previous edge keypoints\n    if (this->PreviousEdgesPoints->size() > this->EgoMotionLineDistanceNbrNeighbors)\n    {\n      for (unsigned int edgeIndex = 0; edgeIndex < this->CurrentEdgesPoints->size(); ++edgeIndex)\n      {\n        // Find the closest correspondence edge line of the current edge point\n        // Compute the parameters of the point - line distance\n        // i.e A = (I - n*n.t)^2 with n being the director vector\n        // and P a point of the line\n        currentPoint = this->CurrentEdgesPoints->points[edgeIndex];\n        int rejectionIndex = this->ComputeLineDistanceParameters(kdtreePreviousEdges, R, T, currentPoint, MatchingMode::EgoMotion);\n        this->EdgePointRejectionEgoMotion[edgeIndex] = rejectionIndex;\n        this->MatchRejectionHistogramLine[rejectionIndex] += 1;\n      }\n    }\n\n    // loop over planars if there is enought previous planar keypoints\n    if (this->PreviousPlanarsPoints->size() > this->EgoMotionPlaneDistanceNbrNeighbors)\n    {\n      for (unsigned int planarIndex = 0; planarIndex < this->CurrentPlanarsPoints->size(); ++planarIndex)\n      {\n        // Find the closest correspondence plane of the current planar point\n        // Compute the parameters of the point - plane distance\n        // i.e A = n * n.t with n being a normal of the plane\n        // and is a point of the plane\n        currentPoint = this->CurrentPlanarsPoints->points[planarIndex];\n        int rejectionIndex = this->ComputePlaneDistanceParameters(kdtreePreviousPlanes, R, T, currentPoint, MatchingMode::EgoMotion);\n        this->PlanarPointRejectionEgoMotion[planarIndex] = rejectionIndex;\n        this->MatchRejectionHistogramPlane[rejectionIndex] += 1;\n      }\n    }\n\n    usedEdges = this->MatchRejectionHistogramLine[6];\n    usedPlanes = this->MatchRejectionHistogramPlane[6];\n    // Skip this frame if there is too few geometric\n    // keypoints matched\n    if ((usedPlanes + usedEdges) < 20)\n    {\n      std::cout << \"Too few geometric features, frame skipped\" << std::endl;\n      break;\n    }\n\n    double lossScale = this->EgoMotionInitLossScale + static_cast<double>(icpCount) * (this->EgoMotionFinalLossScale - this->EgoMotionInitLossScale) / (1.0 * this->EgoMotionICPMaxIter);\n\n    // We want to estimate our 6-DOF parameters using a non\n    // linear least square minimization. The non linear part\n    // comes from the Euler Angle parametrization of the rotation\n    // endomorphism of SO(3). To minimize it, we use CERES to perform\n    // the Levenberg-Marquardt algorithm.\n    ceres::Problem problem;\n    for (unsigned int k = 0; k < Xvalues.size(); ++k)\n    {\n      if (this->Undistortion)\n      {\n        ceres::CostFunction* cost_function = new ceres::AutoDiffCostFunction<CostFunctions::MahalanobisDistanceInterpolatedMotionResidual, 1, 12>(\n                                             new CostFunctions::MahalanobisDistanceInterpolatedMotionResidual(\n                                                this->Avalues[k], this->Pvalues[k], this->Xvalues[k],\n                                                this->TimeValues[k], this->residualCoefficient[k]));\n        problem.AddResidualBlock(cost_function, new ceres::ScaledLoss(new ceres::ArctanLoss(lossScale), this->residualCoefficient[k],\n                                                                      ceres::TAKE_OWNERSHIP), this->MotionParametersEgoMotion.data());\n      }\n      else\n      {\n        ceres::CostFunction* cost_function = new ceres::AutoDiffCostFunction<CostFunctions::MahalanobisDistanceAffineIsometryResidual, 1, 6>(\n                                             new CostFunctions::MahalanobisDistanceAffineIsometryResidual(this->Avalues[k], this->Pvalues[k],\n                                                                                                          this->Xvalues[k], this->residualCoefficient[k]));\n        problem.AddResidualBlock(cost_function, new ceres::ScaledLoss(new ceres::ArctanLoss(lossScale), this->residualCoefficient[k], ceres::TAKE_OWNERSHIP), this->Trelative.data());\n      }\n    }\n\n    ceres::Solver::Options options;\n    options.max_num_iterations = this->EgoMotionLMMaxIter;\n    options.linear_solver_type = ceres::DENSE_QR;\n    options.minimizer_progress_to_stdout = false;\n\n    ceres::Solver::Summary summary;\n    ceres::Solve(options, &problem, &summary);\n    std::cout << summary.BriefReport() << std::endl;\n\n    // If no L-M iteration has been made since the\n    // last ICP matching it means we reached a local\n    // minimum for the ICP-LM algorithm\n    if (summary.num_successful_steps == 1)\n    {\n      break;\n    }\n  }\n\n  this->EgoMotionEdgesPointsUsed = usedEdges;\n  this->EgoMotionPlanesPointsUsed  = usedPlanes;\n  std::cout << \"used keypoints : \" << this->Xvalues.size() << std::endl;\n  std::cout << \"edges : \" << usedEdges << \" planes : \" << usedPlanes << std::endl;\n\n  // Integrate the relative motion\n  // to the world transformation\n  this->UpdateTworldUsingTrelative();\n}\n\n//-----------------------------------------------------------------------------\nvoid Slam::Mapping()\n{\n  // Check that there is enought key-points to compute the Mapping\n  if (this->CurrentEdgesPoints->size() == 0 && this->CurrentPlanarsPoints->size() == 0)\n  {\n    this->MappingVarianceError = 10;\n    this->MappingEdgesPointsUsed = 0;\n    this->MappingPlanesPointsUsed = 0;\n    this->MappingBlobsPointsUsed = 0;\n    // update maps\n    this->UpdateMapsUsingTworld();\n    std::cout << \"Not enought keypoints, Mapping skipped for this frame\" << std::endl;\n    return;\n  }\n    this->EdgePointRejectionMapping.clear(); this->EdgePointRejectionMapping.resize(this->CurrentEdgesPoints->size());\n    this->PlanarPointRejectionMapping.clear(); this->PlanarPointRejectionMapping.resize(this->CurrentPlanarsPoints->size());\n\n  // Set the FarestPoint to reduce the map to the minimum size\n  this->SetLidarMaximunRange(this->KeyPointsExtractor->GetFarestKeypointDist());\n\n  // Update motion model parameters\n  if (this->Undistortion)\n  {\n    std::copy(this->MotionParametersMapping.data(),\n              this->MotionParametersMapping.data() + 5,\n              this->MotionParametersMapping.data() + 6);\n  }\n\n  // get keypoints from the map\n  pcl::PointCloud<Slam::Point>::Ptr subEdgesPointsLocalMap = this->EdgesPointsLocalMap->Get(this->Tworld);\n  pcl::PointCloud<Slam::Point>::Ptr subPlanarPointsLocalMap = this->PlanarPointsLocalMap->Get(this->Tworld);\n\n  // contruct kd-tree for fast closest points search\n  KDTreePCLAdaptor kdtreeEdges(subEdgesPointsLocalMap);\n  KDTreePCLAdaptor kdtreePlanes(subPlanarPointsLocalMap);\n  pcl::KdTreeFLANN<Slam::Point>::Ptr kdtreeBlobs;\n\n  std::cout << \"========== Mapping ==========\" << std::endl;\n  std::cout << \"Edges extracted from map: \" << subEdgesPointsLocalMap->points.size()\n            << \"Planes extracted from map: \" << subPlanarPointsLocalMap->points.size() << std::endl;\n\n  if (!this->FastSlam)\n  {\n    pcl::PointCloud<Slam::Point>::Ptr subBlobPointsLocalMap = this->BlobsPointsLocalMap->Get(this->Tworld);\n    kdtreeBlobs.reset(new pcl::KdTreeFLANN<Slam::Point>());\n    kdtreeBlobs->setInputCloud(subBlobPointsLocalMap);\n    std::cout << \"blobs map: \" << subBlobPointsLocalMap->points.size() << std::endl;\n  }\n\n  // Information about matches\n  unsigned int usedEdges = 0;\n  unsigned int usedPlanes = 0;\n  unsigned int usedBlobs = 0;\n\n  Point currentPoint;\n\n  unsigned int toReserve =   this->CurrentEdgesPoints->size()\n                           + this->CurrentPlanarsPoints->size()\n                           + this->CurrentBlobsPoints->size();\n  this->Xvalues.reserve(toReserve);\n  this->Avalues.resize(toReserve);\n  this->Pvalues.resize(toReserve);\n  this->TimeValues.resize(toReserve);\n  this->residualCoefficient.resize(toReserve);\n\n  // ICP - Levenberg-Marquardt loop:\n  // At each step of this loop an ICP matching is performed\n  // Once the keypoints matched, we estimate the the 6-DOF\n  // parameters by minimizing a non-linear least square cost\n  // function using a Levenberg-Marquardt algorithm\n  for (unsigned int icpCount = 0; icpCount < this->MappingICPMaxIter; ++icpCount)\n  {\n    // clear all keypoints matching data\n    this->ResetDistanceParameters();\n\n    // Init the undistortion interpolator\n    if (this->Undistortion)\n    {\n      this->CreateWithinFrameTrajectory(this->WithinFrameTrajectory, WithinFrameTrajMode::MappingTraj);\n    }\n\n    // Rotation and position at this step\n    Eigen::Matrix3d R = GetRotationMatrix(this->Tworld);\n    Eigen::Vector3d T(this->Tworld(3), this->Tworld(4), this->Tworld(5));\n\n    // loop over edges\n    if (this->CurrentEdgesPoints->size() > 0 && subEdgesPointsLocalMap->points.size() > 10)\n    {\n      for (unsigned int edgeIndex = 0; edgeIndex < this->CurrentEdgesPoints->size(); ++edgeIndex)\n      {\n        // Find the closest correspondence edge line of the current edge point\n        currentPoint = this->CurrentEdgesPoints->points[edgeIndex];\n        int rejectionIndex = this->ComputeLineDistanceParameters(kdtreeEdges, R, T, currentPoint, MatchingMode::Mapping);\n        this->EdgePointRejectionMapping[edgeIndex] = rejectionIndex;\n        this->MatchRejectionHistogramLine[rejectionIndex] += 1;\n        usedEdges = this->Xvalues.size();\n      }\n    }\n    // loop over surfaces\n    if (this->CurrentPlanarsPoints->size() > 0 && subPlanarPointsLocalMap->size() > 10)\n    {\n      for (unsigned int planarIndex = 0; planarIndex < this->CurrentPlanarsPoints->size(); ++planarIndex)\n      {\n        // Find the closest correspondence plane of the current planar point\n        currentPoint = this->CurrentPlanarsPoints->points[planarIndex];\n        int rejectionIndex = this->ComputePlaneDistanceParameters(kdtreePlanes, R, T, currentPoint, MatchingMode::Mapping);\n        this->PlanarPointRejectionMapping[planarIndex] = rejectionIndex;\n        this->MatchRejectionHistogramPlane[rejectionIndex] += 1;\n        usedPlanes = this->Xvalues.size() - usedEdges;\n      }\n    }\n\n    if (!this->FastSlam && this->NbrFrameProcessed > 10)\n    {\n      // loop over blobs\n      for (unsigned int blobIndex = 0; blobIndex < this->CurrentBlobsPoints->size(); ++blobIndex)\n      {\n        // Find the closest correspondence plane of the current planar point\n        currentPoint = this->CurrentBlobsPoints->points[blobIndex];\n        this->ComputeBlobsDistanceParameters(kdtreeBlobs, R, T, currentPoint, MatchingMode::Mapping);\n        usedBlobs = this->Xvalues.size() - usedPlanes - usedEdges;\n      }\n    }\n\n    // Skip this frame if there is too few geometric keypoints matched\n    if ((usedPlanes + usedEdges + usedBlobs) < 20)\n    {\n      std::cout << \"Too few geometric features, loop breaked\" << std::endl;\n      std::cout << \"planes: \" << usedPlanes << \" edges: \" << usedEdges << \" Blobs: \" << usedBlobs << std::endl;\n      break;\n    }\n\n    double lossScale = this->MappingInitLossScale + static_cast<double>(icpCount) * (this->MappingFinalLossScale - this->MappingInitLossScale) / (1.0 * this->MappingICPMaxIter);\n\n    // We want to estimate our 6-DOF parameters using a non\n    // linear least square minimization. The non linear part\n    // comes from the Euler Angle parametrization of the rotation\n    // endomorphism SO(3). To minimize it we use CERES to perform\n    // the Levenberg-Marquardt algorithm.\n    ceres::Problem problem;\n    for (unsigned int k = 0; k < Xvalues.size(); ++k)\n    {\n      if (this->Undistortion)\n      {\n        ceres::CostFunction* cost_function = new ceres::AutoDiffCostFunction<CostFunctions::MahalanobisDistanceInterpolatedMotionResidual, 1, 12>(\n                                                     new CostFunctions::MahalanobisDistanceInterpolatedMotionResidual(\n                                                     this->Avalues[k], this->Pvalues[k], this->Xvalues[k],\n                                                     this->TimeValues[k], this->residualCoefficient[k]));\n        problem.AddResidualBlock(cost_function, new ceres::ScaledLoss(new ceres::ArctanLoss(lossScale), this->residualCoefficient[k],\n                                                                      ceres::TAKE_OWNERSHIP), this->MotionParametersMapping.data());\n      }\n      else\n      {\n        ceres::CostFunction* cost_function = new ceres::AutoDiffCostFunction<CostFunctions::MahalanobisDistanceAffineIsometryResidual, 1, 6>(\n                                             new CostFunctions::MahalanobisDistanceAffineIsometryResidual(this->Avalues[k], this->Pvalues[k],\n                                                                                                          this->Xvalues[k], this->residualCoefficient[k]));\n        problem.AddResidualBlock(cost_function, new ceres::ScaledLoss(new ceres::ArctanLoss(lossScale), this->residualCoefficient[k], ceres::TAKE_OWNERSHIP), this->Tworld.data());\n      }\n    }\n\n    ceres::Solver::Options options;\n    options.max_num_iterations = this->MappingLMMaxIter;\n    options.linear_solver_type = ceres::DENSE_QR;\n    options.minimizer_progress_to_stdout = false;\n\n    ceres::Solver::Summary summary;\n    ceres::Solve(options, &problem, &summary);\n    std::cout << summary.BriefReport() << std::endl;\n\n    // If no L-M iteration has been made since the\n    // last ICP matching it means we reached a local\n    // minimum for the ICP-LM algorithm\n    if (((summary.num_successful_steps == 1) ||\n        (icpCount == (this->MappingICPMaxIter - 1))) &&\n        !this->Undistortion)\n    {\n      // Now evaluate the quality of the parameters\n      // estimated using an approximate computation\n      // of the variance covariance matrix\n      // Covariance computation options\n      ceres::Covariance::Options covOptions;\n      covOptions.apply_loss_function = true;\n      covOptions.algorithm_type = ceres::CovarianceAlgorithmType::DENSE_SVD;\n\n      // Computation of the variance-covariance matrix\n      ceres::Covariance covariance(covOptions);\n      std::vector<std::pair<const double*, const double* > > covariance_blocks;\n      covariance_blocks.push_back(std::make_pair(this->Tworld.data(), this->Tworld.data()));\n      covariance.Compute(covariance_blocks, &problem);\n      double covarianceMat[6 * 6];\n      covariance.GetCovarianceBlock(this->Tworld.data(), this->Tworld.data(), covarianceMat);\n      for (int i = 0; i < 6; ++i)\n        for (int j = 0; j < 6; ++j)\n          this->TworldCovariance(i, j) = covarianceMat[i + 6 * j];\n      break;\n    }\n  }\n\n  Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> eig(this->TworldCovariance);\n  Eigen::MatrixXd D = eig.eigenvalues();\n\n  this->MappingVarianceError = D(5);\n  this->MappingEdgesPointsUsed = usedEdges;\n  this->MappingPlanesPointsUsed = usedPlanes;\n  this->MappingBlobsPointsUsed = usedBlobs;\n\n  std::cout << \"Matches used: Total: \" << this->Xvalues.size()\n            << \" edges: \" << usedEdges << \" planes: \" << usedPlanes << \" blobs: \" << usedBlobs << std::endl;\n\n  std::cout << \"Covariance Eigen values: \" << D.transpose() << std::endl;\n  std::cout << \"Maximum variance eigen vector: \" << eig.eigenvectors().col(5).transpose() << std::endl;\n  std::cout << \"Maximum variance: \" << D(5) << std::endl;\n\n  if (this->Undistortion)\n  {\n    for (int i = 0; i < 6; ++i)\n    {\n      this->Tworld(i) = this->MotionParametersMapping(i + 6);\n    }\n  }\n\n  // Add the current computed transform to the list\n  this->TworldList.push_back(this->Tworld);\n\n  // Update maps\n  this->UpdateMapsUsingTworld();\n\n  // Transform the current keypoints\n  // in the sensor reference frame\n  // corresponding to the end of the\n  // frame\n  if (this->Undistortion)\n  {\n    this->UpdateCurrentKeypointsUsingTworld();\n  }\n  // Compute the undistortion interpolator before replacing previousTworld\n  // this interpolator will be used to output the mapped current frame\n  this->CreateWithinFrameTrajectory(this->WithinFrameTrajectory, WithinFrameTrajMode::MappingTraj);\n\n  // Update the PreviousTworld data\n  this->PreviousTworld = this->Tworld;\n}\n\n//-----------------------------------------------------------------------------\nvoid Slam::UpdateCurrentKeypointsUsingTworld()\n{\n  // Create the undistortion interpolator\n\n  // Now transform the keypoints\n  this->ExpressPointCloudInOtherReferencial(this->CurrentEdgesPoints);\n  this->ExpressPointCloudInOtherReferencial(this->CurrentPlanarsPoints);\n  this->ExpressPointCloudInOtherReferencial(this->CurrentBlobsPoints);\n}\n\n//-----------------------------------------------------------------------------\nvoid Slam::UpdateMapsUsingTworld()\n{\n  // Init the mapping interpolator\n  if (this->Undistortion)\n  {\n    this->CreateWithinFrameTrajectory(this->WithinFrameTrajectory, WithinFrameTrajMode::MappingTraj);\n  }\n\n  // it would nice to add the point frome the frame directly to the map\n  auto updateMap = [this] (std::shared_ptr<RollingGrid> map, pcl::PointCloud<Slam::Point>::Ptr frame) {\n    pcl::PointCloud<Slam::Point>::Ptr temporaryMap(new pcl::PointCloud<Slam::Point>());\n    for (size_t i = 0; i < frame->size(); ++i)\n    {\n      temporaryMap->push_back(frame->at(i));\n      this->TransformToWorld(temporaryMap->at(i));\n    }\n    map->Roll(this->Tworld);\n    map->Add(temporaryMap);\n  };\n\n  updateMap(this->EdgesPointsLocalMap, this->CurrentEdgesPoints);\n  updateMap(this->PlanarPointsLocalMap, this->CurrentPlanarsPoints);\n  if (!this->FastSlam)\n  {\n    updateMap(this->BlobsPointsLocalMap, this->CurrentBlobsPoints);\n  }\n\n}\n\n//-----------------------------------------------------------------------------\nvoid Slam::CreateWithinFrameTrajectory(SampledSensorPath& path, WithinFrameTrajMode mode)\n{\n  Eigen::VectorXd motionParameters;\n  if (mode == WithinFrameTrajMode::EgoMotionTraj)\n  {\n    motionParameters = this->MotionParametersEgoMotion;\n  }\n  else\n  {\n    motionParameters = this->MotionParametersMapping;\n  }\n\n  // Position and orientation of the sensor at time t0\n  Eigen::Vector3d angles0(motionParameters(0), motionParameters(1), motionParameters(2));\n  Eigen::Matrix3d R0 = RollPitchYawToMatrix(angles0);\n  Eigen::Vector3d T0(motionParameters(3), motionParameters(4), motionParameters(5));\n  // Position and orientation of the sensor at time t1\n  Eigen::Vector3d angles1(motionParameters(6), motionParameters(7), motionParameters(8));\n  Eigen::Matrix3d R1 = RollPitchYawToMatrix(angles1);\n  Eigen::Vector3d T1(motionParameters(9), motionParameters(10), motionParameters(11));\n\n  if (mode == WithinFrameTrajMode::UndistortionTraj)\n  {\n    // Relative motion between t0 and t1\n    Eigen::Matrix3d dR = R1.transpose() * R0;\n    Eigen::Vector3d dT = R1.transpose() * (T0 - T1);\n\n    R0 = dR;\n    T0 = dT;\n    R1 = Eigen::Matrix3d::Identity();\n    T1 = Eigen::Vector3d::Zero();\n  }\n\n  path.Samples.resize(2);\n  // Add orientation / position of the sensor at the beginning of the frame\n  this->WithinFrameTrajectory.Samples[0].R = R0;\n  this->WithinFrameTrajectory.Samples[0].T = T0;\n  this->WithinFrameTrajectory.Samples[0].time = 0.0;\n  // Add orientation / position of the sensor at the end of the frame\n  this->WithinFrameTrajectory.Samples[1].R = R1;\n  this->WithinFrameTrajectory.Samples[1].T = T1;\n  this->WithinFrameTrajectory.Samples[1].time = 1.0;\n}\n\n//-----------------------------------------------------------------------------\nvoid Slam::ExpressPointInOtherReferencial(Point& p)\n{\n  // interpolate the transform\n  AffineIsometry iso = this->WithinFrameTrajectory(p.intensity);\n  Eigen::Vector3d X(p.x, p.y, p.z);\n  Eigen::Vector3d Y = iso.R * X + iso.T;\n  p.x = Y(0); p.y = Y(1); p.z = Y(2);\n}\n\n//-----------------------------------------------------------------------------\nvoid Slam::ExpressPointCloudInOtherReferencial(pcl::PointCloud<Point>::Ptr pointcloud)\n{\n  for (unsigned int k = 0; k < pointcloud->size(); ++k)\n  {\n    ExpressPointInOtherReferencial(pointcloud->points[k]);\n  }\n}\n\n//-----------------------------------------------------------------------------\nvoid Slam::ResetDistanceParameters()\n{\n  this->Xvalues.resize(0);\n  this->Avalues.resize(0);\n  this->Pvalues.resize(0);\n  this->TimeValues.resize(0);\n  this->residualCoefficient.resize(0);\n  this->MatchRejectionHistogramLine.clear();\n  this->MatchRejectionHistogramLine.resize(this->NrejectionCauses, 0);\n  this->MatchRejectionHistogramPlane.clear();\n  this->MatchRejectionHistogramPlane.resize(this->NrejectionCauses, 0);\n  this->MatchRejectionHistogramBlob.clear();\n  this->MatchRejectionHistogramBlob.resize(this->NrejectionCauses, 0);\n}\n\n//-----------------------------------------------------------------------------\nvoid Slam::UpdateTworldUsingTrelative()\n{\n  if (this->Undistortion)\n  {\n    // Position and orientation of the sensor at time t0\n    // according to the reference frame attached to the\n    // sensor during the previous frame\n    Eigen::Vector3d angles0(this->MotionParametersEgoMotion(0), this->MotionParametersEgoMotion(1), this->MotionParametersEgoMotion(2));\n    Eigen::Matrix3d dR0 = RollPitchYawToMatrix(angles0);\n    Eigen::Vector3d dT0(this->MotionParametersEgoMotion(3), this->MotionParametersEgoMotion(4), this->MotionParametersEgoMotion(5));\n    // Position and orientation of the sensor at time t1\n    // according to the reference frame attached to the\n    // sensor during the previous frame\n    Eigen::Vector3d angles1(this->MotionParametersEgoMotion(6), this->MotionParametersEgoMotion(7), this->MotionParametersEgoMotion(8));\n    Eigen::Matrix3d dR1 = RollPitchYawToMatrix(angles1);\n    Eigen::Vector3d dT1(this->MotionParametersEgoMotion(9), this->MotionParametersEgoMotion(10), this->MotionParametersEgoMotion(11));\n    // Position and orientation of the sensor during previous\n    // frame according to the world reference frame\n    Eigen::Vector3d angles2(this->MotionParametersMapping(6), this->MotionParametersMapping(7), this->MotionParametersMapping(8));\n    Eigen::Matrix3d Rw = RollPitchYawToMatrix(angles2);\n    Eigen::Vector3d Tw(this->MotionParametersMapping(9), this->MotionParametersMapping(10), this->MotionParametersMapping(11));\n\n    // estimation of the sensor position and orientation\n    // at the time t0 according to the world rederence frame\n    Eigen::Matrix3d R0 = Rw * dR0;\n    Eigen::Vector3d T0 = Rw * dT0 + Tw;\n    // estimation of the sensor position and orientation\n    // at the time t1 according to the world rederence frame\n    Eigen::Matrix3d R1 = Rw * dR1;\n    Eigen::Vector3d T1 = Rw * dT1 + Tw;\n\n    // Next estimation of Tworld using\n    // the odometry result. This estimation\n    // will be used to undistorded the frame\n    // if required and to initialize the\n    this->MotionParametersMapping(0) = std::atan2(R0(2, 1), R0(2, 2));\n    this->MotionParametersMapping(1) = -std::asin(R0(2, 0));\n    this->MotionParametersMapping(2) = std::atan2(R0(1, 0), R0(0, 0));\n    this->MotionParametersMapping(3) = T0(0);\n    this->MotionParametersMapping(4) = T0(1);\n    this->MotionParametersMapping(5) = T0(2);\n\n    this->MotionParametersMapping(6) = std::atan2(R1(2, 1), R1(2, 2));\n    this->MotionParametersMapping(7) = -std::asin(R1(2, 0));\n    this->MotionParametersMapping(8) = std::atan2(R1(1, 0), R1(0, 0));\n    this->MotionParametersMapping(9) = T1(0);\n    this->MotionParametersMapping(10) = T1(1);\n    this->MotionParametersMapping(11) = T1(2);\n  }\n  else\n  {\n    // Relative orientation and position estimated\n    // according to the last sensor pose reference frame\n    Eigen::Matrix3d Rr, Rw;\n    Rr = GetRotationMatrix(this->Trelative);\n    Eigen::Vector3d Tr(this->Trelative(3), this->Trelative(4), this->Trelative(5));\n    // Orientation and position of the sensor at its last pose\n    Rw = GetRotationMatrix(this->Tworld);\n    Eigen::Vector3d Tw(this->Tworld(3), this->Tworld(4), this->Tworld(5));\n\n    // The new pos of the sensor in the world\n    // referential is the previous one composed\n    // with the relative motion estimated at the\n    // odometry step\n    Eigen::Matrix3d newRw = Rw * Rr;\n    Eigen::Vector3d newTw = Rw * Tr + Tw;\n\n    // Next estimation of Tworld using\n    // the odometry result. This estimation\n    // will be used to undistorded the frame\n    // if required and to initialize the\n    this->Tworld(0) = std::atan2(newRw(2, 1), newRw(2, 2));;\n    this->Tworld(1) = -std::asin(newRw(2, 0));\n    this->Tworld(2) = std::atan2(newRw(1, 0), newRw(0, 0));\n    this->Tworld(3) = newTw(0);\n    this->Tworld(4) = newTw(1);\n    this->Tworld(5) = newTw(2);\n  }\n}\n\n//-----------------------------------------------------------------------------\nvoid Slam::SetVoxelGridLeafSizeEdges(double size)\n{\n  this->EdgesPointsLocalMap->SetLeafSize(size);\n}\n\n//-----------------------------------------------------------------------------\nvoid Slam::SetVoxelGridLeafSizePlanes(double size)\n{\n  this->PlanarPointsLocalMap->SetLeafSize(size);\n}\n\n//-----------------------------------------------------------------------------\nvoid Slam::SetVoxelGridLeafSizeBlobs(double size)\n{\n  this->BlobsPointsLocalMap->SetLeafSize(size);\n}\n\n//-----------------------------------------------------------------------------\nvoid Slam::SetVoxelGridSize(unsigned int size)\n{\n  this->EdgesPointsLocalMap->SetSize(size);\n  this->PlanarPointsLocalMap->SetSize(size);\n  this->BlobsPointsLocalMap->SetSize(size);\n}\n\n//-----------------------------------------------------------------------------\nvoid Slam::SetVoxelGridResolution(double resolution)\n{\n  this->EdgesPointsLocalMap->SetResolution(resolution);\n  this->PlanarPointsLocalMap->SetResolution(resolution);\n  this->BlobsPointsLocalMap->SetResolution(resolution);\n}\n\n//-----------------------------------------------------------------------------\nvoid Slam::SetLidarMaximunRange(const double maxRange)\n{\n  this->EdgesPointsLocalMap->SetPointCoudMaxRange(maxRange);\n  this->PlanarPointsLocalMap->SetPointCoudMaxRange(maxRange);\n  this->BlobsPointsLocalMap->SetPointCoudMaxRange(maxRange);\n}\n", "meta": {"hexsha": "09079ff61b49e226864f21ed1cb9f187cf5a8b6c", "size": 68728, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "LidarPlugin/Filter/Slam/Slam.cxx", "max_stars_repo_name": "Pandinosaurus/LidarView", "max_stars_repo_head_hexsha": "9b9b2976e9ac5dcd891a604dabbb79bd6fc6a57a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-13T11:14:18.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-13T11:14:18.000Z", "max_issues_repo_path": "LidarPlugin/Filter/Slam/Slam.cxx", "max_issues_repo_name": "yxw027/LidarView", "max_issues_repo_head_hexsha": "9267729e62886a324ba7f2e3fed50db38b24f001", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LidarPlugin/Filter/Slam/Slam.cxx", "max_forks_repo_name": "yxw027/LidarView", "max_forks_repo_head_hexsha": "9267729e62886a324ba7f2e3fed50db38b24f001", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-05-30T10:07:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-30T10:07:35.000Z", "avg_line_length": 38.1822222222, "max_line_length": 185, "alphanum_fraction": 0.6400302642, "num_tokens": 18186, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.4710476839408491}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n// Unit Test\r\n\r\n// Copyright (c) 2007-2011 Barend Gehrels, Amsterdam, the Netherlands.\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n\r\n#include <boost/geometry/geometries/geometries.hpp>\r\n#include <boost/geometry/geometries/point_xy.hpp>\r\n\r\n#include <algorithms/test_perimeter.hpp>\r\n\r\n\r\ntemplate <typename P>\r\nvoid test_all()\r\n{\r\n    // 3-4-5 triangle\r\n    //test_geometry<std::pair<P, P> >(\"LINESTRING(0 0,3 4)\", 5);\r\n\r\n    test_geometry<bg::model::ring<P> >(\r\n            \"POLYGON((0 0,0 1,1 1,1 0,0 0))\", 4);\r\n    test_geometry<bg::model::polygon<P> >(\r\n            \"POLYGON((0 0,0 1,1 0,0 0))\", 1.0 + 1.0 + sqrt(2.0));\r\n    test_geometry<bg::model::polygon<P> >(\r\n            \"POLYGON((0 0,0 4,4 4,4 0,0 0),(1 1,2 1,2 2,1 2,1 1))\", 20);\r\n}\r\n\r\ntemplate <typename P>\r\nvoid test_open()\r\n{\r\n    typedef bg::model::polygon<P, true, false> open_polygon;\r\n    test_geometry<open_polygon>(\"POLYGON((0 0,0 1,1 1,1 0))\", 4);\r\n}\r\n\r\n\r\nint test_main(int, char* [])\r\n{\r\n    //test_all<bg::model::d2::point_xy<int> >();\r\n    test_all<bg::model::d2::point_xy<float> >();\r\n    test_all<bg::model::d2::point_xy<double> >();\r\n\r\n    test_open<bg::model::d2::point_xy<double> >();\r\n\r\n#if defined(HAVE_TTMATH)\r\n    test_all<bg::model::d2::point_xy<ttmath_big> >();\r\n#endif\r\n\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "038f660fb72c56c16e76e921c4e12700a593b05e", "size": 1480, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/test/algorithms/perimeter.cpp", "max_stars_repo_name": "Ron2014/boost_1_48_0", "max_stars_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "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/geometry/test/algorithms/perimeter.cpp", "max_issues_repo_name": "Ron2014/boost_1_48_0", "max_issues_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "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/geometry/test/algorithms/perimeter.cpp", "max_forks_repo_name": "Ron2014/boost_1_48_0", "max_forks_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.9245283019, "max_line_length": 80, "alphanum_fraction": 0.6182432432, "num_tokens": 495, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6584175005616829, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.47104768314057394}}
{"text": "#pragma once\r\n\r\n#include <cstdio>\r\n\r\n#include <string_view>\r\n#include <array>\r\n#include <string>\r\n#include <algorithm>\r\n#include <type_traits>\r\n\r\n#include <boost/rational_minimal.hpp>\r\n#include <numeric>\r\n\r\nnamespace threads {\r\n  //using ratio_t = boost::rational<uint64_t>;\r\n  using Rational = boost::rational<unsigned>;\r\n\r\n  constexpr auto tpi_pitch = [](auto tpi) -> Rational {\r\n    return {127, 5 * tpi};\r\n  };\r\n  \r\n  enum class pitch_type {\r\n    mm,\r\n    tpi,\r\n  };\r\n  \r\n  struct pitch_info {\r\n    std::string_view pitch_str;\r\n    Rational value;\r\n    pitch_type type;\r\n    \r\n    std::string_view unit() const {\r\n      if (type == pitch_type::mm)\r\n        return \"mm\";\r\n      else\r\n        return \"tpi\";\r\n    }\r\n  };\r\n\r\n  struct thread {\r\n    std::string_view name;\r\n    pitch_info pitch;\r\n    bool is_custom{false};\r\n    \r\n    char * description_c_str(char *buf) const {\r\n      buf = std::copy(name.begin(), name.end(), buf);\r\n      *buf++ = ' ';\r\n      buf = std::copy(pitch.pitch_str.begin(), pitch.pitch_str.end(), buf);\r\n      auto unit = pitch.unit();\r\n      buf = std::copy(unit.begin(), unit.end(), buf);\r\n      if (is_custom) {\r\n        *buf++ = '*';\r\n      }\r\n      return buf;\r\n    }\r\n  };\r\n\r\n  namespace detail {\r\n    // some stdlib functionality is either not constexpr or uses too much space\r\n    constexpr unsigned sv_to_unsigned(std::string_view sv) {\r\n      unsigned result = 0;\r\n      for (auto i = sv.begin(); i != sv.end(); ++i) {\r\n        uint8_t digit = *i - '0';\r\n        result = result * 10 + digit;\r\n      }\r\n      return result;\r\n    }\r\n\r\n    constexpr unsigned pow10(unsigned power) {\r\n      unsigned result = 1;\r\n      for (; power > 0; --power) { result *= 10; }\r\n      return result;\r\n    }\r\n\r\n    // Convert string containing decimal into rational number with no error\r\n    // e.g. \"1.865\" -> 373/200\r\n    constexpr Rational decimal_to_rational(std::string_view decimal) {\r\n      auto i_dot = decimal.find('.');\r\n      if (i_dot == decimal.npos) {\r\n        return {sv_to_unsigned(decimal), 1};\r\n      } else {\r\n        auto fraction = decimal;\r\n        fraction.remove_prefix(i_dot + 1);\r\n        auto denom = pow10(fraction.size());\r\n        decimal.remove_suffix(decimal.size() - i_dot);\r\n        auto num = sv_to_unsigned(decimal) * denom + sv_to_unsigned(fraction);\r\n        return {num, denom};\r\n      }\r\n    }\r\n\r\n    constexpr pitch_info make_pitch_info(const char* pitch, uint16_t num, uint16_t denom, pitch_type type) {\r\n      if (type == pitch_type::mm) {\r\n        return {pitch, {denom, num}, pitch_type::mm};\r\n      } else {\r\n        return {pitch, {127 * denom, 5 * num}, pitch_type::tpi};\r\n      }\r\n    }\r\n\r\n  }\r\n\r\n  inline namespace literals {\r\n    constexpr pitch_info operator\"\" _mm(const char* pitch) {\r\n      return {pitch, detail::decimal_to_rational(pitch), pitch_type::mm};\r\n    }\r\n\r\n    constexpr pitch_info operator\"\" _tpi(const char* pitch) {\r\n      auto r = detail::decimal_to_rational(pitch);\r\n      // TPI = 1 inch/#Threads : 1 inch=25.4mm = 127 / 5 mm\r\n      return {pitch, {127 * r.denominator(), 5 * r.numerator()}, pitch_type::tpi};\r\n    }\r\n  }\r\n\r\n}", "meta": {"hexsha": "25ca90b89424841ad35ab3e69f2c87a154b804f6", "size": 3117, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "firmware/threads.hpp", "max_stars_repo_name": "akunadze/Didge", "max_stars_repo_head_hexsha": "fb4cedfbe20160a447ab9e5edf77a4584b3dc346", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "firmware/threads.hpp", "max_issues_repo_name": "akunadze/Didge", "max_issues_repo_head_hexsha": "fb4cedfbe20160a447ab9e5edf77a4584b3dc346", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "firmware/threads.hpp", "max_forks_repo_name": "akunadze/Didge", "max_forks_repo_head_hexsha": "fb4cedfbe20160a447ab9e5edf77a4584b3dc346", "max_forks_repo_licenses": ["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.5840707965, "max_line_length": 109, "alphanum_fraction": 0.5761950594, "num_tokens": 778, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834734, "lm_q2_score": 0.6584175005616829, "lm_q1q2_score": 0.4710476791456065}}
{"text": "//=======================================================================\r\n// Copyright 2001 Jeremy G. Siek, Andrew Lumsdaine, Lie-Quan Lee, \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, Indiana University,\r\n// Bloomington, IN 47405.\r\n//\r\n// Permission to modify the code and to distribute the code is\r\n// granted, provided the text of this NOTICE is retained, a notice if\r\n// the code was modified is included with the above COPYRIGHT NOTICE\r\n// and with the COPYRIGHT NOTICE in the LICENSE file, and that the\r\n// LICENSE 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#include <boost/config.hpp>\r\n#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n#include <utility>\r\n#include <boost/graph/adjacency_list.hpp>\r\n#include <boost/pending/disjoint_sets.hpp>\r\n#include <boost/graph/incremental_components.hpp>\r\n\r\nint\r\nmain(int, char *[])\r\n{\r\n  using namespace boost;\r\n  // Create a graph\r\n  typedef adjacency_list < vecS, vecS, undirectedS > Graph;\r\n  typedef graph_traits < Graph >::vertex_descriptor Vertex;\r\n  const int N = 6;\r\n  Graph G(N);\r\n  add_edge(0, 1, G);\r\n  add_edge(1, 4, G);\r\n  // create the disjoint-sets object, which requires rank and parent vertex properties\r\n  std::vector < Vertex > rank(num_vertices(G));\r\n  std::vector < Vertex > parent(num_vertices(G));\r\n  typedef graph_traits<Graph>::vertices_size_type* Rank;\r\n  typedef Vertex* Parent;\r\n  disjoint_sets < Rank, Parent > ds(&rank[0], &parent[0]);\r\n\r\n  // determine the connected components, storing the results in the disjoint-sets object\r\n  initialize_incremental_components(G, ds);\r\n  incremental_components(G, ds);\r\n\r\n  // Add a couple more edges and update the disjoint-sets\r\n  graph_traits < Graph >::edge_descriptor e;\r\n  bool flag;\r\n  tie(e, flag) = add_edge(4, 0, G);\r\n  ds.union_set(4, 0);\r\n  tie(e, flag) = add_edge(2, 5, G);\r\n  ds.union_set(2, 5);\r\n\r\n  graph_traits < Graph >::vertex_iterator iter, end;\r\n  for (tie(iter, end) = vertices(G); iter != end; ++iter)\r\n    std::cout << \"representative[\" << *iter << \"] = \" <<\r\n      ds.find_set(*iter) << std::endl;;\r\n  std::cout << std::endl;\r\n\r\n  typedef component_index < unsigned int >Components;\r\n  Components components(parent.begin(), parent.end());\r\n  for (Components::size_type i = 0; i < components.size(); ++i) {\r\n    std::cout << \"component \" << i << \" contains: \";\r\n    for (Components::value_type::iterator j = components[i].begin();\r\n         j != components[i].end(); ++j)\r\n      std::cout << *j << \" \";\r\n    std::cout << std::endl;\r\n  }\r\n\r\n  return EXIT_SUCCESS;\r\n}\r\n", "meta": {"hexsha": "e45481f0d971a2835e7061ba7437678af9026888", "size": 3169, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sdk/boost_1_30_0/libs/graph/example/incremental-components-eg.cpp", "max_stars_repo_name": "acidicMercury8/xray-1.0", "max_stars_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-01-30T12:51:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-31T08:36:49.000Z", "max_issues_repo_path": "sdk/boost_1_30_0/libs/graph/example/incremental-components-eg.cpp", "max_issues_repo_name": "acidicMercury8/xray-1.0", "max_issues_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_issues_repo_licenses": ["Linux-OpenIB"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sdk/boost_1_30_0/libs/graph/example/incremental-components-eg.cpp", "max_forks_repo_name": "acidicMercury8/xray-1.0", "max_forks_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.1234567901, "max_line_length": 89, "alphanum_fraction": 0.6525717892, "num_tokens": 753, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.471047675150639}}
{"text": "// accumulators.cpp\n//\n#include <stdint.h>\n#include <iostream>\n\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics.hpp>\n\nint main(int argc, char* argv[])\n{\n    namespace acc = boost::accumulators;\n    acc::accumulator_set<\n        int32_t,\n        acc::features<acc::tag::count, acc::tag::mean, acc::tag::variance>,\n        int\n    > as;\n    as(8, acc::weight = 1);\n    as(9, acc::weight = 1);\n    as(10, acc::weight = 4);\n    as(11, acc::weight = 1);\n    as(12, acc::weight = 1);\n    std::cout << acc::count(as) << '\\n'\n              << acc::mean(as) << '\\n'\n              << acc::variance(as) << '\\n';\n}\n", "meta": {"hexsha": "be904a34db6a13062d72200de42567828a6ea62c", "size": 642, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/accumulators.cpp", "max_stars_repo_name": "uwydoc/the-practices", "max_stars_repo_head_hexsha": "61ea1d868017ac88fddf6c0e726f0e9adde3f80e", "max_stars_repo_licenses": ["MIT"], "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/accumulators.cpp", "max_issues_repo_name": "uwydoc/the-practices", "max_issues_repo_head_hexsha": "61ea1d868017ac88fddf6c0e726f0e9adde3f80e", "max_issues_repo_licenses": ["MIT"], "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/accumulators.cpp", "max_forks_repo_name": "uwydoc/the-practices", "max_forks_repo_head_hexsha": "61ea1d868017ac88fddf6c0e726f0e9adde3f80e", "max_forks_repo_licenses": ["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.6923076923, "max_line_length": 75, "alphanum_fraction": 0.5560747664, "num_tokens": 195, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239836484143, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.4710476711556713}}
{"text": "/*\n * main.cpp\n * Created on Sun Dec 20 2020\n * Author Nikolai Flowers\n *\n * The MIT License (MIT)\n * Copyright (c) 2020 Nikolai Flowers\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of this software\n * and 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, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,\n * subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all copies or substantial\n * portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED\n * TO THE WARRANTIES OF MERCHANTABILITY, 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 LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n\n#include <sudoku_solver.h>\n#include <sudoku_utils.h>\n#include <colors.h>\n#include <chrono>\n#include <boost/program_options.hpp>\n\nnamespace po = boost::program_options;\n\nint main(int argc,char** argv) {\n\n  po::options_description desc(\"Allowed options\");\n  bool use_diag = false;\n  std::string sudoku_file;\n  int sudoku_size;\n\tdesc.add_options()\n\t\t(\"help,h\", \"usage ./main path-to-txt-file\")\n    (\"input-file,i\", po::value<std::string >(&sudoku_file), \"input sudoku txt file\")\n    (\"sudoku-size,n\", po::value<int >(&sudoku_size)->required()->default_value(3), \"input sudoku block size (2 for 4x4, 3 for 9x9, 4 for 16x16, etc\")\n    (\"sudokux,x\", po::bool_switch(&use_diag), \"sudokuX (diagonal constraints)\")\n    ;\n\n  // Named parameters\n\tpo::variables_map vm;\n\tpo::store(parse_command_line(argc,argv,desc), vm);\n\n  // Redirect positional args to input-file\n  po::positional_options_description p;\n  p.add(\"input-file\", -1);\n  po::store(po::command_line_parser(argc, argv).\n    options(desc).positional(p).run(), vm);\n\n\tpo::notify(vm);\t\n\n  if (vm.count(\"help\")) {\n    std::cout << desc << std::endl;\n    return 1;\n  }\n  if (!vm.count(\"input-file\")) {\n    std::cout << \"Please specify sudoku input txt file\" << std::endl;\n    return 1;\n  }\n\n  // Load board from file\n  board_t board;\n  int N2 = sudoku_size*sudoku_size;\n  board.resize(N2,std::vector<int>(N2,0)); \n\n  if (!load_board_from_file(sudoku_file,board)) {\n    std::cerr << \"Couldn't load board from file \" << sudoku_file.c_str() << std::endl;\n    return 1;\n  }\n\n  print_board(board);\n\n  // Setup solver class\n  SudokuSolver solver(use_diag);\n  solver.set_board(board);\n\n  using namespace std::chrono;\n  steady_clock::time_point t1 = steady_clock::now();\n  bool success = solver.solve();\n  steady_clock::time_point t2 = steady_clock::now();\n  if(!success) {\n    std::cerr << BOLD(FRED(\"Error! Puzzle not solvable.\")) << std::endl;\n  }\n  else {\n    std::cout << BOLD(FGRN(\"Puzzle solved.\")) << std::endl;\n    duration<double> time_span = duration_cast<duration<double>>(t2 - t1);\n    std::cout << \"Solve time: \" << time_span.count()*1000 << \" ms\" << std::endl;\n    std::cout << std::endl;\n    board_t solved_board = solver.get_board();\n    print_board(solved_board);\n  }\n  return 0;  \n}", "meta": {"hexsha": "e1cb1a44e7a7bb81375ff7c578c11e7f877ab221", "size": 3444, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/main.cc", "max_stars_repo_name": "nikolaif399/SudokuFAST", "max_stars_repo_head_hexsha": "2732a63da086b9d65a87035dfdfed4adc28fda56", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/main.cc", "max_issues_repo_name": "nikolaif399/SudokuFAST", "max_issues_repo_head_hexsha": "2732a63da086b9d65a87035dfdfed4adc28fda56", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/main.cc", "max_forks_repo_name": "nikolaif399/SudokuFAST", "max_forks_repo_head_hexsha": "2732a63da086b9d65a87035dfdfed4adc28fda56", "max_forks_repo_licenses": ["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.1428571429, "max_line_length": 149, "alphanum_fraction": 0.6948315912, "num_tokens": 890, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239836484144, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.47104766636042883}}
{"text": "\n#include <iostream>\n#include <string>\n#include <sstream>\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <Eigen/Dense>\n\n#include \"pointCloud.h\"\n#include \"planeCloud.h\"\n#include \"calibration.h\"\n\nint main(int argc, char **argv)\n{\n    pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ>);\n    if(argc<3){\n        std::cout<<\"This node is intend to use offline\"<<std::endl<<\"provide a logfile (produced with the dumpernode) and the output calibration file you want\"<<std::endl;\n        std::cout<<\"example:\"<<std::endl<<\"offlineCalibration <input log filename> <output calibration filename>\"<<std::endl;\n        return 0;\n    }\n    float c0,c1,c2,c3=0;\n    c0=1.0f;\n    if(argc==7){\n        c3=atof(argv[3]);\n        c2=atof(argv[4]);\n        c1=atof(argv[5]);\n        c0=atof(argv[6]);\n        std::cout<<\"polynomial coeffs: d^3*\"<<c3<<\" + d^2*\"<<c2<<\" + d*\"<<c1<<\" + \"<<c0<<std::endl;\n    }\n    std::fstream log;\n    log.open(argv[1]);\n    string topic;\n    int height;\n    int width;\n    log >> topic;\n    log >> height;\n    log >> width;\n    Matrix3f k;\n    log >> k(0,0);\n    log >> k(0,1);\n    log >> k(0,2);\n    log >> k(1,0);\n    log >> k(1,1);\n    log >> k(1,2);\n    log >> k(2,0);\n    log >> k(2,1);\n    log >> k(2,2);\n    string filename;\n    //calibrationMatrix c(480,640,8000,4,8);\n    int rows =240;\n    int cols = 320;\n    calibrationMatrix c(rows,cols,8000,2,16);\n    //calibrationMatrix c(rows,cols,8000,4,64);\n    while(!log.eof()){\n        log>>filename;\n        std::cout<< \"opening \"<<filename<<\"\\r\"<<std::flush;\n        cv::Mat data = cv::imread(filename,cv::IMREAD_ANYDEPTH);\n        pointCloud p(data,k);\n        //VOXELIZER\n        pcl::PointCloud<pcl::PointXYZ>* pcl;\n        pcl=p.pclCloud();\n        calibration::voxelize(pcl,pcl,20);\n        pointCloud p2(pcl);\n        //CENTER SQUARE CLOUD\n        pcl::PointCloud<pcl::PointXYZ>* square= new pcl::PointCloud<pcl::PointXYZ>();\n        calibration::computeCenterSquareCloud(data,k,square,cols/10,rows/10,c0,c1,c2,c3); //100 100\n        pointCloud p3(square);\n        //CENTER PLANE\n        Eigen::Vector4f centerModel;\n        calibration::computerCenterPlane(square,centerModel,40);\n        std::cout.flush();\n        planeCloud centerPlaneCloud;\n        centerPlaneCloud.model=centerModel;\n        Eigen::Vector4f center;\n        pcl::compute3DCentroid(*square,center);\n        //std::cout<<\"CENTROID DISTANCE: \"<<center[2]<<\" ( \"<<center.transpose()<<\" )\"<<std::endl;\n        centerPlaneCloud.com=center.head(3);\n        //NORMALS\n        pcl::PointCloud<pcl::Normal>* normals= new pcl::PointCloud<pcl::Normal>();\n        calibration::computeNormals(p2.pclCloud(),normals,100);\n        //REJECTION\n        Eigen::Vector3f ref;\n        std::vector<bool> valid;\n        ref<<centerModel[0],centerModel[1],centerModel[2];\n        pcl::PointCloud<pcl::PointXYZ> outFromNormalRejection;\n        pcl::PointCloud<pcl::PointXYZ>* tmpCloud =p2.pclCloud();\n        calibration::pointrejection(&ref,0.7f,tmpCloud,normals,&outFromNormalRejection,&valid);\n\n        //pointCloud outFromNormalRejectionCloud(&outFromNormalRejection);\n        //ERROR PER POINT\n        pcl::PointCloud<pcl::PointXYZ> error;\n        calibration::computeErrorPerPoint(tmpCloud,&error,center.head(3),ref,&valid);\n        //std::cout<<\"error cloud has \"<<error.size()<<\" points\"<<std::endl;\n        //std::cout<<\"voxel cloud has \"<<p2.pclCloud()->size()<<\" points\"<<std::endl;\n        pcl::PointCloud<pcl::PointXYZ>* cloudToCalibrate=p2.pclCloud();\n        //COMPUTE CALIBRATION MATRIX\n        std::cout.flush();\n        calibration::computeCalibrationMatrix(*cloudToCalibrate,error,k,&valid,c);\n        std::cout.flush();\n        //CALIBRATE POINT CLOUD\n        pcl::PointCloud<pcl::PointXYZ> fixedCloud;\n        calibration::calibratePointCloudWithMultipliers(*cloudToCalibrate,fixedCloud,c,k);\n        std::cout.flush();\n\n        error.clear();\n        valid.clear();\n        error.clear();\n        cloudToCalibrate->clear();\n        delete cloudToCalibrate;\n        tmpCloud->clear();\n        delete tmpCloud;\n        p2.cloud.clear();\n        normals->clear();\n        outFromNormalRejection.clear();\n        valid.clear();\n        delete normals;\n        delete square;\n        pcl->clear();\n        delete pcl;\n    }\n    std::cout<<std::endl<<\"saving \"<<std::endl;\n    c.dumpSensorImages();\n    c.serialize(argv[2]);\n    char nn[500];\n    std::cout<<\"saving nn\"<<std::endl;\n    sprintf(nn,\"NN_%s\",argv[2]);\n    //c.serializeNN(nn);\n    //calibrationMatrix* cc = c.downsample(2,2);\n    //cc->serialize(argv[2]);\n\n}\n", "meta": {"hexsha": "bc38d6d2fa7c1b32a02142d1c824e924dba77154", "size": 4607, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/offlineCalibration/offlineCalibration.cpp", "max_stars_repo_name": "dkoguciuk/easydepthcalib", "max_stars_repo_head_hexsha": "01fc125868eca3310e8142de7ad060f66825fe19", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/offlineCalibration/offlineCalibration.cpp", "max_issues_repo_name": "dkoguciuk/easydepthcalib", "max_issues_repo_head_hexsha": "01fc125868eca3310e8142de7ad060f66825fe19", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/offlineCalibration/offlineCalibration.cpp", "max_forks_repo_name": "dkoguciuk/easydepthcalib", "max_forks_repo_head_hexsha": "01fc125868eca3310e8142de7ad060f66825fe19", "max_forks_repo_licenses": ["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.6390977444, "max_line_length": 171, "alphanum_fraction": 0.6014760148, "num_tokens": 1243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382129861583, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.47103581043217885}}
{"text": "#include <iostream>\n#include <iomanip>\n\n#include <Eigen/Dense>\n\n#include \"LSLOpt/BFGS.hpp\"\n\n#include \"ModelSystem.hpp\"\n\n\nint main(int argc, char* argv[])\n{\n  ModelSystem modelSystem;\n\n  std::cerr << std::setprecision(16);\n\n  double max_x = 2.0;\n  double step = 0.001;\n  unsigned n = static_cast<unsigned>(max_x / step) + 1;\n\n  for (unsigned i = 0; i < n; ++i) {\n    double x = step * i;\n    double v = modelSystem.spline.eval<0>(x);\n    std::cerr << x << \";\" << v << std::endl;\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "0e64410334596c46899726add7ccef4176ebe13c", "size": 497, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/PaperExamples/Plot1d.cpp", "max_stars_repo_name": "flachsenberg/LSLOpt", "max_stars_repo_head_hexsha": "20dd15b343e117a6b129e3bdeea2ea02f5d7c829", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-03-18T02:42:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-15T14:09:06.000Z", "max_issues_repo_path": "src/PaperExamples/Plot1d.cpp", "max_issues_repo_name": "flachsenberg/LSLOpt", "max_issues_repo_head_hexsha": "20dd15b343e117a6b129e3bdeea2ea02f5d7c829", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/PaperExamples/Plot1d.cpp", "max_forks_repo_name": "flachsenberg/LSLOpt", "max_forks_repo_head_hexsha": "20dd15b343e117a6b129e3bdeea2ea02f5d7c829", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-08T12:12:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-08T12:12:51.000Z", "avg_line_length": 17.1379310345, "max_line_length": 55, "alphanum_fraction": 0.6056338028, "num_tokens": 156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.47096629066568896}}
{"text": "//          Copyright Carl Philipp Reh 2009 - 2016.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n\n#include <fcppt/math/size_type.hpp>\n#include <fcppt/math/static_size.hpp>\n#include <fcppt/math/vector/comparison.hpp>\n#include <fcppt/math/vector/object.hpp>\n#include <fcppt/math/vector/output.hpp>\n#include <fcppt/math/vector/static.hpp>\n#include <fcppt/preprocessor/disable_gcc_warning.hpp>\n#include <fcppt/preprocessor/pop_warning.hpp>\n#include <fcppt/preprocessor/push_warning.hpp>\n#include <fcppt/config/external_begin.hpp>\n#include <boost/test/unit_test.hpp>\n#include <fcppt/config/external_end.hpp>\n\n\nnamespace\n{\n\ntemplate<\n\ttypename T,\n\tfcppt::math::size_type N\n>\nclass view_storage\n{\npublic:\n\ttypedef T value_type;\n\n\ttypedef fcppt::math::size_type size_type;\n\n\ttypedef\n\tfcppt::math::static_size<\n\t\tN\n\t>\n\tstatic_size;\n\n\ttypedef value_type *pointer;\n\n\ttypedef value_type const *const_pointer;\n\n\ttypedef value_type &reference;\n\n\ttypedef value_type const &const_reference;\n\n\ttypedef pointer iterator;\n\n\ttypedef const_pointer const_iterator;\n\n\texplicit\n\tview_storage(\n\t\tpointer const _data\n\t)\n\t:\n\t\tdata_(\n\t\t\t_data\n\t\t)\n\t{\n\t}\n\n\titerator\n\tbegin()\n\t{\n\t\treturn\n\t\t\tdata_;\n\t}\n\n\tconst_iterator\n\tbegin() const\n\t{\n\t\treturn\n\t\t\tdata_;\n\t}\n\n\titerator\n\tend()\n\t{\n\t\treturn\n\t\t\tdata_\n\t\t\t+\n\t\t\tN;\n\t}\n\n\tconst_iterator\n\tend() const\n\t{\n\t\treturn\n\t\t\tdata_\n\t\t\t+\n\t\t\tN;\n\t}\nprivate:\n\tpointer data_;\n};\n\n}\n\nFCPPT_PP_PUSH_WARNING\nFCPPT_PP_DISABLE_GCC_WARNING(-Weffc++)\n\nBOOST_AUTO_TEST_CASE(\n\tmath_vector_view_storage\n)\n{\nFCPPT_PP_POP_WARNING\n\n\ttypedef\n\tview_storage<\n\t\tunsigned,\n\t\t2\n\t>\n\tunsigned_view_storage;\n\n\ttypedef\n\tfcppt::math::vector::object<\n\t\tunsigned,\n\t\t2,\n\t\tunsigned_view_storage\n\t>\n\tview_vector;\n\n\tunsigned data[] = { 1, 2 };\n\n\tview_vector const view{\n\t\tunsigned_view_storage(\n\t\t\tdata\n\t\t)\n\t};\n\n\ttypedef\n\tfcppt::math::vector::static_<\n\t\tunsigned,\n\t\t2\n\t>\n\tuivector2;\n\n\tuivector2 const vec(\n\t\tview\n\t);\n\n\tBOOST_CHECK_EQUAL(\n\t\tvec,\n\t\tview\n\t);\n}\n", "meta": {"hexsha": "f1008cfefd0ee7126cb665304323b4650680c834", "size": 2046, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/math/vector/view_storage.cpp", "max_stars_repo_name": "vinzenz/fcppt", "max_stars_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "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": "test/math/vector/view_storage.cpp", "max_issues_repo_name": "vinzenz/fcppt", "max_issues_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "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/math/vector/view_storage.cpp", "max_forks_repo_name": "vinzenz/fcppt", "max_forks_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "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": 13.7315436242, "max_line_length": 61, "alphanum_fraction": 0.7135874878, "num_tokens": 571, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.47096629066568896}}
{"text": "#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE GraphTests\n#include <boost/test/unit_test.hpp>\n#include <algorithm>\n\n#include \"graph/PBQPGraph.hpp\"\n#include \"graph/Vector.hpp\"\n#include \"graph/PBQPNode.hpp\"\n#include \"graph/PBQPEdge.hpp\"\n\n#include \"util/TestUtils.hpp\"\n\nnamespace pbqppapa {\n\nBOOST_AUTO_TEST_CASE(basicEdgeGeneration) {\n\tPBQPGraph<int> graph = PBQPGraph<int>();\n\tBOOST_CHECK_EQUAL(graph.getEdgeCount(), 0);\n\tBOOST_CHECK_EQUAL(graph.getNodeCount(), 0);\n\n\t//generate a bunch of nodes\n\tfor (int i = 1; i <= 50; i++) {\n\t\tint arr [] = {3, 2};\n\t\tVector<int> vector = Vector<int>(2,arr);\n\t\tPBQPNode<int>* node = graph.addNode(vector);\n\t\tBOOST_CHECK_EQUAL(graph.getEdgeCount(), 0);\n\t\tBOOST_CHECK_EQUAL(graph.getNodeCount(), i);\n\t\tBOOST_CHECK_EQUAL(node->getIndex(), i - 1);\n\t\tBOOST_CHECK(vector == node->getVector());\n\t\tBOOST_CHECK_EQUAL(node->getDegree(), 0);\n\t\tBOOST_CHECK_EQUAL(node->getVectorDegree(), 2);\n\t}\n\n\t//generate a bunch of edges\n\tPBQPNode<int>* node1 = *(graph.getNodeBegin());\n\tint counter = 0;\n\tfor (std::set<PBQPNode<int>*>::iterator it = graph.getNodeBegin();\n\t\t\tit != graph.getNodeEnd(); it++) {\n\t\tPBQPNode<int>* node2 = *it;\n\t\tif (node2 == node1) {\n\t\t\tcontinue;\n\t\t}\n\t\tint matArr [] = {3,2,5,8};\n\t\tMatrix<int> matrix = Matrix<int>(2, 2, matArr);\n\t\tBOOST_CHECK_EQUAL(0, node2->getDegree());\n\t\tstd::vector<PBQPNode<int>*> adjaNodes = node1->getAdjacentNodes(true);\n\t\tBOOST_CHECK(\n\t\t\t\tstd::find(adjaNodes.begin(), adjaNodes.end(), node2)\n\t\t\t\t\t\t== adjaNodes.end());\n\t\tPBQPEdge<int>* edge = graph.addEdge(node1, node2, matrix);\n\t\tBOOST_CHECK_EQUAL(graph.getEdgeCount(), counter + 1);\n\t\tBOOST_CHECK_EQUAL(graph.getNodeCount(), 50);\n\t\tBOOST_CHECK_EQUAL(counter + 1, node1->getDegree());\n\t\tBOOST_CHECK_EQUAL(1, node2->getDegree());\n\n\t\tadjaNodes = node1->getAdjacentNodes(true);\n\t\tBOOST_CHECK(\n\t\t\t\tstd::find(adjaNodes.begin(), adjaNodes.end(), node2)\n\t\t\t\t\t\t!= adjaNodes.end());\n\t\tBOOST_CHECK_EQUAL(adjaNodes.size(), counter + 1);\n\t\tadjaNodes = node1->getAdjacentNodes(false);\n\t\tBOOST_CHECK(\n\t\t\t\tstd::find(adjaNodes.begin(), adjaNodes.end(), node2)\n\t\t\t\t\t\t!= adjaNodes.end());\n\t\tBOOST_CHECK_EQUAL(adjaNodes.size(), counter + 1);\n\t\tif (counter != 0) {\n\t\t\t//exclude initial cycle\n\t\t\tadjaNodes = node2->getAdjacentNodes(true);\n\t\t\tBOOST_CHECK(\n\t\t\t\t\tstd::find(adjaNodes.begin(), adjaNodes.end(), node1)\n\t\t\t\t\t\t\t== adjaNodes.end());\n\t\t\tBOOST_CHECK_EQUAL(adjaNodes.size(), 0);\n\t\t}\n\t\tadjaNodes = node2->getAdjacentNodes(false);\n\t\tBOOST_CHECK(\n\t\t\t\tstd::find(adjaNodes.begin(), adjaNodes.end(), node1)\n\t\t\t\t\t\t!= adjaNodes.end());\n\t\tBOOST_CHECK_EQUAL(adjaNodes.size(), 1);\n\t\tconst std::vector<PBQPEdge<int>*> adjaEdge = node1->getAdjacentEdges(true);\n\t\tBOOST_CHECK(\n\t\t\t\tstd::find(adjaEdge.begin(), adjaEdge.end(), edge)\n\t\t\t\t\t\t!= adjaEdge.end());\n\t\tBOOST_CHECK_EQUAL(adjaEdge.size(), counter + 1);\n\t\tcounter++;\n\t}\n}\n\nBOOST_AUTO_TEST_CASE(advancedEdgeGeneration) {\n\tint size = 20;\n\tPBQPGraph<int>* graph = genGraph(size);\n\tBOOST_CHECK_EQUAL(graph->getEdgeCount(), size * (size - 1) / 2);\n\tBOOST_CHECK_EQUAL(graph->getNodeCount(), size);\n\tfor (std::set<PBQPNode<int>*>::iterator it = graph->getNodeBegin();\n\t\t\tit != graph->getNodeEnd(); it++) {\n\t\tPBQPNode<int>* node = *it;\n\t\tBOOST_CHECK_EQUAL(node->getDegree(), size - 1);\n\t\tBOOST_CHECK_EQUAL(node->getAdjacentNodes(false).size(), size - 1);\n\t}\n\tdelete graph;\n}\n/* TODO fix this maybe some day\nBOOST_AUTO_TEST_CASE(advancedEdgeRemoval) {\n\tint size = 20;\n\tPBQPGraph<int>* graph = genGraph(size);\n\tPBQPNode<int>* node = *(graph->getNodeBegin());\n\tint removed = 0;\n\tstd::vector<PBQPNode<int>*> adjaNodes;\n\tint ogEdgeCount = size / 2 * size + size/2;\n\tfor (PBQPEdge<int>* edge : node->getAdjacentEdges(true)) {\n\t\tPBQPNode<int>* other = edge->getOtherEnd(node);\n\t\tadjaNodes = other->getAdjacentNodes(true);\n\t\tgraph->removeEdge(edge);\n\t\tremoved++;\n\t\tBOOST_CHECK_EQUAL(graph->getEdgeCount(), ogEdgeCount - removed);\n\t\tBOOST_CHECK_EQUAL(node->getDegree(), size - removed);\n\t\tBOOST_CHECK_EQUAL(other->getDegree(), size - 1);\n\t\tadjaNodes = node->getAdjacentNodes(true);\n\t\tBOOST_CHECK(\n\t\t\t\tstd::find(adjaNodes.begin(), adjaNodes.end(), other)\n\t\t\t\t\t\t== adjaNodes.end());\n\t\tadjaNodes = other->getAdjacentNodes(true);\n\t}\n\tdelete graph;\n} */\n\n}\n", "meta": {"hexsha": "8cf31917f0ddb42cf1e8d75bedbfb3d170ac1b5a", "size": 4185, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/graph/GraphTests.cpp", "max_stars_repo_name": "sgraf812/pbqp-papa", "max_stars_repo_head_hexsha": "b5ae6fcb0842cb66956cccc4663f6fd9e6f6ae07", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-08-10T04:18:11.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-10T04:18:11.000Z", "max_issues_repo_path": "test/graph/GraphTests.cpp", "max_issues_repo_name": "sgraf812/pbqp-papa", "max_issues_repo_head_hexsha": "b5ae6fcb0842cb66956cccc4663f6fd9e6f6ae07", "max_issues_repo_licenses": ["MIT"], "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/graph/GraphTests.cpp", "max_forks_repo_name": "sgraf812/pbqp-papa", "max_forks_repo_head_hexsha": "b5ae6fcb0842cb66956cccc4663f6fd9e6f6ae07", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-03-07T10:20:50.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-07T10:20:50.000Z", "avg_line_length": 33.2142857143, "max_line_length": 77, "alphanum_fraction": 0.688172043, "num_tokens": 1205, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585903489892, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.47096628822811865}}
{"text": "// This file is part of Eigen, a lightweight C++ template library\n// for linear algebra.\n//\n// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>\n// Copyright (C) 2009 Benoit Jacob <jacob.benoit.1@gmail.com>\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 \"main.h\"\n#include <Eigen/QR>\n\ntemplate<typename MatrixType> void qr()\n{\n  Index max_size = EIGEN_TEST_MAX_SIZE;\n  Index min_size = numext::maxi(1,EIGEN_TEST_MAX_SIZE/10);\n  Index rows  = internal::random<Index>(min_size,max_size),\n        cols  = internal::random<Index>(min_size,max_size),\n        cols2 = internal::random<Index>(min_size,max_size),\n        rank  = internal::random<Index>(1, (std::min)(rows, cols)-1);\n\n  typedef typename MatrixType::Scalar Scalar;\n  typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, MatrixType::RowsAtCompileTime> MatrixQType;\n  MatrixType m1;\n  createRandomPIMatrixOfRank(rank,rows,cols,m1);\n  FullPivHouseholderQR<MatrixType> qr(m1);\n  VERIFY_IS_EQUAL(rank, qr.rank());\n  VERIFY_IS_EQUAL(cols - qr.rank(), qr.dimensionOfKernel());\n  VERIFY(!qr.isInjective());\n  VERIFY(!qr.isInvertible());\n  VERIFY(!qr.isSurjective());\n\n  MatrixType r = qr.matrixQR();\n\n  MatrixQType q = qr.matrixQ();\n  VERIFY_IS_UNITARY(q);\n\n  // FIXME need better way to construct trapezoid\n  for(int i = 0; i < rows; i++) for(int j = 0; j < cols; j++) if(i>j) r(i,j) = Scalar(0);\n\n  MatrixType c = qr.matrixQ() * r * qr.colsPermutation().inverse();\n\n  VERIFY_IS_APPROX(m1, c);\n\n  // stress the ReturnByValue mechanism\n  MatrixType tmp;\n  VERIFY_IS_APPROX(tmp.noalias() = qr.matrixQ() * r, (qr.matrixQ() * r).eval());\n\n  MatrixType m2 = MatrixType::Random(cols,cols2);\n  MatrixType m3 = m1*m2;\n  m2 = MatrixType::Random(cols,cols2);\n  m2 = qr.solve(m3);\n  VERIFY_IS_APPROX(m3, m1*m2);\n\n  {\n    Index size = rows;\n    do {\n      m1 = MatrixType::Random(size,size);\n      qr.compute(m1);\n    } while(!qr.isInvertible());\n    MatrixType m1_inv = qr.inverse();\n    m3 = m1 * MatrixType::Random(size,cols2);\n    m2 = qr.solve(m3);\n    VERIFY_IS_APPROX(m2, m1_inv*m3);\n  }\n}\n\ntemplate<typename MatrixType> void qr_invertible()\n{\n  using std::log;\n  using std::abs;\n  typedef typename NumTraits<typename MatrixType::Scalar>::Real RealScalar;\n  typedef typename MatrixType::Scalar Scalar;\n\n  Index max_size = numext::mini(50,EIGEN_TEST_MAX_SIZE);\n  Index min_size = numext::maxi(1,EIGEN_TEST_MAX_SIZE/10);\n  Index size = internal::random<Index>(min_size,max_size);\n\n  MatrixType m1(size, size), m2(size, size), m3(size, size);\n  m1 = MatrixType::Random(size,size);\n\n  if (internal::is_same<RealScalar,float>::value)\n  {\n    // let's build a matrix more stable to inverse\n    MatrixType a = MatrixType::Random(size,size*2);\n    m1 += a * a.adjoint();\n  }\n\n  FullPivHouseholderQR<MatrixType> qr(m1);\n  VERIFY(qr.isInjective());\n  VERIFY(qr.isInvertible());\n  VERIFY(qr.isSurjective());\n\n  m3 = MatrixType::Random(size,size);\n  m2 = qr.solve(m3);\n  VERIFY_IS_APPROX(m3, m1*m2);\n\n  // now construct a matrix with prescribed determinant\n  m1.setZero();\n  for(int i = 0; i < size; i++) m1(i,i) = internal::random<Scalar>();\n  RealScalar absdet = abs(m1.diagonal().prod());\n  m3 = qr.matrixQ(); // get a unitary\n  m1 = m3 * m1 * m3;\n  qr.compute(m1);\n  VERIFY_IS_APPROX(absdet, qr.absDeterminant());\n  VERIFY_IS_APPROX(log(absdet), qr.logAbsDeterminant());\n}\n\ntemplate<typename MatrixType> void qr_verify_assert()\n{\n  MatrixType tmp;\n\n  FullPivHouseholderQR<MatrixType> qr;\n  VERIFY_RAISES_ASSERT(qr.matrixQR())\n  VERIFY_RAISES_ASSERT(qr.solve(tmp))\n  VERIFY_RAISES_ASSERT(qr.matrixQ())\n  VERIFY_RAISES_ASSERT(qr.dimensionOfKernel())\n  VERIFY_RAISES_ASSERT(qr.isInjective())\n  VERIFY_RAISES_ASSERT(qr.isSurjective())\n  VERIFY_RAISES_ASSERT(qr.isInvertible())\n  VERIFY_RAISES_ASSERT(qr.inverse())\n  VERIFY_RAISES_ASSERT(qr.absDeterminant())\n  VERIFY_RAISES_ASSERT(qr.logAbsDeterminant())\n}\n\nvoid test_qr_fullpivoting()\n{\n for(int i = 0; i < 1; i++) {\n    // FIXME : very weird bug here\n//     CALL_SUBTEST(qr(Matrix2f()) );\n    CALL_SUBTEST_1( qr<MatrixXf>() );\n    CALL_SUBTEST_2( qr<MatrixXd>() );\n    CALL_SUBTEST_3( qr<MatrixXcd>() );\n  }\n\n  for(int i = 0; i < g_repeat; i++) {\n    CALL_SUBTEST_1( qr_invertible<MatrixXf>() );\n    CALL_SUBTEST_2( qr_invertible<MatrixXd>() );\n    CALL_SUBTEST_4( qr_invertible<MatrixXcf>() );\n    CALL_SUBTEST_3( qr_invertible<MatrixXcd>() );\n  }\n\n  CALL_SUBTEST_5(qr_verify_assert<Matrix3f>());\n  CALL_SUBTEST_6(qr_verify_assert<Matrix3d>());\n  CALL_SUBTEST_1(qr_verify_assert<MatrixXf>());\n  CALL_SUBTEST_2(qr_verify_assert<MatrixXd>());\n  CALL_SUBTEST_4(qr_verify_assert<MatrixXcf>());\n  CALL_SUBTEST_3(qr_verify_assert<MatrixXcd>());\n\n  // Test problem size constructors\n  CALL_SUBTEST_7(FullPivHouseholderQR<MatrixXf>(10, 20));\n  CALL_SUBTEST_7((FullPivHouseholderQR<Matrix<float,10,20> >(10,20)));\n  CALL_SUBTEST_7((FullPivHouseholderQR<Matrix<float,10,20> >(Matrix<float,10,20>::Random())));\n  CALL_SUBTEST_7((FullPivHouseholderQR<Matrix<float,20,10> >(20,10)));\n  CALL_SUBTEST_7((FullPivHouseholderQR<Matrix<float,20,10> >(Matrix<float,20,10>::Random())));\n}\n", "meta": {"hexsha": "ce706029c8125b5b7b654f22e642c03eb1ed945c", "size": 5234, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "simulator/external/habitat-sim-geodesic/habitat_sim_geodesic/csrc/eigen/test/qr_fullpivoting.cpp", "max_stars_repo_name": "eundersander/bps-nav", "max_stars_repo_head_hexsha": "a33bac7d10dc077baa596a76790b4fc829d332f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2021-03-15T01:49:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-11T23:17:14.000Z", "max_issues_repo_path": "simulator/external/habitat-sim-geodesic/habitat_sim_geodesic/csrc/eigen/test/qr_fullpivoting.cpp", "max_issues_repo_name": "eundersander/bps-nav", "max_issues_repo_head_hexsha": "a33bac7d10dc077baa596a76790b4fc829d332f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-06-27T21:41:25.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-18T21:46:40.000Z", "max_forks_repo_path": "simulator/external/habitat-sim-geodesic/habitat_sim_geodesic/csrc/eigen/test/qr_fullpivoting.cpp", "max_forks_repo_name": "eundersander/bps-nav", "max_forks_repo_head_hexsha": "a33bac7d10dc077baa596a76790b4fc829d332f7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2021-03-27T17:17:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-19T12:00:06.000Z", "avg_line_length": 33.1265822785, "max_line_length": 99, "alphanum_fraction": 0.7019487963, "num_tokens": 1594, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585669110203, "lm_q2_score": 0.6442251133170357, "lm_q1q2_score": 0.4709662881096418}}
{"text": "#include <iostream>\n#include <vector>\n#include <type_traits>\n#include <numeric>\n#include <string>\n#include <gsl/gsl>\n#include <Eigen/Dense>\nnamespace Cosan\n{\n//    MISSING VALUES, STRING, NUMERICAL\n    template<typename NumericType,\n             typename = typename std::enable_if<std::is_arithmetic<NumericType>::value,NumericType>::type\n    >\n    using vec = std::vector<NumericType> ;\n\n    template<typename NumericType,\n             typename = typename std::enable_if<std::is_arithmetic<NumericType>::value,NumericType>::type\n    >\n    using CosanMatrix = Eigen::Matrix<NumericType, Eigen::Dynamic, Eigen::Dynamic> ;\n\n\ttemplate <typename NumericType=std::string>\n\tNumericType StringToNum(std::string arg) {\n\t    if constexpr (std::is_same_v<NumericType, unsigned long>) {\n\t    \treturn std::stoul(arg);\n\t    } \n\t    else if constexpr (std::is_same_v<NumericType, unsigned long long>){\n\t    \treturn std::stoull(arg);\n\t    }\n\t    else if constexpr (std::is_same_v<NumericType, int>){\n\t    \treturn std::stoi(arg);\n\t    }\n\t    else if constexpr (std::is_same_v<NumericType, long>){\n\t    \treturn std::stol(arg);\n\t    }\n\t    else if constexpr (std::is_same_v<NumericType, long long>){\n\t    \treturn std::stoll(arg);\n\t    }\n\t    else if constexpr (std::is_same_v<NumericType, float>){\n\t    \treturn std::stof(arg);\n\t    }\n\t    else if constexpr (std::is_same_v<NumericType, double>){\n\t    \treturn std::stod(arg);\n\t    }\n\t    else{\n\t    \treturn std::stold(arg);\n\t    }\t    \n\t}\n\n    template<typename NumericType,\n             typename = typename std::enable_if<std::is_arithmetic<NumericType>::value,NumericType>::type> \n\tclass Test {\n\t\tpublic:\n\t\t\tTest()=default;\n\t\t\tTest(vec<NumericType>& inputX){\n                static_assert(std::is_arithmetic<NumericType>::value, \"NumericType must be numeric\");\t\t\t\t\n\t\t\t\tb = inputX; \n\t\t\t\ta = sumfunction(b);\n\t\t\t}\n\t\t\tTest(vec<NumericType> inputX){\n                static_assert(std::is_arithmetic<NumericType>::value, \"NumericType must be numeric\");\t\t\t\t\n\t\t\t\tb = inputX; \n\t\t\t\ta = sumfunction(b);\n\t\t\t}\t\t\t\n\t\t\tNumericType a;\n\t\t\tvec<NumericType> b;\n\t\t\tCosanMatrix<NumericType> face;\n\t\tprivate:\n\t\t\tNumericType sumfunction(vec<NumericType> &a){\n\t\t\t\tCosanMatrix<NumericType> X = Eigen::Map<const CosanMatrix<NumericType>>(a.data(), 1, a.size());\n\t\t\t\tstd::cout<<X<<std::endl;\n\t\t\t\treturn std::accumulate(a.begin(), a.end(), 0);\n\t\t\t}\n\n\t}    ;\n}\n\nint main(){\n\n\t// std::vector<bool> myVec = {0,1,1,0,0,1,0,1,0,1};\n\t// Eigen::Matrix<bool,2,5,Eigen::RowMajor> X1,X2;\n\t// for (gsl::index i =0;i<myVec.size();i++){\n\t// \tX1(i/5,i%5)=myVec[i];\n\t// }\t\n\t// std::copy(myVec.begin(),myVec.end(),X2.data());\n\t// std::cout<<X1<<std::endl;\n\t// X2.resize(2, 5);\n\t// std::cout<<X2<<std::endl;\t\n\t// std::string a = \"nan\";\n\t// std::cout<<Cosan::StringToNum<int>(a)<<std::endl;\n\tCosan::Test a = Cosan::Test<int>();\n\ta.face.resize(2,2);\n\ta.face<<1,2,3,4;\n\tstd::cout<<a.face<<std::endl;\n\tstatic_assert(std::is_same_v<decltype(a.face)::Scalar, int>);\n\tstd::cout<<typeid(decltype(a.face)::Scalar).name()<<std::endl;\n\treturn 0;\n}", "meta": {"hexsha": "79b270602ae7f1e80eb771e3467510bb115fc3e5", "size": 3023, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/templateTest.cpp", "max_stars_repo_name": "zhxinyu/cosan", "max_stars_repo_head_hexsha": "ea93704782e6c66f6bcf65362c957d719e25b074", "max_stars_repo_licenses": ["MIT"], "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/templateTest.cpp", "max_issues_repo_name": "zhxinyu/cosan", "max_issues_repo_head_hexsha": "ea93704782e6c66f6bcf65362c957d719e25b074", "max_issues_repo_licenses": ["MIT"], "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/templateTest.cpp", "max_forks_repo_name": "zhxinyu/cosan", "max_forks_repo_head_hexsha": "ea93704782e6c66f6bcf65362c957d719e25b074", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-13T05:56:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-13T05:56:38.000Z", "avg_line_length": 31.1649484536, "max_line_length": 107, "alphanum_fraction": 0.6324842871, "num_tokens": 887, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585669110202, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.4709662831160248}}
{"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 *    References\n *      Wakker, K. F. (2007), Lecture Notes astro II (Chapter 18), TU Delft course AE4-874,\n *          Delft University of technology, Delft, The Netherlands.\n *\n */\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MAIN\n\n#include <boost/test/tools/floating_point_comparison.hpp>\n#include <boost/test/unit_test.hpp>\n#include <Eigen/Dense>\n#include <cmath>\n#include <iostream>\n\n#include \"tudat/astro/basic_astro/physicalConstants.h\"\n#include \"tudat/math/basic/mathematicalConstants.h\"\n#include \"tudat/math/basic/basicMathematicsFunctions.h\"\n#include \"tudat/math/basic/coordinateConversions.h\"\n#include \"tudat/astro/ephemerides/approximatePlanetPositions.h\"\n#include \"tudat/simulation/simulation.h\"\n#include \"tudat/simulation/propagation_setup/propagationLowThrustProblem.h\"\n#include \"tudat/astro/basic_astro/celestialBodyConstants.h\"\n#include \"tudat/astro/low_thrust/shape_based/baseFunctionsSphericalShaping.h\"\n#include \"tudat/astro/low_thrust/shape_based/compositeFunctionSphericalShaping.h\"\n#include \"tudat/astro/low_thrust/shape_based/sphericalShaping.h\"\n\nnamespace tudat\n{\nnamespace unit_tests\n{\n\nusing namespace tudat;\nusing namespace tudat::simulation_setup;\nusing namespace tudat::ephemerides;\nusing namespace tudat::shape_based_methods;\nusing namespace tudat::root_finders;\nusing namespace tudat::propagators;\n\n//! Test spherical shaping implementation.\nBOOST_AUTO_TEST_SUITE( test_spherical_shaping )\n\n//! Test.\nBOOST_AUTO_TEST_CASE( test_spherical_shaping_earth_mars_transfer )\n{\n    spice_interface::loadStandardSpiceKernels( );\n\n    int numberOfRevolutions = 1;\n    double julianDate = 8174.5 * physical_constants::JULIAN_DAY;\n    double timeOfFlight = 580.0 * physical_constants::JULIAN_DAY;\n\n    // Ephemeris departure body.\n    EphemerisPointer pointerToDepartureBodyEphemeris = std::make_shared< ApproximateJplEphemeris>(\n                \"Earth\"  );\n    EphemerisPointer pointerToArrivalBodyEphemeris = std::make_shared< ApproximateJplEphemeris >(\n                \"Mars\"  );\n    Eigen::Vector6d initialState = pointerToDepartureBodyEphemeris->getCartesianState( julianDate );\n    Eigen::Vector6d finalState = pointerToArrivalBodyEphemeris->getCartesianState(\n                julianDate + timeOfFlight );\n\n    // Define root finder settings (used to update the updated value of the free coefficient, so that it\n    // matches the required time of flight).\n    std::shared_ptr< RootFinderSettings > rootFinderSettings =\n            tudat::root_finders::bisectionRootFinderSettings( 1.0E-6, TUDAT_NAN, TUDAT_NAN, 30 );\n\n    // Compute shaped trajectory.\n    SphericalShaping sphericalShaping = SphericalShaping(\n                initialState, finalState, timeOfFlight,\n                spice_interface::getBodyGravitationalParameter( \"Sun\" ),\n                numberOfRevolutions, 0.000703, rootFinderSettings, 1.0e-6, 1.0e-1 );\n\n    // Initialise peak acceleration.\n    double peakThrustAcceleration = 0.0;\n\n    double stepSize = ( sphericalShaping.getFinalValueInpendentVariable( ) -\n                        sphericalShaping.getInitialValueInpendentVariable( ) ) / 5000.0;\n    for ( int i = 0 ; i <= 5000 ; i++ )\n    {\n        double currentThetaAngle = sphericalShaping.getInitialValueInpendentVariable() + i * stepSize;\n        if ( sphericalShaping.computeCurrentThrustAcceleration( currentThetaAngle ).norm() >  peakThrustAcceleration )\n        {\n            peakThrustAcceleration = sphericalShaping.computeCurrentThrustAcceleration( currentThetaAngle ).norm();\n        }\n    }\n\n\n    // Check results consistency w.r.t. thesis from T. Roegiers (ADD PROPER REFERENCE)\n    double expectedDeltaV = 5700.0;\n    double expectedPeakAcceleration = 2.4e-4;\n\n    // DeltaV provided with a precision of 5 m/s\n    BOOST_CHECK_SMALL( std::fabs(  sphericalShaping.computeDeltaV() - expectedDeltaV ), 5.0 );\n    // Peak acceleration provided with a precision 2.0e-6 m/s^2\n    BOOST_CHECK_SMALL( std::fabs(  peakThrustAcceleration - expectedPeakAcceleration ), 2.0e-6 );\n\n}\n\n\n\n//! Test.\nBOOST_AUTO_TEST_CASE( test_spherical_shaping_earth_1989ML_transfer )\n{\n    spice_interface::loadStandardSpiceKernels( );\n\n    int numberOfRevolutions = 1;\n    double julianDate = 7799.5 * physical_constants::JULIAN_DAY;\n    double timeOfFlight = 600.0 * physical_constants::JULIAN_DAY;\n\n    // Ephemeris departure body.\n    EphemerisPointer pointerToDepartureBodyEphemeris = std::make_shared< ApproximateJplEphemeris>(\n                \"Earth\"  );\n    Eigen::Vector6d initialState = pointerToDepartureBodyEphemeris->getCartesianState( julianDate );\n\n    // Final state derived from ML1989 ephemeris (from Spice).\n    Eigen::Vector6d finalState = (\n                Eigen::Vector6d() <<\n                1.197701029846094E+00 * physical_constants::ASTRONOMICAL_UNIT,\n                1.653518856610793E-01 * physical_constants::ASTRONOMICAL_UNIT,\n                - 9.230177854743750E-02 * physical_constants::ASTRONOMICAL_UNIT,\n                - 4.891080912584867E-05 * physical_constants::ASTRONOMICAL_UNIT / physical_constants::JULIAN_DAY,\n                1.588950249593135E-02 * physical_constants::ASTRONOMICAL_UNIT / physical_constants::JULIAN_DAY,\n                - 2.980245580772588E-04 * physical_constants::ASTRONOMICAL_UNIT / physical_constants::JULIAN_DAY ).finished();\n\n\n    // Define root finder settings (used to update the updated value of the free coefficient, so that it matches the required time of flight).\n    std::shared_ptr< RootFinderSettings > rootFinderSettings =\n            tudat::root_finders::bisectionRootFinderSettings( 1.0E-6, TUDAT_NAN, TUDAT_NAN, 30 );\n\n    // Compute shaped trajectory.\n    SphericalShaping sphericalShaping = SphericalShaping(\n                initialState, finalState, timeOfFlight,\n                spice_interface::getBodyGravitationalParameter( \"Sun\" ),\n                numberOfRevolutions, -0.0000703, rootFinderSettings, -1.0e-2, 1.0e-2 );\n\n\n    // Compute step size.\n    double numberOfSteps = 5000.0;\n    double stepSize = ( sphericalShaping.getFinalValueInpendentVariable( ) -\n                        sphericalShaping.getInitialValueInpendentVariable( ) ) / numberOfSteps;\n\n    // Initialise peak acceleration.\n    double peakThrustAcceleration = 0.0;\n\n    // Compute peak acceleration.\n    for ( int i = 0 ; i <= numberOfSteps ; i++ )\n    {\n        double currentThetaAngle = sphericalShaping.getInitialValueInpendentVariable() + i * stepSize;\n\n        if ( sphericalShaping.computeCurrentThrustAcceleration( currentThetaAngle ).norm() >  peakThrustAcceleration )\n        {\n            peakThrustAcceleration = sphericalShaping.computeCurrentThrustAcceleration( currentThetaAngle ).norm();\n        }\n    }\n\n\n    // Check results consistency w.r.t. thesis from T. Roegiers (ADD PROPER REFERENCE)\n    // The expected differences are a bit larger than for Earth-Mars transfer due to the higher uncertainty in 1989ML's ephemeris.\n    double expectedDeltaV = 4530.0;\n    double expectedPeakAcceleration = 1.8e-4;\n\n    // DeltaV provided with a precision of 0.1 km/s\n    BOOST_CHECK_SMALL( std::fabs(  sphericalShaping.computeDeltaV() - expectedDeltaV ), 100.0 );\n    // Peak acceleration provided with a precision 1.0e-5 m/s^2\n    BOOST_CHECK_SMALL( std::fabs(  peakThrustAcceleration - expectedPeakAcceleration ), 1e-5 );\n\n}\n\n\n//! Test spherical shaping method with various number of revolutions.\nBOOST_AUTO_TEST_CASE( test_spherical_shaping_earth_mars_transfer_multi_revolutions )\n{\n    spice_interface::loadStandardSpiceKernels( );\n\n    double julianDate = 8174.5 * physical_constants::JULIAN_DAY;\n\n    std::vector< int > numberOfRevolutionsVector = { 0, 1, 2 };\n    std::vector< double > timeOfFlightVector = { 300.0, 580.0, 750.0 };\n\n    // Ephemeris departure body.\n    EphemerisPointer pointerToDepartureBodyEphemeris = std::make_shared< ApproximateJplEphemeris>(\n                \"Earth\"  );\n    EphemerisPointer pointerToArrivalBodyEphemeris = std::make_shared< ApproximateJplEphemeris >(\n                \"Mars\"  );\n\n    // Define root finder settings (used to update the updated value of the free coefficient, so that it matches the required time of flight).\n    std::shared_ptr< RootFinderSettings > rootFinderSettings =\n            tudat::root_finders::bisectionRootFinderSettings( 1.0E-6, TUDAT_NAN, TUDAT_NAN, 30 );\n\n    // Bounds for the free parameter.\n    std::vector< double > freeParameterLowerBoundVector = { -1.0, 1.0e-6, -1.0e-2 };\n    std::vector< double > freeParameterUpperBoundVector = { 5.0e-1, 1.0e-1, 1.0e-2 };\n\n    // Define initial state.\n    Eigen::Vector6d initialState = pointerToDepartureBodyEphemeris->getCartesianState( julianDate );\n\n    for ( unsigned int currentTestCase = 0 ; currentTestCase < numberOfRevolutionsVector.size( ) ; currentTestCase++ )\n    {\n        // Define final state.\n        Eigen::Vector6d finalState = pointerToArrivalBodyEphemeris->getCartesianState(\n                    julianDate + timeOfFlightVector.at( currentTestCase )* physical_constants::JULIAN_DAY );\n\n        // Compute shaped trajectory.\n        SphericalShaping sphericalShaping = SphericalShaping(\n                    initialState, finalState, timeOfFlightVector.at( currentTestCase )* physical_constants::JULIAN_DAY,\n                    spice_interface::getBodyGravitationalParameter( \"Sun\" ),\n                    numberOfRevolutionsVector.at( currentTestCase ),\n                    0.000703, rootFinderSettings, freeParameterLowerBoundVector.at( currentTestCase ),\n                    freeParameterUpperBoundVector.at( currentTestCase ) );\n\n        // Check consistency of final azimuth angle value with required number of revolutions.\n        double initialAzimuthAngle = sphericalShaping.getInitialValueInpendentVariable( );\n        double finalAzimuthAngle = sphericalShaping.getFinalValueInpendentVariable( );\n\n        double expectedInitialAzimuthAngle = coordinate_conversions::convertCartesianToSphericalState( initialState )[ 1 ];\n        if ( expectedInitialAzimuthAngle < 0.0 )\n        {\n            expectedInitialAzimuthAngle += 2.0 * mathematical_constants::PI;\n        }\n        double expectedFinalAzimuthAngle = coordinate_conversions::convertCartesianToSphericalState( finalState )[ 1 ];\n        if ( expectedFinalAzimuthAngle < 0.0 )\n        {\n            expectedFinalAzimuthAngle += 2.0 * mathematical_constants::PI;\n        }\n\n        if ( expectedFinalAzimuthAngle - expectedInitialAzimuthAngle < 0 )\n        {\n            expectedFinalAzimuthAngle += 2.0 * mathematical_constants::PI * ( numberOfRevolutionsVector.at( currentTestCase )+ 1 );\n        }\n        else\n        {\n            expectedFinalAzimuthAngle += 2.0 * mathematical_constants::PI * numberOfRevolutionsVector.at( currentTestCase );\n        }\n\n        BOOST_CHECK_SMALL( std::fabs(  initialAzimuthAngle - expectedInitialAzimuthAngle ), 1.0e-15 );\n        BOOST_CHECK_SMALL( std::fabs(  finalAzimuthAngle - expectedFinalAzimuthAngle ), 1.0e-15 );\n\n        // Check consistency of expected and calculated states (both at departure and arrival).\n        for ( int i = 0 ; i < 6 ; i++ )\n        {\n            BOOST_CHECK_SMALL( std::fabs( ( initialState[ i ] - sphericalShaping.computeCurrentStateVector( initialAzimuthAngle )[ i ] )\n                                          / initialState[ i ] ), 1.0e-12 );\n            BOOST_CHECK_SMALL( std::fabs( ( finalState[ i ] - sphericalShaping.computeCurrentStateVector( finalAzimuthAngle )[ i ] )\n                                          / finalState[ i ] ), 1.0e-12 );\n        }\n    }\n}\n\nSystemOfBodies getTestBodyMap( )\n{\n    // Create central, departure and arrival bodies.\n    std::vector< std::string > bodiesToCreate;\n    bodiesToCreate.push_back( \"Sun\" );\n    bodiesToCreate.push_back( \"Earth\" );\n    bodiesToCreate.push_back( \"Mars\" );\n    bodiesToCreate.push_back( \"Jupiter\" );\n\n\n    std::string frameOrigin = \"SSB\";\n    std::string frameOrientation = \"ECLIPJ2000\";\n\n    BodyListSettings bodySettings =\n            getDefaultBodySettings( bodiesToCreate, frameOrigin, frameOrientation );\n\n    // Define central body ephemeris settings.\n    bodySettings.at( \"Sun\" )->ephemerisSettings = std::make_shared< ConstantEphemerisSettings >(\n                ( Eigen::Vector6d( ) << 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 ).finished( ), frameOrigin, frameOrientation );\n\n\n    // Create system of bodies.\n    SystemOfBodies bodies = createSystemOfBodies( bodySettings );\n\n    bodies.createEmptyBody( \"Vehicle\" );\n\n    return bodies;\n\n}\n\nBOOST_AUTO_TEST_CASE( test_spherical_shaping_full_propagation )\n{\n\n    int numberOfRevolutions = 1;\n    double julianDate = 8174.5 * physical_constants::JULIAN_DAY;\n    double  timeOfFlight = 580.0;\n\n    // Ephemeris for arrival and departure body.\n    EphemerisPointer pointerToDepartureBodyEphemeris = std::make_shared< ApproximateJplEphemeris>(\n                \"Earth\"  );\n    EphemerisPointer pointerToArrivalBodyEphemeris = std::make_shared< ApproximateJplEphemeris >(\n                \"Mars\"  );\n    Eigen::Vector6d stateAtDeparture = pointerToDepartureBodyEphemeris->getCartesianState( julianDate );\n    Eigen::Vector6d stateAtArrival = pointerToArrivalBodyEphemeris->getCartesianState(\n                julianDate + timeOfFlight * physical_constants::JULIAN_DAY );\n\n    // Define root finder settings (used to update the updated value of the free coefficient, so that it matches the required time of flight).\n    std::shared_ptr< RootFinderSettings > rootFinderSettings =\n            tudat::root_finders::bisectionRootFinderSettings( 1.0E-6, TUDAT_NAN, TUDAT_NAN, 30 );\n\n    // Compute shaped trajectory.\n    std::shared_ptr< SphericalShaping > sphericalShaping = std::make_shared< SphericalShaping >(\n                stateAtDeparture, stateAtArrival, timeOfFlight * physical_constants::JULIAN_DAY,\n                spice_interface::getBodyGravitationalParameter( \"Sun\" ),\n                numberOfRevolutions, 0.000703,\n                rootFinderSettings, 1.0e-6, 1.0e-1 );\n\n    std::map< double, Eigen::VectorXd > fullPropagationResults;\n    std::map< double, Eigen::Vector6d > shapingMethodResults;\n    std::map< double, Eigen::VectorXd > dependentVariablesHistory;\n\n    // Create system of bodies\n    SystemOfBodies bodies = getTestBodyMap( );\n    bodies.at( \"Vehicle\" )->setBodyMassFunction(  [ = ]( const double currentTime ){ return 2000.0; } );\n\n\n    // Define integrator settings\n    std::shared_ptr< numerical_integrators::IntegratorSettings< double > > integratorSettings =\n            std::make_shared< numerical_integrators::IntegratorSettings< double > > (\n                numerical_integrators::rungeKutta4, 0.0, timeOfFlight * physical_constants::JULIAN_DAY / ( 1000.0 ) );\n\n    // Define mass and specific impulse functions of the vehicle.\n    std::function< double( const double ) > specificImpulseFunction =\n            [ ]( const double ){ return 3000.0; };\n\n\n    // Create object with list of dependent variables\n    std::vector< std::shared_ptr< SingleDependentVariableSaveSettings > > dependentVariablesList;\n    dependentVariablesList.push_back( std::make_shared< SingleAccelerationDependentVariableSaveSettings >(\n                                          basic_astrodynamics::thrust_acceleration, \"Vehicle\", \"Vehicle\", 0 ) );\n    std::shared_ptr< DependentVariableSaveSettings > dependentVariablesToSave =\n            std::make_shared< DependentVariableSaveSettings >( dependentVariablesList, false );\n\n    // Create complete propagation settings (backward and forward propagations).\n    basic_astrodynamics::AccelerationMap lowThrustAccelerationsMap =\n            retrieveLowThrustAccelerationMap(\n                sphericalShaping, bodies, \"Vehicle\", \"Sun\", specificImpulseFunction, 0.0 );\n    std::pair< std::shared_ptr< PropagatorSettings< double > >,\n            std::shared_ptr< PropagatorSettings< double > > > propagatorSettings =\n            createLowThrustTranslationalStatePropagatorSettings(\n                sphericalShaping, \"Vehicle\", \"Sun\", lowThrustAccelerationsMap, dependentVariablesToSave );\n\n    // Compute shaped trajectory and propagated trajectory.\n    computeLowThrustLegSemiAnalyticalAndFullPropagation(\n                sphericalShaping, bodies, integratorSettings, propagatorSettings,\n                fullPropagationResults, shapingMethodResults, dependentVariablesHistory );\n\n    // Check difference between full propagation and shaping method at arrival\n    // (disregarding the very last values because of expected interpolation errors).\n    int numberOfDisregardedValues = 7;\n    std::map< double, Eigen::VectorXd >::iterator itr = fullPropagationResults.end();\n    for( int i = 0 ; i < numberOfDisregardedValues ; i++ )\n    {\n        itr--;\n    }\n\n    // Check results consistency between full propagation and shaped trajectory at arrival.\n    for ( int i = 0 ; i < 6 ; i++ )\n    {\n        BOOST_CHECK_SMALL( std::fabs( shapingMethodResults[ itr->first ][ i ] - itr->second[ i ] ) /\n                shapingMethodResults[ itr->first ][ i ] , 1.0e-6 );\n    }\n\n    // Check difference between full propagation and shaping method at departure\n    // (disregarding the very first values because of expected interpolation errors).\n    itr = fullPropagationResults.begin();\n    for( int i = 0 ; i < numberOfDisregardedValues ; i++ )\n    {\n        itr++;\n    }\n\n    // Check results consistency between full propagation and shaped trajectory at departure.\n    for ( int i = 0 ; i < 6 ; i++ )\n    {\n        BOOST_CHECK_SMALL( std::fabs( shapingMethodResults[ itr->first ][ i ] - itr->second[ i ] ) /\n                shapingMethodResults[ itr->first ][ i ] , 1.0e-6 );\n    }\n}\n\n\n//BOOST_AUTO_TEST_CASE( test_spherical_shaping_full_propagation_mass_propagation )\n//{\n\n//    spice_interface::loadStandardSpiceKernels( );\n\n\n//    int numberOfRevolutions = 1;\n//    double julianDate = 8174.5 * physical_constants::JULIAN_DAY;\n//    double  timeOfFlight = 580.0;\n//    double initialMass = 2000.0;\n//    std::function< double( const double ) > specificImpulseFunction = [ = ]( const double ) { return 3000.0; };\n\n//    // Ephemeris for arrival and departure body.\n//    EphemerisPointer pointerToDepartureBodyEphemeris = std::make_shared< ApproximateJplEphemeris>(\n//                \"Earth\"  );\n//    EphemerisPointer pointerToArrivalBodyEphemeris = std::make_shared< ApproximateJplEphemeris >(\n//                \"Mars\"  );\n//    Eigen::Vector6d stateAtDeparture = pointerToDepartureBodyEphemeris->getCartesianState( julianDate );\n//    Eigen::Vector6d stateAtArrival = pointerToArrivalBodyEphemeris->getCartesianState( julianDate + timeOfFlight * physical_constants::JULIAN_DAY );\n\n//    // Define root finder settings (used to update the updated value of the free coefficient, so that it matches the required time of flight).\n//    std::shared_ptr< RootFinderSettings > rootFinderSettings =\n//            std::make_shared< RootFinderSettings >( bisection_root_finder, 1.0e-6, 30 );\n\n//    // Compute shaped trajectory.\n//    SphericalShaping sphericalShaping = SphericalShaping(\n//                stateAtDeparture, stateAtArrival, timeOfFlight * physical_constants::JULIAN_DAY,\n//                spice_interface::getBodyGravitationalParameter( \"Sun\" ),\n//                numberOfRevolutions, 0.000703,\n//                rootFinderSettings, 1.0e-6, 1.0e-1, initialMass );\n\n//    std::map< double, Eigen::VectorXd > fullPropagationResults;\n//    std::map< double, Eigen::Vector6d > shapingMethodResults;\n//    std::map< double, Eigen::VectorXd > dependentVariablesHistory;\n\n//    // Create system of bodies\n//    SystemOfBodies bodies = getTestBodyMap( );\n//    bodies.at( \"Vehicle\" )->setConstantBodyMass( initialMass );\n\n\n//    // Define integrator settings\n//    std::shared_ptr< numerical_integrators::IntegratorSettings< double > > integratorSettings =\n//            std::make_shared< numerical_integrators::IntegratorSettings< double > > (\n//                numerical_integrators::rungeKutta4, 0.0,\n//                timeOfFlight * physical_constants::JULIAN_DAY / ( 1000.0 ) );\n\n\n//    // Define list of dependent variables to save.\n//    std::vector< std::shared_ptr< SingleDependentVariableSaveSettings > > dependentVariablesList;\n//    dependentVariablesList.push_back( std::make_shared< SingleAccelerationDependentVariableSaveSettings >(\n//                                          basic_astrodynamics::thrust_acceleration, \"Vehicle\", \"Vehicle\", 0 ) );\n//    dependentVariablesList.push_back( std::make_shared< SingleDependentVariableSaveSettings >(\n//                                          total_mass_rate_dependent_variables, \"Vehicle\" ) );\n\n//    // Create object with list of dependent variables\n//    std::shared_ptr< DependentVariableSaveSettings > dependentVariablesToSave =\n//            std::make_shared< DependentVariableSaveSettings >( dependentVariablesList, false );\n\n//    // Create termination conditions settings.\n//    std::pair< std::shared_ptr< PropagationTerminationSettings >, std::shared_ptr< PropagationTerminationSettings > > terminationConditions =\n//            std::make_pair( std::make_shared< PropagationTimeTerminationSettings >( 0.0 ),\n//                            std::make_shared< PropagationTimeTerminationSettings >( timeOfFlight * physical_constants::JULIAN_DAY ) );\n\n\n//    // Create complete propagation settings (backward and forward propagations).\n//    std::pair< std::shared_ptr< PropagatorSettings< double > >,\n//            std::shared_ptr< PropagatorSettings< double > > > propagatorSettings = sphericalShaping.createLowThrustPropagatorSettings(\n//                bodies, \"Vehicle\", \"Sun\", specificImpulseFunction, basic_astrodynamics::AccelerationMap( ), integratorSettings, dependentVariablesToSave );\n\n//    // Compute shaped trajectory and propagated trajectory.\n//    sphericalShaping.computeSemiAnalyticalAndFullPropagation(\n//                bodies, integratorSettings, propagatorSettings,\n//                fullPropagationResults, shapingMethodResults, dependentVariablesHistory );\n\n\n\n//    // Check difference between full propagation and shaping method at arrival\n//    // (disregarding the very last values because of expected interpolation errors).\n//    int numberOfDisregardedValues = 7;\n//    std::map< double, Eigen::VectorXd >::iterator itr = fullPropagationResults.end();\n//    for( int i = 0 ; i < numberOfDisregardedValues ; i++ )\n//    {\n//        itr--;\n//    }\n\n//    // Check results consistency between full propagation and shaped trajectory at arrival.\n//    for ( int i = 0 ; i < 6 ; i++ )\n//    {\n////        BOOST_CHECK_SMALL( std::fabs( shapingMethodResults[ itr->first ][ i ] - itr->second[ i ] ) / shapingMethodResults[ itr->first ][ i ] , 1.0e-6 );\n//    }\n\n\n\n//    // Check difference between full propagation and shaping method at departure\n//    // (disregarding the very first values because of expected interpolation errors).\n//    itr = fullPropagationResults.begin();\n//    for( int i = 0 ; i < numberOfDisregardedValues ; i++ )\n//    {\n//        itr++;\n//    }\n\n//    // Check results consistency between full propagation and shaped trajectory at departure.\n//    for ( int i = 0 ; i < 6 ; i++ )\n//    {\n//        BOOST_CHECK_SMALL( std::fabs( shapingMethodResults[ itr->first ][ i ] - itr->second[ i ] ) / shapingMethodResults[ itr->first ][ i ] , 1.0e-6 );\n//    }\n\n//    // Check consistency between current and expected mass rates.\n//    for ( std::map< double, Eigen::VectorXd >::iterator itr = dependentVariablesHistory.begin() ; itr != dependentVariablesHistory.end() ; itr++ )\n//    {\n//        Eigen::Vector3d currentThrustAccelerationVector = itr->second.segment( 0, 3 );\n//        double currentMass = fullPropagationResults.at( itr->first )( 6 );\n//        double currentMassRate = - itr->second( 3 );\n//        double expectedMassRate = currentThrustAccelerationVector.norm() * currentMass /\n//                ( specificImpulseFunction( itr->first ) * physical_constants::SEA_LEVEL_GRAVITATIONAL_ACCELERATION );\n//        BOOST_CHECK_SMALL( std::fabs( currentMassRate - expectedMassRate ), 1.0e-15 );\n\n//    }\n\n\n//    // Test trajectory function.\n//    std::vector< double > epochsVector;\n//    epochsVector.push_back( 0.0 );\n//    epochsVector.push_back( timeOfFlight / 4.0 * physical_constants::JULIAN_DAY );\n//    epochsVector.push_back( timeOfFlight / 2.0 * physical_constants::JULIAN_DAY );\n//    epochsVector.push_back( 3.0 * timeOfFlight / 4.0 * physical_constants::JULIAN_DAY );\n//    epochsVector.push_back( timeOfFlight * physical_constants::JULIAN_DAY );\n\n//    std::map< double, Eigen::Vector6d > trajectory;\n//    std::map< double, Eigen::VectorXd > massProfile;\n//    std::map< double, Eigen::VectorXd > thrustProfile;\n//    std::map< double, Eigen::VectorXd > thrustAccelerationProfile;\n\n//    sphericalShaping.getTrajectory( epochsVector, trajectory );\n//    sphericalShaping.getMassProfile( epochsVector, massProfile, specificImpulseFunction, integratorSettings );\n////    sphericalShaping.getThrustForceProfile( epochsVector, thrustProfile, specificImpulseFunction, integratorSettings );\n////    sphericalShaping.getThrustAccelerationProfile( epochsVector, thrustAccelerationProfile, specificImpulseFunction, integratorSettings );\n\n//    for ( int i = 0 ; i < 3 ; i ++ )\n//    {\n//        BOOST_CHECK_SMALL( std::fabs( ( trajectory.begin( )->second[ i ] - stateAtDeparture[ i ] ) /\n//                                      physical_constants::ASTRONOMICAL_UNIT ), 1.0e-6 );\n//        BOOST_CHECK_SMALL( std::fabs( ( trajectory.begin( )->second[ i + 3 ] - stateAtDeparture[ i + 3 ] ) /\n//                ( physical_constants::ASTRONOMICAL_UNIT / physical_constants::JULIAN_YEAR ) ), 1.0e-6 );\n//        BOOST_CHECK_SMALL( std::fabs( ( trajectory.rbegin( )->second[ i ] - stateAtArrival[ i ] ) /\n//                                      physical_constants::ASTRONOMICAL_UNIT ), 1.0e-6 );\n//        BOOST_CHECK_SMALL( std::fabs( ( trajectory.rbegin( )->second[ i + 3 ] - stateAtArrival[ i + 3 ] ) /\n//                ( physical_constants::ASTRONOMICAL_UNIT / physical_constants::JULIAN_YEAR ) ), 1.0e-6 );\n//    }\n\n//    for ( std::map< double, Eigen::Vector6d >::iterator itr = trajectory.begin( ) ; itr != trajectory.end( ) ; itr++ )\n//    {\n//        double independentVariable = sphericalShaping.convertTimeToIndependentVariable( itr->first );\n//        Eigen::Vector6d stateVector = sphericalShaping.computeCurrentStateVector( independentVariable );\n//        Eigen::Vector3d thrustAccelerationVector = sphericalShaping.computeCurrentThrustAcceleration( itr->first, specificImpulseFunction, integratorSettings );\n//        Eigen::Vector3d thrustVector = sphericalShaping.computeCurrentThrustForce( itr->first, specificImpulseFunction, integratorSettings );\n//        double mass = sphericalShaping.computeCurrentMass( itr->first, specificImpulseFunction, integratorSettings );\n\n//        for ( int i = 0 ; i < 3 ; i++ )\n//        {\n//            BOOST_CHECK_SMALL( std::fabs( itr->second[ i ] - stateVector[ i ] ), 1.0e-6 );\n//            BOOST_CHECK_SMALL( std::fabs( itr->second[ i + 3 ] - stateVector[ i + 3 ] ), 1.0e-12 );\n//            BOOST_CHECK_SMALL( std::fabs( thrustAccelerationProfile[ itr->first ][ i ] - thrustAccelerationVector[ i ] ), 1.0e-6 );\n//            BOOST_CHECK_SMALL( std::fabs( thrustProfile[ itr->first ][ i ] - thrustVector[ i ] ), 1.0e-12 );\n//        }\n//        BOOST_CHECK_SMALL( std::fabs( massProfile[ itr->first ][ 0 ] - mass ), 1.0e-10 );\n//    }\n\n//}\n\nBOOST_AUTO_TEST_SUITE_END( )\n\n} // namespace unit_tests\n} // namespace tudat\n", "meta": {"hexsha": "916c2994b0011b357b82c1de49d4bbff7165f1c8", "size": 27916, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/src/astro/low_thrust/shape_based/unitTestSphericalShaping.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": "tests/src/astro/low_thrust/shape_based/unitTestSphericalShaping.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": "tests/src/astro/low_thrust/shape_based/unitTestSphericalShaping.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": 49.76114082, "max_line_length": 162, "alphanum_fraction": 0.6923269809, "num_tokens": 6970, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402813, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.47089026461635947}}
{"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 * Created on June 4, 2020, 10:13 AM\n */\n\n#include \"PermeabilityMohrCoulombFailureIndexModel.h\"\n\n#include <boost/math/constants/constants.hpp>\n#include <cmath>\n#include <limits>\n\n#include \"BaseLib/Error.h\"\n#include \"MaterialLib/MPL/Medium.h\"\n#include \"MaterialLib/MPL/Utils/FormEigenTensor.h\"\n#include \"MaterialLib/MPL/Utils/GetSymmetricTensor.h\"\n#include \"MathLib/KelvinVector.h\"\n#include \"MathLib/MathTools.h\"\n#include \"ParameterLib/CoordinateSystem.h\"\n#include \"ParameterLib/Parameter.h\"\n\nnamespace MaterialPropertyLib\n{\ntemplate <int DisplacementDim>\nPermeabilityMohrCoulombFailureIndexModel<DisplacementDim>::\n    PermeabilityMohrCoulombFailureIndexModel(\n        std::string name, ParameterLib::Parameter<double> const& k0,\n        double const kr, double const b, double const c, double const phi,\n        double const k_max, double const t_sigma_max,\n        ParameterLib::CoordinateSystem const* const local_coordinate_system)\n    : k0_(k0),\n      kr_(kr),\n      b_(b),\n      c_(c),\n      phi_(boost::math::constants::degree<double>() * phi),\n      k_max_(k_max),\n      t_sigma_max_(t_sigma_max),\n      local_coordinate_system_(local_coordinate_system)\n{\n    const double t_sigma_upper = c_ / std::tan(phi_);\n    if (t_sigma_max_ <= 0.0 || t_sigma_max_ > t_sigma_upper ||\n        std::fabs(t_sigma_max_ - t_sigma_upper) <\n            std::numeric_limits<double>::epsilon())\n    {\n        OGS_FATAL(\n            \"Tensile strength parameter of {:e} is out of the range (0, \"\n            \"c/tan(phi)) = (0, {:e})\",\n            t_sigma_max_, t_sigma_upper);\n    }\n\n    name_ = std::move(name);\n}\n\ntemplate <int DisplacementDim>\nvoid PermeabilityMohrCoulombFailureIndexModel<DisplacementDim>::checkScale()\n    const\n{\n    if (!std::holds_alternative<Medium*>(scale_))\n    {\n        OGS_FATAL(\n            \"The property 'PermeabilityMohrCoulombFailureIndexModel' is \"\n            \"implemented on the 'medium' scale only.\");\n    }\n}\n\ntemplate <int DisplacementDim>\nPropertyDataType\nPermeabilityMohrCoulombFailureIndexModel<DisplacementDim>::value(\n    VariableArray const& variable_array,\n    ParameterLib::SpatialPosition const& pos, double const t,\n    double const /*dt*/) const\n{\n    auto const& stress_vector = std::get<SymmetricTensor<DisplacementDim>>(\n        variable_array[static_cast<int>(Variable::total_stress)]);\n\n    auto const& stress_tensor =\n        formEigenTensor<3>(static_cast<PropertyDataType>(stress_vector));\n\n    Eigen::SelfAdjointEigenSolver<Eigen::Matrix<double, 3, 3>>\n        eigenvalue_solver(stress_tensor);\n\n    // Principle stress\n    auto const sigma = eigenvalue_solver.eigenvalues();\n\n    auto k_data = k0_(t, pos);\n\n    double const max_sigma = std::max(std::fabs(sigma[0]), std::fabs(sigma[2]));\n\n    if (max_sigma < std::numeric_limits<double>::epsilon())\n    {\n        return fromVector(k_data);\n    }\n\n    double const sigma_m = 0.5 * (sigma[2] + sigma[0]);\n\n    double const tau_m = 0.5 * std::fabs(sigma[2] - sigma[0]);\n    double f = 0.0;\n    if (sigma_m > t_sigma_max_)\n    {\n        // tensile failure criterion\n        f = sigma_m / t_sigma_max_;\n\n        double const tau_tt =\n            c_ * std::cos(phi_) - t_sigma_max_ * std::sin(phi_);\n\n        f = std::max(f, tau_m / tau_tt);\n    }\n    else\n    {\n        // Mohr Coulomb failure criterion\n        f = tau_m / (c_ * std::cos(phi_) - sigma_m * std::sin(phi_));\n    }\n\n    if (f >= 1.0)\n    {\n        const double exp_value = std::exp(b_ * f);\n        for (auto& k_i : k_data)\n        {\n            k_i = std::min(k_i + kr_ * exp_value, k_max_);\n        }\n    }\n\n    // Local coordinate transformation is only applied for the case that the\n    // initial intrinsic permeability is given with orthotropic assumption.\n    if (local_coordinate_system_ && (k_data.size() == DisplacementDim))\n    {\n        Eigen::Matrix<double, DisplacementDim, DisplacementDim> const e =\n            local_coordinate_system_->transformation<DisplacementDim>(pos);\n        Eigen::Matrix<double, DisplacementDim, DisplacementDim> k =\n            Eigen::Matrix<double, DisplacementDim, DisplacementDim>::Zero();\n\n        for (int i = 0; i < DisplacementDim; ++i)\n        {\n            Eigen::Matrix<double, DisplacementDim, DisplacementDim> const\n                ei_otimes_ei = e.col(i) * e.col(i).transpose();\n\n            k += k_data[i] * ei_otimes_ei;\n        }\n        return k;\n    }\n\n    return fromVector(k_data);\n}\n\ntemplate <int DisplacementDim>\nPropertyDataType\nPermeabilityMohrCoulombFailureIndexModel<DisplacementDim>::dValue(\n    VariableArray const& /*variable_array*/, Variable const variable,\n    ParameterLib::SpatialPosition const& /*pos*/, double const /*t*/,\n    double const /*dt*/) const\n{\n    if (variable == Variable::mechanical_strain)\n    {\n        return 0.;\n    }\n\n    OGS_FATAL(\n        \"The derivative of the intrinsic permeability k(sigma, ...) with \"\n        \"respect to stress tensor (sigma) is not implemented because that \"\n        \"dk/du is normally omitted.\");\n}\ntemplate class PermeabilityMohrCoulombFailureIndexModel<2>;\ntemplate class PermeabilityMohrCoulombFailureIndexModel<3>;\n}  // namespace MaterialPropertyLib\n", "meta": {"hexsha": "b1ecb226a6fa822c30ced596446470c13bdd4e7a", "size": 5413, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "MaterialLib/MPL/Properties/PermeabilityMohrCoulombFailureIndexModel.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/MPL/Properties/PermeabilityMohrCoulombFailureIndexModel.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/MPL/Properties/PermeabilityMohrCoulombFailureIndexModel.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": 31.8411764706, "max_line_length": 80, "alphanum_fraction": 0.6604470719, "num_tokens": 1381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619959279793, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4708902577800187}}
{"text": "// Author: Senthil Kumar Thangavelu kingjuliyen@gmail.com\n\n/*\n  Compile:\n  g++  HiddenFactorsLearner.cpp \\\n       -I/opt/boost/1_61_0/include/\t\t\t\t\t\t\\\n       -L/opt/boost/1_61_0/lib\t\t\t\t\t\t\\\n       -lboost_program_options \\\n       -O3 -o /tmp/hidden-factor-learner\n\n  Usage:\n  export DYLD_LIBRARY_PATH=/opt/boost/1_61_0/lib:$DYLD_LIBRARY_PATH\n\n  DYLD_LIBRARY_PATH=/opt/boost/1_61_0/lib:$DYLD_LIBRARY_PATH \\\n  time /tmp/hidden-factor-learner --num-factors 5 \\\n          --default-rating 2.8485 \\\n          --regularization-param-p 0.002 \\\n          --regularization-param-q 0.002 \\\n          --learning-rate-p 0.000002 \\\n          --learning-rate-q 0.000002 \\\n          --training-sample-percentage 0.7 \\\n          --gradient-descent-iteration-count 100 \\\n          --max-row-dimension 100000000 \\\n          --max-column-dimension 100000000 \\\n          --verbose-mode-level 1 \\\n          --loop-mode-count 3 \\\n          --input-csv-file-path /tmp/1000.csv \\\n          --p-q-matrix-output-file-path /tmp/\n\ne.g csv file (remove header)\nusrid  itemid rating\n785166 6066 3\n521295 4972 3\n1665652 11701 5\n1963419 15887 3\n\n  Linux:\n\n  LD_LIBRARY_PATH=/opt/boost/1_61_0/lib:$LD_LIBRARY_PATH \\\n  time /tmp/hidden-factor-learner --num-factors 2 \\\n          --default-rating 2.8485 \\\n          --regularization-param-p 0.002 \\\n          --regularization-param-q 0.002 \\\n          --learning-rate-p 0.000002 \\\n          --learning-rate-q 0.000002 \\\n          --training-sample-percentage 0.7 \\\n          --gradient-descent-iteration-count 100 \\\n          --max-row-dimension 100000000 \\\n          --max-column-dimension 100000000 \\\n          --verbose-mode-level 1 \\\n          --loop-mode-count 3 \\\n          --input-csv-file-path /tmp/sf41.csv \\\n          --p-q-matrix-output-file-path /tmp/\n\n  Install boost:\n  ./bootstrap.sh --prefix=/opt/boost/1_61_0\n  ./b2 install\n*/\n\n\n\n#include <iostream>\n#include <string>\n#include <boost/program_options.hpp>\n\n#include \"HiddenFactorsLearner.hpp\"\n\nnamespace ProgOpts = boost::program_options;\n\nconst char * num_factors_str =\n  \"Number of hidden factors aka K \";\nconst char * default_rating_str =\n  \"Default rating used in the matrix factorization\"\n  \" at start of gradient descent \";\nconst char * regularization_param_p_str =\n  \"Regularization parameter for matrix P \";\nconst char * regularization_param_q_str =\n  \"Regularization parameter for matrix Q \";\nconst char * learning_rate_p_str =\n  \"Learning rate for matrix P parameters in gradient descent \";\nconst char * learning_rate_q_str =\n  \"Learning rate for matrix Q parameters in gradient descent \";\nconst char * gradient_descent_iteration_count_str =\n  \"Number of times gradient descent iterations need to be run \";\nconst char * training_sample_percentage_str =\n  \"Percentage of data set to be used for training \";\n  //\"remaining percentage will be used for validation \";\nconst char * max_row_dim_str= \"Max dimension for rows in matrix\";\nconst char * max_col_dim_str = \"Max dimension for columns in matrix\";\nconst char * input_csv_str = \"Path of input csv file to read rating \"\n  \"entries from \";\nconst char * verbose_mode_level_str = \"Show debug info about inner workings \";\nconst char * loop_mode_count_str = \"Run repeatedly in loop mode for same input \";\nconst char * P_Q_matrix_output_file_path_str = \"path to store P and Q matrix output\";\n\nbool processInputArgs(int argc, char * argv[], ProgOpts::variables_map &varMap,\n        MatrixFactorizationParams &params)\n{\n  try {\n    ProgOpts::options_description desc(\"Allowed Options\");\n\n    desc.add_options()\n      (\"help\", \"produce help message\")\n      (\"num-factors\", ProgOpts::value<INT_T>(), num_factors_str)\n      (\"default-rating\", ProgOpts::value<FLT_T>(), default_rating_str)\n      (\"regularization-param-p\", ProgOpts::value<FLT_T>(), regularization_param_p_str)\n      (\"regularization-param-q\", ProgOpts::value<FLT_T>(), regularization_param_q_str)\n      (\"learning-rate-p\", ProgOpts::value<FLT_T>(), learning_rate_p_str)\n      (\"learning-rate-q\", ProgOpts::value<FLT_T>(), learning_rate_q_str)\n      (\"gradient-descent-iteration-count\", ProgOpts::value<INT_T>(), gradient_descent_iteration_count_str)\n      (\"training-sample-percentage\", ProgOpts::value<FLT_T>(), training_sample_percentage_str)\n      (\"max-row-dimension\", ProgOpts::value<INT_T>(), max_row_dim_str)\n      (\"max-column-dimension\", ProgOpts::value<INT_T>(), max_col_dim_str)\n      (\"input-csv-file-path\", ProgOpts::value<STRING_T>(), input_csv_str)\n      (\"verbose-mode-level\", ProgOpts::value<INT_T>(), verbose_mode_level_str)\n      (\"loop-mode-count\", ProgOpts::value<INT_T>(), loop_mode_count_str)\n      (\"p-q-matrix-output-file-path\", ProgOpts::value<STRING_T>(), P_Q_matrix_output_file_path_str)\n      ; // leave this semi colon at end don't move this\n\n    ProgOpts::store(ProgOpts::parse_command_line(argc, argv, desc), varMap);\n    ProgOpts::notify(varMap);\n\n    if (varMap.count(\"help\")) {\n      cout << desc << \"\\n\";\n      return false;\n    }\n\n    OPT(num_factors , \"num-factors\", INT_T,  5);\n    OPT(default_rating ,\"default-rating\" , FLT_T,  2.8485);\n    OPT(regularization_param_p ,\"regularization-param-p\", FLT_T,  0.002);\n    OPT(regularization_param_q ,\"regularization-param-q\", FLT_T,  0.002);\n    OPT(learning_rate_p ,\"learning-rate-p\", FLT_T,  0.000002);\n    OPT(learning_rate_q ,\"learning-rate-q\", FLT_T,  0.000002);\n    OPT(gradient_descent_iteration_count ,\"gradient-descent-iteration-count\", INT_T,  100);\n    OPT(training_sample_percentage ,\"training-sample-percentage\", FLT_T,  0.70);\n    OPT(max_row_dim ,\"max-row-dimension\", INT_T,  100000000);\n    OPT(max_col_dim ,\"max-column-dimension\", INT_T,  100000000);\n    OPT(csv_input_file_path ,\"input-csv-file-path\", STRING_T,  STRING_T(\"unknown_bad.csv\"));\n    OPT(verbose_mode_level ,\"verbose-mode-level\", INT_T,  0);\n    OPT(loop_mode_count ,\"loop-mode-count\", INT_T,  1);\n    OPT(p_q_matrix_output_file_path, \"p-q-matrix-output-file-path\", STRING_T,  STRING_T(\"P_Q_matrix.mtx\"));\n\n  }\n  catch(exception &e)\n  {\n    cerr << \"\\n processInputArgs error: \" << e.what() << \"\\n\";\n    return false;\n  }\n  return true;\n}\n\nvoid Sleep() {\n  cout << \"\\n\\n\\n\\n\\n\\nSleeping for 10 seconds \\n\";\n  system(\"sleep 10\");\n}\n\nvoid printHeader() {\n  cout << \"\\n\\n\\n=================================================\\n\";\n  cout << \"=============== START TRAINING ==================\\n\";\n  cout << \"=================================================\\n\\n\";\n}\n\nint startMatrixFactorization_Trainer(int argc, char * argv[])\n{\n  ProgOpts::variables_map vmp; // varmap\n  MatrixFactorizationParams params;\n\n  bool b = processInputArgs(argc, argv, vmp, params);\n  if(!b)\n    return 3;\n\n  printHeader();\n  FLT_T rmseSum = 0;\n  FLT_T iterationCount = 0;\n\n  for(int i=0; i<params.loop_mode_count; i++) {\n    MatrixFactorization trainer(params);\n    if(!trainer.startTraining()) {\n      cout << \"Training failed check input files and training params\\n\";\n      return 4;\n    }\n    cout << \"Trial \" << i << \" finalRMSE \" << trainer.getFinalRMSE()\n      << \" num iterations \" << trainer.getNumIterations() << \"\\n\";\n    rmseSum += trainer.getFinalRMSE();\n    iterationCount += 1;\n    trainer.printPredictedValues(10);\n  }\n  cout << \" avg RMSE \" << (rmseSum/iterationCount)\n    << \" found using \"<< iterationCount << \" trials \\n\";\n  return 0;\n}\n\nint main(int argc, char * argv[])\n{\n  return startMatrixFactorization_Trainer(argc, argv);\n}\n", "meta": {"hexsha": "66a5ee90c447e2a26b009959fa00c3c0f5b40490", "size": 7380, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CppImpl/HiddenFact/HiddenFactorsLearner.cpp", "max_stars_repo_name": "kingjuliyen/RecommenderSystemExplicit", "max_stars_repo_head_hexsha": "fced2f88f9f7d795da142cf309869a184e3b2f43", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CppImpl/HiddenFact/HiddenFactorsLearner.cpp", "max_issues_repo_name": "kingjuliyen/RecommenderSystemExplicit", "max_issues_repo_head_hexsha": "fced2f88f9f7d795da142cf309869a184e3b2f43", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CppImpl/HiddenFact/HiddenFactorsLearner.cpp", "max_forks_repo_name": "kingjuliyen/RecommenderSystemExplicit", "max_forks_repo_head_hexsha": "fced2f88f9f7d795da142cf309869a184e3b2f43", "max_forks_repo_licenses": ["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.461928934, "max_line_length": 107, "alphanum_fraction": 0.6651761518, "num_tokens": 1951, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.47085325401069184}}
{"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/dls_pnp.h\"\n\n#include <Eigen/Core>\n#include <Eigen/Eigenvalues>\n#include <Eigen/Geometry>\n#include <glog/logging.h>\n#include <cmath>\n#include <vector>\n\n#include \"theia/util/random.h\"\n#include \"theia/sfm/pose/dls_impl.h\"\n\nnamespace theia {\n\nusing Eigen::Matrix3d;\nusing Eigen::Matrix;\nusing Eigen::MatrixXd;\nusing Eigen::Quaterniond;\nusing Eigen::Vector2d;\nusing Eigen::Vector3d;\nusing dls_impl::CreateMacaulayMatrix;\nusing dls_impl::ExtractJacobianCoefficients;\nusing dls_impl::LeftMultiplyMatrix;\n\n// This implementation is ported from the Matlab version provided by the authors\n// of \"A Direct Least-Squares (DLS) Method for PnP\". The general approach is to\n// first rewrite the reprojection constraint (i.e., cost function) such that all\n// unknowns appear linearly in terms of the rotation parameters (which are 3\n// parameters in the Cayley-Gibss-Rodriguez formulation). Then we create a\n// system of equations from the jacobian of the cost function, and solve these\n// equations via a Macaulay matrix to obtain the roots (i.e., the 3 parameters\n// of rotation). The translation can then be obtained through back-substitution.\nvoid DlsPnp(const std::vector<Vector2d>& feature_position,\n            const std::vector<Vector3d>& world_point,\n            std::vector<Quaterniond>* solution_rotation,\n            std::vector<Vector3d>* solution_translation) {\n  CHECK_GE(feature_position.size(), 3);\n  CHECK_EQ(feature_position.size(), world_point.size());\n\n  const int num_correspondences = feature_position.size();\n\n  // Holds the normalized feature positions cross multiplied with itself\n  // i.e. n * n^t. This value is used multiple times so it is efficient to\n  // pre-compute it.\n  std::vector<Matrix3d> normalized_feature_cross;\n  normalized_feature_cross.reserve(num_correspondences);\n  for (int i = 0; i < num_correspondences; i++) {\n    const Vector3d normalized_feature_pos =\n        feature_position[i].homogeneous().normalized();\n    normalized_feature_cross.push_back(normalized_feature_pos *\n                                       normalized_feature_pos.transpose());\n  }\n\n  // The bottom-right symmetric block matrix of inverse(A^T * A). Matrix H from\n  // Eq. 25 in the Appendix of the DLS paper.\n  Matrix3d h_inverse = num_correspondences * Matrix3d::Identity();\n  for (int i = 0; i < num_correspondences; i++) {\n    h_inverse = h_inverse - normalized_feature_cross[i];\n  }\n  const Matrix3d h_matrix = h_inverse.inverse();\n\n  // Compute V*W*b with the rotation parameters factored out. This is the\n  // translation parameterized by the 9 entries of the rotation matrix.\n  Matrix<double, 3, 9> translation_factor = Matrix<double, 3, 9>::Zero();\n  for (int i = 0; i < num_correspondences; i++) {\n    translation_factor = translation_factor +\n                         (normalized_feature_cross[i] - Matrix3d::Identity()) *\n                             LeftMultiplyMatrix(world_point[i]);\n  }\n\n  translation_factor = h_matrix * translation_factor;\n\n  // Compute the cost function J' of Eq. 17 in DLS paper. This is a factorized\n  // version where the rotation matrix parameters have been pulled out. The\n  // entries to this equation are the coefficients to the cost function which is\n  // a quartic in the rotation parameters.\n  Matrix<double, 9, 9> ls_cost_coefficients = Matrix<double, 9, 9>::Zero();\n  for (int i = 0; i < num_correspondences; i++) {\n    ls_cost_coefficients =\n        ls_cost_coefficients +\n        (LeftMultiplyMatrix(world_point[i]) + translation_factor).transpose() *\n            (Matrix3d::Identity() - normalized_feature_cross[i]) *\n            (LeftMultiplyMatrix(world_point[i]) + translation_factor);\n  }\n\n  // Extract the coefficients of the jacobian (Eq. 18) from the\n  // ls_cost_coefficients matrix. The jacobian represent 3 monomials in the\n  // rotation parameters. Each entry of the jacobian will be 0 at the roots of\n  // the polynomial, so we can arrange a system of polynomials from these\n  // equations.\n  double f1_coeff[20];\n  double f2_coeff[20];\n  double f3_coeff[20];\n  ExtractJacobianCoefficients(ls_cost_coefficients, f1_coeff, f2_coeff,\n                              f3_coeff);\n\n  // We create one equation with random terms that is generally non-zero at the\n  // roots of our system.\n  const double macaulay_term[4] = { RandDouble(0.0, 100.0),\n                                    RandDouble(0.0, 100.0),\n                                    RandDouble(0.0, 100.0),\n                                    RandDouble(0.0, 100.0) };\n\n  // Create Macaulay matrix that will be used to solve our polynonomial system.\n  const MatrixXd& macaulay_matrix =\n      CreateMacaulayMatrix(f1_coeff, f2_coeff, f3_coeff, macaulay_term);\n\n  // Via the Schur complement trick, the top-left of the Macaulay matrix\n  // contains a multiplication matrix whose eigenvectors correspond to solutions\n  // to our system of equations.\n  const MatrixXd solution_polynomial =\n      macaulay_matrix.block<27, 27>(0, 0) -\n      (macaulay_matrix.block<27, 93>(0, 27) *\n       macaulay_matrix.block<93, 93>(27, 27).partialPivLu().solve(\n           macaulay_matrix.block<93, 27>(27, 0)));\n\n  // Extract eigenvectors of the solution polynomial to obtain the roots which\n  // are contained in the entries of the eigenvectors.\n  const Eigen::EigenSolver<MatrixXd> eigen_solver(solution_polynomial);\n\n  // Many of the eigenvectors will contain complex solutions so we must filter\n  // them to find the real solutions.\n  const auto eigen_vectors = eigen_solver.eigenvectors();\n  for (int i = 0; i < 27; i++) {\n    // The first entry of the eigenvector should equal 1 according to our\n    // polynomial, so we must divide each solution by the first entry.\n    std::complex<double> s1 = eigen_vectors(9, i) / eigen_vectors(0, i);\n    std::complex<double> s2 = eigen_vectors(3, i) / eigen_vectors(0, i);\n    std::complex<double> s3 = eigen_vectors(1, i) / eigen_vectors(0, i);\n\n    // If the rotation solutions are real, treat this as a valid candidate\n    // rotation.\n    const double kEpsilon = 1e-6;\n    if (fabs(s1.imag()) < kEpsilon && fabs(s2.imag()) < kEpsilon &&\n        fabs(s3.imag()) < kEpsilon) {\n      // Compute the rotation (which is the transpose rotation of our solution)\n      // and translation.\n      Quaterniond soln_rotation(1.0, s1.real(), s2.real(), s3.real());\n      soln_rotation = soln_rotation.inverse().normalized();\n\n      const Matrix3d rot_mat = soln_rotation.inverse().toRotationMatrix();\n      const Eigen::Map<const Matrix<double, 9, 1> > rot_vec(rot_mat.data());\n      const Vector3d soln_translation = translation_factor * rot_vec;\n\n      // TODO(cmsweeney): evaluate cost function and return it as an output\n      // variable.\n\n      // Check that all points are in front of the camera. Discard the solution\n      // if this is not the case.\n      bool all_points_in_front_of_camera = true;\n      for (int j = 0; j < num_correspondences; j++) {\n        const Vector3d transformed_point =\n            soln_rotation * world_point[j] + soln_translation;\n        if (transformed_point.z() < 0) {\n          all_points_in_front_of_camera = false;\n          break;\n        }\n      }\n\n      if (all_points_in_front_of_camera) {\n        solution_rotation->push_back(soln_rotation);\n        solution_translation->push_back(soln_translation);\n      }\n    }\n  }\n}\n\n}  // namespace theia\n", "meta": {"hexsha": "ba8acdff76a676e0ffcab0a4c2ce91b3f84f8e1a", "size": 9156, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/sfm/pose/dls_pnp.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/pose/dls_pnp.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/pose/dls_pnp.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": 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": 45.1034482759, "max_line_length": 80, "alphanum_fraction": 0.7029270424, "num_tokens": 2191, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.4708532435178515}}
{"text": "#include \"cnn/dnn.h\"\n#include \"cnn/macros.h\"\n#include <string>\n#include <cassert>\n#include <vector>\n#include <iostream>\n#include <boost/lexical_cast.hpp>\n#include \"cnn/nodes.h\"\n#include \"cnn/expr-xtra.h\"\n\nusing namespace std;\nusing namespace cnn::expr;\nusing namespace cnn;\n\nnamespace cnn {\n\n    enum { X2H = 0, X2HB };\n\n    void DNNBuilder::display(ComputationGraph& cg) {\n\n        for (unsigned i = 0; i < layers; ++i) {\n            const std::vector<Expression>& vars = param_vars[i];\n            for (size_t i = 0; i < vars.size(); i++)\n                display_value(vars[i], cg);\n        }\n    }\n\n    DNNBuilder::DNNBuilder(unsigned ilayers,\n        const vector<unsigned>& dims,\n        Model* model,\n        cnn::real iscale,\n        string name) \n    {\n        unsigned input_dim = dims[INPUT_LAYER];\n        unsigned hidden_dim = dims[HIDDEN_LAYER];\n        unsigned output_dim = dims[OUTPUT_LAYER];\n\n        layers = ilayers;\n        unsigned int layer_input_dim = input_dim;\n        input_dims = vector<unsigned>(layers, layer_input_dim);\n\n        for (unsigned i = 0; i < layers; ++i) {\n            input_dims[i] = layer_input_dim;\n\n            unsigned int odim = (i == layers - 1) ? output_dim : hidden_dim;\n            string i_name = \"\";\n            if (name.size() > 0)\n                i_name = name + \"p_x2h\" + boost::lexical_cast<string>(i);\n            Parameters* p_x2h = model->add_parameters({ (odim), layer_input_dim }, iscale, i_name);\n            if (name.size() > 0)\n                i_name = name + \"p_x2hb\" + boost::lexical_cast<string>(i);\n            Parameters* p_x2hb = model->add_parameters({ (odim) }, iscale, i_name);\n            vector<Parameters*> ps = { p_x2h, p_x2hb };\n            params.push_back(ps);\n            layer_input_dim = hidden_dim;\n        }\n    }\n\n    void DNNBuilder::new_graph_impl(ComputationGraph& cg) {\n        param_vars.clear();\n        for (unsigned i = 0; i < layers; ++i) {\n            Parameters* p_x2h = params[i][X2H];\n            Parameters* p_x2hb = params[i][X2HB];\n            Expression i_x2h = parameter(cg, p_x2h);\n            Expression i_x2hb = parameter(cg, p_x2hb);\n            vector<Expression> vars = { i_x2h, i_x2hb };\n\n            param_vars.push_back(vars);\n        }\n        set_data_in_parallel(1);\n    }\n\n    void DNNBuilder::set_data_in_parallel(int n)\n    {\n        dparallel = n;\n\n        biases.clear();\n        for (unsigned i = 0; i < layers; ++i) {\n            const vector<Expression>& vars = param_vars[i];\n            Expression bimb = concatenate_cols(vector<Expression>(data_in_parallel(), vars[X2HB]));\n\n            vector<Expression> b = { bimb };\n            biases.push_back(b);\n        }\n    }\n\n    Expression DNNBuilder::add_input_impl(const Expression &in) {\n        h.resize(layers);\n\n        Expression x = in;\n\n        for (unsigned i = 0; i < layers; ++i) {\n            const vector<Expression>& vars = param_vars[i];\n\n            Expression y = affine_transform({ biases[i][0], vars[0], x });\n\n            x = h[i] = tanh(y);\n        }\n        return h.back();\n    }\n\n\n    void DNNBuilder::copy(const DNNBuilder & rnn) {\n        const DNNBuilder& rnn_simple = (const DNNBuilder&)rnn;\n        assert(params.size() == rnn_simple.params.size());\n        for (size_t i = 0; i < rnn_simple.params.size(); ++i) {\n            params[i][0]->copy(*rnn_simple.params[i][0]);\n            params[i][1]->copy(*rnn_simple.params[i][1]);\n        }\n    }\n\n    Expression ReluDNNBuilder::add_input_impl(const Expression &in)  {\n        h.resize(layers);\n\n        Expression x = in;\n\n        for (unsigned i = 0; i < layers; ++i) {\n            const vector<Expression>& vars = param_vars[i];\n\n            Expression y = affine_transform({ biases[i][0], vars[0], x });\n\n            x = h[i] = rectify(y);\n        }\n        return h.back();\n    }\n\n\n} // namespace cnn\n", "meta": {"hexsha": "7d7d80c7e333585efa4a4dca1f74797d462f4e86", "size": 3859, "ext": "cc", "lang": "C++", "max_stars_repo_path": "cnn/dnn.cc", "max_stars_repo_name": "kaishengyao/cnn", "max_stars_repo_head_hexsha": "a034b837e88f82bd8adf2c5b0a5defb26fd52096", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2015-09-10T07:50:50.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-17T03:02:38.000Z", "max_issues_repo_path": "cnn/dnn.cc", "max_issues_repo_name": "kaishengyao/cnn", "max_issues_repo_head_hexsha": "a034b837e88f82bd8adf2c5b0a5defb26fd52096", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cnn/dnn.cc", "max_forks_repo_name": "kaishengyao/cnn", "max_forks_repo_head_hexsha": "a034b837e88f82bd8adf2c5b0a5defb26fd52096", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2015-09-08T12:43:13.000Z", "max_forks_repo_forks_event_max_datetime": "2018-09-26T07:32:47.000Z", "avg_line_length": 29.9147286822, "max_line_length": 99, "alphanum_fraction": 0.5576574242, "num_tokens": 984, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.4708532435178515}}
{"text": "#pragma once\n\n#include \"../Math/math.hh\"\n\n#include <Eigen/Core>\n\nnamespace bold\n{\n/*\n  enum class PointType\n  {\n    /// The point is on the lower bound of an occlusion.\n    /// In 2D, this is the bottom of the image.\n    /// In 3D this is the nearest point in the occluded area along a ray from the viewer.\n    Occlusion = 1,\n    /// The point is visually at the top of an area considered as the field, although this may be the camera edge\n    FieldEdge = 2,\n    /// Point is located at the boundary of the camera image\n    CameraEdge = 3\n  };\n*/\n\n  template<typename T,int Dim=2>\n  class OcclusionRay\n  {\n  public:\n    typedef Eigen::Matrix<T,Dim,1> Point;\n\n    OcclusionRay(Point near, Point far/*, PointType nearType, PointType farType*/)\n    : d_near(near),\n      d_far(far)/*,\n      d_nearType(nearType),\n      d_farType(farType)*/\n    {}\n\n    Point const& near() const { return d_near; }\n    Point const& far() const { return d_far; }\n//    PointType const& nearType() const { return d_nearType; }\n//    PointType const& farType() const { return d_farType; }\n\n    double constexpr norm() const { return (d_near - d_far).norm(); }\n    double constexpr angle() const { return Math::angleToPoint(d_near); }\n\n//    double distance() const;\n//    bool isOpenField() const;\n//    bool isOcclusion() const;\n//    bool isFieldEdge() const;\n\n  private:\n    Point d_near;\n    Point d_far;\n//    PointType d_nearType;\n//    PointType d_farType;\n  };\n}\n", "meta": {"hexsha": "fb4732301d93983db49489b78051b458f4cc385c", "size": 1447, "ext": "hh", "lang": "C++", "max_stars_repo_path": "OcclusionRay/occlusionray.hh", "max_stars_repo_name": "drewnoakes/bold-humanoid", "max_stars_repo_head_hexsha": "6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "OcclusionRay/occlusionray.hh", "max_issues_repo_name": "drewnoakes/bold-humanoid", "max_issues_repo_head_hexsha": "6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "OcclusionRay/occlusionray.hh", "max_forks_repo_name": "drewnoakes/bold-humanoid", "max_forks_repo_head_hexsha": "6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335", "max_forks_repo_licenses": ["Apache-2.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.8392857143, "max_line_length": 113, "alphanum_fraction": 0.6482377332, "num_tokens": 388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152325073083131, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.47079299451935924}}
{"text": "#ifndef icvEigenMatrixData_hxx\r\n#define icvEigenMatrixData_hxx\r\n\r\n#include \"OpenICV/Core/icvDataObject.h\"\r\n\r\n#include <Eigen/Core>\r\n#include <boost/utility/enable_if.hpp>\r\n\r\nnamespace icv\r\n{\r\n    namespace eigen\r\n    {\r\n        template <typename _Scalar, int _Rows, int _Cols,\r\n            int _Options = Eigen::AutoAlign | \r\n                ( (_Rows == 1 && _Cols != 1) ? Eigen::RowMajor\r\n                : (_Cols == 1 && _Rows != 1) ? Eigen::ColMajor\r\n                : EIGEN_DEFAULT_MATRIX_STORAGE_ORDER_OPTION),\r\n            int _MaxRows = _Rows, int _MaxCols = _Cols>\r\n        class icvEigenMatrixData : icv::core::icvDataObject\r\n        {\r\n        public:\r\n            typedef Eigen::Matrix<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols> UType;\r\n            typedef icvEigenMatrixData<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols> SelfType;\r\n\r\n        public:\r\n            icvEigenMatrixData()\r\n            {\r\n                BOOST_STATIC_ASSERT_MSG(UType::SizeAtCompileTime != Eigen::Dynamic,\r\n                    \"You shouldn't initialize a dynamic matrix without a shape.\");\r\n            }\r\n            icvEigenMatrixData(uint32_t dim) : _init_arg1(dim)\r\n            {\r\n                BOOST_STATIC_ASSERT_MSG((UType::IsVectorAtCompileTime && UType::SizeAtCompileTime == Eigen::Dynamic),\r\n                    \"You should initialize a dynamic vector giving a dimension.\");\r\n            }\r\n            icvEigenMatrixData(uint32_t rows, uint32_t cols) : _init_arg1(rows), _init_arg2(cols)\r\n            {\r\n                // FIXME: Following statement doesn;t work properly...\r\n                // BOOST_STATIC_ASSERT_MSG((!UType::IsVectorAtCompileTime && UType::SizeAtCompileTime == Eigen::Dynamic),\r\n                //     \"You should initialize a dynamic matrix giving a shape.\");\r\n            }\r\n\r\n            virtual void Reserve() ICV_OVERRIDE\r\n            {\r\n                if (!_data)\r\n                {\r\n                    _new();\r\n                }\r\n            }\r\n            virtual void Dispose() ICV_OVERRIDE\r\n            {\r\n                if (_data) delete _data;\r\n                _data = ICV_NULLPTR;\r\n            }\r\n\r\n            virtual Uint64 GetActualMemorySize() ICV_OVERRIDE\r\n            {\r\n                if (_data) return _data->rows() * _data->cols() * sizeof(_Scalar);\r\n                else return 0;\r\n            }\r\n\r\n            virtual void Serialize(std::stringstream& out, const uint32_t& version) const ICV_OVERRIDE\r\n            {\r\n                ICV_THROW_MESSAGE(\"Directly serialize icvEigenMatrixData is not supported, please convert it to icvTensorData\");\r\n            }\r\n            virtual void Deserialize(std::stringstream& in, const uint32_t& version) ICV_OVERRIDE\r\n            {\r\n                ICV_THROW_MESSAGE(\"Directly serialize icvEigenMatrixData is not supported, please convert it from icvTensorData\");\r\n            }\r\n\r\n            virtual icv::core::icvDataObject* DeepCopy() ICV_OVERRIDE\r\n            {\r\n                SelfType* copy = new SelfType(_init_arg1, _init_arg2);\r\n                copy->_sourceTime = _sourceTime;\r\n                copy->_init_arg1 = _init_arg1;\r\n                copy->_init_arg2 = _init_arg2;\r\n                copy->Reserve(); *(copy->_data) = *_data;\r\n                return copy;\r\n            }\r\n\r\n            virtual std::string Print() ICV_OVERRIDE\r\n            {\r\n                return \"Eigen::Matrix\";\r\n            }\r\n\r\n            operator const UType&() const { return *_data; }\r\n\r\n            UType* operator->() { return _data; }\r\n            const UType* operator->() const { return _data; }\r\n\r\n            SelfType& operator = (const UType& data)\r\n            {\r\n                *_data = data;\r\n                return *this;\r\n            }\r\n\r\n        private:\r\n            UType * _data = ICV_NULLPTR;\r\n\r\n            // Params only for initialization\r\n            uint32_t _init_arg1, _init_arg2;\r\n\r\n        private:\r\n            template<class M = UType, typename boost::enable_if<boost::integral_constant<bool,\r\n                M::IsVectorAtCompileTime && M::SizeAtCompileTime == Eigen::Dynamic>, int>::type = 0>\r\n            void _new()\r\n            {\r\n                _data = new M(_init_arg1);\r\n            }\r\n\r\n            template<class M = UType, typename boost::enable_if<boost::integral_constant<bool,\r\n                !M::IsVectorAtCompileTime && M::SizeAtCompileTime == Eigen::Dynamic>, int>::type = 0>\r\n            void _new()\r\n            {\r\n                _data = new M(_init_arg1, _init_arg2);\r\n            }\r\n\r\n            template<class M = UType, typename boost::enable_if<boost::integral_constant<bool,\r\n                M::SizeAtCompileTime != Eigen::Dynamic>, int>::type = 0>\r\n            void _new()\r\n            {\r\n                _data = new M();\r\n            }\r\n        };\r\n\r\n        #define EIGEN_MAKE_TYPEDEFS(Type, TypeSuffix, Size, SizeSuffix)                             \\\r\n        /** \\ingroup matrixtypedefs */                                                              \\\r\n        typedef icvEigenMatrixData<Type, Size, Size> icvEigenMatrix##SizeSuffix##TypeSuffix##Data;  \\\r\n        /** \\ingroup matrixtypedefs */                                                              \\\r\n        typedef icvEigenMatrixData<Type, Size, 1>    icvEigenVector##SizeSuffix##TypeSuffix##Data;  \\\r\n        /** \\ingroup matrixtypedefs */                                                              \\\r\n        typedef icvEigenMatrixData<Type, 1, Size>    icvEigenRowVector##SizeSuffix##TypeSuffix##Data;\r\n\r\n        #define EIGEN_MAKE_FIXED_TYPEDEFS(Type, TypeSuffix, Size)                                         \\\r\n        /** \\ingroup matrixtypedefs */                                                                    \\\r\n        typedef icvEigenMatrixData<Type, Size, Eigen::Dynamic> icvEigenMatrix##Size##X##TypeSuffix##Data; \\\r\n        /** \\ingroup matrixtypedefs */                                                                    \\\r\n        typedef icvEigenMatrixData<Type, Eigen::Dynamic, Size> icvEigenMatrix##X##Size##TypeSuffix##Dara;\r\n\r\n        #define EIGEN_MAKE_TYPEDEFS_ALL_SIZES(Type, TypeSuffix) \\\r\n                EIGEN_MAKE_TYPEDEFS(Type, TypeSuffix, 2, 2) \\\r\n                EIGEN_MAKE_TYPEDEFS(Type, TypeSuffix, 3, 3) \\\r\n                EIGEN_MAKE_TYPEDEFS(Type, TypeSuffix, 4, 4) \\\r\n                EIGEN_MAKE_TYPEDEFS(Type, TypeSuffix, Eigen::Dynamic, X) \\\r\n                EIGEN_MAKE_FIXED_TYPEDEFS(Type, TypeSuffix, 2) \\\r\n                EIGEN_MAKE_FIXED_TYPEDEFS(Type, TypeSuffix, 3) \\\r\n                EIGEN_MAKE_FIXED_TYPEDEFS(Type, TypeSuffix, 4)\r\n\r\n        EIGEN_MAKE_TYPEDEFS_ALL_SIZES(int, i)\r\n        EIGEN_MAKE_TYPEDEFS_ALL_SIZES(float, f)\r\n        EIGEN_MAKE_TYPEDEFS_ALL_SIZES(double, d)\r\n        // EIGEN_MAKE_TYPEDEFS_ALL_SIZES(std::complex<float>, cf)\r\n        // EIGEN_MAKE_TYPEDEFS_ALL_SIZES(std::complex<double>, cd)\r\n\r\n        #undef EIGEN_MAKE_TYPEDEFS_ALL_SIZES\r\n        #undef EIGEN_MAKE_TYPEDEFS\r\n        #undef EIGEN_MAKE_FIXED_TYPEDEFS\r\n    }\r\n}\r\n\r\n#endif // icvEigenMatrixData_hxx\r\n", "meta": {"hexsha": "ac5759a848b53f26f65fb5aa1edc7c966053656c", "size": 7070, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "Branch/Include/OpenICV/Extensions/Eigen/icvEigenMatrixData.hxx", "max_stars_repo_name": "Tsinghua-OpenICV/OpenICV", "max_stars_repo_head_hexsha": "37bf88122414d0c766491460248f61fa1a9fd78c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2019-12-17T08:17:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-14T03:13:10.000Z", "max_issues_repo_path": "Branch/Include/OpenICV/Extensions/Eigen/icvEigenMatrixData.hxx", "max_issues_repo_name": "Tsinghua-OpenICV/OpenICV", "max_issues_repo_head_hexsha": "37bf88122414d0c766491460248f61fa1a9fd78c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Branch/Include/OpenICV/Extensions/Eigen/icvEigenMatrixData.hxx", "max_forks_repo_name": "Tsinghua-OpenICV/OpenICV", "max_forks_repo_head_hexsha": "37bf88122414d0c766491460248f61fa1a9fd78c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-12-17T08:17:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T15:53:57.000Z", "avg_line_length": 43.6419753086, "max_line_length": 131, "alphanum_fraction": 0.5315417256, "num_tokens": 1587, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324983301567, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4707929893345155}}
{"text": "#include <algorithm>\n#include <fstream>\n#include <functional>\n#include <iostream>\n#include <numeric>\n#include <set>\n#include <string>\n#include <unordered_map>\n#include <vector>\n\n#include <boost/iterator/counting_iterator.hpp>\n\ntemplate<typename T>\nclass Range {\n\tprivate:\n\t\tboost::counting_iterator<T, boost::use_default, T> begin_, end_;\n\tpublic:\n\t\tRange(T b, T e): begin_(b), end_(e) {}\n\t\tauto begin() const { return begin_; }\n\t\tauto end() const { return end_; }\n};\n\nusing PersonID = unsigned;\n\nstruct SeatingPair {\n\tPersonID left_id;\n\tPersonID right_id;\n};\n\nauto operator==(const SeatingPair& lhs, const SeatingPair& rhs) {\n\treturn ((lhs.left_id == rhs.left_id) && (lhs.right_id == rhs.right_id))\n\t\t   || ((lhs.left_id == rhs.right_id) && (lhs.right_id == rhs.left_id));\n}\n\nusing Person = std::string;\n\nstruct SeatingPairEntry {\n\tPerson left_person;\n\tPerson right_person;\n\tunsigned score;\n};\n\nauto& operator>>(std::istream& in, SeatingPairEntry& entry) {\n\treturn in >> entry.left_person >> entry.score >> entry.right_person;\n}\n\nnamespace std {\n\ttemplate<>\n\tstruct hash<SeatingPair> {\n\t\tauto operator()(const SeatingPair& pair) const {\n\t\t\tconst auto [min, max] = std::minmax(pair.left_id, pair.right_id);\n\t\t\treturn (min * 10) + max;\n\t\t}\n\t};\n}\n\ntemplate<typename T>\nauto factorial(T n) {\n\tauto range = Range<T>{2, (n + 1)};\n\treturn std::accumulate(range.begin(), range.end(), T{1}, std::multiplies{});\n}\n\nint main() {\n\n\tconst auto filename = std::string{\"happiness.txt\"};\n\tauto file = std::fstream{filename};\n\n\tif(file.is_open()) {\n\n\t\t// std::set is used for its automatic ordering of keys,\n\t\t// which is important when iterating through permutations\n\t\t// of seating orders later on\n\t\tauto family_set = std::set<PersonID>{};\n\t\tauto family_map = std::unordered_map<Person, PersonID>{};\n\n\t\tusing PairHappiness = int;\n\t\tauto happymeter = std::unordered_map<SeatingPair, PairHappiness>{};\n\n\t\tconst auto add_family_member = [&family_map, &family_set] (const auto& member) {\n\n\t\t\tconst auto is_new = family_map.insert({member, {}}).second;\n\n\t\t\tif(is_new) {\n\t\t\t\tconst auto size = family_map.size();\n\t\t\t\tfamily_map[member] = size;\n\t\t\t\tfamily_set.insert(size);\n\t\t\t}\n\t\t};\n\n\t\tSeatingPairEntry entry;\n\n\t\twhile(file >> entry) {\n\n\t\t\tconst auto& left_person = entry.left_person;\n\t\t\tconst auto& right_person = entry.right_person;\n\n\t\t\tadd_family_member(left_person);\n\t\t\tadd_family_member(right_person);\n\n\t\t\tconst auto left_id = family_map[left_person];\n\t\t\tconst auto right_id = family_map[right_person];\n\n\t\t\thappymeter[{left_id, right_id}] += entry.score;\n\t\t}\n\n\t\t// elements must be sorted, fortunately std::set has already done that job for us\n\t\tauto seating = std::vector<PersonID>{family_set.begin(), family_set.end()};\n\n\t\t// only a subset of all possible permutations of seating orders is relevant for us,\n\t\t// so we create an upper limit to count down from when looping through permutations\n\t\tconst auto size = family_map.size();\n\t\tauto limit = (factorial(size) / size) * (size - 1);\n\n\t\tauto max_happiness = PairHappiness{};\n\n\t\tdo {\n\t\t\t// since the seating is circular, the pair [first, last] won't be\n\t\t\t// added in the algorithm, so we initialize the accumulator with it\n\t\t\tconst auto begin1 = seating.begin();\n\t\t\tconst auto end1\t  = std::prev(seating.end());\n\t\t\tconst auto begin2 = std::next(begin1);\n\t\t\tconst auto acc\t  = happymeter[{seating.front(), seating.back()}];\n\t\t\tconst auto op1\t  = std::plus{};\n\t\t\tconst auto op2\t  = [&happymeter] (auto a, auto b) { return happymeter[{a, b}];};\n\n\t\t\t// inner_product resolves to acc = op1(acc, op2(begin1, begin2)) in a loop\n\t\t\tauto sum = std::inner_product(begin1, end1, begin2, acc, op1, op2);\n\n\t\t\tmax_happiness = std::max(max_happiness, sum);\n\n\t\t} while((limit--) > 0 && std::next_permutation(seating.begin(), seating.end()));\n\n\t\tstd::cout << max_happiness << std::endl;\n\n\t} else {\n\t\tstd::cerr << \"Error! Could not open \\\"\" << filename << \"\\\"!\" << std::endl;\n\t}\n\n\treturn 0;\n}\n", "meta": {"hexsha": "d43cb8e303b45832f23596b04fb4b471e654d634", "size": 3913, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Day 13 Part 1/main.cpp", "max_stars_repo_name": "Miroslav-Cetojevic/aoc-2015", "max_stars_repo_head_hexsha": "2807fcd3fc684843ae4222b25af6fd086fac77f5", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-19T20:19:18.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-19T20:19:18.000Z", "max_issues_repo_path": "Day 13 Part 1/main.cpp", "max_issues_repo_name": "Miroslav-Cetojevic/aoc-2015", "max_issues_repo_head_hexsha": "2807fcd3fc684843ae4222b25af6fd086fac77f5", "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": "Day 13 Part 1/main.cpp", "max_forks_repo_name": "Miroslav-Cetojevic/aoc-2015", "max_forks_repo_head_hexsha": "2807fcd3fc684843ae4222b25af6fd086fac77f5", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7517730496, "max_line_length": 85, "alphanum_fraction": 0.6828520317, "num_tokens": 1041, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.47079298414967163}}
{"text": "\n// Copyright 2010-2014, D. E. Shaw Research.\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_RANDOM_PHILOX_HPP\n#define BOOST_RANDOM_PHILOX_HPP\n#include <boost/array.hpp>\n#include <boost/static_assert.hpp>\n#include <boost/cstdint.hpp>\n#include <boost/limits.hpp>\n#include <boost/random/detail/mulhilo.hpp>\n#include <boost/mpl/for_each.hpp>\n#include <boost/mpl/range_c.hpp>\n\nnamespace boost{\nnamespace random{\n\ntemplate <unsigned _N, typename Uint>\nstruct philox_constants{\n    // specializations will hold the Mutlipliers: M0, M1\n    // and the Weyl constants:  W0, W1\n};\n\ntemplate <>\nstruct philox_constants<2, uint64_t>{\n    static const uint64_t M0 = UINT64_C(0xD2B74407B1CE6E93);\n    static const uint64_t W0 = UINT64_C(0x9E3779B97F4A7C15);\n};\n\ntemplate <>\nstruct philox_constants<2, uint32_t>{\n    static const uint32_t M0 = UINT32_C(0xD256D193);\n    static const uint32_t W0 = UINT32_C(0x9E3779B9);\n};\n\ntemplate <>\nstruct philox_constants<4, uint64_t>{\n    static const uint64_t M0 = UINT64_C(0xD2E7470EE14C6C93);\n    static const uint64_t M1 = UINT64_C(0xCA5A826395121157);\n    static const uint64_t W0 = UINT64_C(0x9E3779B97F4A7C15);  /* golden ratio */\n    static const uint64_t W1 = UINT64_C(0xBB67AE8584CAA73B);  /* sqrt(3)-1 */\n};\n\ntemplate <>\nstruct philox_constants<4, uint32_t>{\n    static const uint32_t M0 = UINT32_C(0xD2511F53);\n    static const uint32_t M1 = UINT32_C(0xCD9E8D57);\n    static const uint32_t W0 = UINT64_C(0x9E3779B9);  /* golden ratio */\n    static const uint32_t W1 = UINT64_C(0xBB67AE85);  /* sqrt(3)-1 */\n};\n\ntemplate <unsigned N, typename Uint, unsigned R=10, typename Constants = philox_constants<N, Uint> >\nstruct philox{\n    BOOST_STATIC_ASSERT( N%2 == 0 );\n};\n\ntemplate <typename Uint, unsigned R, typename Constants>\nstruct philox<2, Uint, R, Constants> {\n    typedef array<Uint, 2> domain_type;\n    typedef array<Uint, 2> range_type;\n    typedef array<Uint, 1> key_type ;\n\n    philox() : k(){}\n    philox(key_type _k) : k(_k) {}\n    philox(const philox& v) : k(v.k){}\n\n    void setkey(key_type _k){\n        k = _k;\n    }\n\n    key_type getkey() const{\n        return k;\n    }\n\n    bool operator==(const philox& rhs) const{\n        return k == rhs.k;\n    }\n\n    bool operator!=(const philox& rhs) const{\n        return k != rhs.k;\n    }\n\n    range_type operator()(domain_type c){\n        key_type kcopy = k;\n#if 0   // using mpl to unroll the loop doesn't seem to help much.\n        _roundapplyer ra(c, kcopy);\n        mpl::for_each<mpl::range_c<unsigned, 0, R> >(ra);\n#else\n        for(unsigned r=0; r<R; ++r)\n            round(c, kcopy);\n#endif\n        return c;\n    }\nprotected:\n    static inline void round(domain_type& ctr, key_type& key){\n        Uint hi;\n        Uint lo = detail::mulhilo(Constants::M0, ctr[0], hi);\n        domain_type out = {{hi^key[0]^ctr[1], lo}};\n        ctr = out;\n        key[0] += Constants::W0;\n    }\n\n    struct _roundapplyer{\n        domain_type& c;\n        key_type& k;\n        _roundapplyer(domain_type& _c, key_type& _k): c(_c), k(_k){}\n        void operator()(unsigned){ round(c, k); }\n    };\n    key_type k;\n};\n\ntemplate<typename Uint, unsigned R, typename Constants>\nstruct philox<4, Uint, R, Constants> {\n    typedef array<Uint, 4> domain_type;\n    typedef array<Uint, 4> range_type;\n    typedef array<Uint, 2> key_type ;\npublic:\n\n    philox() : k(){}\n    philox(key_type _k) : k(_k) {}\n    philox(const philox& v) : k(v.k){}\n\n    void setkey(key_type _k){\n        k = _k;\n    }\n\n    key_type getkey() const{\n        return k;\n    }\n\n    bool operator==(const philox& rhs) const{\n        return k == rhs.k;\n    }\n\n    bool operator!=(const philox& rhs) const{\n        return k != rhs.k;\n    }\n\n    range_type operator()(domain_type c){\n        key_type kcopy = k;\n#if 0   // using mpl to unroll the loop doesn't seem to help much.\n        _roundapplyer ra(c, kcopy);\n        mpl::for_each<mpl::range_c<unsigned, 0, R> >(ra);\n#else\n        for(unsigned r=0; r<R; ++r)\n            round(c, kcopy);\n#endif\n        return c;\n    }\n\nprotected:\n    static inline void round(domain_type& ctr, key_type& key){\n        Uint hi0;\n        Uint hi1;\n        Uint lo0 = detail::mulhilo(Constants::M0, ctr[0], hi0);\n        Uint lo1 = detail::mulhilo(Constants::M1, ctr[2], hi1);\n        domain_type out = {{hi1^ctr[1]^key[0], lo1,\n                                      hi0^ctr[3]^key[1], lo0}};\n        ctr = out;\n        key[0] += Constants::W0;\n        key[1] += Constants::W1;\n    }\n\n    struct _roundapplyer{\n        domain_type& c;\n        key_type& k;\n        _roundapplyer(domain_type& _c, key_type& _k): c(_c), k(_k){}\n        void operator()(unsigned){ round(c, k); }\n    };\n\n    key_type k;\n};\n\n} // namespace random\n} // namespace boost\n\n#endif // BOOST_RANDOM_PHILOX_HPP\n", "meta": {"hexsha": "54d59f1d2b49e52b092399c21ea0c7acf2969d87", "size": 4879, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/random/philox.hpp", "max_stars_repo_name": "DEShawResearch/Random123-Boost", "max_stars_repo_head_hexsha": "65e3d874b67aa7b3e02d5ad8306462f52d2079c0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2015-04-08T18:40:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T00:08:25.000Z", "max_issues_repo_path": "boost/random/philox.hpp", "max_issues_repo_name": "DEShawResearch/Random123-Boost", "max_issues_repo_head_hexsha": "65e3d874b67aa7b3e02d5ad8306462f52d2079c0", "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/random/philox.hpp", "max_forks_repo_name": "DEShawResearch/Random123-Boost", "max_forks_repo_head_hexsha": "65e3d874b67aa7b3e02d5ad8306462f52d2079c0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1055555556, "max_line_length": 100, "alphanum_fraction": 0.6255380201, "num_tokens": 1481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.47079298414967163}}
{"text": "/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\\n|  Phycas: Python software for phylogenetic analysis                          |\n|  Copyright (C) 2012 Mark T. Holder, Paul O. Lewis and David L. Swofford     |\n|                                                                             |\n|  This program is free software; you can redistribute it and/or modify       |\n|  it under the terms of the GNU General Public License as published by       |\n|  the Free Software Foundation; either version 2 of the License, or          |\n|  (at your option) any later version.                                        |\n|                                                                             |\n|  This program is distributed in the hope that it will be useful,            |\n|  but WITHOUT ANY WARRANTY; without even the implied warranty of             |\n|  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the              |\n|  GNU General Public License for more details.                               |\n|                                                                             |\n|  You should have received a copy of the GNU General Public License along    |\n|  with this program; if not, write to the Free Software Foundation, Inc.,    |\n|  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.                |\n\\~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n\n#if !defined(TREE_LENGTH_DISTRIBUTION_HPP)\n#define TREE_LENGTH_DISTRIBUTION_HPP\n\n#if defined(_MSC_VER)\n#\tpragma warning(disable: 4267)\t// warning about loss of data when converting size_t to int\n#endif\n\n#include <cmath>\n#include \"ncl/nxsdefs.h\"\n\n#include <boost/shared_ptr.hpp>\n#include <boost/format.hpp>\n#include \"basic_cdf.hpp\"\n#include \"basic_lot.hpp\"\n#include \"basic_tree.hpp\"\n#include \"probability_distribution.hpp\"\n#include \"multivariate_probability_distribution.hpp\"\n\nnamespace phycas\n{\n\n/*------------------------------------------------------------------------------------------------------------------------------------------------------------------\n|\tThis is the joint distribution of tree length and edge lengths. The marginal distribution of tree length is Gamma(alphaT, betaT), while the marginal\n|   of edge lengths conditional on tree length is Dirichlet(a_1, a_2, ..., a_m, b_1, b_2, ..., b_n) where a_1=a_2=...=a_m=alpha, b_1=b_2=...=b_n=c*alpha,\n|   m is the number of external edges, and n is the number of internal edges. This prior was described in the following paper:\n|\n|   Rannala, Bruce, Tianqi Zhu, and Ziheng Yang. 2012. Tail paradox, partial identifiability, and influential priors in Bayesian branch length inference.\n|   Mol. Biol. Evol. 29(1):325-335.\n|\n|   Note 1: this class follows the conventions of the paper in that the gamma distribution mean equals shape/scale, whereas everywhere else a gamma distribution\n|   appears in Phycas it has the property that mean equals shape*scale.\n|\n|   Note 2: this class is unusual in that it represents a probability distribution but is not derived from either ProbabilityDistribution or\n|   MultivariateProbabilityDistribution. This is because it is a compound distribution combining a univariate (gamma) distribution with a multivariate\n|   (Dirichlet) distribution, and requires a tree as input to its GetLnPDF function.\n*/\nclass TreeLengthDistribution   // TREE_LENGTH_DISTRIBUTION\n\t{\n\tpublic:\n\t\t\t\t\t\t\t\t\t\t\tTreeLengthDistribution();\n\t\t\t\t\t\t\t\t\t\t\tTreeLengthDistribution(double alphaT, double betaT, double alpha, double c);\n                        \t\t\t\t\tTreeLengthDistribution(const TreeLengthDistribution & other);\n\t\tvirtual\t\t\t\t\t\t\t\t~TreeLengthDistribution() {}\n\n\t\tvirtual void\t\t\t\t\t\tSetLot(Lot * other);\n\t\tvirtual void\t\t\t\t\t\tResetLot();\n\t\tvirtual void\t\t\t\t\t\tSetSeed(unsigned rnseed);\n\n        TreeLengthDistribution * \t\t\tcloneAndSetLot(Lot * other) const;\n        TreeLengthDistribution * \t\t\tClone() const;\n\n\t\tvirtual std::string                 GetDistributionName() const;\n\t\tvirtual std::string \t\t\t\tGetDistributionDescription() const;\n\t\tvirtual std::vector<double>\t\t\tSample(unsigned num_external, unsigned num_internal);\n\t\tvirtual double\t\t\t\t\t\tGetLnPDF(TreeShPtr t) const;\n\t\tvirtual double\t\t\t\t\t\tGetRelativeLnPDF(TreeShPtr t) const;\n\n        double                              getShape() const {return _alphaT;}\n        double                              getScale() const {return _betaT;}\n        double                              getExtEdgelenParam() const {return _alpha;}\n        double                              getIntExtEdgelenRatio() const {return _c;}\n\n    protected:\n\n        void                                SetupSamplingDistributions(unsigned num_external, unsigned num_internal);\n\n    private:\n\n\t\tdouble\t\t\t\t\t\t\t\t_alphaT;                /**< The shape parameter of the gamma tree length distribution */\n\t\tdouble\t\t\t\t\t\t\t\t_betaT;                 /**< The scale paramter of the gamma tree length distribution */\n\t\tdouble\t\t\t\t\t\t\t\t_alpha;                 /**< The parameter governing the Dirichlet distribution for external edge lengths (internal edge lengths have parameter c*alpha) */\n\t\tdouble\t\t\t\t\t\t\t\t_c;                     /**< The ratio of the mean internal/external edge length (normally less than 1.0) */\n\n        CDF                                 _cdf;                   /**< Used in GetLnPDF to compute log of gamma function */\n\t\tLot                                 _myLot;                 /**< Own random number generator */\n\t\tLot *                               _lot;                   /**< Points to either _myLot or an external random number generator object */\n\n        ProbDistShPtr                       _tldist;                /**< Points to a gamma distribution of tree lengths used when sampling from this distribution */\n        MultivarProbDistShPtr               _eldist;                /**< Points to a Dirichlet distribution of edge length proportions used when sampling from this distribution */\n        unsigned                            _num_internal_edges;    /**< The number of internal edges specified the last time Sample was called */\n        unsigned                            _num_external_edges;    /**< The number of external edges specified the last time Sample was called */\n\t};\n\ntypedef boost::shared_ptr<TreeLengthDistribution> TreeLengthDistributionShPtr;\n\n} // namespace phycas\n\n#endif\n\n", "meta": {"hexsha": "66d55c7066071344ba0a16fbd9dbb7777ac8c6ba", "size": 6357, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/cpp/tree_length_distribution.hpp", "max_stars_repo_name": "plewis/phycas", "max_stars_repo_head_hexsha": "9f5a4d9b2342dab907d14a46eb91f92ad80a5605", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-09-24T23:12:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-12T07:07:01.000Z", "max_issues_repo_path": "src/cpp/tree_length_distribution.hpp", "max_issues_repo_name": "plewis/phycas", "max_issues_repo_head_hexsha": "9f5a4d9b2342dab907d14a46eb91f92ad80a5605", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cpp/tree_length_distribution.hpp", "max_forks_repo_name": "plewis/phycas", "max_forks_repo_head_hexsha": "9f5a4d9b2342dab907d14a46eb91f92ad80a5605", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-11-23T10:35:43.000Z", "max_forks_repo_forks_event_max_datetime": "2015-11-23T10:35:43.000Z", "avg_line_length": 58.3211009174, "max_line_length": 179, "alphanum_fraction": 0.5914739657, "num_tokens": 1244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324803738429, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.47079297896482747}}
{"text": "// Boost.GIL (Generic Image Library) - tests\n//\n// Copyright 2020 Olzhas Zhumabek <anonymous.from.applecity@gmail.com>\n//\n// Use, modification and distribution are subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//\n\n#include <boost/core/lightweight_test.hpp>\n#include <boost/gil/rasterization/circle.hpp>\n#include <cstddef>\n#include <vector>\n\nnamespace gil = boost::gil;\n\ntemplate <typename Rasterizer>\nvoid test_rasterizer_follows_equation(std::ptrdiff_t radius, Rasterizer rasterizer)\n{\n\n    std::vector<gil::point_t> circle_points(rasterizer.point_count(radius));\n    std::ptrdiff_t const r_squared = radius * radius;\n    rasterizer(radius, {0, 0}, circle_points.begin());\n    std::vector<gil::point_t> first_octant(rasterizer.point_count(radius) / 8);\n\n    for (std::size_t i = 0, octant_index = 0; i < circle_points.size(); i += 8, ++octant_index)\n    {\n        first_octant[octant_index] = circle_points[i];\n    }\n\n    for (const auto& point : first_octant)\n    {\n        double y_exact = std::sqrt(r_squared - point.x * point.x);\n        std::ptrdiff_t lower_result = static_cast<std::ptrdiff_t>(std::floor(y_exact));\n        std::ptrdiff_t upper_result = static_cast<std::ptrdiff_t>(std::ceil(y_exact));\n        BOOST_TEST(point.y >= lower_result && point.y <= upper_result);\n    }\n}\n\ntemplate <typename Rasterizer>\nvoid test_connectivity(std::ptrdiff_t radius, Rasterizer rasterizer)\n{\n    std::vector<gil::point_t> circle_points(rasterizer.point_count(radius));\n    rasterizer(radius, {radius, radius}, circle_points.begin());\n    for (std::size_t i = 0; i < 8; ++i)\n    {\n        std::vector<gil::point_t> octant(circle_points.size() / 8);\n        for (std::size_t octant_index = i, index = 0; octant_index < circle_points.size();\n             octant_index += 8, ++index)\n        {\n            octant[index] = circle_points[octant_index];\n        }\n\n        for (std::size_t index = 1; index < octant.size(); ++index)\n        {\n            const auto diff_x = std::abs(octant[index].x - octant[index - 1].x);\n            const auto diff_y = std::abs(octant[index].y - octant[index - 1].y);\n            BOOST_TEST_LE(diff_x, 1);\n            BOOST_TEST_LE(diff_y, 1);\n        }\n    }\n}\n\nint main()\n{\n    for (std::ptrdiff_t radius = 5; radius <= 512; ++radius)\n    {\n        test_rasterizer_follows_equation(radius, gil::midpoint_circle_rasterizer{});\n        // TODO: find out a new testing procedure for trigonometric rasterizer\n        // test_equation_following(radius, gil::trigonometric_circle_rasterizer{});\n        test_connectivity(radius, gil::midpoint_circle_rasterizer{});\n        test_connectivity(radius, gil::trigonometric_circle_rasterizer{});\n    }\n\n    return boost::report_errors();\n}\n", "meta": {"hexsha": "b4c85c7da45806677e6dfcba75d66f4919a735c2", "size": 2811, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/core/rasterization/circle.cpp", "max_stars_repo_name": "Paul92/gil", "max_stars_repo_head_hexsha": "da0655fb66dd161a643e1ca0ed51937548465d18", "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": "test/core/rasterization/circle.cpp", "max_issues_repo_name": "Paul92/gil", "max_issues_repo_head_hexsha": "da0655fb66dd161a643e1ca0ed51937548465d18", "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/core/rasterization/circle.cpp", "max_forks_repo_name": "Paul92/gil", "max_forks_repo_head_hexsha": "da0655fb66dd161a643e1ca0ed51937548465d18", "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.5064935065, "max_line_length": 95, "alphanum_fraction": 0.6680896478, "num_tokens": 747, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743168019989179, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.4707302514982843}}
{"text": "#pragma once\n#ifndef CANNON_MATH_RANDOM_DOUBLE_H\n#define CANNON_MATH_RANDOM_DOUBLE_H \n\n/*!\n * \\file cannon/math/random_double.hpp\n * \\brief File containing utilities for generating random doubles and vectors.\n */\n\n#include <Eigen/Dense>\n\nusing namespace Eigen;\n\nnamespace cannon {\n  namespace math {\n\n    /*!\n     * \\brief Generate a random double uniformly at random between 0 and 1 in a\n     * thread-safe way.\n     *\n     * \\returns The generated double.\n     */\n    double random_double();\n\n    /*!\n     * \\brief Generate a random double between min and max.\n     *\n     * \\param min The minimum number that can be generated.\n     * \\param max The maximum number that can be generated.\n     *\n     * \\returns The generated double.\n     */\n    double random_double(double min, double max);\n\n    /*!\n     * \\brief Generate a random vector with entries sampled uniformly at random\n     * between 0 and 1.\n     *\n     * \\returns The generated vector.\n     */\n    Vector3d random_vec();\n\n    /*!\n     * \\brief Generate a random vector with entries sampled uniformly at random\n     * between the input minimum and maximum.\n     *\n     * \\param min The minimum value to generate.\n     * \\param max The maximum value to generate.\n     *\n     * \\returns The generated vector.\n     */\n    Vector3d random_vec(double min, double max);\n\n    /*!\n     * \\brief Generate a random vector in the unit sphere.\n     *\n     * \\returns The generated vector.\n     */\n    Vector3d random_in_unit_sphere();\n\n    /*!\n     * \\brief Generate a random unit vector.\n     * \n     * \\returns The generated vector.\n     */\n    Vector3d random_unit_vec();\n\n    /*!\n     * \\brief Generate a random vector in the unit hemisphere around the input\n     * normal vector.\n     *\n     * \\param normal The normal vector to sample around.\n     *\n     * \\returns The generated vector.\n     */\n    Vector3d random_in_hemisphere(const Vector3d& normal);\n\n    /*!\n     * \\brief Generate a random vector in the unit disk in the X-Y plane.\n     *\n     * \\returns The generated vector.\n     */\n    Vector3d random_in_disk();\n\n  } // namespace math\n} // namespace cannon\n\n#endif /* ifndef CANNON_MATH_RANDOM_DOUBLE_H */\n", "meta": {"hexsha": "14acddaf3961452ca192c2f4c1d6cf53a077fd03", "size": 2174, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cannon/math/random_double.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/math/random_double.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/math/random_double.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": 24.4269662921, "max_line_length": 79, "alphanum_fraction": 0.6407543698, "num_tokens": 487, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.47073024789522566}}
{"text": "#include <vector>\n\n#include <aslam/cameras/camera-pinhole.h>\n#include <aslam/common/memory.h>\n#include <aslam/common/stl-helpers.h>\n#include <Eigen/Core>\n#include <Eigen/StdVector>\n#include <glog/logging.h>\n#include <opencv2/calib3d/calib3d.hpp>\n\n#include \"aslam/calibration/target-observation.h\"\n#include \"aslam/calibration/helpers.h\"\n\nnamespace aslam {\nnamespace calibration {\n\n// Initializes the intrinsics vector based on one views of a calibration targets.\n// On success it returns true. These functions are based on functions from Lionel Heng and\n// the excellent camodocal: https://github.com/hengli/camodocal.\n// This algorithm can be used with high distortion lenses.\n//\n// C. Hughes, P. Denny, M. Glavin, and E. Jones,\n// Equidistant Fish-Eye Calibration and Rectification by Vanishing Point\n// Extraction, PAMI 2010\n// Find circles from rows of chessboard corners, and for each pair\n// of circles, find vanishing points: v1 and v2.\n// f = ||v1 - v2|| / PI;\nbool initFocalLengthVanishingPoints(\n    const std::vector<TargetObservation::Ptr>& observations, Eigen::VectorXd* intrinsics) {\n  CHECK_NOTNULL(intrinsics);\n  CHECK(!observations.empty()) << \"Need at least one observation.\";\n\n  const double cu = (observations.at(0)->getImageWidth() - 1.0) / 2.0;\n  const double cv = (observations.at(0)->getImageHeight() - 1.0) / 2.0;\n\n  const size_t num_obs = observations.size();\n  std::vector<double> f_guesses;\n\n  for (size_t obs_idx = 0; obs_idx < num_obs; ++obs_idx) {\n    TargetObservation::ConstPtr obs = observations[obs_idx];\n    CHECK(obs);\n    TargetBase::ConstPtr current_target = obs->getTarget();\n    CHECK(current_target) << \"The TargetObservation has no target object.\";\n\n    // We can only process complete image observations.\n    if (!obs->allCornersObservered()) {\n      continue;\n    }\n\n    // Try to fit circles to each row of observations.\n    Aligned<std::vector, Eigen::Vector2d> center(current_target->rows());\n    std::vector<double> radius(current_target->rows());\n\n    for (size_t r = 0u; r < current_target->rows(); ++r) {\n      std::vector<cv::Point2d> points_on_circle;\n      for (size_t c = 0u; c < current_target->cols(); ++c) {\n        const size_t corner_idx = r * current_target->cols() + c;\n        Eigen::Vector2d obs_corner;\n        bool success = obs->getObservedCornerById(corner_idx, &obs_corner);\n        if (success == true){\n          points_on_circle.emplace_back(\n              obs_corner[0],\n              obs_corner[1]);\n        }\n      }\n      InitializerHelpers::fitCircle(points_on_circle, &center[r](0), &center[r](1), &radius[r]);\n    }\n\n    // Intersect all circles to find the focal length guesses.\n    for (size_t j = 0u; j < current_target->rows(); ++j) {\n      for (size_t k = j + 1u; k < current_target->rows(); ++k) {\n        // Find the distance between pair of vanishing points which\n        // correspond to intersection points of 2 circles.\n        std::vector<cv::Point2d> intersection_points;\n        CHECK_LT(j, center.size());\n        CHECK_LT(k, center.size());\n        CHECK_LT(j, radius.size());\n        CHECK_LT(k, radius.size());\n        InitializerHelpers::intersectCircles(center[j](0), center[j](1), radius[j],\n                                             center[k](0), center[k](1), radius[k],\n                                             &intersection_points);\n        if (intersection_points.size() >= 2) {\n          const double f_guess = cv::norm(intersection_points[0] - intersection_points[1]) / M_PI;\n          f_guesses.emplace_back(f_guess);\n        }\n      }\n    }\n  }\n\n  // Gets the median of the guesses.\n  if (f_guesses.empty()) {\n    return false;\n  }\n  const double f0 = aslam::common::median(f_guesses.begin(), f_guesses.end());\n\n  // Sets the first intrinsics estimate.\n  intrinsics->resize(aslam::PinholeCamera::parameterCount());\n  (*intrinsics)(PinholeCamera::kFu) = f0;\n  (*intrinsics)(PinholeCamera::kFv) = f0;\n  (*intrinsics)(PinholeCamera::kCu) = cu;\n  (*intrinsics)(PinholeCamera::kCv) = cv;\n\n  return true;\n}\n\n// Initializes the intrinsics vector based on one view of a gridded calibration target.\n// On success it returns true. These functions are based on functions from Lionel Heng\n// and the excellent camodocal https://github.com/hengli/camodocal.\n//\n// Z. Zhang\n// A Flexible New Technique for Camera Calibration,\n// Extraction, PAMI 2000\n// Intrinsics estimation with image of absolute conic;\nbool initFocalLengthAbsoluteConic(\n  const std::vector<TargetObservation::Ptr>& observations, Eigen::VectorXd* intrinsics) {\n CHECK_NOTNULL(intrinsics);\n CHECK(!observations.empty()) << \"Need at least one observation.\";\n\n const double cu = (observations.at(0)->getImageWidth() - 1.0) / 2.0;\n const double cv = (observations.at(0)->getImageHeight() - 1.0) / 2.0;\n\n const size_t num_obs = observations.size();\n cv::Mat A(num_obs * 2, 2, CV_64F);\n cv::Mat b(num_obs * 2, 1, CV_64F);\n\n for (size_t obs_idx = 0u; obs_idx < num_obs; ++obs_idx) {\n   TargetObservation::ConstPtr obs = observations[obs_idx];\n   CHECK(obs);\n   TargetBase::ConstPtr current_target = obs->getTarget();\n   CHECK(current_target) << \"The TargetObservation has no target object.\";\n\n   // We can only process complete image observations.\n   if (!obs->allCornersObservered()) {\n     continue;\n   }\n\n   std::vector<cv::Point2f> image_corners(obs->numObservedCorners());\n   std::vector<cv::Point2f> M(obs->numObservedCorners());\n\n   for (size_t j = 0; j < image_corners.size(); ++j) {\n     Eigen::Vector2d obs_corner;\n     bool success = obs->getObservedCornerById(j, &obs_corner);\n     if (success == true){\n       image_corners[j] = cv::Point2f(obs_corner[0],\n                                      obs_corner[1]);\n       M[j] = cv::Point2f(current_target->point(j)[0],\n                          current_target->point(j)[1]);\n     }\n   }\n\n   cv::Mat H = cv::findHomography(M, image_corners);\n\n   H.at<double>(0,0) -= H.at<double>(2,0) * cu;\n   H.at<double>(0,1) -= H.at<double>(2,1) * cu;\n   H.at<double>(0,2) -= H.at<double>(2,2) * cu;\n   H.at<double>(1,0) -= H.at<double>(2,0) * cv;\n   H.at<double>(1,1) -= H.at<double>(2,1) * cv;\n   H.at<double>(1,2) -= H.at<double>(2,2) * cv;\n\n   double h[3], v[3], d1[3], d2[3];\n   double n[4] = {0,0,0,0};\n\n   for (int j = 0; j < 3; ++j) {\n     double t0 = H.at<double>(j,0);\n     double t1 = H.at<double>(j,1);\n     h[j] = t0; v[j] = t1;\n     d1[j] = (t0 + t1) * 0.5;\n     d2[j] = (t0 - t1) * 0.5;\n     n[0] += t0 * t0; n[1] += t1 * t1;\n     n[2] += d1[j] * d1[j]; n[3] += d2[j] * d2[j];\n   }\n\n   for (int j = 0; j < 4; ++j) {\n     n[j] = 1.0 / sqrt(n[j]);\n   }\n\n   for (int j = 0; j < 3; ++j) {\n     h[j] *= n[0]; v[j] *= n[1];\n     d1[j] *= n[2]; d2[j] *= n[3];\n   }\n\n   A.at<double>(obs_idx * 2, 0) = h[0] * v[0];\n   A.at<double>(obs_idx * 2, 1) = h[1] * v[1];\n   A.at<double>(obs_idx * 2 + 1, 0) = d1[0] * d2[0];\n   A.at<double>(obs_idx * 2 + 1, 1) = d1[1] * d2[1];\n   b.at<double>(obs_idx * 2, 0) = -h[2] * v[2];\n   b.at<double>(obs_idx * 2 + 1, 0) = -d1[2] * d2[2];\n }\n\n cv::Mat f(2, 1, CV_64F);\n cv::solve(A, b, f, cv::DECOMP_NORMAL | cv::DECOMP_LU);\n\n // Sets the first intrinsics estimate.\n intrinsics->resize(aslam::PinholeCamera::parameterCount());\n (*intrinsics)(PinholeCamera::kFu) = sqrt(fabs(1.0 / f.at<double>(0)));\n (*intrinsics)(PinholeCamera::kFv) = sqrt(fabs(1.0 / f.at<double>(1)));\n (*intrinsics)(PinholeCamera::kCu) = cu;\n (*intrinsics)(PinholeCamera::kCv) = cv;\n\n return true;\n}\n\n}  // namespace calibration\n}  // namespace aslam\n", "meta": {"hexsha": "976fb4111643af045dbe9012b48bbeac0438bd03", "size": 7468, "ext": "cc", "lang": "C++", "max_stars_repo_path": "aslam_cv_calibration/src/focallength-initializers.cc", "max_stars_repo_name": "shuhannod/aslam_cv2", "max_stars_repo_head_hexsha": "4dd48916b9e5b9d5aa56e28894a04d4a25a87348", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 173.0, "max_stars_repo_stars_event_min_datetime": "2017-09-19T18:14:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-20T09:11:15.000Z", "max_issues_repo_path": "aslam_cv_calibration/src/focallength-initializers.cc", "max_issues_repo_name": "shuhannod/aslam_cv2", "max_issues_repo_head_hexsha": "4dd48916b9e5b9d5aa56e28894a04d4a25a87348", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 30.0, "max_issues_repo_issues_event_min_datetime": "2017-11-16T12:46:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-20T04:38:41.000Z", "max_forks_repo_path": "aslam_cv_calibration/src/focallength-initializers.cc", "max_forks_repo_name": "shuhannod/aslam_cv2", "max_forks_repo_head_hexsha": "4dd48916b9e5b9d5aa56e28894a04d4a25a87348", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 58.0, "max_forks_repo_forks_event_min_datetime": "2017-10-24T17:31:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T03:23:24.000Z", "avg_line_length": 36.4292682927, "max_line_length": 98, "alphanum_fraction": 0.6249330477, "num_tokens": 2253, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743167997235783, "lm_q2_score": 0.63341027751814, "lm_q1q2_score": 0.47073024737171765}}
{"text": "#ifndef BART_SRC_QUADRATURE_CALCULATORS_ANGULAR_FLUX_INTEGRATOR_I_HPP_\n#define BART_SRC_QUADRATURE_CALCULATORS_ANGULAR_FLUX_INTEGRATOR_I_HPP_\n\n#include <map>\n\n#include <deal.II/lac/vector.h>\n\n#include \"quadrature/quadrature_types.h\"\n#include \"utility/named_type.h\"\n\nnamespace bart::quadrature::calculators {\n/*! \\brief Interface for a class that integrates angular flux using a quadrature set.\n *\n * The provided functions calculate the net current at a degree of freedom \\f$i\\f$:\n * \\f[\n * \\vec{J}_i = \\int \\hat{\\Omega} \\psi(\\hat{\\Omega})_i d\\hat{\\Omega} = \\sum_{m = 0}^M w_m\\hat{\\Omega}_m\\psi_{i,m}\\;,\n * \\f]\n * the magnitude of the current in direction \\f$\\hat{n}\\f$:\n * \\f[\n * j_{\\hat{n}} = \\int_{\\hat{n} \\cdot \\hat{\\Omega} \\ge 0} |\\hat{n} \\cdot \\hat{\\Omega}| \\psi(\\hat{\\Omega})_i d\\hat{\\Omega} = \\sum_{\\Omega_m \\mid \\hat{n} \\cdot \\Omega \\ge 0} w_m|\\hat{n} \\cdot \\hat{\\Omega}_m|\\psi_{i,m}\\;,\n * \\f]\n * and the integrated angular flux in direction \\f$\\hat{n}\\f$:\n *\n * \\f[\n * \\phi_{\\hat{n}} = \\int_{\\hat{n} \\cdot \\hat{\\Omega} \\ge 0} \\psi(\\hat{\\Omega})_i d\\hat{\\Omega} = \\sum_{\\Omega_m \\mid \\hat{n} \\cdot \\Omega \\ge 0} w_m\\psi_{i,m}\\;.\n * \\f]\n */\nclass AngularFluxIntegratorI {\n public:\n  virtual ~AngularFluxIntegratorI() = default;\n  using Vector = dealii::Vector<double>;\n  using VectorPtr = std::shared_ptr<dealii::Vector<double>>;\n  using VectorMap = std::map<quadrature::QuadraturePointIndex, VectorPtr>;\n  using DegreeOfFreedom = utility::NamedType<int, struct DegreeOfFreedomParam>;\n\n  virtual auto NetCurrent(const VectorMap&) const -> std::vector<Vector> = 0;\n  virtual auto NetCurrent(const VectorMap&, const DegreeOfFreedom) const -> Vector = 0;\n  virtual auto DirectionalCurrent(const VectorMap&, const Vector normal) const -> std::vector<double> = 0;\n  virtual auto DirectionalCurrent(const VectorMap&, const Vector normal, const DegreeOfFreedom) const -> double = 0;\n  virtual auto DirectionalFlux(const VectorMap&, const Vector normal) const -> std::vector<double> = 0;\n  virtual auto DirectionalFlux(const VectorMap&, const Vector normal, const DegreeOfFreedom) const -> double = 0;\n};\n\n} // namespace bart::quadrature::calculators\n\n#endif //BART_SRC_QUADRATURE_CALCULATORS_ANGULAR_FLUX_INTEGRATOR_I_HPP_", "meta": {"hexsha": "0a439cf4110fa0a93c2782296972d11b35f98521", "size": 2223, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/quadrature/calculators/angular_flux_integrator_i.hpp", "max_stars_repo_name": "SlaybaughLab/Transport", "max_stars_repo_head_hexsha": "8eb32cb8ae50c92875526a7540350ef9a85bc050", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2018-03-14T12:30:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T14:46:44.000Z", "max_issues_repo_path": "src/quadrature/calculators/angular_flux_integrator_i.hpp", "max_issues_repo_name": "SlaybaughLab/Transport", "max_issues_repo_head_hexsha": "8eb32cb8ae50c92875526a7540350ef9a85bc050", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 194.0, "max_issues_repo_issues_event_min_datetime": "2017-07-07T01:38:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-19T18:21:19.000Z", "max_forks_repo_path": "src/quadrature/calculators/angular_flux_integrator_i.hpp", "max_forks_repo_name": "SlaybaughLab/Transport", "max_forks_repo_head_hexsha": "8eb32cb8ae50c92875526a7540350ef9a85bc050", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2017-07-06T22:58:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-15T07:01:21.000Z", "avg_line_length": 48.3260869565, "max_line_length": 217, "alphanum_fraction": 0.7174988754, "num_tokens": 680, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743168019989179, "lm_q2_score": 0.6334102567576901, "lm_q1q2_score": 0.4707302463554501}}
{"text": "// This file is part of Eigen, a lightweight C++ template library\n// for linear algebra.\n//\n// Copyright (C) 2016 Igor Babuschkin <igor@babuschk.in>\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 \"main.h\"\n#include <limits>\n#include <numeric>\n#include <Eigen/CXX11/Tensor>\n\nusing Eigen::Tensor;\n\ntemplate <int DataLayout, typename Type=float, bool Exclusive = false>\nstatic void test_1d_scan()\n{\n  int size = 50;\n  Tensor<Type, 1, DataLayout> tensor(size);\n  tensor.setRandom();\n  Tensor<Type, 1, DataLayout> result = tensor.cumsum(0, Exclusive);\n\n  VERIFY_IS_EQUAL(tensor.dimension(0), result.dimension(0));\n\n  float accum = 0;\n  for (int i = 0; i < size; i++) {\n    if (Exclusive) {\n      VERIFY_IS_EQUAL(result(i), accum);\n      accum += tensor(i);\n    } else {\n      accum += tensor(i);\n      VERIFY_IS_EQUAL(result(i), accum);\n    }\n  }\n\n  accum = 1;\n  result = tensor.cumprod(0, Exclusive);\n  for (int i = 0; i < size; i++) {\n    if (Exclusive) {\n      VERIFY_IS_EQUAL(result(i), accum);\n      accum *= tensor(i);\n    } else {\n      accum *= tensor(i);\n      VERIFY_IS_EQUAL(result(i), accum);\n    }\n  }\n}\n\ntemplate <int DataLayout, typename Type=float>\nstatic void test_4d_scan()\n{\n  int size = 5;\n  Tensor<Type, 4, DataLayout> tensor(size, size, size, size);\n  tensor.setRandom();\n\n  Tensor<Type, 4, DataLayout> result(size, size, size, size);\n\n  result = tensor.cumsum(0);\n  float accum = 0;\n  for (int i = 0; i < size; i++) {\n    accum += tensor(i, 1, 2, 3);\n    VERIFY_IS_EQUAL(result(i, 1, 2, 3), accum);\n  }\n  result = tensor.cumsum(1);\n  accum = 0;\n  for (int i = 0; i < size; i++) {\n    accum += tensor(1, i, 2, 3);\n    VERIFY_IS_EQUAL(result(1, i, 2, 3), accum);\n  }\n  result = tensor.cumsum(2);\n  accum = 0;\n  for (int i = 0; i < size; i++) {\n    accum += tensor(1, 2, i, 3);\n    VERIFY_IS_EQUAL(result(1, 2, i, 3), accum);\n  }\n  result = tensor.cumsum(3);\n  accum = 0;\n  for (int i = 0; i < size; i++) {\n    accum += tensor(1, 2, 3, i);\n    VERIFY_IS_EQUAL(result(1, 2, 3, i), accum);\n  }\n}\n\ntemplate <int DataLayout>\nstatic void test_tensor_maps() {\n  int inputs[20];\n  TensorMap<Tensor<int, 1, DataLayout> > tensor_map(inputs, 20);\n  tensor_map.setRandom();\n\n  Tensor<int, 1, DataLayout> result = tensor_map.cumsum(0);\n\n  int accum = 0;\n  for (int i = 0; i < 20; ++i) {\n    accum += tensor_map(i);\n    VERIFY_IS_EQUAL(result(i), accum);\n  }\n}\n\nEIGEN_DECLARE_TEST(cxx11_tensor_scan) {\n  CALL_SUBTEST((test_1d_scan<ColMajor, float, true>()));\n  CALL_SUBTEST((test_1d_scan<ColMajor, float, false>()));\n  CALL_SUBTEST((test_1d_scan<RowMajor, float, true>()));\n  CALL_SUBTEST((test_1d_scan<RowMajor, float, false>()));\n  CALL_SUBTEST(test_4d_scan<ColMajor>());\n  CALL_SUBTEST(test_4d_scan<RowMajor>());\n  CALL_SUBTEST(test_tensor_maps<ColMajor>());\n  CALL_SUBTEST(test_tensor_maps<RowMajor>());\n}\n", "meta": {"hexsha": "dccee9e848ccbdf9d1cd70b1226b445127d7c754", "size": 2978, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "third_party/eigen3/include/unsupported/test/cxx11_tensor_scan.cpp", "max_stars_repo_name": "Shamraev/motion_imitation", "max_stars_repo_head_hexsha": "9b9166436e4996e2a03b36d19f4f5422cde9c21e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2111.0, "max_stars_repo_stars_event_min_datetime": "2019-01-29T07:01:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T06:48:14.000Z", "max_issues_repo_path": "third_party/eigen3/include/unsupported/test/cxx11_tensor_scan.cpp", "max_issues_repo_name": "Shamraev/motion_imitation", "max_issues_repo_head_hexsha": "9b9166436e4996e2a03b36d19f4f5422cde9c21e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 843.0, "max_issues_repo_issues_event_min_datetime": "2019-01-25T01:06:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T11:15:53.000Z", "max_forks_repo_path": "third_party/eigen3/include/unsupported/test/cxx11_tensor_scan.cpp", "max_forks_repo_name": "Shamraev/motion_imitation", "max_forks_repo_head_hexsha": "9b9166436e4996e2a03b36d19f4f5422cde9c21e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 421.0, "max_forks_repo_forks_event_min_datetime": "2019-02-12T07:59:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T05:22:01.000Z", "avg_line_length": 26.8288288288, "max_line_length": 70, "alphanum_fraction": 0.6370047011, "num_tokens": 932, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.47073024429216703}}
{"text": "//=======================================================================\n// Copyright 2009 Trustees of Indiana University.\n// Authors: Michael Hansen, Andrew Lumsdaine\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n\n#include <fstream>\n#include <iostream>\n#include <set>\n\n#include <boost/foreach.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/graph/grid_graph.hpp>\n#include <boost/random.hpp>\n#include <boost/core/lightweight_test.hpp>\n\nusing namespace boost;\n\n// Function that prints a vertex to std::cout\ntemplate < typename Vertex > void print_vertex(Vertex vertex_to_print)\n{\n\n    std::cout << \"(\";\n\n    for (std::size_t dimension_index = 0;\n         dimension_index < vertex_to_print.size(); ++dimension_index)\n    {\n        std::cout << vertex_to_print[dimension_index];\n\n        if (dimension_index != (vertex_to_print.size() - 1))\n        {\n            std::cout << \", \";\n        }\n    }\n\n    std::cout << \")\";\n}\n\ntemplate < unsigned int Dims > void do_test(minstd_rand& generator)\n{\n    typedef grid_graph< Dims > Graph;\n    typedef\n        typename graph_traits< Graph >::vertices_size_type vertices_size_type;\n    typedef typename graph_traits< Graph >::edges_size_type edges_size_type;\n\n    typedef typename graph_traits< Graph >::vertex_descriptor vertex_descriptor;\n    typedef typename graph_traits< Graph >::edge_descriptor edge_descriptor;\n\n    std::cout << \"Dimensions: \" << Dims << \", lengths: \";\n\n    // Randomly generate the dimension lengths (3-10) and wrapping\n    boost::array< vertices_size_type, Dims > lengths;\n    boost::array< bool, Dims > wrapped;\n\n    for (unsigned int dimension_index = 0; dimension_index < Dims;\n         ++dimension_index)\n    {\n        lengths[dimension_index] = 3 + (generator() % 8);\n        wrapped[dimension_index] = ((generator() % 2) == 0);\n\n        std::cout << lengths[dimension_index]\n                  << (wrapped[dimension_index] ? \" [W]\" : \" [U]\") << \", \";\n    }\n\n    std::cout << std::endl;\n\n    Graph graph(lengths, wrapped);\n\n    // Verify dimension lengths and wrapping\n    for (unsigned int dimension_index = 0; dimension_index < Dims;\n         ++dimension_index)\n    {\n        BOOST_TEST(\n            graph.length(dimension_index) == lengths[dimension_index]);\n        BOOST_TEST(\n            graph.wrapped(dimension_index) == wrapped[dimension_index]);\n    }\n\n    // Verify matching indices\n    for (vertices_size_type vertex_index = 0;\n         vertex_index < num_vertices(graph); ++vertex_index)\n    {\n        BOOST_TEST(\n            get(boost::vertex_index, graph, vertex(vertex_index, graph))\n            == vertex_index);\n    }\n\n    for (edges_size_type edge_index = 0; edge_index < num_edges(graph);\n         ++edge_index)\n    {\n\n        edge_descriptor current_edge = edge_at(edge_index, graph);\n        BOOST_TEST(\n            get(boost::edge_index, graph, current_edge) == edge_index);\n    }\n\n    // Verify all vertices are within bounds\n    vertices_size_type vertex_count = 0;\n    BOOST_FOREACH (vertex_descriptor current_vertex, vertices(graph))\n    {\n\n        vertices_size_type current_index\n            = get(boost::vertex_index, graph, current_vertex);\n\n        for (unsigned int dimension_index = 0; dimension_index < Dims;\n             ++dimension_index)\n        {\n            BOOST_TEST(\n                /*(current_vertex[dimension_index] >= 0) && */ // Always true\n                (current_vertex[dimension_index] < lengths[dimension_index]));\n        }\n\n        // Verify out-edges of this vertex\n        edges_size_type out_edge_count = 0;\n        std::set< vertices_size_type > target_vertices;\n\n        BOOST_FOREACH (\n            edge_descriptor out_edge, out_edges(current_vertex, graph))\n        {\n\n            target_vertices.insert(\n                get(boost::vertex_index, graph, target(out_edge, graph)));\n\n            ++out_edge_count;\n        }\n\n        BOOST_TEST(out_edge_count == out_degree(current_vertex, graph));\n\n        // Verify in-edges of this vertex\n        edges_size_type in_edge_count = 0;\n\n        BOOST_FOREACH (edge_descriptor in_edge, in_edges(current_vertex, graph))\n        {\n\n            BOOST_TEST(target_vertices.count(get(boost::vertex_index, graph,\n                              source(in_edge, graph)))\n                > 0);\n\n            ++in_edge_count;\n        }\n\n        BOOST_TEST(in_edge_count == in_degree(current_vertex, graph));\n\n        // The number of out-edges and in-edges should be the same\n        BOOST_TEST(degree(current_vertex, graph)\n            == out_degree(current_vertex, graph)\n                + in_degree(current_vertex, graph));\n\n        // Verify adjacent vertices to this vertex\n        vertices_size_type adjacent_count = 0;\n\n        BOOST_FOREACH (vertex_descriptor adjacent_vertex,\n            adjacent_vertices(current_vertex, graph))\n        {\n\n            BOOST_TEST(target_vertices.count(\n                              get(boost::vertex_index, graph, adjacent_vertex))\n                > 0);\n\n            ++adjacent_count;\n        }\n\n        BOOST_TEST(adjacent_count == out_degree(current_vertex, graph));\n\n        // Verify that this vertex is not listed as connected to any\n        // vertices outside of its adjacent vertices.\n        BOOST_FOREACH (vertex_descriptor unconnected_vertex, vertices(graph))\n        {\n\n            vertices_size_type unconnected_index\n                = get(boost::vertex_index, graph, unconnected_vertex);\n\n            if ((unconnected_index == current_index)\n                || (target_vertices.count(unconnected_index) > 0))\n            {\n                continue;\n            }\n\n            BOOST_TEST(\n                !edge(current_vertex, unconnected_vertex, graph).second);\n            BOOST_TEST(\n                !edge(unconnected_vertex, current_vertex, graph).second);\n        }\n\n        ++vertex_count;\n    }\n\n    BOOST_TEST(vertex_count == num_vertices(graph));\n\n    // Verify all edges are within bounds\n    edges_size_type edge_count = 0;\n    BOOST_FOREACH (edge_descriptor current_edge, edges(graph))\n    {\n\n        vertices_size_type source_index\n            = get(boost::vertex_index, graph, source(current_edge, graph));\n\n        vertices_size_type target_index\n            = get(boost::vertex_index, graph, target(current_edge, graph));\n\n        BOOST_TEST(source_index != target_index);\n        BOOST_TEST(/* (source_index >= 0) : always true && */ (\n            source_index < num_vertices(graph)));\n        BOOST_TEST(/* (target_index >= 0) : always true && */ (\n            target_index < num_vertices(graph)));\n\n        // Verify that the edge is listed as existing in both directions\n        BOOST_TEST(edge(\n            source(current_edge, graph), target(current_edge, graph), graph)\n                          .second);\n        BOOST_TEST(edge(\n            target(current_edge, graph), source(current_edge, graph), graph)\n                          .second);\n\n        ++edge_count;\n    }\n\n    BOOST_TEST(edge_count == num_edges(graph));\n}\n\nint main(int argc, char* argv[])\n{\n\n    std::size_t random_seed = time(0);\n\n    if (argc > 1)\n    {\n        random_seed = lexical_cast< std::size_t >(argv[1]);\n    }\n\n    minstd_rand generator(random_seed);\n\n    do_test< 0 >(generator);\n    do_test< 1 >(generator);\n    do_test< 2 >(generator);\n    do_test< 3 >(generator);\n    do_test< 4 >(generator);\n\n    return boost::report_errors();\n}\n", "meta": {"hexsha": "74059520e9ac170b08f75c502cff33243ee8eecb", "size": 7550, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/graph/test/grid_graph_test.cpp", "max_stars_repo_name": "uosorio/heroku_face", "max_stars_repo_head_hexsha": "7d6465e71dba17a15d8edaef520adb2fcd09d91e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-12T04:55:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T04:55:21.000Z", "max_issues_repo_path": "3rdparty/boost_1_73_0/libs/graph/test/grid_graph_test.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-13T08:54:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-17T17:25:14.000Z", "max_forks_repo_path": "3rdparty/boost_1_73_0/libs/graph/test/grid_graph_test.cpp", "max_forks_repo_name": "qingkouwei/mediaones", "max_forks_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-08-28T07:14:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-13T11:18:41.000Z", "avg_line_length": 30.9426229508, "max_line_length": 80, "alphanum_fraction": 0.6055629139, "num_tokens": 1575, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.6334102567576901, "lm_q1q2_score": 0.470730239149333}}
{"text": "#include <rsa.h>\n#include <osrng.h>\n#include <files.h>\n#include <string>\n#include <boost/program_options.hpp>\n\ntemplate <typename Key>\nvoid SaveKey(const std::string& filename, const Key& key) {\n  CryptoPP::ByteQueue queue;\n  key.Save(queue);\n  CryptoPP::FileSink file(filename.c_str());\n  \n  queue.CopyTo(file);\n  file.MessageEnd();\n}\n\nint main(int argc, char** argv) {\n  using namespace CryptoPP;\n  namespace po = boost::program_options;\n\n  std::string publicKeyName, privateKeyName;\n  size_t keyLength;\n\n\n  po::options_description desc(\"Allowed Options\");\n  desc.add_options()\n    (\"help\", \"produce help message\")\n    (\"length,l\", po::value<size_t>(&keyLength)->default_value(1024), \"set key length\")\n    (\"pubKey,r\", po::value<std::string>(&publicKeyName)->default_value(\"key.pub\"), \"set public key name\")\n    (\"privKey,u\", po::value<std::string>(&privateKeyName)->default_value(\"key.pem\"), \"set private key name\")\n    ;\n\n  po::variables_map vm;\n  po::store(po::parse_command_line(argc, argv, desc), vm);\n  po::notify(vm);    \n  \n  if (vm.count(\"help\")) {\n    std::cout << desc << \"\\n\";\n    return 1;\n  }\n  \n  AutoSeededRandomPool prng;\n\n  InvertibleRSAFunction parameters;\n  parameters.GenerateRandomWithKeySize(prng, keyLength);\n\n  RSA::PrivateKey privateKey(parameters);\n  RSA::PublicKey publicKey(parameters);\n\n  SaveKey(publicKeyName, publicKey);\n  SaveKey(privateKeyName, privateKey);\n}\n", "meta": {"hexsha": "e86e0e4dba4b412161b6ee407eca8da6d35d0d9b", "size": 1397, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "key.cpp", "max_stars_repo_name": "dunkyp/crypto--rsa-example", "max_stars_repo_head_hexsha": "fef2fbb9ce9787546c7572ab3dc68f3714b09f0a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2017-11-26T19:20:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-30T07:07:42.000Z", "max_issues_repo_path": "key.cpp", "max_issues_repo_name": "dunkyp/crypto--rsa-example", "max_issues_repo_head_hexsha": "fef2fbb9ce9787546c7572ab3dc68f3714b09f0a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "key.cpp", "max_forks_repo_name": "dunkyp/crypto--rsa-example", "max_forks_repo_head_hexsha": "fef2fbb9ce9787546c7572ab3dc68f3714b09f0a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-11-26T19:20:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-08T04:29:15.000Z", "avg_line_length": 26.358490566, "max_line_length": 108, "alphanum_fraction": 0.6950608447, "num_tokens": 353, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.6334102567576901, "lm_q1q2_score": 0.470730239149333}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// Unit Test\n\n// Copyright (c) 2019 Tinko Bartels, Berlin, Germany.\n\n// Contributed and/or modified by Tinko Bartels,\n//   as part of Google Summer of Code 2019 program.\n\n// This file was modified by Oracle on 2021.\n// Modifications copyright (c) 2021, Oracle and/or its affiliates.\n// 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#include <geometry_test_common.hpp>\n\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/strategy/cartesian/in_circle_robust.hpp>\n\ntemplate <typename P>\nvoid test_all()\n{\n    typedef bg::strategy::in_circle::in_circle_robust<double, 2> inc2;\n    typedef bg::strategy::in_circle::in_circle_robust<double, 1> inc1;\n    typedef bg::strategy::in_circle::in_circle_robust<double, 0> inc0;\n\n    P col1(0.0, 0.0), col2(1.0, 0.0), col3(0.0, 1.0);\n    P in(0.5,0.5) , on(1.0, 0.0), out(-0.5, -0.5);\n    int in2 = inc2::apply(col1, col2, col3, in);\n    BOOST_CHECK_GT(in2, 0);\n    int in1 = inc1::apply(col1, col2, col3, in);\n    BOOST_CHECK_GT(in1, 0);\n    int in0 = inc0::apply(col1, col2, col3, in);\n    BOOST_CHECK_GT(in0, 0);\n\n    int on2 = inc2::apply(col1, col2, col3, on);\n    BOOST_CHECK_EQUAL(on2, 0);\n    int on1 = inc1::apply(col1, col2, col3, on);\n    BOOST_CHECK_EQUAL(on1, 0);\n    int on0 = inc0::apply(col1, col2, col3, on);\n    BOOST_CHECK_EQUAL(on0, 0);\n\n    int out2 = inc2::apply(col1, col2, col3, out);\n    BOOST_CHECK_GT(0, out2);\n    int out1 = inc1::apply(col1, col2, col3, out);\n    BOOST_CHECK_GT(0, out1);\n    int out0 = inc0::apply(col1, col2, col3, out);\n    BOOST_CHECK_GT(0, out0);\n\n    P hard1(0, 0), hard2(1e20, 0), hard3(0, 1e20);\n    P inhard(0.5, 0.5);\n    int hardr  = inc2::apply(hard1, hard2, hard3, inhard);\n    BOOST_CHECK_GT(hardr, 0);\n}\n\n\nint test_main(int, char* [])\n{\n    test_all<bg::model::d2::point_xy<double> >();\n    return 0;\n}\n", "meta": {"hexsha": "2eb65ec63b48e22cabe0958d445d20112f168ecd", "size": 2089, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "extensions/test/triangulation/in_circle_robust.cpp", "max_stars_repo_name": "jhypolite/geometry", "max_stars_repo_head_hexsha": "f79b3f0c457bc4ae4bb1c1cb5a117efbe97be3c4", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 326.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T13:47:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T02:13:59.000Z", "max_issues_repo_path": "extensions/test/triangulation/in_circle_robust.cpp", "max_issues_repo_name": "jhypolite/geometry", "max_issues_repo_head_hexsha": "f79b3f0c457bc4ae4bb1c1cb5a117efbe97be3c4", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 623.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T23:45:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T11:15:23.000Z", "max_forks_repo_path": "extensions/test/triangulation/in_circle_robust.cpp", "max_forks_repo_name": "jhypolite/geometry", "max_forks_repo_head_hexsha": "f79b3f0c457bc4ae4bb1c1cb5a117efbe97be3c4", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-01-14T15:50:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T03:58:36.000Z", "avg_line_length": 32.640625, "max_line_length": 79, "alphanum_fraction": 0.6706558162, "num_tokens": 721, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.6334102567576901, "lm_q1q2_score": 0.47073023914933293}}
{"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/*!\n * \\file\n**/\n#ifndef BOOST_SIMD_CONSTANT_CONSTANTS_SQRTVALMAX_HPP_INCLUDED\n#define BOOST_SIMD_CONSTANT_CONSTANTS_SQRTVALMAX_HPP_INCLUDED\n\n#include <boost/simd/include/functor.hpp>\n#include <boost/simd/sdk/constant/register.hpp>\n#include <boost/simd/sdk/constant/constant.hpp>\n\n/*!\n * \\ingroup boost_simd_constant\n * \\defgroup boost_simd_constant_sqrtvalmax Sqrtvalmax\n *\n * \\par Description\n * Constant Sqrtvalmax : the least non zero positive value of floating point numbers,\n * i.e. 2.225073858507201e-308 for double and  1.1754944e-38 for float\n *\n * \\par Header file\n *\n * \\code\n * #include <nt2/include/functions/sqrtvalmax.hpp>\n * \\endcode\n *\n *\n * \\synopsis\n *\n * \\code\n * namespace boost::simd\n * {\n *   template <class T,class A0>\n *     meta::call<tag::sqrtvalmax_(A0)>::type\n *     Sqrtvalmax();\n * }\n * \\endcode\n *\n *\n * \\param T template parameter of Sqrtvalmax\n *\n * \\return type T value\n *\n *\n**/\n\nnamespace boost { namespace simd\n{\n  namespace tag\n  {\n    /*!\n     * \\brief Define the tag Sqrtvalmax of functor Sqrtvalmax\n     *        in namespace boost::simd::tag for toolbox boost.simd.constant\n    **/\n    struct Sqrtvalmax : ext::pure_constant_<Sqrtvalmax>\n    {\n      typedef double default_type;\n      template<class Target, class Dummy=void>\n      struct  apply\n            : meta::int_c < typename Target::type\n                          , typename Target::\n                            type( (typename Target::type(1)\n                                  << (sizeof(typename Target::type)*CHAR_BIT/2))-1\n                                )\n                          >\n      {};\n    };\n\n    template<class T, class Dummy>\n    struct  Sqrtvalmax::apply< boost::dispatch::meta::single_<T>,Dummy>\n          : meta::single_<0x5f800000> {};\n\n    template<class T, class Dummy>\n    struct  Sqrtvalmax::apply<boost::dispatch::meta::double_<T>,Dummy>\n          : meta::double_<0x5ff0000000000001ll> {};\n\n    template<class T, class Dummy>\n    struct  Sqrtvalmax::apply<boost::dispatch::meta::int8_<T>,Dummy>\n          : meta::int_c<T, 11> {};\n\n    template<class T, class Dummy>\n    struct  Sqrtvalmax::apply<boost::dispatch::meta::int16_<T>,Dummy>\n          : meta::int_c<T, 181> {};\n\n    template<class T, class Dummy>\n    struct  Sqrtvalmax::apply<boost::dispatch::meta::int32_<T>,Dummy>\n          : meta::int_c<T, 46340> {};\n\n    template<class T, class Dummy>\n    struct  Sqrtvalmax::apply<boost::dispatch::meta::int64_<T>,Dummy>\n          : meta::int_c<T, 3037000499ll> {};\n  }\n\n  BOOST_SIMD_CONSTANT_IMPLEMENTATION(boost::simd::tag::Sqrtvalmax, Sqrtvalmax)\n} }\n\n#include <boost/simd/sdk/constant/common.hpp>\n\n#endif\n", "meta": {"hexsha": "13ba0fa1290532c5d4aec1d2441ee1f9a56d8094", "size": 3145, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/constant/include/boost/simd/constant/constants/sqrtvalmax.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/constant/include/boost/simd/constant/constants/sqrtvalmax.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/constant/include/boost/simd/constant/constants/sqrtvalmax.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": 29.6698113208, "max_line_length": 85, "alphanum_fraction": 0.5939586645, "num_tokens": 814, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.63341024983754, "lm_q1q2_score": 0.47073023400649877}}
{"text": "#ifndef SPATIAL_DECOMPOSITION_HPP\n#define SPATIAL_DECOMPOSITION_HPP\n\n////////////////////////////////////////////////////////////////////////////////\n//\n// This file is a part of the CxxSDM spatial decomposition\n// library. It is released under the MIT License. You should have\n// received a copy of the MIT License along with CxxSDM.  If not, see\n// http://www.opensource.org/licenses/mit-license.php\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n//\n// For details, see the LICENSE file\n//\n// (C) 2018 Jukka Saarelma\n//\n////////////////////////////////////////////////////////////////////////////////\n\n#include <algorithm>\n#include <iostream>\n#include <string>\n#include <cmath>\n#include <vector>\n#include <fftw3.h>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n#ifdef _WIN32\n  #define DLLEXPORT extern \"C\" __declspec( dllexport )\n#else\n  #define DLLEXPORT\n#endif\n\n#define EIGEN_USE_LAPACKE\n\n// C interface\nextern \"C\" {\n  DLLEXPORT void* initialize(unsigned int fs, unsigned int frame_len,\n                   unsigned int resp_len, float* mic_locs,\n                   unsigned int num_mics);\n\n  DLLEXPORT void destroy(void* sd_);\n\n  DLLEXPORT void processIRs(void* sd_, float* irs, float* az_out, float* el_out);\n\n  DLLEXPORT void synthFromLocs(float* p, float* az0, float* el0, float* az1, float* el1,\n                     unsigned int resp_len, unsigned int ls_num, float* ret);\n}\n\ninline Eigen::Vector3f cart2sph(Eigen::Vector3f cart) {\n  float hypotXY = hypot(cart.x(), cart.y());\n  float r = hypot(hypotXY, cart.z());\n  float elev = atan2(cart.z(), hypotXY)/M_PI*180.f;\n  float az = atan2(cart.y(), cart.x())/M_PI*180.f;\n  return Eigen::Vector3f(az, elev, r);\n}\n\ninline Eigen::Vector3f sph2cart(Eigen::Vector3f sph) {\n  float z = sph.z()*sinf(sph.y()/180*M_PI);\n  float el_cos = sph.z()*cosf(sph.y()/180*M_PI);\n  float x = el_cos*cosf(sph.x()/180*M_PI);\n  float y = el_cos*sinf(sph.x()/180*M_PI);\n  return Eigen::Vector3f(x,y,z);\n}\n\n// From http://eigen.tuxfamily.org/bz/show_bug.cgi?id=257\ntemplate<typename _Matrix_Type_>\ninline bool pinv(const _Matrix_Type_ &a, _Matrix_Type_ &result,\n                 double epsilon = std::numeric_limits<double>::epsilon()) {\n  if(a.rows() < a.cols()) {\n    printf(\"Inverse false rows: %ld cols: %ld \\n\", a.rows(), a.cols());\n    return false;\n  }\n  Eigen::JacobiSVD< _Matrix_Type_ > svd = a.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV);\n  double tolerance = epsilon*std::max(a.cols(), a.rows())*\n                     svd.singularValues().array().abs().maxCoeff();\n\n  result = svd.matrixV()*\n           ((svd.singularValues().array().abs() > tolerance).select(svd.singularValues().array().inverse(), 0) ).matrix().asDiagonal()*\n           svd.matrixU().adjoint();\n  return true;\n}\n\nclass SpatialDecomposer {\npublic:\n  SpatialDecomposer() {};\n  ~SpatialDecomposer() {};\n\n  void initialize(unsigned int fs, unsigned int winlen, unsigned int resp_len,\n                  float* mic_locs, unsigned int num_mics);\n\n  void correlate(float* a, float* b, float* out);\n\n  void destroy();\n\n  void processFrame(float* frame);\n\n  void processIRs(float** irs);\n\nprivate:\n\n  std::vector<unsigned int> comb(int N, int K) {\n    std::string bitmask(K, 1); // K leading 1's\n    bitmask.resize(N, 0); // N-K trailing 0's\n    std::vector<unsigned int> ret;\n    // print integers and permute bitmask\n    do {\n      for (int i = 0; i < N; ++i) { // [0..N-1] integers\n          if (bitmask[i]) ret.push_back(i);\n      }\n    } while (std::prev_permutation(bitmask.begin(), bitmask.end()));\n    return ret;\n  }\n\n  std::vector<float> hanning(unsigned int len) {\n    std::vector<float> ret(len);\n    for(unsigned int i = 0; i < len; i++) {\n        float multiplier = 0.5f * (1.f - cosf(2.0*M_PI*(float)i/(float)len));\n        ret.at(i) = multiplier;\n    }\n    return ret;\n  }\n\n  unsigned int maxIdx(float* data, unsigned int offset, unsigned int max_dist_i);\n\n  //////////////////////////////////////////////////////////////////////////////\n  // Interpolate by fitting a gaussian function f = a*exp(-b(x-c)**2) to three\n  // values around the maximum value of the cross-correlation vector.\n  //\n  // Zhang, Lei, and Xiaolin Wu. \"On cross correlation based-discrete time delay\n  // estimation.\" Acoustics, Speech, and Signal Processing, 2005. Proceedings.\n  // (ICASSP'05). IEEE International Conference on. Vol. 4. IEEE, 2005.\n  //////////////////////////////////////////////////////////////////////////////\n\n  float interpolateTau(float* data, unsigned int i);\n\n// Keeping the fields public for now for debugging\npublic:\n  fftwf_plan fft_;\n  fftwf_plan ifft_;\n  std::vector< fftwf_complex* > f_buffers_;\n  std::vector< float* > t_buffers_;\n  std::vector< float > han_window_;\n\n  std::vector< fftwf_complex* > corr_buffers_;\n  std::vector< float* > real_corr_buffers_;\n\n  std::vector<float> ret_p_;\n  std::vector<float> ret_az_;\n  std::vector<float> ret_el_;\n\n  unsigned int fs_;\n  unsigned int frame_len_;\n  unsigned int complex_len_;\n  unsigned int transform_len_;\n  unsigned int transform_len_dif_;\n  unsigned int num_win_;\n  unsigned int resp_len_;\n  unsigned int num_mics_;\n  unsigned int num_mic_pairs_;\n  unsigned int max_dist_i_;\n  unsigned int offset_;\n  Eigen::MatrixXf mic_locs_;\n  Eigen::MatrixXf ls_locs_;\n  Eigen::MatrixXi mic_pairs_;\n  Eigen::MatrixXf V_;\n  Eigen::MatrixXf inv_V_;\n  Eigen::MatrixXf pair_dists_;\n  Eigen::MatrixXf tau_;\n  float c_;\n\n};\n\n#endif\n", "meta": {"hexsha": "b575ac7161804589c055845dfec635b07d17fc26", "size": 5838, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/spatialDecomposition.hpp", "max_stars_repo_name": "juuli/cxxsdm", "max_stars_repo_head_hexsha": "9db0d017c84b3f3fc1827627025ebaf8166b57fc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-04-30T20:32:30.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-30T20:32:30.000Z", "max_issues_repo_path": "src/spatialDecomposition.hpp", "max_issues_repo_name": "juuli/cxxsdm", "max_issues_repo_head_hexsha": "9db0d017c84b3f3fc1827627025ebaf8166b57fc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/spatialDecomposition.hpp", "max_forks_repo_name": "juuli/cxxsdm", "max_forks_repo_head_hexsha": "9db0d017c84b3f3fc1827627025ebaf8166b57fc", "max_forks_repo_licenses": ["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.2541436464, "max_line_length": 135, "alphanum_fraction": 0.6438848921, "num_tokens": 1536, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.47068580084562217}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2015 NumScale SAS\n  @copyright 2015 J.T. Lapreste\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_ULP_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_ULP_HPP_INCLUDED\n\n#include <boost/simd/constant/mindenormal.hpp>\n#include <boost/simd/constant/nan.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/function/scalar/abs.hpp>\n#include <boost/simd/function/scalar/bitwise_cast.hpp>\n#include <boost/simd/function/scalar/is_eqz.hpp>\n#include <boost/simd/function/scalar/is_invalid.hpp>\n#include <boost/simd/function/scalar/min.hpp>\n#include <boost/simd/function/scalar/prev.hpp>\n#include <boost/dispatch/function/overload.hpp>\n#include <boost/dispatch/meta/as_integer.hpp>\n#include <boost/config.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n BOOST_DISPATCH_OVERLOAD ( ulp_\n                         , (typename A0)\n                         , bd::cpu_\n                         , bd::scalar_< bd::arithmetic_<A0> >\n                         )\n {\n   BOOST_FORCEINLINE A0 operator() ( A0 const &) const BOOST_NOEXCEPT\n   {\n     return One<A0>();\n   }\n };\n\n  BOOST_DISPATCH_OVERLOAD ( ulp_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_< bd::floating_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() ( A0 a0) const BOOST_NOEXCEPT\n    {\n      using i_t = bd::as_integer_t<A0,unsigned>;\n      if (is_eqz(a0)) return Mindenormal<A0>();\n      if (is_invalid(a0)) return Nan<A0>();\n      const A0 x = boost::simd::abs(a0);\n      i_t aa = bitwise_cast<i_t>(x);\n      i_t bb = aa;\n      --bb;\n      ++aa;\n      return boost::simd::min(x-bitwise_cast<A0>(bb), bitwise_cast<A0>(aa)-x);\n    }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "cf8738cef978749a6d4c3dc3b8ed4bd3803cc90a", "size": 2135, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arch/common/scalar/function/ulp.hpp", "max_stars_repo_name": "yaeldarmon/boost.simd", "max_stars_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/simd/arch/common/scalar/function/ulp.hpp", "max_issues_repo_name": "yaeldarmon/boost.simd", "max_issues_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/arch/common/scalar/function/ulp.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": 32.3484848485, "max_line_length": 100, "alphanum_fraction": 0.5714285714, "num_tokens": 498, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.47068580084562217}}
{"text": "/* test_weibull_distribution.cpp\n *\n * Copyright Steven Watanabe 2010\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#include <boost/random/weibull_distribution.hpp>\n#include <limits>\n\n#define BOOST_RANDOM_DISTRIBUTION boost::random::weibull_distribution<>\n#define BOOST_RANDOM_ARG1 a\n#define BOOST_RANDOM_ARG2 b\n#define BOOST_RANDOM_ARG1_DEFAULT 1.0\n#define BOOST_RANDOM_ARG2_DEFAULT 1.0\n#define BOOST_RANDOM_ARG1_VALUE 7.5\n#define BOOST_RANDOM_ARG2_VALUE 0.25\n\n#define BOOST_RANDOM_DIST0_MIN 0.0\n#define BOOST_RANDOM_DIST0_MAX (std::numeric_limits<double>::infinity)()\n#define BOOST_RANDOM_DIST1_MIN 0.0\n#define BOOST_RANDOM_DIST1_MAX (std::numeric_limits<double>::infinity)()\n#define BOOST_RANDOM_DIST2_MIN 0.0\n#define BOOST_RANDOM_DIST2_MAX (std::numeric_limits<double>::infinity)()\n\n#define BOOST_RANDOM_TEST1_PARAMS\n#define BOOST_RANDOM_TEST1_MIN 0.0\n#define BOOST_RANDOM_TEST1_MAX 100.0\n\n#define BOOST_RANDOM_TEST2_PARAMS (1.0, 1000000.0)\n#define BOOST_RANDOM_TEST2_MIN 100.0\n\n#include \"test_distribution.ipp\"\n", "meta": {"hexsha": "cd88b6d5f8a452b9ea0ce589ecad6035e004d5b0", "size": 1144, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/random/test/test_weibull_distribution.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "boost/libs/random/test/test_weibull_distribution.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "boost/libs/random/test/test_weibull_distribution.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "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.9189189189, "max_line_length": 72, "alphanum_fraction": 0.8111888112, "num_tokens": 302, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.47068579452154574}}
{"text": "// ----------------------------------------------------------------------------\n// USAGE EXAMPLES\n// ----------------------------------------------------------------------------\n\n//----------------------------------------------------------\n// Discrete Conformal Map parameterization\n// circle border\n// OpenNL solver\n// output is a eps map\n// input file is mesh.off\n//----------------------------------------------------------\n// polyhedron_ex_parameterization -t conformal -b circle mesh.off mesh.eps\n\n//----------------------------------------------------------\n// Least Squares Conformal Maps parameterization\n// two pinned vertices (automatically picked)\n// OpenNL solver\n// output is a .obj\n// input file is mesh.off\n//----------------------------------------------------------\n// polyhedron_ex_parameterization -t lscm -b 2pts mesh.off mesh.obj\n\n\n#include <CGAL/Timer.h>\n#include <CGAL/parameterize.h>\n#include <CGAL/Parameterization_mesh_patch_3.h>\n#include <CGAL/Circular_border_parameterizer_3.h>\n#include <CGAL/Square_border_parameterizer_3.h>\n#include <CGAL/Two_vertices_parameterizer_3.h>\n#include <CGAL/Barycentric_mapping_parameterizer_3.h>\n#include <CGAL/Discrete_conformal_map_parameterizer_3.h>\n#include <CGAL/Discrete_authalic_parameterizer_3.h>\n#include <CGAL/Mean_value_coordinates_parameterizer_3.h>\n#include <CGAL/LSCM_parameterizer_3.h>\n#include <CGAL/Parameterization_mesh_feature_extractor.h>\n\n#include <CGAL/OpenNL/linear_solver.h>\n\n#include \"Polyhedron_ex.h\"\n#include \"Mesh_cutter.h\"\n#include \"Parameterization_polyhedron_adaptor_ex.h\"\n\n#include <iostream>\n#include <string.h>\n#include <ctype.h>\n#include <fstream>\n#include <cassert>\n\n#if defined(CGAL_USE_BOOST_PROGRAM_OPTIONS) && ! defined(DONT_USE_BOOST_PROGRAM_OPTIONS)\n    #include <boost/program_options.hpp>\n    namespace po = boost::program_options;\n#endif\n\n\n// ----------------------------------------------------------------------------\n// Private types\n// ----------------------------------------------------------------------------\n\ntypedef Polyhedron_ex                                       Polyhedron;\n\n// Mesh adaptors\ntypedef Parameterization_polyhedron_adaptor_ex              Parameterization_polyhedron_adaptor;\ntypedef CGAL::Parameterization_mesh_patch_3<Parameterization_polyhedron_adaptor>\n                                                            Mesh_patch_polyhedron;\n\n// Type describing a border or seam as a vertex list\ntypedef std::list<Parameterization_polyhedron_adaptor::Vertex_handle>\n                                                            Seam;\n\n\n// ----------------------------------------------------------------------------\n// Private functions\n// ----------------------------------------------------------------------------\n\n// Cut the mesh to make it homeomorphic to a disk\n// or extract a region homeomorphic to a disc.\n// Return the border of this region (empty on error)\n//\n// CAUTION:\n// This method is provided \"as is\". It is very buggy and simply part of this example.\n// Developers using this package should implement a more robust cut algorithm!\nstatic Seam cut_mesh(Parameterization_polyhedron_adaptor& mesh_adaptor)\n{\n    // Helper class to compute genus or extract borders\n    typedef CGAL::Parameterization_mesh_feature_extractor<Parameterization_polyhedron_adaptor_ex>\n                                            Mesh_feature_extractor;\n    typedef Mesh_cutter::Backbone           Backbone;\n\n    Seam seam;              // returned list\n\n    // Get refererence to Polyhedron_3 mesh\n    Polyhedron& mesh = mesh_adaptor.get_adapted_mesh();\n\n    // Extract mesh borders and compute genus\n    Mesh_feature_extractor feature_extractor(mesh_adaptor);\n    int nb_borders = feature_extractor.get_nb_borders();\n    int genus = feature_extractor.get_genus();\n\n    // If mesh is a topological disk\n    if (genus == 0 && nb_borders > 0)\n    {\n        // Pick the longest border\n        seam = feature_extractor.get_longest_border();\n    }\n    else // if mesh is *not* a topological disk, create a virtual cut\n    {\n        Backbone seamingBackbone;           // result of cutting\n        Backbone::iterator he;\n\n        // Compute a cutting path that makes the mesh a \"virtual\" topological disk\n        mesh.compute_facet_centers();\n        Mesh_cutter cutter(mesh);\n        if (genus == 0)\n        {\n            // no border, we need to cut the mesh\n            assert (nb_borders == 0);\n            cutter.cut(seamingBackbone);    // simple cut\n        }\n        else // genus > 0 -> cut the mesh\n        {\n            cutter.cut_genus(seamingBackbone);\n        }\n\n        // The Mesh_cutter class is quite buggy\n        // => we check that seamingBackbone is valid\n        //\n        // 1) Check that seamingBackbone is not empty\n        if (seamingBackbone.begin() == seamingBackbone.end())\n            return seam;                    // return empty list\n        //\n        // 2) Check that seamingBackbone is a loop and\n        //    count occurences of seam halfedges\n        mesh.tag_halfedges(0);              // Reset counters\n        for (he = seamingBackbone.begin(); he != seamingBackbone.end(); he++)\n        {\n            // Get next halfedge iterator (looping)\n            Backbone::iterator next_he = he;\n            next_he++;\n            if (next_he == seamingBackbone.end())\n                next_he = seamingBackbone.begin();\n\n            // Check that seamingBackbone is a loop: check that\n            // end of current HE == start of next one\n            if ((*he)->vertex() != (*next_he)->opposite()->vertex())\n                return seam;                // return empty list\n\n            // Increment counter (in \"tag\" field) of seam halfedges\n            (*he)->tag( (*he)->tag()+1 );\n        }\n        //\n        // 3) check that the seamingBackbone is a two-way list\n        for (he = seamingBackbone.begin(); he != seamingBackbone.end(); he++)\n        {\n            // Counter of halfedge and opposite halfedge must be 1\n            if ((*he)->tag() != 1 || (*he)->opposite()->tag() != 1)\n                return seam;                // return empty list\n        }\n\n        // Convert list of halfedges to a list of vertices\n        for (he = seamingBackbone.begin(); he != seamingBackbone.end(); he++)\n            seam.push_back((*he)->vertex());\n    }\n\n    return seam;\n}\n\n// Call appropriate parameterization method based on command line parameters\ntemplate<\n    class ParameterizationMesh_3,   // 3D surface\n    class GeneralSparseLinearAlgebraTraits_d,\n                                    // Traits class to solve a general sparse linear system\n    class SymmetricSparseLinearAlgebraTraits_d\n                                    // Traits class to solve a symmetric sparse linear system\n>\ntypename CGAL::Parameterizer_traits_3<ParameterizationMesh_3>::Error_code\nparameterize(ParameterizationMesh_3& mesh,  // Mesh parameterization adaptor\n             const std::string& type,              // type of parameterization (see usage)\n             const std::string& border)            // type of border parameterization (see usage)\n{\n    typename CGAL::Parameterizer_traits_3<ParameterizationMesh_3>::Error_code err;\n\n    if ( (type == std::string(\"floater\"))  && (border == std::string(\"circle\")) )\n    {\n        err = CGAL::parameterize(\n            mesh,\n            CGAL::Mean_value_coordinates_parameterizer_3<\n                ParameterizationMesh_3,\n                CGAL::Circular_border_arc_length_parameterizer_3<ParameterizationMesh_3>,\n                GeneralSparseLinearAlgebraTraits_d\n            >());\n    }\n    else if ( (type == std::string(\"floater\")) && (border == std::string(\"square\")) )\n    {\n        err = CGAL::parameterize(\n            mesh,\n            CGAL::Mean_value_coordinates_parameterizer_3<\n                ParameterizationMesh_3,\n                CGAL::Square_border_arc_length_parameterizer_3<ParameterizationMesh_3>,\n                GeneralSparseLinearAlgebraTraits_d\n            >());\n    }\n    else if ( (type == std::string(\"barycentric\")) && (border == std::string(\"circle\")) )\n    {\n        err = CGAL::parameterize(\n            mesh,\n            CGAL::Barycentric_mapping_parameterizer_3<\n                ParameterizationMesh_3,\n                CGAL::Circular_border_uniform_parameterizer_3<ParameterizationMesh_3>,\n                GeneralSparseLinearAlgebraTraits_d\n            >());\n    }\n    else if ( (type == std::string(\"barycentric\")) && (border == std::string(\"square\")) )\n    {\n        err = CGAL::parameterize(\n            mesh,\n            CGAL::Barycentric_mapping_parameterizer_3<\n                ParameterizationMesh_3,\n                CGAL::Square_border_uniform_parameterizer_3<ParameterizationMesh_3>,\n                GeneralSparseLinearAlgebraTraits_d\n            >());\n    }\n    else if ( (type == std::string(\"conformal\")) && (border == std::string(\"circle\")) )\n    {\n        err = CGAL::parameterize(\n            mesh,\n            CGAL::Discrete_conformal_map_parameterizer_3<\n                ParameterizationMesh_3,\n                CGAL::Circular_border_arc_length_parameterizer_3<ParameterizationMesh_3>,\n                GeneralSparseLinearAlgebraTraits_d\n            >());\n    }\n    else if ( (type == std::string(\"conformal\")) && (border == std::string(\"square\")) )\n    {\n        err = CGAL::parameterize(\n            mesh,\n            CGAL::Discrete_conformal_map_parameterizer_3<\n                ParameterizationMesh_3,\n                CGAL::Square_border_arc_length_parameterizer_3<ParameterizationMesh_3>,\n                GeneralSparseLinearAlgebraTraits_d\n            >());\n    }\n    else if ( (type == std::string(\"authalic\")) && (border == std::string(\"circle\")) )\n    {\n        err = CGAL::parameterize(\n            mesh,\n            CGAL::Discrete_authalic_parameterizer_3<\n                ParameterizationMesh_3,\n                CGAL::Circular_border_arc_length_parameterizer_3<ParameterizationMesh_3>,\n                GeneralSparseLinearAlgebraTraits_d\n            >());\n    }\n    else if ( (type == std::string(\"authalic\")) && (border == std::string(\"square\")) )\n    {\n        err = CGAL::parameterize(\n            mesh,\n            CGAL::Discrete_authalic_parameterizer_3<\n                ParameterizationMesh_3,\n                CGAL::Square_border_arc_length_parameterizer_3<ParameterizationMesh_3>,\n                GeneralSparseLinearAlgebraTraits_d\n            >());\n    }\n    else if ( (type == std::string(\"lscm\")) && (border == std::string(\"2pts\")) )\n    {\n        err = CGAL::parameterize(\n            mesh,\n            CGAL::LSCM_parameterizer_3<\n                ParameterizationMesh_3,\n                CGAL::Two_vertices_parameterizer_3<ParameterizationMesh_3>,\n                SymmetricSparseLinearAlgebraTraits_d\n            >());\n    }\n    else\n    {\n        std::cerr << \"Error: invalid parameters combination \" << type << \" + \" << border << std::endl;\n        err = CGAL::Parameterizer_traits_3<ParameterizationMesh_3>::ERROR_WRONG_PARAMETER;\n    }\n\n    return err;\n}\n\n\n// ----------------------------------------------------------------------------\n// main()\n// ----------------------------------------------------------------------------\n\n#if defined(CGAL_USE_BOOST_PROGRAM_OPTIONS) && ! defined(DONT_USE_BOOST_PROGRAM_OPTIONS)\nint main(int argc, char * argv[])\n#else\nint main()\n#endif\n{\n    CGAL::Timer total_timer;\n    total_timer.start();\n\n    std::cerr << \"PARAMETERIZATION\" << std::endl;\n\n    //***************************************\n    // Read options on the command line\n    //***************************************\n\n    std::string type;               // default: Floater param\n    std::string border;             // default: circular border param.\n    std::string solver;             // default: OpenNL solver\n    std::string input;              // required\n    std::string output;             // default: out.eps\n    try\n    {\n#if defined(CGAL_USE_BOOST_PROGRAM_OPTIONS) && ! defined(DONT_USE_BOOST_PROGRAM_OPTIONS)\n        po::options_description desc(\"Allowed options\");\n        desc.add_options()\n            (\"help,h\", \"prints this help message\")\n            (\"type,t\", po::value<std::string>(&type)->default_value(\"floater\"),\n            \"parameterization method: floater, conformal, barycentric, authalic or lscm\")\n            (\"border,b\", po::value<std::string>(&border)->default_value(\"circle\"),\n            \"border shape: circle, square or 2pts (lscm only)\")\n            (\"solver,s\", po::value<std::string>(&solver)->default_value(\"opennl\"),\n            \"solver: opennl\")\n            (\"input,i\", po::value<std::string>(&input)->default_value(\"\"),\n            \"input mesh (OFF)\")\n            (\"output,o\", po::value<std::string>(&output)->default_value(\"out.eps\"),\n            \"output file (EPS or OBJ)\")\n            ;\n\n        po::positional_options_description p;\n        p.add(\"input\", 1);\n        p.add(\"output\", 1);\n\n        po::variables_map vm;\n        po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm);\n        po::notify(vm);\n\n        if (vm.count(\"help\")) {\n            std::cout << desc << \"\\n\";\n            return 1;\n        }\n#else\n        std::cerr << \"Command-line options require Boost.ProgramOptions\" << std::endl;\n        std::cerr << \"Use hard-coded options\" << std::endl;\n        border = \"square\";\n        type = \"floater\";\n        solver = \"opennl\";\n        input = \"data/rotor.off\";\n        output = \"rotor_floater_square_opennl_parameterized.obj\";\n#endif\n    }\n    catch(std::exception& e) {\n      std::cerr << \"error: \" << e.what() << \"\\n\";\n      return 1;\n    }\n    catch(...) {\n      std::cerr << \"Exception of unknown type!\\n\";\n      throw;\n    }\n\n    //***************************************\n    // Read the mesh\n    //***************************************\n\n    CGAL::Timer task_timer;\n    task_timer.start();\n\n    // Read the mesh\n    std::ifstream stream(input.c_str());\n    Polyhedron mesh;\n    stream >> mesh;\n    if(!stream || !mesh.is_valid() || mesh.empty())\n    {\n        std::cerr << \"Error: cannot read OFF file \" << input << std::endl;\n        return EXIT_FAILURE;\n    }\n\n    std::cerr << \"Read file \" << input << \": \"\n              << task_timer.time() << \" seconds \"\n              << \"(\" << mesh.size_of_facets() << \" facets, \"\n              << mesh.size_of_vertices() << \" vertices)\" << std::endl;\n    task_timer.reset();\n\n    //***************************************\n    // Create mesh adaptor\n    //***************************************\n\n    // The Surface_mesh_parameterization package needs an adaptor to handle Polyhedron_ex meshes\n    Parameterization_polyhedron_adaptor mesh_adaptor(mesh);\n\n    // The parameterization methods support only meshes that\n    // are topological disks => we need to compute a cutting path\n    // that makes the mesh a \"virtual\" topological disk\n    //\n    // 1) Cut the mesh\n    Seam seam = cut_mesh(mesh_adaptor);\n    if (seam.empty())\n    {\n        std::cerr << \"Input mesh not supported: the example cutting algorithm is too simple to cut this shape\" << std::endl;\n        return EXIT_FAILURE;\n    }\n    //\n    // 2) Create adaptor that virtually \"cuts\" a patch in a Polyhedron_ex mesh\n    Mesh_patch_polyhedron   mesh_patch(mesh_adaptor, seam.begin(), seam.end());\n    if (!mesh_patch.is_valid())\n    {\n        std::cerr << \"Input mesh not supported: non manifold shape or invalid cutting\" << std::endl;\n        return EXIT_FAILURE;\n    }\n\n    std::cerr << \"Mesh cutting: \" << task_timer.time() << \" seconds.\" << std::endl;\n    task_timer.reset();\n\n    //***************************************\n    // switch parameterization\n    //***************************************\n\n    std::cerr << \"Parameterization...\" << std::endl;\n\n    // Defines the error codes\n    typedef CGAL::Parameterizer_traits_3<Mesh_patch_polyhedron> Parameterizer;\n    Parameterizer::Error_code err;\n\n    if (solver == std::string(\"opennl\"))\n    {\n        err = parameterize<Mesh_patch_polyhedron,\n                           OpenNL::DefaultLinearSolverTraits<double>,\n                           OpenNL::SymmetricLinearSolverTraits<double>\n                          >(mesh_patch, type, border);\n    }\n    else\n    {\n        std::cerr << \"Error: invalid solver parameter \" << solver << std::endl;\n        err = Parameterizer::ERROR_WRONG_PARAMETER;\n    }\n\n    // Report errors\n    switch(err) {\n    case Parameterizer::OK: // Success\n        break;\n    case Parameterizer::ERROR_EMPTY_MESH: // Input mesh not supported\n    case Parameterizer::ERROR_NON_TRIANGULAR_MESH:\n    case Parameterizer::ERROR_NO_TOPOLOGICAL_DISC:\n    case Parameterizer::ERROR_BORDER_TOO_SHORT:\n        std::cerr << \"Input mesh not supported: \" << Parameterizer::get_error_message(err) << std::endl;\n        return EXIT_FAILURE;\n        break;\n    default: // Error\n        std::cerr << \"Error: \" << Parameterizer::get_error_message(err) << std::endl;\n        return EXIT_FAILURE;\n        break;\n    };\n\n    std::cerr << \"Parameterization: \" << task_timer.time() << \" seconds.\" << std::endl;\n    task_timer.reset();\n\n    //***************************************\n    // Output\n    //***************************************\n\n    // get output file's extension\n    std::string extension = output.substr(output.find_last_of('.'));\n\n    // Save mesh\n    if (extension == \".eps\" || extension == \".EPS\")\n    {\n        // write Postscript file\n        if ( ! mesh.write_file_eps(output.c_str()) )\n        {\n            std::cerr << \"Error: cannot write file \" << output << std::endl;\n            return EXIT_FAILURE;\n        }\n    }\n    else if (extension == \".obj\" || extension == \".OBJ\")\n    {\n        // write Wavefront obj file\n        if ( ! mesh.write_file_obj(output.c_str()) )\n        {\n            std::cerr << \"Error: cannot write file \" << output << std::endl;\n            return EXIT_FAILURE;\n        }\n    }\n    else\n    {\n        std::cerr << \"Error: output format not supported\" << output << std::endl;\n        err = Parameterizer::ERROR_WRONG_PARAMETER;\n        return EXIT_FAILURE;\n    }\n\n    std::cerr << \"Write file \" << output << \": \"\n              << task_timer.time() << \" seconds \" << std::endl;\n\n    return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "f98a3b556d9785780eee68e38f2d3fd6c732517b", "size": 18174, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "graphics/cgal/Surface_mesh_parameterization/examples/Surface_mesh_parameterization/polyhedron_ex_parameterization.cpp", "max_stars_repo_name": "hlzz/dotfiles", "max_stars_repo_head_hexsha": "0591f71230c919c827ba569099eb3b75897e163e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-03-30T14:31:52.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-02T05:01:32.000Z", "max_issues_repo_path": "graphics/cgal/Surface_mesh_parameterization/examples/Surface_mesh_parameterization/polyhedron_ex_parameterization.cpp", "max_issues_repo_name": "hlzz/dotfiles", "max_issues_repo_head_hexsha": "0591f71230c919c827ba569099eb3b75897e163e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "graphics/cgal/Surface_mesh_parameterization/examples/Surface_mesh_parameterization/polyhedron_ex_parameterization.cpp", "max_forks_repo_name": "hlzz/dotfiles", "max_forks_repo_head_hexsha": "0591f71230c919c827ba569099eb3b75897e163e", "max_forks_repo_licenses": ["BSD-3-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.1656441718, "max_line_length": 124, "alphanum_fraction": 0.5604710025, "num_tokens": 3989, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.47068579452154574}}
{"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\n#pragma once\n\n/// @file\n///\n/// Code used to manage 2d boxes\n\n#include <iostream>\n#include <vector>\n#include <array>\n#include <Eigen/Dense>\n#include <random>\n#include <utilities.hpp>\n#include <pcg_random.hpp>\n#include <exceptions.hpp>\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n#include <boost/geometry/geometries/geometries.hpp>\n#include <boost/geometry/geometries/adapted/boost_tuple.hpp>\n#include <mutex>\n#include <limits>\n#include <map>\n\nBOOST_GEOMETRY_REGISTER_BOOST_TUPLE_CS(cs::cartesian);\n\nnamespace alma {\n\n/// Those are helper functions that turn\n/// 3d points to 2d points\n///@param xyz - 3d vector to become 2d vector\n///@return 2d vector discarding the z axis\ninline Eigen::Vector2d xy_me(Eigen::Vector3d& xyz) {\n    return xyz.block(0, 0, 2, 1);\n}\n\n/// Those are helper functions that turn\n/// 3d points to 2d points\n///@param xyz - matrix of 3d points to become 2d vector\n///@return 2d vectors discarding the z axis\ninline Eigen::MatrixXd xy_me(Eigen::MatrixXd& xyz) {\n    return xyz.block(0, 0, 2, xyz.cols());\n}\n/// It appends a 0 to z axis to obtain 3d vector\n///@param xy - 2d vector to become 3d vector\n///@return 2d vector adding\ninline Eigen::Vector3d upDim(Eigen::Vector2d& xy) {\n    Eigen::Vector3d xyz;\n    xyz << xy(0), xy(1), 0.;\n    return xyz;\n}\n\n\n/// This contains info about sides\nstruct geom2d_border {\n    /// Point limits of border\n    Eigen::Vector2d p1;\n    Eigen::Vector2d p2;\n    // The vector defined\n    /// as p2-p1\n    Eigen::Vector2d nd;\n    /// The normalized perpendicular vector\n    /// pointing outside\n    Eigen::Vector2d np;\n    /// The segment object\n    boost::geometry::model::segment<boost::tuple<double, double>> sb;\n    /// The segment object little bit larger\n    boost::geometry::model::segment<boost::tuple<double, double>> sbl;\n    /// Properties of border:\n    double Tboxeq = -1;\n    int Eborder = 0;\n\n    std::mutex door;\n\n    geom2d_border() = default;\n\n    geom2d_border(const geom2d_border& A)\n        : p1(A.p1), p2(A.p2), nd(A.nd), np(A.np), sb(A.sb), sbl(A.sbl),\n          Tboxeq(A.Tboxeq), Eborder(A.Eborder), door() {\n        /// The mutex is not copyied but generated\n        /// as new in the copy\n    }\n\n    geom2d_border& operator=(const geom2d_border& A) {\n        p1 = A.p1;\n        p2 = A.p2;\n        nd = A.nd;\n        np = A.np;\n        sb = A.sb;\n        sbl = A.sbl;\n        Tboxeq = A.Tboxeq;\n        Eborder = A.Eborder;\n        return *this;\n    }\n\n\n    /// Return a random point in the border\n    ///@param[in] r - random generator\n    ///@return    3d vector with random position\n    template <class Random> Eigen::Vector2d get_random_point(Random& r) {\n        Eigen::Vector2d rp =\n            this->p1 + std::uniform_real_distribution(0., 1.)(r) * this->nd;\n        while (true) {\n            boost::tuple<double, double> rp_(rp(0), rp(1));\n            if (boost::geometry::covered_by(rp_, sb))\n                break;\n            rp =\n                this->p1 + std::uniform_real_distribution(0., 1.)(r) * this->nd;\n        }\n        return rp;\n    }\n\n    /// Returns the border length in length units\n    ///@return border length in length units\n    double get_length() const {\n        return (p2 - p1).norm();\n    }   \n};\n\n\nclass geometry_2d {\nprivate:\n    /// Some typedefs to make shorter definitions\n    typedef boost::tuple<double, double> point;\n    typedef boost::geometry::model::polygon<point> polygon;\n    typedef boost::geometry::model::segment<point> segment;\n\n    /// Boost convex_hull\n    polygon hull;\n\n    /// Central point\n    Eigen::Vector2d center;\n\n    /// Area\n    double area;\n    std::vector<geom2d_border> borders;\n\n    /// Contact map\n    /// [other geoms ids,border defining contact region]\n    std::map<std::size_t, std::vector<geom2d_border>> contacts;\n\n    /// Geom id\n    std::size_t id;\n\n    /// Matrix containing bounding box\n    Eigen::MatrixXd bbox;\n\n\n    /// It returns the bounding box limits\n    ///@param[in] p - polygon to search the bounding box from\n    ///@returns   the bounding box stored as follows:\n    ///           (xmin,ymin)\n    ///           (xmax,ymax)\n    Eigen::MatrixXd bounding_box(polygon& p);\n\n    /// Get the sides of the figures\n    ///@param[in] vertices_ :  Vector containing the vertices\n    void get_sides(Eigen::MatrixXd& vertices_);\n\npublic:\n    /// Public variables about info\n    /// Equilibrium temperature\n    double Teq = -1.;\n    double Treal = -1.;\n    /// Is reservoir\n    bool reservoir = false;\n    /// Material ID\n    std::string material;\n    /// If periodic\n    bool periodic = false;\n    /// Translation to apply\n    Eigen::Vector2d translation;\n    /// Box id to which translate\n    std::size_t box2translate;\n    /// Angle\n    double theta = 0.;\n    Eigen::Matrix2d rotmat;\n\n    /// Notice that move semantics is\n    /// specifically forbiden\n    /// as move Constructor and\n    /// move assignment operator\n    /// are declared deleted\n\n    /// Default and deleted constructors:\n    geometry_2d() = default;\n    geometry_2d(const geometry_2d& original) = default;\n    geometry_2d(geometry_2d&& source) = delete;\n    ~geometry_2d() = default;\n\n    /// Default assignment operators:\n    geometry_2d& operator=(const geometry_2d& original) = default;\n    geometry_2d& operator=(geometry_2d&& source) = delete;\n\n    /// Constructor\n    ///@param[in] vertices_ - Matrix containing 2d points\n    ///                       of the triangle vertex\n    geometry_2d(Eigen::MatrixXd& vertices_);\n\n    /// Other constructors are left to compiler\n\n    /// It returns true if inside or in border of hull\n    ///@param[in] point2check - 2d point to check if inside geometry\n    ///@return true if point is inside geometry\n    bool inside(Eigen::Vector2d& point2check) const;\n\n\n    /// It returns the area\n    ///@return area in (length unit)**2\n    double get_area() const {\n        return this->area;\n    }\n\n    /// It returns the center\n    ///@return center (calculated using mean)\n    Eigen::Vector2d get_center() const {\n        return this->center;\n    }\n\n    /// It returns intersection with polygon sides:\n    ///@param[in] r0 - original position\n    ///@param[in] v  - velocity vector\n    ///@param[in] dt - time step\n    ///@return    [time to side collision,\n    ///            collision position    ,\n    ///            border ids]\n    std::tuple<double, Eigen::Vector2d, std::vector<int>>\n    get_inter_side(Eigen::Vector2d& r0, Eigen::Vector2d& v, double dt);\n\n    /// Getter for geometry ID\n    ///@return geometry id\n    std::size_t get_id() {\n        return this->id;\n    }\n    /// Setter for geometry ID\n    ///@param[in] vale to set geometry id to\n    void set_id(std::size_t id_) {\n        this->id = id_;\n    }\n\n\n    /// Builds up contacts from other boxes\n    /// Id need to be set up\n    ///@param[in] system - geometry_2d of all system\n    void calculate_contacts(std::vector<geometry_2d>& system);\n\n    /// Returns borders in general\n    ///@return all polygon sides\n    std::vector<geom2d_border>& get_borders() {\n        return this->borders;\n    }\n\n    /// Returns border\n    ///@param[in] border_id - the border id\n    ///@return specific side of the polygon\n    geom2d_border& get_border(std::size_t border_id) {\n        return this->borders[border_id];\n    }\n\n    /// Modify border Tboxeq variable\n    ///@param[in] border_id - the border id\n    ///@param[in] _Tboxeq - value to which variable is set\n    void set_border_Tboxeq(std::size_t border_id, double _Tboxeq) {\n        this->borders[border_id].Tboxeq = _Tboxeq;\n    }\n\n\n    /// Get border Tboxeq variable\n    ///@param[in] border_id - the border id\n    ///@return id-th side temperature\n    double get_border_Tboxeq(std::size_t border_id) {\n        return this->borders[border_id].Tboxeq;\n    }\n\n\n    /// Modify border Eborder variable\n    ///@param[in] border_id - the border id\n    ///@param[in] _Eborder - value to which variable is set\n    void set_border_Eborder(std::size_t border_id, double _Eborder) {\n        this->borders[border_id].door.lock();\n        this->borders[border_id].Eborder = _Eborder;\n        this->borders[border_id].door.unlock();\n    }\n\n    /// Modify border Eborder variable\n    ///@param[in] border_id - the border id\n    ///@param[in] _Eborder  - value to add to variable\n    void add_border_Eborder(std::size_t border_id, double _Eborder) {\n        this->borders[border_id].door.lock();\n        this->borders[border_id].Eborder += _Eborder;\n        this->borders[border_id].door.unlock();\n    }\n\n\n    /// Get border Eborder variable\n    ///@param[in] border_id - the border id\n    ///@return id-th boundary energy\n    double get_border_Eborder(std::size_t border_id) {\n        return this->borders[border_id].Eborder;\n    }\n\n\n    /// Returns the polygon\n    ///@return polygon\n    polygon& get_poly() {\n        return this->hull;\n    }\n\n    /// Returns the contacts of the geometry\n    ///@return [contact box id,vector(contact region)]\n    std::map<std::size_t, std::vector<geom2d_border>>& get_contacts() {\n        return this->contacts;\n    }\n\n    /// Returns bounding box limits\n    ///@return bounding box limits ((xmin,ymin),(xmax,ymax))\n    Eigen::MatrixXd get_bbox() {\n        return this->bbox;\n    }\n\n    /// Get point random point inside the geometry\n    ///@param[in] r - random number generator\n    ///@return    random coordinates inside geometry\n    template <class Random> Eigen::Vector2d get_random_point(Random& r) {\n        /// Randomly generate points inside bounding box\n        /// then check if inside geometry\n        /// Inefficient when the ratio between bbox and\n        /// geometry is large\n        Eigen::Vector2d rtrial;\n        while (true) {\n            rtrial(0) =\n                this->bbox(0, 0) + std::uniform_real_distribution(0., 1.)(r) *\n                                       (this->bbox(1, 0) - this->bbox(0, 0));\n            rtrial(1) =\n                this->bbox(0, 1) + std::uniform_real_distribution(0., 1.)(r) *\n                                       (this->bbox(1, 1) - this->bbox(0, 1));\n            point rt(rtrial(0), rtrial(1));\n            if (boost::geometry::covered_by(rt, this->get_poly()))\n                break;\n        }\n        return rtrial;\n    }\n\n\n    /// Function for translation:\n    ///@param[in] r0   - initial point to translate\n    ///@param[in] v    - point direction\n    ///@param[in] gs   - vector of geometries\n    ///@param[in] rng  - random number generator\n    ///@return [new box id,new position after translation]\n    template <class Random>\n    std::pair<std::size_t, Eigen::Vector2d> translate(\n        Eigen::Vector2d& r0,\n        Eigen::Vector2d& v,\n        std::vector<geometry_2d>& gs,\n        Random& rng) {\n        /// Check if using it in periodic structure\n        if (!gs[this->id].periodic) {\n            throw alma::geometry_error(\"Error: this can only be used in\"\n                                       \"periodic cells\");\n        }\n\n        /// Get translation vector\n        /// and box id to translate\n        Eigen::Vector2d T = 1.0005 * gs[this->id].translation;\n        auto Tibox = gs[this->id].box2translate;\n\n        if (Tibox >= gs.size() or alma::almost_equal(T.norm(), 0.)) {\n            std::cout << this->id << '\\t' << Tibox << '\\t' << T << std::endl;\n            throw alma::geometry_error(\"Error: Bad id for mapping of\"\n                                       \"periodic cells\");\n        }\n\n        point p0(r0(0), r0(1));\n        point p1(r0(0) + T(0), r0(1) + T(1));\n        // Segment:\n        segment s(p0, p1);\n\n\n        geom2d_border sborder;\n        for (auto& b : gs[Tibox].get_borders()) {\n            if (boost::geometry::intersects(s, b.sbl)) {\n                sborder = b;\n                break;\n            }\n        }\n\n\n        std::vector<point> rinter;\n        boost::geometry::intersection(s, sborder.sbl, rinter);\n\n        if (rinter.empty()) {\n            std::cout << \"r0:\\n\" << r0 << std::endl;\n            std::cout << \"v:\\n\" << v << std::endl;\n            std::cout << \"T:\\n\" << T << std::endl;\n            std::cout << \"rn:\\n\" << (r0 + T).eval() << std::endl;\n            std::cout << \"center of newbox:\";\n            std::cout << gs[Tibox].get_center() << std::endl;\n            throw alma::geometry_error(\"Error in translation, \"\n                                       \"no box found\");\n        }\n        \n        Eigen::Vector2d transpoint;\n        Eigen::Vector2d transpoint_T;\n        Eigen::Vector2d transpoint_v;\n        transpoint(0) = rinter[0].get<0>();\n        transpoint(1) = rinter[0].get<1>();\n        transpoint_T = transpoint -\n\t\t 1.0e-6 * gs[this->id].translation /\n\t\t (gs[this->id].translation).norm();\n        transpoint_v = transpoint + 1.0e-6 * v/v.norm();\n        /// Getting point\n        std::vector<Eigen::Vector2d> rf;\n        rinter.clear();\n\n        std::vector<std::size_t> pboxes;\n        for (auto& [ibc, border] : gs[Tibox].get_contacts()) {\n\t    bool here_i = boost::geometry::intersects(s,\n                                 border[0].sbl);\n\t    bool here_T = gs[ibc].inside(transpoint);\n            bool here_Tv = gs[ibc].inside(transpoint_v);\n            bool here_TT = gs[ibc].inside(transpoint_T);\n\n\t    bool here = here_i or here_T or here_Tv or here_TT;\n \n            if (ibc == Tibox or !here or\n               gs[ibc].periodic or gs[ibc].reservoir)\n                continue;\n            \n\n\t    if (here_i) {\n                boost::geometry::intersection(s,\n                            border[0].sbl,rinter);\n                Eigen::Vector2d rf_;\n                rf_(0) = rinter[0].get<0>();\n                rf_(1) = rinter[0].get<1>();\n                rf.push_back(rf_);\n                pboxes.push_back(ibc);\n            }\n            else if (here_T){\n\t\trf.push_back(transpoint);\n                pboxes.push_back(ibc);\n\t    }\n\t    else if (here_Tv) {\n\t\trf.push_back(transpoint_v);\n                pboxes.push_back(ibc);\n\t    }\n            else {\n\t\trf.push_back(transpoint_T);\n                pboxes.push_back(ibc);\n            }\n        }\n        /// Choose randomly if we are in corner\n        Eigen::Vector2d RF;\n\n        std::size_t newibox;\n        if (pboxes.size() > 1) {\n            std::vector<std::size_t> pboxes2;\n\n            for (std::size_t ib = 0; ib < pboxes.size(); ib++) {\n                Eigen::Vector2d rcheck = rf[ib] + 1.0e-6 * v;\n                if (gs[pboxes[ib]].inside(rcheck))\n                    pboxes2.push_back(pboxes[ib]);\n            }\n\n            auto pos = alma::choose(pboxes2.begin(), pboxes2.end(), rng) -\n                       pboxes2.begin();\n\n            RF = rf[pos];\n            newibox = pboxes2[pos];\n        }\n        else if (pboxes.size() == 1) {\n            newibox = pboxes[0];\n            RF = rf[0];\n        }\n        else {\n            throw alma::geometry_error(\"Error in Translation\");\n        }\n        return std::make_pair(newibox,RF);\n    }\n};\n\n\n/// Helper function to add id to geometries contained in vector\n///@param[in] gs vector containing the geometries\ninline void assign_geom_ids(std::vector<geometry_2d>& gs) {\n    for (std::size_t i = 0; i < gs.size(); i++) {\n        gs[i].set_id(i);\n    }\n}\n\n/// Check if point is in corner shared by 3 polygons or more\n/// it also gives the id of those figures\nstd::pair<bool, std::vector<std::size_t>> in_corner3(\n    Eigen::Vector2d& r,\n    std::vector<geometry_2d>& gs);\n\n/// Solving intersection in three shared corner\n/// We are not making contact with\n/// void through single points\ntemplate <class Random>\n/// It returns intersection with polygon sides:\n///@param[in] rf  - position to correct\n///@param[in] v   - velocity vector\n///@param[in] sys - system geometry\n///@param[in] candidates - candidates to where particle can be put\n///@param[in] r   - random generator\n///@return    [box id,\n///            border ids]\nstd::pair<std::size_t, std::size_t> correct_corner_problem(\n    Eigen::Vector2d& rf,\n    Eigen::Vector2d& v,\n    std::vector<geometry_2d>& sys,\n    std::vector<std::size_t>& candidates,\n    Random& r) {\n    std::map<std::size_t, std::vector<std::size_t>> bids;\n\n    std::vector<std::size_t> finalist;\n\n    boost::tuple<double, double> rc(rf(0), rf(1));\n\n    for (auto candidate : candidates) {\n        bids[candidate] = std::vector<std::size_t>(0);\n        std::size_t border_id = 0;\n        for (auto& b : sys[candidate].get_borders()) {\n            /// To rule out already there stuff\n            if (boost::geometry::intersects(rc, b.sbl)) {\n                if (b.np.dot(v) > 0.)\n                    bids[candidate].push_back(border_id);\n            }\n            border_id++;\n        }\n\n        /// In triangles facing exterior it can only\n        /// exist single solution\n        if (bids[candidate].size() > 1) {\n            bids.erase(candidate);\n        }\n        else {\n            finalist.push_back(candidate);\n        }\n    }\n\n    std::size_t winner = *(alma::choose(finalist.begin(), finalist.end(), r));\n\n    return std::make_pair(winner, bids[winner][0]);\n}\n\n/// Returns geometry_2d vector containing all vectors\n///@param[in] xmlfname - xml filename\n///@return vector containing all geometric data for each box\nstd::vector<alma::geometry_2d> read_geometry_XML(std::string xmlfname);\n\n/// Calculates the gradient for the box using the contact boxes\n///@param[in] sys - system\n///@return thermal gradient\nEigen::MatrixXd calculate_gradientT(std::vector<alma::geometry_2d>& sys);\n\n\n}; // namespace alma\n", "meta": {"hexsha": "d904499d7ee689068a920a9651b2c506a10d0aba", "size": 18091, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/geometry_2d.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/geometry_2d.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/geometry_2d.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": 31.4626086957, "max_line_length": 80, "alphanum_fraction": 0.5903487922, "num_tokens": 4758, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4706757407911951}}
{"text": "#include <vector>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\nclass PoseInterpolator {\n  public:\n    PoseInterpolator(const int& num_steps){SetStepNum(num_steps);};\n    void SetStepNum(const int& num_steps){m_num_steps = num_steps;};\n\n    virtual std::vector<Eigen::Matrix4d> Interpolate(const Eigen::Matrix4d& pose_src, const Eigen::Matrix4d& pose_dst) = 0;\n    virtual std::vector<Eigen::Matrix4f> Interpolate(const Eigen::Matrix4f& pose_src, const Eigen::Matrix4f& pose_dst) = 0;\n\n  protected:\n    int m_num_steps;\n    Eigen::Matrix4d m_pose_src;\n    Eigen::Matrix4d m_pose_dst;\n};\n\n\nclass SE3Interpolator : public PoseInterpolator {\n  public:\n    SE3Interpolator(const int& num_steps = 3) : PoseInterpolator(num_steps) {};\n\n    std::vector<Eigen::Matrix4d> Interpolate(const Eigen::Matrix4d& pose_src, const Eigen::Matrix4d& pose_dst);\n\n    std::vector<Eigen::Matrix4f> Interpolate(const Eigen::Matrix4f& pose_src, const Eigen::Matrix4f& pose_dst) {\n      std::vector<Eigen::Matrix4f> result; result.reserve(m_num_steps-1);\n\n      Eigen::Matrix4d _pose_src = pose_src.cast<double>();\n      Eigen::Matrix4d _pose_dst = pose_dst.cast<double>();\n      std::vector<Eigen::Matrix4d> \n        v_poses = Interpolate(_pose_src, _pose_dst);\n\n      for(Eigen::Matrix4d pose : v_poses) {\n        result.push_back(pose.cast<float>());\n      }\n    \n      return result;\n    }\n\n};\n\nclass QuatAndTInterpolator : public PoseInterpolator {\n  public:\n    QuatAndTInterpolator(const int& num_steps = 3) : PoseInterpolator(num_steps) {};\n\n    std::vector<Eigen::Matrix4d> Interpolate(const Eigen::Matrix4d& pose_src, const Eigen::Matrix4d& pose_dst);\n\n    std::vector<Eigen::Matrix4f> Interpolate(const Eigen::Matrix4f& pose_src, const Eigen::Matrix4f& pose_dst) {\n      std::vector<Eigen::Matrix4f> result; result.reserve(m_num_steps-1);\n\n      Eigen::Matrix4d _pose_src = pose_src.cast<double>();\n      Eigen::Matrix4d _pose_dst = pose_dst.cast<double>();\n      std::vector<Eigen::Matrix4d> \n        v_poses = Interpolate(_pose_src, _pose_dst);\n\n      for(Eigen::Matrix4d pose : v_poses) {\n        result.push_back(pose.cast<float>());\n      }\n    \n      return result;\n    }\n\n};\n", "meta": {"hexsha": "e674d961aabdfdcc8eb98fe315d358dedcb57def", "size": 2172, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/InterPose.hpp", "max_stars_repo_name": "cashiwamochi/InterPoseLib", "max_stars_repo_head_hexsha": "020f1067d459a1428c29000904e13ae1185290bf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-12-22T00:02:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-17T14:08:56.000Z", "max_issues_repo_path": "src/InterPose.hpp", "max_issues_repo_name": "cashiwamochi/InterPoseLib", "max_issues_repo_head_hexsha": "020f1067d459a1428c29000904e13ae1185290bf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2019-12-21T11:13:30.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T05:23:27.000Z", "max_forks_repo_path": "src/InterPose.hpp", "max_forks_repo_name": "cashiwamochi/InterPose", "max_forks_repo_head_hexsha": "020f1067d459a1428c29000904e13ae1185290bf", "max_forks_repo_licenses": ["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.9090909091, "max_line_length": 123, "alphanum_fraction": 0.6961325967, "num_tokens": 589, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.47067574079119506}}
{"text": "#include <iostream>\n#include <vector>\n#include \"sfmMyFunctions.h\"\n#include \"sfmExceptionMacro.h\"\n#include \"sfmBasicTypes.h\"\n#include <Eigen/Dense>\n#include <unsupported/Eigen/NonLinearOptimization>\n#include <random>\n#include \"sfmPedestrianSpawner.h\"\n#include <iomanip>\n#include <chrono>\n#include <ctime>\n#include <fstream>\n#include <string>\n\n//open mp initialisation\n#ifdef _OPENMP\n#include <omp.h>\n#endif\n\n//dummy function to allow us to set up open mp easier\nstd::vector<std::shared_ptr<sfm::Forces> > &Update_Pedestrian(std::vector<std::shared_ptr<sfm::Forces> > &pedestrians, double dt, double finish_time_s)\n{\n    // decided to leave v_max as default, but can change dt and finish time, also set up variables for open mp\n    double v_max = 1.3;\n    sfm::dir2d temp_force;\n    sfm::dir2d new_velocity;\n    sfm::dir2d position;\n    sfm::pos2d new_position;\n\n    //for loop over time\n    for(int t=0; t<(finish_time_s/dt);++t){\n\n        //set up open mp tasks with each private and shared components\n        #pragma omp tasks private(new_velocity),private(position),private(new_position), firstprivate(temp_force), shared(pedestrians)\n        {\n            //set up parellel for loop\n            #pragma omp for\n            for(int j=0; j<pedestrians.size();++j){    \n\n                //set up temp force as the resultant force of each pedestrian, and a new velocity calculated from it           \n                temp_force = pedestrians[j]->Resultant_force(pedestrians,temp_force, dt);\n                new_velocity = (temp_force*dt) + pedestrians[j]->Return_Velocity();\n\n                //normalising new velocity speed\n                if(new_velocity.length() > v_max*pedestrians[j]->Return_Speed()){\n                    new_velocity = new_velocity*(v_max*pedestrians[j]->Return_Speed()/new_velocity.length());\n                }\n\n                //setting up position from each pedestrian to make the code less dense                \n                position = {pedestrians[j]->Return_Current_Position()[1],pedestrians[j]->Return_Current_Position()[0]};\n                new_position = {position[1]+(new_velocity[1]*dt),(position[0]+new_velocity[0]*dt)};\n\n                //updating new positions at the end of loop\n                pedestrians[j]->Update_Velocity(new_velocity);\n                pedestrians[j]->Update_Current_Position(new_position);\n            }\n        }\n    }\n    return pedestrians;\n}\n\n\n//another dummy function that creates the pedestrian for easier implementation of open mp\nstd::vector<std::shared_ptr<sfm::Forces> > &Create_Pedestrian(std::vector<std::shared_ptr<sfm::Forces> > &pedestrians, int no_pedestrians)\n{\n    //variable initialisations for easier alteration, started in 2 boxes at left and right side of corridor\n    sfm::dir2d left_side_x(1,1);\n    sfm::dir2d left_side_y(0.1,9.9);\n    sfm::dir2d right_side_x(48,49);\n    sfm::dir2d right_side_y(0.1,9.9);\n    sfm::dir2d direc1(1,0);\n    sfm::dir2d direc2(-1,0);\n\n    //this sets up the left pedestrians by appending each pedestrian created to the inputted vector\n    std::vector<std::shared_ptr<sfm::Forces> >pedestrians1;\n    pedestrians1 = sfm::Factory::Directional(pedestrians1,no_pedestrians/2,direc1,left_side_x,left_side_y);\n    for(int point = 0; point < pedestrians1.size();++point){\n        pedestrians.emplace_back(pedestrians1[point]);\n    } \n\n    //and this the right\n    std::vector<std::shared_ptr<sfm::Forces> >pedestrians2;\n    pedestrians2 = sfm::Factory::Directional(pedestrians2,no_pedestrians/2,direc2,right_side_x,right_side_y);\n    for(int point = 0; point < pedestrians2.size();++point){\n        pedestrians.emplace_back(pedestrians2[point]);\n    }\n\n    //directional pedestrians were chosen as they keep moving for the whole time, makes the calculations consistent\n    return pedestrians;   \n}\n\n//the main function\nint main()\n{\n    //small input/output question to make doing multiple benchmarks easier\n    std::string choice;\n    std::cout << \"Default?(Yes/No)\" << std::endl;\n    std::cin >> choice;\n\n    //decided to keep dt constant as it keeps the calculations a little neater\n    //otherwise this section is just initialising variables for later\n    double dt = 0.1; \n    double finish_time_s;\n    int no_pedestrians;\n    if(choice ==  \"Yes\"){\n        finish_time_s = 100;\n        no_pedestrians = 1000;\n    }\n    else{\n        std::cout << \"Finish Time/0.1?\" << std::endl;\n        std::cin >> finish_time_s;\n        std::cout << \"No Pedestrians?\" << std::endl;\n        std::cin >> no_pedestrians;\n    }\n    \n    //naming of file is automatic if you wanted to do multiple benchmarks\n    std::ofstream Results;\n    std::stringstream FileName;\n    FileName << \"Benchmarking_\" << no_pedestrians << \"_\" << finish_time_s << \".txt\";\n    Results.open(FileName.str());\n\n    //this gives a little preamble at the top of each file, and outputs it to the terminal\n    Results << \"Testing done with \" << no_pedestrians << \" pedestrians  \\n\"\n            << \"For time \" << finish_time_s << \" seconds at intervals of 0.1s\\n\";\n    std::cout   << \"Testing done with \" << no_pedestrians << \" pedestrians \\n\"\n                << \"For time \" << finish_time_s << \" seconds at intervals of 0.1s\\n\" << std::endl;\n\n    //initialise a ptr vector for the non mp test\n    std::vector<std::shared_ptr<sfm::Forces> >pedestrians1;\n\n    //start timing \n    std::cout << \"start no mp\" << std::endl;\n    std::clock_t c_start1 = std::clock();\n    auto t_start1 = std::chrono::high_resolution_clock::now();\n\n    //create the pedestrians for the test\n    pedestrians1 = Create_Pedestrian(pedestrians1,no_pedestrians);\n\n    //update their position\n    pedestrians1 = Update_Pedestrian(pedestrians1,dt,finish_time_s);\n\n    //stop the timers\n    std::clock_t c_end1 = std::clock();\n    auto t_end1 = std::chrono::high_resolution_clock::now();\n    std::cout << \"stop no mp\" << std::endl;\n\n    // this outputs to the terminal the time elapsed\n    std::cout << std::fixed << std::setprecision(2) << \"CPU time used no mp: \"\n            << 1000.0 * (c_end1-c_start1) / CLOCKS_PER_SEC << \" ms\\n\"\n            << \"Wall clock time passed no mp: \"\n            << std::chrono::duration<double, std::milli>(t_end1-t_start1).count()\n            << \" ms\\n\";\n\n    //this inputs the same data as above into a csv format of the file\n    Results << \"Thread Count;   CPU time(ms):      Wall clock time(ms): \\n\"\n            << std::fixed << std::setprecision(2)\n            << \"1, \"\n            << 1000.0 * (c_end1-c_start1) / CLOCKS_PER_SEC << \" ,\" \n            << std::chrono::duration<double, std::milli>(t_end1-t_start1).count() <<\"\\n\";\n\n    // throws an error on vscode but works\n    int max_threads = omp_get_max_threads(); \n\n    //now iterate with incresing number of thread with max number for each pc\n    for(int num_threads = 1;num_threads<(max_threads+1);++num_threads)\n    {\n        //outputting how far along on loop we are\n        std::cout << \"Threadcount: \" << num_threads << std::endl;\n\n        //open mp initialisations\n        #ifdef _OPENMP\n        omp_set_num_threads(num_threads);\n        #endif\n\n        //initialising empty vector for pointer storage\n        std::vector<std::shared_ptr<sfm::Forces> >pedestrians;\n\n        // starting timer here\n        std::cout << \"start with mp\" << std::endl;\n        std::clock_t c_start = std::clock();\n        auto t_start = std::chrono::high_resolution_clock::now();\n\n        //creating pedestrians here\n        pedestrians = Create_Pedestrian(pedestrians,no_pedestrians);\n\n        //check for correct data output after parrellelisation\n        // sfm::pos2d origin_before = pedestrians[0]->Return_Origin();\n\n        //implementing open mp\n        #pragma omp parallel shared(pedestrians)\n        {\n            #pragma single nowait\n            {\n                pedestrians = Update_Pedestrian(pedestrians,dt,finish_time_s);\n            }\n        }\n\n        //stoping timers here\n        std::clock_t c_end = std::clock();\n        auto t_end = std::chrono::high_resolution_clock::now();\n\n        //output to terminal to update on progress\n        std::cout << \"stop with mp\" << std::endl;\n        std::cout << std::fixed << std::setprecision(2) << \"CPU time used: \"\n                << 1000.0 * (c_end-c_start) / CLOCKS_PER_SEC << \" ms\\n\"\n                << \"Wall clock time passed: \"\n                << std::chrono::duration<double, std::milli>(t_end-t_start).count()\n                << \" ms\\n\";\n\n        //exporting to text file for easy usage later\n        Results << std::fixed << std::setprecision(2)\n                << num_threads << \", \"\n                << 1000.0 * (c_end-c_start) / CLOCKS_PER_SEC << \" ,\" \n                << std::chrono::duration<double, std::milli>(t_end-t_start).count() <<\"\\n\";\n\n        //section to see if variables are the same before as after, when done on my pc tests came out as 0 difference\n        // sfm::pos2d origin_after = pedestrians[0]->Return_Origin();\n        // std::cout << origin_before[0] - origin_after[0] << \" ,\" << origin_before[1] - origin_after[1] << std::endl;\n        //presumably if the data hasnt been garbled it should all be correct without needing to check each entry\n    }\n\n    //closes the txt file\n    Results.close();\n    return 0;\n}", "meta": {"hexsha": "f65aa27249bb2f01ccb3f0c1d6367082246724ad", "size": 9219, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Code/CommandLineApps/sfmOpen_MP.cpp", "max_stars_repo_name": "sukrire/PHAS0100Assignment2", "max_stars_repo_head_hexsha": "9838e21ac663f557b7969161dee061086effdabd", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/CommandLineApps/sfmOpen_MP.cpp", "max_issues_repo_name": "sukrire/PHAS0100Assignment2", "max_issues_repo_head_hexsha": "9838e21ac663f557b7969161dee061086effdabd", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/CommandLineApps/sfmOpen_MP.cpp", "max_forks_repo_name": "sukrire/PHAS0100Assignment2", "max_forks_repo_head_hexsha": "9838e21ac663f557b7969161dee061086effdabd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-02-16T16:42:58.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-24T12:50:33.000Z", "avg_line_length": 40.7920353982, "max_line_length": 151, "alphanum_fraction": 0.633908233, "num_tokens": 2383, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.47067574079119506}}
{"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 scalar_matrix.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#include <fl/util/types.hpp>\n\nnamespace fl\n{\n\n/**\n * \\ingroup types\n *\n * Represents a matrix of the size 1x1. This Matrix can be used in the same way\n * as a scalar.\n */\nclass ScalarMatrix\n    : public Eigen::Matrix<Real, 1, 1>\n{\npublic:\n    /**\n     * \\brief Default constructor.\n     * Creates ScalarMatrix with no arguments. The initial value is zero by\n     * default.\n     */\n    ScalarMatrix()\n    {\n        this->data()[0] = Real(0);\n    }\n\n    /**\n     * \\brief Creates a ScalarMatrix with an initial value or converts a scalar\n     * into a ScalarMatrix.\n     * \\param value initial value\n     */\n    ScalarMatrix(Real value)\n    {\n        this->data()[0] = value;\n    }\n\n    /**\n     * \\brief Constructor copying the value of the ScalarMatrix \\a other\n     */\n    ScalarMatrix(const ScalarMatrix& other)\n    {\n        this->data()[0] = other.data()[0];\n    }\n\n    /**\n     * \\brief Constructor copying the value of the expression \\a other\n     */\n    template <typename OtherDerived>\n    ScalarMatrix(const Eigen::MatrixBase<OtherDerived> &other)\n    {\n        this->data()[0] = other(0);\n    }\n\n    /**\n     * \\brief operator Real() implicit typecast conversion of a ScalarMatrix\n     * into a scalar\n     */\n    operator Real() const\n    {\n        return Real(this->data()[0]);\n    }\n\n    /**\n     * \\brief operator+= adds a scalar value to this matrix and assigns\n     */\n    void operator+=(Real value)\n    {\n        this->data()[0] += value;\n    }\n\n    /**\n     * \\brief operator-= subtracts a scalar value to this matrix and assigns\n     */\n    void operator-=(Real value)\n    {\n        this->data()[0] -= value;\n    }\n\n    /**\n     * \\brief operator*= multiplies a scalar value with this this matrix and\n     * assigns\n     */\n    void operator*=(Real value)\n    {\n        this->data()[0] *= value;\n    }\n\n    /**\n     * \\brief operator/= divide a scalar value with this this matrix and\n     * assigns\n     */\n    void operator/=(Real value)\n    {\n        this->data()[0] /= value;\n    }\n\n    /**\n     * \\brief prefix operator ++ which increments the matrix value by 1.\n     */\n    ScalarMatrix& operator++()\n    {\n        return (++this->data()[0], *this);\n    }\n\n    /**\n     * \\brief postfix operator ++ which increments the matrix value by 1.\n     */\n    ScalarMatrix operator++(int)\n    {\n        auto r = ScalarMatrix(this->data()[0]++); // RVO\n        return r;\n    }\n\n    /**\n     * \\brief prefix operator -- which decrements the matrix value by 1.\n     */\n    ScalarMatrix& operator--()\n    {\n        return (--this->data()[0], *this);\n    }\n\n    /**\n     * \\brief postfix operator -- which decrements the matrix value by 1.\n     */\n    ScalarMatrix operator--(int)\n    {\n        auto r = ScalarMatrix(this->data()[0]--); // RVO\n        return r;\n    }\n};\n\n}\n\n\n", "meta": {"hexsha": "fe4dd8b6caef918c4891ffa52317825b9452000b", "size": 3346, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/fl/util/scalar_matrix.hpp", "max_stars_repo_name": "aeolusbot-tommyliu/fl", "max_stars_repo_head_hexsha": "a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2015-07-03T06:53:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-15T20:55:12.000Z", "max_issues_repo_path": "include/fl/util/scalar_matrix.hpp", "max_issues_repo_name": "aeolusbot-tommyliu/fl", "max_issues_repo_head_hexsha": "a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2015-02-20T12:48:17.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-18T08:45:13.000Z", "max_forks_repo_path": "include/fl/util/scalar_matrix.hpp", "max_forks_repo_name": "aeolusbot-tommyliu/fl", "max_forks_repo_head_hexsha": "a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2015-02-20T11:34:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-15T20:55:13.000Z", "avg_line_length": 21.3121019108, "max_line_length": 79, "alphanum_fraction": 0.572922893, "num_tokens": 833, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708562, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.4706036896941429}}
{"text": "// read txt files into ArrayXXd\r\n#include <Eigen/Dense>\r\n#include <iostream>\r\n#include <fstream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\nusing namespace Eigen;\r\n\r\nvoid read_array(const char* filename, ArrayXXd& array)\r\n{\r\n\tif (array.cols() != 500 || array.rows() != 500)\r\n\t\tarray.resize(500, 500);\r\n\t//double data[500 * 500];\r\n\tifstream input(filename);\r\n\tfor (int i; i < 500 * 500; i++)\r\n\t{\r\n\t\t//input >> data[i];\r\n\t\t// if input number is biger than 1, it should be modified to inf\r\n\t\tinput >> array(i/500, i%500);\r\n\t}\r\n\t//cout << array << endl;\r\n}\r\n\r\nvoid read_array(const char* filename, vector<vector<double>>& array)\r\n{\r\n\tifstream input(filename);\r\n\tint i = 0;\r\n\tdouble tmp;\r\n\tvector<double> line(5,0.);\r\n\twhile (!(input >> tmp).fail()) {\r\n\t\ti++;\r\n\t\tline[i - 1] = tmp;\r\n\t\tif (i % 5 == 0)\r\n\t\t{\r\n\t\t\tarray.push_back(line);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid read_array(const char* filename, vector<double>& array)\r\n{\r\n\tifstream input(filename);\r\n\tdouble tmp;\r\n\twhile (!(input >> tmp).fail()) {\r\n\t\t\r\n\t\t\tarray.push_back(tmp);\r\n\t}\r\n\tArrayXXd road_center_line(array.data());\r\n}\r\n\r\n\r\nint main()\r\n{\r\n\tchar* file = \"cost_grayscale_map.txt\";\r\n\tArrayXXd arr(500, 500);\r\n\tread_array(file, arr);\r\n\tcout << arr << endl;\r\n\treturn 0;\r\n}\r\n\r\n/*\r\n#include <iostream>\r\n#include <fstream>\r\n\r\nusing namespace std;\r\n\r\nint main() {\r\n\r\ndouble data[size of your data];\r\n\r\nstd::ifstream input(\"file.txt\");\r\n\r\nfor (int i = 0; i < size of your data; i++) {\r\ninput >> data[i];\r\nstd::cout<< data[i]<<std::endl;\r\n}\r\n\r\n}\r\n*/", "meta": {"hexsha": "e01646265fa9ed6b83108a84f17f99b37ca9381b", "size": 1484, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ScenarioGeneration/ScenarioGeneration.cpp", "max_stars_repo_name": "bourbakilee/CppMPL", "max_stars_repo_head_hexsha": "67f6355bcd2db5016841484d16bf9299e3293457", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-12-19T14:13:26.000Z", "max_stars_repo_stars_event_max_datetime": "2016-01-14T01:52:20.000Z", "max_issues_repo_path": "ScenarioGeneration/ScenarioGeneration.cpp", "max_issues_repo_name": "bourbakilee/CppMPL", "max_issues_repo_head_hexsha": "67f6355bcd2db5016841484d16bf9299e3293457", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ScenarioGeneration/ScenarioGeneration.cpp", "max_forks_repo_name": "bourbakilee/CppMPL", "max_forks_repo_head_hexsha": "67f6355bcd2db5016841484d16bf9299e3293457", "max_forks_repo_licenses": ["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.55, "max_line_length": 69, "alphanum_fraction": 0.5997304582, "num_tokens": 406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.4706036839606199}}
{"text": "//==================================================================================================\n/**\n  EVE - Expressive Vector Engine\n  Copyright : EVE Contributors & Maintainers\n  SPDX-License-Identifier: MIT\n**/\n//==================================================================================================\n#include \"test.hpp\"\n#include <eve/concept/value.hpp>\n#include <eve/constant/valmin.hpp>\n#include <eve/constant/valmax.hpp>\n#include <eve/function/all.hpp>\n#include <eve/function/exp_int.hpp>\n#include <eve/function/diff/exp_int.hpp>\n#include <eve/function/is_negative.hpp>\n#include <eve/function/is_positive.hpp>\n#include <type_traits>\n#include <cmath>\n#include <eve/constant/inf.hpp>\n#include <eve/constant/minf.hpp>\n#include <eve/constant/nan.hpp>\n#include <eve/constant/smallestposval.hpp>\n#include <eve/platform.hpp>\n#include <boost/math/special_functions/expint.hpp>\n\n//==================================================================================================\n// Types tests\n//==================================================================================================\nEVE_TEST_TYPES( \"Check return types of exp_int\"\n            , eve::test::simd::ieee_reals\n            )\n<typename T>(eve::as<T>)\n{\n  using v_t = eve::element_type_t<T>;\n  using i_t = eve::as_integer_t<v_t>;\n  using I_t = eve::as_integer_t<T>;\n\n  TTS_EXPR_IS( eve::exp_int(T(), T())  ,   T);\n  TTS_EXPR_IS( eve::exp_int(v_t(),v_t()), v_t);\n  TTS_EXPR_IS( eve::exp_int(i_t(),T()),   T);\n  TTS_EXPR_IS( eve::exp_int(I_t(),T()),   T);\n  TTS_EXPR_IS( eve::exp_int(I_t(),v_t()), T);\n  TTS_EXPR_IS( eve::exp_int(i_t(),v_t()), v_t);\n};\n\n//==================================================================================================\n// exp_int  tests\n//==================================================================================================\nEVE_TEST( \"Check behavior of exp_int on wide\"\n        , eve::test::simd::ieee_reals\n        , eve::test::generate(eve::test::randoms(0.0, 10.0))\n        )\n<typename T>(T const& a0 )\n{\n  using v_t = eve::element_type_t<T>;\n  using eve::exp_int;\n  using eve::as;\n  for(int i=1; i < 4 ; ++i)\n  {\n    TTS_ULP_EQUAL( exp_int(i, a0),  map([i](auto e){return boost::math::expint(i, e);}, a0), 5);\n    auto dexp_int = [i](auto e){return v_t( -boost::math::expint(i-1, e));};\n    TTS_ULP_EQUAL( eve::diff(exp_int)(i, a0),  map(dexp_int, a0), 5);\n  }\n\n  if constexpr( eve::platform::supports_invalids )\n  {\n    TTS_IEEE_EQUAL(exp_int(T(1), eve::nan(eve::as<T>()))  , eve::nan(eve::as<T>()) );\n    TTS_IEEE_EQUAL(exp_int(T(1), eve::inf(eve::as<T>()))   , T(0) );\n  }\n\n\n  for(int i=1; i < 4 ; ++i)\n  {\n    TTS_ULP_EQUAL(exp_int(T(i), T(0))  , eve::rec(T(i-1)), 0.5);\n    TTS_ULP_EQUAL(exp_int(T(i), T(0.5)), T(boost::math::expint(i, 0.5)), 32.0);\n    TTS_ULP_EQUAL(exp_int(T(i), T(1))  , T(boost::math::expint(i, 1.0)), 32.0);\n    TTS_ULP_EQUAL(exp_int(T(i), T(10)) , T(boost::math::expint(i, 10.0)), 32.0);\n  }\n  for(int i=1; i < 4 ; ++i)\n  {\n    TTS_ULP_EQUAL(exp_int(i, T(0))  , eve::rec(T(i-1)), 0.5);\n    TTS_ULP_EQUAL(exp_int(i, T(0.5)), T(boost::math::expint(i, 0.5)), 32.0);\n    TTS_ULP_EQUAL(exp_int(i, T(1))  , T(boost::math::expint(i, 1.0)), 32.0);\n    TTS_ULP_EQUAL(exp_int(i, T(10)) , T(boost::math::expint(i, 10.0)), 32.0);\n  }\n  using elt_t =  eve::element_type_t<T>;\n\n  TTS_ULP_EQUAL(exp_int(elt_t(2.0), elt_t(0.5)), (boost::math::expint(elt_t(2), elt_t(0.5))), 16.0);\n  TTS_ULP_EQUAL(exp_int(elt_t(6000), elt_t(0.5)), (boost::math::expint(elt_t(6000), elt_t(0.5))), 4.0);\n};\n", "meta": {"hexsha": "b4fb5dd5fe88143670bcacd29603d8aed63c1822", "size": 3537, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/module/special/exp_int.cpp", "max_stars_repo_name": "the-moisrex/eve", "max_stars_repo_head_hexsha": "80b52663eefee11460abb0aedf4158a5067cf7dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 340.0, "max_stars_repo_stars_event_min_datetime": "2020-09-16T21:12:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T15:40:33.000Z", "max_issues_repo_path": "test/unit/module/special/exp_int.cpp", "max_issues_repo_name": "the-moisrex/eve", "max_issues_repo_head_hexsha": "80b52663eefee11460abb0aedf4158a5067cf7dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 383.0, "max_issues_repo_issues_event_min_datetime": "2020-09-17T06:56:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T15:58:53.000Z", "max_forks_repo_path": "test/unit/module/special/exp_int.cpp", "max_forks_repo_name": "the-moisrex/eve", "max_forks_repo_head_hexsha": "80b52663eefee11460abb0aedf4158a5067cf7dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 28.0, "max_forks_repo_forks_event_min_datetime": "2021-02-27T23:11:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T12:31:29.000Z", "avg_line_length": 38.8681318681, "max_line_length": 103, "alphanum_fraction": 0.518801244, "num_tokens": 1079, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.47060368001388303}}
{"text": "// Copyright (C) 2002 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#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/dag_shortest_paths.hpp>\n#include <boost/property_map/vector_property_map.hpp>\n#include <boost/test/minimal.hpp>\n\nusing namespace boost;\n\n#include <iostream>\nusing namespace std;\n\nint test_main(int, char*[])\n{\n    typedef adjacency_list<vecS, vecS, directedS, no_property,\n        property<edge_weight_t, int> > Graph;\n\n    Graph graph;\n\n    (void)add_vertex(graph);\n    (void)add_vertex(graph);\n    (void)add_vertex(graph);\n    (void)add_vertex(graph);\n\n    Graph::edge_descriptor e;\n    \n    e = add_edge(0, 1, graph).first;\n    put(edge_weight, graph, e, 1);\n\n    e = add_edge(1, 2, graph).first;\n    put(edge_weight, graph, e, 1);\n\n    e = add_edge(3, 1, graph).first;\n    put(edge_weight, graph, e, 5);\n\n    vector_property_map<int> distance;\n\n    dag_shortest_paths(graph, 0,\n                       distance_map(distance)\n                       .distance_compare(std::greater<int>())\n                       .distance_inf((std::numeric_limits<int>::min)())\n                       .distance_zero(0));\n\n    cout << distance[2] << \"\\n\";\n\n    BOOST_CHECK(distance[2] == 2);\n\n    return 0;\n}\n\n\n\n", "meta": {"hexsha": "4b5151b326e4ee303d6d47d93f942fce5810aaf7", "size": 1369, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/graph/test/dag_longest_paths.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "boost/libs/graph/test/dag_longest_paths.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "boost/libs/graph/test/dag_longest_paths.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 24.0175438596, "max_line_length": 71, "alphanum_fraction": 0.6413440467, "num_tokens": 351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708562, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.47060367517375323}}
{"text": "#include <stan/math/prim/scal.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <gtest/gtest.h>\n\nTEST(MathFunctions,logical_lt) {\n  using stan::math::logical_lt;\n  EXPECT_TRUE(logical_lt(0,1));\n  EXPECT_TRUE(logical_lt(1.0,2.0));\n  EXPECT_TRUE(logical_lt(1, 2.0));\n  EXPECT_TRUE(logical_lt(-1, 0));\n\n  EXPECT_FALSE(logical_lt(1,1));\n  EXPECT_FALSE(logical_lt(5.7,5.7));\n  EXPECT_FALSE(logical_lt(5.7,-9.0));\n  EXPECT_FALSE(logical_lt(0,0.0));\n}\n\nTEST(MathFunctions, logical_lt_nan) {\n  double nan = std::numeric_limits<double>::quiet_NaN();\n  \n  EXPECT_FALSE(stan::math::logical_lt(1.0, nan));\n  EXPECT_FALSE(stan::math::logical_lt(nan, 2.0));\n  EXPECT_FALSE(stan::math::logical_lt(nan, nan));\n}\n", "meta": {"hexsha": "2d3b4ae9df1d3239615c49b75b32a7425acc3bf0", "size": 715, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/scal/fun/logical_lt_test.cpp", "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/test/unit/math/prim/scal/fun/logical_lt_test.cpp", "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/test/unit/math/prim/scal/fun/logical_lt_test.cpp", "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": 28.6, "max_line_length": 56, "alphanum_fraction": 0.7188811189, "num_tokens": 227, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943805178139, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.4706036672802794}}
{"text": "/********************************************************************************\n * Copyright 2009 The Robotics Group, The Maersk Mc-Kinney Moller Institute,\n * Faculty of Engineering, University of Southern Denmark\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n ********************************************************************************/\n\n#ifndef RW_MATH_ROTATION3D_HPP\n#define RW_MATH_ROTATION3D_HPP\n\n/**\n * @file Rotation3D.hpp\n */\n#if !defined(SWIG)\n#include <rw/common/Serializable.hpp>\n#include <rw/core/macros.hpp>\n#include <rw/math/Vector3D.hpp>\n\n#include <Eigen/Core>\n#include <limits>\n#endif\n\nnamespace rw { namespace math {\n\n    template< class T > class Rotation3DVector;\n    /** @addtogroup math */\n    /* @{*/\n\n#if !defined(SWIGJAVA)\n    /**\n     * @brief A 3x3 rotation matrix \\f$ \\mathbf{R}\\in SO(3) \\f$\n     *\n     * @f$\n     *  \\mathbf{R}=\n     *  \\left[\n     *  \\begin{array}{ccc}\n     *  {}^A\\hat{X}_B & {}^A\\hat{Y}_B & {}^A\\hat{Z}_B\n     *  \\end{array}\n     *  \\right]\n     *  =\n     *  \\left[\n     *  \\begin{array}{ccc}\n     *  r_{11} & r_{12} & r_{13} \\\\\n     *  r_{21} & r_{22} & r_{23} \\\\\n     *  r_{31} & r_{32} & r_{33}\n     *  \\end{array}\n     *  \\right]\n     * @f$\n     */\n\n#endif\n    template< class T = double > class Rotation3D\n    {\n      public:\n        //! Value type.\n        typedef T value_type;\n\n        //! @brief The type of the internal Eigen matrix implementation.\n        typedef Eigen::Matrix< T, 3, 3 > EigenMatrix3x3;\n\n        /**\n           @brief A rotation matrix with uninitialized storage.\n         */\n        Rotation3D ()\n        {\n            _m (0, 0) = 1;\n            _m (0, 1) = 0;\n            _m (0, 2) = 0;\n            _m (1, 0) = 0;\n            _m (1, 1) = 1;\n            _m (1, 2) = 0;\n            _m (2, 0) = 0;\n            _m (2, 1) = 0;\n            _m (2, 2) = 1;\n        }\n\n#if !defined(SWIGJAVA)\n        /**\n         * @brief Constructs an initialized 3x3 rotation matrix\n         *\n         * @param r11 \\f$ r_{11} \\f$\n         * @param r12 \\f$ r_{12} \\f$\n         * @param r13 \\f$ r_{13} \\f$\n         * @param r21 \\f$ r_{21} \\f$\n         * @param r22 \\f$ r_{22} \\f$\n         * @param r23 \\f$ r_{23} \\f$\n         * @param r31 \\f$ r_{31} \\f$\n         * @param r32 \\f$ r_{32} \\f$\n         * @param r33 \\f$ r_{33} \\f$\n         *\n         * @f$\n         *  \\mathbf{R} =\n         *  \\left[\n         *  \\begin{array}{ccc}\n         *  r_{11} & r_{12} & r_{13} \\\\\n         *  r_{21} & r_{22} & r_{23} \\\\\n         *  r_{31} & r_{32} & r_{33}\n         *  \\end{array}\n         *  \\right]\n         * @f$\n         */\n\n#endif\n        Rotation3D (T r11, T r12, T r13, T r21, T r22, T r23, T r31, T r32, T r33)\n        {\n            _m (0, 0) = r11;\n            _m (0, 1) = r12;\n            _m (0, 2) = r13;\n            _m (1, 0) = r21;\n            _m (1, 1) = r22;\n            _m (1, 2) = r23;\n            _m (2, 0) = r31;\n            _m (2, 1) = r32;\n            _m (2, 2) = r33;\n        }\n\n#if !defined(SWIGJAVA)\n        /**\n         * @brief Constructs an initialized 3x3 rotation matrix\n         * @f$ \\robabx{a}{b}{\\mathbf{R}} =\n         * \\left[\n         *  \\begin{array}{ccc}\n         *   \\robabx{a}{b}{\\mathbf{i}} & \\robabx{a}{b}{\\mathbf{j}} & \\robabx{a}{b}{\\mathbf{k}}\n         *  \\end{array}\n         * \\right]\n         * @f$\n         *\n         * @param i @f$ \\robabx{a}{b}{\\mathbf{i}} @f$\n         * @param j @f$ \\robabx{a}{b}{\\mathbf{j}} @f$\n         * @param k @f$ \\robabx{a}{b}{\\mathbf{k}} @f$\n         */\n\n#endif\n        Rotation3D (const rw::math::Vector3D< T >& i, const rw::math::Vector3D< T >& j,\n                    const rw::math::Vector3D< T >& k)\n        {\n            _m (0, 0) = i[0];\n            _m (0, 1) = j[0];\n            _m (0, 2) = k[0];\n            _m (1, 0) = i[1];\n            _m (1, 1) = j[1];\n            _m (1, 2) = k[1];\n            _m (2, 0) = i[2];\n            _m (2, 1) = j[2];\n            _m (2, 2) = k[2];\n        }\n\n#if !defined(SWIGJAVA)\n        /**\n         * @brief Initialize Rotation3D from other rotation types\n         * @param rotVec [in] rotation type such as \\b EAA, \\b RPY, or \\b Quaternion\n         */\n        explicit Rotation3D (const Rotation3DVector< T >& rotVec);\n\n        /**\n         * @brief Constructs a 3x3 rotation matrix set to identity\n         * @return a 3x3 identity rotation matrix\n         *\n         * @f$\n         * \\mathbf{R} =\n         * \\left[\n         * \\begin{array}{ccc}\n         * 1 & 0 & 0 \\\\\n         * 0 & 1 & 0 \\\\\n         * 0 & 0 & 1\n         * \\end{array}\n         * \\right]\n         * @f$\n         */\n\n#endif\n        static const Rotation3D& identity ();\n\n        /**\n         * @brief Normalizes the rotation matrix to satisfy SO(3).\n         *\n         * Makes a normalization of the rotation matrix such that the columns\n         * are normalized and othogonal s.t. it belongs to SO(3).\n         */\n        void normalize ();\n#if !defined(SWIG)\n        /**\n         * @brief Returns reference to matrix element\n         * @param row [in] row\n         * @param column [in] column\n         * @return reference to the element\n         */\n        inline T& operator() (size_t row, size_t column) { return _m (row, column); }\n\n        /**\n         * @brief Returns reference to matrix element\n         * @param row [in] row\n         * @param column [in] column\n         * @return reference to the element\n         */\n        inline const T& operator() (size_t row, size_t column) const { return _m (row, column); }\n#else\n        MATRIXOPERATOR (T);\n#endif\n        /**\n         * @brief Returns the i'th row of the rotation matrix\n         * @param i [in] Index of the row to return. Only valid indices are 0, 1 and 2.\n         */\n        const rw::math::Vector3D< T > getRow (size_t i) const\n        {\n            RW_ASSERT (i < 3);\n            return rw::math::Vector3D< T > (_m (i, 0), _m (i, 1), _m (i, 2));\n        }\n\n        /**\n         * @brief Returns the i'th column of the rotation matrix\n         * @param i [in] Index of the column to return. Only valid indices are 0, 1 and 2.\n         */\n        const rw::math::Vector3D< T > getCol (size_t i) const\n        {\n            RW_ASSERT (i < 3);\n            return rw::math::Vector3D< T > (_m (0, i), _m (1, i), _m (2, i));\n        }\n\n        /**\n         * @brief Comparison operator.\n         *\n         * The comparison operator makes a element wise comparison.\n         * Returns true only if all elements are equal.\n         *\n         * @param rhs [in] Rotation to compare with\n         * @return True if equal.\n         */\n        bool operator== (const Rotation3D< T >& rhs) const\n        {\n            for (int i = 0; i < 3; i++)\n                for (int j = 0; j < 3; j++)\n                    if (!(_m (i, j) == rhs (i, j)))\n                        return false;\n            return true;\n        }\n\n        /**\n         * @brief Comparison operator.\n         *\n         * The comparison operator makes a element wise comparison.\n         * Returns true if any of the elements are different.\n         *\n         * @param rhs [in] Rotation to compare with\n         * @return True if not equal.\n         */\n        bool operator!= (const Rotation3D< T >& rhs) const { return !(*this == rhs); }\n\n        /**\n         * @brief Compares rotations with a given precision\n         *\n         * Performs an element wise comparison. Two elements are considered equal if the difference\n         * are less than \\b precision.\n         *\n         * @param rot [in] Rotation to compare with\n         * @param precision [in] The precision to use for testing\n         * @return True if all elements are less than \\b precision apart.\n         */\n        bool equal (const Rotation3D< T >& rot,\n                    const T precision = std::numeric_limits< T >::epsilon ()) const\n        {\n            for (int i = 0; i < 3; i++)\n                for (int j = 0; j < 3; j++)\n                    if (fabs (_m (i, j) - rot (i, j)) > precision)\n                        return false;\n            return true;\n        }\n\n        /**\n         * @brief Verify that this rotation is a proper rotation\n         *\n         * @return True if this rotation is considered a proper rotation\n         */\n        bool isProperRotation () const;\n\n        /**\n         * @brief Verify that this rotation is a proper rotation\n         *\n         * @return True if this rotation is considered a proper rotation\n         */\n        bool isProperRotation (T precision) const;\n\n        /**\n         * @brief Returns a Eigen 3x3 matrix @f$ \\mathbf{M}\\in SO(3)\n         * @f$ that represents this rotation\n         *\n         * @return @f$ \\mathbf{M}\\in SO(3) @f$\n         */\n        const EigenMatrix3x3& e () const { return _m; };\n\n        /**\n         * @brief Returns a Eigen 3x3 matrix @f$ \\mathbf{M}\\in SO(3)\n         * @f$ that represents this rotation\n         *\n         * @return @f$ \\mathbf{M}\\in SO(3) @f$\n         */\n        EigenMatrix3x3& e () { return _m; };\n\n        /**\n         * @brief Calculates \\f$ \\robabx{a}{c}{\\mathbf{R}} =\n         * \\robabx{a}{b}{\\mathbf{R}} \\robabx{b}{c}{\\mathbf{R}} \\f$\n         *\n         * @param bRc [in] \\f$ \\robabx{b}{c}{\\mathbf{R}} \\f$\n         *\n         * @return \\f$ \\robabx{a}{c}{\\mathbf{R}} \\f$\n         */\n        inline const Rotation3D operator* (const Rotation3D& bRc) const\n        {\n            return multiply (*this, bRc);\n        }\n\n        /**\n         * @brief Calculates \\f$ \\robabx{a}{c}{\\mathbf{R}} =\n         * \\robabx{a}{b}{\\mathbf{R}} \\robabx{b}{c}{\\mathbf{R}} \\f$\n         *\n         * @param rhs [in] \\f$ \\robabx{b}{c}{\\mathbf{R}} \\f$\n         *\n         * @return \\f$ \\robabx{a}{c}{\\mathbf{R}} \\f$\n         */\n        template< class R >\n        inline const Rotation3D operator* (const Eigen::MatrixBase< R >& rhs) const\n        {\n            return Rotation3D< T > (this->e () * rhs);\n        }\n\n        /**\n         * @brief Calculates \\f$ \\robabx{a}{c}{\\mathbf{R}} =\n         * \\robabx{a}{b}{\\mathbf{R}} \\robabx{b}{c}{\\mathbf{R}} \\f$\n         *\n         * @param lhs [in] \\f$ \\robabx{b}{c}{\\mathbf{R}} \\f$\n         * @param rhs [in] \\f$ \\robabx{b}{c}{\\mathbf{R}} \\f$\n         * @return \\f$ \\robabx{a}{c}{\\mathbf{R}} \\f$\n         */\n        template< class R >\n        friend inline Rotation3D operator* (const Eigen::MatrixBase< R >& lhs,\n                                            const Rotation3D< T >& rhs)\n        {\n            return Rotation3D< T > (lhs * rhs.e ());\n        }\n\n        /**\n         * @brief Calculates \\f$ \\robabx{a}{c}{\\mathbf{v}} =\n         * \\robabx{a}{b}{\\mathbf{R}} \\robabx{b}{c}{\\mathbf{v}} \\f$\n         *\n         * @param bVc [in] \\f$ \\robabx{b}{c}{\\mathbf{v}} \\f$\n         * @return \\f$ \\robabx{a}{c}{\\mathbf{v}} \\f$\n         */\n        inline const rw::math::Vector3D< T > operator* (const rw::math::Vector3D< T >& bVc) const\n        {\n            return multiply (*this, bVc);\n        }\n\n        /**\n         * @brief Construct a rotation matrix from a 3x3 Eigen matrix\n         * It is the responsibility of the user that 3x3 matrix is indeed a\n           rotation matrix.\n         */\n        template< class R > explicit Rotation3D (const EigenMatrix3x3& r)\n        {\n            _m (0, 0) = r (0, 0);\n            _m (0, 1) = r (0, 1);\n            _m (0, 2) = r (0, 2);\n            _m (1, 0) = r (1, 0);\n            _m (1, 1) = r (1, 1);\n            _m (1, 2) = r (1, 2);\n            _m (2, 0) = r (2, 0);\n            _m (2, 1) = r (2, 1);\n            _m (2, 2) = r (2, 2);\n        }\n\n        /**\n         * @brief Construct a rotation matrix from a 3x3 Eigen matrix\n         * It is the responsibility of the user that 3x3 matrix is indeed a\n           rotation matrix.\n        */\n        template< class R > explicit Rotation3D (const Eigen::MatrixBase< R >& m)\n        {\n            RW_ASSERT (m.cols () == 3);\n            RW_ASSERT (m.rows () == 3);\n            _m (0, 0) = T (m.row (0) (0));\n            _m (0, 1) = T (m.row (0) (1));\n            _m (0, 2) = T (m.row (0) (2));\n            _m (1, 0) = T (m.row (1) (0));\n            _m (1, 1) = T (m.row (1) (1));\n            _m (1, 2) = T (m.row (1) (2));\n            _m (2, 0) = T (m.row (2) (0));\n            _m (2, 1) = T (m.row (2) (1));\n            _m (2, 2) = T (m.row (2) (2));\n        }\n\n        /**\n         * @brief Creates a skew symmetric matrix from a Vector3D. Also\n         * known as the cross product matrix of v.\n         *\n         * @relates Rotation3D\n         *\n         * @param v [in] vector to create Skew matrix from\n         */\n        static Rotation3D< T > skew (const rw::math::Vector3D< T >& v)\n        {\n            return Rotation3D< T > (0, -v (2), v (1), v (2), 0, -v (0), -v (1), v (0), 0);\n        }\n\n        // Faster-than-boost matrix multiplications below.\n\n        /**\n         *  @brief Write to \\b result the product \\b a * \\b b.\n         */\n        static void multiply (const Rotation3D< T >& a, const Rotation3D< T >& b,\n                              Rotation3D< T >& result);\n\n        /**\n         *  @brief Write to \\b result the product \\b a * \\b b.\n         */\n        static void multiply (const Rotation3D< T >& a, const rw::math::Vector3D< T >& b,\n                              rw::math::Vector3D< T >& result);\n\n        /**\n         * @brief Calculates \\f$ \\robabx{a}{c}{\\mathbf{R}} =\n         * \\robabx{a}{b}{\\mathbf{R}} \\robabx{b}{c}{\\mathbf{R}} \\f$\n         *\n         * @param aRb [in] \\f$ \\robabx{a}{b}{\\mathbf{R}} \\f$\n         *\n         * @param bRc [in] \\f$ \\robabx{b}{c}{\\mathbf{R}} \\f$\n         *\n         * @return \\f$ \\robabx{a}{c}{\\mathbf{R}} \\f$\n         */\n        static const Rotation3D< T > multiply (const Rotation3D< T >& aRb,\n                                               const Rotation3D< T >& bRc);\n\n        /**\n         * @brief Calculates \\f$ \\robabx{a}{c}{\\mathbf{v}} =\n         * \\robabx{a}{b}{\\mathbf{R}} \\robabx{b}{c}{\\mathbf{v}} \\f$\n         *\n         * @param aRb [in] \\f$ \\robabx{a}{b}{\\mathbf{R}} \\f$\n         * @param bVc [in] \\f$ \\robabx{b}{c}{\\mathbf{v}} \\f$\n         * @return \\f$ \\robabx{a}{c}{\\mathbf{v}} \\f$\n         */\n        static const rw::math::Vector3D< T > multiply (const Rotation3D< T >& aRb,\n                                                       const rw::math::Vector3D< T >& bVc);\n#if !defined(SWIGJAVA)\n        /**\n         * @brief Calculate the inverse.\n         * @note This function changes the object that it is invoked on, but this is about x5 faster\n         * than rot = inverse( rot )\n         * @see rw::math::inverse(const rw::math::Rotation3D< T > &) for the (slower) version that does not change the\n         * rotation object itself.\n         * @return the inverse rotation.\n         */\n         #endif\n        inline Rotation3D< T >& inverse ()\n        {\n            T tmpVal  = _m (0, 1);\n            _m (0, 1) = _m (1, 0);\n            _m (1, 0) = tmpVal;\n\n            tmpVal    = _m (0, 2);\n            _m (0, 2) = _m (2, 0);\n            _m (2, 0) = tmpVal;\n\n            tmpVal    = _m (1, 2);\n            _m (1, 2) = _m (2, 1);\n            _m (2, 1) = tmpVal;\n            return *this;\n        }\n\n        /**\n         * @brief Calculate the inverse.\n         * @param copy [in] if coopy is false, This function changes the object that it is invoked\n         * on, but this is about x5 faster than rot = inverse( rot ). else it changes the object,\n         * making it a bit slower.\n         * @return the inverse rotation.\n         */\n        Rotation3D< T > inverse (bool copy);\n\n        /**\n         * @brief Calculate the inverse. of a const Rotation3D. For this function copy is always\n         * true\n         * @param copy [in] always true\n         * @return the inverse rotation.\n         */\n        Rotation3D< T > inverse (bool copy) const;\n\n        T tr () const { return (*this) (0, 0) + (*this) (1, 1) + (*this) (2, 2); }\n\n#if defined(SWIG)\n        TOSTRING ();\n#endif\n\n      private:\n        EigenMatrix3x3 _m;\n    };\n\n    /**\n     * @brief Casts Rotation3D<T> to Rotation3D<Q>\n     *\n     * @relates Rotation3D\n     *\n     * @param rot [in] Rotation3D with type T\n     * @return Rotation3D with type Q\n     */\n    template< class Q, class T > const Rotation3D< Q > cast (const Rotation3D< T >& rot)\n    {\n        Rotation3D< Q > res;\n        for (size_t i = 0; i < 3; i++)\n            for (size_t j = 0; j < 3; j++)\n                res (i, j) = static_cast< Q > (rot (i, j));\n        return res;\n    }\n\n#if !defined(SWIGJAVA)\n    /**\n     * @brief Calculates the inverse @f$ \\robabx{b}{a}{\\mathbf{R}} =\n     * \\robabx{a}{b}{\\mathbf{R}}^{-1} @f$ of a rotation matrix\n     *\n     * @relates Rotation3D\n     *\n     * @see Rotation3D::inverse() for a faster version that modifies the existing rotation object\n     * instead of allocating a new one.\n     *\n     * @param aRb [in] the rotation matrix @f$ \\robabx{a}{b}{\\mathbf{R}} @f$\n     *\n     * @return the matrix inverse @f$ \\robabx{b}{a}{\\mathbf{R}} =\n     * \\robabx{a}{b}{\\mathbf{R}}^{-1} @f$\n     *\n     * @f$ \\robabx{b}{a}{\\mathbf{R}} = \\robabx{a}{b}{\\mathbf{R}}^{-1} =\n     * \\robabx{a}{b}{\\mathbf{R}}^T @f$\n     */\n\n#endif\n    template< class T > const rw::math::Rotation3D< T > inverse (const rw::math::Rotation3D< T >& aRb)\n    {\n        return Rotation3D< T > (aRb (0, 0),\n                                aRb (1, 0),\n                                aRb (2, 0),\n\n                                aRb (0, 1),\n                                aRb (1, 1),\n                                aRb (2, 1),\n\n                                aRb (0, 2),\n                                aRb (1, 2),\n                                aRb (2, 2));\n    }\n\n    /**\n     * @brief Writes rotation matrix to stream\n     *\n     * @relates Rotation3D\n     *\n     * @param os [in/out] output stream to use\n     * @param r [in] rotation matrix to print\n     * @return the updated output stream\n     */\n    template< class T > std::ostream& operator<< (std::ostream& os, const Rotation3D< T >& r)\n    {\n        return os << \"Rotation3D(\" << r (0, 0) << \", \" << r (0, 1) << \", \" << r (0, 2) << \", \"\n                  << r (1, 0) << \", \" << r (1, 1) << \", \" << r (1, 2) << \", \" << r (2, 0) << \", \"\n                  << r (2, 1) << \", \" << r (2, 2) << \")\";\n    }\n#if !defined(SWIG)\n    // Explicit template specifications.\n    extern template class rw::math::Rotation3D< double >;\n    extern template class rw::math::Rotation3D< float >;\n#else\n    SWIG_DECLARE_TEMPLATE (Rotation3Dd, rw::math::Rotation3D< double >);\n    SWIG_DECLARE_TEMPLATE (Rotation3Df, rw::math::Rotation3D< float >);\n#endif\n    using Rotation3Dd = Rotation3D< double >;\n    using Rotation3Df = Rotation3D< float >;\n\n    /**@}*/\n}}    // namespace rw::math\n\nnamespace rw { namespace common {\n    class OutputArchive;\n    class InputArchive;\n    namespace serialization {\n        /**\n         * @copydoc rw::common::serialization::write\n         * @relatedalso rw::math::Rotation3D\n         */\n        template<>\n        void write (const rw::math::Rotation3D< double >& sobject,\n                    rw::common::OutputArchive& oarchive, const std::string& id);\n\n        /**\n         * @copydoc rw::common::serialization::write\n         * @relatedalso rw::math::Rotation3D\n         */\n        template<>\n        void write (const rw::math::Rotation3D< float >& sobject,\n                    rw::common::OutputArchive& oarchive, const std::string& id);\n\n        /**\n         * @copydoc rw::common::serialization::read\n         * @relatedalso rw::math::Rotation3D\n         */\n        template<>\n        void read (rw::math::Rotation3D< double >& sobject, rw::common::InputArchive& iarchive,\n                   const std::string& id);\n\n        /**\n         * @copydoc rw::common::serialization::read\n         * @relatedalso rw::math::Rotation3D\n         */\n        template<>\n        void read (rw::math::Rotation3D< float >& sobject, rw::common::InputArchive& iarchive,\n                   const std::string& id);\n    }    // namespace serialization\n}}       // namespace rw::common\n\nnamespace boost { namespace serialization {\n    /**\n     * @brief Boost serialization.\n     * @param archive [in] the boost archive to read from or write to.\n     * @param R [in/out] the rotation matrix to read/write.\n     * @param version [in] class version (currently version 0).\n     * @relatedalso rw::math::Rotation3D\n     */\n    template< class Archive, class T >\n    void serialize (Archive& archive, rw::math::Rotation3D< T >& R, const unsigned int version)\n    {\n        archive& R (0, 0);\n        archive& R (0, 1);\n        archive& R (0, 2);\n        archive& R (1, 0);\n        archive& R (1, 1);\n        archive& R (1, 2);\n        archive& R (2, 0);\n        archive& R (2, 1);\n        archive& R (2, 2);\n    }\n}}    // namespace boost::serialization\n\n#endif    // end include guard\n", "meta": {"hexsha": "979a98c93089bbe7053f3e562bbf134eebde032b", "size": 21270, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "RobWork/src/rw/math/Rotation3D.hpp", "max_stars_repo_name": "ZLW07/RobWork", "max_stars_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-29T14:16:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T14:16:27.000Z", "max_issues_repo_path": "RobWork/src/rw/math/Rotation3D.hpp", "max_issues_repo_name": "ZLW07/RobWork", "max_issues_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RobWork/src/rw/math/Rotation3D.hpp", "max_forks_repo_name": "ZLW07/RobWork", "max_forks_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.8748068006, "max_line_length": 118, "alphanum_fraction": 0.4708039492, "num_tokens": 6506, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943805178139, "lm_q2_score": 0.6548947223065754, "lm_q1q2_score": 0.4706036672802793}}
{"text": "#define CATCH_CONFIG_MAIN  // This tells Catch to provide a main() - only do this in one cpp file\n\n#include \"catch.hpp\"\n#include <mumpscpp/mumpscpp.h>\n#include <boost/numeric/ublas/matrix_sparse.hpp>\n#include <Eigen\\core>\n#include <shiva\\Environment.h>\n#include <shiva\\Communicator.h>\n#include <boost/numeric/ublas/io.hpp>\n#include <mumpscpp/UblasCoordinateAdaptor.h>\n#include <mumpscpp/UblasVectorAdaptor.h>\n#include <mumpscpp/EigenVector.h>\n\nshiva::environment mpi_env;\n\nvoid assemble_unsymmetric(mumpscpp::UblasCoordinateSparseMatrix& k)\n{\n  const size_t matrix_size = 5;\n  k.resize(matrix_size, matrix_size, false);\n  k.clear();\n  k.append_element(0, 0, 1.0);\n  k.append_element(0, 1, 2.0);\n  k.append_element(0, 2, 3.0);\n  k.append_element(0, 3, -4.0);\n  k.append_element(0, 4, -5.0);\n  k.append_element(1, 0, 2.0);\n  k.append_element(1, 1, 1.0);\n  k.append_element(1, 2, 4.0);\n  k.append_element(1, 3, 3.0);\n  k.append_element(1, 4, -2.0);\n  k.append_element(2, 0, 3.0);\n  k.append_element(2, 1, 4.0);\n  k.append_element(2, 2, 1.0);\n  k.append_element(2, 3, 2.0);\n  k.append_element(2, 4, 3.0);\n  k.append_element(3, 0, 4.0);\n  k.append_element(3, 1, -2.0);\n  k.append_element(3, 2, 4.0);\n  k.append_element(3, 3, 1.0);\n  k.append_element(3, 4, 3.0);\n  k.append_element(4, 0, 5.0);\n  k.append_element(4, 1, 4.0);\n  k.append_element(4, 2, -2.0);\n  k.append_element(4, 3, 4.0);\n  k.append_element(4, 4, 1.0);\n  k.sort();\n}\n\nvoid assemble_symmetric(mumpscpp::UblasCoordinateSparseMatrix& k)\n{\n  // lower triangular part\n  const size_t matrix_size = 3;\n  k.resize(matrix_size, matrix_size, false);\n  k.clear();\n  k.append_element(0, 0, 2.0);\n  k.append_element(1, 0, -1.0);\n  k.append_element(1, 1, 2.0);\n  k.append_element(2, 0, 0.0);\n  k.append_element(2, 1, -1.0);\n  k.append_element(2, 2, 2.0);\n\n  k.sort();\n}\n\n\nbool is_close(double d1, double d2, double eps)\n{\n  return abs(d1 - d2) < eps;\n};\n\nTEST_CASE(\"Mumps unsymmetric\", \"[mumps]\") {\n  shiva::communicator world;\n  const size_t matrix_size = 5;\n  \n  mumpscpp::UblasCoordinateSparseMatrix k;\n  assemble_unsymmetric(k);\n  mumpscpp::EigenVector f = Eigen::VectorXd::Ones(matrix_size);\n\n  mumpscpp::Mumps<double> mumps(mumpscpp::MatrixType::unsymmetric, mumpscpp::HostParallelism::involved, world.fortran_mpi_communicator());\n  mumps.set_output_level(mumpscpp::OutputLevel::error);\n  mumps.setDistributedInput(k);\n\n\n\n  mumps.analyzeFactorize();\n  mumps.solve(f);\n  \n  REQUIRE(is_close(f[0], 0.1933, 0.0001));\n  REQUIRE(is_close(f[1], 0.1015, 0.0001));\n  REQUIRE(is_close(f[2], 0.1314, 0.0001));\n  REQUIRE(is_close(f[3], -0.0212, 0.0001));\n  REQUIRE(is_close(f[4], -0.0249, 0.0001));\n\n  mumps.destroy();\n}\n\nTEST_CASE(\"Mumps unsymmetric schur\", \"[mumps]\") {\n  shiva::communicator world;\n  const size_t matrix_size = 5;\n\n  mumpscpp::UblasCoordinateSparseMatrix k;\n  assemble_unsymmetric(k);\n  mumpscpp::EigenVector f = Eigen::VectorXd::Ones(matrix_size);\n\n  mumpscpp::Mumps<double> mumps(mumpscpp::MatrixType::unsymmetric, mumpscpp::HostParallelism::involved, world.fortran_mpi_communicator());\n  mumps.set_output_level(mumpscpp::OutputLevel::none);\n  mumps.setDistributedInput(k);\n\n  auto get_schur = [&](std::vector<int>& dofs)\n  {\n    if (world.rank() == 0) {\n      mumps.set_host_shur_complement(dofs, mumpscpp::SchurReturnType::host);\n    }\n\n    mumps.analyzeFactorize();\n    auto&& schur = mumps.get_host_schur();\n    Eigen::Map<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>> mf(schur.data(), 2, 2);\n    return mf;\n\n  };\n  \n  std::vector<int> dofs = { 1, 2 };\n  auto mf1 = get_schur(dofs);\n  REQUIRE(is_close(mf1(0,0), 2.7826, 0.0001));\n  REQUIRE(is_close(mf1(0,1), 18.6957, 0.0001));\n  REQUIRE(is_close(mf1(1,0), -8.5652, 0.0001));\n  REQUIRE(is_close(mf1(1,1), 17.6087, 0.0001));\n\n  mumps.destroy();\n\n}\n\nTEST_CASE(\"Mumps symmetric\", \"[mumps]\") {\n  shiva::communicator world;\n  const size_t matrix_size = 3;\n\n  mumpscpp::UblasCoordinateSparseMatrix k;\n  assemble_symmetric(k);\n  mumpscpp::EigenVector f = Eigen::VectorXd::Zero(matrix_size);\n  f[0] = 1.25;\n  f[1] = -2.0;\n  f[2] = 1.75;\n\n  mumpscpp::Mumps<double> mumps(mumpscpp::MatrixType::symmetric, mumpscpp::HostParallelism::involved, world.fortran_mpi_communicator());\n  mumps.set_output_level(mumpscpp::OutputLevel::error);\n  mumps.setDistributedInput(k);\n\n  mumps.analyzeFactorize();\n  mumps.solve(f);\n  mumps.write_problem(\"d:\\\\test.txt\");\n\n  //std::cout << f << std::endl;\n\n  REQUIRE(is_close(f[0], 0.375, 0.0001));\n  REQUIRE(is_close(f[1], -0.5, 0.0001));\n  REQUIRE(is_close(f[2], 0.625, 0.0001));\n\n  mumps.destroy();\n}\n\nTEST_CASE(\"Mumps symmetric schur\", \"[mumps]\") {\n  shiva::communicator world;\n  const size_t matrix_size = 3;\n\n  mumpscpp::UblasCoordinateSparseMatrix k;\n  assemble_symmetric(k);\n  mumpscpp::EigenVector f = Eigen::VectorXd::Ones(matrix_size);\n\n  mumpscpp::Mumps<double> mumps(mumpscpp::MatrixType::symmetric, mumpscpp::HostParallelism::involved, world.fortran_mpi_communicator());\n  mumps.set_output_level(mumpscpp::OutputLevel::none);\n  mumps.setDistributedInput(k);\n\n  auto get_schur = [&](std::vector<int>& dofs)\n  {\n    mumps.set_host_shur_complement(dofs, mumpscpp::SchurReturnType::slaves_lower);\n\n    mumps.analyzeFactorize();\n    auto&& schur = mumps.get_host_schur();\n    return schur;\n\n  };\n\n  std::vector<int> dofs = { 1, 2 };\n  auto mf1 = get_schur(dofs);\n\n  //for (auto d : mf1) { std::cout << d << std::endl; }\n\n  // only the lower triangular will be sent by mumps\n  REQUIRE(is_close(mf1[0], 2.0, 0.0001));\n  REQUIRE(is_close(mf1[1], -1, 0.0001));\n  REQUIRE(is_close(mf1[2], 0.0, 0.0001));\n  REQUIRE(is_close(mf1[3], 1.5, 0.0001));\n\n  mumps.destroy();\n\n}\n\n\n", "meta": {"hexsha": "0c145093fd2d1ee508e7cb1228d169e6aec9aea4", "size": 5636, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "projects/tester/source/main.cpp", "max_stars_repo_name": "tuncb/mumpscpp", "max_stars_repo_head_hexsha": "3af29ca465828297aec9205dbc182c82b1ab69a1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-02T10:37:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-02T10:37:37.000Z", "max_issues_repo_path": "projects/tester/source/main.cpp", "max_issues_repo_name": "tuncb/mumpscpp", "max_issues_repo_head_hexsha": "3af29ca465828297aec9205dbc182c82b1ab69a1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "projects/tester/source/main.cpp", "max_forks_repo_name": "tuncb/mumpscpp", "max_forks_repo_head_hexsha": "3af29ca465828297aec9205dbc182c82b1ab69a1", "max_forks_repo_licenses": ["Apache-2.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.3216080402, "max_line_length": 138, "alphanum_fraction": 0.6857700497, "num_tokens": 2008, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.685949467848392, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.47052666803762816}}
{"text": "// Copyright Louis Dionne 2013-2016\r\n// Distributed under the Boost Software License, Version 1.0.\r\n// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\r\n\r\n#include <boost/hana/fold_right.hpp>\r\n#include <boost/hana/optional.hpp>\r\n#include <boost/hana/plus.hpp>\r\nnamespace hana = boost::hana;\r\n\r\n\r\nstatic_assert(hana::fold_right(hana::nothing, 1, hana::plus) == 1, \"\");\r\nstatic_assert(hana::fold_right(hana::just(4), 1, hana::plus) == 5, \"\");\r\n\r\nint main() { }\r\n", "meta": {"hexsha": "a905175bcb24fec7c6126f167d83b48c12444210", "size": 490, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "thirdparty-cpp/boost_1_62_0/libs/hana/example/optional/foldable.cpp", "max_stars_repo_name": "nxplatform/nx-mobile", "max_stars_repo_head_hexsha": "0dc174c893f2667377cb2ef7e5ffeb212fa8b3e5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-12-15T19:57:24.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-15T19:57:24.000Z", "max_issues_repo_path": "thirdparty-cpp/boost_1_62_0/libs/hana/example/optional/foldable.cpp", "max_issues_repo_name": "nxplatform/nx-mobile", "max_issues_repo_head_hexsha": "0dc174c893f2667377cb2ef7e5ffeb212fa8b3e5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thirdparty-cpp/boost_1_62_0/libs/hana/example/optional/foldable.cpp", "max_forks_repo_name": "nxplatform/nx-mobile", "max_forks_repo_head_hexsha": "0dc174c893f2667377cb2ef7e5ffeb212fa8b3e5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.6666666667, "max_line_length": 82, "alphanum_fraction": 0.693877551, "num_tokens": 141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6859494550081926, "lm_q2_score": 0.6859494678483918, "lm_q1q2_score": 0.4705266636337641}}
{"text": "#include <blitz/array.h>\n\nusing namespace blitz;\n\nint main()\n{\n    Array<int,1> A(4), B(4), C(4);\n    A = 0, 1, 2, 3;\n    B = 0, 1, 0, 3;\n    C = A ^ B;\n    cout << C << endl;\n}\n\n", "meta": {"hexsha": "028bb92ef2f1276fcf27c7af53530d8b929dfb76", "size": 179, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depspawn-blitz-0.10/doc/examples/xor.cpp", "max_stars_repo_name": "fraguela/depspawn", "max_stars_repo_head_hexsha": "b5760f4c0d38a1b245ee5274e2ccc5c5fe2d3d45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-04-12T11:05:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T11:10:27.000Z", "max_issues_repo_path": "ibtk/third_party/blitz-0.10/doc/examples/xor.cpp", "max_issues_repo_name": "MSV-Project/IBAMR", "max_issues_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ibtk/third_party/blitz-0.10/doc/examples/xor.cpp", "max_forks_repo_name": "MSV-Project/IBAMR", "max_forks_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 12.7857142857, "max_line_length": 34, "alphanum_fraction": 0.4525139665, "num_tokens": 78, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6859494550081926, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.47052664601830846}}
{"text": "// Header for this file\n#include \"jvector.h\"\n// C System-Headers\n#include <termios.h> /* POSIX terminal control definitions */\n#include <sys/ioctl.h>\n#include <fcntl.h>   //fopen(),fclose()\n#include <unistd.h>  //read(), write()\n#include <stdio.h>\n\n// C++ System headers\n#include <vector>      //vector\n#include <string>      //string\n#include <fstream>     //iss* ofstream\n#include <chrono>      // timing functions\n#include <cmath>       //sqrt, abs\n#include <iostream>    //cout\n#include <typeinfo>    //typeid\n#include <algorithm>   // transform, find, count, erase\n#include <functional>  // plus/minus/multiplies\n#include <utility>     //std::make_pair\n#include <map>         //std::map\n#include <typeinfo>    //typeid\n#include <mutex> //protect against concurrent access when using (unordered) parallel for loops\n#include <assert.h> //static_assert\n\n// Boost Headers\n#include <boost/algorithm/string.hpp>  //split() and is_any_of for parsing .csv files\n#include <boost/lexical_cast.hpp>  //lexical cast (unsurprisingly)\n#include <dirent.h>\n\n// Miscellaneous Headers\n#include <omp.h>  //OpenMP pragmas\n\nnamespace jaspl {\n\ntemplate class JVector<int>;\ntemplate class JVector<float>;\ntemplate class JVector<double>;\ntemplate class JVector<char>;\n\ntemplate <class F> JVector<F>::JVector(std::string raw_data) {\n    ParseRawData(raw_data);\n}\n\ntemplate <class F> JVector<F>::JVector(std::vector<F> vec) {\n    underlying_vector = vec;\n}\n\ntemplate <class F> JVector<F>::JVector(F* ptr, uint ptr_size) {\n\n    underlying_vector.reserve(underlying_vector.size() + ptr_size);\n    std::copy(&ptr[0], &ptr[ptr_size], std::back_inserter(underlying_vector));\n}\n\ntemplate <class F> JVector<F>::JVector(uint size) {\n    underlying_vector.reserve( size );\n}\n\ntemplate <class F> JVector<F>::JVector(uint size, F fill_element) {\n    underlying_vector.reserve( size );\n    underlying_vector = std::vector<F> ( size , fill_element);\n}\n\ntemplate <class F> JVector<F>::JVector() {}\n\ntemplate <class F> JVector<F>::~JVector() {\n    underlying_vector.clear();\n}\n\ntemplate <class F> bool JVector<F>::check_if_arithmetic(F input) {\n\n    if ( !std::is_arithmetic<F>::value ) {\n\n        std::string err_mesg = \"JVector: \";\n        err_mesg += \"cannot initialize from non-arithmetic type \";\n        err_mesg += boost::lexical_cast<std::string>(typeid(input).name());\n        throw std::invalid_argument(err_mesg);\n\n        return false;\n    } else {\n        return true;\n    }\n}\n\ntemplate <class F> uint JVector<F>::size() {\n    return underlying_vector.size();\n}\n\ntemplate <class F> uint JVector<F>::num_chars(std::string raw_data, char delim) {\n    return std::count(raw_data.begin(), raw_data.end(), delim);\n}\n\ntemplate <class F> void JVector<F>::ParseRawData( std::string raw_data ) {\n\n    uint lines = num_chars(raw_data, '\\n');\n\n    std::istringstream data_stream(raw_data);\n\n    for (uint i = 0; i < lines; i++) {\n        std::string input;\n        std::getline(data_stream, input);\n        try {\n            F val = boost::lexical_cast<F>(input);\n            underlying_vector.push_back(val);\n        } catch (const boost::bad_lexical_cast& err) {\n            std::cerr << err.what() << std::endl;\n        }\n    }\n}\n\ntemplate <class F> double JVector<F>::sum(std::vector<F>& data_list,double exponent) {\n\n    double tot=0;\n\n    for ( uint i = 0 ; i < data_list.size(); i ++) {\n        tot += pow( data_list[i], exponent );\n    }\n\n    return tot;\n}\n\ntemplate <class F> double JVector<F>::mean(std::vector<F>& data_list) {\n    //compute mean value of data set\n    double sum_x=sum(data_list,1.0);\n    double n=data_list.size();\n    return sum_x/n;\n}\n\ntemplate <class F> double JVector<F>::mean() {\n    return mean(underlying_vector);\n}\n\ntemplate <class F> F JVector<F>::min() {\n    F min_power= *std::min_element(underlying_vector.begin(), underlying_vector.end());\n    return min_power;\n}\n\ntemplate <class F> F JVector<F>::max() {\n    F min_power= *std::max_element(underlying_vector.begin(), underlying_vector.end());\n    return min_power;\n}\n\ntemplate <class F> double JVector<F>::std_dev(std::vector<F> &data_list) {\n\n    //compute mean value of data set\n    double sum_x=sum(data_list,1.0);\n    double n=data_list.size();\n    double mean = sum_x/n;\n\n    //compute variance taking into account Bessel's correction i.e. n/(n-1)\n    double sum_x2=sum(data_list,2.0);\n    double sigma_sqr=sum_x2/(n-1.0)-n/(n-1.0)*pow(mean,2.0);\n\n    //return square root of variance\n    return sqrt(sigma_sqr);\n}\n\ntemplate <class F> double JVector<F>::std_dev() {\n    return std_dev(underlying_vector);\n}\n\ntemplate <class F> double JVector<F>::norm() {\n    return sqrt(sum(underlying_vector,2.0));\n\n}\n\ntemplate <class F> void JVector<F>::Normalize() {\n    double norm_factor=sqrt(sum(underlying_vector,2.0));\n\n    for(unsigned int i = 0; i<underlying_vector.size(); i++) {\n        underlying_vector.at(i)=underlying_vector.at(i)/norm_factor;\n    }\n}\n\n}\n", "meta": {"hexsha": "bcd6e19eb4ee68445e5503f45826305ea1cf2f13", "size": 4917, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "jVector/jvector.cpp", "max_stars_repo_name": "axion-dark-matter-experiment/JASPL", "max_stars_repo_head_hexsha": "324e65a9a126704c72e69035e47c856239b16298", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "jVector/jvector.cpp", "max_issues_repo_name": "axion-dark-matter-experiment/JASPL", "max_issues_repo_head_hexsha": "324e65a9a126704c72e69035e47c856239b16298", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "jVector/jvector.cpp", "max_forks_repo_name": "axion-dark-matter-experiment/JASPL", "max_forks_repo_head_hexsha": "324e65a9a126704c72e69035e47c856239b16298", "max_forks_repo_licenses": ["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.9375, "max_line_length": 94, "alphanum_fraction": 0.6615822656, "num_tokens": 1282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081925, "lm_q2_score": 0.685949442167993, "lm_q1q2_score": 0.47052664601830846}}
{"text": "// MTL4 Test 05.cpp : Defines the entry point for the console application.\n//\n\n#include <iostream>\n#include <boost/numeric/mtl/mtl.hpp>\n\nusing namespace mtl;\n\ntypedef mtl::dense_vector<double> mtlVec;\nmtlVec testFunc( mtlVec A,double Scale);\n\nint main(int, char**)\n{\n    mtlVec u(3);\n    u(0)=1.1;\n    u(1)=2.2;\n    u(2)=3.3;\n    mtlVec myVec(3);\n    myVec=testFunc(u,55.5);\n    print_vector(myVec);\n\n    return 0;\n}\n\n\nmtlVec testFunc(mtlVec A ,double Scale)\n{\n    const std::size_t testSize=size(A);\n    mtlVec testVec(testSize);\n    testVec=Scale*A;\n    print_vector(testVec);\n\n    return testVec;\n}\n", "meta": {"hexsha": "a3e2987ff59a8c6550bd567a30d3025133e8113c", "size": 602, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/vector_delete_test.cpp", "max_stars_repo_name": "shikharvashistha/mtl4", "max_stars_repo_head_hexsha": "09d8523d59baf5fdec29f3509a63babc2763af4a", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/mtl/test/vector_delete_test.cpp", "max_issues_repo_name": "shikharvashistha/mtl4", "max_issues_repo_head_hexsha": "09d8523d59baf5fdec29f3509a63babc2763af4a", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/mtl/test/vector_delete_test.cpp", "max_forks_repo_name": "shikharvashistha/mtl4", "max_forks_repo_head_hexsha": "09d8523d59baf5fdec29f3509a63babc2763af4a", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 17.2, "max_line_length": 74, "alphanum_fraction": 0.6561461794, "num_tokens": 194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.6893056295505783, "lm_q1q2_score": 0.4705019177137763}}
{"text": "//\n//=======================================================================\n// Copyright 2012\n// Author: Alex Hagen-Zanker\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// The nearest source visitor implements the dijkstra visitor concepts and \n// records for each node which is the nearest source. Only useful for a \n// search with multiple sources.\n//\n//=======================================================================\n//\n\n#ifndef BLINK_GRAPH_DIJKSTRA_VISITOR_NEAREST_SOURCE_VISITOR_HPP\n#define BLINK_GRAPH_DIJKSTRA_VISITOR_NEAREST_SOURCE_VISITOR_HPP\n\n#include <blink/graph/property_maps/vertex_property_map_helper.hpp>\n#include <boost/tuple/tuple.hpp> //tie\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <boost/graph/properties.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <boost/range/algorithm/for_each.hpp>\n\nnamespace blink {\n  \ntemplate<typename NearestsourceMap>  \nstruct nearest_source_visitor : public boost::default_dijkstra_visitor\n{\n  nearest_source_visitor(const NearestsourceMap& nearest = NearestsourceMap() ) \n    : m_nearest_source_map(nearest)\n  {}\n  template<typename Graph>\n  void init_map(const Graph& g) \n  {\n    typename boost::graph_traits<Graph>::vertex_iterator ui, ui_end;\n    for (boost::tie(ui, ui_end) = vertices(g); ui != ui_end; ++ui) {\n      put(m_nearest_source_map, *ui, *ui);\n    }\n  }\n\n  template<typename E, typename G>\n  void edge_relaxed(const E& e, const G& g) \n  {\n    put(m_nearest_source_map, target(e,g), get(m_nearest_source_map, source(e,g))); \n  }\n\n  NearestsourceMap m_nearest_source_map;\n};\n\ntemplate<typename Graph, typename NearestsourceMap>\nvoid init_nearest_source_map(const Graph& g, NearestsourceMap nearest)\n{\n  typename graph_traits<Graph>::vertex_iterator ui, ui_end;\n  for (tie(ui, ui_end) = vertices(g); ui != ui_end; ++ui) {\n    put(nearest, *ui, *ui);\n  }\n}\n\ntemplate<typename DijkstraState>\nstruct nearest_source_helper\n{\n  typedef typename DijkstraState::template param<boost::vertex_index_t>::type index_type;\n  typedef typename DijkstraState::graph_type graph_type;\n\n  typedef typename boost::graph_traits<graph_type>::vertex_descriptor vertex_descriptor;\n  typedef typename vertex_property_map_helper<vertex_descriptor,graph_type, index_type> helper; \n  typedef typename helper::type map_type;\n  typedef typename nearest_source_visitor<map_type> visitor_type;\n \n  static map_type make_map(DijkstraState& state)\n  {\n    return helper::make(state.get_graph(), state.get<boost::vertex_index_t>());\n  }\n\n    static visitor_type make_visitor(DijkstraState& state)\n  {\n    map_type map = make_map(state);\n    visitor_type visitor(map);\n    visitor.init_map(state.get_graph());\n      \n    return visitor;\n  }\n};\n\ntemplate<typename Graph, typename Params>\nstruct nearest_source_helper_indirect : nearest_source_helper<typename dijkstra_state_helper<Graph, Params>::type>\n{};\n\ntemplate<typename DijkstraState>\ntypename nearest_source_helper<DijkstraState>::visitor_type \n  make_nearest_source_visitor(DijkstraState& state)\n{\n  return nearest_source_helper<DijkstraState>::make_visitor(state);\n}\n\n\n};// namespace blink;\n\n#endif //BLINK_GRAPH_DIJKSTRA_VISITOR_NEAREST_SOURCE_VISITOR_HPP", "meta": {"hexsha": "ca9e35ad0cb53094e792e16fd0e4844aad3cebba", "size": 3372, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "blink/graph/dijkstra_visitor/nearest_source_visitor.hpp", "max_stars_repo_name": "ahhz/resumable_dijkstra", "max_stars_repo_head_hexsha": "1fa57b7de5dd9ce9a23f146b709f7cb76cdf01d1", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-11-18T15:55:43.000Z", "max_stars_repo_stars_event_max_datetime": "2015-11-18T15:55:43.000Z", "max_issues_repo_path": "blink/graph/dijkstra_visitor/nearest_source_visitor.hpp", "max_issues_repo_name": "ahhz/resumable_dijkstra", "max_issues_repo_head_hexsha": "1fa57b7de5dd9ce9a23f146b709f7cb76cdf01d1", "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": "blink/graph/dijkstra_visitor/nearest_source_visitor.hpp", "max_forks_repo_name": "ahhz/resumable_dijkstra", "max_forks_repo_head_hexsha": "1fa57b7de5dd9ce9a23f146b709f7cb76cdf01d1", "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.7378640777, "max_line_length": 114, "alphanum_fraction": 0.7197508897, "num_tokens": 756, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056295505783, "lm_q2_score": 0.682573734412324, "lm_q1q2_score": 0.47050191771377625}}
{"text": "#ifndef __fovis_calibration_hpp__\n#define __fovis_calibration_hpp__\n\n#include <Eigen/Geometry>\n\nnamespace fovis\n{\n\n/**\n * \\ingroup FovisCore\n * \\brief Intrinsic parameters for a pinhole camera with plumb-bob distortion model.\n *\n */\nstruct CameraIntrinsicsParameters\n{\n  CameraIntrinsicsParameters() :\n    width(0), height(0), fx(0), fy(0), cx(0), cy(0),\n    k1(0), k2(0), k3(0), p1(0), p2(0)\n  {}\n\n  /**\n   * \\code\n   * [ fx 0  cx 0 ]\n   * [ 0  fy cy 0 ]\n   * [ 0  0  1  0 ]\n   * \\endcode\n   *\n   * \\return a 3x4 projection matrix that transforms 3D homogeneous points in\n   * the camera frame to 2D homogeneous points in the image plane.\n   */\n  Eigen::Matrix<double, 3, 4> toProjectionMatrix() const\n  {\n    Eigen::Matrix<double, 3, 4> result;\n    result <<\n      fx,  0, cx, 0,\n       0, fy, cy, 0,\n       0,  0,  1, 0;\n    return result;\n  }\n\n  /**\n   * Image width.\n   */\n  int width;\n\n  /**\n   * Image height.\n   */\n  int height;\n\n  /**\n   * focal length along the X axis.\n   */\n  double fx;\n\n  /**\n   * focal length along the Y axis.  Should generally be the same as \\p fx.\n   */\n  double fy;\n\n  /**\n   * X-coordinate of the camera center of projection / principal point.\n   */\n  double cx;\n\n  /**\n   * Y-coordinate of the camera center of projection / principal point.\n   */\n  double cy;\n\n  /**\n   * First radial distortion coefficient (r^2) for a plumb-bob distortion model.\n   *\n   * \\sa <a href=\"http://www.vision.caltech.edu/bouguetj/calib_doc/htmls/parameters.html\">http://www.vision.caltech.edu/bouguetj/calib_doc/htmls/parameters.html</a>\n   */\n  double k1;\n\n  /**\n   * Second radial distortion coefficient (r^4) for a plumb-bob distortion model.\n   */\n  double k2;\n\n  /**\n   * Third radial distortion coefficient (r^6) for a plumb-bob distortion model.\n   */\n  double k3;\n\n  /**\n   * First tangential distortion coefficient for a plumb-bob distortion model.\n   */\n  double p1;\n\n  /**\n   * Second tangential distortion coefficient for a plumb-bob distortion model.\n   */\n  double p2;\n};\n\n}\n\n#endif\n", "meta": {"hexsha": "9d01c394e311943b094b8d31ea8536321e4d6501", "size": 2014, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "navigation_layer/fovis/libfovis/libfovis/libfovis/camera_intrinsics.hpp", "max_stars_repo_name": "kartavya2000/Anahita", "max_stars_repo_head_hexsha": "9afbf6c238658188df7d0d97b2fec3bd48028c03", "max_stars_repo_licenses": ["BSD-3-Clause"], "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": "perception/rwth_people_tracker/rwth_visual_odometry/3rd_party/fovis/libfovis/camera_intrinsics.hpp", "max_issues_repo_name": "VisualComputingInstitute/CROWDBOT_perception", "max_issues_repo_head_hexsha": "df98f3f658c39fb3fa4ac0456f1214f7918009f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2018-10-03T12:14:35.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-07T09:33:14.000Z", "max_forks_repo_path": "perception/rwth_people_tracker/rwth_visual_odometry/3rd_party/fovis/libfovis/camera_intrinsics.hpp", "max_forks_repo_name": "VisualComputingInstitute/CROWDBOT_perception", "max_forks_repo_head_hexsha": "df98f3f658c39fb3fa4ac0456f1214f7918009f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2018-09-09T12:35:15.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-03T09:28:19.000Z", "avg_line_length": 19.7450980392, "max_line_length": 164, "alphanum_fraction": 0.6226415094, "num_tokens": 606, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056167854461, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.47050191345159914}}
{"text": "/*\n@copyright Louis Dionne 2014\nDistributed under the Boost Software License, Version 1.0.\n(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n */\n\n#include <boost/hana/detail/assert.hpp>\n#include <boost/hana/detail/constexpr.hpp>\n#include <boost/hana/functional.hpp>\nusing namespace boost::hana;\n\n\nint main() {\n    //! [main]\n    BOOST_HANA_CONSTEXPR_LAMBDA auto plus = _ + _;\n    BOOST_HANA_CONSTEXPR_ASSERT(plus(1, 2) == 1 + 2);\n\n    BOOST_HANA_CONSTEXPR_LAMBDA auto increment = _ + 1;\n    BOOST_HANA_CONSTEXPR_ASSERT(increment(1) == 2);\n\n    BOOST_HANA_CONSTEXPR_LAMBDA auto double_ = 2 * _;\n    BOOST_HANA_CONSTEXPR_ASSERT(double_(1) == 2);\n\n    // Extra arguments are ignored.\n    BOOST_HANA_CONSTEXPR_ASSERT(double_(1, \"ignored\") == 2);\n    //! [main]\n}\n", "meta": {"hexsha": "440cb962bee022b9fa714c1fa00366607d776ac5", "size": 788, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/functional/placeholder.cpp", "max_stars_repo_name": "rbock/hana", "max_stars_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-05-07T14:29:13.000Z", "max_stars_repo_stars_event_max_datetime": "2015-07-04T10:59:46.000Z", "max_issues_repo_path": "example/functional/placeholder.cpp", "max_issues_repo_name": "rbock/hana", "max_issues_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/functional/placeholder.cpp", "max_forks_repo_name": "rbock/hana", "max_forks_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1428571429, "max_line_length": 78, "alphanum_fraction": 0.711928934, "num_tokens": 223, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6893056167854461, "lm_q2_score": 0.682573734412324, "lm_q1q2_score": 0.4705019090006323}}
{"text": "\ufeff/*M///////////////////////////////////////////////////////////////////////////////////////\r\n// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.\r\n//\r\n//  By downloading, copying, installing or using the software you agree to this license.\r\n//  If you do not agree to this license, do not download, install,\r\n//  copy or use the software.\r\n//\r\n//\r\n//                           License Agreement\r\n//                For Open Source Computer Vision Library\r\n//\r\n// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.\r\n// Copyright (C) 2008-2011, Willow Garage Inc., all rights reserved.\r\n// Third party copyrights are property of their respective owners.\r\n//\r\n// Redistribution and use in source and binary forms, with or without modification,\r\n// are permitted provided that the following conditions are met:\r\n//\r\n//   * Redistributions of source code must retain the above copyright notice,\r\n//     this list of conditions and the following disclaimer.\r\n//\r\n//   * Redistributions in binary form must reproduce the above copyright notice,\r\n//     this list of conditions and the following disclaimer in the documentation\r\n//     and/or other materials provided with the distribution.\r\n//\r\n//   * The name of the copyright holders may not be used to endorse or promote products\r\n//     derived from this software without specific prior written permission.\r\n//\r\n// This software is provided by the 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 disclaimed.\r\n// In no event shall the Intel Corporation or contributors be liable for any direct,\r\n// indirect, incidental, special, exemplary, or consequential damages\r\n// (including, but not limited to, procurement of substitute goods or services;\r\n// loss of use, data, or profits; or business interruption) however caused\r\n// 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\r\n// the use of this software, even if advised of the possibility of such damage.\r\n//\r\n// C by Benjamin Wassermann\r\n//M*/\r\n\r\n// detect junction or corner areas and skip them for optimization -> less error for wide range interpolation like cubic....\r\n\r\n#ifndef _LINE_OPTIMIZER_HPP_\r\n#define _LINE_OPTIMIZER_HPP_\r\n#ifdef __cplusplus\r\n\r\n#include <utility/mean.hpp>\r\n#include <dlib/optimization.h>\r\n\r\nnamespace lsfm {\r\n    template <\r\n        class mat_type,\r\n        class search_strategy_type = dlib::bfgs_search_strategy,\r\n        class stop_strategy_type = dlib::objective_delta_stop_strategy\r\n        >\r\n        struct LineOptimizer {\r\n\r\n        //! @brief optimize line for better fitting to gradient maginutde image (rotation and orthogonal translation to line)\r\n        //! @param mag is the magnitude image as mat, it could also be the quadratic magnitude as integer\r\n        //! @param l is the line segment to optimize parameters for\r\n        //! @param d distnance in pixels, parameter to optimize\r\n        //! @param r radian for rotation, parameter to optimize\r\n        //! @param d_lower lower searching bound for distance parameter optimization\r\n        //! @param d_upper upper searching bound for distance parameter optimization\r\n        //! @param r_lower lower searching bound for rotation parameter optimization\r\n        //! @param r_upper upper searching bound for rotation parameter optimization\r\n        //! @param mean_param option for mean calculation (see mean variants)\r\n        //! @param derivative_prec delta for computing approximating derivatives (done with dlib helper)\r\n        //! @param interpolate_op operator for interpolaton (function pointer to linear or cubic interpolation)\r\n        //! @param mean_op operator for mean computation (function pointer to variants of mean - step over line by \r\n        //!        fixed distance or use fixed samples and compute distance to have always the same number of points)\r\n        //! @param search search strategy of optimizer (see dlib for more informations)\r\n        //! @param stop stop strategy of optimizer (see dlib for more informations)\r\n        //! @return error for found values\r\n        template<class FT, template<class> class LPT>\r\n        static inline double optimize(const cv::Mat& mag, const LineSegment<FT, LPT>& l, FT& d, FT& r,\r\n            double d_lower = -1, double d_upper = 1, double r_lower = -CV_PI / 180, double r_upper = CV_PI / 180,\r\n            double mean_param = 1, double derivative_prec = 1e-7,\r\n            typename MeanHelper<double,LPT>::func_type mean_op = Mean<double, mat_type, LinearInterpolator<double, mat_type>>::process,\r\n            search_strategy_type search = dlib::bfgs_search_strategy(),\r\n            stop_strategy_type stop = dlib::objective_delta_stop_strategy(1e-7)) {\r\n\r\n            CV_Assert(cv::DataType<mat_type>::type == mag.type());\r\n\r\n            typedef dlib::matrix<double, 0, 1> column_vector;\r\n            auto eval = [&](const column_vector& v) -> double {\r\n                LineSegment<double, LPT> tmp = l;\r\n                tmp.translateOrtho(v(0));\r\n                tmp.rotate(v(1), tmp.center());\r\n                return mean_op(mag, tmp, mean_param);\r\n            };\r\n\r\n            column_vector starting_point(2), lower(2), upper(2);\r\n            starting_point = d, r;\r\n            lower = d_lower, r_lower;\r\n            upper = d_upper, r_upper;\r\n            double ret = dlib::find_max_box_constrained(search, stop,\r\n                eval, dlib::derivative(eval, derivative_prec), starting_point, lower, upper);\r\n            d = starting_point(0);\r\n            r = starting_point(1);\r\n            return ret;\r\n\r\n        }\r\n\r\n        //! This variant will optimize the line object instead of just calculating the optimized parameters for the line\r\n        template<class FT, template<class> class LPT>\r\n        static inline double optimize_line(const cv::Mat& mag, LineSegment<FT, LPT>& l,\r\n                double d_lower = -1, double d_upper = 1, double r_lower = -CV_PI / 180, double r_upper = CV_PI / 180,\r\n                double mean_param = 1, double derivative_prec = 1e-7,\r\n                typename MeanHelper<double,LPT>::func_type mean_op = Mean<double, mat_type, LinearInterpolator<double, mat_type>>::processs,\r\n                search_strategy_type search = dlib::bfgs_search_strategy(),\r\n                stop_strategy_type stop = dlib::objective_delta_stop_strategy(1e-7)) {\r\n            FT d = 0, r = 0;\r\n            double ret = optimize(mag,l, d, r, d_lower, d_upper, r_lower, r_upper, mean_param, derivative_prec, mean_op, search, stop);\r\n            l.translateOrtho(d);\r\n            l.rotate(r, l.center());\r\n            return ret;\r\n        }\r\n\r\n        //! This variant will optimize the line object instead of just calculating the optimized parameters for the line\r\n        template<class FT, template<class> class LPT, class LV>\r\n        static inline void optimizeLV(const cv::Mat& mag, LV& in,\r\n            double d_lower = -1, double d_upper = 1, double r_lower = -CV_PI / 180, double r_upper = CV_PI / 180,\r\n            FT mean_param = 1, double derivative_prec = 1e-7,\r\n            typename MeanHelper<double,LPT>::func_type mean_op = Mean<double, mat_type, LinearInterpolator<double, mat_type>>::processs,\r\n            search_strategy_type search = dlib::bfgs_search_strategy(),\r\n            stop_strategy_type stop = dlib::objective_delta_stop_strategy(1e-7)) {\r\n            for (size_t i = 0; i != in.size(); ++i)\r\n                optimize_line(mag, in[i], d_lower, d_upper, r_lower, r_upper, mean_param, derivative_prec, mean_op, search, stop);\r\n        }\r\n\r\n        //! This variant will optimize the line object instead of just calculating the optimized parameters for the line\r\n        template<class FT, template<class> class LPT, class LV>\r\n        static inline void optimizeLV(const cv::Mat& mag, LV& in, std::vector<double> &err,\r\n            double d_lower = -1, double d_upper = 1, double r_lower = -CV_PI / 180, double r_upper = CV_PI / 180,\r\n            double mean_param = 1, double derivative_prec = 1e-7,\r\n            typename MeanHelper<FT,LPT>::func_type mean_op = Mean<double, mat_type, LinearInterpolator<double, mat_type>>::processs,\r\n            search_strategy_type search = dlib::bfgs_search_strategy(),\r\n            stop_strategy_type stop = dlib::objective_delta_stop_strategy(1e-7)) {\r\n            err.resize(in.size());\r\n            for (size_t i = 0; i != in.size(); ++i)\r\n                err[i] = optimize_line(mag, in[i], d_lower, d_upper, r_lower, r_upper, mean_param, derivative_prec, mean_op, search, stop);\r\n        }\r\n\r\n        //! This variant will optimize the line object instead of just calculating the optimized parameters for the line\r\n        template<class FT, template<class> class LPT, class LV>\r\n        static inline double optimizeLV(const cv::Mat& mag, const LV& in, LV& out,\r\n            double d_lower = -1, double d_upper = 1, double r_lower = -CV_PI / 180, double r_upper = CV_PI / 180,\r\n            double mean_param = 1, double derivative_prec = 1e-7,\r\n            typename MeanHelper<FT,LPT>::func_type mean_op = Mean<double, mat_type, LinearInterpolator<double, mat_type>>::processs,\r\n            search_strategy_type search = dlib::bfgs_search_strategy(),\r\n            stop_strategy_type stop = dlib::objective_delta_stop_strategy(1e-7)) {\r\n            out.resize(in.size());\r\n            for (size_t i = 0; i != in.size(); ++i) {\r\n                out[i] = in[i];\r\n                optimize_line(mag, out[i], d_lower, d_upper, r_lower, r_upper, mean_param, derivative_prec, mean_op, search, stop);\r\n            }\r\n        }\r\n\r\n        //! This variant will optimize the line object instead of just calculating the optimized parameters for the line\r\n        template<class FT, template<class> class LPT, class LV>\r\n        static inline double optimizeLV(const cv::Mat& mag, const LV& in, LV& out, std::vector<double> &err,\r\n            double d_lower = -1, double d_upper = 1, double r_lower = -CV_PI / 180, double r_upper = CV_PI / 180,\r\n            double mean_param = 1, double derivative_prec = 1e-7,\r\n            typename MeanHelper<double,LPT>::func_type mean_op = Mean<double, mat_type, LinearInterpolator<double, mat_type>>::processs,\r\n            search_strategy_type search = dlib::bfgs_search_strategy(),\r\n            stop_strategy_type stop = dlib::objective_delta_stop_strategy(1e-7)) {\r\n            out.resize(in.size());\r\n            err.resize(in.size());\r\n            for (size_t i = 0; i != in.size(); ++i) {\r\n                out[i] = in[i];\r\n                err[i] = optimize_line(mag, out[i], d_lower, d_upper, r_lower, r_upper, mean_param, derivative_prec, mean_op, search, stop);\r\n            }\r\n        }\r\n    };\r\n    \r\n\r\n}\r\n#endif\r\n#endif\r\n", "meta": {"hexsha": "d6e3cbbe8884e97cc3b018f408d3112daa333ce8", "size": 10906, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/geometry/line_optimizer.hpp", "max_stars_repo_name": "waterben/LineExtraction", "max_stars_repo_head_hexsha": "d247de45417a1512a3bf5d0ffcd630d40ffb8798", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-12T13:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-12T13:30:56.000Z", "max_issues_repo_path": "include/geometry/line_optimizer.hpp", "max_issues_repo_name": "waterben/LineExtraction", "max_issues_repo_head_hexsha": "d247de45417a1512a3bf5d0ffcd630d40ffb8798", "max_issues_repo_licenses": ["MIT"], "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/geometry/line_optimizer.hpp", "max_forks_repo_name": "waterben/LineExtraction", "max_forks_repo_head_hexsha": "d247de45417a1512a3bf5d0ffcd630d40ffb8798", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 59.5956284153, "max_line_length": 141, "alphanum_fraction": 0.6492756281, "num_tokens": 2403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.682573734412324, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.4705019046440602}}
{"text": "// Copyright John Maddock 2006.\n// Copyright Paul A. Bristow 2007, 2009\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include <boost/math/concepts/real_concept.hpp>\n#include <boost/test/test_exec_monitor.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/math/special_functions/math_fwd.hpp>\n#include <boost/math/tools/stats.hpp>\n#include <boost/math/tools/test.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/type_traits/is_floating_point.hpp>\n#include <boost/array.hpp>\n#include \"functor.hpp\"\n\n#include \"test_beta_hooks.hpp\"\n#include \"handle_test_result.hpp\"\n#include \"table_type.hpp\"\n\n#ifndef SC_\n#define SC_(x) static_cast<typename table_type<T>::type>(BOOST_JOIN(x, L))\n#endif\n\ntemplate <class Real, class T>\nvoid test_inverses(const T& data)\n{\n   using namespace std;\n   typedef typename T::value_type row_type;\n   typedef Real                   value_type;\n\n   value_type precision = static_cast<value_type>(ldexp(1.0, 1-boost::math::policies::digits<value_type, boost::math::policies::policy<> >()/2)) * 100;\n   if(boost::math::policies::digits<value_type, boost::math::policies::policy<> >() < 50)\n      precision = 1;   // 1% or two decimal digits, all we can hope for when the input is truncated\n\n   for(unsigned i = 0; i < data.size(); ++i)\n   {\n      //\n      // These inverse tests are thrown off if the output of the\n      // incomplete beta is too close to 1: basically there is insuffient\n      // information left in the value we're using as input to the inverse\n      // to be able to get back to the original value.\n      //\n      if(Real(data[i][5]) == 0)\n         BOOST_CHECK_EQUAL(boost::math::ibeta_inv(Real(data[i][0]), Real(data[i][1]), Real(data[i][5])), value_type(0));\n      else if((1 - Real(data[i][5]) > 0.001) \n         && (fabs(Real(data[i][5])) > 2 * boost::math::tools::min_value<value_type>()) \n         && (fabs(Real(data[i][5])) > 2 * boost::math::tools::min_value<double>()))\n      {\n         value_type inv = boost::math::ibeta_inv(Real(data[i][0]), Real(data[i][1]), Real(data[i][5]));\n         BOOST_CHECK_CLOSE(Real(data[i][2]), inv, precision);\n      }\n      else if(1 == Real(data[i][5]))\n         BOOST_CHECK_EQUAL(boost::math::ibeta_inv(Real(data[i][0]), Real(data[i][1]), Real(data[i][5])), value_type(1));\n\n      if(Real(data[i][6]) == 0)\n         BOOST_CHECK_EQUAL(boost::math::ibetac_inv(Real(data[i][0]), Real(data[i][1]), Real(data[i][6])), value_type(1));\n      else if((1 - Real(data[i][6]) > 0.001) \n         && (fabs(Real(data[i][6])) > 2 * boost::math::tools::min_value<value_type>()) \n         && (fabs(Real(data[i][6])) > 2 * boost::math::tools::min_value<double>()))\n      {\n         value_type inv = boost::math::ibetac_inv(Real(data[i][0]), Real(data[i][1]), Real(data[i][6]));\n         BOOST_CHECK_CLOSE(Real(data[i][2]), inv, precision);\n      }\n      else if(Real(data[i][6]) == 1)\n         BOOST_CHECK_EQUAL(boost::math::ibetac_inv(Real(data[i][0]), Real(data[i][1]), Real(data[i][6])), value_type(0));\n   }\n}\n\ntemplate <class Real, class T>\nvoid test_inverses2(const T& data, const char* type_name, const char* test_name)\n{\n   typedef typename T::value_type row_type;\n   typedef Real                   value_type;\n\n   typedef value_type (*pg)(value_type, value_type, value_type);\n#if defined(BOOST_MATH_NO_DEDUCED_FUNCTION_POINTERS)\n   pg funcp = boost::math::ibeta_inv<value_type, value_type, value_type>;\n#else\n   pg funcp = boost::math::ibeta_inv;\n#endif\n\n   boost::math::tools::test_result<value_type> result;\n\n   std::cout << \"Testing \" << test_name << \" with type \" << type_name\n      << \"\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\";\n\n   //\n   // test ibeta_inv(T, T, T) against data:\n   //\n   result = boost::math::tools::test_hetero<Real>(\n      data,\n      bind_func<Real>(funcp, 0, 1, 2),\n      extract_result<Real>(3));\n   handle_test_result(result, data[result.worst()], result.worst(), type_name, \"boost::math::ibeta_inv\", test_name);\n   //\n   // test ibetac_inv(T, T, T) against data:\n   //\n#if defined(BOOST_MATH_NO_DEDUCED_FUNCTION_POINTERS)\n   funcp = boost::math::ibetac_inv<value_type, value_type, value_type>;\n#else\n   funcp = boost::math::ibetac_inv;\n#endif\n   result = boost::math::tools::test_hetero<Real>(\n      data,\n      bind_func<Real>(funcp, 0, 1, 2),\n      extract_result<Real>(4));\n   handle_test_result(result, data[result.worst()], result.worst(), type_name, \"boost::math::ibetac_inv\", test_name);\n}\n\n\ntemplate <class T>\nvoid test_beta(T, const char* name)\n{\n   (void)name;\n   //\n   // The actual test data is rather verbose, so it's in a separate file\n   //\n   // The contents are as follows, each row of data contains\n   // five items, input value a, input value b, integration limits x, beta(a, b, x) and ibeta(a, b, x):\n   //\n#if !defined(TEST_DATA) || (TEST_DATA == 1)\n#  include \"ibeta_small_data.ipp\"\n\n   test_inverses<T>(ibeta_small_data);\n#endif\n\n#if !defined(TEST_DATA) || (TEST_DATA == 2)\n#  include \"ibeta_data.ipp\"\n\n   test_inverses<T>(ibeta_data);\n#endif\n\n#if !defined(TEST_DATA) || (TEST_DATA == 3)\n#  include \"ibeta_large_data.ipp\"\n\n   test_inverses<T>(ibeta_large_data);\n#endif\n\n#if !defined(TEST_DATA) || (TEST_DATA == 4)\n#  include \"ibeta_inv_data.ipp\"\n\n   test_inverses2<T>(ibeta_inv_data, name, \"Inverse incomplete beta\");\n#endif\n}\n\ntemplate <class T>\nvoid test_spots(T)\n{\n   //\n   // basic sanity checks, tolerance is 100 epsilon expressed as a percentage:\n   //\n   T tolerance = boost::math::tools::epsilon<T>() * 10000;\n   BOOST_CHECK_CLOSE(\n      ::boost::math::ibeta_inv(\n         static_cast<T>(1),\n         static_cast<T>(2),\n         static_cast<T>(0.5)),\n      static_cast<T>(0.29289321881345247559915563789515096071516406231153L), tolerance);\n   BOOST_CHECK_CLOSE(\n      ::boost::math::ibeta_inv(\n         static_cast<T>(3),\n         static_cast<T>(0.5),\n         static_cast<T>(0.5)),\n      static_cast<T>(0.92096723292382700385142816696980724853063433975470L), tolerance);\n   BOOST_CHECK_CLOSE(\n      ::boost::math::ibeta_inv(\n         static_cast<T>(20.125),\n         static_cast<T>(0.5),\n         static_cast<T>(0.5)),\n      static_cast<T>(0.98862133312917003480022776106012775747685870929920L), tolerance);\n   BOOST_CHECK_CLOSE(\n      ::boost::math::ibeta_inv(\n         static_cast<T>(40),\n         static_cast<T>(80),\n         static_cast<T>(0.5)),\n      static_cast<T>(0.33240456430025026300937492802591128972548660643778L), tolerance);\n}\n\n", "meta": {"hexsha": "70807b8e6a9e09a9c8222a00047109274f3ab249", "size": 6596, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/libs/math/test/test_ibeta_inv.hpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2016-04-12T16:29:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-28T11:01:57.000Z", "max_issues_repo_path": "boost/libs/math/test/test_ibeta_inv.hpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-10-31T19:35:14.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-04T17:11:27.000Z", "max_forks_repo_path": "boost/libs/math/test/test_ibeta_inv.hpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-09-09T02:38:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-30T00:24:24.000Z", "avg_line_length": 36.4419889503, "max_line_length": 151, "alphanum_fraction": 0.6476652517, "num_tokens": 1863, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.689305616785446, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.47050190454966545}}
{"text": "#include <boost/test/unit_test.hpp>\n\n#include <boost/date_time/gregorian/gregorian.hpp>\n#include <boost/date_time/posix_time/posix_time.hpp>\n\n#include \"PeriodVal.h\"\n#include \"PatternScannerEngine.h\"\n#include \"SegmentConstraint.h\"\n#include \"SegmentValsCloseToLinearEq.h\"\n#include \"SegmentListConstraint.h\"\n#include \"SlopeIncreasesConstraint.h\"\n#include \"PatternMatchValidator.h\"\n#include \"EndWithinPercentOfStart.h\"\n#include \"PeriodValSegment.h\"\n#include \"DoubleBottomScanner.h\"\n#include \"TestHelper.h\"\n#include \"MultiPatternScanner.h\"\n\nusing namespace boost::posix_time;\nusing namespace boost::gregorian;\nusing namespace testHelper;\n\nBOOST_AUTO_TEST_CASE( DoubleBottomScanner_QCOR_20130819 )\n{\n\t// Test a full double-bottom scan for QCOR in 2013. This unit test is built up from\n\t// VScanner_QCOR_20130819_LHSofDoubleBottom and VScanner_QCOR_20130819_RHSofDoubleBottom, which\n\t// test the LHS and RHS of the double-bottom individually. The number of pattern matches\n\t// should therefore be the number of matches from VScanner_QCOR_20130819_LHSofDoubleBottom\n\t// multiplied times the number of matches from VScanner_QCOR_20130819_RHSofDoubleBottom.\n\n\tPeriodValSegmentPtr chartData = PeriodValSegment::readFromFile(\"./patternScan/QCOR_DoubleBottom_Weekly.csv\");\n\tgenPeriodValSegmentInfo(\"Double bottom segment data\",*chartData);\n\n\tDoubleBottomScanner scanner(DoubleRange(7.0,40.0)); // allow for a deeper depth than the default\n\tPatternMatchListPtr patternMatches = scanner.scanPatternMatches(chartData);\n\n\tverifyMatchList(\"Double bottom match\",patternMatches,1);\n\n\tverifyPatternMatch(\"Double bottom match\",\n            ptime(date(2013,8,26)),ptime(date(2014,2,10)),4,patternMatches->front());\n\n}\n\nBOOST_AUTO_TEST_CASE( DoubleBottom_Synthesized )\n{\n\tusing namespace boost::gregorian;\n\n\tTestPerValRangeList ranges;\n\tranges.push_back(TestPerValRange(4,100.0,92.0)); // initial 8% down-trend\n\tranges.push_back(TestPerValRange(3,92.5,98.0)); // up-trend falling short of down-trend\n\tranges.push_back(TestPerValRange(3,97.5,91.5)); // next down-trend, going below the initial down-trend\n\tranges.push_back(TestPerValRange(4,92.0,100.5)); // final uptrend, goes above start\n\tPeriodValSegmentPtr chartData = synthesizePeriodValSegment(date(2014,1,1),ranges);\n\n\tDoubleBottomScanner scanner;\n\tPatternMatchListPtr patternMatches = scanner.scanPatternMatches(chartData);\n\n    verifyMatchList(\"DoubleBottom_Synthesized\",patternMatches,2);\n\tverifyPatternMatch(\"DoubleBottom_Synthesized match\",\n            ptime(date(2014,1,1)),ptime(date(2014,1,13)),4,patternMatches->front());\n\n}\n\nBOOST_AUTO_TEST_CASE( DoubleBottom_Synthesized_RHSHigherLow )\n{\n\tusing namespace boost::gregorian;\n\n\tTestPerValRangeList ranges;\n\tranges.push_back(TestPerValRange(4,100.0,92.0)); // initial 8% down-trend\n\tranges.push_back(TestPerValRange(3,92.5,98.0)); // up-trend falling short of down-trend\n\tranges.push_back(TestPerValRange(3,97.5,92.5)); // next down-trend, *not* going below the initial down-trend\n\tranges.push_back(TestPerValRange(4,93.0,100.5)); // final uptrend, goes above start\n\tPeriodValSegmentPtr chartData = synthesizePeriodValSegment(date(2014,1,1),ranges);\n\n\tDoubleBottomScanner scanner;\n\tPatternMatchListPtr patternMatches = scanner.scanPatternMatches(chartData);\n\n\tBOOST_TEST_MESSAGE(\"Should return 0 matches, since the lowest low on the RHS is not lower than the LHS\");\n\tverifyMatchList(\"DoubleBottom_Synthesized_RHSHigherLow\",patternMatches,0);\n\n}\n\nBOOST_AUTO_TEST_CASE( DoubleBottom_Synthesized_MinMaxDepth )\n{\n\tusing namespace boost::gregorian;\n\n\tTestPerValRangeList ranges;\n\tranges.push_back(TestPerValRange(4,100.0,92.0)); // initial 8% down-trend\n\tranges.push_back(TestPerValRange(3,92.5,98.0)); // up-trend falling short of down-trend\n\tranges.push_back(TestPerValRange(3,97.5,91.5)); // next down-trend, going below the initial down-trend\n\tranges.push_back(TestPerValRange(4,92.0,100.5)); // final uptrend, goes above start\n\tPeriodValSegmentPtr chartData = synthesizePeriodValSegment(date(2014,1,1),ranges);\n\n\tDoubleBottomScanner scanner(DoubleRange(9.0,30.0)); // Require at least a 10% depth to trigger depth constraints\n\tPatternMatchListPtr patternMatches = scanner.scanPatternMatches(chartData);\n\n\tBOOST_TEST_MESSAGE(\"Should return 0 matches, since the depth is not greater than 9%\");\n\tverifyMatchList(\"DoubleBottom_Synthesized_ShallowDepth\",patternMatches,0);\n\n\tDoubleBottomScanner scannerMaxDepth(DoubleRange(4.0,7.0)); // Require at least a 10% depth to trigger depth constraints\n\tpatternMatches = scanner.scanPatternMatches(chartData);\n\n\tBOOST_TEST_MESSAGE(\"Should return 0 matches, since the depth is greater than 7%\");\n\tverifyMatchList(\"DoubleBottom_Synthesized_ShallowDepth\",patternMatches,0);\n\n\n\n}\n\n\nBOOST_AUTO_TEST_CASE( DoubleBottomScanner_GBX )\n{\n    PeriodValSegmentPtr chartData = PeriodValSegment::readFromFile(\"./patternScan/GBX_Daily.csv\");\n    genPeriodValSegmentInfo(\"Double bottom segment data\",*chartData);\n\n    MultiPatternScanner scanner(PatternScannerPtr(new DoubleBottomScanner(DoubleRange(7.0,40.0))));\n\n    PatternMatchListPtr patternMatches = scanner.scanPatternMatches(chartData);\n\n    // Shouldn't match any double bottoms. The potential double bottom in this pattern data\n    // has a middle which goes higher than the beginning of the pattern, and is thus mal-formed.\n    verifyMatchList(\"Double bottom match\",patternMatches,0);\n\n}\n\n\n\n", "meta": {"hexsha": "6427ee44abe1e69fb0d30b92841b42a7525607fb", "size": 5362, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/patternScan/DoubleBottom.cpp", "max_stars_repo_name": "sroehling/ChartPatternRecognitionLib", "max_stars_repo_head_hexsha": "d9bd25c0fc5a8942bb98c74c42ab52db80f680c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2019-07-15T19:10:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-14T12:16:18.000Z", "max_issues_repo_path": "test/patternScan/DoubleBottom.cpp", "max_issues_repo_name": "sroehling/ChartPatternRecognitionLib", "max_issues_repo_head_hexsha": "d9bd25c0fc5a8942bb98c74c42ab52db80f680c1", "max_issues_repo_licenses": ["MIT"], "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/patternScan/DoubleBottom.cpp", "max_forks_repo_name": "sroehling/ChartPatternRecognitionLib", "max_forks_repo_head_hexsha": "d9bd25c0fc5a8942bb98c74c42ab52db80f680c1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-05-23T03:25:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-19T16:41:44.000Z", "avg_line_length": 41.890625, "max_line_length": 120, "alphanum_fraction": 0.7952256621, "num_tokens": 1382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.689305616785446, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.47050190454966545}}
{"text": "#include <iostream>\n#include <boost/algorithm/string.hpp>\n#include <string>\n#include <sstream>\n#include <stdlib.h>\n#include <fstream>\n#include <vector>\n#include <cmath>\n\n//#include <system.h>\n\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include \"opencv2/imgproc/imgproc.hpp\"\n#include \"opencv2/opencv.hpp\"\n\nusing namespace cv;\nusing namespace std;\n\n/* Keep the webcam from locking up when you interrupt a frame capture */\nvolatile int quit_signal=0;\n#ifdef __unix__\n#include <signal.h>\nextern \"C\" void quit_signal_handler(int signum) {\n if (quit_signal!=0) exit(0); // just exit already\n quit_signal=1;\n printf(\"Will quit at next camera frame (repeat to kill now)\\n\");\n}\n#endif\n\nint capture_video_spacebar(VideoCapture cap){\n\tunsigned int count = 0;\n\tnamedWindow(\"Screen\", CV_WINDOW_NORMAL);\n\tchar setting = 'a';\n\n\tfor(;;){  // Loop through, getting new images from the camera.\n\t\t//cout << \"Setting \" << setting + 'a' << endl;\n\t\tMat frame;\n\t\tcap >> frame; // get a new frame from camera\n\t\tif (quit_signal) exit(0); // exit cleanly on interrupt\n\n\t\timshow(\"Screen\", frame);  // Show the image on the screen\n\n\t\tchar key = waitKey(30);\n\t\tif (key == ' '){\n\t\t\t//cout << \"setting is \" << key + 0<< endl;\n\t\t\tcout << \"space bar\\n\";\n\t\t\tostringstream name;\n\t\t\tname << \"calibrate_webcam/img\" << count++ << \".jpg\";\n\t\t\tstring filename = name.str();\n\t\t\timwrite(filename, frame);\n\t\t\twaitKey(1000);\n\t\t}else if(key == 'x'){\n\t\t\treturn count;\n\t\t}\n\t}\n}\n\nvoid calibrate(int numImages, int numCornersHorizontal, int numCornersVertical, const char* intrinsic_name, const char* distortion_name){\n\tofstream intrinsicFile;\n\tintrinsicFile.open(intrinsic_name);\n\tofstream distortionParams;\n\tdistortionParams.open(distortion_name);\n\n// Task 2\n\tint numSquares = numCornersHorizontal * numCornersVertical;\n\tSize boardSize = Size(numCornersHorizontal, numCornersVertical);\n\n\tvector<vector<Point3f> > object_points;\n\tvector<vector<Point2f> > image_points;\n\tMat image;\n\n\tvector<Point3f> obj;\n\tfor(int j=0;j<numSquares;j++){\n\t\tobj.push_back(Point3f( j/numCornersHorizontal , j%numCornersHorizontal , 0.0f));\n\t}\n\n\tfor (int i = 0; i < numImages; i++){\n\t\tvector<Point2f> pointBuf;\n\t\tostringstream name;\n\t\tname << \"calibrate_webcam/img\" << i << \".jpg\";\n\t\tstring filename = name.str();\n\t\timage = imread(filename, CV_LOAD_IMAGE_GRAYSCALE);\n\n\t// Find chessboard inner corners, 10 corners per row/7 per column\n\t\tbool found = findChessboardCorners(image, boardSize, pointBuf, CV_CALIB_CB_ADAPTIVE_THRESH | CV_CALIB_CB_FILTER_QUADS);\n\t\t\n\t\tif(found){\n\t\t// Find subpixels with the criteria\n\t\t\tTermCriteria criteria = TermCriteria( CV_TERMCRIT_EPS + CV_TERMCRIT_ITER, 40, 0.01 );\n\t\t\tcornerSubPix(image, pointBuf, Size(10,10), Size(-1, -1), criteria);\n\t\t\tdrawChessboardCorners(image, cvSize(10,7), pointBuf, found);\n\n\t\t\tcvtColor(image, image, CV_GRAY2BGR);\n\t\t\timage_points.push_back(pointBuf);\n\t\t\tobject_points.push_back(obj);\n\t\t// Draw the corners on a colored image\n\t/*\t// Write the image\n\t\t\t//imwrite(\"Task_1.jpg\", image[i]);\n\n\t\t\t//imshow(\"Screen\", image[i]);\n\t\t\t//waitKey(100);*/\n\t\t\tstd::cout << i + 1 << \" processed \" << pointBuf[0] << \"\\n\";\n\t\t}\n\t}\n\n\tMat intrinsic = Mat(3,3, CV_32FC1);\n\tMat distCoeffs;\n\tSize imageSize = image.size();\n\tvector<Mat> rvecs, tvecs;\n\tintrinsic.ptr<double>(0)[0] = 1;\n\tintrinsic.ptr<double>(1)[1] = 1;\n\n\tcalibrateCamera(object_points, image_points, imageSize, intrinsic, distCoeffs, rvecs, tvecs);\n\tstd::cout << \"Matrix is \" << intrinsic << std::endl << distCoeffs << std::endl;\n\n\tfor(int i = 0; i < 3; i++){\n\t\tfor(int j =0; j < 3; j++){\n\t\t\tintrinsicFile << intrinsic.at<double>(i, j) << \" \";\n\t\t}\n\t}\n\n\tfor(int k = 0; k < 5; k++)\n\t\tdistortionParams << distCoeffs.at<double>(k) << \" \";\n\t\n//\tintrinsicFile << intrinsic;\n//\tdistortionParams << distCoeffs;\n\n\tintrinsicFile.close();\n\tdistortionParams.close();\n\treturn;\n}\n\nint main(int argc, char** argv){\n\tVideoCapture cap(0); // open the default camera\n\tif(!cap.isOpened()){ // check if we succeeded\n\t\treturn -1;\n\t}\n\t#ifdef __unix__\n\t   signal(SIGINT,quit_signal_handler); // listen for ctrl-C\n\t#endif\n\n\tint count = capture_video_spacebar(cap);\n\n\tint cornersHoriz = 9; \n\tint cornersVert = 7;\n\tcalibrate(count, cornersHoriz, cornersVert, \"intrinsic_webcam.txt\", \"distortion_webcam.txt\");\n\t\n\n// the camera will be deinitialized automatically in VideoCapture destructor\n\nreturn 0;\n}\n", "meta": {"hexsha": "503d14dc7d2e927241362d848ed7f863f7754d8d", "size": 4337, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "calibration/calibrate.cpp", "max_stars_repo_name": "speedyswimmer1000/ueyeROS", "max_stars_repo_head_hexsha": "7b18614c688801dd7acfdfe413c7bec5fdc114c0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "calibration/calibrate.cpp", "max_issues_repo_name": "speedyswimmer1000/ueyeROS", "max_issues_repo_head_hexsha": "7b18614c688801dd7acfdfe413c7bec5fdc114c0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "calibration/calibrate.cpp", "max_forks_repo_name": "speedyswimmer1000/ueyeROS", "max_forks_repo_head_hexsha": "7b18614c688801dd7acfdfe413c7bec5fdc114c0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-10-30T09:11:55.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-30T09:11:55.000Z", "avg_line_length": 28.1623376623, "max_line_length": 137, "alphanum_fraction": 0.6935669818, "num_tokens": 1217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737214979745, "lm_q2_score": 0.6893056040203136, "lm_q1q2_score": 0.4705018913855546}}
{"text": "//          Copyright Gavin Band 2008 - 2012.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef CORE_ASCENT_DIRECTION_PICKER_HPP\n#define CORE_ASCENT_DIRECTION_PICKER_HPP\n\n#include <iostream>\n#include <boost/noncopyable.hpp>\n#include <Eigen/Core>\n#include <Eigen/Cholesky>\n#include <Eigen/Eigenvalues>\n#include \"integration/ModifiedCholesky.hpp\"\n\n// #define DEBUG_ASCENT_DIRECTION_PICKER 1\n\nnamespace integration {\n\ttemplate< typename Function >\n\tstruct CholeskyOrEigenvalueSolver: public boost::noncopyable {\n\tpublic:\n\t\ttypedef Eigen::VectorXd Vector ;\n\t\ttypedef Eigen::MatrixXd Matrix ;\n\t\t\n\tpublic:\n\t\tCholeskyOrEigenvalueSolver(\n\t\t\tdouble const delta = -0.1\n\t\t):\n\t\t\tm_delta( delta )\n\t\t{\n\t\t\tassert( delta < 0 ) ;\n\t\t}\n\n\t\tvoid set_delta( double const delta ) {\n\t\t\tassert( delta < 0 ) ;\n\t\t\tm_delta = delta ;\n\t\t}\n\t\t\n\t\tVector compute( Function& function, Vector const& point ) {\n\t\t\tfunction.evaluate_at( point, 2 ) ;\n\t\t\tMatrix const matrix = function.get_value_of_second_derivative() ;\n\t\t\tVector const v = -function.get_value_of_first_derivative() ;\n\t\t\tm_cholesky_solver.compute( matrix ) ;\n\t\t\tif( m_cholesky_solver.info() == Eigen::Success && m_cholesky_solver.vectorD().array().maxCoeff() < 0 ) {\n\t\t\t\treturn m_cholesky_solver.solve( v ) ;\n\t\t\t} else {\n\t\t\t\tm_eigen_solver.compute( matrix ) ;\n\t\t\t\tif( m_eigen_solver.info() == Eigen::NoConvergence ) {\n\t\t\t\t\tthrow NumericalError( \"integration::CholeskyOrEigenvalueSolver::solve()\", \"Eigenvalue decomposition did not converge\" ) ;\n\t\t\t\t} \n\t\t\t\n\t\t\t\tm_d = m_eigen_solver.eigenvalues() ;\n\t\t\t\tfor( int i = 0; i < m_d.size(); ++i ) {\n\t\t\t\t\tif( m_d(i) > m_delta ) {\n\t\t\t\t\t\tm_d(i) = m_delta ;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tm_d = m_d.array().inverse() ;\n\t\t\t\t\n\t\t\t\treturn (\n\t\t\t\t\tm_eigen_solver.eigenvectors() * m_d.asDiagonal() * m_eigen_solver.eigenvectors().transpose()\n\t\t\t\t) * v ;\n\t\t\t}\n\t\t}\n\n\tprivate:\n\t\tdouble m_delta ;\n\t\tEigen::LDLT< Matrix > m_cholesky_solver ;\n\t\tEigen::SelfAdjointEigenSolver< Matrix > m_eigen_solver ;\n\t\tEigen::VectorXd m_d ;\n\t} ;\n\t\n}\n\n#endif\n", "meta": {"hexsha": "c46a46903937dfe6698a0fee1a42d71921935435", "size": 2108, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "integration/include/integration/AscentDirectionPicker.hpp", "max_stars_repo_name": "gavinband/bingwa", "max_stars_repo_head_hexsha": "d52e166b3bb6bc32cd32ba63bf8a4a147275eca1", "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": "integration/include/integration/AscentDirectionPicker.hpp", "max_issues_repo_name": "gavinband/bingwa", "max_issues_repo_head_hexsha": "d52e166b3bb6bc32cd32ba63bf8a4a147275eca1", "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": "integration/include/integration/AscentDirectionPicker.hpp", "max_forks_repo_name": "gavinband/qctool", "max_forks_repo_head_hexsha": "8d8adb45151c91f953fe4a9af00498073b1132ba", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7368421053, "max_line_length": 126, "alphanum_fraction": 0.6816888046, "num_tokens": 593, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430645886584, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.47044237995687116}}
{"text": "///////////////////////////////////////////////////////////////////////////////\r\n// weighted_tail_quantile.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_QUANTILE_HPP_DE_01_01_2006\r\n#define BOOST_ACCUMULATORS_STATISTICS_WEIGHTED_TAIL_QUANTILE_HPP_DE_01_01_2006\r\n\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/mpl/if.hpp>\r\n#include <boost/type_traits/is_same.hpp>\r\n#include <boost/accumulators/numeric/functional.hpp>\r\n#include <boost/accumulators/framework/depends_on.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_quantile.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 { namespace accumulators\r\n{\r\n\r\nnamespace impl\r\n{\r\n    ///////////////////////////////////////////////////////////////////////////////\r\n    // weighted_tail_quantile_impl\r\n    //  Tail quantile estimation based on order statistics of weighted samples\r\n    /**\r\n        @brief Tail quantile estimation based on order statistics of weighted samples (for both left and right tails)\r\n\r\n        An estimator \\f$\\hat{q}\\f$ of tail quantiles with level \\f$\\alpha\\f$ based on order statistics\r\n        \\f$X_{1:n} \\leq X_{2:n} \\leq\\dots\\leq X_{n:n}\\f$ of weighted samples are given by \\f$X_{\\lambda:n}\\f$ (left tail)\r\n        and \\f$X_{\\rho:n}\\f$ (right tail), where\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        and\r\n\r\n            \\f[\r\n                \\rho = \\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        \\f$n\\f$ being the number of samples and \\f$\\bar{w}_n\\f$ the sum of all weights.\r\n\r\n        @param quantile_probability\r\n    */\r\n    template<typename Sample, typename Weight, typename LeftRight>\r\n    struct weighted_tail_quantile_impl\r\n      : accumulator_base\r\n    {\r\n        typedef typename numeric::functional::average<Weight, std::size_t>::result_type float_type;\r\n        // for boost::result_of\r\n        typedef Sample result_type;\r\n\r\n        weighted_tail_quantile_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<result_type>::has_quiet_NaN)\r\n                    {\r\n                        return std::numeric_limits<result_type>::quiet_NaN();\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                        return Sample(0);\r\n                    }\r\n                }\r\n            }\r\n\r\n            // Note that the cached samples of the left are sorted in ascending order,\r\n            // whereas the samples of the right tail are sorted in descending order\r\n            return *(boost::begin(tail(args)) + n - 1);\r\n        }\r\n    };\r\n} // namespace impl\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// tag::weighted_tail_quantile<>\r\n//\r\nnamespace tag\r\n{\r\n    template<typename LeftRight>\r\n    struct weighted_tail_quantile\r\n      : depends_on<sum_of_weights, tail_weights<LeftRight> >\r\n    {\r\n        /// INTERNAL ONLY\r\n        typedef accumulators::impl::weighted_tail_quantile_impl<mpl::_1, mpl::_2, LeftRight> impl;\r\n    };\r\n}\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// extract::weighted_tail_quantile\r\n//\r\nnamespace extract\r\n{\r\n    extractor<tag::quantile> const weighted_tail_quantile = {};\r\n\r\n    BOOST_ACCUMULATORS_IGNORE_GLOBAL(weighted_tail_quantile)\r\n}\r\n\r\nusing extract::weighted_tail_quantile;\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": "86ea6106b40d77a255ac98e842f4feca9133a3ce", "size": 5284, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "master/core/third/boost/accumulators/statistics/weighted_tail_quantile.hpp", "max_stars_repo_name": "importlib/klib", "max_stars_repo_head_hexsha": "a59837857689d0e60d3df6d2ebd12c3160efa794", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 460.0, "max_stars_repo_stars_event_min_datetime": "2016-01-13T12:49:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-20T04:10:40.000Z", "max_issues_repo_path": "master/core/third/boost/accumulators/statistics/weighted_tail_quantile.hpp", "max_issues_repo_name": "isuhao/klib", "max_issues_repo_head_hexsha": "a59837857689d0e60d3df6d2ebd12c3160efa794", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 197.0, "max_issues_repo_issues_event_min_datetime": "2017-07-06T16:53:59.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-31T17:57:51.000Z", "max_forks_repo_path": "master/core/third/boost/accumulators/statistics/weighted_tail_quantile.hpp", "max_forks_repo_name": "isuhao/klib", "max_forks_repo_head_hexsha": "a59837857689d0e60d3df6d2ebd12c3160efa794", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 148.0, "max_forks_repo_forks_event_min_datetime": "2016-01-17T03:16:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T12:20:36.000Z", "avg_line_length": 35.9455782313, "max_line_length": 135, "alphanum_fraction": 0.5732399697, "num_tokens": 1163, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234877, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.47044237522202953}}
{"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#include<numeric>\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\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\nvoid detect_3d_cuboid::detect_cuboid(const cv::Mat& rgb_img, const Matrix4d& transToWolrd, const MatrixXd& obj_bbox_coors,\n\t\t\t\t     MatrixXd all_lines_raw, std::vector<ObjectSet>& all_object_cuboids)\n{\n      set_cam_pose(transToWolrd);\n      cam_pose_raw = cam_pose;\n      \n      cv::Mat gray_img; \n      if (rgb_img.channels()==3)\n\t  cv::cvtColor(rgb_img, gray_img, CV_BGR2GRAY);\n      else\n\t  gray_img = rgb_img;\n      \n      int img_width = rgb_img.cols;  int img_height = rgb_img.rows;\n\n      int num_2d_objs = obj_bbox_coors.rows();\n      all_object_cuboids.resize(num_2d_objs);\n\n      vector<bool> all_configs;all_configs.push_back(consider_config_1);all_configs.push_back(consider_config_2);\n      \n      // parameters for cuboid generation\n      double vp12_edge_angle_thre = 15; double vp3_edge_angle_thre = 10;  // 10  10  parameters\n      double shorted_edge_thre = 20;  // if box edge are too short. box might be too thin. most possibly wrong.\n      bool reweight_edge_distance = true;  // if want to compare with all configurations. we need to reweight\n      \n      // parameters for proposal scoring\n      bool whether_normalize_two_errors = true; double weight_vp_angle = 0.8; double weight_skew_error = 1.5; \n      // if also consider config2, need to weight two erros, in order to compare two configurations\n\n      \n      align_left_right_edges(all_lines_raw); // this should be guaranteed when detecting edges\n      if(whether_plot_detail_images)\n      {\n\t  cv::Mat output_img;  plot_image_with_edges(rgb_img, output_img, all_lines_raw, cv::Scalar(255,0,0));\n\t  cv::imshow(\"Raw detected Edges\", output_img);\t //cv::waitKey(0);\n      }\n      \n      // find ground-wall boundary edges\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      Vector4d ground_plane_sensor = cam_pose.transToWolrd.transpose()*ground_plane_world;\n      \n\n//       int object_id=1;\n      for (int object_id=0;object_id<num_2d_objs;object_id++)\n      {\n// \t  std::cout<<\"object id  \"<<object_id<<std::endl;\n\t  ca::Profiler::tictoc(\"One 3D object total time\"); \n\t  int left_x_raw = obj_bbox_coors(object_id,0); int top_y_raw = obj_bbox_coors(object_id,1); \n\t  int obj_width_raw = obj_bbox_coors(object_id,2); int obj_height_raw = obj_bbox_coors(object_id,3);\n\t  int right_x_raw = left_x_raw+obj_bbox_coors(object_id,2); int down_y_raw = top_y_raw + obj_height_raw;\n\n\t  std::vector<int> down_expand_sample_all;\n\t  down_expand_sample_all.push_back(0);\n\t  if (whether_sample_bbox_height)  // 2D object detection might not be accurate\n\t  {\n\t      int down_expand_sample_ranges = max(min(20, obj_height_raw-90),20);\n\t      down_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      if (down_expand_sample_ranges>10)  // if expand large margin, give more samples.\n\t\t  down_expand_sample_all.push_back(round(down_expand_sample_ranges/2));\n\t      down_expand_sample_all.push_back(down_expand_sample_ranges);\n\t  }\n\t  \n\t  // NOTE later if in video, could use previous object yaw..., also reduce search range\n\t  double 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  std::vector<double> obj_yaw_samples; linespace<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\n\t  MatrixXd all_configs_errors(400,9); MatrixXd all_box_corners_2ds(800,8); // initialize a large eigen matrix\n\t  int valid_config_number_all_height=0; // all valid objects of all height samples\n\t  ObjectSet raw_obj_proposals;raw_obj_proposals.reserve(100);\n// \t    int sample_down_expan_id=1;\n\t  for (int sample_down_expan_id=0;sample_down_expan_id<down_expand_sample_all.size();sample_down_expan_id++)\n\t  {\n\t      int down_expand_sample = down_expand_sample_all[sample_down_expan_id];\n\t      int obj_height_expan = obj_height_raw + down_expand_sample;\n\t      int down_y_expan = top_y_raw + obj_height_expan; double obj_diaglength_expan = sqrt(obj_width_raw*obj_width_raw+obj_height_expan*obj_height_expan);\n\t      \n\t      // sample points on the top edges, if edge is too large, give more samples. give at least 10 samples for all edges. for small object, object pose changes lots    \n\t      int top_sample_resolution = round(min(20,obj_width_raw/10 )); //  25 pixels\n\t      std::vector<int> top_x_samples; linespace<int>(left_x_raw+5, right_x_raw-5, top_sample_resolution, top_x_samples);\n\t      MatrixXd sample_top_pts(2,top_x_samples.size());\n\t      for (int ii=0;ii<top_x_samples.size();ii++)\n\t      {\n\t\t  sample_top_pts(0,ii)=top_x_samples[ii];\n\t\t  sample_top_pts(1,ii)=top_y_raw;\n\t      }\n\t      \n\t      // expand some small margin for distance map  [10 20]\n\t      int distmap_expand_wid = min(max(min(20, obj_width_raw-100),10),max(min(20, obj_height_expan-100),10));\n\t      int left_x_expan_distmap = max(0,left_x_raw-distmap_expand_wid); int right_x_expan_distmap = min(img_width-1,right_x_raw+distmap_expand_wid);\n\t      int top_y_expan_distmap = max(0,top_y_raw-distmap_expand_wid); int down_y_expan_distmap = min(img_height-1,down_y_expan+distmap_expand_wid);\n\t      int height_expan_distmap = down_y_expan_distmap - top_y_expan_distmap; int width_expan_distmap = right_x_expan_distmap - left_x_expan_distmap;\n\t      Vector2d expan_distmap_lefttop = Vector2d(left_x_expan_distmap, top_y_expan_distmap);\n\t      Vector2d expan_distmap_rightbottom = Vector2d(right_x_expan_distmap, down_y_expan_distmap);\n\t      \n\t      // find edges inside the object bounding box\n\t      MatrixXd 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      int inside_obj_edge_num = 0;\n\t      for (int edge_id=0;edge_id<all_lines_raw.rows();edge_id++)\n\t\tif (check_inside_box(all_lines_raw.row(edge_id).head<2>(),expan_distmap_lefttop, expan_distmap_rightbottom ))\n\t\t  if (check_inside_box(all_lines_raw.row(edge_id).tail<2>(),expan_distmap_lefttop, expan_distmap_rightbottom ))\n\t\t    {\n\t\t\tall_lines_inside_object.row(inside_obj_edge_num) = all_lines_raw.row(edge_id);\n\t\t\tinside_obj_edge_num++;\n\t\t    }\n\t      \n\t      // merge edges and remove short lines, after finding object edges.  edge merge in small regions should be faster than all.\n\t      double pre_merge_dist_thre = 20; double pre_merge_angle_thre = 5; double edge_length_threshold=30;\n\t      MatrixXd all_lines_merge_inobj; \n\t      merge_break_lines(all_lines_inside_object.topRows(inside_obj_edge_num),all_lines_merge_inobj,pre_merge_dist_thre,\n\t\t\t\tpre_merge_angle_thre,edge_length_threshold);\n\n\t      // compute edge angels and middle points\n\t      VectorXd lines_inobj_angles(all_lines_merge_inobj.rows());\n\t      MatrixXd edge_mid_pts(all_lines_merge_inobj.rows(),2);\n\t      for (int i=0;i<all_lines_merge_inobj.rows();i++)\n\t      {\n\t\t  lines_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  edge_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      }\n\n\t      // TODO could canny or distance map outside sampling height to speed up!!!!   Then only need to compute canny onces.\n\t      // detect canny edges and compute distance transform  NOTE opencv canny maybe different from matlab. but roughly same\n\t      cv::Rect object_bbox = cv::Rect(left_x_expan_distmap,top_y_expan_distmap,width_expan_distmap,height_expan_distmap);//\n\t      cv::Mat im_canny; cv::Canny(gray_img(object_bbox),im_canny,80,200); // low thre, high thre    im_canny 0 or 255   [80 200  40 100]\n\t      cv::Mat dist_map; cv::distanceTransform(255-im_canny,dist_map,CV_DIST_L2,3); // dist_map is float datatype\n\n\t      if (whether_plot_detail_images){\n\t\t  cv::imshow(\"im_canny\",im_canny);\n\t\t  cv::Mat dist_map_img;cv::normalize(dist_map, dist_map_img, 0.0, 1.0, cv::NORM_MINMAX);\n\t\t  cv::imshow(\"normalized distance map\", dist_map_img);cv::waitKey();\n\t      }\n\n\t      // Generate cuboids\n\t      MatrixXd all_configs_error_one_objH(200,9);    MatrixXd all_box_corners_2d_one_objH(400,8); \n\t      int valid_config_number_one_objH=0;\n\t      \n\t      std::vector<double> cam_roll_samples; std::vector<double> cam_pitch_samples;\n\t      if (whether_sample_cam_roll_pitch)\n\t      {\n\t\t  linespace<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  linespace<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      }\n\t      else\n\t      {\n\t\t  cam_roll_samples.push_back(cam_pose_raw.euler_angle(0));cam_pitch_samples.push_back(cam_pose_raw.euler_angle(1));\n\t      }\n\t      // different from matlab. first for loop yaw, then for configurations.\n// \t      int obj_yaw_id=8;\n\t      for (int cam_roll_id=0;cam_roll_id<cam_roll_samples.size();cam_roll_id++)\n\t      for (int cam_pitch_id=0;cam_pitch_id<cam_pitch_samples.size();cam_pitch_id++)\n\t      for (int obj_yaw_id=0;obj_yaw_id<obj_yaw_samples.size();obj_yaw_id++)\n\t      {\n\t\t  if (whether_sample_cam_roll_pitch)\n\t\t  {\n\t\t      Matrix4d transToWolrd_new = transToWolrd;\n\t\t      transToWolrd_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      set_cam_pose(transToWolrd_new);\n\t\t      ground_plane_sensor = cam_pose.transToWolrd.transpose()*ground_plane_world;\n\t\t  }\n\t\t\n\t\t  double obj_yaw_esti=obj_yaw_samples[obj_yaw_id];\n\t\t  \n\t\t  Vector2d vp_1, vp_2, vp_3;\n\t\t  getVanishingPoints(cam_pose.KinvR, obj_yaw_esti, vp_1,vp_2,vp_3); // for object x y z  axis\n\n\t\t  MatrixXd all_vps(3,2);all_vps.row(0)=vp_1;all_vps.row(1)=vp_2;all_vps.row(2)=vp_3;\n// \t\t  std::cout<<\"obj_yaw_esti  \"<<obj_yaw_esti<<\"  \"<<obj_yaw_id<<std::endl;\n\t\t  MatrixXd all_vp_bound_edge_angles = VP_support_edge_infos(all_vps, edge_mid_pts,lines_inobj_angles,\n\t\t\t\t\t\t\t\t\t    Vector2d(vp12_edge_angle_thre,vp3_edge_angle_thre));\n// \t\t  int sample_top_pt_id=15;\n\t\t  for (int sample_top_pt_id=0;sample_top_pt_id<sample_top_pts.cols();sample_top_pt_id++)\n\t\t  {\n// \t\t      std::cout<<\"sample_top_pt_id \"<<sample_top_pt_id<<std::endl;\n\t\t      Vector2d corner_1_top = sample_top_pts.col(sample_top_pt_id);\n\t\t      bool config_good = true;\n\t\t      int vp_1_position = 0;  // 0 initial as fail,  1  on left   2 on right\n\t\t      Vector2d corner_2_top = seg_hit_boundary(vp_1,corner_1_top,Vector4d(right_x_raw, top_y_raw, right_x_raw, down_y_expan));\n\t\t      if (corner_2_top(0)==-1){  // vp1-corner1 doesn't hit the right boundary. check whether hit left\n\t\t\t  corner_2_top = seg_hit_boundary(vp_1,corner_1_top,Vector4d(left_x_raw, top_y_raw, left_x_raw, down_y_expan));\n\t\t\t  if (corner_2_top(0)!=-1) // vp1-corner1 hit the left boundary   vp1 on the right\n\t\t\t      vp_1_position = 2;\n\t\t      }\n\t\t      else    // vp1-corner1 hit the right boundary   vp1 on the left\n\t\t\t  vp_1_position = 1;\n\t\t      \n\t\t      config_good = vp_1_position>0;\n\t\t      if (!config_good){\n\t\t\t  if (print_details) printf(\"Configuration fails at corner 2, outside segment\\n\"); \n\t\t\t  continue;\n\t\t      }\n\t\t      if ((corner_1_top-corner_2_top).norm()<shorted_edge_thre){\n\t\t\t  if (print_details) printf(\"Configuration fails at edge 1-2, too short\\n\"); \n\t\t\t  continue;\n\t\t      }\n// \t\t      cout<<\"corner_1/2   \"<<corner_1_top.transpose()<<\"   \"<<corner_2_top.transpose()<<endl;\n// \t\t      int config_ind=0; // have to consider config now.\n\t\t      for (int config_id=1;config_id<3;config_id++)  // configuration one or two of matlab version\n\t\t      {\n\t\t\t  if (!all_configs[config_id-1])  \n\t\t\t      continue;\n\t\t\t  Vector2d corner_3_top,corner_4_top;\n\t\t\t  if (config_id==1)\n\t\t\t  {\n\t\t\t      if (vp_1_position==1)   // then vp2 hit the left boundary\n\t\t\t\t  corner_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      else  // or, then vp2 hit the right boundary\n\t\t\t\t  corner_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      if (corner_4_top(1)==-1){\n\t\t\t\t  config_good = false;\n\t\t\t\t  if (print_details)  printf(\"Configuration %d fails at corner 4, outside segment\\n\",config_id); \n\t\t\t\t  continue;\n\t\t\t      }\n\t\t\t      if ((corner_1_top-corner_4_top).norm()<shorted_edge_thre){\n\t\t\t\t  if (print_details) printf(\"Configuration %d fails at edge 1-4, too short\\n\",config_id);\n\t\t\t\t  continue;\n\t\t\t      }\n\t\t\t      // compute the last point in the top face\n\t\t\t      corner_3_top=lineSegmentIntersect(vp_2,corner_2_top,vp_1,corner_4_top,true);\n\t\t\t      if (!check_inside_box( corner_3_top, Vector2d(left_x_raw,top_y_raw), Vector2d(right_x_raw, down_y_expan))){    // check inside boundary. otherwise edge visibility might be wrong\n\t\t\t\t  config_good=false;  \n\t\t\t\t  if (print_details) printf(\"Configuration %d fails at corner 3, outside box\\n\",config_id); \n\t\t\t\t  continue;\n\t\t\t      }\n\t\t\t      if ( ((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  if (print_details) printf(\"Configuration %d fails at edge 3-4/3-2, too short\\n\",config_id); \n\t\t\t\t  continue;\n\t\t\t      }\n// \t\t\t      cout<<\"corner_3/4   \"<<corner_3_top.transpose()<<\"   \"<<corner_4_top.transpose()<<endl;\n\t\t\t  }\n\t\t\t  if (config_id==2)\n\t\t\t  {\n\t\t\t      if (vp_1_position==1)   // then vp2 hit the left boundary\n\t\t\t\t  corner_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      else  // or, then vp2 hit the right boundary\n\t\t\t\t  corner_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      if (corner_3_top(1)==-1){\n\t\t\t\t  config_good = false; \n\t\t\t\t  if (print_details)  printf(\"Configuration %d fails at corner 3, outside segment\\n\",config_id); \n\t\t\t\t  continue;\n\t\t\t      }\n\t\t\t      if ((corner_2_top-corner_3_top).norm()<shorted_edge_thre){\n\t\t\t\t  if (print_details) printf(\"Configuration %d fails at edge 2-3, too short\\n\",config_id);\n\t\t\t\t  continue;\n\t\t\t      }\n\t\t\t      // compute the last point in the top face\n\t\t\t      corner_4_top=lineSegmentIntersect(vp_1,corner_3_top,vp_2,corner_1_top,true);\n\t\t\t      if (!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  config_good=false;\n\t\t\t\t  if (print_details) printf(\"Configuration %d fails at corner 4, outside box\\n\",config_id); \n\t\t\t\t  continue;\n\t\t\t      }\n\t\t\t      if ( ((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  if (print_details) printf(\"Configuration %d fails at edge 3-4/4-1, too short\\n\",config_id); \n\t\t\t\t  continue;\n\t\t\t      }\n// \t\t\t      cout<<\"corner_3/4   \"<<corner_3_top.transpose()<<\"   \"<<corner_4_top.transpose()<<endl;\n\t\t\t  }\n\t\t\t  // compute first bottom points    computing bottom points is the same for config 1,2\n\t\t\t  Vector2d 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  if (corner_5_down(1)==-1){\n\t\t\t      config_good = false; \n\t\t\t      if (print_details) printf(\"Configuration %d fails at corner 5, outside segment\\n\",config_id); \n\t\t\t      continue;\n\t\t\t  }\n\t\t\t  if ((corner_3_top-corner_5_down).norm()<shorted_edge_thre){\n\t\t\t      if (print_details) printf(\"Configuration %d fails at edge 3-5, too short\\n\",config_id); \n\t\t\t      continue;\n\t\t\t  }\n\t\t\t  Vector2d corner_6_down=lineSegmentIntersect(vp_2,corner_5_down,vp_3, corner_2_top,true);\n\t\t\t  if (!check_inside_box( corner_6_down, expan_distmap_lefttop, expan_distmap_rightbottom)){\n\t\t\t      config_good=false;  \n\t\t\t      if (print_details) printf(\"Configuration %d fails at corner 6, outside box\\n\",config_id); \n\t\t\t      continue;\n\t\t\t  }\n\t\t\t  if ( ((corner_6_down-corner_2_top).norm()<shorted_edge_thre) || ((corner_6_down-corner_5_down).norm()<shorted_edge_thre) ){\n\t\t\t      if (print_details) printf(\"Configuration %d fails at edge 6-5/6-2, too short\\n\",config_id); \n\t\t\t      continue;\n\t\t\t  }\n\t\t\t  Vector2d corner_7_down=lineSegmentIntersect(vp_1,corner_6_down,vp_3, corner_1_top,true);\n\t\t\t  if (!check_inside_box( corner_7_down, expan_distmap_lefttop, expan_distmap_rightbottom)){// might be slightly different from matlab\n\t\t\t      config_good=false;  \n\t\t\t      if (print_details) printf(\"Configuration %d fails at corner 7, outside box\\n\",config_id); \n\t\t\t      continue;\n\t\t\t  }\n\t\t\t  if ( ((corner_7_down-corner_1_top).norm()<shorted_edge_thre) || ((corner_7_down-corner_6_down).norm()<shorted_edge_thre) ){\n\t\t\t      if (print_details) printf(\"Configuration %d fails at edge 7-1/7-6, too short\\n\",config_id); \n\t\t\t      continue;\n\t\t\t  }\n\t\t\t  Vector2d corner_8_down=lineSegmentIntersect(vp_1,corner_5_down,vp_2, corner_7_down,true);\n\t\t\t  if (!check_inside_box( corner_8_down, expan_distmap_lefttop, expan_distmap_rightbottom)){\n\t\t\t      config_good=false;  \n\t\t\t      if (print_details) printf(\"Configuration %d fails at corner 8, outside box\\n\",config_id); \n\t\t\t      continue;\n\t\t\t  }\n\t\t\t  if ( ((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      if (print_details) printf(\"Configuration %d fails at edge 8-4/8-5/8-7, too short\\n\",config_id); \n\t\t\t      continue;\n\t\t\t  }\n\t\t\t  \n\t\t\t  MatrixXd box_corners_2d_float(2,8);\n\t\t\t  box_corners_2d_float<<corner_1_top,corner_2_top,corner_3_top,corner_4_top,corner_5_down,corner_6_down,corner_7_down,corner_8_down;\n// \t\t\t  std::cout<<\"box_corners_2d_float \\n \"<<box_corners_2d_float<<std::endl;\n\t\t\t  MatrixXd box_corners_2d_float_shift(2,8);box_corners_2d_float_shift.row(0)=box_corners_2d_float.row(0).array()-left_x_expan_distmap;\n\t\t\t  box_corners_2d_float_shift.row(1)=box_corners_2d_float.row(1).array()-top_y_expan_distmap;\n\n\t\t\t  MatrixXi visible_edge_pt_ids,vps_box_edge_pt_ids;\n\t\t\t  double sum_dist;\n\t\t\t  if (config_id==1)\n\t\t\t  {\n\t\t\t      visible_edge_pt_ids.resize(9,2); visible_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      vps_box_edge_pt_ids.resize(3,4); vps_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      visible_edge_pt_ids.array() -=1; vps_box_edge_pt_ids.array() -=1; //change to c++ index\n\t\t\t      sum_dist = box_edge_sum_dists(dist_map,box_corners_2d_float_shift,visible_edge_pt_ids);\n\t\t\t  }\n\t\t\t  else\n\t\t\t  {\n\t\t\t      visible_edge_pt_ids.resize(7,2); visible_edge_pt_ids<<1,2, 2,3, 3,4, 4,1, 2,6, 3,5, 5,6;\n\t\t\t      vps_box_edge_pt_ids.resize(3,4); vps_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      visible_edge_pt_ids.array() -=1; vps_box_edge_pt_ids.array() -=1;\n\t\t\t      sum_dist = box_edge_sum_dists(dist_map,box_corners_2d_float_shift,visible_edge_pt_ids,reweight_edge_distance);\n\t\t\t  }\n\t\t\t  double total_angle_diff = box_edge_alignment_angle_error(all_vp_bound_edge_angles,vps_box_edge_pt_ids,box_corners_2d_float);\n\t\t\t  all_configs_error_one_objH.row(valid_config_number_one_objH).head<4>()=Vector4d(config_id, vp_1_position, obj_yaw_esti,sample_top_pt_id);\n\t\t\t  all_configs_error_one_objH.row(valid_config_number_one_objH).segment<3>(4) = Vector3d(sum_dist/obj_diaglength_expan, total_angle_diff, down_expand_sample);\n\t\t\t  if (whether_sample_cam_roll_pitch)\n\t\t\t      all_configs_error_one_objH.row(valid_config_number_one_objH).segment<2>(7) = Vector2d(cam_roll_samples[cam_roll_id],cam_pitch_samples[cam_pitch_id]);\n\t\t\t  else\n\t\t\t      all_configs_error_one_objH.row(valid_config_number_one_objH).segment<2>(7) = Vector2d(cam_pose_raw.euler_angle(0),cam_pose_raw.euler_angle(1));\n\t\t\t  all_box_corners_2d_one_objH.block(2*valid_config_number_one_objH,0,2,8)=box_corners_2d_float;\n\t\t\t  valid_config_number_one_objH++;\n\t\t\t  if (valid_config_number_one_objH>=all_configs_error_one_objH.rows())\n\t\t\t  {\n\t\t\t      all_configs_error_one_objH.conservativeResize(2*valid_config_number_one_objH,NoChange);\n\t\t\t      all_box_corners_2d_one_objH.conservativeResize(4*valid_config_number_one_objH,NoChange);\n\t\t\t  }\n\t\t      } //end of config loop\n\t\t  } //end of top id\n\t      } //end of yaw\n\t      \n// \t      std::cout<<\"valid_config_number_one_hseight  \"<<valid_config_number_one_objH<<std::endl;\n// \t      std::cout<<\"all_configs_error_one_objH  \\n\"<<all_configs_error_one_objH.topRows(valid_config_number_one_objH)<<std::endl;\n// \t      MatrixXd all_corners = all_box_corners_2d_one_objH.topRows(2*valid_config_number_one_objH);\n// \t      std::cout<<\"all corners   \"<<all_corners<<std::endl;\n\n\t      VectorXd normalized_score; vector<int> good_proposal_ids;\n\t      fuse_normalize_scores_v2(all_configs_error_one_objH.col(4).head(valid_config_number_one_objH), all_configs_error_one_objH.col(5).head(valid_config_number_one_objH),\n\t\t\t\t    normalized_score, good_proposal_ids, weight_vp_angle,whether_normalize_two_errors);\t      \n\n\t      for (int box_id=0;box_id<good_proposal_ids.size();box_id++)\n\t      {\n\t\t  int raw_cube_ind = good_proposal_ids[box_id];\n\t\t  \n\t\t  if (whether_sample_cam_roll_pitch)\n\t\t  {\n\t\t      Matrix4d transToWolrd_new = transToWolrd;\n\t\t      transToWolrd_new.topLeftCorner<3,3>() = euler_zyx_to_rot<double>(all_configs_error_one_objH(raw_cube_ind,7), all_configs_error_one_objH(raw_cube_ind,8), cam_pose_raw.euler_angle(2));\n\t\t      set_cam_pose(transToWolrd_new);\n\t\t      ground_plane_sensor = cam_pose.transToWolrd.transpose()*ground_plane_world;\n\t\t  }\n\t\t  \n\t\t  cuboid* sample_obj = new cuboid();\n\t\t  change_2d_corner_to_3d_object(all_box_corners_2d_one_objH.block(2*raw_cube_ind,0,2,8), all_configs_error_one_objH.row(raw_cube_ind).head<3>(), \n\t\t\t\t\t\tground_plane_sensor,  cam_pose.transToWolrd, cam_pose.invK, cam_pose.projectionMatrix,*sample_obj);\n// \t\t  sample_obj->print_cuboid();\n\t\t  if ((sample_obj->scale.array() < 0).any())     continue;                        // scale should be positive\n\t\t  sample_obj->rect_detect_2d =  Vector4d(left_x_raw,top_y_raw,obj_width_raw,obj_height_raw);\n\t\t  sample_obj->edge_distance_error = all_configs_error_one_objH(raw_cube_ind,4); // record the original error\n\t\t  sample_obj->edge_angle_error = all_configs_error_one_objH(raw_cube_ind,5);\n\t\t  sample_obj->normalized_error = normalized_score(box_id);\n\t\t  double skew_ratio = sample_obj->scale.head(2).maxCoeff()/sample_obj->scale.head(2).minCoeff();\n\t\t  sample_obj->skew_ratio = skew_ratio;\n\t\t  sample_obj->down_expand_height = all_configs_error_one_objH(raw_cube_ind,6);\n\t\t  if (whether_sample_cam_roll_pitch)\n\t\t  {\n\t\t      sample_obj->camera_roll_delta = all_configs_error_one_objH(raw_cube_ind,7)-cam_pose_raw.euler_angle(0);\n\t\t      sample_obj->camera_pitch_delta = all_configs_error_one_objH(raw_cube_ind,8)-cam_pose_raw.euler_angle(1);\n\t\t  }\n\t\t  else\n\t\t  {   sample_obj->camera_roll_delta = 0;sample_obj->camera_pitch_delta = 0; }\n\t\t  \n\t\t  raw_obj_proposals.push_back(sample_obj);\n\t      }\n\t  } // end of differnet object height sampling\n\n\t  // %finally rank all proposals. [normalized_error   skew_error]\n\t  int actual_cuboid_num_small = std::min(max_cuboid_num,(int)raw_obj_proposals.size());\n\t  VectorXd all_combined_score(raw_obj_proposals.size());\n\t  for (int box_id=0;box_id<raw_obj_proposals.size();box_id++)\n\t  {\n\t      cuboid* sample_obj = raw_obj_proposals[box_id];\n\t      double skew_error = weight_skew_error*std::max(sample_obj->skew_ratio-nominal_skew_ratio,0.0);\n\t      if (sample_obj->skew_ratio > max_cut_skew)\n\t\t    skew_error = 100;\n\t      double new_combined_error = sample_obj->normalized_error+weight_skew_error*skew_error;\n\t      all_combined_score(box_id) = new_combined_error;\n\t  }\n\t  \n\t  std::vector<int> sort_idx_small(all_combined_score.rows());   iota(sort_idx_small.begin(), sort_idx_small.end(), 0);\n\t  sort_indexes(all_combined_score, sort_idx_small,actual_cuboid_num_small);\n\t  for (int ii=0;ii<actual_cuboid_num_small;ii++) // use sorted index\n\t  {\n\t      all_object_cuboids[object_id].push_back(raw_obj_proposals[sort_idx_small[ii]]);\n\t  }\n\t  \n\t  ca::Profiler::tictoc(\"One 3D object total time\"); \n      }// end of different objects\n\n\n      if (whether_plot_final_images || whether_save_final_images)\n      {\n\t  cv::Mat frame_all_cubes_img = rgb_img.clone();\n\t  for (int object_id=0;object_id< all_object_cuboids.size();object_id++)\n\t    if ( all_object_cuboids[object_id].size()>0 )\n\t    {\n\t\tplot_image_with_cuboid(frame_all_cubes_img, all_object_cuboids[object_id][0]);\n\t    }\n\t  if (whether_save_final_images)\n\t      cuboids_2d_img = frame_all_cubes_img;\n\t  if (whether_plot_final_images)\n\t  {\n\t      cv::imshow(\"frame_all_cubes_img\", frame_all_cubes_img);\t cv::waitKey(0);\n\t  }\n      }\n}\n\n\n\n", "meta": {"hexsha": "7dd765b86600a541c84a99d41249f26766a3052b", "size": 26499, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "detect_3d_cuboid/src/box_proposal_detail.cpp", "max_stars_repo_name": "tiev-tongji/quadric_slam", "max_stars_repo_head_hexsha": "2789cf553d947c87bd601659e60c50b63be09b76", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 45.0, "max_stars_repo_stars_event_min_datetime": "2019-07-28T15:41:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-24T07:48:47.000Z", "max_issues_repo_path": "detect_3d_cuboid/src/box_proposal_detail.cpp", "max_issues_repo_name": "lucianzhong/quadric_slam", "max_issues_repo_head_hexsha": "f1b8f98b1c8d6d4cb36d238ec3a93cb2090611fc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2019-07-10T07:19:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-25T09:08:49.000Z", "max_forks_repo_path": "detect_3d_cuboid/src/box_proposal_detail.cpp", "max_forks_repo_name": "lucianzhong/quadric_slam", "max_forks_repo_head_hexsha": "f1b8f98b1c8d6d4cb36d238ec3a93cb2090611fc", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2019-08-05T02:03:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-14T02:36:29.000Z", "avg_line_length": 54.75, "max_line_length": 209, "alphanum_fraction": 0.7184422054, "num_tokens": 7468, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931457, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4704423657523458}}
{"text": "// Copyright 2018 Xiaomi, 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 <string>\n#include <vector>\n\n#include \"mace/core/testing/test_benchmark.h\"\n#include \"mace/kernels/gemm.h\"\n\nnamespace mace {\nnamespace kernels {\nnamespace test {\n\n// Test the speed of different access order of a NHWC buffer\n\nnamespace {\n\n// Matmul with (m, k) x (k, n)\nvoid MatmulBenchmark_Mace(int iters, int m, int k, int n) {\n  mace::testing::StopTiming();\n  std::vector<float> lhs(m * k);\n  std::vector<float> rhs(k * n);\n  std::vector<float> result(m * n);\n  // warm up\n  Gemm(lhs.data(), rhs.data(), 1, m, k, n, result.data());\n  mace::testing::StartTiming();\n  while (iters--) {\n    Gemm(lhs.data(), rhs.data(), 1, m, k, n, result.data());\n  }\n}\n\nvoid MatmulBenchmark_Eigen(int iters, int m, int k, int n) {\n  mace::testing::StopTiming();\n  Eigen::MatrixXd lhs = Eigen::MatrixXd::Random(m, k);\n  Eigen::MatrixXd rhs = Eigen::MatrixXd::Random(k, n);\n  Eigen::MatrixXd result = Eigen::MatrixXd::Zero(m, n);\n  // warm up\n  result = lhs * rhs;\n  mace::testing::StartTiming();\n  while (iters--) {\n    result = lhs * rhs;\n  }\n}\n\n}  // namespace\n\n#define MACE_BM_MATMUL_FUNC(M, K, N, FUNC)                         \\\n  static void MACE_BM_MATMUL_##M##_##K##_##N##_##FUNC(int iters) { \\\n    const int64_t macc = static_cast<int64_t>(iters) * M * K * N;  \\\n    const int64_t tot = static_cast<int64_t>(iters) * (M + N) * K; \\\n    mace::testing::MaccProcessed(macc);                            \\\n    mace::testing::BytesProcessed(tot * sizeof(float));            \\\n    MatmulBenchmark_##FUNC(iters, M, K, N);                        \\\n  }                                                                \\\n  MACE_BENCHMARK(MACE_BM_MATMUL_##M##_##K##_##N##_##FUNC)\n\n#define MACE_BM_MATMUL(M, K, N)        \\\n  MACE_BM_MATMUL_FUNC(M, K, N, Mace);  \\\n  MACE_BM_MATMUL_FUNC(M, K, N, Eigen);\n\n// Embedding size 384\nMACE_BM_MATMUL(7, 384, 384);\nMACE_BM_MATMUL(7, 384, 1536);\nMACE_BM_MATMUL(7, 1536, 384);\n\nMACE_BM_MATMUL(15, 384, 384);\nMACE_BM_MATMUL(15, 384, 1536);\nMACE_BM_MATMUL(15, 1536, 384);\n\nMACE_BM_MATMUL(1, 384, 384);\nMACE_BM_MATMUL(1, 384, 1536);\nMACE_BM_MATMUL(1, 1536, 384);\nMACE_BM_MATMUL(1, 384, 44678);\n\n// Embedding size 128\nMACE_BM_MATMUL(1, 128, 1536);\nMACE_BM_MATMUL(1, 128, 44678);\n\n}  // namespace test\n}  // namespace kernels\n}  // namespace mace\n", "meta": {"hexsha": "32ab8b4b66b459f34d54e9114046c1b0828e9f29", "size": 2919, "ext": "cc", "lang": "C++", "max_stars_repo_path": "mace/kernels/matmul_benchmark.cc", "max_stars_repo_name": "huuuuusy/MACE-Learn", "max_stars_repo_head_hexsha": "92aa30137bdcd238f7db3ad1612a4a6a44553d23", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2018-08-06T01:56:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-24T19:45:55.000Z", "max_issues_repo_path": "mace/kernels/matmul_benchmark.cc", "max_issues_repo_name": "huuuuusy/MACE-Learn", "max_issues_repo_head_hexsha": "92aa30137bdcd238f7db3ad1612a4a6a44553d23", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mace/kernels/matmul_benchmark.cc", "max_forks_repo_name": "huuuuusy/MACE-Learn", "max_forks_repo_head_hexsha": "92aa30137bdcd238f7db3ad1612a4a6a44553d23", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-06-11T02:12:09.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-11T02:12:09.000Z", "avg_line_length": 30.7263157895, "max_line_length": 75, "alphanum_fraction": 0.6409729359, "num_tokens": 919, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.47044236575234577}}
{"text": "// Copyright (C) 2021 Christian Brommer, Control of Networked Systems, University of Klagenfurt, Austria.\n//\n// All rights reserved.\n//\n// This software is licensed under the terms of the BSD-2-Clause-License with\n// no commercial use allowed, the full terms of which are made available\n// in the LICENSE file. No license in patents is granted.\n//\n// You can contact the author at <christian.brommer@ieee.org>\n\n#include <mars/ekf.h>\n#include <mars/general_functions/utils.h>\n#include <Eigen/Dense>\n\nnamespace mars\n{\nEigen::MatrixXd Ekf::CalculateCorrection()\n{\n  // Calculate innovation\n  S_ = H_ * P_ * H_.transpose() + R_;\n  S_ = Utils::EnforceMatrixSymmetry(S_);\n\n  // Calculate Klamen Gain\n  K_ = P_ * H_.transpose() * S_.inverse();\n\n  // Calculate Correction\n  Eigen::MatrixXd correction = K_ * res_;\n\n  return correction;\n}\n\nEigen::MatrixXd Ekf::CalculateCovUpdate()\n{\n  // Calculate ErrorState Covariance\n  int64_t state_size = H_.cols();\n\n  Eigen::MatrixXd I_state = Eigen::MatrixXd::Identity(state_size, state_size);\n\n  Eigen::MatrixXd KH = I_state - K_ * H_;\n  Eigen::MatrixXd updated_P = KH * P_ * KH.transpose() + K_ * R_ * K_.transpose();\n\n  return updated_P;\n}\n}\n", "meta": {"hexsha": "63cb5f1aab7b96d63ef81b7900037223e2117ddf", "size": 1177, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/mars/source/ekf.cpp", "max_stars_repo_name": "eallak/mars_lib", "max_stars_repo_head_hexsha": "9657fb669c48be39471e7504c3648319126c020b", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/mars/source/ekf.cpp", "max_issues_repo_name": "eallak/mars_lib", "max_issues_repo_head_hexsha": "9657fb669c48be39471e7504c3648319126c020b", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/mars/source/ekf.cpp", "max_forks_repo_name": "eallak/mars_lib", "max_forks_repo_head_hexsha": "9657fb669c48be39471e7504c3648319126c020b", "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.1555555556, "max_line_length": 105, "alphanum_fraction": 0.7119796092, "num_tokens": 308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.831143031127974, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.47044236101750364}}
{"text": "/**\n * \\file MT19937.hpp\n * \\brief Header for MT19937.\n *\n * This provides an interface to Mersenne Twister random number generator,\n * <a href=\"http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html\">MT19937</a>.\n * See\\n Makoto Matsumoto and Takuji Nishimura,\\n Mersenne Twister: A\n * 623-Dimensionally Equidistributed Uniform Pseudo-Random Number Generator,\\n\n * ACM TOMACS 8, 3-30 (1998)\n *\n * Interface routines written by <a href=\"http://charles.karney.info/\">Charles\n * Karney</a> <charles@karney.com> and licensed under the LGPL.  For more\n * information, see http://charles.karney.info/random/\n **********************************************************************/\n\n#if !defined(MT19937_H)\n#define MT19937_H\n\n#define RCSID_MT19937_H \"$Id: MT19937.hpp 6406 2007-05-23 13:29:52Z ckarney $\"\n\n#include \"RandomLib/RandomSeed.hpp\"\n#include <limits>\n\n#if HAVE_BOOST_SERIALIZATION\n#include <boost/serialization/nvp.hpp>\n#include <boost/serialization/split_member.hpp>\n#include <boost/serialization/vector.hpp>\n#endif\n\n/**\n * Which version of seeding and saving to use.  3 = scheme proposed in C++0X\n * random number proposal, version 3 (2006-09) plus append a checksum to data\n * stream (introduced with 2006-11 version).  4 = add leapfrogging (introduced\n * with 2006-12 version).  In this implementation, I/O routines can read\n * versions 3 and 4.\n **********************************************************************/\n#define MT19937_VERSION 4\n\nnamespace RandomLib {\n  /**\n   * \\brief A generator of random bits.\n   *\n   * This provides an interface to Mersenne Twister random number generator,\n   * <a href=\"http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html\">\n   * MT19937</a>.  See\\n Makoto Matsumoto and Takuji Nishimura,\\n Mersenne\n   * Twister: A 623-Dimensionally Equidistributed Uniform Pseudo-Random Number\n   * Generator,\\n ACM TOMACS 8, 3-30 (1998)\n   *\n   * This is adapted from the 32-bit and 64-bit C versions available at\n   * http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/emt19937ar.html and\n   * http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt64.html\n   *\n   * The template arguments give the type \\a UIntType of the \"natural\" result\n   * and the number of random bits \\a BitWidth in each result.  Although the\n   * two versions of MT19937 produce different sequences, the implementations\n   * here are portable across 32-bit and 64-bit architectures.  As expected the\n   * 64-bit version of MT19937 runs somewhat faster on 64-bit machines and\n   * considerably slower on 32-bit machines.\n   *\n   * The class supplies the method for advancing the state and generating the\n   * random output.  The random results are provided as 32-bit quantities via\n   * Ran32(), as 64-bit quantities via Ran64(), and in \"natural\" units of \\a\n   * width bits via Ran().  For MT19937, \\a width is either 32 or 64.  It\n   * inherits from RandomSeed the routines for seed management and for\n   * converting the seed into state.\n   *\n   * It also provides routines for saving and restoring the state of the\n   * generator (including its seed), for stepping the generator forwards or\n   * backwards, and for testing the equality of two generators.\n   *\n   * Interface routines written by <a href=\"http://charles.karney.info/\">\n   * Charles Karney</a> <charles@karney.com> and licensed under the LGPL.  For\n   * more information, see http://charles.karney.info/random/\n   **********************************************************************/\n  template<typename UIntType, unsigned BitWidth>\n  class MT19937 : public RandomSeed {\n  public:\n    enum {\n      /**\n       * The number of random bits produced by Ran().\n       **********************************************************************/\n      width = BitWidth\n    };\n    /**\n     * A type large enough to hold \\e width bits.  This is used for the\n     * internal state of the generator and the result returned by Ran().\n     * (Seeds are specified in terms of the more portable unsigned long.)\n     **********************************************************************/\n    typedef UIntType result_type;\n    /**\n     * The minimum result returned by Ran().\n     **********************************************************************/\n    static const result_type min = 0;\n    /**\n     * The maximum result returned by Ran() = 2<sup><i>w</i></sup> - 1\n     **********************************************************************/\n    static const result_type max =\n      ~result_type(0) >> std::numeric_limits<result_type>::digits - width;\n\n  protected:\n    /**\n     * A mask to give the low \\e width bits in a result_type.\n     **********************************************************************/\n    static const result_type RESULT_MASK = max;\n\n  private:\n    // Constants\n    enum {\n      /**\n       * The Mersenne prime is 2<sup><i>P</i></sup> - 1\n       **********************************************************************/\n      P = 19937,\n      /**\n       * The long lag for MT19937\n       **********************************************************************/\n      N = (P + width - 1)/width,\n      /**\n       * The short lag for MT19937\n       **********************************************************************/\n      M = width == 32 ? 397 : 156,\n      /**\n       * The number of ignored bits in the first word of the state\n       **********************************************************************/\n      R = N * width - P\n    };\n    /**\n     * \"MTrn\" or \"MTsn\" a signature for Save\n     **********************************************************************/\n    static const u32 VERSIONID =\n      u32(width == 32 ? 0x4d547230UL : 0x4d547330UL) + MT19937_VERSION;\n    /**\n     * Magic matrix for MT19937\n     **********************************************************************/\n    static const result_type MATRIX_A =\n      result_type(width == 32 ? 0x9908b0dfULL : 0xb5026f5aa96619e9ULL);\n    /**\n     * Mask for top \\a width - \\a R bits of a word\n     **********************************************************************/\n    static const result_type UPPER_MASK = RESULT_MASK << R & RESULT_MASK;\n    /**\n     * Mask for low \\a R bits of a <i>width</i>-bit word\n     **********************************************************************/\n    static const result_type LOWER_MASK = ~UPPER_MASK & RESULT_MASK;\n    /**\n     * Marker for uninitialized object\n     **********************************************************************/\n    static const unsigned UNINIT = 0xffffffffU;\n\n    /**\n     * The state vector\n     **********************************************************************/\n    result_type _state[N];\n    /**\n     * The index for the next random value\n     **********************************************************************/\n    unsigned _ptr;\n    /**\n     * How many times has NextBatch() been called\n     **********************************************************************/\n    long long _rounds;\n    /**\n     * Stride for leapfrogging\n     **********************************************************************/\n    unsigned _stride;\n\n  public:\n\n    /** \\name Constructors which set the seed\n     **********************************************************************/\n    ///@{\n    /**\n     * Initialize from a vector.  Only the low \\e 32 bits of each element are\n     * used.\n     **********************************************************************/\n    template<typename IntType> explicit MT19937(const std::vector<IntType>& v)\n      throw(std::bad_alloc) { Reseed(v); }\n    /**\n     * Initialize from a pair of iterators setting seed to [\\a a, \\a b).  The\n     * iterator must produce results which can be converted into seed_type.\n     * Only the low \\e 32 bits of each element are used.\n     **********************************************************************/\n    template<typename InputIterator> MT19937(InputIterator a, InputIterator b)\n    { Reseed(a, b); }\n    /**\n     * Initialize with seed [\\a n].  Only the low \\e width bits of \\a n are\n     * used.\n     **********************************************************************/\n    explicit MT19937(seed_type n) throw(std::bad_alloc)\n    { Reseed(n); }\n    /**\n     * Initialize with seed [SeedWord()]\n     **********************************************************************/\n    MT19937() throw(std::bad_alloc) { Reseed(); }\n    /**\n     * Initialize from a string.  See Reseed(const std::string& s)\n     **********************************************************************/\n    explicit MT19937(const std::string& s) throw(std::bad_alloc)\n    { Reseed(s); }\n    ///@}\n\n    /** \\name Functions for returning random data\n     **********************************************************************/\n    ///@{\n    /**\n     * Return \\e width bits of randomness.  Result is in [0,\n     * 2<sup><i>w</i></sup>)\n     **********************************************************************/\n    result_type operator()() throw() { return Ran(); }\n    ///@}\n\n    /** \\name Comparing Random objects\n     **********************************************************************/\n    ///@{\n    /**\n     * Test equality of two Random objects.  This test that the seeds match and\n     * that they have produced the same number of random numbers.\n     **********************************************************************/\n    bool operator==(const MT19937& r) const throw()\n    // Ensure that the two Random objects behave the same way.  Note however\n    // that the internal states may still be different, e.g., the following all\n    // result in Random objects which are == (with Count() == 0) but which all\n    // have different internal states:\n    //\n    // Random r(0);                       _ptr == UNINIT\n    // r.StepCount( 1); r.StepCount(-1);  _ptr == 0, _rounds ==  0\n    // r.StepCount(-1); r.StepCount( 1);  _ptr == N, _rounds == -1\n    { return Count() == r.Count() && _seed == r._seed &&\n\t_stride == r._stride; }\n    /**\n     * Test inequality of two Random objects.  See Random::operator==\n     **********************************************************************/\n    bool operator!=(const MT19937& r) const throw()\n    { return !operator==(r); }\n    ///@}\n\n    /** \\name Writing to and reading from a stream\n     **********************************************************************/\n    ///@{\n    /**\n     * Save the state of the Random object to an output stream.  Format is a\n     * sequence of unsigned 32-bit integers written either in decimal (\\a bin\n     * false, text format) or in network order with most significant byte first\n     * (\\a bin true, binary format).  Data consists of:\n     *\n     *  - VERSIONID (1 word)\n     *  - _seed.size() (1 word)\n     *  - _seed data (_seed.size() words)\n     *  - _ptr (1 word)\n     *  - _stride (1 word)\n     *  - if _ptr != UNINIT, _rounds (2 words)\n     *  - if _ptr != UNINIT, _state (N words or 2 N words)\n     *  - checksum\n     *\n     * Shortest possible saved result consists of 5 words:\n     *  - VERSIONID = \"MTrn\"\n     *  - _seed.size() = 0\n     *  - _ptr = UNINIT\n     *  - _stride = 1\n     *  - checksum\n     *\n     * This corresponds to Seed() = [] and Count() = 0.\n     **********************************************************************/\n    void Save(std::ostream& os, bool bin = true) const\n      throw(std::ios::failure);\n    /**\n     * Restore the state of the Random object from an input stream.  If \\a bin,\n     * read in binary, else use text format.  See documentation of Random::Save\n     * for the format.  Include error checking on date to make sure the input\n     * has not been corrupted.  If an error occurs while reading, the Random\n     * object is unchanged.\n     **********************************************************************/\n    void Load(std::istream& is, bool bin = true)\n      throw(std::ios::failure, std::out_of_range, std::bad_alloc) {\n      // Read state into temporary so as not to change object on error.\n      MT19937 t(is, bin);\n      _seed.reserve(t._seed.size());\n      *this = t;\n    }\n    ///@}\n\n    /** \\name Examining and advancing the Random generator\n     **********************************************************************/\n    ///@{\n    /**\n     * Return the number of random numbers used.  This needs to return a long\n     * long result since it can reasonably exceed 2<sup>31</sup>.  (On a 1GHz\n     * machine, it takes about a minute to produce 2<sup>32</sup> random\n     * numbers.)  More precisely this is the (zero-based) index of the next\n     * random number to be produced.  (This distinction is important when\n     * leapfrogging is in effect.)\n     **********************************************************************/\n    long long Count() const throw()\n    { return _ptr == UNINIT ? 0 : _rounds * N + _ptr; }\n    /**\n     * Step the generator forwards of backwarks so that the value returned\n     * by Count() is \\a n\n     **********************************************************************/\n    void SetCount(long long n) throw() { StepCount(n - Count()); }\n    /**\n     * Step the generator forward \\a n steps.  \\a n can be negative.\n     **********************************************************************/\n    void StepCount(long long n) throw();\n    /**\n     * Resets the sequence.  Equivalent to SetCount(0), but works by\n     * reinitializing the Random object from its seed, rather than by stepping\n     * the sequence backwards.  In addition, this undoes leapfrogging.\n     **********************************************************************/\n    void Reset() throw() { _ptr = UNINIT; _stride = 1; }\n    ///@}\n\n    /** \\name Leapfrogging\n     **********************************************************************/\n    ///@{\n    /**\n     * Set leapfrogging stride to a positive number \\a n and increment Count()\n     * by \\a k < \\a n.  If the current Count() is \\a i, then normally the next\n     * 3 random numbers would have indices \\a i, \\a i + 1, \\a i + 2, and the\n     * new Count() is \\a i + 2.  However, after SetStride(\\a n, \\a k) the next\n     * 3 random numbers have indices \\a i + \\a k, \\a i + \\a k + \\a n, \\a i + \\a\n     * k + 2\\a n, and the new Count() is \\a i + \\a k + 3\\a n.  With\n     * leapfrogging in effect, the time to produce raw random numbers is\n     * roughly proportional to 1 + (\\a n - 1)/2.  Reseed(...) and Reset() both\n     * reset the stride back to 1.  See \\ref leapfrog \"Leapfrogging\" for a\n     * description of how to use this facility.\n     **********************************************************************/\n    void SetStride(unsigned n = 1, unsigned k = 0)\n      throw(std::invalid_argument) {\n      // Limit stride to UNINIT/2.  This catches negative numbers that have\n      // been cast into unsigned.  In reality the stride should be no more than\n      // 10-100.\n      if (n == 0 || n > UNINIT/2)\n\tthrow std::invalid_argument(\"MT19937: Invalid stride\");\n      if (k >= n)\n\tthrow std::invalid_argument(\"MT19937: Invalid index\");\n      _stride = n;\n      StepCount(k);\n    }\n    /**\n     * Return leapfrogging stride.\n     **********************************************************************/\n    unsigned GetStride() const throw() { return _stride; }\n    ///@}\n\n    /**\n     * Return string description of this generator\n     **********************************************************************/\n    static std::string Name() {\n      std::ostringstream s;\n      s << \"RandomLib::MT19937 \" << width << \"-bit \"\n\t<< \"Version \" << MT19937_VERSION;\n      return s.str();\n    }\n\n    /**\n     * Tests basic engine.  Throws out_of_range errors on bad results.\n     **********************************************************************/\n    static void SelfTest() {\n      MT19937 g(std::vector<seed_type>(0));\n      g.SetCount(10000-1);\n      if (g() !=\n\t  result_type(width == 32 ? 4123659995ULL : 9981545732273789042ULL))\n\tthrow std::out_of_range(\"MT19937: Incorrect result with seed \" +\n\t\t\t\tg.SeedString());\n      seed_type s[] = {1, 2, 3, 4};\n      g.Reseed(s, s+4);\n      g.SetCount(-10000);\n      std::string save;\n      {\n\tstd::ostringstream stream;\n\tstream << g << std::endl;\n\tsave = stream.str();\n      }\n      g.Reset();\n      {\n\tstd::istringstream stream(save);\n\tstream >> g;\n      }\n      g.SetCount(10000);\n      {\n\tstd::ostringstream stream;\n\tg.Save(stream, true);\n\tsave = stream.str();\n      }\n      {\n\tstd::istringstream stream(save);\n\tMT19937 h(std::vector<seed_type>(0));\n\th.Load(stream, true);\n\th.SetCount(1000000-1);\n\tif (h() !=\n\t    result_type(width == 32 ? 4244229310ULL : 16856309709668453709ULL))\n\tthrow std::out_of_range(\"MT19937: Incorrect result with seed \" +\n\t\t\t\th.SeedString());\n\tg.SetCount(1000000);\n\tif (h != g)\n\tthrow std::out_of_range(\"MT19937: Comparison failure\");\n      }\n    }\n\n  protected:\n    /**\n     * Return \\e width bits of randomness.  This is the natural unit of random\n     * data produced by MT19937.\n     **********************************************************************/\n    result_type Ran() throw();\n    /**\n     * Return 32 bits of randomness.\n     **********************************************************************/\n    u32 Ran32() throw();\n    /**\n     * Return 64 bits of randomness.\n     **********************************************************************/\n    u64 Ran64() throw();\n\n  private:\n    /**\n     * Compute initial state from seed\n     **********************************************************************/\n    void Init() throw();\n    /**\n     * Advance state by \\e N steps\n     **********************************************************************/\n    void NextBatch(unsigned long long count) throw();\n    /**\n     * Back up state by \\e N steps\n     **********************************************************************/\n    void PreviousBatch(unsigned long long count) throw();\n    /**\n     * The interface to NextBatch used by Ran().\n     **********************************************************************/\n    void Next() throw();\n\n    /**\n     * Consistency check on state; mainly used for validating I/O.  This throws\n     * an out-of-range error if the state is bad.  It also computes a simple\n     * checksum to ensure the integrity of restored data.\n     **********************************************************************/\n    u32 Check(u32 version) const throw(std::out_of_range);\n\n    /**\n     * Read from an input stream.  Potentially corrupts object.  This is used\n     * by Load so that it can avoid corrupting its state on bad input.\n     **********************************************************************/\n    explicit MT19937(std::istream& is, bool bin)\n      throw(std::ios::failure, std::out_of_range, std::bad_alloc);\n\n#if HAVE_BOOST_SERIALIZATION\n    friend class boost::serialization::access;\n    /**\n     * Save to a boost archive.  Boost versioning isn't very robust.  (It\n     * allows a RandomGenerator32 to be read back in as a RandomGenerator64.\n     * It doesn't interact well with templates.)  So we do our own versioning\n     * and supplement this with a checksum.\n     **********************************************************************/\n    template<class Archive> void save(Archive& ar, const unsigned int) const {\n      u32 _version = VERSIONID,\n\t_checksum = Check(_version);\n      ar & boost::serialization::make_nvp(\"version\" , _version )\n\t&  boost::serialization::make_nvp(\"seed\"    , _seed    )\n\t&  boost::serialization::make_nvp(\"ptr\"     , _ptr     )\n\t&  boost::serialization::make_nvp(\"stride\"  , _stride  );\n      if (_ptr != UNINIT)\n\tar & boost::serialization::make_nvp(\"rounds\", _rounds  )\n\t  &  boost::serialization::make_nvp(\"state\" , _state   );\n      ar & boost::serialization::make_nvp(\"checksum\", _checksum);\n    }\n    /**\n     * Load from a boost archive.  Do this safely so that the current object is\n     * not corrupted if the archive is bogus.\n     **********************************************************************/\n    template<class Archive> void load(Archive& ar, const unsigned int) {\n      u32 _version, _checksum;\n      ar & boost::serialization::make_nvp(\"version\" , _version );\n      MT19937 t(std::vector<seed_type>(0));\n      ar & boost::serialization::make_nvp(\"seed\"    , t._seed  )\n\t&  boost::serialization::make_nvp(\"ptr\"     , t._ptr   );\n      if (_version == VERSIONID - 1) {\n\tif (t._ptr == N + 1)\n\t  t._ptr = UNINIT;\n\tt._stride = 1;\n      } else\n\tar &  boost::serialization::make_nvp(\"stride\"  , t._stride);\n      if (t._ptr != UNINIT)\n\tar & boost::serialization::make_nvp(\"rounds\", t._rounds)\n\t  &  boost::serialization::make_nvp(\"state\" , t._state );\n      ar & boost::serialization::make_nvp(\"checksum\", _checksum);\n      if (t.Check(_version) != _checksum)\n\tthrow std::out_of_range(\"MT19937: Checksum failure\");\n      _seed.reserve(t._seed.size());\n      *this = t;\n    }\n    /**\n     * Glue the boost save and load functionality together -- a bit of boost\n     * magic.\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\n  template<>\n  inline RandomSeed::u32 MT19937<RandomSeed::u32, 32>::Ran() throw() {\n    // On exit we have _stride <= _ptr < N + _stride.\n    if (_ptr >= N)\n      Next();\n    result_type y = _state[_ptr];\n    _ptr += _stride;\n\n    // Specific tempering instantiation for width = 32 given in\n    // http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/emt19937ar.html\n    y ^= y >> 11;\n    y ^= y <<  7 & result_type(0x9d2c5680UL);\n    y ^= y << 15 & result_type(0xefc60000UL);\n    y ^= y >> 18;\n\n    return y;\n  }\n\n  template<>\n  inline RandomSeed::u32 MT19937<RandomSeed::u32, 32>::Ran32() throw()\n  { return Ran(); }\n\n  template<>\n  inline RandomSeed::u64 MT19937<RandomSeed::u32, 32>::Ran64() throw()\n  { const u64 x = Ran(); return x << width | static_cast<u64>(Ran()); }\n\n  template<>\n  inline RandomSeed::u64 MT19937<RandomSeed::u64, 64>::Ran() throw() {\n    if (_ptr >= N)\n      Next();\n    result_type y = _state[_ptr];\n    _ptr += _stride;\n\n    // Specific tempering instantiation for width = 64 given in\n    // http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt64.html\n    y ^= y >> 29 & result_type(0x5555555555555555ULL);\n    y ^= y << 17 & result_type(0x71d67fffeda60000ULL);\n    y ^= y << 37 & result_type(0xfff7eee000000000ULL);\n    y ^= y >> 43;\n\n    return y;\n  }\n\n  template<>\n  inline RandomSeed::u32 MT19937<RandomSeed::u64, 64>::Ran32() throw()\n  { return static_cast<u32>(Ran()) & U32_MASK; }\n\n  template<>\n  inline RandomSeed::u64 MT19937<RandomSeed::u64, 64>::Ran64() throw()\n  { return Ran(); }\n} // namespace RandomLib\n#endif\t// MT19937_H\n", "meta": {"hexsha": "62ab852a8a06f0267d92180e6c35460936df3d9a", "size": 22684, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Code/trunk/cpp/RandomLib/MT19937.hpp", "max_stars_repo_name": "jlconlin/PhDThesis", "max_stars_repo_head_hexsha": "8e704613721a800ce1c59576e94f40fa6f7cd986", "max_stars_repo_licenses": ["MIT"], "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/trunk/cpp/RandomLib/MT19937.hpp", "max_issues_repo_name": "jlconlin/PhDThesis", "max_issues_repo_head_hexsha": "8e704613721a800ce1c59576e94f40fa6f7cd986", "max_issues_repo_licenses": ["MIT"], "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/trunk/cpp/RandomLib/MT19937.hpp", "max_forks_repo_name": "jlconlin/PhDThesis", "max_forks_repo_head_hexsha": "8e704613721a800ce1c59576e94f40fa6f7cd986", "max_forks_repo_licenses": ["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.0198915009, "max_line_length": 82, "alphanum_fraction": 0.5115499912, "num_tokens": 5352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.470427685597577}}
{"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#define NT2_UNIT_MODULE \"nt2 combinatorial toolbox - is_prime/expr Mode\"\n\n//////////////////////////////////////////////////////////////////////////////\n// unit test behavior of combinatorial components in scalar mode\n//////////////////////////////////////////////////////////////////////////////\n/// created  by jt the 07/03/2011\n///\n#include <nt2/toolbox/combinatorial/include/functions/is_prime.hpp>\n#include <boost/type_traits/is_same.hpp>\n#include <nt2/sdk/functor/meta/call.hpp>\n\n#include <nt2/sdk/unit/tests.hpp>\n#include <nt2/sdk/unit/module.hpp>\n#include <nt2/sdk/memory/buffer.hpp>\n#include <nt2/toolbox/constant/constant.hpp>\n#include <nt2/include/functions/is_nez.hpp>\n#include <nt2/table.hpp>\n\nNT2_TEST_CASE_TPL ( is_prime_real__1_0,  NT2_REAL_TYPES)\n{\n\n  using nt2::is_prime;\n  using nt2::tag::is_prime_;\n  typedef typename nt2::meta::as_logical<T>::type bT;\n  nt2::table<T> a = nt2::_(T(1), T(30));\n  int aa[] = {false, true, true, false, true, false, true, false, false, false,\n               true, false, true, false, false, false, true, false, true, false,\n               false, false, true, false, false, false, false, false, true, false};\n  nt2::table<bT> ba(nt2::of_size(1, 30));\n\n  for(int i=0; i < 30; i++) ba(i+1) = nt2::is_nez(aa[i]);\n  NT2_DISPLAY( is_prime(a));\n  nt2::table<bT> p = is_prime(a);\n  NT2_TEST_EQUAL(p, ba);\n\n} // end of test for floating_\n\nNT2_TEST_CASE_TPL ( is_prime_integer__1_0,  NT2_INTEGRAL_TYPES)\n{\n\n  using nt2::is_prime;\n  using nt2::tag::is_prime_;\n  NT2_TEST(!is_prime(nt2::Eight<T>()));\n  NT2_TEST(is_prime(nt2::Seven<T>()));\n  NT2_TEST(is_prime(nt2::Two<T>()));\n  NT2_TEST(!is_prime(nt2::One<T>()));\n } // end of test for integer_\n\n", "meta": {"hexsha": "a199a642c4c3c1f88bf13e8dc99bb690ac770a11", "size": 2194, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/core/combinatorial/unit/expr/is_prime.cpp", "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/combinatorial/unit/expr/is_prime.cpp", "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/combinatorial/unit/expr/is_prime.cpp", "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": 38.4912280702, "max_line_length": 83, "alphanum_fraction": 0.5733819508, "num_tokens": 585, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.47042768540882396}}
{"text": "#include <metaSMT/frontend/QF_UF.hpp>\n#include <metaSMT/frontend/QF_BV.hpp>\n#include <boost/test/unit_test.hpp>\n#include <boost/dynamic_bitset.hpp>\n#include <string>\n\nusing namespace metaSMT;\nusing namespace metaSMT::logic;\nusing namespace metaSMT::logic::QF_UF;\nusing namespace metaSMT::logic::QF_BV;\nnamespace proto = boost::proto;\nusing boost::dynamic_bitset;\n\n\nBOOST_FIXTURE_TEST_SUITE(QF_UF, Solver_Fixture )\n\nBOOST_AUTO_TEST_CASE( equal_bool ) {\n  using namespace type;\n\n  unsigned const w = 8;\n  Uninterpreted_Function f = declare_function(Boolean())(BitVector(w));\n  bitvector x = new_bitvector(w);\n\n  assertion(ctx, equal(f(x), f(x)) );\n  BOOST_REQUIRE( solve(ctx) );\n\n  assertion(ctx, nequal(f(x), f(x)) );\n  BOOST_REQUIRE( !solve(ctx) );\n}\n\nBOOST_AUTO_TEST_CASE( equal_bitvector ) {\n  using namespace type;\n  unsigned const result_width = 4;\n  unsigned const param_width = 8;\n  Uninterpreted_Function f = declare_function(BitVector(result_width))(BitVector(param_width));\n  bitvector x = new_bitvector(param_width);\n\n  assertion(ctx, equal(f(x), f(x)) );\n  BOOST_REQUIRE( solve(ctx) );\n\n  assertion(ctx, nequal(f(x), f(x)) );\n  BOOST_REQUIRE( !solve(ctx) );\n}\n\nBOOST_AUTO_TEST_CASE( functional_consistency ) {\n  using namespace type;\n\n  unsigned const w = 8;\n  Uninterpreted_Function f = declare_function(Boolean())(BitVector(w));\n  bitvector x = new_bitvector(w);\n  bitvector y = new_bitvector(w);  \n\n  // functional consistency:\n  //   ( x == y ) --> ( f(x) == f(y) )\n  assertion(ctx, equal(x, y) );\n\n  assertion(ctx, equal(f(x), f(y)) );\n  BOOST_REQUIRE( solve(ctx) );\n}\n\nBOOST_AUTO_TEST_CASE( two_arguments ) {\n  using namespace type;\n  unsigned const w = 8;\n\n  Uninterpreted_Function f = declare_function(Boolean())(BitVector(w))(BitVector(w));\n  bitvector x = new_bitvector(w);\n\n  assertion(ctx, equal(f(x,x), f(x,x)));\n  BOOST_REQUIRE( solve(ctx) );\n}\n\nBOOST_AUTO_TEST_CASE( three_arguments ) {\n  using namespace type;\n  unsigned const w = 8;\n\n  Uninterpreted_Function f = declare_function(Boolean())(BitVector(w))(BitVector(w))(BitVector(w));\n  bitvector x = new_bitvector(w);\n\n  assertion(ctx, equal(f(x,x,x), f(x,x,x)));\n  BOOST_REQUIRE( solve(ctx) );\n}\n\nBOOST_AUTO_TEST_CASE( variable_equality ) {\n  using namespace type;\n\n  unsigned const w = 8;\n  Uninterpreted_Function f = declare_function(Boolean())(BitVector(w));\n  Uninterpreted_Function g = declare_function(Boolean())(BitVector(w));\n\n  bool cmp = (f == f);\n  BOOST_CHECK( cmp );\n\n  cmp = (g == f);\n  BOOST_CHECK( !cmp );\n\n  cmp = (f == g);\n  BOOST_CHECK( !cmp );\n}\n\nBOOST_AUTO_TEST_SUITE_END() // QF_UF\n\n//  vim: ft=cpp:ts=2:sw=2:expandtab\n", "meta": {"hexsha": "287bbb02ea8c3a28a73abf83a930ebf51a4b118b", "size": 2620, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_QF_UF.cpp", "max_stars_repo_name": "voertler/metaSMT", "max_stars_repo_head_hexsha": "726a78e0a18e0c06faa4483e7d7af34cee055529", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-01-11T10:37:28.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-29T08:39:16.000Z", "max_issues_repo_path": "tests/test_QF_UF.cpp", "max_issues_repo_name": "voertler/metaSMT", "max_issues_repo_head_hexsha": "726a78e0a18e0c06faa4483e7d7af34cee055529", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2016-08-02T10:46:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-03T09:17:46.000Z", "max_forks_repo_path": "tests/test_QF_UF.cpp", "max_forks_repo_name": "voertler/metaSMT", "max_forks_repo_head_hexsha": "726a78e0a18e0c06faa4483e7d7af34cee055529", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2018-10-08T12:55:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T14:52:45.000Z", "avg_line_length": 25.4368932039, "max_line_length": 99, "alphanum_fraction": 0.7015267176, "num_tokens": 703, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.4704276766018521}}
{"text": "/*\n * @Description: IMU data\n * @Author: Ge Yao\n * @Date: 2020-11-10 14:25:03\n */\n#ifndef IMU_INTEGRATION_IMU_DATA_HPP_\n#define IMU_INTEGRATION_IMU_DATA_HPP_\n\n#include <Eigen/Dense>\n#include <Eigen/Core>\n\nnamespace imu_integration {\n\nstruct IMUData {\n    double time = 0.0;\n    Eigen::Vector3d linear_acceleration = Eigen::Vector3d::Zero();\n    Eigen::Vector3d angular_velocity = Eigen::Vector3d::Zero();\n};\n\n} // namespace imu_integration\n\n#endif\n", "meta": {"hexsha": "c6238ddb4be27c64cfac7f75b5957849b1820785", "size": 448, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "IMU/05-imu-navigation/src/imu_integration/include/imu_integration/sensor_data/imu_data.hpp", "max_stars_repo_name": "lanqing30/SensorFusionCourse", "max_stars_repo_head_hexsha": "3fcf935d6a4191563afcf2d95b34718fba7f705a", "max_stars_repo_licenses": ["Apache-2.0"], "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": "05-imu-navigation/sensor-fusion-for-localization-and-mapping/workspace/assignments/05-imu-navigation/src/imu_integration/include/imu_integration/sensor_data/imu_data.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": "05-imu-navigation/sensor-fusion-for-localization-and-mapping/workspace/assignments/05-imu-navigation/src/imu_integration/include/imu_integration/sensor_data/imu_data.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": 19.4782608696, "max_line_length": 66, "alphanum_fraction": 0.7209821429, "num_tokens": 130, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419704455589, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.47042767248149564}}
{"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 sigma_point_quadrature_test.hpp\n * \\date August 2015\n * \\author Jan Issac (jan.issac@gmail.com)\n */\n\n#include <gtest/gtest.h>\n#include \"../typecast.hpp\"\n\n#include <Eigen/Dense>\n\n#include <random>\n\n#include <fl/util/profiling.hpp>\n#include <fl/util/math.hpp>\n#include <fl/distribution/gaussian.hpp>\n#include <fl/filter/gaussian/transform/point_set.hpp>\n#include <fl/filter/gaussian/transform/unscented_transform.hpp>\n#include <fl/filter/gaussian/transform/monte_carlo_transform.hpp>\n#include <fl/filter/gaussian/quadrature/sigma_point_quadrature.hpp>\n\ntemplate <typename TestType>\nclass SigmaPointQuadratureTests\n    : public testing::Test\n{\npublic:\n    typedef typename TestType::Parameter Configuration;\n\n    enum: signed int\n    {\n        DimA = Configuration::DimA,\n        DimB = Configuration::DimB,\n\n        SizeA = fl::TestSize<DimA, TestType>::Value,\n        SizeB = fl::TestSize<DimB, TestType>::Value\n    };\n\n    typedef Eigen::Matrix<fl::Real, SizeA, 1> VariateA;\n    typedef Eigen::Matrix<fl::Real, SizeB, 1> VariateB;\n\n    typedef fl::Gaussian<VariateA> GaussianA;\n    typedef fl::Gaussian<VariateB> GaussianB;\n\n    typedef Eigen::Matrix<fl::Real, SizeA, SizeA> MatrixAA;\n    typedef Eigen::Matrix<fl::Real, SizeB, SizeA> MatrixAB;\n\n    typedef typename Configuration::TransformSelection::Transform Transform;\n    typedef fl::SigmaPointQuadrature<Transform> Quadrature;\n\n    SigmaPointQuadratureTests()\n        : F(MatrixAA::Random(DimA, DimA)),\n          H(MatrixAB::Random(DimB, DimA)),\n          p_A(DimA),\n          p_B(DimB),\n          quadrature(Transform()),\n          eps(Configuration::TransformSelection::epsilon)\n    {\n        // create a random source Gaussians\n        p_A.mean(VariateA::Random(DimA));\n        p_A.covariance(p_A.covariance() * fl::Real(std::rand()) / RAND_MAX);\n\n        p_B.mean(VariateB::Random(DimB));\n        p_B.covariance(p_B.covariance() * fl::Real(std::rand()) / RAND_MAX);\n    }\n\n    template <typename Var> Var f(const Var& x)\n    {\n        return F * x;\n    }\n\n    template <typename VarA, typename VarB>\n    VarB f(const VarA& x, const VarB& w)\n    {\n        return H * x + w;\n    }\n\n    void integrate_fx_px()\n    {\n        using namespace fl;\n\n        // compute the expected integration result analytically\n        auto expect_gaussian = GaussianA(DimA);\n        expect_gaussian.mean(f(p_A.mean()));\n        expect_gaussian.covariance(F * p_A.covariance() * F.transpose());\n\n        // create the gaussian which will contail the integration results\n        auto result_gaussian = GaussianA(DimA);\n\n        // define the expected mean lambda function\n        // here we use a simple identity function\n        auto mean_f = [&] (const VariateA& x) { return f(x); };\n\n        // define the expected covariance lambda function\n        auto cov_f = [&] (const VariateA& x)\n        {\n            return ((f(x) - result_gaussian.mean()) *\n                    (f(x) - result_gaussian.mean()).transpose()).eval();\n        };\n\n        // integrate mean and covariance\n        result_gaussian.mean(quadrature.integrate(mean_f, p_A));\n        result_gaussian.covariance(quadrature.integrate(cov_f, p_A));\n\n        EXPECT_TRUE(result_gaussian.is_approx(expect_gaussian, eps, true));\n    }\n\n    void integrate_fxy_pxy()\n    {\n        using namespace fl;\n\n        auto expect_gaussian = GaussianB(DimB);\n        auto result_gaussian = GaussianB(DimB);\n\n        expect_gaussian.mean(f(p_A.mean(), p_B.mean()));\n        expect_gaussian.covariance(\n            H * p_A.covariance() * H.transpose() + p_B.covariance());\n\n\n        // define the expected mean lambda function\n        // here we use a simple identity function\n        auto mean_f = [&] (const VariateA& x, const VariateB& y)\n        {\n            return f(x, y);\n        };\n\n        // define the expected covariance lambda function\n        auto cov_f = [&] (const VariateA& x, const VariateB& y)\n        {\n            return ((f(x, y) - result_gaussian.mean()) *\n                    (f(x, y) - result_gaussian.mean()).transpose()).eval();\n        };\n\n        // integrate mean and covariance\n        result_gaussian.mean(quadrature.integrate(mean_f, p_A, p_B));\n        result_gaussian.covariance(quadrature.integrate(cov_f, p_A, p_B));\n\n        EXPECT_TRUE(result_gaussian.is_approx(expect_gaussian, eps, true));\n    }\n\n    void propergate_gaussian_Z()\n    {\n        using namespace fl;\n\n        auto result_gaussian = GaussianA(DimA);\n        auto expect_gaussian = GaussianA(DimA);\n        expect_gaussian.mean(f(p_A.mean()));\n        expect_gaussian.covariance(F * p_A.covariance() * F.transpose());\n\n        // define the expected mean lambda function\n        // here we use a simple identity function\n        auto mean_f = [&] (const VariateA& x) { return f(x); };\n\n        enum { SetSize = Quadrature::template size<VariateA>() };\n\n        auto Z = PointSet<decltype(mean_f(VariateA())), SetSize>();\n\n        quadrature.propergate_gaussian(mean_f, p_A, Z);\n\n        auto mean = Z.center();\n        auto Z_c = Z.points();\n        auto W = Z.covariance_weights_vector();\n\n        // integrate mean and covariance\n        result_gaussian.mean(mean);\n        result_gaussian.covariance(Z_c * W.asDiagonal() * Z_c.transpose());\n\n        EXPECT_TRUE(result_gaussian.is_approx(expect_gaussian, eps, true));\n    }\n\n    void propergate_gaussian_X_Z()\n    {\n        using namespace fl;\n\n        auto result_gaussian = GaussianA(DimA);\n        auto expect_gaussian = GaussianA(DimA);\n        expect_gaussian.mean(f(p_A.mean()));\n        expect_gaussian.covariance(F * p_A.covariance() * F.transpose());\n\n        // define the expected mean lambda function\n        // here we use a simple identity function\n        auto mean_f = [&] (const VariateA& x) { return f(x); };\n\n        enum { SetSize = Quadrature::template size<VariateA>() };\n\n        auto Y = PointSet<VariateA, SetSize>();\n        auto Z = PointSet<decltype(mean_f(VariateA())), SetSize>();\n\n        // integrate and check moment results\n        quadrature.propergate_gaussian(mean_f, p_A, Y, Z);\n\n        auto mean = Z.center();\n        auto Z_c = Z.points();\n        auto W = Z.covariance_weights_vector();\n\n        // integrate mean and covariance\n        result_gaussian.mean(mean);\n        result_gaussian.covariance(Z_c * W.asDiagonal() * Z_c.transpose());\n\n        EXPECT_TRUE(result_gaussian.is_approx(expect_gaussian, eps, true));\n\n        // finally check the Y result whether it actually represents the\n        // input Gaussian p_A\n        auto temp_gaussian = GaussianA(DimA);\n\n        // center points and get the mean\n        auto Y_mean = Y.center();\n\n        // compute point covariacne\n        auto Y_c = Y.points();\n        auto Y_W = Y.covariance_weights_vector();\n        auto Y_cov = Y_c * Y_W.asDiagonal() * Y_c.transpose();\n\n        temp_gaussian.mean(Y_mean);\n        temp_gaussian.covariance(Y_cov);\n        EXPECT_TRUE(temp_gaussian.is_approx(p_A, eps, true));\n    }\n\n    void propergate_gaussian_pxy_Z()\n    {\n        using namespace fl;\n\n        auto expect_gaussian = GaussianB(DimB);\n        auto result_gaussian = GaussianB(DimB);\n\n        expect_gaussian.mean(f(p_A.mean(), p_B.mean()));\n        expect_gaussian.covariance(\n            H * p_A.covariance() * H.transpose() + p_B.covariance());\n\n        // define the expected mean lambda function\n        // here we use a simple identity function\n        auto mean_f = [&] (const VariateA& x, const VariateB& y)\n        {\n            return f(x, y);\n        };\n\n        enum { SetSize = Quadrature::template size<VariateA, VariateB>() };\n\n        auto Z = PointSet<decltype(mean_f(VariateA(), VariateB())), SetSize>();\n\n        quadrature.propergate_gaussian(mean_f, p_A, p_B, Z);\n\n        auto mean = Z.center();\n        auto Z_c = Z.points();\n        auto W = Z.covariance_weights_vector();\n\n        // integrate mean and covariance\n        result_gaussian.mean(mean);\n        result_gaussian.covariance(Z_c * W.asDiagonal() * Z_c.transpose());\n\n        EXPECT_TRUE(result_gaussian.is_approx(expect_gaussian, eps, true));\n    }\n\n\n    void propergate_gaussian_pxy_X_Y_Z()\n    {\n        using namespace fl;\n\n        auto expect_gaussian = GaussianB(DimB);\n        auto result_gaussian = GaussianB(DimB);\n\n        expect_gaussian.mean(f(p_A.mean(), p_B.mean()));\n        expect_gaussian.covariance(\n            H * p_A.covariance() * H.transpose() + p_B.covariance());\n\n        // define the expected mean lambda function\n        // here we use a simple identity function\n        auto mean_f = [&] (const VariateA& x, const VariateB& y)\n        {\n            return f(x, y);\n        };\n\n        enum { SetSize = Quadrature::template size<VariateA, VariateB>() };\n\n        auto X = PointSet<VariateA, SetSize>();\n        auto Y = PointSet<VariateB, SetSize>();\n        auto Z = PointSet<decltype(mean_f(VariateA(), VariateB())), SetSize>();\n\n        quadrature.propergate_gaussian(mean_f, p_A, p_B, X, Y, Z);\n\n        auto mean = Z.center();\n        auto Z_c = Z.points();\n        auto W = Z.covariance_weights_vector();\n\n        // integrate mean and covariance\n        result_gaussian.mean(mean);\n        result_gaussian.covariance(Z_c * W.asDiagonal() * Z_c.transpose());\n\n        EXPECT_TRUE(result_gaussian.is_approx(expect_gaussian, eps, true));\n\n        // finally check the X and Y result whether they actually represents the\n        // input Gaussians p_A and p_B, respectively\n        auto temp_gaussian_A = GaussianA(DimA);\n        auto temp_gaussian_B = GaussianB(DimB);\n\n        // center points and get the mean\n        auto X_mean = X.center();\n        auto Y_mean = Y.center();\n\n        // compute point covariacne\n        auto X_c = X.points();\n        auto Y_c = Y.points();\n\n        auto X_W = X.covariance_weights_vector();\n        auto Y_W = Y.covariance_weights_vector();\n\n        auto X_cov = X_c * X_W.asDiagonal() * X_c.transpose();\n        auto Y_cov = Y_c * Y_W.asDiagonal() * Y_c.transpose();\n\n        temp_gaussian_A.mean(X_mean);\n        temp_gaussian_A.covariance(X_cov);\n        EXPECT_TRUE(temp_gaussian_A.is_approx(p_A, eps, true));\n\n        temp_gaussian_B.mean(Y_mean);\n        temp_gaussian_B.covariance(Y_cov);\n        EXPECT_TRUE(temp_gaussian_B.is_approx(p_B, eps, true));\n    }\n\n    void integrate_moments_fx_px()\n    {\n        using namespace fl;\n\n        // compute the expected integration result analytically\n        auto expect_gaussian = GaussianA(DimA);\n        expect_gaussian.mean(f(p_A.mean()));\n        expect_gaussian.covariance(F * p_A.covariance() * F.transpose());\n\n        // create the gaussian which will contail the integration results\n        auto result_gaussian = GaussianA(DimA);\n\n        // define the expected mean lambda function\n        // here we use a simple identity function\n        auto mean_f = [&] (const VariateA& x) { return f(x); };\n\n        // integrate mean and covariance\n        auto mean = typename FirstMomentOf<VariateA>::Type();\n        auto cov = typename SecondMomentOf<VariateA>::Type();\n        quadrature.integrate_moments(mean_f, p_A, mean, cov);\n\n        result_gaussian.mean(mean);\n        result_gaussian.covariance(cov);\n\n        EXPECT_TRUE(result_gaussian.is_approx(expect_gaussian, eps, true));\n    }\n\n    void integrate_moments_fxy_pxy()\n    {\n        using namespace fl;\n\n        // compute the expected integration result analytically\n        auto expect_gaussian = GaussianB(DimB);\n\n        expect_gaussian.mean(f(p_A.mean(), p_B.mean()));\n        expect_gaussian.covariance(\n            H * p_A.covariance() * H.transpose() + p_B.covariance());\n\n        // define the expected mean lambda function\n        // here we use a simple identity function\n        auto mean_f = [&] (const VariateA& x, const VariateB& y)\n        {\n            return f(x, y);\n        };\n\n        // integrate mean and covariance\n        auto mean = typename FirstMomentOf<VariateB>::Type();\n        auto cov = typename SecondMomentOf<VariateB>::Type();\n        quadrature.integrate_moments(mean_f, p_A, p_B, mean, cov);\n\n        // create the gaussian which will contail the integration results\n        auto result_gaussian = GaussianB(DimB);\n\n        result_gaussian.mean(mean);\n        result_gaussian.covariance(cov);\n\n        EXPECT_TRUE(result_gaussian.is_approx(expect_gaussian, eps, true));\n    }\n\nprotected:\n    /* parameter of the linear function f(x) = A*x */\n    MatrixAA F;\n    MatrixAB H;\n\n    /* source Gaussian distributions used within the integrals */\n    GaussianA p_A;\n    GaussianB p_B;\n\n    /* our integrator */\n    Quadrature quadrature;\n\n    fl::Real eps;\n};\n\nTYPED_TEST_CASE_P(SigmaPointQuadratureTests);\n\nTYPED_TEST_P(SigmaPointQuadratureTests, integrate_fx_px)\n{\n    TestFixture::integrate_fx_px();\n}\n\nTYPED_TEST_P(SigmaPointQuadratureTests, integrate_fxy_pxy)\n{\n    TestFixture::integrate_fxy_pxy();\n}\n\nTYPED_TEST_P(SigmaPointQuadratureTests, propergate_gaussian_Z)\n{\n    TestFixture::propergate_gaussian_Z();\n}\n\nTYPED_TEST_P(SigmaPointQuadratureTests, propergate_gaussian_X_Z)\n{\n    TestFixture::propergate_gaussian_X_Z();\n}\n\nTYPED_TEST_P(SigmaPointQuadratureTests, propergate_gaussian_pxy_Z)\n{\n    TestFixture::propergate_gaussian_pxy_Z();\n}\n\nTYPED_TEST_P(SigmaPointQuadratureTests, propergate_gaussian_pxy_X_Y_Z)\n{\n    TestFixture::propergate_gaussian_pxy_X_Y_Z();\n}\n\nTYPED_TEST_P(SigmaPointQuadratureTests, integrate_moments_fx_px)\n{\n    TestFixture::integrate_moments_fx_px();\n}\n\nTYPED_TEST_P(SigmaPointQuadratureTests, integrate_moments_fxy_pxy)\n{\n    TestFixture::integrate_moments_fxy_pxy();\n}\n\nREGISTER_TYPED_TEST_CASE_P(SigmaPointQuadratureTests,\n                           integrate_fx_px,\n                           integrate_fxy_pxy,\n                           propergate_gaussian_Z,\n                           propergate_gaussian_X_Z,\n                           propergate_gaussian_pxy_Z,\n                           propergate_gaussian_pxy_X_Y_Z,\n                           integrate_moments_fx_px,\n                           integrate_moments_fxy_pxy);\n\nnamespace internal\n{\n\n// Transform configuration selection helper\ntemplate <typename T> struct TransformSelection;\n\n// TransformSelection for MonteCarlo integration\ntemplate <typename PSP>\nstruct TransformSelection<fl::MonteCarloTransform<PSP>>\n{\n    static constexpr fl::Real epsilon = fl::Real(0.5);\n    typedef fl::MonteCarloTransform<PSP> Transform;\n};\n\n// TransformSelection for deterministic Unscented integration\ntemplate <> struct TransformSelection<fl::UnscentedTransform>\n{\n    static constexpr fl::Real epsilon = fl::Real(1.e-9);\n    typedef fl::UnscentedTransform Transform;\n};\n\n}\n\ntemplate <int DimensionA, int DimensionB, typename Transform>\nstruct TestConfiguration\n{\n    enum : signed int\n    {\n        DimA = DimensionA,\n        DimB = DimensionB\n    };\n\n    typedef internal::TransformSelection<Transform> TransformSelection;\n};\n\n", "meta": {"hexsha": "bf0ae2c191938f2b83f30ab626fecf1d5fb8962b", "size": 15301, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/gaussian_filter/sigma_point_quadrature_test.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": "test/gaussian_filter/sigma_point_quadrature_test.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": "test/gaussian_filter/sigma_point_quadrature_test.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": 31.0995934959, "max_line_length": 80, "alphanum_fraction": 0.6441409058, "num_tokens": 3711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.6926419704455589, "lm_q1q2_score": 0.47042767248149564}}
{"text": "// Copyright 2020 Matt Borland\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#include <boost/multiprecision/cpp_bin_float.hpp>\n#include <boost/math/statistics/univariate_statistics.hpp>\n#include <boost/assert.hpp>\n#include <benchmark/benchmark.h>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <execution>\n#include <iostream>\n#include <iterator>\n\ntemplate<class T>\nstd::vector<T> generate_random_vector(std::size_t size, std::size_t seed)\n{\n    if (seed == 0)\n    {\n        std::random_device rd;\n        seed = rd();\n    }\n    std::vector<T> v(size);\n\n    std::mt19937 gen(seed);\n\n    if constexpr (std::is_floating_point<T>::value)\n    {\n        std::normal_distribution<T> dis(0, 1);\n        for (size_t i = 0; i < v.size(); ++i)\n        {\n            v[i] = dis(gen);\n        }\n        return v;\n    }\n    else if constexpr (std::is_integral<T>::value)\n    {\n        // Rescaling by larger than 2 is UB!\n        std::uniform_int_distribution<T> dis(std::numeric_limits<T>::lowest()/2, (std::numeric_limits<T>::max)()/2);\n        for (size_t i = 0; i < v.size(); ++i)\n        {\n            v[i] = dis(gen);\n        }\n        return v;\n    }\n    else if constexpr (boost::is_complex<T>::value)\n    {\n        std::normal_distribution<typename T::value_type> dis(0, 1);\n        for (size_t i = 0; i < v.size(); ++i)\n        {\n            v[i] = {dis(gen), dis(gen)};\n        }\n        return v;\n    }\n    else if constexpr (boost::multiprecision::number_category<T>::value == boost::multiprecision::number_kind_complex)\n    {\n        std::normal_distribution<long double> dis(0, 1);\n        for (size_t i = 0; i < v.size(); ++i)\n        {\n            v[i] = {dis(gen), dis(gen)};\n        }\n        return v;\n    }\n    else if constexpr (boost::multiprecision::number_category<T>::value == boost::multiprecision::number_kind_floating_point)\n    {\n        std::normal_distribution<long double> dis(0, 1);\n        for (size_t i = 0; i < v.size(); ++i)\n        {\n            v[i] = dis(gen);\n        }\n        return v;\n    }\n    else\n    {\n        BOOST_ASSERT_MSG(false, \"Could not identify type for random vector generation.\");\n        return v;\n    }\n}\n\ntemplate<typename T>\nvoid mean(benchmark::State& state)\n{\n    constexpr std::size_t seed {};\n    const std::size_t size = state.range(0);\n    std::vector<T> test_set = generate_random_vector<T>(size, seed);\n\n    for(auto _ : state)\n    {\n        benchmark::DoNotOptimize(boost::math::statistics::mean(std::execution::seq, test_set));\n    }\n    state.SetComplexityN(state.range(0));\n}\n\ntemplate<typename T>\nvoid parallel_mean(benchmark::State& state)\n{\n    constexpr std::size_t seed {};\n    const std::size_t size = state.range(0);\n    std::vector<T> test_set = generate_random_vector<T>(size, seed);\n\n    for(auto _ : state)\n    {\n        benchmark::DoNotOptimize(boost::math::statistics::mean(std::execution::par, test_set));\n    }\n    state.SetComplexityN(state.range(0));\n}\n\ntemplate<typename T>\nvoid variance(benchmark::State& state)\n{\n    constexpr std::size_t seed {};\n    const std::size_t size = state.range(0);\n    std::vector<T> test_set = generate_random_vector<T>(size, seed);\n\n    for(auto _ : state)\n    {\n        benchmark::DoNotOptimize(boost::math::statistics::variance(std::execution::seq, test_set));\n    }\n    state.SetComplexityN(state.range(0));\n}\n\ntemplate<typename T>\nvoid parallel_variance(benchmark::State& state)\n{\n    constexpr std::size_t seed {};\n    const std::size_t size = state.range(0);\n    std::vector<T> test_set = generate_random_vector<T>(size, seed);\n\n    for(auto _ : state)\n    {\n        benchmark::DoNotOptimize(boost::math::statistics::variance(std::execution::par, test_set));\n    }\n    state.SetComplexityN(state.range(0));\n}\n\ntemplate<typename T>\nvoid skewness(benchmark::State& state)\n{\n    constexpr std::size_t seed {};\n    const std::size_t size = state.range(0);\n    std::vector<T> test_set = generate_random_vector<T>(size, seed);\n\n    for(auto _ : state)\n    {\n        benchmark::DoNotOptimize(boost::math::statistics::skewness(std::execution::seq, test_set));\n    }\n    state.SetComplexityN(state.range(0));\n}\n\ntemplate<typename T>\nvoid parallel_skewness(benchmark::State& state)\n{\n    constexpr std::size_t seed {};\n    const std::size_t size = state.range(0);\n    std::vector<T> test_set = generate_random_vector<T>(size, seed);\n\n    for(auto _ : state)\n    {\n        benchmark::DoNotOptimize(boost::math::statistics::skewness(std::execution::par, test_set));\n    }\n    state.SetComplexityN(state.range(0));\n}\n\ntemplate<typename T>\nvoid first_four_moments(benchmark::State& state)\n{\n    constexpr std::size_t seed {};\n    const std::size_t size = state.range(0);\n    std::vector<T> test_set = generate_random_vector<T>(size, seed);\n\n    for(auto _ : state)\n    {\n        benchmark::DoNotOptimize(boost::math::statistics::first_four_moments(std::execution::seq, test_set));\n    }\n    state.SetComplexityN(state.range(0));\n}\n\ntemplate<typename T>\nvoid parallel_first_four_moments(benchmark::State& state)\n{\n    constexpr std::size_t seed {};\n    const std::size_t size = state.range(0);\n    std::vector<T> test_set = generate_random_vector<T>(size, seed);\n\n    for(auto _ : state)\n    {\n        benchmark::DoNotOptimize(boost::math::statistics::first_four_moments(std::execution::par, test_set));\n    }\n    state.SetComplexityN(state.range(0));\n}\n\ntemplate<typename T>\nvoid kurtosis(benchmark::State& state)\n{\n    constexpr std::size_t seed {};\n    const std::size_t size = state.range(0);\n    std::vector<T> test_set = generate_random_vector<T>(size, seed);\n\n    for(auto _ : state)\n    {\n        benchmark::DoNotOptimize(boost::math::statistics::kurtosis(std::execution::seq, test_set));\n    }\n    state.SetComplexityN(state.range(0));\n}\n\ntemplate<typename T>\nvoid parallel_kurtosis(benchmark::State& state)\n{\n    constexpr std::size_t seed {};\n    const std::size_t size = state.range(0);\n    std::vector<T> test_set = generate_random_vector<T>(size, seed);\n\n    for(auto _ : state)\n    {\n        benchmark::DoNotOptimize(boost::math::statistics::kurtosis(std::execution::par, test_set));\n    }\n    state.SetComplexityN(state.range(0));\n}\n\ntemplate<typename T>\nvoid median(benchmark::State& state)\n{\n    constexpr std::size_t seed {};\n    const std::size_t size = state.range(0);\n    std::vector<T> test_set = generate_random_vector<T>(size, seed);\n\n    for(auto _ : state)\n    {\n        benchmark::DoNotOptimize(boost::math::statistics::median(std::execution::seq, test_set));\n    }\n    state.SetComplexityN(state.range(0));\n}\n\ntemplate<typename T>\nvoid parallel_median(benchmark::State& state)\n{\n    constexpr std::size_t seed {};\n    const std::size_t size = state.range(0);\n    std::vector<T> test_set = generate_random_vector<T>(size, seed);\n\n    for(auto _ : state)\n    {\n        benchmark::DoNotOptimize(boost::math::statistics::median(std::execution::par, test_set));\n    }\n    state.SetComplexityN(state.range(0));\n}\n\ntemplate<typename T>\nvoid median_absolute_deviation(benchmark::State& state)\n{\n    constexpr std::size_t seed {};\n    const std::size_t size = state.range(0);\n    std::vector<T> test_set = generate_random_vector<T>(size, seed);\n\n    for(auto _ : state)\n    {\n        benchmark::DoNotOptimize(boost::math::statistics::median_absolute_deviation(std::execution::seq, test_set));\n    }\n    state.SetComplexityN(state.range(0));\n}\n\ntemplate<typename T>\nvoid parallel_median_absolute_deviation(benchmark::State& state)\n{\n    constexpr std::size_t seed {};\n    const std::size_t size = state.range(0);\n    std::vector<T> test_set = generate_random_vector<T>(size, seed);\n\n    for(auto _ : state)\n    {\n        benchmark::DoNotOptimize(boost::math::statistics::median_absolute_deviation(std::execution::par, test_set));\n    }\n    state.SetComplexityN(state.range(0));\n}\n\ntemplate<typename T>\nvoid gini_coefficient(benchmark::State& state)\n{\n    constexpr std::size_t seed {};\n    const std::size_t size = state.range(0);\n    std::vector<T> test_set = generate_random_vector<T>(size, seed);\n\n    for(auto _ : state)\n    {\n        benchmark::DoNotOptimize(boost::math::statistics::gini_coefficient(std::execution::seq, test_set));\n    }\n    state.SetComplexityN(state.range(0));\n}\n\ntemplate<typename T>\nvoid parallel_gini_coefficient(benchmark::State& state)\n{\n    constexpr std::size_t seed {};\n    const std::size_t size = state.range(0);\n    std::vector<T> test_set = generate_random_vector<T>(size, seed);\n\n    for(auto _ : state)\n    {\n        benchmark::DoNotOptimize(boost::math::statistics::gini_coefficient(std::execution::par, test_set));\n    }\n    state.SetComplexityN(state.range(0));\n}\n\ntemplate<typename T>\nvoid interquartile_range(benchmark::State& state)\n{\n    constexpr std::size_t seed {};\n    const std::size_t size = state.range(0);\n    std::vector<T> test_set = generate_random_vector<T>(size, seed);\n\n    for(auto _ : state)\n    {\n        benchmark::DoNotOptimize(boost::math::statistics::interquartile_range(std::execution::seq, test_set));\n    }\n    state.SetComplexityN(state.range(0));\n}\n\ntemplate<typename T>\nvoid parallel_interquartile_range(benchmark::State& state)\n{\n    constexpr std::size_t seed {};\n    const std::size_t size = state.range(0);\n    std::vector<T> test_set = generate_random_vector<T>(size, seed);\n\n    for(auto _ : state)\n    {\n        benchmark::DoNotOptimize(boost::math::statistics::interquartile_range(std::execution::par, test_set));\n    }\n    state.SetComplexityN(state.range(0));\n}\n\ntemplate<typename T>\nvoid mode(benchmark::State& state)\n{\n    constexpr std::size_t seed {};\n    const std::size_t size = state.range(0);\n    std::vector<T> test_set = generate_random_vector<T>(size, seed);\n    std::vector<T> modes;\n\n    for(auto _ : state)\n    {\n        benchmark::DoNotOptimize(boost::math::statistics::mode(std::execution::seq, test_set, std::back_inserter(modes)));\n    }\n    state.SetComplexityN(state.range(0));\n}\n\ntemplate<typename T>\nvoid parallel_mode(benchmark::State& state)\n{\n    constexpr std::size_t seed {};\n    const std::size_t size = state.range(0);\n    std::vector<T> test_set = generate_random_vector<T>(size, seed);\n    std::vector<T> modes;\n\n    for(auto _ : state)\n    {\n        benchmark::DoNotOptimize(boost::math::statistics::mode(std::execution::par, test_set, std::back_inserter(modes)));\n    }\n    state.SetComplexityN(state.range(0));\n}\n\n// Mean\nBENCHMARK_TEMPLATE(mean, int)->RangeMultiplier(2)->Range(1 << 6, 1 << 20)->Complexity(benchmark::oN)->UseRealTime();\nBENCHMARK_TEMPLATE(parallel_mean, int)->RangeMultiplier(2)->Range(1 << 6, 1 << 20)->Complexity(benchmark::oN)->UseRealTime();\nBENCHMARK_TEMPLATE(mean, double)->RangeMultiplier(2)->Range(1 << 6, 1 << 20)->Complexity(benchmark::oN)->UseRealTime();\nBENCHMARK_TEMPLATE(parallel_mean, double)->RangeMultiplier(2)->Range(1 << 6, 1 << 20)->Complexity(benchmark::oN)->UseRealTime();\n\n// Variance\nBENCHMARK_TEMPLATE(variance, int)->RangeMultiplier(2)->Range(1 << 6, 1 << 20)->Complexity(benchmark::oN)->UseRealTime();\nBENCHMARK_TEMPLATE(parallel_variance, int)->RangeMultiplier(2)->Range(1 << 6, 1 << 20)->Complexity(benchmark::oN)->UseRealTime();\nBENCHMARK_TEMPLATE(variance, double)->RangeMultiplier(2)->Range(1 << 6, 1 << 20)->Complexity(benchmark::oN)->UseRealTime();\nBENCHMARK_TEMPLATE(parallel_variance, double)->RangeMultiplier(2)->Range(1 << 6, 1 << 20)->Complexity(benchmark::oN)->UseRealTime();\n\n// Skewness\nBENCHMARK_TEMPLATE(skewness, int)->RangeMultiplier(2)->Range(1 << 6, 1 << 20)->Complexity(benchmark::oN)->UseRealTime();\nBENCHMARK_TEMPLATE(parallel_skewness, int)->RangeMultiplier(2)->Range(1 << 6, 1 << 20)->Complexity(benchmark::oN)->UseRealTime();\nBENCHMARK_TEMPLATE(skewness, double)->RangeMultiplier(2)->Range(1 << 6, 1 << 20)->Complexity(benchmark::oN)->UseRealTime();\nBENCHMARK_TEMPLATE(parallel_skewness, double)->RangeMultiplier(2)->Range(1 << 6, 1 << 20)->Complexity(benchmark::oN)->UseRealTime();\n\n// First four moments\nBENCHMARK_TEMPLATE(first_four_moments, int)->RangeMultiplier(2)->Range(1 << 6, 1 << 20)->Complexity(benchmark::oN)->UseRealTime();\nBENCHMARK_TEMPLATE(parallel_first_four_moments, int)->RangeMultiplier(2)->Range(1 << 6, 1 << 20)->Complexity(benchmark::oN)->UseRealTime();\nBENCHMARK_TEMPLATE(first_four_moments, double)->RangeMultiplier(2)->Range(1 << 6, 1 << 20)->Complexity(benchmark::oN)->UseRealTime();\nBENCHMARK_TEMPLATE(parallel_first_four_moments, double)->RangeMultiplier(2)->Range(1 << 6, 1 << 20)->Complexity(benchmark::oN)->UseRealTime();\n\n// Kurtosis\nBENCHMARK_TEMPLATE(kurtosis, int)->RangeMultiplier(2)->Range(1 << 6, 1 << 20)->Complexity(benchmark::oN)->UseRealTime();\nBENCHMARK_TEMPLATE(parallel_kurtosis, int)->RangeMultiplier(2)->Range(1 << 6, 1 << 20)->Complexity(benchmark::oN)->UseRealTime();\nBENCHMARK_TEMPLATE(kurtosis, double)->RangeMultiplier(2)->Range(1 << 6, 1 << 20)->Complexity(benchmark::oN)->UseRealTime();\nBENCHMARK_TEMPLATE(parallel_kurtosis, double)->RangeMultiplier(2)->Range(1 << 6, 1 << 20)->Complexity(benchmark::oN)->UseRealTime();\n\n// Median\nBENCHMARK_TEMPLATE(median, int)->RangeMultiplier(2)->Range(1 << 6, 1 << 20)->Complexity(benchmark::oN)->UseRealTime();\nBENCHMARK_TEMPLATE(parallel_median, int)->RangeMultiplier(2)->Range(1 << 6, 1 << 20)->Complexity(benchmark::oN)->UseRealTime();\nBENCHMARK_TEMPLATE(median, double)->RangeMultiplier(2)->Range(1 << 6, 1 << 20)->Complexity(benchmark::oN)->UseRealTime();\nBENCHMARK_TEMPLATE(parallel_median, double)->RangeMultiplier(2)->Range(1 << 6, 1 << 20)->Complexity(benchmark::oN)->UseRealTime();\n\n// Median absolute deviation\nBENCHMARK_TEMPLATE(median_absolute_deviation, int)->RangeMultiplier(2)->Range(1 << 6, 1 << 20)->Complexity(benchmark::oN)->UseRealTime();\nBENCHMARK_TEMPLATE(parallel_median_absolute_deviation, int)->RangeMultiplier(2)->Range(1 << 6, 1 << 20)->Complexity(benchmark::oN)->UseRealTime();\nBENCHMARK_TEMPLATE(median_absolute_deviation, double)->RangeMultiplier(2)->Range(1 << 6, 1 << 20)->Complexity(benchmark::oN)->UseRealTime();\nBENCHMARK_TEMPLATE(parallel_median_absolute_deviation, double)->RangeMultiplier(2)->Range(1 << 6, 1 << 20)->Complexity(benchmark::oN)->UseRealTime();\n\n// Gini Coefficient\nBENCHMARK_TEMPLATE(gini_coefficient, int)->RangeMultiplier(2)->Range(1 << 6, 1 << 20)->Complexity(benchmark::oN)->UseRealTime();\nBENCHMARK_TEMPLATE(parallel_gini_coefficient, int)->RangeMultiplier(2)->Range(1 << 6, 1 << 20)->Complexity(benchmark::oN)->UseRealTime();\nBENCHMARK_TEMPLATE(gini_coefficient, double)->RangeMultiplier(2)->Range(1 << 6, 1 << 20)->Complexity(benchmark::oN)->UseRealTime();\nBENCHMARK_TEMPLATE(parallel_gini_coefficient, double)->RangeMultiplier(2)->Range(1 << 6, 1 << 20)->Complexity(benchmark::oN)->UseRealTime();\n\n// Interquartile Range - Only floating point values implemented\nBENCHMARK_TEMPLATE(interquartile_range, double)->RangeMultiplier(2)->Range(1 << 6, 1 << 20)->Complexity(benchmark::oN)->UseRealTime();\nBENCHMARK_TEMPLATE(parallel_interquartile_range, double)->RangeMultiplier(2)->Range(1 << 6, 1 << 20)->Complexity(benchmark::oN)->UseRealTime();\n\n// Mode\nBENCHMARK_TEMPLATE(mode, int)->RangeMultiplier(2)->Range(1 << 6, 1 << 20)->Complexity(benchmark::oN)->UseRealTime();\nBENCHMARK_TEMPLATE(parallel_mode, int)->RangeMultiplier(2)->Range(1 << 6, 1 << 20)->Complexity(benchmark::oN)->UseRealTime();\nBENCHMARK_TEMPLATE(mode, double)->RangeMultiplier(2)->Range(1 << 6, 1 << 20)->Complexity(benchmark::oN)->UseRealTime();\nBENCHMARK_TEMPLATE(parallel_mode, double)->RangeMultiplier(2)->Range(1 << 6, 1 << 20)->Complexity(benchmark::oN)->UseRealTime();\n\nBENCHMARK_MAIN();\n", "meta": {"hexsha": "ed05a113a20b40a307b84951bb2a97b965de4fb1", "size": 15698, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/reporting/performance/univariate_statistics_performance.cpp", "max_stars_repo_name": "anarthal/boost-unix-mirror", "max_stars_repo_head_hexsha": "8c34eb2fe471d6c3113c680c1fbef29e7a8063a0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-12T13:52:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-12T13:52:18.000Z", "max_issues_repo_path": "libs/math/reporting/performance/univariate_statistics_performance.cpp", "max_issues_repo_name": "anarthal/boost-unix-mirror", "max_issues_repo_head_hexsha": "8c34eb2fe471d6c3113c680c1fbef29e7a8063a0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-10-21T12:42:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-03T08:41:31.000Z", "max_forks_repo_path": "Libs/boost_1_76_0/libs/math/reporting/performance/univariate_statistics_performance.cpp", "max_forks_repo_name": "Antd23rus/S2DE", "max_forks_repo_head_hexsha": "47cc7151c2934cd8f0399a9856c1e54894571553", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-24T08:55:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-24T08:55:27.000Z", "avg_line_length": 36.9364705882, "max_line_length": 149, "alphanum_fraction": 0.6828895401, "num_tokens": 4273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893353516963, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.47035511332650887}}
{"text": "/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center.\n\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http://www.mitk.org for details.\n\n===================================================================*/\n\n#include \"mitkConnectomicsStatisticsCalculator.h\"\n#include \"mitkConnectomicsNetworkConverter.h\"\n\n#include <numeric>\n\n#include <boost/graph/clustering_coefficient.hpp>\n\n#ifdef _MSC_VER\n# pragma warning(push)\n# pragma warning(disable: 4172)\n#endif\n#include <boost/graph/connected_components.hpp>\n#include <boost/graph/betweenness_centrality.hpp>\n\n#ifdef _MSC_VER\n# pragma warning(pop)\n#endif\n\n#include <boost/graph/visitors.hpp>\n\n#include \"vnl/algo/vnl_symmetric_eigensystem.h\"\n\ntemplate<typename GraphType>\nclass all_pairs_shortest_recorder : public boost::default_bfs_visitor\n{\npublic:\n  typedef typename boost::graph_traits<GraphType>::vertex_descriptor VertexType;\n  typedef typename boost::graph_traits<GraphType>::edge_descriptor EdgeType;\n\n  all_pairs_shortest_recorder(int* dist, int &max, unsigned int &size)\n  {\n    d = dist;\n    ecc = &max;\n    component_size = &size;\n  }\n\n  void tree_edge(EdgeType edge, const GraphType& graph) {\n    VertexType u = boost::source(edge, graph);\n    VertexType v = boost::target(edge, graph);\n    d[v] = d[u] + 1;\n    *ecc = d[v];\n    *component_size = *component_size + 1;\n  }\nprivate:\n  int* d;\n  int* ecc;\n  unsigned int* component_size;\n};\n\nmitk::ConnectomicsStatisticsCalculator::ConnectomicsStatisticsCalculator()\n  : m_Network( nullptr )\n  , m_NumberOfVertices( 0 )\n  , m_NumberOfEdges( 0 )\n  , m_AverageDegree( 0.0 )\n  , m_ConnectionDensity( 0.0 )\n  , m_NumberOfConnectedComponents( 0 )\n  , m_AverageComponentSize( 0.0 )\n  , m_Components(0)\n  , m_LargestComponentSize( 0 )\n  , m_HopPlotExponent( 0.0 )\n  , m_EffectiveHopDiameter( 0.0 )\n  , m_VectorOfClusteringCoefficientsC( 0 )\n  , m_VectorOfClusteringCoefficientsD( 0 )\n  , m_VectorOfClusteringCoefficientsE( 0 )\n  , m_AverageClusteringCoefficientsC( 0.0 )\n  , m_AverageClusteringCoefficientsD( 0.0 )\n  , m_AverageClusteringCoefficientsE( 0.0 )\n  , m_VectorOfVertexBetweennessCentralities( 0 )\n  , m_PropertyMapOfVertexBetweennessCentralities( )\n  , m_AverageVertexBetweennessCentrality( 0.0 )\n  , m_VectorOfEdgeBetweennessCentralities( 0 )\n  , m_PropertyMapOfEdgeBetweennessCentralities( )\n  , m_AverageEdgeBetweennessCentrality( 0.0 )\n  , m_NumberOfIsolatedPoints( 0 )\n  , m_RatioOfIsolatedPoints( 0.0 )\n  , m_NumberOfEndPoints( 0 )\n  , m_RatioOfEndPoints( 0.0 )\n  , m_VectorOfEccentrities( 0 )\n  , m_VectorOfEccentrities90( 0 )\n  , m_VectorOfAveragePathLengths( 0.0 )\n  , m_Diameter( 0 )\n  , m_Diameter90( 0 )\n  , m_Radius( 0 )\n  , m_Radius90( 0 )\n  , m_AverageEccentricity( 0.0 )\n  , m_AverageEccentricity90( 0.0 )\n  , m_AveragePathLength( 0.0 )\n  , m_NumberOfCentralPoints( 0 )\n  , m_RatioOfCentralPoints( 0.0 )\n  , m_VectorOfSortedEigenValues( 0 )\n  , m_SpectralRadius( 0.0 )\n  , m_SecondLargestEigenValue( 0.0 )\n  , m_AdjacencyTrace( 0.0 )\n  , m_AdjacencyEnergy( 0.0 )\n  , m_VectorOfSortedLaplacianEigenValues( 0 )\n  , m_LaplacianTrace( 0.0 )\n  , m_LaplacianEnergy( 0.0 )\n  , m_LaplacianSpectralGap( 0.0 )\n  , m_VectorOfSortedNormalizedLaplacianEigenValues( 0 )\n  , m_NormalizedLaplacianTrace( 0.0 )\n  , m_NormalizedLaplacianEnergy( 0.0 )\n  , m_NormalizedLaplacianNumberOf2s( 0 )\n  , m_NormalizedLaplacianNumberOf1s( 0 )\n  , m_NormalizedLaplacianNumberOf0s( 0 )\n  , m_NormalizedLaplacianLowerSlope( 0.0 )\n  , m_NormalizedLaplacianUpperSlope( 0.0 )\n  , m_SmallWorldness( 0.0 )\n{\n}\n\nmitk::ConnectomicsStatisticsCalculator::~ConnectomicsStatisticsCalculator()\n{\n}\n\nvoid mitk::ConnectomicsStatisticsCalculator::Update()\n{\n  CalculateNumberOfVertices();\n  CalculateNumberOfEdges();\n  CalculateAverageDegree();\n  CalculateConnectionDensity();\n  CalculateNumberOfConnectedComponents();\n  CalculateAverageComponentSize();\n  CalculateLargestComponentSize();\n  CalculateRatioOfNodesInLargestComponent();\n  CalculateHopPlotValues();\n  CalculateClusteringCoefficients();\n  CalculateBetweennessCentrality();\n  CalculateIsolatedAndEndPoints();\n  CalculateShortestPathMetrics();\n  CalculateSpectralMetrics();\n  CalculateLaplacianMetrics();\n  CalculateNormalizedLaplacianMetrics();\n  CalculateSmallWorldness();\n}\n\nvoid mitk::ConnectomicsStatisticsCalculator::CalculateNumberOfVertices()\n{\n  m_NumberOfVertices = boost::num_vertices( *(m_Network->GetBoostGraph()) );\n}\n\nvoid mitk::ConnectomicsStatisticsCalculator::CalculateNumberOfEdges()\n{\n  m_NumberOfEdges = boost::num_edges(  *(m_Network->GetBoostGraph()) );\n}\n\nvoid  mitk::ConnectomicsStatisticsCalculator::CalculateAverageDegree()\n{\n  m_AverageDegree = ( ( (double) m_NumberOfEdges * 2.0 ) / (double) m_NumberOfVertices );\n}\n\nvoid mitk::ConnectomicsStatisticsCalculator::CalculateConnectionDensity()\n{\n  double numberOfPossibleEdges = (double) m_NumberOfVertices * ( (double) m_NumberOfVertices - 1 ) / 2;\n\n  m_ConnectionDensity = (double) m_NumberOfEdges / numberOfPossibleEdges;\n}\n\nvoid mitk::ConnectomicsStatisticsCalculator::CalculateNumberOfConnectedComponents()\n{\n  m_Components.resize( m_NumberOfVertices );\n  m_NumberOfConnectedComponents = boost::connected_components( *(m_Network->GetBoostGraph()), &m_Components[0] );\n}\n\nvoid mitk::ConnectomicsStatisticsCalculator::CalculateAverageComponentSize()\n{\n  m_AverageComponentSize = (double) m_NumberOfVertices / (double) m_NumberOfConnectedComponents ;\n}\n\nvoid mitk::ConnectomicsStatisticsCalculator::CalculateLargestComponentSize()\n{\n  m_LargestComponentSize = 0;\n  std::vector<unsigned int> bins( m_NumberOfConnectedComponents );\n\n  for(unsigned int i=0; i < m_NumberOfVertices; i++)\n  {\n    bins[ m_Components[i] ]++;\n  }\n\n  for(unsigned int i=0; i < m_NumberOfConnectedComponents; i++)\n  {\n    if (bins[i] > m_LargestComponentSize )\n    {\n      m_LargestComponentSize = bins[i];\n    }\n  }\n}\n\nvoid mitk::ConnectomicsStatisticsCalculator::CalculateRatioOfNodesInLargestComponent()\n{\n  m_RatioOfNodesInLargestComponent = (double) m_LargestComponentSize / (double) m_NumberOfVertices ;\n}\n\nvoid mitk::ConnectomicsStatisticsCalculator::CalculateHopPlotValues()\n{\n  std::vector<int> bins( m_NumberOfVertices );\n\n  VertexIteratorType vi, vi_end;\n  unsigned int index( 0 );\n\n  for( boost::tie( vi, vi_end ) = boost::vertices( *(m_Network->GetBoostGraph()) ); vi != vi_end; ++vi)\n  {\n    std::vector<int> distances(m_NumberOfVertices, 0);\n    int max_distance = 0;\n    VertexDescriptorType src = *vi;\n    distances[src] = 0;\n    unsigned int size = 0;\n\n    boost::breadth_first_search(*(m_Network->GetBoostGraph()), src,\n      visitor(all_pairs_shortest_recorder< NetworkType >\n      (&distances[0], max_distance, size)));\n\n    for(index=0; index < distances.size(); index++)\n    {\n      if(distances[index] > 0)\n      {\n        bins[distances[index]]++;\n      }\n    }\n  }\n\n  bins[0] = m_NumberOfVertices;\n  for(index=1; index < bins.size(); index++)\n  {\n    bins[index] = bins[index] + bins[index-1];\n  }\n\n  int counter = 0;\n  double C=0, D=0, E=0, F=0;\n\n  for (unsigned int i=1; i<bins.size()-1; i++)\n  {\n    counter ++;\n    if(fabs(log(double(bins[i+1])) - log(double(bins[i]))) < 0.0000001)\n    {\n      break;\n    }\n  }\n\n  for (int i=1; i<=counter; i++)\n  {\n    double x = log(double(i));\n    double y = log(double(bins[i]));\n    C += x;\n    D += y;\n    E += x * y;\n    F += x * x;\n  }\n  double b = (D*F - C*E)/(F*counter - C*C);\n  m_HopPlotExponent = (E - b*C)/F;\n\n  m_EffectiveHopDiameter =\n    std::pow( ( m_NumberOfVertices * m_NumberOfVertices )\n    / ( m_NumberOfVertices + 2 * m_NumberOfEdges ), 1.0 / m_HopPlotExponent );\n}\n\nvoid mitk::ConnectomicsStatisticsCalculator::CalculateClusteringCoefficients()\n{\n  VertexIteratorType vi, vi_end;\n  std::vector<double> m_VectorOfClusteringCoefficientsC;\n  std::vector<double> m_VectorOfClusteringCoefficientsD;\n  std::vector<double> m_VectorOfClusteringCoefficientsE;\n  typedef std::set<VertexDescriptorType> NeighborSetType;\n  typedef NetworkType::out_edge_iterator OutEdgeIterType;\n\n  for(boost::tie(vi,vi_end) = boost::vertices( *(m_Network->GetBoostGraph()) ); vi!=vi_end; ++vi)\n  {\n    // Get the list of vertices which are in the neighborhood of vi.\n    std::pair<AdjacencyIteratorType, AdjacencyIteratorType> adjacent =\n      boost::adjacent_vertices(*vi, *(m_Network->GetBoostGraph()) );\n\n    //Populate a set with the neighbors of vi\n    NeighborSetType neighbors;\n    for(; adjacent.first!=adjacent.second; ++adjacent.first)\n    {\n      neighbors.insert(*adjacent.first);\n    }\n\n    // Now, count the edges between vertices in the neighborhood.\n    unsigned int neighborhood_edge_count = 0;\n    if(neighbors.size() > 0)\n    {\n      NeighborSetType::iterator iter;\n      for(iter = neighbors.begin(); iter != neighbors.end(); ++iter)\n      {\n        std::pair<OutEdgeIterType, OutEdgeIterType> oe = out_edges(*iter, *(m_Network->GetBoostGraph()) );\n        for(; oe.first != oe.second; ++oe.first)\n        {\n          if(neighbors.find(target(*oe.first, *(m_Network->GetBoostGraph()) )) != neighbors.end())\n          {\n            ++neighborhood_edge_count;\n          }\n        }\n      }\n      neighborhood_edge_count /= 2;\n    }\n    //Clustering Coefficienct C,E\n    if(neighbors.size() > 1)\n    {\n      double num   = neighborhood_edge_count;\n      double denum = neighbors.size() * (neighbors.size()-1)/2;\n      m_VectorOfClusteringCoefficientsC.push_back( num / denum);\n      m_VectorOfClusteringCoefficientsE.push_back( num / denum);\n    }\n    else\n    {\n      m_VectorOfClusteringCoefficientsC.push_back(0.0);\n    }\n\n    //Clustering Coefficienct D\n    if(neighbors.size() > 0)\n    {\n      double num   = neighbors.size() + neighborhood_edge_count;\n      double denum = ( (neighbors.size()+1) * neighbors.size()) / 2;\n      m_VectorOfClusteringCoefficientsD.push_back( num / denum);\n    }\n    else\n    {\n      m_VectorOfClusteringCoefficientsD.push_back(0.0);\n    }\n  }\n\n  // Average Clustering coefficienies:\n  m_AverageClusteringCoefficientsC = std::accumulate(m_VectorOfClusteringCoefficientsC.begin(),\n    m_VectorOfClusteringCoefficientsC.end(),\n    0.0) / m_NumberOfVertices;\n\n  m_AverageClusteringCoefficientsD = std::accumulate(m_VectorOfClusteringCoefficientsD.begin(),\n    m_VectorOfClusteringCoefficientsD.end(),\n    0.0) / m_NumberOfVertices;\n\n  m_AverageClusteringCoefficientsE = std::accumulate(m_VectorOfClusteringCoefficientsE.begin(),\n    m_VectorOfClusteringCoefficientsE.end(),\n    0.0) / m_VectorOfClusteringCoefficientsE.size();\n}\n\nvoid mitk::ConnectomicsStatisticsCalculator::CalculateBetweennessCentrality()\n{\n  // std::map used for convenient initialization\n  EdgeIndexStdMapType stdEdgeIndex;\n  // associative property map needed for iterator property map-wrapper\n  EdgeIndexMapType edgeIndex(stdEdgeIndex);\n\n  EdgeIteratorType iterator, end;\n\n  // sets iterator to start end end to end\n  boost::tie(iterator, end) = boost::edges( *(m_Network->GetBoostGraph()) );\n\n  int i(0);\n  for ( ; iterator != end; ++iterator, ++i)\n  {\n    stdEdgeIndex.insert(std::pair< EdgeDescriptorType, int >( *iterator, i));\n  }\n\n  // Define EdgeCentralityMap\n  m_VectorOfEdgeBetweennessCentralities.resize( m_NumberOfEdges, 0.0);\n  // Create the external property map\n  m_PropertyMapOfEdgeBetweennessCentralities = EdgeIteratorPropertyMapType(m_VectorOfEdgeBetweennessCentralities.begin(), edgeIndex);\n\n  // Define VertexCentralityMap\n  VertexIndexMapType vertexIndex = get(boost::vertex_index, *(m_Network->GetBoostGraph()) );\n  m_VectorOfVertexBetweennessCentralities.resize( m_NumberOfVertices, 0.0);\n  // Create the external property map\n  m_PropertyMapOfVertexBetweennessCentralities = VertexIteratorPropertyMapType(m_VectorOfVertexBetweennessCentralities.begin(), vertexIndex);\n\n  boost::brandes_betweenness_centrality( *(m_Network->GetBoostGraph()),\n    m_PropertyMapOfVertexBetweennessCentralities, m_PropertyMapOfEdgeBetweennessCentralities );\n\n  m_AverageVertexBetweennessCentrality = std::accumulate(m_VectorOfVertexBetweennessCentralities.begin(),\n    m_VectorOfVertexBetweennessCentralities.end(),\n    0.0) / (double) m_NumberOfVertices;\n\n  m_AverageEdgeBetweennessCentrality = std::accumulate(m_VectorOfEdgeBetweennessCentralities.begin(),\n    m_VectorOfEdgeBetweennessCentralities.end(),\n    0.0) / (double) m_NumberOfEdges;\n}\n\nvoid mitk::ConnectomicsStatisticsCalculator::CalculateIsolatedAndEndPoints()\n{\n  m_NumberOfIsolatedPoints = 0;\n  m_NumberOfEndPoints = 0;\n\n  VertexIteratorType vi, vi_end;\n  for( boost::tie(vi,vi_end) = boost::vertices( *(m_Network->GetBoostGraph()) ); vi!=vi_end; ++vi)\n  {\n    int degree = boost::out_degree(*vi, *(m_Network->GetBoostGraph()) );\n    if(degree == 0)\n    {\n      m_NumberOfIsolatedPoints++;\n    }\n    else if (degree == 1)\n    {\n      m_NumberOfEndPoints++;\n    }\n  }\n\n  m_RatioOfEndPoints = (double) m_NumberOfEndPoints / (double) m_NumberOfVertices;\n  m_RatioOfIsolatedPoints = (double) m_NumberOfIsolatedPoints / (double) m_NumberOfVertices;\n}\n\n\n/**\n* Calculates Shortest Path Related metrics of the graph.  The\n* function runs a BFS from each node to find out the shortest\n* distances to other nodes in the graph. The maximum of this distance\n* is called the eccentricity of that node. The maximum eccentricity\n* in the graph is called diameter and the minimum eccentricity is\n* called the radius of the graph.  Central points are those nodes\n* having eccentricity equals to radius.\n*/\nvoid mitk::ConnectomicsStatisticsCalculator::CalculateShortestPathMetrics()\n{\n  //for all vertices:\n  VertexIteratorType vi, vi_end;\n\n  //store the eccentricities in a vector.\n  m_VectorOfEccentrities.resize( m_NumberOfVertices );\n  m_VectorOfEccentrities90.resize( m_NumberOfVertices );\n  m_VectorOfAveragePathLengths.resize( m_NumberOfVertices );\n\n  //assign diameter and radius while iterating over the ecccencirities.\n  m_Diameter              = 0;\n  m_Diameter90            = 0;\n  m_Radius                = std::numeric_limits<unsigned int>::max();\n  m_Radius90              = std::numeric_limits<unsigned int>::max();\n  m_AverageEccentricity   = 0.0;\n  m_AverageEccentricity90 = 0.0;\n  m_AveragePathLength     = 0.0;\n\n  //The size of the giant connected component so far.\n  unsigned int giant_component_size = 0;\n  VertexDescriptorType radius_src(0);\n\n  //Loop over the vertices\n  for( boost::tie(vi, vi_end) = boost::vertices( *(m_Network->GetBoostGraph()) ); vi!=vi_end; ++vi)\n  {\n    //We are going to start a BFS, initialize the neccessary\n    //structures for that.  Store the distances of nodes from the\n    //source in distance vector. The maximum distance is stored in\n    //max. The BFS will start from the node that vi is pointing, that\n    //is the src is *vi. We also init the distance of the src node to\n    //itself to 0. size gives the number of nodes discovered during\n    //this BFS.\n    std::vector<int> distances( m_NumberOfVertices );\n    int max_distance = 0;\n    VertexDescriptorType src = *vi;\n    distances[src] = 0;\n    unsigned int size = 0;\n\n    breadth_first_search(*(m_Network->GetBoostGraph()), src,\n      visitor(all_pairs_shortest_recorder<NetworkType>\n      (&distances[0], max_distance, size)));\n    // vertex vi has eccentricity equal to max_distance\n    m_VectorOfEccentrities[src] = max_distance;\n\n    //check whether there is any change in the diameter or the radius.\n    //note that the diameter we are calculating here is also the\n    //diameter of the giant connected component!\n    if(m_VectorOfEccentrities[src] > m_Diameter)\n    {\n      m_Diameter = m_VectorOfEccentrities[src];\n    }\n\n    //The radius should be calculated on the largest connected\n    //component, otherwise it is very likely that radius will be 1.\n    //We change the value of the radius only if this is the giant\n    //connected component so far. After all the eccentricities are\n    //found we should loop over this connected component and find the\n    //minimum eccentricity which is the radius. So we keep the src\n    //node, so that we can find the connected component later on.\n    if(size > giant_component_size)\n    {\n      giant_component_size = size;\n      radius_src = src;\n    }\n\n    //Calculate in how many hops we can reach 90 percent of the\n    //nodes. We store the number of hops we can reach in h hops in the\n    //bucket vector. That is bucket[h] gives the number of nodes\n    //reachable in exactly h hops. sum of bucket[i<h] gives the number\n    //of nodes that are reachable in less than h hops. We also\n    //calculate sum of the distances from this node to every single\n    //other node in the graph.\n    int reachable90 = std::ceil((double)size * 0.9);\n    std::vector <int> bucket (max_distance+1);\n    int counter = 0;\n    for(unsigned int i=0; i<distances.size(); i++)\n    {\n      if(distances[i]>0)\n      {\n        bucket[distances[i]]++;\n        m_VectorOfAveragePathLengths[src] += distances[i];\n        counter ++;\n      }\n    }\n    if(counter > 0)\n    {\n      m_VectorOfAveragePathLengths[src] = m_VectorOfAveragePathLengths[src] / counter;\n    }\n\n    int eccentricity90 = 0;\n    while(reachable90 > 0)\n    {\n      eccentricity90 ++;\n      reachable90 = reachable90 - bucket[eccentricity90];\n    }\n    // vertex vi has eccentricity90 equal to eccentricity90\n    m_VectorOfEccentrities90[src] = eccentricity90;\n    if(m_VectorOfEccentrities90[src] > m_Diameter90)\n    {\n      m_Diameter90 = m_VectorOfEccentrities90[src];\n    }\n  }\n\n  //We are going to calculate the radius now. We stored the src node\n  //that when we start a BFS gives the giant connected component, and\n  //we have the eccentricities calculated. Iterate over the nodes of\n  //this giant component and find the minimum eccentricity.\n  std::vector<int> component( m_NumberOfVertices );\n  boost::connected_components( *(m_Network->GetBoostGraph()), &component[0]);\n  for (unsigned int i=0; i<component.size(); i++)\n  {\n    //If we are in the same component and the radius is not the\n    //minimum so far store the eccentricity as the radius.\n    if( component[i] == component[radius_src])\n    {\n      if(m_Radius > m_VectorOfEccentrities[i])\n      {\n        m_Radius = m_VectorOfEccentrities[i];\n      }\n      if(m_Radius90 > m_VectorOfEccentrities90[i])\n      {\n        m_Radius90 = m_VectorOfEccentrities90[i];\n      }\n    }\n  }\n\n  m_AverageEccentricity = std::accumulate(m_VectorOfEccentrities.begin(),\n    m_VectorOfEccentrities.end(), 0.0) / m_NumberOfVertices;\n\n  m_AverageEccentricity90 = std::accumulate(m_VectorOfEccentrities90.begin(),\n    m_VectorOfEccentrities90.end(), 0.0) / m_NumberOfVertices;\n\n  m_AveragePathLength = std::accumulate(m_VectorOfAveragePathLengths.begin(),\n    m_VectorOfAveragePathLengths.end(), 0.0) / m_NumberOfVertices;\n\n  //calculate Number of Central Points, nodes having eccentricity = radius.\n  m_NumberOfCentralPoints = 0;\n  for (boost::tie(vi, vi_end) = boost::vertices( *(m_Network->GetBoostGraph()) ); vi != vi_end; ++vi)\n  {\n    if(m_VectorOfEccentrities[*vi] == m_Radius)\n    {\n      m_NumberOfCentralPoints++;\n    }\n  }\n  m_RatioOfCentralPoints = (double)m_NumberOfCentralPoints / m_NumberOfVertices;\n}\n\nvoid mitk::ConnectomicsStatisticsCalculator::CalculateSpectralMetrics()\n{\n  mitk::ConnectomicsNetworkConverter::Pointer converter = mitk::ConnectomicsNetworkConverter::New();\n  converter->SetNetwork( m_Network );\n  vnl_matrix<double> adjacencyMatrix = converter->GetNetworkAsVNLAdjacencyMatrix();\n\n  vnl_symmetric_eigensystem<double> eigenSystem(adjacencyMatrix);\n\n  m_AdjacencyTrace = 0;\n  m_AdjacencyEnergy = 0;\n  m_VectorOfSortedEigenValues.clear();\n\n  for(unsigned int i=0; i < m_NumberOfVertices; ++i)\n  {\n    double value = std::fabs(eigenSystem.get_eigenvalue(i));\n    m_VectorOfSortedEigenValues.push_back(value);\n    m_AdjacencyTrace += value;\n    m_AdjacencyEnergy += value * value;\n  }\n\n  std::sort(m_VectorOfSortedEigenValues.begin(), m_VectorOfSortedEigenValues.end());\n\n  m_SpectralRadius = m_VectorOfSortedEigenValues[ m_NumberOfVertices - 1];\n  m_SecondLargestEigenValue  = m_VectorOfSortedEigenValues[ m_NumberOfVertices - 2];\n}\n\nvoid mitk::ConnectomicsStatisticsCalculator::CalculateLaplacianMetrics()\n{\n  mitk::ConnectomicsNetworkConverter::Pointer converter = mitk::ConnectomicsNetworkConverter::New();\n  converter->SetNetwork( m_Network );\n  vnl_matrix<double> adjacencyMatrix = converter->GetNetworkAsVNLAdjacencyMatrix();\n  vnl_matrix<double> laplacianMatrix ( m_NumberOfVertices, m_NumberOfVertices, 0);\n  vnl_matrix<double> degreeMatrix = converter->GetNetworkAsVNLDegreeMatrix();\n\n  m_VectorOfSortedLaplacianEigenValues.clear();\n  laplacianMatrix = degreeMatrix - adjacencyMatrix;\n  int numberOfConnectedComponents = 0;\n  vnl_symmetric_eigensystem <double> laplacianEigenSystem( laplacianMatrix );\n  m_LaplacianEnergy = 0;\n  m_LaplacianTrace  = 0;\n  for(unsigned int i(0); i < m_NumberOfVertices; ++i)\n  {\n    double value = std::fabs( laplacianEigenSystem.get_eigenvalue(i) );\n    m_VectorOfSortedLaplacianEigenValues.push_back( value );\n    m_LaplacianTrace += value;\n    m_LaplacianEnergy += value * value;\n    if ( std::fabs( value ) < mitk::eps )\n    {\n      numberOfConnectedComponents++;\n    }\n  }\n\n  std::sort(m_VectorOfSortedLaplacianEigenValues.begin(), m_VectorOfSortedLaplacianEigenValues.end());\n  for(unsigned int i(0); i < m_VectorOfSortedLaplacianEigenValues.size(); ++i)\n  {\n    if(m_VectorOfSortedLaplacianEigenValues[i] > mitk::eps )\n    {\n      m_LaplacianSpectralGap = m_VectorOfSortedLaplacianEigenValues[i];\n      break;\n    }\n  }\n}\n\nvoid  mitk::ConnectomicsStatisticsCalculator::CalculateNormalizedLaplacianMetrics()\n{\n  vnl_matrix<double> normalizedLaplacianMatrix(m_NumberOfVertices, m_NumberOfVertices, 0);\n  EdgeIteratorType ei, ei_end;\n  VertexDescriptorType sourceVertex, destinationVertex;\n  int sourceIndex, destinationIndex;\n  VertexIndexMapType vertexIndexMap = boost::get(boost::vertex_index, *(m_Network->GetBoostGraph()) );\n  m_VectorOfSortedNormalizedLaplacianEigenValues.clear();\n\n  // Normalized laplacian matrix\n  for( boost::tie(ei, ei_end) = boost::edges( *(m_Network->GetBoostGraph()) ); ei != ei_end; ++ei)\n  {\n    sourceVertex = boost::source(*ei, *(m_Network->GetBoostGraph()) );\n    sourceIndex = vertexIndexMap[sourceVertex];\n\n    destinationVertex = boost::target(*ei, *(m_Network->GetBoostGraph()) );\n    destinationIndex = vertexIndexMap[destinationVertex];\n    int sourceDegree = boost::out_degree(sourceVertex, *(m_Network->GetBoostGraph()) );\n    int destinationDegree = boost::out_degree(destinationVertex, *(m_Network->GetBoostGraph()) );\n\n    normalizedLaplacianMatrix.put(\n      sourceIndex, destinationIndex, -1 / (sqrt(double(sourceDegree * destinationDegree))));\n    normalizedLaplacianMatrix.put(\n      destinationIndex, sourceIndex, -1 / (sqrt(double(sourceDegree * destinationDegree))));\n  }\n\n  VertexIteratorType vi, vi_end;\n  for(boost::tie(vi, vi_end)=boost::vertices( *(m_Network->GetBoostGraph()) ); vi!=vi_end; ++vi)\n  {\n    if(boost::out_degree(*vi, *(m_Network->GetBoostGraph()) ) > 0)\n    {\n      normalizedLaplacianMatrix.put(vertexIndexMap[*vi], vertexIndexMap[*vi], 1);\n    }\n  }\n  //End of normalized laplacian matrix definition\n\n  vnl_symmetric_eigensystem <double>\n    normalizedLaplacianEigensystem(normalizedLaplacianMatrix);\n\n  double N1=0, C1=0, D1=0, E1=0, F1=0, b1=0;\n  double N2=0, C2=0, D2=0, E2=0, F2=0, b2=0;\n  m_NormalizedLaplacianNumberOf2s = 0;\n  m_NormalizedLaplacianNumberOf1s = 0;\n  m_NormalizedLaplacianNumberOf0s = 0;\n  m_NormalizedLaplacianTrace = 0;\n  m_NormalizedLaplacianEnergy = 0;\n\n  for(unsigned int i(0); i< m_NumberOfVertices; ++i)\n  {\n    double eigenValue = std::fabs(normalizedLaplacianEigensystem.get_eigenvalue(i));\n    m_VectorOfSortedNormalizedLaplacianEigenValues.push_back(eigenValue);\n    m_NormalizedLaplacianTrace  += eigenValue;\n    m_NormalizedLaplacianEnergy += eigenValue * eigenValue;\n\n    //0\n    if(eigenValue < mitk::eps)\n    {\n      m_NormalizedLaplacianNumberOf0s++;\n    }\n\n    //Between 0 and 1.\n    else if(eigenValue > mitk::eps && eigenValue< 1 - mitk::eps)\n    {\n      C1 += i;\n      D1 += eigenValue;\n      E1 += i * eigenValue;\n      F1 += i * i;\n      N1 ++;\n    }\n\n    //1\n    else if(std::fabs( std::fabs(eigenValue) - 1) < mitk::eps)\n    {\n      m_NormalizedLaplacianNumberOf1s++;\n    }\n\n    //Between 1 and 2\n    else if(std::fabs(eigenValue) > 1+mitk::eps && std::fabs(eigenValue)< 2 - mitk::eps)\n    {\n      C2 += i;\n      D2 += eigenValue;\n      E2 += i * eigenValue;\n      F2 += i * i;\n      N2 ++;\n    }\n\n    //2\n    else if(std::fabs( std::fabs(eigenValue) - 2) < mitk::eps)\n    {\n      m_NormalizedLaplacianNumberOf2s++;\n    }\n  }\n\n  b1 = (D1*F1 - C1*E1)/(F1*N1 - C1*C1);\n  m_NormalizedLaplacianLowerSlope = (E1 - b1*C1)/F1;\n\n  b2 = (D2*F2 - C2*E2)/(F2*N2 - C2*C2);\n  m_NormalizedLaplacianUpperSlope = (E2 - b2*C2)/F2;\n}\n\nvoid mitk::ConnectomicsStatisticsCalculator::CalculateSmallWorldness()\n{\n  double k( this->GetAverageDegree() );\n  double N( this->GetNumberOfVertices() );\n  // The clustering coefficient of an Erdos-Reny network is equivalent to\n  // the likelihood two random nodes are connected\n  double gamma = this->GetAverageClusteringCoefficientsC() / ( k / N );\n  //The mean path length of an Erdos-Reny network is approximately\n  // ln( #vertices ) / ln( average degree )\n  double lambda = this->GetAveragePathLength() / ( std::log( N ) / std::log( k ) );\n\n  m_SmallWorldness = gamma / lambda;\n}\n", "meta": {"hexsha": "70757777951b9776c86c04a1d45b8fabea920431", "size": 25526, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Modules/Connectomics/Algorithms/mitkConnectomicsStatisticsCalculator.cpp", "max_stars_repo_name": "HRS-Navigation/MITK-Diffusion", "max_stars_repo_head_hexsha": "b1bf62d1c76f0d0cc26dd252561cb5d8769b4f87", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 37.0, "max_stars_repo_stars_event_min_datetime": "2019-07-05T10:55:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T12:09:35.000Z", "max_issues_repo_path": "Modules/Connectomics/Algorithms/mitkConnectomicsStatisticsCalculator.cpp", "max_issues_repo_name": "HRS-Navigation/MITK-Diffusion", "max_issues_repo_head_hexsha": "b1bf62d1c76f0d0cc26dd252561cb5d8769b4f87", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-11-04T16:05:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T15:53:31.000Z", "max_forks_repo_path": "Modules/Connectomics/Algorithms/mitkConnectomicsStatisticsCalculator.cpp", "max_forks_repo_name": "HRS-Navigation/MITK-Diffusion", "max_forks_repo_head_hexsha": "b1bf62d1c76f0d0cc26dd252561cb5d8769b4f87", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-10-15T14:37:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T03:22:01.000Z", "avg_line_length": 34.0346666667, "max_line_length": 141, "alphanum_fraction": 0.7137428504, "num_tokens": 7109, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893335913536, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.47035510322780283}}
{"text": "#include \"Arduino.h\"\r\n#include \"navduino.h\"\r\n#include \"eigen.h\"\r\n#include <Eigen/Geometry>\r\n\r\n\r\n\r\n\r\nusing namespace Eigen;\r\n\r\n\r\n\r\n\r\nvoid printVec2f(const Vector2f& vec, const int& p, Stream& stream)\r\n{\r\n\tstream.println(vec(0), p);\r\n\tstream.println(vec(1), p);\r\n}\r\n\r\n\r\n\r\n\r\nvoid printVec3f(const Vector3f& vec, const int& p, Stream& stream)\r\n{\r\n\tSerial.println(vec(0), p);\r\n\tSerial.println(vec(1), p);\r\n\tSerial.println(vec(2), p);\r\n}\r\n\r\n\r\n\r\n\r\nvoid printVec4f(const Vector4f& vec, const int& p, Stream& stream)\r\n{\r\n\tSerial.println(vec(0), p);\r\n\tSerial.println(vec(1), p);\r\n\tSerial.println(vec(2), p);\r\n\tSerial.println(vec(3), p);\r\n}\r\n\r\n\r\n\r\n\r\nvoid printQuatf(const Quaternionf& quat, const int& p, Stream& stream)\r\n{\r\n\tSerial.println(quat.x(), p);\r\n\tSerial.println(quat.y(), p);\r\n\tSerial.println(quat.z(), p);\r\n\tSerial.println(quat.w(), p);\r\n}\r\n\r\n\r\n\r\n\r\nvoid printMat3f(const Matrix3f& mat, const int& p, Stream& stream)\r\n{\r\n\tSerial.print(mat(0, 0), p); Serial.print(\", \"); Serial.print(mat(0, 1), p); Serial.print(\", \"); Serial.println(mat(0, 2), p);\r\n\tSerial.print(mat(1, 0), p); Serial.print(\", \"); Serial.print(mat(1, 1), p); Serial.print(\", \"); Serial.println(mat(1, 2), p);\r\n\tSerial.print(mat(2, 0), p); Serial.print(\", \"); Serial.print(mat(2, 1), p); Serial.print(\", \"); Serial.println(mat(2, 2), p);\r\n}\r\n\r\n\r\n\r\n\r\nvoid printMat4f(const Matrix4f& mat, const int& p, Stream& stream)\r\n{\r\n\tSerial.print(mat(0, 0), p); Serial.print(\", \"); Serial.print(mat(0, 1), p); Serial.print(\", \"); Serial.print(mat(0, 2), p); Serial.print(\", \"); Serial.println(mat(0, 3), p);\r\n\tSerial.print(mat(1, 0), p); Serial.print(\", \"); Serial.print(mat(1, 1), p); Serial.print(\", \"); Serial.print(mat(1, 2), p); Serial.print(\", \"); Serial.println(mat(1, 3), p);\r\n\tSerial.print(mat(2, 0), p); Serial.print(\", \"); Serial.print(mat(2, 1), p); Serial.print(\", \"); Serial.print(mat(2, 2), p); Serial.print(\", \"); Serial.println(mat(2, 3), p);\r\n\tSerial.print(mat(3, 0), p); Serial.print(\", \"); Serial.print(mat(3, 1), p); Serial.print(\", \"); Serial.print(mat(3, 2), p); Serial.print(\", \"); Serial.println(mat(3, 3), p);\r\n}\r\n\r\n\r\n\r\n\r\nfloat float_constrain(const float& input, const float& min, const float& max)\r\n{\r\n\tif (input > max)\r\n\t\treturn max;\r\n\telse if (input < min)\r\n\t\treturn min;\r\n\telse\r\n\t\treturn input;\r\n}\r\n\r\n\r\n\r\n\r\ndouble double_constrain(const double& input, const double& min, const double& max)\r\n{\r\n\tif (input > max)\r\n\t\treturn max;\r\n\telse if (input < min)\r\n\t\treturn min;\r\n\telse\r\n\t\treturn input;\r\n}\r\n\r\n\r\n\r\n\r\nfloat float_map(const float& x, const float& in_min, const float& in_max, const float& out_min, const float& out_max)\r\n{\r\n\treturn (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;\r\n}\r\n\r\n\r\n\r\n\r\ndouble double_map(const double& x, const double& in_min, const double& in_max, const double& out_min, const double& out_max)\r\n{\r\n\treturn (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;\r\n}", "meta": {"hexsha": "500443aec51f8da8b39af61a7594ae425a8edb55", "size": 2899, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/utils.cpp", "max_stars_repo_name": "PowerBroker2/navduino", "max_stars_repo_head_hexsha": "99275787076204379216123b3707a9f64d1eb6ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2022-03-21T15:51:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T20:20:45.000Z", "max_issues_repo_path": "src/utils.cpp", "max_issues_repo_name": "PowerBroker2/navduino", "max_issues_repo_head_hexsha": "99275787076204379216123b3707a9f64d1eb6ce", "max_issues_repo_licenses": ["MIT"], "max_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.cpp", "max_forks_repo_name": "PowerBroker2/navduino", "max_forks_repo_head_hexsha": "99275787076204379216123b3707a9f64d1eb6ce", "max_forks_repo_licenses": ["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.6548672566, "max_line_length": 175, "alphanum_fraction": 0.6174542946, "num_tokens": 844, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118221, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4703550981784496}}
{"text": "//          Copyright (C) 2012, Michele Caini.\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//          Two Graphs Common Spanning Trees Algorithm\r\n//      Based on academic article of Mint, Read and Tarjan\r\n//     Efficient Algorithm for Common Spanning Tree Problem\r\n// Electron. Lett., 28 April 1983, Volume 19, Issue 9, p.346-347\r\n\r\n\r\n#include <boost/graph/adjacency_list.hpp>\r\n#include <boost/graph/two_graphs_common_spanning_trees.hpp>\r\n#include <exception>\r\n#include <vector>\r\n\r\n\r\nusing namespace std;\r\n\r\ntypedef\r\nboost::adjacency_list\r\n  <\r\n    boost::vecS,         // OutEdgeList\r\n    boost::vecS,         // VertexList\r\n    boost::undirectedS,  // Directed\r\n    boost::no_property,  // VertexProperties\r\n    boost::no_property,  // EdgeProperties\r\n    boost::no_property,  // GraphProperties\r\n    boost::listS         // EdgeList\r\n  >\r\nGraph\r\n;\r\n\r\ntypedef\r\nboost::graph_traits<Graph>::vertex_descriptor\r\nvertex_descriptor;\r\n\r\ntypedef\r\nboost::graph_traits<Graph>::edge_descriptor\r\nedge_descriptor;\r\n\r\ntypedef\r\nboost::graph_traits<Graph>::vertex_iterator\r\nvertex_iterator;\r\n\r\ntypedef\r\nboost::graph_traits<Graph>::edge_iterator\r\nedge_iterator;\r\n\r\n\r\nint main(int argc, char **argv)\r\n{\r\n  Graph iG, vG;\r\n  vector< edge_descriptor > iG_o;\r\n  vector< edge_descriptor > vG_o;\r\n\r\n  iG_o.push_back(boost::add_edge(0, 1, iG).first);\r\n  iG_o.push_back(boost::add_edge(0, 2, iG).first);\r\n  iG_o.push_back(boost::add_edge(0, 3, iG).first);\r\n  iG_o.push_back(boost::add_edge(0, 4, iG).first);\r\n  iG_o.push_back(boost::add_edge(1, 2, iG).first);\r\n  iG_o.push_back(boost::add_edge(3, 4, iG).first);\r\n\r\n  vG_o.push_back(boost::add_edge(1, 2, vG).first);\r\n  vG_o.push_back(boost::add_edge(2, 0, vG).first);\r\n  vG_o.push_back(boost::add_edge(2, 3, vG).first);\r\n  vG_o.push_back(boost::add_edge(4, 3, vG).first);\r\n  vG_o.push_back(boost::add_edge(0, 3, vG).first);\r\n  vG_o.push_back(boost::add_edge(0, 4, vG).first);\r\n\r\n  vector<bool> inL(iG_o.size(), false);\r\n\r\n  std::vector< std::vector<bool> > coll;\r\n  boost::tree_collector<\r\n      std::vector< std::vector<bool> >,\r\n      std::vector<bool>\r\n    > tree_collector(coll);\r\n  boost::two_graphs_common_spanning_trees\r\n    (\r\n      iG,\r\n      iG_o,\r\n      vG,\r\n      vG_o,\r\n      tree_collector,\r\n      inL\r\n    );\r\n  \r\n  std::vector< std::vector<bool> >::iterator it;\r\n  for(it = coll.begin(); it != coll.end(); ++it) {\r\n    // Here you can play with the trees that the algorithm has found.\r\n  }\r\n\r\n  return 0;\r\n}\r\n", "meta": {"hexsha": "3842df6861e7278a80b181d32dbca71586087576", "size": 2584, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/graph/example/two_graphs_common_spanning_trees.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/graph/example/two_graphs_common_spanning_trees.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/graph/example/two_graphs_common_spanning_trees.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": 27.2, "max_line_length": 70, "alphanum_fraction": 0.6540247678, "num_tokens": 755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.47030400438664816}}
{"text": "#ifndef SPLINE_H\n#define SPLINE_H\n\n//#pragma GCC optimize(\"O3\")\n\n#include \"polynomial.hpp\"\n#include <Eigen/Dense>\n\ntemplate <unsigned Deg> class Spline\n{\nprivate:\n\tusing MatrixDXf = Eigen::Matrix<float,Deg+1,Eigen::Dynamic>;\n\tusing MatrixXDf = Eigen::Matrix<float,Eigen::Dynamic,Deg+1>;\n\tMatrixDXf c;\n\tfloat xmin, xmax;\n\tfloat invdx;\n\tSpline() = default;\n\tvoid setFromSorted(const Eigen::Matrix2Xf &sortedXY,\n\t\t\t   const unsigned NPieces);\n\tinline float value(int i, float x) const;\n\tstatic Eigen::VectorXf values(const Eigen::VectorXf& x, const MatrixXDf& cPerm);\n\npublic:\n\tinline float value_unsafe(const float &x) const\n\t{\n\t\tint i = (x - xmin) * invdx;\n\t\tassert(i >= 0);\n\t\tassert(i < c.cols());\n\t\treturn value(i,x);\n\t}\n\tfloat value_or(const float &x, const float &defaultValue) const\n\t{\n\t\tif (x < xmin || x > xmax) {\n\t\t\treturn defaultValue;\n\t\t}\n\t\tint i = (x - xmin) * invdx;\n\t\treturn value(i,x);\n\t}\n\tfloat value_or(const float &x, const float defaultLeft, const float defaultRight) const\n\t{\n\t\tif (x < xmin) {\n\t\t\treturn defaultLeft;\n\t\t}\n\t\tif (x > xmax) {\n\t\t\treturn defaultRight;\n\t\t}\n\t\tint i = (x - xmin) * invdx;\n\t\treturn value(i,x);\n\t}\n\tEigen::VectorXf values_unsafe(const Eigen::VectorXf& x) const;\n\n\tunsigned maxAbsDiffArg(const Eigen::Matrix2Xf &xy) const\n\t{\n\t\tfloat max=0.0f;\n\t\tunsigned arg=0;\n\t\tfor(unsigned i=0; i<xy.cols(); ++i) {\n\t\t\tfloat diff=std::fabs(xy(1,i)-value_unsafe(xy(0,i)));\n\t\t\tif(max<diff) {\n\t\t\t\tmax=diff;\n\t\t\t\targ=i;\n\t\t\t}\n\t\t}\n\t\treturn arg;\n\t}\n\tstatic Spline<Deg> fromSorted(const Eigen::Matrix2Xf &sortedXY,\n\t\t\t\t      const unsigned NPieces);\n\n\ttemplate <unsigned Nd>\n\tfriend std::ostream &operator<<(std::ostream &os,\n\t\t\t\t\tconst Spline<Nd> &spline);\n};\ntemplate <unsigned Deg>\nstd::ostream &operator<<(std::ostream &os, const Spline<Deg> &spline)\n{\n\tfor (int i = 0; i < spline.polynomials.size(); ++i) {\n\t\tfloat dx = 1.0 / spline.invdx;\n\t\tfloat from = spline.xmin + dx * i;\n\t\tfloat to = from + dx;\n\t\tos << '[' << from << \"..\" << to << \"] \" << spline.polynomials[i]\n\t\t   << '\\n';\n\t}\n\treturn os;\n}\n\ntemplate <unsigned int Deg>\nSpline<Deg> Spline<Deg>::fromSorted(const Eigen::Matrix2Xf &sortedXY,\n\t\t\t\t    const unsigned NPieces)\n{\n\tSpline<Deg> sp;\n\tsp.setFromSorted(sortedXY, NPieces);\n\treturn sp;\n}\ntemplate <unsigned int Deg>\nvoid Spline<Deg>::setFromSorted(const Eigen::Matrix2Xf &sortedXY,\n\t\t\t\tconst unsigned NPieces)\n{\n\tconst int nPoints = sortedXY.cols();\n\tassert(nPoints > Deg);\n\n\txmin = sortedXY(0, 0);\n\txmax = sortedXY(0, nPoints - 1);\n\tconstexpr float inf = std::numeric_limits<float>::infinity();\n\tconst float dx = nextafterf((xmax - xmin) / NPieces, inf);\n\tinvdx = 1.0f / dx;\n\n\tassert((xmax - xmin) * invdx < NPieces);\n\n\tc.resize(3,NPieces);\n\tint iStart = 0;\n\tfor (int piece = 0; piece < NPieces - 1; ++piece) {\n\t\tfloat xEnd = dx * (piece + 1) + xmin;\n\t\tint iEnd = iStart;\n\t\twhile (sortedXY(0, iEnd) < xEnd) {\n\t\t\t++iEnd;\n\t\t}\n\t\tint len = std::max(iEnd - iStart, int(Deg + 1));\n\t\tPolynomial<Deg> p(sortedXY.middleCols(iStart, len));\n\t\tc.col(piece) = p.c;\n\t\tif (iEnd > iStart + Deg) {\n\t\t\tiStart = std::min(int(nPoints - Deg - 1), iEnd);\n\t\t}\n\t}\n\n\tPolynomial<Deg> p(sortedXY.middleCols(iStart, nPoints - iStart));\n\tc.col(NPieces - 1) = p.c;\n}\n\ntemplate<>\nfloat Spline<0>::value(int i, float ) const\n{\n\treturn c(0,i);\n}\n\ntemplate<>\nfloat Spline<1>::value(int i, float x) const\n{\n\treturn c(0,i)+c(1,i)*x;\n}\n\ntemplate<>\nfloat Spline<2>::value(int i, float x) const\n{\n\treturn c(0,i)+c(1,i)*x+c(2,i)*x*x;\n}\n\ntemplate<unsigned int Deg>\nfloat Spline<Deg>::value(int i, float x) const\n{\n\tfloat val=c(0,i)+c(1,i)*x+c(2,i)*x*x;\n\tfor (int e=3; e<=Deg; e++) {\n\t\tval+=c(e,i)*std::pow(x,e);\n\t}\n\treturn val;\n}\n\ntemplate<unsigned int Deg>\nEigen::VectorXf Spline<Deg>::values_unsafe(const Eigen::VectorXf& x) const\n{\n\t//x<xmin is not verified at runtime!\n\tassert(x.minCoeff()>=xmin);\n\tconst int maxCol=c.cols()-1;\n\tconst unsigned N=x.size();\n\n\tEigen::VectorXi idxs=((x.array()-xmin)*invdx).cast<int>().min(maxCol);\n\tMatrixXDf slc(N,Deg+1);\n\tfor(int i=0; i<N; ++i) {\n\t\tslc.row(i) = c.col(idxs(i));\n\t}\n\treturn values(x,slc);\n}\n\ntemplate<unsigned int Deg>\nEigen::VectorXf Spline<Deg>::values(const Eigen::VectorXf& x, const Spline::MatrixXDf& cPerm)\n{\n\tEigen::VectorXf res=Spline<2>::values(x,cPerm);\n\tfor (int e=3; e<=Deg; ++e) {\n\t\tres+=cPerm.col(e).cwiseProduct(x.array().pow(e).matrix());\n\t}\n\treturn res;\n}\n\ntemplate<>\nEigen::VectorXf Spline<2>::values(const Eigen::VectorXf& x, const Spline::MatrixXDf& cPerm)\n{\n\treturn cPerm.col(0)+cPerm.col(1).cwiseProduct(x)+cPerm.col(2).cwiseProduct(x.cwiseAbs2());\n}\n\ntemplate<>\nEigen::VectorXf Spline<1>::values(const Eigen::VectorXf& x, const Spline::MatrixXDf& cPerm)\n{\n\treturn cPerm.col(0)+cPerm.col(1).cwiseProduct(x);\n}\n\ntemplate<>\nEigen::VectorXf Spline<0>::values(const Eigen::VectorXf& x, const Spline::MatrixXDf& cPerm)\n{\n\treturn cPerm.col(0);\n}\n#endif // SPLINE_H\n", "meta": {"hexsha": "ae065777706151d545fb3fe7ad598225be100161", "size": 4827, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "spline.hpp", "max_stars_repo_name": "mdimura/SplineApprox", "max_stars_repo_head_hexsha": "de558dcdf906d0a556e6ec0fa01bc9a039596c89", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-03-27T15:30:07.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-27T15:30:07.000Z", "max_issues_repo_path": "spline.hpp", "max_issues_repo_name": "mdimura/SplineApprox", "max_issues_repo_head_hexsha": "de558dcdf906d0a556e6ec0fa01bc9a039596c89", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "spline.hpp", "max_forks_repo_name": "mdimura/SplineApprox", "max_forks_repo_head_hexsha": "de558dcdf906d0a556e6ec0fa01bc9a039596c89", "max_forks_repo_licenses": ["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.135, "max_line_length": 93, "alphanum_fraction": 0.6540294179, "num_tokens": 1569, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.47030400410360984}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2013   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2013   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#include <nt2/include/functions/tand.hpp>\n\n#include <boost/dispatch/functor/meta/call.hpp>\n#include <nt2/sdk/functor/meta/call.hpp>\n#include <nt2/sdk/unit/tests/relation.hpp>\n#include <nt2/sdk/unit/tests/type_expr.hpp>\n#include <complex>\n#include <nt2/sdk/complex/complex.hpp>\n#include <nt2/sdk/unit/tests/ulp.hpp>\n#include <nt2/sdk/unit/tests/basic.hpp>\n#include <nt2/sdk/meta/as_integer.hpp>\n#include <nt2/sdk/unit/module.hpp>\n#include <boost/simd/sdk/config.hpp>\n\n#include <nt2/include/constants/zero.hpp>\n#include <nt2/include/constants/inf.hpp>\n#include <nt2/include/constants/minf.hpp>\n#include <nt2/include/constants/nan.hpp>\n#include <nt2/include/constants/i.hpp>\n\n#include <nt2/include/functions/mul_i.hpp>\n#include <nt2/include/functions/mul_minus_i.hpp>\n\nNT2_TEST_CASE_TPL ( tand,  NT2_REAL_TYPES)\n{\n\n  using nt2::tand;\n  using nt2::tag::tand_;\n  typedef std::complex<T> cT;\n  typedef typename nt2::meta::call<tand_(cT)>::type r_t;\n  typedef typename nt2:: meta::as_complex<T>::type wished_r_t;\n\n  // return type conformity test\n  NT2_TEST_TYPE_IS(r_t, wished_r_t);\n\n  // specific values tests\n  NT2_TEST_ULP_EQUAL(nt2::tand(cT(nt2::Inf<T>())), cT(nt2::Nan<T>()), 13);\n  NT2_TEST_ULP_EQUAL(nt2::tand(cT(nt2::Minf<T>())), cT(nt2::Nan<T>()), 13);\n  NT2_TEST_ULP_EQUAL(nt2::tand(cT(1, 1)),std::tan(nt2::Deginrad<T>()*cT(1.0, 1.0)), 13);\n  NT2_TEST_ULP_EQUAL(nt2::tand(cT(1, 0.3)),std::tan(nt2::Deginrad<T>()*cT(1.0, 0.3)), 13);\n  NT2_TEST_ULP_EQUAL(nt2::tand(cT(0.3, 1)),std::tan(nt2::Deginrad<T>()*cT(0.3, 1.0)), 13);\n  NT2_TEST_ULP_EQUAL(nt2::tand(cT(0.3, 0.3)),std::tan(nt2::Deginrad<T>()*cT(0.3, 0.3)), 13);\n  NT2_TEST_ULP_EQUAL(nt2::tand(cT(0, 1)),std::tan(nt2::Deginrad<T>()*cT(0.0, 1.0)), 13);\n  NT2_TEST_ULP_EQUAL(nt2::tand(cT(0, 0.3)),std::tan(nt2::Deginrad<T>()*cT(0.0, 0.3)), 13);\n  NT2_TEST_ULP_EQUAL(nt2::tand(cT(0.3, 0)),std::tan(nt2::Deginrad<T>()*cT(0.3, 0.0)), 13);\n\n  const int N = 20;\n  cT inputs[N] =\n    { cT(nt2::Zero<T>(),nt2::Zero<T>()),cT(nt2::Inf<T>(),nt2::Zero<T>()),cT(nt2::Minf<T>(),nt2::Zero<T>()),cT(nt2::Nan<T>(),nt2::Zero<T>()),\n      cT(nt2::Zero<T>(),nt2::Inf<T>()), cT(nt2::Inf<T>(),nt2::Inf<T>()), cT(nt2::Minf<T>(),nt2::Inf<T>()), cT(nt2::Nan<T>(),nt2::Inf<T>()),\n      cT(nt2::Zero<T>(),nt2::Minf<T>()),cT(nt2::Inf<T>(),nt2::Minf<T>()),cT(nt2::Minf<T>(),nt2::Minf<T>()),cT(nt2::Nan<T>(),nt2::Minf<T>()),\n      cT(nt2::Zero<T>(),nt2::Nan<T>()), cT(nt2::Inf<T>(),nt2::Nan<T>()), cT(nt2::Minf<T>(),nt2::Nan<T>()), cT(nt2::Nan<T>(),nt2::Nan<T>()),\n      cT(nt2::Zero<T>(),180), cT(nt2::Inf<T>(),180), cT(nt2::Minf<T>(),180), cT(nt2::Nan<T>(),180),\n    };\n\n  for(int i=0; i < N; i++)\n   {\n     std::cout << \"-------------------\" << std::endl;\n     std::cout << \"inputs  \"<< inputs[i] << std::endl;\n     NT2_TEST_ULP_EQUAL(nt2::tand(-inputs[i]), -nt2::tand(inputs[i]), 3);\n     NT2_TEST_ULP_EQUAL(nt2::tand(inputs[i]), nt2::mul_minus_i(nt2::tanh(nt2::mul_i(nt2::multiplies(nt2::Deginrad<T>(), inputs[i])))), 3);\n     std::cout << \"=================== \" << std::endl;\n   }\n\n } // end of test for floating_\n\n", "meta": {"hexsha": "93138da0d78ab4ca331119b8dcc97f7417ccdd99", "size": 3555, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/type/complex/trigonometric/unit/scalar/tand.cpp", "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/type/complex/trigonometric/unit/scalar/tand.cpp", "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/type/complex/trigonometric/unit/scalar/tand.cpp", "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": 47.4, "max_line_length": 140, "alphanum_fraction": 0.5879043601, "num_tokens": 1282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.4703039998421157}}
{"text": "#include <stan/math/prim/scal.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <gtest/gtest.h>\n\nTEST(MathFunctions,logical_lte) {\n  using stan::math::logical_lte;\n  EXPECT_TRUE(logical_lte(0,1));\n  EXPECT_TRUE(logical_lte(1.0,2.0));\n  EXPECT_TRUE(logical_lte(1, 2.0));\n  EXPECT_TRUE(logical_lte(-1, 0));\n  EXPECT_TRUE(logical_lte(1,1));\n  EXPECT_TRUE(logical_lte(5.7,5.7));\n\n  EXPECT_FALSE(logical_lte(5.7,-9.0));\n  EXPECT_FALSE(logical_lte(-1,-2));\n}\n\nTEST(MathFunctions, logical_lte_nan) {\n  double nan = std::numeric_limits<double>::quiet_NaN();\n  \n  EXPECT_FALSE(stan::math::logical_lte(1.0, nan));\n  EXPECT_FALSE(stan::math::logical_lte(nan, 2.0));\n  EXPECT_FALSE(stan::math::logical_lte(nan, nan));\n}\n", "meta": {"hexsha": "1e7b18ee3d454cf4cbf5a58045b9507ee564362e", "size": 727, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/scal/fun/logical_lte_test.cpp", "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/test/unit/math/prim/scal/fun/logical_lte_test.cpp", "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/test/unit/math/prim/scal/fun/logical_lte_test.cpp", "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": 29.08, "max_line_length": 56, "alphanum_fraction": 0.7221458047, "num_tokens": 239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583124210896, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.4703039958636596}}
{"text": "#include <stan/math/prim.hpp>\n#include <boost/math/distributions.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <gtest/gtest.h>\n#include <vector>\n\nTEST(ProbDistributionsDiscreteRange, error_check) {\n  using stan::math::discrete_range_rng;\n  boost::random::mt19937 rng;\n\n  std::vector<int> lower{5, 11, -15};\n  std::vector<int> upper{7, 15, -10};\n\n  EXPECT_NO_THROW(discrete_range_rng(lower, upper, rng));\n  EXPECT_THROW(discrete_range_rng(lower, 10, rng), std::domain_error);\n  EXPECT_THROW(discrete_range_rng(10, upper, rng), std::domain_error);\n\n  std::vector<int> vec2{1, 2};\n  EXPECT_THROW(discrete_range_rng(lower, vec2, rng), std::invalid_argument);\n  EXPECT_THROW(discrete_range_rng(vec2, upper, rng), std::invalid_argument);\n}\n\nTEST(ProbDistributionsDiscreteRange, boundary_values) {\n  using stan::math::discrete_range_rng;\n  boost::random::mt19937 rng;\n\n  std::vector<int> lower{-5, 11, 17};\n  EXPECT_EQ(lower, discrete_range_rng(lower, lower, rng));\n\n  std::vector<int> upper(lower);\n  for (int i = 0; i < upper.size(); i++) {\n    ++upper[i];\n  }\n\n  EXPECT_LE(lower, discrete_range_rng(lower, upper, rng));\n  EXPECT_GE(upper, discrete_range_rng(lower, upper, rng));\n}\n\nTEST(ProbDistributionsDiscreteRange, chiSquareGoodnessFitTest) {\n  boost::random::mt19937 rng;\n\n  int N = 10000;\n  int lower = -3;\n  int upper = 20;\n\n  int K = upper - lower + 1;\n  boost::math::chi_squared mydist(K - 1);\n\n  std::vector<int> bin(K, 0);\n  std::vector<double> expect(K, static_cast<double>(N) / K);\n\n  for (int count = 0; count < N; ++count) {\n    int a = stan::math::discrete_range_rng(lower, upper, rng);\n    ++bin[a - lower];\n  }\n\n  double chi = 0;\n\n  for (int j = 0; j < K; j++) {\n    chi += (bin[j] - expect[j]) * (bin[j] - expect[j]) / expect[j];\n  }\n\n  EXPECT_TRUE(chi < quantile(complement(mydist, 1e-6)));\n}\n", "meta": {"hexsha": "d6535d384f3d69c13a81374493d73d28e4421979", "size": 1822, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/prim/prob/discrete_range_test.cpp", "max_stars_repo_name": "LaudateCorpus1/math", "max_stars_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-14T14:33:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-14T14:33:37.000Z", "max_issues_repo_path": "test/unit/math/prim/prob/discrete_range_test.cpp", "max_issues_repo_name": "LaudateCorpus1/math", "max_issues_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "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": "test/unit/math/prim/prob/discrete_range_test.cpp", "max_forks_repo_name": "LaudateCorpus1/math", "max_forks_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-05-10T12:55:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-10T12:55:07.000Z", "avg_line_length": 28.0307692308, "max_line_length": 76, "alphanum_fraction": 0.6811196487, "num_tokens": 552, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757645879592642, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.47030399075305074}}
{"text": "#include <stan/math/prim/arr.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <gtest/gtest.h>\n\nTEST(MathFunctions, scaled_add) {\n  std::vector<double> x(3), y(3);\n  double lambda;\n  \n  x[0] = 0;\n  x[1] = 0;\n  x[2] = 0;\n  y[0] = 2;\n  y[1] = 3;\n  y[2] = 4;\n  \n  lambda = 0.5;\n  \n  EXPECT_NO_THROW(stan::math::scaled_add(x, y, lambda));\n  EXPECT_FLOAT_EQ(1.0, x[0]);\n  EXPECT_FLOAT_EQ(1.5, x[1]);\n  EXPECT_FLOAT_EQ(2.0, x[2]);\n}\n\nTEST(MathFunctions, scaled_add_nan) {\n  double nan = std::numeric_limits<double>::quiet_NaN();\n  std::vector<double> x(3), y(3);\n  double lambda;\n  \n  x[0] = 0;\n  x[1] = 0;\n  x[2] = 0;\n  y[0] = 2;\n  y[1] = 3;\n  y[2] = 4;\n  \n  lambda = 0.5;\n  \n  EXPECT_NO_THROW(stan::math::scaled_add(x, y, nan));\n  EXPECT_PRED1(boost::math::isnan<double>, x[0]);\n  EXPECT_PRED1(boost::math::isnan<double>, x[1]);\n  EXPECT_PRED1(boost::math::isnan<double>, x[2]);\n\n  x[0] = 0;\n  x[1] = 0;\n  x[2] = 0;\n  y[1] = nan;\n  EXPECT_NO_THROW(stan::math::scaled_add(x, y, lambda));\n  EXPECT_FLOAT_EQ(1.0, x[0]);\n  EXPECT_PRED1(boost::math::isnan<double>, x[1]);\n  EXPECT_FLOAT_EQ(2.0, x[2]);\n\n  x[0] = 0;\n  x[1] = 0;\n  x[2] = 0;\n  EXPECT_NO_THROW(stan::math::scaled_add(x, y, nan));\n  EXPECT_PRED1(boost::math::isnan<double>, x[0]);\n  EXPECT_PRED1(boost::math::isnan<double>, x[1]);\n  EXPECT_PRED1(boost::math::isnan<double>, x[2]);\n}\n", "meta": {"hexsha": "0fb22d2022bf2fde3b274f6b013bfada8ecf989a", "size": 1355, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/arr/fun/scaled_add_test.cpp", "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/test/unit/math/prim/arr/fun/scaled_add_test.cpp", "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/test/unit/math/prim/arr/fun/scaled_add_test.cpp", "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": 22.5833333333, "max_line_length": 56, "alphanum_fraction": 0.6022140221, "num_tokens": 527, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583124210896, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.47030398677459495}}
{"text": "//[ CheckedCalc\n//  Copyright 2011 Eric Niebler. Distributed under the Boost\n//  Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n//\n// This is an example of how to specify a transform externally so\n// that a single grammar can be used to drive multiple differnt\n// calculations. In particular, it defines a calculator grammar\n// that computes the result of an expression with either checked\n// or non-checked division.\n\n#include <iostream>\n#include <boost/assert.hpp>\n#include <boost/mpl/int.hpp>\n#include <boost/mpl/next.hpp>\n#include <boost/mpl/min_max.hpp>\n#include <boost/fusion/container/vector.hpp>\n#include <boost/fusion/container/generation/make_vector.hpp>\n#include <boost/proto/proto.hpp>\nnamespace mpl = boost::mpl;\nnamespace proto = boost::proto;\nnamespace fusion = boost::fusion;\n\n// The argument placeholder type\ntemplate<typename I> struct placeholder : I {};\n\n// Give each rule in the grammar a \"name\". This is so that we\n// can easily dispatch on it later.\nstruct calc_grammar;\nstruct divides_rule : proto::divides<calc_grammar, calc_grammar> {};\n\n// Use external transforms in calc_gramar\nstruct calc_grammar\n  : proto::or_<\n        proto::when<\n            proto::terminal<placeholder<proto::_> >\n            , proto::functional::at(proto::_state, proto::_value)\n        >\n      , proto::when<\n            proto::terminal<proto::convertible_to<double> >\n          , proto::_value\n        >\n      , proto::when<\n            proto::plus<calc_grammar, calc_grammar>\n          , proto::_default<calc_grammar>\n        >\n      , proto::when<\n            proto::minus<calc_grammar, calc_grammar>\n          , proto::_default<calc_grammar>\n        >\n      , proto::when<\n            proto::multiplies<calc_grammar, calc_grammar>\n          , proto::_default<calc_grammar>\n        >\n        // Note that we don't specify how division nodes are\n        // handled here. Proto::external_transform is a placeholder\n        // for an actual transform.\n      , proto::when<\n            divides_rule\n          , proto::external_transform\n        >\n    >\n{};\n\ntemplate<typename E> struct calc_expr;\nstruct calc_domain : proto::domain<proto::generator<calc_expr> > {};\n\ntemplate<typename E>\nstruct calc_expr\n  : proto::extends<E, calc_expr<E>, calc_domain>\n{\n    calc_expr(E const &e = E()) : calc_expr::proto_extends(e) {}\n};\n\ncalc_expr<proto::terminal<placeholder<mpl::int_<0> > >::type> _1;\ncalc_expr<proto::terminal<placeholder<mpl::int_<1> > >::type> _2;\n\n// Use proto::external_transforms to map from named grammar rules to\n// transforms.\nstruct non_checked_division\n  : proto::external_transforms<\n        proto::when< divides_rule, proto::_default<calc_grammar> >\n    >\n{};\n\nstruct division_by_zero : std::exception {};\n\nstruct do_checked_divide\n    : proto::callable\n{\n    typedef int result_type;\n    int operator()(int left, int right) const\n    {\n        if (right == 0) throw division_by_zero();\n        return left / right;\n    }\n};\n\n// Use proto::external_transforms again, this time to map the divides_rule\n// to a transforms that performs checked division.\nstruct checked_division\n  : proto::external_transforms<\n        proto::when<\n            divides_rule\n          , do_checked_divide(calc_grammar(proto::_left), calc_grammar(proto::_right))\n        >\n    >\n{};\n\nint main()\n{\n    non_checked_division non_checked;\n    int result2 = calc_grammar()(_1 / _2, fusion::make_vector(6, 2), non_checked);\n    BOOST_ASSERT(result2 == 3);\n\n    try\n    {\n        checked_division checked;\n        // This should throw\n        int result3 = calc_grammar()(_1 / _2, fusion::make_vector(6, 0), checked);\n        BOOST_ASSERT(false); // shouldn't get here!\n    }\n    catch(division_by_zero)\n    {\n        std::cout << \"caught division by zero!\\n\";\n    }\n}\n//]\n", "meta": {"hexsha": "e9b06a3d5d8cc2aada1bf5e87cb1d58afb1cd541", "size": 3841, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/proto/example/external_transforms.cpp", "max_stars_repo_name": "AishwaryaDoosa/Boost1.49", "max_stars_repo_head_hexsha": "67bdb3b36d72dec7414a62f3b050162e608ea266", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-01-03T23:52:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-22T17:41:27.000Z", "max_issues_repo_path": "libs/proto/example/external_transforms.cpp", "max_issues_repo_name": "AishwaryaDoosa/Boost1.49", "max_issues_repo_head_hexsha": "67bdb3b36d72dec7414a62f3b050162e608ea266", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/proto/example/external_transforms.cpp", "max_forks_repo_name": "AishwaryaDoosa/Boost1.49", "max_forks_repo_head_hexsha": "67bdb3b36d72dec7414a62f3b050162e608ea266", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-11-08T01:56:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-21T09:02:49.000Z", "avg_line_length": 29.7751937984, "max_line_length": 86, "alphanum_fraction": 0.6633689143, "num_tokens": 935, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583124210896, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.47030398677459495}}
{"text": "// (C) 2014 Arek Olek\n\n#pragma once\n\n#include <deque>\n#include <vector>\n\n#include <boost/graph/adjacency_list.hpp>\n\n#include \"range.hpp\"\n\ntemplate <class Graph, class Tree>\nTree greedy_tree(Graph const & G, unsigned seed) {\n  typedef std::pair<int, int> edge;\n\n  unsigned n = num_vertices(G);\n  Tree T(n);\n\n  std::vector<bool> visited(n, false);\n  std::deque<edge> edges;\n  std::default_random_engine gen(seed);\n  unsigned v = std::uniform_int_distribution<unsigned>{0, n-1}(gen);\n  int x = -1, y = -1;\n\n  while(true) {\n    visited[v] = true;\n\n    int i = 0;\n    for(auto w : shuffled(adjacent_vertices(v, G), gen)) if(!visited[w]) {\n      if(++i == 1) x = v, y = w;\n      else         edges.emplace_back (v, w);\n    }\n\n    if(i == 0) {\n      std::shuffle(edges.begin(), edges.end(), gen);\n      do {\n        if(edges.empty()) return T;\n        std::tie(x, y) = edges.front();\n        edges.pop_front();\n      } while(visited[y]);\n    }\n\n    add_edge(x, y, T);\n    v = y;\n  }\n}\n", "meta": {"hexsha": "02ad5a9ac2d115beb92f7f1d7d0b612d0c613bdd", "size": 978, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "graph/greedy.hpp", "max_stars_repo_name": "arekolek/MaxIST", "max_stars_repo_head_hexsha": "6a8b49152cfbf34c1c2728f64b1457a23824fe0d", "max_stars_repo_licenses": ["MIT"], "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/greedy.hpp", "max_issues_repo_name": "arekolek/MaxIST", "max_issues_repo_head_hexsha": "6a8b49152cfbf34c1c2728f64b1457a23824fe0d", "max_issues_repo_licenses": ["MIT"], "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/greedy.hpp", "max_forks_repo_name": "arekolek/MaxIST", "max_forks_repo_head_hexsha": "6a8b49152cfbf34c1c2728f64b1457a23824fe0d", "max_forks_repo_licenses": ["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.8085106383, "max_line_length": 74, "alphanum_fraction": 0.5766871166, "num_tokens": 285, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.734119526900183, "lm_q2_score": 0.6406358617010351, "lm_q1q2_score": 0.470303295707255}}
{"text": "#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE ProMPs\n#include <boost/test/unit_test.hpp>\n#include <chrono>\n#include <ProMPs_emission.hpp>\n\n#define EPSILON 1e-6\n\nusing namespace arma;\nusing namespace hsmm;\nusing namespace std;\n\n\nProMPsEmission getExampleProMP() {\n    int n_basis_functions = 4;\n    int njoints = 1;\n    int nstates = 5;\n\n    // Setting a third order polynomial basis function for the ProMP\n    int polynomial_order = n_basis_functions - 1;\n    shared_ptr<ScalarBasisFun> kernel{ new ScalarPolyBasis(polynomial_order)};\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.fill(i * 10);\n        mat Sigma_w = (i + 1) * eye<mat>(n_basis_functions * njoints,\n                    n_basis_functions * njoints);\n        mat Sigma_y = 0.0001*eye<mat>(njoints, njoints);\n        ProMP promp(mu_w, Sigma_w, Sigma_y);\n        FullProMP poly(kernel, promp, njoints);\n        promps.push_back(poly);\n    }\n\n    ProMPsEmission emission(promps);\n    return emission;\n}\n\nBOOST_AUTO_TEST_CASE( ProMPs ) {\n\n    // Creating the ProMP emission.\n    ProMPsEmission emission = getExampleProMP();\n\n    for(int i = 0; i < emission.getNumberStates(); i++) {\n        for(int size = 1; size < 100; size += 10) {\n            field<mat> obs = emission.sampleFromState(i, size);\n            double loglikelihood = emission.loglikelihood(i, obs);\n            double Iloglikelihood = emission.informationFilterLoglikelihood(i,\n                obs);\n            BOOST_CHECK(fabs(loglikelihood - Iloglikelihood) < EPSILON);\n        }\n    }\n\n    // Comparing the running time.\n    int benchmark_size = 200;\n    for(int i = 0; i < emission.getNumberStates(); i++) {\n        auto t1 = chrono::high_resolution_clock::now();\n        auto sample = emission.sampleFromState(i, benchmark_size);\n        double kf_loglikelihood = emission.loglikelihood(i, sample);\n        auto t2 = chrono::high_resolution_clock::now();\n        double if_loglikelihood = emission.informationFilterLoglikelihood(i,\n                sample);\n        auto t3 = chrono::high_resolution_clock::now();\n        auto elapsed_kf = chrono::duration_cast<chrono::milliseconds>(\n                t2 - t1).count();\n        auto elapsed_if = chrono::duration_cast<chrono::milliseconds>(\n                t3 - t2).count();\n        cout << \"Elapsed KF: \" << elapsed_kf << \" Elapsed IF: \" <<\n                elapsed_if << endl;\n        BOOST_CHECK(fabs(kf_loglikelihood - if_loglikelihood)\n                < EPSILON);\n    }\n\n    // Checking the missing output handling.\n    for(int i = 0; i < emission.getNumberStates(); i++) {\n        int size = 100;\n        field<mat> obs1 = emission.sampleFromState(i, size);\n        int missing_from = 50;\n        for(int j = missing_from; j < obs1.n_elem; j++)\n            obs1(j).reset();\n        // Making sure it doesn't fail. TODO: compare with other thing.\n        double ll1 = emission.loglikelihood(i, obs1);\n    }\n}\n", "meta": {"hexsha": "19d2655197d802d526497402aeb795b23976ad31", "size": 3040, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/ProMPs_test.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": "tests/ProMPs_test.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": "tests/ProMPs_test.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": 35.3488372093, "max_line_length": 78, "alphanum_fraction": 0.6302631579, "num_tokens": 754, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.47030329067036036}}
{"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_EXPONENTIAL_CONSTANTS_EXP_1_HPP_INCLUDED\n#define NT2_EXPONENTIAL_CONSTANTS_EXP_1_HPP_INCLUDED\n\n#include <nt2/include/functor.hpp>\n#include <boost/simd/constant/hierarchy.hpp>\n#include <boost/simd/constant/register.hpp>\n\nnamespace nt2\n{\n  namespace tag\n  {\n    /*!\n      @brief Exp_1 generic tag\n\n      Represents the Exp_1 constant in generic contexts.\n\n      @par Models:\n      Hierarchy\n    **/\n    BOOST_SIMD_CONSTANT_REGISTER( Exp_1, double\n                                , 2, 0x402df854\n                                , 0x4005bf0a8b145769LL\n                                )\n  }\n  namespace ext\n  {\n    template<class Site>\n    BOOST_FORCEINLINE generic_dispatcher<tag::Exp_1, Site> dispatching_Exp_1(adl_helper, boost::dispatch::meta::unknown_<Site>, ...)\n    {\n      return generic_dispatcher<tag::Exp_1, Site>();\n    }\n    template<class... Args>\n    struct impl_Exp_1;\n  }\n  /*!\n    Generates constant e.\n\n    @par Semantic:\n    The e constant is the real number such that \\f$\\log(e) = 1\\f$\n\n    @code\n    T r = Exp_1<T>();\n    @endcode\n\n    is similar to:\n\n    @code\n      r =  T(2.71828182845904523536028747135266249775724709369995);\n    @endcode\n\n  **/\n  BOOST_SIMD_CONSTANT_IMPLEMENTATION(tag::Exp_1, Exp_1);\n}\n\n#endif\n", "meta": {"hexsha": "6680cad452e54163511662080069202e565b49b0", "size": 1754, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/exponential/include/nt2/exponential/constants/exp_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/exponential/include/nt2/exponential/constants/exp_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/exponential/include/nt2/exponential/constants/exp_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.40625, "max_line_length": 132, "alphanum_fraction": 0.5689851767, "num_tokens": 438, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.47030329067036036}}
{"text": "//***************************************************************************************\n// HW02App.cpp by Frank Luna (C) 2015 All Rights Reserved.\n//***************************************************************************************\n\n\n#include \"../common/d3dApp.h\"\n#include \"../common/MathHelper.h\"\n#include <UDX12/UploadBuffer.h>\n#include \"../common/GeometryGenerator.h\"\n#include \"util.h\"\n\n#include <Eigen/Sparse>\n\nusing Microsoft::WRL::ComPtr;\nusing namespace DirectX;\nusing namespace DirectX::PackedVector;\n\nconst int gNumFrameResources = 3;\n\nstruct V : Ubpa::TVertex<Ubpa::HEMeshTriats_EmptyEP<V>> {\n\tUbpa::pointf3 pos;\n\tUbpa::pointf2 uv;\n};\n\nstruct ObjectConstants\n{\n\tDirectX::XMFLOAT4X4 World = MathHelper::Identity4x4();\n\tDirectX::XMFLOAT4X4 TexTransform = MathHelper::Identity4x4();\n};\n\nstruct PassConstants\n{\n\tDirectX::XMFLOAT4X4 View = MathHelper::Identity4x4();\n\tDirectX::XMFLOAT4X4 InvView = MathHelper::Identity4x4();\n\tDirectX::XMFLOAT4X4 Proj = MathHelper::Identity4x4();\n\tDirectX::XMFLOAT4X4 InvProj = MathHelper::Identity4x4();\n\tDirectX::XMFLOAT4X4 ViewProj = MathHelper::Identity4x4();\n\tDirectX::XMFLOAT4X4 InvViewProj = MathHelper::Identity4x4();\n\tDirectX::XMFLOAT3 EyePosW = { 0.0f, 0.0f, 0.0f };\n\tfloat cbPerObjectPad1 = 0.0f;\n\tDirectX::XMFLOAT2 RenderTargetSize = { 0.0f, 0.0f };\n\tDirectX::XMFLOAT2 InvRenderTargetSize = { 0.0f, 0.0f };\n\tfloat NearZ = 0.0f;\n\tfloat FarZ = 0.0f;\n\tfloat TotalTime = 0.0f;\n\tfloat DeltaTime = 0.0f;\n\n\tDirectX::XMFLOAT4 AmbientLight = { 0.0f, 0.0f, 0.0f, 1.0f };\n\n\t// Indices [0, NUM_DIR_LIGHTS) are directional lights;\n\t// indices [NUM_DIR_LIGHTS, NUM_DIR_LIGHTS+NUM_POINT_LIGHTS) are point lights;\n\t// indices [NUM_DIR_LIGHTS+NUM_POINT_LIGHTS, NUM_DIR_LIGHTS+NUM_POINT_LIGHT+NUM_SPOT_LIGHTS)\n\t// are spot lights for a maximum of MaxLights per object.\n\tLight Lights[MaxLights];\n};\n\nstruct Vertex\n{\n\tDirectX::XMFLOAT3 Pos;\n\tDirectX::XMFLOAT3 Normal;\n\tDirectX::XMFLOAT2 TexC;\n};\n\n// Lightweight structure stores parameters to draw a shape.  This will\n// vary from app-to-app.\nstruct RenderItem\n{\n\tRenderItem() = default;\n\n    // World matrix of the shape that describes the object's local space\n    // relative to the world space, which defines the position, orientation,\n    // and scale of the object in the world.\n    XMFLOAT4X4 World = MathHelper::Identity4x4();\n\n\tXMFLOAT4X4 TexTransform = MathHelper::Identity4x4();\n\n\t// Dirty flag indicating the object data has changed and we need to update the constant buffer.\n\t// Because we have an object cbuffer for each FrameResource, we have to apply the\n\t// update to each FrameResource.  Thus, when we modify obect data we should set \n\t// NumFramesDirty = gNumFrameResources so that each frame resource gets the update.\n\tint NumFramesDirty = gNumFrameResources;\n\n\t// Index into GPU constant buffer corresponding to the ObjectCB for this render item.\n\tUINT ObjCBIndex = -1;\n\n\tMaterial* Mat = nullptr;\n\tUbpa::DX12::MeshGeometry* Geo = nullptr;\n\t//std::string Geo;\n\n    // Primitive topology.\n    D3D12_PRIMITIVE_TOPOLOGY PrimitiveType = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST;\n\n    // DrawIndexedInstanced parameters.\n    UINT IndexCount = 0;\n    UINT StartIndexLocation = 0;\n    int BaseVertexLocation = 0;\n};\n\nclass HW04App : public D3DApp\n{\npublic:\n    HW04App(HINSTANCE hInstance);\n    HW04App(const HW04App& rhs) = delete;\n    HW04App& operator=(const HW04App& rhs) = delete;\n    ~HW04App();\n\n    virtual bool Initialize()override;\n\nprivate:\n    virtual void OnResize()override;\n    virtual void Update(const GameTimer& gt)override;\n    virtual void Draw(const GameTimer& gt)override;\n\n    virtual void OnMouseDown(WPARAM btnState, int x, int y)override;\n    virtual void OnMouseUp(WPARAM btnState, int x, int y)override;\n    virtual void OnMouseMove(WPARAM btnState, int x, int y)override;\n\n    void OnKeyboardInput(const GameTimer& gt);\n\tvoid UpdateCamera(const GameTimer& gt);\n\tvoid AnimateMaterials(const GameTimer& gt);\n\tvoid UpdateObjectCBs(const GameTimer& gt);\n\tvoid UpdateMaterialCBs(const GameTimer& gt);\n\tvoid UpdateMainPassCB(const GameTimer& gt);\n\n\tvoid LoadTextures();\n    void BuildRootSignature();\n\tvoid BuildDescriptorHeaps();\n    void BuildShadersAndInputLayout();\n    void BuildShapeGeometry();\n    void BuildPSOs();\n    void BuildFrameResources();\n    void BuildMaterials();\n    void BuildRenderItems();\n    void DrawRenderItems(ID3D12GraphicsCommandList* cmdList, const std::vector<RenderItem*>& ritems);\n\n\tstd::array<const CD3DX12_STATIC_SAMPLER_DESC, 6> GetStaticSamplers();\n\nprivate:\n\n\tstd::vector<std::unique_ptr<Ubpa::DX12::FrameResource>> mFrameResources;\n\tUbpa::DX12::FrameResource* mCurrFrameResource = nullptr;\n    int mCurrFrameResourceIndex = 0;\n\n\tstd::unordered_map<std::string, std::unique_ptr<Material>> mMaterials;\n\n    std::vector<D3D12_INPUT_ELEMENT_DESC> mInputLayout;\n \n\t// List of all the render items.\n\tstd::vector<std::unique_ptr<RenderItem>> mAllRitems;\n\n\t// Render items divided by PSO.\n\tstd::vector<RenderItem*> mOpaqueRitems;\n\n    PassConstants mMainPassCB;\n\n\tXMFLOAT3 mEyePos = { 0.0f, 0.0f, 0.0f };\n\tXMFLOAT4X4 mView = MathHelper::Identity4x4();\n\tXMFLOAT4X4 mProj = MathHelper::Identity4x4();\n\n\tfloat mTheta = 1.3f*XM_PI;\n\tfloat mPhi = 0.4f*XM_PI;\n\tfloat mRadius = 2.5f;\n\n    POINT mLastMousePos;\n\n\tstd::unordered_map<std::string, std::unique_ptr<Ubpa::TriMesh>> trimeshes;\n\n\t// frame graph\n\t//Ubpa::DX12::FG::RsrcMngr fgRsrcMngr;\n\tUbpa::DX12::FG::Executor fgExecutor;\n\tUbpa::FG::Compiler fgCompiler;\n\tUbpa::FG::FrameGraph fg;\n};\n\nint WINAPI WinMain(HINSTANCE hInstance, HINSTANCE prevInstance,\n    PSTR cmdLine, int showCmd)\n{\n    // Enable run-time memory check for debug builds.\n#if defined(DEBUG) | defined(_DEBUG)\n    _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);\n#endif\n\n    try\n    {\n        HW04App theApp(hInstance);\n        if(!theApp.Initialize())\n            return 0;\n\n        int rst = theApp.Run();\n\t\tUbpa::DXRenderer::Instance().Release();\n\t\treturn rst;\n    }\n    catch(Ubpa::DX12::Util::Exception& e)\n    {\n        MessageBox(nullptr, e.ToString().c_str(), L\"HR Failed\", MB_OK);\n        return 0;\n    }\n\n}\n\nHW04App::HW04App(HINSTANCE hInstance)\n    : D3DApp(hInstance)\n{\n}\n\nHW04App::~HW04App()\n{\n    if(!uDevice.IsNull())\n        FlushCommandQueue();\n}\n\nbool HW04App::Initialize()\n{\n    if(!D3DApp::Initialize())\n        return false;\n\n\tUbpa::DXRenderer::Instance().Init(uDevice.raw.Get());\n\n\tUbpa::DX12::DescriptorHeapMngr::Instance().Init(uDevice.raw.Get(), 1024, 1024, 1024, 1024, 1024);\n\n\t//fgRsrcMngr.Init(uGCmdList, uDevice);\n\n    // Reset the command list to prep for initialization commands.\n    ThrowIfFailed(uGCmdList->Reset(mDirectCmdListAlloc.Get(), nullptr));\n\n    // Get the increment size of a descriptor in this heap type.  This is hardware specific, \n\t// so we have to query this information.\n    //mCbvSrvDescriptorSize = uDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);\n\n\tUbpa::DXRenderer::Instance().GetUpload().Begin();\n \n\tLoadTextures();\n    BuildRootSignature();\n\tBuildDescriptorHeaps();\n    BuildShadersAndInputLayout();\n    BuildShapeGeometry();\n\tBuildMaterials();\n    BuildRenderItems();\n    BuildFrameResources();\n    BuildPSOs();\n\n    // Execute the initialization commands.\n    ThrowIfFailed(uGCmdList->Close());\n\tuCmdQueue.Execute(uGCmdList.raw.Get());\n\n\tUbpa::DXRenderer::Instance().GetUpload().End(uCmdQueue.raw.Get());\n\n    // Wait until initialization is complete.\n    FlushCommandQueue();\n\n    return true;\n}\n \nvoid HW04App::OnResize()\n{\n    D3DApp::OnResize();\n\n    // The window resized, so update the aspect ratio and recompute the projection matrix.\n    XMMATRIX P = XMMatrixPerspectiveFovLH(0.25f*MathHelper::Pi, AspectRatio(), 1.0f, 1000.0f);\n    XMStoreFloat4x4(&mProj, P);\n\n\tauto clearFGRsrcMngr = [](void* rsrcMngr) {\n\t\treinterpret_cast<Ubpa::DX12::FG::RsrcMngr*>(rsrcMngr)->Clear();\n\t};\n\tfor (auto& frsrc : mFrameResources)\n\t\tfrsrc->DelayUpdateResource(\"FrameGraphRsrcMngr\", clearFGRsrcMngr);\n}\n\nvoid HW04App::Update(const GameTimer& gt)\n{\n    OnKeyboardInput(gt);\n\tUpdateCamera(gt);\n\n    // Cycle through the circular frame resource array.\n    mCurrFrameResourceIndex = (mCurrFrameResourceIndex + 1) % gNumFrameResources;\n    mCurrFrameResource = mFrameResources[mCurrFrameResourceIndex].get();\n\n    // Has the GPU finished processing the commands of the current frame resource?\n    // If not, wait until the GPU has completed commands up to this fence point.\n\tmCurrFrameResource->Wait();\n\n\tAnimateMaterials(gt);\n\tUpdateObjectCBs(gt);\n\tUpdateMaterialCBs(gt);\n\tUpdateMainPassCB(gt);\n}\n\nvoid HW04App::Draw(const GameTimer& gt)\n{\n\tauto cmdListAlloc = mCurrFrameResource->GetResource<ID3D12CommandAllocator>(\"CommandAllocator\");\n\n    // Reuse the memory associated with command recording.\n    // We can only reset when the associated command lists have finished execution on the GPU.\n    ThrowIfFailed(cmdListAlloc->Reset());\n\n    // A command list can be reset after it has been added to the command queue via ExecuteCommandList.\n    // Reusing the command list reuses memory.\n\tThrowIfFailed(uGCmdList->Reset(cmdListAlloc, nullptr));\n\tuGCmdList.SetDescriptorHeaps(Ubpa::DX12::DescriptorHeapMngr::Instance().GetCSUGpuDH()->GetDescriptorHeap());\n\n\tuGCmdList->RSSetViewports(1, &mScreenViewport);\n\tuGCmdList->RSSetScissorRects(1, &mScissorRect);\n\n\tfg.Clear();\n\tauto fgRsrcMngr = mCurrFrameResource->GetResource<Ubpa::DX12::FG::RsrcMngr>(\"FrameGraphRsrcMngr\");\n\tfgRsrcMngr->NewFrame();\n\tfgExecutor.NewFrame();;\n\n\tauto gbuffer0 = fg.AddResourceNode(\"GBuffer0\");\n\tauto gbuffer1 = fg.AddResourceNode(\"GBuffer1\");\n\tauto gbuffer2 = fg.AddResourceNode(\"GBuffer2\");\n\tauto backbuffer = fg.AddResourceNode(\"Back Buffer\");\n\tauto depthstencil = fg.AddResourceNode(\"Depth Stencil\");\n\tauto gbPass = fg.AddPassNode(\n\t\t\"GBuffer Pass\",\n\t\t{},\n\t\t{ gbuffer0,gbuffer1,gbuffer2,depthstencil }\n\t);\n\t/*auto debugPass = fg.AddPassNode(\n\t\t\"Debug\",\n\t\t{ gbuffer1 },\n\t\t{ backbuffer }\n\t);*/\n\tauto deferLightingPass = fg.AddPassNode(\n\t\t\"Defer Lighting\",\n\t\t{ gbuffer0,gbuffer1,gbuffer2 },\n\t\t{ backbuffer }\n\t);\n\n\t(*fgRsrcMngr)\n\t\t.RegisterTemporalRsrc(gbuffer0,\n\t\t\tUbpa::DX12::FG::RsrcType::RT2D(DXGI_FORMAT_R32G32B32A32_FLOAT, mClientWidth, mClientHeight, Colors::Black))\n\t\t.RegisterTemporalRsrc(gbuffer1,\n\t\t\tUbpa::DX12::FG::RsrcType::RT2D(DXGI_FORMAT_R32G32B32A32_FLOAT, mClientWidth, mClientHeight, Colors::Black))\n\t\t.RegisterTemporalRsrc(gbuffer2,\n\t\t\tUbpa::DX12::FG::RsrcType::RT2D(DXGI_FORMAT_R32G32B32A32_FLOAT, mClientWidth, mClientHeight, Colors::Black))\n\n\t\t.RegisterRsrcTable({\n\t\t\t{gbuffer0,Ubpa::DX12::Desc::SRV::Tex2D(DXGI_FORMAT_R32G32B32A32_FLOAT)},\n\t\t\t{gbuffer1,Ubpa::DX12::Desc::SRV::Tex2D(DXGI_FORMAT_R32G32B32A32_FLOAT)},\n\t\t\t{gbuffer2,Ubpa::DX12::Desc::SRV::Tex2D(DXGI_FORMAT_R32G32B32A32_FLOAT)} })\n\n\t\t.RegisterImportedRsrc(backbuffer, { CurrentBackBuffer(), D3D12_RESOURCE_STATE_PRESENT })\n\t\t.RegisterImportedRsrc(depthstencil, { mDepthStencilBuffer.Get(), D3D12_RESOURCE_STATE_DEPTH_WRITE })\n\n\t\t.RegisterPassRsrcs(gbPass, gbuffer0, D3D12_RESOURCE_STATE_RENDER_TARGET,\n\t\t\tUbpa::DX12::FG::RsrcImplDesc_RTV_Null{})\n\t\t.RegisterPassRsrcs(gbPass, gbuffer1, D3D12_RESOURCE_STATE_RENDER_TARGET,\n\t\t\tUbpa::DX12::FG::RsrcImplDesc_RTV_Null{})\n\t\t.RegisterPassRsrcs(gbPass, gbuffer2, D3D12_RESOURCE_STATE_RENDER_TARGET,\n\t\t\tUbpa::DX12::FG::RsrcImplDesc_RTV_Null{})\n\t\t.RegisterPassRsrcs(gbPass, depthstencil,\n\t\t\tD3D12_RESOURCE_STATE_DEPTH_WRITE, Ubpa::DX12::Desc::DSV::Basic(mDepthStencilFormat))\n\n\t\t/*.RegisterPassRsrcs(debugPass, gbuffer1, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE,\n\t\t\tUbpa::DX12::Desc::SRV::Tex2D(DXGI_FORMAT_R32G32B32A32_FLOAT))\n\n\t\t.RegisterPassRsrcs(debugPass, backbuffer, D3D12_RESOURCE_STATE_RENDER_TARGET,\n\t\t\tUbpa::DX12::FG::RsrcImplDesc_RTV_Null{})*/\n\n\t\t.RegisterPassRsrcs(deferLightingPass, gbuffer0, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE,\n\t\t\tUbpa::DX12::Desc::SRV::Tex2D(DXGI_FORMAT_R32G32B32A32_FLOAT))\n\t\t.RegisterPassRsrcs(deferLightingPass, gbuffer1, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE,\n\t\t\tUbpa::DX12::Desc::SRV::Tex2D(DXGI_FORMAT_R32G32B32A32_FLOAT))\n\t\t.RegisterPassRsrcs(deferLightingPass, gbuffer2, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE,\n\t\t\tUbpa::DX12::Desc::SRV::Tex2D(DXGI_FORMAT_R32G32B32A32_FLOAT))\n\n\t\t.RegisterPassRsrcs(deferLightingPass, backbuffer, D3D12_RESOURCE_STATE_RENDER_TARGET,\n\t\t\tUbpa::DX12::FG::RsrcImplDesc_RTV_Null{})\n\t\t;\n\n\tfgExecutor.RegisterPassFunc(\n\t\tgbPass,\n\t\t[&](const Ubpa::DX12::FG::PassRsrcs& rsrcs) {\n\t\t\tuGCmdList->SetPipelineState(Ubpa::DXRenderer::Instance().GetPSO(\"geometry\"));\n\t\t\tauto gb0 = rsrcs.find(gbuffer0)->second;\n\t\t\tauto gb1 = rsrcs.find(gbuffer1)->second;\n\t\t\tauto gb2 = rsrcs.find(gbuffer2)->second;\n\t\t\tauto ds = rsrcs.find(depthstencil)->second;\n\n\t\t\t// Clear the render texture and depth buffer.\n\t\t\tuGCmdList.ClearRenderTargetView(gb0.cpuHandle, Colors::Black);\n\t\t\tuGCmdList.ClearRenderTargetView(gb1.cpuHandle, Colors::Black);\n\t\t\tuGCmdList.ClearRenderTargetView(gb2.cpuHandle, Colors::Black);\n\t\t\tuGCmdList.ClearDepthStencilView(ds.cpuHandle);\n\n\t\t\t// Specify the buffers we are going to render to.\n\t\t\tstd::array rts{ gb0.cpuHandle,gb1.cpuHandle,gb2.cpuHandle };\n\t\t\tuGCmdList->OMSetRenderTargets(rts.size(), rts.data(), false, &ds.cpuHandle);\n\n\t\t\tuGCmdList->SetGraphicsRootSignature(Ubpa::DXRenderer::Instance().GetRootSignature(\"geometry\"));\n\n\t\t\tauto passCB = mCurrFrameResource\n\t\t\t\t->GetResource<Ubpa::DX12::ArrayUploadBuffer<PassConstants>>(\"gbPass constants\")\n\t\t\t\t->GetResource();\n\t\t\tuGCmdList->SetGraphicsRootConstantBufferView(2, passCB->GetGPUVirtualAddress());\n\n\t\t\tDrawRenderItems(uGCmdList.raw.Get(), mOpaqueRitems);\n\t\t}\n\t);\n\n\t//fgExecutor.RegisterPassFunc(\n\t//\tdebugPass,\n\t//\t[&](const Ubpa::DX12::FG::PassRsrcs& rsrcs) {\n\t//\t\tuGCmdList->SetPipelineState(Ubpa::DXRenderer::Instance().GetPSO(\"screen\"));\n\t//\t\tauto img = rsrcs.find(gbuffer1)->second;\n\t//\t\tauto bb = rsrcs.find(backbuffer)->second;\n\t//\t\t\n\t//\t\t//uGCmdList->CopyResource(bb.resource, rt.resource);\n\n\t//\t\t// Clear the render texture and depth buffer.\n\t//\t\tuGCmdList.ClearRenderTargetView(bb.cpuHandle, Colors::LightSteelBlue);\n\n\t//\t\t// Specify the buffers we are going to render to.\n\t//\t\t//uGCmdList.OMSetRenderTarget(bb.cpuHandle, ds.cpuHandle);\n\t//\t\tuGCmdList->OMSetRenderTargets(1, &bb.cpuHandle, false, nullptr);\n\n\t//\t\tuGCmdList->SetGraphicsRootSignature(Ubpa::DXRenderer::Instance().GetRootSignature(\"screen\"));\n\n\t//\t\tuGCmdList->SetGraphicsRootDescriptorTable(0, img.gpuHandle);\n\n\t//\t\tuGCmdList->IASetVertexBuffers(0, 0, nullptr);\n\t//\t\tuGCmdList->IASetIndexBuffer(nullptr);\n\t//\t\tuGCmdList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);\n\t//\t\tuGCmdList->DrawInstanced(6, 1, 0, 0);\n\t//\t}\n\t//);\n\n\tfgExecutor.RegisterPassFunc(\n\t\tdeferLightingPass,\n\t\t[&](const Ubpa::DX12::FG::PassRsrcs& rsrcs) {\n\t\t\tuGCmdList->SetPipelineState(Ubpa::DXRenderer::Instance().GetPSO(\"defer lighting\"));\n\t\t\tauto gb0 = rsrcs.find(gbuffer0)->second;\n\t\t\tauto gb1 = rsrcs.find(gbuffer1)->second;\n\t\t\tauto gb2 = rsrcs.find(gbuffer2)->second;\n\n\t\t\tauto bb = rsrcs.find(backbuffer)->second;\n\n\t\t\t//uGCmdList->CopyResource(bb.resource, rt.resource);\n\n\t\t\t// Clear the render texture and depth buffer.\n\t\t\tuGCmdList.ClearRenderTargetView(bb.cpuHandle, Colors::LightSteelBlue);\n\n\t\t\t// Specify the buffers we are going to render to.\n\t\t\t//uGCmdList.OMSetRenderTarget(bb.cpuHandle, ds.cpuHandle);\n\t\t\tuGCmdList->OMSetRenderTargets(1, &bb.cpuHandle, false, nullptr);\n\n\t\t\tuGCmdList->SetGraphicsRootSignature(Ubpa::DXRenderer::Instance().GetRootSignature(\"defer lighting\"));\n\n\t\t\tuGCmdList->SetGraphicsRootDescriptorTable(0, gb0.gpuHandle);\n\n\t\t\tuGCmdList->IASetVertexBuffers(0, 0, nullptr);\n\t\t\tuGCmdList->IASetIndexBuffer(nullptr);\n\t\t\tuGCmdList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);\n\t\t\tuGCmdList->DrawInstanced(6, 1, 0, 0);\n\t\t}\n\t);\n\n\tstatic bool flag{ false };\n\tif (!flag) {\n\t\tOutputDebugStringA(fg.ToGraphvizGraph().Dump().c_str());\n\t\tflag = true;\n\t}\n\n\tauto [success, crst] = fgCompiler.Compile(fg);\n\tfgExecutor.Execute(crst, *fgRsrcMngr);\n\n    // Done recording commands.\n    ThrowIfFailed(uGCmdList->Close());\n\n    // Add the command list to the queue for execution.\n\tuCmdQueue.Execute(uGCmdList.raw.Get());\n\n    // Swap the back and front buffers\n    ThrowIfFailed(mSwapChain->Present(0, 0));\n\tmCurrBackBuffer = (mCurrBackBuffer + 1) % SwapChainBufferCount;\n\n\tmCurrFrameResource->Signal(uCmdQueue.raw.Get(), ++mCurrentFence);\n}\n\nvoid HW04App::OnMouseDown(WPARAM btnState, int x, int y)\n{\n    mLastMousePos.x = x;\n    mLastMousePos.y = y;\n\n    SetCapture(mhMainWnd);\n}\n\nvoid HW04App::OnMouseUp(WPARAM btnState, int x, int y)\n{\n    ReleaseCapture();\n}\n\nvoid HW04App::OnMouseMove(WPARAM btnState, int x, int y)\n{\n    if((btnState & MK_LBUTTON) != 0)\n    {\n        // Make each pixel correspond to a quarter of a degree.\n        float dx = XMConvertToRadians(0.25f*static_cast<float>(x - mLastMousePos.x));\n        float dy = XMConvertToRadians(0.25f*static_cast<float>(y - mLastMousePos.y));\n\n        // Update angles based on input to orbit camera around box.\n        mTheta += dx;\n        mPhi += dy;\n\n        // Restrict the angle mPhi.\n        mPhi = MathHelper::Clamp(mPhi, 0.1f, MathHelper::Pi - 0.1f);\n    }\n    else if((btnState & MK_RBUTTON) != 0)\n    {\n        // Make each pixel correspond to 0.2 unit in the scene.\n        float dx = 0.05f*static_cast<float>(x - mLastMousePos.x);\n        float dy = 0.05f*static_cast<float>(y - mLastMousePos.y);\n\n        // Update the camera radius based on input.\n        mRadius += dx - dy;\n\n        // Restrict the radius.\n        mRadius = MathHelper::Clamp(mRadius, 2.0f, 150.0f);\n    }\n\n    mLastMousePos.x = x;\n    mLastMousePos.y = y;\n}\n \nvoid HW04App::OnKeyboardInput(const GameTimer& gt)\n{\n}\n \nvoid HW04App::UpdateCamera(const GameTimer& gt)\n{\n\t// Convert Spherical to Cartesian coordinates.\n\tmEyePos.x = mRadius*sinf(mPhi)*cosf(mTheta);\n\tmEyePos.z = mRadius*sinf(mPhi)*sinf(mTheta);\n\tmEyePos.y = mRadius*cosf(mPhi);\n\n\t// Build the view matrix.\n\tXMVECTOR pos = XMVectorSet(mEyePos.x, mEyePos.y, mEyePos.z, 1.0f);\n\tXMVECTOR target = XMVectorZero();\n\tXMVECTOR up = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);\n\n\tXMMATRIX view = XMMatrixLookAtLH(pos, target, up);\n\tXMStoreFloat4x4(&mView, view);\n}\n\nvoid HW04App::AnimateMaterials(const GameTimer& gt)\n{\n\t\n}\n\nvoid HW04App::UpdateObjectCBs(const GameTimer& gt)\n{\n\tauto currObjectCB = mCurrFrameResource\n\t\t->GetResource<Ubpa::DX12::ArrayUploadBuffer<ObjectConstants>>(\"ArrayUploadBuffer<ObjectConstants>\");\n\tfor(auto& e : mAllRitems)\n\t{\n\t\t// Only update the cbuffer data if the constants have changed.  \n\t\t// This needs to be tracked per frame resource.\n\t\tif(e->NumFramesDirty > 0)\n\t\t{\n\t\t\tXMMATRIX world = XMLoadFloat4x4(&e->World);\n\t\t\tXMMATRIX texTransform = XMLoadFloat4x4(&e->TexTransform);\n\n\t\t\tObjectConstants objConstants;\n\t\t\tXMStoreFloat4x4(&objConstants.World, XMMatrixTranspose(world));\n\t\t\tXMStoreFloat4x4(&objConstants.TexTransform, XMMatrixTranspose(texTransform));\n\n\t\t\tcurrObjectCB->Set(e->ObjCBIndex, objConstants);\n\n\t\t\t// Next FrameResource need to be updated too.\n\t\t\te->NumFramesDirty--;\n\t\t}\n\t}\n}\n\nvoid HW04App::UpdateMaterialCBs(const GameTimer& gt)\n{\n\tauto currMaterialCB = mCurrFrameResource\n\t\t->GetResource<Ubpa::DX12::ArrayUploadBuffer<MaterialConstants>>(\"ArrayUploadBuffer<MaterialConstants>\");\n\tfor(auto& e : mMaterials)\n\t{\n\t\t// Only update the cbuffer data if the constants have changed.  If the cbuffer\n\t\t// data changes, it needs to be updated for each FrameResource.\n\t\tMaterial* mat = e.second.get();\n\t\tif(mat->NumFramesDirty > 0)\n\t\t{\n\t\t\tXMMATRIX matTransform = XMLoadFloat4x4(&mat->MatTransform);\n\n\t\t\tMaterialConstants matConstants;\n\t\t\tmatConstants.DiffuseAlbedo = mat->DiffuseAlbedo;\n\t\t\tmatConstants.FresnelR0 = mat->FresnelR0;\n\t\t\tmatConstants.Roughness = mat->Roughness;\n\t\t\tXMStoreFloat4x4(&matConstants.MatTransform, XMMatrixTranspose(matTransform));\n\n\t\t\tcurrMaterialCB->Set(mat->MatCBIndex, matConstants);\n\n\t\t\t// Next FrameResource need to be updated too.\n\t\t\tmat->NumFramesDirty--;\n\t\t}\n\t}\n}\n\nvoid HW04App::UpdateMainPassCB(const GameTimer& gt)\n{\n\tXMMATRIX view = XMLoadFloat4x4(&mView);\n\tXMMATRIX proj = XMLoadFloat4x4(&mProj);\n\n\tXMMATRIX viewProj = XMMatrixMultiply(view, proj);\n\tXMMATRIX invView = XMMatrixInverse(&XMMatrixDeterminant(view), view);\n\tXMMATRIX invProj = XMMatrixInverse(&XMMatrixDeterminant(proj), proj);\n\tXMMATRIX invViewProj = XMMatrixInverse(&XMMatrixDeterminant(viewProj), viewProj);\n\n\tXMStoreFloat4x4(&mMainPassCB.View, XMMatrixTranspose(view));\n\tXMStoreFloat4x4(&mMainPassCB.InvView, XMMatrixTranspose(invView));\n\tXMStoreFloat4x4(&mMainPassCB.Proj, XMMatrixTranspose(proj));\n\tXMStoreFloat4x4(&mMainPassCB.InvProj, XMMatrixTranspose(invProj));\n\tXMStoreFloat4x4(&mMainPassCB.ViewProj, XMMatrixTranspose(viewProj));\n\tXMStoreFloat4x4(&mMainPassCB.InvViewProj, XMMatrixTranspose(invViewProj));\n\tmMainPassCB.EyePosW = mEyePos;\n\tmMainPassCB.RenderTargetSize = XMFLOAT2((float)mClientWidth, (float)mClientHeight);\n\tmMainPassCB.InvRenderTargetSize = XMFLOAT2(1.0f / mClientWidth, 1.0f / mClientHeight);\n\tmMainPassCB.NearZ = 1.0f;\n\tmMainPassCB.FarZ = 1000.0f;\n\tmMainPassCB.TotalTime = gt.TotalTime();\n\tmMainPassCB.DeltaTime = gt.DeltaTime();\n\tmMainPassCB.AmbientLight = { 0.25f, 0.25f, 0.35f, 1.0f };\n\tmMainPassCB.Lights[0].Direction = { 0.57735f, -0.57735f, 0.57735f };\n\tmMainPassCB.Lights[0].Strength = { 0.6f, 0.6f, 0.6f };\n\tmMainPassCB.Lights[1].Direction = { -0.57735f, -0.57735f, 0.57735f };\n\tmMainPassCB.Lights[1].Strength = { 0.3f, 0.3f, 0.3f };\n\tmMainPassCB.Lights[2].Direction = { 0.0f, -0.707f, -0.707f };\n\tmMainPassCB.Lights[2].Strength = { 0.15f, 0.15f, 0.15f };\n\n\tauto currPassCB = mCurrFrameResource\n\t\t->GetResource<Ubpa::DX12::ArrayUploadBuffer<PassConstants>>(\"gbPass constants\");\n\tcurrPassCB->Set(0, mMainPassCB);\n}\n\nvoid HW04App::LoadTextures()\n{\n\tstd::array<std::wstring_view, 3> ironTextures{\n\t\tL\"../data/textures/iron/albedo.dds\",\n\t\tL\"../data/textures/iron/roughness.dds\",\n\t\tL\"../data/textures/iron/metalness.dds\"\n\t};\n\n\tUbpa::DXRenderer::Instance().RegisterDDSTextureArrayFromFile(\n\t\tUbpa::DXRenderer::Instance().GetUpload(),\n\t\t\"iron\",\n\t\tironTextures.data(), ironTextures.size());\n}\n\nvoid HW04App::BuildRootSignature()\n{\n\t{ // geometry\n\t\tCD3DX12_DESCRIPTOR_RANGE texTable;\n\t\ttexTable.Init(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 3, 0);\n\n\t\t// Root parameter can be a table, root descriptor or root constants.\n\t\tCD3DX12_ROOT_PARAMETER slotRootParameter[4];\n\n\t\t// Perfomance TIP: Order from most frequent to least frequent.\n\t\tslotRootParameter[0].InitAsDescriptorTable(1, &texTable, D3D12_SHADER_VISIBILITY_PIXEL);\n\t\tslotRootParameter[1].InitAsConstantBufferView(0);\n\t\tslotRootParameter[2].InitAsConstantBufferView(1);\n\t\tslotRootParameter[3].InitAsConstantBufferView(2);\n\n\t\tauto staticSamplers = GetStaticSamplers();\n\n\t\t// A root signature is an array of root parameters.\n\t\tCD3DX12_ROOT_SIGNATURE_DESC rootSigDesc(4, slotRootParameter,\n\t\t\t(UINT)staticSamplers.size(), staticSamplers.data(),\n\t\t\tD3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT);\n\n\t\tUbpa::DXRenderer::Instance().RegisterRootSignature(\"geometry\", &rootSigDesc);\n\t}\n\n\t{ // screen\n\t\tCD3DX12_DESCRIPTOR_RANGE texTable;\n\t\ttexTable.Init(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0);\n\n\t\t// Root parameter can be a table, root descriptor or root constants.\n\t\tCD3DX12_ROOT_PARAMETER slotRootParameter[1];\n\n\t\t// Perfomance TIP: Order from most frequent to least frequent.\n\t\tslotRootParameter[0].InitAsDescriptorTable(1, &texTable, D3D12_SHADER_VISIBILITY_PIXEL);\n\n\t\tauto staticSamplers = GetStaticSamplers();\n\n\t\t// A root signature is an array of root parameters.\n\t\tCD3DX12_ROOT_SIGNATURE_DESC rootSigDesc(1, slotRootParameter,\n\t\t\t(UINT)staticSamplers.size(), staticSamplers.data(),\n\t\t\tD3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT);\n\n\t\tUbpa::DXRenderer::Instance().RegisterRootSignature(\"screen\", &rootSigDesc);\n\t}\n\t{ // defer lighting\n\t\tCD3DX12_DESCRIPTOR_RANGE texTable;\n\t\ttexTable.Init(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 3, 0);\n\n\t\t// Root parameter can be a table, root descriptor or root constants.\n\t\tCD3DX12_ROOT_PARAMETER slotRootParameter[4];\n\n\t\t// Perfomance TIP: Order from most frequent to least frequent.\n\t\tslotRootParameter[0].InitAsDescriptorTable(1, &texTable, D3D12_SHADER_VISIBILITY_PIXEL);\n\t\tslotRootParameter[1].InitAsConstantBufferView(0);\n\t\tslotRootParameter[2].InitAsConstantBufferView(1);\n\t\tslotRootParameter[3].InitAsConstantBufferView(2);\n\n\t\tauto staticSamplers = GetStaticSamplers();\n\n\t\t// A root signature is an array of root parameters.\n\t\tCD3DX12_ROOT_SIGNATURE_DESC rootSigDesc(4, slotRootParameter,\n\t\t\t(UINT)staticSamplers.size(), staticSamplers.data(),\n\t\t\tD3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT);\n\n\t\tUbpa::DXRenderer::Instance().RegisterRootSignature(\"defer lighting\", &rootSigDesc);\n\t}\n}\n\nvoid HW04App::BuildDescriptorHeaps()\n{\n}\n\nvoid HW04App::BuildShadersAndInputLayout()\n{\n\tUbpa::DXRenderer::Instance().RegisterShaderByteCode(\"standardVS\",\n\t\tL\"..\\\\data\\\\shaders\\\\Default.hlsl\", nullptr, \"VS\", \"vs_5_0\");\n\tUbpa::DXRenderer::Instance().RegisterShaderByteCode(\"opaquePS\",\n\t\tL\"..\\\\data\\\\shaders\\\\Default.hlsl\", nullptr, \"PS\", \"ps_5_0\");\n\tUbpa::DXRenderer::Instance().RegisterShaderByteCode(\"screenVS\",\n\t\tL\"..\\\\data\\\\shaders\\\\Screen.hlsl\", nullptr, \"VS\", \"vs_5_0\");\n\tUbpa::DXRenderer::Instance().RegisterShaderByteCode(\"screenPS\",\n\t\tL\"..\\\\data\\\\shaders\\\\Screen.hlsl\", nullptr, \"PS\", \"ps_5_0\");\n\tUbpa::DXRenderer::Instance().RegisterShaderByteCode(\"geometryVS\",\n\t\tL\"..\\\\data\\\\shaders\\\\Geometry.hlsl\", nullptr, \"VS\", \"vs_5_0\");\n\tUbpa::DXRenderer::Instance().RegisterShaderByteCode(\"geometryPS\",\n\t\tL\"..\\\\data\\\\shaders\\\\Geometry.hlsl\", nullptr, \"PS\", \"ps_5_0\");\n\tUbpa::DXRenderer::Instance().RegisterShaderByteCode(\"deferLightingVS\",\n\t\tL\"..\\\\data\\\\shaders\\\\deferLighting.hlsl\", nullptr, \"VS\", \"vs_5_0\");\n\tUbpa::DXRenderer::Instance().RegisterShaderByteCode(\"deferLightingPS\",\n\t\tL\"..\\\\data\\\\shaders\\\\deferLighting.hlsl\", nullptr, \"PS\", \"ps_5_0\");\n\t\n    mInputLayout =\n    {\n        { \"POSITION\", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },\n        { \"NORMAL\", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },\n\t\t{ \"TEXCOORD\", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 24, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }\n    };\n}\n\nvoid HW04App::BuildShapeGeometry()\n{\n\tstd::vector<Vertex> orig_vertices;\n\tstd::vector<Vertex> param_vertices;\n\tstd::vector<std::uint32_t> indices;\n\n\tauto bunny = std::make_unique<Ubpa::TriMesh>(\"../data/meshes/Bunny_head.obj\");\n\n\tbunny->CombineSamePositionVertex();\n\tbunny->ScaleToUnit();\n\n\torig_vertices.resize(bunny->VertexNumber());\n\tparam_vertices.resize(bunny->VertexNumber());\n\tindices.resize(3 * bunny->TriangleNumber());\n\tfor (size_t i = 0; i < bunny->VertexNumber(); i++) {\n\t\torig_vertices[i].Pos = bunny->positions[i].as<XMFLOAT3>();\n\n\t\torig_vertices[i].Normal = bunny->normals[i].as<XMFLOAT3>();\n\n\t\torig_vertices[i].TexC = bunny->texcoords[i].as<XMFLOAT2>();\n\t}\n\tfor (size_t i = 0; i < bunny->TriangleNumber(); i++) {\n\t\tindices[3 * i + 0] = bunny->indices[i][0];\n\t\tindices[3 * i + 1] = bunny->indices[i][1];\n\t\tindices[3 * i + 2] = bunny->indices[i][2];\n\t}\n\n\tUbpa::HEMesh<Ubpa::HEMeshTriats_EmptyEP<V>> hemesh(std::vector<size_t>{indices.begin(), indices.end()}, 3);\n\tassert(hemesh.IsValid() && hemesh.IsTriMesh() && hemesh.NumBoundaries() == 1);\n\n\tfor (size_t i = 0; i < orig_vertices.size(); i++)\n\t\themesh.Vertices().at(i)->pos = reinterpret_cast<Ubpa::pointf3&>(orig_vertices[i].Pos);\n\n\tauto boundary = hemesh.Boundaries().front();\n\tfloat boundaryLength = 0.f;\n\tfor (auto he : boundary) {\n\t\tauto p0 = he->Origin()->pos;\n\t\tauto p1 = he->End()->pos;\n\t\tboundaryLength += p0.distance(p1);\n\t}\n\n\t// set boundary to square\n\t// (0, 0) -> (1, 0) -> (1, 1) -> (0, 1) -> (0, 0)\n\tfloat accumulateLength = 0.f;\n\tfor (auto he : boundary) {\n\t\tfloat t = accumulateLength / boundaryLength;\n\t\tfloat s = t * 4 - static_cast<int>(t * 4);\n\n\t\tif (t < 0.25f)\n\t\t\the->Origin()->uv = { s, 0 };\n\t\telse if (t < 0.50f)\n\t\t\the->Origin()->uv = { 1, s };\n\t\telse if (t < 0.75f)\n\t\t\the->Origin()->uv = { 1 - s, 1 };\n\t\telse /* if (t < 1.00f)*/\n\t\t\the->Origin()->uv = { 0, 1 - s };\n\n\t\tauto p0 = he->Origin()->pos;\n\t\tauto p1 = he->End()->pos;\n\t\taccumulateLength += p0.distance(p1);\n\t}\n\n\tsize_t N = orig_vertices.size();\n\tEigen::SparseMatrix<float> A(N, N);\n\tEigen::MatrixXf b(N, 2);\n\tstd::vector<Eigen::Triplet<float>> triplets;\n\tfor (auto v : hemesh.Vertices()) {\n\t\tauto vIdx = hemesh.Index(v);\n\t\tif (v->IsBoundary()) {\n\t\t\tb(vIdx, 0) = v->uv[0];\n\t\t\tb(vIdx, 1) = v->uv[1];\n\t\t\ttriplets.emplace_back(vIdx, vIdx, 1.f);\n\t\t}\n\t\telse {\n\t\t\tfor (auto u : v->AdjVertices()) {\n\t\t\t\tb(vIdx, 0) = 0.f;\n\t\t\t\tb(vIdx, 1) = 0.f;\n\t\t\t\ttriplets.emplace_back(vIdx, hemesh.Index(u), 1.f);\n\t\t\t}\n\t\t\ttriplets.emplace_back(vIdx, vIdx, -static_cast<int>(v->Degree()));\n\t\t}\n\t}\n\tA.setFromTriplets(triplets.begin(), triplets.end());\n\tEigen::BiCGSTAB<Eigen::SparseMatrix<float>> solver(A);\n\tEigen::MatrixXf X = solver.solve(b);\n\tfor (size_t i = 0; i < N; i++)\n\t\tOutputDebugString(((std::to_wstring(X(i, 0)) + L\", \" + std::to_wstring(X(i, 1)) + L\"\\n\").c_str()));\n\tfor (auto v : hemesh.Vertices()) {\n\t\tauto idx = hemesh.Index(v);\n\t\tv->uv[0] = X(idx, 0);\n\t\tv->uv[1] = X(idx, 1);\n\t}\n\t\n\tfor (size_t i = 0; i < bunny->VertexNumber(); i++) {\n\t\tparam_vertices[i].Pos.x = hemesh.Vertices().at(i)->uv[0];\n\t\tparam_vertices[i].Pos.y = 0.f;\n\t\tparam_vertices[i].Pos.z = hemesh.Vertices().at(i)->uv[1];\n\n\t\tparam_vertices[i].Normal = { 0.f,1.f,0.f };\n\n\t\tparam_vertices[i].TexC = hemesh.Vertices().at(i)->uv.as<XMFLOAT2>();\n\t}\n\n\tUbpa::DX12::SubmeshGeometry bunnySubmesh;\n\tbunnySubmesh.IndexCount = bunny->indices.size() * 3;\n\tbunnySubmesh.StartIndexLocation = 0;\n\tbunnySubmesh.BaseVertexLocation = 0;\n\tUbpa::DXRenderer::Instance()\n\t\t.RegisterStaticMeshGeometry(\n\t\t\tUbpa::DXRenderer::Instance().GetUpload(), \"orig_bunnyGeo\",\n\t\t\torig_vertices.data(), (UINT)orig_vertices.size(), sizeof(Vertex),\n\t\t\tindices.data(), (UINT)indices.size(), DXGI_FORMAT_R32_UINT)\n\t\t.submeshGeometries[\"bunny\"] = bunnySubmesh;\n\tUbpa::DXRenderer::Instance()\n\t\t.RegisterStaticMeshGeometry(\n\t\t\tUbpa::DXRenderer::Instance().GetUpload(), \"param_bunnyGeo\",\n\t\t\tparam_vertices.data(), (UINT)param_vertices.size(), sizeof(Vertex),\n\t\t\tindices.data(), (UINT)indices.size(), DXGI_FORMAT_R32_UINT)\n\t\t.submeshGeometries[\"bunny\"] = bunnySubmesh;\n\n\ttrimeshes.emplace(\"bunny\", std::move(bunny));\n}\n\nvoid HW04App::BuildPSOs()\n{\n\tauto screenPsoDesc = Ubpa::DX12::Desc::PSO::Basic(\n\t\tUbpa::DXRenderer::Instance().GetRootSignature(\"screen\"),\n\t\tnullptr, 0,\n\t\tUbpa::DXRenderer::Instance().GetShaderByteCode(\"screenVS\"),\n\t\tUbpa::DXRenderer::Instance().GetShaderByteCode(\"screenPS\"),\n\t\tmBackBufferFormat,\n\t\tDXGI_FORMAT_UNKNOWN\n\t);\n\tUbpa::DXRenderer::Instance().RegisterPSO(\"screen\", &screenPsoDesc);\n\n\tauto geometryPsoDesc = Ubpa::DX12::Desc::PSO::MRT(\n\t\tUbpa::DXRenderer::Instance().GetRootSignature(\"geometry\"),\n\t\tmInputLayout.data(), (UINT)mInputLayout.size(),\n\t\tUbpa::DXRenderer::Instance().GetShaderByteCode(\"geometryVS\"),\n\t\tUbpa::DXRenderer::Instance().GetShaderByteCode(\"geometryPS\"),\n\t\t3,\n\t\tDXGI_FORMAT_R32G32B32A32_FLOAT,\n\t\tmDepthStencilFormat\n\t);\n\tgeometryPsoDesc.RasterizerState.FillMode = D3D12_FILL_MODE_WIREFRAME;\n\tUbpa::DXRenderer::Instance().RegisterPSO(\"geometry\", &geometryPsoDesc);\n\n\tauto deferLightingPsoDesc = Ubpa::DX12::Desc::PSO::Basic(\n\t\tUbpa::DXRenderer::Instance().GetRootSignature(\"defer lighting\"),\n\t\tnullptr, 0,\n\t\tUbpa::DXRenderer::Instance().GetShaderByteCode(\"deferLightingVS\"),\n\t\tUbpa::DXRenderer::Instance().GetShaderByteCode(\"deferLightingPS\"),\n\t\tmBackBufferFormat,\n\t\tDXGI_FORMAT_UNKNOWN\n\t);\n\tUbpa::DXRenderer::Instance().RegisterPSO(\"defer lighting\", &deferLightingPsoDesc);\n}\n\nvoid HW04App::BuildFrameResources()\n{\n    for(int i = 0; i < gNumFrameResources; ++i)\n    {\n\t\tauto fr = std::make_unique<Ubpa::DX12::FrameResource>(mFence.Get());\n\n\t\tID3D12CommandAllocator* allocator;\n\t\tThrowIfFailed(uDevice->CreateCommandAllocator(\n\t\t\tD3D12_COMMAND_LIST_TYPE_DIRECT,\n\t\t\tIID_PPV_ARGS(&allocator)));\n\n\t\tfr->RegisterResource(\"CommandAllocator\", allocator, [](void* allocator) {\n\t\t\treinterpret_cast<ID3D12CommandAllocator*>(allocator)->Release();\n\t\t});\n\n\t\tfr->RegisterResource(\"gbPass constants\",\n\t\t\tnew Ubpa::DX12::ArrayUploadBuffer<PassConstants>{ uDevice.raw.Get(), 1, true });\n\n\t\tfr->RegisterResource(\"ArrayUploadBuffer<MaterialConstants>\",\n\t\t\tnew Ubpa::DX12::ArrayUploadBuffer<MaterialConstants>{ uDevice.raw.Get(), mMaterials.size(), true });\n\n\t\tfr->RegisterResource(\"ArrayUploadBuffer<ObjectConstants>\",\n\t\t\tnew Ubpa::DX12::ArrayUploadBuffer<ObjectConstants>{ uDevice.raw.Get(), mAllRitems.size(), true });\n\n\t\tauto fgRsrcMngr = new Ubpa::DX12::FG::RsrcMngr;\n\t\tfgRsrcMngr->Init(uGCmdList, uDevice);\n\t\tfr->RegisterResource(\"FrameGraphRsrcMngr\", fgRsrcMngr);\n\n\t\tmFrameResources.emplace_back(std::move(fr));\n    }\n}\n\nvoid HW04App::BuildMaterials()\n{\n\tauto iron = std::make_unique<Material>();\n\tiron->Name = \"iron\";\n\tiron->MatCBIndex = 0;\n\tiron->DiffuseSrvGpuHandle = Ubpa::DXRenderer::Instance().GetTextureSrvGpuHandle(\"iron\");\n\tiron->DiffuseAlbedo = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f);\n\tiron->FresnelR0 = XMFLOAT3(0.05f, 0.05f, 0.05f);\n\tiron->Roughness = 0.2f;\n\n\tmMaterials[\"iron\"] = std::move(iron);\n}\n\nvoid HW04App::BuildRenderItems()\n{\n\tauto orig_bunnyRitem = std::make_unique<RenderItem>();\n\torig_bunnyRitem->World = Ubpa::transformf(Ubpa::pointf3{ 1,0,0 }).as<XMFLOAT4X4>();\n\torig_bunnyRitem->ObjCBIndex = 0;\n\torig_bunnyRitem->Mat = mMaterials[\"iron\"].get();\n\torig_bunnyRitem->Geo = &Ubpa::DXRenderer::Instance().GetMeshGeometry(\"orig_bunnyGeo\");\n\torig_bunnyRitem->PrimitiveType = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST;\n\torig_bunnyRitem->IndexCount = orig_bunnyRitem->Geo->submeshGeometries[\"bunny\"].IndexCount;\n\torig_bunnyRitem->StartIndexLocation = orig_bunnyRitem->Geo->submeshGeometries[\"bunny\"].StartIndexLocation;\n\torig_bunnyRitem->BaseVertexLocation = orig_bunnyRitem->Geo->submeshGeometries[\"bunny\"].BaseVertexLocation;\n\tmAllRitems.push_back(std::move(orig_bunnyRitem));\n\n\tauto param_bunnyRitem = std::make_unique<RenderItem>();\n\tparam_bunnyRitem->World = Ubpa::transformf(Ubpa::pointf3{ -1,0,0 }).as<XMFLOAT4X4>();\n\tparam_bunnyRitem->ObjCBIndex = 1;\n\tparam_bunnyRitem->Mat = mMaterials[\"iron\"].get();\n\tparam_bunnyRitem->Geo = &Ubpa::DXRenderer::Instance().GetMeshGeometry(\"param_bunnyGeo\");\n\tparam_bunnyRitem->PrimitiveType = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST;\n\tparam_bunnyRitem->IndexCount = param_bunnyRitem->Geo->submeshGeometries[\"bunny\"].IndexCount;\n\tparam_bunnyRitem->StartIndexLocation = param_bunnyRitem->Geo->submeshGeometries[\"bunny\"].StartIndexLocation;\n\tparam_bunnyRitem->BaseVertexLocation = param_bunnyRitem->Geo->submeshGeometries[\"bunny\"].BaseVertexLocation;\n\tmAllRitems.push_back(std::move(param_bunnyRitem));\n\n\t// All the render items are opaque.\n\tfor(auto& e : mAllRitems)\n\t\tmOpaqueRitems.push_back(e.get());\n}\n\nvoid HW04App::DrawRenderItems(ID3D12GraphicsCommandList* cmdList, const std::vector<RenderItem*>& ritems)\n{\n    UINT objCBByteSize = Ubpa::DX12::Util::CalcConstantBufferByteSize(sizeof(ObjectConstants));\n    UINT matCBByteSize = Ubpa::DX12::Util::CalcConstantBufferByteSize(sizeof(MaterialConstants));\n \n\tauto objectCB = mCurrFrameResource\n\t\t->GetResource<Ubpa::DX12::ArrayUploadBuffer<ObjectConstants>>(\"ArrayUploadBuffer<ObjectConstants>\")\n\t\t->GetResource();\n\tauto matCB = mCurrFrameResource\n\t\t->GetResource<Ubpa::DX12::ArrayUploadBuffer<MaterialConstants>>(\"ArrayUploadBuffer<MaterialConstants>\")\n\t\t->GetResource();\n\n    // For each render item...\n    for(size_t i = 0; i < ritems.size(); ++i)\n    {\n        auto ri = ritems[i];\n\n        cmdList->IASetVertexBuffers(0, 1, &ri->Geo->VertexBufferView());\n        cmdList->IASetIndexBuffer(&ri->Geo->IndexBufferView());\n        cmdList->IASetPrimitiveTopology(ri->PrimitiveType);\n\n        D3D12_GPU_VIRTUAL_ADDRESS objCBAddress = objectCB->GetGPUVirtualAddress() + ri->ObjCBIndex*objCBByteSize;\n\t\tD3D12_GPU_VIRTUAL_ADDRESS matCBAddress = matCB->GetGPUVirtualAddress() + ri->Mat->MatCBIndex*matCBByteSize;\n\n\t\tcmdList->SetGraphicsRootDescriptorTable(0, ri->Mat->DiffuseSrvGpuHandle);\n        cmdList->SetGraphicsRootConstantBufferView(1, objCBAddress);\n        cmdList->SetGraphicsRootConstantBufferView(3, matCBAddress);\n\n        cmdList->DrawIndexedInstanced(ri->IndexCount, 1, ri->StartIndexLocation, ri->BaseVertexLocation, 0);\n    }\n}\n\nstd::array<const CD3DX12_STATIC_SAMPLER_DESC, 6> HW04App::GetStaticSamplers()\n{\n\t// Applications usually only need a handful of samplers.  So just define them all up front\n\t// and keep them available as part of the root signature.  \n\n\tconst CD3DX12_STATIC_SAMPLER_DESC pointWrap(\n\t\t0, // shaderRegister\n\t\tD3D12_FILTER_MIN_MAG_MIP_POINT, // filter\n\t\tD3D12_TEXTURE_ADDRESS_MODE_WRAP,  // addressU\n\t\tD3D12_TEXTURE_ADDRESS_MODE_WRAP,  // addressV\n\t\tD3D12_TEXTURE_ADDRESS_MODE_WRAP); // addressW\n\n\tconst CD3DX12_STATIC_SAMPLER_DESC pointClamp(\n\t\t1, // shaderRegister\n\t\tD3D12_FILTER_MIN_MAG_MIP_POINT, // filter\n\t\tD3D12_TEXTURE_ADDRESS_MODE_CLAMP,  // addressU\n\t\tD3D12_TEXTURE_ADDRESS_MODE_CLAMP,  // addressV\n\t\tD3D12_TEXTURE_ADDRESS_MODE_CLAMP); // addressW\n\n\tconst CD3DX12_STATIC_SAMPLER_DESC linearWrap(\n\t\t2, // shaderRegister\n\t\tD3D12_FILTER_MIN_MAG_MIP_LINEAR, // filter\n\t\tD3D12_TEXTURE_ADDRESS_MODE_WRAP,  // addressU\n\t\tD3D12_TEXTURE_ADDRESS_MODE_WRAP,  // addressV\n\t\tD3D12_TEXTURE_ADDRESS_MODE_WRAP); // addressW\n\n\tconst CD3DX12_STATIC_SAMPLER_DESC linearClamp(\n\t\t3, // shaderRegister\n\t\tD3D12_FILTER_MIN_MAG_MIP_LINEAR, // filter\n\t\tD3D12_TEXTURE_ADDRESS_MODE_CLAMP,  // addressU\n\t\tD3D12_TEXTURE_ADDRESS_MODE_CLAMP,  // addressV\n\t\tD3D12_TEXTURE_ADDRESS_MODE_CLAMP); // addressW\n\n\tconst CD3DX12_STATIC_SAMPLER_DESC anisotropicWrap(\n\t\t4, // shaderRegister\n\t\tD3D12_FILTER_ANISOTROPIC, // filter\n\t\tD3D12_TEXTURE_ADDRESS_MODE_WRAP,  // addressU\n\t\tD3D12_TEXTURE_ADDRESS_MODE_WRAP,  // addressV\n\t\tD3D12_TEXTURE_ADDRESS_MODE_WRAP,  // addressW\n\t\t0.0f,                             // mipLODBias\n\t\t8);                               // maxAnisotropy\n\n\tconst CD3DX12_STATIC_SAMPLER_DESC anisotropicClamp(\n\t\t5, // shaderRegister\n\t\tD3D12_FILTER_ANISOTROPIC, // filter\n\t\tD3D12_TEXTURE_ADDRESS_MODE_CLAMP,  // addressU\n\t\tD3D12_TEXTURE_ADDRESS_MODE_CLAMP,  // addressV\n\t\tD3D12_TEXTURE_ADDRESS_MODE_CLAMP,  // addressW\n\t\t0.0f,                              // mipLODBias\n\t\t8);                                // maxAnisotropy\n\n\treturn { \n\t\tpointWrap, pointClamp,\n\t\tlinearWrap, linearClamp, \n\t\tanisotropicWrap, anisotropicClamp };\n}\n\n", "meta": {"hexsha": "fdc7929d5dede05e36cf0f7c2930045a7f075615", "size": 38317, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "2020Spring/DGP/homeworks/04/src/app/main.cpp", "max_stars_repo_name": "Ubpa/MasterCourses", "max_stars_repo_head_hexsha": "46ea8ae8088d5787af277d33beabd02a2766fcc4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-09-10T13:25:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-03T16:01:03.000Z", "max_issues_repo_path": "2020Spring/DGP/homeworks/04/src/app/main.cpp", "max_issues_repo_name": "Ubpa/MasterCourses", "max_issues_repo_head_hexsha": "46ea8ae8088d5787af277d33beabd02a2766fcc4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2020Spring/DGP/homeworks/04/src/app/main.cpp", "max_forks_repo_name": "Ubpa/MasterCourses", "max_forks_repo_head_hexsha": "46ea8ae8088d5787af277d33beabd02a2766fcc4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-04T09:30:48.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-04T09:30:48.000Z", "avg_line_length": 35.7101584343, "max_line_length": 113, "alphanum_fraction": 0.7273011979, "num_tokens": 11661, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.47030329067036036}}
{"text": "//=======================================================================\n// Copyright 2001 Jeremy G. Siek, Andrew Lumsdaine, Lie-Quan Lee, \n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n#include <boost/config.hpp>\n#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <utility>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/pending/disjoint_sets.hpp>\n#include <boost/graph/incremental_components.hpp>\n\nint\nmain(int, char *[])\n{\n  using namespace boost;\n  // Create a graph\n  typedef adjacency_list < vecS, vecS, undirectedS > Graph;\n  typedef graph_traits < Graph >::vertex_descriptor Vertex;\n  const int N = 6;\n  Graph G(N);\n  add_edge(0, 1, G);\n  add_edge(1, 4, G);\n  // create the disjoint-sets object, which requires rank and parent vertex properties\n  std::vector < Vertex > rank(num_vertices(G));\n  std::vector < Vertex > parent(num_vertices(G));\n  typedef graph_traits<Graph>::vertices_size_type* Rank;\n  typedef Vertex* Parent;\n  disjoint_sets < Rank, Parent > ds(&rank[0], &parent[0]);\n\n  // determine the connected components, storing the results in the disjoint-sets object\n  initialize_incremental_components(G, ds);\n  incremental_components(G, ds);\n\n  // Add a couple more edges and update the disjoint-sets\n  graph_traits < Graph >::edge_descriptor e;\n  bool flag;\n  tie(e, flag) = add_edge(4, 0, G);\n  ds.union_set(4, 0);\n  tie(e, flag) = add_edge(2, 5, G);\n  ds.union_set(2, 5);\n\n  graph_traits < Graph >::vertex_iterator iter, end;\n  for (tie(iter, end) = vertices(G); iter != end; ++iter)\n    std::cout << \"representative[\" << *iter << \"] = \" <<\n      ds.find_set(*iter) << std::endl;;\n  std::cout << std::endl;\n\n  typedef component_index < unsigned int >Components;\n  Components components(parent.begin(), parent.end());\n  for (Components::size_type i = 0; i < components.size(); ++i) {\n    std::cout << \"component \" << i << \" contains: \";\n    for (Components::value_type::iterator j = components[i].begin();\n         j != components[i].end(); ++j)\n      std::cout << *j << \" \";\n    std::cout << std::endl;\n  }\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "521963ff843d03d84d83b0e5869637dd3986a087", "size": 2270, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/graph/example/incremental-components-eg.cpp", "max_stars_repo_name": "mike-code/boost_1_38_0", "max_stars_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-07-31T13:56:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-13T02:55:10.000Z", "max_issues_repo_path": "libs/graph/example/incremental-components-eg.cpp", "max_issues_repo_name": "mike-code/boost_1_38_0", "max_issues_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/graph/example/incremental-components-eg.cpp", "max_forks_repo_name": "mike-code/boost_1_38_0", "max_forks_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2021-08-31T14:34:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-19T08:25:58.000Z", "avg_line_length": 34.9230769231, "max_line_length": 88, "alphanum_fraction": 0.6317180617, "num_tokens": 579, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.6406358479787609, "lm_q1q2_score": 0.47030328563346563}}
{"text": "#include \"OrdinatesData.h\"\n#include <boost/range/irange.hpp>\n#include <cmath>\n#include <fstream>\n#include <sstream>\n#include <algorithm>\n\nusing namespace std;\nusing namespace dolfin;\n\ninline double sqr(double x) { return x*x; }\n\n/* Ordinates in the four octants of the upper hemisphere are ordered as\n *\n *      13         12\n *     17  5     4  16\n *    21  9 1   0 8  20\n *            o\n *    22 10 2   3 11 23\n *     18  6     7  19\n *       14        15\n**/\nOrdinatesData::OrdinatesData(unsigned int N, unsigned int D, const string& filename) : N(N), M(N*(N+2)), D(D)\n{\n\tif (D < 2 || D > 3)\n\t\tdolfin_error(\"OrdinatesData.cpp\",\n\t\t             \"construct the OrdinatesData object\",\n\t\t             \"Only 2D or 3D ordinates currently supported\");\n\n\tif (D == 2)\n\t\tM /= 2;\n\n\tifstream ifs(filename.c_str());\n\n\tif (ifs.fail())\n\t\tdolfin_error(\"OrdinatesData.cpp\",\n\t\t             \"construct the OrdinatesData object\",\n\t\t             \"Discrete ordinates could not be loaded from %s\", filename.c_str());\n\n\tstring tmp;\n\tgetline(ifs, tmp);\n\tgetline(ifs, tmp);\n\n\tint read_n;\n\tdo\n\t{\n\t\tifs >> read_n;\n\t\tif (read_n == N)\n\t\t\tbreak;\n\n\t\tgetline(ifs, tmp);\n\t\tfor (int n = 0; n < read_n; n++)\n\t\t\tgetline(ifs, tmp);\n\t\tgetline(ifs, tmp);\n\t}\n\twhile (!ifs.eof());\n\n\tif (ifs.eof())\n\t\tdolfin_error(\"OrdinatesData.cpp\",\n\t\t             \"construct the OrdinatesData object\",\n\t\t             \"Required set of discrete ordinates could not be found in %s\", filename.c_str());\n\n\tdouble *mu_base = new double [N/2];\n\n\tgetline(ifs, tmp);\n\tfor (int n = 0; n < N/2; n++)\n\t\tifs >> mu_base[n];\n\n\tgetline(ifs, tmp, '\"');\n\tgetline(ifs, tmp);\n\tgetline(ifs, tmp);\n\n\tdo\n\t{\n\t\tifs >> read_n;\n\t\tif (read_n == N)\n\t\t\tbreak;\n\n\t\tgetline(ifs, tmp);\n\t\tfor (int n = 0; n < read_n; n++)\n\t\t\tgetline(ifs, tmp);\n\t\tgetline(ifs, tmp);\n\t}\n\twhile (!ifs.eof());\n\n\tif (ifs.eof())\n\t\tdolfin_error(\"OrdinatesData.cpp\",\n\t\t             \"construct the OrdinatesData object\",\n\t\t             \"Required set of weights could not be found in %s\", filename.c_str());\n\n\tdouble *wt = new double [N/2];\n\n\tgetline(ifs, tmp);\n\tfor (int n = 0; n < N/2; n++)\n\t\tifs >> wt[n];\n\n\tifs.close();\n\n\txi.reserve(M);\n\teta.reserve(M);\n\tmu.reserve(M);\n\tpw.reserve(M);\n\treflections_about_x.reserve(M);\n\treflections_about_y.reserve(M);\n\tif (D == 3) reflections_about_z.reserve(M);\n\n\tint dir = 0;\n\n\t// upper hemisphere\n\n\tfor (int n = 1; n <= N/2; n++) // for each polar level\n\t{\n\t\tfor (int i = 1; i <= n; i++) // for each azimuthal point in the first octant\n\t\t{\n\t\t\tdouble omega = (2*n - 2*i + 1)/(2.*n) * M_PI/2.;\n\t\t\tdouble xi1q = sqrt(1-sqr(mu_base[n-1])) * cos(omega);\n\t\t\tdouble eta1q = sqrt(1-sqr(mu_base[n-1])) * sin(omega);\n\n\t\t\t// octant 1, ordinate index dir\n\t\t\txi.push_back( xi1q );\n\t\t\teta.push_back( eta1q );\n\t\t\treflections_about_x.push_back( dir + 3 );\n\t\t\treflections_about_y.push_back( dir + 1 );\n\n\t\t\t// octant 2, ordinate index dir+1\n\t\t\txi.push_back(-xi1q );\n\t\t\teta.push_back( eta1q );\n\t\t\treflections_about_x.push_back( dir + 2 );\n\t\t\treflections_about_y.push_back( dir );\n\n\t\t\t// octant 3, ordinate index dir+2\n\t\t\txi.push_back(-xi1q );\n\t\t\teta.push_back(-eta1q );\n\t\t\treflections_about_x.push_back( dir + 1 );\n\t\t\treflections_about_y.push_back( dir + 3 );\n\n\t\t\t// octant 4, ordinate index dir+3\n\t\t\txi.push_back( xi1q );\n\t\t\teta.push_back(-eta1q );\n\t\t\treflections_about_x.push_back( dir );\n\t\t\treflections_about_y.push_back( dir + 2 );\n\n\t\t\tfor (int j = 0; j < 4; j++)\n\t\t\t{\n\t\t\t\tmu.push_back(mu_base[n-1]);\n\t\t\t\tpw.push_back( wt[n-1] / n); // equal weights in each polar level, summing up to 4pi over the whole sphere.\n\t\t\t}\n\n\t\t\tdir+=4;\n\t\t}\n\t}\n\n\tif (D == 3)\n\t{\n\t\t// lower hemisphere\n\n\t\txi.insert(xi.end(), xi.begin(), xi.end());\n\t\teta.insert(eta.end(), eta.begin(), eta.end());\n\t\tpw.insert(pw.end(), pw.begin(), pw.end());\n\n\t\tstd::vector<double> base_aux(M/2);// base_aux.reserve(M/2);\n\t\ttransform(mu.begin(), mu.end(), base_aux.begin(), negate<double>());\n\t\tmu.insert(mu.end(), base_aux.begin(), base_aux.end());\n\n\t\t//TODO: use zip_iterators or something similar to do the following steps at once\n\n\t\ttransform(reflections_about_x.begin(), reflections_about_x.end(), base_aux.begin(), bind2nd(plus<int>(), M/2));\n\t\treflections_about_x.insert(reflections_about_x.end(), base_aux.begin(), base_aux.end());\n\t\ttransform(reflections_about_y.begin(), reflections_about_y.end(), base_aux.begin(), bind2nd(plus<int>(), M/2));\n\t\treflections_about_y.insert(reflections_about_y.end(), base_aux.begin(), base_aux.end());\n\n\t\tboost::integer_range<int> aux = boost::irange<int>(M/2,M);\n\t\treflections_about_z.assign(aux.begin(), aux.end());\n\t\taux = boost::irange<int>(0,M/2);\n\t\treflections_about_z.insert(reflections_about_z.end(), aux.begin(), aux.end());\n\t}\n\n\tdelete [] mu_base;\n\tdelete [] wt;\n}\n\nnamespace dolfin {\n\tostream& operator<<(ostream& os, const OrdinatesData& odata)\n\t{\n\t\tos << \"_______________________________________________________\" << endl;\n\t\tos << \"                Discrete ordinates (\" << odata.D << \"D)\" << endl;\n\t\tos << \"                        N = \" << odata.N << endl;\n\t\tos << \"-------------------------------------------------------\" << endl;\n\n\n\t\tint m = 0;\n\t\tvector<double>::const_iterator xi = odata.xi.begin();\n\t\tvector<double>::const_iterator eta = odata.eta.begin();\n\t\tvector<double>::const_iterator mu = odata.mu.begin();\n\t\tvector<double>::const_iterator pw = odata.pw.begin();\n\t\tfor ( ; xi != odata.xi.end(); ++xi, ++eta, ++mu, ++pw)\n\t\t{\n\t\t\tos << endl << *xi << \", \" << *eta << \", \" << *mu << \", \" << *pw << endl;\n\t\t\tos << \" --- \" << odata.xi[odata.reflections_about_x[m]] << \", \"\n                    << odata.eta[odata.reflections_about_x[m]] << \", \"\n                    << odata.mu[odata.reflections_about_x[m]] << endl;\n\t\t\tos << \"  |  \" << odata.xi[odata.reflections_about_y[m]] << \", \"\n\t\t\t              << odata.eta[odata.reflections_about_y[m]] << \", \"\n\t\t\t              << odata.mu[odata.reflections_about_y[m]] << endl;\n\n\t\t\tif (odata.D == 3)\n\t\t\t\tos << \"  /  \" << odata.xi[odata.reflections_about_z[m]] << \", \"\n\t\t\t\t              << odata.eta[odata.reflections_about_z[m]] << \", \"\n\t\t\t\t              << odata.mu[odata.reflections_about_z[m]] << endl;\n\n\t\t\tm++;\n\t\t}\n\n\t\tos << endl << m << \" ordinates loaded (M = \" << odata.M << \").\" << endl;\n\n\t\tdouble sum = 0.0;\n\t\tfor (int n = 0; n < odata.M; n++)\n\t\t\tsum += odata.pw[n];\n\n\t\tos << \"sum of weights over the whole sphere: \" << (odata.D == 3 ? sum : 2*sum) << endl;\n\n\t\treturn os;\n\t}\n}\n\nvoid OrdinatesData::print_info() const\n{\n\tstringstream ss;\n\tss << *this;\n\tdolfin::info(ss.str());\n}\n\nvoid OrdinatesData::write_pw(const string& filename)\n{\n\tFILE* fp;\n\tfp = fopen(filename.c_str(), \"wt\");\n\tfprintf(fp, \"pw = [ \\n\");\n\tfor (int n = 0; n < M; n++)\n\t\tfprintf(fp, \"\\t%1.15f\\n\", pw[n]);\n\tfprintf(fp, \"];\");\n\tfclose(fp);\n\n\tcout << \"weights written to: \" << filename << endl << endl;\n}\n\nstd::vector<double> OrdinatesData::get_ordinate(int n) const\n{\n\tstd::vector<double> ret;\n\tret.reserve(D);\n\tret.push_back(xi[n]);\n\tret.push_back(eta[n]);\n\tif (D == 3)\n\t  ret.push_back(mu[n]);\n\n\treturn ret;\n}\n", "meta": {"hexsha": "383d93b9c21c73d3ad14fe386e76f6b4ad4a850b", "size": 6951, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "transport_data/cpp/OrdinatesData.cpp", "max_stars_repo_name": "mhanus/GOAT", "max_stars_repo_head_hexsha": "056f6409479c0540652a8c71741a7b4b5a53594f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "transport_data/cpp/OrdinatesData.cpp", "max_issues_repo_name": "mhanus/GOAT", "max_issues_repo_head_hexsha": "056f6409479c0540652a8c71741a7b4b5a53594f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "transport_data/cpp/OrdinatesData.cpp", "max_forks_repo_name": "mhanus/GOAT", "max_forks_repo_head_hexsha": "056f6409479c0540652a8c71741a7b4b5a53594f", "max_forks_repo_licenses": ["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.046692607, "max_line_length": 113, "alphanum_fraction": 0.59128183, "num_tokens": 2113, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195152660687, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.4703032832171295}}
{"text": "#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE fold\n#include <boost/test/unit_test.hpp>\n\n#include <type_traits>\n#include \"filter.hpp\"\n\ntemplate<typename...> struct List{};\n\n\ntemplate<typename T> struct is_odd;\n\ntemplate<typename T, T N>\nstruct is_odd<std::integral_constant<T, N>>\n\t: public std::integral_constant<bool, N % 2 == 1>\n{ };\n\n\nBOOST_AUTO_TEST_CASE(fold_max_test)\n{\n\tusing list1 =\n\t\tList<\n\t\t\tstd::integral_constant<unsigned, 1>,\n\t\t\tstd::integral_constant<unsigned, 2>,\n\t\t\tstd::integral_constant<unsigned, 3>,\n\t\t\tstd::integral_constant<unsigned, 4>,\n\t\t\tstd::integral_constant<unsigned, 5>,\n\t\t\tstd::integral_constant<unsigned, 6>\n\t\t>;\n\n\tusing list2 =\n\t\tList<\n\t\t\tstd::integral_constant<unsigned, 1>,\n\t\t\tstd::integral_constant<unsigned, 3>,\n\t\t\tstd::integral_constant<unsigned, 5>\n\t\t>;\n\n\tBOOST_CHECK_EQUAL( (is_odd<std::integral_constant<int, 1>>::value), true );\n\n\tBOOST_CHECK_EQUAL( (std::is_same<typename meta::filter<is_odd, list1>::type, list2>::value), true );\n}\n", "meta": {"hexsha": "99c7887345603d881fafa0d666a36054b722a0a7", "size": 982, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_filter.cpp", "max_stars_repo_name": "wickedmic/multidispatch-lib", "max_stars_repo_head_hexsha": "d30b031e99fc3d911bc7fc9c0ff43e0fa869e33e", "max_stars_repo_licenses": ["MIT"], "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_filter.cpp", "max_issues_repo_name": "wickedmic/multidispatch-lib", "max_issues_repo_head_hexsha": "d30b031e99fc3d911bc7fc9c0ff43e0fa869e33e", "max_issues_repo_licenses": ["MIT"], "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_filter.cpp", "max_forks_repo_name": "wickedmic/multidispatch-lib", "max_forks_repo_head_hexsha": "d30b031e99fc3d911bc7fc9c0ff43e0fa869e33e", "max_forks_repo_licenses": ["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.380952381, "max_line_length": 101, "alphanum_fraction": 0.7199592668, "num_tokens": 254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.734119526900183, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.47030328059657084}}
{"text": "\n\n#include <wav_utils.hxx>\n\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics.hpp>\n#include <boost/foreach.hpp>\n#include <boost/optional.hpp>\n\n#include <iostream>\n#include <algorithm>\n#include <chrono>\n#include <set>\n\n///stats.hpp>\n//#include <boost/accumulators/statistics/mean.hpp>\n//#include <boost/accumulators/statistics/variance.hpp>\n\n// this program is a lot like sync_wavs.cxx\n// in this one, I read a bunch of wav files and find the points of maximum correlation.\n\n// ffmpeg -i sample_video/htc/VIDEO0635.mp4 -map 0:a -ac 1 tmp/htc.wav\n// ffmpeg -i sample_video/s5/VID_20170608_152423.mp4 -map 0:a tmp/s5.wav\n// find . | xargs -I file ffmpeg -i file -map 0:a -ac 1 -ar 10000 -y ../tmp10k/file\n\n// https://en.wikipedia.org/wiki/Cross-correlation\n\nint main(int argc, char** argv) {\n\n  if (argc < 3) {\n    std::cerr << \"need at least two wav filenames\" << std::endl;\n    exit(-1);\n  }\n\n  boost::accumulators::accumulator_set<long int, boost::accumulators::features<boost::accumulators::tag::variance,\n                                                                               boost::accumulators::tag::max,\n                                                                               boost::accumulators::tag::min> > acc;\n \n\n  std::vector<wav_samples> wss;\n  for(int i=1; i<argc; i++) {\n    wss.push_back(wav_samples());\n    wss[i-1].filename = argv[i];\n    read_wav(wss[i-1]);\n    acc(wss[i-1].frames);\n  }\n\n  std::cout << \"mean \" << boost::accumulators::mean(acc)\n            << \" variance \" << sqrt(boost::accumulators::variance(acc))\n            << \" max \" << boost::accumulators::max(acc)\n            << \" min \" << boost::accumulators::min(acc)\n            << std::endl;\n  \n  std::sort(wss.begin(), wss.end(),\n        [] (const wav_samples& struct1, const wav_samples& struct2)\n        {\n            return (struct1.frames > struct2.frames);\n        }\n    );\n\n  // I multiple by two so I can tell the different between a shifted after b and\n  // b shifted after a.\n  int fftsize = boost::accumulators::max(acc)*2;\n  std::cout << \"need fft size of \" << fftsize << std::endl;\n\n  mytimer mt;\n  BOOST_FOREACH(wav_samples& ws, wss) {\n    add_fft(ws, fftsize);\n  }\n  std::cout << \"time for all ffts \" << mt.duration() << std::endl;\n\n  std::vector<correlation_data> correlations;\n  mt.reset();\n  for(unsigned int i=0; i<wss.size(); i++) {\n    for (unsigned int j=i+1; j<wss.size(); j++) {\n      correlation_data cd = correlate_wavs(wss[i], wss[j], fftsize, wss[i].samplerate);\n      //std:: cout << wss[i].filename << \" \" << wss[j].filename << \" offset \" << offset << \" num std \" << num_std << std::endl;\n      correlations.push_back(cd);\n    }\n  }\n  std::cout << \"time for all pairs correlations \" << mt.duration() << std::endl;\n\n  std::sort(correlations.begin(), correlations.end(), [](auto const &t1, auto const &t2) {\n      return t1.num_std > t2.num_std;\n    });\n\n  \n  for(unsigned int i=0; i<correlations.size(); i++) {\n    std:: cout << correlations[i].wss1->filename << \" \" << correlations[i].wss2->filename << \" offset \" << correlations[i].offset/double(correlations[i].wss1->samplerate) << \" num std \" << correlations[i].num_std << std::endl;\n\n    correlation_data cd = correlations[i];\n    // is the correlation reliable enough?\n    if (cd.num_std < 10) { continue; }\n\n\n    // the two wss are already on the same non-null timeline.\n    if (cd.wss1->timeline && (cd.wss1->timeline == cd.wss2->timeline)) {\n      continue;\n    }\n\n    long int tl_offset1=0;\n    if (!cd.wss1->timeline) {\n      std::shared_ptr<Timeline> timeline(new Timeline());\n      timeline->addClip(cd.wss1, 0);\n      cd.wss1->timeline = timeline;\n      tl_offset1 = 0;\n    } else {\n      tl_offset1 = cd.wss1->timeline->wsOffset(cd.wss1);\n    }\n\n    long int tl_offset2=0;\n    if (!cd.wss2->timeline) {\n      std::shared_ptr<Timeline> timeline(new Timeline);\n      timeline->addClip(cd.wss2, 0);\n      cd.wss2->timeline = timeline;\n      tl_offset2 = 0;\n    } else {\n      tl_offset2 = cd.wss2->timeline->wsOffset(cd.wss2);\n    }\n\n    if ((tl_offset1+cd.offset) > tl_offset2) {\n      mergeTimelines(cd.wss1->timeline, cd.wss2->timeline,\n                     tl_offset1+cd.offset-tl_offset2);\n    } else {\n      mergeTimelines(cd.wss2->timeline, cd.wss1->timeline,\n                     tl_offset2-(tl_offset1+cd.offset));\n\n    }\n  }\n\n  std::set<std::shared_ptr<Timeline> > timelines;\n  BOOST_FOREACH(wav_samples& ws, wss) {\n    timelines.insert(ws.timeline);\n  }\n\n  std::cout << \"num timelines \" << timelines.size() << std::endl;\n  int tlnum=0;\n  BOOST_FOREACH(auto tl, timelines) {\n    std::cout << \"timeline\" << std::endl;\n    long int length = 0;\n    int samplerate = 0;\n    BOOST_FOREACH(auto clip, tl->getClips()) {\n      std:: cout << \"  \" << clip.wss->filename << \" offset \" << clip.offset << std::endl;\n      length = std::max(length, clip.wss->frames+clip.offset);\n      samplerate = clip.wss->samplerate;\n    }\n    const int channels = wss.size();\n    std::vector<double> samples(length*channels, 0);\n    int clipnum=0;\n    BOOST_FOREACH(auto clip, tl->getClips()) {\n      for(int i=0; i<clip.wss->frames; i++) {\n        samples[(i+clip.offset)*channels+clipnum] = clip.wss->samples[i];\n      }\n      clipnum++;\n    }\n\n    write_wav(samples, length, samplerate, channels, std::string(\"aligned\") + std::to_string(tlnum) + \".wav\");\n    tlnum++;\n  }\n\n}\n", "meta": {"hexsha": "d601837b80b4f43adb12f7b3f14c1fb09fdc233f", "size": 5386, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "audio_sync/sync_audio.cxx", "max_stars_repo_name": "mmccoo/nerd_mmccoo", "max_stars_repo_head_hexsha": "dc5a152105d65673679ef37ea5d1f7607e4f3b2c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 45.0, "max_stars_repo_stars_event_min_datetime": "2017-06-21T07:46:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T01:39:02.000Z", "max_issues_repo_path": "audio_sync/sync_audio.cxx", "max_issues_repo_name": "zxh1986123/nerd_mmccoo", "max_issues_repo_head_hexsha": "dc5a152105d65673679ef37ea5d1f7607e4f3b2c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2018-02-08T19:29:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-14T09:27:18.000Z", "max_forks_repo_path": "audio_sync/sync_audio.cxx", "max_forks_repo_name": "zxh1986123/nerd_mmccoo", "max_forks_repo_head_hexsha": "dc5a152105d65673679ef37ea5d1f7607e4f3b2c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 23.0, "max_forks_repo_forks_event_min_datetime": "2018-02-12T21:18:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-21T23:04:51.000Z", "avg_line_length": 33.2469135802, "max_line_length": 226, "alphanum_fraction": 0.6024879317, "num_tokens": 1515, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4702017994336412}}
{"text": "#include <boost/simd/meta/is_power_of_2.hpp>\n#include <boost/mpl/assert.hpp>\n#include <boost/mpl/int.hpp>\n\nint main()\n{\n  using boost::mpl::int_;\n\n  BOOST_MPL_ASSERT    (( boost::simd::meta::is_power_of_2< int_<2> >::type  ));\n  BOOST_MPL_ASSERT    (( boost::simd::meta::is_power_of_2< int_<32> >::type ));\n  BOOST_MPL_ASSERT_NOT(( boost::simd::meta::is_power_of_2< int_<0> >::type  ));\n  BOOST_MPL_ASSERT_NOT(( boost::simd::meta::is_power_of_2< int_<6> >::type  ));\n}\n", "meta": {"hexsha": "dca44b5a6e42e07ed58ed0b596153b60ef4cec48", "size": 469, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/sdk/examples/meta/is_power_of_2.cpp", "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/sdk/examples/meta/is_power_of_2.cpp", "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/sdk/examples/meta/is_power_of_2.cpp", "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": 33.5, "max_line_length": 79, "alphanum_fraction": 0.6780383795, "num_tokens": 149, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.769080247656264, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.47020179943364115}}
{"text": "#include \"pybind11/pybind11.h\"\n\n#include \"xtensor/xmath.hpp\"\n#include \"xtensor/xarray.hpp\"\n#include <boost/pending/disjoint_sets.hpp>\n\n#define FORCE_IMPORT_ARRAY\n#include \"xtensor-python/pytensor.hpp\"\n#include \"xtensor-python/pyarray.hpp\"\n\n#include <iostream>\n#include <numeric>\n#include <cmath>\n\nnamespace py = pybind11;\n\n\nxt::pyarray<uint64_t> connected_components(const xt::pytensor<bool, 2> & image)\n{\n    typedef typename xt::pytensor<bool, 2>::shape_type IndexType;\n    const auto & shape = image.shape();\n    const std::size_t n_nodes = shape[0] * shape[1];\n\n    // make union find and map seeds to reperesentatives\n    std::vector<uint64_t> ranks(n_nodes);\n    std::vector<uint64_t> parents(n_nodes);\n    boost::disjoint_sets<uint64_t*, uint64_t*> ufd(&ranks[0], &parents[0]);\n    for(uint64_t node = 0; node < n_nodes; ++node) {\n        ufd.make_set(node);\n    }\n\n    // flatten the image\n    auto flat_image = xt::flatten(image);\n\n    const int n_ngbs = 4;\n    std::vector<int> shifts_x = {-1, 1, 0, 0};\n    std::vector<int> shifts_y = {0, 0, -1, 1};\n\n    // run connected components\n    for(uint64_t u = 0; u < n_nodes; ++u) {\n        if(flat_image[u] == 0) {\n            continue;\n        }\n\n        // get representative\n        const uint64_t ru = ufd.find_set(u);\n\n        const auto coordinate = xt::unravel_index(u, shape);\n        std::vector<IndexType> neighbor_coords;\n\n        // make the neighbors\n        for(unsigned ngb = 0; ngb < n_ngbs; ++ngb) {\n            const int sx = shifts_x[ngb];\n            const int sy = shifts_y[ngb];\n            const int64_t x = coordinate[0] + sx;\n            const int64_t y = coordinate[1] + sy;\n\n            // bounds check\n            if(x < 0 || x >= shape[0]) {\n                continue;\n            }\n            if(y < 0 || y >= shape[1]) {\n                continue;\n            }\n\n            neighbor_coords.emplace_back(IndexType({x, y}));\n        }\n\n        const auto neighbors = xt::ravel_indices(neighbor_coords, shape);\n        // iterate over the neighbors\n        for(const uint64_t v: neighbors) {\n            if(flat_image[v] == 0) {\n                continue;\n            }\n\n            const uint64_t rv = ufd.find_set(v);\n            if(ru == rv) {\n                continue;\n            }\n\n            ufd.link(ru, rv);\n        }\n    }\n\n    xt::pyarray<uint64_t> seg = xt::zeros<uint64_t>({n_nodes});\n    for(uint64_t u = 0; u < n_nodes; ++u) {\n        seg[u] = ufd.find_set(u);    \n    }\n    seg.reshape(shape);\n    return seg;\n}\n\n\n\nPYBIND11_MODULE(ccxt, m)\n{\n    xt::import_numpy();\n\n    m.doc() = R\"pbdoc(\n        ccxt\n\n        .. currentmodule:: ccxt\n\n        .. autosummary::\n           :toctree: _generate\n\n           connected_components\n    )pbdoc\";\n    m.def(\"connected_components\", connected_components, \"compute connected_components\");\n}\n", "meta": {"hexsha": "4553b0b94f5d863e1bfd8cd3f6860d0314fcb3b6", "size": 2830, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ccxt/src/main.cpp", "max_stars_repo_name": "constantinpape/fastpy", "max_stars_repo_head_hexsha": "b3b4f7114b393d4c4d413b13ed032461fd2e903e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ccxt/src/main.cpp", "max_issues_repo_name": "constantinpape/fastpy", "max_issues_repo_head_hexsha": "b3b4f7114b393d4c4d413b13ed032461fd2e903e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ccxt/src/main.cpp", "max_forks_repo_name": "constantinpape/fastpy", "max_forks_repo_head_hexsha": "b3b4f7114b393d4c4d413b13ed032461fd2e903e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-09T15:02:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-09T15:02:31.000Z", "avg_line_length": 25.4954954955, "max_line_length": 88, "alphanum_fraction": 0.5643109541, "num_tokens": 760, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851919, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4702017864900293}}
{"text": "/*\n * Copyright (C) 2016-2019 Istituto Italiano di Tecnologia (IIT)\n *\n * This software may be modified and distributed under the terms of the\n * BSD 3-Clause license. See the accompanying LICENSE file for details.\n */\n\n#include <BayesFilters/LinearStateModel.h>\n\n#include <Eigen/Dense>\n\nusing namespace bfl;\nusing namespace Eigen;\n\n\nvoid LinearStateModel::propagate(const Eigen::Ref<const Eigen::MatrixXd>& cur_states, Eigen::Ref<Eigen::MatrixXd> prop_states)\n{\n    if (is_skipping() && (have_exogenous_model() && exogenous_model().is_skipping()))\n    {\n        prop_states = cur_states;\n    }\n    else if (!is_skipping() && (have_exogenous_model() && !exogenous_model().is_skipping()))\n    {\n        MatrixXd exogenous_state(cur_states.rows(), cur_states.cols());\n\n        exogenous_model().propagate(cur_states, exogenous_state);\n\n        prop_states = getStateTransitionMatrix() * cur_states + exogenous_state;\n    }\n    else if (!is_skipping())\n    {\n        prop_states = getStateTransitionMatrix() * cur_states;\n    }\n    else if (have_exogenous_model() && !exogenous_model().is_skipping())\n    {\n        exogenous_model().propagate(cur_states, prop_states);\n    }\n}\n", "meta": {"hexsha": "39f0ddea2a0d8f940227464683e9007a96d978e2", "size": 1174, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/BayesFilters/src/LinearStateModel.cpp", "max_stars_repo_name": "mfkiwl/bayes-filters-lib", "max_stars_repo_head_hexsha": "8baabba1897bcc5634619fbc048bb5ab17a742da", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 50.0, "max_stars_repo_stars_event_min_datetime": "2017-04-12T09:02:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T20:01:35.000Z", "max_issues_repo_path": "src/BayesFilters/src/LinearStateModel.cpp", "max_issues_repo_name": "xEnVrE/bayes-filters-lib", "max_issues_repo_head_hexsha": "8baabba1897bcc5634619fbc048bb5ab17a742da", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 79.0, "max_issues_repo_issues_event_min_datetime": "2017-11-07T07:32:14.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-20T17:12:08.000Z", "max_forks_repo_path": "src/BayesFilters/src/LinearStateModel.cpp", "max_forks_repo_name": "xEnVrE/bayes-filters-lib", "max_forks_repo_head_hexsha": "8baabba1897bcc5634619fbc048bb5ab17a742da", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 23.0, "max_forks_repo_forks_event_min_datetime": "2017-05-07T01:47:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T10:15:59.000Z", "avg_line_length": 30.1025641026, "max_line_length": 126, "alphanum_fraction": 0.6942078365, "num_tokens": 280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851918, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.47020178649002925}}
{"text": "#include \"adjust_orientation_LBFGS.h\"\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\nusing Eigen::Matrix3d;\nusing Eigen::Vector3d;\nvoid evalfunc_ad_LBFGS(int N, double* x, double *prev_x, double* f, double* g, void* user_pointer)\n{\n\tdouble alpha = x[0]; double beta = x[1]; double gamma = x[2];\n\tdouble cos_alpha = std::cos(alpha); double sin_alpha = std::sin(alpha);\n\tdouble cos_beta = std::cos(beta); double sin_beta = std::sin(beta);\n\tdouble cos_gamma = std::cos(gamma); double sin_gamma = std::sin(gamma);\n\tdouble r00 = cos_alpha*cos_gamma - cos_beta*sin_alpha*sin_gamma;\n\tdouble r01 = sin_alpha*cos_gamma + cos_beta*cos_alpha*sin_gamma;\n\tdouble r02 = sin_beta*sin_gamma;\n\tdouble r10 = -cos_alpha*sin_gamma - cos_beta*sin_alpha*cos_gamma;\n\tdouble r11 = -sin_alpha*sin_gamma + cos_beta*cos_alpha*cos_gamma;\n\tdouble r12 = sin_beta*cos_gamma;\n\tdouble r20 = sin_beta*sin_alpha;\n\tdouble r21 = -sin_beta*cos_alpha;\n\tdouble r22 = cos_beta;\n\t\n\tuser_pointer_ad* up = (user_pointer_ad*)(user_pointer);\n\tint nbf = (int)up->bfn.size(); *f = 0.0;\n\tg[0] = 0; g[1] = 0; g[2] = 0;\n\tfor (int i = 0; i < nbf; ++i)\n\t{\n\t\tOpenVolumeMesh::Geometry::Vec3d& n = up->bfn[i];\n\t\t//OpenVolumeMesh::Geometry::Vec3d n(4.0, 5.0, 6.0);\n\t\tdouble nx = r00 * n[0] + r01 * n[1] + r02 * n[2];\n\t\tdouble ny = r10 * n[0] + r11 * n[1] + r12 * n[2];\n\t\tdouble nz = r20 * n[0] + r21 * n[1] + r22 * n[2];\n\t\t*f += (nx*ny)*(nx*ny) + (ny*nz)*(ny*nz) + (nz*nx)*(nz*nx);\n\t\tdouble d_nx_alpha = (-sin_alpha*cos_gamma - cos_beta*cos_alpha*sin_gamma) * n[0] + (cos_alpha*cos_gamma - cos_beta*sin_alpha*sin_gamma) * n[1] + 0 * n[2];\n\t\tdouble d_ny_alpha = (sin_alpha*sin_gamma - cos_beta*cos_alpha*cos_gamma) * n[0] + (-cos_alpha*sin_gamma - cos_beta*sin_alpha*cos_gamma) * n[1] + 0 * n[2];\n\t\tdouble d_nz_alpha = sin_beta*cos_alpha * n[0] + sin_beta*sin_alpha * n[1] + 0 * n[2];\n\t\tdouble d_nx_beta = (sin_beta*sin_alpha*sin_gamma) * n[0] + (-sin_beta*cos_alpha*sin_gamma) * n[1] + cos_beta*sin_gamma * n[2];\n\t\tdouble d_ny_beta = (sin_beta*sin_alpha*cos_gamma) * n[0] + (-sin_beta*cos_alpha*cos_gamma) * n[1] + cos_beta*cos_gamma * n[2];\n\t\tdouble d_nz_beta = cos_beta*sin_alpha *n[0] - cos_beta*cos_alpha * n[1] - sin_beta * n[2];\n\t\tdouble d_nx_gamma = (-cos_alpha*sin_gamma - cos_beta*sin_alpha*cos_gamma) * n[0] + (-sin_alpha*sin_gamma + cos_beta*cos_alpha*cos_gamma) * n[1] + sin_beta*cos_gamma * n[2];\n\t\tdouble d_ny_gamma = (-cos_alpha*cos_gamma + cos_beta*sin_alpha*sin_gamma) * n[0] + (-sin_alpha*cos_gamma - cos_beta*cos_alpha*sin_gamma) * n[1] + (-sin_beta*sin_gamma) * n[2];\n\t\tdouble d_nz_gamma = 0.0;\n\t\tg[0] += 2 * (nx*ny)*(d_nx_alpha*ny + nx*d_ny_alpha) + 2 * (ny*nz)*(d_ny_alpha*nz + ny*d_nz_alpha) + 2 * (nz*nx)*(d_nz_alpha*nx + nz*d_nx_alpha);\n\t\tg[1] += 2 * (nx*ny)*(d_nx_beta*ny + nx*d_ny_beta) + 2 * (ny*nz)*(d_ny_beta*nz + ny*d_nz_beta) + 2 * (nz*nx)*(d_nz_beta*nx + nz*d_nx_beta);\n\t\tg[2] += 2 * (nx*ny)*(d_nx_gamma*ny + nx*d_ny_gamma) + 2 * (ny*nz)*(d_ny_gamma*nz + ny*d_nz_gamma) + 2 * (nz*nx)*(d_nz_gamma*nx + nz*d_nx_gamma);\n\t\tstd::cout << \"g: \" << g[0] << \" \" << g[1] << \" \" << g[2] << std::endl;\n\t}\n}\nvoid evalfunc_ad_LBFGS_xyz(int N, double* x, double *prev_x, double* f, double* g, void* user_pointer)\n{\n\t//x y z axis rotation\n\tdouble cos_phi = std::cos(x[0]), sin_phi = std::sin(x[0]);\n\tdouble cos_theta = std::cos(x[1]), sin_theta = std::sin(x[1]);\n\tdouble cos_xi = std::cos(x[2]), sin_xi = std::sin(x[2]);\n\tMatrix3d Mtheta, Mphi, Msi, DMtheta, DMphi, DMsi;\n\tMtheta.setZero(); Mphi.setZero(); Msi.setZero();\n\tMphi(0,0) = 1; Mphi(1,1) = Mphi(2,2) = cos_phi, Mphi(1, 2) = sin_phi, Mphi(2, 1) = -sin_phi;\n\tMtheta(1, 1) = 1; Mtheta(0,0) = Mtheta(2,2) = cos_theta, Mtheta(2,0) = sin_theta, Mtheta(0, 2) = -sin_theta;\n\tMsi(2, 2) = 1; Msi(0, 0) = Msi(1, 1) = cos_xi, Msi(0, 1) = sin_xi, Msi(1, 0) = -sin_xi;\n\tDMtheta.setZero(); DMphi.setZero(); DMsi.setZero();\n\tDMphi(1, 1) = DMphi(2, 2) = -sin_phi, DMphi(1, 2) = cos_phi, DMphi(2, 1) = -cos_phi;\n\tDMtheta(0, 0) = DMtheta(2, 2) = -sin_theta, DMtheta(2, 0) = cos_theta, DMtheta(0, 2) = -cos_theta;\n\tDMsi(0, 0) = DMsi(1, 1) = -sin_xi, DMsi(0, 1) = cos_xi, DMsi(1,0) = -cos_xi;\n\tMatrix3d M = Msi * Mphi * Mtheta, dMsi = DMsi * Mphi * Mtheta, dMphi = Msi * DMphi * Mtheta, dMtheta = Msi * Mphi * DMtheta;\n\tVector3d DN, diffN_theta, diffN_phi, diffN_si;\n\tdouble xy, yz, zx;\n\tuser_pointer_ad* up = (user_pointer_ad*)(user_pointer);\n\tint nbf = (int)up->bfn.size(); *f = 0.0;\n\tg[0] = 0; g[1] = 0; g[2] = 0;\n\tfor (int i = 0; i < nbf; ++i)\n\t{\n\t\tOpenVolumeMesh::Geometry::Vec3d& n = up->bfn[i];\n\t\tVector3d N(n[0], n[1], n[2]);\n\t\t//Vector3d  N(1, 2, 3);\n\t\tDN = M * N;\n\t\tdiffN_theta = dMtheta * N;\n\t\tdiffN_phi = dMphi * N;\n\t\tdiffN_si = dMsi * N;\n\t\txy = DN[0] * DN[1];\n\t\tyz = DN[1] * DN[2];\n\t\tzx = DN[2] * DN[0];\n\t\t*f += (xy * xy + yz * yz + zx * zx) / 2;\n\t\tg[0] += xy * (diffN_phi[0] * DN[1] + DN[0] * diffN_phi[1]) +\n\t\t\tyz * (diffN_phi[1] * DN[2] + DN[1] * diffN_phi[2]) +\n\t\t\tzx * (diffN_phi[2] * DN[0] + DN[2] * diffN_phi[0]);\n\t\tg[1] += xy * (diffN_theta[0] * DN[1] + DN[0] * diffN_theta[1]) +\n\t\t\tyz * (diffN_theta[1] * DN[2] + DN[1] * diffN_theta[2]) +\n\t\t\tzx * (diffN_theta[2] * DN[0] + DN[2] * diffN_theta[0]);\n\t\tg[2] += xy * (diffN_si[0] * DN[1] + DN[0] * diffN_si[1]) +\n\t\t\tyz * (diffN_si[1] * DN[2] + DN[1] * diffN_si[2]) +\n\t\t\tzx * (diffN_si[2] * DN[0] + DN[2] * diffN_si[0]);\n\t\t//std::cout << \"f: \" << *f << \" g: \" << g[0] << \" \" << g[1] << \" \" << g[2] << std::endl;\n\t}\n\t\n\t//double alpha = x[0]; double beta = x[1]; double gamma = x[2];\n\t//double cos_alpha = std::cos(alpha); double sin_alpha = std::sin(alpha);\n\t//double cos_beta = std::cos(beta); double sin_beta = std::sin(beta);\n\t//double cos_gamma = std::cos(gamma); double sin_gamma = std::sin(gamma);\n\t//double r00 = cos_alpha * cos_gamma - cos_beta * sin_alpha*sin_gamma;\n\t//double r01 = sin_alpha * cos_gamma + cos_beta * cos_alpha*sin_gamma;\n\t//double r02 = sin_beta * sin_gamma;\n\t//double r10 = -cos_alpha * sin_gamma - cos_beta * sin_alpha*cos_gamma;\n\t//double r11 = -sin_alpha * sin_gamma + cos_beta * cos_alpha*cos_gamma;\n\t//double r12 = sin_beta * cos_gamma;\n\t//double r20 = sin_beta * sin_alpha;\n\t//double r21 = -sin_beta * cos_alpha;\n\t//double r22 = cos_beta;\n\t//user_pointer_ad* up = (user_pointer_ad*)(user_pointer);\n\t//int nbf = up->bfn.size(); *f = 0.0;\n\t//g[0] = 0; g[1] = 0; g[2] = 0;\n\t//for (int i = 0; i < nbf; ++i)\n\t//{\n\t//\tOpenVolumeMesh::Geometry::Vec3d& n = up->bfn[i];\n\t//\tdouble nx = r00 * n[0] + r01 * n[1] + r02 * n[2];\n\t//\tdouble ny = r10 * n[0] + r11 * n[1] + r12 * n[2];\n\t//\tdouble nz = r20 * n[0] + r21 * n[1] + r22 * n[2];\n\t//\t//*f += (nx*ny)*(nx*ny) + (ny*nz)*(ny*nz) + (nz*nx)*(nz*nx);\n\t//\t*f += nx * nx * nx * nx + ny * ny * ny * ny + nz * nz * nz * nz;\n\t//\tdouble d_nx_alpha = (-sin_alpha * cos_gamma - cos_beta * cos_alpha*sin_gamma) * n[0] + (cos_alpha*cos_gamma - cos_beta * sin_alpha*sin_gamma) * n[1] + 0 * n[2];\n\t//\tdouble d_ny_alpha = (sin_alpha*sin_gamma - cos_beta * cos_alpha*cos_gamma) * n[0] + (-cos_alpha * sin_gamma - cos_beta * sin_alpha*cos_gamma) * n[1] + 0 * n[2];\n\t//\tdouble d_nz_alpha = sin_beta * cos_alpha * n[0] + sin_beta * sin_alpha * n[1] + 0 * n[2];\n\t//\tdouble d_nx_beta = (sin_beta*sin_alpha*sin_gamma) * n[0] + (-sin_beta * cos_alpha*sin_gamma) * n[1] + cos_beta * sin_gamma * n[2];\n\t//\tdouble d_ny_beta = (sin_beta*sin_alpha*cos_gamma) * n[0] + (-sin_beta * cos_alpha*cos_gamma) * n[1] + cos_beta * cos_gamma * n[2];\n\t//\tdouble d_nz_beta = cos_beta * sin_alpha *n[0] - cos_beta * cos_alpha * n[1] - sin_beta * n[2];\n\t//\tdouble d_nx_gamma = (-cos_alpha * sin_gamma - cos_beta * sin_alpha*cos_gamma) * n[0] + (-sin_alpha * sin_gamma + cos_beta * cos_alpha*cos_gamma) * n[1] + sin_beta * cos_gamma * n[2];\n\t//\tdouble d_ny_gamma = (-cos_alpha * cos_gamma + cos_beta * sin_alpha*sin_gamma) * n[0] + (-sin_alpha * cos_gamma - cos_beta * cos_alpha*sin_gamma) * n[1] + (-sin_beta * sin_gamma) * n[2];\n\t//\tdouble d_nz_gamma = 0.0;\n\t//\t/*g[0] += 2 * (nx*ny)*(d_nx_alpha*ny + nx * d_ny_alpha) + 2 * (ny*nz)*(d_ny_alpha*nz + ny * d_nz_alpha) + 2 * (nz*nx)*(d_nz_alpha*nx + nz * d_nx_alpha);\n\t//\tg[1] += 2 * (nx*ny)*(d_nx_beta*ny + nx * d_ny_beta) + 2 * (ny*nz)*(d_ny_beta*nz + ny * d_nz_beta) + 2 * (nz*nx)*(d_nz_beta*nx + nz * d_nx_beta);\n\t//\tg[2] += 2 * (nx*ny)*(d_nx_gamma*ny + nx * d_ny_gamma) + 2 * (ny*nz)*(d_ny_gamma*nz + ny * d_nz_gamma) + 2 * (nz*nx)*(d_nz_gamma*nx + nz * d_nx_gamma);*/\n\t//\tg[0] += 4 * nx * nx * nx * (d_nx_alpha) + 4 * ny * ny * ny * (d_ny_alpha) + 4 * nz * nz * nz * (d_nz_alpha);\n\t//\tg[1] += 4 * nx * nx * nx * (d_nx_beta) + 4 * ny * ny * ny * (d_ny_beta) + 4 * nz * nz * nz * (d_nz_beta);\n\t//\tg[2] += 4 * nx * nx * nx * (d_nx_gamma) + 4 * ny * ny * ny * (d_ny_gamma) + 4 * nz * nz * nz * (d_nz_gamma);\n\t//}\n}\nvoid newiteration_ad_LBFGS(int iter, int call_iter, double *x, double* f, double *g, double* gnorm, void* user_pointer)\n{\n\tprintf(\"%d %d; %4.3e, %4.3e\\n\", iter, call_iter, f[0], gnorm[0]);\n}\nbool ad_LBFGS(std::vector<OpenVolumeMesh::Geometry::Vec3d>& bfn, std::vector<double>& X)\n{\n\tuser_pointer_ad up;\n\tup.bfn = bfn;\n\t//LBFGS\n\tdouble parameter[20];\n\tint info[20];\n\t//initialize\n\tINIT_HLBFGS(parameter, info);\n\tparameter[2] = 0.9;\n\tinfo[4] = 100; //number of iteration\n\tinfo[6] = 0;\n\tinfo[7] = 0; //if with hessian 1, without 0\n\tinfo[10] = 0;\n\tint N = 3; int M = 7;\n\t//m is the number of history value\n\t//n is the number of variables\n\tprintf(\"-------------------------------\\n\");\n\tprintf(\"start LBFGS\\n\");\n\t//function change to nx^4 + ny^4 + nz^ 4?\n\t//HLBFGS(N, M, &X[0], evalfunc_ad_LBFGS, 0, HLBFGS_UPDATE_Hessian, newiteration_ad_LBFGS, parameter, info, &up);\n\tHLBFGS(N, M, &X[0], evalfunc_ad_LBFGS_xyz, 0, HLBFGS_UPDATE_Hessian, newiteration_ad_LBFGS, parameter, info, &up);\n\treturn true;\n}\n", "meta": {"hexsha": "0231d97fecf42ab40ff489d4ef054733e5dbb20b", "size": 9656, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ScissorPoly/adjust_orientation_LBFGS.cpp", "max_stars_repo_name": "msraig/CE-PolyCube", "max_stars_repo_head_hexsha": "e46aff6e0594b711735118bfa902a91bc3d392ca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2020-08-13T05:15:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:51:29.000Z", "max_issues_repo_path": "ScissorPoly/adjust_orientation_LBFGS.cpp", "max_issues_repo_name": "xh-liu-tech/CE-PolyCube", "max_issues_repo_head_hexsha": "86d4ed0023215307116b6b3245e2dbd82907cbb8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-09-08T07:03:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-04T05:43:27.000Z", "max_forks_repo_path": "ScissorPoly/adjust_orientation_LBFGS.cpp", "max_forks_repo_name": "xh-liu-tech/CE-PolyCube", "max_forks_repo_head_hexsha": "86d4ed0023215307116b6b3245e2dbd82907cbb8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2020-08-06T02:37:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-01T09:12:06.000Z", "avg_line_length": 59.2392638037, "max_line_length": 189, "alphanum_fraction": 0.6145401823, "num_tokens": 3890, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127678225577, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.47017065948768383}}
{"text": "//==================================================================================================\n/**\n  EVE - Expressive Vector Engine\n  Copyright : EVE Contributors & Maintainers\n  SPDX-License-Identifier: MIT\n**/\n//==================================================================================================\n#include <boost/math/special_functions/bessel.hpp>\n#include <eve/function/cyl_bessel_j.hpp>\n#include <eve/constant/inf.hpp>\n#include <eve/constant/minf.hpp>\n#include <eve/constant/nan.hpp>\n#include <eve/platform.hpp>\n#include <cmath>\n\nTTS_CASE_TPL(\"Check eve::cyl_bessel_j return type\", EVE_TYPE)\n{\n  TTS_EXPR_IS(eve::cyl_bessel_j(T(0), T(0)), T);\n}\n\nTTS_CASE_TPL(\"Check eve::cyl_bessel_j behavior\", EVE_TYPE)\n{\n\n  auto eve__cyl_bessel_j =  [](auto n, auto x) { return eve::cyl_bessel_j(n, x); };\n  auto boost_cyl_bessel_j =  [](auto n, auto x) { return boost::math::cyl_bessel_j(n, x); };\n  if constexpr( eve::platform::supports_invalids )\n  {\n    TTS_ULP_EQUAL(eve__cyl_bessel_j(T(2), eve::minf(eve::as<T>())), eve::zero(eve::as<T>()), 0);\n    TTS_ULP_EQUAL(eve__cyl_bessel_j(T(2), eve::inf(eve::as<T>())), eve::zero(eve::as<T>()), 0);\n    TTS_ULP_EQUAL(eve__cyl_bessel_j(T(3), eve::nan(eve::as<T>())), eve::nan(eve::as<T>()), 0);\n  }\n\n  for(int i=1; i < 2; i*= 2)\n  {\n    TTS_ULP_EQUAL(eve__cyl_bessel_j(T(i), T(10)), T(boost_cyl_bessel_j(i, 10)), 10);\n    TTS_ULP_EQUAL(eve__cyl_bessel_j(T(i), T(5)), T(boost_cyl_bessel_j(i, 5)), 10);\n    TTS_ULP_EQUAL(eve__cyl_bessel_j(T(i), T(2)), T(boost_cyl_bessel_j(i, 2)), 10);\n    TTS_ULP_EQUAL(eve__cyl_bessel_j(T(i), T(1)), T(boost_cyl_bessel_j(i, 1)), 10);\n    TTS_ULP_EQUAL(eve__cyl_bessel_j(T(i), T(0)), T(boost_cyl_bessel_j(i, 0)), 10);\n  }\n}\n", "meta": {"hexsha": "4640ad0dca3f08e8429e9de49e691dda7bdbeac0", "size": 1713, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/unit/module/real/special/cyl_bessel_j/regular/cyl_bessel_j.hpp", "max_stars_repo_name": "orao/eve", "max_stars_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_stars_repo_licenses": ["MIT"], "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/unit/module/real/special/cyl_bessel_j/regular/cyl_bessel_j.hpp", "max_issues_repo_name": "orao/eve", "max_issues_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_issues_repo_licenses": ["MIT"], "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/unit/module/real/special/cyl_bessel_j/regular/cyl_bessel_j.hpp", "max_forks_repo_name": "orao/eve", "max_forks_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_forks_repo_licenses": ["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.7857142857, "max_line_length": 100, "alphanum_fraction": 0.5960303561, "num_tokens": 563, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.47013091728280726}}
{"text": "#include \"PiecewisePolynomial.h\"\n#include <Eigen/Core>\n#include <random>\n#include <vector>\n#include \"testUtil.h\"\n#include <iostream>\n\nusing namespace std;\nusing namespace Eigen;\n\ndefault_random_engine generator;\nuniform_real_distribution<double> uniform;\n\nvector<double> generateSegmentTimes(int num_segments) {\n  vector<double> segment_times;\n  double t0 = uniform(generator);\n  segment_times.push_back(t0);\n  for (int i = 0; i < num_segments; ++i) {\n    double duration = uniform(generator);\n    segment_times.push_back(segment_times[i] + duration);\n  }\n  return segment_times;\n}\n\ntemplate <typename CoefficientType>\nvoid testIntegralAndDerivative() {\n  vector<Polynomial<CoefficientType>> polynomials;\n  int num_coefficients = 5;\n  int num_segments = 3;\n  typedef typename Polynomial<CoefficientType>::CoefficientsType CoefficientsType;\n  for (int i = 0; i < num_segments; ++i) {\n    CoefficientsType coefficients = CoefficientsType::Random(num_coefficients);\n    polynomials.push_back(Polynomial<CoefficientType>(coefficients));\n  }\n\n  // differentiate integral, get original back\n  PiecewisePolynomial<CoefficientType> piecewise(polynomials, generateSegmentTimes(num_segments));\n  PiecewisePolynomial<CoefficientType> piecewise_back = piecewise.integral().derivative();\n  if (!piecewise.isApprox(piecewise_back, 1e-10))\n    throw runtime_error(\"wrong\");\n\n  // check value at start time\n  double value_at_t0 = uniform(generator);\n  PiecewisePolynomial<CoefficientType> integral = piecewise.integral(value_at_t0);\n  valuecheck(value_at_t0, integral.value(piecewise.getStartTime()), 1e-10);\n\n  // check continuity at knot points\n  for (int i = 0; i < piecewise.getNumberOfSegments() - 1; ++i) {\n    valuecheck(integral.getPolynomial(i).value(integral.getDuration(i)), integral.getPolynomial(i + 1).value(0.0));\n  }\n}\n\nint main(int argc, char **argv) {\n  testIntegralAndDerivative<double>();\n\n  std::cout << \"test passed\";\n\n  return 0;\n}\n", "meta": {"hexsha": "c30381b579a1ae3e43c8704ad70fc88b6629bee1", "size": 1939, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "systems/trajectories/test/testPiecewisePolynomial.cpp", "max_stars_repo_name": "jacob-izr/drake", "max_stars_repo_head_hexsha": "d8f0f1f231ecba83ed53b1a1c2f9f43da50396b9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "systems/trajectories/test/testPiecewisePolynomial.cpp", "max_issues_repo_name": "jacob-izr/drake", "max_issues_repo_head_hexsha": "d8f0f1f231ecba83ed53b1a1c2f9f43da50396b9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "systems/trajectories/test/testPiecewisePolynomial.cpp", "max_forks_repo_name": "jacob-izr/drake", "max_forks_repo_head_hexsha": "d8f0f1f231ecba83ed53b1a1c2f9f43da50396b9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.3166666667, "max_line_length": 115, "alphanum_fraction": 0.7550283651, "num_tokens": 481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587586, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.47013091306906307}}
{"text": "//\n// Created by Alex Beccaro on 18/01/18.\n//\n\n#define BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n#include \"../../src/problems/51-100/71/problem71.hpp\"\n\nBOOST_AUTO_TEST_SUITE( Problem71 )\n\n    BOOST_AUTO_TEST_CASE( Example ) {\n        auto res = problems::problem71::solve(8);\n        BOOST_CHECK_EQUAL(res, 2);\n    }\n\n    BOOST_AUTO_TEST_CASE( Solution ) {\n        auto res = problems::problem71::solve();\n        BOOST_CHECK_EQUAL(res, 428570);\n    }\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "fa96298a348c5bfdbf87fcd48d7c6c638c247ecc", "size": 494, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/51-100/test_problem71.cpp", "max_stars_repo_name": "abeccaro/project-euler", "max_stars_repo_head_hexsha": "c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T10:17:15.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-25T10:17:15.000Z", "max_issues_repo_path": "tests/51-100/test_problem71.cpp", "max_issues_repo_name": "abeccaro/project-euler", "max_issues_repo_head_hexsha": "c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3", "max_issues_repo_licenses": ["MIT"], "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/51-100/test_problem71.cpp", "max_forks_repo_name": "abeccaro/project-euler", "max_forks_repo_head_hexsha": "c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3", "max_forks_repo_licenses": ["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.5238095238, "max_line_length": 53, "alphanum_fraction": 0.6761133603, "num_tokens": 125, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.6723316991792861, "lm_q1q2_score": 0.47013091306906307}}
{"text": "//\n// \tCopyright (c) 2020, Cem Bassoy, cem.bassoy@gmail.com\n//\n//  Distributed under the Boost Software License, Version 1.0. (See\n//  accompanying file LICENSE_1_0.txt or copy at\n//  http://www.boost.org/LICENSE_1_0.txt)\n//\n//  The authors gratefully acknowledge the support of\n//  Google and Fraunhofer IOSB, Ettlingen, Germany\n//\n\n\n#include <vector>\n#include <array>\n\n#include <boost/test/unit_test.hpp>\n#include <boost/numeric/ublas/tensor/extents.hpp>\n\n\n\nBOOST_AUTO_TEST_SUITE(test_shape_functions)\n\nstruct fixture_extents_dynamic_rank\n{\n  using shape_t = boost::numeric::ublas::extents<>;\n\n  static inline auto n     = shape_t{};\n  static inline auto n1    = shape_t{1};\n  static inline auto n2    = shape_t{2};\n  static inline auto n11   = shape_t{1,1};\n  static inline auto n12   = shape_t{1,2};\n  static inline auto n21   = shape_t{2,1};\n  static inline auto n22   = shape_t{2,2};\n  static inline auto n32   = shape_t{3,2};\n  static inline auto n111  = shape_t{1,1,1};\n  static inline auto n211  = shape_t{2,1,1};\n  static inline auto n121  = shape_t{1,2,1};\n  static inline auto n112  = shape_t{1,1,2};\n  static inline auto n123  = shape_t{1,2,3};\n  static inline auto n321  = shape_t{3,2,1};\n  static inline auto n213  = shape_t{2,1,3};\n  static inline auto n432  = shape_t{4,3,2};\n};\n\nstruct fixture_extents_static_rank\n{\n  template<std::size_t N>\n  using extents_static_rank = boost::numeric::ublas::extents<N>;\n\n  static constexpr inline auto n     = extents_static_rank<0>{};\n  static constexpr inline auto n1    = extents_static_rank<1>{1};\n  static constexpr inline auto n2    = extents_static_rank<1>{2};\n  static constexpr inline auto n11   = extents_static_rank<2>{{1,1}};\n  static constexpr inline auto n12   = extents_static_rank<2>{{1,2}};\n  static constexpr inline auto n21   = extents_static_rank<2>{{2,1}};\n  static constexpr inline auto n22   = extents_static_rank<2>{{2,2}};\n  static constexpr inline auto n32   = extents_static_rank<2>{{3,2}};\n  static constexpr inline auto n111  = extents_static_rank<3>{{1,1,1}};\n  static constexpr inline auto n211  = extents_static_rank<3>{{2,1,1}};\n  static constexpr inline auto n121  = extents_static_rank<3>{{1,2,1}};\n  static constexpr inline auto n112  = extents_static_rank<3>{{1,1,2}};\n  static constexpr inline auto n123  = extents_static_rank<3>{{1,2,3}};\n  static constexpr inline auto n321  = extents_static_rank<3>{{3,2,1}};\n  static constexpr inline auto n213  = extents_static_rank<3>{{2,1,3}};\n  static constexpr inline auto n432  = extents_static_rank<3>{{4,3,2}};\n\n  static constexpr inline auto tuple = std::make_tuple( n,n1,n2,n11,n12,n21,n22,n32,n111,n211,n121,n112,n123,n321,n213,n432 );\n\n};\n\n\n\nstruct fixture_extents_static\n{\n  template<std::size_t ... ns>\n  using extents_static = boost::numeric::ublas::extents<ns...>;\n\n  static inline auto n     = extents_static<>      {};\n  static inline auto n1    = extents_static<1>     {};\n  static inline auto n2    = extents_static<2>     {};\n  static inline auto n11   = extents_static<1,1>   {};\n  static inline auto n12   = extents_static<1,2>   {};\n  static inline auto n21   = extents_static<2,1>   {};\n  static inline auto n22   = extents_static<2,2>   {};\n  static inline auto n32   = extents_static<3,2>   {};\n  static inline auto n111  = extents_static<1,1,1> {};\n  static inline auto n211  = extents_static<2,1,1> {};\n  static inline auto n121  = extents_static<1,2,1> {};\n  static inline auto n112  = extents_static<1,1,2> {};\n  static inline auto n123  = extents_static<1,2,3> {};\n  static inline auto n321  = extents_static<3,2,1> {};\n  static inline auto n213  = extents_static<2,1,3> {};\n  static inline auto n432  = extents_static<4,3,2> {};\n\n\n\n};\n\n\n\n\nBOOST_FIXTURE_TEST_CASE(test_extents_dynamic_rank_is_scalar,\n                        fixture_extents_dynamic_rank,\n                        *boost::unit_test::label(\"extents_dynamic_rank\")\n                          *boost::unit_test::label(\"is_scalar\"))\n{\n\n  namespace ub = boost::numeric::ublas;  \n  BOOST_CHECK ( !ub::is_scalar( n    ));\n  BOOST_CHECK (  ub::is_scalar( n1   ));\n  BOOST_CHECK ( !ub::is_scalar( n2   ));\n  BOOST_CHECK (  ub::is_scalar( n11  ));\n  BOOST_CHECK ( !ub::is_scalar( n12  ));\n  BOOST_CHECK ( !ub::is_scalar( n21  ));\n  BOOST_CHECK ( !ub::is_scalar( n22  ));\n  BOOST_CHECK ( !ub::is_scalar( n32  ));\n  BOOST_CHECK (  ub::is_scalar( n111 ));\n  BOOST_CHECK ( !ub::is_scalar( n211 ));\n  BOOST_CHECK ( !ub::is_scalar( n121 ));\n  BOOST_CHECK ( !ub::is_scalar( n112 ));\n  BOOST_CHECK ( !ub::is_scalar( n123 ));\n  BOOST_CHECK ( !ub::is_scalar( n321 ));\n  BOOST_CHECK ( !ub::is_scalar( n213 ));\n  BOOST_CHECK ( !ub::is_scalar( n432 ));\n}\n\n\nBOOST_FIXTURE_TEST_CASE(test_extents_static_rank_is_scalar,\n                        fixture_extents_static_rank,\n                        *boost::unit_test::label(\"extents_static_rank\")\n                          *boost::unit_test::label(\"is_scalar\"))\n{\n\n  namespace ub = boost::numeric::ublas;\n  BOOST_CHECK ( !ub::is_scalar( n    ));\n  BOOST_CHECK (  ub::is_scalar( n1   ));\n  BOOST_CHECK ( !ub::is_scalar( n2   ));\n  BOOST_CHECK (  ub::is_scalar( n11  ));\n  BOOST_CHECK ( !ub::is_scalar( n12  ));\n  BOOST_CHECK ( !ub::is_scalar( n21  ));\n  BOOST_CHECK ( !ub::is_scalar( n22  ));\n  BOOST_CHECK ( !ub::is_scalar( n32  ));\n  BOOST_CHECK (  ub::is_scalar( n111 ));\n  BOOST_CHECK ( !ub::is_scalar( n211 ));\n  BOOST_CHECK ( !ub::is_scalar( n121 ));\n  BOOST_CHECK ( !ub::is_scalar( n112 ));\n  BOOST_CHECK ( !ub::is_scalar( n123 ));\n  BOOST_CHECK ( !ub::is_scalar( n321 ));\n  BOOST_CHECK ( !ub::is_scalar( n213 ));\n  BOOST_CHECK ( !ub::is_scalar( n432 ));\n\n}\n\n\nBOOST_FIXTURE_TEST_CASE(test_extents_static_is_scalar,\n                        fixture_extents_static,\n                        *boost::unit_test::label(\"extents_static\")\n                          *boost::unit_test::label(\"is_scalar\"))\n{\n\n  namespace ub = boost::numeric::ublas;\n  BOOST_CHECK ( !ub::is_scalar( n    ));\n//FIXME:  BOOST_CHECK (  ub::is_scalar( n1   ));\n  BOOST_CHECK ( !ub::is_scalar( n2   ));\n  BOOST_CHECK (  ub::is_scalar( n11  ));\n  BOOST_CHECK ( !ub::is_scalar( n12  ));\n  BOOST_CHECK ( !ub::is_scalar( n21  ));\n  BOOST_CHECK ( !ub::is_scalar( n22  ));\n  BOOST_CHECK ( !ub::is_scalar( n32  ));\n  BOOST_CHECK (  ub::is_scalar( n111 ));\n  BOOST_CHECK ( !ub::is_scalar( n211 ));\n  BOOST_CHECK ( !ub::is_scalar( n121 ));\n  BOOST_CHECK ( !ub::is_scalar( n112 ));\n  BOOST_CHECK ( !ub::is_scalar( n123 ));\n  BOOST_CHECK ( !ub::is_scalar( n321 ));\n  BOOST_CHECK ( !ub::is_scalar( n213 ));\n  BOOST_CHECK ( !ub::is_scalar( n432 ));\n\n}\n\n\nBOOST_FIXTURE_TEST_CASE(test_extents_dynamic_rank_is_vector,\n                        fixture_extents_dynamic_rank,\n                        *boost::unit_test::label(\"extents_dynamic_rank\")\n                          *boost::unit_test::label(\"is_vector\"))\n{\n\n  namespace ub = boost::numeric::ublas;\n  BOOST_CHECK ( !ub::is_vector( n    ));\n  BOOST_CHECK (  ub::is_vector( n1   ));\n  BOOST_CHECK (  ub::is_vector( n2   ));\n  BOOST_CHECK (  ub::is_vector( n11  ));\n  BOOST_CHECK (  ub::is_vector( n12  ));\n  BOOST_CHECK (  ub::is_vector( n21  ));\n  BOOST_CHECK ( !ub::is_vector( n22  ));\n  BOOST_CHECK ( !ub::is_vector( n32  ));\n  BOOST_CHECK (  ub::is_vector( n111 ));\n  BOOST_CHECK (  ub::is_vector( n211 ));\n  BOOST_CHECK (  ub::is_vector( n121 ));\n  BOOST_CHECK ( !ub::is_vector( n112 ));\n  BOOST_CHECK ( !ub::is_vector( n123 ));\n  BOOST_CHECK ( !ub::is_vector( n321 ));\n  BOOST_CHECK ( !ub::is_vector( n213 ));\n  BOOST_CHECK ( !ub::is_vector( n432 ));\n}\n\nBOOST_FIXTURE_TEST_CASE(test_extents_static_rank_is_vector,\n                        fixture_extents_static_rank,\n                        *boost::unit_test::label(\"extents_static_rank\")\n                          *boost::unit_test::label(\"is_vector\"))\n{\n\n  namespace ub = boost::numeric::ublas;\n  BOOST_CHECK ( !ub::is_vector( n    ));\n  BOOST_CHECK (  ub::is_vector( n1   ));\n  BOOST_CHECK (  ub::is_vector( n2   ));\n  BOOST_CHECK (  ub::is_vector( n11  ));\n  BOOST_CHECK (  ub::is_vector( n12  ));\n  BOOST_CHECK (  ub::is_vector( n21  ));\n  BOOST_CHECK ( !ub::is_vector( n22  ));\n  BOOST_CHECK ( !ub::is_vector( n32  ));\n  BOOST_CHECK (  ub::is_vector( n111 ));\n  BOOST_CHECK (  ub::is_vector( n211 ));\n  BOOST_CHECK (  ub::is_vector( n121 ));\n  BOOST_CHECK ( !ub::is_vector( n112 ));\n  BOOST_CHECK ( !ub::is_vector( n123 ));\n  BOOST_CHECK ( !ub::is_vector( n321 ));\n  BOOST_CHECK ( !ub::is_vector( n213 ));\n  BOOST_CHECK ( !ub::is_vector( n432 ));\n}\n\n\nBOOST_FIXTURE_TEST_CASE(test_extents_static_is_vector,\n                        fixture_extents_static,\n                        *boost::unit_test::label(\"extents_static\")\n                          *boost::unit_test::label(\"is_vector\"))\n{\n\n  namespace ub = boost::numeric::ublas;\n  BOOST_CHECK ( !ub::is_vector( n1   ));\n//FIXME:  BOOST_CHECK (  ub::is_vector( n2   ));\n  BOOST_CHECK (  ub::is_vector( n11  ));\n  BOOST_CHECK (  ub::is_vector( n12  ));\n  BOOST_CHECK (  ub::is_vector( n21  ));\n  BOOST_CHECK ( !ub::is_vector( n22  ));\n  BOOST_CHECK ( !ub::is_vector( n32  ));\n  BOOST_CHECK (  ub::is_vector( n111 ));\n  BOOST_CHECK (  ub::is_vector( n211 ));\n  BOOST_CHECK (  ub::is_vector( n121 ));\n  BOOST_CHECK ( !ub::is_vector( n112 ));\n  BOOST_CHECK ( !ub::is_vector( n123 ));\n  BOOST_CHECK ( !ub::is_vector( n321 ));\n  BOOST_CHECK ( !ub::is_vector( n213 ));\n  BOOST_CHECK ( !ub::is_vector( n432 ));\n}\n\nBOOST_FIXTURE_TEST_CASE(test_extents_dynamic_rank_is_matrix,\n                        fixture_extents_dynamic_rank,\n                        *boost::unit_test::label(\"extents_dynamic_rank\")\n                          *boost::unit_test::label(\"is_matrix\"))\n{\n\n  namespace ub = boost::numeric::ublas;\n  BOOST_CHECK ( !ub::is_matrix( n    ));\n  BOOST_CHECK (  ub::is_matrix( n1   ));\n  BOOST_CHECK (  ub::is_matrix( n2   ));\n  BOOST_CHECK (  ub::is_matrix( n11  ));\n  BOOST_CHECK (  ub::is_matrix( n12  ));\n  BOOST_CHECK (  ub::is_matrix( n21  ));\n  BOOST_CHECK (  ub::is_matrix( n22  ));\n  BOOST_CHECK (  ub::is_matrix( n32  ));\n  BOOST_CHECK (  ub::is_matrix( n111 ));\n  BOOST_CHECK (  ub::is_matrix( n211 ));\n  BOOST_CHECK (  ub::is_matrix( n121 ));\n  BOOST_CHECK ( !ub::is_matrix( n112 ));\n  BOOST_CHECK ( !ub::is_matrix( n123 ));\n  BOOST_CHECK (  ub::is_matrix( n321 ));\n  BOOST_CHECK ( !ub::is_matrix( n213 ));\n  BOOST_CHECK ( !ub::is_matrix( n432 ));\n}\n\nBOOST_FIXTURE_TEST_CASE(test_extents_static_rank_is_matrix,\n                        fixture_extents_static_rank,\n                        *boost::unit_test::label(\"extents_static_rank\")\n                          *boost::unit_test::label(\"is_matrix\"))\n{\n\n  namespace ub = boost::numeric::ublas;\n  BOOST_CHECK ( !ub::is_matrix( n    ));\n  BOOST_CHECK (  ub::is_matrix( n1   ));\n  BOOST_CHECK (  ub::is_matrix( n2   ));\n  BOOST_CHECK (  ub::is_matrix( n11  ));\n  BOOST_CHECK (  ub::is_matrix( n12  ));\n  BOOST_CHECK (  ub::is_matrix( n21  ));\n  BOOST_CHECK (  ub::is_matrix( n22  ));\n  BOOST_CHECK (  ub::is_matrix( n32  ));\n  BOOST_CHECK (  ub::is_matrix( n111 ));\n  BOOST_CHECK (  ub::is_matrix( n211 ));\n  BOOST_CHECK (  ub::is_matrix( n121 ));\n  BOOST_CHECK ( !ub::is_matrix( n112 ));\n  BOOST_CHECK ( !ub::is_matrix( n123 ));\n  BOOST_CHECK (  ub::is_matrix( n321 ));\n  BOOST_CHECK ( !ub::is_matrix( n213 ));\n  BOOST_CHECK ( !ub::is_matrix( n432 ));\n}\n\n\nBOOST_FIXTURE_TEST_CASE(test_extents_static_is_matrix,\n                        fixture_extents_static,\n                        *boost::unit_test::label(\"extents_static\")\n                          *boost::unit_test::label(\"is_matrix\"))\n{\n\n  namespace ub = boost::numeric::ublas;\n  BOOST_CHECK ( !ub::is_matrix( n    ));\n//FIXME:  BOOST_CHECK ( !ub::is_matrix( n1   ));\n  BOOST_CHECK ( !ub::is_matrix( n2   ));\n  BOOST_CHECK (  ub::is_matrix( n11  ));\n  BOOST_CHECK (  ub::is_matrix( n12  ));\n  BOOST_CHECK (  ub::is_matrix( n21  ));\n  BOOST_CHECK (  ub::is_matrix( n22  ));\n  BOOST_CHECK (  ub::is_matrix( n32  ));\n  BOOST_CHECK (  ub::is_matrix( n111 ));\n  BOOST_CHECK (  ub::is_matrix( n211 ));\n  BOOST_CHECK (  ub::is_matrix( n121 ));\n  BOOST_CHECK ( !ub::is_matrix( n112 ));\n  BOOST_CHECK ( !ub::is_matrix( n123 ));\n  BOOST_CHECK (  ub::is_matrix( n321 ));\n  BOOST_CHECK ( !ub::is_matrix( n213 ));\n  BOOST_CHECK ( !ub::is_matrix( n432 ));\n}\n\n\nBOOST_FIXTURE_TEST_CASE(test_extents_dynamic_rank_is_tensor,\n                        fixture_extents_dynamic_rank,\n                        *boost::unit_test::label(\"extents_dynamic_rank\")\n                          *boost::unit_test::label(\"is_tensor\"))\n{\n\n  namespace ub = boost::numeric::ublas;\n  BOOST_CHECK ( !ub::is_tensor( n    ));\n  BOOST_CHECK ( !ub::is_tensor( n1   ));\n  BOOST_CHECK ( !ub::is_tensor( n2   ));\n  BOOST_CHECK ( !ub::is_tensor( n11  ));\n  BOOST_CHECK ( !ub::is_tensor( n12  ));\n  BOOST_CHECK ( !ub::is_tensor( n21  ));\n  BOOST_CHECK ( !ub::is_tensor( n22  ));\n  BOOST_CHECK ( !ub::is_tensor( n32  ));\n  BOOST_CHECK ( !ub::is_tensor( n111 ));\n  BOOST_CHECK ( !ub::is_tensor( n211 ));\n  BOOST_CHECK ( !ub::is_tensor( n121 ));\n  BOOST_CHECK (  ub::is_tensor( n112 ));\n  BOOST_CHECK (  ub::is_tensor( n123 ));\n  BOOST_CHECK ( !ub::is_tensor( n321 ));\n  BOOST_CHECK (  ub::is_tensor( n213 ));\n  BOOST_CHECK (  ub::is_tensor( n432 ));\n}\n\n\nBOOST_FIXTURE_TEST_CASE(test_extents_static_rank_is_tensor,\n                        fixture_extents_static_rank,\n                        *boost::unit_test::label(\"extents_static_rank\")\n                          *boost::unit_test::label(\"is_tensor\"))\n{\n\n  namespace ub = boost::numeric::ublas;\n  BOOST_CHECK ( !ub::is_tensor( n    ));\n  BOOST_CHECK ( !ub::is_tensor( n1   ));\n  BOOST_CHECK ( !ub::is_tensor( n2   ));\n  BOOST_CHECK ( !ub::is_tensor( n11  ));\n  BOOST_CHECK ( !ub::is_tensor( n12  ));\n  BOOST_CHECK ( !ub::is_tensor( n21  ));\n  BOOST_CHECK ( !ub::is_tensor( n22  ));\n  BOOST_CHECK ( !ub::is_tensor( n32  ));\n  BOOST_CHECK ( !ub::is_tensor( n111 ));\n  BOOST_CHECK ( !ub::is_tensor( n211 ));\n  BOOST_CHECK ( !ub::is_tensor( n121 ));\n  BOOST_CHECK (  ub::is_tensor( n112 ));\n  BOOST_CHECK (  ub::is_tensor( n123 ));\n  BOOST_CHECK ( !ub::is_tensor( n321 ));\n  BOOST_CHECK (  ub::is_tensor( n213 ));\n  BOOST_CHECK (  ub::is_tensor( n432 ));\n}\n\n\nBOOST_FIXTURE_TEST_CASE(test_extents_static_is_tensor,\n                        fixture_extents_static,\n                        *boost::unit_test::label(\"extents_static\")\n                          *boost::unit_test::label(\"is_tensor\"))\n{\n\n  namespace ub = boost::numeric::ublas;\n  BOOST_CHECK ( !ub::is_tensor( n    ));\n//FIXME:  BOOST_CHECK ( !ub::is_tensor( n1   ));\n  BOOST_CHECK ( !ub::is_tensor( n2   ));\n  BOOST_CHECK ( !ub::is_tensor( n11  ));\n  BOOST_CHECK ( !ub::is_tensor( n12  ));\n  BOOST_CHECK ( !ub::is_tensor( n21  ));\n  BOOST_CHECK ( !ub::is_tensor( n22  ));\n  BOOST_CHECK ( !ub::is_tensor( n32  ));\n  BOOST_CHECK ( !ub::is_tensor( n111 ));\n  BOOST_CHECK ( !ub::is_tensor( n211 ));\n  BOOST_CHECK ( !ub::is_tensor( n121 ));\n  BOOST_CHECK (  ub::is_tensor( n112 ));\n  BOOST_CHECK (  ub::is_tensor( n123 ));\n  BOOST_CHECK ( !ub::is_tensor( n321 ));\n  BOOST_CHECK (  ub::is_tensor( n213 ));\n  BOOST_CHECK (  ub::is_tensor( n432 ));\n}\n\nBOOST_FIXTURE_TEST_CASE(test_extents_dynamic_rank_is_valid,\n                        fixture_extents_dynamic_rank,\n                        *boost::unit_test::label(\"extents_dynamic_rank\")\n                          *boost::unit_test::label(\"is_valid\"))\n{\n\n  namespace ub = boost::numeric::ublas;\n  BOOST_CHECK (  ub::is_valid( n1   ));\n  BOOST_CHECK (  ub::is_valid( n2   ));\n  BOOST_CHECK (  ub::is_valid( n11  ));\n  BOOST_CHECK (  ub::is_valid( n12  ));\n  BOOST_CHECK (  ub::is_valid( n21  ));\n  BOOST_CHECK (  ub::is_valid( n22  ));\n  BOOST_CHECK (  ub::is_valid( n32  ));\n  BOOST_CHECK (  ub::is_valid( n111 ));\n  BOOST_CHECK (  ub::is_valid( n211 ));\n  BOOST_CHECK (  ub::is_valid( n121 ));\n  BOOST_CHECK (  ub::is_valid( n112 ));\n  BOOST_CHECK (  ub::is_valid( n123 ));\n  BOOST_CHECK (  ub::is_valid( n321 ));\n  BOOST_CHECK (  ub::is_valid( n213 ));\n  BOOST_CHECK (  ub::is_valid( n432 ));\n}\n\n\nBOOST_FIXTURE_TEST_CASE(test_extents_static_rank_is_valid,\n                        fixture_extents_static_rank,\n                        *boost::unit_test::label(\"extents_static_rank\")\n                          *boost::unit_test::label(\"is_valid\"))\n{\n\n  namespace ub = boost::numeric::ublas;\n  BOOST_CHECK (  ub::is_valid( n    ));\n  BOOST_CHECK (  ub::is_valid( n1   ));\n  BOOST_CHECK (  ub::is_valid( n2   ));\n  BOOST_CHECK (  ub::is_valid( n11  ));\n  BOOST_CHECK (  ub::is_valid( n12  ));\n  BOOST_CHECK (  ub::is_valid( n21  ));\n  BOOST_CHECK (  ub::is_valid( n22  ));\n  BOOST_CHECK (  ub::is_valid( n32  ));\n  BOOST_CHECK (  ub::is_valid( n111 ));\n  BOOST_CHECK (  ub::is_valid( n211 ));\n  BOOST_CHECK (  ub::is_valid( n121 ));\n  BOOST_CHECK (  ub::is_valid( n112 ));\n  BOOST_CHECK (  ub::is_valid( n123 ));\n  BOOST_CHECK (  ub::is_valid( n321 ));\n  BOOST_CHECK (  ub::is_valid( n213 ));\n  BOOST_CHECK (  ub::is_valid( n432 ));\n}\n\n\nBOOST_FIXTURE_TEST_CASE(test_extents_static_is_valid,\n                        fixture_extents_static,\n                        *boost::unit_test::label(\"extents_static\")\n                          *boost::unit_test::label(\"is_valid\"))\n{\n\n  namespace ub = boost::numeric::ublas;\n  BOOST_CHECK (  ub::is_valid( n    ));\n//FIXME:  BOOST_CHECK (  ub::is_valid( n1   ));\n//FIXME:  BOOST_CHECK (  ub::is_valid( n2   ));\n  BOOST_CHECK (  ub::is_valid( n11  ));\n  BOOST_CHECK (  ub::is_valid( n12  ));\n  BOOST_CHECK (  ub::is_valid( n21  ));\n  BOOST_CHECK (  ub::is_valid( n22  ));\n  BOOST_CHECK (  ub::is_valid( n32  ));\n  BOOST_CHECK (  ub::is_valid( n111 ));\n  BOOST_CHECK (  ub::is_valid( n211 ));\n  BOOST_CHECK (  ub::is_valid( n121 ));\n  BOOST_CHECK (  ub::is_valid( n112 ));\n  BOOST_CHECK (  ub::is_valid( n123 ));\n  BOOST_CHECK (  ub::is_valid( n321 ));\n  BOOST_CHECK (  ub::is_valid( n213 ));\n  BOOST_CHECK (  ub::is_valid( n432 ));\n}\n\n\nBOOST_FIXTURE_TEST_CASE(test_extents_dynamic_rank_product,\n                        fixture_extents_dynamic_rank,\n                        *boost::unit_test::label(\"extents_dynamic_rank\")\n                          *boost::unit_test::label(\"product\"))\n{\n\n  namespace ub = boost::numeric::ublas;\n  BOOST_CHECK_EQUAL ( ub::product( n    ), 0U);\n  BOOST_CHECK_EQUAL ( ub::product( n1   ), 1U);\n  BOOST_CHECK_EQUAL ( ub::product( n2   ), 2U);\n  BOOST_CHECK_EQUAL ( ub::product( n11  ), 1U);\n  BOOST_CHECK_EQUAL ( ub::product( n12  ), 2U);\n  BOOST_CHECK_EQUAL ( ub::product( n21  ), 2U);\n  BOOST_CHECK_EQUAL ( ub::product( n22  ), 4U);\n  BOOST_CHECK_EQUAL ( ub::product( n32  ), 6U);\n  BOOST_CHECK_EQUAL ( ub::product( n111 ), 1U);\n  BOOST_CHECK_EQUAL ( ub::product( n211 ), 2U);\n  BOOST_CHECK_EQUAL ( ub::product( n121 ), 2U);\n  BOOST_CHECK_EQUAL ( ub::product( n112 ), 2U);\n  BOOST_CHECK_EQUAL ( ub::product( n123 ), 6U);\n  BOOST_CHECK_EQUAL ( ub::product( n321 ), 6U);\n  BOOST_CHECK_EQUAL ( ub::product( n213 ), 6U);\n  BOOST_CHECK_EQUAL ( ub::product( n432 ),24U);\n}\n\n\nBOOST_FIXTURE_TEST_CASE(test_extents_static_rank_product,\n                        fixture_extents_static_rank,\n                        *boost::unit_test::label(\"extents_static_rank\")\n                          *boost::unit_test::label(\"product\"))\n{\n\n  namespace ub = boost::numeric::ublas;\n  BOOST_CHECK_EQUAL ( ub::product( n    ), 0U);\n  BOOST_CHECK_EQUAL ( ub::product( n1   ), 1U);\n  BOOST_CHECK_EQUAL ( ub::product( n2   ), 2U);\n  BOOST_CHECK_EQUAL ( ub::product( n11  ), 1U);\n  BOOST_CHECK_EQUAL ( ub::product( n12  ), 2U);\n  BOOST_CHECK_EQUAL ( ub::product( n21  ), 2U);\n  BOOST_CHECK_EQUAL ( ub::product( n22  ), 4U);\n  BOOST_CHECK_EQUAL ( ub::product( n32  ), 6U);\n  BOOST_CHECK_EQUAL ( ub::product( n111 ), 1U);\n  BOOST_CHECK_EQUAL ( ub::product( n211 ), 2U);\n  BOOST_CHECK_EQUAL ( ub::product( n121 ), 2U);\n  BOOST_CHECK_EQUAL ( ub::product( n112 ), 2U);\n  BOOST_CHECK_EQUAL ( ub::product( n123 ), 6U);\n  BOOST_CHECK_EQUAL ( ub::product( n321 ), 6U);\n  BOOST_CHECK_EQUAL ( ub::product( n213 ), 6U);\n  BOOST_CHECK_EQUAL ( ub::product( n432 ),24U);\n}\n\n\nBOOST_FIXTURE_TEST_CASE(test_extents_static_product,\n                        fixture_extents_static,\n                        *boost::unit_test::label(\"extents_static\")\n                          *boost::unit_test::label(\"product\"))\n{\n\n  namespace ub = boost::numeric::ublas;\n  BOOST_CHECK_EQUAL ( ub::product( n    ), 0U);\n//FIXME:  BOOST_CHECK_EQUAL ( ub::product( n1   ), 1U);\n//FIXME:  BOOST_CHECK_EQUAL ( ub::product( n2   ), 2U);\n  BOOST_CHECK_EQUAL ( ub::product( n11  ), 1U);\n  BOOST_CHECK_EQUAL ( ub::product( n12  ), 2U);\n  BOOST_CHECK_EQUAL ( ub::product( n21  ), 2U);\n  BOOST_CHECK_EQUAL ( ub::product( n22  ), 4U);\n  BOOST_CHECK_EQUAL ( ub::product( n32  ), 6U);\n  BOOST_CHECK_EQUAL ( ub::product( n111 ), 1U);\n  BOOST_CHECK_EQUAL ( ub::product( n211 ), 2U);\n  BOOST_CHECK_EQUAL ( ub::product( n121 ), 2U);\n  BOOST_CHECK_EQUAL ( ub::product( n112 ), 2U);\n  BOOST_CHECK_EQUAL ( ub::product( n123 ), 6U);\n  BOOST_CHECK_EQUAL ( ub::product( n321 ), 6U);\n  BOOST_CHECK_EQUAL ( ub::product( n213 ), 6U);\n  BOOST_CHECK_EQUAL ( ub::product( n432 ),24U);\n}\n\n\nBOOST_FIXTURE_TEST_CASE(test_extents_dynamic_rank_equal,\n                        fixture_extents_dynamic_rank,\n                        *boost::unit_test::label(\"extents_dynamic_rank\")\n                          *boost::unit_test::label(\"equal\"))\n{\n  BOOST_CHECK (  n   == n   );\n  BOOST_CHECK (  n1  == n1  );\n  BOOST_CHECK (  n2  == n2  );\n  BOOST_CHECK (  n11 == n11 );\n  BOOST_CHECK (  n12 == n12 );\n  BOOST_CHECK (  n21 == n21 );\n  BOOST_CHECK (  n22 == n22 );\n  BOOST_CHECK (  n32 == n32 );\n}\n\n\nBOOST_FIXTURE_TEST_CASE(test_extents_static_rank_equal,\n                        fixture_extents_static_rank,\n                        *boost::unit_test::label(\"extents_static_rank\")\n                          *boost::unit_test::label(\"equal\"))\n{\n  BOOST_CHECK (  n   == n   );\n  BOOST_CHECK (  n1  == n1  );\n  BOOST_CHECK (  n2  == n2  );\n  BOOST_CHECK (  n11 == n11 );\n  BOOST_CHECK (  n12 == n12 );\n  BOOST_CHECK (  n21 == n21 );\n  BOOST_CHECK (  n22 == n22 );\n  BOOST_CHECK (  n32 == n32 );\n}\n\n\nBOOST_FIXTURE_TEST_CASE(test_extents_static_equal,\n                        fixture_extents_static,\n                        *boost::unit_test::label(\"extents_static\")\n                          *boost::unit_test::label(\"equal\"))\n{\n  BOOST_CHECK (  n   == n   );\n  BOOST_CHECK (  n1  == n1  );\n  BOOST_CHECK (  n2  == n2  );\n  BOOST_CHECK (  n11 == n11 );\n  BOOST_CHECK (  n12 == n12 );\n  BOOST_CHECK (  n21 == n21 );\n  BOOST_CHECK (  n22 == n22 );\n  BOOST_CHECK (  n32 == n32 );\n}\n\n\nBOOST_FIXTURE_TEST_CASE(test_extents_dynamic_rank_not_equal,\n                        fixture_extents_dynamic_rank,\n                        *boost::unit_test::label(\"extents_dynamic_rank\")\n                          *boost::unit_test::label(\"not_equal\"))\n{\n  BOOST_CHECK (  ! (n   != n )  );\n  BOOST_CHECK (  ! (n1  != n1)  );\n  BOOST_CHECK (  ! (n2  != n2)  );\n  BOOST_CHECK (  ! (n11 != n11) );\n  BOOST_CHECK (  ! (n12 != n12) );\n  BOOST_CHECK (  ! (n21 != n21) );\n  BOOST_CHECK (  ! (n22 != n22) );\n  BOOST_CHECK (  ! (n32 != n32) );\n  BOOST_CHECK (   (n2  != n1)  );\n  BOOST_CHECK (   (n11 != n12) );\n  BOOST_CHECK (   (n12 != n21) );\n  BOOST_CHECK (   (n21 != n22) );\n  BOOST_CHECK (   (n22 != n32) );\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "868afd26e6837b3b94a5f23e251cc4e85f181c82", "size": 23249, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/tensor/test_extents_functions.cpp", "max_stars_repo_name": "samd2/ublas", "max_stars_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 96.0, "max_stars_repo_stars_event_min_datetime": "2015-01-23T10:15:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T18:31:02.000Z", "max_issues_repo_path": "test/tensor/test_extents_functions.cpp", "max_issues_repo_name": "samd2/ublas", "max_issues_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 105.0, "max_issues_repo_issues_event_min_datetime": "2015-01-14T09:01:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-05T06:10:39.000Z", "max_forks_repo_path": "test/tensor/test_extents_functions.cpp", "max_forks_repo_name": "samd2/ublas", "max_forks_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 157.0, "max_forks_repo_forks_event_min_datetime": "2015-01-26T13:35:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T11:12:27.000Z", "avg_line_length": 36.6125984252, "max_line_length": 126, "alphanum_fraction": 0.6182631511, "num_tokens": 6806, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.6992544085240401, "lm_q1q2_score": 0.4701309046415745}}
{"text": "#define BOOST_TEST_MODULE \"test_static_matrix\"\n\n#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST\n#include <boost/test/unit_test.hpp>\n#else\n#define BOOST_TEST_NO_LIB\n#include <boost/test/included/unit_test.hpp>\n#endif\n\n#include \"../src/Matrix.hpp\"\ntemplate<std::size_t N, std::size_t M>\nusing MatrixNMd = ax::Matrix<double, N, M>;\n\n#include \"test_Defs.hpp\"\nusing ax::test::tolerance;\nusing ax::test::seed;\nusing ax::test::Dim_N;\nusing ax::test::Dim_M;\n\n#include <random>\n\nBOOST_AUTO_TEST_CASE(MatrixNd_Ctor)\n{\n    const MatrixNMd<Dim_N, Dim_M> mat;\n\n    for(std::size_t i=0; i<Dim_N; ++i)\n        for(std::size_t j=0; j<Dim_M; ++j)\n            BOOST_CHECK_EQUAL(mat(i,j), 0e0);\n\n    const MatrixNMd<Dim_N, Dim_M> mat1(1e0);\n\n    for(std::size_t i=0; i<Dim_N; ++i)\n        for(std::size_t j=0; j<Dim_M; ++j)\n            if(i == j)\n                BOOST_CHECK_EQUAL(mat1(i,j), 1e0);\n            else\n                BOOST_CHECK_EQUAL(mat1(i,j), 0e0);\n\n\n    const MatrixNMd<Dim_N, Dim_M> mat2(mat1);\n\n    for(std::size_t i=0; i<Dim_N; ++i)\n        for(std::size_t j=0; j<Dim_M; ++j)\n            if(i == j)\n                BOOST_CHECK_EQUAL(mat2(i,j), 1e0);\n            else\n                BOOST_CHECK_EQUAL(mat2(i,j), 0e0);\n\n    MatrixNMd<Dim_N, Dim_M> mat3;\n    mat3 = mat1;\n\n    for(std::size_t i=0; i<Dim_N; ++i)\n        for(std::size_t j=0; j<Dim_M; ++j)\n            if(i == j)\n                BOOST_CHECK_EQUAL(mat3(i,j), 1e0);\n            else\n                BOOST_CHECK_EQUAL(mat3(i,j), 0e0);\n}\n\nBOOST_AUTO_TEST_CASE(MatrixNd_Add)\n{\n    const MatrixNMd<Dim_N, Dim_M> mat1(1e0);\n    const MatrixNMd<Dim_N, Dim_M> mat2(2e0);\n    const MatrixNMd<Dim_N, Dim_M> mat3(mat1 + mat2);\n\n    for(std::size_t i=0; i<Dim_N; ++i)\n        for(std::size_t j=0; j<Dim_M; ++j)\n            if(i == j)\n                BOOST_CHECK_EQUAL(mat3(i,j), 3e0);\n            else\n                BOOST_CHECK_EQUAL(mat3(i,j), 0e0);\n\n    const MatrixNMd<Dim_N, Dim_M> mat4 = mat1 + mat2;\n\n    for(std::size_t i=0; i<Dim_N; ++i)\n        for(std::size_t j=0; j<Dim_M; ++j)\n            if(i == j)\n                BOOST_CHECK_EQUAL(mat4(i,j), 3e0);\n            else\n                BOOST_CHECK_EQUAL(mat4(i,j), 0e0);\n\n    MatrixNMd<Dim_N, Dim_M> mat5;\n    mat5 = mat1 + mat2;\n\n    for(std::size_t i=0; i<Dim_N; ++i)\n        for(std::size_t j=0; j<Dim_M; ++j)\n            if(i == j)\n                BOOST_CHECK_EQUAL(mat5(i,j), 3e0);\n            else\n                BOOST_CHECK_EQUAL(mat5(i,j), 0e0);\n\n    MatrixNMd<Dim_N, Dim_M> mat6;\n    mat6 += mat1;\n    mat6 += mat2;\n\n    for(std::size_t i=0; i<Dim_N; ++i)\n        for(std::size_t j=0; j<Dim_M; ++j)\n            if(i == j)\n                BOOST_CHECK_EQUAL(mat6(i,j), 3e0);\n            else\n                BOOST_CHECK_EQUAL(mat6(i,j), 0e0);\n\n\n    // ~~~~~~~~~~~~~~~~ random ~~~~~~~~~~~~~~~~\n\n    std::mt19937 mt(seed);\n    std::uniform_real_distribution<double> randreal(0e0, 1e0);\n\n    std::array<std::array<double, Dim_M>, Dim_N> rand1;\n    for(std::size_t i=0; i<Dim_N; ++i)\n        for(std::size_t j=0; j<Dim_M; ++j)\n            rand1[i][j] = randreal(mt);\n\n    std::array<std::array<double, Dim_M>, Dim_N> rand2;\n    for(std::size_t i=0; i<Dim_N; ++i)\n        for(std::size_t j=0; j<Dim_M; ++j)\n            rand2[i][j] = randreal(mt);\n\n    MatrixNMd<Dim_N, Dim_M> mat7;\n    for(std::size_t i=0; i<Dim_N; ++i)\n        for(std::size_t j=0; j<Dim_M; ++j)\n            mat7(i, j) = rand1[i][j];\n\n    MatrixNMd<Dim_N, Dim_M> mat8;\n    for(std::size_t i=0; i<Dim_N; ++i)\n        for(std::size_t j=0; j<Dim_M; ++j)\n            mat8(i, j) = rand2[i][j];\n\n\n    const MatrixNMd<Dim_N, Dim_M> mat9 = mat7 + mat8;\n    for(std::size_t i=0; i<Dim_N; ++i)\n        for(std::size_t j=0; j<Dim_M; ++j)\n            BOOST_CHECK_EQUAL(mat9(i,j), rand1[i][j] + rand2[i][j]);\n\n    const MatrixNMd<Dim_N, Dim_M> mat10 = mat7 + mat7 + mat7 + mat7 + mat7;\n    for(std::size_t i=0; i<Dim_N; ++i)\n        for(std::size_t j=0; j<Dim_M; ++j)\n            BOOST_CHECK_CLOSE(mat10(i,j), rand1[i][j] * 5, tolerance);\n}\n\nBOOST_AUTO_TEST_CASE(MatrixNd_Sub)\n{\n    const MatrixNMd<Dim_N, Dim_M> mat1(3e0);\n    const MatrixNMd<Dim_N, Dim_M> mat2(1e0);\n    const MatrixNMd<Dim_N, Dim_M> mat3(mat1 - mat2);\n\n    for(std::size_t i=0; i<Dim_N; ++i)\n        for(std::size_t j=0; j<Dim_M; ++j)\n            if(i == j)\n                BOOST_CHECK_EQUAL(mat3(i,j), 2e0);\n            else\n                BOOST_CHECK_EQUAL(mat3(i,j), 0e0);\n\n    const MatrixNMd<Dim_N, Dim_M> mat4 = mat1 - mat2;\n\n    for(std::size_t i=0; i<Dim_N; ++i)\n        for(std::size_t j=0; j<Dim_M; ++j)\n            if(i == j)\n                BOOST_CHECK_EQUAL(mat4(i,j), 2e0);\n            else\n                BOOST_CHECK_EQUAL(mat4(i,j), 0e0);\n\n    MatrixNMd<Dim_N, Dim_M> mat5;\n    mat5 = mat1 - mat2;\n\n    for(std::size_t i=0; i<Dim_N; ++i)\n        for(std::size_t j=0; j<Dim_M; ++j)\n            if(i == j)\n                BOOST_CHECK_EQUAL(mat5(i,j), 2e0);\n            else\n                BOOST_CHECK_EQUAL(mat5(i,j), 0e0);\n\n    MatrixNMd<Dim_N, Dim_M> mat6(mat1);\n    mat6 -= mat2;\n\n    for(std::size_t i=0; i<Dim_N; ++i)\n        for(std::size_t j=0; j<Dim_M; ++j)\n            if(i == j)\n                BOOST_CHECK_EQUAL(mat6(i,j), 2e0);\n            else\n                BOOST_CHECK_EQUAL(mat6(i,j), 0e0);\n\n    // ~~~~~~~~~~~~~~~~ random ~~~~~~~~~~~~~~~~\n\n    std::mt19937 mt(seed);\n    std::uniform_real_distribution<double> randreal(0e0, 1e0);\n\n    std::array<std::array<double, Dim_M>, Dim_N> rand1;\n    for(std::size_t i=0; i<Dim_N; ++i)\n        for(std::size_t j=0; j<Dim_M; ++j)\n            rand1[i][j] = randreal(mt);\n\n    std::array<std::array<double, Dim_M>, Dim_N> rand2;\n    for(std::size_t i=0; i<Dim_N; ++i)\n        for(std::size_t j=0; j<Dim_M; ++j)\n            rand2[i][j] = randreal(mt);\n\n    MatrixNMd<Dim_N, Dim_M> mat7;\n    for(std::size_t i=0; i<Dim_N; ++i)\n        for(std::size_t j=0; j<Dim_M; ++j)\n            mat7(i, j) = rand1[i][j];\n\n    MatrixNMd<Dim_N, Dim_M> mat8;\n    for(std::size_t i=0; i<Dim_N; ++i)\n        for(std::size_t j=0; j<Dim_M; ++j)\n            mat8(i, j) = rand2[i][j];\n\n\n    const MatrixNMd<Dim_N, Dim_M> mat9 = mat7 - mat8;\n    for(std::size_t i=0; i<Dim_N; ++i)\n        for(std::size_t j=0; j<Dim_M; ++j)\n            BOOST_CHECK_EQUAL(mat9(i,j), rand1[i][j] - rand2[i][j]);\n\n    const MatrixNMd<Dim_N, Dim_M> zero;\n    const MatrixNMd<Dim_N, Dim_M> mat10 =\n        zero - mat7 - mat7 - mat7 - mat7 - mat7;\n    for(std::size_t i=0; i<Dim_N; ++i)\n        for(std::size_t j=0; j<Dim_M; ++j)\n            BOOST_CHECK_CLOSE(mat10(i,j), rand1[i][j] * (-5e0), tolerance);\n}\n\nBOOST_AUTO_TEST_CASE(MatrixNd_Scalar_Maltiple)\n{\n    std::mt19937 mt(seed);\n    std::uniform_real_distribution<double> randreal(0e0, 1e0);\n\n    std::array<std::array<double, Dim_M>, Dim_N> rand1;\n    for(std::size_t i=0; i<Dim_N; ++i)\n        for(std::size_t j=0; j<Dim_M; ++j)\n            rand1[i][j] = randreal(mt);\n\n    MatrixNMd<Dim_N, Dim_M> mat1;\n    for(std::size_t i=0; i<Dim_N; ++i)\n        for(std::size_t j=0; j<Dim_M; ++j)\n            mat1(i, j) = rand1[i][j];\n\n    const MatrixNMd<Dim_N, Dim_M> mat2(mat1 * 2e0);\n    for(std::size_t i=0; i<Dim_N; ++i)\n        for(std::size_t j=0; j<Dim_M; ++j)\n            BOOST_CHECK_EQUAL(mat2(i,j), rand1[i][j] * 2e0);\n\n    const MatrixNMd<Dim_N, Dim_M> mat3 = mat1 * 2e0;\n    for(std::size_t i=0; i<Dim_N; ++i)\n        for(std::size_t j=0; j<Dim_M; ++j)\n            BOOST_CHECK_EQUAL(mat3(i,j), rand1[i][j] * 2e0);\n\n    const MatrixNMd<Dim_N, Dim_M> mat4(2e0 * mat1);\n    for(std::size_t i=0; i<Dim_N; ++i)\n        for(std::size_t j=0; j<Dim_M; ++j)\n            BOOST_CHECK_EQUAL(mat4(i,j), rand1[i][j] * 2e0);\n\n    const MatrixNMd<Dim_N, Dim_M> mat5 = 2e0 * mat1;\n    for(std::size_t i=0; i<Dim_N; ++i)\n        for(std::size_t j=0; j<Dim_M; ++j)\n            BOOST_CHECK_EQUAL(mat5(i,j), rand1[i][j] * 2e0);\n\n    MatrixNMd<Dim_N, Dim_M> mat6;\n    mat6 = mat1 * 2e0;\n    for(std::size_t i=0; i<Dim_N; ++i)\n        for(std::size_t j=0; j<Dim_M; ++j)\n            BOOST_CHECK_EQUAL(mat6(i,j), rand1[i][j] * 2e0);\n\n    mat6 = 2e0 * mat1;\n    for(std::size_t i=0; i<Dim_N; ++i)\n        for(std::size_t j=0; j<Dim_M; ++j)\n            BOOST_CHECK_EQUAL(mat6(i,j), rand1[i][j] * 2e0);\n\n    MatrixNMd<Dim_N, Dim_M> mat7(mat1);\n    mat7 *= 2e0;\n    for(std::size_t i=0; i<Dim_N; ++i)\n        for(std::size_t j=0; j<Dim_M; ++j)\n            BOOST_CHECK_EQUAL(mat7(i,j), rand1[i][j] * 2e0);\n}\n\nBOOST_AUTO_TEST_CASE(MatrixNd_Scalar_Division)\n{\n    std::mt19937 mt(seed);\n    std::uniform_real_distribution<double> randreal(0e0, 1e0);\n\n    std::array<std::array<double, Dim_M>, Dim_N> rand1;\n    for(std::size_t i=0; i<Dim_N; ++i)\n        for(std::size_t j=0; j<Dim_M; ++j)\n            rand1[i][j] = randreal(mt);\n\n    MatrixNMd<Dim_N, Dim_M> mat1;\n    for(std::size_t i=0; i<Dim_N; ++i)\n        for(std::size_t j=0; j<Dim_M; ++j)\n            mat1(i, j) = rand1[i][j];\n\n    const MatrixNMd<Dim_N, Dim_M> mat2(mat1 / 2e0);\n    for(std::size_t i=0; i<Dim_N; ++i)\n        for(std::size_t j=0; j<Dim_M; ++j)\n            BOOST_CHECK_EQUAL(mat2(i,j), rand1[i][j] / 2e0);\n\n    const MatrixNMd<Dim_N, Dim_M> mat3 = mat1 / 2e0;\n    for(std::size_t i=0; i<Dim_N; ++i)\n        for(std::size_t j=0; j<Dim_M; ++j)\n            BOOST_CHECK_EQUAL(mat3(i,j), rand1[i][j] / 2e0);\n\n    MatrixNMd<Dim_N, Dim_M> mat4;\n    mat4 = mat1 / 2e0;\n    for(std::size_t i=0; i<Dim_N; ++i)\n        for(std::size_t j=0; j<Dim_M; ++j)\n            BOOST_CHECK_EQUAL(mat4(i,j), rand1[i][j] / 2e0);\n\n    MatrixNMd<Dim_N, Dim_M> mat5(mat1);\n    mat5 /= 2e0;\n    for(std::size_t i=0; i<Dim_N; ++i)\n        for(std::size_t j=0; j<Dim_M; ++j)\n            BOOST_CHECK_EQUAL(mat5(i,j), rand1[i][j] / 2e0);\n}\n\nBOOST_AUTO_TEST_CASE(MatrixNd_Multiple)\n{\n    std::mt19937 mt(seed);\n    std::uniform_real_distribution<double> randreal(0e0, 1e0);\n\n    std::array<std::array<double, Dim_M>, Dim_N> rand1;\n    for(std::size_t i=0; i<Dim_N; ++i)\n        for(std::size_t j=0; j<Dim_M; ++j)\n            rand1[i][j] = randreal(mt);\n\n    std::array<std::array<double, Dim_N>, Dim_M> rand2;\n    for(std::size_t i=0; i<Dim_M; ++i)\n        for(std::size_t j=0; j<Dim_N; ++j)\n            rand2[i][j] = randreal(mt);\n\n    MatrixNMd<Dim_N, Dim_M> mat1;\n    for(std::size_t i=0; i<Dim_N; ++i)\n        for(std::size_t j=0; j<Dim_M; ++j)\n            mat1(i, j) = rand1[i][j];\n\n    MatrixNMd<Dim_M, Dim_N> mat2;\n    for(std::size_t i=0; i<Dim_M; ++i)\n        for(std::size_t j=0; j<Dim_N; ++j)\n            mat2(i, j) = rand2[i][j];\n\n    const MatrixNMd<Dim_N, Dim_N> mat3 = mat1 * mat2;\n    for(std::size_t i=0; i<Dim_N; ++i)\n        for(std::size_t j=0; j<Dim_N; ++j)\n        {\n            double value = 0e0;\n            for(std::size_t k=0; k<Dim_M; ++k)\n                value += rand1[i][k] * rand2[k][j];\n\n            BOOST_CHECK_EQUAL(mat3(i,j), value);\n        }\n\n    const MatrixNMd<Dim_M, Dim_M> mat4 = mat2 * mat1;\n    for(std::size_t i=0; i<Dim_M; ++i)\n        for(std::size_t j=0; j<Dim_M; ++j)\n        {\n            double value = 0e0;\n            for(std::size_t k=0; k<Dim_N; ++k)\n                value += rand2[i][k] * rand1[k][j];\n\n            BOOST_CHECK_EQUAL(mat4(i,j), value);\n        }\n}\n\nBOOST_AUTO_TEST_CASE(MatrixNd_transpose)\n{\n    std::mt19937 mt(seed);\n    std::uniform_real_distribution<double> randreal(0e0, 1e0);\n\n    std::array<std::array<double, Dim_M>, Dim_N> rand1;\n    for(std::size_t i=0; i<Dim_N; ++i)\n        for(std::size_t j=0; j<Dim_M; ++j)\n            rand1[i][j] = randreal(mt);\n\n    MatrixNMd<Dim_N, Dim_M> mat1;\n    for(std::size_t i=0; i<Dim_N; ++i)\n        for(std::size_t j=0; j<Dim_M; ++j)\n            mat1(i, j) = rand1[i][j];\n\n    const MatrixNMd<Dim_M, Dim_N> mat2 = transpose(mat1);\n    for(std::size_t i=0; i<Dim_N; ++i)\n        for(std::size_t j=0; j<Dim_M; ++j)\n            BOOST_CHECK_EQUAL(mat2(j, i), rand1[i][j]);\n}\n", "meta": {"hexsha": "6780cce896cfeeb8cc5c540217b4924f41bce903", "size": 11814, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_static_matrix.cpp", "max_stars_repo_name": "ToruNiina/AX", "max_stars_repo_head_hexsha": "c99ddaa683dc94c7ec856a7cf1e10c0a6189951a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-01-16T13:56:31.000Z", "max_stars_repo_stars_event_max_datetime": "2017-01-16T13:56:31.000Z", "max_issues_repo_path": "test/test_static_matrix.cpp", "max_issues_repo_name": "ToruNiina/AX", "max_issues_repo_head_hexsha": "c99ddaa683dc94c7ec856a7cf1e10c0a6189951a", "max_issues_repo_licenses": ["MIT"], "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_static_matrix.cpp", "max_forks_repo_name": "ToruNiina/AX", "max_forks_repo_head_hexsha": "c99ddaa683dc94c7ec856a7cf1e10c0a6189951a", "max_forks_repo_licenses": ["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.0078740157, "max_line_length": 75, "alphanum_fraction": 0.5448620281, "num_tokens": 4281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723316860482763, "lm_q2_score": 0.6992544147913993, "lm_q1q2_score": 0.4701308996734022}}
{"text": "#ifndef _FMM2DTree_HPP__\n#define _FMM2DTree_HPP__\ndouble kappa;\n#include <fstream>\n#include <sstream>\n#include <string>\n#include <omp.h>\n#include <cmath>\n#include <iostream>\n#include <sys/stat.h>\n#include <sys/types.h>\n#include <stdlib.h>\n#include <chrono>\n#include <boost/math/special_functions/bessel.hpp>\n#include <filesystem>\n\n#include \"singularNodes_v2.hpp\"\npts2D SFN_centers[20] = {{-2.5, -2.5},//separatedFineNeighbors\n\t\t\t\t\t\t\t\t\t\t\t\t{-1.5, -2.5},\n\t\t\t\t\t\t\t\t\t\t\t\t{-0.5, -2.5},\n\t\t\t\t\t\t\t\t\t\t\t\t{0.5, -2.5},\n\t\t\t\t\t\t\t\t\t\t\t\t{1.5, -2.5},\n\t\t\t\t\t\t\t\t\t\t\t\t{2.5, -2.5},\n\t\t\t\t\t\t\t\t\t\t\t\t{2.5, -1.5},\n\t\t\t\t\t\t\t\t\t\t\t\t{2.5, -0.5},\n\t\t\t\t\t\t\t\t\t\t\t\t{2.5, 0.5},\n\t\t\t\t\t\t\t\t\t\t\t\t{2.5, 1.5},\n\t\t\t\t\t\t\t\t\t\t\t\t{2.5, 2.5},\n\t\t\t\t\t\t\t\t\t\t\t\t{1.5, 2.5},\n\t\t\t\t\t\t\t\t\t\t\t\t{0.5, 2.5},\n\t\t\t\t\t\t\t\t\t\t\t\t{-0.5, 2.5},\n\t\t\t\t\t\t\t\t\t\t\t\t{-1.5, 2.5},\n\t\t\t\t\t\t\t\t\t\t\t\t{-2.5, 2.5},\n\t\t\t\t\t\t\t\t\t\t\t\t{-2.5, 1.5},\n\t\t\t\t\t\t\t\t\t\t\t\t{-2.5, 0.5},\n\t\t\t\t\t\t\t\t\t\t\t\t{-2.5, -0.5},\n\t\t\t\t\t\t\t\t\t\t\t\t{-2.5, -1.5}\n\t\t\t\t\t\t\t\t\t\t\t\t};\npts2D N_centers[9] = {{-2, -2},//colleagueNeighbors\n\t\t\t\t\t\t\t\t\t\t\t {0, -2},\n\t\t\t\t\t\t\t\t\t\t\t {2, -2},\n\t\t\t\t\t\t\t\t\t\t\t {2, 0},\n\t\t\t\t\t\t\t\t\t\t\t {2, 2},\n\t\t\t\t\t\t\t\t\t\t\t {0, 2},\n\t\t\t\t\t\t\t\t\t\t\t {-2, 2},\n\t\t\t\t\t\t\t\t\t\t\t {-2, 0},\n\t\t\t\t\t\t\t\t\t\t\t {0, 0}};\npts2D FN_centers[12] = {{-1.5, -1.5},//fineNeighbors\n\t\t\t\t\t\t\t\t\t\t\t\t {-0.5, -1.5},\n\t\t\t\t\t\t\t\t\t\t\t\t {0.5, -1.5},\n\t\t\t\t\t\t\t\t\t\t\t\t {1.5, -1.5},\n\t\t\t\t\t\t\t\t\t\t\t\t {1.5, -0.5},\n\t\t\t\t\t\t\t\t\t\t\t\t {1.5, 0.5},\n\t\t\t\t\t\t\t\t\t\t\t\t {1.5, 1.5},\n\t\t\t\t\t\t\t\t\t\t\t\t {0.5, 1.5},\n\t\t\t\t\t\t\t\t\t\t\t\t {-0.5, 1.5},\n\t\t\t\t\t\t\t\t\t\t\t\t {-1.5, 1.5},\n\t\t\t\t\t\t\t\t\t\t\t\t {-1.5, 0.5},\n\t\t\t\t\t\t\t\t\t\t\t\t {-1.5, -0.5}};\npts2D CN_centers[12] = {{-3, -3},//coarseNeighbors\n\t\t\t\t\t\t\t\t\t\t\t\t{-1, -3},\n\t\t\t\t\t\t\t\t\t\t\t\t{1, -3},\n\t\t\t\t\t\t\t\t\t\t\t\t{3, -3},\n\t\t\t\t\t\t\t\t\t\t\t\t{3, -1},\n\t\t\t\t\t\t\t\t\t\t\t\t{3, 1},\n\t\t\t\t\t\t\t\t\t\t\t\t{3, 3},\n\t\t\t\t\t\t\t\t\t\t\t\t{1, 3},\n\t\t\t\t\t\t\t\t\t\t\t\t{-1, 3},\n\t\t\t\t\t\t\t\t\t\t\t\t{-3, 3},\n\t\t\t\t\t\t\t\t\t\t\t\t{-3, 1},\n\t\t\t\t\t\t\t\t\t\t\t\t{-3, -1}};\ndouble besselJ(int n, double x) {\n\t//cout << \"n: \" << n << \"\tx: \" << x << endl;\n\tif (n >= 0) {\n\t\tdouble temp = boost::math::cyl_bessel_j(double(n), x);\n\t\treturn temp;\n\t}\n\telse {\n\t\tdouble temp = boost::math::cyl_bessel_j(double(-n), x);\n\t\tif (-n%2 == 0)\n\t\t\treturn temp;\n\t\telse\n\t\t\treturn -temp;\n\t}\n}\n\ndouble besselY(int n, double x) {\n\tif (n >= 0) {\n\t\tdouble temp = boost::math::cyl_neumann(double(n), x);\n\t\treturn temp;\n\t}\n\telse {\n\t\tdouble temp = boost::math::cyl_neumann(double(-n), x);\n\t\tif (-n%2 == 0)\n\t\t\treturn temp;\n\t\telse\n\t\t\treturn -temp;\n\t}\n}\n\ndouble arctan(double y, double x) {//returns atan2 in range (0,2*PI)\n\tdouble temp = atan2(y, x);\n\tif (temp < 0.0)\n\t\treturn temp + 2*PI;\n\telse\n\t\treturn temp;\n}\n\n#include \"domain2D.hpp\"\n#include \"FarFieldInteraction.hpp\"\n#include \"FarFieldInteraction2.hpp\"\n#include \"NearFieldInteraction1.hpp\"\n#include \"NearFieldInteraction2.hpp\"\n\nconst double epsilonRoundOff = pow(10,-8);\nusing namespace std::chrono;\n\nclass FMM2DCone {\npublic:\n\tbool ILActive;\n\t//Directional multipoles and locals of the box in this cone direction\n\tVec multipoles;\n\n\t//defined only in HFR\n\t//std::vector<pts2D> &outgoing_chargePoints;//equivalent points {y_{k}^{B,o,l}}\n\tVec outgoing_charges;//equivalent densities {f_{k}^{B,o,l}}\n\t//std::vector<pts2D> &outgoing_checkPoints;//check points {x_{k}^{B,o,l}}\n\tVec outgoing_potential;//check potentials {u_{k}^{B,o,l}}\n\n\t//outgoing_chargePoints and outgoing_checkPoints are considered to be same as incoming_checkPoints and incoming_chargePoints respectively; hence are not declared\n\t//This is because of the assumption that the potentials are evaluated at the charge locations\n\tstd::vector<int> incoming_chargePoints;//equivalent points {y_{k}^{B,i,l}}\n\tVec incoming_charges;//equivalent densities {f_{k}^{B,i,l}}\n\tstd::vector<int> incoming_checkPoints;//check points {x_{k}^{B,i,l}}\n\tstd::vector<int> outgoing_chargePoints;//equivalent points {y_{k}^{B,i,l}}\n\tstd::vector<int> outgoing_checkPoints;//check points {x_{k}^{B,i,l}}\n\tstd::vector<int> user_checkPoints;\n\tVec incoming_potential;//check potentials {u_{k}^{B,i,l}}\n\n\tColPivHouseholderQR<Mat> outgoing_Atilde_dec;\n\tColPivHouseholderQR<Mat> incoming_Atilde_dec;\n\n\tstd::vector<orderedPair > InteractionList;\n\tdouble angle;\n\tMat outgoing_Ar;\n\tMat L2L[4], M2M, Ktilde;\n\tstd::vector<Mat> M2L;\n\tFMM2DCone () {}\n\n};\n\nclass FMM2DBox {\npublic:\n\tdouble radius;\n\tint active;\n\tbool ILActive;\n\tint level;\n\tint boxNumber;\n\tint parentNumber;\n\tint childrenNumbers[4];\n\tbool isLeaf;\n\n\tstd::vector<orderedPair > neighborNumbers;\n\n\tint fineNeighbors[12];//12\n\tint coarseNeighbors[12];//12\n\tint separatedFineNeighbors[20];//20\n\tint colleagueNeighbors[9];//9\n\n\tstd::vector<orderedPair > InteractionList;\n\tstd::vector<int > MFR_IL;\n\t//defined only in LFR\n\t//std::vector<pts2D> &outgoing_chargePoints;//equivalent points {y_{k}^{B,o}}\n\tVec outgoing_charges;//equivalent densities {f_{k}^{B,o}}\n\t//std::vector<pts2D> &outgoing_checkPoints;//check points {x_{k}^{B,o}}\n\tVec outgoing_potential;//check potentials {u_{k}^{B,o}}\n\n\t//outgoing_chargePoints and outgoing_checkPoints are considered to be same as incoming_checkPoints and incoming_chargePoints respectively; hence are not declared\n\t//This is because of the assumption that the potentials are evaluated at the charge locations\n\tstd::vector<int> incoming_chargePoints;//equivalent points {y_{k}^{B,i}}\n\tVec incoming_charges;//equivalent densities {f_{k}^{B,i}}\n\tstd::vector<int> incoming_checkPoints;//check points {x_{k}^{B,i}}\n\tstd::vector<int> user_checkPoints;\n\tstd::vector<int> outgoing_chargePoints;//equivalent points {y_{k}^{B,i,l}}\n\tstd::vector<int> outgoing_checkPoints;//check points {x_{k}^{B,i,l}}\n\tVec incoming_potential;//check potentials {u_{k}^{B,i}}\n\n\tColPivHouseholderQR<Mat> outgoing_Atilde_dec;\n\tColPivHouseholderQR<Mat> incoming_Atilde_dec;\n\n\tMat outgoing_Ar;\n\tMat L2L, Ktilde;\n\tstd::vector<Mat> M2L;\n\n\tFMM2DBox () {\n\t\tboxNumber\t\t=\t-1;\n\t\tparentNumber\t=\t-1;\n\t\tfor (int l=0; l<4; ++l) {\n\t\t\tchildrenNumbers[l]\t=\t-1;\n\t\t}\n\t\tisLeaf = false;\n\t\tactive = true;\n\t\tfor (size_t i = 0; i < 12; i++) {\n\t\t\tfineNeighbors[i] = -1;\n\t\t}\n\t\tfor (size_t i = 0; i < 12; i++) {\n\t\t\tcoarseNeighbors[i] = -1;\n\t\t}\n\t\tfor (size_t i = 0; i < 20; i++) {\n\t\t\tseparatedFineNeighbors[i] = -1;\n\t\t}\n\t\tfor (size_t i = 0; i < 9; i++) {\n\t\t\tcolleagueNeighbors[i] = -1;\n\t\t}\n\t}\n\n\tVec multipoles;\n\n\tpts2D center;\n\tstd::vector<int> chargeLocations;\n\n\tstd::vector<pts2D> chebNodes;\n\tstd::vector<FMM2DCone> ConeTree;\n};\n\ntemplate <typename kerneltype>\nclass FMM2DTree: public LowRank {\npublic:\n\tdouble timeIn_getMatrixEntry;//for time profiling\n\tlong NoIn_getMatrixEntry;\n\tkerneltype* Q;\n\tint nLevels;\t\t\t//\tNumber of levels in the tree.\n\tint nChebNodes;\t\t\t//\tNumber of Chebyshev nodes along one direction.\n\tint rank;\t\t\t\t//\tRank of interaction, i.e., rank = nChebNodes*nChebNodes.\n\tint N;\t\t\t\t\t//\tNumber of particles.\n\tdouble L;\t\t\t\t//\tSemi-length of the simulation box.\n\tdouble smallestBoxSize;\t//\tThis is L/2.0^(nLevels).\n\tdouble a;\t\t\t\t//\tCut-off for self-interaction. This is less than the length of the smallest box size.\n\tconst double A = 3.0; //higher A, higher level_FarField\n\tconst double B = 0.35;//4.0; //smaller B, higher level_LFR\n\tint level_LFR;\n\tint level_FarField;\n\tint nCones_LFR;\n\tdouble epsilonTree;//pow(10,-epsilonTree);\n\tVec chargesAll;\n\tdouble SFN_angles[20];\n\tdouble N_angles[9];\n\tdouble FN_angles[12];\n\tdouble CN_angles[12];\n\n\tbool findPhi;\n\tstring NeighborFilename;\n\tstring MFilename;\n\tstd::vector<pts2D> gridPoints;\n\tstd::vector<int> nBoxesPerLevel;\t\t\t//\tNumber of boxes at each level in the tree.\n\tstd::vector<double> boxRadius;\t\t\t\t//\tBox radius at each level in the tree assuming the box at the root is [-1,1]^2\n\tstd::vector<double> ConeAperture;\n\tstd::vector<int> nCones;\n\tstd::vector<double> boxHomogRadius;\t\t\t//\tStores the value of boxRadius^{alpha}\n\tstd::vector<double> boxLogHomogRadius;\t\t//\tStores the value of alpha*log(boxRadius)\n\tstd::vector<std::vector<FMM2DBox> > tree;\t//\tThe tree storing all the information.\n\tstd::vector<std::vector<int> > indexTree;\n\tint TOL_POW;\n\tint treeAdaptivity;\n\t//\tDifferent Operators\n\tint yes2DFMM;\n\tstd::vector<double> standardChebNodes1D;\n\tstd::vector<pts2D> standardChebNodes;\n\tstd::vector<pts2D> standardChebNodesChild;\n\tstd::vector<pts2D> leafChebNodes;\n\n\tstd::vector<orderedPair> leafNodes;\n\t//\tDifferent Operators\n\tEigen::MatrixXd M2M[4];\t\t\t\t\t//\tTransfer from multipoles of 4 children to multipoles of parent.\n\tEigen::MatrixXd L2L[4];\t\t\t\t\t//\tTransfer from locals of parent to locals of 4 children.\n\tFarFieldInteraction* FF; //object needed to computeFarField interaction of Lippmann Schwinger problem\n\tFarFieldInteraction2* FF2;\n\tstd::vector<Mat > M; //M matrices computed during precomputations\n\tEigen::MatrixXd Q_pinv;\n\tEigen::MatrixXd Q_pinv2;\n\tint degreeOfBases;\n\tMat colleagueNeighborInteraction[9][9];\n\tMat fineNeighborInteraction[9][12];\n\tMat separatedFineNeighborInteraction[9][20];\n\tMat coarseNeighborInteraction[9][12];\n\n// public:\n\tFMM2DTree(kerneltype* Q, int nCones_LFR, int nChebNodes, double L, int yes2DFMM, int TOL_POW, std::vector<pts2D> particles_X, std::vector<pts2D> particles_Y, std::vector<int> row_indices, std::vector<int> col_indices, int degreeOfBases, int treeAdaptivity):\n\tLowRank(TOL_POW, particles_X, particles_Y, row_indices, col_indices) {\n\t\tthis->findPhi = true;\n\t\tthis->NoIn_getMatrixEntry = 0;\n\t\tthis->timeIn_getMatrixEntry = 0.0;\n\t\tthis->degreeOfBases = degreeOfBases;//p minus 1\n\t\tthis->treeAdaptivity = treeAdaptivity;\n\t\tthis->epsilonTree = pow(10,-treeAdaptivity);\n\t\tthis->FF = new FarFieldInteraction(nChebNodes, L, degreeOfBases);\n\t\tthis->FF2 = new FarFieldInteraction2(nChebNodes, L, degreeOfBases);\n\t\tFF2->evaluateQ(Q_pinv2);\n\t\tthis->Q = Q;\n\t\tthis->TOL_POW = TOL_POW;\n\t\tthis->nChebNodes\t\t=\tnChebNodes;\n\t\tthis->rank\t\t\t=\tnChebNodes*nChebNodes;\n\t\tthis->L\t\t\t\t=\tL;\n\t\tthis->nCones_LFR\t\t=\tnCones_LFR;\n\t\tthis->yes2DFMM = yes2DFMM;\n\t\tnBoxesPerLevel.push_back(1);\n\t\tboxRadius.push_back(L);\n\t\tthis->a\t\t\t=\tsmallestBoxSize;\n\t\tint k;\n\t\tif (yes2DFMM == 1) {\n\t\t\tif (kappa==0)\n\t\t\t\tthis->level_LFR\t=\t2;\t//actually should be 2; but for checking the accuracy of DFMM i am making it 3; so that HFR code runs even for LFR; if that gives good result it means DFMM code is perfect\n\t\t\telse {\n\t\t\t\tthis->level_LFR\t=\tfloor(log(kappa*L/B)/log(2.0));\n\t\t\t}\n\t\t\tif (level_LFR < 2) level_LFR = 2;\n\t\t}\n\t\telse {\n\t\t\tlevel_LFR = 2;\n\t\t}\n\t\tcout << \"level_LFR: \" << level_LFR << endl;\n\t}\n\n\tvoid evaluatePrecomputations() {\n\t\tFF->evaluateQ(Q_pinv);\n\t\tFF->evaluateM(M);\n\t}\n\n\tvoid getIfNeighbor(int j, int k, int nj, int nk, int& typeOfNeighbor, int& NumOfNeighbor) {\n\t\tif ( fabs(tree[j][k].center.x - tree[nj][nk].center.x) >= 3.0*boxRadius[j] + boxRadius[nj]-epsilonRoundOff\n\t\t || fabs(tree[j][k].center.y - tree[nj][nk].center.y) >= 3.0*boxRadius[j] + boxRadius[nj]-epsilonRoundOff) {\n\t\t\t typeOfNeighbor = -1;\n\t\t}\n\t\telse {\n\t\t\tdouble angle = atan2(tree[nj][nk].center.y-tree[j][k].center.y, tree[nj][nk].center.x-tree[j][k].center.x);\n\t\t\tif (tree[j][k].radius == tree[nj][nk].radius) {\n\t\t\t\ttypeOfNeighbor = 0;\n\t\t\t\tif (fabs(tree[nj][nk].center.y-tree[j][k].center.y)<epsilonRoundOff && fabs(tree[nj][nk].center.x-tree[j][k].center.x)<epsilonRoundOff) {\n\t\t\t\t\tNumOfNeighbor = 8;\n\t\t\t\t} // self\n\t\t\t\telse if (fabs(N_angles[0] - angle) < epsilonRoundOff) {\n\t\t\t\t\tNumOfNeighbor = 0;\n\t\t\t\t}\n\t\t\t\telse if (fabs(N_angles[1] - angle) < epsilonRoundOff) {\n\t\t\t\t\tNumOfNeighbor = 1;\n\t\t\t\t}\n\t\t\t\telse if (fabs(N_angles[2] - angle) < epsilonRoundOff) {\n\t\t\t\t\tNumOfNeighbor = 2;\n\t\t\t\t}\n\t\t\t\telse if (fabs(N_angles[3] - angle) < epsilonRoundOff) {\n\t\t\t\t\tNumOfNeighbor = 3;\n\t\t\t\t}\n\t\t\t\telse if (fabs(N_angles[4] - angle) < epsilonRoundOff) {\n\t\t\t\t\tNumOfNeighbor = 4;\n\t\t\t\t}\n\t\t\t\telse if (fabs(N_angles[5] - angle) < epsilonRoundOff) {\n\t\t\t\t\tNumOfNeighbor = 5;\n\t\t\t\t}\n\t\t\t\telse if (fabs(N_angles[6] - angle) < epsilonRoundOff) {\n\t\t\t\t\tNumOfNeighbor = 6;\n\t\t\t\t}\n\t\t\t\telse if (fabs(N_angles[7] - angle) < epsilonRoundOff) {\n\t\t\t\t\tNumOfNeighbor = 7;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (tree[j][k].radius < tree[nj][nk].radius) { //coarse neighbors\n\t\t\t\ttypeOfNeighbor = 1;\n\t\t\t\tif (fabs(CN_angles[0] - angle) < epsilonRoundOff) {\n\t\t\t\t\tNumOfNeighbor = 0;\n\t\t\t\t}\n\t\t\t\telse if (fabs(CN_angles[1] - angle) < epsilonRoundOff) {\n\t\t\t\t\tNumOfNeighbor = 1;\n\t\t\t\t}\n\t\t\t\telse if (fabs(CN_angles[2] - angle) < epsilonRoundOff) {\n\t\t\t\t\tNumOfNeighbor = 2;\n\t\t\t\t}\n\t\t\t\telse if (fabs(CN_angles[3] - angle) < epsilonRoundOff) {\n\t\t\t\t\tNumOfNeighbor = 3;\n\t\t\t\t}\n\t\t\t\telse if (fabs(CN_angles[4] - angle) < epsilonRoundOff) {\n\t\t\t\t\tNumOfNeighbor = 4;\n\t\t\t\t}\n\t\t\t\telse if (fabs(CN_angles[5] - angle) < epsilonRoundOff) {\n\t\t\t\t\tNumOfNeighbor = 5;\n\t\t\t\t}\n\t\t\t\telse if (fabs(CN_angles[6] - angle) < epsilonRoundOff) {\n\t\t\t\t\tNumOfNeighbor = 6;\n\t\t\t\t}\n\t\t\t\telse if (fabs(CN_angles[7] - angle) < epsilonRoundOff) {\n\t\t\t\t\tNumOfNeighbor = 7;\n\t\t\t\t}\n\t\t\t\telse if (fabs(CN_angles[8] - angle) < epsilonRoundOff) {\n\t\t\t\t\tNumOfNeighbor = 8;\n\t\t\t\t}\n\t\t\t\telse if (fabs(CN_angles[9] - angle) < epsilonRoundOff) {\n\t\t\t\t\tNumOfNeighbor = 9;\n\t\t\t\t}\n\t\t\t\telse if (fabs(CN_angles[10] - angle) < epsilonRoundOff) {\n\t\t\t\t\tNumOfNeighbor = 10;\n\t\t\t\t}\n\t\t\t\telse if (fabs(CN_angles[11] - angle) < epsilonRoundOff) {\n\t\t\t\t\tNumOfNeighbor = 11;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse { //fine neighbors and separated fine neighbors\n\t\t\t\t if (find_distance(j, k, nj, nk) > 2.5*tree[j][k].radius) { //separated fine neighbors\n\t\t\t\t\t typeOfNeighbor = 3;\n\t\t\t\t\t if (fabs(SFN_angles[0] - angle) < epsilonRoundOff) {\n\t\t\t\t\t\t NumOfNeighbor = 0;\n\t\t\t\t\t }\n\t\t\t\t\t else if (fabs(SFN_angles[1] - angle) < epsilonRoundOff) {\n\t\t\t\t\t\t NumOfNeighbor = 1;\n\t\t\t\t\t }\n\t\t\t\t\t else if (fabs(SFN_angles[2] - angle) < epsilonRoundOff) {\n\t\t\t\t\t\t NumOfNeighbor = 2;\n\t\t\t\t\t }\n\t\t\t\t\t else if (fabs(SFN_angles[3] - angle) < epsilonRoundOff) {\n\t\t\t\t\t\t NumOfNeighbor = 3;\n\t\t\t\t\t }\n\t\t\t\t\t else if (fabs(SFN_angles[4] - angle) < epsilonRoundOff) {\n\t\t\t\t\t\t NumOfNeighbor = 4;\n\t\t\t\t\t }\n\t\t\t\t\t else if (fabs(SFN_angles[5] - angle) < epsilonRoundOff) {\n\t\t\t\t\t\t NumOfNeighbor = 5;\n\t\t\t\t\t }\n\t\t\t\t\t else if (fabs(SFN_angles[6] - angle) < epsilonRoundOff) {\n\t\t\t\t\t\t NumOfNeighbor = 6;\n\t\t\t\t\t }\n\t\t\t\t\t else if (fabs(SFN_angles[7] - angle) < epsilonRoundOff) {\n\t\t\t\t\t\t NumOfNeighbor = 7;\n\t\t\t\t\t }\n\t\t\t\t\t else if (fabs(SFN_angles[8] - angle) < epsilonRoundOff) {\n\t\t\t\t\t\t NumOfNeighbor = 8;\n\t\t\t\t\t }\n\t\t\t\t\t else if (fabs(SFN_angles[9] - angle) < epsilonRoundOff) {\n\t\t\t\t\t\t NumOfNeighbor = 9;\n\t\t\t\t\t }\n\t\t\t\t\t else if (fabs(SFN_angles[10] - angle) < epsilonRoundOff) {\n\t\t\t\t\t\t NumOfNeighbor = 10;\n\t\t\t\t\t }\n\t\t\t\t\t else if (fabs(SFN_angles[11] - angle) < epsilonRoundOff) {\n\t\t\t\t\t\t NumOfNeighbor = 11;\n\t\t\t\t\t }\n\t\t\t\t\t else if (fabs(SFN_angles[12] - angle) < epsilonRoundOff) {\n\t\t\t\t\t\t NumOfNeighbor = 12;\n\t\t\t\t\t }\n\t\t\t\t\t else if (fabs(SFN_angles[13] - angle) < epsilonRoundOff) {\n\t\t\t\t\t\t NumOfNeighbor = 13;\n\t\t\t\t\t }\n\t\t\t\t\t else if (fabs(SFN_angles[14] - angle) < epsilonRoundOff) {\n\t\t\t\t\t\t NumOfNeighbor = 14;\n\t\t\t\t\t }\n\t\t\t\t\t else if (fabs(SFN_angles[15] - angle) < epsilonRoundOff) {\n\t\t\t\t\t\t NumOfNeighbor = 15;\n\t\t\t\t\t }\n\t\t\t\t\t else if (fabs(SFN_angles[16] - angle) < epsilonRoundOff) {\n\t\t\t\t\t\t NumOfNeighbor = 16;\n\t\t\t\t\t }\n\t\t\t\t\t else if (fabs(SFN_angles[17] - angle) < epsilonRoundOff) {\n\t\t\t\t\t\t NumOfNeighbor = 17;\n\t\t\t\t\t }\n\t\t\t\t\t else if (fabs(SFN_angles[18] - angle) < epsilonRoundOff) {\n\t\t\t\t\t\t NumOfNeighbor = 18;\n\t\t\t\t\t }\n\t\t\t\t\t else {\n\t\t\t\t\t\t NumOfNeighbor = 19;\n\t\t\t\t\t }\n\t\t\t\t }\n\t\t\t\t else {//fine neighbors\n\t\t\t\t\t typeOfNeighbor = 2;\n\t\t\t\t\t if (fabs(FN_angles[0] - angle) < epsilonRoundOff) {\n\t\t\t\t\t\t NumOfNeighbor = 0;\n\t\t\t\t\t }\n\t\t\t\t\t else if (fabs(FN_angles[1] - angle) < epsilonRoundOff) {\n\t\t\t\t\t\t NumOfNeighbor = 1;\n\t\t\t\t\t }\n\t\t\t\t\t else if (fabs(FN_angles[2] - angle) < epsilonRoundOff) {\n\t\t\t\t\t\t NumOfNeighbor = 2;\n\t\t\t\t\t }\n\t\t\t\t\t else if (fabs(FN_angles[3] - angle) < epsilonRoundOff) {\n\t\t\t\t\t\t NumOfNeighbor = 3;\n\t\t\t\t\t }\n\t\t\t\t\t else if (fabs(FN_angles[4] - angle) < epsilonRoundOff) {\n\t\t\t\t\t\t NumOfNeighbor = 4;\n\t\t\t\t\t }\n\t\t\t\t\t else if (fabs(FN_angles[5] - angle) < epsilonRoundOff) {\n\t\t\t\t\t\t NumOfNeighbor = 5;\n\t\t\t\t\t }\n\t\t\t\t\t else if (fabs(FN_angles[6] - angle) < epsilonRoundOff) {\n\t\t\t\t\t\t NumOfNeighbor = 6;\n\t\t\t\t\t }\n\t\t\t\t\t else if (fabs(FN_angles[7] - angle) < epsilonRoundOff) {\n\t\t\t\t\t\t NumOfNeighbor = 7;\n\t\t\t\t\t }\n\t\t\t\t\t else if (fabs(FN_angles[8] - angle) < epsilonRoundOff) {\n\t\t\t\t\t\t NumOfNeighbor = 8;\n\t\t\t\t\t }\n\t\t\t\t\t else if (fabs(FN_angles[9] - angle) < epsilonRoundOff) {\n\t\t\t\t\t\t NumOfNeighbor = 9;\n\t\t\t\t\t }\n\t\t\t\t\t else if (fabs(FN_angles[10] - angle) < epsilonRoundOff) {\n\t\t\t\t\t\t NumOfNeighbor = 10;\n\t\t\t\t\t }\n\t\t\t\t\t else if (fabs(FN_angles[11] - angle) < epsilonRoundOff) {\n\t\t\t\t\t\t NumOfNeighbor = 11;\n\t\t\t\t\t }\n\t\t\t\t }\n\t\t\t}\n\t\t}\n\t}\n\n\tkernel_dtype getMatrixEntry2(const unsigned i, const unsigned j) {\n\t\tNoIn_getMatrixEntry += 1;\n\t\tdouble start\t=\tomp_get_wtime();\n\n\t\t/*\n\t\tpts2D ri = particles_X[i];//particles_X is a member of base class FMM_Matrix\n\t\tpts2D rj = particles_X[j];//particles_X is a member of base class FMM_Matrix\n\t\tdouble R2 = (ri.x-rj.x)*(ri.x-rj.x) + (ri.y-rj.y)*(ri.y-rj.y);\n\t\tdouble R = sqrt(R2);\n\t\tkernel_dtype out = exp(I*kappa*R)/R;\n\n\t\tdouble end\t\t=\tomp_get_wtime();\n\t\ttimeIn_getMatrixEntry += (end-start);\n\t\t//cout << end-start << endl;\n\t\tif (NoIn_getMatrixEntry == 1) {\n\t\t\tcout << \"avg time to get a matrix entry: \" << timeIn_getMatrixEntry << endl;\n\t\t}\n\t\tif (R < 1e-8) {\n\t\t\treturn R;\n\t\t}\n\t\telse {\n\t\t\treturn out;\n\t\t}\n\t\t*/\n\n\t\tpts2D ri = particles_X[i];//particles_X is a member of base class FMM_Matrix\n\t\tunsigned int leaf_i = i/rank;//identify to which leaf jth charge belongs\n\t\tunsigned int index_i = i%rank;\n\t\tunsigned int level_i = leafNodes[leaf_i].x;//level to which the leaf box that contains jth charge belongs\n\t\tunsigned int box_i = leafNodes[leaf_i].y;\n\n\t\tunsigned int leaf_j = j/rank;//identify to which leaf jth charge belongs\n\t\tunsigned int index_j = j%rank;\n\t\tunsigned int level_j = leafNodes[leaf_j].x;//level to which the leaf box that contains jth charge belongs\n\t\tunsigned int box_j = leafNodes[leaf_j].y;\n\n\t\tbool is_ij_neighbor = false;\n\t\tint typeOfNeighbor, NumOfNeighbor;\n\t\tgetIfNeighbor(level_i, box_i, level_j, box_j, typeOfNeighbor, NumOfNeighbor);\n\t\tif (typeOfNeighbor != -1) {\n\t\t\tis_ij_neighbor = true;\n\t\t}\n\n\t\tif (is_ij_neighbor) {\n\t\t\tkernel_dtype entry;\n\t\t\tif (typeOfNeighbor == 0) { //colleagueNeighbors\n\t\t\t\tentry = colleagueNeighborInteraction[level_i-2][NumOfNeighbor](index_i, index_j);\n\t\t\t}\n\t\t\telse if (typeOfNeighbor == 1) { //coarseNeighbors\n\t\t\t\tentry = coarseNeighborInteraction[level_i-2][NumOfNeighbor](index_i, index_j);\n\t\t\t}\n\t\t\telse if (typeOfNeighbor == 2) { //fine neighbor\n\t\t\t\tentry = fineNeighborInteraction[level_i-2][NumOfNeighbor](index_i, index_j);\n\t\t\t}\n\t\t\telse { // separatedFineNeighbor\n\t\t\t\tentry = separatedFineNeighborInteraction[level_i-2][NumOfNeighbor](index_i, index_j);\n\t\t\t}\n\t\t\tif (findPhi) {\n\t\t\t\tentry = entry*kappa*kappa*(1.0+Q->ContrastFunction(ri));\n\t\t\t\tif (i ==j) {\n\t\t\t\t\tentry = 1.0 + entry;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn entry;\n\t\t}\n\t\telse {\n\t\t\tdouble polar_angle_i = std::atan2(ri.y-tree[level_j][box_j].center.y, ri.x-tree[level_j][box_j].center.x);\n\t\t\tdouble R2\t=\t(ri.y-tree[level_j][box_j].center.y)*(ri.y-tree[level_j][box_j].center.y) + (ri.x-tree[level_j][box_j].center.x)*(ri.x-tree[level_j][box_j].center.x);\n\t\t\tdouble R\t=\tkappa*sqrt(R2);\n\t\t\tkernel_dtype tempSum = 0.0+0.0*I;\n\t\t\tint seriesLength = FF->seriesLength;\n\t\t\tfor (int n = -seriesLength; n <= seriesLength; n++) {\n\t\t\t\tkernel_dtype temp = (besselJ(n, R) + I*besselY(n, R)) * exp(I*double(n)*polar_angle_i);\n\t\t\t\ttempSum += M[level_j](n+seriesLength, index_j)*temp;\n\t\t\t}\n\t\t\ttempSum *= I/4.0;\n\t\t\tif (findPhi) {\n\t\t\t\ttempSum *= kappa*kappa*(1.0+Q->ContrastFunction(ri));\n\t\t\t\tif (i==j) {\n\t\t\t\t\ttempSum += 1.0;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn tempSum;\n\t\t}\n\n\t}\n\n\tkernel_dtype getMatrixEntry(const unsigned i, const unsigned j) {\n\t\tNoIn_getMatrixEntry += 1;\n\t\tdouble start\t=\tomp_get_wtime();\n\t\t/*\n\t\tpts2D ri = particles_X[i];//particles_X is a member of base class FMM_Matrix\n\t\tpts2D rj = particles_X[j];//particles_X is a member of base class FMM_Matrix\n\t\tdouble R2 = (ri.x-rj.x)*(ri.x-rj.x) + (ri.y-rj.y)*(ri.y-rj.y);\n\t\tdouble R = sqrt(R2);\n\t\tkernel_dtype out = exp(I*kappa*R)/R;\n\t\tdouble end\t\t=\tomp_get_wtime();\n\t\ttimeIn_getMatrixEntry += (end-start);\n\t\tif (NoIn_getMatrixEntry == 1) {\n\t\t\tcout << \"avg time to get a matrix entry: \" << timeIn_getMatrixEntry << endl;\n\t\t}\n\t\tif (R < epsilonRoundOff) {\n\t\t\treturn R;\n\t\t}\n\t\telse {\n\t\t\treturn out;\n\t\t}\n\t\t*/\n\n\t\tpts2D ri = particles_X[i];//particles_X is a member of base class FMM_Matrix\n\t\tunsigned int l = j/rank;//identify to which leaf jth charge belongs\n\t\tunsigned int chargeIndex = j%rank;\n\t\tunsigned int tj = leafNodes[l].x;//level to which the leaf box that contains jth charge belongs\n\t\tunsigned int tk = leafNodes[l].y;\n\t\tdouble polar_angle_i = std::atan2(ri.y-tree[tj][tk].center.y, ri.x-tree[tj][tk].center.x);\n\t\tdouble R2\t=\t(ri.y-tree[tj][tk].center.y)*(ri.y-tree[tj][tk].center.y) + (ri.x-tree[tj][tk].center.x)*(ri.x-tree[tj][tk].center.x);\n\t\tdouble R\t=\tkappa*sqrt(R2);\n\t\tkernel_dtype tempSum = 0.0+0.0*I;\n\t\tint seriesLength = FF->seriesLength;\n\t\tfor (int n = -seriesLength; n <= seriesLength; n++) {\n\t\t\tkernel_dtype temp = (besselJ(n, R) + I*besselY(n, R)) * exp(I*double(n)*polar_angle_i);\n\t\t\ttempSum += M[tj](n+seriesLength, chargeIndex)*temp;\n\t\t}\n\t\ttempSum *= I/4.0;\n\t\tif (findPhi) {\n\t\t\ttempSum *= kappa*kappa*(1.0+Q->ContrastFunction(ri));\n\t\t\tif (i==j) {\n\t\t\t\ttempSum += 1.0;\n\t\t\t}\n\t\t}\n\t\tdouble end\t\t=\tomp_get_wtime();\n\t\ttimeIn_getMatrixEntry += (end-start);\n\t\tif (NoIn_getMatrixEntry == 1) {\n\t\t\tcout << \"avg time to get a matrix entry: \" << timeIn_getMatrixEntry << endl;\n\t\t}\n\t\treturn tempSum;\n\n\t}\n\n\tvoid shift_scale_Nodes(std::vector<pts2D>& Nodes, std::vector<pts2D>& shifted_scaled_Nodes, double xShift, double yShift, double radius) {\n\t\tfor (int k=0; k < Nodes.size(); ++k) {\n\t\t\tpts2D temp;\n\t\t\ttemp.x\t=\tradius*Nodes[k].x+xShift;\n\t\t\ttemp.y\t=\tradius*Nodes[k].y+yShift;\n\t\t\tshifted_scaled_Nodes.push_back(temp);\n\t\t}\n\t}\n\n\t//\tget_ChebPoly\n\tdouble get_ChebPoly(double x, int n) {\n\t\treturn cos(n*acos(x));\n\t}\n\n\t//\tget_S\n\tdouble get_S(double x, double y, int n) {\n\t\tdouble S\t=\t0.5;\n\t\tfor (int k=1; k<n; ++k) {\n\t\t\tS+=get_ChebPoly(x,k)*get_ChebPoly(y,k);\n\t\t}\n\t\treturn 2.0/n*S;\n\t}\n\t//\tset_Standard_Cheb_Nodes\n\tvoid set_Standard_Cheb_Nodes() {\n\t\tfor (int k=0; k<nChebNodes; ++k) {\n\t\t\tstandardChebNodes1D.push_back(-cos((k+0.5)/nChebNodes*PI));\n\t\t}\n\t\tpts2D temp1;\n\t\tfor (int j=0; j<nChebNodes; ++j) {\n\t\t\tfor (int k=0; k<nChebNodes; ++k) {\n\t\t\t\ttemp1.x\t=\tstandardChebNodes1D[k];\n\t\t\t\ttemp1.y\t=\tstandardChebNodes1D[j];\n\t\t\t\tstandardChebNodes.push_back(temp1);\n\t\t\t}\n\t\t}\n\t\t//\tLeft Bottom child, i.e., Child 0\n\t\tfor (int j=0; j<rank; ++j) {\n\t\t\t\ttemp1\t=\tstandardChebNodes[j];\n\t\t\t\ttemp1.x\t=\t0.5*temp1.x-0.5;\n\t\t\t\ttemp1.y\t=\t0.5*temp1.y-0.5;\n\t\t\t\tstandardChebNodesChild.push_back(temp1);\n\t\t}\n\t\t//\tRight Bottom child, i.e., Child 1\n\t\tfor (int j=0; j<rank; ++j) {\n\t\t\t\ttemp1\t=\tstandardChebNodes[j];\n\t\t\t\ttemp1.x\t=\t0.5*temp1.x+0.5;\n\t\t\t\ttemp1.y\t=\t0.5*temp1.y-0.5;\n\t\t\t\tstandardChebNodesChild.push_back(temp1);\n\t\t}\n\t\t//\tRight Top child, i.e., Child 2\n\t\tfor (int j=0; j<rank; ++j) {\n\t\t\t\ttemp1\t=\tstandardChebNodes[j];\n\t\t\t\ttemp1.x\t=\t0.5*temp1.x+0.5;\n\t\t\t\ttemp1.y\t=\t0.5*temp1.y+0.5;\n\t\t\t\tstandardChebNodesChild.push_back(temp1);\n\t\t}\n\t\t//\tLeft Top child, i.e., Child 3\n\t\tfor (int j=0; j<rank; ++j) {\n\t\t\t\ttemp1\t=\tstandardChebNodes[j];\n\t\t\t\ttemp1.x\t=\t0.5*temp1.x-0.5;\n\t\t\t\ttemp1.y\t=\t0.5*temp1.y+0.5;\n\t\t\t\tstandardChebNodesChild.push_back(temp1);\n\t\t}\n\t}\n\n\tvoid get_Transfer_Matrix() {\n\t\tfor (int l=0; l<4; ++l) {\n\t\t\tL2L[l]\t=\tEigen::MatrixXd(rank,rank);\n\t\t\tfor (int j=0; j<rank; ++j) {\n\t\t\t\tfor (int k=0; k<rank; ++k) {\n\t\t\t\t\tL2L[l](j,k)\t=\tget_S(standardChebNodes[k].x, standardChebNodesChild[j+l*rank].x, nChebNodes)*get_S(standardChebNodes[k].y, standardChebNodesChild[j+l*rank].y, nChebNodes);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor (int l=0; l<4; ++l) {\n\t\t\tM2M[l]\t=\tL2L[l].transpose();\n\t\t}\n\t}\n\t//////////////////TREE CREATION////////////////////////////////////////////\n\tdouble resolveContrast(int j, int k) {\n\t\tEigen::VectorXd contrastAtChebNodes;\n\t\tstd::vector<pts2D> Nodes;\n\t\tshift_scale_Nodes(standardChebNodes, Nodes, tree[j][k].center.x, tree[j][k].center.y, tree[j][k].radius);\n\t\tEvaluateContrastAtNodes(contrastAtChebNodes, Nodes);\n\t\tEigen::VectorXd approximateContrastAtChildChebNodes(4*rank);\n\t\tfor (size_t c = 0; c < 4; c++) {\n\t\t\tapproximateContrastAtChildChebNodes.segment(rank*c, rank) = L2L[c]*contrastAtChebNodes;\n\t\t}\n\t\tstd::vector<pts2D> NodesChild;\n\t\tshift_scale_Nodes(standardChebNodesChild, NodesChild, tree[j][k].center.x, tree[j][k].center.y, tree[j][k].radius);\n\t\tEigen::VectorXd contrastAtChildChebNodes;\n\t\tEvaluateContrastAtNodes(contrastAtChildChebNodes, NodesChild);\n\t\tdouble err = errInApproximation(contrastAtChildChebNodes, approximateContrastAtChildChebNodes);\n\t\treturn err;\n\t}\n\n\t\tdouble resolveRHS(int j, int k) {\n\t\t\tVec RHSAtChebNodes;\n\t\t\tstd::vector<pts2D> Nodes;\n\t\t\tshift_scale_Nodes(standardChebNodes, Nodes, tree[j][k].center.x, tree[j][k].center.y, tree[j][k].radius);\n\t\t\tEvaluateRHSAtNodes(RHSAtChebNodes, Nodes);\n\t\t\tVec approximateRHSAtChildChebNodes(4*rank);\n\t\t\tfor (size_t c = 0; c < 4; c++) {\n\t\t\t\tapproximateRHSAtChildChebNodes.segment(rank*c, rank) = L2L[c]*RHSAtChebNodes;\n\t\t\t}\n\t\t\tstd::vector<pts2D> NodesChild;\n\t\t\tshift_scale_Nodes(standardChebNodesChild, NodesChild, tree[j][k].center.x, tree[j][k].center.y, tree[j][k].radius);\n\t\t\tVec RHSAtChildChebNodes;\n\t\t\tEvaluateRHSAtNodes(RHSAtChildChebNodes, NodesChild);\n\t\t\tdouble err = errInApproximation(RHSAtChildChebNodes, approximateRHSAtChildChebNodes);\n\t\t\treturn err;\n\t\t}\n\n\t\tvoid createTree(int j, int k) {\n\t\t\t//k: index of box in the vector tree[j]\n\t\t\t//b: boxNumber of box, tree[j][k]\n\t\t\tdouble errContrast = resolveContrast(j, k);\n\t\t\tdouble errRHS = resolveRHS(j, k);\n\t\t\tbool condition1Leaf = false;\n\t\t\tbool condition2Leaf = false;\n\t\t\tbool condition3Leaf = false;\n\t\t\tif (errContrast < epsilonTree) condition1Leaf = true;\n\t\t\tif (errRHS < epsilonTree) condition2Leaf = true;\n\t\t\tif (kappa*tree[j][k].radius <= 2*PI*3.0) condition3Leaf = true;\n\t\t\tif (condition1Leaf && condition2Leaf && condition3Leaf) {\n\t\t\t\ttree[j][k].isLeaf = true;\n\t\t\t\torderedPair op;\n\t\t\t\top.x = j;\n\t\t\t\top.y = k;\n\t\t\t\tleafNodes.push_back(op);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (int(tree.size()) == j+1) {\n\t\t\t\t\tstd::vector<FMM2DBox> level;\n\t\t\t\t\ttree.push_back(level);\n\t\t\t\t\tstd::vector<int> index;\n\t\t\t\t  indexTree.push_back(index);\n\t\t\t\t}\n\t\t\t\tint n\t=\ttree[j+1].size();\n\t\t\t\tint b = tree[j][k].boxNumber;\n\t\t\t\tfor (size_t c = 0; c < 4; c++) {\n\t\t\t\t\tFMM2DBox box;\n\t\t\t\t\tbox.level = j+1;\n\t\t\t\t\tbox.boxNumber\t\t=\tb*4+c;\n\t\t\t\t\tbox.parentNumber\t=\tb;\n\t\t\t\t\tbox.radius = 0.5*tree[j][k].radius;\n\t\t\t\t\tif (c==0) {\n\t\t\t\t\t\tbox.center.x\t\t=\ttree[j][k].center.x-0.5*tree[j][k].radius;\n\t\t\t\t\t\tbox.center.y\t\t=\ttree[j][k].center.y-0.5*tree[j][k].radius;\n\t\t\t\t\t}\n\t\t\t\t\telse if (c==1) {\n\t\t\t\t\t\tbox.center.x\t\t=\ttree[j][k].center.x+0.5*tree[j][k].radius;\n\t\t\t\t\t\tbox.center.y\t\t=\ttree[j][k].center.y-0.5*tree[j][k].radius;\n\t\t\t\t\t}\n\t\t\t\t\telse if (c==2) {\n\t\t\t\t\t\tbox.center.x\t\t=\ttree[j][k].center.x+0.5*tree[j][k].radius;\n\t\t\t\t\t\tbox.center.y\t\t=\ttree[j][k].center.y+0.5*tree[j][k].radius;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tbox.center.x\t\t=\ttree[j][k].center.x-0.5*tree[j][k].radius;\n\t\t\t\t\t\tbox.center.y\t\t=\ttree[j][k].center.y+0.5*tree[j][k].radius;\n\t\t\t\t\t}\n\t\t\t\t\ttree[j+1].push_back(box);\n\t\t\t\t\tindexTree[j+1].push_back(box.boxNumber);\n\t\t\t\t}\n\t\t\t\tfor (size_t c = 0; c < 4; c++) {\n\t\t\t\t\tcreateTree(j+1, n+c);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tvoid createAdaptiveTree() {\n\t\t\tFMM2DBox root;\n\t\t\troot.level = 0;\n\t\t\troot.boxNumber\t\t=\t0;\n\t\t\troot.parentNumber\t=\t-1;\n\t\t\troot.radius = L;\n\t\t\troot.center.x = 0.0;\n\t\t\troot.center.y = 0.0;\n\t\t\tstd::vector<FMM2DBox> level;\n\t\t\tlevel.push_back(root);\n\t\t\ttree.push_back(level);\n\n\t\t\tstd::vector<int> index;\n\t\t\tindex.push_back(0);\n\t\t\tindexTree.push_back(index);\n\t\t\tcreateTree(0, 0);\n\t\t\tnLevels = tree.size() - 1;\n\t\t\tcout << \"nLevels: \" << nLevels << endl;\n\t\t\tfor (size_t j = 1; j <= 10; j++) {\n\t\t\t\tboxRadius.push_back(boxRadius[j-1]/2.0);\n\t\t\t}\n\t\t\tif (level_LFR >= nLevels) {\n\t\t\t\tlevel_LFR = nLevels-1;\n\t\t\t}\n\t\t}\n\n\t\tvoid getFutureGeneration_LFR(int bj, int bk, int pnj, int pni, std::vector<orderedPair>& futureGeneration) {\n\t\t\tif (tree[pnj][pni].isLeaf) {\n\t\t\t\tif ( fabs(tree[bj][bk].center.x - tree[pnj][pni].center.x) >= 3.0*boxRadius[bj] + boxRadius[pnj]-epsilonRoundOff\n\t\t\t\t || fabs(tree[bj][bk].center.y - tree[pnj][pni].center.y) >= 3.0*boxRadius[bj] + boxRadius[pnj]-epsilonRoundOff) {\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\torderedPair op;\n\t\t\t\t\top.x = pnj;\n\t\t\t\t\top.y = pni;\n\t\t\t\t\tfutureGeneration.push_back(op);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tfor (int nc=0; nc<4; ++nc) { //children of parents neighbors\n\t\t\t\t\tint pnn = tree[pnj][pni].boxNumber;//boxNumber\n\t\t\t\t\tint boxB = 4*pnn+nc;//its index=?\n\t\t\t\t\tstd::vector<int>::iterator indx = std::find(indexTree[pnj+1].begin(), indexTree[pnj+1].end(), boxB);\n\t\t\t\t\tint boxB_index = indx-indexTree[pnj+1].begin();\n\t\t\t\t\tgetFutureGeneration_LFR(bj, bk, pnj+1, boxB_index, futureGeneration);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tvoid assign_Child_Interaction_LFR(int c, int j, int k, std::vector<std::vector<std::vector<orderedPair> > >& Tree_Neighbors_LFR) {\n\t\t\tint parentboxNumber = tree[j][k].boxNumber;\n\t\t\tint boxA = 4*parentboxNumber+c;//child box number; its index=?\n\t\t\tstd::vector<int>::iterator indx = std::find(indexTree[j+1].begin(), indexTree[j+1].end(), boxA);\n\t\t\tint boxA_index = indx-indexTree[j+1].begin();\n\t\t\tfor (int n=0; n<Tree_Neighbors_LFR[j][k].size(); ++n) {//parents neighbors; so u need its index to access it which is k\n\t\t\t\t//children of neighbors of parent which are not neighbors to child=IL\n\t\t\t\tint pnj = Tree_Neighbors_LFR[j][k][n].x;//level\n\t\t\t\tint pni = Tree_Neighbors_LFR[j][k][n].y;//index\n\t\t\t\tint pnn = tree[pnj][pni].boxNumber;//boxNumber\n\n\t\t\t\tstd::vector<orderedPair> futureGeneration;\n\t\t\t\tgetFutureGeneration_LFR(j+1, boxA_index, pnj, pni, futureGeneration);\n\t\t\t\tfor (size_t d = 0; d < futureGeneration.size(); d++) {\n\t\t\t\t\tTree_Neighbors_LFR[j+1][boxA_index].push_back(futureGeneration[d]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t//\tAssigns the interactions for the children of a box\n\t\tvoid assign_Box_Interactions_LFR(int j, int k, std::vector<std::vector<std::vector<orderedPair> > >& Tree_Neighbors_LFR) {\n\t\t\tif (!tree[j][k].isLeaf) {\n\t\t\t\t//#pragma omp parallel for\n\t\t\t\tfor (int c=0; c<4; ++c) {\n\t\t\t\t\tassign_Child_Interaction_LFR(c,j,k, Tree_Neighbors_LFR);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t//\tAssigns the interactions for the children all boxes at a given level\n\t\tvoid assign_Level_Interactions_LFR(int j, std::vector<std::vector<std::vector<orderedPair> > >& Tree_Neighbors_LFR) {\n\t\t\t//#pragma omp parallel for\n\t\t\tfor (int k=0; k<tree[j].size(); ++k) {\n\t\t\t\tassign_Box_Interactions_LFR(j,k, Tree_Neighbors_LFR);//k is index number of box in tree[j] vector\n\t\t\t}\n\t\t}\n\n\t\t//\tAssigns the interactions for the children all boxes in the tree\n\t\tvoid assign_Tree_Interactions_LFR(std::vector<std::vector<std::vector<orderedPair> > >& Tree_Neighbors_LFR) {\n\t\t\tint J = 1;\n\t\t\tfor (int c=0; c<4; ++c) {\n\t\t\t\tfor (int n=0; n<4; ++n) {\n\t\t\t\t\torderedPair op;\n\t\t\t\t\top.x = J;\n\t\t\t\t\top.y = n;\n\t\t\t\t\tTree_Neighbors_LFR[J][c].push_back(op);\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (int j=1; j<=nLevels-1; ++j) {\n\t\t\t\tassign_Level_Interactions_LFR(j, Tree_Neighbors_LFR);\n\t\t\t}\n\t\t}\n\n\t\tvoid makeLevelRestriction_Tree() {\n\t\t\tfor (size_t n = 0; n < nLevels; n++) {\n\t\t\t\tstd::vector<std::vector<std::vector<orderedPair> > > Tree_Neighbors_LFR;\n\t\t\t\tfor (size_t j = 0; j <= nLevels; j++) {\n\t\t\t\t\tstd::vector<std::vector<orderedPair> > level;\n\t\t\t\t\tfor (size_t k = 0; k < tree[j].size(); k++) {\n\t\t\t\t\t\tstd::vector<orderedPair> box;\n\t\t\t\t\t\tlevel.push_back(box);\n\t\t\t\t\t}\n\t\t\t\t\tTree_Neighbors_LFR.push_back(level);\n\t\t\t\t}\n\t\t\t\tassign_Tree_Interactions_LFR(Tree_Neighbors_LFR);\n\t\t\t\tstd::vector<orderedPair> leafNodesOld = leafNodes;\n\t\t\t\tfor (size_t l = 0; l < leafNodesOld.size(); l++) {\n\t\t\t\t\tmakeLevelRestriction_Box(l, leafNodes[l], Tree_Neighbors_LFR, leafNodesOld);\n\t\t\t\t}\n\n\t\t\t\tint cnt = 0;\n \t\t\t\tfor (size_t l = 0; l < leafNodesOld.size(); l++) {//removing all the non-leaves from leafNodes vector\n\t\t\t\t\tif (leafNodesOld[l].x == -1) {\n\t\t\t\t\t\tleafNodes.erase(leafNodes.begin()+l-cnt);\n\t\t\t\t\t\tcnt++;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tfor (size_t j = 0; j <= nLevels; j++) {\n\t\t\t\t\tfor (size_t k = 0; k < Tree_Neighbors_LFR[j].size(); k++) {\n\t\t\t\t\t\tTree_Neighbors_LFR[j][k].clear();\n\t\t\t\t\t}\n\t\t\t\t\tTree_Neighbors_LFR[j].clear();\n\t\t\t\t}\n\t\t\t\tTree_Neighbors_LFR.clear();\n\t\t\t}\n\t\t}\n\n\t\tint getIndexOfInLeafNodes(orderedPair op) {\n\t\t\tfor (size_t l = 0; l < leafNodes.size(); l++) {\n\t\t\t\tif (op.x == leafNodes[l].x && op.y == leafNodes[l].y) {\n\t\t\t\t\treturn l;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tvoid makeLevelRestriction_Box(int l, orderedPair leaf, std::vector<std::vector<std::vector<orderedPair> > >& Tree_Neighbors_LFR, std::vector<orderedPair>& leafNodesOld) {\n\t\t\t//l is index of leaf in leafNodes\n\t\t\t/*\n\t\t\tcout << \"leafNodesOld.size(): \" << leafNodesOld.size() << endl;\n\t\t\tfor (size_t r = 0; r < leafNodesOld.size(); r++) {\n\t\t\t\tcout << r << \", \"<< leafNodesOld[r].x << \", \" << leafNodesOld[r].y << endl;\n\t\t\t}\n\t\t\t*/\n\t\t\tint j = leaf.x;\n\t\t\tint k = leaf.y;\n\t\t\tfor (size_t i = 0; i < Tree_Neighbors_LFR[j][k].size(); i++) {\n\t\t\t\tint nj = Tree_Neighbors_LFR[j][k][i].x;\n\t\t\t\tint nk = Tree_Neighbors_LFR[j][k][i].y;\n\t\t\t\tstd::vector<orderedPair> newLeaves;\n\n\t\t\t\tif (j-nj >= 2 || nj-j >= 2) {\n\t\t\t\t\tif (j-nj >= 2) {\n\t\t\t\t\t\tint indexOfBox = getIndexOfInLeafNodes(Tree_Neighbors_LFR[j][k][i]);//index of Tree_Neighbors_LFR[j][k][i]\n\t\t\t\t\t\tif (leafNodesOld[indexOfBox].x != -1) {\n\t\t\t\t\t\t\trefineBox(indexOfBox, Tree_Neighbors_LFR[j][k][i], leafNodesOld);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if(nj-j >= 2) {\n\t\t\t\t\t\tif (leafNodesOld[l].x != -1) {\n\t\t\t\t\t\t\trefineBox(l, leaf, leafNodesOld);\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\tvoid refineBox(int l, orderedPair leaf, std::vector<orderedPair> &leafNodesOld) {\n\t\t\tint j = leaf.x; //level\n\t\t\tint k = leaf.y; //box index\n\t\t\tint b = tree[j][k].boxNumber;\n\t\t\tleafNodesOld[l].x = -1;//making it a non-leaf node\n\t\t\ttree[j][k].isLeaf = false;\n\t\t\tfor (size_t c = 0; c < 4; c++) {\n\t\t\t\tFMM2DBox box;\n\t\t\t\tbox.isLeaf = true;\n\t\t\t\tbox.level = j+1;\n\t\t\t\tbox.boxNumber\t\t=\tb*4+c;\n\t\t\t\tbox.parentNumber\t=\tb;\n\t\t\t\tbox.radius = 0.5*tree[j][k].radius;\n\t\t\t\tif (c==0) {\n\t\t\t\t\tbox.center.x\t\t=\ttree[j][k].center.x-0.5*tree[j][k].radius;\n\t\t\t\t\tbox.center.y\t\t=\ttree[j][k].center.y-0.5*tree[j][k].radius;\n\t\t\t\t}\n\t\t\t\telse if (c==1) {\n\t\t\t\t\tbox.center.x\t\t=\ttree[j][k].center.x+0.5*tree[j][k].radius;\n\t\t\t\t\tbox.center.y\t\t=\ttree[j][k].center.y-0.5*tree[j][k].radius;\n\t\t\t\t}\n\t\t\t\telse if (c==2) {\n\t\t\t\t\tbox.center.x\t\t=\ttree[j][k].center.x+0.5*tree[j][k].radius;\n\t\t\t\t\tbox.center.y\t\t=\ttree[j][k].center.y+0.5*tree[j][k].radius;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tbox.center.x\t\t=\ttree[j][k].center.x-0.5*tree[j][k].radius;\n\t\t\t\t\tbox.center.y\t\t=\ttree[j][k].center.y+0.5*tree[j][k].radius;\n\t\t\t\t}\n\t\t\t\torderedPair op;\n\t\t\t\top.x = j+1;\n\t\t\t\top.y = tree[j+1].size();\n\t\t\t\tleafNodes.push_back(op);\n\t\t\t\ttree[j+1].push_back(box);\n\t\t\t\tindexTree[j+1].push_back(box.boxNumber);\n\t\t\t}\n\t\t}\n\n\t\tvoid assignLeafCharges() {\n\t\t\tfor (size_t k = 0; k < leafNodes.size(); k++) {\n\t\t\t\tint j = leafNodes[k].x;\n\t\t\t\tint b = leafNodes[k].y;\n\t\t\t\ttree[j][b].multipoles\t=\t0.5*(Vec::Ones(rank));//+Eigen::VectorXd::Random(rank));\n\t\t\t}\n\t\t}\n\n\t\tvoid assignLeafCharges(Vec &charges) {\n\t\t\tchargesAll = charges;\n\t\t\tint start = 0;\n\t\t\tfor (size_t k = 0; k < leafNodes.size(); k++) {\n\t\t\t\tint j = leafNodes[k].x;\n\t\t\t\tint b = leafNodes[k].y;\n\t\t\t\ttree[j][b].multipoles\t=\tcharges.segment(start, rank);\n\t\t\t\tstart += rank;\n\t\t\t}\n\t\t}\n\n\t\tvoid assignLeafChargeLocations(std::vector<pts2D> &particles_out) {\n\t\t\tfor (size_t k = 0; k < leafNodes.size(); k++) {\n\t\t\t\tint j = leafNodes[k].x;\n\t\t\t\tint b = leafNodes[k].y;\n\t\t\t\tint startIndex = gridPoints.size();\n\t\t\t\tfor (size_t i = 0; i < rank; i++) {\n\t\t\t\t\ttree[j][b].chargeLocations.push_back(startIndex+i);\n\t\t\t\t}\n\t\t\t\tshift_scale_Nodes(standardChebNodes, gridPoints, tree[j][b].center.x, tree[j][b].center.y, boxRadius[j]);\n\t\t\t}\n\t\t\tparticles_X = gridPoints;//object of base class FMM_Matrix\n\t\t\tparticles_Y = gridPoints;\n\t\t\tparticles_out = gridPoints;\n\t\t}\n\n\t\tvoid assignNonLeafChargeLocations() {\n\t\t\tfor (int j=nLevels-1; j>1; --j) {\n\t\t\t\tint J\t=\tj+1;\n\t\t\t\t//#pragma omp parallel for\n\t\t\t\tfor (int k=0; k<tree[j].size(); ++k) {\n\t\t\t\t\tif (!tree[j][k].isLeaf) {\n\t\t\t\t\t\tint b = tree[j][k].boxNumber;\n\t\t\t\t\t\tint KboxNumber;\n\t\t\t\t\t\tint K[4];\n\t\t\t\t\t\tstd::vector<int>::iterator indx;\n\t\t\t\t\t\tKboxNumber = 4*b+0;\n\t\t\t\t\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\t\t\t\t\tK[0] = indx-indexTree[J].begin();\n\t\t\t\t\t\tKboxNumber = 4*b+1;\n\t\t\t\t\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\t\t\t\t\tK[1] = indx-indexTree[J].begin();\n\t\t\t\t\t\tKboxNumber = 4*b+2;\n\t\t\t\t\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\t\t\t\t\tK[2] = indx-indexTree[J].begin();\n\t\t\t\t\t\tKboxNumber = 4*b+3;\n\t\t\t\t\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\t\t\t\t\tK[3] = indx-indexTree[J].begin();\n\n\t\t\t\t\t\tfor (int c=0; c<4; ++c) {\n\t\t\t\t\t\t\t//Block containing n elements, starting at position i: vector.segment(i,n)\n\t\t\t\t\t\t\tfor (int i = 0; i < tree[J][K[c]].chargeLocations.size(); i++) {\n\t\t\t\t\t\t\t\ttree[j][k].chargeLocations.push_back(tree[J][K[c]].chargeLocations[i]);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tvoid assignLeafChebNodes() {\n\t\t\tfor (size_t k = 0; k < leafNodes.size(); k++) {\n\t\t\t\tint j = leafNodes[k].x;\n\t\t\t\tint b = leafNodes[k].y;\n\t\t\t\tshift_scale_Nodes(standardChebNodes, tree[j][b].chebNodes, tree[j][b].center.x, tree[j][b].center.y, boxRadius[j]);\n\t\t\t}\n\t\t}\n\n\t\tdouble errInApproximation(Eigen::VectorXd& trueValue, Eigen::VectorXd& approximateValue) {\n\t\t\tEigen::VectorXd error(trueValue.size());\n\t\t\tfor (int k=0; k<trueValue.size(); ++k) {\n\t\t\t\terror(k)\t=\tfabs(trueValue(k)-approximateValue(k));\n\t\t\t\t//error(k)\t=\tfabs((trueValue-approximateValue)(k)/trueValue(k));\n\t\t\t}\n\t\t\treturn error.maxCoeff();///trueValue.maxCoeff();\n\t\t}\n\n\t\tdouble errInApproximation(Vec& trueValue, Vec& approximateValue) {\n\t\t\tVec error;\n\t\t\terror = trueValue - approximateValue;\n\t\t\tVectorXd errorAbs = error.cwiseAbs();\n\t\t\tVectorXd trueValueAbs = trueValue.cwiseAbs();\n\t\t\treturn errorAbs.maxCoeff();///trueValueAbs.maxCoeff();\n\t\t}\n\n\t\tvoid EvaluateContrastAtNodes(Eigen::VectorXd& contrastAtChebNodes, std::vector<pts2D>& Nodes) {\n\t\t\tcontrastAtChebNodes = Eigen::VectorXd(Nodes.size());\n\t\t\tfor (size_t i = 0; i < Nodes.size(); i++) {\n\t\t\t\tcontrastAtChebNodes(i) = Q->ContrastFunction(Nodes[i]);\n\t\t\t}\n\t\t}\n\n\t\tvoid EvaluateRHSAtNodes(Vec& RHSAtChebNodes, std::vector<pts2D>& Nodes) {\n\t\t\tRHSAtChebNodes = Vec(Nodes.size());\n\t\t\tfor (size_t i = 0; i < Nodes.size(); i++) {\n\t\t\t\tRHSAtChebNodes(i) = Q->RHSFunction(Nodes[i]);\n\t\t\t}\n\t\t}\n\n\t\tvoid writeMToFile(std::string filename) {\n\t\t\t//create directory\n\t\t\tMFilename = \"M\";\n\t\t\tstring currPath = std::filesystem::current_path();\n\t\t\tchar final1[256];\n\t\t  sprintf (final1, \"%s/%s\", currPath.c_str(), MFilename.c_str());\n\t\t  mkdir(final1, 0775);\n\n\t\t\tMFilename = \"M/M_\" + std::to_string(nChebNodes) + \"_\" + std::to_string(int(kappa)) + \"_\" + std::to_string(degreeOfBases);\n\t\t\tchar final2[256];\n\t\t  sprintf (final2, \"%s/%s\", currPath.c_str(), MFilename.c_str());\n\t\t  mkdir(final2, 0775);\n\n\t\t\tfilename = MFilename + \"/M_\" + std::to_string(nChebNodes) + \"_\" + std::to_string(L);\n\t\t\tfor (size_t l = 0; l < M.size(); l++) {\n\t\t\t\tstring filenameModified = filename + \"_\" + std::to_string(l);\n\t\t\t\tstd::ofstream myfile;\n\t\t\t\tmyfile.open(filenameModified.c_str());\n\t\t\t\tmyfile << M[l] << endl;\n\t\t\t}\n\t\t}\n\n\t\tvoid ReadFromTextFile(Mat &matrix ,std::string filename) {\n\t\t\tstd::ifstream inFile (filename,std::ios::in);\n\t\t\tif(!inFile.good()) {\n\t\t\t\tstd::cout<<\"Error: could not open file:\\\"\"<<filename<<\"\\\"for reading \\n\";\n\t\t\t\texit (2);\n\t\t\t}\n\t\t\t//find the no of values in file\n\t\t\tstd::istream_iterator<std::string> in{inFile};\n\t\t\tstd::istream_iterator<std::string> end;\n\t\t\tlong numberofWords=std::distance(in,end);\n\t\t\t//find the no of lines in file\n\t\t\tinFile.clear();\n\t\t\tinFile.seekg(0,std::ios::beg);\n\t\t\tlong numberofLines=std::count(std::istreambuf_iterator<char>(inFile),std::istreambuf_iterator<char>(),'\\n');\n\t\t\t//std::cout<<\"no. of words : \"<<numberofWords<<\"numberofLines: \"<<numberofLines<<std::endl;\n\t\t\tlong rows=numberofLines;\n\t\t\tlong cols=numberofWords/numberofLines;\n\t\t\tif(rows*cols!=numberofWords) {\n\t\t\t\tstd::cout<<\"\\n Infile\"<<filename<<\"cannot form a matrix \\n\";\n\t\t\t\texit(2);\n\t\t\t}\n\t\t\tmatrix.array().resize(rows,cols);\n\t\t\t//matrix Base does not allow resizing ...hence change array base\n\t\t\tinFile.clear();\n\t\t\tinFile.seekg(0,std::ios::beg);\n\t\t\tfor(unsigned int i=0;i<matrix.rows();i++)\n\t\t\t for(unsigned int j=0;j<matrix.cols();j++)\n\t\t\t\t inFile>>matrix(i,j);\n\t\t\tinFile.close();\n\t\t}\n\n\t\tvoid readMFromFile(std::string filename) {\n\t\t\tstd::vector<Mat> M2;\n\t\t\tMFilename = \"M/M_\" + std::to_string(nChebNodes) + \"_\" + std::to_string(int(kappa)) + \"_\" + std::to_string(degreeOfBases);\n\t\t\tfilename = MFilename + \"/M_\" + std::to_string(nChebNodes) + \"_\" + std::to_string(L);\n\t\t\tfor (size_t l = 0; l <= nLevels; l++) {\n\t\t\t\tstring filenameModified = filename + \"_\" + std::to_string(l);\n\t\t\t\tMat m;\n\t\t\t\tReadFromTextFile(m ,filenameModified);\n\t\t\t\tM.push_back(m);\n\t\t\t}\n\t\t}\n\n\t\tvoid outputAdaptiveGrid(std::string filename) {\n\t\t\tdouble xcenter = 0.0;\n\t\t\tdouble ycenter = 0.0;\n\t\t\tdouble Lx = L;\n\t\t\tdouble Ly = L;\n\n\t\t\tstd::ofstream myfile;\n\t\t\tmyfile.open(filename.c_str());\n\t\t\tmyfile << \"\\\\documentclass{standalone}\" << std::endl;\n\t\t\tmyfile << \"\\\\usepackage{tikz}\" << std::endl;\n\t\t\tmyfile << \"\\\\begin{document}\" << std::endl;\n\t\t\tmyfile << \"\\\\begin{tikzpicture}\" << std::endl;\n\t\t\tfor (int k=0; k<(int)leafNodes.size(); ++k) {\n\t\t\t\tint j = leafNodes[k].x;\n\t\t\t\tint b = leafNodes[k].y;\n\t\t\t\tmyfile << \"\\\\draw (\" << tree[j][b].center.x-tree[j][b].radius << \",\";\n\t\t\t\tmyfile << tree[j][b].center.y-tree[j][b].radius << \") rectangle (\";\n\t\t\t\t//myfile << tree[j][b].center.y-tree[j][b].radius << \") rectangle node{\\\\tiny \" << b << \"} (\";\n\t\t\t\t//myfile << tree[j][b].center.y-tree[j][b].radius << \") rectangle node{\\\\tiny \" << tree[j][b].boxNumber << \"} (\";\n\t\t\t\tmyfile << tree[j][b].center.x+tree[j][b].radius << \",\";\n\t\t\t\tmyfile << tree[j][b].center.y+tree[j][b].radius << \");\" << std::endl;\n\t\t\t}\n\t\t\tlong double push\t=\t0.125;\n\t\t\tmyfile<< \"\\\\node at (\" << xcenter-Lx-push << \",\" << ycenter-Ly-push << \") {\\\\tiny$(\" << xcenter-Lx << \",\" << ycenter-Ly << \")$};\" << std::endl;\n\t\t\tmyfile<< \"\\\\node at (\" << xcenter-Lx-push << \",\" << ycenter+Ly+push << \") {\\\\tiny$(\" << xcenter-Lx << \",\" << ycenter+Ly << \")$};\" << std::endl;\n\t\t\tmyfile<< \"\\\\node at (\" << xcenter+Lx+push << \",\" << ycenter-Ly-push << \") {\\\\tiny$(\" << xcenter+Lx << \",\" << ycenter-Ly << \")$};\" << std::endl;\n\t\t\tmyfile<< \"\\\\node at (\" << xcenter+Lx+push << \",\" << ycenter+Ly+push << \") {\\\\tiny$(\" << xcenter+Lx << \",\" << ycenter+Ly << \")$};\" << std::endl;\n\t\t\tmyfile << \"\\\\end{tikzpicture}\" << std::endl;\n\t\t\tmyfile << \"\\\\end{document}\" << std::endl;\n\t\t\tmyfile.close();\n\t\t}\n\t\t//////////////////////////////////////////////////////////////\n\n\tdouble find_distance(int j1, int k1, int j2, int k2) {\n\t\tpts2D r1 = tree[j1][k1].center;\n\t\tpts2D r2 = tree[j2][k2].center;\n\t\treturn\tsqrt((r1.x-r2.x)*(r1.x-r2.x) + (r1.y-r2.y)*(r1.y-r2.y));\n\t}\n\n\tvoid assign_Child_Interaction(int c, int j, int k) {\n\t\t// j: level\n\t\t// k: parent box\n\t\tint parentboxNumber = tree[j][k].boxNumber;\n\t\tint boxA = 4*parentboxNumber+c;//child box number; its index=?\n\t\tstd::vector<int>::iterator indx = std::find(indexTree[j+1].begin(), indexTree[j+1].end(), boxA);\n\t\tint boxA_index = indx-indexTree[j+1].begin();\n\t\tfor (int n=0; n<tree[j][k].neighborNumbers.size(); ++n) {//parents neighbors; so u need its index to access it which is k\n\t\t\t//children of neighbors of parent which are not neighbors to child=IL\n\t\t\tint pnj = tree[j][k].neighborNumbers[n].x;//level\n\t\t\tint pni = tree[j][k].neighborNumbers[n].y;//index\n\t\t\tint pnn = tree[pnj][pni].boxNumber;//boxNumber\n\t\t\tif (j+1 >= level_LFR || (j+1 < level_LFR && tree[j+1][boxA_index].isLeaf)) { //LFR\n\t\t\t\tif (tree[pnj][pni].isLeaf) {\n\t\t\t\t\tif ( fabs(tree[j+1][boxA_index].center.x - tree[pnj][pni].center.x) >= 3.0*boxRadius[j+1] + boxRadius[pnj]-epsilonRoundOff\n\t\t\t\t\t || fabs(tree[j+1][boxA_index].center.y - tree[pnj][pni].center.y) >= 3.0*boxRadius[j+1] + boxRadius[pnj]-epsilonRoundOff) {\n\t\t\t\t\t\t orderedPair op;\n\t\t\t\t\t\t op.x = pnj;\n\t\t\t\t\t\t op.y = pni;\n\t\t\t\t\t\t tree[j+1][boxA_index].InteractionList.push_back(op);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\torderedPair op;\n\t\t\t\t\t\top.x = pnj;\n\t\t\t\t\t\top.y = pni;\n\t\t\t\t\t\ttree[j+1][boxA_index].neighborNumbers.push_back(op);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tfor (int nc=0; nc<4; ++nc) { //children of parents neighbors\n\t\t\t\t\t\tint boxB = 4*pnn+nc;//its index=?\n\t\t\t\t\t\tstd::vector<int>::iterator indx = std::find(indexTree[j+1].begin(), indexTree[j+1].end(), boxB);\n\t\t\t\t\t\tint boxB_index = indx-indexTree[j+1].begin();\n\t\t\t\t\t\tif ( fabs(tree[j+1][boxA_index].center.x - tree[pnj+1][boxB_index].center.x) >= 3.0*boxRadius[j+1] + boxRadius[pnj+1]-epsilonRoundOff\n\t\t\t\t\t\t || fabs(tree[j+1][boxA_index].center.y - tree[pnj+1][boxB_index].center.y) >= 3.0*boxRadius[j+1] + boxRadius[pnj+1]-epsilonRoundOff) {\n\t\t\t\t\t\t\t orderedPair op;\n\t\t\t\t\t\t\t op.x = pnj+1;\n\t\t\t\t\t\t\t op.y = boxB_index;\n\t\t\t\t\t\t\t tree[j+1][boxA_index].InteractionList.push_back(op);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tif (!tree[j+1][boxA_index].isLeaf) {\n\t\t\t\t\t\t\t\torderedPair op;\n\t\t\t\t\t\t\t\top.x = pnj+1;\n\t\t\t\t\t\t\t\top.y = boxB_index;\n\t\t\t\t\t\t\t\ttree[j+1][boxA_index].neighborNumbers.push_back(op);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tint pj = pnj+1;\n\t\t\t\t\t\t\t\tint pk = boxB_index;\n\n\t\t\t\t\t\t\t\tstd::vector<orderedPair> futureGeneration;\n\t\t\t\t\t\t\t\tgetFutureGeneration_LFR(j+1, boxA_index, pj, pk, futureGeneration);\n\t\t\t\t\t\t\t\tfor (size_t d = 0; d < futureGeneration.size(); d++) {\n\t\t\t\t\t\t\t\t\ttree[j+1][boxA_index].neighborNumbers.push_back(futureGeneration[d]);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse { //HFR\n\t\t\t\tif (tree[pnj][pni].isLeaf) {\n\t\t\t\t\tif ( fabs(tree[j+1][boxA_index].center.x - tree[pnj][pni].center.x) >= kappa*boxRadius[j+1]*boxRadius[j+1] + boxRadius[j+1] + boxRadius[pnj]-epsilonRoundOff\n\t\t\t\t\t || fabs(tree[j+1][boxA_index].center.y - tree[pnj][pni].center.y) >= kappa*boxRadius[j+1]*boxRadius[j+1] + boxRadius[j+1] + boxRadius[pnj]-epsilonRoundOff) {\n\t\t\t\t\t\t\tdouble arg = atan2(tree[j+1][boxA_index].center.y-tree[pnj][pni].center.y, tree[j+1][boxA_index].center.x-tree[pnj][pni].center.x);\n\t \t\t\t\t\t\targ = fmod(arg+2*PI+PI, 2*PI);\n\t \t\t\t\t\t\tint coneNum = int(arg/ConeAperture[j+1]);\n\t\t\t\t\t\t\torderedPair op;\n\t\t\t\t\t\t\top.x = pnj;\n\t\t\t\t\t\t\top.y = pni;\n\t\t\t\t\t\t\ttree[j+1][boxA_index].ConeTree[coneNum].InteractionList.push_back(op);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\torderedPair op;\n\t\t\t\t\t\top.x = pnj;\n\t\t\t\t\t\top.y = pni;\n\t\t\t\t\t\ttree[j+1][boxA_index].neighborNumbers.push_back(op);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tfor (int nc=0; nc<4; ++nc) { //children of parents neighbors\n\t\t\t\t\t\tint boxB = 4*pnn+nc;//its index=?\n\t\t\t\t\t\tstd::vector<int>::iterator indx = std::find(indexTree[j+1].begin(), indexTree[j+1].end(), boxB);\n\t\t\t\t\t\tint boxB_index = indx-indexTree[j+1].begin();\n\t\t\t\t\t\tif ( fabs(tree[j+1][boxA_index].center.x - tree[pnj+1][boxB_index].center.x) >= kappa*boxRadius[j+1]*boxRadius[j+1] + boxRadius[j+1] + boxRadius[pnj+1]-epsilonRoundOff\n\t\t\t\t\t\t || fabs(tree[j+1][boxA_index].center.y - tree[pnj+1][boxB_index].center.y) >= kappa*boxRadius[j+1]*boxRadius[j+1] + boxRadius[pnj+1]-epsilonRoundOff) {\n\t\t\t\t\t\t\t double arg = atan2(tree[j+1][boxA_index].center.y-tree[pnj+1][boxB_index].center.y, tree[j+1][boxA_index].center.x-tree[pnj+1][boxB_index].center.x);\n\t \t \t\t\t\t\t\targ = fmod(arg+2*PI+PI, 2*PI);\n\t \t \t\t\t\t\t\tint coneNum = int(arg/ConeAperture[j+1]);\n\t \t\t\t\t\t\t\torderedPair op;\n\t \t\t\t\t\t\t\top.x = pnj+1;\n\t \t\t\t\t\t\t\top.y = boxB_index;\n\t \t\t\t\t\t\t\ttree[j+1][boxA_index].ConeTree[coneNum].InteractionList.push_back(op);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\torderedPair op;\n\t\t\t\t\t\t\top.x = pnj+1;\n\t\t\t\t\t\t\top.y = boxB_index;\n\t\t\t\t\t\t\ttree[j+1][boxA_index].neighborNumbers.push_back(op);\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\t//\tAssigns the interactions for the children of a box\n\tvoid assign_Box_Interactions(int j, int k) {\n\t\tif (!tree[j][k].isLeaf) {\n\t\t\t//#pragma omp parallel for\n\t\t\tfor (int c=0; c<4; ++c) {\n\t\t\t\tassign_Child_Interaction(c,j,k);\n\t\t\t}\n\t\t}\n\t}\n\n\t//\tAssigns the interactions for the children all boxes at a given level\n\tvoid assign_Level_Interactions(int j) {\n\t\t//#pragma omp parallel for\n\t\tfor (int k=0; k<tree[j].size(); ++k) {\n\t\t\tassign_Box_Interactions(j,k);//k is index number of box in tree[j] vector\n\t\t}\n\t}\n\n\t//\tAssigns the interactions for the children all boxes in the tree\n\tvoid assign_Tree_Interactions() {\n\t\t//j=0, no neighbors, no IL\n\t\t//j=1, no IL, neighbors yes\n\t\t//neighbor includes self\n\t\tint j = 1;\n\t\tfor (int c=0; c<4; ++c) {\n\t\t\tfor (int n=0; n<4; ++n) {\n\t\t\t\torderedPair op;\n\t\t\t\top.x = 1;\n\t\t\t\top.y = n;\n\t\t\t\ttree[j][c].neighborNumbers.push_back(op);\n\t\t\t}\n\t\t}\n\t\tfor (j=1; j<=nLevels-1; ++j) {\n\t\t\tassign_Level_Interactions(j);\n\t\t}\n\t}\n\n\tvoid getNeighbors() {//with respect to unit box at origin; this is assumed to leaf\n\t\t//for a leaf at level_A; the centers need to scaled up by boxRadius[level_A]\n\t\tFF->evaluateQ(Q_pinv);\n\n\t\tfor (size_t i = 0; i < 20; i++) {\n\t\t\tSFN_angles[i] = atan2(SFN_centers[i].y, SFN_centers[i].x);\n\t\t}\n\t\tfor (size_t i = 0; i < 9; i++) {\n\t\t\tN_angles[i] = atan2(N_centers[i].y, N_centers[i].x);\n\t\t}\n\t\tfor (size_t i = 0; i < 12; i++) {\n\t\t\tFN_angles[i] = atan2(FN_centers[i].y, FN_centers[i].x);\n\t\t}\n\t\tfor (size_t i = 0; i < 12; i++) {\n\t\t\tCN_angles[i] = atan2(CN_centers[i].y, CN_centers[i].x);\n\t\t}\n\t  /*\n\t\tdouble SFN_angles[20]= {5.0*PI/4.0,\n\t                    3.0*PI/2.0 - arctan(1.5, 2.5),\n\t                    3.0*PI/2.0 - arctan(0.5, 2.5),\n\t                    3.0*PI/2.0 + arctan(0.5, 2.5),\n\t                    3.0*PI/2.0 + arctan(1.5, 2.5),\n\t                    7.0*PI/4.0,\n\t                    2*PI - arctan(1.5, 2.5),\n\t                    2*PI - arctan(0.5, 2.5),\n\t                    arctan(0.5, 2.5),\n\t                    arctan(1.5, 2.5),\n\t                    PI/4.0,\n\t                    PI/2.0 - arctan(1.5, 2.5),\n\t                    PI/2.0 - arctan(0.5, 2.5),\n\t                    PI/2.0 + arctan(0.5, 2.5),\n\t                    PI/2.0 + arctan(1.5, 2.5),\n\t                    3.0*PI/4.0,\n\t                    PI - arctan(1.5, 2.5),\n\t                    PI - arctan(0.5, 2.5),\n\t                    PI + arctan(0.5, 2.5),\n\t                    PI + arctan(1.5, 2.5)\n\t                    };\n\n\t  double N_angles[9] = {5.0*PI/4.0, 3.0*PI/2.0, 7.0*PI/4.0, 0.0, PI/4.0, PI/2.0, 3.0*PI/4.0, PI, 0.0};\n\t  double FN_angles[12] = {5.0*PI/4.0,\n\t                          3.0*PI/2.0 - arctan(1.0, 3.0),\n\t                          3.0*PI/2.0 + arctan(1.0, 3.0),\n\t                          7.0*PI/4.0,\n\t                          2.0*PI - arctan(1.0, 3.0),\n\t                          arctan(1.0, 3.0),\n\t                          PI/4.0,\n\t                          PI/2.0 - arctan(1.0, 3.0),\n\t                          PI/2.0 + arctan(1.0, 3.0),\n\t                          3.0*PI/4.0,\n\t                          PI - arctan(1.0, 3.0),\n\t                          PI + arctan(1.0, 3.0)\n\t                         };\n\t  double CN_angles[12] = {5.0*PI/4.0,\n\t                          3.0*PI/2.0 - arctan(0.5, 1.5),\n\t                          3.0*PI/2.0 + arctan(0.5, 1.5),\n\t                          7.0*PI/4.0,\n\t                          2.0*PI - arctan(0.5, 1.5),\n\t                          arctan(0.5, 1.5),\n\t                          PI/4.0,\n\t                          arctan(1.5, 0.5),\n\t                          PI/2.0 + arctan(0.5, 1.5),\n\t                          3.0*PI/4.0,\n\t                          PI - arctan(0.5, 1.5),\n\t                          PI + arctan(0.5, 1.5)\n\t\t\t\t\t\t\t\t\t\t\t\t\t};\n\t\t*/\n\t  for (size_t j = 1; j <= nLevels; j++) {\n\t    for (size_t k = 0; k < tree[j].size(); k++) {\n\t      for (size_t n = 0; n < tree[j][k].neighborNumbers.size(); n++) {\n\t        int nj = tree[j][k].neighborNumbers[n].x;\n\t        int nk = tree[j][k].neighborNumbers[n].y;\n\t        double angle = atan2(tree[nj][nk].center.y-tree[j][k].center.y, tree[nj][nk].center.x-tree[j][k].center.x);\n\t        if (tree[j][k].radius == tree[nj][nk].radius) {\n\t\t\t\t\t\tif (fabs(tree[nj][nk].center.y-tree[j][k].center.y)<epsilonRoundOff && fabs(tree[nj][nk].center.x-tree[j][k].center.x)<epsilonRoundOff) {\n\t\t\t\t\t\t\ttree[j][k].colleagueNeighbors[8] = tree[j][k].neighborNumbers[n].y;\n\t\t\t\t\t\t} // self\n\t          else if (fabs(N_angles[0] - angle) < epsilonRoundOff) {\n\t            tree[j][k].colleagueNeighbors[0] = tree[j][k].neighborNumbers[n].y;\n\t          }\n\t          else if (fabs(N_angles[1] - angle) < epsilonRoundOff) {\n\t            tree[j][k].colleagueNeighbors[1] = tree[j][k].neighborNumbers[n].y;\n\t          }\n\t          else if (fabs(N_angles[2] - angle) < epsilonRoundOff) {\n\t            tree[j][k].colleagueNeighbors[2] = tree[j][k].neighborNumbers[n].y;\n\t          }\n\t          else if (fabs(N_angles[3] - angle) < epsilonRoundOff) {\n\t            tree[j][k].colleagueNeighbors[3] = tree[j][k].neighborNumbers[n].y;\n\t          }\n\t          else if (fabs(N_angles[4] - angle) < epsilonRoundOff) {\n\t            tree[j][k].colleagueNeighbors[4] = tree[j][k].neighborNumbers[n].y;\n\t          }\n\t          else if (fabs(N_angles[5] - angle) < epsilonRoundOff) {\n\t            tree[j][k].colleagueNeighbors[5] = tree[j][k].neighborNumbers[n].y;\n\t          }\n\t          else if (fabs(N_angles[6] - angle) < epsilonRoundOff) {\n\t            tree[j][k].colleagueNeighbors[6] = tree[j][k].neighborNumbers[n].y;\n\t          }\n\t          else if (fabs(N_angles[7] - angle) < epsilonRoundOff) {\n\t            tree[j][k].colleagueNeighbors[7] = tree[j][k].neighborNumbers[n].y;\n\t          }\n\t        }\n\t        else if (tree[j][k].radius < tree[nj][nk].radius) { //coarse neighbors\n\t          if (fabs(CN_angles[0] - angle) < epsilonRoundOff) {\n\t            tree[j][k].coarseNeighbors[0] = tree[j][k].neighborNumbers[n].y;\n\t          }\n\t          else if (fabs(CN_angles[1] - angle) < epsilonRoundOff) {\n\t            tree[j][k].coarseNeighbors[1] = tree[j][k].neighborNumbers[n].y;\n\t          }\n\t          else if (fabs(CN_angles[2] - angle) < epsilonRoundOff) {\n\t            tree[j][k].coarseNeighbors[2] = tree[j][k].neighborNumbers[n].y;\n\t          }\n\t          else if (fabs(CN_angles[3] - angle) < epsilonRoundOff) {\n\t            tree[j][k].coarseNeighbors[3] = tree[j][k].neighborNumbers[n].y;\n\t          }\n\t          else if (fabs(CN_angles[4] - angle) < epsilonRoundOff) {\n\t            tree[j][k].coarseNeighbors[4] = tree[j][k].neighborNumbers[n].y;\n\t          }\n\t          else if (fabs(CN_angles[5] - angle) < epsilonRoundOff) {\n\t            tree[j][k].coarseNeighbors[5] = tree[j][k].neighborNumbers[n].y;\n\t          }\n\t          else if (fabs(CN_angles[6] - angle) < epsilonRoundOff) {\n\t            tree[j][k].coarseNeighbors[6] = tree[j][k].neighborNumbers[n].y;\n\t          }\n\t          else if (fabs(CN_angles[7] - angle) < epsilonRoundOff) {\n\t            tree[j][k].coarseNeighbors[7] = tree[j][k].neighborNumbers[n].y;\n\t          }\n\t          else if (fabs(CN_angles[8] - angle) < epsilonRoundOff) {\n\t            tree[j][k].coarseNeighbors[8] = tree[j][k].neighborNumbers[n].y;\n\t          }\n\t          else if (fabs(CN_angles[9] - angle) < epsilonRoundOff) {\n\t            tree[j][k].coarseNeighbors[9] = tree[j][k].neighborNumbers[n].y;\n\t          }\n\t          else if (fabs(CN_angles[10] - angle) < epsilonRoundOff) {\n\t            tree[j][k].coarseNeighbors[10] = tree[j][k].neighborNumbers[n].y;\n\t          }\n\t          else if (fabs(CN_angles[11] - angle) < epsilonRoundOff) {\n\t            tree[j][k].coarseNeighbors[11] = tree[j][k].neighborNumbers[n].y;\n\t          }\n\t        }\n\t        else { //fine neighbors and separated fine neighbors\n\t           if (find_distance(j, k, nj, nk) > 2.5*tree[j][k].radius) { //separated fine neighbors\n\t             if (fabs(SFN_angles[0] - angle) < epsilonRoundOff) {\n\t               tree[j][k].separatedFineNeighbors[0] = tree[j][k].neighborNumbers[n].y;\n\t             }\n\t             else if (fabs(SFN_angles[1] - angle) < epsilonRoundOff) {\n\t               tree[j][k].separatedFineNeighbors[1] = tree[j][k].neighborNumbers[n].y;\n\t             }\n\t             else if (fabs(SFN_angles[2] - angle) < epsilonRoundOff) {\n\t               tree[j][k].separatedFineNeighbors[2] = tree[j][k].neighborNumbers[n].y;\n\t             }\n\t             else if (fabs(SFN_angles[3] - angle) < epsilonRoundOff) {\n\t               tree[j][k].separatedFineNeighbors[3] = tree[j][k].neighborNumbers[n].y;\n\t             }\n\t             else if (fabs(SFN_angles[4] - angle) < epsilonRoundOff) {\n\t               tree[j][k].separatedFineNeighbors[4] = tree[j][k].neighborNumbers[n].y;\n\t             }\n\t             else if (fabs(SFN_angles[5] - angle) < epsilonRoundOff) {\n\t               tree[j][k].separatedFineNeighbors[5] = tree[j][k].neighborNumbers[n].y;\n\t             }\n\t             else if (fabs(SFN_angles[6] - angle) < epsilonRoundOff) {\n\t               tree[j][k].separatedFineNeighbors[6] = tree[j][k].neighborNumbers[n].y;\n\t             }\n\t             else if (fabs(SFN_angles[7] - angle) < epsilonRoundOff) {\n\t               tree[j][k].separatedFineNeighbors[7] = tree[j][k].neighborNumbers[n].y;\n\t             }\n\t             else if (fabs(SFN_angles[8] - angle) < epsilonRoundOff) {\n\t               tree[j][k].separatedFineNeighbors[8] = tree[j][k].neighborNumbers[n].y;\n\t             }\n\t             else if (fabs(SFN_angles[9] - angle) < epsilonRoundOff) {\n\t               tree[j][k].separatedFineNeighbors[9] = tree[j][k].neighborNumbers[n].y;\n\t             }\n\t             else if (fabs(SFN_angles[10] - angle) < epsilonRoundOff) {\n\t               tree[j][k].separatedFineNeighbors[10] = tree[j][k].neighborNumbers[n].y;\n\t             }\n\t             else if (fabs(SFN_angles[11] - angle) < epsilonRoundOff) {\n\t               tree[j][k].separatedFineNeighbors[11] = tree[j][k].neighborNumbers[n].y;\n\t             }\n\t             else if (fabs(SFN_angles[12] - angle) < epsilonRoundOff) {\n\t               tree[j][k].separatedFineNeighbors[12] = tree[j][k].neighborNumbers[n].y;\n\t             }\n\t             else if (fabs(SFN_angles[13] - angle) < epsilonRoundOff) {\n\t               tree[j][k].separatedFineNeighbors[13] = tree[j][k].neighborNumbers[n].y;\n\t             }\n\t             else if (fabs(SFN_angles[14] - angle) < epsilonRoundOff) {\n\t               tree[j][k].separatedFineNeighbors[14] = tree[j][k].neighborNumbers[n].y;\n\t             }\n\t             else if (fabs(SFN_angles[15] - angle) < epsilonRoundOff) {\n\t               tree[j][k].separatedFineNeighbors[15] = tree[j][k].neighborNumbers[n].y;\n\t             }\n\t             else if (fabs(SFN_angles[16] - angle) < epsilonRoundOff) {\n\t               tree[j][k].separatedFineNeighbors[16] = tree[j][k].neighborNumbers[n].y;\n\t             }\n\t             else if (fabs(SFN_angles[17] - angle) < epsilonRoundOff) {\n\t               tree[j][k].separatedFineNeighbors[17] = tree[j][k].neighborNumbers[n].y;\n\t             }\n\t             else if (fabs(SFN_angles[18] - angle) < epsilonRoundOff) {\n\t               tree[j][k].separatedFineNeighbors[18] = tree[j][k].neighborNumbers[n].y;\n\t             }\n\t             else {\n\t               tree[j][k].separatedFineNeighbors[19] = tree[j][k].neighborNumbers[n].y;\n\t             }\n\t           }\n\t           else {//fine neighbors\n\t             if (fabs(FN_angles[0] - angle) < epsilonRoundOff) {\n\t               tree[j][k].fineNeighbors[0] = tree[j][k].neighborNumbers[n].y;\n\t             }\n\t             else if (fabs(FN_angles[1] - angle) < epsilonRoundOff) {\n\t               tree[j][k].fineNeighbors[1] = tree[j][k].neighborNumbers[n].y;\n\t             }\n\t             else if (fabs(FN_angles[2] - angle) < epsilonRoundOff) {\n\t               tree[j][k].fineNeighbors[2] = tree[j][k].neighborNumbers[n].y;\n\t             }\n\t             else if (fabs(FN_angles[3] - angle) < epsilonRoundOff) {\n\t               tree[j][k].fineNeighbors[3] = tree[j][k].neighborNumbers[n].y;\n\t             }\n\t             else if (fabs(FN_angles[4] - angle) < epsilonRoundOff) {\n\t               tree[j][k].fineNeighbors[4] = tree[j][k].neighborNumbers[n].y;\n\t             }\n\t             else if (fabs(FN_angles[5] - angle) < epsilonRoundOff) {\n\t               tree[j][k].fineNeighbors[5] = tree[j][k].neighborNumbers[n].y;\n\t             }\n\t             else if (fabs(FN_angles[6] - angle) < epsilonRoundOff) {\n\t               tree[j][k].fineNeighbors[6] = tree[j][k].neighborNumbers[n].y;\n\t             }\n\t             else if (fabs(FN_angles[7] - angle) < epsilonRoundOff) {\n\t               tree[j][k].fineNeighbors[7] = tree[j][k].neighborNumbers[n].y;\n\t             }\n\t             else if (fabs(FN_angles[8] - angle) < epsilonRoundOff) {\n\t               tree[j][k].fineNeighbors[8] = tree[j][k].neighborNumbers[n].y;\n\t             }\n\t             else if (fabs(FN_angles[9] - angle) < epsilonRoundOff) {\n\t               tree[j][k].fineNeighbors[9] = tree[j][k].neighborNumbers[n].y;\n\t             }\n\t             else if (fabs(FN_angles[10] - angle) < epsilonRoundOff) {\n\t               tree[j][k].fineNeighbors[10] = tree[j][k].neighborNumbers[n].y;\n\t             }\n\t             else if (fabs(FN_angles[11] - angle) < epsilonRoundOff) {\n\t               tree[j][k].fineNeighbors[11] = tree[j][k].neighborNumbers[n].y;\n\t             }\n\t           }\n\t        }\n\t      }\n\t    }\n\t  }\n\t}\n\n\t/*\n\t//the following function is for helmholtz kernel(uses getMatrixEntry)\n\tvoid getOperator(int level_A, int level_B, pts2D center_B, pts2D center_A, Mat &matOperator) {\n\t\tstd::vector<pts2D> Nodes_A;\n\t\tshift_scale_Nodes(standardChebNodes, Nodes_A, center_A.x, center_A.y, boxRadius[level_A]);\n\t\tstd::vector<pts2D> Nodes_B;\n\t\tshift_scale_Nodes(standardChebNodes, Nodes_B, center_B.x, center_B.y, boxRadius[level_B]);\n\n\t\tmatOperator = Mat::Zero(rank,rank);\n\t\tfor (size_t i = 0; i < rank; i++) {\n\t\t\tfor (size_t j = 0; j < rank; j++) {\n\t\t\t\tdouble R2 = (Nodes_B[j].x-Nodes_A[i].x)*(Nodes_B[j].x-Nodes_A[i].x) + (Nodes_B[j].y-Nodes_A[i].y)*(Nodes_B[j].y-Nodes_A[i].y);\n\t\t\t\tdouble R = sqrt(R2);\n\t\t\t\tif (R < epsilonRoundOff) {\n\t\t\t\t\tmatOperator(i,j) = R;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tmatOperator(i,j) = exp(I*kappa*R)/R;\n\t\t\t\t\t//matOperator(i,j) = 1.0/R;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t*/\n\n\t//the following function is for Lippmann Schwinger problem(uses equations specific for neighbor interactions)\n\tvoid getOperator(int level_A, int level_B, pts2D center_B, pts2D center_A, Mat &matOperator) {\n\t\tintegrandInputs II;\n\t\tII.center_B = center_B;\n\t\tII.center_A = center_A;\n\t\tII.level_A = level_A;\n\t\tII.level_B = level_B;//colleague Neighbor; so same level\n\t\tII.radius_A = boxRadius[level_A];\n\t\tII.radius_B = boxRadius[level_B];\n\t\tNearFieldInteraction1 *NFI1 = new NearFieldInteraction1(nChebNodes, II, degreeOfBases);\n\t\tNearFieldInteraction2 *NFI2 = new NearFieldInteraction2(nChebNodes, II, degreeOfBases);\n\t\tMat V1;\n\t\tMat V2;\n\n\t\t//the following two lines use no expansion of H(0,x); it uses H(0,x)=J(0,x)+iY(0,x)\n\t\tNFI1->evaluateV(V1);\n\t\tMat temp = V1;\n\n\t\t//the following lines use series expansion of H(0,x); it uses series expansion of J(0,x) and Y(0,x)\n\t\t//NFI1->evaluateV1(V1);\n\t\t//NFI2->evaluateV2(V2);\n\t\t//Mat temp = V1+V2;\n\n\n\t\tMat V_temp = temp*I*boxRadius[level_B]*boxRadius[level_B]/4.0;\n\t\t//cout << \"V_temp.size(): \" << V_temp.rows() << \", \" << V_temp.cols() << endl;\n\t\tmatOperator = V_temp*Q_pinv;\n\t\t//cout << \"V1: \" << endl << V1 << endl << endl;\n\t\t//cout << \"V2: \" << endl << V2 << endl << endl;\n\t\t//cout << \"Q_pinv: \" << endl << Q_pinv << endl << endl;\n\t\t//exit(0);\n\t\tdelete NFI1;\n\t\tdelete NFI2;\n\t}\n\n\n\tvoid getNeighborInteractions() {\n\t\t//assume domain is always [-1,1]^{2}\n\t\tfor (size_t level_A = 2; level_A <= 10; level_A++) {\n\t\t\twriteNeighborInteractionsForLevel(level_A);\n\t\t}\n\t}\n\n\tvoid writeNeighborInteractionsForLevel(int level_A) {\n\t\t//B is neighbor of A\n\t\tMat colleagueNeighborInteractionTemp[9];\n\t\tMat fineNeighborInteractionTemp[12];\n\t\tMat separatedFineNeighborInteractionTemp[20];\n\t\tMat coarseNeighborInteractionTemp[12];\n\t\tpts2D center_A;\n\t\tcenter_A.x = 0.0;\n\t\tcenter_A.y = 0.0;\n\t\t//cout << \"level_A: \" << level_A << endl;\n\t\tfor (size_t i = 0; i < 9; i++) { //colleagueNeighbors\n\t\t\tint level_B = level_A;\n\t\t\tpts2D center_B = N_centers[i];\n\t\t\tcenter_B.x *= boxRadius[level_A];\n\t\t\tcenter_B.y *= boxRadius[level_A];\n\t\t\t//cout << \"colleagueNeighbors:\t\" << i;\n\t\t\tgetOperator(level_A, level_B, center_B, center_A, colleagueNeighborInteractionTemp[i]);\n\t\t\t//cout << \"\tdone\" << endl;\n\t\t}\n\t\tfor (size_t i = 0; i < 12; i++) { //coarseNeighbors\n\t\t\tint level_B = level_A-1;\n\t\t\tpts2D center_B = CN_centers[i];\n\t\t\tcenter_B.x *= boxRadius[level_A];\n\t\t\tcenter_B.y *= boxRadius[level_A];\n\t\t\t//cout << \"coarseNeighbors:\t\" << i;\n\t\t\tgetOperator(level_A, level_B, center_B, center_A, coarseNeighborInteractionTemp[i]);\n\t\t\t//cout << \"\tdone\" << endl;\n\t\t}\n\t\tfor (size_t i = 0; i < 20; i++) { //separatedFineNeighbors\n\t\t\tint level_B = level_A+1;\n\t\t\tpts2D center_B = SFN_centers[i];\n\t\t\tcenter_B.x *= boxRadius[level_A];\n\t\t\tcenter_B.y *= boxRadius[level_A];\n\t\t\t//cout << \"separatedFineNeighbors:\t\" << i;\n\t\t\tgetOperator(level_A, level_B, center_B, center_A, separatedFineNeighborInteractionTemp[i]);\n\t\t\t//cout << \"\tdone\" << endl;\n\t\t}\n\t\tfor (size_t i = 0; i < 12; i++) { //fineNeighbors\n\t\t\tint level_B = level_A+1;\n\t\t\tpts2D center_B = FN_centers[i];\n\t\t\tcenter_B.x *= boxRadius[level_A];\n\t\t\tcenter_B.y *= boxRadius[level_A];\n\t\t\t//cout << \"fineNeighbors:\t\" << i;\n\t\t\tgetOperator(level_A, level_B, center_B, center_A, fineNeighborInteractionTemp[i]);\n\t\t\t//cout << \"\tdone\" << endl;\n\t\t}\n\n\t\t//create directory\n\t\tMFilename = \"Neighbor\";\n\t\tstring currPath = std::filesystem::current_path();\n\t\tchar final1[256];\n\t\tsprintf (final1, \"%s/%s\", currPath.c_str(), MFilename.c_str());\n\t\tmkdir(final1, 0775);\n\n\t\tMFilename = \"Neighbor/Neighbor_\" + std::to_string(nChebNodes) + \"_\" + std::to_string(int(kappa)) + \"_\" + std::to_string(degreeOfBases);\n\t\tchar final2[256];\n\t\tsprintf (final2, \"%s/%s\", currPath.c_str(), MFilename.c_str());\n\t\tmkdir(final2, 0775);\n\n\t\t//writeToFile\n\t\tstd::string filename;\n\t\tfilename = MFilename + \"/colleagueNeighborInteraction\";\n\t\tfilename = filename + \"_\" + std::to_string(level_A);\n\t\tfor (size_t n = 0; n < 9; n++) {\n\t\t\tstring filenameModified = filename + \"_\" + std::to_string(n);\n\t\t\tstd::ofstream myfile;\n\t\t\tmyfile.open(filenameModified.c_str());\n\t\t\tmyfile << colleagueNeighborInteractionTemp[n] << endl;\n\t\t}\n\n\t\tfilename = MFilename + \"/fineNeighborInteraction\";\n\t\tfilename = filename + \"_\" + std::to_string(level_A);\n\t\tfor (size_t n = 0; n < 12; n++) {\n\t\t\tstring filenameModified = filename + \"_\" + std::to_string(n);\n\t\t\tstd::ofstream myfile;\n\t\t\tmyfile.open(filenameModified.c_str());\n\t\t\tmyfile << fineNeighborInteractionTemp[n] << endl;\n\t\t}\n\n\t\tfilename = MFilename + \"/separatedFineNeighborInteraction\";\n\t\tfilename = filename + \"_\" + std::to_string(level_A);\n\t\tfor (size_t n = 0; n < 20; n++) {\n\t\t\tstring filenameModified = filename + \"_\" + std::to_string(n);\n\t\t\tstd::ofstream myfile;\n\t\t\tmyfile.open(filenameModified.c_str());\n\t\t\tmyfile << separatedFineNeighborInteractionTemp[n] << endl;\n\t\t}\n\n\t\tfilename = MFilename + \"/coarseNeighborInteraction\";\n\t\tfilename = filename + \"_\" + std::to_string(level_A);\n\t\tfor (size_t n = 0; n < 12; n++) {\n\t\t\tstring filenameModified = filename + \"_\" + std::to_string(n);\n\t\t\tstd::ofstream myfile;\n\t\t\tmyfile.open(filenameModified.c_str());\n\t\t\tmyfile << coarseNeighborInteractionTemp[n] << endl;\n\t\t}\n\t}\n\n\tvoid readNeighborInteractions() {\n\t\tint numberOfLevelOperators = nLevels-2+1;\n\t\tstd::string filename;\n\t\tNeighborFilename = \"Neighbor/Neighbor_\" + std::to_string(nChebNodes) + \"_\" + std::to_string(int(kappa)) + \"_\" + std::to_string(degreeOfBases);\n\t\tfor (size_t level_A = 2; level_A <= nLevels; level_A++) {\n\t\t\tfilename = NeighborFilename + \"/colleagueNeighborInteraction\";\n\t\t\tfilename = filename + \"_\" + std::to_string(level_A);\n\t\t\tfor (size_t n = 0; n < 9; n++) {\n\t\t\t\tstring filenameModified = filename + \"_\" + std::to_string(n);\n\t\t\t\tReadFromTextFile(colleagueNeighborInteraction[level_A-2][n] ,filenameModified);\n\t\t\t}\n\n\t\t\tfilename = NeighborFilename + \"/fineNeighborInteraction\";\n\t\t\tfilename = filename + \"_\" + std::to_string(level_A);\n\t\t\tfor (size_t n = 0; n < 12; n++) {\n\t\t\t\tstring filenameModified = filename + \"_\" + std::to_string(n);\n\t\t\t\tReadFromTextFile(fineNeighborInteraction[level_A-2][n] ,filenameModified);\n\t\t\t}\n\n\t\t\tfilename = NeighborFilename + \"/separatedFineNeighborInteraction\";\n\t\t\tfilename = filename + \"_\" + std::to_string(level_A);\n\t\t\tfor (size_t n = 0; n < 20; n++) {\n\t\t\t\tstring filenameModified = filename + \"_\" + std::to_string(n);\n\t\t\t\tReadFromTextFile(separatedFineNeighborInteraction[level_A-2][n] ,filenameModified);\n\t\t\t}\n\n\t\t\tfilename = NeighborFilename + \"/coarseNeighborInteraction\";\n\t\t\tfilename = filename + \"_\" + std::to_string(level_A);\n\t\t\tfor (size_t n = 0; n < 12; n++) {\n\t\t\t\tstring filenameModified = filename + \"_\" + std::to_string(n);\n\t\t\t\tReadFromTextFile(coarseNeighborInteraction[level_A-2][n] ,filenameModified);\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid createCones() {\n\t\tN = leafNodes.size()*rank;\n\t\tcout << \"level_LFR: \" << level_LFR << endl;\n\t\tcout << \"Number of particles: \" << N << endl;\n\t\tnCones.push_back(nCones_LFR*pow(2.0, level_LFR-1));\n\t\tConeAperture.push_back(2*PI/nCones[0]);\n\t\tfor (size_t j = 1; j <= level_LFR-1; j++) {\n\t\t\tnCones.push_back(nCones[j-1]/2.0);\n\t\t\tConeAperture.push_back(ConeAperture[j-1]*2.0);\n\t\t}\n\t\tfor (size_t j = 0; j <= level_LFR-1; j++) {\n\t\t\tfor (int k=0; k<tree[j].size(); ++k) {\n\t\t\t\tif (!tree[j][k].isLeaf) {\n\t\t\t\t\ttree[j][k].ConeTree.clear();////\n\t\t\t\t\tfor (int c=0; c<nCones[j]; ++c) {\n\t\t\t\t\t\tFMM2DCone cone;\n\t\t\t\t\t\tcone.angle\t=\tConeAperture[j]/2.0 + c*ConeAperture[j];\n\t\t\t\t\t\ttree[j][k].ConeTree.push_back(cone);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid assign_NonLeaf_Charges() {\n\t\tfor (int j=nLevels-1; j>1; --j) {\n\t\t\tint J\t=\tj+1;\n\t\t\t#pragma omp parallel for\n\t\t\tfor (int k=0; k<tree[j].size(); ++k) {\n\t\t\t\tif (!tree[j][k].isLeaf) {\n\t\t\t\t\tint b = tree[j][k].boxNumber;\n\t\t\t\t\tint KboxNumber;\n\t\t\t\t\tint K[4];\n\t\t\t\t\tstd::vector<int>::iterator indx;\n\t\t\t\t\tKboxNumber = 4*b+0;\n\t\t\t\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\t\t\t\tK[0] = indx-indexTree[J].begin();\n\t\t\t\t\tKboxNumber = 4*b+1;\n\t\t\t\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\t\t\t\tK[1] = indx-indexTree[J].begin();\n\t\t\t\t\tKboxNumber = 4*b+2;\n\t\t\t\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\t\t\t\tK[2] = indx-indexTree[J].begin();\n\t\t\t\t\tKboxNumber = 4*b+3;\n\t\t\t\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\t\t\t\tK[3] = indx-indexTree[J].begin();\n\n\t\t\t\t\tint NumCharges = tree[J][K[0]].chargeLocations.size() + tree[J][K[1]].chargeLocations.size() +tree[J][K[2]].chargeLocations.size() + tree[J][K[3]].chargeLocations.size();\n\t\t\t\t\ttree[j][k].multipoles = Vec::Zero(NumCharges);\n\t\t\t\t\tint start = 0;\n\t\t\t\t\tfor (int c=0; c<4; ++c) {\n\t\t\t\t\t\t//Block containing n elements, starting at position i: vector.segment(i,n)\n\t\t\t\t\t\tint NumElem = tree[J][K[c]].chargeLocations.size();\n\t\t\t\t\t\ttree[j][k].multipoles.segment(start, NumElem) = tree[J][K[c]].multipoles;\n\t\t\t\t\t\tstart += NumElem;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid getParticlesFromChildrenLFR_outgoing_col(int j, int k, std::vector<int>& searchNodes) {\n\t\tif (tree[j][k].isLeaf) {\n\t\t\tsearchNodes.insert(searchNodes.end(), tree[j][k].chargeLocations.begin(), tree[j][k].chargeLocations.end());\n\t\t}\n\t\telse {\n\t\t\tint J = j+1;\n\t\t\tint b = tree[j][k].boxNumber;\n\t\t\tfor (int c = 0; c < 4; c++) {\n\t\t\t\tint KboxNumber = 4*b+c;\n\t\t\t\tstd::vector<int>::iterator indx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\t\t\tint K = indx-indexTree[J].begin();\n\t\t\t\tif (J >= level_LFR || (J<level_LFR && tree[J][K].isLeaf)) { //LFR\n\t\t\t\t\tif (tree[J][K].incoming_checkPoints.size() == 0) {\n\t\t\t\t\t\tcout << \"problem LFR_outgoing_row: \" << j << \", \" << k << \", \" << J << \", \" << K << endl;\n\t\t\t\t\t}\n\t\t\t\t\tsearchNodes.insert(searchNodes.end(), tree[J][K].outgoing_chargePoints.begin(), tree[J][K].outgoing_chargePoints.end());\n\t\t\t\t}\n\t\t\t\telse { //HFR\n\t\t\t\t\tfor (size_t cone = 0; cone < nCones[J]; cone++) {\n\t\t\t\t\t\tsearchNodes.insert(searchNodes.end(), tree[J][K].ConeTree[cone].outgoing_chargePoints.begin(), tree[J][K].ConeTree[cone].outgoing_chargePoints.end());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid getParticlesFromChildrenLFR_outgoing_row(int j, int k, std::vector<int>& searchNodes, int j1, int k1) {\n\t\tif (tree[j][k].isLeaf) {\n\t\t\tsearchNodes.insert(searchNodes.end(), tree[j][k].chargeLocations.begin(), tree[j][k].chargeLocations.end());\n\t\t}\n\t\telse {\n\t\t\tint J = j+1;\n\t\t\tint b = tree[j][k].boxNumber;\n\t\t\tfor (int c = 0; c < 4; c++) {\n\t\t\t\tint KboxNumber = 4*b+c;\n\t\t\t\tstd::vector<int>::iterator indx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\t\t\tint K = indx-indexTree[J].begin();\n\t\t\t\tif (J >= level_LFR || (J<level_LFR && tree[J][K].isLeaf)) { //LFR\n\t\t\t\t\tsearchNodes.insert(searchNodes.end(), tree[J][K].incoming_checkPoints.begin(), tree[J][K].incoming_checkPoints.end());\n\t\t\t\t}\n\t\t\t\telse { //HFR\n\t\t\t\t\tfor (size_t cone = 0; cone < nCones[J]; cone++) {\n\t\t\t\t\t\tsearchNodes.insert(searchNodes.end(), tree[J][K].ConeTree[cone].incoming_checkPoints.begin(), tree[J][K].ConeTree[cone].incoming_checkPoints.end());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid getNodes_LFR() {\n\t\tfor (int j=nLevels; j>=2; j--) {\n\t\t\tfor (int k=0; k<tree[j].size(); ++k) {\n\t\t\t\tif (tree[j][k].incoming_chargePoints.size() > 0)\n\t\t\t\t\ttree[j][k].incoming_chargePoints.clear();\n\t\t\t\tif (tree[j][k].incoming_checkPoints.size() > 0)\n\t\t\t\t\ttree[j][k].incoming_checkPoints.clear();\n\t\t\t\tif (tree[j][k].outgoing_chargePoints.size() > 0)\n\t\t\t\t\ttree[j][k].outgoing_chargePoints.clear();\n\t\t\t\tif (tree[j][k].outgoing_checkPoints.size() > 0)\n\t\t\t\t\ttree[j][k].outgoing_checkPoints.clear();\n\t\t\t\tif (tree[j][k].user_checkPoints.size() > 0)\n\t\t\t\t\ttree[j][k].user_checkPoints.clear();\n\t\t\t}\n\t\t}\n\t\tfor (int j=nLevels; j>=level_LFR; j--) {\n\t\t\tgetNodes_LFR_outgoing_level(j);\n\t\t\tgetNodes_LFR_incoming_level(j);\n\t\t}\n\t}\n\n\tvoid getNodes_LFR_outgoing_box(int j, int k, int &n_rows, int &n_cols, int &ComputedRank) {\n\t\tint ILcheck = 0;\n\t\tif (tree[j][k].active == true) {\n\t\t\tstd::vector<int> boxA_Nodes;\n\t\t\tgetParticlesFromChildrenLFR_outgoing_col(j, k, boxA_Nodes);\n\n\t\t\t//sort( boxA_Nodes.begin(), boxA_Nodes.end() );\n\t\t\t//boxA_Nodes.erase( unique( boxA_Nodes.begin(), boxA_Nodes.end() ), boxA_Nodes.end() );\n\n\t\t\tstd::vector<int> IL_Nodes;//indices\n\t\t\tfor (int l=0; l<tree[j][k].InteractionList.size(); ++l) {\n\t\t\t\tint jIL = tree[j][k].InteractionList[l].x;\n\t\t\t\tint kIL = tree[j][k].InteractionList[l].y;\n\t\t\t\tstd::vector<int> chargeLocations;\n\t\t\t\tgetParticlesFromChildrenLFR_outgoing_row(jIL, kIL, chargeLocations, j, k);\n\t\t\t\tIL_Nodes.insert(IL_Nodes.end(), chargeLocations.begin(), chargeLocations.end());\n\t\t\t}\n\n\t\t\t//sort( IL_Nodes.begin(), IL_Nodes.end() );\n\t\t\t//IL_Nodes.erase( unique( IL_Nodes.begin(), IL_Nodes.end() ), IL_Nodes.end() );\n\n\t\t\tn_rows = IL_Nodes.size();\n\t\t\tn_cols = boxA_Nodes.size();\n\t\t\tint tol_pow = TOL_POW;\n\t\t\tdouble tol_ACA = pow(10,-1.0*tol_pow);\n\t\t\trow_indices = IL_Nodes;\n\t\t\tcol_indices = boxA_Nodes;//object of base class LowRank\n\t\t\tstd::vector<int> row_bases, col_bases;\n\t\t\tif (n_rows != 0 && n_cols != 0) {\n\t\t\t\ttree[j][k].ILActive = true;\n\t\t\t\tMat dummy;\n\t\t\t\tACA_only_nodes(row_bases, col_bases, ComputedRank, tol_ACA, dummy, tree[j][k].outgoing_Ar);\n\t\t\t\tint minN = n_rows;\n\t\t\t\tif (n_rows > n_cols) {\n\t\t\t\t\tminN = n_cols;\n\t\t\t\t}\n\t\t\t\tfor (int r = 0; r < row_bases.size(); r++) {\n\t\t\t\t\ttree[j][k].outgoing_checkPoints.push_back(IL_Nodes[row_bases[r]]);\n\t\t\t\t}\n\t\t\t\tfor (int c = 0; c < col_bases.size(); c++) {\n\t\t\t\t\ttree[j][k].outgoing_chargePoints.push_back(boxA_Nodes[col_bases[c]]);\n\t\t\t\t}\n\t\t\t\tstd::vector<int> row_indices_local;\n\t\t\t\tfor (size_t r = 0; r < row_bases.size(); r++) {\n\t\t\t\t\trow_indices_local.push_back(IL_Nodes[row_bases[r]]);\n\t\t\t\t}\n\t\t\t\tstd::vector<int> col_indices_local;\n\t\t\t\tfor (size_t c = 0; c < col_bases.size(); c++) {\n\t\t\t\t\tcol_indices_local.push_back(boxA_Nodes[col_bases[c]]);\n\t\t\t\t}\n\t\t\t\tMat Atilde = getMatrix(row_indices_local, col_indices_local);\n\t\t\t\ttree[j][k].outgoing_Atilde_dec = Atilde.colPivHouseholderQr();\n\t\t\t}\n\t\t\tif (n_rows == 0) {\n\t\t\t\ttree[j][k].ILActive = false;\n\t\t\t\tgetParticlesFromChildrenLFR_outgoing_col(j, k, tree[j][k].outgoing_chargePoints);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\ttree[j][k].ILActive = false;\n\t\t}\n\t}\n\n\tvoid getNodes_LFR_outgoing_level(int j) { //LFR; box interactions\n\t  /*\n\t  computes\n\t  1. x^{B,o}\n\t  2. y^{B,o}\n\t  3. matrix decomposition: K(x^{B,o}, y^{B,o})\n\t  */\n\t  //for (int j=nLevels; j>=2; j--) {\n\t    int rankPerLevel = 0;\n\t    int n_rows_checkpoint;\n\t    int n_cols_checkpoint;\n\t    std::vector<int> boxA_Particles_checkpoint;\n\t    std::vector<int> IL_Particles_checkpoint;\n\t\t\tint ComputedRank, n_rows, n_cols;\n\t\t\t//#pragma omp parallel for\n\t    for (int k=0; k<tree[j].size(); ++k) {\n\t\t\t\tgetNodes_LFR_outgoing_box(j, k, n_rows, n_cols, ComputedRank);\n\t\t\t\tif (rankPerLevel < ComputedRank) {\n\t\t\t\t\trankPerLevel = ComputedRank;\n\t\t\t\t\tn_rows_checkpoint = n_rows;\n\t\t\t\t\tn_cols_checkpoint = n_cols;\n\t\t\t\t}\n\t    }\n\t  //}\n\t\tcout << \"O;\tj: \" << j << \"\tNboxes: \" << tree[j].size() << \"\trows,cols: \" << n_rows_checkpoint << \",\" << n_cols_checkpoint << \"\tCrank: \" << rankPerLevel << endl;\n\t}\n\n\n\tvoid getParticlesFromChildrenLFR_incoming_row(int j, int k, std::vector<int>& searchNodes) {\n\t\tif (tree[j][k].isLeaf) {\n\t\t\tsearchNodes.insert(searchNodes.end(), tree[j][k].chargeLocations.begin(), tree[j][k].chargeLocations.end());\n\t\t}\n\t\telse {\n\t\t\tint J = j+1;\n\t\t\tint b = tree[j][k].boxNumber;\n\t\t\tfor (int c = 0; c < 4; c++) {\n\t\t\t\tint KboxNumber = 4*b+c;\n\t\t\t\tstd::vector<int>::iterator indx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\t\t\tint K = indx-indexTree[J].begin();\n\t\t\t\tif (J >= level_LFR || (J<level_LFR && tree[J][K].isLeaf)) { //LFR\n\t\t\t\t\tif (tree[J][K].incoming_checkPoints.size() == 0) {\n\t\t\t\t\t\tcout << \"problem LFR_outgoing_row: \" << j << \", \" << k << \", \" << J << \", \" << K << endl;\n\t\t\t\t\t}\n\t\t\t\t\tsearchNodes.insert(searchNodes.end(), tree[J][K].incoming_checkPoints.begin(), tree[J][K].incoming_checkPoints.end());\n\t\t\t\t}\n\t\t\t\telse { //HFR\n\t\t\t\t\tfor (size_t cone = 0; cone < nCones[J]; cone++) {\n\t\t\t\t\t\tsearchNodes.insert(searchNodes.end(), tree[J][K].ConeTree[cone].incoming_checkPoints.begin(), tree[J][K].ConeTree[cone].incoming_checkPoints.end());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid getParticlesFromChildrenLFR_incoming_col(int j, int k, std::vector<int>& searchNodes) {\n\t\tif (tree[j][k].isLeaf) {\n\t\t\tsearchNodes.insert(searchNodes.end(), tree[j][k].chargeLocations.begin(), tree[j][k].chargeLocations.end());\n\t\t}\n\t\telse {\n\t\t\tint J = j+1;\n\t\t\tint b = tree[j][k].boxNumber;\n\t\t\tfor (int c = 0; c < 4; c++) {\n\t\t\t\tint KboxNumber = 4*b+c;\n\t\t\t\tstd::vector<int>::iterator indx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\t\t\tint K = indx-indexTree[J].begin();\n\t\t\t\tif (J >= level_LFR || (J<level_LFR && tree[J][K].isLeaf)) { //LFR\n\t\t\t\t\tif (tree[J][K].incoming_checkPoints.size() == 0) {\n\t\t\t\t\t\tcout << \"problem LFR_outgoing_row: \" << j << \", \" << k << \", \" << J << \", \" << K << endl;\n\t\t\t\t\t}\n\t\t\t\t\tsearchNodes.insert(searchNodes.end(), tree[J][K].outgoing_chargePoints.begin(), tree[J][K].outgoing_chargePoints.end());\n\t\t\t\t}\n\t\t\t\telse { //HFR\n\t\t\t\t\tfor (size_t cone = 0; cone < nCones[J]; cone++) {\n\t\t\t\t\t\tsearchNodes.insert(searchNodes.end(), tree[J][K].ConeTree[cone].outgoing_chargePoints.begin(), tree[J][K].ConeTree[cone].outgoing_chargePoints.end());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid getNodes_LFR_incoming_box(int j, int k, int& n_rows, int& n_cols, int& ComputedRank) {\n\t\tint ILcheck = 0;\n\t\tif (tree[j][k].active == true) {\n\t\t\tstd::vector<int> boxA_Nodes;\n\t\t\tgetParticlesFromChildrenLFR_incoming_row(j, k, boxA_Nodes);\n\n\t\t\t//sort( boxA_Nodes.begin(), boxA_Nodes.end() );\n\t\t\t//boxA_Nodes.erase( unique( boxA_Nodes.begin(), boxA_Nodes.end() ), boxA_Nodes.end() );\n\n\t\t\tstd::vector<int> IL_Nodes;//indices\n\t\t\tfor (int l=0; l<tree[j][k].InteractionList.size(); ++l) {\n\t\t\t\tint jIL = tree[j][k].InteractionList[l].x;\n\t\t\t\tint kIL = tree[j][k].InteractionList[l].y;\n\t\t\t\tstd::vector<int> chargeLocations;\n\t\t\t\tgetParticlesFromChildrenLFR_incoming_col(jIL, kIL, chargeLocations);\n\t\t\t\tIL_Nodes.insert(IL_Nodes.end(), chargeLocations.begin(), chargeLocations.end());\n\t\t\t}\n\n\t\t\t//sort( IL_Nodes.begin(), IL_Nodes.end() );\n\t\t\t//IL_Nodes.erase( unique( IL_Nodes.begin(), IL_Nodes.end() ), IL_Nodes.end() );\n\n\t\t\tn_rows = boxA_Nodes.size();\n\t\t\tn_cols = IL_Nodes.size();\n\t\t\tint tol_pow = TOL_POW;\n\t\t\tdouble tol_ACA = pow(10,-1.0*tol_pow);\n\t\t\trow_indices = boxA_Nodes;//object of base class LowRank\n\t\t\tcol_indices = IL_Nodes;\n\t\t\tstd::vector<int> row_bases, col_bases;\n\t\t\tif (n_rows != 0 && n_cols != 0) {\n\t\t\t\ttree[j][k].ILActive = true;\n\t\t\t\tMat dummy1, dummy2;\n\t\t\t\tACA_only_nodes(row_bases, col_bases, ComputedRank, tol_ACA, dummy1, dummy2);\n\t\t\t\tint minN = n_rows;\n\t\t\t\tif (n_rows > n_cols) {\n\t\t\t\t\tminN = n_cols;\n\t\t\t\t}\n\t\t\t\tfor (int r = 0; r < row_bases.size(); r++) {\n\t\t\t\t\ttree[j][k].incoming_checkPoints.push_back(boxA_Nodes[row_bases[r]]);\n\t\t\t\t}\n\t\t\t\tfor (int c = 0; c < col_bases.size(); c++) {\n\t\t\t\t\ttree[j][k].incoming_chargePoints.push_back(IL_Nodes[col_bases[c]]);\n\t\t\t\t}\n\t\t\t\tstd::vector<int> row_indices_local;\n\t\t\t\tfor (size_t r = 0; r < row_bases.size(); r++) {\n\t\t\t\t\trow_indices_local.push_back(boxA_Nodes[row_bases[r]]);\n\t\t\t\t}\n\t\t\t\tstd::vector<int> col_indices_local;\n\t\t\t\tfor (size_t c = 0; c < col_bases.size(); c++) {\n\t\t\t\t\tcol_indices_local.push_back(IL_Nodes[col_bases[c]]);\n\t\t\t\t}\n\t\t\t\tMat Atilde = getMatrix(row_indices_local, col_indices_local);\n\t\t\t\ttree[j][k].incoming_Atilde_dec = Atilde.colPivHouseholderQr();\n\t\t\t}\n\t\t\tif (n_cols == 0) {\n\t\t\t\ttree[j][k].ILActive = false;\n\t\t\t\tgetParticlesFromChildrenLFR_incoming_row(j, k, tree[j][k].incoming_checkPoints);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\ttree[j][k].ILActive = false;\n\t\t}\n\t}\n\n\tvoid getNodes_LFR_incoming_level(int j) { //LFR; box interactions\n\t\t/*\n\t\tcomputes\n\t\t1. x^{B,o}\n\t\t2. y^{B,o}\n\t\t3. matrix decomposition: K(x^{B,o}, y^{B,o})\n\t\t*/\n\t\t//for (int j=nLevels; j>=2; j--) {\n\t\t\tint rankPerLevel = 0;\n\t\t\tint n_rows_checkpoint;\n\t\t\tint n_cols_checkpoint;\n\t\t\tstd::vector<int> boxA_Particles_checkpoint;\n\t\t\tstd::vector<int> IL_Particles_checkpoint;\n\t\t\tint ComputedRank, n_rows, n_cols;\n\t\t\t//#pragma omp parallel for\n\t    for (int k=0; k<tree[j].size(); ++k) {\n\t\t\t\tgetNodes_LFR_incoming_box(j, k, n_rows, n_cols, ComputedRank);\n\t\t\t\tif (rankPerLevel < ComputedRank) {\n\t\t\t\t\trankPerLevel = ComputedRank;\n\t\t\t\t\tn_rows_checkpoint = n_rows;\n\t\t\t\t\tn_cols_checkpoint = n_cols;\n\t\t\t\t}\n\t\t\t}\n\t\t//}\n\t\tcout << \"I;\tj: \" << j << \"\tNboxes: \" << tree[j].size() << \"\trows,cols: \" << n_rows_checkpoint << \",\" << n_cols_checkpoint << \"\tCrank: \" << rankPerLevel << endl;\n\t}\n\n\tvoid LFR_M2M_ILActive_True(int j, int k) {\n\t\tstd::vector<int> source_points;// = tree[j][k].chargeLocations//source points\n\t\tVec source_densities;\n\t\tif (tree[j][k].isLeaf) {\n\t\t\tint Veclength = tree[j][k].multipoles.size();\n\t\t\tsource_densities = Vec::Zero(Veclength);// = tree[j][k].multipoles//source densities\n\t\t\tint g = 0;\n\t\t\tfor (int l = 0; l < tree[j][k].multipoles.size(); l++) {\n\t\t\t\tsource_densities(g) = tree[j][k].multipoles(l);\n\t\t\t\t++g;\n\t\t\t}\n\t\t\tsource_points.insert(source_points.end(), tree[j][k].chargeLocations.begin(), tree[j][k].chargeLocations.end());\n\t\t}\n\t\telse {\n\t\t\tint J = j+1;\n\t\t\tint b = tree[j][k].boxNumber;\n\t\t\tint KboxNumber;\n\t\t\tint K[4];\n\t\t\tstd::vector<int>::iterator indx;\n\t\t\tKboxNumber = 4*b+0;\n\t\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\t\tK[0] = indx-indexTree[J].begin();\n\t\t\tKboxNumber = 4*b+1;\n\t\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\t\tK[1] = indx-indexTree[J].begin();\n\t\t\tKboxNumber = 4*b+2;\n\t\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\t\tK[2] = indx-indexTree[J].begin();\n\t\t\tKboxNumber = 4*b+3;\n\t\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\t\tK[3] = indx-indexTree[J].begin();\n\n\t\t\tint Veclength = tree[J][K[0]].outgoing_charges.size()+tree[J][K[1]].outgoing_charges.size()+tree[J][K[2]].outgoing_charges.size()+tree[J][K[3]].outgoing_charges.size();\n\t\t\tsource_densities = Vec::Zero(Veclength);// = tree[j][k].multipoles//source densities\n\t\t\tint g = 0;\n\t\t\tfor (int child = 0; child < 4; child++) {\n\t\t\t\tfor (int l = 0; l < tree[J][K[child]].outgoing_charges.size(); l++) {\n\t\t\t\t\tsource_densities(g) = tree[J][K[child]].outgoing_charges(l);\n\t\t\t\t\t++g;\n\t\t\t\t}\n\t\t\t\tsource_points.insert(source_points.end(), tree[J][K[child]].outgoing_chargePoints.begin(), tree[J][K[child]].outgoing_chargePoints.end());//outgoing_chargePoints\n\t\t\t}\n\t\t}\n\t\ttree[j][k].outgoing_potential = tree[j][k].outgoing_Ar*source_densities;//u^{B,o}\n\t\ttree[j][k].outgoing_charges = tree[j][k].outgoing_Atilde_dec.solve(tree[j][k].outgoing_potential);//f^{B,o} //solve system: A\\tree[j][k].outgoing_potential\n\t}\n\n\tvoid LFR_M2M_ILActive_False(int j, int k) {\n\t\tif (tree[j][k].isLeaf) {\n\t\t\ttree[j][k].outgoing_charges = tree[j][k].multipoles;\n\t\t}\n\t\telse {\n\t\t\tint J = j+1;\n\t\t\tint b = tree[j][k].boxNumber;\n\t\t\tint KboxNumber;\n\t\t\tint K[4];\n\t\t\tstd::vector<int>::iterator indx;\n\t\t\tKboxNumber = 4*b+0;\n\t\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\t\tK[0] = indx-indexTree[J].begin();\n\t\t\tKboxNumber = 4*b+1;\n\t\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\t\tK[1] = indx-indexTree[J].begin();\n\t\t\tKboxNumber = 4*b+2;\n\t\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\t\tK[2] = indx-indexTree[J].begin();\n\t\t\tKboxNumber = 4*b+3;\n\t\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\t\tK[3] = indx-indexTree[J].begin();\n\n\t\t\tint Veclength = tree[J][K[0]].outgoing_charges.size()+tree[J][K[1]].outgoing_charges.size()+tree[J][K[2]].outgoing_charges.size()+tree[J][K[3]].outgoing_charges.size();\n\t\t\ttree[j][k].outgoing_charges = Vec::Zero(Veclength);\n\t\t\tint g = 0;\n\t\t\tfor (int child = 0; child < 4; child++) {\n\t\t\t\tfor (int l = 0; l < tree[J][K[child]].outgoing_charges.size(); l++) {\n\t\t\t\t\ttree[j][k].outgoing_charges(g) = tree[J][K[child]].outgoing_charges(l);\n\t\t\t\t\t++g;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid LFR_M2M() {//outgoing operations\n\t\t/*\n\t\ttree[j][k].multipoles//source densities\n\t\ttree[j][k].chargeLocations//source points\n\t  x^{B,o}=tree[j][k].outgoing_checkPoints\n\t\tkernel evaluation between x^{B,o} and source points\n\t\tA = K(x^{B,o}, y^{B,o})\n\t\tx^{B,o}=tree[j][k].outgoing_checkPoints\n\t\ty^{B,o}=tree[j][k].outgoing_chargePoints\n\t\t*/\n\t\tfor (int j=nLevels; j>=2; --j) {\n\t\t\t#pragma omp parallel for\n\t\t\tfor (int k=0; k<tree[j].size(); ++k) {\n\t\t\t\tif (j<level_LFR && !tree[j][k].isLeaf) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (tree[j][k].active == true) {\n\t\t\t\t\tif (tree[j][k].ILActive) {\n\t\t\t\t\t\tLFR_M2M_ILActive_True(j, k);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tLFR_M2M_ILActive_False(j, k);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid Assemble_LFR_M2L() {\n\t\t/*\n\t\tu^{B,i}: tree[j][boxB].ConeTree[coneB].incoming_potential\n\t\tx^{B,i}: tree[j][boxB].ConeTree[coneB].incoming_checkPoints\n\t\tf^{A,o}: tree[j][boxA].ConeTree[coneA].outgoing_charges\n\t\ty^{A,o}: tree[j][boxA].ConeTree[coneB].outgoing_chargePoints\n\t\t*/\n\t\t#pragma omp parallel for\n\t\tfor (int j=2; j<=nLevels; ++j) {\n\t\t\t#pragma omp parallel for\n\t\t\tfor (int k=0; k<tree[j].size(); ++k) {//BoxA\n\t\t\t\tif (j<level_LFR && !tree[j][k].isLeaf) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (tree[j][k].active == true) {\n\t\t\t\t\tif (!tree[j][k].isLeaf) {\n\t\t\t\t\t\t//tree[j][k].incoming_potential\t=\tVec::Zero(tree[j][k].user_checkPoints.size());\n\t\t\t\t\t\tif (tree[j][k].ILActive) {\n\t\t\t\t\t\t\tfor (int l = 0; l < tree[j][k].InteractionList.size(); l++) {\n\t\t\t\t\t\t\t\tint jIL = tree[j][k].InteractionList[l].x;\n\t\t\t\t\t\t\t\tint kIL = tree[j][k].InteractionList[l].y;\n\t\t\t\t\t\t\t\tif (jIL<level_LFR && !tree[jIL][kIL].isLeaf) {//HFR\n\t\t\t\t\t\t\t\t\tdouble arg = atan2(tree[j][k].center.y-tree[jIL][kIL].center.y, tree[j][k].center.x-tree[jIL][kIL].center.x);\n\t\t\t\t\t\t\t\t\tdouble argA = fmod(arg+2*PI, 2*PI);\n\t\t\t\t\t\t\t\t\tint coneA = int(argA/ConeAperture[jIL]);//=coneB; direction of nBox wrt k\n\t\t\t\t\t\t\t\t\tint n_rows = tree[j][k].user_checkPoints.size();\n\t\t\t\t\t\t\t\t\tint n_cols = tree[jIL][kIL].ConeTree[coneA].outgoing_chargePoints.size();//outgoing_chargePoints\n\t\t\t\t\t\t\t\t\tint RHS_size = tree[jIL][kIL].ConeTree[coneA].outgoing_charges.size();\n\t\t\t\t\t\t\t\t\tif (n_rows != 0 && n_cols != 0) {\n\t\t\t\t\t\t\t\t\t\ttree[j][k].M2L.push_back(getMatrix(tree[j][k].user_checkPoints, tree[jIL][kIL].ConeTree[coneA].outgoing_chargePoints));\n\t\t\t\t\t\t\t\t\t\t//tree[j][k].incoming_potential += R*tree[jIL][kIL].ConeTree[coneA].outgoing_charges;//u^{B,o}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\tint n_rows = tree[j][k].user_checkPoints.size();\n\t\t\t\t\t\t\t\t\tint n_cols = tree[jIL][kIL].outgoing_chargePoints.size();//outgoing_chargePoints\n\t\t\t\t\t\t\t\t\ttree[j][k].M2L.push_back(getMatrix(tree[j][k].user_checkPoints, tree[jIL][kIL].outgoing_chargePoints));\n\t\t\t\t\t\t\t\t\t//tree[j][k].incoming_potential += R*tree[jIL][kIL].outgoing_charges;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\t//tree[j][k].incoming_potential\t=\tVec::Zero(tree[j][k].chargeLocations.size());\n\t\t\t\t\t\tif (tree[j][k].ILActive) {\n\t\t\t\t\t\t\tfor (int l = 0; l < tree[j][k].InteractionList.size(); l++) {\n\t\t\t\t\t\t\t\tint jIL = tree[j][k].InteractionList[l].x;\n\t\t\t\t\t\t\t\tint kIL = tree[j][k].InteractionList[l].y;\n\t\t\t\t\t\t\t\tif (jIL<level_LFR && !tree[jIL][kIL].isLeaf) {//HFR\n\t\t\t\t\t\t\t\t\tdouble arg = atan2(tree[j][k].center.y-tree[jIL][kIL].center.y, tree[j][k].center.x-tree[jIL][kIL].center.x);\n\t\t\t\t\t\t\t\t\tdouble argA = fmod(arg+2*PI, 2*PI);\n\t\t\t\t\t\t\t\t\tint coneA = int(argA/ConeAperture[jIL]);//=coneB; direction of nBox wrt k\n\t\t\t\t\t\t\t\t\tint n_rows = tree[j][k].chargeLocations.size();\n\t\t\t\t\t\t\t\t\tint n_cols = tree[jIL][kIL].ConeTree[coneA].outgoing_chargePoints.size();//outgoing_chargePoints\n\t\t\t\t\t\t\t\t\tint RHS_size = tree[jIL][kIL].ConeTree[coneA].outgoing_charges.size();\n\n\t\t\t\t\t\t\t\t\tif (n_rows != 0 && n_cols != 0) {\n\t\t\t\t\t\t\t\t\t\ttree[j][k].M2L.push_back(getMatrix(tree[j][k].chargeLocations, tree[jIL][kIL].ConeTree[coneA].outgoing_chargePoints));\n\t\t\t\t\t\t\t\t\t\t//tree[j][k].incoming_potential += R*tree[jIL][kIL].ConeTree[coneA].outgoing_charges;//u^{B,o}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\tint n_rows = tree[j][k].chargeLocations.size();\n\t\t\t\t\t\t\t\t\tint n_cols = tree[jIL][kIL].outgoing_chargePoints.size();//outgoing_chargePoints\n\t\t\t\t\t\t\t\t\ttree[j][k].M2L.push_back(getMatrix(tree[j][k].chargeLocations, tree[jIL][kIL].outgoing_chargePoints));\n\t\t\t\t\t\t\t\t\t//tree[j][k].incoming_potential += R*tree[jIL][kIL].outgoing_charges;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid LFR_M2L() {\n\t\t/*\n\t\tu^{B,i}: tree[j][boxB].ConeTree[coneB].incoming_potential\n\t\tx^{B,i}: tree[j][boxB].ConeTree[coneB].incoming_checkPoints\n\t\tf^{A,o}: tree[j][boxA].ConeTree[coneA].outgoing_charges\n\t\ty^{A,o}: tree[j][boxA].ConeTree[coneB].outgoing_chargePoints\n\t\t*/\n\t\t#pragma omp parallel for\n\t\tfor (int j=2; j<=nLevels; ++j) {\n\t\t\t#pragma omp parallel for\n\t\t\tfor (int k=0; k<tree[j].size(); ++k) {//BoxA\n\t\t\t\tif (j<level_LFR && !tree[j][k].isLeaf) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (tree[j][k].active == true) {\n\t\t\t\t\tif (!tree[j][k].isLeaf) {\n\t\t\t\t\t\ttree[j][k].incoming_potential\t=\tVec::Zero(tree[j][k].user_checkPoints.size());\n\t\t\t\t\t\tif (tree[j][k].ILActive) {\n\t\t\t\t\t\t\t#pragma omp parallel for\n\t\t\t\t\t\t\tfor (int l = 0; l < tree[j][k].InteractionList.size(); l++) {\n\t\t\t\t\t\t\t\tint jIL = tree[j][k].InteractionList[l].x;\n\t\t\t\t\t\t\t\tint kIL = tree[j][k].InteractionList[l].y;\n\t\t\t\t\t\t\t\tif (jIL<level_LFR && !tree[jIL][kIL].isLeaf) {//HFR\n\t\t\t\t\t\t\t\t\tdouble arg = atan2(tree[j][k].center.y-tree[jIL][kIL].center.y, tree[j][k].center.x-tree[jIL][kIL].center.x);\n\t\t\t\t\t\t\t\t\tdouble argA = fmod(arg+2*PI, 2*PI);\n\t\t\t\t\t\t\t\t\tint coneA = int(argA/ConeAperture[jIL]);//=coneB; direction of nBox wrt k\n\t\t\t\t\t\t\t\t\tint n_rows = tree[j][k].user_checkPoints.size();\n\t\t\t\t\t\t\t\t\tint n_cols = tree[jIL][kIL].ConeTree[coneA].outgoing_chargePoints.size();//outgoing_chargePoints\n\t\t\t\t\t\t\t\t\tint RHS_size = tree[jIL][kIL].ConeTree[coneA].outgoing_charges.size();\n\t\t\t\t\t\t\t\t\tif (n_rows != 0 && n_cols != 0 && RHS_size != 0) {\n\t\t\t\t\t\t\t\t\t\t//Mat R = getMatrix(tree[j][k].user_checkPoints, tree[jIL][kIL].ConeTree[coneA].outgoing_chargePoints);\n\t\t\t\t\t\t\t\t\t\ttree[j][k].incoming_potential += tree[j][k].M2L[l]*tree[jIL][kIL].ConeTree[coneA].outgoing_charges;//u^{B,o}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\tint n_rows = tree[j][k].user_checkPoints.size();\n\t\t\t\t\t\t\t\t\tint n_cols = tree[jIL][kIL].outgoing_chargePoints.size();//outgoing_chargePoints\n\t\t\t\t\t\t\t\t\t//Mat R = getMatrix(tree[j][k].user_checkPoints, tree[jIL][kIL].outgoing_chargePoints);\n\t\t\t\t\t\t\t\t\ttree[j][k].incoming_potential += tree[j][k].M2L[l]*tree[jIL][kIL].outgoing_charges;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\ttree[j][k].incoming_potential\t=\tVec::Zero(tree[j][k].chargeLocations.size());\n\t\t\t\t\t\tif (tree[j][k].ILActive) {\n\t\t\t\t\t\t\t#pragma omp parallel for\n\t\t\t\t\t\t\tfor (int l = 0; l < tree[j][k].InteractionList.size(); l++) {\n\t\t\t\t\t\t\t\tint jIL = tree[j][k].InteractionList[l].x;\n\t\t\t\t\t\t\t\tint kIL = tree[j][k].InteractionList[l].y;\n\t\t\t\t\t\t\t\tif (jIL<level_LFR && !tree[jIL][kIL].isLeaf) {//HFR\n\t\t\t\t\t\t\t\t\tdouble arg = atan2(tree[j][k].center.y-tree[jIL][kIL].center.y, tree[j][k].center.x-tree[jIL][kIL].center.x);\n\t\t\t\t\t\t\t\t\tdouble argA = fmod(arg+2*PI, 2*PI);\n\t\t\t\t\t\t\t\t\tint coneA = int(argA/ConeAperture[jIL]);//=coneB; direction of nBox wrt k\n\t\t\t\t\t\t\t\t\tint n_rows = tree[j][k].chargeLocations.size();\n\t\t\t\t\t\t\t\t\tint n_cols = tree[jIL][kIL].ConeTree[coneA].outgoing_chargePoints.size();//outgoing_chargePoints\n\t\t\t\t\t\t\t\t\tint RHS_size = tree[jIL][kIL].ConeTree[coneA].outgoing_charges.size();\n\t\t\t\t\t\t\t\t\tif (n_rows != 0 && n_cols != 0 && RHS_size != 0) {\n\t\t\t\t\t\t\t\t\t\t//Mat R = getMatrix(tree[j][k].chargeLocations, tree[jIL][kIL].ConeTree[coneA].outgoing_chargePoints);\n\t\t\t\t\t\t\t\t\t\ttree[j][k].incoming_potential += tree[j][k].M2L[l]*tree[jIL][kIL].ConeTree[coneA].outgoing_charges;//u^{B,o}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\tint n_rows = tree[j][k].chargeLocations.size();\n\t\t\t\t\t\t\t\t\tint n_cols = tree[jIL][kIL].outgoing_chargePoints.size();//outgoing_chargePoints\n\t\t\t\t\t\t\t\t\t//Mat R = getMatrix(tree[j][k].chargeLocations, tree[jIL][kIL].outgoing_chargePoints);\n\t\t\t\t\t\t\t\t\ttree[j][k].incoming_potential += tree[j][k].M2L[l]*tree[jIL][kIL].outgoing_charges;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid Assemble_LFR_L2L_IL_True(int j, int k) {\n\t\t//tree[j][k].multipoles//source densities\n\t\t//tree[j][k].chargeLocations//source points\n\t\t//x^{B,o}=tree[j][k].outgoing_checkPoints\n\t\t//kernel evaluation between x^{B,o} and source points\n\t\tint J = j+1;\n\t\tint b = tree[j][k].boxNumber;\n\t\tint KboxNumber;\n\t\tint K[4];\n\t\tstd::vector<int>::iterator indx;\n\t\tKboxNumber = 4*b+0;\n\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\tK[0] = indx-indexTree[J].begin();\n\t\tKboxNumber = 4*b+1;\n\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\tK[1] = indx-indexTree[J].begin();\n\t\tKboxNumber = 4*b+2;\n\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\tK[2] = indx-indexTree[J].begin();\n\t\tKboxNumber = 4*b+3;\n\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\tK[3] = indx-indexTree[J].begin();\n\n\t\t#pragma omp parallel for\n\t\tfor (int child = 0; child < 4; child++) {\n\t\t\t//x^{C,i}: tree[J][4*k+c].incoming_checkPoints\n\t\t\t//f^{B,i,l}: tree[j][k].ConeTree[cone_parent].incoming_charges\n\t\t\t//y^{B,i,l}: tree[j][k].ConeTree[cone_parent].incoming_chargePoints\n\t\t\tMat R;\n\t\t\tif (!tree[J][K[child]].isLeaf) {\n\t\t\t\ttree[J][K[child]].L2L = getMatrix(tree[J][K[child]].user_checkPoints, tree[j][k].incoming_chargePoints);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (j >= level_LFR) {//LFR\n\t\t\t\t\ttree[J][K[child]].L2L = getMatrix(tree[J][K[child]].chargeLocations, tree[j][k].incoming_chargePoints);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tfor (int cone_parent = 0; cone_parent < nCones[j]; cone_parent++) {//pick l\n\t\t\t\t\t\tint n_rows = tree[J][K[child]].chargeLocations.size();\n\t\t\t\t\t\tint n_cols = tree[j][k].ConeTree[cone_parent].incoming_chargePoints.size();\n\t\t\t\t\t\tif (n_rows != 0 && n_cols != 0) {\n\t\t\t\t\t\t\ttree[J][K[child]].L2L = getMatrix(tree[J][K[child]].chargeLocations, tree[j][k].ConeTree[cone_parent].incoming_chargePoints);\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 LFR_L2L_IL_True(int j, int k) {\n\t\t//tree[j][k].multipoles//source densities\n\t\t//tree[j][k].chargeLocations//source points\n\t\t//x^{B,o}=tree[j][k].outgoing_checkPoints\n\t\t//kernel evaluation between x^{B,o} and source points\n\t\ttree[j][k].incoming_charges = tree[j][k].incoming_Atilde_dec.solve(tree[j][k].incoming_potential);//f^{B,o} //solve system: A\\tree[j][k].outgoing_potential\n\t\tint J = j+1;\n\t\tint b = tree[j][k].boxNumber;\n\t\tint KboxNumber;\n\t\tint K[4];\n\t\tstd::vector<int>::iterator indx;\n\t\tKboxNumber = 4*b+0;\n\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\tK[0] = indx-indexTree[J].begin();\n\t\tKboxNumber = 4*b+1;\n\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\tK[1] = indx-indexTree[J].begin();\n\t\tKboxNumber = 4*b+2;\n\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\tK[2] = indx-indexTree[J].begin();\n\t\tKboxNumber = 4*b+3;\n\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\tK[3] = indx-indexTree[J].begin();\n\n\t\t#pragma omp parallel for\n\t\tfor (int child = 0; child < 4; child++) {\n\t\t\t//x^{C,i}: tree[J][4*k+c].incoming_checkPoints\n\t\t\t//f^{B,i,l}: tree[j][k].ConeTree[cone_parent].incoming_charges\n\t\t\t//y^{B,i,l}: tree[j][k].ConeTree[cone_parent].incoming_chargePoints\n\t\t\tMat R;\n\t\t\tif (!tree[J][K[child]].isLeaf) {\n\t\t\t\ttree[J][K[child]].incoming_potential += tree[J][K[child]].L2L*tree[j][k].incoming_charges;//u^{B,o}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (j >= level_LFR) {//LFR\n\t\t\t\t\ttree[J][K[child]].incoming_potential += tree[J][K[child]].L2L*tree[j][k].incoming_charges;//u^{B,o}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t#pragma omp parallel for\n\t\t\t\t\tfor (int cone_parent = 0; cone_parent < nCones[j]; cone_parent++) {//pick l\n\t\t\t\t\t\tint n_rows = tree[J][K[child]].chargeLocations.size();\n\t\t\t\t\t\tint n_cols = tree[j][k].ConeTree[cone_parent].incoming_chargePoints.size();\n\t\t\t\t\t\tif (n_rows != 0 && n_cols != 0) {\n\t\t\t\t\t\t\ttree[J][K[child]].incoming_potential += tree[J][K[child]].L2L*tree[j][k].ConeTree[cone_parent].incoming_charges;//u^{B,o}\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 LFR_L2L_IL_False(int j, int k) {\n\t\tint J = j+1;\n\t\tint b = tree[j][k].boxNumber;\n\n\t\tint KboxNumber;\n\t\tint K[4];\n\t\tstd::vector<int>::iterator indx;\n\t\tKboxNumber = 4*b+0;\n\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\tK[0] = indx-indexTree[J].begin();\n\t\tKboxNumber = 4*b+1;\n\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\tK[1] = indx-indexTree[J].begin();\n\t\tKboxNumber = 4*b+2;\n\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\tK[2] = indx-indexTree[J].begin();\n\t\tKboxNumber = 4*b+3;\n\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\tK[3] = indx-indexTree[J].begin();\n\t\tint offset = 0;\n\n\t\tfor (int child = 0; child < 4; child++) {\n\t\t\tif (!tree[J][K[child]].isLeaf) {\n\t\t\t\tfor (size_t i = 0; i < tree[J][K[child]].user_checkPoints.size(); i++) {\n\t\t\t\t\ttree[J][K[child]].incoming_potential(i) += tree[j][k].incoming_potential(offset+i);\n\t\t\t\t}\n\t\t\t\toffset += tree[J][K[child]].user_checkPoints.size();\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (j >= level_LFR) {//LFR\n\t\t\t\t\tfor (size_t i = 0; i < tree[J][K[child]].chargeLocations.size(); i++) {\n\t\t\t\t\t\ttree[J][K[child]].incoming_potential(i) += tree[j][k].incoming_potential(offset+i);\n\t\t\t\t\t}\n\t\t\t\t\toffset += tree[J][K[child]].chargeLocations.size();\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tfor (int cone_parent = 0; cone_parent < nCones[j]; cone_parent++) {//pick l\n\t\t\t\t\t\tfor (size_t i = 0; i < tree[J][K[child]].chargeLocations.size(); i++) {\n\t\t\t\t\t\t\ttree[J][K[child]].incoming_potential(i) += tree[j][k].ConeTree[cone_parent].incoming_potential(offset+i);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\toffset += tree[J][K[child]].chargeLocations.size();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid LFR_L2L() {//outgoing operations\n\t\tfor (int j=2; j<nLevels; ++j) {//parent\n\t\t\t#pragma omp parallel for\n\t\t\tfor (int k=0; k<tree[j].size(); ++k) {\n\t\t\t\tif (j<level_LFR && !tree[j][k].isLeaf) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (!tree[j][k].isLeaf) {\n\t\t\t\t\tif (tree[j][k].active == true) {\n\t\t\t\t\t\tif (tree[j][k].ILActive) {\n\t\t\t\t\t\t\tLFR_L2L_IL_True(j, k);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tLFR_L2L_IL_False(j, k);\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\n\t\tvoid Assemble_LFR_L2L() {//outgoing operations\n\t\t\t#pragma omp parallel for\n\t\t\tfor (int j=2; j<nLevels; ++j) {//parent\n\t\t\t\t#pragma omp parallel for\n\t\t\t\tfor (int k=0; k<tree[j].size(); ++k) {\n\t\t\t\t\tif (j<level_LFR && !tree[j][k].isLeaf) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tif (!tree[j][k].isLeaf) {\n\t\t\t\t\t\tif (tree[j][k].active == true) {\n\t\t\t\t\t\t\tif (tree[j][k].ILActive) {\n\t\t\t\t\t\t\t\tAssemble_LFR_L2L_IL_True(j, k);\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\tvoid evaluate_NearField_Using_Precomputations_H() {\n\t\tfor (int t=0; t<leafNodes.size(); ++t) {\n\t\t\tint j = leafNodes[t].x;\n\t\t\tint k = leafNodes[t].y;\n\t\t\tif (tree[j][k].active == true) {\n\t\t\t\tfor (size_t nColleagues = 0; nColleagues < 9; nColleagues++) {\n\t\t\t\t\tint nj = j;\n\t\t\t\t\tint nk = tree[j][k].colleagueNeighbors[nColleagues];\n\t\t\t\t\tif (nk != -1) {\n\t\t\t\t\t\tMat boxOperator = colleagueNeighborInteraction[j-2][nColleagues];\n\t\t\t\t\t\ttree[j][k].incoming_potential += boxOperator*tree[nj][nk].multipoles;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor (size_t nFine = 0; nFine < 12; nFine++) {\n\t\t\t\t\tint nj = j+1;\n\t\t\t\t\tint nk = tree[j][k].fineNeighbors[nFine];\n\t\t\t\t\tif (nk != -1) {\n\t\t\t\t\t\tMat boxOperator = fineNeighborInteraction[j-2][nFine];\n\t\t\t\t\t\ttree[j][k].incoming_potential += boxOperator*tree[nj][nk].multipoles;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor (size_t nSFine = 0; nSFine < 20; nSFine++) {\n\t\t\t\t\tint nj = j+1;\n\t\t\t\t\tint nk = tree[j][k].separatedFineNeighbors[nSFine];\n\t\t\t\t\tif (nk != -1) {\n\t\t\t\t\t\tMat boxOperator = separatedFineNeighborInteraction[j-2][nSFine];\n\t\t\t\t\t\ttree[j][k].incoming_potential += boxOperator*tree[nj][nk].multipoles;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor (size_t nCoarse = 0; nCoarse < 12; nCoarse++) {\n\t\t\t\t\tint nj = j-1;\n\t\t\t\t\tint nk = tree[j][k].coarseNeighbors[nCoarse];\n\t\t\t\t\tif (nk != -1) {\n\t\t\t\t\t\tMat boxOperator = coarseNeighborInteraction[j-2][nCoarse];\n\t\t\t\t\t\ttree[j][k].incoming_potential += boxOperator*tree[nj][nk].multipoles;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid evaluate_NearField_Using_Precomputations_LS() {\n\t\t#pragma omp parallel for\n\t\tfor (int t=0; t<leafNodes.size(); ++t) {\n\t\t\tint j = leafNodes[t].x;\n\t\t\tint k = leafNodes[t].y;\n\t\t\tif (tree[j][k].active == true) {\n\t\t\t\tVectorXd contrastVec(rank);\n\t\t\t\t#pragma omp parallel for\n\t\t\t\tfor (size_t i = 0; i < rank; i++) {\n\t\t\t\t\tcontrastVec(i) = kappa*kappa*(1.0+Q->ContrastFunction(tree[j][k].chebNodes[i]));\n\t\t\t\t}\n\t\t\t\tMatrixXd contrastMat = contrastVec.asDiagonal();\n\t\t\t\t#pragma omp parallel for\n\t\t\t\tfor (size_t nColleagues = 0; nColleagues < 9; nColleagues++) {\n\t\t\t\t\tint nj = j;\n\t\t\t\t\tint nk = tree[j][k].colleagueNeighbors[nColleagues];\n\t\t\t\t\tif (nk != -1) {\n\t\t\t\t\t\tMat boxOperator;\n\t\t\t\t\t\tif (findPhi) {\n\t\t\t\t\t\t\tboxOperator = contrastMat*colleagueNeighborInteraction[j-2][nColleagues];\n\t\t\t\t\t\t\tif (nColleagues == 8) //self interaction\n\t\t\t\t\t\t\t\tboxOperator = boxOperator + MatrixXd::Identity(rank,rank);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tboxOperator = colleagueNeighborInteraction[j-2][nColleagues];\n\t\t\t\t\t\t}\n\t\t\t\t\t\ttree[j][k].incoming_potential += boxOperator*tree[nj][nk].multipoles;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t#pragma omp parallel for\n\t\t\t\tfor (size_t nFine = 0; nFine < 12; nFine++) {\n\t\t\t\t\tint nj = j+1;\n\t\t\t\t\tint nk = tree[j][k].fineNeighbors[nFine];\n\t\t\t\t\tMat boxOperator;\n\t\t\t\t\tif (nk != -1) {\n\t\t\t\t\t\tif (findPhi) {\n\t\t\t\t\t\t\tboxOperator = contrastMat*fineNeighborInteraction[j-2][nFine];\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tboxOperator = fineNeighborInteraction[j-2][nFine];\n\t\t\t\t\t\t}\n\t\t\t\t\t\ttree[j][k].incoming_potential += boxOperator*tree[nj][nk].multipoles;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t#pragma omp parallel for\n\t\t\t\tfor (size_t nSFine = 0; nSFine < 20; nSFine++) {\n\t\t\t\t\tint nj = j+1;\n\t\t\t\t\tint nk = tree[j][k].separatedFineNeighbors[nSFine];\n\t\t\t\t\tMat boxOperator;\n\t\t\t\t\tif (nk != -1) {\n\t\t\t\t\t\tif (findPhi) {\n\t\t\t\t\t\t\tboxOperator = contrastMat*separatedFineNeighborInteraction[j-2][nSFine];\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tboxOperator = separatedFineNeighborInteraction[j-2][nSFine];\n\t\t\t\t\t\t}\n\t\t\t\t\t\ttree[j][k].incoming_potential += boxOperator*tree[nj][nk].multipoles;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t#pragma omp parallel for\n\t\t\t\tfor (size_t nCoarse = 0; nCoarse < 12; nCoarse++) {\n\t\t\t\t\tint nj = j-1;\n\t\t\t\t\tint nk = tree[j][k].coarseNeighbors[nCoarse];\n\t\t\t\t\tMat boxOperator;\n\t\t\t\t\tif (nk != -1) {\n\t\t\t\t\t\tif (findPhi) {\n\t\t\t\t\t\t\tboxOperator = contrastMat*coarseNeighborInteraction[j-2][nCoarse];\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tboxOperator = coarseNeighborInteraction[j-2][nCoarse];\n\t\t\t\t\t\t}\n\t\t\t\t\t\ttree[j][k].incoming_potential += boxOperator*tree[nj][nk].multipoles;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid evaluate_NearField() {\n\t//we are always making sure that we have a tree high enough to be in LFR;\n\t//so, near filed needs to be done only in LFR\n\t\t//#pragma omp parallel for\n\t\tfor (int t=0; t<leafNodes.size(); ++t) {\n\t\t\tint j = leafNodes[t].x;\n\t\t\tint k = leafNodes[t].y;\n\t\t\tif (tree[j][k].active == true) {\n\t\t\t\t//Neighbor Interaction\n\t\t\t\tfor (int l = 0; l < tree[j][k].neighborNumbers.size(); l++) {//excluding self\n\t\t\t\t\tint nj = tree[j][k].neighborNumbers[l].x;\n\t\t\t\t\tint nk = tree[j][k].neighborNumbers[l].y;\n\t\t\t\t\tint n_rows = tree[j][k].chargeLocations.size();\n\t\t\t\t\tint n_cols = tree[nj][nk].chargeLocations.size();\n\t\t\t\t\tMat R = getMatrix(tree[j][k].chargeLocations, tree[nj][nk].chargeLocations);\n\t\t\t\t\ttree[j][k].incoming_potential += R*tree[nj][nk].multipoles;//u^{B,o}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tdouble perform_Error_Check(int t) {\n\t\tint j = leafNodes[t].x;//boxA\n\t\tint k = leafNodes[t].y;\n\t\tif (tree[j][k].active == true) {\n\t\t\tVec potential\t=\tVec::Zero(tree[j][k].chargeLocations.size());\n\t\t\tfor (int p=0; p<leafNodes.size(); ++p) {\n\t\t\t\tint nj = leafNodes[p].x;//boxB\n\t\t\t\tint nk = leafNodes[p].y;\n\t\t\t\tMat NaiveOper;\n\t\t\t\tgetOperator(j, nj, tree[nj][nk].center, tree[j][k].center, NaiveOper);\n\n\t\t\t\tVectorXd contrastVec(rank);\n\t\t\t\tfor (size_t i = 0; i < rank; i++) {\n\t\t\t\t\tcontrastVec(i) = kappa*kappa*Q->ContrastFunction(tree[j][k].chebNodes[i]);\n\t\t\t\t}\n\t\t\t\tMatrixXd contrastMat = contrastVec.asDiagonal();\n\t\t\t\tNaiveOper = contrastMat*NaiveOper;\n\t\t\t\tif (j==nj && k==nk) {\n\t\t\t\t\tNaiveOper = NaiveOper + MatrixXd::Identity(rank,rank);\n\t\t\t\t}\n\n\t\t\t\tpotential = potential + NaiveOper*tree[nj][nk].multipoles;\n\t\t\t}\n\t\t\tEigen::VectorXd error(tree[j][k].chargeLocations.size());\n\t\t\tfor (int p=0; p<tree[j][k].chargeLocations.size(); ++p) {\n\t\t\t\terror(p)\t=\tabs(potential(p)-tree[j][k].incoming_potential(p));\n\t\t\t}\n\t\t\tVectorXd absTruePotential = potential.cwiseAbs();\n\t\t\tVectorXd absCalcPotential = tree[j][k].incoming_potential.cwiseAbs();\n\t\t\treturn error.maxCoeff()/absTruePotential.maxCoeff();\n\t\t}\n\t\telse {\n\t\t\treturn 0.0;\n\t\t}\n\t}\n\n\n\n\tdouble perform_Error_Check2(int t) {\n\t\tint lj = leafNodes[t].x;//boxA\n\t\tint lk = leafNodes[t].y;\n\t\tif (tree[lj][lk].active == true) {\n\t\t\tVec truePotential\t=\tVec::Zero(tree[lj][lk].chargeLocations.size());\n\t\t\tfor (size_t t = 0; t < truePotential.size(); t++) {\n\t\t\t\tint i = tree[lj][lk].chargeLocations[t];\n\t\t\t\tfor (int j = 0; j < N; j++) {\n\t\t\t\t\ttruePotential(t) = truePotential(t) + getMatrixEntry2(i,j)*chargesAll[j];\n\t\t\t\t}\n\t\t\t}\n\t\t\tEigen::VectorXd error(tree[lj][lk].chargeLocations.size());\n\t\t\tfor (int p=0; p<tree[lj][lk].chargeLocations.size(); ++p) {\n\t\t\t\terror(p)\t=\tabs(truePotential(p)-tree[lj][lk].incoming_potential(p));\n\t\t\t}\n\t\t\tVectorXd absTruePotential = truePotential.cwiseAbs();\n\t\t\tVectorXd absCalcPotential = tree[lj][lk].incoming_potential.cwiseAbs();\n\t\t\treturn error.maxCoeff()/absTruePotential.maxCoeff();\n\t\t}\n\t\telse {\n\t\t\treturn 0.0;\n\t\t}\n\t}\n\n\tvoid collectPotential(Vec &potential) {\n\t\tpotential = VectorXcd::Zero(N);\n\t\tint start = 0;\n\t\tfor (size_t t = 0; t < leafNodes.size(); t++) {\n\t\t\tint j = leafNodes[t].x;\n\t\t\tint k = leafNodes[t].y;\n\t\t\tpotential.segment(start, rank) = tree[j][k].incoming_potential;\n\t\t\tstart += rank;\n\t\t}\n\t}\n//////////////////////////////////////////////////////////////////\n/*\nvoid getUserCheckPoints() {\n\tfor (size_t j = level_LFR; j <= nLevels; j++) {//LFR\n\t\tfor (size_t k = 0; k < tree[j].size(); k++) {\n\t\t\tif (tree[j][k].isLeaf) {\n\t\t\t\ttree[j][k].user_checkPoints.insert(tree[j][k].user_checkPoints.end(), tree[j][k].chargeLocations.begin(), tree[j][k].chargeLocations.end());\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (tree[j][k].ILActive) {\n\t\t\t\t\ttree[j][k].user_checkPoints.insert(tree[j][k].user_checkPoints.end(), tree[j][k].incoming_checkPoints.begin(), tree[j][k].incoming_checkPoints.end());\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tint J = j+1;\n\t\t\t\t\tint b = tree[j][k].boxNumber;\n\t\t\t\t\tint KboxNumber;\n\t\t\t\t\tint K[4];\n\t\t\t\t\tstd::vector<int>::iterator indx;\n\t\t\t\t\tKboxNumber = 4*b+0;\n\t\t\t\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\t\t\t\tK[0] = indx-indexTree[J].begin();\n\t\t\t\t\tKboxNumber = 4*b+1;\n\t\t\t\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\t\t\t\tK[1] = indx-indexTree[J].begin();\n\t\t\t\t\tKboxNumber = 4*b+2;\n\t\t\t\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\t\t\t\tK[2] = indx-indexTree[J].begin();\n\t\t\t\t\tKboxNumber = 4*b+3;\n\t\t\t\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\t\t\t\tK[3] = indx-indexTree[J].begin();\n\t\t\t\t\tfor (size_t ch = 0; ch < 4; ch++) {\n\t\t\t\t\t\tif (tree[J][K[ch]].isLeaf) {\n\t\t\t\t\t\t\ttree[j][k].user_checkPoints.insert(tree[j][k].user_checkPoints.end(), tree[J][K[ch]].chargeLocations.begin(), tree[J][K[ch]].chargeLocations.end());\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\ttree[j][k].user_checkPoints.insert(tree[j][k].user_checkPoints.end(), tree[J][K[ch]].incoming_checkPoints.begin(), tree[J][K[ch]].incoming_checkPoints.end());\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\tfor (size_t j = 2; j < level_LFR; j++) {//HFR\n\t\tfor (size_t k = 0; k < tree[j].size(); k++) {\n\t\t\tif (tree[j][k].isLeaf) {\n\t\t\t\ttree[j][k].user_checkPoints.insert(tree[j][k].user_checkPoints.end(), tree[j][k].chargeLocations.begin(), tree[j][k].chargeLocations.end());\n\t\t\t}\n\t\t\telse {//HFR\n\t\t\t\tfor (size_t cone = 0; cone < nCones[j]; cone++) {\n\t\t\t\t\tif (tree[j][k].ConeTree[cone].ILActive) {\n\t\t\t\t\t\ttree[j][k].ConeTree[cone].user_checkPoints.insert(tree[j][k].ConeTree[cone].user_checkPoints.end(), tree[j][k].ConeTree[cone].incoming_checkPoints.begin(), tree[j][k].ConeTree[cone].incoming_checkPoints.end());\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tint J = j+1;\n\t\t\t\t\t\tint b = tree[j][k].boxNumber;\n\t\t\t\t\t\tint KboxNumber;\n\t\t\t\t\t\tint K[4];\n\t\t\t\t\t\tstd::vector<int>::iterator indx;\n\t\t\t\t\t\tKboxNumber = 4*b+0;\n\t\t\t\t\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\t\t\t\t\tK[0] = indx-indexTree[J].begin();\n\t\t\t\t\t\tKboxNumber = 4*b+1;\n\t\t\t\t\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\t\t\t\t\tK[1] = indx-indexTree[J].begin();\n\t\t\t\t\t\tKboxNumber = 4*b+2;\n\t\t\t\t\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\t\t\t\t\tK[2] = indx-indexTree[J].begin();\n\t\t\t\t\t\tKboxNumber = 4*b+3;\n\t\t\t\t\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\t\t\t\t\tK[3] = indx-indexTree[J].begin();\n\t\t\t\t\t\tint cone_child =  cone/2;\n\t\t\t\t\t\tfor (size_t ch = 0; ch < 4; ch++) {\n\t\t\t\t\t\t\tif (tree[J][K[ch]].isLeaf) {\n\t\t\t\t\t\t\t\ttree[j][k].ConeTree[cone].user_checkPoints.insert(tree[j][k].ConeTree[cone].user_checkPoints.end(), tree[J][K[ch]].chargeLocations.begin(), tree[J][K[ch]].chargeLocations.end());\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tif (J == level_LFR) {\n\t\t\t\t\t\t\t\t\ttree[j][k].ConeTree[cone].user_checkPoints.insert(tree[j][k].ConeTree[cone].user_checkPoints.end(), tree[J][K[ch]].incoming_checkPoints.begin(), tree[J][K[ch]].incoming_checkPoints.end());\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\ttree[j][k].ConeTree[cone].user_checkPoints.insert(tree[j][k].ConeTree[cone].user_checkPoints.end(), tree[J][K[ch]].ConeTree[cone_child].incoming_checkPoints.begin(), tree[J][K[ch]].ConeTree[cone_child].incoming_checkPoints.end());\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n*/\nvoid getUserCheckPoints() {\n\tfor (size_t j = nLevels; j >= level_LFR; j--) {//LFR\n\t\t#pragma omp parallel for\n\t\tfor (size_t k = 0; k < tree[j].size(); k++) {\n\t\t\tif (tree[j][k].isLeaf) {\n\t\t\t\ttree[j][k].user_checkPoints.insert(tree[j][k].user_checkPoints.end(), tree[j][k].chargeLocations.begin(), tree[j][k].chargeLocations.end());\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (tree[j][k].ILActive) {\n\t\t\t\t\ttree[j][k].user_checkPoints.insert(tree[j][k].user_checkPoints.end(), tree[j][k].incoming_checkPoints.begin(), tree[j][k].incoming_checkPoints.end());\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tint J = j+1;\n\t\t\t\t\tint b = tree[j][k].boxNumber;\n\t\t\t\t\tint KboxNumber;\n\t\t\t\t\tint K[4];\n\t\t\t\t\tstd::vector<int>::iterator indx;\n\t\t\t\t\tKboxNumber = 4*b+0;\n\t\t\t\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\t\t\t\tK[0] = indx-indexTree[J].begin();\n\t\t\t\t\tKboxNumber = 4*b+1;\n\t\t\t\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\t\t\t\tK[1] = indx-indexTree[J].begin();\n\t\t\t\t\tKboxNumber = 4*b+2;\n\t\t\t\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\t\t\t\tK[2] = indx-indexTree[J].begin();\n\t\t\t\t\tKboxNumber = 4*b+3;\n\t\t\t\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\t\t\t\tK[3] = indx-indexTree[J].begin();\n\t\t\t\t\tfor (size_t ch = 0; ch < 4; ch++) {\n\t\t\t\t\t\ttree[j][k].user_checkPoints.insert(tree[j][k].user_checkPoints.end(), tree[J][K[ch]].user_checkPoints.begin(), tree[J][K[ch]].user_checkPoints.end());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tfor (size_t j = level_LFR-1; j >= 2; j--) {//HFR\n\t\t#pragma omp parallel for\n\t\tfor (size_t k = 0; k < tree[j].size(); k++) {\n\t\t\tif (tree[j][k].isLeaf) {\n\t\t\t\ttree[j][k].user_checkPoints.insert(tree[j][k].user_checkPoints.end(), tree[j][k].chargeLocations.begin(), tree[j][k].chargeLocations.end());\n\t\t\t}\n\t\t\telse {//HFR\n\t\t\t\tfor (size_t cone = 0; cone < nCones[j]; cone++) {\n\t\t\t\t\tif (tree[j][k].ConeTree[cone].ILActive) {\n\t\t\t\t\t\ttree[j][k].ConeTree[cone].user_checkPoints.insert(tree[j][k].ConeTree[cone].user_checkPoints.end(), tree[j][k].ConeTree[cone].incoming_checkPoints.begin(), tree[j][k].ConeTree[cone].incoming_checkPoints.end());\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tint J = j+1;\n\t\t\t\t\t\tint b = tree[j][k].boxNumber;\n\t\t\t\t\t\tint KboxNumber;\n\t\t\t\t\t\tint K[4];\n\t\t\t\t\t\tstd::vector<int>::iterator indx;\n\t\t\t\t\t\tKboxNumber = 4*b+0;\n\t\t\t\t\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\t\t\t\t\tK[0] = indx-indexTree[J].begin();\n\t\t\t\t\t\tKboxNumber = 4*b+1;\n\t\t\t\t\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\t\t\t\t\tK[1] = indx-indexTree[J].begin();\n\t\t\t\t\t\tKboxNumber = 4*b+2;\n\t\t\t\t\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\t\t\t\t\tK[2] = indx-indexTree[J].begin();\n\t\t\t\t\t\tKboxNumber = 4*b+3;\n\t\t\t\t\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\t\t\t\t\tK[3] = indx-indexTree[J].begin();\n\t\t\t\t\t\tint cone_child =  cone/2;\n\t\t\t\t\t\tfor (size_t ch = 0; ch < 4; ch++) {\n\t\t\t\t\t\t\tif (tree[J][K[ch]].isLeaf) {\n\t\t\t\t\t\t\t\ttree[j][k].ConeTree[cone].user_checkPoints.insert(tree[j][k].ConeTree[cone].user_checkPoints.end(), tree[J][K[ch]].user_checkPoints.begin(), tree[J][K[ch]].user_checkPoints.end());\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tif (J == level_LFR) {\n\t\t\t\t\t\t\t\t\ttree[j][k].ConeTree[cone].user_checkPoints.insert(tree[j][k].ConeTree[cone].user_checkPoints.end(), tree[J][K[ch]].user_checkPoints.begin(), tree[J][K[ch]].user_checkPoints.end());\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\ttree[j][k].ConeTree[cone].user_checkPoints.insert(tree[j][k].ConeTree[cone].user_checkPoints.end(), tree[J][K[ch]].ConeTree[cone_child].user_checkPoints.begin(), tree[J][K[ch]].ConeTree[cone_child].user_checkPoints.end());\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid getNodes_HFR() {\n\tfor (int j=level_LFR-1; j>=2; --j) {\n\t\tfor (int k=0; k<tree[j].size(); ++k) {\n\t\t\tif (!tree[j][k].isLeaf) {\n\t\t\t\tfor (int cone=0; cone<nCones[j]; ++cone) {\n\t\t\t\t\tif (tree[j][k].ConeTree[cone].incoming_chargePoints.size() > 0)\n\t\t\t\t\t\ttree[j][k].ConeTree[cone].incoming_chargePoints.clear();\n\t\t\t\t\tif (tree[j][k].ConeTree[cone].incoming_checkPoints.size() > 0)\n\t\t\t\t\t\ttree[j][k].ConeTree[cone].incoming_checkPoints.clear();\n\t\t\t\t\tif (tree[j][k].ConeTree[cone].outgoing_chargePoints.size() > 0)\n\t\t\t\t\t\ttree[j][k].ConeTree[cone].outgoing_chargePoints.clear();\n\t\t\t\t\tif (tree[j][k].ConeTree[cone].outgoing_checkPoints.size() > 0)\n\t\t\t\t\t\ttree[j][k].ConeTree[cone].outgoing_checkPoints.clear();\n\t\t\t\t\tif (tree[j][k].ConeTree[cone].user_checkPoints.size() > 0)\n\t\t\t\t\t\ttree[j][k].ConeTree[cone].user_checkPoints.clear();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tfor (int j=level_LFR-1; j>=2; --j) {\n\t\tgetNodes_HFR_outgoing_level(j);\n\t\tgetNodes_HFR_incoming_level(j);\n\t}\n}\n\n\nvoid getParticlesFromChildrenHFR_outgoing_row(int j, int k, int cone_parent, std::vector<int>& searchNodes) {\n\tif (tree[j][k].isLeaf) {\n\t\tsearchNodes.insert(searchNodes.end(), tree[j][k].chargeLocations.begin(), tree[j][k].chargeLocations.end());\n\t}\n\telse {\n\t\tint J = j+1;//child\n\t\tint b = tree[j][k].boxNumber;\n\t\tif (j == level_LFR-1) {\n\t\t\tfor (int child = 0; child < 4; child++) {\n\t\t\t\tint KboxNumber = 4*b+child;\n\t\t\t\tstd::vector<int>::iterator indx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\t\t\tint K = indx-indexTree[J].begin();\n\t\t\t\tsearchNodes.insert(searchNodes.end(), tree[J][K].incoming_checkPoints.begin(), tree[J][K].incoming_checkPoints.end());//outgoing_chargePoints\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tint cone_child =  cone_parent/2; //of j+1 level;//l'\n\t\t\tfor (int child = 0; child < 4; child++) {\n\t\t\t\tint KboxNumber = 4*b+child;\n\t\t\t\tstd::vector<int>::iterator indx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\t\t\tint K = indx-indexTree[J].begin();\n\t\t\t\tif (tree[J][K].isLeaf) {\n\t\t\t\t\tsearchNodes.insert(searchNodes.end(), tree[J][K].incoming_checkPoints.begin(), tree[J][K].incoming_checkPoints.end());//outgoing_chargePoints\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tsearchNodes.insert(searchNodes.end(), tree[J][K].ConeTree[cone_child].incoming_checkPoints.begin(), tree[J][K].ConeTree[cone_child].incoming_checkPoints.end());//outgoing_chargePoints\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid getParticlesFromChildrenHFR_outgoing_col(int j, int k, int cone_parent, std::vector<int>& searchNodes) {\n\tif (tree[j][k].isLeaf) {\n\t\tsearchNodes.insert(searchNodes.end(), tree[j][k].chargeLocations.begin(), tree[j][k].chargeLocations.end());\n\t}\n\telse {\n\t\tint J = j+1;//child\n\t\tint b = tree[j][k].boxNumber;\n\t\tif (j == level_LFR-1) {\n\t\t\tfor (int child = 0; child < 4; child++) {\n\t\t\t\tint KboxNumber = 4*b+child;\n\t\t\t\tstd::vector<int>::iterator indx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\t\t\tint K = indx-indexTree[J].begin();\n\t\t\t\tsearchNodes.insert(searchNodes.end(), tree[J][K].outgoing_chargePoints.begin(), tree[J][K].outgoing_chargePoints.end());//outgoing_chargePoints\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tint cone_child =  cone_parent/2; //of j+1 level;//l'\n\t\t\tfor (int child = 0; child < 4; child++) {\n\t\t\t\tint KboxNumber = 4*b+child;\n\t\t\t\tstd::vector<int>::iterator indx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\t\t\tint K = indx-indexTree[J].begin();\n\t\t\t\tif (tree[J][K].isLeaf) {\n\t\t\t\t\tsearchNodes.insert(searchNodes.end(), tree[J][K].outgoing_chargePoints.begin(), tree[J][K].outgoing_chargePoints.end());//outgoing_chargePoints\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tsearchNodes.insert(searchNodes.end(), tree[J][K].ConeTree[cone_child].outgoing_chargePoints.begin(), tree[J][K].ConeTree[cone_child].outgoing_chargePoints.end());//outgoing_chargePoints\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid getNodes_HFR_outgoing_box(int j, int k, int& n_rows, int& n_cols, int& ComputedRank) {\n\tif (tree[j][k].active == true) {\n\t\tfor (int cone=0; cone<nCones[j]; ++cone) {\n\t\t\tstd::vector<int> boxA_Nodes;\n\t\t\tgetParticlesFromChildrenHFR_outgoing_col(j, k, cone, boxA_Nodes);\n\n\t\t\t//sort( boxA_Nodes.begin(), boxA_Nodes.end() );\n\t\t\t//boxA_Nodes.erase( unique( boxA_Nodes.begin(), boxA_Nodes.end() ), boxA_Nodes.end() );\n\n\t\t\tstd::vector<int> IL_Nodes;\n\t\t\tfor (int b = 0; b < tree[j][k].ConeTree[cone].InteractionList.size(); b++) {\n\t\t\t\t\tint jB = tree[j][k].ConeTree[cone].InteractionList[b].x;\n\t\t\t\t\tint boxB = tree[j][k].ConeTree[cone].InteractionList[b].y;\n\t\t\t\t\tdouble arg = atan2(tree[j][k].center.y-tree[jB][boxB].center.y, tree[j][k].center.x-tree[jB][boxB].center.x);\n\t\t\t\t\tdouble argB = fmod(arg+2*PI, 2*PI);\n\t\t\t\t\tint coneB = int(argB/ConeAperture[jB]);//=coneB; direction of nBox wrt k\n\t\t\t\t\tstd::vector<int> chargeLocations;\n\t\t\t\t\tgetParticlesFromChildrenHFR_outgoing_row(jB, boxB, coneB, chargeLocations);\n\t\t\t\t\tIL_Nodes.insert(IL_Nodes.end(), chargeLocations.begin(), chargeLocations.end());\n\t\t\t}\n\n\t\t\t//sort( IL_Nodes.begin(), IL_Nodes.end() );\n\t\t\t//IL_Nodes.erase( unique( IL_Nodes.begin(), IL_Nodes.end() ), IL_Nodes.end() );\n\n\t\t\tn_rows = IL_Nodes.size();\n\t\t\tn_cols = boxA_Nodes.size();\n\t\t\tint tol_pow = TOL_POW;\n\t\t\tdouble tol_ACA = pow(10,-1.0*tol_pow);\n\t\t\trow_indices = IL_Nodes;\n\t\t\tcol_indices = boxA_Nodes;\n\t\t\tstd::vector<int> row_bases, col_bases;\n\t\t\tif (n_rows != 0 && n_cols != 0) {\n\t\t\t\ttree[j][k].ConeTree[cone].ILActive = true;\n\t\t\t\tMat dummy;\n\t\t\t\tACA_only_nodes(row_bases, col_bases, ComputedRank, tol_ACA, dummy, tree[j][k].ConeTree[cone].outgoing_Ar);\n\t\t\t\tfor (int r = 0; r < row_bases.size(); r++) {\n\t\t\t\t\ttree[j][k].ConeTree[cone].outgoing_checkPoints.push_back(IL_Nodes[row_bases[r]]);\n\t\t\t\t}\n\t\t\t\tfor (int c = 0; c < col_bases.size(); c++) {\n\t\t\t\t\ttree[j][k].ConeTree[cone].outgoing_chargePoints.push_back(boxA_Nodes[col_bases[c]]);\n\t\t\t\t}\n\t\t\t\tstd::vector<int> row_indices_local;\n\t\t\t\tfor (size_t r = 0; r < row_bases.size(); r++) {\n\t\t\t\t\trow_indices_local.push_back(IL_Nodes[row_bases[r]]);\n\t\t\t\t}\n\t\t\t\tstd::vector<int> col_indices_local;\n\t\t\t\tfor (size_t c = 0; c < col_bases.size(); c++) {\n\t\t\t\t\tcol_indices_local.push_back(boxA_Nodes[col_bases[c]]);\n\t\t\t\t}\n\t\t\t\tMat Atilde = getMatrix(row_indices_local, col_indices_local);\n\t\t\t\ttree[j][k].ConeTree[cone].outgoing_Atilde_dec = Atilde.colPivHouseholderQr();\n\t\t\t}\n\t\t\tif (n_rows == 0) {\n\t\t\t\ttree[j][k].ConeTree[cone].ILActive = false;\n\t\t\t\tgetParticlesFromChildrenHFR_outgoing_col(j, k, cone, tree[j][k].ConeTree[cone].outgoing_chargePoints);\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid getNodes_HFR_outgoing_level(int j) { //HFR; cone interactions\n\t//for (int j=level_LFR-1; j>=2; --j) {\n\t\tint rankPerLevel = 0;\n\t\tint n_rows_checkpoint;\n\t\tint n_cols_checkpoint;\n\t\tint kMax;\n\t\tint n_rows, n_cols, ComputedRank;\n\t\tstd::vector<int> boxA_Particles_checkpoint;\n\t\tstd::vector<int> IL_Particles_checkpoint;\n\t\tfor (int k=0; k<tree[j].size(); ++k) {\n\t\t\tif (tree[j][k].isLeaf) {\n\t\t\t\tgetNodes_LFR_outgoing_box(j, k, n_rows, n_cols, ComputedRank);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tgetNodes_HFR_outgoing_box(j, k, n_rows, n_cols, ComputedRank);\n\t\t\t}\n\t\t\tif (rankPerLevel < ComputedRank) {\n\t\t\t\trankPerLevel = ComputedRank;\n\t\t\t\tn_rows_checkpoint = n_rows;\n\t\t\t\tn_cols_checkpoint = n_cols;\n\t\t\t\tkMax = k;\n\t\t\t}\n\t\t}\n\t//}\n\t\tcout << \"O;\tj: \" << j << \"\tNboxes: \" << tree[j].size() << \"\tk: \" << kMax << \"\trows,cols: \" << n_rows_checkpoint << \",\" << n_cols_checkpoint << \"\tCrank: \" << rankPerLevel << endl;\n\t}\n\nvoid getParticlesFromChildrenHFR_incoming_row(int j, int k, int cone_parent, std::vector<int>& searchNodes) {\n\tif (tree[j][k].isLeaf) {\n\t\tsearchNodes.insert(searchNodes.end(), tree[j][k].chargeLocations.begin(), tree[j][k].chargeLocations.end());\n\t}\n\telse {\n\t\tint J = j+1;//child\n\t\tint b = tree[j][k].boxNumber;\n\t\tif (j == level_LFR-1) {\n\t\t\tfor (int child = 0; child < 4; child++) {\n\t\t\t\tint KboxNumber = 4*b+child;\n\t\t\t\tstd::vector<int>::iterator indx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\t\t\tint K = indx-indexTree[J].begin();\n\t\t\t\tsearchNodes.insert(searchNodes.end(), tree[J][K].incoming_checkPoints.begin(), tree[J][K].incoming_checkPoints.end());//outgoing_chargePoints\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tint cone_child =  cone_parent/2; //of j+1 level;//l'\n\t\t\tfor (int child = 0; child < 4; child++) {\n\t\t\t\tint KboxNumber = 4*b+child;\n\t\t\t\tstd::vector<int>::iterator indx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\t\t\tint K = indx-indexTree[J].begin();\n\t\t\t\tif (tree[J][K].isLeaf) {\n\t\t\t\t\tsearchNodes.insert(searchNodes.end(), tree[J][K].incoming_checkPoints.begin(), tree[J][K].incoming_checkPoints.end());//outgoing_chargePoints\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tsearchNodes.insert(searchNodes.end(), tree[J][K].ConeTree[cone_child].incoming_checkPoints.begin(), tree[J][K].ConeTree[cone_child].incoming_checkPoints.end());//outgoing_chargePoints\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid getParticlesFromChildrenHFR_incoming_col(int j, int k, int cone_parent, std::vector<int>& searchNodes) {\n\tif (tree[j][k].isLeaf) {\n\t\tsearchNodes.insert(searchNodes.end(), tree[j][k].chargeLocations.begin(), tree[j][k].chargeLocations.end());\n\t}\n\telse {\n\t\tint J = j+1;//child\n\t\tint b = tree[j][k].boxNumber;\n\t\tif (j == level_LFR-1) {\n\t\t\tfor (int child = 0; child < 4; child++) {\n\t\t\t\tint KboxNumber = 4*b+child;\n\t\t\t\tstd::vector<int>::iterator indx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\t\t\tint K = indx-indexTree[J].begin();\n\t\t\t\tsearchNodes.insert(searchNodes.end(), tree[J][K].outgoing_chargePoints.begin(), tree[J][K].outgoing_chargePoints.end());//outgoing_chargePoints\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tint cone_child =  cone_parent/2; //of j+1 level;//l'\n\t\t\tfor (int child = 0; child < 4; child++) {\n\t\t\t\tint KboxNumber = 4*b+child;\n\t\t\t\tstd::vector<int>::iterator indx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\t\t\tint K = indx-indexTree[J].begin();\n\t\t\t\tif (tree[J][K].isLeaf) {\n\t\t\t\t\tsearchNodes.insert(searchNodes.end(), tree[J][K].outgoing_chargePoints.begin(), tree[J][K].outgoing_chargePoints.end());//outgoing_chargePoints\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tsearchNodes.insert(searchNodes.end(), tree[J][K].ConeTree[cone_child].outgoing_chargePoints.begin(), tree[J][K].ConeTree[cone_child].outgoing_chargePoints.end());//outgoing_chargePoints\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid getNodes_HFR_incoming_box(int j, int k, int& n_rows, int& n_cols, int& ComputedRank) {\n\tif (tree[j][k].active == true) {\n\t\tfor (int cone=0; cone<nCones[j]; ++cone) {\n\t\t\tstd::vector<int> boxA_Nodes;\n\t\t\tgetParticlesFromChildrenHFR_incoming_row(j, k, cone, boxA_Nodes);\n\n\t\t\t//sort( boxA_Nodes.begin(), boxA_Nodes.end() );\n\t\t\t//boxA_Nodes.erase( unique( boxA_Nodes.begin(), boxA_Nodes.end() ), boxA_Nodes.end() );\n\n\t\t\tstd::vector<int> IL_Nodes;\n\t\t\tfor (int b = 0; b < tree[j][k].ConeTree[cone].InteractionList.size(); b++) {\n\t\t\t\t\tint jB = tree[j][k].ConeTree[cone].InteractionList[b].x;\n\t\t\t\t\tint boxB = tree[j][k].ConeTree[cone].InteractionList[b].y;\n\t\t\t\t\tdouble arg = atan2(tree[j][k].center.y-tree[jB][boxB].center.y, tree[j][k].center.x-tree[jB][boxB].center.x);\n\t\t\t\t\tdouble argB = fmod(arg+2*PI, 2*PI);\n\t\t\t\t\tint coneB = int(argB/ConeAperture[jB]);//=coneB; direction of nBox wrt k\n\t\t\t\t\tstd::vector<int> chargeLocations;\n\t\t\t\t\tgetParticlesFromChildrenHFR_incoming_col(jB, boxB, coneB, chargeLocations);\n\t\t\t\t\tIL_Nodes.insert(IL_Nodes.end(), chargeLocations.begin(), chargeLocations.end());\n\t\t\t}\n\n\t\t\t//sort( IL_Nodes.begin(), IL_Nodes.end() );\n\t\t\t//IL_Nodes.erase( unique( IL_Nodes.begin(), IL_Nodes.end() ), IL_Nodes.end() );\n\n\t\t\tn_rows = boxA_Nodes.size();\n\t\t\tn_cols = IL_Nodes.size();\n\t\t\tint tol_pow = TOL_POW;\n\t\t\tdouble tol_ACA = pow(10,-1.0*tol_pow);\n\t\t\trow_indices = boxA_Nodes;\n\t\t\tcol_indices = IL_Nodes;\n\t\t\tstd::vector<int> row_bases, col_bases;\n\t\t\tif (n_rows != 0 && n_cols != 0) {\n\t\t\t\ttree[j][k].ConeTree[cone].ILActive = true;\n\t\t\t\tMat dummy1, dummy2;\n\t\t\t\tACA_only_nodes(row_bases, col_bases, ComputedRank, tol_ACA, dummy1, dummy2);\n\t\t\t\tfor (int r = 0; r < row_bases.size(); r++) {\n\t\t\t\t\ttree[j][k].ConeTree[cone].incoming_checkPoints.push_back(boxA_Nodes[row_bases[r]]);\n\t\t\t\t}\n\t\t\t\tfor (int c = 0; c < col_bases.size(); c++) {\n\t\t\t\t\ttree[j][k].ConeTree[cone].incoming_chargePoints.push_back(IL_Nodes[col_bases[c]]);\n\t\t\t\t}\n\t\t\t\tstd::vector<int> row_indices_local;\n\t\t\t\tfor (size_t r = 0; r < row_bases.size(); r++) {\n\t\t\t\t\trow_indices_local.push_back(boxA_Nodes[row_bases[r]]);\n\t\t\t\t}\n\t\t\t\tstd::vector<int> col_indices_local;\n\t\t\t\tfor (size_t c = 0; c < col_bases.size(); c++) {\n\t\t\t\t\tcol_indices_local.push_back(IL_Nodes[col_bases[c]]);\n\t\t\t\t}\n\t\t\t\tMat Atilde = getMatrix(row_indices_local, col_indices_local);\n\t\t\t\ttree[j][k].ConeTree[cone].incoming_Atilde_dec = Atilde.colPivHouseholderQr();\n\t\t\t}\n\t\t\tif (n_cols == 0) {\n\t\t\t\ttree[j][k].ConeTree[cone].ILActive = false;\n\t\t\t\tgetParticlesFromChildrenHFR_incoming_row(j, k, cone, tree[j][k].ConeTree[cone].incoming_checkPoints);\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid getNodes_HFR_incoming_level(int j) { //HFR; cone interactions\n\t\tint rankPerLevel = 0;\n\t\tint n_rows_checkpoint;\n\t\tint n_cols_checkpoint;\n\t\tint kMax;\n\t\tstd::vector<int> boxA_Particles_checkpoint;\n\t\tstd::vector<int> IL_Particles_checkpoint;\n\t\tint n_rows, n_cols, ComputedRank;\n\t\tfor (int k=0; k<tree[j].size(); ++k) {\n\t\t\tif (tree[j][k].isLeaf){\n\t\t\t\tgetNodes_LFR_incoming_box(j, k, n_rows, n_cols, ComputedRank);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tgetNodes_HFR_incoming_box(j, k, n_rows, n_cols, ComputedRank);\n\t\t\t}\n\t\t\tif (rankPerLevel < ComputedRank) {\n\t\t\t\trankPerLevel \t\t\t= ComputedRank;\n\t\t\t\tn_rows_checkpoint = n_rows;\n\t\t\t\tn_cols_checkpoint = n_cols;\n\t\t\t\tkMax \t\t\t\t\t\t\t= k;\n\t\t\t}\n\t\t}\n\tcout << \"I;\tj: \" << j << \"\tNboxes: \" << tree[j].size() << \"\tk: \" << kMax << \"\trows,cols: \" << n_rows_checkpoint << \",\" << n_cols_checkpoint << \"\tCrank: \" << rankPerLevel << endl;\n}\n\n\tvoid Assemble_HFR_M2M_ILActiveTrue(int j, int k, int cone_parent) {\n\t\t/*\n\t\tA = K(x^{B,o}, y^{B,o})\n\t\tx^{B,o}=tree[j][k].outgoing_checkPoints\n\t\ty^{B,o}=tree[j][k].outgoing_chargePoints\n\t\t*/\n\t\tstd::vector<int> source_points;// = tree[j][k].chargeLocations//source points\n\t\tint J = j+1;\n\t\tint b = tree[j][k].boxNumber;\n\t\tint KboxNumber;\n\t\tint K[4];\n\t\tstd::vector<int>::iterator indx;\n\t\tKboxNumber = 4*b+0;\n\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\tK[0] = indx-indexTree[J].begin();\n\t\tKboxNumber = 4*b+1;\n\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\tK[1] = indx-indexTree[J].begin();\n\t\tKboxNumber = 4*b+2;\n\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\tK[2] = indx-indexTree[J].begin();\n\t\tKboxNumber = 4*b+3;\n\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\tK[3] = indx-indexTree[J].begin();\n\t\tif (j==level_LFR-1) {\n\t\t\tfor (int child = 0; child < 4; child++) {\n\t\t\t\tsource_points.insert(source_points.end(), tree[J][K[child]].outgoing_chargePoints.begin(), tree[J][K[child]].outgoing_chargePoints.end());//outgoing_chargePoints\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tint cone_child =  cone_parent/2; //of j+1 level;//l'\n\t\t\tint Veclength = 0;\n\t\t\tfor (int child = 0; child < 4; child++) {\n\t\t\t\tif (tree[J][K[child]].isLeaf) {\n\t\t\t\t\tsource_points.insert(source_points.end(), tree[J][K[child]].outgoing_chargePoints.begin(), tree[J][K[child]].outgoing_chargePoints.end());//outgoing_chargePoints\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tsource_points.insert(source_points.end(), tree[J][K[child]].ConeTree[cone_child].outgoing_chargePoints.begin(), tree[J][K[child]].ConeTree[cone_child].outgoing_chargePoints.end());//outgoing_chargePoints\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tint n_rows = tree[j][k].ConeTree[cone_parent].outgoing_checkPoints.size();//outgoing_checkPoints\n\t\tint n_cols = source_points.size();\n\t\tif (n_rows != 0 && n_cols != 0) {\n\t\t\ttree[j][k].ConeTree[cone_parent].M2M = getMatrix(tree[j][k].ConeTree[cone_parent].outgoing_checkPoints, source_points);\n\t\t}\n\t}\n\n\tvoid HFR_M2M_ILActiveTrue(int j, int k, int cone_parent) {\n\t\t/*\n\t\tA = K(x^{B,o}, y^{B,o})\n\t\tx^{B,o}=tree[j][k].outgoing_checkPoints\n\t\ty^{B,o}=tree[j][k].outgoing_chargePoints\n\t\t*/\n\t\tstd::vector<int> source_points;// = tree[j][k].chargeLocations//source points\n\t\tVec source_densities;\n\t\tint J = j+1;\n\t\tint b = tree[j][k].boxNumber;\n\t\tint KboxNumber;\n\t\tint K[4];\n\t\tstd::vector<int>::iterator indx;\n\t\tKboxNumber = 4*b+0;\n\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\tK[0] = indx-indexTree[J].begin();\n\t\tKboxNumber = 4*b+1;\n\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\tK[1] = indx-indexTree[J].begin();\n\t\tKboxNumber = 4*b+2;\n\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\tK[2] = indx-indexTree[J].begin();\n\t\tKboxNumber = 4*b+3;\n\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\tK[3] = indx-indexTree[J].begin();\n\t\tif (j==level_LFR-1) {\n\t\t\tint Veclength = tree[J][K[0]].outgoing_charges.size()+tree[J][K[1]].outgoing_charges.size()+tree[J][K[2]].outgoing_charges.size()+tree[J][K[3]].outgoing_charges.size();\n\t\t\tsource_densities = Vec::Zero(Veclength);// = tree[j][k].multipoles//source densities\n\t\t\tint g = 0;\n\t\t\tfor (int child = 0; child < 4; child++) {//child\n\t\t\t\tfor (int l = 0; l < tree[J][K[child]].outgoing_charges.size(); l++) {\n\t\t\t\t\tsource_densities(g) = tree[J][K[child]].outgoing_charges(l);\n\t\t\t\t\t++g;\n\t\t\t\t}\n\t\t\t}\n\t\t\t/*for (int child = 0; child < 4; child++) {\n\t\t\t\tsource_points.insert(source_points.end(), tree[J][K[child]].outgoing_chargePoints.begin(), tree[J][K[child]].outgoing_chargePoints.end());//outgoing_chargePoints\n\t\t\t}*/\n\t\t}\n\t\telse {\n\t\t\tint cone_child =  cone_parent/2; //of j+1 level;//l'\n\t\t\tint Veclength = 0;\n\t\t\t//#pragma omp parallel for\n\t\t\tfor (int child = 0; child < 4; child++) {//child\n\t\t\t\tif (tree[J][K[child]].isLeaf) {\n\t\t\t\t\tVeclength += tree[J][K[child]].outgoing_charges.size();\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tVeclength += tree[J][K[child]].ConeTree[cone_child].outgoing_charges.size();\n\t\t\t\t}\n\t\t\t}\n\t\t\tsource_densities = Vec::Zero(Veclength);// = tree[j][k].multipoles//source densities\n\t\t\tint g = 0;\n\t\t\tfor (int child = 0; child < 4; child++) {//child\n\t\t\t\tif (tree[J][K[child]].isLeaf) {\n\t\t\t\t\tfor (int l = 0; l < tree[J][K[child]].outgoing_charges.size(); l++) {\n\t\t\t\t\t\tsource_densities(g) = tree[J][K[child]].outgoing_charges(l);\n\t\t\t\t\t\t++g;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tfor (int l = 0; l < tree[J][K[child]].ConeTree[cone_child].outgoing_charges.size(); l++) {\n\t\t\t\t\t\tsource_densities(g) = tree[J][K[child]].ConeTree[cone_child].outgoing_charges(l);\n\t\t\t\t\t\t++g;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t/*for (int child = 0; child < 4; child++) {\n\t\t\t\tif (tree[J][K[child]].isLeaf) {\n\t\t\t\t\tsource_points.insert(source_points.end(), tree[J][K[child]].outgoing_chargePoints.begin(), tree[J][K[child]].outgoing_chargePoints.end());//outgoing_chargePoints\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tsource_points.insert(source_points.end(), tree[J][K[child]].ConeTree[cone_child].outgoing_chargePoints.begin(), tree[J][K[child]].ConeTree[cone_child].outgoing_chargePoints.end());//outgoing_chargePoints\n\t\t\t\t}\n\t\t\t}*/\n\t\t}\n\t\tint n_rows = tree[j][k].ConeTree[cone_parent].outgoing_checkPoints.size();//outgoing_checkPoints\n\t\tint n_cols = source_densities.size();\n\t\tif (n_rows != 0 && n_cols != 0) {\n\t\t\t/*Mat R = getMatrix(tree[j][k].ConeTree[cone_parent].outgoing_checkPoints, source_points);\n\t\t\tMat Err = tree[j][k].ConeTree[cone_parent].outgoing_Ar-R;\n\t\t\tif (Err.norm() != 0.0) {\n\t\t\t\tcout << \"j: \" << j << \"\tk: \" << k << \"\tc: \" << cone_parent << \"\tEr: \" << Err.norm() << \"\tAr.n: \" << tree[j][k].ConeTree[cone_parent].outgoing_Ar.norm() << \", R.n: \" << R.norm() << endl;\n\t\t\t}\n\t\t\ttree[j][k].ConeTree[cone_parent].outgoing_potential = R*source_densities;//u^{B,o}*/\n\t\t\ttree[j][k].ConeTree[cone_parent].outgoing_potential = tree[j][k].ConeTree[cone_parent].M2M*source_densities;//u^{B,o}\n\t\t\ttree[j][k].ConeTree[cone_parent].outgoing_charges = tree[j][k].ConeTree[cone_parent].outgoing_Atilde_dec.solve(tree[j][k].ConeTree[cone_parent].outgoing_potential);//f^{B,o} //solve system: A\\tree[j][k].outgoing_potential\n\t\t}\n\t}\n\n\tvoid HFR_M2M_ILActiveFalse(int j, int k, int cone_parent) {\n\t\tint J = j+1;\n\t\tint b = tree[j][k].boxNumber;\n\t\tint KboxNumber;\n\t\tint K[4];\n\t\tstd::vector<int>::iterator indx;\n\t\tKboxNumber = 4*b+0;\n\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\tK[0] = indx-indexTree[J].begin();\n\t\tKboxNumber = 4*b+1;\n\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\tK[1] = indx-indexTree[J].begin();\n\t\tKboxNumber = 4*b+2;\n\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\tK[2] = indx-indexTree[J].begin();\n\t\tKboxNumber = 4*b+3;\n\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\tK[3] = indx-indexTree[J].begin();\n\t\tif (j==level_LFR-1) {\n\t\t\tint Veclength = tree[J][K[0]].outgoing_charges.size()+tree[J][K[1]].outgoing_charges.size()+tree[J][K[2]].outgoing_charges.size()+tree[J][K[3]].outgoing_charges.size();\n\t\t\ttree[j][k].ConeTree[cone_parent].outgoing_charges = Vec::Zero(Veclength);// = tree[j][k].multipoles//source densities\n\t\t\tint g = 0;\n\t\t\tfor (int child = 0; child < 4; child++) {//child\n\t\t\t\tfor (int l = 0; l < tree[J][K[child]].outgoing_charges.size(); l++) {\n\t\t\t\t\ttree[j][k].ConeTree[cone_parent].outgoing_charges(g) = tree[J][K[child]].outgoing_charges(l);\n\t\t\t\t\t++g;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tint cone_child =  cone_parent/2; //of j+1 level;//l'\n\t\t\tint Veclength = 0;\n\t\t\t//#pragma omp parallel for\n\t\t\tfor (int child = 0; child < 4; child++) {//child\n\t\t\t\tif (tree[J][K[child]].isLeaf) {\n\t\t\t\t\tVeclength += tree[J][K[child]].outgoing_charges.size();\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tVeclength += tree[J][K[child]].ConeTree[cone_child].outgoing_charges.size();\n\t\t\t\t}\n\t\t\t}\n\t\t\ttree[j][k].ConeTree[cone_parent].outgoing_charges = Vec::Zero(Veclength);// = tree[j][k].multipoles//source densities\n\t\t\tint g = 0;\n\t\t\tfor (int child = 0; child < 4; child++) {//child\n\t\t\t\tif (tree[J][K[child]].isLeaf) {\n\t\t\t\t\tfor (int l = 0; l < tree[J][K[child]].outgoing_charges.size(); l++) {\n\t\t\t\t\t\ttree[j][k].ConeTree[cone_parent].outgoing_charges(g) = tree[J][K[child]].outgoing_charges(l);\n\t\t\t\t\t\t++g;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tfor (int l = 0; l < tree[J][K[child]].ConeTree[cone_child].outgoing_charges.size(); l++) {\n\t\t\t\t\t\ttree[j][k].ConeTree[cone_parent].outgoing_charges(g) = tree[J][K[child]].ConeTree[cone_child].outgoing_charges(l);\n\t\t\t\t\t\t++g;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid HFR_M2M() {//outgoing operations\n\t\t/*\n\t\ttree[j][k].multipoles//source densities\n\t\ttree[j][k].chargeLocations//source points\n\t\tx^{B,o}=tree[j][k].outgoing_checkPoints\n\t\tkernel evaluation between x^{B,o} and source points\n\t\t*/\n\t\tfor (int j=level_LFR-1; j>=2; --j) {\n\t\t\t//#pragma omp parallel for\n\t\t\tfor (int k=0; k<tree[j].size(); ++k) {\n\t\t\t\tif (tree[j][k].isLeaf){\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (tree[j][k].active == true) {\n\t\t\t\t\t//#pragma omp parallel for\n\t\t\t\t\tfor (int cone_parent = 0; cone_parent < nCones[j]; cone_parent++) {//pick l\n\t\t\t\t\t\tif (tree[j][k].ConeTree[cone_parent].ILActive) {\n\t\t\t\t\t\t\tHFR_M2M_ILActiveTrue(j, k, cone_parent);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tHFR_M2M_ILActiveFalse(j, k, cone_parent);\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 Assemble_HFR_M2M() {//outgoing operations\n\t\t/*\n\t\ttree[j][k].multipoles//source densities\n\t\ttree[j][k].chargeLocations//source points\n\t\tx^{B,o}=tree[j][k].outgoing_checkPoints\n\t\tkernel evaluation between x^{B,o} and source points\n\t\t*/\n\t\tfor (int j=level_LFR-1; j>=2; --j) {\n\t\t\t//#pragma omp parallel for\n\t\t\tfor (int k=0; k<tree[j].size(); ++k) {\n\t\t\t\tif (tree[j][k].isLeaf){\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (tree[j][k].active == true) {\n\t\t\t\t\t//#pragma omp parallel for\n\t\t\t\t\tfor (int cone_parent = 0; cone_parent < nCones[j]; cone_parent++) {//pick l\n\t\t\t\t\t\tif (tree[j][k].ConeTree[cone_parent].ILActive) {\n\t\t\t\t\t\t\tAssemble_HFR_M2M_ILActiveTrue(j, k, cone_parent);\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 Assemble_HFR_M2L() {\n\t\t/*\n\t\tl:tree[j][boxA].ConeTree[coneA]; l':tree[j][boxB].ConeTree[coneB]\n\t\tu^{B,i,l'}: tree[j][boxB].ConeTree[coneB].incoming_potential\n\t\tx^{B,i,l'}: tree[j][boxB].ConeTree[coneB].incoming_checkPoints\n\t\tf^{A,o,l}: tree[j][boxA].ConeTree[coneA].outgoing_charges\n\t\ty^{A,o,l}: tree[j][boxA].ConeTree[coneA].outgoing_chargePoints\n\t\t*/\n\t\t//#pragma omp parallel for\n\t\tfor (int j=2; j<level_LFR; ++j) {//parent\n\t\t\t//#pragma omp parallel for\n\t\t\tfor (int k=0; k < tree[j].size(); ++k) {\n\t\t\t\tif (tree[j][k].isLeaf){\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (tree[j][k].active) {\n\t\t\t\t\t//#pragma omp parallel for\n\t\t\t\t\tfor (int coneB = 0; coneB < nCones[j]; coneB++) {\n\t\t\t\t\t\t//tree[j][k].ConeTree[coneB].incoming_potential = Vec::Zero(tree[j][k].ConeTree[coneB].user_checkPoints.size());\n\t\t\t\t\t\tif (tree[j][k].ConeTree[coneB].ILActive) {\n\t\t\t\t\t\t\tint numIL = tree[j][k].ConeTree[coneB].InteractionList.size();\n\t\t\t\t\t\t\tfor (int l = 0; l < numIL; l++) {\n\t\t\t\t\t\t\t\tint jIL = tree[j][k].ConeTree[coneB].InteractionList[l].x;\n\t\t\t\t\t\t\t\tint kIL = tree[j][k].ConeTree[coneB].InteractionList[l].y;\n\t\t\t\t\t\t\t\tif (tree[jIL][kIL].isLeaf) {//LFR\n\t\t\t\t\t\t\t\t\tint n_rows = tree[j][k].ConeTree[coneB].user_checkPoints.size();\n\t\t\t\t\t\t\t\t\tint n_cols = tree[jIL][kIL].outgoing_chargePoints.size();//outgoing_chargePoints\n\t\t\t\t\t\t\t\t\tint RHS_size = tree[jIL][kIL].outgoing_charges.size();\n\t\t\t\t\t\t\t\t\tif (n_rows != 0 && n_cols != 0) {\n\t\t\t\t\t\t\t\t\t\ttree[j][k].ConeTree[coneB].M2L.push_back(getMatrix(tree[j][k].ConeTree[coneB].user_checkPoints, tree[jIL][kIL].outgoing_chargePoints));\n\t\t\t\t\t\t\t\t\t\t//tree[j][k].ConeTree[coneB].incoming_potential += R*tree[jIL][kIL].outgoing_charges;//u^{B,o}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\tdouble arg = atan2(tree[j][k].center.y-tree[jIL][kIL].center.y, tree[j][k].center.x-tree[jIL][kIL].center.x);\n\t\t\t\t\t\t\t\t\tdouble argA = fmod(arg+2*PI, 2*PI);\n\t\t\t\t\t\t\t\t\tint coneA = int(argA/ConeAperture[jIL]);//=coneB; direction of nBox wrt k\n\t\t\t\t\t\t\t\t\tint n_rows = tree[j][k].ConeTree[coneB].user_checkPoints.size();\n\t\t\t\t\t\t\t\t\tint n_cols = tree[jIL][kIL].ConeTree[coneA].outgoing_chargePoints.size();//outgoing_chargePoints\n\t\t\t\t\t\t\t\t\tint RHS_size = tree[jIL][kIL].ConeTree[coneA].outgoing_charges.size();\n\t\t\t\t\t\t\t\t\tif (n_rows != 0 && n_cols != 0) {\n\t\t\t\t\t\t\t\t\t\ttree[j][k].ConeTree[coneB].M2L.push_back(getMatrix(tree[j][k].ConeTree[coneB].user_checkPoints, tree[jIL][kIL].ConeTree[coneA].outgoing_chargePoints));\n\t\t\t\t\t\t\t\t\t\t//tree[j][k].ConeTree[coneB].incoming_potential += R*tree[jIL][kIL].ConeTree[coneA].outgoing_charges;//u^{B,o}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid HFR_M2L() {\n\t\t/*\n\t\tl:tree[j][boxA].ConeTree[coneA]; l':tree[j][boxB].ConeTree[coneB]\n\t\tu^{B,i,l'}: tree[j][boxB].ConeTree[coneB].incoming_potential\n\t\tx^{B,i,l'}: tree[j][boxB].ConeTree[coneB].incoming_checkPoints\n\t\tf^{A,o,l}: tree[j][boxA].ConeTree[coneA].outgoing_charges\n\t\ty^{A,o,l}: tree[j][boxA].ConeTree[coneA].outgoing_chargePoints\n\t\t*/\n\t\t//#pragma omp parallel for\n\t\tfor (int j=2; j<level_LFR; ++j) {//parent\n\t\t\t//#pragma omp parallel for\n\t\t\tfor (int k=0; k < tree[j].size(); ++k) {\n\t\t\t\tif (tree[j][k].isLeaf){\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (tree[j][k].active) {\n\t\t\t\t\t//#pragma omp parallel for\n\t\t\t\t\tfor (int coneB = 0; coneB < nCones[j]; coneB++) {\n\t\t\t\t\t\ttree[j][k].ConeTree[coneB].incoming_potential = Vec::Zero(tree[j][k].ConeTree[coneB].user_checkPoints.size());\n\t\t\t\t\t\tif (tree[j][k].ConeTree[coneB].ILActive) {\n\t\t\t\t\t\t\tint numIL = tree[j][k].ConeTree[coneB].InteractionList.size();\n\t\t\t\t\t\t\t//#pragma omp parallel for\n\t\t\t\t\t\t\tfor (int l = 0; l < numIL; l++) {\n\t\t\t\t\t\t\t\tint jIL = tree[j][k].ConeTree[coneB].InteractionList[l].x;\n\t\t\t\t\t\t\t\tint kIL = tree[j][k].ConeTree[coneB].InteractionList[l].y;\n\t\t\t\t\t\t\t\tif (tree[jIL][kIL].isLeaf) {//LFR\n\t\t\t\t\t\t\t\t\tint n_rows = tree[j][k].ConeTree[coneB].user_checkPoints.size();\n\t\t\t\t\t\t\t\t\tint n_cols = tree[jIL][kIL].outgoing_chargePoints.size();//outgoing_chargePoints\n\t\t\t\t\t\t\t\t\tint RHS_size = tree[jIL][kIL].outgoing_charges.size();\n\t\t\t\t\t\t\t\t\tif (n_rows != 0 && n_cols != 0 && RHS_size != 0) {\n\t\t\t\t\t\t\t\t\t\t/*Mat R = getMatrix(tree[j][k].ConeTree[coneB].user_checkPoints, tree[jIL][kIL].outgoing_chargePoints);\n\t\t\t\t\t\t\t\t\t\tMat Err = tree[j][k].ConeTree[coneB].M2L[l]-R;\n\t\t\t\t\t\t\t\t\t\tif (Err.norm() != 0.0) {\n\t\t\t\t\t\t\t\t\t\t\tcout << \"j: \" << j << \"\tk: \" << k << \"\tconeB: \" << coneB << \"\tErr: \" << Err.norm() << endl;\n\t\t\t\t\t\t\t\t\t\t}*/\n\t\t\t\t\t\t\t\t\t\ttree[j][k].ConeTree[coneB].incoming_potential += tree[j][k].ConeTree[coneB].M2L[l]*tree[jIL][kIL].outgoing_charges;//u^{B,o}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\tdouble arg = atan2(tree[j][k].center.y-tree[jIL][kIL].center.y, tree[j][k].center.x-tree[jIL][kIL].center.x);\n\t\t\t\t\t\t\t\t\tdouble argA = fmod(arg+2*PI, 2*PI);\n\t\t\t\t\t\t\t\t\tint coneA = int(argA/ConeAperture[jIL]);//=coneB; direction of nBox wrt k\n\t\t\t\t\t\t\t\t\tint n_rows = tree[j][k].ConeTree[coneB].user_checkPoints.size();\n\t\t\t\t\t\t\t\t\tint n_cols = tree[jIL][kIL].ConeTree[coneA].outgoing_chargePoints.size();//outgoing_chargePoints\n\t\t\t\t\t\t\t\t\tint RHS_size = tree[jIL][kIL].ConeTree[coneA].outgoing_charges.size();\n\t\t\t\t\t\t\t\t\tif (n_rows != 0 && n_cols != 0 && RHS_size != 0) {\n\t\t\t\t\t\t\t\t\t\t/*Mat R = getMatrix(tree[j][k].ConeTree[coneB].user_checkPoints, tree[jIL][kIL].ConeTree[coneA].outgoing_chargePoints);\n\t\t\t\t\t\t\t\t\t\tMat Err = tree[j][k].ConeTree[coneB].M2L[l]-R;\n\t\t\t\t\t\t\t\t\t\tif (Err.norm() != 0.0) {\n\t\t\t\t\t\t\t\t\t\t\tcout << \"j: \" << j << \"\tk: \" << k << \"\tconeB: \" << coneB << \"\tErr: \" << Err.norm() << endl;\n\t\t\t\t\t\t\t\t\t\t}*/\n\t\t\t\t\t\t\t\t\t\ttree[j][k].ConeTree[coneB].incoming_potential += tree[j][k].ConeTree[coneB].M2L[l]*tree[jIL][kIL].ConeTree[coneA].outgoing_charges;//u^{B,o}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid Assemble_HFR_L2L_ILActiveTrue (int j, int k, int cone_parent) {\n\t\tint J = j+1;\n\t\tint b = tree[j][k].boxNumber;\n\t\tint KboxNumber;\n\t\tint K[4];\n\t\tstd::vector<int>::iterator indx;\n\t\tKboxNumber = 4*b+0;\n\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\tK[0] = indx-indexTree[J].begin();\n\t\tKboxNumber = 4*b+1;\n\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\tK[1] = indx-indexTree[J].begin();\n\t\tKboxNumber = 4*b+2;\n\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\tK[2] = indx-indexTree[J].begin();\n\t\tKboxNumber = 4*b+3;\n\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\tK[3] = indx-indexTree[J].begin();\n\t\t//#pragma omp parallel for\n\t\tfor (int child = 0; child < 4; child++) {\n\t\t\t//cout << \"J: \" << J << \"\tK: \" << K[child] << \"\tiL: \" << tree[J][K[child]].isLeaf << endl;\n\t\t\tif (j==level_LFR-1) {\n\t\t\t\tif (level_LFR != nLevels) {\n\t\t\t\t\tif (!tree[J][K[child]].isLeaf) {\n\t\t\t\t\t\tint n_rows = tree[J][K[child]].user_checkPoints.size();\n\t\t\t\t\t\tint n_cols = tree[j][k].ConeTree[cone_parent].incoming_chargePoints.size();\n\t\t\t\t\t\tif (n_rows != 0 && n_cols != 0) {\n\t\t\t\t\t\t\ttree[j][k].ConeTree[cone_parent].L2L[child] = getMatrix(tree[J][K[child]].user_checkPoints, tree[j][k].ConeTree[cone_parent].incoming_chargePoints);\n\t\t\t\t\t\t\t//tree[J][K[child]].incoming_potential += tree[J][K[child]].L2L*tree[j][k].ConeTree[cone_parent].incoming_charges;//u^{B,o}\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\tint n_rows = tree[J][K[child]].chargeLocations.size();\n\t\t\t\t\t\tint n_cols = tree[j][k].ConeTree[cone_parent].incoming_chargePoints.size();\n\t\t\t\t\t\tif (n_rows != 0 && n_cols != 0) {\n\t\t\t\t\t\t\ttree[j][k].ConeTree[cone_parent].L2L[child] = getMatrix(tree[J][K[child]].chargeLocations, tree[j][k].ConeTree[cone_parent].incoming_chargePoints);\n\t\t\t\t\t\t\t//tree[J][K[child]].incoming_potential += tree[J][K[child]].L2L*tree[j][k].ConeTree[cone_parent].incoming_charges;//u^{B,o}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tint n_rows = tree[J][K[child]].chargeLocations.size();\n\t\t\t\t\tint n_cols = tree[j][k].ConeTree[cone_parent].incoming_chargePoints.size();\n\t\t\t\t\tif (n_rows != 0 && n_cols != 0) {\n\t\t\t\t\t\ttree[j][k].ConeTree[cone_parent].L2L[child] = getMatrix(tree[J][K[child]].chargeLocations, tree[j][k].ConeTree[cone_parent].incoming_chargePoints);\n\t\t\t\t\t\t//tree[J][K[child]].incoming_potential += tree[J][K[child]].L2L*tree[j][k].ConeTree[cone_parent].incoming_charges;//u^{B,o}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tint cone_child = cone_parent/2;\n\t\t\t\tif (!tree[J][K[child]].isLeaf) {\n\t\t\t\t\t//cout << \"J: \" << J << \"\tK: \" << K[child] << \"\trc: \" << tree[J][K[child]].ConeTree[cone_child].L2L.rows() << \", \" << tree[J][K[child]].ConeTree[cone_child].L2L.cols() << \"\trhs: \" << tree[j][k].ConeTree[cone_parent].incoming_charges.size() << endl;\n\n\t\t\t\t\tint n_rows = tree[J][K[child]].ConeTree[cone_child].user_checkPoints.size();\n\t\t\t\t\tint n_cols = tree[j][k].ConeTree[cone_parent].incoming_chargePoints.size();\n\t\t\t\t\tif (n_rows != 0 && n_cols != 0) {\n\t\t\t\t\t\ttree[j][k].ConeTree[cone_parent].L2L[child] = getMatrix(tree[J][K[child]].ConeTree[cone_child].user_checkPoints, tree[j][k].ConeTree[cone_parent].incoming_chargePoints);\n\t\t\t\t\t\t//tree[J][K[child]].ConeTree[cone_child].incoming_potential += tree[J][K[child]].ConeTree[cone_child].L2L*tree[j][k].ConeTree[cone_parent].incoming_charges;//u^{B,o}\n\t\t\t\t\t}\n\t\t\t\t\t//cout << \"done\" << endl;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tint n_rows = tree[J][K[child]].user_checkPoints.size();\n\t\t\t\t\tint n_cols = tree[j][k].ConeTree[cone_parent].incoming_chargePoints.size();\n\t\t\t\t\t//cout << \"J: \" << J << \"\tK: \" << K[child] << \"\trc: \" << tree[J][K[child]].L2L.rows() << \", \" << tree[J][K[child]].L2L.cols() << \"\trhs: \" << tree[j][k].ConeTree[cone_parent].incoming_charges.size() << \", \" << tree[j][k].ConeTree[cone_parent].incoming_chargePoints.size() << endl;\n\t\t\t\t\tif (n_rows != 0 && n_cols != 0) {\n\t\t\t\t\t\ttree[j][k].ConeTree[cone_parent].L2L[child] = getMatrix(tree[J][K[child]].user_checkPoints, tree[j][k].ConeTree[cone_parent].incoming_chargePoints);\n\t\t\t\t\t\t//cout << \"R.rc: \" << tree[J][K[child]].L2L.rows() << \", \" << tree[J][K[child]].L2L.cols() << endl;\n\t\t\t\t\t\t//tree[J][K[child]].incoming_potential += tree[J][K[child]].L2L*tree[j][k].ConeTree[cone_parent].incoming_charges;//u^{B,o}\n\t\t\t\t\t}\n\t\t\t\t\t//cout << \"done\" << endl;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid HFR_L2L_ILActiveTrue (int j, int k, int cone_parent) {\n\t\t/*\n\t\tx^{C,i}: tree[J][4*k+c].incoming_checkPoints\n\t\tf^{B,i,l}: tree[j][k].ConeTree[cone_parent].incoming_charges\n\t\ty^{B,i,l}: tree[j][k].ConeTree[cone_parent].incoming_chargePoints\n\t\tx^{C,i}: tree[J][4*k+c].incoming_checkPoints\n\t\tf^{B,i,l}: tree[j][k].ConeTree[cone_parent].incoming_charges\n\t\ty^{B,i,l}: tree[j][k].ConeTree[cone_parent].incoming_chargePoints\n\t\tx^{C,i,l'}: tree[J][4*k+c].ConeTree[cone_child].incoming_checkPoints\n\t\tf^{B,i,l}: tree[j][k].ConeTree[cone_parent].incoming_charges\n\t\ty^{B,i,l}: tree[j][k].ConeTree[cone_parent].incoming_chargePoints\n\t\t*/\n\t\ttree[j][k].ConeTree[cone_parent].incoming_charges = tree[j][k].ConeTree[cone_parent].incoming_Atilde_dec.solve(tree[j][k].ConeTree[cone_parent].incoming_potential);//f^{B,o} //solve system: A\\tree[j][k].outgoing_potential\n\t\tint J = j+1;\n\t\tint b = tree[j][k].boxNumber;\n\t\tint KboxNumber;\n\t\tint K[4];\n\t\tstd::vector<int>::iterator indx;\n\t\tKboxNumber = 4*b+0;\n\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\tK[0] = indx-indexTree[J].begin();\n\t\tKboxNumber = 4*b+1;\n\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\tK[1] = indx-indexTree[J].begin();\n\t\tKboxNumber = 4*b+2;\n\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\tK[2] = indx-indexTree[J].begin();\n\t\tKboxNumber = 4*b+3;\n\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\tK[3] = indx-indexTree[J].begin();\n\t\t//#pragma omp parallel for\n\t\tfor (int child = 0; child < 4; child++) {\n\t\t\tif (j==level_LFR-1) {\n\t\t\t\tif (level_LFR != nLevels) {\n\t\t\t\t\tif (!tree[J][K[child]].isLeaf) {\n\t\t\t\t\t\tint n_rows = tree[J][K[child]].user_checkPoints.size();\n\t\t\t\t\t\tint n_cols = tree[j][k].ConeTree[cone_parent].incoming_chargePoints.size();\n\t\t\t\t\t\tif (n_rows != 0 && n_cols != 0) {\n\t\t\t\t\t\t\t/*Mat R = getMatrix(tree[J][K[child]].user_checkPoints, tree[j][k].ConeTree[cone_parent].incoming_chargePoints);\n\t\t\t\t\t\t\tMat Err = tree[j][k].ConeTree[cone_parent].L2L[child]-R;\n\t\t\t\t\t\t\tif (Err.norm() != 0.0) {\n\t\t\t\t\t\t\t\tcout << \"J: \" << J << \"\tK[child]: \" << K[child] << \"\tcone_parent: \" << cone_parent << \"\tErr: \" << Err.norm() << endl;\n\t\t\t\t\t\t\t}*/\n\t\t\t\t\t\t\ttree[J][K[child]].incoming_potential += tree[j][k].ConeTree[cone_parent].L2L[child]*tree[j][k].ConeTree[cone_parent].incoming_charges;//u^{B,o}\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\tint n_rows = tree[J][K[child]].chargeLocations.size();\n\t\t\t\t\t\tint n_cols = tree[j][k].ConeTree[cone_parent].incoming_chargePoints.size();\n\t\t\t\t\t\tif (n_rows != 0 && n_cols != 0) {\n\t\t\t\t\t\t\t/*Mat R = getMatrix(tree[J][K[child]].chargeLocations, tree[j][k].ConeTree[cone_parent].incoming_chargePoints);\n\t\t\t\t\t\t\tMat Err = tree[j][k].ConeTree[cone_parent].L2L[child]-R;\n\t\t\t\t\t\t\tif (Err.norm() != 0.0) {\n\t\t\t\t\t\t\t\tcout << \"J: \" << J << \"\tK[child]: \" << K[child] << \"\tcone_parent: \" << cone_parent << \"\tErr: \" << Err.norm() << endl;\n\t\t\t\t\t\t\t}*/\n\t\t\t\t\t\t\ttree[J][K[child]].incoming_potential += tree[j][k].ConeTree[cone_parent].L2L[child]*tree[j][k].ConeTree[cone_parent].incoming_charges;//u^{B,o}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tint n_rows = tree[J][K[child]].chargeLocations.size();\n\t\t\t\t\tint n_cols = tree[j][k].ConeTree[cone_parent].incoming_chargePoints.size();\n\t\t\t\t\tif (n_rows != 0 && n_cols != 0) {\n\t\t\t\t\t\t/*Mat R = getMatrix(tree[J][K[child]].chargeLocations, tree[j][k].ConeTree[cone_parent].incoming_chargePoints);\n\t\t\t\t\t\tMat Err = tree[j][k].ConeTree[cone_parent].L2L[child]-R;\n\t\t\t\t\t\tif (Err.norm() != 0.0) {\n\t\t\t\t\t\t\tcout << \"J: \" << J << \"\tK[child]: \" << K[child] << \"\tcone_parent: \" << cone_parent << \"\tErr: \" << Err.norm() << endl;\n\t\t\t\t\t\t}*/\n\t\t\t\t\t\ttree[J][K[child]].incoming_potential += tree[j][k].ConeTree[cone_parent].L2L[child]*tree[j][k].ConeTree[cone_parent].incoming_charges;//u^{B,o}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tint cone_child = cone_parent/2;\n\t\t\t\tif (!tree[J][K[child]].isLeaf) {\n\t\t\t\t\tint n_rows = tree[J][K[child]].ConeTree[cone_child].user_checkPoints.size();\n\t\t\t\t\tint n_cols = tree[j][k].ConeTree[cone_parent].incoming_chargePoints.size();\n\t\t\t\t\tif (n_rows != 0 && n_cols != 0) {\n\t\t\t\t\t\t/*Mat R = getMatrix(tree[J][K[child]].ConeTree[cone_child].user_checkPoints, tree[j][k].ConeTree[cone_parent].incoming_chargePoints);\n\t\t\t\t\t\tMat Err = tree[j][k].ConeTree[cone_parent].L2L[child]-R;\n\t\t\t\t\t\tif (Err.norm() != 0.0) {\n\t\t\t\t\t\t\tcout << \"J: \" << J << \"\tK[child]: \" << K[child] << \"\tcone_child: \" << cone_child << \"\tErr: \" << Err.norm() << endl;\n\t\t\t\t\t\t}*/\n\t\t\t\t\t\ttree[J][K[child]].ConeTree[cone_child].incoming_potential += tree[j][k].ConeTree[cone_parent].L2L[child]*tree[j][k].ConeTree[cone_parent].incoming_charges;//u^{B,o}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tint n_rows = tree[J][K[child]].user_checkPoints.size();\n\t\t\t\t\tint n_cols = tree[j][k].ConeTree[cone_parent].incoming_chargePoints.size();\n\t\t\t\t\tif (n_rows != 0 && n_cols != 0) {\n\t\t\t\t\t\t/*Mat R = getMatrix(tree[J][K[child]].user_checkPoints, tree[j][k].ConeTree[cone_parent].incoming_chargePoints);\n\t\t\t\t\t\tMat Err = tree[j][k].ConeTree[cone_parent].L2L[child]-R;\n\t\t\t\t\t\tif (Err.norm() != 0.0) {\n\t\t\t\t\t\t\tcout << \"J: \" << J << \"\tK[child]: \" << K[child] << \"\tcone_child: \" << cone_child << \"\tErr: \" << Err.norm() << endl;\n\t\t\t\t\t\t}*/\n\t\t\t\t\t\ttree[J][K[child]].incoming_potential += tree[j][k].ConeTree[cone_parent].L2L[child]*tree[j][k].ConeTree[cone_parent].incoming_charges;//u^{B,o}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid HFR_L2L_ILActiveFalse(int j, int k, int cone_parent) {\n\t\tint J = j+1;\n\t\tint b = tree[j][k].boxNumber;\n\t\tint KboxNumber;\n\t\tint K[4];\n\t\tstd::vector<int>::iterator indx;\n\t\tKboxNumber = 4*b+0;\n\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\tK[0] = indx-indexTree[J].begin();\n\t\tKboxNumber = 4*b+1;\n\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\tK[1] = indx-indexTree[J].begin();\n\t\tKboxNumber = 4*b+2;\n\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\tK[2] = indx-indexTree[J].begin();\n\t\tKboxNumber = 4*b+3;\n\t\tindx = std::find(indexTree[J].begin(), indexTree[J].end(), KboxNumber);\n\t\tK[3] = indx-indexTree[J].begin();\n\t\tint offset = 0;\n\t\tfor (int child = 0; child < 4; child++) {\n\t\t\tif (j==level_LFR-1) {\n\t\t\t\tif (level_LFR != nLevels) {\n\t\t\t\t\tif (!tree[J][K[child]].isLeaf) {\n\t\t\t\t\t\tfor (size_t i = 0; i < tree[J][K[child]].user_checkPoints.size(); i++) {\n\t\t\t\t\t\t\ttree[J][K[child]].incoming_potential(i) += tree[j][k].ConeTree[cone_parent].incoming_potential(offset+i);\n\t\t\t\t\t\t}\n\t\t\t\t\t\toffset += tree[J][K[child]].user_checkPoints.size();\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tfor (size_t i = 0; i < tree[J][K[child]].chargeLocations.size(); i++) {\n\t\t\t\t\t\t\ttree[J][K[child]].incoming_potential(i) += tree[j][k].ConeTree[cone_parent].incoming_potential(offset+i);\n\t\t\t\t\t\t}\n\t\t\t\t\t\toffset += tree[J][K[child]].chargeLocations.size();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tfor (size_t i = 0; i < tree[J][K[child]].chargeLocations.size(); i++) {\n\t\t\t\t\t\ttree[J][K[child]].incoming_potential(i) += tree[j][k].ConeTree[cone_parent].incoming_potential(offset+i);\n\t\t\t\t\t}\n\t\t\t\t\toffset += tree[J][K[child]].chargeLocations.size();\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tint cone_child = cone_parent/2;\n\t\t\t\tif (tree[J][K[child]].isLeaf) {\n\t\t\t\t\tfor (size_t i = 0; i < tree[J][K[child]].user_checkPoints.size(); i++) {\n\t\t\t\t\t\ttree[J][K[child]].incoming_potential(i) += tree[j][k].ConeTree[cone_parent].incoming_potential(offset+i);\n\t\t\t\t\t}\n\t\t\t\t\toffset += tree[J][K[child]].user_checkPoints.size();\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tfor (size_t i = 0; i < tree[J][K[child]].ConeTree[cone_child].user_checkPoints.size(); i++) {\n\t\t\t\t\t\ttree[J][K[child]].ConeTree[cone_child].incoming_potential(i) += tree[j][k].ConeTree[cone_parent].incoming_potential(offset+i);\n\t\t\t\t\t}\n\t\t\t\t\toffset += tree[J][K[child]].ConeTree[cone_child].user_checkPoints.size();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid Assemble_HFR_L2L() {//outgoing operations; finds locals untill level: level_LFR\n\t\t/*\n\t\ttree[j][k].multipoles//source densities\n\t\ttree[j][k].chargeLocations//source points\n\t\tx^{B,o}=tree[j][k].outgoing_checkPoints\n\t\tkernel evaluation between x^{B,o} and source points\n\t\t*/\n\t\tfor (int j=2; j<level_LFR; ++j) {//parent\n\t\t\t//#pragma omp parallel for\n\t\t\tfor (int k=0; k<tree[j].size(); ++k) {\n\t\t\t\tif (tree[j][k].isLeaf){\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (tree[j][k].active == true && !tree[j][k].isLeaf) {\n\t\t\t\t\t//#pragma omp parallel for\n\t\t\t\t\tfor (int cone_parent = 0; cone_parent < nCones[j]; cone_parent++) {//pick l\n\t\t\t\t\t\tif (tree[j][k].ConeTree[cone_parent].ILActive) {\n\t\t\t\t\t\t\tAssemble_HFR_L2L_ILActiveTrue(j,k,cone_parent);\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 HFR_L2L() {//outgoing operations; finds locals untill level: level_LFR\n\t\t/*\n\t\ttree[j][k].multipoles//source densities\n\t\ttree[j][k].chargeLocations//source points\n\t\tx^{B,o}=tree[j][k].outgoing_checkPoints\n\t\tkernel evaluation between x^{B,o} and source points\n\t\t*/\n\t\tfor (int j=2; j<level_LFR; ++j) {//parent\n\t\t\t//#pragma omp parallel for\n\t\t\tfor (int k=0; k<tree[j].size(); ++k) {\n\t\t\t\tif (tree[j][k].isLeaf){\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (tree[j][k].active == true && !tree[j][k].isLeaf) {\n\t\t\t\t\t//#pragma omp parallel for\n\t\t\t\t\tfor (int cone_parent = 0; cone_parent < nCones[j]; cone_parent++) {//pick l\n\t\t\t\t\t\tif (tree[j][k].ConeTree[cone_parent].ILActive) {\n\t\t\t\t\t\t\tHFR_L2L_ILActiveTrue(j,k,cone_parent);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tHFR_L2L_ILActiveFalse(j,k,cone_parent);\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};\n\n#endif\n", "meta": {"hexsha": "0d8a6d326b2a328b8e4d03ed10e7a06f90b06942", "size": 157129, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "FMM2DTree_v2.hpp", "max_stars_repo_name": "sivaramambikasaran/DAFMM2D", "max_stars_repo_head_hexsha": "9577c5b0f6d2ca3123a1db64de51af48660e76ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "FMM2DTree_v2.hpp", "max_issues_repo_name": "sivaramambikasaran/DAFMM2D", "max_issues_repo_head_hexsha": "9577c5b0f6d2ca3123a1db64de51af48660e76ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "FMM2DTree_v2.hpp", "max_forks_repo_name": "sivaramambikasaran/DAFMM2D", "max_forks_repo_head_hexsha": "9577c5b0f6d2ca3123a1db64de51af48660e76ce", "max_forks_repo_licenses": ["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.0091857001, "max_line_length": 284, "alphanum_fraction": 0.6104920161, "num_tokens": 51455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.721743206297598, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.4701109582309302}}
{"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_CONSTANT_INVSQRTEPS_HPP_INCLUDED\n#define BOOST_SIMD_CONSTANT_INVSQRTEPS_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n  /*!\n    @ingroup group-constant\n\n    Generate  value \\f$\\1/sqrt(Eps<T>()\\f$\n\n    @return The Invsqrteps constant for the proper type\n  **/\n  template<typename T> T invsqrteps();\n\n  namespace functional\n  {\n    /*!\n      @ingroup group-callable-constant\n      Generate the  constant Invsqrteps.\n\n      @return The invsqrteps constant for the proper type\n    **/\n    const boost::dispatch::functor<tag::invsqrteps_> invsqrteps = {};\n  }\n} }\n#endif\n\n#include <boost/simd/constant/scalar/invsqrteps.hpp>\n#include <boost/simd/constant/simd/invsqrteps.hpp>\n\n#endif\n", "meta": {"hexsha": "10147d5f6beb490a14bdfda04d0ac8eec600b1ca", "size": 1119, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/constant/invsqrteps.hpp", "max_stars_repo_name": "TobiasLudwig/boost.simd", "max_stars_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/simd/constant/invsqrteps.hpp", "max_issues_repo_name": "TobiasLudwig/boost.simd", "max_issues_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/constant/invsqrteps.hpp", "max_forks_repo_name": "TobiasLudwig/boost.simd", "max_forks_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-02-16T09:58:18.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:22:43.000Z", "avg_line_length": 26.023255814, "max_line_length": 100, "alphanum_fraction": 0.5907059875, "num_tokens": 261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.47011095823093013}}
{"text": "/*  The compile and run commands are:\n\n\tCompile:- $ g++-7 mr-pr-cpp.cpp /usr/lib/x86_64-linux-gnu/libboost_system.a /usr/lib/x86_64-linux-gnu/libboost_iostreams.a /usr/lib/x86_64-linux-gnu/libboost_filesystem.a -pthread -o mr-pr-cpp.o\n\tRun:- $ ./mr-pr-cpp.o <input_file>.txt -o <output_file>.txt\n\t\t\n\t* Compile command assumes the presence of the Mapreduce include files in the cwd\n\t* Run command assumes the existence of a file <input_file>.txt in a directory named \"test\" in the cwd of the code\n\t* Run command also assumes the existence of a directory named \"output\" where it writes the outputs of the pagerank algorithm execution.  \n\n*/\n\n// Including the Boost configurations\n#include <boost/config.hpp>\n#if defined(BOOST_MSVC)\n#   pragma warning(disable: 4127)\n\n// turn off checked iterators to avoid performance hit\n#   if !defined(__SGI_STL_PORT)  &&  !defined(_DEBUG)\n#       define _SECURE_SCL 0\n#       define _HAS_ITERATOR_DEBUGGING 0\n#   endif\n#endif\n\n#include <bits/stdc++.h>\n#include \"mapreduce.hpp\"\nusing namespace std;\n\n// Functions for the proper usage of the code\nconst char *OUTPUT_ARG = \"-o\";\n\nvoid usage() {\n    cerr << \"Use the below format \" << endl\n    \t << \"pagerank <graph_file> -o <output_file>\" << endl\n         << \" -o enable output \" << endl;\n}\n\n// Global variables for the pagerank algorithm\nvector<vector<double>> intermediate_page(100000);\nvector<vector<int>> outgoing_links(100000);\nvector<double> pageranks(100000);\nvector<double> pageranks_calc(100000);\n\n// Parameters of alpha and convergence rate\ndouble alpha = 0.85;\ndouble conv = 0.00001;\ndouble dangling_pointer =0.0f;\nint total_webpages=0;\n\nnamespace page_rank {\n\ntemplate<typename MapTask>\nclass number_source : mapreduce::detail::noncopyable\n{\n  public:\n    number_source()\n      : sequence_(0)\n    {\n    }\n\n    bool const setup_key(typename MapTask::key_type &key)\n    {\n        key = sequence_++;\n        return (key <= total_webpages);\n    }\n\n    bool const get_data(typename MapTask::key_type const &key, typename MapTask::value_type &value)\n    {\n        value = pageranks[key];\n        return true;\n    }\n\n  private:\n    unsigned  sequence_;\n};\n\nstruct map_task : public mapreduce::map_task<unsigned, double>\n{\n    template<typename Runtime>\n    void operator()(Runtime &runtime, key_type const &key, value_type const &value) const\n    {\n\t\tint chilren = outgoing_links[key].size();\n\t\t\n\t\tif(chilren!=0){\n\t\t\tfor(int i =0; i<chilren; i++){\n\t\t        typename Runtime::reduce_task_type::key_type const emit_temp = outgoing_links[key][i];\n\t\t        double temp = double(value/chilren);\n\t\t        runtime.emit_intermediate(emit_temp, temp);\t\t\t\n\t\t\t}\n\t\t}\n\t\t\n\t\t// Debugging\n\t\truntime.emit_intermediate(key,0);\n\t\t\n    }\n};\n\nstruct reduce_task : public mapreduce::reduce_task<unsigned, double>\n{\n    template<typename Runtime, typename It>\n    void operator()(Runtime &runtime, key_type const &key, It it, It ite) const\n    {\n        value_type results(*it);\n\t\tdouble pagerank_temp = 0.0f;\n        for (It it1=it; it1!=ite; it1++)\n        {\n\t\t\tpagerank_temp += (double)(*it1);\n        }\n\n\t\t// Applying the pagerank update rule\n\t\tdouble pageranks_calc_temp = pagerank_temp*alpha + (1-alpha)/total_webpages + alpha*dangling_pointer/total_webpages;   \n\t\t\n\t\t// Emitting the (Key,Value) pair for the pageranks_calc\n\t\tresults = pageranks_calc_temp;\n\t\truntime.emit(key,results);\n    }\n};\n\ntypedef\nmapreduce::job<page_rank::map_task,\n               page_rank::reduce_task,\n               mapreduce::null_combiner,\n               page_rank::number_source<page_rank::map_task>\n> job;\n\n} // namespace page_rank\n\n\n// Function to check the convergence\nbool converging(vector<double> pageranks, vector<double> pageranks_calc, int total_webpages){\n\tbool isConverged= true;\n\tfor (int i = 0; i < total_webpages; i++){\n\t\tif (abs(pageranks[i] - pageranks_calc[i])>conv){\n\t\t\tisConverged = false;\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn isConverged;\n}\n\nint main(int argc, char const *argv[])\n{\n\t\n\t// File names\n\tstring input_file;\n\tstring output_file;\n\t\t\n\t// Reading the command line inputs\t\t\n\tif (argc == 4){\n\t\tif (!strcmp(argv[2],OUTPUT_ARG)){\n\t\t\tinput_file=argv[1];\n\t\t\toutput_file=argv[3];\n\t\t}\n\t\t\n\t\telse{\n\t\t\tusage();\n\t\t\texit(1);\n\t\t}\n\t}\n\t\n\telse{\n\t\tusage();\n\t\texit(1);\n\t}\n\t\n\tint max_page_id = 0;\n\tint min_page_id = 0;\t\n\t\n\t// Reading inputs from the specified file in the test folder of the standard pagerank repo\n\tifstream fopen;\n\tfopen.open(\"test/\" + input_file);\n\twhile(!fopen.eof()){\n\t\tint a,b;\n\t\tfopen>>a>>b;\n\t\toutgoing_links[a].push_back(b);\n\t\t\n\t\tint max_temp = std::max(a,b);\n\t\tif (max_temp > max_page_id)\n\t\t\tmax_page_id = max_temp;\n\t\t\n\t\tint min_temp = std::min(a,b);\n\t\tif (min_temp < min_page_id)\n\t\t\tmin_page_id = min_temp;\n\t}\n\t\n\t// Total number of web-pages as: max_page_id - min_page_id + 1\n\tfopen.close();\n\ttotal_webpages = max_page_id - min_page_id + 1;\n\n\t// Initializing the pageranks;\n\tdouble pgr = double(1.0f/total_webpages);\n\tfor(int i=0; i<total_webpages; i++){\n\t\tpageranks[i] = pgr;\n\t}\n\n\t// Initializing the Mapreduce specifications\n    mapreduce::specification spec;\n    spec.reduce_tasks = std::max(1U, std::thread::hardware_concurrency());\n\n\twhile(true){\n\t\t\n\t\tcout << pageranks[0] << endl;\n\t\t\n\t\t// Handling dangling pointers\n\t\tdangling_pointer=0.0f;\n\t\tfor(int i=0; i<total_webpages; i++){\t\t\t\n\t\t\tif (outgoing_links[i].size()==0){\n\t\t\t\tdangling_pointer+=pageranks[i];\n\t\t\t}\n\t\t}\t\t\n\t\t\n\t\t// Scheduling the map-reduce for the pagerank calculation\n        page_rank::job::datasource_type number_source;\n        page_rank::job job(number_source, spec);\n        mapreduce::results result; \n        \n\t\t#ifdef _DEBUG\n\t\t\tjob.run<mapreduce::schedule_policy::sequential<page_rank::job> >(result);\n\t\t#else\n\t\t\tjob.run<mapreduce::schedule_policy::cpu_parallel<page_rank::job> >(result);\n\t\t#endif\n\n\t\t// Storing the reults of the calculated pagerank\n        for (auto it=job.begin_results(); it!=job.end_results(); it++){\n            pageranks_calc[it->first] = it->second;\n        }    \n\t\t    \n\t\t// Checking for convergence\n\t\tif(converging(pageranks, pageranks_calc, total_webpages)){\n\t\t\tbreak;\n\t\t}\t\n\t\telse{\n\t\t\tfor(int i=0; i<total_webpages; i++){\n\t\t\t\tpageranks[i] = pageranks_calc[i];\n\t\t\t}\t\t\n\t\t}\n\t}\n\n\t// Writing to the file\n\tofstream fout;\n\tfout.open(\"output/\" + output_file);\n\n\tstring str;\n\tdouble sumVal = 0.0;\n\tfor(int i=0; i<total_webpages; i++){\n\t\tfout<<i<<\" = \"<<pageranks[i]<<endl;\n\t\tsumVal += pageranks[i];\n\t}\t\n\t\n\tfout << \"sum \" << sumVal << endl;\n\tfout.close();\n\n\treturn 0;\n}\n", "meta": {"hexsha": "e5a60aed3769de90fe25d66e8d596a09b2c074d2", "size": 6439, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Pagerank-using-Mapreduce/mr-pr-cpp.cpp", "max_stars_repo_name": "Vedant2311/Parallel-Matrices", "max_stars_repo_head_hexsha": "54f40b4dcf6d237f68b60f5894c4ad0fbf5f9392", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Pagerank-using-Mapreduce/mr-pr-cpp.cpp", "max_issues_repo_name": "Vedant2311/Parallel-Matrices", "max_issues_repo_head_hexsha": "54f40b4dcf6d237f68b60f5894c4ad0fbf5f9392", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Pagerank-using-Mapreduce/mr-pr-cpp.cpp", "max_forks_repo_name": "Vedant2311/Parallel-Matrices", "max_forks_repo_head_hexsha": "54f40b4dcf6d237f68b60f5894c4ad0fbf5f9392", "max_forks_repo_licenses": ["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.3503937008, "max_line_length": 195, "alphanum_fraction": 0.6690479888, "num_tokens": 1782, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217431943271999, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.47011095043395296}}
{"text": "#include <Eigen/Core>\n\n#include <numpy_eigen/boost_python_headers.hpp>\nEigen::Matrix<int, 6, 4> test_int_6_4(const Eigen::Matrix<int, 6, 4> & M)\n{\n\treturn M;\n}\nvoid export_int_6_4()\n{\n\tboost::python::def(\"test_int_6_4\",test_int_6_4);\n}\n\n", "meta": {"hexsha": "4f0f9afdc6f1635f2c68ccd926be9a7dfda42f82", "size": 237, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Schweizer-Messer/numpy_eigen/src/autogen_test_module/test_6_4_int.cpp", "max_stars_repo_name": "PushyamiKaveti/kalibr", "max_stars_repo_head_hexsha": "d8bdfc59ee666ef854012becc93571f96fe5d80c", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": 2690.0, "max_stars_repo_stars_event_min_datetime": "2015-01-07T03:50:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T20:27:01.000Z", "max_issues_repo_path": "Schweizer-Messer/numpy_eigen/src/autogen_test_module/test_6_4_int.cpp", "max_issues_repo_name": "PushyamiKaveti/kalibr", "max_issues_repo_head_hexsha": "d8bdfc59ee666ef854012becc93571f96fe5d80c", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": 481.0, "max_issues_repo_issues_event_min_datetime": "2015-01-27T10:21:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T14:02:41.000Z", "max_forks_repo_path": "Schweizer-Messer/numpy_eigen/src/autogen_test_module/test_6_4_int.cpp", "max_forks_repo_name": "PushyamiKaveti/kalibr", "max_forks_repo_head_hexsha": "d8bdfc59ee666ef854012becc93571f96fe5d80c", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": 1091.0, "max_forks_repo_forks_event_min_datetime": "2015-01-26T21:21:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T01:55:33.000Z", "avg_line_length": 18.2307692308, "max_line_length": 73, "alphanum_fraction": 0.7172995781, "num_tokens": 83, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.470110948461616}}
{"text": "#define BOOST_TEST_MODULE LCMTest\n\n#include \"LCM.hpp\"\n#include <vector>\n#include <cstdint>\n\n#define BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n#include <boost/algorithm/string.hpp>\n\nBOOST_AUTO_TEST_SUITE(LCMSuite)\n\nusing namespace com::github::nimelo;\nusing namespace std;\n\nBOOST_AUTO_TEST_CASE(ShouldCorrectlyReturnLeastCommonMultiple)\n{\n    // Arrange\n    vector<int> numbers = { 1, 7, 9 };\n    int expected_lcm = 1 * 7 * 9;\n    \n    LCM<int> lcm(numbers);\n    \n    // Act\n    auto actual_lcm  = lcm.get();\n\n    // Assert\n    BOOST_CHECK_EQUAL(expected_lcm, actual_lcm);\n}\n\nBOOST_AUTO_TEST_CASE(ShouldCorrectlyReturnLeastCommonMultiple_2)\n{\n    // Arrange\n    vector<int> numbers = { 48, 180 };\n    int expected_lcm = 720;\n    \n    LCM<int> lcm(numbers);\n    \n    // Act\n    auto actual_lcm  = lcm.get();\n\n    // Assert\n    BOOST_CHECK_EQUAL(expected_lcm, actual_lcm);\n}\n\nBOOST_AUTO_TEST_CASE(ShouldCorrectlyReturnLeastCommonMultiple_3)\n{\n    // Arrange\n    vector<int> numbers = { 21, 6 };\n    int expected_lcm = 42;\n    \n    LCM<int> lcm(numbers);\n    \n    // Act\n    auto actual_lcm  = lcm.get();\n\n    // Assert\n    BOOST_CHECK_EQUAL(expected_lcm, actual_lcm);\n}\n\nBOOST_AUTO_TEST_CASE(ShouldCorrectlyReturnLeastCommonMultiple_4)\n{\n    // Arrange\n    vector<int> numbers = { 8, 9, 21 };\n    int expected_lcm = 504;\n    \n    LCM<int> lcm(numbers);\n    \n    // Act\n    auto actual_lcm  = lcm.get();\n\n    // Assert\n    BOOST_CHECK_EQUAL(expected_lcm, actual_lcm);\n}\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "7785a490f21e1571474ea8d9696dc8e89b7c3e2c", "size": 1508, "ext": "cc", "lang": "C++", "max_stars_repo_path": "algorithms/implementation/between-two-sets/test/LCMTest.cc", "max_stars_repo_name": "Nimelo/hacker-rank", "max_stars_repo_head_hexsha": "c1b22e31668222817a2c9051f75e5912cb912130", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "algorithms/implementation/between-two-sets/test/LCMTest.cc", "max_issues_repo_name": "Nimelo/hacker-rank", "max_issues_repo_head_hexsha": "c1b22e31668222817a2c9051f75e5912cb912130", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "algorithms/implementation/between-two-sets/test/LCMTest.cc", "max_forks_repo_name": "Nimelo/hacker-rank", "max_forks_repo_head_hexsha": "c1b22e31668222817a2c9051f75e5912cb912130", "max_forks_repo_licenses": ["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.8421052632, "max_line_length": 64, "alphanum_fraction": 0.6717506631, "num_tokens": 414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548646660542, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.47011094846161594}}
{"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 * Created on January 12, 2021, x:xx AM\n */\n\n#include <gtest/gtest.h>\n\n#include <Eigen/Eigen>\n#include <boost/math/constants/constants.hpp>\n\n#include \"MaterialLib/MPL/Medium.h\"\n#include \"MaterialLib/MPL/Properties/CreateGasPressureDependentPermeability.h\"\n#include \"MaterialLib/MPL/Properties/GasPressureDependentPermeability.h\"\n#include \"MaterialLib/MPL/Utils/FormEigenTensor.h\"\n#include \"ParameterLib/ConstantParameter.h\"\n#include \"TestMPL.h\"\n#include \"Tests/TestTools.h\"\n\nTEST(MaterialPropertyLib, GasPressureDependentPermeability)\n{\n    ParameterLib::ConstantParameter<double> const k0(\"k0\", 1.e-20);\n    double const a1 = 0.125;\n    double const a2 = 152.0;\n    double const pressure_threshold = 3.2e6;\n    double const min_permeability = 1.e-22;\n    double const max_permeability = 1.e-10;\n\n    auto const k_model = MPL::GasPressureDependentPermeability<3>(\n        \"k_gas\", k0, a1, a2, pressure_threshold, min_permeability,\n        max_permeability, nullptr);\n\n    ParameterLib::SpatialPosition const pos;\n    double const t = std::numeric_limits<double>::quiet_NaN();\n    double const dt = std::numeric_limits<double>::quiet_NaN();\n    MPL::VariableArray vars;\n\n    /// For gas pressure smaller than threshold value.\n    {\n        double const p_gas = 2.5e6;\n\n        vars[static_cast<int>(MPL::Variable::phase_pressure)] = p_gas;\n        auto const k = MPL::formEigenTensor<3>(k_model.value(vars, pos, t, dt));\n\n        double const k_expected = 1.312500000000000000e-20;\n\n        ASSERT_LE(std::fabs(k_expected - k(0, 0)) / k_expected, 1e-10)\n            << \"for expected permeability with gas pressure below threshold\"\n            << k_expected\n            << \" and for computed permeability with gas pressure below \"\n               \"threshold \"\n            << k(0, 0);\n    }\n    /// For gas pressure bigger than threshold value.\n    {\n        double const p_gas = 4.5e6;\n\n        vars[static_cast<int>(MPL::Variable::phase_pressure)] = p_gas;\n        auto const k = MPL::formEigenTensor<3>(k_model.value(vars, pos, t, dt));\n\n        double const k_expected = 1.990000000000000000000e-18;\n\n        ASSERT_LE(std::fabs(k_expected - k(0, 0)) / k_expected, 1e-10)\n            << \"for expected permeability with gas pressure above threshold \"\n            << k_expected\n            << \" and for computed permeability with gas pressure above \"\n               \"threshold \"\n            << k(0, 0);\n    }\n}\n", "meta": {"hexsha": "0e283cef278549372827be1747d7015632762d72", "size": 2683, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tests/MaterialLib/TestGasPressureDependentPermeability.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": "Tests/MaterialLib/TestGasPressureDependentPermeability.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": "Tests/MaterialLib/TestGasPressureDependentPermeability.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": 35.3026315789, "max_line_length": 80, "alphanum_fraction": 0.660827432, "num_tokens": 694, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.4701109435769588}}
{"text": "#include <boost/random/exponential_distribution.hpp>\n", "meta": {"hexsha": "5b1e7a1ee721cc764f3123ec151806e77ebf20f9", "size": 53, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_random_exponential_distribution.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_random_exponential_distribution.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_random_exponential_distribution.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 26.5, "max_line_length": 52, "alphanum_fraction": 0.8490566038, "num_tokens": 9, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.47004741328817834}}
{"text": "// Boost.Geometry\n\n// Copyright (c) 2021, Oracle and/or its affiliates.\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\n\n// Licensed under the Boost Software License version 1.0.\n// http://www.boost.org/users/license.html\n\n#include <boost/test/included/test_exec_monitor.hpp>\n#include <boost/test/impl/execution_monitor.ipp>\n\n#include <algorithm>\n#include <vector>\n#include <map>\n\n#include <boost/geometry/index/detail/minmax_heap.hpp>\n#include <boost/geometry/index/detail/maxmin_heap.hpp>\n\nusing namespace boost::geometry::index::detail;\n\nstruct noncopyable\n{\n    noncopyable(int i_) : i(i_) {}\n    noncopyable(noncopyable const&) = delete;\n    noncopyable& operator=(noncopyable const&) = delete;\n    noncopyable(noncopyable&&) = default;\n    noncopyable& operator=(noncopyable&&) = default;\n    bool operator<(noncopyable const& other) const { return i < other.i; }\n    operator int() const { return i; }\n    int i;\n};\n\ntemplate <typename T>\nstruct minmax_default\n{\n    minmax_default() = default;\n    minmax_default(std::vector<int> const& vec)\n        : heap(vec.begin(), vec.end())\n    {\n        make_minmax_heap(heap.begin(), heap.end());\n    }\n    T const& top() const\n    {\n        return heap[0];\n    }\n    T const& bottom() const\n    {\n        return bottom_minmax_heap(heap.begin(), heap.end());\n    }\n    void push(int i)\n    {\n        heap.push_back(T(i));\n        push_minmax_heap(heap.begin(), heap.end());\n    }\n    void pop_top()\n    {\n        pop_top_minmax_heap(heap.begin(), heap.end());\n        heap.pop_back();\n    }\n    void pop_bottom()\n    {\n        pop_bottom_minmax_heap(heap.begin(), heap.end());\n        heap.pop_back();\n    }\n    bool is_heap() const\n    {\n        return is_minmax_heap(heap.begin(), heap.end());\n    }\n    bool empty() const\n    {\n        return heap.empty();\n    }\n    std::vector<T> heap;\n};\n\ntemplate <typename T>\nstruct minmax_less\n{\n    minmax_less() = default;\n    minmax_less(std::vector<int> const& vec)\n        : heap(vec.begin(), vec.end())\n    {\n        make_minmax_heap(heap.begin(), heap.end(), std::less<>());\n    }\n    T const& top() const\n    {\n        return heap[0];\n    }\n    T const& bottom() const\n    {\n        return bottom_minmax_heap(heap.begin(), heap.end(), std::less<>());\n    }\n    void push(int i)\n    {\n        heap.push_back(T(i));\n        push_minmax_heap(heap.begin(), heap.end(), std::less<>());\n    }\n    void pop_top()\n    {\n        pop_top_minmax_heap(heap.begin(), heap.end(), std::less<>());\n        heap.pop_back();\n    }\n    void pop_bottom()\n    {\n        pop_bottom_minmax_heap(heap.begin(), heap.end(), std::less<>());\n        heap.pop_back();\n    }\n    bool is_heap() const\n    {\n        return is_minmax_heap(heap.begin(), heap.end(), std::less<>());\n    }\n    bool empty() const\n    {\n        return heap.empty();\n    }\n    std::vector<T> heap;\n};\n\ntemplate <typename T>\nstruct maxmin_greater\n{\n    maxmin_greater() = default;\n    maxmin_greater(std::vector<int> const& vec)\n        : heap(vec.begin(), vec.end())\n    {\n        make_maxmin_heap(heap.begin(), heap.end(), std::greater<>());\n    }\n    T const& top() const\n    {\n        return heap[0];\n    }\n    T const& bottom() const\n    {\n        return bottom_maxmin_heap(heap.begin(), heap.end(), std::greater<>());\n    }\n    void push(int i)\n    {\n        heap.push_back(T(i));\n        push_maxmin_heap(heap.begin(), heap.end(), std::greater<>());\n    }\n    void pop_top()\n    {\n        pop_top_maxmin_heap(heap.begin(), heap.end(), std::greater<>());\n        heap.pop_back();\n    }\n    void pop_bottom()\n    {\n        pop_bottom_maxmin_heap(heap.begin(), heap.end(), std::greater<>());\n        heap.pop_back();\n    }\n    bool is_heap() const\n    {\n        return is_maxmin_heap(heap.begin(), heap.end(), std::greater<>());\n    }\n    bool empty() const\n    {\n        return heap.empty();\n    }\n    std::vector<T> heap;\n};\n\ntemplate <typename T>\nstruct maxmin_default_switch\n{\n    maxmin_default_switch() = default;\n    maxmin_default_switch(std::vector<int> const& vec)\n        : heap(vec.begin(), vec.end())\n    {\n        make_maxmin_heap(heap.begin(), heap.end());\n    }\n    T const& bottom() const\n    {\n        return heap[0];\n    }\n    T const& top() const\n    {\n        return bottom_maxmin_heap(heap.begin(), heap.end());\n    }\n    void push(int i)\n    {\n        heap.push_back(T(i));\n        push_maxmin_heap(heap.begin(), heap.end());\n    }\n    void pop_top()\n    {\n        pop_bottom_maxmin_heap(heap.begin(), heap.end());\n        heap.pop_back();\n    }\n    void pop_bottom()\n    {\n        pop_top_maxmin_heap(heap.begin(), heap.end());\n        heap.pop_back();\n    }\n    bool is_heap() const\n    {\n        return is_maxmin_heap(heap.begin(), heap.end());\n    }\n    bool empty() const\n    {\n        return heap.empty();\n    }\n    std::vector<T> heap;\n};\n\ntemplate <typename Heap>\nvoid test()\n{\n    std::vector<int> vec;\n    int const n = 20;\n    for (int i = 0; i < n; ++i)\n    {\n        vec.push_back(rand() % n);\n    }\n\n    {\n        std::map<int, int> map;\n        Heap heap;\n        for (int i : vec)\n        {\n            heap.push(i);\n            BOOST_CHECK(heap.is_heap());\n            \n            map[i]++;\n            BOOST_CHECK_EQUAL(heap.top(), map.begin()->first);\n            BOOST_CHECK_EQUAL(heap.bottom(), (--map.end())->first);\n        }\n\n        while (! heap.empty())\n        {\n            int i = heap.top();\n            BOOST_CHECK_EQUAL(i, map.begin()->first);\n            BOOST_CHECK_EQUAL(heap.bottom(), (--map.end())->first);\n            BOOST_CHECK(map[i] > 0);\n            map[i]--;\n            if (map[i] <= 0)\n                map.erase(i);\n\n            heap.pop_top();\n            BOOST_CHECK(heap.is_heap());\n        }\n\n        BOOST_CHECK(map.empty());\n    }\n\n    {\n        Heap heap(vec);\n        BOOST_CHECK(heap.is_heap());\n        \n        std::map<int, int> map;\n        for (int i : vec)\n            map[i]++;\n        BOOST_CHECK_EQUAL(heap.top(), map.begin()->first);\n        BOOST_CHECK_EQUAL(heap.bottom(), (--map.end())->first);\n\n        while (! heap.empty())\n        {\n            int i = heap.bottom();\n            BOOST_CHECK_EQUAL(heap.top(), map.begin()->first);\n            BOOST_CHECK_EQUAL(i, (--map.end())->first);\n            BOOST_CHECK(map[i] > 0);\n            map[i]--;\n            if (map[i] <= 0)\n                map.erase(i);\n\n            heap.pop_bottom();\n            BOOST_CHECK(heap.is_heap());\n        }\n\n        BOOST_CHECK(map.empty());\n    }\n}\n\nint test_main(int, char* [])\n{\n    test<minmax_default<int>>();\n    test<minmax_default<noncopyable>>();\n    test<minmax_less<int>>();\n    test<maxmin_greater<int>>();\n    test<maxmin_default_switch<int>>();\n\n    return 0;\n}\n", "meta": {"hexsha": "4dd3a7d823645d517413c09628e12469b2711919", "size": 6725, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/boost_1.78.0/libs/geometry/index/test/minmax_heap.cpp", "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/libs/geometry/index/test/minmax_heap.cpp", "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/libs/geometry/index/test/minmax_heap.cpp", "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": 23.7632508834, "max_line_length": 78, "alphanum_fraction": 0.5463197026, "num_tokens": 1625, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4700474074916261}}
{"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_HYPERBOLIC_FUNCTIONS_SCALAR_SINHC_HPP_INCLUDED\n#define NT2_HYPERBOLIC_FUNCTIONS_SCALAR_SINHC_HPP_INCLUDED\n#include <nt2/hyperbolic/functions/sinhc.hpp>\n#include <nt2/hyperbolic/functions/details/sinhc_kernel.hpp>\n#include <nt2/include/constants/half.hpp>\n#include <nt2/include/constants/log_2.hpp>\n#include <nt2/include/constants/maxlog.hpp>\n#include <nt2/include/constants/one.hpp>\n#include <nt2/include/functions/scalar/abs.hpp>\n#include <nt2/include/functions/scalar/average.hpp>\n#include <nt2/include/functions/scalar/exp.hpp>\n#include <nt2/include/functions/scalar/if_else.hpp>\n#include <nt2/include/functions/scalar/rec.hpp>\n#include <nt2/include/functions/scalar/sqr.hpp>\n#include <boost/simd/sdk/config.hpp>\n\n#ifndef BOOST_SIMD_NO_INFINITIES\n#include <nt2/include/constants/inf.hpp>\n#endif\n\nnamespace nt2 { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT  ( sinhc_, tag::cpu_\n                            , (A0)\n                            , (scalar_< floating_<A0> >)\n                            )\n  {\n\n    typedef A0 result_type;\n\n    NT2_FUNCTOR_CALL(1)\n    {\n      //////////////////////////////////////////////////////////////////////////////\n      // if x = abs(a0) is less than 1 sinhc is computed using a polynomial(float)\n      // respectively rational(double) approx inspired from cephes sinh approx.\n      // else according x < Threshold e =  exp(x) or exp(x/2) is respectively\n      // computed\n      // * in the first case sinh is ((e-rec(e))/2)/x\n      // * in the second     sinh is (e/2/x)*e (avoiding undue overflow)\n      // Threshold is Maxlog - Log_2 defined in Maxshlog\n      //////////////////////////////////////////////////////////////////////////////\n      result_type x = nt2::abs(a0);\n      #ifndef BOOST_SIMD_NO_INFINITIES\n      if (x == Inf<A0>()) return x;\n      #endif\n      if( x < One<A0>())\n      {\n        return details::sinhc_kernel<A0>::compute(sqr(x));\n      }\n      else\n      {\n        bool test1 = (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)/x;\n        return if_else(test1, tmp1*tmp, average(tmp, -rec(tmp))/x);\n      }\n     }\n  };\n\n} }\n#endif\n", "meta": {"hexsha": "e21bd9f263d798314e2cc97e70a8c645262f839d", "size": 2714, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/hyperbolic/include/nt2/hyperbolic/functions/scalar/sinhc.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/hyperbolic/include/nt2/hyperbolic/functions/scalar/sinhc.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/hyperbolic/include/nt2/hyperbolic/functions/scalar/sinhc.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.2253521127, "max_line_length": 84, "alphanum_fraction": 0.5593220339, "num_tokens": 662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.47004740749162605}}
{"text": "#pragma once\n\n#include <opencv2/core/core.hpp>\n#include <Eigen/Core>\n\n#include \"../../Colour/colour.hh\"\n#include \"../../DistributionTracker/distributiontracker.hh\"\n#include \"../../geometry/Line.hh\"\n#include \"../../geometry/LineSegment/LineSegment2/LineSegment2i/linesegment2i.hh\"\n#include \"../linefinder.hh\"\n\nnamespace bold\n{\n  class RandomPairLineFinder : public LineFinder\n  {\n    // TODO initialise controls\n\n  public:\n    struct LineHypothesis\n    {\n      LineHypothesis(Line const& line, Eigen::Vector2i const& dot1, Eigen::Vector2i const& dot2)\n      : d_lengthDistribution(),\n        d_theta(line.theta()),\n        d_radius(line.radius())\n      {\n        auto diff = dot2 - dot1;\n\n        d_lengthDistribution.add(length(diff));\n\n        // Determines whether we consider x or y for min/max\n        d_isHorizontal = abs(diff.x()) > abs(diff.y());\n\n        // Set min/max values\n        int elementIndex = d_isHorizontal ? 0 : 1;\n        if (dot1[elementIndex] < dot2[elementIndex])\n        {\n          d_min = dot1;\n          d_max = dot2;\n        }\n        else\n        {\n          d_min = dot2;\n          d_max = dot1;\n        }\n\n        d_lines.push_back(line);\n      }\n\n      bool tryMerge(Line const& line, Eigen::Vector2i const& dot1, Eigen::Vector2i const& dot2)\n      {\n        double dt = line.theta() - d_theta;\n        double dr = line.radius() - d_radius;\n\n        const double dtThreshold = Math::degToRad(10);\n        const double drThreshold = 15;\n\n        if (fabs(dt) < dtThreshold && fabs(dr) < drThreshold)\n        {\n          d_lines.push_back(line);\n\n          // Update min/max values if breached\n          int elementIndex = d_isHorizontal ? 0 : 1;\n          if (dot1[elementIndex] < dot2[elementIndex])\n          {\n            if (d_min[elementIndex] < dot1[elementIndex])\n              d_min = dot1;\n            if (d_max[elementIndex] > dot2[elementIndex])\n              d_max = dot2;\n          }\n          else\n          {\n            if (d_min[elementIndex] < dot2[elementIndex])\n              d_min = dot2;\n            if (d_max[elementIndex] > dot1[elementIndex])\n              d_max = dot1;\n          }\n\n          d_lengthDistribution.add(length(dot2 - dot1));\n          return true;\n        }\n\n        return false;\n      }\n\n      Line toLine() const\n      {\n        double t = d_theta;\n        double r = d_radius;\n\n        while (t < 0)\n        {\n          t += M_PI;\n          r = -r;\n        }\n\n        while (t > M_PI)\n        {\n          t -= M_PI;\n          r = -r;\n        }\n\n        return Line(r, t, d_lines.size());\n      }\n\n      int count() const\n      {\n        return d_lines.size();\n      }\n\n      Eigen::Vector2i min() const { return d_min; }\n      Eigen::Vector2i max() const { return d_max; }\n      DistributionTracker lengthDistribution() const { return d_lengthDistribution; }\n\n      friend std::ostream& operator<<(std::ostream& stream, LineHypothesis const& hypothesis)\n      {\n        auto line = hypothesis.toLine();\n        return stream\n          << \"theta=\" << line.theta() << \" (\" << (line.thetaDegrees()) << \" degs)\"\n          << \" radius=\" << line.radius() << \" votes=\" << hypothesis.count()\n          << \" length=\" << (hypothesis.max().cast<double>() - hypothesis.min().cast<double>()).norm()\n          << \" lengthAvg=\" << hypothesis.lengthDistribution().average()\n          << \" lengthStdDev=\" << hypothesis.lengthDistribution().stdDev()\n          << \" lengthAvg/lengthStdDev=\" << hypothesis.lengthDistribution().average()/hypothesis.lengthDistribution().stdDev();\n      }\n\n    private:\n      static double length(Eigen::Vector2i v)\n      {\n        return sqrt(v.x()*v.x() + v.y()*v.y());\n      }\n\n      DistributionTracker d_lengthDistribution;\n      Eigen::Vector2i d_min;\n      Eigen::Vector2i d_max;\n      double d_theta;\n      double d_radius;\n      std::vector<Line> d_lines;\n      bool d_isHorizontal;\n    };\n\n    RandomPairLineFinder(int imageWidth, int imageHeight)\n    : d_minDotManhattanDistance(3)\n    {}\n\n    std::vector<LineSegment2i> findLineSegments(std::vector<Eigen::Vector2i>& lineDots) override;\n\n    void setMinDotManhattanDistance(unsigned minDotManhattanDistance) { d_minDotManhattanDistance = minDotManhattanDistance; }\n\n  private:\n    unsigned d_minDotManhattanDistance;\n  };\n}\n", "meta": {"hexsha": "ce537c85ae8923228cfed990e65989952c77fda2", "size": 4275, "ext": "hh", "lang": "C++", "max_stars_repo_path": "LineFinder/RandomPairLineFinder/randompairlinefinder.hh", "max_stars_repo_name": "drewnoakes/bold-humanoid", "max_stars_repo_head_hexsha": "6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "LineFinder/RandomPairLineFinder/randompairlinefinder.hh", "max_issues_repo_name": "drewnoakes/bold-humanoid", "max_issues_repo_head_hexsha": "6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LineFinder/RandomPairLineFinder/randompairlinefinder.hh", "max_forks_repo_name": "drewnoakes/bold-humanoid", "max_forks_repo_head_hexsha": "6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335", "max_forks_repo_licenses": ["Apache-2.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.9411764706, "max_line_length": 126, "alphanum_fraction": 0.5714619883, "num_tokens": 1029, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.47004740749162605}}
{"text": "/**********************\n\u89c4\u5b9a type:\ntype 0: left bottom\ntype 1: right bottom\ntype 2: left top\ntype 3: right top\n**********************/\n\n#include \"ros/ros.h\"\n#include <sensor_msgs/LaserScan.h>\n#include <sensor_msgs/PointCloud.h>\n\n#include <vector>\n#include <string.h>\n#include <math.h>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include <Eigen/SVD>\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 </usr/local/include/g2o/solvers/csparse/linear_solver_csparse.h>\n#include <g2o/solvers/dense/linear_solver_dense.h>\n#include <g2o/types/sba/types_six_dof_expmap.h>\n#include <cmath>\n#include <chrono>\n\n#define start_region_boundary_distance 2.1\n\nstd::vector<int> laser_blacklist;\n\ndouble angle_max;\ndouble angle_min;\ndouble angle_increment;\n\nint corner_type = 0;\n//ranges_boundary\u548cangles_boundary\u662f\u6309\u9006\u65f6\u9488\u987a\u5e8f\u6392\u5217\u7684\u8fb9\u7f18\u70b9\u4fe1\u606f\nstd::vector<double> ranges_boundary; \nstd::vector<double> angles_boundary;\n\nint corner = 0;\n\n//g2o\u56fe\u4f18\u5316\u9876\u70b9\uff1a\u4f4d\u59ff\nclass BoundaryPoseVertex: public g2o::BaseVertex<3, Eigen::Vector3d>\n{\npublic:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    // \u91cd\u7f6e\n    virtual void setToOriginImpl() \n    {\n        _estimate << 0,0,0;\n    }\n     // \u66f4\u65b0\n    virtual void oplusImpl( const double* update )\n    {\n        _estimate += Eigen::Vector3d(update);\n    }\n    // \u5b58\u76d8\u548c\u8bfb\u76d8\uff1a\u7559\u7a7a\n    virtual bool read( std::istream& in ) {}\n    virtual bool write( std::ostream& out ) const {}\n};\n// \u8bef\u5dee\u6a21\u578b \u6a21\u677f\u53c2\u6570\uff1a\u89c2\u6d4b\u503c\u7ef4\u5ea6\uff0c\u7c7b\u578b\uff0c\u8fde\u63a5\u9876\u70b9\u7c7b\u578b\n//_measurement\u662f\u89d2\u5ea6\u548c\u8ddd\u79bb\u7684\u4e8c\u7ef4\u5411\u91cf\n//\u573a\u5730\u4e0b\u8fb9\u7684\u70b9\u6240\u6784\u6210\u7684\u56fe\u4f18\u5316\u8fb9\nclass BoundaryEdge_Bottom: public g2o::BaseUnaryEdge<2, Eigen::Vector2d, BoundaryPoseVertex>\n{\npublic:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    BoundaryEdge_Bottom(double point_theta, double point_range): \n    BaseUnaryEdge(), _point_theta(point_theta), _point_range(point_range) {}\n    // \u8ba1\u7b97\u66f2\u7ebf\u6a21\u578b\u8bef\u5dee\n    void computeError()\n    {\n        const BoundaryPoseVertex* pose = static_cast<const BoundaryPoseVertex*> (_vertices[0]);\n        const Eigen::Vector3d pose_estimation = pose->estimate();\n        _error(0,0) = pose_estimation(1) + _measurement(1) * sin( _measurement(0) + pose_estimation(2) ) ;\n    }\n    virtual void linearizeOplus()\n    {\n        const BoundaryPoseVertex* pose = static_cast<const BoundaryPoseVertex*> (_vertices[0]);\n        const Eigen::Vector3d pose_estimation = pose->estimate();\n\n        _jacobianOplusXi(0,0) = 0;\n        _jacobianOplusXi(0,1) = 1;\n        _jacobianOplusXi(0,2) = _point_range * cos(_point_theta + pose_estimation(2));\n    }\n    virtual bool read( std::istream& in ) {}\n    virtual bool write( std::ostream& out ) const {}  \n    \npublic:\n\t  double _point_range;\n\t\tdouble _point_theta;\n\t\t//measurement(0)\u5176\u5b9e\u548cpoint_theta\u662f\u4e00\u6837\u7684\uff0cmeasurement(1)\u5176\u5b9e\u548cpoint_range\u662f\u4e00\u6837\u7684\n};\n//\u573a\u5730\u5de6\u8fb9\u7684\u70b9\u6240\u6784\u6210\u7684\u56fe\u4f18\u5316\u8fb9\nclass BoundaryEdge_Left: public g2o::BaseUnaryEdge<2, Eigen::Vector2d, BoundaryPoseVertex>\n{\npublic:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    BoundaryEdge_Left(double point_theta, double point_range): \n    BaseUnaryEdge(), _point_theta(point_theta), _point_range(point_range) {}\n    // \u8ba1\u7b97\u66f2\u7ebf\u6a21\u578b\u8bef\u5dee\n    void computeError()\n    {\n        const BoundaryPoseVertex* pose = static_cast<const BoundaryPoseVertex*> (_vertices[0]);\n        const Eigen::Vector3d pose_estimation = pose->estimate();\n        _error(0,0) = pose_estimation(0) + _measurement(1) * cos( _measurement(0) + pose_estimation(2) ) ;\n    }\n    virtual void linearizeOplus()\n    {\n        const BoundaryPoseVertex* pose = static_cast<const BoundaryPoseVertex*> (_vertices[0]);\n        const Eigen::Vector3d pose_estimation = pose->estimate();\n\n        _jacobianOplusXi(0,0) = 1;\n        _jacobianOplusXi(0,1) = 0;\n        _jacobianOplusXi(0,2) = -_point_range * sin(_point_theta + pose_estimation(2));\n    }\n    virtual bool read( std::istream& in ) {}\n    virtual bool write( std::ostream& out ) const {}  \n    \npublic:\n\t  double _point_range;\n\t\tdouble _point_theta;\n\t\t//measurement(0)\u5176\u5b9e\u548cpoint_theta\u662f\u4e00\u6837\u7684\uff0cmeasurement(1)\u5176\u5b9e\u548cpoint_range\u662f\u4e00\u6837\u7684\n};\nclass BoundaryEdge_Top: public g2o::BaseUnaryEdge<2, Eigen::Vector2d, BoundaryPoseVertex>\n{\npublic:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    BoundaryEdge_Top(double point_theta, double point_range): \n    BaseUnaryEdge(), _point_theta(point_theta), _point_range(point_range) {}\n    // \u8ba1\u7b97\u66f2\u7ebf\u6a21\u578b\u8bef\u5dee\n    void computeError()\n    {\n        const BoundaryPoseVertex* pose = static_cast<const BoundaryPoseVertex*> (_vertices[0]);\n        const Eigen::Vector3d pose_estimation = pose->estimate();\n        _error(0,0) = 5.0 - pose_estimation(1) - _measurement(1) * sin( _measurement(0) + pose_estimation(2) ) ;\n    }\n    virtual void linearizeOplus()\n    {\n        const BoundaryPoseVertex* pose = static_cast<const BoundaryPoseVertex*> (_vertices[0]);\n        const Eigen::Vector3d pose_estimation = pose->estimate();\n\n        _jacobianOplusXi(0,0) = 0;\n        _jacobianOplusXi(0,1) = -1;\n        _jacobianOplusXi(0,2) = -_point_range * cos(_point_theta + pose_estimation(2));\n    }\n    virtual bool read( std::istream& in ) {}\n    virtual bool write( std::ostream& out ) const {}  \n    \npublic:\n\t  double _point_range;\n\t\tdouble _point_theta;\n\t\t//measurement(0)\u5176\u5b9e\u548cpoint_theta\u662f\u4e00\u6837\u7684\uff0cmeasurement(1)\u5176\u5b9e\u548cpoint_range\u662f\u4e00\u6837\u7684\n};\nclass BoundaryEdge_Right: public g2o::BaseUnaryEdge<2, Eigen::Vector2d, BoundaryPoseVertex>\n{\npublic:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    BoundaryEdge_Right(double point_theta, double point_range): \n    BaseUnaryEdge(), _point_theta(point_theta), _point_range(point_range) {}\n    // \u8ba1\u7b97\u66f2\u7ebf\u6a21\u578b\u8bef\u5dee\n    void computeError()\n    {\n        const BoundaryPoseVertex* pose = static_cast<const BoundaryPoseVertex*> (_vertices[0]);\n        const Eigen::Vector3d pose_estimation = pose->estimate();\n        _error(0,0) = 8.0 - pose_estimation(0) - _measurement(1) * cos( _measurement(0) + pose_estimation(2) ) ;\n    }\n    virtual void linearizeOplus()\n    {\n        const BoundaryPoseVertex* pose = static_cast<const BoundaryPoseVertex*> (_vertices[0]);\n        const Eigen::Vector3d pose_estimation = pose->estimate();\n\n        _jacobianOplusXi(0,0) = 0;\n        _jacobianOplusXi(0,1) = -1;\n        _jacobianOplusXi(0,2) = _point_range * sin(_point_theta + pose_estimation(2));\n    }\n    virtual bool read( std::istream& in ) {}\n    virtual bool write( std::ostream& out ) const {}  \n    \npublic:\n\t  double _point_range;\n\t\tdouble _point_theta;\n\t\t//measurement(0)\u5176\u5b9e\u548cpoint_theta\u662f\u4e00\u6837\u7684\uff0cmeasurement(1)\u5176\u5b9e\u548cpoint_range\u662f\u4e00\u6837\u7684\n};\n\n//\u8ba1\u7b97\u63d0\u53d6\u51fa\u6765\u7684\u8fb9\u754c\u70b9\u7684\u66f2\u7387\u7684\u5e73\u65b9\u768425\u500d\uff0c\u7531\u4e8e\u662f\u4e3a\u4e86\u6bd4\u8f83\u5927\u5c0f\uff0c\u4e0d\u5728\u5f00\u65b9\u4ee5\u53ca\u4e58\u4ee5\u500d\u6570\uff0c\u6ce8\u610f\u4e0d\u80fd\u63d0\u53d6\u6700\u9760\u4e24\u8fb9\u7684\u56db\u4e2a\u70b9\uff0c\u5426\u5219\u4f1a\u51fa\u73b0\u9519\u8bef\ndouble curve_smoothness_square(int number) {\n\tdouble delta_x = 0, delta_y = 0;\n\t\n\tfor (int i = -9 ; i < 10; i++) {\n\t\t\tif (i == 0)\n\t\t\t\tcontinue;\n\t\t\tdouble delta_angle = angles_boundary[number + i] - angles_boundary[number];\n\t\t\tdelta_x += ranges_boundary[number] - ranges_boundary[number + i] * cos(delta_angle);\n\t\t\tdelta_y += ranges_boundary[number + i] * sin(delta_angle);\n\t}\n\tdouble smoothness_square = (delta_x * delta_x + delta_y * delta_y) / (ranges_boundary[number] * ranges_boundary[number]);\n\treturn smoothness_square;\n}\n//\u5c06\u89d2\u5ea6\u9650\u5236\u5728-\u03c0\u5230\u03c0\u4e4b\u95f4\nvoid angle_standard(double& angle) {\n\twhile (angle > M_PI)\n\t\tangle -= 2 * M_PI;\n\twhile (angle < - M_PI)\n\t\tangle += 2 * M_PI;\n}\n\n//\u63d0\u53d6\u8fb9\u7f18\u70b9\u4fe1\u606f\u5230ranges_boundary\u548cangles_boundary\nvoid extract_boundary_information(const std::vector<double> &ranges_raw, const std::vector<int> &increment_raw) {\n\tint available_number = ranges_raw.size();\n\tstd::vector<bool> distance(available_number, false);\n\t\n\t//\u627e\u5230\u7b2c\u4e00\u4e2a\u4e0d\u7b26\u5408\u8ddd\u79bb\u8981\u6c42\u7684\u70b9\n\tint first_negative = -1;\n\tfor (int i = 0; i < available_number; i++) {\n\t\tif (ranges_raw[i] < start_region_boundary_distance)\n\t\t\tdistance[i] = true;\n\t\telse if (first_negative == -1)\n\t\t\tfirst_negative = i;\n\t}\n\t\n\tint continuous_max_last_location = 0;\n\tint continuous_max_number = 0;\n\tint continuous_max_first_location = 0;\n\tint continuous_first_location_temp = 0;\n\tint continuous_number_now = 0;\n\t//\u627e\u5230\u6ee1\u8db3\u8ddd\u79bb\u8981\u6c42\u7684\u6700\u5927\u8fde\u7eed\u70b9\u96c6,\u4ee5\u5224\u65ad\u4e24\u4e2a\u76f4\u89d2\u8fb9\u4f4d\u7f6e,\u4ece\u7b2c\u4e00\u4e2a\u4e0d\u6ee1\u8db3\u8ddd\u79bb\u8981\u6c42\u7684\u70b9\u5f00\u59cb\uff0c\u5faa\u73af\u4e00\u5708\uff0c\u9632\u6b62\u91cd\u590d\u9057\u6f0f\uff0c\u4ee5\u53cavector\u8d77\u59cb\u7ec8\u6b62\u5904\u8fde\u7eed\u70b9\u96c6\u5224\u65ad\u9519\u8bef\u7684\u60c5\u51b5\n\tfor (int i = first_negative + 1; i < available_number; i++) {\n\t\tif (distance[i]) {\n\t\t\t//\u5982\u679c\u4e0a\u4e00\u4e2a\u70b9\u8fdc\uff0c\u8fd9\u4e00\u4e2a\u70b9\u8fd1\uff0c\u5219\u53d6\u5f53\u524d\u70b9\u4f5c\u4e3a\u5f53\u524d\u8fde\u7eed\u70b9\u96c6\u8d77\u59cb\u8fb9\u754c\uff0c\u7531\u4e8e\u662f\u4ecefirst_negative+1\u5f00\u59cb\uff0c\u5230available\u7ed3\u675f\u7684\uff0c\u6240\u4ee5\u4e0d\u4f1a\u5224\u65ad\u521d\u59cb\u96c6\u5916\u7684\u4f4d\u7f6e\n\t\t\tif (!distance[i - 1])\n\t\t\t\tcontinuous_first_location_temp = i;\n\t\t\t\n\t\t\tcontinuous_number_now++;\n\t\t\tif (continuous_number_now > continuous_max_number) {\n\t\t\t\tcontinuous_max_number = continuous_number_now;\n\t\t\t\tcontinuous_max_last_location = i;\n\t\t\t\tcontinuous_max_first_location = continuous_first_location_temp;\n\t\t\t}\n\t\t} else \n\t\t\tcontinuous_number_now = 0;\n\t}\n\tif (distance[0]) {\n\t\tif (!distance[available_number - 1]) \n\t\t\tcontinuous_first_location_temp = 0;\n\t\t\n\t\tcontinuous_number_now++;\n\t\tif (continuous_number_now > continuous_max_number) {\n\t\t\tcontinuous_max_number = continuous_number_now;\n\t\t\tcontinuous_max_last_location = 0;\n\t\t\tcontinuous_max_first_location = continuous_first_location_temp;\n\t\t}\n\t} else \n\t\tcontinuous_number_now = 0;\n\tfor (int i = 1; i < first_negative + 1; i++) {\n\t\tif (distance[i]) {\n\t\t\t//\u5982\u679c\u4e0a\u4e00\u4e2a\u70b9\u8fdc\uff0c\u8fd9\u4e00\u4e2a\u70b9\u8fd1\uff0c\u5219\u53d6\u5f53\u524d\u70b9\u4f5c\u4e3a\u5f53\u524d\u8fde\u7eed\u70b9\u96c6\u8d77\u59cb\u8fb9\u754c\uff0c\u7531\u4e8e\u662f\u4ecefirst_negative+1\u5f00\u59cb\uff0c\u5230available\u7ed3\u675f\u7684\uff0c\u6240\u4ee5\u4e0d\u4f1a\u5224\u65ad\u521d\u59cb\u96c6\u5916\u7684\u4f4d\u7f6e\n\t\t\tif (!distance[i - 1])\n\t\t\t\tcontinuous_first_location_temp = i;\n\t\t\t\n\t\t\tcontinuous_number_now++;\n\t\t\tif (continuous_number_now > continuous_max_number) {\n\t\t\t\tcontinuous_max_number = continuous_number_now;\n\t\t\t\tcontinuous_max_last_location = i;\n\t\t\t\tcontinuous_max_first_location = continuous_first_location_temp;\n\t\t\t}\n\t\t} else \n\t\t\tcontinuous_number_now = 0;\n\t}\n\t\n\tranges_boundary.clear();\n\tangles_boundary.clear();\n\t\n\t\n\tif (continuous_max_first_location < continuous_max_last_location) {\n\t\tfor (int i = continuous_max_first_location; i < continuous_max_last_location + 1; i++) {\n\t\t\tranges_boundary.push_back(ranges_raw[i]);\n\t\t\tangles_boundary.push_back(angle_min + angle_increment * increment_raw[i]);\n\t\t}\n\t} else {\n\t\tfor (int i = continuous_max_first_location; i < available_number; i++) {\n\t\t\tranges_boundary.push_back(ranges_raw[i]);\n\t\t\tangles_boundary.push_back(angle_min + angle_increment * increment_raw[i]);\n\t\t}\n\t\tfor (int i = 0; i <= continuous_max_last_location; i++) {\n\t\t\tranges_boundary.push_back(ranges_raw[i]);\n\t\t\tangles_boundary.push_back(angle_min + angle_increment * increment_raw[i]);\n\t\t}\n\t}\n}\n\n//\u6839\u636e\u8ddd\u79bb\u7b97\u5750\u6807\uff0c\u6839\u636e\u66f2\u7387\u7b97\u89d2\u70b9\uff0ccorner_number\u662f\u66f2\u7387\u6700\u5927\u70b9\nvoid find_roughpose_and_corner(Eigen::Vector3d &pose, int &corner_number, const int type) {\n\n\tdouble smoothness_max = 0;\n\tcorner_number = 0;\n\tfor (int i = 9; i < ranges_boundary.size() - 9; i++) {\n\t\tdouble smoothness = curve_smoothness_square(i);\n\t\tif (smoothness > smoothness_max) {\n\t\t\tsmoothness_max = smoothness;\n\t\t\tcorner_number = i;\n\t\t}\n\t}\n\tstd::cout << \"Corner: \" << corner_number << \"\\tSmoothness_max1: \" << smoothness_max << std::endl;\n\t\n\tdouble min_range1 = 100, min_range2 = 100;\n\t\n\tfor (int i = 0; i < corner_number - 9; i++) {\n\t\tif (ranges_boundary[i] < min_range1)\n\t\t\tmin_range1 = ranges_boundary[i];\n\t}\n\tfor (int i = corner_number + 9; i < ranges_boundary.size(); i++) {\n\t\tif (ranges_boundary[i] < min_range2) {\n\t\t\tmin_range2 = ranges_boundary[i];\n\t\t}\n\t}\n\t\n\t//\u8ddd\u79bb\u8fb9\u7f18\u6700\u8fd1\u7684\u8ddd\u79bb\u5206\u522b\u662flidar\u4f4d\u7f6ex,y\uff0calpha\u662fx=0\u7ebf\u5230lidar\u7684angle_min\u7684\u57fa\u51c6\u7ebf\u7684\u89d2\u5ea6 theta\u662f\u4e2d\u95f4\u53d8\u91cf\n\tdouble x, y, alpha, theta;\n\t\n\tif (min_range1 > ranges_boundary[corner_number] && min_range2 > ranges_boundary[corner_number]) {\n\t\tstd::cout << \"Ranges of all boundary points are bigger than range of corner points!\" << std::endl\n\t\t\t\t\t\t\t<< \"Fatal error happened! Program is shuting down...\" << std::endl;\n\t\t\n\t\texit(0);\n\t}\n\t\n\tswitch(type) {\n\t\tcase 0:\n\t\t\talpha = angles_boundary[corner_number];\n\t\t\tx = min_range1;\n\t\t\ty = min_range2;\n\t\t\tif (min_range1 < min_range2)\n\t\t\t\ttheta = acos(min_range1 / ranges_boundary[corner_number]);\n\t\t\telse\n\t\t\t\ttheta = asin(min_range2 / ranges_boundary[corner_number]);\n\t\t\talpha = M_PI - alpha + theta;\n\t\t\tbreak;\n\t\tcase 1:\n\t\t\talpha = angles_boundary[corner_number];\n\t\t\tx = 8 - min_range2;\n\t\t\ty = min_range1;\n\t\t\tif (min_range1 > min_range2)\n\t\t\t\ttheta = acos(min_range2 / ranges_boundary[corner_number]);\n\t\t\telse\n\t\t\t\ttheta = asin(min_range1 / ranges_boundary[corner_number]);\n\t\t\talpha = - alpha - theta;\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\talpha = angles_boundary[corner_number];\n\t\t\tx = min_range2;\n\t\t\ty = 5 - min_range1;\n\t\t\tif (min_range1 > min_range2)\n\t\t\t\ttheta = acos(min_range2 / ranges_boundary[corner_number]);\n\t\t\telse\n\t\t\t\ttheta = asin(min_range1 / ranges_boundary[corner_number]);\n\t\t\talpha = M_PI - theta - alpha;\n\t\t\tbreak;\n\t\tcase 3:\n\t\t\talpha = angles_boundary[corner_number];\n\t\t\tx = 8 - min_range1;\n\t\t\ty = 5 - min_range2;\n\t\t\tif (min_range1 < min_range2)\n\t\t\t\ttheta = acos(min_range1 / ranges_boundary[corner_number]);\n\t\t\telse\n\t\t\t\ttheta = asin(min_range2 / ranges_boundary[corner_number]);\n\t\t\talpha = -alpha + theta;\n\t\t\tbreak;\n\t}\n\t\n\tangle_standard(alpha);\n\tpose = Eigen::Vector3d(x, y, alpha);\n}\n\nEigen::Vector3d find_pose_precise(const Eigen::Vector3d &initial_pose, const int& corner, const int type) {\n\tEigen::Vector3d pose;\n\t// pose \u7ef4\u5ea6\u4e3a 3, landmark \u7ef4\u5ea6\u4e3a 1\n\ttypedef g2o::BlockSolver< g2o::BlockSolverTraits<3, 1> > Block;\n\t// \u7ebf\u6027\u65b9\u7a0b\u6c42\u89e3\u5668\n\tBlock::LinearSolverType* linearSolver = new g2o::LinearSolverCSparse<Block::PoseMatrixType>();\n\t// \u77e9\u9635\u5757\u6c42\u89e3\u5668\n\tBlock* solver_ptr = new Block ( linearSolver );\n\tg2o::OptimizationAlgorithmLevenberg* solver = new g2o::OptimizationAlgorithmLevenberg ( solver_ptr );\n\tg2o::SparseOptimizer optimizer;\n\toptimizer.setAlgorithm ( solver );\n\n  // vertex\n\tBoundaryPoseVertex* pose_vertex = new BoundaryPoseVertex(); // camera pose\n\tpose_vertex->setEstimate(initial_pose);\n\tpose_vertex->setId(0);\n\toptimizer.addVertex(pose_vertex);\n\t\n\tint index = 1;\n\t\t\n\tEigen::Matrix2d Information_Matrix = Eigen::Matrix2d::Identity() * 1e-4;\n\t\n\tswitch(type) {\n\t\tcase 0:\n\t\t\tfor (int i = 0; i < corner - 9; i++) {\n\t\t\t\tEigen::Vector2d point(angles_boundary[i], ranges_boundary[i]);\n\t\t\t\tBoundaryEdge_Left* edge = new BoundaryEdge_Left(angles_boundary[i], ranges_boundary[i]);\n\t\t\t\tedge->setId(index);\n\t\t\t\tedge->setVertex(0, pose_vertex);\n\t\t\t\t// \u8bbe\u7f6e\u8fde\u63a5\u7684\u9876\u70b9\n\t\t\t\tedge->setMeasurement(point);\n\t\t\t\t// \u89c2\u6d4b\u6570\u503c\n\t\t\t\tedge->setInformation(Information_Matrix);\n\t\t\t\t// \u4fe1\u606f\u77e9\u9635\uff1a\u534f\u65b9\u5dee\u77e9\u9635\u4e4b\u9006\n\t\t\t\toptimizer.addEdge(edge);\n\t\t\t\tindex++;\n\t\t\t}\n\t\t\tfor (int i = corner + 9; i < ranges_boundary.size(); i++) {\n\t\t\t\t\tEigen::Vector2d point(angles_boundary[i], ranges_boundary[i]);\n\t\t\t\t\tBoundaryEdge_Bottom* edge = new BoundaryEdge_Bottom(angles_boundary[i], ranges_boundary[i]);\n\t\t\t\t\tedge->setId(index);\n\t\t\t\t\tedge->setVertex(0, pose_vertex);\n\t\t\t\t\t// \u8bbe\u7f6e\u8fde\u63a5\u7684\u9876\u70b9\n\t\t\t\t\tedge->setMeasurement(point);      \n\t\t\t\t\t// \u89c2\u6d4b\u6570\u503c\n\t\t\t\t\tedge->setInformation(Information_Matrix);\n\t\t\t\t\t// \u4fe1\u606f\u77e9\u9635\uff1a\u534f\u65b9\u5dee\u77e9\u9635\u4e4b\u9006\n\t\t\t\t\toptimizer.addEdge(edge);\n\t\t\t\t\tindex++;\n\t\t\t\t}\n\t\t\tbreak;\n\t\tcase 1:\n\t\t\tfor (int i = 0; i < corner - 9; i++) {\n\t\t\t\tEigen::Vector2d point(angles_boundary[i], ranges_boundary[i]);\n\t\t\t\tBoundaryEdge_Bottom* edge = new BoundaryEdge_Bottom(angles_boundary[i], ranges_boundary[i]);\n\t\t\t\tedge->setId(index);\n\t\t\t\tedge->setVertex(0, pose_vertex);\n\t\t\t\t// \u8bbe\u7f6e\u8fde\u63a5\u7684\u9876\u70b9\n\t\t\t\tedge->setMeasurement(point);      \n\t\t\t\t// \u89c2\u6d4b\u6570\u503c\n\t\t\t\tedge->setInformation(Information_Matrix);\n\t\t\t\t// \u4fe1\u606f\u77e9\u9635\uff1a\u534f\u65b9\u5dee\u77e9\u9635\u4e4b\u9006\n\t\t\t\toptimizer.addEdge(edge);\n\t\t\t\tindex++;\n\t\t\t}\n\t\t\tfor (int i = corner + 9; i < ranges_boundary.size(); i++) {\n\t\t\t\tEigen::Vector2d point(angles_boundary[i], ranges_boundary[i]);\n\t\t\t\tBoundaryEdge_Right* edge = new BoundaryEdge_Right(angles_boundary[i], ranges_boundary[i]);\n\t\t\t\tedge->setId(index);\n\t\t\t\tedge->setVertex(0, pose_vertex);\n\t\t\t\t// \u8bbe\u7f6e\u8fde\u63a5\u7684\u9876\u70b9\n\t\t\t\tedge->setMeasurement(point);      \n\t\t\t\t// \u89c2\u6d4b\u6570\u503c\n\t\t\t\tedge->setInformation(Information_Matrix);\n\t\t\t\t// \u4fe1\u606f\u77e9\u9635\uff1a\u534f\u65b9\u5dee\u77e9\u9635\u4e4b\u9006\n\t\t\t\toptimizer.addEdge(edge);\n\t\t\t\tindex++;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\tfor (int i = 0; i < corner - 9; i++) {\n\t\t\t\tEigen::Vector2d point(angles_boundary[i], ranges_boundary[i]);\n\t\t\t\tBoundaryEdge_Top* edge = new BoundaryEdge_Top(angles_boundary[i], ranges_boundary[i]);\n\t\t\t\tedge->setId(index);\n\t\t\t\tedge->setVertex(0, pose_vertex);\n\t\t\t\t// \u8bbe\u7f6e\u8fde\u63a5\u7684\u9876\u70b9\n\t\t\t\tedge->setMeasurement(point);      \n\t\t\t\t// \u89c2\u6d4b\u6570\u503c\n\t\t\t\tedge->setInformation(Information_Matrix);\n\t\t\t\t// \u4fe1\u606f\u77e9\u9635\uff1a\u534f\u65b9\u5dee\u77e9\u9635\u4e4b\u9006\n\t\t\t\toptimizer.addEdge(edge);\n\t\t\t\tindex++;\n\t\t\t}\n\t\t\tfor (int i = corner + 9; i < ranges_boundary.size(); i++) {\n\t\t\t\tEigen::Vector2d point(angles_boundary[i], ranges_boundary[i]);\n\t\t\t\tBoundaryEdge_Left* edge = new BoundaryEdge_Left(angles_boundary[i], ranges_boundary[i]);\n\t\t\t\tedge->setId(index);\n\t\t\t\tedge->setVertex(0, pose_vertex);\n\t\t\t\t// \u8bbe\u7f6e\u8fde\u63a5\u7684\u9876\u70b9\n\t\t\t\tedge->setMeasurement(point);      \n\t\t\t\t// \u89c2\u6d4b\u6570\u503c\n\t\t\t\tedge->setInformation(Information_Matrix);\n\t\t\t\t// \u4fe1\u606f\u77e9\u9635\uff1a\u534f\u65b9\u5dee\u77e9\u9635\u4e4b\u9006\n\t\t\t\toptimizer.addEdge(edge);\n\t\t\t\tindex++;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 3:\n\t\t\tfor (int i = 0; i < corner - 9; i++) {\n\t\t\t\tEigen::Vector2d point(angles_boundary[i], ranges_boundary[i]);\n\t\t\t\tBoundaryEdge_Right* edge = new BoundaryEdge_Right(angles_boundary[i], ranges_boundary[i]);\n\t\t\t\tedge->setId(index);\n\t\t\t\tedge->setVertex(0, pose_vertex);\n\t\t\t\t// \u8bbe\u7f6e\u8fde\u63a5\u7684\u9876\u70b9\n\t\t\t\tedge->setMeasurement(point);      \n\t\t\t\t// \u89c2\u6d4b\u6570\u503c\n\t\t\t\tedge->setInformation(Information_Matrix);\n\t\t\t\t// \u4fe1\u606f\u77e9\u9635\uff1a\u534f\u65b9\u5dee\u77e9\u9635\u4e4b\u9006\n\t\t\t\toptimizer.addEdge(edge);\n\t\t\t\tindex++;\n\t\t\t}\n\t\t\tfor (int i = corner + 9; i < ranges_boundary.size(); i++) {\n\t\t\t\tEigen::Vector2d point(angles_boundary[i], ranges_boundary[i]);\n\t\t\t\tBoundaryEdge_Top* edge = new BoundaryEdge_Top(angles_boundary[i], ranges_boundary[i]);\n\t\t\t\tedge->setId(index);\n\t\t\t\tedge->setVertex(0, pose_vertex);\n\t\t\t\t// \u8bbe\u7f6e\u8fde\u63a5\u7684\u9876\u70b9\n\t\t\t\tedge->setMeasurement(point);      \n\t\t\t\t// \u89c2\u6d4b\u6570\u503c\n\t\t\t\tedge->setInformation(Information_Matrix);\n\t\t\t\t// \u4fe1\u606f\u77e9\u9635\uff1a\u534f\u65b9\u5dee\u77e9\u9635\u4e4b\u9006\n\t\t\t\toptimizer.addEdge(edge);\n\t\t\t\tindex++;\n\t\t\t}\n\t\t\tbreak;\n\t}\n\tstd::cout << \"start optimization\" << std::endl;\n\toptimizer.initializeOptimization();\n\toptimizer.optimize(100);\n\t\n\treturn pose_vertex->estimate();\n}\n\n\n\nvoid scanCallback(const sensor_msgs::LaserScanConstPtr msg) {\n\tangle_max = msg->angle_max;\n\tangle_min = msg->angle_min;\n\tangle_increment = msg->angle_increment;\n\tint angle_number = (int)( (angle_max - angle_min)/angle_increment ) + 1;\n\t\n\tstd::vector<double> ranges_raw;\n\tstd::vector<int> increment_raw;\n\n\t//\u53bb\u9664\u906e\u6321\u70b9\uff0c\u4fdd\u7559\u6709\u6548\u96f7\u8fbe\u70b9\u4fe1\u606f\uff0cranges_raw\u662frange\u4fe1\u606f\uff0cincrement\u662f\u6709\u6548\u70b9\u987a\u5e8f\u4fe1\u606f\uff08\u7528\u4e8e\u540e\u7eed\u751f\u6210\u89d2\u5ea6\u4fe1\u606f\uff09\n\tfor (int i = 0; i < angle_number; i++) {\n\t\tif (msg->ranges[i] != std::numeric_limits<float>::infinity()) {\n\t\t\tranges_raw.push_back(msg->ranges[i]);\n\t\t\tincrement_raw.push_back(i);\n\t\t}\n\t}\n\n\textract_boundary_information(ranges_raw, increment_raw);\n\t//std::cout << \"boundary_size: \" << ranges_boundary.size() << std::endl;\n\tEigen::Vector3d rough_pose;\n\t\n\tfind_roughpose_and_corner(rough_pose, corner, corner_type);\n\t\n\tstd::cout << \"rough_pose: \" << rough_pose.transpose() << std::endl;\n\t\n\tEigen::Vector3d pose;\n\tpose = find_pose_precise(rough_pose, corner, corner_type);\n\tangle_standard(pose(2));\n\t\n\tstd::cout << \"precise_pose: \" << pose.transpose() << std::endl << std::endl;\n}\n\nint main(int argc, char **argv)\n{\n  ros::init(argc, argv, \"initial_pose\");\n  ros::NodeHandle n;\n\t\n  ros::Subscriber scan_sub = n.subscribe(\"/scan\", 1, scanCallback);\n\tsensor_msgs::LaserScan scan;\n\t\n\tros::Publisher boundary_pub = n.advertise<sensor_msgs::PointCloud>(\"boundary\", 50);\n\tros::Publisher corner_pub = n.advertise<sensor_msgs::PointCloud>(\"corner\", 50);\n\t\n\tros::Rate loop_rate(10);\n\twhile (ros::ok()) {\n\t\tunsigned int num_points = ranges_boundary.size();\n\t\tsensor_msgs::PointCloud cloud;\n    cloud.header.stamp = ros::Time::now();\n    cloud.header.frame_id = \"laser\";\n\n    cloud.points.resize(num_points);\n\n    //we'll also add an intensity channel to the cloud\n    cloud.channels.resize(1);\n    cloud.channels[0].name = \"intensities\";\n    cloud.channels[0].values.resize(num_points);\n\n    //generate some fake data for our point cloud\n    for(unsigned int i = 0; i < num_points; ++i){\n      cloud.points[i].x = ranges_boundary[i] * cos(angles_boundary[i]);\n      cloud.points[i].y = ranges_boundary[i] * sin(angles_boundary[i]);\n      cloud.points[i].z = 0;\n      cloud.channels[0].values[i] = 100;\n    }\n\n    sensor_msgs::PointCloud corner_cloud;\n\t\tcorner_cloud.header.stamp = ros::Time::now();\n\t\tcorner_cloud.header.frame_id = \"laser\";\n\t\tcorner_cloud.points.resize(2);\n\t\tcorner_cloud.channels.resize(1);\n\t\tcorner_cloud.channels[0].name = \"intensities\";\n\t\tcorner_cloud.channels[0].values.resize(2);\n\t\tif (corner != 0) {\n\t\t\tcorner_cloud.points[0].x = (ranges_boundary[corner] + 1) * cos(angles_boundary[corner]);\n\t\t\tcorner_cloud.points[0].y = (ranges_boundary[corner] + 1) * sin(angles_boundary[corner]);\n\t\t\tcorner_cloud.points[0].z = 0;\n\t\t\tcorner_cloud.channels[0].values[0] = 200;\n\t\t}\n\t\tcorner_cloud.points[1].x = 1;\n\t\tcorner_cloud.points[1].y = 0;\n\t\tcorner_cloud.points[1].z = 0;\n\t\tcorner_cloud.channels[0].values[1] = 10;\n    boundary_pub.publish(cloud);\n\t\tcorner_pub.publish(corner_cloud);\n\t\tros::spinOnce();\n\t\tloop_rate.sleep();\n\t}\n  return 0;\n}", "meta": {"hexsha": "c22ad0c430bc1ab5c00dbecb1168b16cd1fdcf20", "size": 20288, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "robot2019-ros/initial_pose/src/new_initial_pose.cpp", "max_stars_repo_name": "junhuizhou/ROS_Learning", "max_stars_repo_head_hexsha": "bb3a0c867ba2bd147bbd59176cf1224c09a63914", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "robot2019-ros/initial_pose/src/new_initial_pose.cpp", "max_issues_repo_name": "junhuizhou/ROS_Learning", "max_issues_repo_head_hexsha": "bb3a0c867ba2bd147bbd59176cf1224c09a63914", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-07T07:30:11.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-07T07:30:11.000Z", "max_forks_repo_path": "robot2019-ros/initial_pose/src/new_initial_pose.cpp", "max_forks_repo_name": "junhuizhou/ROS_Learning", "max_forks_repo_head_hexsha": "bb3a0c867ba2bd147bbd59176cf1224c09a63914", "max_forks_repo_licenses": ["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.1503267974, "max_line_length": 122, "alphanum_fraction": 0.6956821767, "num_tokens": 6315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.47004740749162605}}
{"text": "#ifndef FINDINTRA_CPP\n#define FINDINTRA_CPP\n\n#include <cstdlib>\n#include <ctime>\n#include <fstream>\n#include <iostream>\n#include <map>\n#include <math.h>\n#include <vector>\n\n#include <gsl/gsl_cdf.h>\n\n#include <scythestat/rng/mersenne.h>\n#include <scythestat/distributions.h>\n#include <scythestat/ide.h>\n#include <scythestat/la.h>\n#include <scythestat/matrix.h>\n#include <scythestat/rng.h>\n#include <scythestat/smath.h>\n#include <scythestat/stat.h>\n#include <scythestat/optimize.h>\n\n#include <IRLS_glm/IRLS.h>\n\n//#include <RInside.h>\n\n#include <mlpack/methods/lars/lars.hpp>\n#include <mlpack/methods/linear_regression/linear_regression.hpp>\n#include <boost/test/unit_test.hpp>\n\n#define INTTAG 0\n#define BOOLTAG 1\n#define DIETAG 2\n\n#define TESTFREQTHRES 1\n#define NEIGHBDIS 5\n//#define MORANI 0.001\n#define PCUTOFF 0.005\n#define PRECISION 10e48\n#define READBLOCK 409600\n#define OPTDIST 1000\n\n//using namespace std;\nusing std::abs;\nusing std::basic_string;\nusing std::cerr;\nusing std::cin;\nusing std::cout;\nusing std::endl;\nusing std::exception;\nusing std::flush;\nusing std::ifstream;\nusing std::istringstream;\nusing std::make_pair;\nusing std::map;\nusing std::ofstream;\nusing std::ostringstream;\nusing std::pair;\nusing std::pow;\nusing std::sort;\nusing std::string;\nusing std::vector;\n\n\nint reader_dif(const string&, vector< vector< vector<int> > >&);\nint reader_dsm(const string&, vector< vector<int> >&);\nint reader_coef(const string&, map<int, double>&);\nvoid reader_ictm(const string&, map<int, int>&);\nint findIntraDomainInteraction(map<int, int>&, string, vector< vector<int> >&, vector< vector< vector<int> > >&, map<int, int>&, map<int, double>&, map< int, map< pair<int, int>, double > >&, double, double, double);\nint rmDependentCol(vector< vector<double> >&, vector<double>&, vector< pair<int, int> >&, double, int&, vector< vector<double> >&);\nint calStanScores(vector< vector<double> >&);\nint calPearsonCorr(vector< vector<double> >&, vector< pair<int, int> >&, const double&, int, map<int, int>&);\ndouble calBgFrags(map<int, double>&, int);\nint writer_corrFile(map< pair<int, int>, double >&, string&);\n\nvoid usage();\n\ninline void usage()\n{\n    cout <<\"Usage: findIntraDomainInteraction empericalDistributionFile interChrFreqFile domainSitesFile domainInteractionFreqFile chrNum MORANI CorrelationThresholdForScreen\"<<endl;\n}\n\n//convtIndex is now 0 based\ninline int convtIndex(int row_fun, int col_fun, int siteNum_fun)\n{\n    if (row_fun==col_fun || row_fun>=siteNum_fun || col_fun>=siteNum_fun || row_fun<0 || col_fun<0)\n    {//cout<<\"row or column exceed bound.\"<<endl;\n        return -1;\n    }\n    else\n    {\n        int max_fun = 0, min_fun = 0;\n        if (row_fun<col_fun)\n        {\n            //switch to 1 based\n            max_fun = col_fun+1;\n            min_fun = row_fun+1;\n        }\n        else\n        {\n            max_fun = row_fun+1;\n            min_fun = col_fun+1;\n        }\n        return((2*siteNum_fun-min_fun)*(min_fun-1)/2+max_fun-min_fun) - 1;//-1 put the output to be 0 based\n    }\n}\n\n\n//l=sigma(yi(theta*xi+offseti)-exp(theta*xi+offseti))\nclass PoissonModel {\n    public:\n    double operator() (const scythe::Matrix<double> beta){\n        const int n = y_.rows();\n        const int p = X_.cols();\n\n        scythe::Matrix<double> eta = X_ * beta + offset_;\n        scythe::Matrix<double> m = exp(eta);\n        double loglike = 0.0;\n        for (int i=0; i<n; ++i)\n        loglike += y_(i) * log(m(i)) - m(i);\n        return -1.0 * loglike;\n    }\n    scythe::Matrix<double> y_;\n    scythe::Matrix<double> X_;\n    scythe::Matrix<double> offset_;\n};\n\n\nint main(int argc, char* argv[])\n{\n    if (argc < 8)\n    {\n        usage();\n        exit(1);\n    }\n\n    //string empDisFile = argv[1];\n    string ictmFile = argv[1];\n    string dsmFile = argv[2];\n    string difFile = argv[3];\n    string chrNum = argv[4];\n    //double MORANI = atof(argv[6]);\n    double corrThres = 0.0;\n    string disCoefFile = argv[5];\n    double mu_eff = atof(argv[6]);\n    double beta_eff = atof(argv[7]);\n\n    map<int, int> empDis_map;\n    map<int, int> ictm_map;\n    vector< vector<int> > dsm_map;\n    vector< vector< vector<int> > > dif_map;\n    map<int, double> disPolyCoef;\n\n    //reader_ictm(empDisFile, empDis_map);\n    //cout<<\"\\nReading empDis file done.\"<<endl;\n    reader_ictm(ictmFile, ictm_map);\n    cout<<\"\\nRead ictm file done.\"<<endl;\n    reader_dsm(dsmFile, dsm_map);\n    cout<<\"\\nRead dsm file done.\"<<endl;\n    reader_dif(difFile, dif_map);\n    cout<<\"\\nRead dif file done.\"<<endl;\n    reader_coef(disCoefFile, disPolyCoef);\n    cout<<\"\\nRead distance polynomial fit coefficients done.\"<<endl;\n\n    map< int, map< pair<int, int>, double > > pVal_map;\n\n    findIntraDomainInteraction(empDis_map, chrNum, dsm_map, dif_map, ictm_map, disPolyCoef, pVal_map, corrThres, mu_eff, beta_eff);\n\n    return 0;\n}\n\n\nint reader_dif(const string& fileToread, vector< vector< vector<int> > >& dif_local)\n{\n    ifstream inputFile(fileToread.c_str());\n    if (!inputFile)\n    {\n        //char a;\n        //cin >>a;\n        cout <<\"\\n\"<< \"Error opening \" << fileToread << \".\" << endl;\n        exit(1);\n    }\n\n    char lineStr[READBLOCK];\n    char freq_str[15];\n    int freq_int = 0;\n    int domainNum = 0;\n\n    int column = 0;\n\n    char* it_lineStr;\n    char* it_token;\n\n    int peakNum = 0;\n\n    //copy data to a map, which chrNo is the key, the value is a vector of ints(read's starting point)\n    vector< vector<int> > tempDomn;\n    while(inputFile.getline(lineStr,READBLOCK))\n    {\n        it_lineStr = lineStr;\n\n        column = 0;\n\n        if (lineStr != NULL)\n        {\n            vector<int> tempFreq;\n\n            //pass head white space\n            if(*it_lineStr == 'd')\n            {\n                if (tempDomn.begin() != tempDomn.end())\n                {\n                    ++domainNum;\n                    dif_local.push_back(tempDomn);\n                    tempDomn.clear();\n                }\n                continue;\n            }\n\n            while(*it_lineStr != '\\0' && *it_lineStr != '\\n')\n            {\n                if (*it_lineStr == ' ' || *it_lineStr == '\\t')\n                {\n                    //remove white space\n                    while(*it_lineStr == ' ' || *it_lineStr == '\\t')\n                    {\n                        ++it_lineStr;\n                    }\n\n                    ++column;\n                }\n                else\n                {\n                    it_token = freq_str;\n                    while(*it_lineStr != ' ' && *it_lineStr != '\\t' && *it_lineStr != '\\0' && *it_lineStr != '\\n')\n                    {\n                        *it_token = *it_lineStr;\n                        ++it_token;\n                        ++it_lineStr;\n                    }\n                    *it_token = '\\0';\n                    freq_int = atoi(freq_str);\n                    tempFreq.push_back(freq_int);\n                }\n            }\n\n            tempDomn.push_back(tempFreq);\n            ++peakNum;\n        }\n    }\n\n    if(tempDomn.begin() != tempDomn.end())\n    {\n        dif_local.push_back(tempDomn);\n    }\n\n    inputFile.close();\n\n    return peakNum;\n}\n\n\n\n\nint reader_dsm(const string& fileToread, vector< vector<int> >& dsm_local)\n{\n    ifstream inputFile(fileToread.c_str());\n    if (!inputFile)\n    {\n        //char a;\n        //cin >>a;\n        cout <<\"\\n\"<< \"Error opening \" << fileToread << \".\" << endl;\n        exit(1);\n    }\n\n    char lineStr[READBLOCK];\n    char pos_str[15];\n    int pos_int = 0;\n\n    int column = 0;\n\n    char* it_lineStr;\n    char* it_token;\n\n    int peakNum = 0;\n\n    //copy data to a map, which chrNo is the key, the value is a vector of ints(read's starting point)\n    //ofstream testBadFile(\"test\");\n    while(inputFile.getline(lineStr,READBLOCK))\n    {\n        it_lineStr = lineStr;\n\n        column = 0;\n\n        if (lineStr != NULL)\n        {\n            vector<int> tempPos;\n            //testBadFile<<lineStr<<endl;\n\n            //pass head white space\n            while(*it_lineStr == ' '|| *it_lineStr == '\\t')\n            {\n                ++it_lineStr;\n            }\n\n            while(*it_lineStr != '\\0' && *it_lineStr != '\\n')\n            {\n                if (*it_lineStr == ' ' || *it_lineStr == '\\t')\n                {\n                    //remove white space\n                    while(*it_lineStr == ' ' || *it_lineStr == '\\t')\n                    {\n                        ++it_lineStr;\n                    }\n\n                    ++column;\n                }\n                else\n                {\n                    it_token = pos_str;\n                    while(*it_lineStr != ' ' && *it_lineStr != '\\t' && *it_lineStr != '\\0' && *it_lineStr != '\\n')\n                    {\n                        *it_token = *it_lineStr;\n                        ++it_token;\n                        ++it_lineStr;\n                    }\n                    *it_token = '\\0';\n                    pos_int = atoi(pos_str);\n                    tempPos.push_back(pos_int);\n                }\n            }\n\n            dsm_local.push_back(tempPos);\n            ++peakNum;\n        }\n    }\n\n    inputFile.close();\n\n    return peakNum;\n}\n\n\n\nint reader_coef(const string& fileToread, map<int, double>& disPolyCoef_local)\n{\n    ifstream inputFile(fileToread.c_str());\n    if (!inputFile)\n    {\n        cout <<\"\\n\"<< \"Error opening \" << fileToread << \".\" << endl;\n        exit(1);\n    }\n\n    char degree[15];\n    int degree_int = 0;\n    char coef[50];\n    double coef_dbl = 0.0;\n\n    char* it_lineStr;\n    char* it_token;\n\n    char lineStr[512];\n    while(inputFile.getline(lineStr,512))\n    {\n        if (lineStr != NULL)\n        {\n            it_lineStr = lineStr;\n\n            it_token = degree;\n            while(*it_lineStr != '\\t' && *it_lineStr != ' ' && *it_lineStr != '\\n' && *it_lineStr != '\\0')\n            {\n                *it_token = *it_lineStr;\n                ++it_token;\n                ++it_lineStr;\n            }\n            *it_token = '\\0';\n            degree_int = atoi(degree);\n\t    ++it_lineStr;\n\t    while(*it_lineStr == ' ' || *it_lineStr == '\\t')\n\t    {\n\t\t++it_lineStr;\n\t    }\n\n            it_token = coef;\n            while(*it_lineStr != '\\t' && *it_lineStr != ' ' && *it_lineStr != '\\n' && *it_lineStr != '\\0')\n            {\n                *it_token = *it_lineStr;\n                ++it_token;\n                ++it_lineStr;\n            }\n            *it_token = '\\0';\n            coef_dbl = atof(coef);\n\n            disPolyCoef_local[degree_int] = coef_dbl;\n        }\n    }\n    return 0;\n}\n\n\n\nvoid reader_ictm(const string& fileToread, map<int, int>& ictm_local)\n{\n    ifstream inputFile(fileToread.c_str());\n    if (!inputFile)\n    {\n        cout <<\"\\n\"<< \"Error opening \" << fileToread << \".\" << endl;\n        exit(1);\n    }\n\n    char pos[15];\n    int pos_int = 0;\n    char freq[15];\n    int freq_int = 0;\n\n    char* it_lineStr;\n    char* it_token;\n\n    char lineStr[512];\n    while(inputFile.getline(lineStr,512))\n    {\n        if (lineStr != NULL)\n        {\n            it_lineStr = lineStr;\n\n            it_token = pos;\n            while(*it_lineStr != '\\t')\n            {\n                *it_token = *it_lineStr;\n                ++it_token;\n                ++it_lineStr;\n            }\n            *it_token = '\\0';\n            ++it_lineStr;\n            pos_int = atoi(pos);\n\n            it_token = freq;\n            while(*it_lineStr != '\\t' && *it_lineStr != '\\n' && *it_lineStr != '\\0')\n            {\n                *it_token = *it_lineStr;\n                ++it_token;\n                ++it_lineStr;\n            }\n            *it_token = '\\0';\n            freq_int = atoi(freq);\n\n            ictm_local[pos_int] = freq_int;\n        }\n    }\n}\n\n\n\n\nint findIntraDomainInteraction(map<int, int>& empDisMap_fun, string jobChr_fun, vector< vector<int> >& domainSitesMap_fun, vector< vector< vector<int> > >& domainCSinterFreq_fun, map<int, int>& csInterChromTotalMap_fun, map<int, double>& disPolyCoef_local, map< int, map< pair<int, int>, double > >& pVal_fun, double corrThres_fun, double mu_eff_fun, double beta_eff_fun)\n{\n    string file_debug =  jobChr_fun + \"_debug\";\n    ofstream outDebug(file_debug.c_str());\n\n    int domainNum = domainSitesMap_fun.size();\n\n    //#pragma omp parallel for\n    for (int domainIt = 0; domainIt < domainNum; ++domainIt)\n    {\n\t//if(domainIt==1)\n\t//{exit(0);}\n        map< pair<int, int>, double>& domainPval = pVal_fun[domainIt];\n        outDebug<<\"domain \"<<domainIt<<endl;\n        vector<int>& sitesMap = domainSitesMap_fun[domainIt];\n        vector< vector<int> >& csInterFreqMap = domainCSinterFreq_fun[domainIt];\n        int siteNum = sitesMap.size();\n\n        int size_convert = convtIndex(siteNum-2,siteNum-1,siteNum) + 1;//the convtIndex function's first two input is 0 based and the output is 0 based too\n\tvector<double> freq_convert;\n        vector<double> offset;//distance effect\n        vector<double> effVec;//efficiency of cutting site and mappability, measured by the total inter chromosome hybrid frags\n\n\tostringstream domainIt_str;\n\tdomainIt_str<<domainIt;\n\tstring domainFile = \"domainData_\" + domainIt_str.str();\n\t//ofstream outDomainData(domainFile);\n\n        for (int rowIt=0; rowIt<siteNum; ++rowIt)\n        {\n            for (int colIt=rowIt+1; colIt<siteNum; ++colIt)\n            {\n                int index_convert=convtIndex(rowIt,colIt,siteNum);\n\n\t\t//if(abs(sitesMap[rowIt]-sitesMap[colIt])>OPTDIST)//the index of freq_convert need to be changed because of this\n\t\t{\n\t\t    //log(y/ydist)=mu+betaeff*effvec\n\t\t    freq_convert.push_back(csInterFreqMap[rowIt][colIt]);\n\t\t    offset.push_back(calBgFrags(disPolyCoef_local, abs(sitesMap[rowIt]-sitesMap[colIt])));\n\t\t    //the digestion and ligation efficient of a cutting site should take log because, its log should proportional to log(freq)\n\t\t    effVec.push_back(log(sqrt(csInterChromTotalMap_fun[sitesMap[rowIt]])*sqrt(csInterChromTotalMap_fun[sitesMap[colIt]])+1));\n\t\t    //outDomainData<<rowIt<<\"\\t\"<<colIt<<\"\\t\"<<csInterFreqMap[rowIt][colIt]<<\"\\t\"<<csInterChromTotalMap_fun[sitesMap[rowIt]]<<\"\\t\"<<csInterChromTotalMap_fun[sitesMap[colIt]]<<\"\\t\"<<log(sqrt(csInterChromTotalMap_fun[sitesMap[rowIt]])*sqrt(csInterChromTotalMap_fun[sitesMap[colIt]])+1)<<\"\\t\"<<sitesMap[rowIt]<<\"\\t\"<<sitesMap[colIt]<<\"\\t\"<<calBgFrags(disPolyCoef_local, abs(sitesMap[rowIt]-sitesMap[colIt])+OPTDIST)<<endl;\n\t\t}\n            }\n        }\n\t//outDomainData.close();\n\n\tvector<double> constTerms(size_convert, 0.0);\n        vector<double> effConsts(size_convert, 0.0);//efficiency constand mu+beta_eff_fun*effVec[i]\n\tfor (int i = 0; i < size_convert; ++i)\n\t{\n\t    //constTerms[i] = mu+dist_ij[i]*alpha+effVec[i]*beta;\n\t    effConsts[i] = mu_eff_fun+effVec[i]*beta_eff_fun;\n\t    constTerms[i] = exp(effConsts[i]+offset[i]);\n\t    //constTerms[i] = mu+effVec[i]*beta+offset[i];\n\t}\n\n        int counter_fit=0;\n        int counter_skip=0;\n\n\tint regionIt=0;\n\tint testIt=0;\n\n\tstring regionFile = \"regionData_\" + domainIt_str.str();\n\tofstream outRegionData(regionFile);\n\tbool flag_test = false;\n\n\tstring distMatrixFile = \"distMatrix_\" + domainIt_str.str();\n\tofstream outDistMatrix(distMatrixFile);\n\n        //#pragma omp parallel for\n        for (int rowIt=0; rowIt<siteNum; ++rowIt)\n        {\n            for (int colIt=rowIt+1; colIt<siteNum; ++colIt)\n            {\n                if(csInterFreqMap[rowIt][colIt]>TESTFREQTHRES && abs(sitesMap[rowIt]-sitesMap[colIt])>=20000)\n                {\n                    vector<double> neighbFreq;\n                    vector<double> neighbConstTerms;\n                    vector<double> fullExp;\n\n                    int sideLen = 2*NEIGHBDIS + 1;\n                    int colNum_mat = 0;\n                    int rowNum_mat = 0;\n\n\t\t    //ostringstream regionIt_str;\n\t\t    //regionIt_str<<regionIt;\n\t\t    //string regionFile = \"regionData_\" + domainIt_str.str() + \"_\" + regionIt_str.str();\n\t\t    //ofstream outRegionData(regionFile);\n                    vector< pair<int, int> > oriCoor;\n                    for (int neighbRowIt=(rowIt-NEIGHBDIS), squareRowIt = 0; squareRowIt < sideLen; ++neighbRowIt, ++squareRowIt)\n                    {\n                        for (int neighbColIt=colIt-NEIGHBDIS, squareColIt = 0; squareColIt < sideLen; ++neighbColIt, ++squareColIt)\n                        {\n                            int distMatrix_colIt=convtIndex(neighbRowIt, neighbColIt, siteNum);\n                            //if (distMatrix_colIt==-1 || neighbColIt<=neighbRowIt || colIt<=neighbRowIt || neighbColIt<=rowIt || (neighbRowIt==rowIt && neighbColIt==colIt) )\n                            if (distMatrix_colIt==-1 || neighbColIt<=neighbRowIt || colIt<=neighbRowIt || neighbColIt<=rowIt)\n                            {continue;}\n\n                            //for future get back the original coordinates\n                            if(freq_convert[distMatrix_colIt] > TESTFREQTHRES)\n                            {\n                                oriCoor.push_back(make_pair(neighbRowIt, neighbColIt));\n                                ++colNum_mat;\n                            }\n\n                            neighbFreq.push_back(freq_convert[distMatrix_colIt]-constTerms[distMatrix_colIt]);\n\t\t\t    //outRegionData<<neighbRowIt<<\"\\t\"<<neighbColIt<<\"\\t\"<<distMatrix_colIt<<\"\\t\"<<freq_convert[distMatrix_colIt]<<\"\\t\"<<constTerms[distMatrix_colIt]<<\"\\t\"<<mu_eff_fun<<\"\\t\"<<beta_eff_fun<<\"\\t\"<<effVec[distMatrix_colIt]<<\"\\t\"<<sitesMap[rowIt]<<\"\\t\"<<sitesMap[neighbRowIt]<<\"\\t\"<<sitesMap[colIt]<<\"\\t\"<<sitesMap[neighbColIt]<<\"\\t\"<<mu_eff_fun<<\"\\t\"<<beta_eff_fun<<\"\\t\"<<calBgFrags(disPolyCoef_local, abs(sitesMap[rowIt]-sitesMap[neighbRowIt])+abs(sitesMap[colIt]-sitesMap[neighbColIt])+OPTDIST)<<endl;\n                            //neighbConstTerms.push_back(constTerms[distMatrix_colIt]);\n\t\t\t    //\n                            fullExp.push_back(exp(effConsts[distMatrix_colIt]+calBgFrags(disPolyCoef_local, abs(sitesMap[rowIt]-sitesMap[neighbRowIt])+abs(sitesMap[colIt]-sitesMap[neighbColIt])+OPTDIST)));\n                            ++rowNum_mat;\n                        }\n                    }\n\t\t    //exit(0);\n\n                    //int neighbFreq_size = neighbFreq.size();\n\t\t    arma::vec neighbFreq_lm(neighbFreq);\n \n\t\t    int fullExpMat_size = fullExp.size();\n\n\t\t    arma::mat fullExpMat_lm(1,fullExpMat_size);\n\n\t\t    for(int i=0; i<fullExpMat_size; ++i)\n\t\t    {\n\t\t\t//fullExpMat_lm(i,0)=1;\n\t\t\tfullExpMat_lm(0,i)=fullExp[i];\n\t\t    }\n\n\t\t    mlpack::regression::LinearRegression lm(fullExpMat_lm, neighbFreq_lm,0.0,true);\n\t\t    //cout<<\"construct region model done.\"<<endl;\n\n\t\t    //set start values for theta\n\t\t    arma::vec& beta_lm = lm.Parameters();\n\t\t    //cout << \"The region MLEs are: \" << endl;\n\t\t    //std::cout <<\"regionMLEs: \"<<beta_lm(0)<<\"\\t\"<<beta_lm(1)<<endl;\n\n\t\t    if(beta_lm(1)>0.01)\n\t\t    {\n\t\t\t//arma::vec temp = neighbFreq_lm - arma::trans( (arma::trans(beta_lm.subvec(1, beta_lm.n_elem - 1)) * fullExpMat_lm) + beta_lm(0));\n\t\t\tarma::vec temp = neighbFreq_lm - arma::trans((beta_lm(1) * fullExpMat_lm) + beta_lm(0));\n\t\t\tdouble sigmaSq = arma::dot(temp, temp) / (fullExpMat_size-2);//denominator: n-number of betas(parameters)\n\n\t\t\t//double var_err = lm.ComputeError(fullExpMat_lm, neighbFreq_lm);\n\t\t\t//cout<<\"sigma squared: \"<<sigmaSq<<endl;\n\n\t\t\tdouble sumX=0.0;\n\t\t\tdouble sumXsq=0.0;\n\t\t\tfor(int i=0; i<fullExpMat_size; ++i)\n\t\t\t{\n\t\t\t    sumX+=fullExp[i];\n\t\t\t    sumXsq+=fullExp[i]*fullExp[i];\n\t\t\t}\n\n\t\t\tdouble beta_stderr = sqrt(fullExpMat_size*sigmaSq/(fullExpMat_size*sumXsq-sumX*sumX));\n\t\t\t//cout<<\"beta standard error: \"<<beta_stderr<<endl;\n\t\t\tdouble fitPval=2 * gsl_cdf_gaussian_P(-fabs(beta_lm(1)/beta_stderr), 1.0);\n\t\t\tstd::cout <<\"regionMLEs: \"<<beta_lm(0)<<\"\\t\"<<beta_lm(1)<<\"\\t\"<<fitPval<<\"\\t\"<<colNum_mat<<endl;\n\n\t\t\tif (fitPval < PCUTOFF && colNum_mat > 1)\n\t\t\t{\n\t\t\t    int distNum = colNum_mat;\n\t\t\t    vector<double> distVec_lasso(colNum_mat, 0.0);\n\t\t\t    vector< vector<double> > distMatrix_lasso;\n\t\t\t    for (int i=0; i<rowNum_mat; ++i)\n\t\t\t    {\n\t\t\t\tdistMatrix_lasso.push_back(distVec_lasso);\n\t\t\t    }\n\n\t\t\t    int testIndex = 0;\n\t\t\t    int matColIndex = 0;\n\t\t\t    for (int neighbRowIt=(rowIt-NEIGHBDIS), squareRowIt = 0; squareRowIt < sideLen; ++neighbRowIt, ++squareRowIt)\n\t\t\t    {\n\t\t\t\tfor (int neighbColIt=colIt-NEIGHBDIS, squareColIt = 0; squareColIt < sideLen; ++neighbColIt, ++squareColIt)\n\t\t\t\t{\n\t\t\t\t    int distMatrix_colIt=convtIndex(neighbRowIt, neighbColIt, siteNum);\n\t\t\t\t    //if (distMatrix_colIt==-1 || neighbColIt<=neighbRowIt || colIt<=neighbRowIt || neighbColIt<=rowIt || (neighbRowIt==rowIt && neighbColIt==colIt) )\n\t\t\t\t    if (distMatrix_colIt==-1 || neighbColIt<=neighbRowIt || colIt<=neighbRowIt || neighbColIt<=rowIt || freq_convert[distMatrix_colIt] <= TESTFREQTHRES)\n\t\t\t\t    //if (distMatrix_colIt==-1 || neighbColIt<=neighbRowIt || colIt<=neighbRowIt || neighbColIt<=rowIt || freq_convert[distMatrix_colIt] <= TESTFREQTHRES || abs(sitesMap[neighbRowIt]-sitesMap[neighbColIt])<20000)\n\t\t\t\t    {continue;}\n\n\t\t\t\t    int matRowIndex = 0;//inside loop is actually the row index for the final matrix\n\t\t\t\t    for (int neighbNeighbRowIt=(rowIt-NEIGHBDIS), squareNeighbRowIt = 0; squareNeighbRowIt < sideLen; ++neighbNeighbRowIt, ++squareNeighbRowIt)\n\t\t\t\t    {\n\t\t\t\t\tfor (int neighbNeighbColIt=colIt-NEIGHBDIS, squareNeighbColIt = 0; squareNeighbColIt < sideLen; ++neighbNeighbColIt, ++squareNeighbColIt)\n\t\t\t\t\t{\n\t\t\t\t\t    int distMatrix_rowIt=convtIndex(neighbNeighbRowIt, neighbNeighbColIt, siteNum);\n\t\t\t\t\t    if (distMatrix_rowIt==-1 || neighbNeighbColIt<=neighbNeighbRowIt || colIt<=neighbNeighbRowIt || neighbNeighbColIt<=rowIt)\n\t\t\t\t\t    {continue;}\n\t\t\t\t\t    //distMatrix_lasso[matRowIndex][matColIndex]=exp(-MORANI*(abs(sitesMap[neighbNeighbRowIt]-sitesMap[neighbRowIt])+abs(sitesMap[neighbNeighbColIt]-sitesMap[neighbColIt])));\n\t\t\t\t\t    distMatrix_lasso[matRowIndex][matColIndex]=exp(effConsts[distMatrix_rowIt]+calBgFrags(disPolyCoef_local, abs(sitesMap[neighbNeighbRowIt]-sitesMap[neighbRowIt])+abs(sitesMap[neighbNeighbColIt]-sitesMap[neighbColIt])+OPTDIST));\n\t\t\t\t\t    ++matRowIndex;\n\t\t\t\t\t}\n\t\t\t\t    }\n\t\t\t\t    if (neighbRowIt==rowIt && neighbColIt==colIt)\n\t\t\t\t    {\n\t\t\t\t\ttestIndex=matColIndex;\n\t\t\t\t    }\n\t\t\t\t    ++matColIndex;\n\t\t\t\t    //distMatrix[make_pair(distMatrix_rowIt, distMatrix_colIt)]=exp(-MORANI*(abs(sitesMap[rowIt]-sitesMap[neighbRowIt])+abs(sitesMap[colIt]-sitesMap[neighbColIt])));\n\t\t\t\t}\n\t\t\t    }\n\n\t\t\t    int testFlag = 1;\n\t\t\t    bool flag_rmDep = false;\n\n\t\t\t    if (testFlag == 1)\n\t\t\t    {\n\t\t\t\tflag_test=true;\n\t\t\t\t//#pragma omp critical\n\t\t\t\t{\n\t\t\t\t//cout<<rowIt<<\"\\t\"<<colIt<<\"\\ttest column number: \"<<testIndex<<endl;\n\n\t\t\t\t    const int rowNum_r = distMatrix_lasso.size();\n\t\t\t\t    const int colNum_r = (distMatrix_lasso.begin())->size();\n\t\t\t\t    //cout<<rowNum_r<<\"\\t\"<<colNum_r<<endl;\n\t\t\t//!!!!!!!!!!! if remove dependents is true, this need to change\n\t\t\t//\n\t\t\t\t    arma::mat fullExpMat_lars(colNum_r,rowNum_r);\n\n\t\t\t\t    //ostringstream testIt_str;\n\t\t\t\t    //testIt_str<<testIt;\n\t\t\t\t    //string distMatrixFile = \"distMatrix_\" + domainIt_str.str() + \"_\" + regionIt_str.str() + \"_\" + testIt_str.str();\n\n\t\t\t\t    //ofstream outDistMatrix(distMatrixFile);\n\t\t\t\t    outDistMatrix<<domainIt<<\"\\t\"<<regionIt<<\"\\t\"<<testIt<<\"\\n\";\n\t\t\t\t    for(int i=0; i<colNum_r; ++i)\n\t\t\t\t    {\n\t\t\t\t\tint j=0;\n\t\t\t\t\tfullExpMat_lars(i,j)=distMatrix_lasso[j][i];\n\t\t\t\t\toutDistMatrix<<distMatrix_lasso[j][i];\n\t\t\t\t\tfor(j=1; j<rowNum_r; ++j)\n\t\t\t\t\t{\n\t\t\t\t\t    fullExpMat_lars(i,j)=distMatrix_lasso[j][i];\n\t\t\t\t\t    outDistMatrix<<\"\\t\"<<distMatrix_lasso[j][i];\n\t\t\t\t\t}\n\t\t\t\t\toutDistMatrix<<\"\\n\";\n\t\t\t\t    }\n\n\t\t\t\t    outRegionData<<domainIt<<\"\\t\"<<regionIt<<\"\\n\";\n\t\t\t\t    vector<double>::const_iterator neighbFreqIt = neighbFreq.begin(), neighbFreqIt_end = neighbFreq.end();\n\t\t\t\t    outRegionData<<*neighbFreqIt;\n\t\t\t\t    for(++neighbFreqIt; neighbFreqIt != neighbFreqIt_end; ++neighbFreqIt)\n\t\t\t\t    {\n\t\t\t\t\toutRegionData<<\"\\t\"<<*neighbFreqIt;\n\t\t\t\t    }\n\t\t\t\t    outRegionData<<\"\\n\";\n\n\t\t\t\t    regionIt++;\n\t\t\t\t    testIt++;\n\n\t\t\t\t    distMatrix_lasso.clear();\n\t\t\t\t    ++counter_fit;\n\t\t\t\t}\n\t\t\t\t//#pragma omp end critical\n\n\t\t\t\t//if (fitPval < PCUTOFF)\n\t\t\t\t//{\n\t\t\t\t//    \n\t\t\t\t//}\n\t\t\t    }\n\t\t\t}\n\t\t\telse if(colNum_mat==1)\n\t\t\t{\n\t\t\t    //only 1 box has signal (freq>1), no need to use lasso to choose which one is real,or maybe could remove the ones due to the const terms, however glm should have taken care of that already\n\t\t\t}\n\t\t    }\n                }\n                else\n                {\n                    //#pragma omp critical\n                    {++counter_skip;}\n                    //#pragma omp end critical\n                }\n            }\n        }\n\toutRegionData.close();\n\toutDistMatrix.close();\n    }\n    outDebug.close();\n    \n    return 0;\n}\n\n\n\n\n\nint rmDependentCol(vector< vector<double> >& distMatrix_local, vector<double>& freqVec_local, vector< pair<int, int> >& oriCoor_local, double thres_local, int& testIndex_local, vector< vector<double> >& distMatRmDep_local)\n{\n    int rowNum_fun = distMatrix_local.size();\n    if (rowNum_fun != freqVec_local.size())\n    {\n        cerr<<\"Error: row number of the dist matrix is different from the size of the frequency vector.\"<<endl;\n        exit(1);\n    }\n    int colNum_fun = (distMatrix_local.begin())->size();\n    vector< vector<double> > distMatrix_std;\n    for (int i = 0; i < colNum_fun; ++i)\n    {\n        vector<double> tempVec;\n        for (int j = 0; j < rowNum_fun; ++j)\n        {\n            tempVec.push_back(distMatrix_local[j][i]);\n        }\n        distMatrix_std.push_back(tempVec);\n    }\n    distMatrix_std.push_back(freqVec_local);\n    calStanScores(distMatrix_std);\n\n    map< pair<int, int>, double > corrMap;\n    map<int, int> rmIndex;\n    int testFlag_local = calPearsonCorr(distMatrix_std, oriCoor_local, thres_local, testIndex_local, rmIndex);\n    cout<<\"testFlag: \"<<testFlag_local<<endl;\n\n    int oriTestIndex = testIndex_local;\n    for (int m = 0; m < oriTestIndex; ++m)\n    {\n        if (rmIndex[m]==1)\n        {\n            testIndex_local--;\n        }\n    }\n\n    for (int i = 0; i < rowNum_fun; ++i)\n    {\n        vector<double> tempVec;\n        for (int j = 0; j < colNum_fun; ++j)\n        {\n            if (rmIndex[j]!=1)\n            {\n                tempVec.push_back(distMatrix_local[i][j]);\n            }\n        }\n        distMatRmDep_local.push_back(tempVec);\n    }\n\n    return testFlag_local;\n}\n\n\n\n\nint calStanScores(vector< vector<double> >& distMatrix_std_fun)\n{\n    for (vector< vector<double> >::iterator colIt = distMatrix_std_fun.begin(), colIt_end = distMatrix_std_fun.end(); colIt != colIt_end; ++colIt) //colomn as in original matrix before transpose\n    {\n        int rowNum_fun = colIt->size();\n        double sum = 0.0;\n        for (vector<double>::const_iterator rowIt = colIt->begin(), rowIt_end = colIt->end(); rowIt != rowIt_end; ++rowIt)\n        {\n            sum += *rowIt;\n        }\n        double mean = sum / rowNum_fun;\n\n        double var = 0.0;\n        for (vector<double>::const_iterator rowIt = colIt->begin(), rowIt_end = colIt->end(); rowIt != rowIt_end; ++rowIt)\n        {\n            double diff = *rowIt - mean;\n            var += diff * diff;\n        }\n        var = var / (rowNum_fun - 1);\n        double std = sqrt(var);\n\n        for (vector<double>::iterator rowIt = colIt->begin(), rowIt_end = colIt->end(); rowIt != rowIt_end; ++rowIt)\n        {\n            *rowIt = (*rowIt - mean) / std;\n        }\n    }\n\n    return 0;\n}\n\n\n\n\nint calPearsonCorr(vector< vector<double> >& distMatrix_std_fun, vector< pair<int, int> >& oriCoor_fun, const double& thres_fun, int testIndex_fun, map<int, int>& rmIndex_fun)\n{\n    return 1;\n}\n\n\n\ndouble calBgFrags(map<int, double>& coef_fun, int dist_fun)\n{\n    double logDist=log(dist_fun);\n    double bgFrags=0.0;\n    map<int, double>::const_iterator coefIt=coef_fun.begin(), coefIt_end=coef_fun.end();\n    for( ; coefIt != coefIt_end; ++coefIt)\n    {\n\tbgFrags+=pow(logDist, coefIt->first)*coefIt->second;\n    }\n    return bgFrags;\n}\n\n\n\nint writer_corrFile(map< pair<int, int>, double >& corrMap_local, string& fileName)\n{\n    ofstream outputFile(fileName.c_str());\n\n    for (map< pair<int, int>, double>::const_iterator corrIt = corrMap_local.begin(), corrIt_end = corrMap_local.end(); corrIt != corrIt_end; ++corrIt)\n    {\n        outputFile<<corrIt->first.first<<\"\\t\"<<corrIt->first.second<<\"\\t\"<<corrIt->second<<endl;\n    }\n    outputFile.close();\n\n    return 0;\n}\n\n\n/*\nnnlasso.normal<-function(x,y,lambda=NULL,intercept=TRUE,normalize=TRUE,tau=1,tol=1e-6,maxiter=1e5,nstep=100,min.lambda=1e-4,eps=1e-6,path=TRUE,SE=FALSE)\n{\n        np=dim(x)\n        n=np[1]\n        p=np[2]\n        if (intercept)\n        {\n                meanx = colMeans(x)\n                x = scale(x, meanx, FALSE)\n                meany = sum(y)/n\n                y = y - meany\n        } else {\n                meanx = rep(0, p)\n                meany = 0\n                }\n        if (normalize)\n        {\n                normx = sqrt(colSums(x^2))\n                x = scale(x, FALSE, normx)\n        } else normx = rep(1, p)\n        tx=t(x)\n        xpy=tx%*%y\n        max.lambda=max(abs(xpy))\n        if (path)\n        {\n                stepsize=exp((log(min.lambda)-log(max.lambda))/nstep)\n                lambdas=max.lambda*stepsize^((1:nstep)-1)\n        } else {\n                        nstep=2\n                        lambdas=c(max.lambda,lambda)\n                }\n        coef=matrix(0,nstep,p)\n        of.value=rep(0,nstep)\n        coef[1,]=1e-2\n        xbeta.old=x%*%coef[1,]\n        if (n>p)\n        {\n                xpx=tx%*%x\n                xpxbetaold=xpx%*%coef[1,]\n        } else {\n                        xpx=NULL\n                        xpxbetaold=tx%*%xbeta.old\n                }\n        of.value[1]=-sum((y-xbeta.old)^2)/2-max.lambda*(tau*sum(coef[1,])+(1-tau)*sum(coef[1,]^2))\n        lambda.iter=rep(0,nstep)\n        g1=xpy\n        for(iter in 2:nstep)\n        {\n                kkt=FALSE\n                while(kkt==FALSE)\n                {\n                        res=nnlasso.normal.lambda(n,p,x,y,xpx,xpy,beta.old=coef[iter-1,],tau,lambda1=lambdas[iter],tol,maxiter,xbeta.old,eps,SE)\n                        if (res$conv==\"yes\")\n                        {\n                                coef[iter,]=res$beta.new\n                                xbeta=res$xbeta.new\n                                if (n>p)\n                                {\n                                        xpxbetaold=xpx%*%res$beta.new\n                                } else xpxbetaold=tx%*%xbeta\n                                g1=xpy-xpxbetaold-lambdas[iter]*2*(1-tau)*coef[iter,]\n                                indices=NULL\n                                if (length(indices)==0)\n                                {\n                                        xbeta.old=res$xbeta.new\n                                        lambda.iter[iter]=res$iter\n                                        of.value[iter]=res$ofv.new\n                                        kkt=TRUE\n                                }\n                        } else stop(\"The algorithm did not converge\")\n                }\n        }\n        coef=scale(coef,center=FALSE,scale=normx)\n        if(SE)\n        {\n                vcov=res$vcov\n                vcov=vcov/normx\n                vcov=t(vcov)/normx\n                se=sqrt(diag(vcov))\n                if(intercept)\n                {\n                        se0=sqrt(t(meanx)%*%vcov%*%meanx)\n                        se=c(se0,se)\n                }\n        } else se=NULL\n        if (intercept) beta0=rep(meany,nstep)-coef%*%meanx else beta0=rep(0,nstep)\n        L1norm=rowSums(abs(coef))\n        norm.frac=L1norm/max(L1norm)\n        obj=list(beta0=beta0,coef=coef,lambdas=lambdas,L1norm=L1norm,norm.frac=norm.frac,lambda.iter=lambda.iter,of.value=of.value,normx=normx,se=se)\n        class(obj)='nnlasso'\n        return(obj)\n}\n\nnnlasso.normal.lambda<-function(n,p,x,y,xpx,xpy,beta.old,tau,lambda1,tol,maxiter,xbeta.old,eps,SE=FALSE)\n{\n        epp=0.001\n        if (n<=p) tx=t(x)\n        ofv.old=-sum((y-xbeta.old)^2)/2-lambda1*(tau*sum(beta.old)+(1-tau)*sum(beta.old^2))\n        for (iter in 1:maxiter)\n        {\n                if (n>p)\n                {\n                        xpxbetaold=xpx%*%beta.old\n                } else xpxbetaold=tx%*%xbeta.old\n                g1minus<-g1<-xpy-xpxbetaold\n                g1minus[which(g1>0)]=0\n                b=beta.old*(g1-lambda1*tau-2*lambda1*(1-tau)*beta.old)/(lambda1*tau+2*lambda1*(1-tau)*beta.old-g1minus+1e-16)\n                beta.new=beta.old+b\n                xb=x%*%b\n                xbeta.new=xbeta.old+xb\n                ofv.new=-sum((y-xbeta.new)^2)/2-lambda1*(tau*sum(beta.new)+(1-tau)*sum(beta.new^2))\n                delta=1\n                t1=epp*(sum(g1*b))\n                while (ofv.new-delta*t1<ofv.old & delta>1e-5)\n                {\n                        delta=delta/2\n                        beta.new=beta.old+delta*b\n                        xbeta.new=xbeta.old+delta*xb\n                        ofv.new=-sum((y-xbeta.new)^2)/2-lambda1*(tau*sum(beta.new)+(1-tau)*sum(beta.new^2))\n                }\n                if (ofv.new-delta*t1<ofv.old & delta<=1e-5)\n                {\n                        beta.new=beta.old\n                        ofv.new=ofv.old\n                        xbeta.new=xbeta.old\n                        break\n                }\n                if(abs(ofv.old-ofv.new)<=tol) break\n                beta.old=beta.new\n                xbeta.old=xbeta.new\n                ofv.old=ofv.new\n        }\n        if (iter<maxiter) conv=\"yes\" else conv=\"no\"\n        if (SE==TRUE & conv==\"yes\")\n        {\n                grad=xpy-t(x)%*%xbeta.new-lambda1*tau-2*lambda1*(1-tau)*beta.new\n                Finv<-F<-xpx+2*lambda1*(1-tau)\n                index=which(beta.new<=eps & grad< -1e-2)\n                if (length(index)>0)\n                {\n                        temp=F[-index,-index]\n                        tempinv=solve(temp)\n                        indexc=setdiff(1:p,index)\n                        if (length(indexc)>0) Finv[indexc,indexc]=tempinv\n                        Finv[index,index]=0\n                } else Finv=solve(F)\n                vc=Finv%*%F\n                vcov=vc%*%t(Finv)\n        } else vcov=NULL\n        res=list(beta.new=beta.new,conv=conv,iter=iter,ofv.new=ofv.new,xbeta.new=xbeta.new,vcov=vcov)\n        return(res)\n}\n*/\n\n#endif\n", "meta": {"hexsha": "1ff5d7cbc3b5126510e978da1df8bdbc45efd40a", "size": 34244, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Code/4_Find_IntraDomain_Interaction/findIntraDomainInteraction.cpp", "max_stars_repo_name": "Lan-lab/Chrom-Lasso-", "max_stars_repo_head_hexsha": "3b1c7797bfdf0f7d3330339ace0929e8e2225a40", "max_stars_repo_licenses": ["MIT"], "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/4_Find_IntraDomain_Interaction/findIntraDomainInteraction.cpp", "max_issues_repo_name": "Lan-lab/Chrom-Lasso-", "max_issues_repo_head_hexsha": "3b1c7797bfdf0f7d3330339ace0929e8e2225a40", "max_issues_repo_licenses": ["MIT"], "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/4_Find_IntraDomain_Interaction/findIntraDomainInteraction.cpp", "max_forks_repo_name": "Lan-lab/Chrom-Lasso-", "max_forks_repo_head_hexsha": "3b1c7797bfdf0f7d3330339ace0929e8e2225a40", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-10-15T09:15:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-07T02:16:27.000Z", "avg_line_length": 33.4740957967, "max_line_length": 503, "alphanum_fraction": 0.5529143792, "num_tokens": 9402, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186787341014, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4700435233876181}}
{"text": "#include \"ModuleSetList.h\"\n\n#include <iostream>\n#include <algorithm>\n#include <boost/lambda/lambda.hpp>\n\nusing namespace boost::lambda;\n\nnamespace hydla {\nnamespace hierarchy {\n\nModuleSetList::ModuleSetList()\n{}\n\nModuleSetList::ModuleSetList(ModuleSet m) :\n  ModuleSetContainer(m)\n{}\n\nModuleSetList::~ModuleSetList()\n{}\n\nvoid ModuleSetList::add_parallel(ModuleSetList& parallel_module_set_list) \n{\n\n  // parallel(X, Y) = X \u222a Y \u222a {x \u222a y | x\u2208X, y\u2208Y}\n  // Y\n  module_set_set_t new_list(full_module_set_set_);\n    \n  // X\n  for (auto p_it : parallel_module_set_list.full_module_set_set_)\n  {\n    new_list.insert(p_it);\n  }\n\n  // {x \u222a y | x\u2208X, y\u2208Y}\n  for (auto p_it : parallel_module_set_list.full_module_set_set_)\n  {\n    for (auto this_it : full_module_set_set_)\n    {\n      ModuleSet ms(this_it, p_it);\n      new_list.insert(ms);\n    }\n  }\n\n  full_module_set_set_.swap(new_list);\n  maximal_module_set_ = *full_module_set_set_.rbegin();\n}\n\nvoid ModuleSetList::add_required_parallel(ModuleSetList& parallel_module_set_list) \n{\n  // \u7a7a\u306e\u30e2\u30b8\u30e5\u30fc\u30eb\u96c6\u5408\u306e\u96c6\u5408\u3092\u7528\u610f\n  module_set_set_t new_list;\n\n  // {x \u222a y | x\u2208X, y\u2208Y}\n  for (auto p_it : parallel_module_set_list.full_module_set_set_)\n  {\n    for (auto this_it : full_module_set_set_)\n    {\n      ModuleSet ms(this_it, p_it);\n      new_list.insert(ms);\n    }\n  }\n\n  full_module_set_set_.swap(new_list);\n  maximal_module_set_ = *full_module_set_set_.rbegin();\n}\n\nvoid ModuleSetList::add_weak(ModuleSetList& weak_module_set_list) \n{\n  // ordered(X, Y) = Y \u222a {x \u222a y | x\u2208X, y\u2208Y}\n      \n  // Y\n  module_set_set_t new_list(full_module_set_set_);\n\n  ModuleSet y = *full_module_set_set_.rbegin();\n  // {x \u222a y | x\u2208X, y\u2208Y}\n  for (auto p_it : weak_module_set_list.full_module_set_set_)\n  {\n    ModuleSet ms(y, p_it);\n    new_list.insert(ms);\n  }\n\n  full_module_set_set_.swap(new_list);\n  maximal_module_set_ = *full_module_set_set_.rbegin();\n}\n\nvoid ModuleSetList::remove_included_ms_by_current_ms()\n{\n  ms_to_visit_.clear();\n}\n\nstd::ostream& ModuleSetList::dump(std::ostream& s) const\n{\n  dump_node_names(s);\n  s << \"\\n\";\n  dump_node_trees(s);\n\n  return s;\n}\n\nstd::ostream& ModuleSetList::dump_node_names(std::ostream& s) const\n{\n  module_set_set_t::const_iterator it  = full_module_set_set_.begin();\n  module_set_set_t::const_iterator end = full_module_set_set_.end();\n\n  s << \"{\";\n  if (it != end) s << (*(it++)).get_name();\n  while (it != end)\n  {\n    s << \", \" << (*(it++)).get_name();\n  }\n  s << \"}\";\n\n  return s;\n}\n\nstd::ostream& ModuleSetList::dump_node_trees(std::ostream& s) const\n{\n  module_set_set_t::const_iterator it  = full_module_set_set_.begin();\n  module_set_set_t::const_iterator end = full_module_set_set_.end();\n\n  s << \"{\";\n  if (it != end) s << *(it++);\n  while (it != end)\n  {\n    s << \", \" << *(it++);\n  }\n  s << \"}\";\n\n  return s;\n}\n\n} // namespace hierarchy\n} // namespace hydla\n", "meta": {"hexsha": "03648c82321e6bbeda4dfe8fa5cc5bbec20470b8", "size": 2823, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/hierarchy/ModuleSetList.cpp", "max_stars_repo_name": "takafumihoriuchi/HyLaGI", "max_stars_repo_head_hexsha": "26b9f32a84611ee62d9cbbd903773d224088c959", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-03-15T07:11:09.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-15T07:11:09.000Z", "max_issues_repo_path": "src/hierarchy/ModuleSetList.cpp", "max_issues_repo_name": "takafumihoriuchi/HyLaGI", "max_issues_repo_head_hexsha": "26b9f32a84611ee62d9cbbd903773d224088c959", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/hierarchy/ModuleSetList.cpp", "max_forks_repo_name": "takafumihoriuchi/HyLaGI", "max_forks_repo_head_hexsha": "26b9f32a84611ee62d9cbbd903773d224088c959", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.9111111111, "max_line_length": 83, "alphanum_fraction": 0.6719801629, "num_tokens": 852, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186787341014, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4700435233876181}}
{"text": "#include <Eigen/StdVector>\n#include <kdtreepp.hpp>\n#define CATCH_CONFIG_MAIN\n#include <catch2/catch.hpp>\n\nusing Vector2 = Eigen::Vector2d;\nusing Vector3 = Eigen::Vector3d;\nusing AlignedBox2 = Eigen::AlignedBox2d;\nusing AlignedBox3 = Eigen::AlignedBox3d;\n\nstatic void CHECK_VEC3_EQ(const Vector3& a, const Vector3& b) {\n  CHECK(a[0] == Approx(b[0]));\n  CHECK(a[1] == Approx(b[1]));\n  CHECK(a[2] == Approx(b[2]));\n}\n\nTEST_CASE(\"VERSION_STRING\") { REQUIRE(KDTREEPP_VERSION_STRING == std::string(\"1.0.0\")); }\n\nTEST_CASE(\"PointTreeTest\") {\n  // Build a k-d tree from a list of points\n\n  std::vector<Vector3, Eigen::aligned_allocator<Vector3>> points;\n  std::mt19937_64 randGen{size_t(42)};\n  std::uniform_real_distribution<double> dist{-1000.0, 1000.0};\n\n  // Make random points\n  constexpr size_t count = 1500;\n  points.resize(count);\n  for (auto& point : points) {\n    point << dist(randGen), dist(randGen), dist(randGen);\n  }\n\n  const auto node = kdtreepp::MakeEigenKdTreeNode<double, 3>(\n      points.begin(), points.end(), [](const Vector3& p) { return p; },\n      [](const Vector3& p) { return p; });\n\n  const Vector3 checkPoint{dist(randGen), dist(randGen), dist(randGen)};\n\n  // Find closest point via brute force search\n  double bruteMinDistSq = std::numeric_limits<double>::max();\n  Vector3 bruteClosestPoint;\n  for (const auto& point : points) {\n    const double rSq = (point - checkPoint).squaredNorm();\n    if (rSq < bruteMinDistSq) {\n      bruteMinDistSq = rSq;\n      bruteClosestPoint = point;\n    }\n  }\n\n  // Find closest point using kdtree\n  double minDistSq = std::numeric_limits<double>::max();\n  Vector3 closestPoint;\n  size_t numBoundsChecks = 0;\n  size_t numPointChecks = 0;\n  node.visit(\n      [&minDistSq, checkPoint, &numBoundsChecks](const AlignedBox3& bounds) {\n        ++numBoundsChecks;\n        return bounds.squaredExteriorDistance(checkPoint) < minDistSq;\n      },\n\n      [&minDistSq, &closestPoint, checkPoint, &numPointChecks](const Vector3& point) {\n        ++numPointChecks;\n        const double rSq = (point - checkPoint).squaredNorm();\n        if (rSq < minDistSq) {\n          minDistSq = rSq;\n          closestPoint = point;\n        }\n      });\n\n  CHECK_VEC3_EQ(bruteClosestPoint, closestPoint);\n  CHECK(numBoundsChecks < count);\n  CHECK(numPointChecks < count);\n\n  // Count points within a bounding box\n  AlignedBox3 searchBounds{Vector3{-500.0, -500.0, -500.0}, Vector3{500.0, 500.0, 500.0}};\n  size_t foundPoints = 0;\n  node.visit([&searchBounds](const AlignedBox3& bounds) { return searchBounds.intersects(bounds); },\n             [&searchBounds, &foundPoints](const Vector3& point) {\n               if (searchBounds.contains(point)) {\n                 ++foundPoints;\n               }\n             });\n\n  CHECK(foundPoints > count / 10);\n  CHECK(foundPoints < count / 2);\n}\n\nTEST_CASE(\"ModifyInPlace\") {\n  // Build a k-d tree from a list of points\n\n  std::vector<Vector2, Eigen::aligned_allocator<Vector2>> points;\n  std::mt19937_64 randGen{size_t(42)};\n  std::uniform_real_distribution<double> dist{0.1, 1.0};\n\n  // Make random points\n  constexpr size_t count = 100;\n  points.resize(count);\n  for (auto& point : points) {\n    point << dist(randGen), dist(randGen);\n  }\n\n  auto node = kdtreepp::MakeEigenKdTreeNode<double, 2>(\n      points.begin(), points.end(), [](const Vector2& p) { return p; },\n      [](const Vector2& p) { return p; });\n\n  size_t numBoundsChecks = 0;\n  size_t numPointChecks = 0;\n  node.visit(\n      [&numBoundsChecks](const AlignedBox2& bounds) {\n        (void)bounds;\n        ++numBoundsChecks;\n        return true;\n      },\n\n      [&numPointChecks](Vector2& point) {\n        ++numPointChecks;\n        point *= -1.0;\n      });\n\n  CHECK(numBoundsChecks < count);\n  CHECK(numPointChecks == count);\n\n  for (const auto& point : points) {\n    CHECK(point.x() < 0.0);\n    CHECK(point.y() < 0.0);\n  }\n}\n", "meta": {"hexsha": "0c87f675c6368b21493b57d148f3ad6056a49d4f", "size": 3857, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test.cpp", "max_stars_repo_name": "jhurliman/kdtreepp", "max_stars_repo_head_hexsha": "5fe3107219263f50069efd7c7dc8643b5dcc4d67", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-01-27T13:12:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-04T21:38:22.000Z", "max_issues_repo_path": "test/test.cpp", "max_issues_repo_name": "jhurliman/kdtreepp", "max_issues_repo_head_hexsha": "5fe3107219263f50069efd7c7dc8643b5dcc4d67", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test.cpp", "max_forks_repo_name": "jhurliman/kdtreepp", "max_forks_repo_head_hexsha": "5fe3107219263f50069efd7c7dc8643b5dcc4d67", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1328125, "max_line_length": 100, "alphanum_fraction": 0.6489499611, "num_tokens": 1093, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4700435177334622}}
{"text": "// Copyright 2017 Shunji Lin. All rights reserved.\n// Use of this source code is governed by an MIT-style\n// license that can be found in the LICENSE file.\n#include \"pointer_table.hpp\"\n#include <vector>\n#include <utility>\n#include <cstddef>\n#include <limits>\n#include <cmath>\n#include <climits>\n#include <stdexcept>\n#include <iostream>\n#include \"../utils/wall_timer.hpp\"\n\n// for primality testing\n#include <boost/multiprecision/miller_rabin.hpp>\n\nusing namespace std;\nusing namespace boost::multiprecision;\n\nconstexpr size_t size_t_bits = sizeof(size_t) * CHAR_BIT;\n\n// Note: bools in vectors take up 1 bit each\n// (max_entries * ptr_bits) == bits.size()\n\nPointerTable::PointerTable(size_t ptr_table_size_limit_in_bytes)\n{\n    utils::WallTimer timer;\n    size_t big_ptr_size_in_bits = get_ptr_size_in_bits(ptr_table_size_limit_in_bytes);\n    \n    // choose pointer that gives max table size in entries\n    size_t small_ptr_size_in_bits =\n        big_ptr_size_in_bits > 0 ? big_ptr_size_in_bits - 1 : 0;\n    \n    size_t big_ptr_entries = ptr_table_size_limit_in_bytes * 8 / big_ptr_size_in_bits;\n    size_t small_ptr_entries = pow(2, small_ptr_size_in_bits);\n    \n    for (; big_ptr_entries > 0; --big_ptr_entries) {\n        if (miller_rabin_test(big_ptr_entries, 25)) break;\n    }\n    for (; small_ptr_entries > 0; --small_ptr_entries) {\n        if (miller_rabin_test(small_ptr_entries, 25)) break;\n    }\n\n    size_t max_entries = 0;\n    if (big_ptr_entries > small_ptr_entries) {\n        ptr_size_in_bits = big_ptr_size_in_bits;\n        max_entries = big_ptr_entries;\n    } else {\n        ptr_size_in_bits = small_ptr_size_in_bits;\n        max_entries = small_ptr_entries;\n    }\n    \n    bit_vector.resize(ptr_size_in_bits * max_entries, true);\n\n    // invalid pointer representation: pointer with all bools set to true\n    invalid_ptr = numeric_limits<size_t>::max() >> (size_t_bits - ptr_size_in_bits);\n\n    // For logging purposes.\n    // Due to primality tests, initialization may take some time.\n    cout << \"Time taken to initialize pointer table: \" << timer << \"\\n\"\n         << \"Size of pointer in pointer table: \" << get_ptr_size_in_bits() << \" bits\\n\"\n         << \"Size of pointer table: \" << get_max_size_in_bytes() << \" bytes\\n\"\n         << \"Max entries of pointer table: \" << get_max_entries() << endl;\n}\n\n// Returns the biggest pointer size, may not be optimal in terms of size of\n// pointer table.\nsize_t PointerTable::get_ptr_size_in_bits(size_t ptr_table_size_limit_in_bytes) const {\n    size_t ptr_size_in_bits = 0;\n    auto max_ptr_bits = size_t_bits;\n    for (size_t ptr_sz = 0; ptr_sz < max_ptr_bits; ++ptr_sz) {\n\tsize_t total_ptr_table_bits = ptr_sz * pow(2, ptr_sz);\n\tif (total_ptr_table_bits >= (ptr_table_size_limit_in_bytes * CHAR_BIT)) {\n\t    ptr_size_in_bits = ptr_sz;\n\t    break;\n\t}\n    }\n    return ptr_size_in_bits;\n}\n\nsize_t PointerTable::get_ptr_at_index(size_t index) const {\n    size_t pointer = 0;\n    size_t bit_index = index * ptr_size_in_bits; // actual offset\n    for (size_t i = 0; i < ptr_size_in_bits; ++i) {\n\tpointer <<= 1;\n\tif (bit_vector[bit_index]) pointer |= 1;\n\t++bit_index;\n    }\n    return pointer;\n}\n\nvoid PointerTable::insert_ptr_at_index(size_t pointer, size_t index) {\n    if (get_n_entries() == get_max_entries())\n        throw runtime_error(\"Attempting to insert in full pointer table\");\n    // go to last bit of the entry at index\n    size_t bit_index = ((index + 1) * ptr_size_in_bits) - 1;\n    // insert from last bit to first bit\n    for (size_t i = 0; i < ptr_size_in_bits; ++i) {\n\tif (!(pointer & 1)) bit_vector[bit_index] = false;\n\tpointer >>= 1;\n\t--bit_index;\n    }\n    ++n_entries;\n}\n\nbool PointerTable::ptr_is_invalid(size_t ptr) const {\n    return ptr == invalid_ptr;\n}\n\nvoid PointerTable::insert_ptr_with_hash(size_t pointer,\n                               size_t hash_value,\n                               size_t probe_value) {\n    auto max_entries = get_max_entries();\n    size_t probe_index = hash_value % max_entries;\n    while (!ptr_is_invalid(get_ptr_at_index(probe_index))) {\n\tprobe_index =\n             (probe_index + (probe_value % max_entries)) % max_entries; \n    }\n    insert_ptr_at_index(pointer, probe_index);\n}\n\nsize_t PointerTable::get_ptr_with_hash(size_t hash_value,\n                               size_t probe_value,\n                               bool first_probe) const {\n    auto max_entries = get_max_entries();\n    if (first_probe) {\n\tcurrent_probe_index = hash_value % max_entries;\n    } else {\n        current_probe_index =\n            (current_probe_index + (probe_value % max_entries)) % max_entries; \n    }\n    return get_ptr_at_index(current_probe_index);\n}\n\nsize_t PointerTable::get_n_entries() const {\n    return n_entries;\n}\n\nsize_t PointerTable::get_max_entries() const {\n    return bit_vector.size() / ptr_size_in_bits;\n}\n\nsize_t PointerTable::get_max_size_in_bytes() const {\n    return bit_vector.size() / 8;\n}\n\nsize_t PointerTable::get_ptr_size_in_bits() const {\n    return ptr_size_in_bits;\n}\n\ndouble PointerTable::get_load_factor() const {\n    return static_cast<double>(get_n_entries()) /\n        static_cast<double>(get_max_entries());\n}\n\n\n", "meta": {"hexsha": "a84293df3f4522a99b66b98dca47dc07a5ca4098", "size": 5150, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/compress/pointer_table.cc", "max_stars_repo_name": "shunjilin/15PuzzleExternalMemorySearch", "max_stars_repo_head_hexsha": "0a6044d712c2e3bad17f801e9eb82466a354e24d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2017-11-21T20:22:07.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-22T12:08:40.000Z", "max_issues_repo_path": "src/compress/pointer_table.cc", "max_issues_repo_name": "shunjilin/15PuzzleExternalMemorySearch", "max_issues_repo_head_hexsha": "0a6044d712c2e3bad17f801e9eb82466a354e24d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2017-12-05T09:17:21.000Z", "max_issues_repo_issues_event_max_datetime": "2018-04-13T07:01:11.000Z", "max_forks_repo_path": "src/compress/pointer_table.cc", "max_forks_repo_name": "shunjilin/15PuzzleExternalMemorySearch", "max_forks_repo_head_hexsha": "0a6044d712c2e3bad17f801e9eb82466a354e24d", "max_forks_repo_licenses": ["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.5949367089, "max_line_length": 87, "alphanum_fraction": 0.6881553398, "num_tokens": 1282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4700435177334622}}
{"text": "//\n// Created by Hao Wu on 11/7/16.\n//\n\n#include <iostream>\n#include \"ROWPlus/ROWPlus.h\"\n#include \"lorenz96.h\"\n#include <boost/numeric/odeint.hpp>\n\nusing namespace Eigen;\nusing namespace ROWPlus;\nusing namespace boost::numeric::odeint;\nusing namespace std;\n\ntemplate<typename vec>\nvoid initX(vec& x, size_t N) {\n  for (int i = 0; i < N; ++i)\n    x[i] = 0.5 * ((double) i - 0.5 * (double) N);\n}\n\nint main() {\n  const double t1 = 3.0;\n\n  lorenz96 fun;\n\n  std::cout << \"Lorenz-96 (N=40)\" << std::endl;\n\n  lorenz96::state_type x_ref(40);\n  initX(x_ref, 40);\n  typedef runge_kutta_cash_karp54<lorenz96::state_type> error_stepper_type;\n  integrate_adaptive(make_controlled<error_stepper_type>(1.0e-12, 1.0e-12),\n                     fun, x_ref, 0.0, t1, 1e-8 );\n\n  // initialize solution vectors\n  lorenz96::state_type x_t1(40);\n  VectorXd x_t2(40);\n\n  // creat solver: runge_kutta4_classic\n  runge_kutta4_classic< lorenz96::state_type > stepper_rk4;\n  // create solver: ROWPlus::rosenbrock4\n  ROWPlus::rosenbrock4<lorenz96, double> stepper_grk4t;\n  stepper_grk4t.makeConstantStepper(&fun);\n  // creat solver: rosenbrock_krylov4 ROK4A\n  rosenbrock_krylov4<lorenz96, double> stepper_rok4a(4);\n  ODEOptions<double> &_opts = stepper_rok4a.getOptions();\n  _opts.TypeScheme = ROK4A;\n  stepper_rok4a.makeConstantStepper(&fun);\n  // creat solver: rosenbrock_krylov4 ROK4E\n  rosenbrock_krylov4<lorenz96, double> stepper_rok4e(4);\n  stepper_rok4e.makeConstantStepper(&fun);\n\n  //\n  double dt = 0.05;\n  while (dt >= 5e-5) {\n    ROWPlusSolverSpace::Status ret;\n    cout << dt << \" \";\n    // stepper_rk54\n    initX(x_t1, 40);\n    integrate_const( stepper_rk4 , fun , x_t1 , 0.0 , t1 , dt );\n    Map<VectorXd>(x_t1.data(), 40) -= Map<VectorXd>(x_ref.data(), 40);\n    cout << Map<VectorXd>(x_t1.data(), 40).stableNorm() /\n            Map<VectorXd>(x_ref.data(), 40).stableNorm() << \" \";\n    // stepper_grk4t\n    initX(x_t2, 40);\n    ret = stepper_grk4t.step(x_t2, 0.0, t1, dt);\n    if (ret != ROWPlusSolverSpace::ComputeSucessful) {\n      cout << \"STAT = \" << ret << endl;\n      return 1;\n    }\n    x_t2 -= Map<VectorXd>(x_ref.data(), 40);\n    cout << x_t2.stableNorm() /\n        Map<VectorXd>(x_ref.data(), 40).stableNorm() << \" \";\n    // stepper_rok4a\n    initX(x_t2, 40);\n    ret = stepper_rok4a.step(x_t2, 0.0, t1, dt);\n    if (ret != ROWPlusSolverSpace::ComputeSucessful) {\n      cout << \"STAT = \" << ret << endl;\n      return 1;\n    }\n    x_t2 -= Map<VectorXd>(x_ref.data(), 40);\n    cout << x_t2.stableNorm() /\n        Map<VectorXd>(x_ref.data(), 40).stableNorm() << \" \";\n    // stepper_rok4e\n    initX(x_t2, 40);\n    ret = stepper_rok4e.step(x_t2, 0.0, t1, dt);\n    if (ret != ROWPlusSolverSpace::ComputeSucessful) {\n      cout << \"STAT = \" << ret << endl;\n      return 1;\n    }\n    x_t2 -= Map<VectorXd>(x_ref.data(), 40);\n    cout << x_t2.stableNorm() /\n        Map<VectorXd>(x_ref.data(), 40).stableNorm() << \" \";\n\n    cout << endl;\n    dt /= 2.0;\n  }\n  return 0;\n}", "meta": {"hexsha": "e4f1afe5aeba6f5487a6c940e18392d3b9fc69df", "size": 2956, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/Lorenz_96/main.cpp", "max_stars_repo_name": "IhmeGroup/ROWPlus", "max_stars_repo_head_hexsha": "5c6b36bf68ce8702e22956aa2c23cdc2a297192c", "max_stars_repo_licenses": ["Apache-2.0"], "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/Lorenz_96/main.cpp", "max_issues_repo_name": "IhmeGroup/ROWPlus", "max_issues_repo_head_hexsha": "5c6b36bf68ce8702e22956aa2c23cdc2a297192c", "max_issues_repo_licenses": ["Apache-2.0"], "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/Lorenz_96/main.cpp", "max_forks_repo_name": "IhmeGroup/ROWPlus", "max_forks_repo_head_hexsha": "5c6b36bf68ce8702e22956aa2c23cdc2a297192c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-10-25T22:41:59.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-25T22:41:59.000Z", "avg_line_length": 30.1632653061, "max_line_length": 75, "alphanum_fraction": 0.6302435724, "num_tokens": 1044, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867729389247, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.47004351490638424}}
{"text": "/* test_geometric_distribution.cpp\n *\n * Copyright Steven Watanabe 2011\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#include <boost/random/geometric_distribution.hpp>\n\n#define BOOST_RANDOM_DISTRIBUTION boost::random::geometric_distribution<>\n#define BOOST_RANDOM_ARG1 p\n#define BOOST_RANDOM_ARG1_DEFAULT 0.5\n#define BOOST_RANDOM_ARG1_VALUE 0.25\n\n#define BOOST_RANDOM_DIST0_MIN 0\n#define BOOST_RANDOM_DIST0_MAX (std::numeric_limits<int>::max)()\n#define BOOST_RANDOM_DIST1_MIN 0\n#define BOOST_RANDOM_DIST1_MAX (std::numeric_limits<int>::max)()\n\n#define BOOST_RANDOM_TEST1_PARAMS (0.9999)\n#define BOOST_RANDOM_TEST1_MIN 0\n#define BOOST_RANDOM_TEST1_MAX 0\n\n#define BOOST_RANDOM_TEST2_PARAMS (0.0001)\n#define BOOST_RANDOM_TEST2_MIN 1\n\n#include \"test_distribution.ipp\"\n", "meta": {"hexsha": "bb54d02590bf4a7c086ce234f1aa2df16e60d6aa", "size": 894, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/random/test/test_geometric_distribution.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "boost/libs/random/test/test_geometric_distribution.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "boost/libs/random/test/test_geometric_distribution.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 27.9375, "max_line_length": 73, "alphanum_fraction": 0.8042505593, "num_tokens": 228, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186768138228, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4700435120793061}}
{"text": "#include \"imu.h\"\n#include \"global_config.h\"\n#include \"SPI.h\"\n#include \"ricardo_pins.h\"\n#include \"Storage/systemstatus.h\"\n#include \"Storage/logController.h\"\n#include \"flags.h\"\n#include \"SparkFunLSM9DS1.h\"\n\n#include \"sensorStructs.h\"\n\n#include \"Preferences.h\"\n\n\n#include <Eigen/Core>\n\n\n\n\nImu::Imu(SPIClass* spi, SystemStatus* systemstatus,LogController* logcontroller,raw_measurements_t* raw_data):\n    _spi(spi),\n    _systemstatus(systemstatus),\n    _logcontroller(logcontroller),\n    imu(spi),\n    _raw_data(raw_data),\n    _magCal{1,\n           0,\n           0,\n           Eigen::Matrix3f{{1,0,0},{0,1,0},{0,0,1}},\n           Eigen::Vector3f{{0,0,0}}} // default for mag biases\n{};\n\n\n\n\n\nvoid Imu::setup(){\n\n    imu.setAccelScale(ACCEL_SCALE);\n    //set samplerate of accel to 476Hz\n    imu.settings.accel.sampleRate = 5;\n    imu.settings.accel.enabled = true; // Enable accelerometer\n    \n    imu.setGyroScale(GYRO_SCALE);\n    //set samplerate of gyro to 476Hz\n    imu.settings.gyro.sampleRate = 5;\n    imu.settings.gyro.lowPowerEnable = false;\n    //imu.settings.accel.enabled = false; // Enable accelerometer\n    // [HPFEnable] enables or disables the high-pass filter\n    //imu.settings.gyro.HPFEnable = true; // HPF disabled\n    // [HPFCutoff] sets the HPF cutoff frequency (if enabled)\n    // Allowable values are 0-9. Value depends on ODR.\n    // (Datasheet section 7.14)\n    //imu.settings.gyro.HPFCutoff = 1; // HPF cutoff = 4Hz\n\n    imu.setMagScale(MAG_SCALE);\n    //imu.setMagScale(12);\n    imu.settings.mag.XYPerformance = 3; // Ultra-high perform.\n    imu.settings.mag.ZPerformance = 3; // Ultra-high perform.\n    imu.settings.mag.sampleRate = 7;\n    imu.settings.mag.lowPowerEnable = false;\n    imu.settings.mag.operatingMode = 0; // Continuous mode\n    //mag temp compensation -> this is a good thing right?\n    imu.settings.mag.tempCompensationEnable = true;\n\n    loadAccelGyroBias(); //load previously callibrated bias values from nvs\n    loadMagCal(); //load mag calibration coefficents from nvs\n\n    if (!imu.beginSPI(_SCLK,_MISO,_MOSI,ImuCs, MagCs)){\n        _systemstatus->new_message(SYSTEM_FLAG::ERROR_IMU, \"Unable to initialize the imu\");\n        return;\n    };\n    _logcontroller->log(\"IMU Initialized\");\n\n};\n\n\nvoid Imu::update(){\n\n    read_gyro();\n    read_accel();\n    read_mag();\n    read_temp();\n       \n   \n\n};\n\nvoid Imu::read_gyro(){\n    imu.readGyro(); //degrees per second\n    _raw_data->gx = imu.calcGyro(imu.gx);\n    _raw_data->gy = -imu.calcGyro(imu.gy);\n    _raw_data->gz = imu.calcGyro(imu.gz);\n\n}\nvoid Imu::read_accel(){\n\n    imu.readAccel();//g's\n    _raw_data->ax = imu.calcAccel(imu.ax);\n    _raw_data->ay = -imu.calcAccel(imu.ay);\n    _raw_data->az = imu.calcAccel(imu.az);\n }\nvoid Imu::read_mag(){\n    imu.readMag(); \n    //Gauss\n    float mx = -imu.calcMag(imu.mx);\n    float my = -imu.calcMag(imu.my);\n    float mz = imu.calcMag(imu.mz);\n    Eigen::Vector3f corrected_mag = _magCal.A_1*(Eigen::Vector3f{{mx,my,mz}} - _magCal.b);\n    _raw_data->mx = corrected_mag[0];\n    _raw_data->my = corrected_mag[1];\n    _raw_data->mz = corrected_mag[2];\n    \n\n}\nvoid Imu::read_temp(){\n    imu.readTemp();\n    _raw_data->imu_temp = imu.temperature;\n}\n\nvoid Imu::calibrateAccelGyroBias(bool autocalc){\n    //4.56 0.76 0.45 521 87 51\n    imu.calibrate(autocalc);\n    writeAccelGyroBias(); // write bias offsets to nvs\n    _logcontroller->log(\"IMU accel gyro bias callibration complete\");\n}\n\nvoid Imu::calibrateMagBias(bool loadIn){ // simple bias correction. \n    imu.calibrateMag(loadIn);\n    _logcontroller->log(\"IMU simple mag bias callibration complete\");\n}\n\nvoid Imu::calibrateMagFull(MagCalibrationParameters magCal) \n{\n    _magCal = magCal;\n    writeMagCal();\n}\n\nvoid Imu::writeAccelGyroBias(){\n    Preferences pref;\n\n    if (!pref.begin(\"IMU\")){\n        _logcontroller->log(\"nvs failed to start. Can't write calbration offsets\");\n        return;\n    }   \n    //dont have time to write a new library for this\n    //i dont like the way we cant log the errors to our log file as the error handling\n    //is wrapped up in the preferences class\n    // it shouldnt be too hard to rewrite at a later date\n    if (!pref.putShort(\"gxBias\",imu.gBiasRaw[0])){_logcontroller->log(\"nvs error while writing\");};\n    if (!pref.putShort(\"gyBias\",imu.gBiasRaw[1])){_logcontroller->log(\"nvs error while writing\");};\n    if (!pref.putShort(\"gzBias\",imu.gBiasRaw[2])){_logcontroller->log(\"nvs error while writing\");};\n    if (!pref.putShort(\"axBias\",imu.aBiasRaw[0])){_logcontroller->log(\"nvs error while writing\");};\n    if (!pref.putShort(\"ayBias\",imu.aBiasRaw[1])){_logcontroller->log(\"nvs error while writing\");};\n    if (!pref.putShort(\"azBias\",imu.aBiasRaw[2])){_logcontroller->log(\"nvs error while writing\");};\n    //preferences end is called in destructor of preference class  as it goes out of scope\n\n}\n\nvoid Imu::loadAccelGyroBias(){\n    Preferences pref;\n\n    if (!pref.begin(\"IMU\",true)){\n        _logcontroller->log(\"nvs failed to start\");\n        return;\n    }  \n\n    imu.gBiasRaw[0] = pref.getShort(\"gxBias\");\n    imu.gBiasRaw[1] = pref.getShort(\"gyBias\");\n    imu.gBiasRaw[2] = pref.getShort(\"gzBias\");\n    imu.aBiasRaw[0] = pref.getShort(\"axBias\");\n    imu.aBiasRaw[1] = pref.getShort(\"ayBias\");\n    imu.aBiasRaw[2] = pref.getShort(\"azBias\");\n\n\n}\n\nvoid Imu::writeMagCal() \n{\n    Preferences pref;\n\n    if (!pref.begin(\"IMU\")){\n        _logcontroller->log(\"nvs failed to start. Can't write calbration offsets\");\n        return;\n    }   \n\n    if (!pref.putFloat(\"F\",_magCal.fieldMagnitude)){_logcontroller->log(\"nvs error while writing\");};\n    if (!pref.putFloat(\"I\",_magCal.inclination)){_logcontroller->log(\"nvs error while writing\");};\n    if (!pref.putFloat(\"D\",_magCal.declination)){_logcontroller->log(\"nvs error while writing\");};\n    if (!pref.putFloat(\"A11\",_magCal.A_1(0,0))){_logcontroller->log(\"nvs error while writing\");};\n    if (!pref.putFloat(\"A12\",_magCal.A_1(0,1))){_logcontroller->log(\"nvs error while writing\");};\n    if (!pref.putFloat(\"A12\",_magCal.A_1(0,2))){_logcontroller->log(\"nvs error while writing\");};\n    if (!pref.putFloat(\"A21\",_magCal.A_1(1,0))){_logcontroller->log(\"nvs error while writing\");};\n    if (!pref.putFloat(\"A22\",_magCal.A_1(1,1))){_logcontroller->log(\"nvs error while writing\");};\n    if (!pref.putFloat(\"A22\",_magCal.A_1(1,2))){_logcontroller->log(\"nvs error while writing\");};\n    if (!pref.putFloat(\"A31\",_magCal.A_1(2,0))){_logcontroller->log(\"nvs error while writing\");};\n    if (!pref.putFloat(\"A32\",_magCal.A_1(2,1))){_logcontroller->log(\"nvs error while writing\");};\n    if (!pref.putFloat(\"A32\",_magCal.A_1(2,2))){_logcontroller->log(\"nvs error while writing\");};\n    if (!pref.putFloat(\"b1\",_magCal.b(0))){_logcontroller->log(\"nvs error while writing\");};\n    if (!pref.putFloat(\"b2\",_magCal.b(1))){_logcontroller->log(\"nvs error while writing\");};\n    if (!pref.putFloat(\"b3\",_magCal.b(2))){_logcontroller->log(\"nvs error while writing\");};\n    \n \n\n}\n\nvoid Imu::loadMagCal() \n{\n    Preferences pref;\n\n    if (!pref.begin(\"IMU\",true)){\n        _logcontroller->log(\"nvs failed to start\");\n        return;\n    }  \n\n    _magCal.fieldMagnitude = pref.getFloat(\"F\",1);\n    _magCal.inclination = pref.getFloat(\"I\",0);\n    _magCal.declination = pref.getFloat(\"D\",0);\n\n    _magCal.A_1 << pref.getFloat(\"A11\",1),pref.getFloat(\"A12\",0),pref.getFloat(\"A13\",0),\n                   pref.getFloat(\"A21\",0),pref.getFloat(\"A22\",1),pref.getFloat(\"A23\",0),\n                   pref.getFloat(\"A31\",0),pref.getFloat(\"A32\",0),pref.getFloat(\"A33\",1);\n\n    _magCal.b << pref.getFloat(\"b1\",0),pref.getFloat(\"b2\",0),pref.getFloat(\"b3\",0);\n}", "meta": {"hexsha": "78c1496d975b545946df934acb2321953f1d9e5d", "size": 7606, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Ricardo_OS/Ricardo_OS/src/Sensors/imu.cpp", "max_stars_repo_name": "icl-rocketry/Avionics", "max_stars_repo_head_hexsha": "4fadbccb1cafe4be80c76e15a2546bbb8414398b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2020-01-28T18:35:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-20T13:34:25.000Z", "max_issues_repo_path": "Ricardo_OS/Ricardo_OS/src/Sensors/imu.cpp", "max_issues_repo_name": "icl-rocketry/Avionics", "max_issues_repo_head_hexsha": "4fadbccb1cafe4be80c76e15a2546bbb8414398b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2022-02-15T08:29:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-28T02:13:06.000Z", "max_forks_repo_path": "Ricardo_OS/Ricardo_OS/src/Sensors/imu.cpp", "max_forks_repo_name": "icl-rocketry/Avionics", "max_forks_repo_head_hexsha": "4fadbccb1cafe4be80c76e15a2546bbb8414398b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-06T05:20:51.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-06T05:20:51.000Z", "avg_line_length": 33.8044444444, "max_line_length": 110, "alphanum_fraction": 0.6605311596, "num_tokens": 2274, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186768138228, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4700435120793061}}
{"text": "#include <random>\n#include <boost/math/constants/constants.hpp>\n\n#include <a4wd2/toolkit/waypoint_generators.h>\n\nusing mrpt::nav::TWaypoint;\nusing mrpt::nav::TWaypointSequence;\n\nstatic constexpr double PI = boost::math::constants::pi<double>();\n\nnamespace a4wd2::toolkit\n{\n\nTWaypointSequence uniform_random_waypoint_generator::operator()(\n        const odometry_provider& odometry_provider) const\n{\n    m_logger->debug(\"Request for new waypoint\");\n\n    std::random_device rd;\n    std::mt19937 gen(rd());\n    std::uniform_real_distribution<> distance_sample(1., 3.0);\n    std::uniform_real_distribution<> theta_sample(-PI, PI);\n\n    mrpt::math::TPose2D pose;\n    mrpt::math::TTwist2D twist;\n    bool have_odometry = odometry_provider.get_odometry(pose, twist);\n\n    if (have_odometry)\n    {\n        double theta = theta_sample(gen);\n        double distance = distance_sample(gen);\n\n        double x = pose.x + distance * std::cos(theta);\n        double y = pose.y + distance * std::sin(theta);\n\n        TWaypointSequence waypoints;\n        waypoints.waypoints = {TWaypoint(x, y, 0.1, false, theta)};\n\n        m_logger->info(\"New waypoint distance: {}, theta: {}\", distance, theta);\n        m_logger->info(\"Current pose: x: {}, y: {}\", pose.x, pose.y);\n        m_logger->info(\"New waypoint list: x: {}, y: {}, theta: {}\", x, y, theta);\n        return waypoints;\n    }\n    else\n    {\n        m_logger->warn(\"Don't have odometry, returning empty waypoint list\");\n        return TWaypointSequence{};\n    }\n}\n\n}  // namespace a4wd2::toolkit\n", "meta": {"hexsha": "f8f810f8866a0a7b45f22e7b30bacc40ee98dea8", "size": 1535, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/toolkit/waypoint_generators.cpp", "max_stars_repo_name": "lsolanka/a4wd2", "max_stars_repo_head_hexsha": "886becb2191e27bd628c6cfe831b7155946759e8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-03T22:02:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-03T22:02:11.000Z", "max_issues_repo_path": "src/toolkit/waypoint_generators.cpp", "max_issues_repo_name": "lsolanka/a4wd2", "max_issues_repo_head_hexsha": "886becb2191e27bd628c6cfe831b7155946759e8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/toolkit/waypoint_generators.cpp", "max_forks_repo_name": "lsolanka/a4wd2", "max_forks_repo_head_hexsha": "886becb2191e27bd628c6cfe831b7155946759e8", "max_forks_repo_licenses": ["BSD-3-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.5192307692, "max_line_length": 82, "alphanum_fraction": 0.6560260586, "num_tokens": 395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256631249077, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.4700139922469132}}
{"text": "/* Copyright (C) 2012-2017 IBM Corp.\n * This program is Licensed under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *   http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License. See accompanying LICENSE file.\n */\n/* blockMatmul1D.cpp - Data-movement operations on arrays of slots\n */\n#include <algorithm>\n#include <NTL/BasicThreadPool.h>\n#include \"matmul.h\"\n\n// A class that implements the basic (sparse) 1D matrix-vector functions\ntemplate<class type> class blockMatmul1D_impl {\n  PA_INJECT(type)\n  const MatrixCacheType buildCache;\n  std::unique_ptr<CachedzzxMatrix> zCache;\n  std::unique_ptr<CachedDCRTMatrix> dCache;\n\n  BlockMatMul<type>& mat;\n  const EncryptedArrayDerived<type>& ea;\n\npublic:\n  blockMatmul1D_impl(MatMulBase& _mat, MatrixCacheType tag, long dim)\n    : buildCache(tag), mat(dynamic_cast< BlockMatMul<type>& >(_mat)),\n      ea(_mat.getEA().getDerived(type()))\n  {\n    long n = ea.sizeOfDimension(dim) * ea.getDegree();\n    if (buildCache==cachezzX)\n      zCache.reset(new CachedzzxMatrix(NTL::INIT_SIZE, n));\n    else if (buildCache==cacheDCRT)\n      dCache.reset(new CachedDCRTMatrix(NTL::INIT_SIZE, n));\n  }\n\n  // Extract one \"column\" from a matrix that was built with buildLinPolyCoeffs\n  bool shiftedColumnInDiag(zzX& zpoly, long f,\n                           const std::vector< std::vector<RX> >& diag)\n  {\n    // extract \"column\" with index f and store it in cvev\n    bool zero = true;\n    vector<RX> cvec(ea.size());\n    for (long j = 0; j < ea.size(); j++) {\n      cvec[j] = diag[j][f];\n      if (!NTL::IsZero(cvec[j])) zero = false;\n    }\n    if (zero) { // all are zeros\n      zpoly.kill();\n      return true;\n    }\n    ea.encode(zpoly, cvec);\n\n    if (f>0) {\n      long p = ea.getContext().zMStar.getP();\n      long m = ea.getContext().zMStar.getM();\n      long d = ea.getDegree();\n      long exp = PowerMod(mcMod(p, m), d-f, m); // apply inverse automorphism\n      const auto& F = ea.getTab().getPhimXMod();\n      RX rpoly1, rpoly2;\n\n      convert(rpoly1, zpoly);\n      plaintextAutomorph(rpoly2,rpoly1, exp, m, F);\n      convert(zpoly, rpoly2);\n    }\n    return false;\n  }\n\n  // Process a single block diagonal with index idx along dimenssion dim,\n  // making calls to the get(i,j) method and storing the result in\n  // the diag matrix (# of vectors = extenssion-degree).\n  bool processDiagonal1(std::vector< std::vector<RX> >& diag,\n\t\t\tlong dim, long i, long D, long d)\n  {\n    bool zDiag = true; // is this a zero diagonal?\n    long nzLast = -1;  // index of last non-zero entry\n\n    mat_R entry(INIT_SIZE, d, d);\n    std::vector<RX> entry1(d);\n    std::vector< std::vector<RX> > tmpDiag(D);\n\n    // Process the entries in this diagonal one at a time\n    for (long j = 0; j < D; j++) { // process entry j\n      bool zEntry = mat.get(entry, mcMod(j-i, D), j); // entry [j-i mod D, j]\n      // get(...) returns true if the entry is empty, false otherwise\n\n      if (!zEntry && IsZero(entry)) zEntry = true;// zero is an empty entry too\n      assert(zEntry || (entry.NumRows() == d && entry.NumCols() == d));\n\n      if (!zEntry) {   // not a zero entry\n        zDiag = false; // mark diagonal as non-empty\n\n\tfor (long jj = nzLast+1; jj < j; jj++) {// clear from last nonzero entry\n          tmpDiag[jj].assign(d, RX());\n        }\n        nzLast = j; // current entry is the last nonzero one\n\n        // recode entry as a vector of polynomials\n        for (long k = 0; k < d; k++) conv(entry1[k], entry[k]);\n\n        // compute the linearlized polynomial coefficients\n\tea.buildLinPolyCoeffs(tmpDiag[j], entry1);\n      }\n    }\n    if (zDiag) return true; // zero diagonal, nothing to do\n\n    // clear trailing zero entries\n    for (long jj = nzLast+1; jj < D; jj++) {\n      tmpDiag[jj].assign(d, RX());\n    }\n\n    if (D==1) diag.assign(ea.size(), tmpDiag[0]); // dimension of size one\n    else for (long j = 0; j < ea.size(); j++)\n           diag[j] = tmpDiag[ ea.coordinate(dim,j) ];\n           // rearrange the indexes based on the current dimension\n\n    return false; // a nonzero diagonal\n  }\n\n  // Process a single block diagonal with index idx along dimenssion dim,\n  // making calls to the multiGet(i,j,k) method and storing the result in\n  // the diag matrix (# of vectors = extenssion-degree).\n  bool processDiagonal2(std::vector< std::vector<RX> >& diag,\n\t\t\tlong dim, long idx, long D, long d)\n  {\n    bool zDiag = true; // is this a zero diagonal?\n    long nzLast = -1;  // index of last non-zero entry\n\n    mat_R entry(INIT_SIZE, d, d);\n    std::vector<RX> entry1(d);\n\n    // Get the slots in this diagonal one at a time\n    long blockIdx, rowIdx, colIdx;\n    for (long j = 0; j < ea.size(); j++) { // process entry j\n      if (dim == ea.dimension()) { // \"special\" last dimenssion of size 1\n\trowIdx = colIdx = 0; blockIdx=j;\n      } else {\n        std::tie(blockIdx, colIdx)\n\t  = ea.getContext().zMStar.breakIndexByDim(j, dim);\n\trowIdx = mcMod(colIdx-idx,D);\n      }\n      bool zEntry = mat.multiGet(entry,rowIdx,colIdx,blockIdx);\n      // entry [i,j-i mod D] in the block corresponding to blockIdx\n      // multiGet(...) returns true if the entry is empty, false otherwise\n\n      if (!zEntry && IsZero(entry)) zEntry=true; // zero is an empty entry too\n      assert(zEntry ||\n             (entry.NumRows() == d && entry.NumCols() == d));\n\n      if (!zEntry) {    // non-empty entry\n\tzDiag = false;  // mark diagonal as non-empty\n\n\tfor (long jj = nzLast+1; jj < j; jj++) {// clear from last nonzero entry\n\t  for (long k = 0; k < d; k++)\n\t    clear(diag[jj][k]);\n        }\n\tnzLast = j; // current entry is the last nonzero one\n\n\t// recode entry as a vector of polynomials\n\tfor (long k = 0; k < d; k++) conv(entry1[k], entry[k]);\n\n        // compute the linearlized polynomial coefficients\n\tea.buildLinPolyCoeffs(diag[j], entry1);\n      }\n    }\n    if (zDiag) return true; // zero diagonal, nothing to do\n\n    // clear trailing zero entries\n    for (long jj = nzLast+1; jj < ea.size(); jj++)\n      for (long k = 0; k < d; k++)\n\tclear(diag[jj][k]);\n\n    return false; // a nonzero diagonal\n  }\n\n  void multiply(Ctxt* ctxt, long dim, bool oneTransform) \n  {\n    assert(dim >= 0 && dim <= ea.dimension());\n    RBak bak; bak.save(); ea.getTab().restoreContext(); // backup NTL modulus\n\n    long nslots = ea.size();\n    long d = ea.getDegree();\n    long D = (dim == ea.dimension()) ? 1 : ea.sizeOfDimension(dim);\n\n    const PAlgebra& zMStar = ea.getContext().zMStar;\n    long p = zMStar.getP(); \n    long m = zMStar.getM();\n\n    std::vector< std::vector<RX> > diag(nslots); // scratch space\n    for (long j = 0; j < nslots; j++) diag[j].resize(d);\n\n    std::vector<Ctxt> acc;\n    std::unique_ptr<Ctxt> shCtxt;\n    if (ctxt!=nullptr) { // we need to do an actual multiplication\n      ctxt->cleanUp(); // not sure, but this may be a good idea\n      acc.assign(d, Ctxt(ZeroCtxtLike, *ctxt));\n      shCtxt.reset(new Ctxt(*ctxt));\n    }\n\n    // Check if we have the relevant constant in cache\n    CachedzzxMatrix* zcp;\n    CachedDCRTMatrix* dcp;\n    mat.getCache(&zcp, &dcp);\n\n    // Process the diagonals one at a time\n    for (long e = 0; e < D; e++) { // process diagonal e\n      bool zeroDiag = true;\n      // For each diagonal e, we update the d accumulators y_0,..,y_{d-1}\n      // with y_f += \\sigma^{-f}(\\lambda_{e,f}) * \\rho^e(x)\n\n      std::vector<zzX> zpoly(d, zzX());\n      std::vector<zzX*> zzxPtr(d,nullptr);\n      std::vector<DoubleCRT*> dcrtPtr(d,nullptr);\n\n      if (dcp!=nullptr) for (long f=0; f<d; f++) { // DoubleCRT cache exists\n          dcrtPtr[f] = (*dcp)[d*e +f].get();\n          if (dcrtPtr[f]!=nullptr) zeroDiag = false;\n      }\n      else if (zcp!=nullptr) for (long f=0; f<d; f++) {// zzX but no DoubleCRT\n          zzxPtr[f] = (*zcp)[d*e +f].get();\n          if (zzxPtr[f]!=nullptr) zeroDiag = false;\n      } else {\n       zeroDiag = oneTransform? this->processDiagonal1(diag, dim, e, D, d)\n                               : this->processDiagonal2(diag, dim, e, D, d);\n\n        // extract the \"columns\" from diag and encode them in zpoly\n        if (!zeroDiag) for (long f=0; f<d; f++) {\n          if (!shiftedColumnInDiag(zpoly[f], f, diag))// returns true on zero\n            zzxPtr[f] = &(zpoly[f]);\n        }\n      }\n      if (zeroDiag) continue; // nothing to do for this diagonal\n      // done preparing all the zzxPtr, dcrtPtr variables\n\n      // Rotate the ciphertext to position corresponding to diagonal e.\n      // The code below uses only rotate-by-one operations if this is\n      // a good dimenssion and the matrix is dense, hence it may require\n      // fewer key-switching matrices\n\n      if (ctxt!=nullptr) {\n\tif (e > 0) { // rotate the ciphertext\n          *shCtxt = *ctxt;\n          ea.rotate1D(*shCtxt, dim, e);\n\t} // if (e>0)\n\t// The implementation above incurs an extra mult-by-constant due\n\t// to the masks in rotate1D when applied in a \"bad dimension\".\n\t// These masks can be folded into the constants here, but then\n\t// we would need two constants for each (e,f) rather than one,\n\t// namely const*mask and const*(1-mask).\n\t// We should implement that optimization at some point.\n\n\t// Depending on zzxPtr, dcrtPtr, update the accumulated sums\n\tfor (long f=0; f<d; f++) if (dcrtPtr[f]!=nullptr || zzxPtr[f]!=nullptr) {\n            Ctxt tmp1(*shCtxt);\n            if (dcrtPtr[f] != nullptr) tmp1.multByConstant(*(dcrtPtr[f]));\n            else                    tmp1.multByConstant(*(zzxPtr[f]));\n            acc[f] += tmp1;\n          }\n      } // if (ctxt!=nullptr)\n \n      // allocate constants and store in the cache, if needed\n     if (buildCache==cachezzX) for (long f=0; f<d; f++) {\n          (*zCache)[d*e +f].reset( new zzX(*(zzxPtr[f])) );\n      }\n      else if (buildCache==cacheDCRT) for (long f=0; f<d; f++) {\n          (*dCache)[d*e +f].reset(new DoubleCRT(*(zzxPtr[f]),ea.getContext()));\n      }\n    } // end of e'th diagonal\n\n    // Finally, compute the result as \\sum_{f=0}^{d-1} \\sigma_f(y_f)\n    if (ctxt!=nullptr) {\n      *ctxt = acc[0];\n      for (long f = 1; f < d; f++) {\n\tacc[f].frobeniusAutomorph(f);\n\t*ctxt += acc[f];\n      }\n    }\n    // \"install\" the cache (if needed)\n    if (buildCache == cachezzX)\n      mat.installzzxcache(zCache);\n    else if (buildCache == cacheDCRT)\n      mat.installDCRTcache(dCache);\n  } // end of multiply(...)\n};\n\n// Wrapper functions around the implemenmtation class\nstatic void blockMatmul1d(Ctxt* ctxt, MatMulBase& mat, long dim,\n\t\t          MatrixCacheType buildCache, bool oneTransform)\n{\n  MatMulLock locking(mat, buildCache);\n\n  // If locking.getType()!=cacheEmpty then we really do need to\n  // build the cache, and we also have the lock for it.\n\n  if (locking.getType()==cacheEmpty && ctxt==nullptr) //  nothing to do\n    return;\n\n  switch (mat.getEA().getTag()) {\n    case PA_GF2_tag: {\n      blockMatmul1D_impl<PA_GF2> M(mat, locking.getType(), dim);\n      M.multiply(ctxt, dim, oneTransform);\n      break;\n    }\n    case PA_zz_p_tag: {\n      blockMatmul1D_impl<PA_zz_p> M(mat, locking.getType(), dim);\n      M.multiply(ctxt, dim, oneTransform);\n      break;\n    }\n    default:\n      throw std::logic_error(\"matmul1d: neither PA_GF2 nor PA_zz_p\");\n  }\n}\nvoid buildCache4BlockMatMul1D(MatMulBase& mat,\n\t\t\t      long dim, MatrixCacheType buildCache)\n{ blockMatmul1d(nullptr, mat, dim, buildCache, true); }\n\nvoid blockMatMul1D(Ctxt& ctxt, MatMulBase& mat, long dim,\n               MatrixCacheType buildCache)\n{ blockMatmul1d(&ctxt, mat, dim, buildCache, true); }\n\nvoid buildCache4BlockMatMulti1D(MatMulBase& mat,\n\t\t\t\tlong dim, MatrixCacheType buildCache)\n{ blockMatmul1d(nullptr, mat, dim, buildCache, false); }\n\nvoid blockMatMulti1D(Ctxt& ctxt, MatMulBase& mat, long dim,\n\t\t     MatrixCacheType buildCache)\n{ blockMatmul1d(&ctxt, mat, dim, buildCache, false); }\n\n\n\n// Versions for plaintext rather than ciphertext, useful for debugging\ntemplate<class type> class blockMatmul1D_pa_impl {\npublic:\n  PA_INJECT(type)\n\n  static void multiply(NewPlaintextArray& pa, BlockMatMul<type>& mat,\n\t\t       long dim, bool oneTrans=false)\n  {\n    const EncryptedArrayDerived<type>& ea = mat.getEA().getDerived(type());\n    const PAlgebra& zMStar = ea.getContext().zMStar;\n    RBak bak; bak.save(); ea.getTab().restoreContext();\n\n    long n = ea.size();\n    long D = ea.sizeOfDimension(dim);\n    long d = ea.getDegree();\n\n    vector< vector<RX> > data1(n/D);\n    for (long k = 0; k < n/D; k++)\n      data1[k].resize(D);\n\n    // copy the data into a vector of 1D vectors\n    vector<RX>& data = pa.getData<type>();\n    for (long i = 0; i < n; i++) {\n      long k,j;\n      std::tie(k,j) = zMStar.breakIndexByDim(i, dim);\n      data1[k][j] = data[i];       // k= along dim, j = the rest of i\n    }\n    for (long k = 0; k < n/D; k++) { // multiply each vector by a matrix\n      for (long j = 0; j < D; j++) { // matrix-vector multiplication\n\tvec_R acc, tmp, tmp1;\n\tmat_R val;\n\tacc.SetLength(d);\n\tfor (long i = 0; i < D; i++) {\n          bool zero = oneTrans? mat.get(val, i, j)\n                              : mat.multiGet(val, i, j, k);\n\t  if (!zero) { // if non-zero, multiply and add\n            VectorCopy(tmp1, data1[k][i], d);\n            mul(tmp, tmp1, val);\n            add(acc, acc, tmp);\n\t  }\n\t}\n\tlong idx = zMStar.assembleIndexByDim(make_pair(k,j), dim);\n        conv(data[idx], acc);\n      }\n    }\n  }\n}; \nvoid blockMatMul1D(NewPlaintextArray& pa, MatMulBase& mat, long dim)\n{\n  switch (mat.getEA().getTag()) {\n    case PA_GF2_tag: {\n      BlockMatMul<PA_GF2>& mat1= dynamic_cast< BlockMatMul<PA_GF2>& >(mat);\n      blockMatmul1D_pa_impl<PA_GF2>::multiply(pa, mat1, dim, true);\n      break;\n    }\n    case PA_zz_p_tag: {\n      BlockMatMul<PA_zz_p>& mat1= dynamic_cast< BlockMatMul<PA_zz_p>& >(mat);\n      blockMatmul1D_pa_impl<PA_zz_p>::multiply(pa, mat1, dim, true);\n      break;\n    }\n    default:\n      throw std::logic_error(\"blockMatMul1D: neither PA_GF2 nor PA_zz_p\");\n  }\n}\nvoid blockMatMulti1D(NewPlaintextArray& pa, MatMulBase& mat, long dim)\n{\n  switch (mat.getEA().getTag()) {\n    case PA_GF2_tag: {\n      BlockMatMul<PA_GF2>& mat1= dynamic_cast< BlockMatMul<PA_GF2>& >(mat);\n      blockMatmul1D_pa_impl<PA_GF2>::multiply(pa, mat1, dim, false);\n      break;\n    }\n    case PA_zz_p_tag: {\n      BlockMatMul<PA_zz_p>& mat1= dynamic_cast< BlockMatMul<PA_zz_p>& >(mat);\n      blockMatmul1D_pa_impl<PA_zz_p>::multiply(pa, mat1, dim, false);\n      break;\n    }\n    default:\n      throw std::logic_error(\"blockMatMulti1D: neither PA_GF2 nor PA_zz_p\");\n  }\n}\n", "meta": {"hexsha": "e7a87ee26354ad4631afa4e0aa9d624aa79f2df2", "size": 14823, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "misc/blockMatmul1D.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": "misc/blockMatmul1D.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": "misc/blockMatmul1D.cpp", "max_forks_repo_name": "Souhail-MEFTAH/HElib", "max_forks_repo_head_hexsha": "5f97813b99407d6f9a6251cee920b4e419edc028", "max_forks_repo_licenses": ["Apache-2.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.7180722892, "max_line_length": 79, "alphanum_fraction": 0.6189705188, "num_tokens": 4359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.4699482820573399}}
{"text": "#include <boost/cstdint.hpp>\n#include <boost/mpl/int.hpp>\n#include <boost/mpl/comparison.hpp>\n#include <boost/mpl/assert.hpp>\n#include <nt2/sdk/aligned/next_power_of_2.hpp>\n\nusing boost::mpl::int_;\nusing boost::mpl::equal_to;\nusing nt2::meta::next_power_of_2;\n\nint main()\n{\n  BOOST_MPL_ASSERT(( equal_to<next_power_of_2<int_<0> >::type,int_<0> >::type ));\n  BOOST_MPL_ASSERT(( equal_to<next_power_of_2<int_<1> >::type,int_<1> >::type ));\n  BOOST_MPL_ASSERT(( equal_to<next_power_of_2<int_<2> >::type,int_<2> >::type ));\n  BOOST_MPL_ASSERT(( equal_to<next_power_of_2<int_<2> >::type,int_<2> >::type ));\n  BOOST_MPL_ASSERT(( equal_to<next_power_of_2<int_<3> >::type,int_<4> >::type ));\n  BOOST_MPL_ASSERT(( equal_to<next_power_of_2<int_<1055> >::type,int_<2048> >::type ));\n}\n", "meta": {"hexsha": "69b31c80133beb8befd729a4f69cfbea996199a0", "size": 774, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/sdk/examples/memory/next_power_of_2.cpp", "max_stars_repo_name": "brycelelbach/nt2", "max_stars_repo_head_hexsha": "73d7e8dd390fa4c8d251c6451acdae65def70e0b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-24T03:35:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T03:35:10.000Z", "max_issues_repo_path": "modules/sdk/examples/memory/next_power_of_2.cpp", "max_issues_repo_name": "brycelelbach/nt2", "max_issues_repo_head_hexsha": "73d7e8dd390fa4c8d251c6451acdae65def70e0b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/sdk/examples/memory/next_power_of_2.cpp", "max_forks_repo_name": "brycelelbach/nt2", "max_forks_repo_head_hexsha": "73d7e8dd390fa4c8d251c6451acdae65def70e0b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.7, "max_line_length": 87, "alphanum_fraction": 0.7144702842, "num_tokens": 243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.4699482820573399}}
{"text": "//\n// Copyright (c) 2015-2019 CNRS INRIA\n// Copyright (c) 2016 Wandercraft, 86 rue de Paris 91400 Orsay, France.\n//\n\n#ifndef __pinocchio_se3_tpl_hpp__\n#define __pinocchio_se3_tpl_hpp__\n\n#include <Eigen/Geometry>\n#include \"pinocchio/math/quaternion.hpp\"\n#include \"pinocchio/spatial/cartesian-axis.hpp\"\n\nnamespace pinocchio\n{\n  template<typename _Scalar, int _Options>\n  struct traits< SE3Tpl<_Scalar,_Options> >\n  {\n    enum {\n      Options = _Options,\n      LINEAR = 0,\n      ANGULAR = 3\n    };\n    typedef _Scalar Scalar;\n    typedef Eigen::Matrix<Scalar,3,1,Options> Vector3;\n    typedef Eigen::Matrix<Scalar,4,1,Options> Vector4;\n    typedef Eigen::Matrix<Scalar,6,1,Options> Vector6;\n    typedef Eigen::Matrix<Scalar,3,3,Options> Matrix3;\n    typedef Eigen::Matrix<Scalar,4,4,Options> Matrix4;\n    typedef Eigen::Matrix<Scalar,6,6,Options> Matrix6;\n    typedef Matrix3 AngularType;\n    typedef typename PINOCCHIO_EIGEN_REF_TYPE(Matrix3) AngularRef;\n    typedef typename PINOCCHIO_EIGEN_REF_CONST_TYPE(Matrix3) ConstAngularRef;\n    typedef Vector3 LinearType;\n    typedef typename PINOCCHIO_EIGEN_REF_TYPE(Vector3) LinearRef;\n    typedef typename PINOCCHIO_EIGEN_REF_CONST_TYPE(Vector3) ConstLinearRef;\n    typedef Matrix6 ActionMatrixType;\n    typedef Matrix4 HomogeneousMatrixType;\n  }; // traits SE3Tpl\n  \n  template<typename _Scalar, int _Options>\n  struct SE3Tpl : public SE3Base< SE3Tpl<_Scalar,_Options> >\n  {\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    PINOCCHIO_SE3_TYPEDEF_TPL(SE3Tpl);\n    typedef SE3Base< SE3Tpl<_Scalar,_Options> > Base;\n    typedef Eigen::Quaternion<Scalar,Options> Quaternion;\n    typedef typename traits<SE3Tpl>::Vector3 Vector3;\n    typedef typename traits<SE3Tpl>::Matrix3 Matrix3;\n    typedef typename traits<SE3Tpl>::Matrix4 Matrix4;\n    typedef typename traits<SE3Tpl>::Vector4 Vector4;\n    typedef typename traits<SE3Tpl>::Matrix6 Matrix6;\n    \n    using Base::rotation;\n    using Base::translation;\n    \n    SE3Tpl(): rot(), trans() {};\n    \n    template<typename QuaternionLike,typename Vector3Like>\n    SE3Tpl(const Eigen::QuaternionBase<QuaternionLike> & quat,\n           const Eigen::MatrixBase<Vector3Like> & trans)\n    : rot(quat.matrix()), trans(trans)\n    {\n      EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(Vector3Like,3)\n    }\n    \n    template<typename Matrix3Like,typename Vector3Like>\n    SE3Tpl(const Eigen::MatrixBase<Matrix3Like> & R,\n           const Eigen::MatrixBase<Vector3Like> & trans)\n    : rot(R), trans(trans)\n    {\n      EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(Vector3Like,3)\n      EIGEN_STATIC_ASSERT_MATRIX_SPECIFIC_SIZE(Matrix3Like,3,3)\n    }\n    \n    template<typename Matrix4Like>\n    explicit SE3Tpl(const Eigen::MatrixBase<Matrix4Like> & m)\n    : rot(m.template block<3,3>(LINEAR,LINEAR))\n    , trans(m.template block<3,1>(LINEAR,ANGULAR))\n    {\n      EIGEN_STATIC_ASSERT_MATRIX_SPECIFIC_SIZE(Matrix4Like,4,4);\n    }\n    \n    SE3Tpl(int)\n    : rot(AngularType::Identity())\n    , trans(LinearType::Zero())\n    {}\n    \n    template<int O2>\n    SE3Tpl(const SE3Tpl<Scalar,O2> & clone)\n    : rot(clone.rotation()),trans(clone.translation()) {}\n    \n    template<int O2>\n    SE3Tpl & operator=(const SE3Tpl<Scalar,O2> & other)\n    {\n      rot = other.rotation();\n      trans = other.translation();\n      return *this;\n    }\n    \n    static SE3Tpl Identity()\n    {\n      return SE3Tpl(1);\n    }\n    \n    SE3Tpl & setIdentity()\n    { rot.setIdentity (); trans.setZero (); return *this;}\n    \n    /// aXb = bXa.inverse()\n    SE3Tpl inverse() const\n    {\n      return SE3Tpl(rot.transpose(), -rot.transpose()*trans);\n    }\n    \n    static SE3Tpl Random()\n    {\n      return SE3Tpl().setRandom();\n    }\n    \n    SE3Tpl & setRandom()\n    {\n      Quaternion q; quaternion::uniformRandom(q);\n      rot = q.matrix();\n      trans.setRandom();\n      \n      return *this;\n    }\n    \n    HomogeneousMatrixType toHomogeneousMatrix_impl() const\n    {\n      HomogeneousMatrixType M;\n      M.template block<3,3>(LINEAR,LINEAR) = rot;\n      M.template block<3,1>(LINEAR,ANGULAR) = trans;\n      M.template block<1,3>(ANGULAR,LINEAR).setZero();\n      M(3,3) = 1;\n      return M;\n    }\n    \n    /// Vb.toVector() = bXa.toMatrix() * Va.toVector()\n    ActionMatrixType toActionMatrix_impl() const\n    {\n      typedef Eigen::Block<ActionMatrixType,3,3> Block3;\n      ActionMatrixType M;\n      M.template block<3,3>(ANGULAR,ANGULAR)\n      = M.template block<3,3>(LINEAR,LINEAR) = rot;\n      M.template block<3,3>(ANGULAR,LINEAR).setZero();\n      Block3 B = M.template block<3,3>(LINEAR,ANGULAR);\n      \n      B.col(0) = trans.cross(rot.col(0));\n      B.col(1) = trans.cross(rot.col(1));\n      B.col(2) = trans.cross(rot.col(2));\n      return M;\n    }\n    \n    ActionMatrixType toActionMatrixInverse_impl() const\n    {\n      typedef Eigen::Block<ActionMatrixType,3,3> Block3;\n      ActionMatrixType M;\n      M.template block<3,3>(ANGULAR,ANGULAR)\n      = M.template block<3,3>(LINEAR,LINEAR) = rot.transpose();\n      Block3 C = M.template block<3,3>(ANGULAR,LINEAR); // used as temporary\n      Block3 B = M.template block<3,3>(LINEAR,ANGULAR);\n      \n#define PINOCCHIO_INTERNAL_COMPUTATION(axis_id,v3_in,v3_out,R,res) \\\n  CartesianAxis<axis_id>::cross(v3_in,v3_out); \\\n  res.col(axis_id).noalias() = R.transpose() * v3_out;\n      \n      PINOCCHIO_INTERNAL_COMPUTATION(0,trans,C.col(0),rot,B);\n      PINOCCHIO_INTERNAL_COMPUTATION(1,trans,C.col(0),rot,B);\n      PINOCCHIO_INTERNAL_COMPUTATION(2,trans,C.col(0),rot,B);\n      \n#undef PINOCCHIO_INTERNAL_COMPUTATION\n      \n      C.setZero();\n      return M;\n    }\n    \n    ActionMatrixType toDualActionMatrix_impl() const\n    {\n      typedef Eigen::Block<ActionMatrixType,3,3> Block3;\n      ActionMatrixType M;\n      M.template block<3,3>(ANGULAR,ANGULAR)\n      = M.template block<3,3>(LINEAR,LINEAR) = rot;\n      M.template block<3,3>(LINEAR,ANGULAR).setZero();\n      Block3 B = M.template block<3,3>(ANGULAR,LINEAR);\n      \n      B.col(0) = trans.cross(rot.col(0));\n      B.col(1) = trans.cross(rot.col(1));\n      B.col(2) = trans.cross(rot.col(2));\n      return M;\n    }\n    \n    void disp_impl(std::ostream & os) const\n    {\n      os\n      << \"  R =\\n\" << rot << std::endl\n      << \"  p = \" << trans.transpose() << std::endl;\n    }\n    \n    /// --- GROUP ACTIONS ON M6, F6 and I6 ---\n    \n    /// ay = aXb.act(by)\n    template<typename D>\n    typename SE3GroupAction<D>::ReturnType\n    act_impl(const D & d) const\n    {\n      return d.se3Action(*this);\n    }\n    \n    /// by = aXb.actInv(ay)\n    template<typename D> typename SE3GroupAction<D>::ReturnType\n    actInv_impl(const D & d) const\n    {\n      return d.se3ActionInverse(*this);\n    }\n    \n    template<typename EigenDerived>\n    typename EigenDerived::PlainObject\n    actOnEigenObject(const Eigen::MatrixBase<EigenDerived> & p) const\n    { return (rotation()*p+translation()).eval(); }\n    \n    template<typename MapDerived>\n    Vector3 actOnEigenObject(const Eigen::MapBase<MapDerived> & p) const\n    { return Vector3(rotation()*p+translation()); }\n    \n    template<typename EigenDerived>\n    typename EigenDerived::PlainObject\n    actInvOnEigenObject(const Eigen::MatrixBase<EigenDerived> & p) const\n    { return (rotation().transpose()*(p-translation())).eval(); }\n    \n    template<typename MapDerived>\n    Vector3 actInvOnEigenObject(const Eigen::MapBase<MapDerived> & p) const\n    { return Vector3(rotation().transpose()*(p-translation())); }\n    \n    Vector3 act_impl(const Vector3 & p) const\n    { return Vector3(rotation()*p+translation()); }\n    \n    Vector3 actInv_impl(const Vector3 & p) const\n    { return Vector3(rotation().transpose()*(p-translation())); }\n    \n    template<int O2>\n    SE3Tpl act_impl(const SE3Tpl<Scalar,O2> & m2) const\n    { return SE3Tpl(rot*m2.rotation()\n                    ,translation()+rotation()*m2.translation());}\n    \n    template<int O2>\n    SE3Tpl actInv_impl(const SE3Tpl<Scalar,O2> & m2) const\n    { return SE3Tpl(rot.transpose()*m2.rotation(),\n                    rot.transpose()*(m2.translation()-translation()));}\n    \n    template<int O2>\n    SE3Tpl __mult__(const SE3Tpl<Scalar,O2> & m2) const\n    { return this->act_impl(m2);}\n    \n    template<int O2>\n    bool isEqual(const SE3Tpl<Scalar,O2> & m2) const\n    {\n      return (rotation() == m2.rotation() && translation() == m2.translation());\n    }\n    \n    template<int O2>\n    bool isApprox_impl(const SE3Tpl<Scalar,O2> & m2,\n                       const Scalar & prec = Eigen::NumTraits<Scalar>::dummy_precision()) const\n    {\n      return rotation().isApprox(m2.rotation(), prec)\n      && translation().isApprox(m2.translation(), prec);\n    }\n    \n    bool isIdentity(const Scalar & prec = Eigen::NumTraits<Scalar>::dummy_precision()) const\n    {\n      return rotation().isIdentity(prec) && translation().isZero(prec);\n    }\n    \n    ConstAngularRef rotation_impl() const { return rot; }\n    AngularRef rotation_impl() { return rot; }\n    void rotation_impl(const AngularType & R) { rot = R; }\n    ConstLinearRef translation_impl() const { return trans;}\n    LinearRef translation_impl() { return trans;}\n    void translation_impl(const LinearType & p) { trans = p; }\n    \n    /// \\returns An expression of *this with the Scalar type casted to NewScalar.\n    template<typename NewScalar>\n    SE3Tpl<NewScalar,Options> cast() const\n    {\n      typedef SE3Tpl<NewScalar,Options> ReturnType;\n      ReturnType res(rot.template cast<NewScalar>(),\n                     trans.template cast<NewScalar>());\n      return res;\n    }\n    \n    ///\n    /// \\brief Linear interpolation on the SE3 manifold.\n    ///\n    /// \\param[in] A Initial transformation.\n    /// \\param[in] B Target transformation.\n    /// \\param[in] alpha Interpolation factor in [0 ... 1].\n    ///\n    /// \\returns An interpolated transformation between A and B.\n    ///\n    /// \\note This is similar to the SLERP operation which acts initially for rotation but applied here to rigid transformation.\n    ///\n    template<typename OtherScalar>\n    static SE3Tpl Interpolate(const SE3Tpl & A, const SE3Tpl & B, const OtherScalar & alpha);\n    \n  protected:\n    AngularType rot;\n    LinearType trans;\n    \n  }; // class SE3Tpl\n  \n} // namespace pinocchio\n\n#endif // ifndef __pinocchio_se3_tpl_hpp__\n\n", "meta": {"hexsha": "708d80fd3a0b1969c9bde0a1dd02092e2705e08f", "size": 10213, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/spatial/se3-tpl.hpp", "max_stars_repo_name": "yDMhaven/pinocchio", "max_stars_repo_head_hexsha": "fabed17d5ad0dc1c8d251c64cfa656a0215469a5", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-04-07T07:23:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-07T07:23:34.000Z", "max_issues_repo_path": "src/spatial/se3-tpl.hpp", "max_issues_repo_name": "yDMhaven/pinocchio", "max_issues_repo_head_hexsha": "fabed17d5ad0dc1c8d251c64cfa656a0215469a5", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/spatial/se3-tpl.hpp", "max_forks_repo_name": "yDMhaven/pinocchio", "max_forks_repo_head_hexsha": "fabed17d5ad0dc1c8d251c64cfa656a0215469a5", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.525477707, "max_line_length": 128, "alphanum_fraction": 0.650543425, "num_tokens": 2748, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.4699482820573399}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// statistics::survival::data::meta::failure_random.hpp                      //\n//                                                                           //\n//  Copyright 2009 Erwann Rogard. Distributed under the Boost                //\n//  Software License, Version 1.0. (See accompanying file                    //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)         //\n///////////////////////////////////////////////////////////////////////////////\n#ifndef BOOST_STATISTICS_SURVIVAL_DATA_META_FAILURE_RANDOM_HPP_ER_2009\n#define BOOST_STATISTICS_SURVIVAL_DATA_META_FAILURE_RANDOM_HPP_ER_2009\n#include <boost/dist_random/include.hpp>\n#include <boost/statistics/model/wrap/aggregate/model_covariate_parameter.hpp>\n#include <boost/statistics/survival/data/meta/failure_distribution.hpp>\n\nnamespace boost{\nnamespace statistics{\nnamespace survival{\nnamespace data{\n\n    // Model + Covariate + Parameter --->  RandomDistribution (of failure time)\n    //\n    // These are default implementations that can be overloaded with a \n    // specialization on M\n\n    template<typename M> \n    struct meta_failure_random{\n        typedef meta_failure_distribution<M>                        map1_;\n        typedef typename map1_::type                                dist_;\n        typedef boost::dist_random<dist_>                           map2_;\n        typedef typename map2_::type                                type;\n    };\n\n    template<typename M,typename X,typename P>\n    typename meta_failure_random<M>::type \n    make_failure_random(\n        boost::statistics::model::model_covariate_parameter_<M,X,P>\n    );\n\n    // Implementation //\n\n    template<typename M,typename X,typename P>\n    typename meta_failure_random<M>::type \n    make_failure_random(\n        boost::statistics::model::model_covariate_parameter_<M,X,P> mcp\n    ){\n        typedef meta_failure_random<M>                              map_;\n        typedef typename map_::map2_                                map2_;\n        return map2_::make(\n            make_failure_distribution(mcp) \n        );\n    }\n\n}// data\n}// survival\n}// statistics\n}// boost\n\n#endif", "meta": {"hexsha": "ad9c6fe70db421d2306661f1dd99caa9667d88be", "size": 2227, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "survival_data copy/boost/statistics/survival/data/meta/failure_random.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": "survival_data copy/boost/statistics/survival/data/meta/failure_random.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": "survival_data copy/boost/statistics/survival/data/meta/failure_random.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": 39.0701754386, "max_line_length": 79, "alphanum_fraction": 0.5675797036, "num_tokens": 413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.46994828205733974}}
{"text": "//\n// Created by rgrandia on 23.09.19.\n//\n\n#pragma once\n\n#include <urdf/model.h>\n\n#include <Eigen/Core>\n#include <Eigen/Eigenvalues>\n#include <Eigen/Geometry>\n\n#include <urdf2robcogen/UrdfStructure.hpp>\n\nEigen::Matrix3d inertiaMatrixFromLink(const urdf::Link& link);\nbool isValidInertiaMatrix(const Eigen::Matrix3d& I);\nEigen::Matrix3d expressInertiaFromFrameAInComFrame(const Eigen::Matrix3d& A_I_A, double m, const PoseInWorld& poseA, const PoseInWorld& poseC);\n\nEigen::Matrix3d skewSymMatrixFromVector(const Eigen::Vector3d& vec);\n\nEigen::Vector3d toEigen(const urdf::Vector3& vec);\nurdf::Vector3 fromEigen(const Eigen::Vector3d& vec);\n\nEigen::Quaterniond toEigen(const urdf::Rotation& rotation);\nurdf::Rotation fromEigen(const Eigen::Quaterniond& rotation);\n\nstd::string printVector(const urdf::Vector3& vector);\n\nurdf::Vector3 rotationXyz(const urdf::Rotation& rot_quaternion);\n\nstd::pair<Eigen::Vector3d, Eigen::Quaterniond> getRelativePose(const PoseInWorld& poseChild, const PoseInWorld& poseParent);\n\nstd::string print_timeStamp();\n\ntemplate <typename K, typename T>\nstd::vector<K> getKeys(std::map<K, T> m) {\n  std::vector<K> v;\n  v.reserve(m.size());\n  for (const auto& keyValue : m) {\n    v.push_back(keyValue.first);\n  }\n  return v;\n}\n\ntemplate <typename T>\nstd::vector<std::pair<std::string, T>> toIDSortedVector(std::map<std::string, T> m) {\n  std::vector<std::pair<std::string, T>> v;\n  v.reserve(m.size());\n  for (const auto& keyValue : m) {\n    v.push_back(keyValue);\n  }\n\n  std::sort(v.begin(), v.end(),\n            [](const std::pair<std::string, T>& a, const std::pair<std::string, T>& b) { return a.second.id < b.second.id; });\n  return v;\n}\n\ntemplate <typename K>\nvoid removeFromContainer(const K& key, std::vector<K>& container) {\n  auto keyIterator = std::find(container.begin(), container.end(), key);\n  if (keyIterator != container.end()) {\n    container.erase(keyIterator);\n  } else {\n    throw std::runtime_error(\"Key to be deleted not found\");\n  }\n}\n\ntemplate <typename K, typename T>\nvoid removeFromContainer(const K& key, std::map<K, T>& container) {\n  auto keyIterator = container.find(key);\n  if (keyIterator != container.end()) {\n    container.erase(keyIterator);\n  } else {\n    throw std::runtime_error(\"Key to be deleted not found\");\n  }\n}", "meta": {"hexsha": "384ed5314a0fcc2b493fc26d1090163fc9bf907b", "size": 2276, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/urdf2robcogen/Utils.hpp", "max_stars_repo_name": "leggedrobotics/urdf2robcogen", "max_stars_repo_head_hexsha": "7517c228a28dd6a747d7a8de02697470e1f92655", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2018-12-11T22:51:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-25T13:48:30.000Z", "max_issues_repo_path": "include/urdf2robcogen/Utils.hpp", "max_issues_repo_name": "leggedrobotics/urdf2robcogen", "max_issues_repo_head_hexsha": "7517c228a28dd6a747d7a8de02697470e1f92655", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2019-04-12T17:08:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-24T09:44:31.000Z", "max_forks_repo_path": "include/urdf2robcogen/Utils.hpp", "max_forks_repo_name": "leggedrobotics/urdf2robcogen", "max_forks_repo_head_hexsha": "7517c228a28dd6a747d7a8de02697470e1f92655", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-11-20T14:21:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-19T04:32:27.000Z", "avg_line_length": 29.9473684211, "max_line_length": 143, "alphanum_fraction": 0.7078207381, "num_tokens": 622, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.46994828205733974}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2020-2021 Mikhail Komarov <nemo@nil.foundation>\n// Copyright (c) 2020-2021 Nikita Kaskov <nbering@nil.foundation>\n// Copyright (c) 2020-2021 Ilias Khairullin <ilias@nil.foundation>\n//\n// MIT License\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n//---------------------------------------------------------------------------//\n\n#define BOOST_TEST_MODULE algebra_curves_test\n\n#include <iostream>\n#include <vector>\n#include <array>\n\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 <boost/property_tree/ptree.hpp>\n#include <boost/property_tree/json_parser.hpp>\n\n#include <nil/crypto3/multiprecision/cpp_int.hpp>\n\n#include <nil/crypto3/algebra/curves/bls12.hpp>\n#include <nil/crypto3/algebra/curves/mnt4.hpp>\n#include <nil/crypto3/algebra/curves/mnt6.hpp>\n\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/algebra/algorithms/pair.hpp>\n\n#include <nil/crypto3/algebra/fields/detail/element/fp.hpp>\n#include <nil/crypto3/algebra/fields/detail/element/fp4.hpp>\n#include <nil/crypto3/algebra/fields/detail/element/fp6_2over3.hpp>\n#include <nil/crypto3/algebra/fields/detail/element/fp12_2over3over2.hpp>\n\nusing namespace nil::crypto3::algebra::pairing;\nusing namespace nil::crypto3::algebra;\nusing namespace nil::crypto3::multiprecision;\n\ntemplate<typename FieldParams>\nvoid print_field_element(std::ostream &os, const typename fields::detail::element_fp<FieldParams> &e) {\n    os << e.data;\n}\n\ntemplate<typename FieldParams>\nvoid print_field_element(std::ostream &os, const typename fields::detail::element_fp2<FieldParams> &e) {\n    os << \"[\";\n    print_field_element(os, e.data[0]);\n    os << \", \";\n    print_field_element(os, e.data[1]);\n    os << \"]\";\n}\n\ntemplate<typename FieldParams>\nvoid print_field_element(std::ostream &os, const typename fields::detail::element_fp3<FieldParams> &e) {\n    os << \"[\";\n    print_field_element(os, e.data[0]);\n    os << \", \";\n    print_field_element(os, e.data[1]);\n    os << \", \";\n    print_field_element(os, e.data[2]);\n    os << \"]\";\n}\n\ntemplate<typename FieldParams>\nvoid print_field_element(std::ostream &os, const typename fields::detail::element_fp4<FieldParams> &e) {\n    os << \"[\";\n    print_field_element(os, e.data[0]);\n    os << \", \";\n    print_field_element(os, e.data[1]);\n    os << \"]\";\n}\n\ntemplate<typename FieldParams>\nvoid print_field_element(std::ostream &os, const typename fields::detail::element_fp6_2over3<FieldParams> &e) {\n    os << \"[\";\n    print_field_element(os, e.data[0]);\n    os << \", \";\n    print_field_element(os, e.data[1]);\n    os << \"]\";\n}\n\ntemplate<typename FieldParams>\nvoid print_field_element(std::ostream &os, const fields::detail::element_fp12_2over3over2<FieldParams> &e) {\n    os << \"[[[\" << e.data[0].data[0].data[0].data << \",\" << e.data[0].data[0].data[1].data << \"],[\"\n       << e.data[0].data[1].data[0].data << \",\" << e.data[0].data[1].data[1].data << \"],[\"\n       << e.data[0].data[2].data[0].data << \",\" << e.data[0].data[2].data[1].data << \"]],\"\n       << \"[[\" << e.data[1].data[0].data[0].data << \",\" << e.data[1].data[0].data[1].data << \"],[\"\n       << e.data[1].data[1].data[0].data << \",\" << e.data[1].data[1].data[1].data << \"],[\"\n       << e.data[1].data[2].data[0].data << \",\" << e.data[1].data[2].data[1].data << \"]]]\";\n}\n\ntemplate<typename CurveGroupValue>\nvoid print_curve_group_element(std::ostream &os, const CurveGroupValue &e) {\n    os << \"(\";\n    print_field_element(os, e.X);\n    os << \",\";\n    print_field_element(os, e.Y);\n    os << \",\";\n    print_field_element(os, e.Z);\n    os << \")\" << std::endl;\n}\n\nvoid print_g1_precomp_element(std::ostream &os, const typename pairing::pairing_policy<curves::bls12<381>>::g1_precomputed_type &e) {\n    os << \"{\\\"PX\\\": \";\n    print_field_element(os, e.PX);\n    os << \", \\\"PY\\\": \";\n    print_field_element(os, e.PY);\n    os << \"}\" << std::endl;\n}\n\nvoid print_g1_precomp_element(std::ostream &os, const typename pairing::pairing_policy<curves::mnt4<298>>::g1_precomputed_type &e) {\n    os << \"{\\\"PX\\\": \";\n    print_field_element(os, e.PX);\n    os << \", \\\"PY\\\": \";\n    print_field_element(os, e.PY);\n    os << \", \\\"PX_twist\\\": \";\n    print_field_element(os, e.PX_twist);\n    os << \", \\\"PY_twist\\\": \";\n    print_field_element(os, e.PY_twist);\n    os << \"}\" << std::endl;\n}\n\nvoid print_g1_precomp_element(std::ostream &os, const typename pairing::pairing_policy<curves::mnt6<298>>::g1_precomputed_type &e) {\n    os << \"{\\\"PX\\\": \";\n    print_field_element(os, e.PX);\n    os << \", \\\"PY\\\": \";\n    print_field_element(os, e.PY);\n    os << \", \\\"PX_twist\\\": \";\n    print_field_element(os, e.PX_twist);\n    os << \", \\\"PY_twist\\\": \";\n    print_field_element(os, e.PY_twist);\n    os << \"}\" << std::endl;\n}\n\nvoid print_g2_precomp_element(std::ostream &os, const typename pairing::pairing_policy<curves::bls12<381>>::g2_precomputed_type &e) {\n    os << \"\\\"coordinates\\\": [[\" << e.QX.data[0].data << \" , \" << e.QX.data[1].data << \"] , [\" << e.QY.data[0].data\n       << \" , \" << e.QY.data[1].data << \"]]\" << std::endl;\n    auto print_coeff = [&os](const auto &c) {\n        os << \"\\\"ell_0\\\": [\" << c.ell_0.data[0].data << \",\" << c.ell_0.data[1].data << \"],\"\n           << \"\\\"ell_VW\\\": [\" << c.ell_VW.data[0].data << \",\" << c.ell_VW.data[1].data << \"],\"\n           << \"\\\"ell_VV\\\": [\" << c.ell_VV.data[0].data << \",\" << c.ell_VV.data[1].data << \"]\";\n    };\n    os << \"coefficients: [\";\n    for (auto &c : e.coeffs) {\n        os << \"{\";\n        print_coeff(c);\n        os << \"},\";\n    }\n    os << \"]\" << std::endl;\n}\n\nvoid print_g2_precomp_element(std::ostream &os, const typename pairing::pairing_policy<curves::mnt4<298>>::g2_precomputed_type &e) {\n    os << \"\\\"coordinates\\\": {\\\"QX\\\": \";\n    print_field_element(os, e.QX);\n    os << \", \\\"QY\\\": \";\n    print_field_element(os, e.QY);\n    os << \", \\\"QY2\\\": \";\n    print_field_element(os, e.QY2);\n    os << \", \\\"QX_over_twist\\\": \";\n    print_field_element(os, e.QX_over_twist);\n    os << \", \\\"QY_over_twist\\\": \";\n    print_field_element(os, e.QY_over_twist);\n    os << \"}\" << std::endl;\n\n    auto print_dbl_coeff = [&os](const auto &c) {\n        os << \"{\\\"c_H\\\": \";\n        print_field_element(os, c.c_H);\n        os << \", \\\"c_4C\\\": \";\n        print_field_element(os, c.c_4C);\n        os << \", \\\"c_J\\\": \";\n        print_field_element(os, c.c_J);\n        os << \", \\\"c_L\\\": \";\n        print_field_element(os, c.c_L);\n        os << \"}\" << std::endl;\n    };\n    auto print_add_coeff = [&os](const auto &c) {\n        os << \"{\\\"c_L1\\\": \";\n        print_field_element(os, c.c_L1);\n        os << \", \\\"c_RZ\\\": \";\n        print_field_element(os, c.c_RZ);\n        os << \"}\" << std::endl;\n    };\n\n    os << \"dbl_coeffs: \";\n    for (auto &c : e.dbl_coeffs) {\n        print_dbl_coeff(c);\n    }\n    std::cout << std::endl;\n\n    os << \"add_coeffs: \";\n    for (auto &c : e.add_coeffs) {\n        print_add_coeff(c);\n    }\n    std::cout << std::endl;\n}\n\nvoid print_g2_precomp_element(std::ostream &os, const typename pairing::pairing_policy<curves::mnt6<298>>::g2_precomputed_type &e) {\n    os << \"\\\"coordinates\\\": {\\\"QX\\\": \";\n    print_field_element(os, e.QX);\n    os << \", \\\"QY\\\": \";\n    print_field_element(os, e.QY);\n    os << \", \\\"QY2\\\": \";\n    print_field_element(os, e.QY2);\n    os << \", \\\"QX_over_twist\\\": \";\n    print_field_element(os, e.QX_over_twist);\n    os << \", \\\"QY_over_twist\\\": \";\n    print_field_element(os, e.QY_over_twist);\n    os << \"}\" << std::endl;\n\n    auto print_dbl_coeff = [&os](const auto &c) {\n        os << \"{\\\"c_H\\\": \";\n        print_field_element(os, c.c_H);\n        os << \", \\\"c_4C\\\": \";\n        print_field_element(os, c.c_4C);\n        os << \", \\\"c_J\\\": \";\n        print_field_element(os, c.c_J);\n        os << \", \\\"c_L\\\": \";\n        print_field_element(os, c.c_L);\n        os << \"}\" << std::endl;\n    };\n    auto print_add_coeff = [&os](const auto &c) {\n        os << \"{\\\"c_L1\\\": \";\n        print_field_element(os, c.c_L1);\n        os << \", \\\"c_RZ\\\": \";\n        print_field_element(os, c.c_RZ);\n        os << \"}\" << std::endl;\n    };\n\n    os << \"dbl_coeffs: \";\n    for (auto &c : e.dbl_coeffs) {\n        print_dbl_coeff(c);\n    }\n    std::cout << std::endl;\n\n    os << \"add_coeffs: \";\n    for (auto &c : e.add_coeffs) {\n        print_add_coeff(c);\n    }\n    std::cout << std::endl;\n}\n\nnamespace boost {\n    namespace test_tools {\n        namespace tt_detail {\n            template<typename FieldParams>\n            struct print_log_value<typename fields::detail::element_fp<FieldParams>> {\n                void operator()(std::ostream &os, typename fields::detail::element_fp<FieldParams> const &e) {\n                    print_field_element(os, e);\n                    std::cout << std::endl;\n                }\n            };\n\n            template<typename FieldParams>\n            struct print_log_value<typename fields::detail::element_fp2<FieldParams>> {\n                void operator()(std::ostream &os, typename fields::detail::element_fp2<FieldParams> const &e) {\n                    print_field_element(os, e);\n                    std::cout << std::endl;\n                }\n            };\n\n            template<>\n            struct print_log_value<curves::bls12<381>::g1_type<>::value_type> {\n                void operator()(std::ostream &os,\n                                const typename curves::bls12<381>::g1_type<>::value_type &e) {\n                    print_curve_group_element(os, e);\n                }\n            };\n\n            template<>\n            struct print_log_value<curves::bls12<381>::g2_type<>::value_type> {\n                void operator()(std::ostream &os,\n                                const typename curves::bls12<381>::g2_type<>::value_type &e) {\n                    print_curve_group_element(os, e);\n                }\n            };\n\n            template<>\n            struct print_log_value<pairing::pairing_policy<curves::bls12<381>>::g1_precomputed_type> {\n                void operator()(std::ostream &os, const typename pairing::pairing_policy<curves::bls12<381>>::g1_precomputed_type &e) {\n                    print_g1_precomp_element(os, e);\n                }\n            };\n\n            template<>\n            struct print_log_value<pairing::pairing_policy<curves::bls12<381>>::g2_precomputed_type> {\n                void operator()(std::ostream &os, const typename pairing::pairing_policy<curves::bls12<381>>::g2_precomputed_type &e) {\n                    print_g2_precomp_element(os, e);\n                }\n            };\n\n            template<>\n            struct print_log_value<curves::bls12<381>::gt_type::value_type> {\n                void operator()(std::ostream &os,\n                                const typename curves::bls12<381>::gt_type::value_type &e) {\n                    print_field_element(os, e);\n                    std::cout << std::endl;\n                }\n            };\n\n            template<>\n            struct print_log_value<curves::mnt4<298>::g1_type<>::value_type> {\n                void operator()(std::ostream &os,\n                                const typename curves::mnt4<298>::g1_type<>::value_type &e) {\n                    print_curve_group_element(os, e);\n                }\n            };\n\n            template<>\n            struct print_log_value<curves::mnt4<298>::g2_type<>::value_type> {\n                void operator()(std::ostream &os,\n                                const typename curves::mnt4<298>::g2_type<>::value_type &e) {\n                    print_curve_group_element(os, e);\n                }\n            };\n\n            template<>\n            struct print_log_value<pairing::pairing_policy<curves::mnt4<298>>::g1_precomputed_type> {\n                void operator()(std::ostream &os, const typename pairing::pairing_policy<curves::mnt4<298>>::g1_precomputed_type &e) {\n                    print_g1_precomp_element(os, e);\n                }\n            };\n\n            template<>\n            struct print_log_value<pairing::pairing_policy<curves::mnt4<298>>::g2_precomputed_type> {\n                void operator()(std::ostream &os, const typename pairing::pairing_policy<curves::mnt4<298>>::g2_precomputed_type &e) {\n                    print_g2_precomp_element(os, e);\n                }\n            };\n\n            template<>\n            struct print_log_value<curves::mnt4<298>::gt_type::value_type> {\n                void operator()(std::ostream &os,\n                                const typename curves::mnt4<298>::gt_type::value_type &e) {\n                    print_field_element(os, e);\n                    std::cout << std::endl;\n                }\n            };\n\n            template<>\n            struct print_log_value<curves::mnt6<298>::g1_type<>::value_type> {\n                void operator()(std::ostream &os,\n                                const typename curves::mnt6<298>::g1_type<>::value_type &e) {\n                    print_curve_group_element(os, e);\n                }\n            };\n\n            template<>\n            struct print_log_value<curves::mnt6<298>::g2_type<>::value_type> {\n                void operator()(std::ostream &os,\n                                const typename curves::mnt6<298>::g2_type<>::value_type &e) {\n                    print_curve_group_element(os, e);\n                }\n            };\n\n            template<>\n            struct print_log_value<pairing::pairing_policy<curves::mnt6<298>>::g1_precomputed_type> {\n                void operator()(std::ostream &os, const typename pairing::pairing_policy<curves::mnt6<298>>::g1_precomputed_type &e) {\n                    print_g1_precomp_element(os, e);\n                }\n            };\n\n            template<>\n            struct print_log_value<pairing::pairing_policy<curves::mnt6<298>>::g2_precomputed_type> {\n                void operator()(std::ostream &os, const typename pairing::pairing_policy<curves::mnt6<298>>::g2_precomputed_type &e) {\n                    print_g2_precomp_element(os, e);\n                }\n            };\n\n            template<>\n            struct print_log_value<curves::mnt6<298>::gt_type::value_type> {\n                void operator()(std::ostream &os,\n                                const typename curves::mnt6<298>::gt_type::value_type &e) {\n                    print_field_element(os, e);\n                    std::cout << std::endl;\n                }\n            };\n\n            template<template<typename, typename> class P, typename K, typename V>\n            struct print_log_value<P<K, V>> {\n                void operator()(std::ostream &, P<K, V> const &) {\n                }\n            };\n        }    // namespace tt_detail\n    }        // namespace test_tools\n}    // namespace boost\n\nconst char *test_data = \"../../../../libs/algebra/test/data/pairing.json\";\n\nboost::property_tree::ptree string_data(const std::string &test_name) {\n    boost::property_tree::ptree string_data;\n    boost::property_tree::read_json(test_data, string_data);\n\n    return string_data.get_child(test_name);\n}\n\nenum Fr_enum : std::size_t { VKx_poly, VKy_poly, VKz_poly, A1_poly, B1_poly, C1_poly, A2_poly, B2_poly, C2_poly };\nenum G1_enum : std::size_t { A1, C1, A2, C2, VKx };\nenum G2_enum : std::size_t { B1, B2, VKy, VKz };\nenum GT_enum : std::size_t {\n    pairing_A1_B1,\n    pairing_A2_B2,\n    pair_reduceding_A1_B1,\n    pair_reduceding_A2_B2,\n    pair_reduceding_A1_B1_mul_pair_reduceding_A2_B2,\n    pair_reduceding_VKx_poly_A1_B1,\n    miller_loop_prec_A1_prec_B1,\n    miller_loop_prec_A2_prec_B2,\n    double_miller_loop_prec_A1_prec_B1_prec_A2_prec_B2\n};\nenum g1_precomp_enum : std::size_t { prec_A1, prec_A2 };\nenum g2_precomp_enum : std::size_t { prec_B1, prec_B2 };\n\n// TODO: add affine_pair_reduceding test\ntemplate<typename CurveType, typename Fr_value_type, typename G1_value_type, typename G2_value_type,\n         typename GT_value_type, typename g1_precomp_value_type, typename g2_precomp_value_type>\nvoid check_pairing_operations(std::vector<Fr_value_type> &Fr_elements,\n                              std::vector<G1_value_type> &G1_elements,\n                              std::vector<G2_value_type> &G2_elements,\n                              std::vector<GT_value_type> &GT_elements,\n                              std::vector<g1_precomp_value_type> &G1_prec_elements,\n                              std::vector<g2_precomp_value_type> &G2_prec_elements) {\n    std::cout << \" * Basic fields and groups tests started...\" << std::endl;\n    BOOST_CHECK_EQUAL((Fr_elements[A1_poly] * Fr_elements[B1_poly] - Fr_elements[VKx_poly] * Fr_elements[VKy_poly]) *\n                          Fr_elements[VKz_poly].inversed(),\n                      Fr_elements[C1_poly]);\n    BOOST_CHECK_EQUAL((Fr_elements[A2_poly] * Fr_elements[B2_poly] - Fr_elements[VKx_poly] * Fr_elements[VKy_poly]) *\n                          Fr_elements[VKz_poly].inversed(),\n                      Fr_elements[C2_poly]);\n    BOOST_CHECK_EQUAL(Fr_elements[VKx_poly] * G1_value_type::one(), G1_elements[VKx]);\n    BOOST_CHECK_EQUAL(Fr_elements[VKy_poly] * G2_value_type::one(), G2_elements[VKy]);\n    BOOST_CHECK_EQUAL(Fr_elements[VKz_poly] * G2_value_type::one(), G2_elements[VKz]);\n    BOOST_CHECK_EQUAL(Fr_elements[A1_poly] * G1_value_type::one(), G1_elements[A1]);\n    BOOST_CHECK_EQUAL(Fr_elements[C1_poly] * G1_value_type::one(), G1_elements[C1]);\n    BOOST_CHECK_EQUAL(Fr_elements[A2_poly] * G1_value_type::one(), G1_elements[A2]);\n    BOOST_CHECK_EQUAL(Fr_elements[C2_poly] * G1_value_type::one(), G1_elements[C2]);\n    BOOST_CHECK_EQUAL(Fr_elements[B1_poly] * G2_value_type::one(), G2_elements[B1]);\n    BOOST_CHECK_EQUAL(Fr_elements[B2_poly] * G2_value_type::one(), G2_elements[B2]);\n    std::cout << \" * Basic fields and groups tests finished.\" << std::endl << std::endl;\n\n    std::cout << \" * Precomputing and pairing tests started...\" << std::endl;\n    BOOST_CHECK_EQUAL(precompute_g1<CurveType>(G1_elements[A1]), G1_prec_elements[prec_A1]);\n    BOOST_CHECK_EQUAL(precompute_g1<CurveType>(G1_elements[A2]), G1_prec_elements[prec_A2]);\n    BOOST_CHECK_EQUAL(precompute_g2<CurveType>(G2_elements[B1]), G2_prec_elements[prec_B1]);\n    BOOST_CHECK_EQUAL(precompute_g2<CurveType>(G2_elements[B2]), G2_prec_elements[prec_B2]);\n    BOOST_CHECK_EQUAL(pair<CurveType>(G1_elements[A1], G2_elements[B1]), GT_elements[pairing_A1_B1]);\n    BOOST_CHECK_EQUAL(pair<CurveType>(G1_elements[A2], G2_elements[B2]), GT_elements[pairing_A2_B2]);\n    std::cout << \" * Precomputing and pairing tests finished.\" << std::endl << std::endl;\n\n    // TODO: activate after pair_reduceding->cyclotomic_exp fixed. Bugs in final_exponentiation_last_chunk\n    std::cout << \" * Reduced pairing tests started...\" << std::endl;\n    BOOST_CHECK_EQUAL(pair_reduced<CurveType>(G1_elements[A1], G2_elements[B1]), GT_elements[pair_reduceding_A1_B1]);\n    BOOST_CHECK_EQUAL(pair_reduced<CurveType>(G1_elements[A1], G2_elements[B1]),\n                      pair_reduced<CurveType>(G1_elements[VKx], G2_elements[VKy]) *\n                          pair_reduced<CurveType>(G1_elements[C1], G2_elements[VKz]));\n    BOOST_CHECK_EQUAL(pair_reduced<CurveType>(G1_elements[A2], G2_elements[B2]), GT_elements[pair_reduceding_A2_B2]);\n    BOOST_CHECK_EQUAL(pair_reduced<CurveType>(G1_elements[A2], G2_elements[B2]),\n                      pair_reduced<CurveType>(G1_elements[VKx], G2_elements[VKy]) *\n                          pair_reduced<CurveType>(G1_elements[C2], G2_elements[VKz]));\n    BOOST_CHECK_EQUAL(pair_reduced<CurveType>(G1_elements[A1], G2_elements[B1]) *\n                          pair_reduced<CurveType>(G1_elements[A2], G2_elements[B2]),\n                      GT_elements[pair_reduceding_A1_B1_mul_pair_reduceding_A2_B2]);\n    std::cout << \" * Reduced pairing tests finished.\" << std::endl << std::endl;\n\n    // TODO: activate when scalar multiplication done\n    std::cout << \" * Reduced pairing tests with scalar multiplication started...\" << std::endl;\n    BOOST_CHECK_EQUAL(pair_reduced<CurveType>(G1_elements[A1], G2_elements[B1]) *\n                          pair_reduced<CurveType>(G1_elements[A2], G2_elements[B2]),\n                      pair_reduced<CurveType>(Fr_value_type(2) * G1_elements[VKx], G2_elements[VKy]) *\n                          pair_reduced<CurveType>(G1_elements[C1] + G1_elements[C2], G2_elements[VKz]));\n    BOOST_CHECK_EQUAL(pair_reduced<CurveType>(Fr_elements[VKx_poly] * G1_elements[A1], G2_elements[B1]),\n                      GT_elements[pair_reduceding_VKx_poly_A1_B1]);\n    BOOST_CHECK_EQUAL(pair_reduced<CurveType>(Fr_elements[VKx_poly] * G1_elements[A1], G2_elements[B1]),\n                      pair_reduced<CurveType>(G1_elements[A1], Fr_elements[VKx_poly] * G2_elements[B1]));\n    std::cout << \" * Reduced pairing tests with scalar multiplication finished.\" << std::endl << std::endl;\n\n    // TODO: activate when pow will be override with field element\n    std::cout << \" * Reduced pairing tests with pow started...\" << std::endl;\n    BOOST_CHECK_EQUAL(\n        pair_reduced<CurveType>(Fr_elements[VKx_poly] * G1_elements[A1], G2_elements[B1]),\n        // TODO: fix pow to accept field element as exponent\n        pair_reduced<CurveType>(G1_elements[A1], G2_elements[B1]).pow(cpp_int(Fr_elements[VKx_poly].data)));\n    std::cout << \" * Reduced pairing tests with pow finished.\" << std::endl << std::endl;\n\n    std::cout << \" * Miller loop tests started...\" << std::endl;\n    BOOST_CHECK_EQUAL(miller_loop<CurveType>(G1_prec_elements[prec_A1], G2_prec_elements[prec_B1]),\n                      GT_elements[miller_loop_prec_A1_prec_B1]);\n    BOOST_CHECK_EQUAL(miller_loop<CurveType>(G1_prec_elements[prec_A2], G2_prec_elements[prec_B2]),\n                      GT_elements[miller_loop_prec_A2_prec_B2]);\n    BOOST_CHECK_EQUAL(double_miller_loop<CurveType>(G1_prec_elements[prec_A1], G2_prec_elements[prec_B1],\n                                                   G1_prec_elements[prec_A2], G2_prec_elements[prec_B2]),\n                      GT_elements[double_miller_loop_prec_A1_prec_B1_prec_A2_prec_B2]);\n    BOOST_CHECK_EQUAL(miller_loop<CurveType>(G1_prec_elements[prec_A1], G2_prec_elements[prec_B1]) *\n                          miller_loop<CurveType>(G1_prec_elements[prec_A2], G2_prec_elements[prec_B2]),\n                      double_miller_loop<CurveType>(G1_prec_elements[prec_A1], G2_prec_elements[prec_B1],\n                                                   G1_prec_elements[prec_A2], G2_prec_elements[prec_B2]));\n    std::cout << \" * Miller loop tests finished.\" << std::endl << std::endl;\n}\n\ntemplate<typename ElementType>\nstruct field_element_init;\n\ntemplate<typename FieldParams>\nstruct field_element_init<fields::detail::element_fp<FieldParams>> {\n    using element_type = fields::detail::element_fp<FieldParams>;\n\n    template<typename ElementData>\n    static inline element_type process(const ElementData &element_data) {\n        return element_type(typename element_type::integral_type(element_data.second.data()));\n    }\n};\n\ntemplate<typename FieldParams>\nstruct field_element_init<fields::detail::element_fp2<FieldParams>> {\n    using element_type = fields::detail::element_fp2<FieldParams>;\n\n    template<typename ElementData>\n    static inline element_type process(const ElementData &element_data) {\n        // element_fp\n        using underlying_type = typename element_type::underlying_type;\n\n        std::array<underlying_type, 2> element_values;\n        auto i = 0;\n        for (auto &element_value : element_data.second) {\n            element_values[i++] = field_element_init<underlying_type>::process(element_value);\n        }\n        return element_type(element_values[0], element_values[1]);\n    }\n};\n\ntemplate<typename FieldParams>\nstruct field_element_init<fields::detail::element_fp3<FieldParams>> {\n    using element_type = fields::detail::element_fp3<FieldParams>;\n\n    template<typename ElementData>\n    static inline element_type process(const ElementData &element_data) {\n        // element_fp\n        using underlying_type = typename element_type::underlying_type;\n\n        std::array<underlying_type, 3> element_values;\n        auto i = 0;\n        for (auto &element_value : element_data.second) {\n            element_values[i++] = field_element_init<underlying_type>::process(element_value);\n        }\n        return element_type(element_values[0], element_values[1], element_values[2]);\n    }\n};\n\ntemplate<typename FieldParams>\nstruct field_element_init<fields::detail::element_fp4<FieldParams>> {\n    using element_type = fields::detail::element_fp4<FieldParams>;\n\n    template<typename ElementData>\n    static inline element_type process(const ElementData &element_data) {\n        // element_fp2 over element_fp\n        using underlying_type = typename element_type::underlying_type;\n\n        std::array<underlying_type, 2> element_values;\n        auto i = 0;\n        for (auto &element_value : element_data.second) {\n            element_values[i++] = field_element_init<underlying_type>::process(element_value);\n        }\n        return element_type(element_values[0], element_values[1]);\n    }\n};\n\ntemplate<typename FieldParams>\nstruct field_element_init<fields::detail::element_fp6_2over3<FieldParams>> {\n    using element_type = fields::detail::element_fp6_2over3<FieldParams>;\n\n    template<typename ElementData>\n    static inline element_type process(const ElementData &element_data) {\n        // element_fp3 over element_fp\n        using underlying_type = typename element_type::underlying_type;\n\n        std::array<underlying_type, 2> element_values;\n        auto i = 0;\n        for (auto &element_value : element_data.second) {\n            element_values[i++] = field_element_init<underlying_type>::process(element_value);\n        }\n        return element_type(element_values[0], element_values[1]);\n    }\n};\n\ntemplate<typename FieldParams>\nstruct field_element_init<fields::detail::element_fp12_2over3over2<FieldParams>> {\n    using element_type = fields::detail::element_fp12_2over3over2<FieldParams>;\n\n    template<typename ElementData>\n    static inline element_type process(const ElementData &element_data) {\n        // element_fp3 over element_fp2 over element_fp\n        using underlying_type_3over2 = typename element_type::underlying_type;\n        // element_fp2 over element_fp\n        using underlying_type = typename underlying_type_3over2::underlying_type;\n\n        std::array<underlying_type_3over2, 2> element_values;\n        std::array<underlying_type, 3> underlying_element_values;\n        auto i = 0;\n        for (auto &elem_3over2 : element_data.second) {\n            auto j = 0;\n            for (auto &elem_fp2 : elem_3over2.second) {\n                underlying_element_values[j++] = field_element_init<underlying_type>::process(elem_fp2);\n            }\n            element_values[i++] = underlying_type_3over2(underlying_element_values[0], underlying_element_values[1],\n                                                         underlying_element_values[2]);\n        }\n        return element_type(element_values[0], element_values[1]);\n    }\n};\n\ntemplate<typename CurveGroupValue, typename PointData>\nCurveGroupValue curve_point_init(const PointData &point_data) {\n    using group_value_type = CurveGroupValue;\n    using field_value_type = typename group_value_type::field_type::value_type;\n\n    std::array<field_value_type, 3> coordinates;\n    auto i = 0;\n    for (auto &coordinate : point_data.second) {\n        coordinates[i++] = field_element_init<field_value_type>::process(coordinate);\n    }\n    return group_value_type(coordinates[0], coordinates[1], coordinates[2]);\n}\n\ntemplate<typename FieldParams, typename TestSet>\nvoid pairing_test_Fr_init(std::vector<typename fields::detail::element_fp<FieldParams>> &elements,\n                          const TestSet &test_set) {\n    using value_type = typename fields::detail::element_fp<FieldParams>;\n\n    for (auto &elem : test_set.second.get_child(\"Fr\")) {\n        elements.emplace_back(field_element_init<value_type>::process(elem));\n    }\n}\n\ntemplate<typename CurveType, typename TestSet>\nvoid pairing_test_G1_init(std::vector<typename CurveType::template g1_type<>::value_type> &elements, const TestSet &test_set) {\n    \n    using value_type = typename CurveType::template g1_type<>::value_type;\n\n    for (auto &elem_coords : test_set.second.get_child(\"G1\")) {\n        elements.emplace_back(curve_point_init<value_type>(elem_coords));\n    }\n}\n\ntemplate<typename CurveType, typename TestSet>\nvoid pairing_test_G2_init(std::vector<typename CurveType::template g2_type<>::value_type> &elements, const TestSet &test_set) {\n    \n    using value_type = typename CurveType::template g2_type<>::value_type;\n\n    for (auto &elem_coords : test_set.second.get_child(\"G2\")) {\n        elements.emplace_back(curve_point_init<value_type>(elem_coords));\n    }\n}\n\ntemplate<typename CurveType, typename TestSet>\nvoid pairing_test_GT_init(std::vector<typename CurveType::gt_type::value_type> &elements, const TestSet &test_set) {\n    \n    using value_type = typename CurveType::gt_type::value_type;\n\n    for (auto &elem_GT : test_set.second.get_child(\"GT\")) {\n        elements.emplace_back(field_element_init<value_type>::process(elem_GT));\n    }\n}\n\ntemplate<typename TestSet>\nvoid pairing_test_g1_precomp_init(std::vector<typename pairing::pairing_policy<curves::bls12<381>>::g1_precomputed_type> &elements,\n                                  const TestSet &test_set) {\n    using curve_type = curves::bls12<381>;\n    using pairing_policy = typename pairing::pairing_policy<curve_type>;\n    using value_type = typename pairing_policy::g1_precomputed_type;\n    \n    using g1_field_value_type = typename curve_type::base_field_type::value_type;\n    using g2_field_value_type = typename curve_type::template g2_type<>::field_type::value_type;\n\n    for (auto &elem : test_set.second.get_child(\"g1_precomputed_type\")) {\n        elements.emplace_back(\n            value_type {field_element_init<g1_field_value_type>::process(elem.second.get_child(\"PX\").front()),\n                        field_element_init<g1_field_value_type>::process(elem.second.get_child(\"PY\").front())});\n    }\n}\n\ntemplate<typename TestSet>\nvoid pairing_test_g1_precomp_init(std::vector<typename pairing::pairing_policy<curves::mnt4<298>>::g1_precomputed_type> &elements,\n                                  const TestSet &test_set) {\n    using curve_type = curves::mnt4<298>;\n    using pairing_policy = typename pairing::pairing_policy<curve_type>;\n    using value_type = typename pairing_policy::g1_precomputed_type;\n\n    using g1_field_value_type = typename curve_type::base_field_type::value_type;\n    using g2_field_value_type = typename curve_type::template g2_type<>::field_type::value_type;\n\n    for (auto &elem : test_set.second.get_child(\"g1_precomputed_type\")) {\n        elements.emplace_back(\n            value_type {field_element_init<g1_field_value_type>::process(elem.second.get_child(\"PX\").front()),\n                        field_element_init<g1_field_value_type>::process(elem.second.get_child(\"PY\").front()),\n                        field_element_init<g2_field_value_type>::process(elem.second.get_child(\"PX_twist\").front()),\n                        field_element_init<g2_field_value_type>::process(elem.second.get_child(\"PY_twist\").front())});\n    }\n}\n\ntemplate<typename TestSet>\nvoid pairing_test_g1_precomp_init(std::vector<typename pairing::pairing_policy<curves::mnt6<298>>::g1_precomputed_type> &elements,\n                                  const TestSet &test_set) {\n    using curve_type = curves::mnt6<298>;\n    using pairing_policy = typename pairing::pairing_policy<curve_type>;\n    using value_type = typename pairing_policy::g1_precomputed_type;\n\n    using g1_field_value_type = typename curve_type::base_field_type::value_type;\n    using g2_field_value_type = typename curve_type::template g2_type<>::field_type::value_type;\n\n    for (auto &elem : test_set.second.get_child(\"g1_precomputed_type\")) {\n        elements.emplace_back(\n            value_type {field_element_init<g1_field_value_type>::process(elem.second.get_child(\"PX\").front()),\n                        field_element_init<g1_field_value_type>::process(elem.second.get_child(\"PY\").front()),\n                        field_element_init<g2_field_value_type>::process(elem.second.get_child(\"PX_twist\").front()),\n                        field_element_init<g2_field_value_type>::process(elem.second.get_child(\"PY_twist\").front())});\n    }\n}\n\ntemplate<typename TestSet>\nvoid pairing_test_g2_precomp_init(std::vector<typename pairing::pairing_policy<curves::bls12<381>>::g2_precomputed_type> &elements,\n                                  const TestSet &test_set) {\n    using curve_type = curves::bls12<381>;\n    using pairing_policy = typename pairing::pairing_policy<curve_type>;\n    using value_type = typename pairing_policy::g2_precomputed_type;\n    \n    using g1_field_value_type = typename curve_type::base_field_type::value_type;\n    using g2_field_value_type = typename curve_type::template g2_type<>::field_type::value_type;\n\n    using coeffs_type = value_type::coeffs_type;\n    using coeffs_value_type = g2_field_value_type;\n\n    for (auto &elem : test_set.second.get_child(\"g2_precomputed_type\")) {\n        elements.emplace_back(value_type());\n\n        elements.back().QX = field_element_init<g2_field_value_type>::process(elem.second.get_child(\"QX\").front());\n        elements.back().QY = field_element_init<g2_field_value_type>::process(elem.second.get_child(\"QY\").front());\n\n        for (auto &elem_coeffs : elem.second.get_child(\"coeffs\")) {\n            elements.back().coeffs.emplace_back(coeffs_type());\n\n            elements.back().coeffs.back().ell_0 =\n                field_element_init<coeffs_value_type>::process(elem_coeffs.second.get_child(\"ell_0\").front());\n            elements.back().coeffs.back().ell_VW =\n                field_element_init<coeffs_value_type>::process(elem_coeffs.second.get_child(\"ell_VW\").front());\n            elements.back().coeffs.back().ell_VV =\n                field_element_init<coeffs_value_type>::process(elem_coeffs.second.get_child(\"ell_VV\").front());\n        }\n    }\n}\n\ntemplate<typename TestSet>\nvoid pairing_test_g2_precomp_init(std::vector<typename pairing::pairing_policy<curves::mnt4<298>>::g2_precomputed_type> &elements,\n                                  const TestSet &test_set) {\n    using curve_type = curves::mnt4<298>;\n    using pairing_policy = typename pairing::pairing_policy<curve_type>;\n    using value_type = typename pairing_policy::g2_precomputed_type;\n\n    using g1_field_value_type = typename curve_type::base_field_type::value_type;\n    using g2_field_value_type = typename curve_type::template g2_type<>::field_type::value_type;\n\n    using dbl_coeffs_type = typename value_type::dbl_coeffs_type;\n    using add_coeffs_type = typename value_type::add_coeffs_type;\n    using dbl_coeffs_value_type = g2_field_value_type;\n    using add_coeffs_value_type = g2_field_value_type;\n\n    for (auto &elem : test_set.second.get_child(\"g2_precomputed_type\")) {\n        elements.emplace_back(value_type());\n\n        elements.back().QX = field_element_init<g2_field_value_type>::process(elem.second.get_child(\"QX\").front());\n        elements.back().QY = field_element_init<g2_field_value_type>::process(elem.second.get_child(\"QY\").front());\n        elements.back().QY2 = field_element_init<g2_field_value_type>::process(elem.second.get_child(\"QY2\").front());\n        elements.back().QX_over_twist =\n            field_element_init<g2_field_value_type>::process(elem.second.get_child(\"QX_over_twist\").front());\n        elements.back().QY_over_twist =\n            field_element_init<g2_field_value_type>::process(elem.second.get_child(\"QY_over_twist\").front());\n\n        for (auto &elem_coeffs : elem.second.get_child(\"dbl_coeffs\")) {\n            elements.back().dbl_coeffs.emplace_back(dbl_coeffs_type());\n\n            elements.back().dbl_coeffs.back().c_H =\n                field_element_init<dbl_coeffs_value_type>::process(elem_coeffs.second.get_child(\"c_H\").front());\n            elements.back().dbl_coeffs.back().c_4C =\n                field_element_init<dbl_coeffs_value_type>::process(elem_coeffs.second.get_child(\"c_4C\").front());\n            elements.back().dbl_coeffs.back().c_J =\n                field_element_init<dbl_coeffs_value_type>::process(elem_coeffs.second.get_child(\"c_J\").front());\n            elements.back().dbl_coeffs.back().c_L =\n                field_element_init<dbl_coeffs_value_type>::process(elem_coeffs.second.get_child(\"c_L\").front());\n        }\n\n        for (auto &elem_coeffs : elem.second.get_child(\"add_coeffs\")) {\n            elements.back().add_coeffs.emplace_back(add_coeffs_type());\n\n            elements.back().add_coeffs.back().c_L1 =\n                field_element_init<add_coeffs_value_type>::process(elem_coeffs.second.get_child(\"c_L1\").front());\n            elements.back().add_coeffs.back().c_RZ =\n                field_element_init<add_coeffs_value_type>::process(elem_coeffs.second.get_child(\"c_RZ\").front());\n        }\n    }\n}\n\ntemplate<typename TestSet>\nvoid pairing_test_g2_precomp_init(std::vector<typename pairing::pairing_policy<curves::mnt6<298>>::g2_precomputed_type> &elements,\n                                  const TestSet &test_set) {\n    using curve_type = curves::mnt6<298>;\n    using pairing_policy = typename pairing::pairing_policy<curve_type>;\n    using value_type = typename pairing_policy::g2_precomputed_type;\n    \n    using g1_field_value_type = typename curve_type::base_field_type::value_type;\n    using g2_field_value_type = typename curve_type::template g2_type<>::field_type::value_type;\n\n    using dbl_coeffs_type = typename value_type::dbl_coeffs_type;\n    using add_coeffs_type = typename value_type::add_coeffs_type;\n    using dbl_coeffs_value_type = g2_field_value_type;\n    using add_coeffs_value_type = g2_field_value_type;\n\n    for (auto &elem : test_set.second.get_child(\"g2_precomputed_type\")) {\n        elements.emplace_back(value_type());\n\n        elements.back().QX = field_element_init<g2_field_value_type>::process(elem.second.get_child(\"QX\").front());\n        elements.back().QY = field_element_init<g2_field_value_type>::process(elem.second.get_child(\"QY\").front());\n        elements.back().QY2 = field_element_init<g2_field_value_type>::process(elem.second.get_child(\"QY2\").front());\n        elements.back().QX_over_twist =\n            field_element_init<g2_field_value_type>::process(elem.second.get_child(\"QX_over_twist\").front());\n        elements.back().QY_over_twist =\n            field_element_init<g2_field_value_type>::process(elem.second.get_child(\"QY_over_twist\").front());\n\n        for (auto &elem_coeffs : elem.second.get_child(\"dbl_coeffs\")) {\n            elements.back().dbl_coeffs.emplace_back(dbl_coeffs_type());\n\n            elements.back().dbl_coeffs.back().c_H =\n                field_element_init<dbl_coeffs_value_type>::process(elem_coeffs.second.get_child(\"c_H\").front());\n            elements.back().dbl_coeffs.back().c_4C =\n                field_element_init<dbl_coeffs_value_type>::process(elem_coeffs.second.get_child(\"c_4C\").front());\n            elements.back().dbl_coeffs.back().c_J =\n                field_element_init<dbl_coeffs_value_type>::process(elem_coeffs.second.get_child(\"c_J\").front());\n            elements.back().dbl_coeffs.back().c_L =\n                field_element_init<dbl_coeffs_value_type>::process(elem_coeffs.second.get_child(\"c_L\").front());\n        }\n\n        for (auto &elem_coeffs : elem.second.get_child(\"add_coeffs\")) {\n            elements.back().add_coeffs.emplace_back(add_coeffs_type());\n\n            elements.back().add_coeffs.back().c_L1 =\n                field_element_init<add_coeffs_value_type>::process(elem_coeffs.second.get_child(\"c_L1\").front());\n            elements.back().add_coeffs.back().c_RZ =\n                field_element_init<add_coeffs_value_type>::process(elem_coeffs.second.get_child(\"c_RZ\").front());\n        }\n    }\n}\n\ntemplate<typename PairingT, typename Fr_value_type, typename G1_value_type, typename G2_value_type,\n         typename GT_value_type, typename g1_precomp_value_type, typename g2_precomp_value_type, typename TestSet>\nvoid pairing_test_init(std::vector<Fr_value_type> &Fr_elements,\n                       std::vector<G1_value_type> &G1_elements,\n                       std::vector<G2_value_type> &G2_elements,\n                       std::vector<GT_value_type> &GT_elements,\n                       std::vector<g1_precomp_value_type> &G1_prec_elements,\n                       std::vector<g2_precomp_value_type> &G2_prec_elements,\n                       const TestSet &test_set) {\n    pairing_test_Fr_init(Fr_elements, test_set);\n    pairing_test_G1_init<PairingT>(G1_elements, test_set);\n    pairing_test_G2_init<PairingT>(G2_elements, test_set);\n    pairing_test_GT_init<PairingT>(GT_elements, test_set);\n    pairing_test_g1_precomp_init(G1_prec_elements, test_set);\n    pairing_test_g2_precomp_init(G2_prec_elements, test_set);\n}\n\ntemplate<typename CurveType, typename TestSet>\nvoid pairing_operation_test(const TestSet &test_set) {\n    std::vector<typename CurveType::scalar_field_type::value_type> Fr_elements;\n    std::vector<typename CurveType::template g1_type<>::value_type> G1_elements;\n    std::vector<typename CurveType::template g2_type<>::value_type> G2_elements;\n    std::vector<typename CurveType::gt_type::value_type> GT_elements;\n    std::vector<typename pairing::pairing_policy<CurveType>::g1_precomputed_type> G1_prec_elements;\n    std::vector<typename pairing::pairing_policy<CurveType>::g2_precomputed_type> G2_prec_elements;\n\n    pairing_test_init<CurveType>(Fr_elements, G1_elements, G2_elements, GT_elements, G1_prec_elements, G2_prec_elements,\n                                test_set);\n    check_pairing_operations<CurveType>(Fr_elements, G1_elements, G2_elements, GT_elements, G1_prec_elements,\n                                       G2_prec_elements);\n}\n\nBOOST_AUTO_TEST_SUITE(curves_manual_tests)\n\n// TODO: fix pair_reduceding\nBOOST_DATA_TEST_CASE(pairing_operation_test_bls12_381, string_data(\"pairing_operation_test_bls12_381\"), data_set) {\n    using curve_type = typename curves::bls12<381>;\n\n    pairing_operation_test<curve_type>(data_set);\n}\n\nBOOST_DATA_TEST_CASE(pairing_operation_test_mnt4_298, string_data(\"pairing_operation_test_mnt4_298\"), data_set) {\n    using curve_type = typename curves::mnt4<298>;\n\n    pairing_operation_test<curve_type>(data_set);\n}\n\nBOOST_DATA_TEST_CASE(pairing_operation_test_mnt6_298, string_data(\"pairing_operation_test_mnt6_298\"), data_set) {\n    using curve_type = typename curves::mnt6<298>;\n\n    pairing_operation_test<curve_type>(data_set);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "335bb9d212dddfd39777a514712a48d147d7a815", "size": 43753, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/pairing.cpp", "max_stars_repo_name": "NilFoundation/crypto3-algebra", "max_stars_repo_head_hexsha": "b2e1a199d77c7023b32047fc5c95f66af5bf88d8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-09-20T18:56:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T06:58:28.000Z", "max_issues_repo_path": "test/pairing.cpp", "max_issues_repo_name": "tonlabs/crypto3-algebra", "max_issues_repo_head_hexsha": "b2e1a199d77c7023b32047fc5c95f66af5bf88d8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41.0, "max_issues_repo_issues_event_min_datetime": "2020-08-27T18:11:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-20T21:01:55.000Z", "max_forks_repo_path": "test/pairing.cpp", "max_forks_repo_name": "tonlabs/crypto3-algebra", "max_forks_repo_head_hexsha": "b2e1a199d77c7023b32047fc5c95f66af5bf88d8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-07-05T13:50:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T03:09:12.000Z", "avg_line_length": 47.2494600432, "max_line_length": 135, "alphanum_fraction": 0.6551093639, "num_tokens": 10629, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311856832191, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.4699482761170592}}
{"text": "#include \"lelantus_test_fixture.h\"\n\n#include \"../src/lelantus_prover.h\"\n#include \"../src/lelantus_verifier.h\"\n\n#define BOOST_TEST_MAIN\n#define BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n\nnamespace lelantus {\n\nclass ProtocolTests : public LelantusTestingSetup\n{\npublic:\n    ProtocolTests()\n        : params(Params::get_default())\n    {\n    }\n\npublic:\n    std::vector<PublicCoin> ExtractPublicCoins(std::vector<PrivateCoin> const &coins) const {\n        std::vector<PublicCoin> pubs;\n        pubs.reserve(coins.size());\n\n        for (auto const &c : coins) {\n            pubs.push_back(c.getPublicCoin());\n        }\n\n        return pubs;\n    }\n\n    std::vector<Scalar> ExtractSerials(\n        size_t anonymitySets,\n        std::vector<std::pair<PrivateCoin, uint32_t>> const &Cin,\n        std::vector<uint32_t>& groupIds) const {\n        std::vector<Scalar> serials;\n        for (auto const &in : Cin) {\n            serials.push_back(in.first.getSerialNumber());\n            groupIds.push_back(in.second);\n        }\n\n        return serials;\n    }\n\n    std::map<uint32_t, std::vector<PublicCoin>> GenerateAnonymitySets(std::initializer_list<size_t> sizes) const {\n        std::map<uint32_t, std::vector<PublicCoin>> sets;\n\n        uint32_t id = 0;\n        for (size_t s : sizes) {\n            std::vector<PublicCoin> set;\n            GenerateGroupElements(s, std::back_inserter(set));\n            sets[id] = set;\n            id++;\n        }\n\n        return sets;\n    }\n\npublic:\n    Params const *params;\n};\n\nBOOST_FIXTURE_TEST_SUITE(lelantus_protocol_tests, ProtocolTests)\n\nBOOST_AUTO_TEST_CASE(prove_verify)\n{\n    auto* params = Params::get_default();\n    size_t N = 100;\n\n    uint64_t v1(5);\n    PrivateCoin input_coin1(params ,v1);\n    std::vector<std::pair<PrivateCoin, uint32_t>> Cin = {{input_coin1, 0}};\n\n    std::vector <size_t> indexes = {0};\n\n    auto anonymity_sets = GenerateAnonymitySets({N});\n    anonymity_sets[0][0] = Cin[0].first.getPublicCoin();\n\n    Scalar Vin(5);\n    uint64_t Vout(6);\n    std::vector<PrivateCoin> Cout = {{params, 2}, {params, 1}};\n\n    uint64_t f(1);\n    LelantusProof proof;\n    SchnorrProof qkSchnorrProof;\n\n    LelantusProver prover(params, LELANTUS_TX_VERSION_4_5);\n    prover.proof(anonymity_sets, {}, Vin, Cin, indexes, {}, Vout, Cout, f,  proof, qkSchnorrProof);\n\n    std::vector<uint32_t> groupIds;\n    auto Sin = ExtractSerials(anonymity_sets.size(), Cin, groupIds);\n    auto Cout_Public = ExtractPublicCoins(Cout);\n\n    lelantus::LelantusVerifier verifier(params, LELANTUS_TX_VERSION_4_5);\n    BOOST_CHECK(verifier.verify(anonymity_sets, {}, Sin, {}, groupIds, Vin, Vout, f, Cout_Public, proof, qkSchnorrProof));\n}\n\nBOOST_AUTO_TEST_CASE(prove_verify_many_coins)\n{\n    size_t N = 100;\n\n    PrivateCoin input1(params ,2), input2(params, 2), input3(params, 1);\n    std::vector<std::pair<PrivateCoin, uint32_t>> Cin = {\n        {input1, 0}, {input2, 0}, {input3, 1}\n    };\n\n    std::vector <size_t> indexes = {0, 1, 0};\n\n    auto anonymity_sets = GenerateAnonymitySets({N, N});\n    anonymity_sets[0][0] = Cin[0].first.getPublicCoin();\n    anonymity_sets[0][1] = Cin[1].first.getPublicCoin();\n    anonymity_sets[1][0] = Cin[2].first.getPublicCoin();\n\n    Scalar Vin(5);\n    uint64_t Vout(6), f(1);\n    std::vector<PrivateCoin> Cout = {{params, 2}, {params, 1}};\n\n    LelantusProof proof;\n    SchnorrProof qkSchnorrProof;\n\n    LelantusProver prover(params, LELANTUS_TX_VERSION_4_5);\n    prover.proof(anonymity_sets, {}, Vin, Cin, indexes, {}, Vout, Cout, f,  proof, qkSchnorrProof);\n\n    std::vector<uint32_t> groupIds;\n    auto Sin = ExtractSerials(anonymity_sets.size(), Cin, groupIds);\n    auto Cout_Public = ExtractPublicCoins(Cout);\n\n    lelantus::LelantusVerifier verifier(params, LELANTUS_TX_VERSION_4_5);\n    BOOST_CHECK(verifier.verify(anonymity_sets, {}, Sin, {}, groupIds, Vin, Vout, f, Cout_Public, proof, qkSchnorrProof));\n    //After Lelantus new update (after version LELANTUS_TX_VERSION_4_5) following 2 verifications will fail, as schnorr proof challenge depends also on Vout, Vin  and fee values\n//    BOOST_CHECK(verifier.verify(anonymity_sets, {}, Sin, {}, groupIds, Vin + 1, Vout + 1, f, Cout_Public, proof));\n//    BOOST_CHECK(verifier.verify(anonymity_sets, {}, Sin, {}, groupIds, Vin, Vout + f, uint64_t(0), Cout_Public, proof));\n}\n\nBOOST_AUTO_TEST_CASE(imbalance_proof_should_fail)\n{\n    size_t N = 100;\n\n    // Input\n    PrivateCoin p1(params, 3);\n    std::vector<std::pair<PrivateCoin, uint32_t>> Cin = {{p1, 0}};\n\n    std::vector<size_t> indexs = {0};\n\n    auto anonymitySets = GenerateAnonymitySets({N});\n    anonymitySets[0][0] = Cin[0].first.getPublicCoin();\n\n    Scalar Vin(2); // Use this to verify\n    Scalar FakeVin(4); // Use this to generate proof\n\n    // Output\n    std::vector<PrivateCoin> Cout = {{params, 3}};\n    uint64_t Vout(3);\n    uint64_t f(1);\n\n    // Proof\n    LelantusProof proof;\n    SchnorrProof qkSchnorrProof;\n\n    // Should be prevent from prover\n    LelantusProver prover(params, LELANTUS_TX_VERSION_4_5);\n    BOOST_CHECK_THROW(prover.proof(anonymitySets, {}, Vin, Cin, indexs, {}, Vout, Cout, f, proof, qkSchnorrProof), std::runtime_error);\n\n    // Use fake vin\n    prover.proof(anonymitySets, {}, FakeVin, Cin, indexs, {}, Vout, Cout, f, proof, qkSchnorrProof);\n\n    // Verify\n    std::vector<uint32_t> groupIds;\n    auto Sin = ExtractSerials(anonymitySets.size(), Cin, groupIds);\n    auto publicCoins = ExtractPublicCoins(Cout);\n\n    LelantusVerifier verifier(params, LELANTUS_TX_VERSION_4_5);\n\n    // input: 2 + 3(anonymous), output: 3 + 3(anonymous) + 1(fee)\n    BOOST_CHECK(!verifier.verify(anonymitySets, {}, Sin, {}, groupIds, Vin, Vout, f, publicCoins, proof, qkSchnorrProof));\n\n    // Verify with output which is less than input also should fail\n    // input: 99 + 3(anonymous), output: 3 + 3(anonymous) + 1(fee)\n    Scalar newVin(99);\n    BOOST_CHECK(!verifier.verify(anonymitySets, {}, Sin, {}, groupIds, newVin, Vout, f, publicCoins, proof, qkSchnorrProof));\n}\n\nBOOST_AUTO_TEST_CASE(other_fail_to_validate)\n{\n    size_t N = 100;\n\n    // Input\n    PrivateCoin p1(params, 1), p2(params, 2);\n    std::vector<std::pair<PrivateCoin, uint32_t>> Cin = {{p1, 0}, {p2, 0}};\n\n    std::vector<size_t> indexs = {0, 1};\n\n    auto anonymitySets = GenerateAnonymitySets({N});\n    anonymitySets[0][0] = Cin[0].first.getPublicCoin();\n    anonymitySets[0][1] = Cin[1].first.getPublicCoin();\n\n    Scalar Vin(4);\n\n    // Output\n    std::vector<PrivateCoin> Cout = {{params, 1}, {params, 2}};\n    uint64_t Vout(3);\n    uint64_t f(1);\n\n    // Proof\n    LelantusProof proof;\n    SchnorrProof qkSchnorrProof;\n\n    // Should be prevent from prover\n    LelantusProver prover(params, LELANTUS_TX_VERSION_4_5);\n    prover.proof(anonymitySets, {}, Vin, Cin, indexs, {}, Vout, Cout, f, proof, qkSchnorrProof);\n\n    // Verify\n    std::vector<uint32_t> groupIds;\n    auto Sin = ExtractSerials(anonymitySets.size(), Cin, groupIds);\n    auto publicCoins = ExtractPublicCoins(Cout);\n\n    LelantusVerifier verifier(params, LELANTUS_TX_VERSION_4_5);\n\n    BOOST_CHECK(verifier.verify(anonymitySets, {}, Sin, {}, groupIds, Vin, Vout, f, publicCoins, proof, qkSchnorrProof));\n\n    // Invalid group\n    auto invalidAnonymitySets = anonymitySets;\n    invalidAnonymitySets[0].pop_back();\n    BOOST_CHECK(!verifier.verify(invalidAnonymitySets, {}, Sin, {}, groupIds, Vin, Vout, f, publicCoins, proof, qkSchnorrProof));\n\n    invalidAnonymitySets = anonymitySets;\n    invalidAnonymitySets[0].push_back(PrivateCoin(params, 1).getPublicCoin());\n    BOOST_CHECK(!verifier.verify(invalidAnonymitySets, {}, Sin, {}, groupIds, Vin, Vout, f, publicCoins, proof, qkSchnorrProof));\n\n    // Invalid serial\n    auto invalidSin = Sin;\n    invalidSin[1].randomize();\n    BOOST_CHECK(!verifier.verify(anonymitySets, {}, invalidSin, {}, groupIds, Vin, Vout, f, publicCoins, proof, qkSchnorrProof));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n} // namespace lelantus", "meta": {"hexsha": "521df73f1c3ed7366b9a46cf2dc9c29b092c441e", "size": 7915, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/protocol_tests.cpp", "max_stars_repo_name": "firoorg/mobileliblelantus", "max_stars_repo_head_hexsha": "7e48169a6d38ada7d1f072034886558d3b096340", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-07-05T10:23:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T02:09:38.000Z", "max_issues_repo_path": "tests/protocol_tests.cpp", "max_issues_repo_name": "firoorg/mobileliblelantus", "max_issues_repo_head_hexsha": "7e48169a6d38ada7d1f072034886558d3b096340", "max_issues_repo_licenses": ["MIT"], "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/protocol_tests.cpp", "max_forks_repo_name": "firoorg/mobileliblelantus", "max_forks_repo_head_hexsha": "7e48169a6d38ada7d1f072034886558d3b096340", "max_forks_repo_licenses": ["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.256302521, "max_line_length": 177, "alphanum_fraction": 0.673278585, "num_tokens": 2364, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311856832191, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.46994827611705914}}
{"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// Basic sanity check that header <boost/math/special_functions/spherical_harmonic.hpp>\n// #includes all the files that it needs to.\n//\n#include <boost/math/special_functions/spherical_harmonic.hpp>\n//\n// Note this header includes no other headers, this is\n// important if this test is to be meaningful:\n//\ninline void check_result_imp(std::complex<float>, std::complex<float>){}\ninline void check_result_imp(std::complex<double>, std::complex<double>){}\ninline void check_result_imp(std::complex<long double>, std::complex<long double>){}\n\n#include \"test_compile_result.hpp\"\n\n\n\nvoid check()\n{\n   check_result<std::complex<float> >(boost::math::spherical_harmonic<float>(u, i, f, f));\n   check_result<std::complex<double> >(boost::math::spherical_harmonic<double>(u, i, d, d));\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   check_result<std::complex<long double> >(boost::math::spherical_harmonic<long double>(u, i, l, l));\n#endif\n\n   check_result<float>(boost::math::spherical_harmonic_r<float>(u, i, f, f));\n   check_result<double>(boost::math::spherical_harmonic_r<double>(u, i, d, d));\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   check_result<long double>(boost::math::spherical_harmonic_r<long double>(u, i, l, l));\n#endif\n\n   check_result<float>(boost::math::spherical_harmonic_i<float>(u, i, f, f));\n   check_result<double>(boost::math::spherical_harmonic_i<double>(u, i, d, d));\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   check_result<long double>(boost::math::spherical_harmonic_i<long double>(u, i, l, l));\n#endif\n}\n\n\n", "meta": {"hexsha": "741d3b2d03e8c98747671dffe3690dc641f07a9e", "size": 1778, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/test/compile_test/sf_sph_harm_incl_test.cpp", "max_stars_repo_name": "mike-code/boost_1_38_0", "max_stars_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-07-31T02:19:48.000Z", "max_stars_repo_stars_event_max_datetime": "2017-07-31T02:19:48.000Z", "max_issues_repo_path": "libs/math/test/compile_test/sf_sph_harm_incl_test.cpp", "max_issues_repo_name": "boost-cmake/vintage", "max_issues_repo_head_hexsha": "dcfb7da3177134eddaee6789d6f582259cb0d6ee", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/math/test/compile_test/sf_sph_harm_incl_test.cpp", "max_forks_repo_name": "boost-cmake/vintage", "max_forks_repo_head_hexsha": "dcfb7da3177134eddaee6789d6f582259cb0d6ee", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-07T05:20:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-07T05:20:43.000Z", "avg_line_length": 40.4090909091, "max_line_length": 102, "alphanum_fraction": 0.7480314961, "num_tokens": 468, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311757235431, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.46994827017677826}}
{"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 file if you have any questions.\n// Author: Chris Sweeney (cmsweeney@cs.ucsb.edu)\n\n#include <math.h>\n#include <glog/logging.h>\n#include <Eigen/Core>\n#include <ctime>\n#include <random>\n#include \"gtest/gtest.h\"\n\n#include \"theia/test/test_utils.h\"\n#include \"theia/sfm/pose/four_point_focal_length.h\"\n\nnamespace {\nusing Eigen::Map;\nusing Eigen::Matrix;\nusing Eigen::Matrix3d;\nusing Eigen::Vector3d;\n\nvoid P4pfTestWithNoise(const Matrix3d& gt_rotation,\n                       const Vector3d& gt_translation,\n                       const double focal_length,\n                       const std::vector<Vector3d>& world_points_vector,\n                       const double noise,\n                       const double reproj_tolerance) {\n  Map<const Matrix<double, 3, 4> > world_points(world_points_vector[0].data());\n\n  // Camera intrinsics matrix.\n  const Matrix3d camera_matrix =\n      Eigen::DiagonalMatrix<double, 3>(focal_length, focal_length, 1.0);\n  // Create the projection matrix P = K * [R t].\n  Matrix<double, 3, 4> gt_projection;\n  gt_projection << gt_rotation, gt_translation;\n  gt_projection = camera_matrix * gt_projection;\n\n  // Reproject 3D points to get undistorted image points.\n  std::vector<Eigen::Vector2d> image_points_vector(5);\n  Map<Matrix<double, 2, 4> > image_point(image_points_vector[0].data());\n  image_point = (gt_projection * world_points.colwise().homogeneous()).colwise()\n      .hnormalized();\n\n  // Add noise to distorted image points.\n  if (noise) {\n    std::default_random_engine generator;\n    std::normal_distribution<double> distribution(0.0, noise);\n    for (int i = 0; i < 4; i++) {\n      image_point.col(i).x() += distribution(generator);\n      image_point.col(i).y() += distribution(generator);\n    }\n  }\n\n  // Run P5pf algorithm.\n  std::vector<Matrix<double, 3, 4> > soln_projection;\n  int num_solns = theia::FourPointPoseAndFocalLength(\n      image_points_vector, world_points_vector, &soln_projection);\n  ASSERT_GT(num_solns, 0);\n\n  bool matched_transform = false;\n  for (int i = 0; i < num_solns; ++i) {\n    matched_transform = true;\n    // Check that the reprojection error is very small.\n    for (int n = 0; n < 4; n++) {\n      Vector3d reproj_point =\n          soln_projection[i] * world_points.col(n).homogeneous();\n      const double reproj_error =\n          (reproj_point.hnormalized() - image_point.col(n)).norm();\n      if (reproj_error > reproj_tolerance) {\n        matched_transform = false;\n        break;\n      }\n    }\n    if (matched_transform) {\n      break;\n    }\n  }\n  // One of the solutions must have been a valid solution.\n  EXPECT_TRUE(matched_transform);\n}\n\nvoid BasicTest(const double noise, const double reproj_tolerance) {\n  const double focal_length = 800;\n\n  const double x = -0.10;  // rotation of the view around x axis\n  const double y = -0.20;  // rotation of the view around y axis\n  const double z = 0.30;   // rotation of the view around z axis\n\n  // Create a ground truth pose.\n  Matrix3d Rz, Ry, Rx;\n  Rz << cos(z), sin(z), 0,\n        -sin(z), cos(z), 0,\n        0, 0, 1;\n  Ry << cos(y), 0, -sin(y),\n        0, 1, 0,\n        sin(y), 0, cos(y);\n  Rx << 1, 0, 0,\n        0, cos(x), sin(x),\n        0, -sin(x), cos(x);\n  const Matrix3d gt_rotation = Rz * Ry * Rx;\n  const Vector3d gt_translation = Vector3d(-0.00950692, 0.0171496, 0.0508743);\n\n  // Create 3D world points that are viable based on the camera intrinsics and\n  // extrinsics.\n  std::vector<Vector3d> world_points_vector = { Vector3d(-1.0, 0.5, 1.2),\n                                                Vector3d(-0.79, -0.68, 1.9),\n                                                Vector3d(1.42, 1.01, 2.19),\n                                                Vector3d(0.87, -0.49, 0.89) };\n\n  P4pfTestWithNoise(gt_rotation, gt_translation, focal_length,\n                    world_points_vector, noise, reproj_tolerance);\n}\n\nvoid RandomTestWithNoise(const double noise, const double reproj_tolerance) {\n  // Seed random number generator.\n  srand(time(NULL));\n\n  const double kBaseline = 0.25;\n\n  // focal length (values used in the ICCV paper)\n  std::default_random_engine generator;\n  std::uniform_real_distribution<double> distribution(0.0, 1.0);\n  const double focal_length = distribution(generator) * 50.0 + 600;\n\n  // Rotation areound x, y, z axis.\n  const double x = distribution(generator) * 0.5 - 0.25;\n  const double y = distribution(generator) * 0.5 - 0.25;\n  const double z = distribution(generator) * 0.5 - 0.25;\n\n  // Create a ground truth pose.\n  Matrix3d Rz, Ry, Rx;\n  Rz << cos(z), sin(z), 0,\n        -sin(z), cos(z), 0,\n        0, 0, 1;\n  Ry << cos(y), 0, -sin(y),\n        0, 1, 0,\n        sin(y), 0, cos(y);\n  Rx << 1, 0, 0,\n        0, cos(x), sin(x),\n        0, -sin(x), cos(x);\n  const Matrix3d gt_rotation = Rz * Ry * Rx;\n  const Vector3d gt_translation = Vector3d::Random() * kBaseline;\n\n  // Create 3D world points that are viable based on the camera intrinsics and\n  // extrinsics.\n  std::vector<Vector3d> world_points_vector(4);\n  Map<Matrix<double, 3, 4> > world_points(world_points_vector[0].data());\n  world_points.row(2) = 2.0 * Matrix<double, 1, 4>::Random().array() + 2.0;\n  world_points.row(1) = 2.0 * Matrix<double, 1, 4>::Random();\n  world_points.row(0) = 2.0 * Matrix<double, 1, 4>::Random();\n\n  P4pfTestWithNoise(gt_rotation, gt_translation, focal_length,\n                    world_points_vector, noise, reproj_tolerance);\n}\n\nTEST(P4pf, BasicTest) {\n  BasicTest(0.0, 1e-4);\n}\n\nTEST(P4pf, BasicNoiseTest) {\n  BasicTest(0.5, 10.0);\n}\n\nTEST(P4pf, RandomTest) {\n  RandomTestWithNoise(0.0, 0.1);\n}\n\n}  // namespace\n", "meta": {"hexsha": "0b884cf5274d60ce4a0ca7d0a6d6259770c8982a", "size": 7283, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/sfm/pose/four_point_focal_length_test.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/pose/four_point_focal_length_test.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/pose/four_point_focal_length_test.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": 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": 36.7828282828, "max_line_length": 80, "alphanum_fraction": 0.6605794316, "num_tokens": 1961, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952052, "lm_q2_score": 0.6688802735722128, "lm_q1q2_score": 0.46990849698320725}}
{"text": "//=======================================================================\n// Copyright 2001 Jeremy G. Siek, Andrew Lumsdaine, Lie-Quan Lee,\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/depth_first_search.hpp>\n#include <boost/range/irange.hpp>\n#include <boost/pending/indirect_cmp.hpp>\n\n#include <iostream>\n\nusing namespace boost;\ntemplate < typename TimeMap >\nclass dfs_time_visitor : public default_dfs_visitor\n{\n    typedef typename property_traits< TimeMap >::value_type T;\n\npublic:\n    dfs_time_visitor(TimeMap dmap, TimeMap fmap, T& t)\n    : m_dtimemap(dmap), m_ftimemap(fmap), m_time(t)\n    {\n    }\n    template < typename Vertex, typename Graph >\n    void discover_vertex(Vertex u, const Graph& g) const\n    {\n        put(m_dtimemap, u, m_time++);\n    }\n    template < typename Vertex, typename Graph >\n    void finish_vertex(Vertex u, const Graph& g) const\n    {\n        put(m_ftimemap, u, m_time++);\n    }\n    TimeMap m_dtimemap;\n    TimeMap m_ftimemap;\n    T& m_time;\n};\n\nint main()\n{\n    // Select the graph type we wish to use\n    typedef adjacency_list< vecS, vecS, directedS > graph_t;\n    typedef graph_traits< graph_t >::vertices_size_type size_type;\n    // Set up the vertex names\n    enum\n    {\n        u,\n        v,\n        w,\n        x,\n        y,\n        z,\n        N\n    };\n    char name[] = { 'u', 'v', 'w', 'x', 'y', 'z' };\n    // Specify the edges in the graph\n    typedef std::pair< int, int > E;\n    E edge_array[] = { E(u, v), E(u, x), E(x, v), E(y, x), E(v, y), E(w, y),\n        E(w, z), E(z, z) };\n#if defined(BOOST_MSVC) && BOOST_MSVC <= 1300\n    graph_t g(N);\n    for (std::size_t j = 0; j < sizeof(edge_array) / sizeof(E); ++j)\n        add_edge(edge_array[j].first, edge_array[j].second, g);\n#else\n    graph_t g(edge_array, edge_array + sizeof(edge_array) / sizeof(E), N);\n#endif\n\n    // discover time and finish time properties\n    std::vector< size_type > dtime(num_vertices(g));\n    std::vector< size_type > ftime(num_vertices(g));\n    typedef iterator_property_map< std::vector< size_type >::iterator,\n        property_map< graph_t, vertex_index_t >::const_type >\n        time_pm_type;\n    time_pm_type dtime_pm(dtime.begin(), get(vertex_index, g));\n    time_pm_type ftime_pm(ftime.begin(), get(vertex_index, g));\n    size_type t = 0;\n    dfs_time_visitor< time_pm_type > vis(dtime_pm, ftime_pm, t);\n\n    depth_first_search(g, visitor(vis));\n\n    // use std::sort to order the vertices by their discover time\n    std::vector< size_type > discover_order(N);\n    integer_range< size_type > r(0, N);\n    std::copy(r.begin(), r.end(), discover_order.begin());\n    std::sort(discover_order.begin(), discover_order.end(),\n        indirect_cmp< time_pm_type, std::less< size_type > >(dtime_pm));\n    std::cout << \"order of discovery: \";\n    int i;\n    for (i = 0; i < N; ++i)\n        std::cout << name[discover_order[i]] << \" \";\n\n    std::vector< size_type > finish_order(N);\n    std::copy(r.begin(), r.end(), finish_order.begin());\n    std::sort(finish_order.begin(), finish_order.end(),\n        indirect_cmp< time_pm_type, std::less< size_type > >(ftime_pm));\n    std::cout << std::endl << \"order of finish: \";\n    for (i = 0; i < N; ++i)\n        std::cout << name[finish_order[i]] << \" \";\n    std::cout << std::endl;\n\n    return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "fff17bfddb6a25823ae1ca4821af39efddc9f822", "size": 3530, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/graph/example/dfs-example.cpp", "max_stars_repo_name": "uosorio/heroku_face", "max_stars_repo_head_hexsha": "7d6465e71dba17a15d8edaef520adb2fcd09d91e", "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": "3rdparty/boost_1_73_0/libs/graph/example/dfs-example.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 130.0, "max_issues_repo_issues_event_min_datetime": "2016-06-22T22:11:25.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-29T20:24:09.000Z", "max_forks_repo_path": "Libs/boost_1_76_0/libs/graph/example/dfs-example.cpp", "max_forks_repo_name": "Antd23rus/S2DE", "max_forks_repo_head_hexsha": "47cc7151c2934cd8f0399a9856c1e54894571553", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2015-07-08T19:18:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-14T16:39:56.000Z", "avg_line_length": 33.619047619, "max_line_length": 76, "alphanum_fraction": 0.6059490085, "num_tokens": 950, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.4699084918748419}}
{"text": "\n//          Copyright John McFarlane 2015 - 2016.\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 <sg14/cstdint>\n\n#include <gtest/gtest.h>\n\n#if defined(SG14_BOOST_ENABLED)\n#include <boost/integer.hpp>\n#endif\n\nusing std::declval;\nusing std::is_same;\n\nnamespace sample1 {\n    // range of a*b is UCHAR_MAX*UCHAR_MAX but range of return value is UCHAR_MAX\n    uint8_t multiply(uint8_t a, uint8_t b)\n    {\n        return a*b;\n    }\n\n    // sample 1 tests\n    using single_width = uint8_t;\n\n    static_assert(UCHAR_MAX==255, \"incorrect assumption about value of UCHAR_MAX\");\n    static_assert(UCHAR_MAX*UCHAR_MAX==65025, \"incorrect assumption about value of UCHAR_MAX\");\n\n    TEST(p0381, multiply_uint8_ok)\n    {\n        ASSERT_EQ(100, multiply(10, 10));\n    }\n\n    TEST(p0381, multiply_uint8_overflow)\n    {\n        ASSERT_NE(400, multiply(20, 20));\n    }\n}\n\n#if (__cplusplus>=201402L)\nnamespace sample2 {\n    // range of a*b is UINT_MAX*UINT_MAX but range of return value is UINT_MAX\n    auto multiply(unsigned a, unsigned b)\n    {\n        return a*b;\n    }\n\n    // sample 2 tests\n    using wide_type = unsigned long long;\n\n    static_assert(sizeof(wide_type)>=sizeof(unsigned)*2,\n            \"the following tests assume unsigned long long is twice the size of unsigned\");\n    static_assert(is_same<decltype(declval<unsigned>()*declval<unsigned>()), unsigned>::value,\n            \"incorrect assumption about type of result of unsigned * unsigned\");\n\n    TEST(p0381, multiply_unsigned_ok)\n    {\n        ASSERT_EQ(400u, multiply(20u, 20u));\n    }\n\n    TEST(p0381, multiply_unsigned_overflow)\n    {\n        ASSERT_NE(static_cast<wide_type>(UINT_MAX)*static_cast<wide_type>(UINT_MAX),\n                static_cast<wide_type>(multiply(UINT_MAX, UINT_MAX)));\n    }\n}\n\nnamespace sample3 {\n    auto multiply(uint32_t a, uint32_t b)\n    {\n        using result_type = uint64_t;\n        return result_type{a}*result_type{b};\n    }\n\n    // sample 3 tests\n    static_assert(is_same<uint64_t, decltype(multiply(declval<uint32_t>(), declval<uint32_t>()))>::value,\n            \"incorrect assumption about result of multiply function\");\n\n    TEST(p0381, multiply_unsigned_ok)\n    {\n        ASSERT_EQ(400u, multiply(20u, 20u));\n    }\n\n    TEST(p0381, multiply_unsigned_still_ok)\n    {\n        ASSERT_EQ(static_cast<uint64_t>(UINT_MAX)*static_cast<uint64_t>(UINT_MAX),\n                static_cast<uint64_t>(multiply(UINT_MAX, UINT_MAX)));\n    }\n}\n\nnamespace sample4 {\n    // Sample 4 intentionally does not exist. If it did, there would be no need for P0381!\n}\n\n#if defined(SG14_BOOST_ENABLED)\nnamespace sample5 {\n    template<class Operand>\n    auto multiply(Operand a, Operand b)\n    {\n        constexpr auto operand_width = sizeof(Operand)*CHAR_BIT*2;\n        using result_type = typename boost::uint_t<operand_width>::fast;\n        return result_type{a}*result_type{b};\n    }\n\n    // sample 5 tests are a lot like sample 3 tests\n\n    // they are more generic\n#if ! defined(__APPLE__)    // uint64_t is a different type depending on the version of XCode\n    static_assert(is_same<uint64_t, decltype(multiply(declval<uint32_t>(), declval<uint32_t>()))>::value,\n            \"incorrect assumption about result of multiply function\");\n#endif\n    static_assert(is_same<uint32_t, decltype(multiply(declval<uint16_t>(), declval<uint16_t>()))>::value,\n            \"incorrect assumption about result of multiply function\");\n\n    // but don't do so well with signed types\n//    static_assert(is_same<int64_t, decltype(multiply(declval<int32_t>(), declval<int32_t>()))>::value,\n//            \"incorrect assumption about result of multiply function\");\n//    static_assert(is_same<int32_t, decltype(multiply(declval<int16_t>(), declval<int16_t>()))>::value,\n//            \"incorrect assumption about result of multiply function\");\n\n    TEST(p0381, multiply_unsigned_ok)\n    {\n        ASSERT_EQ(400u, multiply(20u, 20u));\n    }\n\n    TEST(p0381, multiply_unsigned_still_ok)\n    {\n        ASSERT_EQ(static_cast<uint64_t>(UINT_MAX)*static_cast<uint64_t>(UINT_MAX),\n                static_cast<uint64_t>(multiply(UINT_MAX, UINT_MAX)));\n    }\n}\n#endif  // defined(SG14_BOOST_ENABLED)\n#endif  // C++14\n\nnamespace determining {\n    using sg14::width;\n\n    static_assert(width<uint16_t>::value == 16, \"the width of uint16_t is exactly 16 bits\");\n    static_assert(width<long long>::value >= 64, \"long long has a width of at least 64 bits\");\n    static_assert(width<long>::value >= width<short>::value, \"short is no longer than long\");\n    static_assert(width<wchar_t>::value >= width<char>::value, \"a wide character is at least as wide as a character\");\n}\n\nnamespace specifiying {\n    using sg14::set_width_t;\n    using sg14::width;\n    static_assert(is_same<set_width_t<signed, 8>, int8_t>::value, \"int8_t is a signed 8-bit integer\");\n    static_assert(is_same<set_width_t<unsigned, 32>, uint32_t>::value, \"uint32_t is an unsigned 32-bit integer\");\n    static_assert(is_same<set_width_t<uint64_t, 16>, uint16_t>::value, \"a 64-bit unsigned integer was narrowed to 16-bits\");\n    static_assert(is_same<set_width_t<char, 64>, int64_t>::value || is_same<set_width_t<char, 64>, uint64_t>::value, \"char may or may not be signed so the result may be uint64_t or int64_t\");\n    static_assert(width<set_width_t<int, 10>>::value >= 10, \"result must be at least 10 bits wide\");\n}\n", "meta": {"hexsha": "4460218fb6424efbcabef045fcc08027d3c2e138", "size": 5462, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/p0381.cpp", "max_stars_repo_name": "danitzarqp106/Prueba", "max_stars_repo_head_hexsha": "06635ca46a68306073e542b7cb4b519858e44dc2", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/test/p0381.cpp", "max_issues_repo_name": "danitzarqp106/Prueba", "max_issues_repo_head_hexsha": "06635ca46a68306073e542b7cb4b519858e44dc2", "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/test/p0381.cpp", "max_forks_repo_name": "danitzarqp106/Prueba", "max_forks_repo_head_hexsha": "06635ca46a68306073e542b7cb4b519858e44dc2", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.2387096774, "max_line_length": 191, "alphanum_fraction": 0.6849139509, "num_tokens": 1394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.4699084918748419}}
{"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 *      110207    B. Romgens        File created.\n *      110215    K. Kumar          Minor modifications to layout, comments\n *                                  and variable-naming.\n *      110411    K. Kumar          Added unit test for\n *                                  convertCartesianToSpherical( ) function.\n *      110701    K. Kumar          Updated failing tests with relative errors.\n *      110708    K. Kumar          Added unit tests for computeSampleMean( )\n *                                  and computeSampleVariance( ) functions.\n *      110905    S. Billemont      Reorganized includes.\n *                                  Moved (con/de)structors and getter/setters to header.\n *      111111    K. Kumar          Strange error with convertCylindricalToCartesian function;\n *                                  achieved precision of results is less than machine precision,\n *                                  fixed by using slightly larger precision tolerance.\n *      120202    K. Kumar          Moved unit tests from unitTestBasicMathematicsFunctions.h/.cpp;\n *                                  rewrote unit tests using Boost unit test framework.\n *\n *    References\n *\n *    Notes\n *\n */\n\n#define BOOST_TEST_MAIN\n\n#include <limits>\n\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/unit_test.hpp>\n\n#include \"Tudat/Mathematics/Statistics/basicStatistics.h\"\n\nnamespace tudat\n{\nnamespace unit_tests\n{\n\nBOOST_AUTO_TEST_SUITE( test_basic_statistics )\n\n//! Test if sample mean is computed correctly.\nBOOST_AUTO_TEST_CASE( testSampleMean )\n{\n    // Test computation of sample mean on finite population using unbiased estimators.\n    // The expected values are computed using the Microsoft Excel the AVERAGE( ) function.\n\n    // Declare vector of sample data.\n    std::vector< double > sampleData;\n\n    // Populate vector with sample data.\n    sampleData.push_back( 2.5 );\n    sampleData.push_back( 6.4 );\n    sampleData.push_back( 8.9 );\n    sampleData.push_back( 12.7 );\n    sampleData.push_back( 15.0 );\n\n    // Set expected sample mean.\n    double expectedSampleMean = 9.1;\n\n    // Compute sample mean.\n    double computedSampleMean = statistics::computeSampleMean( sampleData );\n\n    // Check if computed sample mean matches expected value.\n    BOOST_CHECK_CLOSE_FRACTION( computedSampleMean, expectedSampleMean,\n                                std::numeric_limits< double >::epsilon( ) );\n}\n\n//! Test if sample variance is computed correctly.\nBOOST_AUTO_TEST_CASE( testSampleVariance )\n{\n    // Test computation of sample variance on finite population using unbiased estimators.\n    // The expected values are computed using the Microsoft Excel the VAR( ) function.\n\n    // Declare vector of sample data.\n    std::vector< double > sampleData;\n\n    // Populate vector with sample data.\n    sampleData.push_back( 2.5 );\n    sampleData.push_back( 6.4 );\n    sampleData.push_back( 8.9 );\n    sampleData.push_back( 12.7 );\n    sampleData.push_back( 15.0 );\n\n    // Declare expected sample variance.\n    double expectedSampleVariance = 24.665;\n\n    // Compute sample variance.\n    double computedSampleVariance = statistics::computeSampleVariance( sampleData );\n\n    // Check if computed sample variance matches expected value.\n    BOOST_CHECK_CLOSE_FRACTION( computedSampleVariance, expectedSampleVariance,\n                                std::numeric_limits< double >::epsilon( ) );\n}\n\nBOOST_AUTO_TEST_SUITE_END( )\n\n} // namespace unit_tests\n} // namespace tudat\n", "meta": {"hexsha": "6c5628fe87b4b02a57afa82ff42c3f72ca3bb423", "size": 5235, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Mathematics/Statistics/UnitTests/unitTestBasicStatistics.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/Statistics/UnitTests/unitTestBasicStatistics.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/Statistics/UnitTests/unitTestBasicStatistics.cpp", "max_forks_repo_name": "JPelamatti/ThesisTUDAT", "max_forks_repo_head_hexsha": "b94ce35fb7c8fa44ae83238e296a979dfa3adfe8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-05-30T03:42:22.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-30T03:42:22.000Z", "avg_line_length": 42.5609756098, "max_line_length": 99, "alphanum_fraction": 0.6783190067, "num_tokens": 1092, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300449389326, "lm_q2_score": 0.6688802735722128, "lm_q1q2_score": 0.4699084886514522}}
{"text": "\n\n/* --------------------------------------------------------------------- \n * \n * Copyright (C) 2008 - 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: Martin Kronbichler, Uppsala University, \n *          Wolfgang Bangerth, Texas A&M University, \n *          Timo Heister, University of Goettingen, 2008-2011 \n */ \n\n\n// @sect3{Include files}  \n\n// \u50cf\u5f80\u5e38\u4e00\u6837\uff0c\u7b2c\u4e00\u4e2a\u4efb\u52a1\u662f\u5305\u62ec\u8fd9\u4e9b\u8457\u540d\u7684deal.II\u5e93\u6587\u4ef6\u548c\u4e00\u4e9bC++\u5934\u6587\u4ef6\u7684\u529f\u80fd\u3002\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#include <deal.II/base/conditional_ostream.h> \n#include <deal.II/base/work_stream.h> \n#include <deal.II/base/timer.h> \n#include <deal.II/base/parameter_handler.h> \n\n#include <deal.II/lac/full_matrix.h> \n#include <deal.II/lac/solver_bicgstab.h> \n#include <deal.II/lac/solver_cg.h> \n#include <deal.II/lac/solver_gmres.h> \n#include <deal.II/lac/affine_constraints.h> \n#include <deal.II/lac/block_sparsity_pattern.h> \n#include <deal.II/lac/trilinos_parallel_block_vector.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_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/filtered_iterator.h> \n#include <deal.II/grid/manifold_lib.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_tools.h> \n\n#include <deal.II/fe/fe_q.h> \n#include <deal.II/fe/fe_dgq.h> \n#include <deal.II/fe/fe_dgp.h> \n#include <deal.II/fe/fe_system.h> \n#include <deal.II/fe/fe_values.h> \n#include <deal.II/fe/mapping_q.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/solution_transfer.h> \n\n#include <fstream> \n#include <iostream> \n#include <limits> \n#include <locale> \n#include <string> \n\n// \u8fd9\u662f\u552f\u4e00\u4e00\u4e2a\u65b0\u7684\u5305\u542b\u6587\u4ef6\uff1a\u5b83\u5f15\u5165\u4e86\u76f8\u5f53\u4e8e parallel::distributed::SolutionTransfer \u7684 dealii::SolutionTransfer \u7c7b\uff0c\u7528\u4e8e\u5728\u7f51\u683c\u7ec6\u5316\u65f6\u5c06\u89e3\u51b3\u65b9\u6848\u4ece\u4e00\u4e2a\u7f51\u683c\u5e26\u5230\u4e0b\u4e00\u4e2a\u7f51\u683c\uff0c\u4f46\u5728\u5e76\u884c\u5206\u5e03\u5f0f\u4e09\u89d2\u5f62\u8ba1\u7b97\u7684\u60c5\u51b5\u4e0b\u3002\n\n#include <deal.II/distributed/solution_transfer.h> \n\n// \u4ee5\u4e0b\u662f\u7528\u4e8e\u5e76\u884c\u5206\u5e03\u5f0f\u8ba1\u7b97\u7684\u7c7b\uff0c\u5728 step-40 \u4e2d\u5df2\u7ecf\u5168\u90e8\u4ecb\u7ecd\u8fc7\u3002\n\n#include <deal.II/base/index_set.h> \n#include <deal.II/distributed/tria.h> \n#include <deal.II/distributed/grid_refinement.h> \n\n// \u63a5\u4e0b\u6765\u7684\u6b65\u9aa4\u4e0e\u4e4b\u524d\u6240\u6709\u7684\u6559\u7a0b\u7a0b\u5e8f\u4e00\u6837\u3002\u6211\u4eec\u628a\u6240\u6709\u4e1c\u897f\u653e\u5230\u4e00\u4e2a\u81ea\u5df1\u7684\u547d\u540d\u7a7a\u95f4\u4e2d\uff0c\u7136\u540e\u628adeal.II\u7684\u7c7b\u548c\u51fd\u6570\u5bfc\u5165\u5176\u4e2d\u3002\n\nnamespace Step32 \n{ \n  using namespace dealii; \n// @sect3{Equation data}  \n\n// \u5728\u4ee5\u4e0b\u547d\u540d\u7a7a\u95f4\u4e2d\uff0c\u6211\u4eec\u5b9a\u4e49\u4e86\u63cf\u8ff0\u95ee\u9898\u7684\u5404\u79cd\u65b9\u7a0b\u6570\u636e\u3002\u8fd9\u5bf9\u5e94\u4e8e\u4f7f\u95ee\u9898\u81f3\u5c11\u6709\u4e00\u70b9\u73b0\u5b9e\u6027\u7684\u5404\u4e2a\u65b9\u9762\uff0c\u5e76\u4e14\u5728\u4ecb\u7ecd\u4e2d\u5bf9\u6d4b\u8bd5\u6848\u4f8b\u7684\u63cf\u8ff0\u4e2d\u5df2\u7ecf\u8be6\u5c3d\u5730\u8ba8\u8bba\u4e86\u8fd9\u4e9b\u65b9\u9762\u3002\n\n// \u6211\u4eec\u4ece\u4e00\u4e9b\u5177\u6709\u5e38\u6570\u7684\u7cfb\u6570\u5f00\u59cb\uff08\u6570\u503c\u540e\u9762\u7684\u6ce8\u91ca\u8868\u793a\u5176\u7269\u7406\u5355\u4f4d\uff09\u3002\n\n  namespace EquationData \n  { \n    constexpr double eta                   = 1e21;    /* Pa s       */ \n\n\n    constexpr double kappa                 = 1e-6;    /* m^2 / s    */ \n\n\n    constexpr double reference_density     = 3300;    /* kg / m^3   */ \n\n\n    constexpr double reference_temperature = 293;     /* K          */ \n\n\n    constexpr double expansion_coefficient = 2e-5;    /* 1/K        */ \n\n\n    constexpr double specific_heat         = 1250;    /* J / K / kg */ \n\n\n    constexpr double radiogenic_heating    = 7.4e-12; /* W / kg     */ \n\n\n\n    constexpr double R0 = 6371000. - 2890000.; /* m          */ \n\n\n    constexpr double R1 = 6371000. - 35000.;   /* m          */ \n\n\n\n    constexpr double T0 = 4000 + 273; /* K          */ \n\n\n    constexpr double T1 = 700 + 273;  /* K          */ \n\n\n\n// \u4e0b\u4e00\u7ec4\u5b9a\u4e49\u662f\u7528\u4e8e\u7f16\u7801\u5bc6\u5ea6\u4e0e\u6e29\u5ea6\u7684\u51fd\u6570\u3001\u91cd\u529b\u77e2\u91cf\u548c\u6e29\u5ea6\u7684\u521d\u59cb\u503c\u7684\u51fd\u6570\u3002\u540c\u6837\uff0c\u6240\u6709\u8fd9\u4e9b\uff08\u4ee5\u53ca\u5b83\u4eec\u6240\u8ba1\u7b97\u7684\u503c\uff09\u90fd\u5728\u4ecb\u7ecd\u4e2d\u8ba8\u8bba\u8fc7\u3002\n\n    double density(const double temperature) \n    { \n      return ( \n        reference_density * \n        (1 - expansion_coefficient * (temperature - reference_temperature))); \n    } \n\n    template <int dim> \n    Tensor<1, dim> gravity_vector(const Point<dim> &p) \n    { \n      const double r = p.norm(); \n      return -(1.245e-6 * r + 7.714e13 / r / r) * p / r; \n    } \n\n    template <int dim> \n    class TemperatureInitialValues : public Function<dim> \n    { \n    public: \n      TemperatureInitialValues() \n        : Function<dim>(1) \n      {} \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> &  value) const override; \n    }; \n\n    template <int dim> \n    double TemperatureInitialValues<dim>::value(const Point<dim> &p, \n                                                const unsigned int) const \n    { \n      const double r = p.norm(); \n      const double h = R1 - R0; \n\n      const double s = (r - R0) / h; \n      const double q = \n        (dim == 3) ? std::max(0.0, cos(numbers::PI * abs(p(2) / R1))) : 1.0; \n      const double phi = std::atan2(p(0), p(1)); \n      const double tau = s + 0.2 * s * (1 - s) * std::sin(6 * phi) * q; \n\n      return T0 * (1.0 - tau) + T1 * tau; \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// \u6b63\u5982\u4ecb\u7ecd\u4e2d\u6240\u63d0\u5230\u7684\uff0c\u6211\u4eec\u9700\u8981\u91cd\u65b0\u8c03\u6574\u538b\u529b\u7684\u6bd4\u4f8b\uff0c\u4ee5\u907f\u514d\u52a8\u91cf\u548c\u8d28\u91cf\u5b88\u6052\u65b9\u7a0b\u7684\u76f8\u5bf9\u6761\u4ef6\u4e0d\u826f\u3002\u6bd4\u4f8b\u7cfb\u6570\u4e3a $\\frac{\\eta}{L}$ \uff0c\u5176\u4e2d $L$ \u662f\u4e00\u4e2a\u5178\u578b\u7684\u957f\u5ea6\u5c3a\u5ea6\u3002\u901a\u8fc7\u5b9e\u9a8c\u53d1\u73b0\uff0c\u4e00\u4e2a\u597d\u7684\u957f\u5ea6\u5c3a\u5ea6\u662f\u70df\u7fbd\u7684\u76f4\u5f84\uff0c\u5927\u7ea6\u662f10\u516c\u91cc\u3002\n\n    constexpr double pressure_scaling = eta / 10000; \n\n// \u8fd9\u4e2a\u547d\u540d\u7a7a\u95f4\u7684\u6700\u540e\u4e00\u4e2a\u6570\u5b57\u662f\u4e00\u4e2a\u5e38\u6570\uff0c\u8868\u793a\u6bcf\uff08\u5e73\u5747\uff0c\u70ed\u5e26\uff09\u5e74\u7684\u79d2\u6570\u3002\u6211\u4eec\u53ea\u5728\u751f\u6210\u5c4f\u5e55\u8f93\u51fa\u65f6\u4f7f\u7528\u5b83\uff1a\u5728\u5185\u90e8\uff0c\u8fd9\u4e2a\u7a0b\u5e8f\u7684\u6240\u6709\u8ba1\u7b97\u90fd\u662f\u4ee5SI\u5355\u4f4d\uff08\u516c\u65a4\u3001\u7c73\u3001\u79d2\uff09\u8fdb\u884c\u7684\uff0c\u4f46\u662f\u7528\u79d2\u6765\u5199\u5730\u8d28\u5b66\u65f6\u95f4\u4ea7\u751f\u7684\u6570\u5b57\u65e0\u6cd5\u4e0e\u73b0\u5b9e\u8054\u7cfb\u8d77\u6765\uff0c\u6240\u4ee5\u6211\u4eec\u7528\u8fd9\u91cc\u5b9a\u4e49\u7684\u7cfb\u6570\u8f6c\u6362\u4e3a\u5e74\u3002\n\n    const double year_in_seconds = 60 * 60 * 24 * 365.2425; \n\n  } // namespace EquationData \n\n//  @sect3{Preconditioning the Stokes system}  \n\n// \u8fd9\u4e2a\u547d\u540d\u7a7a\u95f4\u5b9e\u73b0\u4e86\u9884\u5904\u7406\u7a0b\u5e8f\u3002\u6b63\u5982\u4ecb\u7ecd\u4e2d\u6240\u8ba8\u8bba\u7684\uff0c\u8fd9\u4e2a\u9884\u5904\u7406\u7a0b\u5e8f\u5728\u4e00\u4e9b\u5173\u952e\u90e8\u5206\u4e0e  step-31  \u4e2d\u4f7f\u7528\u7684\u9884\u5904\u7406\u7a0b\u5e8f\u4e0d\u540c\u3002\u5177\u4f53\u6765\u8bf4\uff0c\u5b83\u662f\u4e00\u4e2a\u53f3\u9884\u5904\u7406\u7a0b\u5e8f\uff0c\u5b9e\u73b0\u4e86\u77e9\u9635\n//  @f{align*}\n//    \\left(\\begin{array}{cc}A^{-1} & B^T\n//                         \\\\0 & S^{-1}\n//  \\end{array}\\right)\n//  @f}\n//  \u4e2d\u7684\u4e24\u4e2a\u9006\u77e9\u9635\u64cd\u4f5c\u7531\u7ebf\u6027\u6c42\u89e3\u5668\u8fd1\u4f3c\uff0c\u6216\u8005\uff0c\u5982\u679c\u7ed9\u8fd9\u4e2a\u7c7b\u7684\u6784\u9020\u51fd\u6570\u52a0\u4e0a\u53f3\u6807\u5fd7\uff0c\u5219\u7531\u901f\u5ea6\u5757\u7684\u5355\u4e2aAMG V-\u5faa\u73af\u5b9e\u73b0\u3002 <code>vmult</code> \u51fd\u6570\u7684\u4e09\u4e2a\u4ee3\u7801\u5757\u5b9e\u73b0\u4e86\u4e0e\u8be5\u9884\u5904\u7406\u77e9\u9635\u7684\u4e09\u4e2a\u5757\u7684\u4e58\u6cd5\u8fd0\u7b97\uff0c\u5982\u679c\u4f60\u8bfb\u8fc7 step-31 \u6216 step-20 \u4e2d\u5173\u4e8e\u7ec4\u6210\u6c42\u89e3\u5668\u7684\u8ba8\u8bba\uff0c\u5e94\u8be5\u662f\u4e0d\u8a00\u81ea\u660e\u7684\u3002\n\n  namespace LinearSolvers \n  { \n    template <class PreconditionerTypeA, class PreconditionerTypeMp> \n    class BlockSchurPreconditioner : public Subscriptor \n    { \n    public: \n      BlockSchurPreconditioner(const TrilinosWrappers::BlockSparseMatrix &S, \n                               const TrilinosWrappers::BlockSparseMatrix &Spre, \n                               const PreconditionerTypeMp &Mppreconditioner, \n                               const PreconditionerTypeA & Apreconditioner, \n                               const bool                  do_solve_A) \n        : stokes_matrix(&S) \n        , stokes_preconditioner_matrix(&Spre) \n        , mp_preconditioner(Mppreconditioner) \n        , a_preconditioner(Apreconditioner) \n        , do_solve_A(do_solve_A) \n      {} \n\n      void vmult(TrilinosWrappers::MPI::BlockVector &      dst, \n                 const TrilinosWrappers::MPI::BlockVector &src) const \n      { \n        TrilinosWrappers::MPI::Vector utmp(src.block(0)); \n\n        { \n          SolverControl solver_control(5000, 1e-6 * src.block(1).l2_norm()); \n\n          SolverCG<TrilinosWrappers::MPI::Vector> solver(solver_control); \n\n          solver.solve(stokes_preconditioner_matrix->block(1, 1), \n                       dst.block(1), \n                       src.block(1), \n                       mp_preconditioner); \n\n          dst.block(1) *= -1.0; \n        } \n\n        { \n          stokes_matrix->block(0, 1).vmult(utmp, dst.block(1)); \n          utmp *= -1.0; \n          utmp.add(src.block(0)); \n        } \n\n        if (do_solve_A == true) \n          { \n            SolverControl solver_control(5000, utmp.l2_norm() * 1e-2); \n            TrilinosWrappers::SolverCG solver(solver_control); \n            solver.solve(stokes_matrix->block(0, 0), \n                         dst.block(0), \n                         utmp, \n                         a_preconditioner); \n          } \n        else \n          a_preconditioner.vmult(dst.block(0), utmp); \n      } \n\n    private: \n      const SmartPointer<const TrilinosWrappers::BlockSparseMatrix> \n        stokes_matrix; \n      const SmartPointer<const TrilinosWrappers::BlockSparseMatrix> \n                                  stokes_preconditioner_matrix; \n      const PreconditionerTypeMp &mp_preconditioner; \n      const PreconditionerTypeA & a_preconditioner; \n      const bool                  do_solve_A; \n    }; \n  } // namespace LinearSolvers \n\n//  @sect3{Definition of assembly data structures}  \n\n// \u5982\u4ecb\u7ecd\u4e2d\u6240\u8ff0\uff0c\u6211\u4eec\u5c06\u4f7f\u7528 @ref threads \u6a21\u5757\u4e2d\u8ba8\u8bba\u7684WorkStream\u673a\u5236\u6765\u5b9e\u73b0\u5355\u53f0\u673a\u5668\u7684\u5904\u7406\u5668\u4e4b\u95f4\u7684\u5e76\u884c\u64cd\u4f5c\u3002WorkStream\u7c7b\u8981\u6c42\u6570\u636e\u5728\u4e24\u79cd\u6570\u636e\u7ed3\u6784\u4e2d\u4f20\u9012\uff0c\u4e00\u79cd\u662f\u7528\u4e8e\u6293\u53d6\u6570\u636e\uff0c\u4e00\u79cd\u662f\u5c06\u6570\u636e\u4ece\u88c5\u914d\u51fd\u6570\u4f20\u9012\u5230\u5c06\u672c\u5730\u8d21\u732e\u590d\u5236\u5230\u5168\u5c40\u5bf9\u8c61\u7684\u51fd\u6570\u3002\n\n// \u4e0b\u9762\u7684\u547d\u540d\u7a7a\u95f4\uff08\u4ee5\u53ca\u4e24\u4e2a\u5b50\u547d\u540d\u7a7a\u95f4\uff09\u5305\u542b\u4e86\u670d\u52a1\u4e8e\u8fd9\u4e00\u76ee\u7684\u7684\u6570\u636e\u7ed3\u6784\u7684\u96c6\u5408\uff0c\u4ecb\u7ecd\u4e2d\u8ba8\u8bba\u7684\u56db\u79cd\u64cd\u4f5c\u4e2d\u7684\u6bcf\u4e00\u79cd\u90fd\u6709\u4e00\u5bf9\uff0c\u6211\u4eec\u5c06\u60f3\u628a\u5b83\u4eec\u5e76\u884c\u5316\u3002\u6bcf\u4e2a\u88c5\u914d\u4f8b\u7a0b\u90fd\u4f1a\u5f97\u5230\u4e24\u7ec4\u6570\u636e\uff1a\u4e00\u4e2a\u662fScratch\u6570\u7ec4\uff0c\u6536\u96c6\u6240\u6709\u7528\u4e8e\u8ba1\u7b97\u5355\u5143\u683c\u8d21\u732e\u7684\u7c7b\u548c\u6570\u7ec4\uff0c\u53e6\u4e00\u4e2a\u662fCopyData\u6570\u7ec4\uff0c\u4fdd\u5b58\u5c06\u88ab\u5199\u5165\u5168\u5c40\u77e9\u9635\u7684\u672c\u5730\u77e9\u9635\u548c\u5411\u91cf\u3002\u800cCopyData\u662f\u4e00\u4e2a\u5bb9\u5668\uff0c\u7528\u6765\u5b58\u653e\u6700\u7ec8\u5199\u5165\u5168\u5c40\u77e9\u9635\u548c\u5411\u91cf\u7684\u6570\u636e\uff08\u56e0\u6b64\u662f\u7edd\u5bf9\u5fc5\u8981\u7684\uff09\uff0cScratch\u6570\u7ec4\u53ea\u662f\u51fa\u4e8e\u6027\u80fd\u7684\u8003\u8651\u800c\u5b58\u5728\uff1b\u5728\u6bcf\u4e2a\u5355\u5143\u4e0a\u8bbe\u7f6e\u4e00\u4e2aFEValues\u5bf9\u8c61\uff0c\u8981\u6bd4\u53ea\u521b\u5efa\u4e00\u6b21\u5e76\u66f4\u65b0\u4e00\u4e9b\u5bfc\u6570\u6570\u636e\u8981\u6602\u8d35\u5f97\u591a\u3002\n\n//  Step-31 \u6709\u56db\u4e2a\u6c47\u7f16\u7a0b\u5e8f\u3002\u4e00\u4e2a\u7528\u4e8e\u65af\u6258\u514b\u65af\u7cfb\u7edf\u7684\u9884\u5904\u7406\u77e9\u9635\uff0c\u4e00\u4e2a\u7528\u4e8e\u65af\u6258\u514b\u65af\u77e9\u9635\u548c\u53f3\u624b\u8fb9\uff0c\u4e00\u4e2a\u7528\u4e8e\u6e29\u5ea6\u77e9\u9635\uff0c\u4e00\u4e2a\u7528\u4e8e\u6e29\u5ea6\u65b9\u7a0b\u7684\u53f3\u624b\u8fb9\u3002\u6211\u4eec\u5728\u8fd9\u91cc\u4f7f\u7528 <code>struct</code> \u73af\u5883\u4e3a\u8fd9\u56db\u4e2a\u6c47\u7f16\u7ec4\u4ef6\u4e2d\u7684\u6bcf\u4e00\u4e2a\u7ec4\u7ec7\u4ece\u5934\u6570\u7ec4\u548cCopyData\u5bf9\u8c61\uff08\u56e0\u4e3a\u6211\u4eec\u8ba4\u4e3a\u8fd9\u4e9b\u662f\u6211\u4eec\u4f20\u9012\u7684\u4e34\u65f6\u5bf9\u8c61\uff0c\u800c\u4e0d\u662f\u5b9e\u73b0\u81ea\u5df1\u529f\u80fd\u7684\u7c7b\uff0c\u5c3d\u7ba1\u8fd9\u662f\u533a\u5206 <code>struct</code>s and <code>class</code> es\u7684\u4e00\u4e2a\u6bd4\u8f83\u4e3b\u89c2\u7684\u89c2\u70b9\uff09\u3002\n\n// \u5173\u4e8eScratch\u5bf9\u8c61\uff0c\u6bcf\u4e2a\u7ed3\u6784\u90fd\u914d\u5907\u4e86\u4e00\u4e2a\u6784\u9020\u51fd\u6570\uff0c\u53ef\u4ee5\u4f7f\u7528 @ref FiniteElement \u3001\u6b63\u4ea4\u3001 @ref Mapping \uff08\u63cf\u8ff0\u5f2f\u66f2\u8fb9\u754c\u7684\u63d2\u503c\uff09\u548c @ref UpdateFlags \u5b9e\u4f8b\u521b\u5efa\u4e00\u4e2a @ref FEValues \u5bf9\u8c61\u3002\u6b64\u5916\uff0c\u6211\u4eec\u624b\u52a8\u5b9e\u73b0\u4e86\u4e00\u4e2a\u590d\u5236\u6784\u9020\u51fd\u6570\uff08\u56e0\u4e3aFEValues\u7c7b\u672c\u8eab\u662f\u4e0d\u53ef\u590d\u5236\u7684\uff09\uff0c\u5e76\u63d0\u4f9b\u4e86\u4e00\u4e9b\u989d\u5916\u7684\u77e2\u91cf\u5b57\u6bb5\uff0c\u7528\u4e8e\u5728\u8ba1\u7b97\u5c40\u90e8\u8d21\u732e\u65f6\u4fdd\u5b58\u4e2d\u95f4\u6570\u636e\u3002\n\n// \u8ba9\u6211\u4eec\u4ece\u6293\u53d6\u6570\u7ec4\u5f00\u59cb\uff0c\u7279\u522b\u662f\u7528\u4e8e\u7ec4\u88c5\u65af\u6258\u514b\u65af\u9884\u5904\u7406\u7a0b\u5e8f\u7684\u6570\u7ec4\u3002\n\n  namespace Assembly \n  { \n    namespace Scratch \n    { \n      template <int dim> \n      struct StokesPreconditioner \n      { \n        StokesPreconditioner(const FiniteElement<dim> &stokes_fe, \n                             const Quadrature<dim> &   stokes_quadrature, \n                             const Mapping<dim> &      mapping, \n                             const UpdateFlags         update_flags); \n\n        StokesPreconditioner(const StokesPreconditioner &data); \n\n        FEValues<dim> stokes_fe_values; \n\n        std::vector<Tensor<2, dim>> grad_phi_u; \n        std::vector<double>         phi_p; \n      }; \n\n      template <int dim> \n      StokesPreconditioner<dim>::StokesPreconditioner( \n        const FiniteElement<dim> &stokes_fe, \n        const Quadrature<dim> &   stokes_quadrature, \n        const Mapping<dim> &      mapping, \n        const UpdateFlags         update_flags) \n        : stokes_fe_values(mapping, stokes_fe, stokes_quadrature, update_flags) \n        , grad_phi_u(stokes_fe.n_dofs_per_cell()) \n        , phi_p(stokes_fe.n_dofs_per_cell()) \n      {} \n\n      template <int dim> \n      StokesPreconditioner<dim>::StokesPreconditioner( \n        const StokesPreconditioner &scratch) \n        : stokes_fe_values(scratch.stokes_fe_values.get_mapping(), \n                           scratch.stokes_fe_values.get_fe(), \n                           scratch.stokes_fe_values.get_quadrature(), \n                           scratch.stokes_fe_values.get_update_flags()) \n        , grad_phi_u(scratch.grad_phi_u) \n        , phi_p(scratch.phi_p) \n      {} \n\n// \u4e0b\u4e00\u4e2a\u662f\u7528\u4e8e\u7ec4\u88c5\u5b8c\u6574\u7684\u65af\u6258\u514b\u65af\u7cfb\u7edf\u7684\u4ece\u5934\u5bf9\u8c61\u3002\u8bf7\u6ce8\u610f\uff0c\u6211\u4eec\u4ece\u4e0a\u9762\u7684StokesPreconditioner\u7c7b\u6d3e\u751f\u51faStokesSystem scratch\u7c7b\u3002\u6211\u4eec\u8fd9\u6837\u505a\u662f\u56e0\u4e3a\u6240\u6709\u7528\u4e8e\u7ec4\u88c5\u9884\u5904\u7406\u7a0b\u5e8f\u7684\u5bf9\u8c61\u4e5f\u9700\u8981\u7528\u4e8e\u5b9e\u9645\u7684\u77e9\u9635\u7cfb\u7edf\u548c\u53f3\u624b\u8fb9\uff0c\u8fd8\u6709\u4e00\u4e9b\u989d\u5916\u7684\u6570\u636e\u3002\u8fd9\u4f7f\u5f97\u7a0b\u5e8f\u66f4\u52a0\u7d27\u51d1\u3002\u8fd8\u9700\u8981\u6ce8\u610f\u7684\u662f\uff0c\u65af\u6258\u514b\u65af\u7cfb\u7edf\u7684\u88c5\u914d\u548c\u8fdb\u4e00\u6b65\u7684\u6e29\u5ea6\u53f3\u624b\u8fb9\u5206\u522b\u9700\u8981\u6e29\u5ea6\u548c\u901f\u5ea6\u7684\u6570\u636e\uff0c\u6240\u4ee5\u6211\u4eec\u5b9e\u9645\u4e0a\u9700\u8981\u4e24\u4e2aFEValues\u5bf9\u8c61\u6765\u5904\u7406\u8fd9\u4e24\u79cd\u60c5\u51b5\u3002\n\n      template <int dim> \n      struct StokesSystem : public StokesPreconditioner<dim> \n      { \n        StokesSystem(const FiniteElement<dim> &stokes_fe, \n                     const Mapping<dim> &      mapping, \n                     const Quadrature<dim> &   stokes_quadrature, \n                     const UpdateFlags         stokes_update_flags, \n                     const FiniteElement<dim> &temperature_fe, \n                     const UpdateFlags         temperature_update_flags); \n\n        StokesSystem(const StokesSystem<dim> &data); \n\n        FEValues<dim> temperature_fe_values; \n\n        std::vector<Tensor<1, dim>>          phi_u; \n        std::vector<SymmetricTensor<2, dim>> grads_phi_u; \n        std::vector<double>                  div_phi_u; \n\n        std::vector<double> old_temperature_values; \n      }; \n\n      template <int dim> \n      StokesSystem<dim>::StokesSystem( \n        const FiniteElement<dim> &stokes_fe, \n        const Mapping<dim> &      mapping, \n        const Quadrature<dim> &   stokes_quadrature, \n        const UpdateFlags         stokes_update_flags, \n        const FiniteElement<dim> &temperature_fe, \n        const UpdateFlags         temperature_update_flags) \n        : StokesPreconditioner<dim>(stokes_fe, \n                                    stokes_quadrature, \n                                    mapping, \n                                    stokes_update_flags) \n        , temperature_fe_values(mapping, \n                                temperature_fe, \n                                stokes_quadrature, \n                                temperature_update_flags) \n        , phi_u(stokes_fe.n_dofs_per_cell()) \n        , grads_phi_u(stokes_fe.n_dofs_per_cell()) \n        , div_phi_u(stokes_fe.n_dofs_per_cell()) \n        , old_temperature_values(stokes_quadrature.size()) \n      {} \n\n      template <int dim> \n      StokesSystem<dim>::StokesSystem(const StokesSystem<dim> &scratch) \n        : StokesPreconditioner<dim>(scratch) \n        , temperature_fe_values( \n            scratch.temperature_fe_values.get_mapping(), \n            scratch.temperature_fe_values.get_fe(), \n            scratch.temperature_fe_values.get_quadrature(), \n            scratch.temperature_fe_values.get_update_flags()) \n        , phi_u(scratch.phi_u) \n        , grads_phi_u(scratch.grads_phi_u) \n        , div_phi_u(scratch.div_phi_u) \n        , old_temperature_values(scratch.old_temperature_values) \n      {} \n\n// \u5728\u5b9a\u4e49\u4e86\u7528\u4e8e\u7ec4\u88c5\u65af\u6258\u514b\u65af\u7cfb\u7edf\u7684\u5bf9\u8c61\u4e4b\u540e\uff0c\u6211\u4eec\u5bf9\u6e29\u5ea6\u7cfb\u7edf\u6240\u9700\u7684\u77e9\u9635\u7684\u7ec4\u88c5\u4e5f\u505a\u4e86\u540c\u6837\u7684\u5de5\u4f5c\u3002\u4e00\u822c\u7684\u7ed3\u6784\u662f\u975e\u5e38\u76f8\u4f3c\u7684\u3002\n\n      template <int dim> \n      struct TemperatureMatrix \n      { \n        TemperatureMatrix(const FiniteElement<dim> &temperature_fe, \n                          const Mapping<dim> &      mapping, \n                          const Quadrature<dim> &   temperature_quadrature); \n\n        TemperatureMatrix(const TemperatureMatrix &data); \n\n        FEValues<dim> temperature_fe_values; \n\n        std::vector<double>         phi_T; \n        std::vector<Tensor<1, dim>> grad_phi_T; \n      }; \n\n      template <int dim> \n      TemperatureMatrix<dim>::TemperatureMatrix( \n        const FiniteElement<dim> &temperature_fe, \n        const Mapping<dim> &      mapping, \n        const Quadrature<dim> &   temperature_quadrature) \n        : temperature_fe_values(mapping, \n                                temperature_fe, \n                                temperature_quadrature, \n                                update_values | update_gradients | \n                                  update_JxW_values) \n        , phi_T(temperature_fe.n_dofs_per_cell()) \n        , grad_phi_T(temperature_fe.n_dofs_per_cell()) \n      {} \n\n      template <int dim> \n      TemperatureMatrix<dim>::TemperatureMatrix( \n        const TemperatureMatrix &scratch) \n        : temperature_fe_values( \n            scratch.temperature_fe_values.get_mapping(), \n            scratch.temperature_fe_values.get_fe(), \n            scratch.temperature_fe_values.get_quadrature(), \n            scratch.temperature_fe_values.get_update_flags()) \n        , phi_T(scratch.phi_T) \n        , grad_phi_T(scratch.grad_phi_T) \n      {} \n\n// \u6700\u540e\u7684\u5212\u75d5\u5bf9\u8c61\u88ab\u7528\u4e8e\u6e29\u5ea6\u7cfb\u7edf\u53f3\u4fa7\u7684\u88c5\u914d\u3002\u8fd9\u4e2a\u5bf9\u8c61\u6bd4\u4e0a\u9762\u7684\u5bf9\u8c61\u8981\u5927\u5f97\u591a\uff0c\u56e0\u4e3a\u6709\u66f4\u591a\u7684\u91cf\u8fdb\u5165\u6e29\u5ea6\u65b9\u7a0b\u53f3\u8fb9\u7684\u8ba1\u7b97\u4e2d\u3002\u7279\u522b\u662f\uff0c\u524d\u4e24\u4e2a\u65f6\u95f4\u6b65\u9aa4\u7684\u6e29\u5ea6\u503c\u548c\u68af\u5ea6\u9700\u8981\u5728\u6b63\u4ea4\u70b9\u8bc4\u4f30\uff0c\u8fd8\u6709\u901f\u5ea6\u548c\u5e94\u53d8\u7387\uff08\u5373\u901f\u5ea6\u7684\u5bf9\u79f0\u68af\u5ea6\uff09\uff0c\u5b83\u4eec\u4f5c\u4e3a\u6469\u64e6\u52a0\u70ed\u9879\u8fdb\u5165\u53f3\u4fa7\u3002\u5c3d\u7ba1\u6709\u5f88\u591a\u6761\u6b3e\uff0c\u4f46\u4ee5\u4e0b\u5185\u5bb9\u5e94\u8be5\u662f\u4e0d\u8a00\u81ea\u660e\u7684\u3002\n\n      template <int dim> \n      struct TemperatureRHS \n      { \n        TemperatureRHS(const FiniteElement<dim> &temperature_fe, \n                       const FiniteElement<dim> &stokes_fe, \n                       const Mapping<dim> &      mapping, \n                       const Quadrature<dim> &   quadrature); \n\n        TemperatureRHS(const TemperatureRHS &data); \n\n        FEValues<dim> temperature_fe_values; \n        FEValues<dim> stokes_fe_values; \n\n        std::vector<double>         phi_T; \n        std::vector<Tensor<1, dim>> grad_phi_T; \n\n        std::vector<Tensor<1, dim>> old_velocity_values; \n        std::vector<Tensor<1, dim>> old_old_velocity_values; \n\n        std::vector<SymmetricTensor<2, dim>> old_strain_rates; \n        std::vector<SymmetricTensor<2, dim>> old_old_strain_rates; \n\n        std::vector<double>         old_temperature_values; \n        std::vector<double>         old_old_temperature_values; \n        std::vector<Tensor<1, dim>> old_temperature_grads; \n        std::vector<Tensor<1, dim>> old_old_temperature_grads; \n        std::vector<double>         old_temperature_laplacians; \n        std::vector<double>         old_old_temperature_laplacians; \n      }; \n\n      template <int dim> \n      TemperatureRHS<dim>::TemperatureRHS( \n        const FiniteElement<dim> &temperature_fe, \n        const FiniteElement<dim> &stokes_fe, \n        const Mapping<dim> &      mapping, \n        const Quadrature<dim> &   quadrature) \n        : temperature_fe_values(mapping, \n                                temperature_fe, \n                                quadrature, \n                                update_values | update_gradients | \n                                  update_hessians | update_quadrature_points | \n                                  update_JxW_values) \n        , stokes_fe_values(mapping, \n                           stokes_fe, \n                           quadrature, \n                           update_values | update_gradients) \n        , phi_T(temperature_fe.n_dofs_per_cell()) \n        , grad_phi_T(temperature_fe.n_dofs_per_cell()) \n        , \n\n        old_velocity_values(quadrature.size()) \n        , old_old_velocity_values(quadrature.size()) \n        , old_strain_rates(quadrature.size()) \n        , old_old_strain_rates(quadrature.size()) \n        , \n\n        old_temperature_values(quadrature.size()) \n        , old_old_temperature_values(quadrature.size()) \n        , old_temperature_grads(quadrature.size()) \n        , old_old_temperature_grads(quadrature.size()) \n        , old_temperature_laplacians(quadrature.size()) \n        , old_old_temperature_laplacians(quadrature.size()) \n      {} \n\n      template <int dim> \n      TemperatureRHS<dim>::TemperatureRHS(const TemperatureRHS &scratch) \n        : temperature_fe_values( \n            scratch.temperature_fe_values.get_mapping(), \n            scratch.temperature_fe_values.get_fe(), \n            scratch.temperature_fe_values.get_quadrature(), \n            scratch.temperature_fe_values.get_update_flags()) \n        , stokes_fe_values(scratch.stokes_fe_values.get_mapping(), \n                           scratch.stokes_fe_values.get_fe(), \n                           scratch.stokes_fe_values.get_quadrature(), \n                           scratch.stokes_fe_values.get_update_flags()) \n        , phi_T(scratch.phi_T) \n        , grad_phi_T(scratch.grad_phi_T) \n        , \n\n        old_velocity_values(scratch.old_velocity_values) \n        , old_old_velocity_values(scratch.old_old_velocity_values) \n        , old_strain_rates(scratch.old_strain_rates) \n        , old_old_strain_rates(scratch.old_old_strain_rates) \n        , \n\n        old_temperature_values(scratch.old_temperature_values) \n        , old_old_temperature_values(scratch.old_old_temperature_values) \n        , old_temperature_grads(scratch.old_temperature_grads) \n        , old_old_temperature_grads(scratch.old_old_temperature_grads) \n        , old_temperature_laplacians(scratch.old_temperature_laplacians) \n        , old_old_temperature_laplacians(scratch.old_old_temperature_laplacians) \n      {} \n    } // namespace Scratch \n\n// CopyData\u5bf9\u8c61\u6bd4Scratch\u5bf9\u8c61\u66f4\u7b80\u5355\uff0c\u56e0\u4e3a\u5b83\u4eec\u6240\u8981\u505a\u7684\u5c31\u662f\u5b58\u50a8\u672c\u5730\u8ba1\u7b97\u7684\u7ed3\u679c\uff0c\u76f4\u5230\u5b83\u4eec\u53ef\u4ee5\u88ab\u590d\u5236\u5230\u5168\u5c40\u77e9\u9635\u6216\u5411\u91cf\u5bf9\u8c61\u4e2d\u3002\u56e0\u6b64\uff0c\u8fd9\u4e9b\u7ed3\u6784\u53ea\u9700\u8981\u63d0\u4f9b\u4e00\u4e2a\u6784\u9020\u51fd\u6570\uff0c\u4e00\u4e2a\u590d\u5236\u64cd\u4f5c\uff0c\u4ee5\u53ca\u4e00\u4e9b\u7528\u4e8e\u672c\u5730\u77e9\u9635\u3001\u672c\u5730\u5411\u91cf\u548c\u672c\u5730\u4e0e\u5168\u5c40\u81ea\u7531\u5ea6\u4e4b\u95f4\u5173\u7cfb\u7684\u6570\u7ec4\uff08\u53c8\u79f0 <code>local_dof_indices</code> \uff09\u3002\u540c\u6837\uff0c\u6211\u4eec\u4e3a\u6211\u4eec\u5c06\u4f7f\u7528WorkStream\u7c7b\u5e76\u884c\u5316\u7684\u56db\u4e2a\u64cd\u4f5c\u4e2d\u7684\u6bcf\u4e00\u4e2a\u90fd\u6709\u4e00\u4e2a\u8fd9\u6837\u7684\u7ed3\u6784\u3002\n\n    namespace CopyData \n    { \n      template <int dim> \n      struct StokesPreconditioner \n      { \n        StokesPreconditioner(const FiniteElement<dim> &stokes_fe); \n        StokesPreconditioner(const StokesPreconditioner &data); \n        StokesPreconditioner &operator=(const StokesPreconditioner &) = default; \n\n        FullMatrix<double>                   local_matrix; \n        std::vector<types::global_dof_index> local_dof_indices; \n      }; \n\n      template <int dim> \n      StokesPreconditioner<dim>::StokesPreconditioner( \n        const FiniteElement<dim> &stokes_fe) \n        : local_matrix(stokes_fe.n_dofs_per_cell(), stokes_fe.n_dofs_per_cell()) \n        , local_dof_indices(stokes_fe.n_dofs_per_cell()) \n      {} \n\n      template <int dim> \n      StokesPreconditioner<dim>::StokesPreconditioner( \n        const StokesPreconditioner &data) \n        : local_matrix(data.local_matrix) \n        , local_dof_indices(data.local_dof_indices) \n      {} \n\n      template <int dim> \n      struct StokesSystem : public StokesPreconditioner<dim> \n      { \n        StokesSystem(const FiniteElement<dim> &stokes_fe); \n\n        Vector<double> local_rhs; \n      }; \n\n      template <int dim> \n      StokesSystem<dim>::StokesSystem(const FiniteElement<dim> &stokes_fe) \n        : StokesPreconditioner<dim>(stokes_fe) \n        , local_rhs(stokes_fe.n_dofs_per_cell()) \n      {} \n\n      template <int dim> \n      struct TemperatureMatrix \n      { \n        TemperatureMatrix(const FiniteElement<dim> &temperature_fe); \n\n        FullMatrix<double>                   local_mass_matrix; \n        FullMatrix<double>                   local_stiffness_matrix; \n        std::vector<types::global_dof_index> local_dof_indices; \n      }; \n\n      template <int dim> \n      TemperatureMatrix<dim>::TemperatureMatrix( \n        const FiniteElement<dim> &temperature_fe) \n        : local_mass_matrix(temperature_fe.n_dofs_per_cell(), \n                            temperature_fe.n_dofs_per_cell()) \n        , local_stiffness_matrix(temperature_fe.n_dofs_per_cell(), \n                                 temperature_fe.n_dofs_per_cell()) \n        , local_dof_indices(temperature_fe.n_dofs_per_cell()) \n      {} \n\n      template <int dim> \n      struct TemperatureRHS \n      { \n        TemperatureRHS(const FiniteElement<dim> &temperature_fe); \n\n        Vector<double>                       local_rhs; \n        std::vector<types::global_dof_index> local_dof_indices; \n        FullMatrix<double>                   matrix_for_bc; \n      }; \n\n      template <int dim> \n      TemperatureRHS<dim>::TemperatureRHS( \n        const FiniteElement<dim> &temperature_fe) \n        : local_rhs(temperature_fe.n_dofs_per_cell()) \n        , local_dof_indices(temperature_fe.n_dofs_per_cell()) \n        , matrix_for_bc(temperature_fe.n_dofs_per_cell(), \n                        temperature_fe.n_dofs_per_cell()) \n      {} \n    } // namespace CopyData \n  }   // namespace Assembly \n\n//  @sect3{The <code>BoussinesqFlowProblem</code> class template}  \n\n// \u8fd9\u662f\u4e3b\u7c7b\u7684\u58f0\u660e\u3002\u5b83\u4e0e step-31 \u975e\u5e38\u76f8\u4f3c\uff0c\u4f46\u6709\u4e00\u4e9b\u533a\u522b\u6211\u4eec\u5c06\u5728\u4e0b\u9762\u8bc4\u8bba\u3002\n\n// \u8be5\u7c7b\u7684\u9876\u90e8\u4e0e step-31 \u4e2d\u7684\u5185\u5bb9\u57fa\u672c\u76f8\u540c\uff0c\u5217\u51fa\u4e86\u516c\u5171\u65b9\u6cd5\u548c\u4e00\u7ec4\u505a\u91cd\u6d3b\u7684\u79c1\u6709\u51fd\u6570\u3002\u4e0e step-31 \u76f8\u6bd4\uff0c\u8fd9\u90e8\u5206\u53ea\u589e\u52a0\u4e86\u4e24\u4e2a\uff1a\u8ba1\u7b97\u6240\u6709\u5355\u5143\u7684\u6700\u5927CFL\u6570\u7684\u51fd\u6570 <code>get_cfl_number()</code> \uff0c\u7136\u540e\u6211\u4eec\u6839\u636e\u5b83\u8ba1\u7b97\u5168\u5c40\u65f6\u95f4\u6b65\u957f\uff1b\u4ee5\u53ca\u7528\u4e8e\u8ba1\u7b97\u71b5\u503c\u7a33\u5b9a\u7684\u51fd\u6570 <code>get_entropy_variation()</code> \u3002\u5b83\u7c7b\u4f3c\u4e8e\u6211\u4eec\u5728 step-31 \u4e2d\u7528\u4e8e\u6b64\u76ee\u7684\u7684 <code>get_extrapolated_temperature_range()</code> \uff0c\u4f46\u5b83\u7684\u5de5\u4f5c\u5bf9\u8c61\u662f\u71b5\u800c\u4e0d\u662f\u6e29\u5ea6\u3002\n\n  template <int dim> \n  class BoussinesqFlowProblem \n  { \n  public: \n    struct Parameters; \n    BoussinesqFlowProblem(Parameters &parameters); \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_matrix(); \n    void   assemble_temperature_system(const double maximal_velocity); \n    double get_maximal_velocity() const; \n    double get_cfl_number() const; \n    double get_entropy_variation(const double average_temperature) const; \n    std::pair<double, double> get_extrapolated_temperature_range() const; \n    void                      solve(); \n    void                      output_results(); \n    void                      refine_mesh(const unsigned int max_grid_level); \n\n    double compute_viscosity( \n      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<SymmetricTensor<2, dim>> &old_strain_rates, \n      const std::vector<SymmetricTensor<2, dim>> &old_old_strain_rates, \n      const double                                global_u_infty, \n      const double                                global_T_variation, \n      const double                                average_temperature, \n      const double                                global_entropy_variation, \n      const double                                cell_diameter) const; \n\n  public: \n\n// \u7b2c\u4e00\u4e2a\u91cd\u8981\u7684\u65b0\u7ec4\u4ef6\u662f\u6839\u636e\u4ecb\u7ecd\u4e2d\u7684\u8ba8\u8bba\u4e3a\u53c2\u6570\u5b9a\u4e49\u4e86\u4e00\u4e2a\u7ed3\u6784\u3002\u8fd9\u4e2a\u7ed3\u6784\u662f\u5728\u6784\u5efa\u8fd9\u4e2a\u5bf9\u8c61\u7684\u8fc7\u7a0b\u4e2d\u901a\u8fc7\u8bfb\u53d6\u53c2\u6570\u6587\u4ef6\u6765\u521d\u59cb\u5316\u7684\u3002\n\n    struct Parameters \n    { \n      Parameters(const std::string &parameter_filename); \n\n      static void declare_parameters(ParameterHandler &prm); \n      void        parse_parameters(ParameterHandler &prm); \n\n      double end_time; \n\n      unsigned int initial_global_refinement; \n      unsigned int initial_adaptive_refinement; \n\n      bool         generate_graphical_output; \n      unsigned int graphical_output_interval; \n\n      unsigned int adaptive_refinement_interval; \n\n      double stabilization_alpha; \n      double stabilization_c_R; \n      double stabilization_beta; \n\n      unsigned int stokes_velocity_degree; \n      bool         use_locally_conservative_discretization; \n\n      unsigned int temperature_degree; \n    }; \n\n  private: \n    Parameters &parameters; \n\n//  <code>pcout</code> \uff08\u7528\u4e8e<i>%parallel <code>std::cout</code></i>\uff09\u5bf9\u8c61\u88ab\u7528\u6765\u7b80\u5316\u8f93\u51fa\u7684\u4e66\u5199\uff1a\u6bcf\u4e2aMPI\u8fdb\u7a0b\u90fd\u53ef\u4ee5\u50cf\u5f80\u5e38\u4e00\u6837\u4f7f\u7528\u5b83\u6765\u4ea7\u751f\u8f93\u51fa\uff0c\u4f46\u7531\u4e8e\u8fd9\u4e9b\u8fdb\u7a0b\u4e2d\u7684\u6bcf\u4e00\u4e2a\u90fd\u4f1a\uff08\u5e0c\u671b\uff09\u4ea7\u751f\u76f8\u540c\u7684\u8f93\u51fa\uff0c\u5b83\u53ea\u662f\u88ab\u91cd\u590d\u4e86\u8bb8\u591a\u6b21\uff1b\u4f7f\u7528ConditionalOStream\u7c7b\uff0c\u53ea\u6709\u4e00\u4e2aMPI\u8fdb\u7a0b\u4ea7\u751f\u7684\u8f93\u51fa\u4f1a\u771f\u6b63\u88ab\u6253\u5370\u5230\u5c4f\u5e55\u4e0a\uff0c\u800c\u6240\u6709\u5176\u4ed6\u7ebf\u7a0b\u7684\u8f93\u51fa\u5c06\u53ea\u662f\u88ab\u9057\u5fd8\u3002\n\n    ConditionalOStream pcout; \n\n// \u4e0b\u9762\u7684\u6210\u5458\u53d8\u91cf\u5c06\u518d\u6b21\u4e0e step-31 \u4e2d\u7684\u6210\u5458\u53d8\u91cf\u76f8\u4f3c\uff08\u4e5f\u4e0e\u5176\u4ed6\u6559\u7a0b\u7a0b\u5e8f\u76f8\u4f3c\uff09\u3002\u6b63\u5982\u4ecb\u7ecd\u4e2d\u63d0\u5230\u7684\uff0c\u6211\u4eec\u5b8c\u5168\u5206\u5e03\u8ba1\u7b97\uff0c\u6240\u4ee5\u6211\u4eec\u5c06\u4e0d\u5f97\u4e0d\u4f7f\u7528 parallel::distributed::Triangulation \u7c7b\uff08\u89c1 step-40  \uff09\uff0c\u4f46\u8fd9\u4e9b\u53d8\u91cf\u7684\u5176\u4f59\u90e8\u5206\u76f8\u5f53\u6807\u51c6\uff0c\u6709\u4e24\u4e2a\u4f8b\u5916\u3002\n\n\n\n// --  <code>mapping</code> \u8fd9\u4e2a\u53d8\u91cf\u662f\u7528\u6765\u8868\u793a\u9ad8\u9636\u591a\u9879\u5f0f\u6620\u5c04\u7684\u3002\u6b63\u5982\u5728\u4ecb\u7ecd\u4e2d\u63d0\u5230\u7684\uff0c\u6211\u4eec\u5728\u901a\u8fc7\u6b63\u4ea4\u5f62\u6210\u79ef\u5206\u65f6\u4f7f\u7528\u8fd9\u4e2a\u6620\u5c04\uff0c\u7528\u4e8e\u6240\u6709\u4e0e\u6211\u4eec\u57df\u7684\u5185\u8fb9\u754c\u6216\u5916\u8fb9\u754c\u76f8\u90bb\u7684\u5355\u5143\uff0c\u5176\u4e2d\u8fb9\u754c\u662f\u5f2f\u66f2\u7684\u3002\n\n\n\n// - \u5728\u547d\u540d\u6df7\u4e71\u7684\u60c5\u51b5\u4e0b\uff0c\u4f60\u4f1a\u6ce8\u610f\u5230\u4e0b\u9762\u4e00\u4e9b\u6765\u81ea\u547d\u540d\u7a7a\u95f4TrilinosWrappers\u7684\u53d8\u91cf\u53d6\u81ea\u547d\u540d\u7a7a\u95f4 TrilinosWrappers::MPI \uff08\u6bd4\u5982\u53f3\u624b\u8fb9\u7684\u5411\u91cf\uff09\uff0c\u800c\u5176\u4ed6\u53d8\u91cf\u5219\u4e0d\u662f\uff08\u6bd4\u5982\u5404\u79cd\u77e9\u9635\uff09\u3002\u8fd9\u662f\u7531\u4e8e\u9057\u7559\u7684\u539f\u56e0\u3002\u6211\u4eec\u7ecf\u5e38\u9700\u8981\u67e5\u8be2\u4efb\u610f\u6b63\u4ea4\u70b9\u7684\u901f\u5ea6\u548c\u6e29\u5ea6\uff1b\u56e0\u6b64\uff0c\u6bcf\u5f53\u6211\u4eec\u9700\u8981\u8bbf\u95ee\u4e0e\u672c\u5730\u76f8\u5173\u4f46\u5c5e\u4e8e\u53e6\u4e00\u4e2a\u5904\u7406\u5668\u7684\u81ea\u7531\u5ea6\u65f6\uff0c\u6211\u4eec\u4e0d\u662f\u5bfc\u5165\u77e2\u91cf\u7684\u5e7d\u7075\u4fe1\u606f\uff0c\u800c\u662f\u4ee5%\u5e76\u884c\u65b9\u5f0f\u6c42\u89e3\u7ebf\u6027\u7cfb\u7edf\uff0c\u4f46\u968f\u540e\u7acb\u5373\u521d\u59cb\u5316\u4e00\u4e2a\u77e2\u91cf\uff0c\u5305\u62ec\u6c42\u89e3\u7684\u5e7d\u7075\u6761\u76ee\uff0c\u4ee5\u4fbf\u8fdb\u4e00\u6b65\u5904\u7406\u3002\u56e0\u6b64\uff0c\u5404\u79cd <code>*_solution</code> \u5411\u91cf\u5728\u4ee5%parallel\u6c42\u89e3\u5404\u81ea\u7684\u7ebf\u6027\u7cfb\u7edf\u540e\u7acb\u5373\u88ab\u586b\u5145\uff0c\u5e76\u4e14\u603b\u662f\u5305\u542b\u6240\u6709 @ref GlossLocallyRelevantDof \"\u672c\u5730\u76f8\u5173\u81ea\u7531\u5ea6 \"\u7684\u503c\uff1b\u6211\u4eec\u4ece\u6c42\u89e3\u8fc7\u7a0b\u4e2d\u83b7\u5f97\u7684\u5b8c\u5168\u5206\u5e03\u7684\u5411\u91cf\uff0c\u53ea\u5305\u542b @ref GlossLocallyOwnedDof \"\u672c\u5730\u62e5\u6709\u7684\u81ea\u7531\u5ea6\"\uff0c\u5728\u6c42\u89e3\u8fc7\u7a0b\u540e\uff0c\u5728\u6211\u4eec\u5c06\u76f8\u5173\u503c\u590d\u5236\u5230\u6210\u5458\u53d8\u91cf\u5411\u91cf\u540e\u7acb\u5373\u9500\u6bc1\u3002\n\n    parallel::distributed::Triangulation<dim> triangulation; \n    double                                    global_Omega_diameter; \n\n    const MappingQ<dim> mapping; \n\n    const FESystem<dim>       stokes_fe; \n    DoFHandler<dim>           stokes_dof_handler; \n    AffineConstraints<double> stokes_constraints; \n\n    TrilinosWrappers::BlockSparseMatrix stokes_matrix; \n    TrilinosWrappers::BlockSparseMatrix stokes_preconditioner_matrix; \n\n    TrilinosWrappers::MPI::BlockVector stokes_solution; \n    TrilinosWrappers::MPI::BlockVector old_stokes_solution; \n    TrilinosWrappers::MPI::BlockVector stokes_rhs; \n\n    FE_Q<dim>                 temperature_fe; \n    DoFHandler<dim>           temperature_dof_handler; \n    AffineConstraints<double> temperature_constraints; \n\n    TrilinosWrappers::SparseMatrix temperature_mass_matrix; \n    TrilinosWrappers::SparseMatrix temperature_stiffness_matrix; \n    TrilinosWrappers::SparseMatrix temperature_matrix; \n\n    TrilinosWrappers::MPI::Vector temperature_solution; \n    TrilinosWrappers::MPI::Vector old_temperature_solution; \n    TrilinosWrappers::MPI::Vector old_old_temperature_solution; \n    TrilinosWrappers::MPI::Vector temperature_rhs; \n\n    double       time_step; \n    double       old_time_step; \n    unsigned int timestep_number; \n\n    std::shared_ptr<TrilinosWrappers::PreconditionAMG>    Amg_preconditioner; \n    std::shared_ptr<TrilinosWrappers::PreconditionJacobi> Mp_preconditioner; \n    std::shared_ptr<TrilinosWrappers::PreconditionJacobi> T_preconditioner; \n\n    bool rebuild_stokes_matrix; \n    bool rebuild_stokes_preconditioner; \n    bool rebuild_temperature_matrices; \n    bool rebuild_temperature_preconditioner; \n\n// \u4e0b\u4e00\u4e2a\u6210\u5458\u53d8\u91cf\uff0c <code>computing_timer</code> \u662f\u7528\u6765\u65b9\u4fbf\u5730\u8ba1\u7b97\u5728\u67d0\u4e9b\u91cd\u590d\u8f93\u5165\u7684\u4ee3\u7801 \"\u90e8\u5206 \"\u6240\u82b1\u8d39\u7684\u8ba1\u7b97\u65f6\u95f4\u3002\u4f8b\u5982\uff0c\u6211\u4eec\u5c06\u8fdb\u5165\uff08\u548c\u79bb\u5f00\uff09\u65af\u6258\u514b\u65af\u77e9\u9635\u88c5\u914d\u7684\u90e8\u5206\uff0c\u5e76\u5e0c\u671b\u5728\u6240\u6709\u7684\u65f6\u95f4\u6b65\u9aa4\u4e2d\u7d2f\u79ef\u5728\u8fd9\u90e8\u5206\u82b1\u8d39\u7684\u8fd0\u884c\u65f6\u95f4\u3002\u6bcf\u9694\u4e00\u6bb5\u65f6\u95f4\uff0c\u4ee5\u53ca\u5728\u7a0b\u5e8f\u7ed3\u675f\u65f6\uff08\u901a\u8fc7TimerOutput\u7c7b\u7684\u6790\u6784\u5668\uff09\uff0c\u6211\u4eec\u5c06\u4ea7\u751f\u4e00\u4e2a\u5f88\u597d\u7684\u603b\u7ed3\uff0c\u5373\u5728\u4e0d\u540c\u90e8\u5206\u82b1\u8d39\u7684\u65f6\u95f4\uff0c\u6211\u4eec\u628a\u8fd9\u4e2a\u7a0b\u5e8f\u7684\u8fd0\u884c\u65f6\u95f4\u5f52\u7c7b\u4e3a\u4e0d\u540c\u90e8\u5206\u3002\n\n    TimerOutput computing_timer; \n\n// \u5728\u8fd9\u4e9b\u6210\u5458\u53d8\u91cf\u4e4b\u540e\uff0c\u6211\u4eec\u6709\u4e00\u4e9b\u8f85\u52a9\u51fd\u6570\uff0c\u8fd9\u4e9b\u51fd\u6570\u5df2\u7ecf\u4ece\u4e0a\u9762\u5217\u51fa\u7684\u90a3\u4e9b\u51fd\u6570\u4e2d\u5206\u89e3\u51fa\u6765\u3002\u5177\u4f53\u6765\u8bf4\uff0c\u9996\u5148\u6709\u4e09\u4e2a\u6211\u4eec\u4ece <code>setup_dofs</code> \u4e2d\u8c03\u7528\u7684\u51fd\u6570\uff0c\u7136\u540e\u662f\u505a\u7ebf\u6027\u7cfb\u7edf\u7ec4\u88c5\u7684\u51fd\u6570\u3002\n\n    void setup_stokes_matrix( \n      const std::vector<IndexSet> &stokes_partitioning, \n      const std::vector<IndexSet> &stokes_relevant_partitioning); \n    void setup_stokes_preconditioner( \n      const std::vector<IndexSet> &stokes_partitioning, \n      const std::vector<IndexSet> &stokes_relevant_partitioning); \n    void setup_temperature_matrices( \n      const IndexSet &temperature_partitioning, \n      const IndexSet &temperature_relevant_partitioning); \n\n// \u9075\u5faa @ref MTWorkStream \"\u57fa\u4e8e\u4efb\u52a1\u7684\u5e76\u884c\u5316 \"\u8303\u5f0f\uff0c\u6211\u4eec\u5c06\u6240\u6709\u7684\u6c47\u7f16\u4f8b\u7a0b\u5206\u6210\u4e24\u90e8\u5206\uff1a\u7b2c\u4e00\u90e8\u5206\u53ef\u4ee5\u5728\u67d0\u4e2a\u5355\u5143\u4e0a\u505a\u6240\u6709\u7684\u8ba1\u7b97\uff0c\u800c\u4e0d\u9700\u8981\u7167\u987e\u5176\u4ed6\u7ebf\u7a0b\uff1b\u7b2c\u4e8c\u90e8\u5206\uff08\u5c31\u662f\u5c06\u672c\u5730\u6570\u636e\u5199\u5165\u5168\u5c40\u77e9\u9635\u548c\u5411\u91cf\u4e2d\uff09\uff0c\u6bcf\u6b21\u53ea\u80fd\u7531\u4e00\u4e2a\u7ebf\u7a0b\u8fdb\u5165\u3002\u4e3a\u4e86\u5b9e\u73b0\u8fd9\u4e00\u70b9\uff0c\u6211\u4eec\u4e3a\u8fd9\u4e00\u7a0b\u5e8f\u4e2d\u4f7f\u7528\u7684\u6240\u6709\u56db\u4e2a\u6c47\u7f16\u4f8b\u7a0b\u7684\u8fd9\u4e24\u4e2a\u6b65\u9aa4\u5206\u522b\u63d0\u4f9b\u4e86\u51fd\u6570\u3002\u4e0b\u9762\u7684\u516b\u4e2a\u51fd\u6570\u6b63\u662f\u8fd9\u6837\u505a\u7684\u3002\n\n    void local_assemble_stokes_preconditioner( \n      const typename DoFHandler<dim>::active_cell_iterator &cell, \n      Assembly::Scratch::StokesPreconditioner<dim> &        scratch, \n      Assembly::CopyData::StokesPreconditioner<dim> &       data); \n\n    void copy_local_to_global_stokes_preconditioner( \n      const Assembly::CopyData::StokesPreconditioner<dim> &data); \n\n    void local_assemble_stokes_system( \n      const typename DoFHandler<dim>::active_cell_iterator &cell, \n      Assembly::Scratch::StokesSystem<dim> &                scratch, \n      Assembly::CopyData::StokesSystem<dim> &               data); \n\n    void copy_local_to_global_stokes_system( \n      const Assembly::CopyData::StokesSystem<dim> &data); \n\n    void local_assemble_temperature_matrix( \n      const typename DoFHandler<dim>::active_cell_iterator &cell, \n      Assembly::Scratch::TemperatureMatrix<dim> &           scratch, \n      Assembly::CopyData::TemperatureMatrix<dim> &          data); \n\n    void copy_local_to_global_temperature_matrix( \n      const Assembly::CopyData::TemperatureMatrix<dim> &data); \n\n    void local_assemble_temperature_rhs( \n      const std::pair<double, double> global_T_range, \n      const double                    global_max_velocity, \n      const double                    global_entropy_variation, \n      const typename DoFHandler<dim>::active_cell_iterator &cell, \n      Assembly::Scratch::TemperatureRHS<dim> &              scratch, \n      Assembly::CopyData::TemperatureRHS<dim> &             data); \n\n    void copy_local_to_global_temperature_rhs( \n      const Assembly::CopyData::TemperatureRHS<dim> &data); \n\n// \u6700\u540e\uff0c\u6211\u4eec\u5411\u524d\u58f0\u660e\u4e00\u4e2a\u6210\u5458\u7c7b\uff0c\u6211\u4eec\u5c06\u5728\u4ee5\u540e\u5b9a\u4e49\u8fd9\u4e2a\u6210\u5458\u7c7b\uff0c\u5b83\u5c06\u88ab\u7528\u6765\u4ece\u6211\u4eec\u7684\u89e3\u51b3\u65b9\u6848\u5411\u91cf\u4e2d\u8ba1\u7b97\u4e00\u4e9b\u6570\u91cf\uff0c\u6211\u4eec\u5e0c\u671b\u5c06\u8fd9\u4e9b\u6570\u91cf\u653e\u5165\u8f93\u51fa\u6587\u4ef6\u4e2d\uff0c\u4ee5\u4fbf\u8fdb\u884c\u53ef\u89c6\u5316\u3002\n\n    class Postprocessor; \n  }; \n// @sect3{BoussinesqFlowProblem class implementation}  \n// @sect4{BoussinesqFlowProblem::Parameters}  \n\n// \u8fd9\u91cc\u662f\u5bf9\u65af\u6258\u514b\u65af\u95ee\u9898\u7684\u53c2\u6570\u7684\u5b9a\u4e49\u3002\u6211\u4eec\u5141\u8bb8\u8bbe\u7f6e\u6a21\u62df\u7684\u7ed3\u675f\u65f6\u95f4\u3001\u7ec6\u5316\u6c34\u5e73\uff08\u5305\u62ec\u5168\u5c40\u7ec6\u5316\u548c\u81ea\u9002\u5e94\u7ec6\u5316\uff0c\u603b\u7684\u6765\u8bf4\u5c31\u662f\u5141\u8bb8\u5355\u5143\u7684\u6700\u5927\u7ec6\u5316\u6c34\u5e73\uff09\uff0c\u4ee5\u53ca\u7ec6\u5316\u7684\u65f6\u95f4\u95f4\u9694\u3002\n\n// \u7136\u540e\uff0c\u6211\u4eec\u8ba9\u7528\u6237\u6307\u5b9a\u7a33\u5b9a\u53c2\u6570\u7684\u5e38\u6570\uff08\u5982\u4ecb\u7ecd\u4e2d\u6240\u8ba8\u8bba\u7684\uff09\u3001\u65af\u6258\u514b\u65af\u901f\u5ea6\u7a7a\u95f4\u7684\u591a\u9879\u5f0f\u7a0b\u5ea6\u3001\u662f\u5426\u5bf9\u538b\u529b\u4f7f\u7528\u57fa\u4e8eFE_DGP\u5143\u7d20\u7684\u5c40\u90e8\u4fdd\u5b88\u79bb\u6563\u5316\uff08\u5bf9\u538b\u529b\u4f7f\u7528FE_Q\u5143\u7d20\uff09\u3001\u4ee5\u53ca\u6e29\u5ea6\u63d2\u503c\u7684\u591a\u9879\u5f0f\u7a0b\u5ea6\u3002\n\n// \u6784\u9020\u51fd\u6570\u68c0\u67e5\u662f\u5426\u6709\u6709\u6548\u7684\u8f93\u5165\u6587\u4ef6\uff08\u5982\u679c\u6ca1\u6709\uff0c\u5c06\u5199\u4e00\u4e2a\u5e26\u6709\u9ed8\u8ba4\u53c2\u6570\u7684\u6587\u4ef6\uff09\uff0c\u5e76\u6700\u7ec8\u89e3\u6790\u53c2\u6570\u3002\n\n  template <int dim> \n  BoussinesqFlowProblem<dim>::Parameters::Parameters( \n    const std::string &parameter_filename) \n    : end_time(1e8) \n    , initial_global_refinement(2) \n    , initial_adaptive_refinement(2) \n    , adaptive_refinement_interval(10) \n    , stabilization_alpha(2) \n    , stabilization_c_R(0.11) \n    , stabilization_beta(0.078) \n    , stokes_velocity_degree(2) \n    , use_locally_conservative_discretization(true) \n    , temperature_degree(2) \n  { \n    ParameterHandler prm; \n    BoussinesqFlowProblem<dim>::Parameters::declare_parameters(prm); \n\n    std::ifstream parameter_file(parameter_filename); \n\n    if (!parameter_file) \n      { \n        parameter_file.close(); \n\n        std::ofstream parameter_out(parameter_filename); \n        prm.print_parameters(parameter_out, ParameterHandler::Text); \n\n        AssertThrow( \n          false, \n          ExcMessage( \n            \"Input parameter file <\" + parameter_filename + \n            \"> not found. Creating a template file of the same name.\")); \n      } \n\n    prm.parse_input(parameter_file); \n    parse_parameters(prm); \n  } \n\n// \u63a5\u4e0b\u6765\u6211\u4eec\u6709\u4e00\u4e2a\u51fd\u6570\uff0c\u58f0\u660e\u6211\u4eec\u5728\u8f93\u5165\u6587\u4ef6\u4e2d\u671f\u671b\u7684\u53c2\u6570\uff0c\u4ee5\u53ca\u5b83\u4eec\u7684\u6570\u636e\u7c7b\u578b\u3001\u9ed8\u8ba4\u503c\u548c\u63cf\u8ff0\u3002\n\n  template <int dim> \n  void BoussinesqFlowProblem<dim>::Parameters::declare_parameters( \n    ParameterHandler &prm) \n  { \n    prm.declare_entry(\"End time\", \n                      \"1e8\", \n                      Patterns::Double(0), \n                      \"The end time of the simulation in years.\"); \n    prm.declare_entry(\"Initial global refinement\", \n                      \"2\", \n                      Patterns::Integer(0), \n                      \"The number of global refinement steps performed on \" \n                      \"the initial coarse mesh, before the problem is first \" \n                      \"solved there.\"); \n    prm.declare_entry(\"Initial adaptive refinement\", \n                      \"2\", \n                      Patterns::Integer(0), \n                      \"The number of adaptive refinement steps performed after \" \n                      \"initial global refinement.\"); \n    prm.declare_entry(\"Time steps between mesh refinement\", \n                      \"10\", \n                      Patterns::Integer(1), \n                      \"The number of time steps after which the mesh is to be \" \n                      \"adapted based on computed error indicators.\"); \n    prm.declare_entry(\"Generate graphical output\", \n                      \"false\", \n                      Patterns::Bool(), \n                      \"Whether graphical output is to be generated or not. \" \n                      \"You may not want to get graphical output if the number \" \n                      \"of processors is large.\"); \n    prm.declare_entry(\"Time steps between graphical output\", \n                      \"50\", \n                      Patterns::Integer(1), \n                      \"The number of time steps between each generation of \" \n                      \"graphical output files.\"); \n\n    prm.enter_subsection(\"Stabilization parameters\"); \n    { \n      prm.declare_entry(\"alpha\", \n                        \"2\", \n                        Patterns::Double(1, 2), \n                        \"The exponent in the entropy viscosity stabilization.\"); \n      prm.declare_entry(\"c_R\", \n                        \"0.11\", \n                        Patterns::Double(0), \n                        \"The c_R factor in the entropy viscosity \" \n                        \"stabilization.\"); \n      prm.declare_entry(\"beta\", \n                        \"0.078\", \n                        Patterns::Double(0), \n                        \"The beta factor in the artificial viscosity \" \n                        \"stabilization. An appropriate value for 2d is 0.052 \" \n                        \"and 0.078 for 3d.\"); \n    } \n    prm.leave_subsection(); \n\n    prm.enter_subsection(\"Discretization\"); \n    { \n      prm.declare_entry( \n        \"Stokes velocity polynomial degree\", \n        \"2\", \n        Patterns::Integer(1), \n        \"The polynomial degree to use for the velocity variables \" \n        \"in the Stokes system.\"); \n      prm.declare_entry( \n        \"Temperature polynomial degree\", \n        \"2\", \n        Patterns::Integer(1), \n        \"The polynomial degree to use for the temperature variable.\"); \n      prm.declare_entry( \n        \"Use locally conservative discretization\", \n        \"true\", \n        Patterns::Bool(), \n        \"Whether to use a Stokes discretization that is locally \" \n        \"conservative at the expense of a larger number of degrees \" \n        \"of freedom, or to go with a cheaper discretization \" \n        \"that does not locally conserve mass (although it is \" \n        \"globally conservative.\"); \n    } \n    prm.leave_subsection(); \n  } \n\n// \u7136\u540e\uff0c\u6211\u4eec\u9700\u8981\u4e00\u4e2a\u51fd\u6570\u6765\u8bfb\u53d6\u6211\u4eec\u901a\u8fc7\u8bfb\u53d6\u8f93\u5165\u6587\u4ef6\u5f97\u5230\u7684ParameterHandler\u5bf9\u8c61\u7684\u5185\u5bb9\uff0c\u5e76\u5c06\u7ed3\u679c\u653e\u5165\u50a8\u5b58\u6211\u4eec\u4e4b\u524d\u58f0\u660e\u7684\u53c2\u6570\u503c\u7684\u53d8\u91cf\u3002\n\n  template <int dim> \n  void BoussinesqFlowProblem<dim>::Parameters::parse_parameters( \n    ParameterHandler &prm) \n  { \n    end_time                  = prm.get_double(\"End time\"); \n    initial_global_refinement = prm.get_integer(\"Initial global refinement\"); \n    initial_adaptive_refinement = \n      prm.get_integer(\"Initial adaptive refinement\"); \n\n    adaptive_refinement_interval = \n      prm.get_integer(\"Time steps between mesh refinement\"); \n\n    generate_graphical_output = prm.get_bool(\"Generate graphical output\"); \n    graphical_output_interval = \n      prm.get_integer(\"Time steps between graphical output\"); \n\n    prm.enter_subsection(\"Stabilization parameters\"); \n    { \n      stabilization_alpha = prm.get_double(\"alpha\"); \n      stabilization_c_R   = prm.get_double(\"c_R\"); \n      stabilization_beta  = prm.get_double(\"beta\"); \n    } \n    prm.leave_subsection(); \n\n    prm.enter_subsection(\"Discretization\"); \n    { \n      stokes_velocity_degree = \n        prm.get_integer(\"Stokes velocity polynomial degree\"); \n      temperature_degree = prm.get_integer(\"Temperature polynomial degree\"); \n      use_locally_conservative_discretization = \n        prm.get_bool(\"Use locally conservative discretization\"); \n    } \n    prm.leave_subsection(); \n  } \n\n//  @sect4{BoussinesqFlowProblem::BoussinesqFlowProblem}  \n\n// \u8be5\u95ee\u9898\u7684\u6784\u9020\u51fd\u6570\u4e0e  step-31  \u4e2d\u7684\u6784\u9020\u51fd\u6570\u975e\u5e38\u76f8\u4f3c\u3002\u4e0d\u540c\u7684\u662f%\u5e76\u884c\u901a\u4fe1\u3002Trilinos\u4f7f\u7528\u6d88\u606f\u4f20\u9012\u63a5\u53e3\uff08MPI\uff09\u8fdb\u884c\u6570\u636e\u5206\u914d\u3002\u5f53\u8fdb\u5165BoussinesqFlowProblem\u7c7b\u65f6\uff0c\u6211\u4eec\u5fc5\u987b\u51b3\u5b9a\u5982\u4f55\u8fdb\u884c\u5e76\u884c\u5316\u3002\u6211\u4eec\u9009\u62e9\u4e00\u4e2a\u76f8\u5f53\u7b80\u5355\u7684\u7b56\u7565\uff0c\u8ba9\u6240\u6709\u6b63\u5728\u8fd0\u884c\u7a0b\u5e8f\u7684\u5904\u7406\u5668\u4e00\u8d77\u5de5\u4f5c\uff0c\u7531\u901a\u4fe1\u5668  <code>MPI_COMM_WORLD</code>  \u6307\u5b9a\u3002\u63a5\u4e0b\u6765\uff0c\u6211\u4eec\u521b\u5efa\u8f93\u51fa\u6d41\uff08\u5c31\u50cf\u6211\u4eec\u5728 step-18 \u4e2d\u5df2\u7ecf\u505a\u7684\u90a3\u6837\uff09\uff0c\u5b83\u53ea\u5728\u7b2c\u4e00\u4e2aMPI\u8fdb\u7a0b\u4e0a\u4ea7\u751f\u8f93\u51fa\uff0c\u800c\u5728\u5176\u4ed6\u6240\u6709\u8fdb\u7a0b\u4e0a\u5219\u5b8c\u5168\u4e0d\u8003\u8651\u3002\u8fd9\u4e2a\u60f3\u6cd5\u7684\u5b9e\u73b0\u662f\u5728 <code>pcout</code> \u5f97\u5230\u4e00\u4e2a\u771f\u5b9e\u53c2\u6570\u65f6\u68c0\u67e5\u8fdb\u7a0b\u53f7\uff0c\u5b83\u4f7f\u7528 <code>std::cout</code> \u6d41\u8fdb\u884c\u8f93\u51fa\u3002\u4f8b\u5982\uff0c\u5982\u679c\u6211\u4eec\u662f\u4e00\u4e2a\u5904\u7406\u5668\u4e94\uff0c\u90a3\u4e48\u6211\u4eec\u5c06\u7ed9\u51fa\u4e00\u4e2a  <code>false</code> argument to <code>pcout</code>  \uff0c\u8fd9\u610f\u5473\u7740\u8be5\u5904\u7406\u5668\u7684\u8f93\u51fa\u5c06\u4e0d\u4f1a\u88ab\u6253\u5370\u3002\u9664\u4e86\u6620\u5c04\u5bf9\u8c61\uff08\u6211\u4eec\u5bf9\u5176\u4f7f\u75284\u5ea6\u7684\u591a\u9879\u5f0f\uff09\uff0c\u9664\u4e86\u6700\u540e\u7684\u6210\u5458\u53d8\u91cf\u5916\uff0c\u5176\u4ed6\u90fd\u4e0e  step-31  \u4e2d\u7684\u5b8c\u5168\u76f8\u540c\u3002\n\n// \u8fd9\u4e2a\u6700\u540e\u7684\u5bf9\u8c61\uff0cTimerOutput\u5bf9\u8c61\uff0c\u7136\u540e\u88ab\u544a\u77e5\u9650\u5236\u8f93\u51fa\u5230 <code>pcout</code> \u6d41\uff08\u5904\u7406\u56680\uff09\uff0c\u7136\u540e\u6211\u4eec\u6307\u5b9a\u8981\u5728\u7a0b\u5e8f\u7ed3\u675f\u65f6\u5f97\u5230\u4e00\u4e2a\u6c47\u603b\u8868\uff0c\u8be5\u8868\u663e\u793a\u6211\u4eec\u7684\u58c1\u6302\u65f6\u949f\u65f6\u95f4\uff08\u800c\u4e0d\u662fCPU\u65f6\u95f4\uff09\u3002\u6211\u4eec\u8fd8\u5c06\u5728\u4e0b\u9762\u7684 <code>run()</code> \u51fd\u6570\u4e2d\u624b\u52a8\u8bf7\u6c42\u6bcf\u9694\u8fd9\u4e48\u591a\u65f6\u95f4\u6b65\u7684\u4e2d\u95f4\u603b\u7ed3\u3002\n\n  template <int dim> \n  BoussinesqFlowProblem<dim>::BoussinesqFlowProblem(Parameters &parameters_) \n    : parameters(parameters_) \n    , pcout(std::cout, (Utilities::MPI::this_mpi_process(MPI_COMM_WORLD) == 0)) \n    , \n\n    triangulation(MPI_COMM_WORLD, \n                  typename Triangulation<dim>::MeshSmoothing( \n                    Triangulation<dim>::smoothing_on_refinement | \n                    Triangulation<dim>::smoothing_on_coarsening)) \n    , \n\n    global_Omega_diameter(0.) \n    , \n\n    mapping(4) \n    , \n\n    stokes_fe(FE_Q<dim>(parameters.stokes_velocity_degree), \n              dim, \n              (parameters.use_locally_conservative_discretization ? \n                 static_cast<const FiniteElement<dim> &>( \n                   FE_DGP<dim>(parameters.stokes_velocity_degree - 1)) : \n                 static_cast<const FiniteElement<dim> &>( \n                   FE_Q<dim>(parameters.stokes_velocity_degree - 1))), \n              1) \n    , \n\n    stokes_dof_handler(triangulation) \n    , \n\n    temperature_fe(parameters.temperature_degree) \n    , temperature_dof_handler(triangulation) \n    , \n\n    time_step(0) \n    , old_time_step(0) \n    , timestep_number(0) \n    , rebuild_stokes_matrix(true) \n    , rebuild_stokes_preconditioner(true) \n    , rebuild_temperature_matrices(true) \n    , rebuild_temperature_preconditioner(true) \n    , \n\n    computing_timer(MPI_COMM_WORLD, \n                    pcout, \n                    TimerOutput::summary, \n                    TimerOutput::wall_times) \n  {} \n\n//  @sect4{The BoussinesqFlowProblem helper functions}  \n// @sect5{BoussinesqFlowProblem::get_maximal_velocity}  \n\n// \u9664\u4e86\u4e24\u4e2a\u5c0f\u7ec6\u8282\u5916\uff0c\u8ba1\u7b97\u901f\u5ea6\u5168\u5c40\u6700\u5927\u503c\u7684\u51fd\u6570\u4e0e step-31 \u4e2d\u7684\u76f8\u540c\u3002\u7b2c\u4e00\u4e2a\u7ec6\u8282\u5b9e\u9645\u4e0a\u662f\u6240\u6709\u5728\u4e09\u89d2\u5f62\u7684\u6240\u6709\u5355\u5143\u4e0a\u5b9e\u73b0\u5faa\u73af\u7684\u51fd\u6570\u6240\u5171\u6709\u7684\u3002\u5f53\u4ee5%\u5e76\u884c\u65b9\u5f0f\u64cd\u4f5c\u65f6\uff0c\u6bcf\u4e2a\u5904\u7406\u5668\u53ea\u80fd\u5904\u7406\u4e00\u5927\u5757\u5355\u5143\uff0c\u56e0\u4e3a\u6bcf\u4e2a\u5904\u7406\u5668\u53ea\u62e5\u6709\u6574\u4e2a\u4e09\u89d2\u7ed3\u6784\u7684\u67d0\u4e00\u90e8\u5206\u3002\u6211\u4eec\u8981\u5904\u7406\u7684\u8fd9\u5757\u5355\u5143\u662f\u901a\u8fc7\u6240\u8c13\u7684 <code>subdomain_id</code> \u6765\u786e\u5b9a\u7684\uff0c\u6b63\u5982\u6211\u4eec\u5728 step-18 \u4e2d\u505a\u7684\u90a3\u6837\u3002\u56e0\u6b64\uff0c\u6211\u4eec\u9700\u8981\u6539\u53d8\u7684\u662f\u53ea\u5bf9\u5f53\u524d\u8fdb\u7a0b\u6240\u62e5\u6709\u7684\u5355\u5143\u683c\uff08\u76f8\u5bf9\u4e8e\u5e7d\u7075\u6216\u4eba\u9020\u5355\u5143\u683c\uff09\u8fdb\u884c\u4e0e\u5355\u5143\u683c\u76f8\u5173\u7684\u64cd\u4f5c\uff0c\u5373\u5bf9\u5b50\u57dfid\u7b49\u4e8e\u8fdb\u7a0bID\u7684\u6570\u5b57\u3002\u7531\u4e8e\u8fd9\u662f\u4e00\u4e2a\u5e38\u7528\u7684\u64cd\u4f5c\uff0c\u6240\u4ee5\u8fd9\u4e2a\u64cd\u4f5c\u6709\u4e00\u4e2a\u5feb\u6377\u65b9\u5f0f\uff1a\u6211\u4eec\u53ef\u4ee5\u7528 <code>cell-@>is_locally_owned()</code> \u8be2\u95ee\u5355\u5143\u683c\u662f\u5426\u4e3a\u5f53\u524d\u5904\u7406\u5668\u6240\u62e5\u6709\u3002\n\n// \u7b2c\u4e8c\u4e2a\u533a\u522b\u662f\u6211\u4eec\u8ba1\u7b97\u6700\u5927\u503c\u7684\u65b9\u5f0f\u3002\u4ee5\u524d\uff0c\u6211\u4eec\u53ef\u4ee5\u7b80\u5355\u5730\u6709\u4e00\u4e2a <code>double</code> \u53d8\u91cf\uff0c\u5728\u6bcf\u4e2a\u5355\u5143\u7684\u6bcf\u4e2a\u6b63\u4ea4\u70b9\u4e0a\u8fdb\u884c\u68c0\u67e5\u3002\u73b0\u5728\uff0c\u6211\u4eec\u5fc5\u987b\u66f4\u52a0\u5c0f\u5fc3\uff0c\u56e0\u4e3a\u6bcf\u4e2a\u5904\u7406\u5668\u53ea\u5bf9\u5355\u5143\u683c\u7684\u4e00\u4e2a\u5b50\u96c6\u8fdb\u884c\u64cd\u4f5c\u3002\u6211\u4eec\u8981\u505a\u7684\u662f\uff0c\u9996\u5148\u8ba9\u6bcf\u4e2a\u5904\u7406\u5668\u8ba1\u7b97\u5176\u5355\u5143\u4e2d\u7684\u6700\u5927\u503c\uff0c\u7136\u540e\u505a\u4e00\u4e2a\u5168\u5c40\u901a\u4fe1\u64cd\u4f5c <code>Utilities::MPI::max</code> \uff0c\u8ba1\u7b97\u5404\u4e2a\u5904\u7406\u5668\u6240\u6709\u6700\u5927\u503c\u4e2d\u7684\u6700\u5927\u503c\u3002MPI\u63d0\u4f9b\u4e86\u8fd9\u6837\u7684\u8c03\u7528\uff0c\u4f46\u66f4\u7b80\u5355\u7684\u662f\u4f7f\u7528MPI\u901a\u4fe1\u5668\u5bf9\u8c61\u5728\u547d\u540d\u7a7a\u95f4 Utilities::MPI \u4e2d\u4f7f\u7528\u76f8\u5e94\u7684\u51fd\u6570\uff0c\u56e0\u4e3a\u5373\u4f7f\u6211\u4eec\u6ca1\u6709MPI\u5e76\u4e14\u53ea\u5728\u4e00\u53f0\u673a\u5668\u4e0a\u5de5\u4f5c\uff0c\u8fd9\u4e5f\u4f1a\u505a\u6b63\u786e\u7684\u4e8b\u60c5\u3002\u5bf9 <code>Utilities::MPI::max</code> \u7684\u8c03\u7528\u9700\u8981\u4e24\u4e2a\u53c2\u6570\uff0c\u5373\u672c\u5730\u6700\u5927\u503c\uff08input\uff09\u548cMPI\u901a\u4fe1\u5668\uff0c\u5728\u8fd9\u4e2a\u4f8b\u5b50\u4e2d\u662fMPI_COMM_WORLD\u3002\n\n  template <int dim> \n  double BoussinesqFlowProblem<dim>::get_maximal_velocity() const \n  { \n    const QIterated<dim> quadrature_formula(QTrapezoid<1>(), \n                                            parameters.stokes_velocity_degree); \n    const unsigned int   n_q_points = quadrature_formula.size(); \n\n    FEValues<dim>               fe_values(mapping, \n                            stokes_fe, \n                            quadrature_formula, \n                            update_values); \n    std::vector<Tensor<1, dim>> velocity_values(n_q_points); \n\n    const FEValuesExtractors::Vector velocities(0); \n\n    double max_local_velocity = 0; \n\n    for (const auto &cell : stokes_dof_handler.active_cell_iterators()) \n      if (cell->is_locally_owned()) \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_local_velocity = \n              std::max(max_local_velocity, velocity_values[q].norm()); \n        } \n\n    return Utilities::MPI::max(max_local_velocity, MPI_COMM_WORLD); \n  } \n// @sect5{BoussinesqFlowProblem::get_cfl_number}  \n\n// \u4e0b\u4e00\u4e2a\u51fd\u6570\u505a\u4e86\u7c7b\u4f3c\u7684\u4e8b\u60c5\uff0c\u4f46\u6211\u4eec\u73b0\u5728\u8ba1\u7b97CFL\u6570\uff0c\u5373\u4e00\u4e2a\u5355\u5143\u4e0a\u7684\u6700\u5927\u901f\u5ea6\u9664\u4ee5\u5355\u5143\u76f4\u5f84\u3002\u8fd9\u4e2a\u6570\u5b57\u5bf9\u4e8e\u786e\u5b9a\u65f6\u95f4\u6b65\u957f\u662f\u5fc5\u8981\u7684\uff0c\u56e0\u4e3a\u6211\u4eec\u5bf9\u6e29\u5ea6\u65b9\u7a0b\u4f7f\u7528\u534a\u663e\u5f0f\u7684\u65f6\u95f4\u6b65\u957f\u65b9\u6848\uff08\u8ba8\u8bba\u89c1 step-31 \uff09\u3002\u6211\u4eec\u7528\u4e0a\u8ff0\u540c\u6837\u7684\u65b9\u6cd5\u8ba1\u7b97\u5b83\u3002\u5728\u6240\u6709\u672c\u5730\u62e5\u6709\u7684\u5355\u5143\u4e0a\u8ba1\u7b97\u672c\u5730\u6700\u5927\u503c\uff0c\u7136\u540e\u901a\u8fc7MPI\u4ea4\u6362\uff0c\u627e\u5230\u5168\u7403\u6700\u5927\u503c\u3002\n\n  template <int dim> \n  double BoussinesqFlowProblem<dim>::get_cfl_number() const \n  { \n    const QIterated<dim> quadrature_formula(QTrapezoid<1>(), \n                                            parameters.stokes_velocity_degree); \n    const unsigned int   n_q_points = quadrature_formula.size(); \n\n    FEValues<dim>               fe_values(mapping, \n                            stokes_fe, \n                            quadrature_formula, \n                            update_values); \n    std::vector<Tensor<1, dim>> velocity_values(n_q_points); \n\n    const FEValuesExtractors::Vector velocities(0); \n\n    double max_local_cfl = 0; \n\n    for (const auto &cell : stokes_dof_handler.active_cell_iterators()) \n      if (cell->is_locally_owned()) \n        { \n          fe_values.reinit(cell); \n          fe_values[velocities].get_function_values(stokes_solution, \n                                                    velocity_values); \n\n          double max_local_velocity = 1e-10; \n          for (unsigned int q = 0; q < n_q_points; ++q) \n            max_local_velocity = \n              std::max(max_local_velocity, velocity_values[q].norm()); \n          max_local_cfl = \n            std::max(max_local_cfl, max_local_velocity / cell->diameter()); \n        } \n\n    return Utilities::MPI::max(max_local_cfl, MPI_COMM_WORLD); \n  } \n// @sect5{BoussinesqFlowProblem::get_entropy_variation}  \n\n// \u63a5\u4e0b\u6765\u662f\u8ba1\u7b97\u5168\u5c40\u71b5\u7684\u53d8\u5316 $\\|E(T)-\\bar{E}(T)\\|_\\infty$ \uff0c\u5176\u4e2d\u71b5 $E$ \u7684\u5b9a\u4e49\u5982\u4ecb\u7ecd\u4e2d\u6240\u8ba8\u8bba\u7684\u3002 \u8fd9\u5bf9\u4e8e\u8bc4\u4f30\u6e29\u5ea6\u65b9\u7a0b\u4e2d\u7684\u7a33\u5b9a\u5ea6\u662f\u5fc5\u8981\u7684\uff0c\u6b63\u5982\u4ecb\u7ecd\u4e2d\u6240\u89e3\u91ca\u7684\u3002\u5b9e\u9645\u4e0a\uff0c\u53ea\u6709\u5f53\u6211\u4eec\u5728\u6b8b\u5dee\u8ba1\u7b97\u4e2d\u4f7f\u7528 $\\alpha=2$ \u4f5c\u4e3a\u5e42\u65f6\uff0c\u624d\u9700\u8981\u71b5\u7684\u53d8\u5316\u3002\u65e0\u9650\u51c6\u5219\u662f\u7531\u6b63\u4ea4\u70b9\u4e0a\u7684\u6700\u5927\u503c\u8ba1\u7b97\u51fa\u6765\u7684\uff0c\u5c31\u50cf\u79bb\u6563\u8ba1\u7b97\u4e2d\u901a\u5e38\u7684\u90a3\u6837\u3002\n\n// \u4e3a\u4e86\u8ba1\u7b97\u8fd9\u4e2a\u91cf\uff0c\u6211\u4eec\u9996\u5148\u8981\u627e\u5230\u7a7a\u95f4\u5e73\u5747\u6570 $\\bar{E}(T)$ \uff0c\u7136\u540e\u8bc4\u4f30\u6700\u5927\u503c\u3002\u7136\u800c\uff0c\u8fd9\u610f\u5473\u7740\u6211\u4eec\u9700\u8981\u6267\u884c\u4e24\u4e2a\u5faa\u73af\u3002\u6211\u4eec\u53ef\u4ee5\u901a\u8fc7\u6ce8\u610f\u5230 $\\|E(T)-\\bar{E}(T)\\|_\\infty =\n//  \\max\\big(E_{\\textrm{max}}(T)-\\bar{E}(T),\n//  \\bar{E}(T)-E_{\\textrm{min}}(T)\\big)$ \uff0c\u5373\u6b63\u8d1f\u65b9\u5411\u4e0a\u4e0e\u5e73\u5747\u71b5\u7684\u504f\u5dee\u7684\u6700\u5927\u503c\u6765\u907f\u514d\u5f00\u9500\u3002\u6211\u4eec\u5728\u540e\u4e00\u4e2a\u516c\u5f0f\u4e2d\u9700\u8981\u7684\u56db\u4e2a\u91cf\uff08\u6700\u5927\u71b5\u3001\u6700\u5c0f\u71b5\u3001\u5e73\u5747\u71b5\u3001\u9762\u79ef\uff09\u90fd\u53ef\u4ee5\u5728\u6240\u6709\u5355\u5143\u683c\u7684\u540c\u4e00\u4e2a\u5faa\u73af\u4e2d\u8fdb\u884c\u8bc4\u4f30\uff0c\u6240\u4ee5\u6211\u4eec\u9009\u62e9\u8fd9\u4e2a\u66f4\u7b80\u5355\u7684\u53d8\u4f53\u3002\n\n  template <int dim> \n  double BoussinesqFlowProblem<dim>::get_entropy_variation( \n    const double average_temperature) const \n  { \n    if (parameters.stabilization_alpha != 2) \n      return 1.; \n\n    const QGauss<dim>  quadrature_formula(parameters.temperature_degree + 1); \n    const unsigned int n_q_points = quadrature_formula.size(); \n\n    FEValues<dim>       fe_values(temperature_fe, \n                            quadrature_formula, \n                            update_values | update_JxW_values); \n    std::vector<double> old_temperature_values(n_q_points); \n    std::vector<double> old_old_temperature_values(n_q_points); \n\n// \u5728\u4e0a\u9762\u7684\u4e24\u4e2a\u51fd\u6570\u4e2d\uff0c\u6211\u4eec\u8ba1\u7b97\u4e86\u6240\u6709\u975e\u8d1f\u6570\u7684\u6700\u5927\u503c\uff0c\u6240\u4ee5\u6211\u4eec\u77e5\u90530\u80af\u5b9a\u662f\u4e00\u4e2a\u4e0b\u9650\u3002\u53e6\u4e00\u65b9\u9762\uff0c\u5728\u8fd9\u91cc\u6211\u4eec\u9700\u8981\u627e\u5230\u4e0e\u5e73\u5747\u503c\u7684\u6700\u5927\u504f\u5dee\uff0c\u4e5f\u5c31\u662f\u8bf4\uff0c\u6211\u4eec\u9700\u8981\u77e5\u9053\u71b5\u7684\u6700\u5927\u548c\u6700\u5c0f\u503c\uff0c\u800c\u8fd9\u4e9b\u503c\u7684\u7b26\u53f7\u6211\u4eec\u5e76\u4e0d\u4e8b\u5148\u77e5\u9053\u3002\n\n// \u4e3a\u4e86\u8ba1\u7b97\u5b83\uff0c\u6211\u4eec\u53ef\u4ee5\u4ece\u6211\u4eec\u53ef\u4ee5\u5b58\u50a8\u5728\u4e00\u4e2a\u53cc\u7cbe\u5ea6\u6570\u5b57\u4e2d\u7684\u6700\u5927\u548c\u6700\u5c0f\u7684\u53ef\u80fd\u503c\u5f00\u59cb\u3002\u6700\u5c0f\u503c\u88ab\u521d\u59cb\u5316\u4e3a\u4e00\u4e2a\u66f4\u5927\u7684\u6570\u5b57\uff0c\u6700\u5927\u503c\u88ab\u521d\u59cb\u5316\u4e3a\u4e00\u4e2a\u6bd4\u5c06\u8981\u51fa\u73b0\u7684\u4efb\u4f55\u4e00\u4e2a\u6570\u5b57\u90fd\u5c0f\u7684\u6570\u5b57\u3002\u7136\u540e\uff0c\u6211\u4eec\u4fdd\u8bc1\u8fd9\u4e9b\u6570\u5b57\u5c06\u5728\u7b2c\u4e00\u4e2a\u5355\u5143\u7684\u5faa\u73af\u4e2d\u88ab\u8986\u76d6\uff0c\u6216\u8005\uff0c\u5982\u679c\u8fd9\u4e2a\u5904\u7406\u5668\u4e0d\u62e5\u6709\u4efb\u4f55\u5355\u5143\uff0c\u6700\u8fdf\u5728\u901a\u4fe1\u6b65\u9aa4\u4e2d\u88ab\u8986\u76d6\u3002\u4e0b\u9762\u7684\u5faa\u73af\u5c06\u8ba1\u7b97\u6700\u5c0f\u548c\u6700\u5927\u7684\u5c40\u90e8\u71b5\uff0c\u5e76\u8ddf\u8e2a\u6211\u4eec\u5c40\u90e8\u62e5\u6709\u7684\u57df\u7684\u9762\u79ef/\u4f53\u79ef\uff0c\u4ee5\u53ca\u5bf9\u5176\u71b5\u7684\u79ef\u5206\u3002\n\n    double min_entropy = std::numeric_limits<double>::max(), \n           max_entropy = -std::numeric_limits<double>::max(), area = 0, \n           entropy_integrated = 0; \n\n    for (const auto &cell : temperature_dof_handler.active_cell_iterators()) \n      if (cell->is_locally_owned()) \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          for (unsigned int q = 0; q < n_q_points; ++q) \n            { \n              const double T = \n                (old_temperature_values[q] + old_old_temperature_values[q]) / 2; \n              const double entropy = \n                ((T - average_temperature) * (T - average_temperature)); \n\n              min_entropy = std::min(min_entropy, entropy); \n              max_entropy = std::max(max_entropy, entropy); \n              area += fe_values.JxW(q); \n              entropy_integrated += fe_values.JxW(q) * entropy; \n            } \n        } \n\n// \u73b0\u5728\u6211\u4eec\u53ea\u9700\u8981\u5728\u5904\u7406\u5668\u4e4b\u95f4\u4ea4\u6362\u6570\u636e\uff1a\u6211\u4eec\u9700\u8981\u5c06\u4e24\u4e2a\u79ef\u5206\u76f8\u52a0\uff08  <code>area</code>, <code>entropy_integrated</code>  \uff09\uff0c\u5e76\u5f97\u5230\u6700\u5927\u548c\u6700\u5c0f\u7684\u6781\u503c\u3002\u6211\u4eec\u53ef\u4ee5\u901a\u8fc7\u56db\u4e2a\u4e0d\u540c\u7684\u6570\u636e\u4ea4\u6362\u6765\u5b8c\u6210\u8fd9\u4e2a\u4efb\u52a1\uff0c\u4f46\u6211\u4eec\u53ea\u9700\u8981\u4e24\u4e2a\u5c31\u53ef\u4ee5\u4e86\u3002  Utilities::MPI::sum \u4e5f\u6709\u4e00\u4e2a\u53d8\u4f53\uff0c\u5b83\u63a5\u53d7\u4e00\u4e2a\u6570\u7ec4\u7684\u503c\uff0c\u8fd9\u4e9b\u503c\u90fd\u662f\u8981\u52a0\u8d77\u6765\u7684\u3002\u6211\u4eec\u8fd8\u53ef\u4ee5\u5229\u7528 Utilities::MPI::max \u51fd\u6570\uff0c\u8ba4\u8bc6\u5230\u5728\u6700\u5c0f\u71b5\u4e0a\u5f62\u6210\u6700\u5c0f\u503c\u7b49\u4e8e\u5728\u6700\u5c0f\u71b5\u7684\u8d1f\u503c\u4e0a\u5f62\u6210\u6700\u5927\u503c\u7684\u8d1f\u503c\uff1b\u7136\u540e\u8fd9\u4e2a\u6700\u5927\u503c\u53ef\u4ee5\u4e0e\u5728\u6700\u5927\u71b5\u4e0a\u5f62\u6210\u6700\u5927\u503c\u7ed3\u5408\u8d77\u6765\u3002\n\n    const double local_sums[2]   = {entropy_integrated, area}, \n                 local_maxima[2] = {-min_entropy, max_entropy}; \n    double global_sums[2], global_maxima[2]; \n\n    Utilities::MPI::sum(local_sums, MPI_COMM_WORLD, global_sums); \n    Utilities::MPI::max(local_maxima, MPI_COMM_WORLD, global_maxima); \n\n// \u4ee5\u8fd9\u79cd\u65b9\u5f0f\u8ba1\u7b97\u4e86\u6240\u6709\u7684\u4e1c\u897f\u4e4b\u540e\uff0c\u6211\u4eec\u5c31\u53ef\u4ee5\u8ba1\u7b97\u5e73\u5747\u71b5\uff0c\u5e76\u901a\u8fc7\u53d6\u6700\u5927\u503c\u6216\u6700\u5c0f\u503c\u4e0e\u5e73\u5747\u503c\u7684\u504f\u5dee\u4e2d\u7684\u8f83\u5927\u503c\u6765\u627e\u5230 $L^\\infty$ \u51c6\u5219\u3002\n\n    const double average_entropy = global_sums[0] / global_sums[1]; \n    const double entropy_diff    = std::max(global_maxima[1] - average_entropy, \n                                         average_entropy - (-global_maxima[0])); \n    return entropy_diff; \n  } \n\n//  @sect5{BoussinesqFlowProblem::get_extrapolated_temperature_range}  \n\n// \u4e0b\u4e00\u4e2a\u51fd\u6570\u662f\u8ba1\u7b97\u6574\u4e2a\u9886\u57df\u5185\u5916\u63a8\u6e29\u5ea6\u7684\u6700\u5c0f\u503c\u548c\u6700\u5927\u503c\u3002\u540c\u6837\uff0c\u8fd9\u53ea\u662f  step-31  \u4e2d\u76f8\u5e94\u51fd\u6570\u7684\u4e00\u4e2a\u7565\u5fae\u4fee\u6539\u7684\u7248\u672c\u3002\u548c\u4e0a\u9762\u7684\u51fd\u6570\u4e00\u6837\uff0c\u6211\u4eec\u6536\u96c6\u5c40\u90e8\u6700\u5c0f\u503c\u548c\u6700\u5927\u503c\uff0c\u7136\u540e\u7528\u4e0a\u9762\u7684\u6280\u5de7\u8ba1\u7b97\u5168\u5c40\u6781\u503c\u3002\n\n// \u6b63\u5982\u5728 step-31 \u4e2d\u5df2\u7ecf\u8ba8\u8bba\u8fc7\u7684\uff0c\u8be5\u51fd\u6570\u9700\u8981\u533a\u5206\u7b2c\u4e00\u4e2a\u65f6\u95f4\u6b65\u957f\u548c\u6240\u6709\u540e\u7eed\u65f6\u95f4\u6b65\u957f\uff0c\u56e0\u4e3a\u5f53\u81f3\u5c11\u6709\u4e24\u4e2a\u4ee5\u524d\u7684\u65f6\u95f4\u6b65\u957f\u65f6\uff0c\u5b83\u4f7f\u7528\u4e86\u4e00\u4e2a\u9ad8\u9636\u6e29\u5ea6\u5916\u63a8\u65b9\u6848\u3002\n\n  template <int dim> \n  std::pair<double, double> \n  BoussinesqFlowProblem<dim>::get_extrapolated_temperature_range() const \n  { \n    const QIterated<dim> quadrature_formula(QTrapezoid<1>(), \n                                            parameters.temperature_degree); \n    const unsigned int   n_q_points = quadrature_formula.size(); \n\n    FEValues<dim>       fe_values(mapping, \n                            temperature_fe, \n                            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    double min_local_temperature = std::numeric_limits<double>::max(), \n           max_local_temperature = -std::numeric_limits<double>::max(); \n\n    if (timestep_number != 0) \n      { \n        for (const auto &cell : temperature_dof_handler.active_cell_iterators()) \n          if (cell->is_locally_owned()) \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) * \n                      old_temperature_values[q] - \n                    time_step / old_time_step * old_old_temperature_values[q]; \n\n                  min_local_temperature = \n                    std::min(min_local_temperature, temperature); \n                  max_local_temperature = \n                    std::max(max_local_temperature, temperature); \n                } \n            } \n      } \n    else \n      { \n        for (const auto &cell : temperature_dof_handler.active_cell_iterators()) \n          if (cell->is_locally_owned()) \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_local_temperature = \n                    std::min(min_local_temperature, temperature); \n                  max_local_temperature = \n                    std::max(max_local_temperature, temperature); \n                } \n            } \n      } \n\n    double local_extrema[2] = {-min_local_temperature, max_local_temperature}; \n    double global_extrema[2]; \n    Utilities::MPI::max(local_extrema, MPI_COMM_WORLD, global_extrema); \n\n    return std::make_pair(-global_extrema[0], global_extrema[1]); \n  } \n// @sect5{BoussinesqFlowProblem::compute_viscosity}  \n\n// \u8ba1\u7b97\u7c98\u5ea6\u7684\u51fd\u6570\u662f\u7eaf\u7cb9\u7684\u672c\u5730\u51fd\u6570\uff0c\u6240\u4ee5\u6839\u672c\u4e0d\u9700\u8981\u901a\u4fe1\u3002\u5b83\u4e0e step-31 \u4e2d\u7684\u5185\u5bb9\u57fa\u672c\u76f8\u540c\uff0c\u4f46\u5982\u679c\u9009\u62e9 $\\alpha=2$ \uff0c\u5219\u4f1a\u6709\u4e00\u4e2a\u6700\u65b0\u7684\u7c98\u5ea6\u8868\u8ff0\u3002\n\n  template <int dim> \n  double BoussinesqFlowProblem<dim>::compute_viscosity( \n    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<SymmetricTensor<2, dim>> &old_strain_rates, \n    const std::vector<SymmetricTensor<2, dim>> &old_old_strain_rates, \n    const double                                global_u_infty, \n    const double                                global_T_variation, \n    const double                                average_temperature, \n    const double                                global_entropy_variation, \n    const double                                cell_diameter) const \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 = \n          (old_velocity_values[q] + old_old_velocity_values[q]) / 2; \n\n        const SymmetricTensor<2, dim> strain_rate = \n          (old_strain_rates[q] + old_old_strain_rates[q]) / 2; \n\n        const double T = (old_temperature[q] + old_old_temperature[q]) / 2; \n        const double dT_dt = \n          (old_temperature[q] - old_old_temperature[q]) / old_time_step; \n        const double u_grad_T = \n          u * (old_temperature_grads[q] + old_old_temperature_grads[q]) / 2; \n\n        const double kappa_Delta_T = \n          EquationData::kappa * \n          (old_temperature_laplacians[q] + old_old_temperature_laplacians[q]) / \n          2; \n        const double gamma = \n          ((EquationData::radiogenic_heating * EquationData::density(T) + \n            2 * EquationData::eta * strain_rate * strain_rate) / \n           (EquationData::density(T) * EquationData::specific_heat)); \n\n        double residual = std::abs(dT_dt + u_grad_T - kappa_Delta_T - gamma); \n        if (parameters.stabilization_alpha == 2) \n          residual *= std::abs(T - average_temperature); \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 max_viscosity = \n      (parameters.stabilization_beta * max_velocity * cell_diameter); \n    if (timestep_number == 0) \n      return max_viscosity; \n    else \n      { \n        Assert(old_time_step > 0, ExcInternalError()); \n\n        double entropy_viscosity; \n        if (parameters.stabilization_alpha == 2) \n          entropy_viscosity = \n            (parameters.stabilization_c_R * cell_diameter * cell_diameter * \n             max_residual / global_entropy_variation); \n        else \n          entropy_viscosity = \n            (parameters.stabilization_c_R * cell_diameter * \n             global_Omega_diameter * max_velocity * max_residual / \n             (global_u_infty * global_T_variation)); \n\n        return std::min(max_viscosity, entropy_viscosity); \n      } \n  } \n\n//  @sect4{The BoussinesqFlowProblem setup functions}  \n\n// \u4ee5\u4e0b\u4e09\u4e2a\u51fd\u6570\u8bbe\u7f6e\u4e86\u65af\u6258\u514b\u65af\u77e9\u9635\u3001\u7528\u4e8e\u65af\u6258\u514b\u65af\u9884\u8c03\u8282\u5668\u7684\u77e9\u9635\u548c\u6e29\u5ea6\u77e9\u9635\u3002\u8fd9\u4e9b\u4ee3\u7801\u4e0e step-31 \u4e2d\u7684\u4ee3\u7801\u57fa\u672c\u76f8\u540c\uff0c\u4f46\u4e3a\u4e86\u7b80\u5355\u8d77\u89c1\uff0c\u5c06\u5176\u5206\u6210\u4e86\u4e09\u4e2a\u81ea\u5df1\u7684\u51fd\u6570\u3002\n\n// \u8fd9\u91cc\u7684\u4ee3\u7801\u4e0e step-31 \u4e2d\u7684\u4ee3\u7801\u5728\u529f\u80fd\u4e0a\u7684\u4e3b\u8981\u533a\u522b\u662f\uff0c\u6211\u4eec\u8981\u5efa\u7acb\u7684\u77e9\u9635\u662f\u5206\u5e03\u5728\u591a\u4e2a\u5904\u7406\u5668\u4e0a\u7684\u3002\u7531\u4e8e\u6211\u4eec\u4ecd\u7136\u5e0c\u671b\u51fa\u4e8e\u6548\u7387\u7684\u539f\u56e0\u5148\u5efa\u7acb\u8d77\u7a00\u758f\u6027\u6a21\u5f0f\uff0c\u6211\u4eec\u53ef\u4ee5\u7ee7\u7eed\u5c06<i>entire</i>\u7684\u7a00\u758f\u6027\u6a21\u5f0f\u4f5c\u4e3aBlockDynamicSparsityPattern\u6765\u5efa\u7acb\uff0c\u6b63\u5982\u6211\u4eec\u5728 step-31 \u4e2d\u6240\u505a\u7684\u90a3\u6837\u3002\u7136\u800c\uff0c\u8fd9\u5c06\u662f\u4f4e\u6548\u7684\uff1a\u6bcf\u4e2a\u5904\u7406\u5668\u5c06\u5efa\u7acb\u76f8\u540c\u7684\u7a00\u758f\u6027\u6a21\u5f0f\uff0c\u4f46\u53ea\u7528\u5b83\u521d\u59cb\u5316\u77e9\u9635\u7684\u4e00\u5c0f\u90e8\u5206\u3002\u8fd9\u4e5f\u8fdd\u53cd\u4e86\u4e00\u4e2a\u539f\u5219\uff0c\u5373\u6bcf\u4e2a\u5904\u7406\u5668\u5e94\u8be5\u53ea\u5bf9\u5b83\u6240\u62e5\u6709\u7684\u5355\u5143\u683c\uff08\u5982\u679c\u6709\u5fc5\u8981\u7684\u8bdd\uff0c\u8fd8\u6709\u5b83\u5468\u56f4\u7684\u5e7d\u7075\u5355\u5143\u683c\u5c42\uff09\u5de5\u4f5c\u3002\n\n// \u76f8\u53cd\uff0c\u6211\u4eec\u4f7f\u7528\u4e00\u4e2a\u7c7b\u578b\u4e3a TrilinosWrappers::BlockSparsityPattern, \u7684\u5bf9\u8c61\uff0c\u5b83\uff08\u663e\u7136\uff09\u662f\u5bf9Trilinos\u63d0\u4f9b\u7684\u7a00\u758f\u6a21\u5f0f\u5bf9\u8c61\u7684\u4e00\u4e2a\u5c01\u88c5\u3002\u8fd9\u6837\u505a\u7684\u597d\u5904\u662fTrilinos\u7a00\u758f\u6a21\u5f0f\u7c7b\u53ef\u4ee5\u5728\u591a\u4e2a\u5904\u7406\u5668\u4e4b\u95f4\u8fdb\u884c\u901a\u4fe1\uff1a\u5982\u679c\u8fd9\u4e2a\u5904\u7406\u5668\u586b\u5165\u5b83\u6240\u62e5\u6709\u7684\u5355\u5143\u683c\u4ea7\u751f\u7684\u6240\u6709\u975e\u96f6\u6761\u76ee\uff0c\u5e76\u4e14\u5176\u4ed6\u6bcf\u4e2a\u5904\u7406\u5668\u4e5f\u8fd9\u6837\u505a\uff0c\u90a3\u4e48\u5728\u7531 <code>compress()</code> \u8c03\u7528\u53d1\u8d77\u7684MPI\u901a\u4fe1\u7ed3\u675f\u540e\uff0c\u6211\u4eec\u5c06\u6709\u5168\u5c40\u7ec4\u88c5\u7684\u7a00\u758f\u6a21\u5f0f\u53ef\u7528\uff0c\u5168\u5c40\u77e9\u9635\u53ef\u4ee5\u88ab\u521d\u59cb\u5316\u3002\n\n// \u5728\u5e76\u884c\u521d\u59cb\u5316Trilinos\u7a00\u758f\u5ea6\u6a21\u5f0f\u65f6\uff0c\u6709\u4e00\u4e2a\u91cd\u8981\u7684\u65b9\u9762\u3002\u9664\u4e86\u901a\u8fc7 @p stokes_partitioning \u7d22\u5f15\u96c6\u6307\u5b9a\u77e9\u9635\u7684\u672c\u5730\u62e5\u6709\u7684\u884c\u548c\u5217\u4e4b\u5916\uff0c\u6211\u4eec\u8fd8\u63d0\u4f9b\u4e86\u5728\u67d0\u4e2a\u5904\u7406\u5668\u4e0a\u88c5\u914d\u65f6\u53ef\u80fd\u8981\u5199\u8fdb\u7684\u6240\u6709\u884c\u7684\u4fe1\u606f\u3002\u672c\u5730\u76f8\u5173\u884c\u7684\u96c6\u5408\u5305\u542b\u4e86\u6240\u6709\u8fd9\u6837\u7684\u884c\uff08\u53ef\u80fd\u8fd8\u6709\u4e00\u4e9b\u4e0d\u5fc5\u8981\u7684\u884c\uff0c\u4f46\u5728\u5b9e\u9645\u83b7\u5f97\u6240\u6709\u5355\u5143\u683c\u7684\u7d22\u5f15\u548c\u89e3\u51b3\u7ea6\u675f\u4e4b\u524d\uff0c\u5f88\u96be\u627e\u5230\u786e\u5207\u7684\u884c\u7d22\u5f15\uff09\u3002\u8fd9\u79cd\u989d\u5916\u7684\u4fe1\u606f\u53ef\u4ee5\u51c6\u786e\u5730\u786e\u5b9a\u5728\u88c5\u914d\u8fc7\u7a0b\u4e2d\u53d1\u73b0\u7684\u975e\u5904\u7406\u5668\u6570\u636e\u7684\u7ed3\u6784\u3002\u867d\u7136Trilinos\u77e9\u9635\u4e5f\u80fd\u5728\u98de\u884c\u4e2d\u6536\u96c6\u8fd9\u4e9b\u4fe1\u606f\uff08\u5f53\u4ece\u5176\u4ed6\u4e00\u4e9breinit\u65b9\u6cd5\u521d\u59cb\u5316\u5b83\u4eec\u65f6\uff09\uff0c\u4f46\u6548\u7387\u8f83\u4f4e\uff0c\u5728\u7528\u591a\u7ebf\u7a0b\u7ec4\u88c5\u77e9\u9635\u65f6\uff0c\u4f1a\u5bfc\u81f4\u95ee\u9898\u3002\u5728\u8fd9\u4e2a\u7a0b\u5e8f\u4e2d\uff0c\u6211\u4eec\u60b2\u89c2\u5730\u5047\u8bbe\u6bcf\u6b21\u53ea\u6709\u4e00\u4e2a\u5904\u7406\u5668\u53ef\u4ee5\u5728\u7ec4\u88c5\u65f6\u5199\u5165\u77e9\u9635\uff08\u800c\u8ba1\u7b97\u662f\u5e76\u884c\u7684\uff09\uff0c\u8fd9\u5bf9\u7279\u91cc\u8bfa\u65af\u77e9\u9635\u662f\u6ca1\u6709\u95ee\u9898\u7684\u3002\u5728\u5b9e\u8df5\u4e2d\uff0c\u53ef\u4ee5\u901a\u8fc7\u5728\u4e0d\u5171\u4eab\u9876\u70b9\u7684\u5355\u5143\u4e2d\u63d0\u793aWorkStream\u6765\u505a\u5f97\u66f4\u597d\uff0c\u5141\u8bb8\u8fd9\u4e9b\u5355\u5143\u4e4b\u95f4\u7684\u5e76\u884c\u6027\uff08\u53c2\u89c1\u56fe\u5f62\u7740\u8272\u7b97\u6cd5\u548c\u5e26\u6709\u5f69\u8272\u8fed\u4ee3\u5668\u7684WorkStream\u53c2\u6570\uff09\u3002\u7136\u800c\uff0c\u8fd9\u53ea\u5728\u53ea\u6709\u4e00\u4e2aMPI\u5904\u7406\u5668\u7684\u60c5\u51b5\u4e0b\u6709\u6548\uff0c\u56e0\u4e3aTrilinos\u7684\u5185\u90e8\u6570\u636e\u7ed3\u6784\u5728\u98de\u884c\u4e2d\u79ef\u7d2f\u975e\u5904\u7406\u5668\u7684\u6570\u636e\uff0c\u4e0d\u662f\u7ebf\u7a0b\u5b89\u5168\u3002\u6709\u4e86\u8fd9\u91cc\u4ecb\u7ecd\u7684\u521d\u59cb\u5316\uff0c\u5c31\u4e0d\u5b58\u5728\u8fd9\u6837\u7684\u95ee\u9898\uff0c\u4eba\u4eec\u53ef\u4ee5\u5b89\u5168\u5730\u4e3a\u8fd9\u4e2a\u7b97\u6cd5\u5f15\u5165\u56fe\u5f62\u7740\u8272\u3002\n\n// \u6211\u4eec\u552f\u4e00\u9700\u8981\u505a\u7684\u6539\u53d8\u662f\u544a\u8bc9 DoFTools::make_sparsity_pattern() \u51fd\u6570\uff0c\u5b83\u53ea\u5e94\u8be5\u5728\u4e00\u4e2a\u5355\u5143\u683c\u5b50\u96c6\u4e0a\u5de5\u4f5c\uff0c\u5373\u90a3\u4e9b <code>subdomain_id</code> \u7b49\u4e8e\u5f53\u524d\u5904\u7406\u5668\u6570\u91cf\u7684\u5355\u5143\u683c\uff0c\u800c\u5ffd\u7565\u6240\u6709\u5176\u4ed6\u5355\u5143\u683c\u3002\n\n// \u8fd9\u4e2a\u7b56\u7565\u88ab\u590d\u5236\u5230\u4ee5\u4e0b\u4e09\u4e2a\u51fd\u6570\u4e2d\u3002\n\n// \u6ce8\u610f\uff0cTrilinos \u77e9\u9635\u5b58\u50a8\u7684\u4fe1\u606f\u5305\u542b\u5728\u7a00\u758f\u6a21\u5f0f\u4e2d\uff0c\u6240\u4ee5\u4e00\u65e6\u77e9\u9635\u88ab\u8d4b\u4e88\u7a00\u758f\u7ed3\u6784\uff0c\u6211\u4eec\u5c31\u53ef\u4ee5\u5b89\u5168\u5730\u91ca\u653e  <code>sp</code>  \u53d8\u91cf\u3002\n\n  template <int dim> \n  void BoussinesqFlowProblem<dim>::setup_stokes_matrix( \n    const std::vector<IndexSet> &stokes_partitioning, \n    const std::vector<IndexSet> &stokes_relevant_partitioning) \n  { \n    stokes_matrix.clear(); \n\n    TrilinosWrappers::BlockSparsityPattern sp(stokes_partitioning, \n                                              stokes_partitioning, \n                                              stokes_relevant_partitioning, \n                                              MPI_COMM_WORLD); \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 == 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, \n                                    coupling, \n                                    sp, \n                                    stokes_constraints, \n                                    false, \n                                    Utilities::MPI::this_mpi_process( \n                                      MPI_COMM_WORLD)); \n    sp.compress(); \n\n    stokes_matrix.reinit(sp); \n  } \n\n  template <int dim> \n  void BoussinesqFlowProblem<dim>::setup_stokes_preconditioner( \n    const std::vector<IndexSet> &stokes_partitioning, \n    const std::vector<IndexSet> &stokes_relevant_partitioning) \n  { \n    Amg_preconditioner.reset(); \n    Mp_preconditioner.reset(); \n\n    stokes_preconditioner_matrix.clear(); \n\n    TrilinosWrappers::BlockSparsityPattern sp(stokes_partitioning, \n                                              stokes_partitioning, \n                                              stokes_relevant_partitioning, \n                                              MPI_COMM_WORLD); \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, \n                                    coupling, \n                                    sp, \n                                    stokes_constraints, \n                                    false, \n                                    Utilities::MPI::this_mpi_process( \n                                      MPI_COMM_WORLD)); \n    sp.compress(); \n\n    stokes_preconditioner_matrix.reinit(sp); \n  } \n\n  template <int dim> \n  void BoussinesqFlowProblem<dim>::setup_temperature_matrices( \n    const IndexSet &temperature_partitioner, \n    const IndexSet &temperature_relevant_partitioner) \n  { \n    T_preconditioner.reset(); \n    temperature_mass_matrix.clear(); \n    temperature_stiffness_matrix.clear(); \n    temperature_matrix.clear(); \n\n    TrilinosWrappers::SparsityPattern sp(temperature_partitioner, \n                                         temperature_partitioner, \n                                         temperature_relevant_partitioner, \n                                         MPI_COMM_WORLD); \n    DoFTools::make_sparsity_pattern(temperature_dof_handler, \n                                    sp, \n                                    temperature_constraints, \n                                    false, \n                                    Utilities::MPI::this_mpi_process( \n                                      MPI_COMM_WORLD)); \n    sp.compress(); \n\n    temperature_matrix.reinit(sp); \n    temperature_mass_matrix.reinit(sp); \n    temperature_stiffness_matrix.reinit(sp); \n  } \n\n// \u8bbe\u7f6e\u51fd\u6570\u7684\u5176\u4f59\u90e8\u5206\uff08\u5728\u62c6\u5206\u51fa\u4e0a\u9762\u7684\u4e09\u4e2a\u51fd\u6570\u540e\uff09\u4e3b\u8981\u662f\u5904\u7406\u6211\u4eec\u9700\u8981\u505a\u7684\u8de8\u5904\u7406\u5668\u5e76\u884c\u5316\u7684\u4e8b\u60c5\u3002\u56e0\u4e3a\u8bbe\u7f6e\u6240\u6709\u8fd9\u4e9b\u90fd\u662f\u7a0b\u5e8f\u7684\u4e00\u4e2a\u91cd\u8981\u7684\u8ba1\u7b97\u65f6\u95f4\u652f\u51fa\uff0c\u6240\u4ee5\u6211\u4eec\u628a\u5728\u8fd9\u91cc\u505a\u7684\u6240\u6709\u4e8b\u60c5\u90fd\u653e\u5230\u4e00\u4e2a\u5b9a\u65f6\u5668\u7ec4\u4e2d\uff0c\u8fd9\u6837\u6211\u4eec\u5c31\u53ef\u4ee5\u5728\u7a0b\u5e8f\u7ed3\u675f\u65f6\u5f97\u5230\u5173\u4e8e\u8fd9\u90e8\u5206\u65f6\u95f4\u7684\u603b\u7ed3\u4fe1\u606f\u3002\n\n// \u50cf\u5f80\u5e38\u4e00\u6837\uff0c\u6211\u4eec\u5728\u9876\u90e8\u5217\u4e3e\u81ea\u7531\u5ea6\uff0c\u5e76\u6309\u7167\u7ec4\u4ef6/\u5757\u8fdb\u884c\u6392\u5e8f\uff0c\u7136\u540e\u4ece\u96f6\u53f7\u5904\u7406\u5668\u5f00\u59cb\u5c06\u5b83\u4eec\u7684\u6570\u5b57\u5199\u5230\u5c4f\u5e55\u4e0a\u3002\u5f53 DoFHandler::distributed_dofs() \u51fd\u6570\u5e94\u7528\u4e8e parallel::distributed::Triangulation \u5bf9\u8c61\u65f6\uff0c\u5bf9\u81ea\u7531\u5ea6\u7684\u6392\u5e8f\u662f\u8fd9\u6837\u7684\uff1a\u6240\u6709\u4e0e\u5b50\u57df0\u76f8\u5173\u7684\u81ea\u7531\u5ea6\u6392\u5728\u6240\u6709\u4e0e\u5b50\u57df1\u76f8\u5173\u7684\u81ea\u7531\u5ea6\u4e4b\u524d\uff0c\u7b49\u7b49\u3002\u5bf9\u4e8e\u65af\u6258\u514b\u65af\u90e8\u5206\uff0c\u8fd9\u610f\u5473\u7740\u901f\u5ea6\u548c\u538b\u529b\u4f1a\u6df7\u5728\u4e00\u8d77\uff0c\u4f46\u8fd9\u53ef\u4ee5\u901a\u8fc7\u518d\u6b21\u6309\u5757\u6392\u5e8f\u6765\u89e3\u51b3\uff1b\u503c\u5f97\u6ce8\u610f\u7684\u662f\uff0c\u540e\u4e00\u79cd\u64cd\u4f5c\u53ea\u4fdd\u7559\u4e86\u6240\u6709\u901f\u5ea6\u548c\u538b\u529b\u7684\u76f8\u5bf9\u987a\u5e8f\uff0c\u5373\u5728\u901f\u5ea6\u5757\u5185\uff0c\u6211\u4eec\u4ecd\u7136\u4f1a\u5c06\u6240\u6709\u4e0e\u5b50\u57df\u96f6\u76f8\u5173\u7684\u901f\u5ea6\u653e\u5728\u4e0e\u5b50\u57df\u4e00\u76f8\u5173\u7684\u901f\u5ea6\u4e4b\u524d\uff0c\u7b49\u7b49\u3002\u8fd9\u4e00\u70b9\u5f88\u91cd\u8981\uff0c\u56e0\u4e3a\u6211\u4eec\u628a\u8fd9\u4e2a\u77e9\u9635\u7684\u6bcf\u4e00\u4e2a\u5757\u90fd\u5206\u5e03\u5728\u6240\u6709\u7684\u5904\u7406\u5668\u4e0a\uff0c\u5e76\u4e14\u5e0c\u671b\u8fd9\u6837\u505a\u7684\u65b9\u5f0f\u662f\uff0c\u6bcf\u4e2a\u5904\u7406\u5668\u5b58\u50a8\u7684\u77e9\u9635\u90e8\u5206\u4e0e\u5b83\u5c06\u5b9e\u9645\u5de5\u4f5c\u7684\u5355\u5143\u4e0a\u7684\u81ea\u7531\u5ea6\u5927\u81f4\u76f8\u7b49\u3002\n\n// \u5728\u6253\u5370\u81ea\u7531\u5ea6\u7684\u6570\u5b57\u65f6\uff0c\u6ce8\u610f\u5982\u679c\u6211\u4eec\u4f7f\u7528\u8bb8\u591a\u5904\u7406\u5668\uff0c\u8fd9\u4e9b\u6570\u5b57\u5c06\u4f1a\u5f88\u5927\u3002\u56e0\u6b64\uff0c\u6211\u4eec\u8ba9\u6d41\u5728\u6bcf\u4e09\u4e2a\u6570\u5b57\u4e4b\u95f4\u653e\u4e00\u4e2a\u9017\u53f7\u5206\u9694\u7b26\u3002\u6d41\u7684\u72b6\u6001\uff0c\u4f7f\u7528locale\uff0c\u4ece\u8fd9\u4e2a\u64cd\u4f5c\u4e4b\u524d\u4fdd\u5b58\u5230\u4e4b\u540e\u3002\u867d\u7136\u6709\u70b9\u4e0d\u900f\u660e\uff0c\u4f46\u8fd9\u6bb5\u4ee3\u7801\u662f\u6709\u6548\u7684\uff0c\u56e0\u4e3a\u9ed8\u8ba4\u7684locale\uff08\u6211\u4eec\u4f7f\u7528\u6784\u9020\u51fd\u6570\u8c03\u7528 <code>std::locale(\"\")</code> \u5f97\u5230\u7684\uff09\u610f\u5473\u7740\u6253\u5370\u6570\u5b57\u65f6\uff0c\u6bcf\u4e09\u4f4d\u6570\u5b57\u90fd\u6709\u4e00\u4e2a\u9017\u53f7\u5206\u9694\u7b26\uff08\u5373\u5343\u3001\u767e\u4e07\u3001\u4ebf\uff09\u3002\n\n// \u5728\u8fd9\u4e2a\u51fd\u6570\u4ee5\u53ca\u4e0b\u9762\u7684\u8bb8\u591a\u51fd\u6570\u4e2d\uff0c\u6211\u4eec\u6d4b\u91cf\u4e86\u6211\u4eec\u5728\u8fd9\u91cc\u82b1\u8d39\u7684\u65f6\u95f4\uff0c\u5e76\u5c06\u5176\u6536\u96c6\u5728\u4e00\u4e2a\u53eb\u505a \"\u8bbe\u7f6edof\u7cfb\u7edf \"\u7684\u90e8\u5206\uff0c\u8de8\u51fd\u6570\u8c03\u7528\u3002\u8fd9\u662f\u7528\u4e00\u4e2a TimerOutput::Scope \u5bf9\u8c61\u5b8c\u6210\u7684\uff0c\u8be5\u5bf9\u8c61\u5728\u6784\u5efa\u672c\u5730\u53d8\u91cf\u65f6\uff0c\u5728\u4e0a\u8ff0\u540d\u79f0\u4e3a`computing_timer`\u7684\u90e8\u5206\u542f\u52a8\u4e00\u4e2a\u5b9a\u65f6\u5668\uff1b\u5f53`timing_section`\u53d8\u91cf\u7684\u6790\u6784\u5668\u88ab\u8c03\u7528\u65f6\uff0c\u8be5\u5b9a\u65f6\u5668\u518d\u6b21\u505c\u6b62\u3002 \u5f53\u7136\uff0c\u8fd9\u8981\u4e48\u53d1\u751f\u5728\u51fd\u6570\u7684\u672b\u5c3e\uff0c\u8981\u4e48\u6211\u4eec\u901a\u8fc7`return`\u8bed\u53e5\u79bb\u5f00\u51fd\u6570\uff0c\u6216\u8005\u5728\u67d0\u5904\u629b\u51fa\u5f02\u5e38\u65f6--\u6362\u53e5\u8bdd\u8bf4\uff0c\u53ea\u8981\u6211\u4eec\u4ee5\u4efb\u4f55\u65b9\u5f0f\u79bb\u5f00\u8fd9\u4e2a\u51fd\u6570\u3002\u56e0\u6b64\uff0c\u4f7f\u7528\u8fd9\u79cd \"\u8303\u56f4 \"\u5bf9\u8c61\u53ef\u4ee5\u786e\u4fdd\u6211\u4eec\u4e0d\u5fc5\u624b\u52a8\u6dfb\u52a0\u4ee3\u7801\uff0c\u544a\u8bc9\u5b9a\u65f6\u5668\u5728\u6bcf\u4e2a\u53ef\u80fd\u79bb\u5f00\u8fd9\u4e2a\u51fd\u6570\u7684\u5730\u65b9\u505c\u6b62\u3002\n\n  template <int dim> \n  void BoussinesqFlowProblem<dim>::setup_dofs() \n  { \n    TimerOutput::Scope timing_section(computing_timer, \"Setup dof systems\"); \n\n    stokes_dof_handler.distribute_dofs(stokes_fe); \n\n    std::vector<unsigned int> stokes_sub_blocks(dim + 1, 0); \n    stokes_sub_blocks[dim] = 1; \n    DoFRenumbering::component_wise(stokes_dof_handler, stokes_sub_blocks); \n\n    temperature_dof_handler.distribute_dofs(temperature_fe); \n\n    const std::vector<types::global_dof_index> stokes_dofs_per_block = \n      DoFTools::count_dofs_per_fe_block(stokes_dof_handler, 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::locale s = pcout.get_stream().getloc(); \n    pcout.get_stream().imbue(std::locale(\"\")); \n    pcout << \"Number of active cells: \" << triangulation.n_global_active_cells() \n          << \" (on \" << triangulation.n_levels() << \" levels)\" << std::endl \n          << \"Number of degrees of freedom: \" << n_u + n_p + n_T << \" (\" << n_u \n          << '+' << n_p << '+' << n_T << ')' << std::endl \n          << std::endl; \n    pcout.get_stream().imbue(s); \n\n// \u5728\u8fd9\u4e4b\u540e\uff0c\u6211\u4eec\u5fc5\u987b\u8bbe\u7f6e\u5404\u79cd\u5206\u533a\u5668\uff08\u7c7b\u578b\u4e3a <code>IndexSet</code>  \uff0c\u89c1\u4ecb\u7ecd\uff09\uff0c\u63cf\u8ff0\u6bcf\u4e2a\u77e9\u9635\u6216\u5411\u91cf\u7684\u54ea\u4e9b\u90e8\u5206\u5c06\u88ab\u5b58\u50a8\u5728\u54ea\u91cc\uff0c\u7136\u540e\u8c03\u7528\u5b9e\u9645\u8bbe\u7f6e\u77e9\u9635\u7684\u51fd\u6570\uff0c\u5728\u6700\u540e\u8fd8\u8981\u8c03\u6574\u6211\u4eec\u5728\u8fd9\u4e2a\u7a0b\u5e8f\u4e2d\u4fdd\u7559\u7684\u5404\u79cd\u5411\u91cf\u7684\u5927\u5c0f\u3002\n\n    std::vector<IndexSet> stokes_partitioning, stokes_relevant_partitioning; \n    IndexSet              temperature_partitioning(n_T), \n      temperature_relevant_partitioning(n_T); \n    IndexSet stokes_relevant_set; \n    { \n      IndexSet stokes_index_set = stokes_dof_handler.locally_owned_dofs(); \n      stokes_partitioning.push_back(stokes_index_set.get_view(0, n_u)); \n      stokes_partitioning.push_back(stokes_index_set.get_view(n_u, n_u + n_p)); \n\n      DoFTools::extract_locally_relevant_dofs(stokes_dof_handler, \n                                              stokes_relevant_set); \n      stokes_relevant_partitioning.push_back( \n        stokes_relevant_set.get_view(0, n_u)); \n      stokes_relevant_partitioning.push_back( \n        stokes_relevant_set.get_view(n_u, n_u + n_p)); \n\n      temperature_partitioning = temperature_dof_handler.locally_owned_dofs(); \n      DoFTools::extract_locally_relevant_dofs( \n        temperature_dof_handler, temperature_relevant_partitioning); \n    } \n\n// \u5728\u8fd9\u4e4b\u540e\uff0c\u6211\u4eec\u53ef\u4ee5\u8ba1\u7b97\u6c42\u89e3\u5411\u91cf\u7684\u7ea6\u675f\uff0c\u5305\u62ec\u60ac\u6302\u8282\u70b9\u7ea6\u675f\u548c\u65af\u6258\u514b\u65af\u548c\u6e29\u5ea6\u573a\u7684\u540c\u8d28\u548c\u975e\u540c\u8d28\u8fb9\u754c\u503c\u3002\u8bf7\u6ce8\u610f\uff0c\u548c\u5176\u4ed6\u4e00\u5207\u4e00\u6837\uff0c\u7ea6\u675f\u5bf9\u8c61\u4e0d\u80fd\u5728\u6bcf\u4e2a\u5904\u7406\u5668\u4e0a\u90fd\u6301\u6709<i>all</i>\u7ea6\u675f\u3002\u76f8\u53cd\uff0c\u9274\u4e8e\u6bcf\u4e2a\u5904\u7406\u5668\u53ea\u5728\u5176\u62e5\u6709\u7684\u5355\u5143\u4e0a\u7ec4\u88c5\u7ebf\u6027\u7cfb\u7edf\uff0c\u56e0\u6b64\u6bcf\u4e2a\u5904\u7406\u5668\u53ea\u9700\u8981\u5b58\u50a8\u90a3\u4e9b\u5bf9\u6b63\u786e\u6027\u5b9e\u9645\u5fc5\u8981\u7684\u7ea6\u675f\u3002\u6b63\u5982\u5728 @ref distributed_paper \"\u672c\u6587 \"\u4e2d\u6240\u8ba8\u8bba\u7684\uff0c\u6211\u4eec\u9700\u8981\u4e86\u89e3\u7684\u7ea6\u675f\u96c6\u6b63\u662f\u6240\u6709\u672c\u5730\u76f8\u5173\u81ea\u7531\u5ea6\u7684\u7ea6\u675f\u96c6\uff0c\u6240\u4ee5\u8fd9\u5c31\u662f\u6211\u4eec\u7528\u6765\u521d\u59cb\u5316\u7ea6\u675f\u5bf9\u8c61\u7684\u3002\n\n    { \n      stokes_constraints.clear(); \n      stokes_constraints.reinit(stokes_relevant_set); \n\n      DoFTools::make_hanging_node_constraints(stokes_dof_handler, \n                                              stokes_constraints); \n\n      FEValuesExtractors::Vector velocity_components(0); \n      VectorTools::interpolate_boundary_values( \n        stokes_dof_handler, \n        0, \n        Functions::ZeroFunction<dim>(dim + 1), \n        stokes_constraints, \n        stokes_fe.component_mask(velocity_components)); \n\n      std::set<types::boundary_id> no_normal_flux_boundaries; \n      no_normal_flux_boundaries.insert(1); \n      VectorTools::compute_no_normal_flux_constraints(stokes_dof_handler, \n                                                      0, \n                                                      no_normal_flux_boundaries, \n                                                      stokes_constraints, \n                                                      mapping); \n      stokes_constraints.close(); \n    } \n    { \n      temperature_constraints.clear(); \n      temperature_constraints.reinit(temperature_relevant_partitioning); \n\n      DoFTools::make_hanging_node_constraints(temperature_dof_handler, \n                                              temperature_constraints); \n      VectorTools::interpolate_boundary_values( \n        temperature_dof_handler, \n        0, \n        EquationData::TemperatureInitialValues<dim>(), \n        temperature_constraints); \n      VectorTools::interpolate_boundary_values( \n        temperature_dof_handler, \n        1, \n        EquationData::TemperatureInitialValues<dim>(), \n        temperature_constraints); \n      temperature_constraints.close(); \n    } \n\n// \u505a\u5b8c\u8fd9\u4e9b\uff0c\u6211\u4eec\u5c31\u53ef\u4ee5\u5c06\u5404\u79cd\u77e9\u9635\u548c\u5411\u91cf\u5bf9\u8c61\u521d\u59cb\u5316\u5230\u5408\u9002\u7684\u5927\u5c0f\u3002\u5728\u6700\u540e\uff0c\u6211\u4eec\u8fd8\u8bb0\u5f55\u4e86\u6240\u6709\u7684\u77e9\u9635\u548c\u524d\u7f6e\u6761\u4ef6\u5668\u5fc5\u987b\u5728\u4e0b\u4e00\u4e2a\u65f6\u95f4\u6b65\u957f\u5f00\u59cb\u65f6\u91cd\u65b0\u8ba1\u7b97\u3002\u6ce8\u610f\u6211\u4eec\u662f\u5982\u4f55\u521d\u59cb\u5316\u65af\u6258\u514b\u65af\u548c\u6e29\u5ea6\u53f3\u4fa7\u7684\u5411\u91cf\u7684\u3002\u8fd9\u4e9b\u662f\u53ef\u5199\u7684\u5411\u91cf\uff08\u6700\u540e\u4e00\u4e2a\u5e03\u5c14\u53c2\u6570\u8bbe\u7f6e\u4e3a @p true) \uff09\uff0c\u5177\u6709\u6b63\u786e\u7684\u4e00\u5bf9\u4e00\u7684\u672c\u5730\u62e5\u6709\u5143\u7d20\u7684\u5206\u533a\uff0c\u4f46\u4ecd\u88ab\u8d4b\u4e88\u76f8\u5173\u7684\u5206\u533a\uff0c\u4ee5\u5f04\u6e05\u8981\u7acb\u5373\u8bbe\u7f6e\u7684\u5411\u91cf\u6761\u76ee\u3002\u81f3\u4e8e\u77e9\u9635\uff0c\u8fd9\u5141\u8bb8\u7528\u591a\u4e2a\u7ebf\u7a0b\u5c06\u672c\u5730\u8d21\u732e\u5199\u5165\u5411\u91cf\uff08\u603b\u662f\u5047\u8bbe\u540c\u4e00\u5411\u91cf\u6761\u76ee\u4e0d\u88ab\u591a\u4e2a\u7ebf\u7a0b\u540c\u65f6\u8bbf\u95ee\uff09\u3002\u5176\u4ed6\u5411\u91cf\u53ea\u5141\u8bb8\u5bf9\u5355\u4e2a\u5143\u7d20\u7684\u8bfb\u53d6\u8bbf\u95ee\uff0c\u5305\u62ec\u9b3c\u9b42\uff0c\u4f46\u4e0d\u9002\u5408\u6c42\u89e3\u5668\u3002\n\n    setup_stokes_matrix(stokes_partitioning, stokes_relevant_partitioning); \n    setup_stokes_preconditioner(stokes_partitioning, \n                                stokes_relevant_partitioning); \n    setup_temperature_matrices(temperature_partitioning, \n                               temperature_relevant_partitioning); \n\n    stokes_rhs.reinit(stokes_partitioning, \n                      stokes_relevant_partitioning, \n                      MPI_COMM_WORLD, \n                      true); \n    stokes_solution.reinit(stokes_relevant_partitioning, MPI_COMM_WORLD); \n    old_stokes_solution.reinit(stokes_solution); \n\n    temperature_rhs.reinit(temperature_partitioning, \n                           temperature_relevant_partitioning, \n                           MPI_COMM_WORLD, \n                           true); \n    temperature_solution.reinit(temperature_relevant_partitioning, \n                                MPI_COMM_WORLD); \n    old_temperature_solution.reinit(temperature_solution); \n    old_old_temperature_solution.reinit(temperature_solution); \n\n    rebuild_stokes_matrix              = true; \n    rebuild_stokes_preconditioner      = true; \n    rebuild_temperature_matrices       = true; \n    rebuild_temperature_preconditioner = true; \n  } \n\n//  @sect4{The BoussinesqFlowProblem assembly functions}  \n\n// \u6309\u7167\u4ecb\u7ecd\u548c @ref threads \u6a21\u5757\u4e2d\u7684\u8ba8\u8bba\uff0c\u6211\u4eec\u5c06\u88c5\u914d\u529f\u80fd\u5206\u6210\u4e0d\u540c\u7684\u90e8\u5206\u3002\n\n//  <ul>  \n//  <li>  \u77e9\u9635\u548c\u53f3\u624b\u8fb9\u7684\u5c40\u90e8\u8ba1\u7b97\uff0c\u7ed9\u5b9a\u67d0\u4e2a\u5355\u5143\u4f5c\u4e3a\u8f93\u5165\uff08\u8fd9\u4e9b\u51fd\u6570\u88ab\u547d\u540d\u4e3a\u4e0b\u9762\u7684 <code>local_assemble_*</code> \uff09\u3002\u6362\u53e5\u8bdd\u8bf4\uff0c\u5f97\u51fa\u7684\u51fd\u6570\u57fa\u672c\u4e0a\u662f step-31 \u4e2d\u6240\u6709\u5355\u5143\u683c\u7684\u5faa\u73af\u4f53\u3002\u7136\u800c\uff0c\u8bf7\u6ce8\u610f\uff0c\u8fd9\u4e9b\u51fd\u6570\u5c06\u672c\u5730\u8ba1\u7b97\u7684\u7ed3\u679c\u5b58\u50a8\u5728CopyData\u547d\u540d\u7a7a\u95f4\u7684\u7c7b\u7684\u53d8\u91cf\u4e2d\u3002\n\n//  <li>  \u7136\u540e\u8fd9\u4e9b\u5bf9\u8c61\u88ab\u4ea4\u7ed9\u7b2c\u4e8c\u6b65\uff0c\u5c06\u672c\u5730\u6570\u636e\u5199\u5165\u5168\u5c40\u6570\u636e\u7ed3\u6784\u4e2d\uff08\u8fd9\u4e9b\u51fd\u6570\u88ab\u547d\u540d\u4e3a\u4e0b\u9762\u7684 <code>copy_local_to_global_*</code> \uff09\u3002\u8fd9\u4e9b\u51fd\u6570\u662f\u76f8\u5f53\u7410\u788e\u7684\u3002\n\n//  <li>  \u7136\u540e\u8fd9\u4e24\u4e2a\u5b50\u51fd\u6570\u88ab\u7528\u4e8e\u5404\u81ea\u7684\u6c47\u7f16\u4f8b\u7a0b\uff08\u4e0b\u9762\u79f0\u4e3a <code>assemble_*</code> \uff09\uff0c\u5728\u90a3\u91cc\uff0c\u4e00\u4e2aWorkStream\u5bf9\u8c61\u88ab\u8bbe\u7f6e\u5e76\u5728\u5c5e\u4e8e\u5904\u7406\u5668\u5b50\u57df\u7684\u6240\u6709\u5355\u5143\u4e2d\u8fd0\u884c\u3002   </ul>  \n// @sect5{Stokes preconditioner assembly}  \n\n// \u8ba9\u6211\u4eec\u4ece\u6784\u5efa\u65af\u6258\u514b\u65af\u9884\u5904\u7406\u7684\u51fd\u6570\u5f00\u59cb\u3002\u8003\u8651\u5230\u4e0a\u9762\u7684\u8ba8\u8bba\uff0c\u5176\u4e2d\u7684\u524d\u4e24\u4e2a\u662f\u975e\u5e38\u5fae\u4e0d\u8db3\u9053\u7684\u3002\u8bf7\u7279\u522b\u6ce8\u610f\uff0c\u4f7f\u7528scratch\u6570\u636e\u5bf9\u8c61\u7684\u4e3b\u8981\u610f\u4e49\u5728\u4e8e\uff0c\u6211\u4eec\u5e0c\u671b\u907f\u514d\u6bcf\u6b21\u8bbf\u95ee\u65b0\u5355\u5143\u65f6\u5728\u81ea\u7531\u7a7a\u95f4\u4e0a\u5206\u914d\u4efb\u4f55\u5bf9\u8c61\u3002\u56e0\u6b64\uff0c\u4e0b\u9762\u7684\u6c47\u7f16\u51fd\u6570\u53ea\u6709\u81ea\u52a8\u7684\u5c40\u90e8\u53d8\u91cf\uff0c\u5176\u4ed6\u7684\u90fd\u662f\u901a\u8fc7\u4ece\u5934\u5f00\u59cb\u7684\u6570\u636e\u5bf9\u8c61\u8bbf\u95ee\u7684\uff0c\u5728\u6211\u4eec\u5f00\u59cb\u5bf9\u6240\u6709\u5355\u5143\u8fdb\u884c\u5faa\u73af\u4e4b\u524d\uff0c\u53ea\u5206\u914d\u4e86\u4e00\u6b21\u3002\n\n  template <int dim> \n  void BoussinesqFlowProblem<dim>::local_assemble_stokes_preconditioner( \n    const typename DoFHandler<dim>::active_cell_iterator &cell, \n    Assembly::Scratch::StokesPreconditioner<dim> &        scratch, \n    Assembly::CopyData::StokesPreconditioner<dim> &       data) \n  { \n    const unsigned int dofs_per_cell = stokes_fe.n_dofs_per_cell(); \n    const unsigned int n_q_points = \n      scratch.stokes_fe_values.n_quadrature_points; \n\n    const FEValuesExtractors::Vector velocities(0); \n    const FEValuesExtractors::Scalar pressure(dim); \n\n    scratch.stokes_fe_values.reinit(cell); \n    cell->get_dof_indices(data.local_dof_indices); \n\n    data.local_matrix = 0; \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            scratch.grad_phi_u[k] = \n              scratch.stokes_fe_values[velocities].gradient(k, q); \n            scratch.phi_p[k] = scratch.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            data.local_matrix(i, j) += \n              (EquationData::eta * \n                 scalar_product(scratch.grad_phi_u[i], scratch.grad_phi_u[j]) + \n               (1. / EquationData::eta) * EquationData::pressure_scaling * \n                 EquationData::pressure_scaling * \n                 (scratch.phi_p[i] * scratch.phi_p[j])) * \n              scratch.stokes_fe_values.JxW(q); \n      } \n  } \n\n  template <int dim> \n  void BoussinesqFlowProblem<dim>::copy_local_to_global_stokes_preconditioner( \n    const Assembly::CopyData::StokesPreconditioner<dim> &data) \n  { \n    stokes_constraints.distribute_local_to_global(data.local_matrix, \n                                                  data.local_dof_indices, \n                                                  stokes_preconditioner_matrix); \n  } \n\n// \u73b0\u5728\u662f\u771f\u6b63\u628a\u4e8b\u60c5\u653e\u5728\u4e00\u8d77\u7684\u51fd\u6570\uff0c\u4f7f\u7528WorkStream\u51fd\u6570\u3002   WorkStream::run \u9700\u8981\u4e00\u4e2a\u5f00\u59cb\u548c\u7ed3\u675f\u8fed\u4ee3\u5668\u6765\u5217\u4e3e\u5b83\u5e94\u8be5\u5de5\u4f5c\u7684\u5355\u5143\u683c\u3002\u901a\u5e38\u60c5\u51b5\u4e0b\uff0c\u6211\u4eec\u4f1a\u4f7f\u7528 DoFHandler::begin_active() \u548c DoFHandler::end() \u6765\u5b9e\u73b0\u8fd9\u4e00\u70b9\uff0c\u4f46\u5728\u8fd9\u91cc\uff0c\u6211\u4eec\u5b9e\u9645\u4e0a\u53ea\u60f3\u83b7\u5f97\u4e8b\u5b9e\u4e0a\u7531\u5f53\u524d\u5904\u7406\u5668\u62e5\u6709\u7684\u5355\u5143\u683c\u5b50\u96c6\u3002\u8fd9\u5c31\u662fFilteredIterator\u7c7b\u53d1\u6325\u4f5c\u7528\u7684\u5730\u65b9\uff1a\u4f60\u7ed9\u5b83\u4e00\u4e2a\u5355\u5143\u683c\u8303\u56f4\uff0c\u5b83\u63d0\u4f9b\u4e00\u4e2a\u8fed\u4ee3\u5668\uff0c\u53ea\u8fed\u4ee3\u6ee1\u8db3\u67d0\u4e2a\u8c13\u8bcd\u7684\u5355\u5143\u683c\u5b50\u96c6\uff08\u8c13\u8bcd\u662f\u4e00\u4e2a\u53c2\u6570\u7684\u51fd\u6570\uff0c\u8981\u4e48\u8fd4\u56de\u771f\uff0c\u8981\u4e48\u8fd4\u56de\u5047\uff09\u3002\u6211\u4eec\u5728\u8fd9\u91cc\u4f7f\u7528\u7684\u8c13\u8bcd\u662f IteratorFilters::LocallyOwnedCell, \uff0c\u4e5f\u5c31\u662f\u8bf4\uff0c\u5982\u679c\u5355\u5143\u683c\u4e3a\u5f53\u524d\u5904\u7406\u5668\u6240\u62e5\u6709\uff0c\u5b83\u5c31\u4f1a\u51c6\u786e\u8fd4\u56de\u771f\u3002\u8fd9\u6837\u5f97\u5230\u7684\u8fed\u4ee3\u5668\u8303\u56f4\u6b63\u662f\u6211\u4eec\u9700\u8981\u7684\u3002\n\n// \u6709\u4e86\u8fd9\u4e2a\u969c\u788d\uff0c\u6211\u4eec\u7528\u8fd9\u7ec4\u5355\u5143\u683c\u3001scratch\u548ccopy\u5bf9\u8c61\u4ee5\u53ca\u4e24\u4e2a\u51fd\u6570\u7684\u6307\u9488\u6765\u8c03\u7528 WorkStream::run \u51fd\u6570\uff1a\u672c\u5730\u88c5\u914d\u548ccopy-local-to-global\u51fd\u6570\u3002\u8fd9\u4e9b\u51fd\u6570\u9700\u8981\u6709\u975e\u5e38\u5177\u4f53\u7684\u7b7e\u540d\uff1a\u524d\u8005\u6709\u4e09\u4e2a\u53c2\u6570\uff0c\u540e\u8005\u6709\u4e00\u4e2a\u53c2\u6570\uff08\u5173\u4e8e\u8fd9\u4e9b\u53c2\u6570\u7684\u542b\u4e49\uff0c\u8bf7\u53c2\u89c1 WorkStream::run \u51fd\u6570\u7684\u6587\u6863\uff09\u3002\u6ce8\u610f\u6211\u4eec\u662f\u5982\u4f55\u4f7f\u7528lambda\u51fd\u6570\u6765\u521b\u5efa\u4e00\u4e2a\u6ee1\u8db3\u8fd9\u4e00\u8981\u6c42\u7684\u51fd\u6570\u5bf9\u8c61\u7684\u3002\u5b83\u4f7f\u7528\u4e86\u6307\u5b9a\u5355\u5143\u683c\u3001\u6293\u53d6\u6570\u636e\u548c\u590d\u5236\u6570\u636e\u7684\u672c\u5730\u88c5\u914d\u51fd\u6570\u7684\u51fd\u6570\u53c2\u6570\uff0c\u4ee5\u53ca\u671f\u671b\u5c06\u6570\u636e\u5199\u5165\u5168\u5c40\u77e9\u9635\u7684\u590d\u5236\u51fd\u6570\u7684\u51fd\u6570\u53c2\u6570\uff08\u4e5f\u53ef\u53c2\u89c1 step-13 \u7684 <code>assemble_linear_system()</code> \u51fd\u6570\u4e2d\u7684\u8ba8\u8bba\uff09\u3002\u53e6\u4e00\u65b9\u9762\uff0c\u6210\u5458\u51fd\u6570\u7684\u9690\u542b\u7684\u7b2c2\u4e2a\u53c2\u6570\uff08\u5373\u8be5\u6210\u5458\u51fd\u6570\u8981\u64cd\u4f5c\u7684\u5bf9\u8c61\u7684 <code>this</code> \u6307\u9488\uff09\u662f<i>bound</i>\u5230\u5f53\u524d\u51fd\u6570\u7684 <code>this</code> \u6307\u9488\u7684\uff0c\u5e76\u88ab\u6355\u83b7\u3002\u56e0\u6b64\uff0c WorkStream::run \u51fd\u6570\u4e0d\u9700\u8981\u77e5\u9053\u8fd9\u4e9b\u51fd\u6570\u6240\u64cd\u4f5c\u7684\u5bf9\u8c61\u7684\u4efb\u4f55\u4fe1\u606f\u3002\n\n// \u5f53WorkStream\u88ab\u6267\u884c\u65f6\uff0c\u5b83\u5c06\u4e3a\u51e0\u4e2a\u5355\u5143\u521b\u5efa\u51e0\u4e2a\u7b2c\u4e00\u7c7b\u7684\u672c\u5730\u88c5\u914d\u4f8b\u7a0b\uff0c\u5e76\u8ba9\u4e00\u4e9b\u53ef\u7528\u7684\u5904\u7406\u5668\u5bf9\u5176\u5de5\u4f5c\u3002\u7136\u800c\uff0c\u9700\u8981\u540c\u6b65\u7684\u51fd\u6570\uff0c\u5373\u5199\u8fdb\u5168\u5c40\u77e9\u9635\u7684\u64cd\u4f5c\uff0c\u6bcf\u6b21\u53ea\u7531\u4e00\u4e2a\u7ebf\u7a0b\u6309\u7167\u89c4\u5b9a\u7684\u987a\u5e8f\u6267\u884c\u3002\u5f53\u7136\uff0c\u8fd9\u53ea\u9002\u7528\u4e8e\u5355\u4e2aMPI\u8fdb\u7a0b\u4e0a\u7684\u5e76\u884c\u5316\u3002\u4e0d\u540c\u7684MPI\u8fdb\u7a0b\u5c06\u6709\u81ea\u5df1\u7684WorkStream\u5bf9\u8c61\uff0c\u5e76\u5b8c\u5168\u72ec\u7acb\u5730\u8fdb\u884c\u8fd9\u9879\u5de5\u4f5c\uff08\u5e76\u4e14\u5728\u4e0d\u540c\u7684\u5185\u5b58\u7a7a\u95f4\uff09\u3002\u5728\u5206\u5e03\u5f0f\u8ba1\u7b97\u4e2d\uff0c\u4e00\u4e9b\u6570\u636e\u5c06\u79ef\u7d2f\u5728\u4e0d\u5c5e\u4e8e\u5404\u81ea\u5904\u7406\u5668\u7684\u81ea\u7531\u5ea6\u4e0a\u3002\u5982\u679c\u6bcf\u6b21\u9047\u5230\u8fd9\u6837\u7684\u81ea\u7531\u5ea6\u5c31\u628a\u6570\u636e\u9001\u6765\u9001\u53bb\uff0c\u90a3\u5c31\u6ca1\u6709\u6548\u7387\u4e86\u3002\u53d6\u800c\u4ee3\u4e4b\u7684\u662f\uff0cTrilinos\u7a00\u758f\u77e9\u9635\u5c06\u4fdd\u7559\u8fd9\u4e9b\u6570\u636e\uff0c\u5e76\u5728\u88c5\u914d\u7ed3\u675f\u65f6\u901a\u8fc7\u8c03\u7528 <code>compress()</code> \u547d\u4ee4\u5c06\u5176\u53d1\u9001\u7ed9\u6240\u6709\u8005\u3002\n\n  template <int dim> \n  void BoussinesqFlowProblem<dim>::assemble_stokes_preconditioner() \n  { \n    stokes_preconditioner_matrix = 0; \n\n    const QGauss<dim> quadrature_formula(parameters.stokes_velocity_degree + 1); \n\n    using CellFilter = \n      FilteredIterator<typename DoFHandler<2>::active_cell_iterator>; \n\n    auto worker = \n      [this](const typename DoFHandler<dim>::active_cell_iterator &cell, \n             Assembly::Scratch::StokesPreconditioner<dim> &        scratch, \n             Assembly::CopyData::StokesPreconditioner<dim> &       data) { \n        this->local_assemble_stokes_preconditioner(cell, scratch, data); \n      }; \n\n    auto copier = \n      [this](const Assembly::CopyData::StokesPreconditioner<dim> &data) { \n        this->copy_local_to_global_stokes_preconditioner(data); \n      }; \n\n    WorkStream::run(CellFilter(IteratorFilters::LocallyOwnedCell(), \n                               stokes_dof_handler.begin_active()), \n                    CellFilter(IteratorFilters::LocallyOwnedCell(), \n                               stokes_dof_handler.end()), \n                    worker, \n                    copier, \n                    Assembly::Scratch::StokesPreconditioner<dim>( \n                      stokes_fe, \n                      quadrature_formula, \n                      mapping, \n                      update_JxW_values | update_values | update_gradients), \n                    Assembly::CopyData::StokesPreconditioner<dim>(stokes_fe)); \n\n    stokes_preconditioner_matrix.compress(VectorOperation::add); \n  } \n\n// \u8fd9\u4e2a\u6a21\u5757\u7684\u6700\u540e\u4e00\u4e2a\u51fd\u6570\u542f\u52a8\u4e86\u65af\u6258\u514b\u65af\u9884\u5904\u7406\u77e9\u9635\u7684\u88c5\u914d\uff0c\u7136\u540e\u5b9e\u9645\u4e0a\u662f\u5efa\u7acb\u4e86\u65af\u6258\u514b\u65af\u9884\u5904\u7406\u7a0b\u5e8f\u3002\u5b83\u4e0e\u4e32\u884c\u60c5\u51b5\u4e0b\u7684\u529f\u80fd\u57fa\u672c\u76f8\u540c\u3002\u4e0e step-31 \u552f\u4e00\u4e0d\u540c\u7684\u662f\uff0c\u6211\u4eec\u5bf9\u538b\u529b\u8d28\u91cf\u77e9\u9635\u4f7f\u7528\u96c5\u53ef\u6bd4\u9884\u5904\u7406\uff0c\u800c\u4e0d\u662fIC\uff0c\u8fd9\u4e00\u70b9\u5728\u4ecb\u7ecd\u4e2d\u5df2\u7ecf\u8ba8\u8bba\u8fc7\u3002\n\n  template <int dim> \n  void BoussinesqFlowProblem<dim>::build_stokes_preconditioner() \n  { \n    if (rebuild_stokes_preconditioner == false) \n      return; \n\n    TimerOutput::Scope timer_section(computing_timer, \n                                     \"   Build Stokes preconditioner\"); \n    pcout << \"   Rebuilding Stokes preconditioner...\" << std::flush; \n\n    assemble_stokes_preconditioner(); \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( \n                                       velocity_components), \n                                     constant_modes); \n\n    Mp_preconditioner = \n      std::make_shared<TrilinosWrappers::PreconditionJacobi>(); \n    Amg_preconditioner = std::make_shared<TrilinosWrappers::PreconditionAMG>(); \n\n    TrilinosWrappers::PreconditionAMG::AdditionalData Amg_data; \n    Amg_data.constant_modes        = constant_modes; \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\n    Mp_preconditioner->initialize(stokes_preconditioner_matrix.block(1, 1)); \n    Amg_preconditioner->initialize(stokes_preconditioner_matrix.block(0, 0), \n                                   Amg_data); \n\n    rebuild_stokes_preconditioner = false; \n\n    pcout << std::endl; \n  } \n// @sect5{Stokes system assembly}  \n\n// \u63a5\u4e0b\u6765\u7684\u4e09\u4e2a\u51fd\u6570\u5b9e\u73b0\u4e86\u65af\u6258\u514b\u65af\u7cfb\u7edf\u7684\u88c5\u914d\uff0c\u540c\u6837\u5206\u4e3a\u6267\u884c\u5c40\u90e8\u8ba1\u7b97\u7684\u90e8\u5206\uff0c\u5c06\u5c40\u90e8\u6570\u636e\u5199\u5165\u5168\u5c40\u77e9\u9635\u548c\u5411\u91cf\u7684\u90e8\u5206\uff0c\u4ee5\u53ca\u5728WorkStream\u7c7b\u7684\u5e2e\u52a9\u4e0b\u5b9e\u9645\u8fd0\u884c\u6240\u6709\u5355\u5143\u7684\u5faa\u73af\u3002\u8bf7\u6ce8\u610f\uff0c\u53ea\u6709\u5728\u6211\u4eec\u6539\u53d8\u4e86\u7f51\u683c\u7684\u60c5\u51b5\u4e0b\u624d\u9700\u8981\u8fdb\u884c\u65af\u6258\u514b\u65af\u77e9\u9635\u7684\u7ec4\u88c5\u3002\u5426\u5219\uff0c\u8fd9\u91cc\u53ea\u9700\u8981\u8ba1\u7b97\uff08\u4e0e\u6e29\u5ea6\u6709\u5173\u7684\uff09\u53f3\u624b\u8fb9\u3002\u7531\u4e8e\u6211\u4eec\u6b63\u5728\u5904\u7406\u5206\u5e03\u5f0f\u77e9\u9635\u548c\u5411\u91cf\uff0c\u6211\u4eec\u5fc5\u987b\u5728\u88c5\u914d\u7ed3\u675f\u65f6\u8c03\u7528\u76f8\u5e94\u7684 <code>compress()</code> \u51fd\u6570\uff0c\u4ee5\u4fbf\u5c06\u975e\u672c\u5730\u6570\u636e\u53d1\u9001\u5230\u6240\u6709\u8005\u8fdb\u7a0b\u3002\n\n  template <int dim> \n  void BoussinesqFlowProblem<dim>::local_assemble_stokes_system( \n    const typename DoFHandler<dim>::active_cell_iterator &cell, \n    Assembly::Scratch::StokesSystem<dim> &                scratch, \n    Assembly::CopyData::StokesSystem<dim> &               data) \n  { \n    const unsigned int dofs_per_cell = \n      scratch.stokes_fe_values.get_fe().n_dofs_per_cell(); \n    const unsigned int n_q_points = \n      scratch.stokes_fe_values.n_quadrature_points; \n\n    const FEValuesExtractors::Vector velocities(0); \n    const FEValuesExtractors::Scalar pressure(dim); \n\n    scratch.stokes_fe_values.reinit(cell); \n\n    typename DoFHandler<dim>::active_cell_iterator temperature_cell( \n      &triangulation, cell->level(), cell->index(), &temperature_dof_handler); \n    scratch.temperature_fe_values.reinit(temperature_cell); \n\n    if (rebuild_stokes_matrix) \n      data.local_matrix = 0; \n    data.local_rhs = 0; \n\n    scratch.temperature_fe_values.get_function_values( \n      old_temperature_solution, scratch.old_temperature_values); \n\n    for (unsigned int q = 0; q < n_q_points; ++q) \n      { \n        const double old_temperature = scratch.old_temperature_values[q]; \n\n        for (unsigned int k = 0; k < dofs_per_cell; ++k) \n          { \n            scratch.phi_u[k] = scratch.stokes_fe_values[velocities].value(k, q); \n            if (rebuild_stokes_matrix) \n              { \n                scratch.grads_phi_u[k] = \n                  scratch.stokes_fe_values[velocities].symmetric_gradient(k, q); \n                scratch.div_phi_u[k] = \n                  scratch.stokes_fe_values[velocities].divergence(k, q); \n                scratch.phi_p[k] = \n                  scratch.stokes_fe_values[pressure].value(k, q); \n              } \n          } \n\n        if (rebuild_stokes_matrix == true) \n          for (unsigned int i = 0; i < dofs_per_cell; ++i) \n            for (unsigned int j = 0; j < dofs_per_cell; ++j) \n              data.local_matrix(i, j) += \n                (EquationData::eta * 2 * \n                   (scratch.grads_phi_u[i] * scratch.grads_phi_u[j]) - \n                 (EquationData::pressure_scaling * scratch.div_phi_u[i] * \n                  scratch.phi_p[j]) - \n                 (EquationData::pressure_scaling * scratch.phi_p[i] * \n                  scratch.div_phi_u[j])) * \n                scratch.stokes_fe_values.JxW(q); \n\n        const Tensor<1, dim> gravity = EquationData::gravity_vector( \n          scratch.stokes_fe_values.quadrature_point(q)); \n\n        for (unsigned int i = 0; i < dofs_per_cell; ++i) \n          data.local_rhs(i) += (EquationData::density(old_temperature) * \n                                gravity * scratch.phi_u[i]) * \n                               scratch.stokes_fe_values.JxW(q); \n      } \n\n    cell->get_dof_indices(data.local_dof_indices); \n  } \n\n  template <int dim> \n  void BoussinesqFlowProblem<dim>::copy_local_to_global_stokes_system( \n    const Assembly::CopyData::StokesSystem<dim> &data) \n  { \n    if (rebuild_stokes_matrix == true) \n      stokes_constraints.distribute_local_to_global(data.local_matrix, \n                                                    data.local_rhs, \n                                                    data.local_dof_indices, \n                                                    stokes_matrix, \n                                                    stokes_rhs); \n    else \n      stokes_constraints.distribute_local_to_global(data.local_rhs, \n                                                    data.local_dof_indices, \n                                                    stokes_rhs); \n  } \n\n  template <int dim> \n  void BoussinesqFlowProblem<dim>::assemble_stokes_system() \n  { \n    TimerOutput::Scope timer_section(computing_timer, \n                                     \"   Assemble Stokes system\"); \n\n    if (rebuild_stokes_matrix == true) \n      stokes_matrix = 0; \n\n    stokes_rhs = 0; \n\n    const QGauss<dim> quadrature_formula(parameters.stokes_velocity_degree + 1); \n\n    using CellFilter = \n      FilteredIterator<typename DoFHandler<2>::active_cell_iterator>; \n\n    WorkStream::run( \n      CellFilter(IteratorFilters::LocallyOwnedCell(), \n                 stokes_dof_handler.begin_active()), \n      CellFilter(IteratorFilters::LocallyOwnedCell(), stokes_dof_handler.end()), \n      [this](const typename DoFHandler<dim>::active_cell_iterator &cell, \n             Assembly::Scratch::StokesSystem<dim> &                scratch, \n             Assembly::CopyData::StokesSystem<dim> &               data) { \n        this->local_assemble_stokes_system(cell, scratch, data); \n      }, \n      [this](const Assembly::CopyData::StokesSystem<dim> &data) { \n        this->copy_local_to_global_stokes_system(data); \n      }, \n      Assembly::Scratch::StokesSystem<dim>( \n        stokes_fe, \n        mapping, \n        quadrature_formula, \n        (update_values | update_quadrature_points | update_JxW_values | \n         (rebuild_stokes_matrix == true ? update_gradients : UpdateFlags(0))), \n        temperature_fe, \n        update_values), \n      Assembly::CopyData::StokesSystem<dim>(stokes_fe)); \n\n    if (rebuild_stokes_matrix == true) \n      stokes_matrix.compress(VectorOperation::add); \n    stokes_rhs.compress(VectorOperation::add); \n\n    rebuild_stokes_matrix = false; \n\n    pcout << std::endl; \n  } \n// @sect5{Temperature matrix assembly}  \n\n// \u4e0b\u9762\u4e09\u4e2a\u51fd\u6570\u8981\u5b8c\u6210\u7684\u4efb\u52a1\u662f\u8ba1\u7b97\u6e29\u5ea6\u7cfb\u7edf\u7684\u8d28\u91cf\u77e9\u9635\u548c\u62c9\u666e\u62c9\u65af\u77e9\u9635\u3002\u8fd9\u4e9b\u5c06\u88ab\u7ed3\u5408\u8d77\u6765\uff0c\u4ee5\u4ea7\u751f\u534a\u9690\u5f0f\u65f6\u95f4\u6b65\u8fdb\u77e9\u9635\uff0c\u8be5\u77e9\u9635\u7531\u8d28\u91cf\u77e9\u9635\u52a0\u4e0a\u4e00\u4e2a\u4e0e\u65f6\u95f4 step- \u76f8\u5173\u7684\u6743\u91cd\u7cfb\u6570\u4e58\u4ee5\u62c9\u666e\u62c9\u65af\u77e9\u9635\u7ec4\u6210\u3002\u8fd9\u4e2a\u51fd\u6570\u672c\u8d28\u4e0a\u8fd8\u662f\u4ece step-31 \u5f00\u59cb\u7684\u6240\u6709\u5355\u5143\u7684\u5faa\u73af\u4e3b\u4f53\u3002\n\n// \u4e0b\u9762\u4e24\u4e2a\u51fd\u6570\u7684\u529f\u80fd\u4e0e\u4e0a\u9762\u7684\u7c7b\u4f3c\u3002\n\n  template <int dim> \n  void BoussinesqFlowProblem<dim>::local_assemble_temperature_matrix( \n    const typename DoFHandler<dim>::active_cell_iterator &cell, \n    Assembly::Scratch::TemperatureMatrix<dim> &           scratch, \n    Assembly::CopyData::TemperatureMatrix<dim> &          data) \n  { \n    const unsigned int dofs_per_cell = \n      scratch.temperature_fe_values.get_fe().n_dofs_per_cell(); \n    const unsigned int n_q_points = \n      scratch.temperature_fe_values.n_quadrature_points; \n\n    scratch.temperature_fe_values.reinit(cell); \n    cell->get_dof_indices(data.local_dof_indices); \n\n    data.local_mass_matrix      = 0; \n    data.local_stiffness_matrix = 0; \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            scratch.grad_phi_T[k] = \n              scratch.temperature_fe_values.shape_grad(k, q); \n            scratch.phi_T[k] = scratch.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              data.local_mass_matrix(i, j) += \n                (scratch.phi_T[i] * scratch.phi_T[j] * \n                 scratch.temperature_fe_values.JxW(q)); \n              data.local_stiffness_matrix(i, j) += \n                (EquationData::kappa * scratch.grad_phi_T[i] * \n                 scratch.grad_phi_T[j] * scratch.temperature_fe_values.JxW(q)); \n            } \n      } \n  } \n\n  template <int dim> \n  void BoussinesqFlowProblem<dim>::copy_local_to_global_temperature_matrix( \n    const Assembly::CopyData::TemperatureMatrix<dim> &data) \n  { \n    temperature_constraints.distribute_local_to_global(data.local_mass_matrix, \n                                                       data.local_dof_indices, \n                                                       temperature_mass_matrix); \n    temperature_constraints.distribute_local_to_global( \n      data.local_stiffness_matrix, \n      data.local_dof_indices, \n      temperature_stiffness_matrix); \n  } \n\n  template <int dim> \n  void BoussinesqFlowProblem<dim>::assemble_temperature_matrix() \n  { \n    if (rebuild_temperature_matrices == false) \n      return; \n\n    TimerOutput::Scope timer_section(computing_timer, \n                                     \"   Assemble temperature matrices\"); \n    temperature_mass_matrix      = 0; \n    temperature_stiffness_matrix = 0; \n\n    const QGauss<dim> quadrature_formula(parameters.temperature_degree + 2); \n\n    using CellFilter = \n      FilteredIterator<typename DoFHandler<2>::active_cell_iterator>; \n\n    WorkStream::run( \n      CellFilter(IteratorFilters::LocallyOwnedCell(), \n                 temperature_dof_handler.begin_active()), \n      CellFilter(IteratorFilters::LocallyOwnedCell(), \n                 temperature_dof_handler.end()), \n      [this](const typename DoFHandler<dim>::active_cell_iterator &cell, \n             Assembly::Scratch::TemperatureMatrix<dim> &           scratch, \n             Assembly::CopyData::TemperatureMatrix<dim> &          data) { \n        this->local_assemble_temperature_matrix(cell, scratch, data); \n      }, \n      [this](const Assembly::CopyData::TemperatureMatrix<dim> &data) { \n        this->copy_local_to_global_temperature_matrix(data); \n      }, \n      Assembly::Scratch::TemperatureMatrix<dim>(temperature_fe, \n                                                mapping, \n                                                quadrature_formula), \n      Assembly::CopyData::TemperatureMatrix<dim>(temperature_fe)); \n\n    temperature_mass_matrix.compress(VectorOperation::add); \n    temperature_stiffness_matrix.compress(VectorOperation::add); \n\n    rebuild_temperature_matrices       = false; \n    rebuild_temperature_preconditioner = true; \n  } \n// @sect5{Temperature right hand side assembly}  \n\n// \u8fd9\u662f\u6700\u540e\u4e00\u4e2a\u88c5\u914d\u51fd\u6570\u3002\u5b83\u8ba1\u7b97\u6e29\u5ea6\u7cfb\u7edf\u7684\u53f3\u4fa7\uff0c\u5176\u4e2d\u5305\u62ec\u5bf9\u6d41\u548c\u7a33\u5b9a\u9879\u3002\u5b83\u5305\u62ec\u5bf9\u6b63\u4ea4\u70b9\u4e0a\u7684\u65e7\u89e3\u7684\u5927\u91cf\u8bc4\u4f30\uff08\u8fd9\u5bf9\u4e8e\u8ba1\u7b97\u7a33\u5b9a\u5316\u7684\u4eba\u5de5\u7c98\u6027\u662f\u5fc5\u8981\u7684\uff09\uff0c\u4f46\u5728\u5176\u4ed6\u65b9\u9762\u4e0e\u5176\u4ed6\u88c5\u914d\u51fd\u6570\u7c7b\u4f3c\u3002\u8bf7\u6ce8\u610f\uff0c\u6211\u4eec\u518d\u6b21\u89e3\u51b3\u4e86\u5177\u6709\u4e0d\u5747\u5300\u8fb9\u754c\u6761\u4ef6\u7684\u56f0\u5883\uff0c\u53ea\u662f\u5728\u8fd9\u4e00\u70b9\u4e0a\u505a\u4e86\u4e00\u4e2a\u53f3\u624b\u8fb9\uff08\u6bd4\u8f83\u4e0a\u9762\u5bf9 <code>project()</code> \u51fd\u6570\u7684\u8bc4\u8bba\uff09\u3002\u6211\u4eec\u521b\u5efa\u4e00\u4e9b\u77e9\u9635\u5217\uff0c\u5176\u503c\u6b63\u597d\u662f\u4e3a\u6e29\u5ea6\u521a\u5ea6\u77e9\u9635\u8f93\u5165\u7684\u503c\uff0c\u5982\u679c\u6211\u4eec\u6709\u4e0d\u5747\u5300\u7ea6\u675f\u7684DFS\u7684\u8bdd\u3002\u8fd9\u5c06\u8bf4\u660e\u53f3\u8fb9\u7684\u5411\u91cf\u4e0e\u6e29\u5ea6\u77e9\u9635\u7cfb\u7edf\u7684\u6b63\u786e\u5e73\u8861\u3002\n\n  template <int dim> \n  void BoussinesqFlowProblem<dim>::local_assemble_temperature_rhs( \n    const std::pair<double, double> global_T_range, \n    const double                    global_max_velocity, \n    const double                    global_entropy_variation, \n    const typename DoFHandler<dim>::active_cell_iterator &cell, \n    Assembly::Scratch::TemperatureRHS<dim> &              scratch, \n    Assembly::CopyData::TemperatureRHS<dim> &             data) \n  { \n    const bool use_bdf2_scheme = (timestep_number != 0); \n\n    const unsigned int dofs_per_cell = \n      scratch.temperature_fe_values.get_fe().n_dofs_per_cell(); \n    const unsigned int n_q_points = \n      scratch.temperature_fe_values.n_quadrature_points; \n\n    const FEValuesExtractors::Vector velocities(0); \n\n    data.local_rhs     = 0; \n    data.matrix_for_bc = 0; \n    cell->get_dof_indices(data.local_dof_indices); \n\n    scratch.temperature_fe_values.reinit(cell); \n\n    typename DoFHandler<dim>::active_cell_iterator stokes_cell( \n      &triangulation, cell->level(), cell->index(), &stokes_dof_handler); \n    scratch.stokes_fe_values.reinit(stokes_cell); \n\n    scratch.temperature_fe_values.get_function_values( \n      old_temperature_solution, scratch.old_temperature_values); \n    scratch.temperature_fe_values.get_function_values( \n      old_old_temperature_solution, scratch.old_old_temperature_values); \n\n    scratch.temperature_fe_values.get_function_gradients( \n      old_temperature_solution, scratch.old_temperature_grads); \n    scratch.temperature_fe_values.get_function_gradients( \n      old_old_temperature_solution, scratch.old_old_temperature_grads); \n\n    scratch.temperature_fe_values.get_function_laplacians( \n      old_temperature_solution, scratch.old_temperature_laplacians); \n    scratch.temperature_fe_values.get_function_laplacians( \n      old_old_temperature_solution, scratch.old_old_temperature_laplacians); \n\n    scratch.stokes_fe_values[velocities].get_function_values( \n      stokes_solution, scratch.old_velocity_values); \n    scratch.stokes_fe_values[velocities].get_function_values( \n      old_stokes_solution, scratch.old_old_velocity_values); \n    scratch.stokes_fe_values[velocities].get_function_symmetric_gradients( \n      stokes_solution, scratch.old_strain_rates); \n    scratch.stokes_fe_values[velocities].get_function_symmetric_gradients( \n      old_stokes_solution, scratch.old_old_strain_rates); \n\n    const double nu = \n      compute_viscosity(scratch.old_temperature_values, \n                        scratch.old_old_temperature_values, \n                        scratch.old_temperature_grads, \n                        scratch.old_old_temperature_grads, \n                        scratch.old_temperature_laplacians, \n                        scratch.old_old_temperature_laplacians, \n                        scratch.old_velocity_values, \n                        scratch.old_old_velocity_values, \n                        scratch.old_strain_rates, \n                        scratch.old_old_strain_rates, \n                        global_max_velocity, \n                        global_T_range.second - global_T_range.first, \n                        0.5 * (global_T_range.second + global_T_range.first), \n                        global_entropy_variation, \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            scratch.phi_T[k] = scratch.temperature_fe_values.shape_value(k, q); \n            scratch.grad_phi_T[k] = \n              scratch.temperature_fe_values.shape_grad(k, q); \n          } \n\n        const double T_term_for_rhs = \n          (use_bdf2_scheme ? \n             (scratch.old_temperature_values[q] * \n                (1 + time_step / old_time_step) - \n              scratch.old_old_temperature_values[q] * (time_step * time_step) / \n                (old_time_step * (time_step + old_time_step))) : \n             scratch.old_temperature_values[q]); \n\n        const double ext_T = \n          (use_bdf2_scheme ? (scratch.old_temperature_values[q] * \n                                (1 + time_step / old_time_step) - \n                              scratch.old_old_temperature_values[q] * \n                                time_step / old_time_step) : \n                             scratch.old_temperature_values[q]); \n\n        const Tensor<1, dim> ext_grad_T = \n          (use_bdf2_scheme ? (scratch.old_temperature_grads[q] * \n                                (1 + time_step / old_time_step) - \n                              scratch.old_old_temperature_grads[q] * time_step / \n                                old_time_step) : \n                             scratch.old_temperature_grads[q]); \n\n        const Tensor<1, dim> extrapolated_u = \n          (use_bdf2_scheme ? \n             (scratch.old_velocity_values[q] * (1 + time_step / old_time_step) - \n              scratch.old_old_velocity_values[q] * time_step / old_time_step) : \n             scratch.old_velocity_values[q]); \n\n        const SymmetricTensor<2, dim> extrapolated_strain_rate = \n          (use_bdf2_scheme ? \n             (scratch.old_strain_rates[q] * (1 + time_step / old_time_step) - \n              scratch.old_old_strain_rates[q] * time_step / old_time_step) : \n             scratch.old_strain_rates[q]); \n\n        const double gamma = \n          ((EquationData::radiogenic_heating * EquationData::density(ext_T) + \n            2 * EquationData::eta * extrapolated_strain_rate * \n              extrapolated_strain_rate) / \n           (EquationData::density(ext_T) * EquationData::specific_heat)); \n\n        for (unsigned int i = 0; i < dofs_per_cell; ++i) \n          { \n            data.local_rhs(i) += \n              (T_term_for_rhs * scratch.phi_T[i] - \n               time_step * extrapolated_u * ext_grad_T * scratch.phi_T[i] - \n               time_step * nu * ext_grad_T * scratch.grad_phi_T[i] + \n               time_step * gamma * scratch.phi_T[i]) * \n              scratch.temperature_fe_values.JxW(q); \n\n            if (temperature_constraints.is_inhomogeneously_constrained( \n                  data.local_dof_indices[i])) \n              { \n                for (unsigned int j = 0; j < dofs_per_cell; ++j) \n                  data.matrix_for_bc(j, i) += \n                    (scratch.phi_T[i] * scratch.phi_T[j] * \n                       (use_bdf2_scheme ? ((2 * time_step + old_time_step) / \n                                           (time_step + old_time_step)) : \n                                          1.) + \n                     scratch.grad_phi_T[i] * scratch.grad_phi_T[j] * \n                       EquationData::kappa * time_step) * \n                    scratch.temperature_fe_values.JxW(q); \n              } \n          } \n      } \n  } \n\n  template <int dim> \n  void BoussinesqFlowProblem<dim>::copy_local_to_global_temperature_rhs( \n    const Assembly::CopyData::TemperatureRHS<dim> &data) \n  { \n    temperature_constraints.distribute_local_to_global(data.local_rhs, \n                                                       data.local_dof_indices, \n                                                       temperature_rhs, \n                                                       data.matrix_for_bc); \n  } \n\n// \u5728\u8fd0\u884c\u5b9e\u9645\u8ba1\u7b97\u53f3\u624b\u8fb9\u7684WorkStream\u7684\u51fd\u6570\u4e2d\uff0c\u6211\u4eec\u4e5f\u751f\u6210\u4e86\u6700\u7ec8\u77e9\u9635\u3002\u5982\u4e0a\u6240\u8ff0\uff0c\u5b83\u662f\u8d28\u91cf\u77e9\u9635\u548c\u62c9\u666e\u62c9\u65af\u77e9\u9635\u7684\u603b\u548c\uff0c\u518d\u52a0\u4e0a\u4e00\u4e9b\u4e0e\u65f6\u95f4 step- \u76f8\u5173\u7684\u6743\u91cd\u3002\u8fd9\u4e2a\u6743\u91cd\u662f\u7531BDF-2\u65f6\u95f4\u79ef\u5206\u65b9\u6848\u6307\u5b9a\u7684\uff0c\u89c1  step-31  \u4e2d\u7684\u4ecb\u7ecd\u3002\u8fd9\u4e2a\u6559\u7a0b\u7a0b\u5e8f\u7684\u65b0\u5185\u5bb9\uff08\u9664\u4e86\u4f7f\u7528MPI\u5e76\u884c\u5316\u548cWorkStream\u7c7b\uff09\uff0c\u662f\u6211\u4eec\u73b0\u5728\u4e5f\u9884\u5148\u8ba1\u7b97\u4e86\u6e29\u5ea6\u9884\u5904\u7406\u7a0b\u5e8f\u3002\u539f\u56e0\u662f\u4e0e\u6c42\u89e3\u5668\u76f8\u6bd4\uff0c\u8bbe\u7f6e\u96c5\u53ef\u6bd4\u9884\u5904\u7406\u5668\u9700\u8981\u660e\u663e\u7684\u65f6\u95f4\uff0c\u56e0\u4e3a\u6211\u4eec\u901a\u5e38\u53ea\u9700\u898110\u523020\u6b21\u8fed\u4ee3\u6765\u6c42\u89e3\u6e29\u5ea6\u7cfb\u7edf\uff08\u8fd9\u542c\u8d77\u6765\u5f88\u5947\u602a\uff0c\u56e0\u4e3a\u96c5\u53ef\u6bd4\u5b9e\u9645\u4e0a\u53ea\u5305\u62ec\u5bf9\u89d2\u7ebf\uff0c\u4f46\u5728\u7279\u91cc\u8bfa\u65af\uff0c\u5b83\u662f\u4ece\u66f4\u666e\u904d\u7684\u70b9\u677e\u5f1b\u9884\u5904\u7406\u5668\u6846\u67b6\u4e2d\u884d\u751f\u51fa\u6765\u7684\uff0c\u6548\u7387\u6709\u70b9\u4f4e\uff09\u3002\u56e0\u6b64\uff0c\u5c3d\u7ba1\u7531\u4e8e\u65f6\u95f4\u6b65\u957f\u53ef\u80fd\u4f1a\u53d1\u751f\u53d8\u5316\uff0c\u77e9\u9635\u6761\u76ee\u53ef\u80fd\u4f1a\u7565\u6709\u53d8\u5316\uff0c\u4f46\u9884\u5148\u8ba1\u7b97\u9884\u5904\u7406\u7a0b\u5e8f\u7684\u6548\u7387\u66f4\u9ad8\u3002\u8fd9\u4e0d\u662f\u592a\u5927\u7684\u95ee\u9898\uff0c\u56e0\u4e3a\u6211\u4eec\u6bcf\u9694\u51e0\u6b65\u5c31\u91cd\u65b0\u7f51\u683c\u5316\uff08\u7136\u540e\u91cd\u65b0\u751f\u6210\u9884\u5904\u7406\u7a0b\u5e8f\uff09\u3002\n\n  template <int dim> \n  void BoussinesqFlowProblem<dim>::assemble_temperature_system( \n    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 *= \n          (2 * time_step + old_time_step) / (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    if (rebuild_temperature_preconditioner == true) \n      { \n        T_preconditioner = \n          std::make_shared<TrilinosWrappers::PreconditionJacobi>(); \n        T_preconditioner->initialize(temperature_matrix); \n        rebuild_temperature_preconditioner = false; \n      } \n\n// \u63a5\u4e0b\u6765\u7684\u90e8\u5206\u662f\u8ba1\u7b97\u53f3\u624b\u8fb9\u7684\u5411\u91cf\u3002 \u4e3a\u6b64\uff0c\u6211\u4eec\u9996\u5148\u8ba1\u7b97\u5e73\u5747\u6e29\u5ea6  $T_m$  \uff0c\u6211\u4eec\u901a\u8fc7\u6b8b\u5dee  $E(T) =\n//  (T-T_m)^2$  \u6765\u8bc4\u4f30\u4eba\u5de5\u9ecf\u5ea6\u7684\u7a33\u5b9a\u3002\u6211\u4eec\u901a\u8fc7\u5728\u71b5\u7c98\u5ea6\u7684\u5b9a\u4e49\u4e2d\u628a\u6700\u9ad8\u548c\u6700\u4f4e\u6e29\u5ea6\u4e4b\u95f4\u7684\u4e2d\u70b9\u5b9a\u4e49\u4e3a\u5e73\u5747\u6e29\u5ea6\u6765\u505a\u5230\u8fd9\u4e00\u70b9\u3002\u53e6\u4e00\u79cd\u65b9\u6cd5\u662f\u4f7f\u7528\u79ef\u5206\u5e73\u5747\uff0c\u4f46\u7ed3\u679c\u5bf9\u8fd9\u79cd\u9009\u62e9\u4e0d\u662f\u5f88\u654f\u611f\u3002\u90a3\u4e48\u5269\u4e0b\u7684\u5c31\u53ea\u9700\u8981\u518d\u6b21\u8c03\u7528 WorkStream::run \uff0c\u5c06\u6bcf\u6b21\u8c03\u7528\u90fd\u76f8\u540c\u7684 <code>local_assemble_temperature_rhs</code> \u51fd\u6570\u7684\u53c2\u6570\u7ed1\u5b9a\u5230\u6b63\u786e\u7684\u503c\u4e2d\u3002\n\n    temperature_rhs = 0; \n\n    const QGauss<dim> quadrature_formula(parameters.temperature_degree + 2); \n    const std::pair<double, double> global_T_range = \n      get_extrapolated_temperature_range(); \n\n    const double average_temperature = \n      0.5 * (global_T_range.first + global_T_range.second); \n    const double global_entropy_variation = \n      get_entropy_variation(average_temperature); \n\n    using CellFilter = \n      FilteredIterator<typename DoFHandler<2>::active_cell_iterator>; \n\n    auto worker = \n      [this, global_T_range, maximal_velocity, global_entropy_variation]( \n        const typename DoFHandler<dim>::active_cell_iterator &cell, \n        Assembly::Scratch::TemperatureRHS<dim> &              scratch, \n        Assembly::CopyData::TemperatureRHS<dim> &             data) { \n        this->local_assemble_temperature_rhs(global_T_range, \n                                             maximal_velocity, \n                                             global_entropy_variation, \n                                             cell, \n                                             scratch, \n                                             data); \n      }; \n\n    auto copier = [this](const Assembly::CopyData::TemperatureRHS<dim> &data) { \n      this->copy_local_to_global_temperature_rhs(data); \n    }; \n\n    WorkStream::run(CellFilter(IteratorFilters::LocallyOwnedCell(), \n                               temperature_dof_handler.begin_active()), \n                    CellFilter(IteratorFilters::LocallyOwnedCell(), \n                               temperature_dof_handler.end()), \n                    worker, \n                    copier, \n                    Assembly::Scratch::TemperatureRHS<dim>( \n                      temperature_fe, stokes_fe, mapping, quadrature_formula), \n                    Assembly::CopyData::TemperatureRHS<dim>(temperature_fe)); \n\n    temperature_rhs.compress(VectorOperation::add); \n  } \n\n//  @sect4{BoussinesqFlowProblem::solve}  \n\n// \u8fd9\u4e2a\u51fd\u6570\u5728Boussinesq\u95ee\u9898\u7684\u6bcf\u4e2a\u65f6\u95f4\u6b65\u957f\u4e2d\u6c42\u89e3\u7ebf\u6027\u7cfb\u7edf\u3002\u9996\u5148\uff0c\u6211\u4eec\u5728\u65af\u6258\u514b\u65af\u7cfb\u7edf\u4e0a\u5de5\u4f5c\uff0c\u7136\u540e\u5728\u6e29\u5ea6\u7cfb\u7edf\u4e0a\u5de5\u4f5c\u3002\u4ece\u672c\u8d28\u4e0a\u8bb2\uff0c\u5b83\u4e0e  step-31  \u4e2d\u7684\u76f8\u5e94\u51fd\u6570\u505a\u4e86\u540c\u6837\u7684\u4e8b\u60c5\u3002\u7136\u800c\uff0c\u8fd9\u91cc\u6709\u4e00\u4e9b\u53d8\u5316\u3002\n\n// \u7b2c\u4e00\u4e2a\u53d8\u5316\u4e0e\u6211\u4eec\u5b58\u50a8\u89e3\u51b3\u65b9\u6848\u7684\u65b9\u5f0f\u6709\u5173\uff1a\u6211\u4eec\u5728\u6bcf\u4e2aMPI\u8282\u70b9\u4e0a\u4fdd\u7559\u5177\u6709\u672c\u5730\u62e5\u6709\u7684\u81ea\u7531\u5ea6\u7684\u5411\u91cf\u52a0\u9b3c\u9b42\u8282\u70b9\u3002\u5f53\u6211\u4eec\u8fdb\u5165\u4e00\u4e2a\u5e94\u8be5\u7528\u5206\u5e03\u5f0f\u77e9\u9635\u8fdb\u884c\u77e9\u9635-\u5411\u91cf\u4e58\u79ef\u7684\u6c42\u89e3\u5668\u65f6\uff0c\u8fd9\u4e0d\u662f\u5408\u9002\u7684\u5f62\u5f0f\uff0c\u867d\u7136\u3002\u5728\u90a3\u91cc\uff0c\u6211\u4eec\u5e0c\u671b\u6c42\u89e3\u5411\u91cf\u7684\u5206\u5e03\u65b9\u5f0f\u4e0e\u77e9\u9635\u7684\u5206\u5e03\u65b9\u5f0f\u76f8\u540c\uff0c\u5373\u6ca1\u6709\u4efb\u4f55\u91cd\u5f71\u3002\u6240\u4ee5\u6211\u4eec\u9996\u5148\u8981\u505a\u7684\u662f\u751f\u6210\u4e00\u4e2a\u540d\u4e3a <code>distributed_stokes_solution</code> \u7684\u5206\u5e03\u5f0f\u5411\u91cf\uff0c\u5e76\u53ea\u5c06\u672c\u5730\u62e5\u6709\u7684dof\u653e\u5165\u5176\u4e2d\uff0c\u8fd9\u53ef\u4ee5\u901a\u8fc7\u7279\u91cc\u8bfa\u5411\u91cf\u7684 <code>operator=</code> \u6574\u9f50\u5730\u5b8c\u6210\u3002\n\n// \u63a5\u4e0b\u6765\uff0c\u6211\u4eec\u4e3a\u6c42\u89e3\u5668\u7f29\u653e\u538b\u529b\u89e3\uff08\u6216\u8005\u8bf4\uff0c\u521d\u59cb\u731c\u6d4b\uff09\uff0c\u4f7f\u5176\u4e0e\u77e9\u9635\u4e2d\u7684\u957f\u5ea6\u5c3a\u5ea6\u76f8\u5339\u914d\uff0c\u6b63\u5982\u5728\u4ecb\u7ecd\u4e2d\u8ba8\u8bba\u7684\u90a3\u6837\u3002\u5728\u6c42\u89e3\u5b8c\u6210\u540e\uff0c\u6211\u4eec\u4e5f\u4f1a\u7acb\u5373\u5c06\u538b\u529b\u503c\u7f29\u56de\u5230\u6b63\u786e\u7684\u5355\u4f4d\u3002 \u6211\u4eec\u8fd8\u9700\u8981\u5c06\u60ac\u6302\u8282\u70b9\u7684\u538b\u529b\u503c\u8bbe\u7f6e\u4e3a\u96f6\u3002\u8fd9\u4e00\u70b9\u6211\u4eec\u5728 step-31 \u4e2d\u4e5f\u505a\u8fc7\uff0c\u4ee5\u907f\u514d\u4e00\u4e9b\u5728\u6c42\u89e3\u9636\u6bb5\u5b9e\u9645\u4e0a\u65e0\u5173\u7d27\u8981\u7684\u5411\u91cf\u9879\u5e72\u6270\u8212\u5c14\u8865\u6570\u3002\u4e0e step-31 \u4e0d\u540c\u7684\u662f\uff0c\u8fd9\u91cc\u6211\u4eec\u53ea\u5bf9\u5c40\u90e8\u62e5\u6709\u7684\u538b\u529b\u9053\u592b\u8fdb\u884c\u4e86\u5904\u7406\u3002\u5728\u5bf9\u65af\u6258\u514b\u65af\u89e3\u8fdb\u884c\u6c42\u89e3\u540e\uff0c\u6bcf\u4e2a\u5904\u7406\u5668\u5c06\u5206\u5e03\u5f0f\u89e3\u590d\u5236\u5230\u89e3\u5411\u91cf\u4e2d\uff0c\u5176\u4e2d\u4e5f\u5305\u62ec\u9b3c\u5143\u7d20\u3002\n\n// \u7b2c\u4e09\u4e2a\u4e5f\u662f\u6700\u660e\u663e\u7684\u53d8\u5316\u662f\uff0c\u6211\u4eec\u6709\u4e24\u79cd\u65af\u6258\u514b\u65af\u6c42\u89e3\u5668\u7684\u53d8\u4f53\u3002\u4e00\u79cd\u662f\u6709\u65f6\u4f1a\u5d29\u6e83\u7684\u5feb\u901f\u6c42\u89e3\u5668\uff0c\u53e6\u4e00\u79cd\u662f\u901f\u5ea6\u8f83\u6162\u7684\u7a33\u5065\u6c42\u89e3\u5668\u3002\u8fd9\u5c31\u662f\u6211\u4eec\u5728\u4ecb\u7ecd\u4e2d\u5df2\u7ecf\u8ba8\u8bba\u8fc7\u7684\u3002\u4ee5\u4e0b\u662f\u6211\u4eec\u5982\u4f55\u5b9e\u73b0\u5b83\u7684\u3002\u9996\u5148\uff0c\u6211\u4eec\u7528\u5feb\u901f\u6c42\u89e3\u5668\u8fdb\u884c30\u6b21\u8fed\u4ee3\uff0c\u8be5\u6c42\u89e3\u5668\u662f\u57fa\u4e8eAMG V\u578b\u5faa\u73af\u7684\u7b80\u5355\u9884\u5904\u7406\uff0c\u800c\u4e0d\u662f\u8fd1\u4f3c\u6c42\u89e3\uff08\u8fd9\u7531 <code>false</code> \u5bf9\u8c61\u7684 <code>LinearSolvers::BlockSchurPreconditioner</code> \u53c2\u6570\u8868\u793a\uff09\u3002\u5982\u679c\u6211\u4eec\u6536\u655b\u4e86\uff0c\u4e00\u5207\u90fd\u5f88\u597d\u3002\u5982\u679c\u6211\u4eec\u6ca1\u6709\u6536\u655b\uff0c\u6c42\u89e3\u5668\u63a7\u5236\u5bf9\u8c61\u5c06\u629b\u51fa\u4e00\u4e2a\u5f02\u5e38 SolverControl::NoConvergence. \u901a\u5e38\uff0c\u8fd9\u5c06\u4e2d\u6b62\u7a0b\u5e8f\uff0c\u56e0\u4e3a\u6211\u4eec\u5728\u901a\u5e38\u7684 <code>solve()</code> \u51fd\u6570\u4e2d\u6ca1\u6709\u6355\u6349\u5b83\u4eec\u3002\u8fd9\u5f53\u7136\u4e0d\u662f\u6211\u4eec\u60f3\u5728\u8fd9\u91cc\u53d1\u751f\u7684\u3002\u76f8\u53cd\uff0c\u6211\u4eec\u5e0c\u671b\u5207\u6362\u5230\u5f3a\u6c42\u89e3\u5668\uff0c\u5e76\u7ee7\u7eed\u7528\u6211\u4eec\u76ee\u524d\u5f97\u5230\u7684\u4efb\u4f55\u77e2\u91cf\u8fdb\u884c\u6c42\u89e3\u3002\u56e0\u6b64\uff0c\u6211\u4eec\u7528C++\u7684try/catch\u673a\u5236\u6765\u6355\u83b7\u8fd9\u4e2a\u5f02\u5e38\u3002\u7136\u540e\u6211\u4eec\u5728 <code>catch</code> \u5b50\u53e5\u4e2d\u7b80\u5355\u5730\u518d\u6b21\u7ecf\u5386\u76f8\u540c\u7684\u6c42\u89e3\u5668\u5e8f\u5217\uff0c\u8fd9\u6b21\u6211\u4eec\u5c06 @p true \u6807\u5fd7\u4f20\u9012\u7ed9\u5f3a\u6c42\u89e3\u5668\u7684\u9884\u5904\u7406\u7a0b\u5e8f\uff0c\u8868\u793a\u8fd1\u4f3cCG\u6c42\u89e3\u3002\n\n  template <int dim> \n  void BoussinesqFlowProblem<dim>::solve() \n  { \n    { \n      TimerOutput::Scope timer_section(computing_timer, \n                                       \"   Solve Stokes system\"); \n\n      pcout << \"   Solving Stokes system... \" << std::flush; \n\n      TrilinosWrappers::MPI::BlockVector distributed_stokes_solution( \n        stokes_rhs); \n      distributed_stokes_solution = stokes_solution; \n\n      distributed_stokes_solution.block(1) /= EquationData::pressure_scaling; \n\n      const unsigned int \n        start = (distributed_stokes_solution.block(0).size() + \n                 distributed_stokes_solution.block(1).local_range().first), \n        end   = (distributed_stokes_solution.block(0).size() + \n               distributed_stokes_solution.block(1).local_range().second); \n      for (unsigned int i = start; i < end; ++i) \n        if (stokes_constraints.is_constrained(i)) \n          distributed_stokes_solution(i) = 0; \n\n      PrimitiveVectorMemory<TrilinosWrappers::MPI::BlockVector> mem; \n\n      unsigned int  n_iterations     = 0; \n      const double  solver_tolerance = 1e-8 * stokes_rhs.l2_norm(); \n      SolverControl solver_control(30, solver_tolerance); \n\n      try \n        { \n          const LinearSolvers::BlockSchurPreconditioner< \n            TrilinosWrappers::PreconditionAMG, \n            TrilinosWrappers::PreconditionJacobi> \n            preconditioner(stokes_matrix, \n                           stokes_preconditioner_matrix, \n                           *Mp_preconditioner, \n                           *Amg_preconditioner, \n                           false); \n\n          SolverFGMRES<TrilinosWrappers::MPI::BlockVector> solver( \n            solver_control, \n            mem, \n            SolverFGMRES<TrilinosWrappers::MPI::BlockVector>::AdditionalData( \n              30)); \n          solver.solve(stokes_matrix, \n                       distributed_stokes_solution, \n                       stokes_rhs, \n                       preconditioner); \n\n          n_iterations = solver_control.last_step(); \n        } \n\n      catch (SolverControl::NoConvergence &) \n        { \n          const LinearSolvers::BlockSchurPreconditioner< \n            TrilinosWrappers::PreconditionAMG, \n            TrilinosWrappers::PreconditionJacobi> \n            preconditioner(stokes_matrix, \n                           stokes_preconditioner_matrix, \n                           *Mp_preconditioner, \n                           *Amg_preconditioner, \n                           true); \n\n          SolverControl solver_control_refined(stokes_matrix.m(), \n                                               solver_tolerance); \n          SolverFGMRES<TrilinosWrappers::MPI::BlockVector> solver( \n            solver_control_refined, \n            mem, \n            SolverFGMRES<TrilinosWrappers::MPI::BlockVector>::AdditionalData( \n              50)); \n          solver.solve(stokes_matrix, \n                       distributed_stokes_solution, \n                       stokes_rhs, \n                       preconditioner); \n\n          n_iterations = \n            (solver_control.last_step() + solver_control_refined.last_step()); \n        } \n\n      stokes_constraints.distribute(distributed_stokes_solution); \n\n      distributed_stokes_solution.block(1) *= EquationData::pressure_scaling; \n\n      stokes_solution = distributed_stokes_solution; \n      pcout << n_iterations << \" iterations.\" << std::endl; \n    } \n\n// \u73b0\u5728\u8ba9\u6211\u4eec\u8f6c\u5230\u6e29\u5ea6\u90e8\u5206\u3002\u9996\u5148\uff0c\u6211\u4eec\u8ba1\u7b97\u65f6\u95f4\u6b65\u957f\u3002\u6211\u4eec\u53d1\u73b0\uff0c\u5bf9\u4e8e\u58f3\u7684\u51e0\u4f55\u5f62\u72b6\uff0c\u6211\u4eec\u9700\u8981\u4e09\u7ef4\u7684\u65f6\u95f4\u6b65\u957f\u6bd4\u4e8c\u7ef4\u7684\u5c0f\u3002\u8fd9\u662f\u56e0\u4e3a\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0c\u5355\u5143\u683c\u7684\u53d8\u5f62\u66f4\u5927\uff08\u51b3\u5b9aCFL\u6570\u503c\u7684\u662f\u6700\u5c0f\u7684\u8fb9\u957f\uff09\u3002\u6211\u4eec\u4e0d\u662f\u50cf step-31 \u4e2d\u90a3\u6837\u4ece\u6700\u5927\u901f\u5ea6\u548c\u6700\u5c0f\u7f51\u683c\u5c3a\u5bf8\u8ba1\u7b97\u65f6\u95f4\u6b65\u957f\uff0c\u800c\u662f\u8ba1\u7b97\u5c40\u90e8\u7684CFL\u6570\uff0c\u5373\u5728\u6bcf\u4e2a\u5355\u5143\u4e0a\u8ba1\u7b97\u6700\u5927\u901f\u5ea6\u4e58\u4ee5\u7f51\u683c\u5c3a\u5bf8\uff0c\u5e76\u8ba1\u7b97\u5b83\u4eec\u7684\u6700\u5927\u503c\u3002\u56e0\u6b64\uff0c\u6211\u4eec\u9700\u8981\u5c06\u65f6\u95f4\u6b65\u957f\u524d\u9762\u7684\u56e0\u5b50\u9009\u62e9\u5f97\u7a0d\u5c0f\u4e00\u4e9b\u3002\n\n// \u5728\u6e29\u5ea6\u7684\u53f3\u624b\u8fb9\u88c5\u914d\u540e\uff0c\u6211\u4eec\u89e3\u51b3\u6e29\u5ea6\u7684\u7ebf\u6027\u7cfb\u7edf\uff08\u6709\u5b8c\u5168\u5206\u5e03\u7684\u5411\u91cf\uff0c\u6ca1\u6709\u4efb\u4f55\u9b3c\u9b42\uff09\uff0c\u5e94\u7528\u7ea6\u675f\u6761\u4ef6\uff0c\u5e76\u5c06\u5411\u91cf\u590d\u5236\u56de\u6709\u9b3c\u9b42\u7684\u5411\u91cf\u3002\n\n// \u6700\u540e\uff0c\u6211\u4eec\u63d0\u53d6\u4e0e step-31 \u7c7b\u4f3c\u7684\u6e29\u5ea6\u8303\u56f4\uff0c\u4ee5\u4ea7\u751f\u4e00\u4e9b\u8f93\u51fa\uff08\u4f8b\u5982\u4e3a\u4e86\u5e2e\u52a9\u6211\u4eec\u9009\u62e9\u7a33\u5b9a\u5e38\u6570\uff0c\u5982\u4ecb\u7ecd\u4e2d\u6240\u8ba8\u8bba\u7684\uff09\u3002\u552f\u4e00\u7684\u533a\u522b\u662f\uff0c\u6211\u4eec\u9700\u8981\u5728\u6240\u6709\u5904\u7406\u5668\u4e0a\u4ea4\u6362\u6700\u5927\u503c\u3002\n\n    { \n      TimerOutput::Scope timer_section(computing_timer, \n                                       \"   Assemble temperature rhs\"); \n\n      old_time_step = time_step; \n\n      const double scaling = (dim == 3 ? 0.25 : 1.0); \n      time_step            = (scaling / (2.1 * dim * std::sqrt(1. * dim)) / \n                   (parameters.temperature_degree * get_cfl_number())); \n\n      const double maximal_velocity = get_maximal_velocity(); \n      pcout << \"   Maximal velocity: \" \n            << maximal_velocity * EquationData::year_in_seconds * 100 \n            << \" cm/year\" << std::endl; \n      pcout << \"   \" \n            << \"Time step: \" << time_step / EquationData::year_in_seconds \n            << \" years\" << std::endl; \n\n      temperature_solution = old_temperature_solution; \n      assemble_temperature_system(maximal_velocity); \n    } \n\n    { \n      TimerOutput::Scope timer_section(computing_timer, \n                                       \"   Solve temperature system\"); \n\n      SolverControl solver_control(temperature_matrix.m(), \n                                   1e-12 * temperature_rhs.l2_norm()); \n      SolverCG<TrilinosWrappers::MPI::Vector> cg(solver_control); \n\n      TrilinosWrappers::MPI::Vector distributed_temperature_solution( \n        temperature_rhs); \n      distributed_temperature_solution = temperature_solution; \n\n      cg.solve(temperature_matrix, \n               distributed_temperature_solution, \n               temperature_rhs, \n               *T_preconditioner); \n\n      temperature_constraints.distribute(distributed_temperature_solution); \n      temperature_solution = distributed_temperature_solution; \n\n      pcout << \"   \" << solver_control.last_step() \n            << \" CG iterations for temperature\" << std::endl; \n\n      double temperature[2] = {std::numeric_limits<double>::max(), \n                               -std::numeric_limits<double>::max()}; \n      double global_temperature[2]; \n\n      for (unsigned int i = \n             distributed_temperature_solution.local_range().first; \n           i < distributed_temperature_solution.local_range().second; \n           ++i) \n        { \n          temperature[0] = \n            std::min<double>(temperature[0], \n                             distributed_temperature_solution(i)); \n          temperature[1] = \n            std::max<double>(temperature[1], \n                             distributed_temperature_solution(i)); \n        } \n\n      temperature[0] *= -1.0; \n      Utilities::MPI::max(temperature, MPI_COMM_WORLD, global_temperature); \n      global_temperature[0] *= -1.0; \n\n      pcout << \"   Temperature range: \" << global_temperature[0] << ' ' \n            << global_temperature[1] << std::endl; \n    } \n  } \n// @sect4{BoussinesqFlowProblem::output_results}  \n\n// \u63a5\u4e0b\u6765\u662f\u751f\u6210\u8f93\u51fa\u7684\u51fd\u6570\u3002\u8f93\u51fa\u7684\u6570\u91cf\u53ef\u4ee5\u50cf\u6211\u4eec\u5728  step-31  \u4e2d\u90a3\u6837\u624b\u52a8\u5f15\u5165\u3002\u53e6\u4e00\u79cd\u65b9\u6cd5\u662f\u628a\u8fd9\u4e2a\u4efb\u52a1\u4ea4\u7ed9\u4e00\u4e2a\u7ee7\u627f\u81eaDataPostprocessor\u7c7b\u7684PostProcessor\uff0c\u5b83\u53ef\u4ee5\u88ab\u9644\u52a0\u5230DataOut\u3002\u8fd9\u5141\u8bb8\u6211\u4eec\u4ece\u89e3\u51b3\u65b9\u6848\u4e2d\u8f93\u51fa\u6d3e\u751f\u91cf\uff0c\u6bd4\u5982\u672c\u4f8b\u4e2d\u5305\u542b\u7684\u6469\u64e6\u70ed\u3002\u5b83\u91cd\u8f7d\u4e86\u865a\u62df\u51fd\u6570 DataPostprocessor::evaluate_vector_field(), \uff0c\u7136\u540e\u4ece DataOut::build_patches(). \u5185\u90e8\u8c03\u7528\u3002 \u6211\u4eec\u5fc5\u987b\u7ed9\u5b83\u6570\u503c\u89e3\u3001\u5b83\u7684\u5bfc\u6570\u3001\u5355\u5143\u7684\u6cd5\u7ebf\u3001\u5b9e\u9645\u8bc4\u4f30\u70b9\u548c\u4efb\u4f55\u989d\u5916\u7684\u6570\u91cf\u3002\u8fd9\u4e0e step-29 \u548c\u5176\u4ed6\u7a0b\u5e8f\u4e2d\u8ba8\u8bba\u7684\u7a0b\u5e8f\u76f8\u540c\u3002\n\n  template <int dim> \n  class BoussinesqFlowProblem<dim>::Postprocessor \n    : public DataPostprocessor<dim> \n  { \n  public: \n    Postprocessor(const unsigned int partition, const double minimal_pressure); \n\n    virtual void evaluate_vector_field( \n      const DataPostprocessorInputs::Vector<dim> &inputs, \n      std::vector<Vector<double>> &computed_quantities) const override; \n\n    virtual std::vector<std::string> get_names() const override; \n\n    virtual std::vector< \n      DataComponentInterpretation::DataComponentInterpretation> \n    get_data_component_interpretation() const override; \n\n    virtual UpdateFlags get_needed_update_flags() const override; \n\n  private: \n    const unsigned int partition; \n    const double       minimal_pressure; \n  }; \n\n  template <int dim> \n  BoussinesqFlowProblem<dim>::Postprocessor::Postprocessor( \n    const unsigned int partition, \n    const double       minimal_pressure) \n    : partition(partition) \n    , minimal_pressure(minimal_pressure) \n  {} \n\n// \u8fd9\u91cc\u6211\u4eec\u5b9a\u4e49\u4e86\u8981\u8f93\u51fa\u7684\u53d8\u91cf\u7684\u540d\u79f0\u3002\u8fd9\u4e9b\u662f\u901f\u5ea6\u3001\u538b\u529b\u548c\u6e29\u5ea6\u7684\u5b9e\u9645\u6c42\u89e3\u503c\uff0c\u4ee5\u53ca\u6469\u64e6\u70ed\u548c\u5bf9\u6bcf\u4e2a\u5355\u5143\u62e5\u6709\u7684\u5904\u7406\u5668\u7684\u7f16\u53f7\u3002\u8fd9\u4f7f\u6211\u4eec\u80fd\u591f\u76f4\u89c2\u5730\u770b\u5230\u5904\u7406\u5668\u4e4b\u95f4\u7684\u9886\u57df\u5212\u5206\u3002\u9664\u4e86\u901f\u5ea6\u662f\u77e2\u91cf\u503c\u7684\uff0c\u5176\u4ed6\u7684\u91cf\u90fd\u662f\u6807\u91cf\u3002\n\n  template <int dim> \n  std::vector<std::string> \n  BoussinesqFlowProblem<dim>::Postprocessor::get_names() const \n  { \n    std::vector<std::string> solution_names(dim, \"velocity\"); \n    solution_names.emplace_back(\"p\"); \n    solution_names.emplace_back(\"T\"); \n    solution_names.emplace_back(\"friction_heating\"); \n    solution_names.emplace_back(\"partition\"); \n\n    return solution_names; \n  } \n\n  template <int dim> \n  std::vector<DataComponentInterpretation::DataComponentInterpretation> \n  BoussinesqFlowProblem<dim>::Postprocessor::get_data_component_interpretation() \n    const \n  { \n    std::vector<DataComponentInterpretation::DataComponentInterpretation> \n      interpretation(dim, \n                     DataComponentInterpretation::component_is_part_of_vector); \n\n    interpretation.push_back(DataComponentInterpretation::component_is_scalar); \n    interpretation.push_back(DataComponentInterpretation::component_is_scalar); \n    interpretation.push_back(DataComponentInterpretation::component_is_scalar); \n    interpretation.push_back(DataComponentInterpretation::component_is_scalar); \n\n    return interpretation; \n  } \n\n  template <int dim> \n  UpdateFlags \n  BoussinesqFlowProblem<dim>::Postprocessor::get_needed_update_flags() const \n  { \n    return update_values | update_gradients | update_quadrature_points; \n  } \n\n// \u73b0\u5728\u6211\u4eec\u5b9e\u73b0\u8ba1\u7b97\u6d3e\u751f\u91cf\u7684\u51fd\u6570\u3002\u6b63\u5982\u6211\u4eec\u5bf9\u8f93\u51fa\u6240\u505a\u7684\u90a3\u6837\uff0c\u6211\u4eec\u5c06\u901f\u5ea6\u4ece\u5176SI\u5355\u4f4d\u91cd\u65b0\u8c03\u6574\u4e3a\u66f4\u5bb9\u6613\u9605\u8bfb\u7684\u5355\u4f4d\uff0c\u5373\u5398\u7c73/\u5e74\u3002\u63a5\u4e0b\u6765\uff0c\u538b\u529b\u88ab\u7f29\u653e\u4e3a0\u548c\u6700\u5927\u538b\u529b\u4e4b\u95f4\u3002\u8fd9\u4f7f\u5f97\u5b83\u66f4\u5bb9\u6613\u6bd4\u8f83--\u672c\u8d28\u4e0a\u662f\u4f7f\u6240\u6709\u7684\u538b\u529b\u53d8\u91cf\u53d8\u6210\u6b63\u6570\u6216\u96f6\u3002\u6e29\u5ea6\u6309\u539f\u6837\u8ba1\u7b97\uff0c\u6469\u64e6\u70ed\u6309  $2 \\eta \\varepsilon(\\mathbf{u}) \\cdot \\varepsilon(\\mathbf{u})$  \u8ba1\u7b97\u3002\n\n// \u6211\u4eec\u5728\u8fd9\u91cc\u8f93\u51fa\u7684\u6570\u91cf\u66f4\u591a\u7684\u662f\u4e3a\u4e86\u8bf4\u660e\u95ee\u9898\uff0c\u800c\u4e0d\u662f\u4e3a\u4e86\u5b9e\u9645\u7684\u79d1\u5b66\u4ef7\u503c\u3002\u6211\u4eec\u5728\u672c\u7a0b\u5e8f\u7684\u7ed3\u679c\u90e8\u5206\u7b80\u8981\u5730\u56de\u5230\u8fd9\u4e00\u70b9\uff0c\u5e76\u89e3\u91ca\u4eba\u4eec\u5b9e\u9645\u4e0a\u53ef\u80fd\u611f\u5174\u8da3\u7684\u662f\u4ec0\u4e48\u3002\n\n  template <int dim> \n  void BoussinesqFlowProblem<dim>::Postprocessor::evaluate_vector_field( \n    const DataPostprocessorInputs::Vector<dim> &inputs, \n    std::vector<Vector<double>> &               computed_quantities) const \n  { \n    const unsigned int n_quadrature_points = inputs.solution_values.size(); \n    Assert(inputs.solution_gradients.size() == n_quadrature_points, \n           ExcInternalError()); \n    Assert(computed_quantities.size() == n_quadrature_points, \n           ExcInternalError()); \n    Assert(inputs.solution_values[0].size() == dim + 2, ExcInternalError()); \n\n    for (unsigned int q = 0; q < n_quadrature_points; ++q) \n      { \n        for (unsigned int d = 0; d < dim; ++d) \n          computed_quantities[q](d) = (inputs.solution_values[q](d) * \n                                       EquationData::year_in_seconds * 100); \n\n        const double pressure = \n          (inputs.solution_values[q](dim) - minimal_pressure); \n        computed_quantities[q](dim) = pressure; \n\n        const double temperature        = inputs.solution_values[q](dim + 1); \n        computed_quantities[q](dim + 1) = temperature; \n\n        Tensor<2, dim> grad_u; \n        for (unsigned int d = 0; d < dim; ++d) \n          grad_u[d] = inputs.solution_gradients[q][d]; \n        const SymmetricTensor<2, dim> strain_rate = symmetrize(grad_u); \n        computed_quantities[q](dim + 2) = \n          2 * EquationData::eta * strain_rate * strain_rate; \n\n        computed_quantities[q](dim + 3) = partition; \n      } \n  } \n\n//  <code>output_results()</code> \u51fd\u6570\u7684\u4efb\u52a1\u4e0e step-31 \u4e2d\u7684\u7c7b\u4f3c\u3002\u7136\u800c\uff0c\u5728\u8fd9\u91cc\u6211\u4eec\u5c06\u6f14\u793a\u4e00\u79cd\u4e0d\u540c\u7684\u6280\u672f\uff0c\u5373\u5982\u4f55\u5408\u5e76\u6765\u81ea\u4e0d\u540cDoFHandler\u5bf9\u8c61\u7684\u8f93\u51fa\u3002\u6211\u4eec\u8981\u5b9e\u73b0\u8fd9\u79cd\u91cd\u7ec4\u7684\u65b9\u6cd5\u662f\u521b\u5efa\u4e00\u4e2a\u8054\u5408\u7684DoFHandler\uff0c\u6536\u96c6\u4e24\u4e2a\u90e8\u5206\uff0c\u65af\u6258\u514b\u65af\u89e3\u548c\u6e29\u5ea6\u89e3\u3002\u8fd9\u53ef\u4ee5\u901a\u8fc7\u5c06\u4e24\u4e2a\u7cfb\u7edf\u7684\u6709\u9650\u5143\u7ed3\u5408\u8d77\u6765\u5f62\u6210\u4e00\u4e2aFES\u7cfb\u7edf\u6765\u5f88\u597d\u5730\u5b8c\u6210\uff0c\u5e76\u8ba9\u8fd9\u4e2a\u96c6\u4f53\u7cfb\u7edf\u5b9a\u4e49\u4e00\u4e2a\u65b0\u7684DoFHandler\u5bf9\u8c61\u3002\u4e3a\u4e86\u786e\u4fdd\u4e00\u5207\u90fd\u505a\u5f97\u5f88\u6b63\u786e\uff0c\u6211\u4eec\u8fdb\u884c\u4e86\u4e00\u6b21\u7406\u667a\u7684\u68c0\u67e5\uff0c\u786e\u4fdd\u6211\u4eec\u4ece\u65af\u6258\u514b\u65af\u548c\u6e29\u5ea6\u4e24\u4e2a\u7cfb\u7edf\u4e2d\u5f97\u5230\u4e86\u6240\u6709\u7684\u9053\u592b\uff0c\u751a\u81f3\u662f\u5728\u7ec4\u5408\u7cfb\u7edf\u4e2d\u3002\u7136\u540e\u6211\u4eec\u5c06\u6570\u636e\u5411\u91cf\u5408\u5e76\u3002\u4e0d\u5e78\u7684\u662f\uff0c\u6ca1\u6709\u76f4\u63a5\u7684\u5173\u7cfb\u544a\u8bc9\u6211\u4eec\u5982\u4f55\u5c06\u65af\u6258\u514b\u65af\u548c\u6e29\u5ea6\u77e2\u91cf\u5206\u7c7b\u5230\u8054\u5408\u77e2\u91cf\u4e2d\u3002\u6211\u4eec\u53ef\u4ee5\u7ed5\u8fc7\u8fd9\u4e2a\u9ebb\u70e6\u7684\u65b9\u6cd5\u662f\u4f9d\u9760FES\u7cfb\u7edf\u4e2d\u6536\u96c6\u7684\u4fe1\u606f\u3002\u5bf9\u4e8e\u4e00\u4e2a\u5355\u5143\u4e0a\u7684\u6bcf\u4e2adof\uff0c\u8054\u5408\u6709\u9650\u5143\u77e5\u9053\u5b83\u5c5e\u4e8e\u54ea\u4e2a\u65b9\u7a0b\u5206\u91cf\uff08\u901f\u5ea6\u5206\u91cf\u3001\u538b\u529b\u6216\u6e29\u5ea6\uff09--\u8fd9\u5c31\u662f\u6211\u4eec\u6240\u9700\u8981\u7684\u4fe1\u606f\uff01\u8fd9\u5c31\u662f\u6211\u4eec\u6240\u9700\u8981\u7684\u3002\u56e0\u6b64\uff0c\u6211\u4eec\u901a\u8fc7\u6240\u6709\u5355\u5143\uff08\u8fed\u4ee3\u5668\u8fdb\u5165\u6240\u6709\u4e09\u4e2aDoFHandlers\u540c\u6b65\u79fb\u52a8\uff09\uff0c\u5bf9\u4e8e\u6bcf\u4e2a\u8054\u5408\u5355\u5143dof\uff0c\u6211\u4eec\u4f7f\u7528 FiniteElement::system_to_base_index \u51fd\u6570\u8bfb\u51fa\u8be5\u5206\u91cf\uff08\u5173\u4e8e\u5176\u8fd4\u56de\u503c\u7684\u5404\u4e2a\u90e8\u5206\u7684\u63cf\u8ff0\u89c1\u90a3\u91cc\uff09\u3002\u6211\u4eec\u8fd8\u9700\u8981\u8ddf\u8e2a\u6211\u4eec\u662f\u5728\u65af\u6258\u514b\u65af\u9053\u6b21\u8fd8\u662f\u6e29\u5ea6\u9053\u6b21\uff0c\u8fd9\u5305\u542b\u5728joint_fe.system_to_base_index(i).first.first\u4e2d\u3002\u6700\u7ec8\uff0c\u4e09\u4e2a\u7cfb\u7edf\u4e2d\u7684\u4efb\u4f55\u4e00\u4e2a\u7cfb\u7edf\u7684dof_indices\u6570\u636e\u7ed3\u6784\u90fd\u4f1a\u544a\u8bc9\u6211\u4eec\u5168\u5c40\u77e2\u91cf\u548c\u5c40\u90e8dof\u4e4b\u95f4\u7684\u5173\u7cfb\u5728\u5f53\u524d\u5355\u5143\u4e0a\u662f\u600e\u6837\u7684\uff0c\u8fd9\u5c31\u7ed3\u675f\u4e86\u8fd9\u9879\u7e41\u7410\u7684\u5de5\u4f5c\u3002\u6211\u4eec\u786e\u4fdd\u6bcf\u4e2a\u5904\u7406\u5668\u5728\u5efa\u7acb\u8054\u5408\u6c42\u89e3\u5411\u91cf\u65f6\uff0c\u53ea\u5728\u5176\u672c\u5730\u62e5\u6709\u7684\u5b50\u57df\u4e0a\u5de5\u4f5c\uff08\u800c\u4e0d\u662f\u5728\u5e7d\u7075\u6216\u4eba\u5de5\u5355\u5143\u4e0a\uff09\u3002\u7136\u540e\u5728 DataOut::build_patches(), \u4e2d\u4e5f\u8981\u8fd9\u6837\u505a\uff0c\u4f46\u8be5\u51fd\u6570\u4f1a\u81ea\u52a8\u8fd9\u6837\u505a\u3002\n\n// \u6211\u4eec\u6700\u7ec8\u5f97\u5230\u7684\u662f\u4e00\u7ec4\u8865\u4e01\uff0c\u6211\u4eec\u53ef\u4ee5\u4f7f\u7528DataOutBase\u4e2d\u7684\u51fd\u6570\u4ee5\u5404\u79cd\u8f93\u51fa\u683c\u5f0f\u7f16\u5199\u8865\u4e01\u3002\u5728\u8fd9\u91cc\uff0c\u6211\u4eec\u5fc5\u987b\u6ce8\u610f\uff0c\u6bcf\u4e2a\u5904\u7406\u5668\u6240\u5199\u7684\u5b9e\u9645\u4e0a\u53ea\u662f\u5b83\u81ea\u5df1\u9886\u57df\u7684\u4e00\u90e8\u5206\uff0c\u4e5f\u5c31\u662f\u8bf4\uff0c\u6211\u4eec\u8981\u628a\u6bcf\u4e2a\u5904\u7406\u5668\u7684\u8d21\u732e\u5199\u8fdb\u4e00\u4e2a\u5355\u72ec\u7684\u6587\u4ef6\u3002\u6211\u4eec\u901a\u8fc7\u5728\u5199\u89e3\u51b3\u65b9\u6848\u65f6\u7ed9\u6587\u4ef6\u540d\u6dfb\u52a0\u4e00\u4e2a\u989d\u5916\u7684\u6570\u5b57\u6765\u505a\u5230\u8fd9\u4e00\u70b9\u3002\u8fd9\u5176\u5b9e\u5e76\u4e0d\u65b0\u9c9c\uff0c\u6211\u4eec\u5728  step-40  \u4e2d\u4e5f\u662f\u8fd9\u6837\u505a\u7684\u3002\u6ce8\u610f\uff0c\u6211\u4eec\u7528\u538b\u7f29\u683c\u5f0f @p .vtu \u800c\u4e0d\u662f\u666e\u901a\u7684vtk\u6587\u4ef6\u6765\u5199\uff0c\u8fd9\u6837\u53ef\u4ee5\u8282\u7701\u4e0d\u5c11\u5b58\u50a8\u7a7a\u95f4\u3002\n\n// \u6240\u6709\u5176\u4f59\u7684\u5de5\u4f5c\u90fd\u5728\u540e\u5904\u7406\u7a0b\u5e8f\u7c7b\u4e2d\u5b8c\u6210\u3002\n\n  template <int dim> \n  void BoussinesqFlowProblem<dim>::output_results() \n  { \n    TimerOutput::Scope timer_section(computing_timer, \"Postprocessing\"); \n\n    const FESystem<dim> joint_fe(stokes_fe, 1, temperature_fe, 1); \n\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    TrilinosWrappers::MPI::Vector joint_solution; \n    joint_solution.reinit(joint_dof_handler.locally_owned_dofs(), \n                          MPI_COMM_WORLD); \n\n    { \n      std::vector<types::global_dof_index> local_joint_dof_indices( \n        joint_fe.n_dofs_per_cell()); \n      std::vector<types::global_dof_index> local_stokes_dof_indices( \n        stokes_fe.n_dofs_per_cell()); \n      std::vector<types::global_dof_index> local_temperature_dof_indices( \n        temperature_fe.n_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; \n           ++joint_cell, ++stokes_cell, ++temperature_cell) \n        if (joint_cell->is_locally_owned()) \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.n_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                           local_stokes_dof_indices.size(), \n                         ExcInternalError()); \n\n                  joint_solution(local_joint_dof_indices[i]) = stokes_solution( \n                    local_stokes_dof_indices[joint_fe.system_to_base_index(i) \n                                               .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                           local_temperature_dof_indices.size(), \n                         ExcInternalError()); \n                  joint_solution(local_joint_dof_indices[i]) = \n                    temperature_solution( \n                      local_temperature_dof_indices \n                        [joint_fe.system_to_base_index(i).second]); \n                } \n          } \n    } \n\n    joint_solution.compress(VectorOperation::insert); \n\n    IndexSet locally_relevant_joint_dofs(joint_dof_handler.n_dofs()); \n    DoFTools::extract_locally_relevant_dofs(joint_dof_handler, \n                                            locally_relevant_joint_dofs); \n    TrilinosWrappers::MPI::Vector locally_relevant_joint_solution; \n    locally_relevant_joint_solution.reinit(locally_relevant_joint_dofs, \n                                           MPI_COMM_WORLD); \n    locally_relevant_joint_solution = joint_solution; \n\n    Postprocessor postprocessor(Utilities::MPI::this_mpi_process( \n                                  MPI_COMM_WORLD), \n                                stokes_solution.block(1).min()); \n\n    DataOut<dim> data_out; \n    data_out.attach_dof_handler(joint_dof_handler); \n    data_out.add_data_vector(locally_relevant_joint_solution, postprocessor); \n    data_out.build_patches(); \n\n    static int out_index = 0; \n    data_out.write_vtu_with_pvtu_record( \n      \"./\", \"solution\", out_index, MPI_COMM_WORLD, 5); \n\n    out_index++; \n  } \n\n//  @sect4{BoussinesqFlowProblem::refine_mesh}  \n\n// \u8fd9\u4e2a\u51fd\u6570\u4e5f\u4e0d\u662f\u771f\u6b63\u7684\u65b0\u51fd\u6570\u3002\u56e0\u4e3a\u6211\u4eec\u5728\u4e2d\u95f4\u8c03\u7528\u7684 <code>setup_dofs</code> \u51fd\u6570\u6709\u81ea\u5df1\u7684\u5b9a\u65f6\u5668\u90e8\u5206\uff0c\u6240\u4ee5\u6211\u4eec\u628a\u8fd9\u4e2a\u51fd\u6570\u7684\u5b9a\u65f6\u5206\u6210\u4e24\u90e8\u5206\u3002\u8fd9\u4e5f\u53ef\u4ee5\u8ba9\u6211\u4eec\u5f88\u5bb9\u6613\u5730\u8bc6\u522b\u51fa\u8fd9\u4e24\u4e2a\u4e2d\u54ea\u4e2a\u66f4\u6602\u8d35\u3002\n//\u4f46\u662f\uff0c\n//\u6709\u4e00\u70b9\u9700\u8981\u6ce8\u610f\u7684\u662f\uff0c\u6211\u4eec\u53ea\u60f3\u5728\u672c\u5730\u62e5\u6709\u7684\u5b50\u57df\u4e0a\u8ba1\u7b97\u9519\u8bef\u6307\u6807\u3002\u4e3a\u4e86\u8fbe\u5230\u8fd9\u4e2a\u76ee\u7684\uff0c\u6211\u4eec\u5411 KellyErrorEstimator::estimate \u51fd\u6570\u4f20\u9012\u4e00\u4e2a\u989d\u5916\u7684\u53c2\u6570\u3002\u8bf7\u6ce8\u610f\uff0c\u7528\u4e8e\u8bef\u5dee\u4f30\u8ba1\u7684\u5411\u91cf\u88ab\u8c03\u6574\u4e3a\u5f53\u524d\u8fdb\u7a0b\u4e0a\u5b58\u5728\u7684\u6d3b\u52a8\u5355\u5143\u7684\u6570\u91cf\uff0c\u5b83\u5c0f\u4e8e\u6240\u6709\u5904\u7406\u5668\u4e0a\u6d3b\u52a8\u5355\u5143\u7684\u603b\u6570\uff08\u4f46\u5927\u4e8e\u672c\u5730\u62e5\u6709\u7684\u6d3b\u52a8\u5355\u5143\u7684\u6570\u91cf\uff09\uff1b\u6bcf\u4e2a\u5904\u7406\u5668\u53ea\u6709\u672c\u5730\u62e5\u6709\u7684\u5355\u5143\u5468\u56f4\u6709\u4e00\u4e9b\u7c97\u7565\u7684\u5355\u5143\uff0c\u8fd9\u5728  step-40  \u4e2d\u4e5f\u6709\u89e3\u91ca\u3002\n\n// \u672c\u5730\u8bef\u5dee\u4f30\u8ba1\u503c\u7136\u540e\u88ab\u4ea4\u7ed9GridRefinement\u7684%\u5e76\u884c\u7248\u672c\uff08\u5728\u547d\u540d\u7a7a\u95f4 parallel::distributed::GridRefinement, \u4e2d\uff0c\u4e5f\u89c1 step-40 \uff09\uff0c\u5b83\u67e5\u770b\u8bef\u5dee\u5e76\u901a\u8fc7\u6bd4\u8f83\u5404\u5904\u7406\u5668\u7684\u8bef\u5dee\u503c\u627e\u5230\u9700\u8981\u7ec6\u5316\u7684\u5355\u5143\u3002\u6b63\u5982\u5728 step-31 \u4e2d\uff0c\u6211\u4eec\u5e0c\u671b\u9650\u5236\u6700\u5927\u7684\u7f51\u683c\u7ea7\u522b\u3002\u56e0\u6b64\uff0c\u4e07\u4e00\u6709\u4e9b\u5355\u5143\u683c\u5df2\u7ecf\u88ab\u6807\u8bb0\u4e3a\u6700\u7cbe\u7ec6\u7684\u7ea7\u522b\uff0c\u6211\u4eec\u53ea\u9700\u6e05\u9664\u7ec6\u5316\u6807\u5fd7\u3002\n\n  template <int dim> \n  void \n  BoussinesqFlowProblem<dim>::refine_mesh(const unsigned int max_grid_level) \n  { \n    parallel::distributed::SolutionTransfer<dim, TrilinosWrappers::MPI::Vector> \n      temperature_trans(temperature_dof_handler); \n    parallel::distributed::SolutionTransfer<dim, \n                                            TrilinosWrappers::MPI::BlockVector> \n      stokes_trans(stokes_dof_handler); \n\n    { \n      TimerOutput::Scope timer_section(computing_timer, \n                                       \"Refine mesh structure, part 1\"); \n\n      Vector<float> estimated_error_per_cell(triangulation.n_active_cells()); \n\n      KellyErrorEstimator<dim>::estimate( \n        temperature_dof_handler, \n        QGauss<dim - 1>(parameters.temperature_degree + 1), \n        std::map<types::boundary_id, const Function<dim> *>(), \n        temperature_solution, \n        estimated_error_per_cell, \n        ComponentMask(), \n        nullptr, \n        0, \n        triangulation.locally_owned_subdomain()); \n\n      parallel::distributed::GridRefinement::refine_and_coarsen_fixed_fraction( \n        triangulation, estimated_error_per_cell, 0.3, 0.1); \n\n      if (triangulation.n_levels() > max_grid_level) \n        for (typename Triangulation<dim>::active_cell_iterator cell = \n               triangulation.begin_active(max_grid_level); \n             cell != triangulation.end(); \n             ++cell) \n          cell->clear_refine_flag(); \n\n// \u6709\u4e86\u6240\u6709\u7684\u6807\u8bb0\uff0c\u6211\u4eec\u5c31\u53ef\u4ee5\u544a\u8bc9 parallel::distributed::SolutionTransfer \u5bf9\u8c61\u51c6\u5907\u5c06\u6570\u636e\u4ece\u4e00\u4e2a\u7f51\u683c\u8f6c\u79fb\u5230\u4e0b\u4e00\u4e2a\u7f51\u683c\uff0c\u5f53Triangulation\u4f5c\u4e3a @p execute_coarsening_and_refinement() \u8c03\u7528\u7684\u4e00\u90e8\u5206\u901a\u77e5\u4ed6\u4eec\u65f6\uff0c\u4ed6\u4eec\u5c31\u4f1a\u8fd9\u6837\u505a\u3002\u8bed\u6cd5\u7c7b\u4f3c\u4e8e\u975e%\u5e76\u884c\u89e3\u51b3\u65b9\u6848\u7684\u4f20\u8f93\uff08\u4f8b\u5916\u7684\u662f\u8fd9\u91cc\u6709\u4e00\u4e2a\u6307\u5411\u5411\u91cf\u9879\u7684\u6307\u9488\u5c31\u8db3\u591f\u4e86\uff09\u3002\u4e0b\u9762\u51fd\u6570\u7684\u5176\u4f59\u90e8\u5206\u662f\u5728\u7f51\u683c\u7ec6\u5316\u540e\u518d\u6b21\u8bbe\u7f6e\u6570\u636e\u7ed3\u6784\uff0c\u5e76\u5728\u65b0\u7684\u7f51\u683c\u4e0a\u6062\u590d\u6c42\u89e3\u5411\u91cf\u3002\n\n      std::vector<const TrilinosWrappers::MPI::Vector *> x_temperature(2); \n      x_temperature[0] = &temperature_solution; \n      x_temperature[1] = &old_temperature_solution; \n      std::vector<const TrilinosWrappers::MPI::BlockVector *> x_stokes(2); \n      x_stokes[0] = &stokes_solution; \n      x_stokes[1] = &old_stokes_solution; \n\n      triangulation.prepare_coarsening_and_refinement(); \n\n      temperature_trans.prepare_for_coarsening_and_refinement(x_temperature); \n      stokes_trans.prepare_for_coarsening_and_refinement(x_stokes); \n\n      triangulation.execute_coarsening_and_refinement(); \n    } \n\n    setup_dofs(); \n\n    { \n      TimerOutput::Scope timer_section(computing_timer, \n                                       \"Refine mesh structure, part 2\"); \n\n      { \n        TrilinosWrappers::MPI::Vector distributed_temp1(temperature_rhs); \n        TrilinosWrappers::MPI::Vector distributed_temp2(temperature_rhs); \n\n        std::vector<TrilinosWrappers::MPI::Vector *> tmp(2); \n        tmp[0] = &(distributed_temp1); \n        tmp[1] = &(distributed_temp2); \n        temperature_trans.interpolate(tmp); \n\n// \u5f3a\u5236\u6267\u884c\u7ea6\u675f\u6761\u4ef6\uff0c\u4f7f\u63d2\u503c\u540e\u7684\u89e3\u51b3\u65b9\u6848\u5728\u65b0\u7684\u7f51\u683c\u4e0a\u7b26\u5408\u8981\u6c42\u3002\n\n        temperature_constraints.distribute(distributed_temp1); \n        temperature_constraints.distribute(distributed_temp2); \n\n        temperature_solution     = distributed_temp1; \n        old_temperature_solution = distributed_temp2; \n      } \n\n      { \n        TrilinosWrappers::MPI::BlockVector distributed_stokes(stokes_rhs); \n        TrilinosWrappers::MPI::BlockVector old_distributed_stokes(stokes_rhs); \n\n        std::vector<TrilinosWrappers::MPI::BlockVector *> stokes_tmp(2); \n        stokes_tmp[0] = &(distributed_stokes); \n        stokes_tmp[1] = &(old_distributed_stokes); \n\n        stokes_trans.interpolate(stokes_tmp); \n\n// \u5f3a\u5236\u6267\u884c\u7ea6\u675f\u6761\u4ef6\uff0c\u4f7f\u63d2\u503c\u540e\u7684\u89e3\u51b3\u65b9\u6848\u5728\u65b0\u7684\u7f51\u683c\u4e0a\u7b26\u5408\u8981\u6c42\u3002\n\n        stokes_constraints.distribute(distributed_stokes); \n        stokes_constraints.distribute(old_distributed_stokes); \n\n        stokes_solution     = distributed_stokes; \n        old_stokes_solution = old_distributed_stokes; \n      } \n    } \n  } \n\n//  @sect4{BoussinesqFlowProblem::run}  \n\n// \u8fd9\u662f\u8fd9\u4e2a\u7c7b\u4e2d\u7684\u6700\u540e\u4e00\u4e2a\u63a7\u5236\u51fd\u6570\u3002\u4e8b\u5b9e\u4e0a\uff0c\u5b83\u8fd0\u884c\u4e86\u6574\u4e2a\u7a0b\u5e8f\u7684\u5176\u4f59\u90e8\u5206\uff0c\u5e76\u4e14\u518d\u6b21\u4e0e  step-31  \u975e\u5e38\u76f8\u4f3c\u3002\u552f\u4e00\u7684\u5b9e\u8d28\u6027\u533a\u522b\u662f\u6211\u4eec\u73b0\u5728\u4f7f\u7528\u4e86\u4e00\u4e2a\u4e0d\u540c\u7684\u7f51\u683c\uff08\u4e00\u4e2a GridGenerator::hyper_shell \u800c\u4e0d\u662f\u4e00\u4e2a\u7b80\u5355\u7684\u7acb\u65b9\u4f53\u51e0\u4f55\uff09\u3002\n\n  template <int dim> \n  void BoussinesqFlowProblem<dim>::run() \n  { \n    GridGenerator::hyper_shell(triangulation, \n                               Point<dim>(), \n                               EquationData::R0, \n                               EquationData::R1, \n                               (dim == 3) ? 96 : 12, \n                               true); \n\n    global_Omega_diameter = GridTools::diameter(triangulation); \n\n    triangulation.refine_global(parameters.initial_global_refinement); \n\n    setup_dofs(); \n\n    unsigned int pre_refinement_step = 0; \n\n  start_time_iteration: \n\n    { \n      TrilinosWrappers::MPI::Vector solution( \n        temperature_dof_handler.locally_owned_dofs()); \n// VectorTools::project \u901a\u8fc7deal.II\u81ea\u5df1\u7684\u672c\u5730MatrixFree\u6846\u67b6\u652f\u6301\u5177\u6709\u5927\u591a\u6570\u6807\u51c6\u6709\u9650\u5143\u7d20\u7684\u5e76\u884c\u77e2\u91cf\u7c7b\uff1a\u7531\u4e8e\u6211\u4eec\u4f7f\u7528\u4e2d\u7b49\u9636\u6570\u7684\u6807\u51c6\u62c9\u683c\u6717\u65e5\u5143\u7d20\uff0c\u8fd9\u4e2a\u51fd\u6570\u5728\u8fd9\u91cc\u5de5\u4f5c\u5f97\u5f88\u597d\u3002\n\n      VectorTools::project(temperature_dof_handler, \n                           temperature_constraints, \n                           QGauss<dim>(parameters.temperature_degree + 2), \n                           EquationData::TemperatureInitialValues<dim>(), \n                           solution); \n\n// \u5728\u5982\u6b64\u8ba1\u7b97\u4e86\u5f53\u524d\u7684\u6e29\u5ea6\u5b57\u6bb5\u4e4b\u540e\uff0c\u8ba9\u6211\u4eec\u8bbe\u7f6e\u4fdd\u5b58\u6e29\u5ea6\u8282\u70b9\u7684\u6210\u5458\u53d8\u91cf\u3002\u4e25\u683c\u6765\u8bf4\uff0c\u6211\u4eec\u771f\u7684\u53ea\u9700\u8981\u8bbe\u7f6e <code>old_temperature_solution</code> \uff0c\u56e0\u4e3a\u6211\u4eec\u8981\u505a\u7684\u7b2c\u4e00\u4ef6\u4e8b\u662f\u8ba1\u7b97\u65af\u6258\u514b\u65af\u89e3\uff0c\u5b83\u53ea\u9700\u8981\u524d\u4e00\u4e2a\u65f6\u95f4\u6b65\u957f\u7684\u6e29\u5ea6\u573a\u3002\u5c3d\u7ba1\u5982\u6b64\uff0c\u5982\u679c\u6211\u4eec\u60f3\u6269\u5c55\u6211\u4eec\u7684\u6570\u503c\u65b9\u6cd5\u6216\u7269\u7406\u6a21\u578b\uff0c\u4e0d\u521d\u59cb\u5316\u5176\u4ed6\u7684\u5411\u91cf\u4e5f\u4e0d\u4f1a\u6709\u4ec0\u4e48\u597d\u5904\uff08\u7279\u522b\u662f\u8fd9\u662f\u4e00\u4e2a\u76f8\u5bf9\u4fbf\u5b9c\u7684\u64cd\u4f5c\uff0c\u6211\u4eec\u53ea\u9700\u8981\u5728\u7a0b\u5e8f\u5f00\u59cb\u65f6\u505a\u4e00\u6b21\uff09\uff0c\u6240\u4ee5\u6211\u4eec\u4e5f\u521d\u59cb\u5316 <code>old_temperature_solution</code> \u548c <code>old_old_temperature_solution</code> \u3002\u8fd9\u4e2a\u8d4b\u503c\u786e\u4fdd\u4e86\u5de6\u8fb9\u7684\u5411\u91cf\uff08\u521d\u59cb\u5316\u540e\u4e5f\u5305\u542b\u9b3c\u9b42\u5143\u7d20\uff09\u4e5f\u5f97\u5230\u4e86\u6b63\u786e\u7684\u9b3c\u9b42\u5143\u7d20\u3002\u6362\u53e5\u8bdd\u8bf4\uff0c\u8fd9\u91cc\u7684\u8d4b\u503c\u9700\u8981\u5904\u7406\u5668\u4e4b\u95f4\u7684\u901a\u4fe1\u3002\n\n      temperature_solution         = solution; \n      old_temperature_solution     = solution; \n      old_old_temperature_solution = solution; \n    } \n\n    timestep_number = 0; \n    time_step = old_time_step = 0; \n\n    double time = 0; \n\n    do \n      { \n        pcout << \"Timestep \" << timestep_number \n              << \":  t=\" << time / EquationData::year_in_seconds << \" years\" \n              << std::endl; \n\n        assemble_stokes_system(); \n        build_stokes_preconditioner(); \n        assemble_temperature_matrix(); \n\n        solve(); \n\n        pcout << std::endl; \n\n        if ((timestep_number == 0) && \n            (pre_refinement_step < parameters.initial_adaptive_refinement)) \n          { \n            refine_mesh(parameters.initial_global_refinement + \n                        parameters.initial_adaptive_refinement); \n            ++pre_refinement_step; \n            goto start_time_iteration; \n          } \n        else if ((timestep_number > 0) && \n                 (timestep_number % parameters.adaptive_refinement_interval == \n                  0)) \n          refine_mesh(parameters.initial_global_refinement + \n                      parameters.initial_adaptive_refinement); \n\n        if ((parameters.generate_graphical_output == true) && \n            (timestep_number % parameters.graphical_output_interval == 0)) \n          output_results(); \n\n// \u4e3a\u4e86\u52a0\u5feb\u7ebf\u6027\u6c42\u89e3\u5668\u7684\u901f\u5ea6\uff0c\u6211\u4eec\u4ece\u65e7\u7684\u65f6\u95f4\u6c34\u5e73\u4e0a\u63a8\u65ad\u51fa\u65b0\u7684\u89e3\u51b3\u65b9\u6848\u3002\u8fd9\u53ef\u4ee5\u63d0\u4f9b\u4e00\u4e2a\u975e\u5e38\u597d\u7684\u521d\u59cb\u731c\u6d4b\uff0c\u4f7f\u6c42\u89e3\u5668\u6240\u9700\u7684\u8fed\u4ee3\u6b21\u6570\u51cf\u5c11\u4e00\u534a\u4ee5\u4e0a\u3002\u6211\u4eec\u4e0d\u9700\u8981\u5728\u6700\u540e\u4e00\u6b21\u8fed\u4ee3\u4e2d\u8fdb\u884c\u63a8\u65ad\uff0c\u6240\u4ee5\u5982\u679c\u6211\u4eec\u8fbe\u5230\u4e86\u6700\u540e\u7684\u65f6\u95f4\uff0c\u6211\u4eec\u5c31\u5728\u8fd9\u91cc\u505c\u6b62\u3002\n\n// \u4f5c\u4e3a\u4e00\u4e2a\u65f6\u95f4\u6b65\u957f\u7684\u6700\u540e\u4e00\u4ef6\u4e8b\uff08\u5728\u5b9e\u9645\u63d0\u9ad8\u65f6\u95f4\u6b65\u957f\u4e4b\u524d\uff09\uff0c\u6211\u4eec\u68c0\u67e5\u5f53\u524d\u7684\u65f6\u95f4\u6b65\u957f\u662f\u5426\u88ab100\u6574\u9664\uff0c\u5982\u679c\u662f\u7684\u8bdd\uff0c\u6211\u4eec\u8ba9\u8ba1\u7b97\u8ba1\u65f6\u5668\u6253\u5370\u4e00\u4e2a\u5230\u76ee\u524d\u4e3a\u6b62\u6240\u82b1\u8d39\u7684CPU\u65f6\u95f4\u7684\u603b\u7ed3\u3002\n\n        if (time > parameters.end_time * EquationData::year_in_seconds) \n          break; \n\n        TrilinosWrappers::MPI::BlockVector old_old_stokes_solution; \n        old_old_stokes_solution      = old_stokes_solution; \n        old_stokes_solution          = stokes_solution; \n        old_old_temperature_solution = old_temperature_solution; \n        old_temperature_solution     = temperature_solution; \n        if (old_time_step > 0) \n          { \n\n// Trilinos sadd\u4e0d\u559c\u6b22\u9b3c\u9b42\u5411\u91cf\uff0c\u5373\u4f7f\u4f5c\u4e3a\u8f93\u5165\u3002\u6682\u65f6\u590d\u5236\u5230\u5206\u5e03\u5f0f\u5411\u91cf\u4e2d\u3002\n\n            { \n              TrilinosWrappers::MPI::BlockVector distr_solution(stokes_rhs); \n              distr_solution = stokes_solution; \n              TrilinosWrappers::MPI::BlockVector distr_old_solution(stokes_rhs); \n              distr_old_solution = old_old_stokes_solution; \n              distr_solution.sadd(1. + time_step / old_time_step, \n                                  -time_step / old_time_step, \n                                  distr_old_solution); \n              stokes_solution = distr_solution; \n            } \n            { \n              TrilinosWrappers::MPI::Vector distr_solution(temperature_rhs); \n              distr_solution = temperature_solution; \n              TrilinosWrappers::MPI::Vector distr_old_solution(temperature_rhs); \n              distr_old_solution = old_old_temperature_solution; \n              distr_solution.sadd(1. + time_step / old_time_step, \n                                  -time_step / old_time_step, \n                                  distr_old_solution); \n              temperature_solution = distr_solution; \n            } \n          } \n\n        if ((timestep_number > 0) && (timestep_number % 100 == 0)) \n          computing_timer.print_summary(); \n\n        time += time_step; \n        ++timestep_number; \n      } \n    while (true); \n\n// \u5982\u679c\u6211\u4eec\u8981\u751f\u6210\u56fe\u5f62\u8f93\u51fa\uff0c\u4e5f\u8981\u5bf9\u6700\u540e\u4e00\u4e2a\u65f6\u95f4\u6b65\u9aa4\u8fd9\u6837\u505a\uff0c\u9664\u975e\u6211\u4eec\u5728\u79bb\u5f00do-while\u5faa\u73af\u4e4b\u524d\u521a\u521a\u8fd9\u6837\u505a\u3002\n\n    if ((parameters.generate_graphical_output == true) && \n        !((timestep_number - 1) % parameters.graphical_output_interval == 0)) \n      output_results(); \n  } \n} // namespace Step32 \n\n//  @sect3{The <code>main</code> function}  \n\n// \u4e3b\u51fd\u6570\u50cf\u5f80\u5e38\u4e00\u6837\u7b80\u77ed\uff0c\u4e0e  step-31  \u4e2d\u7684\u51fd\u6570\u975e\u5e38\u76f8\u4f3c\u3002\u7531\u4e8e\u6211\u4eec\u4f7f\u7528\u4e86\u4e00\u4e2a\u53c2\u6570\u6587\u4ef6\uff0c\u8be5\u6587\u4ef6\u5728\u547d\u4ee4\u884c\u4e2d\u88ab\u6307\u5b9a\u4e3a\u53c2\u6570\uff0c\u6240\u4ee5\u6211\u4eec\u5fc5\u987b\u5728\u8fd9\u91cc\u8bfb\u53d6\u5b83\uff0c\u5e76\u5c06\u5176\u4f20\u9012\u7ed9\u53c2\u6570\u7c7b\u8fdb\u884c\u89e3\u6790\u3002\u5982\u679c\u547d\u4ee4\u884c\u4e2d\u6ca1\u6709\u7ed9\u51fa\u6587\u4ef6\u540d\uff0c\u6211\u4eec\u5c31\u7b80\u5355\u5730\u4f7f\u7528\u4e0e\u7a0b\u5e8f\u4e00\u8d77\u5206\u53d1\u7684  <code>\\step-32.prm</code>  \u6587\u4ef6\u3002\n\n// \u7531\u4e8e\u4e09\u7ef4\u8ba1\u7b97\u975e\u5e38\u7f13\u6162\uff0c\u9664\u975e\u4f60\u6295\u5165\u5927\u91cf\u7684\u5904\u7406\u5668\uff0c\u7a0b\u5e8f\u9ed8\u8ba4\u4e3a\u4e8c\u7ef4\u3002\u4f60\u53ef\u4ee5\u901a\u8fc7\u628a\u4e0b\u9762\u7684\u5e38\u6570\u7ef4\u5ea6\u6539\u4e3a3\u6765\u83b7\u5f97\u4e09\u7ef4\u7248\u672c\u3002\n\nint main(int argc, char *argv[]) \n{ \n  try \n    { \n      using namespace Step32; \n      using namespace dealii; \n\n      Utilities::MPI::MPI_InitFinalize mpi_initialization( \n        argc, argv, numbers::invalid_unsigned_int); \n\n      std::string parameter_filename; \n      if (argc >= 2) \n        parameter_filename = argv[1]; \n      else \n        parameter_filename = \"step-32.prm\"; \n\n      const int                              dim = 2; \n      BoussinesqFlowProblem<dim>::Parameters parameters(parameter_filename); \n      BoussinesqFlowProblem<dim>             flow_problem(parameters); \n      flow_problem.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  return 0; \n} \n\n\n", "meta": {"hexsha": "1f6095e0501b3180f137aed60a32735022874f28", "size": 121952, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-32/step-32.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-32/step-32.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-32/step-32.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": 42.3150589868, "max_line_length": 776, "alphanum_fraction": 0.6396615062, "num_tokens": 38818, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802603710085, "lm_q2_score": 0.7025300573952052, "lm_q1q2_score": 0.4699084877089644}}
{"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 * Authors: Wolfgang Bangerth, Ralf Hartmann, University of Heidelberg, 2001 \n */ \n\n\n\n// \u4ee5\u4e0b\u7b2c\u4e00\u4e2ainclude\u6587\u4ef6\u73b0\u5728\u53ef\u80fd\u5df2\u7ecf\u4f17\u6240\u5468\u77e5\uff0c\u4e0d\u9700\u8981\u8fdb\u4e00\u6b65\u89e3\u91ca\u3002\n\n#include <deal.II/base/quadrature_lib.h> \n#include <deal.II/base/convergence_table.h> \n#include <deal.II/grid/grid_generator.h> \n#include <deal.II/grid/manifold_lib.h> \n#include <deal.II/grid/tria.h> \n#include <deal.II/grid/grid_out.h> \n#include <deal.II/dofs/dof_handler.h> \n#include <deal.II/fe/fe_values.h> \n\n// \u8fd9\u4e2a\u5305\u542b\u6587\u4ef6\u662f\u65b0\u7684\u3002\u5373\u4f7f\u6211\u4eec\u5728\u672c\u6559\u7a0b\u4e2d\u4e0d\u6c42\u89e3PDE\uff0c\u6211\u4eec\u4e5f\u8981\u4f7f\u7528FE_Nothing\u7c7b\u63d0\u4f9b\u7684\u81ea\u7531\u5ea6\u4e3a\u96f6\u7684\u5047\u6709\u9650\u5143\u3002\n\n#include <deal.II/fe/fe_nothing.h> \n\n// \u4e0b\u9762\u7684\u5934\u6587\u4ef6\u4e5f\u662f\u65b0\u7684\uff1a\u5728\u5176\u4e2d\uff0c\u6211\u4eec\u58f0\u660e\u4e86MappingQ\u7c7b\uff0c\u6211\u4eec\u5c06\u4f7f\u7528\u8be5\u7c7b\u6765\u5904\u7406\u4efb\u610f\u9636\u7684\u591a\u9879\u5f0f\u6620\u5c04\u3002\n\n#include <deal.II/fe/mapping_q.h> \n\n// \u8fd9\u53c8\u662f\u4e00\u4e2aC++\u7684\u6587\u4ef6\u3002\n\n#include <iostream> \n#include <fstream> \n#include <cmath> \n\n// \u6700\u540e\u4e00\u6b65\u548c\u4ee5\u524d\u7684\u7a0b\u5e8f\u4e00\u6837\u3002\n\nnamespace Step10 \n{ \n  using namespace dealii; \n\n// \u73b0\u5728\uff0c\u7531\u4e8e\u6211\u4eec\u8981\u8ba1\u7b97 $\\pi$ \u7684\u503c\uff0c\u6211\u4eec\u5fc5\u987b\u4e0e\u4e00\u4e9b\u4e1c\u897f\u8fdb\u884c\u6bd4\u8f83\u3002\u8fd9\u4e9b\u662f $\\pi$ \u7684\u524d\u51e0\u4e2a\u6570\u5b57\uff0c\u6211\u4eec\u4e8b\u5148\u5b9a\u4e49\u597d\uff0c\u4ee5\u4fbf\u4ee5\u540e\u4f7f\u7528\u3002\u7531\u4e8e\u6211\u4eec\u60f3\u8ba1\u7b97\u4e24\u4e2a\u6570\u5b57\u7684\u5dee\u503c\uff0c\u800c\u8fd9\u4e24\u4e2a\u6570\u5b57\u662f\u76f8\u5f53\u7cbe\u786e\u7684\uff0c\u8ba1\u7b97\u51fa\u7684 $\\pi$ \u7684\u8fd1\u4f3c\u503c\u7684\u7cbe\u5ea6\u5728\u4e00\u4e2a\u53cc\u6570\u53d8\u91cf\u53ef\u4ee5\u5bb9\u7eb3\u7684\u6570\u5b57\u8303\u56f4\u5185\uff0c\u6240\u4ee5\u6211\u4eec\u5b81\u53ef\u5c06\u53c2\u8003\u503c\u58f0\u660e\u4e3a <code>long double</code> \uff0c\u5e76\u7ed9\u5b83\u589e\u52a0\u4e00\u4e9b\u6570\u5b57\u3002\n\n  const long double pi = 3.141592653589793238462643L; \n\n// \u7136\u540e\uff0c\u7b2c\u4e00\u4e2a\u4efb\u52a1\u5c06\u662f\u751f\u6210\u4e00\u4e9b\u8f93\u51fa\u3002\u7531\u4e8e\u8fd9\u4e2a\u7a0b\u5e8f\u975e\u5e38\u5c0f\uff0c\u6211\u4eec\u5728\u5176\u4e2d\u6ca1\u6709\u91c7\u7528\u9762\u5411\u5bf9\u8c61\u7684\u6280\u672f\uff0c\u4e5f\u6ca1\u6709\u58f0\u660e\u7c7b\uff08\u5f53\u7136\uff0c\u6211\u4eec\u4f7f\u7528\u4e86\u5e93\u7684\u9762\u5411\u5bf9\u8c61\u7684\u529f\u80fd\uff09\u3002\u76f8\u53cd\uff0c\u6211\u4eec\u53ea\u662f\u5c06\u529f\u80fd\u6253\u5305\u6210\u72ec\u7acb\u7684\u51fd\u6570\u3002\u6211\u4eec\u4f7f\u8fd9\u4e9b\u51fd\u6570\u6210\u4e3a\u7a7a\u95f4\u7ef4\u6570\u7684\u6a21\u677f\uff0c\u4ee5\u7b26\u5408\u4f7f\u7528deal.II\u65f6\u7684\u901a\u5e38\u505a\u6cd5\uff0c\u5c3d\u7ba1\u6211\u4eec\u53ea\u5bf9\u4e24\u4e2a\u7a7a\u95f4\u7ef4\u6570\u4f7f\u7528\u8fd9\u4e9b\u51fd\u6570\uff0c\u5f53\u8bd5\u56fe\u5bf9\u4efb\u4f55\u5176\u4ed6\u7a7a\u95f4\u7ef4\u6570\u4f7f\u7528\u65f6\uff0c\u4f1a\u51fa\u73b0\u5f02\u5e38\u3002\n\n// \u8fd9\u4e9b\u51fd\u6570\u4e2d\u7684\u7b2c\u4e00\u4e2a\u53ea\u662f\u751f\u6210\u4e00\u4e2a\u5706\u7684\u4e09\u89d2\u5f62\uff08hyperball\uff09\uff0c\u5e76\u8f93\u51fa $Q_p$ \u7684\u4e0d\u540c\u503c\u7684\u5355\u5143\u7684\u6620\u5c04\u3002\u7136\u540e\uff0c\u6211\u4eec\u7ec6\u5316\u4e00\u6b21\u7f51\u683c\uff0c\u518d\u505a\u4e00\u6b21\u3002\n\n  template <int dim> \n  void gnuplot_output() \n  { \n    std::cout << \"Output of grids into gnuplot files:\" << std::endl \n              << \"===================================\" << std::endl; \n//\u56e0\u6b64\uff0c\n//\u9996\u5148\u751f\u6210\u4e00\u4e2a\u5706\u7684\u7c97\u7565\u4e09\u89d2\u5256\u5206\uff0c\u5e76\u5c06\u4e00\u4e2a\u5408\u9002\u7684\u8fb9\u754c\u63cf\u8ff0\u4e0e\u4e4b\u5173\u8054\u3002\u9ed8\u8ba4\u60c5\u51b5\u4e0b\uff0c GridGenerator::hyper_ball \u5c06SphericalManifold\u9644\u52a0\u5230\u8fb9\u754c\u4e0a\uff08\u5185\u90e8\u4f7f\u7528FlatManifold\uff09\uff0c\u6240\u4ee5\u6211\u4eec\u7b80\u5355\u5730\u8c03\u7528\u8be5\u51fd\u6570\u5e76\u7ee7\u7eed\u524d\u8fdb\u3002\n\n    Triangulation<dim> triangulation; \n    GridGenerator::hyper_ball(triangulation); \n\n// \u7136\u540e\u5728\u5f53\u524d\u7f51\u683c\u4e0a\u4ea4\u66ff\u751f\u6210 $Q_1$ \u3001 $Q_2$ \u548c $Q_3$ \u6620\u5c04\u7684\u8f93\u51fa\uff0c\u4ee5\u53ca\uff08\u5728\u5faa\u73af\u4f53\u7684\u672b\u7aef\uff09\u5bf9\u7f51\u683c\u8fdb\u884c\u4e00\u6b21\u5168\u5c40\u7ec6\u5316\u3002\n\n    for (unsigned int refinement = 0; refinement < 2; ++refinement) \n      { \n        std::cout << \"Refinement level: \" << refinement << std::endl; \n\n        std::string filename_base = \"ball_\" + std::to_string(refinement); \n\n        for (unsigned int degree = 1; degree < 4; ++degree) \n          { \n            std::cout << \"Degree = \" << degree << std::endl; \n\n// \u4e3a\u6b64\uff0c\u9996\u5148\u5efa\u7acb\u4e00\u4e2a\u63cf\u8ff0\u6620\u5c04\u7684\u5bf9\u8c61\u3002\u8fd9\u662f\u7528MappingQ\u7c7b\u6765\u5b8c\u6210\u7684\uff0c\u8be5\u7c7b\u5728\u6784\u9020\u51fd\u6570\u4e2d\u91c7\u7528\u4e86\u5b83\u5e94\u4f7f\u7528\u7684\u591a\u9879\u5f0f\u7a0b\u5ea6\u4f5c\u4e3a\u53c2\u6570\u3002\n\n            const MappingQ<dim> mapping(degree); \n\n// \u987a\u4fbf\u63d0\u4e00\u4e0b\uff0c\u5bf9\u4e8e\u4e00\u4e2a\u7247\u72b6\u7ebf\u6027\u6620\u5c04\uff0c\u4f60\u53ef\u4ee5\u7ed9MappingQ\u7684\u6784\u9020\u51fd\u6570\u4e00\u4e2a <code>1</code> \u7684\u503c\uff0c\u4f46\u4e5f\u6709\u4e00\u4e2aMappingQ1\u7c7b\u53ef\u4ee5\u8fbe\u5230\u540c\u6837\u7684\u6548\u679c\u3002\u5386\u53f2\u4e0a\uff0c\u5b83\u4ee5\u6bd4MappingQ\u66f4\u7b80\u5355\u7684\u65b9\u5f0f\u505a\u4e86\u5f88\u591a\u4e8b\u60c5\uff0c\u4f46\u4eca\u5929\u53ea\u662f\u540e\u8005\u7684\u4e00\u4e2a\u5305\u88c5\u3002\u7136\u800c\uff0c\u5982\u679c\u4f60\u6ca1\u6709\u660e\u786e\u6307\u5b9a\u53e6\u4e00\u4e2a\u6620\u5c04\uff0c\u5b83\u4ecd\u7136\u662f\u5e93\u4e2d\u8bb8\u591a\u5730\u65b9\u9690\u542b\u4f7f\u7528\u7684\u7c7b\u3002\n\n// \u4e3a\u4e86\u771f\u6b63\u7528\u8fd9\u4e2a\u6620\u5c04\u5199\u51fa\u73b0\u5728\u7684\u7f51\u683c\uff0c\u6211\u4eec\u8bbe\u7f6e\u4e86\u4e00\u4e2a\u5bf9\u8c61\uff0c\u6211\u4eec\u5c06\u7528\u5b83\u6765\u8f93\u51fa\u3002\u6211\u4eec\u5c06\u751f\u6210Gnuplot\u8f93\u51fa\uff0c\u5b83\u7531\u4e00\u7ec4\u63cf\u8ff0\u6620\u5c04\u7684\u4e09\u89d2\u56fe\u7684\u7ebf\u6761\u7ec4\u6210\u3002\u9ed8\u8ba4\u60c5\u51b5\u4e0b\uff0c\u4e09\u89d2\u5256\u5206\u7684\u6bcf\u4e2a\u9762\u53ea\u753b\u4e00\u6761\u7ebf\uff0c\u4f46\u7531\u4e8e\u6211\u4eec\u60f3\u660e\u786e\u5730\u770b\u5230\u6620\u5c04\u7684\u6548\u679c\uff0c\u6240\u4ee5\u6211\u4eec\u60f3\u66f4\u8be6\u7ec6\u5730\u4e86\u89e3\u8fd9\u4e9b\u9762\u3002\u8fd9\u53ef\u4ee5\u901a\u8fc7\u4f20\u9012\u7ed9\u8f93\u51fa\u5bf9\u8c61\u4e00\u4e2a\u5305\u542b\u4e00\u4e9b\u6807\u5fd7\u7684\u7ed3\u6784\u6765\u5b9e\u73b0\u3002\u5728\u76ee\u524d\u7684\u60c5\u51b5\u4e0b\uff0c\u7531\u4e8eGnuplot\u53ea\u80fd\u753b\u76f4\u7ebf\uff0c\u6211\u4eec\u5728\u9762\u5b54\u4e0a\u8f93\u51fa\u4e86\u4e00\u4e9b\u989d\u5916\u7684\u70b9\uff0c\u8fd9\u6837\u6bcf\u4e2a\u9762\u5b54\u5c31\u753130\u6761\u5c0f\u7ebf\u6765\u753b\uff0c\u800c\u4e0d\u662f\u53ea\u6709\u4e00\u6761\u3002\u8fd9\u8db3\u4ee5\u8ba9\u6211\u4eec\u770b\u5230\u4e00\u6761\u5f2f\u66f2\u7684\u7ebf\uff0c\u800c\u4e0d\u662f\u4e00\u7ec4\u76f4\u7ebf\u7684\u5370\u8c61\u3002\n\n            GridOut               grid_out; \n            GridOutFlags::Gnuplot gnuplot_flags(false, 60); \n            grid_out.set_flags(gnuplot_flags); \n\n// \u6700\u540e\uff0c\u751f\u6210\u4e00\u4e2a\u6587\u4ef6\u540d\u548c\u4e00\u4e2a\u7528\u4e8e\u8f93\u51fa\u7684\u6587\u4ef6\u3002\n\n            std::string filename = \n              filename_base + \"_mapping_q_\" + std::to_string(degree) + \".dat\"; \n            std::ofstream gnuplot_file(filename); \n\n// \u7136\u540e\u628a\u4e09\u89d2\u56fe\u5199\u5230\u8fd9\u4e2a\u6587\u4ef6\u91cc\u3002\u8be5\u51fd\u6570\u7684\u6700\u540e\u4e00\u4e2a\u53c2\u6570\u662f\u4e00\u4e2a\u6307\u5411\u6620\u5c04\u5bf9\u8c61\u7684\u6307\u9488\u3002\u8fd9\u4e2a\u53c2\u6570\u6709\u4e00\u4e2a\u9ed8\u8ba4\u503c\uff0c\u5982\u679c\u6ca1\u6709\u7ed9\u51fa\u503c\uff0c\u5c31\u4f1a\u53d6\u4e00\u4e2a\u7b80\u5355\u7684MappingQ1\u5bf9\u8c61\uff0c\u6211\u4eec\u5728\u4e0a\u9762\u7b80\u5355\u4ecb\u7ecd\u8fc7\u3002\u8fd9\u6837\u5c31\u4f1a\u5728\u8f93\u51fa\u4e2d\u4ea7\u751f\u4e00\u4e2a\u771f\u5b9e\u8fb9\u754c\u7684\u7247\u72b6\u7ebf\u6027\u8fd1\u4f3c\u3002\n\n            grid_out.write_gnuplot(triangulation, gnuplot_file, &mapping); \n          } \n        std::cout << std::endl; \n\n// \u5728\u5faa\u73af\u7ed3\u675f\u65f6\uff0c\u5bf9\u7f51\u683c\u8fdb\u884c\u5168\u5c40\u7ec6\u5316\u3002\n\n        triangulation.refine_global(); \n      } \n  } \n\n// \u73b0\u5728\u6211\u4eec\u8fdb\u884c\u4ee3\u7801\u7684\u4e3b\u8981\u90e8\u5206\uff0c\u5373 $\\pi$ \u7684\u8fd1\u4f3c\u3002\u5706\u7684\u9762\u79ef\u5f53\u7136\u662f\u7531 $\\pi r^2$ \u7ed9\u51fa\u7684\uff0c\u6240\u4ee5\u6709\u4e00\u4e2a\u534a\u5f84\u4e3a1\u7684\u5706\uff0c\u9762\u79ef\u4ee3\u8868\u7684\u53ea\u662f\u88ab\u641c\u7d22\u7684\u6570\u5b57\u3002\u9762\u79ef\u7684\u6570\u503c\u8ba1\u7b97\u662f\u901a\u8fc7\u5728\u6574\u4e2a\u8ba1\u7b97\u57df\u4e2d\u79ef\u5206\u503c\u4e3a1\u7684\u5e38\u6570\u51fd\u6570\u6765\u8fdb\u884c\u7684\uff0c\u5373\u901a\u8fc7\u8ba1\u7b97\u9762\u79ef $\\int_K 1 dx=\\int_{\\hat K} 1\n// \\ \\textrm{det}\\ J(\\hat x) d\\hat x \\approx \\sum_i \\textrm{det}\n// \\ J(\\hat x_i)w(\\hat x_i)$ \uff0c\u5176\u4e2d\u603b\u548c\u5ef6\u4f38\u5230\u4e09\u89d2\u5f62\u4e2d\u6240\u6709\u6d3b\u52a8\u5355\u5143\u4e0a\u7684\u6240\u6709\u6b63\u4ea4\u70b9\uff0c $w(x_i)$ \u662f\u6b63\u4ea4\u70b9\u7684\u91cd\u91cf $x_i$ \u3002\u6bcf\u4e2a\u5355\u5143\u4e0a\u7684\u79ef\u5206\u90fd\u662f\u901a\u8fc7\u6570\u5b57\u6b63\u4ea4\u6765\u903c\u8fd1\u7684\uff0c\u56e0\u6b64\u6211\u4eec\u552f\u4e00\u9700\u8981\u7684\u989d\u5916\u6210\u5206\u662f\u5efa\u7acb\u4e00\u4e2aFEValues\u5bf9\u8c61\uff0c\u63d0\u4f9b\u6bcf\u4e2a\u5355\u5143\u7684\u76f8\u5e94`JxW`\u503c\u3002\u6ce8\u610f`JxW`\u662f\u6307<i>Jacobian determinant\n// times weight</i>\u7684\u7f29\u5199\uff1b\u56e0\u4e3a\u5728\u6570\u5b57\u6b63\u4ea4\u4e2d\uff0c\u4e24\u4e2a\u56e0\u5b50\u603b\u662f\u51fa\u73b0\u5728\u76f8\u540c\u7684\u5730\u65b9\uff0c\u6240\u4ee5\u6211\u4eec\u53ea\u63d0\u4f9b\u5408\u5e76\u7684\u6570\u91cf\uff0c\u800c\u4e0d\u662f\u4e24\u4e2a\u5355\u72ec\u7684\u6570\u91cf\uff09\u3002\u6211\u4eec\u6ce8\u610f\u5230\uff0c\u5728\u8fd9\u91cc\u6211\u4eec\u4e0d\u4f1a\u5728\u5176\u6700\u521d\u7684\u76ee\u7684\u4e2d\u4f7f\u7528FEValues\u5bf9\u8c61\uff0c\u5373\u7528\u4e8e\u8ba1\u7b97\u7279\u5b9a\u6b63\u4ea4\u70b9\u4e0a\u7684\u7279\u5b9a\u6709\u9650\u5143\u7684\u57fa\u51fd\u6570\u503c\u3002\u76f8\u53cd\uff0c\u6211\u4eec\u53ea\u7528\u5b83\u6765\u83b7\u5f97\u6b63\u4ea4\u70b9\u7684 \"JxW\"\uff0c\u800c\u4e0d\u8003\u8651\u6211\u4eec\u5c06\u7ed9FEValues\u5bf9\u8c61\u7684\u6784\u9020\u8005\u7684\uff08\u5047\uff09\u6709\u9650\u5143\u3002\u7ed9\u4e88FEValues\u5bf9\u8c61\u7684\u5b9e\u9645\u6709\u9650\u5143\u6839\u672c\u4e0d\u4f7f\u7528\uff0c\u6240\u4ee5\u6211\u4eec\u53ef\u4ee5\u7ed9\u4efb\u4f55\u3002\n\n  template <int dim> \n  void compute_pi_by_area() \n  { \n    std::cout << \"Computation of Pi by the area:\" << std::endl \n              << \"==============================\" << std::endl; \n\n// \u5bf9\u4e8e\u6240\u6709\u5355\u5143\u7684\u6570\u5b57\u6b63\u4ea4\uff0c\u6211\u4eec\u91c7\u7528\u8db3\u591f\u9ad8\u7684\u6b63\u4ea4\u89c4\u5219\u3002\u6211\u4eec\u9009\u62e98\u9636\u7684QGauss\uff084\u70b9\uff09\uff0c\u4ee5\u786e\u4fdd\u6570\u5b57\u6b63\u4ea4\u5f15\u8d77\u7684\u8bef\u5dee\u6bd4\u7531\u4e8e\u8fb9\u754c\u8fd1\u4f3c\u7684\u9636\u6570\uff0c\u5373\u6240\u91c7\u7528\u7684\u6620\u5c04\u7684\u9636\u6570\uff08\u6700\u59276\uff09\u8981\u9ad8\u3002\u8bf7\u6ce8\u610f\uff0c\u79ef\u5206\uff0c\u96c5\u5404\u5e03\u884c\u5217\u5f0f\uff0c\u4e0d\u662f\u4e00\u4e2a\u591a\u9879\u5f0f\u51fd\u6570\uff08\u76f8\u53cd\uff0c\u5b83\u662f\u4e00\u4e2a\u6709\u7406\u51fd\u6570\uff09\uff0c\u6240\u4ee5\u6211\u4eec\u4e0d\u4f7f\u7528\u9ad8\u65af\u6b63\u4ea4\u6765\u83b7\u5f97\u79ef\u5206\u7684\u7cbe\u786e\u503c\uff0c\u5c31\u50cf\u5728\u6709\u9650\u5143\u8ba1\u7b97\u4e2d\u7ecf\u5e38\u505a\u7684\u90a3\u6837\uff0c\u4f46\u4e5f\u53ef\u4ee5\u4f7f\u7528\u4efb\u4f55\u7c7b\u4f3c\u9636\u6570\u7684\u6b63\u4ea4\u516c\u5f0f\u6765\u4ee3\u66ff\u3002\n\n    const QGauss<dim> quadrature(4); \n\n// \u73b0\u5728\u5f00\u59cb\u5728\u591a\u9879\u5f0f\u6620\u5c04\u5ea6=1...4\u7684\u57fa\u7840\u4e0a\u8fdb\u884c\u5faa\u73af\u3002\n\n    for (unsigned int degree = 1; degree < 5; ++degree) \n      { \n        std::cout << \"Degree = \" << degree << std::endl; \n\n// \u9996\u5148\u751f\u6210\u4e09\u89d2\u5f62\u3001\u8fb9\u754c\u548c\u6620\u5c04\u5bf9\u8c61\uff0c\u6b63\u5982\u5df2\u7ecf\u770b\u5230\u7684\u90a3\u6837\u3002\n\n        Triangulation<dim> triangulation; \n        GridGenerator::hyper_ball(triangulation); \n\n        const MappingQ<dim> mapping(degree); \n\n// \u6211\u4eec\u73b0\u5728\u521b\u5efa\u4e00\u4e2a\u6709\u9650\u5143\u3002\u4e0e\u5176\u4ed6\u7684\u4f8b\u5b50\u7a0b\u5e8f\u4e0d\u540c\uff0c\u6211\u4eec\u5b9e\u9645\u4e0a\u4e0d\u9700\u8981\u7528\u5f62\u72b6\u51fd\u6570\u505a\u4efb\u4f55\u8ba1\u7b97\uff1b\u6211\u4eec\u53ea\u9700\u8981FEValues\u5bf9\u8c61\u7684`JxW`\u503c\u3002\u56e0\u6b64\uff0c\u6211\u4eec\u4f7f\u7528\u7279\u6b8a\u7684\u6709\u9650\u5143\u7c7bFE_Nothing\uff0c\u5b83\u7684\u6bcf\u4e2a\u5355\u5143\u7684\u81ea\u7531\u5ea6\u6b63\u597d\u4e3a\u96f6\uff08\u987e\u540d\u601d\u4e49\uff0c\u6bcf\u4e2a\u5355\u5143\u7684\u5c40\u90e8\u57fa\u7840\u4e3a\u7a7a\u96c6\uff09\u3002FE_Nothing\u7684\u4e00\u4e2a\u6bd4\u8f83\u5178\u578b\u7684\u7528\u6cd5\u89c1  step-46  \u3002\n\n        const FE_Nothing<dim> fe; \n\n// \u540c\u6837\u5730\uff0c\u6211\u4eec\u9700\u8981\u521b\u5efa\u4e00\u4e2aDoFHandler\u5bf9\u8c61\u3002\u6211\u4eec\u5b9e\u9645\u4e0a\u5e76\u6ca1\u6709\u4f7f\u7528\u5b83\uff0c\u4f46\u662f\u5b83\u5c06\u4e3a\u6211\u4eec\u63d0\u4f9b`active_cell_iterators'\uff0c\u8fd9\u662f\u91cd\u65b0\u521d\u59cb\u5316\u4e09\u89d2\u5f62\u7684\u6bcf\u4e2a\u5355\u5143\u4e0a\u7684FEValues\u5bf9\u8c61\u6240\u9700\u8981\u7684\u3002\n\n        DoFHandler<dim> dof_handler(triangulation); \n\n// \u73b0\u5728\u6211\u4eec\u8bbe\u7f6eFEValues\u5bf9\u8c61\uff0c\u5411\u6784\u9020\u51fd\u6570\u63d0\u4f9bMapping\u3001\u5047\u6709\u9650\u5143\u548c\u6b63\u4ea4\u5bf9\u8c61\uff0c\u4ee5\u53ca\u8981\u6c42\u53ea\u5728\u6b63\u4ea4\u70b9\u63d0\u4f9b`JxW`\u503c\u7684\u66f4\u65b0\u6807\u5fd7\u3002\u8fd9\u544a\u8bc9FEValues\u5bf9\u8c61\u5728\u8c03\u7528 <code>reinit</code> \u51fd\u6570\u65f6\u4e0d\u9700\u8981\u8ba1\u7b97\u5176\u4ed6\u6570\u91cf\uff0c\u4ece\u800c\u8282\u7701\u8ba1\u7b97\u65f6\u95f4\u3002\n\n// \u4e0e\u4e4b\u524d\u7684\u4f8b\u5b50\u7a0b\u5e8f\u76f8\u6bd4\uff0cFEValues\u5bf9\u8c61\u7684\u6784\u9020\u6700\u91cd\u8981\u7684\u533a\u522b\u662f\uff0c\u6211\u4eec\u4f20\u9012\u4e86\u4e00\u4e2a\u6620\u5c04\u5bf9\u8c61\u4f5c\u4e3a\u7b2c\u4e00\u4e2a\u53c2\u6570\uff0c\u5b83\u5c06\u88ab\u7528\u4e8e\u8ba1\u7b97\u4ece\u5355\u5143\u5230\u5b9e\u6570\u5355\u5143\u7684\u6620\u5c04\u3002\u5728\u4ee5\u524d\u7684\u4f8b\u5b50\u4e2d\uff0c\u8fd9\u4e2a\u53c2\u6570\u88ab\u7701\u7565\u4e86\uff0c\u7ed3\u679c\u662f\u9690\u542b\u5730\u4f7f\u7528\u4e86MappingQ1\u7c7b\u578b\u7684\u5bf9\u8c61\u3002\n\n        FEValues<dim> fe_values(mapping, fe, quadrature, update_JxW_values); \n\n// \u6211\u4eec\u4f7f\u7528\u4e00\u4e2aConvergenceTable\u7c7b\u7684\u5bf9\u8c61\u6765\u5b58\u50a8\u6240\u6709\u91cd\u8981\u7684\u6570\u636e\uff0c\u5982 $\\pi$ \u7684\u8fd1\u4f3c\u503c\u548c\u4e0e $\\pi$ \u7684\u771f\u5b9e\u503c\u76f8\u6bd4\u7684\u8bef\u5dee\u3002\u6211\u4eec\u8fd8\u5c06\u4f7f\u7528ConvergenceTable\u7c7b\u63d0\u4f9b\u7684\u51fd\u6570\u6765\u8ba1\u7b97 $\\pi$ \u7684\u8fd1\u4f3c\u503c\u7684\u6536\u655b\u7387\u3002\n\n        ConvergenceTable table; \n\n// \u73b0\u5728\u6211\u4eec\u5728\u4e09\u89d2\u5f62\u7684\u51e0\u4e2a\u7ec6\u5316\u6b65\u9aa4\u4e0a\u5faa\u73af\u3002\n\n        for (unsigned int refinement = 0; refinement < 6; \n             ++refinement, triangulation.refine_global(1)) \n          { \n\n// \u5728\u8fd9\u4e2a\u5faa\u73af\u4e2d\uff0c\u6211\u4eec\u9996\u5148\u5c06\u5f53\u524d\u4e09\u89d2\u5f62\u7684\u6d3b\u52a8\u5355\u5143\u7684\u6570\u91cf\u6dfb\u52a0\u5230\u8868\u683c\u4e2d\u3002\u8fd9\u4e2a\u51fd\u6570\u4f1a\u81ea\u52a8\u521b\u5efa\u4e00\u4e2a\u4e0a\u6807\u4e3a \"cells \"\u7684\u8868\u683c\u5217\uff0c\u4ee5\u9632\u8fd9\u4e2a\u5217\u4e4b\u524d\u6ca1\u6709\u88ab\u521b\u5efa\u3002\n\n            table.add_value(\"cells\", triangulation.n_active_cells()); \n\n// \u7136\u540e\u6211\u4eec\u4e3a\u865a\u62df\u6709\u9650\u5143\u5206\u914d\u81ea\u7531\u5ea6\u3002\u4e25\u683c\u6765\u8bf4\uff0c\u5728\u6211\u4eec\u7684\u7279\u6b8a\u60c5\u51b5\u4e0b\uff0c\u6211\u4eec\u4e0d\u9700\u8981\u8fd9\u4e2a\u51fd\u6570\u7684\u8c03\u7528\uff0c\u4f46\u6211\u4eec\u8c03\u7528\u5b83\u662f\u4e3a\u4e86\u8ba9DoFHandler\u9ad8\u5174 -- \u5426\u5219\u5b83\u5c06\u5728\u4e0b\u9762\u7684 FEValues::reinit \u51fd\u6570\u4e2d\u629b\u51fa\u4e00\u4e2a\u65ad\u8a00\u3002\n\n            dof_handler.distribute_dofs(fe); \n\n// \u6211\u4eec\u5c06\u53d8\u91cf\u9762\u79ef\u5b9a\u4e49\u4e3a \"\u957f\u53cc\"\uff0c\u5c31\u50cf\u6211\u4eec\u4e4b\u524d\u4e3a \"pi \"\u53d8\u91cf\u6240\u505a\u7684\u90a3\u6837\u3002\n\n            long double area = 0; \n\n// \u73b0\u5728\u6211\u4eec\u5faa\u73af\u6240\u6709\u7684\u5355\u5143\u683c\uff0c\u91cd\u65b0\u521d\u59cb\u5316\u6bcf\u4e2a\u5355\u5143\u683c\u7684FEValues\u5bf9\u8c61\uff0c\u5e76\u5c06\u8be5\u5355\u5143\u683c\u7684\u6240\u6709`JxW`\u503c\u52a0\u5230`area`\u4e0a......\n\n            for (const auto &cell : dof_handler.active_cell_iterators()) \n              { \n                fe_values.reinit(cell); \n                for (unsigned int i = 0; i < fe_values.n_quadrature_points; ++i) \n                  area += static_cast<long double>(fe_values.JxW(i)); \n              } \n\n// ...\u5e76\u5c06\u5f97\u5230\u7684\u533a\u57df\u503c\u548c\u9519\u8bef\u5b58\u50a8\u5728\u8868\u4e2d\u3002\u6211\u4eec\u9700\u8981\u9759\u6001\u8f6c\u6362\u4e3a\u53cc\u6570\uff0c\u56e0\u4e3a\u6ca1\u6709\u5b9e\u73b0add_value(string, long double)\u51fd\u6570\u3002\u8bf7\u6ce8\u610f\uff0c\u8fd9\u4e5f\u6d89\u53ca\u5230\u7b2c\u4e8c\u4e2a\u8c03\u7528\uff0c\u56e0\u4e3a <code>std</code> \u547d\u540d\u7a7a\u95f4\u4e2d\u7684 <code>fabs</code> \u51fd\u6570\u5728\u5176\u53c2\u6570\u7c7b\u578b\u4e0a\u662f\u91cd\u8f7d\u7684\uff0c\u6240\u4ee5\u5b58\u5728\u4e00\u4e2a\u83b7\u53d6\u5e76\u8fd4\u56de <code>long double</code> \u7684\u7248\u672c\uff0c\u800c\u5168\u5c40\u547d\u540d\u7a7a\u95f4\u4e2d\u53ea\u6709\u4e00\u4e2a\u8fd9\u6837\u7684\u51fd\u6570\u88ab\u58f0\u660e\uff08\u83b7\u53d6\u5e76\u8fd4\u56de\u4e00\u4e2a\u53cc\u6570\uff09\u3002\n\n            table.add_value(\"eval.pi\", static_cast<double>(area)); \n            table.add_value(\"error\", static_cast<double>(std::fabs(area - pi))); \n          } \n\n// \u6211\u4eec\u60f3\u8ba1\u7b97`error`\u5217\u7684\u6536\u655b\u7387\u3002\u56e0\u6b64\u6211\u4eec\u9700\u8981\u5728\u8c03\u7528`evaluate_all_convergence_rates`\u4e4b\u524d\uff0c\u5c06\u5176\u4ed6\u5217\u4ece\u6536\u655b\u7387\u8bc4\u4f30\u4e2d\u7701\u7565\u3002\n\n        table.omit_column_from_convergence_rate_evaluation(\"cells\"); \n        table.omit_column_from_convergence_rate_evaluation(\"eval.pi\"); \n        table.evaluate_all_convergence_rates( \n                                    ConvergenceTable::reduction_rate_log2); \n\n// \u6700\u540e\u6211\u4eec\u8bbe\u7f6e\u4e00\u4e9b\u91cf\u7684\u8f93\u51fa\u7cbe\u5ea6\u548c\u79d1\u5b66\u6a21\u5f0f...\n\n        table.set_precision(\"eval.pi\", 16); \n        table.set_scientific(\"error\", true); \n\n// ...\u5e76\u5c06\u6574\u4e2a\u8868\u683c\u5199\u5230  std::cout.  \u3002\n        table.write_text(std::cout); \n\n        std::cout << std::endl; \n      } \n  } \n\n// \u4e0b\u9762\u7684\u7b2c\u4e8c\u4e2a\u51fd\u6570\u4e5f\u662f\u8ba1\u7b97 $\\pi$ \u7684\u8fd1\u4f3c\u503c\uff0c\u4f46\u8fd9\u6b21\u662f\u901a\u8fc7\u57df\u7684\u5468\u957f $2\\pi r$ \u800c\u4e0d\u662f\u9762\u79ef\u3002\u8fd9\u4e2a\u51fd\u6570\u53ea\u662f\u524d\u4e00\u4e2a\u51fd\u6570\u7684\u4e00\u4e2a\u53d8\u4f53\u3002\u56e0\u6b64\uff0c\u6211\u4eec\u4e3b\u8981\u662f\u7ed9\u51fa\u4e0d\u540c\u4e4b\u5904\u7684\u6587\u4ef6\u3002\n\n  template <int dim> \n  void compute_pi_by_perimeter() \n  { \n    std::cout << \"Computation of Pi by the perimeter:\" << std::endl \n              << \"===================================\" << std::endl; \n\n// \u6211\u4eec\u91c7\u53d6\u540c\u6837\u7684\u6b63\u4ea4\u987a\u5e8f\uff0c\u4f46\u8fd9\u6b21\u662f`dim-1`\u7ef4\u6b63\u4ea4\uff0c\u56e0\u4e3a\u6211\u4eec\u5c06\u5728\uff08\u8fb9\u754c\uff09\u7ebf\u4e0a\u800c\u4e0d\u662f\u5728\u5355\u5143\u4e0a\u79ef\u5206\u3002\n\n    const QGauss<dim - 1> quadrature(4); \n\n// \u6211\u4eec\u5728\u6240\u6709\u5ea6\u6570\u4e0a\u5faa\u73af\uff0c\u521b\u5efa\u4e09\u89d2\u5f62\u3001\u8fb9\u754c\u3001\u6620\u5c04\u3001\u5047\u6709\u9650\u5143\u548cDoFHandler\u5bf9\u8c61\uff0c\u5982\u4e4b\u524d\u6240\u89c1\u3002\n\n    for (unsigned int degree = 1; degree < 5; ++degree) \n      { \n        std::cout << \"Degree = \" << degree << std::endl; \n        Triangulation<dim> triangulation; \n        GridGenerator::hyper_ball(triangulation); \n\n        const MappingQ<dim>   mapping(degree); \n        const FE_Nothing<dim> fe; \n\n        DoFHandler<dim> dof_handler(triangulation); \n\n// \u7136\u540e\u6211\u4eec\u521b\u5efa\u4e00\u4e2aFEFaceValues\u5bf9\u8c61\uff0c\u800c\u4e0d\u662f\u50cf\u524d\u4e00\u4e2a\u51fd\u6570\u4e2d\u7684FEValues\u5bf9\u8c61\u3002\u540c\u6837\uff0c\u6211\u4eec\u4f20\u9012\u4e00\u4e2a\u6620\u5c04\u4f5c\u4e3a\u7b2c\u4e00\u4e2a\u53c2\u6570\u3002\n\n        FEFaceValues<dim> fe_face_values(mapping, \n                                         fe, \n                                         quadrature, \n                                         update_JxW_values); \n        ConvergenceTable  table; \n\n        for (unsigned int refinement = 0; refinement < 6; \n             ++refinement, triangulation.refine_global(1)) \n          { \n            table.add_value(\"cells\", triangulation.n_active_cells()); \n\n            dof_handler.distribute_dofs(fe); \n\n// \u73b0\u5728\u6211\u4eec\u5728\u6240\u6709\u5355\u5143\u548c\u6bcf\u4e2a\u5355\u5143\u7684\u6240\u6709\u9762\u4e0a\u8fd0\u884c\u3002\u53ea\u6709\u8fb9\u754c\u9762\u4e0a\u7684`JxW`\u503c\u7684\u8d21\u732e\u88ab\u6dfb\u52a0\u5230\u957f\u53cc\u53d8\u91cf`\u5468\u957f`\u4e2d\u3002\n\n            long double perimeter = 0; \n            for (const auto &cell : dof_handler.active_cell_iterators()) \n              for (const auto &face : cell->face_iterators()) \n                if (face->at_boundary()) \n                  { \n\n// \u6211\u4eec\u7528\u5355\u5143\u683c\u8fed\u4ee3\u5668\u548c\u9762\u7684\u7f16\u53f7\u91cd\u65b0\u542f\u52a8FEFaceValues\u5bf9\u8c61\u3002\n\n                    fe_face_values.reinit(cell, face); \n                    for (unsigned int i = 0; \n                         i < fe_face_values.n_quadrature_points; \n                         ++i) \n                      perimeter += \n                        static_cast<long double>(fe_face_values.JxW(i)); \n                  } \n\n// \u7136\u540e\u5c06\u8bc4\u4f30\u540e\u7684\u6570\u503c\u5b58\u50a8\u5728\u8868\u4e2d...\n\n            table.add_value(\"eval.pi\", static_cast<double>(perimeter / 2.0L)); \n            table.add_value( \n              \"error\", static_cast<double>(std::fabs(perimeter / 2.0L - pi))); \n          } \n\n// ......\u7136\u540e\u50cf\u524d\u4e00\u4e2a\u51fd\u6570\u90a3\u6837\u7ed3\u675f\u8fd9\u4e2a\u51fd\u6570\u3002\n\n        table.omit_column_from_convergence_rate_evaluation(\"cells\"); \n        table.omit_column_from_convergence_rate_evaluation(\"eval.pi\"); \n        table.evaluate_all_convergence_rates( \n          ConvergenceTable::reduction_rate_log2); \n\n        table.set_precision(\"eval.pi\", 16); \n        table.set_scientific(\"error\", true); \n\n        table.write_text(std::cout); \n\n        std::cout << std::endl; \n      } \n  } \n} // namespace Step10 \n\n// \u4e0b\u9762\u7684\u4e3b\u51fd\u6570\u53ea\u662f\u6309\u7167\u4e0a\u8ff0\u51fd\u6570\u7684\u51fa\u73b0\u987a\u5e8f\u6765\u8c03\u7528\u5b83\u4eec\u3002\u9664\u6b64\u4ee5\u5916\uff0c\u5b83\u770b\u8d77\u6765\u5c31\u50cf\u4ee5\u524d\u7684\u6559\u7a0b\u7a0b\u5e8f\u7684\u4e3b\u51fd\u6570\u4e00\u6837\u3002\n\nint main() \n{ \n  try \n    { \n      std::cout.precision(16); \n\n      const unsigned int dim = 2; \n\n      Step10::gnuplot_output<dim>(); \n\n      Step10::compute_pi_by_area<dim>(); \n      Step10::compute_pi_by_perimeter<dim>(); \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": "7fd89f91e4aa2f49cc77b428bbd42d963eb288af", "size": 11957, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-10/step-10.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-10/step-10.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-10/step-10.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": 35.064516129, "max_line_length": 240, "alphanum_fraction": 0.6218114912, "num_tokens": 5131, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.46990848354308706}}
{"text": "/*\n * testSudoku.cpp\n * @brief develop code for Sudoku CSP solver\n * @date Jan 29, 2012\n * @author Frank Dellaert\n */\n\n#include <gtsam_unstable/discrete/CSP.h>\n#include <CppUnitLite/TestHarness.h>\n#include <boost/assign/std/map.hpp>\nusing boost::assign::insert;\n#include <iostream>\n#include <sstream>\n#include <stdarg.h>\n\nusing namespace std;\nusing namespace gtsam;\n\n#define PRINT false\n\nclass Sudoku: public CSP {\n\n\t/// sudoku size\n\tsize_t n_;\n\n\t/// discrete keys\n\ttypedef std::pair<size_t, size_t> IJ;\n\tstd::map<IJ, DiscreteKey> dkeys_;\n\npublic:\n\n\t/// return DiscreteKey for cell(i,j)\n\tconst DiscreteKey& dkey(size_t i, size_t j) const {\n\t\treturn dkeys_.at(IJ(i, j));\n\t}\n\n\t/// return Index for cell(i,j)\n\tIndex key(size_t i, size_t j) const {\n\t\treturn dkey(i, j).first;\n\t}\n\n\t/// Constructor\n\tSudoku(size_t n, ...) :\n\t\t\tn_(n) {\n\t\t// Create variables, ordering, and unary constraints\n\t\tva_list ap;\n\t\tva_start(ap, n);\n\t\tIndex k=0;\n\t\tfor (size_t i = 0; i < n; ++i) {\n\t\t\tfor (size_t j = 0; j < n; ++j, ++k) {\n\t\t\t\t// create the key\n\t\t\t\tIJ ij(i, j);\n\t\t\t\tdkeys_[ij] = DiscreteKey(k, n);\n\t\t\t\t// get the unary constraint, if any\n\t\t\t\tint value = va_arg(ap, int);\n\t\t\t\t// cout << value << \" \";\n\t\t\t\tif (value != 0) addSingleValue(dkeys_[ij], value - 1);\n\t\t\t}\n\t\t\t//cout << endl;\n\t\t}\n\t\tva_end(ap);\n\n\t\t// add row constraints\n\t\tfor (size_t i = 0; i < n; i++) {\n\t\t\tDiscreteKeys dkeys;\n\t\t\tfor (size_t j = 0; j < n; j++)\n\t\t\t\tdkeys += dkey(i, j);\n\t\t\taddAllDiff(dkeys);\n\t\t}\n\n\t\t// add col constraints\n\t\tfor (size_t j = 0; j < n; j++) {\n\t\t\tDiscreteKeys dkeys;\n\t\t\tfor (size_t i = 0; i < n; i++)\n\t\t\t\tdkeys += dkey(i, j);\n\t\t\taddAllDiff(dkeys);\n\t\t}\n\n\t\t// add box constraints\n\t\tsize_t N = (size_t)sqrt(double(n)), i0 = 0;\n\t\tfor (size_t I = 0; I < N; I++) {\n\t\t\tsize_t j0 = 0;\n\t\t\tfor (size_t J = 0; J < N; J++) {\n\t\t\t\t// Box I,J\n\t\t\t\tDiscreteKeys dkeys;\n\t\t\t\tfor (size_t i = i0; i < i0 + N; i++)\n\t\t\t\t\tfor (size_t j = j0; j < j0 + N; j++)\n\t\t\t\t\t\tdkeys += dkey(i, j);\n\t\t\t\taddAllDiff(dkeys);\n\t\t\t\tj0 += N;\n\t\t\t}\n\t\t\ti0 += N;\n\t\t}\n\t}\n\n\t/// Print readable form of assignment\n\tvoid printAssignment(DiscreteFactor::sharedValues assignment) const {\n\t\tfor (size_t i = 0; i < n_; i++) {\n\t\t\tfor (size_t j = 0; j < n_; j++) {\n\t\t\t\tIndex k = key(i, j);\n\t\t\t\tcout << 1 + assignment->at(k) << \" \";\n\t\t\t}\n\t\t\tcout << endl;\n\t\t}\n\t}\n\n\t/// solve and print solution\n\tvoid printSolution() {\n\t\tDiscreteFactor::sharedValues MPE = optimalAssignment();\n\t\tprintAssignment(MPE);\n\t}\n\n};\n\n/* ************************************************************************* */\nTEST_UNSAFE( Sudoku, small)\n{\n\tSudoku csp(4,\n\t\t\t1,0, 0,4,\n\t\t\t0,0, 0,0,\n\n\t\t\t4,0, 2,0,\n\t\t\t0,1, 0,0);\n\n\t// Do BP\n\tcsp.runArcConsistency(4,10,PRINT);\n\n\t// optimize and check\n\tCSP::sharedValues solution = csp.optimalAssignment();\n\tCSP::Values expected;\n\tinsert(expected)\n\t(csp.key(0,0), 0)(csp.key(0,1), 1)(csp.key(0,2), 2)(csp.key(0,3), 3)\n\t(csp.key(1,0), 2)(csp.key(1,1), 3)(csp.key(1,2), 0)(csp.key(1,3), 1)\n\t(csp.key(2,0), 3)(csp.key(2,1), 2)(csp.key(2,2), 1)(csp.key(2,3), 0)\n\t(csp.key(3,0), 1)(csp.key(3,1), 0)(csp.key(3,2), 3)(csp.key(3,3), 2);\n\tEXPECT(assert_equal(expected,*solution));\n\t//csp.printAssignment(solution);\n}\n\n/* ************************************************************************* */\nTEST_UNSAFE( Sudoku, easy)\n{\n\tSudoku sudoku(9,\n\t\t\t0,0,5, 0,9,0, 0,0,1,\n\t\t\t0,0,0, 0,0,2, 0,7,3,\n\t\t\t7,6,0, 0,0,8, 2,0,0,\n\n\t\t\t0,1,2, 0,0,9, 0,0,4,\n\t\t\t0,0,0, 2,0,3, 0,0,0,\n\t\t\t3,0,0, 1,0,0, 9,6,0,\n\n\t\t\t0,0,1, 9,0,0, 0,5,8,\n\t\t\t9,7,0, 5,0,0, 0,0,0,\n\t\t\t5,0,0, 0,3,0, 7,0,0);\n\n\t// Do BP\n\tsudoku.runArcConsistency(4,10,PRINT);\n\n\t// sudoku.printSolution(); // don't do it\n}\n\n/* ************************************************************************* */\nTEST_UNSAFE( Sudoku, extreme)\n{\n\tSudoku sudoku(9,\n\t\t\t0,0,9, 7,4,8, 0,0,0,\n\t\t\t7,0,0, 0,0,0, 0,0,0,\n\t\t\t0,2,0, 1,0,9, 0,0,0,\n\n\t\t\t0,0,7, 0,0,0, 2,4,0,\n\t\t\t0,6,4, 0,1,0, 5,9,0,\n\t\t\t0,9,8, 0,0,0, 3,0,0,\n\n\t\t\t0,0,0, 8,0,3, 0,2,0,\n\t\t\t0,0,0, 0,0,0, 0,0,6,\n\t\t\t0,0,0, 2,7,5, 9,0,0);\n\n\t// Do BP\n\tsudoku.runArcConsistency(9,10,PRINT);\n\n#ifdef METIS\n\tVariableIndex index(sudoku);\n\tindex.print(\"index\");\n\tofstream os(\"/Users/dellaert/src/hmetis-1.5-osx-i686/extreme-dual.txt\");\n  index.outputMetisFormat(os);\n#endif\n\n  //sudoku.printSolution(); // don't do it\n}\n\n/* ************************************************************************* */\nTEST_UNSAFE( Sudoku, AJC_3star_Feb8_2012)\n{\n\tSudoku sudoku(9,\n\t\t\t9,5,0, 0,0,6, 0,0,0,\n\t\t\t0,8,4, 0,7,0, 0,0,0,\n\t\t\t6,2,0, 5,0,0, 4,0,0,\n\n\t\t\t0,0,0, 2,9,0, 6,0,0,\n\t\t\t0,9,0, 0,0,0, 0,2,0,\n\t\t\t0,0,2, 0,6,3, 0,0,0,\n\n\t\t\t0,0,9, 0,0,7, 0,6,8,\n\t\t\t0,0,0, 0,3,0, 2,9,0,\n\t\t\t0,0,0, 1,0,0, 0,3,7);\n\n\t// Do BP\n\tsudoku.runArcConsistency(9,10,PRINT);\n\n\t//sudoku.printSolution(); // don't do it\n}\n\n/* ************************************************************************* */\nint main() {\n\tTestResult tr;\n\treturn TestRegistry::runAllTests(tr);\n}\n/* ************************************************************************* */\n\n", "meta": {"hexsha": "1e4026e7f7cdcbb7fcf7b2b291e7659e0f38d77b", "size": 4880, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam_unstable/discrete/tests/testSudoku.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_unstable/discrete/tests/testSudoku.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_unstable/discrete/tests/testSudoku.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": 22.1818181818, "max_line_length": 79, "alphanum_fraction": 0.5165983607, "num_tokens": 1974, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.668880247169804, "lm_q2_score": 0.7025300573952052, "lm_q1q2_score": 0.46990847843472144}}
{"text": "// Copyright 2004 The Trustees of Indiana University.\n\n// Use, modification and distribution is subject to the Boost Software\n// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n//  Authors: Douglas Gregor\n//           Andrew Lumsdaine\n#ifndef BOOST_GRAPH_KAMADA_KAWAI_SPRING_LAYOUT_HPP\n#define BOOST_GRAPH_KAMADA_KAWAI_SPRING_LAYOUT_HPP\n\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/johnson_all_pairs_shortest.hpp>\n#include <boost/type_traits/is_convertible.hpp>\n#include <utility>\n#include <iterator>\n#include <vector>\n#include <boost/limits.hpp>\n#include <cmath>\n\nnamespace boost {\n  namespace detail { namespace graph {\n    /**\n     * Denotes an edge or display area side length used to scale a\n     * Kamada-Kawai drawing.\n     */\n    template<bool Edge, typename T>\n    struct edge_or_side\n    {\n      explicit edge_or_side(T value) : value(value) {}\n\n      T value;\n    };\n\n    /**\n     * Compute the edge length from an edge length. This is trivial.\n     */\n    template<typename Graph, typename DistanceMap, typename IndexMap, \n             typename T>\n    T compute_edge_length(const Graph&, DistanceMap, IndexMap, \n                          edge_or_side<true, T> length)\n    { return length.value; }\n\n    /**\n     * Compute the edge length based on the display area side\n       length. We do this by dividing the side length by the largest\n       shortest distance between any two vertices in the graph.\n     */\n    template<typename Graph, typename DistanceMap, typename IndexMap, \n             typename T>\n    T\n    compute_edge_length(const Graph& g, DistanceMap distance, IndexMap index,\n                        edge_or_side<false, T> length)\n    {\n      T result(0);\n\n      typedef typename graph_traits<Graph>::vertex_iterator vertex_iterator;\n\n      for (vertex_iterator ui = vertices(g).first, end = vertices(g).second;\n           ui != end; ++ui) {\n        vertex_iterator vi = ui;\n        for (++vi; vi != end; ++vi) {\n          T dij = distance[get(index, *ui)][get(index, *vi)];\n          if (dij > result) result = dij;\n        }\n      }\n      return length.value / result;\n    }\n\n    /**\n     * Implementation of the Kamada-Kawai spring layout algorithm.\n     */\n    template<typename Graph, typename PositionMap, typename WeightMap,\n             typename EdgeOrSideLength, typename Done,\n             typename VertexIndexMap, typename DistanceMatrix,\n             typename SpringStrengthMatrix, typename PartialDerivativeMap>\n    struct kamada_kawai_spring_layout_impl\n    {\n      typedef typename property_traits<WeightMap>::value_type weight_type;\n      typedef std::pair<weight_type, weight_type> deriv_type;\n      typedef typename graph_traits<Graph>::vertex_iterator vertex_iterator;\n      typedef typename graph_traits<Graph>::vertex_descriptor\n        vertex_descriptor;\n\n      kamada_kawai_spring_layout_impl(\n        const Graph& g, \n        PositionMap position,\n        WeightMap weight, \n        EdgeOrSideLength edge_or_side_length,\n        Done done,\n        weight_type spring_constant,\n        VertexIndexMap index,\n        DistanceMatrix distance,\n        SpringStrengthMatrix spring_strength,\n        PartialDerivativeMap partial_derivatives)\n        : g(g), position(position), weight(weight), \n          edge_or_side_length(edge_or_side_length), done(done),\n          spring_constant(spring_constant), index(index), distance(distance),\n          spring_strength(spring_strength), \n          partial_derivatives(partial_derivatives) {}\n\n      // Compute contribution of vertex i to the first partial\n      // derivatives (dE/dx_m, dE/dy_m) (for vertex m)\n      deriv_type\n      compute_partial_derivative(vertex_descriptor m, vertex_descriptor i)\n      {\n#ifndef BOOST_NO_STDC_NAMESPACE\n        using std::sqrt;\n#endif // BOOST_NO_STDC_NAMESPACE\n\n        deriv_type result(0, 0);\n        if (i != m) {\n          weight_type x_diff = position[m].x - position[i].x;\n          weight_type y_diff = position[m].y - position[i].y;\n          weight_type dist = sqrt(x_diff * x_diff + y_diff * y_diff);\n          result.first = spring_strength[get(index, m)][get(index, i)] \n            * (x_diff - distance[get(index, m)][get(index, i)]*x_diff/dist);\n          result.second = spring_strength[get(index, m)][get(index, i)] \n            * (y_diff - distance[get(index, m)][get(index, i)]*y_diff/dist);\n        }\n\n        return result;\n      }\n\n      // Compute partial derivatives dE/dx_m and dE/dy_m\n      deriv_type \n      compute_partial_derivatives(vertex_descriptor m)\n      {\n#ifndef BOOST_NO_STDC_NAMESPACE\n        using std::sqrt;\n#endif // BOOST_NO_STDC_NAMESPACE\n\n        deriv_type result(0, 0);\n\n        // TBD: looks like an accumulate to me\n        std::pair<vertex_iterator, vertex_iterator> verts = vertices(g);\n        for (/* no init */; verts.first != verts.second; ++verts.first) {\n          vertex_descriptor i = *verts.first;\n          deriv_type deriv = compute_partial_derivative(m, i);\n          result.first += deriv.first;\n          result.second += deriv.second;\n        }\n\n        return result;\n      }\n\n      // The actual Kamada-Kawai spring layout algorithm implementation\n      bool run()\n      {\n#ifndef BOOST_NO_STDC_NAMESPACE\n        using std::sqrt;\n#endif // BOOST_NO_STDC_NAMESPACE\n\n        // Compute d_{ij} and place it in the distance matrix\n        if (!johnson_all_pairs_shortest_paths(g, distance, index, weight, \n                                              weight_type(0)))\n          return false;\n\n        // Compute L based on side length (if needed), or retrieve L\n        weight_type edge_length = \n          detail::graph::compute_edge_length(g, distance, index,\n                                             edge_or_side_length);\n        \n        // Compute l_{ij} and k_{ij}\n        const weight_type K = spring_constant;\n        vertex_iterator ui, end = vertices(g).second;\n        for (ui = vertices(g).first; ui != end; ++ui) {\n          vertex_iterator vi = ui;\n          for (++vi; vi != end; ++vi) {\n            weight_type dij = distance[get(index, *ui)][get(index, *vi)];\n            if (dij == (std::numeric_limits<weight_type>::max)())\n              return false;\n            distance[get(index, *ui)][get(index, *vi)] = edge_length * dij;\n            distance[get(index, *vi)][get(index, *ui)] = edge_length * dij;\n            spring_strength[get(index, *ui)][get(index, *vi)] = K/(dij*dij);\n            spring_strength[get(index, *vi)][get(index, *ui)] = K/(dij*dij);\n          }\n        }\n        \n        // Compute Delta_i and find max\n        vertex_descriptor p = *vertices(g).first;\n        weight_type delta_p(0);\n\n        for (ui = vertices(g).first; ui != end; ++ui) {\n          deriv_type deriv = compute_partial_derivatives(*ui);\n          put(partial_derivatives, *ui, deriv);\n\n          weight_type delta = \n            sqrt(deriv.first*deriv.first + deriv.second*deriv.second);\n\n          if (delta > delta_p) {\n            p = *ui;\n            delta_p = delta;\n          }\n        }\n\n        while (!done(delta_p, p, g, true)) {\n          // The contribution p makes to the partial derivatives of\n          // each vertex. Computing this (at O(n) cost) allows us to\n          // update the delta_i values in O(n) time instead of O(n^2)\n          // time.\n          std::vector<deriv_type> p_partials(num_vertices(g));\n          for (ui = vertices(g).first; ui != end; ++ui) {\n            vertex_descriptor i = *ui;\n            p_partials[get(index, i)] = compute_partial_derivative(i, p);\n          }\n\n          do {\n            // Compute the 4 elements of the Jacobian\n            weight_type dE_dx_dx = 0, dE_dx_dy = 0, dE_dy_dx = 0, dE_dy_dy = 0;\n            for (ui = vertices(g).first; ui != end; ++ui) {\n              vertex_descriptor i = *ui;\n              if (i != p) {\n                weight_type x_diff = position[p].x - position[i].x;\n                weight_type y_diff = position[p].y - position[i].y;\n                weight_type dist = sqrt(x_diff * x_diff + y_diff * y_diff);\n                weight_type dist_cubed = dist * dist * dist;\n                weight_type k_mi = spring_strength[get(index,p)][get(index,i)];\n                weight_type l_mi = distance[get(index, p)][get(index, i)];\n                dE_dx_dx += k_mi * (1 - (l_mi * y_diff * y_diff)/dist_cubed);\n                dE_dx_dy += k_mi * l_mi * x_diff * y_diff / dist_cubed;\n                dE_dy_dx += k_mi * l_mi * x_diff * y_diff / dist_cubed;\n                dE_dy_dy += k_mi * (1 - (l_mi * x_diff * x_diff)/dist_cubed);\n              }\n            }\n\n            // Solve for delta_x and delta_y\n            weight_type dE_dx = get(partial_derivatives, p).first;\n            weight_type dE_dy = get(partial_derivatives, p).second;\n\n            weight_type delta_x = \n              (dE_dx_dy * dE_dy - dE_dy_dy * dE_dx)\n              / (dE_dx_dx * dE_dy_dy - dE_dx_dy * dE_dy_dx);\n\n            weight_type delta_y = \n              (dE_dx_dx * dE_dy - dE_dy_dx * dE_dx)\n              / (dE_dy_dx * dE_dx_dy - dE_dx_dx * dE_dy_dy);\n\n\n            // Move p by (delta_x, delta_y)\n            position[p].x += delta_x;\n            position[p].y += delta_y;\n\n            // Recompute partial derivatives and delta_p\n            deriv_type deriv = compute_partial_derivatives(p);\n            put(partial_derivatives, p, deriv);\n\n            delta_p = \n              sqrt(deriv.first*deriv.first + deriv.second*deriv.second);\n          } while (!done(delta_p, p, g, false));\n\n          // Select new p by updating each partial derivative and delta\n          vertex_descriptor old_p = p;\n          for (ui = vertices(g).first; ui != end; ++ui) {\n            deriv_type old_deriv_p = p_partials[get(index, *ui)];\n            deriv_type old_p_partial = \n              compute_partial_derivative(*ui, old_p);\n            deriv_type deriv = get(partial_derivatives, *ui);\n\n            deriv.first += old_p_partial.first - old_deriv_p.first;\n            deriv.second += old_p_partial.second - old_deriv_p.second;\n\n            put(partial_derivatives, *ui, deriv);\n            weight_type delta = \n              sqrt(deriv.first*deriv.first + deriv.second*deriv.second);\n\n            if (delta > delta_p) {\n              p = *ui;\n              delta_p = delta;\n            }\n          }\n        }\n\n        return true;\n      }\n\n      const Graph& g; \n      PositionMap position;\n      WeightMap weight; \n      EdgeOrSideLength edge_or_side_length;\n      Done done;\n      weight_type spring_constant;\n      VertexIndexMap index;\n      DistanceMatrix distance;\n      SpringStrengthMatrix spring_strength;\n      PartialDerivativeMap partial_derivatives;\n    };\n  } } // end namespace detail::graph\n\n  /// States that the given quantity is an edge length.\n  template<typename T> \n  inline detail::graph::edge_or_side<true, T>\n  edge_length(T x) \n  { return detail::graph::edge_or_side<true, T>(x); }\n\n  /// States that the given quantity is a display area side length.\n  template<typename T> \n  inline detail::graph::edge_or_side<false, T>\n  side_length(T x) \n  { return detail::graph::edge_or_side<false, T>(x); }\n\n  /** \n   * \\brief Determines when to terminate layout of a particular graph based\n   * on a given relative tolerance. \n   */\n  template<typename T = double>\n  struct layout_tolerance\n  {\n    layout_tolerance(const T& tolerance = T(0.001))\n      : tolerance(tolerance), last_energy((std::numeric_limits<T>::max)()),\n        last_local_energy((std::numeric_limits<T>::max)()) { }\n\n    template<typename Graph>\n    bool \n    operator()(T delta_p, \n               typename boost::graph_traits<Graph>::vertex_descriptor p,\n               const Graph& g,\n               bool global)\n    {\n      if (global) {\n        if (last_energy == (std::numeric_limits<T>::max)()) {\n          last_energy = delta_p;\n          return false;\n        }\n          \n        T diff = last_energy - delta_p;\n        if (diff < T(0)) diff = -diff;\n        bool done = (delta_p == T(0) || diff / last_energy < tolerance);\n        last_energy = delta_p;\n        return done;\n      } else {\n        if (last_local_energy == (std::numeric_limits<T>::max)()) {\n          last_local_energy = delta_p;\n          return delta_p == T(0);\n        }\n          \n        T diff = last_local_energy - delta_p;\n        bool done = (delta_p == T(0) || (diff / last_local_energy) < tolerance);\n        last_local_energy = delta_p;\n        return done;\n      }\n    }\n\n  private:\n    T tolerance;\n    T last_energy;\n    T last_local_energy;\n  };\n\n  /** \\brief Kamada-Kawai spring layout for undirected graphs.\n   *\n   * This algorithm performs graph layout (in two dimensions) for\n   * connected, undirected graphs. It operates by relating the layout\n   * of graphs to a dynamic spring system and minimizing the energy\n   * within that system. The strength of a spring between two vertices\n   * is inversely proportional to the square of the shortest distance\n   * (in graph terms) between those two vertices. Essentially,\n   * vertices that are closer in the graph-theoretic sense (i.e., by\n   * following edges) will have stronger springs and will therefore be\n   * placed closer together.\n   *\n   * Prior to invoking this algorithm, it is recommended that the\n   * vertices be placed along the vertices of a regular n-sided\n   * polygon.\n   *\n   * \\param g (IN) must be a model of Vertex List Graph, Edge List\n   * Graph, and Incidence Graph and must be undirected.\n   *\n   * \\param position (OUT) must be a model of Lvalue Property Map,\n   * where the value type is a class containing fields @c x and @c y\n   * that will be set to the @c x and @c y coordinates of each vertex.\n   *\n   * \\param weight (IN) must be a model of Readable Property Map,\n   * which provides the weight of each edge in the graph @p g.\n   *\n   * \\param edge_or_side_length (IN) provides either the unit length\n   * @c e of an edge in the layout or the length of a side @c s of the\n   * display area, and must be either @c boost::edge_length(e) or @c\n   * boost::side_length(s), respectively.\n   *\n   * \\param done (IN) is a 4-argument function object that is passed\n   * the current value of delta_p (i.e., the energy of vertex @p p),\n   * the vertex @p p, the graph @p g, and a boolean flag indicating\n   * whether @p delta_p is the maximum energy in the system (when @c\n   * true) or the energy of the vertex being moved. Defaults to @c\n   * layout_tolerance instantiated over the value type of the weight\n   * map.\n   *\n   * \\param spring_constant (IN) is the constant multiplied by each\n   * spring's strength. Larger values create systems with more energy\n   * that can take longer to stabilize; smaller values create systems\n   * with less energy that stabilize quickly but do not necessarily\n   * result in pleasing layouts. The default value is 1.\n   *\n   * \\param index (IN) is a mapping from vertices to index values\n   * between 0 and @c num_vertices(g). The default is @c\n   * get(vertex_index,g).\n   *\n   * \\param distance (UTIL/OUT) will be used to store the distance\n   * from every vertex to every other vertex, which is computed in the\n   * first stages of the algorithm. This value's type must be a model\n   * of BasicMatrix with value type equal to the value type of the\n   * weight map. The default is a a vector of vectors.\n   *\n   * \\param spring_strength (UTIL/OUT) will be used to store the\n   * strength of the spring between every pair of vertices. This\n   * value's type must be a model of BasicMatrix with value type equal\n   * to the value type of the weight map. The default is a a vector of\n   * vectors.\n   *\n   * \\param partial_derivatives (UTIL) will be used to store the\n   * partial derivates of each vertex with respect to the @c x and @c\n   * y coordinates. This must be a Read/Write Property Map whose value\n   * type is a pair with both types equivalent to the value type of\n   * the weight map. The default is an iterator property map.\n   *\n   * \\returns @c true if layout was successful or @c false if a\n   * negative weight cycle was detected.\n   */\n  template<typename Graph, typename PositionMap, typename WeightMap,\n           typename T, bool EdgeOrSideLength, typename Done,\n           typename VertexIndexMap, typename DistanceMatrix,\n           typename SpringStrengthMatrix, typename PartialDerivativeMap>\n  bool \n  kamada_kawai_spring_layout(\n    const Graph& g, \n    PositionMap position,\n    WeightMap weight, \n    detail::graph::edge_or_side<EdgeOrSideLength, T> edge_or_side_length,\n    Done done,\n    typename property_traits<WeightMap>::value_type spring_constant,\n    VertexIndexMap index,\n    DistanceMatrix distance,\n    SpringStrengthMatrix spring_strength,\n    PartialDerivativeMap partial_derivatives)\n  {\n    BOOST_STATIC_ASSERT((is_convertible<\n                           typename graph_traits<Graph>::directed_category*,\n                           undirected_tag*\n                         >::value));\n\n    detail::graph::kamada_kawai_spring_layout_impl<\n      Graph, PositionMap, WeightMap, \n      detail::graph::edge_or_side<EdgeOrSideLength, T>, Done, VertexIndexMap, \n      DistanceMatrix, SpringStrengthMatrix, PartialDerivativeMap>\n      alg(g, position, weight, edge_or_side_length, done, spring_constant,\n          index, distance, spring_strength, partial_derivatives);\n    return alg.run();\n  }\n\n  /**\n   * \\overload\n   */\n  template<typename Graph, typename PositionMap, typename WeightMap,\n           typename T, bool EdgeOrSideLength, typename Done, \n           typename VertexIndexMap>\n  bool \n  kamada_kawai_spring_layout(\n    const Graph& g, \n    PositionMap position,\n    WeightMap weight, \n    detail::graph::edge_or_side<EdgeOrSideLength, T> edge_or_side_length,\n    Done done,\n    typename property_traits<WeightMap>::value_type spring_constant,\n    VertexIndexMap index)\n  {\n    typedef typename property_traits<WeightMap>::value_type weight_type;\n\n    typename graph_traits<Graph>::vertices_size_type n = num_vertices(g);\n    typedef std::vector<weight_type> weight_vec;\n\n    std::vector<weight_vec> distance(n, weight_vec(n));\n    std::vector<weight_vec> spring_strength(n, weight_vec(n));\n    std::vector<std::pair<weight_type, weight_type> > partial_derivatives(n);\n\n    return \n      kamada_kawai_spring_layout(\n        g, position, weight, edge_or_side_length, done, spring_constant, index,\n        distance.begin(),\n        spring_strength.begin(),\n        make_iterator_property_map(partial_derivatives.begin(), index,\n                                   std::pair<weight_type, weight_type>()));\n  }\n\n  /**\n   * \\overload\n   */\n  template<typename Graph, typename PositionMap, typename WeightMap,\n           typename T, bool EdgeOrSideLength, typename Done>\n  bool \n  kamada_kawai_spring_layout(\n    const Graph& g, \n    PositionMap position,\n    WeightMap weight, \n    detail::graph::edge_or_side<EdgeOrSideLength, T> edge_or_side_length,\n    Done done,\n    typename property_traits<WeightMap>::value_type spring_constant)\n  {\n    return kamada_kawai_spring_layout(g, position, weight, edge_or_side_length,\n                                      done, spring_constant, \n                                      get(vertex_index, g));\n  }\n\n  /**\n   * \\overload\n   */\n  template<typename Graph, typename PositionMap, typename WeightMap,\n           typename T, bool EdgeOrSideLength, typename Done>\n  bool \n  kamada_kawai_spring_layout(\n    const Graph& g, \n    PositionMap position,\n    WeightMap weight, \n    detail::graph::edge_or_side<EdgeOrSideLength, T> edge_or_side_length,\n    Done done)\n  {\n    typedef typename property_traits<WeightMap>::value_type weight_type;\n    return kamada_kawai_spring_layout(g, position, weight, edge_or_side_length,\n                                      done, weight_type(1)); \n  }\n\n  /**\n   * \\overload\n   */\n  template<typename Graph, typename PositionMap, typename WeightMap,\n           typename T, bool EdgeOrSideLength>\n  bool \n  kamada_kawai_spring_layout(\n    const Graph& g, \n    PositionMap position,\n    WeightMap weight, \n    detail::graph::edge_or_side<EdgeOrSideLength, T> edge_or_side_length)\n  {\n    typedef typename property_traits<WeightMap>::value_type weight_type;\n    return kamada_kawai_spring_layout(g, position, weight, edge_or_side_length,\n                                      layout_tolerance<weight_type>(),\n                                      weight_type(1.0), \n                                      get(vertex_index, g));\n  }\n} // end namespace boost\n\n#endif // BOOST_GRAPH_KAMADA_KAWAI_SPRING_LAYOUT_HPP\n", "meta": {"hexsha": "884cb0369f845ed4a3b2f8199f027a3b9f2dfe9c", "size": 20584, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "applications/physbam/physbam-lib/External_Libraries/Archives/boost/boost/graph/kamada_kawai_spring_layout.hpp", "max_stars_repo_name": "schinmayee/nimbus", "max_stars_repo_head_hexsha": "170cd15e24a7a88243a6ea80aabadc0fc0e6e177", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2017-07-03T19:09:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-10T02:53:56.000Z", "max_issues_repo_path": "applications/physbam/physbam-lib/External_Libraries/Archives/boost/boost/graph/kamada_kawai_spring_layout.hpp", "max_issues_repo_name": "schinmayee/nimbus", "max_issues_repo_head_hexsha": "170cd15e24a7a88243a6ea80aabadc0fc0e6e177", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "applications/physbam/physbam-lib/External_Libraries/Archives/boost/boost/graph/kamada_kawai_spring_layout.hpp", "max_forks_repo_name": "schinmayee/nimbus", "max_forks_repo_head_hexsha": "170cd15e24a7a88243a6ea80aabadc0fc0e6e177", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2017-09-17T02:05:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-31T00:12:01.000Z", "avg_line_length": 37.9079189687, "max_line_length": 80, "alphanum_fraction": 0.6332588418, "num_tokens": 4850, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300449389326, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.4699084747400881}}
{"text": "#define BOOST_TEST_MAIN\n#include <boost/test/unit_test.hpp>\n\n#include <boost/assign/list_of.hpp>\n#include <boost/lexical_cast.hpp>\nusing boost::assign::list_of;\nusing boost::assign::map_list_of;\n\n#include <evaluation/util/CoordinateDescentParameterOptimiser.h>\nusing namespace evaluation;\n\n#include <tvgutil/numbers/NumberSequenceGenerator.h>\nusing namespace tvgutil;\n\n//#################### HELPER FUNCTIONS ####################\n\nfloat sum_squares_cost_fn(const ParamSet& params)\n{\n  float cost = 0.0f;\n  for(std::map<std::string,std::string>::const_iterator it = params.begin(), iend = params.end(); it != iend; ++it)\n  {\n    float value = boost::lexical_cast<float>(it->second);\n    cost += value * value;\n  }\n  return cost;\n}\n\n//#################### TESTS ####################\n\nBOOST_AUTO_TEST_SUITE(test_CoordinateDescentParameterOptimiser)\n\nBOOST_AUTO_TEST_CASE(optimise_for_parameters_test)\n{\n  // Set up the optimiser.\n  const unsigned int seed = 12345;\n  const size_t epochCount = 10;\n  CoordinateDescentParameterOptimiser optimiser(sum_squares_cost_fn, epochCount, seed);\n  optimiser.add_param(\"Foo\", NumberSequenceGenerator::generate_stepped<float>(-5.5f, 1.5f, 5.0f))\n           .add_param(\"Bar\", NumberSequenceGenerator::generate_stepped<float>(-1000.0f, 1.0f, 5.0f))\n           .add_param(\"Boo\", list_of<float>(-10.0f)(-5.0f)(-2.0f)(0.0f)(5.0f)(15.0f))\n           .add_param(\"Dum\", list_of<float>(0.0f));\n\n  // Use the optimiser to choose a set of parameters.\n  float cost;\n  ParamSet params = optimiser.optimise_for_parameters(&cost);\n\n  // Check that the chosen parameters are as expected.\n  ParamSet expectedParams = map_list_of(\"Foo\",boost::lexical_cast<std::string>(0.5f))\n                                       (\"Bar\",boost::lexical_cast<std::string>(0.0f))\n                                       (\"Boo\",boost::lexical_cast<std::string>(0.0f))\n                                       (\"Dum\",boost::lexical_cast<std::string>(0.0f));\n\n  BOOST_CHECK_EQUAL(ParamSetUtil::param_set_to_string(params), ParamSetUtil::param_set_to_string(expectedParams));\n\n  // Check that the cost of the chosen parameters is as expected.\n  const float expectedCost = 0.25f;\n  const float TOL = 1e-5f;\n  BOOST_CHECK_CLOSE(cost, expectedCost, TOL);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "f9e6e8bda33da32e1301d84922e228f34a7d35f1", "size": 2274, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/unit/evaluation/test_CoordinateDescentParameterOptimiser.cpp", "max_stars_repo_name": "torrvision/spaint", "max_stars_repo_head_hexsha": "9cac8100323ea42fe439f66407b832b88f72d2fd", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 197.0, "max_stars_repo_stars_event_min_datetime": "2015-10-01T07:23:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T03:02:31.000Z", "max_issues_repo_path": "tests/unit/evaluation/test_CoordinateDescentParameterOptimiser.cpp", "max_issues_repo_name": "GucciPrada/spaint", "max_issues_repo_head_hexsha": "b09ff1ec0d9e123cf316f2737e1b70b5ecc0beea", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 16.0, "max_issues_repo_issues_event_min_datetime": "2016-03-26T13:01:08.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-02T09:13:49.000Z", "max_forks_repo_path": "tests/unit/evaluation/test_CoordinateDescentParameterOptimiser.cpp", "max_forks_repo_name": "GucciPrada/spaint", "max_forks_repo_head_hexsha": "b09ff1ec0d9e123cf316f2737e1b70b5ecc0beea", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 62.0, "max_forks_repo_forks_event_min_datetime": "2015-10-03T07:14:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-31T08:58:18.000Z", "avg_line_length": 36.6774193548, "max_line_length": 115, "alphanum_fraction": 0.6732629727, "num_tokens": 599, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.46990387783988075}}
{"text": "#include <boost/test/unit_test.hpp>\n#include \"algorithms/math/parallel_lines.hpp\"\n\nBOOST_AUTO_TEST_SUITE(CheckIfParallelLines)\n\nBOOST_AUTO_TEST_CASE(dots)\n{\n    Point dot;\n    Line first(dot, dot);\n    Line second(dot, dot);\n\n    BOOST_CHECK(AreLinesParallel(first, second));\n}\n\nBOOST_AUTO_TEST_CASE(line_and_dot)\n{\n    Point dot;\n    Line first(dot, dot);\n    Point x(1, 1), y(2, 2);\n    Line second(x, y);\n\n    BOOST_CHECK(false == AreLinesParallel(first, second));\n}\n\nBOOST_AUTO_TEST_CASE(same_lines)\n{\n    Point x(1, 1), y(2, 2);\n    Line first(x, y);\n    Line second(x, y);\n\n    BOOST_CHECK(AreLinesParallel(first, second));\n}\n\nBOOST_AUTO_TEST_CASE(parallel)\n{\n    Point x1(-12, 0), y1(0, 8);\n    Line first(x1, y1);\n\n    Point x2(0, -12), y2(18, 0);\n    Line second(x2, y2);\n\n    BOOST_CHECK(AreLinesParallel(first, second));\n}\n\nBOOST_AUTO_TEST_CASE(not_parallel)\n{\n    Point x1(-12, 0), y1(0, 8);\n    Line first(x1, y1);\n\n    Point x2(0, -12), y2(18, 5);\n    Line second(x2, y2);\n\n    BOOST_CHECK(false == AreLinesParallel(first, second));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "99bda665bc0efdafeaf52a073ea16f399a704281", "size": 1078, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/algorithms/math/test_parallel_lines.cpp", "max_stars_repo_name": "iamantony/CppNotes", "max_stars_repo_head_hexsha": "2707db6560ad80b0e5e286a04b2d46e5c0280b3f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-07-31T14:13:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-03T09:51:43.000Z", "max_issues_repo_path": "test/algorithms/math/test_parallel_lines.cpp", "max_issues_repo_name": "iamantony/CppNotes", "max_issues_repo_head_hexsha": "2707db6560ad80b0e5e286a04b2d46e5c0280b3f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 28.0, "max_issues_repo_issues_event_min_datetime": "2015-09-22T07:38:21.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-02T11:00:58.000Z", "max_forks_repo_path": "test/algorithms/math/test_parallel_lines.cpp", "max_forks_repo_name": "iamantony/CppNotes", "max_forks_repo_head_hexsha": "2707db6560ad80b0e5e286a04b2d46e5c0280b3f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-10-11T14:10:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-27T08:53:50.000Z", "avg_line_length": 18.9122807018, "max_line_length": 58, "alphanum_fraction": 0.6576994434, "num_tokens": 328, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.46990387783988075}}
{"text": "#define BOOST_TEST_MODULE \"test_gocontact_potential\"\n\n#ifdef BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n#else\n#include <boost/test/included/unit_test.hpp>\n#endif\n\n#include <mjolnir/forcefield/local/GoContactPotential.hpp>\n\nBOOST_AUTO_TEST_CASE(GoContact_double)\n{\n    using real_type = double;\n    constexpr std::size_t N = 1000;\n    constexpr real_type   h = 1e-6;\n\n    const real_type e  = 1.0;\n    const real_type r0 = 5.0;\n\n    mjolnir::GoContactPotential<real_type> Go(e, r0);\n\n    const real_type x_min = 0.8 * r0;\n    const real_type x_max = 5.0 * r0;\n    const real_type dx = (x_max - x_min) / N;\n\n    for(std::size_t i=0; i<N; ++i)\n    {\n        const real_type x    = x_min + i * dx;\n        const real_type pot1 = Go.potential(x + h);\n        const real_type pot2 = Go.potential(x - h);\n        const real_type dpot = (pot1 - pot2) / (2 * h);\n        const real_type deri = Go.derivative(x);\n\n        BOOST_TEST(dpot == deri, boost::test_tools::tolerance(h));\n    }\n}\n\nBOOST_AUTO_TEST_CASE(GoContact_float)\n{\n    using real_type = double;\n    constexpr std::size_t N = 100;\n    constexpr real_type   h = 1e-3;\n\n    const real_type e  = 1.0;\n    const real_type r0 = 5.0;\n\n    mjolnir::GoContactPotential<real_type> Go(e, r0);\n\n    const real_type x_min = 0.8 * r0;\n    const real_type x_max = 5.0 * r0;\n    const real_type dx = (x_max - x_min) / N;\n\n    for(std::size_t i=0; i<N; ++i)\n    {\n        const real_type x    = x_min + i * dx;\n        const real_type pot1 = Go.potential(x + h);\n        const real_type pot2 = Go.potential(x - h);\n        const real_type dpot = (pot1 - pot2) / (2 * h);\n        const real_type deri = Go.derivative(x);\n\n        BOOST_TEST(dpot == deri, boost::test_tools::tolerance(h));\n    }\n}\n", "meta": {"hexsha": "8f3691f3abc961b4c60f9afedc3b9c62c9da40be", "size": 1747, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/core/test_go_contact_potential.cpp", "max_stars_repo_name": "yutakasi634/Mjolnir", "max_stars_repo_head_hexsha": "ab7a29a47f994111e8b889311c44487463f02116", "max_stars_repo_licenses": ["MIT"], "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/core/test_go_contact_potential.cpp", "max_issues_repo_name": "yutakasi634/Mjolnir", "max_issues_repo_head_hexsha": "ab7a29a47f994111e8b889311c44487463f02116", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-07T11:41:45.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-08T10:01:38.000Z", "max_forks_repo_path": "test/core/test_go_contact_potential.cpp", "max_forks_repo_name": "yutakasi634/Mjolnir", "max_forks_repo_head_hexsha": "ab7a29a47f994111e8b889311c44487463f02116", "max_forks_repo_licenses": ["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.296875, "max_line_length": 66, "alphanum_fraction": 0.6273611906, "num_tokens": 549, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.46990387783988075}}
{"text": "/**\n * \\file boost/numeric/ublasx/operation/log10.hpp\n *\n * \\brief Apply the \\c std::log10 function to each element of a vector or\n *  matrix expression.\n *\n * Copyright (c) 2011, Marco Guazzone\n * \n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\n\n#ifndef BOOST_NUMERIC_UBLASX_OPERATION_LOG10_HPP\n#define BOOST_NUMERIC_UBLASX_OPERATION_LOG10_HPP\n\n\n#include <boost/numeric/ublas/traits.hpp>\n#include <boost/numeric/ublasx/expression/matrix_unary_functor.hpp>\n#include <boost/numeric/ublasx/expression/vector_unary_functor.hpp>\n#include <cmath>\n\n\nnamespace boost { namespace numeric { namespace ublasx {\n\nusing namespace ::boost::numeric::ublas;\n\nnamespace detail {\n\ntemplate <typename VectorExprT>\nstruct vector_log10_functor_traits\n{\n\ttypedef VectorExprT input_expression_type;\n\ttypedef typename vector_traits<input_expression_type>::value_type signature_argument_type;\n\ttypedef signature_argument_type signature_result_type;\n\ttypedef vector_unary_functor_traits<\n\t\t\t\tinput_expression_type,\n\t\t\t\tsignature_result_type (signature_argument_type)\n\t\t\t> unary_functor_expression_type;\n\ttypedef typename unary_functor_expression_type::result_type result_type;\n\ttypedef typename unary_functor_expression_type::expression_type expression_type;\n};\n\n\ntemplate <typename MatrixExprT>\nstruct matrix_log10_functor_traits\n{\n\ttypedef MatrixExprT input_expression_type;\n\ttypedef typename matrix_traits<input_expression_type>::value_type signature_argument_type;\n\ttypedef signature_argument_type signature_result_type;\n\ttypedef matrix_unary_functor_traits<\n\t\t\t\tinput_expression_type,\n\t\t\t\tsignature_result_type (signature_argument_type)\n\t\t\t> unary_functor_expression_type;\n\ttypedef typename unary_functor_expression_type::result_type result_type;\n\ttypedef typename unary_functor_expression_type::expression_type expression_type;\n};\n\n\nnamespace /*<unnamed>*/ {\n\n/// Auxiliary function used to replace ::std::log2 when that is not available.\ntemplate <typename T>\nBOOST_UBLAS_INLINE\nT log10(T x)\n{\n\treturn ::std::log10(x);\n}\n\n} // Namespace <unnamed>\n\n} // Namespace detail\n\n\n/**\n * \\brief Applies the \\c std::log10 function to each element of a given vector\n *  expression.\n *\n * \\tparam VectorExprT The type of the input vector expression.\n *\n * \\param ve The input vector expression.\n * \\return A vector expression representing the application of \\c std::log10 to\n *  each element of \\a ve.\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\ntemplate <typename VectorExprT>\nBOOST_UBLAS_INLINE\ntypename detail::vector_log10_functor_traits<VectorExprT>::result_type log10(vector_expression<VectorExprT> const& ve)\n{\n\ttypedef typename detail::vector_log10_functor_traits<VectorExprT>::expression_type expression_type;\n\ttypedef typename detail::vector_log10_functor_traits<VectorExprT>::signature_result_type signature_result_type;\n\n\treturn expression_type(ve(), detail::log10<signature_result_type>);\n}\n\n\n/**\n * \\brief Applies the \\c std::log10 function to each element of a given matrix\n *  expression.\n *\n * \\tparam MatrixExprT The type of the input matrix expression.\n *\n * \\param me The input matrix expression.\n * \\return A matrix expression representing the application of \\c std::log10 to\n *  each element of \\a me.\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\ntemplate <typename MatrixExprT>\nBOOST_UBLAS_INLINE\ntypename detail::matrix_log10_functor_traits<MatrixExprT>::result_type log10(matrix_expression<MatrixExprT> const& me)\n{\n\ttypedef typename detail::matrix_log10_functor_traits<MatrixExprT>::expression_type expression_type;\n\ttypedef typename detail::matrix_log10_functor_traits<MatrixExprT>::signature_result_type signature_result_type;\n\n\treturn expression_type(me(), detail::log10<signature_result_type>);\n}\n\n}}} // Namespace boost::numeric::ublasx\n\n\n#endif // BOOST_NUMERIC_UBLASX_OPERATION_LOG10_HPP\n", "meta": {"hexsha": "79a98dbef508f5aec74a39c3b8292d0e4625c7ef", "size": 3988, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/ublasx/operation/log10.hpp", "max_stars_repo_name": "comcon1/boost-ublasx", "max_stars_repo_head_hexsha": "290b92b643a944825df99bece3468a4f81518056", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "boost/numeric/ublasx/operation/log10.hpp", "max_issues_repo_name": "comcon1/boost-ublasx", "max_issues_repo_head_hexsha": "290b92b643a944825df99bece3468a4f81518056", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "boost/numeric/ublasx/operation/log10.hpp", "max_forks_repo_name": "comcon1/boost-ublasx", "max_forks_repo_head_hexsha": "290b92b643a944825df99bece3468a4f81518056", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.6507936508, "max_line_length": 118, "alphanum_fraction": 0.8014042126, "num_tokens": 910, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.4699038778398807}}
{"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/math/find_polynomial_roots_jenkins_traub.h\"\n\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n#include <glog/logging.h>\n\n#include <cmath>\n#include <complex>\n#include <limits>\n#include <vector>\n\n#include \"theia/math/polynomial.h\"\n#include \"theia/math/util.h\"\n\nnamespace theia {\n\nusing Eigen::MatrixXd;\nusing Eigen::Vector3d;\nusing Eigen::VectorXd;\nusing Eigen::Vector3cd;\nusing Eigen::VectorXcd;\n\nnamespace {\n// Machine precision constants.\nstatic const double mult_eps = std::numeric_limits<double>::epsilon();\nstatic const double sum_eps = std::numeric_limits<double>::epsilon();\nstatic const double kAbsoluteTolerance = 1e-14;\nstatic const double kRelativeTolerance = 1e-10;\n\nenum class ConvergenceType {\n  NO_CONVERGENCE = 0,\n  LINEAR_CONVERGENCE = 1,\n  QUADRATIC_CONVERGENCE = 2\n};\n\n// Perform division by a linear term of the form (z - x) and evaluate P at x.\nvoid SyntheticDivisionAndEvaluate(const VectorXd& polynomial,\n                                  const double x,\n                                  VectorXd* quotient,\n                                  double* eval) {\n  quotient->setZero(polynomial.size() - 1);\n  (*quotient)(0) = polynomial(0);\n  for (int i = 1; i < polynomial.size() - 1; i++) {\n    (*quotient)(i) = polynomial(i) + (*quotient)(i - 1) * x;\n  }\n\n  const VectorXd::ReverseReturnType& creverse_quotient = quotient->reverse();\n  *eval = polynomial.reverse()(0) + creverse_quotient(0) * x;\n}\n\n// Perform division of a polynomial by a quadratic factor. The quadratic divisor\n// should have leading 1s.\nvoid QuadraticSyntheticDivision(const VectorXd& polynomial,\n                                const VectorXd& quadratic_divisor,\n                                VectorXd* quotient,\n                                VectorXd* remainder) {\n  CHECK_EQ(quadratic_divisor.size(), 3);\n  CHECK_GE(polynomial.size(), 3);\n\n  quotient->setZero(polynomial.size() - 2);\n  remainder->setZero(2);\n\n  (*quotient)(0) = polynomial(0);\n  // If the quotient is a constant then polynomial is degree 2 and the math is\n  // simple.\n  if (quotient->size() == 1) {\n    *remainder =\n        polynomial.tail<2>() - polynomial(0) * quadratic_divisor.tail<2>();\n    return;\n  }\n\n  (*quotient)(1) = polynomial(1) - polynomial(0) * quadratic_divisor(1);\n  for (int i = 2; i < polynomial.size() - 2; i++) {\n    (*quotient)(i) = polynomial(i) - (*quotient)(i - 2) * quadratic_divisor(2) -\n        (*quotient)(i - 1) * quadratic_divisor(1);\n  }\n\n  const VectorXd::ReverseReturnType &creverse_quotient = quotient->reverse();\n  (*remainder)(0) = polynomial.reverse()(1) -\n                    quadratic_divisor(1) * creverse_quotient(0) -\n                    quadratic_divisor(2) * creverse_quotient(1);\n  (*remainder)(1) =\n      polynomial.reverse()(0) - quadratic_divisor(2) * creverse_quotient(0);\n}\n\n// Determines whether the iteration has converged by examining the three most\n// recent values for convergence.\ntemplate<typename T>\nbool HasConverged(const T& sequence) {\n  const bool convergence_condition_1 =\n      std::abs(sequence(1) - sequence(0)) < std::abs(sequence(0)) / 2.0;\n  const bool convergence_condition_2 =\n      std::abs(sequence(2) - sequence(1)) < std::abs(sequence(1)) / 2.0;\n\n  // If the sequence has converged then return true.\n  return convergence_condition_1 && convergence_condition_2;\n}\n\n// Determines if the root has converged by measuring the relative and absolute\n// change in the root value. This stopping criterion is a simple measurement\n// that proves to work well. It is referred to as \"Ward's method\" in the\n// following reference:\n//\n// Nikolajsen, Jorgen L. \"New stopping criteria for iterative root finding.\"\n// Royal Society open science (2014)\ntemplate <typename T>\nbool HasRootConverged(const std::vector<T>& roots) {\n  static const double kRootMagnitudeTolerance = 1e-8;\n\n  if (roots.size() != 3) {\n    return false;\n  }\n\n  const double e_i = std::abs(roots[2] - roots[1]);\n  const double e_i_minus_1 = std::abs(roots[1] - roots[0]);\n  const double mag_root = std::abs(roots[1]);\n  if (e_i <= e_i_minus_1) {\n    if (mag_root < kRootMagnitudeTolerance) {\n      return e_i < kAbsoluteTolerance;\n    } else {\n      return e_i / mag_root <= kRelativeTolerance;\n    }\n  }\n\n  return false;\n}\n\n// Implementation closely follows the three-stage algorithm for finding roots of\n// polynomials with real coefficients as outlined in: \"A Three-Stage Algorithm\n// for Real Polynomaials Using Quadratic Iteration\" by Jenkins and Traub, SIAM\n// 1970. Please note that this variant is different than the complex-coefficient\n// version, and is estimated to be up to 4 times faster.\nclass JenkinsTraubSolver {\n public:\n  JenkinsTraubSolver(const VectorXd& coeffs,\n                     VectorXd* real_roots,\n                     VectorXd* complex_roots)\n      : polynomial_(coeffs),\n        real_roots_(real_roots),\n        complex_roots_(complex_roots),\n        num_solved_roots_(0) {}\n\n  // Extracts the roots using the Jenkins Traub method.\n  bool ExtractRoots();\n\n private:\n  // Removes any zero roots and divides polynomial by z.\n  void RemoveZeroRoots();\n\n  // Computes the magnitude of the roots to provide and initial search radius\n  // for the iterative solver.\n  double ComputeRootRadius();\n\n  // Computes the zero-shift applied to the K-Polynomial.\n  void ComputeZeroShiftKPolynomial();\n\n  // Stage 1 of the Jenkins-Traub method. This stage is not technically\n  // necessary, but helps separate roots that are close to zero.\n  void ApplyZeroShiftToKPolynomial(const int num_iterations);\n\n  // Computes and returns the update of sigma(z) based on the current\n  // K-polynomial.\n  //\n  // NOTE: This function is used by the fixed shift iterations (which hold sigma\n  // constant) so sigma is *not* modified internally by this function. If you\n  // want to change sigma, simply call\n  //    sigma = ComputeNextSigma();\n  VectorXd ComputeNextSigma();\n\n  // Updates the K-polynomial based on the current value of sigma for the fixed\n  // or variable shift stage.\n  void UpdateKPolynomialWithQuadraticShift(\n      const VectorXd& polynomial_quotient,\n      const VectorXd& k_polynomial_quotient);\n\n  // Apply fixed-shift iterations to the K-polynomial to separate the\n  // roots. Based on the convergence of the K-polynomial, we apply a\n  // variable-shift linear or quadratic iteration to determine a real root or\n  // complex conjugate pair of roots respectively.\n  ConvergenceType ApplyFixedShiftToKPolynomial(const std::complex<double>& root,\n                                               const int max_iterations);\n\n  // Applies one of the variable shifts to the K-Polynomial. Returns true upon\n  // successful convergence to a good root, and false otherwise.\n  bool ApplyVariableShiftToKPolynomial(\n      const ConvergenceType& fixed_shift_convergence,\n      const std::complex<double>& root);\n\n  // Applies a quadratic shift to the K-polynomial to determine a pair of roots\n  // that are complex conjugates. Return true if a root was successfully found.\n  bool ApplyQuadraticShiftToKPolynomial(const std::complex<double>& root,\n                                        const int max_iterations);\n\n  // Applies a linear shift to the K-polynomial to determine a single real root.\n  // Return true if a root was successfully found.\n  bool ApplyLinearShiftToKPolynomial(const std::complex<double>& root,\n                                     const int max_iterations);\n\n  // These methods determine whether the root finding has converged based on the\n  // machine roundoff error expected in evaluating the polynomials at the root.\n  bool HasQuadraticSequenceConverged(const VectorXd& quotient,\n                                     const std::complex<double>& root);\n  bool HasLinearSequenceConverged(const VectorXd& quotient,\n                                  const double root,\n                                  const double p_at_root);\n\n  // Adds the root to the output variables.\n  void AddRootToOutput(const double real, const double imag);\n\n  // Solves polynomials of degree <= 2.\n  bool SolveClosedFormPolynomial();\n\n  // Helper variables to manage the polynomials as they are being manipulated\n  // and deflated.\n  VectorXd polynomial_;\n  VectorXd k_polynomial_;\n  // Sigma is the quadratic factor the divides the K-polynomial.\n  Vector3d sigma_;\n\n  // Let us define a, b, c, and d such that:\n  //   P(z) = Q_P * sigma(z) + b * (z + u) + a\n  //   K(z) = Q_K * sigma(z) + d * (z + u ) + c\n  //\n  // where Q_P and Q_K are the quotients from polynomial division of\n  // sigma(z). Note that this means for a given a root s of sigma:\n  //\n  //   P(s)      = a - b * s_conj\n  //   P(s_conj) = a - b * s\n  //   K(s)      = c - d * s_conj\n  //   K(s_conj) = c - d * s\n  double a_, b_, c_, d_;\n\n  // Output reference variables.\n  VectorXd* real_roots_;\n  VectorXd* complex_roots_;\n  int num_solved_roots_;\n\n  // Keeps track of whether the linear and quadratic shifts have been attempted\n  // yet so that we do not attempt the same shift twice.\n  bool attempted_linear_shift_;\n  bool attempted_quadratic_shift_;\n\n  // Number of zero-shift iterations to perform.\n  static const int kNumZeroShiftIterations = 20;\n\n  // The number of fixed shift iterations is computed as\n  //   # roots found * this multiplier.\n  static const int kFixedShiftIterationMultiplier = 20;\n\n  // If the fixed shift iterations fail to converge, we restart this many times\n  // before considering the solve attempt as a failure.\n  static const int kMaxFixedShiftRestarts = 20;\n\n  // The maximum number of linear shift iterations to perform before considering\n  // the shift as a failure.\n  static const int kMaxLinearShiftIterations = 20;\n\n  // The maximum number of quadratic shift iterations to perform before\n  // considering the shift as a failure.\n  static const int kMaxQuadraticShiftIterations = 20;\n\n  // When quadratic shift iterations are stalling, we attempt a few fixed shift\n  // iterations to help convergence.\n  static const int kInnerFixedShiftIterations = 5;\n\n  // During quadratic iterations, the real values of the root pairs should be\n  // nearly equal since the root pairs are complex conjugates. This tolerance\n  // measures how much the real values may diverge before consider the quadratic\n  // shift to be failed.\n  const double kRootPairTolerance = 0.01;\n};\n\nbool JenkinsTraubSolver::ExtractRoots() {\n  if (polynomial_.size() == 0) {\n    LOG(ERROR) << \"Invalid polynomial of size 0 passed to \"\n                  \"FindPolynomialRootsJenkinsTraub\";\n    return false;\n  }\n\n  // Remove any leading zeros of the polynomial.\n  polynomial_ = RemoveLeadingZeros(polynomial_);\n\n  const int degree = static_cast<int>(polynomial_.size()) - 1;\n\n  // Allocate the output roots.\n  if (real_roots_ != NULL) {\n    real_roots_->setZero(degree);\n  }\n  if (complex_roots_ != NULL) {\n    complex_roots_->setZero(degree);\n  }\n\n  // Normalize the polynomial.\n  polynomial_ /= polynomial_(0);\n\n  // Remove any zero roots.\n  RemoveZeroRoots();\n\n  // Choose the initial starting value for the root-finding on the complex\n  // plane.\n  double phi = DegToRad(49.0);\n\n  // Iterate until the polynomial has been completely deflated.\n  for (int i = 0; i < degree; i++) {\n    // Compute the root radius.\n    const double root_radius = ComputeRootRadius();\n\n    // Solve in closed form if the polynomial is small enough.\n    if (polynomial_.size() <= 3) {\n      break;\n    }\n\n    // Stage 1: Apply zero-shifts to the K-polynomial to separate the small\n    // zeros of the polynomial.\n    ApplyZeroShiftToKPolynomial(kNumZeroShiftIterations);\n\n    // Stage 2: Apply fixed shift iterations to the K-polynomial to separate the\n    // roots further.\n    std::complex<double> root;\n    ConvergenceType convergence = ConvergenceType::NO_CONVERGENCE;\n    for (int j = 0; j < kMaxFixedShiftRestarts; j++) {\n      root = root_radius * std::complex<double>(std::cos(phi), std::sin(phi));\n      convergence = ApplyFixedShiftToKPolynomial(\n          root, kFixedShiftIterationMultiplier * (i + 1));\n\n      if (convergence != ConvergenceType::NO_CONVERGENCE) {\n        break;\n      }\n\n      // Rotate the initial root value on the complex plane and try again.\n      phi += DegToRad(94.0);\n    }\n\n    // Stage 3: Find the root(s) with variable shift iterations on the\n    // K-polynomial. If this stage was not successful then we return a failure.\n    if (!ApplyVariableShiftToKPolynomial(convergence, root)) {\n      return false;\n    }\n  }\n  return SolveClosedFormPolynomial();\n}\n\n// Stage 1: Generate K-polynomials with no shifts (i.e. zero-shifts).\nvoid JenkinsTraubSolver::ApplyZeroShiftToKPolynomial(\n    const int num_iterations) {\n  // K0 is the first order derivative of polynomial.\n  k_polynomial_ = DifferentiatePolynomial(polynomial_) / polynomial_.size();\n  for (int i = 1; i < num_iterations; i++) {\n    ComputeZeroShiftKPolynomial();\n  }\n}\n\nConvergenceType JenkinsTraubSolver::ApplyFixedShiftToKPolynomial(\n    const std::complex<double>& root, const int max_iterations) {\n  // Compute the fixed-shift quadratic:\n  // sigma(z) = (x - m - n * i) * (x - m + n * i) = x^2 - 2 * m + m^2 + n^2.\n  sigma_(0) = 1.0;\n  sigma_(1) = -2.0 * root.real();\n  sigma_(2) = root.real() * root.real() + root.imag() * root.imag();\n\n  // Compute the quotient and remainder for divinding P by the quadratic\n  // divisor. Since this iteration involves a fixed-shift sigma these may be\n  // computed once prior to any iterations.\n  VectorXd polynomial_quotient, polynomial_remainder;\n  QuadraticSyntheticDivision(\n      polynomial_, sigma_, &polynomial_quotient, &polynomial_remainder);\n\n  // Compute a and b from the above equations.\n  b_ = polynomial_remainder(0);\n  a_ = polynomial_remainder(1) - b_ * sigma_(1);\n\n  // Precompute P(s) for later using the equation above.\n  const std::complex<double> p_at_root = a_ - b_ * std::conj(root);\n\n  // These two containers hold values that we test for convergence such that the\n  // zero index is the convergence value from 2 iterations ago, the first\n  // index is from one iteration ago, and the second index is the current value.\n  Vector3cd t_lambda = Vector3cd::Zero();\n  Vector3d sigma_lambda = Vector3d::Zero();\n  VectorXd k_polynomial_quotient, k_polynomial_remainder;\n  for (int i = 0; i < max_iterations; i++) {\n    k_polynomial_ /= k_polynomial_(0);\n\n    // Divide the shifted polynomial by the quadratic polynomial.\n    QuadraticSyntheticDivision(\n        k_polynomial_, sigma_, &k_polynomial_quotient, &k_polynomial_remainder);\n    d_ = k_polynomial_remainder(0);\n    c_ = k_polynomial_remainder(1) - d_ * sigma_(1);\n\n    // Test for convergence.\n    const VectorXd variable_shift_sigma = ComputeNextSigma();\n    const std::complex<double> k_at_root = c_ - d_ * std::conj(root);\n\n    t_lambda.head<2>() = t_lambda.tail<2>().eval();\n    sigma_lambda.head<2>() = sigma_lambda.tail<2>().eval();\n    t_lambda(2) = root - p_at_root / k_at_root;\n    sigma_lambda(2) = variable_shift_sigma(2);\n\n    // Return with the convergence code if the sequence has converged.\n    if (HasConverged(sigma_lambda)) {\n      return ConvergenceType::QUADRATIC_CONVERGENCE;\n    } else if (HasConverged(t_lambda)) {\n      return ConvergenceType::LINEAR_CONVERGENCE;\n    }\n\n    // Compute K_next using the formula above.\n    UpdateKPolynomialWithQuadraticShift(polynomial_quotient,\n                                        k_polynomial_quotient);\n  }\n  return ConvergenceType::NO_CONVERGENCE;\n}\n\nbool JenkinsTraubSolver::ApplyVariableShiftToKPolynomial(\n    const ConvergenceType& fixed_shift_convergence,\n    const std::complex<double>& root) {\n  attempted_linear_shift_ = false;\n  attempted_quadratic_shift_ = false;\n  if (fixed_shift_convergence == ConvergenceType::LINEAR_CONVERGENCE) {\n    return ApplyLinearShiftToKPolynomial(root, kMaxLinearShiftIterations);\n  } else if (fixed_shift_convergence ==\n             ConvergenceType::QUADRATIC_CONVERGENCE) {\n    return ApplyQuadraticShiftToKPolynomial(root, kMaxQuadraticShiftIterations);\n  }\n  return false;\n}\n\n// Generate K-polynomials with variable-shifts. During variable shifts, the\n// quadratic shift is computed as:\n//                | K0(s1)  K0(s2)  z^2 |\n//                | K1(s1)  K1(s2)    z |\n//                | K2(s1)  K2(s2)    1 |\n//    sigma(z) = __________________________\n//                  | K1(s1)  K2(s1) |\n//                  | K2(s1)  K2(s2) |\n// Where K0, K1, and K2 are successive zero-shifts of the K-polynomial.\n//\n// The K-polynomial shifts are otherwise exactly the same as Stage 2 after\n// accounting for a variable-shift sigma.\nbool JenkinsTraubSolver::ApplyQuadraticShiftToKPolynomial(\n    const std::complex<double>& root, const int max_iterations) {\n  // Only proceed if we have not already tried a quadratic shift.\n  if (attempted_quadratic_shift_) {\n    return false;\n  }\n\n  const double kTinyRelativeStep = 0.01;\n\n  // Compute the fixed-shift quadratic:\n  // sigma(z) = (x - m - n * i) * (x - m + n * i) = x^2 - 2 * m + m^2 + n^2.\n  sigma_(0) = 1.0;\n  sigma_(1) = -2.0 * root.real();\n  sigma_(2) = root.real() * root.real() + root.imag() * root.imag();\n\n  // These two containers hold values that we test for convergence such that the\n  // zero index is the convergence value from 2 iterations ago, the first\n  // index is from one iteration ago, and the second index is the current value.\n  VectorXd polynomial_quotient, polynomial_remainder, k_polynomial_quotient,\n      k_polynomial_remainder;\n  double poly_at_root(0), prev_poly_at_root(0), prev_v(0);\n  bool tried_fixed_shifts = false;\n\n  // These containers maintain a history of the predicted roots. The convergence\n  // of the algorithm is determined by the convergence of the root value.\n  std::vector<std::complex<double> > roots1, roots2;\n  roots1.push_back(root);\n  roots2.push_back(std::conj(root));\n  for (int i = 0; i < max_iterations; i++) {\n    // Terminate if the root evaluation is within our tolerance. This will\n    // return false if we do not have enough samples.\n    if (HasRootConverged(roots1) && HasRootConverged(roots2)) {\n      AddRootToOutput(roots1[1].real(), roots1[1].imag());\n      AddRootToOutput(roots2[1].real(), roots2[1].imag());\n      polynomial_ = polynomial_quotient;\n      return true;\n    }\n\n    QuadraticSyntheticDivision(\n        polynomial_, sigma_, &polynomial_quotient, &polynomial_remainder);\n\n    // Compute a and b from the above equations.\n    b_ = polynomial_remainder(0);\n    a_ = polynomial_remainder(1) - b_ * sigma_(1);\n\n    // Solve for the roots of the quadratic factor sigma.\n    std::complex<double> roots[2];\n    VectorXd real, imag;\n    FindQuadraticPolynomialRoots(sigma_, &real, &imag);\n    roots[0] = std::complex<double>(real(0), imag(0));\n    roots[1] = std::complex<double>(real(1), imag(1));\n\n    // Check that the roots are close. If not, then try a linear shift.\n    if (std::abs(std::abs(roots[0].real()) - std::abs(roots[1].real())) >\n        kRootPairTolerance * std::abs(roots[1].real())) {\n      return ApplyLinearShiftToKPolynomial(root, kMaxLinearShiftIterations);\n    }\n\n    // If the iteration is stalling at a root pair then apply a few fixed shift\n    // iterations to help convergence.\n    poly_at_root =\n        std::abs(a_ - roots[0].real() * b_) + std::abs(roots[0].imag() * b_);\n    const double rel_step = std::abs((sigma_(2) - prev_v) / sigma_(2));\n    if (!tried_fixed_shifts && rel_step < kTinyRelativeStep &&\n        prev_poly_at_root > poly_at_root) {\n      tried_fixed_shifts = true;\n      ApplyFixedShiftToKPolynomial(roots[0], kInnerFixedShiftIterations);\n    }\n\n    // Divide the shifted polynomial by the quadratic polynomial.\n    QuadraticSyntheticDivision(\n        k_polynomial_, sigma_, &k_polynomial_quotient, &k_polynomial_remainder);\n    d_ = k_polynomial_remainder(0);\n    c_ = k_polynomial_remainder(1) - d_ * sigma_(1);\n\n    prev_v = sigma_(2);\n    sigma_ = ComputeNextSigma();\n\n    // Compute K_next using the formula above.\n    UpdateKPolynomialWithQuadraticShift(polynomial_quotient,\n                                        k_polynomial_quotient);\n    k_polynomial_ /= k_polynomial_(0);\n    prev_poly_at_root = poly_at_root;\n\n    // Save the roots for convergence testing.\n    roots1.push_back(roots[0]);\n    roots2.push_back(roots[1]);\n    if (roots1.size() > 3) {\n      roots1.erase(roots1.begin());\n      roots2.erase(roots2.begin());\n    }\n  }\n\n  attempted_quadratic_shift_ = true;\n  return ApplyLinearShiftToKPolynomial(root, kMaxLinearShiftIterations);\n}\n\n// Generate K-Polynomials with variable-shifts that are linear. The shift is\n// computed as:\n//   K_next(z) = 1 / (z - s) * (K(z) - K(s) / P(s) * P(z))\n//   s_next = s - P(s) / K_next(s)\nbool JenkinsTraubSolver::ApplyLinearShiftToKPolynomial(\n    const std::complex<double>& root, const int max_iterations) {\n  if (attempted_linear_shift_) {\n    return false;\n  }\n\n  // Compute an initial guess for the root.\n  double real_root = (root -\n                      EvaluatePolynomial(polynomial_, root) /\n                      EvaluatePolynomial(k_polynomial_, root)).real();\n\n  VectorXd deflated_polynomial, deflated_k_polynomial;\n  double polynomial_at_root(0), k_polynomial_at_root(0);\n\n  // This container maintains a history of the predicted roots. The convergence\n  // of the algorithm is determined by the convergence of the root value.\n  std::vector<double> roots;\n  roots.push_back(real_root);\n  for (int i = 0; i < max_iterations; i++) {\n    // Terminate if the root evaluation is within our tolerance. This will\n    // return false if we do not have enough samples.\n    if (HasRootConverged(roots)) {\n      AddRootToOutput(roots[1], 0);\n      polynomial_ = deflated_polynomial;\n      return true;\n    }\n\n    const double prev_polynomial_at_root = polynomial_at_root;\n    SyntheticDivisionAndEvaluate(\n        polynomial_, real_root, &deflated_polynomial, &polynomial_at_root);\n\n    // If the root is exactly the root then end early. Otherwise, the k\n    // polynomial will be filled with inf or nans.\n    if (std::abs(polynomial_at_root) <= kAbsoluteTolerance) {\n      AddRootToOutput(roots[0], 0);\n      polynomial_ = deflated_polynomial;\n      return true;\n    }\n\n    // Update the K-Polynomial.\n    SyntheticDivisionAndEvaluate(k_polynomial_, real_root,\n                                 &deflated_k_polynomial, &k_polynomial_at_root);\n    k_polynomial_ = AddPolynomials(\n        deflated_k_polynomial,\n        -k_polynomial_at_root / polynomial_at_root * deflated_polynomial);\n    k_polynomial_ /= k_polynomial_(0);\n\n    // Compute the update for the root estimation.\n    k_polynomial_at_root = EvaluatePolynomial(k_polynomial_, real_root);\n    const double delta_root = polynomial_at_root / k_polynomial_at_root;\n    real_root -= delta_root;\n\n    // Save the root so that convergence can be measured. Only the 3 most\n    // recently root values are needed.\n    roots.push_back(real_root);\n    if (roots.size() > 3) {\n      roots.erase(roots.begin());\n    }\n\n    // If the linear iterations appear to be stalling then we may have found a\n    // double real root of the form (z - x^2). Attempt a quadratic variable\n    // shift from the current estimate of the root.\n    if (i >= 2 &&\n        std::abs(delta_root) < 0.001 * std::abs(real_root) &&\n        std::abs(prev_polynomial_at_root) < std::abs(polynomial_at_root)) {\n      const std::complex<double> new_root(real_root, 0);\n      return ApplyQuadraticShiftToKPolynomial(new_root,\n                                              kMaxQuadraticShiftIterations);\n    }\n  }\n\n  attempted_linear_shift_ = true;\n  return ApplyQuadraticShiftToKPolynomial(root, kMaxQuadraticShiftIterations);\n}\n\nbool JenkinsTraubSolver::HasQuadraticSequenceConverged(\n    const VectorXd& quotient, const std::complex<double>& root) {\n  const double z = std::sqrt(std::abs(sigma_(2)));\n  const double t = -root.real() * b_;\n\n  double e = 2.0 * std::abs(quotient(0));\n  for (int i = 1; i < quotient.size(); i++) {\n    e = e * z + std::abs(quotient(i));\n  }\n  e = e * z + std::abs(a_ + t);\n  e *= 5.0 * mult_eps + 4.0 * sum_eps;\n  e = e -\n      (5.0 * mult_eps + 2.0 * sum_eps) * (std::abs(a_ + t) + std::abs(b_) * z);\n  e = e + 2.0 * sum_eps * std::abs(t);\n  return std::abs(a_ - b_ * root) < e;\n}\n\nbool JenkinsTraubSolver::HasLinearSequenceConverged(const VectorXd& quotient,\n                                                    const double root,\n                                                    const double p_at_root) {\n  double e = std::abs(quotient(0)) * mult_eps / (sum_eps + mult_eps);\n  const double abs_root = std::abs(root);\n  for (int i = 0; i < quotient.size(); i++) {\n    e = e * abs_root + std::abs(quotient(i));\n  }\n  const double machine_precision =\n      (sum_eps + mult_eps) * e - mult_eps * std::abs(p_at_root);\n  return std::abs(p_at_root) < machine_precision;\n}\n\nvoid JenkinsTraubSolver::AddRootToOutput(const double real, const double imag) {\n  if (real_roots_ != NULL) {\n    (*real_roots_)(num_solved_roots_) = real;\n  }\n  if (complex_roots_ != NULL) {\n    (*complex_roots_)(num_solved_roots_) = imag;\n  }\n  ++num_solved_roots_;\n}\n\nvoid JenkinsTraubSolver::RemoveZeroRoots() {\n  int num_zero_roots = 0;\n\n  const VectorXd::ReverseReturnType& creverse_polynomial =\n      polynomial_.reverse();\n  while (creverse_polynomial(num_zero_roots) == 0) {\n    ++num_zero_roots;\n  }\n\n  // The output roots have 0 as the default value so there is no need to\n  // explicitly add the zero roots.\n  polynomial_ = polynomial_.head(polynomial_.size() - num_zero_roots).eval();\n}\n\nbool JenkinsTraubSolver::SolveClosedFormPolynomial() {\n  const int degree = static_cast<int>(polynomial_.size()) - 1;\n\n  // Is the polynomial constant?\n  if (degree == 0) {\n    LOG(WARNING) << \"Trying to extract roots from a constant \"\n                 << \"polynomial in FindPolynomialRoots\";\n    // We return true with no roots, not false, as if the polynomial is constant\n    // it is correct that there are no roots. It is not the case that they were\n    // there, but that we have failed to extract them.\n    return true;\n  }\n\n  // Linear\n  if (degree == 1) {\n    AddRootToOutput(-polynomial_(1) / polynomial_(0), 0);\n    return true;\n  }\n\n  // Quadratic\n  if (degree == 2) {\n    VectorXd real, imaginary;\n    FindQuadraticPolynomialRoots(polynomial_, &real, &imaginary);\n    AddRootToOutput(real(0), imaginary(0));\n    AddRootToOutput(real(1), imaginary(1));\n    return true;\n  }\n\n  return false;\n}\n\n// Computes a lower bound on the radius of the roots of polynomial by examining\n// the Cauchy sequence:\n//\n//    z^n + |a_1| * z^{n - 1} + ... + |a_{n-1}| * z - |a_n|\n//\n// The unique positive zero of this polynomial is an approximate lower bound of\n// the radius of zeros of the original polynomial.\ndouble JenkinsTraubSolver::ComputeRootRadius() {\n  static const double kEpsilon = 1e-2;\n  static const int kMaxIterations = 100;\n\n  VectorXd poly = polynomial_;\n  // Take the absolute value of all coefficients.\n  poly = poly.array().abs();\n  // Negate the last coefficient.\n  poly(poly.size() - 1) *= -1.0;\n\n  // Find the unique positive zero using Newton-Raphson iterations.\n  double x0 = 1.0;\n  return FindRootIterativeNewton(poly, x0, kEpsilon, kMaxIterations);\n}\n\n// The k polynomial with a zero-shift is\n//  (K(x) - K(0) / P(0) * P(x)) / x.\n//\n// This is equivalent to:\n//    K(x) - K(0)      K(0)     P(x) - P(0)\n//    ___________   -  ____  *  ___________\n//         x           P(0)          x\n//\n// Note that removing the constant term and dividing by x is equivalent to\n// shifting the polynomial to one degree lower in our representation.\nvoid JenkinsTraubSolver::ComputeZeroShiftKPolynomial() {\n  // Evaluating the polynomial at zero is equivalent to the constant term\n  // (i.e. the last coefficient).\n  const double polynomial_at_zero = polynomial_(polynomial_.size() - 1);\n  const double k_at_zero = k_polynomial_(k_polynomial_.size() - 1);\n\n  k_polynomial_ = AddPolynomials(k_polynomial_.head(k_polynomial_.size() - 1),\n                                 -k_at_zero / polynomial_at_zero *\n                                 polynomial_.head(polynomial_.size() - 1));\n}\n\n// The iterations are computed with the following equation:\n//              a^2 + u * a * b + v * b^2\n//   K_next =  ___________________________ * Q_K\n//                    b * c - a * d\n//\n//                      a * c + u * a * d + v * b * d\n//             +  (z - _______________________________) * Q_P + b.\n//                              b * c - a * d\n//\n// This is done using *only* realy arithmetic so it can be done very fast!\nvoid JenkinsTraubSolver::UpdateKPolynomialWithQuadraticShift(\n    const VectorXd& polynomial_quotient,\n    const VectorXd& k_polynomial_quotient) {\n  const double coefficient_q_k =\n      (a_ * a_ + sigma_(1) * a_ * b_ + sigma_(2) * b_ * b_) /\n      (b_ * c_ - a_ * d_);\n  VectorXd linear_polynomial(2);\n  linear_polynomial(0) = 1.0;\n  linear_polynomial(1) =\n      -(a_ * c_ + sigma_(1) * a_ * d_ + sigma_(2) * b_ * d_) /\n      (b_ * c_ - a_ * d_);\n  k_polynomial_ = AddPolynomials(\n      coefficient_q_k * k_polynomial_quotient,\n      MultiplyPolynomials(linear_polynomial, polynomial_quotient));\n\n  k_polynomial_(k_polynomial_.size() - 1) += b_;\n}\n\n// Using a bit of algebra, the update of sigma(z) can be computed from the\n// previous value along with a, b, c, and d defined above. The details of this\n// simplification can be found in \"Three Stage Variable-Shift Iterations for the\n// Solution of Polynomial Equations With a Posteriori Error Bounds for the\n// Zeros\" by M.A. Jenkins, Doctoral Thesis, Stanford Univeristy, 1969.\n//\n// NOTE: we assume the leading term of quadratic_sigma is 1.0.\nVectorXd JenkinsTraubSolver::ComputeNextSigma() {\n  const double u = sigma_(1);\n  const double v = sigma_(2);\n  const VectorXd::ReverseReturnType& creverse_k_polynomial =\n      k_polynomial_.reverse();\n  const VectorXd::ReverseReturnType& creverse_polynomial =\n      polynomial_.reverse();\n\n  const double b1 = -creverse_k_polynomial(0) / creverse_polynomial(0);\n  const double b2 = -(creverse_k_polynomial(1) + b1 * creverse_polynomial(1)) /\n                    creverse_polynomial(0);\n\n  const double a1 = b_* c_ - a_ * d_;\n  const double a2 = a_ * c_ + u * a_ * d_ + v * b_* d_;\n  const double c2 = b1 * a2;\n  const double c3 = b1 * b1 * (a_ * a_ + u * a_ * b_ + v * b_ * b_);\n  const double c4 = v * b2 * a1 - c2 - c3;\n  const double c1 = c_ * c_ + u * c_ * d_ + v * d_ * d_ +\n                    b1 * (a_ * c_ + u * b_ * c_ + v * b_ * d_) - c4;\n  const double delta_u = -(u * (c2 + c3) + v * (b1 * a1 + b2 * a2)) / c1;\n  const double delta_v = v * c4 / c1;\n\n  // Update u and v in the quadratic sigma.\n  VectorXd new_quadratic_sigma(3);\n  new_quadratic_sigma(0) = 1.0;\n  new_quadratic_sigma(1) = u + delta_u;\n  new_quadratic_sigma(2) = v + delta_v;\n  return new_quadratic_sigma;\n}\n\n}  // namespace\n\nbool FindPolynomialRootsJenkinsTraub(const VectorXd& polynomial,\n                                     VectorXd* real_roots,\n                                     VectorXd* complex_roots) {\n  JenkinsTraubSolver solver(polynomial, real_roots, complex_roots);\n  return solver.ExtractRoots();\n}\n\n}  // namespace theia\n", "meta": {"hexsha": "cd0b670932a52c53879f154c47c3d0985f9685ac", "size": 32889, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/math/find_polynomial_roots_jenkins_traub.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": "src/theia/math/find_polynomial_roots_jenkins_traub.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": "src/theia/math/find_polynomial_roots_jenkins_traub.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": 38.6021126761, "max_line_length": 80, "alphanum_fraction": 0.6772173067, "num_tokens": 8557, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.46990387783988063}}
{"text": "//Link to Boost\n #define BOOST_TEST_DYN_LINK\n\n//VERY IMPORTANT - include this last\n#include <boost/test/unit_test.hpp>\n\n#include <cmath>\n#include <boost/math/special_functions/gamma.hpp>\n#include \"test.h\"\n#include \"../common.h\"\n#include \"../CftData.h\"\n\nBOOST_FIXTURE_TEST_SUITE(CftData_suite, SimpleTestFixture, * utf::label(\"CftData\"))\n\nBOOST_DATA_TEST_CASE(CftData_construct_test, CreateCfgConfigTestData(TCNumber), cfg)\n{\n    CftData data(cfg);\n    BOOST_TEST(data.D == cfg.D);\n    BOOST_TEST(data.MaxPrimaryId() == Sum(cfg.OperatorNumbers));\n    BOOST_TEST(data.MaxScalarId() == cfg.OperatorNumbers[0]);\n\n    int stressTensorId = data.StressTensorId;\n    BOOST_TEST(data.GetPrimaryInfo(stressTensorId).Spin == 2);\n    BOOST_TEST(data.GetPrimaryInfo(stressTensorId).Dim == cfg.D);\n\n    float_type Pi = acos(-1.0);\n    for (int i = 1; i <= data.MaxScalarId(); i++) {\n        MY_FLOAT_EQUAL(data.GetOpeCoefficient(i, i, 0), 1.0, tol);\n\n        float_type prefactor = - data.D * data.GetPrimaryDim(i) / (data.D - 1);\n        float_type sd = 2 * pow(Pi, data.D/2.0) / boost::math::tgamma<float_type>(data.D/2.0);\n        MY_FLOAT_EQUAL(data.GetOpeCoefficient(i, i, data.StressTensorId), prefactor / sd, tol);\n    \n        for (int j = i + 1; j <= data.MaxScalarId(); j++) {\n            BOOST_TEST(data.GetOpeCoefficient(i, j, 0) == 0.0);\n            BOOST_TEST(data.GetOpeCoefficient(i, j, data.StressTensorId) == 0.0);\n        }\n    }\n}\n\nBOOST_DATA_TEST_CASE(CftData_SaveLoad_test, CreateCfgConfigTestData(TCNumber) ^ bdata::xrange(TCNumber), cfg, index)\n{\n    CftData data(cfg);\n\n    string file = \"CftData_SaveLoad_test\" + ToString(index) + \".txt\";\n    data.Save(file);\n\n    CftData data2;\n    data2.LoadFromFile(file);\n\n    BOOST_TEST(data2.D == data.D);\n    BOOST_TEST(data2.StressTensorId == data.StressTensorId);\n    BOOST_TEST(data2.MaxPrimaryId() == data.MaxPrimaryId());\n    BOOST_TEST(data2.MaxScalarId() == data.MaxScalarId());\n\n    for (int i = 0; i <= data.MaxPrimaryId(); i++) {\n        BOOST_TEST(data2.GetPrimarySpin(i) == data.GetPrimarySpin(i));\n        MY_FLOAT_EQUAL(data2.GetPrimaryDim(i), data.GetPrimaryDim(i), tol);\n    }\n\n    for (int i = 1; i <= data.MaxScalarId(); i++) {\n        for (int j = i; j <= data.MaxScalarId(); j++) {\n            MY_FLOAT_EQUAL(data2.GetOpeCoefficient(i, j, 0), data.GetOpeCoefficient(i, j, 0), tol);\n        }\n    }\n\n    for (int i = 1; i <= data.MaxScalarId(); i++) {\n        for (int j = i; j <= data.MaxScalarId(); j++) {\n            for (int k = j; k <= data.MaxPrimaryId(); k++) {\n                BOOST_TEST_INFO(\"i=\" << i << \", j=\" << j << \", k=\" << k);\n                MY_FLOAT_EQUAL(data2.GetOpeCoefficient(i, j, k), data.GetOpeCoefficient(i, j, k), tol);\n            }\n        }\n    }\n\n}\n\nBOOST_DATA_TEST_CASE(CftData_PrimaryNumber_test, CreateCfgConfigTestData(TCNumber), cfg)\n{\n    CftData data(cfg);\n    for (int i = 0; i < cfg.OperatorNumbers.size(); i++) {\n        BOOST_TEST(data.PrimaryNumber(i) == cfg.OperatorNumbers[i]);\n    }\n}\n\nBOOST_DATA_TEST_CASE(CftData_GetSetPrimaryInfo_test, CreateCfgConfigTestData(TCNumber), cfg)\n{\n    CftData data(cfg);\n    int id = cfg.OperatorNumbers[0] + randomint(1, cfg.OperatorNumbers[1]);\n    double dim = random(2.0, 4.0);\n\n    data.SetPrimaryDim(id, dim);\n    PrimaryInfo info = data.GetPrimaryInfo(id);\n\n    BOOST_TEST(info.Id == id);\n    BOOST_TEST(info.Spin == 1);\n    MY_FLOAT_EQUAL(info.Dim, dim, tol);\n}\n\nBOOST_DATA_TEST_CASE(CftData_GetSetOpeCoefficient_test, CreateCfgConfigTestData(TCNumber), cfg)\n{\n    CftData data(cfg);\n    int id1 = randomint(0, data.MaxPrimaryId());\n    int id2 = randomint(0, data.MaxPrimaryId());\n    int id3 = randomint(0, data.MaxPrimaryId());\n    float_type expect = random(-2.0, 2.0);\n\n    data.SetOpeCoefficient(id1, id2, id3, expect);\n    float_type actual = data.GetOpeCoefficient(id2, id3, id1);\n    MY_FLOAT_EQUAL(actual, expect, tol);\n}\n\n// test suite end\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "bccc215756a07a735ecc5eaa4709831af245fda0", "size": 3938, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/CftDataTests.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/test/CftDataTests.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/test/CftDataTests.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": 34.2434782609, "max_line_length": 116, "alphanum_fraction": 0.6503301168, "num_tokens": 1120, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.754914997895581, "lm_q2_score": 0.6224593171945416, "lm_q1q2_score": 0.4699038741300022}}
{"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_FUNCTION_IROUND_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_IROUND_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-arithmetic\n    Function object implementing iround capabilities\n\n    Computes the integer conversion of the round of its parameter.\n\n    @par semantic:\n    For any given value @c x of type @c T:\n\n    @code\n    as_integer_t<T> r = iround(x);\n    @endcode\n\n    is similar to:\n\n    @code\n    as_integer_t<T> r = toints(round(x));\n    @endcode\n\n  **/\n  const boost::dispatch::functor<tag::iround_> iround = {};\n} }\n#endif\n\n#include <boost/simd/function/scalar/iround.hpp>\n#include <boost/simd/function/simd/iround.hpp>\n\n#endif\n", "meta": {"hexsha": "fc53815799e9bea4f74a95ee964b316f9c85921a", "size": 1131, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/iround.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/function/iround.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/function/iround.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": 23.5625, "max_line_length": 100, "alphanum_fraction": 0.58443855, "num_tokens": 249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.46989940177440725}}
{"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    testBayesTree.cpp\n * @brief   Unit tests for Bayes Tree\n * @author  Frank Dellaert\n * @author  Michael Kaess\n * @author  Viorela Ila\n */\n\n#include <boost/assign/std/list.hpp> // for operator +=\n#include <boost/assign/std/vector.hpp>\n#include <boost/assign/list_of.hpp>\nusing namespace boost::assign;\n\n#include <CppUnitLite/TestHarness.h>\n#include <gtsam/base/TestableAssertions.h>\n\n#include <gtsam/inference/SymbolicFactorGraph.h>\n#include <gtsam/inference/BayesTree-inl.h>\n#include <gtsam/inference/IndexFactor.h>\n#include <gtsam/inference/SymbolicSequentialSolver.h>\n\nusing namespace std;\nusing namespace gtsam;\n\n///* ************************************************************************* */\n//// SLAM example from RSS sqrtSAM paper\nstatic const Index _x3_=0, _x2_=1;\n//static const Index _x1_=2, _l2_=3, _l1_=4; // unused\n//IndexConditional::shared_ptr\n//\t\tx3(new IndexConditional(_x3_)),\n//\t\tx2(new IndexConditional(_x2_,_x3_)),\n//\t\tx1(new IndexConditional(_x1_,_x2_,_x3_)),\n//\t\tl1(new IndexConditional(_l1_,_x1_,_x2_)),\n//\t\tl2(new IndexConditional(_l2_,_x1_,_x3_));\n//\n//// Bayes Tree for sqrtSAM example\n//SymbolicBayesTree createSlamSymbolicBayesTree(){\n//\t// Create using insert\n////\tOrdering slamOrdering; slamOrdering += _x3_, _x2_, _x1_, _l2_, _l1_;\n//\tSymbolicBayesTree bayesTree_slam;\n//\tbayesTree_slam.insert(x3);\n//\tbayesTree_slam.insert(x2);\n//\tbayesTree_slam.insert(x1);\n//\tbayesTree_slam.insert(l2);\n//\tbayesTree_slam.insert(l1);\n//\treturn bayesTree_slam;\n//}\n\n/* ************************************************************************* */\n// Conditionals for ASIA example from the tutorial with A and D evidence\nstatic const Index _X_=0, _T_=1, _S_=2, _E_=3, _L_=4, _B_=5;\nstatic IndexConditional::shared_ptr\n\tB(new IndexConditional(_B_)),\n\tL(new IndexConditional(_L_, _B_)),\n\tE(new IndexConditional(_E_, _L_, _B_)),\n\tS(new IndexConditional(_S_, _L_, _B_)),\n\tT(new IndexConditional(_T_, _E_, _L_)),\n\tX(new IndexConditional(_X_, _E_));\n\n// Cliques\nstatic IndexConditional::shared_ptr\n  ELB(IndexConditional::FromKeys(cref_list_of<3>(_E_)(_L_)(_B_), 3));\n\n// Bayes Tree for Asia example\nstatic SymbolicBayesTree createAsiaSymbolicBayesTree() {\n\tSymbolicBayesTree bayesTree;\n//\tOrdering asiaOrdering; asiaOrdering += _X_, _T_, _S_, _E_, _L_, _B_;\n\tSymbolicBayesTree::insert(bayesTree, B);\n\tSymbolicBayesTree::insert(bayesTree, L);\n\tSymbolicBayesTree::insert(bayesTree, E);\n\tSymbolicBayesTree::insert(bayesTree, S);\n\tSymbolicBayesTree::insert(bayesTree, T);\n\tSymbolicBayesTree::insert(bayesTree, X);\n\treturn bayesTree;\n}\n\n/* ************************************************************************* */\nTEST( BayesTree, constructor )\n{\n\t// Create using insert\n\tSymbolicBayesTree bayesTree = createAsiaSymbolicBayesTree();\n\n\t// Check Size\n\tLONGS_EQUAL(4,bayesTree.size());\n\n\t// Check root\n\tboost::shared_ptr<IndexConditional> actual_root = bayesTree.root()->conditional();\n\tCHECK(assert_equal(*ELB,*actual_root));\n\n\t// Create from symbolic Bayes chain in which we want to discover cliques\n\tBayesNet<IndexConditional> ASIA;\n\tASIA.push_back(X);\n\tASIA.push_back(T);\n\tASIA.push_back(S);\n\tASIA.push_back(E);\n\tASIA.push_back(L);\n\tASIA.push_back(B);\n\tSymbolicBayesTree bayesTree2(ASIA);\n\n\t// Check whether the same\n\tCHECK(assert_equal(bayesTree,bayesTree2));\n\n\t// CHECK findParentClique, should *not depend on order of parents*\n//\tOrdering ordering; ordering += _X_, _T_, _S_, _E_, _L_, _B_;\n//\tIndexTable<Symbol> index(ordering);\n\n\tlist<Index> parents1; parents1 += _E_, _L_;\n\tCHECK(assert_equal(_E_, bayesTree.findParentClique(parents1)));\n\n\tlist<Index> parents2; parents2 += _L_, _E_;\n\tCHECK(assert_equal(_E_, bayesTree.findParentClique(parents2)));\n\n\tlist<Index> parents3; parents3 += _L_, _B_;\n\tCHECK(assert_equal(_L_, bayesTree.findParentClique(parents3)));\n}\n\n/* ************************************************************************* */\nTEST(BayesTree, clear)\n{\n//\tSymbolicBayesTree bayesTree = createAsiaSymbolicBayesTree();\n//\tbayesTree.clear();\n//\n//\tSymbolicBayesTree expected;\n//\n//\t// Check whether cleared BayesTree is equal to a new BayesTree\n//\tCHECK(assert_equal(expected, bayesTree));\n}\n\n/* ************************************************************************* *\nBayes Tree for testing conversion to a forest of orphans needed for incremental.\n       A,B\n   C|A    E|B\n   D|C    F|E\n   */\n/* ************************************************************************* */\nTEST( BayesTree, removePath )\n{\n  const Index _A_=5, _B_=4, _C_=3, _D_=2, _E_=1, _F_=0;\n\tIndexConditional::shared_ptr\n\t\t\tA(new IndexConditional(_A_)),\n\t\t\tB(new IndexConditional(_B_, _A_)),\n\t\t\tC(new IndexConditional(_C_, _A_)),\n\t\t\tD(new IndexConditional(_D_, _C_)),\n\t\t\tE(new IndexConditional(_E_, _B_)),\n\t\t\tF(new IndexConditional(_F_, _E_));\n\tSymbolicBayesTree bayesTree;\n//\tOrdering ord; ord += _A_,_B_,_C_,_D_,_E_,_F_;\n\tSymbolicBayesTree::insert(bayesTree, A);\n\tSymbolicBayesTree::insert(bayesTree, B);\n\tSymbolicBayesTree::insert(bayesTree, C);\n\tSymbolicBayesTree::insert(bayesTree, D);\n\tSymbolicBayesTree::insert(bayesTree, E);\n\tSymbolicBayesTree::insert(bayesTree, F);\n\n\t// remove C, expected outcome: factor graph with ABC,\n\t// Bayes Tree now contains two orphan trees: D|C and E|B,F|E\n\tSymbolicFactorGraph expected;\n\texpected.push_factor(_B_,_A_);\n//\texpected.push_factor(_A_);\n\texpected.push_factor(_C_,_A_);\n\tSymbolicBayesTree::Cliques expectedOrphans;\n  expectedOrphans += bayesTree[_D_], bayesTree[_E_];\n\n  BayesNet<IndexConditional> bn;\n\tSymbolicBayesTree::Cliques orphans;\n\tbayesTree.removePath(bayesTree[_C_], bn, orphans);\n\tSymbolicFactorGraph factors(bn);\n  CHECK(assert_equal((SymbolicFactorGraph)expected, factors));\n  CHECK(assert_equal(expectedOrphans, orphans));\n\n  // remove E: factor graph with EB; E|B removed from second orphan tree\n\tSymbolicFactorGraph expected2;\n  expected2.push_factor(_E_,_B_);\n  SymbolicBayesTree::Cliques expectedOrphans2;\n  expectedOrphans2 += bayesTree[_F_];\n\n  BayesNet<IndexConditional> bn2;\n\tSymbolicBayesTree::Cliques orphans2;\n  bayesTree.removePath(bayesTree[_E_], bn2, orphans2);\n  SymbolicFactorGraph factors2(bn2);\n  CHECK(assert_equal((SymbolicFactorGraph)expected2, factors2));\n  CHECK(assert_equal(expectedOrphans2, orphans2));\n}\n\n/* ************************************************************************* */\nTEST( BayesTree, removePath2 )\n{\n\tSymbolicBayesTree bayesTree = createAsiaSymbolicBayesTree();\n\n\t// Call remove-path with clique B\n\tBayesNet<IndexConditional> bn;\n\tSymbolicBayesTree::Cliques orphans;\n  bayesTree.removePath(bayesTree[_B_], bn, orphans);\n\tSymbolicFactorGraph factors(bn);\n\n\t// Check expected outcome\n\tSymbolicFactorGraph expected;\n\texpected.push_factor(_E_,_L_,_B_);\n//\texpected.push_factor(_L_,_B_);\n//\texpected.push_factor(_B_);\n  CHECK(assert_equal(expected, factors));\n\tSymbolicBayesTree::Cliques expectedOrphans;\n  expectedOrphans += bayesTree[_S_], bayesTree[_T_], bayesTree[_X_];\n  CHECK(assert_equal(expectedOrphans, orphans));\n}\n\n/* ************************************************************************* */\nTEST( BayesTree, removePath3 )\n{\n\tSymbolicBayesTree bayesTree = createAsiaSymbolicBayesTree();\n\n\t// Call remove-path with clique S\n\tBayesNet<IndexConditional> bn;\n\tSymbolicBayesTree::Cliques orphans;\n  bayesTree.removePath(bayesTree[_S_], bn, orphans);\n\tSymbolicFactorGraph factors(bn);\n\n\t// Check expected outcome\n\tSymbolicFactorGraph expected;\n\texpected.push_factor(_E_,_L_,_B_);\n//\texpected.push_factor(_L_,_B_);\n//\texpected.push_factor(_B_);\n\texpected.push_factor(_S_,_L_,_B_);\n  CHECK(assert_equal(expected, factors));\n\tSymbolicBayesTree::Cliques expectedOrphans;\n  expectedOrphans += bayesTree[_T_], bayesTree[_X_];\n  CHECK(assert_equal(expectedOrphans, orphans));\n}\n\nvoid getAllCliques(const SymbolicBayesTree::sharedClique& subtree, SymbolicBayesTree::Cliques& cliques)\t{\n\t// Check if subtree exists\n\tif (subtree) {\n\t\tcliques.push_back(subtree);\n\t\t// Recursive call over all child cliques\n\t\tBOOST_FOREACH(SymbolicBayesTree::sharedClique& childClique, subtree->children()) {\n\t\t\tgetAllCliques(childClique,cliques);\n\t\t}\n\t}\n}\n\n/* ************************************************************************* */\nTEST( BayesTree, shortcutCheck )\n{\n  const Index _A_=6, _B_=5, _C_=4, _D_=3, _E_=2, _F_=1, _G_=0;\n\tIndexConditional::shared_ptr\n\t\t\tA(new IndexConditional(_A_)),\n\t\t\tB(new IndexConditional(_B_, _A_)),\n\t\t\tC(new IndexConditional(_C_, _A_)),\n\t\t\tD(new IndexConditional(_D_, _C_)),\n\t\t\tE(new IndexConditional(_E_, _B_)),\n\t\t\tF(new IndexConditional(_F_, _E_)),\n\t\t\tG(new IndexConditional(_G_, _F_));\n\tSymbolicBayesTree bayesTree;\n//\tOrdering ord; ord += _A_,_B_,_C_,_D_,_E_,_F_;\n\tSymbolicBayesTree::insert(bayesTree, A);\n\tSymbolicBayesTree::insert(bayesTree, B);\n\tSymbolicBayesTree::insert(bayesTree, C);\n\tSymbolicBayesTree::insert(bayesTree, D);\n\tSymbolicBayesTree::insert(bayesTree, E);\n\tSymbolicBayesTree::insert(bayesTree, F);\n\tSymbolicBayesTree::insert(bayesTree, G);\n\n\t//bayesTree.print(\"BayesTree\");\n\t//bayesTree.saveGraph(\"BT1.dot\");\n\n\tSymbolicBayesTree::sharedClique rootClique= bayesTree.root();\n\t//rootClique->printTree();\n\tSymbolicBayesTree::Cliques allCliques;\n\tgetAllCliques(rootClique,allCliques);\n\n\tBayesNet<IndexConditional> bn;\n\tBOOST_FOREACH(SymbolicBayesTree::sharedClique& clique, allCliques) {\n\t\t//clique->print(\"Clique#\");\n\t\tbn = clique->shortcut(rootClique, &EliminateSymbolic);\n\t\t//bn.print(\"Shortcut:\\n\");\n\t\t//cout << endl;\n\t}\n\n\t// Check if all the cached shortcuts are cleared\n\trootClique->deleteCachedShorcuts();\n\tBOOST_FOREACH(SymbolicBayesTree::sharedClique& clique, allCliques) {\n\t\tbool notCleared = clique->cachedShortcut();\n\t\tCHECK( notCleared == false);\n\t}\n\n//\tBOOST_FOREACH(SymbolicBayesTree::sharedClique& clique, allCliques) {\n//\t\tclique->print(\"Clique#\");\n//\t\tif(clique->cachedShortcut()){\n//\t\t\tbn = clique->cachedShortcut().get();\n//\t\t\tbn.print(\"Shortcut:\\n\");\n//\t\t}\n//\t\telse\n//\t\t\tcout << \"Not Initialized\" << endl;\n//\t\tcout << endl;\n//\t}\n}\n\n\n\n/* ************************************************************************* */\nTEST( BayesTree, removeTop )\n{\n\tSymbolicBayesTree bayesTree = createAsiaSymbolicBayesTree();\n\n\t// create a new factor to be inserted\n\tboost::shared_ptr<IndexFactor> newFactor(new IndexFactor(_S_,_B_));\n\n\t// Remove the contaminated part of the Bayes tree\n\tBayesNet<IndexConditional> bn;\n\tSymbolicBayesTree::Cliques orphans;\n\tlist<Index> keys; keys += _B_,_S_;\n\tbayesTree.removeTop(keys, bn, orphans);\n\tSymbolicFactorGraph factors(bn);\n\n\t// Check expected outcome\n\tSymbolicFactorGraph expected;\n\texpected.push_factor(_E_,_L_,_B_);\n//\texpected.push_factor(_L_,_B_);\n//\texpected.push_factor(_B_);\n\texpected.push_factor(_S_,_L_,_B_);\n  CHECK(assert_equal(expected, factors));\n\tSymbolicBayesTree::Cliques expectedOrphans;\n  expectedOrphans += bayesTree[_T_], bayesTree[_X_];\n  CHECK(assert_equal(expectedOrphans, orphans));\n\n  // Try removeTop again with a factor that should not change a thing\n\tboost::shared_ptr<IndexFactor> newFactor2(new IndexFactor(_B_));\n\tBayesNet<IndexConditional> bn2;\n\tSymbolicBayesTree::Cliques orphans2;\n\tkeys.clear(); keys += _B_;\n\tbayesTree.removeTop(keys, bn2, orphans2);\n\tSymbolicFactorGraph factors2(bn2);\n\tSymbolicFactorGraph expected2;\n  CHECK(assert_equal(expected2, factors2));\n\tSymbolicBayesTree::Cliques expectedOrphans2;\n  CHECK(assert_equal(expectedOrphans2, orphans2));\n}\n\n/* ************************************************************************* */\nTEST( BayesTree, removeTop2 )\n{\n\tSymbolicBayesTree bayesTree = createAsiaSymbolicBayesTree();\n\n\t// create two factors to be inserted\n\tSymbolicFactorGraph newFactors;\n\tnewFactors.push_factor(_B_);\n\tnewFactors.push_factor(_S_);\n\n\t// Remove the contaminated part of the Bayes tree\n\tBayesNet<IndexConditional> bn;\n\tSymbolicBayesTree::Cliques orphans;\n  list<Index> keys; keys += _B_,_S_;\n\tbayesTree.removeTop(keys, bn, orphans);\n\tSymbolicFactorGraph factors(bn);\n\n\t// Check expected outcome\n\tSymbolicFactorGraph expected;\n\texpected.push_factor(_E_,_L_,_B_);\n//\texpected.push_factor(_L_,_B_);\n//\texpected.push_factor(_B_);\n\texpected.push_factor(_S_,_L_,_B_);\n  CHECK(assert_equal(expected, factors));\n\tSymbolicBayesTree::Cliques expectedOrphans;\n  expectedOrphans += bayesTree[_T_], bayesTree[_X_];\n\tCHECK(assert_equal(expectedOrphans, orphans));\n}\n\n/* ************************************************************************* */\nTEST( BayesTree, removeTop3 )\n{\n  const Index _x4_=5, _l5_=6;\n\t// simple test case that failed after COLAMD was fixed/activated\n\tIndexConditional::shared_ptr\n\tX(new IndexConditional(_l5_)),\n\tA(new IndexConditional(_x4_, _l5_)),\n\tB(new IndexConditional(_x2_, _x4_)),\n\tC(new IndexConditional(_x3_, _x2_));\n\n//\tOrdering newOrdering;\n//\tnewOrdering += _x3_, _x2_, _x1_, _l2_, _l1_, _x4_, _l5_;\n\tSymbolicBayesTree bayesTree;\n\tSymbolicBayesTree::insert(bayesTree, X);\n\tSymbolicBayesTree::insert(bayesTree, A);\n\tSymbolicBayesTree::insert(bayesTree, B);\n\tSymbolicBayesTree::insert(bayesTree, C);\n\n\t// remove all\n\tlist<Index> keys;\n\tkeys += _l5_, _x2_, _x3_, _x4_;\n\tBayesNet<IndexConditional> bn;\n\tSymbolicBayesTree::Cliques orphans;\n\tbayesTree.removeTop(keys, bn, orphans);\n\tSymbolicFactorGraph factors(bn);\n\n\tCHECK(orphans.size() == 0);\n}\n///* ************************************************************************* */\n///**\n// *  x2 - x3 - x4 - x5\n// *   |  /       \\   |\n// *  x1 /\t\t\t\t \\ x6\n// */\n//TEST( BayesTree, insert )\n//{\n//\t// construct bayes tree by split the graph along the separator x3 - x4\n//\tconst Index _x1_=0, _x2_=1, _x6_=2, _x5_=3, _x3_=4, _x4_=5;\n//\tSymbolicFactorGraph fg1, fg2, fg3;\n//\tfg1.push_factor(_x3_, _x4_);\n//\tfg2.push_factor(_x1_, _x2_);\n//\tfg2.push_factor(_x2_, _x3_);\n//\tfg2.push_factor(_x1_, _x3_);\n//\tfg3.push_factor(_x5_, _x4_);\n//\tfg3.push_factor(_x6_, _x5_);\n//\tfg3.push_factor(_x6_, _x4_);\n//\n////\tOrdering ordering1; ordering1 += _x3_, _x4_;\n////\tOrdering ordering2; ordering2 += _x1_, _x2_;\n////\tOrdering ordering3; ordering3 += _x6_, _x5_;\n//\n//\tBayesNet<IndexConditional> bn1, bn2, bn3;\n//\tbn1 = *SymbolicSequentialSolver::EliminateUntil(fg1, _x4_+1);\n//\tbn2 = *SymbolicSequentialSolver::EliminateUntil(fg2, _x2_+1);\n//\tbn3 = *SymbolicSequentialSolver::EliminateUntil(fg3, _x5_+1);\n//\n//\t// insert child cliques\n//\tSymbolicBayesTree actual;\n//\tlist<SymbolicBayesTree::sharedClique> children;\n//\tSymbolicBayesTree::sharedClique r1 = actual.insert(bn2, children);\n//\tSymbolicBayesTree::sharedClique r2 = actual.insert(bn3, children);\n//\n//\t// insert root clique\n//\tchildren.push_back(r1);\n//\tchildren.push_back(r2);\n//\tactual.insert(bn1, children, true);\n//\n//\t// traditional way\n//\tSymbolicFactorGraph fg;\n//\tfg.push_factor(_x3_, _x4_);\n//\tfg.push_factor(_x1_, _x2_);\n//\tfg.push_factor(_x2_, _x3_);\n//\tfg.push_factor(_x1_, _x3_);\n//  fg.push_factor(_x5_, _x4_);\n//  fg.push_factor(_x6_, _x5_);\n//  fg.push_factor(_x6_, _x4_);\n//\n////\tOrdering ordering;  ordering += _x1_, _x2_, _x6_, _x5_, _x3_, _x4_;\n//\tBayesNet<IndexConditional> bn(*SymbolicSequentialSolver(fg).eliminate());\n//\tSymbolicBayesTree expected(bn);\n//\tCHECK(assert_equal(expected, actual));\n//\n//}\n/* ************************************************************************* */\n\nint main() {\n\tTestResult tr;\n\treturn TestRegistry::runAllTests(tr);\n}\n/* ************************************************************************* */\n", "meta": {"hexsha": "b9936409206b546964e0c99348b9473c8bb46d4a", "size": 15630, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/inference/tests/testBayesTree.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/inference/tests/testBayesTree.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/inference/tests/testBayesTree.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": 33.2553191489, "max_line_length": 105, "alphanum_fraction": 0.6781190019, "num_tokens": 4581, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.746138993030751, "lm_q1q2_score": 0.4698993914050656}}
{"text": "#include <iostream>\n#include <string>\n#include <sstream>\n#include <boost/regex.hpp>\n#include <cstdlib>\n\nstd::string encode ( const std::string & ) ;\nstd::string decode ( const std::string & ) ;\n\nint main( ) {\n   std::string to_encode ( \"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW\" ) ;\n   std::cout << to_encode << \" encoded:\" << std::endl ;\n   std::string encoded ( encode ( to_encode ) ) ;\n   std::cout << encoded << std::endl ;\n   std::string decoded ( decode( encoded ) ) ;\n   std::cout << \"Decoded again:\\n\" ;\n   std::cout << decoded << std::endl ;\n   if ( to_encode == decoded )\n      std::cout << \"It must have worked!\\n\" ;\n   return 0 ;\n}\n\nstd::string encode( const std::string & to_encode ) {\n   std::string::size_type found = 0 , nextfound = 0 ;\n   std::ostringstream oss ;\n   nextfound = to_encode.find_first_not_of( to_encode[ found ] , found ) ;\n   while ( nextfound != std::string::npos ) {\n      oss << nextfound - found ;\n      oss << to_encode[ found ] ;\n      found = nextfound ;\n      nextfound = to_encode.find_first_not_of( to_encode[ found ] , found ) ;\n   }\n   //since we must not discard the last characters we add them at the end of the string\n   std::string rest ( to_encode.substr( found ) ) ;//last run of characters starts at position found\n   oss << rest.length( ) << to_encode[ found ] ;\n   return oss.str( ) ;\n}\n\nstd::string decode ( const std::string & to_decode ) {\n   boost::regex e ( \"(\\\\d+)(\\\\w)\" ) ;\n   boost::match_results<std::string::const_iterator> matches ;\n   std::ostringstream oss ;\n   std::string::const_iterator start = to_decode.begin( ) , end = to_decode.end( ) ;\n   while ( boost::regex_search ( start , end , matches , e ) ) {\n      std::string numberstring ( matches[ 1 ].first , matches[ 1 ].second ) ;\n      int number = atoi( numberstring.c_str( ) ) ;\n      std::string character ( matches[ 2 ].first , matches[ 2 ].second ) ;\n      for ( int i = 0 ; i < number ; i++ )\n\t oss << character ;\n      start = matches[ 2 ].second ;\n   }\n   return oss.str( ) ;\n}\n", "meta": {"hexsha": "f993f04affe417cf072ac38b2342df66d99c97ee", "size": 2037, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lang/C++/run-length-encoding-2.cpp", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-01-29T20:08:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T06:16:05.000Z", "max_issues_repo_path": "lang/C++/run-length-encoding-2.cpp", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/C++/run-length-encoding-2.cpp", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-13T04:19:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-13T04:19:31.000Z", "avg_line_length": 37.7222222222, "max_line_length": 100, "alphanum_fraction": 0.6254295533, "num_tokens": 573, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.4698993914050656}}
{"text": "#include \"f1_datalogger/udp_logging/utils/eigen_utils.h\"\n#include <thread>\n#include <iostream>\n#include <google/protobuf/util/json_util.h>\n#include <sstream>\n#include \"f1_datalogger/udp_logging/utils/udp_stream_utils.h\"\n#ifdef USE_ARMADILLO\n#include <armadillo>\n#endif\n#include <stdexcept>\nnamespace deepf1\n{ \n\nEigenUtils::EigenUtils()\n{\n}\n\nEigenUtils::~EigenUtils()\n{\n}\nEigen::MatrixXd EigenUtils::loadArmaTxt(const std::string& armafile)\n{\n  #ifdef USE_ARMADILLO\n  arma::Mat<double> arma_mat;\n  if (!arma_mat.load(armafile, arma::arma_ascii))\n  {\n    throw std::runtime_error(\"Could not load arma txt file: \" + armafile);\n  }\n  Eigen::MatrixXd rtn(Eigen::Map<Eigen::MatrixXd>(arma_mat.memptr(), arma_mat.n_rows, arma_mat.n_cols));\n  return rtn;\n  #else\n  throw std::runtime_error(\"This feature only works with the armadillo library. Recompile with the WITH_ARMA option turned on\");\n  #endif\n}\ndeepf1::protobuf::eigen::Pose3d EigenUtils::eigenToProto(const Eigen::Affine3d& poseEigen, const double& session_time, deepf1::protobuf::eigen::FrameId frameid)\n{\n  deepf1::protobuf::eigen::Pose3d rtn;\n\n  Eigen::Vector3d translation(poseEigen.translation());\n  Eigen::Quaterniond rotation(poseEigen.rotation());\n  \n  rtn.mutable_translation()->set_x(translation.x());\n  rtn.mutable_translation()->set_y(translation.y());\n  rtn.mutable_translation()->set_y(translation.z());\n\n  rtn.mutable_rotation()->set_x(rotation.x());\n  rtn.mutable_rotation()->set_y(rotation.y());\n  rtn.mutable_rotation()->set_y(rotation.z());\n  rtn.mutable_rotation()->set_w(rotation.w());\n\n  rtn.set_frame(frameid);\n  rtn.set_session_time(session_time);\n\n  return rtn;\n}\nEigen::Affine3d EigenUtils::protoToEigen(const deepf1::protobuf::eigen::Pose3d& poseProto)\n{\n  Eigen::Affine3d poseEigen;\n  Eigen::Vector3d translation(poseProto.translation().x(), poseProto.translation().y(), poseProto.translation().z());\n  Eigen::Quaterniond rotation(poseProto.rotation().w(), poseProto.rotation().x(), poseProto.rotation().y(), poseProto.rotation().z());\n  poseEigen.fromPositionOrientationScale(translation, rotation, Eigen::Vector3d::Ones());\n  return poseEigen;\n}\nEigen::Affine3d EigenUtils::interpPoses(const Eigen::Affine3d& a, const Eigen::Affine3d& b, const double& s)\n{\n\tEigen::Affine3d rtn;\n\tEigen::Vector3d translationA(a.translation());\n\tEigen::Quaterniond rotationA(a.rotation());\n\tEigen::Vector3d translationB(b.translation());\n\tEigen::Quaterniond rotationB(b.rotation());\n\n\tEigen::Vector3d translationOut = (1 - s) * translationA + s * translationB;\n\tEigen::Quaterniond rotationOut = rotationA.slerp(s, rotationB);\n\n\trtn.fromPositionOrientationScale(translationOut, rotationOut, Eigen::Vector3d::Ones());\n\n\n\treturn rtn;\n}\nEigen::Affine3d EigenUtils::motionPacketToPose(const deepf1::twenty_eighteen::CarMotionData& motion_packet)\n{\n\tconst deepf1::twenty_eighteen::protobuf::CarMotionData& motion_packet_pb =\n\t\tdeepf1::twenty_eighteen::TwentyEighteenUDPStreamUtils::toProto(motion_packet);\n\treturn motionPacketToPose(motion_packet_pb);\n}\nEigen::Affine3d EigenUtils::motionPacketToPose(const deepf1::twenty_eighteen::protobuf::CarMotionData& motion_packet)\n{\n\tEigen::Affine3d rtn;\n\tEigen::Vector3d translation(motion_packet.m_worldpositionx(), motion_packet.m_worldpositiony(), motion_packet.m_worldpositionz());\n\n\tEigen::Vector3d forward(motion_packet.m_worldforwarddirx(), motion_packet.m_worldforwarddiry(), motion_packet.m_worldforwarddirz());\n\tforward.normalize();\n\tEigen::Vector3d right(motion_packet.m_worldrightdirx(), motion_packet.m_worldrightdiry(), motion_packet.m_worldrightdirz());\n\tright.normalize();\n\tEigen::Vector3d up = right.cross(forward);\n\tup.normalize();\n\tEigen::Matrix3d rotationMat(Eigen::Matrix3d::Identity());\n\trotationMat.col(0) = -right;\n\trotationMat.col(1) = up;\n\trotationMat.col(2) = forward;\n\tEigen::Quaterniond rotation(rotationMat);\n\n\trtn.fromPositionOrientationScale(translation, rotation, Eigen::Vector3d::Ones());\n\n\treturn rtn;\n}\nEigen::MatrixXd EigenUtils::vectorToMatrix(const std::vector < Eigen::Vector4d >& vector)\n{\n\tEigen::MatrixXd rtnMat(4, vector.size());\n\t/**/\n\trtnMat.resize(4, vector.size());\n\tunsigned int idx = 0;\n\tstd::for_each(vector.begin(), vector.end(), [&rtnMat, &idx](const Eigen::Vector4d & point)\n\t{\n\t\trtnMat.col(idx) = point;\n\t\tidx++;\n\t});\n\treturn rtnMat;\n}\n\n\n}", "meta": {"hexsha": "147ef8896662eddd38e84df0624cc76095f3a41f", "size": 4293, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "data-logger/src/udp_logging/utils/eigen_utils.cpp", "max_stars_repo_name": "linklab-uva/deepracing", "max_stars_repo_head_hexsha": "fc25c47658277df029e7399d295d97a75fe85216", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2020-06-29T15:21:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-12T00:42:26.000Z", "max_issues_repo_path": "data-logger/src/udp_logging/utils/eigen_utils.cpp", "max_issues_repo_name": "linklab-uva/deepracing", "max_issues_repo_head_hexsha": "fc25c47658277df029e7399d295d97a75fe85216", "max_issues_repo_licenses": ["Apache-2.0"], "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-logger/src/udp_logging/utils/eigen_utils.cpp", "max_forks_repo_name": "linklab-uva/deepracing", "max_forks_repo_head_hexsha": "fc25c47658277df029e7399d295d97a75fe85216", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-01-23T23:36:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-02T00:18:37.000Z", "avg_line_length": 35.1885245902, "max_line_length": 160, "alphanum_fraction": 0.7570463545, "num_tokens": 1138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389817407016, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.4698993842948791}}
{"text": "/*******************************************************************************\n * An array content domain.\n * \n * This domain is a simplified implementation of the paper: \n * \"A Partial-Order Approach to Array Content Analysis\" by \n *  Gange, Navas, Schachte, Sondergaard, and Stuckey\n *  available here http://arxiv.org/pdf/1408.1754v1.pdf.\n *\n * It keeps a graph where vertices are array indexes and edges are\n * labelled with weights.  An edge (i,j) with weight w denotes that\n * the property w holds for the array segment [i,j). A weight is an\n * arbitrary lattice that can relate multiple array variables as well\n * as array with scalar variables.\n ******************************************************************************/\n\n/* IMPORTANT\n * JN: the implementation works for toy programs but two main things\n * must to be done for being able to analyze real programs:\n *\n * 1) landmarks must be kept as local state as part of each abstract\n *    state.\n * \n * 2) reduction between scalar and weight domains must be done\n *    incrementally. For that, we need some assumptions about the\n *    underlying scalar domain. For instance, if we assume zones then\n *    after each operation we know which are the indexes affected by\n *    the operation. We can use that information for doing reduction\n *    only on those indexes. This would remove the need of having\n *    methods such as array_sgraph_domain_traits::is_unsat and\n *    array_sgraph_domain_traits::active_variables which are anyway\n *    domain dependent.\n */ \n\n#ifndef ARRAY_SPARSE_GRAPH_HPP\n#define ARRAY_SPARSE_GRAPH_HPP\n\n#include <crab/common/types.hpp>\n#include <crab/common/debug.hpp>\n#include <crab/common/stats.hpp>\n#include <crab/domains/operators_api.hpp>\n#include <crab/domains/domain_traits.hpp>\n#include <crab/domains/array_sparse_graph/array_segmentation.hpp>\n#include <crab/domains/array_sparse_graph/array_graph_ops.hpp>\n#include <crab/domains/graphs/adapt_sgraph.hpp>\n#include <crab/domains/graphs/sparse_graph.hpp>\n#include <crab/domains/linear_constraints.hpp>\n#include <crab/domains/intervals.hpp>\n\n// XXX: if expression domain is a template parameter no need to include\n#include <crab/domains/term_equiv.hpp>\n// XXX: for customized propagations between weight and scalar domains\n#include <crab/domains/combined_domains.hpp>\n#include <crab/domains/nullity.hpp>\n\n#include <boost/unordered_map.hpp>\n#include <boost/shared_ptr.hpp>\n#include <boost/make_shared.hpp>\n#include <boost/range/iterator_range.hpp>\n#include <boost/range/join.hpp>\n#include <boost/iterator/transform_iterator.hpp>\n\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wsign-compare\"\n\nnamespace crab {\n\n  namespace domains {\n\n    /* \n       A weighted directed graph where the weight is an abstract\n       domain. The graph should be always kept in a consistent form,\n       i.e., for all i,j,k:: weight(i,j) <= join(weight(i,k), weight(k,j))\n    */\n    template< typename Vertex, typename Weight, bool IsDistWeight >\n    class array_sparse_graph_: public writeable {\n\n     public:\n\n      // XXX: make this a template parameter later\n      //typedef AdaptGraph<Weight> graph_t;\n      typedef SparseWtGraph<Weight> graph_t;\n      typedef typename graph_t::vert_id _vert_id;\n      typedef typename graph_t::edge_ref_t edge_ref_t;\n      typedef typename graph_t::Wt Wt;\n      typedef typename graph_t::mut_val_ref_t mut_val_ref_t;\n      // XXX: needs to have this typedef so we can use GraphRev\n      typedef Vertex vert_id;\n\n     private:\n\n      typedef GraphPerm<graph_t> GrPerm;\n      typedef ArrayGrOps<graph_t, IsDistWeight> GrOps;\n      typedef typename GrOps::Wt_join Wt_join;\n      typedef typename GrOps::Wt_meet Wt_meet;\n\n      typedef boost::container::flat_map<Vertex, _vert_id> vert_map_t;\n      typedef typename vert_map_t::value_type vmap_elt_t;\n      typedef std::vector<boost::optional<Vertex> > rev_map_t;\n      typedef std::unordered_set<_vert_id> vert_set_t;\n      typedef array_sparse_graph_<Vertex, Weight, IsDistWeight> array_sparse_graph_t;\n\n      vert_map_t _vert_map;\n      rev_map_t _rev_map;\n      graph_t _g;\n      vert_set_t _unstable;\n      bool _is_bottom;\n\n      struct vert_set_wrap_t {\n        vert_set_wrap_t(const vert_set_t& _vs)\n            : vs(_vs) { }\n        \n        bool operator[](_vert_id v) const {\n          return vs.find(v) != vs.end();\n        }\n        const vert_set_t& vs;\n      };\n\n      _vert_id get_vert(Vertex v)\n      {\n        auto it = _vert_map.find(v);\n        if(it != _vert_map.end())\n          return (*it).second;\n\n        _vert_id vert(_g.new_vertex());\n        assert(vert <= _rev_map.size());\n\n        if(vert < _rev_map.size()) {\n          assert(!_rev_map[vert]);\n          _rev_map[vert] = v;\n        } else {\n          _rev_map.push_back(v);\n        }\n        _vert_map.insert(vmap_elt_t(v, vert));\n\n        return vert;\n      }\n\n     public: \n\n      template<class ItS>\n      class iterator {\n       public:\n        typedef iterator<ItS> iter_t;\n        iterator(const ItS& _it, const rev_map_t& _rev_map) \n            : it(_it), rev_map(_rev_map) { }\n        bool operator!=(const iter_t& o) \n        { return it != o.it; }\n        iter_t& operator++(void) { ++it; return *this; }\n        Vertex operator*(void) const { \n          if (!rev_map[*it]) CRAB_ERROR(\"Reverse map failed\");\n          return *(rev_map[*it]);\n        }\n       protected:\n        ItS it;      \n        const rev_map_t& rev_map;\n      };\n\n      struct edge_t {\n        edge_t(Vertex _v, Wt& _w) : vert(_v), val(_w) { }\n        Vertex vert;\n        Wt& val; \n      };\n\n      template<class ItS>\n      class edge_iterator {\n       public:\n        typedef edge_iterator<ItS> iter_t;\n        edge_iterator(const ItS& _it, const rev_map_t& _rev_map) \n            : it(_it), rev_map(_rev_map) { }\n        bool operator!=(const iter_t& o) \n        { return it != o.it; }\n        iter_t& operator++(void) { ++it; return *this; }\n        edge_t operator*(void) const { \n          edge_ref_t e = *it;\n          if (!rev_map[e.vert]) CRAB_ERROR(\"Reverse map failed\");\n          Vertex v = *(rev_map[e.vert]);\n          return edge_t(v, e.val);\n        }\n       protected:\n        ItS it;      \n        const rev_map_t& rev_map;\n      };\n\n      template<class Range, class ItS>\n      class iterator_range {\n       public:\n        typedef ItS iterator;\n        iterator_range(const Range &r, const rev_map_t &rev_map) \n            : _r(r), _rev_map(rev_map) { }\n        iterator begin(void) const { return iterator(_r.begin(), _rev_map); }\n        iterator end(void) const { return iterator(_r.end(), _rev_map); }\n       protected:\n        Range _r;\n        const rev_map_t &_rev_map;\n      };\n\n      typedef iterator<typename graph_t::succ_iterator> succ_transform_iterator;\n      typedef iterator<typename graph_t::pred_iterator> pred_transform_iterator;\n      typedef iterator<typename graph_t::vert_iterator> vert_transform_iterator;\n      typedef edge_iterator<typename graph_t::fwd_edge_iterator> fwd_edge_transform_iterator;\n      typedef edge_iterator<typename graph_t::rev_edge_iterator> rev_edge_transform_iterator;\n\n      typedef iterator_range<typename graph_t::succ_range, succ_transform_iterator> succ_range;\n      typedef iterator_range<typename graph_t::pred_range, pred_transform_iterator> pred_range;\n      typedef iterator_range<typename graph_t::vert_range, vert_transform_iterator> vert_range;\n      typedef iterator_range<typename graph_t::e_succ_range, fwd_edge_transform_iterator>\n      e_succ_range;\n      typedef iterator_range<typename graph_t::e_pred_range, rev_edge_transform_iterator>\n      e_pred_range;\n\n      vert_range verts() {\n        typename graph_t::vert_range p = _g.verts();\n        return vert_range(p, _rev_map);\n      }\n      \n      succ_range succs(Vertex v) {\n        typename graph_t::succ_range p = _g.succs(get_vert(v));\n        return succ_range(p, _rev_map);        \n      }\n\n      pred_range preds(Vertex v) {\n        typename graph_t::pred_range p = _g.preds(get_vert(v));\n        return pred_range(p, _rev_map);        \n      }\n\n      e_succ_range e_succs(Vertex v) {\n        typename graph_t::e_succ_range p = _g.e_succs(get_vert(v));\n        return e_succ_range(p, _rev_map);        \n      }\n\n      e_pred_range e_preds(Vertex v) {\n        typename graph_t::e_pred_range p = _g.e_preds(get_vert(v));\n        return e_pred_range(p, _rev_map);        \n      }\n      \n     public:\n\n      array_sparse_graph_(bool is_bottom = false)\n          : writeable(), _is_bottom(is_bottom) \n      { }\n\n      array_sparse_graph_(const array_sparse_graph_t& o)\n          : writeable(),\n            _vert_map(o._vert_map), _rev_map(o._rev_map), _g(o._g),\n            _unstable(o._unstable), _is_bottom (false) \n      { \n        if (o._is_bottom)\n          set_to_bottom();\n      }\n\n      array_sparse_graph_(array_sparse_graph_t&& o)\n          : _vert_map(std::move(o._vert_map)), _rev_map(std::move(o._rev_map)),\n            _g(std::move(o._g)), _unstable(std::move(o._unstable)), _is_bottom(o._is_bottom) \n      { }\n\n      array_sparse_graph_(vert_map_t& vert_map, rev_map_t& rev_map, graph_t& g,\n\t\t\t  vert_set_t unstable)\n\t: writeable(),\n\t  _vert_map(vert_map), _rev_map(rev_map), _g(g), \n\t  _unstable(unstable), _is_bottom(false)\n      { }\n      \n      array_sparse_graph_(vert_map_t&& vert_map, rev_map_t&& rev_map, graph_t&& g,\n\t\t\t  vert_set_t &&unstable)\n          : writeable(),\n            _vert_map(std::move(vert_map)), _rev_map(std::move(rev_map)), _g(std::move(g)),\n            _unstable(std::move(unstable)), _is_bottom(false)\n      { }\n\n      array_sparse_graph_t& operator=(const array_sparse_graph_t& o)\n      {\n        if(this != &o)\n        {\n          if(o._is_bottom)\n            set_to_bottom();\n          else {\n            _is_bottom = false;\n            _vert_map = o._vert_map;\n            _rev_map = o._rev_map;\n            _g = o._g;\n            _unstable = o._unstable;\n          }\n        }\n        return *this;\n      }\n\n      array_sparse_graph_t& operator=(array_sparse_graph_t&& o)\n      {\n        if(o._is_bottom) {\n          set_to_bottom();\n        } else {\n          _is_bottom = false;\n          _vert_map = std::move(o._vert_map);\n          _rev_map = std::move(o._rev_map);\n          _unstable = std::move(o._unstable);\n          _g = std::move(o._g);\n        }\n        return *this;\n      }\n\n     public: \n\n      void set_to_bottom() {\n        _vert_map.clear();\n        _rev_map.clear();\n        _g.clear();\n        _unstable.clear();\n        _is_bottom = true;\n      }\n\n      static array_sparse_graph_t top() { return array_sparse_graph_t(false); }\n    \n      static array_sparse_graph_t bottom() { return array_sparse_graph_t(true); }\n    \n      bool is_bottom() const { return _is_bottom; }\n    \n      bool is_top() {\n        if(_is_bottom) \n          return false;\n        return _g.is_empty();\n      }\n\n      bool lookup_edge(Vertex s, Vertex d, mut_val_ref_t* w) {\n        if (is_bottom()) return false;\n        auto se = get_vert(s);\n        auto de = get_vert(d);\n        return _g.lookup(se, de, w);\n      }\n\n      // // update edge but do not close graph\n      // void update_edge_unclosed (Vertex s, Weight w, Vertex d) {\n      //   if (w.is_top()) return;\n      //   normalize();\n      //   if (is_bottom ()) return;\n      //   auto se = get_vert(s);\n      //   auto de = get_vert(d);\n      //   Wt_meet op;\n      //   _g.update_edge(se, w, de, op);\n      // }\n\n      // close the graph after edge (s,d) has been updated\n      void close_edge (Vertex s, Vertex d) {\n        normalize();\n        if (is_bottom ()) return;\n        auto se = get_vert(s);\n        auto de = get_vert(d);\n        GrOps::close_after_edge(_g, se, de);\n      }\n\n      void update_edge (Vertex s, Weight w, Vertex d) {\n        if (w.is_top())\n          return;\n\n        normalize();\n        \n        if (is_bottom ())\n          return;\n        \n        auto se = get_vert(s);\n        auto de = get_vert(d);\n        Wt_meet op;\n        _g.update_edge(se, w, de, op);\n        GrOps::close_after_edge(_g, se, de);\n      }\n\n      // void full_close () { // for debugging\n      //   if (is_bottom ()) return;\n      //   GrOps::floyd_warshall(_g);\n      // }\n\n      void expand (Vertex s, Vertex d) {\n        if(is_bottom()) \n          return;\n\n        auto it = _vert_map.find(d);\n        if(it != _vert_map.end()) {\n          CRAB_ERROR(\"array_sparse_graph expand failed because vertex \", d, \" already exists\");\n        }\n\n        auto se = get_vert(s);        \n        auto de = get_vert(d);\n        \n        for (auto edge : _g.e_preds(se))  \n          _g.add_edge (edge.vert, edge.val, de);\n        \n        for (auto edge : _g.e_succs(se))  \n          _g.add_edge (de, edge.val, edge.vert);\n\n      }\n\n      void normalize() {\n        #if 0\n        GrOps::closure(_g); // only for debugging purposes\n        #else\n        // Always maintained in closed form except for widening\n        if(_unstable.size() == 0)\n          return;\n        GrOps::close_after_widen(_g, vert_set_wrap_t(_unstable));\n        _unstable.clear();\n        #endif \n      }\n\n      void operator|=(array_sparse_graph_t& o) {\n        *this = *this | o;\n      }\n\n      bool operator<=(array_sparse_graph_t& o)  {\n        if (is_bottom()) \n          return true;\n        else if(o.is_bottom())\n          return false;\n        else if (o.is_top ())\n          return true;\n        else if (is_top ())\n          return false;\n        else {\n          normalize();\n\n          if(_vert_map.size() < o._vert_map.size())\n            return false;\n\n          // Set up a mapping from o to this.\n          std::vector<unsigned int> vert_renaming(o._g.size(),-1);\n          for(auto p : o._vert_map)\n          {\n            auto it = _vert_map.find(p.first);\n            // We can't have this <= o if we're missing some\n            // vertex.\n            if(it == _vert_map.end())\n              return false;\n            vert_renaming[p.second] = (*it).second;\n          }\n\n          assert(_g.size() > 0);\n          mut_val_ref_t wx;\n\n          for(_vert_id ox : o._g.verts()) {\n            assert(vert_renaming[ox] != -1);\n            _vert_id x = vert_renaming[ox];\n            for(auto edge : o._g.e_succs(ox)) {\n              _vert_id oy = edge.vert;\n              assert(vert_renaming[ox] != -1);\n              _vert_id y = vert_renaming[oy];\n              auto ow = (Weight) edge.val;\n              if(!_g.lookup(x, y, &wx) || (! ((Weight) wx <= ow))) \n                return false;\n            }\n          }\n          return true;\n        }\n      }\n\n      array_sparse_graph_t operator|(array_sparse_graph_t& o) {\n\n        if (is_bottom() || o.is_top ())\n          return o;\n        else if (is_top () || o.is_bottom())\n          return *this;\n        else {\n          CRAB_LOG (\"array-sgraph\",\n                    crab::outs() << \"Before join:\\n\"<<\"Graph 1\\n\"<<*this\n                                 <<\"\\n\"<<\"Graph 2\\n\"<<o << \"\\n\");\n\n          normalize();\n          o.normalize();\n\n          // Figure out the common renaming.\n          std::vector<_vert_id> perm_x;\n          std::vector<_vert_id> perm_y;\n\n          vert_map_t out_vmap;\n          rev_map_t out_revmap;\n\n          for(auto p : _vert_map)\n          {\n            auto it = o._vert_map.find(p.first); \n            // Vertex exists in both\n            if(it != o._vert_map.end())\n            {\n              out_vmap.insert(vmap_elt_t(p.first, perm_x.size()));\n              out_revmap.push_back(p.first);\n\n              perm_x.push_back(p.second);\n              perm_y.push_back((*it).second);\n            }\n          }\n\n          // Build the permuted view of x and y.\n          assert(_g.size() > 0);\n          GrPerm gx(perm_x, _g);\n          assert(o._g.size() > 0);\n          GrPerm gy(perm_y, o._g);\n\n          // We now have the relevant set of relations. Because g_rx\n          // and g_ry are closed, the result is also closed.\n          graph_t join_g(GrOps::join(gx, gy));\n\n          // Now garbage collect any unused vertices\n          for(_vert_id v : join_g.verts())\n          {\n            if(join_g.succs(v).size() == 0 && join_g.preds(v).size() == 0)\n            {\n              join_g.forget(v);\n              if(out_revmap[v])\n              {\n                out_vmap.erase(*(out_revmap[v]));\n                out_revmap[v] = boost::none;\n              }\n            }\n          }\n\n          array_sparse_graph_t res(std::move(out_vmap), std::move(out_revmap), \n                                   std::move(join_g), vert_set_t());\n          CRAB_LOG (\"array-sgraph\", crab::outs() << \"Result join:\\n\"<< res <<\"\\n\";);\n          return res;\n        }\n      }\n\n      template<typename Thresholds>\n      array_sparse_graph_t widening_thresholds (array_sparse_graph_t &o, \n                                                const Thresholds & /*ts*/) {\n        return (*this || o);\n      }\n      \n      array_sparse_graph_t operator||(array_sparse_graph_t &o) {\t\n        if (is_bottom())\n          return o;\n        else if (o.is_bottom())\n          return *this;\n        else {\n          CRAB_LOG (\"array-sgraph\",\n                    crab::outs() << \"Before widening:\\n\"<<\"Graph 1\\n\"<<*this\n                                 <<\"\\n\"<<\"Graph 2\\n\"<<o<<\"\\n\";);\n          o.normalize();\n          \n          // Figure out the common renaming\n          std::vector<_vert_id> perm_x;\n          std::vector<_vert_id> perm_y;\n          vert_map_t out_vmap;\n          rev_map_t out_revmap;\n          vert_set_t widen_unstable(_unstable);\n\n          for(auto p : _vert_map)\n          {\n            auto it = o._vert_map.find(p.first); \n            // Vertex exists in both\n            if(it != o._vert_map.end())\n            {\n              out_vmap.insert(vmap_elt_t(p.first, perm_x.size()));\n              out_revmap.push_back(p.first);\n\n              perm_x.push_back(p.second);\n              perm_y.push_back((*it).second);\n            }\n          }\n          \n          // Build the permuted view of x and y.\n          //assert(_g.size() > 0);\n          GrPerm gx(perm_x, _g);            \n          //assert(o._g.size() > 0);\n          GrPerm gy(perm_y, o._g);\n          \n          // Now perform the widening \n          std::vector<_vert_id> destabilized;\n          graph_t widen_g(GrOps::widen(gx, gy, destabilized));\n          for(_vert_id v : destabilized) {\n            widen_unstable.insert(v);\n          }\n          \n          array_sparse_graph_t res(std::move(out_vmap), std::move(out_revmap), \n                                   std::move(widen_g), std::move(widen_unstable));\n          CRAB_LOG (\"array-sgraph\", crab::outs() << \"Result widening:\\n\"<<res<<\"\\n\";);\n          return res;\n        }\n      }\n\n\n      array_sparse_graph_t meet_or_narrowing(array_sparse_graph_t &o, bool is_meet,\n\t\t\t\t\t     const std::string op) {\n\n        if (is_bottom() || o.is_bottom())\n          return bottom();\n        else if (is_top())\n          return o;\n        else if (o.is_top())\n          return *this;\n        else {\n          CRAB_LOG (\"array-sgraph\",\n                    crab::outs() << \"Before \" << op << \":\\n\"<<\"Graph 1\\n\"<<*this<<\"\\n\"\n                                 <<\"Graph 2\\n\"<<o << \"\\n\");\n\n          normalize();\n          o.normalize();\n\n          // Figure out the common renaming.\n          std::vector<_vert_id> perm_x;\n          std::vector<_vert_id> perm_y;\n\n          vert_map_t out_vmap;\n          rev_map_t out_revmap;\n\n          for(auto p : _vert_map)\n          {\n            _vert_id vv = perm_x.size();\n            out_vmap.insert(vmap_elt_t(p.first, vv));\n            out_revmap.push_back(p.first);\n            \n            perm_x.push_back(p.second);\n            perm_y.push_back(-1);\n          }\n\n\n          // Add missing mappings from the right operand.\n          for(auto p : o._vert_map)\n          {\n            auto it = out_vmap.find(p.first);\n            if(it == out_vmap.end())\n            {\n              _vert_id vv = perm_y.size();\n              out_revmap.push_back(p.first);\n\n              perm_y.push_back(p.second);\n              perm_x.push_back(-1);\n              out_vmap.insert(vmap_elt_t(p.first, vv));\n            } else {\n              perm_y[(*it).second] = p.second;\n            }\n          }\n\n          // Build the permuted view of x and y.\n          GrPerm gx(perm_x, _g);\n          GrPerm gy(perm_y, o._g);\n\n          // Compute the syntactic meet/narrowing of the permuted graphs.\n          std::vector<_vert_id> changes;\n          graph_t out_g(GrOps::meet_or_narrowing(gx, gy, is_meet, changes));\n          vert_set_t unstable;\n          for(_vert_id v : changes)\n            unstable.insert(v);\n\n          GrOps::close_after_meet_or_narrowing(_g, vert_set_wrap_t(unstable));\n\n          array_sparse_graph_t res(std::move(out_vmap), std::move(out_revmap), \n                                   std::move(out_g), vert_set_t());\n          CRAB_LOG (\"array-sgraph\", crab::outs() << \"Result \" << op << \":\\n\"<< res <<\"\\n\";);\n          return res;\n        }\n      }\n\n      array_sparse_graph_t operator&(array_sparse_graph_t& o) {\n        return meet_or_narrowing(o, true, \"meet\");\n      }\n\n      array_sparse_graph_t operator&&(array_sparse_graph_t& o) {\n        return meet_or_narrowing(o, false, \"narrowing\");\n      }\n      \n      // array_sparse_graph_t operator&(array_sparse_graph_t& o) {\n\n      //   if (is_bottom() || o.is_bottom())\n      //     return bottom();\n      //   else if (is_top())\n      //     return o;\n      //   else if (o.is_top())\n      //     return *this;\n      //   else {\n      //     CRAB_LOG (\"array-sgraph\",\n      //               crab::outs() << \"Before meet:\\n\"<<\"Graph 1\\n\"<<*this<<\"\\n\"\n      //                            <<\"Graph 2\\n\"<<o << \"\\n\");\n\n      //     normalize();\n      //     o.normalize();\n\n      //     // Figure out the common renaming.\n      //     std::vector<_vert_id> perm_x;\n      //     std::vector<_vert_id> perm_y;\n\n      //     vert_map_t out_vmap;\n      //     rev_map_t out_revmap;\n\n      //     for(auto p : _vert_map)\n      //     {\n      //       _vert_id vv = perm_x.size();\n      //       out_vmap.insert(vmap_elt_t(p.first, vv));\n      //       out_revmap.push_back(p.first);\n            \n      //       perm_x.push_back(p.second);\n      //       perm_y.push_back(-1);\n      //     }\n\n\n      //     // Add missing mappings from the right operand.\n      //     for(auto p : o._vert_map)\n      //     {\n      //       auto it = out_vmap.find(p.first);\n      //       if(it == out_vmap.end())\n      //       {\n      //         _vert_id vv = perm_y.size();\n      //         out_revmap.push_back(p.first);\n\n      //         perm_y.push_back(p.second);\n      //         perm_x.push_back(-1);\n      //         out_vmap.insert(vmap_elt_t(p.first, vv));\n      //       } else {\n      //         perm_y[(*it).second] = p.second;\n      //       }\n      //     }\n\n      //     // Build the permuted view of x and y.\n      //     //assert(_g.size() > 0);\n      //     GrPerm gx(perm_x, _g);\n      //     //assert(o._g.size() > 0);\n      //     GrPerm gy(perm_y, o._g);\n\n      //     // Compute the syntactic meet of the permuted graphs.\n      //     std::vector<_vert_id> changes;\n      //     graph_t meet_g(GrOps::meet_or_narrowing(gx, gy, true /*meet*/, changes));\n      //     vert_set_t unstable;\n      //     for(_vert_id v : changes)\n      //       unstable.insert(v);\n\n      //     GrOps::close_after_meet_or_narrowing(_g, vert_set_wrap_t(unstable));\n\n      //     array_sparse_graph_t res(std::move(out_vmap), std::move(out_revmap), \n      //                              std::move(meet_g), vert_set_t());\n      //     CRAB_LOG (\"array-sgraph\", crab::outs() << \"Result meet:\\n\"<< res <<\"\\n\";);\n      //     return res;\n      //   }\n      // }\n\n      // array_sparse_graph_t operator&&(array_sparse_graph_t& o) {\n      //   if (is_bottom() || o.is_bottom())\n      //     return bottom();\n      //   else if (is_top ())\n      //     return o;\n      //   else{\n      //     CRAB_LOG (\"array-sgraph\",\n      //               crab::outs() << \"Before narrowing:\\n\"<<\"Graph 1\\n\"<<*this<<\"\\n\"\n      //                            <<\"Graph 2\\n\"<<o<<\"\\n\";);\n\n      //     // Narrowing as a no-op should be sound.\n      //     normalize();\n      //     array_sparse_graph_t res(*this);\n          \n      //     CRAB_LOG (\"array-sgraph\",\n      //               crab::outs() << \"Result narrowing:\\n\" << res<<\"\\n\";);\n      //     return res;\n      //   }\n      // }\n\n      void operator-=(Vertex v) {\n        if (is_bottom ())\n          return;\n        auto it = _vert_map.find (v);\n        if (it != _vert_map.end ()) {\n          normalize();\n          _g.forget(it->second);\n          _rev_map[it->second] = boost::none;\n          _vert_map.erase(v);\n        }\n      }\n\n      void remove_from_weights(typename Weight::varname_t v) {\n        mut_val_ref_t w_pq;\n        for(auto p : _g.verts()) \n          for(auto e : _g.e_succs(p)) {\n            auto q = e.vert;\n            if (_g.lookup(p, q, &w_pq)) { \n              Weight w = (Weight) w_pq;\n              w -= v;\n              Wt_meet op;\n              _g.update_edge(p, w, q, op);\n              GrOps::close_after_edge(_g, p, q);\n            }\n          }\n      }\n\n      void write(crab_os& o) {\n        write(o, true);\n      }\n\n      void write(crab_os& o, bool print_bottom_edges) {\n        \n        normalize ();\n\n        if(is_bottom()){\n          o << \"_|_\";\n          return;\n        }\n        else if (is_top()){\n          o << \"{}\";\n          return;\n        }\n        else\n        {\n          bool first = true;\n          o << \"{\";\n          for(_vert_id s : _g.verts())\n          {\n            if(!_rev_map[s]) continue;\n              \n            auto vs = *_rev_map[s];\n            for(_vert_id d : _g.succs(s))\n            {\n              if(!_rev_map[d]) continue;\n\n              auto w = _g.edge_val(s, d);\n              if (!print_bottom_edges && w.is_bottom())\n                continue; // do not print bottom edges\n                \n              auto vd = *_rev_map[d];\n\n              if(first)\n                first = false;\n              else\n                o << \", \";\n              o << \"[\" << vs << \",\" << vd << \")=>\" << w;\n            }\n          }\n          o << \"}\";\n        }\n      }\n    };\n\n    namespace array_sparse_graph_impl {\n\n      // JN: I do not know how to propagate arbitrary invariants\n      // between weight and scalar domains in a domain-independent\n      // manner. Here, we define propagations between specific\n      // domains.\n\n      template <typename Dom>\n      interval<typename Dom::number_t> \n      eval_interval(Dom dom, typename Dom::linear_expression_t e)\n      {\n        interval<typename Dom::number_t>  r = e.constant();\n        for (auto p : e)\n          r += p.first * dom[p.second.name()];\n        return r;\n      }\n\n      template<typename Dom1, typename Dom2>\n      void propagate_between_weight_and_scalar(Dom1 src, typename Dom1::varname_t src_var, \n                                               variable_type ty, \n                                               Dom2 &dst, typename Dom2::varname_t dst_var) {\n        if (ty == ARR_INT_TYPE) {\n          // --- XXX: simplification wrt Gange et.al.:\n          //     Only non-relational numerical invariants are\n          //     propagated from the graph domain to the scalar domain.\n          dst.set (dst_var, eval_interval(src, typename Dom1::variable_t(src_var))); \n        } else {\n          CRAB_WARN (\"Missing propagation between weight and scalar domains\");\n        }\n      }\n\n      template<typename BaseDom>\n      void propagate_between_weight_and_scalar(numerical_nullity_domain<BaseDom> src,\n                                               typename BaseDom::varname_t src_var, \n                                               variable_type ty, \n                                               numerical_nullity_domain<BaseDom> &dst, \n                                               typename BaseDom::varname_t dst_var) {\n        if (ty == ARR_INT_TYPE) {\n          // --- XXX: simplification wrt Gange et.al.:\n          //     Only non-relational numerical invariants are\n          //     propagated from the graph domain to the scalar domain.\n          dst.set (dst_var, eval_interval(src, typename BaseDom::variable_t(src_var))); \n        } else if (ty == ARR_PTR_TYPE) {\n          auto &null_dom = dst.second ();\n          null_dom.set_nullity (dst_var, src.get_nullity (src_var));\n        } else {\n          CRAB_WARN (\"Missing propagation between weight and scalar domains\");\n        }\n      }\n\n      template<typename BaseDom>\n      void propagate_between_weight_and_scalar(nullity_domain<typename BaseDom::number_t,\n                                                              typename BaseDom::varname_t> src,\n                                               typename BaseDom::varname_t src_var, \n                                               variable_type ty, \n                                               numerical_nullity_domain<BaseDom> &dst, \n                                               typename BaseDom::varname_t dst_var) {\n        if (ty == ARR_INT_TYPE) {\n          // do nothing\n        } else if (ty == ARR_PTR_TYPE) {\n          auto &null_dom = dst.second ();\n          null_dom.set_nullity (dst_var, src.get_nullity (src_var));\n        } else {\n          CRAB_WARN (\"Missing propagation between weight and scalar domains\");\n        }\n      }\n\n      template<typename BaseDom>\n      void propagate_between_weight_and_scalar(numerical_nullity_domain<BaseDom> src, \n                                               typename BaseDom::varname_t src_var, \n                                               variable_type ty, \n                                               nullity_domain<typename BaseDom::number_t,\n                                                              typename BaseDom::varname_t> &dst,\n                                               typename BaseDom::varname_t dst_var) {\n        if (ty == ARR_INT_TYPE) {\n          // do nothing\n        } else if (ty == ARR_PTR_TYPE) {\n          dst.set_nullity (dst_var, src.second ().get_nullity (src_var));\n        } else {\n          CRAB_WARN (\"Missing propagation between weight and scalar domains\");\n        }\n      }\n\n    } /* end array_sparse_graph_impl */\n    \n\n    // Wrapper which uses shared references with copy-on-write.\n    template<class Vertex, class Weight, bool IsDistWeight>\n    class array_sparse_graph : public writeable {\n      public:\n\n      typedef array_sparse_graph_<Vertex, Weight, IsDistWeight> array_sgraph_impl_t;\n      typedef std::shared_ptr<array_sgraph_impl_t> array_sgraph_ref_t;\n      typedef array_sparse_graph<Vertex, Weight, IsDistWeight> array_sgraph_t;\n\n      typedef typename array_sgraph_impl_t::Wt Wt;\n      typedef typename array_sgraph_impl_t::mut_val_ref_t mut_val_ref_t;\n      typedef typename array_sgraph_impl_t::graph_t graph_t;\n      typedef typename array_sgraph_impl_t::vert_id vert_id;\n      typedef typename array_sgraph_impl_t::succ_range succ_range;\n      typedef typename array_sgraph_impl_t::pred_range pred_range;\n      typedef typename array_sgraph_impl_t::vert_range vert_range;\n      typedef typename array_sgraph_impl_t::e_succ_range e_succ_range;\n      typedef typename array_sgraph_impl_t::e_pred_range e_pred_range;\n\n      array_sparse_graph(array_sgraph_ref_t _ref) : norm_ref(_ref) { }\n\n      array_sparse_graph(array_sgraph_ref_t _base, array_sgraph_ref_t _norm) \n        : base_ref(_base), norm_ref(_norm) { }\n\n      array_sgraph_t create(array_sgraph_impl_t&& t)\n      {\n        return std::make_shared<array_sgraph_impl_t>(std::move(t));\n      }\n\n      array_sgraph_t create_base(array_sgraph_impl_t&& t)\n      {\n        array_sgraph_ref_t base = std::make_shared<array_sgraph_impl_t>(t);\n        array_sgraph_ref_t norm = std::make_shared<array_sgraph_impl_t>(std::move(t));  \n        return array_sgraph_t(base, norm);\n      }\n\n      void lock(void)\n      { // Allocate a fresh copy.\n        if(!norm_ref.unique())\n          norm_ref = std::make_shared<array_sgraph_impl_t>(*norm_ref);\n        base_ref.reset();\n      }\n\n    public:\n\n      static array_sgraph_t top() { return array_sparse_graph(false); }\n    \n      static array_sgraph_t bottom() { return array_sparse_graph(true); }\n\n      array_sparse_graph(bool is_bottom = false)\n        : norm_ref(std::make_shared<array_sgraph_impl_t>(is_bottom)) { }\n\n      array_sparse_graph(const array_sgraph_t& o)\n        : base_ref(o.base_ref), norm_ref(o.norm_ref)\n      { }\n\n      array_sgraph_t& operator=(const array_sgraph_t& o) {\n        base_ref = o.base_ref;\n        norm_ref = o.norm_ref;\n        return *this;\n      }\n\n      array_sgraph_impl_t& base(void) {\n        if(base_ref)\n          return *base_ref;\n        else\n          return *norm_ref;\n      }\n\n      array_sgraph_impl_t& norm(void) { return *norm_ref; }\n      const array_sgraph_impl_t& norm(void) const { return *norm_ref; }\n\n      bool is_bottom() { return norm().is_bottom(); }\n\n      bool is_top() { return norm().is_top(); }\n\n      bool operator<=(array_sgraph_t& o) { return norm() <= o.norm(); }\n\n      void operator|=(array_sgraph_t o) { lock(); norm() |= o.norm(); }\n\n      array_sgraph_t operator|(array_sgraph_t o) { return create(norm() | o.norm()); }\n\n      array_sgraph_t operator||(array_sgraph_t o) { return create_base(base() || o.norm()); }\n\n      array_sgraph_t operator&(array_sgraph_t o) { return create(norm() & o.norm()); }\n\n      array_sgraph_t operator&&(array_sgraph_t o) { return create(norm() && o.norm()); }\n\n      template<typename Thresholds>\n      array_sgraph_t widening_thresholds (array_sgraph_t o, const Thresholds &ts) {\n        return create_base(base().template widening_thresholds<Thresholds>(o.norm(), ts));\n      }\n\n      void normalize() { lock(); norm().normalize(); }\n\n      vert_range verts () { return norm().verts(); }\n\n      succ_range succs (Vertex v) { return norm().succs(v); }\n\n      pred_range preds (Vertex v) { return norm().preds(v); }\n\n      e_succ_range e_succs (Vertex v) { return norm().e_succs(v); }\n\n      e_pred_range e_preds (Vertex v) { return norm().e_preds(v); }\n\n      void set_to_bottom() { lock(); norm().set_to_bottom(); }\n\n      bool lookup_edge(Vertex s, Vertex d, mut_val_ref_t* w) \n      { lock(); return norm().lookup_edge(s,d,w); }\n\n      void expand(Vertex s, Vertex d) \n      { lock(); norm().expand(s,d); }\n\n      void update_edge (Vertex s, Weight w, Vertex d) { lock(); norm().update_edge(s,w,d); }\n\n      // void full_close () { lock(); norm().full_close(); }\n      // void update_edge_unclosed (Vertex s, Weight w, Vertex d) { lock(); norm().update_edge_unclosed(s,w,d); }\n      void close_edge (Vertex s, Vertex d) { lock(); norm().close_edge(s,d); }\n\n      void remove_from_weights(typename Weight::varname_t v)\n      { lock(); norm().remove_from_weights(v);}\n\n      void operator-=(Vertex v) { lock(); norm() -= v; }\n\n      void write(crab_os& o) { norm().write(o); }\n      void write(crab_os& o, bool print_bottom_edges) { norm().write(o, print_bottom_edges); }\n\n    protected:  \n      array_sgraph_ref_t base_ref;  \n      array_sgraph_ref_t norm_ref;\n    };\n\n\n    // Another C++ datatype to wrap variables and numbers as graph\n    // vertices.\n\n    enum landmark_kind_t { LMC, LMV, LMVP};\n    template<class V, class N>\n    class landmark {\n     protected:\n      landmark_kind_t _kind;\n      landmark(landmark_kind_t kind): _kind(kind) { }\n     public:\n      virtual ~landmark() { }\n      landmark_kind_t kind() const { return _kind;} \n      virtual bool operator==(const landmark<V,N>& o) const = 0;\n      virtual bool operator<(const landmark<V,N>& o) const = 0;\n      virtual void write(crab_os&o) const = 0;\n      virtual std::size_t hash () const = 0;\n    };\n\n    template<class V, class N>\n    class landmark_cst: public landmark<V,N> {\n      N _n;\n      typedef landmark<V,N> landmark_t;\n      typedef landmark_cst<V,N> landmark_cst_t;\n\n     public:\n      landmark_cst (N n): landmark_t(landmark_kind_t::LMC), _n(n) {}\n\n      bool operator==(const landmark_t& o) const {\n        if (this->_kind != o.kind()) return false;\n\n        assert (o.kind () == landmark_kind_t::LMC);\n        auto o_ptr =  static_cast<const landmark_cst_t*>(&o);\n        return (_n == o_ptr->_n);\n      }\n\n      bool operator<(const landmark_t& o) const {\n        if (this->_kind != o.kind()) return true;\n\n        assert (o.kind () == landmark_kind_t::LMC);\n        return (_n < static_cast<const landmark_cst_t*>(&o)->_n);\n      }\n\n      void write(crab_os&o) const { o << _n; }\n\n      std::size_t hash() const { return hash_value(_n);}\n\n      N get_cst () const { return _n;}\n    };\n\n    template<class V, class N>\n    class landmark_var: public landmark<V,N> {\n      V _v;\n      typedef landmark<V,N> landmark_t;\n      typedef landmark_var<V,N> landmark_var_t;\n\n     public:\n      landmark_var (V v) : landmark_t(landmark_kind_t::LMV), _v(v) {}\n\n      bool operator==(const landmark_t& o) const {\n        if (this->_kind != o.kind()) return false;\n\n        assert (o.kind () == landmark_kind_t::LMV);\n        auto o_ptr = static_cast<const landmark_var_t*>(&o);\n        return (_v == o_ptr->_v);\n      }\n\n      bool operator<(const landmark_t& o) const {\n        if (this->_kind == o.kind()) {\n          assert (o.kind () == landmark_kind_t::LMV);\n          auto o_ptr =  static_cast<const landmark_var_t*>(&o);\n          return (_v < o_ptr->_v);\n        } else if (o.kind () == LMC) {\n          return false;\n        } else if (o.kind () == LMVP) {\n          return true;\n        } else  \n          CRAB_ERROR(\"unreachable!\");\n      }\n\n      void write(crab_os&o) const { o << _v; }\n\n      std::size_t hash() const { return hash_value(_v);}\n\n      V get_var () const { return _v;}\n    };\n\n    template<class V, class N>\n    class landmark_varprime: public landmark<V,N> {\n      std::string _lm;\n      V _v;\n      typedef landmark<V,N> landmark_t;\n      typedef landmark_varprime<V,N> landmark_var_prime_t;\n\n     public:\n      landmark_varprime (std::string lm, V v) \n          : landmark_t(landmark_kind_t::LMVP), _lm(lm), _v(v) {}\n\n      bool operator==(const landmark_t& o) const {\n        if (this->_kind != o.kind()) return false;\n        \n        assert (o.kind () == landmark_kind_t::LMVP);\n        auto o_ptr =  static_cast<const landmark_var_prime_t*>(&o);\n        return (_v == o_ptr->_v);\n      }\n\n      bool operator<(const landmark_t& o) const {\n        if (this->_kind != o.kind()) return false;\n\n        assert (o.kind () == landmark_kind_t::LMVP);\n        auto o_ptr =  static_cast<const landmark_var_prime_t*>(&o);\n        return (_v < o_ptr->_v);\n      }\n\n      void write(crab_os&o) const { o << _lm << \"'\"; }\n\n      std::size_t hash() const { return hash_value(_v);}\n\n      V get_var () const { return _v;}\n    };\n\n\n    // Wrapper for landmark\n    template<class V, class N>\n    class landmark_ref {\n      typedef landmark<V,N> landmark_t;\n      typedef landmark_ref<V,N> landmark_ref_t;\n\n     public:\n\n      boost::shared_ptr<landmark_t> _ref;\n\n      landmark_ref(V v, std::string name=\"\"): _ref(nullptr) {\n        if (name==\"\") {\n          _ref = boost::static_pointer_cast<landmark_t>\n              (boost::make_shared<landmark_var<V,N> >(landmark_var<V,N>(v)));\n        } else {\n          _ref = boost::static_pointer_cast<landmark_t>\n              (boost::make_shared<landmark_varprime<V,N> >(landmark_varprime<V,N>(name, v)));\n        }\n      }\n      landmark_ref(N n)\n          : _ref(boost::static_pointer_cast<landmark_t>\n                 (boost::make_shared<landmark_cst<V,N> >(landmark_cst<V,N>(n)))) { }\n      \n      landmark_kind_t kind() const { return _ref->kind();} \n\n      bool operator==(const landmark_ref &o) const { return (*_ref == *(o._ref)); } \n\n      bool operator<(const landmark_ref &o) const { return (*_ref < *(o._ref)); } \n\n      void write(crab_os& o) const { _ref->write(o); } \n\n      std::size_t hash () const { return _ref->hash();}\n    };\n \n    // super unsafe!\n    template<class V, class N>\n    inline V get_var(const landmark_ref<V,N>& lm) {\n      assert (lm.kind() == LMVP);\n      return boost::static_pointer_cast<const landmark_varprime<V,N> >(lm._ref)->get_var();\n    }\n\n    // super unsafe!\n    template<class V, class N>\n    inline N get_cst(const landmark_ref<V,N>& lm) {\n      assert (lm.kind() == LMC);\n      return boost::static_pointer_cast<const landmark_cst<V,N> >(lm._ref)->get_cst();\n    }\n\n    template<class V, class N>\n    inline crab_os& operator<<(crab_os& o, const landmark_ref<V,N> &lm) {\n      lm.write(o);\n      return o;\n    }\n\n    template<class V, class N>\n    inline std::size_t hash_value(const landmark_ref<V,N> &lm) {\n      return lm.hash();\n    }\n\n    /*\n      Reduced product of a numerical domain with a weighted array\n      graph.\n\n      FIXME: the set of array landmarks are chosen statically before\n             starting the analysis (do_initialization). However, at\n             anytime only those alive (using scalar domain) are\n             considered.\n\n             The main issue is that the landmarks are kept as global\n             state. This is really error-prone. For instance,\n             landmarks are reset each time a new CFG is analyzed. For\n             a summary-based inter-procedural analysis might be ok but\n             not, e.g., for inlining.\n    */\n    template<typename NumDom, typename Weight, bool IsDistWeight = false>\n    class array_sparse_graph_domain: \n        public writeable,\n        public numerical_domain<typename NumDom::number_t, typename NumDom::varname_t>,\n        public bitwise_operators<typename NumDom::number_t, typename NumDom::varname_t>, \n        public division_operators<typename NumDom::number_t, typename NumDom::varname_t>,\n        public array_operators<typename NumDom::number_t, typename NumDom::varname_t>,\n        public pointer_operators<typename NumDom::number_t, typename NumDom::varname_t>,\n\tpublic boolean_operators<typename NumDom::number_t, typename NumDom::varname_t>\t\n    {\n      \n     public:\n      typedef typename NumDom::number_t Number;\n      typedef typename NumDom::varname_t VariableName;\n      \n      // WARNING: assume NumDom::number_t = Weight::number_t and\n      //                 NumDom::varname_t = Weight::varname_t\n      using typename numerical_domain< Number, VariableName>::linear_expression_t;\n      using typename numerical_domain< Number, VariableName>::linear_constraint_t;\n      using typename numerical_domain< Number, VariableName>::linear_constraint_system_t;\n      using typename numerical_domain< Number, VariableName>::variable_t;\n      using typename numerical_domain< Number, VariableName>::number_t;\n      using typename numerical_domain< Number, VariableName>::varname_t;\n      typedef crab::pointer_constraint<VariableName> ptr_cst_t;\n      typedef interval<Number> interval_t;\n      \n      typedef landmark_cst<VariableName,Number> landmark_cst_t;\n      typedef landmark_var<VariableName,Number> landmark_var_t;\n      typedef landmark_varprime<VariableName,Number> landmark_var_prime_t;\n      typedef landmark_ref<VariableName,Number> landmark_ref_t;\n      typedef array_sparse_graph<landmark_ref_t,Weight,IsDistWeight> array_sgraph_t;\n      typedef array_sparse_graph_domain<NumDom,Weight,IsDistWeight> array_sgraph_domain_t;\n\n      //// XXX: make this a template parameter later\n      typedef crab::cfg::var_factory_impl::str_var_alloc_col::varname_t str_varname_t;\n      typedef interval_domain<z_number, str_varname_t> str_interval_dom_t;\n      typedef term::TDomInfo<z_number, varname_t, str_interval_dom_t> idom_info;\n      typedef term_domain<idom_info> expression_domain_t;  \n\n     private:\n      typedef typename array_sgraph_t::mut_val_ref_t mut_val_ref_t;\n\n      // Quick wrapper to perform efficient unsat queries on the\n      // scalar domain.\n      struct solver_wrapper {\n        // XXX: do not pass by reference\n        NumDom _inv;\n        solver_wrapper(NumDom inv): _inv(inv) { }\n        bool is_unsat (linear_constraint_t cst) {\n          // XXX: it might modify _inv so that's why we make a copy in\n          // the constructor.\n          return array_sgraph_domain_traits<NumDom>::is_unsat(_inv, cst);        \n        }\n      };\n\n      NumDom _scalar;        \n      expression_domain_t _expressions; // map each program variable to a symbolic expression\n      array_sgraph_t _g;        \n\n      // A landmark is either a variable or number that may appear as\n      // an array index. In addition, for each landmark l we keep\n      // track of a prime landmark l' whose meaning is l'=l+1.\n\n      /// === Static data\n      typedef boost::unordered_map<landmark_ref_t,landmark_ref_t> lm_map_t;\n      static lm_map_t var_landmarks;\n      static lm_map_t cst_landmarks;\n\n      // --- landmark iterators\n      struct get_first : public std::unary_function<typename lm_map_t::value_type,\n\t\t\t\t\t\t    landmark_ref_t> {\n        get_first () {}\n        landmark_ref_t operator()(const typename lm_map_t::value_type &p) const \n        { return p.first; }\n      }; \n      struct get_second : public std::unary_function<typename lm_map_t::value_type,\n\t\t\t\t\t\t     landmark_ref_t> {\n        get_second () {}\n        landmark_ref_t operator()(const typename lm_map_t::value_type &p) const \n        { return p.second; }\n      }; \n      typedef boost::transform_iterator<get_first, \n                                        typename lm_map_t::iterator> lm_iterator;\n      typedef boost::transform_iterator<get_second, \n                                        typename lm_map_t::iterator> lm_prime_iterator;\n      typedef boost::iterator_range<lm_iterator> lm_range;\n      typedef boost::iterator_range<lm_prime_iterator> lm_prime_range;\n\n      lm_prime_iterator var_lm_prime_begin()\n      { return boost::make_transform_iterator(var_landmarks.begin(), get_second());}\n      lm_prime_iterator var_lm_prime_end()\n      { return boost::make_transform_iterator(var_landmarks.end(), get_second());}\n      lm_prime_range var_lm_primes() \n      { return boost::make_iterator_range(var_lm_prime_begin(), var_lm_prime_end());}\n\n      lm_prime_iterator cst_lm_prime_begin()\n      { return boost::make_transform_iterator(cst_landmarks.begin(), get_second());}\n      lm_prime_iterator cst_lm_prime_end()\n      { return boost::make_transform_iterator(cst_landmarks.end(), get_second());}\n      lm_prime_range cst_lm_primes() \n      { return boost::make_iterator_range(cst_lm_prime_begin(), cst_lm_prime_end());}\n                                          \n     \n     public:\n\n      template<class CFG>\n      static void do_initialization (CFG cfg) {\n\n        typedef crab::analyzer::array_segmentation<CFG> array_segment_analysis_t;\n        typedef typename array_segment_analysis_t::array_segment_domain_t\n\t  array_segment_domain_t;\n        typedef crab::analyzer::array_constant_segment_visitor\n\t  <typename CFG::number_t, array_segment_domain_t>\n\t  array_cst_segment_visitor_t;\n\n        std::set<landmark_ref_t> lms;\n\n        // add variables \n        array_segment_analysis_t analysis(cfg);\n        analysis.exec();\n        auto var_indexes = analysis.get_variables(cfg.entry());\n\n        if (var_indexes.begin() == var_indexes.end()) {\n          CRAB_WARN (\"No variables found in the cfg. No array graph landmarks will be added\\n\");\n          return;\n        }\n        lms.insert(var_indexes.begin(), var_indexes.end());\n\n        // get variable factory\n        auto &vfac = (*var_indexes.begin()).get_var_factory ();\n\n        // add constants\n        // make sure 0 is always considered as an array index\n        lms.insert(landmark_ref_t(number_t(0)));\n        typename array_cst_segment_visitor_t::constant_set_t constants;\n        for (auto &bb: boost::make_iterator_range(cfg.begin(), cfg.end())) {\n          auto var_indexes = analysis.get_variables(bb.label());\n          // XXX: use some heuristics to choose \"relevant\" constants\n          array_cst_segment_visitor_t vis(var_indexes);          \n          for (auto &s: boost::make_iterator_range(bb.begin(), bb.end()))\n            s.accept(&vis);\n          auto cst_indexes = vis.get_constants();\n          lms.insert(cst_indexes.begin(), cst_indexes.end());\n        }\n\n        set_landmarks (lms, vfac);\n      }\n\n      template<class Range, class VarFactory>\n      static void set_landmarks(const Range& lms, VarFactory& vfac) {\n        \n        var_landmarks.clear();\n        cst_landmarks.clear();\n        \n        unsigned num_vl = 0;\n        unsigned num_cl = 0;\n\n        for (auto lm: lms) {\n          switch (lm.kind()) {\n            case LMV: {\n              auto v = boost::static_pointer_cast<const landmark_var_t>(lm._ref)->get_var();\n              varname_t v_prime = vfac.get(v.index());\n              landmark_ref_t lm_prime(v_prime, v.str());\n              var_landmarks.insert(std::make_pair(lm, lm_prime));\n              num_vl++;\n              break;\n            }\n            case LMC: {\n              auto n = boost::static_pointer_cast<const landmark_cst_t>(lm._ref)->get_cst();\n              varname_t v_prime = vfac.get(); \n              landmark_ref_t lm_prime(v_prime, n.get_str());\n              cst_landmarks.insert(std::make_pair(lm, lm_prime));\n              num_cl++;\n              break;\n            }\n            default: \n              CRAB_ERROR(\"A landmark can only be either variable or constant\");\n          }\n        }\n        CRAB_LOG(\"array-sgraph-domain-landmark\",\n                 crab::outs() << \"Added \" << num_vl << \" variable landmarks \"\n                              << \"and \" << num_cl << \" constant landmarks={\";\n                 bool first=true;\n                 for (auto &l: var_landmarks) {\n                   if (!first) crab::outs() << \",\";\n                   first=false;\n                   crab::outs() << l.first;\n                 }\n                  for (auto &l: cst_landmarks) {\n                   if (!first) crab::outs() << \",\";\n                   first=false;\n                   crab::outs() << l.first;\n                 }\n                 crab::outs() << \"}\\n\";\n                 );\n      }\n\n     public: // public only for tests\n\n      void add_landmark(VariableName v)\n      {\n        landmark_ref_t lm_v (v);\n        landmark_ref_t lm_v_prime(v.get_var_factory().get(v.index()), v.str());\n        // add pair  x -> x'\n        var_landmarks.insert(std::make_pair(lm_v, lm_v_prime));\n        // x' = x + 1\n        _scalar += make_prime_relation(lm_v_prime, lm_v);\n\n        // reduce between _scalar and the array graph\n        if (!reduce(_scalar, _g)) { \n          // FIXME: incremental version\n          // TODO: we can assume that the scalar domain is zones so\n          // that we can return the affected edges after each\n          // operation and apply reduction only on those edges. That\n          // would suffice for now. If the scalar domain is not zones\n          // then we don't reduce incrementally.\n          set_to_bottom();\n        }\n\n        CRAB_LOG(\"array-sgraph-domain-landmark\", \n                 crab::outs () << \"Added landmark \" << v << \"\\n\";);\n      }\n\n      void remove_landmark(VariableName v) {\n        array_forget (v);\n        forget_prime_var (v);\n        var_landmarks.erase (landmark_ref_t (v));\n\n        CRAB_LOG(\"array-sgraph-domain-landmark\", \n                 crab::outs () << \"Removed landmark \" << v << \"\\n\";);\n      }\n\n\n     private:\n\n      // By active we mean current variables that are kept track by\n      // the scalar domain.\n      void get_active_landmarks(NumDom &scalar, std::vector<landmark_ref_t> & landmarks) const {\n        landmarks.reserve(cst_landmarks.size());\n        for (auto p: cst_landmarks) { \n          landmarks.push_back (p.first);\n          landmarks.push_back (p.second);\n        }\n        auto active_vars = array_sgraph_domain_traits<NumDom>::active_variables(scalar);        \n        for (auto v: active_vars) {\n          auto it = var_landmarks.find(landmark_ref_t(v));\n          if (it != var_landmarks.end()){\n            landmarks.push_back(landmark_ref_t(v)); \n            landmarks.push_back(it->second);\n          }\n        }\n      }\n\n      void set_to_bottom(){\n        _scalar = NumDom::bottom();\n        _expressions = expression_domain_t::bottom();\n        _g.set_to_bottom();\n      }\n\n      linear_expression_t make_expr (landmark_ref_t x) {\n        switch (x.kind()) {\n          case LMC: \n            return boost::static_pointer_cast<landmark_cst_t>(x._ref)->get_cst();\n          case LMV: \n            return variable_t(boost::static_pointer_cast<landmark_var_t>(x._ref)->get_var());\n          case LMVP:\n            return variable_t(boost::static_pointer_cast<landmark_var_prime_t>\n\t\t\t      (x._ref)->get_var());\n          default:\n            CRAB_ERROR(\"unreachable!\");\n        }\n      }\n\n      // make constraint x < y\n      linear_constraint_t make_lt_cst (landmark_ref_t x, landmark_ref_t y) {\n        return linear_constraint_t(make_expr(x) <= make_expr(y) - 1);\n      }\n\n      // make constraint x <= y\n      linear_constraint_t make_leq_cst (landmark_ref_t x, landmark_ref_t y) {\n        return linear_constraint_t(make_expr(x) <= make_expr(y));\n      }\n\n      // make constraint x == y\n      linear_constraint_t make_eq_cst (landmark_ref_t x, landmark_ref_t y) {\n        return linear_constraint_t(make_expr(x) == make_expr(y));\n      }\n\n      // make constraint x' == x+1\n      linear_constraint_t make_prime_relation(landmark_ref_t x_prime, landmark_ref_t x){\n        return linear_constraint_t(make_expr(x_prime) == make_expr(x) + 1);\n      }\n\n      // return true if v is a landmark in the graph\n      bool is_landmark (VariableName v) const {\n        landmark_ref_t lm_v (v);       \n        auto it = var_landmarks.find(lm_v);\n        return (it != var_landmarks.end());\n      }\n\n      // return true if n is a landmark in the graph\n      bool is_landmark (z_number n) const {\n        landmark_ref_t lm_n (n);       \n        auto it = cst_landmarks.find(lm_n);\n        return (it != cst_landmarks.end());\n      }\n\n      // return the prime landmark of v\n      landmark_ref_t get_landmark_prime (VariableName v) const {\n        landmark_ref_t lm_v (v);\n        auto it = var_landmarks.find(lm_v);\n        assert (it != var_landmarks.end());\n        return it->second;\n      }\n\n      // Return the weight from the edge (i, i') otherwise top\n      Weight array_edge (VariableName i) {\n        if (is_bottom()) return Weight::bottom();\n        if (is_top() || !is_landmark (i)) return Weight::top();\n\n        mut_val_ref_t wi;   \n        if (_g.lookup_edge(landmark_ref_t (i), get_landmark_prime(i), &wi))\n          return (Weight) wi;\n        else \n          return Weight::top();\n      } \n\n      // Remove v from the edge (i,i')\n      void array_edge_forget(VariableName i, VariableName v) {\n        if (is_bottom()) return;\n\n        if (!is_landmark (i)) return;\n\n        mut_val_ref_t wi;          \n        landmark_ref_t lm_i (i);\n        landmark_ref_t lm_i_prime = get_landmark_prime (i);\n        if (_g.lookup_edge(lm_i, lm_i_prime, &wi)) {\n          Weight w = (Weight) wi;\n          w -= v;\n          // XXX: update_edge closes the array graph\n          _g.update_edge (lm_i, w, lm_i_prime);\n        }\n      }\n\n      // Remove v from all vertices and edges\n      void array_forget(VariableName v) {\n        if (is_bottom()) return;\n        if (!is_landmark (v)) return;\n\n        _g -= landmark_ref_t(v);\n        _g.remove_from_weights(v);\n      }\n\n      // Update the weight from the edge (i, i')\n      void array_edge_update (VariableName i, Weight w)\n      {\n        if (is_bottom()) return;\n        \n        //--- strong update\n        if (!is_landmark (i)) return;\n\n        landmark_ref_t lm_i(i);\n        landmark_ref_t lm_i_prime = get_landmark_prime(i);\n        \n        _g.update_edge(lm_i, w, lm_i_prime);\n        mut_val_ref_t wi;          \n        if (!_g.lookup_edge(lm_i, lm_i_prime, &wi))\n          return; \n\n        //--- weak update\n        // An edge (p,q) must be weakened if p <= i <= q and p < q\n        solver_wrapper solve(_scalar);\n        mut_val_ref_t w_pq;\n        for(auto p : _g.verts ()) {\n          for(auto e : _g.e_succs(p)) {\n            auto q = e.vert;\n            if ((p == lm_i) &&  (q == lm_i_prime)) \n              continue;\n            if (_g.lookup_edge(p, q, &w_pq) && ((Weight) w_pq).is_bottom())\n              continue;\n            // we know already that p < q in the array graph\n\n            // check p <= i  \n            if (solve.is_unsat(make_leq_cst(p, lm_i)))\n              continue;\n            // check i' <= q\n            if (solve.is_unsat(make_leq_cst(lm_i_prime, q)))\n              continue;\n\n            w_pq = (Weight) w_pq | (Weight) wi;\n          }\n        }\n      }\n\n      // x := x op k \n      template<typename VarOrNum>\n      void apply_one_variable (operation_t op, VariableName x, VarOrNum k) { \n        if (is_bottom()) return;\n\n        if (!is_landmark (x)) {\n          // If x is not a landmark we just apply the operation on the\n          // scalar domain and return.\n          apply_only_scalar(op, x, x, k);\n          return;\n        }\n\n        landmark_ref_t lm_x (x);\n        landmark_ref_t lm_x_prime = get_landmark_prime (x);\n        \n        /// --- Add x_old and x_old' to store old values of x and x'\n\n        VariableName x_old = x.get_var_factory().get();      \n        VariableName x_old_prime = x.get_var_factory().get(); \n        landmark_ref_t lm_x_old (x_old);\n        landmark_ref_t lm_x_old_prime (x_old_prime, x_old.str());\n        var_landmarks.insert(std::make_pair(lm_x_old, lm_x_old_prime));\n        // x_old = x\n        _scalar.assign(x_old, linear_expression_t(x)); \n        // relation between x_old and x' \n        _scalar += make_prime_relation(lm_x_old_prime, lm_x_old);\n        //_scalar += make_eq_cst(lm_x_old_prime, lm_x_prime);      \n\n        /*** Incremental graph reduction ***/\n        //// x_old  has all the x predecessors and successors \n        _g.expand(lm_x, lm_x_old); \n        //// x_old' has all the x' predecessors and successors \n        _g.expand(lm_x_prime, lm_x_old_prime); \n        //// edges between x and x_old \n        _g.update_edge(lm_x, Weight::bottom(), lm_x_old);        \n        _g.update_edge(lm_x_old, Weight::bottom(), lm_x);        \n        //// edges between x' and x_old' \n        _g.update_edge(lm_x_prime, Weight::bottom(), lm_x_old_prime);        \n        _g.update_edge(lm_x_old_prime, Weight::bottom(), lm_x_prime);        \n        //// edges between x_old and x_old'\n        mut_val_ref_t w;   \n        if (_g.lookup_edge(lm_x, lm_x_prime, &w))\n          _g.update_edge(lm_x_old, (Weight) w, lm_x_old_prime);        \n        _g.update_edge(lm_x_old_prime, Weight::bottom(), lm_x_old);        \n\n        /// --- Remove x and x'\n        _g -= lm_x;\n        _g -= lm_x_prime;\n\n        /// --- Perform operation in the scalar domain\n        _scalar.apply(op, x, x, k); \n\n        //restore relation between x and x'\n        _scalar.apply(OP_ADDITION, get_var(lm_x_prime), x, 1);\n        //_scalar -= get_var(lm_x_prime);\n        //_scalar += make_prime_relation(lm_x_prime, lm_x);\n\n        if (!reduce(_scalar, _g)) { // FIXME: incremental version\n          set_to_bottom();\n          return;\n        }\n\n        /// --- Remove x_old and x_old'\n        _g -= lm_x_old;\n        _g -= lm_x_old_prime;\n        _scalar -= x_old;\n        _scalar -= x_old_prime;\n        var_landmarks.erase(lm_x_old);\n      }\n\n      // remove v' from scalar and array graph\n      void forget_prime_var(VariableName v) {\n        if (!is_landmark(v)) return;\n        \n        landmark_ref_t lm_v_prime = get_landmark_prime (v);\n        _scalar -= get_var(lm_v_prime);\n        // XXX: v' cannot appear in the array weights so we do not\n        //      need to call array_forget.\n        _g -= lm_v_prime;        \n      }\n\n      // perform the operation in the scalar domain assuming that\n      // nothing can be done in the graph domain.\n      template<class Op, class K>\n      void apply_only_scalar(Op op, VariableName x, VariableName y, K k) {\n        _scalar.apply(op, x, y, k);\n\n        // Abstract x in the array graph\n        if (is_landmark (x)){ \n          array_forget(x);     // remove x from the array graph\n          forget_prime_var(x); // remove x' from scalar and array graph\n          /// XXX: I think no need to reduce here\n        }\n      }\n            \n\n      // return a pair with the normalized offset and a bool that is\n      // true if a new landmark was added in the array graph\n      std::pair<VariableName,bool> normalize_offset (VariableName o, z_number n)\n      {\n        CRAB_LOG(\"array-sgraph-domain-norm\",\n                 crab::outs() << \"BEFORE NORMALIZE OFFSET: expressions=\"\n\t\t              << _expressions << \"\\n\");\n\n        // --- create a fresh variable no such that no := o;\n        VariableName no = o.get_var_factory().get();\n        _expressions.assign (no, linear_expression_t (o));\n\n        // -- apply no := no / n; in the expressions domain\n        _expressions.apply (operation_t::OP_DIVISION, no, no, n);\n        \n        // -- simplify the expression domain \n        bool simp_done = _expressions.simplify (no);\n\n        CRAB_LOG(\"array-sgraph-domain-norm\",\n                 crab::outs() << \"AFTER NORMALIZE OFFSET: expressions=\"\n\t\t              << _expressions << \"\\n\");\n\n        if (!simp_done) {\n          CRAB_LOG(\"array-sgraph-domain-norm\",\n                   crab::outs() << \"NO NORMALIZATION done using the expression abstraction\\n\");\n\n          // cleanup of the expression abstraction\n          _expressions -= no;\n\n          bool added_lm = false;\n          if (!is_landmark (o)) \n          { add_landmark (o); added_lm = true; } \n                      \n          return std::make_pair(o, added_lm);\n        }\n\n        CRAB_LOG(\"array-sgraph-domain-norm\",\n                 crab::outs() << \"NORMALIZATION DONE! using the expression abstraction\\n\");\n                \n        // -- propagate equalities from _expressions to _scalar\n        product_domain_traits<expression_domain_t, NumDom>::push(no, _expressions, _scalar);\n        \n        // -- add landmark for the new array index\n        add_landmark (no);\n        \n        // cleanup of the expression abstraction\n        _expressions -= no;\n        \n        return std::make_pair(no, true);\n      }\n\n\n     public:\n\n      // The reduction consists of detecting dead segments so it is\n      // done only in one direction (scalar -> array graph). Note that\n      // whenever an edge becomes bottom closure is also happening.\n      // Return false if bottom is detected during the reduction.\n      bool reduce(NumDom &scalar, array_sgraph_t &g) {\n        crab::CrabStats::count (getDomainName() + \".count.reduce\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".reduce\");\n\n        domain_traits<NumDom>::normalize(scalar);\n        g.normalize();\n\n        if (scalar.is_bottom() || g.is_bottom())\n          return false;\n\n        if (!scalar.is_top ()) { \n          std::vector<landmark_ref_t> active_landmarks;\n          get_active_landmarks(scalar, active_landmarks);\n          solver_wrapper solve(scalar);\n          for (auto lm_s : active_landmarks)\n            for (auto lm_d : active_landmarks) {\n              // XXX: we do not exploit the following facts:\n              //   - i < i' is always sat\n              //   - i' < i is always unsat\n              //   - if i < j  unsat then i' < j unsat.\n              //   - if i < j' unsat then i' < j unsat.\n              if ((lm_s == lm_d) || solve.is_unsat (make_lt_cst(lm_s,lm_d))) {\n                g.update_edge(lm_s, Weight::bottom(), lm_d);\n              }\n            }\n        }        \n        return (!g.is_bottom());\n      }\n\n      \n      static array_sgraph_domain_t top () {\n        return array_sgraph_domain_t(false);\n      }\n\n      static array_sgraph_domain_t bottom () {\n        return array_sgraph_domain_t(true);\n      }\n\n     public:\n\n      array_sparse_graph_domain(bool is_bottom=false)\n          : _scalar(NumDom::top()), _expressions(expression_domain_t::top ()), \n            _g(array_sgraph_t::top()) { \n        if (is_bottom) \n          set_to_bottom();\n      }\n\n      array_sparse_graph_domain(const NumDom& s, const expression_domain_t& e, \n                                const array_sgraph_t& g)\n          : _scalar(s), _expressions(e), _g(g) { \n        if (_scalar.is_bottom() || _expressions.is_bottom() || _g.is_bottom())\n          set_to_bottom();\n      }\n    \n      array_sparse_graph_domain(NumDom &&s, expression_domain_t &&e, \n                                array_sgraph_t &&g)\n          : _scalar(std::move(s)), _expressions (std::move(e)), _g(std::move(g)) { \n        if (_scalar.is_bottom() || _expressions.is_bottom() || _g.is_bottom())\n          set_to_bottom();\n      }\n\n      array_sparse_graph_domain(const array_sgraph_domain_t&o)\n          : _scalar(o._scalar), _expressions (o._expressions), _g(o._g) { \n        crab::CrabStats::count (getDomainName() + \".count.copy\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".copy\");\n      }\n\n      array_sparse_graph_domain(array_sgraph_domain_t &&o)\n          : _scalar(std::move(o._scalar)), \n            _expressions (std::move(o._expressions)), \n            _g(std::move(o._g)) { \n      }\n\n      array_sgraph_domain_t& operator=(const array_sgraph_domain_t& o) {\n        crab::CrabStats::count (getDomainName() + \".count.copy\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".copy\");\n        if(this != &o) {\n          _scalar = o._scalar;\n          _expressions = o._expressions;\n          _g = o._g;\n        }\n        return *this;\n      }\n\n      array_sgraph_domain_t& operator=(array_sgraph_domain_t &&o) {\n        _scalar = std::move(o._scalar);\n        _expressions = std::move(o._expressions);\n        _g = std::move(o._g);\n        return *this;\n      }\n      \n      bool is_top() {\n        return _scalar.is_top () && _expressions.is_top () && _g.is_top();\n      }\n      \n      bool is_bottom() {\n        return _scalar.is_bottom() || _expressions.is_bottom() || _g.is_bottom();\n      }\n\n      bool operator<=(array_sgraph_domain_t &o) {\n        crab::CrabStats::count (getDomainName() + \".count.leq\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".leq\");\n\n        CRAB_LOG(\"array-sgraph-domain\",\n                 crab::outs () << \"Leq \" << *this << \" and\\n\"  << o << \"=\\n\";);\n        bool res = (_scalar <= o._scalar) && \n                   (_expressions <= o._expressions) && \n                   (_g <= o._g);\n        CRAB_LOG(\"array-sgraph-domain\", crab::outs () << res << \"\\n\";);\n        return res;\n      }\n\n      void operator|=(array_sgraph_domain_t o)  {\n        *this = (*this | o);\n      }\n\n      array_sgraph_domain_t operator|(array_sgraph_domain_t &o){\n        crab::CrabStats::count (getDomainName() + \".count.join\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".join\");\n\n        CRAB_LOG(\"array-sgraph-domain\",\n                 crab::outs () << \"Join \" << *this << \" and \"  << o << \"=\\n\");\n        array_sgraph_domain_t join(_scalar | o._scalar, \n                                   _expressions | o._expressions,\n                                   _g | o._g);\n        CRAB_LOG(\"array-sgraph-domain\", crab::outs () << join << \"\\n\";);\n        return join;\n      }\n\n      template<typename Thresholds>\n      array_sgraph_domain_t widening_thresholds (array_sgraph_domain_t& o, \n                                                 const Thresholds & ts) {\n        crab::CrabStats::count (getDomainName() + \".count.widening\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".widening\");\n\n          CRAB_LOG(\"array-sgraph-domain\",\n                   crab::outs () << \"Widening (w/ thresholds) \" << *this << \" and \"\n\t\t                 << o << \"=\\n\";);\n        auto widen_scalar(_scalar.widening_thresholds(o._scalar,ts));\n        auto widen_expr(_expressions.widening_thresholds(o._expressions,ts));\n        auto widen_g(_g.widening_thresholds(o._g,ts));\n        if (!reduce(widen_scalar, widen_g)) {\n          CRAB_LOG(\"array-sgraph-domain\", crab::outs () << \"_|_\\n\";);\n          return array_sgraph_domain_t::bottom();\n        } else {\n          array_sgraph_domain_t widen(widen_scalar, widen_expr, widen_g);\n          CRAB_LOG(\"array-sgraph-domain\", crab::outs () << widen << \"\\n\";);\n          return widen;\n        }\n      }\n\n      array_sgraph_domain_t operator||(array_sgraph_domain_t &o){\n        crab::CrabStats::count (getDomainName() + \".count.widening\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".widening\");\n\n        CRAB_LOG(\"array-sgraph-domain\",\n                 crab::outs () << \"Widening \" << *this << \" and \"  << o << \"=\\n\");        \n        auto widen_scalar(_scalar || o._scalar);\n        auto widen_expr(_expressions || o._expressions);\n        auto widen_g(_g || o._g);\n        if (!reduce(widen_scalar, widen_g)) {\n          CRAB_LOG(\"array-sgraph-domain\", crab::outs () << \"_|_\\n\";);\n          return array_sgraph_domain_t::bottom();\n        } else {\n          array_sgraph_domain_t widen(widen_scalar, widen_expr, widen_g);\n          CRAB_LOG(\"array-sgraph-domain\", crab::outs () << widen << \"\\n\";);\n          return widen;\n        }\n      }\n\n      array_sgraph_domain_t operator&(array_sgraph_domain_t &o){\n        crab::CrabStats::count (getDomainName() + \".count.meet\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".meet\");\n\n        CRAB_LOG(\"array-sgraph-domain\",\n                 crab::outs () << \"Meet \" << *this << \" and \"  << o << \"=\\n\");\n        auto meet_scalar(_scalar & o._scalar);\n        auto meet_expr(_expressions & o._expressions);\n        auto meet_g(_g & o._g);\n        if (!reduce(meet_scalar, meet_g)) {\n          CRAB_LOG(\"array-sgraph-domain\", crab::outs () << \"_|_\\n\";);\n          return array_sgraph_domain_t::bottom();\n        } else {\n          array_sgraph_domain_t meet(meet_scalar, meet_expr, meet_g);\n          CRAB_LOG(\"array-sgraph-domain\", crab::outs () << meet << \"\\n\";);\n          return meet;\n        }\n      }\n\n      array_sgraph_domain_t operator&&(array_sgraph_domain_t &o){\n        crab::CrabStats::count (getDomainName() + \".count.narrowing\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".narrowing\");\n\n        CRAB_LOG(\"array-sgraph-domain\",\n                 crab::outs () << \"Narrowing \" << *this << \" and \"  << o << \"=\\n\");\n        auto narrow_scalar(_scalar && o._scalar);\n        auto narrow_expr(_expressions && o._expressions);\n        auto narrow_g(_g && o._g);\n        if (!reduce(narrow_scalar, narrow_g)) {\n          CRAB_LOG(\"array-sgraph-domain\", crab::outs () << \"_|_\\n\";);\n          return array_sgraph_domain_t::bottom();\n        } else {\n          array_sgraph_domain_t narrow(narrow_scalar, narrow_expr, narrow_g);\n          CRAB_LOG(\"array-sgraph-domain\", crab::outs () << narrow << \"\\n\";);\n          return narrow;\n        }\n      }\n\n      void operator-=(VariableName v) {\n        crab::CrabStats::count (getDomainName() + \".count.forget\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".forget\");\n\n        if (is_bottom())\n          return;\n\n        // remove v from scalar and array graph\n        _scalar -= v;\n        // remove v from expressions\n        _expressions -= v;\n        \n        if (is_landmark (v)) {\n          array_forget(v);\n          // remove v' from scalar and array graph\n          forget_prime_var(v);\n        }\n      }\n\n\n      // remove all variables except [vIt,...vEt)\n      template<typename Iterator>\n      void project (Iterator vIt, Iterator vEt) {\n        crab::CrabStats::count (getDomainName() + \".count.project\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".project\");\n\n        if (is_bottom ()) return;\n        if (vIt == vEt) return;\n\n\n        std::set<VariableName> keep_vars (vIt, vEt);\n        auto active_vars = array_sgraph_domain_traits<NumDom>::active_variables(_scalar);        \n        for (auto v: active_vars) {\n          if (!keep_vars.count (v)) {\n            array_forget (v);\n            forget_prime_var (v);\n          }\n        }\n\n        domain_traits<NumDom>::project(_scalar, vIt, vEt);\n        domain_traits<expression_domain_t>::project(_expressions, vIt, vEt);\n\n      }\n\n      void operator+=(linear_constraint_system_t csts) \n      {\n        crab::CrabStats::count (getDomainName() + \".count.add_constraints\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".add_constraints\");\n\n        if (is_bottom()) return;\n        \n        _scalar += csts;\n        _expressions += csts;\n\n        if (!reduce(_scalar, _g)) { // FIXME: incremental version\n          set_to_bottom();\n          return;\n        }\n        CRAB_LOG(\"array-sgraph-domain\", \n                 crab::outs() << \"Assume(\"<< csts<< \") --- \"<< *this<<\"\\n\";);\n      }\n\n      void assign (VariableName x, linear_expression_t e) \n      { assign (x, e, true); }\n\n      // Perform the operation in the scalar (optionally expression)\n      // domain and reduce.\n      // \n      // NOTE: if the assignment is something like i = i + k then we\n      // will lose precision in the array graph. This kind of\n      // assignments should be managed by the apply methods instead.\n      void assign (VariableName x, linear_expression_t e, bool update_expressions) \n      {\n        crab::CrabStats::count (getDomainName() + \".count.assign\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".assign\");\n\n        if (is_bottom()) return;\n\n        if (auto y = e.get_variable()) {\n          // skip x:=x \n          if ((*y).name() == x) \n            return;\n        }\n            \n        _scalar.assign(x, e);\n        if (update_expressions) \n          _expressions.assign(x, e);\n\n        if (is_landmark (x)) {\n           array_forget (x);\n           // remove x' from scalar and array graph\n           forget_prime_var(x);\n           // restore the relationship between x and x'\n           _scalar.apply(OP_ADDITION, get_var(get_landmark_prime (x)), x, 1);\n           // XXX: is it needed ??\n           //_g.close_edge (landmark_ref_t(x), get_landmark_prime (x));\n        }\n\n        if (!reduce(_scalar, _g)) { // FIXME: incremental version\n          set_to_bottom();\n          return;\n        }\n\n        CRAB_LOG(\"array-sgraph-domain\", \n                 crab::outs() << \"Assign \"<<x<<\" := \"<<e<<\" ==> \"<<*this<<\"\\n\";);\n      }\n\n      void apply (operation_t op, VariableName x, VariableName y, Number z) {\n        if (x == y) {\n          crab::CrabStats::count (getDomainName() + \".count.apply\");\n          crab::ScopedCrabStats __st__(getDomainName() + \".apply\");\n          _expressions.apply (op, x, y, z);\n          apply_one_variable<Number> (op, x, z);\n          CRAB_LOG(\"array-sgraph-domain\",\n                   crab::outs() << \"Apply \"<<x<<\" := \"<<y<<\" \"<<op<<\" \"<<z<<\" ==> \"\n\t\t                << *this<<\"\\n\";); \n        }\n        else {\n          switch (op) {\n            case OP_ADDITION:\n              assign (x, linear_expression_t(y) + linear_expression_t(z)); break;\n            case OP_SUBTRACTION:\n              assign (x, linear_expression_t(y) - linear_expression_t(z)); break;\n            case OP_MULTIPLICATION:\n              assign (x, linear_expression_t(y) * z); break;\n            case OP_DIVISION:\n              CRAB_WARN(\"Division operation not implemented in array-sgraph-domain\\n\");\n            default: ;;\n          }\n        }\n      }\n      \n      void apply(operation_t op, VariableName x, VariableName y, VariableName z)  {\n        if (x==y) {\n          crab::CrabStats::count (getDomainName() + \".count.apply\");\n          crab::ScopedCrabStats __st__(getDomainName() + \".apply\");\n          _expressions.apply (op, x, y, z);\n          apply_one_variable<VariableName> (op, x, z);\n          CRAB_LOG(\"array-sgraph-domain\", \n                   crab::outs() << \"Apply \"<<x<<\" := \"<<y<<\" \"<<op<<\" \"<<z<<\" ==> \"\n\t\t                << *this<<\"\\n\";);\n        }\n        else {\n          switch (op) {\n            case OP_ADDITION:\n              assign (x, linear_expression_t(y) + linear_expression_t(z)); break;\n            case OP_SUBTRACTION:\n              assign (x, linear_expression_t(y) - linear_expression_t(z)); break;\n            case OP_MULTIPLICATION:\n              CRAB_WARN(\"Mutiplication not implemented in array-sgraph-domain\\n\"); break;\n            case OP_DIVISION:              \n              CRAB_WARN(\"Division not implemented in array-sgraph-domain\\n\"); break;\n            default:;;\n          }\n        }\n      }\n\n      void apply(operation_t op, VariableName x, Number k)  {\n        crab::CrabStats::count (getDomainName() + \".count.apply\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".apply\");\n        _expressions.apply (op, x, k);\n        apply_one_variable <Number> (op, x, k);\n\n        CRAB_LOG(\"array-sgraph-domain\",\n                 crab::outs() << \"Apply \"<<x<<\" := \"<<x<<\" \"<<op<<\" \"<<k<<\" ==> \"\n\t\t              << *this<<\"\\n\";);\n      }\n\n      void apply(conv_operation_t op, VariableName x, VariableName y, unsigned width) {\n        _expressions.apply (op, x, y, width);\n        // assume unlimited precision so width is ignored.\n        assign(x, variable_t (y), false);\n      }\n      \n      void apply(conv_operation_t op, VariableName x, Number k, unsigned width) {\n        _expressions.apply (op, x, k, width);\n        // assume unlimited precision so width is ignored.\n        assign(x, k, false);\n      }\n\n      // bitwise_operators_api      \n      void apply(bitwise_operation_t op, VariableName x, VariableName y, VariableName z) {\n        crab::CrabStats::count (getDomainName() + \".count.apply\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".apply\");\n\n        _expressions.apply (op, x, y, z);\n        // XXX: we give up soundly in the graph domain\n        apply_only_scalar (op, x, y, z);\n      }\n      \n      void apply(bitwise_operation_t op, VariableName x, VariableName y, Number k) {\n        crab::CrabStats::count (getDomainName() + \".count.apply\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".apply\");\n\n        _expressions.apply (op, x, y, k);\n        // XXX: we give up soundly in the graph domain\n        apply_only_scalar (op, x, y, k);\n      }\n      \n      // division_operators_api\n      void apply(div_operation_t op, VariableName x, VariableName y, VariableName z) {\n        crab::CrabStats::count (getDomainName() + \".count.apply\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".apply\");\n\n        _expressions.apply (op, x, y, z);\n        // XXX: we give up soundly in the graph domain\n        apply_only_scalar (op, x, y, z);\n      }\n      \n      void apply(div_operation_t op, VariableName x, VariableName y, Number k) {\n        crab::CrabStats::count (getDomainName() + \".count.apply\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".apply\");\n\n        _expressions.apply (op, x, y, k);\n        // XXX: we give up soundly in the graph domain\n        apply_only_scalar (op, x, y, k);\n      }\n\n      interval_t operator[](VariableName v)  {\n        return _scalar[v];\n      }\n\n      // pointer_operators_api\n      virtual void pointer_load (VariableName lhs, VariableName rhs) override {\n        _scalar.pointer_load(lhs,rhs);\n      }\n      \n      virtual void pointer_store (VariableName lhs, VariableName rhs) override {\n        _scalar.pointer_store(lhs,rhs);\n      } \n      \n      virtual void pointer_assign (VariableName lhs, VariableName rhs,\n\t\t\t\t   linear_expression_t offset) override {\n        _scalar.pointer_assign (lhs,rhs,offset);\n      }\n      \n      virtual void pointer_mk_obj (VariableName lhs, ikos::index_t address) override {\n        _scalar.pointer_mk_obj (lhs, address);\n      }\n      \n      virtual void pointer_function (VariableName lhs, VariableName func) override {\n        _scalar.pointer_function (lhs, func);\n      }\n      \n      virtual void pointer_mk_null (VariableName lhs) override {\n        _scalar.pointer_mk_null (lhs);\n      }\n      \n      virtual void pointer_assume (ptr_cst_t cst) override {\n        _scalar.pointer_assume (cst);\n      }    \n      \n      virtual void pointer_assert (ptr_cst_t cst) override {\n        _scalar.pointer_assert (cst);\n      }    \n        \n\n      // array_operators_api       \n\n      virtual void array_assume (VariableName a, variable_type a_ty, \n                                 linear_expression_t lb_idx, linear_expression_t ub_idx, \n                                 VariableName var) override {\n        \n        auto lb_var_opt = lb_idx.get_variable ();\n        auto ub_var_opt = ub_idx.get_variable ();\n\n        if (lb_idx.is_constant () && ub_idx.is_constant ())\n          array_assume (a, a_ty, lb_idx.constant (), ub_idx.constant (), var);\n        else if (lb_idx.is_constant () && ub_var_opt)\n          array_assume (a, a_ty, lb_idx.constant (), (*ub_var_opt).name(), var);\n        else if (lb_var_opt && ub_idx.is_constant ())\n          array_assume (a, a_ty, (*lb_var_opt).name(), ub_idx.constant (), var);\n        else if (lb_var_opt && ub_var_opt)\n          array_assume (a, a_ty, (*lb_var_opt).name(), (*ub_var_opt).name(), var);\n        else\n          CRAB_WARN (\"array_sparse_graph only supports assume_array with number or cst indexes\");\n      }\n\n      virtual void array_load (VariableName lhs, VariableName a, crab::variable_type a_ty,\n                               linear_expression_t i, z_number nbytes) override \n      {\n\n        crab::CrabStats::count (getDomainName() + \".count.load\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".load\");\n\n        auto vi = i.get_variable ();\n        if (!vi) {\n          CRAB_WARN (\"TODO: array load index must be a variable\");\n          return;\n        }\n\n        // -- normalization ensures that closure and reduction have\n        // -- been applied.\n        auto p = normalize_offset ((*vi).name(), nbytes);\n        VariableName norm_idx = p.first;\n\n        // #if 0\n        // if (is_landmark (norm_idx)) {\n        //   landmark_ref_t lm_norm_idx(norm_idx);\n        //   landmark_ref_t lm_norm_idx_prime = get_landmark_prime (norm_idx);\n          \n        //   _g.close_edge (lm_norm_idx, lm_norm_idx_prime);\n        //   crab::outs () << \"#### 1 \" << _g << \"\\n\"; \n          \n        //   Weight w;\n        //   w += linear_constraint_t(linear_expression_t(lhs) == linear_expression_t(a));\n        //   crab::outs () << \"#### 2 \" << w << \"\\n\";\n        //   //_g.update_edge_unclosed(lm_norm_idx, w, lm_norm_idx_prime);\n        //   _g.update_edge(lm_norm_idx, w, lm_norm_idx_prime);\n        // }\n        // #endif \n\n        Weight w = array_edge (norm_idx);\n\n        if (a_ty == ARR_INT_TYPE) {\n          // Only non-relational numerical invariants are\n          // propagated from the graph domain to the expressions domain.\n          _expressions.set (lhs, w[a]);\n        }\n\n        array_sparse_graph_impl::propagate_between_weight_and_scalar(w, a, a_ty, _scalar, lhs);\n        \n        // if normalize_offset created a landmark we remove it here to\n        // keep smaller array graph\n        if (p.second) remove_landmark (norm_idx); \n\n        /// XXX: due to the above simplification we need to reduce\n        /// only if the content of an array cell can be an index.\n        if (is_landmark (lhs))\n          if (!reduce(_scalar,_g)) // FIXME: incremental version\n            set_to_bottom();\n        \n        CRAB_LOG(\"array-sgraph-domain\",\n                 crab::outs() << \"Array read \"<<lhs<<\" := \"<< a<<\"[\"<<i<<\"] ==> \"\n                               << *this <<\"\\n\";);    \n      }\n\n      virtual void array_store (VariableName a, crab::variable_type a_ty,\n                                linear_expression_t i, VariableName val, \n                                z_number nbytes, bool /*is_singleton*/) override {\n        crab::CrabStats::count (getDomainName() + \".count.store\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".store\");\n\n        auto vi = i.get_variable ();\n        if (!vi) {\n          CRAB_WARN (\"TODO: array store index must be a variable\");\n          return;\n        }\n\n        Weight w = Weight::top ();\n        array_sparse_graph_impl::propagate_between_weight_and_scalar(_scalar, val, a_ty, w, a);\n\n        auto p = normalize_offset ((*vi).name(), nbytes);\n        VariableName norm_idx = p.first;\n\n        array_edge_forget (norm_idx, a);\n        array_edge_update (norm_idx, w);\n\n        // XXX: since we do not propagate from the array weights to\n        // the scalar domain I think we don't need to reduce here.\n\n        CRAB_LOG(\"array-sgraph-domain\",\n                 crab::outs() << \"Array write \"<<a<<\"[\"<<i<<\"] := \"<<val<< \" ==> \"\n                              << *this <<\"\\n\";);\n      }\n\n      // T1 and T2 are either VariableName or z_number\n      template<typename T1, typename T2>\n      void array_assume (VariableName arr, variable_type arr_ty, T1 src, T2 dst,\n\t\t\t VariableName val)\n      {\n        if (!is_landmark (src)) {\n          crab::outs () << \"WARNING no landmark found for \" << src << \"\\n\";\n          return;\n        }\n\n        if (!is_landmark(dst)) {\n          crab::outs () << \"WARNING no landmark found for \" << dst << \"\\n\";\n          return;\n        }\n       \n        landmark_ref_t lm_src (src);\n        landmark_ref_t lm_dst (dst); \n\n        Weight w = Weight::top ();\n        array_sparse_graph_impl::propagate_between_weight_and_scalar\n\t  (_scalar, val, arr_ty, w, arr);\n        _g.update_edge(lm_src, w, lm_dst);        \n      }\n    \n      void write(crab_os& o) {\n        #if 1\n        NumDom copy_scalar(_scalar);\n        array_sgraph_t copy_g(_g);\n        // Remove all primed variables for pretty printing\n        for(auto lm: var_lm_primes()) {\n          copy_scalar -= get_var(lm);\n          copy_g -= lm;\n        }\n        for(auto lm: cst_lm_primes()) {\n          copy_scalar -= get_var(lm);\n          copy_g -= lm;\n        }\n        o << \"(\" << copy_scalar  << \",\";\n        copy_g.write(o,false);  // we do not print bottom edges\n        o << \")\";\n        //o << \"##\" << _expressions;\n        #else\n        o << \"(\" \n          << \"S=\" << _scalar  << \",\"\n          << \"E=\" << _expressions  << \",\"\n          << \"G=\" << _g\n          << \")\";\n        #endif \n      }\n\n      // XXX: the array domain is disjunctive so it is not really\n      // useful to express it through a conjunction of linear\n      // constraints\n      linear_constraint_system_t to_linear_constraint_system (){\n        CRAB_WARN (\"array-sgraph does not implement to_linear_constraint_system\");\n        return linear_constraint_system_t();\n      }\n\n      static std::string getDomainName () {\n        std::string name (\"ArraySparseGraph(\" + \n\t\t\t  NumDom::getDomainName () +  \",\" +  Weight::getDomainName () + \")\");\n        return name;\n      }\n\n    };\n\n    template<typename NumDom, typename Weight>\n    class domain_traits<array_sparse_graph_domain<NumDom,Weight,false> > {\n\n     public:\n      // WARNING: assume NumDom::number_t = Weight::number_t and\n      //                 NumDom::varname_t = Weight::varname_t\n      typedef typename NumDom::number_t N;\n      typedef typename NumDom::varname_t V;\n      \n      typedef array_sparse_graph_domain<NumDom,Weight,false> array_sgraph_domain_t;\n\n      template<class CFG>\n      static void do_initialization (CFG cfg) {\n        array_sgraph_domain_t::do_initialization(cfg);\n      }\n\n      static void expand (array_sgraph_domain_t& inv, V x, V new_x) {\n        CRAB_WARN (\"array_graph_domain expand not implemented\");\n      }\n    \n      static void normalize (array_sgraph_domain_t& inv) {\n        CRAB_WARN (\"array_graph_domain normalize not implemented\");\n      }\n    \n      template <typename Iter>\n      static void forget (array_sgraph_domain_t& inv, Iter it, Iter end){\n        for (auto v: boost::make_iterator_range(it,end))\n        { inv -= v; }\n      }\n\n      template <typename Iter>\n      static void project (array_sgraph_domain_t& inv, Iter it, Iter end) {\n        inv.project (it, end);\n      }\n    };\n  \n    // Static data allocation\n    template<class Dom, class Wt, bool IsDistWt>\n    boost::unordered_map<landmark_ref<typename Dom::varname_t, typename Dom::number_t>, \n                         landmark_ref<typename Dom::varname_t, typename Dom::number_t> > \n    array_sparse_graph_domain<Dom,Wt,IsDistWt>::var_landmarks;\n\n    template<class Dom, class Wt, bool IsDistWt>\n    boost::unordered_map<landmark_ref<typename Dom::varname_t, typename Dom::number_t>, \n                         landmark_ref<typename Dom::varname_t, typename Dom::number_t> > \n    array_sparse_graph_domain<Dom,Wt,IsDistWt>::cst_landmarks;\n\n  } // end namespace domains\n \n} // end namespace crab\n#pragma GCC diagnostic pop\n#endif \n", "meta": {"hexsha": "5997338399b65ab86aadd81e89ea562f9ade24fe", "size": 88705, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/crab/domains/array_sparse_graph.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/domains/array_sparse_graph.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/domains/array_sparse_graph.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": 35.7825736184, "max_line_length": 113, "alphanum_fraction": 0.5680175864, "num_tokens": 21391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.46989938103572376}}
{"text": "// This file is part of Eigen, a lightweight C++ template library\r\n// for linear algebra.\r\n//\r\n// Copyright (C) 2008-2012 Gael Guennebaud <gael.guennebaud@inria.fr>\r\n// Copyright (C) 2012 D\u00e9sir\u00e9 Nuentsa-Wakam <desire.nuentsa_wakam@inria.fr>\r\n//\r\n// This Source Code Form is subject to the terms of the Mozilla\r\n// Public License v. 2.0. If a copy of the MPL was not distributed\r\n// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.\r\n#include \"sparse_solver.h\"\r\n#include <Eigen/PaStiXSupport>\r\n#include <unsupported/Eigen/SparseExtra>\r\n\r\n\r\ntemplate<typename T> void test_pastix_T()\r\n{\r\n  PastixLLT< SparseMatrix<T, ColMajor>, Eigen::Lower > pastix_llt_lower;\r\n  PastixLDLT< SparseMatrix<T, ColMajor>, Eigen::Lower > pastix_ldlt_lower;\r\n  PastixLLT< SparseMatrix<T, ColMajor>, Eigen::Upper > pastix_llt_upper;\r\n  PastixLDLT< SparseMatrix<T, ColMajor>, Eigen::Upper > pastix_ldlt_upper;\r\n  PastixLU< SparseMatrix<T, ColMajor> > pastix_lu;\r\n\r\n  check_sparse_spd_solving(pastix_llt_lower);\r\n  check_sparse_spd_solving(pastix_ldlt_lower);\r\n  check_sparse_spd_solving(pastix_llt_upper);\r\n  check_sparse_spd_solving(pastix_ldlt_upper);\r\n  check_sparse_square_solving(pastix_lu);\r\n}\r\n\r\n// There is no support for selfadjoint matrices with PaStiX. \r\n// Complex symmetric matrices should pass though\r\ntemplate<typename T> void test_pastix_T_LU()\r\n{\r\n  PastixLU< SparseMatrix<T, ColMajor> > pastix_lu;\r\n  check_sparse_square_solving(pastix_lu);\r\n}\r\n\r\nvoid test_pastix_support()\r\n{\r\n  CALL_SUBTEST_1(test_pastix_T<float>());\r\n  CALL_SUBTEST_2(test_pastix_T<double>());\r\n  CALL_SUBTEST_3( (test_pastix_T_LU<std::complex<float> >()) );\r\n  CALL_SUBTEST_4(test_pastix_T_LU<std::complex<double> >());\r\n} ", "meta": {"hexsha": "738d80791e120292d502f4e2b4dd50daa18037c6", "size": 1703, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "eigen/test/pastix_support.cpp", "max_stars_repo_name": "subond/tools", "max_stars_repo_head_hexsha": "05b93e6c78eab65ef6587e684303b12c686a3480", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "eigen/test/pastix_support.cpp", "max_issues_repo_name": "subond/tools", "max_issues_repo_head_hexsha": "05b93e6c78eab65ef6587e684303b12c686a3480", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "eigen/test/pastix_support.cpp", "max_forks_repo_name": "subond/tools", "max_forks_repo_head_hexsha": "05b93e6c78eab65ef6587e684303b12c686a3480", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-04T15:41:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-04T15:41:53.000Z", "avg_line_length": 38.7045454545, "max_line_length": 75, "alphanum_fraction": 0.7498532002, "num_tokens": 499, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389817407016, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.46989937392553743}}
{"text": "\n#include <iostream>\n\n#include \"EKFBallModel.hpp\"\n\n/* Lin Alg Includes */\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n\nusing namespace std;\nusing namespace Geometry2d;\n\nModeling::EKFBallModel::EKFBallModel(RobotModel::RobotMap* robotMap,\n                                     Configuration* config)\n    : BallModel(robotMap, config),\n      _processNoiseSqrdPos(config, \"EKFModelBall/Process Noise Position\", 0.2),\n      _processNoiseSqrdVel(config, \"EKFModelBall/Process Noise Velocity\", 1.0),\n      _measurementNoiseSqrd(config, \"EKFModelBall/Measurement Noise Position\",\n                            0.01) {\n    typedef boost::numeric::ublas::vector<double> Vector;\n    typedef boost::numeric::ublas::matrix<double> Matrix;\n\n    _ekf = new ExtendedKalmanFilter(Q, R);\n}\n\nModeling::EKFBallModel::~EKFBallModel() {\n    if (_ekf) {\n        delete _ekf;\n    }\n}\n\nvoid Modeling::EKFBallModel::singleUpdate(float dtime) {\n    raoBlackwellizedParticleFilter->update(observedPos.x, observedPos.y, dtime);\n    RbpfState* bestState = raoBlackwellizedParticleFilter->getBestFilterState();\n    Point posOld = pos;\n    pos.x = bestState->X(0);\n    pos.y = bestState->X(1);\n    vel.x = bestState->X(2);\n    vel.y = bestState->X(3);\n    accel.x = bestState->X(4);\n    accel.y = bestState->X(5);\n}\n\nvoid Modeling::EKFBallModel::update(float dtime) {\n    if (_observations.size() >=\n        1) {  // currently hacked to just handle a single update\n        // pick the closest observation to the current estimate\n        float bestDist = 99999;\n        for (const observation_type& observation : _observations) {\n            if (observation.pos.distTo(pos) < bestDist) {\n                bestDist = observation.pos.distTo(pos);\n                observedPos = observation.pos;\n            }\n        }\n        float dtime = (float)(_observations.at(0).time - lastUpdatedTime) / 1e6;\n        singleUpdate(dtime);\n    }\n}\n\nvoid Modeling::EKFBallModel::initParams();\n", "meta": {"hexsha": "d051158ec7a6c36ddfd9e1e48cf3927a4562cab2", "size": 1982, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "old/modeling-old/EKFBallModel.cpp", "max_stars_repo_name": "Alex-Gurung/robocup-software", "max_stars_repo_head_hexsha": "9271df5ed16928f0081fc81c50affb0a08dd54bd", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-09-25T20:28:58.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-25T20:28:58.000Z", "max_issues_repo_path": "old/modeling-old/EKFBallModel.cpp", "max_issues_repo_name": "Alex-Gurung/robocup-software", "max_issues_repo_head_hexsha": "9271df5ed16928f0081fc81c50affb0a08dd54bd", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "old/modeling-old/EKFBallModel.cpp", "max_forks_repo_name": "Alex-Gurung/robocup-software", "max_forks_repo_head_hexsha": "9271df5ed16928f0081fc81c50affb0a08dd54bd", "max_forks_repo_licenses": ["Apache-2.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.4918032787, "max_line_length": 80, "alphanum_fraction": 0.6528758829, "num_tokens": 517, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4698218196514036}}
{"text": "#pragma once\n#include <numeric>\n#include <iostream>\n#include <Eigen/Dense>\n#include <autoppl/math/ess.hpp>\n\nnamespace ppl {\n\ntemplate <class Derived>\ninline auto mean(const Eigen::MatrixBase<Derived>& m)\n{ return m.colwise().mean(); }\n\ntemplate <class Derived>\ninline auto sd(const Eigen::MatrixBase<Derived>& m)\n{\n    assert(m.rows() > 1);\n    auto var = (m.rowwise() - ppl::mean(m))\n                    .colwise().squaredNorm() / (m.rows() - 1);\n    return var.array().sqrt().matrix();\n}\n\ninline void summary(const std::string& header,\n                    const Eigen::MatrixXd& m,\n                    double warmup_time,\n                    double sampling_time)\n{\n    std::cout << \"Warmup: \" << warmup_time << std::endl;\n    std::cout << \"Sampling: \" << sampling_time << std::endl;\n\n    std::cout << header << std::endl;\n\n    Eigen::MatrixXd mean = ppl::mean(m);\n    std::cout << \"Mean:\\n\"\n              << mean << std::endl; \n\n    Eigen::MatrixXd sd = ppl::sd(m);\n    std::cout << \"SD:\\n\"\n              << sd << std::endl; \n\n    Eigen::MatrixXd ess = ppl::math::ess(m);\n    std::cout << \"ESS:\\n\"\n              << ess << std::endl;\n\n    Eigen::MatrixXd ess_per_s = ess / sampling_time;\n    std::cout << \"ESS/s:\\n\"\n              << ess_per_s << std::endl;\n}\n\n} // namespace ppl\n", "meta": {"hexsha": "0ec7326c744249ae66ef8128d12120fff75c6d53", "size": 1281, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "benchmark/benchmark_utils.hpp", "max_stars_repo_name": "JamesYang007/autoppl", "max_stars_repo_head_hexsha": "e78f8d229d2e399f86f338e473da5ddc7dbed053", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 37.0, "max_stars_repo_stars_event_min_datetime": "2020-04-12T19:45:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-28T19:05:38.000Z", "max_issues_repo_path": "benchmark/benchmark_utils.hpp", "max_issues_repo_name": "JamesYang007/autoppl", "max_issues_repo_head_hexsha": "e78f8d229d2e399f86f338e473da5ddc7dbed053", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2020-04-26T14:55:52.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-13T19:21:50.000Z", "max_forks_repo_path": "benchmark/benchmark_utils.hpp", "max_forks_repo_name": "JamesYang007/autoppl", "max_forks_repo_head_hexsha": "e78f8d229d2e399f86f338e473da5ddc7dbed053", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2020-04-15T04:45:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T17:28:42.000Z", "avg_line_length": 25.62, "max_line_length": 62, "alphanum_fraction": 0.5519125683, "num_tokens": 335, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765706, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.46982181473571233}}
{"text": "\n\n#define BOOST_TEST_MAIN\n#include <boost/test/unit_test.hpp>\n\n\n#include \"Voxelizer/include/helper_math.h\"\n#include \"Voxelizer/include/voxelizer.h\"\n\n\n#include \"../src/kernels/voxelizationUtils.h\"\n#include \"../src/base/GeometryHandler.h\"\n#include \"../src/io/FileReader.h\"\n\nBOOST_AUTO_TEST_SUITE(VoxelizerTest)\n\nBOOST_AUTO_TEST_CASE(VoxelizeGeometry) {\n  GeometryHandler gh;\n  FileReader fr;\n  fr.readVTK(&gh, \"./Data/box_753.vtk\");\n\n  // Shortcut variables\n  nv::Vec3f bb = gh.getBoundingBox();\n  float* verts = gh.getVerticePtr();\n  unsigned int* indices = gh.getIndexPtr();\n  unsigned int num_triangles = gh.getNumberOfTriangles();\n  unsigned int num_vertices = gh.getNumberOfVertices();\n  unsigned int num_uniq_mat = 1;\n\n  unsigned int displace_mesh_voxels = 1;\n  double voxel_edge = 0.02;\n  uint3 vox_dim;\n  vox_dim = get_Geometry_surface_Voxelization_dims(verts, indices,\n                                                   num_triangles,\n                                                   num_vertices,\n                                                   voxel_edge);\n\n  // Vox dims are padded by default to be multiple of uint3(32, 4, 1)\n  // Additionally 1 layers of cells are added at each end\n  unsigned int check_x = (unsigned int)round(bb.x/voxel_edge)+2;\n  check_x += (32-(check_x%32));\n  unsigned int check_y = (unsigned int)round(bb.y/voxel_edge)+2;\n  check_y += (4-(check_y%4));\n  unsigned int check_z = (unsigned int)round(bb.z/voxel_edge)+2;\n\n  BOOST_CHECK_EQUAL(vox_dim.x, check_x);\n  BOOST_CHECK_EQUAL(vox_dim.y, check_y);\n  BOOST_CHECK_EQUAL(vox_dim.z, check_z);\n\n  std::vector<unsigned char> materials(num_triangles, 1);\n\n  unsigned char* h_pos = NULL;\n  unsigned char* h_mat = NULL;\n\n  voxelizeGeometrySurfToHost(&(verts[0]),\n                             &(indices[0]),\n                             &(materials[0]),\n                             num_triangles,\n                             num_vertices,\n                             num_uniq_mat,\n                             voxel_edge,\n                             &h_pos,\n                             &h_mat,\n                             &vox_dim,\n                             displace_mesh_voxels,\n                             VOX_6_SEPARATING,\n                             make_uint3(32, 4, 1),\n                             0, vox_dim.z);\n\n  unsigned int dim_x = vox_dim.x;\n  unsigned int dim_y = vox_dim.y;\n  unsigned int dim_z = vox_dim.z;\n  unsigned int dim_xy = vox_dim.x*vox_dim.y;\n\n  // Edge of the geometry is at coordinate 1, 1, 2\n  BOOST_CHECK_EQUAL(h_pos[1+dim_x+dim_xy*2], 0);\n\n  // Check how many voxels are inside\n  bool in = false;\n  unsigned int count = 0;\n  for(unsigned int i = 0; i < dim_x; i++) {\n    unsigned int cur = i+2*dim_x+dim_xy*3;\n    unsigned char val = h_pos[cur];\n    if(val == 0) {\n      printf(\"IN/OUT, x: %u\\n\", i);\n      in = !in;\n    }\n    if(val == 128 && in)\n      count++;\n  }\n\n  // Calculate the number of voxels from the initial bounding box\n  unsigned int check = (unsigned int)floor(bb.x/voxel_edge);\n  BOOST_CHECK_EQUAL(count, check);\n\n  // Check boundary value calculation\n  calcBoundaryValuesInplace(h_pos, dim_x, dim_y, dim_z);\n\n  // \"outside\" point should still be where it was\n  BOOST_CHECK_EQUAL((unsigned int)h_pos[1+dim_x+dim_xy*2], 0);\n  // A corner should lie one step diagonally in\n  BOOST_CHECK_EQUAL((unsigned int)h_pos[2+dim_x*2+dim_xy*3], 3+128);\n  // One next to it towards x should be an edge\n  BOOST_CHECK_EQUAL((unsigned int)h_pos[3+dim_x*2+dim_xy*3], 4+128);\n  // One step towards y should be a wall\n  BOOST_CHECK_EQUAL((unsigned int)h_pos[3+dim_x*3+dim_xy*3], 5+128);\n  // One step towards z should be air\n  BOOST_CHECK_EQUAL((unsigned int)h_pos[3+dim_x*3+dim_xy*4], 6+128);\n\n  // Check material index calculation\n  calcMaterialIndicesInplace(h_mat, h_pos, dim_x, dim_y, dim_z);\n\n  // Only one material now so all should be 1\n  BOOST_CHECK_EQUAL((unsigned int)h_mat[2+dim_x*2+dim_xy*3], 1);\n  BOOST_CHECK_EQUAL((unsigned int)h_mat[3+dim_x*2+dim_xy*3], 1);\n  BOOST_CHECK_EQUAL((unsigned int)h_mat[3+dim_x*3+dim_xy*3], 1);\n  // Except air is 0\n  BOOST_CHECK_EQUAL((unsigned int)h_mat[3+dim_x*3+dim_xy*4], 0);\n\n  delete[] h_pos;\n  delete[] h_mat;\n}\n\nBOOST_AUTO_TEST_CASE(PadWithZerosTest) {\n\n\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "338b672cfc4924f9811e5e747e35a268eb499468", "size": 4261, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/VoxelizerTest.cpp", "max_stars_repo_name": "bijulette/ParallelFDTD", "max_stars_repo_head_hexsha": "8e1fde06998d5468a657b3bd5652cf118ee50ba7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-03-09T14:11:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T14:11:16.000Z", "max_issues_repo_path": "tests/VoxelizerTest.cpp", "max_issues_repo_name": "bijulette/ParallelFDTD", "max_issues_repo_head_hexsha": "8e1fde06998d5468a657b3bd5652cf118ee50ba7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/VoxelizerTest.cpp", "max_forks_repo_name": "bijulette/ParallelFDTD", "max_forks_repo_head_hexsha": "8e1fde06998d5468a657b3bd5652cf118ee50ba7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-06-22T07:21:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-28T22:08:37.000Z", "avg_line_length": 32.5267175573, "max_line_length": 69, "alphanum_fraction": 0.6261440976, "num_tokens": 1167, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503206, "lm_q2_score": 0.5698526514141572, "lm_q1q2_score": 0.469821809820021}}
{"text": "#if USE_MKL\n#include <mkl.h>\n#endif\n\n#include <boost/math/special_functions/next.hpp>\n#include <boost/random.hpp>\n\n#include <algorithm>\n#include <limits>\n\n#include \"caffe/common.hpp\"\n#include \"caffe/util/math_functions.hpp\"\n#include \"caffe/util/rng.hpp\"\n\n\nnamespace caffe {\n\ntemplate<>\nvoid caffe_cpu_gemm<float>(const CBLAS_TRANSPOSE TransA,\n    const CBLAS_TRANSPOSE TransB, const int M, const int N, const int K,\n    const float alpha, const float* A, const float* B, const float beta,\n    float* C) {\n  int lda = (TransA == CblasNoTrans) ? K : M;\n  int ldb = (TransB == CblasNoTrans) ? N : K;\n  cblas_sgemm(CblasRowMajor, TransA, TransB, M, N, K, alpha, A, lda, B,\n      ldb, beta, C, N);\n}\n\ntemplate<>\nvoid caffe_cpu_gemm<double>(const CBLAS_TRANSPOSE TransA,\n    const CBLAS_TRANSPOSE TransB, const int M, const int N, const int K,\n    const double alpha, const double* A, const double* B, const double beta,\n    double* C) {\n  int lda = (TransA == CblasNoTrans) ? K : M;\n  int ldb = (TransB == CblasNoTrans) ? N : K;\n  cblas_dgemm(CblasRowMajor, TransA, TransB, M, N, K, alpha, A, lda, B,\n      ldb, beta, C, N);\n}\n\ntemplate <>\nvoid caffe_cpu_gemv<float>(const CBLAS_TRANSPOSE TransA, const int M,\n    const int N, const float alpha, const float* A, const float* x,\n    const float beta, float* y) {\n  cblas_sgemv(CblasRowMajor, TransA, M, N, alpha, A, N, x, 1, beta, y, 1);\n}\n\ntemplate <>\nvoid caffe_cpu_gemv<double>(const CBLAS_TRANSPOSE TransA, const int M,\n    const int N, const double alpha, const double* A, const double* x,\n    const double beta, double* y) {\n  cblas_dgemv(CblasRowMajor, TransA, M, N, alpha, A, N, x, 1, beta, y, 1);\n}\n\ntemplate <>\nvoid caffe_axpy<float>(const int N, const float alpha, const float* X,\n    float* Y) { cblas_saxpy(N, alpha, X, 1, Y, 1); }\n\ntemplate <>\nvoid caffe_axpy<double>(const int N, const double alpha, const double* X,\n    double* Y) { cblas_daxpy(N, alpha, X, 1, Y, 1); }\n\ntemplate <typename Dtype>\nvoid caffe_set(const int N, const Dtype alpha, Dtype* Y) {\n  // If we are executing parallel region already then do not start another one\n  // if also number of data to be processed is smaller than arbitrary:\n  // threashold 12*4 cachelines per thread then no parallelization is to be made\n  if (alpha == 0) {\n    memset(Y, 0, sizeof(Dtype) * N);  // NOLINT(caffe/alt_fn)\n  } else {\n    std::fill(Y, Y + N, alpha);\n  }\n}\n\ntemplate void caffe_set<char>(const int N, const char alpha, char* Y);\ntemplate void caffe_set<int>(const int N, const int alpha, int* Y);\ntemplate <>\nvoid caffe_set<float>(const int N, const float alpha, float* Y) {\n  if (alpha == 0) {\n    cblas_sscal(N, alpha, Y, 1);\n  } else {\n    std::fill(Y, Y + N, alpha);\n  }\n}\n\ntemplate <>\nvoid caffe_set<double>(const int N, const double alpha, double* Y) {\n  if (alpha == 0) {\n    cblas_dscal(N, alpha, Y, 1);\n  } else {\n    std::fill(Y, Y + N, alpha);\n  }\n}\n\ntemplate void caffe_set<size_t>(const int N, const size_t alpha, size_t* Y);\n\ntemplate <>\nvoid caffe_add_scalar(const int N, const float alpha, float* Y) {\n  for (int i = 0; i < N; ++i) {\n    Y[i] += alpha;\n  }\n}\n\ntemplate <>\nvoid caffe_add_scalar(const int N, const double alpha, double* Y) {\n  for (int i = 0; i < N; ++i) {\n    Y[i] += alpha;\n  }\n}\n\ntemplate  <typename Dtype>\nvoid caffe_cpu_copy(const int N, const Dtype* X, Dtype* Y) {\n  if (X == Y) return;\n\n  memcpy(Y, X, sizeof(Dtype) * N);  // NOLINT(caffe/alt_fn)\n}\n\ntemplate void caffe_cpu_copy<int>(const int N, const int* X, int* Y);\ntemplate void caffe_cpu_copy<unsigned int>(const int N, const unsigned int* X,\n    unsigned int* Y);\ntemplate <>\nvoid caffe_cpu_copy<float>(const int N, const float* X, float* Y) {\n  if (X == Y) return;\n\n  cblas_scopy(N, X, 1, Y, 1);\n}\n\ntemplate <>\nvoid caffe_cpu_copy<double>(const int N, const double* X, double* Y) {\n  if (X == Y) return;\n\n  cblas_dcopy(N, X, 1, Y, 1);\n}\n\ntemplate <typename Dtype>\nvoid caffe_copy(const int N, const Dtype* X, Dtype* Y) {\n  if (X != Y) {\n    // If there are more than one openmp thread (we are in active region)\n    // then checking Caffe::mode can create additional GPU Context\n    //\n    if (\n        (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      caffe_cpu_copy<Dtype>(N, X, Y);\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);\ntemplate void caffe_copy<char>(const int N, const char* X, char* Y);\ntemplate void caffe_copy<size_t>(const int N, const size_t* X, size_t* Y);\n\ntemplate <>\nvoid caffe_scal<float>(const int N, const float alpha, float *X) {\n  cblas_sscal(N, alpha, X, 1);\n}\n\ntemplate <>\nvoid caffe_scal<double>(const int N, const double alpha, double *X) {\n  cblas_dscal(N, alpha, X, 1);\n}\n\ntemplate <>\nvoid caffe_scal<size_t>(const int N, const size_t alpha, size_t *X) {\n}\n\ntemplate <>\nvoid caffe_cpu_axpby<float>(const int N, const float alpha, const float* X,\n                            const float beta, float* Y) {\n  cblas_saxpby(N, alpha, X, 1, beta, Y, 1);\n}\n\ntemplate <>\nvoid caffe_cpu_axpby<double>(const int N, const double alpha, const double* X,\n                             const double beta, double* Y) {\n  cblas_daxpby(N, alpha, X, 1, beta, Y, 1);\n}\n\ntemplate <>\nvoid caffe_axpy<size_t>(const int N, const size_t alpha, const size_t* X,\n    size_t* Y) { }\n\ntemplate <>\nvoid caffe_add<float>(const int n, const float* a, const float* b,\n    float* y) {\n  vsAdd(n, a, b, y);\n}\n\ntemplate <>\nvoid caffe_add<double>(const int n, const double* a, const double* b,\n    double* y) {\n  vdAdd(n, a, b, y);\n}\n\ntemplate <>\nvoid caffe_sub<float>(const int n, const float* a, const float* b,\n    float* y) {\n  vsSub(n, a, b, y);\n}\n\ntemplate <>\nvoid caffe_sub<double>(const int n, const double* a, const double* b,\n    double* y) {\n  vdSub(n, a, b, y);\n}\n\ntemplate <>\nvoid caffe_mul<float>(const int n, const float* a, const float* b,\n    float* y) {\n  vsMul(n, a, b, y);\n}\n\ntemplate <>\nvoid caffe_mul<double>(const int n, const double* a, const double* b,\n    double* y) {\n  vdMul(n, a, b, y);\n}\n\ntemplate <>\nvoid caffe_div<float>(const int n, const float* a, const float* b,\n    float* y) {\n  vsDiv(n, a, b, y);\n}\n\ntemplate <>\nvoid caffe_div<double>(const int n, const double* a, const double* b,\n    double* y) {\n  vdDiv(n, a, b, y);\n}\n\ntemplate <>\nvoid caffe_powx<float>(const int n, const float* a, const float b,\n    float* y) {\n  vsPowx(n, a, b, y);\n}\n\ntemplate <>\nvoid caffe_powx<double>(const int n, const double* a, const double b,\n    double* y) {\n  vdPowx(n, a, b, y);\n}\n\ntemplate <>\nvoid caffe_sqr<float>(const int n, const float* a, float* y) {\n  vsSqr(n, a, y);\n}\n\ntemplate <>\nvoid caffe_sqr<double>(const int n, const double* a, double* y) {\n  vdSqr(n, a, y);\n}\n\ntemplate <>\nvoid caffe_exp<float>(const int n, const float* a, float* y) {\n  vsExp(n, a, y);\n}\n\ntemplate <>\nvoid caffe_exp<double>(const int n, const double* a, double* y) {\n  vdExp(n, a, y);\n}\n\ntemplate <>\nvoid caffe_log<float>(const int n, const float* a, float* y) {\n  vsLn(n, a, y);\n}\n\ntemplate <>\nvoid caffe_log<double>(const int n, const double* a, double* y) {\n  vdLn(n, a, y);\n}\n\ntemplate <>\nvoid caffe_abs<float>(const int n, const float* a, float* y) {\n    vsAbs(n, a, y);\n}\n\ntemplate <>\nvoid caffe_abs<double>(const int n, const double* a, double* y) {\n    vdAbs(n, a, y);\n}\n\nunsigned int caffe_rng_rand() {\n#ifdef DETERMINISTIC\n    return 5153;\n#else\n    return (*caffe_rng())();\n#endif\n}\n\ntemplate <typename Dtype>\nDtype caffe_nextafter(const Dtype b) {\n  return boost::math::nextafter<Dtype>(\n      b, std::numeric_limits<Dtype>::max());\n}\n\ntemplate\nfloat caffe_nextafter(const float b);\n\ntemplate\ndouble caffe_nextafter(const double b);\n\ntemplate <typename Dtype>\nvoid caffe_rng_uniform(const int n, const Dtype a, const Dtype b, Dtype* r) {\n  CHECK_GE(n, 0);\n  CHECK(r);\n  CHECK_LE(a, b);\n  boost::uniform_real<Dtype> random_distribution(a, caffe_nextafter<Dtype>(b));\n  boost::variate_generator<caffe::rng_t*, boost::uniform_real<Dtype> >\n      variate_generator(caffe_rng(), random_distribution);\n  for (int i = 0; i < n; ++i) {\n    r[i] = variate_generator();\n  }\n}\n\ntemplate\nvoid caffe_rng_uniform<float>(const int n, const float a, const float b,\n                              float* r);\n\ntemplate\nvoid caffe_rng_uniform<double>(const int n, const double a, const double b,\n                               double* r);\n\ntemplate <typename Dtype>\nvoid caffe_rng_gaussian(const int n, const Dtype a,\n                        const Dtype sigma, Dtype* r) {\n  CHECK_GE(n, 0);\n  CHECK(r);\n  CHECK_GT(sigma, 0);\n  boost::normal_distribution<Dtype> random_distribution(a, sigma);\n  boost::variate_generator<caffe::rng_t*, boost::normal_distribution<Dtype> >\n      variate_generator(caffe_rng(), random_distribution);\n  for (int i = 0; i < n; ++i) {\n    r[i] = variate_generator();\n  }\n}\n\ntemplate\nvoid caffe_rng_gaussian<float>(const int n, const float mu,\n                               const float sigma, float* r);\n\ntemplate\nvoid caffe_rng_gaussian<double>(const int n, const double mu,\n                                const double sigma, double* r);\n\n#ifdef USE_MKL\nstatic void bernoulli_generate(int n, double p, int* r) {\n  int seed = 17 + caffe_rng_rand() % 4096;\n  {\n    const int my_amount = n;\n    const int my_offset = 0;\n\n    VSLStreamStatePtr stream;\n    vslNewStream(&stream, VSL_BRNG_MCG31, seed);\n    vslSkipAheadStream(stream, my_offset);\n    viRngBernoulli(VSL_RNG_METHOD_BERNOULLI_ICDF, stream, my_amount,\n      r + my_offset, p);\n    vslDeleteStream(&stream);\n  }\n}\n#endif\n\ntemplate <typename Dtype>\nvoid caffe_rng_bernoulli(const int n, const Dtype p, int* r) {\n  CHECK_GE(n, 0);\n  CHECK(r);\n  CHECK_GE(p, 0);\n  CHECK_LE(p, 1);\n#ifdef USE_MKL\n  bernoulli_generate(n, p, r);\n#else\n  boost::bernoulli_distribution<Dtype> random_distribution(p);\n  boost::variate_generator<caffe::rng_t*, boost::bernoulli_distribution<Dtype> >\n      variate_generator(caffe_rng(), random_distribution);\n  for (int i = 0; i < n; ++i) {\n    r[i] = variate_generator();\n  }\n#endif\n}\n\ntemplate\nvoid caffe_rng_bernoulli<double>(const int n, const double p, int* r);\n\ntemplate\nvoid caffe_rng_bernoulli<float>(const int n, const float p, int* r);\n\ntemplate <typename Dtype>\nvoid caffe_rng_bernoulli(const int n, const Dtype p, unsigned int* r) {\n  CHECK_GE(n, 0);\n  CHECK(r);\n  CHECK_GE(p, 0);\n  CHECK_LE(p, 1);\n#ifdef USE_MKL\n  bernoulli_generate(n, p, reinterpret_cast<int *>(r));\n#else\n  boost::bernoulli_distribution<Dtype> random_distribution(p);\n  boost::variate_generator<caffe::rng_t*, boost::bernoulli_distribution<Dtype> >\n      variate_generator(caffe_rng(), random_distribution);\n  for (int i = 0; i < n; ++i) {\n    r[i] = static_cast<unsigned int>(variate_generator());\n  }\n#endif\n}\n\ntemplate\nvoid caffe_rng_bernoulli<double>(const int n, const double p, unsigned int* r);\n\ntemplate\nvoid caffe_rng_bernoulli<float>(const int n, const float p, unsigned int* r);\n\ntemplate <>\nfloat caffe_cpu_strided_dot<float>(const int n, const float* x, const int incx,\n    const float* y, const int incy) {\n  return cblas_sdot(n, x, incx, y, incy);\n}\n\ntemplate <>\ndouble caffe_cpu_strided_dot<double>(const int n, const double* x,\n    const int incx, const double* y, const int incy) {\n  return cblas_ddot(n, x, incx, y, incy);\n}\n\ntemplate <>\nsize_t caffe_cpu_strided_dot<size_t>(const int n, const size_t* x,\n        const int incx, const size_t* y, const int incy) {\n  return 0;\n}\n\ntemplate <typename Dtype>\nDtype caffe_cpu_dot(const int n, const Dtype* x, const Dtype* y) {\n  return caffe_cpu_strided_dot(n, x, 1, y, 1);\n}\n\ntemplate\nfloat caffe_cpu_dot<float>(const int n, const float* x, const float* y);\n\ntemplate\ndouble caffe_cpu_dot<double>(const int n, const double* x, const double* y);\n\ntemplate\nsize_t caffe_cpu_dot<size_t>(const int n, const size_t* x, const size_t* y);\n\ntemplate <>\nfloat caffe_cpu_asum<float>(const int n, const float* x) {\n  return cblas_sasum(n, x, 1);\n}\n\ntemplate <>\ndouble caffe_cpu_asum<double>(const int n, const double* x) {\n  return cblas_dasum(n, x, 1);\n}\n\ntemplate <>\nsize_t caffe_cpu_asum<size_t>(const int n, const size_t* x) {\n  return 0;\n}\n\ntemplate <>\nvoid caffe_cpu_scale<float>(const int n, const float alpha, const float *x,\n                            float* y) {\n  cblas_scopy(n, x, 1, y, 1);\n  cblas_sscal(n, alpha, y, 1);\n}\n\ntemplate <>\nvoid caffe_cpu_scale<double>(const int n, const double alpha, const double *x,\n                             double* y) {\n  cblas_dcopy(n, x, 1, y, 1);\n  cblas_dscal(n, alpha, y, 1);\n}\n\n}  // namespace caffe\n", "meta": {"hexsha": "e5c1819334fd76eb1eb140b2e4b0055a421992de", "size": 12848, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/caffe/util/math_functions.cpp", "max_stars_repo_name": "AIROBOTAI/caffe-mnode", "max_stars_repo_head_hexsha": "e8b03bfb04f09dce21c9b5bbf66dacecb095d3e1", "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": "AIROBOTAI/caffe-mnode", "max_issues_repo_head_hexsha": "e8b03bfb04f09dce21c9b5bbf66dacecb095d3e1", "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": "AIROBOTAI/caffe-mnode", "max_forks_repo_head_hexsha": "e8b03bfb04f09dce21c9b5bbf66dacecb095d3e1", "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.6556016598, "max_line_length": 80, "alphanum_fraction": 0.6613480697, "num_tokens": 3842, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.46982180982002086}}
{"text": "///////////////////////////////////////////////////////////////\r\n//  Copyright 2012 John Maddock. Distributed under the Boost\r\n//  Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_\r\n\r\n#ifdef _MSC_VER\r\n#  define _SCL_SECURE_NO_WARNINGS\r\n#endif\r\n\r\n#include <boost/multiprecision/cpp_bin_float.hpp>\r\n\r\n#include \"libs/multiprecision/test/test_arithmetic.hpp\"\r\n\r\ntemplate <unsigned Digits, boost::multiprecision::backends::digit_base_type DigitBase, class Allocator, class Exponent, Exponent MinExponent, Exponent MaxExponent, boost::multiprecision::expression_template_option ET>\r\nstruct related_type<boost::multiprecision::number< boost::multiprecision::cpp_bin_float<Digits, DigitBase, Allocator, Exponent, MinExponent, MaxExponent>, ET> >\r\n{\r\n   typedef boost::multiprecision::number< boost::multiprecision::cpp_bin_float<Digits, DigitBase, Allocator, Exponent, MinExponent, MaxExponent>, ET> number_type;\r\n   typedef boost::multiprecision::number< boost::multiprecision::cpp_bin_float<((std::numeric_limits<number_type>::digits / 2) > std::numeric_limits<long double>::digits ? Digits / 2 : Digits), DigitBase, Allocator, Exponent, MinExponent, MaxExponent>, ET> type;\r\n};\r\n\r\nint main()\r\n{\r\n   //test<boost::multiprecision::cpp_bin_float_50>();\r\n   //test<boost::multiprecision::number<boost::multiprecision::cpp_bin_float<1000, boost::multiprecision::digit_base_10, std::allocator<void> > > >();\r\n   test<boost::multiprecision::cpp_bin_float_quad>();\r\n   return boost::report_errors();\r\n}\r\n\r\n", "meta": {"hexsha": "4f3b2aadbb597bd41a47c46e6ef33d18ed765060", "size": 1561, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/multiprecision/test/test_arithmetic_cpp_bin_float_3.cpp", "max_stars_repo_name": "lijgame/boost", "max_stars_repo_head_hexsha": "ec2214a19cdddd1048058321a8105dd0231dac47", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 85.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T20:36:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T20:38:31.000Z", "max_issues_repo_path": "libs/boost/libs/multiprecision/test/test_arithmetic_cpp_bin_float_3.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/multiprecision/test/test_arithmetic_cpp_bin_float_3.cpp", "max_forks_repo_name": "flingone/frameworks_base_cmds_remoted", "max_forks_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2015-01-28T16:33:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-12T05:04:39.000Z", "avg_line_length": 53.8275862069, "max_line_length": 263, "alphanum_fraction": 0.732863549, "num_tokens": 373, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529376, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.46974490909728833}}
{"text": "#include <igl/opengl/glfw/Viewer.h>\n#include <igl/writeOBJ.h>\n#include <igl/barycenter.h>\n#include <igl/readOFF.h>\n#include <igl/readDMAT.h>\n#include <igl/writeDMAT.h>\n#include <igl/readOBJ.h>\n#include <igl/jet.h>\n#include <igl/png/readPNG.h>\n#include <igl/png/writePNG.h>\n#include <igl/volume.h>\n#include <igl/slice.h>\n#include <igl/boundary_facets.h>\n#include <igl/opengl/glfw/imgui/ImGuiMenu.h>\n#include <igl/opengl/destroy_shader_program.h>\n#include <igl/opengl/create_shader_program.h>\n#include <igl/opengl/glfw/imgui/ImGuiHelpers.h>\n#include <igl/remove_unreferenced.h>\n#include <igl/list_to_matrix.h>\n#include <imgui/imgui.h>\n#include <igl/null.h>\n#include <json.hpp>\n#include <Eigen/SparseCholesky>\n\n#include <sstream>\n#include <iomanip>\n// #include <omp.h>\n\n#include \"famu/store.h\"\n#include \"famu/read_config_files.h\"\n#include \"famu/vertex_bc.h\"\n#include \"famu/discontinuous_edge_vectors.h\"\n#include \"famu/discontinuous_centroids_matrix.h\"\n#include \"famu/cont_to_discont_tets.h\"\n#include \"famu/construct_kkt_system.h\"\n#include \"famu/get_min_max_verts.h\"\n#include \"famu/muscle_energy_gradient.h\"\n#include \"famu/stablenh_energy_gradient.h\"\n#include \"famu/acap_solve_energy_gradient.h\"\n#include \"famu/draw_disc_mesh_functions.h\"\n#include \"famu/dfmatrix_vector_swap.h\"\n#include \"famu/newton_solver.h\"\n#include \"famu/joint_constraint_matrix.h\"\n#include \"famu/fixed_bones_projection_matrix.h\"\n#include \"famu/bone_elem_def_grad_projection_matrix.h\"\n#include \"famu/setup_hessian_modes.h\"\n\n\nusing namespace Eigen;\nusing namespace std;\nusing json = nlohmann::json;\n\nusing Store = famu::Store;\njson j_input;\n\n\nint main(int argc, char *argv[])\n{\n  int fancy_data_index,debug_data_index,discontinuous_data_index;\n\tstd::cout<<\"-----Configs-------\"<<std::endl;\n\t\tstd::string inputfile;\n\t\tint num_threads = 1;\n\t\tif(argc<1){\n\t\t\tcout<<\"Run as: ./famu input.json <threads>\"<<endl;\n\t\t\texit(0);\n\t\t}\n\t\tif(argc==3){\n\t\t\tnum_threads = std::stoi(argv[2]);\n\t\t\t#ifdef __linux__\n\t\t\tomp_set_num_threads(num_threads);\n\t\t\t#endif\n\t\t\tstd::ifstream input_file(argv[1]);\n\t\t\tinput_file >> j_input;\n\t\t}else if(argc==4){\n\t\t\tnum_threads = std::stoi(argv[3]);\n\t\t\t#ifdef __linux__\n\t\t\tomp_set_num_threads(num_threads);\n\t\t\t#endif\n\t\t\tstd::ifstream input_file(argv[2]);\n\t\t\tinput_file >> j_input;\n\n\t\t}\n\t\tEigen::initParallel();\n\t\n\t\t\n    \tigl::Timer timer;\n\n\t\tfamu::Store store;\n\t\tstore.jinput = j_input;\n\n\t\tfamu::read_config_files(store.V, \n\t\t\t\t\t\t\t\tstore.T, \n\t\t\t\t\t\t\t\tstore.F, \n\t\t\t\t\t\t\t\tstore.Uvec, \n\t\t\t\t\t\t\t\tstore.bone_name_index_map, \n\t\t\t\t\t\t\t\tstore.muscle_name_index_map, \n\t\t\t\t\t\t\t\tstore.joint_bones_verts, \n\t\t\t\t\t\t\t\tstore.bone_tets, \n\t\t\t\t\t\t\t\tstore.muscle_tets, \n\t\t\t\t\t\t\t\tstore.fix_bones, \n\t\t\t\t\t\t\t\tstore.relativeStiffness,\n\t\t\t\t\t\t\t\tstore.contract_muscles,\n\t\t\t\t\t\t\t\tstore.jinput);  \n\t\tstore.alpha_arap = store.jinput[\"alpha_arap\"];\n\t\tstore.alpha_neo = store.jinput[\"alpha_neo\"];\n\t\t\n\n\n\tcout<<\"---Record Mesh Setup Info\"<<endl;\n\t\tcout<<\"V size: \"<<store.V.rows()<<endl;\n\t\tcout<<\"T size: \"<<store.T.rows()<<endl;\n\t\tcout<<\"F size: \"<<store.F.rows()<<endl;\n\t\tstore.jinput[\"number_modes\"] = NUM_MODES;\n\t\tstd::string outputfile = j_input[\"output\"];\n\t\tigl::boundary_facets(store.T, store.F);\n\n\tcout<<\"---Set Fixed Vertices\"<<endl;\n\t\t// store.mfix = famu::getMaxVerts(store.V, 1);\n\t\t// store.mmov = {};//famu::getMinVerts(store.V, 1);\n\t\tcout<<\"If it fails here, make sure indexing is within bounds\"<<endl;\n\t    std::set<int> fix_verts_set;\n\t    for(int ii=0; ii<store.fix_bones.size(); ii++){\n\t        cout<<store.fix_bones[ii]<<endl;\n\t        int bone_ind = store.bone_name_index_map[store.fix_bones[ii]];\n\t        fix_verts_set.insert(store.T.row(store.bone_tets[bone_ind][0])[0]);\n\t        fix_verts_set.insert(store.T.row(store.bone_tets[bone_ind][0])[1]);\n\t        fix_verts_set.insert(store.T.row(store.bone_tets[bone_ind][0])[2]);\n\t        fix_verts_set.insert(store.T.row(store.bone_tets[bone_ind][0])[3]);\n\t    }\n\t    store.mfix.assign(fix_verts_set.begin(), fix_verts_set.end());\n\t    std::sort (store.mfix.begin(), store.mfix.end());\n\t\n\tcout<<\"---Set Mesh Params\"<<store.x.size()<<endl;\n\t\t//YM, poissons\n\t\tstore.eY = 1e10*VectorXd::Ones(store.T.rows());\n\t\tstore.eP = 0.49*VectorXd::Ones(store.T.rows());\n\t\tstore.muscle_mag = VectorXd::Zero(store.T.rows());\n\t\tfor(int m=0; m<store.muscle_tets.size(); m++){\n\t\t\tfor(int t=0; t<store.muscle_tets[m].size(); t++){\n\t\t\t\tif(store.relativeStiffness[store.muscle_tets[m][t]]>1){\n\t\t\t\t\tstore.eY[store.muscle_tets[m][t]] = 1.2e9;\n\t\t\t\t}else{\n\t\t\t\t\tstore.eY[store.muscle_tets[m][t]] = 60000;\n\t\t\t\t}\n\t\t\t\tstore.muscle_mag[store.muscle_tets[m][t]] = j_input[\"muscle_starting_strength\"];\n\t\t\t}\n\t\t}\n\t\tigl::writeDMAT(\"youngs_per_tet.dmat\", store.eY);\n        {\n          store.elogVY = Eigen::VectorXd::Zero(store.V.rows());\n          // volume associated with each vertex\n          Eigen::VectorXd Vvol = Eigen::VectorXd::Zero(store.V.rows());\n          Eigen::VectorXd Tvol;\n          igl::volume(store.V,store.T,Tvol);\n          // loop over tets\n          for(int i = 0;i<store.T.rows();i++)\n          {\n            const double vol4 = Tvol(i)/4.0;\n            for(int j = 0;j<4;j++)\n            {\n              Vvol(store.T(i,j)) += vol4;\n              store.elogVY(store.T(i,j)) += vol4*log10(store.eY(i));\n            }\n          }\n          // loop over vertices to divide to take average\n          for(int i = 0;i<store.V.rows();i++)\n          {\n            store.elogVY(i) /= Vvol(i);\n          }\n        }\n\n\n\t\t//bone dF map\n\t\t//start off all as -1\n\t\tstore.bone_or_muscle = -1*Eigen::VectorXi::Ones(store.T.rows());\n\t\tif(store.jinput[\"reduced\"]){\n\n\t\t\t// // // assign bone tets to 1 dF for each bone, starting at 0...bone_tets.size()\n\t\t\tfor(int i=0; i<store.bone_tets.size(); i++){\n\t\t    \tfor(int j=0; j<store.bone_tets[i].size(); j++){\n\t\t    \t\tstore.bone_or_muscle[store.bone_tets[i][j]] = i;\n\t\t    \t}\n\t\t    }\n\n\t\t    //assign muscle tets, dF per element, starting at bone_tets.size()\n\t\t    int muscle_ind = store.bone_tets.size();\n\t\t    for(int i=0; i<store.T.rows(); i++){\n\t\t    \tif(store.bone_or_muscle[i]<-1e-8){\n\t\t    \t\tstore.bone_or_muscle[i] = muscle_ind;\n\t\t    \t\tmuscle_ind +=1;\n\t\t    \t}\n\t\t    }\n\t\t}\n\t    else{\n\t\t\tfor(int i=0; i<store.T.rows(); i++){\n\t\t\t\tstore.bone_or_muscle[i] = i;\n\t\t\t}\n\t    }\n\n\t    //Rest state volumes\n\t    store.rest_tet_volume = VectorXd::Ones(store.T.rows());\n\t\tfor(int i =0; i<store.T.rows(); i++){\n\t\t\tVector3d p1 = store.V.row(store.T.row(i)[0]); \n\t\t\tVector3d p2 = store.V.row(store.T.row(i)[1]); \n\t\t\tVector3d p3 = store.V.row(store.T.row(i)[2]);\n\t\t\tVector3d p4 = store.V.row(store.T.row(i)[3]); \n\t\t\t\n\t\t\tMatrix3d Dm;\n\t\t\tDm.col(0) = p1 - p4;\n\t\t\tDm.col(1) = p2 - p4;\n\t\t\tDm.col(2) = p3 - p4;\n\t\t\tdouble density = 1000;\n\t\t\tdouble undef_vol = (1.0/6)*fabs(Dm.determinant());\n\t\t\tstore.rest_tet_volume[i] = undef_vol;\n\t\t}\n\t\tfor(int i=0; i<store.bone_tets.size(); i++){\n\t\t\tdouble bone_vol = 0;\n\t    \tfor(int j=0; j<store.bone_tets[i].size(); j++){\n\t    \t\tbone_vol += store.rest_tet_volume[store.bone_tets[i][j]];\n\t    \t}\n\t    \tstore.bone_vols.push_back(bone_vol);\n\t    }\n\n\tcout<<\"---Setup continuous mesh\"<<store.x.size()<<endl;\n\t\tstore.x0.resize(3*store.V.rows());\n\t\tfor(int i=0; i<store.V.rows(); i++){\n\t\t\tstore.x0[3*i+0] = store.V(i,0); \n\t\t\tstore.x0[3*i+1] = store.V(i,1); \n\t\t\tstore.x0[3*i+2] = store.V(i,2);   \n\t    }\n\t    store.dx = VectorXd::Zero(3*store.V.rows());\n\n\n\tcout<<\"---Cont. to Discont. matrix\"<<store.x.size()<<endl;\n\t\tfamu::cont_to_discont_tets(store.S, store.T, store.V);\n\t    \n    cout<<\"---Set Vertex Constraint Matrices\"<<store.x.size()<<endl;\n\t\tfamu::vertex_bc(store.mmov, store.mfix, store.UnconstrainProjection, store.ConstrainProjection, store.V);\n\n\tcout<<\"---Set Discontinuous Tet Centroid vector matrix\"<<store.x.size()<<endl;\n\t\tfamu::discontinuous_edge_vectors(store, store.D, store._D, store.T, store.muscle_tets);\n\n\tcout<<\"---Set Centroid Matrix\"<<store.x.size()<<endl;\n\t\tfamu::discontinuous_centroids_matrix(store.C, store.T);\n\n\tcout<<\"---Set Disc T and V\"<<store.x.size()<<endl;\n\t\tfamu::setDiscontinuousMeshT(store.T, store.discT);\n\t\tigl::boundary_facets(store.discT, store.discF);\n\t\tstore.discV.resize(4*store.T.rows(), 3);\n\n\tcout<<\"---Set Joints Constraint Matrix\"<<store.x.size()<<endl;\n\t\tfamu::fixed_bones_projection_matrix(store, store.Y);\n\t    store.x = VectorXd::Zero(store.Y.cols());\n\t\tfamu::joint_constraint_matrix(store, store.JointConstraints);\n\n\t\tfamu::bone_def_grad_projection_matrix(store, store.ProjectF, store.PickBoneF);\n\t\tfamu::bone_acap_deformation_constraints(store, store.Bx, store.Bf);\n\t    store.lambda2 = VectorXd::Zero(store.Bf.rows());\n\n\t    // std::vector<std::pair<int, int>> springs;\n\t    // std::vector<int> bcMuscle1 = getMinVerts_Axis_Tolerance(store.T, store.V, 2, 1e-1, store.muscle_tets[0]);\n\t    // std::vector<int> bcMuscle2 = getMaxVerts_Axis_Tolerance(store.T, store.V, 2, 1e-1, store.muscle_tets[1]);\n\t    // // famu::make_closest_point_springs(store.T, store.V, store.muscle_tets[1],  bcMuscle1, springs);\n\t    // famu::make_closest_point_springs(store.T, store.V, store.muscle_tets[0],  bcMuscle2, springs);\n\n\t    // famu::penalty_spring_bc(springs, store.ContactP, store.V);\n\n\n\n\tcout<<\"---ACAP Solve KKT setup\"<<store.x.size()<<endl;\n\t\tSparseMatrix<double, Eigen::RowMajor> KKT_left, KKT_left1;\n\t\tstore.YtStDtDSY = (store.D*store.S*store.Y).transpose()*(store.D*store.S*store.Y);\n\t\tfamu::construct_kkt_system_left(store.YtStDtDSY, store.JointConstraints, KKT_left);\n\n\t\tdouble k = store.jinput[\"springk\"];\n\t\t// SparseMatrix<double, Eigen::RowMajor> PY = k*store.ContactP*store.Y;\n\t\t// famu::construct_kkt_system_left(KKT_left, PY, KKT_left1, -1);\n\n\n\t\tSparseMatrix<double, Eigen::RowMajor> KKT_left2;\n\t\tfamu::construct_kkt_system_left(KKT_left, store.Bx,  KKT_left2, -1e-3); \n\t\t// MatrixXd Hkkt = MatrixXd(KKT_left2);\n\t\t#ifdef __linux__\n\t\tstore.ACAP_KKT_SPLU.pardisoParameterArray()[2] = num_threads; \n\t\t#endif\n\n\t\tstore.ACAP_KKT_SPLU.analyzePattern(KKT_left2);\n\t\tstore.ACAP_KKT_SPLU.factorize(KKT_left2);\n\n\t\tif(store.ACAP_KKT_SPLU.info()!=Success){\n\t\t\tcout<<\"1. ACAP Jacobian solve failed\"<<endl;\n\t\t\tcout<<\"2. numerical issue: \"<<(store.ACAP_KKT_SPLU.info()==NumericalIssue)<<endl;\n\t\t\tcout<<\"3. invalid input: \"<<(store.ACAP_KKT_SPLU.info()==InvalidInput)<<endl;\n\n\t\t\texit(0);\n\t\t}\n\t\t\n\tcout<<\"---Setup dFvec and dF\"<<endl;\n\t\tstore.dFvec = VectorXd::Zero(store.ProjectF.cols());\n\t\tfor(int t=0; t<store.dFvec.size()/9; t++){\n\t\t\tstore.dFvec[9*t + 0] = 1;\n\t\t\tstore.dFvec[9*t + 4] = 1;\n\t\t\tstore.dFvec[9*t + 8] = 1;\n\t\t}\n\t\tstore.BfI0 = store.Bf*store.dFvec;\n\t\tstore.acap_solve_result.resize(KKT_left2.rows());\n\t\tstore.acap_solve_rhs = VectorXd::Zero(KKT_left2.rows());\n\n\n\n\tcout<<\"---Setup Fast ACAP energy\"<<endl;\n\t\tstore.StDtDS = (store.D*store.S).transpose()*(store.D*store.S);\n\t\tstore.DSY = store.D*store.S*store.Y;\n\t\tstore.DSx0 = store.D*store.S*store.x0;\n\t\tfamu::dFMatrix_Vector_Swap(store.DSx0_mat, store.DSx0);\n\t\t\n\n\t\tstore.x0tStDtDSx0 = store.DSx0.transpose()*store.DSx0;\n\t\tstore.x0tStDtDSY = store.DSx0.transpose()*store.DSY;\n\t\tstore.x0tStDt_dF_DSx0 = store.DSx0.transpose()*store.DSx0_mat*store.ProjectF;\n\t\tstore.YtStDt_dF_DSx0 = (store.DSY).transpose()*store.DSx0_mat*store.ProjectF;\n\t\tstore.x0tStDt_dF_dF_DSx0 = (store.DSx0_mat*store.ProjectF).transpose()*store.DSx0_mat*store.ProjectF;\n\n\t\tfamu::muscle::setupFastMuscles(store);\n\n\n\tcout<<\"--- Setup Modes\"<<endl;\n\tif(store.jinput[\"woodbury\"]){\n\n        MatrixXd temp1;\n        if(store.JointConstraints.rows() != 0){\n\t\t\tMatrixXd nullJ;\n\t\t\tigl::null(MatrixXd(store.JointConstraints), nullJ);\n\t\t\tstore.NullJ = nullJ.sparseView();\n\t\t}else{\n\t\t\tstore.NullJ.resize(store.Y.cols(), store.Y.cols());\n\t\t\tstore.NullJ.setIdentity();\n\t\t}\n        SparseMatrix<double> NjtYtStDtDSYNj = store.NullJ.transpose()*store.Y.transpose()*store.S.transpose()*store.D.transpose()*store.D*store.S*store.Y*store.NullJ;\n        igl::readDMAT(outputfile+\"/\"+to_string((int)store.jinput[\"number_modes\"])+\"modes.dmat\", temp1);\n        if(temp1.rows() == 0){\n\t\t\tfamu::setup_hessian_modes(store, NjtYtStDtDSYNj, temp1);\n\t\t}else{\n\t\t\t//read eigenvalues (for the woodbury solve)\n\t\t\tigl::readDMAT(outputfile+\"/\"+to_string((int)store.jinput[\"number_modes\"])+\"eigs.dmat\", store.eigenvalues);\n\t\t}\n\t\tstore.G = store.NullJ*temp1;\n\t}\n\t\n\n\tcout<<\"--- ACAP Hessians\"<<endl;\n\t\tfamu::acap::setJacobian(store);\n\t\t\n\t\tstore.denseNeoHess = MatrixXd::Zero(store.dFvec.size(), 9);\n\t\tstore.neoHess.resize(store.dFvec.size(), store.dFvec.size());\n\t\tfamu::stablenh::hessian(store, store.neoHess, store.denseNeoHess);\n\n\t\tstore.denseMuscleHess = MatrixXd::Zero(store.dFvec.size(), 9);\n\t\tstore.muscleHess.resize(store.dFvec.size(), store.dFvec.size());\n\t\tfamu::muscle::fastHessian(store, store.muscleHess, store.denseMuscleHess);\n\n\t\tstore.denseAcapHess = MatrixXd::Zero(store.dFvec.size(), 9);\n\t\tstore.acapHess.resize(store.dFvec.size(), store.dFvec.size());\n\t\tfamu::acap::fastHessian(store, store.acapHess, store.denseAcapHess);\n\t\t\n\n\t\tSparseMatrix<double> hessFvec = store.neoHess + store.acapHess + store.muscleHess;\n\t\tstore.NM_SPLU.analyzePattern(hessFvec);\n\t\tstore.NM_SPLU.factorize(hessFvec);\n\n\t\t\t\n\tif(store.jinput[\"woodbury\"]){\n\t\tcout<<\"--- Setup woodbury matrices\"<<endl;\n\t\t\tstore.WoodB = -store.YtStDt_dF_DSx0.transpose()*store.G;\n\t\t\tstore.WoodD = -1*store.WoodB.transpose();\n\t\t\t\n\n\t\t\tstore.InvC = store.eigenvalues.asDiagonal();\n\t\t\tstore.WoodC = store.eigenvalues.asDiagonal().inverse();\n\t\t\tfor(int i=0; i<store.dFvec.size()/9; i++){\n\t\t\t\tLDLT<Matrix9d> InvA;\n\t\t\t\tstore.vecInvA.push_back(InvA);\n\t\t\t}\n\n\t}\n\n\n    cout<<\"---Setup TMP Vars\"<<endl;\n    \tfamu::discontinuousV(store);\n    \tstore.acaptmp_sizex = store.x;\n\t\tstore.acaptmp_sizedFvec1= store.dFvec;\n\t\tstore.acaptmp_sizedFvec2 = store.dFvec;\n\n\n\t// store.dFvec[9+0] = 0.7071;\n    // store.dFvec[9+1] = 0.7071;\n    // store.dFvec[9+2] = 0;\n    // store.dFvec[9+3] = -0.7071;\n    // store.dFvec[9+4] = 0.7071;\n    // store.dFvec[9+5] = 0;\n    // store.dFvec[9+6] = 0;\n    // store.dFvec[9+7] = 0;\n    // store.dFvec[9+8] = 1;\n    // famu::acap::solve(store, store.dFvec);        \t\n\n\t// cout<<\"ACAP Energy: \"<<famu::acap::energy(store, store.dFvec, store.boneDOFS)<<\"-\"<<famu::acap::fastEnergy(store,store.dFvec)<<endl;\n\t// VectorXd dEdF = VectorXd::Zero(store.dFvec.size());\n\t// famu::acap::fastGradient(store, dEdF);\n\t// VectorXd fdgrad = famu::acap::fd_gradient(store);\n\t// cout<<\"ACAP Grad\"<<endl;\n\t// cout<<(fdgrad.transpose() - dEdF.segment<20>(0).transpose()).squaredNorm()<<endl;\n\t// cout<<\"ACAP Hess:\"<<endl;\n\t// MatrixXd testH = MatrixXd(store.acapHess);\n\t// MatrixXd fdH = famu::acap::fd_hessian(store);\n\t// // cout<<fdH<<endl<<endl<<endl;\n\t// // cout<<testH.block<20,20>(0,0)<<endl<<endl;\n\t// cout<<\"Norm:\"<<(testH.block<20,20>(0,0) - fdH).squaredNorm()<<endl;\n\t// cout<<\"ACAP dxdF:\"<<endl;\n\t// MatrixXd testJac = MatrixXd(store.JacdxdF);\n\t// MatrixXd fdJac = famu::acap::fd_dxdF(store);\n\t// cout<<testJac.block<15,15>(0,0)<<endl<<endl;\n\t// cout<<fdJac.block<15,15>(0,0)<<endl<<endl;\n\t// cout<<(testJac.block<15,15>(0,0) - fdJac.block<15,15>(0,0)).squaredNorm()<<endl;\n\n\t// exit(0);\n\n\n\tcout<<\"--- Write Meshes\"<<endl;\n\t\t// double fx = 0;\n\t\t// int niters = 0;\n\t\t// niters = famu::newton_static_solve(store);\n\n\t\t// VectorXd y = store.Y*store.x;\n\t\t// Eigen::Map<Eigen::MatrixXd> newV(y.data(), store.V.cols(), store.V.rows());\n\t\t// igl::writeOBJ(outputfile+\"/EMU\"+to_string(store.T.rows())+\"-Alpha:\"+to_string(store.alpha_arap)+\".obj\", (newV.transpose()+store.V), store.F);\n\t\t// exit(0);\n\n\tcout<<\"--- External Forces Hard Coded Contact Matrices\"<<endl;\n\t    // famu::acap::adjointMethodExternalForces(store);\n\t\n\n\tstd::cout<<\"-----Display-------\"<<std::endl;\n    \tigl::opengl::glfw::Viewer viewer;\n    \tint currentStep = 0;\n    \tviewer.callback_post_draw= [&](igl::opengl::glfw::Viewer & viewer) {\n\t    \n\t    // std::stringstream out_file;\n\t    // //render out current view\n\t    // // Allocate temporary buffers for 1280x800 image\n\t    // Eigen::Matrix<unsigned char,Eigen::Dynamic,Eigen::Dynamic> R(1920,1280);\n\t    // Eigen::Matrix<unsigned char,Eigen::Dynamic,Eigen::Dynamic> G(1920,1280);\n\t    // Eigen::Matrix<unsigned char,Eigen::Dynamic,Eigen::Dynamic> B(1920,1280);\n\t    // Eigen::Matrix<unsigned char,Eigen::Dynamic,Eigen::Dynamic> A(1920,1280);\n\t    \n\t    // // Draw the scene in the buffers\n\t    // viewer.core.draw_buffer(viewer.data(),false,R,G,B,A);\n\t    \n\t    // // Save it to a PNG\n\t    // out_file<<\"out_\"<<std::setfill('0') << std::setw(5) <<currentStep<<\".png\";\n\t    // igl::png::writePNG(R,G,B,A,out_file.str());\n\t    // currentStep += 1;\n\t    return false;\n\t};\n\n    viewer.callback_key_down = [&](igl::opengl::glfw::Viewer & viewer, unsigned char key, int modifiers){   \n        std::cout<<\"Key down, \"<<key<<std::endl;\n        // given data show it as colors on debug mesh\n        const auto set_colors_from_data = [&](const Eigen::VectorXd & zz)\n        {\n          MatrixXd COLRS;\n          igl::jet(zz, true, COLRS);\n          viewer.data_list[debug_data_index].set_colors(COLRS);\n        };\n        // If debug mesh is currently visible, turn it off and turn on fancy\n        // mesh and return true; otherwise return false.\n        const auto hide_debug = [&]()->bool\n        {\n          if(viewer.data_list[debug_data_index].show_faces)\n          {\n            viewer.data_list[debug_data_index].show_faces = false;\n            viewer.data_list[fancy_data_index].show_faces = true;\n            std::cout<<\"hiding debug...\"<<std::endl;\n            return true;\n          }\n          viewer.data_list[debug_data_index].show_faces = true;\n          viewer.data_list[fancy_data_index].show_faces = false;\n          return false;\n        };\n        switch(key)\n        {\n          case ' ':\n          {\n          \n            //store.dFvec[9+0] = 0.7071;\n            //store.dFvec[9+1] = 0.7071;\n            //store.dFvec[9+2] = 0;\n            //store.dFvec[9+3] = -0.7071;\n            //store.dFvec[9+4] = 0.7071;\n            //store.dFvec[9+5] = 0;\n            //store.dFvec[9+6] = 0;\n            //store.dFvec[9+7] = 0;\n            //store.dFvec[9+8] = 1;\n            //timer.start();\n            // famu::acap::solve(store, store.dFvec);        \t\n            // timer.stop();\n            // cout<<\"+++Microsecs per solve: \"<<timer.getElapsedTimeInMicroSec()<<endl;\n\n            double fx = 0;\n            int niters = 0;\n            niters = famu::newton_static_solve(store);\n\n            VectorXd y = store.Y*store.x;\n        \tEigen::Map<Eigen::MatrixXd> newV(y.data(), store.V.cols(), store.V.rows());\n            igl::writeOBJ(outputfile+\"EMU\"+to_string(store.T.rows())+\".obj\", (newV.transpose()+store.V), store.F);\n            viewer.data_list[fancy_data_index].set_vertices((newV.transpose()+store.V));\n            viewer.data_list[debug_data_index].set_vertices((newV.transpose()+store.V));\n            return true;\n          }\n          case 'A':\n          case 'a':\n          {\n            store.muscle_mag *= 1.5;\n            famu::muscle::setupFastMuscles(store);\n            famu::muscle::fastHessian(store, store.muscleHess, store.denseMuscleHess);\n            return true;\n          }\n          case 'C':\n          case 'c':\n          {\n            std::cout<<\"C...\"<<std::endl;\n            if(!hide_debug())\n            {\n              std::cout<<\" C...\"<<std::endl;\n              VectorXd zz = VectorXd::Ones(store.V.rows());\n              // probably want to have this visualization update with each press\n              // of space ' '... I'd consider having a little lambda that will\n              // update the geometry _and_ any active visualizations. Might want\n              // to have an enum or something to tell which debug visualization\n              // is active.\n              VectorXd y = store.Y*store.x;\n              for(int m=0; m<store.T.rows(); m++){\n                Matrix3d Dm;\n                for(int i=0; i<3; i++){\n                  Dm.col(i) = store.V.row(store.T.row(m)[i]) - store.V.row(store.T.row(m)[3]);\n                }\n                Matrix3d m_InvRefShapeMatrix = Dm.inverse();\n\n                Matrix3d Ds;\n                for(int i=0; i<3; i++)\n                {\n                  Ds.col(i) = y.segment<3>(3*store.T.row(m)[i]) - y.segment<3>(3*store.T.row(m)[3]);\n                }\n\n                Matrix3d F = Matrix3d::Identity() + Ds*m_InvRefShapeMatrix;\n\n                double snorm = (F.transpose()*F - Matrix3d::Identity()).norm();\n\n                zz[store.T.row(m)[0]] += snorm;\n                zz[store.T.row(m)[1]] += snorm;\n                zz[store.T.row(m)[2]] += snorm; \n                zz[store.T.row(m)[3]] += snorm;\n              }\n              set_colors_from_data(zz);\n            }\n            return true;\n          }\n          case 'D':\n          case 'd':\n          {\n            viewer.data_list[discontinuous_data_index].show_lines =\n              !viewer.data_list[discontinuous_data_index].show_lines;\n            if(viewer.data_list[discontinuous_data_index].show_lines)\n            {\n              famu::discontinuousV(store);\n              viewer.data_list[discontinuous_data_index].set_vertices(store.discV);\n            }\n            return true;\n          }\n          case 'E':\n          case 'e':\n          {\n            if(!hide_debug())\n            {\n              VectorXd zz = VectorXd::Ones(store.V.rows());\n              //map ACAP energy over the meseh\n              VectorXd ls = store.DSY*store.x + store.DSx0;\n              VectorXd rs = store.DSx0_mat*store.ProjectF*store.dFvec;\n              for(int i=0; i<store.T.rows(); i++){\n                double enorm = (ls.segment<12>(12*i) - rs.segment<12>(12*i)).norm();\n\n                zz[store.T.row(i)[0]] += enorm;\n                zz[store.T.row(i)[1]] += enorm;\n                zz[store.T.row(i)[2]] += enorm; \n                zz[store.T.row(i)[3]] += enorm;\n\n              }\n              set_colors_from_data(zz);\n            }\n            return true;\n          }\n          case 'S':\n          case 's':\n          {\n            if(!hide_debug())\n            {\n              VectorXd zz = VectorXd::Ones(store.V.rows());\n              //map strains\n              VectorXd fulldFvec = store.ProjectF*store.dFvec;\n              for(int m=0; m<store.T.rows(); m++){\n                Matrix3d F = Map<Matrix3d>(fulldFvec.segment<9>(9*m).data()).transpose();\n                double snorm = (F.transpose()*F - Matrix3d::Identity()).norm();\n\n                zz[store.T.row(m)[0]] += snorm;\n                zz[store.T.row(m)[1]] += snorm;\n                zz[store.T.row(m)[2]] += snorm; \n                zz[store.T.row(m)[3]] += snorm;\n\t      }\n              set_colors_from_data(zz);\n            }\n            return true;\n          }\n          case 'V':\n          case 'v':\n          {\n            if(!hide_debug())\n            {\n              VectorXd zz = VectorXd::Ones(store.V.rows());\n              //Display tendon areas\n              for(int i=0; i<store.T.rows(); i++){\n                zz[store.T.row(i)[0]] = store.relativeStiffness[i];\n                zz[store.T.row(i)[1]] = store.relativeStiffness[i];\n                zz[store.T.row(i)[2]] = store.relativeStiffness[i];\n                zz[store.T.row(i)[3]] = store.relativeStiffness[i];\n              }\n              set_colors_from_data(zz);\n            }\n            return true;\n          }\n        }\n\n\n        // viewer.data().add_points( (store.ContactP1.transpose()*(store.Y*store.x + store.x0)).transpose() , Eigen::RowVector3d(1,0,0));\n        // viewer.data().add_points( (store.ContactP2.transpose()*(store.Y*store.x + store.x0)).transpose() , Eigen::RowVector3d(0,1,0));\n        viewer.data().points = Eigen::MatrixXd(0,6);\n        viewer.data().lines = Eigen::MatrixXd(0,9);\n        // for(int i=0; i<springs.size(); i++){\n        // \tviewer.data().add_points(viewer.data_list[debug_data_index].V.row(springs[i].first), Eigen::RowVector3d(1,0,0));\n        // \tviewer.data().add_points(viewer.data_list[debug_data_index].V.row(springs[i].second), Eigen::RowVector3d(1,0,0));\n        // \tviewer.data().add_edges(viewer.data_list[debug_data_index].V.row(springs[i].first),viewer.data_list[debug_data_index].V.row(springs[i].second),Eigen::RowVector3d(1,0,0));\n        // }\n    \n\n        //for(int i=0; i<store.mmov.size(); i++){\n        //\tviewer.data().add_points((newV.transpose().row(store.mmov[i]) + store.V.row(store.mmov[i])), Eigen::RowVector3d(0,1,0));\n        //}\n \n        // return false indicates that keystroke was not used and should be\n        // passed on to viewer to handle\n        return false;\n    };\n\n  fancy_data_index = viewer.selected_data_index;\n  viewer.data_list[fancy_data_index].set_mesh(store.V, store.F);\n  viewer.data_list[fancy_data_index].show_lines = false;\n  viewer.data_list[fancy_data_index].invert_normals = true;\n  viewer.data_list[fancy_data_index].set_face_based(false);\n  viewer.append_mesh();\n  debug_data_index = viewer.selected_data_index;\n  viewer.data_list[debug_data_index].set_mesh(store.V, store.F);\n  viewer.data_list[debug_data_index].show_faces = false;\n  viewer.data_list[debug_data_index].invert_normals = true;\n  viewer.data_list[debug_data_index].show_lines = false;\n  viewer.append_mesh();\n  discontinuous_data_index = viewer.selected_data_index;\n  viewer.data_list[discontinuous_data_index].set_mesh(store.discV, store.discF);\n  viewer.data_list[discontinuous_data_index].show_lines = true;\n  viewer.data_list[discontinuous_data_index].show_faces = false;\n  // set fancy rendered mesh to be selected.\n  viewer.selected_data_index = fancy_data_index;\n\n\n  // must be called before messing with shaders\n  viewer.launch_init(true,false);\n  std::cout<<R\"(\nfd_famu:\n  C,c  Show continuous mesh's strain\n  D,d  Toggle discontinous mesh wireframe\n  E,e  Show ACAP energy (interpolated on the continuous mesh)\n  S,s  Show discontinuous mesh's strain (interpolated on the continuous mesh)\n  V,v  Tendon vs. muscle vis\n)\";\n\n  // Send Young's modulus data in via color channel\n  {\n    Eigen::MatrixXd C(store.V.rows(),3);\n    for(int i = 0;i<store.V.rows();i++)\n    {\n      if(store.elogVY(i) < 0.5*(60000 + 1.2e9))\n      {\n        C.row(i) = Eigen::RowVector3d(1,0,0);\n      }else if(store.elogVY(i) < 0.5*(1.2e9 + 1.0e10))\n      {\n        C.row(i) = Eigen::RowVector3d(0.99,0.99,1);\n      }else\n      {\n        C.row(i) = Eigen::RowVector3d(0.85,0.85,0.8);\n      }\n    }\n    viewer.data_list[fancy_data_index].set_colors(store.elogVY.replicate(1,3));\n    Eigen::Matrix<unsigned char,Eigen::Dynamic,Eigen::Dynamic> R,G,B,A;\n    // @Vismay, perhaps include this path in the json?\n    igl::png::readPNG(store.jinput[\"material\"],R,G,B,A);\n    viewer.data_list[fancy_data_index].set_texture(R,G,B,A);\n    viewer.data_list[fancy_data_index].show_texture = true;\n    // must be called before messing with shaders\n    viewer.data_list[fancy_data_index].meshgl.init();\n    igl::opengl::destroy_shader_program(\n      viewer.data_list[fancy_data_index].meshgl.shader_mesh);\n    {\n      std::string mesh_vertex_shader_string =\nR\"(#version 150\nuniform mat4 view;\nuniform mat4 proj;\nuniform mat4 normal_matrix;\nin vec3 position;\nin vec3 normal;\n// Color\nin vec3 Kd;\n// Young's modulus\nout float elogY;\nout vec3 normal_eye;\n\nvoid main()\n{\n  normal_eye = normalize(vec3 (normal_matrix * vec4 (normal, 0.0)));\n  gl_Position = proj * view * vec4(position, 1.0);\n  elogY = Kd.r;\n})\";\n\n      std::string mesh_fragment_shader_string =\nR\"(#version 150\nin vec3 normal_eye;\n// Young's modulus\nin float elogY;\nout vec4 outColor;\nuniform sampler2D tex;\nvoid main()\n{\n  vec2 uv = normalize(normal_eye).xy * vec2(0.5/3.0,0.5);\n  float t_tendon = clamp( (elogY-4.7782)/(9.0792-4.7782) , 0.0 , 1.0);\n  float t_bone =   clamp( (elogY-9.0092)/(10.000-9.0792) , 0.0 , 1.0);\n  outColor = mix(\n      texture(tex, uv + vec2(0.5/3.0,0.5)),\n      texture(tex, uv + vec2(1.5/3.0,0.5)),\n      t_tendon);\n  outColor = mix( outColor,   texture(tex, uv + vec2(2.5/3.0,0.5)),t_bone);\n  //outColor.a = 1.0;\n})\";\n\n      igl::opengl::create_shader_program(\n        mesh_vertex_shader_string,\n        mesh_fragment_shader_string,\n        {},\n        viewer.data_list[fancy_data_index].meshgl.shader_mesh);\n    }\n  }\n\n\n\n  viewer.core.is_animating = false;\n  viewer.core.background_color = Eigen::Vector4f(1,1,1,0);\n\n  viewer.launch_rendering(true);\n  viewer.launch_shut();\n\n}\n", "meta": {"hexsha": "a97ed8076359d49f67113a22cd71ae7ec247ee4f", "size": 28169, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "fd_famu.cpp", "max_stars_repo_name": "itsvismay/fast_muscles", "max_stars_repo_head_hexsha": "86c9d93bd14da92ce2140bf47857810b579e7b2c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2019-05-08T22:20:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-02T01:38:52.000Z", "max_issues_repo_path": "fd_famu.cpp", "max_issues_repo_name": "itsvismay/fast_muscles", "max_issues_repo_head_hexsha": "86c9d93bd14da92ce2140bf47857810b579e7b2c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-05-08T21:10:36.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-08T21:10:36.000Z", "max_forks_repo_path": "fd_famu.cpp", "max_forks_repo_name": "itsvismay/fast_muscles", "max_forks_repo_head_hexsha": "86c9d93bd14da92ce2140bf47857810b579e7b2c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-05-08T21:11:10.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-08T21:11:10.000Z", "avg_line_length": 36.2535392535, "max_line_length": 182, "alphanum_fraction": 0.6168483084, "num_tokens": 8381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4697449090972883}}
{"text": "/* vim: set tabstop=4 expandtab shiftwidth=4 softtabstop=4: */\n\n/**\n * \\file boost/numeric/ublasx/operation/tanh.hpp\n *\n * \\brief Compute the hyperbolic tangent for each element of a vector or\n *  matrix expression.\n *\n * \\author comcon1, [at pm dot me]\n *\n * <hr/>\n *\n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#ifndef BOOST_NUMERIC_UBLASX_OPERATION_TANH_HPP\n#define BOOST_NUMERIC_UBLASX_OPERATION_TANH_HPP\n\n\n#include <boost/numeric/ublas/traits.hpp>\n#include <boost/numeric/ublasx/expression/matrix_unary_functor.hpp>\n#include <boost/numeric/ublasx/expression/vector_unary_functor.hpp>\n#include <cmath>\n\n\nnamespace boost { namespace numeric { namespace ublasx {\n\nusing namespace ::boost::numeric::ublas;\n\nnamespace detail {\n\ntemplate <typename VectorExprT>\nstruct vector_tanh_functor_traits\n{\n    typedef VectorExprT input_expression_type;\n    typedef typename vector_traits<input_expression_type>::value_type signature_argument_type;\n    typedef signature_argument_type signature_result_type;\n    typedef vector_unary_functor_traits<\n                input_expression_type,\n                signature_result_type (signature_argument_type)\n            > unary_functor_expression_type;\n    typedef typename unary_functor_expression_type::result_type result_type;\n    typedef typename unary_functor_expression_type::expression_type expression_type;\n};\n\n\ntemplate <typename MatrixExprT>\nstruct matrix_tanh_functor_traits\n{\n    typedef MatrixExprT input_expression_type;\n    typedef typename matrix_traits<input_expression_type>::value_type signature_argument_type;\n    typedef signature_argument_type signature_result_type;\n    typedef matrix_unary_functor_traits<\n                input_expression_type,\n                signature_result_type (signature_argument_type)\n            > unary_functor_expression_type;\n    typedef typename unary_functor_expression_type::result_type result_type;\n    typedef typename unary_functor_expression_type::expression_type expression_type;\n};\n\n\ntemplate <typename T>\nBOOST_UBLAS_INLINE\nT tanh(T x)\n{\n    return ::std::tanh(x);\n}\n\n} // Namespace detail\n\n\n/**\n * \\brief Applies the \\c std::tanh function to each element of a given vector\n *  expression.\n *\n * \\tparam VectorExprT The type of the input vector expression.\n *\n * \\param ve The input vector expression.\n * \\return A vector expression representing the application of \\c std::tanh to\n *  each element of \\a ve.\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\ntemplate <typename VectorExprT>\nBOOST_UBLAS_INLINE\ntypename detail::vector_tanh_functor_traits<VectorExprT>::result_type tanh(vector_expression<VectorExprT> const& ve)\n{\n    typedef typename detail::vector_tanh_functor_traits<VectorExprT>::expression_type expression_type;\n    typedef typename detail::vector_tanh_functor_traits<VectorExprT>::signature_result_type signature_result_type;\n\n    return expression_type(ve(), detail::tanh<signature_result_type>);\n}\n\n\n/**\n * \\brief Applies the \\c std::tanh function to each element of a given matrix\n *  expression.\n *\n * \\tparam MatrixExprT The type of the input matrix expression.\n *\n * \\param me The input matrix expression.\n * \\return A matrix expression representing the application of \\c std::tanh to\n *  each element of \\a me.\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\ntemplate <typename MatrixExprT>\nBOOST_UBLAS_INLINE\ntypename detail::matrix_tanh_functor_traits<MatrixExprT>::result_type tanh(matrix_expression<MatrixExprT> const& me)\n{\n    typedef typename detail::matrix_tanh_functor_traits<MatrixExprT>::expression_type expression_type;\n    typedef typename detail::matrix_tanh_functor_traits<MatrixExprT>::signature_result_type signature_result_type;\n\n    return expression_type(me(), detail::tanh<signature_result_type>);\n}\n\n}}} // Namespace boost::numeric::ublasx\n\n\n#endif // BOOST_NUMERIC_UBLASX_OPERATION_LOG_HPP\n", "meta": {"hexsha": "15cd0508f9b0cacb9f453622e90808f471104791", "size": 3972, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/ublasx/operation/tanh.hpp", "max_stars_repo_name": "sguazt/boost-ublasx", "max_stars_repo_head_hexsha": "21c9b393d33a6ec2a8071ba8d48680073d766409", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2016-05-14T11:08:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-05T14:22:20.000Z", "max_issues_repo_path": "boost/numeric/ublasx/operation/tanh.hpp", "max_issues_repo_name": "sguazt/boost-ublasx", "max_issues_repo_head_hexsha": "21c9b393d33a6ec2a8071ba8d48680073d766409", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-12-28T18:36:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-06T11:28:51.000Z", "max_forks_repo_path": "boost/numeric/ublasx/operation/tanh.hpp", "max_forks_repo_name": "sguazt/boost-ublasx", "max_forks_repo_head_hexsha": "21c9b393d33a6ec2a8071ba8d48680073d766409", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-12-23T02:53:27.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-23T02:53:27.000Z", "avg_line_length": 32.2926829268, "max_line_length": 116, "alphanum_fraction": 0.7774420947, "num_tokens": 897, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529376, "lm_q2_score": 0.6001883592602049, "lm_q1q2_score": 0.4697449090972882}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   Utility_BoostSolver.cpp\n//! \\author Alex Bennett\n//! \\brief  Boost Solver\n//!\n//---------------------------------------------------------------------------//\n\n// Trilinos Includes\n#include <Teuchos_Array.hpp>\n\n// Boost Includes\n#include <boost/numeric/odeint.hpp>\n\n// FRENSIE Includes\n#include \"Utility_BoostSolver.hpp\"\n\nnamespace Utility {\n\nBoostSolver::BoostSolver(const Teuchos::RCP<Teuchos::SerialDenseMatrix<int,double> >& matrix,\n                         const Teuchos::Array<double>& y) :\n  m_system(BatemanSystem(matrix)),\n  m_jacobian(BatemanJacobian(matrix))\n{\n  m_y.resize( y.size() );\n  for(int i = 0; i != m_y.size(); i++)\n  {\n    m_y(i) = y[i];\n  }\n}\n\nvoid BoostSolver::getNumberDensities(Teuchos::Array<double>& y)\n{\n  y.resize(m_y.size(),0);\n  for(int i = 0; i != m_y.size(); i++)\n  {\n    y[i] = m_y(i);\n  }\n}\n\nvoid BoostSolver::Solve(const double& time)\n{\n  size_t nstep = boost::numeric::odeint::integrate_adaptive( \n           boost::numeric::odeint::rosenbrock4_controller<boost::numeric::odeint::rosenbrock4<double> >(1e-6,1e-6),\n           std::make_pair( m_system, m_jacobian ),\n           m_y,\n           0.0,\n           time,\n           0.1);\n}\n\nvoid BoostSolver::BatemanSystem::operator()(const boost::numeric::ublas::vector<double>& y,\n                                                  boost::numeric::ublas::vector<double>& dxdt,\n                                            double time)\n{\n  for(int i = 0; i != dxdt.size(); i++)\n  {\n    dxdt(i) = 0.0;\n\n    for(int j = 0; j != dxdt.size(); j++)\n    {\n      dxdt(i) += (*m_matrix)(i,j) * y(j);\n    }\n  }\n}\n\nvoid BoostSolver::BatemanJacobian::operator()(const boost::numeric::ublas::vector<double>& m_y,\n                                                    boost::numeric::ublas::matrix<double>& jacobian,\n                                              const double& time,\n                                                    boost::numeric::ublas::vector<double>& dfdt )\n{\n  for(int i = 0; i != jacobian.size1(); i++)\n  {\n    for(int j = 0; j != jacobian.size2(); j++)\n    {\n      jacobian(i,j) = (*m_matrix)(i,j);\n    }\n\n    dfdt(i) = 0.0;\n  }\n}\n \n\n} // end namespace utility\n\n//---------------------------------------------------------------------------//\n// end Utility_BoostSolver.cpp\n//---------------------------------------------------------------------------//\n\n", "meta": {"hexsha": "304e3812577e4cfe63ce2afdc483418794f249f4", "size": 2440, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "packages/utility/core/src/Utility_BoostSolver.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/utility/core/src/Utility_BoostSolver.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/utility/core/src/Utility_BoostSolver.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": 27.1111111111, "max_line_length": 115, "alphanum_fraction": 0.4668032787, "num_tokens": 590, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.46973197406033335}}
{"text": "#include \"QPReactiveRecoveryPlan.hpp\"\n#include <unsupported/Eigen/Polynomials>\n#include <Eigen/StdVector>\n#include \"drake/util/drakeGeometryUtil.h\"\n#include \"drake/solvers/qpSpline/splineGeneration.h\"\n#include \"drake/util/lcmUtil.h\"\n#include \"lcmtypes/drc/reactive_recovery_debug_t.hpp\"\nextern \"C\" {\n  #include \"iris/solver.h\"\n}\n\n#define CVXGEN_MAX_ROWS 3\n#define CVXGEN_MAX_PTS 8\n\n#define DEBUG\n\nusing namespace Eigen;\n\nVars vars;\nParams params;\nWorkspace work;\nSettings settings;\n\nVectorXd QPReactiveRecoveryPlan::closestPointInConvexHull(const Ref<const VectorXd> &x, const Ref<const MatrixXd> &V) {\n\n  int dim = x.size();\n\n  Matrix<double, CVXGEN_MAX_ROWS, 1> x_resized;\n  Matrix<double, CVXGEN_MAX_ROWS, CVXGEN_MAX_PTS> V_resized;\n\n  if (dim > CVXGEN_MAX_ROWS) {\n    fprintf(stderr, \"x can not be more than %d elements\\n\", CVXGEN_MAX_ROWS);\n    exit(1);\n  }\n  if (V.rows() != dim) {\n    fprintf(stderr, \"V must have same number of rows as x\\n\");\n    exit(1);\n  }\n  if (V.cols() > CVXGEN_MAX_PTS) {\n    fprintf(stderr, \"V can not be larger than %d x %d\\n\", CVXGEN_MAX_ROWS, CVXGEN_MAX_PTS);\n    exit(1);\n  }\n\n  x_resized.head(dim) = x;\n  V_resized.block(0, 0, dim, V.cols()) = V;\n\n  if (dim < CVXGEN_MAX_ROWS) {\n    x_resized.tail(CVXGEN_MAX_ROWS - dim) = VectorXd::Zero(CVXGEN_MAX_ROWS-dim);\n    V_resized.block(dim, 0, CVXGEN_MAX_ROWS - dim, V_resized.cols()) = MatrixXd::Zero(CVXGEN_MAX_ROWS-dim, V_resized.cols());\n  }\n\n  for (int i=V.cols(); i < CVXGEN_MAX_PTS; i++) {\n    for (int j=0; j < CVXGEN_MAX_ROWS; j++) {\n      V_resized(j,i) = V_resized(j,i-1);\n    }\n  }\n\n  for (int j=0; j < CVXGEN_MAX_PTS; j++) {\n    V_resized.col(j) = V_resized.col(j) - x_resized;\n  }\n\n  set_defaults();\n  setup_indexing();\n  settings.verbose = 0;\n\n\n  double *src = V_resized.data();\n  double *dest = params.Y;\n  for (int i=0; i < CVXGEN_MAX_ROWS * CVXGEN_MAX_PTS; i++) {\n    *dest++ = *src++;\n  }\n\n  solve();\n\n\n  Map<VectorXd>y(vars.v, CVXGEN_MAX_ROWS);\n  Map<VectorXd>w(vars.w, CVXGEN_MAX_PTS);\n\n  y.head(dim) = y.head(dim) + x.head(dim);\n  return y.head(dim);\n}\n\nIsometry3d QPReactiveRecoveryPlan::closestPoseInConvexHull(const Isometry3d &pose, const Ref<const MatrixXd> &V) {\n  if (V.rows() < 2 || V.rows() > 3) {\n    fprintf(stderr, \"Vertices should have dimension 2 or 3\\n\");\n    exit(1);\n  }\n  const int dim = V.rows();\n  Isometry3d new_pose = pose;\n  new_pose.translation().head(dim) = QPReactiveRecoveryPlan::closestPointInConvexHull(pose.translation().head(dim), V);\n  return new_pose;\n}\n\nPolynomial<double> QPReactiveRecoveryPlan::bangBangPolynomial(double x0, double xd0, double u) {\n  VectorXd coefs(3);\n  coefs << x0 - 0.25*xd0*xd0/u,\n           0.5*xd0,\n           0.25*u;\n  Polynomial<double> p(coefs);\n  return p;\n}\n\nstd::vector<double> realRoots(Polynomial<double> p) {\n  VectorXd coefs = p.getCoefficients();\n  double order = p.getDegree();\n  std::vector<double> roots;\n  if (order == 1) {\n    // c0 + c1*t = 0;\n    // t = -c0/c1\n    roots.push_back(-coefs(0) / coefs(1));\n  } else if (order == 2) {\n    // c0 + c1*t + c2*t^2 = 0;\n    // t = (-c1 +- sqrt(c1^2 - 4*c2*c0)) / (2*c2)\n    double discriminant = pow(coefs(1), 2) - 4*coefs(2)*coefs(0);\n    if (discriminant >= 0) {\n      roots.push_back((-coefs(1) + sqrt(discriminant)) / (2*coefs(2)));\n      roots.push_back((-coefs(1) - sqrt(discriminant)) / (2*coefs(2)));\n    }\n  } else {\n    PolynomialSolver<double, Dynamic> poly_solver(coefs);\n    poly_solver.realRoots(roots);\n  }\n  return roots;\n}\n\nstd::vector<double> QPReactiveRecoveryPlan::expIntercept(const ExponentialForm &expform, double l0, double ld0, double u, int degree) {\n  // Find the t >= 0 solutions to a*e^(b*t) + c == l0 + 1/2*ld0*t + 1/4*u*t^2 - 1/4*ld0^2/u\n  // using a taylor expansion up to power [degree]\n\n  Polynomial<double> p_taylor = expform.taylorExpand(degree);\n  Polynomial<double> p_bang = QPReactiveRecoveryPlan::bangBangPolynomial(l0, ld0, u);\n  Polynomial<double> p_int = p_taylor - p_bang;\n\n  std::vector<double> roots = realRoots(p_int);\n  std::vector<double> nonneg_roots;\n\n  for (std::vector<double>::iterator it = roots.begin(); it != roots.end(); ++it) {\n    if (*it > 0) {\n      nonneg_roots.push_back(*it);\n    } \n  }\n\n  return nonneg_roots;\n}\n\nstd::vector<BangBangIntercept> QPReactiveRecoveryPlan::bangBangIntercept(double x0, double xd0, double xf, double u_max) {\n  std::vector<BangBangIntercept> intercepts;\n\n  double us[2] = {u_max, -u_max};\n  for (int i=0; i<2; i++) {\n    double u = us[i];\n    Polynomial<double> p = QPReactiveRecoveryPlan::bangBangPolynomial(x0 - xf, xd0, u);\n    std::vector<double> roots = realRoots(p);\n    for (std::vector<double>::iterator it = roots.begin(); it != roots.end(); ++it) {\n      double t = *it;\n      if (t >= std::abs(xd0 / u)) {\n        BangBangIntercept inter;\n        inter.tf = t;\n        inter.tswitch = 0.5 * (t - xd0 / u);\n        inter.u = u;\n        intercepts.push_back(inter);\n        break;\n      }\n    }\n  }\n  return intercepts;\n}\n\n\ndouble QPReactiveRecoveryPlan::icpError(const Ref<const Vector2d> &r_ic, const FootStateMap &foot_states, const VertMap &foot_vertices) {\n  if (foot_states.size() != 2) {\n    throw std::runtime_error(\"isICPCaptured only supports 2 feet\");\n  }\n  Matrix<double, 3, 8> all_vertices_in_world;\n\n  int foot_count = 0;\n  for (std::map<FootID, FootState>::const_iterator state = foot_states.begin(); state != foot_states.end(); ++state) {\n    if (state->second.contact || \n        (state->second.pose.translation()(2) - state->second.terrain_height < this->capture_max_flyfoot_height)) {\n      auto vert_it = foot_vertices.find(state->first);\n      if (vert_it == foot_vertices.end()) {\n        std::cout << footIDToName[state->first] << std::endl;\n        throw std::runtime_error(\"Cannot find foot name in foot_vertices\");\n      }\n\n      Matrix<double, 3, QP_REACTIVE_RECOVERY_VERTICES_PER_FOOT> foot_vertices_in_world = state->second.pose * (this->capture_shrink_factor * vert_it->second);\n      all_vertices_in_world.block(0, QP_REACTIVE_RECOVERY_VERTICES_PER_FOOT*foot_count, 3, QP_REACTIVE_RECOVERY_VERTICES_PER_FOOT) = foot_vertices_in_world.block(0,0,3,QP_REACTIVE_RECOVERY_VERTICES_PER_FOOT);\n      ++foot_count;\n    } \n  }\n\n  Matrix<double, 2, Dynamic> active_vertices_in_world = all_vertices_in_world.block(0, 0, 2, foot_count * QP_REACTIVE_RECOVERY_VERTICES_PER_FOOT);\n\n  VectorXd r_ic_near = QPReactiveRecoveryPlan::closestPointInConvexHull(r_ic, active_vertices_in_world);\n  return (r_ic - r_ic_near).norm();\n}\n\n\nbool QPReactiveRecoveryPlan::isICPCaptured(const Ref<const Vector2d> &r_ic, const FootStateMap &foot_states, const VertMap &foot_vertices) {\n  if (foot_states.size() != 2) {\n    throw std::runtime_error(\"isICPCaptured only supports 2 feet\");\n  }\n  Matrix<double, 3, 8> all_vertices_in_world;\n\n  int foot_count = 0;\n  for (std::map<FootID, FootState>::const_iterator state = foot_states.begin(); state != foot_states.end(); ++state) {\n    if (state->second.contact || \n        (state->second.pose.translation()(2) - state->second.terrain_height < this->capture_max_flyfoot_height)) {\n      auto vert_it = foot_vertices.find(state->first);\n      if (vert_it == foot_vertices.end()) {\n        std::cout << footIDToName[state->first] << std::endl;\n        throw std::runtime_error(\"Cannot find foot name in foot_vertices\");\n      }\n\n      Matrix<double, 3, QP_REACTIVE_RECOVERY_VERTICES_PER_FOOT> foot_vertices_in_world = state->second.pose * (this->capture_shrink_factor * vert_it->second);\n      all_vertices_in_world.block(0, QP_REACTIVE_RECOVERY_VERTICES_PER_FOOT*foot_count, 3, QP_REACTIVE_RECOVERY_VERTICES_PER_FOOT) = foot_vertices_in_world.block(0,0,3,QP_REACTIVE_RECOVERY_VERTICES_PER_FOOT);\n      ++foot_count;\n    } else {\n      return false;\n    }\n  }\n\n  Matrix<double, 2, Dynamic> active_vertices_in_world = all_vertices_in_world.block(0, 0, 2, foot_count * QP_REACTIVE_RECOVERY_VERTICES_PER_FOOT);\n\n  VectorXd r_ic_near = QPReactiveRecoveryPlan::closestPointInConvexHull(r_ic, active_vertices_in_world);\n  return (r_ic - r_ic_near).norm() < 1e-2; // threshold set by the accuracy of the cvxgen qp solver\n\n}\n\nExponentialForm QPReactiveRecoveryPlan::icpTrajectory(double x_ic, double x_cop, double omega) {\n  ExponentialForm icptraj((x_ic - x_cop), omega, x_cop);\n  return icptraj;\n}\n\nbool tswitchComp(const BangBangIntercept int0, const BangBangIntercept int1) {\n  return int0.tswitch < int1.tswitch;\n}\n\nbool errorCompare(const InterceptPlan plan0, const InterceptPlan plan1) {\n  return plan0.error < plan1.error;\n}\n\nIsometry3d QPReactiveRecoveryPlan::getTWorldToLocal(const Isometry3d &icp, const Isometry3d &cop) {\n  Isometry3d T_world_to_local = Isometry3d::Identity();\n  T_world_to_local.rotate(AngleAxis<double>(-std::atan2(icp.translation().y() - cop.translation().y(), icp.translation().x() - cop.translation().x()), Vector3d(0, 0, 1)));\n  T_world_to_local.translate(-cop.translation());\n  return T_world_to_local;\n}\n\ndouble QPReactiveRecoveryPlan::getMinTimeToXprimeAxis(const FootState foot_state, const BipedDescription &biped, Isometry3d &T_world_to_local) {\n  std::vector<BangBangIntercept> xprime_axis_intercepts = \n    QPReactiveRecoveryPlan::bangBangIntercept((T_world_to_local * foot_state.pose).translation().y(),\n                                              (T_world_to_local.linear() * foot_state.velocity.head(3))(1),\n                                              0,\n                                              biped.u_max);\n\n  VectorXd times_to_xprime_axis(xprime_axis_intercepts.size());\n  for (int i=0; i < xprime_axis_intercepts.size(); i++) {\n    times_to_xprime_axis(i) = xprime_axis_intercepts[i].tf;\n  }\n  return times_to_xprime_axis.minCoeff();\n}\n\ndouble interceptPlanError(const InterceptPlan &plan, const std::map<FootID, FootState> &foot_states, const BipedDescription &biped) {\n  Matrix<double, 3, 2*QP_REACTIVE_RECOVERY_VERTICES_PER_FOOT> foot_vertices_in_world;\n  foot_vertices_in_world.block(0, 0, 3, QP_REACTIVE_RECOVERY_VERTICES_PER_FOOT) = plan.pose_next * biped.foot_vertices.find(plan.swing_foot)->second;\n  foot_vertices_in_world.block(0, QP_REACTIVE_RECOVERY_VERTICES_PER_FOOT, 3, QP_REACTIVE_RECOVERY_VERTICES_PER_FOOT) = foot_states.find(plan.stance_foot)->second.pose * biped.foot_vertices.find(plan.stance_foot)->second;\n\n  Vector2d icp_projected_onto_support_polygon = QPReactiveRecoveryPlan::closestPointInConvexHull(plan.icp_next.translation().head(2),\n                                                                                                 foot_vertices_in_world.topRows(2));\n  return (icp_projected_onto_support_polygon - plan.icp_next.translation().head(2)).norm();\n\n  // return (plan.pose_next.translation().head(2) - plan.icp_plus_offset_next.translation().head(2)).norm();\n}\n\nIsometry3d snapToTerrain(const Isometry3d &pose, const double terrain_height, const Ref<const Vector3d> &terrain_normal) {\n  Isometry3d pose_snapped = Isometry3d(Translation<double, 3>(Vector3d(pose.translation().x(), pose.translation().y(), terrain_height)));\n  pose_snapped.linear() = pose.linear();\n\n  Vector3d axis = (pose.rotation() * Vector3d(0, 0, 1)).cross(terrain_normal);\n  double sin_theta = axis.norm();\n  if (sin_theta > 1e-14) {\n    pose_snapped.rotate(AngleAxis<double>(std::asin(sin_theta), axis));\n  }\n  return pose_snapped;\n}\n\nstd::vector<InterceptPlan> QPReactiveRecoveryPlan::getInterceptsWithCoP(const FootID &swing_foot, const std::map<FootID, FootState> &foot_states, const Isometry3d &icp, const Isometry3d &cop) {\n\n  Isometry3d T_world_to_local = QPReactiveRecoveryPlan::getTWorldToLocal(icp, cop);\n  FootID stance_foot = otherFoot[swing_foot];\n\n  // std::cerr << \"reach verts in stance: \" << this->biped.reachable_vertices.find(swing_foot)->second << std::endl;\n  Matrix<double, 3, 4> reachable_vertices_in_world = foot_states.find(stance_foot)->second.pose * this->biped.reachable_vertices.find(swing_foot)->second;\n  // std::cerr << \"stance pose: \" << foot_states.find(stance_foot)->second.pose.translation() << std::endl;\n  // std::cerr << \"reach verts in world: \" << reachable_vertices_in_world << std::endl;\n  // std::cerr << \"foot name: \" << footIDToName[swing_foot] << std::endl;\n\n  double t_min_to_xprime = QPReactiveRecoveryPlan::getMinTimeToXprimeAxis(foot_states.find(swing_foot)->second, this->biped, T_world_to_local);\n  t_min_to_xprime = std::max(t_min_to_xprime, this->min_step_duration);\n\n  double x0 = (T_world_to_local * foot_states.find(swing_foot)->second.pose).translation().x();\n  double xd0 = (T_world_to_local.linear() * foot_states.find(swing_foot)->second.velocity.head(3))(0);\n\n  std::vector<InterceptPlan> intercept_plans;\n\n  double x_ic = (T_world_to_local * icp).translation()(0);\n  double x_cop = 0; // by the definition of our local frame\n\n  ExponentialForm icp_traj_in_local = QPReactiveRecoveryPlan::icpTrajectory(x_ic, x_cop, this->biped.omega);\n  double x_ic_int = icp_traj_in_local.value(t_min_to_xprime) + this->desired_icp_offset;\n  // Don't narrow our stance to intercept if possible\n  // double x_ic_target = std::max(x_ic_int, x0);\n  double x_ic_target = x_ic_int;\n\n  Polynomial<double> x_foot_poly_plus = QPReactiveRecoveryPlan::bangBangPolynomial(x0, xd0, this->biped.u_max);\n  Polynomial<double> x_foot_poly_minus = QPReactiveRecoveryPlan::bangBangPolynomial(x0, xd0, -this->biped.u_max);\n  Vector2d x_foot_int(x_foot_poly_plus.value(t_min_to_xprime), x_foot_poly_minus.value(t_min_to_xprime));\n\n  if ((x_ic_target >= x_foot_int.minCoeff()) && (x_ic_target <= x_foot_int.maxCoeff())) {\n    // std::cerr << \"xprime dominates\" << std::endl;\n    // The time to get onto the xprime axis dominates, and we can hit the ICP (plus offset) as soon as we get to that axis\n    std::vector<BangBangIntercept> intercepts = QPReactiveRecoveryPlan::bangBangIntercept(x0, xd0, x_ic_target, this->biped.u_max);\n    if (intercepts.size() > 0) {\n      // std::cerr << \"x_ic_target: \" << x_ic_target << std::endl;\n      // if there are multiple options, take the one that switches sooner\n      std::vector<BangBangIntercept>::iterator it_min = std::min_element(intercepts.begin(), intercepts.end(), tswitchComp);\n      Isometry3d intercept_pose_in_world = T_world_to_local.inverse() * Isometry3d(Translation<double, 3>(Vector3d(x_ic_target, 0, 0)));\n      // std::cerr << \"intercept before reach: \" << intercept_pose_in_world.translation() << std::endl;\n      intercept_pose_in_world = QPReactiveRecoveryPlan::closestPoseInConvexHull(intercept_pose_in_world, reachable_vertices_in_world.topRows(2));\n      // std::cerr << \"intercept after reach: \" << intercept_pose_in_world.translation() << std::endl;\n      InterceptPlan intercept_plan;\n      intercept_plan.tf = t_min_to_xprime;\n      intercept_plan.tswitch = it_min->tswitch;\n      intercept_plan.pose_next = intercept_pose_in_world;\n      intercept_plan.icp_next = T_world_to_local.inverse() * Isometry3d(Translation<double, 3>(Vector3d(x_ic_int, 0, 0)));\n      intercept_plan.cop = cop;\n      intercept_plan.swing_foot = swing_foot;\n      intercept_plan.stance_foot = otherFoot[swing_foot];\n      intercept_plan.error = 0; // to be filled in later\n      intercept_plan.stance_pose = foot_states.at(stance_foot).pose;\n      intercept_plans.push_back(intercept_plan);\n    }\n  } else {\n    // std::cerr << \"xprime does not dominate\" << std::endl;\n    std::vector<double> us = {this->biped.u_max, -this->biped.u_max};\n    for (std::vector<double>::iterator u = us.begin(); u != us.end(); ++u) {\n      std::vector<double> t_int = QPReactiveRecoveryPlan::expIntercept(icp_traj_in_local + this->desired_icp_offset, x0, xd0, *u, 7);\n      std::vector<double> t_int_feasible;\n      for (std::vector<double>::iterator it = t_int.begin(); it != t_int.end(); ++it) {\n        if (*it >= t_min_to_xprime && *it >= std::abs(xd0 / (*u))) {\n          t_int_feasible.push_back(*it);\n        }\n      }\n      std::vector<Isometry3d, aligned_allocator<Isometry3d>> reachable_poses;\n      if (t_int_feasible.size() == 0) {\n        // If there are no intercepts, get as close to our desired capture as possible within the reachable set. \n        // note: this might be off the xcop->xic line\n        double x_ic_future = icp_traj_in_local.value(t_min_to_xprime);\n        Isometry3d reachable_pose_in_world = T_world_to_local.inverse() * Isometry3d(Translation<double, 3>(Vector3d(x_ic_future + this->desired_icp_offset, 0, 0)));\n          // std::cerr << \"intercept before reach: \" << reachable_pose_in_world.translation() << std::endl;\n        reachable_pose_in_world = QPReactiveRecoveryPlan::closestPoseInConvexHull(reachable_pose_in_world, reachable_vertices_in_world.topRows(2));\n          // std::cerr << \"intercept after reach: \" << reachable_pose_in_world.translation() << std::endl;\n        reachable_poses.push_back(reachable_pose_in_world);\n      } else {\n        for (std::vector<double>::iterator t = t_int_feasible.begin(); t != t_int_feasible.end(); ++t) {\n          Isometry3d reachable_pose_in_world = T_world_to_local.inverse() * Isometry3d(Translation<double, 3>(Vector3d(icp_traj_in_local.value(*t) + this->desired_icp_offset, 0, 0)));\n          // std::cerr << \"intercept before reach: \" << reachable_pose_in_world.translation() << std::endl;\n          reachable_pose_in_world = QPReactiveRecoveryPlan::closestPoseInConvexHull(reachable_pose_in_world, reachable_vertices_in_world.topRows(2));\n          // std::cerr << \"intercept after reach: \" << reachable_pose_in_world.translation() << std::endl;\n          reachable_poses.push_back(reachable_pose_in_world);\n        }\n      }\n      for (std::vector<Isometry3d, aligned_allocator<Isometry3d>>::iterator reachable_pose = reachable_poses.begin(); reachable_pose != reachable_poses.end(); ++ reachable_pose) {\n        Isometry3d reachable_pose_in_local = T_world_to_local * (*reachable_pose);\n\n        std::vector<BangBangIntercept> intercepts = QPReactiveRecoveryPlan::bangBangIntercept(x0, xd0, reachable_pose_in_local.translation().x(), this->biped.u_max);\n        if (intercepts.size() > 0) {\n          // if there are multiple options, take the one that switches sooner\n          std::vector<BangBangIntercept>::iterator it_min = std::min_element(intercepts.begin(), intercepts.end(), tswitchComp);\n\n          InterceptPlan intercept_plan;\n          intercept_plan.tf = std::max(it_min->tf, t_min_to_xprime);\n          intercept_plan.tswitch = it_min->tswitch;\n          intercept_plan.pose_next = *reachable_pose;\n          intercept_plan.icp_next = T_world_to_local.inverse() * Isometry3d(Translation<double, 3>(Vector3d(icp_traj_in_local.value(it_min->tf), 0, 0)));\n          intercept_plan.cop = cop;\n          intercept_plan.swing_foot = swing_foot;\n          intercept_plan.stance_foot = otherFoot[swing_foot];\n          intercept_plan.error = 0; // to be filled in later\n          intercept_plan.stance_pose = foot_states.at(stance_foot).pose;\n          intercept_plans.push_back(intercept_plan);\n        }\n      }\n    }\n  }\n\n  for (std::vector<InterceptPlan>::iterator it = intercept_plans.begin(); it != intercept_plans.end(); ++it) {\n    it->pose_next.linear() = foot_states.find(stance_foot)->second.pose.linear();\n    it->pose_next = snapToTerrain(it->pose_next, foot_states.find(stance_foot)->second.terrain_height, foot_states.find(stance_foot)->second.terrain_normal);\n    it->error = interceptPlanError(*it, foot_states, this->biped);\n  }\n\n  return intercept_plans;\n}\n\nstd::vector<InterceptPlan> QPReactiveRecoveryPlan::getInterceptPlansForFoot(const FootID &swing_foot, const std::map<FootID, FootState> &foot_states, const Isometry3d &icp) {\n  FootID stance_foot = otherFoot.find(swing_foot)->second;\n\n  // Find the center of pressure, which we'll place as close as possible to the ICP\n  Isometry3d cop = QPReactiveRecoveryPlan::closestPoseInConvexHull(icp, \n                       (foot_states.find(stance_foot)->second.pose * (this->foot_hull_cop_shrink_factor * this->biped.foot_vertices.find(stance_foot)->second)).topRows(2));\n  return this->getInterceptsWithCoP(swing_foot, foot_states, icp, cop);\n}\n\nstd::vector<InterceptPlan> QPReactiveRecoveryPlan::getInterceptPlans(const std::map<FootID, FootState> &foot_states, const Isometry3d &icp) {\n  std::vector<InterceptPlan> all_intercept_plans;\n  std::vector<FootID> available_swing_feet;\n\n  if (foot_states.find(RIGHT)->second.contact && foot_states.find(LEFT)->second.contact) {\n    available_swing_feet.push_back(LEFT);\n    available_swing_feet.push_back(RIGHT);\n  } else if (!foot_states.find(RIGHT)->second.contact) {\n    available_swing_feet.push_back(RIGHT);\n  } else {\n    available_swing_feet.push_back(LEFT);\n  }\n\n  for (std::vector<FootID>::iterator swing_foot = available_swing_feet.begin(); swing_foot != available_swing_feet.end(); ++swing_foot) {\n    if (foot_states.find(*swing_foot)->second.velocity.head(3).squaredNorm() / this->biped.u_max / 2.0 < this->max_considerable_foot_swing) {\n      std::vector<InterceptPlan> foot_plans = this->getInterceptPlansForFoot(*swing_foot, foot_states, icp);\n      all_intercept_plans.insert(all_intercept_plans.end(), foot_plans.begin(), foot_plans.end());\n    }\n  }\n  return all_intercept_plans;\n}\n\nstd::unique_ptr<PiecewisePolynomial<double>> QPReactiveRecoveryPlan::freeKnotTimesSpline(double t0, double tf, const Ref<const MatrixXd> &xs, const Ref<const VectorXd> xd0, const Ref<const VectorXd> xdf) {\n  const int grid_steps = 10;\n\n  const size_t num_segments = xs.cols() - 1;\n  const size_t ndof = xs.rows();\n  const size_t num_knots = num_segments - 1;\n\n  if (xs.rows() != xd0.rows() || xs.rows() != xdf.rows()) {\n    throw std::runtime_error(\"size of xs and xd0 (or xdf) don't match\");\n  }\n\n  std::vector<double> segment_times;\n  segment_times.resize(num_segments + 1);\n  segment_times[0] = t0;\n  segment_times[static_cast<size_t>(num_segments)] = tf;\n  std::vector<double> best_segment_times = segment_times;\n  double t_step = (tf - t0) / grid_steps;\n  double min_objective_value = std::numeric_limits<double>::infinity();\n\n  // assemble the knot point locations for input to nWaypointCubicSpline\n  MatrixXd xi = xs.block(0, 1, ndof, num_knots);\n\n  int t_indices[num_knots];\n  if (grid_steps <= num_knots){\n    // If we have have too few grid steps, then by pigeonhole it's\n    // impossible to give each a unique time in our grid search.\n    throw std::runtime_error(\"Drake:freeKnotTimesSpline:TooManyKnotsForNumGridSteps\");\n  }\n  for (int i=0; i<num_knots; i++)\n    t_indices[i] = i+1; // assume knot point won't be the same time as the\n          // initial state, or previous knot point\n \n  while (t_indices[0] < grid_steps-num_knots+1){\n    for (int i=0; i<num_knots; i++)\n      segment_times[i+1] = t0 + t_indices[i]*t_step;\n\n    bool valid_solution = true;\n    double objective_value = 0.0;\n    for (int dof = 0; dof < ndof && valid_solution; dof++) {\n      try {\n        PiecewisePolynomial<double> spline = nWaypointCubicSpline(segment_times, xs(dof, 0), xd0(dof), xs(dof, num_segments), xdf(dof), xi.row(dof).transpose());\n        PiecewisePolynomial<double> acceleration_squared = spline.derivative(2);\n        acceleration_squared *= acceleration_squared;\n        PiecewisePolynomial<double> acceleration_squared_integral = acceleration_squared.integral();\n        objective_value += acceleration_squared_integral.scalarValue(spline.getEndTime()) - acceleration_squared_integral.scalarValue(spline.getStartTime());\n      }\n      catch (ConstraintMatrixSingularError&) {\n        valid_solution = false;\n      }\n    }\n\n    if (valid_solution && objective_value < min_objective_value) {\n      best_segment_times = segment_times;\n      min_objective_value = objective_value;\n    }\n\n    // Advance grid search counter or terminate, counting from\n    // the latest t_index, and on overflow carrying to the\n    // next lowest t_index and resetting to the new value of that\n    // next lowest t_index. (since times must always be in order!)\n    t_indices[num_knots-1]++;\n    // carry, except for the lowest place, which we \n    // use to detect doneness.\n    for (int i=num_knots-1; i>0; i--){\n      if ((i==num_knots-1 && t_indices[i] >= grid_steps) || (i<num_knots-1 && t_indices[i] >= t_indices[i+1])){\n        t_indices[i-1]++;\n        t_indices[i] = t_indices[i-1]+1;\n      }\n    }\n  }\n\n  std::vector<Matrix<Polynomial<double>, Dynamic, Dynamic>> poly_matrix;\n  poly_matrix.reserve(num_segments);\n  for (int i=0; i < num_segments; ++i) {\n    poly_matrix.push_back(Matrix<Polynomial<double>, Dynamic, Dynamic> (ndof, 1));\n  }\n  for (int dof=0; dof < ndof; ++dof) {\n    PiecewisePolynomial<double> one_d_spline = nWaypointCubicSpline(best_segment_times, xs(dof, 0), xd0(dof), xs(dof, num_segments), xdf(dof), xi.row(dof).transpose());\n    for (int i=0; i < num_segments; ++i) {\n      poly_matrix[i](dof) = one_d_spline.getPolynomial(i);\n    }\n  }\n  std::unique_ptr<PiecewisePolynomial<double>> spline(new PiecewisePolynomial<double>(poly_matrix, best_segment_times));\n  return spline;\n}\n\nstd::unique_ptr<PiecewisePolynomial<double>> QPReactiveRecoveryPlan::straightToGoalTrajectory(double t_global, const InterceptPlan &intercept_plan, const FootStateMap &foot_states) {\n  const FootState state = foot_states.at(intercept_plan.swing_foot);\n\n  std::cout << \"case 1\" << std::endl;\n\n  const double fraction_first = 0.7;\n\n  const double swing_height_first_in_world = state.terrain_height + (state.pose.translation().z() - state.terrain_height) * (1 - std::pow(fraction_first,2));\n\n  Matrix<double, 6, 3> xs;\n  Vector6d xd0 = Vector6d::Zero(); // don't try to continue current velocity (it just leads to unpredictable and weird splines)\n  Vector6d xdf = Vector6d::Zero();\n\n  Quaterniond quat;\n  xs.block(0, 0, 3, 1) = state.pose.translation();\n  quat = Quaterniond(state.pose.rotation());\n  auto w = quat2expmap(Vector4d(quat.w(), quat.x(), quat.y(), quat.z()), 1);\n  xs.block(3, 0, 3, 1) = w.value();\n\n  xs.block(0, 2, 3, 1) = intercept_plan.pose_next.translation();\n  quat = Quaterniond(intercept_plan.pose_next.rotation());\n  xs.block(3, 2, 3, 1) = quat2expmap(Vector4d(quat.w(), quat.x(), quat.y(), quat.z()), 0).value();\n\n  auto w_unwrap = closestExpmap(xs.block(3, 0, 3, 1), xs.block(3, 2, 3, 1), 1);\n  xs.block(3, 2, 3, 1) = w_unwrap.value();\n  xd0.tail<3>() = w_unwrap.gradient().value() * xd0.tail<3>();\n\n  xs.block(0, 1, 6, 1) = (1 - fraction_first) * xs.block(0, 0, 6, 1) + fraction_first * xs.block(0, 2, 6, 1);\n  xs(2, 1) = swing_height_first_in_world;\n\n  return QPReactiveRecoveryPlan::freeKnotTimesSpline(t_global, intercept_plan.tf + t_global, xs, xd0, xdf);\n}\n\nstd::unique_ptr<PiecewisePolynomial<double>> QPReactiveRecoveryPlan::upOverAndDownTrajectory(double t_global, const InterceptPlan &intercept_plan, const FootStateMap &foot_states) {\n  const FootState state = foot_states.at(intercept_plan.swing_foot);\n\n  std::cout << \"case 2\" << std::endl;\n\n  const double fraction_first = 0.15;\n  const double fraction_second = 1 - fraction_first;\n\n  double swing_height_first_in_world = state.terrain_height + this->swing_height_above_terrain;\n  double swing_height_second_in_world = state.terrain_height + this->swing_height_above_terrain;\n\n  if (state.pose.translation().z() > swing_height_first_in_world) {\n    swing_height_first_in_world = swing_height_second_in_world * (fraction_first / fraction_second) + state.pose.translation().z() * (1 - fraction_first / fraction_second);\n  }\n\n  Matrix<double, 6, 4> xs;\n  Vector6d xd0 = Vector6d::Zero(); // don't try to continue current velocity (it just leads to unpredictable and weird splines)\n  Vector6d xdf = Vector6d::Zero();\n\n  Quaterniond quat;\n  xs.block(0, 0, 3, 1) = state.pose.translation();\n  quat = Quaterniond(state.pose.rotation());\n  auto w = quat2expmap(Vector4d(quat.w(), quat.x(), quat.y(), quat.z()), 1);\n  xs.block(3, 0, 3, 1) = w.value();\n\n  xs.block(0, 3, 3, 1) = intercept_plan.pose_next.translation();\n  quat = Quaterniond(intercept_plan.pose_next.rotation());\n  xs.block(3, 3, 3, 1) = quat2expmap(Vector4d(quat.w(), quat.x(), quat.y(), quat.z()), 0).value();\n\n  auto w_unwrap = closestExpmap(xs.block(3, 0, 3, 1), xs.block(3, 3, 3, 1), 1);\n  xs.block(3, 3, 3, 1) = w_unwrap.value();\n  xd0.tail<3>() = w_unwrap.gradient().value() * xd0.tail<3>();\n\n  xs.block(0, 1, 2, 1) = (1 - fraction_first) * xs.block(0, 0, 2, 1) + fraction_first * xs.block(0, 3, 2, 1);\n  xs(2, 1) = swing_height_first_in_world;\n  xs.block(3, 1, 3, 1) = xs.block(3, 0, 3, 1);\n\n  xs.block(0, 2, 2, 1) = (1 - fraction_second) * xs.block(0, 0, 2, 1) + fraction_second * xs.block(0, 3, 2, 1);\n  xs(2, 2) = swing_height_second_in_world;\n  xs.block(3, 2, 3, 1) = xs.block(3, 3, 3, 1);\n\n  return QPReactiveRecoveryPlan::freeKnotTimesSpline(t_global, t_global + intercept_plan.tf, xs, xd0, xdf);\n}\n\nstd::unique_ptr<PiecewisePolynomial<double>> QPReactiveRecoveryPlan::swingTrajectory(double t_global, const InterceptPlan &intercept_plan, const std::map<FootID, FootState> &foot_states) {\n  const FootState state = foot_states.at(intercept_plan.swing_foot);\n  const double dist_to_goal = (intercept_plan.pose_next.translation().head(2) - state.pose.translation().head(2)).norm();\n  // TODO: name the magic numbers here\n  const double descend_coeff = std::pow(1.0 / 0.15, 2);\n\n  std::cout << \"planning swing with tf = \" << intercept_plan.tf << std::endl;\n  if (descend_coeff * std::pow(state.pose.translation().z() - state.terrain_height, 2) >= dist_to_goal) {\n    // We're within a quadratic bowl around our target, so let's just descend straight there\n    return this->straightToGoalTrajectory(t_global, intercept_plan, foot_states);\n  } else {\n    // We'll need to go up and then back down to get to the goal\n    return this->upOverAndDownTrajectory(t_global, intercept_plan, foot_states);\n  }\n}\n\nvoid QPReactiveRecoveryPlan::setRobot(RigidBodyTree *robot) {\n  this->robot = robot;\n  this->findFootSoleFrames();\n  this->q_des.resize(robot->num_positions);\n}\n\nQPReactiveRecoveryPlan::QPReactiveRecoveryPlan(RigidBodyTree *robot, const RobotPropertyCache &rpc) {\n  this->robot = robot;\n  this->biped = getAtlasDefaults();\n  this->robot_property_cache = rpc;\n  if (this->robot) {\n    this->setRobot(robot);\n  }\n  this->initLCM();\n}\n\nQPReactiveRecoveryPlan::QPReactiveRecoveryPlan(RigidBodyTree *robot, const RobotPropertyCache &rpc, BipedDescription biped) {\n  this->robot = robot;\n  this->biped = biped;\n  this->robot_property_cache = rpc;\n  if (this->robot) {\n    this->setRobot(robot);\n  }\n  this->initLCM();\n}\n\nvoid QPReactiveRecoveryPlan::findFootSoleFrames() {\n  std::map<FootID, bool> has_frame;\n  has_frame[RIGHT] = false;\n  has_frame[LEFT] = false;\n  for (int i=0; i < robot->frames.size(); ++i) {\n    if (this->robot->frames[i]->name == \"r_foot_sole\") {\n      has_frame[RIGHT] = true;\n      // frame_ind0 = -frameID - 2\n      // i = -frameID - 2;\n      // frameID = -i - 2;\n      this->foot_frame_ids[RIGHT] = -i - 2;\n      Isometry3d Tframe;\n      int body_id = this->robot->parseBodyOrFrameID( this->foot_frame_ids[RIGHT], &Tframe);\n      if (!Tframe.isApprox(this->robot->frames[i]->transform_to_body)) {\n        throw std::runtime_error(\"somehow I got the frame ID/index logic wrong\");\n      }\n      this->foot_body_ids[RIGHT] = body_id;\n    } else if (this->robot->frames[i]->name == \"l_foot_sole\") {\n      has_frame[LEFT] = true;\n      this->foot_frame_ids[LEFT] = -i - 2;\n      Isometry3d Tframe;\n      int body_id = this->robot->parseBodyOrFrameID(this->foot_frame_ids[LEFT], &Tframe);\n      if (!Tframe.isApprox(this->robot->frames[i]->transform_to_body)) {\n        throw std::runtime_error(\"somehow I got the frame ID/index logic wrong\");\n      }\n      this->foot_body_ids[LEFT] = body_id;\n    }\n  }\n\n  if (!has_frame[RIGHT]) {\n    throw std::runtime_error(\"could not find r_foot_sole frame\");\n  }\n  if (!has_frame[LEFT]) {\n    throw std::runtime_error(\"could not find l_foot_sole frame\");\n  }\n}\n\nvoid QPReactiveRecoveryPlan::resetInitialization() {\n  this->initialized = false;\n  this->last_swing_plan.reset(NULL);\n}\n\ndrake::lcmt_qp_controller_input QPReactiveRecoveryPlan::getQPControllerInput(double t_global, const VectorXd &q, const VectorXd &v, const std::vector<bool>& contact_force_detected) {\n  if (!this->initialized) {\n    for (int i=0; i < this->robot_property_cache.position_indices.at(\"arm\").size(); ++i) {\n      int j = this->robot_property_cache.position_indices.at(\"arm\")(i);\n      this->q_des(j) = q(j);\n    }\n    this->initialized = true;\n    this->t_start = t_global;\n  }\n\n  KinematicsCache<double> cache = this->robot->doKinematics(q, v);\n\n\n  Vector2d r_ic = this->getICP(cache, v);\n  Isometry3d icp = Isometry3d(Translation<double, 3>(Vector3d(r_ic(0), r_ic(1), 0)));\n\n  FootStateMap foot_states = this->getFootStates(cache, v, contact_force_detected);\n\n  bool is_captured = this->isICPCaptured(icp.translation().head<2>(), foot_states, this->biped.foot_vertices);\n\n  drake::lcmt_qp_controller_input qp_input;\n  this->setupQPInputDefaults(t_global, qp_input);\n\n  if (this->last_swing_plan && t_global < this->last_swing_plan->getEndTime()) {\n    // std::cout << \"continuing current plan\" << std::endl;\n    this->getInterceptInput(t_global, foot_states, qp_input);\n  } else if (is_captured) {\n    // std::cout << \"is captured\" << std::endl;\n    this->getCaptureInput(t_global, foot_states, icp, qp_input);\n  } else if (this->last_swing_plan && t_global < this->last_swing_plan->getEndTime() + this->post_execution_delay) {\n    // std::cout << \"in delay after plan end\" << std::endl;\n    this->getCaptureInput(t_global, foot_states, icp, qp_input);\n  } else {\n    std::cout << \"replanning\" << std::endl;\n    std::vector<InterceptPlan> intercept_plans = this->getInterceptPlans(foot_states, icp);\n    if (intercept_plans.size() == 0) {\n      std::cout << \"recovery is not possible\" << std::endl;\n      this->getCaptureInput(t_global, foot_states, icp, qp_input);\n    } else {\n      std::vector<InterceptPlan>::iterator best_plan = std::min_element(intercept_plans.begin(), intercept_plans.end(), errorCompare);\n      this->last_intercept_plan = *best_plan;\n      this->last_swing_plan.reset(this->swingTrajectory(t_global, this->last_intercept_plan, foot_states).release());\n      this->t_start = t_global;\n      this->getInterceptInput(t_global, foot_states, qp_input);\n    }\n  }\n\n  this->publishForVisualization(cache, t_global, icp);\n  verifySubtypeSizes(qp_input);\n  return qp_input;\n}\n\nvoid QPReactiveRecoveryPlan::publishQPControllerInput(double t_global, const VectorXd &q, const VectorXd &v, const std::vector<bool>& contact_force_detected) {\n  drake::lcmt_qp_controller_input qp_input = this->getQPControllerInput(t_global, q, v, contact_force_detected);\n  this->LCMHandle->publish(\"QP_CONTROLLER_INPUT\", &qp_input);\n}\n\nvoid QPReactiveRecoveryPlan::setupQPInputDefaults(double t_global, drake::lcmt_qp_controller_input &qp_input) {\n  qp_input.be_silent = false;\n  qp_input.timestamp = static_cast<int64_t> (t_global * 1e6);\n  qp_input.num_support_data = 0;\n  qp_input.num_tracked_bodies = 0;\n  qp_input.num_external_wrenches = 0;\n  qp_input.num_joint_pd_overrides = 0;\n\n  qp_input.zmp_data.timestamp = 0;\n\n  Matrix4d A = Matrix4d::Zero();\n  A.block(0, 2, 2, 2) = Matrix2d::Identity();\n  eigenToCArrayOfArrays(A, qp_input.zmp_data.A);\n\n  Matrix<double, 4, 2> B = Matrix<double, 4, 2>::Zero();\n  B.block(2, 0, 2, 2) = Matrix2d::Identity();\n  eigenToCArrayOfArrays(B, qp_input.zmp_data.B);\n\n  Matrix<double, 2, 4> C = Matrix<double, 2, 4>::Zero();\n  C.block(0, 0, 2, 2) = Matrix2d::Identity();\n  eigenToCArrayOfArrays(C, qp_input.zmp_data.C);\n\n  Matrix2d D = Matrix2d::Identity();\n  D *= -(1.0 / pow(this->biped.omega, 2));\n  eigenToCArrayOfArrays(D, qp_input.zmp_data.D);\n\n  // x0 and y0 will be filled in from the plan\n\n  Vector2d u0 = Vector2d::Zero();\n  eigenToCArrayOfArrays(u0, qp_input.zmp_data.u0);\n\n  Matrix2d R = Matrix2d::Zero();\n  eigenToCArrayOfArrays(R, qp_input.zmp_data.R);\n\n  Matrix2d Qy = Matrix2d::Identity();\n  Qy *= 0.8;\n  eigenToCArrayOfArrays(Qy, qp_input.zmp_data.Qy);\n\n  eigenToCArrayOfArrays(this->S, qp_input.zmp_data.S);\n\n  Vector4d s1 = Vector4d::Zero();\n  eigenToCArrayOfArrays(s1, qp_input.zmp_data.s1);\n\n  Vector4d s1dot = Vector4d::Zero();\n  eigenToCArrayOfArrays(s1dot, qp_input.zmp_data.s1dot);\n\n  qp_input.zmp_data.s2 = 0;\n  qp_input.zmp_data.s2dot = 0;\n\n  qp_input.whole_body_data.num_positions = this->robot->num_positions;\n  qp_input.whole_body_data.q_des.resize(this->robot->num_positions);\n  for (int i=0; i < this->robot->num_positions; ++i) {\n    qp_input.whole_body_data.q_des[i] = this->q_des(i);\n  }\n  for (int i=0; i < this->robot_property_cache.position_indices.at(\"arm\").size(); i++) {\n    qp_input.whole_body_data.constrained_dofs.push_back(this->robot_property_cache.position_indices.at(\"arm\")[i] + 1);\n  }\n  for (int i=0; i < this->robot_property_cache.position_indices.at(\"neck\").size(); i++) {\n    qp_input.whole_body_data.constrained_dofs.push_back(this->robot_property_cache.position_indices.at(\"neck\")[i] + 1);\n  }\n  for (int i=0; i < this->robot_property_cache.position_indices.at(\"back_bky\").size(); i++) {\n    qp_input.whole_body_data.constrained_dofs.push_back(this->robot_property_cache.position_indices.at(\"back_bky\")[i] + 1);\n  }\n  for (int i=0; i < this->robot_property_cache.position_indices.at(\"back_bkz\").size(); i++) {\n    qp_input.whole_body_data.constrained_dofs.push_back(this->robot_property_cache.position_indices.at(\"back_bkz\")[i] + 1);\n  }\n  qp_input.whole_body_data.num_constrained_dofs = qp_input.whole_body_data.constrained_dofs.size();\n\n  qp_input.param_set_name = \"recovery\";\n\n}\n\n\nvoid QPReactiveRecoveryPlan::publishForVisualization(KinematicsCache<double>& cache, double t_global, const Isometry3d &icp) {\n  std::shared_ptr<drc::reactive_recovery_debug_t> msg(new drc::reactive_recovery_debug_t());\n\n  msg->utime = static_cast<int64_t> (t_global * 1e6);\n\n  auto com = this->robot->centerOfMass<double>(cache);\n  memcpy(msg->com, com.data(), 3*sizeof(double));\n  memcpy(msg->icp, icp.translation().head<2>().data(), 2*sizeof(double));\n\n  msg->num_spline_ts = 0;\n  msg->num_spline_segments = 0;\n\n  this->LCMHandle->publish(\"REACTIVE_RECOVERY_DEBUG\", msg.get());\n}\n\nMatrix3Xd QPReactiveRecoveryPlan::heelToeContacts(int body_id) {\n  Matrix3Xd toe_contacts = this->robot_property_cache.contact_groups[body_id].at(\"toe\");\n  Matrix3Xd heel_contacts = this->robot_property_cache.contact_groups[body_id].at(\"heel\");\n  Matrix3Xd all_contacts(3, toe_contacts.cols() + heel_contacts.cols());\n  all_contacts.block(0, 0, 3, toe_contacts.cols()) = toe_contacts;\n  all_contacts.block(0, toe_contacts.cols(), 3, heel_contacts.cols()) = heel_contacts;\n  return all_contacts;\n}\n\nstd::map<SupportLogicType, std::vector<bool>> createSupportLogicMaps() {\n  std::map<SupportLogicType, std::vector<bool> > ret;\n  ret[REQUIRE_SUPPORT] = { {true, true, true, true} };\n  ret[ONLY_IF_FORCE_SENSED] = { {false, false, true, true} };\n  ret[KINEMATIC_OR_SENSED] = { {false, true, true, true} };\n  ret[PREVENT_SUPPORT] = { {false, false, false, false} };\n  return ret;\n}\n\nvoid QPReactiveRecoveryPlan::encodeSupportData(const int body_id, const FootState &foot_state, const SupportLogicType &support_logic, drake::lcmt_support_data &support_data) {\n  support_data.timestamp = 0;\n  support_data.body_id = body_id + 1;\n  support_data.contact_pts.resize(3);\n  Matrix3Xd all_contacts = this->heelToeContacts(body_id);\n  support_data.num_contact_pts = all_contacts.cols();\n  for (int i=0; i < 3; i++) {\n    support_data.contact_pts[i].resize(all_contacts.cols());\n    for (int j=0; j < all_contacts.cols(); j++) {\n      support_data.contact_pts[i][j] = all_contacts(i, j);\n    }\n  }\n  std::map<SupportLogicType, std::vector<bool>> logic_maps = createSupportLogicMaps();\n  std::vector<bool> logic = logic_maps.at(support_logic);\n  for (int i=0; i < 4; ++i) {\n    support_data.support_logic_map[i] = logic[i];\n  }\n  support_data.mu = this->mu;\n  support_data.use_support_surface = true;\n  for (int i=0; i < 3; ++i) {\n    // 4-vector describing a support surface: [v; b] such that v' * [x;y;z] + b == 0\n    // we have normal n and height h at x0,y0\n    // n' * [x0;y0;h] + b == 0\n    // b = -n' * [x0;y0;h]\n    support_data.support_surface[i] = static_cast<float>(foot_state.terrain_normal(i));\n  }\n  support_data.support_surface[3] = static_cast<float> (-1 * foot_state.terrain_normal.transpose() * Vector3d(foot_state.pose.translation().x(), foot_state.pose.translation().y(), foot_state.terrain_height));\n}\n\nvoid QPReactiveRecoveryPlan::encodeBodyMotionData(int body_or_frame_id, PiecewisePolynomial<double> spline, drake::lcmt_body_motion_data &body_motion) {\n  body_motion.timestamp = 0;\n  body_motion.body_id = body_or_frame_id + 1;\n  encodePiecewisePolynomial(spline, body_motion.spline);\n  body_motion.in_floating_base_nullspace = false;\n  body_motion.control_pose_when_in_contact = false;\n  body_motion.quat_task_to_world[0] = 1;\n  body_motion.quat_task_to_world[1] = 0;\n  body_motion.quat_task_to_world[2] = 0;\n  body_motion.quat_task_to_world[3] = 0;\n  body_motion.translation_task_to_world[0] = 0;\n  body_motion.translation_task_to_world[1] = 0;\n  body_motion.translation_task_to_world[2] = 0;\n  body_motion.xyz_kp_multiplier[0] = 1;\n  body_motion.xyz_kp_multiplier[1] = 1;\n  body_motion.xyz_kp_multiplier[2] = 1;\n  body_motion.xyz_damping_ratio_multiplier[0] = 1;\n  body_motion.xyz_damping_ratio_multiplier[1] = 1;\n  body_motion.xyz_damping_ratio_multiplier[2] = 1;\n  body_motion.expmap_kp_multiplier = 1;\n  body_motion.expmap_damping_ratio_multiplier = 1;\n  body_motion.weight_multiplier[0] = 1;\n  body_motion.weight_multiplier[1] = 1;\n  body_motion.weight_multiplier[2] = 1;\n  body_motion.weight_multiplier[3] = 1;\n  body_motion.weight_multiplier[4] = 1;\n  body_motion.weight_multiplier[5] = 1;\n}\n\ndouble angleAverage(double theta1, double theta2) {\n  // (Copied from drakeUtil.cpp to avoid a lot of extra dependencies)\n  //\n  // Computes the average between two angles by averaging points on the unit\n  // circle and taking the arctan of the result.\n  //   see: http://en.wikipedia.org/wiki/Mean_of_circular_quantities\n  // theta1 is a scalar or column vector of angles (rad)\n  // theta2 is a scalar or column vector of angles (rad)\n\n  double x_mean = 0.5 * (std::cos(theta1) + std::cos(theta2));\n  double y_mean = 0.5 * (std::sin(theta1) + std::sin(theta2));\n\n  double angle_mean = atan2(y_mean, x_mean);\n\n  return angle_mean;\n}\n\nPiecewisePolynomial<double> constantPoseCubicSpline(const Isometry3d &pose) {\n  std::vector<Matrix<Polynomial<double>, Dynamic, Dynamic>> poly_matrix;\n  poly_matrix.push_back(Matrix<Polynomial<double>, Dynamic, Dynamic>(6, 1));\n  std::vector<double> ts = {0, 0};\n  Matrix<double, 0, 1> xi;\n  Vector6d xyzexp;\n  xyzexp.head<3>() = pose.translation().head<3>();\n  Quaterniond quat = Quaterniond(pose.rotation());\n  xyzexp.tail<3>() = quat2expmap(Vector4d(quat.w(), quat.x(), quat.y(), quat.z()), 0).value();\n  for (int i=0; i < 6; ++i) {\n    poly_matrix[0](i) = Polynomial<double>(Vector4d(xyzexp(i), 0, 0, 0));\n  }\n  return PiecewisePolynomial<double>(poly_matrix, ts);\n}\n\nvoid QPReactiveRecoveryPlan::getInterceptInput(double t_global, const FootStateMap &foot_states, drake::lcmt_qp_controller_input &qp_input) {\n\n  PiecewisePolynomial<double>::CoefficientMatrix plan_shift(6, 1);\n  plan_shift.topRows<3>() = this->last_intercept_plan.stance_pose.translation() - foot_states.at(this->last_intercept_plan.stance_foot).pose.translation();\n  plan_shift.bottomRows<3>().setZero();\n  // plan_shift = desired - measured;\n  // measured = desired - plan_shift\n\n  Vector4d x0 = Vector4d::Zero();\n  x0.head<2>() = 0.5 * this->last_intercept_plan.stance_pose.translation().head<2>() + 0.5 * this->last_intercept_plan.pose_next.translation().head<2>() - plan_shift.topRows<2>();\n  eigenToCArrayOfArrays(x0, qp_input.zmp_data.x0);\n  eigenToCArrayOfArrays(this->last_intercept_plan.cop.translation().head<2>() - plan_shift.topRows<2>(), qp_input.zmp_data.y0);\n\n  drake::lcmt_support_data support_data_stance;\n  int stance_foot_id = this->foot_body_ids.at(this->last_intercept_plan.stance_foot);\n  this->encodeSupportData(stance_foot_id, foot_states.at(this->last_intercept_plan.stance_foot), \n                          REQUIRE_SUPPORT, support_data_stance);\n  qp_input.support_data.push_back(support_data_stance);\n\n  drake::lcmt_support_data support_data_swing;\n  if (t_global - this->t_start <= (this->last_swing_plan->getEndTime() - this->last_swing_plan->getStartTime()) / 2) {\n    this->encodeSupportData(this->foot_body_ids.at(this->last_intercept_plan.swing_foot),\n                            foot_states.at(this->last_intercept_plan.swing_foot),\n                            PREVENT_SUPPORT, support_data_swing);\n  } else {\n    this->encodeSupportData(this->foot_body_ids.at(this->last_intercept_plan.swing_foot),\n                            foot_states.at(this->last_intercept_plan.swing_foot),\n                            ONLY_IF_FORCE_SENSED, support_data_swing);\n  }\n  qp_input.support_data.push_back(support_data_swing);\n  qp_input.num_support_data = qp_input.support_data.size();\n\n  drake::lcmt_body_motion_data body_motion;\n  this->encodeBodyMotionData(this->foot_frame_ids.at(this->last_intercept_plan.swing_foot),\n                             *this->last_swing_plan - plan_shift, body_motion);\n  body_motion.in_floating_base_nullspace = true;\n  qp_input.body_motion_data.push_back(body_motion);\n\n  double pelvis_height = this->last_intercept_plan.stance_pose.translation().z() + this->pelvis_height_above_sole;\n  // double pelvis_height = foot_states.at(this->last_intercept_plan.stance_foot).terrain_height + this->pelvis_height_above_sole;\n  Quaterniond rfoot_quat = Quaterniond(foot_states.at(RIGHT).pose.rotation());\n  Quaterniond lfoot_quat = Quaterniond(foot_states.at(LEFT).pose.rotation());\n  double pelvis_yaw = angleAverage(quat2rpy(Vector4d(rfoot_quat.w(), rfoot_quat.x(), rfoot_quat.y(), rfoot_quat.z()))(2), \n                                quat2rpy(Vector4d(lfoot_quat.w(), lfoot_quat.x(), lfoot_quat.y(), lfoot_quat.z()))(2));\n  Isometry3d pelvis_pose = Isometry3d(Translation<double, 3>(Vector3d(0, 0, pelvis_height)));\n  pelvis_pose.rotate(AngleAxis<double>(pelvis_yaw, Vector3d(0, 0, 1)));\n  this->encodeBodyMotionData(this->robot_property_cache.body_ids.pelvis,\n                             constantPoseCubicSpline(pelvis_pose) - plan_shift,\n                             body_motion);\n  body_motion.weight_multiplier[3] = 0; // don't try to control x and y\n  body_motion.weight_multiplier[4] = 0;\n  qp_input.body_motion_data.push_back(body_motion);\n  qp_input.num_tracked_bodies = qp_input.body_motion_data.size();\n}\n\nvoid QPReactiveRecoveryPlan::getCaptureInput(double t_global, const FootStateMap &foot_states, const Isometry3d &icp, drake::lcmt_qp_controller_input &qp_input) {\n\n  Vector4d x0 = Vector4d::Zero();\n  x0.head<2>() = 0.5 * foot_states.at(RIGHT).pose.translation().head<2>() + 0.5 * foot_states.at(LEFT).pose.translation().head<2>();\n  eigenToCArrayOfArrays(x0, qp_input.zmp_data.x0);\n  eigenToCArrayOfArrays(x0.head<2>(), qp_input.zmp_data.y0);\n\n  std::vector<FootID> foot_ids = {RIGHT, LEFT};\n  for (std::vector<FootID>::iterator foot = foot_ids.begin(); foot != foot_ids.end(); ++foot) {\n    drake::lcmt_support_data support_data;\n    drake::lcmt_body_motion_data body_motion;\n    if ((foot_states.at(*foot).pose.translation().z() - foot_states.at(*foot).terrain_height) < this->capture_max_flyfoot_height) {\n      this->encodeSupportData(this->foot_body_ids.at(*foot), foot_states.at(*foot),\n                              REQUIRE_SUPPORT, support_data);\n    } else {\n      this->encodeSupportData(this->foot_body_ids.at(*foot), foot_states.at(*foot),\n                              ONLY_IF_FORCE_SENSED, support_data);\n    }\n    qp_input.support_data.push_back(support_data);\n\n    Isometry3d pose_on_terrain = snapToTerrain(foot_states.at(*foot).pose, foot_states.at(*foot).terrain_height, foot_states.at(*foot).terrain_normal);\n    this->encodeBodyMotionData(this->foot_frame_ids.at(*foot), \n                               constantPoseCubicSpline(pose_on_terrain),\n                               body_motion);\n    body_motion.in_floating_base_nullspace = true;\n    qp_input.body_motion_data.push_back(body_motion);\n  }\n  qp_input.num_support_data = qp_input.support_data.size();\n\n  drake::lcmt_body_motion_data body_motion;\n  double pelvis_height = 0.5 * (foot_states.at(LEFT).terrain_height + foot_states.at(RIGHT).terrain_height) + this->pelvis_height_above_sole;\n  Quaterniond rfoot_quat = Quaterniond(foot_states.at(RIGHT).pose.rotation());\n  Quaterniond lfoot_quat = Quaterniond(foot_states.at(LEFT).pose.rotation());\n  double pelvis_yaw = angleAverage(quat2rpy(Vector4d(rfoot_quat.w(), rfoot_quat.x(), rfoot_quat.y(), rfoot_quat.z()))(2), \n                                quat2rpy(Vector4d(lfoot_quat.w(), lfoot_quat.x(), lfoot_quat.y(), lfoot_quat.z()))(2));\n  Isometry3d pelvis_pose = Isometry3d(Translation<double, 3>(Vector3d(0, 0, pelvis_height)));\n  pelvis_pose.rotate(AngleAxis<double>(pelvis_yaw, Vector3d(0, 0, 1)));\n  this->encodeBodyMotionData(this->robot_property_cache.body_ids.pelvis,\n                             constantPoseCubicSpline(pelvis_pose),\n                             body_motion);\n  body_motion.weight_multiplier[3] = 0; // don't try to control x and y\n  body_motion.weight_multiplier[4] = 0;\n  qp_input.body_motion_data.push_back(body_motion);\n  qp_input.num_tracked_bodies = qp_input.body_motion_data.size();\n}\n\nVector2d QPReactiveRecoveryPlan::getICP(KinematicsCache<double>& cache, const VectorXd &v) {\n  Vector3d com_position = this->robot->centerOfMass(cache);\n  Vector3d com_velocity = this->robot->centerOfMassJacobian(cache) * v;\n  Vector2d icp = com_position.head(2) + com_velocity.head(2) / this->biped.omega;\n  return icp;\n}\n\nFootStateMap QPReactiveRecoveryPlan::getFootStates(const KinematicsCache<double>& cache, const VectorXd &v, const std::vector<bool>& contact_force_detected) {\n  std::vector<FootID> foot_ids = {RIGHT, LEFT};\n  FootStateMap foot_states;\n  double min_foot_height = std::numeric_limits<double>::infinity();\n  for (std::vector<FootID>::iterator id = foot_ids.begin(); id != foot_ids.end(); ++id) {\n    const int frame_id = this->foot_frame_ids[*id];\n    Vector3d origin = Vector3d::Zero();\n    foot_states[*id].pose = robot->relativeTransform(cache, 0, frame_id);\n    auto twist = robot->relativeTwist(cache, 0, frame_id, frame_id);\n    auto quat = rotmat2quat(foot_states[*id].pose.linear());\n    foot_states[*id].velocity.topRows<3>() = foot_states[*id].pose.linear() * twist.bottomRows<3>();\n    Matrix<double, QUAT_SIZE, SPACE_DIMENSION> omega_to_quatdot;\n    angularvel2quatdotMatrix(quat, omega_to_quatdot, static_cast<Gradient<decltype(omega_to_quatdot), Dynamic>::type*>(nullptr));\n    foot_states[*id].velocity.bottomRows<4>() = omega_to_quatdot * foot_states[*id].pose.linear() * twist.topRows<3>();\n    int body_id = this->robot->parseBodyOrFrameID(this->foot_frame_ids[*id]);\n    foot_states[*id].contact = contact_force_detected[body_id];\n    if (foot_states[*id].pose.translation().z() < min_foot_height) {\n      min_foot_height = foot_states[*id].pose.translation().z();\n    }\n  }\n\n  for (std::vector<FootID>::iterator id = foot_ids.begin(); id != foot_ids.end(); ++id) {\n    // NOTE: not using terrain maps at all, so we're just assuming the ground is flat under the lower foot\n    foot_states[*id].terrain_height = min_foot_height;\n    foot_states[*id].terrain_normal = Vector3d(0,0,1);\n  }\n\n  return foot_states;\n}\n\nvoid QPReactiveRecoveryPlan::initLCM() {\n  this->LCMHandle = std::shared_ptr<lcm::LCM>(new lcm::LCM);\n  if (!this->LCMHandle->good()) {\n    throw std::runtime_error(\"lcm is not good\");\n  }\n}\n\n", "meta": {"hexsha": "82874df4d277215e2b0f1254f9b3b1fc708b0397", "size": 51630, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "software/control/src/QPReactiveRecoveryPlan.cpp", "max_stars_repo_name": "liangfok/oh-distro", "max_stars_repo_head_hexsha": "eeee1d832164adce667e56667dafc64a8d7b8cee", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 92.0, "max_stars_repo_stars_event_min_datetime": "2016-01-14T21:03:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-01T17:57:46.000Z", "max_issues_repo_path": "software/control/src/QPReactiveRecoveryPlan.cpp", "max_issues_repo_name": "liangfok/oh-distro", "max_issues_repo_head_hexsha": "eeee1d832164adce667e56667dafc64a8d7b8cee", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 62.0, "max_issues_repo_issues_event_min_datetime": "2016-01-16T18:08:14.000Z", "max_issues_repo_issues_event_max_datetime": "2016-03-24T15:16:28.000Z", "max_forks_repo_path": "software/control/src/QPReactiveRecoveryPlan.cpp", "max_forks_repo_name": "liangfok/oh-distro", "max_forks_repo_head_hexsha": "eeee1d832164adce667e56667dafc64a8d7b8cee", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2016-01-14T21:26:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T03:10:39.000Z", "avg_line_length": 47.6731301939, "max_line_length": 220, "alphanum_fraction": 0.7085609142, "num_tokens": 14816, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672181749421, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.46973197137344647}}
{"text": "////////////////////////////////////////////////////////////////////////////////\n// DualLaplacianStencil.hh\n////////////////////////////////////////////////////////////////////////////////\n/*! @file\n//  A configurable stencil for Laplacian regularization terms for face-based\n//  (piecewise constant) quantities. We support a plain 1D graph Laplacian\n//  (with optional scaling by inverse dual edge lengths to ensure proper\n//  scaling under refinement) and a Laplacian based on arbitrarily\n//  triangulating the dual mesh and then using an intrinsic delaunay\n//  triangulation-based Laplacian to cope with bad mesh quality.\n*/\n//  Author:  Julian Panetta (jpanetta), julian.panetta@gmail.com\n//  Created:  01/01/2020 16:26:45\n////////////////////////////////////////////////////////////////////////////////\n#ifndef DUALLAPLACIANSTENCIL_HH\n#define DUALLAPLACIANSTENCIL_HH\n\n#include \"DualMesh.hh\"\n#include <Eigen/Sparse>\n#include <MeshFEM/Utilities/MeshConversion.hh>\n\n// We need to provide a wrapper for this function instead of calling it\n// directly: libigl's `Triplet` will clash with ours if we include\n// `intrinsic_delaunay_cotmatrix.h` in this header.\nvoid igl_intrinsic_delaunay_cotmatrix(const Eigen::MatrixX3d &V,\n                                      const Eigen::MatrixXi  &F,\n                                      Eigen::SparseMatrix<Real> &L);\n\ntemplate<class Mesh>\nstruct DualLaplacianStencil {\n    enum class Type { DualGraph, DualMeshIDT };\n\n    Type type = Type::DualGraph;\n    bool useUniformGraphWeights = true;\n\n    DualLaplacianStencil(const Mesh &m) : m_mesh(m) {\n        m_graphEdgeInvLen.resize(m.numHalfEdges());\n        Real totalEdgeLen = 0;\n        size_t num = 0;\n        for (const auto &he : m.halfEdges()) {\n            if (he.isBoundary()) continue;\n            Real l = (m.elementBarycenter(he.           tri().index())\n                    - m.elementBarycenter(he.opposite().tri().index())).norm();\n            m_graphEdgeInvLen[he.index()] = 1.0 / l;\n            totalEdgeLen += l;\n            ++num;\n        }\n        m_averageEdgeLen = totalEdgeLen / num;\n\n        std::vector<MeshIO::IOVertex > dualVertices;\n        std::vector<MeshIO::IOElement> dualTris;\n        std::vector<size_t> originatingPolygon;\n        triangulatedBarycentricDual(m, dualVertices, dualTris, originatingPolygon);\n        // LibIGL constructs the negative semi-definite Laplacian (which has\n        // positive weights in the off-diagonals, assuming non-obtuse angles).\n        igl_intrinsic_delaunay_cotmatrix(getV(dualVertices), getF(dualTris), m_dualIDTLaplacian);\n    }\n\n    // Call visitor(i, j, w_ij) for each stencil edge e_ij incident face i.\n    template<class F>\n    void visit(size_t i, F &&visitor) const {\n        if (type == Type::DualGraph) {\n            for (const auto &he : m_mesh.element(i).halfEdges()) {\n                if (he.isBoundary()) continue;\n                const auto &tri_j = he.opposite().tri();\n                if (useUniformGraphWeights) visitor(i, tri_j.index(), 1.0);\n                else                        visitor(i, tri_j.index(), m_averageEdgeLen * m_graphEdgeInvLen[he.index()]);\n            }\n        }\n        else if (type == Type::DualMeshIDT) {\n            // Loop over the ith column of the sparse Laplacian matrix...\n            for (Eigen::SparseMatrix<Real>::InnerIterator it(m_dualIDTLaplacian, i); it; ++it) {\n                size_t j = it.index(); // inner index (could also use it.row(), but that is storage-order-dependent)\n                if (j == i) continue;  // skip diagonal\n                visitor(i, j, it.value());\n            }\n        }\n        else {\n            assert(false);\n        }\n    }\n\n    // Visit each edge e_ij with (i < j) in the graph\n    template<class F>\n    void visit_edges(F &&visitor) const {\n        if (type == Type::DualGraph) {\n            for (const auto &tri_i : m_mesh.elements()) {\n                const size_t i = tri_i.index();\n                for (const auto &he : tri_i.halfEdges()) {\n                    if (he.isBoundary()) continue;\n                    const auto &tri_j = he.opposite().tri();\n                    const size_t j = tri_j.index();\n                    if (i >= j) continue;\n                    if (useUniformGraphWeights) visitor(i, j, 1.0);\n                    else                        visitor(i, j, m_averageEdgeLen * m_graphEdgeInvLen[he.index()]);\n                }\n            }\n        }\n        else if (type == Type::DualMeshIDT) {\n            for (const auto &tri_i : m_mesh.elements()) {\n                const size_t i = tri_i.index();\n                // Loop over the ith column of the sparse Laplacian matrix's upper triangle in order\n                for (Eigen::SparseMatrix<Real>::InnerIterator it(m_dualIDTLaplacian, i); it; ++it) {\n                    const size_t j = it.index(); // inner index (could also use it.row(), but that is storage-order-dependent)\n                    if (j == i) break; // skip diagonal/lower triangle\n                    visitor(i, j, it.value());\n                }\n            }\n        }\n        else {\n            assert(false);\n        }\n    }\n\nprivate:\n    const Mesh &m_mesh;\n    Eigen::SparseMatrix<Real> m_dualIDTLaplacian;\n    Real m_averageEdgeLen;\n    std::vector<Real> m_graphEdgeInvLen;\n};\n\n#endif /* end of include guard: DUALLAPLACIANSTENCIL_HH */\n", "meta": {"hexsha": "338d9693a5d7f54a905796dddeca378f2cfecc41", "size": 5347, "ext": "hh", "lang": "C++", "max_stars_repo_path": "DualLaplacianStencil.hh", "max_stars_repo_name": "jpanetta/Inflatables", "max_stars_repo_head_hexsha": "6941fb1bf4a2f61a847605aea37adef97bf05d76", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2021-10-05T18:52:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T06:35:04.000Z", "max_issues_repo_path": "DualLaplacianStencil.hh", "max_issues_repo_name": "jpanetta/Inflatables", "max_issues_repo_head_hexsha": "6941fb1bf4a2f61a847605aea37adef97bf05d76", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DualLaplacianStencil.hh", "max_forks_repo_name": "jpanetta/Inflatables", "max_forks_repo_head_hexsha": "6941fb1bf4a2f61a847605aea37adef97bf05d76", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-09-24T22:26:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-14T21:51:18.000Z", "avg_line_length": 43.4715447154, "max_line_length": 126, "alphanum_fraction": 0.5606882364, "num_tokens": 1256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080671950640465, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4697319579390114}}
{"text": "/*\n * CurrentFlowGroupCloseness.cpp\n *\n *      Author: gstoszek\n */\n\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 \"EffectiveResistanceDistance.h\"\n#include \"ERDLevel.h\"\n#include <armadillo>\n\nnamespace NetworKit {\n\n   CurrentFlowGroupCloseness::CurrentFlowGroupCloseness(const Graph& G,const count k, const count CB) : Centrality(G, true),k(k),CB(CB){\n        S.resize(k);\n        CFGCC = 0.;\n        n=G.upperNodeIdBound();\n        vList.resize(n);\n        TopMatch.resize(n);\n        /*Laplacian*/\n        L.set_size(n,n);\n        L.zeros();\n\n        ERD.M=L;\n        Adj=L;\n\n        for(count i=0;i<L.n_rows;i++){\n          vList[i]=i;\n          for(count j=0;j<L.n_rows;j++){\n            if(G.hasEdge(i,j)){\n              L(i,j)=-1.;\n              L(i,i)+=1;\n              TopMatch[i].push_back(j);\n            }\n          }\n        }\n    }\n\n    void CurrentFlowGroupCloseness::run() {\n      count ID;\n      count nPeripheralMerges;\n      count 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<std::pair<node,node>> Matching;\n      std::vector<std::pair<count,count>> Indices;\n\n      nPeripheralMerges=0;\n      if(CB>1){\n          minDegree=1;\n          std::vector<std::pair<count,count>> c_indices;\n          std::vector<std::pair<node,node>> Matching;\n          ID=0;\n          c_indices.resize(0);\n\n          ERDLevel Level(ID,vList,Matching,TopMatch,Adj);\n          LevelList.push_back (Level);\n          /*update*/\n          minDegree=updateMinDegree(minDegree);\n\n          while(minDegree==1){\n            c_indices=peripheralCoarsingIndices();\n            Matching=updateMatching(c_indices);\n            coarseLaplacian(c_indices);\n            ID++;\n            Level.set(ID,vList,Matching,TopMatch,Adj);\n            LevelList.push_back (Level);\n            minDegree=updateMinDegree(minDegree);\n            TopMatch=updateTopMatch(minDegree);\n          }\n          /*\n          while(minDegree<CB){\n            c_indices=coarsingIndices(minDegree, false);\n            Matching=updateMatching(c_indices);\n            coarseLaplacian(c_indices);\n            ID++;\n            Level.set(ID,vList,Matching,TopMatch,Adj);\n            LevelList.push_back (Level);\n            minDegree=updateMinDegree(minDegree);\n            TopMatch=updateTopMatch(minDegree);\n          }\n          */\n        }\n        L=arma::pinv(L, 0.01);\n        ERD.computeFromPinvL(L,vList);\n        if(CB>1){\n          ID=LevelList[LevelList.size()-1].get_ID();\n          while(ID>1){\n            Matching=LevelList[ID].get_Matching();\n            for(count i=0;i<Matching.size();i++){\n              uncoarse(Matching[i].second, Matching[i].first, ID);\n            }\n            ID--;\n            vList=LevelList[ID].get_vList();\n          }\n          nPeripheralMerges=mergePeripheralNodes();\n        }\n        end = std::chrono::high_resolution_clock::now();\n        diff = end-start;\n        std::cout << \"Computation of EffectiveResistanceDistanceMatrice finished in \" << diff.count() << \"(s)\" << \"\\n\\n\";\n\n\n        greedy(nPeripheralMerges);\n      }\n      /*******************************************************************************************************************************************************/\n      std::vector<node> CurrentFlowGroupCloseness::groupMaxCurrentFlowCloseness(){\n          return S;\n      }\n      /*******************************************************************************************************************************************************/\n      double CurrentFlowGroupCloseness::getCFGCC() {\n          return CFGCC;\n      }\n      /**************************************************************************************************************/\n        void CurrentFlowGroupCloseness::cleanNetwork(){\n          count n2;\n          n2=0;\n          for(count i=0;i<n;i++){\n            if(L(i,i)==0){\n              vList.erase(vList.begin()+i-n2);\n              n2++;\n            }\n          }\n          if(n2>0){\n            n-=n2;\n            arma::uvec indices(n);\n            for(count i=0;i<n;i++){\n                indices(i)=vList[i];\n            }\n            L=L.submat(indices, indices);\n          }\n        }\n        /**************************************************************************************************************/\n        void CurrentFlowGroupCloseness::greedy(count n_peripheral_merges){\n          count k_max;\n          node s;\n          node s_next;\n          node v;\n          double S_CFGCC;\n          double S_currentCFGCC;\n          double scaling_factor;\n          std::vector<bool> V;\n          std::vector<double> d;\n\n          k_max=S.size();\n          scaling_factor=(double)(n);\n          if(k_max>vList.size()){\n            k_max=vList.size()-1;\n            scaling_factor=(double)((G.upperNodeIdBound()))/(double)(k_max);\n          }\n          S_CFGCC=0.;\n          V.resize(vList.size(),true);\n          d.resize(G.upperNodeIdBound(),n*n);\n          for(count i=0;i<k_max;i++){\n            /*Maximal Gain Loop*/\n            for (count j=0; j<vList.size()-n_peripheral_merges;j++) {\n                //use vector of bools\n                if (V[j]){\n                    s=vList[j];\n                    /*Sample Loop*/\n                    S_currentCFGCC = 0.;\n                    for (count l = 0; l < vList.size(); l++) {\n                        v=vList[l];\n                        if (ERD.M(v,s)< d[v])\n                            S_currentCFGCC = S_currentCFGCC + ERD.M(v,s);\n                        else {\n                            S_currentCFGCC = S_currentCFGCC + d[v];\n                        }\n                    }\n                    S_currentCFGCC =  scaling_factor / S_currentCFGCC;\n                    if (S_currentCFGCC > S_CFGCC) {\n                        S_CFGCC = S_currentCFGCC;\n                        s_next = s;\n                    }\n                }\n            }\n            for(count j= 0; j<vList.size(); j++) {\n              v=vList[j];\n                if (ERD.M(v,s_next)< d[v]) {\n                    d[v] = ERD.M(v,s_next);\n                }\n            }\n            S[i]=s_next;\n            V[s_next]=false;\n        }\n        CFGCC=S_CFGCC;\n    }\n\n    void CurrentFlowGroupCloseness::computeInitialERD(count CB){\n      count ID;\n      count minDegree;\n\n      minDegree=1;\n      std::vector<std::pair<count,count>> c_indices;\n      std::vector<std::pair<node,node>> Matching;\n      ID=0;\n      c_indices.resize(0);\n\n      ERDLevel Level(ID,vList,Matching,TopMatch,Adj);\n      LevelList.push_back (Level);\n      /*update*/\n      minDegree=updateMinDegree(minDegree);\n\n      while(minDegree==1){\n        c_indices=peripheralCoarsingIndices();\n        Matching=updateMatching(c_indices);\n        coarseLaplacian(c_indices);\n        ID++;\n        Level.set(ID,vList,Matching,TopMatch,Adj);\n        LevelList.push_back (Level);\n        minDegree=updateMinDegree(minDegree);\n        TopMatch=updateTopMatch(minDegree);\n      }\n      /*\n      while(minDegree<CB){\n        c_indices=coarsingIndices(minDegree, false);\n        Matching=updateMatching(c_indices);\n        coarseLaplacian(c_indices);\n        ID++;\n        Level.set(ID,vList,Matching,TopMatch,Adj);\n        LevelList.push_back (Level);\n        minDegree=updateMinDegree(minDegree);\n        TopMatch=updateTopMatch(minDegree);\n      }\n      */\n    }\n    /***************************************************************************/\n    std::vector<std::vector<node>> CurrentFlowGroupCloseness::updateTopMatch(count minDegree){\n      bool search;\n      count j;\n\n      node v;\n      node w;\n      std::vector<std::vector<node>> update_List;\n      update_List.resize(G.upperNodeIdBound());\n      for(count i=0;i<vList.size();i++){\n        v=vList[i];\n        if(L(i,i)==minDegree){\n          search=true;\n          j=0;\n          while( (j<vList.size())&&(search)){\n            if((L(i,j)!=0) && (i!=j)){\n              w=vList[j];\n              update_List[v].push_back(w);\n              if(update_List[v].size()==minDegree){\n                search=false;\n              }\n            }\n            j++;\n          }\n        }\n      }\n      return update_List;\n    }\n    /***************************************************************************/\n    count CurrentFlowGroupCloseness::updateMinDegree(count minDegree){\n      bool search;\n      count min;\n      count i;\n\n      search=true;\n      min=n;\n      i=0;\n\n      while((i<L.n_rows)&&(search)){\n        if(L(i,i)<min){\n          min=L(i,i);\n          if(min==minDegree){\n            search=false;\n          }\n        }\n        i++;\n      }\n      if(min==0){\n        std::cout<<\"NETWORK_ERROR: min= \"<< min << \"\\n\\n\";\n      }\n      for(count i=0;i<L.n_rows;i++){\n        if(L(i,i)==0){\n          std::cout<<\"ERROR\\n\";\n        }\n      }\n      return min;\n    }\n    /***************************************************************************/\n    std::vector<std::pair<node,node>> CurrentFlowGroupCloseness::updateMatching(std::vector<std::pair<count,count>> indices){\n      std::vector<std::pair<node,node>> Matching;\n      Matching.resize(indices.size());\n        for(count i=0;i<Matching.size();i++){\n          Matching[i].first=vList[indices[i].first];\n          Matching[i].second=vList[indices[i].second];\n        }\n      return Matching;\n    }\n    /***************************************************************************/\n    std::vector<std::pair<count,count>> CurrentFlowGroupCloseness::peripheralCoarsingIndices(){\n      count v;\n      count s;\n\n      std::vector<std::pair<count,count>> indices;\n      std::vector<count> reverse;\n      reverse.resize(G.upperNodeIdBound());\n      for(count i=0;i<vList.size();i++){\n        reverse[vList[i]]=i;\n      }\n      indices.resize(0);\n      for(count i=0;i<L.n_rows;i++){\n        if(L(i,i)==1){\n          v=vList[i];\n          s=reverse[TopMatch[v][0]];\n          indices.push_back(std::make_pair(i,s));\n        }\n      }\n      return indices;\n    }\n    /***************************************************************************/\n    std::vector<std::pair<count,count>> CurrentFlowGroupCloseness::coarsingIndices(count cDegree, bool Random){\n        bool s_found;\n\n        count c_index;\n        count s_index;\n        count l;\n\n        node c;\n        /*free supernodes*/\n        std::vector<bool> s_List;\n        /*potential candidates*/\n        std::vector<count> c_List;\n        /*c_index-s_index mapping*/\n        std::vector<count> reverse;\n        reverse.resize(G.upperNodeIdBound());\n        for(count i=0;i<vList.size();i++){\n          reverse[vList[i]]=i;\n        }\n        std::vector<std::pair<count,count>> indices;\n\n        c_List.resize(0);\n        s_List.resize(G.upperNodeIdBound(),true);\n        /*potential candidates*/\n        for(count i=0;i<L.n_rows;i++){\n          if(L(i,i)==cDegree){\n            c_List.push_back(i);\n          }\n        }\n        if(Random){\n          std::random_shuffle (c_List.begin(), c_List.end());\n        }\n        for(count i=0;i<c_List.size();i++){\n          c_index=c_List[i];\n          c=vList[c_index];\n          if(s_List[c_index]){\n            s_found=false;\n            l=0;\n            while(!(s_found)&&(k<TopMatch[c].size())){\n              s_index=reverse[TopMatch[c][l]];\n              if(s_List[s_index]){\n                s_List[s_index]=false;\n                s_found=true;\n                indices.push_back(std::make_pair(c_index,s_index));\n              }\n              else{\n                l++;\n              }\n            }\n          }\n        }\n        return indices;\n      }\n    /***************************************************************************/\n    void CurrentFlowGroupCloseness::uncoarse(node s,node v,count ID){\n      node w;\n      std::vector<node> v_TopMatch;\n      arma::vec v_Adj;\n      arma::vec s_Adj;\n\n      v_TopMatch = LevelList[ID].get_vecofTopmatch(v);\n      v_Adj = LevelList[ID-1].get_CalofAdj(v);\n      s_Adj = LevelList[ID-1].get_CalofAdj(s);\n      ERD.firstJoin(vList,s,v,1.);\n      vList.push_back (v);\n      LevelList[ID].set_i_j_ofAdj(s,v,s_Adj(v));\n\n      for(count i=1;i<v_TopMatch.size();i++){\n        w=v_TopMatch[i];\n        if(v_Adj(w)!=0){\n          if(s_Adj(w)!=0){\n            ERD.edgeFire(vList,v,w,1.);\n            LevelList[ID].set_i_j_ofAdj(v,w,v_Adj(w));\n            LevelList[ID].set_i_j_ofAdj(v,w,s_Adj(w)-v_Adj(w));\n          }\n          else{\n            ERD.edgeFire(vList,v,w,1.);\n            LevelList[ID].set_i_j_ofAdj(v,w,v_Adj(w));\n            ERD.nonBridgeDelete(vList,s,w,1.);\n            LevelList[ID].set_i_j_ofAdj(v,w,0.);\n          }\n        }\n      }\n    }\n    /***************************************************************************/\n    count CurrentFlowGroupCloseness::mergePeripheralNodes(){\n      node s;\n      node v;\n      std::vector<std::pair<node,node>> merge;\n      std::vector<std::pair<node,node>> Matching;\n      std::vector<count> merge_value;\n\n      Matching=LevelList[1].get_Matching();\n      merge_value.resize(G.upperNodeIdBound(),0);\n      for(count i=0;i<Matching.size();i++){\n        v=Matching[i].first;\n        s=Matching[i].second;\n        merge_value[s]++;\n        if(merge_value[s]==1){\n          merge.push_back (std::make_pair(v,s));\n        }\n      }\n      for(count i=0;i<merge.size();i++){\n        v=merge[i].first;\n        s=merge[i].second;\n        ERD.firstJoin(vList,s,v,merge_value[s]);\n        LevelList[1].set_i_j_ofAdj(s,v,merge_value[s]);\n        vList.push_back (v);\n      }\n      return merge.size();\n    }\n    /***************************************************************************/\n    void CurrentFlowGroupCloseness::coarseLaplacian(std::vector<std::pair<count,count>> Matchings){\n      count a;\n      count l;\n      /*s=supernode - c = to be coarsed node - w = adjacent node to c*/\n      node s;\n      node c;\n      node w;\n\n      std::vector<count> reverse;\n      reverse.resize(G.upperNodeIdBound());\n      for(count i=0;i<vList.size();i++){\n        reverse[vList[i]]=i;\n      }\n      for(count i=0;i<Matchings.size();i++){\n        c=Matchings[i].first;\n        s=Matchings[i].second;\n        L(s,s)-=1;\n        for(count j=1;j<TopMatch[c].size();j++){\n          w=reverse[TopMatch[c][j]];\n          if(L(s,w)==0){\n            L(s,w)=-1.;\n            L(w,s)=-1.;\n            /*Diagonal*/\n            L(s,s)+=1.;\n          }\n          Adj(vList[s],vList[w])+=Adj(vList[c],vList[w]);\n          Adj(vList[w],vList[s])=Adj(vList[s],vList[w]);\n        }\n        Adj(vList[s],vList[c])=0;\n        Adj(vList[c],vList[s])=0;\n      }\n      arma::uvec indices(vList.size()-Matchings.size());\n      a=0;\n      l=0;\n      for(count i=0;i<vList.size();i++){\n        if(Matchings[l].first==i){\n          l++;\n        }\n        else{\n          indices(a)=i;\n          a++;\n        }\n      }\n      for(count i=0;i<Matchings.size();i++){\n        vList.erase(vList.begin()+Matchings[i].first-i);\n      }\n      L=L.submat(indices, indices);\n\n    }\n} /* namespace NetworKit*/\n", "meta": {"hexsha": "c3b198cb623a22057cd9c015a8ff079520303cc3", "size": 15237, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "networkit/cpp/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/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/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": 31.4814049587, "max_line_length": 159, "alphanum_fraction": 0.4710244799, "num_tokens": 3551, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.5428632831725053, "lm_q1q2_score": 0.46969838614769255}}
{"text": "// Boost.Geometry\n\n// Copyright (c) 2018-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_ARITHMETIC_LINE_FUNCTIONS_HPP\n#define BOOST_GEOMETRY_ARITHMETIC_LINE_FUNCTIONS_HPP\n\n#include <boost/geometry/core/access.hpp>\n#include <boost/geometry/core/config.hpp>\n#include <boost/geometry/geometries/infinite_line.hpp>\n#include <boost/geometry/util/math.hpp>\n#include <boost/geometry/util/select_most_precise.hpp>\n\nnamespace boost { namespace geometry\n{\n\nnamespace arithmetic\n{\n\n// Calculates intersection point of two infinite lines.\n// Returns true if the lines intersect.\n// Returns false if lines are parallel (or collinear, possibly opposite)\ntemplate <typename Point, typename Type>\ninline bool intersection_point(model::infinite_line<Type> const& p,\n    model::infinite_line<Type> const& q, Point& ip)\n{\n    Type const denominator = p.b * q.a - p.a * q.b;\n\n    static Type const zero = 0;\n    if (math::equals(denominator, zero))\n    {\n        // Lines are parallel\n        return false;\n    }\n\n    // Calculate the intersection coordinates\n    geometry::set<0>(ip, (p.c * q.b - p.b * q.c) / denominator);\n    geometry::set<1>(ip, (p.a * q.c - p.c * q.a) / denominator);\n\n    return true;\n}\n\n//! Return a distance-side-measure for a point to a line\n//! Point is located left of the line if value is positive,\n//! right of the line is value is negative, and on the line if the value\n//! is exactly zero\ntemplate <typename Type, typename CoordinateType>\ninline\ntypename select_most_precise<Type, CoordinateType>::type\nside_value(model::infinite_line<Type> const& line,\n    CoordinateType const& x, CoordinateType const& y)\n{\n    // https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line#Line_defined_by_an_equation\n    // Distance from point to line in general form is given as:\n    // (a * x + b * y + c) / sqrt(a * a + b * b);\n    // In most use cases comparisons are enough, saving the sqrt\n    // and often even the division.\n    // Also, this gives positive values for points left to the line,\n    // and negative values for points right to the line.\n    return line.a * x + line.b * y + line.c;\n}\n\ntemplate <typename Type, typename Point>\ninline\ntypename select_most_precise\n<\n    Type,\n    typename geometry::coordinate_type<Point>::type\n>::type\nside_value(model::infinite_line<Type> const& line, Point const& p)\n{\n    return side_value(line, geometry::get<0>(p), geometry::get<1>(p));\n}\n\n// Returns true for two lines which are supposed to be (close to) collinear\n// (which is not checked) and have a similar direction\n// (in practice up to 45 degrees, TO BE VERIFIED)\n// true: -----------------> p -----------------> q\n// false: -----------------> p <----------------- q\ntemplate <typename Type>\ninline\nbool similar_direction(const model::infinite_line<Type>& p,\n                       const model::infinite_line<Type>& q)\n{\n    return p.a * q.a >= 0 && p.b * q.b >= 0;\n}\n\ntemplate <typename Type>\ninline bool is_degenerate(const model::infinite_line<Type>& line)\n{\n    static Type const zero = 0;\n    return math::equals(line.a, zero) && math::equals(line.b, zero);\n}\n\n\n} // namespace arithmetic\n\n\n}} // namespace boost::geometry\n\n\n#endif // BOOST_GEOMETRY_ARITHMETIC_LINE_FUNCTIONS_HPP\n", "meta": {"hexsha": "0e82814831eaa111bc05ffca4d49e18488564c05", "size": 3415, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/geometry/arithmetic/infinite_line_functions.hpp", "max_stars_repo_name": "cpp-pm/boost", "max_stars_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2015-05-18T07:04:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-02T03:01:43.000Z", "max_issues_repo_path": "boost/geometry/arithmetic/infinite_line_functions.hpp", "max_issues_repo_name": "cpp-pm/boost", "max_issues_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_issues_repo_licenses": ["BSL-1.0"], "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": "boost/geometry/arithmetic/infinite_line_functions.hpp", "max_forks_repo_name": "cpp-pm/boost", "max_forks_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2015-06-06T07:16:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T13:45:56.000Z", "avg_line_length": 31.9158878505, "max_line_length": 96, "alphanum_fraction": 0.6954612006, "num_tokens": 842, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961425, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4696892160422466}}
{"text": "//==================================================================================================\n/*\n  EVE - Expressive Vector Engine\n  Copyright : EVE Contributors & Maintainers\n  SPDX-License-Identifier: MIT\n*/\n//==================================================================================================\n#include <cmath>\n#include <boost/math/special_functions/bessel.hpp>\n#include <eve/function/cyl_bessel_jn.hpp>\n#include <eve/constant/valmin.hpp>\n#include <eve/constant/valmax.hpp>\n#include \"producers.hpp\"\n#include <cmath>\n\nTTS_CASE_TPL(\"wide random check on cyl_bessel_jn\", EVE_TYPE)\n{\n  EVE_VALUE n;\n  eve::uniform_prng<EVE_VALUE> p(0, 12);\n\n  for(EVE_VALUE n=0; n < EVE_VALUE(5) ; n+= 0.25)\n  {\n    auto bjn = [n](auto x) -> EVE_VALUE {return boost::math::cyl_bessel_j(n, x); };\n    auto  jn = [n](auto x) -> EVE_VALUE {return eve::cyl_bessel_jn(n, x); };\n    TTS_RANGE_CHECK(p, bjn, jn);\n  }\n}\n", "meta": {"hexsha": "07b5f3e3abe0bb1765059eb3aa0a23468faa96cd", "size": 914, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/random/module/real/special/cyl_bessel_jn/regular/cyl_bessel_jn.hpp", "max_stars_repo_name": "the-moisrex/eve", "max_stars_repo_head_hexsha": "80b52663eefee11460abb0aedf4158a5067cf7dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 340.0, "max_stars_repo_stars_event_min_datetime": "2020-09-16T21:12:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T15:40:33.000Z", "max_issues_repo_path": "test/random/module/real/special/cyl_bessel_jn/regular/cyl_bessel_jn.hpp", "max_issues_repo_name": "the-moisrex/eve", "max_issues_repo_head_hexsha": "80b52663eefee11460abb0aedf4158a5067cf7dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 383.0, "max_issues_repo_issues_event_min_datetime": "2020-09-17T06:56:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T15:58:53.000Z", "max_forks_repo_path": "test/random/module/real/special/cyl_bessel_jn/regular/cyl_bessel_jn.hpp", "max_forks_repo_name": "the-moisrex/eve", "max_forks_repo_head_hexsha": "80b52663eefee11460abb0aedf4158a5067cf7dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 28.0, "max_forks_repo_forks_event_min_datetime": "2021-02-27T23:11:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T12:31:29.000Z", "avg_line_length": 32.6428571429, "max_line_length": 100, "alphanum_fraction": 0.5371991247, "num_tokens": 233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8354835371034369, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4696892114365}}
{"text": "#pragma once\n\n#include <random>\n#include <vector>\n\n#if USE_XSIMD\n#include <xsimd/xsimd.hpp>\nusing vec_type = std::vector<double, XSIMD_DEFAULT_ALLOCATOR(double)>;\n#elif USE_EIGEN\n#include <Eigen/Dense>\nusing vec_type = std::vector<double, Eigen::aligned_allocator<double>>;\n#else\nusing vec_type = std::vector<double>;\n#endif\n\nstd::vector<vec_type> generate_signal(size_t n_samples,\n    size_t in_size)\n{\n    std::vector<vec_type> signal(n_samples);\n    for(auto& x : signal)\n        x.resize(in_size, 0.0);\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 < n_samples; ++i)\n        for(size_t k = 0; k < in_size; ++k)\n            signal[i][k] = distribution(generator);\n\n    return std::move(signal);\n}\n", "meta": {"hexsha": "9ef7be136e5e5e3b318f03e4007998c148346596", "size": 790, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "bench/bench_utils.hpp", "max_stars_repo_name": "wayne-chen/RTNeural", "max_stars_repo_head_hexsha": "60812009e3a84d45baee4984ff65d656039645b6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bench/bench_utils.hpp", "max_issues_repo_name": "wayne-chen/RTNeural", "max_issues_repo_head_hexsha": "60812009e3a84d45baee4984ff65d656039645b6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bench/bench_utils.hpp", "max_forks_repo_name": "wayne-chen/RTNeural", "max_forks_repo_head_hexsha": "60812009e3a84d45baee4984ff65d656039645b6", "max_forks_repo_licenses": ["BSD-3-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.6875, "max_line_length": 71, "alphanum_fraction": 0.6860759494, "num_tokens": 214, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.46963681384607275}}
{"text": "#include <Eigen/Core>\n#include <cmath>\n#include <cstdlib>\n#include <ctime>\n#include <fstream>\n#include <iostream>\n#include <map>\n#include <sstream>\n#include <stdexcept>\n#include <vector>\n\nclass NameValuePair {\n  public:\n/** \n * @param fname File containing data.\n */\n    NameValuePair(const std::string& fname) {\n      std::string line;\n// open file for reading\n      std::ifstream file(fname.c_str());\n      if (!file)\n        throw std::runtime_error(\"NameValuePair::NameValuePair: Unable to open input file\");\n// loop over each line in file\n      while (std::getline(file, line)) {\n        unsigned commentLoc = line.find('#');\n        std::string myLine = line.substr(0, commentLoc);\n        if (myLine != \"\") {\n// only work on non-blank line: horribly ugly, but works\n          unsigned eqLoc = myLine.find('=');\n          std::string lhs, lhsStr, valueStr;\n          lhsStr = myLine.substr(0, eqLoc);\n          valueStr = myLine.substr(eqLoc+1, std::string::npos);\n          std::istringstream lhsToken(lhsStr);\n          lhsToken >> lhs;\n\n          double value;\n          std::istringstream tokens(valueStr);\n          tokens >> value;\n// insert it into map\n          nvmap[lhs] = value;\n        }\n      }\n    }\n\n/** \n * @param name Name to lookup\n * @return value associated with name\n */\n    double getValue(const std::string& name) const {\n      std::map<std::string, double>::const_iterator itr =\n        nvmap.find(name);\n      if (itr != nvmap.end())\n        return itr->second;\n      throw std::runtime_error(\"NameValuePair::getValue: not found\");\n    }\n\n/**\n * @param name Name to lookup\n * @return true if it exists, false otherwise\n */\n    bool hasValue(const std::string& name) const {\n      std::map<std::string, double>::const_iterator itr =\n        nvmap.find(name);\n      if (itr != nvmap.end())\n        return true;\n      return false;\n    }\n\n  private:\n    std::map<std::string, double> nvmap;\n};\n\n/** Store sim data */\nstruct QuadData {\n    int NDIM; /* Number of dimensions */\n    int Np, Nq; /* Number of basis, Number of quadrature points */\n    void show() {\n      std::cout << \"Np: \" << Np << \" Nq: \" << Nq << std::endl;\n    }\n};\n\nint cost(const QuadData& qd)\n{\n  int np = qd.Np, nq = qd.Nq, NDIM = qd.NDIM;\n  return np*nq + NDIM*(2*np*nq+nq);\n}\n\nvoid\nvol(int nloop, const QuadData& qd)\n{\n  int np = qd.Np, nq = qd.Nq;\n  int NDIM = qd.NDIM;\n  \n  Eigen::VectorXd f(np), alpha(np), result(np);\n  Eigen::VectorXd fQuad(nq), alphaQuad(nq);\n  Eigen::MatrixXd interpMatrix(nq, np);\n  Eigen::MatrixXd bigMatrix(np, nq);\n\n  f = Eigen::VectorXd::Random(np);\n  alpha = Eigen::VectorXd::Random(np);\n  interpMatrix = Eigen::MatrixXd::Random(nq, np);\n  bigMatrix = Eigen::MatrixXd::Random(np, nq);\n\n  for (unsigned n=0; n<nloop; ++n)\n  {\n// interpolate to quadrature nodes    \n    fQuad.noalias() = interpMatrix*f; // Np*Nq (do this only once)\n    for (unsigned d=0; d<NDIM; ++d)\n    {\n      alphaQuad.noalias() = interpMatrix*alpha; // Np*Nq\n      alphaQuad.cwiseProduct(fQuad); // Nq\n// compute updated solution\n      result.noalias() = bigMatrix*fQuad; // Np*Nq\n    }\n  }\n}\n\ndouble run(int nloop, const QuadData& qd)\n{\n  clock_t t1 = clock();\n  vol(nloop, qd);\n  clock_t t2 = clock();\n  return (double) (t2-t1)/CLOCKS_PER_SEC;\n}\n\nvoid printInfo(const QuadData& qd, double tm)\n{\n  std::cout << qd.NDIM << \" \" << qd.Np << \" \" << qd.Nq << \" \" << tm << std::endl;\n}\n\nvoid\nrunSimulation(const NameValuePair& nvpair)\n{\n  QuadData forceVolQuad, streamVolQuad;\n  forceVolQuad.Np = nvpair.getValue(\"NpVolForce\");\n  forceVolQuad.Nq = nvpair.getValue(\"NqVolForce\");\n  forceVolQuad.NDIM = nvpair.getValue(\"VDIM\");\n\n  streamVolQuad.Np = nvpair.getValue(\"NpVolStream\");\n  streamVolQuad.Nq = nvpair.getValue(\"NqVolStream\");\n  streamVolQuad.NDIM = nvpair.getValue(\"CDIM\");\n  \n  int nloop = nvpair.getValue(\"nloop\");\n\n  std::cout << std::endl;\n  std::cout << \"# Nloop  \" << nloop << std::endl;\n  \n  std::cout << \"# NDIM | Basis | Quadrature | Time (Force terms) \" << std::endl;\n// force terms\n  double tForce = run(nloop, forceVolQuad);\n  printInfo(forceVolQuad, tForce);\n\n  std::cout << \"# NDIM | Basis | Quadrature | Time (Streaming terms) \" << std::endl;\n// stream terms\n  double tStream = run(nloop, streamVolQuad);\n  printInfo(streamVolQuad, tStream);\n\n// stats\n  std::cout << std::endl;\n  std::cout << \"# Total time | Time per DOF \" << std::endl;  \n  double tm = (tForce+tStream)/nloop;\n  double tmPerDof = tm/forceVolQuad.Np;\n  std::cout << tm << \" \" << tmPerDof << std::endl;\n\n// cost\n  std::cout << std::endl;\n  std::cout << \"# Theoretical Cost (Arb. Units)\" << std::endl;\n  std::cout << \"Force vol. terms \" << cost(forceVolQuad) << std::endl;\n  std::cout << \"Streaming vol. terms \" << cost(streamVolQuad) << std::endl;  \n  std::cout << \"Net: \" << cost(forceVolQuad) + cost(streamVolQuad)  << std::endl;\n\n  std::cout << std::endl;  \n}\n\nint\nmain (int argc, char **argv)\n{\n  if (argc != 2) {\n    std::cout << \"Usage::\" << std::endl;\n    std::cout << \" dg-int <input-file>\" << std::endl;\n    std::cout << \"  input-file: Name of input file\" << std::endl;\n\n    exit(1);\n  }\n  std::string inFile(argv[1]); // input file\n  NameValuePair nvpair(inFile);\n  runSimulation(nvpair);\n\n  return 0;\n}\n", "meta": {"hexsha": "e84f046a1e13ae2f0142190be4e9f25b2ac983f9", "size": 5199, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "sims/code/dg-int/dg-int.cxx", "max_stars_repo_name": "ammarhakim/ammar-simjournal", "max_stars_repo_head_hexsha": "85b64ddc9556f01a4fab37977864a7d878eac637", "max_stars_repo_licenses": ["MIT", "Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-19T16:21:13.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-19T16:21:13.000Z", "max_issues_repo_path": "sims/code/dg-int/dg-int.cxx", "max_issues_repo_name": "ammarhakim/ammar-simjournal", "max_issues_repo_head_hexsha": "85b64ddc9556f01a4fab37977864a7d878eac637", "max_issues_repo_licenses": ["MIT", "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": "sims/code/dg-int/dg-int.cxx", "max_forks_repo_name": "ammarhakim/ammar-simjournal", "max_forks_repo_head_hexsha": "85b64ddc9556f01a4fab37977864a7d878eac637", "max_forks_repo_licenses": ["MIT", "Unlicense"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-01-08T06:23:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-08T07:06:50.000Z", "avg_line_length": 27.219895288, "max_line_length": 92, "alphanum_fraction": 0.6130025005, "num_tokens": 1515, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.6654105454764747, "lm_q1q2_score": 0.46963680036215455}}
{"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/*\n*\n*   Tutorial:  Iterative solvers in ViennaCL (iterative.cpp and iterative.cu are identical, the latter being required for compilation using CUDA nvcc)\n*\n*/\n\n//\n// include necessary system headers\n//\n#include <iostream>\n\n//\n// Necessary to obtain a suitable performance in ublas\n#ifndef NDEBUG\n #define NDEBUG\n#endif\n\n//\n// ublas includes\n//\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/triangular.hpp>\n#include <boost/numeric/ublas/matrix_sparse.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/operation_sparse.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n\n// Must be set if you want to use ViennaCL algorithms on ublas objects\n#define VIENNACL_WITH_UBLAS 1\n\n\n//\n// ViennaCL includes\n//\n#include \"viennacl/scalar.hpp\"\n#include \"viennacl/vector.hpp\"\n#include \"viennacl/compressed_matrix.hpp\"\n#include \"viennacl/coordinate_matrix.hpp\"\n#include \"viennacl/linalg/prod.hpp\"\n#include \"viennacl/linalg/ilu.hpp\"\n#include \"viennacl/linalg/jacobi_precond.hpp\"\n#include \"viennacl/linalg/cg.hpp\"\n#include \"viennacl/linalg/bicgstab.hpp\"\n#include \"viennacl/linalg/gmres.hpp\"\n#include \"viennacl/io/matrix_market.hpp\"\n\n\n// Some helper functions for this tutorial:\n#include \"Random.hpp\"\n#include \"vector-io.hpp\"\n\n\nusing namespace boost::numeric;\n\n\nint main()\n{\n  typedef float       ScalarType;\n\n  //\n  // Set up some ublas objects\n  //\n  ublas::vector<ScalarType> rhs;\n  ublas::vector<ScalarType> rhs2;\n  ublas::vector<ScalarType> ref_result;\n  ublas::vector<ScalarType> result;\n  ublas::compressed_matrix<ScalarType> ublas_matrix;\n\n  //\n  // Read system from file\n  //\n  if (!viennacl::io::read_matrix_market_file(ublas_matrix, \"../examples/testdata/mat65k.mtx\"))\n  {\n    std::cout << \"Error reading Matrix file\" << std::endl;\n    return 0;\n  }\n  //std::cout << \"done reading matrix\" << std::endl;\n\n  if (!readVectorFromFile(\"../examples/testdata/rhs65025.txt\", rhs))\n  {\n    std::cout << \"Error reading RHS file\" << std::endl;\n    return 0;\n  }\n  //std::cout << \"done reading rhs\" << std::endl;\n\n  if (!readVectorFromFile(\"../examples/testdata/result65025.txt\", ref_result))\n  {\n    std::cout << \"Error reading Result file\" << std::endl;\n    return 0;\n  }\n  //std::cout << \"done reading result\" << std::endl;\n\n  //\n  // Set up some ViennaCL objects\n  //\n  std::size_t vcl_size = rhs.size();\n  viennacl::compressed_matrix<ScalarType> vcl_compressed_matrix;\n  viennacl::coordinate_matrix<ScalarType> vcl_coordinate_matrix;\n  viennacl::vector<ScalarType> vcl_rhs(vcl_size);\n  viennacl::vector<ScalarType> vcl_result(vcl_size);\n  viennacl::vector<ScalarType> vcl_ref_result(vcl_size);\n\n  viennacl::copy(rhs.begin(), rhs.end(), vcl_rhs.begin());\n  viennacl::copy(ref_result.begin(), ref_result.end(), vcl_ref_result.begin());\n\n\n  //\n  // Transfer ublas-matrix to GPU:\n  //\n  viennacl::copy(ublas_matrix, vcl_compressed_matrix);\n\n  //\n  // alternative way: via STL. Sparse matrix as std::vector< std::map< unsigned int, ScalarType> >\n  //\n  std::vector< std::map< unsigned int, ScalarType> > stl_matrix(rhs.size());\n  for (ublas::compressed_matrix<ScalarType>::iterator1 iter1 = ublas_matrix.begin1();\n       iter1 != ublas_matrix.end1();\n       ++iter1)\n  {\n    for (ublas::compressed_matrix<ScalarType>::iterator2 iter2 = iter1.begin();\n         iter2 != iter1.end();\n         ++iter2)\n         stl_matrix[iter2.index1()][static_cast<unsigned int>(iter2.index2())] = *iter2;\n  }\n  viennacl::copy(stl_matrix, vcl_coordinate_matrix);\n  viennacl::copy(vcl_coordinate_matrix, stl_matrix);\n\n  //\n  // set up ILUT preconditioners for ublas and ViennaCL objects:\n  //\n  std::cout << \"Setting up preconditioners for uBLAS-matrix...\" << std::endl;\n  viennacl::linalg::ilut_precond< ublas::compressed_matrix<ScalarType> >    ublas_ilut(ublas_matrix, viennacl::linalg::ilut_tag());\n  viennacl::linalg::ilu0_precond< ublas::compressed_matrix<ScalarType> >    ublas_ilu0(ublas_matrix, viennacl::linalg::ilu0_tag());\n  viennacl::linalg::block_ilu_precond< ublas::compressed_matrix<ScalarType>,\n                                       viennacl::linalg::ilu0_tag>          ublas_block_ilu0(ublas_matrix, viennacl::linalg::ilu0_tag());\n\n  std::cout << \"Setting up preconditioners for ViennaCL-matrix...\" << std::endl;\n  viennacl::linalg::ilut_precond< viennacl::compressed_matrix<ScalarType> > vcl_ilut(vcl_compressed_matrix, viennacl::linalg::ilut_tag());\n  viennacl::linalg::ilu0_precond< viennacl::compressed_matrix<ScalarType> > vcl_ilu0(vcl_compressed_matrix, viennacl::linalg::ilu0_tag());\n  viennacl::linalg::block_ilu_precond< viennacl::compressed_matrix<ScalarType>,\n                                       viennacl::linalg::ilu0_tag>          vcl_block_ilu0(vcl_compressed_matrix, viennacl::linalg::ilu0_tag());\n\n  //\n  // set up Jacobi preconditioners for ViennaCL and ublas objects:\n  //\n  viennacl::linalg::jacobi_precond< ublas::compressed_matrix<ScalarType> >    ublas_jacobi(ublas_matrix, viennacl::linalg::jacobi_tag());\n  viennacl::linalg::jacobi_precond< viennacl::compressed_matrix<ScalarType> > vcl_jacobi(vcl_compressed_matrix, viennacl::linalg::jacobi_tag());\n\n  //\n  // Conjugate gradient solver:\n  //\n  std::cout << \"----- CG Test -----\" << std::endl;\n\n  //\n  // for ublas objects:\n  //\n  result = viennacl::linalg::solve(ublas_matrix, rhs, viennacl::linalg::cg_tag());\n  result = viennacl::linalg::solve(ublas_matrix, rhs, viennacl::linalg::cg_tag(1e-6, 20), ublas_ilut);\n  result = viennacl::linalg::solve(ublas_matrix, rhs, viennacl::linalg::cg_tag(1e-6, 20), ublas_jacobi);\n\n\n  //\n  // for ViennaCL objects:\n  //\n  vcl_result = viennacl::linalg::solve(vcl_compressed_matrix, vcl_rhs, viennacl::linalg::cg_tag());\n  vcl_result = viennacl::linalg::solve(vcl_compressed_matrix, vcl_rhs, viennacl::linalg::cg_tag(1e-6, 20), vcl_ilut);\n  vcl_result = viennacl::linalg::solve(vcl_compressed_matrix, vcl_rhs, viennacl::linalg::cg_tag(1e-6, 20), vcl_jacobi);\n\n  //\n  // Stabilized BiConjugate gradient solver:\n  //\n  std::cout << \"----- BiCGStab Test -----\" << std::endl;\n\n  //\n  // for ublas objects:\n  //\n  result = viennacl::linalg::solve(ublas_matrix, rhs, viennacl::linalg::bicgstab_tag());          //without preconditioner\n  result = viennacl::linalg::solve(ublas_matrix, rhs, viennacl::linalg::bicgstab_tag(1e-6, 20), ublas_ilut); //with preconditioner\n  result = viennacl::linalg::solve(ublas_matrix, rhs, viennacl::linalg::bicgstab_tag(1e-6, 20), ublas_jacobi); //with preconditioner\n\n\n  //\n  // for ViennaCL objects:\n  //\n  vcl_result = viennacl::linalg::solve(vcl_compressed_matrix, vcl_rhs, viennacl::linalg::bicgstab_tag());   //without preconditioner\n  vcl_result = viennacl::linalg::solve(vcl_compressed_matrix, vcl_rhs, viennacl::linalg::bicgstab_tag(1e-6, 20), vcl_ilut); //with preconditioner\n  vcl_result = viennacl::linalg::solve(vcl_compressed_matrix, vcl_rhs, viennacl::linalg::bicgstab_tag(1e-6, 20), vcl_jacobi); //with preconditioner\n\n  //\n  // GMRES solver:\n  //\n  std::cout << \"----- GMRES Test -----\" << std::endl;\n\n  //\n  // for ublas objects:\n  //\n  result = viennacl::linalg::solve(ublas_matrix, rhs, viennacl::linalg::gmres_tag());   //without preconditioner\n  result = viennacl::linalg::solve(ublas_matrix, rhs, viennacl::linalg::gmres_tag(1e-6, 20), ublas_ilut);//with preconditioner\n  result = viennacl::linalg::solve(ublas_matrix, rhs, viennacl::linalg::gmres_tag(1e-6, 20), ublas_jacobi);//with preconditioner\n\n  //\n  // for ViennaCL objects:\n  //\n  vcl_result = viennacl::linalg::solve(vcl_compressed_matrix, vcl_rhs, viennacl::linalg::gmres_tag());   //without preconditioner\n  vcl_result = viennacl::linalg::solve(vcl_compressed_matrix, vcl_rhs, viennacl::linalg::gmres_tag(1e-6, 20), vcl_ilut);//with preconditioner\n  vcl_result = viennacl::linalg::solve(vcl_compressed_matrix, vcl_rhs, viennacl::linalg::gmres_tag(1e-6, 20), vcl_jacobi);//with preconditioner\n\n  //\n  //  That's it.\n  //\n  std::cout << \"!!!! TUTORIAL COMPLETED SUCCESSFULLY !!!!\" << std::endl;\n\n  return 0;\n}\n\n", "meta": {"hexsha": "1efde9d11fed9a737a45524079848d944b104735", "size": 8856, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/tutorial/iterative.cpp", "max_stars_repo_name": "denis14/ViennaCL-1.5.2", "max_stars_repo_head_hexsha": "fec808905cca30196e10126681611bdf8da5297a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/tutorial/iterative.cpp", "max_issues_repo_name": "denis14/ViennaCL-1.5.2", "max_issues_repo_head_hexsha": "fec808905cca30196e10126681611bdf8da5297a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/tutorial/iterative.cpp", "max_forks_repo_name": "denis14/ViennaCL-1.5.2", "max_forks_repo_head_hexsha": "fec808905cca30196e10126681611bdf8da5297a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.5254237288, "max_line_length": 150, "alphanum_fraction": 0.6823622403, "num_tokens": 2574, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.46960959746625053}}
{"text": "#include <string>\n\n#include <ros/ros.h>\n#include <geometry_msgs/Quaternion.h>\n#include <rviz_visual_tools/rviz_visual_tools.h>\n#include <tf2_eigen/tf2_eigen.h>\n#include <tf2_ros/transform_listener.h>\n\n#include <Eigen/Geometry>\n#include <Eigen/SVD>\n\nnamespace\n{\n\nconstexpr auto pi {3.141592653589793};\n\n}\n\nint main(int argc, char** argv)\n{\n  ros::init(argc, argv, \"body_angle_visualizer\");\n  ros::NodeHandle n {};\n\n  int target_number {1};\n  std::string root_name {\"openni_coordinater\"};\n  std::string to_name {\"head\"};\n  std::string from_name {\"torso\"};\n  {\n    ros::NodeHandle pn {\"~\"};\n    pn.getParam(\"target_number\", target_number);\n    pn.getParam(\"root\", root_name);\n    pn.getParam(\"to\", to_name);\n    pn.getParam(\"from\", from_name);\n  }\n\n  const auto to_frame_name {to_name + '_' + std::to_string(target_number)};\n  const auto from_frame_name {from_name + '_' + std::to_string(target_number)};\n\n  ros::Publisher pub {n.advertise<geometry_msgs::Quaternion>(\"body_direction\", 1)};\n  ros::Rate r {5};\n  tf2_ros::Buffer tfBuffer {};\n  tf2_ros::TransformListener tfListener {tfBuffer};\n  rviz_visual_tools::RvizVisualTools rvt {root_name, \"rviz_visual_markers\"};\n\n  while (ros::ok()) {\n    try {\n      const auto to_pos {tf2::transformToEigen(tfBuffer.lookupTransform(root_name, to_frame_name, ros::Time{0}))};\n      const auto from_pos {tf2::transformToEigen(tfBuffer.lookupTransform(root_name, from_frame_name, ros::Time{0}))};\n      auto copy {from_pos};\n      copy.translation() = Eigen::Vector3d::Zero();\n      const auto from_ypr {copy.rotation().eulerAngles(2, 0, 1)};\n      ROS_INFO(\"yaw pitch roll : %f %f %f\", from_ypr(2), from_ypr(1), from_ypr(0));\n      constexpr auto trim_half_rotation {[](double angle) {\n        if (angle < -pi / 2)\n          return angle + pi;\n        if (angle > pi / 2)\n          return angle - pi;\n        return angle;\n      }};\n      const auto roll_angle {trim_half_rotation(from_ypr(0))};\n      constexpr auto invert_half_rotation {[](double angle) {\n        if (angle < -pi / 2)\n          return -angle - pi;\n        if (angle > pi / 2)\n          return -angle + pi;\n        return angle;\n      }};\n      const auto pitch_angle {invert_half_rotation(from_ypr(1))};\n      //const auto stand_vec {to_pos.translation() - from_pos.translation()};\n      //const auto stand_vec {from_pos * Eigen::Vector3d::UnitX()};\n      const auto stand_vec {copy * Eigen::Vector3d::UnitY()};\n      //const auto stand_quaternion {Eigen::Quaterniond::FromTwoVectors(Eigen::Vector3d::UnitX(), stand_vec)};\n      const auto stand_quaternion {copy.rotation()};\n\n      pub.publish(tf2::toMsg(Eigen::Quaterniond{from_pos.rotation()}));\n\n      rvt.deleteAllMarkers();\n      rvt.publishArrow(Eigen::Affine3d{stand_quaternion}, rviz_visual_tools::BLUE, rviz_visual_tools::LARGE);\n\n      Eigen::Affine3d text_pos {};\n      text_pos.translation() = stand_vec.normalized() * .5;\n      rvt.publishText(text_pos, std::to_string(roll_angle * 180 / pi), rviz_visual_tools::WHITE, rviz_visual_tools::XLARGE, false);\n      text_pos.translation() *= 1.1;\n      rvt.publishText(text_pos, std::to_string(pitch_angle * 180 / pi), rviz_visual_tools::WHITE, rviz_visual_tools::XLARGE, false);\n\n      rvt.trigger();\n    } catch (tf2::TransformException &e) {\n      ROS_WARN(\"%s\", e.what());\n    }\n\n    r.sleep();\n  }\n}\n", "meta": {"hexsha": "d81de58560486149c8021d4f15a35b7fef79127f", "size": 3319, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/body_angle_visualizer_node.cpp", "max_stars_repo_name": "forno/body_angle_visualizer", "max_stars_repo_head_hexsha": "0e0719fed7be007904e51399ecdf43a6f73fc8e1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-26T04:44:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-26T04:44:20.000Z", "max_issues_repo_path": "src/body_angle_visualizer_node.cpp", "max_issues_repo_name": "forno/body_angle_visualizer", "max_issues_repo_head_hexsha": "0e0719fed7be007904e51399ecdf43a6f73fc8e1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/body_angle_visualizer_node.cpp", "max_forks_repo_name": "forno/body_angle_visualizer", "max_forks_repo_head_hexsha": "0e0719fed7be007904e51399ecdf43a6f73fc8e1", "max_forks_repo_licenses": ["BSD-3-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.3085106383, "max_line_length": 132, "alphanum_fraction": 0.6649593251, "num_tokens": 891, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4696095908459453}}
{"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  InitializePose3.h\n *  @author Luca Carlone\n *  @author Frank Dellaert\n *  @date   August, 2014\n */\n\n#include <gtsam/slam/InitializePose3.h> \n#include <gtsam/slam/PriorFactor.h>\n#include <gtsam/slam/BetweenFactor.h>\n#include <gtsam/nonlinear/GaussNewtonOptimizer.h>\n#include <gtsam/inference/Symbol.h>\n#include <gtsam/geometry/Pose3.h>\n#include <gtsam/base/timing.h>\n\n#include <boost/math/special_functions.hpp>\n\nusing namespace std;\n\nnamespace gtsam {\n\nstatic const Key kAnchorKey = symbol('Z', 9999999);\n\n/* ************************************************************************* */\nGaussianFactorGraph InitializePose3::buildLinearOrientationGraph(const NonlinearFactorGraph& g) {\n\n  GaussianFactorGraph linearGraph;\n\n  for(const auto& factor: g) {\n    Matrix3 Rij;\n    double rotationPrecision = 1.0;\n\n    auto pose3Between = boost::dynamic_pointer_cast<BetweenFactor<Pose3> >(factor);\n    if (pose3Between){\n      Rij = pose3Between->measured().rotation().matrix();\n      Vector precisions = Vector::Zero(6);\n      precisions[0] = 1.0; // vector of all zeros except first entry equal to 1\n      pose3Between->noiseModel()->whitenInPlace(precisions); // gets marginal precision of first variable\n      rotationPrecision = precisions[0]; // rotations first\n    }else{\n      cout << \"Error in buildLinearOrientationGraph\" << endl;\n    }\n\n    const auto& keys = factor->keys();\n    Key key1 = keys[0], key2 = keys[1];\n    Matrix M9 = Z_9x9;\n    M9.block(0,0,3,3) = Rij;\n    M9.block(3,3,3,3) = Rij;\n    M9.block(6,6,3,3) = Rij;\n    linearGraph.add(key1, -I_9x9, key2, M9, Z_9x1, noiseModel::Isotropic::Precision(9, rotationPrecision));\n  }\n  // prior on the anchor orientation\n  linearGraph.add(\n      kAnchorKey, I_9x9,\n      (Vector(9) << 1.0, 0.0, 0.0, /*  */ 0.0, 1.0, 0.0, /*  */ 0.0, 0.0, 1.0)\n          .finished(),\n          noiseModel::Isotropic::Precision(9, 1));\n  return linearGraph;\n}\n\n/* ************************************************************************* */\n// Transform VectorValues into valid Rot3\nValues InitializePose3::normalizeRelaxedRotations(\n    const VectorValues& relaxedRot3) {\n  gttic(InitializePose3_computeOrientationsChordal);\n\n  Matrix ppm = Z_3x3; // plus plus minus\n  ppm(0,0) = 1; ppm(1,1) = 1; ppm(2,2) = -1;\n\n  Values validRot3;\n  for(const auto& it: relaxedRot3) {\n    Key key = it.first;\n    if (key != kAnchorKey) {\n      Matrix3 R;\n      R << Eigen::Map<const Matrix3>(it.second.data()); // Recover M from vectorized\n\n      // ClosestTo finds rotation matrix closest to H in Frobenius sense\n      // Rot3 initRot = Rot3::ClosestTo(M.transpose());\n\n      Matrix U, V; Vector s;\n      svd(R.transpose(), U, s, V);\n      Matrix3 normalizedRotMat = U * V.transpose();\n\n      if(normalizedRotMat.determinant() < 0)\n        normalizedRotMat = U * ppm * V.transpose();\n\n      Rot3 initRot = Rot3(normalizedRotMat);\n      validRot3.insert(key, initRot);\n    }\n  }\n  return validRot3;\n}\n\n/* ************************************************************************* */\nNonlinearFactorGraph InitializePose3::buildPose3graph(const NonlinearFactorGraph& graph) {\n  gttic(InitializePose3_buildPose3graph);\n  NonlinearFactorGraph pose3Graph;\n\n  for(const auto& factor: graph) {\n\n    // recast to a between on Pose3\n    const auto pose3Between = boost::dynamic_pointer_cast<BetweenFactor<Pose3> >(factor);\n    if (pose3Between)\n      pose3Graph.add(pose3Between);\n\n    // recast PriorFactor<Pose3> to BetweenFactor<Pose3>\n    const auto pose3Prior = boost::dynamic_pointer_cast<PriorFactor<Pose3> >(factor);\n    if (pose3Prior)\n      pose3Graph.emplace_shared<BetweenFactor<Pose3> >(kAnchorKey, pose3Prior->keys()[0],\n              pose3Prior->prior(), pose3Prior->noiseModel());\n  }\n  return pose3Graph;\n}\n\n/* ************************************************************************* */\nValues InitializePose3::computeOrientationsChordal(\n    const NonlinearFactorGraph& pose3Graph) {\n  gttic(InitializePose3_computeOrientationsChordal);\n\n  // regularize measurements and plug everything in a factor graph\n  GaussianFactorGraph relaxedGraph = buildLinearOrientationGraph(pose3Graph);\n\n  // Solve the LFG\n  VectorValues relaxedRot3 = relaxedGraph.optimize();\n\n  // normalize and compute Rot3\n  return normalizeRelaxedRotations(relaxedRot3);\n}\n\n/* ************************************************************************* */\nValues InitializePose3::computeOrientationsGradient(\n    const NonlinearFactorGraph& pose3Graph, const Values& givenGuess,\n    const size_t maxIter, const bool setRefFrame) {\n  gttic(InitializePose3_computeOrientationsGradient);\n\n  // this works on the inverse rotations, according to Tron&Vidal,2011\n  Values inverseRot;\n  inverseRot.insert(kAnchorKey, Rot3());\n  for(const auto& key_value: givenGuess) {\n    Key key = key_value.key;\n    const Pose3& pose = givenGuess.at<Pose3>(key);\n    inverseRot.insert(key, pose.rotation().inverse());\n  }\n\n  // Create the map of edges incident on each node\n  KeyVectorMap adjEdgesMap;\n  KeyRotMap factorId2RotMap;\n\n  createSymbolicGraph(adjEdgesMap, factorId2RotMap, pose3Graph);\n\n  // calculate max node degree & allocate gradient\n  size_t maxNodeDeg = 0;\n  VectorValues grad;\n  for(const auto& key_value: inverseRot) {\n    Key key = key_value.key;\n    grad.insert(key,Z_3x1);\n    size_t currNodeDeg = (adjEdgesMap.at(key)).size();\n    if(currNodeDeg > maxNodeDeg)\n      maxNodeDeg = currNodeDeg;\n  }\n\n  // Create parameters\n  double b = 1;\n  double f0 = 1/b - (1/b + M_PI) * exp(-b*M_PI);\n  double a = (M_PI*M_PI)/(2*f0);\n  double rho = 2*a*b;\n  double mu_max = maxNodeDeg * rho;\n  double stepsize = 2/mu_max; // = 1/(a b dG)\n\n  double maxGrad;\n  // gradient iterations\n  size_t it;\n  for (it = 0; it < maxIter; it++) {\n    //////////////////////////////////////////////////////////////////////////\n    // compute the gradient at each node\n    maxGrad = 0;\n    for (const auto& key_value : inverseRot) {\n      Key key = key_value.key;\n      Vector gradKey = Z_3x1;\n      // collect the gradient for each edge incident on key\n      for (const size_t& factorId : adjEdgesMap.at(key)) {\n        Rot3 Rij = factorId2RotMap.at(factorId);\n        Rot3 Ri = inverseRot.at<Rot3>(key);\n        auto factor = pose3Graph.at(factorId);\n        const auto& keys = factor->keys();\n        if (key == keys[0]) {\n          Key key1 = keys[1];\n          Rot3 Rj = inverseRot.at<Rot3>(key1);\n          gradKey = gradKey + gradientTron(Ri, Rij * Rj, a, b);\n        } else if (key == keys[1]) {\n          Key key0 = keys[0];\n          Rot3 Rj = inverseRot.at<Rot3>(key0);\n          gradKey = gradKey + gradientTron(Ri, Rij.between(Rj), a, b);\n        } else {\n          cout << \"Error in gradient computation\" << endl;\n        }\n      }  // end of i-th gradient computation\n      grad.at(key) = stepsize * gradKey;\n\n      double normGradKey = (gradKey).norm();\n      if(normGradKey>maxGrad)\n        maxGrad = normGradKey;\n    } // end of loop over nodes\n\n    //////////////////////////////////////////////////////////////////////////\n    // update estimates\n    inverseRot = inverseRot.retract(grad);\n\n    //////////////////////////////////////////////////////////////////////////\n    // check stopping condition\n    if (it>20 && maxGrad < 5e-3)\n      break;\n  } // enf of gradient iterations\n\n  // Return correct rotations\n  const Rot3& Rref = inverseRot.at<Rot3>(kAnchorKey); // This will be set to the identity as so far we included no prior\n  Values estimateRot;\n  for(const auto& key_value: inverseRot) {\n    Key key = key_value.key;\n    if (key != kAnchorKey) {\n      const Rot3& R = inverseRot.at<Rot3>(key);\n      if(setRefFrame)\n        estimateRot.insert(key, Rref.compose(R.inverse()));\n      else\n        estimateRot.insert(key, R.inverse());\n    }\n  }\n  return estimateRot;\n}\n\n/* ************************************************************************* */\nvoid InitializePose3::createSymbolicGraph(KeyVectorMap& adjEdgesMap, KeyRotMap& factorId2RotMap,\n                         const NonlinearFactorGraph& pose3Graph) {\n  size_t factorId = 0;\n  for(const auto& factor: pose3Graph) {\n    auto pose3Between = boost::dynamic_pointer_cast<BetweenFactor<Pose3> >(factor);\n    if (pose3Between){\n      Rot3 Rij = pose3Between->measured().rotation();\n      factorId2RotMap.insert(pair<Key, Rot3 >(factorId,Rij));\n\n      Key key1 = pose3Between->key1();\n      if (adjEdgesMap.find(key1) != adjEdgesMap.end()){  // key is already in\n        adjEdgesMap.at(key1).push_back(factorId);\n      }else{\n        vector<size_t> edge_id;\n        edge_id.push_back(factorId);\n        adjEdgesMap.insert(pair<Key, vector<size_t> >(key1, edge_id));\n      }\n      Key key2 = pose3Between->key2();\n      if (adjEdgesMap.find(key2) != adjEdgesMap.end()){  // key is already in\n        adjEdgesMap.at(key2).push_back(factorId);\n      }else{\n        vector<size_t> edge_id;\n        edge_id.push_back(factorId);\n        adjEdgesMap.insert(pair<Key, vector<size_t> >(key2, edge_id));\n      }\n    }else{\n      cout << \"Error in createSymbolicGraph\" << endl;\n    }\n    factorId++;\n  }\n}\n\n/* ************************************************************************* */\nVector3 InitializePose3::gradientTron(const Rot3& R1, const Rot3& R2, const double a, const double b) {\n  Vector3 logRot = Rot3::Logmap(R1.between(R2));\n\n  double th = logRot.norm();\n  if(th != th){ // the second case means that th = nan (logRot does not work well for +/-pi)\n    Rot3 R1pert = R1.compose( Rot3::Expmap(Vector3(0.01, 0.01, 0.01)) ); // some perturbation\n    logRot = Rot3::Logmap(R1pert.between(R2));\n    th = logRot.norm();\n  }\n  // exclude small or invalid rotations\n  if (th > 1e-5 && th == th) {  // nonzero valid rotations\n    logRot = logRot / th;\n  } else {\n    logRot = Z_3x1;\n    th = 0.0;\n  }\n\n  double fdot = a*b*th*exp(-b*th);\n  return fdot*logRot;\n}\n\n/* ************************************************************************* */\nValues InitializePose3::initializeOrientations(const NonlinearFactorGraph& graph) {\n  // We \"extract\" the Pose3 subgraph of the original graph: this\n  // is done to properly model priors and avoiding operating on a larger graph\n  NonlinearFactorGraph pose3Graph = buildPose3graph(graph);\n\n  // Get orientations from relative orientation measurements\n  return computeOrientationsChordal(pose3Graph);\n}\n\n///* ************************************************************************* */\nValues InitializePose3::computePoses(NonlinearFactorGraph& pose3graph,  Values& initialRot) {\n  gttic(InitializePose3_computePoses);\n\n  // put into Values structure\n  Values initialPose;\n  for (const auto& key_value : initialRot) {\n    Key key = key_value.key;\n    const Rot3& rot = initialRot.at<Rot3>(key);\n    Pose3 initializedPose = Pose3(rot, Point3(0, 0, 0));\n    initialPose.insert(key, initializedPose);\n  }\n\n  // add prior\n  noiseModel::Unit::shared_ptr priorModel = noiseModel::Unit::Create(6);\n  initialPose.insert(kAnchorKey, Pose3());\n  pose3graph.emplace_shared<PriorFactor<Pose3> >(kAnchorKey, Pose3(), priorModel);\n\n  // Create optimizer\n  GaussNewtonParams params;\n  bool singleIter = true;\n  if (singleIter) {\n    params.maxIterations = 1;\n  } else {\n    cout << \" \\n\\n\\n\\n  performing more than 1 GN iterations \\n\\n\\n\" << endl;\n    params.setVerbosity(\"TERMINATION\");\n  }\n  GaussNewtonOptimizer optimizer(pose3graph, initialPose, params);\n  Values GNresult = optimizer.optimize();\n\n  // put into Values structure\n  Values estimate;\n  for (const auto& key_value : GNresult) {\n    Key key = key_value.key;\n    if (key != kAnchorKey) {\n      const Pose3& pose = GNresult.at<Pose3>(key);\n      estimate.insert(key, pose);\n    }\n  }\n  return estimate;\n}\n\n/* ************************************************************************* */\nValues InitializePose3::initialize(const NonlinearFactorGraph& graph, const Values& givenGuess,\n                  bool useGradient) {\n  gttic(InitializePose3_initialize);\n  Values initialValues;\n\n  // We \"extract\" the Pose3 subgraph of the original graph: this\n  // is done to properly model priors and avoiding operating on a larger graph\n  NonlinearFactorGraph pose3Graph = buildPose3graph(graph);\n\n  // Get orientations from relative orientation measurements\n  Values orientations;\n  if (useGradient)\n    orientations = computeOrientationsGradient(pose3Graph, givenGuess);\n  else\n    orientations = computeOrientationsChordal(pose3Graph);\n\n  // Compute the full poses (1 GN iteration on full poses)\n  return computePoses(pose3Graph, orientations);\n}\n\n/* ************************************************************************* */\nValues InitializePose3::initialize(const NonlinearFactorGraph& graph) {\n  return initialize(graph, Values(), false);\n}\n\n} // namespace gtsam\n", "meta": {"hexsha": "a1baab5fa4acce2561b64287780394ec053f9083", "size": 13107, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/slam/InitializePose3.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/slam/InitializePose3.cpp", "max_issues_repo_name": "DEVESHTARASIA/gtsam", "max_issues_repo_head_hexsha": "e90e1f1dd2105b47df1d731ac82da28a6a9be454", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-10-04T18:53:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-04T18:53:24.000Z", "max_forks_repo_path": "gtsam/slam/InitializePose3.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": "2021-10-04T18:52:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-04T18:52:09.000Z", "avg_line_length": 34.8590425532, "max_line_length": 120, "alphanum_fraction": 0.613946746, "num_tokens": 3399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4696095908459453}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2007-2011 Barend Gehrels, Amsterdam, the Netherlands.\n// Copyright (c) 2008-2011 Bruno Lalande, Paris, France.\n// Copyright (c) 2009-2011 Mateusz Loskot, London, UK.\n\n// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library\n// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#include <algorithm>\n#include <ostream>\n#include <sstream>\n#include <string>\n#include <vector>\n\n#include <boost/config.hpp>\n#include <geometry_test_common.hpp>\n\n#include <boost/geometry/algorithms/correct.hpp>\n#include <boost/geometry/algorithms/within.hpp>\n#include <boost/geometry/algorithms/intersection_segment.hpp>\n#include <boost/geometry/io/wkt/aswkt.hpp>\n\nstatic std::ostream & operator<<(std::ostream &s, const bg::intersection_result& r)\n{\n    switch(r)\n    {\n        case bg::is_intersect_no : s << \"is_intersect_no\"; break;\n        case bg::is_intersect : s << \"is_intersect\"; break;\n        case bg::is_parallel : s << \"is_parallel\"; break;\n        case bg::is_collinear_no : s << \"is_collinear_no\"; break;\n        case bg::is_collinear_one : s << \"is_collinear_one\"; break;\n        case bg::is_collinear_connect : s << \"is_collinear_connect\"; break;\n        case bg::is_collinear_overlap : s << \"is_collinear_overlap\"; break;\n        case bg::is_collinear_overlap_opposite : s << \"is_collinear_overlap_opposite\"; break;\n        case bg::is_collinear_connect_opposite : s << \"is_collinear_connect_opposite\"; break;\n\n        // detailed connection results:\n        case bg::is_intersect_connect_s1p1 : s << \"is_intersect_connect_s1p1\"; break;\n        case bg::is_intersect_connect_s1p2 : s << \"is_intersect_connect_s1p2\"; break;\n        case bg::is_intersect_connect_s2p1 : s << \"is_intersect_connect_s2p1\"; break;\n        case bg::is_intersect_connect_s2p2 : s << \"is_intersect_connect_s2p2\"; break;\n    }\n    return s;\n}\n\nstatic std::string as_string(const bg::intersection_result& r)\n{\n    std::stringstream out;\n    out << r;\n    return out.str();\n}\n\ntypedef bg::model::point<double> P;\ntypedef bg::const_segment<P> S;\n\n\nstatic void test_intersection(double s1x1, double s1y1, double s1x2, double s1y2,\n                       double s2x1, double s2y1, double s2x2, double s2y2,\n                       // Expected results\n                       bg::intersection_result expected_result,\n                       int exptected_count, const P& exp_p1, const P& exp_p2)\n{\n    S s1(P(s1x1, s1y1), P(s1x2, s1y2));\n    S s2(P(s2x1, s2y1), P(s2x2, s2y2));\n    std::vector<P> ip;\n    double ra, rb;\n    bg::intersection_result r = bg::intersection_s(s1, s2, ra, rb, ip);\n    r = bg::intersection_connect_result(r, ra, rb);\n\n    BOOST_CHECK_EQUAL(ip.size(), exptected_count);\n    BOOST_CHECK_EQUAL(as_string(expected_result), as_string(r));\n\n    if (ip.size() == 2 && ip[0] != exp_p1)\n    {\n        // Swap results, second point is not as expected, swap results, order is not prescribed,\n        // it might be OK.\n        std::reverse(ip.begin(), ip.end());\n    }\n\n    if (ip.size() >= 1)\n    {\n        BOOST_CHECK_EQUAL(ip[0], exp_p1);\n    }\n    if (ip.size() >= 2)\n    {\n        BOOST_CHECK_EQUAL(ip[1], exp_p2);\n    }\n\n\n    /*\n    std::cout << exptected_count << \" \" << r;\n    if (exptected_count >= 1) std::cout << \" \" << ip[0];\n    if (exptected_count >= 2) std::cout << \" \" << ip[1];\n    std::cout << std::endl;\n    */\n}\n\n//BOOST_AUTO_TEST_CASE( test1 )\nint test_main( int , char* [] )\n{\n    // Identical cases\n    test_intersection(0,0, 1,1,  0,0, 1,1,          bg::is_collinear_overlap, 2,  P(0,0), P(1,1));\n    test_intersection(1,1, 0,0,  0,0, 1,1,          bg::is_collinear_overlap_opposite, 2,  P(1,1), P(0,0));\n    test_intersection(0,1, 0,2,  0,1, 0,2,          bg::is_collinear_overlap, 2,  P(0,1), P(0,2)); // Vertical\n    test_intersection(0,2, 0,1,  0,1, 0,2,          bg::is_collinear_overlap_opposite, 2,  P(0,2), P(0,1)); // Vertical\n    // Overlap cases\n    test_intersection(0,0, 1,1,  -0.5,-0.5, 2,2,    bg::is_collinear_overlap, 2,  P(0,0), P(1,1));\n    test_intersection(0,0, 1,1,  0.5,0.5, 1.5,1.5,  bg::is_collinear_overlap, 2,  P(0.5,0.5), P(1,1));\n    test_intersection(0,0, 0,1,  0,-10, 0,10,       bg::is_collinear_overlap, 2,  P(0,0), P(0,1)); // Vertical\n    test_intersection(0,0, 0,1,  0,10, 0,-10,       bg::is_collinear_overlap_opposite, 2,  P(0,0), P(0,1)); // Vertical\n    test_intersection(0,0, 1,1,  1,1, 2,2,          bg::is_collinear_connect, 1,  P(1,1), P(0,0)); // Single point\n    // Colinear, non overlap cases\n    test_intersection(0,0, 1,1,  1.5,1.5, 2.5,2.5,  bg::is_collinear_no, 0,  P(0,0), P(0,0));\n    test_intersection(0,0, 0,1,  0,5, 0,6,          bg::is_collinear_no, 0,  P(0,0), P(0,0)); // Vertical\n    // Parallel cases\n    test_intersection(0,0, 1,1,  1,0, 2,1,       bg::is_parallel, 0,  P(0,0), P(0,1));\n    // Intersect cases\n    test_intersection(0,2, 4,2,  3,0, 3,4,       bg::is_intersect, 1,  P(3,2), P(0,0));\n    // Non intersect cases\n\n    // Single point cases\n    test_intersection(0,0, 0,0,  1,1, 2,2,          bg::is_collinear_no, 0,  P(1,1), P(0,0)); // Colinear/no\n    test_intersection(2,2, 2,2,  1,1, 3,3,          bg::is_collinear_one, 1,  P(2,2.01), P(0,0)); // On segment\n    test_intersection(1,1, 3,3,  2,2, 2,2,          bg::is_collinear_one, 1,  P(2,2), P(0,0)); // On segment\n    test_intersection(1,1, 3,3,  1,1, 1,1,          bg::is_collinear_one, 1,  P(1,1), P(0,0)); // On segment, start\n    test_intersection(1,1, 3,3,  3,3, 3,3,          bg::is_collinear_one, 1,  P(3,3), P(0,0)); // On segment, end\n\n    return 0;\n}\n", "meta": {"hexsha": "c19d2e5988897114d264ec3e75d96187820a9435", "size": 5794, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/test/algorithms/intersection_segment.cpp", "max_stars_repo_name": "olegshnitko/libboost", "max_stars_repo_head_hexsha": "548eb6365af3724d8f4b47ebbabf7eb3ad8e66a8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-10-31T00:40:22.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-31T00:40:22.000Z", "max_issues_repo_path": "libs/geometry/test/algorithms/intersection_segment.cpp", "max_issues_repo_name": "olegshnitko/libboost", "max_issues_repo_head_hexsha": "548eb6365af3724d8f4b47ebbabf7eb3ad8e66a8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-01-17T10:11:43.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-17T10:11:43.000Z", "max_forks_repo_path": "libs/geometry/test/algorithms/intersection_segment.cpp", "max_forks_repo_name": "olegshnitko/libboost", "max_forks_repo_head_hexsha": "548eb6365af3724d8f4b47ebbabf7eb3ad8e66a8", "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.9185185185, "max_line_length": 119, "alphanum_fraction": 0.6211598205, "num_tokens": 2011, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4696095908459453}}
{"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_REM_PIO2_STRAIGHT_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_REM_PIO2_STRAIGHT_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 Computes the remainder modulo \\f$\\pi/2\\f$.\n\n\n\n    @par Header <boost/simd/function/rem_pio2_straight.hpp>\n\n    @par Notes\n\n    - @c rem_pio2_straight computes the remainder modulo \\f$\\pi/2\\f$ with \"straight\" algorithm,\n    and returns an angle quadrant which is always 1.\n    This is a very quick version only correct if the input\n    is in \\f$[\\pi/4,\\pi/2]\\f$.\n\n    - In fact it only substracts \\f$\\pi/2\\f$ to the input\n    so it can be viewed as a specially accurate minuspio_2 function outside\n    the interval in which it can be used as a substitute to @ref rem_pio2.\n\n    - The reduction of the argument modulo \\f$\\pi/2\\f$ is generally\n    the most difficult part of trigonometric evaluations.\n    The accurate algorithm over the whole floating point range\n    is over costly and implies the knowledge\n    of a few hundred \\f$\\pi\\f$ decimals\n    some simpler algorithms as this one\n    can be used, but the precision is only insured on specific intervals.\n\n    @see rem_pio2, rem_pio2_medium,rem_2pi, rem_pio2_cephes,\n\n\n    @par Example:\n\n      @snippet rem_pio2_straight.cpp rem_pio2_straight\n\n    @par Possible output:\n\n      @snippet rem_pio2_straight.txt rem_pio2_straight\n\n  **/\n  std::pair<IEEEValue, IEEEValue> rem_pio2_straight(IEEEValue const& x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/rem_pio2_straight.hpp>\n#include <boost/simd/function/simd/rem_pio2_straight.hpp>\n\n#endif\n", "meta": {"hexsha": "496fd05ff12a3f56242ae4414384459e7a0b2719", "size": 2051, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/rem_pio2_straight.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/rem_pio2_straight.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/rem_pio2_straight.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": 31.5538461538, "max_line_length": 100, "alphanum_fraction": 0.6674792784, "num_tokens": 506, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4696095908459453}}
{"text": "\r\n// Copyright 2017 Peter Dimov.\r\n//\r\n// Distributed under the Boost Software License, Version 1.0.\r\n//\r\n// See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt\r\n\r\n\r\n#include <boost/mp11/function.hpp>\r\n#include <boost/mp11/integral.hpp>\r\n#include <boost/core/lightweight_test_trait.hpp>\r\n#include <type_traits>\r\n\r\nint main()\r\n{\r\n    using boost::mp11::mp_max;\r\n    using boost::mp11::mp_int;\r\n    using boost::mp11::mp_size_t;\r\n\r\n    BOOST_TEST_TRAIT_TRUE((std::is_same<mp_max<mp_int<1>>, mp_int<1>>));\r\n    BOOST_TEST_TRAIT_TRUE((std::is_same<mp_max<mp_int<2>, mp_int<1>, mp_int<2>, mp_int<3>>, mp_int<3>>));\r\n    BOOST_TEST_TRAIT_TRUE((std::is_same<mp_max<mp_int<-1>, mp_size_t<1>, mp_int<-2>, mp_size_t<2>>, mp_size_t<2>>));\r\n\r\n    return boost::report_errors();\r\n}\r\n", "meta": {"hexsha": "a9aff2ed5dc70be6d0028943436ffa002d3151f1", "size": 807, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/mp11/test/mp_max.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": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/mp11/test/mp_max.cpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-04T18:00:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-04T18:00:00.000Z", "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/mp11/test/mp_max.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 29.8888888889, "max_line_length": 117, "alphanum_fraction": 0.6840148699, "num_tokens": 239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4696095908459453}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2016-2017, Oracle and/or its affiliates.\n\n// Contributed and/or modified by Vissarion Fysikopoulos, 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_DISTANCE_CROSS_TRACK_HPP\n#define BOOST_GEOMETRY_STRATEGIES_GEOGRAPHIC_DISTANCE_CROSS_TRACK_HPP\n\n#include <algorithm>\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/cs.hpp>\n#include <boost/geometry/core/access.hpp>\n#include <boost/geometry/core/radian_access.hpp>\n#include <boost/geometry/core/tags.hpp>\n\n#include <boost/geometry/strategies/distance.hpp>\n#include <boost/geometry/strategies/concepts/distance_concept.hpp>\n#include <boost/geometry/strategies/spherical/distance_haversine.hpp>\n#include <boost/geometry/strategies/geographic/azimuth.hpp>\n#include <boost/geometry/strategies/geographic/parameters.hpp>\n\n#include <boost/geometry/formulas/vincenty_direct.hpp>\n\n#include <boost/geometry/util/math.hpp>\n#include <boost/geometry/util/promote_floating_point.hpp>\n#include <boost/geometry/util/select_calculation_type.hpp>\n#include <boost/geometry/util/normalize_spheroidal_coordinates.hpp>\n\n#include <boost/geometry/formulas/result_direct.hpp>\n#include <boost/geometry/formulas/mean_radius.hpp>\n\n#ifdef BOOST_GEOMETRY_DEBUG_GEOGRAPHIC_CROSS_TRACK\n#include <boost/geometry/io/dsv/write.hpp>\n#endif\n\n#ifndef BOOST_GEOMETRY_DETAIL_POINT_SEGMENT_DISTANCE_MAX_STEPS\n#define BOOST_GEOMETRY_DETAIL_POINT_SEGMENT_DISTANCE_MAX_STEPS 100\n#endif\n\n#ifdef BOOST_GEOMETRY_DEBUG_GEOGRAPHIC_CROSS_TRACK\n#include <iostream>\n#endif\n\nnamespace boost { namespace geometry\n{\n\nnamespace strategy { namespace distance\n{\n\n/*!\n\\brief Strategy functor for distance point to segment calculation on ellipsoid\n       Algorithm uses direct and inverse geodesic problems as subroutines.\n       The algorithm approximates the distance by an iterative Newton method.\n\\ingroup strategies\n\\details Class which calculates the distance of a point to a segment, for points\non the ellipsoid\n\\see C.F.F.Karney - Geodesics on an ellipsoid of revolution,\n      https://arxiv.org/abs/1102.1215\n\\tparam FormulaPolicy underlying point-point distance strategy\n\\tparam Spheroid is the spheroidal model used\n\\tparam CalculationType \\tparam_calculation\n\\tparam EnableClosestPoint computes the closest point on segment if true\n*/\ntemplate\n<\n    typename FormulaPolicy = strategy::andoyer,\n    typename Spheroid = srs::spheroid<double>,\n    typename CalculationType = void,\n    bool EnableClosestPoint = false\n>\nclass geographic_cross_track\n{\npublic :\n    template <typename Point, typename PointOfSegment>\n    struct return_type\n        : promote_floating_point\n          <\n              typename select_calculation_type\n                  <\n                      Point,\n                      PointOfSegment,\n                      CalculationType\n                  >::type\n          >\n    {};\n\n    struct distance_strategy\n    {\n        typedef geographic<FormulaPolicy, Spheroid, CalculationType> type;\n    };\n\n    inline typename distance_strategy::type get_distance_strategy() const\n    {\n        typedef typename distance_strategy::type distance_type;\n        return distance_type(m_spheroid);\n    }\n\n    explicit geographic_cross_track(Spheroid const& spheroid = Spheroid())\n        : m_spheroid(spheroid)\n    {}\n\n    template <typename Point, typename PointOfSegment>\n    inline typename return_type<Point, PointOfSegment>::type\n    apply(Point const& p, PointOfSegment const& sp1, PointOfSegment const& sp2) const\n    {\n        typedef typename coordinate_system<Point>::type::units units_type;\n\n        return (apply<units_type>(get<0>(sp1), get<1>(sp1),\n                                  get<0>(sp2), get<1>(sp2),\n                                  get<0>(p), get<1>(p),\n                                  m_spheroid)).distance;\n    }\n\nprivate :\n\n    template <typename CT>\n    struct result_distance_point_segment\n    {\n        result_distance_point_segment()\n            : distance(0)\n            , closest_point_lon(0)\n            , closest_point_lat(0)\n        {}\n\n        CT distance;\n        CT closest_point_lon;\n        CT closest_point_lat;\n    };\n\n    template <typename CT>\n    result_distance_point_segment<CT>\n    static inline non_iterative_case(CT lon, CT lat, CT distance)\n    {\n        result_distance_point_segment<CT> result;\n        result.distance = distance;\n\n        if (EnableClosestPoint)\n        {\n            result.closest_point_lon = lon;\n            result.closest_point_lat = lat;\n        }\n        return result;\n    }\n\n    template <typename CT>\n    result_distance_point_segment<CT>\n    static inline non_iterative_case(CT lon1, CT lat1, //p1\n                                     CT lon2, CT lat2, //p2\n                                     Spheroid const& spheroid)\n    {\n        CT distance = geometry::strategy::distance::geographic<FormulaPolicy, Spheroid, CT>\n                              ::apply(lon1, lat1, lon2, lat2, spheroid);\n\n        return non_iterative_case(lon1, lat1, distance);\n    }\n\n    template <typename CT>\n    CT static inline normalize(CT g4, CT& der)\n    {\n        CT const pi = math::pi<CT>();\n        if (g4 < -1.25*pi)//close to -270\n        {\n#ifdef BOOST_GEOMETRY_DEBUG_GEOGRAPHIC_CROSS_TRACK\n            std::cout << \"g4=\" << g4 <<  \", close to -270\" << std::endl;\n#endif\n            return g4 + 1.5 * pi;\n        }\n        else if (g4 > 1.25*pi)//close to 270\n        {\n#ifdef BOOST_GEOMETRY_DEBUG_GEOGRAPHIC_CROSS_TRACK\n            std::cout << \"g4=\" << g4 <<  \", close to 270\" << std::endl;\n#endif\n            return - g4 + 1.5 * pi;\n        }\n        else if (g4 < 0 && g4 > -0.75*pi)//close to -90\n        {\n#ifdef BOOST_GEOMETRY_DEBUG_GEOGRAPHIC_CROSS_TRACK\n            std::cout << \"g4=\" << g4 <<  \", close to -90\" << std::endl;\n#endif\n            der = -der;\n            return -g4 - pi/2;\n        }\n        return g4 - pi/2;\n    }\n\n    template <typename Units, typename CT>\n    result_distance_point_segment<CT>\n    static inline apply(CT lon1, CT lat1, //p1\n                        CT lon2, CT lat2, //p2\n                        CT lon3, CT lat3, //query point p3\n                        Spheroid const& spheroid)\n    {\n        typedef typename FormulaPolicy::template inverse<CT, true, false, false, true, true>\n                inverse_distance_quantities_type;\n        typedef typename FormulaPolicy::template inverse<CT, false, true, false, false, false>\n                inverse_azimuth_type;\n        typedef typename FormulaPolicy::template inverse<CT, false, true, true, false, false>\n                inverse_azimuth_reverse_type;\n        typedef typename FormulaPolicy::template direct<CT, true, false, false, false>\n                direct_distance_type;\n\n        CT const earth_radius = geometry::formula::mean_radius<CT>(spheroid);\n\n        result_distance_point_segment<CT> result;\n\n        // Constants\n        //CT const f = geometry::formula::flattening<CT>(spheroid);\n        CT const pi = math::pi<CT>();\n        CT const half_pi = pi / CT(2);\n        CT const c0 = CT(0);\n\n        // Convert to radians\n        lon1 = math::as_radian<Units>(lon1);\n        lat1 = math::as_radian<Units>(lat1);\n        lon2 = math::as_radian<Units>(lon2);\n        lat2 = math::as_radian<Units>(lat2);\n        lon3 = math::as_radian<Units>(lon3);\n        lat3 = math::as_radian<Units>(lat3);\n\n        if (lon1 > lon2)\n        {\n            std::swap(lon1, lon2);\n            std::swap(lat1, lat2);\n        }\n\n        //segment on equator\n        //Note: antipodal points on equator does not define segment on equator\n        //but pass by the pole\n        CT diff = geometry::math::longitude_distance_signed<geometry::radian>(lon1, lon2);\n\n        typedef typename formula::elliptic_arc_length<CT> elliptic_arc_length;\n\n        bool meridian_not_crossing_pole =\n              elliptic_arc_length::meridian_not_crossing_pole(lat1, lat2, diff);\n\n        bool meridian_crossing_pole =\n              elliptic_arc_length::meridian_crossing_pole(diff);\n\n        //bool meridian_crossing_pole = math::equals(math::abs(diff), pi);\n        //bool meridian_not_crossing_pole = math::equals(math::abs(diff), c0);\n\n        if (math::equals(lat1, c0) && math::equals(lat2, c0) && !meridian_crossing_pole)\n        {\n#ifdef BOOST_GEOMETRY_DEBUG_GEOGRAPHIC_CROSS_TRACK\n            std::cout << \"Equatorial segment\" << std::endl;\n            std::cout << \"segment=(\" << lon1 * math::r2d<CT>();\n            std::cout << \",\" << lat1 * math::r2d<CT>();\n            std::cout << \"),(\" << lon2 * math::r2d<CT>();\n            std::cout << \",\" << lat2 * math::r2d<CT>();\n            std::cout << \")\\np=(\" << lon3 * math::r2d<CT>();\n            std::cout << \",\" << lat3 * math::r2d<CT>() << \")\\n\";\n#endif\n            if (lon3 <= lon1)\n            {\n                return non_iterative_case(lon1, lat1, lon3, lat3, spheroid);\n            }\n            if (lon3 >= lon2)\n            {\n                return non_iterative_case(lon2, lat2, lon3, lat3, spheroid);\n            }\n            return non_iterative_case(lon3, lat1, lon3, lat3, spheroid);\n        }\n\n        if ( (meridian_not_crossing_pole || meridian_crossing_pole ) && lat1 > lat2)\n        {\n            std::swap(lat1,lat2);\n        }\n\n        if (meridian_crossing_pole)\n        {\n#ifdef BOOST_GEOMETRY_DEBUG_GEOGRAPHIC_CROSS_TRACK\n            std::cout << \"Meridian segment\" << std::endl;\n#endif\n            result_distance_point_segment<CT> d1 = apply<geometry::radian>(lon1, lat1, lon1, half_pi, lon3, lat3, spheroid);\n            result_distance_point_segment<CT> d2 = apply<geometry::radian>(lon2, lat2, lon2, half_pi, lon3, lat3, spheroid);\n            if (d1.distance < d2.distance)\n            {\n                return d1;\n            }\n            else\n            {\n                return d2;\n            }\n        }\n\n        CT d1 = geometry::strategy::distance::geographic<FormulaPolicy, Spheroid, CT>\n                ::apply(lon1, lat1, lon3, lat3, spheroid);\n\n        CT d3 = geometry::strategy::distance::geographic<FormulaPolicy, Spheroid, CT>\n                ::apply(lon1, lat1, lon2, lat2, spheroid);\n\n        if (geometry::math::equals(d3, c0))\n        {\n#ifdef BOOST_GEOMETRY_DEBUG_GEOGRAPHIC_CROSS_TRACK\n            std::cout << \"Degenerate segment\" << std::endl;\n            std::cout << \"distance between points=\" << d1 << std::endl;\n#endif\n            return non_iterative_case(lon1, lat2, d1);\n        }\n\n        CT d2 = geometry::strategy::distance::geographic<FormulaPolicy, Spheroid, CT>\n                ::apply(lon2, lat2, lon3, lat3, spheroid);\n\n        // Compute a12 (GEO)\n        geometry::formula::result_inverse<CT> res12 =\n                inverse_azimuth_reverse_type::apply(lon1, lat1, lon2, lat2, spheroid);\n        CT a12 = res12.azimuth;\n        CT a13 = inverse_azimuth_type::apply(lon1, lat1, lon3, lat3, spheroid).azimuth;\n\n        CT a312 = a13 - a12;\n\n        if (geometry::math::equals(a312, c0))\n        {\n#ifdef BOOST_GEOMETRY_DEBUG_GEOGRAPHIC_CROSS_TRACK\n            std::cout << \"point on segment\" << std::endl;\n#endif\n            return non_iterative_case(lon3, lat3, c0);\n        }\n\n        CT projection1 = cos( a312 ) * d1 / d3;\n\n#ifdef BOOST_GEOMETRY_DEBUG_GEOGRAPHIC_CROSS_TRACK\n        std::cout << \"segment=(\" << lon1 * math::r2d<CT>();\n        std::cout << \",\" << lat1 * math::r2d<CT>();\n        std::cout << \"),(\" << lon2 * math::r2d<CT>();\n        std::cout << \",\" << lat2 * math::r2d<CT>();\n        std::cout << \")\\np=(\" << lon3 * math::r2d<CT>();\n        std::cout << \",\" << lat3 * math::r2d<CT>();\n        std::cout << \")\\na1=\" << a12 * math::r2d<CT>() << std::endl;\n        std::cout << \"a13=\" << a13 * math::r2d<CT>() << std::endl;\n        std::cout << \"a312=\" << a312 * math::r2d<CT>() << std::endl;\n        std::cout << \"cos(a312)=\" << cos(a312) << std::endl;\n#endif\n        if (projection1 < 0.0)\n        {\n#ifdef BOOST_GEOMETRY_DEBUG_GEOGRAPHIC_CROSS_TRACK\n            std::cout << \"projection closer to p1\" << std::endl;\n#endif\n            // projection of p3 on geodesic spanned by segment (p1,p2) fall\n            // outside of segment on the side of p1\n            return non_iterative_case(lon1, lat1, lon3, lat3, spheroid);\n        }\n\n        CT a21 = res12.reverse_azimuth - pi;\n        CT a23 = inverse_azimuth_type::apply(lon2, lat2, lon3, lat3, spheroid).azimuth;\n\n        CT a321 = a23 - a21;\n\n#ifdef BOOST_GEOMETRY_DEBUG_GEOGRAPHIC_CROSS_TRACK\n        std::cout << \"a21=\" << a21 * math::r2d<CT>() << std::endl;\n        std::cout << \"a23=\" << a23 * math::r2d<CT>() << std::endl;\n        std::cout << \"a321=\" << a321 * math::r2d<CT>() << std::endl;\n        std::cout << \"cos(a321)=\" << cos(a321) << std::endl;\n#endif\n        CT projection2 = cos( a321 ) * d2 / d3;\n\n        if (projection2 < 0.0)\n        {\n#ifdef BOOST_GEOMETRY_DEBUG_GEOGRAPHIC_CROSS_TRACK\n            std::cout << \"projection closer to p2\" << std::endl;\n#endif\n            // projection of p3 on geodesic spanned by segment (p1,p2) fall\n            // outside of segment on the side of p2\n            return non_iterative_case(lon2, lat2, lon3, lat3, spheroid);\n        }\n\n        // Guess s14 (SPHERICAL)\n        typedef geometry::model::point\n                <\n                    CT, 2,\n                    geometry::cs::spherical_equatorial<geometry::radian>\n                > point;\n\n        point p1 = point(lon1, lat1);\n        point p2 = point(lon2, lat2);\n        point p3 = point(lon3, lat3);\n\n        geometry::strategy::distance::cross_track<CT> cross_track(earth_radius);\n        CT s34 = cross_track.apply(p3, p1, p2);\n\n        geometry::strategy::distance::haversine<CT> str(earth_radius);\n        CT s13 = str.apply(p1, p3);\n        CT s14 = acos( cos(s13/earth_radius) / cos(s34/earth_radius) ) * earth_radius;\n\n#ifdef BOOST_GEOMETRY_DEBUG_GEOGRAPHIC_CROSS_TRACK\n        std::cout << \"s34=\" << s34 << std::endl;\n        std::cout << \"s13=\" << s13 << std::endl;\n        std::cout << \"s14=\" << s14 << std::endl;\n        std::cout << \"===============\" << std::endl;\n#endif\n\n        // Update s14 (using Newton method)\n        CT prev_distance = 0;\n        geometry::formula::result_direct<CT> res14;\n        geometry::formula::result_inverse<CT> res34;\n\n        int counter = 0; // robustness\n        CT g4;\n        CT delta_g4;\n\n        do{\n            prev_distance = res34.distance;\n\n            // Solve the direct problem to find p4 (GEO)\n            res14 = direct_distance_type::apply(lon1, lat1, s14, a12, spheroid);\n\n            // Solve an inverse problem to find g4\n            // g4 is the angle between segment (p1,p2) and segment (p3,p4) that meet on p4 (GEO)\n\n            CT a4 = inverse_azimuth_type::apply(res14.lon2, res14.lat2,\n                                                lon2, lat2, spheroid).azimuth;\n            res34 = inverse_distance_quantities_type::apply(res14.lon2, res14.lat2,\n                                                            lon3, lat3, spheroid);\n            g4 = res34.azimuth - a4;\n\n\n\n            CT M43 = res34.geodesic_scale; // cos(s14/earth_radius) is the spherical limit\n            CT m34 = res34.reduced_length;\n            CT der = (M43 / m34) * sin(g4);\n\n            // normalize (g4 - pi/2)\n            delta_g4 = normalize(g4, der);\n\n            s14 = s14 - delta_g4 / der;\n\n#ifdef BOOST_GEOMETRY_DEBUG_GEOGRAPHIC_CROSS_TRACK\n            std::cout << \"p4=\" << res14.lon2 * math::r2d<CT>() <<\n                         \",\" << res14.lat2 * math::r2d<CT>() << std::endl;\n            std::cout << \"a34=\" << res34.azimuth * math::r2d<CT>() << std::endl;\n            std::cout << \"a4=\" << a4 * math::r2d<CT>() << std::endl;\n            std::cout << \"g4=\" << g4 * math::r2d<CT>() << std::endl;\n            std::cout << \"delta_g4=\" << delta_g4 * math::r2d<CT>()  << std::endl;\n            std::cout << \"der=\" << der  << std::endl;\n            std::cout << \"M43=\" << M43 << std::endl;\n            std::cout << \"spherical limit=\" << cos(s14/earth_radius) << std::endl;\n            std::cout << \"m34=\" << m34 << std::endl;\n            std::cout << \"new_s14=\" << s14 << std::endl;\n            std::cout << std::setprecision(16) << \"dist     =\" << res34.distance << std::endl;\n            std::cout << \"---------end of step \" << counter << std::endl<< std::endl;\n#endif\n            result.distance = prev_distance;\n\n#ifdef BOOST_GEOMETRY_DEBUG_GEOGRAPHIC_CROSS_TRACK\n            if (g4 == half_pi)\n            {\n                std::cout << \"Stop msg: g4 == half_pi\" << std::endl;\n            }\n            if (res34.distance >= prev_distance && prev_distance != 0)\n            {\n                std::cout << \"Stop msg: res34.distance >= prev_distance\" << std::endl;\n            }\n            if (delta_g4 == 0)\n            {\n                std::cout << \"Stop msg: delta_g4 == 0\" << std::endl;\n            }\n            if (counter == 19)\n            {\n                std::cout << \"Stop msg: counter\" << std::endl;\n            }\n#endif\n\n        } while (g4 != half_pi\n                 && (prev_distance > res34.distance || prev_distance == 0)\n                 && delta_g4 != 0\n                 && ++counter < BOOST_GEOMETRY_DETAIL_POINT_SEGMENT_DISTANCE_MAX_STEPS ) ;\n\n#ifdef BOOST_GEOMETRY_DEBUG_GEOGRAPHIC_CROSS_TRACK\n        std::cout << \"distance=\" << res34.distance << std::endl;\n\n        point p4(res14.lon2, res14.lat2);\n        CT s34_sph = str.apply(p4, p3);\n\n        std::cout << \"s34(sph) =\" << s34_sph << std::endl;\n        std::cout << \"s34(geo) =\"\n                  << inverse_distance_quantities_type::apply(get<0>(p4), get<1>(p4), lon3, lat3, spheroid).distance\n                  << \", p4=(\" << get<0>(p4) * math::r2d<double>() << \",\"\n                              << get<1>(p4) * math::r2d<double>() << \")\"\n                  << std::endl;\n\n        CT s31 = inverse_distance_quantities_type::apply(lon3, lat3, lon1, lat1, spheroid).distance;\n        CT s32 = inverse_distance_quantities_type::apply(lon3, lat3, lon2, lat2, spheroid).distance;\n\n        CT a4 = inverse_azimuth_type::apply(get<0>(p4), get<1>(p4), lon2, lat2, spheroid).azimuth;\n        geometry::formula::result_direct<CT> res4 = direct_distance_type::apply(get<0>(p4), get<1>(p4), .04, a4, spheroid);\n        CT p4_plus = inverse_distance_quantities_type::apply(res4.lon2, res4.lat2, lon3, lat3, spheroid).distance;\n\n        geometry::formula::result_direct<CT> res1 = direct_distance_type::apply(lon1, lat1, s14-.04, a12, spheroid);\n        CT p4_minus = inverse_distance_quantities_type::apply(res1.lon2, res1.lat2, lon3, lat3, spheroid).distance;\n\n        std::cout << \"s31=\" << s31 << \"\\ns32=\" << s32\n                  << \"\\np4_plus=\" << p4_plus << \", p4=(\" << res4.lon2 * math::r2d<double>() << \",\" << res4.lat2 * math::r2d<double>() << \")\"\n                  << \"\\np4_minus=\" << p4_minus << \", p4=(\" << res1.lon2 * math::r2d<double>() << \",\" << res1.lat2 * math::r2d<double>() << \")\"\n                  << std::endl;\n\n        if (res34.distance <= p4_plus && res34.distance <= p4_minus)\n        {\n            std::cout << \"Closest point computed\" << std::endl;\n        }\n        else\n        {\n            std::cout << \"There is a closer point nearby\" << std::endl;\n        }\n#endif\n\n        return result;\n    }\n\n    Spheroid m_spheroid;\n};\n\n\n\n#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\nnamespace services\n{\n\n//tags\ntemplate <typename FormulaPolicy>\nstruct tag<geographic_cross_track<FormulaPolicy> >\n{\n    typedef strategy_tag_distance_point_segment type;\n};\n\ntemplate\n<\n        typename FormulaPolicy,\n        typename Spheroid\n>\nstruct tag<geographic_cross_track<FormulaPolicy, Spheroid> >\n{\n    typedef strategy_tag_distance_point_segment type;\n};\n\ntemplate\n<\n        typename FormulaPolicy,\n        typename Spheroid,\n        typename CalculationType\n>\nstruct tag<geographic_cross_track<FormulaPolicy, Spheroid, CalculationType> >\n{\n    typedef strategy_tag_distance_point_segment type;\n};\n\n\n//return types\ntemplate <typename FormulaPolicy, typename P, typename PS>\nstruct return_type<geographic_cross_track<FormulaPolicy>, P, PS>\n    : geographic_cross_track<FormulaPolicy>::template return_type<P, PS>\n{};\n\ntemplate\n<\n        typename FormulaPolicy,\n        typename Spheroid,\n        typename P,\n        typename PS\n>\nstruct return_type<geographic_cross_track<FormulaPolicy, Spheroid>, P, PS>\n    : geographic_cross_track<FormulaPolicy, Spheroid>::template return_type<P, PS>\n{};\n\ntemplate\n<\n        typename FormulaPolicy,\n        typename Spheroid,\n        typename CalculationType,\n        typename P,\n        typename PS\n>\nstruct return_type<geographic_cross_track<FormulaPolicy, Spheroid, CalculationType>, P, PS>\n    : geographic_cross_track<FormulaPolicy, Spheroid, CalculationType>::template return_type<P, PS>\n{};\n\n//comparable types\ntemplate\n<\n        typename FormulaPolicy,\n        typename Spheroid,\n        typename CalculationType\n>\nstruct comparable_type<geographic_cross_track<FormulaPolicy, Spheroid, CalculationType> >\n{\n    typedef geographic_cross_track\n        <\n            FormulaPolicy, Spheroid, CalculationType\n        >  type;\n};\n\ntemplate\n<\n        typename FormulaPolicy,\n        typename Spheroid,\n        typename CalculationType\n>\nstruct get_comparable<geographic_cross_track<FormulaPolicy, Spheroid, CalculationType> >\n{\n    typedef typename comparable_type\n        <\n            geographic_cross_track<FormulaPolicy, Spheroid, CalculationType>\n        >::type comparable_type;\npublic :\n    static inline comparable_type\n    apply(geographic_cross_track<FormulaPolicy, Spheroid, CalculationType> const& )\n    {\n        return comparable_type();\n    }\n};\n\n\ntemplate\n<\n    typename FormulaPolicy,\n    typename P,\n    typename PS\n>\nstruct result_from_distance<geographic_cross_track<FormulaPolicy>, P, PS>\n{\nprivate :\n    typedef typename geographic_cross_track\n        <\n            FormulaPolicy\n        >::template return_type<P, PS>::type return_type;\npublic :\n    template <typename T>\n    static inline return_type\n    apply(geographic_cross_track<FormulaPolicy> const& , T const& distance)\n    {\n        return distance;\n    }\n};\n\ntemplate\n<\n    typename FormulaPolicy,\n    typename Spheroid,\n    typename CalculationType,\n    typename P,\n    typename PS\n>\nstruct result_from_distance<geographic_cross_track<FormulaPolicy, Spheroid, CalculationType>, P, PS>\n{\nprivate :\n    typedef typename geographic_cross_track\n        <\n            FormulaPolicy, Spheroid, CalculationType\n        >::template return_type<P, PS>::type return_type;\npublic :\n    template <typename T>\n    static inline return_type\n    apply(geographic_cross_track<FormulaPolicy, Spheroid, CalculationType> const& , T const& distance)\n    {\n        return distance;\n    }\n};\n\n\ntemplate <typename Point, typename PointOfSegment>\nstruct default_strategy\n    <\n        point_tag, segment_tag, Point, PointOfSegment,\n        geographic_tag, geographic_tag\n    >\n{\n    typedef geographic_cross_track<> type;\n};\n\n\ntemplate <typename PointOfSegment, typename Point>\nstruct default_strategy\n    <\n        segment_tag, point_tag, PointOfSegment, Point,\n        geographic_tag, geographic_tag\n    >\n{\n    typedef typename default_strategy\n        <\n            point_tag, segment_tag, Point, PointOfSegment,\n            geographic_tag, geographic_tag\n        >::type type;\n};\n\n} // namespace services\n#endif // DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\n\n}} // namespace strategy::distance\n\n}} // namespace boost::geometry\n#endif // BOOST_GEOMETRY_STRATEGIES_GEOGRAPHIC_DISTANCE_CROSS_TRACK_HPP\n", "meta": {"hexsha": "ba53cd737b3bab00a3e13d43bb26c9681af7f9fe", "size": 23806, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/geometry/strategies/geographic/distance_cross_track.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/geographic/distance_cross_track.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/geographic/distance_cross_track.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": 33.9600570613, "max_line_length": 142, "alphanum_fraction": 0.6074939091, "num_tokens": 6151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4696095908459453}}
{"text": "/*\n * poh_bfs_example.cpp\n * Author: Aven Bross\n *\n * An example using Poh with BFS to path 3-color a plane graph.\n */\n\n// STL headers\n#include <algorithm>\n#include <iostream>\n#include <vector>\n#include <utility>\n\n// Basic graph headers\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/properties.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/property_map/property_map.hpp>\n\n// Planar graph headers\n#include <boost/graph/boyer_myrvold_planar_test.hpp>\n\n// Local project headers\n#include \"../../include/path_coloring/poh_color_bfs.hpp\"\n#include \"../../include/path_coloring/incidence_list_helpers.hpp\"\n\nusing namespace boost;\n\n/* \n * -----------------------------------------------------------------------------\n *                         Template type definitions\n * -----------------------------------------------------------------------------\n */\n\n// Define the graph type for all test graphs\ntypedef adjacency_list<\n        vecS,\n        vecS,\n        undirectedS,\n        property<vertex_index_t, std::size_t>,\n        property<edge_index_t, std::size_t>\n    > graph_t;\n\n// Vertex and edge types\ntypedef typename graph_traits<graph_t>::vertex_descriptor vertex_t;\ntypedef typename graph_traits<graph_t>::edge_descriptor edge_t;\n\n// Vertex and edge index map types\ntypedef typename property_map<graph_t, vertex_index_t>::const_type\n    vertex_index_map_t;\n\n// Vertex property map type for an integer property\ntypedef std::vector<int> integer_property_storage_t;\ntypedef iterator_property_map<\n        typename integer_property_storage_t::iterator, \n        vertex_index_map_t\n    > integer_property_map_t;\n\n// Vertex property map type for a planar embedding\ntypedef std::vector<std::vector<edge_t>> planar_embedding_storage_t;\ntypedef iterator_property_map<\n        typename planar_embedding_storage_t::iterator, \n        vertex_index_map_t\n    > planar_embedding_t;\n\n\n/* \n * -----------------------------------------------------------------------------\n *               Main: path 3-color a plane graph\n * -----------------------------------------------------------------------------\n */\n\nint main() {\n    // First we will construct a planar graph.\n    graph_t graph(5);\n    \n    boost::add_edge(0, 1, graph);\n    boost::add_edge(1, 2, graph);\n    boost::add_edge(2, 0, graph);\n    boost::add_edge(1, 3, graph);\n    boost::add_edge(0, 3, graph);\n    boost::add_edge(2, 3, graph);\n    boost::add_edge(0, 4, graph);\n    boost::add_edge(2, 4, graph);\n    boost::add_edge(3, 4, graph);\n    \n    // We choose our outer face to be the triangle 012\n    std::vector<vertex_t> path_1 = { 0 };\n    std::vector<vertex_t> path_2 = { 1, 2 };\n    \n    // Create the planar embedding\n    planar_embedding_storage_t planar_embedding_storage(num_vertices(graph));\n    planar_embedding_t planar_embedding(\n            planar_embedding_storage.begin(), get(vertex_index, graph)\n        );\n    for(std::size_t v=0; v < num_vertices(graph); ++v) {\n        planar_embedding[v].reserve(out_degree(v, graph));\n    }\n    boyer_myrvold_planarity_test(\n            boyer_myrvold_params::graph = graph,\n            boyer_myrvold_params::embedding = planar_embedding\n        );\n    \n    // Print embedding ordered adjacency list\n    std::cout << \"Embedding ordered adajacency lists:\\n\";\n    for(std::size_t v=0; v < num_vertices(graph); ++v) {\n        std::cout << \"    Adj[\" << v << \"] = \";\n        for(auto edge_iter = planar_embedding[v].begin();\n            edge_iter != planar_embedding[v].end(); ++edge_iter)\n        {\n            if(edge_iter != planar_embedding[v].begin())\n                std::cout << \" -> \";\n            std::cout << get_incident_vertex(v, *edge_iter, graph);\n        }\n        std::cout << \"\\n\";\n    }\n    std::cout << \"\\n\";\n    \n    // Create a vertex property map for the coloring\n    integer_property_storage_t color_map_storage(num_vertices(graph));\n    integer_property_map_t color_map(\n            color_map_storage.begin(), get(vertex_index, graph)\n        );\n    \n    // Call Poh with the given paths and structurs and color set { 1, 2, 3 }\n    poh_color_bfs(\n            graph,\n            planar_embedding,\n            path_1.begin(), path_1.end(),\n            path_2.begin(), path_2.end(),\n            1, 2, 3,\n            color_map\n        );\n    \n    // Print the coloring\n    std::cout << \"The path 3-coloring:\\n\";\n    for(std::size_t v=0; v < num_vertices(graph); ++v) {\n        std::cout << \"    color[\" << v << \"] = \" << color_map[v] << \"\\n\";\n    }\n    \n    return 0;\n}\n\n", "meta": {"hexsha": "f850ca16dee283e425fd2ba6e91bdfe7744120f6", "size": 4521, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/examples/poh_bfs_example/poh_bfs_example.cpp", "max_stars_repo_name": "permutationlock/path_coloring_bgl", "max_stars_repo_head_hexsha": "ec8ca14faadfdf65f7dcab9aef5a91d82dc7d6d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/examples/poh_bfs_example/poh_bfs_example.cpp", "max_issues_repo_name": "permutationlock/path_coloring_bgl", "max_issues_repo_head_hexsha": "ec8ca14faadfdf65f7dcab9aef5a91d82dc7d6d1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/examples/poh_bfs_example/poh_bfs_example.cpp", "max_forks_repo_name": "permutationlock/path_coloring_bgl", "max_forks_repo_head_hexsha": "ec8ca14faadfdf65f7dcab9aef5a91d82dc7d6d1", "max_forks_repo_licenses": ["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.3958333333, "max_line_length": 80, "alphanum_fraction": 0.5945587259, "num_tokens": 1065, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581741774411, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.46959245735396404}}
{"text": "#include \"Constraint/BoxConstraint.h\"\n\n#include <Eigen/Geometry> \n#include <QtMath>\n\nBoxConstraint::BoxConstraint(const QVector3D& position, const QVector3D& halfDimension, bool isBoundary) :\n\tm_position(position),\n\tm_halfDimension(halfDimension),\n\tm_isBoundary(isBoundary)\n{\n\tsetRotation(0.f, QVector3D(1.f, 0.f, 0.f));\n}\n\nBoxConstraint::~BoxConstraint()\n{\n}\n\nvoid BoxConstraint::setPosition(const QVector3D& position)\n{\n\tm_position = position;\n}\n\nvoid BoxConstraint::setHalfDimension(const QVector3D& halfDimension)\n{\n\tm_halfDimension = halfDimension;\n}\n\nvoid BoxConstraint::setRotation(float angleDegrees, const QVector3D& axis)\n{\n\tm_angle = angleDegrees;\n\tm_rotationAxis = axis;\n\tm_rotation = Eigen::AngleAxisf((angleDegrees / 180.f) * M_PI, Eigen::Vector3f(axis.x(), axis.y(), axis.z()));\n}\n\nvoid BoxConstraint::setIsBoundary(bool isBoundary)\n{\n\tm_isBoundary = isBoundary;\n}\n\nconst QVector3D& BoxConstraint::getPosition()\n{\n\treturn m_position;\n}\n\nconst QVector3D& BoxConstraint::getHalfDimension()\n{\n\treturn m_halfDimension;\n}\n\nconst Eigen::Matrix3f& BoxConstraint::getRotation()\n{\n\treturn m_rotation;\n}\n\nfloat BoxConstraint::getAngle()\n{\n\treturn m_angle;\n}\n\nconst QVector3D& BoxConstraint::getRotationAxis()\n{\n\treturn m_rotationAxis;\n}\n\nbool BoxConstraint::getIsBoundary()\n{\n\treturn m_isBoundary;\n}\n", "meta": {"hexsha": "cc493e3215d883477a0442aebf36565c8a89dd2c", "size": 1305, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SoftbodyPhysics/src/Constraint/BoxConstraint.cpp", "max_stars_repo_name": "GitDaroth/SoftbodySimulation", "max_stars_repo_head_hexsha": "21b32dfb7a72be1f2fe54de8d2863bbf6a100288", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-02-28T23:48:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-02T15:08:34.000Z", "max_issues_repo_path": "SoftbodyPhysics/src/Constraint/BoxConstraint.cpp", "max_issues_repo_name": "GitDaroth/SoftbodySimulation", "max_issues_repo_head_hexsha": "21b32dfb7a72be1f2fe54de8d2863bbf6a100288", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SoftbodyPhysics/src/Constraint/BoxConstraint.cpp", "max_forks_repo_name": "GitDaroth/SoftbodySimulation", "max_forks_repo_head_hexsha": "21b32dfb7a72be1f2fe54de8d2863bbf6a100288", "max_forks_repo_licenses": ["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.9130434783, "max_line_length": 110, "alphanum_fraction": 0.7624521073, "num_tokens": 322, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799253, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.4695924527996035}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// Unit Test\n\n// Copyright (c) 2016 Oracle and/or its affiliates.\n// Contributed and/or modified by Vissarion Fisikopoulos, 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#include <algorithms/test_perimeter.hpp>\n#include <algorithms/perimeter/perimeter_polygon_cases.hpp>\n\n#include <boost/geometry/geometries/geometries.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n\ntemplate <typename P>\nvoid test_all_default() //test the default strategy\n{\n    double const pi = boost::math::constants::pi<double>();\n\n    for (std::size_t i = 0; i <= 2; ++i)\n    {\n        test_geometry<bg::model::polygon<P> >(poly_data_sph[i], 2 * pi);\n    }\n\n    // Multipolygon\n    test_geometry<bg::model::multi_polygon<bg::model::polygon<P> > >\n                                            (multipoly_data[0], 3 * pi);\n\n    // Geometries with length zero\n    test_geometry<P>(\"POINT(0 0)\", 0);\n    test_geometry<bg::model::linestring<P> >(\"LINESTRING(0 0,3 4,4 3)\", 0);\n}\n\n\ntemplate <typename P>\nvoid test_all_haversine(double const mean_radius)\n{\n    double const pi = boost::math::constants::pi<double>();\n    bg::strategy::distance::haversine<double> haversine_strategy(mean_radius);\n\n    for (std::size_t i = 0; i <= 2; ++i)\n    {\n        test_geometry<bg::model::polygon<P> >(poly_data_sph[i],\n                                              2 * pi * mean_radius,\n                                              haversine_strategy);\n    }\n\n    // Multipolygon\n    test_geometry<bg::model::multi_polygon<bg::model::polygon<P> > >\n                                            (multipoly_data[0],\n                                             3 * pi * mean_radius,\n                                             haversine_strategy);\n\n    // Geometries with length zero\n    test_geometry<P>(\"POINT(0 0)\", 0, haversine_strategy);\n    test_geometry<bg::model::linestring<P> >(\"LINESTRING(0 0,3 4,4 3)\",\n                                             0,\n                                             haversine_strategy);\n}\n\nint test_main(int, char* [])\n{\n    //Earth radius estimation in Km\n    //(see https://en.wikipedia.org/wiki/Earth_radius)\n    double const mean_radius = 6371.0;\n\n    test_all_default<bg::model::d2::point_xy<int,\n            bg::cs::spherical_equatorial<bg::degree> > >();\n    test_all_default<bg::model::d2::point_xy<float,\n            bg::cs::spherical_equatorial<bg::degree> > >();\n    test_all_default<bg::model::d2::point_xy<double,\n            bg::cs::spherical_equatorial<bg::degree> > >();\n\n    test_all_haversine<bg::model::d2::point_xy<int,\n        bg::cs::spherical_equatorial<bg::degree> > >(mean_radius);\n    test_all_haversine<bg::model::d2::point_xy<float,\n        bg::cs::spherical_equatorial<bg::degree> > >(mean_radius);\n    test_all_haversine<bg::model::d2::point_xy<double,\n        bg::cs::spherical_equatorial<bg::degree> > >(mean_radius);\n\n#if defined(HAVE_TTMATH)\n    test_all<bg::model::d2::point_xy<ttmath_big> >();\n#endif\n\n    return 0;\n}\n", "meta": {"hexsha": "73cf9180009460cf4595a1b916672409f84eae73", "size": 3174, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/libs/geometry/test/algorithms/perimeter/perimeter_sph.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/geometry/test/algorithms/perimeter/perimeter_sph.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/geometry/test/algorithms/perimeter/perimeter_sph.cpp", "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": 35.6629213483, "max_line_length": 79, "alphanum_fraction": 0.6042848141, "num_tokens": 829, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799253, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.4695924527996035}}
{"text": "#pragma once\n#include <Eigen/Sparse>\n#include <Eigen/SparseLU>\n#include <vector>\n\n#include \"basis.hpp\"\n#include \"triangulation_view.hpp\"\n\nnamespace space {\n\nstruct OperatorOptions {\n  // Options for all operators.\n  bool dirichlet_boundary = true;\n\n  // Whether or not to build the matrix for a forward operator.\n  bool build_mat = false;\n\n  // Options for stiff plus scaled mass operator.\n  size_t time_level = 0;\n  double alpha = 1;\n\n  // Options for multigrid preconditioner.\n  size_t mg_cycles = 3;\n\n  OperatorOptions() = default;\n\n  friend std::ostream &operator<<(std::ostream &os,\n                                  const OperatorOptions &opts) {\n    os << \"OperatorOptions:\" << std::endl;\n    os << \"\\tdirichlet_boundary: \"\n       << (opts.dirichlet_boundary ? \"true\" : \"false\") << std::endl;\n    os << \"\\tbuild_mat: \" << (opts.build_mat ? \"true\" : \"false\") << std::endl;\n    os << \"\\ttime_level: \" << opts.time_level << std::endl;\n    os << \"\\talpha: \" << opts.alpha << std::endl;\n    os << \"\\tcycles: \" << opts.mg_cycles << std::endl;\n    return os;\n  }\n};\n\nclass Operator {\n public:\n  Operator(const TriangulationView &triang,\n           OperatorOptions opts = OperatorOptions())\n      : triang_(triang), opts_(std::move(opts)) {}\n\n  virtual ~Operator() {}\n\n  // Apply the operator in the hierarchical basis.\n  virtual void Apply(Eigen::VectorXd &vec_in) const = 0;\n\n  // Does the given vertex correspond to a dof?\n  inline bool IsDof(uint vertex) const {\n    return !triang_.OnBoundary(vertex) || !opts_.dirichlet_boundary;\n  }\n\n  // Verify that the given vector satisfy the boundary conditions.\n  bool FeasibleVector(const Eigen::VectorXd &vec) const;\n  inline bool DirichletBoundary() const { return opts_.dirichlet_boundary; }\n\n  // Overloads required to for Eigen.\n  Eigen::VectorXd operator*(const Eigen::VectorXd &vec_in) const {\n    Eigen::VectorXd result = vec_in;\n    Apply(result);\n    return result;\n  }\n  size_t rows() const { return triang_.V; }\n  size_t cols() const { return triang_.V; }\n\n  // Debug function for turning this operator into a mtrix.\n  Eigen::MatrixXd ToMatrix() const;\n\n protected:\n  const TriangulationView &triang_;\n  OperatorOptions opts_;\n};\n\ntemplate <class ForwardOp>\nclass ForwardOperator : public Operator {\n public:\n  ForwardOperator(const TriangulationView &triang,\n                  OperatorOptions opts = OperatorOptions());\n\n  // Apply the operator in the hierarchical basis.\n  virtual void Apply(Eigen::VectorXd &vec_in) const final;\n\n  // Apply the operator in single scale, to be implemented by derived.\n  void ApplySingleScale(Eigen::VectorXd &vec_SS) const;\n\n  const Eigen::SparseMatrix<double> &MatrixSingleScale() const {\n    assert(matrix_.nonZeros());\n    return matrix_;\n  }\n\n  // Hierarhical Basis Transformations from HB to SS, and its transpose.\n  void ApplyHierarchToSingle(Eigen::VectorXd &vec_HB) const;\n  void ApplyTransposeHierarchToSingle(Eigen::VectorXd &vec_SS) const;\n\n protected:\n  void InitializeMatrixSingleScale();\n  Eigen::SparseMatrix<double> matrix_;\n};\n\nclass BackwardOperator : public Operator {\n public:\n  BackwardOperator(const TriangulationView &triang,\n                   OperatorOptions opts = OperatorOptions());\n\n  // Apply the operator in the hierarchical basis.\n  virtual void Apply(Eigen::VectorXd &vec_in) const final;\n\n  // Apply the operator in single scale, to be implemented by derived.\n  virtual void ApplySingleScale(Eigen::VectorXd &vec_SS) const = 0;\n\n protected:\n  // Inverse Hierarhical Basis Transformations.\n  void ApplyInverseHierarchToSingle(Eigen::VectorXd &vec_SS) const;\n  void ApplyTransposeInverseHierarchToSingle(Eigen::VectorXd &vec_HB) const;\n\n  // Vertex-to-DoF transformation matrices.\n  Eigen::SparseMatrix<double> transform_;\n  Eigen::SparseMatrix<double> transformT_;\n};\n\n/**\n *  Implementation of the actual operators.\n */\nclass MassOperator : public ForwardOperator<MassOperator> {\n public:\n  // Inherit constructor.\n  using ForwardOperator::ForwardOperator;\n\n  // Returns the element matrix for the given element.\n  inline static Eigen::Matrix3d ElementMatrix(const Element2D *elem,\n                                              const OperatorOptions &opts);\n};\n\nclass StiffnessOperator : public ForwardOperator<StiffnessOperator> {\n public:\n  // Inherit constructor.\n  using ForwardOperator::ForwardOperator;\n\n  // Returns the element matrix for the given element.\n  inline static const Eigen::Matrix3d &ElementMatrix(\n      const Element2D *elem, const OperatorOptions &opts);\n};\n\nclass StiffPlusScaledMassOperator\n    : public ForwardOperator<StiffPlusScaledMassOperator> {\n public:\n  // Inherit constructor.\n  using ForwardOperator::ForwardOperator;\n\n  // Returns the element matrix for the given element.\n  inline static Eigen::Matrix3d ElementMatrix(const Element2D *elem,\n                                              const OperatorOptions &opts);\n};\n\ntemplate <typename ForwardOp>\nclass DirectInverse : public BackwardOperator {\n public:\n  DirectInverse(const TriangulationView &triang,\n                OperatorOptions opts = OperatorOptions());\n\n  void ApplySingleScale(Eigen::VectorXd &vec_SS) const final;\n\n protected:\n  Eigen::SparseLU<Eigen::SparseMatrix<double>, Eigen::COLAMDOrdering<int>>\n      solver_;\n};\n\ntemplate <typename ForwardOp>\nclass CGInverse : public BackwardOperator {\n public:\n  CGInverse(const TriangulationView &triang,\n            OperatorOptions opts = OperatorOptions());\n\n  void ApplySingleScale(Eigen::VectorXd &vec_SS) const final;\n\n protected:\n  Eigen::ConjugateGradient<Eigen::SparseMatrix<double>,\n                           Eigen::Lower | Eigen::Upper>\n      solver_;\n};\n\ntemplate <typename ForwardOp>\nclass MultigridPreconditioner : public BackwardOperator {\n public:\n  MultigridPreconditioner(const TriangulationView &triang,\n                          OperatorOptions opts = OperatorOptions());\n\n  void ApplySingleScale(Eigen::VectorXd &vec_SS) const final;\n\n  inline void Prolongate(uint vertex, Eigen::VectorXd &vec_SS) const {\n    for (auto gp : triang_.Godparents(vertex))\n      vec_SS[vertex] += 0.5 * vec_SS[gp];\n  }\n\n  inline void Restrict(uint vertex, Eigen::VectorXd &vec_SS) const {\n    for (auto gp : triang_.Godparents(vertex))\n      vec_SS[gp] += 0.5 * vec_SS[vertex];\n  }\n\n  inline void RestrictInverse(uint vertex, Eigen::VectorXd &vec_SS) const {\n    for (auto gp : triang_.Godparents(vertex))\n      vec_SS[gp] -= 0.5 * vec_SS[vertex];\n  }\n\n protected:\n  // Initializes the static variable row_mat.\n  void InitializeMultigridMatrix() const;\n\n  // Returns a row of the _forward_ matrix on the given multilevel triang.\n  // NOTE: The result might not be compressed.\n  inline void RowMatrix(uint vertex,\n                        std::vector<std::pair<uint, double>> &result) const;\n\n  // Forward operator on the finest level.\n  ForwardOp forward_op_;\n\n  // Solver on the coarsest level.\n  DirectInverse<ForwardOp> initial_triang_solver_;\n\n  // (Static) variables reused for calculation of the multigrid matrix.\n  static std::vector<std::vector<std::pair<uint, double>>> row_mat;\n  static std::vector<std::vector<Element2D *>> patches;\n  static std::vector<std::vector<uint>> vertices_relaxation;\n};\n\ntemplate <template <typename> class InverseOp>\nclass XPreconditionerOperator : public BackwardOperator {\n public:\n  XPreconditionerOperator(const TriangulationView &triang,\n                          OperatorOptions opts = OperatorOptions());\n\n  void ApplySingleScale(Eigen::VectorXd &vec_SS) const final;\n\n protected:\n  StiffnessOperator stiff_op_;\n  InverseOp<StiffPlusScaledMassOperator> inverse_op_;\n};\n\nextern template class ForwardOperator<MassOperator>;\nextern template class ForwardOperator<StiffnessOperator>;\nextern template class ForwardOperator<StiffPlusScaledMassOperator>;\n\nextern template class DirectInverse<MassOperator>;\nextern template class DirectInverse<StiffnessOperator>;\nextern template class DirectInverse<StiffPlusScaledMassOperator>;\n\nextern template class MultigridPreconditioner<MassOperator>;\nextern template class MultigridPreconditioner<StiffnessOperator>;\nextern template class MultigridPreconditioner<StiffPlusScaledMassOperator>;\n\nextern template class XPreconditionerOperator<DirectInverse>;\nextern template class XPreconditionerOperator<MultigridPreconditioner>;\n\n}  // namespace space\n", "meta": {"hexsha": "49c1e0ee808b6d6b8b6e3f2b33ab1515926cde0b", "size": 8305, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/space/operators.hpp", "max_stars_repo_name": "rvanvenetie/spacetime", "max_stars_repo_head_hexsha": "b516419be2a59115d9b2d853aeea9fcd4f125c94", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/space/operators.hpp", "max_issues_repo_name": "rvanvenetie/spacetime", "max_issues_repo_head_hexsha": "b516419be2a59115d9b2d853aeea9fcd4f125c94", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/space/operators.hpp", "max_forks_repo_name": "rvanvenetie/spacetime", "max_forks_repo_head_hexsha": "b516419be2a59115d9b2d853aeea9fcd4f125c94", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1899224806, "max_line_length": 78, "alphanum_fraction": 0.7228175798, "num_tokens": 1913, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.46959244999704974}}
{"text": "/*\n * Copyright (c) 2012 Jonathan Perry\n * This code is released under the MIT license (see LICENSE file).\n */\n#include \"channels/MimoChannel.h\"\n\n#include <boost/numeric/ublas/operation.hpp>\n\nMimoChannel::MimoChannel(\n\t\tunsigned int nTransmitter,\n\t\tunsigned int nReceiver,\n\t\tconst std::vector<ComplexNumber> & channelMatrix)\n  : m_nTransmitter(nTransmitter),\n    m_nReceiver(nReceiver),\n    m_channelMatrix(nReceiver, nTransmitter)\n{\n\tfor(unsigned int row = 0; row < nReceiver; row++) {\n\t\tfor(unsigned int col = 0; col < nTransmitter; col++) {\n\t\t\tm_channelMatrix(row, col) = channelMatrix[row * nTransmitter + col];\n\t\t}\n\t}\n}\n\nvoid MimoChannel::seed(unsigned int *const , int )\n{\n\t// no RNG in this class\n\treturn;\n}\n\n\n\nvoid MimoChannel::process(\n\t\tconst std::vector<ComplexSymbol> & inSymbols,\n\t\tstd::vector<ComplexSymbol> & outSymbols)\n{\n\tunsigned int numIQSymbols = inSymbols.size();\n\n\tunsigned int numChannelUsages = numIQSymbols / m_nTransmitter;\n\n\tif (inSymbols.size() != m_nTransmitter * numChannelUsages) {\n\t\tthrow std::runtime_error(\"input symbols size should contain symbols for all transmit antenna\");\n\t}\n\n\tunsigned int numOutputSymbols = numChannelUsages * m_nReceiver;\n\toutSymbols.clear();\n\toutSymbols.resize(numOutputSymbols);\n\n\t// Initialize a matrix with all symbols\n\tboost::numeric::ublas::matrix<ComplexSymbol> symbolMatrix(m_nTransmitter,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  numChannelUsages);\n\tunsigned int inSymbolIter = 0;\n\tfor(unsigned int col = 0; col < numChannelUsages; col++) {\n\t\tfor(unsigned int row = 0; row < m_nTransmitter; row++) {\n\t\t\tsymbolMatrix(row, col) = inSymbols[inSymbolIter++];\n\t\t}\n\t}\n\n\t// Multiply channel matrix by symbol matrix\n\tboost::numeric::ublas::matrix<ComplexSymbol> outputMatrix(m_nReceiver,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  numChannelUsages);\n\taxpy_prod(m_channelMatrix, symbolMatrix, outputMatrix, true);\n\n\t// Read the output symbols from outputMatrix\n\tunsigned int outSymbolIter = 0;\n\tfor(unsigned int col = 0; col < numChannelUsages; col++) {\n\t\tfor(unsigned int row = 0; row < m_nReceiver; row++) {\n\t\t\toutSymbols[outSymbolIter++] = outputMatrix(row, col);\n\t\t}\n\t}\n\n}\n\nunsigned int MimoChannel::forecast(unsigned int numOutputs)\n{\n\tunsigned int numChannelUsages = (numOutputs + m_nReceiver - 1) / m_nReceiver;\n\treturn numChannelUsages * m_nTransmitter;\n}\n\n", "meta": {"hexsha": "537081f4a6becaf5aecf1f4c3ca024d8a11af9ee", "size": 2273, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/channels/MimoChannel.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/channels/MimoChannel.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/channels/MimoChannel.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": 28.7721518987, "max_line_length": 97, "alphanum_fraction": 0.7245930488, "num_tokens": 590, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581741774411, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.4695924471944952}}
{"text": "// (C) Copyright Andrew Sutton 2007\r\n//\r\n// Use, modification and distribution are subject to the\r\n// Boost Software License, Version 1.0 (See accompanying file\r\n// LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n//[code_bron_kerbosch_clique_number\r\n#include <iostream>\r\n\r\n#include <boost/graph/undirected_graph.hpp>\r\n#include <boost/graph/bron_kerbosch_all_cliques.hpp>\r\n\r\n#include \"helper.hpp\"\r\n\r\nusing namespace std;\r\nusing namespace boost;\r\n\r\n// Declare the graph type and its vertex and edge types.\r\ntypedef undirected_graph<> Graph;\r\ntypedef graph_traits<Graph>::vertex_descriptor Vertex;\r\ntypedef graph_traits<Graph>::edge_descriptor Edge;\r\n\r\nint\r\nmain(int argc, char *argv[])\r\n{\r\n    // Create the graph and read it from standard input.\r\n    Graph g;\r\n    read_graph(g, cin);\r\n\r\n    // Use the Bron-Kerbosch algorithm to find all cliques, and\r\n    size_t c = bron_kerbosch_clique_number(g);\r\n    cout << \"clique number: \" << c << endl;\r\n\r\n    return 0;\r\n}\r\n//]\r\n", "meta": {"hexsha": "0690b94db28a696b9f26af31e86c0cb3f8feb01c", "size": 982, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/graph/example/bron_kerbosch_clique_number.cpp", "max_stars_repo_name": "zyiacas/boost-doc-zh", "max_stars_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 198.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T05:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:46:46.000Z", "max_issues_repo_path": "libs/graph/example/bron_kerbosch_clique_number.cpp", "max_issues_repo_name": "sdfict/boost-doc-zh", "max_issues_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/graph/example/bron_kerbosch_clique_number.cpp", "max_forks_repo_name": "sdfict/boost-doc-zh", "max_forks_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 26.5405405405, "max_line_length": 64, "alphanum_fraction": 0.7087576375, "num_tokens": 240, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.6370307875894138, "lm_q1q2_score": 0.46959244491731533}}
{"text": "#include <iostream>\r\n#include <vector>\r\n#include <locale>\r\n#include <omp.h>\r\n\r\n#include <boost/multiprecision/cpp_int.hpp>\r\nusing namespace boost::multiprecision;\r\n\r\n#include \"ThreadPool.h\"\r\n\r\n// Included from collat_asm.asm (.o/.obj)\r\nint16_t collatz(uint64_t *, int64_t);\r\n\r\nstruct record_t {\r\n\tint64_t number;\r\n\tint16_t steps;\r\n};\r\n\r\nint64_t overflowCollatz(uint64_t number_, int64_t bufferSize, int16_t &extraSteps) {\r\n\tcpp_int number = number_;\r\n\r\n\twhile (number > bufferSize) {\r\n\t\tif (number % 2 == 0) {\r\n\t\t\tnumber = number / 2;\r\n\t\t}\r\n\t\telse {\r\n\t\t\tnumber = number * 3 + 1;\r\n\t\t}\r\n\t\textraSteps++;\r\n\t}\r\n\r\n\treturn number.convert_to<int64_t>();\r\n}\r\n\r\nvoid fillLUT(std::vector<int16_t> &LUT, record_t &largest) {\r\n\r\n\tstd::vector<int64_t> sequence;\r\n\tint64_t LUTSum = 0;\r\n\r\n\t// Fill the lookup table with distances\r\n\tfor (int64_t i = 3; i < LUT.size(); i++) {\r\n\r\n\t\t// If the number has already been added to the look up table\r\n\t\tif (LUT[i] != 0) {\r\n\t\t\tif (LUT[i] > largest.steps) {\r\n\t\t\t\tlargest.steps = LUT[i];\r\n\t\t\t\tlargest.number = i;\r\n\t\t\t\t// VT100 escape character for clearing line only works if running through visual studio\r\n\t\t\t\tstd::cout << \"\\r                                                                                           \";//\"\\33[2K\";\r\n\t\t\t\tstd::cout << \"\\r\" << largest.number << \" : \" << largest.steps << \"\\n\";\r\n\t\t\t}\r\n\t\t\tcontinue;\r\n\t\t}\r\n\r\n\t\tint64_t number = i;\r\n\r\n\t\t// Compute sequence until we find a number that has already been computed\r\n\t\twhile (true) {\r\n\t\t\tif (number < LUT.size()) {\r\n\t\t\t\tif (LUT[number] != 0) break;\r\n\t\t\t\tsequence.push_back(number);\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\t// Don't need to save the number if the sequence goes above the lookup table size\r\n\t\t\t\t// but 0 is used as a place holder to get the correct amount of steps\r\n\t\t\t\tsequence.push_back(0);\r\n\t\t\t}\r\n\r\n\t\t\tif (number % 2 == 0) {\r\n\t\t\t\tnumber = number / 2;\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tnumber = 3 * number + 1;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t// Iterate through the sequence and add all steps to the lookup table\r\n\t\tint16_t sequenceSteps = 0;\r\n\t\tint16_t LUTSteps = LUT[number];\r\n\t\tfor (auto it = sequence.rbegin(); it != sequence.rend(); it++) {\r\n\t\t\tsequenceSteps++;\r\n\r\n\t\t\tif (*it > 0) {\r\n\t\t\t\tLUT[*it] = LUTSteps + sequenceSteps;\r\n\t\t\t\tLUTSum += static_cast<int64_t>(LUTSteps) + sequenceSteps;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tsequence.clear();\r\n\r\n\t\tif (LUT[i] > largest.steps) {\r\n\t\t\tlargest.steps = LUT[i];\r\n\t\t\tlargest.number = i;\r\n\t\t\t// VT100 escape character for clearing line only works if running through visual studio\r\n\t\t\tstd::cout << \"\\r                                                                                           \";//\"\\33[2K\";\r\n\t\t\tstd::cout << \"\\r\" << i << \" : \" << largest.steps << \"\\n\";\r\n\t\t\tstd::cout << \"Filling lookup table. Currently on: \" << i << \" of \" << LUT.size() << std::flush;\r\n\t\t}\r\n\t\telse if (i % 1000000 == 0) {\r\n\t\t\tstd::cout << \"\\rFilling lookup table. Currently on: \" << i << \" of \" << LUT.size() << std::flush;\r\n\t\t}\r\n\t}\r\n\r\n\tstd::cout << \"\\33[2K\";\r\n\tstd::cout << \"\\r\" << \"Lookup table filled. Avg steps: \" << LUTSum / LUT.size() << \"\\n\";\r\n}\r\n\r\nclass multiThreadCollatz {\r\npublic:\r\n\tstd::vector<int16_t> &LUT;\r\n\tstd::vector<std::vector<record_t>> &potentialRecords;\r\n\tint64_t start;\r\n\tint64_t end;\r\n\tint64_t blockIndex;\r\n\trecord_t largest;\r\n\r\n\tvoid operator()() {\r\n\t\tfor (int64_t j = start; j < end; j++) {\r\n\t\t\tuint64_t number = j;\r\n\r\n\t\t\tint16_t steps = collatz(&number, LUT.size());\r\n\t\t\tif (number > LUT.size()) {\r\n\t\t\t\tnumber = overflowCollatz(number, LUT.size(), steps);\r\n\t\t\t}\r\n\r\n\t\t\tint16_t totalSteps = LUT[number] + steps;\r\n\t\t\tif (totalSteps > largest.steps) {\r\n\t\t\t\tlargest = record_t{ j, totalSteps };\r\n\t\t\t\tpotentialRecords[blockIndex].push_back(largest);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n};\r\n\r\nenum LUT_SIZE : long long { L1 = 16000, L2 = 130000, L3 = 1000000, RAM = 5000000000 };\r\n\r\nint main() {\r\n\t// Adding space as a thousands separator for cout\r\n\tstruct separate_thousands : std::numpunct<char> {\r\n\t\tchar_type do_thousands_sep() const override { return ' '; }  // separate with space\r\n\t\tstring_type do_grouping() const override { return \"\\3\"; } // groups of 3 digit\r\n\t};\r\n\tauto thousands = std::make_unique<separate_thousands>();\r\n\tstd::cout.imbue(std::locale(std::cout.getloc(), thousands.release()));\r\n\r\n\tconst int64_t LUTSize = LUT_SIZE::RAM;\r\n\tconst int64_t blocks = 100;\r\n\tconst int64_t iterationsPerBlock = 1e6;\r\n\r\n\t// Allocate memory for the lookup table\r\n\tstd::cout << \"Allocting \" << LUTSize * sizeof(int16_t) << \" Bytes of memory\" << std::endl;\r\n\tstd::vector<int16_t> LUT(LUTSize);\r\n\r\n\t// Setting up the beginning of the lookup table\r\n\tLUT[2] = 1;\t\r\n\tstd::cout << \"1 : \" << LUT[1] << std::endl;\r\n\tstd::cout << \"2 : \" << LUT[2] << std::endl;\r\n\trecord_t largest{ 2, LUT[2] };\r\n\r\n\t// Fill the lookup table and update the largest distance\r\n\tfillLUT(LUT, largest);\r\n\r\n\tThreadPool<multiThreadCollatz> pool(10);\r\n\t\r\n\t// Each block stores all potential records in their own vector\r\n\tstd::vector<std::vector<record_t>> potentialRecords(blocks);\r\n\r\n\tstd::vector<record_t> records;\r\n\tfor (int64_t i = LUTSize; i < INT64_MAX; i += (blocks * iterationsPerBlock)) {\r\n\t\tstd::cout << \"\\rCurrently on \" << i << std::flush;\r\n\r\n\t\t// Start filling buffer 1\r\n\t\tfor (int64_t blockIndex = 0; blockIndex < blocks; blockIndex++) {\r\n\t\t\tpool.addWork(multiThreadCollatz{ LUT, potentialRecords, i + blockIndex * iterationsPerBlock, i + (blockIndex + 1) * iterationsPerBlock, blockIndex, largest });\r\n\t\t}\r\n\r\n\t\tpool.waitForThreads();\r\n\r\n\t\t// Combine all potential records in a vector and sort it\t\t\r\n\t\tfor (std::vector<record_t> &blockRecords : potentialRecords) {\r\n\t\t\tstd::copy(blockRecords.begin(), blockRecords.end(), std::back_inserter(records));\r\n\t\t\tblockRecords.clear();\r\n\t\t}\r\n\t\tstd::sort(records.begin(), records.end(), [](record_t const &rhs, record_t const &lhs) { return rhs.number < lhs.number; });\r\n\r\n\t\tfor (const record_t record : records) {\r\n\t\t\tif (record.steps > largest.steps) {\r\n\t\t\t\tlargest = record;\r\n\t\t\t\tstd::cout << \"\\r                                                                                           \";//\"\\33[2K\";\r\n\t\t\t\tstd::cout << \"\\r\" << largest.number << \" : \" << largest.steps << std::endl;\r\n\t\t\t}\r\n\t\t}\r\n\t\trecords.clear();\r\n\t}\r\n}\r\n", "meta": {"hexsha": "aa253423d8ea6495fd4d9486604a1ead3c250cba", "size": 6117, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Collatz/Collatz.cpp", "max_stars_repo_name": "HildingLinden/collatz-records", "max_stars_repo_head_hexsha": "a2b5c6e07e56b8317fcfd0fc02d12b7e0111b529", "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": "Collatz/Collatz.cpp", "max_issues_repo_name": "HildingLinden/collatz-records", "max_issues_repo_head_hexsha": "a2b5c6e07e56b8317fcfd0fc02d12b7e0111b529", "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": "Collatz/Collatz.cpp", "max_forks_repo_name": "HildingLinden/collatz-records", "max_forks_repo_head_hexsha": "a2b5c6e07e56b8317fcfd0fc02d12b7e0111b529", "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.2091836735, "max_line_length": 163, "alphanum_fraction": 0.5931011934, "num_tokens": 1705, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799253, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.4695924426401351}}
{"text": "/*\n * 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 *    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 *          Erik Nelson            ( eanelson@eecs.berkeley.edu )\n */\n\n#include <Eigen/Dense>\n#include <gflags/gflags.h>\n#include <iostream>\n\n#include <geometry/rotation.h>\n#include <math/random_generator.h>\n#include <pose/pose.h>\n\n#include <gtest/gtest.h>\n\nnamespace bsfm {\n\nusing Eigen::Matrix3d;\nusing Eigen::Matrix4d;\nusing Eigen::Vector3d;\n\nTEST(Pose, TestPoseAxisAngle) {\n  // Create a simple rotation matrix and random translation vector.\n  Eigen::Matrix3d R;\n  R << cos(0.5), -sin(0.5), 0,\n       sin(0.5),  cos(0.5), 0,\n       0,         0,        1;\n\n  const Vector3d t = Vector3d::Random();\n  const Pose p1 = Pose(R, t);\n  Pose p2 = p1;\n\n  // Convert to/from axis angle representation and check nothing has changed.\n  Vector3d aa = p2.AxisAngle();\n  p2.FromAxisAngle(aa);\n  EXPECT_TRUE(p1.IsApprox(p2));\n}\n\nTEST(Pose, TestPoseDelta) {\n\n  math::RandomGenerator rng(0);\n\n  for (int ii = 0; ii < 100; ++ii) {\n    // Repeatedly make two poses, compose them, and compute the relative\n    // transformation between them. Check that this value is correct.\n    const double phi1 = rng.DoubleUniform(-M_PI, M_PI);\n    const double phi2 = rng.DoubleUniform(-M_PI, M_PI);\n    const double theta1 = rng.DoubleUniform(-M_PI, M_PI);\n    const double theta2 = rng.DoubleUniform(-M_PI, M_PI);\n    const double psi1 = rng.DoubleUniform(-M_PI, M_PI);\n    const double psi2 = rng.DoubleUniform(-M_PI, M_PI);\n\n    // Make 2 rotation matrices.\n    const Matrix3d R1(EulerAnglesToMatrix(phi1, theta1, psi1));\n    const Matrix3d R2(EulerAnglesToMatrix(phi2, theta2, psi2));\n    const Vector3d t1(Vector3d::Random());\n    const Vector3d t2(Vector3d::Random());\n\n    // Compose the two poses.\n    Pose p1(R1, t1);\n    Pose p2(R2, t2);\n    Pose composed = p1 * p2;\n\n    // Get the deltas between p1 and p2, and between p2 and p1. These should be\n    // inverses of one another.\n    Pose p12 = p1.Delta(p2);\n    Pose p21 = p2.Delta(p1);\n    EXPECT_TRUE(p12.IsApprox(p21.Inverse()));\n\n    // Make sure the deltas are what we would expect.\n    Matrix4d Rt1(Matrix4d::Identity());\n    Rt1.block(0, 0, 3, 3) = R1;\n    Rt1.block(0, 3, 3, 1) = t1;\n\n    Matrix4d Rt2(Matrix4d::Identity());\n    Rt2.block(0, 0, 3, 3) = R2;\n    Rt2.block(0, 3, 3, 1) = t2;\n\n    Matrix4d expected_delta12 = Rt1.inverse() * Rt2;\n    Matrix4d expected_delta21 = Rt2.inverse() * Rt1;\n    EXPECT_TRUE(expected_delta12.isApprox(p12.Get()));\n    EXPECT_TRUE(expected_delta21.isApprox(p21.Get()));\n  }\n\n}\n\n} // namespace bsfm\n", "meta": {"hexsha": "dee5d8cc2852461ab157a595997f861383271936", "size": 4271, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_pose.cpp", "max_stars_repo_name": "jamesdsmith/berkeley_sfm", "max_stars_repo_head_hexsha": "de3ae6b104602c006d939b1f3da8c497b86d39ff", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 21.0, "max_stars_repo_stars_event_min_datetime": "2016-01-14T13:52:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-03T19:30:33.000Z", "max_issues_repo_path": "test/test_pose.cpp", "max_issues_repo_name": "jamesdsmith/berkeley_sfm", "max_issues_repo_head_hexsha": "de3ae6b104602c006d939b1f3da8c497b86d39ff", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-10-17T17:01:46.000Z", "max_issues_repo_issues_event_max_datetime": "2015-10-22T20:59:43.000Z", "max_forks_repo_path": "test/test_pose.cpp", "max_forks_repo_name": "erik-nelson/berkeley_sfm", "max_forks_repo_head_hexsha": "5bf0b45fac176ff7abfca0ff690893c1afc73c51", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2016-01-22T06:23:59.000Z", "max_forks_repo_forks_event_max_datetime": "2018-01-16T03:54:33.000Z", "avg_line_length": 35.5916666667, "max_line_length": 79, "alphanum_fraction": 0.6942168111, "num_tokens": 1138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799253, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.4695924426401351}}
{"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 <Eigen/Core>\n#include <Eigen/Geometry>\n#include <algorithm>\n#include <glog/logging.h>\n\n#include \"theia/matching/feature_correspondence.h\"\n#include \"theia/sfm/pose/essential_matrix_utils.h\"\n#include \"theia/sfm/pose/test_util.h\"\n#include \"theia/sfm/pose/util.h\"\n#include \"theia/util/random.h\"\n#include \"gtest/gtest.h\"\n\nnamespace theia {\n\nusing Eigen::Matrix3d;\nusing Eigen::Vector3d;\n\nRandomNumberGenerator rng(51);\n\nTEST(DecomposeEssentialMatrix, BasicTest) {\n  const double kTranslationTolerance = 1e-6;\n  const double kRotationTolerance = 1e-4;\n\n  for (int i = 0; i < 100; i++) {\n    const Matrix3d gt_rotation = RandomRotation(10.0, &rng);\n    const Vector3d gt_translation = rng.RandVector3d().normalized();\n    const Matrix3d essential_matrix =\n        CrossProductMatrix(gt_translation) * gt_rotation;\n\n    Matrix3d rotation1, rotation2;\n    Vector3d translation;\n    DecomposeEssentialMatrix(\n        essential_matrix, &rotation1, &rotation2, &translation);\n\n    const double translation_dist =\n        std::min((translation - gt_translation).norm(),\n                 (translation + gt_translation).norm());\n\n    const Eigen::AngleAxisd rotation1_aa(gt_rotation.transpose() * rotation1);\n    const Eigen::AngleAxisd rotation2_aa(gt_rotation.transpose() * rotation2);\n    const double rotation1_dist = rotation1_aa.angle();\n    const double rotation2_dist = rotation2_aa.angle();\n\n    EXPECT_TRUE(translation_dist < kTranslationTolerance &&\n                (rotation1_dist < kRotationTolerance ||\n                 rotation2_dist < kRotationTolerance));\n  }\n}\n\nTEST(EssentialMatrixFromTwoProjectionMatrices, BasicTest) {\n  const double kTranslationTolerance = 1e-6;\n  const double kRotationTolerance = 1e-4;\n\n  for (int i = 0; i < 100; i++) {\n    const Eigen::Matrix3d in_rotation1 = RandomRotation(10.0, &rng);\n    const Eigen::Vector3d in_position1 =\n        Eigen::Vector3d::Zero();  // rng.RandVector3d().normalized();\n    const Eigen::Vector3d in_translation1 = -in_rotation1 * in_position1;\n    const Eigen::Matrix3d in_rotation2 = RandomRotation(10.0, &rng);\n    const Eigen::Vector3d in_position2 = rng.RandVector3d().normalized();\n    const Eigen::Vector3d in_translation2 = -in_rotation2 * in_position2;\n\n    Matrix3x4d proj1, proj2;\n    proj1.leftCols<3>() = in_rotation1;\n    proj1.rightCols<1>() = in_translation1;\n    proj2.leftCols<3>() = in_rotation2;\n    proj2.rightCols<1>() = in_translation2;\n\n    // Get the essential matrix.\n    Eigen::Matrix3d essential_matrix;\n    EssentialMatrixFromTwoProjectionMatrices(proj1, proj2, &essential_matrix);\n\n    Matrix3d rotation1, rotation2;\n    Vector3d translation;\n    DecomposeEssentialMatrix(\n        essential_matrix, &rotation1, &rotation2, &translation);\n\n    const Eigen::Vector3d gt_translation =\n        -in_rotation1 * (in_position2 - in_position1);\n    const double translation_dist =\n        std::min((translation - gt_translation).norm(),\n                 (translation + gt_translation).norm());\n\n    const Eigen::Matrix3d gt_rotation = in_rotation1 * in_rotation2.transpose();\n    const Eigen::AngleAxisd rotation1_aa(gt_rotation.transpose() * rotation1);\n    const Eigen::AngleAxisd rotation2_aa(gt_rotation.transpose() * rotation2);\n    const double rotation1_dist = rotation1_aa.angle();\n    const double rotation2_dist = rotation2_aa.angle();\n\n    ASSERT_TRUE(translation_dist < kTranslationTolerance);\n    ASSERT_TRUE(rotation1_dist < kRotationTolerance ||\n                rotation2_dist < kRotationTolerance);\n  }\n}\n\nvoid TestGetBestPoseFromEssentialMatrix(const int num_inliers,\n                                        const int num_outliers) {\n  static const double kTolerance = 1e-12;\n\n  for (int i = 0; i < 100; i++) {\n    const Matrix3d gt_rotation = RandomRotation(15.0, &rng);\n\n    const Vector3d gt_translation = rng.RandVector3d().normalized();\n    const Vector3d gt_position = -gt_rotation.transpose() * gt_translation;\n    const Matrix3d essential_matrix =\n        CrossProductMatrix(gt_translation) * gt_rotation;\n\n    // Create Correspondences.\n    std::vector<FeatureCorrespondence> correspondences;\n    for (int j = 0; j < num_inliers; j++) {\n      // Make sure the point is in front of the camera.\n      const Vector3d point_3d = rng.RandVector3d() + Vector3d(0, 0, 100);\n      const Vector3d proj_3d = gt_rotation * point_3d + gt_translation;\n\n      FeatureCorrespondence correspondence;\n      correspondence.feature1.point_ = point_3d.hnormalized();\n      correspondence.feature2.point_ = proj_3d.hnormalized();\n      correspondences.emplace_back(correspondence);\n    }\n\n    // Add outliers\n    for (int j = 0; j < num_outliers; j++) {\n      // Make sure the point is in front of the camera.\n      const Vector3d point_3d = rng.RandVector3d() + Vector3d(0, 0, -100);\n      const Vector3d proj_3d = gt_rotation * point_3d + gt_translation;\n\n      FeatureCorrespondence correspondence;\n      correspondence.feature1.point_ = point_3d.hnormalized();\n      correspondence.feature2.point_ = proj_3d.hnormalized();\n      correspondences.emplace_back(correspondence);\n    }\n\n    Matrix3d estimated_rotation;\n    Vector3d estimated_position;\n    const int num_points_in_front =\n        GetBestPoseFromEssentialMatrix(essential_matrix,\n                                       correspondences,\n                                       &estimated_rotation,\n                                       &estimated_position);\n\n    // Ensure that the results are correct. Sincer there is no noise we can\n    // expect te number of point in front to be exact.\n    EXPECT_EQ(num_points_in_front, num_inliers);\n    EXPECT_LT((gt_rotation - estimated_rotation).norm(), kTolerance);\n    EXPECT_LT((gt_position - estimated_position).norm(), kTolerance);\n  }\n}\n\nTEST(GetBestPoseFromEssentialMatrix, AllInliers) {\n  static const int kNumInliers = 100;\n  static const int kNumOutliers = 0;\n  TestGetBestPoseFromEssentialMatrix(kNumInliers, kNumOutliers);\n}\n\nTEST(GetBestPoseFromEssentialMatrix, MostlyInliers) {\n  static const int kNumInliers = 100;\n  static const int kNumOutliers = 50;\n  TestGetBestPoseFromEssentialMatrix(kNumInliers, kNumOutliers);\n}\n\n}  // namespace theia\n", "meta": {"hexsha": "616b24be3682f6baf08270763d8b296185b3b235", "size": 7955, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/sfm/pose/essential_matrix_utils_test.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/essential_matrix_utils_test.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/essential_matrix_utils_test.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": 40.5867346939, "max_line_length": 80, "alphanum_fraction": 0.7156505343, "num_tokens": 1896, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.46956967315380116}}
{"text": "/* Copyright 2017 Battelle Energy Alliance, LLC\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n   http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*/\n/*\n *\n *  Created on: April 28, 2012\n *      Author: MANDD\n *\n *      Tests  : None for the custom\n *\n *      Problems : None\n *      Issues  : None\n *      Complaints : None\n *      Compliments : None\n *\n *      source: Numerical Recipes in C++ 3rd edition\n *\n */\n\n#include <sstream>\n#include <fstream>\n#include <ctime>\n#include <cstdlib>\n#include <vector>\n#include <iostream>\n#include <string>\n#include <iostream>\n#include <cmath> // to use erfc error function\n#include <ctime> // for rand() and srand()\n#include <cstdio>\n\n#include \"distribution_1D.h\"\n#include \"distributionFunctions.h\"\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n\n//#include <Eigen/Dense>\n#include <Eigen/SVD>\n#define throwError(msg) { std::cerr << \"\\n\\n\" << msg << \"\\n\\n\"; throw std::runtime_error(\"Error\"); }\n\n#define _USE_MATH_DEFINES\n\n/*\nextern \"C\" {\n    // LU decomoposition of a general matrix\n    void dgetrf_(int* M, int *N, double* A, int* lda, int* IPIV, int* INFO);\n\n    // generate inverse of a matrix given its LU decomposition\n    void dgetri_(int* N, double* A, int* lda, int* IPIV, double* WORK, int* lwork, int* INFO);\n}\n*/\n\ntypedef boost::numeric::ublas::matrix<double> matrixDouble;\n\nvoid matrixConversionBoost(const std::vector<std::vector<double> > & original, matrixDouble & converted)\n{\n  converted.resize(original.size(),original.at(0).size());\n  for(unsigned int r=0; r < original.size(); r++)\n  {\n    for(unsigned int c=0; c < original.at(r).size(); c++)\n    {\n      converted(r,c)  = original.at(r).at(c);\n    }\n  }\n}\n\n/*\nvoid matrixConversion(std::vector<std::vector<double> > original, double converted[]){\n        if (original.size() == original[0].size()){\n                int dimensions = original.size();\n                for (int r=0; r<dimensions; r++)\n                        for (int c=0; c<dimensions; c++){\n                                converted[r*dimensions+c] = original[r][c];\n                        }\n        }else\n                throwError(\"Error in matrixConversion: matrix is not squared.\");\n}\n*/\n\nvoid matrixBackConversionBoost(const matrixDouble & original, std::vector<std::vector<double> > & converted)\n{\n  for(unsigned int r=0; r < original.size1(); r++)\n  {\n    for(unsigned int c = 0; c < original.size2(); c++)\n    {\n      converted.at(r).at(c) = original(r,c);\n    }\n  }\n}\n\n/*\nvoid matrixBackConversion(double original[], std::vector<std::vector<double> > converted){\n        int dimensions = int(sizeof(original)/sizeof(double));\n        dimensions = sqrt(dimensions);\n\n        for (int r=0; r<dimensions; r++)\n                for (int c=0; c<dimensions; c++)\n                        converted[r][c] = original[r*dimensions+c];\n}\n*/\n\n/*\n//http://stackoverflow.com/questions/3519959/computing-the-inverse-of-a-matrix-using-lapack-in-c\nvoid inverseMatrix(double* a, int n)\n{\n    int *IPIV = new int[n+1];\n    int LWORK = n*n;\n    double *WORK = new double[LWORK];\n    int INFO;\n\n    dgetrf_(&n,&n,a,&n,IPIV,&INFO);\n    dgetri_(&n,a,&n,IPIV,WORK,&LWORK,&INFO);\n\n    delete IPIV;\n    delete WORK;\n}\n*/\n\n//Roughly based on http://savingyoutime.wordpress.com/2009/09/21/c-matrix-inversion-boostublas/ and libs/numeric/ublas/test/test_lu.cpp\nvoid invertMatrixBoost(matrixDouble & a, matrixDouble & aInverted)\n{\n  boost::numeric::ublas::permutation_matrix<std::size_t> pm(a.size1());\n\n  boost::numeric::ublas::lu_factorize<matrixDouble,\n                                      boost::numeric::ublas::permutation_matrix<> >(a, pm);\n\n  aInverted.assign(boost::numeric::ublas::identity_matrix<double>(a.size1()));\n\n  boost::numeric::ublas::lu_substitute(a, pm, aInverted);\n}\n\nvoid computeInverse(const std::vector<std::vector<double> > & matrix, std::vector<std::vector<double> > & inverse){\n        int dimensions = matrix.size();\n        matrixDouble A(dimensions,dimensions),inverted(dimensions,dimensions);\n        matrixConversionBoost(matrix, A);\n        invertMatrixBoost(A,inverted);\n        matrixBackConversionBoost(inverted, inverse);\n}\n\n// Convert the vector of covariance to vector of vector of covariance\nvoid  vectorToMatrix(unsigned int &rows,unsigned int &columns,std::vector<double> &vec_matrix, std::vector<std::vector<double> > &cov_matrix) {\n        /** Input Parameter\n         * vec_matrix: covariance matrix stored in a vector\n         * Output Parameter\n         * rows: the first dimension of the covariance matrix\n         * columns: the second dimension of the covariance matrix\n         * cov_matrix: covariance matrix stored in vector<vector<double> >\n         */\n        unsigned int dimensions = vec_matrix.size();\n        dimensions = std::lround(std::sqrt(dimensions));\n        rows = dimensions;\n        columns = dimensions;\n        if(rows*columns != vec_matrix.size())\n                      throwError(\"MultivariateNormal error: covariance matrix in is not a square matrix.\");\n        for (unsigned int row = 0; row < rows; ++row) {\n                std::vector<double> temp;\n                for (unsigned int colm = 0; colm < columns; ++colm) {\n                        temp.push_back(vec_matrix.at(colm+row*columns));\n                }\n                cov_matrix.push_back(temp);\n        }\n}\n\n//See for example http://en.wikipedia.org/wiki/LU_decomposition or\n// http://programmingexamples.net/wiki/CPP/Boost/Math/uBLAS/determinant\ndouble getDeterminantBoost(matrixDouble & a)\n{\n  boost::numeric::ublas::permutation_matrix<std::size_t> pm(a.size1());\n  double determinant = 1.0;\n\n  int result = boost::numeric::ublas::lu_factorize<matrixDouble,boost::numeric::ublas::permutation_matrix<> >(a, pm);\n\n  if(result)\n  {\n    return 0.0;\n  }\n  //det(a) = det(P^-1)det(L)det(U) = (-1)^S*(product(u_ii))\n  //Where S is the number of row exchanges\n  for(unsigned int i = 0; i < a.size1(); i++)\n  {\n    //Multiple by current diagonal entry\n    determinant *= a(i,i);\n    if(i != pm(i))\n    {\n      //Found a row exchange\n      determinant *= -1;\n    }\n\n  }\n  return determinant;\n}\n\ndouble getDeterminant(std::vector<std::vector<double> > matrix){\n        int dimensions = matrix.size();\n        matrixDouble A(dimensions,dimensions);\n\n        matrixConversionBoost(matrix, A);\n\n        return getDeterminantBoost(A);\n\n}\n\n/*\ndouble getDeterminant(std::vector<std::vector<double> > matrix){\n        int dimensions = matrix.size();\n        double A [dimensions*dimensions];\n\n        matrixConversion(matrix, A);\n\n    int *IPIV = new int[dimensions+1];\n    int LWORK = dimensions*dimensions;\n    double *WORK = new double[LWORK];\n    int INFO;\n\n    dgetrf_(&dimensions,&dimensions,A,&dimensions,IPIV,&INFO);\n\n    double determinant =1;\n\n    for(int index=0; index<dimensions; index++)\n        determinant *= A[index*dimensions];\n\n    delete IPIV;\n    delete WORK;\n\n        return determinant;\n}\n*/\n\nvoid svdDecomposition(const std::vector<std::vector<double> > &matrix, std::vector<std::vector<double> > &left_singular_vectors, std::vector<std::vector<double> > &right_singular_vectors, std::vector<double> &singular_values, std::vector<std::vector<double> > &transformed_matrix) {\n  /**\n   * This function compute the singular value decomposition for given matrix\n   * Input Parameters\n   * matrix: provided data\n   * Output Parameters\n   * left_singular_vectors: stores the left singular vectors for given matrix\n   * right_singular_vectors: stores the right singular vectors for given matrix\n   * singular_values: stores the singular values for given matrix\n   * transformed_matrix: stores the transformation matrix\n   */\n  unsigned int row = matrix.size();\n  unsigned int col = matrix.at(0).size();\n  unsigned int dim = 0;\n  if(row > col) {\n    dim = col;\n  }else {\n    dim = row;\n  }\n  Eigen::MatrixXd A(row,col);\n  Eigen::MatrixXd U(row,row);\n  Eigen::MatrixXd V(col,col);\n  Eigen::MatrixXd X(row,dim);\n  Eigen::VectorXd S(dim);\n  matrixConversionToEigenType(matrix,A);\n  Eigen::JacobiSVD<Eigen::MatrixXd> svd(A,Eigen::ComputeFullU | Eigen::ComputeFullV);\n  U = svd.matrixU();\n  V = svd.matrixV();\n  S = svd.singularValues();\n  for(unsigned int i = 0; i < dim; ++i) {\n    X.col(i) = U.col(i)*sqrt(S(i));\n  }\n  matrixConversionToCxxVVectorType(U,left_singular_vectors);\n  matrixConversionToCxxVVectorType(V,right_singular_vectors);\n  vectorConversionToCxxVectorType(S,singular_values);\n  matrixConversionToCxxVVectorType(X,transformed_matrix);\n}\n\nvoid getInverseTransformedMatrix(const std::vector<std::vector<double> > &left_singular_vectors, std::vector<double> &singular_values, std::vector<std::vector<double> > &inverse_transformed_matrix) {\n  /**\n   * This function compute the inverse transformation matrix\n   * Input Parameters\n   * left_singular_vectors: stores the left singular vectors for given matrix\n   * singular_values: stores the singular values for given matrix\n   * Output Parameters\n   * inverse_transformed_matrix: stores the inverse transformation matrix\n   */\n  unsigned int row = left_singular_vectors.size();\n  unsigned int col = left_singular_vectors.at(0).size();\n  unsigned int dim = singular_values.size();\n  Eigen::MatrixXd U(row,col);\n  Eigen::MatrixXd inverseX(row,dim);\n  matrixConversionToEigenType(left_singular_vectors,U);\n  for (unsigned int i = 0; i < dim; ++i) {\n    if (singular_values.at(i) == 0) {\n      inverseX.col(i) = U.col(i) * 0.0;\n    } else {\n      inverseX.col(i) = U.col(i) * (1.0/sqrt(singular_values.at(i)));\n    }\n  }\n  matrixConversionToCxxVVectorType(inverseX.transpose(),inverse_transformed_matrix);\n}\n\nvoid svdDecomposition(const std::vector<std::vector<double> > &matrix, std::vector<std::vector<double> > &left_singular_vectors, std::vector<std::vector<double> > &right_singular_vectors, std::vector<double> &singular_values, std::vector<std::vector<double> > &transformed_matrix, unsigned int rank) {\n  /**\n   * This function compute the singular value decomposition for given matrix\n   * Input Parameters\n   * matrix: provided data\n   * Output Parameters\n   * left_singular_vectors: stores the left singular vectors for given matrix\n   * right_singular_vectors: stores the right singular vectors for given matrix\n   * singular_values: stores the singular values for given matrix\n   * rank: used for truncated svd, the number of singular values that will be kept for truncated svd\n   */\n  unsigned int row = matrix.size();\n  unsigned int col = matrix.at(0).size();\n  unsigned int dim = 0;\n  if(row > col) {\n    dim = col;\n  }else {\n    dim = row;\n  }\n  Eigen::MatrixXd A(row,col);\n  Eigen::MatrixXd U(row,row);\n  Eigen::MatrixXd V(col,col);\n  Eigen::MatrixXd X(row,rank);\n  Eigen::VectorXd S(dim);\n  matrixConversionToEigenType(matrix,A);\n  Eigen::JacobiSVD<Eigen::MatrixXd> svd(A,Eigen::ComputeFullU | Eigen::ComputeFullV);\n  U = svd.matrixU();\n  V = svd.matrixV();\n  S = svd.singularValues();\n  for(unsigned int i = 0; i < rank; ++i) {\n    X.col(i) = U.col(i)*sqrt(S(i));\n  }\n  // transform and store the matrix for the truncated svd\n  matrixConversionToCxxVVectorType(U.block(0,0,row,rank),left_singular_vectors);\n  matrixConversionToCxxVVectorType(V.block(0,0,col,rank),right_singular_vectors);\n  vectorConversionToCxxVectorType(S.head(rank),singular_values);\n  matrixConversionToCxxVVectorType(X,transformed_matrix);\n}\n\nvoid  computeNearestSymmetricMatrix(const std::vector<std::vector<double> > &matrix, std::vector<std::vector<double> > &symmetric_matrix) {\n  /**\n   * This function used to compute the nearest symmetric matrix\n   * Input Parameters\n   * matrix: std::vector<std::vector<double> >, given matrix\n   * Output Parameters\n   * symmetric_matrix: std::vector<std::vector<double> >, the computed symmetric matrix\n   */\n  unsigned int row = matrix.size();\n  unsigned int col = matrix.at(0).size();\n  if (row != col) {\n    throwError(\"The provided matrix is not a square matrix!\" );\n  }\n  Eigen::MatrixXd A(row,col);\n  Eigen::MatrixXd B(col,row);\n  matrixConversionToEigenType(matrix,A);\n  B = A.transpose();\n  A = (A + B)*0.5;\n  matrixConversionToCxxVVectorType(A,symmetric_matrix);\n}\n\nvoid resetSingularValues(std::vector<std::vector<double> > &left_singular_vectors, std::vector<std::vector<double> > &right_singular_vectors, std::vector<double> &singular_values,std::vector<std::vector<double> > &transformed_matrix) {\n  /**\n   * used to reset singular values\n   * Input Parameters\n   * left_singular_vectors: std::vector<std::vector<double> >, the left singular vectors\n   * right_singular_vectors: std::vector<std::vector<double> >, the right singular vectors\n   * singular_values: std::vector<double>, the singular values\n   * transformed_matrix: std::vector<vector<double> >, the transformation matrix\n   * Output Parameters\n   * singular_values: std::vector<double>, the modified singular values\n   * transformed_matrix: std::vector<vector<double> >, the updated transformation matrix\n   */\n  unsigned int row1 = left_singular_vectors.size();\n  unsigned int col1 = left_singular_vectors.at(0).size();\n  unsigned int row2 = right_singular_vectors.size();\n  unsigned int col2 = right_singular_vectors.at(0).size();\n  unsigned int rank = transformed_matrix.at(0).size();\n  if (row1 != row2 && col1 != col2) {\n    throwError(\"The provided matrices should have the same shape!\" );\n  }\n  Eigen::MatrixXd A(row1,col1);\n  Eigen::MatrixXd B(row2,col2);\n  Eigen::MatrixXd X(row1,rank);\n  matrixConversionToEigenType(left_singular_vectors,A);\n  matrixConversionToEigenType(right_singular_vectors,B);\n  double tol;\n  tol = 1.0E-15;\n  if (singular_values.at(0) == 0.0) {\n    throwError(\"The provided covariance matrix is zero matrix!\")\n  }\n  for (unsigned int i = 0; i < singular_values.size(); ++i) {\n    if ((A.col(i) + B.col(i)).lpNorm<1>()/row1 < tol) {\n      singular_values.at(i) = 0.0;\n    }\n    if (singular_values.at(i)/singular_values.at(0) < tol) {\n      singular_values.at(i) = 0.0;\n    }\n  }\n  for(unsigned int i = 0; i < rank; ++i) {\n    X.col(i) = A.col(i)*sqrt(singular_values.at(i));\n  }\n  transformed_matrix.clear();\n  matrixConversionToCxxVVectorType(X,transformed_matrix);\n}\n\n\nvoid matrixConversionToEigenType(std::vector<std::vector<double> > original, Eigen::MatrixXd &converted) {\n  /**\n   * This function convert the data from type std::vector<std::vector<double> > to Eigen::MatrixXd\n   * Input Parameters\n   * original: provided data with the type of std::vector<std::vector<double> >\n   * Output Parameters\n   * converted: output data with the type of Eigen::MatrixXd\n   */\n  converted.resize(original.size(),original.at(0).size());\n  for(unsigned int row = 0; row < original.size(); ++row) {\n    for(unsigned int col = 0; col < original.at(0).size(); ++col) {\n      if(original.at(0).size() != original.at(row).size()) {\n        throwError(\"The matrix stored in the C++ vector container with different lenght of columns\");\n      }\n      converted(row,col) = original.at(row).at(col);\n    }\n  }\n}\n\nvoid matrixConversionToCxxVVectorType(const Eigen::MatrixXd & original, std::vector<std::vector<double> > &converted) {\n  /**\n   * This function convert the data from type Eigen::MatrixXd to type std::vector<double>\n   * Input Parameters\n   * original: provided data with the type of Eigen::MatrixXd\n   * Output Parameters\n   * converted: output data with the type of std::vector<std::vector<double> >\n   */\n  for(unsigned int row = 0; row < original.rows(); ++row) {\n    std::vector<double> temp;\n    for(unsigned int col = 0; col < original.cols(); ++col) {\n      temp.push_back(original(row,col));\n    }\n    converted.push_back(temp);\n  }\n}\n\nvoid vectorConversionToCxxVectorType(const Eigen::VectorXd & original, std::vector<double> &converted) {\n  /**\n   * This function convert the data from type Eigen::VectorXd to type std::vector<double>\n   * Input Parameters\n   * original: provided data with the type of Eigen::VectorXd\n   * Output Parameters\n   * converted: output data with the type of std::vector<double>\n   */\n  for(unsigned int dim = 0; dim < original.rows(); ++dim) {\n    converted.push_back(original(dim));\n  }\n}\n\n// void nrerror(const char error_text[]){     // added const to avoid \"warning: deprecated conversion from string constant to *char\n// /* Numerical Recipes standard error handler */\n//  fprintf(stderr,\"Numerical Recipes run-time error...\\n\");\n//  fprintf(stderr,\"%s\\n\",error_text);\n//  fprintf(stderr,\"...now exiting to system...\\n\");\n// }\n//\n// double gammp(double a, double x){\n// /* high level function for incomplete gamma function */\n//         void gcf(double *gammcf,double a,double x,double *gln);\n//         void gser(double *gamser,double a,double x,double *gln);\n//         double gamser,gammcf,gln;\n//         if(x < 0.0 || a <= 0.0) nrerror(\"Invalid arg in gammp\");\n//         if(x < (a+1.0)){\n// /* here I change routine so that it returns \\gamma(a,x)\n//         or P(a,x)-just take out comments to get P(a,x) vs \\gamma(a,x)-\n//         to get latter use the exp(log(.)+gln) expression */\n//                gser(&gamser,a,x,&gln);\n// //      return exp(log(gamser)+gln);\n//                return gamser;\n//         }\n//         else{\n//                gcf(&gammcf,a,x,&gln);\n// //      return exp(log(1.0-gammcf)+gln);\n//                return 1.0-gammcf;\n//         }\n// }\n//\n// double loggam(double xx)\n// {\n//         double x,y,tmp,ser;\n//         static double cof[6]={76.18009172947146, -86.50532032941677,\n//                24.01409824083091,-1.231739572450155, 0.001208650973866179,\n//                -5.395239384953e-006};\n//         int j;\n//         y=x=xx;\n//         tmp=x+5.5;\n//         tmp -= (x+0.5)*log(tmp);\n//         ser=1.000000000190015;\n//         for(j=0;j<=5;j++) ser += cof[j]/++y;\n//         return -tmp+log(2.506628274631*ser/x);\n// }\n//\n// #define ITMAX 100\n// #define EPSW 3.0e-7\n//\n// void gser(double *gamser,double a,double x,double *gln){\n//         int n;\n//         double sum,del,ap;\n//         *gln=loggam(a);\n//         if(x <= 0.0){\n//                if(x < 0.0) nrerror(\"x less than 0 in routine gser\");\n//                *gamser=0.0;\n//                return;\n//         }\n//         else{\n//                ap=a;\n//                del=sum=1.0/a;\n//                for(n=1;n<=ITMAX;n++){\n//                       ++ap;\n//                       del *= x/ap;\n//                       sum += del;\n//                       if(fabs(del) < fabs(sum)*EPSW){\n//    *gamser=sum*exp(-x+a*log(x)-(*gln));\n//    return;\n//                       }\n//                }\n//                nrerror(\"a too large, ITMAX too small in routine gser\");\n//                return;\n//         }\n// }\n//\n//\n// #define FPMIN 1.0e-30\n//\n// void gcf(double *gammcf,double a,double x,double *gln){\n//         int i;\n//         double an,b,c,d,del,h;\n//         *gln=loggam(a);\n//         b=x+1.0-a;\n//         c=1.0/FPMIN;\n//         d=1.0/b;\n//         h=d;\n//         for(i=1;i<=ITMAX;i++){\n//                an = -i*(i-a);\n//                b += 2.0;\n//                d=an*d+b;\n//                if(fabs(d) < FPMIN) d=FPMIN;\n//                c=b+an/c;\n//                if(fabs(c) < FPMIN) c=FPMIN;\n//                d=1.0/d;\n//                del=d*c;\n//                h *= del;\n//                if(fabs(del-1.0) < EPSW) break;\n//         }\n//         if(i > ITMAX) nrerror(\"a too large, ITMAX too small in gcf\");\n//         *gammcf=exp(-x+a*log(x)-(*gln))*h;\n// }\n//\n// // Gamma function\n// // source http://www.crbond.com/math.htm\n// double gammaFunc(double x){\n//  int i,k,m;\n//  double ga,gr,r,z;\n//\n//  static double g[] = {\n//   1.0,\n//   0.5772156649015329,\n//                 -0.6558780715202538,\n//                 -0.420026350340952e-1,\n//   0.1665386113822915,\n//                 -0.421977345555443e-1,\n//                 -0.9621971527877e-2,\n//   0.7218943246663e-2,\n//                 -0.11651675918591e-2,\n//                 -0.2152416741149e-3,\n//   0.1280502823882e-3,\n//                 -0.201348547807e-4,\n//                 -0.12504934821e-5,\n//   0.1133027232e-5,\n//                 -0.2056338417e-6,\n//   0.6116095e-8,\n//   0.50020075e-8,\n//                 -0.11812746e-8,\n//   0.1043427e-9,\n//   0.77823e-11,\n//                 -0.36968e-11,\n//   0.51e-12,\n//                 -0.206e-13,\n//                 -0.54e-14,\n//   0.14e-14};\n//\n//  if (x > 171.0) return 1e308;    // This value is an overflow flag.\n//  if (x == (int)x) {\n//   if (x > 0.0) {\n//    ga = 1.0;               // use factorial\n//    for (i=2;i<x;i++) {\n//                                 ga *= i;\n//    }\n//                       }\n//                       else\n//    ga = 1e308;\n//               }\n//               else {\n//   if (fabs(x) > 1.0) {\n//    z = fabs(x);\n//    m = (int)z;\n//    r = 1.0;\n//    for (k=1;k<=m;k++)\n//     r *= (z-k);\n//    z -= m;\n//   }\n//   else\n//    z = x;\n//   gr = g[24];\n//   for (k=23;k>=0;k--)\n//    gr = gr*z+g[k];\n//\n//   ga = 1.0/(gr*z);\n//   if (fabs(x) > 1.0) {\n//    ga *= r;\n//    if (x < 0.0)\n//     ga = -M_PI/(x*ga*sin(M_PI*x));\n//   }\n//  }\n//  return ga;\n// }\n//\n//\n// // Beta function\n// double betaFunc(double alpha, double beta){\n//  double value=gammaFunc(alpha)*gammaFunc(beta)/gammaFunc(alpha+beta);\n//  return value;\n// }\n//\n//\n// // log gamma using the Lanczos approximation\n// double logGamma(double x) {\n// const double c[8] = { 676.5203681218851, -1259.1392167224028,\n//                       771.32342877765313, -176.61502916214059,\n//                       12.507343278686905, -0.13857109526572012,\n//                       9.9843695780195716e-6, 1.5056327351493116e-7 };\n// double sum = 0.99999999999980993;\n// double y = x;\n// for (int j = 0; j < 8; j++)\n//        sum += c[j] / ++y;\n// return log(sqrt(2*3.14159) * sum / x) - (x + 7.5) + (x + 0.5) * log(x + 7.5);\n// }\n//\n// // helper function for incomplete beta\n// // computes continued fraction\n//\n// double betaContFrac(double a, double b, double x) {\n//  const int MAXIT = 1000;\n//  const double EPS = 3e-7;\n//  double qab = a + b;\n//  double qap = a + 1;\n//  double qam = a - 1;\n//  double c = 1;\n//  double d = 1 - qab * x / qap;\n//  if (fabs(d) < FPMIN) d = FPMIN;\n//  d = 1 / d;\n//  double h = d;\n//  int m;\n//  for (m = 1; m <= MAXIT; m++) {\n//                int m2 = 2 * m;\n//                double aa = m * (b-m) * x / ((qam + m2) * (a + m2));\n//                d = 1 + aa * d;\n//                if (fabs(d) < FPMIN) d = FPMIN;\n//                c = 1 + aa / c;\n//                if (fabs(c) < FPMIN) c = FPMIN;\n//                d = 1 / d;\n//                h *= (d * c);\n//                aa = -(a+m) * (qab+m) * x / ((a+m2) * (qap+m2));\n//                d = 1 + aa * d;\n//                if (fabs(d) < FPMIN) d = FPMIN;\n//                c = 1 + aa / c;\n//                if (fabs(c) < FPMIN) c = FPMIN;\n//                d = 1 / d;\n//                double del = d*c;\n//                h *= del;\n//                if (fabs(del - 1) < EPS) break;\n//  }\n//  if (m > MAXIT) {\n//                cerr << \"betaContFrac: too many iterations\\n\";\n//  }\n//  return h;\n// }\n//\n// // incomplete beta function\n// // must have 0 <= x <= 1\n// double betaInc(double a, double b, double x) {\n//        if (x == 0)\n//  return 0;\n//        else if (x == 1)\n//  return 1;\n//        else {\n//  double logBeta = logGamma(a+b) - logGamma(a) - logGamma(b)\n//                + a * log(x) + b * log(1-x);\n//  if (x < (a+1) / (a+b+2))\n//                return exp(logBeta) * betaContFrac(a, b, x) / a;\n//  else\n//                return 1 - exp(logBeta) * betaContFrac(b, a, 1-x) / b;\n//        }\n// }\n//\n// double normRNG(double mu, double sigma, double RNG) {\n//  static bool deviateAvailable=false;                        //        flag\n//  static float storedDeviate;                        //        deviate from previous calculation\n//  double polar, rsquared, var1, var2;\n//  //srand(time(NULL));\n//  //srand((unsigned)time(0));\n//  //srand(time(0));\n//  //Ran ran(time(0));\n//  //        If no deviate has been stored, the polar Box-Muller transformation is\n//  //        performed, producing two independent normally-distributed random\n//  //        deviates.  One is stored for the next round, and one is returned.\n//  if (!deviateAvailable) {\n//\n//   //        choose pairs of uniformly distributed deviates, discarding those\n//   //        that don't fall within the unit circle\n//   do {\n//    var1 = 2.0*( RNG ) - 1.0;\n//    var2 = 2.0*( RNG ) - 1.0;\n//\n//    //var1=2.0*( ran.doub() ) - 1.0;\n//    //var2=2.0*( ran.doub() ) - 1.0;\n//\n//    rsquared=var1*var1+var2*var2;\n//   } while ( rsquared>=1.0 || rsquared == 0.0);\n//\n//   //        calculate polar transformation for each deviate\n//   polar=sqrt(-2.0*log(rsquared)/rsquared);\n//\n//   //        store first deviate and set flag\n//   storedDeviate=var1*polar;\n//   deviateAvailable=true;\n//\n//   //        return second deviate\n//   return var2*polar*sigma + mu;\n//  }\n//\n//  //        If a deviate is available from a previous call to this function, it is\n//  //        returned, and the flag is set to false.\n//  else {\n//   deviateAvailable=false;\n//   return storedDeviate*sigma + mu;\n//  }\n// }\n//\n//\n// void loadData(double** data, int dimensionality, int cardinality, string filename) {\n//        int x, y;\n//\n//        ifstream in(filename.c_str());\n//\n//        if (!in) {\n//          cout << \"Cannot open file.\\n\";\n//          return;\n//        }\n//\n//        for (y = 0; y < cardinality; y++) {\n//          for (x = 0; x < dimensionality; x++) {\n//            in >> data[y][x];\n//          }\n//        }\n//\n//        in.close();\n// }\n//\n// double calculateCustomPdf(double position, double fitting, double** data_set, int number_samples){\n//  double value=-1;\n//  double min;\n//  double max;\n//\n//  for (int i=1; i<number_samples; i++){\n//   max=data_set[i][1];\n//   min=data_set[i-1][1];\n//\n//   if((position>min)&(position<max)){\n//    if (fitting==1)\n//     value=data_set[i-1][2];\n//    else\n//     value=data_set[i-1][2]+(data_set[i][2]-data_set[i-1][2])/(data_set[i][1]-data_set[i-1][1])*(position-data_set[i-1][1]);\n//   }\n//   else\n//    perror (\"The following error occurred: distribution sampled out of its boundaries\");\n//  }\n//\n//  return value;\n// }\n//\n// double calculateCustomCDF(double position, double fitting, double** data_set, int number_samples){\n//  double value=-1;\n//  double min;\n//  double max;\n//  double cumulative=0;\n//\n//  for (int i=1; i<number_samples; i++){\n//   max=data_set[i][1];\n//   min=data_set[i-1][1];\n//\n//   if((position>min)&(position<max)){\n//    if (fitting==1)\n//     value=cumulative+data_set[i-1][2]*(position-data_set[i-1][1]);\n//    else{\n//     double pdfValueInPosition =data_set[i-1][2]+(data_set[i][2]-data_set[i-1][2])/(data_set[i][1]-data_set[i-1][1])*(position-data_set[i-1][1]);\n//     value=cumulative + (pdfValueInPosition+data_set[i-1][2])*(position-data_set[i-1][1])/2;\n//    }\n//   }\n//   else\n//    perror (\"The following error occurred: distribution sampled out of its boundaries\");\n//\n//   if (fitting==1)\n//    cumulative=cumulative+data_set[i-1][2]*(data_set[i][1]-data_set[i-1][1]);\n//   else\n//    cumulative=cumulative+(data_set[i][2]+data_set[i-1][2])*(data_set[i][1]-data_set[i-1][1])/2;\n//  }\n//\n//  return value;\n// }\n//\n//        double stdGammaRNG(double shape);\n//\n// double gammaRNG(double shape, double scale){\n//  double value=scale * stdGammaRNG(shape);\n//  return value;\n// }\n//\n//        double rkGauss();\n//\n// double stdGammaRNG(double shape)\n// {\n//          double b, c;\n//          double U, V, X, Y;\n//\n//          if (shape == 1.0)\n//          {\n//              return -log(1.0 - rand());\n//          }\n//          else if (shape < 1.0)\n//          {\n//              for (;;)\n//              {\n//                  U = rand();\n//                  V = -log(1.0 - rand());\n//                  if (U <= 1.0 - shape)\n//                  {\n//                      X = pow(U, 1./shape);\n//                      if (X <= V)\n//                      {\n//                          return X;\n//                      }\n//                  }\n//                  else\n//                  {\n//                      Y = -log((1-U)/shape);\n//                      X = pow(1.0 - shape + shape*Y, 1./shape);\n//                      if (X <= (V + Y))\n//                      {\n//                          return X;\n//                      }\n//                  }\n//              }\n//          }\n//          else\n//          {\n//              b = shape - 1./3.;\n//              c = 1./sqrt(9*b);\n//              for (;;)\n//              {\n//                  do\n//                  {\n//                      X = rkGauss();\n//                      V = 1.0 + c*X;\n//                  } while (V <= 0.0);\n//\n//                  V = V*V*V;\n//                  U = rand();\n//                  if (U < 1.0 - 0.0331*(X*X)*(X*X))\n//                      return (b*V);\n//                  if (log(U) < 0.5*X*X + b*(1. - V + log(V)))\n//                      return (b*V);\n//              }\n//          }\n// }\n//\n// double rkGauss() {\n//  double f, x1, x2, r2;\n//\n//  do {\n//   x1 = 2.0*rand() - 1.0;\n//   x2 = 2.0*rand() - 1.0;\n//   r2 = x1*x1 + x2*x2;\n//  }\n//  while (r2 >= 1.0 || r2 == 0.0);\n//\n//  /* Box-Muller transform */\n//  f = sqrt(-2.0*log(r2)/r2);\n//  return f*x2;\n//\n// }\n//\n//\n// double betaRNG(double alpha, double beta){\n//  // To be updated\n//  double value=0;\n//  return value;\n// }\n//\n// double modifiedLogFunction(double x){\n//          if (x <= -1.0)\n//          {\n//              std::stringstream os;\n//              os << \"Invalid input argument (\" << x << \"); must be greater than -1.0\";\n//              throw std::invalid_argument( os.str() );\n//          }\n//\n//          if (fabs(x) > 1e-4)\n//              return log(1.0 + x);\n//          else\n//              return (-0.5*x + 1.0)*x;\n// }\n\n        double abramStegunApproximation(double t)\n        {\n            // Abramowitz and Stegun formula\n\n            double c[] = {2.515517, 0.802853, 0.010328};\n            double d[] = {1.432788, 0.189269, 0.001308};\n            return t - ((c[2]*t + c[1])*t + c[0]) /\n                       (((d[2]*t + d[1])*t + d[0])*t + 1.0);\n        }\n", "meta": {"hexsha": "4c2e7df085845a75e5b1e24e5890fb076717182b", "size": 30546, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "crow/src/distributions/distributionFunctions.cxx", "max_stars_repo_name": "rinelson456/raven", "max_stars_repo_head_hexsha": "1114246136a2f72969e75b5e99a11b35500d4eef", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 159.0, "max_stars_repo_stars_event_min_datetime": "2017-03-24T21:07:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T13:44:40.000Z", "max_issues_repo_path": "crow/src/distributions/distributionFunctions.cxx", "max_issues_repo_name": "rinelson456/raven", "max_issues_repo_head_hexsha": "1114246136a2f72969e75b5e99a11b35500d4eef", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1667.0, "max_issues_repo_issues_event_min_datetime": "2017-03-27T14:41:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T19:50:06.000Z", "max_forks_repo_path": "crow/src/distributions/distributionFunctions.cxx", "max_forks_repo_name": "rinelson456/raven", "max_forks_repo_head_hexsha": "1114246136a2f72969e75b5e99a11b35500d4eef", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 95.0, "max_forks_repo_forks_event_min_datetime": "2017-03-24T21:05:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T17:30:22.000Z", "avg_line_length": 32.7746781116, "max_line_length": 301, "alphanum_fraction": 0.5676684345, "num_tokens": 8626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702642896702, "lm_q2_score": 0.6477982247516797, "lm_q1q2_score": 0.4695696703821292}}
{"text": "#include<iostream>\n#include <armadillo>\n\nusing namespace std;\nusing namespace arma;\n\nint main()\n{\n    int nz=600;\n    int nx=400;\n\n    arma::Mat<float> model_ori(nz,nx,fill::zeros);\n    arma::Mat<float> model_str(nz,nx,fill::zeros);\n\n    model_ori.load(\"./model.dat\",raw_binary);\n    model_ori.reshape(nz,nx);\n\n    for(int ix=0; ix<nx; ix++)\n    {\n        for(int iz=1; iz<nz; iz++)\n        {\n            if(model_ori(iz,ix)-model_ori(iz-1,ix)>20)\n            {\n                model_str(iz,ix)=1;\n            }\n        }\n    }\n    model_str.save(\"model_str.dat\",raw_binary);\n\n\n\n\n    return 0;\n}\n", "meta": {"hexsha": "87a2e7d3140374cb35283c95316fa02e10f8275a", "size": 596, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "model/surface_cal.cpp", "max_stars_repo_name": "Bohan-Zhang-2017/-ELASTIC_WAVE_FD", "max_stars_repo_head_hexsha": "b2e2658b1cb24d4dbe603fa11f977f854c762add", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "model/surface_cal.cpp", "max_issues_repo_name": "Bohan-Zhang-2017/-ELASTIC_WAVE_FD", "max_issues_repo_head_hexsha": "b2e2658b1cb24d4dbe603fa11f977f854c762add", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "model/surface_cal.cpp", "max_forks_repo_name": "Bohan-Zhang-2017/-ELASTIC_WAVE_FD", "max_forks_repo_head_hexsha": "b2e2658b1cb24d4dbe603fa11f977f854c762add", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.0285714286, "max_line_length": 54, "alphanum_fraction": 0.5453020134, "num_tokens": 173, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7248702642896702, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.46956966545332357}}
{"text": "/**\n * \\file LMSFilter.cpp\n */\n\n#include <ATK/Adaptive/LMSFilter.h>\n\n#include <complex>\n#include <cstdint>\n#include <stdexcept>\n\n#include <Eigen/Core>\n\n#include <ATK/Core/TypeTraits.h>\n#include <ATK/Core/Utilities.h>\n\nnamespace ATK\n{\n  template<typename DataType_>\n  class LMSFilter<DataType_>::LMSFilterImpl\n  {\n  public:\n    using wType = Eigen::Matrix<DataType_, Eigen::Dynamic, 1>;\n    using xType = Eigen::Map<const wType>;\n\n    wType w;\n    /// Memory factor\n    double alpha = 0.99;\n    /// line search\n    double mu = 0.05;\n\n    explicit LMSFilterImpl(gsl::index size)\n    :w(wType::Zero(size))\n    {\n    }\n\n    using UpdateFunction = void (LMSFilterImpl::*)(const xType& x, DataType error);\n\n    void update(const xType& x, DataType error)\n    {\n      w = static_cast<DataType>(alpha) * w + static_cast<DataType>(mu) * error * x;\n    }\n\n    void update_normalized(const xType& x, DataType error)\n    {\n      w = static_cast<DataType>(alpha) * w + static_cast<DataType>(mu) * error * x / (std::numeric_limits<DataType>::epsilon() + static_cast<DataType>(x.squaredNorm()));\n    }\n\n    void update_signerror(const xType& x, DataType error)\n    {\n      w = static_cast<DataType>(alpha) * w + static_cast<DataType>(mu) * error / (std::numeric_limits<DataType>::epsilon() + std::abs(error)) * x;\n    }\n\n    void update_signdata(const xType& x, DataType error)\n    {\n      w = static_cast<DataType>(alpha) * w.array() + static_cast<DataType>(mu) * error * x.array() / (x.cwiseAbs().template cast<DataType>().array() + static_cast<DataType>(std::numeric_limits<DataType>::epsilon()));\n    }\n\n    void update_signsign(const xType& x, DataType error)\n    {\n      w = static_cast<DataType>(alpha) * w.array() + static_cast<DataType>(mu) * error / (std::numeric_limits<DataType>::epsilon() + std::abs(error)) * x.array() / (x.cwiseAbs().template cast<DataType>().array() + static_cast<DataType>(std::numeric_limits<DataType>::epsilon()));\n    }\n\n    UpdateFunction select(Mode mode)\n    {\n      switch (mode)\n      {\n      case Mode::NORMAL:\n        return &LMSFilterImpl::update;\n      case Mode::NORMALIZED:\n        return &LMSFilterImpl::update_normalized;\n      case Mode::SIGNERROR:\n        return &LMSFilterImpl::update_signerror;\n      case Mode::SIGNDATA:\n        return &LMSFilterImpl::update_signdata;\n      case Mode::SIGNSIGN:\n        return &LMSFilterImpl::update_signsign;\n      default:\n          throw std::range_error(\"Wrong mode for LMS filter\");\n      }\n    }\n  };\n\n  template<typename DataType_>\n  LMSFilter<DataType_>::LMSFilter(gsl::index size)\n  :Parent(2, 1), impl(std::make_unique<LMSFilterImpl>(size))\n  {\n    input_delay = size - 1;\n  }\n  \n  template<typename DataType_>\n  LMSFilter<DataType_>::~LMSFilter()\n  {\n  }\n\n  template<typename DataType_>\n  void LMSFilter<DataType_>::set_size(gsl::index size)\n  {\n    if(size == 0)\n    {\n      throw RuntimeError(\"Size must be strictly positive\");\n    }\n\n    input_delay = size - 1;\n    impl = std::make_unique<LMSFilterImpl>(size);\n  }\n\n  template<typename DataType_>\n  gsl::index LMSFilter<DataType_>::get_size() const\n  {\n    return input_delay + 1;\n  }\n  \n  template<typename DataType_>\n  void LMSFilter<DataType_>::set_memory(double memory)\n  {\n    if (memory >= 1)\n    {\n      throw ATK::RuntimeError(\"Memory must be less than 1\");\n    }\n    if (memory <= 0)\n    {\n      throw ATK::RuntimeError(\"Memory must be strictly positive\");\n    }\n\n    impl->alpha = memory;\n  }\n\n  template<typename DataType_>\n  double LMSFilter<DataType_>::get_memory() const\n  {\n    return impl->alpha;\n  }\n\n  template<typename DataType_>\n  void LMSFilter<DataType_>::set_mu(double mu)\n  {\n    if (mu >= 1)\n    {\n      throw ATK::RuntimeError(\"Mu must be less than 1\");\n    }\n    if (mu <= 0)\n    {\n      throw ATK::RuntimeError(\"Mu must be strictly positive\");\n    }\n\n    impl->mu = mu;\n  }\n\n  template<typename DataType_>\n  double LMSFilter<DataType_>::get_mu() const\n  {\n    return impl->mu;\n  }\n\n  template<typename DataType_>\n  void LMSFilter<DataType_>::set_mode(Mode mode)\n  {\n    this->mode = mode;\n  }\n\n  template<typename DataType_>\n  typename LMSFilter<DataType_>::Mode LMSFilter<DataType_>::get_mode() const\n  {\n    return mode;\n  }\n\n  template<typename DataType_>\n  void LMSFilter<DataType_>::process_impl(gsl::index size) const\n  {\n    const DataType* ATK_RESTRICT input = converted_inputs[0];\n    const DataType* ATK_RESTRICT ref = converted_inputs[1];\n    DataType* ATK_RESTRICT output = outputs[0];\n    \n    auto update_function = impl->select(mode);\n\n    for(gsl::index i = 0; i < size; ++i)\n    {\n      typename LMSFilterImpl::xType x(input - input_delay + i, input_delay + 1, 1);\n      output[i] = impl->w.conjugate().dot(x);\n      if(learning)\n      {\n        (impl.get()->*update_function)(x, TypeTraits<DataType>::conj(ref[i] - output[i]));\n      }\n    }\n  }\n\n  template<typename DataType_>\n  const DataType_* LMSFilter<DataType_>::get_w() const\n  {\n    return impl->w.data();\n  }\n  \n  template<typename DataType_>\n  void LMSFilter<DataType_>::set_w(gsl::not_null<const DataType_*> w)\n  {\n    impl->w = Eigen::Map<const typename LMSFilterImpl::wType>(w.get(), get_size());\n  }\n\n  template<typename DataType_>\n  void LMSFilter<DataType_>::set_learning(bool learning)\n  {\n    this->learning = learning;\n  }\n\n  template<typename DataType_>\n  bool LMSFilter<DataType_>::get_learning() const\n  {\n    return learning;\n  }\n\n  template class LMSFilter<double>;\n#if ATK_ENABLE_INSTANTIATION\n  template class LMSFilter<float>;\n  template class LMSFilter<std::complex<float>>;\n  template class LMSFilter<std::complex<double>>;\n#endif\n}\n", "meta": {"hexsha": "2c42f0fe1fb5c6460f1ccd0401f1ddede5407519", "size": 5597, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ATK/Adaptive/LMSFilter.cpp", "max_stars_repo_name": "D-J-Roberts/AudioTK", "max_stars_repo_head_hexsha": "accf009d7238f32702eb1d5ee23c5148fc68e3bd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 249.0, "max_stars_repo_stars_event_min_datetime": "2015-01-05T13:36:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T18:47:46.000Z", "max_issues_repo_path": "ATK/Adaptive/LMSFilter.cpp", "max_issues_repo_name": "D-J-Roberts/AudioTK", "max_issues_repo_head_hexsha": "accf009d7238f32702eb1d5ee23c5148fc68e3bd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 22.0, "max_issues_repo_issues_event_min_datetime": "2015-07-28T15:20:24.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-11T14:18:19.000Z", "max_forks_repo_path": "ATK/Adaptive/LMSFilter.cpp", "max_forks_repo_name": "D-J-Roberts/AudioTK", "max_forks_repo_head_hexsha": "accf009d7238f32702eb1d5ee23c5148fc68e3bd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 48.0, "max_forks_repo_forks_event_min_datetime": "2015-08-15T12:08:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-07T02:33:07.000Z", "avg_line_length": 25.6743119266, "max_line_length": 279, "alphanum_fraction": 0.6524924066, "num_tokens": 1514, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.46943613051416405}}
{"text": "// This file is part of OpenCV project.\n// It is subject to the license terms in the LICENSE file found in the top-level directory\n// of this distribution and at http://opencv.org/license.html\n\n#include <iostream>\n#include <unordered_map>\n\n#include \"opencv2/core/base.hpp\"\n#include \"opencv2/core/types.hpp\"\n\n#if defined(HAVE_EIGEN)\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n#include <Eigen/SparseCholesky>\n\n#include \"opencv2/core/eigen.hpp\"\n#endif\n\nnamespace cv\n{\nnamespace kinfu\n{\n/*!\n * \\class BlockSparseMat\n * Naive implementation of Sparse Block Matrix\n */\ntemplate<typename _Tp, int blockM, int blockN>\nstruct BlockSparseMat\n{\n    struct Point2iHash\n    {\n        size_t operator()(const cv::Point2i& point) const noexcept\n        {\n            size_t seed                     = 0;\n            constexpr uint32_t GOLDEN_RATIO = 0x9e3779b9;\n            seed ^= std::hash<int>()(point.x) + GOLDEN_RATIO + (seed << 6) + (seed >> 2);\n            seed ^= std::hash<int>()(point.y) + GOLDEN_RATIO + (seed << 6) + (seed >> 2);\n            return seed;\n        }\n    };\n    typedef Matx<_Tp, blockM, blockN> MatType;\n    typedef std::unordered_map<Point2i, MatType, Point2iHash> IDtoBlockValueMap;\n\n    BlockSparseMat(int _nBlocks) : nBlocks(_nBlocks), ijValue() {}\n\n    MatType& refBlock(int i, int j)\n    {\n        Point2i p(i, j);\n        auto it = ijValue.find(p);\n        if (it == ijValue.end())\n        {\n            it = ijValue.insert({ p, Matx<_Tp, blockM, blockN>::zeros() }).first;\n        }\n        return it->second;\n    }\n\n    Mat diagonal()\n    {\n        // Diagonal max length is the number of columns in the sparse matrix\n        int diagLength = blockN * nBlocks;\n        cv::Mat diag   = cv::Mat::zeros(diagLength, 1, CV_32F);\n\n        for (int i = 0; i < diagLength; i++)\n        {\n            diag.at<float>(i, 0) = refElem(i, i);\n        }\n        return diag;\n    }\n\n    float& refElem(int i, int j)\n    {\n        Point2i ib(i / blockM, j / blockN), iv(i % blockM, j % blockN);\n        return refBlock(ib.x, ib.y)(iv.x, iv.y);\n    }\n\n#if defined(HAVE_EIGEN)\n    Eigen::SparseMatrix<_Tp> toEigen() const\n    {\n        std::vector<Eigen::Triplet<double>> tripletList;\n        tripletList.reserve(ijValue.size() * blockM * blockN);\n        for (auto ijv : ijValue)\n        {\n            int xb = ijv.first.x, yb = ijv.first.y;\n            MatType vblock = ijv.second;\n            for (int i = 0; i < blockM; i++)\n            {\n                for (int j = 0; j < blockN; j++)\n                {\n                    float val = vblock(i, j);\n                    if (abs(val) >= NON_ZERO_VAL_THRESHOLD)\n                    {\n                        tripletList.push_back(Eigen::Triplet<double>(blockM * xb + i, blockN * yb + j, val));\n                    }\n                }\n            }\n        }\n        Eigen::SparseMatrix<_Tp> EigenMat(blockM * nBlocks, blockN * nBlocks);\n        EigenMat.setFromTriplets(tripletList.begin(), tripletList.end());\n        EigenMat.makeCompressed();\n\n        return EigenMat;\n    }\n#endif\n    size_t nonZeroBlocks() const { return ijValue.size(); }\n\n    static constexpr float NON_ZERO_VAL_THRESHOLD = 0.0001f;\n    int nBlocks;\n    IDtoBlockValueMap ijValue;\n};\n\n//! Function to solve a sparse linear system of equations HX = B\n//! Requires Eigen\nstatic bool sparseSolve(const BlockSparseMat<float, 6, 6>& H, const Mat& B, Mat& X, Mat& predB)\n{\n    bool result = false;\n#if defined(HAVE_EIGEN)\n    Eigen::SparseMatrix<float> bigA = H.toEigen();\n    Eigen::VectorXf bigB;\n    cv2eigen(B, bigB);\n\n    Eigen::SparseMatrix<float> bigAtranspose = bigA.transpose();\n    if(!bigA.isApprox(bigAtranspose))\n    {\n        CV_Error(Error::StsBadArg, \"H matrix is not symmetrical\");\n        return result;\n    }\n\n    Eigen::SimplicialLDLT<Eigen::SparseMatrix<float>> solver;\n\n    solver.compute(bigA);\n    if (solver.info() != Eigen::Success)\n    {\n        std::cout << \"failed to eigen-decompose\" << std::endl;\n        result = false;\n    }\n    else\n    {\n        Eigen::VectorXf solutionX = solver.solve(bigB);\n        Eigen::VectorXf predBEigen = bigA * solutionX;\n        if (solver.info() != Eigen::Success)\n        {\n            std::cout << \"failed to eigen-solve\" << std::endl;\n            result = false;\n        }\n        else\n        {\n            eigen2cv(solutionX, X);\n            eigen2cv(predBEigen, predB);\n            result = true;\n        }\n    }\n#else\n    std::cout << \"no eigen library\" << std::endl;\n    CV_Error(Error::StsNotImplemented, \"Eigen library required for matrix solve, dense solver is not implemented\");\n#endif\n    return result;\n}\n}  // namespace kinfu\n}  // namespace cv\n", "meta": {"hexsha": "0e607af639d3791046b27bf452d41eae02331472", "size": 4653, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/rgbd/src/sparse_block_matrix.hpp", "max_stars_repo_name": "Trevol/opencv_contrib", "max_stars_repo_head_hexsha": "1803962b3be42ab69ea927c9362b63f1b4abc8fd", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 35.0, "max_stars_repo_stars_event_min_datetime": "2021-01-07T11:58:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T11:35:25.000Z", "max_issues_repo_path": "modules/rgbd/src/sparse_block_matrix.hpp", "max_issues_repo_name": "Trevol/opencv_contrib", "max_issues_repo_head_hexsha": "1803962b3be42ab69ea927c9362b63f1b4abc8fd", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-05-22T19:23:38.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-29T12:32:24.000Z", "max_forks_repo_path": "modules/rgbd/src/sparse_block_matrix.hpp", "max_forks_repo_name": "Trevol/opencv_contrib", "max_forks_repo_head_hexsha": "1803962b3be42ab69ea927c9362b63f1b4abc8fd", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2020-12-14T09:13:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-13T07:03:53.000Z", "avg_line_length": 29.08125, "max_line_length": 115, "alphanum_fraction": 0.5766172362, "num_tokens": 1243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.46943613051416405}}
{"text": "#include <map>\n#include <numeric>\n\n#include <Eigen/Dense>\n\n#include \"BingoCpp/acyclic_graph.h\"\n#include \"BingoCpp/backend.h\"\n#include \"BingoCpp/backend_nodes.h\"\n\nconst int NODE_IDX = 0;\nconst int OP_1 = 1;\nconst int OP_2 = 2;\n\nnamespace bingo {\nnamespace {\n\nEigen::ArrayXXd reverse_eval(const std::pair<int, int>& deriv_shape,\n                             const int deriv_wrt_node,\n                             const std::vector<Eigen::ArrayXXd>& forward_eval,\n                             const Eigen::ArrayX3i& stack) {\n  int num_samples = deriv_shape.first;\n  int num_features = deriv_shape.second;\n  int stack_depth = stack.rows();\n\n  Eigen::ArrayXXd derivative = Eigen::ArrayXXd::Zero(num_samples, num_features);\n  std::vector<Eigen::ArrayXXd> reverse_eval(stack_depth); \n  for (int row = 0; row < stack_depth; row++) {\n      reverse_eval[row] = Eigen::ArrayXd::Zero(num_samples);\n  }\n\n  reverse_eval[stack_depth-1] = Eigen::ArrayXd::Ones(num_samples);\n  for (int i = stack_depth - 1; i >= 0; i--) {\n    int node = stack(i, NODE_IDX);\n    int param1 = stack(i, OP_1);\n    int param2 = stack(i, OP_2);\n    if (node == deriv_wrt_node) {\n      derivative.col(param1) += reverse_eval[i];\n    } else {\n      reverse_eval_function(node, i, param1, param2, forward_eval, reverse_eval);\n    }\n  }\n  return derivative;\n}\n\nEigen::ArrayXXd reverse_eval_with_mask(const std::pair<int, int>& deriv_shape,\n                                       const int deriv_wrt_node,\n                                       const std::vector<Eigen::ArrayXXd>& forward_eval,\n                                       const Eigen::ArrayX3i& stack,\n                                       const std::vector<bool>& mask) {\n  int num_samples = deriv_shape.first;\n  int num_features = deriv_shape.second;\n  int stack_depth = stack.rows();\n\n  Eigen::ArrayXXd derivative = Eigen::ArrayXXd::Zero(num_samples, num_features);\n  std::vector<Eigen::ArrayXXd> reverse_eval(stack_depth); \n  for (int row = 0; row < stack_depth; row++) {\n    if (mask[row]) {\n      reverse_eval[row] = Eigen::ArrayXd::Zero(num_samples);\n    }\n  }\n\n  reverse_eval[stack_depth-1] = Eigen::ArrayXd::Ones(num_samples);\n  for (int i = stack_depth - 1; i >= 0; i--) {\n    if (mask[i]) {\n      int node = stack(i, NODE_IDX);\n      int param1 = stack(i, OP_1);\n      int param2 = stack(i, OP_2);\n      if (node == deriv_wrt_node) {\n        derivative.col(param1) += reverse_eval[i];\n      } else {\n        reverse_eval_function(node, i, param1, param2, forward_eval, reverse_eval);\n      }\n    }\n  }\n  return derivative;\n}\n\nstd::vector<Eigen::ArrayXXd> forward_eval(\n    const Eigen::ArrayX3i& stack,\n    const Eigen::ArrayXXd& x,\n    const Eigen::VectorXd& constants) {\n  std::vector<Eigen::ArrayXXd> _forward_eval(stack.rows());\n\n  for (int i = 0; i < stack.rows(); ++i) {\n    int node = stack(i, NODE_IDX);\n    int op1 = stack(i, OP_1);\n    int op2 = stack(i, OP_2);\n    _forward_eval[i] = forward_eval_function(\n      node, op1, op2, x, constants, _forward_eval);\n  }\n  return _forward_eval;\n}\n\nstd::vector<Eigen::ArrayXXd> forward_eval_with_mask(\n    const Eigen::ArrayX3i& stack,\n    const Eigen::ArrayXXd& x,\n    const Eigen::VectorXd& constants,\n    const std::vector<bool>& mask) {\n  std::vector<Eigen::ArrayXXd> _forward_eval(stack.rows());\n\n  for (int i = 0; i < stack.rows(); ++i) {\n    if (mask[i]) {\n      int node = stack(i, NODE_IDX);\n      int op1 = stack(i, OP_1);\n      int op2 = stack(i, OP_2);\n      _forward_eval[i] = forward_eval_function(\n        node, op1, op2, x, constants, _forward_eval);\n    }\n  }\n  return _forward_eval;\n}\n\nstd::pair<Eigen::ArrayXXd, Eigen::ArrayXXd> _evaluate_with_derivative(\n    const Eigen::ArrayX3i& stack,\n    const Eigen::ArrayXXd& x,\n    const Eigen::VectorXd& constants,\n    const bool param_x_or_c) {\n  std::vector<Eigen::ArrayXXd> _forward_eval = forward_eval(\n      stack, x, constants);\n\n  std::pair<int, int> deriv_shape;\n  int deriv_wrt_node;\n  if (param_x_or_c) {  // true = x\n    deriv_shape = std::make_pair(x.rows(), x.cols());\n    deriv_wrt_node = 0;\n  } else {  // false = c\n    deriv_shape = std::make_pair(x.rows(), constants.size());\n    deriv_wrt_node = 1;\n  }\n\n  Eigen::ArrayXXd derivative = reverse_eval(\n      deriv_shape, deriv_wrt_node, _forward_eval, stack);\n  return std::make_pair(_forward_eval.back(), derivative);\n}\n\nstd::pair<Eigen::ArrayXXd, Eigen::ArrayXXd> evaluate_with_derivative_and_mask(\n    const Eigen::ArrayX3i& stack,\n    const Eigen::ArrayXXd& x,\n    const Eigen::VectorXd& constants,\n    const std::vector<bool>& mask,\n    const bool param_x_or_c) {\n  std::vector<Eigen::ArrayXXd> forward_eval = forward_eval_with_mask(\n      stack, x, constants, mask);\n\n  std::pair<int, int> deriv_shape;\n  int deriv_wrt_node;\n  if (param_x_or_c) {  // true = x\n    deriv_shape = std::make_pair(x.rows(), x.cols());\n    deriv_wrt_node = 0;\n  } else {  // false = c\n    deriv_shape = std::make_pair(x.rows(), constants.size());\n    deriv_wrt_node = 1;\n  }\n\n  Eigen::ArrayXXd derivative = reverse_eval_with_mask(\n      deriv_shape, deriv_wrt_node, forward_eval, stack, mask);\n  return std::make_pair(forward_eval.back(), derivative);\n}\n} // namespace\n\nbool is_cpp() {\n    return true;\n}\n\nEigen::ArrayXXd evaluate(const Eigen::ArrayX3i& stack,\n                         const Eigen::ArrayXXd& x,\n                         const Eigen::VectorXd& constants) {\n  std::vector<Eigen::ArrayXXd> _forward_eval = forward_eval(\n      stack, x, constants);\n  return _forward_eval.back();  \n}\n\nstd::pair<Eigen::ArrayXXd, Eigen::ArrayXXd> evaluate_with_derivative(\n    const Eigen::ArrayX3i& stack,\n    const Eigen::ArrayXXd& x,\n    const Eigen::VectorXd& constants,\n    const bool param_x_or_c) {\n  return _evaluate_with_derivative(stack, x, constants, param_x_or_c);\n}\n\nEigen::ArrayXXd simplify_and_evaluate(const Eigen::ArrayX3i& stack,\n                                    const Eigen::ArrayXXd& x,\n                                    const Eigen::VectorXd& constants) {\n  std::vector<bool> mask = get_utilized_commands(stack);\n  std::vector<Eigen::ArrayXXd> forward_eval = forward_eval_with_mask(\n      stack, x, constants, mask);\n  return forward_eval.back();\n}\n\nstd::pair<Eigen::ArrayXXd, Eigen::ArrayXXd> simplify_and_evaluate_with_derivative(\n    const Eigen::ArrayX3i& stack,\n    const Eigen::ArrayXXd& x,\n    const Eigen::VectorXd& constants,\n    const bool param_x_or_c) {\n  std::vector<bool> mask = get_utilized_commands(stack);\n  return evaluate_with_derivative_and_mask(stack, x, constants, mask, param_x_or_c);\n}\n\nstd::vector<bool> get_utilized_commands(const Eigen::ArrayX3i& stack) {\n  std::vector<bool> used_commands(stack.rows());\n  used_commands.back() = true;\n  int stack_size = stack.rows();\n  for (int i = 1; i < stack_size; i++) {\n    int row = stack_size - i;\n    int node = stack(row, NODE_IDX);\n    int param1 = stack(row, OP_1);\n    int param2 = stack(row, OP_2);\n    if (used_commands[row] && node > 1) {\n      used_commands[param1] = true;\n      if (AcyclicGraph::has_arity_two(node)) {\n        used_commands[param2] = true;\n      }\n    }\n  }\n  return used_commands;\n}\n\nEigen::ArrayX3i simplify_stack(const Eigen::ArrayX3i& stack) {\n  std::vector<bool> used_command = get_utilized_commands(stack);\n  std::map<int, int> reduced_param_map;\n  int num_commands = 0;\n  num_commands = std::accumulate(used_command.begin(), used_command.end(), 0);\n  Eigen::ArrayX3i new_stack(num_commands, 3);\n\n  for (int i = 0, j = 0; i < stack.rows(); ++i) {\n    if (used_command[i]) {\n      new_stack(j, 0) = stack(i, 0);\n      if (AcyclicGraph::is_terminal(new_stack(j, 0))) {\n        new_stack(j, 1) = stack(i, 1);\n        new_stack(j, 2) = stack(i, 2);\n      } else {\n        new_stack(j, 1) = reduced_param_map[stack(i, 1)];\n        if (AcyclicGraph::has_arity_two(new_stack(j, 0))) {\n          new_stack(j, 2) = reduced_param_map[stack(i, 2)];\n        } else {\n          new_stack(j, 2) = new_stack(j, 1);\n        }\n      }\n      reduced_param_map[i] = j;\n      ++j;\n    }\n  }\n  return new_stack;\n}\n\nint get_arity(int node) {\n  if (AcyclicGraph::is_terminal(node)) return 0;\n  return AcyclicGraph::has_arity_two(node) ? 2 : 1;\n}\n} // namespace bingo \n", "meta": {"hexsha": "b4263dbbe2b888ed9e7f089166007442f081e043", "size": 8162, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/backend.cpp", "max_stars_repo_name": "tylertownsend/bingocpp", "max_stars_repo_head_hexsha": "c8133fca89edaea30205b70eb5d2a8c91271cb80", "max_stars_repo_licenses": ["Apache-2.0"], "max_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.cpp", "max_issues_repo_name": "tylertownsend/bingocpp", "max_issues_repo_head_hexsha": "c8133fca89edaea30205b70eb5d2a8c91271cb80", "max_issues_repo_licenses": ["Apache-2.0"], "max_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.cpp", "max_forks_repo_name": "tylertownsend/bingocpp", "max_forks_repo_head_hexsha": "c8133fca89edaea30205b70eb5d2a8c91271cb80", "max_forks_repo_licenses": ["Apache-2.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.5179282869, "max_line_length": 88, "alphanum_fraction": 0.6386914972, "num_tokens": 2271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.46943613051416405}}
{"text": "#include <iostream>\n// #include <boost/gil.hpp>\n#include <boost/gil/extension/histogram/histogram.hpp>\n#include <boost/gil/extension/histogram/histogram_algorithms.hpp>\n#include <boost/gil/extension/io/jpeg.hpp>\n#include <boost/gil/extension/io/png.hpp>\n#include <boost/gil/color_base.hpp>\n#include <type_traits>\n#include <boost/gil/detail/mp11.hpp>\n#include <boost/mp11.hpp>\n\nusing namespace boost::gil;\n\nint main() {\n    rgb8_image_t img;\n    read_and_convert_image(\"test.png\", img, png_tag());\n    histogram<gray8_pixel_t> hist;\n    fill_histogram<rgb8_view_t, gray8_pixel_t>(view(img), hist);\n    save_histogram_img(hist, \"test_histogram.jpg\");\n    rgb8_image_t equalized_img(img.dimensions());\n    equalise_histogram(view(img), view(equalized_img));\n    write_view(\"test_equalized.jpg\", view(equalized_img), jpeg_tag{});\n    return 0;\n}\n", "meta": {"hexsha": "94d14613c1b66a792787709721d4cc186b13cbef", "size": 842, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/histogram_equalization.cpp", "max_stars_repo_name": "NEDJIMAbelgacem/gil", "max_stars_repo_head_hexsha": "8ea3644825d4b2dcabda6d4ce6281d4882f45c61", "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": "example/histogram_equalization.cpp", "max_issues_repo_name": "NEDJIMAbelgacem/gil", "max_issues_repo_head_hexsha": "8ea3644825d4b2dcabda6d4ce6281d4882f45c61", "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": "example/histogram_equalization.cpp", "max_forks_repo_name": "NEDJIMAbelgacem/gil", "max_forks_repo_head_hexsha": "8ea3644825d4b2dcabda6d4ce6281d4882f45c61", "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.68, "max_line_length": 70, "alphanum_fraction": 0.7458432304, "num_tokens": 212, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568416, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.46943612428288634}}
{"text": "#include <Sphere.h>\n\n#include <Eigen/Dense>\n\n#include <Util.h>\n\n#include <cmath>\n#include <cstdio>\n\nvoid Sphere::generate_geometry(int width, int height) {\n    int  gNumVertices  = 0;\n    int  gNumTriangles = 0;\n    int* gIndexBuffer  = nullptr;\n\n    float theta, phi;\n    int t;\n    \n    gNumVertices    = (height - 2) * width + 2;\n    gNumTriangles   = (height - 2) * (width - 1) * 2;\n    \n    // TODO: Allocate an array for gNumVertices vertices.\n    Eigen::Vector3f* vertices = new Eigen::Vector3f[gNumVertices];\n\n    gIndexBuffer = new int[3*gNumTriangles];\n    \n    t = 0;\n    for (int j = 1; j < height-1; ++j) {\n        for (int i = 0; i < width; ++i) {\n            theta = (float) j / (height-1) * M_PI;\n            phi   = (float) i / (width-1)  * M_PI * 2;\n            \n            float   x   = sinf(theta) * cosf(phi);\n            float   y   = cosf(theta);\n            float   z   = -sinf(theta) * sinf(phi);\n            \n            // TODO: Set vertex t in the vertex array to {x, y, z}.\n            vertices[t] = Eigen::Vector3f(x, y, z); \n            t++;\n        }\n    }\n    \n    // TODO: Set vertex t in the vertex array to {0, 1, 0}.\n    vertices[t] = Eigen::Vector3f(0, 1, 0);\n    t++;\n    \n    // TODO: Set vertex t in the vertex array to {0, -1, 0}.\n    vertices[t] = Eigen::Vector3f(0, -1, 0); \n    t++;\n    \n    t = 0;\n    for (int j = 0; j < height-3; ++j) {\n        for (int i = 0; i < width-1; ++i) {\n            gIndexBuffer[t++] = j*width + i;\n            gIndexBuffer[t++] = (j+1)*width + (i+1);\n            gIndexBuffer[t++] = j*width + (i+1);\n            gIndexBuffer[t++] = j*width + i;\n            gIndexBuffer[t++] = (j+1)*width + i;\n            gIndexBuffer[t++] = (j+1)*width + (i+1);\n        }\n    }\n    for (int i = 0; i < width-1; ++i) {\n        gIndexBuffer[t++] = (height-2)*width;\n        gIndexBuffer[t++] = i;\n        gIndexBuffer[t++] = i + 1;\n        gIndexBuffer[t++] = (height-2)*width + 1;\n        gIndexBuffer[t++] = (height-3)*width + (i+1);\n        gIndexBuffer[t++] = (height-3)*width + i;\n    }\n\n    // Create triangles\n    for (int i = 0; i < gNumTriangles; i++) {\n        Eigen::Vector3f a = vertices[gIndexBuffer[3*i + 0]];\n        Eigen::Vector3f b = vertices[gIndexBuffer[3*i + 1]];\n        Eigen::Vector3f c = vertices[gIndexBuffer[3*i + 2]];\n\n        triangles.push_back(Triangle(a, b, c));\n    }\n\n    delete[] gIndexBuffer;\n    delete[] vertices;\n}\n\nvoid Sphere::transform_geometry(const Eigen::Matrix4f& xform) {\n    for (auto& tri : triangles) {\n        // Transformed Cartesian vertex coordinates\n        auto a = vec4to3(xform * Eigen::Vector4f(tri.a[0], tri.a[1], tri.a[2], 1.0f));\n        auto b = vec4to3(xform * Eigen::Vector4f(tri.b[0], tri.b[1], tri.b[2], 1.0f));\n        auto c = vec4to3(xform * Eigen::Vector4f(tri.c[0], tri.c[1], tri.c[2], 1.0f));\n\n        // Transform vertices\n        tri.a = a;\n        tri.b = b;\n        tri.c = c;\n\n        // Transform normal\n        tri.n = ((b-a).cross(c-a)).normalized();\n\n        // Transform vertex normals\n        tri.an = (a-center).normalized();\n        tri.bn = (b-center).normalized();\n        tri.cn = (c-center).normalized();\n    }\n}\n", "meta": {"hexsha": "6897f20e8f1008a9b2a27ab48bbc125224888807", "size": 3163, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Sphere.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": "src/Sphere.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": "src/Sphere.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": 30.4134615385, "max_line_length": 86, "alphanum_fraction": 0.5077458109, "num_tokens": 1008, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568416, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4694361242828862}}
{"text": "/*! \\file demo_boxplot_full.cpp\n    \\brief Demonstration of more options for Boxplots.\n    \\details Quickbook markup so can be included in documentation.\n\n    \\author Jacob Voytko and Paul A. Bristow \n    \\date Feb 2009\n*/\n\n// Copyright Jacob Voytko 2007\n// Copyright Paul A. Bristow 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// An example to demonstrate nearly all boxplot options.\n// See also demo_boxplot_simple.cpp and demo_boxplot.cpp for a narrow range of use.\n\n// This file is written to be included from a Quickbook .qbk document.\n// It can be compiled by the C++ compiler, and run. Any output can\n// also be added here as comment or included or pasted in elsewhere.\n\n// Caution: this file contains Quickbook markup as well as code\n// and comments: don't change any of the special comment markups!\n\n//[demo_boxplot_full_1\n\n/*`\nBoxplot is a  convenient way of graphically depicting groups of numerical data \nthrough their five-number summaries.\nShow 1st quartile, median and 3rd quartile as a box,\nminimum and maximum non-outlier values as whiskers,\nand outliers and extreme outliers.\n\nSee [@http://en.wikipedia.org/wiki/Boxplot boxplot] and\n\nSome Implementations of the Boxplot\nMichael Frigge, David C. Hoaglin and Boris Iglewicz\nThe American Statistician, Vol. 43, No. 1 (Feb., 1989), pp. 50-54\n\nFirst we need a few includes to use Boost.Plot.\n*/\n\n#include <vector>\nusing std::vector;\n#include <cmath>\nusing ::sin;\n#include <boost/svg_plot/svg_boxplot.hpp>\n\n#include <boost/array.hpp>\n  using boost::array;\n\n#include <iostream>\nusing std::cout;\nusing std::endl;\n\n/*`Use two functions, 1/x and sin(x), to simulate distributions.\n*/\n\ndouble f(double x)\n{ // Effectively 1/x.\n  return 50 / x;\n}\n\ndouble g(double x)\n{ // Effectively sin(x).\n  return 40 + 25 * sin(x * 50);\n}\n//] [demo_boxplot_full_1]\n\nint main()\n{\n  using namespace boost::svg;\n  try\n  {\n//[demo_boxplot_full_2]\n/*`10 values are computed and stored in two std:: vectors.\n*/\n  std::vector<double> data1;\n  std::vector<double> data2;\n\n  cout.precision(2);\n  for(double i = 0.1; i < 10; i += 0.1)\n  {   // Fill our vectors with 100 values:\n    double fv = f(i);\n    double gv = g(i);\n    // cout << i << ' ' << fv << ' ' << gv << endl;\n    data1.push_back(fv);\n    data2.push_back(gv);\n  }\n\n  /*`Other containers, for example array, can be used too:\n  */\n\n  //const boost::array<double, 0> data0;\n  //const boost::array<double, 10> data3 = {20., 30., 40., 45., 47., 50., 55., 60., 70, 80.};\n\n/*`A new boxplot is contructed and very many settings added.\nThis is only to show their use and is intended to be visible, if totally tasteless!\n*/\n  svg_boxplot my_boxplot;\n\n  //my_boxplot.plot(data0, \"data0\"); // Produces warning: \"Message from thrown exception was: Data series data0 is empty!\"\n\n  //my_boxplot.plot(data3); // Produces warning: \"Data series has no title!\"\n\n  my_boxplot.background_border_color(darkblue);\n  my_boxplot.background_color(azure);\n\n  my_boxplot  // Title and axes labels.\n    .title(\"Boxplots of 1/x and sin(x) Functions\")\n    .x_label(\"Functions\")\n    .y_label(\"Population Size\");\n\n  my_boxplot.y_range(0, 100)  // Y-Axis information.\n    .y_minor_tick_length(2)\n    .y_major_interval(20);\n\n/*`Many attributes of boxplots can be changed from the 'built-in' defaults, for example: */\n\n   my_boxplot.whisker_length(25.).box_width(10)\n     .box_fill(lime)\n     .box_border(blue)\n     .box_fill(lightblue)\n     .median_color(red). median_width(2)\n     .axis_color(orange).axis_width(4)\n     .outlier_color(red)\n     .outlier_fill(yellow)\n     .outlier_shape(square)\n     .outlier_size(5)\n     .median_values_on(true)\n     .outlier_values_on(true)\n     .extreme_outlier_values_on(true) \n     .extreme_outlier_color(brown)\n     .extreme_outlier_shape(diamond)\n     .extreme_outlier_size(10)\n    ;\n\n   cout << my_boxplot.outlier_color() << endl; // red\n   cout << my_boxplot.outlier_size() << endl; // size 10\n   cout << my_boxplot.outlier_shape() << endl; // square\n\n   //cout << my_boxplot.outlier_style.size() << endl; // doesn't work???\n\n\n/*` Applies to all boxplots, unless changed for any individual plots, for example, change colors for data1 only:*/\n\n   my_boxplot.plot(data1, \"data1\")\n     .whisker_length(50.)\n     .min_whisker_width(4).min_whisker_color(red)\n     .max_whisker_width(7).max_whisker_color(green)\n     .box_width(10)\n     .box_fill(yellow)\n     .box_border(magenta)\n     .median_color(blue). median_width(5)\n     .axis_color(lime). axis_width(1)\n     .outlier_color(blue)\n     .outlier_fill(yellow)\n     .outlier_shape(cone)\n     .outlier_size(10)\n     .extreme_outlier_color(red)\n     .extreme_outlier_fill(green)\n     .extreme_outlier_shape(circlet)\n     .extreme_outlier_size(10)\n     //.extreme_outlier_values_on(true) not implemented.\n;\n\n\n\n   // my_boxplot.plot(data1, \"test\").box_style().fill_color(pink).stroke_color(green);\n   // Once box_style() has been used to chain box styles, one can no longer chain to other non-box items, which is limiting.\n   // So convenience functions are provided for many (but not all) features like: .box_fill(pink), box_border(green)...\n   // Similar restrictions follow\n   // my_boxplot.plot(data1, \"test\").box_width(10).whisker_length(5).median_style().stroke_color(purple);\n\n\n/*`Add the two data series containers, and their labels, to the plot.\n*/\n\n  my_boxplot.plot(data1, \"[50/x]\");\n  my_boxplot.plot(data2, \"[sin(x*50)]\");\n\n/* \n  cout << \"my_boxplot.title \" << my_boxplot.title() << endl;\n  cout << \"my_boxplot.x_label_text \"<< my_boxplot.x_label_text() << endl;\n  cout << \"my_boxplot.y_label_text \" << my_boxplot.y_label_text() << endl; \n\n  cout << \"my_boxplot.background_color \" << my_boxplot.background_color() << endl;\n  cout << \"my_boxplot.background_border_color \" << my_boxplot.background_border_color() << endl;\n  cout << \"my_boxplot.plot_background_color \" << my_boxplot.plot_background_color() << endl;\n  cout << \"my_boxplot.plot_border_color \" << my_boxplot.plot_border_color() << endl;\n */\n\n/*`Finally write the SVG plot to a file.\n*/\n  my_boxplot.write(\"demo_boxplot_full.svg\");\n\n/*`You can view the plot (in all its 'glory') at demo_boxplot_full.svg.\"\n*/\n\n//] [demo_boxplot_full_2]\n  }\n  catch(const std::exception& e)\n  {\n    std::cout <<\n      \"\\n\"\"Message from thrown exception was:\\n  \" << e.what() << std::endl;\n  }\n  return 0;\n} // int main()\n\n/*\n\nOutput:\ndemo_boxplot_full.cpp\nLinking...\nEmbedding manifest...\nAutorun \"j:\\Cpp\\SVG\\debug\\demo_boxplot_full.exe\"\nRGB(255,0,0)\n5\n2\nBuild Time 0:03\n\n*/\n\n", "meta": {"hexsha": "cf5842aa83883f643bfce8cfbcd32c9cb11aa8d4", "size": 6633, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/demo_boxplot_full.cpp", "max_stars_repo_name": "pabristow/svg_plot", "max_stars_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2016-03-09T03:23:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T14:02:07.000Z", "max_issues_repo_path": "example/demo_boxplot_full.cpp", "max_issues_repo_name": "pabristow/svg_plot", "max_issues_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2018-03-05T14:39:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-22T09:00:33.000Z", "max_forks_repo_path": "example/demo_boxplot_full.cpp", "max_forks_repo_name": "pabristow/svg_plot", "max_forks_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2016-11-04T14:36:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-17T08:12:03.000Z", "avg_line_length": 29.3495575221, "max_line_length": 124, "alphanum_fraction": 0.6948590381, "num_tokens": 1872, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.8128673246376009, "lm_q1q2_score": 0.4694271124892051}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\n#include \"y2019/vision/target_finder.h\"\n\n#include \"aos/vision/blob/move_scale.h\"\n#include \"aos/vision/blob/stream_view.h\"\n#include \"aos/vision/blob/transpose.h\"\n#include \"aos/vision/debug/debug_framework.h\"\n#include \"aos/vision/math/vector.h\"\n#include \"gflags/gflags.h\"\n\nusing aos::vision::ImageRange;\nusing aos::vision::ImageFormat;\nusing aos::vision::RangeImage;\nusing aos::vision::AnalysisAllocator;\nusing aos::vision::BlobList;\nusing aos::vision::Vector;\nusing aos::vision::Segment;\nusing aos::vision::PixelRef;\n\nDEFINE_int32(camera, 10, \"The camera to use the intrinsics for\");\n\nnamespace y2019 {\nnamespace vision {\n\nstd::vector<PixelRef> GetNColors(size_t num_colors) {\n  std::vector<PixelRef> colors;\n  for (size_t i = 0; i < num_colors; ++i) {\n    int quadrent = i * 6 / num_colors;\n    uint8_t alpha = (256 * 6 * i - quadrent * num_colors * 256) / num_colors;\n    uint8_t inv_alpha = 255 - alpha;\n    switch (quadrent) {\n      case 0:\n        colors.push_back(PixelRef{255, alpha, 0});\n        break;\n      case 1:\n        colors.push_back(PixelRef{inv_alpha, 255, 0});\n        break;\n      case 2:\n        colors.push_back(PixelRef{0, 255, alpha});\n        break;\n      case 3:\n        colors.push_back(PixelRef{0, inv_alpha, 255});\n        break;\n      case 4:\n        colors.push_back(PixelRef{alpha, 0, 255});\n        break;\n      case 5:\n        colors.push_back(PixelRef{255, 0, inv_alpha});\n        break;\n    }\n  }\n  return colors;\n}\n\nclass FilterHarness : public aos::vision::FilterHarness {\n public:\n FilterHarness() {\n   *(target_finder_.mutable_intrinsics()) = GetCamera(FLAGS_camera)->intrinsics;\n }\n  aos::vision::RangeImage Threshold(aos::vision::ImagePtr image) override {\n    return target_finder_.Threshold(image);\n  }\n\n  void InstallViewer(aos::vision::BlobStreamViewer *viewer) override {\n    viewer_ = viewer;\n    viewer_->SetScale(2.0);\n    overlays_.push_back(&overlay_);\n    overlays_.push_back(target_finder_.GetOverlay());\n    viewer_->view()->SetOverlays(&overlays_);\n  }\n\n  void DrawBlob(const RangeImage &blob, PixelRef color) {\n    if (viewer_) {\n      BlobList list;\n      list.push_back(blob);\n      viewer_->DrawBlobList(list, color);\n    }\n  }\n\n  bool HandleBlobs(BlobList imgs, ImageFormat fmt) override {\n    const CameraGeometry camera_geometry = GetCamera(FLAGS_camera)->geometry;\n    imgs_last_ = imgs;\n    fmt_last_ = fmt;\n    // reset for next drawing cycle\n    for (auto &overlay : overlays_) {\n      overlay->Reset();\n    }\n\n    if (draw_select_blob_ || draw_raw_poly_ || draw_components_ ||\n        draw_raw_target_ || draw_raw_IR_ || draw_results_) {\n      printf(\"_____ New Image _____\\n\");\n    }\n\n    const int num_pixels = target_finder_.PixelCount(&imgs);\n    printf(\"Number pixels: %d\\n\", num_pixels);\n\n    // Remove bad blobs.\n    target_finder_.PreFilter(&imgs);\n\n    // Find polygons from blobs.\n    ::std::vector<Polygon> raw_polys;\n    for (const RangeImage &blob : imgs) {\n      // Convert blobs to contours in the corrected space.\n      ContourNode *contour = target_finder_.GetContour(blob);\n      if (draw_contours_) {\n        DrawContour(contour, {255, 0, 0});\n      }\n      ::std::vector<::Eigen::Vector2f> unwarped_contour =\n          target_finder_.UnWarpContour(contour);\n      if (draw_contours_) {\n        DrawContour(unwarped_contour, {0, 0, 255});\n      }\n\n      // Process to polygons.\n      const Polygon polygon = target_finder_.FindPolygon(\n          ::std::move(unwarped_contour), draw_raw_poly_);\n      if (polygon.segments.empty()) {\n        if (!draw_contours_) {\n          DrawBlob(blob, {255, 0, 0});\n        }\n      } else {\n        raw_polys.push_back(polygon);\n        if (draw_select_blob_) {\n          DrawBlob(blob, {0, 0, 255});\n        }\n        if (draw_raw_poly_) {\n          std::vector<PixelRef> colors = GetNColors(polygon.segments.size());\n          std::vector<Vector<2>> corners;\n          for (size_t i = 0; i < polygon.segments.size(); ++i) {\n            corners.push_back(polygon.segments[i].Intersect(\n                polygon.segments[(i + 1) % polygon.segments.size()]));\n          }\n\n          for (size_t i = 0; i < polygon.segments.size(); ++i) {\n            overlay_.AddLine(corners[i],\n                             corners[(i + 1) % polygon.segments.size()],\n                             colors[i]);\n          }\n        }\n      }\n    }\n\n    // Calculate each component side of a possible target.\n    std::vector<TargetComponent> target_component_list =\n        target_finder_.FillTargetComponentList(raw_polys, draw_components_);\n    if (draw_components_) {\n      for (const TargetComponent &component : target_component_list) {\n        DrawComponent(component, {0, 255, 255}, {0, 255, 255}, {255, 0, 0},\n                      {0, 0, 255});\n        overlay_.DrawCross(component.bottom_point, 4, {128, 0, 255});\n      }\n    }\n\n    // Put the compenents together into targets.\n    std::vector<Target> target_list = target_finder_.FindTargetsFromComponents(\n        target_component_list, draw_raw_target_);\n    if (draw_raw_target_) {\n      for (const Target &target : target_list) {\n        DrawTarget(target);\n      }\n    }\n\n    // Use the solver to generate an intermediate version of our results.\n    std::vector<IntermediateResult> results;\n    for (const Target &target : target_list) {\n      results.emplace_back(\n          target_finder_.ProcessTargetToResult(target, draw_raw_IR_));\n      if (draw_raw_IR_) {\n        IntermediateResult updatable_result = results.back();\n        target_finder_.MaybePickAndUpdateResult(&updatable_result,\n                                                draw_raw_IR_);\n        DrawResult(updatable_result, {255, 128, 0});\n      }\n    }\n\n    // Check that our current results match possible solutions.\n    results = target_finder_.FilterResults(results, 0, draw_results_);\n    if (draw_results_) {\n      for (const IntermediateResult &result : results) {\n        ::std::cout << \"Found target x: \"\n                    << camera_geometry.location[0] +\n                           ::std::cos(camera_geometry.heading +\n                                      result.extrinsics.r2) *\n                               result.extrinsics.z\n                    << ::std::endl;\n        ::std::cout << \"Found target y: \"\n                    << camera_geometry.location[1] +\n                           ::std::sin(camera_geometry.heading +\n                                      result.extrinsics.r2) *\n                               result.extrinsics.z\n                    << ::std::endl;\n        ::std::cout << \"Found target z: \"\n                    << camera_geometry.location[2] + result.extrinsics.y\n                    << ::std::endl;\n        DrawTarget(result, {0, 255, 0});\n      }\n    }\n\n    int desired_exposure;\n    if (target_finder_.TestExposure(results, num_pixels, &desired_exposure)) {\n      printf(\"Switching exposure to %d.\\n\", desired_exposure);\n      SetExposure(desired_exposure);\n    }\n\n    // If the target list is not empty then we found a target.\n    return !results.empty();\n  }\n\n  std::function<void(uint32_t)> RegisterKeyPress() override {\n    return [this](uint32_t key) {\n      (void)key;\n      if (key == 'z') {\n        draw_results_ = !draw_results_;\n      } else if (key == 'x') {\n        draw_raw_IR_ = !draw_raw_IR_;\n      } else if (key == 'c') {\n        draw_raw_target_ = !draw_raw_target_;\n      } else if (key == 'v') {\n        draw_components_ = !draw_components_;\n      } else if (key == 'b') {\n        draw_raw_poly_ = !draw_raw_poly_;\n      } else if (key == 'n') {\n        draw_contours_ = !draw_contours_;\n      } else if (key == 'm') {\n        draw_select_blob_ = !draw_select_blob_;\n      } else if (key == 'h') {\n        printf(\"Key Mappings:\\n\");\n        printf(\" z: Toggle drawing final target pose.\\n\");\n        printf(\" x: Toggle drawing re-projected targets and print solver results.\\n\");\n        printf(\" c: Toggle drawing proposed target groupings.\\n\");\n        printf(\" v: Toggle drawing ordered target components.\\n\");\n        printf(\" b: Toggle drawing proposed target components.\\n\");\n        printf(\" n: Toggle drawing countours before and after warping.\\n\");\n        printf(\" m: Toggle drawing raw blob data (may need to change image to toggle a redraw).\\n\");\n        printf(\" h: Print this message.\\n\");\n        printf(\" a: May log camera image to /tmp/debug_viewer_jpeg_<#>.yuyv\\n\");\n        printf(\" q: Exit the application.\\n\");\n      } else if (key == 'q') {\n        printf(\"User requested shutdown.\\n\");\n        exit(0);\n      }\n      HandleBlobs(imgs_last_, fmt_last_);\n      viewer_->Redraw();\n    };\n  }\n\n  void DrawContour(ContourNode *contour, PixelRef color) {\n    if (viewer_) {\n      for (ContourNode *node = contour; node->next != contour;) {\n        Vector<2> a(node->pt.x, node->pt.y);\n        Vector<2> b(node->next->pt.x, node->next->pt.y);\n        overlay_.AddLine(a, b, color);\n        node = node->next;\n      }\n    }\n  }\n\n  void DrawContour(const ::std::vector<::Eigen::Vector2f> &contour,\n                   PixelRef color) {\n    if (viewer_) {\n      for (size_t i = 0; i < contour.size(); ++i) {\n        Vector<2> a(contour[i].x(), contour[i].y());\n        Vector<2> b(contour[(i + 1) % contour.size()].x(),\n                    contour[(i + 1) % contour.size()].y());\n        overlay_.AddLine(a, b, color);\n      }\n    }\n  }\n\n  void DrawComponent(const TargetComponent &comp, PixelRef top_color,\n                     PixelRef bot_color, PixelRef in_color,\n                     PixelRef out_color) {\n    overlay_.AddLine(comp.top, comp.inside, top_color);\n    overlay_.AddLine(comp.bottom, comp.outside, bot_color);\n\n    overlay_.AddLine(comp.bottom, comp.inside, in_color);\n    overlay_.AddLine(comp.top, comp.outside, out_color);\n  }\n\n  void DrawTarget(const Target &target) {\n    Vector<2> leftTop = (target.left.top + target.left.inside) * 0.5;\n    Vector<2> rightTop = (target.right.top + target.right.inside) * 0.5;\n    overlay_.AddLine(leftTop, rightTop, {255, 215, 0});\n\n    Vector<2> leftBot = (target.left.bottom + target.left.outside) * 0.5;\n    Vector<2> rightBot = (target.right.bottom + target.right.outside) * 0.5;\n    overlay_.AddLine(leftBot, rightBot, {255, 215, 0});\n\n    overlay_.AddLine(leftTop, leftBot, {255, 215, 0});\n    overlay_.AddLine(rightTop, rightBot, {255, 215, 0});\n  }\n\n  void DrawResult(const IntermediateResult &result, PixelRef color) {\n    Target target = Project(target_finder_.GetTemplateTarget(), intrinsics(),\n                            result.extrinsics);\n    DrawComponent(target.left, color, color, color, color);\n    DrawComponent(target.right, color, color, color, color);\n  }\n\n  void DrawTarget(const IntermediateResult &result, PixelRef color) {\n    Target target = Project(target_finder_.GetTemplateTarget(), intrinsics(),\n                            result.extrinsics);\n    Segment<2> leftAx((target.left.top + target.left.inside) * 0.5,\n                      (target.left.bottom + target.left.outside) * 0.5);\n    leftAx.Set(leftAx.A() * 0.9 + leftAx.B() * 0.1,\n               leftAx.B() * 0.9 + leftAx.A() * 0.1);\n    overlay_.AddLine(leftAx, color);\n\n    Segment<2> rightAx((target.right.top + target.right.inside) * 0.5,\n                       (target.right.bottom + target.right.outside) * 0.5);\n    rightAx.Set(rightAx.A() * 0.9 + rightAx.B() * 0.1,\n                rightAx.B() * 0.9 + rightAx.A() * 0.1);\n    overlay_.AddLine(rightAx, color);\n\n    overlay_.AddLine(leftAx.A(), rightAx.A(), color);\n    overlay_.AddLine(leftAx.B(), rightAx.B(), color);\n    Vector<3> p1(0.0, 0.0, 100.0);\n\n    Vector<3> p2 =\n        Rotate(intrinsics().mount_angle, result.extrinsics.r1, 0.0, p1);\n    Vector<2> p3(p2.x(), p2.y());\n    overlay_.AddLine(leftAx.A(), p3 + leftAx.A(), {0, 255, 0});\n    overlay_.AddLine(leftAx.B(), p3 + leftAx.B(), {0, 255, 0});\n    overlay_.AddLine(rightAx.A(), p3 + rightAx.A(), {0, 255, 0});\n    overlay_.AddLine(rightAx.B(), p3 + rightAx.B(), {0, 255, 0});\n\n    overlay_.AddLine(p3 + leftAx.A(), p3 + leftAx.B(), {0, 255, 0});\n    overlay_.AddLine(p3 + leftAx.A(), p3 + rightAx.A(), {0, 255, 0});\n    overlay_.AddLine(p3 + rightAx.A(), p3 + rightAx.B(), {0, 255, 0});\n    overlay_.AddLine(p3 + leftAx.B(), p3 + rightAx.B(), {0, 255, 0});\n  }\n\n  const IntrinsicParams &intrinsics() const {\n    return target_finder_.intrinsics();\n  }\n\n private:\n  // implementation of the filter pipeline.\n  TargetFinder target_finder_;\n  aos::vision::BlobStreamViewer *viewer_ = nullptr;\n  aos::vision::PixelLinesOverlay overlay_;\n  std::vector<aos::vision::OverlayBase *> overlays_;\n  BlobList imgs_last_;\n  ImageFormat fmt_last_;\n  bool draw_select_blob_ = false;\n  bool draw_contours_ = true;\n  bool draw_raw_poly_ = true;\n  bool draw_components_ = false;\n  bool draw_raw_target_ = false;\n  bool draw_raw_IR_ = true;\n  bool draw_results_ = true;\n};\n\n}  // namespace vision\n}  // namespace y2017\n\nint main(int argc, char **argv) {\n  ::gflags::ParseCommandLineFlags(&argc, &argv, true);\n\n  y2019::vision::FilterHarness filter_harness;\n  aos::vision::DebugFrameworkMain(argc, argv, &filter_harness,\n                                  aos::vision::CameraParams());\n}\n", "meta": {"hexsha": "e98f0187cced23bb7ce43dc9a15224f61dfda97c", "size": 13186, "ext": "cc", "lang": "C++", "max_stars_repo_path": "y2019/vision/debug_viewer.cc", "max_stars_repo_name": "Ewpratten/frc_971_mirror", "max_stars_repo_head_hexsha": "3a8a0c4359f284d29547962c2b4c43d290d8065c", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 39.0, "max_stars_repo_stars_event_min_datetime": "2021-06-18T03:22:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T15:23:43.000Z", "max_issues_repo_path": "y2019/vision/debug_viewer.cc", "max_issues_repo_name": "Ewpratten/frc_971_mirror", "max_issues_repo_head_hexsha": "3a8a0c4359f284d29547962c2b4c43d290d8065c", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2021-06-18T03:22:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-18T22:14:15.000Z", "max_forks_repo_path": "y2019/vision/debug_viewer.cc", "max_forks_repo_name": "Ewpratten/frc_971_mirror", "max_forks_repo_head_hexsha": "3a8a0c4359f284d29547962c2b4c43d290d8065c", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-08-19T19:20:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T07:33:18.000Z", "avg_line_length": 36.0273224044, "max_line_length": 100, "alphanum_fraction": 0.6067799181, "num_tokens": 3465, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4694271085622208}}
{"text": "// Copyright (c) 2017-2018 The Rhombus Core developers\n// Distributed under the MIT software license, see the accompanying\n// file COPYING or http://www.opensource.org/licenses/mit-license.php.\n\n#include <test/setup_common.h>\n\n#include <crypto/sha256.h>\n\n#include <secp256k1.h>\n#include <secp256k1_rangeproof.h>\n#include <secp256k1_bulletproofs.h>\n#include <stdint.h>\n#include <util/strencodings.h>\n\n#include <boost/test/unit_test.hpp>\n\n#include <blind.h>\n\nBOOST_FIXTURE_TEST_SUITE(ct_tests, BasicTestingSetup)\n\n\nclass CTxOutValueTest\n{\npublic:\n    secp256k1_pedersen_commitment commitment;\n    std::vector<uint8_t> vchRangeproof;\n    std::vector<uint8_t> vchNonceCommitment;\n};\n\n\nBOOST_AUTO_TEST_CASE(ct_test)\n{\n    SeedInsecureRand();\n    secp256k1_context *ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY);\n\n    std::vector<CTxOutValueTest> txins(1);\n\n    std::vector<const uint8_t*> blindptrs;\n    uint8_t blindsin[1][32];\n    //GetStrongRandBytes(&blindsin[0][0], 32);\n    InsecureRandBytes(&blindsin[0][0], 32);\n    blindptrs.push_back(&blindsin[0][0]);\n\n    CAmount nValueIn = 45.69 * COIN;\n    BOOST_CHECK(secp256k1_pedersen_commit(ctx, &txins[0].commitment, &blindsin[0][0], nValueIn, &secp256k1_generator_const_h, &secp256k1_generator_const_g));\n\n    const int nTxOut = 2;\n    std::vector<CTxOutValueTest> txouts(nTxOut);\n\n    std::vector<CAmount> amount_outs(2);\n    amount_outs[0] = 5.69 * COIN;\n    amount_outs[1] = 40 * COIN;\n\n    std::vector<CKey> kto_outs(2);\n    InsecureNewKey(kto_outs[0], true);\n    InsecureNewKey(kto_outs[1], true);\n\n    std::vector<CPubKey> pkto_outs(2);\n    pkto_outs[0] = kto_outs[0].GetPubKey();\n    pkto_outs[1] = kto_outs[1].GetPubKey();\n\n    uint8_t blind[nTxOut][32];\n\n    size_t nBlinded = 0;\n    for (size_t k = 0; k < txouts.size(); ++k) {\n        CTxOutValueTest &txout = txouts[k];\n\n        if (nBlinded + 1 == txouts.size()) {\n            // Last to-be-blinded value: compute from all other blinding factors.\n            // sum of output blinding values must equal sum of input blinding values\n            BOOST_CHECK(secp256k1_pedersen_blind_sum(ctx, &blind[nBlinded][0], &blindptrs[0], 2, 1));\n            blindptrs.push_back(&blind[nBlinded++][0]);\n        } else {\n            //GetStrongRandBytes(&blind[nBlinded][0], 32);\n            InsecureRandBytes(&blind[nBlinded][0], 32);\n            blindptrs.push_back(&blind[nBlinded++][0]);\n        }\n\n        BOOST_CHECK(secp256k1_pedersen_commit(ctx, &txout.commitment, (uint8_t*)blindptrs.back(), amount_outs[k], &secp256k1_generator_const_h, &secp256k1_generator_const_g));\n\n        // Generate ephemeral key for ECDH nonce generation\n        CKey ephemeral_key;\n        InsecureNewKey(ephemeral_key, true);\n        CPubKey ephemeral_pubkey = ephemeral_key.GetPubKey();\n        txout.vchNonceCommitment.resize(33);\n        memcpy(&txout.vchNonceCommitment[0], &ephemeral_pubkey[0], 33);\n\n        // Generate nonce\n        uint256 nonce = ephemeral_key.ECDH(pkto_outs[k]);\n        CSHA256().Write(nonce.begin(), 32).Finalize(nonce.begin());\n\n        // Create range proof\n        size_t nRangeProofLen = 5134;\n        // TODO: smarter min_value selection\n\n        txout.vchRangeproof.resize(nRangeProofLen);\n\n        uint64_t min_value = 0;\n        int ct_exponent = 2;\n        int ct_bits = 32;\n\n        const char *message = \"narration\";\n        size_t mlen = strlen(message);\n\n        BOOST_CHECK(secp256k1_rangeproof_sign(ctx,\n            &txout.vchRangeproof[0], &nRangeProofLen,\n            min_value, &txout.commitment,\n            blindptrs.back(), nonce.begin(),\n            ct_exponent, ct_bits,\n            amount_outs[k],\n            (const unsigned char*) message, mlen,\n            nullptr, 0,\n            secp256k1_generator_h));\n\n        txout.vchRangeproof.resize(nRangeProofLen);\n    }\n\n    std::vector<secp256k1_pedersen_commitment*> vpCommitsIn, vpCommitsOut;\n    vpCommitsIn.push_back(&txins[0].commitment);\n\n    vpCommitsOut.push_back(&txouts[0].commitment);\n    vpCommitsOut.push_back(&txouts[1].commitment);\n\n    BOOST_CHECK(secp256k1_pedersen_verify_tally(ctx, vpCommitsIn.data(), vpCommitsIn.size(), vpCommitsOut.data(), vpCommitsOut.size()));\n\n\n    for (size_t k = 0; k < txouts.size(); ++k) {\n        CTxOutValueTest &txout = txouts[k];\n\n        int rexp;\n        int rmantissa;\n        uint64_t min_value, max_value;\n\n        BOOST_CHECK(secp256k1_rangeproof_info(ctx,\n            &rexp, &rmantissa,\n            &min_value, &max_value,\n            &txout.vchRangeproof[0], txout.vchRangeproof.size()) == 1);\n\n        min_value = 0;\n        max_value = 0;\n        BOOST_CHECK(1 == secp256k1_rangeproof_verify(ctx, &min_value, &max_value,\n            &txout.commitment, txout.vchRangeproof.data(), txout.vchRangeproof.size(),\n            nullptr, 0,\n            secp256k1_generator_h));\n\n        CPubKey ephemeral_key(txout.vchNonceCommitment);\n        BOOST_CHECK(ephemeral_key.IsValid());\n        uint256 nonce = kto_outs[k].ECDH(ephemeral_key);\n        CSHA256().Write(nonce.begin(), 32).Finalize(nonce.begin());\n\n        uint8_t blindOut[32];\n        unsigned char msg[4096];\n        size_t msg_size = sizeof(msg);\n        uint64_t amountOut;\n        BOOST_CHECK(secp256k1_rangeproof_rewind(ctx,\n            blindOut, &amountOut, msg, &msg_size, nonce.begin(),\n            &min_value, &max_value,\n            &txout.commitment, txout.vchRangeproof.data(), txout.vchRangeproof.size(),\n            nullptr, 0,\n            secp256k1_generator_h));\n\n        msg[9] = '\\0';\n        BOOST_CHECK(memcmp(msg, \"narration\", 9) == 0);\n    }\n\n    secp256k1_context_destroy(ctx);\n}\n\n\nBOOST_AUTO_TEST_CASE(ct_test_bulletproofs)\n{\n    SeedInsecureRand();\n    secp256k1_context *ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY);\n    secp256k1_scratch_space *scratch = secp256k1_scratch_space_create(ctx, 1024 * 1024);\n    secp256k1_bulletproof_generators *gens;\n\n    gens = secp256k1_bulletproof_generators_create(ctx, &secp256k1_generator_const_g, 256);\n    BOOST_CHECK(gens != nullptr);\n\n    std::vector<CTxOutValueTest> txins(1);\n\n    std::vector<const uint8_t*> blindptrs;\n    uint8_t blindsin[1][32];\n    //GetStrongRandBytes(&blindsin[0][0], 32);\n    InsecureRandBytes(&blindsin[0][0], 32);\n    blindptrs.push_back(&blindsin[0][0]);\n\n    CAmount nValueIn = 45.69 * COIN;\n    BOOST_CHECK(secp256k1_pedersen_commit(ctx, &txins[0].commitment, &blindsin[0][0], nValueIn, &secp256k1_generator_const_h, &secp256k1_generator_const_g));\n\n    const int nTxOut = 2;\n    std::vector<CTxOutValueTest> txouts(nTxOut);\n\n    std::vector<CAmount> amount_outs(2);\n    amount_outs[0] = 5.69 * COIN;\n    amount_outs[1] = 40 * COIN;\n\n    std::vector<CKey> kto_outs(2);\n    InsecureNewKey(kto_outs[0], true);\n    InsecureNewKey(kto_outs[1], true);\n\n    std::vector<CPubKey> pkto_outs(2);\n    pkto_outs[0] = kto_outs[0].GetPubKey();\n    pkto_outs[1] = kto_outs[1].GetPubKey();\n\n    uint8_t blind[nTxOut][32];\n\n    size_t nBlinded = 0;\n    for (size_t k = 0; k < txouts.size(); ++k) {\n        CTxOutValueTest &txout = txouts[k];\n\n        if (nBlinded + 1 == txouts.size()) {\n            // Last to-be-blinded value: compute from all other blinding factors.\n            // sum of output blinding values must equal sum of input blinding values\n            BOOST_CHECK(secp256k1_pedersen_blind_sum(ctx, &blind[nBlinded][0], &blindptrs[0], 2, 1));\n            blindptrs.push_back(&blind[nBlinded++][0]);\n        } else {\n            //GetStrongRandBytes(&blind[nBlinded][0], 32);\n            InsecureRandBytes(&blind[nBlinded][0], 32);\n            blindptrs.push_back(&blind[nBlinded++][0]);\n        }\n\n        BOOST_CHECK(secp256k1_pedersen_commit(ctx, &txout.commitment, (uint8_t*)blindptrs.back(), amount_outs[k], &secp256k1_generator_const_h, &secp256k1_generator_const_g));\n\n        // Generate ephemeral key for ECDH nonce generation\n        CKey ephemeral_key;\n        InsecureNewKey(ephemeral_key, true);\n        CPubKey ephemeral_pubkey = ephemeral_key.GetPubKey();\n        txout.vchNonceCommitment.resize(33);\n        memcpy(&txout.vchNonceCommitment[0], &ephemeral_pubkey[0], 33);\n\n        // Generate nonce\n        uint256 nonce = ephemeral_key.ECDH(pkto_outs[k]);\n        CSHA256().Write(nonce.begin(), 32).Finalize(nonce.begin());\n\n        // Create range proof\n        size_t nRangeProofLen = 5134;\n        txout.vchRangeproof.resize(nRangeProofLen);\n\n        uint8_t *proof = &txout.vchRangeproof[0];\n        const uint8_t *blindptrs_[] = {blindptrs.back()};\n        BOOST_CHECK(secp256k1_bulletproof_rangeproof_prove(ctx, scratch, gens, proof, &nRangeProofLen, (const uint64_t*)&amount_outs[k], NULL, blindptrs_, 1, &secp256k1_generator_const_h, 64, nonce.begin(), NULL, 0) == 1);\n\n        txout.vchRangeproof.resize(nRangeProofLen);\n    }\n\n    std::vector<secp256k1_pedersen_commitment*> vpCommitsIn, vpCommitsOut;\n    vpCommitsIn.push_back(&txins[0].commitment);\n\n    vpCommitsOut.push_back(&txouts[0].commitment);\n    vpCommitsOut.push_back(&txouts[1].commitment);\n\n    BOOST_CHECK(secp256k1_pedersen_verify_tally(ctx, vpCommitsIn.data(), vpCommitsIn.size(), vpCommitsOut.data(), vpCommitsOut.size()));\n\n\n    for (size_t k = 0; k < txouts.size(); ++k) {\n        CTxOutValueTest &txout = txouts[k];\n\n        uint64_t value_out;\n\n        uint8_t *proof = &txout.vchRangeproof[0];\n        size_t nRangeProofLen = txout.vchRangeproof.size();\n        BOOST_CHECK(secp256k1_bulletproof_rangeproof_verify(ctx, scratch, gens, proof, nRangeProofLen, NULL, &txout.commitment, 1, 64, &secp256k1_generator_const_h, NULL, 0) == 1);\n\n        CPubKey ephemeral_key(txout.vchNonceCommitment);\n        BOOST_CHECK(ephemeral_key.IsValid());\n        uint256 nonce = kto_outs[k].ECDH(ephemeral_key);\n        CSHA256().Write(nonce.begin(), 32).Finalize(nonce.begin());\n        uint8_t blind_out[32];\n        BOOST_CHECK(secp256k1_bulletproof_rangeproof_rewind(ctx, gens, &value_out, blind_out, proof, nRangeProofLen, 0, &txout.commitment, &secp256k1_generator_const_h, nonce.begin(), NULL, 0));\n        BOOST_CHECK((int64_t)value_out == amount_outs[k]);\n    }\n\n    secp256k1_bulletproof_generators_destroy(ctx, gens);\n    secp256k1_scratch_space_destroy(scratch);\n    secp256k1_context_destroy(ctx);\n}\n\nBOOST_AUTO_TEST_CASE(ct_parameters_test)\n{\n    //for (size_t k = 0; k < 10000; ++k)\n    for (size_t k = 0; k < 100; ++k)\n    {\n        CAmount nValue = (GetRand((MAX_MONEY / (k+1))) / COIN) * COIN;\n        uint64_t min_value = 0;\n        int ct_exponent = 0;\n        int ct_bits = 32;\n\n        SelectRangeProofParameters(nValue, min_value, ct_exponent, ct_bits);\n    };\n}\n\nBOOST_AUTO_TEST_CASE(ct_commitment_test)\n{\n    secp256k1_context *ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY);\n\n    secp256k1_pedersen_commitment commitment1, commitment2, commitment3;\n    uint8_t blind[32];\n    memset(blind, 0, 32);\n\n    BOOST_CHECK(secp256k1_pedersen_commit(ctx, &commitment1, blind, 10, &secp256k1_generator_const_h, &secp256k1_generator_const_g));\n    BOOST_CHECK(HexStr(commitment1.data, commitment1.data+33) == \"093806b3e479859dc6dd508eca22257d796bba3e32a6616cc97b51723b50a5f429\");\n\n    memset(blind, 1, 32);\n    BOOST_CHECK(secp256k1_pedersen_commit(ctx, &commitment2, blind, 10, &secp256k1_generator_const_h, &secp256k1_generator_const_g));\n    BOOST_CHECK(HexStr(commitment2.data, commitment2.data+33) == \"09badd85325926c329aa62f5a7d37d0a015aabfb52608052d277530bd025ddc971\");\n\n    secp256k1_pedersen_commitment *pc[2];\n    pc[0] = &commitment1;\n    pc[1] = &commitment2;\n    BOOST_CHECK(secp256k1_pedersen_commitment_sum(ctx, &commitment3, pc, 2));\n    BOOST_CHECK(HexStr(commitment3.data, commitment3.data+33) == \"09e922a6c61aecd734d79ce41dbf09f71779bfcca6d3f30e4495923eb9801fb9a2\");\n\n    secp256k1_context_destroy(ctx);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "f68b00e9b69268e062e109aea08657dcb7abe7c2", "size": 11856, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/ct_tests.cpp", "max_stars_repo_name": "rhombus-project/rhombus-core", "max_stars_repo_head_hexsha": "7d183c143f4dee5b967291dc7ab64f54821e97fd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-28T01:29:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-28T01:29:00.000Z", "max_issues_repo_path": "src/test/ct_tests.cpp", "max_issues_repo_name": "rhombus-project/rhombus-core", "max_issues_repo_head_hexsha": "7d183c143f4dee5b967291dc7ab64f54821e97fd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/test/ct_tests.cpp", "max_forks_repo_name": "rhombus-project/rhombus-core", "max_forks_repo_head_hexsha": "7d183c143f4dee5b967291dc7ab64f54821e97fd", "max_forks_repo_licenses": ["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.2830188679, "max_line_length": 222, "alphanum_fraction": 0.6812584345, "num_tokens": 3658, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4694271085622208}}
{"text": "/*! @file pitts_tensortrain_from_dense_twosided.hpp\n* @brief conversion of a dense tensor to the tensor-train format (based on a hopefully faster TSQR algorithm, two-sided variant)\n* @author Melven Roehrig-Zoellner <Melven.Roehrig-Zoellner@DLR.de>\n* @date 2020-08-08\n* @copyright Deutsches Zentrum fuer Luft- und Raumfahrt e. V. (DLR), German Aerospace Center\n*\n**/\n\n// include guard\n#ifndef PITTS_TENSORTRAIN_FROM_DENSE_TWOSIDED_HPP\n#define PITTS_TENSORTRAIN_FROM_DENSE_TWOSIDED_HPP\n\n// includes\n#include <limits>\n#include <numeric>\n#pragma GCC push_options\n#pragma GCC optimize(\"no-unsafe-math-optimizations\")\n#include <Eigen/Dense>\n#pragma GCC pop_options\n#include \"pitts_tensortrain.hpp\"\n#include \"pitts_multivector.hpp\"\n#include \"pitts_multivector_tsqr.hpp\"\n#include \"pitts_multivector_transform.hpp\"\n#include \"pitts_multivector_transpose.hpp\"\n#include \"pitts_multivector_eigen_adaptor.hpp\"\n#include \"pitts_tensor2.hpp\"\n#include \"pitts_tensor2_eigen_adaptor.hpp\"\n#include \"pitts_timer.hpp\"\n\n//! namespace for the library PITTS (parallel iterative tensor train solvers)\nnamespace PITTS\n{\n  //! namespace for helper functionality\n  namespace internal\n  {\n    //! helper namespace for high-order SVD functionality (e.g. TensorTrain_fromDense)\n    namespace HOSVD\n    {\n      template<typename T>\n      void split(const MultiVector<T>& X, MultiVector<T>& Y, Tensor2<T>& M, int nextDim, T rankTolerance, int maxRank)\n      {\n        using EigenMatrix = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>;\n        Eigen::JacobiSVD<EigenMatrix> svd;\nstd::cout << \"HOSVD::split  matrix dimensions: \" << X.rows() << \" x \" << X.cols() << \"\\n\";\n        if( X.rows() > 10*X.cols() )\n        {\n          // calculate QR decomposition (QR-trick: X=QR,SVD(R))\n          block_TSQR(X, M, 0, false);\n          svd.compute(ConstEigenMap(M), Eigen::ComputeThinU | Eigen::ComputeThinV);\n        }\n        else\n        {\n          svd.compute(ConstEigenMap(X), Eigen::ComputeThinU | Eigen::ComputeThinV);\n        }\n\nstd::cout << \"singular values: \" << svd.singularValues().transpose() << \"\\n\";\n\n        // truncate svd\n        svd.setThreshold(rankTolerance);\n        int rank = svd.rank();\n        if( maxRank > 0 )\n          rank = std::min(maxRank, rank);\n\n        // copy right singular vectors\n        M.resize(X.cols(), rank);\n        EigenMap(M) = svd.matrixV().leftCols(rank);\n\n        // transform input, s.t. Y \\approx X M\n        transform(X, M, Y, {X.rows()/nextDim, rank*nextDim});\n      }\n    }\n  }\n\n\n  //! calculate tensor-train decomposition of a tensor stored in fully dense format\n  //!\n  //! Passing a large enough buffer in work helps to avoid costly reallocations + later page-faults for large data.\n  //!\n  //! @warning To reduce memory overhead, this function will overwrite the input arguments with temporary data.\n  //!          Please pass a copy of the data if you still need it!\n  //!\n  //! @tparam T         underlying data type (double, complex, ...)\n  //!\n  //! @param X              input tensor, overwritten and modified output, dimension must be (size/lastDim, lastDim) where lastDim = dimensions.back()\n  //! @param dimensions     tensor dimensions, input is interpreted in Fortran storage order (first index changes the fastest)\n  //! @param work           buffer for temporary data, will be resized and modified\n  //! @param rankTolerance  approximation accuracy, used to reduce the TTranks of the resulting tensor train\n  //! @param maxRank        maximal TTrank (bond dimension), unbounded by default\n  //! @return               resulting tensor train\n  //!\n  template<typename T>\n  TensorTrain<T> fromDense_twoSided(MultiVector<T>& X, MultiVector<T>& work, const std::vector<int>& dimensions, T rankTolerance = std::sqrt(std::numeric_limits<T>::epsilon()), int maxRank = -1)\n  {\n    // timer\n    const auto timer = PITTS::timing::createScopedTimer<TensorTrain<T>>();\n\n    // abort early for zero dimensions\n    if( dimensions.size() == 0 )\n    {\n      if( X.rows()*X.cols() !=  0 )\n        throw std::out_of_range(\"Mismatching dimensions in TensorTrain<T>::fromDense\");\n      return TensorTrain<T>{dimensions};\n    }\n\n    const auto totalSize = std::accumulate(begin(dimensions), end(dimensions), (std::ptrdiff_t)1, std::multiplies<std::ptrdiff_t>());\n    const auto nDims = dimensions.size();\n    if( X.rows() != totalSize/dimensions[nDims-1] || X.cols() != dimensions[nDims-1] )\n      throw std::out_of_range(\"Mismatching dimensions in TensorTrain<T>::fromDense\");\n\n    TensorTrain<T> result(dimensions);\n\n    // actually convert to tensor train format\n    Tensor2<T> M;\n    for(int ii = 0; ii < nDims; ii++)\n    {\n      if( ii % 2 == 0 )\n      {\n        // right part\n        const auto iDim = nDims - 1 - ii/2;\n        if( ii > 0 )\n        {\n          const auto r1 = result.subTensors()[iDim+1].r1();\n          const auto n = dimensions[iDim];\n          transpose(work, X, {(work.rows()*work.cols())/(n*r1), n*r1}, true);\n        }\n        if( ii != nDims-1 )\n        {\n          internal::HOSVD::split(X, work, M, 1, rankTolerance, maxRank);\n        }\n        else\n        {\n          M.resize(X.cols(), X.rows());\n          EigenMap(M) = ConstEigenMap(X).transpose();\n        }\n\n        auto& subT = result.editableSubTensors()[iDim];\n        const int rank = M.r2();\n        subT.resize(rank, dimensions[iDim], X.cols()/dimensions[iDim]);\n        for(int i = 0; i < rank; i++)\n          for(int j = 0; j < subT.n(); j++)\n            for(int k = 0; k < subT.r2(); k++)\n              subT(i,j,k) = M(j+subT.n()*k, i);\n      }\n      else\n      {\n        // left part\n        const auto iDim = ii / 2;\n        {\n          const auto r2 = (iDim == 0 ) ? 1 : result.subTensors()[iDim-1].r2();\n          const auto n = dimensions[iDim];\n          transpose(work, X, {(work.cols()*work.rows())/(n*r2), n*r2}, false);\n        }\n        if( ii != nDims - 1 )\n        {\n          internal::HOSVD::split(X, work, M, 1, rankTolerance, maxRank);\n        }\n        else\n        {\n          M.resize(X.cols(), X.rows());\n          EigenMap(M) = ConstEigenMap(X).transpose();\n        }\n\n        auto& subT = result.editableSubTensors()[iDim];\n        const int rank = M.r2();\n        subT.resize(X.cols()/dimensions[iDim], dimensions[iDim], rank);\n        for(int i = 0; i < rank; i++)\n          for(int j = 0; j < subT.n(); j++)\n            for(int k = 0; k < subT.r1(); k++)\n              subT(k,j,i) = M(k+j*subT.r1(), i);\n      }\n    }\n\n    return result;\n  }\n\n}\n\n\n#endif // PITTS_TENSORTRAIN_FROM_DENSE_TWOSIDED_HPP\n", "meta": {"hexsha": "5f8df9ea0b876529c756dfe157349f707bb7dd8c", "size": 6534, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/pitts_tensortrain_from_dense_twosided.hpp", "max_stars_repo_name": "melven/pitts", "max_stars_repo_head_hexsha": "491f503a99a7d1161a27672955ae53ca6b5d3412", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-12-31T08:28:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T14:48:49.000Z", "max_issues_repo_path": "src/pitts_tensortrain_from_dense_twosided.hpp", "max_issues_repo_name": "melven/pitts", "max_issues_repo_head_hexsha": "491f503a99a7d1161a27672955ae53ca6b5d3412", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pitts_tensortrain_from_dense_twosided.hpp", "max_forks_repo_name": "melven/pitts", "max_forks_repo_head_hexsha": "491f503a99a7d1161a27672955ae53ca6b5d3412", "max_forks_repo_licenses": ["BSD-3-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.3, "max_line_length": 194, "alphanum_fraction": 0.6117232935, "num_tokens": 1763, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708698, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4694271033262415}}
{"text": "#ifndef PYBNESIAN_LEARNING_INDEPENDENCES_CONTINUOUS_RCOT_HPP\n#define PYBNESIAN_LEARNING_INDEPENDENCES_CONTINUOUS_RCOT_HPP\n\n#include <random>\n#include <Eigen/Eigenvalues>\n#include <learning/independences/independence.hpp>\n#include <util/math_constants.hpp>\n#include <util/basic_eigen_ops.hpp>\n#include <util/chisquaresum.hpp>\n\nusing learning::independences::IndependenceTest;\n\nnamespace learning::independences::continuous {\n\ntemplate <typename MatrixType>\ntypename MatrixType::Scalar rf_sigma_impl(MatrixType& m) {\n    using Scalar = typename MatrixType::Scalar;\n    using VectorType = Matrix<Scalar, Dynamic, 1>;\n    auto r = std::min(static_cast<decltype(m.rows())>(500), m.rows());\n    VectorType distances(r * (r - 1) / 2);\n\n    for (int i = r - 1, j = 0; i > 0; --i, j += i) {\n        distances.segment(j, i) = (m.topRows(i).rowwise() - m.row(i)).matrix().rowwise().norm();\n    }\n\n    // Compute median\n    int median_index = distances.rows() / 2;\n\n    double median;\n    if (distances.rows() % 2 == 1) {\n        std::nth_element(distances.data(), distances.data() + median_index, distances.data() + distances.rows());\n        median = distances[median_index];\n    } else {\n        std::sort(distances.data(), distances.data() + distances.rows());\n        median = 0.5 * (distances[median_index - 1] + distances[median_index]);\n    }\n\n    if (median == 0) median = 1;\n\n    return median;\n}\n\nclass RCoT : public IndependenceTest {\npublic:\n    RCoT(const DataFrame& df, int random_fourier_xy = 5, int random_fourier_z = 100)\n        : m_df(df.normalize()),\n          m_num_random_fourier_xy(random_fourier_xy),\n          m_num_random_fourier_z(random_fourier_z),\n          m_dfourier_x(),\n          m_dfourier_y(),\n          m_dfourier_z(),\n          m_dsigma(),\n          m_ffourier_x(),\n          m_ffourier_y(),\n          m_ffourier_z(),\n          m_fsigma() {\n        auto continuous_indices = df.continuous_columns();\n\n        if (continuous_indices.size() < 2) {\n            throw std::invalid_argument(\"DataFrame does not contain enough continuous columns.\");\n        }\n\n        auto type = m_df.same_type(continuous_indices);\n\n        switch (type->id()) {\n            case Type::DOUBLE: {\n                m_dfourier_x = MatrixXd(df.num_rows(), m_num_random_fourier_xy);\n                m_dfourier_y = MatrixXd(df.num_rows(), m_num_random_fourier_xy);\n                m_dfourier_z = MatrixXd(df.num_rows(), m_num_random_fourier_z);\n                m_tmp_dcov = MatrixXd(df.num_rows(), m_num_random_fourier_xy * m_num_random_fourier_xy);\n                m_dsigma = VectorXd(df->num_columns());\n\n                for (auto c : continuous_indices) {\n                    if (m_df.null_count(c) == 0) {\n                        auto x_vec = m_df.to_eigen<false, arrow::DoubleType, false>(c);\n                        m_dsigma(c) = rf_sigma_impl(*x_vec);\n                    }\n                }\n\n                break;\n            }\n            case Type::FLOAT: {\n                m_ffourier_x = MatrixXf(df.num_rows(), m_num_random_fourier_xy);\n                m_ffourier_y = MatrixXf(df.num_rows(), m_num_random_fourier_xy);\n                m_ffourier_z = MatrixXf(df.num_rows(), m_num_random_fourier_z);\n                m_tmp_fcov = MatrixXf(df.num_rows(), m_num_random_fourier_xy * m_num_random_fourier_xy);\n                m_fsigma = VectorXf(df->num_columns());\n\n                for (auto c : continuous_indices) {\n                    if (m_df.null_count(c) == 0) {\n                        auto x_vec = m_df.to_eigen<false, arrow::FloatType, false>(c);\n                        m_fsigma(c) = rf_sigma_impl(*x_vec);\n                    }\n                }\n\n                break;\n            }\n            default:\n                throw std::runtime_error(\"[RCoT] Unreachable code\");\n        }\n    }\n\n    double pvalue(const std::string& x, const std::string& y) const override;\n    template <typename ArrowType>\n    double pvalue(const std::string& x, const std::string& y) const;\n\n    double pvalue(const std::string& x, const std::string& y, const std::string& z) const override;\n    template <typename ArrowType>\n    double pvalue(const std::string& x, const std::string& y, const std::string& z) const;\n\n    double pvalue(const std::string& x, const std::string& y, const std::vector<std::string>& z) const override;\n    template <typename ArrowType>\n    double pvalue(const std::string& x, const std::string& y, const std::vector<std::string>& z) const;\n\n    int num_variables() const override { return m_df->num_columns(); }\n\n    std::vector<std::string> variable_names() const override { return m_df.column_names(); }\n\n    const std::string& name(int i) const override { return m_df.name(i); }\n\n    bool has_variables(const std::string& name) const override { return m_df.has_columns(name); }\n\n    bool has_variables(const std::vector<std::string>& cols) const override { return m_df.has_columns(cols); }\n\nprivate:\n    template <typename Scalar>\n    Scalar rf_sigma(int index) const {\n        if constexpr (std::is_same_v<Scalar, double>)\n            return m_dsigma(index);\n        else\n            return m_fsigma(index);\n    }\n\n    template <typename Scalar>\n    Matrix<Scalar, Dynamic, Dynamic>& fourier_x() const {\n        if constexpr (std::is_same_v<Scalar, double>)\n            return m_dfourier_x;\n        else\n            return m_ffourier_x;\n    }\n\n    template <typename Scalar>\n    Matrix<Scalar, Dynamic, Dynamic>& fourier_y() const {\n        if constexpr (std::is_same_v<Scalar, double>)\n            return m_dfourier_y;\n        else\n            return m_ffourier_y;\n    }\n\n    template <typename Scalar>\n    Matrix<Scalar, Dynamic, Dynamic>& fourier_z() const {\n        if constexpr (std::is_same_v<Scalar, double>)\n            return m_dfourier_z;\n        else\n            return m_ffourier_z;\n    }\n\n    template <typename Scalar>\n    Matrix<Scalar, Dynamic, Dynamic>& tmp_cov() const {\n        if constexpr (std::is_same_v<Scalar, double>)\n            return m_tmp_dcov;\n        else\n            return m_tmp_fcov;\n    }\n\n    template <typename Mat>\n    Matrix<typename Mat::Scalar, Dynamic, 1> eigenvalues_covariance(Mat& fourier_x, Mat& fourier_y) const;\n\n    template <typename VectorType, typename FeatureType>\n    double RIT_impl(\n        VectorType& x, VectorType& y, FeatureType& feat_x, FeatureType& feat_y, double sigma_x, double sigma_y) const;\n    template <bool contains_null, typename VectorType>\n    double RIT(int x_index, int y_index, VectorType& x, VectorType& y) const;\n\n    template <typename VectorType, typename MatType, typename FeatureType>\n    double TestWithZ_impl(VectorType& x,\n                          VectorType& y,\n                          MatType& z,\n                          FeatureType& feat_x,\n                          FeatureType& feat_y,\n                          FeatureType& feat_z,\n                          double sigma_x,\n                          double sigma_y,\n                          double sigma_z) const;\n\n    template <bool contains_null, typename VectorType>\n    double RSingleZ(int x_index, int y_index, int z_index, VectorType& x, VectorType& y, VectorType& z) const;\n\n    template <bool contains_null, typename VectorType, typename MatType>\n    double RMultiZ(int x_index, int y_index, VectorType& x, VectorType& y, MatType& z) const;\n\n    DataFrame m_df;\n    int m_num_random_fourier_xy;\n    int m_num_random_fourier_z;\n    // Cache fourier matrices and sigmas (double or float).\n    mutable MatrixXd m_dfourier_x;\n    mutable MatrixXd m_dfourier_y;\n    mutable MatrixXd m_dfourier_z;\n    mutable MatrixXd m_tmp_dcov;\n    VectorXd m_dsigma;\n    mutable MatrixXf m_ffourier_x;\n    mutable MatrixXf m_ffourier_y;\n    mutable MatrixXf m_ffourier_z;\n    mutable MatrixXf m_tmp_fcov;\n    VectorXf m_fsigma;\n};\n\ntemplate <typename InputMatrix, typename OutputMatrix>\nvoid random_fourier_features(InputMatrix& m,\n                             typename InputMatrix::Scalar sigma,\n                             int num_features,\n                             OutputMatrix& fourier_features) {\n    static_assert(std::is_same_v<typename InputMatrix::Scalar, typename OutputMatrix::Scalar>,\n                  \"Input/Output matrices must have the same type\");\n\n    using Scalar = typename InputMatrix::Scalar;\n    using MatrixType = Matrix<Scalar, Dynamic, Dynamic>;\n    using VectorType = Matrix<Scalar, Dynamic, 1>;\n\n    MatrixType W(m.cols(), num_features);\n    VectorType b(num_features);\n\n    std::mt19937 rng(std::random_device{}());\n    std::normal_distribution<Scalar> normal;\n    for (auto j = 0; j < W.cols(); ++j) {\n        for (auto i = 0; i < W.rows(); ++i) {\n            W(i, j) = normal(rng);\n        }\n    }\n    W *= (1 / sigma);\n\n    std::uniform_real_distribution<Scalar> unif;\n    for (auto i = 0; i < num_features; ++i) {\n        b(i) = unif(rng);\n    }\n    b *= 2 * util::pi<Scalar>;\n\n    fourier_features.noalias() = (m * W).rowwise() + b.transpose();\n    fourier_features = fourier_features.array().cos().matrix();\n    fourier_features = fourier_features * util::root_two<Scalar>;\n}\n\ntemplate <typename Mat, typename TmpMat>\nMatrix<typename Mat::Scalar, Dynamic, 1> eigenvalues_covariance_impl(Mat& fourier_x, Mat& fourier_y, TmpMat& tmp_mat) {\n    using Scalar = typename Mat::Scalar;\n    using MatrixType = Matrix<Scalar, Dynamic, Dynamic>;\n\n    for (int i = 0; i < fourier_x.cols(); ++i) {\n        tmp_mat.block(0, i * fourier_y.cols(), tmp_mat.rows(), fourier_y.cols()) =\n            fourier_y.array().colwise() * fourier_x.col(i).array();\n    }\n    auto cov = util::sse_mat(tmp_mat) * (1 / static_cast<Scalar>(fourier_x.rows()));\n    auto eigen_solver = Eigen::SelfAdjointEigenSolver<MatrixType>(cov, Eigen::DecompositionOptions::EigenvaluesOnly);\n    return eigen_solver.eigenvalues();\n}\n\ntemplate <typename Mat>\nMatrix<typename Mat::Scalar, Dynamic, 1> RCoT::eigenvalues_covariance(Mat& fourier_x, Mat& fourier_y) const {\n    using Scalar = typename Mat::Scalar;\n    auto& cc = tmp_cov<Scalar>();\n\n    if (fourier_x.rows() != cc.rows()) {\n        auto tmp = cc.topRows(fourier_x.rows());\n        return eigenvalues_covariance_impl(fourier_x, fourier_y, tmp);\n    } else {\n        return eigenvalues_covariance_impl(fourier_x, fourier_y, cc);\n    }\n}\n\ntemplate <typename VectorType>\nMatrix<typename VectorType::Scalar, Dynamic, 1> filter_positive_elements(const VectorType& v) {\n    using Scalar = typename VectorType::Scalar;\n    using NewVectorType = Matrix<Scalar, Dynamic, 1>;\n    std::vector<Scalar> positive;\n    for (int i = 0; i < v.rows(); ++i) {\n        if (v(i) > 0) positive.push_back(v(i));\n    }\n\n    NewVectorType res(positive.size());\n    for (size_t i = 0; i < positive.size(); ++i) {\n        res(i) = positive[i];\n    }\n\n    return res;\n}\n\ntemplate <typename VectorType, typename FeatureType>\ndouble RCoT::RIT_impl(\n    VectorType& x, VectorType& y, FeatureType& feat_x, FeatureType& feat_y, double sigma_x, double sigma_y) const {\n    random_fourier_features(x, sigma_x, m_num_random_fourier_xy, feat_x);\n    random_fourier_features(y, sigma_y, m_num_random_fourier_xy, feat_y);\n\n    util::normalize_cols(feat_x);\n    util::normalize_cols(feat_y);\n\n    auto Cxy = util::cov(feat_x, feat_y);\n    auto sta = x.rows() * Cxy.squaredNorm();\n    auto eigs = eigenvalues_covariance(feat_x, feat_y);\n    auto pos_eigs = filter_positive_elements(eigs);\n\n    if (pos_eigs.rows() < 4) {\n        auto pvalue = util::hbe_complement(pos_eigs, sta);\n        if (pvalue < 0) return 0;\n        return pvalue;\n    }\n\n    try {\n        auto pvalue = util::lpb4_complement(pos_eigs, sta);\n        if (pvalue < 0) return 0;\n        return pvalue;\n    } catch (std::exception&) {\n        auto pvalue = util::hbe_complement(pos_eigs, sta);\n        if (pvalue < 0) return 0;\n        return pvalue;\n    }\n}\n\ntemplate <bool contains_null, typename VectorType>\ndouble RCoT::RIT(int x_index, int y_index, VectorType& x, VectorType& y) const {\n    using Scalar = typename VectorType::Scalar;\n\n    if constexpr (contains_null) {\n        Scalar sigma_x = rf_sigma_impl(x);\n        Scalar sigma_y = rf_sigma_impl(y);\n\n        auto feat_x = fourier_x<Scalar>().topRows(x.rows());\n        auto feat_y = fourier_y<Scalar>().topRows(y.rows());\n\n        return RIT_impl(x, y, feat_x, feat_y, sigma_x, sigma_y);\n    } else {\n        Scalar sigma_x = rf_sigma<Scalar>(x_index);\n        Scalar sigma_y = rf_sigma<Scalar>(y_index);\n\n        auto& feat_x = fourier_x<Scalar>();\n        auto& feat_y = fourier_y<Scalar>();\n\n        return RIT_impl(x, y, feat_x, feat_y, sigma_x, sigma_y);\n    }\n}\n\ntemplate <typename VectorType, typename MatType, typename FeatureType>\ndouble RCoT::TestWithZ_impl(VectorType& x,\n                            VectorType& y,\n                            MatType& z,\n                            FeatureType& feat_x,\n                            FeatureType& feat_y,\n                            FeatureType& feat_z,\n                            double sigma_x,\n                            double sigma_y,\n                            double sigma_z) const {\n    random_fourier_features(x, sigma_x, m_num_random_fourier_xy, feat_x);\n    random_fourier_features(y, sigma_y, m_num_random_fourier_xy, feat_y);\n    random_fourier_features(z, sigma_z, m_num_random_fourier_z, feat_z);\n\n    util::normalize_cols(feat_x);\n    util::normalize_cols(feat_y);\n    util::normalize_cols(feat_z);\n\n    auto Cxy = util::cov(feat_x, feat_y);\n\n    auto Czz = util::cov(feat_z);\n    Czz.diagonal().array() += 1e-10;\n\n    auto i_Czz = Czz.inverse();\n\n    auto Cxz = util::cov(feat_x, feat_z);\n    auto Czy = util::cov(feat_z, feat_y);\n\n    auto z_i_Czz = feat_z * i_Czz;\n    feat_x = feat_x - z_i_Czz * Cxz.transpose();\n    feat_y = feat_y - z_i_Czz * Czy;\n\n    auto Cxy_z = Cxy - Cxz * i_Czz * Czy;\n\n    auto sta = x.rows() * Cxy_z.squaredNorm();\n    auto eigs = eigenvalues_covariance(feat_x, feat_y);\n    auto pos_eigs = filter_positive_elements(eigs);\n\n    if (m_num_random_fourier_z == 1 || pos_eigs.rows() < 4) {\n        auto pvalue = util::hbe_complement(pos_eigs, sta);\n        if (pvalue < 0) return 0;\n        return pvalue;\n    }\n\n    try {\n        auto pvalue = util::lpb4_complement(pos_eigs, sta);\n        if (pvalue < 0) return 0;\n        return pvalue;\n    } catch (std::exception&) {\n        auto pvalue = util::hbe_complement(pos_eigs, sta);\n        if (pvalue < 0) return 0;\n        return pvalue;\n    }\n}\n\ntemplate <bool contains_null, typename VectorType>\ndouble RCoT::RSingleZ(int x_index, int y_index, int z_index, VectorType& x, VectorType& y, VectorType& z) const {\n    using Scalar = typename VectorType::Scalar;\n\n    if constexpr (contains_null) {\n        Scalar sigma_x = rf_sigma_impl(x);\n        Scalar sigma_y = rf_sigma_impl(y);\n        Scalar sigma_z = rf_sigma_impl(z);\n\n        auto feat_x = fourier_x<Scalar>().topRows(x.rows());\n        auto feat_y = fourier_y<Scalar>().topRows(y.rows());\n        auto feat_z = fourier_z<Scalar>().topRows(z.rows());\n\n        return TestWithZ_impl(x, y, z, feat_x, feat_y, feat_z, sigma_x, sigma_y, sigma_z);\n    } else {\n        Scalar sigma_x = rf_sigma<Scalar>(x_index);\n        Scalar sigma_y = rf_sigma<Scalar>(y_index);\n        Scalar sigma_z = rf_sigma<Scalar>(z_index);\n\n        auto& feat_x = fourier_x<Scalar>();\n        auto& feat_y = fourier_y<Scalar>();\n        auto& feat_z = fourier_z<Scalar>();\n\n        return TestWithZ_impl(x, y, z, feat_x, feat_y, feat_z, sigma_x, sigma_y, sigma_z);\n    }\n}\n\ntemplate <bool contains_null, typename VectorType, typename MatType>\ndouble RCoT::RMultiZ(int x_index, int y_index, VectorType& x, VectorType& y, MatType& z) const {\n    using Scalar = typename VectorType::Scalar;\n\n    if constexpr (contains_null) {\n        Scalar sigma_x = rf_sigma_impl(x);\n        Scalar sigma_y = rf_sigma_impl(y);\n        Scalar sigma_z = rf_sigma_impl(z);\n\n        auto feat_x = fourier_x<Scalar>().topRows(x.rows());\n        auto feat_y = fourier_y<Scalar>().topRows(y.rows());\n        auto feat_z = fourier_z<Scalar>().topRows(z.rows());\n\n        return TestWithZ_impl(x, y, z, feat_x, feat_y, feat_z, sigma_x, sigma_y, sigma_z);\n    } else {\n        Scalar sigma_x = rf_sigma<Scalar>(x_index);\n        Scalar sigma_y = rf_sigma<Scalar>(y_index);\n        Scalar sigma_z = rf_sigma_impl(z);\n\n        auto& feat_x = fourier_x<Scalar>();\n        auto& feat_y = fourier_y<Scalar>();\n        auto& feat_z = fourier_z<Scalar>();\n\n        return TestWithZ_impl(x, y, z, feat_x, feat_y, feat_z, sigma_x, sigma_y, sigma_z);\n    }\n}\n\nusing DynamicRCoT = DynamicIndependenceTestAdaptator<RCoT>;\n\n}  // namespace learning::independences::continuous\n\n#endif  // PYBNESIAN_LEARNING_INDEPENDENCES_CONTINUOUS_RCOT_HPP\n", "meta": {"hexsha": "6196a41cafff61d359e425d87c08283cb7442ef6", "size": 16695, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pybnesian/learning/independences/continuous/RCoT.hpp", "max_stars_repo_name": "vishalbelsare/PyBNesian", "max_stars_repo_head_hexsha": "0190cd4cf6d133746741e2750004ccf0a9061fbd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2021-06-22T19:21:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T13:08:05.000Z", "max_issues_repo_path": "pybnesian/learning/independences/continuous/RCoT.hpp", "max_issues_repo_name": "vishalbelsare/PyBNesian", "max_issues_repo_head_hexsha": "0190cd4cf6d133746741e2750004ccf0a9061fbd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pybnesian/learning/independences/continuous/RCoT.hpp", "max_forks_repo_name": "vishalbelsare/PyBNesian", "max_forks_repo_head_hexsha": "0190cd4cf6d133746741e2750004ccf0a9061fbd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-08-20T13:44:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T02:57:02.000Z", "avg_line_length": 36.6923076923, "max_line_length": 119, "alphanum_fraction": 0.6300089847, "num_tokens": 4257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.812867299704166, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4694270980902621}}
{"text": "#include <armadillo>\n#include \"../Array.hpp\"\n#include \"../Function.hpp\"\n#include \"../NodePool.hpp\"\n#include \"../Operator.hpp\"\n#include \"../IO.hpp\"\n#include \"gtest/gtest.h\"\n#include <boost/filesystem.hpp>\n#include <unistd.h>\n\nnamespace gt=::testing;\n\n#define MRange gt::Range(1, 4)\n#define NRange gt::Range(1, 4)\n#define PRange gt::Range(1, 4)\n\nclass MPITest : public gt::TestWithParam\n<std::tr1::tuple<MPI_Comm, int, int, int> > {\nprotected:\n  virtual void SetUp() {\n\n    comm = std::tr1::get<0>(GetParam());\n\n    m  = std::tr1::get<1>(GetParam());\n    n  = std::tr1::get<2>(GetParam());\n    p  = std::tr1::get<3>(GetParam());\n\n    MPI_Comm_size(comm, &size);\n    MPI_Comm_rank(comm, &rank);\n  }\n\n  virtual void TearDown() {\n\n  }\n\n  MPI_Comm comm;\n  int size;\n  int rank;\n\n  int m;\n  int n;\n  int p;\n};\n\ntemplate<class T>\narma::Cube<T> make_seqs(int m, int n, int p){\n  arma::Cube<T> v1(m, n, p);\n\n  int cnt = 0;\n  for(int k = 0; k < p; ++k){\n    for(int j = 0; j < n; ++j){\n      for(int i = 0; i < m; ++i){\n        v1(i, j, k) = cnt;\n        cnt++;\n      }\n    }\n  }\n\n  return v1;\n}\n\n///:set dtypes = ['int', 'float', 'double']\n///:set fdtypes = ['float', 'double']\n\nusing namespace oa::funcs;\n\nnamespace{\n  TEST(Array, Basic){\n    int rank, size;\n    MPI_Comm_rank(MPI_COMM_WORLD, &rank);\n    MPI_Comm_size(MPI_COMM_WORLD, &size);\n    \n    ArrayPtr A1 = ones(MPI_COMM_SELF, {10,10,10}, 1, DATA_INT);\n    if(rank == 0){\n      EXPECT_FALSE(A1->is_scalar());\n      EXPECT_FALSE(A1->is_seqs_scalar());\n      EXPECT_TRUE(A1->is_seqs());\n      EXPECT_EQ(A1->shape(), Shape({10,10,10}));\n    }\n\n    ArrayPtr A2 = ones(MPI_COMM_WORLD, {1,1,1}, 1, DATA_INT);\n    if(rank == 0){\n      EXPECT_TRUE(A2->is_scalar());\n      EXPECT_FALSE(A2->is_seqs_scalar());\n      EXPECT_FALSE(A2->is_seqs());\n      EXPECT_EQ(A2->shape(), Shape({1,1,1}));\n    }\n\n    ArrayPtr A3 = ones(MPI_COMM_WORLD, {1,1,1}, 1, DATA_INT);\n    if(rank == 0){\n      EXPECT_TRUE(A3->is_scalar());\n      EXPECT_FALSE(A3->is_seqs_scalar());\n      EXPECT_FALSE(A3->is_seqs());\n      EXPECT_EQ(A3->shape(), Shape({1,1,1}));\n    }\n\n    ArrayPtr A4 = ones(MPI_COMM_SELF, {1,1,1}, 1, DATA_INT);\n    if(rank == 0){\n      EXPECT_TRUE(A4->is_scalar());\n      EXPECT_TRUE(A4->is_seqs_scalar());\n      EXPECT_TRUE(A4->is_seqs());\n      EXPECT_EQ(A4->shape(), Shape({1,1,1}));\n    }\n\n  }\n\n\n  //test save and load function\n  TEST_P(MPITest, InputAndOutput){\n    ArrayPtr A = oa::funcs::seqs(MPI_COMM_WORLD, {m,n,p}, 1);\n    oa::io::save(A, \"/tmp/A.nc\", \"data\");\n\n    // const boost::filesystem::path fileName(\"/tmp/A.nc\");\n\n    // bool b = boost::filesystem::exists(boost::filesystem::status(fileName));\n    // std::cout<<b<<std::endl;\n    \n    if(rank == 0){\n      std::ifstream infile(\"/tmp/A.nc\");\n      EXPECT_TRUE(infile.good());      \n    }\n      \n    ArrayPtr B = oa::io::load(\"/tmp/A.nc\", \"data\", MPI_COMM_WORLD);\n\n    ArrayPtr A1 = to_rank0(A);\n    ArrayPtr B1 = to_rank0(B);\n    \n    if(rank == 0){\n      EXPECT_TRUE(oa::funcs::is_equal(A1, B1));\n    }\n  }\n  \n  TEST_P(MPITest, ArrayCreation){\n    ///:for t in dtypes\n    {\n      ArrayPtr A1 = oa::funcs::to_rank0(oa::funcs::seqs(comm, {m, n, p}, 1,\n                      oa::utils::dtype<${t}$>::type));\n      arma::Cube<${t}$> B1 = make_seqs<${t}$>(m, n, p);\n\n      ArrayPtr A2 =\n        oa::funcs::to_rank0(oa::funcs::consts<${t}$>(comm, {m, n, p},\n                        ${t}$(2),\n                        oa::utils::dtype<${t}$>::type));\n      arma::Cube<${t}$> B2(m, n, p);\n      B2.fill(${t}$(2));\n\n      if(rank == 0){\n        EXPECT_TRUE(oa::funcs::is_equal(A1, B1));\n        EXPECT_TRUE(oa::funcs::is_equal(A2, B2));\n      }\n    }\n    ///:endfor\n  }\n\n\n  TEST_P(MPITest, BasicMath_Arrray_Array){\n    ///:for t1 in dtypes\n    ///:for t2 in dtypes\n    {\n      DataType dt1  = oa::utils::dtype<${t1}$>::type;\n      DataType dt2  = oa::utils::dtype<${t2}$>::type;\n      \n      NodePtr N1 = oa::ops::new_node(oa::funcs::seqs(comm, {m, n, p}, 0, dt1));\n      NodePtr N2 = oa::ops::new_node(oa::funcs::consts(comm,\n                      {m, n, p},\n                      ${t2}$(2.0), 0));\n\n      \n      typedef otype<${t1}$, ${t2}$>::value result_type;\n      arma::Cube<result_type> C3;\n      arma::Cube<result_type> C1 = make_seqs<result_type>(m, n, p);\n      arma::Cube<result_type> C2(m,n,p);\n      C2.fill(result_type(2));\n      \n      ///:for o in [['+','PLUS'], ['-', 'MINUS'], ['%','MULT'], ['/', 'DIVD']]\n      {\n        NodePtr N3 = oa::ops::new_node(TYPE_${o[1]}$, N1, N2);\n        ArrayPtr A3 = oa::funcs::to_rank0(oa::ops::eval(N3));\n\n        C3 = C1 ${o[0]}$ C2;\n\n        // N1->get_data()->display(\"A1\");\n        // N2->get_data()->display(\"A2\");\n\n        if(rank == 0){\n          // A3->display(\"A3\");\n          // std::cout<<\"C3\"<<std::endl<<C3<<std::endl;\n          // std::cout<<\"Operation:${o[1]}$\"<<std::endl;\n          \n          EXPECT_TRUE(oa::funcs::is_equal(A3, C3));\n        }\n      }\n      ///:endfor\n    }\n    ///:endfor\n    ///:endfor\n  }\n\n  TEST_P(MPITest, BasicMath_Arrray_Scalar){\n    ///:for t1 in dtypes\n    ///:for t2 in dtypes\n    {\n      DataType dt1  = oa::utils::dtype<${t1}$>::type;\n      DataType dt2  = oa::utils::dtype<${t2}$>::type;\n      \n      NodePtr N1 = oa::ops::new_node(oa::funcs::consts(comm, {m, n, p},\n                      ${t1}$(3.0), 0));\n      NodePtr N2 = oa::ops::new_node(oa::funcs::consts(MPI_COMM_SELF,\n                      {1, 1, 1}, ${t2}$(2), 0));\n\n      typedef otype<${t1}$, ${t2}$>::value result_type;\n      arma::Cube<result_type> C3, C4;\n      arma::Cube<result_type> C1 = arma::ones<arma::Cube<result_type> >(m, n, p) * 3.0;\n      result_type  C2 = result_type(2);\n      \n      ///:for o in [['+','PLUS'], ['-', 'MINUS'], ['*','MULT'], ['/', 'DIVD']]\n      {\n      \tNodePtr N3 = oa::ops::new_node(TYPE_${o[1]}$, N1, N2);\n      \tNodePtr N4 = oa::ops::new_node(TYPE_${o[1]}$, N2, N1);        \n\tArrayPtr A3 = oa::funcs::to_rank0(oa::ops::eval(N3));\n\tArrayPtr A4 = oa::funcs::to_rank0(oa::ops::eval(N4));\n        \n\tC3 = C1 ${o[0]}$ C2;\n        C4 = C2 ${o[0]}$ C1;\n        \n\tif(rank == 0){\n          // std::cout<<\"${o[1]}$\"<<\"    ${o[0]}$\"<<std::endl;\n          // std::cout<<C3<<std::endl;\n          // A4->display(\"A4\");\n          // MPI_Barrier(A4->get_partition()->get_comm());\n\n\t  EXPECT_TRUE(oa::funcs::is_equal(A3, C3));\n\t  EXPECT_TRUE(oa::funcs::is_equal(A4, C4));\n\t}\n      }\n      ///:endfor\n    }\n    ///:endfor\n    ///:endfor\n  }\n\n\n  TEST_P(MPITest, GhostUpdate){\n    ///:for t in dtypes\n    {\n      ArrayPtr A1 =\n        oa::funcs::seqs(comm,{m*5, n*5, p*5}, 1, oa::utils::dtype<${t}$>::type);\n\n      // ArrayPtr A2 =\n      //   oa::funcs::seqs(comm,{m*5, n*5, p*5}, 2, oa::utils::dtype<${t}$>::type);\n\n      std::vector<MPI_Request> reqs; \n      update_ghost_start(A1, reqs, -1);\n      update_ghost_end(reqs);\n      reqs.clear();\n      \n      // update_ghost_start(A2, reqs, -1);\n      // update_ghost_end(reqs);\n      // reqs.clear();\n\n      // update_ghost_start(A3, reqs, -1);\n      // update_ghost_end(reqs);\n      // reqs.clear();\n      \n      // if(A1->local_size() > 0){\n      //   arma::Cube<${t}$> C1 = oa::utils::make_cube<${t}$>(A1->buffer_shape(),\n      //                                                      A1->get_buffer());\n      // }\n    }\n    ///:endfor\n  }\n\n\n  TEST_P(MPITest, MinMax){\n\n    ///:for t in dtypes\n    {\n      int sw = NO_STENCIL;\n      DataType dt = oa::utils::dtype<${t}$>::type;\n      ArrayPtr A = oa::funcs::rands(comm, {m,n,p}, sw, dt);\n      NodePtr NA = oa::ops::new_node(A);\n      //NA->display(\"NA\");\n\n      NodePtr N1 = oa::ops::new_node(TYPE_MAX, NA);\n      NodePtr N2 = oa::ops::new_node(TYPE_MIN, NA);\n      NodePtr N3 = oa::ops::new_node(TYPE_ABS_MAX, NA);\n      NodePtr N4 = oa::ops::new_node(TYPE_ABS_MIN, NA);\n      \n      NodePtr N5 = oa::ops::new_node(TYPE_MAX_AT, NA);\n      NodePtr N6 = oa::ops::new_node(TYPE_MIN_AT, NA);\n      NodePtr N7 = oa::ops::new_node(TYPE_ABS_MAX_AT, NA);\n      NodePtr N8 = oa::ops::new_node(TYPE_ABS_MIN_AT, NA);\n\n      ArrayPtr V1 = oa::funcs::to_rank0(oa::ops::eval(N1));\n      ArrayPtr V2 = oa::funcs::to_rank0(oa::ops::eval(N2));\n      ArrayPtr V3 = oa::funcs::to_rank0(oa::ops::eval(N3));\n      ArrayPtr V4 = oa::funcs::to_rank0(oa::ops::eval(N4));\n      ArrayPtr V5 = oa::funcs::to_rank0(oa::ops::eval(N5));\n      ArrayPtr V6 = oa::funcs::to_rank0(oa::ops::eval(N6));\n      ArrayPtr V7 = oa::funcs::to_rank0(oa::ops::eval(N7));\n      ArrayPtr V8 = oa::funcs::to_rank0(oa::ops::eval(N8));\n      \n      // NodePtr NSA = oa::ops::new_node(TYPE_MIN, NA);\n\n      //A->display(\"A\");\n      \n      ArrayPtr A1 = oa::funcs::to_rank0(A);\n      Shape s = A1->buffer_shape();\n      arma::Cube<${t}$> C = oa::utils::make_cube<${t}$>(\n          s, A1->get_buffer())(\n              arma::span(sw, s[0] - sw - 1),\n              arma::span(sw, s[1] - sw - 1),\n              arma::span(sw, s[2] - sw - 1));\n      \n\n      // ArrayPtr V2 = oa::ops::eval(NSA);\n      \n      if(rank == 0){\n\n        EXPECT_TRUE(oa::funcs::is_equal(V1, C.max()));\n        EXPECT_TRUE(oa::funcs::is_equal(V2, C.min()));\n        EXPECT_TRUE(oa::funcs::is_equal(V3, arma::abs(C).max()));\n        EXPECT_TRUE(oa::funcs::is_equal(V4, arma::abs(C).min()));\n\n        \n        // V1->display(\"V1\");\n        // std::cout<<\"C.max():\"<<C.max()<<std::endl;\n        // V2->display(\"V2\");\n        // std::cout<<\"C.min():\"<<C.min()<<std::endl;\n        // V1->display(\"V3\");\n        // std::cout<<\"abs(C).max():\"<<arma::abs(C).max()<<std::endl;\n        // V2->display(\"V4\");\n        // std::cout<<\"abs(C).min():\"<<arma::abs(C).min()<<std::endl;\n\n        arma::uvec VI;\n        VI = ind2sub(arma::size(C), C.index_max());\n\n        EXPECT_TRUE(oa::funcs::is_equal(V5, VI.memptr()));\n\n        VI = ind2sub(arma::size(C), C.index_min());\n        \n        // V6->display(\"V6\");\n        // std::cout<<VI<<std::endl;\n\n        EXPECT_TRUE(oa::funcs::is_equal(V6, VI.memptr()));\n\n        VI = ind2sub(arma::size(C), abs(C).index_max());\n        EXPECT_TRUE(oa::funcs::is_equal(V7, VI.memptr()));\n\n        VI = ind2sub(arma::size(C), abs(C).index_min());\n        EXPECT_TRUE(oa::funcs::is_equal(V8, VI.memptr()));\n        \n        // V2->display(\"V2\");\n        //EXPECT_TRUE(V1->is_seqs());\n        //EXPECT_TRUE(V1->shape() == SCALAR_SHAPE);\n      }\n    }\n    ///:endfor\n  }\n\n  TEST_P(MPITest, SUM_scalar_CSUM_scalar){\n\n    ///:for t in dtypes\n    {\n      int sw = NO_STENCIL;\n      DataType dt = oa::utils::dtype<${t}$>::type;\n\n      double x = 0;\n      ArrayPtr A = oa::funcs::seqs(comm, {m,n,p}, sw, dt);\n      NodePtr NA = oa::ops::new_node(A);\n\n      NodePtr type0 = oa::ops::new_seqs_scalar_node(MPI_COMM_SELF, 0);//c=0 scalar, c=1 sum to x, c=2 sum to y, c=3 sum to z\n      NodePtr N0 = oa::ops::new_node(TYPE_CSUM, NA, type0);\n      ArrayPtr RA0 = oa::ops::eval(N0);\n      ${t}$* res = (${t}$*) RA0->get_buffer();\n\n      NodePtr N1 = oa::ops::new_node(TYPE_SUM, NA, type0);\n      ArrayPtr RA1 = oa::ops::eval(N1);\n      ${t}$* res1 = (${t}$*) RA1->get_buffer();\n\n\n\n      ArrayPtr rank0A = oa::funcs::to_rank0(A);\n      if(rank == 0){\n        arma::Cube<${t}$> C = oa::utils::make_cube<${t}$>(rank0A->buffer_shape(), rank0A->get_buffer());\n        x = accu(C);\n        EXPECT_TRUE(res[0] == x);\n        EXPECT_TRUE(res1[0] == x);\n      }\n\n      MPI_Barrier(comm);\n    }\n    ///:endfor\n  }\n\n  TEST_P(MPITest, CSUM_x){\n    ///:for t in dtypes\n    {\n      int sw = NO_STENCIL;\n      DataType dt = oa::utils::dtype<${t}$>::type;\n\n      double x = 0;\n      ArrayPtr A = oa::funcs::seqs(comm, {m,n,p}, sw, dt);\n      NodePtr NA = oa::ops::new_node(A);\n\n      NodePtr type0 = oa::ops::new_seqs_scalar_node(MPI_COMM_SELF, 1);//c=0 scalar, c=1 sum to x, c=2 sum to y, c=3 sum to z\n      NodePtr N0 = oa::ops::new_node(TYPE_CSUM, NA, type0);\n      ArrayPtr RA0 = oa::ops::eval(N0);\n\n\n      ArrayPtr rank0A = oa::funcs::to_rank0(A);\n      ArrayPtr result = oa::funcs::to_rank0(RA0);\n      if(rank == 0){\n        arma::Cube<${t}$> C = oa::utils::make_cube<${t}$>(rank0A->buffer_shape(), rank0A->get_buffer());\n        for(int i = 0; i <= m; i++){\n          if(i-1 >= 0 && i <= m-1){\n            C.subcube( i, 0, 0, i, n-1, p-1 ) += C.subcube( i-1, 0, 0, i-1, n-1, p-1 );\n          }\n        }\n        EXPECT_TRUE(oa::funcs::is_equal(result, C));\n      }\n\n      MPI_Barrier(comm);\n    }\n    ///:endfor\n  }\n\n  TEST_P(MPITest, CSUM_y){\n    ///:for t in dtypes\n    {\n      int sw = NO_STENCIL;\n      DataType dt = oa::utils::dtype<${t}$>::type;\n\n      double x = 0;\n      ArrayPtr A = oa::funcs::seqs(comm, {m,n,p}, sw, dt);\n      NodePtr NA = oa::ops::new_node(A);\n\n      NodePtr type0 = oa::ops::new_seqs_scalar_node(MPI_COMM_SELF, 2);//c=0 scalar, c=1 sum to x, c=2 sum to y, c=3 sum to z\n      NodePtr N0 = oa::ops::new_node(TYPE_CSUM, NA, type0);\n      ArrayPtr RA0 = oa::ops::eval(N0);\n\n\n      ArrayPtr rank0A = oa::funcs::to_rank0(A);\n      ArrayPtr result = oa::funcs::to_rank0(RA0);\n      if(rank == 0){\n        arma::Cube<${t}$> C = oa::utils::make_cube<${t}$>(rank0A->buffer_shape(), rank0A->get_buffer());\n        for(int i = 0; i <= n ; i++){\n          if(i-1 >= 0 && i <= n-1){\n            C.subcube( 0, i, 0, m-1, i, p-1 ) += C.subcube( 0, i-1, 0, m-1, i-1, p-1 );\n          }\n        }\n        EXPECT_TRUE(oa::funcs::is_equal(result, C));\n      }\n\n      MPI_Barrier(comm);\n    }\n    ///:endfor\n  }\n\n  TEST_P(MPITest, CSUM_z){\n    ///:for t in dtypes\n    {\n      int sw = NO_STENCIL;\n      DataType dt = oa::utils::dtype<${t}$>::type;\n\n      double x = 0;\n      ArrayPtr A = oa::funcs::seqs(comm, {m,n,p}, sw, dt);\n      NodePtr NA = oa::ops::new_node(A);\n\n      NodePtr type0 = oa::ops::new_seqs_scalar_node(MPI_COMM_SELF, 3);//c=0 scalar, c=1 sum to x, c=2 sum to y, c=3 sum to z\n      NodePtr N0 = oa::ops::new_node(TYPE_CSUM, NA, type0);\n      ArrayPtr RA0 = oa::ops::eval(N0);\n\n\n      ArrayPtr rank0A = oa::funcs::to_rank0(A);\n      ArrayPtr result = oa::funcs::to_rank0(RA0);\n      if(rank == 0){\n        arma::Cube<${t}$> C = oa::utils::make_cube<${t}$>(rank0A->buffer_shape(), rank0A->get_buffer());\n        for(int i = 0; i <=p; i++){\n          if(i-1 >= 0 && i <= p-1){\n            C.subcube( 0, 0, i, m-1, n-1, i ) += C.subcube( 0, 0, i-1, m-1, n-1, i-1 );\n          }\n        }\n        EXPECT_TRUE(oa::funcs::is_equal(result, C));\n      }\n\n      MPI_Barrier(comm);\n    }\n    ///:endfor\n  }\n\n  TEST_P(MPITest, SUM_x){\n    ///:for t in dtypes\n    {\n      int sw = NO_STENCIL;\n      DataType dt = oa::utils::dtype<${t}$>::type;\n\n      double x = 0;\n      ArrayPtr A = oa::funcs::seqs(comm, {m,n,p}, sw, dt);\n      NodePtr NA = oa::ops::new_node(A);\n\n      NodePtr type0 = oa::ops::new_seqs_scalar_node(MPI_COMM_SELF, 1);//c=0 scalar, c=1 sum to x, c=2 sum to y, c=3 sum to z\n      NodePtr N0 = oa::ops::new_node(TYPE_SUM, NA, type0);\n      ArrayPtr RA0 = oa::ops::eval(N0);\n\n\n      ArrayPtr rank0A = oa::funcs::to_rank0(A);\n      ArrayPtr result = oa::funcs::to_rank0(RA0);\n      if(rank == 0){\n        arma::Cube<${t}$> C = oa::utils::make_cube<${t}$>(rank0A->buffer_shape(), rank0A->get_buffer());\n        for(int i = m; i >= 0; i--){\n          if(i-1 >= 0 && i <= m-1){\n            C.subcube( 0, 0, 0, 0, n-1, p-1 ) += C.subcube( i, 0, 0, i, n-1, p-1 );\n          }\n        }\n        arma::Cube<${t}$> Cr = C.subcube( 0, 0, 0, 0, n-1, p-1 );\n        EXPECT_TRUE(oa::funcs::is_equal(result, Cr));\n      }\n\n      MPI_Barrier(comm);\n    }\n    ///:endfor\n  }\n\n  TEST_P(MPITest, SUM_y){\n    ///:for t in dtypes\n    {\n      int sw = NO_STENCIL;\n      DataType dt = oa::utils::dtype<${t}$>::type;\n\n      double x = 0;\n      ArrayPtr A = oa::funcs::seqs(comm, {m,n,p}, sw, dt);\n      NodePtr NA = oa::ops::new_node(A);\n\n      NodePtr type0 = oa::ops::new_seqs_scalar_node(MPI_COMM_SELF, 2);//c=0 scalar, c=1 sum to x, c=2 sum to y, c=3 sum to z\n      NodePtr N0 = oa::ops::new_node(TYPE_SUM, NA, type0);\n      ArrayPtr RA0 = oa::ops::eval(N0);\n\n\n      ArrayPtr rank0A = oa::funcs::to_rank0(A);\n      ArrayPtr result = oa::funcs::to_rank0(RA0);\n      if(rank == 0){\n        arma::Cube<${t}$> C = oa::utils::make_cube<${t}$>(rank0A->buffer_shape(), rank0A->get_buffer());\n        for(int i = n; i >= 0; i--){\n          if(i-1 >= 0 && i <= n-1){\n            C.subcube( 0, 0, 0, m-1, 0, p-1 ) += C.subcube( 0, i, 0, m-1, i, p-1 );\n          }\n        }\n        arma::Cube<${t}$> Cr = C.subcube( 0, 0, 0, m-1, 0, p-1 );\n        EXPECT_TRUE(oa::funcs::is_equal(result, Cr));\n      }\n\n      MPI_Barrier(comm);\n    }\n    ///:endfor\n  }\n\n  TEST_P(MPITest, SUM_z){\n    ///:for t in dtypes\n    {\n      int sw = NO_STENCIL;\n      DataType dt = oa::utils::dtype<${t}$>::type;\n\n      double x = 0;\n      ArrayPtr A = oa::funcs::seqs(comm, {m,n,p}, sw, dt);\n      NodePtr NA = oa::ops::new_node(A);\n\n      NodePtr type0 = oa::ops::new_seqs_scalar_node(MPI_COMM_SELF, 3);//c=0 scalar, c=1 sum to x, c=2 sum to y, c=3 sum to z\n      NodePtr N0 = oa::ops::new_node(TYPE_SUM, NA, type0);\n      ArrayPtr RA0 = oa::ops::eval(N0);\n\n\n      ArrayPtr rank0A = oa::funcs::to_rank0(A);\n      ArrayPtr result = oa::funcs::to_rank0(RA0);\n      if(rank == 0){\n        arma::Cube<${t}$> C = oa::utils::make_cube<${t}$>(rank0A->buffer_shape(), rank0A->get_buffer());\n        for(int i = p; i >= 0; i--){\n          if(i-1 >= 0 && i <= p-1){\n            C.subcube( 0, 0, 0, m-1, n-1, 0 ) += C.subcube( 0, 0, i, m-1, n-1, i );\n          }\n        }\n        arma::Cube<${t}$> Cr = C.subcube( 0, 0, 0, m-1, n-1, 0 );\n        EXPECT_TRUE(oa::funcs::is_equal(result, Cr));\n      }\n\n      MPI_Barrier(comm);\n    }\n    ///:endfor\n  }\n\n  TEST_P(MPITest, REP){\n    ///:for t in dtypes\n    {\n      int sw = NO_STENCIL;\n      DataType dt = oa::utils::dtype<${t}$>::type;\n\n      int x = 2;\n      int y = 2;\n      int z = 2;\n\n      ArrayPtr A = oa::funcs::seqs(comm, {m,n,p}, sw, dt);\n      NodePtr NN = oa::ops::new_node(A);\n      ArrayPtr lap = oa::funcs::consts(MPI_COMM_SELF, {3, 1, 1}, 2, 0);\n      NodePtr NN2 = oa::ops::new_node(lap);\n\n\n      NodePtr NP = oa::ops::new_node(TYPE_REP, NN, NN2);\n      ArrayPtr repA = oa::ops::eval(NP);\n\n      ArrayPtr rank0A = oa::funcs::to_rank0(A);\n      ArrayPtr result = oa::funcs::to_rank0(repA);\n      //if(rank == 0)result->display(\"result\");\n      if(rank == 0){\n        arma::Cube<${t}$> C0 = oa::utils::make_cube<${t}$>(rank0A->buffer_shape(), rank0A->get_buffer());\n        arma::Cube<${t}$> Cr(m*x, n*y, p*z); \n        Cr.zeros();\n        int ii,jj,kk;\n        //result->display(\"result\");\n        //Cr.print(\"Cr\");\n        ii = 0;\n        for(int i = 0; i < x; i++){\n          jj = 0;\n          for(int j = 0; j < y; j++){\n            kk = 0;\n            for(int k = 0; k < z; k++){\n              //cout<<ii<<\",\"<<jj<<\",\"<<kk<<endl;\n              Cr.subcube(0+ii,0+jj,0+kk,m-1+ii,n-1+jj,p-1+kk) = C0;\n              kk += p;\n            }\n            jj += n;\n          }\n          ii += m;\n        }\n        //Cr.print(\"Cr\");\n        //result->display(\"result\");\n        //        EXPECT_TRUE(oa::funcs::is_equal(rank0A, C));\n        EXPECT_TRUE(oa::funcs::is_equal(result, Cr));\n\n      }\n\n\n      MPI_Barrier(comm);\n    }\n    ///:endfor\n  }\n\n  TEST_P(MPITest, RAND){\n    ///:for t in dtypes\n    {\n      int sw = NO_STENCIL;\n      DataType dt = oa::utils::dtype<${t}$>::type;\n\n      int x = 2;\n      int y = 3;\n      int z = 4;\n\n      ArrayPtr A = oa::funcs::rands(comm, {m,n,p}, sw, dt);\n\n      ArrayPtr rank0A = oa::funcs::to_rank0(A);\n      //if(rank == 0)result->display(\"result\");\n      if(rank == 0){\n        //rank0A->display(\"rand\");\n        ;\n      }\n\n      MPI_Barrier(comm);\n    }\n    ///:endfor\n  }\n\n\n  INSTANTIATE_TEST_CASE_P(OpenArray, MPITest,\n          gt::Combine(gt::Values(MPI_COMM_WORLD),\n                  MRange, NRange, PRange));\n\n}\n", "meta": {"hexsha": "9a995198c01585307b5dd66e628bd32da898ef99", "size": 19682, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittest/test_array.cpp", "max_stars_repo_name": "hxmhuang/OpenArray_Dev", "max_stars_repo_head_hexsha": "863866a6b7accf21fa253567b0e66143c7506cdf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-09-08T05:01:56.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-23T13:11:25.000Z", "max_issues_repo_path": "unittest/test_array.cpp", "max_issues_repo_name": "hxmhuang/OpenArray_Dev", "max_issues_repo_head_hexsha": "863866a6b7accf21fa253567b0e66143c7506cdf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unittest/test_array.cpp", "max_forks_repo_name": "hxmhuang/OpenArray_Dev", "max_forks_repo_head_hexsha": "863866a6b7accf21fa253567b0e66143c7506cdf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-08-16T08:32:30.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T08:44:04.000Z", "avg_line_length": 29.0723781388, "max_line_length": 124, "alphanum_fraction": 0.5077227924, "num_tokens": 6681, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.46931599352487147}}
{"text": "/**\n * Copyright (c) 2020, Rom\u00e1n C\u00e1rdenas Rodr\u00edguez\n * ARSLab - Carleton University\n * GreenLSI - Polytechnic University of Madrid\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * 1. Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n#define BOOST_TEST_DYN_LINK\n\n#include <boost/test/unit_test.hpp>\n#include <cadmium/celldevs/utils/grid_utils.hpp>\n\nusing namespace cadmium::celldevs;\n\n\nint moore_cells(int dimension, int range) {\n    return std::pow(2 * range + 1, dimension);\n}\n\nBOOST_AUTO_TEST_CASE(moore) {\n    for (unsigned int D = 1; D < 5; D++) {\n        for (unsigned int r = 0; r < 4; r++) {\n            cell_position shape = cell_position();\n            cell_position middle = cell_position();\n            for (int d = 0; d < D; d++) {\n                shape.push_back(2 * r + 1);\n                middle.push_back(r);\n            }\n            std::vector<cell_position> neighbors = grid_scenario<int, int>::biassed_moore_neighborhood(D, r);\n            BOOST_CHECK_EQUAL(neighbors.size(), moore_cells(D, r));\n            for (auto const &cell: neighbors) {\n                int a = grid_scenario<int, int>::chebyshev_distance(middle, cell, shape, false);\n                BOOST_CHECK_LE( a, r);\n            }\n        }\n    }\n}\n\nBOOST_AUTO_TEST_CASE(von_neumann) {\n    for (unsigned int D = 1; D < 5; D++) {\n        for (unsigned int r = 0; r < 4; r++) {\n            cell_position shape = cell_position();\n            cell_position middle = cell_position();\n            for (int d = 0; d < D; d++) {\n                shape.push_back(2 * r + 1);\n                middle.push_back(r);\n            }\n            std::vector<cell_position> neighbors = grid_scenario<int, int>::biassed_von_neumann_neighborhood(D, r);\n            for (auto const &cell: neighbors) {\n                int a = grid_scenario<int, int>::manhattan_distance(middle, cell, shape, false);\n                BOOST_CHECK_LE(a, r);\n            }\n        }\n    }\n}\n", "meta": {"hexsha": "a0e2a4cdfb18d599e097cb0cb5b7ace4c24c8373", "size": 3150, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/celldevs_grid_utils_test.cpp", "max_stars_repo_name": "romancardenas/cadmium", "max_stars_repo_head_hexsha": "a1c7d0d75569731496852cb3e2bdd37c07c3ddf0", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2016-09-16T21:49:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-24T17:30:35.000Z", "max_issues_repo_path": "test/celldevs_grid_utils_test.cpp", "max_issues_repo_name": "romancardenas/cadmium", "max_issues_repo_head_hexsha": "a1c7d0d75569731496852cb3e2bdd37c07c3ddf0", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 31.0, "max_issues_repo_issues_event_min_datetime": "2016-10-06T01:59:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-27T16:15:34.000Z", "max_forks_repo_path": "test/celldevs_grid_utils_test.cpp", "max_forks_repo_name": "romancardenas/cadmium", "max_forks_repo_head_hexsha": "a1c7d0d75569731496852cb3e2bdd37c07c3ddf0", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2016-09-17T16:19:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-16T14:50:35.000Z", "avg_line_length": 42.0, "max_line_length": 115, "alphanum_fraction": 0.6555555556, "num_tokens": 727, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850933, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.46931598879628617}}
{"text": "#include <geometry.h>\n#include <tiny.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n\n\n#include <vector>\n\ntypedef tiny::MathTypes<float> MT;\ntypedef MT::vector3_type       V;\ntypedef MT::quaternion_type    Q;\ntypedef MT::real_type          T;\ntypedef MT::value_traits       VT;\n\nclass ContactInfo\n{\npublic:\n\n  V m_point;\n  V m_normal;\n  T m_distance;\n\n};\n\n\nclass MyCallback\n  : public geometry::ContactsCallback<V>\n{\npublic:\n\n  std::vector<ContactInfo> m_contacts;\n\npublic:\n\n  void operator()(\n                  V const & point\n                  , V const & normal\n                  , typename V::real_type const & distance\n                  )\n  {\n    ContactInfo info;\n\n    info.m_point = point;\n    info.m_normal = normal;\n    info.m_distance = distance;\n\n    m_contacts.push_back(info);\n  }\n\n};\n\n\n\nBOOST_AUTO_TEST_SUITE(geometry);\n\nBOOST_AUTO_TEST_CASE(contacts_obb_obb_test)\n{\n  // touching bottom-top faces\n  {\n    V const centerA   = V::make(0.0, 0.0, 0.0);\n    V const half_extA = V::make(1.0, 1.0, 1.0);\n    Q const qA        = Q::identity();\n\n    geometry::OBB<MT> obbA = geometry::make_obb<MT>(centerA, qA, half_extA);\n\n    V const centerB   = V::make(0.0, -2.0, 0.0);\n    V const half_extB = V::make(1.0, 1.0, 1.0);\n    Q const qB        = Q::Ry(VT::pi_quarter());\n\n    geometry::OBB<MT> obbB = geometry::make_obb<MT>(centerB, qB, half_extB);\n\n    MyCallback callback1;\n    MyCallback callback2;\n\n    bool const test1 = geometry::contacts_obb_obb(obbA,obbB, 0.0, callback1);\n    bool const test2 = geometry::contacts_obb_obb(obbB,obbA, 0.0, callback2);\n\n    BOOST_CHECK(test1);\n    BOOST_CHECK(test2);\n\n    BOOST_CHECK_EQUAL(callback1.m_contacts.size(), 8u);\n    BOOST_CHECK_EQUAL(callback2.m_contacts.size(), 8u);\n\n    for(unsigned int k = 0u;k <8u;++k)\n    {\n      BOOST_CHECK( fabs(       callback1.m_contacts[k].m_normal(2)) < 0.00001 );\n      BOOST_CHECK( fabs(       callback1.m_contacts[k].m_normal(0)) < 0.00001 );\n      BOOST_CHECK( 1.0  - fabs(callback1.m_contacts[k].m_normal(1)) < 0.00001 );\n      BOOST_CHECK(       fabs( callback1.m_contacts[k].m_distance)  < 0.00001 );\n    }\n\n\n  }\n  // touching left-right faces\n  {\n    V const centerA   = V::make(0.0, 0.0, 0.0);\n    V const half_extA = V::make(1.0, 1.0, 1.0);\n    Q const qA        = Q::identity();\n\n    geometry::OBB<MT> obbA = geometry::make_obb<MT>(centerA, qA, half_extA);\n\n    V const centerB   = V::make(2.0, 0.0, 0.0);\n    V const half_extB = V::make(1.0, 1.0, 1.0);\n    Q const qB        = Q::Rx(VT::pi_quarter());\n\n    geometry::OBB<MT> obbB = geometry::make_obb<MT>(centerB, qB, half_extB);\n\n    MyCallback callback1;\n    MyCallback callback2;\n\n    bool const test1 = geometry::contacts_obb_obb(obbA,obbB, 0.0, callback1);\n    bool const test2 = geometry::contacts_obb_obb(obbB,obbA, 0.0, callback2);\n\n    BOOST_CHECK(test1);\n    BOOST_CHECK(test2);\n\n    BOOST_CHECK_EQUAL(callback1.m_contacts.size(), 8u);\n    BOOST_CHECK_EQUAL(callback2.m_contacts.size(), 8u);\n\n    for(unsigned int k = 0u;k <8u;++k)\n    {\n      BOOST_CHECK( fabs(       callback1.m_contacts[k].m_normal(2)) < 0.00001 );\n      BOOST_CHECK( fabs(       callback1.m_contacts[k].m_normal(1)) < 0.00001 );\n      BOOST_CHECK( 1.0  - fabs(callback1.m_contacts[k].m_normal(0)) < 0.00001 );\n      BOOST_CHECK(       fabs( callback1.m_contacts[k].m_distance)  < 0.00001 );\n    }\n\n\n  }\n  // touching front-back faces\n  {\n    V const centerA   = V::make(0.0, 0.0, 0.0);\n    V const half_extA = V::make(1.0, 1.0, 1.0);\n    Q const qA        = Q::identity();\n\n    geometry::OBB<MT> obbA = geometry::make_obb<MT>(centerA, qA, half_extA);\n\n    V const centerB   = V::make(0.0, 0.0, 2.0);\n    V const half_extB = V::make(1.0, 1.0, 1.0);\n    Q const qB        = Q::Rz(VT::pi_quarter());\n\n    geometry::OBB<MT> obbB = geometry::make_obb<MT>(centerB, qB, half_extB);\n\n    MyCallback callback1;\n    MyCallback callback2;\n\n    bool const test1 = geometry::contacts_obb_obb(obbA,obbB, 0.0, callback1);\n    bool const test2 = geometry::contacts_obb_obb(obbB,obbA, 0.0, callback2);\n\n    BOOST_CHECK(test1);\n    BOOST_CHECK(test2);\n\n    BOOST_CHECK_EQUAL(callback1.m_contacts.size(), 8u);\n    BOOST_CHECK_EQUAL(callback2.m_contacts.size(), 8u);\n\n    for(unsigned int k = 0u;k <8u;++k)\n    {\n      BOOST_CHECK( fabs(       callback1.m_contacts[k].m_normal(0)) < 0.00001 );\n      BOOST_CHECK( fabs(       callback1.m_contacts[k].m_normal(1)) < 0.00001 );\n      BOOST_CHECK( 1.0  - fabs(callback1.m_contacts[k].m_normal(2)) < 0.00001 );\n      BOOST_CHECK(       fabs( callback1.m_contacts[k].m_distance)  < 0.00001 );\n    }\n\n\n  }\n  // separating bottom-top faces\n  {\n    V const centerA   = V::make(0.0, 0.0, 0.0);\n    V const half_extA = V::make(1.0, 1.0, 1.0);\n    Q const qA        = Q::identity();\n\n    geometry::OBB<MT> obbA = geometry::make_obb<MT>(centerA, qA, half_extA);\n\n    V const centerB   = V::make(0.0, -2.1, 0.0);\n    V const half_extB = V::make(1.0, 1.0, 1.0);\n    Q const qB        = Q::Ry(VT::pi_quarter());\n\n    geometry::OBB<MT> obbB = geometry::make_obb<MT>(centerB, qB, half_extB);\n\n    MyCallback callback1;\n    MyCallback callback2;\n\n    bool const test1 = geometry::contacts_obb_obb(obbA,obbB, 0.0, callback1);\n    bool const test2 = geometry::contacts_obb_obb(obbB,obbA, 0.0, callback2);\n\n    BOOST_CHECK(!test1);\n    BOOST_CHECK(!test2);\n\n    BOOST_CHECK_EQUAL(callback1.m_contacts.size(), 0u);\n    BOOST_CHECK_EQUAL(callback2.m_contacts.size(), 0u);\n\n  }\n  // separating left-right faces\n  {\n    V const centerA   = V::make(0.0, 0.0, 0.0);\n    V const half_extA = V::make(1.0, 1.0, 1.0);\n    Q const qA        = Q::identity();\n\n    geometry::OBB<MT> obbA = geometry::make_obb<MT>(centerA, qA, half_extA);\n\n    V const centerB   = V::make(2.1, 0.0, 0.0);\n    V const half_extB = V::make(1.0, 1.0, 1.0);\n    Q const qB        = Q::Rx(VT::pi_quarter());\n\n    geometry::OBB<MT> obbB = geometry::make_obb<MT>(centerB, qB, half_extB);\n\n    MyCallback callback1;\n    MyCallback callback2;\n\n    bool const test1 = geometry::contacts_obb_obb(obbA,obbB, 0.0, callback1);\n    bool const test2 = geometry::contacts_obb_obb(obbB,obbA, 0.0, callback2);\n\n    BOOST_CHECK(!test1);\n    BOOST_CHECK(!test2);\n\n    BOOST_CHECK_EQUAL(callback1.m_contacts.size(), 0u);\n    BOOST_CHECK_EQUAL(callback2.m_contacts.size(), 0u);\n\n  }\n  // separating front-back faces\n  {\n    V const centerA   = V::make(0.0, 0.0, 0.0);\n    V const half_extA = V::make(1.0, 1.0, 1.0);\n    Q const qA        = Q::identity();\n\n    geometry::OBB<MT> obbA = geometry::make_obb<MT>(centerA, qA, half_extA);\n\n    V const centerB   = V::make(0.0, 0.0, 2.1);\n    V const half_extB = V::make(1.0, 1.0, 1.0);\n    Q const qB        = Q::Rz(VT::pi_quarter());\n\n    geometry::OBB<MT> obbB = geometry::make_obb<MT>(centerB, qB, half_extB);\n\n    MyCallback callback1;\n    MyCallback callback2;\n\n    bool const test1 = geometry::contacts_obb_obb(obbA,obbB, 0.0, callback1);\n    bool const test2 = geometry::contacts_obb_obb(obbB,obbA, 0.0, callback2);\n\n    BOOST_CHECK(!test1);\n    BOOST_CHECK(!test2);\n\n    BOOST_CHECK_EQUAL(callback1.m_contacts.size(), 0u);\n    BOOST_CHECK_EQUAL(callback2.m_contacts.size(), 0u);\n\n  }\n  // A inside of B\n  {\n    V const centerA   = V::make(0.0,   0.5,  0.0 );\n    V const half_extA = V::make(0.5,   0.25, 0.5);\n    Q const qA        = Q::identity();\n\n    geometry::OBB<MT> obbA = geometry::make_obb<MT>(centerA, qA, half_extA);\n\n    V const centerB   = V::make(0.0, 0.0, 0.0);\n    V const half_extB = V::make(1.0, 1.0, 1.0);\n    Q const qB        = Q::identity();\n\n    geometry::OBB<MT> obbB = geometry::make_obb<MT>(centerB, qB, half_extB);\n\n    MyCallback callback1;\n    MyCallback callback2;\n\n    bool const test1 = geometry::contacts_obb_obb(obbA,obbB, 0.0, callback1);\n    bool const test2 = geometry::contacts_obb_obb(obbB,obbA, 0.0, callback2);\n\n    BOOST_CHECK(test1);\n    BOOST_CHECK(test2);\n\n    BOOST_CHECK_EQUAL(callback1.m_contacts.size(), 4u);\n    BOOST_CHECK_EQUAL(callback2.m_contacts.size(), 4u);\n\n    for(unsigned int k = 0u;k <4u;++k)\n    {\n      BOOST_CHECK( 0.5 - fabs(callback1.m_contacts[k].m_point(0))   < 0.00001 );\n      BOOST_CHECK( 0.5 - fabs(callback1.m_contacts[k].m_point(1))   < 0.00001 );\n      BOOST_CHECK( 0.5 - fabs(callback1.m_contacts[k].m_point(2))   < 0.00001 );\n      BOOST_CHECK( fabs(       callback1.m_contacts[k].m_normal(0)) < 0.00001 );\n      BOOST_CHECK( 1.0  - fabs(callback1.m_contacts[k].m_normal(1)) < 0.00001 );\n      BOOST_CHECK( fabs(       callback1.m_contacts[k].m_normal(2)) < 0.00001 );\n      BOOST_CHECK( 0.5 - fabs( callback1.m_contacts[k].m_distance)  < 0.00001 ); // depth is off due to technicality in method, should have been 0.75\n    }\n\n  }\n  // separating edge-edge-case\n  {\n    V const centerA   = V::make(0.0, 0.0, 0.0);\n    V const half_extA = V::make(1.0, 1.0, 1.0);\n    Q const qA        = Q::identity();\n\n    geometry::OBB<MT> obbA = geometry::make_obb<MT>(centerA, qA, half_extA);\n\n    V const centerB   = V::make(2.01, 2.01, 0.0);\n    V const half_extB = V::make(1.0, 1.0, 1.0);\n    Q const qB        = Q::Ru(VT::pi_half(), centerB );\n\n    geometry::OBB<MT> obbB = geometry::make_obb<MT>(centerB, qB, half_extB);\n\n    MyCallback callback1;\n    MyCallback callback2;\n\n    bool const test1 = geometry::contacts_obb_obb(obbA,obbB, 0.0, callback1);\n    bool const test2 = geometry::contacts_obb_obb(obbB,obbA, 0.0, callback2);\n\n    BOOST_CHECK(!test1);\n    BOOST_CHECK(!test2);\n\n    BOOST_CHECK_EQUAL(callback1.m_contacts.size(), 0u);\n    BOOST_CHECK_EQUAL(callback2.m_contacts.size(), 0u);\n  }\n  // touching edge-edge-case\n  {\n    V const centerA   = V::make(0.0, 0.0, 0.0);\n    V const half_extA = V::make(1.0, 1.0, 1.0);\n    Q const qA        = Q::identity();\n\n    geometry::OBB<MT> obbA = geometry::make_obb<MT>(centerA, qA, half_extA);\n\n\n    V const centerB   = V::make(1.999999, 1.999999, 0.0);\n    V const half_extB = V::make(1.0, 1.0, 1.0);\n    Q const qB        = Q::Ru(VT::pi_half(), centerB );\n\n    geometry::OBB<MT> obbB = geometry::make_obb<MT>(centerB, qB, half_extB);\n\n    MyCallback callback1;\n    MyCallback callback2;\n\n    bool const test1 = geometry::contacts_obb_obb(obbA,obbB, 0.0, callback1);\n    bool const test2 = geometry::contacts_obb_obb(obbB,obbA, 0.0, callback2);\n\n    BOOST_CHECK(test1);\n    BOOST_CHECK(test2);\n\n    BOOST_CHECK_EQUAL(callback1.m_contacts.size(), 4u);\n    BOOST_CHECK_EQUAL(callback2.m_contacts.size(), 4u);\n\n\n    BOOST_CHECK( fabs(1.0 - callback1.m_contacts[0].m_point(0)) < 0.00001);\n    BOOST_CHECK( fabs(1.0 - callback1.m_contacts[0].m_point(1)) < 0.00001);\n    BOOST_CHECK( fabs(      callback1.m_contacts[0].m_point(2)) < 0.00001);\n    BOOST_CHECK( fabs(sqrt(0.5) - callback1.m_contacts[0].m_normal(0)) < 0.00001);\n    BOOST_CHECK( fabs(sqrt(0.5) - callback1.m_contacts[0].m_normal(1)) < 0.00001);\n    BOOST_CHECK( fabs(            callback1.m_contacts[0].m_normal(2)) < 0.00001);\n    BOOST_CHECK( fabs( callback1.m_contacts[0].m_distance) < 0.00001);\n\n\n    BOOST_CHECK( fabs(1.0 - callback1.m_contacts[1].m_point(0)) < 0.00001);\n    BOOST_CHECK( fabs(1.0 - callback1.m_contacts[1].m_point(1)) < 0.00001);\n    BOOST_CHECK( fabs(      callback1.m_contacts[1].m_point(2)) < 0.00001);\n    BOOST_CHECK( fabs(sqrt(0.5) - callback1.m_contacts[1].m_normal(0)) < 0.00001);\n    BOOST_CHECK( fabs(sqrt(0.5) - callback1.m_contacts[1].m_normal(1)) < 0.00001);\n    BOOST_CHECK( fabs(            callback1.m_contacts[1].m_normal(2)) < 0.00001);\n    BOOST_CHECK( fabs( callback1.m_contacts[1].m_distance) < 0.00001);\n\n    BOOST_CHECK( fabs(1.0 - callback1.m_contacts[2].m_point(0)) < 0.00001);\n    BOOST_CHECK( fabs(1.0 - callback1.m_contacts[2].m_point(1)) < 0.00001);\n    BOOST_CHECK( fabs(      callback1.m_contacts[2].m_point(2)) < 0.00001);\n    BOOST_CHECK( fabs(sqrt(0.5) - callback1.m_contacts[2].m_normal(0)) < 0.00001);\n    BOOST_CHECK( fabs(sqrt(0.5) - callback1.m_contacts[2].m_normal(1)) < 0.00001);\n    BOOST_CHECK( fabs(            callback1.m_contacts[2].m_normal(2)) < 0.00001);\n    BOOST_CHECK( fabs( callback1.m_contacts[2].m_distance) < 0.00001);\n\n    BOOST_CHECK( fabs(1.0 - callback1.m_contacts[3].m_point(0)) < 0.00001);\n    BOOST_CHECK( fabs(1.0 - callback1.m_contacts[3].m_point(1)) < 0.00001);\n    BOOST_CHECK( fabs(      callback1.m_contacts[3].m_point(2)) < 0.00001);\n    BOOST_CHECK( fabs(sqrt(0.5) - callback1.m_contacts[3].m_normal(0)) < 0.00001);\n    BOOST_CHECK( fabs(sqrt(0.5) - callback1.m_contacts[3].m_normal(1)) < 0.00001);\n    BOOST_CHECK( fabs(            callback1.m_contacts[3].m_normal(2)) < 0.00001);\n    BOOST_CHECK( fabs( callback1.m_contacts[3].m_distance) < 0.00001);\n\n  }\n\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "1f3ad78ffb7d466b66849cf0ee0a6c4ff8df54af", "size": 12754, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/FOUNDATION/GEOMETRY/unit_tests/geometry_contacts_obb_obb/geometry_contacts_obb_obb.cpp", "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/FOUNDATION/GEOMETRY/unit_tests/geometry_contacts_obb_obb/geometry_contacts_obb_obb.cpp", "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/FOUNDATION/GEOMETRY/unit_tests/geometry_contacts_obb_obb/geometry_contacts_obb_obb.cpp", "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": 33.4750656168, "max_line_length": 149, "alphanum_fraction": 0.6355653128, "num_tokens": 4405, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191214879991, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.4693159806565581}}
{"text": "/* ---------------------------------------------------------------------\n *\n * Copyright (C) 2000 - 2018 by the deal.II authors\n *\n * This file is modification of the version in 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, 2000\n */\n#include <deal.II/base/function.h>\n#include <deal.II/base/logstream.h>\n#include <deal.II/base/multithread_info.h>\n#include <deal.II/base/quadrature_lib.h>\n#include <deal.II/base/tensor_function.h>\n#include <deal.II/base/work_stream.h>\n#include <deal.II/dofs/dof_accessor.h>\n#include <deal.II/dofs/dof_handler.h>\n#include <deal.II/dofs/dof_tools.h>\n#include <deal.II/fe/fe_q.h>\n#include <deal.II/fe/fe_values.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.h>\n#include <deal.II/grid/tria_accessor.h>\n#include <deal.II/grid/tria_iterator.h>\n#include <deal.II/lac/affine_constraints.h>\n#include <deal.II/lac/dynamic_sparsity_pattern.h>\n#include <deal.II/lac/full_matrix.h>\n#include <deal.II/lac/precondition.h>\n#include <deal.II/lac/solver_gmres.h>\n#include <deal.II/lac/sparse_matrix.h>\n#include <deal.II/lac/vector.h>\n#include <deal.II/numerics/data_out.h>\n#include <deal.II/numerics/error_estimator.h>\n#include <deal.II/numerics/matrix_tools.h>\n#include <deal.II/numerics/vector_tools.h>\n#include <fstream>\n#include <iostream>\n\n\n#include <bench_base.hpp>\n\n\nDEFINE_uint32(\n    num_refine_cycles, 1,\n    \"Number of refinement cycles for the adaptive refinement within deal.ii\");\nDEFINE_uint32(init_refine_level, 4,\n              \"Initial level for the refinement of the mesh.\");\nDEFINE_bool(dealii_orig, false, \"Solve with dealii iterative GMRES\");\nDEFINE_bool(vis_sol, false, \"Print the solution for visualization\");\n\n#define CHECK_HERE std::cout << \"Here \" << __LINE__ << std::endl;\n\nusing namespace dealii;\n\n\ntemplate <int dim>\nclass AdvectionField : public TensorFunction<1, dim> {\npublic:\n    virtual Tensor<1, dim> value(const Point<dim> &p) const override;\n    DeclException2(ExcDimensionMismatch, unsigned int, unsigned int,\n                   << \"The vector has size \" << arg1 << \" but should have \"\n                   << arg2 << \" elements.\");\n};\n\n\ntemplate <int dim>\nTensor<1, dim> 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    return value;\n}\n\n\ntemplate <int dim>\nclass RightHandSide : public Function<dim> {\npublic:\n    virtual double value(const Point<dim> &p,\n                         const unsigned int component = 0) const override;\n\nprivate:\n    static const Point<dim> center_point;\n};\n\n\ntemplate <>\nconst Point<1> RightHandSide<1>::center_point = Point<1>(-0.75);\ntemplate <>\nconst Point<2> RightHandSide<2>::center_point = Point<2>(-0.75, -0.75);\ntemplate <>\nconst Point<3> RightHandSide<3>::center_point = Point<3>(-0.75, -0.75, -0.75);\n\n\ntemplate <int dim>\ndouble RightHandSide<dim>::value(const Point<dim> &p,\n                                 const unsigned int component) const\n{\n    (void)component;\n    Assert(component == 0, ExcIndexRange(component, 0, 1));\n    const double diameter = 0.1;\n    return ((p - center_point).norm_square() < diameter * diameter\n                ? 0.1 / std::pow(diameter, dim)\n                : 0.1);\n}\n\n\ntemplate <int dim>\nclass BoundaryValues : public Function<dim> {\npublic:\n    virtual double value(const Point<dim> &p,\n                         const unsigned int component = 0) const override;\n};\n\n\ntemplate <int dim>\ndouble BoundaryValues<dim>::value(const Point<dim> &p,\n                                  const unsigned int component) const\n{\n    (void)component;\n    Assert(component == 0, ExcIndexRange(component, 0, 1));\n    const double sine_term = std::sin(16. * numbers::PI * p.norm_square());\n    const double weight = std::exp(5. * (1. - p.norm_square()));\n    return weight * sine_term;\n}\n\n\ntemplate <int dim>\nclass AdvectionProblem : public BenchBase<double, int> {\npublic:\n    AdvectionProblem();\n    void run();\n    void run(MPI_Comm mpi_communicator);\n\nprivate:\n    void setup_system();\n    struct AssemblyScratchData {\n        AssemblyScratchData(const FiniteElement<dim> &fe);\n        AssemblyScratchData(const AssemblyScratchData &scratch_data);\n        FEValues<dim> fe_values;\n        FEFaceValues<dim> fe_face_values;\n        std::vector<double> rhs_values;\n        std::vector<Tensor<1, dim>> advection_directions;\n        std::vector<double> face_boundary_values;\n        std::vector<Tensor<1, dim>> face_advection_directions;\n        AdvectionField<dim> advection_field;\n        RightHandSide<dim> right_hand_side;\n        BoundaryValues<dim> boundary_values;\n    };\n    struct AssemblyCopyData {\n        FullMatrix<double> cell_matrix;\n        Vector<double> cell_rhs;\n        std::vector<types::global_dof_index> local_dof_indices;\n    };\n    void assemble_system();\n    void local_assemble_system(\n        const typename DoFHandler<dim>::active_cell_iterator &cell,\n        AssemblyScratchData &scratch, AssemblyCopyData &copy_data);\n    void copy_local_to_global(const AssemblyCopyData &copy_data);\n    void solve();\n    void solve(MPI_Comm mpi_communicator);\n    void refine_grid();\n    void output_results(const unsigned int cycle) const;\n    Triangulation<dim> triangulation;\n    DoFHandler<dim> dof_handler;\n    FE_Q<dim> fe;\n    AffineConstraints<double> hanging_node_constraints;\n    SparsityPattern sparsity_pattern;\n    SparseMatrix<double> system_matrix;\n    Vector<double> solution;\n    Vector<double> system_rhs;\n};\n\n\nclass GradientEstimation {\npublic:\n    template <int dim>\n    static void estimate(const DoFHandler<dim> &dof,\n                         const Vector<double> &solution,\n                         Vector<float> &error_per_cell);\n    DeclException2(ExcInvalidVectorLength, int, int,\n                   << \"Vector has length \" << arg1 << \", but should have \"\n                   << arg2);\n    DeclException0(ExcInsufficientDirections);\n\nprivate:\n    template <int dim>\n    struct EstimateScratchData {\n        EstimateScratchData(const FiniteElement<dim> &fe,\n                            const Vector<double> &solution,\n                            Vector<float> &error_per_cell);\n        EstimateScratchData(const EstimateScratchData &data);\n        FEValues<dim> fe_midpoint_value;\n        std::vector<typename DoFHandler<dim>::active_cell_iterator>\n            active_neighbors;\n        const Vector<double> &solution;\n        Vector<float> &error_per_cell;\n        std::vector<double> cell_midpoint_value;\n        std::vector<double> neighbor_midpoint_value;\n    };\n    struct EstimateCopyData {};\n    template <int dim>\n    static void estimate_cell(\n        const typename DoFHandler<dim>::active_cell_iterator &cell,\n        EstimateScratchData<dim> &scratch_data,\n        const EstimateCopyData &copy_data);\n};\n\n\ntemplate <int dim>\nAdvectionProblem<dim>::AdvectionProblem() : dof_handler(triangulation), fe(5)\n{}\n\n\ntemplate <int dim>\nvoid AdvectionProblem<dim>::setup_system()\n{\n    dof_handler.distribute_dofs(fe);\n    hanging_node_constraints.clear();\n    DoFTools::make_hanging_node_constraints(dof_handler,\n                                            hanging_node_constraints);\n    hanging_node_constraints.close();\n    DynamicSparsityPattern dsp(dof_handler.n_dofs(), dof_handler.n_dofs());\n    DoFTools::make_sparsity_pattern(dof_handler, dsp, hanging_node_constraints,\n                                    /*keep_constrained_dofs =*/false);\n    sparsity_pattern.copy_from(dsp);\n    system_matrix.reinit(sparsity_pattern);\n    solution.reinit(dof_handler.n_dofs());\n    system_rhs.reinit(dof_handler.n_dofs());\n}\n\n\ntemplate <int dim>\nvoid AdvectionProblem<dim>::assemble_system()\n{\n    WorkStream::run(dof_handler.begin_active(), dof_handler.end(), *this,\n                    &AdvectionProblem::local_assemble_system,\n                    &AdvectionProblem::copy_local_to_global,\n                    AssemblyScratchData(fe), AssemblyCopyData());\n}\n\n\ntemplate <int dim>\nAdvectionProblem<dim>::AssemblyScratchData::AssemblyScratchData(\n    const FiniteElement<dim> &fe)\n    : fe_values(fe, QGauss<dim>(fe.degree + 1),\n                update_values | update_gradients | update_quadrature_points |\n                    update_JxW_values),\n      fe_face_values(fe, QGauss<dim - 1>(fe.degree + 1),\n                     update_values | update_quadrature_points |\n                         update_JxW_values | update_normal_vectors),\n      rhs_values(fe_values.get_quadrature().size()),\n      advection_directions(fe_values.get_quadrature().size()),\n      face_boundary_values(fe_face_values.get_quadrature().size()),\n      face_advection_directions(fe_face_values.get_quadrature().size())\n{}\n\n\ntemplate <int dim>\nAdvectionProblem<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_values | update_gradients | update_quadrature_points |\n                    update_JxW_values),\n      fe_face_values(scratch_data.fe_face_values.get_fe(),\n                     scratch_data.fe_face_values.get_quadrature(),\n                     update_values | update_quadrature_points |\n                         update_JxW_values | update_normal_vectors),\n      rhs_values(scratch_data.rhs_values.size()),\n      advection_directions(scratch_data.advection_directions.size()),\n      face_boundary_values(scratch_data.face_boundary_values.size()),\n      face_advection_directions(scratch_data.face_advection_directions.size())\n{}\n\n\ntemplate <int dim>\nvoid AdvectionProblem<dim>::local_assemble_system(\n    const typename DoFHandler<dim>::active_cell_iterator &cell,\n    AssemblyScratchData &scratch_data, AssemblyCopyData &copy_data)\n{\n    const unsigned int dofs_per_cell = fe.dofs_per_cell;\n    const unsigned int n_q_points =\n        scratch_data.fe_values.get_quadrature().size();\n    const unsigned int n_face_q_points =\n        scratch_data.fe_face_values.get_quadrature().size();\n    copy_data.cell_matrix.reinit(dofs_per_cell, dofs_per_cell);\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    scratch_data.advection_field.value_list(\n        scratch_data.fe_values.get_quadrature_points(),\n        scratch_data.advection_directions);\n    scratch_data.right_hand_side.value_list(\n        scratch_data.fe_values.get_quadrature_points(),\n        scratch_data.rhs_values);\n    const double delta = 0.1 * cell->diameter();\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            const auto &sd = scratch_data;\n            for (unsigned int j = 0; j < dofs_per_cell; ++j)\n                copy_data.cell_matrix(i, j) +=\n                    ((sd.fe_values.shape_value(i, q_point) +       // (phi_i +\n                      delta * (sd.advection_directions[q_point] *  // delta beta\n                               sd.fe_values.shape_grad(\n                                   i, q_point))) *           // grad phi_i)\n                     sd.advection_directions[q_point] *      // beta\n                     sd.fe_values.shape_grad(j, q_point)) *  // grad phi_j\n                    sd.fe_values.JxW(q_point);               // dx\n            copy_data.cell_rhs(i) +=\n                (sd.fe_values.shape_value(i, q_point) +  // (phi_i +\n                 delta *\n                     (sd.advection_directions[q_point] *       // delta beta\n                      sd.fe_values.shape_grad(i, q_point))) *  // grad phi_i)\n                sd.rhs_values[q_point] *                       // f\n                sd.fe_values.JxW(q_point);                     // dx\n        }\n    for (const auto &face : cell->face_iterators())\n        if (face->at_boundary()) {\n            scratch_data.fe_face_values.reinit(cell, face);\n            scratch_data.boundary_values.value_list(\n                scratch_data.fe_face_values.get_quadrature_points(),\n                scratch_data.face_boundary_values);\n            scratch_data.advection_field.value_list(\n                scratch_data.fe_face_values.get_quadrature_points(),\n                scratch_data.face_advection_directions);\n            for (unsigned int q_point = 0; q_point < n_face_q_points; ++q_point)\n                if (scratch_data.fe_face_values.normal_vector(q_point) *\n                        scratch_data.face_advection_directions[q_point] <\n                    0.)\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\n                                     .face_advection_directions[q_point] *\n                                 scratch_data.fe_face_values.normal_vector(\n                                     q_point) *\n                                 scratch_data.fe_face_values.shape_value(\n                                     i, q_point) *\n                                 scratch_data.fe_face_values.shape_value(\n                                     j, q_point) *\n                                 scratch_data.fe_face_values.JxW(q_point));\n                        copy_data.cell_rhs(i) -=\n                            (scratch_data.face_advection_directions[q_point] *\n                             scratch_data.fe_face_values.normal_vector(\n                                 q_point) *\n                             scratch_data.face_boundary_values[q_point] *\n                             scratch_data.fe_face_values.shape_value(i,\n                                                                     q_point) *\n                             scratch_data.fe_face_values.JxW(q_point));\n                    }\n        }\n    cell->get_dof_indices(copy_data.local_dof_indices);\n}\n\n\ntemplate <int dim>\nvoid AdvectionProblem<dim>::copy_local_to_global(\n    const AssemblyCopyData &copy_data)\n{\n    hanging_node_constraints.distribute_local_to_global(\n        copy_data.cell_matrix, copy_data.cell_rhs, copy_data.local_dof_indices,\n        system_matrix, system_rhs);\n}\n\n\ntemplate <int dim>\nvoid AdvectionProblem<dim>::solve(MPI_Comm mpi_communicator)\n{\n    using ValueType = double;\n    using IndexType = int;\n    schwz::Metadata<ValueType, IndexType> metadata;\n    schwz::Settings settings(FLAGS_executor);\n\n    // Set solver metadata from command line args.\n    metadata.mpi_communicator = mpi_communicator;\n    MPI_Comm_rank(metadata.mpi_communicator, &metadata.my_rank);\n    MPI_Comm_size(metadata.mpi_communicator, &metadata.comm_size);\n    metadata.tolerance = FLAGS_set_tol;\n    metadata.max_iters = FLAGS_num_iters;\n    metadata.num_subdomains = metadata.comm_size;\n    metadata.num_threads = FLAGS_num_threads;\n    metadata.oned_laplacian_size = FLAGS_set_1d_laplacian_size;\n\n    // Generic settings\n    settings.write_debug_out = FLAGS_enable_debug_write;\n    settings.write_perm_data = FLAGS_write_perm_data;\n    settings.write_iters_and_residuals = FLAGS_write_iters_and_residuals;\n    settings.print_matrices = FLAGS_print_matrices;\n    settings.shifted_iter = FLAGS_shifted_iter;\n\n    // Set solver settings from command line args.\n    // Comm settings\n    settings.comm_settings.enable_onesided = FLAGS_enable_onesided;\n    if (FLAGS_remote_comm_type == \"put\") {\n        settings.comm_settings.enable_put = true;\n        settings.comm_settings.enable_get = false;\n    } else if (FLAGS_remote_comm_type == \"get\") {\n        settings.comm_settings.enable_put = false;\n        settings.comm_settings.enable_get = true;\n    }\n    settings.comm_settings.enable_one_by_one = FLAGS_enable_one_by_one;\n    settings.comm_settings.stage_through_host = FLAGS_stage_through_host;\n    settings.comm_settings.enable_overlap = FLAGS_enable_comm_overlap;\n    if (FLAGS_flush_type == \"flush-all\") {\n        settings.comm_settings.enable_flush_all = true;\n    } else if (FLAGS_flush_type == \"flush-local\") {\n        settings.comm_settings.enable_flush_all = false;\n        settings.comm_settings.enable_flush_local = true;\n    }\n    if (FLAGS_lock_type == \"lock-all\") {\n        settings.comm_settings.enable_lock_all = true;\n    } else if (FLAGS_lock_type == \"lock-local\") {\n        settings.comm_settings.enable_lock_all = false;\n        settings.comm_settings.enable_lock_local = true;\n    }\n\n    // Convergence settings\n    settings.convergence_settings.put_all_local_residual_norms =\n        FLAGS_enable_put_all_local_residual_norms;\n    settings.convergence_settings.enable_global_check_iter_offset =\n        FLAGS_enable_global_check_iter_offset;\n    settings.convergence_settings.enable_global_check =\n        FLAGS_enable_global_check;\n    if (FLAGS_global_convergence_type == \"centralized-tree\") {\n        settings.convergence_settings.enable_global_simple_tree = true;\n    } else if (FLAGS_global_convergence_type == \"decentralized\") {\n        settings.convergence_settings.enable_decentralized_leader_election =\n            true;\n        settings.convergence_settings.enable_accumulate =\n            FLAGS_enable_decentralized_accumulate;\n    }\n\n    // General solver settings\n    metadata.local_solver_tolerance = FLAGS_local_tol;\n    metadata.local_precond = FLAGS_local_precond;\n    metadata.local_max_iters = FLAGS_local_max_iters;\n    metadata.updated_max_iters = FLAGS_updated_max_iters;\n    settings.non_symmetric_matrix = FLAGS_non_symmetric_matrix;\n    settings.restart_iter = FLAGS_restart_iter;\n    settings.reset_local_crit_iter = FLAGS_reset_local_crit_iter;\n    settings.enable_logging = FLAGS_enable_logging;\n    metadata.precond_max_block_size = FLAGS_precond_max_block_size;\n    settings.matrix_filename = FLAGS_matrix_filename;\n    settings.explicit_laplacian = FLAGS_explicit_laplacian;\n    settings.enable_random_rhs = FLAGS_enable_random_rhs;\n    settings.use_mixed_precision = FLAGS_use_mixed_precision;\n    settings.overlap = FLAGS_overlap;\n    settings.naturally_ordered_factor = FLAGS_factor_ordering_natural;\n    settings.reorder = FLAGS_local_reordering;\n    settings.factorization = FLAGS_local_factorization;\n    if (FLAGS_partition == \"metis\") {\n        settings.partition =\n            schwz::Settings::partition_settings::partition_metis;\n        settings.metis_objtype = FLAGS_metis_objtype;\n    } else if (FLAGS_partition == \"regular\") {\n        settings.partition =\n            schwz::Settings::partition_settings::partition_regular;\n    } else if (FLAGS_partition == \"regular2d\") {\n        settings.partition =\n            schwz::Settings::partition_settings::partition_regular2d;\n    }\n    if (FLAGS_local_solver == \"iterative-ginkgo\") {\n        settings.local_solver =\n            schwz::Settings::local_solver_settings::iterative_solver_ginkgo;\n    } else if (FLAGS_local_solver == \"direct-cholmod\") {\n        settings.local_solver =\n            schwz::Settings::local_solver_settings::direct_solver_cholmod;\n    } else if (FLAGS_local_solver == \"direct-umfpack\") {\n        settings.local_solver =\n            schwz::Settings::local_solver_settings::direct_solver_umfpack;\n    } else if (FLAGS_local_solver == \"direct-ginkgo\") {\n        settings.local_solver =\n            schwz::Settings::local_solver_settings::direct_solver_ginkgo;\n    }\n    settings.debug_print = FLAGS_debug;\n    int gsize = 0;\n    if (metadata.my_rank == 0) {\n        metadata.global_size = system_matrix.m();\n        std::cout << \" Running on the \" << FLAGS_executor << \" executor on \"\n                  << metadata.num_subdomains << \" ranks with \"\n                  << FLAGS_num_threads << \" threads\" << std::endl;\n        std::cout << \" Problem Size: \" << metadata.global_size\n                  << \" Number of non-zeros: \"\n                  << system_matrix.n_nonzero_elements() << std::endl;\n        gsize = metadata.global_size;\n    }\n    MPI_Bcast(&gsize, 1, MPI_INT, 0, MPI_COMM_WORLD);\n    metadata.global_size = gsize;\n    if (FLAGS_print_config) {\n        if (metadata.my_rank == 0) {\n            this->print_config();\n        }\n    }\n    using vec_vtype = gko::matrix::Dense<ValueType>;\n    std::shared_ptr<vec_vtype> solution_vector;\n    schwz::SolverRAS<ValueType, IndexType> solver(settings, metadata);\n    solver.initialize(system_matrix, system_rhs);\n    auto start_time = std::chrono::steady_clock::now();\n    solver.run(solution_vector);\n    auto elapsed_time = std::chrono::duration<double>(\n        std::chrono::steady_clock::now() - start_time);\n    if (metadata.my_rank == 0) {\n        std::cout << \"Time for solve only: \" << elapsed_time.count()\n                  << std::endl;\n    }\n    if (FLAGS_timings_file != \"null\") {\n        std::string rank_string = std::to_string(metadata.my_rank);\n        if (metadata.my_rank < 10) {\n            rank_string = \"0\" + std::to_string(metadata.my_rank);\n        }\n        std::string filename = FLAGS_timings_file + \"_\" + rank_string + \".csv\";\n        this->write_timings(metadata.time_struct, filename,\n                            settings.comm_settings.enable_onesided);\n    }\n    if (FLAGS_write_comm_data) {\n        std::string rank_string = std::to_string(metadata.my_rank);\n        if (metadata.my_rank < 10) {\n            rank_string = \"0\" + std::to_string(metadata.my_rank);\n        }\n        std::string filename_send = \"num_send_\" + rank_string + \".csv\";\n        std::string filename_recv = \"num_recv_\" + rank_string + \".csv\";\n        this->write_comm_data(metadata.num_subdomains, metadata.my_rank,\n                              metadata.comm_data_struct, filename_send,\n                              filename_recv);\n    }\n\n    if (metadata.my_rank == 0) {\n        std::copy(solution_vector->get_values(),\n                  solution_vector->get_values() + metadata.global_size,\n                  solution.begin());\n        hanging_node_constraints.distribute(solution);\n    }\n}\n\n\ntemplate <int dim>\nvoid AdvectionProblem<dim>::solve()\n{\n    SolverControl solver_control(\n        std::max<std::size_t>(1000, system_rhs.size() / 10),\n        1e-10 * system_rhs.l2_norm());\n    SolverGMRES<> solver(solver_control);\n    PreconditionJacobi<> preconditioner;\n    preconditioner.initialize(system_matrix, 1.0);\n    auto start_time = std::chrono::steady_clock::now();\n    solver.solve(system_matrix, solution, system_rhs, preconditioner);\n    auto elapsed_time = std::chrono::duration<double>(\n        std::chrono::steady_clock::now() - start_time);\n    std::cout << \"Time for solve only: \" << elapsed_time.count() << std::endl;\n    Vector<double> residual(dof_handler.n_dofs());\n    system_matrix.vmult(residual, solution);\n    residual -= system_rhs;\n    std::cout << \"   Iterations required for convergence: \"\n              << solver_control.last_step() << '\\n'\n              << \"   Max norm of residual:                \"\n              << residual.linfty_norm() << '\\n';\n    hanging_node_constraints.distribute(solution);\n}\n\n\ntemplate <int dim>\nvoid AdvectionProblem<dim>::refine_grid()\n{\n    Vector<float> estimated_error_per_cell(triangulation.n_active_cells());\n    GradientEstimation::estimate(dof_handler, solution,\n                                 estimated_error_per_cell);\n    GridRefinement::refine_and_coarsen_fixed_number(\n        triangulation, estimated_error_per_cell, 0.3, 0.03);\n    triangulation.execute_coarsening_and_refinement();\n}\n\n\ntemplate <int dim>\nvoid AdvectionProblem<dim>::output_results(const unsigned int cycle) const\n{\n    {\n        GridOut grid_out;\n        std::ofstream output(\"grid-\" + std::to_string(cycle) + \".vtu\");\n        grid_out.write_vtu(triangulation, output);\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(8);\n        DataOutBase::VtkFlags vtk_flags;\n        vtk_flags.compression_level =\n            DataOutBase::VtkFlags::ZlibCompressionLevel::best_speed;\n        data_out.set_flags(vtk_flags);\n        std::ofstream output(\"solution-\" + std::to_string(cycle) + \".vtu\");\n        data_out.write_vtu(output);\n    }\n}\n\n\ntemplate <int dim>\nvoid AdvectionProblem<dim>::run(MPI_Comm mpi_communicator)\n{\n    int num_cycles = FLAGS_num_refine_cycles;\n    int mpi_size, mpi_rank;\n    MPI_Comm_size(MPI_COMM_WORLD, &mpi_size);\n    MPI_Comm_rank(MPI_COMM_WORLD, &mpi_rank);\n    for (unsigned int cycle = 0; cycle < num_cycles; ++cycle) {\n        if (mpi_rank == 0) {\n            std::cout << \"Cycle \" << cycle << ':' << std::endl;\n\n            if (cycle == 0) {\n                GridGenerator::hyper_cube(triangulation, -1, 1);\n                triangulation.refine_global(FLAGS_init_refine_level);\n            } else\n                refine_grid();\n            std::cout << \"   Number of active cells:       \"\n                      << triangulation.n_active_cells() << std::endl;\n            setup_system();\n            std::cout << \"   Number of degrees of freedom: \"\n                      << dof_handler.n_dofs() << std::endl;\n            assemble_system();\n        }\n        this->solve(MPI_COMM_WORLD);\n        if (mpi_rank == 0) {\n            if (FLAGS_vis_sol) {\n                output_results(cycle);\n            }\n        }\n    }\n}\n\n\ntemplate <int dim>\nvoid AdvectionProblem<dim>::run()\n{\n    int num_cycles = FLAGS_num_refine_cycles;\n    for (unsigned int cycle = 0; cycle < num_cycles; ++cycle) {\n        std::cout << \"Cycle \" << cycle << ':' << std::endl;\n\n        if (cycle == 0) {\n            GridGenerator::hyper_cube(triangulation, -1, 1);\n            triangulation.refine_global(FLAGS_init_refine_level);\n        } else\n            refine_grid();\n        std::cout << \"   Number of active cells:       \"\n                  << triangulation.n_active_cells() << std::endl;\n        setup_system();\n        std::cout << \"   Number of degrees of freedom: \" << dof_handler.n_dofs()\n                  << std::endl;\n        assemble_system();\n        this->solve();\n        if (FLAGS_vis_sol) {\n            output_results(cycle);\n        }\n    }\n}\n\n\ntemplate <int dim>\nGradientEstimation::EstimateScratchData<dim>::EstimateScratchData(\n    const FiniteElement<dim> &fe, const Vector<double> &solution,\n    Vector<float> &error_per_cell)\n    : fe_midpoint_value(fe, QMidpoint<dim>(),\n                        update_values | update_quadrature_points),\n      solution(solution),\n      error_per_cell(error_per_cell),\n      cell_midpoint_value(1),\n      neighbor_midpoint_value(1)\n{\n    active_neighbors.reserve(GeometryInfo<dim>::faces_per_cell *\n                             GeometryInfo<dim>::max_children_per_face);\n}\n\n\ntemplate <int dim>\nGradientEstimation::EstimateScratchData<dim>::EstimateScratchData(\n    const EstimateScratchData &scratch_data)\n    : fe_midpoint_value(scratch_data.fe_midpoint_value.get_fe(),\n                        scratch_data.fe_midpoint_value.get_quadrature(),\n                        update_values | update_quadrature_points),\n      solution(scratch_data.solution),\n      error_per_cell(scratch_data.error_per_cell),\n      cell_midpoint_value(1),\n      neighbor_midpoint_value(1)\n{}\n\n\ntemplate <int dim>\nvoid GradientEstimation::estimate(const DoFHandler<dim> &dof_handler,\n                                  const Vector<double> &solution,\n                                  Vector<float> &error_per_cell)\n{\n    Assert(error_per_cell.size() ==\n               dof_handler.get_triangulation().n_active_cells(),\n           ExcInvalidVectorLength(\n               error_per_cell.size(),\n               dof_handler.get_triangulation().n_active_cells()));\n    WorkStream::run(dof_handler.begin_active(), dof_handler.end(),\n                    &GradientEstimation::template estimate_cell<dim>,\n                    std::function<void(const EstimateCopyData &)>(),\n                    EstimateScratchData<dim>(dof_handler.get_fe(), solution,\n                                             error_per_cell),\n                    EstimateCopyData());\n}\n\n\ntemplate <int dim>\nvoid GradientEstimation::estimate_cell(\n    const typename DoFHandler<dim>::active_cell_iterator &cell,\n    EstimateScratchData<dim> &scratch_data, const EstimateCopyData &)\n{\n    Tensor<2, dim> Y;\n    scratch_data.fe_midpoint_value.reinit(cell);\n    scratch_data.active_neighbors.clear();\n    for (unsigned int face_n : GeometryInfo<dim>::face_indices())\n        if (!cell->at_boundary(face_n)) {\n            const auto face = cell->face(face_n);\n            const auto neighbor = cell->neighbor(face_n);\n            if (neighbor->is_active())\n                scratch_data.active_neighbors.push_back(neighbor);\n            else {\n                if (dim == 1) {\n                    auto neighbor_child = neighbor;\n                    while (neighbor_child->has_children())\n                        neighbor_child =\n                            neighbor_child->child(face_n == 0 ? 1 : 0);\n                    Assert(\n                        neighbor_child->neighbor(face_n == 0 ? 1 : 0) == cell,\n                        ExcInternalError());\n                    scratch_data.active_neighbors.push_back(neighbor_child);\n                } else\n                    for (unsigned int subface_n = 0;\n                         subface_n < face->n_children(); ++subface_n)\n                        scratch_data.active_neighbors.push_back(\n                            cell->neighbor_child_on_subface(face_n, subface_n));\n            }\n        }\n    const Point<dim> this_center =\n        scratch_data.fe_midpoint_value.quadrature_point(0);\n    scratch_data.fe_midpoint_value.get_function_values(\n        scratch_data.solution, scratch_data.cell_midpoint_value);\n    Tensor<1, dim> projected_gradient;\n    for (const auto &neighbor : scratch_data.active_neighbors) {\n        scratch_data.fe_midpoint_value.reinit(neighbor);\n        const Point<dim> neighbor_center =\n            scratch_data.fe_midpoint_value.quadrature_point(0);\n        scratch_data.fe_midpoint_value.get_function_values(\n            scratch_data.solution, scratch_data.neighbor_midpoint_value);\n        Tensor<1, dim> y = neighbor_center - this_center;\n        const double distance = y.norm();\n        y /= distance;\n        for (unsigned int i = 0; i < dim; ++i)\n            for (unsigned int j = 0; j < dim; ++j) Y[i][j] += y[i] * y[j];\n        projected_gradient += (scratch_data.neighbor_midpoint_value[0] -\n                               scratch_data.cell_midpoint_value[0]) /\n                              distance * y;\n    }\n    AssertThrow(determinant(Y) != 0, ExcInsufficientDirections());\n    const Tensor<2, dim> Y_inverse = invert(Y);\n    const Tensor<1, dim> gradient = Y_inverse * projected_gradient;\n    scratch_data.error_per_cell(cell->active_cell_index()) =\n        (std::pow(cell->diameter(), 1 + 1.0 * dim / 2) * gradient.norm());\n}\n\n\nint main(int argc, char **argv)\n{\n    using namespace dealii;\n    try {\n        initialize_argument_parsing(&argc, &argv);\n        MultithreadInfo::set_thread_limit();\n        AdvectionProblem<2> advection_problem_2d;\n        if (FLAGS_num_threads > 1) {\n            int req_thread_support = MPI_THREAD_MULTIPLE;\n            int prov_thread_support = MPI_THREAD_MULTIPLE;\n\n            MPI_Init_thread(&argc, &argv, req_thread_support,\n                            &prov_thread_support);\n            if (prov_thread_support != req_thread_support) {\n                std::cout << \"Required thread support is \" << req_thread_support\n                          << \" but provided thread support is only \"\n                          << prov_thread_support << std::endl;\n            }\n        } else {\n            MPI_Init(&argc, &argv);\n        }\n        int rank = 0;\n        MPI_Comm_rank(MPI_COMM_WORLD, &rank);\n\n        if (FLAGS_dealii_orig) {\n            if (rank == 0) {\n                auto start_time = std::chrono::steady_clock::now();\n                advection_problem_2d.run();\n                auto elapsed_time = std::chrono::duration<double>(\n                    std::chrono::steady_clock::now() - start_time);\n                std::cout << \"Total Time for setup+solve: \"\n                          << elapsed_time.count() << std::endl;\n            }\n        } else {\n            auto start_time = std::chrono::steady_clock::now();\n            advection_problem_2d.run(MPI_COMM_WORLD);\n            auto elapsed_time = std::chrono::duration<double>(\n                std::chrono::steady_clock::now() - start_time);\n            if (rank == 0) {\n                std::cout << \"Total Time for setup+solve: \"\n                          << elapsed_time.count() << std::endl;\n            }\n        }\n        MPI_Finalize();\n    } catch (std::exception &exc) {\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    } catch (...) {\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": "af72213236553153a975ba131ab611a7ff9e2009", "size": 34171, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "benchmarking/dealii_ex_9.cpp", "max_stars_repo_name": "soumyadipghosh/schwarz-lib", "max_stars_repo_head_hexsha": "7a9a97dd0bde49fa0dd4bd386c6f185bef128fe0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-09-23T07:37:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-19T09:39:01.000Z", "max_issues_repo_path": "benchmarking/dealii_ex_9.cpp", "max_issues_repo_name": "soumyadipghosh/schwarz-lib", "max_issues_repo_head_hexsha": "7a9a97dd0bde49fa0dd4bd386c6f185bef128fe0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 15.0, "max_issues_repo_issues_event_min_datetime": "2020-03-23T14:20:31.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-08T07:43:27.000Z", "max_forks_repo_path": "benchmarking/dealii_ex_9.cpp", "max_forks_repo_name": "soumyadipghosh/schwarz-lib", "max_forks_repo_head_hexsha": "7a9a97dd0bde49fa0dd4bd386c6f185bef128fe0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-09-23T15:38:48.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-19T19:50:50.000Z", "avg_line_length": 40.5831353919, "max_line_length": 80, "alphanum_fraction": 0.6230429311, "num_tokens": 7476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191214879992, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.46931597592797286}}
{"text": "#include <iostream>\n#include <cmath>\n#include <algorithm>\n#include <vector>\n#include <boost/multiprecision/cpp_int.hpp>\nusing namespace boost::multiprecision;\nusing namespace std;\nint main() {\n    cpp_int a, b, c; cin >> a >> b >> c;\n\n    cout << (a * b * c * (a + 1) * (b + 1) * (c + 1) / 8) % 998244353 << endl;\n}\n", "meta": {"hexsha": "6e51cd7799b9fef601fee5fa2c3271866c554a74", "size": 316, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AtCoder/arc107/a/main.cpp", "max_stars_repo_name": "H-Tatsuhiro/Com_Pro-Cpp", "max_stars_repo_head_hexsha": "fd79f7821a76b11f4a6f83bbb26a034db577a877", "max_stars_repo_licenses": ["MIT"], "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/arc107/a/main.cpp", "max_issues_repo_name": "H-Tatsuhiro/Com_Pro-Cpp", "max_issues_repo_head_hexsha": "fd79f7821a76b11f4a6f83bbb26a034db577a877", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-10-19T08:47:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T05:23:56.000Z", "max_forks_repo_path": "AtCoder/arc107/a/main.cpp", "max_forks_repo_name": "H-Tatsuhiro/Com_Pro-Cpp", "max_forks_repo_head_hexsha": "fd79f7821a76b11f4a6f83bbb26a034db577a877", "max_forks_repo_licenses": ["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.3076923077, "max_line_length": 78, "alphanum_fraction": 0.6075949367, "num_tokens": 101, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.46923732326786777}}
{"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\u2019s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n#pragma once\n\n#include \"../util/ConvolutionTools.hpp\"\n#include \"../util/FluidEigenMappings.hpp\"\n#include \"../util/Novelty.hpp\"\n#include \"../../data/FluidIndex.hpp\"\n#include \"../../data/TensorTypes.hpp\"\n#include <Eigen/Core>\n\nnamespace fluid {\nnamespace algorithm {\n\nclass NoveltySegmentation\n{\n\npublic:\n  using ArrayXd = Eigen::ArrayXd;\n\n  NoveltySegmentation(index maxKernelSize, index maxFilterSize)\n      : mFilterBufferStorage(maxFilterSize), mNovelty(maxKernelSize)\n  {}\n\n  void init(index kernelSize, index filterSize, index nDims)\n  {\n    assert(kernelSize % 2);\n    mNovelty.init(kernelSize, nDims);\n    mFilterBuffer = mFilterBufferStorage.segment(0, filterSize);\n    mFilterBuffer.setZero();\n    mDebounceCount = 1;\n  }\n\n  double processFrame(const RealVectorView input, double threshold,\n                      index minSliceLength)\n  {\n    double novelty = mNovelty.processFrame(_impl::asEigen<Eigen::Array>(input));\n    double detected = 0.;\n    index  filterSize = mFilterBuffer.size();\n    if (filterSize > 1)\n    {\n      mFilterBuffer.segment(0, filterSize - 1) =\n          mFilterBuffer.segment(1, filterSize - 1);\n    }\n    mPeakBuffer.segment(0, 2) = mPeakBuffer.segment(1, 2);\n    mFilterBuffer(filterSize - 1) = novelty;\n    mPeakBuffer(2) = mFilterBuffer.mean();\n    if (mPeakBuffer(1) > mPeakBuffer(0) && mPeakBuffer(1) > mPeakBuffer(2) &&\n        mPeakBuffer(1) > threshold && mDebounceCount == 0)\n    {\n      detected = 1.0;\n      mDebounceCount = minSliceLength;\n    }\n    else\n    {\n      if (mDebounceCount > 0) mDebounceCount--;\n    }\n    return detected;\n  }\n\nprivate:\n  ArrayXd mFilterBuffer;\n  ArrayXd mFilterBufferStorage;\n  ArrayXd mPeakBuffer{3};\n  Novelty mNovelty;\n  index   mDebounceCount{1};\n};\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "99d2644c294e13bca1b78f37038ad2d728d6431b", "size": 2188, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/public/NoveltySegmentation.hpp", "max_stars_repo_name": "elgiano/flucoma-core", "max_stars_repo_head_hexsha": "d34a04e7a68f24eaf09b24df57020d45664061fc", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/algorithms/public/NoveltySegmentation.hpp", "max_issues_repo_name": "elgiano/flucoma-core", "max_issues_repo_head_hexsha": "d34a04e7a68f24eaf09b24df57020d45664061fc", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/algorithms/public/NoveltySegmentation.hpp", "max_forks_repo_name": "elgiano/flucoma-core", "max_forks_repo_head_hexsha": "d34a04e7a68f24eaf09b24df57020d45664061fc", "max_forks_repo_licenses": ["BSD-3-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.0512820513, "max_line_length": 80, "alphanum_fraction": 0.7001828154, "num_tokens": 577, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387914176259, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4691947204854313}}
{"text": "#include <iostream>\n#include <fstream>\n#include <Eigen/Eigen>\n//include the bie header files\n#include \"material.hh\"\n#include \"precomputed_kernel.hh\"\n#include \"bimat_interface.hh\"\n#include \"infinite_boundary.hh\"\n//include the fem header files\n#include \"mesh_Abaqus_multi_faults.hpp\"\n#include \"bcdof.hpp\"\n#include \"bcdof_ptr.hpp\"\n#include \"cal_ke.hpp\"\n#include \"cal_fe_global_const_ke.hpp\"\n#include \"mapglobal.hpp\"\n#include \"maplocal.hpp\"\n#include \"Slip_Weakening_lumpM.hpp\"\n#include \"cal_slip_sliprate_angle.hpp\"\n#include \"time_advance.hpp\"\n#include \"BIE_correct.hpp\"\n#include \"igl/list_to_matrix.h\"\n#include <math.h>\nusing namespace Eigen;\nusing namespace std;\n\ntypedef Eigen::Matrix<int, -1, -1,RowMajor> MatrixXi_rm;\n\nvoid read_matrix(std::string fileName, Eigen::MatrixXd &outputMat);\n\ndouble time_fem=0;\ndouble time_bie;\nint main() {\n    std::string filename = \"abaqus_cpp_5degree_100m_10km_4km.inp\";\n    std::cout<<filename<<std::endl;\n    double fault_angle  = 5/180.0*M_PI;\n    int dim = 2.0;\n    double x_max = 5.0e3;\n    double x_min = -5.0e3;\n    double dx = 100.0;\n    double dy = 100.0;\n    std::vector<int> BIE_top, BIE_bot;\n    MatrixXd Node;\n    MatrixXi_rm Element;\n    int num_faults = 1;\n    std::vector<std::vector<int>> fault_nodes(2*num_faults);\n    mesh_Abaqus_multi_faults(filename, Node, Element, BIE_top, BIE_bot,fault_nodes);\n    std::cout<<Node<<std::endl;\n    std::cout<<\"Node size=\" << Node.rows()<<std::endl;\n    std::cout<<Element<<std::endl;\n    std::cout<<\"Element size=\"<<Element.rows()<<std::endl;\n    int nx_BIE = BIE_top.size();\n    int n_nodes = Node.rows();\n    int n_el = Element.rows();\n    int Ndofn = 2;\n    int Nnel = Element.cols();\n    // Material\n    double density = 2670.0;\n    double v_s =3.464e3;\n    double v_p = 6.0e3;\n    double G= pow(v_s,2)*density;\n    double Lambda = pow(v_p,2)*density-2.0*G;\n    double E  = G*(3.0*Lambda+2.0*G)/(Lambda+G);\n    double nu = Lambda/(2.0*(Lambda+G));\n    // Time\n    double alpha = 0.4;\n    double dt = alpha*dx/v_p;\n    // Reyleigh Damping\n    double beta =0.1;\n    double q = beta*dt;\n    double time_run = 6.0;\n    int numt = time_run/dt;\n    //numt = 1;\n    VectorXd time = dt*VectorXd::LinSpaced(numt,1,numt);\n    // Slip weakening friction parameters\n    double Dc = 0.2;\n    double mu_d= 0.5;\n    double mu_s = 0.6;\n    // Intialization\n    // disp velocity current and next time step (new)\n    VectorXd u_n = VectorXd::Zero(n_nodes*Ndofn,1);\n    VectorXd v_n = VectorXd::Zero(n_nodes*Ndofn,1);\n    VectorXd u_new = VectorXd::Zero(n_nodes*Ndofn,1);\n    VectorXd v_new = VectorXd::Zero(n_nodes*Ndofn,1);\n    VectorXd a_n = VectorXd::Zero(n_nodes*Ndofn,1);\n    // slip and slip-rate\n    std::vector<Eigen::Array<double, -1, 1> > delt_u_n(num_faults);\n    std::vector<Eigen::Array<double, -1, 1> > delt_v_n(num_faults);\n    std::vector<Eigen::Array<double, -1, 1> > T_c(num_faults);\n    std::vector<Eigen::Array<double, -1, 1> > T_0(num_faults);\n    std::vector<Eigen::Array<double, -1, 1> > tau_s(num_faults);\n\n\n    // Vector containing number of elements on each faults (nx)\n    std::vector<int> nx_faults(num_faults);\n    for (int i=0;i<num_faults;i++)\n    {\n        nx_faults[i] =fault_nodes[2*i].size();\n    }\n    \n    for (int i=0;i<num_faults;i++)\n    {\n        delt_u_n[i] = ArrayXd::Zero(Ndofn*(nx_faults[i]),1);\n        delt_v_n[i] = ArrayXd::Zero(Ndofn*(nx_faults[i]),1);\n        T_c[i] = ArrayXd::Zero(Ndofn*(nx_faults[i]),1);\n        T_0[i] = ArrayXd::Zero(Ndofn*(nx_faults[i]),1);\n       // tau_s[i] = ArrayXd::Zero(Ndofn*(nx_faults[i]),1);\n        tau_s[i] = 0.6*ArrayXd::Ones((nx_faults[i]),1)*50.0e6;\n    }\n    VectorXd F_ext_global = VectorXd::Zero(n_nodes*Ndofn,1);\n    \n    VectorXd x = VectorXd::Zero(nx_faults[0], 1);\n    for (int i=0; i<x.size(); i++)\n    {\n        x(i) = Node(fault_nodes[0][i],0);\n    }\n    std::ofstream x_output(\"results/fault_x_coord.txt\");\n    x_output << x;\n\n    \n    std::cout<<x<<std::endl;\n    // Setting intial stress on the fault\n    for (int j=0; j<num_faults;j++)\n    {\n        for (int i=0; i<nx_faults[j]; i++)\n        {\n            T_0[j](2*i+1) = -50.0e6;\n            T_c[j](2*i+1) = T_0[j](2*i+1);\n        }\n        if (j==0)\n        {\n            VectorXd x = VectorXd::LinSpaced(nx_faults[j], x_min, x_max);\n            for (int i=0 ; i<nx_faults[j]; i++)\n            {\n                //if ((x(i)<=(fault_pos(j,1)+fault_pos(j,2))/2+0.2e3)&&(x(i)>=(fault_pos(j,1)+fault_pos(j,2))/2-0.2e3))\n                if ((x(i)<=(x_min+x_max)/2+0.6e3)&&(x(i)>=(x_min+x_max)/2-0.6e3))\n                {\n                    T_0[j](2*i) = 31.0e6;\n                    T_c[j](2*i) = T_0[j](2*i);\n                }\n                else\n                {\n                    T_0[j](2*i) = 27.5e6;\n                    T_c[j](2*i) = T_0[j](2*i);\n                }\n            }\n        }\n        else\n        {\n            for (int i=0 ; i<nx_faults[j]; i++)\n            {\n                T_0[j](2*i) = 27.5e6;\n            }\n        }\n    }\n    // Get the index degree of freedome for each element\n    VectorXi index_el = VectorXi::Zero(Ndofn*Nnel,1);\n    MatrixXi index_store = MatrixXi::Zero(Nnel*Ndofn,n_el);\n    for (int i=0;i<n_el;i++)\n    {\n        bcdof(Element.row(i),dim,index_el);\n        index_store.col(i) = index_el;\n    }\n  //  VectorXi BIE_top_surf_index = VectorXi::Zero(Ndofn*(BIE_top_surf_nodes.size()),1);\n   // VectorXi BIE_bot_surf_index = VectorXi::Zero(Ndofn*(BIE_bot_surf_nodes.size()),1);\n    VectorXi BIE_top_surf_index = VectorXi::Zero(Ndofn*(BIE_top.size()),1);\n    VectorXi BIE_bot_surf_index = VectorXi::Zero(Ndofn*(BIE_bot.size()),1);\n    std::vector<Eigen::ArrayXi> Fault_surf_index(num_faults*2);\n    for (int i=0; i <num_faults*2; i++)\n    {\n        Fault_surf_index[i] = ArrayXi::Zero(Ndofn*(fault_nodes[i].size()),1);\n    }\n  \n    // Getting the faults DOF index\n    for (int i=0; i<num_faults*2;i++)\n    {\n        bcdof_ptr(fault_nodes[i], dim, Fault_surf_index[i].data());\n    }\n\n    bcdof_ptr(BIE_top,dim,BIE_top_surf_index.data());\n    bcdof_ptr(BIE_bot,dim,BIE_bot_surf_index.data());\n    //bcdof(BIE_top_surf_nodes,dim,BIE_top_surf_index);\n    //bcdof(BIE_bot_surf_nodes,dim,BIE_bot_surf_index);\n    // Calculating the Global Mass Vector (lumped mass)\n    // Element mass\n    double M=density*dx*dy*1.0;\n    VectorXd M_el_vec = M/4*VectorXd::Ones(Nnel*Ndofn,1);\n    VectorXd M_global_vec=VectorXd::Zero(n_nodes*Ndofn,1);\n    for (int i=0 ; i<n_el;i++)\n    {\n        index_el = index_store.col(i);\n        mapglobal(index_el,M_global_vec,M_el_vec);\n    }\n    // Element matrix\n    MatrixXd ke = MatrixXd::Zero(8,8);\n    MatrixXd coord = MatrixXd::Zero(4,2);\n    VectorXi Element_0= Element.row(0);\n    coord.row(0) = Node.row(Element_0(0));\n    coord.row(1) = Node.row(Element_0(1));\n    coord.row(2) = Node.row(Element_0(2));\n    coord.row(3) = Node.row(Element_0(3));\n    cal_ke (coord,E,nu,ke);\n    // BIE part initiation\n    // Setting up the material property for the BIE code\n    Material BIE_top_mat = Material(E,nu,density);\n    Material BIE_bot_mat = Material(E,nu,density);\n    double length = x_max-x_min;\n    // infinte bc BIE call infinite_boundary.cc\n    PrecomputedKernel h11(\"kernels/nu_.25_h11.dat\");\n    PrecomputedKernel h12(\"kernels/nu_.25_k12.dat\");\n    PrecomputedKernel h22(\"kernels/nu_.25_h22.dat\");\n    InfiniteBoundary BIE_inf_top(length,nx_BIE,1.0,&BIE_top_mat,&h11,&h12,&h22);\n    InfiniteBoundary BIE_inf_bot(length,nx_BIE,-1.0,&BIE_bot_mat,&h11,&h12,&h22);\n    // BIE setting time step\n    BIE_inf_top.setTimeStep(dt);\n    BIE_inf_bot.setTimeStep(dt);\n    // BIE initialization\n    BIE_inf_top.init();\n    BIE_inf_bot.init();\n    printf(\"ready to start\\n\");\n    // Output\n    ofstream file;\n    file.open(\"results/num_nodes_fault.bin\",ios::binary);\n    file.write((char*)(nx_faults.data()),nx_faults.size()*sizeof(int));\n    file.close();\n    \n    file.open(\"results/u_n.bin\",ios::binary);\n   // file.write((char*)(u_n.data()),u_n.size()*sizeof(double));\n    file.close();\n    \n    for (int i=0;i<num_faults;i++)\n    {\n        std::string slip = \"results/slip_\"+std::to_string(i)+\".bin\";\n        file.open(slip);\n        file.close();\n        std::string slip_rate = \"results/slip_rate_\"+std::to_string(i)+\".bin\";\n        file.open(slip_rate);\n        file.close();\n        std::string shear = \"results/shear_\"+std::to_string(i)+\".bin\";\n        file.open(shear);\n        file.close();\n    }\n    std::ofstream Element_output(\"results/Element.txt\");\n    std::ofstream Node_output(\"results/Node.txt\");\n    Node_output<<Node;\n    Element_output<<Element;\n    //    std::ofstream shear_x(\"results/shear.txt\");\n    //double start = omp_get_wtime();\n\n    // Main time loop\n    for (int j=0;j<numt;j++)\n    {\n        // Compute the global internal force\n        VectorXd fe_global= VectorXd::Zero(n_nodes*Ndofn,1);\n        cal_fe_global_const_ke(n_nodes, n_el, index_store, q, u_n, v_n, Ndofn, ke, fe_global);\n        // Friction subroutine\n        VectorXd F_total = F_ext_global-fe_global;\n        for (int i=0 ; i<num_faults; i++)\n        {\n            VectorXd F_fault = VectorXd::Zero(Ndofn*(nx_faults[i]),1);\n            VectorXd M_pos = VectorXd::Zero(nx_faults[i], 1);\n            VectorXd M_neg = VectorXd::Zero(nx_faults[i],1);\n            maplocal(Fault_surf_index[2*i], M_global_vec, M_pos);\n            maplocal(Fault_surf_index[2*i+1], M_global_vec, M_neg);\n            //std::cout<<M_pos<<std::endl;\n            Slip_Weakening_lumpM(M_global_vec, Fault_surf_index[2*i], Fault_surf_index[2*i+1], fe_global, dt, dx, dy, nx_faults[i]-1, delt_v_n[i], delt_u_n[i], T_0[i], tau_s[i], mu_s, mu_d, Dc, Ndofn, M_pos, M_neg , F_fault, T_c[i], fault_angle);\n            mapglobal(Fault_surf_index[2*i],F_total,-F_fault);\n            mapglobal(Fault_surf_index[2*i+1],F_total,F_fault);\n        }\n        \n        // Central Difference Time integration\n        time_advance(u_n, v_n, F_total, M_global_vec, dt);\n        // Get the slip and slip rate\n        \n        for (int i=0; i<num_faults; i++)\n        {\n            cal_slip_slip_rate_angle(u_n, v_n,  Fault_surf_index[2*i], Fault_surf_index[2*i+1] , Ndofn, nx_faults[i]-1, delt_u_n[i], delt_v_n[i],fault_angle);\n        }\n        // Correct the BIE surf nodes solutions from FEM with the BIE solution\n        BIE_correct(BIE_top_surf_index, BIE_bot_surf_index, fe_global, Ndofn, nx_BIE-1, dx, BIE_inf_top, BIE_inf_bot, u_n, v_n);\n        \n      //  if (j%4==3)\n       // {\n        for (int i=0;i<num_faults;i++)\n        {\n            std::string slip = \"results/slip_\"+std::to_string(i)+\".bin\";\n            file.open(slip,ios::binary | ios::app);\n            file.write((char*)(delt_u_n[i].data()),delt_u_n[i].size()*sizeof(double));\n            file.close();\n            \n            std::string slip_rate = \"results/slip_rate_\"+std::to_string(i)+\".bin\";\n            file.open(slip_rate,ios::binary | ios::app);\n            file.write((char*)(delt_v_n[i].data()),delt_v_n[i].size()*sizeof(double));\n            file.close();\n            \n            std::string shear = \"results/shear_\"+std::to_string(i)+\".bin\";\n            file.open(shear,ios::binary | ios::app);\n            file.write((char*)(T_c[i].data()),T_c[i].size()*sizeof(double));\n            file.close();\n        }\n        file.open(\"results/u_n.bin\",ios::binary | ios::app);\n        file.write((char*)(u_n.data()),u_n.size()*sizeof(double));\n        file.close();\n       // }\n        printf(\"Simulation time = %f\\n\",time(j));\n      //  double end_t = omp_get_wtime();\n       // std::cout<<\"time_cpu_t=\"<<end_t-start<<std::endl;\n    //   std::cout<<\"time_fem=\"<< time_fem<<std::endl;\n    //   std::cout<<\"time_bie=\"<< time_bie<<std::endl;\n    }\n    //double end = omp_get_wtime();\n    //std::cout<<\"time_cpu=\"<<end-start<<std::endl;\n    return 0;\n}\n\nvoid read_matrix(std::string fileName, Eigen::MatrixXd &outputMat) {\n    fstream cin;\n    cin.open(fileName.c_str());\n    if (cin.fail())\n    {\n        std::cerr << \"Failed to open file: \" << fileName << std::endl;\n        std::cin.get(); }\n    string s;\n    vector <vector <double> > matrix;\n    while (getline(cin, s)) {\n        stringstream input(s);\n        double temp;\n        vector <double> currentLine;\n        while (input >> temp)\n            currentLine.push_back(temp);\n        matrix.push_back(currentLine);\n    }\n    if (!igl::list_to_matrix(matrix, outputMat))\n    { std::cerr << \"list tom matrix error\" << std::endl; std::cin.get();\n        //return false;\n    }\n}\n", "meta": {"hexsha": "03fe30762ba77d33e55c705aa14c71266718bc76", "size": 12454, "ext": "cc", "lang": "C++", "max_stars_repo_path": "junk/junk_simulation/junk_test_abaqus_run_incline.cc", "max_stars_repo_name": "XiaoMaResearch/hybrid_FEM_SBI", "max_stars_repo_head_hexsha": "32fcf1e21a7f78907e01585d892777c11ff1c21e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-04-12T19:51:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-16T07:12:57.000Z", "max_issues_repo_path": "junk/junk_simulation/junk_test_abaqus_run_incline.cc", "max_issues_repo_name": "XiaoMaResearch/hybrid_FEM_SBI", "max_issues_repo_head_hexsha": "32fcf1e21a7f78907e01585d892777c11ff1c21e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "junk/junk_simulation/junk_test_abaqus_run_incline.cc", "max_forks_repo_name": "XiaoMaResearch/hybrid_FEM_SBI", "max_forks_repo_head_hexsha": "32fcf1e21a7f78907e01585d892777c11ff1c21e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-07-07T07:23:58.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-07T07:23:58.000Z", "avg_line_length": 36.9554896142, "max_line_length": 246, "alphanum_fraction": 0.5996466999, "num_tokens": 3805, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387914176258, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.46919472048543126}}
{"text": "#include \"tbb/parallel_for.h\"\n#include <iostream>\n#include <mex.h>\n#include <omp.h>\n#include <vector>\n\n#include <eigen3/Eigen/Core>\n#include <eigen3/Eigen/Dense>\n#include <eigen3/Eigen/Sparse>\n// #include <Eigen/StdVector>\n\n// #include <range/v3/all.hpp>\n// #include <range/v3/core.hpp>\n\n// #include \"storage_aliases.h\"\n\n// #define ngp int(*mxGetPr(prhs[0]))\n\n#define int_space_ptr mxGetPr(prhs[0])\n#define delta_ptr mxGetPr(prhs[1])\n#define Hdo_raw prhs[2]\n#define Hdo_ptr mxGetPr(prhs[2])\n#define int_time_ptr mxGetPr(prhs[3])\n#define d_alpha_ptr mxGetPr(prhs[4])\n#define alpha_ptr mxGetPr(prhs[5])\n#define inv_hooke_ptr mxGetPr(prhs[6])\n#define gradient_ptr mxGetPr(prhs[7])\n#define dof_imposed_raw prhs[8]\n#define dof_imposed_ptr mxGetPr(prhs[8])\n#define inv_hooke_full_ptr mxGetPr(prhs[9])\n#define gradient_width int(*mxGetPr(prhs[10]))\n\n#define output plhs[0]\n\nvoid mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {\n\n  // auto t1 = omp_get_wtime();\n  using sparse_matrix = Eigen::SparseMatrix<double, Eigen::RowMajor>;\n  using Matrix = Eigen::MatrixXd;\n  using Vector = Eigen::VectorXd;\n  using matrix6 = Eigen::Matrix<double, 6, 6>;\n  using vector6 = Eigen::Matrix<double, 6, 1>;\n\n  auto Hdo_Dimensions = mxGetDimensions(Hdo_raw);\n  auto dof_imposed_Dimensions = mxGetDimensions(dof_imposed_raw);\n  size_t const ncomp = 6; // TODO 3D only\n  size_t const ngp = Hdo_Dimensions[2];\n  size_t const ntp = Hdo_Dimensions[3];\n  size_t const ndof_imp = dof_imposed_Dimensions[0];\n  size_t const tensor_shift = ncomp * ncomp;\n  size_t const delta_shift = ncomp;\n\n  Vector alpha = Eigen::Map<Vector>(alpha_ptr, ntp);\n  Vector d_alpha = Eigen::Map<Vector>(d_alpha_ptr, ntp);\n  Eigen::Map<Matrix> int_time(int_time_ptr, ntp, ntp);\n  Eigen::Map<Matrix> gradient(gradient_ptr, ngp * ncomp, gradient_width);\n  Eigen::Map<matrix6> inv_hooke(inv_hooke_ptr);\n  Eigen::Map<Matrix> inv_hooke_full(inv_hooke_full_ptr, ngp * ncomp,\n                                    ngp * ncomp);\n  std::vector<std::int32_t> fixed_dofs;\n  for (size_t j = 0; j < ndof_imp; j++)\n    fixed_dofs.push_back(*(dof_imposed_ptr + j));\n\n  sparse_matrix A(ncomp * ngp, ncomp * ngp);\n  sparse_matrix A_noint(ncomp * ngp, ncomp * ngp);\n  Vector b(ngp * ncomp);\n  Vector Q3_vec(ngp * ncomp);\n  Vector space_mode(ngp * ncomp);\n\n  double int_alpha_d_alpha = alpha.transpose() * int_time * d_alpha;\n  Vector int_alpha_alpha = int_time * alpha.cwiseProduct(alpha);\n  Vector int_alpha = int_time * alpha;\n  Vector int_d_alpha = int_time * d_alpha;\n  // auto t2 = omp_get_wtime();\n  // std::cout << \" /* block1 */ \" << t2 - t1 << '\\n';\n\n  // t1 = omp_get_wtime();\n  // #pragma omp parallel for\n  for (size_t i = 0; i < ngp; i++) {\n    size_t const position = i * ncomp;\n    size_t const int_idx = i * tensor_shift;\n    matrix6 B = matrix6::Zeros();\n    vector6 Q3 = vector6::Zeros();\n\n    // #pragma omp parallel for\n    for (size_t j = 0; j < ntp; j++) {\n      int const delta_idx = (j * ngp + i) * delta_shift;\n      int const tensor_idx = (j * ngp + i) * tensor_shift;\n      matrix6 H = Eigen::Map<matrix6>(Hdo_ptr + tensor_idx);\n      vector6 delta = Eigen::Map<vector6>(delta_ptr + delta_idx);\n      B.noalias() += H * int_alpha_alpha(j);\n      Q3 += delta * int_alpha(j);\n    }\n\n    matrix6 Int_space = Eigen::Map<matrix6>(int_space_ptr + int_idx, ncomp,\n                                            ncomp); // TODO: alligned\n    matrix6 Z = (B + int_alpha_d_alpha * inv_hooke).inverse();\n    matrix6 int_Z = Int_space * Z;\n\n    // #pragma omp critical\n    for (size_t k = 0; k < ncomp; k++) {\n      for (size_t l = 0; l < ncomp; l++) {\n        A.insert(position + k, position + l) = int_Z(k, l);\n        A_noint.insert(position + k, position + l) = Z(k, l);\n      }\n    }\n    b.segment<6>(position) = -int_Z * Q3;\n    Q3_vec.segment<6>(position) = Q3;\n  }\n  // t2 = omp_get_wtime();\n  // std::cout << \" /* block2 */ \" << t2 - t1 << '\\n';\n\n  // t1 = omp_get_wtime();\n  Matrix K = gradient.transpose() * A * gradient;\n  Vector F = gradient.transpose() * b;\n  for (auto const fixed_dof : fixed_dofs) {\n    auto const diagonal_entry = K.coeff(fixed_dof, fixed_dof); // TODO //\n    F(fixed_dof) = 0.0;\n    for (int i = 0; i < K.rows(); i++) {\n      for (int j = 0; j < K.cols(); j++) {\n        K.coeffRef(fixed_dof, j) = 0.0;\n        K.coeffRef(i, fixed_dof) = 0.0; // TODO K.row(i)=0;\n      }\n    }\n    K.coeffRef(fixed_dof, fixed_dof) = diagonal_entry;\n  }\n  // if (b.norm() > 0)\n  auto U_tilde = K.llt().solve(F); // TODO: is this ok?\n  // else {\n  //   U_tilde = F;\n  // }\n  //   t2 = omp_get_wtime();\n  //   std::cout << \" /* block3 */ \" << t2 - t1 << '\\n';\n\n  // t1 = omp_get_wtime();\n  auto E_tilde = gradient * U_tilde;\n  auto sigma = A_noint * (E_tilde + Q3_vec);\n  space_mode = E_tilde / int_alpha_d_alpha - inv_hooke_full * sigma;\n  // t2 = omp_get_wtime();\n  // std::cout << \" /* block4 */ \" << t2 - t1 << '\\n';\n\n  // t1 = omp_get_wtime();\n  output = mxCreateDoubleMatrix(ngp * ncomp, 1, mxREAL);\n  Eigen::Map<Matrix>(mxGetPr(output), ngp * ncomp, 1) = space_mode;\n  // t2 = omp_get_wtime();\n  // std::cout << \" /* block5 */ \" << t2 - t1 << '\\n';\n\n  return;\n}\n\n// mxArray *cpp_to_MexArray(const std::vector<double> &v) {\n//   mxArray *mx = mxCreateDoubleMatrix(1, v.size(), mxREAL);\n//   std::copy(v.begin(), v.end(), mxGetPr(mx));\n//\n//   return mx;\n// }\n", "meta": {"hexsha": "b436bf008b551615a103edf6ac11e37d7b480019", "size": 5344, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "matlab/matlab_mex/src_mex/semi_cleaned_version/mex_functions/src/compute_stress_space_mode/compute_stress_space_mode.cpp", "max_stars_repo_name": "shadialameddin/numerical_tools_and_friends", "max_stars_repo_head_hexsha": "cc9f10f58886ee286ed89080e38ebd303d3c72a5", "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": "matlab/matlab_mex/src_mex/semi_cleaned_version/mex_functions/src/compute_stress_space_mode/compute_stress_space_mode.cpp", "max_issues_repo_name": "shadialameddin/numerical_tools_and_friends", "max_issues_repo_head_hexsha": "cc9f10f58886ee286ed89080e38ebd303d3c72a5", "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": "matlab/matlab_mex/src_mex/semi_cleaned_version/mex_functions/src/compute_stress_space_mode/compute_stress_space_mode.cpp", "max_forks_repo_name": "shadialameddin/numerical_tools_and_friends", "max_forks_repo_head_hexsha": "cc9f10f58886ee286ed89080e38ebd303d3c72a5", "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.0382165605, "max_line_length": 78, "alphanum_fraction": 0.6285553892, "num_tokens": 1723, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528132451417, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.4690914940612441}}
{"text": "\n#include <iostream>\n#include <string>\n#include <vector>\n#include <valarray>\n\n#include <thread>\n\n#include <Eigen/Core>\n#include <Eigen/LU>\n#include <Eigen/Dense>\n\n#include <stdio.h>  \n\n#include \"refine_variational.h\"\n\nusing std::cout;\nusing std::endl;\nusing std::vector;\n\n\nnamespace OFC\n{\n  \n  VarRefClass::VarRefClass(const float * im_ao_in, const float * im_ao_dx_in, const float * im_ao_dy_in, \n                            const float * im_bo_in, const float * im_bo_dx_in, const float * im_bo_dy_in,\n                           const camparam* cpt_in,const camparam* cpo_in,const optparam* op_in, float *flowout) \n  : cpt(cpt_in), cpo(cpo_in), op(op_in)    \n{  \n\n  // initialize parameters\n  tvparams.alpha = op->tv_alpha;\n  tvparams.beta = 0.0f;  // for matching term, not needed for us\n  tvparams.gamma = op->tv_gamma; \n  tvparams.delta = op->tv_delta;\n  tvparams.n_inner_iteration = op->tv_innerit * (cpt->curr_lv+1);\n  tvparams.n_solver_iteration = op->tv_solverit;//5;\n  tvparams.sor_omega = op->tv_sor;  \n  \n  tvparams.tmp_quarter_alpha = 0.25f*tvparams.alpha;\n  tvparams.tmp_half_gamma_over3 = tvparams.gamma*0.5f/3.0f;\n  tvparams.tmp_half_delta_over3 = tvparams.delta*0.5f/3.0f;\n  tvparams.tmp_half_beta = tvparams.beta*0.5f;\n  \n  float deriv_filter[3] = {0.0f, -8.0f/12.0f, 1.0f/12.0f};\n  deriv = convolution_new(2, deriv_filter, 0);\n  float deriv_filter_flow[2] = {0.0f, -0.5f};\n  deriv_flow = convolution_new(1, deriv_filter_flow, 0);  \n  \n  // copy flow initialization into FV structs\n  #if (SELECTMODE==1)\n  static int noparam = 2; // Optical flow\n  #else\n  static int noparam = 1; // Only horizontal displacements for stereo depth\n  #endif\n  std::vector<image_t*> flow_sep(noparam);  \n\n  for (int i = 0; i < noparam; ++i )\n    flow_sep[i] = image_new(cpt->width,cpt->height);\n  \n  for (int iy = 0; iy < cpt->height; ++iy)\n    for (int ix = 0; ix < cpt->width; ++ix)\n    {\n      int i  = iy * cpt->width          + ix;\n      int is = iy * flow_sep[0]->stride + ix;\n      for (int j = 0; j < noparam; ++j)\n        flow_sep[j]->c1[is] = flowout[i*noparam + j];\n    }\n\n  // copy image data into FV structs\n  #if (SELECTCHANNEL==1 | SELECTCHANNEL==2)    \n  image_t * im_ao, *im_bo;\n  im_ao = image_new(cpt->width,cpt->height);\n  im_bo = image_new(cpt->width,cpt->height);\n  #else\n  color_image_t * im_ao, *im_bo;\n  im_ao = color_image_new(cpt->width,cpt->height);\n  im_bo = color_image_new(cpt->width,cpt->height);\n  #endif\n      \n  copyimage(im_ao_in, im_ao);\n  copyimage(im_bo_in, im_bo);  \n  \n  // Call solver\n  #if (SELECTMODE==1)\n  RefLevelOF(flow_sep[0], flow_sep[1], im_ao, im_bo);\n  #else\n  RefLevelDE(flow_sep[0], im_ao, im_bo);\n  #endif  \n  \n  // Copy flow result back\n  for (int iy = 0; iy < cpt->height; ++iy)\n    for (int ix = 0; ix < cpt->width; ++ix)\n    {\n      int i  = iy * cpt->width          + ix;\n      int is = iy * flow_sep[0]->stride + ix;\n      for (int j = 0; j < noparam; ++j)\n        flowout[i*noparam + j] = flow_sep[j]->c1[is];\n    }\n\n  // free FV structs\n  for (int i = 0; i < noparam; ++i )\n    image_delete(flow_sep[i]);\n  \n  convolution_delete(deriv);\n  convolution_delete(deriv_flow);\n\n  \n  #if (SELECTCHANNEL==1 | SELECTCHANNEL==2)\n  image_delete(im_ao); \n  image_delete(im_bo);\n  #else\n  color_image_delete(im_ao); \n  color_image_delete(im_bo);\n  #endif\n}\n\n\n#if (SELECTCHANNEL==1 | SELECTCHANNEL==2)    \nvoid VarRefClass::copyimage(const float* img, image_t * img_t)\n#else\nvoid VarRefClass::copyimage(const float* img, color_image_t * img_t)\n#endif\n{\n  #if (SELECTCHANNEL==1 | SELECTCHANNEL==2)    \n  const float * img_st = img +     (cpt->tmp_w + 1 ) * (cpt->imgpadding); // remove image padding, start at first valid pixel\n  #else\n  const float * img_st = img + 3 * (cpt->tmp_w + 1 ) * (cpt->imgpadding); \n  #endif\n    \n  for (int yi = 0; yi < cpt->height; ++yi)\n  {\n    for (int xi = 0; xi < cpt->width; ++xi, ++img_st)\n    {\n      int i    = yi*img_t->stride+ xi;\n      \n      img_t->c1[i] =  (*img_st);\n      #if (SELECTCHANNEL==3)    \n      ++img_st; img_t->c2[i] =  (*img_st);\n      ++img_st; img_t->c3[i] =  (*img_st);\n      #endif\n    }\n    #if (SELECTCHANNEL==1 | SELECTCHANNEL==2)\n    img_st +=     2 * cpt->imgpadding;\n    #else\n    img_st += 3 * 2 * cpt->imgpadding;\n    #endif\n  }\n}\n \n\n#if (SELECTCHANNEL==1 | SELECTCHANNEL==2)\nvoid VarRefClass::RefLevelOF(image_t *wx, image_t *wy, const image_t *im1, const image_t *im2)\n#else\nvoid VarRefClass::RefLevelOF(image_t *wx, image_t *wy, const color_image_t *im1, const color_image_t *im2)\n#endif\n{\n    int i_inner_iteration;\n    int width  = wx->width;\n    int height = wx->height;\n    int stride = wx->stride;\n\n\n    image_t *du = image_new(width,height), *dv = image_new(width,height), // the flow increment\n      *mask = image_new(width,height), // mask containing 0 if a point goes outside image boundary, 1 otherwise\n      *smooth_horiz = image_new(width,height), *smooth_vert = image_new(width,height), // horiz: (i,j) contains the diffusivity coeff. from (i,j) to (i+1,j) \n      *uu = image_new(width,height), *vv = image_new(width,height), // flow plus flow increment\n      *a11 = image_new(width,height), *a12 = image_new(width,height), *a22 = image_new(width,height), // system matrix A of Ax=b for each pixel\n      *b1 = image_new(width,height), *b2 = image_new(width,height); // system matrix b of Ax=b for each pixel  \n      \n    #if (SELECTCHANNEL==1 | SELECTCHANNEL==2)  // use single band image\n    image_t *w_im2 = image_new(width,height), // warped second image\n        *Ix = image_new(width,height), *Iy = image_new(width,height), *Iz = image_new(width,height), // first order derivatives\n        *Ixx = image_new(width,height), *Ixy = image_new(width,height), *Iyy = image_new(width,height), *Ixz = image_new(width,height), *Iyz = image_new(width,height); // second order derivatives\n    #else                                     // use RGB image\n    color_image_t *w_im2 = color_image_new(width,height), // warped second image\n        *Ix = color_image_new(width,height), *Iy = color_image_new(width,height), *Iz = color_image_new(width,height), // first order derivatives\n        *Ixx = color_image_new(width,height), *Ixy = color_image_new(width,height), *Iyy = color_image_new(width,height), *Ixz = color_image_new(width,height), *Iyz = color_image_new(width,height); // second order derivatives\n    #endif\n                \n    // warp second image\n    image_warp(w_im2, mask, im2, wx, wy);\n    // compute derivatives\n    get_derivatives(im1, w_im2, deriv, Ix, Iy, Iz, Ixx, Ixy, Iyy, Ixz, Iyz);\n    // erase du and dv\n    image_erase(du);\n    image_erase(dv);\n    // initialize uu and vv\n    memcpy(uu->c1,wx->c1,wx->stride*wx->height*sizeof(float));\n    memcpy(vv->c1,wy->c1,wy->stride*wy->height*sizeof(float));\n    // inner fixed point iterations\n    for(i_inner_iteration = 0 ; i_inner_iteration < tvparams.n_inner_iteration ; i_inner_iteration++)\n    {\n        //  compute robust function and system\n        compute_smoothness(smooth_horiz, smooth_vert, uu, vv, deriv_flow, tvparams.tmp_quarter_alpha );\n        //compute_data_and_match(a11, a12, a22, b1, b2, mask, wx, wy, du, dv, uu, vv, Ix, Iy, Iz, Ixx, Ixy, Iyy, Ixz, Iyz, desc_weight, desc_flow_x, desc_flow_y, tvparams.tmp_half_delta_over3, tvparams.tmp_half_beta, tvparams.tmp_half_gamma_over3);\n        compute_data(a11, a12, a22, b1, b2, mask, wx, wy, du, dv, uu, vv, Ix, Iy, Iz, Ixx, Ixy, Iyy, Ixz, Iyz, tvparams.tmp_half_delta_over3, tvparams.tmp_half_beta, tvparams.tmp_half_gamma_over3);\n        sub_laplacian(b1, wx, smooth_horiz, smooth_vert);\n        sub_laplacian(b2, wy, smooth_horiz, smooth_vert);\n\n        // solve system\n        #ifdef WITH_OPENMP\n        sor_coupled_slow_but_readable(du, dv, a11, a12, a22, b1, b2, smooth_horiz, smooth_vert, tvparams.n_solver_iteration, tvparams.sor_omega); // slower but parallelized\n        #else\n        sor_coupled(du, dv, a11, a12, a22, b1, b2, smooth_horiz, smooth_vert, tvparams.n_solver_iteration, tvparams.sor_omega);\n        #endif\n        \n        // update flow plus flow increment\n        int i;\n        v4sf *uup = (v4sf*) uu->c1, *vvp = (v4sf*) vv->c1, *wxp = (v4sf*) wx->c1, *wyp = (v4sf*) wy->c1, *dup = (v4sf*) du->c1, *dvp = (v4sf*) dv->c1;\n        for( i=0 ; i<height*stride/4 ; i++)\n        {\n          (*uup) = (*wxp) + (*dup);\n          (*vvp) = (*wyp) + (*dvp);\n          uup+=1; vvp+=1; wxp+=1; wyp+=1;dup+=1;dvp+=1;\n        }\n        \n    }\n    // add flow increment to current flow\n    memcpy(wx->c1,uu->c1,uu->stride*uu->height*sizeof(float));\n    memcpy(wy->c1,vv->c1,vv->stride*vv->height*sizeof(float)); \n    \n    // free memory\n    image_delete(du); image_delete(dv);\n    image_delete(mask);\n    image_delete(smooth_horiz); image_delete(smooth_vert);\n    image_delete(uu); image_delete(vv);\n    image_delete(a11); image_delete(a12); image_delete(a22);\n    image_delete(b1); image_delete(b2);\n    \n    #if (SELECTCHANNEL==1 | SELECTCHANNEL==2)  // use single band image\n    image_delete(w_im2); \n    image_delete(Ix); image_delete(Iy); image_delete(Iz);\n    image_delete(Ixx); image_delete(Ixy); image_delete(Iyy); image_delete(Ixz); image_delete(Iyz);          \n    #else\n    color_image_delete(w_im2); \n    color_image_delete(Ix); color_image_delete(Iy); color_image_delete(Iz);\n    color_image_delete(Ixx); color_image_delete(Ixy); color_image_delete(Iyy); color_image_delete(Ixz); color_image_delete(Iyz);    \n    #endif\n      \n}\n\n\n#if (SELECTCHANNEL==1 | SELECTCHANNEL==2)\nvoid VarRefClass::RefLevelDE(image_t *wx, const image_t *im1, const image_t *im2)\n#else\nvoid VarRefClass::RefLevelDE(image_t *wx, const color_image_t *im1, const color_image_t *im2)\n#endif\n{\n    int i_inner_iteration;\n    int width  = wx->width;\n    int height = wx->height;\n    int stride = wx->stride;\n\n      image_t *du = image_new(width,height), *wy_dummy = image_new(width,height), // the flow increment\n        *mask = image_new(width,height), // mask containing 0 if a point goes outside image boundary, 1 otherwise\n        *smooth_horiz = image_new(width,height), *smooth_vert = image_new(width,height), // horiz: (i,j) contains the diffusivity coeff. from (i,j) to (i+1,j) \n        *uu = image_new(width,height), // flow plus flow increment\n        *a11 = image_new(width,height), // system matrix A of Ax=b for each pixel\n        *b1 = image_new(width,height); // system matrix b of Ax=b for each pixel  \n        \n      image_erase(wy_dummy);\n\t\n      #if (SELECTCHANNEL==1 | SELECTCHANNEL==2)  // use single band image\n      image_t *w_im2 = image_new(width,height), // warped second image\n          *Ix = image_new(width,height), *Iy = image_new(width,height), *Iz = image_new(width,height), // first order derivatives\n          *Ixx = image_new(width,height), *Ixy = image_new(width,height), *Iyy = image_new(width,height), *Ixz = image_new(width,height), *Iyz = image_new(width,height); // second order derivatives\n      #else                                     // use RGB image\n      color_image_t *w_im2 = color_image_new(width,height), // warped second image\n          *Ix = color_image_new(width,height), *Iy = color_image_new(width,height), *Iz = color_image_new(width,height), // first order derivatives\n          *Ixx = color_image_new(width,height), *Ixy = color_image_new(width,height), *Iyy = color_image_new(width,height), *Ixz = color_image_new(width,height), *Iyz = color_image_new(width,height); // second order derivatives\n      #endif\n          \n      // warp second image\n      image_warp(w_im2, mask, im2, wx, wy_dummy);\n      // compute derivatives\n      get_derivatives(im1, w_im2, deriv, Ix, Iy, Iz, Ixx, Ixy, Iyy, Ixz, Iyz);\n      // erase du and dv\n      image_erase(du);\n\n      // initialize uu and vv\n      memcpy(uu->c1,wx->c1,wx->stride*wx->height*sizeof(float));\n      \n      // inner fixed point iterations\n      for(i_inner_iteration = 0 ; i_inner_iteration < tvparams.n_inner_iteration ; i_inner_iteration++)\n      {\n          //  compute robust function and system\n          compute_smoothness(smooth_horiz, smooth_vert, uu, wy_dummy, deriv_flow, tvparams.tmp_quarter_alpha );\n          compute_data_DE(a11, b1, mask, wx, du, uu, Ix, Iy, Iz, Ixx, Ixy, Iyy, Ixz, Iyz, tvparams.tmp_half_delta_over3, tvparams.tmp_half_beta, tvparams.tmp_half_gamma_over3);\n          sub_laplacian(b1, wx, smooth_horiz, smooth_vert);\n          \n          // solve system\n          sor_coupled_slow_but_readable_DE(du, a11, b1, smooth_horiz, smooth_vert, tvparams.n_solver_iteration, tvparams.sor_omega);\n          \n          // update flow plus flow increment\n          int i;\n          v4sf *uup = (v4sf*) uu->c1, *wxp = (v4sf*) wx->c1, *dup = (v4sf*) du->c1;\n          \n          if(cpt->camlr==0)  // check if right or left camera, needed to truncate values above/below zero\n          {\n            for( i=0 ; i<height*stride/4 ; i++)\n            {\n                (*uup) = __builtin_ia32_minps(   (*wxp) + (*dup)   ,  op->zero);\n                uup+=1; wxp+=1; dup+=1;\n            }\n          }\n          else\n          {\n            for( i=0 ; i<height*stride/4 ; i++)\n            {\n                (*uup) = __builtin_ia32_maxps(   (*wxp) + (*dup)   ,  op->zero);\n                uup+=1; wxp+=1; dup+=1;\n            }\n          }\n      }\n      // add flow increment to current flow\n      memcpy(wx->c1,uu->c1,uu->stride*uu->height*sizeof(float));\n\n      // free memory\n      image_delete(du); image_delete(wy_dummy);\n      image_delete(mask);\n      image_delete(smooth_horiz); image_delete(smooth_vert);\n      image_delete(uu); \n      image_delete(a11);\n      image_delete(b1); \n      \n      #if (SELECTCHANNEL==1 | SELECTCHANNEL==2)\n      image_delete(w_im2); \n      image_delete(Ix); image_delete(Iy); image_delete(Iz);\n      image_delete(Ixx); image_delete(Ixy); image_delete(Iyy); image_delete(Ixz); image_delete(Iyz);          \n      #else\n      color_image_delete(w_im2); \n      color_image_delete(Ix); color_image_delete(Iy); color_image_delete(Iz);\n      color_image_delete(Ixx); color_image_delete(Ixy); color_image_delete(Iyy); color_image_delete(Ixz); color_image_delete(Iyz);    \n      #endif\n}\n\n\nVarRefClass::~VarRefClass()\n{\n \n}\n\n}", "meta": {"hexsha": "8ab62bcc0ffa561dac2529f1cb902da77967b8bf", "size": 14130, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "of_dis/refine_variational.cpp", "max_stars_repo_name": "beaupreda/IMOT_OpticalFlow_Edges", "max_stars_repo_head_hexsha": "633b8fec2c2a4525d1e62d385e553789d56f61f9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2018-01-31T13:32:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-03T16:35:29.000Z", "max_issues_repo_path": "of_dis/refine_variational.cpp", "max_issues_repo_name": "beaupreda/IMOT_OpticalFlow_Edges", "max_issues_repo_head_hexsha": "633b8fec2c2a4525d1e62d385e553789d56f61f9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-09-14T11:02:37.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-29T23:28:48.000Z", "max_forks_repo_path": "of_dis/refine_variational.cpp", "max_forks_repo_name": "beaupreda/IMOT_OpticalFlow_Edges", "max_forks_repo_head_hexsha": "633b8fec2c2a4525d1e62d385e553789d56f61f9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-04-01T12:20:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-06T03:42:54.000Z", "avg_line_length": 41.0755813953, "max_line_length": 248, "alphanum_fraction": 0.6355980184, "num_tokens": 4222, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.851952809486198, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.46909149199154204}}
{"text": "#include <graphene/singularity/ncd_aware_rank.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\nusing namespace boost;\nusing namespace boost::numeric::ublas;\nusing namespace singularity;\n\nstd::shared_ptr<vector_t> ncd_aware_rank::process(\n        const matrix_t& outlink_matrix\n) {\n    sparce_vector_t v = matrix_tools::calculate_correction_vector(outlink_matrix);\n    Graph g = create_graph(outlink_matrix);\n    scan scan(parameters.clustering_e, parameters.clustering_m);\n    scan.process(g);\n    std::shared_ptr<matrix_t> ms = create_interlevel_matrix_s(g);\n    std::shared_ptr<matrix_t> ml = create_interlevel_matrix_l(g, outlink_matrix);\n    \n    return calculate_ncd_aware_rank(outlink_matrix, v, *ms, *ml);\n}\n\nstd::shared_ptr<vector_t> ncd_aware_rank::iterate(\n        const matrix_t& outlink_matrix, \n        const sparce_vector_t& outlink_vector, \n        const matrix_t& interlevel_matrix_s, \n        const matrix_t& interlevel_matrix_l, \n        const vector_t& previous,\n        const vector_t& teleportation\n) {\n    unsigned int num_accounts = outlink_matrix.size2();\n    vector_t tmp(interlevel_matrix_l.size1(), 0); \n    matrix_tools::prod(tmp, interlevel_matrix_l, previous, parameters.num_threads);\n    \n    vector_t tmp2(interlevel_matrix_s.size1(), 0);\n    std::shared_ptr<vector_t> next(new vector_t(outlink_matrix.size1(), 0));\n    \n    matrix_tools::prod(*next, outlink_matrix, previous, parameters.num_threads);\n    matrix_tools::prod(tmp2, interlevel_matrix_s, tmp, parameters.num_threads);\n    \n    *next += tmp2;\n    \n    vector_t correction_vector(num_accounts, inner_prod(outlink_vector, previous));\n    \n    *next += correction_vector;\n    *next += teleportation;\n    \n    return next;\n}\n\nstd::shared_ptr<vector_t> ncd_aware_rank::calculate_ncd_aware_rank(\n        const matrix_t& outlink_matrix, \n        const sparce_vector_t& outlink_vector, \n        const matrix_t& interlevel_matrix_s, \n        const matrix_t& interlevel_matrix_l\n) {\n    unsigned int num_accounts = outlink_matrix.size2();\n    double initialValue = 1.0/num_accounts;\n    std::shared_ptr<vector_t> next;\n    std::shared_ptr<vector_t> previous(new vector_t(num_accounts, initialValue));\n    vector_t teleportation = (*previous) * (1.0 - parameters.outlink_weight - parameters.interlevel_weight) ;\n    \n    matrix_t outlink_matrix_weighted = outlink_matrix * parameters.outlink_weight;\n    matrix_t interlevel_matrix_s_weighted = interlevel_matrix_s * parameters.interlevel_weight;\n    sparce_vector_t outlink_vector_weighted = outlink_vector * parameters.outlink_weight;\n    \n    for (uint i = 0; i < MAX_ITERATIONS; i++) {\n        next  = iterate(outlink_matrix_weighted, outlink_vector_weighted, interlevel_matrix_s_weighted, interlevel_matrix_l, *previous, teleportation);\n        double norm = norm_1(*next - *previous);\n        if (norm <= precision) {\n            return next;\n        } else {\n            previous = next;\n        }\n    }\n    \n    return next;\n}\n\n\nstd::shared_ptr<matrix_t> ncd_aware_rank::create_interlevel_matrix_s(const Graph& g)\n{\n    Graph::vertex_iterator current, end;\n    \n    unsigned int num_clasters = get_property(g, graph_num_clusters);\n    \n    std::shared_ptr<matrix_t> S(new matrix_t(num_vertices(g), num_clasters));\n    \n    tie(current, end) = vertices(g);\n    \n    for ( ; current != end; current++) {\n        unsigned int index = get(vertex_index, g, *current);\n        unsigned int cluster_id = get(vertex_cluster_id, g, *current);\n        (*S)(index, cluster_id) = 1;\n    }\n\n    matrix_tools::normalize_columns(*S);\n    \n    return S;\n}\n\nstd::shared_ptr<matrix_t> ncd_aware_rank::create_interlevel_matrix_l(\n        const Graph& g, \n        const matrix_t& outlink_matrix\n) \n{\n    unsigned int num_clusters = get_property(g, graph_num_clusters);\n\n    Graph::vertex_iterator start, end;\n    \n    tie(start, end) = vertices(g);\n    \n    std::shared_ptr<matrix_t> L(new matrix_t(num_clusters, num_vertices(g)));\n    \n    for (matrix_t::const_iterator1 i = outlink_matrix.begin1(); i != outlink_matrix.end1(); i++)\n    {\n        Graph::vertex_descriptor vertex = start[i.index1()];\n        unsigned int clusterId = get(vertex_cluster_id, g, vertex);\n        (*L)(clusterId, i.index1()) = 1;\n        for (matrix_t::const_iterator2 j = i.begin(); j != i.end(); j++)\n        {\n            if (*j > 0) {\n                (*L)(clusterId, j.index2()) = 1;\n            }\n        }\n    }\n    \n    matrix_tools::normalize_columns(*L);\n    \n    return L;\n}\n\nGraph ncd_aware_rank::create_graph(const matrix_t& m)\n{\n    Graph g(m.size2());\n    \n    Graph::vertex_iterator v,ve;\n    \n    tie(v, ve) = vertices(g);\n\n    unsigned int id = 0;\n    \n    for (matrix_t::const_iterator1 i = m.begin1(); i != m.end1(); i++)\n    {\n        for (matrix_t::const_iterator2 j = i.begin(); j != i.end(); j++)\n        {\n            Graph::edge_descriptor edge;\n            bool added = false;\n            if (*j > 0) {\n                tie(edge, added) = add_edge(v[j.index1()], v[j.index2()], g);\n                if (added) {\n                    put(edge_index, g, edge, id++);\n                }\n            }\n        }\n    }\n    \n    return g;\n}\n", "meta": {"hexsha": "da1e3e770a7750b0281cdc20acbaead7e9c39045", "size": 5153, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libraries/singularity/singularity/ncd_aware_rank.cpp", "max_stars_repo_name": "petrkotegov/gravity-core", "max_stars_repo_head_hexsha": "52c9a96126739c33ee0681946e1d88c5be9a6190", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2018-05-25T17:58:46.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-23T21:13:26.000Z", "max_issues_repo_path": "libraries/singularity/singularity/ncd_aware_rank.cpp", "max_issues_repo_name": "petrkotegov/gravity-core", "max_issues_repo_head_hexsha": "52c9a96126739c33ee0681946e1d88c5be9a6190", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2018-05-25T19:44:30.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-03T11:35:27.000Z", "max_forks_repo_path": "libraries/singularity/singularity/ncd_aware_rank.cpp", "max_forks_repo_name": "petrkotegov/gravity-core", "max_forks_repo_head_hexsha": "52c9a96126739c33ee0681946e1d88c5be9a6190", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2018-05-30T04:37:46.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-05T14:47:34.000Z", "avg_line_length": 32.6139240506, "max_line_length": 151, "alphanum_fraction": 0.6522414128, "num_tokens": 1283, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.4690914837127334}}
{"text": "#pragma once\n#include \"bank/interfaces/DataSource/IDataObjectMetaInfo.h\"\n#include \"bank/DataSources//VirtualObjectMetaInfo.h\"\n#include \"constants.h\"\n#include <boost/date_time/gregorian/gregorian.hpp>\n#include <string>\n#include <vector>\n#include <ctime>\n\n\n#define AllowCreating virtual void makeVirtual() override {}\n\n\n\nnamespace DatabaseObjects {\n    using namespace boost::gregorian;\n    using namespace constants;\n    \n    using id = std::size_t;\n\n    struct DatabaseObject {\n        id object_id;\n        interfaces::DataSource::IDataObjectMetaInfo* meta_info;\n\n        virtual void makeVirtual() = 0;\n    };\n\n    struct Client: DatabaseObject {\n        std::string name;\n        std::string surname;\n        std::string address;\n        std::string passport;\n\n        AllowCreating;\n    };\n\n    struct BankAccount: DatabaseObject {\n        id client_id;\n        date opened_date;\n        double money;\n\n        virtual BankAccount* lookFuture(date futureMoment, date_duration periodInterval) = 0;\n\n    protected:\n        struct PaymentsResult {\n            date closest_payment;\n            date latest_payment;\n            size_t num_payments;\n        };\n\n        PaymentsResult getPaymentsBound(date today, date future_moment, date_duration period_interval) {\n            size_t num_payments = 0;\n\n            auto it = day_iterator(opened_date, period_interval.days());\n            while (today > *it) {\n                ++it;\n            }\n            date closest_payment = *it;\n            while (future_moment >= *it) {\n                ++it;\n                num_payments += 1;\n            }\n            date last_payment = *(--it);\n            return {closest_payment, last_payment, num_payments};\n        }\n    };\n\n    struct DebitAccount: BankAccount {\n        double interest_rate;\n        double accumulated;\n\n        virtual BankAccount* lookFuture(date future_moment, date_duration period_interval) override {\n            DebitAccount* object = new DebitAccount();\n            object->meta_info = new VirtualDataObjectMetaInfo();\n            object->opened_date = opened_date;\n            object->client_id = client_id;\n            object->interest_rate = interest_rate;\n\n            date today = day_clock::local_day();\n            auto res = getPaymentsBound(today, future_moment, period_interval);\n\n            double future_money = accumulated + money * (1 + interest_rate / daysPerYear * (res.closest_payment - today).days());\n            future_money *= pow(1 + interest_rate / daysPerYear * period_interval.days(), res.num_payments - 1);\n            object->money = future_money;\n\n            return object;\n        }\n\n        AllowCreating;\n    };\n\n    struct DepositAccount: BankAccount {\n        double interest_rate;\n        double accumulated;\n        date end_date;\n\n        virtual BankAccount* lookFuture(date future_moment, date_duration period_interval) override {\n            DepositAccount* object = new DepositAccount();\n            object->meta_info = new VirtualDataObjectMetaInfo();\n            object->opened_date = opened_date;\n            object->client_id = client_id;\n            object->interest_rate = interest_rate;\n\n            date today = day_clock::local_day();\n            future_moment = std::min(future_moment, end_date);\n            auto res = getPaymentsBound(today, future_moment, period_interval);\n\n            double future_money = accumulated + money * (1 + interest_rate / daysPerYear * (res.closest_payment - today).days());\n            future_money *= pow(1 + interest_rate / daysPerYear * period_interval.days(), res.num_payments - 1);\n            object->money = future_money;\n\n            return object;\n        }\n\n        AllowCreating;\n    };\n\n    struct CreditAccount: BankAccount {\n        double credit_limit;\n        double commission;\n\n        virtual BankAccount* lookFuture(date future_moment, date_duration period_interval) override {\n            CreditAccount* object = new CreditAccount();\n            object->meta_info = new VirtualDataObjectMetaInfo();\n            object->opened_date = opened_date;\n            object->client_id = client_id;\n            object->commission = commission;\n            object->credit_limit = credit_limit;\n            object->money = money;\n            return object;\n        }\n\n        AllowCreating;\n    };\n\n    struct Transaction: DatabaseObject {\n        time_t time;\n        double money;\n\n        virtual std::vector<id> getAssociatedAccounts() = 0;\n    };\n\n    struct PutTransaction: Transaction {\n        id bank_account_id;\n\n        virtual std::vector<id> getAssociatedAccounts() override {\n            return {bank_account_id};\n        }\n\n        AllowCreating;\n    };\n\n    struct SendTransaction: Transaction {\n        id from_bank_account_id;\n        id to_bank_account_id;\n\n        virtual std::vector<id> getAssociatedAccounts() override {\n            return {from_bank_account_id, to_bank_account_id};\n        }\n\n        AllowCreating;\n    };\n\n    struct GetTransaction: Transaction {\n        id bank_account_id;\n\n        virtual std::vector<id> getAssociatedAccounts() override {\n            return {bank_account_id};\n        }\n\n        AllowCreating;\n    };\n\n    struct DebitPercentsTransaction: Transaction {\n        date begin_period;\n        date end_period;\n        id bank_account_id;\n\n        virtual std::vector<id> getAssociatedAccounts() override {\n            return {bank_account_id};\n        }\n\n        AllowCreating;\n    };\n\n    struct DepositEndTransaction: Transaction {\n        id bank_account_id;\n\n        virtual std::vector<id> getAssociatedAccounts() override {\n            return {bank_account_id};\n        }\n\n        AllowCreating;\n    };\n\n    struct CreditPercentsTransaction: Transaction {\n        id bank_account_id;\n\n        virtual std::vector<id> getAssociatedAccounts() override {\n            return {bank_account_id};\n        }\n\n        AllowCreating;\n    };\n\n    struct CancelTransaction: Transaction {\n        id transaction_id;\n        id bank_account_id;\n        std::string reason;\n\n        virtual std::vector<id> getAssociatedAccounts() override {\n            return {bank_account_id};\n        }\n\n        AllowCreating;\n    };\n}", "meta": {"hexsha": "1c7787abcb73391f48572bf43343ee7ab851f891", "size": 6194, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/bank/DataObjects.hpp", "max_stars_repo_name": "nikhovas/bank", "max_stars_repo_head_hexsha": "cfdb6fd5ac820605e3afbf4c5675ad8534e36fbd", "max_stars_repo_licenses": ["MIT"], "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/bank/DataObjects.hpp", "max_issues_repo_name": "nikhovas/bank", "max_issues_repo_head_hexsha": "cfdb6fd5ac820605e3afbf4c5675ad8534e36fbd", "max_issues_repo_licenses": ["MIT"], "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/bank/DataObjects.hpp", "max_forks_repo_name": "nikhovas/bank", "max_forks_repo_head_hexsha": "cfdb6fd5ac820605e3afbf4c5675ad8534e36fbd", "max_forks_repo_licenses": ["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.5437788018, "max_line_length": 129, "alphanum_fraction": 0.6159186309, "num_tokens": 1231, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744939732856, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.46902483367638603}}
{"text": "\n//#include \"pipeline.hpp\"\n#include <boost/filesystem.hpp>\n#include <cstdlib>\n#include <iostream>\n#include <string>\n#include <iterator>\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Exact_predicates_exact_constructions_kernel.h>\n#include <CGAL/Surface_mesh.h>\n#include <CGAL/Polygon_mesh_processing/corefinement.h>\n#include <fstream>\n\n#include <CGAL/Mesh_triangulation_3.h>\n#include <CGAL/Mesh_complex_3_in_triangulation_3.h>\n#include <CGAL/Mesh_criteria_3.h>\n#include <CGAL/Polyhedral_complex_mesh_domain_3.h>\n#include <CGAL/make_mesh_3.h>\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K; /*inexact*/\ntypedef CGAL::Exact_predicates_exact_constructions_kernel EK;\ntypedef CGAL::Surface_mesh<K::Point_3> Mesh;\ntypedef CGAL::Surface_mesh<EK::Point_3> Mesh_exact;\n\nusing namespace std;\n\n//#include <CGAL/MP_Float.h>\n#include <CGAL/Polygon_mesh_processing/connected_components.h>\n#include <CGAL/Polygon_mesh_processing/remesh.h>\n#include <CGAL/Polygon_mesh_processing/border.h>\n\ntypedef K::Compare_dihedral_angle_3                    Compare_dihedral_angle_3;\n\ntypedef boost::graph_traits<Mesh>::halfedge_descriptor halfedge_descriptor;\ntypedef boost::graph_traits<Mesh>::edge_descriptor     edge_descriptor;\ntypedef boost::graph_traits<Mesh>::face_descriptor     face_descriptor;\n\n//typedef CGAL::Quotient<CGAL::MP_Float> mp_number;\n\ntemplate <typename G>\nstruct Constraint : public boost::put_get_helper<bool,Constraint<G> >\n{\n  typedef typename boost::graph_traits<G>::edge_descriptor edge_descriptor;\n  typedef boost::readable_property_map_tag      category;\n  typedef bool                                  value_type;\n  typedef bool                                  reference;\n  typedef edge_descriptor                       key_type;\n\n  Constraint()\n    :g_(NULL)\n  {}\n\n  Constraint(G& g, double bound) \n    : g_(&g), bound_(bound)\n  {}\n\n  bool operator[](edge_descriptor e) const\n  {\n    const G& g = *g_;\n    return compare_(g.point(source(e, g)),\n                    g.point(target(e, g)),\n                    g.point(target(next(halfedge(e, g), g), g)),\n                    g.point(target(next(opposite(halfedge(e, g), g), g), g)),\n                   bound_) == CGAL::SMALLER;\n  }\n  \n  const G* g_;\n  Compare_dihedral_angle_3 compare_;\n  double bound_;\n};\n\nstruct halfedge2edge\n{\n  halfedge2edge(const Mesh& m, vector<edge_descriptor>& edges)\n    : m_mesh(m), m_edges(edges)\n  {}\n  void operator()(const halfedge_descriptor& h) const\n  {\n    m_edges.push_back(edge(h, m_mesh));\n  }\n  const Mesh& m_mesh;\n  vector<edge_descriptor>& m_edges;\n};\n\nusing namespace CGAL ;\n\nusing namespace Polygon_mesh_processing;\n\ntemplate <typename PolygonMesh\n        , typename NamedParameters>\nsize_t make_vector_of_connected_components(\n    PolygonMesh& pmesh, \n    pair<int, int> pair_,\n    vector<PolygonMesh> &mesh_vec, \n    vector<pair<int, int> >  &pair_vec,\n    const NamedParameters& np\n)\n{ \n  typedef PolygonMesh PM;\n  typedef typename boost::graph_traits<PM>::face_descriptor face_descriptor;\n  using boost::choose_param;\n  using boost::get_param;\n                                                                            //FaceIndexMap\n  typedef typename GetFaceIndexMap<PM,  NamedParameters>::type FaceIndexMap;\n  FaceIndexMap fimap = choose_param(get_param(np, internal_np::face_index),\n                                    get_property_map(boost::face_index, pmesh));\n                                                                            //vector_property_map\n  boost::vector_property_map<size_t, FaceIndexMap> face_cc(fimap);\n  size_t num = connected_components(pmesh, face_cc, np);\n  vector< pair<size_t, size_t> > component_size(num);\n\n  for(size_t i=0; i < num; i++)\n    component_size[i] = make_pair(i,0);\n\n  BOOST_FOREACH(face_descriptor f, faces(pmesh))\n    ++component_size[face_cc[f]].second;\n                                                // we sort the range [0, num) by component size\n  sort(component_size.begin(), component_size.end(), PMP::internal::MoreSecond());\n  vector<size_t> cc_to_keep;\n  \n  for(size_t i=0; i<num; ++i) {\n      PM tmp_mesh = pmesh;\n      cc_to_keep.clear();\n      cc_to_keep.push_back( component_size[i].first );\n      keep_connected_components(tmp_mesh, cc_to_keep, face_cc, np);\n      mesh_vec.push_back(tmp_mesh);\n      pair_vec.push_back(pair_);\n  }\n  int indx=0;                                   // dbg verify written to mesh_vec\n  BOOST_FOREACH(PM cc_mesh , mesh_vec){\n      string filename =  \"data/blobby_vec\";\n      filename +=  to_string(indx) + \".off\";\n      ofstream outfile(filename);\n      outfile << cc_mesh;\n      outfile.close();\n      indx++;\n  }\n  return num;\n}\n\n\nint mkvec_cc(\n        vector<Mesh_exact> &patch_vec, \n        vector<pair<int, int> >  &pair_vec,\n        std::string out_dir\n            )\n{\n    boost::filesystem::path p (out_dir.c_str()); \n    vector<Mesh_exact> new_patch_vec;\n    vector<Mesh_exact> new_patch_vec2;\n    vector<pair<int, int> >  new_pair_vec;\n    const double bound = cos(0.75 * CGAL_PI);\n    \n    int idx =0;\n    BOOST_FOREACH(Mesh_exact pmesh, patch_vec){\n        make_vector_of_connected_components(pmesh, pair_vec.at(idx), new_patch_vec, new_pair_vec,\n                PMP::parameters::edge_is_constrained_map(Constraint<Mesh_exact>(pmesh, bound)) );\n        idx++;    // no match for epick  epeck\n    }\n    \n    for(int i=0; i< patch_vec.size() ;i++){\n        std::string filename = p.c_str();\n        filename += \"/patch_num_\" + to_string(i) + \".off\";\n        std::ofstream output(filename);\n        output << patch_vec.at(i);\n        output.close();\n    }\n\n    patch_vec.swap(new_patch_vec); /*new_patch_vec2*/\n    pair_vec.swap(new_pair_vec);\n    return patch_vec.size();\n}\n\n\n// int iso_remesh(Mesh &nmesh, unsigned int nb_iter, double target_edge_length){\n//     vector<edge_descriptor> border;\n//     PMP::border_halfedges(\n//                 faces(nmesh),\n//                 nmesh,\n//                 boost::make_function_output_iterator(halfedge2edge(nmesh, border))\n//                 );\n//     PMP::split_long_edges(border, target_edge_length, nmesh);\n//         \n//     PMP::isotropic_remeshing(\n//                 faces(nmesh),\n//                 target_edge_length,\n//                 nmesh,                                    //protect border, here\n//                 PMP::parameters::number_of_iterations(nb_iter).protect_constraints(true)\n//                 );   \n// }\n\n", "meta": {"hexsha": "10bd2c081b6730268478526f14fe0bc4c769fe2d", "size": 6440, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mesh_pipeline/Mesh_pipeline_exact_src/mkvec_cc_old.cpp", "max_stars_repo_name": "NH89/SOFA_mesh_partitioning_tools", "max_stars_repo_head_hexsha": "5d09155d5725aa000b1c994864cfc95f02dfc80c", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-03-23T22:39:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T13:00:32.000Z", "max_issues_repo_path": "mesh_pipeline/Mesh_pipeline_exact_src/mkvec_cc_old.cpp", "max_issues_repo_name": "csiro-robotics/SOFA_mesh_partitioning_tools", "max_issues_repo_head_hexsha": "5d09155d5725aa000b1c994864cfc95f02dfc80c", "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": "mesh_pipeline/Mesh_pipeline_exact_src/mkvec_cc_old.cpp", "max_forks_repo_name": "csiro-robotics/SOFA_mesh_partitioning_tools", "max_forks_repo_head_hexsha": "5d09155d5725aa000b1c994864cfc95f02dfc80c", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5416666667, "max_line_length": 97, "alphanum_fraction": 0.6430124224, "num_tokens": 1523, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744939732856, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4690248336763859}}
{"text": "#include <boost/config.hpp>\n#include <boost/random/random_device.hpp>\n#include <boost/random/uniform_int_distribution.hpp>\n#include <iostream>\n\nint main() {\n    static const std::string provider =\n#ifdef BOOST_WINDOWS\n        \"Microsoft Strong Cryptographic Provider\"\n#else\n        \"/dev/urandom\"\n#endif\n    ;\n\n    boost::random_device device(provider);\n    boost::random::uniform_int_distribution<unsigned short> random(1000);\n\n    for (unsigned int i = 0; i < 100; ++i) {\n        std::cerr << random(device) << '\\t';\n    }\n}\n", "meta": {"hexsha": "7b5762a8ba90719015aac9be343129da7b83e7ed", "size": 527, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Chapter12/03_random/main.cpp", "max_stars_repo_name": "apolukhin/boost-cookbook", "max_stars_repo_head_hexsha": "912e36f38b9b1da93b03ae7afd19fcec0900aa83", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 313.0, "max_stars_repo_stars_event_min_datetime": "2017-05-28T15:30:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T12:32:40.000Z", "max_issues_repo_path": "Chapter12/03_random/main.cpp", "max_issues_repo_name": "apolukhin/boost-cookbook", "max_issues_repo_head_hexsha": "912e36f38b9b1da93b03ae7afd19fcec0900aa83", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 15.0, "max_issues_repo_issues_event_min_datetime": "2021-12-07T06:46:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-31T07:55:32.000Z", "max_forks_repo_path": "Chapter12/03_random/main.cpp", "max_forks_repo_name": "apolukhin/boost-cookbook", "max_forks_repo_head_hexsha": "912e36f38b9b1da93b03ae7afd19fcec0900aa83", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 85.0, "max_forks_repo_forks_event_min_datetime": "2017-05-28T16:47:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T10:04:55.000Z", "avg_line_length": 23.9545454545, "max_line_length": 73, "alphanum_fraction": 0.6717267552, "num_tokens": 123, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744584140004, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.46902481327679185}}
{"text": "/******************************************************************************\n * Copyright 2017 Baidu Robotic Vision Authors. 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 \"feature_utils.h\"\n#include <Eigen/Dense>\n\nnamespace XP {\nnamespace warp {\n\nusing Eigen::Vector2f;\nusing Eigen::Vector3f;\nusing Eigen::Matrix2f;\nusing Eigen::Matrix3f;\n\n// Compute affine warp matrix A_ref_cur\n// The warping matrix is warping the ref patch (at level_ref) to the current frame (at pyr 0)\n//\u8f93\u5165\u5de6\u53f3\u76f8\u673a\u7c7b,\u5de6\u76f8\u673a\u50cf\u7d20\u5750\u6807,\u5f52\u4e00\u5316\u5750\u6807,\u4f30\u8ba1\u7684\u6df1\u5ea6,\u7279\u5f81\u70b9\u6240\u5728\u7684\u91d1\u5b57\u5854\u5c42,\u5916\u53c2\nbool getWarpMatrixAffine(const vio::cameras::CameraBase& cam_ref,\n                         const vio::cameras::CameraBase& cam_cur,\n                         const Vector2f& px_ref,  // distorted pixel at pyr0\n                         const Vector3f& f_ref,   // undist ray in unit plane\n                         const float depth_ref,\n                         const Matrix3f& R_cur_ref,\n                         const Vector3f& t_cur_ref,\n                         const int level_ref,\n                         Eigen::Matrix2f* A_cur_ref) {\n  CHECK_NOTNULL(A_cur_ref);\n  // TODO(mingyu): tune the *d_unit* size in pixel for different 1st order approximation\n  const int halfpatch_size = 5;\n  const Vector3f xyz_ref(f_ref * depth_ref);// \u7279\u5f81\u70b9\u5728\u5de6\u76f8\u673a\u5750\u6807\u4e2d\u7684\u4f4d\u7f6e\n  //\u8fd9\u4e2a\u662f\u4e00\u534a\u5757\u7684\u5927\u5c0f,\u5728\u4e0d\u540c\u7684\u91d1\u5b50\u5854\u5c42patch\u7684\u5927\u5c0f\u4e5f\u662f\u9700\u8981\u7f29\u653e\u7684\n  float d_unit = halfpatch_size * (1 << level_ref);\n  //\u8fd9\u91cc\u5728\u7b97\u4ee5px_ref\u4e3a\u539f\u70b9,uv\u7684\u65b9\u5411\n  Vector2f du_ref(px_ref + Vector2f(d_unit, 0));\n  Vector2f dv_ref(px_ref + Vector2f(0, d_unit));\n  Vector3f xyz_du_ref, xyz_dv_ref;\n  //\u53cd\u6295\u5f71\n  if (cam_ref.backProject(du_ref, &xyz_du_ref) && cam_ref.backProject(dv_ref, &xyz_dv_ref))\n  {\n    // Make sure the back project succeed for both du_ref & dv_ref\n    //\u521d\u59cb\u6df1\u5ea6\n    xyz_du_ref *= xyz_ref[2] / xyz_du_ref[2];\n    xyz_dv_ref *= xyz_ref[2] / xyz_dv_ref[2];\n    Vector2f px_cur, du_cur, dv_cur;\n      // \u5229\u7528\u5916\u53c2\u628a\u8fd9\u4e09\u70b9\u53d8\u6362\u5230\u53f3\u76f8\u673a\u5750\u6807\u7cfb\u4e0b\n    if (vio::cameras::CameraBase::ProjectionStatus::Successful ==\n        cam_cur.project(R_cur_ref * xyz_ref + t_cur_ref, &px_cur) &&\n        vio::cameras::CameraBase::ProjectionStatus::Successful ==\n            cam_cur.project(R_cur_ref * xyz_du_ref + t_cur_ref, &du_cur) &&\n        vio::cameras::CameraBase::ProjectionStatus::Successful ==\n            cam_cur.project(R_cur_ref * xyz_dv_ref + t_cur_ref, &dv_cur)) {\n        //\u5982\u679c\u90fd\u6295\u5f71\u6210\u529f\u7684\u8bdd,\u8ba1\u7b97\u4eff\u5c04\u53d8\u6362(\u6bcf\u5217\u5c31\u662f\u67d0\u8f74\u53d8\u6362\u4ee5\u540e\u7684\u65b9\u5411)\n      A_cur_ref->col(0) = (du_cur - px_cur) / halfpatch_size;\n      A_cur_ref->col(1) = (dv_cur - px_cur) / halfpatch_size;\n      return true;\n    }\n  }\n  A_cur_ref->setIdentity();  // No warping\n  return false;\n}\n// \u627e\u5230\u5408\u9002\u91d1\u5b57\u5854\u5c42\n// Compute patch level in other image (based on pyramid level 0)\nint getBestSearchLevel(const Eigen::Matrix2f& A_cur_ref,\n                       const int max_level) {\n  int search_level = 0;\n  float D = A_cur_ref.determinant();\n  //\u884c\u5217\u5f0f\u5c0f\u4e8e3\u4e3a\u6b62\n  while (D > 3.f && search_level < max_level) {\n    ++search_level;\n    D *= 0.25;\n  }\n  return search_level;\n}\n\nnamespace {\n// Return value between 0 and 255\n// [NOTE] Does not check whether the x/y is within the border\ninline float interpolateMat_8u(const cv::Mat& mat, float u, float v) {\n  CHECK_EQ(mat.type(), CV_8U);\n  int x = floor(u);\n  int y = floor(v);\n  float subpix_x = u - x;\n  float subpix_y = v - y;\n\n  float w00 = (1.0f - subpix_x) * (1.0f - subpix_y);\n  float w01 = (1.0f - subpix_x) * subpix_y;\n  float w10 = subpix_x * (1.0f - subpix_y);\n  float w11 = 1.0f - w00 - w01 - w10;\n\n  const int stride = mat.step.p[0];\n  uint8_t* ptr = mat.data + y * stride + x;\n  return w00 * ptr[0] + w01 * ptr[stride] + w10 * ptr[1] + w11 * ptr[stride+1];\n}\n}  // namespace\n\n//\u5c06\u5de6\u76f8\u673a\u56fe\u50cf\u7279\u5f81\u70b9\u4e2d\u5fc3\u7684\u56fe\u50cf\u5757warp\u5230\u53f3\u76f8\u673a\u56fe\u50cf\u5750\u6807\u7cfb\u4e2d\n// Compute acc squared patch that is *warperd* from img_ref with A_cur_ref.\n//\u8f93\u5165\u4e4b\u524d\u5f97\u5230\u7684\u7c97\u7565\u7684\u4eff\u5c04\u77e9\u9635,\u5de6\u76f8\u673a\u7279\u5f81\u70b9\u6240\u5728\u6240\u5728\u91d1\u5b57\u5854\u56fe\u50cf,\u5de6\u7279\u5f81\u70b9\u50cf\u7d20\u5750\u6807,\u5de6\u7279\u5f81\u7684\u91d1\u5b57\u5854\u5c42\uff0c\u53f3\u76f8\u673a\u9700\u8981\u641c\u7d22\u7684\u91d1\u5b57\u5854\u5c42,\nbool warpAffine(const Eigen::Matrix2f& A_cur_ref,\n                const cv::Mat& img_ref,         // at pyramid level_ref\n                const Eigen::Vector2f& px_ref,  // at pyramid 0\n                const int level_ref,\n                const int level_cur,\n                const int halfpatch_size,\n                uint8_t* patch) {\n  const int patch_size = halfpatch_size * 2;\n  const Matrix2f A_ref_cur = A_cur_ref.inverse();\n  if (std::isnan(A_ref_cur(0, 0))) {\n    // TODO(mingyu): Use looser criteria for invalid affine warp?\n    //               I suspect A_ref_cur can barely hit NaN.\n    LOG(ERROR) << \"Invalid affine warp matrix (NaN)\";\n    return false;\n  }\n\n  // px_ref is at pyr0, img_ref is at level_ref pyr already\n  CHECK_NOTNULL(patch);\n  uint8_t* patch_ptr = patch;\n  const Vector2f px_ref_pyr = px_ref / (1<< level_ref);  // pixel at pyramid level_ref//\u53d8\u6362\u5230\u5bf9\u5e94\u7684\u91d1\u5b57\u5854\u5c42\u5750\u6807\u4e0a\n  for (int y = 0; y < patch_size; ++y)\n  {\n    for (int x = 0; x < patch_size; ++x, ++patch_ptr)// // \u4ee5\u5efa\u7acbpatch\u5750\u6807\u7cfb\n    {\n      Vector2f px_patch(x - halfpatch_size, y - halfpatch_size);\n      px_patch *= (1 << level_cur);//\u7f29\u653e\n      const Vector2f px(A_ref_cur * px_patch + px_ref_pyr);  // pixel at pyramid level_ref\n      if (px[0] < 0 || px[1] < 0 || px[0] >= img_ref.cols - 1 || px[1] >= img_ref.rows - 1) {\n        *patch_ptr = 0;\n      } else {\n        *patch_ptr = interpolateMat_8u(img_ref, px[0], px[1]);//\u5c06\u5de6\u76f8\u673a\u56fe\u50cfwarp\u5230\u53f3\u76f8\u673a\u56fe\u50cf\u5750\u6807\u7cfb\u4e2d\n      }\n    }\n  }\n  return true;\n}\n\n}  // namespace warp\n}  // namespace XP\n", "meta": {"hexsha": "785d51cb696abb5edc391483629bf264142309cc", "size": 5850, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Frontend/feature_utils_warp.cc", "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/feature_utils_warp.cc", "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/feature_utils_warp.cc", "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": 39.0, "max_line_length": 101, "alphanum_fraction": 0.6314529915, "num_tokens": 1900, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744584140004, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.46902481327679185}}
{"text": "/*\n * Copyright 2018, LAAS-CNRS\n * Author: Steve Tonneau\n */\n\n#ifndef BEZIER_COM_TRAJ_LIB_UTILS_H\n#define BEZIER_COM_TRAJ_LIB_UTILS_H\n\n#include <hpp/bezier-com-traj/local_config.hh>\n#include <hpp/bezier-com-traj/definitions.hh>\n#include <hpp/bezier-com-traj/flags.hh>\n\n#include <Eigen/Dense>\n\n#include <vector>\n\nnamespace bezier_com_traj\n{\n\ntemplate<typename T> T initwp();\nwaypoint_t initwp(const size_t rows, const size_t cols);\nwaypoint_t operator+(const waypoint_t& w1, const waypoint_t& w2);\nwaypoint_t operator-(const waypoint_t& w1, const waypoint_t& w2);\nwaypoint_t operator*(const double k, const waypoint_t& w);\nwaypoint_t operator*(const waypoint_t& w,const double k);\n\nstruct waypoint_t{\n    MatrixXX first;\n    VectorX second;\n\n    waypoint_t():first(MatrixXX()),second(VectorX())\n    {}\n\n    waypoint_t(MatrixXX A,VectorX b):first(A),second(b)\n    {}\n\n    static waypoint_t Zero(size_t dim){\n        return initwp(dim,dim);\n    }\n\n};\n\n\n/**\n * @brief Compute the Bernstein polynoms for a given degree\n * @param degree required degree\n * @return the bernstein polynoms\n */\nBEZIER_COM_TRAJ_DLLAPI std::vector<spline::Bern<double> > ComputeBersteinPolynoms(const unsigned int degree);\n\n\n/**\n * @brief given the constraints of the problem, and a set of waypoints, return\n * the bezier curve corresponding\n * @param pData problem data\n * @param T total trajectory time\n * @param pis list of waypoints\n * @return the bezier curve\n */\ntemplate<typename Bezier, typename Point>\nBEZIER_COM_TRAJ_DLLAPI Bezier computeBezierCurve(const ConstraintFlag& flag, const double T,\n                                                   const std::vector<Point>& pi, const Point& x);\n\n/**\n * @brief computeDiscretizedTime build an array of discretized points in time,\n * such that there is the same number of point in each phase. Doesn't contain t=0,\n * is of size pointsPerPhase*phaseTimings.size()\n * @param phaseTimings\n * @param pointsPerPhase\n * @return\n */\nT_time computeDiscretizedTimeFixed(const VectorX& phaseTimings, const unsigned int pointsPerPhase );\n\n/**\n * @brief computeDiscretizedTime build an array of discretized points in time,\n * given the timestep. Doesn't contain t=0,\n * is of size pointsPerPhase*phaseTimings.size()\n * @param phaseTimings\n * @param timeStep\n * @return */\nT_time computeDiscretizedTime(const VectorX& phaseTimings, const double timeStep);\n\n\n/**\n * @brief write a polytope describe by A x <= b linear constraints in\n * a given filename\n * @return the bernstein polynoms\n */\nvoid printQHullFile(const std::pair<MatrixXX, VectorX>& Ab,VectorX intPoint,\n                    const std::string& fileName,bool clipZ = false);\n\n/**\n * @brief skew symmetric matrix\n */\nBEZIER_COM_TRAJ_DLLAPI Matrix3 skew(point_t_tC x);\n\n/**\n * @brief normalize inequality constraints\n */\nint Normalize(Ref_matrixXX A, Ref_vectorX b);\n\n\n\n} // end namespace bezier_com_traj\n\ntemplate<typename Bezier, typename Point>\nBezier bezier_com_traj::computeBezierCurve(const ConstraintFlag& flag, const double T,\n                                           const std::vector<Point>& pi, const Point& x)\n{\n    std::vector<Point> wps;\n    size_t i = 0;\n    if(flag & INIT_POS ){\n        wps.push_back(pi[i]);\n        i++;\n        if(flag & INIT_VEL){\n            wps.push_back(pi[i]);\n            i++;\n            if(flag & INIT_ACC){\n                wps.push_back(pi[i]);\n                i++;\n            }\n        }\n    }\n    wps.push_back(x);\n    i++;\n    if(flag & (END_VEL) && !(flag & (END_POS) ))\n    {\n        wps.push_back(x);\n        i++;\n    }\n    else\n    {\n        if(flag & END_ACC){\n            assert(flag & END_VEL && \"You cannot constrain final acceleration if final velocity is not constrained.\");\n            wps.push_back(pi[i]);\n            i++;\n        }\n        if(flag & END_VEL){\n            assert(flag & END_POS && \"You cannot constrain final velocity if final position is not constrained.\");\n            wps.push_back(pi[i]);\n            i++;\n        }\n        if(flag & END_POS){\n            wps.push_back(pi[i]);\n            i++;\n        }\n    }\n    return Bezier (wps.begin(), wps.end(),T);\n}\n\n\n\n\n#endif\n", "meta": {"hexsha": "bff1fc0c2558e7287a1c10824af5c043c03c9863", "size": 4128, "ext": "hh", "lang": "C++", "max_stars_repo_path": "include/hpp/bezier-com-traj/utils.hh", "max_stars_repo_name": "jmirabel/hpp-bezier-com-traj", "max_stars_repo_head_hexsha": "b6484f4538ee774c815133fae919784e5df08674", "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/hpp/bezier-com-traj/utils.hh", "max_issues_repo_name": "jmirabel/hpp-bezier-com-traj", "max_issues_repo_head_hexsha": "b6484f4538ee774c815133fae919784e5df08674", "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/hpp/bezier-com-traj/utils.hh", "max_forks_repo_name": "jmirabel/hpp-bezier-com-traj", "max_forks_repo_head_hexsha": "b6484f4538ee774c815133fae919784e5df08674", "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.6322580645, "max_line_length": 118, "alphanum_fraction": 0.6511627907, "num_tokens": 1005, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872243177518, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.4690216324502086}}
{"text": "/* boost random/uniform_on_sphere.hpp header file\n *\n * Copyright Jens Maurer 2000-2001\n * Permission to use, copy, modify, sell, and distribute this software\n * is hereby granted without fee provided that the above copyright notice\n * appears in all copies and that both that copyright notice and this\n * permission notice appear in supporting documentation,\n *\n * Jens Maurer makes no representations about the suitability of this\n * software for any purpose. It is provided \"as is\" without express or\n * implied warranty.\n *\n * See http://www.boost.org for most recent version including documentation.\n *\n * $Id: uniform_on_sphere.hpp,v 1.9 2002/12/22 22:03:11 jmaurer Exp $\n *\n * Revision history\n *  2001-02-18  moved to individual header files\n */\n\n#ifndef BOOST_RANDOM_UNIFORM_ON_SPHERE_HPP\n#define BOOST_RANDOM_UNIFORM_ON_SPHERE_HPP\n\n#include <vector>\n#include <algorithm>     // std::transform\n#include <functional>    // std::bind2nd, std::divides\n#include <boost/random/normal_distribution.hpp>\n\nnamespace boost {\n\ntemplate<class UniformRandomNumberGenerator, class RealType = double,\n         class Cont = std::vector<RealType>,\n         class Adaptor = uniform_01<UniformRandomNumberGenerator, RealType> >\nclass uniform_on_sphere\n{\npublic:\n  typedef Adaptor adaptor_type;\n  typedef UniformRandomNumberGenerator base_type;\n  typedef Cont result_type;\n\n  explicit uniform_on_sphere(base_type & rng, int dim = 2)\n    : _rng(rng), _container(dim), _dim(dim) { }\n\n  // compiler-generated copy ctor and assignment operator are fine\n\n  adaptor_type& adaptor() { return _rng.adaptor(); }\n  base_type& base() const { return _rng.base(); }\n  void reset() { _rng.reset(); }\n\n  const result_type & operator()()\n  {\n    RealType sqsum = 0;\n    for(typename Cont::iterator it = _container.begin();\n        it != _container.end();\n        ++it) {\n      RealType val = _rng();\n      *it = val;\n      sqsum += val * val;\n    }\n#ifndef BOOST_NO_STDC_NAMESPACE\n    using std::sqrt;\n#endif\n    // for all i: result[i] /= sqrt(sqsum)\n    std::transform(_container.begin(), _container.end(), _container.begin(),\n                   std::bind2nd(std::divides<RealType>(), sqrt(sqsum)));\n    return _container;\n  }\n\n#ifndef BOOST_NO_OPERATORS_IN_NAMESPACE\n  friend bool operator==(const uniform_on_sphere& x, \n                         const uniform_on_sphere& y)\n  { return x._dim == y._dim && x._rng == y._rng; }\n\n#ifndef BOOST_NO_MEMBER_TEMPLATE_FRIENDS\n  template<class CharT, class Traits>\n  friend std::basic_ostream<CharT,Traits>&\n  operator<<(std::basic_ostream<CharT,Traits>& os, const uniform_on_sphere& sd)\n  {\n    os << sd._dim;\n    return os;\n  }\n\n  template<class CharT, class Traits>\n  friend std::basic_istream<CharT,Traits>&\n  operator>>(std::basic_istream<CharT,Traits>& is, uniform_on_sphere& sd)\n  {\n    is >> std::ws >> sd._dim;\n    sd._container.resize(sd._dim);\n    return is;\n  }\n#endif\n\n#else\n  // Use a member function\n  bool operator==(const uniform_on_sphere& rhs) const\n  { return _dim == rhs._dim && _rng == rhs._rng; }\n#endif\nprivate:\n  normal_distribution<base_type, RealType, Adaptor> _rng;\n  result_type _container;\n  int _dim;\n};\n\n} // namespace boost\n\n#endif // BOOST_RANDOM_UNIFORM_ON_SPHERE_HPP\n", "meta": {"hexsha": "1b2d1543874cb1170e55140679510a487f7d6377", "size": 3220, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/3rd party/boost/boost/random/uniform_on_sphere.hpp", "max_stars_repo_name": "OLR-xray/OLR-3.0", "max_stars_repo_head_hexsha": "b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2016-01-25T20:18:51.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-06T07:00:04.000Z", "max_issues_repo_path": "src/3rd party/boost/boost/random/uniform_on_sphere.hpp", "max_issues_repo_name": "OLR-xray/OLR-3.0", "max_issues_repo_head_hexsha": "b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/3rd party/boost/boost/random/uniform_on_sphere.hpp", "max_forks_repo_name": "OLR-xray/OLR-3.0", "max_forks_repo_head_hexsha": "b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-02-14T01:20:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-03T11:19:11.000Z", "avg_line_length": 30.0934579439, "max_line_length": 79, "alphanum_fraction": 0.702484472, "num_tokens": 810, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872243177518, "lm_q2_score": 0.6261241842048092, "lm_q1q2_score": 0.4690216272241972}}
{"text": "// Copyright (c) 2021 Marcus Valtonen \u00d6rnhag\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 <Eigen/Dense>\n#include <vector>\n#include <algorithm>\n#include \"get_valtonenornhag_arxiv_2021.hpp\"\n#include \"normalize2dpts.hpp\"\n#include \"radial.hpp\"\n#include \"relpose.hpp\"\n#include \"solver_frEfr.hpp\"\n\nnamespace DronePoseLib {\nnamespace ValtonenOrnhagArxiv2021 {\n    inline Eigen::Vector3d extract_translation(\n        const double f,\n        const double r,\n        const Eigen::Matrix3d &R1,\n        const Eigen::Matrix3d &R2,\n        const Eigen::Matrix2d &x1,\n        const Eigen::Matrix2d &x2);\n\n    std::vector<RelPose> get_frEfr(\n        const Eigen::MatrixXd &p1,\n        const Eigen::MatrixXd &p2,\n        const Eigen::Matrix3d &R1,\n        const Eigen::Matrix3d &R2,\n        const bool use_fast_solver\n    ) {\n        // This is a 4-point method\n        const int nbr_pts = 4;\n\n        // We expect inhomogenous input data, i.e. p1 and p2 are 2x3 matrices\n        assert(p1.rows() == 2);\n        assert(p2.rows() == 2);\n        assert(p1.cols() == nbr_pts);\n        assert(p2.cols() == nbr_pts);\n\n        // Compute normalization matrix\n        double scale1 = normalize2dpts(p1);\n        double scale2 = normalize2dpts(p2);\n        double scale = std::max(scale1, scale2);\n        Eigen::Vector3d s;\n        s << scale, scale, 1.0;\n        Eigen::DiagonalMatrix<double, 3> S = s.asDiagonal();\n\n        // Normalize data\n        Eigen::Matrix<double, 3, nbr_pts> x1;\n        Eigen::Matrix<double, 3, nbr_pts> x2;\n        x1 = p1.colwise().homogeneous();\n        x2 = p2.colwise().homogeneous();\n        x1 = S * x1;\n        x2 = S * x2;\n\n        Eigen::Matrix<double, 2, nbr_pts> x1t;\n        Eigen::Matrix<double, 2, nbr_pts> x2t;\n        x1t << x1.colwise().hnormalized();\n        x2t << x2.colwise().hnormalized();\n\n        // Compute relative rotation\n        Eigen::Matrix3d R = R2 * R1.transpose();\n\n        // Wrap input data to expected format\n        Eigen::VectorXd input(25);\n        input << Eigen::Map<Eigen::VectorXd>(x1t.data(), 8),\n                 Eigen::Map<Eigen::VectorXd>(x2t.data(), 8),\n                 Eigen::Map<Eigen::VectorXd>(R.data(), 9);\n\n        // Extract solution\n        Eigen::MatrixXcd sols = DronePoseLib::ValtonenOrnhagArxiv2021::solver_frEfr(input, use_fast_solver);\n\n        // Pre-processing: Remove complex-valued solutions\n        double thresh = 1e-12;\n        Eigen::ArrayXd real_sols(11);\n        real_sols = sols.imag().cwiseAbs().colwise().sum();\n        int nbr_real_sols = (real_sols <= thresh).count();\n\n        // Construct putative output\n        // Eigen::Vector3d t;\n        std::vector<RelPose> output;\n        RelPose relpose;\n        double f, r;\n        Eigen::Vector3d kinv;\n        Eigen::DiagonalMatrix<double, 3> Kinv;\n        Eigen::Matrix3d skew_t;\n\n        // Loop over real solutions\n        for (int i=0; i < real_sols.size(); i++) {\n            if (real_sols(i) < thresh) {\n                f = sols(0, i).real();\n                r = sols(1, i).real();\n\n                // Extract translation\n                relpose.t = extract_translation(f, r, R1, R2, x1t.leftCols<2>(), x2t.leftCols<2>());\n                relpose.f = f / scale;\n                relpose.r = r * std::pow(scale, 2);\n\n                // Compute fundamental matrix\n                kinv << 1.0 / relpose.f, 1.0 / relpose.f, 1.0;\n                Kinv = kinv.asDiagonal();\n                skew_t << 0, -relpose.t(2), relpose.t(1),\n                          relpose.t(2), 0, -relpose.t(0),\n                         -relpose.t(1), relpose.t(0), 0;\n                relpose.F = Kinv * skew_t * R * Kinv;\n\n                // Add\n                output.push_back(relpose);\n            }\n        }\n\n        return output;\n    }\n\n    inline Eigen::Vector3d extract_translation(\n        const double f,\n        const double r,\n        const Eigen::Matrix3d &R1,\n        const Eigen::Matrix3d &R2,\n        const Eigen::Matrix2d &x1,\n        const Eigen::Matrix2d &x2\n    ) {\n        Eigen::Vector3d fmat;\n        fmat << 1.0 / f, 1.0 / f, 1.0;\n        Eigen::DiagonalMatrix<double, 3> Kinv = fmat.asDiagonal();\n\n        // Transform points\n        Eigen::Matrix<double, 3, 2> y1, y2;\n        y1 = R1.transpose() * Kinv * DronePoseLib::radialundistort(x1, r).colwise().homogeneous();\n        y2 = R2.transpose() * Kinv * DronePoseLib::radialundistort(x2, r).colwise().homogeneous();\n\n        // Extract translation\n        Eigen::Vector3d t;\n        t = R2 * y1.col(0).cross(y2.col(0)).cross(y1.col(1).cross(y2.col(1)));\n        return t;\n    }\n}  // namespace ValtonenOrnhagArxiv2021\n}  // namespace DronePoseLib\n", "meta": {"hexsha": "4e8187b6db41a7e55ed98f4deddc2fc0832e89a6", "size": 5675, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/solvers/valtonenornhag_arxiv_2021/frEfr/get_frEfr.cpp", "max_stars_repo_name": "marcusvaltonen/DronePoseLib", "max_stars_repo_head_hexsha": "0fb7e85accb41eb0d3c6601830b61a2c8be36232", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2021-03-17T09:35:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T13:41:20.000Z", "max_issues_repo_path": "src/solvers/valtonenornhag_arxiv_2021/frEfr/get_frEfr.cpp", "max_issues_repo_name": "marcusvaltonen/DronePoseLib", "max_issues_repo_head_hexsha": "0fb7e85accb41eb0d3c6601830b61a2c8be36232", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-04-23T17:25:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-27T11:21:44.000Z", "max_forks_repo_path": "src/solvers/valtonenornhag_arxiv_2021/frEfr/get_frEfr.cpp", "max_forks_repo_name": "marcusvaltonen/DronePoseLib", "max_forks_repo_head_hexsha": "0fb7e85accb41eb0d3c6601830b61a2c8be36232", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-04-23T17:40:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-17T19:04:59.000Z", "avg_line_length": 36.6129032258, "max_line_length": 108, "alphanum_fraction": 0.5968281938, "num_tokens": 1541, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.4690216149837015}}
{"text": "#include \"Surfelizer.hpp\"\n\n#include \"Utils.hpp\"\n\n#include <boost/circular_buffer.hpp>\n\nusing namespace maps;\n\nstruct Surfelizer::Helper {\n  struct ScanData {\n    std::vector<Eigen::Vector3f> mPoints;\n    std::vector<float> mRanges;\n    std::vector<bool> mValid;\n    Eigen::Isometry3f mPose;\n    float mIntraScanAngle;\n  };\n\n  int mScanRadius;\n  int mPointRadius;\n  SizeMethod mSizeMethod;\n  float mNominalSize;\n  int mDecimation;\n  boost::circular_buffer<ScanData> mDataBuffer;\n\n  std::vector<Surfel> addScan(const maps::PointSet& iScan) {\n    // cache some basic information\n    ScanData data;\n    data.mPose = Utils::getPose(*iScan.mCloud);\n    data.mRanges.resize(iScan.mCloud->size());\n    data.mValid.resize(iScan.mCloud->size());\n    data.mPoints.resize(iScan.mCloud->size());\n    data.mIntraScanAngle = 0;\n    int counter = 0;\n    for (int i = 0; i < iScan.mCloud->size(); ++i) {\n      data.mPoints[i] = data.mPose*(*(iScan.mCloud))[i].getVector3fMap();\n      Eigen::Vector3f ray = data.mPoints[i] - data.mPose.translation();\n      data.mRanges[i] = ray.norm();\n      data.mValid[i] = (data.mRanges[i] >= iScan.mMinRange) &&\n        (data.mRanges[i] <= iScan.mMaxRange);\n      if ((i>0) && data.mValid[i] && data.mValid[i-1]) {\n        Eigen::Vector3f ray2 = data.mPoints[i-1] - data.mPose.translation();\n        data.mIntraScanAngle += acos(ray.normalized().dot(ray2.normalized()));\n        ++counter;\n      }\n    }\n    data.mIntraScanAngle /= counter;\n    mDataBuffer.push_back(data);\n\n    // check to see whether we have enough scans in the buffer to proceed\n    std::vector<Surfel> surfels;\n    int r1 = mScanRadius;\n    int r2 = mPointRadius;\n    int w1 = 2*r1+1;\n    int w2 = 2*r2+1;\n    if (mDataBuffer.size() < w1) return surfels;\n\n    const ScanData& curScan = mDataBuffer[r1];\n    surfels.reserve(curScan.mPoints.size());\n    std::vector<Eigen::Vector3f> points;\n    points.reserve(w1*w2);\n\n    float interScanAngle =\n      acos(mDataBuffer[r1-1].mPose.linear().col(2).dot\n           (mDataBuffer[r1+1].mPose.linear().col(2))) / 2;\n\n    // loop over scan points\n    int numPoints = curScan.mPoints.size();\n    for (int i = r2; i < numPoints - r2; i += mDecimation) {\n      if (!curScan.mValid[i]) continue;\n      \n      // initiate surfel\n      Surfel surfel;\n      surfel.mCenter = curScan.mPoints[i];\n\n      // approximate surfel orientation\n      points.clear();\n      for (int j = 0; j < w1; ++j) {\n        int kMax = std::min(i+r2, (int)mDataBuffer[j].mValid.size()-1);\n        for (int k = i-r2; k <= kMax; ++k) {\n          if (mDataBuffer[j].mValid[k]) {\n            points.push_back(mDataBuffer[j].mPoints[k]);\n          }\n        }\n      }\n      if (points.size() < 3) continue;\n      surfel.mOrientation = estimateOrientation(points,curScan.mPose.linear());\n\n      // approximate surfel size\n      surfel.mSize = Eigen::Vector2f(mNominalSize, mNominalSize);\n      if (mSizeMethod == SizeMethodRange) {\n        surfel.mSize *= curScan.mRanges[i];\n      }\n      else if (mSizeMethod == SizeMethodAngles) {\n        float range = curScan.mRanges[i];\n        Eigen::Vector3f xPt = curScan.mPose.translation() +\n          curScan.mPose.linear().col(0)*range;\n        float dist = (xPt-surfel.mCenter).norm();\n        surfel.mSize = Eigen::Vector2f(interScanAngle*dist,\n                                       curScan.mIntraScanAngle*range);\n      }\n      else if (mSizeMethod == SizeMethodNeighbors) {\n        if (!mDataBuffer[r1+1].mValid[i] || !mDataBuffer[r1-1].mValid[i] ||\n            !mDataBuffer[r1].mValid[i-1] || !mDataBuffer[r1].mValid[i+1]) {\n          continue;\n        }\n        float d1 = (mDataBuffer[r1+1].mPoints[i] -\n                    mDataBuffer[r1-1].mPoints[i]).norm();\n        float d2 = (mDataBuffer[r1].mPoints[i-1] -\n                    mDataBuffer[r1].mPoints[i+1]).norm();\n        surfel.mSize = Eigen::Vector2f(d1/2,d2/2);\n      }\n\n      surfels.push_back(surfel);\n    }\n    return surfels;\n  }\n\n  Eigen::Matrix3f\n  estimateOrientation(const std::vector<Eigen::Vector3f>& iPoints,\n                      const Eigen::Matrix3f& iScanOrientation) {\n    Eigen::Vector3f mean = Eigen::Vector3f::Zero();\n    Eigen::Matrix3f meanSq = Eigen::Matrix3f::Zero();\n    int n = iPoints.size();\n    for (int i = 0; i < n; ++i) {\n      mean += iPoints[i];\n      meanSq += iPoints[i]*iPoints[i].transpose();\n    }\n    mean /= n;\n    meanSq /= n;\n    Eigen::Matrix3f cov = meanSq - mean*mean.transpose();\n    Eigen::JacobiSVD<Eigen::Matrix3f> svd;\n    svd.compute(cov, Eigen::ComputeFullV);\n    Eigen::Matrix3f v = svd.matrixV();\n\n    Eigen::Matrix3f orientation;\n    orientation.col(2) = v.col(2);\n    orientation.col(1) = v.col(2).cross(iScanOrientation.col(2));\n    orientation.col(0) = orientation.col(1).cross(v.col(2));\n    for (int k = 0; k < 3; ++k) orientation.col(k).normalize();\n    return orientation;\n  }\n\n};\n\nSurfelizer::\nSurfelizer() {\n  mHelper.reset(new Helper());\n  setScanRadius(1);\n  setPointRadius(1);\n  setSizeMethod(SizeMethodAngles);\n  setNominalSize(1);\n  setDecimation(1);\n}\n\nSurfelizer::\n~Surfelizer() {\n}\n\nvoid Surfelizer::\nsetScanRadius(const int iRadius) {\n  mHelper->mScanRadius = iRadius;\n  mHelper->mDataBuffer.set_capacity(2*iRadius+1);\n}\n\nvoid Surfelizer::\nsetPointRadius(const int iRadius) {\n  mHelper->mPointRadius = iRadius;\n}\n\nvoid Surfelizer::\nsetSizeMethod(const SizeMethod iMethod) {\n  mHelper->mSizeMethod = iMethod;\n}\n\nvoid Surfelizer::\nsetNominalSize(const float iSize) {\n  mHelper->mNominalSize = iSize;\n}\n\nvoid Surfelizer::\nsetDecimation(const int iDecimation) {\n  mHelper->mDecimation = iDecimation;\n}\n\nstd::vector<Surfelizer::Surfel> Surfelizer::\naddScan(const maps::PointSet& iScan) {\n  return mHelper->addScan(iScan);\n}\n", "meta": {"hexsha": "932403b3c41b2f065be7bda65b870acf766e901c", "size": 5703, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "software/perception/maps/src/Surfelizer.cpp", "max_stars_repo_name": "liangfok/oh-distro", "max_stars_repo_head_hexsha": "eeee1d832164adce667e56667dafc64a8d7b8cee", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 92.0, "max_stars_repo_stars_event_min_datetime": "2016-01-14T21:03:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-01T17:57:46.000Z", "max_issues_repo_path": "software/perception/maps/src/Surfelizer.cpp", "max_issues_repo_name": "liangfok/oh-distro", "max_issues_repo_head_hexsha": "eeee1d832164adce667e56667dafc64a8d7b8cee", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 62.0, "max_issues_repo_issues_event_min_datetime": "2016-01-16T18:08:14.000Z", "max_issues_repo_issues_event_max_datetime": "2016-03-24T15:16:28.000Z", "max_forks_repo_path": "software/perception/maps/src/Surfelizer.cpp", "max_forks_repo_name": "liangfok/oh-distro", "max_forks_repo_head_hexsha": "eeee1d832164adce667e56667dafc64a8d7b8cee", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2016-01-14T21:26:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T03:10:39.000Z", "avg_line_length": 30.1746031746, "max_line_length": 79, "alphanum_fraction": 0.6258109767, "num_tokens": 1681, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.4690216149837015}}
{"text": "// Boost.Range 2.0 Extension library\n// via PStade Oven Library\n//\n// Copyright Akira Takahashi 2011.\n// Copyright Shunsuke Sogame 2005-2007.\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#include <iostream>\n#include <boost/detail/lightweight_test.hpp>\n#include <boost/range/algorithm/equal.hpp>\n\n#include <vector>\n#include <boost/assign/list_of.hpp>\n#include <boost/range/adaptor/taken.hpp>\n\n#include <boost/range/adaptor/regular_extension/filtered.hpp>\n#include <boost/range/adaptor/transformed.hpp>\n#include <boost/range/adaptor/dropped.hpp>\n#include <boost/range/access/front.hpp>\n#include <boost/range/iteration.hpp>\n#include <boost/range/any_range.hpp>\n#include <boost/lambda/lambda.hpp>\n\ntypedef\n    boost::any_range<int, boost::single_pass_traversal_tag, int, std::ptrdiff_t>\nrange;\n\nusing boost::lambda::_1;\nusing namespace boost::adaptors;\nusing boost::range::access::value_front;\n\nrange sieve(range r)\n{\n    return r | dropped(1) |+ filtered(_1 % value_front(r) != 0);\n}\n\nint main()\n{\n    range primes = boost::iteration(range(boost::iteration(2, boost::regular(_1 + 1))), sieve)\n                     | transformed(value_front);\n\n    BOOST_TEST(boost::equal(\n        primes | taken(5),\n        boost::assign::list_of(2)(3)(5)(7)(11)\n    ));\n\n    return boost::report_errors();\n}\n\n", "meta": {"hexsha": "8ea080f2e48425cfc68f46ca691ba0d3ddbc22da", "size": 1433, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/primes.cpp", "max_stars_repo_name": "Flast/OvenToBoost", "max_stars_repo_head_hexsha": "5e39339b1ab2f465083541dfbea1523a0974b9dd", "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": "example/primes.cpp", "max_issues_repo_name": "Flast/OvenToBoost", "max_issues_repo_head_hexsha": "5e39339b1ab2f465083541dfbea1523a0974b9dd", "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": "example/primes.cpp", "max_forks_repo_name": "Flast/OvenToBoost", "max_forks_repo_head_hexsha": "5e39339b1ab2f465083541dfbea1523a0974b9dd", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5576923077, "max_line_length": 94, "alphanum_fraction": 0.7166782973, "num_tokens": 371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.749087201911703, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.469021607969217}}
{"text": "#include <sparse.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n\nBOOST_AUTO_TEST_SUITE(SPARSE);\n\nBOOST_AUTO_TEST_CASE(element_prod_test)\n{    \n  typedef sparse::Block<2,1,float>   block_type;\n  typedef sparse::Vector<block_type> vector_type;\n  \n  vector_type a;\n  vector_type b;\n  vector_type c;\n  \n  a.resize(2);\n  b.resize(2);\n  c.resize(2);\n  \n  a(0)(0) = 1.0f;\n  a(0)(1) = 2.0f;\n  a(1)(0) = 3.0f;\n  a(1)(1) = 4.0f;\n  \n  b(0)(0) = 4.0f;\n  b(0)(1) = 3.0f;\n  b(1)(0) = 2.0f;\n  b(1)(1) = 1.0f;\n  \n  c(0)(0) = 1.0f;\n  c(0)(1) = 1.0f;\n  c(1)(0) = 1.0f;\n  c(1)(1) = 1.0f;\n  \n  sparse::element_prod( a, b, c);\n  \n  BOOST_CHECK( c(0)(0) == 4.0f );\n  BOOST_CHECK( c(0)(1) == 6.0f );\n  BOOST_CHECK( c(1)(0) == 6.0f );\n  BOOST_CHECK( c(1)(1) == 4.0f );\n  \n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "b2734ba9ce3ed00bde2c47be601a8766d7360c08", "size": 938, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/FOUNDATION/SPARSE/unit_tests/sparse_element_prod/sparse_element_prod.cpp", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-11-27T09:44:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-13T00:24:21.000Z", "max_issues_repo_path": "PROX/FOUNDATION/SPARSE/unit_tests/sparse_element_prod/sparse_element_prod.cpp", "max_issues_repo_name": "erleben/matchstick", "max_issues_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_issues_repo_licenses": ["MIT"], "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/FOUNDATION/SPARSE/unit_tests/sparse_element_prod/sparse_element_prod.cpp", "max_forks_repo_name": "erleben/matchstick", "max_forks_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_forks_repo_licenses": ["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.1428571429, "max_line_length": 51, "alphanum_fraction": 0.6023454158, "num_tokens": 387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872019117029, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.46902160796921694}}
{"text": "/*\n *\n * matrix.hpp\n * functions in matrix_ops.cpp\n *\n */\n#pragma once\n\n#include <vector>\n#include <cstdint>\n#include <cstddef>\n#include <string>\n\n#include <Eigen/Dense>\n\n#include \"matrix_idx.hpp\"\n\ntypedef Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> NumpyMatrix;\ntypedef std::tuple<std::vector<long>, std::vector<long>, std::vector<float>> sparse_coo;\ntypedef std::tuple<std::vector<long>, std::vector<long>, std::vector<long>> network_coo;\n\nNumpyMatrix long_to_square(const Eigen::VectorXf &rrDists,\n                           const Eigen::VectorXf &qrDists,\n                           const Eigen::VectorXf &qqDists,\n                           unsigned int num_threads = 1);\n\nEigen::VectorXf square_to_long(const NumpyMatrix &squareDists,\n                               const unsigned int num_threads);\n\nsparse_coo sparsify_dists(const NumpyMatrix &denseDists,\n                          const float distCutoff,\n                          const unsigned long int kNN,\n                          bool reciprocal_only,\n                          bool all_neighbours);\n", "meta": {"hexsha": "0285ae696a8f6828550f6149cb4dcaa231b068f4", "size": 1090, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/dist/matrix.hpp", "max_stars_repo_name": "nickjcroucher/pp-sketchlib", "max_stars_repo_head_hexsha": "66778ab4d8b593b88e0eac3b35cb54c424b32127", "max_stars_repo_licenses": ["ECL-2.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": "src/dist/matrix.hpp", "max_issues_repo_name": "nickjcroucher/pp-sketchlib", "max_issues_repo_head_hexsha": "66778ab4d8b593b88e0eac3b35cb54c424b32127", "max_issues_repo_licenses": ["ECL-2.0", "Apache-2.0", "MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/dist/matrix.hpp", "max_forks_repo_name": "nickjcroucher/pp-sketchlib", "max_forks_repo_head_hexsha": "66778ab4d8b593b88e0eac3b35cb54c424b32127", "max_forks_repo_licenses": ["ECL-2.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": 31.1428571429, "max_line_length": 90, "alphanum_fraction": 0.6137614679, "num_tokens": 233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.46902160453167874}}
{"text": "/**\n * @date Sat Mar 19 22:14:10 2011 +0100\n * @author Laurent El Shafey <Laurent.El-Shafey@idiap.ch>\n *\n * Copyright (C) Idiap Research Institute, Martigny, Switzerland\n */\n\n#include <stdexcept>\n#include <boost/shared_array.hpp>\n\n#include <bob.math/svd.h>\n\n#include <bob.core/assert.h>\n#include <bob.core/check.h>\n#include <bob.core/array_copy.h>\n\n// Declaration of the external LAPACK function (Divide and conquer SVD)\nextern \"C\" void dgesdd_( const char *jobz, const int *M, const int *N,\n  double *A, const int *lda, double *S, double *U, const int* ldu, double *VT,\n  const int *ldvt, double *work, const int *lwork, int *iwork, int *info);\n\n// Declaration of the external LAPACK function ('Slow' but 'safe' SVD)\nextern \"C\" void dgesvd_( const char *jobu, const char *jobvt, const int *M,\n  const int *N, double *A, const int *lda, double *S, double *U,\n  const int* ldu, double *VT, const int *ldvt, double *work, const int *lwork,\n  int *info);\n\nstatic void svd_lapack( const char jobz, const int M, const int N,\n  double *A, const int lda, double *S, double *U, const int ldu, double *VT,\n  const int ldvt, const bool safe)\n{\n  // Calls the LAPACK function:\n  // We use dgesdd by default which is faster than its predecessor dgesvd,\n  // when computing the singular vectors.\n  //   (cf. http://www.netlib.org/lapack/lug/node71.html)\n  // However, dgesdd is failing on some matrices:\n  //   see #171: http://github.com/idiap/bob/issues/171\n  // Please note that matlab is relying on dgesvd.\n  int info = 0;\n  if (safe) {\n    // A/ Queries the optimal size of the working array\n    const int lwork_query = -1;\n    double work_query;\n    dgesvd_( &jobz, &jobz, &M, &N, A, &lda, S, U, &ldu,\n      VT, &ldvt, &work_query, &lwork_query, &info );\n    // Check info variable\n    if (info != 0)\n      throw std::runtime_error(\"The LAPACK dgesvd function returned a non-zero value.\");\n\n    // B/ Computes\n    const int lwork = static_cast<int>(work_query);\n    boost::shared_array<double> work(new double[lwork]);\n    dgesvd_( &jobz, &jobz, &M, &N, A, &lda, S, U, &ldu,\n      VT, &ldvt, work.get(), &lwork, &info );\n    // Check info variable\n    if (info != 0)\n      throw std::runtime_error(\"The LAPACK dgesvd function returned a non-zero value.\");\n  }\n  else {\n    // Integer (workspace) array, dimension (8*min(M,N))\n    const int l_iwork = 8*std::min(M,N);\n    boost::shared_array<int> iwork(new int[l_iwork]);\n\n    // A/ Queries the optimal size of the working array\n    const int lwork_query = -1;\n    double work_query;\n    dgesdd_( &jobz, &M, &N, A, &lda, S, U, &ldu,\n      VT, &ldvt, &work_query, &lwork_query, iwork.get(), &info );\n    // Check info variable\n    if (info != 0)\n      throw std::runtime_error(\"The LAPACK dgesdd function returned a non-zero value. You may consider using LAPACK dgsevd instead (see #171) by enabling the 'safe' option.\");\n\n    // B/ Computes\n    const int lwork = static_cast<int>(work_query);\n    boost::shared_array<double> work(new double[lwork]);\n    dgesdd_( &jobz, &M, &N, A, &lda, S, U, &ldu,\n      VT, &ldvt, work.get(), &lwork, iwork.get(), &info );\n    // Check info variable\n    if (info != 0)\n      throw std::runtime_error(\"The LAPACK dgesdd function returned a non-zero value. You may consider using LAPACK dgsevd instead (see #171) by enabling the 'safe' option.\");\n  }\n  \n  // Defining the sign of the eigenvectors\n  // Approch extracted from page 8 - http://prod.sandia.gov/techlib/access-control.cgi/2007/076422.pdf  \n  if(U[0] < 0){    \n    int ucol=0; ucol= (jobz=='A')? M : std::min(M,N);\n    for (int i=0; i<ldu*ucol; i++){\n      U[i] = -1*U[i];\n    }\n\n    for (int i=0; i<ldvt*N; i++){\n      VT[i] = -1*VT[i];\n    }\n  }\n}\n\nvoid bob::math::svd(const blitz::Array<double,2>& A, blitz::Array<double,2>& U,\n  blitz::Array<double,1>& sigma, blitz::Array<double,2>& Vt, bool safe)\n{\n  // Size variables\n  const int M = A.extent(0);\n  const int N = A.extent(1);\n  const int nb_singular = std::min(M,N);\n\n  // Checks zero base\n  bob::core::array::assertZeroBase(A);\n  bob::core::array::assertZeroBase(U);\n  bob::core::array::assertZeroBase(sigma);\n  bob::core::array::assertZeroBase(Vt);\n  // Checks and resizes if required\n  bob::core::array::assertSameDimensionLength(U.extent(0), M);\n  bob::core::array::assertSameDimensionLength(U.extent(1), M);\n  bob::core::array::assertSameDimensionLength(sigma.extent(0), nb_singular);\n  bob::core::array::assertSameDimensionLength(Vt.extent(0), N);\n  bob::core::array::assertSameDimensionLength(Vt.extent(1), N);\n\n  bob::math::svd_(A, U, sigma, Vt, safe);\n}\n\nvoid bob::math::svd_(const blitz::Array<double,2>& A, blitz::Array<double,2>& U,\n  blitz::Array<double,1>& sigma, blitz::Array<double,2>& Vt, bool safe)\n{\n  // Size variables\n  const int M = A.extent(0);\n  const int N = A.extent(1);\n  const int nb_singular = std::min(M,N);\n\n  // Prepares to call LAPACK function:\n  // We will decompose A^T rather than A to reduce the required number of copy\n  // We recall that FORTRAN/LAPACK is column-major order whereas blitz arrays\n  // are row-major order by default.\n  // If A = U.S.V^T, then A^T = V.S.U^T\n\n  // Initialises LAPACK variables\n  const char jobz = 'A'; // Get All left singular vectors\n  const int lda = N;\n  const int ldu = N;\n  const int ldvt = M;\n  // Initialises LAPACK arrays\n  blitz::Array<double,2> A_blitz_lapack(bob::core::array::ccopy(A));\n  double* A_lapack = A_blitz_lapack.data();\n  // Tries to use U, Vt and S directly to limit the number of copy()\n  // S_lapack = S\n  blitz::Array<double,1> S_blitz_lapack;\n  const bool sigma_direct_use = bob::core::array::isCZeroBaseContiguous(sigma);\n  if (!sigma_direct_use) S_blitz_lapack.resize(nb_singular);\n  else                   S_blitz_lapack.reference(sigma);\n  double *S_lapack = S_blitz_lapack.data();\n  // U_lapack = V^T\n  blitz::Array<double,2> U_blitz_lapack;\n  const bool U_direct_use = bob::core::array::isCZeroBaseContiguous(Vt);\n  if (!U_direct_use) U_blitz_lapack.resize(N,N);\n  else               U_blitz_lapack.reference(Vt);\n  double *U_lapack = U_blitz_lapack.data();\n  // V^T_lapack = U\n  blitz::Array<double,2> VT_blitz_lapack;\n  const bool VT_direct_use = bob::core::array::isCZeroBaseContiguous(U);\n  if (!VT_direct_use) VT_blitz_lapack.resize(M,M);\n  else                VT_blitz_lapack.reference(U);\n  double *VT_lapack = VT_blitz_lapack.data();\n\n  // Call the LAPACK function\n  svd_lapack(jobz, N, M, A_lapack, lda, S_lapack, U_lapack, ldu,\n    VT_lapack, ldvt, safe);  \n\n\n  // Copy singular vectors back to U, V and sigma if required\n  if (!U_direct_use)  Vt = U_blitz_lapack;\n  if (!VT_direct_use) U = VT_blitz_lapack;\n  if (!sigma_direct_use) sigma = S_blitz_lapack;\n}\n\n\nvoid bob::math::svd(const blitz::Array<double,2>& A, blitz::Array<double,2>& U,\n  blitz::Array<double,1>& sigma, bool safe)\n{\n  // Size variables\n  const int M = A.extent(0);\n  const int N = A.extent(1);\n  const int nb_singular = std::min(M,N);\n\n  // Checks zero base\n  bob::core::array::assertZeroBase(A);\n  bob::core::array::assertZeroBase(U);\n  bob::core::array::assertZeroBase(sigma);\n  // Checks and resizes if required\n  bob::core::array::assertSameDimensionLength(U.extent(0), M);\n  bob::core::array::assertSameDimensionLength(U.extent(1), nb_singular);\n  bob::core::array::assertSameDimensionLength(sigma.extent(0), nb_singular);\n\n  bob::math::svd_(A, U, sigma, safe);\n}\n\nvoid bob::math::svd_(const blitz::Array<double,2>& A, blitz::Array<double,2>& U,\n  blitz::Array<double,1>& sigma, bool safe)\n{\n  // Size variables\n  const int M = A.extent(0);\n  const int N = A.extent(1);\n  const int nb_singular = std::min(M,N);\n\n  // Prepares to call LAPACK function\n\n  // Initialises LAPACK variables\n  const char jobz = 'S'; // Get first min(M,N) columns of U\n  const int lda = M;\n  const int ldu = M;\n  const int ldvt = std::min(M,N);\n\n  // Initialises LAPACK arrays\n  blitz::Array<double,2> A_blitz_lapack(bob::core::array::ccopy(const_cast<blitz::Array<double,2>&>(A).transpose(1,0)));\n  double* A_lapack = A_blitz_lapack.data();\n  // Tries to use U and S directly to limit the number of copy()\n  // S_lapack = S\n  blitz::Array<double,1> S_blitz_lapack;\n  const bool sigma_direct_use = bob::core::array::isCZeroBaseContiguous(sigma);\n  if (!sigma_direct_use) S_blitz_lapack.resize(nb_singular);\n  else                   S_blitz_lapack.reference(sigma);\n  double *S_lapack = S_blitz_lapack.data();\n  // U_lapack = U^T\n  blitz::Array<double,2> U_blitz_lapack;\n  blitz::Array<double,2> Ut = U.transpose(1,0);\n  const bool U_direct_use = bob::core::array::isCZeroBaseContiguous(Ut);\n  if (!U_direct_use) U_blitz_lapack.resize(nb_singular,M);\n  else               U_blitz_lapack.reference(Ut);\n  double *U_lapack = U_blitz_lapack.data();\n  boost::shared_array<double> VT_lapack(new double[nb_singular*N]);\n\n  // Call the LAPACK function\n  svd_lapack(jobz, M, N, A_lapack, lda, S_lapack, U_lapack, ldu,\n    VT_lapack.get(), ldvt, safe);\n\n  // Copy singular vectors back to U, V and sigma if required\n  if (!U_direct_use) Ut = U_blitz_lapack;\n  if (!sigma_direct_use) sigma = S_blitz_lapack;\n}\n\n\nvoid bob::math::svd(const blitz::Array<double,2>& A, blitz::Array<double,1>& sigma, bool safe)\n{\n  // Size variables\n  const int M = A.extent(0);\n  const int N = A.extent(1);\n  const int nb_singular = std::min(M,N);\n\n  // Checks zero base\n  bob::core::array::assertZeroBase(A);\n  bob::core::array::assertZeroBase(sigma);\n  // Checks and resizes if required\n  bob::core::array::assertSameDimensionLength(sigma.extent(0), nb_singular);\n\n  bob::math::svd_(A, sigma, safe);\n}\n\nvoid bob::math::svd_(const blitz::Array<double,2>& A, blitz::Array<double,1>& sigma, bool safe)\n{\n  // Size variables\n  const int M = A.extent(0);\n  const int N = A.extent(1);\n  const int nb_singular = std::min(M,N);\n\n  // Prepares to call LAPACK function\n\n  // Initialises LAPACK variables\n  const char jobz = 'N'; // Get first min(M,N) columns of U\n  const int lda = M;\n  const int ldu = M;\n  const int ldvt = std::min(M,N);\n\n  // Initialises LAPACK arrays\n  blitz::Array<double,2> A_blitz_lapack(\n    bob::core::array::ccopy(const_cast<blitz::Array<double,2>&>(A).transpose(1,0)));\n  double* A_lapack = A_blitz_lapack.data();\n  // Tries to use S directly to limit the number of copy()\n  // S_lapack = S\n  blitz::Array<double,1> S_blitz_lapack;\n  const bool sigma_direct_use = bob::core::array::isCZeroBaseContiguous(sigma);\n  if (!sigma_direct_use) S_blitz_lapack.resize(nb_singular);\n  else                   S_blitz_lapack.reference(sigma);\n  double *S_lapack = S_blitz_lapack.data();\n  double *U_lapack = 0;\n  double *VT_lapack = 0;\n\n  // Call the LAPACK function\n  svd_lapack(jobz, M, N, A_lapack, lda, S_lapack, U_lapack, ldu,\n    VT_lapack, ldvt, safe);\n\n  // Copy singular vectors back to U, V and sigma if required\n  if (!sigma_direct_use) sigma = S_blitz_lapack;\n}\n", "meta": {"hexsha": "854cd47328f134cabab3c4f28040c879243ab409", "size": 10810, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bob/math/cpp/svd.cpp", "max_stars_repo_name": "bioidiap/bob.math", "max_stars_repo_head_hexsha": "e0efcd51a609755e55b723e97dca2b5eac6b7976", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/math/cpp/svd.cpp", "max_issues_repo_name": "bioidiap/bob.math", "max_issues_repo_head_hexsha": "e0efcd51a609755e55b723e97dca2b5eac6b7976", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2015-12-02T01:42:32.000Z", "max_issues_repo_issues_event_max_datetime": "2016-05-26T16:37:07.000Z", "max_forks_repo_path": "bob/math/cpp/svd.cpp", "max_forks_repo_name": "bioidiap/bob.math", "max_forks_repo_head_hexsha": "e0efcd51a609755e55b723e97dca2b5eac6b7976", "max_forks_repo_licenses": ["BSD-3-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.147766323, "max_line_length": 175, "alphanum_fraction": 0.6737280296, "num_tokens": 3400, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435083355187, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4690208728901012}}
{"text": "//----------------------------------------------------------------------------\n/** @file SgMathTest.cpp\n    Unit tests for SgMath.\n*/\n//----------------------------------------------------------------------------\n\n#include \"SgSystem.h\"\n\n#include <boost/test/auto_unit_test.hpp>\n#include \"SgMath.h\"\n\nusing namespace std;\n\n//----------------------------------------------------------------------------\n\nnamespace {\n\nBOOST_AUTO_TEST_CASE(SgMathTest_RoundToInt)\n{\n    BOOST_CHECK_EQUAL(SgMath::RoundToInt(-0.8), -1);\n    BOOST_CHECK_EQUAL(SgMath::RoundToInt(-0.3), 0);\n    BOOST_CHECK_EQUAL(SgMath::RoundToInt(0.3), 0);\n    BOOST_CHECK_EQUAL(SgMath::RoundToInt(0.8), 1);\n}\n\n} // namespace\n\n//----------------------------------------------------------------------------\n\n", "meta": {"hexsha": "c3963230147df097dccb3780ae3fe2ce59be1acd", "size": 766, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "fuego-0.4/smartgame/test/SgMathTest.cpp", "max_stars_repo_name": "MisterTea/HyperNEAT", "max_stars_repo_head_hexsha": "516fef725621991ee709eb9b4afe40e0ce82640d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 85.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T20:36:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T20:38:31.000Z", "max_issues_repo_path": "fuego-0.4/smartgame/test/SgMathTest.cpp", "max_issues_repo_name": "afcarl/HyperNEAT", "max_issues_repo_head_hexsha": "516fef725621991ee709eb9b4afe40e0ce82640d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "fuego-0.4/smartgame/test/SgMathTest.cpp", "max_forks_repo_name": "afcarl/HyperNEAT", "max_forks_repo_head_hexsha": "516fef725621991ee709eb9b4afe40e0ce82640d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2015-01-28T16:33:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-12T05:04:39.000Z", "avg_line_length": 25.5333333333, "max_line_length": 78, "alphanum_fraction": 0.4151436031, "num_tokens": 144, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.4690208728901012}}
{"text": "#include <ros/ros.h>\n#include \"AdaptiveController.hpp\"\n#include <Eigen/Dense>\n\n#define RAD_TO_DEG \t\t(double)(180.0/M_PI)\n#define DEG_TO_RAD \t\t(double)(M_PI/180.0)\n\n#define MAX_ROLL_DEG\t20.0\n#define MAX_PITCH_DEG\t20.0\n#define MAX_YAW_DEG\t\t160.0\n#define MAX_THROTTLE\t65000\n#define TRIM_THROTTLE\t40000\n\nusing namespace Eigen;\n\nAdaptiveController::AdaptiveController(void (*_phi_functions) (VectorXd&, const VectorXd))\n{\n\t(*this).phi_functions = _phi_functions;\n}\nAdaptiveController::~AdaptiveController() {}\n\nvoid AdaptiveController::reset()\n{\n\tthis->model.reset();\n\tthis->law.reset();\n}\nvoid AdaptiveController::initialize(const PID_Config_t _pid_x_config,\n                \t\t\t\t\tconst PID_Config_t _pid_y_config,\n                \t\t\t\t\tconst PID_Config_t _pid_z_config, \n                \t\t\t\t\tconst ReferenceModel_Config_t _model_config,\n                                    const AdaptiveLaw_Config_t _law_config,\n                                    const double _dt)\n{\n    Controller::initialize(_pid_x_config, _pid_y_config, _pid_z_config);\n    this->model.initialize(_model_config);\n    this->law.initialize(_law_config);\n\n    this->last_zpos = 0.0;\n    this->dt = _dt;\n\n    switch_to_standby();\n}\n\n\n\nvoid AdaptiveController::compute_outputs(geometry_msgs::Twist* _cmd)\n{\n    // position error in world frame\n    double p_err_world[3], p_err_body[3];\n    for(int i=0;i<3;i++) {\n    \tp_err_world[i] = target_position[i] - current_position[i];\n    }\n\trotate(current_orientation[2], p_err_world, p_err_body);\n\n\t// PID controllers\n\tdouble roll_cmd  =  pid_x.get_output(-p_err_body[0]) * RAD_TO_DEG;\n\tdouble pitch_cmd = -pid_y.get_output(-p_err_body[1]) * RAD_TO_DEG;\n\tdouble yaw_cmd\t =  target_yaw* RAD_TO_DEG;\n\tdouble pid_throttle  =  pid_z.get_output( p_err_body[2]);\n\n\t// Z Adaptive controller\n\tVectorXd zRefCommands, zStates;\t\t// Input to func, need to initialize\n\tVectorXd zRefOutputs, zPhi;\t// Output from func\n\tMatrixXd zGains;\n\n\t// Note: model is z down (-z is above ground)\n\tzRefCommands = VectorXd(1);\t\n\tzStates = VectorXd(2);\n\tzRefCommands(0) = -target_position[2];\n\tzStates(0) = -current_position[2];\t\t\t\t// pose z\n\tzStates(1) = (zStates(0)-last_zpos)/this->dt;\t// vel z\n\tlast_zpos = zStates(0);\n\n    this->model.update(zRefCommands);\n    this->model.get_outputs(zRefOutputs);\n\n\t(*(*this).phi_functions) (zPhi, zStates);\n\n    this->law.update(zStates - zRefOutputs, zPhi);\n    this->law.get_gains(zGains);\n\n    VectorXd adp_throttle = -zGains.transpose()*zPhi;\n    if (adp_throttle.size() != 1)\n        throw std::range_error(\"Adaptive gain is not a scaler!\");\n    adp_throttle *= -4.403669725e5; // convert to PWM from force (model)\n    adp_throttle(0) = limit(adp_throttle(0), -3e4, 3e4);\n\n    double total_throttle = pid_throttle + adp_throttle(0);\n    //ROS_INFO(\"%.4f, %.4f, %.1lf, %.6lf, %.6lf\", zStates(0), zRefOutputs(0),\n    //\t\t\t\t\t\t\t\t\t\t\tadp_throttle(0),\n    //\t\t\t\t\t\t\t\t\t\t\tzGains(0), zGains(1));\n    \n\t// Send Commands\n\t_cmd->linear.y  = limit(roll_cmd, -MAX_ROLL_DEG, MAX_ROLL_DEG);\n\t_cmd->linear.x  = limit(pitch_cmd, -MAX_PITCH_DEG, MAX_PITCH_DEG);\n\t_cmd->angular.z = yaw_cmd;\n\tswitch(flight_state) {\n\t\tcase STANDBY:\n\t\t\t_cmd->linear.z  = limit(0, 0, MAX_THROTTLE);\n\t\t\tbreak;\n\t\tcase EMERGENCY:\n\t\t\t_cmd->linear.z  = limit(0, 0, MAX_THROTTLE);\n\t\t\tbreak;\n\t\tdefault:\n            _cmd->linear.z  = limit(total_throttle + TRIM_THROTTLE, 0.0, MAX_THROTTLE);\n\t}\n}\n\nvoid AdaptiveController::get_reference_states(VectorXd &_states) {\n\tthis->model.get_states(_states);\n}\n\n\nvoid AdaptiveController::get_adaptive_gains(MatrixXd &gains)\n{\n\tthis->law.get_gains(gains);\n}\n", "meta": {"hexsha": "8a84de66cc88f9539eeb250131b67d7b593908cd", "size": 3570, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "crazyflie_mrac_controllers/src/AdaptiveController.cpp", "max_stars_repo_name": "fjctp/crazyflie_mrac_ros", "max_stars_repo_head_hexsha": "d43df1832860addd0ff7fbad391c7871cb3c6577", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-10-09T03:17:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-24T06:00:12.000Z", "max_issues_repo_path": "crazyflie_mrac_controllers/src/AdaptiveController.cpp", "max_issues_repo_name": "fjctp/crazyflie_mrac_ros", "max_issues_repo_head_hexsha": "d43df1832860addd0ff7fbad391c7871cb3c6577", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "crazyflie_mrac_controllers/src/AdaptiveController.cpp", "max_forks_repo_name": "fjctp/crazyflie_mrac_ros", "max_forks_repo_head_hexsha": "d43df1832860addd0ff7fbad391c7871cb3c6577", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-05-24T22:48:29.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-24T22:48:29.000Z", "avg_line_length": 30.2542372881, "max_line_length": 90, "alphanum_fraction": 0.6817927171, "num_tokens": 1057, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.4690208665117988}}
{"text": "#ifndef RADIUMENGINE_POINT_CLOUD_HPP_\n#define RADIUMENGINE_POINT_CLOUD_HPP_\n\n#include <Core/RaCore.hpp>\n\n#include <Eigen/Eigenvalues>\n\n#include <Core/Math/Math.hpp>\n#include <Core/Math/LinearAlgebra.hpp>\n#include <Core/Math/Obb.hpp>\n#include <Core/Containers/VectorArray.hpp>\n\nnamespace Ra\n{\n    namespace Core\n    {\n        /// This file contains functions operating on any unstructured set of points.\n        /// If not stated otherwise the functions behaviour is undefined if the set\n        /// of points is empty.\n        namespace PointCloud\n        {\n            /// Compute the mean point of a set of points, i.e. the barycenter.\n            RA_CORE_API inline Vector3 meanPoint(const Vector3Array& pts);\n\n            /// Returns a transform computed by PCA of the given set of points.\n            /// The rotation gives you the principal directions in increasing\n            /// order of importance (Z = principal direction)\n            /// The translation is the barycenter of the point set.\n            RA_CORE_API inline Transform principalAxis(const Vector3Array& pts);\n\n            /// Returns the axis-aligned bounding box of a set of points.\n            /// This function returns an empty AABB if the set of points is\n            /// empty.\n            RA_CORE_API inline Aabb aabb(const Vector3Array& pts);\n\n            /// Computes an oriented bounding box based on PCA of the points coordinates.\n            RA_CORE_API inline Obb pcaObb(const Vector3Array& pts);\n\n        }\n    }\n}\n\n#include <Core/Geometry/PointCloud/PointCloud.inl>\n\n#endif // RADIUMENGINE_POINT_CLOUD_HPP_\n", "meta": {"hexsha": "b1198ba305ecdd7464fb33b0452bcb4616de8041", "size": 1595, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Core/Geometry/PointCloud/PointCloud.hpp", "max_stars_repo_name": "nmellado/Radium-Engine", "max_stars_repo_head_hexsha": "6e42e4be8d14bcd496371a5f58d483f7d03f9cf4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Core/Geometry/PointCloud/PointCloud.hpp", "max_issues_repo_name": "nmellado/Radium-Engine", "max_issues_repo_head_hexsha": "6e42e4be8d14bcd496371a5f58d483f7d03f9cf4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Core/Geometry/PointCloud/PointCloud.hpp", "max_forks_repo_name": "nmellado/Radium-Engine", "max_forks_repo_head_hexsha": "6e42e4be8d14bcd496371a5f58d483f7d03f9cf4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.6739130435, "max_line_length": 89, "alphanum_fraction": 0.6714733542, "num_tokens": 337, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.46902086651179875}}
{"text": "// Copyright 2002 Rensselaer Polytechnic Institute\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: Lauren Foutz\n//           Scott Hill\n\n/*\n  This file implements the functions\n\n  template <class VertexListGraph, class DistanceMatrix,\n    class P, class T, class R>\n  bool floyd_warshall_initialized_all_pairs_shortest_paths(\n    const VertexListGraph& g, DistanceMatrix& d,\n    const bgl_named_params<P, T, R>& params)\n\n  AND\n\n  template <class VertexAndEdgeListGraph, class DistanceMatrix,\n    class P, class T, class R>\n  bool floyd_warshall_all_pairs_shortest_paths(\n    const VertexAndEdgeListGraph& g, DistanceMatrix& d,\n    const bgl_named_params<P, T, R>& params)\n*/\n\n#ifndef BOOST_GRAPH_FLOYD_WARSHALL_HPP\n#define BOOST_GRAPH_FLOYD_WARSHALL_HPP\n\n#include <boost/property_map/property_map.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/named_function_params.hpp>\n#include <boost/graph/graph_concepts.hpp>\n#include <boost/graph/relax.hpp>\n#include <boost/concept/assert.hpp>\n\nnamespace boost\n{\nnamespace detail\n{\n    template < typename T, typename BinaryPredicate >\n    T min_with_compare(const T& x, const T& y, const BinaryPredicate& compare)\n    {\n        if (compare(x, y))\n            return x;\n        else\n            return y;\n    }\n\n    template < typename VertexListGraph, typename DistanceMatrix,\n        typename BinaryPredicate, typename BinaryFunction, typename Infinity,\n        typename Zero >\n    bool floyd_warshall_dispatch(const VertexListGraph& g, DistanceMatrix& d,\n        const BinaryPredicate& compare, const BinaryFunction& combine,\n        const Infinity& inf, const Zero& zero)\n    {\n        typename graph_traits< VertexListGraph >::vertex_iterator i, lasti, j,\n            lastj, k, lastk;\n\n        for (boost::tie(k, lastk) = vertices(g); k != lastk; k++)\n            for (boost::tie(i, lasti) = vertices(g); i != lasti; i++)\n                if (d[*i][*k] != inf)\n                    for (boost::tie(j, lastj) = vertices(g); j != lastj; j++)\n                        if (d[*k][*j] != inf)\n                            d[*i][*j] = detail::min_with_compare(d[*i][*j],\n                                combine(d[*i][*k], d[*k][*j]), compare);\n\n        for (boost::tie(i, lasti) = vertices(g); i != lasti; i++)\n            if (compare(d[*i][*i], zero))\n                return false;\n        return true;\n    }\n}\n\ntemplate < typename VertexListGraph, typename DistanceMatrix,\n    typename BinaryPredicate, typename BinaryFunction, typename Infinity,\n    typename Zero >\nbool floyd_warshall_initialized_all_pairs_shortest_paths(\n    const VertexListGraph& g, DistanceMatrix& d, const BinaryPredicate& compare,\n    const BinaryFunction& combine, const Infinity& inf, const Zero& zero)\n{\n    BOOST_CONCEPT_ASSERT((VertexListGraphConcept< VertexListGraph >));\n\n    return detail::floyd_warshall_dispatch(g, d, compare, combine, inf, zero);\n}\n\ntemplate < typename VertexAndEdgeListGraph, typename DistanceMatrix,\n    typename WeightMap, typename BinaryPredicate, typename BinaryFunction,\n    typename Infinity, typename Zero >\nbool floyd_warshall_all_pairs_shortest_paths(const VertexAndEdgeListGraph& g,\n    DistanceMatrix& d, const WeightMap& w, const BinaryPredicate& compare,\n    const BinaryFunction& combine, const Infinity& inf, const Zero& zero)\n{\n    BOOST_CONCEPT_ASSERT((VertexListGraphConcept< VertexAndEdgeListGraph >));\n    BOOST_CONCEPT_ASSERT((EdgeListGraphConcept< VertexAndEdgeListGraph >));\n    BOOST_CONCEPT_ASSERT((IncidenceGraphConcept< VertexAndEdgeListGraph >));\n\n    typename graph_traits< VertexAndEdgeListGraph >::vertex_iterator firstv,\n        lastv, firstv2, lastv2;\n    typename graph_traits< VertexAndEdgeListGraph >::edge_iterator first, last;\n\n    for (boost::tie(firstv, lastv) = vertices(g); firstv != lastv; firstv++)\n        for (boost::tie(firstv2, lastv2) = vertices(g); firstv2 != lastv2;\n             firstv2++)\n            d[*firstv][*firstv2] = inf;\n\n    for (boost::tie(firstv, lastv) = vertices(g); firstv != lastv; firstv++)\n        d[*firstv][*firstv] = zero;\n\n    for (boost::tie(first, last) = edges(g); first != last; first++)\n    {\n        if (d[source(*first, g)][target(*first, g)] != inf)\n        {\n            d[source(*first, g)][target(*first, g)]\n                = detail::min_with_compare(get(w, *first),\n                    d[source(*first, g)][target(*first, g)], compare);\n        }\n        else\n            d[source(*first, g)][target(*first, g)] = get(w, *first);\n    }\n\n    bool is_undirected = is_same<\n        typename graph_traits< VertexAndEdgeListGraph >::directed_category,\n        undirected_tag >::value;\n    if (is_undirected)\n    {\n        for (boost::tie(first, last) = edges(g); first != last; first++)\n        {\n            if (d[target(*first, g)][source(*first, g)] != inf)\n                d[target(*first, g)][source(*first, g)]\n                    = detail::min_with_compare(get(w, *first),\n                        d[target(*first, g)][source(*first, g)], compare);\n            else\n                d[target(*first, g)][source(*first, g)] = get(w, *first);\n        }\n    }\n\n    return detail::floyd_warshall_dispatch(g, d, compare, combine, inf, zero);\n}\n\nnamespace detail\n{\n    template < class VertexListGraph, class DistanceMatrix, class WeightMap,\n        class P, class T, class R >\n    bool floyd_warshall_init_dispatch(const VertexListGraph& g,\n        DistanceMatrix& d, WeightMap /*w*/,\n        const bgl_named_params< P, T, R >& params)\n    {\n        typedef typename property_traits< WeightMap >::value_type WM;\n        WM inf = choose_param(get_param(params, distance_inf_t()),\n            std::numeric_limits< WM >::max BOOST_PREVENT_MACRO_SUBSTITUTION());\n\n        return floyd_warshall_initialized_all_pairs_shortest_paths(g, d,\n            choose_param(\n                get_param(params, distance_compare_t()), std::less< WM >()),\n            choose_param(get_param(params, distance_combine_t()),\n                closed_plus< WM >(inf)),\n            inf, choose_param(get_param(params, distance_zero_t()), WM()));\n    }\n\n    template < class VertexAndEdgeListGraph, class DistanceMatrix,\n        class WeightMap, class P, class T, class R >\n    bool floyd_warshall_noninit_dispatch(const VertexAndEdgeListGraph& g,\n        DistanceMatrix& d, WeightMap w,\n        const bgl_named_params< P, T, R >& params)\n    {\n        typedef typename property_traits< WeightMap >::value_type WM;\n\n        WM inf = choose_param(get_param(params, distance_inf_t()),\n            std::numeric_limits< WM >::max BOOST_PREVENT_MACRO_SUBSTITUTION());\n        return floyd_warshall_all_pairs_shortest_paths(g, d, w,\n            choose_param(\n                get_param(params, distance_compare_t()), std::less< WM >()),\n            choose_param(get_param(params, distance_combine_t()),\n                closed_plus< WM >(inf)),\n            inf, choose_param(get_param(params, distance_zero_t()), WM()));\n    }\n\n} // namespace detail\n\ntemplate < class VertexListGraph, class DistanceMatrix, class P, class T,\n    class R >\nbool floyd_warshall_initialized_all_pairs_shortest_paths(\n    const VertexListGraph& g, DistanceMatrix& d,\n    const bgl_named_params< P, T, R >& params)\n{\n    return detail::floyd_warshall_init_dispatch(g, d,\n        choose_const_pmap(get_param(params, edge_weight), g, edge_weight),\n        params);\n}\n\ntemplate < class VertexListGraph, class DistanceMatrix >\nbool floyd_warshall_initialized_all_pairs_shortest_paths(\n    const VertexListGraph& g, DistanceMatrix& d)\n{\n    bgl_named_params< int, int > params(0);\n    return detail::floyd_warshall_init_dispatch(\n        g, d, get(edge_weight, g), params);\n}\n\ntemplate < class VertexAndEdgeListGraph, class DistanceMatrix, class P, class T,\n    class R >\nbool floyd_warshall_all_pairs_shortest_paths(const VertexAndEdgeListGraph& g,\n    DistanceMatrix& d, const bgl_named_params< P, T, R >& params)\n{\n    return detail::floyd_warshall_noninit_dispatch(g, d,\n        choose_const_pmap(get_param(params, edge_weight), g, edge_weight),\n        params);\n}\n\ntemplate < class VertexAndEdgeListGraph, class DistanceMatrix >\nbool floyd_warshall_all_pairs_shortest_paths(\n    const VertexAndEdgeListGraph& g, DistanceMatrix& d)\n{\n    bgl_named_params< int, int > params(0);\n    return detail::floyd_warshall_noninit_dispatch(\n        g, d, get(edge_weight, g), params);\n}\n\n} // namespace boost\n\n#endif\n", "meta": {"hexsha": "e8eeae547221cd8172a1bb5da3eabf9b945830ae", "size": 8510, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/graph/floyd_warshall_shortest.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/floyd_warshall_shortest.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/floyd_warshall_shortest.hpp", "max_forks_repo_name": "Harshitha91/Tmdb-react-native-node", "max_forks_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2015-07-08T19:18:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-14T16:39:56.000Z", "avg_line_length": 37.9910714286, "max_line_length": 80, "alphanum_fraction": 0.6634547591, "num_tokens": 2070, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390746, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4690208665117987}}
{"text": "// Copyright 2018 Apex.AI, Inc.\n// Co-developed by Tier IV, Inc. and 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//  \u00a0 \u00a0http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS 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 2018 Apex.AI, Inc.\n// All rights reserved.\n#include <chrono>\n#include <Eigen/Cholesky>\n#include \"kalman_filter/srcf_core.hpp\"\n#include \"kalman_filter/esrcf.hpp\"\n#include \"motion_model/constant_velocity.hpp\"\n#include \"motion_model/parameter_estimator.hpp\"\n\nusing autoware::prediction::kalman_filter::SrcfCore;\nusing autoware::prediction::kalman_filter::Esrcf;\nusing autoware::motion::motion_model::ConstantVelocity;\nusing autoware::motion::motion_model::ParameterEstimator;\nusing Eigen::Matrix;\nconst float TOL = 1.0E-6F;\n\ntemplate<typename T, uint64_t H, uint64_t W>\nvoid print(const Matrix<T, H, W> & A)\n{\n  std::cerr << \"\\nPrint Matrix:\\n\\n\";\n  for (int i = 0; i < H; ++i) {\n    for (int j = 0; j < W; ++j) {\n      std::cerr << A(i, j) << \", \\t\";\n    }\n    std::cerr << \"\\n\";\n  }\n}\n\n// example 5.4, in Kalman Filtering Theory and Practice using Matlab, pg 193-194\nTEST(srcf_core, univariate)\n{\n  Matrix<float, 1, 1> F, H, Q, R, x, z, P, B, G;\n  // TODO(ltbj): implement memory_test after the completion of #39\n  // osrf_testing_tools_cpp::memory_test::start();\n  const float log2pi = 1.83787706641F;\n  EXPECT_FLOAT_EQ(log2pi, logf(3.14159265359F * 2.0F));\n  F << 1;\n  H << 1;\n  Q << 1;  // sqrt, but 1 so whatever\n  R << 2;\n  x << 1;\n  P << sqrtf(10.0F);\n  G << 1;  // no mapping from procss noise subspace to state space\n  SrcfCore<1, 1> core;\n  // temporal update 0->1\n  P(0) = F(0) * P(0);\n  B(0) = G(0) * Q(0);\n  core.right_lower_triangularize_matrices(P, B);\n  EXPECT_LT(fabsf(B(0) - 0.0F), TOL);\n  EXPECT_LT(fabsf(P(0) - sqrtf(11.0F)), TOL);\n  // observation update 1\n  z(0) = 2;\n  float S = (H(0) * (P(0) * P(0)) * H(0)) + R(0);\n  float err = z(0) - (H(0) * x(0));\n  float pdf = -0.5F * (log2pi + logf(S) + (err * err) / S);\n  EXPECT_LT(fabsf(core.scalar_update(z(0), R(0), H, P, x) - pdf), TOL) << pdf;\n  EXPECT_LT(fabsf(x(0) - 24.0F / 13.0F), TOL);\n  EXPECT_LT(fabsf(P(0) - sqrtf(22.0 / 13.0)), TOL);\n  // temporal update 1->2\n  P(0) = F(0) * P(0);\n  B(0) = G(0) * Q(0);\n  core.right_lower_triangularize_matrices(P, B);\n  EXPECT_LT(fabsf(B(0) - 0.0F), TOL);\n  EXPECT_LT(fabsf(P(0) - sqrtf(35.0F / 13.0F)), TOL);\n  // observation update 2\n  z(0) = 3;\n  S = (H(0) * (P(0) * P(0)) * H(0)) + R(0);\n  err = z(0) - (H(0) * x(0));\n  pdf = -0.5F * (log2pi + logf(S) + (err * err) / S);\n  EXPECT_LT(fabsf(core.scalar_update(z(0), R(0), H, P, x) - pdf), TOL) << pdf;\n  EXPECT_LT(fabsf(x(0) - 153.0F / 61.0F), TOL);\n  EXPECT_LT(fabsf(P(0) - sqrtf(70.0F / 61.0F)), TOL);\n  // TODO(ltbj): implement memory_test after the completion of #39\n  // osrf_testing_tools_cpp::memory_test::stop();\n  // test bad case\n  EXPECT_THROW(core.scalar_update(0.0F, 0.0F, H, P, x), std::domain_error);\n}\n\n// example 5.5 in Kalman Filtering Theory and Pracice using Matlab, pg 195-196\nTEST(srcf_core, multivariate)\n{\n  Matrix<float, 2, 1> x({1, 2}), z({3, 4});\n  Matrix<float, 2, 2> H, C, R;\n  H << 0, 2, 3, 0;\n  C << 4, 1, 1, 9;\n  R << 1, 0, 0, 4;\n  Matrix<float, 2, 1> h_row = H.row(0);\n  // TODO(ltbj): implement memory_test after the completion of #39\n  // osrf_testing_tools_cpp::memory_test::start();\n  int info = 1;\n  // higher TOL to match matlab precision\n  const float TOL2 = 1.0E-4F;\n  Eigen::LLT<Eigen::Ref<decltype(C)>> llt(C);\n\n  C(0U, 1U) = 0.0F;\n  // cholesky from numpy\n  EXPECT_LT(fabsf(C(0, 0) - 2), TOL);\n  EXPECT_LT(fabsf(C(1, 0) - 0.5F), TOL);\n  EXPECT_LT(fabsf(C(1, 1) - 2.95803989F), TOL);\n  // do vector update\n  SrcfCore<2, 2> core;\n  // observation update 1a\n  float likelihood = core.scalar_update(z(0), R(0, 0), H.row(0), C, x);\n  //// check intermediate values\n  // These values are from the worked example in the book\n  EXPECT_LT(fabsf(x(0) - (35.0 / 37.0)), TOL2);\n  EXPECT_LT(fabsf(x(1) - (56.0 / 37.0)), TOL2);\n  // check C, computed manually with scipy\n  EXPECT_LT(fabsf(C(0, 0) - (1.97278785)), TOL2);\n  EXPECT_LT(fabsf(C(1, 0) - (0.01369992)), TOL2);\n  EXPECT_LT(fabsf(C(1, 1) - (0.49300665)), TOL2);\n  // observation update 1b\n  likelihood += core.scalar_update(z(1), R(1, 1), H.row(1), C, x);\n  //// check final values\n  // These values are from the worked example in the book\n  EXPECT_LT(fabsf(x(0) - (467.0 / 361.0)), TOL2);\n  EXPECT_LT(fabsf(x(1) - (2189.0 / 1444.0)), TOL2);\n  // check C\n  EXPECT_LT(fabsf(C(0, 0) - (0.63157895)), TOL2);\n  EXPECT_LT(fabsf(C(1, 0) - (0.00438596)), TOL2);\n  EXPECT_LT(fabsf(C(1, 1) - (0.49300665)), TOL2);\n  // check likelihood of exact matrix:\n  // S = H * P * H' + R = [37, 6; 6, 40]\n  // err = z - (H * x) = [-1; 1]\n  // P(err | 0, S) = -5.506280400650966 (from scipy)\n  EXPECT_LT(fabsf(likelihood - (-5.506280400650966)), 0.01F) << likelihood;\n  // Close enough, < 1% relative error\n  // TODO(ltbj): implement memory_test after the completion of #39\n  // osrf_testing_tools_cpp::memory_test::stop();\n}\n\n// example from Thornton's thesis (see below), pg 28\n// This is a case where the conventional kalman filter will fail but the square root will not\n// Because the example uses a different factorization paradigm, the answers in thes Thesis\n// don't work (they use P = U * U^T, modern standard is P = U^T * U)\n/*\ns = some big number\ne = 1/s = some small number\nP = [s^2, 0; 0, s^2]\nH = [1, e; 1, 1]\nR = [1, 1]\nP1 = [\n\u23a1    2        3     \u23a4\n\u23a2 2\u22c5s       -s      \u23a5\n\u23a2\u2500\u2500\u2500\u2500\u2500\u2500    \u2500\u2500\u2500\u2500\u2500\u2500   \u23a5\n\u23a2 2         2       \u23a5\n\u23a2s  + 2    s  + 2   \u23a5\n\u23a2                   \u23a5 ~ [2    -s ]\n\u23a2   3     2 \u239b 2    \u239e\u23a5   [-s   s^2]\n\u23a2 -s     s \u22c5\u239ds  + 1\u23a0\u23a5\n\u23a2\u2500\u2500\u2500\u2500\u2500\u2500  \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u23a5\n\u23a2 2          2      \u23a5\n\u23a3s  + 2     s  + 2  \u23a6\nS1 = L1 =\n\u23a1           ________              \u23a4\n\u23a2          \u2571    2                 \u23a5\n\u23a2         \u2571    s                  \u23a5\n\u23a2  \u221a2\u22c5   \u2571   \u2500\u2500\u2500\u2500\u2500\u2500         0     \u23a5\n\u23a2       \u2571     2                   \u23a5\n\u23a2     \u2572\u2571     s  + 2               \u23a5\n\u23a2                                 \u23a5\n\u23a2            ________             \u23a5 ~ [sqrtf(2)         0             ]\n\u23a2           \u2571    2                \u23a5   [-sqrf(2)/2 * s   sqrtf(2)/2 * s]\n\u23a2          \u2571    s                 \u23a5\n\u23a2-\u221a2\u22c5s\u22c5   \u2571   \u2500\u2500\u2500\u2500\u2500\u2500          ____\u23a5\n\u23a2        \u2571     2             \u2571  2 \u23a5\n\u23a2      \u2572\u2571     s  + 2    \u221a2\u22c5\u2572\u2571  s  \u23a5\n\u23a2\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500  \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u23a5\n\u23a3          2                2     \u23a6\n\nAbove were computed exactly using sympy\n\nSimilarly, the factors end up being\n\u23a1  _________                       \u23a4\n\u23a2\u2572\u2571 2\u22c5e + 1             0          \u23a5\n\u23a2                                  \u23a5\n\u23a2                  ________________\u23a5\n\u23a2                 \u2571    2           \u23a5\n\u23a2-(3\u22c5e + 1)      \u2571  - e  + 2\u22c5e + 1 \u23a5\n\u23a2\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500    \u2571   \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 \u23a5\n\u23a2  _________  \u2572\u2571       2\u22c5e + 1     \u23a5\n\u23a3\u2572\u2571 2\u22c5e + 1                        \u23a6\n\nfor the second update\n*/\n// TODO(esteve): Test disabled until we fix\n// https://gitlab.com/autowarefoundation/autoware.auto/AutowareAuto/issues/92\nTEST(srcf_core, DISABLED_degenerate)\n{\n  const float eps = 1.0E-6F;\n  EXPECT_LT(fabsf((1.0F + (eps * eps)) - 1), TOL);\n  const float sigma = 1.0F / eps;\n  Matrix<float, 2, 2> H, C;\n  H << 1, eps, 1, 1;\n  C << sigma * sigma, 0, 0, sigma * sigma;\n  Matrix<float, 2, 1> R({1, 1}), x;\n  // cholesky on C\n  int info = 1;\n  Eigen::LLT<Eigen::Ref<decltype(C)>> llt(C);\n\n  C(0, 1) = 0.0F;\n  SrcfCore<2, 2> core;\n  // TODO(ltbj): implement memory_test after the completion of #39\n  // osrf_testing_tools_cpp::memory_test::start();\n  // update\n  float ll = core.scalar_update(0, R(0), H.row(0), C, x);\n  EXPECT_LT(fabsf(C(0, 0) - sqrtf(2)), TOL);\n  EXPECT_LT(fabsf(C(1, 0) - (-sqrtf(2) * sigma / 2)), TOL);\n  EXPECT_LT(fabsf(C(1, 1) - sqrtf(2) * sigma / 2), TOL);\n  ll += core.scalar_update(0, R(1), H.row(1), C, x);\n  EXPECT_LT(fabsf(C(0, 0) - (1)), TOL);\n  EXPECT_LT(fabsf(C(1, 0) - (-1 - 3 * eps)), 0.1F);  // This one is hard to compute exactly\n  EXPECT_LT(fabsf(C(1, 1) - (1)), TOL);\n  // S = [sig^2, sig^2; sig^2, 2*sig^2]\n  // z = err = x = 0\n  EXPECT_LT(fabsf(ll - (-29.468897182338893)), 1.0E-5F) << ll;\n  // TODO(ltbj): implement memory_test after the completion of #39\n  // osrf_testing_tools_cpp::memory_test::stop();\n}\n\n// Example 3.1 in page 66 in NASA JPL paper:\n// https://ntrs.nasa.gov/archive/nasa/casi.ntrs.nasa.gov/19770005172.pdf\n// Modified from reference, since they use U*U^T = P, where convention is U^T * U = P\n// test covariance temporal update\nTEST(srcf_core, propagation)\n{\n  Matrix<float, 2, 1> GQ({0, 1});  // B = [0; 1], Q = 1\n  const float eps = 1.0E-5F;\n  const float sigma = 1.0F / eps;\n  // sigma ^2 + 1 ~= sigma ^2\n  EXPECT_LT(fabsf((sigma * sigma + 1) - (sigma * sigma)), TOL);\n  Matrix<float, 2, 2> C;\n  C << sigma, 0, sigma, 1;\n  SrcfCore<2, 1> core;\n  // TODO(ltbj): implement memory_test after the completion of #39\n  // osrf_testing_tools_cpp::memory_test::start();\n  core.right_lower_triangularize_matrices(C, GQ);\n  EXPECT_LT(fabsf(C(1, 1) - (sqrtf(2))), eps) << C(0, 0);\n  EXPECT_LT(fabsf(C(1, 0) - (sigma)), eps) << C(1, 0);\n  EXPECT_LT(fabsf(C(0, 0) - (sigma)), eps) << C(1, 1);\n  // B should be zero'd\n  EXPECT_LT(fabsf(GQ(0)), eps) << GQ(0);\n  EXPECT_LT(fabsf(GQ(1)), eps) << GQ(1);\n  // TODO(ltbj): implement memory_test after the completion of #39\n  // osrf_testing_tools_cpp::memory_test::stop();\n}\n\n// test other branches of givens rotations\nTEST(srcf_core, triangularization)\n{\n  SrcfCore<3, 1> core;\n  Matrix<float, 3, 3> A;\n  A <<\n    1, 1, 1,\n    1, -1, 1,\n    1, 1, 0;\n  Matrix<float, 3, 3> C(A), D(A), E(A);\n  Matrix<float, 3, 1> B;  // zero\n  // TODO(ltbj): implement memory_test after the completion of #39\n  // osrf_testing_tools_cpp::memory_test::start();\n  core.right_lower_triangularize_matrices(A, B);\n  // B should remain 0\n  EXPECT_LT(fabsf(B(0)), TOL);\n  EXPECT_LT(fabsf(B(1)), TOL);\n  EXPECT_LT(fabsf(B(2)), TOL);\n  // lower triangle of A should be 0\n  EXPECT_LT(fabsf(A(0, 1)), TOL);\n  EXPECT_LT(fabsf(A(0, 2)), TOL);\n  EXPECT_LT(fabsf(A(1, 2)), TOL);\n  // Not NAN\n  EXPECT_NE(A(0, 0), NAN);\n  EXPECT_NE(A(1, 0), NAN);\n  EXPECT_NE(A(2, 0), NAN);\n  EXPECT_NE(A(1, 1), NAN);\n  EXPECT_NE(A(2, 1), NAN);\n  EXPECT_NE(A(2, 2), NAN);\n  //// yet another case\n  E(0, 0) = 0;\n  E(2, 0) = -1;\n  core.right_lower_triangularize_matrices(E, B);\n  // B should remain 0\n  EXPECT_LT(fabsf(B(0)), TOL);\n  EXPECT_LT(fabsf(B(1)), TOL);\n  EXPECT_LT(fabsf(B(2)), TOL);\n  // lower triangle of A should be 0\n  EXPECT_LT(fabsf(E(0, 1)), TOL);\n  EXPECT_LT(fabsf(E(0, 2)), TOL);\n  EXPECT_LT(fabsf(E(1, 2)), TOL);\n  // Not NAN\n  EXPECT_NE(E(0, 0), NAN);\n  EXPECT_NE(E(1, 0), NAN);\n  EXPECT_NE(E(2, 0), NAN);\n  EXPECT_NE(E(1, 1), NAN);\n  EXPECT_NE(E(1, 2), NAN);\n  EXPECT_NE(E(2, 2), NAN);\n  // another arbitrary case\n  B(2) = -1;\n  C(2, 1) = -1;\n  core.right_lower_triangularize_matrices(C, B);\n  EXPECT_LT(fabsf(B(0)), TOL);\n  EXPECT_LT(fabsf(B(1)), TOL);\n  EXPECT_LT(fabsf(B(2)), TOL);\n  // lower triangle of A should be 0\n  EXPECT_LT(fabsf(C(0, 1)), TOL);\n  EXPECT_LT(fabsf(C(0, 2)), TOL);\n  EXPECT_LT(fabsf(C(1, 2)), TOL);\n  // Not NAN\n  EXPECT_NE(C(0, 0), NAN);\n  EXPECT_NE(C(1, 0), NAN);\n  EXPECT_NE(C(2, 0), NAN);\n  EXPECT_NE(C(1, 1), NAN);\n  EXPECT_NE(C(1, 2), NAN);\n  EXPECT_NE(C(2, 2), NAN);\n  // one more case\n  B(0) = -1;\n  B(1) = -2;\n  B(2) = 1;\n  D(0, 0) = 0;\n  D(1, 1) = 0;\n  core.right_lower_triangularize_matrices(D, B);\n  EXPECT_LT(fabsf(B(0)), TOL);\n  EXPECT_LT(fabsf(B(1)), TOL);\n  EXPECT_LT(fabsf(B(2)), TOL);\n  // lower triangle of A should be 0\n  EXPECT_LT(fabsf(D(0, 1)), TOL);\n  EXPECT_LT(fabsf(D(0, 2)), TOL);\n  EXPECT_LT(fabsf(D(1, 2)), TOL);\n  // Not NAN\n  EXPECT_NE(D(0, 0), NAN);\n  EXPECT_NE(D(1, 0), NAN);\n  EXPECT_NE(D(2, 0), NAN);\n  EXPECT_NE(D(1, 1), NAN);\n  EXPECT_NE(D(1, 2), NAN);\n  EXPECT_NE(D(2, 2), NAN);\n  // TODO(ltbj): implement memory_test after the completion of #39\n  // osrf_testing_tools_cpp::memory_test::stop();\n}\n\n// given a correct initial guess and perfect observations, state\n// should not change and covariance should shrink to steady state\nTEST(esrcf, convergence)\n{\n  ConstantVelocity model;\n  Matrix<float, 4, 1> R({1, 1, 1, 1});\n  // identity\n  Matrix<float, 4, 4> GQ;\n  GQ <<\n    0.1F, 0.0F, 0.0F, 0.0F,\n    0.0F, 0.1F, 0.0F, 0.0F,\n    0.0F, 0.0F, 0.1F, 0.0F,\n    0.0F, 0.0F, 0.0F, 0.1F;\n\n  Matrix<float, 4, 1> x({0, 0, 1, -1});  // all 0's\n  // cholesky of: (so there is some covariance wrt hidden state\n  // 1   0   0.5 0\n  // 0   1   0   0.5\n  // 0.5 0   1   0\n  // 0   0.5 0   1\n  Matrix<float, 4, 4> P;\n  P <<\n    1, 0, 0, 0,\n    0, 1, 0, 0,\n    0, 0, 1, 0,\n    0, 0, 0, 1;\n  // prefit and postfit covariance matrices\n  Matrix<float, 4, 4> P_m(P), P_p(P), P_last;\n  const Matrix<float, 4, 4> H((Matrix<float, 4, 4>() <<\n    1, 0, 0, 0,\n    0, 1, 0, 0,\n    0, 0, 1, 0,\n    0, 0, 0, 1 ).finished());\n\n  Esrcf<4, 4> kf(model, GQ);\n  // TODO(ltbj): implement memory_test after the completion of #39\n  // osrf_testing_tools_cpp::memory_test::start();\n  kf.reset(x, P);\n  float last_ll = -std::numeric_limits<float>::max();\n  // microseconds_100 = 0.1s\n  std::chrono::nanoseconds microseconds_100(100000000LL);\n  for (uint32_t idx = 0; idx < 30; ++idx) {\n    x(0) += 0.1;\n    x(1) -= 0.1;\n    kf.temporal_update(microseconds_100);\n    // covariance should grow wrt postfit\n    EXPECT_GT(kf.get_covariance()(0, 0), P_p(0, 0));\n    EXPECT_GT(kf.get_covariance()(1, 1), P_p(1, 1));\n    EXPECT_GT(kf.get_covariance()(2, 2), P_p(2, 2));\n    EXPECT_GT(kf.get_covariance()(3, 3), P_p(3, 3));\n    // covariance should be smaller than last prefit\n    if (idx > 0) {\n      EXPECT_LE(kf.get_covariance()(0, 0), P_m(0, 0));\n      EXPECT_LE(kf.get_covariance()(1, 1), P_m(1, 1));\n      EXPECT_LE(kf.get_covariance()(2, 2), P_m(2, 2));\n      EXPECT_LE(kf.get_covariance()(3, 3), P_m(3, 3));\n    }\n    P_m = kf.get_covariance();\n    // state should still be 0\n    EXPECT_LT(fabsf(model[0] - x(0)), TOL);\n    EXPECT_LT(fabsf(model[1] - x(1)), TOL);\n    EXPECT_LT(fabsf(model[2] - x(2)), TOL);\n    EXPECT_LT(fabsf(model[3] - x(3)), TOL);\n    //// exact observation\n    const float ll = kf.observation_update(x, H, R);\n    // likelihood should improve\n    EXPECT_GT(ll, last_ll);\n    last_ll = ll;\n    // covariance should shrink\n    EXPECT_LE(kf.get_covariance()(0, 0), P_m(0, 0));\n    EXPECT_LE(kf.get_covariance()(1, 1), P_m(1, 1));\n    EXPECT_LE(kf.get_covariance()(2, 2), P_m(2, 2));\n    EXPECT_LE(kf.get_covariance()(3, 3), P_m(3, 3));\n    // covariance should also be smaller wrt last postfit\n    EXPECT_LE(kf.get_covariance()(0, 0), P_p(0, 0));\n    EXPECT_LE(kf.get_covariance()(1, 1), P_p(1, 1));\n    EXPECT_LE(kf.get_covariance()(2, 2), P_p(2, 2));\n    EXPECT_LE(kf.get_covariance()(3, 3), P_p(3, 3));\n    P_last = P_p;\n    P_p = kf.get_covariance();\n    // state should still be 0\n    EXPECT_LT(fabsf(model[0] - x(0)), TOL);\n    EXPECT_LT(fabsf(model[1] - x(1)), TOL);\n    EXPECT_LT(fabsf(model[2] - x(2)), TOL);\n    EXPECT_LT(fabsf(model[3] - x(3)), TOL);\n  }\n  P_last -= P_p;\n  float norm = 0.0F;\n  for (int i = 0; i < P_last.rows(); ++i) {\n    for (int j = 0; j < P_last.cols(); ++j) {\n      norm += P_last(i, j) * P_last(i, j);\n    }\n  }\n  EXPECT_LE(sqrtf(norm), 0.0005);\n  // TODO(ltbj): implement memory_test after the completion of #39\n  // osrf_testing_tools_cpp::memory_test::stop();\n}\n\n\n// Hidden states should converge to a good value\nTEST(esrcf, hidden_state)\n{\n  ConstantVelocity model;\n  Matrix<float, 2, 1> R({0.001F, 0.001F});\n  // identity\n  Matrix<float, 4, 4> GQ;\n  GQ <<\n    0.125F, 0.0F, 0.0F, 0.0F,\n    0.0F, 0.125F, 0.0F, 0.0F,\n    0.5F, 0.0F, 0.1F, 0.0F,\n    0.0F, 0.5F, 0.0F, 0.1F\n  ;\n  const float vx = 1.0F, vy = 1.0F;\n  Matrix<float, 4, 1> x({0, 0, 0.0, 0.0});  // all 0's\n  // cholesky of: (so there is some covariance wrt hidden state\n  // 1   0   0.5 0\n  // 0   1   0   0.5\n  // 0.5 0   1   0\n  // 0   0.5 0   1\n  Matrix<float, 4, 4> P;\n  P <<\n    1.0F, 0.0F, 0.0F, 0.0F,\n    0.0F, 1.0F, 0.0F, 0.0F,\n    0.0F, 0.0F, 10.0F, 0.0F,\n    0.0F, 0.0F, 0.0F, 10.0F\n  ;\n  // prefit and postfit covariance matrices\n  Matrix<float, 4, 4> P_m(P), P_p(P);\n  const Matrix<float, 4, 4> P0(P);\n  const Matrix<float, 2, 4> H((Matrix<float, 2, 4>() <<\n    1, 0, 0, 0,\n    0, 1, 0, 0).finished());\n\n  Matrix<float, 2, 1> z({0, 0});\n  Esrcf<4, 4> kf(model, GQ, x, P);\n  EXPECT_NE(model[ConstantVelocity::States::VELOCITY_X], vx);\n  EXPECT_NE(model[ConstantVelocity::States::VELOCITY_Y], vy);\n  // microseconds_100 = 0.1s\n  const std::chrono::nanoseconds microseconds_100(100000000LL);\n  // TODO(ltbj): implement memory_test after the completion of #39\n  // osrf_testing_tools_cpp::memory_test::start();\n  // velocity error should be shrinking\n  float err_u = std::numeric_limits<float>::max();\n  float err_v = std::numeric_limits<float>::max();\n  float last_ll = -std::numeric_limits<float>::max();\n  for (uint32_t idx = 0; idx < 90; ++idx) {\n    z(0) += static_cast<float>(microseconds_100.count()) / 1000000000LL * vx;\n    z(1) += static_cast<float>(microseconds_100.count()) / 1000000000LL * vy;\n    kf.temporal_update(microseconds_100);\n    // covariance should grow wrt postfit\n    EXPECT_GT(kf.get_covariance()(0, 0), P_p(0, 0)) << idx;\n    EXPECT_GT(kf.get_covariance()(1, 1), P_p(1, 1)) << idx;\n    // EXPECT_GT(kf.get_covariance()(2, 2), P_p(2, 2)) << idx;\n    // EXPECT_GT(kf.get_covariance()(3, 3), P_p(3, 3)) << idx;\n    // Analytically, the updated velocity/hidden state covariance is\n    // t^2 * (p_v + s^2), where t is the characteristic time step, and s is the characteristic\n    // measurement noise. Since the time step is < 1, then variance shrinks\n    // Hidden state error should shrink\n    float err = fabsf(model[2] - vx);\n    EXPECT_LT(err, err_u) << idx;\n    err_u = err;\n    err = fabsf(model[3] - vy);\n    EXPECT_LT(err, err_v) << idx;\n    err_v = err;\n    if ((err_u < TOL) && (err_v < TOL)) {\n      // TODO(ltbj): implement memory_test after the completion of #39\n      // osrf_testing_tools_cpp::memory_test::pause();\n      std::cout << \"Converged at \" << idx << \"\\n\";\n      // TODO(ltbj): implement memory_test after the completion of #39\n      // osrf_testing_tools_cpp::memory_test::resume();\n      break;\n    }\n    P_m = kf.get_covariance();\n    //// exact observation\n    const float ll = kf.observation_update(z, H, R);\n    // likelihood should improve or converge\n    EXPECT_GE(ll, last_ll) << idx;\n    last_ll = ll;\n    // covariance should shrink or converge\n    EXPECT_LE(kf.get_covariance()(0, 0), P_m(0, 0)) << idx;\n    EXPECT_LE(kf.get_covariance()(1, 1), P_m(1, 1)) << idx;\n    EXPECT_LE(kf.get_covariance()(2, 2), P_m(2, 2)) << idx;\n    EXPECT_LE(kf.get_covariance()(3, 3), P_m(3, 3)) << idx;\n    // postfit covariance should always be smaller than p0\n    EXPECT_LT(kf.get_covariance()(0, 0), P0(0, 0)) << idx;\n    EXPECT_LT(kf.get_covariance()(1, 1), P0(1, 1)) << idx;\n    EXPECT_LT(kf.get_covariance()(2, 2), P0(2, 2)) << idx;\n    EXPECT_LT(kf.get_covariance()(3, 3), P0(3, 3)) << idx;\n    P_p = kf.get_covariance();\n    // state should be very close to observation\n    EXPECT_LT(fabsf(model[0] - z(0)), kf.get_covariance()(0, 0)) << idx;\n    EXPECT_LT(fabsf(model[1] - z(0)), kf.get_covariance()(1, 1)) << idx;\n  }\n  // TODO(ltbj): implement memory_test after the completion of #39\n  // osrf_testing_tools_cpp::memory_test::stop();\n}\n\nTEST(esrcf, imm_mix)\n{\n  static const uint32_t dim = 2U;\n  int info;\n  Matrix<float, dim, dim> P1, P2, P, C, GQ;\n  Matrix<float, dim, 1> x1, x2, x_mix;\n  P1 << 2.0F, 2.0F, 2.0F, 4.0F;\n  P2 << 2.0F, 1.0F, 1.0F, 2.0F;\n  C = P1;\n  Eigen::LLT<Eigen::Ref<decltype(C)>> llt(C);\n\n  C(0U, 1U) = 0.0F;\n  const float u1 = 0.75F;\n  const float u2 = 0.25F;\n  x1 = {-3.0F, 5.0F};\n  x2 = {5.0F, -3.0F};\n  x_mix = {-1.0F, 3.0F};\n  ParameterEstimator<dim> model;\n  Esrcf<dim, dim> kf(model, GQ, x1, C);\n  // TODO(ltbj): implement memory_test after the completion of #39\n  // osrf_testing_tools_cpp::memory_test::start();\n  // P1' = u P1 * (x1 - x) (x1 - x)^T\n  kf.imm_self_mix(u1, x_mix);\n  EXPECT_FLOAT_EQ(model.get_state()(0U), -1.0F);\n  EXPECT_FLOAT_EQ(model.get_state()(1U), 3.0F);\n  P = P1;\n  // dx = {-2, 2} --> dx * dx' = {4, -4; -4, 4}\n  P += (Matrix<float, dim, dim>() << 4.0F, -4.0F, -4.0F, 4.0F).finished();\n  P *= u1;\n  C = P;\n  llt.compute(C);\n  C(0U, 1U) = 0.0F;\n  EXPECT_FLOAT_EQ(kf.get_covariance()(0U, 0U), C(0U, 0U));\n  EXPECT_LT(fabsf(kf.get_covariance()(0U, 1U) - C(0U, 1U)), TOL);\n  EXPECT_FLOAT_EQ(kf.get_covariance()(1U, 0U), C(1U, 0U));\n  EXPECT_FLOAT_EQ(kf.get_covariance()(1U, 1U), C(1U, 1U));\n  // Apply update from other model\n  C = P2;\n  llt.compute(C);\n\n  C(0U, 1U) = 0.0F;\n  kf.imm_other_mix(u2, x2, C, dim);\n  // inputs should be zero'd after triangularization\n  EXPECT_LT(fabsf(C(0U, 0U)), TOL);\n  EXPECT_LT(fabsf(C(0U, 1U)), TOL);\n  EXPECT_LT(fabsf(C(1U, 0U)), TOL);\n  EXPECT_LT(fabsf(C(1U, 1U)), TOL);\n  // internal state should remain unchanged\n  EXPECT_FLOAT_EQ(model.get_state()(0U), -1.0F);\n  EXPECT_FLOAT_EQ(model.get_state()(1U), 3.0F);\n  // Compute updated covariance\n  // dx2 = {6, -6}\n  P2 += (Matrix<float, dim, dim>() << 36.0F, -36.0F, -36.0F, 36.0F).finished();\n  P2 *= u2;\n  P += P2;\n  C = P;\n  C(0U, 1U) = 0.0F;\n  llt.compute(C);\n\n  EXPECT_FLOAT_EQ(kf.get_covariance()(0U, 0U), C(0U, 0U));\n  EXPECT_LT(fabsf(kf.get_covariance()(0U, 1U) - C(0U, 1U)), TOL);\n  EXPECT_FLOAT_EQ(kf.get_covariance()(1U, 0U), C(1U, 0U));\n  EXPECT_FLOAT_EQ(kf.get_covariance()(1U, 1U), C(1U, 1U));\n  // TODO(ltbj): implement memory_test after the completion of #39\n  // osrf_testing_tools_cpp::memory_test::stop();\n}\n", "meta": {"hexsha": "a00e90358d4f2def1e260f682b494cb0a08d8ad9", "size": 21786, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/prediction/kalman_filter/test/include/test_kalman_filter.hpp", "max_stars_repo_name": "jimaldon/AutowareAuto", "max_stars_repo_head_hexsha": "2b639aa06f67e41222c89f3885c0472483ac6b38", "max_stars_repo_licenses": ["Apache-2.0"], "max_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/kalman_filter/test/include/test_kalman_filter.hpp", "max_issues_repo_name": "jimaldon/AutowareAuto", "max_issues_repo_head_hexsha": "2b639aa06f67e41222c89f3885c0472483ac6b38", "max_issues_repo_licenses": ["Apache-2.0"], "max_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/kalman_filter/test/include/test_kalman_filter.hpp", "max_forks_repo_name": "jimaldon/AutowareAuto", "max_forks_repo_head_hexsha": "2b639aa06f67e41222c89f3885c0472483ac6b38", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-21T04:17:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-21T04:17:33.000Z", "avg_line_length": 35.3095623987, "max_line_length": 94, "alphanum_fraction": 0.5860644451, "num_tokens": 8659, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.46902086013349603}}
{"text": "#include <eve/function/ellint_3.hpp>\n#include <boost/math/special_functions/ellint_3.hpp>\n#include <eve/wide.hpp>\n#include <iostream>\n\nusing wide_ft = eve::wide<float, eve::fixed<4>>;\n\nint main()\n{\n  wide_ft pf = {0.1f, 0.0f, 0.2f, 3.0f};\n  wide_ft qf = {0.1f, 1.5f, 0.2f, 0.5f};\n  wide_ft rf = {2.0f, 1.0f, 0.1f, 1.0f};\n\n  std::cout << \"---- simd\" << '\\n'\n            << \"<- pf                    = \" << pf << '\\n'\n            << \"<- qf                    = \" << qf << '\\n'\n            << \"<- rf                    = \" << rf << '\\n'\n            << \"-> ellint_3(pf, qf, rf) = \" << eve::ellint_3(pf, qf, rf) << '\\n';\n\n  float xf = 3.0f;\n  float yf = 0.5f;\n  float zf = 1.0f;\n\n  std::cout << \"---- scalar\" << '\\n'\n            << \"<- xf                    = \" << xf << '\\n'\n            << \"<- yf                    = \" << yf << '\\n'\n            << \"<- zf                    = \" << zf << '\\n'\n            << \"-> ellint_3(xf, yf, zf) = \" << eve::ellint_3(xf, yf, zf) << '\\n';\n\n  return 0;\n}\n", "meta": {"hexsha": "441eda9d6764ad5ad89473ed85df23add3e4552b", "size": 986, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/doc/core/ellint_3.cpp", "max_stars_repo_name": "orao/eve", "max_stars_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_stars_repo_licenses": ["MIT"], "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/doc/core/ellint_3.cpp", "max_issues_repo_name": "orao/eve", "max_issues_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_issues_repo_licenses": ["MIT"], "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/doc/core/ellint_3.cpp", "max_forks_repo_name": "orao/eve", "max_forks_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_forks_repo_licenses": ["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.8125, "max_line_length": 81, "alphanum_fraction": 0.3701825558, "num_tokens": 365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.46898006109091606}}
{"text": "// Implement member functions for SimplicialComplexOperators class.\n#include \"simplicial-complex-operators.h\"\n#include \"geometrycentral/numerical/linear_algebra_utilities.h\"\n#include <Eigen/Sparse>\n#include <cassert>\n\n\nusing namespace geometrycentral;\nusing namespace geometrycentral::surface;\n\n/*\n * Assign a unique index to each vertex, edge, and face of a mesh.\n * All elements are 0-indexed.\n *\n * Input: None. Access geometry via the member variable <geometry>, and pointer to the mesh via <mesh>.\n * Returns: None.\n */\nvoid SimplicialComplexOperators::assignElementIndices() {\n\n    // Needed to access geometry->vertexIndices, etc. as cached quantities.\n    // Not needed if you're just using v->getIndex(), etc.\n    geometry->requireVertexIndices();\n    geometry->requireEdgeIndices();\n    geometry->requireFaceIndices();\n\n    // You can set the index field of a vertex via geometry->vertexIndices[v], where v is a Vertex object (or an\n    // integer). Similarly you can do edges and faces via geometry->edgeIndices, geometry->faceIndices, like so:\n    size_t idx = 0;\n    for (Vertex v : mesh->vertices()) {\n        idx = geometry->vertexIndices[v];\n    }\n\n    for (Edge e : mesh->edges()) {\n        idx = geometry->edgeIndices[e];\n    }\n\n    for (Face f : mesh->faces()) {\n        idx = geometry->faceIndices[f];\n    }\n\n    // You can more easily get the indices of mesh elements using the function getIndex(), albeit less efficiently and\n    // technically less safe (although you don't need to worry about it), like so:\n    //\n    //      v.getIndex()\n    //\n    // where v can be a Vertex, Edge, Face, Halfedge, etc. For example:\n\n    for (Vertex v : mesh->vertices()) {\n        idx = v.getIndex(); // == geometry->vertexIndices[v])\n    }\n\n    // Geometry Central already sets the indices for us, though, so this function is just here for demonstration.\n    // You don't have to do anything :)\n}\n\n/*\n * Construct the unsigned vertex-edge adjacency matrix A0.\n *\n * Input:\n * Returns: The sparse vertex-edge adjacency matrix which gets stored in the global variable A0.\n */\nSparseMatrix<size_t> SimplicialComplexOperators::buildVertexEdgeAdjacencyMatrix() const {\n\n    geometry->requireVertexIndices();\n    geometry->requireEdgeIndices();\n    geometry->requireFaceIndices();\n    // Note: You can build an Eigen sparse matrix from triplets, then return it as a Geometry Central SparseMatrix.\n    // See <https://eigen.tuxfamily.org/dox/group__TutorialSparse.html> for documentation.\n    \n    // initialize eigensparse matrix\n    SparseMatrix<size_t> mat(mesh->nEdges(),mesh->nVertices());\n\n    for (Edge e : mesh->edges()){\n        // we compute by edge since we know there will only be 2 per row\n        // enter sparse matrix values one by one:\n        size_t i1 = geometry->vertexIndices[e.firstVertex()];\n        size_t i2 = geometry->vertexIndices[e.secondVertex()];\n        size_t e_i = geometry->edgeIndices[e];\n \n        mat.insert(e_i,i1)=1;\n        mat.insert(e_i,i2)=1;\n\n    }\n\n    return mat; \n}\n\n/*\n * Construct the unsigned face-edge adjacency matrix A1.\n *\n * Input:\n * Returns: The sparse face-edge adjacency matrix which gets stored in the global variable A1.\n */\nSparseMatrix<size_t> SimplicialComplexOperators::buildFaceEdgeAdjacencyMatrix() const {\n    \n    geometry->requireVertexIndices();\n    geometry->requireEdgeIndices();\n    geometry->requireFaceIndices();\n\n    // initialize eigensparse matrix\n    SparseMatrix<size_t> mat(mesh->nFaces(),mesh->nEdges());\n    \n    for (Halfedge he : mesh->halfedges()){\n\n        // only count interior edges\n        if(he.isInterior()){\n        // enter sparse matrix values one by one:\n        size_t e = geometry->edgeIndices[he.edge()];\n        \n        size_t f = geometry->faceIndices[he.face()];\n        \n        mat.insert(f,e)=1;\n        }\n        \n    }\n    return mat; \n}\n\n/*\n * Construct a vector encoding the vertices in the selected subset of simplices.\n *\n * Input: Selected subset of simplices.\n * Returns: Vector of length |V|, where |V| = # of vertices in the mesh.\n */\nVector<size_t> SimplicialComplexOperators::buildVertexVector(const MeshSubset& subset) const {\n    \n    Vector<size_t> vertices= Vector<size_t>::Zero(mesh->nVertices(),1);\n\n    std::set<size_t>::iterator it;\n    \n    for (it = subset.vertices.begin(); it!= subset.vertices.end(); it++){\n        vertices[*it]=1;\n    }\n    \n    return vertices;\n}\n\n/*\n * Construct a vector encoding the edges in the selected subset of simplices.\n *\n * Input: Selected subset of simplices.\n * Returns: Vector of length |E|, where |E| = # of edges in mesh.\n */\nVector<size_t> SimplicialComplexOperators::buildEdgeVector(const MeshSubset& subset) const {\n\n    Vector<size_t> edges= Vector<size_t>::Zero(mesh->nEdges(),1);\n\n    std::set<size_t>::iterator it;\n    \n    for (it = subset.edges.begin(); it!= subset.edges.end(); it++){\n         edges[*it]=1;\n    }\n    \n    return edges;\n}\n\n/*\n * Construct a vector encoding the faces in the selected subset of simplices.\n *\n * Input: Selected subset of simplices.\n * Returns: Vector of length |F|, where |F| = # of faces in mesh.\n */\nVector<size_t> SimplicialComplexOperators::buildFaceVector(const MeshSubset& subset) const {\n\n    Vector<size_t> faces= Vector<size_t>::Zero(mesh->nFaces(),1);\n\n    std::set<size_t>::iterator it;\n    \n    for (it = subset.faces.begin(); it!= subset.faces.end(); it++){\n         faces[*it]=1;\n    }\n    \n    return faces;\n}\n\n/*\n * Compute the simplicial star St(S) of the selected subset of simplices.\n *\n * Input: A MeshSubset object containing the indices of the currently active vertices, edges, and faces, respectively.\n * Returns: The star of the given subset.\n */\nMeshSubset SimplicialComplexOperators::star(const MeshSubset& subset) const {\n\n\n    MeshSubset star = subset;\n    \n    Vector<size_t> E0;\n    Vector<size_t> F0;\n    Vector<size_t> F1;\n\n    std::set<size_t> set_E0;\n    std::set<size_t> set_F0;\n    std::set<size_t> set_F1;\n\n\n    Vector<size_t> sub_verts = buildVertexVector(subset);\n    Vector<size_t> sub_edges = buildEdgeVector(subset);\n    Vector<size_t> sub_faces = buildFaceVector(subset);\n   \n    // Compute all connected vertices in the vectors\n    E0 = A0 * sub_verts;\n    F0 = A1 * A0 * sub_verts;\n    F1 = A1 * sub_edges;\n\n\n    // fill edge sets\n    for(int i =0; i<E0.rows(); ++i){\n        if(E0[i] != 0){\n            set_E0.insert(i);\n        }\n    } \n    // fill face sets\n    for(int i =0; i<F0.rows(); ++i){\n        if(F0[i] != 0){\n            set_F0.insert(i);\n        }\n        if(F1[i] != 0){\n            set_F1.insert(i);\n        }\n    }\n    \n    star.addEdges(set_E0);\n    star.addFaces(set_F0);\n    star.addFaces(set_F1);\n\n    return star;\n}\n\n\n/*\n * Compute the closure Cl(S) of the selected subset of simplices.\n *\n * Input: A MeshSubset object containing the indices of the currently active vertices, edges, and faces, respectively.\n * Returns: The closure of the given subset.\n */\nMeshSubset SimplicialComplexOperators::closure(const MeshSubset& subset) const {\n    \n    // final returned subset\n    MeshSubset closure = subset;\n    \n    // vectors for computation\n    Vector<size_t> V0;\n    Vector<size_t> E1;\n    Vector<size_t> V1;\n\n    // sets for storing indices\n    std::set<size_t> set_V0;\n    std::set<size_t> set_E1;\n    std::set<size_t> set_V1;\n\n    // Only need the subset edges and faces to compute the closure\n    Vector<size_t> sub_edges = buildEdgeVector(subset);\n    Vector<size_t> sub_faces = buildFaceVector(subset);\n    \n    // Add vertices that touch edges\n    V0 = A0.transpose()*sub_edges;\n    for(int i =0; i<V0.rows(); ++i){\n        if(V0[i] != 0){\n            set_V0.insert(i);\n        }\n    }\n    closure.addVertices(set_V0);\n\n\n    // Add edges that touch faces\n    E1 = A1.transpose()*sub_faces;\n    for(int i =0; i<E1.rows(); i++){\n        if(E1[i] != 0){\n            set_E1.insert(i);\n        }\n    }\n    closure.addEdges(set_E1);\n\n    // Add edges that touch faces\n    V1 =A0.transpose()*A1.transpose()*sub_faces;\n    for(int i =0; i<V1.rows(); i++){\n        if(V1[i] != 0){\n            set_V1.insert(i);\n        }\n    }\n    closure.addVertices(set_V1);\n\n\n    return closure;\n    }\n\n/*\n * Compute the link Lk(S) of the selected subset of simplices.\n *\n * Input: A MeshSubset object containing the indices of the currently active vertices, edges, and faces, respectively.\n * Returns: The link of the given subset.\n */\nMeshSubset SimplicialComplexOperators::link(const MeshSubset& subset) const {\n\n    // define Cl(St(subset)) and St(Cl(subset))\n    MeshSubset ClSt = closure(star(subset));\n    MeshSubset StCl = star(closure(subset));\n\n    // to remove StCl from ClSt we pick out the set of faces, edges and vertices of StCl\n    std::set<size_t> v = StCl.vertices;\n    std::set<size_t> e = StCl.edges;\n    std::set<size_t> f = StCl.faces;\n    \n    // initialize link as Cl(St(subset))\n    MeshSubset link = ClSt;\n    \n    link.deleteVertices(v);\n    link.deleteEdges(e);\n    link.deleteFaces(f);\n\n    return link;\n}\n\n/*\n * Return true if the selected subset is a simplicial complex, false otherwise.\n *\n * Input: A MeshSubset object containing the indices of the currently active vertices, edges, and faces, respectively.\n * Returns: True if given subset is a simplicial complex, false otherwise.\n */\nbool SimplicialComplexOperators::isComplex(const MeshSubset& subset) const {\n    \n    MeshSubset Cl;\n    Cl = closure(subset);\n    \n    // a potentially faster method that only compares sizes rather than each elt\n    size_t v0 = subset.vertices.size();\n    size_t e0 = subset.edges.size();\n    size_t f0 = subset.faces.size();\n    size_t v1 = Cl.vertices.size();\n    size_t e1 = Cl.edges.size();\n    size_t f1 = Cl.faces.size();\n\n    return (v0==v1 && e0==e1 && f0==f1);\n    //return closure==subset;\n\n}\n\n/*\n * Check if the given subset S is a pure simplicial complex. If so, return the degree of the complex. Otherwise, return\n * -1.\n *\n * Input: A MeshSubset object containing the indices of the currently active vertices, edges, and faces, respectively.\n * Returns: int representing the degree of the given complex (-1 if not pure)\n */\nint SimplicialComplexOperators::isPureComplex(const MeshSubset& subset) const {\n\n    if(isComplex(subset)){\n        Vector<size_t> sub_verts = buildVertexVector(subset);\n        Vector<size_t> sub_edges = buildEdgeVector(subset);\n        Vector<size_t> sub_faces = buildFaceVector(subset);\n\n        \n        if(subset.faces.size()!=0){\n            // make sure every edge and vertex is part of a face\n            Vector<size_t> new_edges = A1.transpose() * sub_faces;\n            for(int i =0; i<new_edges.rows(); i++){\n                if(new_edges[i] != 0){\n                    new_edges[i]=1;\n                }\n            }\n            Vector<size_t> new_verts = A0.transpose() * A1.transpose() * sub_faces;\n            for(int i =0; i<new_verts.rows(); i++){\n                if(new_verts[i] != 0){\n                    new_verts[i]=1; \n                }\n            }\n\n            if(new_edges == sub_edges && new_verts == sub_verts){\n                return 2;\n            }\n            else{\n                return -1;   \n            }\n        }\n\n        else if(subset.edges.size()!=0){\n            // make sure every vertex is part of an edge\n            Vector<size_t> new_verts = A0.transpose() * sub_edges;\n            for(int i =0; i<new_verts.rows(); i++){\n                if(new_verts[i] != 0){\n                    new_verts[i]=1;\n                }\n            }\n\n            if(new_verts == sub_verts){\n                return 1;\n            }\n            else{\n                return -1;\n            }\n        }\n\n        // if only vertices we are done\n        else{\n            return 0;\n        }\n    }\n    return -1;\n}\n\n/*\n * Compute the set of simplices contained in the boundary bd(S) of the selected subset S of simplices.\n *\n * Input: A MeshSubset object containing the indices of the currently active vertices, edges, and faces, respectively.\n * Returns: The boundary of the given subset.\n */\nMeshSubset SimplicialComplexOperators::boundary(const MeshSubset& subset) const {\n    \n    MeshSubset boundary;\n\n    // find simplicial complex degree\n    int deg = isPureComplex(subset);\n    \n    // if not pure complex, return empty placeholder\n    // (or error?)\n    if(deg == -1){\n        return boundary;\n    }\n    \n    // if subset is points, return empty placeholder\n    else if(deg == 0){\n        return boundary;    \n    }\n    \n    // 1-simplicial complex, return points connected to one edge\n    else if(deg ==1){\n        // only vertices that touch 1 edge\n        // first find vertex connection vector\n        Vector<size_t> edges = buildEdgeVector(subset);\n        Vector<size_t> vertices = A0.transpose()*edges;\n        std::set<size_t> int_verts_set;\n        \n        \n        // fill bd_edges_set and turn edges into boundary edges \n        for(int i =0; i<vertices.rows(); i++){\n            if(vertices[i] == 1){\n                int_verts_set.insert(i);\n            }\n        }\n        boundary.addVertices(int_verts_set);\n    }\n    \n    // since boundaries are simplicial complexes of degree one lower:\n    // we can only find the boundary edges, then take the closure at the end\n    else if(deg ==2){ \n        // first find edges connected to one face\n        // then take the closure\n        Vector<size_t> faces = buildFaceVector(subset);\n        Vector<size_t> edges = A1.transpose()*faces;\n        std::set<size_t> int_edges_set;\n        MeshSubset bdry_only_edges;\n        \n        \n        for(int i =0; i<edges.rows(); i++){\n            if(edges[i] == 1){\n                int_edges_set.insert(i);\n            }\n        }\n        bdry_only_edges.addEdges(int_edges_set);\n\n        boundary = closure(bdry_only_edges);\n        \n    }\n        \n    return boundary; \n    }\n", "meta": {"hexsha": "5e696c90b8478f8009d0059597239adb0e753707", "size": 13834, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "projects/simplicial-complex-operators/src/simplicial-complex-operators.cpp", "max_stars_repo_name": "shulkinj/ddg-local", "max_stars_repo_head_hexsha": "b594d39456af59e3e0207e19704ce2549afd0910", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "projects/simplicial-complex-operators/src/simplicial-complex-operators.cpp", "max_issues_repo_name": "shulkinj/ddg-local", "max_issues_repo_head_hexsha": "b594d39456af59e3e0207e19704ce2549afd0910", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "projects/simplicial-complex-operators/src/simplicial-complex-operators.cpp", "max_forks_repo_name": "shulkinj/ddg-local", "max_forks_repo_head_hexsha": "b594d39456af59e3e0207e19704ce2549afd0910", "max_forks_repo_licenses": ["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.6231263383, "max_line_length": 119, "alphanum_fraction": 0.6212230736, "num_tokens": 3357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442250928250375, "lm_q2_score": 0.727975460709318, "lm_q1q2_score": 0.4689800587498098}}
{"text": "/*********************************************************************\n* Software License Agreement (BSD License)\n*\n*  Copyright (c) 2013, 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: Bryant Gipson, Mark Moll */\n\n#include <ompl/base/spaces/RealVectorStateSpace.h>\n#include <ompl/geometric/planners/rrt/RRT.h>\n#include <ompl/geometric/planners/kpiece/KPIECE1.h>\n#include <ompl/geometric/planners/est/EST.h>\n#include <ompl/geometric/planners/prm/PRM.h>\n#include <ompl/geometric/planners/stride/STRIDE.h>\n#include <ompl/tools/benchmark/Benchmark.h>\n\n#include <boost/math/constants/constants.hpp>\n#include <boost/format.hpp>\n#include <fstream>\n\nunsigned ndim = 6;\nconst double edgeWidth = 0.1;\n\n// Only states near some edges of a hypercube are valid. The valid edges form a\n// narrow passage from (0,...,0) to (1,...,1). A state s is valid if there exists\n// a k s.t. (a) 0<=s[k]<=1, (b) for all i<k s[i]<=edgeWidth, and (c) for all i>k\n// s[i]>=1-edgewidth.\nbool isStateValid(const ompl::base::State *state)\n{\n    const ompl::base::RealVectorStateSpace::StateType *s\n        = static_cast<const ompl::base::RealVectorStateSpace::StateType*>(state);\n    bool foundMaxDim = false;\n\n    for (int i = ndim - 1; i >= 0; i--)\n        if (!foundMaxDim)\n        {\n            if ((*s)[i] > edgeWidth)\n                foundMaxDim = true;\n        }\n        else if ((*s)[i] < (1. - edgeWidth))\n            return false;\n        return true;\n}\n\nvoid addPlanner(ompl::tools::Benchmark& benchmark, ompl::base::PlannerPtr planner, double range)\n{\n    ompl::base::ParamSet& params = planner->params();\n    if (params.hasParam(std::string(\"range\")))\n        params.setParam(std::string(\"range\"), boost::lexical_cast<std::string>(range));\n    benchmark.addPlanner(planner);\n}\n\nint main(int argc, char **argv)\n{\n    if(argc > 1)\n        ndim = boost::lexical_cast<size_t>(argv[1]);\n\n    double range = edgeWidth * 0.5;\n    ompl::base::StateSpacePtr space(new ompl::base::RealVectorStateSpace(ndim));\n    ompl::base::RealVectorBounds bounds(ndim);\n    ompl::geometric::SimpleSetup ss(space);\n    ompl::base::ScopedState<> start(space), goal(space);\n\n    bounds.setLow(0.);\n    bounds.setHigh(1.);\n    space->as<ompl::base::RealVectorStateSpace>()->setBounds(bounds);\n    ss.setStateValidityChecker(&isStateValid);\n    ss.getSpaceInformation()->setStateValidityCheckingResolution(0.001);\n    for(unsigned int i = 0; i < ndim; ++i)\n    {\n        start[i] = 0.;\n        goal[i] = 1.;\n    }\n    ss.setStartAndGoalStates(start, goal);\n\n    // by default, use the Benchmark class\n    double runtime_limit = 1000, memory_limit = 4096;\n    int run_count = 20;\n    ompl::tools::Benchmark::Request request(runtime_limit, memory_limit, run_count);\n    ompl::tools::Benchmark b(ss, \"HyperCube\");\n    b.addExperimentParameter(\"num_dims\", \"INTEGER\", boost::lexical_cast<std::string>(ndim));\n\n    addPlanner(b, ompl::base::PlannerPtr(new ompl::geometric::STRIDE(ss.getSpaceInformation())), range);\n    addPlanner(b, ompl::base::PlannerPtr(new ompl::geometric::EST(ss.getSpaceInformation())), range);\n    addPlanner(b, ompl::base::PlannerPtr(new ompl::geometric::KPIECE1(ss.getSpaceInformation())), range);\n    addPlanner(b, ompl::base::PlannerPtr(new ompl::geometric::RRT(ss.getSpaceInformation())), range);\n    addPlanner(b, ompl::base::PlannerPtr(new ompl::geometric::PRM(ss.getSpaceInformation())), range);\n    b.benchmark(request);\n    b.saveResultsToFile(boost::str(boost::format(\"hypercube_%i.log\") % ndim).c_str());\n\n    exit(0);\n}\n", "meta": {"hexsha": "9eee7b92793baec88eb78147dc3a87974d1b7e87", "size": 5099, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "demos/HypercubeBenchmark.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": "demos/HypercubeBenchmark.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": "demos/HypercubeBenchmark.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": 42.1404958678, "max_line_length": 105, "alphanum_fraction": 0.6824867621, "num_tokens": 1301, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754371026367, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.46898004354179335}}
{"text": "#include <iostream>\n#include <cmath>\n#include <algorithm>\n#include <vector>\n#include <boost/multiprecision/cpp_int.hpp>\nusing namespace boost::multiprecision;\nusing namespace std;\nint main() {\n    cpp_int s, p; cin >> s >> p;\n    for (cpp_int i = 1; i <= sqrt(p); i++) {\n        if (p % i == 0) {\n            if (i + p / i == s) {\n                cout << \"Yes\" << endl;\n                return 0;\n            }\n        }\n    }\n    cout << \"No\" << endl;\n    return 0;\n}\n", "meta": {"hexsha": "7be0d5fb57c1522b02a8a6806c02cb1169e5e5bb", "size": 468, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AtCoder/arc108/a/main.cpp", "max_stars_repo_name": "H-Tatsuhiro/Com_Pro-Cpp", "max_stars_repo_head_hexsha": "fd79f7821a76b11f4a6f83bbb26a034db577a877", "max_stars_repo_licenses": ["MIT"], "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/arc108/a/main.cpp", "max_issues_repo_name": "H-Tatsuhiro/Com_Pro-Cpp", "max_issues_repo_head_hexsha": "fd79f7821a76b11f4a6f83bbb26a034db577a877", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-10-19T08:47:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T05:23:56.000Z", "max_forks_repo_path": "AtCoder/arc108/a/main.cpp", "max_forks_repo_name": "H-Tatsuhiro/Com_Pro-Cpp", "max_forks_repo_head_hexsha": "fd79f7821a76b11f4a6f83bbb26a034db577a877", "max_forks_repo_licenses": ["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.2857142857, "max_line_length": 44, "alphanum_fraction": 0.4871794872, "num_tokens": 130, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681195338728, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.4689745565052669}}
{"text": "/*****************************************************************************\n*\n* Rokko: Integrated Interface for libraries of eigenvalue decomposition\n*\n* Copyright (C) 2014-2015 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#include <rokko/utility/sort_eigenpairs.hpp>\n\n#include <algorithm>\n#include <boost/iterator/counting_iterator.hpp>\n\n#define BOOST_TEST_MODULE test_sort_eigenpairs\n#ifndef BOOST_TEST_DYN_LINK\n#include <boost/test/included/unit_test.hpp>\n#else\n#include <boost/test/unit_test.hpp>\n#endif\n\n#define make_test(major, ascending) \\\n  int num = 10;\\\n  std::vector<int> index;\\\n  std::copy(boost::counting_iterator<int>(0),\\\n            boost::counting_iterator<int>(num),\\\n            back_inserter(index));\\\n  std::random_shuffle(index.begin(), index.end());\\\n  rokko::localized_vector<double> eigvals(num), eigvals_sorted(num);   \\\n  rokko::localized_matrix<double, major > eigvecs(num, num), eigvecs_sorted(num, num); \\\n  for(int i=0; i<num; ++i){\\\n    eigvals(i) = 1.0*index[i];\\\n    for(int j=0; j<num; ++j){\\\n      if(eigvecs.is_row_major()){\\\n        eigvecs(i,j) = eigvals(i);\\\n      }else{\\\n        eigvecs(j,i) = eigvals(i);\\\n      }\\\n    }\\\n  }\\\n  rokko::sort_eigenpairs(eigvals, eigvecs, eigvals_sorted, eigvecs_sorted, ascending);\\\n  for(int i=0; i<num; ++i){\\\n    std::cout << \"dim: \" << i << std::endl;\\\n    double e = ascending ? 1.0 * i : 1.0*(num-i-1);\\\n    if(eigvecs.is_row_major()){\\\n      BOOST_CHECK_EQUAL( eigvals_sorted(i), e);\\\n      BOOST_CHECK_EQUAL( eigvecs_sorted(i,0), e);\\\n      BOOST_CHECK_EQUAL( eigvecs_sorted(i,1), e);\\\n    }else{\\\n      BOOST_CHECK_EQUAL( eigvals_sorted(i), e);\\\n      BOOST_CHECK_EQUAL( eigvecs_sorted(0,i), e);\\\n      BOOST_CHECK_EQUAL( eigvecs_sorted(1,i), e);\\\n    }\\\n  }\n\nBOOST_AUTO_TEST_CASE(test_sort_eigenpairs) {\n  {\n    std::cout << \"row_major, ascending order\\n\";\n    make_test(rokko::matrix_row_major, true)\n  }\n  {\n    std::cout << \"row_major, descending order\\n\";\n    make_test(rokko::matrix_row_major, false)\n  }\n  {\n    std::cout << \"col_major, ascending order\\n\";\n    make_test(rokko::matrix_col_major, true)\n  }\n  {\n    std::cout << \"col_major, descending order\\n\";\n    make_test(rokko::matrix_col_major, false)\n  }\n}\n\n#undef make_test\n", "meta": {"hexsha": "e051e6db2cfbea77406478e0f26954f568fa0053", "size": 2469, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/sort_eigenpairs.cpp", "max_stars_repo_name": "wistaria/rokko", "max_stars_repo_head_hexsha": "7cd9d5155e82f038039a46c1dc8f382b3fe7e2b7", "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": "test/sort_eigenpairs.cpp", "max_issues_repo_name": "wistaria/rokko", "max_issues_repo_head_hexsha": "7cd9d5155e82f038039a46c1dc8f382b3fe7e2b7", "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/sort_eigenpairs.cpp", "max_forks_repo_name": "wistaria/rokko", "max_forks_repo_head_hexsha": "7cd9d5155e82f038039a46c1dc8f382b3fe7e2b7", "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.6538461538, "max_line_length": 88, "alphanum_fraction": 0.6221142163, "num_tokens": 671, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.6584175072643415, "lm_q1q2_score": 0.4689461393400446}}
{"text": "// Copyright John Maddock 2006, 2007.\n// Copyright Paul A. Bristow 2007.\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_CAUCHY_HPP\n#define BOOST_STATS_CAUCHY_HPP\n\n#ifdef _MSC_VER\n#pragma warning(push)\n#pragma warning(disable : 4127) // conditional expression is constant\n#endif\n\n#include <boost/math/distributions/fwd.hpp>\n#include <boost/math/constants/constants.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#include <utility>\n\nnamespace boost{ namespace math\n{\n\ntemplate <class RealType, class Policy>\nclass cauchy_distribution;\n\nnamespace detail\n{\n\ntemplate <class RealType, class Policy>\nRealType cdf_imp(const cauchy_distribution<RealType, Policy>& dist, const RealType& x, bool complement)\n{\n   //\n   // This calculates the cdf of the Cauchy distribution and/or its complement.\n   //\n   // The usual formula for the Cauchy cdf is:\n   //\n   // cdf = 0.5 + atan(x)/pi\n   //\n   // But that suffers from cancellation error as x -> -INF.\n   //\n   // Recall that for x < 0:\n   //\n   // atan(x) = -pi/2 - atan(1/x)\n   //\n   // Substituting into the above we get:\n   //\n   // CDF = -atan(1/x)  ; x < 0\n   //\n   // So the proceedure is to calculate the cdf for -fabs(x)\n   // using the above formula, and then subtract from 1 when required\n   // to get the result.\n   //\n   BOOST_MATH_STD_USING // for ADL of std functions\n   static const char* function = \"boost::math::cdf(cauchy<%1%>&, %1%)\";\n   RealType result = 0;\n   RealType location = dist.location();\n   RealType scale = dist.scale();\n   if(false == detail::check_location(function, location, &result, Policy()))\n   {\n     return result;\n   }\n   if(false == detail::check_scale(function, scale, &result, Policy()))\n   {\n      return result;\n   }\n   if(std::numeric_limits<RealType>::has_infinity && x == std::numeric_limits<RealType>::infinity())\n   { // cdf +infinity is unity.\n     return static_cast<RealType>((complement) ? 0 : 1);\n   }\n   if(std::numeric_limits<RealType>::has_infinity && x == -std::numeric_limits<RealType>::infinity())\n   { // cdf -infinity is zero.\n     return static_cast<RealType>((complement) ? 1 : 0);\n   }\n   if(false == detail::check_x(function, x, &result, Policy()))\n   { // Catches x == NaN\n      return result;\n   }\n   RealType mx = -fabs((x - location) / scale); // scale is > 0\n   if(mx > -tools::epsilon<RealType>() / 8)\n   {  // special case first: x extremely close to location.\n      return 0.5;\n   }\n   result = -atan(1 / mx) / constants::pi<RealType>();\n   return (((x > location) != complement) ? 1 - result : result);\n} // cdf\n\ntemplate <class RealType, class Policy>\nRealType quantile_imp(\n      const cauchy_distribution<RealType, Policy>& dist,\n      const RealType& p,\n      bool complement)\n{\n   // This routine implements the quantile for the Cauchy distribution,\n   // the value p may be the probability, or its complement if complement=true.\n   //\n   // The procedure first performs argument reduction on p to avoid error\n   // when calculating the tangent, then calulates the distance from the\n   // mid-point of the distribution.  This is either added or subtracted\n   // from the location parameter depending on whether `complement` is true.\n   //\n   static const char* function = \"boost::math::quantile(cauchy<%1%>&, %1%)\";\n   BOOST_MATH_STD_USING // for ADL of std functions\n\n   RealType result = 0;\n   RealType location = dist.location();\n   RealType scale = dist.scale();\n   if(false == detail::check_location(function, location, &result, Policy()))\n   {\n     return result;\n   }\n   if(false == detail::check_scale(function, scale, &result, Policy()))\n   {\n      return result;\n   }\n   if(false == detail::check_probability(function, p, &result, Policy()))\n   {\n      return result;\n   }\n   // Special cases:\n   if(p == 1)\n   {\n      return (complement ? -1 : 1) * policies::raise_overflow_error<RealType>(function, 0, Policy());\n   }\n   if(p == 0)\n   {\n      return (complement ? 1 : -1) * policies::raise_overflow_error<RealType>(function, 0, Policy());\n   }\n\n   RealType P = p - floor(p);   // argument reduction of p:\n   if(P > 0.5)\n   {\n      P = P - 1;\n   }\n   if(P == 0.5)   // special case:\n   {\n      return location;\n   }\n   result = -scale / tan(constants::pi<RealType>() * P);\n   return complement ? RealType(location - result) : RealType(location + result);\n} // quantile\n\n} // namespace detail\n\ntemplate <class RealType = double, class Policy = policies::policy<> >\nclass cauchy_distribution\n{\npublic:\n   typedef RealType value_type;\n   typedef Policy policy_type;\n\n   cauchy_distribution(RealType location = 0, RealType scale = 1)\n      : m_a(location), m_hg(scale)\n   {\n    static const char* function = \"boost::math::cauchy_distribution<%1%>::cauchy_distribution\";\n     RealType result;\n     detail::check_location(function, location, &result, Policy());\n     detail::check_scale(function, scale, &result, Policy());\n   } // cauchy_distribution\n\n   RealType location()const\n   {\n      return m_a;\n   }\n   RealType scale()const\n   {\n      return m_hg;\n   }\n\nprivate:\n   RealType m_a;    // The location, this is the median of the distribution.\n   RealType m_hg;   // The scale )or shape), this is the half width at half height.\n};\n\ntypedef cauchy_distribution<double> cauchy;\n\ntemplate <class RealType, class Policy>\ninline const std::pair<RealType, RealType> range(const cauchy_distribution<RealType, Policy>&)\n{ // Range of permissible values for random variable x.\n  if (std::numeric_limits<RealType>::has_infinity)\n  { \n     return std::pair<RealType, RealType>(-std::numeric_limits<RealType>::infinity(), std::numeric_limits<RealType>::infinity()); // - to + infinity.\n  }\n  else\n  { // Can only use max_value.\n   using boost::math::tools::max_value;\n   return std::pair<RealType, RealType>(-max_value<RealType>(), max_value<RealType>()); // - to + max.\n  }\n}\n\ntemplate <class RealType, class Policy>\ninline const std::pair<RealType, RealType> support(const cauchy_distribution<RealType, Policy>& )\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  if (std::numeric_limits<RealType>::has_infinity)\n  { \n     return std::pair<RealType, RealType>(-std::numeric_limits<RealType>::infinity(), std::numeric_limits<RealType>::infinity()); // - to + infinity.\n  }\n  else\n  { // Can only use max_value.\n     using boost::math::tools::max_value;\n     return std::pair<RealType, RealType>(-tools::max_value<RealType>(), max_value<RealType>()); // - to + max.\n  }\n}\n\ntemplate <class RealType, class Policy>\ninline RealType pdf(const cauchy_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(cauchy<%1%>&, %1%)\";\n   RealType result = 0;\n   RealType location = dist.location();\n   RealType scale = dist.scale();\n   if(false == detail::check_scale(\"boost::math::pdf(cauchy<%1%>&, %1%)\", scale, &result, Policy()))\n   {\n      return result;\n   }\n   if(false == detail::check_location(\"boost::math::pdf(cauchy<%1%>&, %1%)\", location, &result, Policy()))\n   {\n      return result;\n   }\n   if((boost::math::isinf)(x))\n   {\n     return 0; // pdf + and - infinity is zero.\n   }\n   // These produce 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\n   if(false == detail::check_x(function, x, &result, Policy()))\n   { // Catches x = NaN\n      return result;\n   }\n\n   RealType xs = (x - location) / scale;\n   result = 1 / (constants::pi<RealType>() * scale * (1 + xs * xs));\n   return result;\n} // pdf\n\ntemplate <class RealType, class Policy>\ninline RealType cdf(const cauchy_distribution<RealType, Policy>& dist, const RealType& x)\n{\n   return detail::cdf_imp(dist, x, false);\n} // cdf\n\ntemplate <class RealType, class Policy>\ninline RealType quantile(const cauchy_distribution<RealType, Policy>& dist, const RealType& p)\n{\n   return detail::quantile_imp(dist, p, false);\n} // quantile\n\ntemplate <class RealType, class Policy>\ninline RealType cdf(const complemented2_type<cauchy_distribution<RealType, Policy>, RealType>& c)\n{\n   return detail::cdf_imp(c.dist, c.param, true);\n} //  cdf complement\n\ntemplate <class RealType, class Policy>\ninline RealType quantile(const complemented2_type<cauchy_distribution<RealType, Policy>, RealType>& c)\n{\n   return detail::quantile_imp(c.dist, c.param, true);\n} // quantile complement\n\ntemplate <class RealType, class Policy>\ninline RealType mean(const cauchy_distribution<RealType, Policy>&)\n{  // There is no mean:\n   typedef typename Policy::assert_undefined_type assert_type;\n   BOOST_STATIC_ASSERT(assert_type::value == 0);\n\n   return policies::raise_domain_error<RealType>(\n      \"boost::math::mean(cauchy<%1%>&)\",\n      \"The Cauchy distribution does not have a mean: \"\n      \"the only possible return value is %1%.\",\n      std::numeric_limits<RealType>::quiet_NaN(), Policy());\n}\n\ntemplate <class RealType, class Policy>\ninline RealType variance(const cauchy_distribution<RealType, Policy>& /*dist*/)\n{\n   // There is no variance:\n   typedef typename Policy::assert_undefined_type assert_type;\n   BOOST_STATIC_ASSERT(assert_type::value == 0);\n\n   return policies::raise_domain_error<RealType>(\n      \"boost::math::variance(cauchy<%1%>&)\",\n      \"The Cauchy distribution does not have a variance: \"\n      \"the only possible return value is %1%.\",\n      std::numeric_limits<RealType>::quiet_NaN(), Policy());\n}\n\ntemplate <class RealType, class Policy>\ninline RealType mode(const cauchy_distribution<RealType, Policy>& dist)\n{\n   return dist.location();\n}\n\ntemplate <class RealType, class Policy>\ninline RealType median(const cauchy_distribution<RealType, Policy>& dist)\n{\n   return dist.location();\n}\ntemplate <class RealType, class Policy>\ninline RealType skewness(const cauchy_distribution<RealType, Policy>& /*dist*/)\n{\n   // There is no skewness:\n   typedef typename Policy::assert_undefined_type assert_type;\n   BOOST_STATIC_ASSERT(assert_type::value == 0);\n\n   return policies::raise_domain_error<RealType>(\n      \"boost::math::skewness(cauchy<%1%>&)\",\n      \"The Cauchy distribution does not have a skewness: \"\n      \"the only possible return value is %1%.\",\n      std::numeric_limits<RealType>::quiet_NaN(), Policy()); // infinity?\n}\n\ntemplate <class RealType, class Policy>\ninline RealType kurtosis(const cauchy_distribution<RealType, Policy>& /*dist*/)\n{\n   // There is no kurtosis:\n   typedef typename Policy::assert_undefined_type assert_type;\n   BOOST_STATIC_ASSERT(assert_type::value == 0);\n\n   return policies::raise_domain_error<RealType>(\n      \"boost::math::kurtosis(cauchy<%1%>&)\",\n      \"The Cauchy distribution does not have a kurtosis: \"\n      \"the only possible return value is %1%.\",\n      std::numeric_limits<RealType>::quiet_NaN(), Policy());\n}\n\ntemplate <class RealType, class Policy>\ninline RealType kurtosis_excess(const cauchy_distribution<RealType, Policy>& /*dist*/)\n{\n   // There is no kurtosis excess:\n   typedef typename Policy::assert_undefined_type assert_type;\n   BOOST_STATIC_ASSERT(assert_type::value == 0);\n\n   return policies::raise_domain_error<RealType>(\n      \"boost::math::kurtosis_excess(cauchy<%1%>&)\",\n      \"The Cauchy distribution does not have a kurtosis: \"\n      \"the only possible return value is %1%.\",\n      std::numeric_limits<RealType>::quiet_NaN(), Policy());\n}\n\n} // namespace math\n} // namespace boost\n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n\n// This include must be at the end, *after* the accessors\n// for this distribution have been defined, in order to\n// keep compilers that support two-phase lookup happy.\n#include <boost/math/distributions/detail/derived_accessors.hpp>\n\n#endif // BOOST_STATS_CAUCHY_HPP\n", "meta": {"hexsha": "0e8c1deeda83117e0fa6c3b3b33f7feb89b681aa", "size": 12097, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/boost/math/distributions/cauchy.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/math/distributions/cauchy.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/math/distributions/cauchy.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": 33.3250688705, "max_line_length": 149, "alphanum_fraction": 0.684301893, "num_tokens": 3153, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.4689461393400446}}
{"text": "//\n// Created by mathis on 28/02/2020.\n//\n\n#ifndef DAFT_ENGINE_ADAPTERS_HPP\n#define DAFT_ENGINE_ADAPTERS_HPP\n\n//#include <Eigen/Eigen>\n#include <Eigen/Eigen>\n#include <glm/glm.hpp>\n\ntemplate <int m, int n>\ninline glm::mat<m, n, float> toGlm( const Eigen::Matrix<float, m, n>& mat ) {\n    glm::mat<m, n, float> ret;\n    for ( int i = 0; i < m; ++i )\n    {\n        for ( int j = 0; j < n; ++j )\n        {\n            ret[j][i] = mat( i, j );\n        }\n    }\n    return ret;\n}\n\ntemplate <int m>\ninline glm::vec<m, float> toGlm( const Eigen::Vector<float, m>& vec ) {\n    glm::vec<m, float> ret;\n    for ( int i = 0; i < m; ++i )\n    {\n        ret[i] = vec( i );\n    }\n    return ret;\n}\n\ntemplate <int m, int n>\ninline Eigen::Matrix<float, m, n> toEigen( const glm::mat<m, n, float>& mat ) {\n    Eigen::Matrix<float, m, n> ret;\n    for ( int i = 0; i < m; ++i )\n    {\n        for ( int j = 0; j < n; ++j )\n        {\n            ret( i, j ) = mat[j][i];\n        }\n    }\n    return ret;\n}\n\ntemplate <int m>\ninline Eigen::Vector<float, m> toEigen( const glm::vec<m, float>& vec ) {\n    Eigen::Vector<float, m> ret;\n    for ( int i = 0; i < m; ++i )\n    {\n        ret( i ) = vec[i];\n    }\n    return ret;\n}\n\n#endif // DAFT_ENGINE_ADAPTERS_HPP\n", "meta": {"hexsha": "2515c020991445edc352e32bea25d1a681d73f25", "size": 1235, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Utils/adapters.hpp", "max_stars_repo_name": "DaftMat/Draft-Engine", "max_stars_repo_head_hexsha": "395b22c454a4c198824b158dbe8778babb4e11c6", "max_stars_repo_licenses": ["MIT"], "max_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/adapters.hpp", "max_issues_repo_name": "DaftMat/Draft-Engine", "max_issues_repo_head_hexsha": "395b22c454a4c198824b158dbe8778babb4e11c6", "max_issues_repo_licenses": ["MIT"], "max_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/adapters.hpp", "max_forks_repo_name": "DaftMat/Draft-Engine", "max_forks_repo_head_hexsha": "395b22c454a4c198824b158dbe8778babb4e11c6", "max_forks_repo_licenses": ["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.9322033898, "max_line_length": 79, "alphanum_fraction": 0.5101214575, "num_tokens": 413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.4689461393400445}}
{"text": "/*\n   For more information, please see: http://software.sci.utah.edu\n\n   The MIT License\n\n   Copyright (c) 2020 Scientific Computing and Imaging Institute,\n   University of Utah.\n\n   Permission is hereby granted, free of charge, to any person obtaining a\n   copy of this software and associated documentation files (the \"Software\"),\n   to deal in the Software without restriction, including without limitation\n   the rights to use, copy, modify, merge, publish, distribute, sublicense,\n   and/or sell copies of the Software, and to permit persons to whom the\n   Software is furnished to do so, subject to the following conditions:\n\n   The above copyright notice and this permission notice shall be included\n   in all copies or substantial portions of the Software.\n\n   THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n   DEALINGS IN THE SOFTWARE.\n*/\n\n\n#include <gtest/gtest.h>\n#include <gmock/gmock.h>\n\n#include <fstream>\n#include <Core/Algorithms/Math/ParallelAlgebra/ParallelLinearAlgebra.h>\n#include <Core/Datatypes/DenseMatrix.h>\n#include <Core/Datatypes/DenseColumnMatrix.h>\n#include <Core/Datatypes/SparseRowMatrix.h>\n#include <Core/Datatypes/MatrixComparison.h>\n#include <Core/Datatypes/MatrixTypeConversions.h>\n#include <Core/Datatypes/MatrixIO.h>\n#include <Testing/Utils/MatrixTestUtilities.h>\n#include <boost/thread/thread.hpp>\n\nusing namespace SCIRun::Core::Datatypes;\nusing namespace SCIRun::Core::Algorithms::Math;\nusing namespace SCIRun::Core::Algorithms;\nusing namespace SCIRun::TestUtils;\nusing namespace SCIRun;\nusing namespace ::testing;\n\nnamespace\n{\n  const int size = 1000;\n  SparseRowMatrixHandle matrix1()\n  {\n    SparseRowMatrixHandle m(boost::make_shared<SparseRowMatrix>(size,size));\n    m->insert(0,0) = 1;\n    m->insert(1,2) = -1;\n    m->insert(size-1,size-1) = 2;\n    return m;\n  }\n\n  DenseColumnMatrixHandle vector1()\n  {\n    DenseColumnMatrixHandle v(boost::make_shared<DenseColumnMatrix>(size));\n\t  v->setZero();\n//    *v << 1, 2, 4;\n\t  (*v)[0] = 1;\n  \t(*v)[1] = 2;\n\t  (*v)[2] = 4;\n    (*v)[size-1] = -1;\n    return v;\n  }\n\n  DenseColumnMatrixHandle vector2()\n  {\n    DenseColumnMatrixHandle v(boost::make_shared<DenseColumnMatrix>(size));\n    v->setZero();\n    //*v << -1, -2, -4;\n\t  (*v)[0] = -1;\n\t  (*v)[1] = -2;\n\t  (*v)[2] = -4;\n    (*v)[300] = -300;\n    (*v)[size/2] = -6;\n    (*v)[size/2 + 1] = -7;\n    (*v)[600] = -600;\n    (*v)[size-1] = 1;\n    return v;\n  }\n\n  DenseColumnMatrixHandle vector3()\n  {\n    DenseColumnMatrixHandle v(boost::make_shared<DenseColumnMatrix>(size));\n    v->setZero();\n   // *v << 0, 1, 0;\n\t  (*v)[0] = 0;\n\t  (*v)[1] = 1;\n\t  (*v)[2] = 0;\n    (*v)[size-1] = -7;\n    return v;\n  }\n\n  SolverInputs getDummySystem()\n  {\n    SolverInputs system;\n    system.A = matrix1();\n    system.b = vector1();\n    system.x = vector2();\n    system.x0 = vector3();\n    return system;\n  }\n\n  const int SINGLE_THREADED_TEST_NUMPROCS = 1;\n  const int SINGLE_THREADED_TEST_PROC_INDEX = 0;\n}\n\nTEST(ParallelLinearAlgebraTests, CanCreateEmptyParallelVector)\n{\n  ParallelLinearAlgebraSharedData data(getDummySystem(), SINGLE_THREADED_TEST_NUMPROCS);\n  ParallelLinearAlgebra pla(data, SINGLE_THREADED_TEST_PROC_INDEX);\n\n  ParallelLinearAlgebra::ParallelVector v;\n  EXPECT_TRUE(pla.new_vector(v));\n\n  EXPECT_EQ(size, v.size_);\n}\n\nTEST(ParallelLinearAlgebraTests, CanCreateParallelVectorFromVectorAsShallowReference)\n{\n  ParallelLinearAlgebraSharedData data(getDummySystem(), 1);\n  ParallelLinearAlgebra pla(data, 0);\n\n  ParallelLinearAlgebra::ParallelVector v;\n  auto v1 = vector1();\n  EXPECT_TRUE(pla.add_vector(v1, v));\n\n  EXPECT_EQ(v1->nrows(), v.size_);\n  for (size_t i = 0; i < size; ++i)\n    EXPECT_EQ((*v1)[i], v.data_[i]);\n\n  EXPECT_EQ(0, (*v1)[100]);\n  v.data_[100]++;\n  EXPECT_EQ(1, (*v1)[100]);\n}\n\nTEST(ParallelLinearAlgebraTests, CanCopyParallelSparseMatrixAsShallowReference)\n{\n  ParallelLinearAlgebraSharedData data(getDummySystem(), 1);\n  ParallelLinearAlgebra pla(data, 0);\n\n  ParallelLinearAlgebra::ParallelMatrix m;\n  auto m1 = matrix1();\n  EXPECT_TRUE(pla.add_matrix(m1, m));\n\n  EXPECT_EQ(m1->nrows(), m.m_);\n  EXPECT_EQ(m1->ncols(), m.n_);\n  EXPECT_EQ(m1->nonZeros(), m.nnz_);\n  EXPECT_EQ(m1->coeff(1,2), m.data_[1]);\n\n  EXPECT_EQ(1, m1->coeff(0,0));\n  m.data_[0]++;\n  EXPECT_EQ(2, m1->coeff(0,0));\n}\n\nTEST(ParallelLinearAlgebraTests, CanCopyContentsOfVector)\n{\n  ParallelLinearAlgebraSharedData data(getDummySystem(), 1);\n  ParallelLinearAlgebra pla(data, 0);\n\n  ParallelLinearAlgebra::ParallelVector v1;\n  pla.new_vector(v1);\n\n  ParallelLinearAlgebra::ParallelVector v2;\n  auto vec2 = vector2();\n  pla.add_vector(vec2, v2);\n\n  pla.copy(v2, v1);\n\n  EXPECT_EQ(v1.size_, v2.size_);\n  for (size_t i = 0; i < size; ++i)\n  {\n    EXPECT_EQ(v2.data_[i], v1.data_[i]);\n  }\n  v1.data_[7]++;\n  EXPECT_NE(v1.data_[7], v2.data_[7]);\n}\n\nstruct Copy\n{\n  Copy(ParallelLinearAlgebraSharedData& data, ParallelLinearAlgebra::ParallelVector& v1,\n    ParallelLinearAlgebra::ParallelVector& v2, int proc, DenseColumnMatrixHandle vec2copy) :\n    data_(data), proc_(proc), v1_(v1), v2_(v2), vec2copy_(vec2copy) {}\n\n  ParallelLinearAlgebraSharedData& data_;\n  int proc_;\n  ParallelLinearAlgebra::ParallelVector& v1_;\n  ParallelLinearAlgebra::ParallelVector& v2_;\n  DenseColumnMatrixHandle vec2copy_;\n\n  void operator()()\n  {\n    ParallelLinearAlgebra pla(data_, proc_);\n    pla.new_vector(v1_);\n    pla.add_vector(vec2copy_, v2_);\n    pla.copy(v2_, v1_);\n  }\n};\n\nTEST(ParallelLinearAlgebraTests, CanCopyContentsOfVectorMulti)\n{\n\tconst int NUM_THREADS = 2;\n  ParallelLinearAlgebraSharedData data(getDummySystem(), NUM_THREADS);\n\n  ParallelLinearAlgebra::ParallelVector v1, v2;\n\n  auto vec2copy = vector2();\n  {\n\t  Copy c0(data, v1, v2, 0, vec2copy);\n\t  Copy c1(data, v1, v2, 1, vec2copy);\n\n\t  boost::thread t1 = boost::thread(boost::ref(c0));\n\t  boost::thread t2 = boost::thread(boost::ref(c1));\n\t  t1.join();\n\t  t2.join();\n  }\n\n  EXPECT_EQ(v1.size_, v2.size_);\n  for (size_t i = 0; i < size; ++i)\n  {\n    EXPECT_EQ(v2.data_[i], v1.data_[i]);\n  }\n  v1.data_[7]++;\n  EXPECT_NE(v1.data_[7], v2.data_[7]);\n}\n\n\nTEST(ParallelArithmeticTests, CanComputeMaxOfVector)\n{\n  ParallelLinearAlgebraSharedData data(getDummySystem(), SINGLE_THREADED_TEST_NUMPROCS);\n  ParallelLinearAlgebra pla(data, SINGLE_THREADED_TEST_PROC_INDEX);\n\n  ParallelLinearAlgebra::ParallelVector v1;\n  auto vec1 = vector1();\n  pla.add_vector(vec1, v1);\n  double max1 = pla.max(v1);\n  ParallelLinearAlgebra::ParallelVector v2;\n  auto vec2 = vector2();\n  pla.add_vector(vec2, v2);\n  double max2 = pla.max(v2);\n\n  EXPECT_EQ(4, max1);\n  EXPECT_EQ(1, max2);\n}\n\nTEST(ParallelArithmeticTests, CanTakeAbsoluteValueOfDiagonal)\n{\n  ParallelLinearAlgebraSharedData data(getDummySystem(),1);\n  ParallelLinearAlgebra pla(data,0);\n\n  ParallelLinearAlgebra::ParallelVector v1;\n  auto vec1 = vector1();\n  vec1->setZero();\n  pla.add_vector(vec1, v1);\n\n  ParallelLinearAlgebra::ParallelMatrix m1;\n  auto mat1 = matrix1();\n  pla.add_matrix(mat1 , m1);\n\n  pla.absdiag(m1, v1);\n  for (size_t i = 0; i < size; ++i)\n  {\n\t  EXPECT_GE(v1.data_[i],0);\n  }\n  EXPECT_EQ(1,v1.data_[0]);\n  EXPECT_EQ(0,v1.data_[2]);\n  EXPECT_EQ(2,v1.data_[size-1]);\n}\n\nstruct absdiag\n{\n   absdiag(ParallelLinearAlgebraSharedData& data, ParallelLinearAlgebra::ParallelMatrix& m1,\n     ParallelLinearAlgebra::ParallelVector& v2, int proc, DenseColumnMatrixHandle dcmHandle,\n     SparseRowMatrixHandle srmHandle) : data_(data), proc_(proc), m1_(m1), v2_(v2),\n     dcmHandle_(dcmHandle), srmHandle_(srmHandle) {}\n\n  ParallelLinearAlgebraSharedData& data_;\n  int proc_;\n  ParallelLinearAlgebra::ParallelMatrix& m1_;\n  ParallelLinearAlgebra::ParallelVector& v2_;\n  DenseColumnMatrixHandle dcmHandle_;\n  SparseRowMatrixHandle srmHandle_;\n\n  void operator()()\n  {\n    ParallelLinearAlgebra pla(data_, proc_);\n    pla.add_matrix(srmHandle_, m1_);\n\n    pla.new_vector(v2_);\n    pla.add_vector(dcmHandle_, v2_);\n\n    pla.absdiag(m1_, v2_);\n  }\n};\n\nTEST(ParallelArithmeticTests, CanTakeAbsoluteValueOfDiagonalMulti)\n{\n  const int NUM_THREADS = 2;\n  ParallelLinearAlgebraSharedData data(getDummySystem(), NUM_THREADS);\n\n  ParallelLinearAlgebra::ParallelVector v2;\n  ParallelLinearAlgebra::ParallelMatrix m1;\n\n  auto vec2 = vector2();\n  auto mat1 = matrix1();\n\n  {\n\t  absdiag diag0(data, m1, v2, 0, vec2, mat1);\n\t  absdiag diag1(data, m1, v2, 1, vec2, mat1);\n\n\t  boost::thread t1 = boost::thread(boost::ref(diag0));\n\t  boost::thread t2 = boost::thread(boost::ref(diag1));\n\t  t1.join();\n\t  t2.join();\n  }\n\n  EXPECT_EQ( v2.size_, size );\n  for (size_t i = 0; i < size; ++i)\n  {\n    EXPECT_GE(v2.data_[i] , 0);\n  }\n}\n\nstruct max\n{\n  max(ParallelLinearAlgebraSharedData& data, ParallelLinearAlgebra::ParallelVector& v1,\n     int proc, DenseColumnMatrixHandle dcmHandle) :\n      data_(data), proc_(proc), v1_(v1), dcmHandle_(dcmHandle) {}\n\n  ParallelLinearAlgebraSharedData& data_;\n  int proc_;\n  ParallelLinearAlgebra::ParallelVector& v1_;\n  DenseColumnMatrixHandle dcmHandle_;\n  double maxResult_{0};\n\n  void operator()()\n  {\n    ParallelLinearAlgebra pla(data_, proc_);\n    pla.new_vector(v1_);\n    pla.add_vector(dcmHandle_, v1_);\n    maxResult_ = pla.max(v1_);\n  }\n};\n\nTEST(ParallelArithmeticTests, CanComputeMaxOfVectorMulti)\n{\n  /// @todo: multi thread\n  ParallelLinearAlgebraSharedData data(getDummySystem(), 2);\n\n  ParallelLinearAlgebra::ParallelVector v1;\n  double maxDouble_;\n\n  auto vec2 = vector2();\n  {\n\t  max max0(data, v1, 0, vec2);\n\t  max max1(data, v1, 1, vec2);\n\n\t  boost::thread t1 = boost::thread(boost::ref(max0));\n\t  boost::thread t2 = boost::thread(boost::ref(max1));\n\t  t1.join();\n\t  t2.join();\n    maxDouble_ = max0.maxResult_;\n  }\n  EXPECT_EQ(1, maxDouble_);\n}\n\n//Find what error is acceptable for the float comparison\nTEST(ParallelArithmeticTests, CanInvertElementsOfVectorWithAbsoluteValueThreshold)\n{\n\tParallelLinearAlgebraSharedData data(getDummySystem(),1);\n\tParallelLinearAlgebra pla(data, 0);\n\n  DenseColumnMatrixHandle v(boost::make_shared<DenseColumnMatrix>(size));\n\tv->setZero();\n\n  ParallelLinearAlgebra::ParallelVector dummyResult;\n\tauto dcmDummy = v;\n\tpla.add_vector(dcmDummy, dummyResult);\n\n  //test vector 1\n  ParallelLinearAlgebra::ParallelVector v1;\n\tauto vec1 = vector1();\n\tpla.add_vector(vec1, v1);\n  pla.absthreshold_invert(v1, dummyResult, 1);\n\tEXPECT_EQ(dummyResult.data_[0],1);\n\tEXPECT_DOUBLE_EQ(dummyResult.data_[1], 0.5);\n\tEXPECT_DOUBLE_EQ(dummyResult.data_[2], 0.25);\n\tEXPECT_EQ(dummyResult.data_[size-1], 1);\n\n  //test vector 2\n  pla.zeros(dummyResult);\n\tParallelLinearAlgebra::ParallelVector v2;\n\tauto vec2 = vector2();\n\tpla.add_vector(vec2, v2);\n  pla.absthreshold_invert(v2, dummyResult, 1);\n\n  EXPECT_EQ(1,dummyResult.data_[0]);\n\tEXPECT_DOUBLE_EQ(-0.5,dummyResult.data_[1]);\n\tEXPECT_DOUBLE_EQ(-0.25,dummyResult.data_[2]);\n\tEXPECT_EQ(1,dummyResult.data_[size-1]);\n\n  //test vector 3\n  pla.zeros(dummyResult);\n  ParallelLinearAlgebra::ParallelVector v3;\n\tauto vec3 = vector3();\n\tpla.add_vector(vec3, v3);\n  pla.absthreshold_invert(v3, dummyResult, 1);\n\n  EXPECT_EQ(1,dummyResult.data_[0]);\n\tEXPECT_EQ(1,dummyResult.data_[1]);\n\tEXPECT_EQ(1,dummyResult.data_[2]);\n\tEXPECT_NEAR(-0.1429, dummyResult.data_[size-1], 0.001);\n}\n\nstruct absthreshold_inv\n{\n   absthreshold_inv(ParallelLinearAlgebraSharedData& data, ParallelLinearAlgebra::ParallelVector& v1,\n     ParallelLinearAlgebra::ParallelVector& v2, int proc, DenseColumnMatrixHandle dcmHandle) :\n    data_(data), proc_(proc), v1_(v1), v2_(v2), dcmHandle_(dcmHandle) {}\n\n  ParallelLinearAlgebraSharedData& data_;\n  int proc_;\n  ParallelLinearAlgebra::ParallelVector& v1_;\n  ParallelLinearAlgebra::ParallelVector& v2_;\n  DenseColumnMatrixHandle dcmHandle_;\n\n  void operator()()\n  {\n    ParallelLinearAlgebra pla(data_, proc_);\n\n    pla.new_vector(v1_);\n    pla.add_vector(dcmHandle_, v1_);\n\n    pla.new_vector(v2_);\n\n    pla.absthreshold_invert(v1_, v2_, 1);\n  }\n};\n\nTEST(ParallelArithmeticTests, CanInvertElementsOfVectorWithAbsoluteValueThresholdMulti)\n{\n  const int NUM_THREADS = 2;\n  ParallelLinearAlgebraSharedData data(getDummySystem(), NUM_THREADS);\n\n  ParallelLinearAlgebra::ParallelVector v1;\n  ParallelLinearAlgebra::ParallelVector v2;\n\n  auto vec2 = vector2();\n  {\n\t  absthreshold_inv absthreshold_inv0(data, v1, v2, 0, vec2);\n\t  absthreshold_inv absthreshold_inv1(data, v1, v2, 1, vec2);\n\n\t  boost::thread t1 = boost::thread(boost::ref(absthreshold_inv0));\n\t  boost::thread t2 = boost::thread(boost::ref(absthreshold_inv1));\n\t  t1.join();\n\t  t2.join();\n  }\n\n  //test vector 1\n\tEXPECT_EQ(1,v2.data_[0]);\n\tEXPECT_NEAR(-0.5,v2.data_[1],0.001);\n\tEXPECT_NEAR(-0.25,v2.data_[2],0.001);\n  EXPECT_NEAR(-0.0033,v2.data_[300],0.001);\n  EXPECT_NEAR(-0.1667,v2.data_[size/2],0.001);\n  EXPECT_NEAR(-0.1429,v2.data_[size/2 + 1],0.001);\n  EXPECT_NEAR(-0.0017,v2.data_[600],0.001);\n\tEXPECT_EQ(1,v2.data_[size-1]);\n\n}\n\nTEST(ParallelArithmeticTests, CanInvertElementsOfVectorWithAbsoluteValueThresholdMulti8Threads)\n{\n  const int NUM_THREADS = 8;\n  ParallelLinearAlgebraSharedData data(getDummySystem(), NUM_THREADS);\n\n  ParallelLinearAlgebra::ParallelVector v1;\n  ParallelLinearAlgebra::ParallelVector v2;\n\n  auto vec2 = vector1();\n  std::vector<boost::shared_ptr<absthreshold_inv>> workers;\n  boost::thread_group threads;\n  {\n    for (int i = 0; i < NUM_THREADS; ++i)\n      workers.push_back(boost::make_shared<absthreshold_inv>(data, v1, v2, i, vec2));\n\n    for (int i = 0; i < NUM_THREADS; ++i)\n      threads.create_thread(boost::ref(*workers[i]));\n\n    threads.join_all();\n  }\n\n  //test vector 1\n\tEXPECT_EQ(1, v2.data_[0]);\n\tEXPECT_DOUBLE_EQ(0.5, v2.data_[1]);\n\tEXPECT_DOUBLE_EQ(0.25,v2.data_[2] );\n  EXPECT_DOUBLE_EQ(1, v2.data_[300]);\n  EXPECT_DOUBLE_EQ(1, v2.data_[size/2]);\n  EXPECT_DOUBLE_EQ(1, v2.data_[size/2 + 1]);\n  EXPECT_DOUBLE_EQ(1, v2.data_[600]);\n\tEXPECT_EQ(1, v2.data_[size-1]);\n\n}\n\nTEST(ParallelLinearAlgebraTests, CanFillVectorWithOnes)\n{\n  ParallelLinearAlgebraSharedData data(getDummySystem(),1);\n  ParallelLinearAlgebra pla(data,0);\n\n  ParallelLinearAlgebra::ParallelVector v1;\n  auto vec1 = vector1();\n  pla.add_vector(vec1, v1);\n\n  pla.ones(v1);\n\n  for (size_t i = 0; i < size; ++i)\n  {\n    EXPECT_EQ(1,v1.data_[i]);\n  }\n}\n\nTEST(ParallelArithmeticTests, CanMultiplyMatrixByVector)\n{\n  ParallelLinearAlgebraSharedData data(getDummySystem(),1);\n  ParallelLinearAlgebra pla(data,0);\n\n  ParallelLinearAlgebra::ParallelVector v1;\n  auto vec1 = vector1();\n  pla.add_vector(vec1, v1);\n\n  ParallelLinearAlgebra::ParallelVector v2;\n  auto vec2 = vector2();\n  pla.add_vector(vec2, v2);\n  pla.zeros(v2);\n\n  ParallelLinearAlgebra::ParallelMatrix m1;\n  auto mat1 = matrix1();\n  pla.add_matrix(mat1 , m1);\n\n  pla.mult(m1,v1,v2);\n\n  EXPECT_EQ(1,v2.data_[0]);\n  EXPECT_EQ(-4,v2.data_[1]);\n  EXPECT_EQ(-2,v2.data_[size-1]);\n}\n\nstruct mv_Multiply\n{\n  mv_Multiply(ParallelLinearAlgebraSharedData& data, ParallelLinearAlgebra::ParallelMatrix& m1,\n    ParallelLinearAlgebra::ParallelVector& v2, ParallelLinearAlgebra::ParallelVector& vR,\n    int proc, DenseColumnMatrixHandle dcmHandle, SparseRowMatrixHandle srmHandle) :\n    data_(data), proc_(proc), m1_(m1), v2_(v2), vR_(vR), dcmHandle_(dcmHandle), srmHandle_(srmHandle) {}\n\n  ParallelLinearAlgebraSharedData& data_;\n  int proc_;\n  ParallelLinearAlgebra::ParallelMatrix& m1_;\n  ParallelLinearAlgebra::ParallelVector& v2_;\n  ParallelLinearAlgebra::ParallelVector& vR_;\n  DenseColumnMatrixHandle dcmHandle_;\n  SparseRowMatrixHandle srmHandle_;\n\n  void operator()()\n  {\n    ParallelLinearAlgebra pla(data_, proc_);\n\n    pla.add_matrix(srmHandle_, m1_);\n\n    pla.new_vector(v2_);\n    pla.add_vector(dcmHandle_,v2_);\n\n    pla.new_vector(vR_);\n    pla.add_vector(dcmHandle_,vR_);\n\n    pla.mult(m1_, v2_, vR_);\n  }\n};\n\nTEST(ParallelArithmeticTests, CanMultiplyMatrixByVectorMulti)\n{\n  ParallelLinearAlgebraSharedData data(getDummySystem(), 2);\n\n  ParallelLinearAlgebra::ParallelMatrix m1;\n  ParallelLinearAlgebra::ParallelVector v2;\n  ParallelLinearAlgebra::ParallelVector vR;\n\n  auto vecR = vector2();\n  auto mat1 = matrix1();\n  {\n\t  mv_Multiply mult_0(data, m1, v2, vR, 0, vecR, mat1);\n\t  mv_Multiply mult_1(data, m1, v2, vR, 1, vecR, mat1);\n\n\t  boost::thread t1 = boost::thread(boost::ref(mult_0));\n\t  boost::thread t2 = boost::thread(boost::ref(mult_1));\n\t  t1.join();\n\t  t2.join();\n  }\n\n  EXPECT_EQ(-1,vR.data_[0]);\n  EXPECT_EQ(4,vR.data_[1]);\n  EXPECT_EQ(0,vR.data_[2]);\n  EXPECT_EQ(2,vR.data_[size-1]);\n}\n\nTEST(ParallelArithmeticTests, CanSubtractVectors)\n{\n  ParallelLinearAlgebraSharedData data(getDummySystem(),1);\n  ParallelLinearAlgebra pla(data,0);\n\n  ParallelLinearAlgebra::ParallelVector v1;\n  auto vec1 = vector1();\n  pla.add_vector(vec1, v1);\n\n  ParallelLinearAlgebra::ParallelVector v2;\n  auto vec2 = vector2();\n  pla.add_vector(vec2, v2);\n\n  ParallelLinearAlgebra::ParallelVector v3;\n  auto vec3 = vector3();\n  pla.add_vector(vec3, v3);\n  pla.zeros(v3);\n\n  pla.sub(v1, v2, v3);\n  EXPECT_EQ(v3.data_[0],2);\n  EXPECT_EQ(v3.data_[1],4);\n  EXPECT_EQ(v3.data_[2],8);\n  EXPECT_EQ(v3.data_[3],0);\n  EXPECT_EQ(v3.data_[size-1],-2);\n}\n\nstruct subtract\n{\n  subtract(ParallelLinearAlgebraSharedData& data, ParallelLinearAlgebra::ParallelVector& v1,\n    ParallelLinearAlgebra::ParallelVector& v2, ParallelLinearAlgebra::ParallelVector& vR,\n    int proc, DenseColumnMatrixHandle dcmHandle, DenseColumnMatrixHandle dcmHandle2) :\n    data_(data), proc_(proc), v1_(v1), v2_(v2), vR_(vR), dcmHandle_(dcmHandle), dcmHandle2_(dcmHandle2) {}\n\n  ParallelLinearAlgebraSharedData& data_;\n  int proc_;\n  ParallelLinearAlgebra::ParallelVector& v1_;\n  ParallelLinearAlgebra::ParallelVector& v2_;\n  ParallelLinearAlgebra::ParallelVector& vR_;\n  DenseColumnMatrixHandle dcmHandle_;\n  DenseColumnMatrixHandle dcmHandle2_;\n\n  void operator()()\n  {\n    ParallelLinearAlgebra pla(data_, proc_);\n\n    pla.new_vector(v1_);\n    pla.add_vector(dcmHandle_, v1_);\n\n    pla.new_vector(v2_);\n    pla.add_vector(dcmHandle2_,v2_);\n\n    pla.new_vector(vR_);\n\n    pla.ones(vR_);\n\n    pla.sub(v1_, v2_, vR_);\n  }\n};\n\nTEST(ParallelArithmeticTests, CanSubtractVectorsMulti)\n{\n  ParallelLinearAlgebraSharedData data(getDummySystem(),2);\n\n  ParallelLinearAlgebra::ParallelVector v1;\n  ParallelLinearAlgebra::ParallelVector v2;\n  ParallelLinearAlgebra::ParallelVector vR;\n\n  auto vec2 = vector2();\n  auto vec1 = vector1();\n    {\n\t    subtract sub_0(data, v1, v2, vR, 0, vec1, vec2);\n\t    subtract sub_1(data, v1, v2, vR, 1, vec1, vec2);\n\n\t    boost::thread t1 = boost::thread(boost::ref(sub_0));\n\t    boost::thread t2 = boost::thread(boost::ref(sub_1));\n\t    t1.join();\n\t    t2.join();\n    }\n\n  EXPECT_EQ(2,  vR.data_[0]);\n  EXPECT_EQ(4,  vR.data_[1]);\n  EXPECT_EQ(8,  vR.data_[2]);\n  EXPECT_EQ(0,  vR.data_[3]);\n  EXPECT_EQ(-2, vR.data_[size-1]);\n}\n//\nTEST(ParallelArithmeticTests, CanCompute2Norm)\n{\n  ParallelLinearAlgebraSharedData data(getDummySystem(),1);\n  ParallelLinearAlgebra pla(data,0);\n\n  ParallelLinearAlgebra::ParallelVector v1;\n  auto vec1 = vector1();\n  pla.add_vector(vec1,v1);\n\n  ParallelLinearAlgebra::ParallelVector v2;\n  auto vec2 = vector2();\n  pla.add_vector(vec2,v2);\n\n  ParallelLinearAlgebra::ParallelVector v3;\n  auto vec3 = vector3();\n  pla.add_vector(vec3,v3);\n\n  EXPECT_NEAR(4.6904,pla.norm(v1),0.001);\n  EXPECT_NEAR(670.900,pla.norm(v2),0.001);\n  EXPECT_NEAR(7.0711,pla.norm(v3),0.001);\n}\n\n\nstruct norm\n{\n  norm(ParallelLinearAlgebraSharedData& data, ParallelLinearAlgebra::ParallelVector& v1,\n    ParallelLinearAlgebra::ParallelVector& v2, ParallelLinearAlgebra::ParallelVector& v3,\n    int proc, DenseColumnMatrixHandle dcmHandle1, DenseColumnMatrixHandle dcmHandle2\n    , DenseColumnMatrixHandle dcmHandle3) :\n    data_(data), proc_(proc), v1_(v1), v2_(v2), v3_(v3), dcmHandle1_(dcmHandle1),\n    dcmHandle2_(dcmHandle2), dcmHandle3_(dcmHandle3) {}\n\n  ParallelLinearAlgebraSharedData& data_;\n  int proc_;\n  ParallelLinearAlgebra::ParallelVector& v1_;\n  ParallelLinearAlgebra::ParallelVector& v2_;\n  ParallelLinearAlgebra::ParallelVector& v3_;\n  DenseColumnMatrixHandle dcmHandle1_;\n  DenseColumnMatrixHandle dcmHandle2_;\n  DenseColumnMatrixHandle dcmHandle3_;\n  double v1Norm_;\n  double v2Norm_;\n  double v3Norm_;\n\n  void operator()()\n  {\n    ParallelLinearAlgebra pla(data_, proc_);\n\n    pla.new_vector(v1_);\n    pla.add_vector(dcmHandle1_,v1_);\n\n    pla.new_vector(v2_);\n    pla.add_vector(dcmHandle2_,v2_);\n\n    pla.new_vector(v3_);\n    pla.add_vector(dcmHandle3_,v3_);\n\n    v1Norm_ = pla.norm(v1_);\n    v2Norm_ = pla.norm(v2_);\n    v3Norm_ = pla.norm(v3_);\n  }\n};\n\nTEST(ParallelArithmeticTests, CanCompute2NormMulti)\n{\n  ParallelLinearAlgebraSharedData data(getDummySystem(), 2);\n\n  ParallelLinearAlgebra::ParallelVector v1;\n  ParallelLinearAlgebra::ParallelVector v2;\n  ParallelLinearAlgebra::ParallelVector v3;\n  double v1Norm_Result;\n  double v2Norm_Result;\n  double v3Norm_Result;\n\n  auto vec1 = vector1();\n  auto vec2 = vector2();\n  auto vec3 = vector3();\n  {\n\t  norm norm_0(data, v1, v2, v3, 0, vec1, vec2, vec3);\n\t  norm norm_1(data, v1, v2, v3, 1, vec1, vec2, vec3);\n\n\t  boost::thread t1 = boost::thread(boost::ref(norm_0));\n\t  boost::thread t2 = boost::thread(boost::ref(norm_1));\n\t  t1.join();\n\t  t2.join();\n\n    v1Norm_Result = norm_0.v1Norm_;\n    v2Norm_Result = norm_0.v2Norm_;\n    v3Norm_Result = norm_0.v3Norm_;\n  }\n\n  EXPECT_NEAR(4.6904,v1Norm_Result,0.001);\n  EXPECT_NEAR(670.900,v2Norm_Result,0.001);\n  EXPECT_NEAR(7.0711,v3Norm_Result,0.001);\n}\n\nTEST(ParallelArithmeticTests, CanMultiplyVectorsComponentWise)\n{\n  ParallelLinearAlgebraSharedData data(getDummySystem(),1);\n  ParallelLinearAlgebra pla(data,0);\n\n  ParallelLinearAlgebra::ParallelVector v1;\n  auto vec1 = vector1();\n  pla.add_vector(vec1,v1);\n\n  ParallelLinearAlgebra::ParallelVector v2;\n  auto vec2 = vector2();\n  pla.add_vector(vec2,v2);\n\n  ParallelLinearAlgebra::ParallelVector v3;\n  auto vec3 = vector3();\n  pla.add_vector(vec3,v3);\n  pla.zeros(v3);\n\n  pla.mult(v1,v2,v3);\n  EXPECT_EQ(v3.data_[0],-1);\n  EXPECT_EQ(v3.data_[1],-4);\n  EXPECT_EQ(v3.data_[2],-16);\n  EXPECT_EQ(v3.data_[size-1],-1);\n\n  pla.zeros(v2);\n  auto resetV3 = vector3();\n  pla.add_vector(resetV3,v3);\n  pla.mult(v1,v3,v2);\n\n  EXPECT_EQ(0,v2.data_[0]);\n  EXPECT_EQ(2,v2.data_[1]);\n  EXPECT_EQ(0,v2.data_[2]);\n  EXPECT_EQ(7,v2.data_[size-1]);\n}\nstruct multVectors\n{\n  multVectors(ParallelLinearAlgebraSharedData& data, ParallelLinearAlgebra::ParallelVector& v1,\n    ParallelLinearAlgebra::ParallelVector& v2, ParallelLinearAlgebra::ParallelVector& v3,\n    int proc, DenseColumnMatrixHandle dcmHandle1, DenseColumnMatrixHandle dcmHandle2) :\n    data_(data), proc_(proc), v1_(v1), v2_(v2), v3_(v3),\n      dcmHandle1_(dcmHandle1), dcmHandle2_(dcmHandle2) {}\n\n  ParallelLinearAlgebraSharedData& data_;\n  int proc_;\n  ParallelLinearAlgebra::ParallelVector& v1_;\n  ParallelLinearAlgebra::ParallelVector& v2_;\n  ParallelLinearAlgebra::ParallelVector& v3_;\n  DenseColumnMatrixHandle dcmHandle1_;\n  DenseColumnMatrixHandle dcmHandle2_;\n\n  void operator()()\n  {\n    ParallelLinearAlgebra pla(data_, proc_);\n\n    pla.new_vector(v1_);\n    pla.add_vector(dcmHandle1_, v1_);\n\n    pla.new_vector(v2_);\n    pla.add_vector(dcmHandle2_,v2_);\n\n    pla.new_vector(v3_);\n\n    pla.mult(v1_,v2_,v3_);\n  }\n};\n/// @todo: by intern\nTEST(ParallelArithmeticTests, CanMultiplyVectorsComponentWiseMulti)\n{\n  ParallelLinearAlgebraSharedData data(getDummySystem(), 2);\n\n  ParallelLinearAlgebra::ParallelVector v1;\n  ParallelLinearAlgebra::ParallelVector v2;\n  ParallelLinearAlgebra::ParallelVector v3;\n\n  auto vec1 = vector1();\n  auto vec2 = vector2();\n  {\n\t  multVectors mult_0(data, v1, v2, v3, 0, vec1, vec2);\n\t  multVectors mult_1(data, v1, v2, v3, 1, vec1, vec2);\n\n\t  boost::thread t1 = boost::thread(boost::ref(mult_0));\n\t  boost::thread t2 = boost::thread(boost::ref(mult_1));\n\t  t1.join();\n\t  t2.join();\n  }\n\n  EXPECT_EQ(-1  , v3.data_[0]);\n  EXPECT_EQ(-4  , v3.data_[1]);\n  EXPECT_EQ(-16 , v3.data_[2]);\n  EXPECT_EQ(-1  , v3.data_[size-1]);\n}\n\nTEST(ParallelArithmeticTests, CanComputeDotProduct)\n{\n  ParallelLinearAlgebraSharedData data(getDummySystem(),1);\n  ParallelLinearAlgebra pla(data,0);\n\n  ParallelLinearAlgebra::ParallelVector v1;\n  auto vec1 = vector1();\n  pla.add_vector(vec1,v1);\n\n  ParallelLinearAlgebra::ParallelVector v2;\n  auto vec2 = vector2();\n  pla.add_vector(vec2,v2);\n\n  ParallelLinearAlgebra::ParallelVector v3;\n  auto vec3 = vector3();\n  pla.add_vector(vec3,v3);\n\n  EXPECT_EQ(-22 , pla.dot(v1,v2));\n  EXPECT_EQ(-9 , pla.dot(v2,v3));\n  EXPECT_EQ(9 , pla.dot(v1,v3));\n}\n\nstruct dotMult\n{\n  dotMult(ParallelLinearAlgebraSharedData& data, ParallelLinearAlgebra::ParallelVector& v1,\n    ParallelLinearAlgebra::ParallelVector& v2, ParallelLinearAlgebra::ParallelVector& v3,\n    int proc, DenseColumnMatrixHandle dcmHandle, DenseColumnMatrixHandle dcmHandle2,\n    DenseColumnMatrixHandle dcmHandle3) :\n      data_(data), proc_(proc), v1_(v1), v2_(v2), v3_(v3),\n      dcmHandle_(dcmHandle), dcmHandle2_(dcmHandle2), dcmHandle3_(dcmHandle3) {}\n\n  ParallelLinearAlgebraSharedData& data_;\n  int proc_;\n  ParallelLinearAlgebra::ParallelVector& v1_;\n  ParallelLinearAlgebra::ParallelVector& v2_;\n  ParallelLinearAlgebra::ParallelVector& v3_;\n  DenseColumnMatrixHandle dcmHandle_;\n  DenseColumnMatrixHandle dcmHandle2_;\n  DenseColumnMatrixHandle dcmHandle3_;\n  double v12_;\n  double v23_;\n  double v13_;\n\n  void operator()()\n  {\n    ParallelLinearAlgebra pla(data_, proc_);\n\n    pla.new_vector(v1_);\n    pla.add_vector(dcmHandle_, v1_);\n\n    pla.new_vector(v2_);\n    pla.add_vector(dcmHandle2_,v2_);\n\n    pla.new_vector(v3_);\n    pla.add_vector(dcmHandle3_,v3_);\n\n\n    v12_ = pla.dot(v1_,v2_);\n    v23_ = pla.dot(v2_,v3_);\n    v13_ = pla.dot(v1_,v3_);\n  }\n};\n\nTEST(ParallelArithmeticTests, CanComputeDotProductMulti)\n{\n  ParallelLinearAlgebraSharedData data(getDummySystem(), 2);\n\n  ParallelLinearAlgebra::ParallelVector v1;\n  ParallelLinearAlgebra::ParallelVector v2;\n  ParallelLinearAlgebra::ParallelVector v3;\n  double v12;\n  double v23;\n  double v13;\n\n  auto vec1 = vector1();\n  auto vec2 = vector2();\n  auto vec3 = vector3();\n  {\n\t  dotMult dotMult_0(data, v1, v2, v3, 0, vec1, vec2, vec3);\n\t  dotMult dotMult_1(data, v1, v2, v3, 1, vec1, vec2, vec3);\n\n\t  boost::thread t1 = boost::thread(boost::ref(dotMult_0));\n\t  boost::thread t2 = boost::thread(boost::ref(dotMult_1));\n\t  t1.join();\n\t  t2.join();\n    v12 = dotMult_0.v12_;\n    v23 = dotMult_0.v23_;\n    v13 = dotMult_0.v13_;\n  }\n\n  EXPECT_EQ(-22 , v12);\n  EXPECT_EQ(-9 , v23);\n  EXPECT_EQ(9 , v13);\n}\n", "meta": {"hexsha": "eb0853809690c2e7afdf145ef343bb6e00131740", "size": 26684, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/Core/Algorithms/Math/Tests/ParallelLinearAlgebraTests.cc", "max_stars_repo_name": "Haydelj/SCIRun", "max_stars_repo_head_hexsha": "f7ee04d85349b946224dbff183438663e54b9413", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Core/Algorithms/Math/Tests/ParallelLinearAlgebraTests.cc", "max_issues_repo_name": "Haydelj/SCIRun", "max_issues_repo_head_hexsha": "f7ee04d85349b946224dbff183438663e54b9413", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Core/Algorithms/Math/Tests/ParallelLinearAlgebraTests.cc", "max_forks_repo_name": "Haydelj/SCIRun", "max_forks_repo_head_hexsha": "f7ee04d85349b946224dbff183438663e54b9413", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.2563840654, "max_line_length": 106, "alphanum_fraction": 0.7187453155, "num_tokens": 8096, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.6584175005616829, "lm_q1q2_score": 0.46894613456619544}}
{"text": "/////////////////////////////////////////////////////////////////////////////////////////////\n// Copyright (c) 2021 Andreas Milton Maniotis.\n//\n// Email: andreas.maniotis@gmail.com\n//\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n/////////////////////////////////////////////////////////////////////////////////////////////\n\n\n#include \"aml/list.hpp\"\n#include \"aml/term_algebra.hpp\"\n\n#include <type_traits>\n\n#include <iostream>\n#include <boost/core/demangle.hpp>\n\n\nnamespace test::list\n{\n    template<auto n>\n    struct number\n    {\n        static constexpr auto eval() { return n; }\n    };\n\n    void test_head_and_tail()\n    {\n        using aml::_;\n\n        using list_t = aml::head_and_tail<int, int*, int**, int***>;\n\n        static_assert( std::is_same< list_t::head, int>::value );\n        static_assert( std::is_same< aml::power< list_t::tail, _<2> >::return_, aml::head_and_tail<int**, int***> >::value);\n\n        static_assert( std::is_same< aml::head<int, int*, int**>, int >::value );\n\n        static_assert( std::is_same< aml::at< _<0>, int>, int >::value);\n\n        static_assert( std::is_same< aml::at< _<3>, int, int*, int**, int***, int**** >, int***>::value );\n        static_assert( std::is_same< aml::at< _<3>, int, int*, int**, int***>, int*** >::value );\n\n        using t3 = aml::list<int*, int**, int***>;\n\n        static_assert( std::is_same< typename t3::head, aml::list_head<t3> >::value );\n        static_assert( std::is_same< aml::list_head<t3>, int* >::value );\n\n        static_assert( std::is_same< typename t3::tail, aml::list_tail<t3> >::value );\n        static_assert( std::is_same< aml::list_tail<t3>, aml::list<int**, int***> >::value);\n\n        static_assert( std::is_same< typename t3::init, aml::list_init<t3> >::value );\n        static_assert( std::is_same< aml::list_init<t3>, aml::list<int*, int**> >::value );\n\n\n        static_assert( std::is_same< t3::last, aml::list_last<t3> >::value );\n        static_assert( std::is_same< aml::list_last<t3>, int*** >::value );\n    }\n\n\n    template< typename... > struct F {};\n\n\n    void test_apply()\n    {\n        using f0 = aml::list<>::apply<F>;\n        using f1 = aml::list<int*>::apply<F>;\n        using f2 = aml::list<int*, int**>::apply<F>;\n\n        using f0_ = aml::list_apply< aml::list<>, aml::function<F> >;\n        using f1_ = aml::list_apply< aml::list<int*>, aml::function<F> >;\n        using f2_ = aml::list_apply< aml::list<int*, int**>, aml::function<F> >;\n\n        using g0 = aml::list<>::pointwise_apply<F>;\n        using g1 = aml::list<int*>::pointwise_apply<F>;\n        using g2 = aml::list<int*, int**>::pointwise_apply<F>;\n\n        using g0_ = aml::list_pointwise_apply< aml::list<>, aml::function<F> >;\n        using g1_ = aml::list_pointwise_apply< aml::list<int*>, aml::function<F> >;\n        using g2_ = aml::list_pointwise_apply< aml::list<int*, int**>, aml::function<F> >;\n\n        static_assert(std::is_same<f0, f0_>::value);\n        static_assert(std::is_same<f1, f1_>::value);\n        static_assert(std::is_same<f2, f2_>::value);\n\n        static_assert(std::is_same<g0, g0_>::value);\n        static_assert(std::is_same<g1, g1_>::value);\n        static_assert(std::is_same<g2, g2_>::value);\n\n        static_assert(std::is_same< g0, aml::list<> >::value);\n        static_assert(std::is_same< g1, aml::list<F<int*>> >::value);\n        static_assert(std::is_same< g2, aml::list<F<int*>, F<int**> > >::value);\n    }\n\n\n    void test_drop_and_take()\n    {\n        using aml::_;\n\n        using t3 = aml::list<int*, int**, int***>;\n\n        static_assert( std::is_same< t3::drop< _<0> >, t3 >::value );\n\n\n        static_assert( std::is_same< t3::drop< _<1> >, aml::list<int**, int***> >::value );\n        static_assert( std::is_same< t3::drop< _<2> >, aml::list<       int***> >::value );\n        static_assert( std::is_same< t3::drop< _<3> >, aml::list<             > >::value );\n\n        static_assert( std::is_same< aml::list<>::take< _<0> >, aml::list<> >::value );\n\n        static_assert( std::is_same< t3::take< _<1> >, aml::list< int*                > >::value );\n        static_assert( std::is_same< t3::take< _<2> >, aml::list< int*, int**         > >::value );\n        static_assert( std::is_same< t3::take< _<3> >, aml::list< int*, int**, int*** > >::value );\n    }\n\n\n    void test_cons()\n    {\n        using aml::_;\n\n        using l0 = aml::list<>;\n        using l0_a = l0::cons<>;\n        using l0_b = l0::rcons<>;\n\n        using l1 = l0::cons< _<1>, _<2>, _<3> >;\n        using l1_a = l0::rcons<_<1>, _<2>, _<3> >;\n\n        using l2 = l1::cons<>;\n        using l2_a = l1::rcons<>;\n\n        using l3 = l1::rcons< _<4>, _<5> >;\n        using l4 = l1::cons< _<-1>, _< 0> >;\n\n        static_assert( std::is_same<l0, l0_a>::value );\n        static_assert( std::is_same<l0, l0_b>::value );\n        static_assert( std::is_same<l1, l1_a>::value );\n\n        static_assert( std::is_same<l2, l2_a>::value );\n        static_assert( std::is_same<l3, aml::list< _<1>, _<2>, _<3>, _<4>, _<5> > >::value );\n\n        static_assert( std::is_same<l4, aml::list< _<-1>, _<-0>,  _<1>, _<2>, _<3> > >::value );\n\n        using l5 = aml::list_cons< aml::list< _<1>, _<2>, _<3> >  >;\n        using l6 = aml::list_rcons< aml::list< _<1>, _<2>, _<3> > >;\n\n        using l7 = aml::list_rcons< aml::list< _<1>, _<2>, _<3> >, _<4>, _<5>  >;\n        using l8 = aml::list_cons< aml::list< _<1>, _<2>, _<3> >, _<-1>, _<0>  >;\n\n        static_assert( std::is_same< l5, aml::list< _<1>, _<2>, _<3> > >::value );\n        static_assert( std::is_same< l5, l6 >::value );\n\n        static_assert( std::is_same< l7, aml::list< _<1>, _<2>, _<3>, _<4>, _<5> > >::value );\n        static_assert( std::is_same< l8, aml::list< _<-1>, _<0>, _<1>, _<2>, _<3> > >::value );\n    }\n\n    void test_reverse()\n    {\n        using aml::_;\n\n        using l1 = aml::list<>;\n        using l2 = aml::list<>::reverse;\n        using l3 = aml::list_reverse< aml::list<> >;\n\n        using l4 = aml::list< _<1> >;\n        using l5 = aml::list< _<1> >::reverse;\n        using l6 = aml::list_reverse< l4 >;\n\n        using l7 = aml::list< _<1>, _<2> >;\n        using l8 = l7::reverse;\n        using l9 = aml::list_reverse< l7 >;\n\n        static_assert( std::is_same< l1, l2 >::value );\n        static_assert( std::is_same< l1, l3 >::value );\n\n        static_assert( std::is_same< l4, l5 >::value );\n        static_assert( std::is_same< l4, l6 >::value );\n\n        static_assert( std::is_same< l8, l9 >::value );\n\n        static_assert( std::is_same< l8::reverse, l7 >::value );\n    }\n\n\n    template<typename List, typename X>\n    using G = typename List::template rcons<  aml::num< -X::eval() >  >;\n\n\n    void test_fold_left()\n    {\n        using aml::_;\n\n        using l0  =  aml::list<>;\n        using l1  =  aml::list< _<1> >;\n        using l2  =  aml::list< _<1>, _<2> >;\n        using l4  =  aml::list< _<1>, _<2>, _<3>, _<4> >;\n\n\n        using f0  =  l0::lfold_with< G, aml::list<> >;\n        using r0  =  aml::list< >;\n\n        static_assert( std::is_same< f0, r0 >::value );\n\n\n        using f1  =  l1::lfold_with< G, aml::list<> >;\n        using r1  =  aml::list< _<-1> >;\n\n        static_assert( std::is_same< f1, r1 >::value );\n\n\n        using f2  =  l2::lfold_with< G, aml::list<> >;\n        using r2  =  aml::list< _<-1>, _<-2> >;\n\n        static_assert( std::is_same< f2, r2 >::value );\n\n\n        using f4  =  l4::lfold_with< G, aml::list<> >;\n        using r4  =  aml::list< _<-1>, _<-2>, _<-3>, _<-4> >;\n\n        static_assert( std::is_same< f4, r4 >::value );\n    }\n\n\n    template<typename X, typename List>\n    using H  =  typename List::template cons<  aml::num< -X::eval() >  >;\n\n\n    void test_fold_right()\n    {\n        using aml::_;\n\n        using l0  =  aml::list<>;\n        using l1  =  aml::list< _<1> >;\n        using l2  =  aml::list< _<1>, _<2> >;\n        using l4  =  aml::list< _<1>, _<2>, _<3>, _<4> >;\n\n\n        using f0  =  l0::rfold_with< H, aml::list<> >;\n        using r0  =  aml::list< >;\n\n        static_assert( std::is_same< f0, r0 >::value );\n\n\n        using f1  =  l1::rfold_with< H, aml::list<> >;\n        using r1  =  aml::list< _<-1> >;\n\n        static_assert( std::is_same< f1, r1 >::value );\n\n\n        using f2  =  l2::rfold_with< H, aml::list<> >;\n        using r2  =  aml::list< _<-1>, _<-2> >;\n\n        static_assert( std::is_same< f2, r2 >::value );\n\n\n        using f4  =  l4::rfold_with< H, aml::list<> >;\n        using r4  =  aml::list< _<-1>, _<-2>, _<-3>, _<-4> >;\n\n        static_assert( std::is_same< f4, r4 >::value );\n    }\n\n\n    void test_scan_left()\n    {\n        using aml::_;\n\n        using l0  =  aml::list<>;\n        using l1  =  aml::list< _<1> >;\n        using l2  =  aml::list< _<1>, _<2> >;\n        using l4  =  aml::list< _<1>, _<2>, _<3>, _<4> >;\n\n\n        using f0  =  l0::lscan_with< G, aml::list<> >;\n        using r0  =  aml::list< aml::list<> >;\n\n        static_assert( std::is_same< f0, r0 >::value );\n\n\n        using f1  =  l1::lscan_with< G, aml::list<> >;\n        using r1  =  aml::list<  aml::list<>,  aml::list< _<-1> >  >;\n\n        static_assert( std::is_same< f1, r1 >::value );\n\n\n        using f2  =  l2::lscan_with< G, aml::list<> >;\n        using r2  =  aml::list< aml::list<>, aml::list< _<-1> >, aml::list< _<-1>, _<-2> > >;\n\n        static_assert( std::is_same< f2, r2 >::value );\n\n\n        using f4  =  l4::lscan_with< G, aml::list<> >;\n        using r4  =  aml::list<  aml::list<>,\n                                 aml::list< _<-1> >,\n                                 aml::list< _<-1>, _<-2> >,\n                                 aml::list< _<-1>, _<-2>, _<-3> >,\n                                 aml::list< _<-1>, _<-2>, _<-3>, _<-4> >  >;\n\n        static_assert( std::is_same< f4, r4 >::value );\n    }\n\n    void test_scan_right()\n    {\n        using aml::_;\n\n        using l0  =  aml::list<>;\n        using l1  =  aml::list< _<1> >;\n        using l2  =  aml::list< _<1>, _<2> >;\n        using l4  =  aml::list< _<1>, _<2>, _<3>, _<4> >;\n\n\n        using f0  =  l0::rscan_with< H, aml::list<> >;\n        using r0  =  aml::list< aml::list<> >;\n\n        static_assert( std::is_same< f0, r0 >::value );\n\n        using f1  =  l1::rscan_with< H, aml::list<> >;\n        using r1  =  aml::list<  aml::list<>,  aml::list< _<-1> >  >::reverse;\n\n        static_assert( std::is_same< f1, r1 >::value );\n\n        using f2  =  l2::rscan_with< H, aml::list<> >;\n        using r2  =  aml::list<  aml::list< _<-1>, _<-2> >,\n                                 aml::list< _<-2> > ,\n                                 aml::list<>  >;\n\n        static_assert( std::is_same< f2, r2 >::value );\n\n\n        using f4  =  l4::rscan_with< H, aml::list<> >;\n        using r4  =  aml::list<  aml::list<  _<-1>, _<-2>, _<-3>, _<-4>  >,\n                                 aml::list<         _<-2>, _<-3>, _<-4>  >,\n                                 aml::list<                _<-3>, _<-4>  >,\n                                 aml::list<                       _<-4>  >,\n                                 aml::list<                              >   >;\n\n        static_assert( std::is_same< f4, r4 >::value );\n\n    }\n\n    template<typename B, typename A>\n    using multiply = aml::list< aml::num< B::eval() * A::eval() >, aml::num< -A::eval() > >;\n\n    void test_map_accum_left()\n    {\n\n        using aml::_;\n\n\n        using macl_0  =  aml::list<>::map_accum_left_with<multiply, _<1> >;\n\n        static_assert( std::is_same<macl_0, aml::list< _<1>, aml::list<>  > >::value );\n\n\n        using macl_1  =  aml::list< _<1> >::map_accum_left_with< multiply, _<1> >;\n\n        static_assert( std::is_same<macl_1, aml::list< _<1>, aml::list<_<-1> >  > >::value );\n\n\n        using macl_2  =  aml::list< _<1>, _<2> >::map_accum_left_with< multiply, _<1> >;\n\n        static_assert( std::is_same<macl_2, aml::list< _<2>, aml::list<_<-1>, _<-2> >  > >::value );\n\n\n        using macl_3  =  aml::list< _<1>, _<2>, _<3>  >::map_accum_left_with< multiply, _<1> >;\n\n        static_assert( std::is_same<macl_3, aml::list< _<6>, aml::list<_<-1>, _<-2>, _<-3> >  > >::value );\n    }\n\n\n    void test_map_accum_right()\n    {\n\n        using aml::_;\n\n\n        using macr_0  =  aml::list<>::map_accum_right_with<multiply, _<1> >;\n\n        static_assert( std::is_same<macr_0, aml::list< _<1>, aml::list<>  > >::value );\n\n\n        using macr_1  =  aml::list< _<1> >::map_accum_right_with< multiply, _<1> >;\n\n        static_assert( std::is_same<macr_1, aml::list< _<1>, aml::list<_<-1> >  > >::value );\n\n\n        using macr_2  =  aml::list< _<1>, _<2> >::map_accum_right_with< multiply, _<1> >;\n\n        static_assert( std::is_same<macr_2, aml::list< _<2>, aml::list<_<-2>, _<-1> >  > >::value );\n\n\n        using macr_3  =  aml::list< _<1>, _<2>, _<3>  >::map_accum_right_with< multiply, _<1> >;\n\n        static_assert( std::is_same<macr_3, aml::list< _<6>, aml::list<_<-3>, _<-2>, _<-1> >  > >::value );\n    }\n\n\n    template<typename N>\n    using is_even = aml::bool_< (N::eval() & 1) == 0 >;\n\n\n    void test_partition()\n    {\n        using aml::_;\n\n        using l0    =  aml::list<>::partition_with<is_even>;\n        using l1_a  =  aml::list< _<1> >::partition_with<is_even>;\n        using l1_b  =  aml::list< _<2> >::partition_with<is_even>;\n        using l2_a  =  aml::list< _<1>, _<2> >::partition_with<is_even>;\n        using l2_b  =  aml::list< _<1>, _<3> >::partition_with<is_even>;\n        using l2_c  =  aml::list< _<1>, _<4> >::partition_with<is_even>;\n        using l2_d  =  aml::list< _<2>, _<4> >::partition_with<is_even>;\n\n        using l4    =  aml::list< _<1>, _<2>, _<4>, _<3> >::partition_with<is_even>;\n\n        using a0    =  aml::list<>;\n        using r0    =  aml::list<>;\n\n        using a1_a  =  aml::list<>;\n        using r1_a  =  aml::list< _<1> >;\n\n        using a1_b  =  aml::list< _<2> >;\n        using r1_b  =  aml::list<>;\n\n        using a2_a  =  aml::list< _<2> >;\n        using r2_a  =  aml::list< _<1> >;\n\n        using a2_b  =  aml::list<>;\n        using r2_b  =  aml::list< _<1>, _<3> >;\n\n        using a2_c  =  aml::list< _<4> >;\n        using r2_c  =  aml::list< _<1> >;\n\n        using a2_d  =  aml::list< _<2>, _<4> >;\n        using r2_d  =  aml::list< >;\n\n        static_assert( std::is_same< a0, l0::accepted >::value);\n        static_assert( std::is_same< r0, l0::rejected >::value);\n\n\n        static_assert( std::is_same< a1_a, l1_a::accepted >::value);\n        static_assert( std::is_same< r1_a, l1_a::rejected >::value);\n\n\n        static_assert( std::is_same< a1_b, l1_b::accepted >::value);\n        static_assert( std::is_same< r1_b, l1_b::rejected >::value);\n\n\n        static_assert( std::is_same< a2_a, l2_a::accepted >::value);\n        static_assert( std::is_same< r2_a, l2_a::rejected >::value);\n\n\n        static_assert( std::is_same< a2_b, l2_b::accepted >::value);\n        static_assert( std::is_same< r2_b, l2_b::rejected >::value);\n\n\n        static_assert( std::is_same< a2_c, l2_c::accepted >::value);\n        static_assert( std::is_same< r2_c, l2_c::rejected >::value);\n\n\n        static_assert( std::is_same< a2_d, l2_d::accepted >::value);\n        static_assert( std::is_same< r2_d, l2_d::rejected >::value);\n\n        static_assert( std::is_same< l4::accepted, aml::list< _<2>, _<4> > >::value);\n        static_assert( std::is_same< l4::rejected, aml::list< _<1>, _<3> > >::value);\n\n    }\n\n\n    void test_split_by_first_occurence_of()\n    {\n        using aml::_;\n\n        using s0    =  aml::list<>::split_by_first_occurence_of< is_even >;\n        using s1_a  =  aml::list< _<2> >::split_by_first_occurence_of< is_even >;\n        using s1_r  =  aml::list< _<1> >::split_by_first_occurence_of< is_even >;\n\n        using s2    =  aml::list< _<1>, _<2> >::split_by_first_occurence_of<is_even>;\n        using s3    =  aml::list< _<2>, _<1> >::split_by_first_occurence_of<is_even>;\n\n        using s4    =  aml::list< _<1>, _<3>, _<2>, _<5> >::split_by_first_occurence_of<is_even>;\n\n        static_assert( std::is_same<s0::prefix, aml::list<> >::value );\n        static_assert( std::is_same<s0::suffix, aml::list<> >::value );\n\n        static_assert( std::is_same< s1_a::prefix, aml::list<> >::value );\n        static_assert( std::is_same< s1_a::suffix, aml::list<_<2>> >::value );\n\n        static_assert( std::is_same< s1_r::prefix, aml::list<_<1>> >::value );\n        static_assert( std::is_same< s1_r::suffix, aml::list< > >::value );\n\n        static_assert( std::is_same< s2::prefix, aml::list< _<1> > >::value );\n        static_assert( std::is_same< s2::suffix, aml::list< _<2> > >::value );\n\n        static_assert( std::is_same< s3::prefix, aml::list<> >::value );\n        static_assert( std::is_same< s3::suffix, aml::list< _<2>, _<1> > >::value );\n\n        static_assert( std::is_same< s4::prefix, aml::list< _<1>, _<3> > >::value );\n        static_assert( std::is_same< s4::suffix, aml::list< _<2>, _<5> > >::value );\n    }\n\n    void test_take_and_drop_while()\n    {\n        using aml::_;\n\n        using l0 = aml::list<>;\n        using l1 = aml::list< _<1> >;\n        using l2 = aml::list< _<0> >;\n        using l3 = aml::list< _<0>, _<1> >;\n        using l4 = aml::list< _<1>, _<0> >;\n        using l5 = aml::list< _<0>, _<2>, _<4>, _<3>, _<6> >;\n\n        using t0  = l0::take_while< is_even >;\n        using t1  = l1::take_while< is_even >;\n        using t2  = l2::take_while< is_even >;\n        using t3  = l3::take_while< is_even >;\n        using t4  = l4::take_while< is_even >;\n        using t5  = l5::take_while< is_even >;\n\n        using d0  = l0::drop_while< is_even >;\n        using d1  = l1::drop_while< is_even >;\n        using d2  = l2::drop_while< is_even >;\n        using d3  = l3::drop_while< is_even >;\n        using d4  = l4::drop_while< is_even >;\n        using d5  = l5::drop_while< is_even >;\n\n        static_assert( std::is_same< t0, aml::list<> >::value );\n        static_assert( std::is_same< t1, aml::list<> >::value );\n        static_assert( std::is_same< t2, aml::list<_<0>>>::value );\n        static_assert( std::is_same< t3, aml::list<_<0>> >::value );\n        static_assert( std::is_same< t4, aml::list< > >::value );\n        static_assert( std::is_same< t5, aml::list< _<0>, _<2>, _<4> > >::value );\n\n        static_assert( std::is_same< d0, aml::list<> >::value );\n        static_assert( std::is_same< d1, aml::list<_<1>> >::value );\n        static_assert( std::is_same< d2, aml::list<> >::value );\n        static_assert( std::is_same< d3, aml::list<_<1>> >::value );\n        static_assert( std::is_same< d4, aml::list< _<1>, _<0> > >::value );\n        static_assert( std::is_same< d5, aml::list< _<3>, _<6> > >::value );\n    }\n\n\n\n    //    template< typename X, typename Y, typename... >\n    //    template<typename X, typename Y, typename...>\n    //    using less = aml::bool_< (X::eval() < Y::eval()) >;\n\n    template<typename X, typename Y>\n    using less  = aml::bool_< (X::eval() < Y::eval()) >;\n\n\n    template<typename... X>\n    using size_less  =  aml::bool_< (sizeof( aml::at< aml::_<0>, X...>) < sizeof( aml::at< aml::_<1>, X...>)) >;\n\n    void test_sort()\n    {\n\n        using aml::_;\n\n        using unsorted_5 = aml::list< _<3>, _<2>, _<1>, _<4>, _<0> >;\n\n        using sorted_5 = unsorted_5::sort_with<less>;\n        static_assert( std::is_same< sorted_5, aml::list< _<0>, _<1>, _<2>, _<3>, _<4> > >::value );\n\n\n        static_assert( std::is_same< aml::list<>::sort_with<less>, aml::list<> >::value );\n\n        // test stability\n        using list  =  aml::list< unsigned char, unsigned int, int, signed char, unsigned int, int, unsigned int>;\n\n        using expected_sorting  =  aml::list< unsigned char, signed char,\n                                              unsigned int, int, unsigned int, int, unsigned int >;\n\n        using acquired_sorting = list::sort_with<size_less>;\n\n\n        static_assert( std::is_same< acquired_sorting, expected_sorting >::value );\n\n        static_assert( std::is_same< aml::list_sort<list, aml::function<size_less> >, expected_sorting>::value );\n\n    }\n\n}\n\n\n#include <iostream>\n#include <string>\n\n\nint main()\n{\n\n    void (*test_set[])() =\n    {\n        test::list::test_head_and_tail,\n        test::list::test_apply,\n        test::list::test_drop_and_take,\n        test::list::test_cons,\n        test::list::test_reverse,\n        test::list::test_fold_left,\n        test::list::test_fold_right,\n        test::list::test_scan_left,\n        test::list::test_scan_right,\n        test::list::test_map_accum_left,\n        test::list::test_map_accum_right,\n        test::list::test_partition,\n        test::list::test_split_by_first_occurence_of,\n        test::list::test_take_and_drop_while,\n        test::list::test_sort\n\n    };\n\n\n    for ( auto test : test_set )\n        test();\n\n    std::cout << __FILE__ << \": \" << sizeof(test_set)/sizeof(test_set[0])  << \" tests passed.\" << std::endl;\n\n}\n", "meta": {"hexsha": "e0e0c9868db634fd8f915d6c9ae7e89d54d35505", "size": 20902, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_list.cpp", "max_stars_repo_name": "aandriko/libaml", "max_stars_repo_head_hexsha": "9db1a3ac13ef8160a33ed03e861be5d8cc8ea311", "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": "test/test_list.cpp", "max_issues_repo_name": "aandriko/libaml", "max_issues_repo_head_hexsha": "9db1a3ac13ef8160a33ed03e861be5d8cc8ea311", "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/test_list.cpp", "max_forks_repo_name": "aandriko/libaml", "max_forks_repo_head_hexsha": "9db1a3ac13ef8160a33ed03e861be5d8cc8ea311", "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.8220064725, "max_line_length": 124, "alphanum_fraction": 0.5202851402, "num_tokens": 7075, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321720225279, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.46894613129654034}}
{"text": "#include <cstdlib>\n#include <iostream>\n#include <memory>\n#include <random>\n#include <algorithm>\n#include <utility>\n#include <string>\n#include <sstream>\n#include <boost/asio.hpp>\n\nusing namespace std;\nusing boost::asio::ip::tcp;\n\nnamespace std {\n    template<typename T>\n    std::string to_string(const T &n) {\n        std::ostringstream stm;\n        stm << n;\n        return stm.str();\n    }\n}\n\nclass session : public std::enable_shared_from_this<session> {\npublic:\n    session(tcp::socket socket) : socket_(move(socket)), mt(rd()), dist(1, 49) {\n    }\n\n    void start() {\n        generateLotteryNumbers();\n        do_write();\n    }\n\nprivate:\n    void generateLotteryNumbers() {\n        numbers.empty();\n        while (numbers.size() < 6) {\n            int candidate = dist(mt);\n            if (find(numbers.begin(), numbers.end(), candidate) == numbers.end())\n                numbers.push_back(candidate);\n        }\n        sort(numbers.begin(), numbers.end());\n        _buffer.empty();\n        for (auto x: numbers) {\n            _buffer.append(std::to_string(x)).append(\",\");\n        }\n        _buffer.erase(_buffer.begin() + _buffer.size() - 1);\n        _buffer.append(\"\\n\");\n    }\n\n    void do_write() {\n        auto self(shared_from_this());\n        boost::asio::async_write(socket_, boost::asio::buffer(_buffer.c_str(), _buffer.size()),\n                                 [this, self](boost::system::error_code ec, std::size_t) {\n                                 });\n    }\n\n    tcp::socket socket_;\n    enum {\n        max_length = 1024\n    };\n    char data_[max_length];\n    string _buffer;\n    random_device rd;\n    mt19937 mt;\n    uniform_int_distribution<int> dist;\n    vector<int> numbers;\n};\n\nclass server {\npublic:\n    server(boost::asio::io_service &io_service, short port)\n            : acceptor_(io_service, tcp::endpoint(tcp::v4(), port)),\n              socket_(io_service) {\n        do_accept();\n    }\n\nprivate:\n    void do_accept() {\n        acceptor_.async_accept(socket_,\n                               [this](boost::system::error_code ec) {\n                                   if (!ec) {\n                                       std::make_shared<session>(std::move(socket_))->start();\n                                   }\n\n                                   do_accept();\n                               });\n    }\n\n    tcp::acceptor acceptor_;\n    tcp::socket socket_;\n};\n\nint main(int argc, char *argv[]) {\n    try {\n        boost::asio::io_service io_service;\n        server s(io_service, std::atoi(\"7001\"));\n        cerr << \"Server is running at port 7001\" << endl;\n        io_service.run();\n    }\n    catch (std::exception &e) {\n        std::cerr << \"Exception: \" << e.what() << endl;\n    }\n\n    return 0;\n}", "meta": {"hexsha": "bbb2e4f634d2bfbf19aae7d13eebefd6030eba0c", "size": 2726, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "module07-networking.with.boost.asio/lottery-server.cpp", "max_stars_repo_name": "deepcloudlabs/dcl118-2020-sep-21", "max_stars_repo_head_hexsha": "900a601f8c9a631a342ad8ce131ad08825d00466", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-09-22T08:52:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-13T19:31:02.000Z", "max_issues_repo_path": "module07-networking.with.boost.asio/lottery-server.cpp", "max_issues_repo_name": "deepcloudlabs/dcl118-2020-sep-21", "max_issues_repo_head_hexsha": "900a601f8c9a631a342ad8ce131ad08825d00466", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "module07-networking.with.boost.asio/lottery-server.cpp", "max_forks_repo_name": "deepcloudlabs/dcl118-2020-sep-21", "max_forks_repo_head_hexsha": "900a601f8c9a631a342ad8ce131ad08825d00466", "max_forks_repo_licenses": ["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.9619047619, "max_line_length": 95, "alphanum_fraction": 0.5264123258, "num_tokens": 605, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145998, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.468908336515403}}
{"text": "/*\n * Copyright (C) 2015, Nils Moehrle, Michael Waechter\n * TU Darmstadt - Graphics, Capture and Massively Parallel Computing\n * All rights reserved.\n *\n * This software may be modified and distributed under the terms\n * of the BSD 3-Clause license. See the LICENSE.txt file for details.\n */\n\n#include <numeric>\n\n#include <mve/image_color.h>\n#include <acc/bvh_tree.h>\n#include <Eigen/Core>\n#include <Eigen/LU>\n\n#include \"util.h\"\n#include \"histogram.h\"\n#include \"texturing.h\"\n#include \"sparse_table.h\"\n#include \"progress_counter.h\"\n\ntypedef acc::BVHTree<unsigned int, math::Vec3f> BVHTree;\n\nTEX_NAMESPACE_BEGIN\n\n/**\n * Dampens the quality of all views in which the face's projection\n * has a much different color than in the majority of views.\n * Returns whether the outlier removal was successfull.\n *\n * @param infos contains information about one face seen from several views\n * @param settings runtime configuration.\n */\nbool\nphotometric_outlier_detection(std::vector<FaceProjectionInfo> * infos, Settings const & settings) {\n    if (infos->size() == 0) return true;\n\n    /* Configuration variables. */\n\n    double const gauss_rejection_threshold = 6e-3;\n\n    /* If all covariances drop below this we stop outlier detection. */\n    double const minimal_covariance = 5e-4;\n\n    int const outlier_detection_iterations = 10;\n    int const minimal_num_inliers = 4;\n\n    float outlier_removal_factor = std::numeric_limits<float>::signaling_NaN();\n    switch (settings.outlier_removal) {\n        case OUTLIER_REMOVAL_NONE: return true;\n        case OUTLIER_REMOVAL_GAUSS_CLAMPING:\n            outlier_removal_factor = 1.0f;\n        break;\n        case OUTLIER_REMOVAL_GAUSS_DAMPING:\n            outlier_removal_factor = 0.2f;\n        break;\n    }\n\n    Eigen::MatrixX3d inliers(infos->size(), 3);\n    std::vector<std::uint32_t> is_inlier(infos->size(), 1);\n    for (std::size_t row = 0; row < infos->size(); ++row) {\n        inliers.row(row) = mve_to_eigen(infos->at(row).mean_color).cast<double>();\n    }\n\n    Eigen::RowVector3d var_mean;\n    Eigen::Matrix3d covariance;\n    Eigen::Matrix3d covariance_inv;\n\n    for (int i = 0; i < outlier_detection_iterations; ++i) {\n\n        if (inliers.rows() < minimal_num_inliers) {\n            return false;\n        }\n\n        /* Calculate the inliers' mean color and color covariance. */\n        var_mean = inliers.colwise().mean();\n        Eigen::MatrixX3d centered = inliers.rowwise() - var_mean;\n        covariance = (centered.adjoint() * centered) / double(inliers.rows() - 1);\n\n        /* If all covariances are very small we stop outlier detection\n         * and only keep the inliers (set quality of outliers to zero). */\n        if (covariance.array().abs().maxCoeff() < minimal_covariance) {\n            for (std::size_t row = 0; row < infos->size(); ++row) {\n                if (!is_inlier[row]) infos->at(row).quality = 0.0f;\n            }\n            return true;\n        }\n\n        /* Invert the covariance. FullPivLU is not the fastest way but\n         * it gives feedback about numerical stability during inversion. */\n        Eigen::FullPivLU<Eigen::Matrix3d> lu(covariance);\n        if (!lu.isInvertible()) {\n            return false;\n        }\n        covariance_inv = lu.inverse();\n\n        /* Compute new number of inliers (all views with a gauss value above a threshold). */\n        for (std::size_t row = 0; row < infos->size(); ++row) {\n            Eigen::RowVector3d color = mve_to_eigen(infos->at(row).mean_color).cast<double>();\n            double gauss_value = multi_gauss_unnormalized<double,3>(color, var_mean, covariance_inv);\n            is_inlier[row] = (gauss_value >= gauss_rejection_threshold ? 1 : 0);\n        }\n        /* Resize Eigen matrix accordingly and fill with new inliers. */\n        inliers.resize(std::accumulate(is_inlier.begin(), is_inlier.end(), 0), Eigen::NoChange);\n        for (std::size_t row = 0, inlier_row = 0; row < infos->size(); ++row) {\n            if (is_inlier[row]) {\n                inliers.row(inlier_row++) = mve_to_eigen(infos->at(row).mean_color).cast<double>();\n            }\n        }\n    }\n\n    covariance_inv *= outlier_removal_factor;\n    for (FaceProjectionInfo & info : *infos) {\n        Eigen::RowVector3d color = mve_to_eigen(info.mean_color).cast<double>();\n        double gauss_value = multi_gauss_unnormalized<double,3>(color, var_mean, covariance_inv);\n        assert(0.0 <= gauss_value && gauss_value <= 1.0);\n        switch(settings.outlier_removal) {\n            case OUTLIER_REMOVAL_NONE: return true;\n            case OUTLIER_REMOVAL_GAUSS_DAMPING:\n                info.quality *= gauss_value;\n            break;\n            case OUTLIER_REMOVAL_GAUSS_CLAMPING:\n                if (gauss_value < gauss_rejection_threshold) info.quality = 0.0f;\n            break;\n        }\n    }\n    return true;\n}\n\nvoid\ncalculate_face_projection_infos(mve::TriangleMesh::ConstPtr mesh,\n    std::vector<TextureView> * texture_views, Settings const & settings,\n    FaceProjectionInfos * face_projection_infos) {\n\n    std::vector<unsigned int> const & faces = mesh->get_faces();\n    std::vector<math::Vec3f> const & vertices = mesh->get_vertices();\n    mve::TriangleMesh::NormalList const & face_normals = mesh->get_face_normals();\n\n    std::size_t const num_views = texture_views->size();\n\n    util::WallTimer timer;\n    std::cout << \"\\tBuilding BVH from \" << faces.size() / 3 << \" faces... \" << std::flush;\n    BVHTree bvh_tree(faces, vertices);\n    std::cout << \"done. (Took: \" << timer.get_elapsed() << \" ms)\" << std::endl;\n\n    ProgressCounter view_counter(\"\\tCalculating face qualities\", num_views);\n    #pragma omp parallel\n    {\n        std::vector<std::pair<std::size_t, FaceProjectionInfo> > projected_face_view_infos;\n\n        #pragma omp for schedule(dynamic)\n        for (std::int32_t j = 0; j < static_cast<std::uint16_t>(num_views); ++j) {\n            view_counter.progress<SIMPLE>();\n\n            TextureView * texture_view = &texture_views->at(j);\n            texture_view->load_image();\n            texture_view->generate_validity_mask();\n\n            if (settings.data_term == DATA_TERM_GMI) {\n                texture_view->generate_gradient_magnitude();\n                texture_view->erode_validity_mask();\n            }\n\n            math::Vec3f const & view_pos = texture_view->get_pos();\n            math::Vec3f const & viewing_direction = texture_view->get_viewing_direction();\n\n            for (std::size_t i = 0; i < faces.size(); i += 3) {\n                std::size_t face_id = i / 3;\n\n                math::Vec3f const & v1 = vertices[faces[i]];\n                math::Vec3f const & v2 = vertices[faces[i + 1]];\n                math::Vec3f const & v3 = vertices[faces[i + 2]];\n                math::Vec3f const & face_normal = face_normals[face_id];\n                math::Vec3f const face_center = (v1 + v2 + v3) / 3.0f;\n\n                /* Check visibility and compute quality */\n\n                math::Vec3f view_to_face_vec = (face_center - view_pos).normalized();\n                math::Vec3f face_to_view_vec = (view_pos - face_center).normalized();\n\n                /* Backface and basic frustum culling */\n                float viewing_angle = face_to_view_vec.dot(face_normal);\n                if (viewing_angle < 0.0f || viewing_direction.dot(view_to_face_vec) < 0.0f)\n                    continue;\n\n                float cutoffAngle = settings.geometric_visibility_test ? 75.0f : 90.0f;\n                if (std::acos(viewing_angle) > MATH_DEG2RAD(cutoffAngle))\n                    continue;\n\n                /* Projects into the valid part of the TextureView? */\n                if (!texture_view->inside(v1, v2, v3))\n                    continue;\n\n                if (settings.geometric_visibility_test) {\n                    /* Viewing rays do not collide? */\n                    bool visible = true;\n                    math::Vec3f const * samples[] = {&v1, &v2, &v3};\n                    // TODO: random monte carlo samples...\n\n                    for (std::size_t k = 0; k < sizeof(samples) / sizeof(samples[0]); ++k) {\n                        BVHTree::Ray ray;\n                        ray.origin = *samples[k];\n                        ray.dir = view_pos - ray.origin;\n                        ray.tmax = ray.dir.norm();\n                        ray.tmin = ray.tmax * 0.0001f;\n                        ray.dir.normalize();\n\n                        BVHTree::Hit hit;\n                        if (bvh_tree.intersect(ray, &hit)) {\n                            visible = false;\n                            break;\n                        }\n                    }\n                    if (!visible) continue;\n                }\n\n                FaceProjectionInfo info = {j, 0.0f, math::Vec3f(0.0f, 0.0f, 0.0f)};\n\n                /* Calculate quality. */\n                texture_view->get_face_info(v1, v2, v3, &info, settings);\n\n                if (info.quality == 0.0) continue;\n\n                /* Change color space. */\n                mve::image::color_rgb_to_ycbcr(*(info.mean_color));\n\n                std::pair<std::size_t, FaceProjectionInfo> pair(face_id, info);\n                projected_face_view_infos.push_back(pair);\n            }\n\n            texture_view->release_image();\n            texture_view->release_validity_mask();\n            if (settings.data_term == DATA_TERM_GMI) {\n                texture_view->release_gradient_magnitude();\n            }\n            view_counter.inc();\n        }\n\n        //std::sort(projected_face_view_infos.begin(), projected_face_view_infos.end());\n\n        #pragma omp critical\n        {\n            for (std::size_t i = projected_face_view_infos.size(); 0 < i; --i) {\n                std::size_t face_id = projected_face_view_infos[i - 1].first;\n                FaceProjectionInfo const & info = projected_face_view_infos[i - 1].second;\n                face_projection_infos->at(face_id).push_back(info);\n            }\n            projected_face_view_infos.clear();\n        }\n    }\n}\n\nvoid\npostprocess_face_infos(Settings const & settings,\n        FaceProjectionInfos * face_projection_infos,\n        DataCosts * data_costs) {\n\n    ProgressCounter face_counter(\"\\tPostprocessing face infos\",\n        face_projection_infos->size());\n    #pragma omp parallel for schedule(dynamic)\n    for (std::int64_t i = 0; i < face_projection_infos->size(); ++i) {\n        face_counter.progress<SIMPLE>();\n\n        std::vector<FaceProjectionInfo> & infos = face_projection_infos->at(i);\n        if (settings.outlier_removal != OUTLIER_REMOVAL_NONE) {\n            photometric_outlier_detection(&infos, settings);\n\n            infos.erase(std::remove_if(infos.begin(), infos.end(),\n                [](FaceProjectionInfo const & info) -> bool {return info.quality == 0.0f;}),\n                infos.end());\n        }\n        std::sort(infos.begin(), infos.end());\n\n        face_counter.inc();\n    }\n\n    /* Determine the function for the normlization. */\n    float max_quality = 0.0f;\n    for (std::size_t i = 0; i < face_projection_infos->size(); ++i)\n        for (FaceProjectionInfo const & info : face_projection_infos->at(i))\n            max_quality = std::max(max_quality, info.quality);\n\n    Histogram hist_qualities(0.0f, max_quality, 10000);\n    for (std::size_t i = 0; i < face_projection_infos->size(); ++i)\n        for (FaceProjectionInfo const & info : face_projection_infos->at(i))\n            hist_qualities.add_value(info.quality);\n\n    float percentile = hist_qualities.get_approx_percentile(0.995f);\n\n    /* Calculate the costs. */\n    for (std::uint32_t i = 0; i < face_projection_infos->size(); ++i) {\n        for (FaceProjectionInfo const & info : face_projection_infos->at(i)) {\n\n            /* Clamp to percentile and normalize. */\n            float normalized_quality = std::min(1.0f, info.quality / percentile);\n            float data_cost = (1.0f - normalized_quality);\n            data_costs->set_value(i, info.view_id, data_cost);\n        }\n\n        /* Ensure that all memory is freeed. */\n        face_projection_infos->at(i) = std::vector<FaceProjectionInfo>();\n    }\n\n    std::cout << \"\\tMaximum quality of a face within an image: \" << max_quality << std::endl;\n    std::cout << \"\\tClamping qualities to \" << percentile << \" within normalization.\" << std::endl;\n}\n\nvoid\ncalculate_data_costs(mve::TriangleMesh::ConstPtr mesh, std::vector<TextureView> * texture_views,\n    Settings const & settings, DataCosts * data_costs) {\n\n    std::size_t const num_faces = mesh->get_faces().size() / 3;\n    std::size_t const num_views = texture_views->size();\n\n    if (num_faces > std::numeric_limits<std::uint32_t>::max())\n        throw std::runtime_error(\"Exeeded maximal number of faces\");\n    if (num_views > std::numeric_limits<std::uint16_t>::max())\n        throw std::runtime_error(\"Exeeded maximal number of views\");\n\n    FaceProjectionInfos face_projection_infos(num_faces);\n    calculate_face_projection_infos(mesh, texture_views, settings, &face_projection_infos);\n    postprocess_face_infos(settings, &face_projection_infos, data_costs);\n}\n\nTEX_NAMESPACE_END\n", "meta": {"hexsha": "ba6f0a36e37868df22cab5b2943d6c3d5148c44a", "size": 13055, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/tex/calculate_data_costs.cpp", "max_stars_repo_name": "lmarzora/mvs-texturing", "max_stars_repo_head_hexsha": "02984be3b6c3b1e5de367a9c13d8b846b2dbc33f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/tex/calculate_data_costs.cpp", "max_issues_repo_name": "lmarzora/mvs-texturing", "max_issues_repo_head_hexsha": "02984be3b6c3b1e5de367a9c13d8b846b2dbc33f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/tex/calculate_data_costs.cpp", "max_forks_repo_name": "lmarzora/mvs-texturing", "max_forks_repo_head_hexsha": "02984be3b6c3b1e5de367a9c13d8b846b2dbc33f", "max_forks_repo_licenses": ["BSD-3-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.9235474006, "max_line_length": 101, "alphanum_fraction": 0.6081194944, "num_tokens": 3136, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.46890832974597024}}
{"text": "// An example showing TEASER++ registration with the Stanford bunny model\n// std\n#include <iostream>\n\n// teaser dependencies\n#include <Eigen/Core>\n#include <teaser/registration.h>\n\n// visualization\n#include \"polyscope/polyscope.h\"\n#include \"polyscope/point_cloud.h\"\n\n// IO \n#include \"IO/readPLY.hpp\"\n\n// Macro constants for generating noise and outliers\n#define NOISE_BOUND 0.05\n#define N_OUTLIERS 1700\n#define OUTLIER_TRANSLATION_LB 5\n#define OUTLIER_TRANSLATION_UB 10\n\n\nint main() {\n\n    Eigen::MatrixXd src_V, trg_V;\n    Eigen::MatrixXi F;\n\n    readPLY(\"../data/1000point_model.ply\", src_V, F);\n    readPLY(\"../data/1000point_scene.ply\", trg_V, F);\n\n    std::cout << \"Size of src_V: [\" << src_V.rows() << \", \" << src_V.cols() << \"]\\n\";\n    std::cout << \"Size of trg_V: [\" << trg_V.rows() << \", \" << trg_V.cols() << \"]\\n\";\n\n    // polyscope init\n    polyscope::init();\n\n    // plot before registration\n    polyscope::registerPointCloud(\"source\", src_V.transpose());\n    polyscope::registerPointCloud(\"target\", trg_V.transpose());\n    polyscope::show();\n\n\n\n    // Run TEASER++ registration\n    // Prepare solver parameters\n    teaser::RobustRegistrationSolver::Params params;\n    params.noise_bound = 0.0337;\n    params.cbar2 = 1;\n    params.estimate_scaling = false;\n    params.rotation_max_iterations = 100;\n    params.rotation_gnc_factor = 1.4;\n    params.rotation_estimation_algorithm =\n        teaser::RobustRegistrationSolver::ROTATION_ESTIMATION_ALGORITHM::GNC_TLS; // GNC_TLS or FGR\n    params.rotation_cost_threshold = 0.005;\n\n    // Solve with TEASER++\n    teaser::RobustRegistrationSolver solver(params);\n    solver.solve(src_V, trg_V);\n\n    auto solution = solver.getSolution();\n\n\n    // extract solution\n    double scale = solution.scale;\n    Eigen::MatrixXd rot = solution.rotation;\n    Eigen::VectorXd tra = solution.translation;\n    \n    // perform rotation and translation\n    src_V = rot  * src_V;\n    src_V = src_V.colwise() + tra;\n\n    // plot after registration\n    polyscope::registerPointCloud(\"source\", src_V.transpose());\n    polyscope::registerPointCloud(\"target\", trg_V.transpose());\n    polyscope::show();\n\n}", "meta": {"hexsha": "b37124d4b3bee54c2fcac7a4d118a8e361ebd214", "size": 2137, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "app/teaser_plusplus_test.cpp", "max_stars_repo_name": "rFalque/TEASER-plusplus_cpp-test", "max_stars_repo_head_hexsha": "304ae814c9361256880f0d2004dea40318a72812", "max_stars_repo_licenses": ["MIT"], "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/teaser_plusplus_test.cpp", "max_issues_repo_name": "rFalque/TEASER-plusplus_cpp-test", "max_issues_repo_head_hexsha": "304ae814c9361256880f0d2004dea40318a72812", "max_issues_repo_licenses": ["MIT"], "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/teaser_plusplus_test.cpp", "max_forks_repo_name": "rFalque/TEASER-plusplus_cpp-test", "max_forks_repo_head_hexsha": "304ae814c9361256880f0d2004dea40318a72812", "max_forks_repo_licenses": ["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.7532467532, "max_line_length": 99, "alphanum_fraction": 0.6855404773, "num_tokens": 543, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.757794360334681, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4689083229765373}}
{"text": "//\n// $Id$\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 \"LinearSolver.hpp\"\n#include \"pwiz/utility/misc/unit.hpp\"\n#include <boost/numeric/ublas/matrix_sparse.hpp>\n#include <boost/numeric/ublas/banded.hpp>\n#include \"pwiz/utility/misc/Std.hpp\"\n#include <cstring>\n\n\nusing namespace pwiz::util;\nusing namespace pwiz::math;\n\n\nnamespace ublas = boost::numeric::ublas;\n\n\nostream* os_ = 0;\n\n\nvoid testDouble()\n{\n    if (os_) *os_ << \"testDouble()\\n\";\n\n    LinearSolver<> solver;\n\n    ublas::matrix<double> A(2,2);\n    A(0,0) = 1; A(0,1) = 2;\n    A(1,0) = 3; A(1,1) = 4;\n   \n    ublas::vector<double> y(2);\n    y(0) = 5;\n    y(1) = 11;\n\n    ublas::vector<double> x = solver.solve(A, y);\n\n    if (os_) *os_ << \"A: \" << A << endl;\n    if (os_) *os_ << \"y: \" << y << endl;\n    if (os_) *os_ << \"x: \" << x << endl;\n\n    unit_assert(x(0) == 1.);\n    unit_assert(x(1) == 2.);\n}\n\n\nvoid testComplex()\n{\n    if (os_) *os_ << \"testComplex()\\n\";\n\n    LinearSolver<> solver;\n    \n    ublas::matrix< complex<double> > A(2,2);\n    A(0,0) = 1; A(0,1) = 2;\n    A(1,0) = 3; A(1,1) = 4;\n   \n    ublas::vector< complex<double> > y(2);\n    y(0) = 5;\n    y(1) = 11;\n\n    ublas::vector< complex<double> > x = solver.solve(A, y);\n\n    if (os_) *os_ << \"A: \" << A << endl;\n    if (os_) *os_ << \"y: \" << y << endl;\n    if (os_) *os_ << \"x: \" << x << endl;\n\n    unit_assert(x(0) == 1.);\n    unit_assert(x(1) == 2.);\n}\n\nvoid testDoubleQR()\n{\n    if (os_) *os_ << \"testDoubleQR()\\n\";\n\n    LinearSolver<LinearSolverType_QR> solver;\n\n    ublas::matrix<double> A(2,2);\n    A(0,0) = 1.; A(0,1) = 2.;\n    A(1,0) = 3.; A(1,1) = 4.;\n   \n    ublas::vector<double> y(2);\n    y(0) = 5.;\n    y(1) = 11.;\n\n    ublas::vector<double> x = solver.solve(A, y);\n\n    if (os_) *os_ << \"A: \" << A << endl;\n    if (os_) *os_ << \"y: \" << y << endl;\n    if (os_) *os_ << \"x: \" << x << endl;\n\n    if (os_) *os_ << x(0) << \" - 1. = \" << x(0) - 1. << endl;\n\n    unit_assert_equal(x(0), 1., 1e-14);\n    unit_assert_equal(x(1), 2., 1e-14);\n}\n\n/*\nvoid testComplexQR()\n{\n    if (os_) *os_ << \"testComplex()\\n\";\n\n    LinearSolver<LinearSolverType_QR> solver;\n    \n    ublas::matrix< complex<double> > A(2,2);\n    A(0,0) = 1; A(0,1) = 2;\n    A(1,0) = 3; A(1,1) = 4;\n   \n    ublas::vector< complex<double> > y(2);\n    y(0) = 5;\n    y(1) = 11;\n\n    ublas::vector< complex<double> > x = solver.solve(A, y);\n\n    if (os_) *os_ << \"A: \" << A << endl;\n    if (os_) *os_ << \"y: \" << y << endl;\n    if (os_) *os_ << \"x: \" << x << endl;\n\n    unit_assert(x(0) == 1.);\n    unit_assert(x(1) == 2.);\n}\n*/\n\n\nvoid testSparse()\n{\n    if (os_) *os_ << \"testSparse()\\n\";\n\n    LinearSolver<> solver;\n\n    ublas::mapped_matrix<double> A(2,2,4);\n    A(0,0) = 1.; A(0,1) = 2.;\n    A(1,0) = 3.; A(1,1) = 4.;\n   \n    ublas::vector<double> y(2);\n    y(0) = 5.;\n    y(1) = 11.;\n\n    ublas::vector<double> x = solver.solve(A, y);\n\n    if (os_) *os_ << \"A: \" << A << endl;\n    if (os_) *os_ << \"y: \" << y << endl;\n    if (os_) *os_ << \"x: \" << x << endl;\n\n    unit_assert_equal(x(0), 1., 1e-14);\n    unit_assert_equal(x(1), 2., 1e-14);\n}\n\n\n/*\nvoid testSparseComplex()\n{\n    if (os_) *os_ << \"testSparseComplex()\\n\";\n\n    LinearSolver<> solver;\n\n    ublas::mapped_matrix< complex<double> > A(2,2,4);\n    A(0,0) = 1.; A(0,1) = 2.;\n    A(1,0) = 3.; A(1,1) = 4.;\n   \n    ublas::vector< complex<double> > y(2);\n    y(0) = 5.;\n    y(1) = 11.;\n\n    ublas::vector< complex<double> > x = solver.solve(A, y);\n\n    if (os_) *os_ << \"A: \" << A << endl;\n    if (os_) *os_ << \"y: \" << y << endl;\n    if (os_) *os_ << \"x: \" << x << endl;\n\n    unit_assert(norm(x(0)-1.) < 1e-14);\n    unit_assert(norm(x(1)-2.) < 1e-14);\n}\n*/\n\n\nvoid testBanded()\n{\n    if (os_) *os_ << \"testBanded()\\n\";\n\n    LinearSolver<> solver;\n\n    ublas::banded_matrix<double> A(2,2,1,1);\n    A(0,0) = 1.; A(0,1) = 2.;\n    A(1,0) = 3.; A(1,1) = 4.;\n   \n    ublas::vector<double> y(2);\n    y(0) = 5.;\n    y(1) = 11.;\n\n    ublas::vector<double> x = solver.solve(A, y);\n\n    if (os_) *os_ << \"A: \" << A << endl;\n    if (os_) *os_ << \"y: \" << y << endl;\n    if (os_) *os_ << \"x: \" << x << endl;\n\n    unit_assert_equal(x(0), 1., 1e-14);\n    unit_assert_equal(x(1), 2., 1e-14);\n}\n\n\nvoid testBandedComplex()\n{\n    if (os_) *os_ << \"testBandedComplex()\\n\";\n\n    LinearSolver<> solver;\n\n    ublas::banded_matrix< complex<double> > A(2,2,1,1);\n    A(0,0) = 1.; A(0,1) = 2.;\n    A(1,0) = 3.; A(1,1) = 4.;\n   \n    ublas::vector< complex<double> > y(2);\n    y(0) = 5.;\n    y(1) = 11.;\n\n    ublas::vector< complex<double> > x = solver.solve(A, y);\n\n    if (os_) *os_ << \"A: \" << A << endl;\n    if (os_) *os_ << \"y: \" << y << endl;\n    if (os_) *os_ << \"x: \" << x << endl;\n\n    unit_assert(norm(x(0)-1.) < 1e-14);\n    unit_assert(norm(x(1)-2.) < 1e-14);\n}\n\n\nint main(int argc, char* argv[])\n{\n    TEST_PROLOG(argc, argv)\n\n    try\n    {\n        if (argc>1 && !strcmp(argv[1],\"-v\")) os_ = &cout;\n        if (os_) *os_ << \"LinearSolverTest\\n\";\n\n        testDouble();\n        testComplex();\n        testDoubleQR();\n        //testComplexQR();\n        testSparse();\n        //testSparseComplex(); // lu_factorize doesn't like mapped_matrix<complex> \n        testBanded();\n        //testBandedComplex(); // FIXME: GCC 4.2 doesn't like this test with link=shared\n    }\n    catch (exception& e)\n    {\n        TEST_FAILED(e.what())\n    }\n    catch (...)\n    {\n        TEST_FAILED(\"Caught unknown exception.\")\n    }\n\n    TEST_EPILOG\n}\n\n", "meta": {"hexsha": "12f80a8fbd1989f14e4b0d7a596d82c1b0753b36", "size": 6088, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pwiz/utility/math/LinearSolverTest.cpp", "max_stars_repo_name": "austinkeller/pwiz", "max_stars_repo_head_hexsha": "aa8e575cb40fd5e97cc7d922e4d8da44c9277cca", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pwiz/utility/math/LinearSolverTest.cpp", "max_issues_repo_name": "austinkeller/pwiz", "max_issues_repo_head_hexsha": "aa8e575cb40fd5e97cc7d922e4d8da44c9277cca", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pwiz/utility/math/LinearSolverTest.cpp", "max_forks_repo_name": "austinkeller/pwiz", "max_forks_repo_head_hexsha": "aa8e575cb40fd5e97cc7d922e4d8da44c9277cca", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.0579710145, "max_line_length": 88, "alphanum_fraction": 0.523653088, "num_tokens": 2247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.757794360334681, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4689083229765373}}
{"text": "\n#include <stdexcept>\n#include <utility>\n#include <boost/cstdint.hpp>\n#include <boost/bind.hpp>\n#include <boost/unordered_set.hpp>\n#include <luabind/luabind.hpp>\n#include <luabind/iterator_policy.hpp>\n#include \"a_star.h\"\n#include \"bresenham_supercover.h\"\n#include \"heightfield.h\"\n\nnamespace math\n{\n\ntemplate<class T>\nheightfield<T>::heightfield(matrix<4,4> const &tf, size_t nrows, size_t ncols):\n    nrows_(nrows),\n    ncols_(ncols)\n{\n\tset_local_to_world(tf);\n\n\theights_.resize(nrows * ncols);\n\n\tlocal_aabb_.lo.set(0, -1, 0);\n\tlocal_aabb_.hi.set(math::scalar(ncols_ - 1), 1, math::scalar(nrows_ - 1));\n}\n\ntemplate<class T>\nheightfield<T>::~heightfield()\n{\n}\n\ntemplate<class T>\nscalar heightfield<T>::y_under(vec<3> const &position, scalar default_value)\n{\n\tvec<3> local_position = position * world_to_local_;\n\n\tint col = (int) local_position.x;\n\tint row = (int) local_position.z;\n\n\tif (col < 0 || row < 0 || col >= (int) ncols_ - 1 || row >= (int) nrows_ - 1) return default_value;\n\n\tscalar v1 = local_y_at(col + 0, row + 0);\n\tscalar v2 = local_y_at(col + 1, row + 0);\n\tscalar v3 = local_y_at(col + 0, row + 1);\n\tscalar v4 = local_y_at(col + 1, row + 1);\n\n\tscalar k1 = local_position.x - col;\n\tscalar k2 = local_position.z - col;\n\n\tscalar v12 = v1 * (1 - k1) + v2 * k1;\n\tscalar v34 = v3 * (1 - k1) + v4 * k1;\n\n\treturn v12 * (1 - k2) + v34 * k2;\n}\n\ntemplate<class T>\nscalar heightfield<T>::max_y_in_cell(int col, int row, scalar default_value) const\n{\n\tif (col < 0 || row < 0 || col >= (int) ncols_ - 1 || row >= (int) nrows_ - 1)\n\t{\n\t\treturn default_value;\n\t}\n\n\tscalar result = (scalar) local_y_at(col + 0, row + 0);\n\tresult = std::max(result, (scalar) local_y_at(col + 0, row + 1));\n\tresult = std::max(result, (scalar) local_y_at(col + 1, row + 0));\n\tresult = std::max(result, (scalar) local_y_at(col + 1, row + 1));\n\n\treturn result;\n}\n\ntemplate<class T>\nscalar heightfield<T>::max_y_in_cell(vec<3> const &position, scalar default_value) const\n{\n\tvec<3> local_position = position * world_to_local_;\n\n\tint col = (int) local_position.x;\n\tint row = (int) local_position.z;\n\n\treturn max_y_in_cell(col, row, default_value);\n}\n\ntemplate<class T>\nvoid heightfield<T>::set_local_to_world(math::matrix<4, 4> const &tf)\n{\n\tlocal_to_world_ = tf;\n    local_to_world_.inverse(world_to_local_);\n}\n\ntemplate<class T> typename heightfield<T>::cell_t\nheightfield<T>::world_position_to_cell(vec<3> const &position) const\n{\n\tvec<3> p = position * world_to_local_;\n\treturn cell_t(int(p.x), int(p.z));\n}\n\ntemplate<class T>\nvec<3> heightfield<T>::cell_to_world_position(cell_t const &cell) const\n{\n\treturn vec<3>((scalar) cell.x + 0.5f, 0, (scalar) cell.y + 0.5f) * local_to_world_;\n}\n\ntemplate<class T>\ncontact_info<3> heightfield<T>::trace(ray<3> const &r, scalar max_distance) const\n{\n\tvec<3> local_p0 = r.r0 * world_to_local_;\n\tvec<3> local_p1 = (r.r0 + normalize(r.a) * max_distance) * world_to_local_;\n\n\tray<3> local_ray(local_p0, local_p1 - local_p0);\n\n\tcontact_info<3> result;\n\tresult.happened = false;\n\n\tscalar local_ray_t0, local_ray_t1;\n\n\tif (!local_aabb_.trace(local_ray, &local_ray_t0, &local_ray_t1)) return result;\n\n\tvec<3> local_p0_adjusted = local_ray.apply(local_ray_t0);\n\tvec<3> local_p1_adjusted = local_ray.apply(local_ray_t1);\n\n\tbresenham_supercover<> cells_iterator(cell_t(int (local_p0_adjusted.x), int(local_p0_adjusted.z)),\n\t\tcell_t(int(local_p1_adjusted.x), int(local_p1_adjusted.z)));\n\n\twhile (true)\n\t{\n\t\tcell_t cell;\n\t\tbool flag;\n\n\t\tboost::tie(cell, flag) = cells_iterator.get();\n\t\tif (flag) break;\n\n\t\tif (cell.x == ncols_ - 1) --cell.x;\n\t\tif (cell.y == nrows_ - 1) --cell.y;\n\n\t\tvec<3> v1 = local_vertex_at(cell.x + 0, cell.y + 0);\n\t\tvec<3> v2 = local_vertex_at(cell.x + 0, cell.y + 1);\n\t\tvec<3> v3 = local_vertex_at(cell.x + 1, cell.y + 1);\n\t\tvec<3> v4 = local_vertex_at(cell.x + 1, cell.y + 0);\n\n\t\ttriangle<3> t1(v1, v2, v3);\n\t\ttriangle<3> t2(v1, v3, v4);\n\n\t\tbool trace_h1, trace_h2;\n        scalar trace_t1, trace_t2;\n\t\tvec<3> trace_p1, trace_p2;\n\n\t\ttrace_h1 = t1.trace(local_ray, trace_t1, trace_p1);\n\t\ttrace_h2 = t2.trace(local_ray, trace_t2, trace_p2);\n\n\t\tif (trace_h1 || trace_h2)\n        {\n            contact_info<3> ci;\n\n            ci.happened = true;\n            ci.penetrated = false;\n\n            if (trace_h1 && ((trace_h2 && trace_t1 < trace_t2) || trace_h2 == false))\n            {\n                ci.position = trace_p1;\n                ci.normal = t1.get_normal();\n                ci.time = trace_t1;\n            }\n            else\n            {\n                ci.position = trace_p2;\n                ci.normal = t2.get_normal();\n                ci.time = trace_t2;\n            }\n\n\t\t\tif (result.worse_than(ci))\n\t\t\t{\n\t\t\t\tresult = ci;\n\t\t\t}\n        }\n    }\n\n\tresult.position = result.position * local_to_world_;\n\n\treturn result;\n}\n\ntemplate<class T>\nvoid heightfield<T>::load_from_raw_buffer(value_t const *heights)\n{\n    heights_.assign(heights, heights + nsamples());\n\n\tpost_load();\n}\n\ntemplate<class T>\nvoid heightfield<T>::resize(size_t ncols, size_t nrows)\n{\n\tstd::vector<value_t> heights;\n\theights.resize(nrows * ncols);\n\n\tfor (size_t i = 0, ni = std::min(nrows, nrows_); i < ni; ++i)\n\t{\n\t\tfor (size_t j = 0, nj = std::min(ncols, ncols_); j < nj; ++j)\n\t\t{\n\t\t\theights[i * ncols + j] = heights_[i * ncols_ + j];\n\t\t}\n\t}\n\n\theights_.swap(heights);\n\tncols_ = ncols;\n\tnrows_ = nrows;\n\n\tpost_load();\n}\n\nnamespace\n{\ntemplate<class T>\nclass scorer_closure {\npublic:\n\ttypedef typename heightfield<T>::cell_t cell_t;\n\n\tscorer_closure(heightfield<T> const *hf, scalar min_value, cell_t goal, std::vector<cell_t> const &obstacles):\n\t\thf_(hf),\n\t\tmin_value_(min_value),\n\t\tgoal_(goal)\n\t{\n\t\tobstacles_.insert(obstacles.begin(), obstacles.end());\n\t}\n\n\tscalar get_score(cell_t const &cell) const\n\t{\n\t\tif (cell.x < 0) return -1;\n\t\tif (cell.y < 0) return -1;\n\t\tif (cell.x >= (int) hf_->nrows()) return -1;\n\t\tif (cell.y >= (int) hf_->ncols()) return -1;\n\n\t\ttypename obstacles_t::const_iterator it = obstacles_.find(cell);\n\t\tif (it != obstacles_.end()) return -1;\n\n\t\tscalar delta = (scalar) (cell - goal_).length_sq();\n\n\t\tif (hf_->max_y_in_cell(cell.x, cell.y) < min_value_)\n\t\t{\n\t\t\treturn delta;\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn -1;\n\t\t}\n\t}\n\nprivate:\n\tstruct cell_hash {\n\t\tstd::size_t operator ()(cell_t const &cell) const {\n\t\t\treturn (cell.x * 1011) ^ cell.y;\n\t\t}\n\t};\n\n\tstruct cell_eq {\n\t\tstd::size_t operator ()(cell_t const &lhs, cell_t const &rhs) const {\n\t\t\treturn lhs == rhs;\n\t\t}\n\t};\n\n\ttypedef boost::unordered_set<cell_t, cell_hash, cell_eq> obstacles_t;\n\n\theightfield<T> const *hf_;\n\tscalar min_value_;\n\tcell_t goal_;\n\tobstacles_t obstacles_;\n};\n}\n\ntemplate<class T> std::vector<typename heightfield<T>::cell_t>\nheightfield<T>::build_path(vec<3> const &from, vec<3> const &to, value_t min_value, bool allow_best_heuristic_point,\n\tstd::vector<cell_t> const &obstacles) const\n{\n\tcell_t start = world_position_to_cell(from);\n\tcell_t goal = world_position_to_cell(to);\n\n\tscorer_closure<T> scorer(this, min_value, goal, obstacles);\n\ta_star pathfinder(start, goal, boost::bind(&scorer_closure<T>::get_score, &scorer, _1));\n\n\tpathfinder.calculate_path();\n\n\treturn pathfinder.build_path(allow_best_heuristic_point);\n}\n\ntemplate<class T>\nvoid heightfield<T>::post_load()\n{\n\tlocal_aabb_.null();\n\n\tfor (typename std::vector<value_t>::const_iterator it = heights_.begin();\n\t\t it != heights_.end(); ++it)\n\t{\n\t\tif (local_aabb_.lo.y > *it) local_aabb_.lo.y = *it;\n\t\tif (local_aabb_.hi.y < *it) local_aabb_.hi.y = *it;\n\t}\n\n\tlocal_aabb_.lo.y -= 1;\n\tlocal_aabb_.hi.y += 1;\n\n\tlocal_aabb_.lo.x = 0;\n\tlocal_aabb_.lo.z = 0;\n\n\tlocal_aabb_.hi.x = scalar(ncols_ - 1);\n\tlocal_aabb_.hi.z = scalar(nrows_ - 1);\n}\n\ntemplate<class T>\nvoid heightfield<T>::bind(lua_State *L, char const *name)\n{\n\tusing namespace luabind;\n\n\tmodule(L, \"math\")\n\t[\n\t\tclass_<heightfield>(name)\n\t\t.def(constructor<matrix<4,4> const &, size_t, size_t>())\n\t\t.def(\"y_under\", &heightfield::y_under)\n\t\t.def(\"max_y_in_cell\", (scalar (heightfield::*)(vec<3> const &, scalar) const) &heightfield::max_y_in_cell)\n\t\t.def(\"ncols\", &heightfield::ncols)\n\t\t.def(\"nrows\", &heightfield::nrows)\n\t\t.def(\"set_local_to_world\", &heightfield::set_local_to_world)\n\t\t.def(\"get_local_aabb\", &heightfield::get_local_aabb)\n\t\t.def(\"world_position_to_cell\", &heightfield::world_position_to_cell)\n\t\t.def(\"cell_to_world_position\", &heightfield::cell_to_world_position)\n\t\t.def(\"build_path\", &heightfield::build_path)\n\t\t.def(\"trace\", &heightfield::trace)\n\t\t.def(\"resize\", &heightfield::resize)\n\t];\n}\n\ntemplate class heightfield<boost::uint8_t>;\ntemplate class heightfield<boost::uint16_t>;\ntemplate class heightfield<scalar>;\n\nvoid bind_heightfield(lua_State *L)\n{\n\theightfield<boost::uint8_t>::bind(L, \"heightfield_u8\");\n\theightfield<boost::uint16_t>::bind(L, \"heightfield_u16\");\n\theightfield<scalar>::bind(L, \"heightfield_s\");\n}\n\n}\n", "meta": {"hexsha": "e04ce78d3212a55fcc6f14f555a4ff9442caa5d9", "size": 8754, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/math/heightfield.cc", "max_stars_repo_name": "mnvl/scratch", "max_stars_repo_head_hexsha": "7717772e0b9a85c8feb73fdc3562425f48b4a727", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-08-15T11:55:32.000Z", "max_stars_repo_stars_event_max_datetime": "2016-08-15T11:55:32.000Z", "max_issues_repo_path": "src/math/heightfield.cc", "max_issues_repo_name": "mnvl/scratch", "max_issues_repo_head_hexsha": "7717772e0b9a85c8feb73fdc3562425f48b4a727", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/math/heightfield.cc", "max_forks_repo_name": "mnvl/scratch", "max_forks_repo_head_hexsha": "7717772e0b9a85c8feb73fdc3562425f48b4a727", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.4476744186, "max_line_length": 116, "alphanum_fraction": 0.669750971, "num_tokens": 2701, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.4688461466904594}}
{"text": "#include \"MP2.hpp\"\n#include \"RHF.hpp\"\n#include <armadillo>\n\nnamespace willow {\nnamespace qcmol {\n\narma::mat MP2::cphf(const arma::mat &l_ai, const arma::vec &ao_tei,\n                    const bool l_print) {\n\n  const double epsilon = 1.0e-8;\n  // arma::vec v_p_ai (nvir*nocc, arma::fill::zeros);\n  // arma::mat pm_ai  (v_p_aj.memptr(), nvir, nocc, false);\n\n  arma::mat Cvir = Cmat.submat(0, ivir1, nbf - 1, ivir2);\n  arma::mat Cocc = Cmat.submat(0, 0, nbf - 1, iocc2);\n\n  arma::vec v_Pm(nvir * nocc, arma::fill::zeros);\n  arma::mat Pm(v_Pm.memptr(), nvir, nocc, false);\n\n  for (auto moi = 0; moi < nocc; moi++) {\n    for (auto am = 0; am < nvir; am++) {\n      auto moa = ivir1 + am;\n      Pm(am, moi) = l_ai(am, moi) / (eval(moa) - eval(moi));\n    }\n  }\n\n  std::vector<arma::vec> Pm_list;\n  Pm_list.push_back(v_Pm);\n\n  arma::vec v_APm(nvir * nocc, arma::fill::zeros);\n  arma::mat APm(v_APm.memptr(), nvir, nocc, false);\n  std::vector<arma::vec> APm_list;\n\n  // arma::mat Dm  (nbf,  nbf,  arma::fill::zeros);\n  // arma::mat Gm  (nbf,  nbf,  arma::fill::zeros);\n\n  arma::vec P_sum_old(nvir * nocc, arma::fill::zeros);\n  arma::vec P_sum_new(nvir * nocc, arma::fill::zeros);\n\n  const int maxiter = 30;\n\n  for (auto iter = 0; iter < maxiter; ++iter) {\n\n    const int ndim = iter + 1;\n\n    // Compute A*P[i-1] (call AP matrix)\n    v_Pm = Pm_list[iter];\n\n    arma::mat Dm = Cvir * Pm * Cocc.t();\n    arma::mat Gm = g_matrix(ao_tei, Dm);\n    APm = 4.0 * Cvir.t() * Gm * Cocc;\n\n    for (auto moi = 0; moi < nocc; moi++) {\n      for (auto am = 0; am < nvir; am++) {\n        auto moa = ivir1 + am;\n        double tmpval = APm(am, moi) / (eval(moi) - eval(moa));\n        APm(am, moi) = tmpval;\n      }\n    }\n\n    APm_list.push_back(v_APm);\n\n    // compute alpha\n    // Solve the linear system of equations C*X = B\n    // where C is matrix, X and B are vector\n    // put result (x) into array alpha\n    arma::vec alpha(ndim, arma::fill::zeros);\n    {\n      arma::vec norm(ndim, arma::fill::zeros);\n\n      for (auto i = 0; i < ndim; i++) {\n        norm(i) = arma::norm(Pm_list[i]);\n      }\n\n      // Construct matrix Cm\n      arma::mat Cm(ndim, ndim, arma::fill::zeros);\n\n      for (auto j = 0; j < ndim; j++) {\n        for (auto i = 0; i < ndim; i++) {\n\n          double tmp1 = -arma::dot(Pm_list[i], APm_list[j]);\n\n          if (i == j) {\n            tmp1 += arma::dot(Pm_list[i], Pm_list[i]);\n          }\n\n          Cm(i, j) = tmp1 / (norm(i) * norm(j));\n        }\n      }\n\n      arma::vec Bv(ndim, arma::fill::zeros);\n      Bv(0) = norm(0);\n\n      arma::vec Xv = Cm.i() * Bv;\n\n      for (auto i = 0; i < ndim; i++) {\n        alpha(i) = Xv(i) / norm(i);\n      }\n    }\n\n    // P_sum_new = alpha[0]*P[0] +\n    P_sum_new.zeros();\n    for (auto j = 0; j < ndim; j++) {\n      P_sum_new += alpha(j) * Pm_list[j];\n    }\n\n    // Test for convergence\n    // (based on RMS (P2aj_new - P2aj_old)\n    // and max abs. val. of element\n\n    double tmpval = 0.0;\n    double maxabs = 0.0;\n    for (auto j = 0; j < nocc * nvir; j++) {\n      double tmpval1 = P_sum_new(j) - P_sum_old(j);\n      double tmpval2 = tmpval1 * tmpval1;\n      tmpval += tmpval2;\n      if (tmpval2 > maxabs)\n        maxabs = tmpval2;\n    }\n\n    if (std::sqrt(tmpval / (nocc * nvir)) < epsilon &&\n        std::sqrt(maxabs) < epsilon)\n      break;\n\n    // Put P_sum_new into P_sum_old\n\n    P_sum_old = P_sum_new;\n\n    // Compute projection of A*P[i-1] on P[0], ..., P[i-1]\n\n    arma::vec projctn(nocc * nvir, arma::fill::zeros);\n\n    for (auto j = 0; j < iter + 1; j++) {\n      double dot_prod = arma::dot(Pm_list[j], Pm_list[j]);\n      double coef = arma::dot(Pm_list[j], APm) / dot_prod;\n\n      projctn += coef * Pm_list[j];\n    }\n\n    Pm_list.push_back(v_APm - projctn);\n\n    // Test for convergence (based on norm (Pm[i]))\n\n    double rmsd = arma::norm(Pm_list[iter + 1]) / sqrt(nocc * nvir);\n    // double rmsd = arma::norm (p_ai - p_ai_old);\n\n    if (l_print)\n      std::cout << \"Iter CPHF \" << iter << \"   \" << rmsd << std::endl;\n    if (rmsd < epsilon)\n      break;\n  }\n\n  // Converged vector is in P_sum_new\n\n  arma::mat p_ai(P_sum_new.memptr(), nvir, nocc, true);\n\n  return p_ai;\n}\n\n/*\narma:mat MP2::cphf_old ()\n{\n  double epsilon = 1.0e-8;\n\n  for (auto moi = 0; moi < nocc; moi++) {\n    for (auto am = 0; am < navir; am++) {\n      auto moa = ivir1 + am;\n      p_ai(am,moi) = l_ai(am,moi)/(eval(moa) - eval(moi));\n    }\n  }\n\n  // Solve the CPHF equations (iteratively, with DIIS like method)\n  int ii = 0;\n  int niter = 0;\n  const int maxiter = 30;\n  for (auto iter = 0; iter != maxiter; ++iter) {\n\n    arma::mat p_ai_old = p_ai;\n    // Compute A*P[ii-1]\n    // Dm(nbf,nbf) = (nbf,navir)*(navir,nocc)*(nbf,nocc)\n    arma::mat Dm = Cvir*p_ai_old*Cocc.t();\n    arma::mat Gm = g_matrix (ints.TEI, Dm);\n\n    //  APm(navir,nocc) =\n    arma::mat APm = 2.0*Cvir.t()*Gm*Cocc;\n\n    for (auto moi = 0; moi < nocc; moi++) {\n      for (auto am = 0; am < navir; am++) {\n        auto moa = ivir1 + am;\n        p_ai (am,moi) = (l_ai(am,moi) - APm(am,moi))/(eval(moa) - eval(moi));\n      }\n    }\n    p_ai = 0.6*p_ai + 0.4*p_ai_old;\n\n    double rmsd = arma::norm (p_ai - p_ai_old);\n\n    std::cout << \"Iter CPHF \" << iter << \"   \" << rmsd << std::endl;\n    if (rmsd < 1.0e-7) break;\n  }\n\n  std::cout << \"p_ai \\n\";\n\n  return p_ai;\n}\n*/\n\n} // namespace qcmol\n} // namespace willow\n", "meta": {"hexsha": "4ed7f402b9d88562967534107ac06cca0c80b916", "size": 5314, "ext": "cc", "lang": "C++", "max_stars_repo_path": "w-qcmol/MP2cphf.cc", "max_stars_repo_name": "swillow/mbe_pol", "max_stars_repo_head_hexsha": "5accadc91eff9f9120873e10b1b8fb56fd96f160", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-05-01T22:35:29.000Z", "max_stars_repo_stars_event_max_datetime": "2016-05-01T22:35:33.000Z", "max_issues_repo_path": "w-qcmol/MP2cphf.cc", "max_issues_repo_name": "swillow/mbe_pol", "max_issues_repo_head_hexsha": "5accadc91eff9f9120873e10b1b8fb56fd96f160", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "w-qcmol/MP2cphf.cc", "max_forks_repo_name": "swillow/mbe_pol", "max_forks_repo_head_hexsha": "5accadc91eff9f9120873e10b1b8fb56fd96f160", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.3047619048, "max_line_length": 77, "alphanum_fraction": 0.5374482499, "num_tokens": 1932, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.4688461422117598}}
{"text": "//\n// Copyright (c) 2020 INRIA\n//\n\n#include <pinocchio/math/matrix.hpp>\n\n#include <boost/variant.hpp> // to avoid C99 warnings\n\n#include <boost/test/unit_test.hpp>\n#include <boost/utility/binary.hpp>\n\nBOOST_AUTO_TEST_SUITE(BOOST_TEST_MODULE)\n\nBOOST_AUTO_TEST_CASE(test_isNormalized)\n{\n  srand(0);\n\n  using namespace pinocchio;\n  typedef Eigen::Matrix<double,Eigen::Dynamic,1> Vector;\n  \n  const int max_size = 1000;\n#ifdef NDEBUG\n  const int max_test = 1e6;\n#else\n  const int max_test = 1e2;\n#endif\n  for(int i = 0; i < max_test; ++i)\n  {\n    const Eigen::DenseIndex size = rand() % max_size + 1; // random vector size\n    Vector vec;\n    vec = Vector::Random(size) + Vector::Constant(size,2.);\n    BOOST_CHECK(!isNormalized(vec));\n    \n    vec.normalize();\n    BOOST_CHECK(isNormalized(vec));\n    \n    // Specific check for the Zero vector\n    BOOST_CHECK(!isNormalized(Vector(Vector::Zero(size))));\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "1c9fd8e20f0d8cbea662922347a2f4028206cec8", "size": 936, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittest/vector.cpp", "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": "unittest/vector.cpp", "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": "unittest/vector.cpp", "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": 21.7674418605, "max_line_length": 79, "alphanum_fraction": 0.6923076923, "num_tokens": 250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.740174350576073, "lm_q2_score": 0.6334102775181399, "lm_q1q2_score": 0.46883404081019936}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n// Unit Test\r\n\r\n// Copyright (c) 2007-2015 Barend Gehrels, Amsterdam, the Netherlands.\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_TEST_DIFFERENCE_HPP\r\n#define BOOST_GEOMETRY_TEST_DIFFERENCE_HPP\r\n\r\n#include <fstream>\r\n#include <iomanip>\r\n\r\n#include <geometry_test_common.hpp>\r\n\r\n#include <boost/core/ignore_unused.hpp>\r\n#include <boost/foreach.hpp>\r\n\r\n#include <boost/range/algorithm/copy.hpp>\r\n\r\n#include <boost/geometry/algorithms/correct.hpp>\r\n#include <boost/geometry/algorithms/difference.hpp>\r\n#include <boost/geometry/algorithms/sym_difference.hpp>\r\n\r\n#include <boost/geometry/algorithms/area.hpp>\r\n#include <boost/geometry/algorithms/length.hpp>\r\n#include <boost/geometry/algorithms/num_points.hpp>\r\n\r\n#include <boost/geometry/geometries/geometries.hpp>\r\n\r\n\r\n#include <boost/geometry/geometries/multi_point.hpp>\r\n#include <boost/geometry/geometries/multi_linestring.hpp>\r\n#include <boost/geometry/geometries/multi_polygon.hpp>\r\n\r\n#include <boost/geometry/strategies/strategies.hpp>\r\n\r\n#include <boost/geometry/io/wkt/wkt.hpp>\r\n\r\n\r\n#if defined(TEST_WITH_SVG)\r\n#  define BOOST_GEOMETRY_DEBUG_SEGMENT_IDENTIFIER\r\n#  define BOOST_GEOMETRY_DEBUG_IDENTIFIER\r\n#  include <boost/geometry/io/svg/svg_mapper.hpp>\r\n#  include <boost/geometry/algorithms/detail/overlay/debug_turn_info.hpp>\r\n#endif\r\n\r\n\r\ntemplate <typename Output, typename G1, typename G2>\r\nvoid difference_output(std::string const& caseid, G1 const& g1, G2 const& g2, Output const& output)\r\n{\r\n    boost::ignore_unused(caseid, g1, g2, output);\r\n\r\n#if defined(TEST_WITH_SVG)\r\n    {\r\n        typedef typename bg::coordinate_type<G1>::type coordinate_type;\r\n        typedef typename bg::point_type<G1>::type point_type;\r\n\r\n        std::ostringstream filename;\r\n        filename << \"difference_\"\r\n            << caseid << \"_\"\r\n            << string_from_type<coordinate_type>::name()\r\n#if defined(BOOST_GEOMETRY_NO_ROBUSTNESS)\r\n            << \"_no_rob\"\r\n#endif\r\n            << \".svg\";\r\n\r\n        std::ofstream svg(filename.str().c_str());\r\n\r\n        bg::svg_mapper<point_type> mapper(svg, 500, 500);\r\n\r\n        mapper.add(g1);\r\n        mapper.add(g2);\r\n\r\n        mapper.map(g1, \"fill-opacity:0.3;fill:rgb(51,51,153);stroke:rgb(51,51,153);stroke-width:3\");\r\n        mapper.map(g2, \"fill-opacity:0.5;fill:rgb(153,204,0);stroke:rgb(153,204,0);stroke-width:3\");\r\n\r\n\r\n        for (typename Output::const_iterator it = output.begin(); it != output.end(); ++it)\r\n        {\r\n            mapper.map(*it,\r\n                //sym ? \"fill-opacity:0.2;stroke-opacity:0.4;fill:rgb(255,255,0);stroke:rgb(255,0,255);stroke-width:8\" :\r\n                \"fill-opacity:0.2;stroke-opacity:0.4;fill:rgb(255,0,0);stroke:rgb(255,0,255);stroke-width:8\");\r\n        }\r\n    }\r\n#endif\r\n}\r\n\r\ntemplate <typename OutputType, typename G1, typename G2>\r\nvoid test_difference(std::string const& caseid, G1 const& g1, G2 const& g2,\r\n        int expected_count, int expected_point_count,\r\n        double expected_area,\r\n        double percentage = 0.0001,\r\n        bool sym = false)\r\n{\r\n    typedef typename bg::coordinate_type<G1>::type coordinate_type;\r\n    boost::ignore_unused<coordinate_type>();\r\n\r\n    std::vector<OutputType> clip;\r\n\r\n    if (sym)\r\n    {\r\n        bg::sym_difference(g1, g2, clip);\r\n    }\r\n    else\r\n    {\r\n        bg::difference(g1, g2, clip);\r\n    }\r\n\r\n    typename bg::default_area_result<G1>::type area = 0;\r\n    std::size_t n = 0;\r\n    for (typename std::vector<OutputType>::iterator it = clip.begin();\r\n            it != clip.end();\r\n            ++it)\r\n    {\r\n        if (expected_point_count >= 0)\r\n        {\r\n            n += bg::num_points(*it);\r\n        }\r\n\r\n        area += bg::area(*it);\r\n    }\r\n\r\n    difference_output(caseid, g1, g2, clip);\r\n\r\n#ifndef BOOST_GEOMETRY_DEBUG_ASSEMBLE\r\n    {\r\n        // Test inserter functionality\r\n        // Test if inserter returns output-iterator (using Boost.Range copy)\r\n        typedef typename bg::point_type<G1>::type point_type;\r\n        typedef typename bg::rescale_policy_type<point_type>::type\r\n            rescale_policy_type;\r\n\r\n        rescale_policy_type rescale_policy\r\n                = bg::get_rescale_policy<rescale_policy_type>(g1, g2);\r\n\r\n        std::vector<OutputType> inserted, array_with_one_empty_geometry;\r\n        array_with_one_empty_geometry.push_back(OutputType());\r\n        if (sym)\r\n        {\r\n            boost::copy(array_with_one_empty_geometry,\r\n                bg::detail::sym_difference::sym_difference_insert<OutputType>\r\n                    (g1, g2, rescale_policy, std::back_inserter(inserted)));\r\n        }\r\n        else\r\n        {\r\n            boost::copy(array_with_one_empty_geometry,\r\n                bg::detail::difference::difference_insert<OutputType>(\r\n                    g1, g2, rescale_policy, std::back_inserter(inserted)));\r\n        }\r\n\r\n        BOOST_CHECK_EQUAL(boost::size(clip), boost::size(inserted) - 1);\r\n    }\r\n#endif\r\n\r\n\r\n\r\n#if ! defined(BOOST_GEOMETRY_NO_BOOST_TEST)\r\n    if (expected_point_count >= 0)\r\n    {\r\n        BOOST_CHECK_MESSAGE(bg::math::abs(int(n) - expected_point_count) < 3,\r\n                \"difference: \" << caseid\r\n                << \" #points expected: \" << expected_point_count\r\n                << \" detected: \" << n\r\n                << \" type: \" << (type_for_assert_message<G1, G2>())\r\n                );\r\n    }\r\n\r\n    if (expected_count >= 0)\r\n    {\r\n        BOOST_CHECK_MESSAGE(int(clip.size()) == expected_count,\r\n                \"difference: \" << caseid\r\n                << \" #outputs expected: \" << expected_count\r\n                << \" detected: \" << clip.size()\r\n                << \" type: \" << (type_for_assert_message<G1, G2>())\r\n                );\r\n    }\r\n\r\n    BOOST_CHECK_CLOSE(area, expected_area, percentage);\r\n#endif\r\n\r\n\r\n}\r\n\r\n\r\n#ifdef BOOST_GEOMETRY_CHECK_WITH_POSTGIS\r\nstatic int counter = 0;\r\n#endif\r\n\r\n\r\ntemplate <typename OutputType, typename G1, typename G2>\r\nvoid test_one(std::string const& caseid,\r\n        std::string const& wkt1, std::string const& wkt2,\r\n        int expected_count1,\r\n        int expected_point_count1,\r\n        double expected_area1,\r\n        int expected_count2,\r\n        int expected_point_count2,\r\n        double expected_area2,\r\n        int expected_count_s,\r\n        int expected_point_count_s,\r\n        double expected_area_s,\r\n        double percentage = 0.0001)\r\n{\r\n#ifdef BOOST_GEOMETRY_CHECK_WITH_SQLSERVER\r\n    std::cout\r\n        << \"-- \" << caseid << std::endl\r\n        << \"with qu as (\" << std::endl\r\n        << \"select geometry::STGeomFromText('\" << wkt1 << \"',0) as p,\" << std::endl\r\n        << \"geometry::STGeomFromText('\" << wkt2 << \"',0) as q)\" << std::endl\r\n        << \"select \" << std::endl\r\n        << \" p.STDifference(q).STNumGeometries() as cnt1,p.STDifference(q).STNumPoints() as pcnt1,p.STDifference(q).STArea() as area1,\" << std::endl\r\n        << \" q.STDifference(p).STNumGeometries() as cnt2,q.STDifference(p).STNumPoints() as pcnt2,q.STDifference(p).STArea() as area2,\" << std::endl\r\n        << \" p.STDifference(q) as d1,q.STDifference(p) as d2 from qu\" << std::endl << std::endl;\r\n#endif\r\n\r\n\r\n    G1 g1;\r\n    bg::read_wkt(wkt1, g1);\r\n\r\n    G2 g2;\r\n    bg::read_wkt(wkt2, g2);\r\n\r\n    bg::correct(g1);\r\n    bg::correct(g2);\r\n\r\n    test_difference<OutputType>(caseid + \"_a\", g1, g2,\r\n        expected_count1, expected_point_count1,\r\n        expected_area1, percentage);\r\n#ifdef BOOST_GEOMETRY_DEBUG_ASSEMBLE\r\n    return;\r\n#endif\r\n    test_difference<OutputType>(caseid + \"_b\", g2, g1,\r\n        expected_count2, expected_point_count2,\r\n        expected_area2, percentage);\r\n    test_difference<OutputType>(caseid + \"_s\", g1, g2,\r\n        expected_count_s,\r\n        expected_point_count_s,\r\n        expected_area_s,\r\n        percentage, true);\r\n\r\n\r\n#ifdef BOOST_GEOMETRY_CHECK_WITH_POSTGIS\r\n    std::cout\r\n        << (counter > 0 ? \"union \" : \"\")\r\n        << \"select \" << counter++\r\n        << \", '\" << caseid << \"' as caseid\"\r\n        << \", ST_NumPoints(ST_Difference(ST_GeomFromText('\" << wkt1 << \"'), \"\r\n        << \"      ST_GeomFromText('\" << wkt2 << \"'))) \"\r\n        << \", ST_NumGeometries(ST_Difference(ST_GeomFromText('\" << wkt1 << \"'), \"\r\n        << \"      ST_GeomFromText('\" << wkt2 << \"'))) \"\r\n        << \", ST_Area(ST_Difference(ST_GeomFromText('\" << wkt1 << \"'), \"\r\n        << \"      ST_GeomFromText('\" << wkt2 << \"'))) \"\r\n        //<< \", \" << expected_area1 << \" as expected_area_a\"\r\n        //<< \", \" << expected_count1 << \" as expected_count_a\"\r\n        << \", ST_NumPoints(ST_Difference(ST_GeomFromText('\" << wkt2 << \"'), \"\r\n        << \"      ST_GeomFromText('\" << wkt1 << \"'))) \"\r\n        << \", ST_NumGeometries(ST_Difference(ST_GeomFromText('\" << wkt2 << \"'), \"\r\n        << \"      ST_GeomFromText('\" << wkt1 << \"'))) \"\r\n        << \", ST_Area(ST_Difference(ST_GeomFromText('\" << wkt2 << \"'), \"\r\n        << \"      ST_GeomFromText('\" << wkt1 << \"'))) \"\r\n        //<< \", \" << expected_area2 << \" as expected_area_b\"\r\n        //<< \", \" << expected_count2 << \" as expected_count_b\"\r\n        << \", ST_NumPoints(ST_SymDifference(ST_GeomFromText('\" << wkt1 << \"'), \"\r\n        << \"      ST_GeomFromText('\" << wkt2 << \"'))) \"\r\n        << \", ST_NumGeometries(ST_SymDifference(ST_GeomFromText('\" << wkt1 << \"'), \"\r\n        << \"      ST_GeomFromText('\" << wkt2 << \"'))) \"\r\n        << \", ST_Area(ST_SymDifference(ST_GeomFromText('\" << wkt1 << \"'), \"\r\n        << \"      ST_GeomFromText('\" << wkt2 << \"'))) \"\r\n        //<< \", \" << expected_area1 + expected_area2 << \" as expected_area_s\"\r\n        //<< \", \" << expected_count1 + expected_count2 << \" as expected_count_s\"\r\n        << std::endl;\r\n#endif\r\n\r\n}\r\n\r\ntemplate <typename OutputType, typename G1, typename G2>\r\nvoid test_one(std::string const& caseid,\r\n        std::string const& wkt1, std::string const& wkt2,\r\n        int expected_count1,\r\n        int expected_point_count1,\r\n        double expected_area1,\r\n        int expected_count2,\r\n        int expected_point_count2,\r\n        double expected_area2,\r\n        double percentage = 0.0001)\r\n{\r\n    test_one<OutputType, G1, G2>(caseid, wkt1, wkt2,\r\n        expected_count1, expected_point_count1, expected_area1,\r\n        expected_count2, expected_point_count2, expected_area2,\r\n        expected_count1 + expected_count2,\r\n        expected_point_count1 >= 0 && expected_point_count2 >= 0\r\n            ? (expected_point_count1 + expected_point_count2) : -1,\r\n        expected_area1 + expected_area2,\r\n        percentage);\r\n}\r\n\r\ntemplate <typename OutputType, typename G1, typename G2>\r\nvoid test_one_lp(std::string const& caseid,\r\n        std::string const& wkt1, std::string const& wkt2,\r\n        std::size_t expected_count,\r\n        int expected_point_count,\r\n        double expected_length)\r\n{\r\n    G1 g1;\r\n    bg::read_wkt(wkt1, g1);\r\n\r\n    G2 g2;\r\n    bg::read_wkt(wkt2, g2);\r\n\r\n    bg::correct(g1);\r\n\r\n    std::vector<OutputType> pieces;\r\n    bg::difference(g1, g2, pieces);\r\n\r\n    typename bg::default_length_result<G1>::type length = 0;\r\n    std::size_t n = 0;\r\n    std::size_t piece_count = 0;\r\n    for (typename std::vector<OutputType>::iterator it = pieces.begin();\r\n            it != pieces.end();\r\n            ++it)\r\n    {\r\n        if (expected_point_count >= 0)\r\n        {\r\n            n += bg::num_points(*it);\r\n        }\r\n        piece_count++;\r\n        length += bg::length(*it);\r\n    }\r\n\r\n    BOOST_CHECK_MESSAGE(piece_count == expected_count,\r\n            \"difference: \" << caseid\r\n            << \" #outputs expected: \" << expected_count\r\n            << \" detected: \" << pieces.size()\r\n            );\r\n\r\n    if (expected_point_count >= 0)\r\n    {\r\n        BOOST_CHECK_EQUAL(n, std::size_t(expected_point_count));\r\n    }\r\n\r\n    BOOST_CHECK_CLOSE(length, expected_length, 0.001);\r\n\r\n    std::string lp = \"lp_\";\r\n    difference_output(lp + caseid, g1, g2, pieces);\r\n}\r\n\r\n\r\n\r\n#endif\r\n", "meta": {"hexsha": "b91b4e55ffe8d26d68e6deee918a27366fa640c1", "size": 11977, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/test/algorithms/set_operations/difference/test_difference.hpp", "max_stars_repo_name": "fineshift/boost", "max_stars_repo_head_hexsha": "67469225b1d640f8d0cdcec25b099d212c6bfa41", "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/geometry/test/algorithms/set_operations/difference/test_difference.hpp", "max_issues_repo_name": "fineshift/boost", "max_issues_repo_head_hexsha": "67469225b1d640f8d0cdcec25b099d212c6bfa41", "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/geometry/test/algorithms/set_operations/difference/test_difference.hpp", "max_forks_repo_name": "fineshift/boost", "max_forks_repo_head_hexsha": "67469225b1d640f8d0cdcec25b099d212c6bfa41", "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.0255681818, "max_line_length": 149, "alphanum_fraction": 0.595057193, "num_tokens": 3084, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.63341027751814, "lm_q2_score": 0.7401743505760728, "lm_q1q2_score": 0.46883404081019936}}
{"text": "// Copyright Paul A. Bristow 2016, 2017, 2018.\n// Copyright John Maddock 2016.\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// test_lambert_w_integrals.cpp\n//! \\brief quadrature tests that cover the whole range of the Lambert W0 function.\n\n#include <boost/config.hpp>   // for BOOST_MSVC definition etc.\n#include <boost/version.hpp>   // for BOOST_MSVC versions.\n\n#ifdef BOOST_HAS_FLOAT128\n\n// Boost macros\n#define BOOST_TEST_MAIN\n#define BOOST_LIB_DIAGNOSTIC \"on\" // Report library file details.\n#include <boost/test/included/unit_test.hpp> // Boost.Test\n// #include <boost/test/unit_test.hpp> // Boost.Test\n#include <boost/test/floating_point_comparison.hpp>\n\n#include <boost/array.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/type_traits/is_constructible.hpp>\n\n#include <boost/multiprecision/float128.hpp>\n\n#include <boost/math/special_functions/fpclassify.hpp> // isnan, ifinite.\n#include <boost/math/special_functions/next.hpp> // float_next, float_prior\nusing boost::math::float_next;\nusing boost::math::float_prior;\n#include <boost/math/special_functions/ulp.hpp>  // ulp\n\n#include <boost/math/tools/test_value.hpp>  // for create_test_value and macro BOOST_MATH_TEST_VALUE.\n#include <boost/math/policies/policy.hpp>\nusing boost::math::policies::digits2;\nusing boost::math::policies::digits10;\n#include <boost/math/special_functions/lambert_w.hpp> // For Lambert W lambert_w function.\nusing boost::math::lambert_wm1;\nusing boost::math::lambert_w0;\n\n#include <limits>\n#include <cmath>\n#include <typeinfo>\n#include <iostream>\n#include <type_traits>\n#include <exception>\n\nstd::string show_versions(void);\n\n// Added code and test for Integral of the Lambert W function: by Nick Thompson.\n// https://en.wikipedia.org/wiki/Lambert_W_function#Definite_integrals\n\n#include <boost/math/constants/constants.hpp> // for integral tests.\n#include <boost/math/quadrature/tanh_sinh.hpp> // for integral tests.\n#include <boost/math/quadrature/exp_sinh.hpp> // for integral tests.\n\n  using boost::math::policies::policy;\n  using boost::math::policies::make_policy;\n\n// using statements needed for changing error handling policy.\nusing boost::math::policies::evaluation_error;\nusing boost::math::policies::domain_error;\nusing boost::math::policies::overflow_error;\nusing boost::math::policies::ignore_error;\nusing boost::math::policies::throw_on_error;\n\ntypedef policy<\n  domain_error<throw_on_error>,\n  overflow_error<ignore_error>\n> no_throw_policy;\n\n// Assumes that function has a throw policy, for example:\n//    NOT lambert_w0<T>(1 / (x * x), no_throw_policy());\n// Error in function boost::math::quadrature::exp_sinh<double>::integrate:\n// The exp_sinh quadrature evaluated your function at a singular point and resulted in inf.\n// Please ensure your function evaluates to a finite number of its entire domain.\ntemplate <typename T>\nT debug_integration_proc(T x)\n{\n   T result; // warning C4701: potentially uninitialized local variable 'result' used\n  // T result = 0 ; // But result may not be assigned below?\n  try\n  {\n   // Assign function call to result in here...\n    if (x <= sqrt(boost::math::tools::min_value<T>()) )\n    {\n      result = 0;\n    }\n    else\n    {\n      result = lambert_w0<T>(1 / (x * x));\n    }\n   // result = lambert_w0<T>(1 / (x * x), no_throw_policy());  // Bad idea, less helpful diagnostic message is:\n    // Error in function boost::math::quadrature::exp_sinh<double>::integrate:\n    // The exp_sinh quadrature evaluated your function at a singular point and resulted in inf.\n    // Please ensure your function evaluates to a finite number of its entire domain.\n\n  } // try\n  catch (const std::exception& e)\n  {\n    std::cout << \"Exception \" << e.what() << std::endl;\n    // set breakpoint here:\n    std::cout << \"Unexpected exception thrown in integration code at abscissa (x): \" << x << \".\" << std::endl;\n    if (!std::isfinite(result))\n    {\n      // set breakpoint here:\n      std::cout << \"Unexpected non-finite result in integration code at abscissa (x): \" << x << \".\" << std::endl;\n    }\n    if (std::isnan(result))\n    {\n      // set breakpoint here:\n      std::cout << \"Unexpected non-finite result in integration code at abscissa (x): \" << x << \".\" << std::endl;\n    }\n  } // catch\n  return result;\n} // T debug_integration_proc(T x)\n\ntemplate<class Real>\nvoid test_integrals()\n{\n  // Integral of the Lambert W function:\n  // https://en.wikipedia.org/wiki/Lambert_W_function\n  using boost::math::quadrature::tanh_sinh;\n  using boost::math::quadrature::exp_sinh;\n  // file:///I:/modular-boost/libs/math/doc/html/math_toolkit/quadrature/double_exponential/de_tanh_sinh.html\n  using std::sqrt;\n\n  std::cout << \"Integration of type \" << typeid(Real).name()  << std::endl;\n\n  Real tol = std::numeric_limits<Real>::epsilon();\n  { //  // Integrate for function lambert_W0(z);\n    tanh_sinh<Real> ts;\n    Real a = 0;\n    Real b = boost::math::constants::e<Real>();\n    auto f = [](Real z)->Real\n    {\n      return lambert_w0<Real>(z);\n    };\n    Real z = ts.integrate(f, a, b); // OK without any decltype(f)\n    BOOST_CHECK_CLOSE_FRACTION(z, boost::math::constants::e<Real>() - 1, tol);\n  }\n  {\n    // Integrate for function lambert_W0(z/(z sqrt(z)).\n    exp_sinh<Real> es;\n    auto f = [](Real z)->Real\n    {\n      return lambert_w0<Real>(z)/(z * sqrt(z));\n    };\n    Real z = es.integrate(f); // OK\n    BOOST_CHECK_CLOSE_FRACTION(z, 2 * boost::math::constants::root_two_pi<Real>(), tol);\n  }\n  {\n    // Integrate for function lambert_W0(1/z^2).\n    exp_sinh<Real> es;\n    //const Real sqrt_min = sqrt(boost::math::tools::min_value<Real>()); // 1.08420217e-19 fo 32-bit float.\n    // error C3493: 'sqrt_min' cannot be implicitly captured because no default capture mode has been specified\n    auto f = [](Real z)->Real\n    {\n      if (z <= sqrt(boost::math::tools::min_value<Real>()) )\n      { // Too small would underflow z * z and divide by zero to overflow 1/z^2 for lambert_w0 z parameter.\n        return static_cast<Real>(0);\n      }\n      else\n      {\n        return lambert_w0<Real>(1 / (z * z)); // warning C4756: overflow in constant arithmetic, even though cannot happen.\n      }\n    };\n    Real z = es.integrate(f);\n    BOOST_CHECK_CLOSE_FRACTION(z, boost::math::constants::root_two_pi<Real>(), tol);\n  }\n} // template<class Real> void test_integrals()\n\n\nBOOST_AUTO_TEST_CASE( integrals )\n{\n  std::cout << \"Macro BOOST_MATH_LAMBERT_W0_INTEGRALS is defined.\" << std::endl;\n  BOOST_TEST_MESSAGE(\"\\nTest Lambert W0 integrals.\");\n  try\n  {\n  // using statements needed to change precision policy.\n  using boost::math::policies::policy;\n  using boost::math::policies::make_policy;\n  using boost::math::policies::precision;\n  using boost::math::policies::digits2;\n  using boost::math::policies::digits10;\n\n  // using statements needed for changing error handling policy.\n  using boost::math::policies::evaluation_error;\n  using boost::math::policies::domain_error;\n  using boost::math::policies::overflow_error;\n  using boost::math::policies::ignore_error;\n  using boost::math::policies::throw_on_error;\n\n  typedef policy<\n    domain_error<throw_on_error>,\n    overflow_error<ignore_error>\n  > no_throw_policy;\n\n  /*\n  // Experiment with better diagnostics.\n  typedef float Real;\n\n  Real inf = std::numeric_limits<Real>::infinity();\n  Real max = (std::numeric_limits<Real>::max)();\n  std::cout.precision(std::numeric_limits<Real>::max_digits10);\n  //std::cout << \"lambert_w0(inf) = \" << lambert_w0(inf) << std::endl; // lambert_w0(inf) = 1.79769e+308\n  std::cout << \"lambert_w0(inf, throw_policy()) = \" << lambert_w0(inf, no_throw_policy()) << std::endl; // inf\n  std::cout << \"lambert_w0(max) = \" << lambert_w0(max) << std::endl; // lambert_w0(max) = 703.227\n  //std::cout << lambert_w0(inf) << std::endl; // inf - will throw.\n  std::cout << \"lambert_w0(0) = \" << lambert_w0(0.) << std::endl; // 0\n  std::cout << \"lambert_w0(std::numeric_limits<Real>::denorm_min()) = \" << lambert_w0(std::numeric_limits<Real>::denorm_min()) << std::endl; // 4.94066e-324\n  std::cout << \"lambert_w0(std::numeric_limits<Real>::min()) = \" << lambert_w0((std::numeric_limits<Real>::min)()) << std::endl; // 2.22507e-308\n\n  // Approximate the largest lambert_w you can get for type T?\n  float max_w_f = boost::math::lambert_w_detail::lambert_w0_approx((std::numeric_limits<float>::max)()); // Corless equation 4.19, page 349, and Chapeau-Blondeau equation 20, page 2162.\n  std::cout << \"w max_f \" << max_w_f << std::endl; // 84.2879\n  Real max_w = boost::math::lambert_w_detail::lambert_w0_approx((std::numeric_limits<Real>::max)()); // Corless equation 4.19, page 349, and Chapeau-Blondeau equation 20, page 2162.\n  std::cout << \"w max \" << max_w << std::endl; // 703.227\n\n  std::cout << \"lambert_w0(7.2416706213544837e-163) = \" << lambert_w0(7.2416706213544837e-163) << std::endl; //\n  std::cout << \"test integral 1/z^2\" << std::endl;\n  std::cout << \"ULP = \" << boost::math::ulp(1., policy<digits2<> >()) << std::endl; // ULP = 2.2204460492503131e-16\n  std::cout << \"ULP = \" << boost::math::ulp(1e-10, policy<digits2<> >()) << std::endl; // ULP = 2.2204460492503131e-16\n  std::cout << \"ULP = \" << boost::math::ulp(1., policy<digits2<11> >()) << std::endl; // ULP = 2.2204460492503131e-16\n  std::cout << \"epsilon =  \" << std::numeric_limits<Real>::epsilon() << std::endl; //\n  std::cout << \"sqrt(max) =  \" << sqrt(boost::math::tools::max_value<float>() ) << std::endl; // sqrt(max) =  1.8446742974197924e+19\n  std::cout << \"sqrt(min) =  \" << sqrt(boost::math::tools::min_value<float>() ) << std::endl; // sqrt(min) =  1.0842021724855044e-19\n\n\n\n// Demo debug version.\nReal tol = std::numeric_limits<Real>::epsilon();\nReal x;\n{\n  using boost::math::quadrature::exp_sinh;\n  exp_sinh<Real> es;\n  // Function to be integrated, lambert_w0(1/z^2).\n\n    //auto f = [](Real z)->Real\n    //{ // Naive - no protection against underflow and subsequent divide by zero.\n    //  return lambert_w0<Real>(1 / (z * z));\n    //};\n    // Diagnostic is:\n    // Error in function boost::math::lambert_w0<Real>: Expected a finite value but got inf\n\n    auto f = [](Real z)->Real\n    { // Debug with diagnostics for underflow and subsequent divide by zero and other bad things.\n      return debug_integration_proc(z);\n    };\n    // Exception Error in function boost::math::lambert_w0<double>: Expected a finite value but got inf.\n\n    // Unexpected exception thrown in integration code at abscissa: 7.2416706213544837e-163.\n    // Unexpected exception thrown in integration code at abscissa (x): 3.478765835953569e-23.\n    x = es.integrate(f);\n    std::cout << \"es.integrate(f) = \" << x << std::endl;\n    BOOST_CHECK_CLOSE_FRACTION(x, boost::math::constants::root_two_pi<Real>(), tol);\n    // root_two_pi<double = 2.506628274631000502\n  }\n    */\n\n  test_integrals<boost::multiprecision::float128>();\n  }\n  catch (std::exception& ex)\n  {\n    std::cout << ex.what() << std::endl;\n  }\n}\n\n#else\n\nint main() { return 0; }\n\n#endif\n", "meta": {"hexsha": "1010b138d0fa64d37792068664712cd15987e157", "size": 11074, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/libs/math/test/test_lambert_w_integrals_float128.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/math/test/test_lambert_w_integrals_float128.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/math/test/test_lambert_w_integrals_float128.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": 39.9783393502, "max_line_length": 185, "alphanum_fraction": 0.6801517067, "num_tokens": 3161, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743735019594, "lm_q2_score": 0.63341024983754, "lm_q1q2_score": 0.4688340348432207}}
{"text": "/*    Copyright (c) 2010-2018, Delft University of Technology\n *    All rigths reserved\n *\n *    This file is part of the Tudat. Redistribution and use in source and\n *    binary forms, with or without modification, are permitted exclusively\n *    under the terms of the Modified BSD license. You should have received\n *    a copy of the license with this file. If not, please or visit:\n *    http://tudat.tudelft.nl/LICENSE.\n */\n\n#include <boost/make_shared.hpp>\n#include <boost/bind.hpp>\n\n#include \"Tudat/Mathematics/Statistics/randomVariableGenerator.h\"\n#include \"Tudat/Mathematics/Statistics/boostProbabilityDistributions.h\"\n\nnamespace tudat\n{\n\nnamespace statistics\n{\n\n//! Function to create a random number generating function from a continuous univariate distribution implemented in boost\nstd::function< double( ) > createBoostContinuousRandomVariableGeneratorFunction(\n        const ContinuousBoostStatisticalDistributions boostDistribution,\n        const std::vector< double >& parameters,\n        const double seed )\n{\n    return std::bind( &RandomVariableGenerator< double >::getRandomVariableValue,\n                        createBoostContinuousRandomVariableGenerator( boostDistribution, parameters, seed ) );\n}\n\n//! Function to create a random number generator from a continuous univariate distribution implemented in boost\nstd::shared_ptr< RandomVariableGenerator< double > > createBoostContinuousRandomVariableGenerator(\n        const ContinuousBoostStatisticalDistributions boostDistribution,\n        const std::vector< double >& parameters,\n        const double seed )\n{\n    return std::make_shared< ContinuousRandomVariableGenerator >(\n                createBoostRandomVariable( boostDistribution, parameters ), seed );\n}\n\n}\n\n}\n\n", "meta": {"hexsha": "7941407d69648474362ed3c459a3b9e9afa44d52", "size": 1746, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Mathematics/Statistics/randomVariableGenerator.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/Mathematics/Statistics/randomVariableGenerator.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/Mathematics/Statistics/randomVariableGenerator.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": 37.1489361702, "max_line_length": 121, "alphanum_fraction": 0.7520045819, "num_tokens": 352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391617003942, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.4687036078703781}}
{"text": "//\n// Copyright (c) 2019-2020 INRIA\n//\n\n#include \"pinocchio/algorithm/jacobian.hpp\"\n#include \"pinocchio/algorithm/rnea.hpp\"\n#include \"pinocchio/algorithm/rnea-derivatives.hpp\"\n#include \"pinocchio/algorithm/kinematics-derivatives.hpp\"\n#include \"pinocchio/algorithm/contact-dynamics.hpp\"\n#include \"pinocchio/algorithm/joint-configuration.hpp\"\n#include \"pinocchio/parsers/sample-models.hpp\"\n\n#include <iostream>\n\n#include <boost/test/unit_test.hpp>\n#include <boost/utility/binary.hpp>\n\nBOOST_AUTO_TEST_SUITE ( BOOST_TEST_MODULE )\n\nusing namespace Eigen;\nusing namespace pinocchio;\n\nBOOST_AUTO_TEST_CASE ( test_FD_with_contact_cst_gamma )\n{\n  pinocchio::Model model;\n  pinocchio::buildModels::humanoidRandom(model,true);\n  pinocchio::Data data(model), data_check(model);\n  \n  VectorXd q = VectorXd::Ones(model.nq);\n  normalize(model,q);\n\n  computeJointJacobians(model, data, q);\n  \n  VectorXd v = VectorXd::Ones(model.nv);\n  VectorXd tau = VectorXd::Random(model.nv);\n  \n  const std::string RF = \"rleg6_joint\";\n  const Model::JointIndex RF_id = model.getJointId(RF);\n//  const std::string LF = \"lleg6_joint\";\n//  const Model::JointIndex LF_id = model.getJointId(LF);\n  \n  Data::Matrix6x J_RF(6,model.nv); J_RF.setZero();\n  getJointJacobian(model, data, RF_id, LOCAL, J_RF);\n  Motion::Vector6 gamma_RF; gamma_RF.setZero();\n  forwardKinematics(model,data,q,v,VectorXd::Zero(model.nv));\n  gamma_RF += data.a[RF_id].toVector(); // Jdot * qdot\n  \n  forwardDynamics(model, data, q, v, tau, J_RF, gamma_RF);\n  VectorXd ddq_ref = data.ddq;\n  Force::Vector6 contact_force_ref = data.lambda_c;\n  \n  PINOCCHIO_ALIGNED_STD_VECTOR(Force) fext((size_t)model.njoints,Force::Zero());\n  fext[RF_id] = ForceRef<Force::Vector6>(contact_force_ref);\n  \n  // check call to RNEA\n  rnea(model,data_check,q,v,ddq_ref,fext);\n  \n  BOOST_CHECK(data_check.tau.isApprox(tau));\n  forwardKinematics(model,data_check,q,VectorXd::Zero(model.nv),ddq_ref);\n  BOOST_CHECK(data_check.a[RF_id].toVector().isApprox(-gamma_RF));\n  \n  Data data_fd(model);\n  VectorXd q_plus(model.nq);\n  VectorXd v_eps(model.nv); v_eps.setZero();\n  VectorXd v_plus(v);\n  VectorXd tau_plus(tau);\n  const double eps = 1e-8;\n  \n  // check: dddq_dtau and dlambda_dtau\n  MatrixXd dddq_dtau(model.nv,model.nv);\n  Data::Matrix6x dlambda_dtau(6,model.nv);\n  \n  for(int k = 0; k < model.nv; ++k)\n  {\n    tau_plus[k] += eps;\n    forwardDynamics(model, data_fd, q, v, tau_plus, J_RF, gamma_RF);\n    \n    const Data::TangentVectorType & ddq_plus = data_fd.ddq;\n    Force::Vector6 contact_force_plus = data_fd.lambda_c;\n    \n    dddq_dtau.col(k) = (ddq_plus - ddq_ref)/eps;\n    dlambda_dtau.col(k) = (contact_force_plus - contact_force_ref)/eps;\n    \n    tau_plus[k] -= eps;\n  }\n    \n  MatrixXd A(model.nv+6,model.nv+6);\n  data.M.transpose().triangularView<Eigen::Upper>() = data.M.triangularView<Eigen::Upper>();\n  A.topLeftCorner(model.nv,model.nv) = data.M;\n  A.bottomLeftCorner(6, model.nv) = J_RF;\n  A.topRightCorner(model.nv, 6) = J_RF.transpose();\n  A.bottomRightCorner(6,6).setZero();\n  \n  MatrixXd Ainv = A.inverse();\n  BOOST_CHECK(Ainv.topRows(model.nv).leftCols(model.nv).isApprox(dddq_dtau,std::sqrt(eps)));\n  BOOST_CHECK(Ainv.bottomRows(6).leftCols(model.nv).isApprox(-dlambda_dtau,std::sqrt(eps)));\n  \n  // check: dddq_dv and dlambda_dv\n  MatrixXd dddq_dv(model.nv,model.nv);\n  Data::Matrix6x dlambda_dv(6,model.nv);\n  \n  for(int k = 0; k < model.nv; ++k)\n  {\n    v_plus[k] += eps;\n    forwardDynamics(model, data_fd, q, v_plus, tau, J_RF, gamma_RF);\n    \n    const Data::TangentVectorType & ddq_plus = data_fd.ddq;\n    Force::Vector6 contact_force_plus = data_fd.lambda_c;\n    \n    dddq_dv.col(k) = (ddq_plus - ddq_ref)/eps;\n    dlambda_dv.col(k) = (contact_force_plus - contact_force_ref)/eps;\n    \n    v_plus[k] -= eps;\n  }\n  \n  computeRNEADerivatives(model,data_check,q,v,VectorXd::Zero(model.nv));\n  MatrixXd dddq_dv_anal = -Ainv.topRows(model.nv).leftCols(model.nv) * data_check.dtau_dv;\n  MatrixXd dlambda_dv_anal = -Ainv.bottomRows(6).leftCols(model.nv) * data_check.dtau_dv;\n  \n  BOOST_CHECK(dddq_dv_anal.isApprox(dddq_dv,std::sqrt(eps)));\n  BOOST_CHECK(dlambda_dv_anal.isApprox(-dlambda_dv,std::sqrt(eps)));\n  \n  MatrixXd dddq_dq(model.nv,model.nv);\n  Data::Matrix6x dlambda_dq(6,model.nv);\n\n  for(int k = 0; k < model.nv; ++k)\n  {\n    v_eps[k] = eps;\n    q_plus = integrate(model,q,v_eps);\n    computeJointJacobians(model, data_fd, q_plus);\n    getJointJacobian(model, data_fd, RF_id, LOCAL, J_RF);\n    forwardDynamics(model, data_fd, q_plus, v, tau, J_RF, gamma_RF);\n    \n    const Data::TangentVectorType & ddq_plus = data_fd.ddq;\n    Force::Vector6 contact_force_plus = data_fd.lambda_c;\n    \n    dddq_dq.col(k) = (ddq_plus - ddq_ref)/eps;\n    dlambda_dq.col(k) = (contact_force_plus - contact_force_ref)/eps;\n    \n    v_eps[k] = 0.;\n  }\n  \n  computeRNEADerivatives(model,data_check,q,v,ddq_ref,fext);\n  Data::Matrix6x v_partial_dq(6,model.nv), a_partial_dq(6,model.nv), a_partial_dv(6,model.nv), a_partial_da(6,model.nv);\n  v_partial_dq.setZero(); a_partial_dq.setZero(); a_partial_dv.setZero(); a_partial_da.setZero();\n  Data data_kin(model);\n  computeForwardKinematicsDerivatives(model,data_kin,q,VectorXd::Zero(model.nv),ddq_ref);\n  getJointAccelerationDerivatives(model,data_kin,RF_id,LOCAL,v_partial_dq,a_partial_dq,a_partial_dv,a_partial_da);\n  \n  MatrixXd dddq_dq_anal = -Ainv.topRows(model.nv).leftCols(model.nv) * data_check.dtau_dq;\n  dddq_dq_anal -= Ainv.topRows(model.nv).rightCols(6) * a_partial_dq;\n  \n  MatrixXd dlambda_dq_anal = Ainv.bottomRows(6).leftCols(model.nv) * data_check.dtau_dq;\n  dlambda_dq_anal += Ainv.bottomRows(6).rightCols(6) * a_partial_dq;\n  \n  BOOST_CHECK(dddq_dq_anal.isApprox(dddq_dq,std::sqrt(eps)));\n  BOOST_CHECK(dlambda_dq_anal.isApprox(dlambda_dq,std::sqrt(eps)));\n  \n}\n\ntemplate<typename ConfigVectorType, typename TangentVectorType1, typename TangentVectorType2>\nVectorXd contactDynamics(const Model & model, Data & data,\n                         const Eigen::MatrixBase<ConfigVectorType> & q,\n                         const Eigen::MatrixBase<TangentVectorType1> & v,\n                         const Eigen::MatrixBase<TangentVectorType2> & tau,\n                         const Model::JointIndex id)\n{\n  computeJointJacobians(model, data, q);\n  Data::Matrix6x J(6,model.nv); J.setZero();\n  \n  getJointJacobian(model, data, id, LOCAL, J);\n  Motion::Vector6 gamma;\n  forwardKinematics(model, data, q, v, VectorXd::Zero(model.nv));\n  gamma = data.a[id].toVector();\n  \n  forwardDynamics(model, data, q, v, tau, J, gamma);\n  VectorXd res(VectorXd::Zero(model.nv+6));\n  \n  res.head(model.nv) = data.ddq;\n  res.tail(6) = data.lambda_c;\n  \n  return res;\n}\n\nBOOST_AUTO_TEST_CASE ( test_FD_with_contact_varying_gamma )\n{\n  pinocchio::Model model;\n  pinocchio::buildModels::humanoidRandom(model,true);\n  pinocchio::Data data(model), data_check(model);\n  \n  VectorXd q = VectorXd::Ones(model.nq);\n  normalize(model,q);\n  \n  VectorXd v = VectorXd::Random(model.nv);\n  VectorXd tau = VectorXd::Random(model.nv);\n  \n  const std::string RF = \"rleg6_joint\";\n  const Model::JointIndex RF_id = model.getJointId(RF);\n  \n  Data::Matrix6x J_RF(6,model.nv); J_RF.setZero();\n  computeJointJacobians(model, data, q);\n  getJointJacobian(model, data, RF_id, LOCAL, J_RF);\n  Motion::Vector6 gamma_RF; gamma_RF.setZero();\n  \n  VectorXd x_ref = contactDynamics(model,data,q,v,tau,RF_id);\n  VectorXd ddq_ref = x_ref.head(model.nv);\n  Force::Vector6 contact_force_ref = x_ref.tail(6);\n  \n  PINOCCHIO_ALIGNED_STD_VECTOR(Force) fext((size_t)model.njoints,Force::Zero());\n  fext[RF_id] = ForceRef<Force::Vector6>(contact_force_ref);\n  \n  // check call to RNEA\n  rnea(model,data_check,q,v,ddq_ref,fext);\n  \n  BOOST_CHECK(data_check.tau.isApprox(tau));\n  forwardKinematics(model,data_check,q,v,ddq_ref);\n  BOOST_CHECK(data_check.a[RF_id].toVector().isZero());\n  \n  Data data_fd(model);\n  VectorXd q_plus(model.nq);\n  VectorXd v_eps(model.nv); v_eps.setZero();\n  VectorXd v_plus(v);\n  VectorXd tau_plus(tau);\n  VectorXd x_plus(model.nv + 6);\n  const double eps = 1e-8;\n\n  // check: dddq_dtau and dlambda_dtau\n  MatrixXd dddq_dtau(model.nv,model.nv);\n  Data::Matrix6x dlambda_dtau(6,model.nv);\n\n  for(int k = 0; k < model.nv; ++k)\n  {\n    tau_plus[k] += eps;\n    x_plus = contactDynamics(model,data,q,v,tau_plus,RF_id);\n\n    const Data::TangentVectorType ddq_plus = x_plus.head(model.nv);\n    Force::Vector6 contact_force_plus = x_plus.tail(6);\n\n    dddq_dtau.col(k) = (ddq_plus - ddq_ref)/eps;\n    dlambda_dtau.col(k) = (contact_force_plus - contact_force_ref)/eps;\n\n    tau_plus[k] -= eps;\n  }\n\n  MatrixXd A(model.nv+6,model.nv+6);\n  data.M.transpose().triangularView<Eigen::Upper>() = data.M.triangularView<Eigen::Upper>();\n  A.topLeftCorner(model.nv,model.nv) = data.M;\n  A.bottomLeftCorner(6, model.nv) = J_RF;\n  A.topRightCorner(model.nv, 6) = J_RF.transpose();\n  A.bottomRightCorner(6,6).setZero();\n\n  MatrixXd Ainv = A.inverse();\n  BOOST_CHECK(Ainv.topRows(model.nv).leftCols(model.nv).isApprox(dddq_dtau,std::sqrt(eps)));\n  BOOST_CHECK(Ainv.bottomRows(6).leftCols(model.nv).isApprox(-dlambda_dtau,std::sqrt(eps)));\n\n  // check: dddq_dv and dlambda_dv\n  MatrixXd dddq_dv(model.nv,model.nv);\n  Data::Matrix6x dlambda_dv(6,model.nv);\n\n  for(int k = 0; k < model.nv; ++k)\n  {\n    v_plus[k] += eps;\n    x_plus = contactDynamics(model,data,q,v_plus,tau,RF_id);\n\n    const Data::TangentVectorType ddq_plus = x_plus.head(model.nv);\n    Force::Vector6 contact_force_plus = x_plus.tail(6);\n\n    dddq_dv.col(k) = (ddq_plus - ddq_ref)/eps;\n    dlambda_dv.col(k) = (contact_force_plus - contact_force_ref)/eps;\n\n    v_plus[k] -= eps;\n  }\n  \n  \n  computeRNEADerivatives(model,data_check,q,v,VectorXd::Zero(model.nv));\n  Data::Matrix6x v_partial_dq(6,model.nv), a_partial_dq(6,model.nv), a_partial_dv(6,model.nv), a_partial_da(6,model.nv);\n  v_partial_dq.setZero(); a_partial_dq.setZero(); a_partial_dv.setZero(); a_partial_da.setZero();\n  Data data_kin(model);\n  computeForwardKinematicsDerivatives(model,data_kin,q,v,VectorXd::Zero(model.nv));\n  getJointAccelerationDerivatives(model,data_kin,RF_id,LOCAL,v_partial_dq,a_partial_dq,a_partial_dv,a_partial_da);\n  \n  MatrixXd dddq_dv_anal = -Ainv.topRows(model.nv).leftCols(model.nv) * data_check.dtau_dv;\n  dddq_dv_anal -= Ainv.topRows(model.nv).rightCols(6) * a_partial_dv;\n  MatrixXd dlambda_dv_anal = -Ainv.bottomRows(6).leftCols(model.nv) * data_check.dtau_dv;\n  dlambda_dv_anal -= Ainv.bottomRows(6).rightCols(6) * a_partial_dv;\n  \n  BOOST_CHECK(dddq_dv_anal.isApprox(dddq_dv,std::sqrt(eps)));\n  BOOST_CHECK(dlambda_dv_anal.isApprox(-dlambda_dv,std::sqrt(eps)));\n  \n\n  MatrixXd dddq_dq(model.nv,model.nv);\n  Data::Matrix6x dlambda_dq(6,model.nv);\n\n  for(int k = 0; k < model.nv; ++k)\n  {\n    v_eps[k] = eps;\n    q_plus = integrate(model,q,v_eps);\n    \n    x_plus = contactDynamics(model,data,q_plus,v,tau,RF_id);\n    \n    const Data::TangentVectorType ddq_plus = x_plus.head(model.nv);\n    Force::Vector6 contact_force_plus = x_plus.tail(6);\n\n    dddq_dq.col(k) = (ddq_plus - ddq_ref)/eps;\n    dlambda_dq.col(k) = (contact_force_plus - contact_force_ref)/eps;\n\n    v_eps[k] = 0.;\n  }\n\n  computeRNEADerivatives(model,data_check,q,v,ddq_ref,fext);\n  v_partial_dq.setZero(); a_partial_dq.setZero(); a_partial_dv.setZero(); a_partial_da.setZero();\n  computeForwardKinematicsDerivatives(model,data_kin,q,v,ddq_ref);\n  getJointAccelerationDerivatives(model,data_kin,RF_id,LOCAL,v_partial_dq,a_partial_dq,a_partial_dv,a_partial_da);\n\n  MatrixXd dddq_dq_anal = -Ainv.topRows(model.nv).leftCols(model.nv) * data_check.dtau_dq;\n  dddq_dq_anal -= Ainv.topRows(model.nv).rightCols(6) * a_partial_dq;\n\n  BOOST_CHECK(dddq_dq_anal.isApprox(dddq_dq,std::sqrt(eps)));\n  \n  MatrixXd dlambda_dq_anal = Ainv.bottomRows(6).leftCols(model.nv) * data_check.dtau_dq;\n  dlambda_dq_anal += Ainv.bottomRows(6).rightCols(6) * a_partial_dq;\n  \n  BOOST_CHECK(dlambda_dq_anal.isApprox(dlambda_dq,std::sqrt(eps)));\n  \n}\n\nBOOST_AUTO_TEST_SUITE_END ()\n\n", "meta": {"hexsha": "03853b0240f4f4f43c0e70fe95b307ab94b64c1b", "size": 11923, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittest/contact-dynamics-derivatives.cpp", "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": "unittest/contact-dynamics-derivatives.cpp", "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": "unittest/contact-dynamics-derivatives.cpp", "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": 36.2401215805, "max_line_length": 120, "alphanum_fraction": 0.7161788141, "num_tokens": 3773, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.46855441264143993}}
{"text": "#include <boost/math/distributions/pareto.hpp>\n", "meta": {"hexsha": "241d81ef6899d4ed3afea2188fe1fd376c4802b1", "size": 47, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_distributions_pareto.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_distributions_pareto.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_distributions_pareto.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 23.5, "max_line_length": 46, "alphanum_fraction": 0.8085106383, "num_tokens": 11, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.46855441264143993}}
{"text": "#pragma once\n\n#include <array>\n#include <Eigen/Dense>\n#include <CGAL/Exact_predicates_exact_constructions_kernel.h>\n#include <CGAL/Boolean_set_operations_2.h>\n#include <CGAL/Polygon_2.h>\n#include <CGAL/Polygon_with_holes_2.h>\n#include <CGAL/Aff_transformation_2.h>\n\n#include <object_model_msgs/msg/object_model.hpp>\n\nusing state_t = std::array<float, object_model_msgs::msg::Track::STATE_SIZE>;\nusing state_squared_t = std::array<float, object_model_msgs::msg::Track::STATE_SIZE*object_model_msgs::msg::Track::STATE_SIZE>;\n\nusing state_vector_t = Eigen::Matrix<float, object_model_msgs::msg::Track::STATE_SIZE, 1>;\nusing state_covariance_matrix_t = Eigen::Matrix<float, object_model_msgs::msg::Track::STATE_SIZE, object_model_msgs::msg::Track::STATE_SIZE>;\nusing measurement_noise_matrix_t = Eigen::Matrix<float, object_model_msgs::msg::Track::STATE_SIZE, object_model_msgs::msg::Track::STATE_SIZE>;\nusing process_noise_matrix_t = Eigen::Matrix<float, object_model_msgs::msg::Track::STATE_SIZE, object_model_msgs::msg::Track::STATE_SIZE>;\n\nusing capable_vector_t = std::array<bool, object_model_msgs::msg::Track::STATE_SIZE>;\n\n// EKF - Temporal Alignment\nconstexpr int ctra_size_t = 6;\nusing ctra_vector_t = Eigen::Matrix<float, ctra_size_t, 1>;\nusing ctra_matrix_t = Eigen::Matrix<float, ctra_size_t, ctra_size_t>;\nusing ctra_array_t = std::array<float, 6>;\nusing ctra_squared_t = std::array<float, ctra_size_t*ctra_size_t>;\n\n// CGAL\nusing Kernel = CGAL::Exact_predicates_exact_constructions_kernel;\nusing Polygon = CGAL::Polygon_2<Kernel>;\nusing Point = CGAL::Point_2<Kernel>;\nusing PolygonWithHoles = CGAL::Polygon_with_holes_2<Kernel>;\nusing Transformation = CGAL::Aff_transformation_2<Kernel>;\n", "meta": {"hexsha": "10e2e5175993c724e87b46811164710a8852f7e9", "size": 1699, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "fusion_layer/include/types.hpp", "max_stars_repo_name": "icaropires/objectlevel_fusion", "max_stars_repo_head_hexsha": "ef76835ac5f0475eee8098e66c7a1baa9f4d1f96", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-05-26T18:04:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T14:07:09.000Z", "max_issues_repo_path": "fusion_layer/include/types.hpp", "max_issues_repo_name": "icaropires/objectlevel_fusion", "max_issues_repo_head_hexsha": "ef76835ac5f0475eee8098e66c7a1baa9f4d1f96", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fusion_layer/include/types.hpp", "max_forks_repo_name": "icaropires/objectlevel_fusion", "max_forks_repo_head_hexsha": "ef76835ac5f0475eee8098e66c7a1baa9f4d1f96", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-23T14:05:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T14:05:28.000Z", "avg_line_length": 47.1944444444, "max_line_length": 142, "alphanum_fraction": 0.7981165391, "num_tokens": 448, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.46855441264143993}}
{"text": "//\n//  lung_model_discrete_branching.hpp\n//  \n//\n//  Created by Carl Whitfield on 09/03/2017.\n//\n//\n// Checked and commented 16/05/2018\n#if defined(_WIN32) || defined(_WIN64)\n#define _USE_MATH_DEFINES\n#include <windows.h>\n#endif\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <iostream>\n#include <algorithm>\n#include <unordered_map>\n#include <string.h>\n#include <math.h>\n#include <iomanip>\n#include <fstream>\n#include <sstream>\n#include <vector>\n#include <chrono>\n#include <ctime>\n#include <Eigen/Eigen/Dense>\n#include <Eigen/Eigen/LU>\n#include <Eigen/Eigen/Sparse>\n#include <Eigen/Eigen/SparseLU>\n#include <Eigen/Eigen/IterativeLinearSolvers>\n\n//Options for tree config\n#define LINEARPERT 1       //option TREE l\n#define NOPERT 2    //option TREE n\n\n//options for BCs\n#define BAG 101            //option BC b\n#define NOFLUX 102         //option BC n\n#define SINK 103\n\n//options for Defects\n#define BLOCKAGE 201\n#define AREA 202\n#define LENGTH 203\n#define ELASTICITY 204\n#define BAG_RESISTANCE 205\n\n//options for upwind scheme\n#define CENTRAL_UPWIND 301\n#define FIRST_ORDER_UPWIND 302      //First order upwind interpolation\n\n//options for flow type\n#define POISEUILLE 401   //--Poiseuille Flow Assumption--//\n#define PEDLEY 402       //--See Pedley 1970--//\n\n//option for elastic response function\n#define LINEAR_RESP 501\n#define NONLINEAR_RESP 502\n\n//options for pressure profile\n#define STEP_FUNCTION 601\n#define SIGMOIDAL 602\n#define SINUSOIDAL 603\n#define LINEAR 604\n\n//options for parameters to use\n#define GEOMETRIC    701\n#define HOMOGENISED  702\n#define WEIBEL  703\n#define LOBE_GEOMETRIC 704\n#define ALT_LOBE_GEOMETRIC 705\n\n//options for linear solve\n#define ITERATIVE    801\n#define DIRECT       802\n\n//options for initialisation\n#define EMPTY 901\n#define FULL 902      \n\n//options for perturbations\n#define PERT_AREA 1001\n#define PERT_LENGTH 1002\n#define PERT_ELASTICITY 1003\n\n//options for volume/pressure input\n#define VOLUME 1101\n#define PRESSURE 1102\n\n//options for dispersion\n#define TAYLOR 1201\n#define SCHERER 1202\n#define NONE 1203\n\n//Options for concentration file printout\n#define VTK 1301\n#define CSV 1302\n#define VTK_CSV 1303\n\n//Options for leak types\n#define INSPIRATORY_LEAK 1401\n#define EXPIRATORY_LEAK 1402\n#define INSPIRATORY_AND_EXPIRATORY_LEAK 1403\n\n/********************************************/\n//Unit conversions\n#define cmH20_Pa 100    //pressure conv from cm^2H20 to Pa\n#define L_m3 0.001      //volume from litres to m^3\n#define cm_m 0.01       //cm to metres\n#define PEDLEY_C 1.85   //pedley constant\n\n//Default values of parameters\n#define NGENTOT 23              //Number of generations total\n#define NGENDEF 15              //Number of generations before model terminates\n#define VISCDEF 1.93E-07            //Air Viscosity (cmH20 s) (actual, 1.93E-07 at 37C) -- engineering toolbox\n#define DENSITYDEF 1.138        //Air Density (kg m^-3) 1.138 at 37C -- engineering toolbox\n#define EDEF 5.0              //Elastance (cmH20 L^-1)\n#define RBDEF 0.2              //bag resistance\n#define RMDEF 0.6              //mouth resistance\n#define DIFFUSIONDEF 0.105       //Diffusion constant (cm2/s) (Helium is approx 0.71, Oxygen 0.19)\n#define MAXPECDEF 10            //Max element peclet number\n#define K0DEF 0                 //Uptake term\n#define LDDEF 3.0                //Length to diameter ratio\n#define LD2DEF 2.3                //Length to diameter ratio\n#define VFRCDEF 3.0            //Functional residual capacity in L\n#define VDDEF 0.12             //Conducting airway dead space\n#define VDMDEF 0.05            //Volume of mouth cavity\n#define VDUCTDEF 0.20            //fraction of acinus consisting of duct at FRC\n#define TINDEF 2.5              //Duration of first breath in (secs)\n#define P0DEF 1.0           //Max pressure applied at distal end (cmH20)\n#define VTDEF 1.0\n#define RUNDEF 40               //Total Simulation Time (number of breathing cycles)\n#define LAMBDADEF 0.794          //Geometric parameter\n#define LAMBDA2DEF 0.92         //Geom parameter acinus\n#define STDEF 0               //Time source is left at opening (in number of breaths)\n#define DEFPERTSIZE 0.1       //perturbation size\n#define DEFPRINTERVAL 10       //time between prints (in terms of length of first breath)\n#define DEFMINGENSIZE 1          //minimum number of points in a generation\n#define MINGENSIZE_ACIN 4\n#define DEFSTARTDELAY 10         //number of breaths to simulate before starting transport simulation\n#define DFACTOR 0.2   //increase in eff area in acinus (default)\n\n//Tolerances precisions etc.\n#define PTOL 1E-12  //precision for stree calc\n#define TOL 1E-12   //precision for ltree calc\n#define OUTPUT_PRECISION_CONC 12   //precision for conc file output\n#define OUTPUT_PRECISION_FLUX 12   //precision for flux file output\n#define DEF_TS 0.01               //defined timestep\n#define DEF_DX 0.025               //defined max spacestep\n\n//define stree numbers for lobar models -- trachea is 0\n#define BR 1    //right branch\n#define BL 2    //left branch\n#define BRML 3   //right middle/lower\n#define BRU 4    //right upper\n#define BLL 5    //left lower\n#define BLU 6    //left upper\n#define BRM 7    //right middle\n#define BRL 8    //right lower\n#define BRL1 9   //right lower major\n#define BRL2 10  //right lower minor\n#define BLL1 11  //left lower major\n#define BLL2 12  //left lower minor\n\nusing namespace std;\n\nclass Defect    //class for storing ariway/acinar defect information \n{\npublic:\n\tunsigned jn;   //generation number\n\tunsigned long kstart, kend;   //branch number start and end\n\tunsigned type;       //defect type\n\tdouble mag;      //magnitude of defect\n\tDefect()\n\t{\n\t\tjn = 0;\n\t\tkstart = 0;\n\t\tkend = 0;\n\t\ttype = 0;   //should return error if unchanged\n\t\tmag = 0;\n\t}\n\tinline bool operator==(Defect d)   //equality operator\n\t{\n\t\tif (type == BLOCKAGE) return(type == d.type);  //defects are equal if both blocked\n\t\telse return (type == d.type && ((int)(1000000 * mag)) == ((int)(1000000 * d.mag)));  //defects equal if same type and magnitude\n\t}\n};\n\nclass Leak    //class for storing leak details - for simulating inspiratory and expiratory leaks at mouth\n{\npublic:\n\tbool exists;\n\tdouble start, end, size;    //start time (breaths), end time (breaths), size (fraction)\n\tunsigned type;             //Insp only, exp only or both\n\tLeak()\n\t{\n\t\texists = false;\n\t\tstart = 0;\n\t\tend = 100000;\n\t\tsize = 0;\n\t\ttype = INSPIRATORY_AND_EXPIRATORY_LEAK;\n\t}\n};\n\nclass Conversions    //class for storing unit conversions\n{\npublic:\n\tdouble LL_to_cm;    //lung length (sim units) to cm\n\tdouble P_to_cmH20;   //pressure (sim units) to cmH20\n\tdouble t_to_s;      //time (sim units) to seconds\n\tdouble V_to_Litres;    //volume (sim units) to litres\n};\n\nclass Options    //for storing input options\n{\npublic:\n\t/***Determined by input file***/\n\n\t/**Overarching options**/\n\tunsigned TreeOp;         //Tree format\n\tunsigned BcOp;           //Boundary condition\n\tunsigned UpwindOp;       //Upwind interpolation scheme\n\tunsigned PressOp;        //Function for pressure profile\n\tunsigned RespFunc;       //Function for elastic resistance\n\tunsigned FlowType;       //Poiseuille or turbulent\n\tunsigned ShapeOp;        //Determines the shape and size of the tubes\n\tunsigned SolverOp;\n\tunsigned InitOp;        //Determines c initialisation (empty c=0, full c=1)\n\tunsigned InputOp;         //Determines whether volume or pressure is inputted\n\tunsigned TaylorDisp;    //True if Taylor Dispersion is considered\n\tunsigned OutputOp;   //output format option\n\tbool output_perts;  //whether to output pert files or not\n\tbool output_lung_volumes;\n\tLeak N2leak;\n\n\t/**Parameters**/\n\tunsigned Ngen;           //Number of generations before alveoli\n\tunsigned Ngen2;          //Total number of generations in tree\n\tunsigned MinGenSize, MinAcinGenSize;\n\tdouble dt, dxmax;                //timestep\n\tdouble Viscosity;        //Air viscosity\n\tdouble Density;          //Air density\n\tdouble Diffusion;      //Diffusion constant\n\tdouble k0;          //bare uptake rate\n\tdouble LDratio, LDratio2;          //L0 length of trachea\n\tdouble VFRC;        //total lung resting volume\n\tdouble Tin;         //period first inhalation\n\tdouble P0;          //Pressure on first inhalation (always negative)\n\tdouble VT, VD, VDM, Vductvol;          //Tidal volume\n\tdouble E, Rb, Rmouth, V0;           //Elastance of bag, (Total) Resistance of bag, volume of bag\n\tdouble RunTime;     //Total run time of simulation in breaths\n\tdouble PrerunTime;\n\tdouble lambda, lambda2;      //Geometric ratio of tree generations\n\tdouble StimTime;    //Time stimulation kept at inlet\n\tdouble printerval;  //Time between data outputs\n\tdouble MaxPeclet;   //Maximum element peclet number allowed\n\tdouble AcinAreaFactor;\n\tvector<vector<Defect>> def;     //Vector of large magnitude perturbations to symmetric tree\n\t//vector<Defect> pert;      //Vector of small magnitude perturbations to consider individually\n\t//vector<vector<char>> *tree_pert;\n\tunordered_map<unsigned long, vector<Defect>> def_map;   //map from position in tree to defects at that location\n\tunsigned long kmtot;   //total number of finite volumes\n\n\t/***Determined in code***/\n\tchrono::time_point<std::chrono::system_clock> tstart, tend;\n\tunsigned Ntrees;               //Number of subtrees - identifier for this run\n\tstring SimID;\n\tdouble Peclet;        //Peclet number for branch 0\n\t/***Constructor - Default Values***/\n\tOptions()\n\t{\n\t\tTreeOp = NOPERT;\n\t\tBcOp = NOFLUX;\n\t\tUpwindOp = FIRST_ORDER_UPWIND;\n\t\tPressOp = SINUSOIDAL;\n\t\tRespFunc = LINEAR_RESP;\n\t\tFlowType = POISEUILLE;\n\t\tShapeOp = GEOMETRIC;\n\t\tSolverOp = ITERATIVE;\n\t\tInitOp = FULL;\n\t\tInputOp = VOLUME;\n\t\tTaylorDisp = SCHERER;\n\t\toutput_perts = true;\n\t\toutput_lung_volumes = true;\n\t\tOutputOp = CSV;\n\t\tNgen = NGENDEF;\n\t\tNgen2 = NGENTOT;\n\t\tMinGenSize = DEFMINGENSIZE;\n\t\tMinAcinGenSize = MINGENSIZE_ACIN;\n\t\tViscosity = VISCDEF;\n\t\tDensity = DENSITYDEF;\n\t\tE = EDEF;\n\t\tRb = RBDEF;\n\t\tRmouth = RMDEF;\n\t\tDiffusion = DIFFUSIONDEF;\n\t\tMaxPeclet = MAXPECDEF;\n\t\tk0 = K0DEF;\n\t\tLDratio = LDDEF;\n\t\tLDratio2 = LD2DEF;\n\t\tVFRC = VFRCDEF;\n\t\tVD = VDDEF;\n\t\tVDM = VDMDEF;\n\t\tVductvol = VDUCTDEF;\n\t\tTin = TINDEF;\n\t\tP0 = P0DEF;\n\t\tVT = VTDEF;\n\t\tRunTime = RUNDEF;\n\t\tPrerunTime = DEFSTARTDELAY;\n\t\tlambda = LAMBDADEF;\n\t\tlambda2 = LAMBDA2DEF;\n\t\tStimTime = STDEF;\n\t\tprinterval = DEFPRINTERVAL;\n\t\tdt = DEF_TS;\n\t\tdxmax = DEF_DX;\n\t\tAcinAreaFactor = DFACTOR;\n\t\tdef.resize(13);\n\t}\n\t//functions to return text for options\n\tstring read_tree_option();\n\tstring read_bc_option();\n\tstring read_flow_option();\n\tstring read_resp_option();\n\tstring read_pressure_option();\n\tstring read_shape_option();\n\tstring read_upwind_option();\n\tstring read_perttype();\n\tstring read_taylor_option();\n\tstring read_solver_option();\n\tstring read_init_option();\n\tstring read_input_option();\n\tstring read_output_option();\n\tstring read_leak_type();\n};\n\nstruct node     //stores info at a single finite volume node\n{\n\tdouble c, cold, Aold, Anew, DA, x, uc, y0;        //values of conc, previous conc, totarea, position, vel at element centre\n\tdouble ul, ur, al, ar, Dl, Dr;                             //velocity, diffusion and area on left and right of element\n\tunsigned long km;                                       //corresponding entrance in matrix\n\tvector<unsigned> iup[3], jup[3], kup[3];        //stores indices for neighbours n-1, n and n+1 respectively\n\tvector<double> dxup[3], dcfr[3], dcfl[3], ucfrpos[3], ucflpos[3], ucfrneg[3], ucflneg[3], sr, sul;   //vector of dx at n-1, n  and n+1 and cross-sections\n\tdouble sl, sdr;   //cross section left sl and right (for node to left) sdr \n\tnode()   //constructor\n\t{\n\t\tc = 0;\n\t\tcold = 0;\n\t\tAold = 0;\n\t\tAnew = 0;\n\t\tDA = 0;\n\t\tx = 0;\n\t\tuc = 0;\n\t\tul = 0;\n\t\tur = 0;\n\t\tal = 0;\n\t\tar = 0;\n\t\tDl = 0;\n\t\tDr = 0;\n\t\tkm = 0;\n\t\tsl = 0;\n\t\tsdr = 0;\n\t}\n\tvoid set_quantities_zero()   //rest relevant quantities to zeros\n\t{\n\t\tc = 0;\n\t\tcold = 0;\n\t\tAold = 0;\n\t\tAnew = 0;\n\t\tDA = 0;\n\t\tx = 0;\n\t\tuc = 0;\n\t\tul = 0;\n\t\tur = 0;\n\t\tal = 0;\n\t\tar = 0;\n\t\tDl = 0;\n\t\tDr = 0;\n\t\tsl = 0;\n\t\tsdr = 0;\n\t\tkm = 0;\n\t\tfor (unsigned counter = 0; counter < 3; counter++)\n\t\t{\n\t\t\tfor (unsigned counter2 = 0; counter2 < dxup[counter].size(); counter2++)\n\t\t\t{\n\t\t\t\tdxup[counter][counter2] = 0;\n\t\t\t\tdcfr[counter][counter2] = 0;\n\t\t\t\tdcfl[counter][counter2] = 0;\n\t\t\t\tucfrpos[counter][counter2] = 0;\n\t\t\t\tucflpos[counter][counter2] = 0;\n\t\t\t\tucfrneg[counter][counter2] = 0;\n\t\t\t\tucflneg[counter][counter2] = 0;\n\t\t\t}\n\n\t\t}\n\t\tfor (unsigned counter2 = 0; counter2 < sr.size(); counter2++) sr[counter2] = 0;\n\t\tfor (unsigned counter2 = 0; counter2 < sul.size(); counter2++) sul[counter2] = 0;\n\t}\n};\n\nstruct gen    //stores a generation of finite volume nodes\n{\n\tdouble dx;              //element length\n\tunsigned long Nb;        //No of branches in this gen\n\tdouble x0;         //start position\n\tvector<node> p;    //vector of nodes\n\tdouble Ap, Lp;     //defects/perturbations\n\tgen()    //Constructor\n\t{\n\t\tdx = 0;\n\t\tNb = 0;\n\t\tx0 = 0;\n\t}\n\tvoid set_quantities_zero()\n\t{\n\t\tdx = 0;\n\t\tx0 = 0;\n\t\tAp = 0;\n\t\tLp = 0;\n\t}\n};\n\nstruct subtree    //stores a subtree consisting of generations connected in series\n{\n\tunsigned StartGen;           //generation where subtree starts\n\tunsigned long StartBranch;        //branch no. of tree base\n\tunsigned EndGen;             //generation where subtree ends\n\tunsigned Ncond, Ntot;         //Gen at which conducting airways terminate and alv airways terminate\n\tunsigned imeanpath;         //number of mean path\n\tdouble A0, L0, A1, L1;\n\tdouble Vold;            //equivalent total volume of bags at end at time t\n\tdouble Vnew;            //equivalent total volume of bags at end at time t+dt\n\tdouble Valv0, sValv0, V0, Vacinduct;           //length of all pipes in alveoli region\n\tdouble qend;\n\tvector<gen> gn;                 //generation\n\tdouble fluxin, fluxout; //instantantaneous flux at inlet and outlet\n\tdouble masstot, totIGvol;         //total mass in system\n\tdouble totIGvolold;         //total mass in system\n\tint treein;             //number of the tree feeding this one (-1 if root)\n\tint treeout[2];         //numbers of tree fed by this one (both -1 if base)\n\tdouble E, Ep, Rb, Rbp;              //tree elastance and bag resistance\n\tdouble dR;              //effective resistance change at start gen of tree\n\tdouble Rj;                  //effective resistance of subtree\n\tdouble Rtree;                 //resistance of this tree only\n\tdouble dVacinus;           //stores the volume change of the associated acinus (or acini)\n\tdouble z0;   //coordinate for plotting\n\tvector<unsigned> EndSubtrees;              //list of terminating subtrees connected to this subtree\n\tvector<unsigned> isub;                     //list of all subtrees\n\tbool blocked;     //true if blocked off, false if not\n\tunsigned i_stree;   //stores index of corresponding subtree in stree\n\tsubtree()   //constructor\n\t{\n\t\tStartGen = 0;\n\t\tEndGen = NGENTOT;\n\t\tVold = 0;\n\t\tVnew = 0;\n\t\tValv0 = 0;\n\t\tsValv0 = 0;\n\t\tVacinduct = 0;\n\t\tL0 = 0;\n\t\tA0 = 0;\n\t\tL1 = 0;\n\t\tA1 = 0;\n\t\tV0 = 0;\n\t\tqend = 0;\n\t\tfluxin = 0;\n\t\tfluxout = 0;\n\t\tmasstot = 0;\n\t\ttotIGvol = 0;\n\t\ttotIGvolold = 0;\n\t\ttreein = -1;\n\t\ttreeout[0] = -1;\n\t\ttreeout[1] = -1;\n\t\tE = EDEF;\n\t\tEp = 0;\n\t\tRb = RBDEF;\n\t\tRbp = 0;\n\t\tdR = 0;\n\t\tRj = 0;\n\t\tRtree = 0;\n\t\tz0 = 0;\n\t\tblocked = false;\n\t\ti_stree = 0;\n\t\tdVacinus = 0;\n\t}\n\n\t~subtree()\n\t{\n\t\tgn.clear();\n\t}\n\tvoid set_quantities_zero() //set relevant quantities to zero for perturbative model\n\t{\n\t\tVold = 0;\n\t\tVnew = 0;\n\t\tValv0 = 0;\n\t\tsValv0 = 0;\n\t\tV0 = 0;\n\t\tqend = 0;\n\t\tfluxin = 0;\n\t\tfluxout = 0;\n\t\tmasstot = 0;\n\t\ttotIGvol = 0;\n\t\ttotIGvolold = 0;\n\t\tEndSubtrees.clear();\n\t\tEp = 0;\n\t\tRbp = 0;\n\t\tdR = 0;\n\t\tRj = 0;\n\t}\n\tvoid allocate_gn(unsigned size)\n\t{\n\t\tgn.resize(size);\n\t}\n\tvoid deallocate_gn()\n\t{\n\t\tgn.clear();\n\t}\n\tdouble length_function(unsigned j, Options &o);    //returns gen j length\n\tdouble area_function(double dx, unsigned j, Options &o);       //returns dx along gen j cross section  \n\tdouble alveolar_density(unsigned j, unsigned k, Options &o);    //returns alveolar density function\n\tvoid subtree_resistance(void);                               //computes subtree resistance\n\tvoid tot_area_function(double Vtot);                         //distributes sac volume to cross section A\n\tvoid tot_lp_area_function(subtree &sst, double DVtot);        //same as abouve for perturbed tree\n\tvoid velocity_calc(double qend, Options &o);                //calculates flow velocity from A\n\tvoid velocity_lp_calc(subtree &sst, double qend, Options &o);          //same as above for perturbed tree\n};\n\nclass Tree                  //for storing whole airway tree data\n{\npublic:\n\tvector<subtree> st;\n\tdouble masstot, masstotold, fluxin;            //total mass in system\n\tdouble Ppl, Pplold;                //pleural pressure\n\tunsigned pert_ij[2];          //stores st and generation of perturbation\n\tchar pert_type;               //'K', 'A' or 'L' depending on which per\n\t//Eigen matrices and functions fro ventialtion and transport problems\n\tEigen::HouseholderQR<Eigen::MatrixXd> *AmatQR;\n\tEigen::PartialPivLU<Eigen::MatrixXd> *AmatLU;\n\tEigen::BiCGSTAB<Eigen::SparseMatrix<double, Eigen::RowMajor>, Eigen::IncompleteLUT<double>> *solver_iter;\n\tEigen::SparseLU<Eigen::SparseMatrix<double>> *solver_dir;\n\tEigen::MatrixXd Amat, Bmat, Kmat;\n\tEigen::VectorXd KVs, Vs;\n\tdouble VDfront, VDfrontold, VDfrontoldold, cmouth, cmouthold, Vlung, Vairways;  //volume of mouth dead space filled this breath\n\tdouble Vlungold;\n\tvector<double> ctop, Vtot;\n\tvector<unsigned> EndSubtrees, meanpath;         \n\tunordered_map<unsigned, unsigned> STno_to_ESTno;   //subtree number to end subtree number\n\tvector<vector<unsigned>> mpsubtrees;  //stores subtrees that are in a given mean path\n\tdouble R0;\n\tunsigned long kmtot;  //total number of points for transport equations\n\tTree() //constructor\n\t{\n\t\tmasstot = 0;\n\t\tfluxin = 0;\n\t\tPpl = 0;\n\t\tPplold = 0;\n\t\tpert_ij[0] = 0;\n\t\tpert_ij[1] = 0;\n\t\tpert_type = 'N';  //N for none\n\t\tcmouth = 1;\n\t\tcmouthold = 1;\n\t\tVDfront = 0;\n\t\tVDfrontold = 0;\n\t\tVDfrontoldold = 0;\n\t\tkmtot = 0;\n\t\tctop.clear();\n\t\tVtot.clear();\n\t}\n\t~Tree()\n\t{\n\t\tctop.clear();\n\t\tVtot.clear();\n\t}\n\t//output functions\n\tint printfunc_tree(string filename, Conversions cons);\n\tint printfunc_lp_tree(string filename, Tree &stree, Conversions cons);\n\tint printfunc_tree_csv(string filename, Conversions cons);\n\tint printfunc_lp_tree_csv(string filename, Tree &stree, Conversions cons);\n\tEIGEN_MAKE_ALIGNED_OPERATOR_NEW\n};\n\n//read and set simulation options\nint parse_options(string infile, Options &o);\nvoid check_option_consistency(Options &o);\nint convert_units(Tree &stree, Conversions &cons, double LL, Options &o);\n\n//initialisation\nint initialise_system(Tree &stree, Conversions &cons, Options &o);\nint initialise_defects(Tree &stree, Options &o);\nint initialise_tree(Tree &stree, Options &o);\nint pre_run_breaths(Tree &stree, vector<Tree> &ltree, double &time, Options &o);\nint initialise_lung_volumes(Tree &stree, vector<Tree> &ltree, Options &o);\n\n//tree building\ndouble build_alternative_lobe_branches(Tree &stree, Options &o);\ndouble build_symmetric_branches(Tree &stree, Options &o);\nstring read_lobe_no(unsigned i, Options &o);\n\n//build perturbed trees\nvoid setup_pert_trees(vector<Tree> &ltree, Tree &stree, Options &o);\nvoid setup_lp_tree(vector<Tree> &ltree, Tree &stree, Options &o);\nvoid calc_perts(vector<Tree> &ltree, Tree &stree);\nvoid apply_pert(Tree &ltree, Tree &stree);\n\n//build and solve ventilation problem\nint update_flux(Tree &stree, vector<Tree> &ltree, double time, Options &o);\nint tree_flux(Tree &stree, double time, Options &o);\nint tree_lp_flux(Tree &ltree, Tree &stree, Options &o);\n\n//build and solve transport problem\nint update_conc(Tree &stree, vector<Tree> &ltree, double time, Options &o);\nint update_c_stree(Tree &stree, double time, Options &o);\nint update_c_ltree(Tree &ltree, Tree &stree, double time, Options &o);\nvoid calc_gas_concs(Tree &stree, Eigen::VectorXd &XC, Options &o);\nvoid fill_Ab(Tree &stree, Eigen::SparseMatrix<double, Eigen::RowMajor> &AC, Eigen::VectorXd &XC, Eigen::VectorXd &BC, unsigned long Ntot, double time, Options &o);\nvoid calc_gas_concs_lp(Tree &ltree, Tree &stree, Eigen::VectorXd &XC, Options &o);\nvoid fill_Ab_lp(Tree &ltree, Tree &stree, Eigen::SparseMatrix<double, Eigen::RowMajor> &AC, Eigen::VectorXd &XC, Eigen::VectorXd &BC, unsigned long Ntot, Options &o);\n\n//output functions\nint printfunc(Tree &stree, vector<Tree> &ltree, Options &o, Conversions cons, double t);\nint append_masterout(string filename, double time, Tree &tree, Options &o, Conversions cons);\nint print_simops(ofstream &summary_file, Options &o);\nint print_params(ofstream &summary_file, Options &o);\n\n//various input functions determining parameters\ndouble pressure_func(double t, Options &o);\ndouble c_stim(double t, Options &o);\n\ndouble total_run_time(Options &o);\nunsigned long calc_ts_number(Options &o);\nunsigned lobe_gens(unsigned nlobe, Options &o);  //returns gen number of final branch\nunsigned long ijk_index(unsigned i, unsigned j, unsigned long k, Options &o);\ndouble weibel_length(unsigned j);\ndouble weibel_area(unsigned j);\n\n//calculating resistance matrices for ventilation problem\nvoid subtree_resistance(Tree &tree, unsigned i, Options &o);\nvoid subtree_lp_symm_resistance(subtree &st, subtree &symm, Options &o);\nint full_tree_fluxcalc(Tree &tree, double time, Options &o);\nint full_lp_tree_fluxcalc(Tree &ltree, Tree &stree, Options &o);\nint build_resistance_matrix(Tree &tree, Options &o);\nbool isparent(Tree &tree, unsigned ip, unsigned id);\n\n//finite difference functions and solving routines\nvoid upwind_coeffs(vector<double> ucfl[3], vector<double> ucfr[3], vector<double> dxh[3], double u0, Options &o);\nvoid lp_upwind_coeffs(vector<double> ducfl[3], vector<double> ducfr[3], vector<double> dx0[3], vector<double> dxh[3], double u0, Options &o);\nvoid fd_coeffs(vector<double> dcfl[3], vector<double> dcfr[3], vector<double> dxh[3]);\nvoid lp_fd_coeffs(vector<double> ddcfl[3], vector<double> ddcfr[3], vector<double> dx0[3], vector<double> dxh[3]);\nvoid tree_point_pos(Tree &tree, unsigned i, unsigned j, unsigned k, int n, vector<unsigned> &in, vector<unsigned> &jn, vector<unsigned> &kn);\nint iterative_solver(Eigen::BiCGSTAB<Eigen::SparseMatrix<double, Eigen::RowMajor>, Eigen::IncompleteLUT<double>> *solver, Eigen::SparseMatrix<double, Eigen::RowMajor> &AC, Eigen::VectorXd &x, Eigen::VectorXd &b);\nint LU_solver(Eigen::SparseLU<Eigen::SparseMatrix<double>, Eigen::COLAMDOrdering<int>> *solver, Eigen::SparseMatrix<double> &A, Eigen::VectorXd &x, Eigen::VectorXd &b);\n\ninline unsigned bitflip(unsigned m)\n{\n\tif (m == 0) return 1;\n\telse return 0;\n}\n\ninline bool jcomp(Defect d1, Defect d2)  //compare defect by i, then j, then k, then type, then magntiude\n{\n\treturn ((d1.jn < d2.jn) || ((d1.jn == d2.jn) && (d1.kstart < d2.kstart)) || ((d1.jn == d2.jn) && (d1.kstart == d2.kstart) && (d1.type < d2.type)));\n}\n", "meta": {"hexsha": "8fd7f51f7502354f385870fef8323faf15656d6e", "size": 22778, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/lung_model_discrete_branching.hpp", "max_stars_repo_name": "CarlWhitfield/PULMsim", "max_stars_repo_head_hexsha": "3f7e135e44c0cbae2064a3a43dcaf3239fef5c67", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-07T15:53:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-07T15:53:30.000Z", "max_issues_repo_path": "include/lung_model_discrete_branching.hpp", "max_issues_repo_name": "CarlWhitfield/PULMsim", "max_issues_repo_head_hexsha": "3f7e135e44c0cbae2064a3a43dcaf3239fef5c67", "max_issues_repo_licenses": ["MIT"], "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/lung_model_discrete_branching.hpp", "max_forks_repo_name": "CarlWhitfield/PULMsim", "max_forks_repo_head_hexsha": "3f7e135e44c0cbae2064a3a43dcaf3239fef5c67", "max_forks_repo_licenses": ["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.4078549849, "max_line_length": 212, "alphanum_fraction": 0.6850030731, "num_tokens": 6679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.46855440693457556}}
{"text": "#ifndef GIFS_LINKATOMS_H\n#define GIFS_LINKATOMS_H\n\n#include <armadillo>\n\nclass LinkAtoms\n{\npublic:\n\n    // you own it\n    static LinkAtoms* with_const_factors(const arma::umat global_idx, arma::vec factors);\n    //\n    static LinkAtoms* with_const_length(const arma::umat global_idx, arma::vec dist);\n    //\n    arma::mat& get_frc() { return frc; }\n    arma::mat& get_crd() { return crd; }\n    //\n    inline void set_local_idx(const size_t* indices) {\n        auto itr = local_idx.begin();\n        for (size_t idx=0; idx<nlink; ++idx) {\n            *itr++ = indices[idx*2];\n            *itr++ = indices[idx*2+1];\n        }\n    };\n    // assume global coords\n    template<typename T>\n    void update_crd(T* syscrd);\n    // assume local coords!\n    template<typename T>\n    void update_crd(T* qmcrd, T* mmcrd);\n    //\npublic:\n    arma::uword nlink{0};\nprivate:\n    LinkAtoms(arma::umat in_idxs, arma::vec in_factors, arma::vec in_dist):\n      nlink{in_factors.size()}, factors{in_factors},  dist{in_dist},\n      crd(3, nlink), frc(3, nlink), global_idx{in_idxs}, local_idx(2, nlink) {}\n    //\n    template<typename T>\n    inline double \n    get_la_crd(const double& x, const T& qmcrd, const T& mmcrd) {\n        return (1.0-x) * qmcrd + x * mmcrd;\n    };\n    //\n    template<typename T>\n    void update_factors(T* qmcrd, T* mmcrd);\n    //\n    template<typename T>\n    void update_factors(T* syscrd); \n    //\nprotected:\n     //\n    arma::vec factors{};\n    arma::vec dist{};\n    // \n    arma::mat crd{};\n    arma::mat frc{};\n    // global idx\n    arma::umat global_idx{};\n    // local index\n    arma::umat local_idx{};\n};\n// assume global coords\ntemplate<typename T>\nvoid \nLinkAtoms::update_crd(T* syscrd) {\n    if (!dist.empty()) {\n        update_factors(syscrd);\n    }\n    auto itr = crd.begin();\n    for (size_t idx=0; idx<nlink; ++idx) {\n        auto col = global_idx.col(idx);\n        arma::uword qmid = col[0]*3;\n        arma::uword mmid = col[1]*3;\n        double fac = factors[idx];\n\n        for(size_t ixyz=0; ixyz<3; ++ixyz) {\n            *itr++ = get_la_crd(fac, syscrd[qmid + ixyz], syscrd[mmid + ixyz]);\n        }\n    }\n};\n// assume local coords, qm and mm section\ntemplate<typename T>\nvoid \nLinkAtoms::update_crd(T* qmcrd, T* mmcrd) {\n    if (!dist.empty()) {\n        update_factors(qmcrd, mmcrd);\n    }\n\n    auto itr = crd.begin();\n    for (size_t idx=0; idx<nlink; ++idx) {\n        auto col = local_idx.col(idx);\n        arma::uword qmid = col[0]*3;\n        arma::uword mmid = col[1]*3;\n        double fac = factors[idx];\n\n        for(size_t ixyz=0; ixyz<3; ++ixyz) {\n            *itr++ = get_la_crd(fac, qmcrd[qmid + ixyz], mmcrd[mmid + ixyz]);\n        }\n    }\n};\n    \ntemplate<typename T>\nvoid \nLinkAtoms::update_factors(T* syscrd) {\n    auto fac_itr = factors.begin();\n    auto dist_itr = dist.begin();\n    for (size_t idx=0; idx<nlink; ++idx) {\n        auto col = local_idx.col(idx);\n        arma::uword qmid = col[0]*3;\n        arma::uword mmid = col[1]*3;\n        double R = 0;\n        for(size_t ixyz=0; ixyz<3; ++ixyz) {\n            R += pow(syscrd[qmid + ixyz] - syscrd[mmid + ixyz], 2);\n        }\n            *fac_itr++ = *dist_itr++/std::sqrt(R);\n    }\n};\n// assume local coords, qm and mm section\ntemplate<typename T>\nvoid \nLinkAtoms::update_factors(T* qmcrd, T* mmcrd) {\n    auto fac_itr = factors.begin();\n    auto dist_itr = dist.begin();\n    for (size_t idx=0; idx<nlink; ++idx) {\n        auto col = local_idx.col(idx);\n        arma::uword qmid = col[0]*3;\n        arma::uword mmid = col[1]*3;\n        double R = 0;\n        for(size_t ixyz=0; ixyz<3; ++ixyz) {\n            R += pow(qmcrd[qmid + ixyz] - mmcrd[mmid + ixyz], 2);\n        }\n        *fac_itr++ = *dist_itr++/std::sqrt(R);\n    }\n};\n\n#endif // GIFS_LINKATOMS_H\n", "meta": {"hexsha": "2d9a79d313c47fc87a28b86a81497dd9770c11fb", "size": 3749, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/linkatoms.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/linkatoms.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/linkatoms.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": 27.1666666667, "max_line_length": 89, "alphanum_fraction": 0.5689517205, "num_tokens": 1176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4685544069345755}}
{"text": "/*\n * Copyright [2015] [Ke Sun <sunke.polyu@gmail.com>]\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#include <ros/ros.h>\n#include <Eigen/SVD>\n#include <mocap_base/KalmanFilter.h>\n\nusing namespace std;\nusing namespace Eigen;\n\nnamespace mocap {\n\nKalmanFilter::KalmanFilter():\n  attitude         (Quaterniond::Identity()),\n  position         (Vector3d::Zero()),\n  angular_vel      (Vector3d::Zero()),\n  linear_vel       (Vector3d::Zero()),\n  state_cov        (Matrix12d::Identity()),\n  input_cov        (Matrix12d::Identity()),\n  measurement_cov  (Matrix6d::Identity()),\n  filter_status    (INIT_POSE),\n  last_time_stamp  (0.0),\n  msg_interval     (0.01),\n  proc_jacob       (Matrix12d::Zero()),\n  meas_jacob       (Matrix6_12d::Zero()),\n  proc_noise_jacob (Matrix12d::Zero()),\n  meas_noise_jacob (Matrix6d::Zero()) {\n\n  // Needs to be changed based on angular velocity\n  // and time interval\n  proc_jacob = Matrix12d::Identity();\n  proc_noise_jacob = Matrix12d::Identity();\n\n  // Do not need to be changed\n  meas_jacob.leftCols<6>() = Matrix6d::Identity();\n  meas_noise_jacob = Matrix6d::Identity();\n\n  return;\n}\n\nbool KalmanFilter::init(const Matrix12d& u_cov,\n    const Matrix6d& m_cov, const int& freq) {\n  bool is_valid = true;\n  JacobiSVD<Matrix12d> u_svd(u_cov);\n  JacobiSVD<Matrix6d> m_svd(m_cov);\n\n  Vector12d u_sigmas = u_svd.singularValues();\n  Vector6d m_sigmas = m_svd.singularValues();\n\n  if (u_sigmas(11) < 1e-10) {\n    is_valid = false;\n    ROS_ERROR(\"Input Cov is close to singular (least singlar value:%f < 1e-7)\",\n        u_sigmas(11));\n  } else {\n    input_cov = u_cov;\n  }\n\n  if (m_sigmas(5) < 1e-10) {\n    is_valid = false;\n    ROS_ERROR(\"Measurement Cov is close to singular (least singlar value:%f < 1e-7)\",\n        m_sigmas(5));\n  } else {\n    measurement_cov = m_cov;\n  }\n\n  if (freq < 0) {\n    is_valid = false;\n    ROS_ERROR(\"Invalid frequency for filter (%d < 0)\", freq);\n  } else {\n    msg_interval = 1.0 / static_cast<double>(freq);\n  }\n\n  return is_valid;\n}\n\nbool KalmanFilter::prepareInitialCondition(\n    const double& curr_time_stamp,\n    const Eigen::Quaterniond& m_attitude,\n    const Eigen::Vector3d& m_position) {\n\n  switch (filter_status) {\n    case INIT_POSE: {\n      // Set the current pose\n      last_time_stamp = curr_time_stamp;\n      attitude = m_attitude;\n      position = m_position;\n      filter_status = INIT_TWIST;\n      // Set the uncertainty of the state\n      state_cov = Matrix12d::Identity();\n      return true;\n    }\n    case INIT_TWIST: {\n      // Compute the difference between the current\n      // pose and last pose\n      Quaterniond dq = m_attitude*attitude.inverse();\n      AngleAxisd daa(dq);\n      Vector3d dr = m_position-position;\n      double dt = curr_time_stamp-last_time_stamp;\n      //dt = dt > 0 ? dt : msg_interval;\n      dt = dt*0.9 + msg_interval*0.1;\n      // Set current pose and velocity\n      last_time_stamp += dt;\n      attitude = m_attitude;\n      position = m_position;\n      angular_vel = daa.axis()*daa.angle()/dt;\n      linear_vel = dr/dt;\n      // Set the uncertainty of the state\n      state_cov = Matrix12d::Identity();\n      filter_status = READY;\n      return true;\n    }\n    case READY:\n      return false;\n    default:\n      return false;\n  }\n  return false;\n}\n\nbool KalmanFilter::isReady() {\n  if (filter_status != READY)\n    return false;\n  else\n    return true;\n}\n\nvoid KalmanFilter::reset() {\n  filter_status = INIT_POSE;\n  return;\n}\n\nvoid KalmanFilter::prediction(const double& curr_time_stamp) {\n  // Propogate the actual state\n  double dt = curr_time_stamp - last_time_stamp;\n  //dt = dt > 0 ? dt : msg_interval;\n  dt = dt*0.9 + msg_interval*0.1;\n  Vector3d dw = angular_vel * dt;\n  Vector3d dr = linear_vel * dt;\n\n  double dangle = dw.norm();\n  Vector3d axis = dw / dangle;\n  AngleAxisd daa(dangle, axis);\n  Quaterniond dq(daa);\n  // Velocities are modeled as constants\n  last_time_stamp += dt;\n  attitude = dq * attitude;\n  position = dr + position;\n\n  // Propogate the uncertainty of the estimation error\n  // TODO: Optimize this part\n  proc_jacob(0,  1) =  dw(2);\n  proc_jacob(0,  2) = -dw(1);\n  proc_jacob(1,  0) = -dw(2);\n  proc_jacob(1,  2) =  dw(0);\n  proc_jacob(2,  0) =  dw(1);\n  proc_jacob(2,  1) = -dw(0);\n  proc_jacob(0,  6) =  dt;\n  proc_jacob(1,  7) =  dt;\n  proc_jacob(2,  8) =  dt;\n  proc_jacob(3,  9) =  dt;\n  proc_jacob(4, 10) =  dt;\n  proc_jacob(5, 11) =  dt;\n\n  //state_cov = proc_jacob*state_cov*proc_jacob.transpose() +\n  //  proc_noise_jacob*input_cov*proc_noise_jacob.transpose();\n  state_cov = proc_jacob*state_cov*proc_jacob.transpose() + input_cov;\n\n  //cout << \"Process: \" << endl;\n  //cout << \"att: \" <<\n  //  Vector4d(attitude.w(), attitude.x(), attitude.y(), attitude.z()).transpose() << endl;\n  //cout << \"pos: \" << position.transpose() << endl;\n  //cout << \"ang: \" << angular_vel.transpose() << endl;\n  //cout << \"lin: \" << linear_vel.transpose() << endl;\n  //cout << \"input noise:\\n\" << input_cov << endl;\n  //cout << \"proc_jacob:\\n\" << proc_jacob << endl;\n  //cout << \"Pk+1|k:\\n\" << state_cov << endl;\n\n  return;\n}\n\nvoid KalmanFilter::update(const Eigen::Quaterniond& m_attitude,\n    const Eigen::Vector3d& m_position) {\n  // TODO: Optimize the whole function\n  // Compute the residual of the measurement\n  Quaterniond re_q = m_attitude * attitude.inverse();\n  AngleAxisd re_aa(re_q);\n  if (std::abs(re_aa.angle()) > std::abs(2*M_PI-re_aa.angle())) {\n    re_aa.angle() = 2*M_PI - re_aa.angle();\n    re_aa.axis() = -re_aa.axis();\n  }\n  Quaterniond re_qs(re_aa);\n  Vector3d re_th(re_qs.x()*2.0, re_qs.y()*2.0, re_qs.z()*2.0);\n  Vector3d re_r = m_position - position;\n  Vector6d re;\n  re.head<3>() = re_th;\n  re.tail<3>() = re_r;\n\n  // Compute the covariance of the residual\n  //Matrix6d S = measurement_cov +\n  //  meas_jacob*state_cov*meas_jacob.transpose();\n  Matrix6d S = measurement_cov + state_cov.topLeftCorner<6, 6>();\n\n  // Compute the Kalman gain\n  //Matrix12_6d K = state_cov*meas_jacob.transpose()*S.inverse();\n  Matrix12_6d K = state_cov.leftCols<6>()*S.inverse();\n\n  // Compute the correction of the state\n  Vector12d dx = K * re;\n\n  // Update the state based on the correction\n  Vector3d dq_vec3 = dx.head<3>() / 2.0;\n  Vector4d dq_vec4 = 1.0/sqrt(1.0+dq_vec3.squaredNorm())*\n    Vector4d(dq_vec3(0), dq_vec3(1), dq_vec3(2), 1.0);\n  Quaterniond dq(dq_vec4(3), dq_vec4(0), dq_vec4(1), dq_vec4(2));\n\n  attitude = dq * attitude;\n  position += dx.segment<3>(3);\n  angular_vel += dx.segment<3>(6);\n  linear_vel += dx.segment<3>(9);\n\n  // Update the uncertainty of the state/error\n  state_cov = (Matrix12d::Identity()-K*meas_jacob) * state_cov;\n\n  //cout << \"Error: \" << endl;\n  //cout << \"dat: \" << Vector4d(re_q.w(), re_q.x(), re_q.y(), re_q.z()).transpose() << endl;\n  //cout << \"dpo: \" << re_r.transpose() << endl;\n\n  //cout << \"Innovation: \" << endl;\n  //cout << \"dat: \" << Vector4d(dq.w(), dq.x(), dq.y(), dq.z()).transpose() << endl;\n  //cout << \"dpo: \" << dx.segment<3>(3).transpose() << endl;\n  //cout << \"dan: \" << dx.segment<3>(6).transpose() << endl;\n  //cout << \"dli: \" << dx.segment<3>(9).transpose() << endl;\n\n  //cout << \"Update: \" << endl;\n  //cout << \"att: \" <<\n  //  Vector4d(attitude.w(), attitude.x(), attitude.y(), attitude.z()).transpose() << endl;\n  //cout << \"pos: \" << position.transpose() << endl;\n  //cout << \"ang: \" << angular_vel.transpose() << endl;\n  //cout << \"lin: \" << linear_vel.transpose() << endl;\n  //cout << \"means_jacob:\\n\" << meas_jacob << endl;\n  //cout << \"Pk+1|k:\\n\" << state_cov << endl;\n  //cout << \"meas_noise:\\n\" << measurement_cov << endl;\n  //cout << endl;\n\n  return;\n}\n}\n", "meta": {"hexsha": "edd1e252dc5fcbdfe6dca89dce079f18f27c6bf8", "size": 8078, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mocap_base/src/KalmanFilter.cpp", "max_stars_repo_name": "mbaytas/motion_capture_system", "max_stars_repo_head_hexsha": "fbc1a89df63d1cca15b7b471f50270e423198a69", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 48.0, "max_stars_repo_stars_event_min_datetime": "2017-02-02T22:49:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-26T12:20:41.000Z", "max_issues_repo_path": "mocap_base/src/KalmanFilter.cpp", "max_issues_repo_name": "mbaytas/motion_capture_system", "max_issues_repo_head_hexsha": "fbc1a89df63d1cca15b7b471f50270e423198a69", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-12-15T11:29:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-25T21:11:47.000Z", "max_forks_repo_path": "mocap_base/src/KalmanFilter.cpp", "max_forks_repo_name": "mbaytas/motion_capture_system", "max_forks_repo_head_hexsha": "fbc1a89df63d1cca15b7b471f50270e423198a69", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 33.0, "max_forks_repo_forks_event_min_datetime": "2016-01-11T15:46:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-25T13:09:44.000Z", "avg_line_length": 30.9501915709, "max_line_length": 92, "alphanum_fraction": 0.6365436989, "num_tokens": 2465, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956580903722561, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.468554401227711}}
{"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_GORDON_LOWE_HPP\n#define PIC_COMPUTER_VISION_NELDER_MEAD_OPT_GORDON_LOWE_HPP\n\n#include \"../util/matrix_3_x_3.hpp\"\n#include \"../util/nelder_mead_opt_base.hpp\"\n#include \"../computer_vision/camera_matrix.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\n#define GL_PACKED_CAMERA_SIZE 11\n#define GL_3D_POINT_SIZE 3\n\nclass NelderMeadOptGordonLowe: public NelderMeadOptBase<double>\n{\npublic:\n    std::vector< std::vector< Vec<2, float> > > m;\n\n    /**\n     * @brief NelderMeadOptGordonLowe\n     * @param m0\n     * @param m1\n     */\n    NelderMeadOptGordonLowe(std::vector< Vec<2, float> > m0, std::vector< Vec<2, float> > m1) : NelderMeadOptBase()\n    {\n        this->m.push_back(m0);\n        this->m.push_back(m1);\n    }    \n\n    static Eigen::Matrix34d parseCameraMatrix(float *x, unsigned int index)\n    {\n        Eigen::Matrix3d K, R;\n        Eigen::Vector3d t;\n\n        //offset of the matrix\n        unsigned int c = index * 11;\n\n        Eigen::Quaternion<double> reg;\n        reg.x() = x[c]; c++;\n        reg.y() = x[c]; c++;\n        reg.z() = x[c]; c++;\n        reg.w() = x[c]; c++;\n        R = reg.toRotationMatrix();\n\n        t[0] = x[c]; c++;\n        t[1] = x[c]; c++;\n        t[2] = x[c]; c++;\n\n        K.setZero();\n        K(0, 0) = x[c]; c++;\n        K(1, 1) = x[c]; c++;\n        K(0, 2) = x[c]; c++;\n        K(1, 2) = x[c];\n        K(2, 2) = 1.0;\n\n        return getCameraMatrix(K, R, t);\n    }\n\n    /**\n     * @brief ProjectionError\n     * @param x\n     * @param index\n     * @return\n     */\n    double ProjectionError(float *x, unsigned int index) {\n\n       double err = 0.0;\n\n       Eigen::Matrix34d P = parseCameraMatrix(x, index);\n\n       //offset of vertices\n       int c = GL_PACKED_CAMERA_SIZE * int(m.size());\n\n       Eigen::Vector4d point;\n       for(int i = 0; i < m[index].size(); i++) {\n           point = Eigen::Vector4d(x[c], x[c + 1], x[c + 2], 1.0);\n\n           Eigen::Vector3d point_proj = P * point;\n           point_proj /= point_proj[2];\n\n           double dx = point_proj[0] - m[index][i][0];\n           double dy = point_proj[1] - m[index][i][1];\n\n           err += dx * dx + dy * dy;\n\n           c += 3;\n       }\n\n\n       return err;\n    }\n\n    /**\n     * @brief function\n     * @param x\n     * @param n\n     * @return\n     */\n    float function(float *x, unsigned int n)\n    {       \n        int n2 = int(m.size() * m[0].size());\n        double err = sqrt((ProjectionError(x, 0) + ProjectionError(x, 1)) / double(n2));\n\n        return float(err);\n    }\n\n\n    /**\n     * @brief init3DPoints\n     * @param K\n     * @param m\n     * @param x\n     * @param distance\n     */\n    static void init3DPoints(Eigen::Matrix3d K, std::vector< Vec<2, float> > &m, std::vector< Eigen::Vector3d > &x, float distance = 20.0f)\n    {\n        Eigen::Matrix3d K_inv = K.inverse();\n    \\\n        printf(\"Points: %zd\\n\", m.size());\n\n        for(unsigned int i = 0; i < m.size(); i++) {\n            Eigen::Vector3d point = Eigen::Vector3d (m[i][0], m[i][1], 1.0);\n\n            point = K_inv * point;\n\n            point *= distance;\n\n            x.push_back(point);\n        }\n    }\n\n    /**\n     * @brief prepareInputData\n     * @param K\n     * @param R\n     * @param t\n     * @param x\n     * @param ret_size\n     * @return\n     */\n    static double *prepareInputData(std::vector< Eigen::Matrix3d > &K, std::vector< Eigen::Matrix3d > &R, std::vector< Eigen::Vector3d > &t, std::vector< Eigen::Vector3d > &x, unsigned int &ret_size)\n    {\n        if(R.size() != t.size()) {\n            return NULL;\n        }\n\n        if(x.empty()) {\n            return NULL;\n        }\n\n        int n = int (R.size());\n        ret_size = GL_PACKED_CAMERA_SIZE * n + GL_3D_POINT_SIZE * int(x.size());\n        double *ret = new double[ret_size];\n\n        int c = 0;\n        for(int i = 0; i < n; i++) {\n\n            Eigen::Quaternion<double> reg(R[i]);\n\n            ret[c] = reg.x(); c++;\n            ret[c] = reg.y(); c++;\n            ret[c] = reg.z(); c++;\n            ret[c] = reg.w(); c++;\n\n            ret[c] = t[i][0]; c++;\n            ret[c] = t[i][1]; c++;\n            ret[c] = t[i][2]; c++;\n\n            ret[c] = K[i](0, 0); c++;\n            ret[c] = K[i](1, 1); c++;\n            ret[c] = K[i](0, 2); c++;\n            ret[c] = K[i](1, 2); c++;\n        }\n\n        for(size_t i = 0; i < x.size(); i++) {\n            ret[c] = x[i][0]; c++;\n            ret[c] = x[i][1]; c++;\n            ret[c] = x[i][2]; c++;\n        }\n\n        return ret;\n    }\n};\n\n#endif\n\n}\n\n#endif // PIC_COMPUTER_VISION_NELDER_MEAD_OPT_GORDON_LOWE_HPP\n", "meta": {"hexsha": "66726b5d5046fed6ad81e45c5992a0f61dc76755", "size": 5097, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/computer_vision/nelder_mead_opt_gordon_lowe.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_gordon_lowe.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_gordon_lowe.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": 23.5972222222, "max_line_length": 199, "alphanum_fraction": 0.5140278595, "num_tokens": 1566, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.795658090372256, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.46855440122771097}}
{"text": "// https://qiita.com/lucidfrontier45/items/5048ef74fbf32eeb9f08\r\n\r\n#include <iostream>\r\n#include <pybind11/eigen.h>\r\n#include <Eigen/Core>\r\nnamespace py = pybind11;\r\n\r\ntemplate <typename T>\r\nusing RMatrix = Eigen::Matrix<T, -1, -1, Eigen::RowMajor>;\r\n\r\ntemplate <typename T>\r\nvoid print_array(RMatrix<T> m){\r\n    py::print(m);\r\n}\r\ntemplate <typename T>\r\nRMatrix<T> modify_array(RMatrix<T> m, T a){\r\n    return m * a;\r\n}\r\ntemplate <typename T>\r\nvoid modify_array_inplace(Eigen::Ref<RMatrix<T>> m, T a){ //\u4e2d\u8eab\u53c2\u7167\r\n    m = m * a;\r\n}\r\ntemplate<typename T>\r\nvoid modify_new_array(Eigen::Ref<RMatrix<T>> m){\r\n    m = RMatrix<T>::Ones(3,10); // not work\r\n\t\r\n}\r\ntemplate<typename T>\r\nRMatrix<T> get_new_array(){\r\n    RMatrix<T> m = RMatrix<T>::Ones(10,3);\r\n\tfor(int i=0; i<m.rows(); ++i){\r\n\t\tfor(int j=0; j<m.cols(); ++j){\r\n\t\t\tstd::cout << m(i,j) << std::endl;\r\n\t\t}\r\n\t}\r\n\tRMatrix<T> mm(1,3);\r\n\tmm << 100,200,300;\r\n\tm.block(0,0,1,3) = mm;\r\n\treturn m;\r\n}\r\n\r\nPYBIND11_MODULE(MY_MODULE_NAME, m){\r\n    m.def(\"print_array\", &print_array<double>, \"\");\r\n    m.def(\"modify_array\", &modify_array<double>, \"\");\r\n    m.def(\"modify_array_inplace\", &modify_array_inplace<double>, \"\");\r\n\tm.def(\"modify_new_array\", &modify_new_array<double>, \"\");\r\n\tm.def(\"get_new_array\", &get_new_array<double>, \"\");\r\n}\r\n", "meta": {"hexsha": "4877f036fc1973406648045fa79ea06335b91c0a", "size": 1279, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "eigen_mod2/main.cpp", "max_stars_repo_name": "Nitta-K-git/pybind_samples", "max_stars_repo_head_hexsha": "6b618bfebc4289061b4ebcfb64ce1da171515bb9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "eigen_mod2/main.cpp", "max_issues_repo_name": "Nitta-K-git/pybind_samples", "max_issues_repo_head_hexsha": "6b618bfebc4289061b4ebcfb64ce1da171515bb9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "eigen_mod2/main.cpp", "max_forks_repo_name": "Nitta-K-git/pybind_samples", "max_forks_repo_head_hexsha": "6b618bfebc4289061b4ebcfb64ce1da171515bb9", "max_forks_repo_licenses": ["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.1020408163, "max_line_length": 70, "alphanum_fraction": 0.6286161063, "num_tokens": 397, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947425132315, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.46852741747999804}}
{"text": "#include <k52/optimization/hooke_jeeves_method.h>\n\n#ifdef BUILD_WITH_MPI\n\n#include <boost/mpi.hpp>\n#include <k52/parallel/mpi/constants.h>\n\n#endif\n\n#include <iostream>\n#include <cmath>\n#include <algorithm>\n#include <stdexcept>\n\n#include <k52/common/floating_point.h>\n#include <k52/optimization/params/i_continuous_parameters.h>\n\nusing ::std::vector;\n\nnamespace k52\n{\nnamespace optimization\n{\n\nHookeJeevesMethod::HookeJeevesMethod(\n    double acceleration,\n    double init_step,\n    size_t max_iteration_number,\n    double precision,\n    double step_divider)\n    : acceleration_(acceleration)\n    , init_step_(init_step)\n    , max_iteration_number_(max_iteration_number)\n    , precision_(precision)\n    , step_divider_(step_divider)\n{\n}\n\nHookeJeevesMethod* HookeJeevesMethod::Clone() const\n{\n    return new HookeJeevesMethod(\n        acceleration_,\n        init_step_,\n        max_iteration_number_,\n        precision_,\n        step_divider_);\n}\n\nstd::string HookeJeevesMethod::get_name() const\n{\n    return \"Hooke-Jeeves Method\";\n}\n\n#ifdef BUILD_WITH_MPI\nvoid HookeJeevesMethod::Send(boost::mpi::communicator* communicator, int target) const\n{\n    communicator->send(target, k52::parallel::mpi::constants::kCommonTag, acceleration_);\n    communicator->send(target, k52::parallel::mpi::constants::kCommonTag, precision_);\n    communicator->send(target, k52::parallel::mpi::constants::kCommonTag, max_iteration_number_);\n    communicator->send(target, k52::parallel::mpi::constants::kCommonTag, init_step_);\n    communicator->send(target, k52::parallel::mpi::constants::kCommonTag, step_divider_);\n}\n\nvoid HookeJeevesMethod::Receive(boost::mpi::communicator* communicator, int source)\n{\n    communicator->recv(source, k52::parallel::mpi::constants::kCommonTag, acceleration_);\n    communicator->recv(source, k52::parallel::mpi::constants::kCommonTag, precision_);\n    communicator->recv(source, k52::parallel::mpi::constants::kCommonTag, max_iteration_number_);\n    communicator->recv(source, k52::parallel::mpi::constants::kCommonTag, init_step_);\n    communicator->recv(source, k52::parallel::mpi::constants::kCommonTag, step_divider_);\n}\n#endif\n\nvector<double> HookeJeevesMethod::FindOptimalParameters(const vector<double>& initial_parameters)\n{\n    vector<double> arguments(initial_parameters);\n    vector<double> arguments_after_search(initial_parameters.size());\n    vector<double> steps_array = vector<double>(arguments.size(), init_step_);\n    size_t iteration = 0;\n\n    do\n    {\n        arguments_after_search = CoordinatewiseSearch(arguments, steps_array);\n        if (common::FloatingPoint::AreEqual(arguments, arguments_after_search))\n        {\n            for (size_t i = 0; i < steps_array.size(); ++i)\n            {\n                steps_array[i] /= step_divider_;\n            }\n            continue;\n        }\n\n        vector<double> next_step_arguments(arguments.size());\n        vector<double> next_step_arguments_after_search(arguments.size());\n        while (true)\n        {\n            for (size_t i = 0; i<arguments.size(); ++i)\n            {\n                next_step_arguments[i] = arguments[i] + acceleration_\n                        * (arguments_after_search[i] - arguments[i]);\n            }\n            next_step_arguments_after_search = CoordinatewiseSearch(next_step_arguments, steps_array);\n\n            arguments = arguments_after_search;\n            if (CountObjectiveFunctionValueToMinimize(arguments_after_search) <=\n                    CountObjectiveFunctionValueToMinimize(next_step_arguments_after_search))\n            {\n                break;\n            }\n            arguments_after_search = next_step_arguments_after_search;\n\n            iteration++;\n            // Check number of iterations\n            if (iteration == max_iteration_number_)\n            {\n                std::cout << \"Solution not found\" << std::endl;\n                return arguments_after_search;\n            }\n        }\n    } while (!IsExitCriteriaFulfilled(steps_array));\n    return arguments_after_search;\n}\n\nbool HookeJeevesMethod::IsExitCriteriaFulfilled(\n    const vector<double>& steps_array) const\n{\n    double temp = 0;\n    // Check if step is small enough\n    for (size_t j = 0; j<steps_array.size(); ++j)\n    {\n        temp += steps_array[j] * steps_array[j];\n    }\n    if (std::sqrt(temp) <= precision_)\n    {\n        return true;\n    }\n    return false;\n}\n\nvector<double> HookeJeevesMethod::CoordinatewiseSearch(\n    const vector<double>& arguments,\n    const vector<double>& steps_array) const\n{\n    vector<double> new_arguments(arguments);\n    for (size_t i = 0; i < arguments.size(); ++i)\n    {\n        double new_function_value = CountObjectiveFunctionValueToMinimize(new_arguments);\n        vector<double> temp(new_arguments);\n\n        temp[i] = new_arguments[i] + steps_array[i];\n        if (CountObjectiveFunctionValueToMinimize(temp) < new_function_value)\n        {\n            new_arguments = temp;\n            continue;\n        }\n\n        temp[i] = new_arguments[i] - steps_array[i];\n        if (CountObjectiveFunctionValueToMinimize(temp) < new_function_value)\n        {\n            new_arguments = temp;\n        }\n    }\n    return new_arguments;\n}\n\n}/* namespace optimization */\n}/* namespace k52 */", "meta": {"hexsha": "5d8b56262b033a2a40c5b2514164138658795adc", "size": 5237, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/optimization/hooke_jeeves_method.cpp", "max_stars_repo_name": "PavelKovalets/k52", "max_stars_repo_head_hexsha": "2d2c58cc4e3330e88a9cc6ae03d80749d04bcba7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2016-04-14T07:36:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-22T22:03:20.000Z", "max_issues_repo_path": "src/optimization/hooke_jeeves_method.cpp", "max_issues_repo_name": "PavelKovalets/k52", "max_issues_repo_head_hexsha": "2d2c58cc4e3330e88a9cc6ae03d80749d04bcba7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 29.0, "max_issues_repo_issues_event_min_datetime": "2016-04-05T08:49:05.000Z", "max_issues_repo_issues_event_max_datetime": "2016-10-29T07:09:00.000Z", "max_forks_repo_path": "src/optimization/hooke_jeeves_method.cpp", "max_forks_repo_name": "PavelKovalets/k52", "max_forks_repo_head_hexsha": "2d2c58cc4e3330e88a9cc6ae03d80749d04bcba7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2016-04-16T07:53:04.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-12T21:31:51.000Z", "avg_line_length": 31.3592814371, "max_line_length": 102, "alphanum_fraction": 0.6700400993, "num_tokens": 1170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154240079185318, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.4685274166348154}}
{"text": "#include \"gtest/gtest.h\"\n#include <string>\n#include <boost/algorithm/string.hpp>\n#include \"Graph.h\"\n\nTEST(graph_check, test_directed) {\n    //this adjancency matrix is directed\n    vector<vector<int>> am = {\n            {0, 1, 0, 0},\n            {1, 0, 1, 0},\n            {0, 1, 0, 1},\n            {0, 0, 1, 0}\n    };\n    Graph *g = new Graph(am);\n    EXPECT_EQ(g->isDirected(), false);\n\n}\n\nTEST(graph_check, test_not_directed) {\n    //this adjancency matrix is directed\n    vector<vector<int>> am = {\n            {0, 1, 0, 1},\n            {1, 0, 1, 0},\n            {0, 1, 0, 1},\n            {0, 0, 1, 0}\n    };\n    Graph *g = new Graph(am);\n    EXPECT_EQ(g->isDirected(), true);\n}\n\nTEST(graph_check, test_nr_edges_1) {\n    //this adjancency matrix is directed\n    vector<vector<int>> am = {\n            {0, 1, 0, 0},\n            {1, 0, 1, 0},\n            {0, 1, 0, 1},\n            {0, 0, 1, 0}\n    };\n    Graph *g = new Graph(am);\n    EXPECT_EQ(g->getNumberOfEdges(), 3);\n}\n\nTEST(graph_check, test_nr_edges_2) {\n    //this adjancency matrix is not directed\n    vector<vector<int>> am = {\n            {0, 1, 0, 1},\n            {1, 0, 1, 0},\n            {0, 1, 0, 1},\n            {0, 0, 1, 0}\n    };\n    Graph *g = new Graph(am);\n    EXPECT_EQ(g->getNumberOfEdges(), 7);\n}\n\nTEST(graph_check, test_has_cycle_1) {\n    //this adjancency matrix has a cycle\n    vector<vector<int>> am = {\n            {0, 1, 1, 0},\n            {1, 0, 1, 0},\n            {1, 1, 0, 0},\n            {0, 0, 0, 0}\n    };\n    Graph *g = new Graph(am);\n    EXPECT_EQ(g->hasCycle(), true);\n}\n\nTEST(graph_check, test_has_cycle_2) {\n    //this adjancency matrix has no cycle\n    vector<vector<int>> am = {\n            {0, 1, 0, 0},\n            {1, 0, 1, 0},\n            {0, 1, 0, 1},\n            {0, 0, 1, 0}\n    };\n    Graph *g = new Graph(am);\n    EXPECT_EQ(g->hasCycle(), true);\n}\n\nTEST(graph_check, test_nr_of_nodes) {\n    vector<vector<int>> am = {\n            {0, 1, 0, 0},\n            {1, 0, 1, 0},\n            {0, 1, 0, 1},\n            {0, 0, 1, 0}\n    };\n    Graph *g = new Graph(am);\n    EXPECT_EQ(g->getNumberOfNodes(), 4);\n}\n\nTEST(graph_check, test_regular_1) {\n    vector<vector<int>> am = {\n            {0, 1, 1},\n            {1, 0, 1},\n            {1, 1, 0},\n    };\n    Graph *g = new Graph(am);\n    EXPECT_EQ(g->isRegular(), true);\n}\n\nTEST(graph_check, test_regular_2) {\n    vector<vector<int>> am = {\n            {0, 1, 1, 0},\n            {1, 0, 1, 0},\n            {1, 1, 0, 0},\n            {1, 1, 0, 0},\n    };\n    Graph *g = new Graph(am);\n    EXPECT_EQ(g->isRegular(), false);\n}\n\n\nTEST(graph_check, test_complete_1) {\n    vector<vector<int>> am = {\n            {0, 1, 1},\n            {1, 0, 1},\n            {1, 1, 0},\n    };\n    Graph *g = new Graph(am);\n    EXPECT_EQ(g->isComplete(), true);\n}\n\nTEST(graph_check, test_complete_2) {\n    vector<vector<int>> am = {\n            {0, 1, 1, 0},\n            {1, 0, 1, 0},\n            {1, 1, 0, 0},\n            {1, 1, 0, 0},\n    };\n    Graph *g = new Graph(am);\n    EXPECT_EQ(g->isComplete(), false);\n}\n\nTEST(graph_check, test_indegree) {\n    vector<vector<int>> am = {\n            {0, 1, 1, 0},\n            {1, 0, 1, 0},\n            {1, 1, 0, 0},\n            {0, 0, 0, 0},\n    };\n    Graph *g = new Graph(am);\n    EXPECT_EQ(g->getInDeg(0), 2);\n    EXPECT_EQ(g->getInDeg(1), 2);\n    EXPECT_EQ(g->getInDeg(2), 2);\n    EXPECT_EQ(g->getInDeg(3), 0);\n}\n\nTEST(graph_check, test_outdegree) {\n    vector<vector<int>> am = {\n            {0, 1, 1, 0},\n            {1, 0, 1, 0},\n            {1, 1, 0, 0},\n            {0, 0, 0, 0},\n    };\n    Graph *g = new Graph(am);\n    EXPECT_EQ(g->getOutDeg(0), 2);\n    EXPECT_EQ(g->getOutDeg(1), 2);\n    EXPECT_EQ(g->getOutDeg(2), 2);\n    EXPECT_EQ(g->getOutDeg(3), 0);\n}\n\nTEST(graph_check, test_free_of_loops) {\n    vector<vector<int>> am = {\n            {0, 1, 1, 0},\n            {1, 0, 1, 0},\n            {1, 1, 0, 0},\n            {0, 0, 0, 0},\n    };\n    Graph *g = new Graph(am);\n    EXPECT_TRUE(g->isFreeOfLoops());\n}\n\nTEST(graph_check, test_free_of_loops_2) {\n    vector<vector<int>> am = {\n            {0, 1, 1, 0},\n            {1, 1, 1, 0},\n            {1, 1, 0, 0},\n            {0, 0, 0, 0},\n    };\n    Graph *g = new Graph(am);\n    EXPECT_FALSE(g->isFreeOfLoops());\n}\n\nTEST(graph_check, test_are_neighbours_1) {\n    vector<vector<int>> am = {\n            {0, 1, 1, 0},\n            {1, 1, 1, 0},\n            {1, 1, 0, 0},\n            {0, 0, 0, 0},\n    };\n    Graph *g = new Graph(am);\n    EXPECT_FALSE(g->areNeighbours(0, 0));\n    EXPECT_FALSE(g->areNeighbours(0, 3));\n    EXPECT_FALSE(g->areNeighbours(1, 3));\n    EXPECT_FALSE(g->areNeighbours(2, 2));\n    EXPECT_FALSE(g->areNeighbours(2, 3));\n    EXPECT_FALSE(g->areNeighbours(3, 0));\n    EXPECT_FALSE(g->areNeighbours(3, 1));\n    EXPECT_FALSE(g->areNeighbours(3, 2));\n    EXPECT_FALSE(g->areNeighbours(3, 3));\n\n    EXPECT_TRUE(g->areNeighbours(0, 1));\n    EXPECT_TRUE(g->areNeighbours(0, 2));\n    EXPECT_TRUE(g->areNeighbours(1, 0));\n    EXPECT_TRUE(g->areNeighbours(1, 1));\n    EXPECT_TRUE(g->areNeighbours(1, 2));\n    EXPECT_TRUE(g->areNeighbours(2, 0));\n    EXPECT_TRUE(g->areNeighbours(2, 1));\n}\n\nTEST(graph_check, test_are_neighbours_directed) {\n    vector<vector<int>> am = {\n            {0, 1, 1, 1},\n            {0, 0, 0, 0},\n            {0, 0, 0, 0},\n            {0, 0, 0, 0},\n    };\n    Graph *g = new Graph(am);\n    EXPECT_FALSE(g->areNeighbours(0, 0));\n    EXPECT_FALSE(g->areNeighbours(1, 0));\n    EXPECT_FALSE(g->areNeighbours(2, 0));\n    EXPECT_FALSE(g->areNeighbours(3, 0));\n\n    EXPECT_TRUE(g->areNeighbours(0, 1));\n    EXPECT_TRUE(g->areNeighbours(0, 2));\n    EXPECT_TRUE(g->areNeighbours(0, 3));\n}\n\nTEST(graph_check, test_are_neighbours_undirected) {\n    vector<vector<int>> am = {\n            {0, 1, 1, 1},\n            {1, 0, 0, 0},\n            {1, 0, 0, 0},\n            {1, 0, 0, 0},\n    };\n    Graph *g = new Graph(am);\n    EXPECT_TRUE(g->areNeighbours(1, 0));\n    EXPECT_TRUE(g->areNeighbours(2, 0));\n    EXPECT_TRUE(g->areNeighbours(3, 0));\n\n    EXPECT_TRUE(g->areNeighbours(0, 1));\n    EXPECT_TRUE(g->areNeighbours(0, 2));\n    EXPECT_TRUE(g->areNeighbours(0, 3));\n}\n\nTEST(graph_check, test_are_neighbours_range_1) {\n    vector<vector<int>> am = {\n            {0, 1, 1, 1},\n            {1, 0, 0, 0},\n            {1, 0, 0, 0},\n            {1, 0, 0, 0},\n    };\n    Graph *g = new Graph(am);\n\n    // throw out_of_range(\"from/to must be in [0, \" + getNumberOfNodes() + string(\"[.\"));\n    try {\n        g->areNeighbours(-1, 3);\n        FAIL();\n    } catch (const out_of_range &e) {\n        cout << e.what() << endl;\n        ASSERT_STREQ(\"from and to have to be in the range. \", e.what());\n    }\n}\n\nTEST(graph_check, test_are_neighbours_range_2) {\n    vector<vector<int>> am = {\n            {0, 1, 1, 1},\n            {1, 0, 0, 0},\n            {1, 0, 0, 0},\n            {1, 0, 0, 0},\n    };\n    Graph *g = new Graph(am);\n\n    // throw out_of_range(\"from/to must be in [0, \" + getNumberOfNodes() + string(\"[.\"));\n    try {\n        g->areNeighbours(2, -2);\n        FAIL();\n    } catch (const out_of_range &e) {\n        cout << e.what() << endl;\n        ASSERT_STREQ(\"from and to have to be in the range. \", e.what());\n    }\n}\n\nTEST(graph_check, test_are_neighbours_range_3) {\n    vector<vector<int>> am = {\n            {0, 1, 1, 1},\n            {1, 0, 0, 0},\n            {1, 0, 0, 0},\n            {1, 0, 0, 0},\n    };\n    Graph *g = new Graph(am);\n\n    // throw out_of_range(\"from/to must be in [0, \" + getNumberOfNodes() + string(\"[.\"));\n    try {\n        g->areNeighbours(0, 4);\n        FAIL();\n    } catch (const out_of_range &e) {\n        cout << e.what() << endl;\n        ASSERT_STREQ(\"from and to have to be in the range. \", e.what());\n    }\n}\n\nTEST(graph_check, test_are_neighbours_range_4) {\n    vector<vector<int>> am = {\n            {0, 1, 1, 1},\n            {1, 0, 0, 0},\n            {1, 0, 0, 0},\n            {1, 0, 0, 0},\n    };\n    Graph *g = new Graph(am);\n\n    // throw out_of_range(\"from/to must be in [0, \" + getNumberOfNodes() + string(\"[.\"));\n    try {\n        g->areNeighbours(4, 0);\n        FAIL();\n    } catch (const out_of_range &e) {\n        cout << e.what() << endl;\n        ASSERT_STREQ(\"from and to have to be in the range. \", e.what());\n    }\n}\n\n\nTEST(graph_check, test_matlab_correct_notation) {\n\n    try {\n        // These graphs should not cause an error.\n        Graph *a = new Graph(\"[1 0 1; 1 1 1; 0 0 1]\");\n        Graph *b = new Graph(\"  \\t [1 0  1;1 \\t\\t 1 1\\t\\t\\t    ;     0  0  1 ] \");\n        Graph *c = new Graph(\"[1\\t0\\t1;1\\t1\\t1;0\\t0\\t1]\");\n        Graph *d = new Graph(\" [ 1   0   1 ;   1   1   1 ;   0   0   1 ] \");\n        Graph *e = new Graph(\"[1]\");\n\n    } catch (const invalid_argument &e) {\n        cout << e.what();\n        FAIL();\n    }\n\n    SUCCEED();\n}\n\nTEST(graph_check, test_matlab_wrong_notation_1) {\n\n    try {\n        Graph *g = new Graph(\"[1 0 1; 1 1 1 1; 0 0 1]\"); // one column too much\n        FAIL();\n    } catch (const invalid_argument &e) {\n        ASSERT_STREQ(\"There must be a syntax error, because the number of columns are different.\", e.what());\n    }\n}\n\nTEST(graph_check, test_matlab_wrong_notation_2) {\n\n    try {\n        Graph *g = new Graph(\"[1 0 1 0; 1 1 1 1; 0 0 1 1]\"); // is not square\n        FAIL();\n    } catch (const invalid_argument &e) {\n        ASSERT_STREQ(\"adjacency matrix has to be symmetrical\", e.what());\n    }\n}\n\nTEST(graph_check, test_matlab_wrong_notation_3) {\n\n    try {\n        Graph *g = new Graph(\"[0 1 0; 1 1 1; 0 1 1; 1 1 1]\"); // is not square\n        FAIL();\n    } catch (const invalid_argument &e) {\n        ASSERT_STREQ(\"adjacency matrix has to be symmetrical\", e.what());\n    }\n\n}\n\nTEST(graph_check, test_matlab_wrong_notation_4) {\n\n    try {\n        Graph *g = new Graph(\"1 0 1; 1 1 1; 0 0 1\");\n        FAIL();\n    } catch (const invalid_argument &e) {\n        ASSERT_STREQ(\"A valid matlab matrix notation must start with '[' and end up with ']'.\", e.what());\n    }\n}\n\nTEST(graph_check, test_matlab_wrong_notation_5) {\n\n    try {\n        Graph *g = new Graph(\"[]\");\n        FAIL();\n    } catch (const invalid_argument &e) {\n        ASSERT_STREQ(\"matrix entries must be and contain at least one integer.\", e.what());\n    }\n}\n\n\nTEST(graph_check, test_matlab_wrong_notation_6) {\n\n    try {\n        Graph *g = new Graph(\"[ a ]\");\n        FAIL();\n    } catch (const invalid_argument &e) {\n        ASSERT_STREQ(\"matrix entries must be and contain at least one integer.\", e.what());\n    }\n}\n\nTEST(graph_check, test_constructor_names) {\n    vector<vector<int>> am = {\n            {0, 1, 1, 0},\n            {1, 0, 1, 0},\n            {1, 1, 0, 0},\n            {1, 1, 0, 0},\n    };\n    vector<string> nodes = {\"test\", \"node2\", \"node3\", \"node4\"};\n    Graph *g = new Graph(am, nodes);\n    string dot = g->exportDot();\n    cout << dot << endl;\n    EXPECT_NE(dot.find(\"test -> node2\"), string::npos);\n    EXPECT_NE(dot.find(\"test -> node3\"), string::npos);\n    EXPECT_NE(dot.find(\"node2 -> test\"), string::npos);\n    EXPECT_NE(dot.find(\"node2 -> node3\"), string::npos);\n    EXPECT_NE(dot.find(\"node3 -> test\"), string::npos);\n    EXPECT_NE(dot.find(\"node3 -> node2\"), string::npos);\n    EXPECT_NE(dot.find(\"node4 -> test\"), string::npos);\n    EXPECT_NE(dot.find(\"node4 -> node2\"), string::npos);\n}\n\nTEST(graph_check, test_adjazenzmatrix_string) {\n    Graph *g = new Graph(\"[1 0 1; 1 1 1; 0 0 1]\");\n    string mat = g->getAdjacencyMatrixString();\n\n    std::vector<std::string> strs;\n    boost::split(strs, mat, boost::is_any_of(\"\\n\"));\n\n    ASSERT_EQ(strs[0], \"1,0,1\");\n    ASSERT_EQ(strs[1], \"1,1,1\");\n    ASSERT_EQ(strs[2], \"0,0,1\");\n}\n\nTEST(graph_check, test_forest_true) {\n    Graph *g = new Graph(\"[0 1 1; 0 0 0; 0 0 0]\");\n    bool forest = g->isForest();\n\n    ASSERT_TRUE(forest);\n}\n\nTEST(graph_check, test_forest_false) {\n    //cycle -> false\n    Graph *g = new Graph(\"[0 1 1; 0 0 0; 1 0 0]\");\n    bool forest = g->isForest();\n\n    ASSERT_FALSE(forest);\n}\n\nTEST(graph_check, test_forest_undirected) {\n    //undirected -> false\n    Graph *g = new Graph(\"[0 1 1; 1 0 0; 1 0 0]\");\n    bool forest = g->isForest();\n\n    ASSERT_FALSE(forest);\n}", "meta": {"hexsha": "3877508706bf0db6ce845a5503cbb0060cca61bc", "size": 12074, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/main.cpp", "max_stars_repo_name": "089/blatt-2-amf0", "max_stars_repo_head_hexsha": "c6da0f816a80c8b3eaedf9230b0476433ea7b2c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-04-03T13:19:19.000Z", "max_stars_repo_stars_event_max_datetime": "2017-04-03T13:19:19.000Z", "max_issues_repo_path": "test/main.cpp", "max_issues_repo_name": "089/Graphs", "max_issues_repo_head_hexsha": "c6da0f816a80c8b3eaedf9230b0476433ea7b2c4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 46.0, "max_issues_repo_issues_event_min_datetime": "2017-04-26T18:07:59.000Z", "max_issues_repo_issues_event_max_datetime": "2017-07-07T12:53:21.000Z", "max_forks_repo_path": "test/main.cpp", "max_forks_repo_name": "089/Graphs", "max_forks_repo_head_hexsha": "c6da0f816a80c8b3eaedf9230b0476433ea7b2c4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-06-27T14:42:54.000Z", "max_forks_repo_forks_event_max_datetime": "2017-06-27T14:42:54.000Z", "avg_line_length": 26.4780701754, "max_line_length": 109, "alphanum_fraction": 0.5107669372, "num_tokens": 4101, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834732, "lm_q2_score": 0.6548947357776796, "lm_q1q2_score": 0.46852740868762943}}
{"text": "/**\n * @file mesh.cc\n * @brief NPDE homework ElementMatrixComputation code\n * @author Janik Sch\u00fcttler, edited by Oliver Rietmann\n * @date 03.03.2019\n * @copyright Developed at ETH Zurich\n */\n\n#include \"mesh.h\"\n\n#include <lf/base/base.h>\n#include <lf/geometry/geometry.h>\n#include <lf/mesh/hybrid2d/hybrid2d.h>\n\n#include <Eigen/Core>\n#include <array>\n#include <memory>\n\nstd::shared_ptr<lf::mesh::Mesh> Generate2DTestMesh() {\n  using size_type = lf::mesh::Mesh::size_type;\n\n  // Obtain mesh factory\n  std::shared_ptr<lf::mesh::hybrid2d::MeshFactory> mesh_factory_ptr =\n      std::make_shared<lf::mesh::hybrid2d::MeshFactory>(2);\n\n  double scale = 1.0;\n\n  // Hybrid mesh of square [0,3]^2 with only triangles and rectangles\n  // Set coordinates of nodes\n  // clang-format off\n  std::array<std::array<double, 2>, 10> node_coord{\n      std::array<double, 2>({0, 0 }),\n      std::array<double, 2>({1, 0 }),\n      std::array<double, 2>({2, 0 }),\n      std::array<double, 2>({3, 0 }),\n      std::array<double, 2>({0 ,2 }),\n      std::array<double, 2>({1 ,2 }),\n      std::array<double, 2>({3 ,2 }),\n      std::array<double, 2>({0 ,3 }),\n      std::array<double, 2>({1 ,3 }),\n      std::array<double, 2>({3 ,3 })};\n  // clang-format on\n\n  // Specify triangles (five)\n  std::array<std::array<size_type, 3>, 5> tria_nodes{\n      std::array<size_type, 3>({1, 2, 5}), std::array<size_type, 3>({2, 3, 6}),\n      std::array<size_type, 3>({5, 2, 6}), std::array<size_type, 3>({4, 5, 7}),\n      std::array<size_type, 3>({5, 8, 7})};\n\n  // Specify parallelograms (two)\n  std::array<std::array<size_type, 4>, 2> parg_nodes{\n      std::array<size_type, 4>({0, 1, 5, 4}),\n      std::array<size_type, 4>({5, 6, 9, 8})};\n\n  // Create nodes\n  for (const auto &node : node_coord) {\n    mesh_factory_ptr->AddPoint(\n        Eigen::Vector2d({node[0] * scale, node[1] * scale}));\n  }\n\n  // generate triangles\n  for (const auto &node : tria_nodes) {\n    mesh_factory_ptr->AddEntity(\n        lf::base::RefEl::kTria(),\n        nonstd::span<const size_type>({node[0], node[1], node[2]}),\n        std::unique_ptr<lf::geometry::Geometry>(nullptr));\n  }\n\n  // generate Parallelograms\n  for (const auto &node : parg_nodes) {\n    Eigen::MatrixXd quad_coord(2, 4);\n    for (int n_pt = 0; n_pt < 4; ++n_pt) {\n      quad_coord(0, n_pt) = node_coord[node[n_pt]][0];\n      quad_coord(1, n_pt) = node_coord[node[n_pt]][1];\n    }\n    mesh_factory_ptr->AddEntity(\n        lf::base::RefEl::kQuad(),\n        nonstd::span<const size_type>({node[0], node[1], node[2], node[3]}),\n        std::make_unique<lf::geometry::Parallelogram>(quad_coord));\n  }\n\n  // Optional: Inspect data\n  // mesh_factory_ptr->PrintLists(std::cout);\n  return mesh_factory_ptr->Build();\n}\n", "meta": {"hexsha": "7dffe82101c516e39149e35001b2063e98074d0d", "size": 2714, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/ElementMatrixComputation/meshes/mesh.cc", "max_stars_repo_name": "kryo4096/NPDECODES", "max_stars_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/ElementMatrixComputation/meshes/mesh.cc", "max_issues_repo_name": "kryo4096/NPDECODES", "max_issues_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/ElementMatrixComputation/meshes/mesh.cc", "max_forks_repo_name": "kryo4096/NPDECODES", "max_forks_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 31.5581395349, "max_line_length": 79, "alphanum_fraction": 0.6120117907, "num_tokens": 882, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239836484143, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.4685274007404432}}
{"text": "// -----------------------------------------------------------------------------\n// Fern \u00a9 Geoneric\n//\n// This file is part of Geoneric Fern which is available under the terms of\n// the GNU General Public License (GPL), version 2. If you do not want to\n// be bound by the terms of the GPL, you may purchase a proprietary license\n// from Geoneric (http://www.geoneric.eu/contact).\n// -----------------------------------------------------------------------------\n#define BOOST_TEST_MODULE fern algorithm trigonometry sin\n#include <boost/test/unit_test.hpp>\n#include \"fern/core/data_customization_point/scalar.h\"\n#include \"fern/core/type_traits.h\"\n#include \"fern/algorithm/trigonometry/sin.h\"\n\n\nnamespace fa = fern::algorithm;\n\n\ntemplate<\n    class Value>\nusing OutOfDomainPolicy = fa::sin::OutOfDomainPolicy<Value>;\n\n\nBOOST_AUTO_TEST_CASE(out_of_domain_policy)\n{\n    {\n        OutOfDomainPolicy<double> policy;\n        BOOST_CHECK(policy.within_domain(5));\n        BOOST_CHECK(policy.within_domain(-5));\n        BOOST_CHECK(policy.within_domain(0));\n        BOOST_CHECK(!policy.within_domain(fern::infinity<double>()));\n        BOOST_CHECK(!policy.within_domain(-fern::infinity<double>()));\n    }\n}\n\n\ntemplate<\n    class Value,\n    class Result>\nvoid verify_value(\n    Value const& value,\n    Result const& result_we_want)\n{\n    fa::SequentialExecutionPolicy sequential;\n\n    Result result_we_get;\n    fa::trigonometry::sin(sequential, value, result_we_get);\n    BOOST_CHECK_CLOSE(1.0 + result_we_get, 1.0 + result_we_want, 1e-10);\n}\n\n\nBOOST_AUTO_TEST_CASE(algorithm)\n{\n    verify_value<double, double>(0.0, 0.0);\n    verify_value<double, double>(-0.0, -0.0);\n    verify_value<double, double>(fern::half_pi<double>(), 1.0);\n    verify_value<double, double>(fern::pi<double>(), 0.0);\n    verify_value<double, double>(-fern::half_pi<double>(), -1.0);\n    verify_value<double, double>(-fern::pi<double>(), 0.0);\n}\n", "meta": {"hexsha": "f5169eaae834ee9f03a8bf2432885f8639054b70", "size": 1909, "ext": "cc", "lang": "C++", "max_stars_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/fern/source/fern/algorithm/trigonometry/test/sin_test.cc", "max_stars_repo_name": "quanpands/wflow", "max_stars_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/fern/source/fern/algorithm/trigonometry/test/sin_test.cc", "max_issues_repo_name": "quanpands/wflow", "max_issues_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/fern/source/fern/algorithm/trigonometry/test/sin_test.cc", "max_forks_repo_name": "quanpands/wflow", "max_forks_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.2950819672, "max_line_length": 80, "alphanum_fraction": 0.6495547407, "num_tokens": 451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.6548947223065754, "lm_q1q2_score": 0.4685273990500783}}
{"text": "//---------------------------------------------------------------------------\n//    $Id: compressed_block_sparsity_pattern.cc 28377 2013-02-13 15:22:32Z heister $\n//\n//    Copyright (C) 2006-2007 by the deal.II authors\n//\n//    This file is subject to QPL and may not be  distributed\n//    without copyright and license information. Please refer\n//    to the file deal.II/doc/license.html for the  text  and\n//    further information on this license.\n//\n//---------------------------------------------------------------------------\n\n// See documentation of BlockCompressedSparsityPattern for documentation of this example\n\n#include <deal.II/lac/block_sparsity_pattern.h>\n#include <deal.II/lac/constraint_matrix.h>\n#include <deal.II/grid/tria.h>\n#include <deal.II/grid/tria_accessor.h>\n#include <deal.II/grid/tria_iterator.h>\n#include <deal.II/grid/grid_generator.h>\n#include <deal.II/fe/fe_q.h>\n#include <deal.II/fe/fe_system.h>\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 <iostream>\n\nusing namespace dealii;\n\nint main()\n{\n  Triangulation<2> tr;\n  GridGenerator::subdivided_hyper_cube(tr, 3);\n  tr.begin_active()->set_refine_flag();\n  tr.execute_coarsening_and_refinement();\n\n  FE_Q<2> fe1(1);\n  FE_Q<2> fe2(2);\n  FESystem<2> fe(fe1, 2, fe2, 1);\n\n  DoFHandler<2> dof(tr);\n  dof.distribute_dofs(fe);\n  DoFRenumbering::Cuthill_McKee(dof);\n  DoFRenumbering::component_wise(dof);\n\n  ConstraintMatrix constraints;\n  DoFTools::make_hanging_node_constraints(dof, constraints);\n  constraints.close();\n\n  std::vector<unsigned int> dofs_per_block(fe.n_blocks());\n  DoFTools::count_dofs_per_block(dof, dofs_per_block);\n\n  BlockCompressedSparsityPattern c_sparsity(fe.n_blocks(), fe.n_blocks());\n  for (unsigned int i=0; i<fe.n_blocks(); ++i)\n    for (unsigned int j=0; j<fe.n_blocks(); ++j)\n      c_sparsity.block(i,j).reinit(dofs_per_block[i],dofs_per_block[j]);\n  c_sparsity.collect_sizes();\n\n  DoFTools::make_sparsity_pattern(dof, c_sparsity);\n  constraints.condense(c_sparsity);\n\n  BlockSparsityPattern sparsity;\n  sparsity.copy_from(c_sparsity);\n\n  unsigned int ig = 0;\n  for (unsigned int ib=0; ib<fe.n_blocks(); ++ib)\n    for (unsigned int i=0; i<dofs_per_block[ib]; ++i,++ig)\n      {\n        unsigned int jg = 0;\n        for (unsigned int jb=0; jb<fe.n_blocks(); ++jb)\n          for (unsigned int j=0; j<dofs_per_block[jb]; ++j,++jg)\n            {\n              if (sparsity.exists(ig,jg))\n                std::cout << ig << ' ' << jg\n                          << '\\t' << ib << jb << std::endl;\n            }\n      }\n}\n", "meta": {"hexsha": "162a09df59002bbc8090b93900955fba08663f2c", "size": 2598, "ext": "cc", "lang": "C++", "max_stars_repo_path": "MHD/examples/doxygen/compressed_block_sparsity_pattern.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/doxygen/compressed_block_sparsity_pattern.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/doxygen/compressed_block_sparsity_pattern.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": 32.475, "max_line_length": 88, "alphanum_fraction": 0.6404926867, "num_tokens": 727, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239836484144, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.46852739592166787}}
{"text": "#include <math.h>\n\n#include <boost/foreach.hpp>\n\n#include <ros/ros.h>\n\n// #include <tf/transform_datatypes.h>\n#include <eigen_conversions/eigen_msg.h>\n\n#include <pcl_ros/point_cloud.h>\n\n#include <pcl/common/common.h>\n#include <pcl/point_cloud.h>\n#include <pcl/ModelCoefficients.h>\n#include <pcl/point_types.h>\n#include <pcl/io/pcd_io.h>\n#include <pcl/filters/extract_indices.h>\n#include <pcl/filters/voxel_grid.h>\n#include <pcl/filters/passthrough.h>\n#include <pcl/features/normal_3d.h>\n#include <pcl/kdtree/kdtree.h>\n#include <pcl/sample_consensus/method_types.h>\n#include <pcl/sample_consensus/model_types.h>\n#include <pcl/segmentation/sac_segmentation.h>\n#include <pcl/segmentation/extract_clusters.h>\n#include <pcl/segmentation/extract_polygonal_prism_data.h>\n#include <pcl/surface/concave_hull.h>\n#include <pcl/pcl_config.h>\n\n#include \"sensor_msgs/JointState.h\"\n#include \"geometry_msgs/Pose.h\"\n#include \"geometry_msgs/Vector3.h\"\n#include \"geometry_msgs/PointStamped.h\"\n#include \"visualization_msgs/Marker.h\"\n#include \"simple_grasping/shape_extraction.h\"\n#include \"shape_msgs/SolidPrimitive.h\"\n\n#include <fetch_delivery_system/BoxTarget.h>\n\ntypedef pcl::PointCloud<pcl::PointXYZ> PointCloud;\n\n// not good practice, might want to get rid of globals in future\nros::Publisher pub_object;\nros::Publisher pub_plane;\nros::Publisher box_marker;\nros::Publisher box_pose_pub;\nros::Publisher box_target;\nros::Publisher plane_centroid;\ndouble head_tilt = 0;\n\nvoid update_head_angle(const sensor_msgs::JointStateConstPtr &msg)\n{\n  // get the head tilt angle not sure if the index is fixed?\n  head_tilt = msg->position[5];\n}\n\nvoid callback(const PointCloud::ConstPtr &cloud)\n{\n  pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_filtered(new pcl::PointCloud<pcl::PointXYZ>);\n\n  // filtering\n  pcl::PassThrough<pcl::PointXYZ> pass;\n  pass.setInputCloud(cloud);\n  pass.setFilterFieldName(\"z\");\n  pass.setFilterLimits(0.0, 1.5);\n  //pass.setFilterLimitsNegative (true);\n  pass.filter(*cloud_filtered);\n\n  // Plane extraction\n  pcl::ModelCoefficients::Ptr coefficients(new pcl::ModelCoefficients);\n  pcl::PointIndices::Ptr inliers(new pcl::PointIndices);\n  // Create the segmentation object\n  pcl::SACSegmentation<pcl::PointXYZ> seg;\n  // seg.setOptimizeCoefficients (true); // optional, refines estimated plane coeffecients, takes more time\n  // Mandatory\n  seg.setModelType(pcl::SACMODEL_PERPENDICULAR_PLANE);\n  seg.setMethodType(pcl::SAC_RANSAC);\n  seg.setDistanceThreshold(0.02);\n  double y = 1.0 * cos(head_tilt);\n  double z = 1.0 * sin(head_tilt);\n  Eigen::Vector3f axis = Eigen::Vector3f(0.0, y, z);\n  seg.setAxis(axis);\n  seg.setEpsAngle(5.0 * (M_PI / 180.0));\n\n  seg.setInputCloud(cloud_filtered);\n  seg.segment(*inliers, *coefficients);\n\n  if (inliers->indices.size() == 0)\n  {\n    PCL_ERROR(\"Could not estimate a planar model for the given dataset.\");\n    return;\n  }\n\n  std::cerr << \"Model inliers: \" << inliers->indices.size() << std::endl;\n\n  pcl::PointCloud<pcl::PointXYZ>::Ptr plane_cloud(new pcl::PointCloud<pcl::PointXYZ>);\n\n  pcl::copyPointCloud(*cloud_filtered, *inliers, *plane_cloud);\n\n  std::cout << \"PointCloud representing the Cluster: \" << plane_cloud->size() << \" data points.\" << std::endl;\n\n  // publish the plane cloud as a ROS message\n  sensor_msgs::PointCloud2 plane_output;\n  pcl::toROSMsg(*plane_cloud, plane_output);\n  plane_output.header.frame_id = \"head_camera_rgb_optical_frame\";\n  pub_plane.publish(plane_output);\n\n  // find the centroid of the plane\n  Eigen::Vector4d plane_centroid4;\n  Eigen::Vector3d plane_centroid3;\n  geometry_msgs::PointStamped plane_point_stamped;\n  pcl::compute3DCentroid(*plane_cloud, plane_centroid4);\n  plane_centroid3 = plane_centroid4.head<3>();\n  tf::pointEigenToMsg(plane_centroid3, plane_point_stamped.point);\n  plane_point_stamped.header.frame_id = \"head_camera_rgb_optical_frame\";\n  // publish centroid of plane\n  plane_centroid.publish(plane_point_stamped);\n\n  // Segment object\n  pcl::PointIndices::Ptr object_indices(new pcl::PointIndices);\n  double z_min = 0.05, z_max = 0.5; // we want the points above the plane, between 5 cm and 50 cm from the surface\n  pcl::PointCloud<pcl::PointXYZ>::Ptr hull_points(new pcl::PointCloud<pcl::PointXYZ>());\n  pcl::ConvexHull<pcl::PointXYZ> hull;\n  // hull.setDimension (2); // not necessarily needed, but we need to check the dimensionality of the output\n  hull.setInputCloud(plane_cloud);\n  hull.reconstruct(*hull_points);\n  if (hull.getDimension() == 2)\n  {\n    pcl::ExtractPolygonalPrismData<pcl::PointXYZ> prism;\n    prism.setInputCloud(cloud_filtered);\n    prism.setInputPlanarHull(hull_points);\n    prism.setHeightLimits(z_min, z_max);\n    prism.segment(*object_indices);\n  }\n  else\n  {\n    PCL_ERROR(\"The input cloud does not represent a planar surface.\\n\");\n  }\n\n\n  // a point cloud of possible objects\n  pcl::PointCloud<pcl::PointXYZ>::Ptr object_cloud(new pcl::PointCloud<pcl::PointXYZ>);\n\n  pcl::copyPointCloud(*cloud_filtered, *object_indices, *object_cloud);\n\n  std::cout << \"Object cloud: \" << object_cloud->size() << \" data points.\" << std::endl;\n\n  if (object_cloud->size() == 0)\n  {\n    return;\n  }\n\n  // Clustering\n  // find the clusters\n  std::vector<pcl::PointIndices> cluster_indices;\n  pcl::EuclideanClusterExtraction<pcl::PointXYZ> euclid;\n  euclid.setInputCloud(object_cloud);\n  euclid.setClusterTolerance(0.02);\n  euclid.setMinClusterSize(100);\n  euclid.setMaxClusterSize(25000);\n  euclid.extract(cluster_indices);\n\n  // find the closest cluster\n  pcl::PointCloud<pcl::PointXYZ>::Ptr nearest_cluster_cloud(new pcl::PointCloud<pcl::PointXYZ>);\n  double shortest_distance = INFINITY;\n  double current_distance;\n  Eigen::Vector4d centroid4;\n  Eigen::Vector3d centroid3;\n  pcl::PointIndices nearest_cluster_indices;\n  for (pcl::PointIndices it : cluster_indices)\n  {\n    // find centroid of cluster\n    pcl::compute3DCentroid(*object_cloud, it, centroid4);\n    // std::cerr << \"centroid: \" << centroid4 << std::endl;\n    // compute distance from centroid to head camera\n    centroid3 = centroid4.head<3>();\n    current_distance = centroid3.norm();\n    if (current_distance < shortest_distance)\n    {\n      // reset shortest distance\n      shortest_distance = current_distance;\n      // store nearest cluster indicies\n      nearest_cluster_indices = it;\n    }\n    \n  }\n  if (nearest_cluster_indices.indices.size() == 0)\n  {\n    return;\n  }\n  else\n  {\n    // create nearest cluster cloud\n    pcl::copyPointCloud(*object_cloud, nearest_cluster_indices, *nearest_cluster_cloud);\n    std::cerr << \"distance: \" << shortest_distance << std::endl;\n  }\n\n  sensor_msgs::PointCloud2 object_output;\n  pcl::toROSMsg(*nearest_cluster_cloud, object_output);\n  object_output.header.frame_id = \"head_camera_rgb_optical_frame\";\n  pub_object.publish(object_output);\n\n  // Bounding box\n  pcl::PointCloud<pcl::PointXYZRGB> object_cloud_xyzrgb;\n  pcl::copyPointCloud(*nearest_cluster_cloud, object_cloud_xyzrgb);\n  pcl::PointCloud<pcl::PointXYZRGB>::Ptr extract_out(new pcl::PointCloud<pcl::PointXYZRGB>);\n  shape_msgs::SolidPrimitive shape;\n  geometry_msgs::Pose box_pose;\n  // for(auto myc : coefficients->values)\n  // {\n  //   std::cout << myc << \", \";\n  // }\n  // std::cout << std::endl;\n\n  // very bad code\n  // fixing the normal vector of the plane segmentation\n  if (coefficients->values[3] < 0)\n  {\n    coefficients->values[0] = -coefficients->values[0];\n    coefficients->values[1] = -coefficients->values[1];\n    coefficients->values[2] = -coefficients->values[2];\n    coefficients->values[3] = -coefficients->values[3];\n  }\n\n  simple_grasping::extractShape(object_cloud_xyzrgb, coefficients, *extract_out, shape,\n                                box_pose);\n\n  if (shape.type == shape_msgs::SolidPrimitive::BOX)\n  {\n    pcl::PointXYZRGB min;\n    pcl::PointXYZRGB max;\n    pcl::getMinMax3D<pcl::PointXYZRGB>(*extract_out, min, max);\n\n    visualization_msgs::Marker object_marker;\n    object_marker.ns = \"objects\";\n    object_marker.id = 0;\n    object_marker.header.frame_id = \"head_camera_rgb_optical_frame\";\n    object_marker.type = visualization_msgs::Marker::CUBE;\n    object_marker.color.g = 1;\n    object_marker.color.a = 0.3;\n\n    object_marker.pose = box_pose;\n\n    object_marker.scale.x = shape.dimensions[0];\n    object_marker.scale.y = shape.dimensions[1];\n    object_marker.scale.z = shape.dimensions[2];\n    box_marker.publish(object_marker);\n    box_pose_pub.publish(box_pose);\n    fetch_delivery_system::BoxTarget box_target_msg;\n    box_target_msg.box_scale = object_marker;\n    box_target_msg.box_pose = box_pose;\n    box_target.publish(box_target_msg);\n  }\n}\n\nint main(int argc, char **argv)\n{\n  ros::init(argc, argv, \"sub_pcl\");\n  ros::NodeHandle nh;\n  pub_object = nh.advertise<PointCloud>(\"points2_object\", 1);\n  pub_plane = nh.advertise<PointCloud>(\"points2_plane\", 1);\n  box_marker = nh.advertise<visualization_msgs::Marker>(\"box_marker\", 1);\n  box_pose_pub = nh.advertise<geometry_msgs::Pose>(\"box_target_pose\", 1);\n  box_target = nh.advertise<fetch_delivery_system::BoxTarget>(\"box_target\", 1);\n  plane_centroid = nh.advertise<geometry_msgs::PointStamped>(\"plane_centroid\", 1);\n  ros::Subscriber sub = nh.subscribe<PointCloud>(\"/head_camera/depth_downsample/points\", 1, callback);\n  ros::Subscriber joint_sub = nh.subscribe<sensor_msgs::JointState>(\"joint_states\", 1, update_head_angle);\n  ros::spin();\n}", "meta": {"hexsha": "548b5552e734c8a279f80c1e6ff195ec797d10f6", "size": 9329, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/segment_object.cpp", "max_stars_repo_name": "GIX-C4RT/fetch-delivery-system", "max_stars_repo_head_hexsha": "812beb1c5981a40d5e86b8cb8c35b5a729e3df7e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/segment_object.cpp", "max_issues_repo_name": "GIX-C4RT/fetch-delivery-system", "max_issues_repo_head_hexsha": "812beb1c5981a40d5e86b8cb8c35b5a729e3df7e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/segment_object.cpp", "max_forks_repo_name": "GIX-C4RT/fetch-delivery-system", "max_forks_repo_head_hexsha": "812beb1c5981a40d5e86b8cb8c35b5a729e3df7e", "max_forks_repo_licenses": ["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.6802973978, "max_line_length": 114, "alphanum_fraction": 0.7307321256, "num_tokens": 2399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891479496523, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.46852666592305603}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2015 NumScale SAS\n  @copyright 2015 J.T.Lapreste\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_COMMON_DETAIL_SCALAR_F_TRIG_EVALUATION_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_DETAIL_SCALAR_F_TRIG_EVALUATION_HPP_INCLUDED\n\n#include <boost/simd/function/horn.hpp>\n#include <boost/simd/constant/mhalf.hpp>\n#include <boost/simd/function/scalar/fma.hpp>\n#include <boost/simd/function/scalar/oneplus.hpp>\n#include <boost/simd/function/scalar/rec.hpp>\n#include <boost/simd/function/scalar/sqr.hpp>\n#include <boost/dispatch/meta/scalar_of.hpp>\n\nnamespace boost { namespace simd\n{\n  namespace detail\n  {\n    namespace bd =  boost::dispatch;\n    namespace bs =  boost::simd;\n\n    template < class A0,\n               class style,\n               class base_A0 = bd::scalar_of_t<A0>\n             >\n    struct trig_evaluation {};\n\n    // This class exposes the public static members:\n    // sin_eval\n    // cos_eval\n    // tan_eval\n    // which evaluate a polynomial approximation of each standard trigonometric\n    // functions in the range [pi/4, -pi/4]\n\n\n    template < class A0> struct trig_evaluation < A0,  tag::not_simd_type, float>\n    {\n      static BOOST_FORCEINLINE A0 cos_eval(A0 z) BOOST_NOEXCEPT\n      {\n        const A0 y = horn<A0\n          , 0x3d2aaaa5\n          , 0xbab60619\n          , 0x37ccf5ce\n          > (z);\n        return oneplus( fma(z,Mhalf<A0>(), y* sqr(z)));\n      }\n\n      static BOOST_FORCEINLINE A0 sin_eval(A0 z, A0 x) BOOST_NOEXCEPT\n      {\n        const A0 y1 = horn<A0\n          , 0xbe2aaaa2\n          , 0x3c08839d\n          , 0xb94ca1f9\n          > (z);\n        return fma(y1*z,x,x);\n      }\n\n      static BOOST_FORCEINLINE A0 base_tan_eval(A0 z) BOOST_NOEXCEPT\n      {\n        const A0 zz = sqr(z);\n        A0 y = horn<A0,\n          0x3eaaaa6f,\n          0x3e0896dd,\n          0x3d5ac5c9,\n          0x3cc821b5,\n          0x3b4c779c,\n          0x3c19c53b\n          >(zz)*zz*z+z;\n        return y;\n      }\n\n      static BOOST_FORCEINLINE A0 tan_eval(A0 z, const int n) BOOST_NOEXCEPT\n      {\n        const A0 y = base_tan_eval(z);\n        if (n == 1) return y;  else return -rec(y);\n      }\n      static BOOST_FORCEINLINE A0 cot_eval(A0 z, const int n) BOOST_NOEXCEPT\n      {\n        const A0 y = base_tan_eval(z);\n        if (n == 1) return rec(y);  else return -y;\n      }\n    };\n  }\n} }\n#endif\n", "meta": {"hexsha": "aa1c7117ef1be57e135e2ac6e3069ca2dde708af", "size": 2674, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arch/common/detail/scalar/f_trig_evaluation.hpp", "max_stars_repo_name": "yaeldarmon/boost.simd", "max_stars_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/simd/arch/common/detail/scalar/f_trig_evaluation.hpp", "max_issues_repo_name": "yaeldarmon/boost.simd", "max_issues_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/arch/common/detail/scalar/f_trig_evaluation.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": 28.4468085106, "max_line_length": 100, "alphanum_fraction": 0.5710545999, "num_tokens": 736, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.46852666095744505}}
{"text": "/* ----------------------------------------------------------------------\n *\n *                    *** Smooth Mach Dynamics ***\n *\n * This file is part of the USER-SMD package for LAMMPS.\n * Copyright (2014) Georg C. Ganzenmueller, georg.ganzenmueller@emi.fhg.de\n * Fraunhofer Ernst-Mach Institute for High-Speed Dynamics, EMI,\n * Eckerstrasse 4, D-79104 Freiburg i.Br, Germany.\n *\n * ----------------------------------------------------------------------- */\n\n/* ----------------------------------------------------------------------\n LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator\n http://lammps.sandia.gov, Sandia National Laboratories\n Steve Plimpton, sjplimp@sandia.gov\n\n Copyright (2003) Sandia Corporation.  Under the terms of Contract\n DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains\n certain rights in this software.  This software is distributed under\n the GNU General Public License.\n\n See the README file in the top-level LAMMPS directory.\n ------------------------------------------------------------------------- */\n#include <iostream>\n#include \"math_special.h\"\n#include <stdio.h>\n\n#include <Eigen/Eigen>\n\nusing namespace LAMMPS_NS::MathSpecial;\nusing namespace std;\nusing namespace Eigen;\n\n#define MIN(A,B) ((A) < (B) ? (A) : (B))\n#define MAX(A,B) ((A) > (B) ? (A) : (B))\n\n/* ----------------------------------------------------------------------\n linear EOS for use with linear elasticity\n input: initial pressure pInitial, isotropic part of the strain rate d, time-step dt\n output: final pressure pFinal, pressure rate p_rate\n ------------------------------------------------------------------------- */\nvoid LinearEOS(double lambda, double pInitial, double d, double dt, double &pFinal, double &p_rate) {\n\n\t/*\n\t * pressure rate\n\t */\n\tp_rate = lambda * d;\n\n\tpFinal = pInitial + dt * p_rate; // increment pressure using pressure rate\n\t//cout << \"hurz\" << endl;\n\n}\n\n/* ----------------------------------------------------------------------\n shock EOS\n input:\n current density rho\n reference density rho0\n current energy density e\n reference energy density e0\n reference speed of sound c0\n shock Hugoniot parameter S\n Grueneisen parameter Gamma\n initial pressure pInitial\n time step dt\n\n output:\n pressure rate p_rate\n final pressure pFinal\n\n ------------------------------------------------------------------------- */\nvoid ShockEOS(double rho, double rho0, double e, double e0, double c0, double S, double Gamma, double pInitial, double dt,\n\t\tdouble &pFinal, double &p_rate) {\n\n\tdouble mu = rho / rho0 - 1.0;\n\tdouble pH = rho0 * square(c0) * mu * (1.0 + mu) / square(1.0 - (S - 1.0) * mu);\n\n\tpFinal = (pH + rho * Gamma * (e - e0));\n\n\t//printf(\"shock EOS: rho = %g, rho0 = %g, Gamma=%f, c0=%f, S=%f, e=%f, e0=%f\\n\", rho, rho0, Gamma, c0, S, e, e0);\n\t//printf(\"pFinal = %f\\n\", pFinal);\n\tp_rate = (pFinal - pInitial) / dt;\n\n}\n\n/* ----------------------------------------------------------------------\n polynomial EOS\n input:\n current density rho\n reference density rho0\n coefficients 0 .. 6\n initial pressure pInitial\n time step dt\n\n output:\n pressure rate p_rate\n final pressure pFinal\n\n ------------------------------------------------------------------------- */\nvoid polynomialEOS(double rho, double rho0, double e, double C0, double C1, double C2, double C3, double C4, double C5, double C6,\n\t\tdouble pInitial, double dt, double &pFinal, double &p_rate) {\n\n\tdouble mu = rho / rho0 - 1.0;\n\n\tif (mu > 0.0) {\n\t\tpFinal = C0 + C1 * mu + C2 * mu * mu + C3 * mu * mu * mu; // + (C4 + C5 * mu + C6 * mu * mu) * e;\n\t} else {\n\t\tpFinal = C0 + C1 * mu + C3 * mu * mu * mu; //  + (C4 + C5 * mu) * e;\n\t}\n\tpFinal = -pFinal; // we want the mean stress, not the pressure.\n\n\n\t//printf(\"pFinal = %f\\n\", pFinal);\n\tp_rate = (pFinal - pInitial) / dt;\n\n}\n\n/* ----------------------------------------------------------------------\n Tait EOS based on current density vs. reference density.\n\n input: (1) reference sound speed\n (2) equilibrium mass density\n (3) current mass density\n\n output:(1) pressure\n (2) current speed of sound\n ------------------------------------------------------------------------- */\nvoid TaitEOS_density(const double exponent, const double c0_reference, const double rho_reference, const double rho_current,\n\t\tdouble &pressure, double &sound_speed) {\n\n\tdouble B = rho_reference * c0_reference * c0_reference / exponent;\n\tdouble tmp = pow(rho_current / rho_reference, exponent);\n\tpressure = B * (tmp - 1.0);\n\tdouble bulk_modulus = B * tmp * exponent; // computed as rho * d(pressure)/d(rho)\n\tsound_speed = sqrt(bulk_modulus / rho_current);\n\n//\tif (fabs(pressure) > 0.01) {\n//\t\tprintf(\"tmp = %f, press=%f, K=%f\\n\", tmp, pressure, bulk_modulus);\n//\t}\n\n}\n\n/* ----------------------------------------------------------------------\n perfect gas EOS\n input: gamma -- adiabatic index (ratio of specific heats)\n J -- determinant of deformation gradient\n volume0 -- reference configuration volume of particle\n energy -- energy of particle\n pInitial -- initial pressure of the particle\n d -- isotropic part of the strain rate tensor,\n dt -- time-step size\n\n output: final pressure pFinal, pressure rate p_rate\n ------------------------------------------------------------------------- */\nvoid PerfectGasEOS(const double gamma, const double vol, const double mass, const double energy, double &pFinal, double &c0) {\n\n\t/*\n\t * perfect gas EOS is p = (gamma - 1) rho e\n\t */\n\n\tif (energy > 0.0) {\n\n\t\tpFinal = (1.0 - gamma) * energy / vol;\n//printf(\"gamma = %f, vol%f, e=%g ==> p=%g\\n\", gamma, vol, energy, *pFinal__/1.0e-9);\n\n\t\tc0 = sqrt((gamma - 1.0) * energy / mass);\n\n\t} else {\n\t\tpFinal = c0 = 0.0;\n\t}\n\n}\n\n/* ----------------------------------------------------------------------\n linear strength model for use with linear elasticity\n input: lambda, mu : Lame parameters\n input: sigmaInitial_dev, d_dev: initial stress deviator, deviatoric part of the strain rate tensor\n input: dt: time-step\n output:  sigmaFinal_dev, sigmaFinal_dev_rate__: final stress deviator and its rate.\n ------------------------------------------------------------------------- */\nvoid LinearStrength(const double mu, const Matrix3d sigmaInitial_dev, const Matrix3d d_dev, const double dt,\n\t\tMatrix3d &sigmaFinal_dev__, Matrix3d &sigma_dev_rate__) {\n\n\t/*\n\t * deviatoric rate of unrotated stress\n\t */\n\tsigma_dev_rate__ = 2.0 * mu * d_dev;\n\n\t/*\n\t * elastic update to the deviatoric stress\n\t */\n\tsigmaFinal_dev__ = sigmaInitial_dev + dt * sigma_dev_rate__;\n}\n\n/* ----------------------------------------------------------------------\n linear strength model for use with linear elasticity\n input: lambda, mu : Lame parameters\n input: F: deformation gradient\n output:  total stress tensor, deviator + pressure\n ------------------------------------------------------------------------- */\n//void PairTlsph::LinearStrengthDefgrad(double lambda, double mu, Matrix3d F, Matrix3d *T) {\n//\tMatrix3d E, PK2, eye, sigma, S, tau;\n//\n//\teye.setIdentity();\n//\n//\tE = 0.5 * (F * F.transpose() - eye); // strain measure E = 0.5 * (B - I) = 0.5 * (F * F^T - I)\n//\ttau = lambda * E.trace() * eye + 2.0 * mu * E; // Kirchhoff stress, work conjugate to above strain\n//\tsigma = tau / F.determinant(); // convert Kirchhoff stress to Cauchy stress\n//\n////printf(\"l=%f, mu=%f, sigma xy = %f\\n\", lambda, mu, sigma(0,1));\n//\n////    E = 0.5 * (F.transpose() * F - eye); // Green-Lagrange Strain E = 0.5 * (C - I)\n////    S = lambda * E.trace() * eye + 2.0 * mu * Deviator(E); // PK2 stress\n////    tau = F * S * F.transpose(); // convert PK2 to Kirchhoff stress\n////    sigma = tau / F.determinant();\n//\n//\t//*T = sigma;\n//\n//\t/*\n//\t * neo-hookean model due to Bonet\n//\t */\n////    lambda = mu = 100.0;\n////    // left Cauchy-Green Tensor, b = F.F^T\n//\tdouble J = F.determinant();\n//\tdouble logJ = log(J);\n//\tMatrix3d b;\n//\tb = F * F.transpose();\n//\n//\tsigma = (mu / J) * (b - eye) + (lambda / J) * logJ * eye;\n//\t*T = sigma;\n//}\n/* ----------------------------------------------------------------------\n linear strength model for use with linear elasticity\n input: lambda, mu : Lame parameters\n input: sigmaInitial_dev, d_dev: initial stress deviator, deviatoric part of the strain rate tensor\n input: dt: time-step\n output:  sigmaFinal_dev, sigmaFinal_dev_rate__: final stress deviator and its rate.\n ------------------------------------------------------------------------- */\nvoid LinearPlasticStrength(const double G, const double yieldStress, const Matrix3d sigmaInitial_dev, const Matrix3d d_dev,\n\t\tconst double dt, Matrix3d &sigmaFinal_dev__, Matrix3d &sigma_dev_rate__, double &plastic_strain_increment) {\n\n\tMatrix3d sigmaTrial_dev, dev_rate;\n\tdouble J2;\n\n\t/*\n\t * deviatoric rate of unrotated stress\n\t */\n\tdev_rate = 2.0 * G * d_dev;\n\n\t/*\n\t * perform a trial elastic update to the deviatoric stress\n\t */\n\tsigmaTrial_dev = sigmaInitial_dev + dt * dev_rate; // increment stress deviator using deviatoric rate\n\n\t/*\n\t * check yield condition\n\t */\n\tJ2 = sqrt(3. / 2.) * sigmaTrial_dev.norm();\n\n\tif (J2 < yieldStress) {\n\t\t/*\n\t\t * no yielding has occured.\n\t\t * final deviatoric stress is trial deviatoric stress\n\t\t */\n\t\tsigma_dev_rate__ = dev_rate;\n\t\tsigmaFinal_dev__ = sigmaTrial_dev;\n\t\tplastic_strain_increment = 0.0;\n\t\t//printf(\"no yield\\n\");\n\n\t} else {\n\t\t//printf(\"yiedl\\n\");\n\t\t/*\n\t\t * yielding has occured\n\t\t */\n\t\tplastic_strain_increment = (J2 - yieldStress) / (3.0 * G);\n\n\t\t/*\n\t\t * new deviatoric stress:\n\t\t * obtain by scaling the trial stress deviator\n\t\t */\n\t\tsigmaFinal_dev__ = (yieldStress / J2) * sigmaTrial_dev;\n\n\t\t/*\n\t\t * new deviatoric stress rate\n\t\t */\n\t\tsigma_dev_rate__ = sigmaFinal_dev__ - sigmaInitial_dev;\n\t\t//printf(\"yielding has occured.\\n\");\n\t}\n}\n\n/* ----------------------------------------------------------------------\n Johnson Cook Material Strength model\n input:\n G : shear modulus\n cp : heat capacity\n espec : energy / mass\n A : initial yield stress under quasi-static / room temperature conditions\n B : proportionality factor for plastic strain dependency\n a : exponent for plastic strain dpendency\n C : proportionality factor for logarithmic plastic strain rate dependency\n epdot0 : dimensionality factor for plastic strain rate dependency\n T : current temperature\n T0 : reference (room) temperature\n Tmelt : melting temperature\n input: sigmaInitial_dev, d_dev: initial stress deviator, deviatoric part of the strain rate tensor\n input: dt: time-step\n output:  sigmaFinal_dev, sigmaFinal_dev_rate__: final stress deviator and its rate.\n ------------------------------------------------------------------------- */\nvoid JohnsonCookStrength(const double G, const double cp, const double espec, const double A, const double B, const double a,\n\t\tconst double C, const double epdot0, const double T0, const double Tmelt, const double M, const double dt, const double ep,\n\t\tconst double epdot, const Matrix3d sigmaInitial_dev, const Matrix3d d_dev, Matrix3d &sigmaFinal_dev__,\n\t\tMatrix3d &sigma_dev_rate__, double &plastic_strain_increment) {\n\n\tMatrix3d sigmaTrial_dev, dev_rate;\n\tdouble J2, yieldStress;\n\n\tdouble deltaT = espec / cp;\n\tdouble TH = deltaT / (Tmelt - T0);\n\tTH = MAX(TH, 0.0);\n\tdouble epdot_ratio = epdot / epdot0;\n\tepdot_ratio = MAX(epdot_ratio, 1.0);\n\t//printf(\"current temperature delta is %f, TH=%f\\n\", deltaT, TH);\n\n\tyieldStress = (A + B * pow(ep, a)) * (1.0 + C * log(epdot_ratio)); // * (1.0 - pow(TH, M));\n\n\t/*\n\t * deviatoric rate of unrotated stress\n\t */\n\tdev_rate = 2.0 * G * d_dev;\n\n\t/*\n\t * perform a trial elastic update to the deviatoric stress\n\t */\n\tsigmaTrial_dev = sigmaInitial_dev + dt * dev_rate; // increment stress deviator using deviatoric rate\n\n\t/*\n\t * check yield condition\n\t */\n\tJ2 = sqrt(3. / 2.) * sigmaTrial_dev.norm();\n\n\tif (J2 < yieldStress) {\n\t\t/*\n\t\t * no yielding has occured.\n\t\t * final deviatoric stress is trial deviatoric stress\n\t\t */\n\t\tsigma_dev_rate__ = dev_rate;\n\t\tsigmaFinal_dev__ = sigmaTrial_dev;\n\t\tplastic_strain_increment = 0.0;\n\t\t//printf(\"no yield\\n\");\n\n\t} else {\n\t\t//printf(\"yiedl\\n\");\n\t\t/*\n\t\t * yielding has occured\n\t\t */\n\t\tplastic_strain_increment = (J2 - yieldStress) / (3.0 * G);\n\n\t\t/*\n\t\t * new deviatoric stress:\n\t\t * obtain by scaling the trial stress deviator\n\t\t */\n\t\tsigmaFinal_dev__ = (yieldStress / J2) * sigmaTrial_dev;\n\n\t\t/*\n\t\t * new deviatoric stress rate\n\t\t */\n\t\tsigma_dev_rate__ = sigmaFinal_dev__ - sigmaInitial_dev;\n\t\t//printf(\"yielding has occured.\\n\");\n\t}\n}\n\n/* ----------------------------------------------------------------------\n isotropic maximum strain damage model\n input:\n current strain\n maximum value of allowed principal strain\n\n output:\n return value is true if any eigenvalue of the current strain exceeds the allowed principal strain\n\n ------------------------------------------------------------------------- */\n\nbool IsotropicMaxStrainDamage(const Matrix3d E, const double maxStrain) {\n\n\t/*\n\t * compute Eigenvalues of strain matrix\n\t */\n\tSelfAdjointEigenSolver < Matrix3d > es;\n\tes.compute(E); // compute eigenvalue and eigenvectors of strain\n\n\tdouble max_eigenvalue = es.eigenvalues().maxCoeff();\n\n\tif (max_eigenvalue > maxStrain) {\n\t\treturn true;\n\t} else {\n\t\treturn false;\n\t}\n}\n\n/* ----------------------------------------------------------------------\n isotropic maximum stress damage model\n input:\n current stress\n maximum value of allowed principal stress\n\n output:\n return value is true if any eigenvalue of the current stress exceeds the allowed principal stress\n\n ------------------------------------------------------------------------- */\n\nbool IsotropicMaxStressDamage(const Matrix3d S, const double maxStress) {\n\n\t/*\n\t * compute Eigenvalues of strain matrix\n\t */\n\tSelfAdjointEigenSolver < Matrix3d > es;\n\tes.compute(S); // compute eigenvalue and eigenvectors of strain\n\n\tdouble max_eigenvalue = es.eigenvalues().maxCoeff();\n\n\tif (max_eigenvalue > maxStress) {\n\t\treturn true;\n\t} else {\n\t\treturn false;\n\t}\n}\n\n/* ----------------------------------------------------------------------\n Johnson-Cook failure model\n input:\n\n\n output:\n\n\n ------------------------------------------------------------------------- */\n\ndouble JohnsonCookFailureStrain(const double p, const Matrix3d Sdev, const double d1, const double d2, const double d3,\n\t\tconst double d4, const double epdot0, const double epdot) {\n\n\n\n\tdouble vm = sqrt(3. / 2.) * Sdev.norm(); // von-Mises equivalent stress\n\tif (vm < 0.0) {\n\t\tcout << \"this is sdev \" << endl << Sdev << endl;\n\t\tprintf(\"vm=%f < 0.0, surely must be an error\\n\", vm);\n\t\texit(1);\n\t}\n\n\t// determine stress triaxiality\n\tdouble triax = p / (vm + 0.01 * fabs(p)); // have softening in denominator to avoid divison by zero\n\tif (triax < 0.0) {\n\t\ttriax = 0.0;\n\t} else if (triax > 3.0) {\n\t\ttriax = 3.0;\n\t}\n\n\t// Johnson-Cook failure strain, dependence on stress triaxiality\n\tdouble jc_failure_strain = d1 + d2 * exp(d3 * triax);\n\n\t// include strain rate dependency if parameter d4 is defined and current plastic strain rate exceeds reference strain rate\n\tif (d4 > 0.0) { //\n\t\tif (epdot > epdot0) {\n\t\t\tdouble epdot_ratio = epdot / epdot0;\n\t\t\tjc_failure_strain *= (1.0 + d4 * log(epdot_ratio));\n\t\t\t//printf(\"epsdot=%f, epsdot0=%f, factor = %f\\n\", epdot, epdot0, (1.0 + d4 * log(epdot_ratio)));\n\t\t\t//exit(1);\n\n\t\t}\n\t}\n\n\treturn jc_failure_strain;\n\n}\n", "meta": {"hexsha": "228d1c709a77870ecb752a31580cfa6c571d8ff2", "size": 15189, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/USER-SMD/smd_material_models.cpp", "max_stars_repo_name": "luwei0917/GlpG_Nature_Communication", "max_stars_repo_head_hexsha": "a7f4f8b526e633b158dc606050e8993d70734943", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-11-28T15:04:55.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-28T15:04:55.000Z", "max_issues_repo_path": "src/USER-SMD/smd_material_models.cpp", "max_issues_repo_name": "luwei0917/GlpG_Nature_Communication", "max_issues_repo_head_hexsha": "a7f4f8b526e633b158dc606050e8993d70734943", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/USER-SMD/smd_material_models.cpp", "max_forks_repo_name": "luwei0917/GlpG_Nature_Communication", "max_forks_repo_head_hexsha": "a7f4f8b526e633b158dc606050e8993d70734943", "max_forks_repo_licenses": ["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.9768421053, "max_line_length": 130, "alphanum_fraction": 0.593258279, "num_tokens": 3907, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4685266559918339}}
{"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_VMX_ALTIVEC_FAST_RSQRT_HPP_INCLUDED\n#define BOOST_SIMD_ARITHMETIC_FUNCTIONS_SIMD_VMX_ALTIVEC_FAST_RSQRT_HPP_INCLUDED\n#ifdef BOOST_SIMD_HAS_VMX_SUPPORT\n\n#include <boost/simd/arithmetic/functions/rsqrt.hpp>\n#include <boost/simd/include/functions/simd/multiplies.hpp>\n#include <boost/simd/include/functions/simd/fma.hpp>\n#include <boost/simd/include/functions/simd/sqr.hpp>\n#include <boost/simd/include/constants/zero.hpp>\n#include <boost/simd/include/constants/one.hpp>\n#include <boost/simd/include/constants/half.hpp>\n#include <boost/dispatch/attributes.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT          ( fast_rsqrt_\n                                    , boost::simd::tag::vmx_\n                                    , (A0)\n                                    , ((simd_ < single_<A0>\n                                              , boost::simd::tag::vmx_\n                                              >\n                                      ))\n                                    )\n  {\n    typedef A0 result_type;\n\n    BOOST_FORCEINLINE BOOST_SIMD_FUNCTOR_CALL(1)\n    {\n      result_type hf = Half<result_type>();\n      result_type o  = One<result_type>();\n\n      result_type estimate = vec_rsqrte( a0() );\n      result_type se = sqr(estimate);\n      result_type he = estimate*hf;\n      result_type st = vec_nmsub(a0(),se(),o());\n\n      return fma( st, he, estimate);\n    }\n  };\n} } }\n\n#endif\n\n#endif\n\n", "meta": {"hexsha": "505dd606f7a9c39b7f31045bb491fade0e16135f", "size": 2040, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/simd/vmx/altivec/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/simd/vmx/altivec/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/simd/vmx/altivec/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": 37.0909090909, "max_line_length": 82, "alphanum_fraction": 0.5495098039, "num_tokens": 443, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891130942472, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.46852664606061106}}
{"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_ASIN_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_ASIN_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 inverse sine.\n\n\n    @par Header <boost/simd/function/asin.hpp>\n\n    @par Note\n\n      For every parameter of floating type `asin(x)`\n      returns the arc @c r in the interval  \\f$[-\\pi/2, \\pi/2]\\f$ such that\n      <tt>sin(r) == x</tt>.  If @c x is outside \\f$[-1, 1]\\f$ the result is Nan.\n\n    @par Decorators\n\n      - std_ for floating entries provides access to std::asin\n\n    @see asind, asinpi, sin\n\n\n    @par Example:\n\n      @snippet asin.cpp asin\n\n    @par Possible output:\n\n      @snippet asin.txt asin\n\n  **/\n  IEEEValue asin(IEEEValue const & x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/asin.hpp>\n#include <boost/simd/function/simd/asin.hpp>\n\n#endif\n", "meta": {"hexsha": "81856ac9547acd33c1fb11528f5aaa4968ecb2d1", "size": 1293, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/asin.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/asin.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/asin.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 23.5090909091, "max_line_length": 100, "alphanum_fraction": 0.5754060325, "num_tokens": 310, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397349, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4685209219762184}}
{"text": "#include <cstdio>\n#include <iostream>\n\n#include \"gflags/gflags.h\"\n#include \"sndfile.h\"\n#include \"CImg.h\"\n#include \"ipp.h\"\n#include \"tbb/tbb.h\"\n#include \"tbb/pipeline.h\"\n#include \"tbb/scalable_allocator.h\"\n#include \"tbb/cache_aligned_allocator.h\"\n#include <boost/filesystem.hpp>\n#include \"bakuage/sndfile_wrapper.h\"\n#include \"bakuage/dft.h\"\n#include \"bakuage/memory.h\"\n#include \"bakuage/utils.h\"\n#include \"bakuage/window_func.h\"\n#include \"bakuage/vector_math.h\"\n\nDEFINE_bool(quick_exit, true, \"quick exit\");\nDEFINE_int32(worker_count, 0, \"thread count\");\nDEFINE_string(input, \"\", \"input wav file path\");\nDEFINE_string(output, \"\", \"output directory or - for stdout\");\nDEFINE_string(background, \"\", \"background image path\");\nDEFINE_string(foreground, \"\", \"foreground image path\");\nDEFINE_int32(min_hz, 50, \"min freq in hz\");\nDEFINE_int32(max_hz, 8000, \"max freq in hz\");\nDEFINE_int32(band_count, 30, \"band count\");\nDEFINE_int32(width, 640, \"width of output video\");\nDEFINE_int32(height, 480, \"height of output video\");\nDEFINE_double(fps, 30, \"frame per sec\");\nDEFINE_double(window_sec, 0.04, \"dft window size in sec\");\n\nnamespace {\n\ntypedef float Float;\ntypedef float PixelType;\n    typedef std::shared_ptr<bakuage::AlignedPodVector<char>> BufferPtr;\n\n    void PrintMemoryUsage() {\n        std::cerr << \"Peak RSS(MB)\\t\" << bakuage::GetPeakRss() / (1024 * 1024)\n        << \"\\tCurrent RSS(MB)\\t\" << bakuage::GetCurrentRss() / (1024 * 1024)\n        << std::endl;\n    }\n\n// \u52d5\u753b\u306e\u9577\u3055\u304c\u97f3\u6e90\u306e\u9577\u3055\u4ee5\u4e0a\u306b\u306a\u308b\u3088\u3046\u306b\u3059\u308b\nvoid CalculateSpectrogram(Float *input, int channels, int samples, int sample_freq, std::vector<bakuage::AlignedPodVector<float>> *output) {\n    using namespace bakuage;\n\n    const double min_mel = bakuage::HzToMel(FLAGS_min_hz);\n    const double max_mel = bakuage::HzToMel(FLAGS_max_hz);\n\n    const int width = 2 * (sample_freq * FLAGS_window_sec / 2); // even\n    const int spec_len = width / 2 + 1;\n    bakuage::AlignedPodVector<float> window(width);\n    bakuage::CopyHanning(width, window.begin());\n    bakuage::AlignedPodVector<float> fft_input(width);\n    bakuage::AlignedPodVector<std::complex<float>> fft_output(spec_len);\n    bakuage::RealDft<float> dft(width);\n\n    std::vector<bakuage::AlignedPodVector<float>> spectrogram;\n\n    for (int pos_i = 0; pos_i < samples * FLAGS_fps / sample_freq; pos_i++) {\n        const int pos = std::floor((double)pos_i / FLAGS_fps * sample_freq) - width / 2;\n\n        bakuage::AlignedPodVector<std::complex<float>> complex_spec_mid(spec_len);\n        bakuage::AlignedPodVector<std::complex<float>> complex_spec_side(spec_len);\n\n        // window and fft\n        for (int i = 0; i < channels; i++) {\n            for (int j = 0; j < width; j++) {\n                int k = pos + j;\n                fft_input[j] = (0 <= k && k < samples) ? input[channels * k + i] * window[j] : 0;\n            }\n            dft.Forward(fft_input.data(), (float *)fft_output.data());\n            for (int j = 0; j < spec_len; j++) {\n                const auto spec = fft_output[j];\n                complex_spec_mid[j] += spec;\n                complex_spec_side[j] += spec * (2.0f * i - 1);\n            }\n        }\n\n        // 3dB/oct \u30b9\u30ed\u30fc\u30d7\u88dc\u6b63 + \u30a8\u30cd\u30eb\u30ae\u30fc\u6b63\u898f\u5316\n        // mean \u30e2\u30fc\u30c9\u3092\u4f7f\u3046\u306e\u3067\u3001\u30d4\u30f3\u30af\u30ce\u30a4\u30ba\u306f-3dB/oct\u306b\u306a\u308b\u3053\u3068\u306b\u6ce8\u610f\n        for (int j = 0; j < spec_len; j++) {\n            const auto freq = 1.0 * j / width * sample_freq;\n            const auto slope_scale = std::sqrt(freq); // linear\u7a7a\u9593\u306a\u306e\u3067sqrt\n            const auto normalize_scale = 1.0 / std::sqrt(width);\n            const auto scale = slope_scale * normalize_scale;\n            complex_spec_mid[j] *= scale;\n            complex_spec_side[j] *= scale;\n        }\n\n        bakuage::AlignedPodVector<float> row(FLAGS_band_count);\n        bakuage::AlignedPodVector<float> row_count(FLAGS_band_count);\n        for (int j = 0; j < spec_len; j++) {\n            const double compensation = (j == 0 || j == spec_len - 1) ? 1 : 2;\n            const double freq = 1.0 * j / width * sample_freq;\n            const int k = FLAGS_band_count * (bakuage::HzToMel(freq) - min_mel) / (max_mel - min_mel);\n            if (0 <= k && k < row.size()) {\n                row[k] += std::norm(complex_spec_mid[j]) * compensation;\n                row_count[k] += 1;\n            }\n        }\n        for (int j = 0; j < row.size(); j++) {\n            row[j] /= 1e-37 + row_count[j];\n        }\n        spectrogram.emplace_back(std::move(row));\n    }\n\n    *output = std::move(spectrogram);\n}\n\nvoid overlay_4ch_on_3ch(const cimg_library::CImg<PixelType> &src, cimg_library::CImg<PixelType> *dest) {\n    // CImg\u306e\u30e1\u30e2\u30ea\u914d\u7f6e\n    /*\n     T& operator()(const unsigned int x, const unsigned int y, const unsigned int z, const unsigned int c) {\n     return _data[x + y*(ulongT)_width + z*(ulongT)_width*_height + c*(ulongT)_width*_height*_depth];\n     }\n     */\n\n    bakuage::AlignedPodVector<float> one_minus_alpha(src.width());\n\n    const double scale = 1.0 / 255.0;\n    for (int c = 0; c < 3; c++) {\n        for (int j = 0; j < src.height(); j++) {\n#if 1\n            const PixelType *src_row = &src(0, j, 0, c);\n            const PixelType *src_alpha_row = &src(0, j, 0, 3);\n            PixelType *dest_row = &(*dest)(0, j, 0, c);\n\n            bakuage::VectorSubConstantRev(src_alpha_row, 255.0f, one_minus_alpha.data(), src.width());\n            bakuage::VectorMulInplace(one_minus_alpha.data(), dest_row, src.width());\n            bakuage::VectorMadInplace(src_alpha_row, src_row, dest_row, src.width());\n            bakuage::VectorMulConstantInplace(scale, dest_row, src.width());\n#else\n#if 1\n            // for integer\n            for (int i = 0; i < src.width(); i++) {\n                const PixelType alpha = src(i, j, 0, 3);\n                (*dest)(i, j, 0, c) = ((*dest)(i, j, 0, c) * (255 - alpha) + src(i, j, 0, c) * alpha) >> 8;\n            }\n#else\n            for (int i = 0; i < src.width(); i++) {\n                const double alpha = src(i, j, 0, 3) * scale;\n                (*dest)(i, j, 0, c) = (*dest)(i, j, 0, c) * (1 - alpha) + src(i, j, 0, c) * alpha;\n            }\n#endif\n#endif\n        }\n    }\n}\n\n}\n\n// wav\u3092\u53d7\u3051\u53d6\u3063\u3066\u3001\u6a19\u6e96\u51fa\u529b\u306brawvideo\u3092\u51fa\u529b\nint main(int argc, char* argv[]) {\n    gflags::SetVersionString(\"1.0.0-oss\");\n    gflags::ParseCommandLineFlags(&argc, &argv, true);\n\n    ippInit();\n    const IppLibraryVersion *lib = ippGetLibVersion();\n    std::cerr << \"Ipp initialized \" << lib->Name << \" \" << lib->Version << std::endl;\n    PrintMemoryUsage();\n\n    // TBB\u306e\u521d\u671f\u5316\u3068\u304b (\u3053\u3053\u3067\u521d\u671f\u5316\u3057\u3066\u304a\u304f\u3068\u3001\u6bce\u56de\u521d\u671f\u5316\u3057\u306a\u304f\u3066\u3082\u826f\u3044\u3089\u3057\u3044)\n    // https://www.xlsoft.com/jp/products/intel/perflib/tbb/41/tbb_userguide_lnx/reference/task_scheduler/task_scheduler_init_cls.htm\n    tbb::task_scheduler_init tbb_init(FLAGS_worker_count ? FLAGS_worker_count : tbb::task_scheduler_init::default_num_threads());\n    std::cerr << \"TBB default_num_threads:\" << tbb::task_scheduler_init::default_num_threads() << std::endl;\n    PrintMemoryUsage();\n\n    bakuage::SndfileWrapper infile;\n    SF_INFO sfinfo = { 0 };\n\n    const auto input_file_path = FLAGS_input;\n\n    if ((infile.set(sf_open (input_file_path.c_str(), SFM_READ, &sfinfo))) == NULL) {\n        fprintf(stderr, \"Not able to open input file %s.\\n\", input_file_path.c_str());\n        fprintf(stderr, \"%s\\n\", sf_strerror(NULL));\n        return 1;\n    }\n\n    // check format\n    fprintf(stderr, \"sfinfo.format 0x%08x.\\n\", sfinfo.format);\n    switch (sfinfo.format & SF_FORMAT_TYPEMASK) {\n        case SF_FORMAT_WAV:\n        case SF_FORMAT_WAVEX:\n            break;\n        default:\n            fprintf(stderr, \"Not supported sfinfo.format 0x%08x.\\n\", sfinfo.format);\n            return 2;\n    }\n\n    bakuage::AlignedPodVector<float> buffer(sfinfo.channels * sfinfo.frames);\n    int read_size = sf_readf_float(infile.get(), buffer.data(), sfinfo.frames);\n    fprintf(stderr, \"%d samples read.\\n\", read_size);\n    if (read_size != sfinfo.frames) {\n        fprintf(stderr, \"sf_readf_float error: %d %d\\n\", read_size, (int)sfinfo.frames);\n        return 3;\n    }\n\n    // calculate spectrogram (energy)\n    std::vector<bakuage::AlignedPodVector<float>> spectrogram;\n    CalculateSpectrogram(buffer.data(), sfinfo.channels, sfinfo.frames, sfinfo.samplerate, &spectrogram);\n\n    // log and normalize spectrogram\n    {\n        double min_x = 1e100;\n        double max_x = -1e100;\n        for (auto &spectrum: spectrogram) {\n            for (auto &x: spectrum) {\n                x = std::log(1e-7 + x);\n                min_x = std::min<double>(min_x, x);\n                max_x = std::max<double>(max_x, x);\n            }\n        }\n        for (auto &spectrum: spectrogram) {\n            for (auto &x: spectrum) {\n                x = (x - min_x) / (max_x - min_x);\n            }\n        }\n    }\n\n    cimg_library::CImg<PixelType> background(FLAGS_width, FLAGS_height, 1, 3, 0);\n    if (!FLAGS_background.empty()) {\n        cimg_library::CImg<PixelType> tmp(FLAGS_background.c_str());\n        tmp.resize(FLAGS_width, FLAGS_height);\n        for (int i = 0; i < FLAGS_width; i++) {\n            for (int j = 0; j < FLAGS_height; j++) {\n                background(i, j, 0, 0) = tmp(i, j, 0, 0);\n                background(i, j, 0, 1) = tmp(i, j, 0, 1);\n                background(i, j, 0, 2) = tmp(i, j, 0, 2);\n            }\n        }\n    }\n\n    cimg_library::CImg<PixelType> foreground(FLAGS_width, FLAGS_height, 1, 4, 0);\n    if (!FLAGS_foreground.empty()) {\n        cimg_library::CImg<PixelType> tmp(FLAGS_foreground.c_str());\n        tmp.resize(FLAGS_width, FLAGS_height);\n        for (int i = 0; i < FLAGS_width; i++) {\n            for (int j = 0; j < FLAGS_height; j++) {\n                foreground(i, j, 0, 0) = tmp(i, j, 0, 0);\n                foreground(i, j, 0, 1) = tmp(i, j, 0, 1);\n                foreground(i, j, 0, 2) = tmp(i, j, 0, 2);\n                foreground(i, j, 0, 3) = tmp.spectrum() < 4 ? 255 : tmp(i, j, 0, 3);\n            }\n        }\n    }\n\n    auto spectrogram_it = spectrogram.begin();\n    const auto spectrogram_end = spectrogram.end();\n    const auto filter1_func = [&spectrogram_it, spectrogram_end](tbb::flow_control& fc) -> bakuage::AlignedPodVector<float> * {\n        if (spectrogram_it != spectrogram_end) {\n            return &(*(spectrogram_it++));\n        } else {\n            fc.stop();\n            return nullptr;\n        }\n    };\n    const auto filter2_func = [&foreground, &background](bakuage::AlignedPodVector<float> *spectrum){\n        cimg_library::CImg<PixelType> img(FLAGS_width, FLAGS_height, 1, 3, 0);\n\n        // draw background image\n        img = background;\n\n        // draw spectrum\n        cimg_library::CImg<PixelType> spec_img(FLAGS_width, FLAGS_height, 1, 4, 0);\n        spec_img.fill((PixelType)0, 0, 0, 0);\n        for (int i = 0; i < spectrum->size(); i++) {\n            const int block_div = 24;\n            const double center_x = FLAGS_width / 2;\n            const double center_y = FLAGS_height * 0.7;\n            const double spectrum_width = FLAGS_width * 0.5;\n            const double spectrum_height = FLAGS_height * 0.3;\n            const double spectrum_left = center_x - spectrum_width / 2;\n            const double spectrum_bottom = center_y + spectrum_height / 2;\n            const double x1 = spectrum_left + spectrum_width * i / spectrum->size();\n            const double x2 = spectrum_left + spectrum_width * (i + 1) / spectrum->size();\n            const double space_x = (x2 - x1) * 0.5;\n            const int block_count = std::floor((*spectrum)[i] * block_div + 0.5);\n            for (int j = 0; j < block_count; j++) {\n                const double y1 = spectrum_bottom - spectrum_height * (j + 1) / block_div;\n                const double y2 = spectrum_bottom - spectrum_height * j / block_div;\n                const double space_y = (y2 - y1) * 0.5;\n                const PixelType color[4] = { 255, 255, 255, 200 };\n                spec_img.draw_rectangle(x1 + space_x / 2, y1 + space_y / 2, 0, x2 - space_x / 2, y2 - space_y / 2, 1, color);\n            }\n        }\n        overlay_4ch_on_3ch(spec_img, &img);\n\n        // alpha blend foreground image\n        overlay_4ch_on_3ch(foreground, &img);\n\n        const auto temp_path = (boost::filesystem::temp_directory_path() / boost::filesystem::unique_path()).native();\n        // img.save_bmp(output_path.str().c_str()); // slow\n        img.save_png(temp_path.c_str());\n        BufferPtr buffer;\n        bakuage::LoadDataFromFile(temp_path.c_str(), [&buffer](const char *data, size_t size) {\n            buffer = std::make_shared<bakuage::AlignedPodVector<char>>(data, data + size);\n        });\n        boost::filesystem::remove(temp_path);\n        return buffer;\n    };\n    int spectrogram_i = 0;\n    const auto filter3_func = [&spectrogram_i](BufferPtr buffer) {\n        if (FLAGS_output == \"-\") {\n            const size_t n = std::fwrite(buffer->data(), 1, buffer->size(), stdout);\n            if (n != buffer->size()) {\n                throw std::logic_error(\"failed to write stdout\");\n            }\n        } else {\n            std::stringstream output_path;\n            output_path << FLAGS_output << \"/\" << spectrogram_i++ << \".png\";\n\n            FILE* pf = std::fopen(output_path.str().c_str(), \"wb\");\n            std::fwrite(buffer->data(), 1, buffer->size(), pf);\n            std::fclose(pf);\n        }\n    };\n    tbb::parallel_pipeline(256,\n                           tbb::make_filter<void, bakuage::AlignedPodVector<float> *>(tbb::filter::serial, filter1_func)\n                           & tbb::make_filter<bakuage::AlignedPodVector<float> *,BufferPtr>(tbb::filter::parallel, filter2_func)\n                           & tbb::make_filter<BufferPtr, void>(tbb::filter::serial, filter3_func)\n                           );\n    std::fflush(stdout);\n\n    PrintMemoryUsage();\n\n    if (FLAGS_quick_exit) {\n        // \u666e\u901a\u306b\u7d42\u4e86\u3059\u308b\u3068\u30af\u30e9\u30c3\u30b7\u30e5\u3059\u308b\u3002\u591a\u5206thread_local\u3068\u304b\u306e\u30c7\u30b9\u30c8\u30e9\u30af\u30bf\u5468\u308a\n        // CircleCI\u4e0a\u3067\u518d\u73fe\u3057\u305f\u306e\u3067\u8981\u6ce8\u610f\n        // \u30af\u30e9\u30c3\u30b7\u30e5\u56de\u907f\u3064\u3044\u3067\u306b\u52b9\u7387\u7684\u306b\u7d42\u4e86\u3067\u304d\u308b\u306e\u3067\u4f7f\u3046\u304c\u3001\u6839\u672c\u7684\u306b\u30d0\u30b0\u3082\u76f4\u3057\u305f\u3044\n        // https://stackoverflow.com/questions/24821265/exiting-a-c-app-immediately\n        std::cerr << \"quick exiting: \" << 0 << std::endl;\n        std::_Exit(0);\n    } else {\n        return 0;\n    }\n}\n\n", "meta": {"hexsha": "f35332881a9b47908195a7f5245d3bf98392b32f", "size": 13994, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/audio_visualizer/main.cpp", "max_stars_repo_name": "nankasuisui/phaselimiter", "max_stars_repo_head_hexsha": "dd155676a3750d4977b8248d52fc77f5c28d1906", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2021-07-07T14:37:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T16:43:47.000Z", "max_issues_repo_path": "src/audio_visualizer/main.cpp", "max_issues_repo_name": "nankasuisui/phaselimiter", "max_issues_repo_head_hexsha": "dd155676a3750d4977b8248d52fc77f5c28d1906", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/audio_visualizer/main.cpp", "max_forks_repo_name": "nankasuisui/phaselimiter", "max_forks_repo_head_hexsha": "dd155676a3750d4977b8248d52fc77f5c28d1906", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-04-03T13:36:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-28T20:21:10.000Z", "avg_line_length": 40.918128655, "max_line_length": 140, "alphanum_fraction": 0.5874660569, "num_tokens": 4040, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4685209161265635}}
{"text": "/**************************************************************************\n *\n * (C) Copyright VMware, Inc 2010.\n * (C) Copyright John Maddock 2006.\n * Use, modification and distribution are subject to the\n * Boost Software License, Version 1.0. (See accompanying file\n * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n *\n **************************************************************************/\n\n\n/*\n * This file allows to compute the minimax polynomial coefficients we use\n * for fast exp2/log2.\n *\n * How to use this source:\n *\n * - Download and build the NTL library from\n *   http://shoup.net/ntl/download.html , or install libntl-dev package if on\n *   Debian.\n *\n * - Download boost source code matching to your distro. \n *\n * - Goto libs/math/minimax and replace f.cpp with this file.\n *\n * - Build as\n *\n *   g++ -o minimax -I /path/to/ntl/include main.cpp f.cpp /path/to/ntl/src/ntl.a\n *\n * - Run as \n *\n *    ./minimax\n *\n * - For example, to compute exp2 5th order polynomial between [0, 1] do:\n *\n *    variant 0\n *    range 0 1\n *    order 5 0\n *    step 200\n *    info\n *\n *  and take the coefficients from the P = { ... } array.\n *\n * - To compute log2 4th order polynomial between [0, 1/9] do:\n *\n *    variant 1\n *    range 0 0.111111112\n *    order 4 0\n *    step 200\n *    info\n *\n * - For more info see\n * http://www.boost.org/doc/libs/1_47_0/libs/math/doc/sf_and_dist/html/math_toolkit/toolkit/internals2/minimax.html\n */\n\n#define L22\n#include <boost/math/bindings/rr.hpp>\n#include <boost/math/tools/polynomial.hpp>\n\n#include <cmath>\n\nboost::math::ntl::RR exp2(const boost::math::ntl::RR& x)\n{\n      return exp(x*log(2.0));\n}\n\nboost::math::ntl::RR log2(const boost::math::ntl::RR& x)\n{\n      return log(x)/log(2.0);\n}\n\nboost::math::ntl::RR f(const boost::math::ntl::RR& x, int variant)\n{\n   switch(variant)\n   {\n   case 0:\n      return exp2(x);\n\n   case 1:\n      return log2((1.0 + sqrt(x))/(1.0 - sqrt(x)))/sqrt(x);\n   }\n\n   return 0;\n}\n\n\nvoid show_extra(\n   const boost::math::tools::polynomial<boost::math::ntl::RR>& n, \n   const boost::math::tools::polynomial<boost::math::ntl::RR>& d, \n   const boost::math::ntl::RR& x_offset, \n   const boost::math::ntl::RR& y_offset, \n   int variant)\n{\n   switch(variant)\n   {\n   default:\n      // do nothing here...\n      ;\n   }\n}\n\n", "meta": {"hexsha": "4b33e49b477725b7b353d650afd3d81299c9aa88", "size": 2317, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/gallium/auxiliary/gallivm/f.cpp", "max_stars_repo_name": "thermasol/mesa3d", "max_stars_repo_head_hexsha": "6f1bc4e7edfface197ef281cffdf399b5389e24a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2151.0, "max_stars_repo_stars_event_min_datetime": "2020-04-18T07:31:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:39:18.000Z", "max_issues_repo_path": "src/gallium/auxiliary/gallivm/f.cpp", "max_issues_repo_name": "thermasol/mesa3d", "max_issues_repo_head_hexsha": "6f1bc4e7edfface197ef281cffdf399b5389e24a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 395.0, "max_issues_repo_issues_event_min_datetime": "2020-04-18T08:22:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-08T13:04:49.000Z", "max_forks_repo_path": "src/gallium/auxiliary/gallivm/f.cpp", "max_forks_repo_name": "thermasol/mesa3d", "max_forks_repo_head_hexsha": "6f1bc4e7edfface197ef281cffdf399b5389e24a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 338.0, "max_forks_repo_forks_event_min_datetime": "2020-04-18T08:03:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T12:33:22.000Z", "avg_line_length": 22.7156862745, "max_line_length": 115, "alphanum_fraction": 0.5856711265, "num_tokens": 673, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.46852091027690823}}
{"text": "#include <CGAL/Real_timer.h>\n#include <CGAL/Random.h>\n#include <CGAL/Simple_cartesian.h>\n\n#include <CGAL/Point_set_3.h>\n#include <CGAL/Point_set_3/IO.h>\n\n#include <CGAL/Shape_detection/Region_growing/Region_growing.h>\n#include <CGAL/Shape_detection/Region_growing/Region_growing_on_point_set.h>\n\n#include <boost/iterator/function_output_iterator.hpp>\n\n#include <fstream>\n\nusing Kernel = CGAL::Simple_cartesian<double>;\nusing Point_3 = Kernel::Point_3;\nusing Vector_3 = Kernel::Vector_3;\nusing Point_2 = Kernel::Point_2;\nusing Vector_2 = Kernel::Vector_2;\n\nusing Point_set_3 = CGAL::Point_set_3<Point_3, Vector_3>;\nusing Point_set_2 = CGAL::Point_set_3<Point_2, Vector_2>;\nusing Point_map = Point_set_2::Point_map;\nusing Normal_map = Point_set_2::Vector_map;\n\nnamespace Shape_detection = CGAL::Shape_detection::Point_set;\n\nusing Neighbor_query = Shape_detection::K_neighbor_query\n  <Kernel, Point_set_2, Point_map>;\nusing Region_type = Shape_detection::Least_squares_circle_fit_region\n  <Kernel, Point_set_2, Point_map, Normal_map>;\nusing Sorting = Shape_detection::Least_squares_circle_fit_sorting\n  <Kernel, Point_set_2, Neighbor_query, Point_map>;\nusing Region_growing = CGAL::Shape_detection::Region_growing\n  <Point_set_2, Neighbor_query, Region_type, typename Sorting::Seed_map>;\n\nint main (int argc, char** argv)\n{\n  std::ifstream ifile (argc > 1 ? argv[1] : \"data/circles.ply\");\n  Point_set_3 points3;\n  ifile >> points3;\n\n  std::cerr << points3.size() << \" points read\" << std::endl;\n\n  // Input should have normals\n  assert (points3.has_normal_map());\n\n  Point_set_2 points;\n  points.add_normal_map();\n  for (Point_set_3::Index idx : points3)\n  {\n    const Point_3& p = points3.point(idx);\n    const Vector_3& n = points3.normal(idx);\n    points.insert (Point_2 (p.x(), p.y()), Vector_2 (n.x(), n.y()));\n  }\n\n  // Default parameters for data/circles.ply\n  const std::size_t k = 12;\n  const double tolerance = 0.01;\n  const double max_angle = 10.;\n  const std::size_t min_region_size = 20;\n\n  // No constraint on radius\n  const double min_radius = 0.;\n  const double max_radius = std::numeric_limits<double>::infinity();\n\n  Neighbor_query neighbor_query(points, k, points.point_map());\n  Region_type region_type(points, tolerance, max_angle, min_region_size,\n                          min_radius, max_radius,\n                          points.point_map(), points.normal_map());\n\n  // Sort indices\n  Sorting sorting(points, neighbor_query, points.point_map());\n  sorting.sort();\n\n  Region_growing region_growing(points, neighbor_query, region_type, sorting.seed_map());\n\n  // Add maps to get colored output\n  Point_set_3::Property_map<unsigned char>\n    red = points3.add_property_map<unsigned char>(\"red\", 0).first,\n    green = points3.add_property_map<unsigned char>(\"green\", 0).first,\n    blue = points3.add_property_map<unsigned char>(\"blue\", 0).first;\n\n  CGAL::Random random;\n\n  std::size_t nb_circles = 0;\n  CGAL::Real_timer timer;\n  timer.start();\n  region_growing.detect\n    (boost::make_function_output_iterator\n     ([&](const std::vector<std::size_t>& region)\n      {\n        // Assign a random color to each region\n        unsigned char r = static_cast<unsigned char>(random.get_int(64, 192));\n        unsigned char g = static_cast<unsigned char>(random.get_int(64, 192));\n        unsigned char b = static_cast<unsigned char>(random.get_int(64, 192));\n        for (const std::size_t& idx : region)\n        {\n          red[idx] = r;\n          green[idx] = g;\n          blue[idx] = b;\n        }\n        ++ nb_circles;\n      }));\n  timer.stop();\n\n  std::cerr << nb_circles << \" circles detected in \"\n            << timer.time() << \" seconds\" << std::endl;\n\n  // Save in colored_circles.ply\n  std::ofstream out (\"colored_circles.ply\");\n  CGAL::IO::set_binary_mode (out);\n  out << points3;\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "362ab391cc98c55aadeee3d216d5bbfb19721712", "size": 3829, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Shape_detection/examples/Shape_detection/region_growing_circles_on_point_set_2.cpp", "max_stars_repo_name": "kintel/cgal", "max_stars_repo_head_hexsha": "ef94cd588de60ce9c3352c517f002277fc0512f8", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-10-02T05:38:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-02T05:38:11.000Z", "max_issues_repo_path": "Shape_detection/examples/Shape_detection/region_growing_circles_on_point_set_2.cpp", "max_issues_repo_name": "kintel/cgal", "max_issues_repo_head_hexsha": "ef94cd588de60ce9c3352c517f002277fc0512f8", "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": "Shape_detection/examples/Shape_detection/region_growing_circles_on_point_set_2.cpp", "max_forks_repo_name": "kintel/cgal", "max_forks_repo_head_hexsha": "ef94cd588de60ce9c3352c517f002277fc0512f8", "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": 32.7264957265, "max_line_length": 89, "alphanum_fraction": 0.7007051449, "num_tokens": 1015, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.46852091027690823}}
{"text": "#include <Python.h>\n#include <iostream>\n#include <Eigen/Dense>\n\nusing namespace Eigen;\n\ntypedef struct\n{\n    PyObject_HEAD\n    MatrixXd *matrix=nullptr;\n} PyMatrixObject;\n\nstatic PyObject *\nPyMatrix_new(PyTypeObject *type, PyObject *args, PyObject *kwds)\n{\n    PyMatrixObject *self;\n    self = (PyMatrixObject *)type->tp_alloc(type, 0);\n\n    char *kwlist[] = {\"width\", \"height\", NULL};\n    int width = 0;\n    int height = 0;\n\n    if (!PyArg_ParseTupleAndKeywords(args, kwds, \"ii\", kwlist,\n                                     &width, &height))\n    {\n        Py_DECREF(self);\n        return NULL;\n    }\n    if (width <= 0 or height <= 0)\n    {\n        PyErr_SetString(PyExc_ValueError, \"The height and width must be greater than 0.\");\n        return NULL;\n    }\n\n    self->matrix = new MatrixXd(width, height);\n    return (PyObject *)self;\n}\n\nstatic void\n*PyMatrix_dealloc(PyObject *obj)\n{\n    delete ((PyMatrixObject *)obj)->matrix; \n    Py_TYPE(obj)->tp_free(obj);\n}\n\n\ninline MatrixXd *ParseMatrix(PyObject *obj){\n    return ((PyMatrixObject *)obj)->matrix;\n}\n\ninline PyObject *ReturnMatrix(MatrixXd *m, PyTypeObject *type){\n    PyMatrixObject *obj = PyObject_NEW(PyMatrixObject, type);\n    obj->matrix = m;\n    return (PyObject *)obj;\n}\n\nstatic PyObject *\nPyMatrix_add(PyObject *a, PyObject *b)\n{\n    MatrixXd *matrix_a = ParseMatrix(a);\n    MatrixXd *matrix_b = ParseMatrix(b);\n\n    if (matrix_a->cols() != matrix_b->cols() or matrix_a->rows() != matrix_b->rows()){\n        PyErr_SetString(PyExc_ValueError, \"The input matrix must be the same shape.\");\n        return NULL;\n    }\n\n    MatrixXd *matrix_c = new MatrixXd(matrix_a->cols(), matrix_b->rows());\n    *matrix_c = *matrix_a + *matrix_b;\n\n    return ReturnMatrix(matrix_c, a->ob_type);\n}\n\nstatic PyObject *\nPyMatrix_minus(PyObject *a, PyObject *b)\n{\n    MatrixXd *matrix_a = ParseMatrix(a);\n    MatrixXd *matrix_b = ParseMatrix(b);\n\n    if (matrix_a->cols() != matrix_b->cols() or matrix_a->rows() != matrix_b->rows()){\n        PyErr_SetString(PyExc_ValueError, \"The input matrix must be the same shape.\");\n        return NULL;\n    }\n\n    MatrixXd *matrix_c = new MatrixXd(matrix_a->cols(), matrix_b->rows());\n    *matrix_c = *matrix_a + *matrix_b;\n    return ReturnMatrix(matrix_c, a->ob_type);\n}\n\nstatic PyObject *\nPyMatrix_multiply(PyObject *a, PyObject *b)\n{\n    MatrixXd *matrix_a = ParseMatrix(a);\n    MatrixXd *matrix_b = ParseMatrix(b);\n\n    if (matrix_a->cols() != matrix_b->rows()){\n        PyErr_SetString(PyExc_ValueError, \"The colonm rank of matrix A must be the same as the row rank of matrix B.\");\n        return NULL;\n    }\n    MatrixXd *matrix_c = new MatrixXd(matrix_a->rows(), matrix_b->cols());\n    *matrix_c = (*matrix_a) * (*matrix_b);\n    return ReturnMatrix(matrix_c, a->ob_type);\n}\n\nstatic PyObject *PyMatrix_str(PyObject *a)\n{\n    MatrixXd *matrix = ParseMatrix(a);\n    std::stringstream ss;\n    ss << *matrix;\n    return Py_BuildValue(\"s\", ss.str().c_str());\n}\n\nstatic PyNumberMethods numberMethods = {\n    PyMatrix_add,      //nb_add\n    PyMatrix_minus,    //nb_subtract;\n    PyMatrix_multiply, //nb_multiply\n    nullptr,           //nb_remainder;\n    nullptr,           //nb_divmod;\n    nullptr,           // nb_power;\n    nullptr,           // nb_negative;\n    nullptr,           // nb_positive;\n    nullptr,           // nb_absolute;\n    nullptr,           // nb_bool;\n    nullptr,           // nb_invert;\n    nullptr,           // nb_lshift;\n    nullptr,           // nb_rshift;\n    nullptr,           // nb_and;\n    nullptr,           // nb_xor;\n    nullptr,           // nb_or;\n    nullptr,           // nb_int;\n    nullptr,           // nb_reserved;\n    nullptr,           // nb_float;\n\n    nullptr, // nb_inplace_add;\n    nullptr, // nb_inplace_subtract;\n    nullptr, // nb_inplace_multiply;\n    nullptr, // nb_inplace_remainder;\n    nullptr, // nb_inplace_power;\n    nullptr, // nb_inplace_lshift;\n    nullptr, // nb_inplace_rshift;\n    nullptr, // nb_inplace_and;\n    nullptr, // nb_inplace_xor;\n    nullptr, // nb_inplace_or;\n\n    nullptr, // nb_floor_divide;\n    nullptr, // nb_true_divide;\n    nullptr, // nb_inplace_floor_divide;\n    nullptr, // nb_inplace_true_divide;\n\n    nullptr, // nb_index;\n\n    nullptr, //nb_matrix_multiply;\n    nullptr  //nb_inplace_matrix_multiply;\n\n};\n\nPyObject *PyMatrix_data(PyObject *self, void *closure)\n{\n\n    PyMatrixObject *obj = (PyMatrixObject *)self;\n    Py_ssize_t width = obj->matrix->cols();\n    Py_ssize_t height = obj->matrix->rows();\n\n    PyObject *list = PyList_New(height);\n    for (int i = 0; i < height; i++)\n    {\n        PyObject *internal = PyList_New(width);\n\n        for (int j = 0; j < width; j++)\n        {\n            PyObject *value = PyFloat_FromDouble((*obj->matrix)(i, j));\n            PyList_SetItem(internal, j, value);\n        }\n\n        PyList_SetItem(list, i, internal);\n    }\n    return list;\n}\n\nPyObject *PyMatrix_rows(PyObject *self, void *closure)\n{\n    PyMatrixObject *obj = (PyMatrixObject *)self;\n    return Py_BuildValue(\"i\", obj->matrix->rows());\n}\n\nPyObject *PyMatrix_cols(PyObject *self, void *closure)\n{\n    PyMatrixObject *obj = (PyMatrixObject *)self;\n    return Py_BuildValue(\"i\", obj->matrix->cols());\n}\n\nstatic PyGetSetDef MatrixGetSet[] = {\n    {\"data\", (getter)PyMatrix_data, nullptr, nullptr},\n    {\"row\", (getter)PyMatrix_rows, nullptr, nullptr},\n    {\"colunm\", (getter)PyMatrix_cols, nullptr, nullptr},\n    {nullptr}};\n\nPyObject *PyMatrix_tolist(PyObject *self, PyObject *args)\n{\n    return PyMatrix_data(self, nullptr);\n}\n\nstatic PyMethodDef MatrixMethods[] = {\n    {\"to_list\", (PyCFunction)PyMatrix_tolist, METH_VARARGS, \"Return the matrix data to a list object.\"},\n    {nullptr}};\n\nstatic PyTypeObject MatrixType = {\n    PyVarObject_HEAD_INIT(nullptr, 0) \"matrix.Matrix\", /* tp_name */\n    sizeof(PyMatrixObject),                            /* tp_basicsize */\n    0,                                                 /* tp_itemsize */\n    (destructor)PyMatrix_dealloc,                      /* tp_dealloc */\n    nullptr,                                           /* tp_print */\n    nullptr,                                           /* tp_getattr */\n    nullptr,                                           /* tp_setattr */\n    nullptr,                                           /* tp_reserved */\n    nullptr,                                           /* tp_repr */\n    &numberMethods,                                    /* tp_as_number */\n    nullptr,                                           /* tp_as_sequence */\n    nullptr,                                           /* tp_as_mapping */\n    nullptr,                                           /* tp_hash  */\n    nullptr,                                           /* tp_call */\n    PyMatrix_str,                                      /* tp_str */\n    nullptr,                                           /* tp_getattro */\n    nullptr,                                           /* tp_setattro */\n    nullptr,                                           /* tp_as_buffer */\n    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,          /* tp_flags */\n    \"Coustom matrix class.\",                           /* tp_doc */\n    nullptr,                                           /* tp_traverse */\n    nullptr,                                           /* tp_clear */\n    nullptr,                                           /* tp_richcompare */\n    0,                                                 /* tp_weaklistoffset */\n    nullptr,                                           /* tp_iter */\n    nullptr,                                           /* tp_iternext */\n    MatrixMethods,                                     /* tp_methods */\n    nullptr,                                           /* tp_members */\n    MatrixGetSet,                                      /* tp_getset */\n    nullptr,                                           /* tp_base */\n    nullptr,                                           /* tp_dict */\n    nullptr,                                           /* tp_descr_get */\n    nullptr,                                           /* tp_descr_set */\n    0,                                                 /* tp_dictoffset */\n    nullptr,                                           /* tp_init */\n    nullptr,                                           /* tp_alloc */\n    PyMatrix_new                                       /* tp_new */\n};\n\nstatic PyObject *PyMatrix_ones(PyObject *self, PyObject *args, PyObject *kwargs)\n{\n    PyMatrixObject *m = (PyMatrixObject *)PyMatrix_new(&MatrixType, args, kwargs);\n    m->matrix->setOnes();\n    return (PyObject *)m;\n}\n\nstatic PyObject *PyMatrix_zeros(PyObject *self, PyObject *args, PyObject *kwargs)\n{\n    PyMatrixObject *m = (PyMatrixObject *)PyMatrix_new(&MatrixType, args, kwargs);\n    m->matrix->setZero();\n    return (PyObject *)m;\n}\n\nstatic PyObject *PyMatrix_random(PyObject *self, PyObject *args, PyObject *kwargs)\n{\n    PyMatrixObject *m = (PyMatrixObject *)PyMatrix_new(&MatrixType, args, kwargs);\n    m->matrix->setRandom();\n    return (PyObject *)m;\n}\n\nstatic PyObject *PyMatrix_matrix(PyObject *self, PyObject *args)\n{\n    PyObject *data = nullptr;\n    if (!PyArg_ParseTuple(args, \"O\", &data))\n    {\n        PyErr_SetString(PyExc_ValueError, \"Please pass a 2 dimensions list object. 1\");\n        return nullptr;\n    }\n    if (!PyList_Check(data))\n    {\n        PyErr_SetString(PyExc_ValueError, \"Please pass a 2 dimensions list object. 2\");\n        return nullptr;\n    }\n    int height = PyList_GET_SIZE(data);\n    if (height <= 0)\n    {\n        PyErr_SetString(PyExc_ValueError, \"Please pass a 2 dimensions list object. 2\");\n        return nullptr;\n    }\n    PyObject *list = PyList_GET_ITEM(data, 0);\n    if (!PyList_Check(list))\n    {\n        PyErr_SetString(PyExc_ValueError, \"Please pass a 2 dimensions list object. 3\");\n        return nullptr;\n    }\n    int width = PyList_GET_SIZE(list);\n    MatrixXd *p_mat = new MatrixXd(width, height);\n    for (int i = 0; i < height; i++)\n    {\n        PyObject *list = PyList_GET_ITEM(data, i);\n        if (!PyList_Check(list))\n        {\n            PyErr_SetString(PyExc_ValueError, \"Please pass a 2 dimensions list object. 3\");\n            return nullptr;\n        }\n        int tmp = PyList_GET_SIZE(list);\n        if (width != tmp)\n        {\n            PyErr_SetString(PyExc_ValueError, \"Please pass a 2 dimensions list object. Each elements of it must be the same length.\");\n            return nullptr;\n        }\n        width = tmp;\n\n        for (int j = 0; j < width; j++)\n        {\n            PyObject *num = PyList_GET_ITEM(list, j);\n            if (!PyFloat_Check(num))\n            {\n                PyErr_SetString(PyExc_ValueError, \"Every elements of the matrix must float.\");\n                return nullptr;\n            }\n            (*p_mat)(i, j) = ((PyFloatObject *)num)->ob_fval;\n        }\n    }\n\n    return ReturnMatrix(p_mat, &MatrixType);\n}\n\nstatic PyMethodDef matrixMethods[] = {\n    {\"ones\", (PyCFunction)PyMatrix_ones, METH_VARARGS | METH_KEYWORDS, \"Return a new matrix with initial values one.\"},\n    {\"zeros\", (PyCFunction)PyMatrix_zeros, METH_VARARGS | METH_KEYWORDS, \"Return a new matrix with initial values zero.\"},\n    {\"random\", (PyCFunction)PyMatrix_random, METH_VARARGS | METH_KEYWORDS, \"Return a new matrix with random values\"},\n    {\"matrix\", (PyCFunction)PyMatrix_matrix, METH_VARARGS, \"Return a new matrix with given values\"},\n    {nullptr}};\n\nstatic struct PyModuleDef module = {\n    PyModuleDef_HEAD_INIT,\n    \"matrix\",\n    \"Python interface for Matrix calculation\",\n    -1,\n    matrixMethods};\n\nPyObject *initModule(void)\n{\n    PyObject *m;\n    if (PyType_Ready(&MatrixType) < 0)\n        return NULL;\n\n    m = PyModule_Create(&module);\n    if (m == NULL)\n        return NULL;\n\n    Py_INCREF(&MatrixType);\n    if (PyModule_AddObject(m, \"Matrix\", (PyObject *)&MatrixType) < 0)\n    {\n        Py_DECREF(&MatrixType);\n        Py_DECREF(m);\n        return NULL;\n    }\n\n    return m;\n}", "meta": {"hexsha": "1ac695e97f770e3c36c5c21cb37a811a948b05ee", "size": 11949, "ext": "cc", "lang": "C++", "max_stars_repo_path": "PythonExtention/python_matrix.cc", "max_stars_repo_name": "ChineseBoyLY/CMakeTutorial", "max_stars_repo_head_hexsha": "0f494462f75a46a68b76c3ced0b729c7750e1adb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 637.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T08:44:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T06:27:16.000Z", "max_issues_repo_path": "PythonExtention/python_matrix.cc", "max_issues_repo_name": "ChineseBoyLY/CMakeTutorial", "max_issues_repo_head_hexsha": "0f494462f75a46a68b76c3ced0b729c7750e1adb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-03-01T06:30:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T02:24:52.000Z", "max_forks_repo_path": "PythonExtention/python_matrix.cc", "max_forks_repo_name": "ChineseBoyLY/CMakeTutorial", "max_forks_repo_head_hexsha": "0f494462f75a46a68b76c3ced0b729c7750e1adb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 177.0, "max_forks_repo_forks_event_min_datetime": "2020-02-13T06:52:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T06:27:17.000Z", "avg_line_length": 33.2841225627, "max_line_length": 134, "alphanum_fraction": 0.5508410746, "num_tokens": 2755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.766293653760418, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.4684981261588293}}
{"text": "/* ----------------------------------------------------------------------------\n\n * GTSAM Copyright 2010-2020, 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  TimeOfArrivalExample.cpp\n *  @brief Track a moving object \"Time of Arrival\" measurements at 4\n * microphones.\n *  @author Frank Dellaert\n *  @author Jay Chakravarty\n *  @date March 2020\n */\n\n#include <gtsam/nonlinear/LevenbergMarquardtOptimizer.h>\n#include <gtsam/nonlinear/NonlinearFactorGraph.h>\n#include <gtsam/nonlinear/expressions.h>\n#include <gtsam_unstable/geometry/Event.h>\n#include <gtsam_unstable/slam/TOAFactor.h>\n\n#include <boost/format.hpp>\n\n#include <vector>\n\nusing namespace std;\nusing namespace gtsam;\n\n// units\nstatic const double ms = 1e-3;\nstatic const double cm = 1e-2;\n\n// Instantiate functor with speed of sound value\nstatic const TimeOfArrival kTimeOfArrival(330);\n\n/* ************************************************************************* */\n// Create microphones\nvector<Point3> defineMicrophones() {\n  const double height = 0.5;\n  vector<Point3> microphones;\n  microphones.push_back(Point3(0, 0, height));\n  microphones.push_back(Point3(403 * cm, 0, height));\n  microphones.push_back(Point3(403 * cm, 403 * cm, height));\n  microphones.push_back(Point3(0, 403 * cm, 2 * height));\n  return microphones;\n}\n\n/* ************************************************************************* */\n// Create ground truth trajectory\nvector<Event> createTrajectory(size_t n) {\n  vector<Event> trajectory;\n  double timeOfEvent = 10;\n  // simulate emitting a sound every second while moving on straight line\n  for (size_t key = 0; key < n; key++) {\n    trajectory.push_back(\n        Event(timeOfEvent, 245 * cm + key * 1.0, 201.5 * cm, (212 - 45) * cm));\n    timeOfEvent += 1;\n  }\n  return trajectory;\n}\n\n/* ************************************************************************* */\n// Simulate time-of-arrival measurements for a single event\nvector<double> simulateTOA(const vector<Point3>& microphones,\n                           const Event& event) {\n  size_t K = microphones.size();\n  vector<double> simulatedTOA(K);\n  for (size_t i = 0; i < K; i++) {\n    simulatedTOA[i] = kTimeOfArrival(event, microphones[i]);\n  }\n  return simulatedTOA;\n}\n\n/* ************************************************************************* */\n// Simulate time-of-arrival measurements for an entire trajectory\nvector<vector<double>> simulateTOA(const vector<Point3>& microphones,\n                                   const vector<Event>& trajectory) {\n  vector<vector<double>> simulatedTOA;\n  for (auto event : trajectory) {\n    simulatedTOA.push_back(simulateTOA(microphones, event));\n  }\n  return simulatedTOA;\n}\n\n/* ************************************************************************* */\n// create factor graph\nNonlinearFactorGraph createGraph(const vector<Point3>& microphones,\n                                 const vector<vector<double>>& simulatedTOA) {\n  NonlinearFactorGraph graph;\n\n  // Create a noise model for the TOA error\n  auto model = noiseModel::Isotropic::Sigma(1, 0.5 * ms);\n\n  size_t K = microphones.size();\n  size_t key = 0;\n  for (auto toa : simulatedTOA) {\n    for (size_t i = 0; i < K; i++) {\n      graph.emplace_shared<TOAFactor>(key, microphones[i], toa[i], model);\n    }\n    key += 1;\n  }\n  return graph;\n}\n\n/* ************************************************************************* */\n// create initial estimate for n events\nValues createInitialEstimate(size_t n) {\n  Values initial;\n\n  Event zero;\n  for (size_t key = 0; key < n; key++) {\n    initial.insert(key, zero);\n  }\n  return initial;\n}\n\n/* ************************************************************************* */\nint main(int argc, char* argv[]) {\n  // Create microphones\n  auto microphones = defineMicrophones();\n  size_t K = microphones.size();\n  for (size_t i = 0; i < K; i++) {\n    cout << \"mic\" << i << \" = \" << microphones[i] << endl;\n  }\n\n  // Create a ground truth trajectory\n  const size_t n = 5;\n  auto groundTruth = createTrajectory(n);\n\n  // Simulate time-of-arrival measurements\n  auto simulatedTOA = simulateTOA(microphones, groundTruth);\n  for (size_t key = 0; key < n; key++) {\n    for (size_t i = 0; i < K; i++) {\n      cout << \"z_\" << key << i << \" = \" << simulatedTOA[key][i] / ms << \" ms\"\n           << endl;\n    }\n  }\n\n  // Create factor graph\n  auto graph = createGraph(microphones, simulatedTOA);\n\n  // Create initial estimate\n  auto initialEstimate = createInitialEstimate(n);\n  initialEstimate.print(\"Initial Estimate:\\n\");\n\n  // Optimize using Levenberg-Marquardt optimization.\n  LevenbergMarquardtParams params;\n  params.setAbsoluteErrorTol(1e-10);\n  params.setVerbosityLM(\"SUMMARY\");\n  LevenbergMarquardtOptimizer optimizer(graph, initialEstimate, params);\n  Values result = optimizer.optimize();\n  result.print(\"Final Result:\\n\");\n}\n/* ************************************************************************* */\n", "meta": {"hexsha": "8d496a30ec66daed89a3a86d20b8ed3b522acb1c", "size": 5148, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam_unstable/examples/TimeOfArrivalExample.cpp", "max_stars_repo_name": "h-rover/gtsam", "max_stars_repo_head_hexsha": "a0206e210d8f47b6ee295a1fbf95af84d98c5cf0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1402.0, "max_stars_repo_stars_event_min_datetime": "2017-03-28T00:18:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T10:28:32.000Z", "max_issues_repo_path": "gtsam_unstable/examples/TimeOfArrivalExample.cpp", "max_issues_repo_name": "h-rover/gtsam", "max_issues_repo_head_hexsha": "a0206e210d8f47b6ee295a1fbf95af84d98c5cf0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 851.0, "max_issues_repo_issues_event_min_datetime": "2017-11-27T15:09:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T22:26:38.000Z", "max_forks_repo_path": "gtsam_unstable/examples/TimeOfArrivalExample.cpp", "max_forks_repo_name": "h-rover/gtsam", "max_forks_repo_head_hexsha": "a0206e210d8f47b6ee295a1fbf95af84d98c5cf0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 565.0, "max_forks_repo_forks_event_min_datetime": "2017-11-30T16:15:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T02:53:04.000Z", "avg_line_length": 32.175, "max_line_length": 80, "alphanum_fraction": 0.5755633256, "num_tokens": 1244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859598, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.46849811963265797}}
{"text": "/*\n * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 <libint2/initialize.h>\n#define BOOST_TEST_MAIN\n\n#define BOOST_TEST_MODULE density_integration_test\n\n// Standard includes\n#include <fstream>\n\n// Third party includes\n#include <boost/test/unit_test.hpp>\n\n// Local VOTCA includes\n#include \"votca/tools/eigenio_matrixmarket.h\"\n#include \"votca/xtp/density_integration.h\"\n#include \"votca/xtp/orbitals.h\"\n#include \"votca/xtp/vxc_grid.h\"\n\nusing namespace votca::xtp;\nusing namespace std;\n\nBOOST_AUTO_TEST_SUITE(density_integration_test)\n\nAOBasis CreateBasis(const QMMolecule& mol) {\n\n  BasisSet basis;\n  basis.Load(std::string(XTP_TEST_DATA_FOLDER) +\n             \"/densityintegration/3-21G.xml\");\n  AOBasis aobasis;\n  aobasis.Fill(basis, mol);\n  return aobasis;\n}\n\nBOOST_AUTO_TEST_CASE(density_test) {\n  libint2::initialize();\n  QMMolecule mol(\"none\", 0);\n\n  mol.LoadFromFile(std::string(XTP_TEST_DATA_FOLDER) +\n                   \"/densityintegration/molecule.xyz\");\n  AOBasis aobasis = CreateBasis(mol);\n\n  Eigen::MatrixXd dmat = votca::tools::EigenIO_MatrixMarket::ReadMatrix(\n      std::string(XTP_TEST_DATA_FOLDER) + \"/densityintegration/dmat.mm\");\n\n  Vxc_Grid grid;\n  grid.GridSetup(\"medium\", mol, aobasis);\n  DensityIntegration<Vxc_Grid> num(grid);\n\n  double ntot = num.IntegrateDensity(dmat);\n  BOOST_CHECK_CLOSE(ntot, 8.000000, 1e-5);\n\n  Eigen::Vector3d pos = {3, 3, 3};\n\n  BOOST_CHECK_CLOSE(num.IntegratePotential(pos), -1.543242, 1e-4);\n\n  Eigen::Vector3d field = num.IntegrateField(pos);\n  Eigen::Vector3d field_ref = {0.172802, 0.172802, 0.172802};\n  bool field_check = field.isApprox(field_ref, 1e-5);\n  if (!field_check) {\n    std::cout << \"field\" << std::endl;\n    std::cout << field.transpose() << std::endl;\n    std::cout << \"ref\" << std::endl;\n    std::cout << field_ref.transpose() << std::endl;\n  }\n  libint2::finalize();\n}\n\nBOOST_AUTO_TEST_CASE(gyration_test) {\n  libint2::initialize();\n  ofstream xyzfile(\"molecule.xyz\");\n  xyzfile << \" 5\" << endl;\n  xyzfile << \" methane\" << endl;\n  xyzfile << \" C            1.000000     1.000000     1.000000\" << endl;\n  xyzfile << \" H            1.629118     1.629118     1.629118\" << endl;\n  xyzfile << \" H           0.370882    0.370882     1.629118\" << endl;\n  xyzfile << \" H            1.629118    0.370882    0.370882\" << endl;\n  xyzfile << \" H           0.370882     1.629118   0.370882\" << endl;\n  xyzfile.close();\n\n  QMMolecule mol(\"none\", 0);\n\n  mol.LoadFromFile(\"molecule.xyz\");\n  AOBasis aobasis = CreateBasis(mol);\n\n  Eigen::MatrixXd dmat = votca::tools::EigenIO_MatrixMarket::ReadMatrix(\n      std::string(XTP_TEST_DATA_FOLDER) + \"/densityintegration/dmat.mm\");\n  Vxc_Grid grid;\n  grid.GridSetup(\"medium\", mol, aobasis);\n  DensityIntegration<Vxc_Grid> num(grid);\n\n  Gyrationtensor tensor = num.IntegrateGyrationTensor(dmat);\n  BOOST_CHECK_CLOSE(tensor.mass, 8.0000005, 1e-5);\n\n  Eigen::Vector3d dip_ref = Eigen::Vector3d::Zero();\n  dip_ref << 1.88973, 1.88973, 1.88973;\n  bool centroid_check = dip_ref.isApprox(tensor.centroid, 1e-5);\n  BOOST_CHECK_EQUAL(centroid_check, true);\n  if (!centroid_check) {\n    std::cout << \"centroid\" << std::endl;\n    std::cout << tensor.centroid.transpose() << std::endl;\n    std::cout << \"ref\" << std::endl;\n    std::cout << dip_ref.transpose() << std::endl;\n  }\n  Eigen::Matrix3d gyro_ref = Eigen::Matrix3d::Zero();\n  gyro_ref << 0.596158, 2.85288e-12, 2.86873e-12, 2.85289e-12, 0.596158,\n      2.87163e-12, 2.86874e-12, 2.87161e-12, 0.596158;\n  bool gyro_check = gyro_ref.isApprox(tensor.gyration, 1e-5);\n  BOOST_CHECK_EQUAL(gyro_check, true);\n  if (!gyro_check) {\n    std::cout << \"gyro\" << std::endl;\n    std::cout << tensor.gyration << std::endl;\n    std::cout << \"ref\" << std::endl;\n    std::cout << gyro_ref << std::endl;\n  }\n\n  libint2::finalize();\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "619ecc4bc89c9b652f9b979d6fffdca48fbd85f5", "size": 4343, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/tests/test_densityintegration.cc", "max_stars_repo_name": "rubengerritsen/xtp", "max_stars_repo_head_hexsha": "af4db53ca99853280d0e2ddc7f3c41bce8ae6e91", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/tests/test_densityintegration.cc", "max_issues_repo_name": "rubengerritsen/xtp", "max_issues_repo_head_hexsha": "af4db53ca99853280d0e2ddc7f3c41bce8ae6e91", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tests/test_densityintegration.cc", "max_forks_repo_name": "rubengerritsen/xtp", "max_forks_repo_head_hexsha": "af4db53ca99853280d0e2ddc7f3c41bce8ae6e91", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4104477612, "max_line_length": 75, "alphanum_fraction": 0.6799447387, "num_tokens": 1313, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.46849811963265797}}
{"text": "#include<iostream>\n#include <vector>\n#include <tuple>\n#include <float.h>\n#include <numeric>\n#include <Eigen/Dense>\n#include \"../nanoflann.hpp\"\n#include \"gsec.hpp\"\n#include \"utils.hpp\"\n#include \"icp.hpp\"\n#include \"../SO3.hpp\"\n\n\nusing namespace nanoflann;\nusing namespace Geometry;\n\n//\n// Robust ICP\n//\n\nicp::Icp::Icp(icp::PointCloud &P, icp::PointCloud &M): \n    resultSet(1), \n    m_index(dim, std::cref(M), 10),\n    p_index(dim, P, 10)\n{\n    // std::cout << \"T: \" << this->T << std::endl;\n    // std::cout<<\"&P = \"<<&P<<std::endl;\n    this->P = &P;\n    // std::cout<<\"&this->P = \"<<(this->P)<<std::endl;\n    this->Np = P.rows();\n    this->M = &M;\n    // \n    this->constructKDTree();\n    //\n    this->resultSet.init(&(this->m_ret_index), &(this->m_out_dist_sqr));\n    this->closestPtsFinder = &icp::Icp::closestpoints;\n}\n\n\n/**\n * if reciprocal is true, reject points based on eps,\n * otherwise based on a mutual closeness\n*/\nicp::Icp::Icp(icp::PointCloud &P, icp::PointCloud &M, bool reciprocal): icp::Icp(P, M)\n{\n    this->reciprocal = reciprocal;\n    if(this->reciprocal) this->closestPtsFinder = &icp::Icp::closestpointsReciprocal;\n}\n\n/**\n * update iterations and distances vector\n*/\nvoid icp::Icp::init()\n{\n    this->iter++;\n    this->initdists();\n}\n\n/**\n * clear ditances vector content\n*/\nvoid icp::Icp::initdists()\n{\n    // initialize heap\n    this->distances.clear();\n    // std::cout<< std::distance(distances.begin(), distances.begin()+Npo) << std::endl;\n    // std::cout<< mse_cost(distances, xi) << std::endl;\n    std::make_heap(this->distances.begin(), this->distances.end(), icp::comparePairs);\n}\n\n\n/**\n * find corresponces in the two pointclouds and compute distances.\n * kdtree is used\n*/\nvoid icp::Icp::closestpoints()\n{\n    // Step 1: Closest Point\n    for (size_t i = 0; i < this->Np; i++)\n    {\n        this->resultSet.init(&(this->m_ret_index), &(this->m_out_dist_sqr));\n        this->p_query_pt = {(*this->P)(i,0), (*this->P)(i,1), (*this->P)(i,2)};//{-15.7116, -10.9587, 0.650531};\n        // \n        this->m_index.index->findNeighbors(\n            this->resultSet, \n            &this->p_query_pt[0],\n            nanoflann::SearchParams(10));\n\n        // wrong pair rejection\n        if(icp::rejectWrongPair(*this->M, this->m_ret_index, this->p_index, i)) continue;\n    \n        // update heap(distance)\n        std::tuple<float, int, int> tmpDist = std::make_tuple(this->m_out_dist_sqr, i, this->m_ret_index);\n        this->distances.push_back(tmpDist);\n        std::push_heap(this->distances.begin(), this->distances.end(), icp::comparePairs);\n        \n    }\n}\n\n/**\n * using Reciprocal: Geometric criterion\n*/\nvoid icp::Icp::closestpointsReciprocal()\n{\n    // Step 1: Closest Point\n    for (size_t i = 0; i < this->Np; i++)\n    {\n        \n        this->resultSet.init(&(this->m_ret_index), &(this->m_out_dist_sqr));\n        //auto query_ptt = P.row(i);\n        this->p_query_pt = {(*this->P)(i,0), (*this->P)(i,1), (*this->P)(i,2)};\n        // \n        this->m_index.index->findNeighbors(\n            this->resultSet, \n            &this->p_query_pt[0],\n            nanoflann::SearchParams(10));\n\n        std::vector<float> m_query_pt = {(*this->M)(this->m_ret_index,0), (*this->M)(this->m_ret_index,1), (*this->M)(this->m_ret_index,2)};\n        // wrong pair rejection\n        if(icp::rejectWrongPair(\n            m_query_pt, *this->P, this->p_index, i, \n            this->eps)) \n            continue;\n    \n        std::tuple<float, int, int> tmpDist = std::make_tuple(this->m_out_dist_sqr, i, this->m_ret_index);\n        this->distances.push_back(tmpDist);\n        std::push_heap(this->distances.begin(), this->distances.end(), icp::comparePairs);\n        \n    }\n    std::sort_heap(this->distances.begin(), this->distances.end(),  icp::comparePairs);\n    // auto [ dist, pidx, midx ] = this->distances[0];\n    // std::cout << \"dist: \" << dist << std::endl;\n}\n\nvoid icp::Icp::updateNpo()\n{\n    this->Npo = this->distances.size();//< Npo? distances.size():Npo;\n    // std::cout << \"Npo = \" << Npo << std::endl;\n}\n\n\n/**\n * calculate squared distances and mean squared error (mse)\n*/\nvoid icp::Icp::calculateErrors()\n{\n    this->updateNpo();\n    // this->Npo = this->distances.size();\n    // Step 2: Squares\n    this->Sts = std::accumulate(this->distances.begin(), this->distances.begin()+this->Npo, 0.0, icp::tupleAccumulateOP);\n    // MSE\n    this->e = this->Sts / this->Npo;\n\n}\n\nbool icp::Icp::convergencetest()\n{\n    // Step 3: Convergence test\n    return (\n        this->e <= this->mse_tol || \n        std::abs(this->e - this->e_prev)/this->e <= this->tol || \n        this->iter > this->Niter);// ||\n        //std::abs(Sts-Stsprime) <= stsTolerance) \n    \n}\n\nvoid icp::Icp::constructKDTree()\n{\n    // this->m_index(this->dim, std::cref(this->M), 10);\n    // this->m_index.index->buildIndex();\n    // // for Geometric criteria: rejecting wrong point pairs\n    // this->p_index.index->buildIndex();\n}\n\nvoid icp::Icp::calculateMotion()\n{\n    // Step 4: Motion Calculation\n    // https://igl.ethz.ch/projects/ARAP/svd_rot.pdf\n    // select Npo points\n    icp::PointCloud A(this->Npo, this->dim), B(this->Npo, this->dim);\n    for (size_t i = 0; i < (this->Npo); i++)\n    {\n        auto [ dist, pidx, midx ] = this->distances[i];\n        // std::cout<<\"dist = \"<<dist<<std::endl;\n        A.row(i) = this->P->row(pidx);\n        B.row(i) = this->M->row(midx);\n    }\n\n    Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> umeyama = Eigen::umeyama(A.transpose(), B.transpose(), false);\n    // std::cout << \"The matrix umeyama is of size \"\n    //         << umeyama.rows() << \"x\" << umeyama.cols() << std::endl;\n    // std::cout << \"Transformation: \" << std::endl << umeyama << std::endl;\n    this->R = umeyama.block(0,0,3,3);\n    this->t  = umeyama.block(0,3,3,1);\n\n    // std::cout << \"rotation error = \" <<\n    //             std::acos(((\n    //                 this->R.transpose().array() * this->Rtotal.array()).matrix().trace() - 1) / 2.0 \n    //                 ) * 180.f/M_PI << \n    //             std::endl;\n\n    this->Rtotal = this->R * this->Rtotal;\n    this->T = umeyama * this->T;\n    this->ttotal = this->t + this->ttotal;\n    // auto centerA = A.colwise().mean();\n    // auto centerB = B.colwise().mean();\n    \n    // A.rowwise() -= centerA;\n    // B.rowwise() -= centerB;\n    \n    // icp::PointCloud H = A.transpose()*B;\n    // Eigen::BDCSVD<Eigen::Matrix<float, -1, -1> > svd(H,Eigen::ComputeFullU | Eigen::ComputeFullV);\n    \n    // // Rotation\n    // this->R = svd.matrixV() * svd.matrixU().transpose();\n    // // Translation\n    // this->t = centerB.transpose() - this->R * centerA.transpose();\n}\n\nvoid icp::Icp::transform()\n{\n    // affine transformation\n    (*this->P) = (R * (this->P->transpose())).transpose();\n    (*this->P).rowwise() += this->t.transpose();\n    // t.col(0)\n}\n\nvoid icp::Icp::updateParameters()\n{\n    // update parameters\n    // float* rng = gss(mse_cost, distances, 0.4, 1.0);\n    // xi = (rng[0] + rng[1])/ 2.f; //0.5; // 1 -> ICP\n    // Npo = xi*Np;\n    \n    (this->p_index).index->buildIndex();\n    (this->e_prev) = this->e;\n    (this->Stsprime) = this->Sts;\n}\n\n/**\n * calculate rotaion error using Log(R_gt*R).norm()\n*/\nfloat icp::Icp::rotationError(Eigen::Matrix3f R)\n{\n    // Eigen::Matrix3f Rt = this->Rtotal;\n    Eigen::Matrix3f Rt = this->T.block(0,0,3,3);\n    Eigen::Matrix3f rotE = R * (Rt).transpose();\n    // std::cout << \"Log(rotE): \" << SO3::Log(rotE).transpose() << std::endl;\n    // std::cout << \"||Log(rotE)||_2: \" << SO3::Log(rotE).norm() << std::endl;\n    return SO3::Log(rotE).norm() * 180.f / M_PI;\n\n}\n\nvoid icp::Icp::run()\n{\n    do\n    {\n        // initialize heap\n        this->init();\n\n        // Step 1: Closest Point\n        // if(this->reciprocal)\n        //     this->closestpoints(this->eps);\n        // else this->closestpoints();\n        (this->*closestPtsFinder)();\n        \n        // Step 2: Trimmed Squares\n        this->calculateErrors();\n            \n        // Step 3: Convergence test\n        if(this->convergencetest()) break;\n\n        // Step 4: Motion Calculation\n        this->calculateMotion();\n\n        // Step 5: Transformation\n        this->transform();\n        \n        // Step 6: update parameters\n        this->updateParameters();\n\n    } while (true);\n}\n\n// getters\nsize_t icp::Icp::getIter()\n{\n    return this->iter;\n}\nsize_t icp::Icp::getNpo()\n{\n    return this->Npo;\n}\nfloat icp::Icp::getSts()\n{\n    return this->Sts;\n}\nfloat icp::Icp::getMse()\n{\n    return this->e;\n}\n\n/**\n * return the accumulated rotation matrix\n*/\nicp::PointCloud icp::Icp::getR()\n{\n    return this->T.block(0,0,3,3);\n    // return this->Rtotal;\n}\n\n/**\n * return the accumulated translation vector\n*/\nEigen::Vector3f icp::Icp::getT()\n{\n    return this->T.block(0,3,3,1);\n    // return   this->ttotal;\n}\n//\nicp::Icp::~Icp()\n{\n    this->P = NULL;\n    delete this->P;\n    this->M = NULL;\n    delete this->M;\n    // this->closestPtsFinder = NULL;\n    // delete this->closestPtsFinder;\n}\n\n\n//\n// Trimmed Icp\n//\n// Constructors\nicp::TrIcp::TrIcp(icp::PointCloud& P, icp::PointCloud& M): icp::Icp(P, M)\n{\n    this->Npo = this->xi * this->Np;\n}\n\nicp::TrIcp::TrIcp(icp::PointCloud& P, icp::PointCloud& M, float xi): icp::Icp(P, M)\n{\n    this->xi = xi;\n    this->Npo = xi * this->Np;\n}\n\n// public methods\nvoid icp::TrIcp::closestpoints()\n{\n    // Step 1: Closest Point\n    for (size_t i = 0; i < this->Np; i++)\n    {\n        this->resultSet.init(&(this->m_ret_index), &(this->m_out_dist_sqr));\n        this->p_query_pt = {(*this->P)(i,0), (*this->P)(i,1), (*this->P)(i,2)};//{-15.7116, -10.9587, 0.650531};\n        // \n        this->m_index.index->findNeighbors(\n            this->resultSet, \n            &this->p_query_pt[0],\n            nanoflann::SearchParams(10));\n\n    \n        // update heap(distance)\n        std::tuple<float, int, int> tmpDist = std::make_tuple(this->m_out_dist_sqr, i, this->m_ret_index);\n        this->distances.push_back(tmpDist);\n        std::push_heap(this->distances.begin(), this->distances.end(), icp::comparePairs);\n        \n    }\n    std::sort_heap(this->distances.begin(), this->distances.end(),  icp::comparePairs);\n    // auto [ dist, pidx, midx ] = this->distances[0];\n    // std::cout << \"dist: \" << dist << std::endl;\n}\n\nvoid icp::TrIcp::updateNpo()\n{\n    if(!this->isUpdatedNpo)\n    {\n        float* rng = gss(mse_cost, this->distances, 0.4, 1.0);\n        this->xi = (rng[0] + rng[1])/ 2.f; //0.5; // 1 -> ICP\n        this->Npo = this->xi * this->Np;\n        //\n        // this->isUpdatedNpo = true;\n    }\n}\n\nvoid icp::TrIcp::updateParameters()\n{\n    (this->e_prev) = this->e;\n    (this->Stsprime) = this->Sts;\n}\n\n\n// destructor   \nicp::TrIcp::~TrIcp()\n{\n}", "meta": {"hexsha": "a43b6ce4998bf55cd8d95140f7bbe1d67e648750", "size": 10678, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/icp.cpp", "max_stars_repo_name": "SohilZidan/point-cloud-registration", "max_stars_repo_head_hexsha": "5e7f52fbf04f3a58238a2c92393143d5e110c8e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/icp.cpp", "max_issues_repo_name": "SohilZidan/point-cloud-registration", "max_issues_repo_head_hexsha": "5e7f52fbf04f3a58238a2c92393143d5e110c8e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-11-27T17:52:07.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-28T07:04:05.000Z", "max_forks_repo_path": "src/icp.cpp", "max_forks_repo_name": "SohilZidan/point-cloud-registration", "max_forks_repo_head_hexsha": "5e7f52fbf04f3a58238a2c92393143d5e110c8e4", "max_forks_repo_licenses": ["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.0329113924, "max_line_length": 140, "alphanum_fraction": 0.5640569395, "num_tokens": 3364, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.4684981196326579}}
{"text": "/*------------------------------------------------------*/\n/* Biological Engineering: Problem Set 03               */\n/* main program                                         */\n/*                                                      */\n/* file name    :   BiologicalEngineering_set3.cpp      */\n/* compiler     :   gcc                                 */\n/* Student ID   :   1526084                             */\n/* author       :   Takaharu Nakajima                   */\n/* date         :   2016.11.11                          */\n/* memo         :   \u001b$B@8BN9)3XBh;02sL\\$N\u001b(B1.1\u001b$B$+$i\u001b(B1.3\u001b$B$N\u001b(B      */\n/*                  \u001b$B%W%m%0%i%`$r$^$H$a$?$b$N$K$J$j$^$9\u001b(B  */\n/*                                                      */\n/*                  \u001b$B0lItJQ?t$NDj5A$N$?$aJQ99$7$?ItJ,\u001b(B    */\n/*                  (\u001b$BNc\u001b(B)                                */\n/*                  RT0 -> RTa                          */\n/*                  \u001b$B$3$N$h$&$K\u001b(B0, 1...E\u001b$B$r\u001b(Ba, b...E\u001b$B$K\u001b(B      */\n/*                  \u001b$BJQ99$7$^$7$?\u001b(B                        */\n/*                                                      */\n/*------------------------------------------------------*/\n\n#include <iostream>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\nusing namespace std;\nusing namespace Eigen;\n\n#define PI 3.1415926\n\ndouble deg2rad(double degree)\n{\n    double radian = degree * PI / 180.0f;\n    return radian;\n}\n\nint main()\n{\n    double deg1, deg2, deg3, deg4, deg5;\n    double rad1, rad2, rad3, rad4, rad5;\n    Matrix<double,4,4> RTa, aTb, bTc, cTd, dTe, eTf, fTg;\n    Matrix<double,4,4> RTb, RTc, RTd, RTe, RTf, RTg;\n    Vector3d RZa, RZb, RZc, RZd, RZe, RZf, RZg;\n    Vector3d Rpa, Rpb, Rpc, Rpd, Rpe, Rpf, Rpg;\n    Vector3d RpEa, RpEb, RpEc, RpEd, RpEe, RpEf, RpEg;\n\n    /* Input */\n    cout << \"Angle input\" << endl;\n    cout << \"deg1= \";\n    cin >> deg1;\n    cout << \"deg2= \";\n    cin >> deg2;\n    cout << \"deg3= \";\n    cin >> deg3;\n    cout << \"deg4= \";\n    cin >> deg4;\n    cout << \"deg5= \";\n    cin >> deg5;\n\n    /* Convert to radians */\n    rad1 = deg2rad(deg1);\n    rad2 = deg2rad(deg2);\n    rad3 = deg2rad(deg3);\n    rad4 = deg2rad(deg4);\n    rad5 = deg2rad(deg5);\n\n    /* Link parameters */\n    RTa << 1, 0, 0, 0,\n           0, 1, 0, 0, \n           0, 0, 1, 1, \n           0, 0, 0, 1;\n    aTb << cos(rad1), -sin(rad1), 0, 0,\n           sin(rad1),  cos(rad1), 0, 0,\n                   0,          0, 1, 0,\n                   0,          0, 0, 1;\n    bTc << cos(rad2), -sin(rad2), 0, 0,\n                   0,          0, -1, 0,\n           sin(rad2),  cos(rad2), 0, 0, \n                   0,          0, 0, 1;\n    cTd << cos(rad3), -sin(rad3), 0, 1,\n           sin(rad3),  cos(rad3), 0, 0, \n                   0,          0, 1, 0, \n                   0,          0, 0, 1;\n    dTe << cos(rad4), -sin(rad4), 0, 1,\n           sin(rad4),  cos(rad4), 0, 0, \n                   0,          0, 1, 0, \n                   0,          0, 0, 1;\n    eTf << cos(rad5), -sin(rad5), 0, 0,\n                   0,          0, -1, 0,\n           sin(rad5),  cos(rad5), 0, 0, \n                   0,          0, 0, 1;\n    fTg << 1, 0, 0, 0, \n           0, 1, 0, 0, \n           0, 0, 1, 1, \n           0, 0, 0, 1; \n\n    /* Matrix calculation */\n    RTb = RTa * aTb;\n    RTc = RTb * bTc;\n    RTd = RTc * cTd;\n    RTe = RTd * dTe;\n    RTf = RTe * eTf;\n    RTg = RTf * fTg;\n\n    RZa = RTa.block<3,1>(0,2);\n    RZb = RTb.block<3,1>(0,2);\n    RZc = RTc.block<3,1>(0,2);\n    RZd = RTd.block<3,1>(0,2);\n    RZe = RTe.block<3,1>(0,2);\n    RZf = RTf.block<3,1>(0,2);\n    RZg = RTg.block<3,1>(0,2);\n\n    Rpa = RTa.block<3,1>(0,3);\n    Rpb = RTb.block<3,1>(0,3);\n    Rpc = RTc.block<3,1>(0,3);\n    Rpd = RTd.block<3,1>(0,3);\n    Rpe = RTe.block<3,1>(0,3);\n    Rpf = RTf.block<3,1>(0,3);\n    Rpg = RTg.block<3,1>(0,3);\n\n    RpEa = Rpg - Rpa;\n    RpEb = Rpg - Rpb;\n    RpEc = Rpg - Rpc;\n    RpEd = Rpg - Rpd;\n    RpEe = Rpg - Rpe;\n    RpEf = Rpg - Rpf;\n    RpEg = Rpg - Rpg;\n    \n    /* Calculation result display */\n    /* RT0 ~ 3TE */\n    cout << \"RT0=\" << endl;\n    cout << RTa << endl;\n    cout << \"0T1=\" << endl;\n    cout << aTb << endl;\n    cout << \"1T2=\" << endl;\n    cout << bTc << endl;\n    cout << \"2T3=\" << endl;\n    cout << cTd << endl;\n    cout << \"3T4=\" << endl;\n    cout << dTe << endl;\n    cout << \"4T5=\" << endl;\n    cout << eTf << endl;\n    cout << \"5T6=\" << endl;\n    cout << fTg << endl << endl;\n\n    /* RZ0 ~ RZE */\n    cout << \"RZ0=\" << endl;\n    cout << RZa << endl;\n    cout << \"RZ1=\" << endl;\n    cout << RZb << endl;\n    cout << \"RZ2=\" << endl;\n    cout << RZc << endl;\n    cout << \"RZ3=\" << endl;\n    cout << RZd << endl;\n    cout << \"RZ4=\" << endl;\n    cout << RZe << endl;\n    cout << \"RZ5=\" << endl;\n    cout << RZf << endl;\n    cout << \"RZ6=\" << endl;\n    cout << RZg << endl;\n\n    /* Rp0 ~ Rp1 */\n    cout << \"Rp0=\" << endl;\n    cout << Rpa << endl;\n    cout << \"Rp1=\" << endl;\n    cout << Rpb << endl;\n    cout << \"Rp2=\" << endl;\n    cout << Rpc << endl;\n    cout << \"Rp3=\" << endl;\n    cout << Rpd << endl;\n    cout << \"Rp4=\" << endl;\n    cout << Rpe << endl;\n    cout << \"Rp5=\" << endl;\n    cout << Rpf << endl;\n    cout << \"Rp6=\" << endl;\n    cout << Rpg << endl;\n\n    /* RZ0 x RpE,0 ~ RZE x RpE,E */\n    cout << \"RZ0 x RpE,0=\" << endl;\n    cout << RZa.cross(RpEa) << endl;\n    cout << \"RZ1 x RpE,1=\" << endl;\n    cout << RZb.cross(RpEb) << endl;\n    cout << \"RZ2 x RpE,2=\" << endl;\n    cout << RZc.cross(RpEc) << endl;\n    cout << \"RZ3 x RpE,3=\" << endl;\n    cout << RZd.cross(RpEd) << endl;\n    cout << \"RZ4 x RpE,4=\" << endl;\n    cout << RZe.cross(RpEe) << endl;\n    cout << \"RZ5 x RpE,5=\" << endl;\n    cout << RZf.cross(RpEf) << endl;\n    cout << \"RZ6 x RpE,6=\" << endl;\n    cout << RZg.cross(RpEg) << endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "9446197738e8b743fb18bd860fa2fc9fc0897ebd", "size": 5737, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/BiologicalEngineering_set4.cpp", "max_stars_repo_name": "takayan660/RobotArm_Simulator", "max_stars_repo_head_hexsha": "f9c5d8da5660d9586c43c0b4181ca4157aab5034", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-09-15T03:17:51.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-15T03:17:51.000Z", "max_issues_repo_path": "src/BiologicalEngineering_set4.cpp", "max_issues_repo_name": "takayan660/RobotArm_Simulator", "max_issues_repo_head_hexsha": "f9c5d8da5660d9586c43c0b4181ca4157aab5034", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-11-19T21:11:17.000Z", "max_issues_repo_issues_event_max_datetime": "2017-11-19T21:11:17.000Z", "max_forks_repo_path": "src/BiologicalEngineering_set4.cpp", "max_forks_repo_name": "tAkayan660/RobotArm_Simulator", "max_forks_repo_head_hexsha": "f9c5d8da5660d9586c43c0b4181ca4157aab5034", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-15T03:38:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-15T03:38:32.000Z", "avg_line_length": 29.4205128205, "max_line_length": 76, "alphanum_fraction": 0.3866132125, "num_tokens": 2174, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920211198871, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4684858257185639}}
{"text": "/*\n* Copyright (c) by CryptoLab inc.\n* This program is licensed under a\n* Creative Commons Attribution-NonCommercial 3.0 Unported License.\n* You should have received a copy of the license along with this\n* work.  If not, see <http://creativecommons.org/licenses/by-nc/3.0/>.\n*/\n\n#include \"RingMultiplier.h\"\n\n#include <NTL/BasicThreadPool.h>\n#include <NTL/tools.h>\n#include <cmath>\n#include <cstdlib>\n#include <iterator>\n\nRingMultiplier::RingMultiplier() {\n\n\tuint64_t primetest = (1ULL << pbnd) + 1;\n\tfor (long i = 0; i < nprimes; ++i) {\n\t\twhile(true) {\n\t\t\tprimetest += M;\n\t\t\tif(primeTest(primetest)) {\n\t\t\t\tpVec[i] = primetest;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tfor (long i = 0; i < nprimes; ++i) {\n\t\tred_ss_array[i] = _ntl_general_rem_one_struct_build(pVec[i]);\n\t\tpInvVec[i] = inv(pVec[i]);\n\t\tprVec[i] = (static_cast<unsigned __int128>(1) << kbar2) / pVec[i];\n\t\tuint64_t root = findMthRootOfUnity(M, pVec[i]);\n\t\tuint64_t rootinv = invMod(root, pVec[i]);\n\t\tuint64_t NInv = invMod(N, pVec[i]);\n\t\tmulMod(scaledNInv[i], NInv, (1ULL << 32), pVec[i]);\n\t\tmulMod(scaledNInv[i], scaledNInv[i], (1ULL << 32), pVec[i]);\n\t\tscaledRootPows[i] = new uint64_t[N]();\n\t\tscaledRootInvPows[i] = new uint64_t[N]();\n\t\tuint64_t power = 1;\n\t\tuint64_t powerInv = 1;\n\t\tfor (long j = 0; j < N; ++j) {\n\t\t\tuint32_t jprime = bitReverse(static_cast<uint32_t>(j)) >> (32 - logN);\n\t\t\tuint64_t rootpow = power;\n\t\t\tmulMod(scaledRootPows[i][jprime], rootpow,(1ULL << 32), pVec[i]);\n\t\t\tmulMod(scaledRootPows[i][jprime], scaledRootPows[i][jprime], (1ULL << 32), pVec[i]);\n\t\t\tuint64_t rootpowInv = powerInv;\n\t\t\tmulMod(scaledRootInvPows[i][jprime], rootpowInv, (1ULL << 32), pVec[i]);\n\t\t\tmulMod(scaledRootInvPows[i][jprime], scaledRootInvPows[i][jprime], (1ULL << 32), pVec[i]);\n\t\t\tmulMod(power, power, root, pVec[i]);\n\t\t\tmulMod(powerInv, powerInv, rootinv, pVec[i]);\n\t\t}\n\t}\n\n\tfor (long i = 0; i < nprimes; ++i) {\n\t\tcoeffpinv_array[i] = new mulmod_precon_t[i + 1];\n\t\tpProd[i] = (i == 0) ? to_ZZ((long) pVec[i]) : pProd[i - 1] * (long) pVec[i];\n\t\tpProdh[i] = pProd[i] / 2;\n\t\tpHat[i] = new ZZ[i + 1];\n\t\tpHatInvModp[i] = new uint64_t[i + 1];\n\t\tfor (long j = 0; j < i + 1; ++j) {\n\t\t\tpHat[i][j] = ZZ(1);\n\t\t\tfor (long k = 0; k < j; ++k) {\n\t\t\t\tpHat[i][j] *= (long) pVec[k];\n\t\t\t}\n\t\t\tfor (long k = j + 1; k < i + 1; ++k) {\n\t\t\t\tpHat[i][j] *= (long) pVec[k];\n\t\t\t}\n\t\t\tpHatInvModp[i][j] = to_long(pHat[i][j] % (long) pVec[j]);\n\t\t\tpHatInvModp[i][j] = invMod(pHatInvModp[i][j], pVec[j]);\n\t\t\tcoeffpinv_array[i][j] = PrepMulModPrecon(pHatInvModp[i][j], pVec[j]);\n\t\t}\n\t}\n}\n\nbool RingMultiplier::primeTest(uint64_t p) {\n\tif(p < 2) return false;\n\tif(p != 2 && p % 2 == 0) return false;\n\tuint64_t s = p - 1;\n\twhile(s % 2 == 0) {\n\t\ts /= 2;\n\t}\n\tfor(long i = 0; i < 200; i++) {\n\t\tuint64_t temp1 = rand();\n\t\ttemp1  = (temp1 << 32) | rand();\n\t\ttemp1 = temp1 % (p - 1) + 1;\n\t\tuint64_t temp2 = s;\n\t\tuint64_t mod = powMod(temp1,temp2,p);\n\t\twhile (temp2 != p - 1 && mod != 1 && mod != p - 1) {\n\t\t\tmulMod(mod, mod, mod, p);\n\t\t    temp2 *= 2;\n\t\t}\n\t\tif (mod != p - 1 && temp2 % 2 == 0) return false;\n\t}\n\treturn true;\n}\n\nvoid RingMultiplier::NTT(uint64_t* a, long index) {\n\tlong t = N;\n\tlong logt1 = logN + 1;\n\tuint64_t p = pVec[index];\n\tuint64_t pInv = pInvVec[index];\n\tfor (long m = 1; m < N; m <<= 1) {\n\t\tt >>= 1;\n\t\tlogt1 -= 1;\n\t\tfor (long i = 0; i < m; i++) {\n\t\t\tlong j1 = i << logt1;\n\t\t\tlong j2 = j1 + t - 1;\n\t\t\tuint64_t W = scaledRootPows[index][m + i];\n\t\t\tfor (long j = j1; j <= j2; j++) {\n\t\t\t\tbutt(a[j], a[j+t], W, p, pInv);\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid RingMultiplier::INTT(uint64_t* a, long index) {\n\tuint64_t p = pVec[index];\n\tuint64_t pInv = pInvVec[index];\n\tlong t = 1;\n\tfor (long m = N; m > 1; m >>= 1) {\n\t\tlong j1 = 0;\n\t\tlong h = m >> 1;\n\t\tfor (long i = 0; i < h; i++) {\n\t\t\tlong j2 = j1 + t - 1;\n\t\t\tuint64_t W = scaledRootInvPows[index][h + i];\n\t\t\tfor (long j = j1; j <= j2; j++) {\n\t\t\t\tibutt(a[j], a[j+t], W, p, pInv);\n\t\t\t}\n\t\t\tj1 += (t << 1);\n\t\t}\n\t\tt <<= 1;\n\t}\n\n\tuint64_t NScale = scaledNInv[index];\n\tfor (long i = 0; i < N; i++) {\n\t\tidivN(a[i], NScale, p, pInv);\n\t}\n}\n\n//----------------------------------------------------------------------------------\n//   FFT\n//----------------------------------------------------------------------------------\n\nvoid RingMultiplier::CRT(uint64_t* rx, ZZ* x, const long np) {\n\tNTL_EXEC_RANGE(np, first, last);\n\tfor (long i = first; i < last; ++i) {\n\t\tuint64_t* rxi = rx + (i << logN);\n\t\tuint64_t pi = pVec[i];\n\t\t_ntl_general_rem_one_struct* red_ss = red_ss_array[i];\n\t\tfor (long n = 0; n < N; ++n) {\n\t\t\trxi[n] = _ntl_general_rem_one_struct_apply(x[n].rep, pi, red_ss);\n\t\t}\n\t\tNTT(rxi, i);\n\t}\n\tNTL_EXEC_RANGE_END;\n}\n\nvoid RingMultiplier::addNTTAndEqual(uint64_t* ra, uint64_t* rb, const long np) {\n\tfor (long i = 0; i < np; ++i) {\n\t\tuint64_t* rai = ra + (i << logN);\n\t\tuint64_t* rbi = rb + (i << logN);\n\t\tuint64_t pi = pVec[i];\n\t\tfor (long n = 0; n < N; ++n) {\n\t\t\trai[n] += rbi[n];\n\t\t\tif(rai[n] > pi) rai[n] -= pi;\n\t\t}\n\t}\n}\n\nvoid RingMultiplier::reconstruct(ZZ* x, uint64_t* rx, long np, const ZZ& q) {\n\tZZ* pHatnp = pHat[np - 1];\n\tuint64_t* pHatInvModpnp = pHatInvModp[np - 1];\n\tmulmod_precon_t* coeffpinv_arraynp = coeffpinv_array[np - 1];\n\tZZ& pProdnp = pProd[np - 1];\n\tZZ& pProdhnp = pProdh[np - 1];\n\tNTL_EXEC_RANGE(N, first, last);\n\tfor (long n = first; n < last; ++n) {\n\t\tZZ& acc = x[n];\n\t\tQuickAccumBegin(acc, pProdnp.size());\n\t\tfor (long i = 0; i < np; i++) {\n\t\t\tlong p = pVec[i];\n\t\t\tlong tt = pHatInvModpnp[i];\n\t\t\tmulmod_precon_t ttpinv = coeffpinv_arraynp[i];\n\t\t\tlong s = MulModPrecon(rx[n + (i << logN)], tt, p, ttpinv);\n\t\t\tQuickAccumMulAdd(acc, pHatnp[i], s);\n\t\t}\n\t\tQuickAccumEnd(acc);\n\t\trem(x[n], x[n], pProdnp);\n\t\tif (x[n] > pProdhnp) x[n] -= pProdnp;\n\t\tx[n] %= q;\n\t}\n\tNTL_EXEC_RANGE_END;\n}\n\nvoid RingMultiplier::mult(ZZ* x, ZZ* a, ZZ* b, long np, const ZZ& mod) {\n\tuint64_t* ra = new uint64_t[np << logN]();\n\tuint64_t* rb = new uint64_t[np << logN]();\n\tuint64_t* rx = new uint64_t[np << logN]();\n\n\tNTL_EXEC_RANGE(np, first, last);\n\tfor (long i = first; i < last; ++i) {\n\t\tuint64_t* rai = ra + (i << logN);\n\t\tuint64_t* rbi = rb + (i << logN);\n\t\tuint64_t* rxi = rx + (i << logN);\n\t\tuint64_t pi = pVec[i];\n\t\tuint64_t pri = prVec[i];\n\t\t_ntl_general_rem_one_struct* red_ss = red_ss_array[i];\n\t\tfor (long n = 0; n < N; ++n) {\n\t\t\trai[n] = _ntl_general_rem_one_struct_apply(a[n].rep, pi, red_ss);\n\t\t\trbi[n] = _ntl_general_rem_one_struct_apply(b[n].rep, pi, red_ss);\n\t\t}\n\t\tNTT(rai, i);\n\t\tNTT(rbi, i);\n\t\tfor (long n = 0; n < N; ++n) {\n\t\t\tmulModBarrett(rxi[n], rai[n], rbi[n], pi, pri);\n\t\t}\n\t\tINTT(rxi, i);\n\t}\n\tNTL_EXEC_RANGE_END;\n\n\treconstruct(x, rx, np, mod);\n\n\tdelete[] ra;\n\tdelete[] rb;\n\tdelete[] rx;\n}\n\nvoid RingMultiplier::multNTT(ZZ* x, ZZ* a, uint64_t* rb, long np, const ZZ& mod) {\n\tuint64_t* ra = new uint64_t[np << logN]();\n\tuint64_t* rx = new uint64_t[np << logN]();\n\tNTL_EXEC_RANGE(np, first, last);\n\tfor (long i = first; i < last; ++i) {\n\t\tuint64_t* rai = ra + (i << logN);\n\t\tuint64_t* rbi = rb + (i << logN);\n\t\tuint64_t* rxi = rx + (i << logN);\n\t\tuint64_t pi = pVec[i];\n\t\tuint64_t pri = prVec[i];\n\t\t_ntl_general_rem_one_struct* red_ss = red_ss_array[i];\n\t\tfor (long n = 0; n < N; ++n) {\n\t\t\trai[n] = _ntl_general_rem_one_struct_apply(a[n].rep, pi, red_ss);\n\t\t}\n\t\tNTT(rai, i);\n\t\tfor (long n = 0; n < N; ++n) {\n\t\t\tmulModBarrett(rxi[n], rai[n], rbi[n], pi, pri);\n\t\t}\n\t\tINTT(rxi, i);\n\t}\n\tNTL_EXEC_RANGE_END;\n\n\treconstruct(x, rx, np, mod);\n\n\tdelete[] ra;\n\tdelete[] rx;\n}\n\nvoid RingMultiplier::multDNTT(ZZ* x, uint64_t* ra, uint64_t* rb, long np, const ZZ& mod) {\n\tuint64_t* rx = new uint64_t[np << logN]();\n\n\tNTL_EXEC_RANGE(np, first, last);\n\tfor (long i = first; i < last; ++i) {\n\t\tuint64_t* rai = ra + (i << logN);\n\t\tuint64_t* rbi = rb + (i << logN);\n\t\tuint64_t* rxi = rx + (i << logN);\n\t\tuint64_t pi = pVec[i];\n\t\tuint64_t pri = prVec[i];\n\t\tfor (long n = 0; n < N; ++n) {\n\t\t\tmulModBarrett(rxi[n], rai[n], rbi[n], pi, pri);\n\t\t}\n\t\tINTT(rxi, i);\n\t}\n\tNTL_EXEC_RANGE_END;\n\n\treconstruct(x, rx, np, mod);\n\n\tdelete[] rx;\n}\n\nvoid RingMultiplier::multAndEqual(ZZ* a, ZZ* b, long np, const ZZ& mod) {\n\tuint64_t* ra = new uint64_t[np << logN]();\n\tuint64_t* rb = new uint64_t[np << logN]();\n\n\tNTL_EXEC_RANGE(np, first, last);\n\tfor (long i = first; i < last; ++i) {\n\t\tuint64_t* rai = ra + (i << logN);\n\t\tuint64_t* rbi = rb + (i << logN);\n\t\tuint64_t pi = pVec[i];\n\t\tuint64_t pri = prVec[i];\n\t\t_ntl_general_rem_one_struct* red_ss = red_ss_array[i];\n\t\tfor (long n = 0; n < N; ++n) {\n\t\t\trai[n] = _ntl_general_rem_one_struct_apply(a[n].rep, pi, red_ss);\n\t\t\trbi[n] = _ntl_general_rem_one_struct_apply(b[n].rep, pi, red_ss);\n\t\t}\n\t\tNTT(rai, i);\n\t\tNTT(rbi, i);\n\t\tfor (long n = 0; n < N; ++n) {\n\t\t\tmulModBarrett(rai[n], rai[n], rbi[n], pi, pri);\n\t\t}\n\t\tINTT(rai, i);\n\t}\n\tNTL_EXEC_RANGE_END;\n\n\tZZ* pHatnp = pHat[np - 1];\n\tuint64_t* pHatInvModpnp = pHatInvModp[np - 1];\n\n\treconstruct(a, ra, np, mod);\n\n\tdelete[] ra;\n\tdelete[] rb;\n}\n\nvoid RingMultiplier::multNTTAndEqual(ZZ* a, uint64_t* rb, long np, const ZZ& mod) {\n\tuint64_t* ra = new uint64_t[np << logN]();\n\n\tNTL_EXEC_RANGE(np, first, last);\n\tfor (long i = first; i < last; ++i) {\n\t\tuint64_t* rai = ra + (i << logN);\n\t\tuint64_t* rbi = rb + (i << logN);\n\t\tuint64_t pi = pVec[i];\n\t\tuint64_t pri = prVec[i];\n\t\t_ntl_general_rem_one_struct* red_ss = red_ss_array[i];\n\t\tfor (long n = 0; n < N; ++n) {\n\t\t\trai[n] = _ntl_general_rem_one_struct_apply(a[n].rep, pi, red_ss);\n\t\t}\n\t\tNTT(rai, i);\n\t\tfor (long n = 0; n < N; ++n) {\n\t\t\tmulModBarrett(rai[n], rai[n], rbi[n], pi, pri);\n\t\t}\n\t\tINTT(rai, i);\n\t}\n\tNTL_EXEC_RANGE_END;\n\n\tZZ* pHatnp = pHat[np - 1];\n\tuint64_t* pHatInvModpnp = pHatInvModp[np - 1];\n\n\treconstruct(a, ra, np, mod);\n\n\tdelete[] ra;\n}\n\n\nvoid RingMultiplier::square(ZZ* x, ZZ* a, long np, const ZZ& mod) {\n\tuint64_t* ra = new uint64_t[np << logN]();\n\tuint64_t* rx = new uint64_t[np << logN]();\n\n\tNTL_EXEC_RANGE(np, first, last);\n\tfor (long i = first; i < last; ++i) {\n\t\tuint64_t* rai = ra + (i << logN);\n\t\tuint64_t* rxi = rx + (i << logN);\n\t\tuint64_t pi = pVec[i];\n\t\tuint64_t pri = prVec[i];\n\t\t_ntl_general_rem_one_struct* red_ss = red_ss_array[i];\n\t\tfor (long n = 0; n < N; ++n) {\n\t\t\trai[n] = _ntl_general_rem_one_struct_apply(a[n].rep, pi, red_ss);\n\t\t}\n\t\tNTT(rai, i);\n\t\tfor (long n = 0; n < N; ++n) {\n\t\t\tmulModBarrett(rxi[n], rai[n], rai[n], pi, pri);\n\t\t}\n\t\tINTT(rxi, i);\n\t}\n\tNTL_EXEC_RANGE_END;\n\n\tZZ* pHatnp = pHat[np - 1];\n\tuint64_t* pHatInvModpnp = pHatInvModp[np - 1];\n\n\treconstruct(x, rx, np, mod);\n\n\tdelete[] ra;\n\tdelete[] rx;\n}\n\nvoid RingMultiplier::squareNTT(ZZ* x, uint64_t* ra, long np, const ZZ& mod) {\n\tuint64_t* rx = new uint64_t[np << logN]();\n\n\tNTL_EXEC_RANGE(np, first, last);\n\tfor (long i = first; i < last; ++i) {\n\t\tuint64_t* rai = ra + (i << logN);\n\t\tuint64_t* rxi = rx + (i << logN);\n\t\tuint64_t pi = pVec[i];\n\t\tuint64_t pri = prVec[i];\n\t\tfor (long n = 0; n < N; ++n) {\n\t\t\tmulModBarrett(rxi[n], rai[n], rai[n], pi, pri);\n\t\t}\n\t\tINTT(rxi, i);\n\t}\n\tNTL_EXEC_RANGE_END;\n\n\treconstruct(x, rx, np, mod);\n\n\tdelete[] rx;\n}\n\nvoid RingMultiplier::squareAndEqual(ZZ* a, long np, const ZZ& mod) {\n\tuint64_t* ra = new uint64_t[np << logN]();\n\n\tNTL_EXEC_RANGE(np, first, last);\n\tfor (long i = first; i < last; ++i) {\n\t\tuint64_t* rai = ra + (i << logN);\n\t\tuint64_t pi = pVec[i];\n\t\tuint64_t pri = prVec[i];\n\t\t_ntl_general_rem_one_struct* red_ss = red_ss_array[i];\n\t\tfor (long n = 0; n < N; ++n) {\n\t\t\trai[n] = _ntl_general_rem_one_struct_apply(a[n].rep, pi, red_ss);\n\t\t}\n\t\tNTT(rai, i);\n\t\tfor (long n = 0; n < N; ++n) {\n\t\t\tmulModBarrett(rai[n], rai[n], rai[n], pi, pri);\n\t\t}\n\t\tINTT(rai, i);\n\t}\n\tNTL_EXEC_RANGE_END;\n\n\treconstruct(a, ra, np, mod);\n\n\tdelete[] ra;\n}\n\nvoid RingMultiplier::mulMod(uint64_t &r, uint64_t a, uint64_t b, uint64_t m) {\n\tunsigned __int128 mul = static_cast<unsigned __int128>(a) * b;\n\tmul %= static_cast<unsigned __int128>(m);\n\tr = static_cast<uint64_t>(mul);\n}\n\nvoid RingMultiplier::mulModBarrett(uint64_t& r, uint64_t a, uint64_t b, uint64_t p, uint64_t pr) {\n\tunsigned __int128 mul = static_cast<unsigned __int128>(a) * b;\n\tuint64_t abot = static_cast<uint64_t>(mul);\n\tuint64_t atop = static_cast<uint64_t>(mul >> 64);\n\tunsigned __int128 tmp = static_cast<unsigned __int128>(abot) * pr;\n\ttmp >>= 64;\n\ttmp += static_cast<unsigned __int128>(atop) * pr;\n\ttmp >>= kbar2 - 64;\n\ttmp *= p;\n\ttmp = mul - tmp;\n\tr = static_cast<uint64_t>(tmp);\n\tif(r >= p) r -= p;\n}\n\nvoid RingMultiplier::butt(uint64_t& a, uint64_t& b, uint64_t W, uint64_t p, uint64_t pInv) {\n\tunsigned __int128 U = static_cast<unsigned __int128>(b) * W;\n\tuint64_t U0 = static_cast<uint64_t>(U);\n\tuint64_t U1 = U >> 64;\n\tuint64_t Q = U0 * pInv;\n\tunsigned __int128 Hx = static_cast<unsigned __int128>(Q) * p;\n\tuint64_t H = Hx >> 64;\n\tuint64_t V = U1 < H ? U1 + p - H : U1 - H;\n\tb = a < V ? a + p - V : a - V;\n\ta += V;\n\tif (a > p) a -= p;\n}\n\nvoid RingMultiplier::ibutt(uint64_t& a, uint64_t& b, uint64_t W, uint64_t p, uint64_t pInv) {\n\tuint64_t T = a < b ? a + p - b : a - b;\n\ta += b;\n\tif (a > p) a -= p;\n\tunsigned __int128 UU = static_cast<unsigned __int128>(T) * W;\n\tuint64_t U0 = static_cast<uint64_t>(UU);\n\tuint64_t U1 = UU >> 64;\n\tuint64_t Q = U0 * pInv;\n\tunsigned __int128 Hx = static_cast<unsigned __int128>(Q) * p;\n\tuint64_t H = Hx >> 64;\n\tb = (U1 < H) ? U1 + p - H : U1 - H;\n}\n\nvoid RingMultiplier::idivN(uint64_t& a, uint64_t NScale, uint64_t p, uint64_t pInv) {\n\tunsigned __int128 U = static_cast<unsigned __int128>(a) * NScale;\n\tuint64_t U0 = static_cast<uint64_t>(U);\n\tuint64_t U1 = U >> 64;\n\tuint64_t Q = U0 * pInv;\n\tunsigned __int128 Hx = static_cast<unsigned __int128>(Q) * p;\n\tuint64_t H = Hx >> 64;\n\ta = (U1 < H) ? U1 + p - H : U1 - H;\n}\n\nuint64_t RingMultiplier::invMod(uint64_t x, uint64_t m) {\n\treturn powMod(x, m - 2, m);\n}\n\nuint64_t RingMultiplier::powMod(uint64_t x, uint64_t y, uint64_t modulus) {\n\tuint64_t res = 1;\n\twhile (y > 0) {\n\t\tif (y & 1) {\n\t\t\tmulMod(res, res, x, modulus);\n\t\t}\n\t\ty = y >> 1;\n\t\tmulMod(x, x, x, modulus);\n\t}\n\treturn res;\n}\n\nuint64_t RingMultiplier::inv(uint64_t x) {\n\treturn pow(x, static_cast<uint64_t>(-1));\n}\n\nuint64_t RingMultiplier::pow(uint64_t x, uint64_t y) {\n\tuint64_t res = 1;\n\twhile (y > 0) {\n\t\tif (y & 1) {\n\t\t\tres *= x;\n\t\t}\n\t\ty = y >> 1;\n\t\tx *= x;\n\t}\n\treturn res;\n}\n\nuint32_t RingMultiplier::bitReverse(uint32_t x) {\n\tx = (((x & 0xaaaaaaaa) >> 1) | ((x & 0x55555555) << 1));\n\tx = (((x & 0xcccccccc) >> 2) | ((x & 0x33333333) << 2));\n\tx = (((x & 0xf0f0f0f0) >> 4) | ((x & 0x0f0f0f0f) << 4));\n\tx = (((x & 0xff00ff00) >> 8) | ((x & 0x00ff00ff) << 8));\n\treturn ((x >> 16) | (x << 16));\n}\n\nvoid RingMultiplier::findPrimeFactors(vector<uint64_t> &s, uint64_t number) {\n\twhile (number % 2 == 0) {\n\t\ts.push_back(2);\n\t\tnumber /= 2;\n\t}\n\tfor (uint64_t i = 3; i < sqrt(number); i++) {\n\t\twhile (number % i == 0) {\n\t\t\ts.push_back(i);\n\t\t\tnumber /= i;\n\t\t}\n\t}\n\tif (number > 2) {\n\t\ts.push_back(number);\n\t}\n}\n\nuint64_t RingMultiplier::findPrimitiveRoot(uint64_t modulus) {\n\tvector<uint64_t> s;\n\tuint64_t phi = modulus - 1;\n\tfindPrimeFactors(s, phi);\n\tfor (uint64_t r = 2; r <= phi; r++) {\n\t\tbool flag = false;\n\t\tfor (auto it = s.begin(); it != s.end(); it++) {\n\t\t\tif (powMod(r, phi / (*it), modulus) == 1) {\n\t\t\t\tflag = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (flag == false) {\n\t\t\treturn r;\n\t\t}\n\t}\n\treturn -1;\n}\n\nuint64_t RingMultiplier::findMthRootOfUnity(uint64_t M, uint64_t mod) {\n    uint64_t res;\n    res = findPrimitiveRoot(mod);\n    if((mod - 1) % M == 0) {\n        uint64_t factor = (mod - 1) / M;\n        res = powMod(res, factor, mod);\n        return res;\n    }\n    else {\n        return -1;\n    }\n}\n\n\n", "meta": {"hexsha": "5860b662079a6e4f604adce2103699549bcf0341", "size": 15327, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "HEAAN/src/RingMultiplier.cpp", "max_stars_repo_name": "Huelse/HEAAN-Python", "max_stars_repo_head_hexsha": "034ee757a7b7949d96b27d3228819dd9be6579ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2020-01-04T13:02:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T08:37:58.000Z", "max_issues_repo_path": "HEAAN/src/RingMultiplier.cpp", "max_issues_repo_name": "Huelse/PYHEAAN", "max_issues_repo_head_hexsha": "034ee757a7b7949d96b27d3228819dd9be6579ae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-07-03T09:43:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-02T08:30:56.000Z", "max_forks_repo_path": "HEAAN/src/RingMultiplier.cpp", "max_forks_repo_name": "Huelse/PYHEAAN", "max_forks_repo_head_hexsha": "034ee757a7b7949d96b27d3228819dd9be6579ae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-01-04T13:02:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-14T00:04:53.000Z", "avg_line_length": 27.1274336283, "max_line_length": 98, "alphanum_fraction": 0.5886996803, "num_tokens": 5901, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079209, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4684858201531015}}
{"text": "#include <boost_adaptbx/graph/graph_type.hpp>\n#include <boost_adaptbx/graph/graph_export_adaptor.hpp>\n#include <boost_adaptbx/graph/vertex_map.hpp>\n\n#include <boost_adaptbx/exporting.hpp>\n\n#include <boost/python/module.hpp>\n#include <boost/python/list.hpp>\n#include <boost/python/tuple.hpp>\n#include <boost/python/dict.hpp>\n#include <boost/python/def.hpp>\n#include <boost/python/extract.hpp>\n#include <boost/python/stl_iterator.hpp>\n\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/stoer_wagner_min_cut.hpp>\n#include <boost/graph/one_bit_color_map.hpp>\n#include <boost/graph/boykov_kolmogorov_max_flow.hpp>\n#include <boost/graph/graph_utility.hpp>\n#include <boost/graph/properties.hpp>\n\n#include <boost/mpl/if.hpp>\n#include <boost/type_traits.hpp>\n\n#include <iostream>\n\nnamespace boost_adaptbx\n{\n\ntemplate< typename Graph >\nstruct minimum_cut_export\n{\n  typedef boost::graph_traits< Graph > graph_traits;\n  typedef typename graph_traits::vertex_iterator vertex_iterator;\n  typedef typename graph_traits::edge_iterator edge_iterator;\n  typedef vertex_map::index_map< Graph > index_map_type;\n  typedef typename index_map_type::property_map_type index_property_map_type;\n  typedef boost::one_bit_color_map< index_property_map_type > parity_map_type;\n  typedef edge_map::generic_edge_map< Graph, double > edge_map_type;\n  typedef typename edge_map_type::property_map_type edge_property_map_type;\n\n  static boost::python::tuple stoer_wagner_minimum_cut(Graph const& graph)\n  {\n    index_map_type index_map( graph );\n    parity_map_type parities = boost::make_one_bit_color_map(\n      boost::num_vertices( graph ),\n      index_map.get()\n      );\n\n    edge_map_type edge_map( graph );\n    edge_property_map_type epropmap( edge_map.get() );\n    edge_iterator ei, ej;\n    double w;\n\n    for( boost::tie( ei, ej ) = boost::edges( graph ); ei != ej; ++ei )\n    {\n      w = boost::python::extract< double >( boost::get( boost::edge_weight, graph, *ei ) );\n      boost::put( epropmap, *ei, w);\n    }\n\n    w = boost::stoer_wagner_min_cut(\n      graph,\n      epropmap,\n      boost::parity_map( parities ).\n      vertex_index_map( index_map.get() )\n      );\n\n    vertex_iterator di, dj;\n    boost::python::list result;\n\n    for( boost::tie( di, dj ) = boost::vertices( graph ); di != dj; ++di )\n    {\n      result.append( bool( boost::get( parities, *di ) ) );\n    }\n\n    return boost::python::make_tuple( w, result );\n  }\n\n  static void process()\n  {\n    using namespace boost::python;\n\n    def( \"stoer_wagner_min_cut\", stoer_wagner_minimum_cut, arg( \"graph\" ) );\n  }\n};\n\nstruct min_cut_exporter\n{\n  template< typename Export >\n  void operator ()(boost::mpl::identity< Export > myexport) const\n  {\n    typedef typename Export::first graph_type;\n    typedef typename Export::second name_type;\n\n    typedef boost::graph_traits< graph_type > graph_traits;\n    typedef typename boost::mpl::if_<\n      boost::is_same<\n        typename  graph_traits::directed_category,\n        boost::undirected_tag\n        >,\n      minimum_cut_export< graph_type >,\n      graph_export_adaptor::no_export< graph_type >\n      >::type exporter_type;\n    exporter_type::process();\n  }\n};\n\ntemplate< typename Graph >\nstruct maximum_flow_export\n{\n  typedef boost::graph_traits< Graph > graph_traits;\n  typedef typename graph_traits::vertex_iterator vertex_iterator;\n  typedef typename graph_traits::vertex_descriptor vertex_descriptor;\n  typedef typename graph_traits::edge_iterator edge_iterator;\n  typedef typename graph_traits::edge_descriptor edge_descriptor;\n\n  typedef vertex_map::index_map< Graph > index_map_type;\n  typedef typename index_map_type::property_map_type index_property_map_type;\n\n  typedef edge_map::generic_edge_map< Graph, double > capacity_map_type;\n  typedef typename capacity_map_type::property_map_type capacity_property_map_type;\n\n  typedef edge_map::generic_edge_map< Graph, edge_descriptor > reverse_edge_map_type;\n  typedef typename reverse_edge_map_type::property_map_type reverse_edge_property_map_type;\n\n  typedef vertex_map::generic_vertex_map< Graph, boost::default_color_type > color_map_type;\n  typedef typename color_map_type::property_map_type color_property_map_type;\n\n  typedef graph_export_adaptor::vertex_descriptor_converter< vertex_descriptor > converter;\n\n  static boost::python::tuple boykov_kolmogorov_max_flow(\n    Graph const& graph,\n    boost::python::dict reverse_edge_map,\n    typename converter::type source,\n    typename converter::type sink\n    )\n  {\n    using namespace boost;\n    using namespace boost::python;\n\n    index_map_type index_map( graph );\n\n    capacity_map_type capmap( graph );\n    capacity_property_map_type cappropmap( capmap.get() );\n    edge_iterator ei, ej;\n\n    for( boost::tuples::tie( ei, ej ) = edges( graph ); ei != ej; ++ei )\n    {\n      double weight( extract< double >( get( edge_weight, graph, *ei ) ) );\n      boost::put( cappropmap, *ei, weight );\n    }\n\n    reverse_edge_map_type revmap( graph );\n    reverse_edge_property_map_type revpropmap( revmap.get() );\n\n    stl_input_iterator< object > end;\n\n    for( stl_input_iterator< object > it( reverse_edge_map.iteritems() ); it!=end; ++it)\n    {\n      edge_descriptor ed = extract< edge_descriptor >( (*it)[0] );\n      edge_descriptor red = extract< edge_descriptor >( (*it)[1] );\n      put( revpropmap, ed, red );\n    }\n\n    color_map_type colormap( graph );\n    color_property_map_type colorpropmap( colormap.get() );\n    capacity_map_type resicapmap( graph );\n\n    double w = boost::boykov_kolmogorov_max_flow(\n        graph,\n        cappropmap,\n        resicapmap.get(),\n        revpropmap,\n        colorpropmap,\n        index_map.get(),\n        converter::backward( source ),\n        converter::backward( sink )\n        );\n\n    vertex_iterator di, dj;\n    boost::python::list result;\n    default_color_type const black( color_traits< default_color_type >::black() );\n    default_color_type current;\n\n    for( boost::tie( di, dj ) = boost::vertices( graph ); di != dj; ++di )\n    {\n      current = get( colorpropmap, *di );\n      result.append( current == black );\n    }\n\n    return boost::python::make_tuple( w, result );\n  }\n\n  static void process()\n  {\n    using namespace boost::python;\n\n    def(\n      \"boykov_kolmogorov_max_flow\",\n      boykov_kolmogorov_max_flow,\n      ( arg( \"graph\" ), arg( \"reverse_edge_map\" ), arg( \"source\" ), arg( \"sink\" ) )\n      );\n  }\n};\n\nstruct max_flow_exporter\n{\n  template< typename Export >\n  void operator ()(boost::mpl::identity< Export > myexport) const\n  {\n    typedef typename Export::first graph_type;\n    typedef typename Export::second name_type;\n\n    typedef boost::graph_traits< graph_type > graph_traits;\n    typedef typename boost::mpl::if_<\n      boost::is_same<\n        typename  graph_traits::directed_category,\n        boost::directed_tag\n        >,\n      maximum_flow_export< graph_type >,\n      graph_export_adaptor::no_export< graph_type >\n      >::type exporter_type;\n    exporter_type::process();\n  }\n};\n\n} // namespace boost_adaptbx\n\nBOOST_PYTHON_MODULE(boost_adaptbx_graph_min_cut_max_flow_ext)\n{\n  boost_adaptbx::exporting::class_list< boost_adaptbx::graph_type::exports >::process(\n    boost_adaptbx::min_cut_exporter()\n    );\n  boost_adaptbx::exporting::class_list< boost_adaptbx::graph_type::exports >::process(\n    boost_adaptbx::max_flow_exporter()\n    );\n}\n", "meta": {"hexsha": "3dbf28471699f0eb44aae811f8e81343503af751", "size": 7339, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost_adaptbx/graph/min_cut_max_flow_ext.cpp", "max_stars_repo_name": "rimmartin/cctbx_project", "max_stars_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 155.0, "max_stars_repo_stars_event_min_datetime": "2016-11-23T12:52:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:35:44.000Z", "max_issues_repo_path": "boost_adaptbx/graph/min_cut_max_flow_ext.cpp", "max_issues_repo_name": "rimmartin/cctbx_project", "max_issues_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": 590.0, "max_issues_repo_issues_event_min_datetime": "2016-12-10T11:31:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T23:10:09.000Z", "max_forks_repo_path": "boost_adaptbx/graph/min_cut_max_flow_ext.cpp", "max_forks_repo_name": "rimmartin/cctbx_project", "max_forks_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 115.0, "max_forks_repo_forks_event_min_datetime": "2016-11-15T08:17:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T15:30:14.000Z", "avg_line_length": 30.8361344538, "max_line_length": 92, "alphanum_fraction": 0.7107235318, "num_tokens": 1774, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079208, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4684858201531014}}
{"text": "/*******************************************************************************\n *\n * Sparse DBM implementation, with the same underlying architecture\n * as SplitDBM\n *\n * Graeme Gange (gkgange@unimelb.edu.au)\n * Jorge A. Navas (jorge.navas@sri.com)\n ******************************************************************************/\n\n#pragma once\n\n#include <crab/domains/abstract_domain.hpp>\n#include <crab/domains/abstract_domain_params.hpp>\n#include <crab/domains/abstract_domain_specialized_traits.hpp>\n#include <crab/domains/backward_assign_operations.hpp>\n#include <crab/domains/graphs/graph_config.hpp>\n#include <crab/domains/graphs/graph_ops.hpp>\n#include <crab/domains/interval.hpp>\n#include <crab/support/debug.hpp>\n#include <crab/support/stats.hpp>\n\n#include <boost/container/flat_map.hpp>\n#include <boost/optional.hpp>\n#include <unordered_set>\n\n//#define CHECK_POTENTIAL\n//#define SDBM_NO_NORMALIZE\n\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wsign-compare\"\n\nnamespace crab {\n\nnamespace domains {\n\ntemplate <class Number, class VariableName,\n          class Params = DBM_impl::DefaultParams<Number>>\nclass sparse_dbm_domain final\n    : public abstract_domain_api<\n          sparse_dbm_domain<Number, VariableName, Params>> {\n  using DBM_t = sparse_dbm_domain<Number, VariableName, Params>;\n  using abstract_domain_t = abstract_domain_api<DBM_t>;\n\npublic:\n  using typename abstract_domain_t::disjunctive_linear_constraint_system_t;\n  using typename abstract_domain_t::interval_t;\n  using typename abstract_domain_t::linear_constraint_system_t;\n  using typename abstract_domain_t::linear_constraint_t;\n  using typename abstract_domain_t::linear_expression_t;\n  using typename abstract_domain_t::reference_constraint_t;\n  using typename abstract_domain_t::variable_or_constant_t;\n  using typename abstract_domain_t::variable_t;\n  using typename abstract_domain_t::variable_vector_t;\n  using typename abstract_domain_t::variable_or_constant_vector_t;    \n  using number_t = Number;\n  using varname_t = VariableName;\n  using constraint_kind_t = typename linear_constraint_t::kind_t;\n\nprivate:\n  using bound_t = ikos::bound<number_t>;\n  using Wt = typename Params::Wt;\n  using graph_t = typename Params::graph_t;\n  using ntow = DBM_impl::NtoW<number_t, Wt>;\n  using vert_id = typename graph_t::vert_id;\n  using vert_map_t = boost::container::flat_map<variable_t, vert_id>;\n  using vmap_elt_t = typename vert_map_t::value_type;\n  using rev_map_t = std::vector<boost::optional<variable_t>>;\n  using GrOps = GraphOps<graph_t>;\n  using GrPerm = GraphPerm<graph_t>;\n  using edge_vector = typename GrOps::edge_vector;\n  // < <x, y>, k> == x - y <= k.\n  using diffcst_t = std::pair<std::pair<variable_t, variable_t>, Wt>;\n  using vert_set_t = std::unordered_set<vert_id>;\n\nprotected:\n  //================\n  // Domain data\n  //================\n  vert_map_t vert_map; // Mapping from variables to vertices\n  rev_map_t rev_map;\n  graph_t g;                 // The underlying relation graph\n  std::vector<Wt> potential; // Stored potential for the vertex\n  vert_set_t unstable;\n  bool _is_bottom;\n\n  /*\n  void forget(std::vector<int> idxs) {\n    dbm ret = NULL;\n    ret = dbm_forget_array(&idxs[0], idxs.size(), _dbm);\n    dbm_dealloc(_dbm);\n    swap(_dbm, ret);\n  }\n  */\n\n  class Wt_max {\n  public:\n    Wt_max() {}\n    Wt apply(const Wt &x, const Wt &y) { return max(x, y); }\n    bool default_is_absorbing() { return true; }\n  };\n\n  class Wt_min {\n  public:\n    Wt_min() {}\n    Wt apply(const Wt &x, const Wt &y) { return std::min(x, y); }\n    bool default_is_absorbing() { return false; }\n  };\n\n  vert_id get_vert(variable_t v) {\n    auto it = vert_map.find(v);\n    if (it != vert_map.end())\n      return (*it).second;\n\n    vert_id vert(g.new_vertex());\n    // Initialize\n    assert(vert <= rev_map.size());\n    if (vert < rev_map.size()) {\n      assert(!rev_map[vert]);\n      potential[vert] = Wt(0);\n      rev_map[vert] = v;\n    } else {\n      potential.push_back(Wt(0));\n      rev_map.push_back(v);\n    }\n    vert_map.insert(vmap_elt_t(v, vert));\n\n    assert(vert != 0);\n\n    return vert;\n  }\n\n  vert_id get_vert(graph_t &g, vert_map_t &vmap, rev_map_t &rmap,\n                   std::vector<Wt> &pot, variable_t v) {\n    auto it = vmap.find(v);\n    if (it != vmap.end())\n      return (*it).second;\n\n    vert_id vert(g.new_vertex());\n    // vmap.insert(vmap_elt_t(v, vert));\n    // Initialize\n    assert(vert <= rmap.size());\n    if (vert < rmap.size()) {\n      assert(!rmap[vert]);\n      pot[vert] = Wt(0);\n      rmap[vert] = v;\n    } else {\n      pot.push_back(Wt(0));\n      rmap.push_back(v);\n    }\n    vmap.insert(vmap_elt_t(v, vert));\n\n    return vert;\n  }\n\n  template <class G, class P>\n  inline bool check_potential(const G &g, const P &p) const {\n#ifdef CHECK_POTENTIAL\n    for (vert_id v : g.verts()) {\n      for (vert_id d : g.succs(v)) {\n        if (p[v] + g.edge_val(v, d) - p[d] < Wt(0)) {\n          assert(0 && \"Invalid potential.\");\n          return false;\n        }\n      }\n    }\n#endif\n    return true;\n  }\n\n  class vert_set_wrap_t {\n  public:\n    vert_set_wrap_t(const vert_set_t &_vs) : vs(_vs) {}\n\n    bool operator[](vert_id v) const { return vs.find(v) != vs.end(); }\n    const vert_set_t &vs;\n  };\n\n  // Evaluate the potential value of a variable.\n  Wt pot_value(const variable_t &v) {\n    auto it = vert_map.find(v);\n    if (it != vert_map.end())\n      return potential[(*it).second];\n\n    return ((Wt)0);\n  }\n\n  // Evaluate an expression under the chosen potentials\n  Wt eval_expression(const linear_expression_t &e, bool &overflow) {\n    overflow = false;\n    Wt v(ntow::convert(e.constant(), overflow));\n    if (overflow) {\n      return Wt(0);\n    }\n\n    for (auto p : e) {\n      Wt coef = ntow::convert(p.first, overflow);\n      if (overflow) {\n        return Wt(0);\n      }\n      v += (pot_value(p.second) - potential[0]) * coef;\n    }\n    return v;\n  }\n\n  interval_t eval_interval(const linear_expression_t &e) {\n    interval_t r = e.constant();\n    for (auto p : e) {\n      r += p.first * operator[](p.second);\n    }\n    return r;\n  }\n\n  interval_t compute_residual(const linear_expression_t &e,\n                              const variable_t &pivot) {\n    interval_t residual(-e.constant());\n    for (auto kv : e) {\n      const variable_t &v = kv.second;\n      if (v.index() != pivot.index()) {\n        residual = residual - (interval_t(kv.first) * this->operator[](v));\n      }\n    }\n    return residual;\n  }\n\n  interval_t get_interval(const variable_t &x) const {\n    return get_interval(vert_map, g, x);\n  }\n\n  interval_t get_interval(const vert_map_t &m, const graph_t &g,\n                          const variable_t &x) const {\n    auto it = m.find(x);\n    if (it == m.end()) {\n      return interval_t::top();\n    }\n    vert_id v = (*it).second;\n    interval_t x_out = interval_t(\n        g.elem(v, 0) ? -number_t(g.edge_val(v, 0)) : bound_t::minus_infinity(),\n        g.elem(0, v) ? number_t(g.edge_val(0, v)) : bound_t::plus_infinity());\n    return x_out;\n  }\n\n  // Turn an assignment into a set of difference constraints.\n  void diffcsts_of_assign(const variable_t &x, const linear_expression_t &exp,\n                          std::vector<std::pair<variable_t, Wt>> &lb,\n                          std::vector<std::pair<variable_t, Wt>> &ub) {\n    {\n      // Process upper bounds.\n      boost::optional<variable_t> unbounded_ubvar;\n      bool overflow;\n\n      Wt exp_ub(ntow::convert(exp.constant(), overflow));\n      if (overflow) {\n        return;\n      }\n\n      std::vector<std::pair<variable_t, Wt>> ub_terms;\n      for (auto p : exp) {\n        Wt coeff(ntow::convert(p.first, overflow));\n        if (overflow) {\n          continue;\n        }\n        if (coeff < Wt(0)) {\n          // Can't do anything with negative coefficients.\n          bound_t y_lb = operator[](p.second).lb();\n          if (y_lb.is_infinite())\n            goto assign_ub_finish;\n          exp_ub += ntow::convert(*(y_lb.number()), overflow) * coeff;\n          if (overflow) {\n            continue;\n          }\n        } else {\n          variable_t y(p.second);\n          bound_t y_ub = operator[](y).ub();\n          if (y_ub.is_infinite()) {\n            if (unbounded_ubvar || coeff != Wt(1))\n              goto assign_ub_finish;\n            unbounded_ubvar = y;\n          } else {\n            Wt ymax(ntow::convert(*(y_ub.number()), overflow));\n            if (overflow) {\n              continue;\n            }\n            exp_ub += ymax * coeff;\n            ub_terms.push_back({y, ymax});\n          }\n        }\n      }\n\n      if (unbounded_ubvar) {\n        // There is exactly one unbounded variable.\n        ub.push_back({*unbounded_ubvar, exp_ub});\n      } else {\n        for (auto p : ub_terms) {\n          ub.push_back({p.first, exp_ub - p.second});\n        }\n      }\n    }\n  assign_ub_finish :\n\n  {\n    boost::optional<variable_t> unbounded_lbvar;\n    bool overflow;\n\n    Wt exp_lb(ntow::convert(exp.constant(), overflow));\n    if (overflow) {\n      return;\n    }\n    std::vector<std::pair<variable_t, Wt>> lb_terms;\n    for (auto p : exp) {\n      Wt coeff(ntow::convert(p.first, overflow));\n      if (overflow) {\n        continue;\n      }\n      if (coeff < Wt(0)) {\n        // Again, can't do anything with negative coefficients.\n        bound_t y_ub = operator[](p.second).ub();\n        if (y_ub.is_infinite())\n          goto assign_lb_finish;\n        exp_lb += (ntow::convert(*(y_ub.number()), overflow)) * coeff;\n        if (overflow) {\n          continue;\n        }\n      } else {\n        variable_t y(p.second);\n        bound_t y_lb = operator[](y).lb();\n        if (y_lb.is_infinite()) {\n          if (unbounded_lbvar || coeff != Wt(1))\n            goto assign_lb_finish;\n          unbounded_lbvar = y;\n        } else {\n          Wt ymin(ntow::convert(*(y_lb.number()), overflow));\n          if (overflow) {\n            continue;\n          }\n          exp_lb += ymin * coeff;\n          lb_terms.push_back({y, ymin});\n        }\n      }\n    }\n\n    if (unbounded_lbvar) {\n      lb.push_back({*unbounded_lbvar, exp_lb});\n    } else {\n      for (auto p : lb_terms) {\n        lb.push_back({p.first, exp_lb - p.second});\n      }\n    }\n  }\n  assign_lb_finish:\n    return;\n  }\n\n  // GKG: I suspect there're some sign/bound direction errors in the\n  // following.\n  void diffcsts_of_lin_leq(const linear_expression_t &exp,\n                           std::vector<diffcst_t> &csts,\n                           std::vector<std::pair<variable_t, Wt>> &lbs,\n                           std::vector<std::pair<variable_t, Wt>> &ubs) {\n    // Process upper bounds.\n    Wt unbounded_lbcoeff;\n    Wt unbounded_ubcoeff;\n    boost::optional<variable_t> unbounded_lbvar;\n    boost::optional<variable_t> unbounded_ubvar;\n    bool underflow, overflow;\n\n    Wt exp_ub = -(ntow::convert(exp.constant(), overflow));\n    if (overflow) {\n      return;\n    }\n\n    // temporary hack\n    ntow::convert(exp.constant() - 1, underflow);\n    if (underflow) {\n      // We don't like MIN either because the code will compute\n      // minus MIN and it will silently overflow.\n      return;\n    }\n\n    std::vector<std::pair<std::pair<Wt, variable_t>, Wt>> pos_terms, neg_terms;\n    for (auto p : exp) {\n      Wt coeff(ntow::convert(p.first, overflow));\n      if (overflow) {\n        continue;\n      }\n      if (coeff > Wt(0)) {\n        variable_t y(p.second);\n        bound_t y_lb = operator[](y).lb();\n        if (y_lb.is_infinite()) {\n          if (unbounded_lbvar)\n            goto diffcst_finish;\n          unbounded_lbvar = y;\n          unbounded_lbcoeff = coeff;\n        } else {\n          Wt ymin(ntow::convert(*(y_lb.number()), overflow));\n          if (overflow) {\n            continue;\n          }\n          // Coeff is negative, so it's still add\n          exp_ub -= ymin * coeff;\n          pos_terms.push_back({{coeff, y}, ymin});\n        }\n      } else {\n        variable_t y(p.second);\n        bound_t y_ub = operator[](y).ub();\n        if (y_ub.is_infinite()) {\n          if (unbounded_ubvar)\n            goto diffcst_finish;\n          unbounded_ubvar = y;\n          unbounded_ubcoeff = -coeff;\n        } else {\n          Wt ymax(ntow::convert(*(y_ub.number()), overflow));\n          if (overflow) {\n            continue;\n          }\n          exp_ub -= ymax * coeff;\n          neg_terms.push_back({{-coeff, y}, ymax});\n        }\n      }\n    }\n\n    if (unbounded_lbvar) {\n      variable_t x(*unbounded_lbvar);\n      if (unbounded_ubvar) {\n        if (unbounded_lbcoeff != Wt(1) || unbounded_ubcoeff != Wt(1))\n          goto diffcst_finish;\n        variable_t y(*unbounded_ubvar);\n        csts.push_back({{x, y}, exp_ub});\n      } else {\n        if (unbounded_lbcoeff == Wt(1)) {\n          for (auto p : neg_terms)\n            csts.push_back({{x, p.first.second}, exp_ub - p.second});\n        }\n        // Add bounds for x\n        ubs.push_back({x, exp_ub / unbounded_lbcoeff});\n      }\n    } else {\n      if (unbounded_ubvar) {\n        variable_t y(*unbounded_ubvar);\n        if (unbounded_ubcoeff == Wt(1)) {\n          for (auto p : pos_terms)\n            csts.push_back({{p.first.second, y}, exp_ub + p.second});\n        }\n        // Bounds for y\n        lbs.push_back({y, -exp_ub / unbounded_ubcoeff});\n      } else {\n        for (auto pl : neg_terms) {\n          for (auto pu : pos_terms) {\n            csts.push_back({{pu.first.second, pl.first.second},\n                            exp_ub - pl.second + pu.second});\n          }\n        }\n\n        for (auto pl : neg_terms) {\n          lbs.push_back(\n              {pl.first.second, -exp_ub / pl.first.first + pl.second});\n        }\n        for (auto pu : pos_terms) {\n          ubs.push_back({pu.first.second, exp_ub / pu.first.first + pu.second});\n        }\n      }\n    }\n  diffcst_finish:\n    return;\n  }\n\n  bool add_linear_leq(const linear_expression_t &exp) {\n    CRAB_LOG(\"zones-sparse\", linear_expression_t exp_tmp(exp);\n             crab::outs() << \"Adding: \" << exp_tmp << \"<= 0\"\n                          << \"\\n\");\n    std::vector<std::pair<variable_t, Wt>> lbs, ubs;\n    std::vector<diffcst_t> csts;\n    diffcsts_of_lin_leq(exp, csts, lbs, ubs);\n\n    assert(check_potential(g, potential));\n\n    Wt_min min_op;\n\n    edge_vector es;\n    for (auto p : lbs) {\n      es.push_back({{get_vert(p.first), 0}, -p.second});\n    }\n    for (auto p : ubs) {\n      es.push_back({{0, get_vert(p.first)}, p.second});\n    }\n    for (auto diff : csts) {\n      CRAB_LOG(\"zones-sparse\", crab::outs() << diff.first.first << \"-\"\n                                            << diff.first.second\n                                            << \"<=\" << diff.second << \"\\n\";);\n      es.push_back({{get_vert(diff.first.second), get_vert(diff.first.first)},\n                    diff.second});\n    }\n\n    for (auto edge : es) {\n      // CRAB_LOG(\"zones-sparse\",\n      // crab::outs() << diff.first.first<< \"-\"<< diff.first.second<< \"<=\"\n      //              << diff.second<<\"\\n\";);\n\n      vert_id src = edge.first.first;\n      vert_id dest = edge.first.second;\n      g.update_edge(src, edge.second, dest, min_op);\n      if (!repair_potential(src, dest)) {\n        set_to_bottom();\n        return false;\n      }\n      assert(check_potential(g, potential));\n\n      close_over_edge(src, dest);\n      assert(check_potential(g, potential));\n    }\n\n    assert(check_potential(g, potential));\n    return true;\n  }\n\n  // x != n\n  void add_univar_disequation(const variable_t &x, number_t n) {\n    bool overflow;\n    interval_t i = get_interval(x);\n    interval_t ni(n); \n    interval_t new_i =\n        ikos::linear_interval_solver_impl::trim_interval<interval_t>(\n            i, ni);\n    if (new_i.is_bottom()) {\n      set_to_bottom();\n    } else if (!new_i.is_top() && (new_i <= i)) {\n      vert_id v = get_vert(x);\n      Wt_min min_op;\n      typename graph_t::mut_val_ref_t w;\n      if (new_i.lb().is_finite()) {\n        // strenghten lb\n        Wt lb_val = ntow::convert(-(*(new_i.lb().number())), overflow);\n        if (overflow) {\n          return;\n        }\n        if (g.lookup(v, 0, &w) && lb_val < w) {\n          g.set_edge(v, lb_val, 0);\n          if (!repair_potential(v, 0)) {\n            set_to_bottom();\n            return;\n          }\n          assert(check_potential(g, potential));\n          // Update other bounds\n          for (auto e : g.e_preds(v)) {\n            if (e.vert == 0)\n              continue;\n            g.update_edge(e.vert, e.val + lb_val, 0, min_op);\n            if (!repair_potential(e.vert, 0)) {\n              set_to_bottom();\n              return;\n            }\n            assert(check_potential(g, potential));\n          }\n        }\n      }\n      if (new_i.ub().is_finite()) {\n        // strengthen ub\n        Wt ub_val = ntow::convert(*(new_i.ub().number()), overflow);\n        if (overflow) {\n          return;\n        }\n        if (g.lookup(0, v, &w) && (ub_val < w)) {\n          g.set_edge(0, ub_val, v);\n          if (!repair_potential(0, v)) {\n            set_to_bottom();\n            return;\n          }\n          assert(check_potential(g, potential));\n          // Update other bounds\n          for (auto e : g.e_succs(v)) {\n            if (e.vert == 0)\n              continue;\n            g.update_edge(0, e.val + ub_val, e.vert, min_op);\n            if (!repair_potential(0, e.vert)) {\n              set_to_bottom();\n              return;\n            }\n            assert(check_potential(g, potential));\n          }\n        }\n      }\n    }\n  }\n\n  void add_disequation(const linear_expression_t &e) {\n    // XXX: similar precision as the interval domain\n    for (auto kv : e) {\n      const variable_t &pivot = kv.second;\n      interval_t i = compute_residual(e, pivot) / interval_t(kv.first);\n      if (auto k = i.singleton()) {\n        add_univar_disequation(pivot, *k);\n      }\n    }\n  }\n\n  // Restore potential after an edge addition\n  bool repair_potential(vert_id src, vert_id dest) {\n    return GrOps::repair_potential(g, potential, src, dest);\n  }\n\n  // Restore closure after a single edge addition\n  void close_over_edge(vert_id ii, vert_id jj) {\n    Wt_min min_op;\n\n    Wt c = g.edge_val(ii, jj);\n\n    typename graph_t::mut_val_ref_t w;\n\n    // There may be a cheaper way to do this.\n    // GKG: Now implemented.\n    std::vector<std::pair<vert_id, Wt>> src_dec;\n\n    for (auto edge : g.e_preds(ii)) {\n      vert_id se = edge.vert;\n      Wt w_si = edge.val;\n      Wt wt_sij = w_si + c;\n\n      assert(g.succs(se).begin() != g.succs(se).end());\n      if (se != jj) {\n        if (g.lookup(se, jj, &w)) {\n          if (w.get() <= wt_sij)\n            continue;\n          w = wt_sij;\n        } else {\n          g.add_edge(se, wt_sij, jj);\n        }\n        // assert(potential[se] + g.edge_val(se, jj) - potential[jj] >= Wt(0));\n        src_dec.push_back({se, w_si});\n\n        /*\n         for(auto edge : g.e_succs(jj))\n         {\n           vert_id de = edge.vert;\n           if(se != de)\n           {\n             Wt wt_sijd = wt_sij + edge.val;\n             if(g.lookup(se, de, &w))\n             {\n               if((*w) <= wt_sijd)\n                 continue;\n               (*w) = wt_sijd;\n             } else {\n               g.add_edge(se, wt_sijd, de);\n             }\n           }\n         }\n         */\n      }\n    }\n\n    std::vector<std::pair<vert_id, Wt>> dest_dec;\n    for (auto edge : g.e_succs(jj)) {\n      vert_id de = edge.vert;\n      Wt w_jd = edge.val;\n      Wt wt_ijd = w_jd + c;\n      if (de != ii) {\n        if (g.lookup(ii, de, &w)) {\n          if (w.get() <= wt_ijd)\n            continue;\n          w = wt_ijd;\n        } else {\n          g.add_edge(ii, wt_ijd, de);\n        }\n        // assert(potential[ii] + g.edge_val(ii, de) - potential[de] >= Wt(0));\n        // dest_dec.push_back(std::make_pair(de, edge.val));\n        dest_dec.push_back({de, w_jd});\n      }\n    }\n    // Look at (src, dest) pairs with updated edges.\n    for (auto s_p : src_dec) {\n      vert_id se = s_p.first;\n      Wt wt_sij = c + s_p.second;\n      for (auto d_p : dest_dec) {\n        vert_id de = d_p.first;\n        Wt wt_sijd = wt_sij + d_p.second;\n        if (g.lookup(se, de, &w)) {\n          if (w.get() <= wt_sijd)\n            continue;\n          w = wt_sijd;\n        } else {\n          g.add_edge(se, wt_sijd, de);\n        }\n        //  assert(potential[se] + g.edge_val(se, de) - potential[de] >= Wt(0));\n      }\n    }\n    // Closure is now updated.\n  }\n\n  // Restore closure after a variable assignment\n  // Assumption: x = f(y_1, ..., y_n) cannot induce non-trivial\n  // relations between (y_i, y_j)\n  /*\n  bool close_after_assign(vert_id v)\n  {\n    // Run Dijkstra's forward to collect successors of v,\n    // and backward to collect predecessors\n    edge_vector delta;\n    if(!GrOps::close_after_assign(g, potential, v, delta))\n      return false;\n    GrOps::apply_delta(g, delta);\n    return true;\n  }\n\n  bool closure(void)\n  {\n    // Full Johnson-style all-pairs shortest path\n    CRAB_ERROR(\"SparseWtGraph::closure not yet implemented.\");\n  }\n  */\n\n  bool need_normalization() const {\n#ifdef SDBM_NO_NORMALIZE\n    return false;\n#endif\n    return unstable.size() > 0;\n  }\n\n  // dbm is already normalized\n  linear_constraint_system_t\n  to_linear_constraint_system(const DBM_t &dbm) const {\n    linear_constraint_system_t csts;\n\n    if (dbm.is_bottom()) {\n      csts += linear_constraint_t::get_false();\n      return csts;\n    }\n\n    // Extract all the edges\n    SubGraph<graph_t> g_excl(const_cast<graph_t &>(dbm.g), 0);\n    for (vert_id v : g_excl.verts()) {\n      if (!dbm.rev_map[v])\n        continue;\n      if (dbm.g.elem(v, 0)) {\n        variable_t vv = *dbm.rev_map[v];\n        csts += linear_constraint_t(linear_expression_t(vv) >=\n                                    -number_t(dbm.g.edge_val(v, 0)));\n      }\n      if (dbm.g.elem(0, v)) {\n        variable_t vv = *dbm.rev_map[v];\n        csts += linear_constraint_t(linear_expression_t(vv) <=\n                                    number_t(dbm.g.edge_val(0, v)));\n      }\n    }\n\n    for (vert_id s : g_excl.verts()) {\n      if (!dbm.rev_map[s])\n        continue;\n      variable_t vs = *dbm.rev_map[s];\n      for (vert_id d : g_excl.succs(s)) {\n        if (!dbm.rev_map[d])\n          continue;\n        variable_t vd = *dbm.rev_map[d];\n        csts += linear_constraint_t(vd - vs <= number_t(g_excl.edge_val(s, d)));\n      }\n    }\n\n    return csts;\n  }\n\n  // Assume dbm is already normalized\n  void write(crab_os &o, const DBM_t &dbm) const {\n    if (dbm.is_bottom()) {\n      o << \"_|_\";\n      return;\n    } else if (dbm.is_top()) {\n      o << \"{}\";\n      return;\n    } else {\n      // Intervals\n      bool first = true;\n      o << \"{\";\n      // Extract all the edges\n      SubGraph<graph_t> g_excl(const_cast<graph_t &>(dbm.g), 0);\n      for (vert_id v : g_excl.verts()) {\n        if (!dbm.rev_map[v])\n          continue;\n        if (!dbm.g.elem(0, v) && !dbm.g.elem(v, 0))\n          continue;\n        interval_t v_out =\n            interval_t(dbm.g.elem(v, 0) ? -number_t(dbm.g.edge_val(v, 0))\n                                        : bound_t::minus_infinity(),\n                       dbm.g.elem(0, v) ? number_t(dbm.g.edge_val(0, v))\n                                        : bound_t::plus_infinity());\n        if (first)\n          first = false;\n        else\n          o << \", \";\n        o << *(dbm.rev_map[v]) << \" -> \" << v_out;\n      }\n\n      for (vert_id s : g_excl.verts()) {\n        if (!dbm.rev_map[s])\n          continue;\n        variable_t vs = *dbm.rev_map[s];\n        for (vert_id d : g_excl.succs(s)) {\n          if (!dbm.rev_map[d])\n            continue;\n          variable_t vd = *dbm.rev_map[d];\n          if (first)\n            first = false;\n          else\n            o << \", \";\n          o << vd << \"-\" << vs << \"<=\" << g_excl.edge_val(s, d);\n        }\n      }\n      o << \"}\";\n    }\n  }\n\n  // Magical rvalue ownership stuff for efficient initialization\n  sparse_dbm_domain(vert_map_t &&_vert_map, rev_map_t &&_rev_map, graph_t &&_g,\n                    std::vector<Wt> &&_potential, vert_set_t &&_unstable)\n      : vert_map(std::move(_vert_map)), rev_map(std::move(_rev_map)),\n        g(std::move(_g)), potential(std::move(_potential)),\n        unstable(std::move(_unstable)), _is_bottom(false) {\n\n    if (is_top()) {\n      // Garbage collection from unconstrained variables in vert_map\n      // and rev_map.\n      set_to_top();\n    }\n    CRAB_LOG(\"zones-sparse-size\", auto p = size();\n             crab::outs() << \"#nodes = \" << p.first << \" #edges=\" << p.second\n                          << \"\\n\";);\n  }\n\npublic:\n  sparse_dbm_domain(bool is_bottom = false) : _is_bottom(is_bottom) {\n    g.growTo(1); // Allocate the zero vector\n    potential.push_back(Wt(0));\n    rev_map.push_back(boost::none);\n  }\n\n  // FIXME: Rewrite to avoid copying if o is _|_\n  sparse_dbm_domain(const DBM_t &o)\n      : vert_map(o.vert_map), rev_map(o.rev_map), g(o.g),\n        potential(o.potential), unstable(o.unstable), _is_bottom(false) {\n\n    crab::CrabStats::count(domain_name() + \".count.copy\");\n    crab::ScopedCrabStats __st__(domain_name() + \".copy\");\n\n    if (o._is_bottom)\n      set_to_bottom();\n\n    if (!_is_bottom)\n      assert(g.size() > 0);\n  }\n\n  sparse_dbm_domain(DBM_t &&o)\n      : vert_map(std::move(o.vert_map)), rev_map(std::move(o.rev_map)),\n        g(std::move(o.g)), potential(std::move(o.potential)),\n        unstable(std::move(o.unstable)), _is_bottom(o._is_bottom) {}\n\n  sparse_dbm_domain &operator=(const sparse_dbm_domain &o) {\n    crab::CrabStats::count(domain_name() + \".count.copy\");\n    crab::ScopedCrabStats __st__(domain_name() + \".copy\");\n\n    if (this != &o) {\n      if (o._is_bottom)\n        set_to_bottom();\n      else {\n        _is_bottom = false;\n        vert_map = o.vert_map;\n        rev_map = o.rev_map;\n        g = o.g;\n        potential = o.potential;\n        unstable = o.unstable;\n        assert(g.size() > 0);\n      }\n    }\n    return *this;\n  }\n\n  sparse_dbm_domain &operator=(sparse_dbm_domain &&o) {\n    if (o._is_bottom) {\n      set_to_bottom();\n    } else {\n      _is_bottom = false;\n      vert_map = std::move(o.vert_map);\n      rev_map = std::move(o.rev_map);\n      g = std::move(o.g);\n      potential = std::move(o.potential);\n      unstable = std::move(o.unstable);\n    }\n    return *this;\n  }\n\n  DBM_t make_top() const override { return DBM_t(false); }\n\n  DBM_t make_bottom() const override { return DBM_t(true); }\n\n  void set_to_top() override {\n    sparse_dbm_domain abs(false);\n    std::swap(*this, abs);\n  }\n\n  void set_to_bottom() override {\n    vert_map.clear();\n    rev_map.clear();\n    g.clear();\n    potential.clear();\n    unstable.clear();\n    _is_bottom = true;\n  }\n\n  bool is_bottom() const override {\n    // if(!_is_bottom && g.has_negative_cycle())\n    // _is_bottom = true;\n    return _is_bottom;\n  }\n\n  bool is_top() const override {\n    if (_is_bottom)\n      return false;\n    return g.is_empty();\n  }\n\n  bool operator<=(const DBM_t &o) const override {\n    crab::CrabStats::count(domain_name() + \".count.leq\");\n    crab::ScopedCrabStats __st__(domain_name() + \".leq\");\n\n    // cover all trivial cases to avoid allocating a dbm matrix\n    if (is_bottom())\n      return true;\n    else if (o.is_bottom())\n      return false;\n    else if (o.is_top())\n      return true;\n    else if (is_top())\n      return false;\n    else {\n      DBM_t left(*this);\n      left.normalize();\n      // XXX: we can avoid copy of the right operand but we need to\n      // create const versions of several methods in graph_t.\n      DBM_t right(o);\n\n      // CRAB_LOG(\"zones-sparse\",\n      //          crab::outs() << \"operator<=: \"<< *this<< \"<=?\"<< o << \"\\n\");\n\n      if (left.vert_map.size() < right.vert_map.size())\n        return false;\n\n      typename graph_t::mut_val_ref_t wx;\n\n      // Set up a mapping from o to this.\n      std::vector<unsigned int> vert_renaming(right.g.size(), -1);\n      vert_renaming[0] = 0;\n      for (auto p : right.vert_map) {\n        auto it = left.vert_map.find(p.first);\n        // We can't have this <= o if we're missing some\n        // vertex.\n        if (it == left.vert_map.end())\n          return false;\n        vert_renaming[p.second] = (*it).second;\n      }\n\n      assert(left.g.size() > 0);\n      // GrPerm g_perm(vert_renaming, g);\n\n      for (vert_id ox : right.g.verts()) {\n        assert(vert_renaming[ox] != -1);\n        vert_id x = vert_renaming[ox];\n        for (auto edge : right.g.e_succs(ox)) {\n          vert_id oy = edge.vert;\n          assert(vert_renaming[ox] != -1);\n          vert_id y = vert_renaming[oy];\n          Wt ow = edge.val;\n\n          if (!left.g.lookup(x, y, &wx) || (ow < wx))\n            return false;\n        }\n      }\n      return true;\n    }\n  }\n\n  void operator|=(const DBM_t &o) override {\n    crab::CrabStats::count(domain_name() + \".count.join\");\n    crab::ScopedCrabStats __st__(domain_name() + \".join\");\n\n    CRAB_LOG(\"zones-sparse\", crab::outs() << \"Before join:\\n\"\n                                          << \"DBM 1\\n\"\n                                          << *this << \"\\n\"\n                                          << \"DBM 2\\n\"\n                                          << o << \"\\n\");\n\n    if (is_bottom()) {\n      *this = o;\n    } else if (o.is_top()) {\n      set_to_top();\n    } else if (is_top() || o.is_bottom()) {\n      // do nothing\n    } else {\n      normalize();\n      DBM_t right(o);\n      right.normalize();\n\n      assert(check_potential(g, potential));\n      assert(check_potential(right.g, right.potential));\n\n      // Figure out the common renaming, initializing the\n      // resulting potentials as we go.\n      std::vector<vert_id> perm_x;\n      std::vector<vert_id> perm_y;\n      std::vector<variable_t> perm_inv;\n\n      std::vector<Wt> pot_rx;\n      std::vector<Wt> pot_ry;\n      vert_map_t out_vmap;\n      rev_map_t out_revmap;\n      // Add the zero vertex\n      assert(potential.size() > 0);\n      pot_rx.push_back(0);\n      pot_ry.push_back(0);\n      perm_x.push_back(0);\n      perm_y.push_back(0);\n      out_revmap.push_back(boost::none);\n\n      for (auto p : vert_map) {\n        auto it = right.vert_map.find(p.first);\n        // Variable exists in both\n        if (it != right.vert_map.end()) {\n          out_vmap.insert(vmap_elt_t(p.first, perm_x.size()));\n          out_revmap.push_back(p.first);\n\n          pot_rx.push_back(potential[p.second] - potential[0]);\n          pot_ry.push_back(right.potential[(*it).second] - right.potential[0]);\n          perm_inv.push_back(p.first);\n          perm_x.push_back(p.second);\n          perm_y.push_back((*it).second);\n        }\n      }\n      // unsigned int sz = perm_x.size();\n\n      // Build the permuted view of x and y.\n      assert(g.size() > 0);\n      GrPerm gx(perm_x, g);\n      assert(right.g.size() > 0);\n      GrPerm gy(perm_y, right.g);\n\n      // We now have the relevant set of relations. Because g_rx and g_ry are\n      // closed, the result is also closed.\n      Wt_min min_op;\n      graph_t join_g(GrOps::join(gx, gy));\n\n      // Now garbage collect any unused vertices\n      for (vert_id v : join_g.verts()) {\n        if (v == 0)\n          continue;\n        if (join_g.succs(v).size() == 0 && join_g.preds(v).size() == 0) {\n          join_g.forget(v);\n          if (out_revmap[v]) {\n            out_vmap.erase(*(out_revmap[v]));\n            out_revmap[v] = boost::none;\n          }\n        }\n      }\n\n      std::swap(vert_map, out_vmap);\n      std::swap(rev_map, out_revmap);\n      std::swap(g, join_g);\n      std::swap(potential, pot_rx);\n      unstable.clear();\n      _is_bottom = false;\n    }\n    CRAB_LOG(\"zones-sparse\", crab::outs() << \"Result join:\\n\"\n                                          << *this << \"\\n\";);\n  }\n\n  DBM_t operator|(const DBM_t &o) const override {\n    crab::CrabStats::count(domain_name() + \".count.join\");\n    crab::ScopedCrabStats __st__(domain_name() + \".join\");\n\n    if (is_bottom()) {\n      return o;\n    } else if (o.is_top() || is_top()) {\n      DBM_t res;\n      return res;\n    } else if (o.is_bottom()) {\n      return *this;\n    } else {\n      CRAB_LOG(\"zones-sparse\", crab::outs() << \"Before join:\\n\"\n                                            << \"DBM 1\\n\"\n                                            << *this << \"\\n\"\n                                            << \"DBM 2\\n\"\n                                            << o << \"\\n\");\n\n      DBM_t left(*this);\n      DBM_t right(o);\n\n      left.normalize();\n      right.normalize();\n\n      assert(check_potential(left.g, left.potential));\n      assert(check_potential(right.g, right.potential));\n\n      // Figure out the common renaming, initializing the\n      // resulting potentials as we go.\n      std::vector<vert_id> perm_x;\n      std::vector<vert_id> perm_y;\n      std::vector<variable_t> perm_inv;\n\n      std::vector<Wt> pot_rx;\n      std::vector<Wt> pot_ry;\n      vert_map_t out_vmap;\n      rev_map_t out_revmap;\n      // Add the zero vertex\n      assert(left.potential.size() > 0);\n      pot_rx.push_back(0);\n      pot_ry.push_back(0);\n      perm_x.push_back(0);\n      perm_y.push_back(0);\n      out_revmap.push_back(boost::none);\n\n      for (auto p : left.vert_map) {\n        auto it = right.vert_map.find(p.first);\n        // Variable exists in both\n        if (it != right.vert_map.end()) {\n          out_vmap.insert(vmap_elt_t(p.first, perm_x.size()));\n          out_revmap.push_back(p.first);\n\n          pot_rx.push_back(left.potential[p.second] - left.potential[0]);\n          pot_ry.push_back(right.potential[(*it).second] - right.potential[0]);\n          perm_inv.push_back(p.first);\n          perm_x.push_back(p.second);\n          perm_y.push_back((*it).second);\n        }\n      }\n      // unsigned int sz = perm_x.size();\n\n      // Build the permuted view of x and y.\n      assert(left.g.size() > 0);\n      GrPerm gx(perm_x, left.g);\n      assert(right.g.size() > 0);\n      GrPerm gy(perm_y, right.g);\n\n      // We now have the relevant set of relations. Because g_rx and g_ry are\n      // closed, the result is also closed.\n      Wt_min min_op;\n      graph_t join_g(GrOps::join(gx, gy));\n\n      // Now garbage collect any unused vertices\n      for (vert_id v : join_g.verts()) {\n        if (v == 0)\n          continue;\n        if (join_g.succs(v).size() == 0 && join_g.preds(v).size() == 0) {\n          join_g.forget(v);\n          if (out_revmap[v]) {\n            out_vmap.erase(*(out_revmap[v]));\n            out_revmap[v] = boost::none;\n          }\n        }\n      }\n\n      DBM_t res(std::move(out_vmap), std::move(out_revmap), std::move(join_g),\n                std::move(pot_rx), vert_set_t());\n      CRAB_LOG(\"zones-sparse\", crab::outs() << \"Result join:\\n\"\n                                            << res << \"\\n\";);\n\n      return res;\n    }\n  }\n\n  DBM_t operator||(const DBM_t &o) const override {\n    crab::CrabStats::count(domain_name() + \".count.widening\");\n    crab::ScopedCrabStats __st__(domain_name() + \".widening\");\n\n    if (is_bottom())\n      return o;\n    else if (o.is_bottom())\n      return *this;\n    else {\n      CRAB_LOG(\"zones-sparse\",\n               DBM_t left(*this); // to avoid closure on left operand\n               crab::outs() << \"Before widening:\\n\"\n                            << \"DBM 1\\n\"\n                            << left << \"\\n\"\n                            << \"DBM 2\\n\"\n                            << o << \"\\n\";);\n      // Do not normalize left operand\n      DBM_t right(o);\n      right.normalize();\n\n      // Figure out the common renaming\n      std::vector<vert_id> perm_x;\n      std::vector<vert_id> perm_y;\n      vert_map_t out_vmap;\n      rev_map_t out_revmap;\n      std::vector<Wt> widen_pot;\n      vert_set_t widen_unstable(unstable);\n\n      assert(potential.size() > 0);\n      widen_pot.push_back(Wt(0));\n      perm_x.push_back(0);\n      perm_y.push_back(0);\n      out_revmap.push_back(boost::none);\n      for (auto p : vert_map) {\n        auto it = right.vert_map.find(p.first);\n        // Variable exists in both\n        if (it != right.vert_map.end()) {\n          out_vmap.insert(vmap_elt_t(p.first, perm_x.size()));\n          out_revmap.push_back(p.first);\n\n          widen_pot.push_back(potential[p.second] - potential[0]);\n          perm_x.push_back(p.second);\n          perm_y.push_back((*it).second);\n        }\n      }\n\n      // Build the permuted view of x and y.\n      graph_t left_g(g);\n\n      assert(left_g.size() > 0);\n      GrPerm gx(perm_x, left_g);\n      assert(right.g.size() > 0);\n      GrPerm gy(perm_y, right.g);\n\n      // Now perform the widening\n      std::vector<vert_id> destabilized;\n      graph_t widen_g(GrOps::widen(gx, gy, destabilized));\n      for (vert_id v : destabilized)\n        widen_unstable.insert(v);\n\n      DBM_t res(std::move(out_vmap), std::move(out_revmap), std::move(widen_g),\n                std::move(widen_pot), std::move(widen_unstable));\n\n      CRAB_LOG(\"zones-sparse\", DBM_t res_copy(res); crab::outs()\n                                                    << \"Result widening:\\n\"\n                                                    << res_copy << \"\\n\";);\n      return res;\n    }\n  }\n\n  DBM_t operator&(const DBM_t &o) const override {\n    crab::CrabStats::count(domain_name() + \".count.meet\");\n    crab::ScopedCrabStats __st__(domain_name() + \".meet\");\n\n    if (is_bottom() || o.is_top())\n      return *this;\n    else if (is_top() || o.is_bottom()) {\n      return o;\n    } else {\n      CRAB_LOG(\"zones-sparse\", crab::outs() << \"Before meet:\\n\"\n                                            << \"DBM 1\\n\"\n                                            << *this << \"\\n\"\n                                            << \"DBM 2\\n\"\n                                            << o << \"\\n\";);\n      DBM_t left(*this);\n      DBM_t right(o);\n\n      left.normalize();\n      right.normalize();\n\n      // We map vertices in the left operand onto a contiguous range.\n      // This will often be the identity map, but there might be gaps.\n      vert_map_t meet_verts;\n      rev_map_t meet_rev;\n\n      std::vector<vert_id> perm_x;\n      std::vector<vert_id> perm_y;\n      std::vector<Wt> meet_pi;\n      perm_x.push_back(0);\n      perm_y.push_back(0);\n      meet_pi.push_back(Wt(0));\n      meet_rev.push_back(boost::none);\n      for (auto p : left.vert_map) {\n        vert_id vv = perm_x.size();\n        meet_verts.insert(vmap_elt_t(p.first, vv));\n        meet_rev.push_back(p.first);\n\n        perm_x.push_back(p.second);\n        perm_y.push_back(-1);\n        meet_pi.push_back(left.potential[p.second] - left.potential[0]);\n      }\n\n      // Add missing mappings from the right operand.\n      for (auto p : right.vert_map) {\n        auto it = meet_verts.find(p.first);\n\n        if (it == meet_verts.end()) {\n          vert_id vv = perm_y.size();\n          meet_rev.push_back(p.first);\n\n          perm_y.push_back(p.second);\n          perm_x.push_back(-1);\n          meet_pi.push_back(right.potential[p.second] - right.potential[0]);\n          meet_verts.insert(vmap_elt_t(p.first, vv));\n        } else {\n          perm_y[(*it).second] = p.second;\n        }\n      }\n\n      // Build the permuted view of x and y.\n      assert(left.g.size() > 0);\n      GrPerm gx(perm_x, left.g);\n      assert(right.g.size() > 0);\n      GrPerm gy(perm_y, right.g);\n\n      // Compute the syntactic meet of the permuted graphs.\n      bool is_closed;\n      graph_t meet_g(GrOps::meet(gx, gy, is_closed));\n\n      // Compute updated potentials on the zero-enriched graph\n      // std::vector<Wt> meet_pi(meet_g.size());\n      // We've warm-started pi with the operand potentials\n      if (!GrOps::select_potentials(meet_g, meet_pi)) {\n        // Potentials cannot be selected -- state is infeasible.\n        DBM_t res;\n        res.set_to_bottom();\n        return res;\n      }\n\n      if (!is_closed) {\n        edge_vector delta;\n        if (crab_domain_params_man::get().zones_chrome_dijkstra())\n          GrOps::close_after_meet(meet_g, meet_pi, gx, gy, delta);\n        else\n          GrOps::close_johnson(meet_g, meet_pi, delta);\n\n        GrOps::apply_delta(meet_g, delta);\n      }\n      assert(check_potential(meet_g, meet_pi));\n      DBM_t res(std::move(meet_verts), std::move(meet_rev), std::move(meet_g),\n                std::move(meet_pi), vert_set_t());\n      CRAB_LOG(\"zones-sparse\", crab::outs() << \"Result meet:\\n\"\n                                            << res << \"\\n\";);\n      return res;\n    }\n  }\n\n  DBM_t operator&&(const DBM_t &o) const override {\n    crab::CrabStats::count(domain_name() + \".count.narrowing\");\n    crab::ScopedCrabStats __st__(domain_name() + \".narrowing\");\n\n    if (is_bottom() || o.is_top())\n      return *this;\n    else if (is_top() || o.is_bottom()) {\n      return o;\n    } else {\n      CRAB_LOG(\"zones-sparse\", crab::outs() << \"Before narrowing:\\n\"\n                                            << \"DBM 1\\n\"\n                                            << *this << \"\\n\"\n                                            << \"DBM 2\\n\"\n                                            << o << \"\\n\";);\n\n      // FIXME: Implement properly\n      // Narrowing as a no-op should be sound.\n      DBM_t res(*this);\n      res.normalize();\n      CRAB_LOG(\"zones-sparse\", crab::outs() << \"Result narrowing:\\n\"\n                                            << res << \"\\n\";);\n      return res;\n    }\n  }\n\n  DBM_t widening_thresholds(\n      const DBM_t &o,\n      const iterators::thresholds<number_t> &ts) const override {\n    // TODO: use thresholds\n    return (*this || o);\n  }\n\n  void normalize() override {\n    // Always maintained in normal form, except for widening\n    if (!need_normalization()) {\n      return;\n    }\n    edge_vector delta;\n    if (crab_domain_params_man::get().zones_widen_restabilize())\n      GrOps::close_after_widen(g, potential, vert_set_wrap_t(unstable), delta);\n    else\n      GrOps::close_johnson(g, potential, delta);\n    GrOps::apply_delta(g, delta);\n    unstable.clear();\n  }\n\n  void minimize() override {}\n\n  void operator-=(const variable_t &v) override {\n    crab::CrabStats::count(domain_name() + \".count.forget\");\n    crab::ScopedCrabStats __st__(domain_name() + \".forget\");\n\n    if (is_bottom())\n      return;\n    normalize();\n\n    auto it = vert_map.find(v);\n    if (it != vert_map.end()) {\n      CRAB_LOG(\"zones-sparse\", crab::outs() << \"Before forget \" << it->second\n                                            << \": \" << g << \"\\n\";);\n      g.forget(it->second);\n      CRAB_LOG(\"zones-sparse\", crab::outs() << \"After: \" << g << \"\\n\";);\n\n      rev_map[it->second] = boost::none;\n      vert_map.erase(v);\n    }\n  }\n\n  // Assumption: state is currently feasible.\n  void assign(const variable_t &x, const linear_expression_t &e) override {\n    crab::CrabStats::count(domain_name() + \".count.assign\");\n    crab::ScopedCrabStats __st__(domain_name() + \".assign\");\n\n    if (is_bottom()) {\n      return;\n    }\n\n    normalize();\n\n    assert(check_potential(g, potential));\n\n    // If it's a constant, just assign the interval.\n    if (e.is_constant()) {\n      set(x, e.constant());\n    } else {\n      interval_t x_int = eval_interval(e);\n\n      boost::optional<Wt> lb_w, ub_w;\n      bool overflow;\n      if (x_int.lb().is_finite()) {\n        lb_w = ntow::convert(-(*(x_int.lb().number())), overflow);\n        if (overflow) {\n          operator-=(x);\n          CRAB_LOG(\"zones-sparse\", crab::outs()\n                                       << \"---\" << x << \":=\" << e << \"\\n\"\n                                       << *this << \"\\n\");\n          return;\n        }\n      }\n      if (x_int.ub().is_finite()) {\n        ub_w = ntow::convert(*(x_int.ub().number()), overflow);\n        if (overflow) {\n          operator-=(x);\n          CRAB_LOG(\"zones-sparse\", crab::outs()\n                                       << \"---\" << x << \":=\" << e << \"\\n\"\n                                       << *this << \"\\n\");\n          return;\n        }\n      }\n\n      std::vector<std::pair<variable_t, Wt>> diffs_lb, diffs_ub;\n      // Construct difference constraints from the assignment\n      diffcsts_of_assign(x, e, diffs_lb, diffs_ub);\n      if (diffs_lb.size() > 0 || diffs_ub.size() > 0) {\n        if (crab_domain_params_man::get().zones_special_assign()) {\n          bool overflow;\n          Wt e_val = eval_expression(e, overflow);\n          if (overflow) {\n            operator-=(x);\n            return;\n          }\n\n          // Allocate a new vertex for x\n          vert_id v = g.new_vertex();\n          assert(v <= rev_map.size());\n          if (v == rev_map.size()) {\n            rev_map.push_back(x);\n            potential.push_back(potential[0] + e_val);\n          } else {\n            potential[v] = potential[0] + e_val;\n            rev_map[v] = x;\n          }\n\n          edge_vector delta;\n          for (auto diff : diffs_lb) {\n            delta.push_back({{v, get_vert(diff.first)}, -diff.second});\n          }\n\n          for (auto diff : diffs_ub) {\n            delta.push_back({{get_vert(diff.first), v}, diff.second});\n          }\n\n          if (lb_w) {\n            delta.push_back({{v, 0}, *lb_w});\n          }\n\n          if (ub_w) {\n            delta.push_back({{0, v}, *ub_w});\n          }\n\n          GrOps::apply_delta(g, delta);\n          delta.clear();\n          GrOps::close_after_assign(g, potential, v, delta);\n          GrOps::apply_delta(g, delta);\n\n          // Clear the old x vertex\n          operator-=(x);\n          vert_map.insert(vmap_elt_t(x, v));\n        } else {\n          vert_id v = g.new_vertex();\n          assert(v <= rev_map.size());\n          if (v == rev_map.size()) {\n            rev_map.push_back(x);\n            potential.push_back(Wt(0));\n          } else {\n            assert(!rev_map[v]);\n            potential[v] = Wt(0);\n            rev_map[v] = x;\n          }\n          Wt_min min_op;\n          edge_vector cst_edges;\n\n          if (lb_w) {\n            cst_edges.push_back({{v, 0}, *lb_w});\n          }\n          if (ub_w) {\n            cst_edges.push_back({{0, v}, *ub_w});\n          }\n\n          for (auto diff : diffs_lb) {\n            cst_edges.push_back({{v, get_vert(diff.first)}, -diff.second});\n          }\n\n          for (auto diff : diffs_ub) {\n            cst_edges.push_back({{get_vert(diff.first), v}, diff.second});\n          }\n\n          for (auto diff : cst_edges) {\n            vert_id src = diff.first.first;\n            vert_id dest = diff.first.second;\n            g.update_edge(src, diff.second, dest, min_op);\n            if (!repair_potential(src, dest)) {\n              assert(0 && \"Unreachable\");\n              set_to_bottom();\n            }\n            assert(check_potential(g, potential));\n            close_over_edge(src, dest);\n            assert(check_potential(g, potential));\n          }\n          // Clear the old x vertex\n          operator-=(x);\n          vert_map.insert(vmap_elt_t(x, v));\n        }\n        assert(check_potential(g, potential));\n      } else {\n        set(x, x_int);\n      }\n      // CRAB_WARN(\"DBM only supports a cst or var on the rhs of assignment\");\n      // this->operator-=(x);\n    }\n\n    // g.check_adjs();\n\n    assert(check_potential(g, potential));\n    CRAB_LOG(\"zones-sparse\", crab::outs() << \"---\" << x << \":=\" << e << \"\\n\"\n                                          << *this << \"\\n\";);\n  }\n\n  void apply(arith_operation_t op, const variable_t &x, const variable_t &y,\n             const variable_t &z) override {\n    crab::CrabStats::count(domain_name() + \".count.apply\");\n    crab::ScopedCrabStats __st__(domain_name() + \".apply\");\n\n    if (is_bottom()) {\n      return;\n    }\n\n    normalize();\n\n    switch (op) {\n    case OP_ADDITION:\n      assign(x, y + z);\n      break;\n    case OP_SUBTRACTION:\n      assign(x, y - z);\n      break;\n    // For the rest of operations, we fall back on intervals.\n    case OP_MULTIPLICATION:\n      set(x, get_interval(y) * get_interval(z));\n      break;\n    case OP_SDIV:\n      set(x, get_interval(y) / get_interval(z));\n      break;\n    case OP_UDIV:\n      set(x, get_interval(y).UDiv(get_interval(z)));\n      break;\n    case OP_SREM:\n      set(x, get_interval(y).SRem(get_interval(z)));\n      break;\n    case OP_UREM:\n      set(x, get_interval(y).URem(get_interval(z)));\n      break;\n    default:\n      CRAB_ERROR(\"Operation \", op, \" not supported\");\n    }\n    CRAB_LOG(\"zones-sparse\", crab::outs()\n                                 << \"---\" << x << \":=\" << y << op << z << \"\\n\"\n                                 << *this << \"\\n\";);\n  }\n\n  void apply(arith_operation_t op, const variable_t &x, const variable_t &y,\n             number_t k) override {\n    crab::CrabStats::count(domain_name() + \".count.apply\");\n    crab::ScopedCrabStats __st__(domain_name() + \".apply\");\n\n    if (is_bottom()) {\n      return;\n    }\n\n    normalize();\n\n    switch (op) {\n    case OP_ADDITION:\n      assign(x, y + k);\n      break;\n    case OP_SUBTRACTION:\n      assign(x, y - k);\n      break;\n    // For the rest of operations, we fall back on intervals.\n    case OP_MULTIPLICATION:\n      set(x, get_interval(y) * interval_t(k));\n      break;\n    case OP_SDIV:\n      set(x, get_interval(y) / interval_t(k));\n      break;\n    case OP_UDIV:\n      set(x, get_interval(y).UDiv(interval_t(k)));\n      break;\n    case OP_SREM:\n      set(x, get_interval(y).SRem(interval_t(k)));\n      break;\n    case OP_UREM:\n      set(x, get_interval(y).URem(interval_t(k)));\n      break;\n    default:\n      CRAB_ERROR(\"Operation \", op, \" not supported\");\n    }\n\n    CRAB_LOG(\"zones-sparse\", crab::outs()\n                                 << \"---\" << x << \":=\" << y << op << k << \"\\n\"\n                                 << *this << \"\\n\";);\n  }\n\n  void operator+=(const linear_constraint_t &cst) {\n    crab::CrabStats::count(domain_name() + \".count.add_constraints\");\n    crab::ScopedCrabStats __st__(domain_name() + \".add_constraints\");\n\n    // XXX: we do nothing with unsigned linear inequalities\n    if (cst.is_inequality() && cst.is_unsigned()) {\n      CRAB_WARN(\"unsigned inequality \", cst, \" skipped by split_dbm domain\");\n      return;\n    }\n\n    if (is_bottom())\n      return;\n\n    normalize();\n\n    if (cst.is_tautology())\n      return;\n\n    // g.check_adjs();\n\n    if (cst.is_contradiction()) {\n      set_to_bottom();\n      return;\n    }\n\n    if (cst.is_inequality()) {\n      if (!add_linear_leq(cst.expression())) {\n        set_to_bottom();\n      }\n      // g.check_adjs();\n      CRAB_LOG(\"zones-sparse\", crab::outs() << \"--- \" << cst << \"\\n\"\n                                            << *this << \"\\n\";);\n      return;\n    }\n\n    if (cst.is_strict_inequality()) {\n      // We try to convert a strict to non-strict.\n      auto nc =\n          ikos::linear_constraint_impl::strict_to_non_strict_inequality(cst);\n      if (nc.is_inequality()) {\n        // here we succeed\n        if (!add_linear_leq(nc.expression())) {\n          set_to_bottom();\n        }\n        CRAB_LOG(\"zones-split\", crab::outs() << \"--- \" << cst << \"\\n\"\n                                             << *this << \"\\n\");\n        return;\n      }\n    }\n\n    if (cst.is_equality()) {\n      const linear_expression_t &exp = cst.expression();\n      if (!add_linear_leq(exp) || !add_linear_leq(-exp)) {\n        CRAB_LOG(\"zones-sparse\", crab::outs() << \" ~~> _|_\"\n                                              << \"\\n\";);\n        set_to_bottom();\n      }\n      // g.check_adjs();\n      CRAB_LOG(\"zones-sparse\", crab::outs() << \"--- \" << cst << \"\\n\"\n                                            << *this << \"\\n\";);\n      return;\n    }\n\n    if (cst.is_disequation()) {\n      add_disequation(cst.expression());\n      return;\n    }\n\n    CRAB_WARN(\"Unhandled constraint \", cst, \" by split_dbm\");\n    CRAB_LOG(\"zones-sparse\", crab::outs() << \"---\" << cst << \"\\n\"\n                                          << *this << \"\\n\";);\n    return;\n  }\n\n  void operator+=(const linear_constraint_system_t &csts) override {\n    if (is_bottom())\n      return;\n\n    for (auto cst : csts) {\n      operator+=(cst);\n    }\n  }\n\n  interval_t operator[](const variable_t &x) override {\n    crab::CrabStats::count(domain_name() + \".count.to_intervals\");\n    crab::ScopedCrabStats __st__(domain_name() + \".to_intervals\");\n\n    // Needed for accuracy\n    normalize();\n\n    if (is_bottom()) {\n      return interval_t::bottom();\n    } else {\n      // XXX: we should normalize\n      return get_interval(vert_map, g, x);\n    }\n  }\n\n  void set(const variable_t &x, interval_t intv) {\n    crab::CrabStats::count(domain_name() + \".count.assign\");\n    crab::ScopedCrabStats __st__(domain_name() + \".assign\");\n\n    if (is_bottom()) {\n      return;\n    }\n\n    if (intv.is_bottom()) {\n      set_to_bottom();\n      return;\n    }\n\n    this->operator-=(x);\n\n    if (intv.is_top()) {\n      return;\n    }\n\n    vert_id v = get_vert(x);\n    bool overflow;\n    if (intv.ub().is_finite()) {\n      Wt ub = ntow::convert(*(intv.ub().number()), overflow);\n      if (overflow) {\n        return;\n      }\n      potential[v] = potential[0] + ub;\n      g.set_edge(0, ub, v);\n      close_over_edge(0, v);\n    }\n    if (intv.lb().is_finite()) {\n      Wt lb = ntow::convert(*(intv.lb().number()), overflow);\n      if (overflow) {\n        return;\n      }\n      potential[v] = potential[0] + lb;\n      g.set_edge(v, -lb, 0);\n      close_over_edge(v, 0);\n    }\n  }\n\n  // backward arithmetic operators\n  void backward_assign(const variable_t &x, const linear_expression_t &e,\n                       const DBM_t &inv) override {\n    crab::CrabStats::count(domain_name() + \".count.backward_assign\");\n    crab::ScopedCrabStats __st__(domain_name() + \".backward_assign\");\n\n    crab::domains::BackwardAssignOps<DBM_t>::assign(*this, x, e, inv);\n  }\n\n  void backward_apply(arith_operation_t op, const variable_t &x,\n                      const variable_t &y, number_t z,\n                      const DBM_t &inv) override {\n    crab::CrabStats::count(domain_name() + \".count.backward_apply\");\n    crab::ScopedCrabStats __st__(domain_name() + \".backward_apply\");\n\n    crab::domains::BackwardAssignOps<DBM_t>::apply(*this, op, x, y, z, inv);\n  }\n\n  void backward_apply(arith_operation_t op, const variable_t &x,\n                      const variable_t &y, const variable_t &z,\n                      const DBM_t &inv) override {\n    crab::CrabStats::count(domain_name() + \".count.backward_apply\");\n    crab::ScopedCrabStats __st__(domain_name() + \".backward_apply\");\n\n    crab::domains::BackwardAssignOps<DBM_t>::apply(*this, op, x, y, z, inv);\n  }\n\n  // cast operators\n\n  void apply(int_conv_operation_t op, const variable_t &dst,\n             const variable_t &src) override {\n    // since reasoning about infinite precision we simply assign and\n    // ignore the widths.\n    assign(dst, src);\n\n    if ((op == crab::domains::OP_ZEXT || op == crab::domains::OP_SEXT) &&\n\tsrc.get_type().is_bool()) {\n      interval_t dst_max(number_t(0), number_t(1));\n      set(dst, operator[](dst) & dst_max);\n    }    \n  }\n\n  // bitwise operators\n\n  void apply(bitwise_operation_t op, const variable_t &x, const variable_t &y,\n             const variable_t &z) override {\n    crab::CrabStats::count(domain_name() + \".count.apply\");\n    crab::ScopedCrabStats __st__(domain_name() + \".apply\");\n\n    if (is_bottom())\n      return;\n    normalize();\n\n    // Convert to intervals and perform the operation\n    interval_t yi = operator[](y);\n    interval_t zi = operator[](z);\n    interval_t xi = interval_t::bottom();\n    switch (op) {\n    case OP_AND: {\n      xi = yi.And(zi);\n      break;\n    }\n    case OP_OR: {\n      xi = yi.Or(zi);\n      break;\n    }\n    case OP_XOR: {\n      xi = yi.Xor(zi);\n      break;\n    }\n    case OP_SHL: {\n      xi = yi.Shl(zi);\n      break;\n    }\n    case OP_LSHR: {\n      xi = yi.LShr(zi);\n      break;\n    }\n    case OP_ASHR: {\n      xi = yi.AShr(zi);\n      break;\n    }\n    default:\n      CRAB_ERROR(\"DBM: unreachable\");\n    }\n    set(x, xi);\n  }\n\n  void apply(bitwise_operation_t op, const variable_t &x, const variable_t &y,\n             number_t k) override {\n    crab::CrabStats::count(domain_name() + \".count.apply\");\n    crab::ScopedCrabStats __st__(domain_name() + \".apply\");\n\n    if (is_bottom())\n      return;\n    normalize();\n\n    // Convert to intervals and perform the operation\n    interval_t yi = operator[](y);\n    interval_t zi(k);\n    interval_t xi = interval_t::bottom();\n\n    switch (op) {\n    case OP_AND: {\n      xi = yi.And(zi);\n      break;\n    }\n    case OP_OR: {\n      xi = yi.Or(zi);\n      break;\n    }\n    case OP_XOR: {\n      xi = yi.Xor(zi);\n      break;\n    }\n    case OP_SHL: {\n      xi = yi.Shl(zi);\n      break;\n    }\n    case OP_LSHR: {\n      xi = yi.LShr(zi);\n      break;\n    }\n    case OP_ASHR: {\n      xi = yi.AShr(zi);\n      break;\n    }\n    default:\n      CRAB_ERROR(\"DBM: unreachable\");\n    }\n    set(x, xi);\n  }\n\n  /// sparse_dbm_domain implements only standard abstract operations\n  /// of a numerical domain so it is intended to be used as a leaf\n  /// domain in the hierarchy of domains.\n  BOOL_OPERATIONS_NOT_IMPLEMENTED(DBM_t)\n  ARRAY_OPERATIONS_NOT_IMPLEMENTED(DBM_t)\n  REGION_AND_REFERENCE_OPERATIONS_NOT_IMPLEMENTED(DBM_t)\n  DEFAULT_SELECT(DBM_t)\n  \n  void rename(const variable_vector_t &from,\n              const variable_vector_t &to) override {\n    crab::CrabStats::count(domain_name() + \".count.rename\");\n    crab::ScopedCrabStats __st__(domain_name() + \".rename\");\n\n    if (is_top() || is_bottom())\n      return;\n\n    // renaming vert_map by creating a new vert_map since we are\n    // modifying the keys.\n    // rev_map is modified in-place since we only modify values.\n    CRAB_LOG(\"zones-sparse\", crab::outs() << \"Renaming {\";\n             for (auto v\n                  : from) crab::outs()\n             << v << \";\";\n             crab::outs() << \"} with \"; for (auto v\n                                             : to) crab::outs()\n                                        << v << \";\";\n             crab::outs() << \"}:\\n\"; crab::outs() << *this << \"\\n\";);\n\n    for (unsigned i = 0, sz = from.size(); i < sz; ++i) {\n      variable_t v = from[i];\n      variable_t new_v = to[i];\n      if (v == new_v) { // nothing to rename\n        continue;\n      }\n\n      { // We do garbage collection of unconstrained variables only\n        // after joins so it's possible to find new_v but we are ok as\n        // long as it's unconstrained.\n        auto it = vert_map.find(new_v);\n        if (it != vert_map.end()) {\n          vert_id dim = it->second;\n          if (g.succs(dim).size() != 0 || g.preds(dim).size() != 0) {\n            CRAB_ERROR(domain_name() + \"::rename assumes that \", new_v,\n                       \" does not exist\");\n          }\n        }\n      }\n\n      auto it = vert_map.find(v);\n      if (it != vert_map.end()) {\n        vert_id dim = it->second;\n        vert_map.erase(it);\n        vert_map.insert(vmap_elt_t(new_v, dim));\n        rev_map[dim] = new_v;\n      }\n    }\n\n    CRAB_LOG(\"zones-sparse\", crab::outs() << \"RESULT=\" << *this << \"\\n\");\n  }\n\n  void forget(const variable_vector_t &variables) override {\n    crab::CrabStats::count(domain_name() + \".count.forget\");\n    crab::ScopedCrabStats __st__(domain_name() + \".forget\");\n\n    if (is_bottom() || is_top())\n      return;\n\n    for (auto const &v : variables) {\n      auto it = vert_map.find(v);\n      if (it != vert_map.end()) {\n        operator-=(v);\n      }\n    }\n  }\n\n  void project(const variable_vector_t &variables) override {\n    crab::CrabStats::count(domain_name() + \".count.project\");\n    crab::ScopedCrabStats __st__(domain_name() + \".project\");\n\n    if (is_bottom() || is_top()) {\n      return;\n    }\n    if (variables.empty()) {\n      set_to_top();\n      return;\n    }\n\n    normalize();\n\n    std::vector<bool> save(rev_map.size(), false);\n    for (auto const &x : variables) {\n      auto it = vert_map.find(x);\n      if (it != vert_map.end()) {\n        save[(*it).second] = true;\n      }\n    }\n\n    for (vert_id v = 0; v < rev_map.size(); v++) {\n      if (!save[v] && rev_map[v]) {\n        variable_t vv = (*rev_map[v]);\n        operator-=(vv);\n      }\n    }\n  }\n\n  void expand(const variable_t &x, const variable_t &y) override {\n    crab::CrabStats::count(domain_name() + \".count.expand\");\n    crab::ScopedCrabStats __st__(domain_name() + \".expand\");\n\n    if (is_bottom() || is_top()) {\n      return;\n    }\n\n    CRAB_LOG(\"zones-sparse\", crab::outs() << \"Before expand \" << x << \" into \"\n                                          << y << \":\\n\"\n                                          << *this << \"\\n\");\n\n    auto it = vert_map.find(y);\n    if (it != vert_map.end()) {\n      CRAB_ERROR(\"sparse_dbm expand operation failed because y already exists\");\n    }\n\n    vert_id ii = get_vert(x);\n    vert_id jj = get_vert(y);\n\n    for (auto edge : g.e_preds(ii)) {\n      g.add_edge(edge.vert, edge.val, jj);\n    }\n\n    for (auto edge : g.e_succs(ii)) {\n      g.add_edge(jj, edge.val, edge.vert);\n    }\n\n    potential[jj] = potential[ii];\n\n    CRAB_LOG(\"zones-sparse\", crab::outs() << \"After expand \" << x << \" into \"\n                                          << y << \":\\n\"\n                                          << *this << \"\\n\");\n  }\n\n  void extract(const variable_t &x, linear_constraint_system_t &csts,\n               bool only_equalities) {\n    crab::CrabStats::count(domain_name() + \".count.extract\");\n    crab::ScopedCrabStats __st__(domain_name() + \".extract\");\n\n    normalize();\n    if (is_bottom()) {\n      return;\n    }\n\n    auto it = vert_map.find(x);\n    if (it != vert_map.end()) {\n      vert_id s = (*it).second;\n      if (rev_map[s]) {\n        variable_t vs = *rev_map[s];\n        SubGraph<graph_t> g_excl(g, 0);\n        for (vert_id d : g_excl.verts()) {\n          if (rev_map[d]) {\n            variable_t vd = *rev_map[d];\n            // We give priority to equalities since some domains\n            // might not understand inequalities\n            if (g_excl.elem(s, d) && g_excl.elem(d, s) &&\n                g_excl.edge_val(s, d) == Wt(0) &&\n                g_excl.edge_val(d, s) == Wt(0)) {\n              linear_constraint_t cst(linear_expression_t(vs) == vd);\n              csts += cst;\n            } else {\n              if (!only_equalities && g_excl.elem(s, d)) {\n                linear_constraint_t cst(vd - vs <=\n                                        number_t(g_excl.edge_val(s, d)));\n                csts += cst;\n              }\n              if (!only_equalities && g_excl.elem(d, s)) {\n                linear_constraint_t cst(vs - vd <=\n                                        number_t(g_excl.edge_val(d, s)));\n                csts += cst;\n              }\n            }\n          }\n        }\n      }\n    }\n  }\n\n  /* begin intrinsics operations */\n  void intrinsic(std::string name,\n\t\t const variable_or_constant_vector_t &inputs,\n                 const variable_vector_t &outputs) override {\n    CRAB_WARN(\"Intrinsics \", name, \" not implemented by \", domain_name());\n  }\n\n  void backward_intrinsic(std::string name,\n\t\t\t  const variable_or_constant_vector_t &inputs,\n                          const variable_vector_t &outputs,\n                          const DBM_t &invariant) override {\n    CRAB_WARN(\"Intrinsics \", name, \" not implemented by \", domain_name());\n  }\n  /* end intrinsics operations */\n\n  // Output function\n  void write(crab_os &o) const override {\n    crab::CrabStats::count(domain_name() + \".count.write\");\n    crab::ScopedCrabStats __st__(domain_name() + \".write\");\n\n    // linear_constraint_system_t inv = to_linear_constraint_system();\n    // o << inv;\n\n    if (need_normalization()) {\n      DBM_t tmp(*this);\n      tmp.normalize();\n      write(o, tmp);\n    } else {\n      write(o, *this);\n    }\n  }\n\n  linear_constraint_system_t to_linear_constraint_system() const override {\n    crab::CrabStats::count(domain_name() +\n                           \".count.to_linear_constraint_system\");\n    crab::ScopedCrabStats __st__(domain_name() +\n                                 \".to_linear_constraint_system\");\n\n    if (need_normalization()) {\n      DBM_t tmp(*this);\n      tmp.normalize();\n      return to_linear_constraint_system(tmp);\n    } else {\n      return to_linear_constraint_system(*this);\n    }\n  }\n\n  disjunctive_linear_constraint_system_t\n  to_disjunctive_linear_constraint_system() const override {\n    auto lin_csts = to_linear_constraint_system();\n    if (lin_csts.is_false()) {\n      return disjunctive_linear_constraint_system_t(true /*is_false*/);\n    } else if (lin_csts.is_true()) {\n      return disjunctive_linear_constraint_system_t(false /*is_false*/);\n    } else {\n      return disjunctive_linear_constraint_system_t(lin_csts);\n    }\n  }\n\n  // return number of vertices and edges\n  std::pair<std::size_t, std::size_t> size() const {\n    return {g.size(), g.num_edges()};\n  }\n\n  std::string domain_name() const override { return \"SparseDBM\"; }\n\n}; // class sparse_dbm_domain\n\ntemplate <typename Number, typename VariableName, typename Params>\nstruct abstract_domain_traits<sparse_dbm_domain<Number, VariableName, Params>> {\n  using number_t = Number;\n  using varname_t = VariableName;\n};\n\ntemplate <typename Number, typename VariableName, typename Params>\nclass reduced_domain_traits<sparse_dbm_domain<Number, VariableName, Params>> {\npublic:\n  using sdbm_domain_t = sparse_dbm_domain<Number, VariableName, Params>;\n  using variable_t = typename sdbm_domain_t::variable_t;\n  using linear_constraint_system_t =\n      typename sdbm_domain_t::linear_constraint_system_t;\n\n  static void extract(sdbm_domain_t &dom, const variable_t &x,\n                      linear_constraint_system_t &csts, bool only_equalities) {\n    dom.extract(x, csts, only_equalities);\n  }\n};\n\n} // namespace domains\n\n} // namespace crab\n\n#pragma GCC diagnostic pop\n", "meta": {"hexsha": "dcdb2765bd1277477501b2255d15948eb7ee694c", "size": 65419, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/crab/domains/sparse_dbm.hpp", "max_stars_repo_name": "LinerSu/crab", "max_stars_repo_head_hexsha": "8f3516f4b4765f4a093bb3c3a94ac2daa174130c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 152.0, "max_stars_repo_stars_event_min_datetime": "2016-02-28T06:04:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T10:44:56.000Z", "max_issues_repo_path": "include/crab/domains/sparse_dbm.hpp", "max_issues_repo_name": "LinerSu/crab", "max_issues_repo_head_hexsha": "8f3516f4b4765f4a093bb3c3a94ac2daa174130c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 43.0, "max_issues_repo_issues_event_min_datetime": "2017-07-03T06:25:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T21:09:32.000Z", "max_forks_repo_path": "include/crab/domains/sparse_dbm.hpp", "max_forks_repo_name": "LinerSu/crab", "max_forks_repo_head_hexsha": "8f3516f4b4765f4a093bb3c3a94ac2daa174130c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 28.0, "max_forks_repo_forks_event_min_datetime": "2015-11-22T15:51:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-30T00:46:57.000Z", "avg_line_length": 29.9674759505, "max_line_length": 80, "alphanum_fraction": 0.5434201073, "num_tokens": 16960, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4684858145876389}}
{"text": "#pragma once\n\n#include <armadillo>\n#include <string>\n\n#include \"equationofstate/equationofstatebase.hpp\"\n\n/*!\n * \\brief The GERG04 class implements the GERG 2004 equation of state.\n *\n * This is a higly accurate, but extremely complex equation of state. It has\n * explicit forms for a lot of properties like heat capacity etc., which are\n * utilized where possible.\n *\n * \\warning Note that the composition stored internally in GERG04::X is not in\n * the typical order, but in order C1, C2, C3, iC4, nC4, iC5, nC5, C6, N2, CO2.\n *\n * More info:\n *  - <a href=\"http://www.gerg.eu/public/uploads/files/publications/technical_monographs/tm15_04.pdf\"><i>The GERG-2004 Wide-Range Equation of State for Natural Gases and Other Mixtures</i> (O. Kunz and W. Wagner, J. Chem. Eng. Data. 2012, 57, 11, 3032-3091)</a>\n *  - <a href=\"https://doi.org/10.1021/je300655b\"><i>The GERG-2008 Wide-Range Equation of State for Natural Gases and Other Mixtures: An Expansion of GERG-2004</i> (O. Kunz and W. Wagner, J. Chem. Eng. Data. 2012, 57, 11, 3032-3091)</a>\n */\nclass GERG04 : public EquationOfStateBase\n{\npublic:\n    /*!\n     * \\brief GERG04 constructor.\n     *\n     * Initializes the coefficients that only depend on composition.\n     *\n     * \\param composition Gas composition in arma::vec, in the order C1, C2, C3, iC4, nC4, iC5, nC5, C6, N2, CO2.\n     */\n    explicit GERG04(const arma::vec& composition = Composition::defaultComposition);\n\n    /*!\n     * \\brief Evaluate the GERG 2004 equation of state at the given pressure and temperature.\n     *\n     * This is a wrapper around evaluateAllProperties(), which selects the\n     * wanted properties from that function. This could perhaps be optimized a\n     * bit, since some of the calculations are not required. But the brunt of\n     * the cpu time is spent in findDensity() anyway, so there probably isn't\n     * that much to save.\n     *\n     * \\param pressure Gas pressure [Pa]\n     * \\param temperature Gas temperature [K]\n     * \\return See EquationOfStateBase::evaluate().\n     */\n    virtual arma::vec evaluate(const double pressure, const double temperature) const override;\n\n    /*!\n     * \\brief Evaluate all available gas properties at a given pressure and temperature.\n     *\n     * We have implemented 15 of the explicit equations for different properties\n     * given in the GERG 2004 documentation.\n     *\n     * The method returns an arma::vec containing:\n     *  - compressibility factor <i>Z</i>\n     *  - partial derivative of Z wrt. temperature at constant pressure \\f$\\frac{\\partial Z}{\\partial T}|_p\\f$\n     *  - partial derivative of Z wrt. pressure at constant temperature \\f$\\frac{\\partial Z}{\\partial p}|_T\\f$\n     *  - partial derivative of Z wrt. temperature at constant density \\f$\\frac{\\partial Z}{\\partial T}|_\\rho\\f$\n     *  - entropy <i>S</i>\n     *  - internal energy <i>U</i>\n     *  - heat capacity at constant volume \\f$c_v\\f$\n     *  - enthalpy <i>H</i>\n     *  - heat capacity at constant pressure \\f$c_p\\f$\n     *  - gibbs free energy <i>G</i>\n     *  - Joule-Thomson coefficient\n     *  - speed of sound\n     *  - isothermal throttling coefficient\n     *  - density <i>\u03c1</i>\n     *  - isentropic exponent \\f$\\gamma = \\frac{c_p}{c_v}\\f$\n     *\n     * \\warning Other than the compressibility factor, the partial derivatives,\n     * and the heat capacity, the output of this function has not been tested\n     * properly. Feel free to implement tests for the other results.\n     *\n     * \\param pressure Gas pressure [Pa].\n     * \\param temperature Gas temperature [K].\n     * \\return An arma::vec containing all the properties. See the detailed description for more details.\n     */\n    arma::vec evaluateAllProperties(const double pressure, const double temperature) const;\n\n    /*!\n     * \\brief Calculate compressibility Z at given pressure and temperature.\n     * \\param pressure Gas pressure [Pa].\n     * \\param temperature Gas temperature [K].\n     * \\return Compressibility factor Z [-].\n     */\n    virtual double calculateCompressibility(const double pressure, const double temperature) const override;\n\n    /*!\n     * \\brief Set the composition.\n     *\n     * This calls EquationOfStateBase::setComposition(), updates the non-zero\n     * component indices GERG04::m_indices, and calculates the inverse reducing function\n     * for mixture density GERG04::rhored and the reducing function for mixture\n     * temperature GERG04::tred.\n     *\n     * \\param composition New gas composition.\n     * \\param force If the composition should be changed even if it's within machine precision of the previous composition.\n     * \\return True if composition was changed, else false.\n     */\n    virtual bool setComposition(const arma::vec& composition, const bool force = true) override;\n\n    /*!\n     * \\brief Find the density of the gas at a given pressure and temperature.\n     * \\param pressure Gas pressure [Pa].\n     * \\param temperature Gas temperature [K].\n     * \\return Gas density [kg/m3]\n     */\n    double findDensity(const double pressure, const double temperature) const;\n\n    /*!\n     * \\brief Find the soundspeed in the gas at a given temperature and density.\n     * \\param temperature Gas temperature [K].\n     * \\param density Gas density [kg/m3]\n     * \\return Speed of sound in gas [m/s].\n     */\n    double findSpeedOfSound(const double temperature, const double density) const;\n\n//    void useBadHeatCapacities(bool useBadHeatCapacities);\n\n//    arma::vec getOutput() const;\n\n    /*!\n     * \\brief Get the indices of the non-zero components in the composition.\n     *\n     * \\warning Note that the components are stored internally in GERG04 in a\n     * different order than the input order and the usual order, so it's not\n     * straight-forward to relate this to usual composition.\n     *\n     * \\return The indices of the non-zero components.\n     */\n    const arma::uvec& indicesOfNonZeroComponents() const { return m_indices; }\n\nprivate:\n    /*!\n     * \\brief Internal (private) function used in the process of evaluating the GERG 2004 equations.\n     *\n     * Uses Newton-Raphson to find the density, so will be pretty cpu heavy\n     * (depending on the starting point).\n     *\n     * \\param pressure Gas pressure [P].\n     * \\param temperature Gas Temperature [K].\n     * \\param density Gas density [kg/m3].\n     * \\param aroidelta Output argument - left sum in eq. (7.21b) in TM15 (also appears in other equations).\n     * \\param arijdelta Output argument - the right (double) sum in eq. (7.21b) in TM15 (also appears in other equations).\n     * \\param aroideltadelta Output argument - the left sum in eq. (7.21c) in TM15 (also appears in other equations).\n     * \\param arijdeltadelta Output argument - the right (double) sum in eq. (7.21c) in TM15 (also appears in other equations).\n     * \\return The gas density [kg/m3] as well as many other factors via the output arguments.\n     */\n    double findDensity(\n            const double pressure,\n            const double temperature,\n            double& density, // output\n            double& aroidelta, // output\n            double& arijdelta, // output\n            double& aroideltadelta, // output\n            double& arijdeltadelta // output\n            ) const;\n\n    /*!\n     * \\brief Internal (private) function used in the process of evaluating the GERG 2004 equations.\n     * \\param tred_temperature Inverse reduced mixture temperature.\n     * \\param start_rhored Reduced mixture density.\n     * \\param start_rhored_pow_minusOne pow(reduced mixture density, -1)\n     * \\param start_rhored_pow_minusTwo pow(reduced mixture density, -2)\n     * \\param aroidelta Output argument -- left sum in eq. (7.21b) in TM15 (also appears in other equations).\n     * \\param arijdelta Output argument -- the right (double) sum in eq. (7.21b) in TM15 (also appears in other equations).\n     * \\param aroideltadelta Output argument -- the left sum in eq. (7.21c) in TM15 (also appears in other equations).\n     * \\param arijdeltadelta Output argument -- the right (double) sum in eq. (7.21c) in TM15 (also appears in other equations).\n     */\n    void evaluateAlpha_roi_deltas(\n            const double tred_temperature,\n            const double start_rhored,\n            const double start_rhored_pow_minusOne,\n            const double start_rhored_pow_minusTwo,\n            double& aroidelta, // output\n            double& arijdelta, // output\n            double& aroideltadelta, // output\n            double& arijdeltadelta // output\n            ) const;\n\n    /*!\n     * \\brief Internal (private) function that updates the non-zero components.\n     *\n     * This function updates GERG04::m_indices, GERG04::m_firstIndices, and\n     * GERG04::m_lastIndices according to the current composition stored in\n     * GERG04::X.\n     */\n    void setNonZeroComponents();\n\n    /*!\n     * \\brief Set the pressure and temperature independent coefficients.\n     *\n     * This calculates and sets the pressure and temperature independent factors\n     * GERG04::rhored and GERG04::tred, which are stored for efficient'\n     * computation.\n     */\n    void calculateCoefficients();\n\n    const arma::uword N = 10; //!< Number of components\n    arma::vec X; //!< Composition in order CH4, N2, CO2, C2H6, C3H8, nC4H10, iC4H10, nC5H12, iC5H12, nC6H14\n\n    //! Critical temperature [K] for components CH4, N2, CO2, C2H6, C3H8, nC4H10, iC4H10, nC5H12, iC5H12, nC6H14\n    arma::vec Tc =   {190.56,         126.19,         304.13,         305.32,         369.83,         425.13,         407.82,         469.7,          460.35,         507.82};\n    //! Critical density [kg/m3] for components CH4, N2, CO2, C2H6, C3H8, nC4H10, iC4H10, nC5H12, iC5H12, nC6H14\n    arma::vec rhoc = {10.14*16.04,    11.18*28.01,    10.62*44.01,    6.87*30.07,     5*44.1,         3.92*58.12,     3.86*58.12,     3.21*72.15,     3.27*72.15,     2.71*86.18};\n    //                ch4,            n2,             c02,            c2h6,           c3h8,           nc4h10,         ic4h10,         nc5h12,         ic5h12          nc6h14\n\n    /*!\n     * \\brief The indices of the non-zero gas fractions (components).\n     *\n     * \\warning Note that the components are stored internally in GERG04 in a\n     * different order than the input order and the usual order, so it's not\n     * straight-forward to relate this to usual composition.\n     */\n    arma::uvec m_indices;\n\n    /*!\n     * \\brief The indices of the two first non-zero gas fractions (components).\n     *\n     * \\warning Note that the components are stored internally in GERG04 in a\n     * different order than the input order and the usual order, so it's not\n     * straight-forward to relate this to usual composition.\n     */\n    arma::uvec m_firstIndices;\n\n    /*!\n     * \\brief The indices of the two last non-zero gas fractions (components).\n     *\n     * \\warning Note that the components are stored internally in GERG04 in a\n     * different order than the input order and the usual order, so it's not\n     * straight-forward to relate this to usual composition.\n     */\n    arma::uvec m_lastIndices;\n\n    static arma::mat betav; //!< \\f$\\beta_{v, ij}\\f$ density interaction coefficient, from table A3.8\n    static arma::mat betat; //!< \\f$\\beta_{T, ij}\\f$ temperature coefficient, from table A3.8\n    static arma::mat gammav; //!< \\f$\\gamma_{v, ij}\\f$ density interaction coefficient, from table A3.8\n    static arma::mat gammat; //!< \\f$\\gamma_{T, ij}\\f$ temperature interaction coefficient, from table A3.8\n\n    // Kpol coefficients - used in the first sum in alpha^r_{oi} and derivatives\n    static arma::mat noipol; //!< \\f$n_{oi, k}\\f$, from Table A3.2 in TM15, used in the first sum of alpha^r_{oi}\n    static arma::mat doipol; //!< \\f$d_{oi, k}\\f$, from Table A3.2 in TM15, used in the first sum of alpha^r_{oi}\n    static arma::mat toipol; //!< \\f$t_{oi, k}\\f$, from Table A3.2 in TM15, used in the first sum of alpha^r_{oi}\n\n    // Kexp coefficient - used in the second sum in alpha^r_{oi} and derivatives\n    static arma::mat noiexp; //!< \\f$n_{oi, k}\\f$, from Table A3.3 in TM15, used in the second sum of alpha^r_{oi}\n    static arma::mat doiexp; //!< \\f$d_{oi, k}\\f$, from Table A3.3 in TM15, used in the second sum of alpha^r_{oi}\n    static arma::mat coiexp; //!< \\f$c_{oi, k}\\f$, from Table A3.3 in TM15, used in the second sum of alpha^r_{oi}\n    static arma::mat toiexp; //!< \\f$t_{oi, k}\\f$, from Table A3.3 in TM15, used in the second sum of alpha^r_{oi}\n\n    static arma::mat Fij; //!< \\f$F_{ij}\\f$ interaction coefficient\n\n    static arma::cube nijpol; //!< \\f$n_{ij, k}\\f$, from Table A3.7 in TM15, used in the first sum of alpha^r_{ij}\n    static arma::cube dijpol; //!< \\f$d_{ij, k}\\f$, from Table A3.7 in TM15, used in the first sum of alpha^r_{ij}\n    static arma::cube tijpol; //!< \\f$t_{ij, k}\\f$, from Table A3.7 in TM15, used in the first sum of alpha^r_{ij}\n\n    static arma::cube nijexp; //!< \\f$n_{ij, k}\\f$, from Table A3.7 in TM15, used in the second sum of alpha^r_{ij}\n    static arma::cube dijexp; //!< \\f$d_{ij, k}\\f$, from Table A3.7 in TM15, used in the second sum of alpha^r_{ij}\n    static arma::cube tijexp; //!< \\f$t_{ij, k}\\f$, from Table A3.7 in TM15, used in the second sum of alpha^r_{ij}\n\n    static arma::cube nuijexp; //!< \\f$\\nu_{ij, k}\\f$, from Table A3.7 in TM15, used in the second sum of alpha^r_{ij}\n    static arma::cube epijexp; //!< \\f$\\epsilon_{ij, k}\\f$, from Table A3.7 in TM15, used in the second sum of alpha^r_{ij}\n    static arma::cube beijexp; //!< \\f$\\beta_{ij, k}\\f$, from Table A3.7 in TM15, used in the second sum of alpha^r_{ij}\n    static arma::cube gaijexp; //!< \\f$\\gamma_{ij, k}\\f$, from Table A3.7 in TM15, used in the second sum of alpha^r_{ij}\n\n    // other coefficients\n    static arma::mat noik; //!< \\f$n^o_{oi, k}\\f$, from Table A3.1 in TM15, used in alpha^o_{oi}\n    static arma::mat voik; //!< \\f$n^o_{oi, k}\\f$, from Table A3.1 in TM15, used in alpha^o_{oi}\n\n    // constant terms\n    static arma::cube nijpol_times_tijpol; //!< \\f$n_{ij, k} \\times t_{ij, k}\\f$ (GERG04::nijpol x GERG04::tijpol)\n    static arma::cube nijpol_times_tijpol_times_tijpol_minus_one; //!<  \\f$(n_{ij, k} \\times t_{ij, k}) \\times (t_{ij, k} - 1)\\f$ ((GERG04::nijpol x GERG04::tijpol) x (GERG04::tijpol - 1.0))\n    static arma::cube nijexp_times_tijexp; //!< \\f$n_{ij, k} \\times t_{ij, k}\\f$ (GERG04::nijexp x GERG04::tijexp)\n    static arma::cube nijexp_times_tijexp_times_tijexp_minus_one; //!< \\f$(n_{ij, k} \\times t_{ij, k}) \\times (t_{ij, k} - 1)\\f$ ((GERG04::nijpol x GERG04::tijpol) x (GERG04::tijpol - 1.0))\n    static arma::cube nijpol_times_dijpol; //!< \\f$n_{ij, k} \\times d_{ij, k}\\f$ (GERG04::nijpol x GERG04::dijpol)\n    static arma::cube nijpol_times_dijpol_times_tijpol; //!< \\f$n_{ij, k} \\times d_{ij, k} \\times t_{ij, k}\\f$ (GERG04::nijpol x GERG04::dijpol x GERG04::tijpol)\n    static arma::cube nijpol_times_dijpol_times_dijpol_minus_one; //!< \\f$n_{ij, k} \\times d_{ij, k} \\times(d_{ij, k} - 1) \\f$ (GERG04::nijpol x GERG04::dijpol x (GERG04::dijpol - 1.0))\n\n    double rhored; //!< Inverse reducing function for mixture density \\f$1/\\rho_r(\\bar x)\\f$.\n    double tred; //!< Reducing function for mixture temperature \\f$T_r(\\bar x)\\f$.\n\n    double Ra; //!< Gas constant of mixture [J/mol K]\n};\n", "meta": {"hexsha": "7182ff05404a42c3ba9a207aa7148cad2448ca62", "size": 15257, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/equationofstate/gerg04.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/equationofstate/gerg04.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/equationofstate/gerg04.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": 53.3461538462, "max_line_length": 261, "alphanum_fraction": 0.6558301108, "num_tokens": 4466, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4684858145876389}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2012 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 swaptionvolmatrix.hpp\n    \\brief Swaption matrix whith hull white smiles\n*/\n\n#ifndef quantlib_swaption_volatility_hullwhite_hpp\n#define quantlib_swaption_volatility_hullwhite_hpp\n\n#include <ql/termstructures/yieldtermstructure.hpp>\n#include <ql/indexes/SwapIndex.hpp>\n#include <ql/time/daycounters/actual360.hpp>\n#include <ql/termstructures/volatility/swaption/swaptionvoldiscrete.hpp>\n#include <ql/termstructures/volatility/swaption/swaptionvolstructure.hpp>\n#include <ql/models/shortrate/calibrationhelpers/swaptionhelper.hpp>\n#include <ql/models/shortrate/onefactormodels/hullwhite.hpp>\n#include <ql/math/interpolations/interpolation2d.hpp>\n#include <ql/math/matrix.hpp>\n#include <ql/math/solvers1D/brent.hpp>\n#include <ql/math/optimization/levenbergmarquardt.hpp>\n#include <ql/math/optimization/simplex.hpp>\n#include <ql/math/optimization/costfunction.hpp>\n#include <ql/math/optimization/endcriteria.hpp>\n#include <ql/math/optimization/problem.hpp>\n#include <ql/termstructures/volatility/smilesection.hpp>\n#include <ql/pricingengines/swaption/jamshidianswaptionengine.hpp>\n#include <boost/noncopyable.hpp>\n#include <vector>\n\n#include <iostream>\n\n#include <hullwhitesmilesection.hpp>\n\nnamespace QuantLib {\n\n    class Quote;\n    \n    class SwaptionVolatilityHullWhite : public SwaptionVolatilityDiscrete,\n                                     private boost::noncopyable {\n      public:\n        //! floating reference date, floating market data\n        SwaptionVolatilityHullWhite(const Real reversion, const Handle<YieldTermStructure>& yts, const boost::shared_ptr<SwapIndex> indexBase,\n                    const Calendar& calendar,\n                    BusinessDayConvention bdc,\n                    const std::vector<Period>& optionTenors,\n                    const std::vector<Period>& swapTenors,\n                    const std::vector<std::vector<Handle<Quote> > >& vols,\n                    const DayCounter& dayCounter);\n        //! fixed reference date, floating market data\n        SwaptionVolatilityHullWhite(const Real reversion, const Handle<YieldTermStructure>& yts, const boost::shared_ptr<SwapIndex> indexBase,\n                    const Date& referenceDate,\n                    const Calendar& calendar,\n                    BusinessDayConvention bdc,\n                    const std::vector<Period>& optionTenors,\n                    const std::vector<Period>& swapTenors,\n                    const std::vector<std::vector<Handle<Quote> > >& vols,\n                    const DayCounter& dayCounter);\n        //! floating reference date, fixed market data\n        SwaptionVolatilityHullWhite(const Real reversion, const Handle<YieldTermStructure>& yts, const boost::shared_ptr<SwapIndex> indexBase,\n                    const Calendar& calendar,\n                    BusinessDayConvention bdc,\n                    const std::vector<Period>& optionTenors,\n                    const std::vector<Period>& swapTenors,\n                    const Matrix& volatilities,\n                    const DayCounter& dayCounter);\n        //! fixed reference date, fixed market data\n        SwaptionVolatilityHullWhite(const Real reversion, const Handle<YieldTermStructure>& yts, const boost::shared_ptr<SwapIndex> indexBase,\n                    const Date& referenceDate,\n                    const Calendar& calendar,\n                    BusinessDayConvention bdc,\n                    const std::vector<Period>& optionTenors,\n                    const std::vector<Period>& swapTenors,\n                    const Matrix& volatilities,\n                    const DayCounter& dayCounter);\n        // fixed reference date and fixed market data, option dates\n        SwaptionVolatilityHullWhite(const Real reversion, const Handle<YieldTermStructure>& yts, const boost::shared_ptr<SwapIndex> indexBase,\n\t\t\t\t\t\t\t\t const Date& referenceDate,\n                                 const std::vector<Date>& optionDates,\n                                 const std::vector<Period>& swapTenors,\n                                 const Matrix& volatilities,\n                                 const DayCounter& dayCounter);\n        //! \\name LazyObject interface\n        //@{\n        void performCalculations() const;\n        //@}\n        //! \\name TermStructure interface\n        //@{\n        Date maxDate() const;\n        //@}\n        //! \\name VolatilityTermStructure interface\n        //@{\n        Rate minStrike() const;\n        Rate maxStrike() const;\n        //@}\n        //! \\name SwaptionVolatilityStructure interface\n        //@{\n        const Period& maxSwapTenor() const;\n        //@}\n        //! \\name Other inspectors\n        //@{\n        //! returns the lower indexes of surrounding volatility matrix corners\n        std::pair<Size,Size> locate(const Date& optionDate,\n                                    const Period& swapTenor) const {\n            return locate(timeFromReference(optionDate),\n                          swapLength(swapTenor));\n        }\n        //! returns the lower indexes of surrounding volatility matrix corners\n        std::pair<Size,Size> locate(Time optionTime,\n                                    Time swapLength) const {\n            return std::make_pair(interpolation_.locateY(optionTime),\n                                  interpolation_.locateX(swapLength));\n        }\n        //@}\n      protected:\n        boost::shared_ptr<SmileSection> smileSectionImpl(const Date&,\n                                                         const Period&) const;\n        boost::shared_ptr<SmileSection> smileSectionImpl(Time,\n                                                         Time) const;\n        Volatility volatilityImpl(Time optionTime,\n                                  Time swapLength,\n                                  Rate strike) const;\n\t\tVolatility volatilityImpl(const Date& optionDate, const Period& swapTenor, Rate strike) const;\n\n      private:\n        void checkInputs(Size volRows,\n                         Size volsColumns) const;\n        void registerWithMarketData();\n        std::vector<std::vector<Handle<Quote> > > volHandles_;\n        mutable Matrix volatilities_;\n        mutable Interpolation2D interpolation_;\n\t\tmutable Matrix hwsigmas_;\n\t\tmutable Interpolation2D interpolationSigma_;\n\t\tReal reversion_;\n\t\tHandle<YieldTermStructure> yts_;\n\t\tboost::shared_ptr<SwapIndex> indexBase_;\n\n\t\tstruct calibrationFunction : CostFunction {\n\t\t\t\n\t\t\tcalibrationFunction(boost::shared_ptr<CalibratedModel> model, boost::shared_ptr<SwaptionHelper> helper) : model_(model), helper_(helper) {}\n\n\t\t\tReal value(const Array& params0) const {\n\t\t\t\tArray params(2);\n\t\t\t\tparams[0]=model_->params()[0];\n\t\t\t\tparams[1]=params0[0]*params0[0];\n\t\t\t\tmodel_->setParams(params);\n\t\t\t\tReal error=helper_->calibrationError();\n\t\t\t\treturn error;\t\n\t\t\t}\n\n\t\t\tDisposable<Array> values(const Array& params) const {\n\t\t\t   Array result(1);\n\t\t\t   result[0] = value(params);\n\t\t\t   return result;\n\t\t\t}\n\n\t\t\tboost::shared_ptr<CalibratedModel> model_;\n\t\t\tboost::shared_ptr<SwaptionHelper> helper_;\n\t\t};\n\t};\n\t\t\n\t\t\n\n    // inline definitions\n\n    inline Date SwaptionVolatilityHullWhite::maxDate() const {\n        return optionDates_.back();\n    }\n\n    inline Rate SwaptionVolatilityHullWhite::minStrike() const {\n        return QL_MIN_REAL;\n    }\n\n    inline Rate SwaptionVolatilityHullWhite::maxStrike() const {\n        return QL_MAX_REAL;\n    }\n\n    inline const Period& SwaptionVolatilityHullWhite::maxSwapTenor() const {\n        return swapTenors_.back();\n    }\n\n    inline Volatility SwaptionVolatilityHullWhite::volatilityImpl(Time optionTime,\n                                                               Time swapLength,\n                                                               Rate strike) const {\n        calculate();\n\t\treturn smileSection(optionTime,swapLength,true)->volatility(strike);\n    }\n\n\tinline Volatility SwaptionVolatilityHullWhite::volatilityImpl(const Date& optionDate,\n                                                const Period& swapTenor, Rate strike) const {\n        calculate();\n\t\treturn smileSection(optionDate,swapTenor,true)->volatility(strike);\n    }\n\n}\n\n#endif\n", "meta": {"hexsha": "023f1985f2ee59d38b9dcbff25af83df7b295dc4", "size": 8887, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/experimental/preexperimental/swaptionvolhullwhite.hpp", "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/preexperimental/swaptionvolhullwhite.hpp", "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/preexperimental/swaptionvolhullwhite.hpp", "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": 41.5280373832, "max_line_length": 142, "alphanum_fraction": 0.6337346686, "num_tokens": 1874, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4684858145876389}}
{"text": "#pragma once\n\n#include <boost/polygon/polygon.hpp>\n#include <boost/polygon/voronoi.hpp>\n#include <cslibs_vectormaps/dxf/dxf_map.h>\n\nnamespace boost {\nnamespace polygon {\nusing PointType = cslibs_vectormaps::dxf::DXFMap::Point;\nusing SegmentType = cslibs_vectormaps::dxf::DXFMap::Vector;\ntemplate<>\nstruct geometry_concept<PointType> {\n    typedef point_concept type;\n};\ntemplate<>\nstruct point_traits<PointType> {\n    typedef double coordinate_type;\n\n    static inline coordinate_type get(const PointType &point, orientation_2d orient)\n    {\n        return (orient == HORIZONTAL) ? point.x() : point.y();\n    }\n};\n\ntemplate<>\nstruct geometry_concept<SegmentType> {\n    typedef segment_concept type;\n};\ntemplate<>\nstruct segment_traits<SegmentType> {\n    typedef double coordinate_type;\n    typedef PointType point_type;\n\n    static inline point_type get(const SegmentType &segment, direction_1d dir)\n    {\n        return dir.to_int() ? segment.second : segment.first;\n    }\n};\n}\n}\n\ntypedef boost::polygon::voronoi_diagram<double> VoronoiType;\n\n\n\n", "meta": {"hexsha": "3ea376a69cf7798619249fda921f67e3a6e2bf7a", "size": 1046, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/map_viewer/algorithms/voronoi.hpp", "max_stars_repo_name": "cogsys-tuebingen/cslibs_vectormaps", "max_stars_repo_head_hexsha": "bafdea3e25db51a1324634ded30c69322faa02bb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/map_viewer/algorithms/voronoi.hpp", "max_issues_repo_name": "cogsys-tuebingen/cslibs_vectormaps", "max_issues_repo_head_hexsha": "bafdea3e25db51a1324634ded30c69322faa02bb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-03-31T02:12:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-31T02:12:27.000Z", "max_forks_repo_path": "src/map_viewer/algorithms/voronoi.hpp", "max_forks_repo_name": "cogsys-tuebingen/cslibs_vectormaps", "max_forks_repo_head_hexsha": "bafdea3e25db51a1324634ded30c69322faa02bb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.7391304348, "max_line_length": 84, "alphanum_fraction": 0.7351816444, "num_tokens": 249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.46848580902217607}}
{"text": "//  ================================================================\n//  Created by Gregory Kramida on 10/23/18.\n//  Copyright (c) 2018 Gregory Kramida\n//  Licensed under the Apache License, Version 2.0 (the \"License\");\n//  you may not use this file except in compliance with the License.\n//  You may obtain a copy of the License at\n\n//  http://www.apache.org/licenses/LICENSE-2.0\n\n//  Unless required by applicable law or agreed to in writing, software\n//  distributed under the License is distributed on an \"AS IS\" BASIS,\n//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//  See the License for the specific language governing permissions and\n//  limitations under the License.\n//  ================================================================\n#pragma once\n\n//libraries\n#include <Eigen/Eigen>\n#include <unsupported/Eigen/CXX11/Tensor>\n\n//local\n#include \"data_term.hpp\"\n\nnamespace eig = Eigen;\n\nnamespace nonrigid_optimization {\nnamespace slavcheva{\n\nvoid compute_energy_gradient(const eig::MatrixXf& warped_live_field, const eig::MatrixXf& canonical_field,\n                             const eig::MatrixXf& warp_field_x, const eig::MatrixXf& warp_field_y,\n                             eig::MatrixXf& gradient_field_x, eig::MatrixXf& gradient_field_y,\n                             bool band_union_only = true);\n\n} //namespace slavcheva\n}//namespace nonrigid_optimization\n", "meta": {"hexsha": "1fbc7b15825b3b1942f19ee1d051871f7752aa73", "size": 1403, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/nonrigid_optimization/slavcheva/full_gradient.hpp", "max_stars_repo_name": "Algomorph/LevelSetFusionExperimentsCPP", "max_stars_repo_head_hexsha": "f56962f0ad5c62e6706f818062782a2e1660afda", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2019-01-07T14:12:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T01:48:03.000Z", "max_issues_repo_path": "src/nonrigid_optimization/slavcheva/full_gradient.hpp", "max_issues_repo_name": "Algomorph/LevelSetFusionExperimentsCPP", "max_issues_repo_head_hexsha": "f56962f0ad5c62e6706f818062782a2e1660afda", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2018-12-19T16:43:33.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-06T19:50:22.000Z", "max_forks_repo_path": "src/nonrigid_optimization/slavcheva/full_gradient.hpp", "max_forks_repo_name": "Algomorph/LevelSetFusionExperimentsCPP", "max_forks_repo_head_hexsha": "f56962f0ad5c62e6706f818062782a2e1660afda", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-01-07T14:12:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-06T06:30:24.000Z", "avg_line_length": 37.9189189189, "max_line_length": 106, "alphanum_fraction": 0.6457590877, "num_tokens": 306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.46838406768749374}}
{"text": "\n#include <opencv2/video.hpp>\n#include <opencv2/imgproc.hpp>\n#include <opencv2/highgui.hpp>\n#include <opencv2/features2d.hpp>\n#include <opencv2/calib3d.hpp>\n\n#include <iostream>\n#include <ctype.h>\n#include <algorithm>\n#include <iterator>\n#include <vector>\n#include <ctime>\n#include <sstream>\n#include <fstream>\n#include <string>\n#include <Eigen/Dense>\n#include <unsupported/Eigen/NonLinearOptimization>\n#include <unsupported/Eigen/NumericalDiff>\n#include <opencv2/core/eigen.hpp>\n\n\n\n#include \"feature.h\"\n#include \"utils.h\"\n#include \"evaluate_odometry.h\"\n#include \"visualOdometry.h\"\n#include \"Frame.h\"\n\nusing namespace std;\n\n\nint main(int argc, char **argv)\n{\n\n\t// \u8f7d\u5165\u56fe\u7247\u548c\u6807\u5b9a\u6570\u636e\n    bool display_ground_truth = false;\n    std::vector<Matrix> pose_matrix_gt;\n    if(argc == 4)\n    {   display_ground_truth = true;\n        cerr << \"Display ground truth trajectory\" << endl;\n        // load ground truth pose\n        string filename_pose = string(argv[3]);\n        pose_matrix_gt = loadPoses(filename_pose);\n    }\n    if(argc < 3)\n    {\n        cerr << \"Usage: ./run path_to_sequence path_to_calibration [optional]path_to_ground_truth_pose\" << endl;\n        return 1;\n    }\n\n    // \u6570\u636e\u96c6\u8def\u5f84\uff0c\u76ee\u524d\u53ea\u6d4b\u8bd5\u4e86kitti00\n    string filepath = string(argv[1]);\n    cout << \"Filepath: \" << filepath << endl;\n\n    // \u76f8\u673a\u53c2\u6570\n    string strSettingPath = string(argv[2]);\n    cout << \"Calibration Filepath: \" << strSettingPath << endl;\n\n\tstd::vector<cv::Mat> pose_results;\n\n\n    MVSO::MultiViewStereoOdometry mvso(strSettingPath);\n    \n\t// \u76f8\u673a\u77e9\u9635\n    cv::Mat projMatrl = mvso.camera_.getLeftProjectionMatrix();\n    cv::Mat projMatrr = mvso.camera_.getRightProjectionMatrix();\n\n    // -----------------------------------------\n    // Initialize variables\n    // -----------------------------------------\n    cv::Mat rotation = cv::Mat::eye(3, 3, CV_64F);\n    cv::Mat translation_stereo = cv::Mat::zeros(3, 1, CV_64F);\n\n    cv::Mat Rpose = cv::Mat::eye(3, 3, CV_64F);\n    \n    cv::Mat frame_pose = cv::Mat::eye(4, 4, CV_64F);\n    cv::Mat frame_pose32 = cv::Mat::eye(4, 4, CV_32F);\n\n    std::cout << \"frame_pose \" << frame_pose << std::endl;\n    cv::Mat trajectory = cv::Mat::zeros(600, 1200, CV_8UC3);\n    FeatureSet currentVOFeatures;\n    cv::Mat points4D, points3D;\n    int init_frame_id = 0;\n\n    // ------------------------\n    // \u8bfb\u5165\u7b2c\u4e00\u5e27\u56fe\u50cf\n    // ------------------------\n    cv::Mat imageLeft_t0_color,  imageLeft_t0;\n    loadImageLeft(imageLeft_t0_color,  imageLeft_t0, init_frame_id, filepath);\n    \n    cv::Mat imageRight_t0_color, imageRight_t0;  \n    loadImageRight(imageRight_t0_color, imageRight_t0, init_frame_id, filepath);\n\n\n    float fps;\n\n\tpose_results.push_back(mvso.grabImage(imageLeft_t0_color, imageRight_t0_color));\n\t\n    // -----------------------------------------\n    // \u8fd0\u884c\u89c6\u89c9\u91cc\u7a0b\u8ba1\n    // -----------------------------------------\n    clock_t tic = clock();\n\n    for (int frame_id = init_frame_id+1; frame_id <= 4540; frame_id++)\n    {\n        std::cout << std::endl << \"frame_id \" << frame_id << std::endl;\n        // ------------\n        // \u8bfb\u56fe\n        // ------------\n        cv::Mat imageLeft_t1_color,  imageLeft_t1;\n        loadImageLeft(imageLeft_t1_color,  imageLeft_t1, frame_id, filepath);        \n        cv::Mat imageRight_t1_color, imageRight_t1;  \n        loadImageRight(imageRight_t1_color, imageRight_t1, frame_id, filepath);\n\n\t\tcv::Mat pose_mvso;\n\t\tpose_mvso = mvso.grabImage(imageLeft_t1, imageRight_t1);\n\t\tcv::Mat rotation_mvso, translation_mvso;\n\t\trotation_mvso = pose_mvso.colRange(0, 3);\n\t\ttranslation_mvso = pose_mvso.col(3);\n\t\tpose_results.push_back(pose_mvso);\n\n\t\t//cout << pose_mvso << endl;\n\n\n\t\trotation = rotation_mvso.clone();\n\t\ttranslation_stereo = translation_mvso.clone();\n\n\n        cv::Vec3f rotation_euler = rotationMatrixToEulerAngles(rotation);\n        // std::cout << \"rotation: \" << rotation_euler << std::endl;\n        // std::cout << \"translation: \" << translation_stereo.t() << std::endl;\n\n        cv::Mat rigid_body_transformation;\n\t\t//integrateOdometryStereo(frame_id, rigid_body_transformation, frame_pose, rotation, translation_stereo);\n        \n\t\tif(abs(rotation_euler[1])<0.2 && abs(rotation_euler[0])<0.2 && abs(rotation_euler[2])<0.2)\n        {\n\t\t\tintegrateOdometryStereo(frame_id, rigid_body_transformation, frame_pose, rotation, translation_stereo);\n        } else {\n            std::cout << \"Too large rotation\"  << std::endl;\n        }\n\n        // std::cout << \"rigid_body_transformation\" << rigid_body_transformation << std::endl;\n\n        // std::cout << \"frame_pose\" << frame_pose << std::endl;\n\n\n        Rpose =  frame_pose(cv::Range(0, 3), cv::Range(0, 3));\n        cv::Vec3f Rpose_euler = rotationMatrixToEulerAngles(Rpose);\n        // std::cout << \"Rpose_euler\" << Rpose_euler << std::endl;\n\n        cv::Mat pose = frame_pose.col(3).clone();\n\n        clock_t toc = clock();\n        fps = float(frame_id-init_frame_id)/(toc-tic)*CLOCKS_PER_SEC;\n\n        // std::cout << \"Pose\" << pose.t() << std::endl;\n        std::cout << \"FPS: \" << fps << std::endl;\n\n        display(frame_id, trajectory, pose, pose_matrix_gt, fps, display_ground_truth);\n\n    }\n\tauto eval_time = chrono::system_clock::to_time_t(std::chrono::system_clock::now());\n\tstring time = std::ctime(&eval_time);\n\ttime.erase(time.length() - 1);\n\tfor (char& c : time)\n\t\tif (c == ':')\n\t\t\tc = '~';\n\tstring filename = cv::format(\"trajectory%s.png\", time.c_str());\n\tcout << \"filename: \" << filename << endl;\n\tcv::imwrite(filename, trajectory);\n    return 0;\n}\n\n", "meta": {"hexsha": "132849be0779a8553e331846ec90c7956f4b654b", "size": 5456, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "lambdald/visualOdometry", "max_stars_repo_head_hexsha": "e1a93d6a91de3ae601417d77b604d27d5f9f171f", "max_stars_repo_licenses": ["MIT"], "max_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": "lambdald/visualOdometry", "max_issues_repo_head_hexsha": "e1a93d6a91de3ae601417d77b604d27d5f9f171f", "max_issues_repo_licenses": ["MIT"], "max_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": "lambdald/visualOdometry", "max_forks_repo_head_hexsha": "e1a93d6a91de3ae601417d77b604d27d5f9f171f", "max_forks_repo_licenses": ["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.0, "max_line_length": 112, "alphanum_fraction": 0.6228005865, "num_tokens": 1507, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.4683840676874937}}
{"text": "#ifndef _OPTIMIZE_SCORES_HPP_\n#define _OPTIMIZE_SCORES_HPP_\n\n#include <iostream>\n#include <string>\n#include <math.h>\n#include <algorithm>\n#include <Eigen/Dense>\n#include \"ffttools.hpp\"\n\nnamespace eco_tracker {\n\n  void computeScores(\n      const std::vector<Eigen::MatrixXcf>& scores_fs,\n      const int& max_iteration,\n      int& scale_ind,\n      float& opt_score,\n      float& opt_pos_x,\n      float& opt_pos_y);\n\n} // namespace eco_tracker\n#endif\n", "meta": {"hexsha": "97d252379793422943e3980eb434d5d0f6aedbd7", "size": 449, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "app/inc/optimize_scores.hpp", "max_stars_repo_name": "lygbuaa/eco_tracker", "max_stars_repo_head_hexsha": "d77afb97d356769bfe5f7d9cb5e96b3cf40c4601", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2019-04-20T05:38:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-08T06:30:41.000Z", "max_issues_repo_path": "app/inc/optimize_scores.hpp", "max_issues_repo_name": "lygbuaa/eco_tracker", "max_issues_repo_head_hexsha": "d77afb97d356769bfe5f7d9cb5e96b3cf40c4601", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-06-06T11:12:06.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-10T11:27:12.000Z", "max_forks_repo_path": "app/inc/optimize_scores.hpp", "max_forks_repo_name": "lygbuaa/eco_tracker", "max_forks_repo_head_hexsha": "d77afb97d356769bfe5f7d9cb5e96b3cf40c4601", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-07-12T03:47:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-08T06:44:17.000Z", "avg_line_length": 19.5217391304, "max_line_length": 53, "alphanum_fraction": 0.710467706, "num_tokens": 110, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.46838406768749363}}
{"text": "#include \"pcg_solver/BinBlockCSR.h\"\n#include \"pcg_solver/block6x6_pcg_weber.h\"\n#include \"common/sanity_check.h\"\n\n#include <iostream>\n#include <Eigen/Eigen>\n\nvoid surfelwarp::checkBinBlock6x6SparseMV()\n{\n\t//First load the data for 6x6 block\n\tstd::vector<float> A_data, b, diag_blks;\n\tstd::vector<int> A_colptr, A_rowptr;\n\tloadCheckData(A_data, A_rowptr, A_colptr, b, diag_blks);\n\n\t//Use random vector\n\tconst auto matrix_size = b.size();\n\tVectorXf x; x.resize(matrix_size);\n\tx.setRandom();\n\n\t//Do a spase matrix vector product\n\tstd::vector<float> spmv; \n\tspmv.resize(matrix_size);\n\tfor(auto i = 0; i < matrix_size; i++)\n\t{\n\t\tspmv[i] = BinBlockCSR<6>::SparseMV(A_data.data(), A_colptr.data(), A_rowptr.data(), x.data(), i);\n\t}\n\n\t//Check the result with Eigen version\n\thostEigenSpMV(A_data, A_rowptr, A_colptr, matrix_size, x, b);\n\n\t//Check against b and spmv\n\tassert(b.size() == spmv.size());\n\tconst auto relative_err = maxRelativeError(b, spmv);\n\tif(relative_err > 1e-4)\n\t{\n\t\tstd::cout << \"The relative error of sparse matrix vector product checking \" << relative_err << std::endl;\n\t}\n}\n", "meta": {"hexsha": "79e91b89159dc488e71d1a09fa0480a23d7dd550", "size": 1085, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pcg_solver/BinBlockCSR.cpp", "max_stars_repo_name": "pwais/surfelwarp", "max_stars_repo_head_hexsha": "6e547e6b33b49d903475b869a58c9bda7b9c3061", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 223.0, "max_stars_repo_stars_event_min_datetime": "2019-06-06T04:40:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T05:59:54.000Z", "max_issues_repo_path": "pcg_solver/BinBlockCSR.cpp", "max_issues_repo_name": "pwais/surfelwarp", "max_issues_repo_head_hexsha": "6e547e6b33b49d903475b869a58c9bda7b9c3061", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 69.0, "max_issues_repo_issues_event_min_datetime": "2019-07-13T07:15:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T08:20:39.000Z", "max_forks_repo_path": "pcg_solver/BinBlockCSR.cpp", "max_forks_repo_name": "pwais/surfelwarp", "max_forks_repo_head_hexsha": "6e547e6b33b49d903475b869a58c9bda7b9c3061", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 65.0, "max_forks_repo_forks_event_min_datetime": "2019-06-06T06:06:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-19T15:59:52.000Z", "avg_line_length": 27.8205128205, "max_line_length": 107, "alphanum_fraction": 0.7133640553, "num_tokens": 327, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.46838406768749363}}
{"text": "/*\n * personBHMIP.cpp\n *\n *  Created on: Jul 9, 2013\n *      Author: gferrer\n */\n#include \"scene_elements/person_bhmip.h\"\n#include <Eigen/Dense>\n#include <iostream>\n\nCperson_bhmip::Cperson_bhmip(unsigned int id, Cperson_abstract::target_type person_target_type,\n\t\t Cperson_abstract::force_type person_force_type, double _time_window) :\n    Cperson_abstract(id,person_target_type, person_force_type),\n    time_window_( _time_window ) , phi_var_( 0.8*0.8 )\n{\n\tdestinations_.reserve(15);\n}\n\nCperson_bhmip::~Cperson_bhmip()\n{\n\n}\n\nvoid Cperson_bhmip::add_pointV( SpointV_cov point, Cperson_abstract::filtering_method filter)\n{\n\tSpointV_cov filtered_pose;\n\tif( filter != Cperson_abstract::No_filtering )\n\t{\n\t\tSpointV_cov pointV = point;//only positions, position_covariances and time_stamp\n\t\tdouble dx, dy;\n\t\tif ( !trajectory_.empty() )\n\t\t{\n\t\t\tdx = point.x - trajectory_.back().x;\n\t\t\tdy = point.y - trajectory_.back().y;\n\t\t\tdouble dt =  point.time_stamp - trajectory_.back().time_stamp ;\n\t\t\t//just to avoid singularities, ideally time stamps are well separated in time\n\t\t\tif ( point.time_stamp - trajectory_.back().time_stamp  < 0.001 ) dt = 0.1;\n\t\t\tpointV.vx = dx / dt;\n\t\t\tpointV.vy = dy / dt;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tpointV.vx = 0;\n\t\t\tpointV.vy = 0;\n\t\t}\n\n\t\t//slide temporal window for all trajectories\n\t\ttrajectory_.push_back(pointV);\n\t\ttrajectory_windowing();\n\n\t\t//filters velocities\n\t\tswitch( filter )\n\t\t{\n\t\t  case Cperson_abstract::Linear_regression_filtering:\n\t\t\tfiltered_pose = filter_current_state_linear_regression( );\n\t\t\tbreak;\n\t\t  case Cperson_abstract::Bayes_filtering:\n\t\t\tfiltered_pose = filter_current_state_linear_regression_bayes( );\n\t\t  \tbreak;\n\t\t  case Cperson_abstract::Low_pass_linear_regression_filtering:\n\t\t  default :\n\t\t\tfiltered_pose = low_pass_filter_current_state_linear_regression( );\n\t\t\tbreak;\n\t\t}\n\n\n\t}\n\telse\n\t{\n\t\t//no filter is required\n\t\ttrajectory_.push_back(point);\n\t\t//slide temporal window for all trajectories\n\t\ttrajectory_windowing();\n\t\tfiltered_pose = trajectory_.back();\n\t}\n\n\t//update current positions and velocities according to filtering results\n\tdiff_pointV_ = filtered_pose - current_pointV_ ;\n\tcurrent_pointV_ = filtered_pose;\n\tdesired_velocity_ = filtered_pose.v();\n\tnow_ = filtered_pose.time_stamp;\n\n\n\t//precalculates data required for the BHMIP\n\tintention_precalculation();\n\n\tobservation_update_ = true;\n}\n\n\nSpointV_cov Cperson_bhmip::filter_current_state_linear_regression( )\n{\n\n\n\t//Discard a single and double pose trajectory --------------------------------------------\n\tif (trajectory_.size() <= 2 )\n\t{\n\t\treturn trajectory_.back();\n\t}\n\t// First order Regression: y(t) ~ beta * x(t) = beta_1 + beta_2 * x(t) ----------------------------\n\t//vector and matrices initialization\n\tunsigned int window_elements = trajectory_.size();\n\tdouble initial_ts = trajectory_.front().time_stamp;\n\tEigen::VectorXd vx ( window_elements ) , vy ( window_elements );\n\tEigen::MatrixXd R (window_elements , 2 ); //1st order regression -> 2 coeffs\n\tfor (unsigned int i = 0 ; i < window_elements ; i++)\n\t{\n\t\tvx ( i ) = trajectory_.at(i).vx;\n\t\tvy ( i ) = trajectory_.at(i).vy;\n\t\tR.row ( i ) << 1 , trajectory_.at(i).time_stamp - initial_ts;\n\t}\n\t//pseudo inverse of the R matrix ---------------------------------------------------------------\n\tEigen::MatrixXd invR ( 2 , window_elements ) , sqrR ( 2 , 2 );\n\tsqrR = R.transpose() * R;\n\tinvR = sqrR.inverse() * R.transpose() ;\n\n\t//linear regression ----------------------------------------------------------------------------\n\tEigen::Vector2d  r_pred (1 , trajectory_.back().time_stamp - initial_ts ),vx_coef,vy_coef;\n\t//invR * v = beta -> parameter estimation\n\tvx_coef = invR * vx;\n\tvy_coef = invR * vy;\n\tSpointV_cov filtered_pose(\n\t\t\ttrajectory_.back().x, //no filtering at position\n\t\t\ttrajectory_.back().y,\n\t\t\ttrajectory_.back().time_stamp,\n\t\t\tr_pred.dot ( vx_coef ),\n\t\t\tr_pred.dot ( vy_coef ) );\n    filtered_pose.cov[0] = trajectory_.back().cov_xx();\n    filtered_pose.cov[1] = trajectory_.back().cov_xy();\n    filtered_pose.cov[4] = trajectory_.back().cov_xy();\n    filtered_pose.cov[5] = trajectory_.back().cov_yy();\n\n\n\t//covariance of velocity prediction, with respect to regression velocity\n\tEigen::VectorXd vx_mean ( window_elements ) , vy_mean ( window_elements );\n\tvx_mean = R*vx_coef;\n\tvy_mean = R*vy_coef;\n\tdouble cov_vx = (vx - vx_mean).dot( vx - vx_mean );\n\tdouble cov_vy = (vy - vy_mean).dot( vy - vy_mean );\n\tdouble cov_vxy = (vy - vy_mean).dot( vx - vx_mean );\n\n\t//regression covariances + projected uncertainty from positions P_x / dt\n\tfiltered_pose.cov[10] = cov_vx + 0.001;\n\tfiltered_pose.cov[11] = cov_vxy;\n\tfiltered_pose.cov[14] = filtered_pose.cov[11];\n\tfiltered_pose.cov[15] = cov_vy + 0.001;\n\n\treturn filtered_pose;\n}\n\n\nSpointV_cov Cperson_bhmip::filter_current_state_linear_regression_bayes( )\n{\n\n\t//Discard a single and double pose trajectory --------------------------------------------\n\tif (trajectory_.size() <= 2 )\n\t{\n\t\treturn trajectory_.back();\n\t}\n\t// First order Regression: y(t) ~ beta * x(t) = beta_1 + beta_2 * x(t) ----------------------------\n\t//vector and matrices initialization\n\tunsigned int window_elements = trajectory_.size();\n\tdouble initial_ts = trajectory_.front().time_stamp;\n\tEigen::VectorXd vx ( window_elements ) , vy ( window_elements );\n\tEigen::MatrixXd R (window_elements , 2 ); //1st order regression -> 2 coeffs\n\tfor (unsigned int i = 0 ; i < window_elements ; i++)\n\t{\n\t\tvx ( i ) = trajectory_.at(i).vx;\n\t\tvy ( i ) = trajectory_.at(i).vy;\n\t\tR.row ( i ) << 1 , trajectory_.at(i).time_stamp - initial_ts;\n\t}\n\t//pseudo inverse of the R matrix ---------------------------------------------------------------\n\tEigen::MatrixXd invR ( 2 , window_elements ) , sqrR ( 2 , 2 );\n\tsqrR = R.transpose() * R;\n\tinvR = sqrR.inverse() * R.transpose() ;\n\n\t//linear regression ----------------------------------------------------------------------------\n\tEigen::Vector2d  r_pred (1 , trajectory_.back().time_stamp - initial_ts ),vx_coef,vy_coef;\n\t//invR * v = beta -> parameter estimation\n\tvx_coef = invR * vx;\n\tvy_coef = invR * vy;\n\tSpointV_cov filtered_pose(\n\t\t\ttrajectory_.back().x, //no filtering at position\n\t\t\ttrajectory_.back().y,\n\t\t\ttrajectory_.back().time_stamp,\n\t\t\tr_pred.dot ( vx_coef ),\n\t\t\tr_pred.dot ( vy_coef ) );\n    filtered_pose.cov[0] = trajectory_.back().cov_xx();\n    filtered_pose.cov[1] = trajectory_.back().cov_xy();\n    filtered_pose.cov[4] = trajectory_.back().cov_xy();\n    filtered_pose.cov[5] = trajectory_.back().cov_yy();\n\n\t//covariance of velocity prediction, average of uncertainty propagated from estimated positions, equidistribited\n\tdouble dt;\n\tEigen::Matrix2d v_cov_joint = Eigen::Matrix2d::Zero();\n\tfor( unsigned int i = 0; i < window_elements ; i++)\n\t{\n\t\tif( i == 0 )\n\t\t\tdt = R(1,1)-R(0,1);\n\t\telse\n\t\t\tdt = R(i,1)-R(i-1,1);\n\t\tEigen::Matrix2d v_cov;\n\t\tv_cov << trajectory_.at(i).cov_xx() , trajectory_.at(i).cov_xy(),\n\t\t\t\ttrajectory_.at(i).cov_xy() , trajectory_.at(i).cov_yy();\n\t\tv_cov_joint += v_cov / (dt*dt);\n\t}\n\n\t//regression covariances + projected uncertainty from positions P_x / dt\n\tdouble N = 2.0*(double)window_elements*(double)window_elements;\n\tfiltered_pose.cov[10] = v_cov_joint(0,0)/N;\n\tfiltered_pose.cov[11] = v_cov_joint(0,1)/N;\n\tfiltered_pose.cov[14] = filtered_pose.cov[11];\n\tfiltered_pose.cov[15] = v_cov_joint(1,1)/N;\n\n\treturn filtered_pose;\n}\n\nSpointV_cov Cperson_bhmip::low_pass_filter_current_state_linear_regression( )\n{\n\n\t//Discard a single and double pose trajectory --------------------------------------------\n\tif (trajectory_.size() <= 2 )\n\t{\n\t\treturn trajectory_.back();\n\t}\n\t// First order Regression: y(t) ~ beta * x(t) = beta_1 + beta_2 * x(t) ----------------------------\n\t//vector and matrices initialization\n\tunsigned int window_elements = trajectory_.size();\n//\tdouble initial_ts = trajectory_.front().time_stamp;\n\tEigen::VectorXd vx ( window_elements ) , vy ( window_elements );\n\tEigen::VectorXd R (window_elements ); //0st order regression -> 1 coeffs\n\tEigen::VectorXd r_pred (window_elements);\n\tfor (unsigned int i = 0 ; i < window_elements ; i++)\n\t{\n\t\tvx ( i ) = trajectory_.at(i).vx;\n\t\tvy ( i ) = trajectory_.at(i).vy;\n\t\tR(i)=1;\n\t\tr_pred(i)=1;\n\t}\n\t//pseudo inverse of the R matrix ---------------------------------------------------------------\n\tEigen::VectorXd invR (  window_elements );\n\tdouble sqrR =  R.dot( R);\n\tinvR = (1/sqrR) * R.transpose() ;\n\n\t//linear regression ----------------------------------------------------------------------------\n\n\t//invR * v = beta -> parameter estimation\n\tdouble vx_coef =  invR.dot(vx.transpose());\n\tdouble vy_coef = invR.dot(vy.transpose());\n\n\tSpointV_cov filtered_pose(\n\t\t\ttrajectory_.back().x, //no filtering at position\n\t\t\ttrajectory_.back().y,\n\t\t\ttrajectory_.back().time_stamp,\n\t\t\tvx_coef ,\n\t\t\tvy_coef );\n\n    filtered_pose.cov[0] = trajectory_.back().cov_xx();\n    filtered_pose.cov[1] = trajectory_.back().cov_xy();\n    filtered_pose.cov[4] = trajectory_.back().cov_xy();\n    filtered_pose.cov[5] = trajectory_.back().cov_yy();\n\n\n\t//covariance of velocity prediction, with respect to regression velocity\n\tEigen::VectorXd vx_mean ( window_elements ) , vy_mean ( window_elements );\n\tvx_mean = R*vx_coef;\n\tvy_mean = R*vy_coef;\n\tdouble cov_vx = (vx - vx_mean).dot( vx - vx_mean );\n\tdouble cov_vy = (vy - vy_mean).dot( vy - vy_mean );\n\tdouble cov_vxy = (vy - vy_mean).dot( vx - vx_mean );\n\n\t//regression covariances + projected uncertainty from positions P_x / dt\n\tfiltered_pose.cov[10] = cov_vx;// + 0.001;\n\tfiltered_pose.cov[11] = cov_vxy;\n\tfiltered_pose.cov[14] = filtered_pose.cov[11];\n\tfiltered_pose.cov[15] = cov_vy;// + 0.001;\n\n\treturn filtered_pose;\n}\n\n\nvoid  Cperson_bhmip::intention_precalculation()\n{\n\tdouble phi , phi_prob;\n\tstd::vector<double> s;\n\tphi_pose2dest_.push_back( s );\n\tphi_prob_.push_back( s );\n\tfor(unsigned int i = 0; i < destinations_.size() ; ++i)\n\t{\n\t\tdouble dx = destinations_[i].x - current_pointV_.x;\n\t\tdouble dy = destinations_[i].y - current_pointV_.y;\n\t\tphi = diffangle( atan2(  dy , dx ) , current_pointV_.orientation());\n\t\tphi_pose2dest_.back().push_back( phi );\n\t\t//c * Pr ( phi | destination_i) calculations\n\t\tphi_prob = 100*exp( - phi*phi / phi_var_ );\n\t\tphi_prob_.back().push_back( phi_prob );\n\t}\n\n\n}\n\nvoid Cperson_bhmip::trajectory_windowing()\n{\n\twhile(  trajectory_.back().time_stamp  - trajectory_.front().time_stamp >  time_window_ )\n\t{\n\t\ttrajectory_.pop_front();\n\t\tif(type_ == Person)//Robot and Virtual_Person do not require prediction methods\n\t\t{\n\t\t\tphi_pose2dest_.pop_front();\n\t\t\tphi_prob_.pop_front();\n\t\t}\n\t}\n}\n\nvoid Cperson_bhmip::refresh_person( double now )\n{\n\t//this method is used when manual remove of persons is required and thus, we must\n\t//guarantee that the trajectory container and other variables are OK\n\n\tif (trajectory_.empty() )\n\t{\n\t\twhile( trajectory_.back().time_stamp - now > time_window_)\n\t\t{\n\t\t\ttrajectory_.pop_front();\n\t\t\tif (trajectory_.empty() ) break;\n\t\t}\n\t}\n\tnow_ = now;\n}\n\nvoid Cperson_bhmip::prediction( double min_v_to_predict )\n{\n\t//calculate if it is adequate to predict intentionality:\n\t//if target is almost stopped and decelerating\n\tif( current_pointV_.v() <  min_v_to_predict)\n\t{\n\t\tbest_destination_ = Sdestination( 0, current_pointV_.x, current_pointV_.y,\n\t\t\t\t1.0, Sdestination::Stopping);\n\t\tdesired_velocity_ = 0.0;//to avoid being too reactive to its environment, it remains in place v_d = 0.0\n\t\treturn;\n\t}\n\n\t//calculate probabilities to destinations\n\tdouble norm_term(0.0),max_prob(-0.1);\n\tunsigned int max_prob_index;\n\tposterior_destinations_prob_.clear();\n\tfor( unsigned int i = 0; i<destinations_.size() ; ++i)\n\t{\n\t\tposterior_destinations_prob_.push_back( destinations_[i].prob);\n\t\tfor (unsigned int j = 0; j < phi_prob_.size() ; ++j)\n\t\t{\n\t\t\t//phi_probabilities [ time ] [ destination ]\n\t\t\tposterior_destinations_prob_[i] *= phi_prob_[j][i];\n\t\t}\n\t\tnorm_term += posterior_destinations_prob_[i];\n\t\tif( max_prob < posterior_destinations_prob_[i])\n\t\t{\n\t\t\tmax_prob_index = i;\n\t\t\tmax_prob = posterior_destinations_prob_[i];\n\t\t}\n\t}\n\n\t//uncertain behavior of prediction depending on certain threshold\n\tif( 0) //max_prob < 1e16 )//hardcoded threshold corresponds aprox to a diff of 45\u00ba\n\t{\n\t\tbest_destination_ = Sdestination( 0, current_pointV_.x, current_pointV_.y,\n\t\t\t\t1.0, Sdestination::Uncertain);\n\t\treturn;\n\t}\n\t//normalization of probabilities\n\tnorm_term = 1/norm_term;\n\tif ( !is_nan( norm_term ) && !destinations_.empty() )\n\t{\n\t\tfor (unsigned int i = 0 ; i < destinations_.size() ; ++i)\n\t\t\tposterior_destinations_prob_[i] *= norm_term;\n\t\tbest_destination_ = destinations_[max_prob_index];\n\t\tbest_destination_.prob = posterior_destinations_prob_[max_prob_index];\n\t}\n\telse\n\t{\n\t\tbest_destination_ = Sdestination( 0, current_pointV_.x, current_pointV_.y,\n\t\t\t\t1.0, Sdestination::Uncertain);\n\t}\n}\n\nvoid Cperson_bhmip::reset(  )\n{\n\ttrajectory_.clear();\n\tcurrent_pointV_ = SpointV_cov();\n\tdiff_pointV_ = SpointV_cov();\n\tphi_pose2dest_.clear();\n\tphi_prob_.clear();\n\tforce_to_goal_ = Sforce() ;\n\tforce_int_person_ = Sforce() ;\n\tforce_obstacle_ = Sforce() ;\n\tforce_int_robot_ = Sforce() ;\n}\n\n\nvoid Cperson_bhmip::rotate_and_translate_trajectory(double R, double thetaZ, double linear_vx, double linear_vy, double v_rot_x, double v_rot_y, std::vector<double> vect_odom_eigen_tf, bool debug_odometry){\n\t// Function for local tracking. This function change the frame of the Current_pose and the window of poses for the person,\n\t// tacking into account the actual position of the robot.\n\t// Also compensate the rotational velocities applied to the person when the robot turns.\n\t\t// R -> Robot Translation ; thetaZ -> Robot rotation\n\n\n\tif(debug_odometry){\n\tstd::cout << \"!!!!!!!!!!!!!!!!!! (people prediction) rotate_and_translate_trajectory !!!!!!!!!!!!!\" << std::endl;\n\t}\n\thom2_ant.clear();\n\n\tEigen::MatrixXd homT1; // homogeneous transfor para pasar los tracks al nuevo frame de la odometria.\n\tEigen::MatrixXd homT1vis;\n\tEigen::MatrixXd homT2;\n\tEigen::MatrixXd J; // necesaria para introducir el aumento de la covarianza por culpa del error en R=traslacion y en thetaZ=rotaci\u00f3n.\n\tEigen::MatrixXd H_cov;\n\tEigen::MatrixXd P;\n\thomT1.resize(3, 3);\n\thomT1vis.resize(3, 3);\n\thomT2.resize(3, 3);\n\tJ.resize(4, 2);\n\tH_cov.resize(4, 4);\n\tP.resize(2, 2);\n\n\t/*homT1.row(0) << cos(thetaZ), -sin(thetaZ), R * cos(thetaZ/2);\n\thomT1.row(1) << sin(thetaZ), cos(thetaZ), R * sin(thetaZ/2);\n\thomT1.row(2) << 0, 0, 1;*/\n\t\n\tif(debug_odometry){\n\tstd::cout << \"(people prediction) homT1 tf=\" << std::endl;\n\tstd::cout << \"[\"<<vect_odom_eigen_tf[0]<<\",\"<<vect_odom_eigen_tf[1]<<\",\"<< vect_odom_eigen_tf[2]<<\"]\" << std::endl;\n\tstd::cout << \"[\"<<vect_odom_eigen_tf[3]<<\",\"<<vect_odom_eigen_tf[4]<<\",\"<< vect_odom_eigen_tf[5]<<\"]\" << std::endl;\n\tstd::cout << \"[\"<<vect_odom_eigen_tf[6]<<\",\"<<vect_odom_eigen_tf[7]<<\",\"<< vect_odom_eigen_tf[8]<<\"]\"  << std::endl;\n\t}\n\t\n\thomT1.row(0) << vect_odom_eigen_tf[0], vect_odom_eigen_tf[1], vect_odom_eigen_tf[2];\n\thomT1.row(1) << vect_odom_eigen_tf[3], vect_odom_eigen_tf[4], vect_odom_eigen_tf[5];\n\thomT1.row(2) << vect_odom_eigen_tf[6], vect_odom_eigen_tf[7], vect_odom_eigen_tf[8];\n\n\tif(debug_odometry){\n\thomT1vis.row(0) << cos(thetaZ), -sin(thetaZ), R * cos(thetaZ/2);\n\thomT1vis.row(1) << sin(thetaZ), cos(thetaZ), R * sin(thetaZ/2);\n\thomT1vis.row(2) << 0, 0, 1;\n\t\tstd::cout << \"homT1vis _ prediction  = [ \" << homT1(0, 0) << \" , \" << homT1(0, 1)\n\t\t\t\t<< \" , \" << homT1(0, 2) << std::endl << \"               \"\n\t\t\t\t<< homT1(1, 0) << \" , \" << homT1(1, 1) << \" , \" << homT1(1, 2)\n\t\t\t\t<< std::endl << \"               \" << homT1(2, 0) << \" , \"\n\t\t\t\t<< homT1(2, 1) << \" , \" << homT1(2, 2) << std::endl;\n\t}\n\n\t//homT2 = homT1.inverse();\n\thomT2 = homT1;//.inverse();\n\n\tif(debug_odometry){\n\t\tstd::cout << \"homT2 _ prediction = [ \" << homT2(0, 0) << \" , \" << homT2(0, 1)\n\t\t\t\t<< \" , \" << homT2(0, 2) << std::endl << \"               \"\n\t\t\t\t<< homT2(1, 0) << \" , \" << homT2(1, 1) << \" , \" << homT2(1, 2)\n\t\t\t\t<< std::endl << \"               \" << homT2(2, 0) << \" , \"\n\t\t\t\t<< homT2(2, 1) << \" , \" << homT2(2, 2) << std::endl;\n\t}\n\t\t/*hom2_ant.push_back(homT2(0, 0));\n\t\thom2_ant.push_back(homT2(0, 1));\n\t\thom2_ant.push_back(homT2(0, 2));\n\t\thom2_ant.push_back(homT2(1, 0));\n\t\thom2_ant.push_back(homT2(1, 1));\n\t\thom2_ant.push_back(homT2(1, 2));\n\t\thom2_ant.push_back(homT2(2, 0));\n\t\thom2_ant.push_back(homT2(2, 1));\n\t\thom2_ant.push_back(homT2(2, 2));\n\t\thom2_tf.push_front(hom2_ant);*/\n\n\tH_cov.row(0) << cos(thetaZ), sin(thetaZ), 0, 0;\n\tH_cov.row(1) << -sin(thetaZ), cos(thetaZ), 0, 0;\n\tH_cov.row(2) << 0, 0, cos(thetaZ), sin(thetaZ);\n\tH_cov.row(3) << 0, 0, -sin(thetaZ), cos(thetaZ);\n\n\tP.row(0) << 10 * R / 100, 0; //[G_R^2       0    ]\n\tP.row(1) << 0, 10 * thetaZ / 100; //[  0    G_thetaZ^2]\n\n\t// Robot local velocity\n\ttrajectory_local_velocity_x_.push_back(linear_vx);\n\ttrajectory_local_velocity_y_.push_back(linear_vy);\n\n\n\t// Change tracks trajectories to the actual robot frame.\n\n\tfor(unsigned int i=0; i<trajectory_.size(); i++){\n\n\t\t/*Eigen::MatrixXd homT2_act;\n\t\tfor(unsigned int j=0;j=<i;j++){\n\t\t\thomT2_act=homT2_act*hom2_tf\n\t\t}*/\n\n\t\tSpointV_cov track_ant=trajectory_[i];\n\t\tif(debug_odometry){\n\t\t\tstd::cout << \" Before (people prediction) trajectory_(\"<<i<<\")\"<< std::endl;\n\t\t\t\ttrajectory_[i].print();\n\t\t}\n\t\tSpointV_cov track_act; //trajectory point transformed.\n\n\t\tEigen::MatrixXd pos_ant(3,1);\n\t\tEigen::MatrixXd pos_act(3,1);\n\t\tEigen::MatrixXd vel_ant(3,1);\n\t\tEigen::MatrixXd vel_act(3,1);\n\t\tEigen::MatrixXd cov_ant(4,4);\n\t\tEigen::MatrixXd cov_act(4,4);\n\t\tEigen::MatrixXd robot_linear_vel(3,1);\n\n\t\trobot_linear_vel(0, 0) = linear_vx;\n\t\trobot_linear_vel(1, 0) = linear_vy;\n\t\trobot_linear_vel(2, 0) = 0;\n\n\t\tpos_ant(0, 0) = track_ant.x;\n\t\tpos_ant(1, 0) = track_ant.y;\n\t\tpos_ant(2, 0) = 1;\n\n\t\tpos_act = homT2 * pos_ant;\n\n\t\tvel_ant.row(0) << track_ant.vx;\n\t\tvel_ant.row(1) << track_ant.vy;\n\t\tvel_ant.row(2) << 0;\n\n\t\tvel_act = homT2 * vel_ant;\n\n\t\t//vel_act=vel_act-robot_linear_vel- w_robot x pos_act;\n\n\t\tJ.row(0) << -cos(thetaZ), -sin(thetaZ) * track_ant.x\n\t\t\t\t\t\t+ cos(thetaZ) * track_ant.y + R * sin(thetaZ );\n\t\tJ.row(1) << sin(thetaZ), -cos(thetaZ) * track_ant.x\n\t\t\t\t\t\t- sin(thetaZ) * track_ant.y + R * cos(thetaZ );\n\t\tJ.row(2) << 0, -sin(thetaZ) * track_ant.vx + cos(thetaZ) * track_ant.vy;\n\t\tJ.row(3) << 0, -cos(thetaZ) * track_ant.vx - sin(thetaZ) * track_ant.vy;\n\n\t\tcov_ant.row(0) << track_ant.cov[0], track_ant.cov[1], track_ant.cov[2], track_ant.cov[3];\n\t\tcov_ant.row(1) << track_ant.cov[4], track_ant.cov[5], track_ant.cov[6], track_ant.cov[7];\n\t\tcov_ant.row(2) << track_ant.cov[8], track_ant.cov[9], track_ant.cov[10], track_ant.cov[11];\n\t\tcov_ant.row(3) << track_ant.cov[12], track_ant.cov[13], track_ant.cov[14], track_ant.cov[15];\n\n\t\t//cov_act = H_cov * cov_ant * H_cov.transpose() + J * P * J.transpose();\n\t\tcov_act = H_cov * cov_ant * H_cov.transpose();\n\n\t\tstd::vector<double> vect_cov_act;\n\t\tvect_cov_act.reserve(16);\n\t\tvect_cov_act.resize(16, 0.0);\n\t\tvect_cov_act[0] = (double) cov_act(0, 0); // cov_xx\n\t\tvect_cov_act[1] = (double) cov_act(0, 1); //cov_xy\n\t\tvect_cov_act[2] = (double) cov_act(0, 2); // cov_xvx\n\t\tvect_cov_act[3] = (double) cov_act(0, 3); //cov_xvy\n\t\tvect_cov_act[4] = (double) cov_act(1, 0); //cov_yx\n\t\tvect_cov_act[5] = (double) cov_act(1, 1); //cov_yy\n\t\tvect_cov_act[6] = (double) cov_act(1, 2); //cov_yvx\n\t\tvect_cov_act[7] = (double) cov_act(1, 3); //cov_yvy\n\t\tvect_cov_act[8] = (double) cov_act(2, 0); // cov_vxvx\n\t\tvect_cov_act[9] = (double) cov_act(2, 1); //cov_vxvy\n\t\tvect_cov_act[10] = (double) cov_act(2, 2); // cov_vxx\n\t\tvect_cov_act[11] = (double) cov_act(2, 3); //cov_vxy\n\t\tvect_cov_act[12] = (double) cov_act(3, 0); //cov_vyvx\n\t\tvect_cov_act[13] = (double) cov_act(3, 1); //cov_vyvy\n\t\tvect_cov_act[14] = (double) cov_act(3, 2); //cov_vyx\n\t\tvect_cov_act[15] = (double) cov_act(3, 3); //cov_vyy\n\n\t\ttrack_act = SpointV_cov(pos_act(0, 0), pos_act(1, 0),track_ant.time_stamp, vel_act(0, 0), vel_act(1, 0),vect_cov_act);\n\n\t\ttrajectory_[i]=track_act;\n\n\t\tif(debug_odometry){\n\t\tstd::cout << \"(people prediction) track_ant(\"<<i<<\")\" << std::endl;\n\t\ttrack_ant.print();\n\t\tstd::cout << \" (people prediction) track_act(\"<<i<<\")\"<< std::endl;\n\t\ttrack_act.print();\n\t\tstd::cout << \" After (people prediction) trajectory_(\"<<i<<\")\"<< std::endl;\n\t\ttrajectory_[i].print();\n\t\t}\n\t}\n\n\t// change current_pointV_ with odometry\n\tSpointV_cov ant_current_pointV=current_pointV_;\n\tif(debug_odometry){\n\tstd::cout << \" ANT current_pointV_=\"<< std::endl;\n\tcurrent_pointV_.print();\n\t}\n\t//SpointV_cov act_current_pointV;\n\tEigen::MatrixXd pos_ant_current_pointV(3,1);\n\tEigen::MatrixXd pos_act_current_pointV(3,1);\n\tEigen::MatrixXd vel_ant_current_pointV(3,1);\n\tEigen::MatrixXd vel_act_current_pointV(3,1);\n\tEigen::MatrixXd cov_ant_current_pointV(4,4);\n\tEigen::MatrixXd cov_act_current_pointV(4,4);\n\n\tpos_ant_current_pointV(0, 0) = ant_current_pointV.x;\n\tpos_ant_current_pointV(1, 0) = ant_current_pointV.y;\n\tpos_ant_current_pointV(2, 0) = 1;\n\n\tpos_act_current_pointV = homT2 * pos_ant_current_pointV;\n\n\tvel_ant_current_pointV.row(0) << ant_current_pointV.vx;\n\tvel_ant_current_pointV.row(1) << ant_current_pointV.vy;\n\tvel_ant_current_pointV.row(2) << 0;\n\n\tvel_act_current_pointV = homT2 * vel_ant_current_pointV;\n\n\tJ.row(0) << -cos(thetaZ), -sin(thetaZ) * ant_current_pointV.x + cos(thetaZ) * ant_current_pointV.y + R * sin(thetaZ / 2);\n\tJ.row(1) << sin(thetaZ), -cos(thetaZ) * ant_current_pointV.x - sin(thetaZ) * ant_current_pointV.y + R * cos(thetaZ / 2);\n\tJ.row(2) << 0, -sin(thetaZ) * ant_current_pointV.vx + cos(thetaZ) * ant_current_pointV.vy;\n\tJ.row(3) << 0, -cos(thetaZ) * ant_current_pointV.vx - sin(thetaZ) * ant_current_pointV.vy;\n\n\tcov_ant_current_pointV.row(0) << ant_current_pointV.cov[0], ant_current_pointV.cov[1], ant_current_pointV.cov[2], ant_current_pointV.cov[3];\n\tcov_ant_current_pointV.row(1) << ant_current_pointV.cov[4], ant_current_pointV.cov[5], ant_current_pointV.cov[6], ant_current_pointV.cov[7];\n\tcov_ant_current_pointV.row(2) << ant_current_pointV.cov[8], ant_current_pointV.cov[9], ant_current_pointV.cov[10], ant_current_pointV.cov[11];\n\tcov_ant_current_pointV.row(3) << ant_current_pointV.cov[12], ant_current_pointV.cov[13], ant_current_pointV.cov[14], ant_current_pointV.cov[15];\n\n\tcov_act_current_pointV = H_cov * cov_ant_current_pointV * H_cov.transpose() + J * P * J.transpose();\n\n\tstd::vector<double> vect_cov_act_current_pointV;\n\tvect_cov_act_current_pointV.reserve(16);\n\tvect_cov_act_current_pointV.resize(16, 0.0);\n\tvect_cov_act_current_pointV[0] = (double) cov_act_current_pointV(0, 0); // cov_xx\n\tvect_cov_act_current_pointV[1] = (double) cov_act_current_pointV(0, 1); //cov_xy\n\tvect_cov_act_current_pointV[2] = (double) cov_act_current_pointV(0, 2); // cov_xvx\n\tvect_cov_act_current_pointV[3] = (double) cov_act_current_pointV(0, 3); //cov_xvy\n\tvect_cov_act_current_pointV[4] = (double) cov_act_current_pointV(1, 0); //cov_yx\n\tvect_cov_act_current_pointV[5] = (double) cov_act_current_pointV(1, 1); //cov_yy\n\tvect_cov_act_current_pointV[6] = (double) cov_act_current_pointV(1, 2); //cov_yvx\n\tvect_cov_act_current_pointV[7] = (double) cov_act_current_pointV(1, 3); //cov_yvy\n\tvect_cov_act_current_pointV[8] = (double) cov_act_current_pointV(2, 0); // cov_vxvx\n\tvect_cov_act_current_pointV[9] = (double) cov_act_current_pointV(2, 1); //cov_vxvy\n\tvect_cov_act_current_pointV[10] = (double) cov_act_current_pointV(2, 2); // cov_vxx\n\tvect_cov_act_current_pointV[11] = (double) cov_act_current_pointV(2, 3); //cov_vxy\n\tvect_cov_act_current_pointV[12] = (double) cov_act_current_pointV(3, 0); //cov_vyvx\n\tvect_cov_act_current_pointV[13] = (double) cov_act_current_pointV(3, 1); //cov_vyvy\n\tvect_cov_act_current_pointV[14] = (double) cov_act_current_pointV(3, 2); //cov_vyx\n\tvect_cov_act_current_pointV[15] = (double) cov_act_current_pointV(3, 3); //cov_vyy\n\n\t//double track_vx=vel_act_current_pointV(0,0) - v_rot_x;\n\t//double track_vy=vel_act_current_pointV(1,0) - v_rot_y;\n\n\t//vel_act_current_pointV(0,0)=track_vx;\n\t//vel_act_current_pointV(1,0)=track_vy;\n\n\n\n\tcurrent_pointV_ = SpointV_cov(pos_act_current_pointV(0, 0), pos_act_current_pointV(1, 0), ant_current_pointV.time_stamp, vel_act_current_pointV(0,0), vel_act_current_pointV(1,0),vect_cov_act_current_pointV);\n\tif(debug_odometry){\n\tstd::cout << \" AcT current_pointV_=\"<< std::endl;\n\tcurrent_pointV_.print();\n\t}\n}\n", "meta": {"hexsha": "eb2b00d201cf31666cc22cfab917d6fc16426e4b", "size": 24114, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "iri_navigation/iri_simulated_person_companion_akp_local_planner/local_lib/src/scene_elements/person_bhmip.cpp", "max_stars_repo_name": "yinzixuan126/modified_dwa", "max_stars_repo_head_hexsha": "b379c01e37adc1f6414005750633b05e1a024ae5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-12-30T04:00:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-10T23:59:30.000Z", "max_issues_repo_path": "iri_navigation/iri_simulated_person_companion_akp_local_planner/local_lib/src/scene_elements/person_bhmip.cpp", "max_issues_repo_name": "yinzixuan126/modified_dwa", "max_issues_repo_head_hexsha": "b379c01e37adc1f6414005750633b05e1a024ae5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "iri_navigation/iri_simulated_person_companion_akp_local_planner/local_lib/src/scene_elements/person_bhmip.cpp", "max_forks_repo_name": "yinzixuan126/modified_dwa", "max_forks_repo_head_hexsha": "b379c01e37adc1f6414005750633b05e1a024ae5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-05-17T02:35:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-17T00:34:53.000Z", "avg_line_length": 37.212962963, "max_line_length": 208, "alphanum_fraction": 0.6766608609, "num_tokens": 7663, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4683840676874936}}
{"text": "#include <kv/Heine.hpp>\n#include <kv/qAiry.hpp>\n#include <iostream>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <cmath>\ntypedef kv::interval<double> itv;\ntypedef kv::complex< kv::interval<double> > cp;\nusing namespace std;\nnamespace ub = boost::numeric::ublas;\nint main()\n{\n  cout.precision(17);\n  ub::vector< itv > x(100);\n  int n=40;\n  itv q,xx,xy,omega;\n  q=\"0.9\";\n  omega=\"0.3\";\n  x(0)=1.55;\n  xy=mid(x(0));\n  for(int i=0;i<=n;i++){\n    xx=mid(x(i));\n    x(i+1)=xx-kv::Ramanujan_qAiry(itv(q),itv(xx))*(xy-q*xy-omega)\n      /(kv::Ramanujan_qAiry(itv(q),itv(xy))-kv::Ramanujan_qAiry(itv(q),itv(q*xy+omega)))\n      +(1-(xy-q*xy-omega)*(kv::Ramanujan_qAiry(itv(q),itv(x(i)))-kv::Ramanujan_qAiry(itv(q),itv(q*x(i)+omega))) \n\t/(x(i)-q*x(i)-omega)/(kv::Ramanujan_qAiry(itv(q),itv(xy))-kv::Ramanujan_qAiry(itv(q),itv(q*xy+omega))))*(x(i)-xx);\n    cout<<x(i+1)<<endl;\n    cout<<\"value of RqA inf\"<<kv::Ramanujan_qAiry(itv(q),itv(x(i+1).lower()))<<endl;\n    cout<<\"value of RqA sup\"<<kv::Ramanujan_qAiry(itv(q),itv(x(i+1).upper()))<<endl;\n    cout<<\"value of RqA mid\"<<kv::Ramanujan_qAiry(itv(q),itv(mid(x(i+1))))<<endl;\n    cout<<\"value of contraction const:\"<<abs(1-(xy-q*xy-omega)*(kv::Ramanujan_qAiry(itv(q),itv(x(i)))-kv::Ramanujan_qAiry(itv(q),itv(q*x(i)+omega))) \n\t\t\t\t\t     /(x(i)-q*x(i)-omega)/(kv::Ramanujan_qAiry(itv(q),itv(xy))-kv::Ramanujan_qAiry(itv(q),itv(q*xy+omega)))).upper()<<endl;\n  }\n}\n", "meta": {"hexsha": "86529545107ce6e8461a4700a122b5a135ede5e4", "size": 1445, "ext": "cc", "lang": "C++", "max_stars_repo_path": "qNewton/Hahn-difference/RqAqHK.cc", "max_stars_repo_name": "Daisuke-Kanaizumi/q-special-functions", "max_stars_repo_head_hexsha": "91aafafe125d864931e640cbe6993d9d61a32126", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2017-02-03T20:55:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-23T12:26:00.000Z", "max_issues_repo_path": "qNewton/Hahn-difference/RqAqHK.cc", "max_issues_repo_name": "Daisuke-Kanaizumi/q-special-functions", "max_issues_repo_head_hexsha": "91aafafe125d864931e640cbe6993d9d61a32126", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-03-07T04:32:20.000Z", "max_issues_repo_issues_event_max_datetime": "2017-09-05T01:48:57.000Z", "max_forks_repo_path": "qNewton/Hahn-difference/RqAqHK.cc", "max_forks_repo_name": "Daisuke-Kanaizumi/q-special-functions", "max_forks_repo_head_hexsha": "91aafafe125d864931e640cbe6993d9d61a32126", "max_forks_repo_licenses": ["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.2857142857, "max_line_length": 149, "alphanum_fraction": 0.6283737024, "num_tokens": 580, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894520743981, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.46835100722932366}}
{"text": "#ifndef POINT_HPP_\n#define POINT_HPP_\n\n\n#include <boost/operators.hpp>\n#include <ostream>\n\nnamespace gnssro\n{\n  template< class T , size_t Dim >\n  class Point :\n    boost::additive1< Point< T , Dim > ,\n    boost::additive2< Point< T , Dim  > , T ,\n    boost::multiplicative2< Point< T , Dim > , T> > >\n    {\n    public:\n\n        const static size_t dim = Dim;\n\n        // \n        // Constructors\n        //\n        Point( void )\n        {\n            for( size_t i=0 ; i<dim ; ++i ) m_val[i] = 0.0;\n        }\n\n        Point( T val )\n        {\n            for( size_t i=0 ; i<dim ; ++i ) m_val[i] = val;\n        }\n\n        Point( T x , T y , T z = 0.0 )\n        {\n            if( dim > 0 ) m_val[0] = x;\n            if( dim > 1 ) m_val[1] = y;\n            if( dim > 2 ) m_val[2] = z;\n        }\n\n        Point( Point< T , Dim >& p )\n        {\n            for( size_t ii=0; ii<dim; ++ii )\n                m_val[ii] = p[ii];\n        }\n\n        //  End Constructors\n\n        //  Destructor\n        ~Point(){};\n        //  End Destructor\n\n        // \n        //  Operators\n        //\n        T operator[]( size_t i ) const { return m_val[i]; }\n        T& operator[]( size_t i ) { return m_val[i]; }\n\n        Point<T,dim>& operator= ( const Point<T,dim>& p )\n        {\n            for( size_t ii=0; ii<dim; ++ii )\n                m_val[ii] = p[ii];\n            return *this;\n        }\n\n        Point<T,dim>& operator+=( const Point<T,dim>& p )\n        {\n            for( size_t ii=0 ; ii<dim ; ++ii )\n                m_val[ii] += p[ii];\n            return *this;\n        }\n\n        Point<T,dim>& operator-=( const Point<T,dim>& p )\n        {\n            for( size_t ii=0; ii<dim; ++ii )\n                m_val[ii] -= p[ii];\n            return *this;\n        }\n\n        Point<T,dim>& operator+=( const T& val )\n        {\n            for( size_t ii=0; ii<dim; ++ii )\n                m_val[ii] += val;\n            return *this;\n        }\n\n        Point<T,dim>& operator-=( const T& val )\n        {\n            for( size_t ii=0; ii<dim; ++ii )\n                m_val[ii] -= val;\n            return *this;\n        }\n\n        Point<T,dim>& operator*=( const T &val )\n        {\n            for( size_t ii=0; ii<dim; ++ii )\n                m_val[ii] *= val;\n            return *this;\n        }\n\n        Point<T,dim>& operator/=( const T &val )\n        {\n            for( size_t i=0 ; i<dim ; ++i )\n                m_val[i] /= val;\n            return *this;\n        }\n\n        //  End Operators\n\n    private:\n\n        // Actual Point coordinates are private (access via [] operator):\n        T m_val[dim];\n\n    };\n\n    //\n    //  Additional vector operators\n    //\n\n    //\n    //  the - operator\n    //\n    template< class T , size_t Dim >\n    Point< T , Dim > operator-( const Point< T , Dim > &p )\n    {\n        Point< T , Dim > tmp;\n        for( size_t i=0 ; i<Dim ; ++i ) tmp[i] = -p[i];\n        return tmp;\n    }\n\n    //\n    //  Inner product\n    //\n    template< class T , size_t Dim >\n    T scalar_prod( const Point< T , Dim > &p1 , const Point< T , Dim > &p2 )\n    {\n        T tmp = 0.0;\n        for( size_t i=0 ; i<Dim ; ++i ) tmp += p1[i] * p2[i];\n        return tmp;\n    }\n\n\n\n    //\n    //  L^1 norm\n    //\n    template< class T , size_t Dim >\n    T norm( const Point< T , Dim > &p1 )\n    {\n        return scalar_prod( p1 , p1 );\n    }\n\n\n\n\n    //\n    //  L^2 norm\n    //\n    template< class T , size_t Dim >\n    T abs( const Point< T , Dim > &p1 )\n    {\n        return sqrt( norm( p1 ) );\n    }\n\n\n\n\n    //\n    //  output stream operator\n    //\n    template< class T , size_t Dim >\n    std::ostream& operator<<( std::ostream &out , const Point< T , Dim > &p )\n    {\n        if( Dim > 0 ) out << p[0];\n        for( size_t i=1 ; i<Dim ; ++i ) out << \" \" << p[i];\n        return out;\n    }\n\n}  //  end of namespace gnssro\n\n#endif  //  POINT_HPP_\n", "meta": {"hexsha": "f214f3c4a245b6a7e22bb1b0d4d39f1446731d49", "size": 3836, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Point.hpp", "max_stars_repo_name": "mfkiwl/gnssrolib", "max_stars_repo_head_hexsha": "3590f0bbade4f09695b71496525bfbdb0daa2d14", "max_stars_repo_licenses": ["Apache-2.0"], "max_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.hpp", "max_issues_repo_name": "mfkiwl/gnssrolib", "max_issues_repo_head_hexsha": "3590f0bbade4f09695b71496525bfbdb0daa2d14", "max_issues_repo_licenses": ["Apache-2.0"], "max_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.hpp", "max_forks_repo_name": "mfkiwl/gnssrolib", "max_forks_repo_head_hexsha": "3590f0bbade4f09695b71496525bfbdb0daa2d14", "max_forks_repo_licenses": ["Apache-2.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.0769230769, "max_line_length": 77, "alphanum_fraction": 0.4202294056, "num_tokens": 1095, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585903489891, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.46834235499806176}}
{"text": "#include \"fft.hpp\"\n\n#include \"dynamic_grid.hpp\"\n#include \"global.hpp\"\n#include \"test_helpers.hpp\"\n\n#include <fftw3.h>\n#include <vector>\n#include <complex>\n#include <cstdlib>\n\n#include <boost/test/unit_test.hpp>\n\nBOOST_AUTO_TEST_SUITE(fft_tests)\n\nBOOST_AUTO_TEST_CASE(check_roundtrip)\n{\n\n\tstd::vector<complex_t> data(64);\n\tfor(int i=0; i < 64; ++i)\n\t{\n\t\tdata[i] = rand_value();\n\t}\n\n\tBOOST_TEST_CHECKPOINT(\"checking 1d fft\");\n\n\tauto copy = data;\n\n\tfft(copy, std::vector<int>({64}));\n\tifft(copy, std::vector<int>({64}));\n\n\tfor(int i=0; i < 64; ++i)\n\t{\n\t\tBOOST_CHECK_SMALL( std::abs(copy[i] - data[i]), 1e3*std::numeric_limits<double>::epsilon() );\n\t}\n\n\tBOOST_TEST_CHECKPOINT(\"checking 2d fft\");\n\n\tcopy = data;\n\n\tfft(copy, std::vector<int>({8,8}));\n\tifft(copy, std::vector<int>({8,8}));\n\tfor(int i=0; i < 64; ++i)\n\t{\n\t\tBOOST_CHECK_SMALL( std::abs(copy[i] - data[i]), 1e3*std::numeric_limits<double>::epsilon() );\n\t}\n\n\n\tBOOST_TEST_CHECKPOINT(\"checking 3d fft\");\n\n\tcopy = data;\n\n\tfft(copy, std::vector<int>({4, 4, 4}));\n\tifft(copy, std::vector<int>({4, 4, 4}));\n\tfor(int i=0; i < 64; ++i)\n\t{\n\t\tBOOST_CHECK_SMALL( std::abs(copy[i] - data[i]), 1e3*std::numeric_limits<double>::epsilon() );\n\t}\n}\n\nBOOST_AUTO_TEST_CASE(check_error_handling)\n{\n\n    std::vector<complex_t> data(35);\n    for(int i=0; i < 35; ++i)\n\t{\n\t\tdata[i] = rand_value();\n\t}\n\n\tauto copy = data;\n\n\t// throw because copy.size does not match expected size\n\tBOOST_CHECK_THROW(fft(copy, std::vector<int>({64})), std::invalid_argument);\n\tBOOST_CHECK_THROW(fft(copy, std::vector<int>({5,5})), std::invalid_argument);\n\tBOOST_CHECK_THROW(fft(copy, std::vector<int>({5,5,5})), std::invalid_argument);\n\n\t// check that copy is left unchanged by the preceding calls\n\tfor(unsigned int i=0; i < data.size(); ++i)\n\t{\n\t\tBOOST_CHECK_EQUAL( copy[i], data[i] );\n\t}\n\n\t// same thing for ifft\n\tBOOST_CHECK_THROW(ifft(copy, std::vector<int>({64})), std::invalid_argument);\n\tBOOST_CHECK_THROW(ifft(copy, std::vector<int>({5,5})), std::invalid_argument);\n\tBOOST_CHECK_THROW(ifft(copy, std::vector<int>({5,5,5})), std::invalid_argument);\n\t// check that copy is left unchanged\n\tfor(unsigned int i=0; i < data.size(); ++i)\n\t{\n\t\tBOOST_CHECK_EQUAL( copy[i], data[i] );\n\t}\n\n\n\t// check size argument fitting into int\n\tBOOST_CHECK_THROW( fft(copy, std::vector<int>({-1})), std::overflow_error );\n\tBOOST_CHECK_THROW( ifft(copy, std::vector<int>({-1})), std::overflow_error );\n}\n\n/// \\todo grid_interface_test is obsolete\n/// \\todo iterator interface and DynamicGrid interface tests missing.\n/*\nBOOST_AUTO_TEST_CASE(grid_interface_test)\n{\n\n    std::vector<std::complex<double>> data(64);\n    for(int i=0; i < 64; ++i)\n\t{\n\t\tdata[i] = rand_value();\n\t}\n\n\t// 1d\n\n\tauto grid_dat = data;\n    grid<decltype(data), 1> grid1d(64, grid_dat );\n\n\tauto copy = data;\n\n\tfft(grid1d);\n\tfft(1, copy, 64);\n\tfor(int i=0; i < 64; ++i)\n\t{\n\t\tBOOST_CHECK_EQUAL( copy[i], grid_dat[i] );\n\t}\n\n\tifft(grid1d);\n\tifft(1, copy, 64);\n\tfor(int i=0; i < 64; ++i)\n\t{\n\t\tBOOST_CHECK_EQUAL( copy[i], grid_dat[i] );\n\t}\n\n\t// 3d\n    grid<decltype(data), 3> grid3d(4, grid_dat );\n\n\tfft(grid3d);\n\tfft(3, copy, 4);\n\tfor(int i=0; i < 64; ++i)\n\t{\n\t\tBOOST_CHECK_EQUAL( copy[i], grid_dat[i] );\n\t}\n\n\tifft(grid3d);\n\tifft(3, copy, 4);\n\tfor(int i=0; i < 64; ++i)\n\t{\n\t\tBOOST_CHECK_EQUAL( copy[i], grid_dat[i] );\n\t}\n}*/\n\nBOOST_AUTO_TEST_CASE( fftw_wisdom_check )\n{\n\t// try fft without wisdom\n\tfftw_forget_wisdom();\n\tfftw_cleanup();\n\n\tstd::vector<std::complex<double>> data(64);\n\tfor( auto& d : data )\n\t\td = rand_value();\n\n\tauto copy = data;\n\n\t// fft without wisdom\n\tfft( data, std::vector<int>({64}) );\n\t// fft with wisdom\n\tfft( copy, std::vector<int>({64}) );\n\n\tfor(unsigned i = 0; i < data.size(); ++i)\n\t{\n\t\tBOOST_CHECK_SMALL( std::abs(data[i] - copy[i]), 1e-10 );\n\t}\n\n\t// check inverse\n\tfftw_cleanup();\n\tifft( data, std::vector<int>({64}) );\n\tifft( copy, std::vector<int>({64}) );\n\tfor(unsigned i = 0; i < data.size(); ++i)\n\t\tBOOST_CHECK_SMALL( std::abs(data[i] - copy[i]), 1e-10 );\n\n\n}\n\n/// \\todo maybe add another check that actually checks values for a know case.\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "caf75edc1080e87acc77c0b265f841f3509bf4b0", "size": 4066, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/potgen/test/fft_test.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/potgen/test/fft_test.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/potgen/test/fft_test.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": 21.9783783784, "max_line_length": 95, "alphanum_fraction": 0.6458435809, "num_tokens": 1267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300048, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.468342342474567}}
{"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 expressions.hpp\n * @brief\n * @author Piotr Godlewski\n * @version 1.0\n * @date 2014-04-02\n */\n\n#ifndef PAAL_EXPRESSIONS_HPP\n#define PAAL_EXPRESSIONS_HPP\n\n#include \"paal/lp/ids.hpp\"\n#include \"paal/utils/floating.hpp\"\n#include \"paal/utils/functors.hpp\"\n#include \"paal/utils/print_collection.hpp\"\n#include \"paal/utils/pretty_stream.hpp\"\n\n#include <boost/range/adaptor/transformed.hpp>\n#include <boost/range/algorithm/count_if.hpp>\n\n#include <functional>\n#include <unordered_map>\n\nnamespace paal {\nnamespace lp {\n\nnamespace {\nstruct linear_expression_traits {\n    static const utils::compare<double> CMP;\n};\n\nconst utils::compare<double> linear_expression_traits::CMP = utils::compare<double>();\n}\n\n/**\n * Expression class.\n */\nclass linear_expression {\n    typedef std::unordered_map<col_id, double> Elements;\n    typedef Elements::const_iterator ExprIter;\n\n  public:\n    /// Constructor.\n    linear_expression() {}\n\n    /// Constructor.\n    linear_expression(col_id col, double coef = 1.) {\n        m_coefs.emplace(col, coef);\n    }\n\n    /// Addition operator.\n    linear_expression &operator+=(const linear_expression &expr) {\n        join_expression(expr, utils::plus{});\n        return *this;\n    }\n\n    /// Subtraction operator.\n    linear_expression &operator-=(const linear_expression &expr) {\n        join_expression(expr, utils::minus{});\n        return *this;\n    }\n\n    /// Multiplication by a constant operator.\n    linear_expression &operator*=(double val) {\n        for (auto &elem : m_coefs) {\n            elem.second *= val;\n        }\n        return *this;\n    }\n\n    /// Division by a constant operator.\n    linear_expression &operator/=(double val) { return operator*=(1. / val); }\n\n    /// Returns the coefficient for a given column.\n    double get_coefficient(col_id col) const {\n        auto elem = m_coefs.find(col);\n        if (elem != m_coefs.end()) {\n            return elem->second;\n        } else {\n            return 0.;\n        }\n    }\n\n    /// Returns the iterator range of the elements in the expression.\n    const Elements &get_elements() const { return m_coefs; }\n\n    /// Returns the size (number of nonzero coefficients) of the expression.\n    int non_zeros() const {\n        return boost::count_if(m_coefs, [](std::pair<col_id, double> x) {\n            return !linear_expression_traits::CMP.e(x.second, 0);\n        });\n    }\n\n  private:\n    template <typename Operation>\n    void join_expression(const linear_expression &expr, Operation op) {\n        for (auto new_elem : expr.m_coefs) {\n            auto elem = m_coefs.find(new_elem.first);\n            if (elem == m_coefs.end()) {\n                new_elem.second = op(0., new_elem.second);\n                m_coefs.insert(new_elem);\n            } else {\n                elem->second = op(elem->second, new_elem.second);\n            }\n        }\n    }\n\n    Elements m_coefs;\n};\n\nnamespace detail {\ninline std::string col_id_to_string(col_id col) {\n    return \" x_\" + std::to_string(col.get());\n}\n\ntemplate <typename Stream, typename PrintCol>\nvoid print_expression(Stream &o, const linear_expression &expr,\n                      PrintCol print_col) {\n    print_collection(o, expr.get_elements() |\n                            boost::adaptors::transformed(\n                                [&](std::pair<col_id, double> col_and_val) {\n        return pretty_to_string(col_and_val.second) +\n               print_col(col_and_val.first);\n    }),\n                     \" + \");\n}\n};\n\n/// operator<< : printing expression\ntemplate <typename Stream>\nStream &operator<<(Stream &o, const linear_expression &expr) {\n    detail::print_expression(o, expr, detail::col_id_to_string);\n    return o;\n}\n\n/// linear_expression + linear_expression operator.\ninline linear_expression operator+(linear_expression expr_left,\n                                   const linear_expression &expr_right) {\n    expr_left += expr_right;\n    return expr_left;\n}\n\n/// linear_expression - linear_expression operator.\ninline linear_expression operator-(linear_expression expr_left,\n                                   const linear_expression &expr_right) {\n    expr_left -= expr_right;\n    return expr_left;\n}\n\n/// linear_expression * double operator.\ninline linear_expression operator*(linear_expression expr, double val) {\n    expr *= val;\n    return expr;\n}\n\n/// double * linear_expression operator.\ninline linear_expression operator*(double val, const linear_expression &expr) {\n    return expr * val;\n}\n\n/// linear_expression / double operator.\ninline linear_expression operator/(linear_expression expr, double val) {\n    expr /= val;\n    return expr;\n}\n\n/// Unary - operator.\ninline linear_expression operator-(const linear_expression &expr) {\n    return expr * (-1.);\n}\n\n} // lp\n} // paal\n\n#endif // PAAL_EXPRESSIONS_HPP\n", "meta": {"hexsha": "a84346af8f5c2b63f9317ad889f862b844028d61", "size": 5106, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/paal/lp/expressions.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/lp/expressions.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/lp/expressions.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": 27.9016393443, "max_line_length": 86, "alphanum_fraction": 0.6269095182, "num_tokens": 1097, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585903489891, "lm_q2_score": 0.640635847978761, "lm_q1q2_score": 0.4683423399503823}}
{"text": "/*********************************************************************\n * Software License Agreement (BSD License)\n *\n *  Copyright (c) 2021,\n *  Max Planck Institute for Intelligent Systems (MPI-IS).\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 MPI-IS nor the names\n *     of its contributors may be used to endorse or promote products\n *     derived from this software without specific prior written\n *     permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n *  \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n *  POSSIBILITY OF SUCH DAMAGE.\n *********************************************************************/\n\n/* Author: Andreas Orthey */\n\n#include <ompl/base/spaces/SphereStateSpace.h>\n#include <ompl/tools/config/MagicConstants.h>\n#include <cstring>\n#include <boost/math/constants/constants.hpp>\n\nusing namespace boost::math::double_constants;  // pi\nusing namespace ompl::base;\n\nSphereStateSampler::SphereStateSampler(const StateSpace *space) : StateSampler(space)\n{\n}\n\nvoid SphereStateSampler::sampleUniform(State *state)\n{\n    // see for example http://corysimon.github.io/articles/uniformdistn-on-sphere/\n    double theta = 2.0 * pi * rng_.uniformReal(0, 1) - pi; //uniform in [-pi,+pi]\n    double phi = acos(1.0 - 2.0 * rng_.uniformReal(0, 1));//in [0,+pi]\n    SphereStateSpace::StateType *S = state->as<SphereStateSpace::StateType>();\n    S->setThetaPhi(theta, phi);\n}\n\nvoid SphereStateSampler::sampleUniformNear(State *state, const State *near, double distance)\n{\n    SphereStateSpace::StateType *S = state->as<SphereStateSpace::StateType>();\n    const SphereStateSpace::StateType *Snear = near->as<SphereStateSpace::StateType>();\n    S->setTheta(rng_.uniformReal(Snear->getTheta() - distance, Snear->getTheta() + distance));\n    S->setPhi(rng_.uniformReal(Snear->getPhi() - distance, Snear->getPhi() + distance));\n    space_->enforceBounds(state);\n}\n\nvoid SphereStateSampler::sampleGaussian(State *state, const State *mean, double stdDev)\n{\n    SphereStateSpace::StateType *S = state->as<SphereStateSpace::StateType>();\n    const SphereStateSpace::StateType *Smean = mean->as<SphereStateSpace::StateType>();\n    S->setTheta(rng_.gaussian(Smean->getTheta(), stdDev));\n    S->setPhi(rng_.gaussian(Smean->getPhi(), stdDev));\n    space_->enforceBounds(state);\n}\n\nStateSamplerPtr SphereStateSpace::allocDefaultStateSampler() const\n{\n    return std::make_shared<SphereStateSampler>(this);\n}\n\nSphereStateSpace::SphereStateSpace(double radius):\n  radius_(radius)\n{\n    setName(\"Sphere\" + getName());\n    type_ = STATE_SPACE_SPHERE;\n\n    StateSpacePtr SO2(std::make_shared<SO2StateSpace>());\n    StateSpacePtr R1(std::make_shared<RealVectorStateSpace>(1));\n    R1->as<RealVectorStateSpace>()->setBounds(0, pi);\n\n    addSubspace(SO2, 1.0);\n    addSubspace(R1, 1.0);\n    lock();\n}\n\ndouble SphereStateSpace::distance(const State *state1, const State *state2) const\n{\n    // https://en.wikipedia.org/wiki/Great-circle_distance#Formulae\n\n    const SphereStateSpace::StateType *S1 = state1->as<SphereStateSpace::StateType>();\n    const SphereStateSpace::StateType *S2 = state2->as<SphereStateSpace::StateType>();\n\n    // Note: Formula assumes phi in [-pi/2,+pi/2]\n    float t1 = S1->getTheta();\n    float phi1 = S1->getPhi() - pi/2.0;\n\n    float t2 = S2->getTheta();\n    float phi2 = S2->getPhi() - pi/2.0;\n\n    // This is the Vincenty formula, but it is less numerically stable\n    // double dt = t2 - t1;\n    // double d1 = powf(cos(phi2) * sin(dt), 2);\n    // double d2 = powf(cos(phi1) * sin(phi2) - sin(phi1) * cos(phi2) * cos(dt), 2);\n    // double numerator = sqrtf(d1 + d2);\n    // double denumerator = sin(phi1) * sin(phi2) + cos(phi1) * cos(phi2) * cos(dt);\n    // return radius_ * atan2(numerator, denumerator);\n\n    // Haversine formula\n    float s = 0.5*(phi1 - phi2);\n    float t = 0.5*(t1 - t2);\n    float d = sqrtf(sin(s)*sin(s) + cos(phi1)*cos(phi2)*sin(t)*sin(t));\n    return 2*radius_*asin(d);\n\n}\n\ndouble SphereStateSpace::getMeasure() const\n{\n    return 4 * pi * radius_ * radius_;\n}\n\nState *SphereStateSpace::allocState() const\n{\n    auto *state = new StateType();\n    allocStateComponents(state);\n    return state;\n}\n\nEigen::Vector3f SphereStateSpace::toVector(const State *state) const\n{\n    Eigen::Vector3f v;\n\n    const SphereStateSpace::StateType *S1 = state->as<SphereStateSpace::StateType>();\n    float theta = S1->getTheta();\n    float phi = S1->getPhi();\n\n    v[0] = radius_*sin(phi)*cos(theta);\n    v[1] = radius_*sin(phi)*sin(theta);\n    v[2] = radius_*cos(phi);\n\n    return v;\n}\n", "meta": {"hexsha": "e83332e81802586d597d681160ac9f6a9d039309", "size": 5739, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ompl/base/spaces/src/SphereStateSpace.cpp", "max_stars_repo_name": "Russ76/ompl", "max_stars_repo_head_hexsha": "687239a0a8b578e00a95cf80636e3278de56bc7c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-07T02:19:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-07T02:19:26.000Z", "max_issues_repo_path": "src/ompl/base/spaces/src/SphereStateSpace.cpp", "max_issues_repo_name": "Russ76/ompl", "max_issues_repo_head_hexsha": "687239a0a8b578e00a95cf80636e3278de56bc7c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ompl/base/spaces/src/SphereStateSpace.cpp", "max_forks_repo_name": "Russ76/ompl", "max_forks_repo_head_hexsha": "687239a0a8b578e00a95cf80636e3278de56bc7c", "max_forks_repo_licenses": ["BSD-3-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.2662337662, "max_line_length": 94, "alphanum_fraction": 0.6840913051, "num_tokens": 1498, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585669110203, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.46834232995107233}}
{"text": "#include <pcl_ros_wrapper/common/surface.hpp>\n#include <pcl/features/moment_of_inertia_estimation.h>\n#include <pcl/surface/convex_hull.h>\n#include <pcl/surface/concave_hull.h>\n#include <pcl/features/normal_3d.h>\n#include <pcl/visualization/pcl_visualizer.h>\n#include <boost/make_shared.hpp>\n\nfloat pcl_ros_wrapper::common::get_cloud_volume(const PointCloudT::Ptr& input)\n{\n  pcl::MomentOfInertiaEstimation<pcl::PointXYZ> feature_extractor;\n  feature_extractor.setInputCloud(input);\n  feature_extractor.compute();\n\n  pcl::PointXYZ   minPt;\n  pcl::PointXYZ   maxPt;\n  pcl::PointXYZ   position_OBB;\n  Eigen::Matrix3f rotational_matrix_OBB;\n  feature_extractor.getOBB(minPt, maxPt, position_OBB, rotational_matrix_OBB);\n\n  return abs(maxPt.z - minPt.z) * abs(maxPt.x - minPt.x) * abs(maxPt.y - minPt.y);\n}\n\npcl_ros_wrapper::PointCloudT::Ptr pcl_ros_wrapper::common::convex_hull(\n  const PointCloudT::Ptr& cloud)\n{\n  auto                           hull_points = boost::make_shared<PointCloudT>();\n  pcl::ConvexHull<pcl::PointXYZ> conv_hull;\n  conv_hull.setInputCloud(cloud);\n  conv_hull.reconstruct(*hull_points);\n  return hull_points;\n}\n\npcl_ros_wrapper::common::concave_hull_result pcl_ros_wrapper::common::concave_hull(\n  const PointCloudT::Ptr& cloud,\n  const float             alpha)\n{\n  auto                            hull_points  = boost::make_shared<PointCloudT>();\n  auto                            hull_indices = boost::make_shared<pcl::PointIndices>();\n  pcl::ConcaveHull<pcl::PointXYZ> conv_hull;\n  conv_hull.setInputCloud(cloud);\n  conv_hull.setAlpha(alpha);\n  conv_hull.setKeepInformation(true);\n  conv_hull.reconstruct(*hull_points);\n  conv_hull.getHullPointIndices(*hull_indices);\n  return concave_hull_result{ hull_points, hull_indices };\n}\n\npcl_ros_wrapper::PointCloudNormalsT::Ptr pcl_ros_wrapper::common::do_normal_estimation(\n  const PointCloudT::Ptr& cloud,\n  float                   radius,\n  bool                    visualize)\n{\n  auto cloud_normals = boost::make_shared<PointCloudNormalsT>();\n  pcl::NormalEstimation<pcl::PointXYZ, pcl::Normal> ne;\n  ne.setInputCloud(cloud);\n  ne.setRadiusSearch(radius);\n  ne.compute(*cloud_normals);\n\n  if (visualize) {\n    pcl::visualization::PCLVisualizer viewer(\"PCL Viewer\");\n    viewer.setBackgroundColor(0.0, 0.0, 0.0);\n    viewer.addPointCloudNormals<pcl::PointXYZ, pcl::Normal>(cloud, cloud_normals, 1, 8);\n    viewer.setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE,\n                                            10);\n    viewer.spin();\n  }\n  return cloud_normals;\n}", "meta": {"hexsha": "3a8b0d9f8f239d8d7672a210ebd69db890da72d2", "size": 2560, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/common/surface.cpp", "max_stars_repo_name": "larics/pcl_ros_wrapper", "max_stars_repo_head_hexsha": "cbb4fb2c74a463cee8d5c42dcd8cbabb407b617f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/common/surface.cpp", "max_issues_repo_name": "larics/pcl_ros_wrapper", "max_issues_repo_head_hexsha": "cbb4fb2c74a463cee8d5c42dcd8cbabb407b617f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/surface.cpp", "max_forks_repo_name": "larics/pcl_ros_wrapper", "max_forks_repo_head_hexsha": "cbb4fb2c74a463cee8d5c42dcd8cbabb407b617f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-31T12:42:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-31T12:42:13.000Z", "avg_line_length": 37.1014492754, "max_line_length": 90, "alphanum_fraction": 0.716796875, "num_tokens": 640, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.46834232742688775}}
{"text": "// Copyright  (C)  2007  Ruben Smits <ruben dot smits at mech dot kuleuven dot be>\n\n#ifndef KDL_CHAIN_IKSOLVERVEL_PINV_GIVENS_HPP\n#define KDL_CHAIN_IKSOLVERVEL_PINV_GIVENS_HPP\n\n#include \"chainiksolver.hpp\"\n#include \"chainjnttojacsolver.hpp\"\n\n#include <Eigen/Core>\n\nusing namespace Eigen;\n\nnamespace KDL\n{\n    /**\n     * Implementation of a inverse velocity kinematics algorithm based\n     * on the generalize pseudo inverse to calculate the velocity\n     * transformation from Cartesian to joint space of a general\n     * KDL::Chain. It uses a svd-calculation based on householders\n     * rotations.\n     *\n     * @ingroup KinematicFamily\n     */\n    class ChainIkSolverVel_pinv_givens : public ChainIkSolverVel\n    {\n    public:\n\n        /**\n         * Constructor of the solver\n         *\n         * @param chain the chain to calculate the inverse velocity\n         * kinematics for\n         * @param eps if a singular value is below this value, its\n         * inverse is set to zero, default: 0.00001\n         * @param maxiter maximum iterations for the svd calculation,\n         * default: 150\n         *\n         */\n        explicit ChainIkSolverVel_pinv_givens(const Chain& chain);\n        ~ChainIkSolverVel_pinv_givens();\n\n        virtual int CartToJnt(const JntArray& q_in, const Twist& v_in, JntArray& qdot_out);\n        /**\n         * not (yet) implemented.\n         *\n         */\n        virtual int CartToJnt(const JntArray& q_init, const FrameVel& v_in, JntArrayVel& q_out){return (error = E_NOT_IMPLEMENTED);};\n\n        /// @copydoc KDL::SolverI::updateInternalDataStructures\n        virtual void updateInternalDataStructures();\n\n    private:\n        const Chain& chain;\n        unsigned int nj;\n        ChainJntToJacSolver jnt2jac;\n        Jacobian jac;\n        bool transpose,toggle;\n        unsigned int m,n;\n        MatrixXd jac_eigen,U,V,B;\n        VectorXd S,tempi,tempj,UY,SUY,qdot_eigen,v_in_eigen;\n    };\n}\n#endif\n", "meta": {"hexsha": "be27450be644b1ad829036710a9a2f1183142274", "size": 1937, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libraries/kdl/kdl/chainiksolvervel_pinv_givens.hpp", "max_stars_repo_name": "Laragervaise/AR-mobile-app-for-robots", "max_stars_repo_head_hexsha": "f8b6581bb21a3956893d6552913cc606cc063992", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-07-14T12:33:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-21T07:14:13.000Z", "max_issues_repo_path": "melodic/src/orocos_kinematics_dynamics/orocos_kdl/src/chainiksolvervel_pinv_givens.hpp", "max_issues_repo_name": "disorn-inc/ROS-melodic-python3-Opencv-4.1.1-CUDA", "max_issues_repo_head_hexsha": "3d265bb64712e3cd7dfa0ad56d78fcdebafdb4b0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-07-08T10:26:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-08T10:31:11.000Z", "max_forks_repo_path": "melodic/src/orocos_kinematics_dynamics/orocos_kdl/src/chainiksolvervel_pinv_givens.hpp", "max_forks_repo_name": "disorn-inc/ROS-melodic-python3-Opencv-4.1.1-CUDA", "max_forks_repo_head_hexsha": "3d265bb64712e3cd7dfa0ad56d78fcdebafdb4b0", "max_forks_repo_licenses": ["BSD-3-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.265625, "max_line_length": 133, "alphanum_fraction": 0.6566855963, "num_tokens": 496, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4683164868028986}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n\n#include \"spectral/basis/spectral_basis_factory_ks.hpp\"\n#include \"spectral/basis/toolbox/spectral_basis.hpp\"\n#include \"spectral/p2n_factory.hpp\"\n\nnamespace boltzmann {\n\ntemplate <typename DERIVED, typename FUNC>\nvoid\nto_polar(Eigen::DenseBase<DERIVED>& dst,\n         const FUNC& cart_fun,\n         const SpectralBasisFactoryKS::basis_type basis)\n{\n  using basis_t = SpectralBasisFactoryKS::basis_type;\n\n  int K = spectral::get_K(basis);\n  const auto& P2N = P2NFactory<>::GetInstance(basis);\n\n  dst.derived().resize(basis.size());\n\n  QHermiteW quad(1., K);\n  Eigen::MatrixXd Nd(K, K);\n  for (int i = 0; i < K; ++i) {\n    for (int j = 0; j < K; ++j) {\n      double xi = quad.pts(i);\n      double wi = quad.wts(i);\n      double xj = quad.pts(j);\n      double wj = quad.wts(j);\n      Nd(i,j) = cart_fun(xi, xj) * std::sqrt(wi * wj);\n    }\n  }\n  p2n.to_polar(dst, Nd);\n\n}\n\n\n\n}  // namespace boltzmann\n", "meta": {"hexsha": "e8216962a76b0faa0bf35028fcac1f642553b3c0", "size": 934, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/spectral/to_polar.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/to_polar.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/to_polar.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": 22.2380952381, "max_line_length": 56, "alphanum_fraction": 0.6466809422, "num_tokens": 292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146847, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.46831648680289856}}
{"text": "/*============================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center (DKFZ)\nAll rights reserved.\n\nUse of this source code is governed by a 3-clause BSD license that can be\nfound in the LICENSE file.\n\n============================================================================*/\n\n#ifndef _mitkCLUtil_HXX\n#define _mitkCLUtil_HXX\n\n#include <mitkCLUtil.h>\n\n#include <mitkImageAccessByItk.h>\n\n\n\n#include <Eigen/Dense>\n#include <itkImage.h>\n\n// itk includes\n#include <itkCheckerBoardImageFilter.h>\n#include <itkShapedNeighborhoodIterator.h>\n#include \"itkHessianRecursiveGaussianImageFilter.h\"\n#include \"itkUnaryFunctorImageFilter.h\"\n#include \"vnl/algo/vnl_symmetric_eigensystem.h\"\n#include <itkLaplacianRecursiveGaussianImageFilter.h>\n#include <itkMultiHistogramFilter.h>\n\n// Morphologic Operations\n#include <itkBinaryBallStructuringElement.h>\n#include <itkBinaryDilateImageFilter.h>\n#include <itkBinaryErodeImageFilter.h>\n#include <itkBinaryFillholeImageFilter.h>\n#include <itkBinaryMorphologicalClosingImageFilter.h>\n#include <itkGrayscaleErodeImageFilter.h>\n#include <itkGrayscaleDilateImageFilter.h>\n#include <itkGrayscaleFillholeImageFilter.h>\n\n// Image Filter\n#include <itkDiscreteGaussianImageFilter.h>\n#include <itkSubtractImageFilter.h>\n\nvoid mitk::CLUtil::ProbabilityMap(const mitk::Image::Pointer & image , double mean, double stddev, mitk::Image::Pointer & outimage)\n{\n  AccessFixedDimensionByItk_3(image, mitk::CLUtil::itkProbabilityMap, 3, mean, stddev, outimage);\n}\n\nvoid mitk::CLUtil::ErodeGrayscale(mitk::Image::Pointer & image , unsigned int radius, mitk::CLUtil::MorphologicalDimensions d, mitk::Image::Pointer & outimage)\n{\n  AccessFixedDimensionByItk_3(image, mitk::CLUtil::itkErodeGrayscale, 3, outimage, radius, d);\n}\n\nvoid mitk::CLUtil::DilateGrayscale(mitk::Image::Pointer & image, unsigned int radius, mitk::CLUtil::MorphologicalDimensions d, mitk::Image::Pointer & outimage)\n{\n  AccessFixedDimensionByItk_3(image, mitk::CLUtil::itkDilateGrayscale, 3, outimage, radius, d);\n}\n\nvoid mitk::CLUtil::FillHoleGrayscale(mitk::Image::Pointer & image, mitk::Image::Pointer & outimage)\n{\n  AccessFixedDimensionByItk_1(image, mitk::CLUtil::itkFillHoleGrayscale, 3, outimage);\n}\n\nvoid mitk::CLUtil::InsertLabel(mitk::Image::Pointer & image, mitk::Image::Pointer & maskImage, unsigned int label)\n{\n  AccessByItk_2(image, mitk::CLUtil::itkInsertLabel, maskImage, label);\n}\n\nvoid mitk::CLUtil::GrabLabel(mitk::Image::Pointer & image, mitk::Image::Pointer & outimage, unsigned int label)\n{\n  AccessFixedDimensionByItk_2(image, mitk::CLUtil::itkGrabLabel, 3, outimage, label);\n}\n\nvoid mitk::CLUtil::ConnectedComponentsImage(mitk::Image::Pointer & image, mitk::Image::Pointer& mask, mitk::Image::Pointer &outimage, unsigned int& num_components)\n{\n  AccessFixedDimensionByItk_3(image, mitk::CLUtil::itkConnectedComponentsImage,3, mask, outimage, num_components);\n}\n\nvoid mitk::CLUtil::MergeLabels(mitk::Image::Pointer & img, const std::map<unsigned int, unsigned int> & map)\n{\n  AccessByItk_1(img, mitk::CLUtil::itkMergeLabels, map);\n}\n\nvoid mitk::CLUtil::CountVoxel(mitk::Image::Pointer image, std::map<unsigned int, unsigned int> & map)\n{\n  AccessByItk_1(image, mitk::CLUtil::itkCountVoxel, map);\n}\n\nvoid mitk::CLUtil::CountVoxel(mitk::Image::Pointer image, unsigned int label, unsigned int & count)\n{\n  AccessByItk_2(image, mitk::CLUtil::itkCountVoxel, label, count);\n}\n\nvoid mitk::CLUtil::CountVoxel(mitk::Image::Pointer image, unsigned int & count)\n{\n  AccessByItk_1(image, mitk::CLUtil::itkCountVoxel, count);\n}\n\nvoid mitk::CLUtil::CreateCheckerboardMask(mitk::Image::Pointer image, mitk::Image::Pointer & outimage)\n{\n  AccessFixedDimensionByItk_1(image, mitk::CLUtil::itkCreateCheckerboardMask,3, outimage);\n}\n\nvoid mitk::CLUtil::LogicalAndImages(const mitk::Image::Pointer & image1, const mitk::Image::Pointer & image2, mitk::Image::Pointer & outimage)\n{\n  AccessFixedDimensionByItk_2(image1,itkLogicalAndImages, 3, image2, outimage);\n\n}\n\nvoid mitk::CLUtil::InterpolateCheckerboardPrediction(mitk::Image::Pointer checkerboard_prediction, mitk::Image::Pointer & checkerboard_mask, mitk::Image::Pointer & outimage)\n{\n  AccessFixedDimensionByItk_2(checkerboard_prediction, mitk::CLUtil::itkInterpolateCheckerboardPrediction,3, checkerboard_mask, outimage);\n}\n\nvoid mitk::CLUtil::GaussianFilter(mitk::Image::Pointer image, mitk::Image::Pointer & smoothed ,double sigma)\n{\n  AccessFixedDimensionByItk_2(image, mitk::CLUtil::itkGaussianFilter,3, smoothed, sigma);\n}\n\nvoid mitk::CLUtil::DifferenceOfGaussianFilter(mitk::Image::Pointer image, mitk::Image::Pointer & smoothed, double sigma1, double sigma2)\n{\n  AccessFixedDimensionByItk_3(image, mitk::CLUtil::itkDifferenceOfGaussianFilter, 3, smoothed, sigma1, sigma2);\n}\n\nvoid mitk::CLUtil::LaplacianOfGaussianFilter(mitk::Image::Pointer image, mitk::Image::Pointer & smoothed, double sigma1)\n{\n  AccessByItk_2(image, mitk::CLUtil::itkLaplacianOfGaussianFilter, sigma1, smoothed);\n}\n\nvoid mitk::CLUtil::HessianOfGaussianFilter(mitk::Image::Pointer image, std::vector<mitk::Image::Pointer> &out, double sigma)\n{\n  AccessByItk_2(image, mitk::CLUtil::itkHessianOfGaussianFilter, sigma, out);\n}\n\nvoid mitk::CLUtil::LocalHistogram(mitk::Image::Pointer image, std::vector<mitk::Image::Pointer> &out, int Bins, int NeighbourhoodSize)\n{\n  AccessByItk_3(image, mitk::CLUtil::itkLocalHistograms, out, NeighbourhoodSize, Bins);\n}\n\n\n\nvoid mitk::CLUtil::DilateBinary(mitk::Image::Pointer & sourceImage, mitk::Image::Pointer& resultImage, int factor , MorphologicalDimensions d)\n{\n  AccessFixedDimensionByItk_3(sourceImage, mitk::CLUtil::itkDilateBinary, 3, resultImage, factor, d);\n}\n\n\nvoid mitk::CLUtil::ErodeBinary(mitk::Image::Pointer & sourceImage, mitk::Image::Pointer& resultImage, int factor, MorphologicalDimensions d)\n{\n  AccessFixedDimensionByItk_3(sourceImage, mitk::CLUtil::itkErodeBinary, 3, resultImage, factor, d);\n}\n\n\nvoid mitk::CLUtil::ClosingBinary(mitk::Image::Pointer & sourceImage, mitk::Image::Pointer& resultImage, int factor, MorphologicalDimensions d)\n{\n  AccessFixedDimensionByItk_3(sourceImage, mitk::CLUtil::itkClosingBinary, 3, resultImage, factor, d);\n}\n\ntemplate<typename TImageType>\nvoid mitk::CLUtil::itkProbabilityMap(const TImageType * sourceImage, double mean, double std_dev, mitk::Image::Pointer& resultImage)\n{\n  itk::Image<double, 3>::Pointer itk_img = itk::Image<double, 3>::New();\n  itk_img->SetRegions(sourceImage->GetLargestPossibleRegion());\n  itk_img->SetOrigin(sourceImage->GetOrigin());\n  itk_img->SetSpacing(sourceImage->GetSpacing());\n  itk_img->SetDirection(sourceImage->GetDirection());\n  itk_img->Allocate();\n\n\n  itk::ImageRegionConstIterator<TImageType> it(sourceImage,sourceImage->GetLargestPossibleRegion());\n  itk::ImageRegionIterator<itk::Image<double, 3> > outit(itk_img,itk_img->GetLargestPossibleRegion());\n\n  while(!it.IsAtEnd())\n  {\n    double x = it.Value();\n\n    double prob = (1.0/(std_dev*std::sqrt(2.0*itk::Math::pi))) * std::exp(-(((x-mean)*(x-mean))/(2.0*std_dev*std_dev)));\n    outit.Set(prob);\n    ++it;\n    ++outit;\n  }\n\n  mitk::CastToMitkImage(itk_img, resultImage);\n}\n\ntemplate< typename TImageType >\nvoid mitk::CLUtil::itkInterpolateCheckerboardPrediction(TImageType * checkerboard_prediction, Image::Pointer &checkerboard_mask, mitk::Image::Pointer & outimage)\n{\n  typename TImageType::Pointer itk_checkerboard_mask;\n  mitk::CastToItkImage(checkerboard_mask,itk_checkerboard_mask);\n\n  typename TImageType::Pointer itk_outimage = TImageType::New();\n  itk_outimage->SetRegions(checkerboard_prediction->GetLargestPossibleRegion());\n  itk_outimage->SetDirection(checkerboard_prediction->GetDirection());\n  itk_outimage->SetOrigin(checkerboard_prediction->GetOrigin());\n  itk_outimage->SetSpacing(checkerboard_prediction->GetSpacing());\n  itk_outimage->Allocate();\n  itk_outimage->FillBuffer(0);\n\n  //typedef typename itk::ShapedNeighborhoodIterator<TImageType>::SizeType SizeType;\n  typedef itk::Size<3> SizeType;\n  SizeType size;\n  size.Fill(1);\n  itk::ShapedNeighborhoodIterator<TImageType> iit(size,checkerboard_prediction,checkerboard_prediction->GetLargestPossibleRegion());\n  itk::ShapedNeighborhoodIterator<TImageType> mit(size,itk_checkerboard_mask,itk_checkerboard_mask->GetLargestPossibleRegion());\n  itk::ImageRegionIterator<TImageType> oit(itk_outimage,itk_outimage->GetLargestPossibleRegion());\n\n  typedef typename itk::ShapedNeighborhoodIterator<TImageType>::OffsetType OffsetType;\n  OffsetType offset;\n  offset.Fill(0);\n  offset[0] = 1;       // {1,0,0}\n  iit.ActivateOffset(offset);\n  mit.ActivateOffset(offset);\n  offset[0] = -1;      // {-1,0,0}\n  iit.ActivateOffset(offset);\n  mit.ActivateOffset(offset);\n  offset[0] = 0; offset[1] = 1; //{0,1,0}\n  iit.ActivateOffset(offset);\n  mit.ActivateOffset(offset);\n  offset[1] = -1;      //{0,-1,0}\n  iit.ActivateOffset(offset);\n  mit.ActivateOffset(offset);\n\n  //    iit.ActivateOffset({{0,0,1}});\n  //    iit.ActivateOffset({{0,0,-1}});\n  //    mit.ActivateOffset({{0,0,1}});\n  //    mit.ActivateOffset({{0,0,-1}});\n\n  while(!iit.IsAtEnd())\n  {\n    if(mit.GetCenterPixel() == 0)\n    {\n      typename TImageType::PixelType mean = 0;\n      for (auto i = iit.Begin(); ! i.IsAtEnd(); i++)\n      { mean += i.Get(); }\n\n\n      //std::sort(list.begin(),list.end(),[](const typename TImageType::PixelType x,const typename TImageType::PixelType y){return x<=y;});\n\n      oit.Set((mean+0.5)/6.0);\n    }\n    else\n    {\n      oit.Set(iit.GetCenterPixel());\n    }\n    ++iit;\n    ++mit;\n    ++oit;\n  }\n\n  mitk::CastToMitkImage(itk_outimage,outimage);\n}\n\ntemplate< typename TImageType >\nvoid mitk::CLUtil::itkCreateCheckerboardMask(TImageType * image, mitk::Image::Pointer & outimage)\n{\n  typename TImageType::Pointer zeroimg = TImageType::New();\n  zeroimg->SetRegions(image->GetLargestPossibleRegion());\n  zeroimg->SetDirection(image->GetDirection());\n  zeroimg->SetOrigin(image->GetOrigin());\n  zeroimg->SetSpacing(image->GetSpacing());\n\n  zeroimg->Allocate();\n  zeroimg->FillBuffer(0);\n\n  typedef itk::CheckerBoardImageFilter<TImageType> FilterType;\n  typename FilterType::Pointer filter = FilterType::New();\n  filter->SetInput1(image);\n  filter->SetInput2(zeroimg);\n  typename FilterType::PatternArrayType pattern;\n  pattern.SetElement(0,(image->GetLargestPossibleRegion().GetSize()[0]));\n  pattern.SetElement(1,(image->GetLargestPossibleRegion().GetSize()[1]));\n  pattern.SetElement(2,(image->GetLargestPossibleRegion().GetSize()[2]));\n  filter->SetCheckerPattern(pattern);\n\n  filter->Update();\n  mitk::CastToMitkImage(filter->GetOutput(), outimage);\n}\n\n\ntemplate <class TImageType>\nvoid mitk::CLUtil::itkSumVoxelForLabel(TImageType* image, const mitk::Image::Pointer & source , typename TImageType::PixelType label, double & val )\n{\n  itk::Image<double,3>::Pointer itk_source;\n  mitk::CastToItkImage(source,itk_source);\n\n  itk::ImageRegionConstIterator<TImageType> inputIter(image, image->GetLargestPossibleRegion());\n  itk::ImageRegionConstIterator< itk::Image<double,3> > sourceIter(itk_source, itk_source->GetLargestPossibleRegion());\n  while(!inputIter.IsAtEnd())\n  {\n    if(inputIter.Value() == label) val += sourceIter.Value();\n    ++inputIter;\n    ++sourceIter;\n  }\n}\n\ntemplate <class TImageType>\nvoid mitk::CLUtil::itkSqSumVoxelForLabel(TImageType* image, const mitk::Image::Pointer & source, typename TImageType::PixelType label, double & val )\n{\n  itk::Image<double,3>::Pointer itk_source;\n  mitk::CastToItkImage(source,itk_source);\n\n  itk::ImageRegionConstIterator<TImageType> inputIter(image, image->GetLargestPossibleRegion());\n  itk::ImageRegionConstIterator< itk::Image<double,3> > sourceIter(itk_source, itk_source->GetLargestPossibleRegion());\n  while(!inputIter.IsAtEnd())\n  {\n    if(inputIter.Value() == label) val += sourceIter.Value() * sourceIter.Value();\n    ++inputIter;\n    ++sourceIter;\n  }\n}\n\ntemplate<typename TStructuringElement>\nvoid mitk::CLUtil::itkFitStructuringElement(TStructuringElement & se, MorphologicalDimensions d, int factor)\n{\n  typename TStructuringElement::SizeType size;\n  size.Fill(factor);\n  switch(d)\n  {\n  case(All):\n  case(Axial):\n    size.SetElement(2,0);\n    break;\n  case(Sagital):\n    size.SetElement(0,0);\n    break;\n  case(Coronal):\n    size.SetElement(1,0);\n    break;\n  }\n  se.SetRadius(size);\n  se.CreateStructuringElement();\n}\n\ntemplate<typename TImageType>\nvoid mitk::CLUtil::itkClosingBinary(TImageType * sourceImage, mitk::Image::Pointer& resultImage, int factor, MorphologicalDimensions d)\n{\n  typedef itk::BinaryBallStructuringElement<typename TImageType::PixelType, 3> BallType;\n  typedef itk::BinaryMorphologicalClosingImageFilter<TImageType, TImageType, BallType> FilterType;\n\n  BallType strElem;\n  itkFitStructuringElement(strElem,d,factor);\n\n  typename FilterType::Pointer erodeFilter = FilterType::New();\n  erodeFilter->SetKernel(strElem);\n  erodeFilter->SetInput(sourceImage);\n  erodeFilter->SetForegroundValue(1);\n  erodeFilter->Update();\n\n  mitk::CastToMitkImage(erodeFilter->GetOutput(), resultImage);\n\n}\n\ntemplate<typename TImageType>\nvoid mitk::CLUtil::itkDilateBinary(TImageType * sourceImage, mitk::Image::Pointer& resultImage, int factor, MorphologicalDimensions d)\n{\n  typedef itk::BinaryBallStructuringElement<typename TImageType::PixelType, 3> BallType;\n  typedef typename itk::BinaryDilateImageFilter<TImageType, TImageType, BallType> BallDilateFilterType;\n\n  BallType strElem;\n  itkFitStructuringElement(strElem,d,factor);\n\n  typename BallDilateFilterType::Pointer erodeFilter = BallDilateFilterType::New();\n  erodeFilter->SetKernel(strElem);\n  erodeFilter->SetInput(sourceImage);\n  erodeFilter->SetDilateValue(1);\n  erodeFilter->Update();\n\n  mitk::CastToMitkImage(erodeFilter->GetOutput(), resultImage);\n\n}\n\ntemplate<typename TImageType>\nvoid mitk::CLUtil::itkErodeBinary(TImageType * sourceImage, mitk::Image::Pointer& resultImage, int factor, MorphologicalDimensions d)\n{\n  typedef itk::BinaryBallStructuringElement<typename TImageType::PixelType, 3> BallType;\n  typedef typename itk::BinaryErodeImageFilter<TImageType, TImageType, BallType> BallErodeFilterType;\n\n  BallType strElem;\n  itkFitStructuringElement(strElem,d,factor);\n\n\n  typename BallErodeFilterType::Pointer erodeFilter = BallErodeFilterType::New();\n  erodeFilter->SetKernel(strElem);\n  erodeFilter->SetInput(sourceImage);\n  erodeFilter->SetErodeValue(1);\n//  erodeFilter->UpdateLargestPossibleRegion();\n  erodeFilter->Update();\n\n  mitk::CastToMitkImage(erodeFilter->GetOutput(), resultImage);\n\n}\n\n///\n/// \\brief itkFillHolesBinary\n/// \\param sourceImage\n/// \\param resultImage\n///\ntemplate<typename TPixel, unsigned int VDimension>\nvoid mitk::CLUtil::itkFillHolesBinary(itk::Image<TPixel, VDimension>* sourceImage, mitk::Image::Pointer& resultImage)\n{\n  typedef itk::Image<TPixel, VDimension> ImageType;\n  typedef typename itk::BinaryFillholeImageFilter<ImageType> FillHoleFilterType;\n\n  typename FillHoleFilterType::Pointer fillHoleFilter = FillHoleFilterType::New();\n  fillHoleFilter->SetInput(sourceImage);\n  fillHoleFilter->SetForegroundValue(1);\n  fillHoleFilter->Update();\n\n  mitk::CastToMitkImage(fillHoleFilter->GetOutput(), resultImage);\n}\n\n///\n/// \\brief itkLogicalAndImages\n/// \\param image1 keep the values of image 1\n/// \\param image2\n///\ntemplate<typename TImageType>\nvoid mitk::CLUtil::itkLogicalAndImages(const TImageType * image1, const mitk::Image::Pointer & image2, mitk::Image::Pointer & outimage)\n{\n\n  typename TImageType::Pointer itk_outimage = TImageType::New();\n  itk_outimage->SetRegions(image1->GetLargestPossibleRegion());\n  itk_outimage->SetDirection(image1->GetDirection());\n  itk_outimage->SetOrigin(image1->GetOrigin());\n  itk_outimage->SetSpacing(image1->GetSpacing());\n\n  itk_outimage->Allocate();\n  itk_outimage->FillBuffer(0);\n\n  typename TImageType::Pointer itk_image2;\n  mitk::CastToItkImage(image2,itk_image2);\n\n  itk::ImageRegionConstIterator<TImageType> it1(image1, image1->GetLargestPossibleRegion());\n  itk::ImageRegionConstIterator<TImageType> it2(itk_image2, itk_image2->GetLargestPossibleRegion());\n  itk::ImageRegionIterator<TImageType> oit(itk_outimage,itk_outimage->GetLargestPossibleRegion());\n\n  while(!it1.IsAtEnd())\n  {\n    if(it1.Value() == 0 || it2.Value() == 0)\n    {\n      oit.Set(0);\n    }else\n      oit.Set(it1.Value());\n    ++it1;\n    ++it2;\n    ++oit;\n  }\n\n  mitk::CastToMitkImage(itk_outimage, outimage);\n}\n\n///\n/// \\brief GaussianFilter\n/// \\param image\n/// \\param smoothed\n/// \\param sigma\n///\ntemplate<class TImageType>\nvoid mitk::CLUtil::itkGaussianFilter(TImageType * image, mitk::Image::Pointer & smoothed ,double sigma)\n{\n  typedef itk::DiscreteGaussianImageFilter<TImageType,TImageType> FilterType;\n  typename FilterType::Pointer filter = FilterType::New();\n  filter->SetInput(image);\n  filter->SetVariance(sigma);\n  filter->Update();\n\n  mitk::CastToMitkImage(filter->GetOutput(),smoothed);\n}\n\ntemplate<class TImageType>\nvoid mitk::CLUtil::itkDifferenceOfGaussianFilter(TImageType * image, mitk::Image::Pointer & smoothed, double sigma1, double sigma2)\n{\n  typedef itk::DiscreteGaussianImageFilter<TImageType, TImageType> FilterType;\n  typedef itk::SubtractImageFilter <TImageType, TImageType> SubtractFilterType;\n  typename FilterType::Pointer filter1 = FilterType::New();\n  typename FilterType::Pointer filter2 = FilterType::New();\n  typename SubtractFilterType::Pointer subFilter = SubtractFilterType::New();\n  filter1->SetInput(image);\n  filter1->SetVariance(sigma1);\n  filter1->Update();\n  filter2->SetInput(image);\n  filter2->SetVariance(sigma2);\n  filter2->Update();\n  subFilter->SetInput1(filter1->GetOutput());\n  subFilter->SetInput2(filter2->GetOutput());\n  subFilter->Update();\n\n  mitk::CastToMitkImage(subFilter->GetOutput(), smoothed);\n}\n\n\ntemplate<typename TPixel, unsigned int VImageDimension>\nvoid mitk::CLUtil::itkLaplacianOfGaussianFilter(itk::Image<TPixel, VImageDimension>* itkImage, double variance, mitk::Image::Pointer &output)\n{\n  typedef itk::Image<TPixel, VImageDimension> ImageType;\n  typedef itk::DiscreteGaussianImageFilter< ImageType, ImageType >  GaussFilterType;\n  typedef itk::LaplacianRecursiveGaussianImageFilter<ImageType, ImageType>    LaplacianFilter;\n\n  typename GaussFilterType::Pointer gaussianFilter = GaussFilterType::New();\n  gaussianFilter->SetInput(itkImage);\n  gaussianFilter->SetVariance(variance);\n  gaussianFilter->Update();\n  typename LaplacianFilter::Pointer laplaceFilter = LaplacianFilter::New();\n  laplaceFilter->SetInput(gaussianFilter->GetOutput());\n  laplaceFilter->Update();\n  mitk::CastToMitkImage(laplaceFilter->GetOutput(), output);\n}\n\nnamespace Functor\n{\n  template <class TInput, class TOutput>\n  class MatrixFirstEigenvalue\n  {\n  public:\n    MatrixFirstEigenvalue() {}\n    virtual ~MatrixFirstEigenvalue() {}\n\n    int order;\n\n    inline TOutput operator ()(const TInput& input)\n    {\n      double a, b, c;\n      if (input[0] < 0.01 && input[1] < 0.01 &&input[2] < 0.01 &&input[3] < 0.01 &&input[4] < 0.01 &&input[5] < 0.01)\n        return 0;\n      vnl_symmetric_eigensystem_compute_eigenvals(input[0], input[1], input[2], input[3], input[4], input[5], a, b, c);\n      switch (order)\n      {\n      case 0: return a;\n      case 1: return b;\n      case 2: return c;\n      default: return a;\n      }\n    }\n    bool operator !=(const MatrixFirstEigenvalue) const\n    {\n      return false;\n    }\n    bool operator ==(const MatrixFirstEigenvalue& other) const\n    {\n      return !(*this != other);\n    }\n  };\n}\n\ntemplate<typename TPixel, unsigned int VImageDimension>\nvoid mitk::CLUtil::itkHessianOfGaussianFilter(itk::Image<TPixel, VImageDimension>* itkImage, double variance, std::vector<mitk::Image::Pointer> &out)\n{\n  typedef itk::Image<TPixel, VImageDimension> ImageType;\n  typedef itk::Image<double, VImageDimension> FloatImageType;\n  typedef itk::HessianRecursiveGaussianImageFilter <ImageType> HessianFilterType;\n  typedef typename HessianFilterType::OutputImageType VectorImageType;\n  typedef Functor::MatrixFirstEigenvalue<typename VectorImageType::PixelType, double> DeterminantFunctorType;\n  typedef itk::UnaryFunctorImageFilter<VectorImageType, FloatImageType, DeterminantFunctorType> DetFilterType;\n\n  typename HessianFilterType::Pointer hessianFilter = HessianFilterType::New();\n  hessianFilter->SetInput(itkImage);\n  hessianFilter->SetSigma(std::sqrt(variance));\n  for (unsigned int i = 0; i < VImageDimension; ++i)\n  {\n    mitk::Image::Pointer tmpImage = mitk::Image::New();\n    typename DetFilterType::Pointer detFilter = DetFilterType::New();\n    detFilter->SetInput(hessianFilter->GetOutput());\n    detFilter->GetFunctor().order = i;\n    detFilter->Update();\n    mitk::CastToMitkImage(detFilter->GetOutput(), tmpImage);\n    out.push_back(tmpImage);\n  }\n}\n\ntemplate<typename TPixel, unsigned int VImageDimension>\nvoid mitk::CLUtil::itkLocalHistograms(itk::Image<TPixel, VImageDimension>* itkImage, std::vector<mitk::Image::Pointer> &out, int size, int bins)\n{\n  typedef itk::Image<TPixel, VImageDimension> ImageType;\n  typedef itk::MultiHistogramFilter <ImageType, ImageType> MultiHistogramType;\n\n  typename MultiHistogramType::Pointer filter = MultiHistogramType::New();\n  filter->SetInput(itkImage);\n  filter->SetUseImageIntensityRange(true);\n  filter->SetSize(size);\n  filter->SetBins(bins);\n  filter->Update();\n  for (int i = 0; i < bins; ++i)\n  {\n    mitk::Image::Pointer img = mitk::Image::New();\n    mitk::CastToMitkImage(filter->GetOutput(i), img);\n    out.push_back(img);\n  }\n}\n\ntemplate<class TImageType>\nvoid mitk::CLUtil::itkErodeGrayscale(TImageType * image, mitk::Image::Pointer & outimage , unsigned int radius, mitk::CLUtil::MorphologicalDimensions d)\n{\n  typedef itk::BinaryBallStructuringElement<typename TImageType::PixelType, 3>          StructureElementType;\n  typedef itk::GrayscaleErodeImageFilter<TImageType,TImageType,StructureElementType>    FilterType;\n\n  StructureElementType ball;\n  itkFitStructuringElement(ball,d, radius);\n\n  typename FilterType::Pointer filter = FilterType::New();\n  filter->SetKernel(ball);\n  filter->SetInput(image);\n  filter->Update();\n\n  mitk::CastToMitkImage(filter->GetOutput(),outimage);\n}\n\ntemplate<class TImageType>\nvoid mitk::CLUtil::itkDilateGrayscale(TImageType * image, mitk::Image::Pointer & outimage , unsigned int radius, mitk::CLUtil::MorphologicalDimensions d)\n{\n  typedef itk::BinaryBallStructuringElement<typename TImageType::PixelType, 3>          StructureElementType;\n  typedef itk::GrayscaleDilateImageFilter<TImageType,TImageType,StructureElementType>    FilterType;\n\n  StructureElementType ball;\n  itkFitStructuringElement(ball,d, radius);\n\n  typename FilterType::Pointer filter = FilterType::New();\n  filter->SetKernel(ball);\n  filter->SetInput(image);\n  filter->Update();\n\n  mitk::CastToMitkImage(filter->GetOutput(),outimage);\n}\n\ntemplate<class TImageType>\nvoid mitk::CLUtil::itkFillHoleGrayscale(TImageType * image, mitk::Image::Pointer & outimage)\n{\n  typedef itk::GrayscaleFillholeImageFilter<TImageType,TImageType>    FilterType;\n\n  typename FilterType::Pointer filter = FilterType::New();\n  filter->SetInput(image);\n  filter->Update();\n\n  mitk::CastToMitkImage(filter->GetOutput(),outimage);\n}\n\n\n#endif\n", "meta": {"hexsha": "115d7c863033ac816d45a4c1b637d66b5968dab7", "size": 23156, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Modules/Classification/CLUtilities/src/mitkCLUtil.cpp", "max_stars_repo_name": "zhaomengxiao/MITK", "max_stars_repo_head_hexsha": "a09fd849a4328276806008bfa92487f83a9e2437", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-03T12:03:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T12:03:32.000Z", "max_issues_repo_path": "Modules/Classification/CLUtilities/src/mitkCLUtil.cpp", "max_issues_repo_name": "zhaomengxiao/MITK", "max_issues_repo_head_hexsha": "a09fd849a4328276806008bfa92487f83a9e2437", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-22T10:19:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-22T10:19:02.000Z", "max_forks_repo_path": "Modules/Classification/CLUtilities/src/mitkCLUtil.cpp", "max_forks_repo_name": "zhaomengxiao/MITK_lancet", "max_forks_repo_head_hexsha": "a09fd849a4328276806008bfa92487f83a9e2437", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-27T09:41:18.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-27T09:41:18.000Z", "avg_line_length": 36.0124416796, "max_line_length": 173, "alphanum_fraction": 0.7470202107, "num_tokens": 6495, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4683164813773472}}
{"text": "#include <math.h>\n#include <uWS/uWS.h>\n#include <iostream>\n#include <string>\n#include \"json.hpp\"\n#include \"PID.h\"\n#include <boost/algorithm/clamp.hpp>\n\n// for convenience\nusing nlohmann::json;\nusing std::string;\n\n// For converting back and forth between radians and degrees.\nconstexpr double pi() { return M_PI; }\ndouble deg2rad(double x) { return x * pi() / 180; }\ndouble rad2deg(double x) { return x * 180 / pi(); }\n\n// Checks if the SocketIO event has JSON data.\n// If there is data the JSON object in string format will be returned,\n// else the empty string \"\" will be returned.\nstring hasData(string s) {\n  auto found_null = s.find(\"null\");\n  auto b1 = s.find_first_of(\"[\");\n  auto b2 = s.find_last_of(\"]\");\n  if (found_null != string::npos) {\n    return \"\";\n  }\n  else if (b1 != string::npos && b2 != string::npos) {\n    return s.substr(b1, b2 - b1 + 1);\n  }\n  return \"\";\n}\n\n// for PID and twiddle\ndouble MAX_ANGLE = 100.0;\ndouble MAX_SPD_MOD = 1.0;\ndouble MIN_SPD_MOD = 0.25; \ndouble HI_ANGLE = 5.0;\n\nint main() {\n  uWS::Hub h;\n\n  PID pid;\n  PID spd_pid;\n  /**\n   * Initialize the pid variable.\n   */ \n\n  double kd = 0.01;\n  double kp = 0.1;\n  double ki = 0.0001;\n  pid.Init(kp, ki, kd);\n  spd_pid.Init(0.3, 0.00, 0.001);\n  int iter = 0; \n  double tol = 0.0005  ;\n  double best_cte = 100000;\n  double throttle_set = 0.2;\n  bool tune_steering = false;\n  bool hs_tuning = false;\n  bool tune_throttle = false;\n  double target_speed = 20.0;\n  double best_spd_err = 100000;\n  bool spd_tuned = false;\n\n  h.onMessage([&pid, &spd_pid, &iter, &tol, &best_cte, &best_spd_err, &hs_tuning,\n                &throttle_set, &target_speed, &spd_tuned,\n                &tune_steering, &tune_throttle](uWS::WebSocket<uWS::SERVER> ws, char *data, size_t length, \n                     uWS::OpCode opCode) {\n    // \"42\" at the start of the message means there's a websocket message event.\n    // The 4 signifies a websocket message\n    // The 2 signifies a websocket event\n    if (length && length > 2 && data[0] == '4' && data[1] == '2') {\n      auto s = hasData(string(data).substr(0, length));\n\n      if (s != \"\") {\n        auto j = json::parse(s);\n\n        string event = j[0].get<string>();\n\n        if (event == \"telemetry\") {\n          // j[1] is the data JSON object\n          double cte = std::stod(j[1][\"cte\"].get<string>());\n          double speed = std::stod(j[1][\"speed\"].get<string>());\n          double angle = std::stod(j[1][\"steering_angle\"].get<string>());\n          double steer_value;\n          /**\n           * Calculate steering value--remember the steering value is\n           *   [-1, 1]\n           */\n\n          double spd_err = speed - target_speed;     \n\n          if (iter == 20) {\n            best_cte = fabs(cte);\n            tune_steering = true;\n            //spd_tuned = true;\n            }\n\n\n          pid.UpdateError(cte);\n          steer_value = pid.TotalError();\n          steer_value = boost::algorithm::clamp(steer_value, -1.0, 1.0);\n          iter+=1;\n\n\n          if (tune_steering == true) {\n            std::cout << \"cte/best: \" << cte << \" / \" << best_cte << std::endl;\n            pid.Twiddle(best_cte, cte);\n            std::cout << \"  --- tol: \"<< pid.TolCheck() << std::endl;\n\n            if (pid.TolCheck() < tol) {\n              std::cout << \"*************** steering tuned ***************\" << std::endl;\n              tune_steering = false;\n              tune_throttle = true;\n              best_spd_err = spd_err;\n              hs_tuning = false;\n            }\n          }\n\n          // if (tune_throttle) {\n          //   std::cout << \"speed err/best: \" << spd_err << \" / \" << best_spd_err << std::endl;\n          //   spd_pid.Twiddle(best_spd_err, spd_err);\n          //   std::cout << \"  --- tol: \"<< spd_pid.TolCheck() << std::endl;\n\n          //   if (spd_pid.TolCheck() < tol) {\n          //     tune_throttle = false;\n          //     spd_tuned = true;\n          //   }\n          // }\n\n          if (iter % 3000 == 0 && hs_tuning == false) {\n            tune_steering = true;\n            hs_tuning = true;\n            pid.RetrainPID();\n          }\n\n          if (tune_throttle) {\n            spd_tuned = true;\n            }\n\n          \n          if (spd_tuned) {\n            spd_pid.UpdateError(spd_err);\n            throttle_set = spd_pid.TotalError();\n            throttle_set = boost::algorithm::clamp(throttle_set, 0.0, 0.5);\n\n            double spd_mod = 1.0;\n            if (fabs(angle) > HI_ANGLE) {\n              spd_mod = 0.25;\n            } else {\n              double low_mod = 1.0 / (HI_ANGLE + 1);\n              spd_mod = 1.0 / (fabs(angle) + 1);\n\n              spd_mod =  (spd_mod - low_mod)/(1.0 - low_mod) * (MAX_SPD_MOD - MIN_SPD_MOD) + MIN_SPD_MOD;\n              // spd_mod = boost::algorithm::clamp(spd_mod, 0.5, 1.0);            \n            }\n            //std::cout << spd_mod << std::endl;\n            throttle_set *= spd_mod;\n\n          }\n\n\n\n          // DEBUG\n\n          // std::cout << iter << \" ->  CTE: \" << cte << \" Steering Value: \" << steer_value  << \"   Throttle: \" << throttle_set\n          //           << std::endl;\n\n          json msgJson;\n          msgJson[\"steering_angle\"] = steer_value;\n          msgJson[\"throttle\"] = throttle_set;\n          auto msg = \"42[\\\"steer\\\",\" + msgJson.dump() + \"]\";\n          // std::cout << msg << std::endl;\n          ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT);\n    \n\n        }  // end \"telemetry\" if\n      } else {\n        // Manual driving\n        string msg = \"42[\\\"manual\\\",{}]\";\n        ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT);\n      }\n    }  // end websocket message if\n  }); // end h.onMessage\n\n  h.onConnection([&h](uWS::WebSocket<uWS::SERVER> ws, uWS::HttpRequest req) {\n    std::cout << \"Connected!!!\" << std::endl;\n  });\n\n  h.onDisconnection([&h](uWS::WebSocket<uWS::SERVER> ws, int code, \n                         char *message, size_t length) {\n    ws.close();\n    std::cout << \"Disconnected\" << std::endl;\n  });\n\n  int port = 4567;\n  if (h.listen(port)) {\n    std::cout << \"Listening to port \" << port << std::endl;\n  } else {\n    std::cerr << \"Failed to listen to port\" << std::endl;\n    return -1;\n  }\n  \n  h.run();\n  \n\n}", "meta": {"hexsha": "ad15fd6d947120baf8f9e0e4ddf2cc477baa3c00", "size": 6174, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "stevenjnovotny/PID_controller", "max_stars_repo_head_hexsha": "d2a8cf1775b506b61d5a13dcb88363e4b95c8ce8", "max_stars_repo_licenses": ["MIT"], "max_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": "stevenjnovotny/PID_controller", "max_issues_repo_head_hexsha": "d2a8cf1775b506b61d5a13dcb88363e4b95c8ce8", "max_issues_repo_licenses": ["MIT"], "max_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": "stevenjnovotny/PID_controller", "max_forks_repo_head_hexsha": "d2a8cf1775b506b61d5a13dcb88363e4b95c8ce8", "max_forks_repo_licenses": ["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.8260869565, "max_line_length": 127, "alphanum_fraction": 0.5186264982, "num_tokens": 1747, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4683164813773472}}
{"text": "#include \"sigma.h\"\n#include \"../wavelet/wavelet.h\"\n#include <armadillo>\n#include <iostream>\n\nrpm::vector<double> SIGMA::analyse(const rpm::vector<double>& lx, double fs)\n{\n    constexpr double fmin = 50;\n    constexpr double fmax = 400;\n\n    constexpr double Tmin = 1.0 / fmax;\n    constexpr double Tmax = 1.0 / fmin;\n\n    constexpr double oqmin = 0.1;\n    constexpr double oqmax = 0.9;\n\n    constexpr double gwlen = Tmin;\n    constexpr double fwlen = 0.000;\n    \n    constexpr int nclust = 2;\n   \n    // Calculate SWT\n    constexpr int nlev = 5;\n    Wt::DiscreteWavelet wavelet(Wt::BIOR, 15);\n    rpm::vector<double> swc = Analysis::swt(lx, wavelet, nlev, 0, true);\n\n    // Calculate multiscale product\n    int dlen = (int) Wt::swt_buffer_length((int) lx.size());\n    rpm::vector<double> mp(dlen, 1.0);\n    for (int k = 1; k * dlen < (int) swc.size(); ++k) {\n        for (int i = 0; i < dlen; ++i) {\n            mp[i] *= swc[k * dlen + i];\n        }\n    }\n    \n    // Find third roots\n    rpm::vector<double> nmp(mp);\n    rpm::vector<double> pmp(mp);\n    rpm::vector<double> crnmp(mp.size());\n    rpm::vector<double> crpmp(mp.size());\n    for (int i = 0; i < (int) mp.size(); ++i) {\n        // Half-wave rectify on negative half of mp for GCI\n        if (nmp[i] > 0)\n            nmp[i] = 0;\n\n        // Half-wave rectify on positive half of mp for GOI\n        if (pmp[i] < 0)\n            pmp[i] = 0;\n\n        crnmp[i] = cbrt(nmp[i]);\n        crpmp[i] = cbrt(pmp[i]);\n    }\n\n    // Group delay evaluation on mp\n    auto [gcic, nsew, ngrdel, ntoff] = xewgrdel(nmp, fs, gwlen, fwlen);\n    ngrdel.insert(ngrdel.begin(), ntoff, 0.0);\n    ngrdel.erase(std::prev(ngrdel.end(), ntoff), ngrdel.end());\n\n    auto [goic, psew, pgrdel, ptoff] = xewgrdel(pmp, fs, gwlen, fwlen);\n    pgrdel.insert(pgrdel.begin(), ptoff, 0.0);\n    pgrdel.erase(std::prev(pgrdel.end(), ptoff), pgrdel.end());\n\n    // Set up other variables\n    rpm::vector<double> gci(lx.size(), 0.0);\n    rpm::vector<double> goi(lx.size(), 0.0);\n    \n    // --- GCI Detection ---\n\n    // Model GD slope\n    const int nr = ((int) std::round(gwlen * fs)) / 2 - 1;\n    const int mngrdellen = 2 * nr + 1;\n    rpm::vector<double> mngrdel(mngrdellen);\n    for (int i = 0; i < mngrdellen; ++i) {\n        mngrdel[i] = i - nr;\n    }\n    rpm::vector<double> cmngrdel(ngrdel.size(), 0.0);\n\n    const int snfv = (int) gcic.size();\n    arma::mat nfv(3, snfv, arma::fill::zeros);\n\n    for (int i = 0; i < snfv; ++i) {\n        int lbnd = (int) std::round(gcic[i] - nr);\n        int ubnd = lbnd + mngrdellen - 1;\n\n        if (lbnd >= 0 && ubnd < (int) ngrdel.size()) {\n            double sum = 0.0;\n            double min = HUGE_VAL;\n            double mean = 0.0;\n\n            for (int k = lbnd; k <= ubnd; ++k) {\n                sum += crnmp[k];\n                if (crnmp[k] < min)\n                    min = crnmp[k];\n                \n                double v = mngrdel[k - lbnd] - ngrdel[k];\n                mean += v * v;\n\n                cmngrdel[k] = mngrdel[k - lbnd];\n            }\n\n            nfv(0, i) = sum; // Sum of crnmp over GD window\n            nfv(1, i) = min; // Peak value of crnmp\n            nfv(2, i) = sqrt(mean / mngrdellen); // Phase slope deviation\n        }\n    }\n\n    // Determine clusters\n    arma::gmm_diag ngmm;\n    bool status = ngmm.learn(nfv, 3, arma::eucl_dist, arma::random_subset, 10, 5, 1e-8, false);\n\n    // Find cluster with lowest crnmp sum\n    int I = (int) arma::index_min(ngmm.means.row(0));\n   \n    // If the candidate belongs to the chosen cluster then keep \n    for (int i = 0; i < snfv; ++i) {\n        if (ngmm.assign(nfv.col(i), arma::eucl_dist) == (arma::uword) I) {\n            int k = std::max(0, std::min((int) gci.size() - 1, (int) std::round(gcic[i])));\n            gci[k] = 1.0;\n        }\n    }\n\n    // --- Post-filter swallows (GCIs only) ---\n\n    if (gci.size() > 2) {\n        // If a gci is separated from all others by more than Tmax, delete\n        rpm::list<int> fgci;\n        for (int i = 0; i < (int) gci.size(); ++i) {\n            if (gci[i] > 0) {\n                fgci.push_back(i);\n            }\n        }\n        \n        // Check first one\n        auto i0 = fgci.begin();\n        auto i1 = std::next(i0);\n        if (*i1 - *i0 > Tmax * fs) {\n            fgci.pop_front();\n        }\n\n        // Check the middle\n        auto i2 = std::next(fgci.begin(), 2);\n        auto iend = std::prev(fgci.end());\n        \n        while (i2 != iend) {\n            auto i2prev = std::prev(i2);\n            auto i2next = std::next(i2);\n\n            if ((*i2 - *i2prev > Tmax * fs)\n                    && (*i2next - *i2 > Tmax * fs)) {\n                fgci.erase(i2);\n            }\n\n            i2 = i2next;\n        }\n\n        // Check last one\n        auto iendprev = std::prev(iend);\n        if (*iend - *iendprev > Tmax * fs) {\n            fgci.pop_back();\n        }\n\n        // Convert back\n        std::fill(gci.begin(), gci.end(), 0.0);\n        for (auto t : fgci) {\n            gci[t] = 1.0;\n        }\n    }\n\n    return gci;\n\n    // --- GOI detection ---\n\n}\n", "meta": {"hexsha": "87d28cef6c50a06513230af53fd5d7d61e696983", "size": 5056, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/analysis/gci/sigma.cpp", "max_stars_repo_name": "alargepileofash/in-formant", "max_stars_repo_head_hexsha": "3fc77925b68e349b96d7cf20c00223a4b343d04d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 55.0, "max_stars_repo_stars_event_min_datetime": "2020-10-07T20:22:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-28T10:58:36.000Z", "max_issues_repo_path": "src/analysis/gci/sigma.cpp", "max_issues_repo_name": "alargepileofash/in-formant", "max_issues_repo_head_hexsha": "3fc77925b68e349b96d7cf20c00223a4b343d04d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 16.0, "max_issues_repo_issues_event_min_datetime": "2020-12-06T22:02:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-19T09:37:56.000Z", "max_forks_repo_path": "src/analysis/gci/sigma.cpp", "max_forks_repo_name": "alargepileofash/in-formant", "max_forks_repo_head_hexsha": "3fc77925b68e349b96d7cf20c00223a4b343d04d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2019-12-16T16:06:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-15T15:28:31.000Z", "avg_line_length": 29.0574712644, "max_line_length": 95, "alphanum_fraction": 0.4982199367, "num_tokens": 1643, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478255, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4683164759517956}}
{"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 * testDiscreteBayesNet.cpp\n *\n *  @date Feb 27, 2011\n *  @author Frank Dellaert\n */\n\n#include <gtsam/discrete/DiscreteBayesNet.h>\n#include <gtsam/discrete/DiscreteFactorGraph.h>\n#include <gtsam/discrete/DiscreteMarginals.h>\n#include <gtsam/base/debug.h>\n#include <gtsam/base/Testable.h>\n#include <gtsam/base/Vector.h>\n\n#include <CppUnitLite/TestHarness.h>\n\n\n#include <boost/assign/list_inserter.hpp>\n#include <boost/assign/std/map.hpp>\n\nusing namespace boost::assign;\n\n#include <iostream>\n#include <string>\n#include <vector>\n\nusing namespace std;\nusing namespace gtsam;\n\n/* ************************************************************************* */\nTEST(DiscreteBayesNet, bayesNet) {\n  DiscreteBayesNet bayesNet;\n  DiscreteKey Parent(0, 2), Child(1, 2);\n\n  auto prior = boost::make_shared<DiscreteConditional>(Parent % \"6/4\");\n  CHECK(assert_equal(Potentials::ADT({Parent}, \"0.6 0.4\"),\n                     (Potentials::ADT)*prior));\n  bayesNet.push_back(prior);\n\n  auto conditional =\n      boost::make_shared<DiscreteConditional>(Child | Parent = \"7/3 8/2\");\n  EXPECT_LONGS_EQUAL(1, *(conditional->beginFrontals()));\n  Potentials::ADT expected(Child & Parent, \"0.7 0.8 0.3 0.2\");\n  CHECK(assert_equal(expected, (Potentials::ADT)*conditional));\n  bayesNet.push_back(conditional);\n\n  DiscreteFactorGraph fg(bayesNet);\n  LONGS_EQUAL(2, fg.back()->size());\n\n  // Check the marginals\n  const double expectedMarginal[2]{0.4, 0.6 * 0.3 + 0.4 * 0.2};\n  DiscreteMarginals marginals(fg);\n  for (size_t j = 0; j < 2; j++) {\n    Vector FT = marginals.marginalProbabilities(DiscreteKey(j, 2));\n    EXPECT_DOUBLES_EQUAL(expectedMarginal[j], FT[1], 1e-3);\n    EXPECT_DOUBLES_EQUAL(FT[0], 1.0 - FT[1], 1e-9);\n  }\n}\n\n/* ************************************************************************* */\nTEST(DiscreteBayesNet, Asia) {\n  DiscreteBayesNet asia;\n  DiscreteKey Asia(0, 2), Smoking(4, 2), Tuberculosis(3, 2), LungCancer(6, 2),\n      Bronchitis(7, 2), Either(5, 2), XRay(2, 2), Dyspnea(1, 2);\n\n  asia.add(Asia % \"99/1\");\n  asia.add(Smoking % \"50/50\");\n\n  asia.add(Tuberculosis | Asia = \"99/1 95/5\");\n  asia.add(LungCancer | Smoking = \"99/1 90/10\");\n  asia.add(Bronchitis | Smoking = \"70/30 40/60\");\n\n  asia.add((Either | Tuberculosis, LungCancer) = \"F T T T\");\n\n  asia.add(XRay | Either = \"95/5 2/98\");\n  asia.add((Dyspnea | Either, Bronchitis) = \"9/1 2/8 3/7 1/9\");\n\n  // Convert to factor graph\n  DiscreteFactorGraph fg(asia);\n  LONGS_EQUAL(3, fg.back()->size());\n\n  // Check the marginals we know (of the parent-less nodes)\n  DiscreteMarginals marginals(fg);\n  Vector2 va(0.99, 0.01), vs(0.5, 0.5);\n  EXPECT(assert_equal(va, marginals.marginalProbabilities(Asia)));\n  EXPECT(assert_equal(vs, marginals.marginalProbabilities(Smoking)));\n\n  // Create solver and eliminate\n  Ordering ordering;\n  ordering += Key(0), Key(1), Key(2), Key(3), Key(4), Key(5), Key(6), Key(7);\n  DiscreteBayesNet::shared_ptr chordal = fg.eliminateSequential(ordering);\n  DiscreteConditional expected2(Bronchitis % \"11/9\");\n  EXPECT(assert_equal(expected2, *chordal->back()));\n\n  // solve\n  auto actualMPE = chordal->optimize();\n  DiscreteValues expectedMPE;\n  insert(expectedMPE)(Asia.first, 0)(Dyspnea.first, 0)(XRay.first, 0)(\n      Tuberculosis.first, 0)(Smoking.first, 0)(Either.first, 0)(\n      LungCancer.first, 0)(Bronchitis.first, 0);\n  EXPECT(assert_equal(expectedMPE, actualMPE));\n\n  // add evidence, we were in Asia and we have dyspnea\n  fg.add(Asia, \"0 1\");\n  fg.add(Dyspnea, \"0 1\");\n\n  // solve again, now with evidence\n  DiscreteBayesNet::shared_ptr chordal2 = fg.eliminateSequential(ordering);\n  auto actualMPE2 = chordal2->optimize();\n  DiscreteValues expectedMPE2;\n  insert(expectedMPE2)(Asia.first, 1)(Dyspnea.first, 1)(XRay.first, 0)(\n      Tuberculosis.first, 0)(Smoking.first, 1)(Either.first, 0)(\n      LungCancer.first, 0)(Bronchitis.first, 1);\n  EXPECT(assert_equal(expectedMPE2, actualMPE2));\n\n  // now sample from it\n  DiscreteValues expectedSample;\n  SETDEBUG(\"DiscreteConditional::sample\", false);\n  insert(expectedSample)(Asia.first, 1)(Dyspnea.first, 1)(XRay.first, 1)(\n      Tuberculosis.first, 0)(Smoking.first, 1)(Either.first, 1)(\n      LungCancer.first, 1)(Bronchitis.first, 0);\n  auto actualSample = chordal2->sample();\n  EXPECT(assert_equal(expectedSample, actualSample));\n}\n\n/* ************************************************************************* */\nTEST_UNSAFE(DiscreteBayesNet, Sugar) {\n  DiscreteKey T(0, 2), L(1, 2), E(2, 2), C(8, 3), S(7, 2);\n\n  DiscreteBayesNet bn;\n\n  // try logic\n  bn.add((E | T, L) = \"OR\");\n  bn.add((E | T, L) = \"AND\");\n\n  // try multivalued\n  bn.add(C % \"1/1/2\");\n  bn.add(C | S = \"1/1/2 5/2/3\");\n}\n\n/* ************************************************************************* */\nint main() {\n  TestResult tr;\n  return TestRegistry::runAllTests(tr);\n}\n/* ************************************************************************* */\n", "meta": {"hexsha": "cb50dd05f2bb230e4590527f2b99ca7b35a26f39", "size": 5270, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/discrete/tests/testDiscreteBayesNet.cpp", "max_stars_repo_name": "NaokiTakahashi12/gtsam", "max_stars_repo_head_hexsha": "0bab7b00c8c822b172e9d4d1cfa88ed471763e26", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gtsam/discrete/tests/testDiscreteBayesNet.cpp", "max_issues_repo_name": "NaokiTakahashi12/gtsam", "max_issues_repo_head_hexsha": "0bab7b00c8c822b172e9d4d1cfa88ed471763e26", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 22.0, "max_issues_repo_issues_event_min_datetime": "2022-02-08T18:34:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T16:14:32.000Z", "max_forks_repo_path": "gtsam/discrete/tests/testDiscreteBayesNet.cpp", "max_forks_repo_name": "NaokiTakahashi12/gtsam", "max_forks_repo_head_hexsha": "0bab7b00c8c822b172e9d4d1cfa88ed471763e26", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-14T10:10:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T10:10:40.000Z", "avg_line_length": 33.3544303797, "max_line_length": 80, "alphanum_fraction": 0.6130929791, "num_tokens": 1589, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.6859494678483918, "lm_q1q2_score": 0.4682110898874233}}
{"text": "#ifdef COMPILATION// -*-indent-tabs-mode:t;c-basic-offset:4;tab-width:4;autowrap:nil;-*-\n$CXX $0 -o $0x -lcudart  -lcufft `pkg-config --libs fftw3` -lboost_timer -lboost_unit_test_framework&&$0x&&rm $0x;exit\n#endif\n// \u00a9 Alfredo A. Correa 2020\n\n#ifndef MULTI_ADAPTORS_FFT_HPP\n#define MULTI_ADAPTORS_FFT_HPP\n\n#include \"../adaptors/fftw.hpp\"\n#include \"../adaptors/cufft.hpp\"\n\nnamespace boost{\nnamespace multi{\nnamespace fft{\n\n\tstatic constexpr int forward = fftw::forward;//FFTW_FORWARD;\n\tstatic constexpr int none = 0;\n\tstatic constexpr int backward = fftw::backward;//FFTW_BACKWARD;\n\n\tstatic_assert( forward != none and none != backward and backward != forward, \"!\");\n\n\ttemplate<std::size_t I> struct priority : std::conditional_t<I==0, std::true_type, struct priority<I-1>>{}; \n\t\n\ttemplate<class... Args> auto dft_aux_(priority<0>, Args&&... args) DECLRETURN(  fftw::dft(std::forward<Args>(args)...))\n\ttemplate<class... Args> auto dft_aux_(priority<1>, Args&&... args) DECLRETURN(cufft ::dft(std::forward<Args>(args)...))\n\ttemplate<class... Args> auto dft(Args&&... args) DECLRETURN(dft_aux_(priority<1>{}, std::forward<Args>(args)...))\n\n\ttemplate<class In, class... Args> auto dft(std::array<bool, std::decay_t<In>::dimensionality> which, In&& in, Args&&... args) DECLRETURN(dft_aux_(priority<1>{}, which, std::forward<In>(in), std::forward<Args>(args)...))\n\n\ttemplate<class... Args> auto many_dft_aux_(priority<0>, Args&&... args) DECLRETURN(  fftw::many_dft(std::forward<Args>(args)...))\n\ttemplate<class... Args> auto many_dft_aux_(priority<1>, Args&&... args) DECLRETURN(cufft ::many_dft(std::forward<Args>(args)...))\n\ttemplate<class... Args> auto many_dft(Args&&... args) DECLRETURN(many_dft_aux_(priority<1>{}, std::forward<Args>(args)...))\n\t\n\ttemplate<class... Args> auto dft_forward_aux_(priority<0>, Args&&... args) DECLRETURN(  fftw::dft_forward(std::forward<Args>(args)...))\n\ttemplate<class... Args> auto dft_forward_aux_(priority<1>, Args&&... args) DECLRETURN(cufft ::dft_forward(std::forward<Args>(args)...))\n\ttemplate<class... Args> auto dft_forward(Args&&... args) DECLRETURN(dft_forward_aux_(priority<1>{}, std::forward<Args>(args)...))\n\ttemplate<class In, class... Args> auto dft_forward(std::array<bool, std::decay_t<In>::dimensionality> which, In&& in, Args&&... args) DECLRETURN(dft_forward_aux_(priority<1>{}, which, std::forward<In>(in), std::forward<Args>(args)...))\n\n\ttemplate<class... Args> auto dft_backward_aux_(priority<0>, Args&&... args) DECLRETURN(  fftw::dft_backward(std::forward<Args>(args)...))\n\ttemplate<class... Args> auto dft_backward_aux_(priority<1>, Args&&... args) DECLRETURN(cufft ::dft_backward(std::forward<Args>(args)...))\n\ttemplate<class... Args> auto dft_backward(Args&&... args) DECLRETURN(dft_backward_aux_(priority<1>{}, std::forward<Args>(args)...))\n\ttemplate<class In, class... Args> auto dft_backward(std::array<bool, std::decay_t<In>::dimensionality> which, In&& in, Args&&... args) DECLRETURN(dft_backward_aux_(priority<1>{}, which, std::forward<In>(in), std::forward<Args>(args)...))\n\n}}}\n\n#if not __INCLUDE_LEVEL__\n\n#define BOOST_TEST_MODULE \"C++ Unit Tests for Multi FFT adaptor\"\n#define BOOST_TEST_DYN_LINK\n#include<boost/test/unit_test.hpp>\n\n#include <boost/timer/timer.hpp>\n#include <boost/config.hpp>\n\nnamespace utf = boost::unit_test;\n\nusing complex = std::complex<double>;\nnamespace multi = boost::multi;\n\nusing std::cout;\n\nBOOST_AUTO_TEST_CASE(fft_combinations, *utf::tolerance(0.00001)){\n\tcout<< \"# threads is \" << multi::fftw::plan::with_nthreads() <<\"\\n\";\n\tcout<<\"=========================================================\\n\";\n\tcout<< BOOST_PLATFORM <<' '<< BOOST_COMPILER <<' '<< __DATE__<<'\\n';\n\n\tauto const in = []{\n\t\tmulti::array<complex, 4> ret({32, 90, 98, 96});\n\t\tstd::generate(ret.data_elements(), ret.data_elements() + ret.num_elements(), \n\t\t\t[](){return complex{std::rand()/1./RAND_MAX, std::rand()/1./RAND_MAX};}\n\t\t);\n\t\treturn ret;\n\t}();\n\tstd::cout<<\"memory size \"<< in.num_elements()*sizeof(complex)/1e6 <<\" MB\\n\";\n\n\tmulti::cuda::array<complex, 4> const in_gpu = in;\n\tmulti::cuda::managed::array<complex, 4> const in_mng = in;\n\n\tstd::vector<std::array<bool, 4>> cases = {\n\t\t{false, true , true , true }, \n\t\t{false, true , true , false}, \n\t\t{true , false, false, false}, \n\t\t{true , true , false, false},\n\t\t{false, false, true , false},\n\t\t{false, false, false, false},\n\t};\n\n\tfor(auto c : cases){\n\t\tcout<<\"case: \"<<std::boolalpha; \n\t\tcopy(begin(c), end(c), std::ostream_iterator<bool>{cout,\", \"}); cout<<\"\\n\";\n\n\t\tmulti::array<complex, 4> out(extensions(in));\n\t\t{\n\t\t\tcout<<\"flops \"<< multi::fftw::plan(c, in, out, multi::fft::forward).flops() <<\"\\n\";\n\t\t\tboost::timer::auto_cpu_timer t{\"cpu____ %ws wall, CPU (%p%)\\n\"};\n\t\t\tmulti::fft::dft(c, in, out, multi::fft::forward);\n\t\t}\n\t\t{\n\t\t\tboost::timer::auto_cpu_timer t{\"cpu_hot %ws wall, CPU (%p%)\\n\"};\n\t\t\tmulti::fft::dft(c, in, out, multi::fft::forward);\n\t\t}\n\t\tmulti::cuda::array<complex, 4> out_gpu(extensions(in_gpu));\n\t\t{\n\t\t\tboost::timer::auto_cpu_timer t{\"gpu_cld %ws wall, CPU (%p%)\\n\"};\n\t\t\tmulti::fft::dft(c, in_gpu   , out_gpu   , multi::fft::forward);\n\t\t\tBOOST_TEST( abs( static_cast<complex>(out_gpu[5][4][3][1]) - out[5][4][3][1] ) == 0. );\n\t\t}\n\t\t{\n\t\t\tboost::timer::auto_cpu_timer t{\"gpu_hot %ws wall, CPU (%p%)\\n\"};\n\t\t\tmulti::fft::dft(c, in_gpu   , out_gpu   , multi::fft::forward);\n//\t\t\tBOOST_TEST( abs( static_cast<complex>(out_gpu[5][4][3][1]) - out[5][4][3][1] ) == 0. );\n\t\t}\n\t\tmulti::cuda::managed::array<complex, 4> out_mng(extensions(in_mng));\n\t\t{\n\t\t\tboost::timer::auto_cpu_timer t{\"mng_cld %ws wall, CPU (%p%)\\n\"};\n\t\t\tmulti::fft::dft(c, in_mng   , out_mng   , multi::fft::forward);\n\t\t\tcudaDeviceSynchronize();\n\t\t\tBOOST_TEST( abs( out_mng[5][4][3][1] - out[5][4][3][1] ) == 0. );\n\t\t}\n\t\t{\n\t\t///\tboost::timer::auto_cpu_timer t{\"mng_hot %ws wall, CPU (%p%)\\n\"};\n\t\t\tmulti::fft::dft(c, in_mng()   , out_mng()   , multi::fft::forward);\n\t\t\tcudaDeviceSynchronize();\n\t\t\tBOOST_TEST( abs( out_mng[5][4][3][1] - out[5][4][3][1] ) == 0. );\n\t\t}\n\t}\n\n}\n#endif\n#endif\n\n", "meta": {"hexsha": "c88b2b333de2d589dd02a5415ff25afcac8fa7fc", "size": 5993, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "adaptors/fft.hpp", "max_stars_repo_name": "correaa/b-multi", "max_stars_repo_head_hexsha": "1e961f877662aa7a26933834f9064d2ec8b00b4a", "max_stars_repo_licenses": ["Intel"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "adaptors/fft.hpp", "max_issues_repo_name": "correaa/b-multi", "max_issues_repo_head_hexsha": "1e961f877662aa7a26933834f9064d2ec8b00b4a", "max_issues_repo_licenses": ["Intel"], "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": "adaptors/fft.hpp", "max_forks_repo_name": "correaa/b-multi", "max_forks_repo_head_hexsha": "1e961f877662aa7a26933834f9064d2ec8b00b4a", "max_forks_repo_licenses": ["Intel"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.4015151515, "max_line_length": 238, "alphanum_fraction": 0.6544301685, "num_tokens": 1877, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737473266736, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.46821108559943997}}
{"text": "#include <fstream>\n#include <iostream>\n#include <string>\n#include <unordered_map>\n#include <boost/algorithm/string.hpp>\n#include <xtensor/xarray.hpp>\n#include <xtensor/xview.hpp>\n\nusing namespace std;\n\nclass Distributions {\n\tvector<string> keys;\n\tunordered_map<string, size_t> lookup;\n\txt::xarray<double> values;\n\n\tpublic:\n\t\tDistributions(istream& is) :keys{}, lookup{} {\n\t\t\tstring line;\n\t\t\tint i = 0;\n\t\t\tvector<xt::xarray<double>> tempVector;\n\t\t\twhile (getline(is, line)) {\n\t\t\t\tif (i == 0 || line.empty()) {\n\t\t\t\t\t++i;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tvector<string> elements;\n\t\t\t\tboost::split(elements, line, boost::is_any_of(\",\"));\n\t\t\t\tif (elements.size() < 2) {\n\t\t\t\t\tthrow runtime_error(\"Invalid distribution data\");\n\t\t\t\t}\n\t\t\t\tstring key = elements[0];\n\t\t\t\tkeys.push_back(key);\n\t\t\t\tlookup[key] = i-1;\n\n\t\t\t\txt::xarray<double> distribution = xt::zeros<double>({elements.size() - 1});\n\t\t\t\tfor (int k = 0; k < elements.size() - 1; ++k) {\n\t\t\t\t\tdistribution[k] = stod(elements[k+1]);\n\t\t\t\t}\n\t\t\t\ttempVector.push_back(distribution);\n\t\t\t\t++i;\n\t\t\t}\n\t\t\tif (tempVector.empty()) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tsize_t innerDim = tempVector[0].size();\n\t\t\tvalues = xt::zeros<double>({tempVector.size(), innerDim});\n\t\t\tfor (int j = 0; j < tempVector.size(); ++j) {\n\t\t\t\tfor (int l = 0; l < innerDim; ++l) {\n\t\t\t\t\tvalues(j, l) = tempVector[j][l];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\txt::xarray<double> operator[](const string& id) {\n\t\t\treturn xt::view(values, lookup[id]);\n\t\t}\n\n\t\tvector<string>& Keys() {\n\t\t\treturn keys;\n\t\t}\n\n\t\txt::xarray<double>& Values() {\n\t\t\treturn values;\n\t\t}\n\n\t\tsize_t size() {\n\t\t\treturn lookup.size();\n\t\t}\n};\n", "meta": {"hexsha": "542caa4064c20e688810529254737b94e209d145", "size": 1580, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/distribution/distribution.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/distribution/distribution.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/distribution/distribution.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": 22.2535211268, "max_line_length": 79, "alphanum_fraction": 0.603164557, "num_tokens": 465, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.685949467848392, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.4682110854581278}}
{"text": "/*\n [auto_generated]\n boost/numeric/odeint/stepper/symplectic_euler.hpp\n\n [begin_description]\n Implementation of the symplectic Euler for separable Hamiltonian systems.\n [end_description]\n\n Copyright 2009-2011 Karsten Ahnert\n Copyright 2009-2011 Mario Mulansky\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_SYMPLECTIC_EULER_HPP_INCLUDED\n#define BOOST_NUMERIC_ODEINT_STEPPER_SYMPLECTIC_EULER_HPP_INCLUDED\n\n\n#include <boost/numeric/odeint/stepper/base/symplectic_rkn_stepper_base.hpp>\n\n#include <boost/numeric/odeint/algebra/range_algebra.hpp>\n#include <boost/numeric/odeint/algebra/default_operations.hpp>\n\n#include <boost/array.hpp>\n\nnamespace boost {\nnamespace numeric {\nnamespace odeint {\n\n\n#ifndef DOXYGEN_SKIP\nnamespace detail {\nnamespace symplectic_euler_coef {\n\ntemplate< class Value >\nstruct coef_a_type : public boost::array< Value , 1 >\n{\n    coef_a_type( void )\n    {\n        (*this)[0] = static_cast< Value >( 1 );\n    }\n};\n\ntemplate< class Value >\nstruct coef_b_type : public boost::array< Value , 1 >\n{\n    coef_b_type( void )\n    {\n        (*this)[0] = static_cast< Value >( 1 );\n    }\n};\n\n} // namespace symplectic_euler_coef\n} // namespace detail\n#endif\n\n\n\ntemplate<\nclass Coor ,\nclass Momentum = Coor ,\nclass Value = double ,\nclass CoorDeriv = Coor ,\nclass MomentumDeriv = Coor ,\nclass Time = Value ,\nclass Algebra = range_algebra ,\nclass Operations = default_operations ,\nclass Resizer = initially_resizer\n>\n#ifndef DOXYGEN_SKIP\nclass symplectic_euler :\npublic symplectic_nystroem_stepper_base\n<\n1 , 1 ,\nCoor , Momentum , Value , CoorDeriv , MomentumDeriv , Time , Algebra , Operations , Resizer\n>\n#else\nclass symplectic_euler : public symplectic_nystroem_stepper_base\n#endif\n{\npublic:\n\n#ifndef DOXYGEN_SKIP\n    typedef symplectic_nystroem_stepper_base<\n    1 , 1 , Coor , Momentum , Value , CoorDeriv , MomentumDeriv , Time , Algebra , Operations , Resizer > stepper_base_type;\n#endif\n    typedef typename stepper_base_type::algebra_type algebra_type;\n    typedef typename stepper_base_type::value_type value_type;\n\n\n    symplectic_euler( const algebra_type &algebra = algebra_type() )\n    : stepper_base_type( detail::symplectic_euler_coef::coef_a_type< value_type >() ,\n            detail::symplectic_euler_coef::coef_b_type< value_type >() ,\n            algebra )\n    { }\n};\n\n\n/*************** DOXYGEN ***************/\n\n/**\n * \\class symplectic_euler\n * \\brief Implementation of the symplectic Euler method.\n *\n * The method is of first order and has one stage. It is described HERE.\n *\n * \\tparam Order The order of the stepper.\n * \\tparam Coor The type representing the coordinates q.\n * \\tparam Momentum The type representing the coordinates p.\n * \\tparam Value The basic value type. Should be somethink like float, double or a high-precision type.\n * \\tparam CoorDeriv The type representing the time derivative of the coordinate dq/dt.\n * \\tparam MomemtnumDeriv The type representing the time derivative of the momentum dp/dt.\n * \\tparam Time The type representing the time t.\n * \\tparam Algebra The algebra.\n * \\tparam Operations The operations.\n * \\tparam Resizer The resizer policy.\n */\n\n    /**\n     * \\fn symplectic_euler::symplectic_euler( const algebra_type &algebra )\n     * \\brief Constructs the symplectic_euler. 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} // namespace odeint\n} // namespace numeric\n} // namespace boost\n\n\n#endif // BOOST_NUMERIC_ODEINT_STEPPER_SYMPLECTIC_EULER_HPP_INCLUDED\n", "meta": {"hexsha": "0e8cf55ab8e74d0c7b9299a0e1dcd39ffd687d8b", "size": 3735, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/odeint/stepper/symplectic_euler.hpp", "max_stars_repo_name": "datacratic/boost-svn", "max_stars_repo_head_hexsha": "fcfba33e940cdb150b18d1d03821dcb30af52a94", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-17T18:18:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-17T18:18:10.000Z", "max_issues_repo_path": "boost/numeric/odeint/stepper/symplectic_euler.hpp", "max_issues_repo_name": "datacratic/boost-svn", "max_issues_repo_head_hexsha": "fcfba33e940cdb150b18d1d03821dcb30af52a94", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "boost/numeric/odeint/stepper/symplectic_euler.hpp", "max_forks_repo_name": "datacratic/boost-svn", "max_forks_repo_head_hexsha": "fcfba33e940cdb150b18d1d03821dcb30af52a94", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6666666667, "max_line_length": 124, "alphanum_fraction": 0.7416331995, "num_tokens": 935, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737214979745, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.46821107664664074}}
{"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\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include <iostream>\n#include <cmath>\n#include <boost/numeric/mtl/concept/collection.hpp>\n#include <boost/numeric/mtl/vector/dense_vector.hpp>\n#include <boost/numeric/mtl/vector/parameter.hpp>\n#include <boost/numeric/mtl/operation/operators.hpp>\n#include <boost/numeric/mtl/operation/min.hpp>\n#include <boost/numeric/mtl/operation/max.hpp>\n\n\n\nusing namespace std;  \n    \n\ntemplate <typename Vector>\nvoid test(Vector& v, const char* name)\n{\n    typedef typename mtl::Collection<Vector>::value_type value_type;\n    using mtl::min; using mtl::max; \n\n    for (unsigned i= 0; i < size(v); i++)\n\tv[i]= value_type(double(i+1) * pow(-1.0, int(i))); // Amb. in MSVC \n\n    std::cout << \"\\n\" << name << \"  --- v = \" << v; std::cout.flush();\n\n    std::cout << \"min(v) = \" << min(v) << \"\\n\"; std::cout.flush();\n    MTL_THROW_IF(min(v) != -4.0, mtl::runtime_error(\"min wrong\"));\n\n    std::cout << \"min<4>(v) = \" << min<4>(v) << \"\\n\"; std::cout.flush();\n    MTL_THROW_IF(min<4>(v) != -4.0, mtl::runtime_error(\"min<4> wrong\"));\n\n    std::cout << \"max(v) = \" << max(v) << \"\\n\"; std::cout.flush();\n    MTL_THROW_IF(max(v) != 5.0, mtl::runtime_error(\"max wrong\"));\n}\n \n\nint main(int, char**)\n{\n    mtl::dense_vector<float>   u(5);\n    mtl::dense_vector<double>  x(5);\n\n    std::cout << \"Testing vector operations\\n\";\n\n    test(u, \"test float\");\n    test(x, \"test double\");\n\n    mtl::dense_vector<float, mtl::vec::parameters<mtl::row_major> >   ur(5);\n    test(ur, \"test float in row vector\");\n\n    return 0;\n}\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "10b1d552089bf4b7d118b1ff99481f74961c4e02", "size": 1950, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/vector_min_max_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/vector_min_max_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/vector_min_max_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": 24.6835443038, "max_line_length": 94, "alphanum_fraction": 0.6282051282, "num_tokens": 578, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494421679929, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.46821106792936207}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// QuickBook Example\n\n// Copyright (c) 2014, Oracle and/or its affiliates\n\n// Contributed and/or modified by Menelaos Karavelas, on behalf of Oracle\n\n// Licensed under the Boost Software License version 1.0.\n// http://www.boost.org/users/license.html\n\n//[is_simple\n//` Checks whether a geometry is simple\n\n#include <iostream>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/linestring.hpp>\n#include <boost/geometry/geometries/multi_linestring.hpp>\n/*<-*/ #include \"create_svg_one.hpp\" /*->*/\n\nint main()\n{\n    typedef boost::geometry::model::d2::point_xy<double> point_type;\n    typedef boost::geometry::model::linestring<point_type> linestring_type;\n    typedef boost::geometry::model::multi_linestring<linestring_type> multi_linestring_type;\n\n    multi_linestring_type multi_linestring;\n    boost::geometry::read_wkt(\"MULTILINESTRING((0 0,0 10,10 10,10 0,0 0),(10 10,20 20))\", multi_linestring);\n\n    std::cout << \"is simple? \"\n              << (boost::geometry::is_simple(multi_linestring) ? \"yes\" : \"no\")\n              << std::endl;\n    /*<-*/ create_svg(\"is_simple_example.svg\", multi_linestring); /*->*/\n    return 0;\n}\n\n//]\n\n//[is_simple_output\n/*`\nOutput:\n[pre\nis simple? no\n\n[$img/algorithms/is_simple_example.png]\n\n]\n\n*/\n//]\n", "meta": {"hexsha": "8255b5f1a48638e7ec7ae804edbb93728597225f", "size": 1358, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/doc/src/examples/algorithms/is_simple.cpp", "max_stars_repo_name": "Manu343726/boost-cmake", "max_stars_repo_head_hexsha": "009c3843b49a56880d988ffdca6d909f881edb3d", "max_stars_repo_licenses": ["BSL-1.0"], "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": "libs/geometry/doc/src/examples/algorithms/is_simple.cpp", "max_issues_repo_name": "Manu343726/boost-cmake", "max_issues_repo_head_hexsha": "009c3843b49a56880d988ffdca6d909f881edb3d", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 623.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T23:45:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T11:15:23.000Z", "max_forks_repo_path": "libs/geometry/doc/src/examples/algorithms/is_simple.cpp", "max_forks_repo_name": "Manu343726/boost-cmake", "max_forks_repo_head_hexsha": "009c3843b49a56880d988ffdca6d909f881edb3d", "max_forks_repo_licenses": ["BSL-1.0"], "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": 26.1153846154, "max_line_length": 108, "alphanum_fraction": 0.7039764359, "num_tokens": 363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6791786991753931, "lm_q2_score": 0.6893056231680121, "lm_q1q2_score": 0.4681616964775342}}
{"text": "#pragma once\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n\nnamespace mtao::eigen {\n\n    template <typename T>\n        constexpr bool is_sparse() {\n            return std::is_base_of_v<\n                Eigen::SparseMatrixBase<T>,T\n                >;\n        }\n    template <typename T>\n        constexpr bool is_matrix() {\n            return std::is_base_of_v<\n                Eigen::MatrixBase<T>,T\n                >;\n        }\n    template <typename T>\n        constexpr bool is_array() {\n            return std::is_base_of_v<\n                Eigen::ArrayBase<T>,T\n                >;\n        }\n    template <typename T>\n        constexpr bool is_row_major() {\n            return T::Options & Eigen::RowMajor;\n        }\n    template <typename T>\n        constexpr bool is_col_major() {\n            return T::Options & Eigen::ColMajor;\n        }\n    template <typename T>\n        constexpr bool is_sparse(const T& A) {\n            return is_sparse<T>();\n        }\n    template <typename T>\n        constexpr bool is_matrix(const T& A) {\n            return is_matrix<T>();\n        }\n    template <typename T>\n        constexpr bool is_array(const T& A) {\n            return is_array<T>();\n        }\n    template <typename T>\n        constexpr bool is_row_major(const T& A) {\n            return is_row_major<T>();\n        }\n    template <typename T>\n        constexpr bool is_col_major(const T& A) {\n            return is_col_major<T>();\n        }\n}\n", "meta": {"hexsha": "d24e5e87f0da6d94dfdaca8ef62390e332a76645", "size": 1448, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mtao/eigen/type_info.hpp", "max_stars_repo_name": "mtao/core", "max_stars_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_stars_repo_licenses": ["MIT"], "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/mtao/eigen/type_info.hpp", "max_issues_repo_name": "mtao/core", "max_issues_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-04-18T16:16:05.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-18T16:17:36.000Z", "max_forks_repo_path": "include/mtao/eigen/type_info.hpp", "max_forks_repo_name": "mtao/core", "max_forks_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_forks_repo_licenses": ["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.8148148148, "max_line_length": 49, "alphanum_fraction": 0.5214088398, "num_tokens": 315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056040203135, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.4681616924252185}}
{"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\n#include <nt2/hyperbolic/include/functions/sinhcosh.hpp>\n#include <nt2/exponential/constants.hpp>\n#include <nt2/sdk/functor/meta/call.hpp>\n#include <nt2/sdk/unit/tests/ulp.hpp>\n#include <nt2/sdk/unit/tests/type_expr.hpp>\n#include <nt2/sdk/unit/module.hpp>\n\n\n#include <nt2/include/functions/sinh.hpp>\n#include <nt2/include/functions/cosh.hpp>\n#include <nt2/include/functions/tie.hpp>\n#include <nt2/include/constants/zero.hpp>\n#include <nt2/include/constants/one.hpp>\n#include <nt2/include/constants/inf.hpp>\n#include <nt2/include/constants/minf.hpp>\n#include <nt2/include/constants/nan.hpp>\n#include <boost/fusion/include/vector_tie.hpp>\n\nNT2_TEST_CASE_TPL(sinhcosh, NT2_REAL_TYPES)\n{\n  using nt2::sinhcosh;\n  using nt2::tag::sinhcosh_;\n  T a[] = {nt2::Zero<T>(), nt2::One<T>(), T(5), T(-5)};\n  size_t N =  sizeof(a)/sizeof(T);\n  NT2_TEST_TYPE_IS( (typename boost::dispatch::meta::call<sinhcosh_(T)>::type)\n                  , (std::pair<T,T>)\n                  );\n\n  {\n    T s, c;\n    for(size_t i=0; i < N; ++i)\n    {\n      sinhcosh(a[i], s, c);\n      NT2_TEST_ULP_EQUAL(s, nt2::sinh(a[i]), 1);\n      NT2_TEST_ULP_EQUAL(c, nt2::cosh(a[i]), 1);\n    }\n  }\n\n  {\n    T s, c;\n    for(size_t i=0; i < N; ++i)\n    {\n      s = sinhcosh(a[i], c);\n      NT2_TEST_ULP_EQUAL(s, nt2::sinh(a[i]), 1);\n      NT2_TEST_ULP_EQUAL(c, nt2::cosh(a[i]), 1);\n    }\n  }\n\n  {\n    T s, c;\n    for(size_t i=0; i < N; ++i)\n    {\n      boost::fusion::vector_tie(s, c) = sinhcosh(a[i]);\n      NT2_TEST_ULP_EQUAL(s, nt2::sinh(a[i]), 1);\n      NT2_TEST_ULP_EQUAL(c, nt2::cosh(a[i]), 1);\n    }\n  }\n\n  {\n    for(size_t i=0; i < N; ++i)\n    {\n      std::pair<T,T> p = sinhcosh(a[i]);\n      NT2_TEST_ULP_EQUAL(p.first,  nt2::sinh(a[i]), 1);\n      NT2_TEST_ULP_EQUAL(p.second, nt2::cosh(a[i]), 1);\n    }\n  }\n\n  T b[] = {nt2::Inf<T>(), nt2::Minf<T>(), nt2::Nan<T>()};\n  N =  sizeof(b)/sizeof(T);\n#ifndef BOOST_SIMD_NO_INVALIDS\n\n  {\n    T s, c;\n    for(size_t i=0; i < N; ++i)\n    {\n      sinhcosh(b[i], s, c);\n      NT2_TEST_ULP_EQUAL(s, nt2::sinh(b[i]), 1);\n      NT2_TEST_ULP_EQUAL(c, nt2::cosh(b[i]), 1);\n    }\n  }\n\n  {\n    T s, c;\n    for(size_t i=0; i < N; ++i)\n    {\n      s = sinhcosh(b[i], c);\n      NT2_TEST_ULP_EQUAL(s, nt2::sinh(b[i]), 1);\n      NT2_TEST_ULP_EQUAL(c, nt2::cosh(b[i]), 1);\n    }\n  }\n\n  {\n    T s, c;\n    for(size_t i=0; i < N; ++i)\n    {\n      boost::fusion::vector_tie(s, c) = sinhcosh(b[i]);\n      NT2_TEST_ULP_EQUAL(s, nt2::sinh(b[i]), 1);\n      NT2_TEST_ULP_EQUAL(c, nt2::cosh(b[i]), 1);\n    }\n  }\n\n  {\n    for(size_t i=0; i < N; ++i)\n    {\n      std::pair<T,T> p = sinhcosh(b[i]);\n      NT2_TEST_ULP_EQUAL(p.first,  nt2::sinh(b[i]), 1);\n      NT2_TEST_ULP_EQUAL(p.second, nt2::cosh(b[i]), 1);\n    }\n  }\n#endif\n}\n", "meta": {"hexsha": "b1e4af6fe794632a5bb55275247f4343f400ec35", "size": 3216, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/core/hyperbolic/unit/scalar/sinhcosh.cpp", "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/hyperbolic/unit/scalar/sinhcosh.cpp", "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/hyperbolic/unit/scalar/sinhcosh.cpp", "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": 26.5785123967, "max_line_length": 80, "alphanum_fraction": 0.5382462687, "num_tokens": 1080, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6791786991753931, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.4681616921426312}}
{"text": "//\n// A demo program of reordering using Rabbit Order.\n//\n// Author: ARAI Junya <arai.junya@lab.ntt.co.jp> <araijn@gmail.com>\n//\n\n#include <boost/range/adaptor/transformed.hpp>\n#include <boost/range/algorithm/count.hpp>\n\n#include \"../rabbit_order.hpp\"\n#include \"edge_list.hpp\"\n#include <utils/yche_serialization.h>\n\nusing rabbit_order::vint;\ntypedef std::vector<std::vector<std::pair<vint, float> > > adjacency_list;\n\nstring g_path_dir;\n\nvint count_unused_id(const vint n, const std::vector<edge_list::edge> &edges) {\n    std::vector<char> appears(n);\n    for (size_t i = 0; i < edges.size(); ++i) {\n        appears[std::get<0>(edges[i])] = true;\n        appears[std::get<1>(edges[i])] = true;\n    }\n    return static_cast<vint>(boost::count(appears, false));\n}\n\n\nvint count_unused_id_unweighted(const vint n, const std::vector<edge_list::aux::unweighted_edge> &edges) {\n    std::vector<char> appears(n);\n    for (size_t i = 0; i < edges.size(); ++i) {\n        appears[std::get<0>(edges[i])] = true;\n        appears[std::get<1>(edges[i])] = true;\n    }\n    return static_cast<vint>(boost::count(appears, false));\n}\n\ntemplate<typename RandomAccessRange>\nadjacency_list make_adj_list(const vint n, const RandomAccessRange &es) {\n    using std::get;\n\n    // Symmetrize the edge list and remove self-loops simultaneously\n    std::vector<edge_list::aux::edge> ss(boost::size(es) * 2);\n#pragma omp parallel for\n    for (size_t i = 0; i < boost::size(es); ++i) {\n        auto &e = es[i];\n        if (get<0>(e) != get<1>(e)) {\n            ss[i * 2] = std::make_tuple(get<0>(e), get<1>(e), 1.0f);\n            ss[i * 2 + 1] = std::make_tuple(get<1>(e), get<0>(e), 1.0f);\n        } else {\n            // Insert zero-weight edges instead of loops; they are ignored in making\n            // an adjacency list\n            ss[i * 2] = std::make_tuple(0, 0, 0.0f);\n            ss[i * 2 + 1] = std::make_tuple(0, 0, 0.0f);\n        }\n    }\n\n    // Sort the edges\n    __gnu_parallel::sort(ss.begin(), ss.end());\n\n    // Convert to an adjacency list\n    adjacency_list adj(n);\n#pragma omp parallel\n    {\n        // Advance iterators to a boundary of a source vertex\n        const auto adv = [](auto it, const auto first, const auto last) {\n            while (first != it && it != last && get<0>(*(it - 1)) == get<0>(*it))\n                ++it;\n            return it;\n        };\n\n        // Compute an iterator range assigned to this thread\n        const int p = omp_get_max_threads();\n        const size_t t = static_cast<size_t>(omp_get_thread_num());\n        const size_t ifirst = ss.size() / p * (t) + std::min(t, ss.size() % p);\n        const size_t ilast = ss.size() / p * (t + 1) + std::min(t + 1, ss.size() % p);\n        auto it = adv(ss.begin() + ifirst, ss.begin(), ss.end());\n        const auto last = adv(ss.begin() + ilast, ss.begin(), ss.end());\n\n        // Reduce edges and store them in std::vector\n        while (it != last) {\n            const vint s = get<0>(*it);\n\n            // Obtain an upper bound of degree and reserve memory\n            const auto maxdeg =\n                    std::find_if(it, last, [s](auto &x) { return get<0>(x) != s; }) - it;\n            adj[s].reserve(maxdeg);\n\n            while (it != last && get<0>(*it) == s) {\n                const vint t = get<1>(*it);\n                float w = 0.0;\n                while (it != last && get<0>(*it) == s && get<1>(*it) == t)\n                    w += get<2>(*it++);\n                if (w > 0.0)\n                    adj[s].push_back({t, w});\n            }\n\n            // The actual degree can be smaller than the upper bound\n            adj[s].shrink_to_fit();\n        }\n    }\n\n    return adj;\n}\n\nadjacency_list read_graph(const std::string &graphpath) {\n//    const auto edges = edge_list::read(graphpath);\n    FILE *pFile = fopen(graphpath.c_str(), \"r\");\n    YcheSerializer serializer;\n    vector<tuple<vint, vint >> edges;\n    serializer.read_array(pFile, edges);\n    fclose(pFile);\n\n    // The number of vertices = max vertex ID + 1 (assuming IDs start from zero)\n    const auto n =\n            boost::accumulate(edges, static_cast<vint>(0), [](vint s, auto &e) {\n                return std::max(s, std::max(std::get<0>(e), std::get<1>(e)) + 1);\n            });\n\n    if (const size_t c = count_unused_id_unweighted(n, edges)) {\n        std::cerr << \"WARNING: \" << c << \"/\" << n << \" vertex IDs are unused\"\n                  << \" (zero-degree vertices or noncontiguous IDs?)\\n\";\n    }\n\n    return make_adj_list(n, edges);\n}\n\ntemplate<typename InputIt>\ntypename std::iterator_traits<InputIt>::difference_type\ncount_uniq(const InputIt f, const InputIt l) {\n    std::vector<typename std::iterator_traits<InputIt>::value_type> ys(f, l);\n    return boost::size(boost::unique(boost::sort(ys)));\n}\n\ndouble compute_modularity(const adjacency_list &adj, const vint *const coms) {\n    const vint n = static_cast<vint>(adj.size());\n    const auto ncom = count_uniq(coms, coms + n);\n    double m2 = 0.0;  // total weight of the (bidirectional) edges\n\n    std::unordered_map<vint, double[2]> degs(ncom);  // ID -> {all, loop}\n    degs.reserve(ncom);\n\n#pragma omp parallel reduction(+:m2)\n    {\n        std::unordered_map<vint, double[2]> mydegs(ncom);\n        mydegs.reserve(ncom);\n\n#pragma omp for\n        for (vint v = 0; v < n; ++v) {\n            const vint c = coms[v];\n            auto *const d = &mydegs[c];\n            for (const auto e : adj[v]) {\n                m2 += e.second;\n                (*d)[0] += e.second;\n                if (coms[e.first] == c) (*d)[1] += e.second;\n            }\n        }\n\n#pragma omp critical\n        {\n            for (auto &kv : mydegs) {\n                auto *const d = &degs[kv.first];\n                (*d)[0] += kv.second[0];\n                (*d)[1] += kv.second[1];\n            }\n        }\n    }\n    assert(static_cast<intmax_t>(degs.size()) == ncom);\n\n    double q = 0.0;\n    for (auto &kv : degs) {\n        const double all = kv.second[0];\n        const double loop = kv.second[1];\n        q += loop / m2 - (all / m2) * (all / m2);\n    }\n\n    return q;\n}\n\nvoid detect_community(adjacency_list adj) {\n    auto _adj = adj;  // copy `adj` because it is used for computing modularity\n\n    std::cerr << \"Detecting communities...\\n\";\n    const double tstart = rabbit_order::now_sec();\n    //--------------------------------------------\n    auto g = rabbit_order::aggregate(std::move(_adj));\n    const auto c = std::make_unique<vint[]>(g.n());\n#pragma omp parallel for\n    for (vint v = 0; v < g.n(); ++v)\n        c[v] = rabbit_order::trace_com(v, &g);\n    //--------------------------------------------\n    std::cerr << \"Runtime for community detection [sec]: \"\n              << rabbit_order::now_sec() - tstart << std::endl;\n\n    // Print the result\n    std::copy(&c[0], &c[g.n()], std::ostream_iterator<vint>(std::cout, \"\\n\"));\n\n    std::cerr << \"Computing modularity of the result...\\n\";\n    const double q = compute_modularity(adj, c.get());\n    std::cerr << \"Modularity: \" << q << std::endl;\n}\n\nvoid reorder(adjacency_list adj) {\n    std::cerr << \"Generating a permutation...\\n\";\n    const double tstart = rabbit_order::now_sec();\n    //--------------------------------------------\n    const auto g = rabbit_order::aggregate(std::move(adj));\n    const auto p = rabbit_order::compute_perm(g);\n    //--------------------------------------------\n    std::cerr << \"Runtime for permutation generation [sec]: \"\n              << rabbit_order::now_sec() - tstart << std::endl;\n\n    // Print the result\n    std::copy(&p[0], &p[g.n()], std::ostream_iterator<vint>(std::cout, \"\\n\"));\n\n    // save the binary dictionary to file here\n    // output using ycheserializer\n    string my_path = g_path_dir + \"/\" + \"rabbit_order.dict\";\n    cout << my_path << endl;\n    FILE *pFile = fopen(my_path.c_str(), \"wb\");\n    YcheSerializer serializer;\n    serializer.write_array(pFile, p.get(), g.n());\n\n    // flush and close the file handle\n    fflush(pFile);\n    fclose(pFile);\n}\n\nint main(int argc, char *argv[]) {\n    using boost::adaptors::transformed;\n\n    // Parse command-line arguments\n    if (argc != 2 && (argc != 3 || std::string(\"-c\") != argv[1])) {\n        std::cerr << \"Usage: reorder [-c] GRAPH_FILE\\n\"\n                  << \"  -c    Print community IDs instead of a new ordering\\n\";\n        exit(EXIT_FAILURE);\n    }\n    const std::string graphpath = argc == 3 ? argv[2] : argv[1];\n\n    string tmp = graphpath;\n    auto upper_bound = tmp.find_last_of('/');\n    g_path_dir = tmp.substr(0, upper_bound);\n\n    const bool commode = argc == 3;\n\n    std::cerr << \"Number of threads: \" << omp_get_max_threads() << std::endl;\n\n    std::cerr << \"Reading an edge-list file: \" << graphpath << std::endl;\n    auto adj = read_graph(graphpath);\n    const auto m =\n            boost::accumulate(adj | transformed([](auto &es) { return es.size(); }),\n                              static_cast<size_t>(0));\n    std::cerr << \"Number of vertices: \" << adj.size() << std::endl;\n    std::cerr << \"Number of edges: \" << m << std::endl;\n\n    if (commode)\n        detect_community(std::move(adj));\n    else\n        reorder(std::move(adj));\n\n    return EXIT_SUCCESS;\n}\n\n", "meta": {"hexsha": "5bae2259921f83df4ee0ff39b19b52ec52304b85", "size": 9137, "ext": "cc", "lang": "C++", "max_stars_repo_path": "graph-reordering/reordering/other-reorderings/rabbit_order/demo/reorder.cc", "max_stars_repo_name": "HackerFoo/GraphReorderAndConverter", "max_stars_repo_head_hexsha": "58248a0c23f4ed8b52a0b47178b021126b6b33f5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-07-28T14:35:00.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-30T12:35:39.000Z", "max_issues_repo_path": "graph-reordering/reordering/other-reorderings/rabbit_order/demo/reorder.cc", "max_issues_repo_name": "HackerFoo/GraphReorderAndConverter", "max_issues_repo_head_hexsha": "58248a0c23f4ed8b52a0b47178b021126b6b33f5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-04-11T17:24:22.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-30T14:38:06.000Z", "max_forks_repo_path": "graph-reordering/reordering/other-reorderings/rabbit_order/demo/reorder.cc", "max_forks_repo_name": "HackerFoo/GraphReorderAndConverter", "max_forks_repo_head_hexsha": "58248a0c23f4ed8b52a0b47178b021126b6b33f5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-21T22:44:03.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-21T22:44:03.000Z", "avg_line_length": 34.6098484848, "max_line_length": 106, "alphanum_fraction": 0.5525883769, "num_tokens": 2486, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056040203135, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.46816167899662825}}
{"text": "#include <stan/math/rev/mat.hpp>\n#include <gtest/gtest.h>\n#include <test/unit/math/rev/mat/fun/util.hpp>\n#include <test/unit/math/rev/mat/util.hpp>\n#ifdef STAN_OPENCL\n#include <boost/random/mersenne_twister.hpp>\n#endif\n// multiply operates on two matrices A X B\n// A (n, m)\n// B (m, k)\n// If stacked col-wise like vec operator\n// first n*m elements are for A\n// second m*k elements starting with n*m + 1-th element (indexed by\n// n*m (remember !)\ntemplate <int R_A, int C_A, int C_B>\nclass mult_vv {\n  int i, j, N, M, K;\n\n public:\n  mult_vv(int i_, int j_, int N_, int M_, int K_)\n      : i(i_), j(j_), N(N_), M(M_), K(K_) {}\n  template <typename T>\n  T operator()(Eigen::Matrix<T, -1, 1> x) const {\n    using stan::math::multiply;\n    Eigen::Matrix<T, R_A, C_A> A_c(N, M);\n    Eigen::Matrix<T, C_A, C_B> B_c(M, K);\n    int pos = 0;\n    // traverse col-major\n    for (int m = 0; m < M; ++m)\n      for (int n = 0; n < N; ++n)\n        A_c(n, m) = x(pos++);\n\n    for (int k = 0; k < K; ++k)\n      for (int m = 0; m < M; ++m)\n        B_c(m, k) = x(pos++);\n\n    Eigen::Matrix<T, R_A, C_B> AB_c = multiply(A_c, B_c);\n    return AB_c(i, j);\n  }\n};\n\ntemplate <>\nclass mult_vv<1, -1, 1> {\n  int N, M, K;\n\n public:\n  mult_vv(int N_, int M_, int K_) : N(N_), M(M_), K(K_) {}\n  template <typename T>\n  T operator()(Eigen::Matrix<T, -1, 1> x) const {\n    using stan::math::multiply;\n    Eigen::Matrix<T, 1, -1> A_c(N, M);\n    Eigen::Matrix<T, -1, 1> B_c(M, K);\n    int pos = 0;\n    // traverse col-major\n    for (int m = 0; m < M; ++m)\n      for (int n = 0; n < N; ++n)\n        A_c(n, m) = x(pos++);\n\n    for (int k = 0; k < K; ++k)\n      for (int m = 0; m < M; ++m)\n        B_c(m, k) = x(pos++);\n\n    T AB_c = multiply(A_c, B_c);\n    return AB_c;\n  }\n};\n\ntemplate <int R_A, int C_A, int C_B>\nclass mult_dv {\n  int i, j, M, K;\n  Eigen::Matrix<double, R_A, C_A> A_c;\n\n public:\n  mult_dv(int i_, int j_, int M_, int K_, Eigen::Matrix<double, R_A, C_A> A_c_)\n      : i(i_), j(j_), M(M_), K(K_), A_c(A_c_) {}\n  template <typename T>\n  T operator()(Eigen::Matrix<T, -1, 1> x) const {\n    using stan::math::multiply;\n    Eigen::Matrix<T, C_A, C_B> B_c(M, K);\n    int pos = 0;\n    // traverse col-major\n\n    for (int k = 0; k < K; ++k)\n      for (int m = 0; m < M; ++m)\n        B_c(m, k) = x(pos++);\n\n    Eigen::Matrix<T, R_A, C_B> AB_c = multiply(A_c, B_c);\n    return AB_c(i, j);\n  }\n};\n\ntemplate <>\nclass mult_dv<1, -1, 1> {\n  int M, K;\n  Eigen::Matrix<double, 1, -1> A_c;\n\n public:\n  mult_dv(int M_, int K_, Eigen::Matrix<double, 1, -1> A_c_)\n      : M(M_), K(K_), A_c(A_c_) {}\n  template <typename T>\n  T operator()(Eigen::Matrix<T, -1, 1> x) const {\n    using stan::math::multiply;\n    Eigen::Matrix<T, -1, 1> B_c(M, K);\n    int pos = 0;\n    // traverse col-major\n\n    for (int k = 0; k < K; ++k)\n      for (int m = 0; m < M; ++m)\n        B_c(m, k) = x(pos++);\n\n    T AB_c = multiply(A_c, B_c);\n    return AB_c;\n  }\n};\n\ntemplate <int R_A, int C_A, int C_B>\nclass mult_vd {\n  int i, j, N, M;\n  Eigen::Matrix<double, C_A, C_B> B_c;\n\n public:\n  mult_vd(int i_, int j_, int N_, int M_, Eigen::Matrix<double, C_A, C_B> B_c_)\n      : i(i_), j(j_), N(N_), M(M_), B_c(B_c_) {}\n  template <typename T>\n  T operator()(Eigen::Matrix<T, -1, 1> x) const {\n    using stan::math::multiply;\n    Eigen::Matrix<T, R_A, C_A> A_c(N, M);\n    int pos = 0;\n    // traverse col-major\n    for (int m = 0; m < M; ++m)\n      for (int n = 0; n < N; ++n)\n        A_c(n, m) = x(pos++);\n\n    Eigen::Matrix<T, -1, -1> AB_c = multiply(A_c, B_c);\n    return AB_c(i, j);\n  }\n};\n\ntemplate <>\nclass mult_vd<1, -1, 1> {\n  int N, M;\n  Eigen::Matrix<double, -1, 1> B_c;\n\n public:\n  mult_vd(int N_, int M_, Eigen::Matrix<double, -1, 1> B_c_)\n      : N(N_), M(M_), B_c(B_c_) {}\n  template <typename T>\n  T operator()(Eigen::Matrix<T, -1, 1> x) const {\n    using stan::math::multiply;\n    Eigen::Matrix<T, 1, -1> A_c(N, M);\n    int pos = 0;\n    // traverse col-major\n    for (int m = 0; m < M; ++m)\n      for (int n = 0; n < N; ++n)\n        A_c(n, m) = x(pos++);\n\n    T AB_c = multiply(A_c, B_c);\n    return AB_c;\n  }\n};\n\nEigen::Matrix<double, -1, 1> generate_inp(int N, int M, int K) {\n  std::srand(123);\n  int size_vec = N * M + M * K;\n  Eigen::Matrix<double, -1, 1> vec\n      = Eigen::Matrix<double, -1, 1>::Random(size_vec);\n  return vec;\n}\n\ntemplate <int R_A, int C_A, int C_B>\nvoid pull_vals(int N, int M, int K, const Eigen::Matrix<double, -1, 1>& x,\n               Eigen::Matrix<double, R_A, C_A>& A,\n               Eigen::Matrix<double, C_A, C_B>& B) {\n  A.resize(N, M);\n  B.resize(M, K);\n  int pos = 0;\n  for (int m = 0; m < M; ++m)\n    for (int n = 0; n < N; ++n)\n      A(n, m) = x(pos++);\n\n  for (int k = 0; k < K; ++k)\n    for (int m = 0; m < M; ++m)\n      B(m, k) = x(pos++);\n}\n\nTEST(AgradRevMatrix, multiply_scalar_scalar) {\n  using stan::math::multiply;\n  double d1, d2;\n  AVAR v1, v2;\n\n  d1 = 10;\n  v1 = 10;\n  d2 = -2;\n  v2 = -2;\n\n  EXPECT_FLOAT_EQ(-20.0, multiply(d1, d2));\n  EXPECT_FLOAT_EQ(-20.0, multiply(d1, v2).val());\n  EXPECT_FLOAT_EQ(-20.0, multiply(v1, d2).val());\n  EXPECT_FLOAT_EQ(-20.0, multiply(v1, v2).val());\n\n  EXPECT_FLOAT_EQ(6.0, multiply(AVAR(3), AVAR(2)).val());\n  EXPECT_FLOAT_EQ(6.0, multiply(3.0, AVAR(2)).val());\n  EXPECT_FLOAT_EQ(6.0, multiply(AVAR(3), 2.0).val());\n}\nTEST(AgradRevMatrix, multiply_vector_scalar) {\n  using stan::math::vector_d;\n  using stan::math::vector_v;\n\n  vector_d d1(3);\n  vector_v v1(3);\n  double d2;\n  AVAR v2;\n\n  d1 << 100, 0, -3;\n  v1 << 100, 0, -3;\n  d2 = -2;\n  v2 = -2;\n\n  vector_v output;\n  output = multiply(d1, v2);\n  EXPECT_FLOAT_EQ(-200, output(0).val());\n  EXPECT_FLOAT_EQ(0, output(1).val());\n  EXPECT_FLOAT_EQ(6, output(2).val());\n\n  output = multiply(v1, d2);\n  EXPECT_FLOAT_EQ(-200, output(0).val());\n  EXPECT_FLOAT_EQ(0, output(1).val());\n  EXPECT_FLOAT_EQ(6, output(2).val());\n\n  output = multiply(v1, v2);\n  EXPECT_FLOAT_EQ(-200, output(0).val());\n  EXPECT_FLOAT_EQ(0, output(1).val());\n  EXPECT_FLOAT_EQ(6, output(2).val());\n}\nTEST(AgradRevMatrix, multiply_rowvector_scalar) {\n  using stan::math::row_vector_d;\n  using stan::math::row_vector_v;\n\n  row_vector_d d1(3);\n  row_vector_v v1(3);\n  double d2;\n  AVAR v2;\n\n  d1 << 100, 0, -3;\n  v1 << 100, 0, -3;\n  d2 = -2;\n  v2 = -2;\n\n  row_vector_v output;\n  output = multiply(d1, v2);\n  EXPECT_FLOAT_EQ(-200, output(0).val());\n  EXPECT_FLOAT_EQ(0, output(1).val());\n  EXPECT_FLOAT_EQ(6, output(2).val());\n\n  output = multiply(v1, d2);\n  EXPECT_FLOAT_EQ(-200, output(0).val());\n  EXPECT_FLOAT_EQ(0, output(1).val());\n  EXPECT_FLOAT_EQ(6, output(2).val());\n\n  output = multiply(v1, v2);\n  EXPECT_FLOAT_EQ(-200, output(0).val());\n  EXPECT_FLOAT_EQ(0, output(1).val());\n  EXPECT_FLOAT_EQ(6, output(2).val());\n}\nTEST(AgradRevMatrix, multiply_matrix_scalar) {\n  using stan::math::matrix_d;\n  using stan::math::matrix_v;\n\n  matrix_d d1(2, 2);\n  matrix_v v1(2, 2);\n  double d2;\n  AVAR v2;\n\n  d1 << 100, 0, -3, 4;\n  v1 << 100, 0, -3, 4;\n  d2 = -2;\n  v2 = -2;\n\n  matrix_v output;\n  output = multiply(d1, v2);\n  EXPECT_FLOAT_EQ(-200, output(0, 0).val());\n  EXPECT_FLOAT_EQ(0, output(0, 1).val());\n  EXPECT_FLOAT_EQ(6, output(1, 0).val());\n  EXPECT_FLOAT_EQ(-8, output(1, 1).val());\n\n  output = multiply(v1, d2);\n  EXPECT_FLOAT_EQ(-200, output(0, 0).val());\n  EXPECT_FLOAT_EQ(0, output(0, 1).val());\n  EXPECT_FLOAT_EQ(6, output(1, 0).val());\n  EXPECT_FLOAT_EQ(-8, output(1, 1).val());\n\n  output = multiply(v1, v2);\n  EXPECT_FLOAT_EQ(-200, output(0, 0).val());\n  EXPECT_FLOAT_EQ(0, output(0, 1).val());\n  EXPECT_FLOAT_EQ(6, output(1, 0).val());\n  EXPECT_FLOAT_EQ(-8, output(1, 1).val());\n}\nTEST(AgradRevMatrix, multiply_rowvector_vector) {\n  using stan::math::row_vector_d;\n  using stan::math::row_vector_v;\n  using stan::math::vector_d;\n  using stan::math::vector_v;\n\n  row_vector_d d1(3);\n  row_vector_v v1(3);\n  vector_d d2(3);\n  vector_v v2(3);\n\n  d1 << 1, 3, -5;\n  v1 << 1, 3, -5;\n  d2 << 4, -2, -1;\n  v2 << 4, -2, -1;\n\n  EXPECT_FLOAT_EQ(3, multiply(v1, v2).val());\n  EXPECT_FLOAT_EQ(3, multiply(v1, d2).val());\n  EXPECT_FLOAT_EQ(3, multiply(d1, v2).val());\n\n  d1.resize(1);\n  v1.resize(1);\n  EXPECT_THROW(multiply(v1, v2), std::invalid_argument);\n  EXPECT_THROW(multiply(v1, d2), std::invalid_argument);\n  EXPECT_THROW(multiply(d1, v2), std::invalid_argument);\n}\nTEST(AgradRevMatrix, multiply_vector_rowvector) {\n  using stan::math::matrix_v;\n  using stan::math::row_vector_d;\n  using stan::math::row_vector_v;\n  using stan::math::vector_d;\n  using stan::math::vector_v;\n\n  vector_d d1(3);\n  vector_v v1(3);\n  row_vector_d d2(3);\n  row_vector_v v2(3);\n\n  d1 << 1, 3, -5;\n  v1 << 1, 3, -5;\n  d2 << 4, -2, -1;\n  v2 << 4, -2, -1;\n\n  matrix_v output = multiply(v1, v2);\n  EXPECT_EQ(3, output.rows());\n  EXPECT_EQ(3, output.cols());\n  EXPECT_FLOAT_EQ(4, output(0, 0).val());\n  EXPECT_FLOAT_EQ(-2, output(0, 1).val());\n  EXPECT_FLOAT_EQ(-1, output(0, 2).val());\n  EXPECT_FLOAT_EQ(12, output(1, 0).val());\n  EXPECT_FLOAT_EQ(-6, output(1, 1).val());\n  EXPECT_FLOAT_EQ(-3, output(1, 2).val());\n  EXPECT_FLOAT_EQ(-20, output(2, 0).val());\n  EXPECT_FLOAT_EQ(10, output(2, 1).val());\n  EXPECT_FLOAT_EQ(5, output(2, 2).val());\n\n  output = multiply(v1, d2);\n  EXPECT_EQ(3, output.rows());\n  EXPECT_EQ(3, output.cols());\n  EXPECT_FLOAT_EQ(4, output(0, 0).val());\n  EXPECT_FLOAT_EQ(-2, output(0, 1).val());\n  EXPECT_FLOAT_EQ(-1, output(0, 2).val());\n  EXPECT_FLOAT_EQ(12, output(1, 0).val());\n  EXPECT_FLOAT_EQ(-6, output(1, 1).val());\n  EXPECT_FLOAT_EQ(-3, output(1, 2).val());\n  EXPECT_FLOAT_EQ(-20, output(2, 0).val());\n  EXPECT_FLOAT_EQ(10, output(2, 1).val());\n  EXPECT_FLOAT_EQ(5, output(2, 2).val());\n\n  output = multiply(d1, v2);\n  EXPECT_EQ(3, output.rows());\n  EXPECT_EQ(3, output.cols());\n  EXPECT_FLOAT_EQ(4, output(0, 0).val());\n  EXPECT_FLOAT_EQ(-2, output(0, 1).val());\n  EXPECT_FLOAT_EQ(-1, output(0, 2).val());\n  EXPECT_FLOAT_EQ(12, output(1, 0).val());\n  EXPECT_FLOAT_EQ(-6, output(1, 1).val());\n  EXPECT_FLOAT_EQ(-3, output(1, 2).val());\n  EXPECT_FLOAT_EQ(-20, output(2, 0).val());\n  EXPECT_FLOAT_EQ(10, output(2, 1).val());\n  EXPECT_FLOAT_EQ(5, output(2, 2).val());\n}\nTEST(AgradRevMatrix, multiply_matrix_vector) {\n  using stan::math::matrix_d;\n  using stan::math::matrix_v;\n  using stan::math::vector_d;\n  using stan::math::vector_v;\n\n  matrix_d d1(3, 2);\n  matrix_v v1(3, 2);\n  vector_d d2(2);\n  vector_v v2(2);\n\n  d1 << 1, 3, -5, 4, -2, -1;\n  v1 << 1, 3, -5, 4, -2, -1;\n  d2 << -2, 4;\n  v2 << -2, 4;\n\n  vector_v output = multiply(v1, v2);\n  EXPECT_EQ(3, output.size());\n  EXPECT_FLOAT_EQ(10, output(0).val());\n  EXPECT_FLOAT_EQ(26, output(1).val());\n  EXPECT_FLOAT_EQ(0, output(2).val());\n\n  output = multiply(v1, d2);\n  EXPECT_EQ(3, output.size());\n  EXPECT_FLOAT_EQ(10, output(0).val());\n  EXPECT_FLOAT_EQ(26, output(1).val());\n  EXPECT_FLOAT_EQ(0, output(2).val());\n\n  output = multiply(d1, v2);\n  EXPECT_EQ(3, output.size());\n  EXPECT_FLOAT_EQ(10, output(0).val());\n  EXPECT_FLOAT_EQ(26, output(1).val());\n  EXPECT_FLOAT_EQ(0, output(2).val());\n}\nTEST(AgradRevMatrix, multiply_matrix_vector_exception) {\n  using stan::math::matrix_d;\n  using stan::math::matrix_v;\n  using stan::math::vector_d;\n  using stan::math::vector_v;\n\n  matrix_d d1(3, 2);\n  matrix_v v1(3, 2);\n  vector_d d2(4);\n  vector_v v2(4);\n  EXPECT_THROW(multiply(v1, v2), std::invalid_argument);\n  EXPECT_THROW(multiply(v1, d2), std::invalid_argument);\n  EXPECT_THROW(multiply(d1, v2), std::invalid_argument);\n}\nTEST(AgradRevMatrix, multiply_rowvector_matrix) {\n  using stan::math::matrix_d;\n  using stan::math::matrix_v;\n  using stan::math::row_vector_d;\n  using stan::math::row_vector_v;\n  using stan::math::vector_v;\n\n  row_vector_d d1(3);\n  row_vector_v v1(3);\n  matrix_d d2(3, 2);\n  matrix_v v2(3, 2);\n\n  d1 << -2, 4, 1;\n  v1 << -2, 4, 1;\n  d2 << 1, 3, -5, 4, -2, -1;\n  v2 << 1, 3, -5, 4, -2, -1;\n\n  vector_v output = multiply(v1, v2);\n  EXPECT_EQ(2, output.size());\n  EXPECT_FLOAT_EQ(-24, output(0).val());\n  EXPECT_FLOAT_EQ(9, output(1).val());\n\n  output = multiply(v1, d2);\n  EXPECT_EQ(2, output.size());\n  EXPECT_FLOAT_EQ(-24, output(0).val());\n  EXPECT_FLOAT_EQ(9, output(1).val());\n\n  output = multiply(d1, v2);\n  EXPECT_EQ(2, output.size());\n  EXPECT_FLOAT_EQ(-24, output(0).val());\n  EXPECT_FLOAT_EQ(9, output(1).val());\n}\nTEST(AgradRevMatrix, multiply_rowvector_matrix_exception) {\n  using stan::math::matrix_d;\n  using stan::math::matrix_v;\n  using stan::math::row_vector_d;\n  using stan::math::row_vector_v;\n\n  row_vector_d d1(4);\n  row_vector_v v1(4);\n  matrix_d d2(3, 2);\n  matrix_v v2(3, 2);\n  EXPECT_THROW(multiply(v1, v2), std::invalid_argument);\n  EXPECT_THROW(multiply(v1, d2), std::invalid_argument);\n  EXPECT_THROW(multiply(d1, v2), std::invalid_argument);\n}\nTEST(AgradRevMatrix, multiply_matrix_matrix) {\n  using stan::math::matrix_d;\n  using stan::math::matrix_v;\n\n  matrix_d d1(2, 3);\n  matrix_v v1(2, 3);\n  matrix_d d2(3, 2);\n  matrix_v v2(3, 2);\n\n  d1 << 9, 24, 3, 46, -9, -33;\n  v1 << 9, 24, 3, 46, -9, -33;\n  d2 << 1, 3, -5, 4, -2, -1;\n  v2 << 1, 3, -5, 4, -2, -1;\n\n  matrix_v output = multiply(v1, v2);\n  EXPECT_EQ(2, output.rows());\n  EXPECT_EQ(2, output.cols());\n  EXPECT_FLOAT_EQ(-117, output(0, 0).val());\n  EXPECT_FLOAT_EQ(120, output(0, 1).val());\n  EXPECT_FLOAT_EQ(157, output(1, 0).val());\n  EXPECT_FLOAT_EQ(135, output(1, 1).val());\n\n  output = multiply(v1, d2);\n  EXPECT_EQ(2, output.rows());\n  EXPECT_EQ(2, output.cols());\n  EXPECT_FLOAT_EQ(-117, output(0, 0).val());\n  EXPECT_FLOAT_EQ(120, output(0, 1).val());\n  EXPECT_FLOAT_EQ(157, output(1, 0).val());\n  EXPECT_FLOAT_EQ(135, output(1, 1).val());\n\n  output = multiply(d1, v2);\n  EXPECT_EQ(2, output.rows());\n  EXPECT_EQ(2, output.cols());\n  EXPECT_FLOAT_EQ(-117, output(0, 0).val());\n  EXPECT_FLOAT_EQ(120, output(0, 1).val());\n  EXPECT_FLOAT_EQ(157, output(1, 0).val());\n  EXPECT_FLOAT_EQ(135, output(1, 1).val());\n}\nTEST(AgradRevMatrix, multiply_matrix_matrix_exception) {\n  using stan::math::matrix_d;\n  using stan::math::matrix_v;\n\n  matrix_d d1(2, 2);\n  matrix_v v1(2, 2);\n  matrix_d d2(3, 2);\n  matrix_v v2(3, 2);\n\n  EXPECT_THROW(multiply(v1, v2), std::invalid_argument);\n  EXPECT_THROW(multiply(v1, d2), std::invalid_argument);\n  EXPECT_THROW(multiply(d1, v2), std::invalid_argument);\n}\nTEST(AgradRevMatrix, multiply_scalar_vector_cv) {\n  using stan::math::multiply;\n  using stan::math::vector_v;\n\n  vector_v x(3);\n  x << 1, 2, 3;\n  AVEC x_ind = createAVEC(x(0), x(1), x(2));\n  vector_v y = multiply(2.0, x);\n  EXPECT_FLOAT_EQ(2.0, y(0).val());\n  EXPECT_FLOAT_EQ(4.0, y(1).val());\n  EXPECT_FLOAT_EQ(6.0, y(2).val());\n\n  VEC g = cgradvec(y(0), x_ind);\n  EXPECT_FLOAT_EQ(2.0, g[0]);\n  EXPECT_FLOAT_EQ(0.0, g[1]);\n  EXPECT_FLOAT_EQ(0.0, g[2]);\n}\nTEST(AgradRevMatrix, multiply_scalar_vector_vv) {\n  using stan::math::multiply;\n  using stan::math::vector_v;\n\n  vector_v x(3);\n  x << 1, 4, 9;\n  AVAR two = 2.0;\n  AVEC x_ind = createAVEC(x(0), x(1), x(2), two);\n  vector_v y = multiply(two, x);\n  EXPECT_FLOAT_EQ(2.0, y(0).val());\n  EXPECT_FLOAT_EQ(8.0, y(1).val());\n  EXPECT_FLOAT_EQ(18.0, y(2).val());\n\n  VEC g = cgradvec(y(1), x_ind);\n  EXPECT_FLOAT_EQ(0.0, g[0]);\n  EXPECT_FLOAT_EQ(2.0, g[1]);\n  EXPECT_FLOAT_EQ(0.0, g[2]);\n  EXPECT_FLOAT_EQ(4.0, g[3]);\n}\nTEST(AgradRevMatrix, multiply_scalar_vector_vc) {\n  using stan::math::multiply;\n  using stan::math::vector_v;\n\n  vector_v x(3);\n  x << 1, 2, 3;\n  AVAR two = 2.0;\n  AVEC x_ind = createAVEC(two);\n  vector_v y = multiply(two, x);\n  EXPECT_FLOAT_EQ(2.0, y(0).val());\n  EXPECT_FLOAT_EQ(4.0, y(1).val());\n  EXPECT_FLOAT_EQ(6.0, y(2).val());\n\n  VEC g = cgradvec(y(2), x_ind);\n  EXPECT_FLOAT_EQ(3.0, g[0]);\n}\n\nTEST(AgradRevMatrix, multiply_scalar_row_vector_cv) {\n  using stan::math::multiply;\n  using stan::math::row_vector_v;\n\n  row_vector_v x(3);\n  x << 1, 2, 3;\n  AVEC x_ind = createAVEC(x(0), x(1), x(2));\n  row_vector_v y = multiply(2.0, x);\n  EXPECT_FLOAT_EQ(2.0, y(0).val());\n  EXPECT_FLOAT_EQ(4.0, y(1).val());\n  EXPECT_FLOAT_EQ(6.0, y(2).val());\n\n  VEC g = cgradvec(y(0), x_ind);\n  EXPECT_FLOAT_EQ(2.0, g[0]);\n  EXPECT_FLOAT_EQ(0.0, g[1]);\n  EXPECT_FLOAT_EQ(0.0, g[2]);\n}\nTEST(AgradRevMatrix, multiply_scalar_row_vector_vv) {\n  using stan::math::multiply;\n  using stan::math::row_vector_v;\n\n  row_vector_v x(3);\n  x << 1, 4, 9;\n  AVAR two = 2.0;\n  AVEC x_ind = createAVEC(x(0), x(1), x(2), two);\n  row_vector_v y = multiply(two, x);\n  EXPECT_FLOAT_EQ(2.0, y(0).val());\n  EXPECT_FLOAT_EQ(8.0, y(1).val());\n  EXPECT_FLOAT_EQ(18.0, y(2).val());\n\n  VEC g = cgradvec(y(1), x_ind);\n  EXPECT_FLOAT_EQ(0.0, g[0]);\n  EXPECT_FLOAT_EQ(2.0, g[1]);\n  EXPECT_FLOAT_EQ(0.0, g[2]);\n  EXPECT_FLOAT_EQ(4.0, g[3]);\n}\nTEST(AgradRevMatrix, multiply_scalar_row_vector_vc) {\n  using stan::math::multiply;\n  using stan::math::row_vector_v;\n\n  row_vector_v x(3);\n  x << 1, 2, 3;\n  AVAR two = 2.0;\n  AVEC x_ind = createAVEC(two);\n  row_vector_v y = multiply(two, x);\n  EXPECT_FLOAT_EQ(2.0, y(0).val());\n  EXPECT_FLOAT_EQ(4.0, y(1).val());\n  EXPECT_FLOAT_EQ(6.0, y(2).val());\n\n  VEC g = cgradvec(y(2), x_ind);\n  EXPECT_FLOAT_EQ(3.0, g[0]);\n}\n\nTEST(AgradRevMatrix, multiply_scalar_matrix_cv) {\n  using stan::math::matrix_v;\n  using stan::math::multiply;\n\n  matrix_v x(2, 3);\n  x << 1, 2, 3, 4, 5, 6;\n  AVEC x_ind = createAVEC(x(0, 0), x(0, 1), x(0, 2), x(1, 0));\n  matrix_v y = multiply(2.0, x);\n  EXPECT_FLOAT_EQ(2.0, y(0, 0).val());\n  EXPECT_FLOAT_EQ(4.0, y(0, 1).val());\n  EXPECT_FLOAT_EQ(6.0, y(0, 2).val());\n\n  VEC g = cgradvec(y(0, 0), x_ind);\n  EXPECT_FLOAT_EQ(2.0, g[0]);\n  EXPECT_FLOAT_EQ(0.0, g[1]);\n  EXPECT_FLOAT_EQ(0.0, g[2]);\n  EXPECT_FLOAT_EQ(0.0, g[3]);\n}\n\nTEST(AgradRevMatrix, multiply_scalar_matrix_vc) {\n  using stan::math::matrix_d;\n  using stan::math::matrix_v;\n  using stan::math::multiply;\n\n  matrix_d x(2, 3);\n  x << 1, 2, 3, 4, 5, 6;\n  AVAR two = 2.0;\n  AVEC x_ind = createAVEC(two);\n\n  matrix_v y = multiply(two, x);\n  EXPECT_FLOAT_EQ(2.0, y(0, 0).val());\n  EXPECT_FLOAT_EQ(4.0, y(0, 1).val());\n  EXPECT_FLOAT_EQ(6.0, y(0, 2).val());\n\n  VEC g = cgradvec(y(1, 0), x_ind);\n  EXPECT_FLOAT_EQ(4.0, g[0]);\n}\n\nTEST(AgradRevMatrix, multiply_vector_int) {\n  // test namespace resolution\n  using stan::math::multiply;\n  using stan::math::vector_d;\n  using stan::math::vector_v;\n\n  vector_d dvec(3);\n  dvec << 1, 2, 3;\n  int a = 2;\n  vector_d prod_vec = multiply(dvec, a);\n  EXPECT_EQ(3, prod_vec.size());\n  EXPECT_EQ(2.0, prod_vec[0]);\n  EXPECT_EQ(4.0, prod_vec[1]);\n  EXPECT_EQ(6.0, prod_vec[2]);\n}\n\nTEST(AgradRevMatrix, multiply_matrix_matrix_grad_fd) {\n  using Eigen::MatrixXd;\n  using Eigen::VectorXd;\n\n  int N = 3;\n  int M = 4;\n  int K = 5;\n  MatrixXd A;\n  MatrixXd B;\n  MatrixXd AB(N, K);\n  VectorXd test = generate_inp(N, M, K);\n  pull_vals(N, M, K, test, A, B);\n  AB = A * B;\n  for (int n = 0; n < N; ++n) {\n    for (int k = 0; k < K; ++k) {\n      mult_vv<-1, -1, -1> func(n, k, N, M, K);\n      VectorXd grad_ad(N * M + M * K);\n      VectorXd grad_fd(N * M + M * K);\n      double val_ad;\n      double val_fd;\n      stan::math::gradient(func, test, val_ad, grad_ad);\n      stan::math::finite_diff_gradient(func, test, val_fd, grad_fd);\n      EXPECT_FLOAT_EQ(AB(n, k), val_ad);\n      EXPECT_FLOAT_EQ(AB(n, k), val_fd);\n      for (int i = 0; i < grad_ad.size(); ++i)\n        EXPECT_NEAR(grad_ad(i), grad_fd(i), 1e-10);\n    }\n  }\n}\n\nTEST(AgradRevMatrix, multiply_matrix_matrix_grad_ex) {\n  using Eigen::Infinity;\n  using Eigen::MatrixXd;\n  using Eigen::VectorXd;\n\n  int N = 3;\n  int M = 4;\n  int K = 5;\n  MatrixXd A;\n  MatrixXd B;\n  MatrixXd AB(N, K);\n  VectorXd test = generate_inp(N, M, K);\n  pull_vals(N, M, K, test, A, B);\n  AB = A * B;\n  for (int n = 0; n < N; ++n) {\n    for (int k = 0; k < K; ++k) {\n      mult_vv<-1, -1, -1> func(n, k, N, M, K);\n      VectorXd grad_ad(N * M + M * K);\n      MatrixXd grad_A;\n      MatrixXd grad_B;\n      MatrixXd grad_A_ex;\n      MatrixXd grad_B_ex;\n      grad_A_ex.resize(N, M);\n      grad_A_ex.setZero();\n      grad_B_ex.resize(M, K);\n      grad_B_ex.setZero();\n      grad_A_ex.row(n) = B.col(k);\n      grad_B_ex.col(k) = A.row(n);\n      double val_ad;\n      stan::math::gradient(func, test, val_ad, grad_ad);\n      EXPECT_FLOAT_EQ(AB(n, k), val_ad);\n      pull_vals(N, M, K, grad_ad, grad_A, grad_B);\n      EXPECT_FLOAT_EQ((grad_A - grad_A_ex).lpNorm<Infinity>(), 0);\n      EXPECT_FLOAT_EQ((grad_B - grad_B_ex).lpNorm<Infinity>(), 0);\n    }\n  }\n}\n\nTEST(AgradRevMatrix, multiply_matrix_vector_grad_fd) {\n  using Eigen::MatrixXd;\n  using Eigen::VectorXd;\n\n  int N = 3;\n  int M = 4;\n  int K = 1;\n  MatrixXd A;\n  VectorXd B;\n  VectorXd AB(N);\n  VectorXd test = generate_inp(N, M, K);\n  pull_vals(N, M, K, test, A, B);\n  AB = A * B;\n  for (int n = 0; n < N; ++n) {\n    for (int k = 0; k < K; ++k) {\n      mult_vv<-1, -1, 1> func(n, k, N, M, K);\n      VectorXd grad_ad(N * M + M * K);\n      VectorXd grad_fd(N * M + M * K);\n      double val_ad;\n      double val_fd;\n      stan::math::gradient(func, test, val_ad, grad_ad);\n      stan::math::finite_diff_gradient(func, test, val_fd, grad_fd);\n      EXPECT_FLOAT_EQ(AB(n), val_ad);\n      EXPECT_FLOAT_EQ(AB(n), val_fd);\n      for (int i = 0; i < grad_ad.size(); ++i)\n        EXPECT_NEAR(grad_ad(i), grad_fd(i), 1e-10);\n    }\n  }\n}\n\nTEST(AgradRevMatrix, multiply_matrix_vector_grad_ex) {\n  using Eigen::Infinity;\n  using Eigen::MatrixXd;\n  using Eigen::VectorXd;\n\n  int N = 3;\n  int M = 4;\n  int K = 1;\n  MatrixXd A;\n  VectorXd B;\n  VectorXd AB(N);\n  VectorXd test = generate_inp(N, M, K);\n  pull_vals(N, M, K, test, A, B);\n  AB = A * B;\n  for (int n = 0; n < N; ++n) {\n    for (int k = 0; k < K; ++k) {\n      mult_vv<-1, -1, 1> func(n, k, N, M, K);\n      VectorXd grad_ad(N * M + M * K);\n      MatrixXd grad_A;\n      MatrixXd grad_B;\n      MatrixXd grad_A_ex;\n      MatrixXd grad_B_ex;\n      grad_A_ex.resize(N, M);\n      grad_A_ex.setZero();\n      grad_B_ex.resize(M, K);\n      grad_B_ex.setZero();\n      grad_A_ex.row(n) = B.col(k);\n      grad_B_ex.col(k) = A.row(n);\n      double val_ad;\n      stan::math::gradient(func, test, val_ad, grad_ad);\n      EXPECT_FLOAT_EQ(AB(n), val_ad);\n      pull_vals(N, M, K, grad_ad, grad_A, grad_B);\n      EXPECT_FLOAT_EQ((grad_A - grad_A_ex).lpNorm<Infinity>(), 0);\n      EXPECT_FLOAT_EQ((grad_B - grad_B_ex).lpNorm<Infinity>(), 0);\n    }\n  }\n}\n\nTEST(AgradRevMatrix, multiply_row_vector_matrix_grad_fd) {\n  using Eigen::MatrixXd;\n  using Eigen::RowVectorXd;\n  using Eigen::VectorXd;\n\n  int N = 1;\n  int M = 4;\n  int K = 5;\n  RowVectorXd A;\n  MatrixXd B;\n  RowVectorXd AB(K);\n  VectorXd test = generate_inp(N, M, K);\n  pull_vals(N, M, K, test, A, B);\n  AB = A * B;\n  for (int n = 0; n < N; ++n) {\n    for (int k = 0; k < K; ++k) {\n      mult_vv<1, -1, -1> func(n, k, N, M, K);\n      VectorXd grad_ad(N * M + M * K);\n      VectorXd grad_fd(N * M + M * K);\n      double val_ad;\n      double val_fd;\n      stan::math::gradient(func, test, val_ad, grad_ad);\n      stan::math::finite_diff_gradient(func, test, val_fd, grad_fd);\n      EXPECT_FLOAT_EQ(AB(k), val_ad);\n      EXPECT_FLOAT_EQ(AB(k), val_fd);\n      for (int i = 0; i < grad_ad.size(); ++i)\n        EXPECT_NEAR(grad_ad(i), grad_fd(i), 1e-10);\n    }\n  }\n}\n\nTEST(AgradRevMatrix, multiply_row_vector_matrix_grad_ex) {\n  using Eigen::Infinity;\n  using Eigen::MatrixXd;\n  using Eigen::RowVectorXd;\n  using Eigen::VectorXd;\n\n  int N = 1;\n  int M = 4;\n  int K = 5;\n  RowVectorXd A;\n  MatrixXd B;\n  RowVectorXd AB(K);\n  VectorXd test = generate_inp(N, M, K);\n  pull_vals(N, M, K, test, A, B);\n  AB = A * B;\n  for (int n = 0; n < N; ++n) {\n    for (int k = 0; k < K; ++k) {\n      mult_vv<1, -1, -1> func(n, k, N, M, K);\n      VectorXd grad_ad(N * M + M * K);\n      RowVectorXd grad_A;\n      MatrixXd grad_B;\n      RowVectorXd grad_A_ex;\n      MatrixXd grad_B_ex;\n      grad_A_ex.resize(M);\n      grad_A_ex.setZero();\n      grad_B_ex.resize(M, K);\n      grad_B_ex.setZero();\n      grad_A_ex.row(n) = B.col(k);\n      grad_B_ex.col(k) = A.row(n);\n      double val_ad;\n      stan::math::gradient(func, test, val_ad, grad_ad);\n      EXPECT_FLOAT_EQ(AB(k), val_ad);\n      pull_vals(N, M, K, grad_ad, grad_A, grad_B);\n      EXPECT_FLOAT_EQ((grad_A - grad_A_ex).lpNorm<Infinity>(), 0);\n      EXPECT_FLOAT_EQ((grad_B - grad_B_ex).lpNorm<Infinity>(), 0);\n    }\n  }\n}\n\nTEST(AgradRevMatrix, multiply_row_vector_vector_grad_fd) {\n  using Eigen::MatrixXd;\n  using Eigen::RowVectorXd;\n  using Eigen::VectorXd;\n\n  int N = 1;\n  int M = 4;\n  int K = 1;\n  RowVectorXd A;\n  VectorXd B;\n  double AB;\n  VectorXd test = generate_inp(N, M, K);\n  pull_vals(N, M, K, test, A, B);\n  AB = A * B;\n  for (int n = 0; n < N; ++n) {\n    for (int k = 0; k < K; ++k) {\n      mult_vv<1, -1, 1> func(N, M, K);\n      VectorXd grad_ad(N * M + M * K);\n      VectorXd grad_fd(N * M + M * K);\n      double val_ad;\n      double val_fd;\n      stan::math::gradient(func, test, val_ad, grad_ad);\n      stan::math::finite_diff_gradient(func, test, val_fd, grad_fd);\n      EXPECT_FLOAT_EQ(AB, val_ad);\n      EXPECT_FLOAT_EQ(AB, val_fd);\n      for (int i = 0; i < grad_ad.size(); ++i)\n        EXPECT_NEAR(grad_ad(i), grad_fd(i), 1e-10);\n    }\n  }\n}\n\nTEST(AgradRevMatrix, multiply_row_vector_vector_grad_ex) {\n  using Eigen::Infinity;\n  using Eigen::MatrixXd;\n  using Eigen::RowVectorXd;\n  using Eigen::VectorXd;\n\n  int N = 1;\n  int M = 4;\n  int K = 1;\n  RowVectorXd A;\n  VectorXd B;\n  double AB;\n  VectorXd test = generate_inp(N, M, K);\n  pull_vals(N, M, K, test, A, B);\n  AB = A * B;\n  for (int n = 0; n < N; ++n) {\n    for (int k = 0; k < K; ++k) {\n      mult_vv<1, -1, 1> func(N, M, K);\n      VectorXd grad_ad(N * M + M * K);\n      RowVectorXd grad_A;\n      VectorXd grad_B;\n      RowVectorXd grad_A_ex;\n      VectorXd grad_B_ex;\n      grad_A_ex.resize(M);\n      grad_A_ex.setZero();\n      grad_B_ex.resize(M);\n      grad_B_ex.setZero();\n      grad_A_ex = B.transpose();\n      grad_B_ex = A.transpose();\n      double val_ad;\n      stan::math::gradient(func, test, val_ad, grad_ad);\n      EXPECT_FLOAT_EQ(AB, val_ad);\n      pull_vals(N, M, K, grad_ad, grad_A, grad_B);\n      EXPECT_FLOAT_EQ((grad_A - grad_A_ex).lpNorm<Infinity>(), 0);\n      EXPECT_FLOAT_EQ((grad_B - grad_B_ex).lpNorm<Infinity>(), 0);\n    }\n  }\n}\n\nTEST(AgradRevMatrix, multiply_vector_row_vector_grad_fd) {\n  using Eigen::MatrixXd;\n  using Eigen::RowVectorXd;\n  using Eigen::VectorXd;\n\n  int N = 3;\n  int M = 1;\n  int K = 5;\n  VectorXd A;\n  RowVectorXd B;\n  MatrixXd AB;\n  VectorXd test = generate_inp(N, M, K);\n  pull_vals(N, M, K, test, A, B);\n  AB = A * B;\n  for (int n = 0; n < N; ++n) {\n    for (int k = 0; k < K; ++k) {\n      mult_vv<-1, 1, -1> func(n, k, N, M, K);\n      VectorXd grad_ad(N * M + M * K);\n      VectorXd grad_fd(N * M + M * K);\n      double val_ad;\n      double val_fd;\n      stan::math::gradient(func, test, val_ad, grad_ad);\n      stan::math::finite_diff_gradient(func, test, val_fd, grad_fd);\n      EXPECT_FLOAT_EQ(AB(n, k), val_ad);\n      EXPECT_FLOAT_EQ(AB(n, k), val_fd);\n      for (int i = 0; i < grad_ad.size(); ++i)\n        EXPECT_NEAR(grad_ad(i), grad_fd(i), 1e-10);\n    }\n  }\n}\n\nTEST(AgradRevMatrix, multiply_vector_row_vector_grad_ex) {\n  using Eigen::Infinity;\n  using Eigen::MatrixXd;\n  using Eigen::RowVectorXd;\n  using Eigen::VectorXd;\n\n  int N = 3;\n  int M = 1;\n  int K = 5;\n  VectorXd A;\n  RowVectorXd B;\n  MatrixXd AB;\n  VectorXd test = generate_inp(N, M, K);\n  pull_vals(N, M, K, test, A, B);\n  AB = A * B;\n  for (int n = 0; n < N; ++n) {\n    for (int k = 0; k < K; ++k) {\n      mult_vv<-1, 1, -1> func(n, k, N, M, K);\n      VectorXd grad_ad(N * M + M * K);\n      VectorXd grad_A;\n      VectorXd grad_A_ex;\n      RowVectorXd grad_B;\n      RowVectorXd grad_B_ex;\n      grad_A_ex.resize(N);\n      grad_A_ex.setZero();\n      grad_B_ex.resize(K);\n      grad_B_ex.setZero();\n      grad_A_ex.row(n) = B.col(k);\n      grad_B_ex.col(k) = A.row(n);\n      double val_ad;\n      stan::math::gradient(func, test, val_ad, grad_ad);\n      EXPECT_FLOAT_EQ(AB(n, k), val_ad);\n      pull_vals(N, M, K, grad_ad, grad_A, grad_B);\n      EXPECT_FLOAT_EQ((grad_A - grad_A_ex).lpNorm<Infinity>(), 0);\n      EXPECT_FLOAT_EQ((grad_B - grad_B_ex).lpNorm<Infinity>(), 0);\n    }\n  }\n}\n\nTEST(AgradRevMatrix, multiply_matrix_matrix_grad_fd_dv) {\n  using Eigen::MatrixXd;\n  using Eigen::VectorXd;\n\n  int N = 3;\n  int M = 4;\n  int K = 5;\n  MatrixXd A;\n  MatrixXd B;\n  MatrixXd AB(N, K);\n  VectorXd test = generate_inp(N, M, K);\n  pull_vals(N, M, K, test, A, B);\n  AB = A * B;\n  for (int n = 0; n < N; ++n) {\n    for (int k = 0; k < K; ++k) {\n      mult_dv<-1, -1, -1> func(n, k, M, K, A);\n      VectorXd grad_ad(M * K);\n      VectorXd grad_fd(M * K);\n      double val_ad;\n      double val_fd;\n      stan::math::gradient(func, test.tail(M * K), val_ad, grad_ad);\n      stan::math::finite_diff_gradient(func, test.tail(M * K), val_fd, grad_fd);\n      EXPECT_FLOAT_EQ(AB(n, k), val_ad);\n      EXPECT_FLOAT_EQ(AB(n, k), val_fd);\n      for (int i = 0; i < grad_ad.size(); ++i)\n        EXPECT_NEAR(grad_ad(i), grad_fd(i), 1e-10);\n    }\n  }\n}\n\nTEST(AgradRevMatrix, multiply_matrix_matrix_grad_ex_dv) {\n  using Eigen::Infinity;\n  using Eigen::MatrixXd;\n  using Eigen::VectorXd;\n\n  int N = 3;\n  int M = 4;\n  int K = 5;\n  MatrixXd A;\n  MatrixXd B;\n  MatrixXd AB(N, K);\n  VectorXd test = generate_inp(N, M, K);\n  pull_vals(N, M, K, test, A, B);\n  AB = A * B;\n  for (int n = 0; n < N; ++n) {\n    for (int k = 0; k < K; ++k) {\n      mult_dv<-1, -1, -1> func(n, k, M, K, A);\n      VectorXd grad_ad(M * K);\n      MatrixXd grad_B;\n      MatrixXd grad_A;\n      MatrixXd grad_B_ex;\n      grad_B_ex.resize(M, K);\n      grad_B_ex.setZero();\n      grad_B_ex.col(k) = A.row(n);\n      double val_ad;\n      stan::math::gradient(func, test.tail(M * K), val_ad, grad_ad);\n      EXPECT_FLOAT_EQ(AB(n, k), val_ad);\n      pull_vals(0, M, K, grad_ad, grad_A, grad_B);\n      EXPECT_FLOAT_EQ((grad_B - grad_B_ex).lpNorm<Infinity>(), 0);\n    }\n  }\n}\n\nTEST(AgradRevMatrix, multiply_matrix_vector_grad_fd_dv) {\n  using Eigen::MatrixXd;\n  using Eigen::VectorXd;\n\n  int N = 3;\n  int M = 4;\n  int K = 1;\n  MatrixXd A;\n  VectorXd B;\n  VectorXd AB(N);\n  VectorXd test = generate_inp(N, M, K);\n  pull_vals(N, M, K, test, A, B);\n  AB = A * B;\n  for (int n = 0; n < N; ++n) {\n    for (int k = 0; k < K; ++k) {\n      mult_dv<-1, -1, 1> func(n, k, M, K, A);\n      VectorXd grad_ad(M * K);\n      VectorXd grad_fd(M * K);\n      double val_ad;\n      double val_fd;\n      stan::math::gradient(func, test.tail(M * K), val_ad, grad_ad);\n      stan::math::finite_diff_gradient(func, test.tail(M * K), val_fd, grad_fd);\n      EXPECT_FLOAT_EQ(AB(n), val_ad);\n      EXPECT_FLOAT_EQ(AB(n), val_fd);\n      for (int i = 0; i < grad_ad.size(); ++i)\n        EXPECT_NEAR(grad_ad(i), grad_fd(i), 1e-10);\n    }\n  }\n}\n\nTEST(AgradRevMatrix, multiply_matrix_vector_grad_ex_dv) {\n  using Eigen::Infinity;\n  using Eigen::MatrixXd;\n  using Eigen::VectorXd;\n\n  int N = 3;\n  int M = 4;\n  int K = 1;\n  MatrixXd A;\n  VectorXd B;\n  VectorXd AB(N);\n  VectorXd test = generate_inp(N, M, K);\n  pull_vals(N, M, K, test, A, B);\n  AB = A * B;\n  for (int n = 0; n < N; ++n) {\n    for (int k = 0; k < K; ++k) {\n      mult_dv<-1, -1, 1> func(n, k, M, K, A);\n      VectorXd grad_ad(M * K);\n      VectorXd grad_B;\n      MatrixXd grad_A;\n      VectorXd grad_B_ex;\n      grad_B_ex.resize(M);\n      grad_B_ex.setZero();\n      grad_B_ex = A.row(n);\n      double val_ad;\n      stan::math::gradient(func, test.tail(M * K), val_ad, grad_ad);\n      EXPECT_FLOAT_EQ(AB(n), val_ad);\n      pull_vals(0, M, K, grad_ad, grad_A, grad_B);\n      EXPECT_FLOAT_EQ((grad_B - grad_B_ex).lpNorm<Infinity>(), 0);\n    }\n  }\n}\n\nTEST(AgradRevMatrix, multiply_row_vector_matrix_grad_fd_dv) {\n  using Eigen::MatrixXd;\n  using Eigen::RowVectorXd;\n  using Eigen::VectorXd;\n\n  int N = 1;\n  int M = 4;\n  int K = 5;\n  RowVectorXd A;\n  MatrixXd B;\n  RowVectorXd AB(K);\n  VectorXd test = generate_inp(N, M, K);\n  pull_vals(N, M, K, test, A, B);\n  AB = A * B;\n  for (int n = 0; n < N; ++n) {\n    for (int k = 0; k < K; ++k) {\n      mult_dv<1, -1, -1> func(n, k, M, K, A);\n      VectorXd grad_ad(M * K);\n      VectorXd grad_fd(M * K);\n      double val_ad;\n      double val_fd;\n      stan::math::gradient(func, test.tail(M * K), val_ad, grad_ad);\n      stan::math::finite_diff_gradient(func, test.tail(M * K), val_fd, grad_fd);\n      EXPECT_FLOAT_EQ(AB(k), val_ad);\n      EXPECT_FLOAT_EQ(AB(k), val_fd);\n      for (int i = 0; i < grad_ad.size(); ++i)\n        EXPECT_NEAR(grad_ad(i), grad_fd(i), 1e-10);\n    }\n  }\n}\n\nTEST(AgradRevMatrix, multiply_row_vector_matrix_grad_ex_dv) {\n  using Eigen::Infinity;\n  using Eigen::MatrixXd;\n  using Eigen::RowVectorXd;\n  using Eigen::VectorXd;\n\n  int N = 1;\n  int M = 4;\n  int K = 5;\n  RowVectorXd A;\n  MatrixXd B;\n  RowVectorXd AB(N, K);\n  VectorXd test = generate_inp(N, M, K);\n  pull_vals(N, M, K, test, A, B);\n  AB = A * B;\n  for (int n = 0; n < N; ++n) {\n    for (int k = 0; k < K; ++k) {\n      mult_dv<1, -1, -1> func(n, k, M, K, A);\n      VectorXd grad_ad(M * K);\n      MatrixXd grad_B;\n      MatrixXd grad_A;\n      MatrixXd grad_B_ex;\n      grad_B_ex.resize(M, K);\n      grad_B_ex.setZero();\n      grad_B_ex.col(k) = A.row(n);\n      double val_ad;\n      stan::math::gradient(func, test.tail(M * K), val_ad, grad_ad);\n      EXPECT_FLOAT_EQ(AB(k), val_ad);\n      pull_vals(0, M, K, grad_ad, grad_A, grad_B);\n      EXPECT_FLOAT_EQ((grad_B - grad_B_ex).lpNorm<Infinity>(), 0);\n    }\n  }\n}\n\nTEST(AgradRevMatrix, multiply_row_vector_vector_grad_fd_dv) {\n  using Eigen::MatrixXd;\n  using Eigen::RowVectorXd;\n  using Eigen::VectorXd;\n\n  int N = 1;\n  int M = 4;\n  int K = 1;\n  RowVectorXd A;\n  VectorXd B;\n  double AB;\n  VectorXd test = generate_inp(N, M, K);\n  pull_vals(N, M, K, test, A, B);\n  AB = A * B;\n  for (int n = 0; n < N; ++n) {\n    for (int k = 0; k < K; ++k) {\n      mult_dv<1, -1, 1> func(M, K, A);\n      VectorXd grad_ad(M * K);\n      VectorXd grad_fd(M * K);\n      double val_ad;\n      double val_fd;\n      stan::math::gradient(func, test.tail(M * K), val_ad, grad_ad);\n      stan::math::finite_diff_gradient(func, test.tail(M * K), val_fd, grad_fd);\n      EXPECT_FLOAT_EQ(AB, val_ad);\n      EXPECT_FLOAT_EQ(AB, val_fd);\n      for (int i = 0; i < grad_ad.size(); ++i)\n        EXPECT_NEAR(grad_ad(i), grad_fd(i), 1e-10);\n    }\n  }\n}\n\nTEST(AgradRevMatrix, multiply_row_vector_vector_grad_ex_dv) {\n  using Eigen::Infinity;\n  using Eigen::MatrixXd;\n  using Eigen::RowVectorXd;\n  using Eigen::VectorXd;\n\n  int N = 1;\n  int M = 4;\n  int K = 1;\n  RowVectorXd A;\n  VectorXd B;\n  double AB;\n  VectorXd test = generate_inp(N, M, K);\n  pull_vals(N, M, K, test, A, B);\n  AB = A * B;\n  for (int n = 0; n < N; ++n) {\n    for (int k = 0; k < K; ++k) {\n      mult_dv<1, -1, 1> func(M, K, A);\n      VectorXd grad_ad(M * K);\n      VectorXd grad_B;\n      MatrixXd grad_A;\n      VectorXd grad_B_ex;\n      grad_B_ex.resize(M, K);\n      grad_B_ex.setZero();\n      grad_B_ex = A;\n      double val_ad;\n      stan::math::gradient(func, test.tail(M * K), val_ad, grad_ad);\n      EXPECT_FLOAT_EQ(AB, val_ad);\n      pull_vals(0, M, K, grad_ad, grad_A, grad_B);\n      EXPECT_FLOAT_EQ((grad_B - grad_B_ex).lpNorm<Infinity>(), 0);\n    }\n  }\n}\n\nTEST(AgradRevMatrix, multiply_vector_row_vector_grad_fd_dv) {\n  using Eigen::MatrixXd;\n  using Eigen::RowVectorXd;\n  using Eigen::VectorXd;\n\n  int N = 3;\n  int M = 1;\n  int K = 5;\n  VectorXd A;\n  RowVectorXd B;\n  MatrixXd AB;\n  VectorXd test = generate_inp(N, M, K);\n  pull_vals(N, M, K, test, A, B);\n  AB = A * B;\n  for (int n = 0; n < N; ++n) {\n    for (int k = 0; k < K; ++k) {\n      mult_dv<-1, 1, -1> func(n, k, M, K, A);\n      VectorXd grad_ad(M * K);\n      VectorXd grad_fd(M * K);\n      double val_ad;\n      double val_fd;\n      stan::math::gradient(func, test.tail(M * K), val_ad, grad_ad);\n      stan::math::finite_diff_gradient(func, test.tail(M * K), val_fd, grad_fd);\n      EXPECT_FLOAT_EQ(AB(n, k), val_ad);\n      EXPECT_FLOAT_EQ(AB(n, k), val_fd);\n      for (int i = 0; i < grad_ad.size(); ++i)\n        EXPECT_NEAR(grad_ad(i), grad_fd(i), 1e-10);\n    }\n  }\n}\n\nTEST(AgradRevMatrix, multiply_vector_row_vector_grad_ex_dv) {\n  using Eigen::Infinity;\n  using Eigen::MatrixXd;\n  using Eigen::RowVectorXd;\n  using Eigen::VectorXd;\n\n  int N = 3;\n  int M = 1;\n  int K = 5;\n  VectorXd A;\n  RowVectorXd B;\n  MatrixXd AB;\n  VectorXd test = generate_inp(N, M, K);\n  pull_vals(N, M, K, test, A, B);\n  AB = A * B;\n  for (int n = 0; n < N; ++n) {\n    for (int k = 0; k < K; ++k) {\n      mult_dv<-1, 1, -1> func(n, k, M, K, A);\n      VectorXd grad_ad(M * K);\n      VectorXd grad_A;\n      RowVectorXd grad_B;\n      RowVectorXd grad_B_ex;\n      grad_B_ex.resize(K);\n      grad_B_ex.setZero();\n      grad_B_ex.col(k) = A.row(n);\n      double val_ad;\n      stan::math::gradient(func, test.tail(M * K), val_ad, grad_ad);\n      EXPECT_FLOAT_EQ(AB(n, k), val_ad);\n      pull_vals(0, M, K, grad_ad, grad_A, grad_B);\n      EXPECT_FLOAT_EQ((grad_B - grad_B_ex).lpNorm<Infinity>(), 0);\n    }\n  }\n}\n\nTEST(AgradRevMatrix, multiply_matrix_matrix_grad_fd_vd) {\n  using Eigen::MatrixXd;\n  using Eigen::VectorXd;\n\n  int N = 3;\n  int M = 4;\n  int K = 5;\n  MatrixXd A;\n  MatrixXd B;\n  MatrixXd AB(N, K);\n  VectorXd test = generate_inp(N, M, K);\n  pull_vals(N, M, K, test, A, B);\n  AB = A * B;\n  for (int n = 0; n < N; ++n) {\n    for (int k = 0; k < K; ++k) {\n      mult_vd<-1, -1, -1> func(n, k, N, M, B);\n      VectorXd grad_ad(N * M);\n      VectorXd grad_fd(N * M);\n      double val_ad;\n      double val_fd;\n      stan::math::gradient(func, test.head(N * M), val_ad, grad_ad);\n      stan::math::finite_diff_gradient(func, test.head(N * M), val_fd, grad_fd);\n      EXPECT_FLOAT_EQ(AB(n, k), val_ad);\n      EXPECT_FLOAT_EQ(AB(n, k), val_fd);\n      for (int i = 0; i < grad_ad.size(); ++i)\n        EXPECT_NEAR(grad_ad(i), grad_fd(i), 1e-10);\n    }\n  }\n}\n\nTEST(AgradRevMatrix, multiply_matrix_matrix_grad_ex_vd) {\n  using Eigen::Infinity;\n  using Eigen::MatrixXd;\n  using Eigen::VectorXd;\n\n  int N = 3;\n  int M = 4;\n  int K = 5;\n  MatrixXd A;\n  MatrixXd B;\n  MatrixXd AB(N, K);\n  VectorXd test = generate_inp(N, M, K);\n  pull_vals(N, M, K, test, A, B);\n  AB = A * B;\n  for (int n = 0; n < N; ++n) {\n    for (int k = 0; k < K; ++k) {\n      mult_vd<-1, -1, -1> func(n, k, N, M, B);\n      VectorXd grad_ad(N * M);\n      MatrixXd grad_B;\n      MatrixXd grad_A;\n      MatrixXd grad_A_ex;\n      grad_A_ex.resize(N, M);\n      grad_A_ex.setZero();\n      grad_A_ex.row(n) = B.col(k);\n      double val_ad;\n      stan::math::gradient(func, test.head(N * M), val_ad, grad_ad);\n      EXPECT_FLOAT_EQ(AB(n, k), val_ad);\n      pull_vals(N, M, 0, grad_ad, grad_A, grad_B);\n      EXPECT_FLOAT_EQ((grad_A - grad_A_ex).lpNorm<Infinity>(), 0);\n    }\n  }\n}\n\nTEST(AgradRevMatrix, multiply_matrix_vector_grad_fd_vd) {\n  using Eigen::MatrixXd;\n  using Eigen::VectorXd;\n\n  int N = 3;\n  int M = 4;\n  int K = 1;\n  MatrixXd A;\n  VectorXd B;\n  VectorXd AB(N);\n  VectorXd test = generate_inp(N, M, K);\n  pull_vals(N, M, K, test, A, B);\n  AB = A * B;\n  for (int n = 0; n < N; ++n) {\n    for (int k = 0; k < K; ++k) {\n      mult_vd<-1, -1, 1> func(n, k, N, M, B);\n      VectorXd grad_ad(N * M);\n      VectorXd grad_fd(N * M);\n      double val_ad;\n      double val_fd;\n      stan::math::gradient(func, test.head(M * N), val_ad, grad_ad);\n      stan::math::finite_diff_gradient(func, test.head(N * M), val_fd, grad_fd);\n      EXPECT_FLOAT_EQ(AB(n), val_ad);\n      EXPECT_FLOAT_EQ(AB(n), val_fd);\n      for (int i = 0; i < grad_ad.size(); ++i)\n        EXPECT_NEAR(grad_ad(i), grad_fd(i), 1e-10);\n    }\n  }\n}\n\nTEST(AgradRevMatrix, multiply_matrix_vector_grad_ex_vd) {\n  using Eigen::Infinity;\n  using Eigen::MatrixXd;\n  using Eigen::VectorXd;\n\n  int N = 3;\n  int M = 4;\n  int K = 1;\n  MatrixXd A;\n  MatrixXd B;\n  VectorXd AB(N);\n  VectorXd test = generate_inp(N, M, K);\n  pull_vals(N, M, K, test, A, B);\n  AB = A * B;\n  for (int n = 0; n < N; ++n) {\n    for (int k = 0; k < K; ++k) {\n      mult_vd<-1, -1, 1> func(n, k, N, M, B);\n      VectorXd grad_ad(N * M);\n      MatrixXd grad_B;\n      MatrixXd grad_A;\n      MatrixXd grad_A_ex;\n      grad_A_ex.resize(N, M);\n      grad_A_ex.setZero();\n      grad_A_ex.row(n) = B.col(k);\n      double val_ad;\n      stan::math::gradient(func, test.head(N * M), val_ad, grad_ad);\n      EXPECT_FLOAT_EQ(AB(n), val_ad);\n      pull_vals(N, M, 0, grad_ad, grad_A, grad_B);\n      EXPECT_FLOAT_EQ((grad_A - grad_A_ex).lpNorm<Infinity>(), 0);\n    }\n  }\n}\n\nTEST(AgradRevMatrix, multiply_row_vector_matrix_grad_fd_vd) {\n  using Eigen::MatrixXd;\n  using Eigen::RowVectorXd;\n  using Eigen::VectorXd;\n\n  int N = 1;\n  int M = 4;\n  int K = 5;\n  RowVectorXd A;\n  MatrixXd B;\n  RowVectorXd AB(K);\n  VectorXd test = generate_inp(N, M, K);\n  pull_vals(N, M, K, test, A, B);\n  AB = A * B;\n  for (int n = 0; n < N; ++n) {\n    for (int k = 0; k < K; ++k) {\n      mult_vd<1, -1, -1> func(n, k, N, M, B);\n      VectorXd grad_ad(N * M);\n      VectorXd grad_fd(N * M);\n      double val_ad;\n      double val_fd;\n      stan::math::gradient(func, test.head(N * M), val_ad, grad_ad);\n      stan::math::finite_diff_gradient(func, test.head(N * M), val_fd, grad_fd);\n      EXPECT_FLOAT_EQ(AB(k), val_ad);\n      EXPECT_FLOAT_EQ(AB(k), val_fd);\n      for (int i = 0; i < grad_ad.size(); ++i)\n        EXPECT_NEAR(grad_ad(i), grad_fd(i), 1e-10);\n    }\n  }\n}\n\nTEST(AgradRevMatrix, multiply_row_vector_matrix_grad_ex_vd) {\n  using Eigen::Infinity;\n  using Eigen::MatrixXd;\n  using Eigen::RowVectorXd;\n  using Eigen::VectorXd;\n\n  int N = 1;\n  int M = 4;\n  int K = 5;\n  RowVectorXd A;\n  MatrixXd B;\n  RowVectorXd AB(K);\n  VectorXd test = generate_inp(N, M, K);\n  pull_vals(N, M, K, test, A, B);\n  AB = A * B;\n  for (int n = 0; n < N; ++n) {\n    for (int k = 0; k < K; ++k) {\n      mult_vd<1, -1, -1> func(n, k, N, M, B);\n      VectorXd grad_ad(N * M);\n      MatrixXd grad_B;\n      MatrixXd grad_A;\n      RowVectorXd grad_A_ex;\n      grad_A_ex.resize(M);\n      grad_A_ex.setZero();\n      grad_A_ex = B.col(k);\n      double val_ad;\n      stan::math::gradient(func, test.head(N * M), val_ad, grad_ad);\n      EXPECT_FLOAT_EQ(AB(k), val_ad);\n      pull_vals(N, M, 0, grad_ad, grad_A, grad_B);\n      EXPECT_FLOAT_EQ((grad_A - grad_A_ex).lpNorm<Infinity>(), 0);\n    }\n  }\n}\n\nTEST(AgradRevMatrix, multiply_row_vector_vector_grad_fd_vd) {\n  using Eigen::MatrixXd;\n  using Eigen::RowVectorXd;\n  using Eigen::VectorXd;\n\n  int N = 1;\n  int M = 4;\n  int K = 1;\n  RowVectorXd A;\n  VectorXd B;\n  double AB;\n  VectorXd test = generate_inp(N, M, K);\n  pull_vals(N, M, K, test, A, B);\n  AB = A * B;\n  for (int n = 0; n < N; ++n) {\n    for (int k = 0; k < K; ++k) {\n      mult_vd<1, -1, 1> func(N, M, B);\n      VectorXd grad_ad(N * M);\n      VectorXd grad_fd(N * M);\n      double val_ad;\n      double val_fd;\n      stan::math::gradient(func, test.head(N * M), val_ad, grad_ad);\n      stan::math::finite_diff_gradient(func, test.head(N * M), val_fd, grad_fd);\n      EXPECT_FLOAT_EQ(AB, val_ad);\n      EXPECT_FLOAT_EQ(AB, val_fd);\n      for (int i = 0; i < grad_ad.size(); ++i)\n        EXPECT_NEAR(grad_ad(i), grad_fd(i), 1e-10);\n    }\n  }\n}\n\nTEST(AgradRevMatrix, multiply_row_vector_vector_grad_ex_vd) {\n  using Eigen::Infinity;\n  using Eigen::MatrixXd;\n  using Eigen::RowVectorXd;\n  using Eigen::VectorXd;\n\n  int N = 1;\n  int M = 4;\n  int K = 1;\n  RowVectorXd A;\n  VectorXd B;\n  double AB;\n  VectorXd test = generate_inp(N, M, K);\n  pull_vals(N, M, K, test, A, B);\n  AB = A * B;\n  for (int n = 0; n < N; ++n) {\n    for (int k = 0; k < K; ++k) {\n      mult_vd<1, -1, 1> func(N, M, B);\n      VectorXd grad_ad(N * M);\n      MatrixXd grad_B;\n      RowVectorXd grad_A;\n      RowVectorXd grad_A_ex;\n      grad_A_ex.resize(M);\n      grad_A_ex.setZero();\n      grad_A_ex = B;\n      double val_ad;\n      stan::math::gradient(func, test.head(N * M), val_ad, grad_ad);\n      EXPECT_FLOAT_EQ(AB, val_ad);\n      pull_vals(N, M, 0, grad_ad, grad_A, grad_B);\n      EXPECT_FLOAT_EQ((grad_A - grad_A_ex).lpNorm<Infinity>(), 0);\n    }\n  }\n}\n\nTEST(AgradRevMatrix, multiply_vector_row_vector_grad_fd_vd) {\n  using Eigen::MatrixXd;\n  using Eigen::RowVectorXd;\n  using Eigen::VectorXd;\n\n  int N = 3;\n  int M = 1;\n  int K = 5;\n  VectorXd A;\n  RowVectorXd B;\n  MatrixXd AB;\n  VectorXd test = generate_inp(N, M, K);\n  pull_vals(N, M, K, test, A, B);\n  AB = A * B;\n  for (int n = 0; n < N; ++n) {\n    for (int k = 0; k < K; ++k) {\n      mult_vd<-1, 1, -1> func(n, k, N, M, B);\n      VectorXd grad_ad(N * M);\n      VectorXd grad_fd(N * M);\n      double val_ad;\n      double val_fd;\n      stan::math::gradient(func, test.head(M * N), val_ad, grad_ad);\n      stan::math::finite_diff_gradient(func, test.head(N * M), val_fd, grad_fd);\n      EXPECT_FLOAT_EQ(AB(n, k), val_ad);\n      EXPECT_FLOAT_EQ(AB(n, k), val_fd);\n      for (int i = 0; i < grad_ad.size(); ++i)\n        EXPECT_NEAR(grad_ad(i), grad_fd(i), 1e-10);\n    }\n  }\n}\n\nTEST(AgradRevMatrix, multiply_vector_row_vector_grad_ex_vd) {\n  using Eigen::Infinity;\n  using Eigen::MatrixXd;\n  using Eigen::RowVectorXd;\n  using Eigen::VectorXd;\n\n  int N = 3;\n  int M = 1;\n  int K = 5;\n  VectorXd A;\n  RowVectorXd B;\n  MatrixXd AB;\n  VectorXd test = generate_inp(N, M, K);\n  pull_vals(N, M, K, test, A, B);\n  AB = A * B;\n  for (int n = 0; n < N; ++n) {\n    for (int k = 0; k < K; ++k) {\n      mult_vd<-1, 1, -1> func(n, k, N, M, B);\n      VectorXd grad_ad(N * M);\n      RowVectorXd grad_B;\n      VectorXd grad_A;\n      VectorXd grad_A_ex;\n      grad_A_ex.resize(N);\n      grad_A_ex.setZero();\n      grad_A_ex.row(n) = B.col(k);\n      double val_ad;\n      stan::math::gradient(func, test.head(N * M), val_ad, grad_ad);\n      EXPECT_FLOAT_EQ(AB(n, k), val_ad);\n      pull_vals(N, M, 0, grad_ad, grad_A, grad_B);\n      EXPECT_FLOAT_EQ((grad_A - grad_A_ex).lpNorm<Infinity>(), 0);\n    }\n  }\n}\nTEST(AgradRevMatrix, check_varis_on_stack) {\n  using stan::math::value_of;\n  stan::math::matrix_v m(3, 3);\n  m << 1, 2, 3, 4, 5, 6, 7, 8, 9;\n  stan::math::vector_v v(3);\n  v << 10, 20, 30;\n  stan::math::row_vector_v rv(3);\n  rv << 100, 200, 300;\n  stan::math::var s = 1;\n\n  test::check_varis_on_stack(stan::math::multiply(m, m));\n  test::check_varis_on_stack(stan::math::multiply(m, value_of(m)));\n  test::check_varis_on_stack(stan::math::multiply(value_of(m), m));\n\n  test::check_varis_on_stack(stan::math::multiply(m, v));\n  test::check_varis_on_stack(stan::math::multiply(m, value_of(v)));\n  test::check_varis_on_stack(stan::math::multiply(value_of(m), v));\n\n  test::check_varis_on_stack(stan::math::multiply(rv, m));\n  test::check_varis_on_stack(stan::math::multiply(rv, value_of(m)));\n  test::check_varis_on_stack(stan::math::multiply(value_of(rv), m));\n\n  test::check_varis_on_stack(stan::math::multiply(rv, v));\n  test::check_varis_on_stack(stan::math::multiply(rv, value_of(v)));\n  test::check_varis_on_stack(stan::math::multiply(value_of(rv), v));\n\n  test::check_varis_on_stack(stan::math::multiply(s, m));\n  test::check_varis_on_stack(stan::math::multiply(s, value_of(m)));\n  test::check_varis_on_stack(stan::math::multiply(value_of(s), m));\n\n  test::check_varis_on_stack(stan::math::multiply(s, rv));\n  test::check_varis_on_stack(stan::math::multiply(s, value_of(rv)));\n  test::check_varis_on_stack(stan::math::multiply(value_of(s), rv));\n\n  test::check_varis_on_stack(stan::math::multiply(s, v));\n  test::check_varis_on_stack(stan::math::multiply(s, value_of(v)));\n  test::check_varis_on_stack(stan::math::multiply(value_of(s), v));\n\n  test::check_varis_on_stack(stan::math::multiply(m, s));\n  test::check_varis_on_stack(stan::math::multiply(m, value_of(s)));\n  test::check_varis_on_stack(stan::math::multiply(value_of(m), s));\n\n  test::check_varis_on_stack(stan::math::multiply(rv, s));\n  test::check_varis_on_stack(stan::math::multiply(rv, value_of(s)));\n  test::check_varis_on_stack(stan::math::multiply(value_of(rv), s));\n\n  test::check_varis_on_stack(stan::math::multiply(v, s));\n  test::check_varis_on_stack(stan::math::multiply(v, value_of(s)));\n  test::check_varis_on_stack(stan::math::multiply(value_of(v), s));\n\n  test::check_varis_on_stack(stan::math::multiply(s, s));\n  test::check_varis_on_stack(stan::math::multiply(s, value_of(s)));\n  test::check_varis_on_stack(stan::math::multiply(value_of(s), s));\n}\n\n#ifdef STAN_OPENCL\n#define EXPECT_MATRIX_NEAR(A, B, DELTA) \\\n  for (int i = 0; i < A.size(); i++)    \\\n    EXPECT_NEAR(stan::math::value_of(A(i)), stan::math::value_of(B(i)), DELTA);\n\nboost::random::mt19937 rng;\n#define MULTIPLY_OPENCL_OVERRIDE 0\n#define MULTIPLY_CPU_OVERRIDE INT_MAX\nTEST(AgradRevMatrix, multiply_val_vv_cl) {\n  int temp = stan::math::opencl_context.tuning_opts()\n                 .multiply_dim_prod_worth_transfer;\n  using stan::math::matrix_d;\n  using stan::math::matrix_v;\n  using stan::math::multiply;\n  int size = 234;\n  matrix_v Av(size, size);\n  matrix_v Bv(size, size);\n  matrix_v C, C_cl;\n  for (int i = 0; i < size; i++) {\n    for (int j = 0; j < size; j++) {\n      Av(i, j) = stan::math::uniform_rng(-5, 5, rng);\n      Bv(i, j) = stan::math::uniform_rng(-5, 5, rng);\n    }\n  }\n  stan::math::opencl_context.tuning_opts().multiply_dim_prod_worth_transfer\n      = MULTIPLY_OPENCL_OVERRIDE;\n  C_cl = multiply(Av, Bv);\n  C_cl(0, 0).grad();\n  stan::math::opencl_context.tuning_opts().multiply_dim_prod_worth_transfer\n      = MULTIPLY_CPU_OVERRIDE;\n  C = multiply(Av, Bv);\n  C(0, 0).grad();\n  EXPECT_MATRIX_NEAR(C, C_cl, 1.0E-12);\n  EXPECT_MATRIX_NEAR(C.adj(), C_cl.adj(), 1.0E-12);\n  stan::math::recover_memory();\n  stan::math::opencl_context.tuning_opts().multiply_dim_prod_worth_transfer\n      = temp;\n}\n\nTEST(AgradRevMatrix, multiply_val_vd_cl) {\n  int temp = stan::math::opencl_context.tuning_opts()\n                 .multiply_dim_prod_worth_transfer;\n  using stan::math::matrix_d;\n  using stan::math::matrix_v;\n  using stan::math::multiply;\n  int size = 256;\n  matrix_v Av(size, size);\n  matrix_v Bd(size, size);\n  matrix_v C, C_cl;\n  for (int i = 0; i < size; i++) {\n    for (int j = 0; j < size; j++) {\n      Av(i, j) = stan::math::uniform_rng(-5, 5, rng);\n      Bd(i, j) = stan::math::uniform_rng(-5, 5, rng);\n    }\n  }\n  stan::math::opencl_context.tuning_opts().multiply_dim_prod_worth_transfer\n      = MULTIPLY_OPENCL_OVERRIDE;\n  C_cl = multiply(Av, Bd);\n  C_cl(0, 0).grad();\n  stan::math::opencl_context.tuning_opts().multiply_dim_prod_worth_transfer\n      = MULTIPLY_CPU_OVERRIDE;\n  C = multiply(Av, Bd);\n  C(0, 0).grad();\n  EXPECT_MATRIX_NEAR(C, C_cl, 1.0E-12);\n  EXPECT_MATRIX_NEAR(C.adj(), C_cl.adj(), 1.0E-12);\n  stan::math::recover_memory();\n  stan::math::opencl_context.tuning_opts().multiply_dim_prod_worth_transfer\n      = temp;\n}\n\nTEST(AgradRevMatrix, multiply_val_dv_cl) {\n  int temp = stan::math::opencl_context.tuning_opts()\n                 .multiply_dim_prod_worth_transfer;\n  using stan::math::matrix_d;\n  using stan::math::matrix_v;\n  using stan::math::multiply;\n  int size = 321;\n  matrix_v Ad(size, size);\n  matrix_v Bv(size, size);\n  matrix_v C, C_cl;\n  for (int i = 0; i < size; i++) {\n    for (int j = 0; j < size; j++) {\n      Ad(i, j) = stan::math::uniform_rng(-5, 5, rng);\n      Bv(i, j) = stan::math::uniform_rng(-5, 5, rng);\n    }\n  }\n  stan::math::opencl_context.tuning_opts().multiply_dim_prod_worth_transfer\n      = MULTIPLY_OPENCL_OVERRIDE;\n  C_cl = multiply(Ad, Bv);\n  C_cl(0, 0).grad();\n  stan::math::opencl_context.tuning_opts().multiply_dim_prod_worth_transfer\n      = MULTIPLY_CPU_OVERRIDE;\n  C = multiply(Ad, Bv);\n  C(0, 0).grad();\n  EXPECT_MATRIX_NEAR(C, C_cl, 1.0E-12);\n  EXPECT_MATRIX_NEAR(C.adj(), C_cl.adj(), 1.0E-12);\n  stan::math::recover_memory();\n  stan::math::opencl_context.tuning_opts().multiply_dim_prod_worth_transfer\n      = temp;\n}\n\n#endif\n", "meta": {"hexsha": "067ac39bd3007ed982a9e6738e0569eff2435e2f", "size": 51220, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/rev/mat/fun/multiply_test.cpp", "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": "test/unit/math/rev/mat/fun/multiply_test.cpp", "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": "test/unit/math/rev/mat/fun/multiply_test.cpp", "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": 28.0043739748, "max_line_length": 80, "alphanum_fraction": 0.6043342444, "num_tokens": 17883, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257126, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.46814265289915796}}
{"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__C1_HPP_\n#define SMOOTH__C1_HPP_\n\n#include <Eigen/Core>\n\n#include <complex>\n\n#include \"internal/c1.hpp\"\n#include \"internal/lie_group_base.hpp\"\n#include \"internal/macro.hpp\"\n#include \"lie_group.hpp\"\n#include \"map.hpp\"\n#include \"so2.hpp\"\n\nnamespace smooth {\n\n// \\cond\ntemplate<typename Scalar>\nclass SO2;\n// \\endcond\n\n/**\n * @brief Base class for C1 Lie group types.\n *\n * Memory layout\n * -------------\n *\n * - Group:    \\f$ \\mathbf{x} = [a, b] \\f$\n * - Tangent:  \\f$ \\mathbf{a} = [s, \\omega_z] \\f$\n *\n * Constraints\n * -----------\n *\n * - Group:   \\f$ a^2 + b^2 > 0 \\f$\n * - Tangent: \\f$ -\\pi < \\omega_z \\leq \\pi \\f$\n *\n * Lie group matrix form\n * ---------------------\n *\n * \\f[\n * \\mathbf{X} =\n * \\begin{bmatrix}\n *  b & -a \\\\\n *  a &  b\n * \\end{bmatrix} \\in \\mathbb{R}^{2 \\times 2}\n * \\f]\n *\n *\n * Lie algebra matrix form\n * -----------------------\n *\n * \\f[\n * \\mathbf{a}^\\wedge =\n * \\begin{bmatrix}\n *   s & -\\omega_z \\\\\n *  \\omega_z &   s \\\\\n * \\end{bmatrix} \\in \\mathbb{R}^{2 \\times 2}\n * \\f]\n */\ntemplate<typename _Derived>\nclass C1Base : public LieGroupBase<_Derived>\n{\n  using Base = LieGroupBase<_Derived>;\n\nprotected:\n  C1Base() = default;\n\npublic:\n  SMOOTH_INHERIT_TYPEDEFS;\n\n  /**\n   * @brief Rotation angle.\n   */\n  Scalar angle() const\n  {\n    using std::atan2;\n\n    return atan2(\n      static_cast<const _Derived &>(*this).coeffs().x(),\n      static_cast<const _Derived &>(*this).coeffs().y());\n  }\n\n  /**\n   * @brief Scaling.\n   */\n  Scalar scaling() const\n  {\n    using std::sqrt;\n\n    return sqrt(\n      static_cast<const _Derived &>(*this).coeffs().x()\n        * static_cast<const _Derived &>(*this).coeffs().x()\n      + static_cast<const _Derived &>(*this).coeffs().y()\n          * static_cast<const _Derived &>(*this).coeffs().y());\n  }\n\n  /**\n   * @brief Rotation.\n   */\n  SO2<Scalar> so2() const\n  {\n    return SO2<Scalar>(c1());  // it's normalized inside SO2\n  }\n\n  /**\n   * @brief Complex number representation.\n   */\n  std::complex<Scalar> c1() const\n  {\n    return std::complex<Scalar>(\n      static_cast<const _Derived &>(*this).coeffs().y(),\n      static_cast<const _Derived &>(*this).coeffs().x());\n  }\n\n  /**\n   * @brief Rotation and scaling action on 2D vector.\n   */\n  template<typename EigenDerived>\n  Eigen::Matrix<Scalar, 2, 1> operator*(const Eigen::MatrixBase<EigenDerived> & v) const\n  {\n    return Base::matrix() * v;\n  }\n};\n\n// \\cond\ntemplate<typename _Scalar>\nclass C1;\n// \\endcond\n\n// \\cond\ntemplate<typename _Scalar>\nstruct liebase_info<C1<_Scalar>>\n{\n  static constexpr bool is_mutable = true;\n\n  using Impl   = C1Impl<_Scalar>;\n  using Scalar = _Scalar;\n\n  template<typename NewScalar>\n  using PlainObject = C1<NewScalar>;\n};\n// \\endcond\n\n/**\n * @brief Storage implementation of C1 Lie group.\n *\n * @see C1Base for memory layout.\n */\ntemplate<typename _Scalar>\nclass C1 : public C1Base<C1<_Scalar>>\n{\n  using Base = C1Base<C1<_Scalar>>;\n  SMOOTH_GROUP_API(C1);\n\npublic:\n  /**\n   * @brief Construct from scaling and angle.\n   *\n   * @param scaling strictly greater than zero.\n   * @param angle angle of rotation (radians).\n   */\n  C1(const Scalar & scaling, const Scalar & angle)\n  {\n    using std::cos, std::sin;\n\n    coeffs_.x() = scaling * sin(angle);\n    coeffs_.y() = scaling * cos(angle);\n  }\n\n  /**\n   * @brief Construct from complex number.\n   *\n   * @param c complex number.\n   */\n  C1(const std::complex<Scalar> & c)\n  {\n    coeffs_.x() = c.imag();\n    coeffs_.y() = c.real();\n  }\n};\n\n// \\cond\ntemplate<typename _Scalar>\nstruct liebase_info<Map<C1<_Scalar>>> : public liebase_info<C1<_Scalar>>\n{};\n// \\endcond\n\n/**\n * @brief Memory mapping of C1 Lie group.\n *\n * @see C1Base for memory layout.\n */\ntemplate<typename _Scalar>\nclass Map<C1<_Scalar>> : public C1Base<Map<C1<_Scalar>>>\n{\n  using Base = C1Base<Map<C1<_Scalar>>>;\n\n  SMOOTH_MAP_API();\n};\n\n// \\cond\ntemplate<typename _Scalar>\nstruct liebase_info<Map<const C1<_Scalar>>> : public liebase_info<C1<_Scalar>>\n{\n  static constexpr bool is_mutable = false;\n};\n// \\endcond\n\n/**\n * @brief Const memory mapping of C1 Lie group.\n *\n * @see C1Base for memory layout.\n */\ntemplate<typename _Scalar>\nclass Map<const C1<_Scalar>> : public C1Base<Map<const C1<_Scalar>>>\n{\n  using Base = C1Base<Map<const C1<_Scalar>>>;\n\n  SMOOTH_CONST_MAP_API();\n};\n\nusing C1f = C1<float>;   ///< C1 with float scalar representation\nusing C1d = C1<double>;  ///< C1 with double scalar representation\n\n}  // namespace smooth\n\n#endif  // SMOOTH__C1_HPP_\n", "meta": {"hexsha": "b2b3634ccfd0f8cf7b428301b2b6bcc576370662", "size": 5716, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/smooth/c1.hpp", "max_stars_repo_name": "tgurriet/smooth", "max_stars_repo_head_hexsha": "c19e35e23c8e0084314726729d0cf6729192240f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2021-07-06T21:05:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T13:26:44.000Z", "max_issues_repo_path": "include/smooth/c1.hpp", "max_issues_repo_name": "tgurriet/smooth", "max_issues_repo_head_hexsha": "c19e35e23c8e0084314726729d0cf6729192240f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 23.0, "max_issues_repo_issues_event_min_datetime": "2021-07-07T21:13:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T04:40:37.000Z", "max_forks_repo_path": "include/smooth/c1.hpp", "max_forks_repo_name": "tgurriet/smooth", "max_forks_repo_head_hexsha": "c19e35e23c8e0084314726729d0cf6729192240f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2021-07-09T07:16:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-12T14:29:44.000Z", "avg_line_length": 22.5928853755, "max_line_length": 88, "alphanum_fraction": 0.6474807558, "num_tokens": 1580, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.6224593452091672, "lm_q1q2_score": 0.468097254251584}}
{"text": "#define BOOST_TEST_MODULE snark_logic_test\n#include <boost/test/included/unit_test.hpp>\n\n#include \"../bin/comparerLogic.h\"\n\nusing namespace nil::crypto3;\nusing namespace nil::crypto3::zk;\n\ntemplate<typename FieldType>\nbool test_bp_input(int minYear, int maxYear, int year) {\n    blueprint<FieldType> bp;\n    ComparerLogic<FieldType> comparerLogic(bp);\n    comparerLogic.generate_r1cs_constraints(bp);\n    comparerLogic.generate_r1cs_witness(bp, minYear, maxYear, year);\n    return bp.is_satisfied();\n}\n\nvoid test_comparerLogic_range(bool isSatisfied, int minYear, int maxYear, int year) {\n    std::cout << \"Testing \" << year <<\" in range (\" << minYear << \", \" << maxYear << \")\" << std::endl;\n    BOOST_CHECK(test_bp_input<field_type>(minYear, maxYear, year) == isSatisfied);\n}\n\n\nBOOST_AUTO_TEST_SUITE(comparerLogic_test_suite)\n\nint minYear = 2,\n    maxYear = 100,\n    yearInside = 5,\n    yearOutsideLess = 1,\n    yearOutsideMore = 101;\n\nBOOST_AUTO_TEST_CASE(comparerLogic_test_valid_ranges) {\n    test_comparerLogic_range(true, minYear, maxYear, yearInside);\n}\n\nBOOST_AUTO_TEST_CASE(comparerLogic_test_invalid_ranges) {\n    test_comparerLogic_range(false, minYear, maxYear, yearOutsideLess);\n    test_comparerLogic_range(false, minYear, maxYear, yearOutsideMore);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "6db69c1160b921fc04a84ce5c7b63f2c0fad3cb2", "size": 1295, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "snark-logic/unit-tests/test.cpp", "max_stars_repo_name": "idealatom/podlodkin-freeton-year-control", "max_stars_repo_head_hexsha": "6aa96e855fe065c9a75c76da976a87fe2d1668e6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "snark-logic/unit-tests/test.cpp", "max_issues_repo_name": "idealatom/podlodkin-freeton-year-control", "max_issues_repo_head_hexsha": "6aa96e855fe065c9a75c76da976a87fe2d1668e6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "snark-logic/unit-tests/test.cpp", "max_forks_repo_name": "idealatom/podlodkin-freeton-year-control", "max_forks_repo_head_hexsha": "6aa96e855fe065c9a75c76da976a87fe2d1668e6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-15T20:27:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-15T20:27:27.000Z", "avg_line_length": 30.8333333333, "max_line_length": 102, "alphanum_fraction": 0.7536679537, "num_tokens": 327, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125848754471, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4680972506369487}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2009 Klaus Spanderen\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n/*! \\file ranluxuniformrng.hpp\n    \\brief \"Luxury\" random number generator.\n*/\n\n#ifndef quantlib_ranlux_uniform_rng_h\n#define quantlib_ranlux_uniform_rng_h\n\n#include <ql/methods/montecarlo/sample.hpp>\n#include <boost/random/ranlux.hpp>\n\nnamespace QuantLib {\n\n    //! Uniform random number generator\n    /*! M. Luescher's \"luxury\" random number generator\n\n        Implementation is a proxy for the corresponding boost random\n        number generator. For more detail see the boost documentation and:\n          M.Luescher, A portable high-quality random number generator for\n          lattice field theory simulations, Comp. Phys. Comm. 79 (1994) 100\n          \n        Available luxury levels:\n        Ranlux3: Any theoretically possible correlations have very small change\n                 of being observed.\n        Ranlux4: highest possible luxury.         \n    */\n    class Ranlux3UniformRng {\n      public:\n        typedef Sample<Real> sample_type;\n\n        explicit Ranlux3UniformRng(Size seed = 19780503U)\n        : ranlux3_(boost::random::ranlux64_base_01(seed)) {}\n\n        sample_type next() const { return {ranlux3_(), 1.0}; }\n\n      private:\n        mutable boost::ranlux64_3_01 ranlux3_;\n    };\n\n    class Ranlux4UniformRng {\n      public:\n        typedef Sample<Real> sample_type;\n\n        explicit Ranlux4UniformRng(Size seed = 19780503U)\n        : ranlux4_(boost::random::ranlux64_base_01(seed)) {}\n\n        sample_type next() const { return {ranlux4_(), 1.0}; }\n\n      private:\n        mutable boost::ranlux64_4_01 ranlux4_;\n    };\n}\n\n\n#endif\n", "meta": {"hexsha": "b4f7f4c0694c67e94de6f8f630e05d628a616810", "size": 2361, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/math/randomnumbers/ranluxuniformrng.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/math/randomnumbers/ranluxuniformrng.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/math/randomnumbers/ranluxuniformrng.hpp", "max_forks_repo_name": "jiangjiali/QuantLib", "max_forks_repo_head_hexsha": "37c98eccfa18a95acb1e98b276831641be92b38e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1663.0, "max_forks_repo_forks_event_min_datetime": "2015-12-17T17:45:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T07:58:29.000Z", "avg_line_length": 31.9054054054, "max_line_length": 79, "alphanum_fraction": 0.6946209233, "num_tokens": 564, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597974, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4680972437179088}}
{"text": "/******************************************************************************\n  This source file is part of the Avogadro project.\n\n  Adapted from Avogadro 1.x with the following authors' permission:\n  Copyright (C) 2007 by Shahzad Ali\n  Copyright (C) 2007 by Ross Braithwaite\n  Copyright (C) 2007 by James Bunt\n  Copyright (C) 2007,2008 by Marcus D. Hanwell\n  Copyright (C) 2006,2007 by Benoit Jacob\n\n  This source code is released under the 3-Clause BSD License, (see \"LICENSE\").\n******************************************************************************/\n\n#include \"bondcentrictool.h\"\n\n#include <avogadro/qtopengl/glwidget.h>\n\n#include <avogadro/rendering/geometrynode.h>\n#include <avogadro/rendering/glrenderer.h>\n#include <avogadro/rendering/groupnode.h>\n#include <avogadro/rendering/linestripgeometry.h>\n#include <avogadro/rendering/meshgeometry.h>\n#include <avogadro/rendering/textlabel3d.h>\n#include <avogadro/rendering/textproperties.h>\n\n#include <avogadro/core/array.h>\n#include <avogadro/core/atom.h>\n#include <avogadro/core/elements.h>\n#include <avogadro/core/vector.h>\n#include <avogadro/qtgui/molecule.h>\n#include <avogadro/qtgui/rwmolecule.h>\n\n#include <QtGui/QIcon>\n#include <QtGui/QMouseEvent>\n#include <QtWidgets/QAction>\n\n#include <Eigen/Geometry>\n\n#include <cmath>\n\n#ifndef M_PI\n#define M_PI 3.14159265358979323846\n#endif\n\nnamespace Avogadro {\nnamespace QtPlugins {\n\nusing Core::Array;\nusing Core::Elements;\nusing QtGui::Molecule;\nusing QtGui::RWAtom;\nusing QtGui::RWBond;\nusing QtGui::RWMolecule;\nusing Rendering::GeometryNode;\nusing Rendering::GroupNode;\nusing Rendering::Identifier;\nusing Rendering::LineStripGeometry;\nusing Rendering::MeshGeometry;\n\nnamespace {\nconst std::string degreeString(\"\u00b0\");\n/// @todo Add wide character support to text renderer.\nconst std::string angstromString(\"\u00c5\");\n\n// Lookup for coloring bond angles:\nconst Vector3ub& getColor(size_t i)\n{\n  static std::vector<Vector3ub> colors;\n  if (colors.empty()) {\n    colors.push_back(Vector3ub(255, 64, 32));\n    colors.push_back(Vector3ub(64, 255, 32));\n    colors.push_back(Vector3ub(32, 64, 255));\n    colors.push_back(Vector3ub(255, 255, 32));\n    colors.push_back(Vector3ub(255, 32, 255));\n    colors.push_back(Vector3ub(32, 255, 255));\n    colors.push_back(Vector3ub(255, 128, 0));\n    colors.push_back(Vector3ub(128, 255, 0));\n    colors.push_back(Vector3ub(0, 255, 128));\n    colors.push_back(Vector3ub(0, 128, 255));\n    colors.push_back(Vector3ub(255, 0, 128));\n    colors.push_back(Vector3ub(128, 0, 255));\n  }\n\n  return colors[i % colors.size()];\n}\n\n// Returns unsigned, smallest angle between v1 and v2\ninline float vectorAngleDegrees(const Vector3f& v1, const Vector3f& v2)\n{\n  const float crossProductNorm(v1.cross(v2).norm());\n  const float dotProduct(v1.dot(v2));\n  return std::atan2(crossProductNorm, dotProduct) * RAD_TO_DEG_F;\n}\n\n// Returns signed, smallest angle between v1 and v2. Sign is determined from a\n// right hand rule around axis.\ninline float vectorAngleDegrees(const Vector3f& v1, const Vector3f& v2,\n                                const Vector3f& axis)\n{\n  const Vector3f crossProduct(v1.cross(v2));\n  const float crossProductNorm(crossProduct.norm());\n  const float dotProduct(v1.dot(v2));\n  const float signDet(crossProduct.dot(axis));\n  const float angle(std::atan2(crossProductNorm, dotProduct) * RAD_TO_DEG_F);\n  return signDet > 0.f ? angle : -angle;\n}\n\n// Convenience quad drawable:\nclass Quad : public MeshGeometry\n{\npublic:\n  Quad() {}\n  ~Quad() override {}\n\n  /**\n   * @brief setQuad Set the four corners of the quad.\n   */\n  void setQuad(const Vector3f& topLeft, const Vector3f& topRight,\n               const Vector3f& bottomLeft, const Vector3f& bottomRight);\n};\n\nvoid Quad::setQuad(const Vector3f& topLeft, const Vector3f& topRight,\n                   const Vector3f& bottomLeft, const Vector3f& bottomRight)\n{\n  const Vector3f bottom = bottomRight - bottomLeft;\n  const Vector3f left = topLeft - bottomLeft;\n  const Vector3f normal = bottom.cross(left).normalized();\n  Array<Vector3f> norms(4, normal);\n\n  Array<Vector3f> verts(4);\n  verts[0] = topLeft;\n  verts[1] = topRight;\n  verts[2] = bottomLeft;\n  verts[3] = bottomRight;\n\n  Array<unsigned int> indices(6);\n  indices[0] = 0;\n  indices[1] = 1;\n  indices[2] = 2;\n  indices[3] = 2;\n  indices[4] = 1;\n  indices[5] = 3;\n\n  clear();\n  addVertices(verts, norms);\n  addTriangles(indices);\n}\n\n// Convenience arc sector drawable:\nclass ArcSector : public MeshGeometry\n{\npublic:\n  ArcSector() {}\n  ~ArcSector() override {}\n\n  /**\n   * Define the sector.\n   * @param origin Center of the circle from which the arc is cut.\n   * @param startEdge A vector defining an leading edge of the sector. The\n   * direction is used to fix the sector's rotation about the origin, and the\n   * length defines the radius of the sector.\n   * @param normal The normal direction to the plane of the sector.\n   * @param degreesCCW The extent of the sector, measured counter-clockwise from\n   * startEdge in degrees.\n   * @param resolutionDeg The radial width of each triangle used in the sector\n   * approximation in degrees. This will be adjusted to fit an integral number\n   * of triangles in the sector. Smaller triangles (better approximations) are\n   * chosen if adjustment is needed.\n   */\n  void setArcSector(const Vector3f& origin, const Vector3f& startEdge,\n                    const Vector3f& normal, float degreesCCW,\n                    float resolutionDeg);\n};\n\nvoid ArcSector::setArcSector(const Vector3f& origin, const Vector3f& startEdge,\n                             const Vector3f& normal, float degreesCCW,\n                             float resolutionDeg)\n{\n  // Prepare rotation, calculate sizes\n  const unsigned int numTriangles =\n    static_cast<unsigned int>(std::fabs(std::ceil(degreesCCW / resolutionDeg)));\n  const size_t numVerts = static_cast<size_t>(numTriangles + 2);\n  const float stepAngleRads =\n    (degreesCCW / static_cast<float>(numTriangles)) * DEG_TO_RAD_F;\n  const Eigen::AngleAxisf rot(stepAngleRads, normal);\n\n  // Generate normal array\n  Array<Vector3f> norms(numVerts, normal);\n\n  // Generate vertices\n  Array<Vector3f> verts(numVerts);\n  Array<Vector3f>::iterator vertsInserter(verts.begin());\n  Array<Vector3f>::iterator vertsEnd(verts.end());\n  Vector3f radial = startEdge;\n  *(vertsInserter++) = origin;\n  *(vertsInserter++) = origin + radial;\n  while (vertsInserter != vertsEnd)\n    *(vertsInserter++) = origin + (radial = rot * radial);\n\n  // Generate indices\n  Array<unsigned int> indices(numTriangles * 3);\n  Array<unsigned int>::iterator indexInserter(indices.begin());\n  Array<unsigned int>::iterator indexEnd(indices.end());\n  for (unsigned int i = 1; indexInserter != indexEnd; ++i) {\n    *(indexInserter++) = 0;\n    *(indexInserter++) = i;\n    *(indexInserter++) = i + 1;\n  }\n\n  clear();\n  addVertices(verts, norms);\n  addTriangles(indices);\n}\n\n// Convenience quad outline drawable:\nclass QuadOutline : public LineStripGeometry\n{\npublic:\n  QuadOutline() {}\n  ~QuadOutline() override {}\n\n  /**\n   * @brief setQuad Set the four corners of the quad.\n   */\n  void setQuad(const Vector3f& topLeft, const Vector3f& topRight,\n               const Vector3f& bottomLeft, const Vector3f& bottomRight,\n               float lineWidth);\n};\n\nvoid QuadOutline::setQuad(const Vector3f& topLeft, const Vector3f& topRight,\n                          const Vector3f& bottomLeft,\n                          const Vector3f& bottomRight, float lineWidth)\n{\n  Array<Vector3f> verts(5);\n  verts[0] = topLeft;\n  verts[1] = topRight;\n  verts[2] = bottomRight;\n  verts[3] = bottomLeft;\n  verts[4] = topLeft;\n\n  clear();\n  addLineStrip(verts, lineWidth);\n}\n\n// Convenience arc drawable:\nclass ArcStrip : public LineStripGeometry\n{\npublic:\n  ArcStrip() {}\n  ~ArcStrip() override {}\n\n  /**\n   * Define the arc.\n   * @param origin Center of the circle from which the arc is cut.\n   * @param start A vector pointing from the origin to the start of the arc.\n   * @param normal The normal direction to the plane of the circle.\n   * @param degreesCCW The extent of the arc, measured counter-clockwise from\n   * start in degrees.\n   * @param resolutionDeg The radial width of each segment used in the arc\n   * approximation, in degrees. This will be adjusted to fit an integral number\n   * of segments into the arc. Smaller segments (better approximations) are\n   * chosen if adjustment is needed.\n   * @param lineWidth The width of the line.\n   */\n  void setArc(const Vector3f& origin, const Vector3f& start,\n              const Vector3f& normal, float degreesCCW, float resolutionDeg,\n              float lineWidth);\n};\n\nvoid ArcStrip::setArc(const Vector3f& origin, const Vector3f& start,\n                      const Vector3f& normal, float degreesCCW,\n                      float resolutionDeg, float lineWidth)\n{\n  // Prepare rotation, calculate sizes\n  const unsigned int resolution =\n    static_cast<unsigned int>(std::fabs(std::ceil(degreesCCW / resolutionDeg)));\n  const size_t numVerts = static_cast<size_t>(resolution + 1);\n  const float stepAngleRads =\n    (degreesCCW / static_cast<float>(resolution)) * DEG_TO_RAD_F;\n  const Eigen::AngleAxisf rot(stepAngleRads, normal);\n\n  // Generate vertices\n  Array<Vector3f> verts(numVerts);\n  Array<Vector3f>::iterator vertsInserter(verts.begin());\n  Array<Vector3f>::iterator vertsEnd(verts.end());\n  Vector3f radial = start;\n  *(vertsInserter++) = origin + radial;\n  while (vertsInserter != vertsEnd)\n    *(vertsInserter++) = origin + (radial = rot * radial);\n\n  clear();\n  addLineStrip(verts, lineWidth);\n}\n\n} // namespace\n\nBondCentricTool::BondCentricTool(QObject* parent_)\n  : QtGui::ToolPlugin(parent_), m_activateAction(new QAction(this)),\n    m_molecule(nullptr), m_renderer(nullptr), m_moveState(IgnoreMove),\n    m_planeSnapIncr(10.f), m_snapPlaneToBonds(true)\n{\n  m_activateAction->setText(tr(\"Bond-Centric Manipulation\"));\n  m_activateAction->setIcon(QIcon(\":/icons/bondcentrictool.png\"));\n  m_activateAction->setToolTip(\n    tr(\"Bond Centric Manipulation Tool\\n\\n\"\n       \"Left Mouse: \\tClick and drag to rotate the view.\\n\"\n       \"Middle Mouse: \\tClick and drag to zoom in or out.\\n\"\n       \"Right Mouse: \\tClick and drag to move the view.\\n\"\n       \"Double-Click: \\tReset the view.\\n\\n\"\n       \"Left Click & Drag on a Bond to set the Manipulation Plane:\\n\"\n       \"Left Click & Drag one of the Atoms in the Bond to change the angle\\n\"\n       \"Right Click & Drag one of the Atoms in the Bond to change the length\"));\n}\n\nBondCentricTool::~BondCentricTool() {}\n\nQWidget* BondCentricTool::toolWidget() const\n{\n  return nullptr;\n}\n\nvoid BondCentricTool::setMolecule(QtGui::Molecule* mol)\n{\n  if (mol && mol->undoMolecule() != m_molecule) {\n    m_molecule = mol->undoMolecule();\n    reset();\n  }\n}\n\nvoid BondCentricTool::setEditMolecule(QtGui::RWMolecule* mol)\n{\n  if (m_molecule != mol) {\n    m_molecule = mol;\n    reset();\n  }\n}\n\nvoid BondCentricTool::setGLWidget(QtOpenGL::GLWidget*) {}\n\nvoid BondCentricTool::setGLRenderer(Rendering::GLRenderer* ren)\n{\n  m_renderer = ren;\n}\n\nQUndoCommand* BondCentricTool::mousePressEvent(QMouseEvent* e)\n{\n  // Don't start a new operation if we're already working:\n  if (m_moveState != IgnoreMove)\n    return nullptr;\n\n  Rendering::Identifier ident = m_renderer->hit(e->pos().x(), e->pos().y());\n\n  // If no hits, return. Also ensure that the hit molecule is the one we expect.\n  const Core::Molecule* mol = &m_molecule->molecule();\n  if (!ident.isValid() || ident.molecule != mol)\n    return nullptr;\n\n  // If the hit is a left click on a bond, make it the selected bond and map\n  // mouse movements to the bond plane rotation.\n  if (ident.type == Rendering::BondType && e->button() == Qt::LeftButton)\n    return initRotatePlane(e, ident);\n\n  // Return if selectedBond is not valid or the hit is not on a bond:\n  if (!m_selectedBond.isValid() || ident.type != Rendering::AtomType)\n    return nullptr;\n\n  // Test if the atom is in the selected bond, or one bond removed.\n  RWAtom clickedAtom = m_molecule->atom(ident.index);\n  RWBond selectedBond = m_selectedBond.bond();\n  bool atomIsInBond = bondContainsAtom(selectedBond, clickedAtom);\n  bool atomIsNearBond = false;\n  RWAtom anchorAtom;\n  if (!atomIsInBond) {\n    Array<RWBond> bonds = m_molecule->bonds(clickedAtom);\n    for (Array<RWBond>::const_iterator it = bonds.begin(), itEnd = bonds.end();\n         it != itEnd; ++it) {\n      RWAtom atom = otherBondedAtom(*it, clickedAtom);\n      if (bondContainsAtom(selectedBond, atom)) {\n        anchorAtom = atom;\n        atomIsNearBond = true;\n        break;\n      }\n    }\n  }\n\n  if (!atomIsInBond && !atomIsNearBond)\n    return nullptr;\n\n  if (m_molecule) {\n    m_molecule->setInteractive(true);\n  }\n\n  // If the hit is a left click on an atom in the selected bond, prepare to\n  // rotate the clicked bond around the other atom in the bond.\n  if (atomIsInBond && e->button() == Qt::LeftButton)\n    return initRotateBondedAtom(e, clickedAtom);\n\n  // If the hit is a right click on an atom in the selected bond, prepare to\n  // change the bond length.\n  if (atomIsInBond && e->button() == Qt::RightButton)\n    return initAdjustBondLength(e, clickedAtom);\n\n  // Is the hit a left click on an atom bonded to an atom in selectedBond?\n  if (atomIsNearBond &&\n      (e->button() == Qt::LeftButton || e->button() == Qt::RightButton)) {\n    return initRotateNeighborAtom(e, clickedAtom, anchorAtom);\n  }\n\n  return nullptr;\n}\n\nQUndoCommand* BondCentricTool::mouseDoubleClickEvent(QMouseEvent* e)\n{\n  if (m_selectedBond.isValid() && e->button() == Qt::LeftButton) {\n    reset();\n    emit drawablesChanged();\n  }\n  return nullptr;\n}\n\nQUndoCommand* BondCentricTool::mouseMoveEvent(QMouseEvent* e)\n{\n  if (m_moveState == IgnoreMove)\n    return nullptr;\n\n  QUndoCommand* result = nullptr;\n\n  switch (m_moveState) {\n    case RotatePlane:\n      result = rotatePlane(e);\n      break;\n    case RotateBondedAtom:\n      result = rotateBondedAtom(e);\n      break;\n    case AdjustBondLength:\n      result = adjustBondLength(e);\n      break;\n    case RotateNeighborAtom:\n      result = rotateNeighborAtom(e);\n      break;\n    default:\n      break;\n  }\n\n  return result;\n}\n\nQUndoCommand* BondCentricTool::mouseReleaseEvent(QMouseEvent*)\n{\n  if (m_moveState != IgnoreMove) {\n    reset(KeepBond);\n    emit drawablesChanged();\n\n    if (m_molecule) {\n      m_molecule->setInteractive(false); // allow an undo now\n    }\n  }\n\n  return nullptr;\n}\n\nvoid BondCentricTool::draw(Rendering::GroupNode& node)\n{\n  RWBond selectedBond = m_selectedBond.bond();\n\n  if (!selectedBond.isValid())\n    return;\n\n  GeometryNode* geo = new GeometryNode;\n  node.addChild(geo);\n\n  switch (m_moveState) {\n    default:\n    case IgnoreMove:\n    case RotatePlane:\n      drawBondQuad(*geo, selectedBond);\n      drawAtomBondAngles(*geo, selectedBond.atom1(), selectedBond);\n      drawAtomBondAngles(*geo, selectedBond.atom2(), selectedBond);\n      break;\n\n    case RotateBondedAtom: {\n      drawBondQuad(*geo, selectedBond);\n\n      RWAtom otherAtom = otherBondedAtom(selectedBond, m_clickedAtom.atom());\n      if (otherAtom.isValid()) {\n        drawAtomBondAngles(*geo, otherAtom, selectedBond);\n      }\n\n      break;\n    }\n\n    case AdjustBondLength:\n      drawBondQuad(*geo, selectedBond);\n      drawBondLengthLabel(*geo, selectedBond);\n      break;\n\n    case RotateNeighborAtom: {\n      RWAtom clickedAtom = m_clickedAtom.atom();\n      RWAtom anchorAtom = m_anchorAtom.atom();\n      RWBond otherBond = m_molecule->bond(clickedAtom, anchorAtom);\n      if (otherBond.isValid())\n        drawBondAngle(*geo, selectedBond, otherBond);\n      break;\n    }\n  }\n}\n\nvoid BondCentricTool::reset(BondCentricTool::ResetBondBehavior bond)\n{\n  if (bond == ResetBond)\n    m_selectedBond.reset();\n\n  m_clickedAtom.reset();\n  m_anchorAtom.reset();\n  m_moveState = IgnoreMove;\n  m_clickedPoint = QPoint();\n}\n\nvoid BondCentricTool::initializeBondVectors()\n{\n  RWBond bond = m_selectedBond.bond();\n  if (bond.isValid()) {\n    m_bondVector = (bond.atom2().position3d().cast<float>() -\n                    bond.atom1().position3d().cast<float>())\n                     .normalized();\n    m_planeNormalMouse = m_bondVector.unitOrthogonal();\n  }\n}\n\nvoid BondCentricTool::updateBondVector()\n{\n  RWBond bond = m_selectedBond.bond();\n  if (bond.isValid()) {\n    m_bondVector = (bond.atom2().position3d().cast<float>() -\n                    bond.atom1().position3d().cast<float>())\n                     .normalized();\n  }\n}\n\nQUndoCommand* BondCentricTool::initRotatePlane(\n  QMouseEvent* e, const Rendering::Identifier& ident)\n{\n  RWBond selectedBond = m_molecule->bond(ident.index);\n  // Get unique id:\n  Index bondUniqueId = m_molecule->bondUniqueId(selectedBond);\n  if (bondUniqueId == MaxIndex)\n    return nullptr; // Something went horribly wrong.\n\n  // Reset the bond vector/plane normal if the bond changed\n  if (bondUniqueId != m_selectedBond.uniqueIdentifier()) {\n    m_selectedBond =\n      QtGui::RWMolecule::PersistentBondType(m_molecule, bondUniqueId);\n    initializeBondVectors();\n  }\n  updatePlaneSnapAngles();\n  updateSnappedPlaneNormal();\n  if (!m_selectedBond.isValid())\n    return nullptr;\n  e->accept();\n  m_moveState = RotatePlane;\n  m_clickedPoint = e->pos();\n  m_lastDragPoint = e->pos();\n  emit drawablesChanged();\n  return nullptr;\n}\n\nQUndoCommand* BondCentricTool::initRotateBondedAtom(\n  QMouseEvent* e, const QtGui::RWAtom& clickedAtom)\n{\n  m_clickedAtom = RWMolecule::PersistentAtomType(clickedAtom);\n  if (!m_clickedAtom.isValid())\n    return nullptr;\n  e->accept();\n  m_moveState = RotateBondedAtom;\n  m_clickedPoint = e->pos();\n  m_lastDragPoint = e->pos();\n  resetFragment();\n  emit drawablesChanged();\n  return nullptr;\n}\n\nQUndoCommand* BondCentricTool::initAdjustBondLength(\n  QMouseEvent* e, const QtGui::RWAtom& clickedAtom)\n{\n  m_clickedAtom = RWMolecule::PersistentAtomType(clickedAtom);\n  if (!m_clickedAtom.isValid())\n    return nullptr;\n  e->accept();\n  m_moveState = AdjustBondLength;\n  m_clickedPoint = e->pos();\n  m_lastDragPoint = e->pos();\n  resetFragment();\n  emit drawablesChanged();\n  return nullptr;\n}\n\nQUndoCommand* BondCentricTool::initRotateNeighborAtom(\n  QMouseEvent* e, const QtGui::RWAtom& clickedAtom,\n  const QtGui::RWAtom& anchorAtom)\n{\n  m_clickedAtom = RWMolecule::PersistentAtomType(clickedAtom);\n  m_anchorAtom = RWMolecule::PersistentAtomType(anchorAtom);\n  if (!m_clickedAtom.isValid() || !m_anchorAtom.isValid())\n    return nullptr;\n  e->accept();\n  m_moveState = RotateNeighborAtom;\n  m_clickedPoint = e->pos();\n  m_lastDragPoint = e->pos();\n  resetFragment();\n  emit drawablesChanged();\n  return nullptr;\n}\n\nQUndoCommand* BondCentricTool::rotatePlane(QMouseEvent* e)\n{\n  // The bond should be valid.\n  const RWBond selectedBond = m_selectedBond.bond();\n  if (!selectedBond.isValid())\n    return nullptr;\n\n  const QPoint deltaDrag = e->pos() - m_lastDragPoint;\n  const Rendering::Camera& camera(m_renderer->camera());\n\n  // Atomic position in world coordinates\n  const Vector3 beginPos(selectedBond.atom1().position3d());\n  const Vector3 endPos(selectedBond.atom2().position3d());\n\n  // Various quantities in window coordinates.\n  const Vector3f beginWin(camera.project(beginPos.cast<float>()));\n  const Vector3f endWin(camera.project(endPos.cast<float>()));\n  Vector3f bondVecWin(endWin - beginWin);\n  bondVecWin.z() = 0.f;\n  // Points into the viewing volume from camera:\n  const Vector3f zAxisWin(0.f, 0.f, 1.f);\n  // In plane of screen, orthogonal to bond:\n  const Vector3f orthoWin(zAxisWin.cross(bondVecWin).normalized());\n  const Vector3f dragWin(static_cast<float>(deltaDrag.x()),\n                         static_cast<float>(deltaDrag.y()), 0.f);\n\n  // Compute the rotation. Not quite sure what's going on here, this is just\n  // ported from Avogadro 1. It doesn't seem right that rotation would be in\n  // degrees (it's the result of a dot product) and I think the fact that the\n  // DEG_TO_RAD conversion results in a useful angle is just a happy\n  // coincidence. But it works quite well.\n  const float rotation = dragWin.dot(orthoWin) / orthoWin.norm();\n  const Eigen::AngleAxisf rotator(rotation * DEG_TO_RAD_F, m_bondVector);\n\n  // Rotate\n  m_planeNormalMouse = rotator * m_planeNormalMouse;\n  updateSnappedPlaneNormal();\n  emit drawablesChanged();\n\n  m_lastDragPoint = e->pos();\n  return nullptr;\n}\n\nQUndoCommand* BondCentricTool::rotateBondedAtom(QMouseEvent* e)\n{\n  // Ensure that the mouse has moved a reasonable amount:\n  if ((m_lastDragPoint - e->pos()).manhattanLength() < 2)\n    return nullptr;\n\n  RWBond bond = m_selectedBond.bond();\n  RWAtom clickedAtom = m_clickedAtom.atom();\n  RWAtom centerAtom = otherBondedAtom(bond, clickedAtom);\n\n  // Sanity check:\n  if (!bond.isValid() || !clickedAtom.isValid() || !centerAtom.isValid())\n    return nullptr;\n\n  // Compute the transformation:\n  //   - Rotation axis is m_planeNormal\n  //   - Rotation angle is:\n  //       - magnitude is angle between initial click and current pos around\n  //         center atom (performed in 2D).\n  //       - sign is based on whether m_planeNormal is pointing into/out of the\n  //         screen.\n  const Rendering::Camera& camera(m_renderer->camera());\n\n  // Get the window coordinates of the relevant points\n  const Vector3f centerPos(centerAtom.position3d().cast<float>());\n  const Vector3f centerWin(camera.project(centerPos));\n  const Vector2f centerWin2(centerWin.head<2>());\n  const Vector2f lastDragWin(\n    static_cast<float>(m_lastDragPoint.x()),\n    static_cast<float>(camera.height() - m_lastDragPoint.y()));\n  const Vector2f dragWin(static_cast<float>(e->pos().x()),\n                         static_cast<float>(camera.height() - e->pos().y()));\n\n  // Compute the angle between last drag and current drag positions\n  const Vector2f lastDragWinVec((lastDragWin - centerWin2).normalized());\n  const Vector2f dragWinVec((dragWin - centerWin2).normalized());\n  const float crossProductNorm(lastDragWinVec.x() * dragWinVec.y() -\n                               lastDragWinVec.y() * dragWinVec.x());\n  const float dotProduct(lastDragWinVec.dot(dragWinVec));\n  const float angle(std::atan2(crossProductNorm, dotProduct));\n\n  // Figure out if the sign needs to be reversed:\n  const Vector3f centerPlusNormal(centerPos + m_planeNormal);\n  const Vector3f centerPlusNormalWin(camera.project(centerPlusNormal));\n  bool reverseSign = (centerPlusNormalWin.z() - centerWin.z()) >= 0;\n\n  // Build transform\n  m_transform.setIdentity();\n  m_transform.translate(centerPos);\n  m_transform.rotate(\n    Eigen::AngleAxisf(reverseSign ? -angle : angle, m_planeNormal));\n  m_transform.translate(-centerPos);\n\n  // Build the fragment if needed:\n  if (m_fragment.empty())\n    buildFragment(bond, clickedAtom);\n\n  // Perform transformation\n  transformFragment();\n  updateBondVector();\n  m_molecule->emitChanged(Molecule::Modified | Molecule::Atoms);\n  emit drawablesChanged();\n\n  m_lastDragPoint = e->pos();\n  return nullptr;\n}\n\nQUndoCommand* BondCentricTool::adjustBondLength(QMouseEvent* e)\n{\n  // Ensure that the mouse has moved a reasonable amount:\n  if ((m_lastDragPoint - e->pos()).manhattanLength() < 2)\n    return nullptr;\n\n  RWBond selectedBond = m_selectedBond.bond();\n  RWAtom clickedAtom = m_clickedAtom.atom();\n\n  // Sanity check:\n  if (!selectedBond.isValid() || !clickedAtom.isValid())\n    return nullptr;\n\n  const Rendering::Camera& camera(m_renderer->camera());\n  RWAtom otherAtom = otherBondedAtom(selectedBond, clickedAtom);\n\n  const Vector2f curPosWin(static_cast<float>(e->pos().x()),\n                           static_cast<float>(e->pos().y()));\n  const Vector2f lastPosWin(static_cast<float>(m_lastDragPoint.x()),\n                            static_cast<float>(m_lastDragPoint.y()));\n\n  const Vector3f bond(clickedAtom.position3d().cast<float>() -\n                      otherAtom.position3d().cast<float>());\n  const Vector3f mouse(camera.unProject(curPosWin) -\n                       camera.unProject(lastPosWin));\n\n  const Vector3f displacement((mouse.dot(bond) / bond.squaredNorm()) * bond);\n\n  // Build transform\n  m_transform.setIdentity();\n  m_transform.translate(displacement);\n\n  // Build the fragment if needed:\n  if (m_fragment.empty())\n    buildFragment(selectedBond, clickedAtom);\n\n  // Perform transformation\n  transformFragment();\n  m_molecule->emitChanged(QtGui::Molecule::Modified | QtGui::Molecule::Atoms);\n  emit drawablesChanged();\n\n  m_lastDragPoint = e->pos();\n  return nullptr;\n}\n\nQUndoCommand* BondCentricTool::rotateNeighborAtom(QMouseEvent* e)\n{\n  // Ensure that the mouse has moved a reasonable amount:\n  if ((m_lastDragPoint - e->pos()).manhattanLength() < 2)\n    return nullptr;\n\n  RWBond selectedBond = m_selectedBond.bond();\n  // Atom that was clicked\n  RWAtom clickedAtom = m_clickedAtom.atom();\n  // Atom in selected bond also attached to clickedAtom\n  RWAtom anchorAtom = m_anchorAtom.atom();\n  // The \"other\" atom in selected bond\n  RWAtom otherAtom = otherBondedAtom(selectedBond, anchorAtom);\n\n  // Sanity check:\n  if (!selectedBond.isValid() || !anchorAtom.isValid() ||\n      !otherAtom.isValid() || !clickedAtom.isValid()) {\n    return nullptr;\n  }\n\n  const Rendering::Camera& camera(m_renderer->camera());\n\n  // Compute the angle between last drag and current drag positions\n  const Vector3f center(anchorAtom.position3d().cast<float>());\n  const Vector3f centerProj(camera.project(center));\n  const Vector2f centerWin(centerProj.head<2>());\n  const Vector2f curWin(static_cast<float>(e->pos().x()),\n                        static_cast<float>(camera.height() - e->pos().y()));\n  const Vector2f lastWin(\n    static_cast<float>(m_lastDragPoint.x()),\n    static_cast<float>(camera.height() - m_lastDragPoint.y()));\n  const Vector2f curVecWin((curWin - centerWin).normalized());\n  const Vector2f lastVecWin((lastWin - centerWin).normalized());\n  const float crossProductNorm(lastVecWin.x() * curVecWin.y() -\n                               lastVecWin.y() * curVecWin.x());\n  const float dotProduct(lastVecWin.dot(curVecWin));\n  const float angle(std::atan2(crossProductNorm, dotProduct));\n\n  // Figure out if the sign needs to be reversed:\n  const Vector3f other(otherAtom.position3d().cast<float>());\n  const Vector3f otherProj(camera.project(other));\n  const bool reverseSign = otherProj.z() <= centerProj.z();\n\n  // Axis of rotation\n  const Vector3f axis((center - other).normalized());\n\n  // Build transform\n  m_transform.setIdentity();\n  m_transform.translate(center);\n  m_transform.rotate(Eigen::AngleAxisf(reverseSign ? -angle : angle, axis));\n  m_transform.translate(-center);\n\n  // Build the fragment if needed:\n  if (m_fragment.empty())\n    buildFragment(selectedBond, anchorAtom);\n\n  // Perform transformation\n  transformFragment();\n  updateBondVector();\n  m_molecule->emitChanged(QtGui::Molecule::Modified | QtGui::Molecule::Atoms);\n  emit drawablesChanged();\n\n  m_lastDragPoint = e->pos();\n\n  return nullptr;\n}\n\nvoid BondCentricTool::drawBondQuad(Rendering::GeometryNode& node,\n                                   const RWBond& bond) const\n{\n  const Vector3f atom1Pos(bond.atom1().position3d().cast<float>());\n  const Vector3f atom2Pos(bond.atom2().position3d().cast<float>());\n  Vector3f offset(m_bondVector.cross(m_planeNormal));\n\n  const Vector3f v1(atom1Pos + offset);\n  const Vector3f v2(atom2Pos + offset);\n  const Vector3f v3(atom1Pos - offset);\n  const Vector3f v4(atom2Pos - offset);\n\n  Quad* quad = new Quad;\n  node.addDrawable(quad);\n  quad->setColor(Vector3ub(63, 127, 255));\n  quad->setOpacity(127);\n  quad->setRenderPass(Rendering::TranslucentPass);\n  quad->setQuad(v1, v2, v3, v4);\n\n  QuadOutline* quadOutline = new QuadOutline;\n  node.addDrawable(quadOutline);\n  quadOutline->setColor(Vector3ub(63, 127, 255));\n  quadOutline->setRenderPass(Rendering::OpaquePass);\n  quadOutline->setQuad(v1, v2, v3, v4, 1.f);\n\n  // If the plane is rotating, show a hint for the unsnapped plane.\n  if (m_moveState == RotatePlane) {\n    Vector3f moffset(m_bondVector.cross(m_planeNormalMouse));\n\n    const Vector3f mv1(atom1Pos + moffset);\n    const Vector3f mv2(atom2Pos + moffset);\n    const Vector3f mv3(atom1Pos - moffset);\n    const Vector3f mv4(atom2Pos - moffset);\n\n    QuadOutline* mouseQuadOutline = new QuadOutline;\n    node.addDrawable(mouseQuadOutline);\n    mouseQuadOutline->setColor(Vector3ub(255, 255, 255));\n    mouseQuadOutline->setOpacity(127);\n    mouseQuadOutline->setRenderPass(Rendering::TranslucentPass);\n    mouseQuadOutline->setQuad(mv1, mv2, mv3, mv4, 1.f);\n  }\n}\n\nvoid BondCentricTool::drawBondAngle(Rendering::GeometryNode& node,\n                                    const QtGui::RWBond& selectedBond,\n                                    const QtGui::RWBond& movingBond) const\n{\n  // Draw the selected bond quad as usual\n  drawBondQuad(node, selectedBond);\n\n  // Determine the atom shared between the bonds (atom1).\n  RWAtom atom1;\n  RWAtom atom2;\n  if (selectedBond.atom1() == movingBond.atom1() ||\n      selectedBond.atom2() == movingBond.atom1()) {\n    atom1 = movingBond.atom1();\n    atom2 = movingBond.atom2();\n  } else if (selectedBond.atom1() == movingBond.atom2() ||\n             selectedBond.atom2() == movingBond.atom2()) {\n    atom1 = movingBond.atom2();\n    atom2 = movingBond.atom1();\n  }\n\n  if (!atom1.isValid())\n    return;\n\n  // Add another quad in the plane normal to\n  // m_bondVector.cross(movingBondVector)\n  const Vector3f a1(atom1.position3d().cast<float>());\n  const Vector3f a2(atom2.position3d().cast<float>());\n  const Vector3f movingBondVector(a2 - a1);\n  const Vector3f movingBondUnitVector(movingBondVector.normalized());\n  // calculate a vector in the plane spanned by movingBondVector and\n  // m_bondVector that is orthogonal to m_bondVector, then project\n  // movingBondVector onto it. This is used to calculate the 'new' a2.\n  const Vector3f movingBondNormal(m_bondVector.cross(movingBondUnitVector));\n  const Vector3f newA2Direction(movingBondNormal.cross(m_bondVector));\n  const Vector3f movingBondVectorProj(movingBondVector.dot(newA2Direction) *\n                                      newA2Direction);\n  const Vector3f newA2(a1 + movingBondVectorProj);\n  const Vector3f& movingBondOffset(m_bondVector);\n  const Vector3f v1(a1 + movingBondOffset);\n  const Vector3f v2(newA2 + movingBondOffset);\n  const Vector3f v3(a1 - movingBondOffset);\n  const Vector3f v4(newA2 - movingBondOffset);\n\n  Quad* quad = new Quad;\n  node.addDrawable(quad);\n  quad->setColor(Vector3ub(63, 127, 255));\n  quad->setOpacity(127);\n  quad->setRenderPass(Rendering::TranslucentPass);\n  quad->setQuad(v1, v2, v3, v4);\n\n  QuadOutline* quadOutline = new QuadOutline;\n  node.addDrawable(quadOutline);\n  quadOutline->setColor(Vector3ub(63, 127, 255));\n  quadOutline->setRenderPass(Rendering::OpaquePass);\n  quadOutline->setQuad(v1, v2, v3, v4, 1.f);\n\n  // Add an arc and label to show a bit more info:\n  const Vector3f selectedBondOffset(m_planeNormal.cross(m_bondVector));\n  const float radius(movingBondVector.norm() * 0.75f);\n  Vector3f startEdge(newA2Direction * radius);\n  Vector3f normal(m_bondVector);\n  float angle = vectorAngleDegrees(startEdge, selectedBondOffset, normal);\n  float displayAngle = std::fabs(angle);\n\n  ArcSector* sect = new ArcSector;\n  node.addDrawable(sect);\n  sect->setColor(Vector3ub(255, 127, 63));\n  sect->setOpacity(127);\n  sect->setRenderPass(Rendering::TranslucentPass);\n  sect->setArcSector(a1, startEdge, normal, angle, 5.f);\n\n  ArcStrip* arc = new ArcStrip;\n  node.addDrawable(arc);\n  arc->setColor(Vector3ub(255, 127, 63));\n  arc->setRenderPass(Rendering::OpaquePass);\n  arc->setArc(a1, startEdge, normal, angle, 5.f, 1.f);\n\n  const Vector3f& textPos(a1);\n\n  Rendering::TextLabel3D* label = new Rendering::TextLabel3D;\n  label->setText(tr(\"%L1\u00b0\").arg(displayAngle, 5, 'f', 1).toStdString());\n  label->setRenderPass(Rendering::Overlay3DPass);\n  label->setAnchor(textPos);\n  node.addDrawable(label);\n\n  Rendering::TextProperties tprop;\n  tprop.setAlign(Rendering::TextProperties::HCenter,\n                 Rendering::TextProperties::VCenter);\n  tprop.setFontFamily(Rendering::TextProperties::SansSerif);\n  tprop.setColorRgb(255, 200, 64);\n  label->setTextProperties(tprop);\n}\n\nvoid BondCentricTool::drawBondLengthLabel(Rendering::GeometryNode& node,\n                                          const QtGui::RWBond& bond)\n{\n  const Vector3f startPos(bond.atom1().position3d().cast<float>());\n  const Vector3f endPos(bond.atom2().position3d().cast<float>());\n  const Vector3f bondCenter((startPos + endPos) * 0.5f);\n  const Vector3f bondVector(endPos - startPos);\n\n  Rendering::TextLabel3D* label = new Rendering::TextLabel3D;\n  label->setText(tr(\"%L1 \u00c5\").arg(bondVector.norm(), 4, 'f', 2).toStdString());\n  label->setRenderPass(Rendering::Overlay3DPass);\n  label->setAnchor(bondCenter);\n  node.addDrawable(label);\n\n  Rendering::TextProperties tprop;\n  tprop.setAlign(Rendering::TextProperties::HCenter,\n                 Rendering::TextProperties::VCenter);\n  tprop.setFontFamily(Rendering::TextProperties::SansSerif);\n  tprop.setColorRgb(255, 200, 64);\n  label->setTextProperties(tprop);\n}\n\nvoid BondCentricTool::drawAtomBondAngles(Rendering::GeometryNode& node,\n                                         const RWAtom& atom,\n                                         const RWBond& anchorBond)\n{\n  const Array<RWBond> bonds = m_molecule->bonds(atom);\n  Array<RWBond>::const_iterator bondIter(bonds.begin());\n  Array<RWBond>::const_iterator bondEnd(bonds.end());\n  size_t count = 0;\n  while (bondIter != bondEnd) {\n    if (*bondIter != anchorBond)\n      drawAtomBondAngle(node, atom, anchorBond, *bondIter, getColor(count++));\n    ++bondIter;\n  }\n}\n\nvoid BondCentricTool::drawAtomBondAngle(Rendering::GeometryNode& node,\n                                        const QtGui::RWAtom& atom,\n                                        const QtGui::RWBond& anchorBond,\n                                        const QtGui::RWBond& otherBond,\n                                        const Vector3ub& color)\n{\n  const RWAtom otherAtom = otherBondedAtom(otherBond, atom);\n  const RWAtom otherAnchorAtom = otherBondedAtom(anchorBond, atom);\n\n  const Vector3f atomPos(atom.position3d().cast<float>());\n  const Vector3f otherAtomPos(otherAtom.position3d().cast<float>());\n  const Vector3f otherAnchorAtomPos(otherAnchorAtom.position3d().cast<float>());\n\n  const Vector3f otherVector(otherAtomPos - atomPos);\n  const Vector3f anchorVector(otherAnchorAtomPos - atomPos);\n  const Vector3f anchorUnitVector(anchorVector.normalized());\n\n  const float radius(otherVector.norm() * 0.75f);\n  const Vector3f& origin(atomPos);\n  const Vector3f start(anchorUnitVector * radius);\n  const Vector3f axis(anchorVector.cross(otherVector).normalized());\n  const float angle = vectorAngleDegrees(otherVector, anchorVector);\n  const Vector3f& labelPos(otherAtomPos);\n\n  ArcSector* sect = new ArcSector;\n  node.addDrawable(sect);\n  sect->setColor(color);\n  sect->setOpacity(127);\n  sect->setRenderPass(Rendering::TranslucentPass);\n  sect->setArcSector(origin, start, axis, angle, 5.f);\n\n  ArcStrip* arc = new ArcStrip;\n  node.addDrawable(arc);\n  arc->setColor(color);\n  arc->setRenderPass(Rendering::OpaquePass);\n  arc->setArc(origin, start, axis, angle, 5.f, 1.f);\n\n  Rendering::TextLabel3D* label = new Rendering::TextLabel3D;\n  label->setText(tr(\"%L1\u00b0\").arg(angle, 6, 'f', 1).toStdString());\n  label->setRenderPass(Rendering::Overlay3DPass);\n  label->setAnchor(labelPos);\n  node.addDrawable(label);\n\n  Rendering::TextProperties tprop;\n  tprop.setAlign(Rendering::TextProperties::HCenter,\n                 Rendering::TextProperties::VCenter);\n  tprop.setFontFamily(Rendering::TextProperties::SansSerif);\n  tprop.setColorRgb(color);\n  label->setTextProperties(tprop);\n}\n\ninline bool BondCentricTool::bondContainsAtom(const QtGui::RWBond& bond,\n                                              const QtGui::RWAtom& atom) const\n{\n  return atom == bond.atom1() || atom == bond.atom2();\n}\n\ninline QtGui::RWAtom BondCentricTool::otherBondedAtom(\n  const QtGui::RWBond& bond, const QtGui::RWAtom& atom) const\n{\n  return bond.atom1() == atom ? bond.atom2() : bond.atom1();\n}\n\ninline void BondCentricTool::transformFragment() const\n{\n  // Convert the internal float matrix to use the same precision as the atomic\n  // coordinates.\n  Eigen::Transform<Real, 3, Eigen::Affine> transform(m_transform.cast<Real>());\n  for (std::vector<int>::const_iterator it = m_fragment.begin(),\n                                        itEnd = m_fragment.end();\n       it != itEnd; ++it) {\n    RWAtom atom = m_molecule->atomByUniqueId(*it);\n    if (atom.isValid()) {\n      Vector3 pos = atom.position3d();\n      pos = transform * pos;\n      atom.setPosition3d(pos);\n    }\n  }\n}\n\nvoid BondCentricTool::updatePlaneSnapAngles()\n{\n  m_planeSnapRef = m_bondVector.unitOrthogonal();\n  m_planeSnapAngles.clear();\n\n  // Add bond angles if requested:\n  RWBond selectedBond = m_selectedBond.bond();\n  if (m_snapPlaneToBonds && selectedBond.isValid()) {\n    const RWAtom atom1 = selectedBond.atom1();\n    const RWAtom atom2 = selectedBond.atom2();\n    for (int i = 0; i < 2; ++i) {\n      const RWAtom& atom = i == 0 ? atom1 : atom2;\n      const Vector3f atomPos(atom.position3d().cast<float>());\n      const Array<RWBond> bonds = m_molecule->bonds(atom);\n      for (std::vector<RWBond>::const_iterator it = bonds.begin(),\n                                               itEnd = bonds.end();\n           it != itEnd; ++it) {\n        if (*it != selectedBond) {\n          const RWAtom otherAtom(otherBondedAtom(*it, atom));\n          const Vector3f otherAtomPos(otherAtom.position3d().cast<float>());\n          const Vector3f otherBondVector(otherAtomPos - atomPos);\n          // Project otherBondVector into the plane normal to m_bondVector\n          // (e.g. the rejection of otherBondVector onto m_bondVector)\n          const Vector3f rej(\n            otherBondVector -\n            (otherBondVector.dot(m_bondVector) * m_bondVector));\n          float angle(vectorAngleDegrees(m_planeSnapRef, rej, m_bondVector));\n          m_planeSnapAngles.insert(angle);\n          angle += 180.f;\n          if (angle > 180.f)\n            angle -= 360.f;\n          m_planeSnapAngles.insert(angle);\n        }\n      }\n    }\n  }\n\n  // Add default increments only if they are more than 5 degrees away\n  // from a bond angle.\n  const float minDist(5.f);\n  for (float angle = -180.f; angle < 180.f; angle += m_planeSnapIncr) {\n    std::set<float>::const_iterator upper(m_planeSnapAngles.lower_bound(angle));\n    if (upper != m_planeSnapAngles.end()) {\n      if (*upper - minDist < angle)\n        continue;\n      if (upper != m_planeSnapAngles.begin()) {\n        std::set<float>::const_iterator lower(upper);\n        std::advance(lower, -1);\n        if (*lower + minDist > angle)\n          continue;\n      }\n      m_planeSnapAngles.insert(angle);\n    }\n  }\n}\n\n// There may be some weirdness around +/-180 since we don't check for\n// wrapping, but it should be fine for this use case.\nvoid BondCentricTool::updateSnappedPlaneNormal()\n{\n  const Vector3f mousePlaneVector(m_planeNormalMouse.cross(m_bondVector));\n  const float angle(\n    vectorAngleDegrees(m_planeSnapRef, mousePlaneVector, m_bondVector));\n  float snappedAngle(angle);\n  std::set<float>::const_iterator upper(m_planeSnapAngles.lower_bound(angle));\n  if (upper != m_planeSnapAngles.end()) {\n    if (upper != m_planeSnapAngles.begin()) {\n      std::set<float>::const_iterator lower(upper);\n      std::advance(lower, -1);\n      float upperDist = std::fabs(angle - *upper);\n      float lowerDist = std::fabs(angle - *lower);\n      snappedAngle = upperDist < lowerDist ? *upper : *lower;\n    } else {\n      snappedAngle = *upper;\n    }\n  }\n\n  if (angle == snappedAngle) {\n    // If the angle didn't change, keep on keepin' on:\n    m_planeNormal = m_planeNormalMouse;\n  } else {\n    // Otherwise, update the vector.\n    const Vector3f planeVector =\n      Eigen::AngleAxisf(snappedAngle * DEG_TO_RAD_F, m_bondVector) *\n      m_planeSnapRef;\n    m_planeNormal = planeVector.cross(m_bondVector);\n  }\n}\n\ninline bool BondCentricTool::fragmentHasAtom(int uid) const\n{\n  return std::find(m_fragment.begin(), m_fragment.end(), uid) !=\n         m_fragment.end();\n}\n\nvoid BondCentricTool::buildFragment(const QtGui::RWBond& bond,\n                                    const QtGui::RWAtom& startAtom)\n{\n  m_fragment.clear();\n  if (!buildFragmentRecurse(bond, startAtom, startAtom)) {\n    // If this returns false, then a cycle has been found. Only move startAtom\n    // in this case.\n    m_fragment.clear();\n  }\n  m_fragment.push_back(m_molecule->atomUniqueId(startAtom));\n}\n\nbool BondCentricTool::buildFragmentRecurse(const QtGui::RWBond& bond,\n                                           const QtGui::RWAtom& startAtom,\n                                           const QtGui::RWAtom& currentAtom)\n{\n  Array<RWBond> bonds = m_molecule->bonds(currentAtom);\n  typedef std::vector<RWBond>::const_iterator BondIter;\n  for (BondIter it = bonds.begin(), itEnd = bonds.end(); it != itEnd; ++it) {\n    if (*it != bond) { // Skip the current bond\n      RWAtom nextAtom = otherBondedAtom(*it, currentAtom);\n      if (nextAtom != startAtom) {\n        // Skip atoms that have already been added. This prevents infinite\n        // recursion on cycles in the fragments\n        int uid = m_molecule->atomUniqueId(nextAtom);\n        if (!fragmentHasAtom(uid)) {\n          m_fragment.push_back(uid);\n          if (!buildFragmentRecurse(*it, startAtom, nextAtom))\n            return false;\n        }\n      } else {\n        // If we've reached startAtom, then we've found a cycle that indicates\n        // no moveable fragment exists.\n        return false;\n      } // nextAtom != startAtom else\n    }   // *it != bond\n  }     // foreach bond\n  return true;\n}\n\n} // namespace QtPlugins\n} // namespace Avogadro\n", "meta": {"hexsha": "c7251ca6a29de90362f711c23b6bf533fcc63b18", "size": 41723, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "avogadro/qtplugins/bondcentrictool/bondcentrictool.cpp", "max_stars_repo_name": "sneznaj/avogadrolibs", "max_stars_repo_head_hexsha": "7558da2fffdfe86c7c626735dca44890174f6ae4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 244.0, "max_stars_repo_stars_event_min_datetime": "2015-09-09T15:08:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T17:44:21.000Z", "max_issues_repo_path": "avogadro/qtplugins/bondcentrictool/bondcentrictool.cpp", "max_issues_repo_name": "sneznaj/avogadrolibs", "max_issues_repo_head_hexsha": "7558da2fffdfe86c7c626735dca44890174f6ae4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 670.0, "max_issues_repo_issues_event_min_datetime": "2015-05-08T18:59:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T19:47:08.000Z", "max_forks_repo_path": "avogadro/qtplugins/bondcentrictool/bondcentrictool.cpp", "max_forks_repo_name": "sneznaj/avogadrolibs", "max_forks_repo_head_hexsha": "7558da2fffdfe86c7c626735dca44890174f6ae4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 129.0, "max_forks_repo_forks_event_min_datetime": "2015-01-28T01:18:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T08:50:25.000Z", "avg_line_length": 34.0318107667, "max_line_length": 80, "alphanum_fraction": 0.685545143, "num_tokens": 10690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.46809724371790873}}
{"text": "//---------------------------------------------------------------------------\n//\n//    FCST: Fuel Cell Simulation Toolbox\n//\n//    Copyright (C) 2006-13 by Energy Systems Design Laboratory, University of Alberta\n//\n//    This software is distributed under the MIT License.\n//    For more information, see the README file in /doc/LICENSE\n//\n//    - Class: PSD_test.cc\n//    - Description: Unit testing class for PSD\n//    - Developers: Prafful Mangal\n//    - Id: $Id: PSD_HI_test.cc 2605 2014-08-15 03:36:44Z secanell $ \n//\n//---------------------------------------------------------------------------\n\n#include \"PSD_HI_test.h\"\n#include <boost/concept_check.hpp>\n\n//-------------------------------------------------------------\nvoid PSD_HI_Test::setup()\n{\n    ParameterHandler param;\n    \n    boost::shared_ptr<FuelCellShop::Layer::GasDiffusionLayer<dim> > CGDL;\n    \n    FuelCellShop::Layer::GasDiffusionLayer<dim>::declare_GasDiffusionLayer_parameters(\"Cathode gas diffusion layer\", param);\n    \n    param.enter_subsection(\"Fuel cell data\");\n    {\n        param.enter_subsection(\"Cathode gas diffusion layer\");\n        {\n            \n            psd_object.declare_parameters(param);\n            \n            param.enter_subsection(\"PSD parameters\");\n            {\n                param.enter_subsection(\"BasePSD\");\n                {\n                    \n                    //param.set(\"porosity\", \"0.84\");\n                    param.set(\"Gamma\", \"0.0728\");\n                    param.set(\"Contact angle\", \"1.396\");\n                    param.set(\"lambda\", \"1.0\");\n                    param.set(\"Volume fraction Hydrophilic\", \"0.7\");\n                    param.set(\"probability P_b\", \"1.0\");\n                    param.set(\"Mode probability global\", \"0.72, 0.28\");\n                    param.set(\"Mode characteristic radius global\", \"34.0, 14.2\");\n                    param.set(\"Mode width global\", \"0.35, 1.0\");\n                    param.set(\"psd type\", \"HIPSD\"); \n                    \n                    param.enter_subsection(\"HIPSD\");\n                    {\n                        param.set(\"Hydrophilic Mode probability global\", \"0.72, 0.28\");\n                        param.set(\"Hydrophilic Mode characteristic radius global\", \"34.0, 14.2\");\n                        param.set(\"Hydrophilic Mode width global\", \"0.35, 1.0\");\n                        param.set(\"capillay pressure\", \"10100.0\");   \n                    }\n                    param.leave_subsection(); \n                    \n                }\n                param.leave_subsection();\n            }\n            param.leave_subsection();\n            \n            param.enter_subsection(\"Generic data\");\n            {\n                param.set(\"Porosity\", \"0.84\");\n            }\n            param.leave_subsection();\n        }\n        param.leave_subsection();\n    }\n    param.leave_subsection();\n    \n    \n    \n    param.enter_subsection(\"Fuel cell data\");\n    {\n        param.enter_subsection(\"Cathode gas diffusion layer\");\n        {\n            psd_object.initialize(param);\n        }\n        param.leave_subsection();\n    }\n    param.leave_subsection();\n    \n    CGDL = FuelCellShop::Layer::GasDiffusionLayer<dim>::create_GasDiffusionLayer(\"Cathode gas diffusion layer\",param);\n    \n    psd_object.set_porosity (CGDL->get_porosity());\n    \n}\n\n//-------------------------------------------------------------\nvoid PSD_HI_Test::testcompute_rc_HI()\n{\n    \n    std::vector<double> answer(0.0);\n    \n    psd_object.set_critical_radius();\n    \n    psd_object.get_critical_radius(answer);\n    \n    double expectedAnswer = 2.507024;\n  \n    std::ostringstream streamOut;\n    streamOut <<\"The value of the rc_HI (microns) is: \"<<answer[0]<<\". The expected value is: \"<<expectedAnswer<<std::endl;\n    TEST_ASSERT_DELTA_MSG(expectedAnswer, answer[0], 1e-6, streamOut.str().c_str()); \n}\n\n//-------------------------------------------------------------\nvoid PSD_HI_Test::testcompute_k_sat_HI()\n{\n    double answer(0.0);\n    \n    psd_object.set_saturation();\n  \n    psd_object.get_global_saturated_permeability(answer); \n    \n    double expectedAnswer = 58.1327578;\n  \n    std::ostringstream streamOut;\n    streamOut <<\"The value of the k_sat_HI (microns^2) is: \"<<answer<<\". The expected value is: \"<<expectedAnswer<<std::endl;\n    TEST_ASSERT_DELTA_MSG(expectedAnswer, answer, 1e-7, streamOut.str().c_str());\n}\n\n//-------------------------------------------------------------\nvoid PSD_HI_Test::testcompute_sat_HI()\n{\n    std::vector<double> answer(0.0);\n  \n    psd_object.get_saturation(answer); \n    \n    double expectedAnswer = 0.0081234135;\n  \n    std::ostringstream streamOut;\n    streamOut <<\"The value of the Saturation_HI is: \"<<answer[0]<<\". The expected value is: \"<<expectedAnswer<<std::endl;\n    TEST_ASSERT_DELTA_MSG(expectedAnswer, answer[0], 1e-7, streamOut.str().c_str());\n}\n\n//-------------------------------------------------------------\nvoid PSD_HI_Test::testcompute_k_L_HI()\n{\n    std::vector<double> answer(0.0);\n    psd_object.get_pore_HI_liquid_saturated_permeability(answer);  \n    \n    double expectedAnswer = 2.9317742175e-9;\n  \n    std::ostringstream streamOut;\n    streamOut <<\"The value of the K_L_HI(microns^2) is: \"<<answer[0]<<\". The expected value is: \"<<expectedAnswer<<std::endl;\n    TEST_ASSERT_DELTA_MSG(expectedAnswer, answer[0], 1e-13, streamOut.str().c_str());\n}\n\n//-------------------------------------------------------------\nvoid PSD_HI_Test::testcompute_kr_L_HI()\n{\n    std::vector<double> answer(0.0);\n    \n    psd_object.get_relative_liquid_permeability(answer);  \n    \n    double expectedAnswer = 5.04323951277e-11;\n  \n    std::ostringstream streamOut;\n    streamOut <<\"The value of the Kr_L_HI is: \"<<answer[0]<<\". The expected value is: \"<<expectedAnswer<<std::endl;\n    TEST_ASSERT_DELTA_MSG(expectedAnswer, answer[0], 1e-15, streamOut.str().c_str());\n}\n\n//-------------------------------------------------------------\nvoid PSD_HI_Test::testcompute_k_G_HI()\n{\n    std::vector<double> answer(0.0);\n  \n    psd_object.get_pore_HI_gas_saturated_permeability(answer);  \n    \n    double expectedAnswer = 40.0344411166;\n  \n    std::ostringstream streamOut;\n    streamOut <<\"The value of the K_G_HI(microns^2) is: \"<<answer[0]<<\". The expected value is: \"<<expectedAnswer<<std::endl;\n    TEST_ASSERT_DELTA_MSG(expectedAnswer, answer[0], 1e-5, streamOut.str().c_str());\n}\n\n//-------------------------------------------------------------\nvoid PSD_HI_Test::testcompute_kr_G_HI()\n{\n    std::vector<double> answer(0.0);\n  \n    psd_object.get_relative_gas_permeability(answer);  \n    \n    double expectedAnswer = 0.6886726621;\n  \n    std::ostringstream streamOut;\n    streamOut <<\"The value of the Kr_G_HI is: \"<<answer[0]<<\". The expected value is: \"<<expectedAnswer<<std::endl;\n    TEST_ASSERT_DELTA_MSG(expectedAnswer, answer[0], 1e-7, streamOut.str().c_str());\n}\n\n//-------------------------------------------------------------\nvoid PSD_HI_Test::testcompute_interfacial_area_per_volume_HI()\n{\n    std::vector<double> answer(0.0);\n  \n    psd_object.get_liquid_gas_interfacial_surface(answer);  \n    double expectedAnswer = 0.000113962;\n  \n    std::ostringstream streamOut;\n    streamOut <<\"The value of the interfacial area per unit volume for hydrophilic pores is: \"<<answer[0]<<\". The expected value is: \"<<expectedAnswer<<std::endl;\n    TEST_ASSERT_DELTA_MSG(expectedAnswer, answer[0], 1e-9, streamOut.str().c_str());\n}\n\n//-------------------------------------------------------------\n//-------------------------------------------------------------", "meta": {"hexsha": "fb6ebcb8b44633c393303b0f180dc0c639c484d9", "size": 7538, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/fcst/unit_tests/source/PSD_HI_test.cc", "max_stars_repo_name": "OpenFcst/OpenFcst0.2", "max_stars_repo_head_hexsha": "770a0d9b145cd39c3a065b653a53b5082dc5d85c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2015-05-08T18:19:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-21T17:22:47.000Z", "max_issues_repo_path": "src/fcst/unit_tests/source/PSD_HI_test.cc", "max_issues_repo_name": "OpenFcst/OpenFcst0.2", "max_issues_repo_head_hexsha": "770a0d9b145cd39c3a065b653a53b5082dc5d85c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2016-09-05T10:17:36.000Z", "max_issues_repo_issues_event_max_datetime": "2016-12-11T18:23:06.000Z", "max_forks_repo_path": "src/fcst/unit_tests/source/PSD_HI_test.cc", "max_forks_repo_name": "OpenFcst/OpenFcst0.2", "max_forks_repo_head_hexsha": "770a0d9b145cd39c3a065b653a53b5082dc5d85c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-15T16:45:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-15T16:45:47.000Z", "avg_line_length": 35.8952380952, "max_line_length": 162, "alphanum_fraction": 0.5508092332, "num_tokens": 1703, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.46809724371790873}}
{"text": "\n\n/* --------------------------------------------------------------------- \n * \n * Copyright (C) 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: Justin O'Connor, Colorado State University, 2021. \n */ \n\n\n// @sect3{Preliminaries}  \n#include <deal.II/base/quadrature_lib.h> \n#include <deal.II/base/function.h> \n#include <deal.II/base/tensor.h> \n#include <deal.II/base/timer.h> \n#include <deal.II/base/signaling_nan.h> \n\n#include <deal.II/lac/block_vector.h> \n#include <deal.II/lac/full_matrix.h> \n#include <deal.II/lac/block_sparse_matrix.h> \n#include <deal.II/lac/linear_operator.h> \n#include <deal.II/lac/packaged_operation.h> \n#include <deal.II/lac/sparse_direct.h> \n#include <deal.II/lac/affine_constraints.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\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_values.h> \n#include <deal.II/fe/fe_dgq.h> \n#include <deal.II/fe/fe_system.h> \n#include <deal.II/fe/fe_q.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\n#include <iostream> \n#include <fstream> \n#include <algorithm> \n\n// \u4ee5\u4e0a\u662f\u76f8\u5f53\u5e38\u89c1\u7684\u5305\u542b\u6587\u4ef6\u3002\u8fd9\u4e9b\u6587\u4ef6\u8fd8\u5305\u62ec\u7a00\u758f\u76f4\u63a5\u7c7b\u7684\u6587\u4ef6 SparseDirectUMFPACK\u3002\u8fd9\u4e0d\u662f\u89e3\u51b3\u5927\u578b\u7ebf\u6027\u95ee\u9898\u7684\u6700\u6709\u6548\u7684\u65b9\u6cd5\uff0c\u4f46\u73b0\u5728\u53ef\u4ee5\u4e86\u3002\n\n// \u50cf\u5f80\u5e38\u4e00\u6837\uff0c\u6211\u4eec\u628a\u6240\u6709\u7684\u4e1c\u897f\u90fd\u653e\u5230\u4e00\u4e2a\u5171\u540c\u7684\u547d\u540d\u7a7a\u95f4\u91cc\u3002\u7136\u540e\uff0c\u6211\u4eec\u5f00\u59cb\u58f0\u660e\u4e00\u4e9b\u5e38\u6570\u7684\u7b26\u53f7\u540d\u79f0\uff0c\u8fd9\u4e9b\u5e38\u6570\u5c06\u5728\u672c\u6559\u7a0b\u4e2d\u4f7f\u7528\u3002\u5177\u4f53\u6765\u8bf4\uff0c\u6211\u4eec\u5728\u8fd9\u4e2a\u7a0b\u5e8f\u4e2d\u6709*\u591a\u7684\u53d8\u91cf\uff08\u5f53\u7136\u662f\u5bc6\u5ea6\u548c\u4f4d\u79fb\uff0c\u4f46\u4e5f\u6709\u672a\u8fc7\u6ee4\u7684\u5bc6\u5ea6\u548c\u76f8\u5f53\u591a\u7684\u62c9\u683c\u6717\u65e5\u4e58\u6570\uff09\u3002\u6211\u4eec\u5f88\u5bb9\u6613\u5fd8\u8bb0\u8fd9\u4e9b\u53d8\u91cf\u5728\u6c42\u89e3\u5411\u91cf\u4e2d\u7684\u54ea\u4e2a\u4f4d\u7f6e\uff0c\u800c\u4e14\u8bd5\u56fe\u7528\u6570\u5b57\u6765\u8868\u793a\u8fd9\u4e9b\u5411\u91cf\u5206\u91cf\u662f\u4e00\u4e2a\u9519\u8bef\u7684\u5904\u65b9\u3002\u76f8\u53cd\uff0c\u6211\u4eec\u5b9a\u4e49\u7684\u9759\u6001\u53d8\u91cf\u53ef\u4ee5\u5728\u6240\u6709\u8fd9\u4e9b\u5730\u65b9\u4f7f\u7528\uff0c\u800c\u4e14\u53ea\u9700\u521d\u59cb\u5316\u4e00\u6b21\u3002\u5728\u5b9e\u8df5\u4e2d\uff0c\u8fd9\u5c06\u5bfc\u81f4\u4e00\u4e9b\u5197\u957f\u7684\u8868\u8fbe\u5f0f\uff0c\u4f46\u5b83\u4eec\u66f4\u5177\u53ef\u8bfb\u6027\uff0c\u800c\u4e14\u4e0d\u592a\u53ef\u80fd\u51fa\u9519\u3002\n\n// \u4e00\u4e2a\u7c7b\u4f3c\u7684\u95ee\u9898\u51fa\u73b0\u5728\u7cfb\u7edf\u77e9\u9635\u548c\u5411\u91cf\u4e2d\u5757\u7684\u6392\u5e8f\u4e0a\u3002\u77e9\u9635\u4e2d\u6709 $9\\times 9$ \u5757\uff0c\u800c\u4e14\u5f88\u96be\u8bb0\u4f4f\u54ea\u4e2a\u662f\u54ea\u4e2a\u3002\u5bf9\u8fd9\u4e9b\u5757\u4e5f\u4f7f\u7528\u7b26\u53f7\u540d\u79f0\u8981\u5bb9\u6613\u5f97\u591a\u3002\n\n// \u6700\u540e\uff0c\u6211\u4eec\u4e3a\u6211\u4eec\u5c06\u8981\u4f7f\u7528\u7684\u8fb9\u754c\u6307\u6807\u5f15\u5165\u7b26\u53f7\u540d\u79f0\uff0c\u4e0e  step-19  \u4e2d\u7684\u7cbe\u795e\u76f8\u540c\u3002\n\n// \u5728\u6240\u6709\u8fd9\u4e9b\u60c5\u51b5\u4e0b\uff0c\u6211\u4eec\u5c06\u8fd9\u4e9b\u53d8\u91cf\u58f0\u660e\u4e3a\u547d\u540d\u7a7a\u95f4\u4e2d\u7684\u6210\u5458\u3002\u5728\u6c42\u89e3\u7ec4\u4ef6\u7684\u60c5\u51b5\u4e0b\uff0c\u8fd9\u4e9b\u53d8\u91cf\u7684\u5177\u4f53\u6570\u503c\u53d6\u51b3\u4e8e\u7a7a\u95f4\u7ef4\u5ea6\uff0c\u56e0\u6b64\u6211\u4eec\u4f7f\u7528[\u6a21\u677f\u53d8\u91cf](https:en.cppreference.com/w/cpp/language/variable_template)\u6765\u4f7f\u53d8\u91cf\u7684\u6570\u503c\u53d6\u51b3\u4e8e\u6a21\u677f\u53c2\u6570\uff0c\u5c31\u50cf\u6211\u4eec\u7ecf\u5e38\u4f7f\u7528\u6a21\u677f\u51fd\u6570\u4e00\u6837\u3002\n\nnamespace SAND \n{ \n  using namespace dealii; \n\n// \u8fd9\u4e2a\u547d\u540d\u7a7a\u95f4\u8bb0\u5f55\u4e86\u6211\u4eec\u7684\u6709\u9650\u5143\u7cfb\u7edf\u4e2d\u4e0e\u6bcf\u4e2a\u53d8\u91cf\u76f8\u5bf9\u5e94\u7684\u7b2c\u4e00\u4e2a\u7ec4\u4ef6\u3002\n\n  namespace SolutionComponents \n  { \n    template <int dim> \n    constexpr unsigned int density = 0; \n    template <int dim> \n    constexpr unsigned int displacement = 1; \n    template <int dim> \n    constexpr unsigned int unfiltered_density = 1 + dim; \n    template <int dim> \n    constexpr unsigned int displacement_multiplier = 2 + dim; \n    template <int dim> \n    constexpr unsigned int unfiltered_density_multiplier = 2 + 2 * dim; \n    template <int dim> \n    constexpr unsigned int density_lower_slack = 3 + 2 * dim; \n    template <int dim> \n    constexpr unsigned int density_lower_slack_multiplier = 4 + 2 * dim; \n    template <int dim> \n    constexpr unsigned int density_upper_slack = 5 + 2 * dim; \n    template <int dim> \n    constexpr unsigned int density_upper_slack_multiplier = 6 + 2 * dim; \n  } // namespace SolutionComponents \n\n// \u8fd9\u662f\u4e00\u4e2a\u547d\u540d\u7a7a\u95f4\uff0c\u5b83\u8bb0\u5f55\u4e86\u54ea\u4e2a\u533a\u5757\u5bf9\u5e94\u4e8e\u54ea\u4e2a\u53d8\u91cf\u3002\n\n  namespace SolutionBlocks \n  { \n    constexpr unsigned int density                        = 0; \n    constexpr unsigned int displacement                   = 1; \n    constexpr unsigned int unfiltered_density             = 2; \n    constexpr unsigned int displacement_multiplier        = 3; \n    constexpr unsigned int unfiltered_density_multiplier  = 4; \n    constexpr unsigned int density_lower_slack            = 5; \n    constexpr unsigned int density_lower_slack_multiplier = 6; \n    constexpr unsigned int density_upper_slack            = 7; \n    constexpr unsigned int density_upper_slack_multiplier = 8; \n  } // namespace SolutionBlocks \n\n  namespace BoundaryIds \n  { \n    constexpr types::boundary_id down_force = 101; \n    constexpr types::boundary_id no_force   = 102; \n  } // namespace BoundaryIds \n\n  namespace ValueExtractors \n  { \n    template <int dim> \n    const FEValuesExtractors::Scalar \n      densities(SolutionComponents::density<dim>); \n    template <int dim> \n    const FEValuesExtractors::Vector \n      displacements(SolutionComponents::displacement<dim>); \n    template <int dim> \n    const FEValuesExtractors::Scalar \n      unfiltered_densities(SolutionComponents::unfiltered_density<dim>); \n    template <int dim> \n    const FEValuesExtractors::Vector displacement_multipliers( \n      SolutionComponents::displacement_multiplier<dim>); \n    template <int dim> \n    const FEValuesExtractors::Scalar unfiltered_density_multipliers( \n      SolutionComponents::unfiltered_density_multiplier<dim>); \n    template <int dim> \n    const FEValuesExtractors::Scalar \n      density_lower_slacks(SolutionComponents::density_lower_slack<dim>); \n    template <int dim> \n    const FEValuesExtractors::Scalar density_lower_slack_multipliers( \n      SolutionComponents::density_lower_slack_multiplier<dim>); \n    template <int dim> \n    const FEValuesExtractors::Scalar \n      density_upper_slacks(SolutionComponents::density_upper_slack<dim>); \n    template <int dim> \n    const FEValuesExtractors::Scalar density_upper_slack_multipliers( \n      SolutionComponents::density_upper_slack_multiplier<dim>); \n  } // namespace ValueExtractors \n// @sect3{The SANDTopOpt main class}  \n\n// \u63a5\u4e0b\u6765\u662f\u8fd9\u4e2a\u95ee\u9898\u7684\u4e3b\u7c7b\u3002\u5927\u591a\u6570\u51fd\u6570\u90fd\u9075\u5faa\u6559\u7a0b\u7a0b\u5e8f\u7684\u5e38\u89c4\u547d\u540d\u65b9\u5f0f\uff0c\u4e0d\u8fc7\u6709\u51e0\u4e2a\u51fd\u6570\u56e0\u4e3a\u957f\u5ea6\u95ee\u9898\u88ab\u4ece\u901a\u5e38\u79f0\u4e3a`setup_system()`\u7684\u51fd\u6570\u4e2d\u5206\u79bb\u51fa\u6765\uff0c\u8fd8\u6709\u4e00\u4e9b\u51fd\u6570\u662f\u5904\u7406\u4f18\u5316\u7b97\u6cd5\u7684\u5404\u4e2a\u65b9\u9762\u7684\u3002\n\n// \u4f5c\u4e3a\u989d\u5916\u7684\u5956\u52b1\uff0c\u8be5\u7a0b\u5e8f\u5c06\u8ba1\u7b97\u51fa\u7684\u8bbe\u8ba1\u5199\u6210STL\u6587\u4ef6\uff0c\u4f8b\u5982\uff0c\u53ef\u4ee5\u5c06\u5176\u53d1\u9001\u7ed93D\u6253\u5370\u673a\u3002\n\n  template <int dim> \n  class SANDTopOpt \n  { \n  public: \n    SANDTopOpt(); \n\n    void run(); \n\n  private: \n    void create_triangulation(); \n\n    void setup_boundary_values(); \n\n    void setup_block_system(); \n\n    void setup_filter_matrix(); \n\n    void assemble_system(); \n\n    BlockVector<double> solve(); \n\n    std::pair<double, double> \n    calculate_max_step_size(const BlockVector<double> &state, \n                            const BlockVector<double> &step) const; \n\n    BlockVector<double> \n    calculate_test_rhs(const BlockVector<double> &test_solution) const; \n\n    double calculate_exact_merit(const BlockVector<double> &test_solution); \n\n    BlockVector<double> find_max_step(); \n\n    BlockVector<double> compute_scaled_step(const BlockVector<double> &state, \n                                            const BlockVector<double> &step, \n                                            const double descent_requirement); \n\n    bool check_convergence(const BlockVector<double> &state); \n\n    void output_results(const unsigned int j) const; \n\n    void write_as_stl(); \n\n    std::set<typename Triangulation<dim>::cell_iterator> \n    find_relevant_neighbors( \n      typename Triangulation<dim>::cell_iterator cell) const; \n\n// \u5927\u90e8\u5206\u7684\u6210\u5458\u53d8\u91cf\u4e5f\u662f\u6807\u51c6\u7684\u3002\u4f46\u662f\uff0c\u6709\u4e00\u4e9b\u53d8\u91cf\u662f\u4e13\u95e8\u4e0e\u4f18\u5316\u7b97\u6cd5\u6709\u5173\u7684\uff08\u6bd4\u5982\u4e0b\u9762\u7684\u5404\u79cd\u6807\u91cf\u56e0\u5b50\uff09\uff0c\u4ee5\u53ca\u8fc7\u6ee4\u5668\u77e9\u9635\uff0c\u4ee5\u786e\u4fdd\u8bbe\u8ba1\u4fdd\u6301\u5e73\u7a33\u3002\n\n    Triangulation<dim>        triangulation; \n    FESystem<dim>             fe; \n    DoFHandler<dim>           dof_handler; \n    AffineConstraints<double> constraints; \n\n    std::map<types::global_dof_index, double> boundary_values; \n\n    BlockSparsityPattern      sparsity_pattern; \n    BlockSparseMatrix<double> system_matrix; \n\n    SparsityPattern      filter_sparsity_pattern; \n    SparseMatrix<double> filter_matrix; \n\n    BlockVector<double> system_rhs; \n    BlockVector<double> nonlinear_solution; \n\n    const double density_ratio; \n    const double density_penalty_exponent; \n    const double filter_r; \n    double       penalty_multiplier; \n    double       barrier_size; \n\n    TimerOutput timer; \n  }; \n// @sect3{Constructor and set-up functions}  \n\n// \u6211\u4eec\u521d\u59cb\u5316\u4e00\u4e2a\u75312  $\\times$  dim `FE_Q(1)`\u5143\u7d20\u7ec4\u6210\u7684FES\u7cfb\u7edf\uff0c\u7528\u4e8e\u4f4d\u79fb\u53d8\u91cf\u53ca\u5176\u62c9\u683c\u6717\u65e5\u4e58\u6570\uff0c\u4ee5\u53ca7 `FE_DGQ(0)`\u5143\u7d20\u3002 \u8fd9\u4e9b\u7247\u72b6\u5e38\u6570\u51fd\u6570\u7528\u4e8e\u4e0e\u5bc6\u5ea6\u76f8\u5173\u7684\u53d8\u91cf\uff1a\u5bc6\u5ea6\u672c\u8eab\u3001\u672a\u8fc7\u6ee4\u7684\u5bc6\u5ea6\u3001\u7528\u4e8e\u672a\u8fc7\u6ee4\u7684\u5bc6\u5ea6\u7684\u4e0b\u9650\u548c\u4e0a\u9650\u7684\u677e\u5f1b\u53d8\u91cf\uff0c\u7136\u540e\u662f\u7528\u4e8e\u8fc7\u6ee4\u548c\u672a\u8fc7\u6ee4\u7684\u5bc6\u5ea6\u4e4b\u95f4\u7684\u8fde\u63a5\u4ee5\u53ca\u4e0d\u7b49\u5f0f\u7ea6\u675f\u7684\u62c9\u683c\u6717\u65e5\u4e58\u5b50\u3002\n\n// \u8fd9\u4e9b\u5143\u7d20\u51fa\u73b0\u7684\u987a\u5e8f\u5728\u4e0a\u9762\u6709\u8bb0\u8f7d\u3002\n\n  template <int dim> \n  SANDTopOpt<dim>::SANDTopOpt() \n    : fe(FE_DGQ<dim>(0), \n         1, \n         (FESystem<dim>(FE_Q<dim>(1) ^ dim)), \n         1, \n         FE_DGQ<dim>(0), \n         1, \n         (FESystem<dim>(FE_Q<dim>(1) ^ dim)), \n         1, \n         FE_DGQ<dim>(0), \n         5) \n    , dof_handler(triangulation) \n    , density_ratio(.5) \n    , density_penalty_exponent(3) \n    , filter_r(.251) \n    , penalty_multiplier(1) \n    , timer(std::cout, TimerOutput::summary, TimerOutput::wall_times) \n  { \n    Assert(dim > 1, ExcNotImplemented()); \n  } \n\n// \u7136\u540e\uff0c\u7b2c\u4e00\u6b65\u662f\u521b\u5efa\u4e0e\u4ecb\u7ecd\u4e2d\u7684\u95ee\u9898\u63cf\u8ff0\u76f8\u5339\u914d\u7684\u4e09\u89d2\u5f62--\u4e00\u4e2a6\u4e581\u7684\u77e9\u5f62\uff08\u6216\u8005\u4e00\u4e2a6\u4e581\u4e581\u76843D\u76d2\u5b50\uff09\uff0c\u5728\u8fd9\u4e2a\u76d2\u5b50\u7684\u9876\u90e8\u4e2d\u5fc3\u5c06\u65bd\u52a0\u4e00\u4e2a\u529b\u3002\u7136\u540e\uff0c\u8fd9\u4e2a\u4e09\u89d2\u5f62\u88ab\u5747\u5300\u5730\u7ec6\u5316\u82e5\u5e72\u6b21\u3002\n\n// \u4e0e\u672c\u7a0b\u5e8f\u7684\u5176\u4ed6\u90e8\u5206\u76f8\u6bd4\uff0c\u8fd9\u4e2a\u51fd\u6570\u7279\u522b\u5047\u5b9a\u6211\u4eec\u662f\u57282D\u4e2d\uff0c\u5982\u679c\u6211\u4eec\u60f3\u8f6c\u52303D\u6a21\u62df\uff0c\u5c31\u9700\u8981\u8fdb\u884c\u4fee\u6539\u3002\u6211\u4eec\u901a\u8fc7\u51fd\u6570\u9876\u90e8\u7684\u65ad\u8a00\u6765\u786e\u4fdd\u6ca1\u6709\u4eba\u8bd5\u56fe\u4e0d\u7ecf\u4fee\u6539\u5c31\u610f\u5916\u5730\u5728\u4e09\u7ef4\u4e2d\u8fd0\u884c\u3002\n\n  template <int dim> \n  void SANDTopOpt<dim>::create_triangulation() \n  { \n    Assert(dim == 2, ExcNotImplemented()); \n    GridGenerator::subdivided_hyper_rectangle(triangulation, \n                                              {6, 1}, \n                                              Point<dim>(0, 0), \n                                              Point<dim>(6, 1)); \n\n    triangulation.refine_global(3); \n\n// \u7b2c\u4e8c\u6b65\u662f\u5c06\u8fb9\u754c\u6307\u6807\u5e94\u7528\u4e8e\u8fb9\u754c\u7684\u4e00\u90e8\u5206\u3002\u4e0b\u9762\u7684\u4ee3\u7801\u5206\u522b\u4e3a\u76d2\u5b50\u7684\u5e95\u90e8\u3001\u9876\u90e8\u3001\u5de6\u4fa7\u548c\u53f3\u4fa7\u7684\u8fb9\u754c\u5206\u914d\u4e86\u8fb9\u754c\u6307\u793a\u5668\u3002\u9876\u90e8\u8fb9\u754c\u7684\u4e2d\u5fc3\u533a\u57df\u88ab\u8d4b\u4e88\u4e00\u4e2a\u5355\u72ec\u7684\u8fb9\u754c\u6307\u793a\u5668\u3002\u8fd9\u5c31\u662f\u6211\u4eec\u8981\u65bd\u52a0\u5411\u4e0b\u529b\u7684\u5730\u65b9\u3002\n\n    for (const auto &cell : triangulation.active_cell_iterators()) \n      { \n        for (const auto &face : cell->face_iterators()) \n          { \n            if (face->at_boundary()) \n              { \n                const auto center = face->center(); \n                if (std::fabs(center(1) - 1) < 1e-12) \n                  { \n                    if ((std::fabs(center(0) - 3) < .3)) \n                      face->set_boundary_id(BoundaryIds::down_force); \n                    else \n                      face->set_boundary_id(BoundaryIds::no_force); \n                  } \n                else \n                  face->set_boundary_id(BoundaryIds::no_force); \n              } \n          } \n      } \n  } \n\n// \u63a5\u4e0b\u6765\uff0c\u786e\u5b9a\u7531\u4e8e\u8fb9\u754c\u503c\u800c\u4ea7\u751f\u7684\u7ea6\u675f\u3002 \u57df\u7684\u5e95\u89d2\u5728 $y$ \u65b9\u5411\u4fdd\u6301\u4e0d\u53d8--\u5de6\u4e0b\u89d2\u4e5f\u5728 $x$ \u65b9\u5411\u3002deal.II\u901a\u5e38\u8ba4\u4e3a\u8fb9\u754c\u503c\u662f\u9644\u7740\u5728\u8fb9\u754c\u7684\u7247\u6bb5\u4e0a\u7684\uff0c\u5373\u9762\uff0c\u800c\u4e0d\u662f\u5355\u4e2a\u9876\u70b9\u3002\u7684\u786e\uff0c\u4ece\u6570\u5b66\u4e0a\u8bb2\uff0c\u5bf9\u4e8e\u65e0\u7a77\u5927\u7684\u504f\u5fae\u5206\u65b9\u7a0b\uff0c\u6211\u4eec\u4e0d\u80fd\u628a\u8fb9\u754c\u503c\u5206\u914d\u7ed9\u5355\u4e2a\u70b9\u3002\u4f46\u662f\uff0c\u7531\u4e8e\u6211\u4eec\u8bd5\u56fe\u91cd\u73b0\u4e00\u4e2a\u5e7f\u6cdb\u4f7f\u7528\u7684\u57fa\u51c6\uff0c\u6211\u4eec\u8fd8\u662f\u8981\u8fd9\u6837\u505a\uff0c\u5e76\u7262\u8bb0\u6211\u4eec\u6709\u4e00\u4e2a\u6709\u9650\u7ef4\u7684\u95ee\u9898\uff0c\u5728\u5355\u4e2a\u8282\u70b9\u4e0a\u65bd\u52a0\u8fb9\u754c\u6761\u4ef6\u662f\u6709\u6548\u7684\u3002\n\n  template <int dim> \n  void SANDTopOpt<dim>::setup_boundary_values() \n  { \n    boundary_values.clear(); \n    for (const auto &cell : dof_handler.active_cell_iterators()) \n      { \n        for (const auto &face : cell->face_iterators()) \n          { \n            if (face->at_boundary()) \n              { \n                const auto center = face->center(); \n\n// \u68c0\u67e5\u5f53\u524d\u9762\u662f\u5426\u5728\u5e95\u5c42\u8fb9\u754c\u4e0a\uff0c\u5982\u679c\u662f\uff0c\u5219\u68c0\u67e5\u5176\u9876\u70b9\u4e4b\u4e00\u662f\u5426\u53ef\u80fd\u662f\u5de6\u5e95\u5c42\u6216\u53f3\u5e95\u5c42\u9876\u70b9\u3002\n\n                if (std::fabs(center(1) - 0) < 1e-12) \n                  { \n                    for (const auto vertex_number : cell->vertex_indices()) \n                      { \n                        const auto vert = cell->vertex(vertex_number); \n\n                        if (std::fabs(vert(0) - 0) < 1e-12 && \n                            std::fabs(vert(1) - 0) < 1e-12) \n                          { \n                            types::global_dof_index x_displacement = \n                              cell->vertex_dof_index(vertex_number, 0); \n                            types::global_dof_index y_displacement = \n                              cell->vertex_dof_index(vertex_number, 1); \n                            types::global_dof_index x_displacement_multiplier = \n                              cell->vertex_dof_index(vertex_number, 2); \n                            types::global_dof_index y_displacement_multiplier = \n                              cell->vertex_dof_index(vertex_number, 3); \n\n                            boundary_values[x_displacement]            = 0; \n                            boundary_values[y_displacement]            = 0; \n                            boundary_values[x_displacement_multiplier] = 0; \n                            boundary_values[y_displacement_multiplier] = 0; \n                          } \n\n                        else if (std::fabs(vert(0) - 6) < 1e-12 && \n                                 std::fabs(vert(1) - 0) < 1e-12) \n                          { \n                            types::global_dof_index y_displacement = \n                              cell->vertex_dof_index(vertex_number, 1); \n                            types::global_dof_index y_displacement_multiplier = \n                              cell->vertex_dof_index(vertex_number, 3); \n\n                            boundary_values[y_displacement]            = 0; \n                            boundary_values[y_displacement_multiplier] = 0; \n                          } \n                      } \n                  } \n              } \n          } \n      } \n  } \n// @sect3{Setting up block matrices and vectors}  \n\n// \u4e0b\u4e00\u4e2a\u51fd\u6570\u5236\u4f5c\u4e86\u4e00\u4e2a\u5de8\u5927\u76849\u4e589\u7684\u5757\u72b6\u77e9\u9635\uff0c\u5e76\u4e14\u8fd8\u8bbe\u7f6e\u4e86\u5fc5\u8981\u7684\u5757\u72b6\u5411\u91cf\u3002 \u8fd9\u4e2a\u77e9\u9635\u7684\u7a00\u758f\u5ea6\u6a21\u5f0f\u5305\u62ec\u6ee4\u6ce2\u77e9\u9635\u7684\u7a00\u758f\u5ea6\u6a21\u5f0f\u3002\u5b83\u8fd8\u521d\u59cb\u5316\u4e86\u6211\u4eec\u5c06\u4f7f\u7528\u7684\u4efb\u4f55\u5757\u5411\u91cf\u3002\n\n// \u8bbe\u7f6e\u5757\u672c\u8eab\u5e76\u4e0d\u590d\u6742\uff0c\u5e76\u4e14\u9075\u5faa\u8bf8\u5982  step-22  \u7b49\u7a0b\u5e8f\u4e2d\u5df2\u7ecf\u5b8c\u6210\u7684\u5de5\u4f5c\uff0c\u4f8b\u5982\u3002\n\n  template <int dim> \n  void SANDTopOpt<dim>::setup_block_system() \n  { \n    std::vector<unsigned int> block_component(9, 2); \n    block_component[0] = 0; \n    block_component[1] = 1; \n    const std::vector<types::global_dof_index> dofs_per_block = \n      DoFTools::count_dofs_per_fe_block(dof_handler, block_component); \n\n    const types::global_dof_index                     n_p = dofs_per_block[0]; \n    const types::global_dof_index                     n_u = dofs_per_block[1]; \n    const std::vector<BlockVector<double>::size_type> block_sizes = { \n      n_p, n_u, n_p, n_u, n_p, n_p, n_p, n_p, n_p}; \n\n    BlockDynamicSparsityPattern dsp(9, 9); \n    for (unsigned int k = 0; k < 9; ++k) \n      for (unsigned int j = 0; j < 9; ++j) \n        dsp.block(j, k).reinit(block_sizes[j], block_sizes[k]); \n    dsp.collect_sizes(); \n\n// \u8be5\u51fd\u6570\u7684\u5927\u90e8\u5206\u5185\u5bb9\u662f\u8bbe\u7f6e\u8fd9\u4e9b\u5757\u4e2d\u54ea\u4e9b\u5c06\u5b9e\u9645\u5305\u542b\u4efb\u4f55\u5185\u5bb9\uff0c\u5373\u54ea\u4e9b\u53d8\u91cf\u4e0e\u54ea\u4e9b\u5176\u4ed6\u53d8\u91cf\u76f8\u8026\u5408\u3002\u8fd9\u5f88\u9ebb\u70e6\uff0c\u4f46\u4e5f\u662f\u5fc5\u8981\u7684\uff0c\u4ee5\u786e\u4fdd\u6211\u4eec\u4e0d\u4f1a\u4e3a\u6211\u4eec\u7684\u77e9\u9635\u5206\u914d\u5927\u91cf\u7684\u6761\u76ee\uff0c\u800c\u8fd9\u4e9b\u6761\u76ee\u6700\u7ec8\u4f1a\u53d8\u6210\u96f6\u3002\n\n// \u4f60\u5728\u4e0b\u9762\u770b\u5230\u7684\u5177\u4f53\u6a21\u5f0f\u53ef\u80fd\u9700\u8981\u5728\u7eb8\u4e0a\u753b\u4e00\u6b21\uff0c\u4f46\u662f\u4ece\u6211\u4eec\u5728\u6bcf\u6b21\u975e\u7ebf\u6027\u8fed\u4ee3\u4e2d\u5fc5\u987b\u7ec4\u88c5\u7684\u53cc\u7ebf\u6027\u5f62\u5f0f\u7684\u8bb8\u591a\u9879\u6765\u770b\uff0c\u5b83\u662f\u76f8\u5bf9\u76f4\u63a5\u7684\u65b9\u5f0f\u3002\n\n// \u4f7f\u7528\u547d\u540d\u7a7a\u95f4 \"SolutionComponents \"\u4e2d\u5b9a\u4e49\u7684\u7b26\u53f7\u540d\u79f0\u6709\u52a9\u4e8e\u7406\u89e3\u4e0b\u9762\u6bcf\u4e2a\u9879\u6240\u5bf9\u5e94\u7684\u5185\u5bb9\uff0c\u4f46\u5b83\u4e5f\u4f7f\u8868\u8fbe\u5f0f\u53d8\u5f97\u5197\u957f\u800c\u4e0d\u6d41\u7545\u3002\u50cf `coupling[SolutionComponents::density_upper_slack_multiplier<dim>][SolutionComponents::density<dim>]` \u8fd9\u6837\u7684\u672f\u8bed\u8bfb\u8d77\u6765\u5c31\u4e0d\u592a\u987a\u53e3\uff0c\u8981\u4e48\u5fc5\u987b\u5206\u6210\u51e0\u884c\uff0c\u8981\u4e48\u51e0\u4e4e\u8dd1\u5230\u6bcf\u4e2a\u5c4f\u5e55\u7684\u53f3\u8fb9\u7f18\u3002\u56e0\u6b64\uff0c\u6211\u4eec\u6253\u5f00\u4e86\u4e00\u4e2a\u5927\u62ec\u53f7\u5c01\u95ed\u7684\u4ee3\u7801\u5757\uff0c\u5728\u8fd9\u4e2a\u4ee3\u7801\u5757\u4e2d\uff0c\u6211\u4eec\u901a\u8fc7\u8bf4 \"\u4f7f\u7528\u547d\u540d\u7a7a\u95f4SolutionComponents\"\uff0c\u6682\u65f6\u4f7f\u547d\u540d\u7a7a\u95f4`SolutionComponents'\u4e2d\u7684\u540d\u5b57\u53ef\u7528\uff0c\u800c\u4e0d\u9700\u8981\u547d\u540d\u7a7a\u95f4\u4fee\u9970\u8bed\u3002\n\n    Table<2, DoFTools::Coupling> coupling(2 * dim + 7, 2 * dim + 7); \n    { \n      using namespace SolutionComponents; \n\n      coupling[density<dim>][density<dim>] = DoFTools::always; \n\n      for (unsigned int i = 0; i < dim; ++i) \n        { \n          coupling[density<dim>][displacement<dim> + i] = DoFTools::always; \n          coupling[displacement<dim> + i][density<dim>] = DoFTools::always; \n        } \n\n      for (unsigned int i = 0; i < dim; ++i) \n        { \n          coupling[density<dim>][displacement_multiplier<dim> + i] = \n            DoFTools::always; \n          coupling[displacement_multiplier<dim> + i][density<dim>] = \n            DoFTools::always; \n        } \n\n      coupling[density<dim>][unfiltered_density_multiplier<dim>] = \n        DoFTools::always; \n      coupling[unfiltered_density_multiplier<dim>][density<dim>] = \n        DoFTools::always; \n      /*\u4f4d\u79fb\u7684\u8054\u7ed3  */ \n      for (unsigned int i = 0; i < dim; ++i) \n        { \n          for (unsigned int k = 0; k < dim; ++k) \n            { \n              coupling[displacement<dim> + i] \n                      [displacement_multiplier<dim> + k] = DoFTools::always; \n              coupling[displacement_multiplier<dim> + k] \n                      [displacement<dim> + i] = DoFTools::always; \n            } \n        } \n      /*\u677e\u5f1b\u53d8\u91cf\u7684\u8026\u5408 */ \n      coupling[density_lower_slack<dim>][density_lower_slack<dim>] = \n        DoFTools::always; \n      coupling[density_lower_slack<dim>][density_upper_slack<dim>] = \n        DoFTools::always; \n      coupling[density_upper_slack<dim>][density_lower_slack<dim>] = \n        DoFTools::always; \n\n      coupling[density_lower_slack_multiplier<dim>] \n              [density_lower_slack_multiplier<dim>] = DoFTools::always; \n      coupling[density_lower_slack_multiplier<dim>] \n              [density_upper_slack_multiplier<dim>] = DoFTools::always; \n      coupling[density_upper_slack_multiplier<dim>] \n              [density_lower_slack_multiplier<dim>] = DoFTools::always; \n    } \n\n// \u5728\u521b\u5efa\u7a00\u758f\u6a21\u5f0f\u4e4b\u524d\uff0c\u6211\u4eec\u8fd8\u5fc5\u987b\u8bbe\u7f6e\u7ea6\u675f\u3002\u7531\u4e8e\u8fd9\u4e2a\u7a0b\u5e8f\u6ca1\u6709\u81ea\u9002\u5e94\u5730\u7ec6\u5316\u7f51\u683c\uff0c\u6211\u4eec\u552f\u4e00\u7684\u7ea6\u675f\u662f\u5c06\u6240\u6709\u7684\u5bc6\u5ea6\u53d8\u91cf\u8026\u5408\u5728\u4e00\u8d77\uff0c\u5f3a\u5236\u6267\u884c\u4f53\u79ef\u7ea6\u675f\u3002\u8fd9\u5c06\u6700\u7ec8\u5bfc\u81f4\u77e9\u9635\u7684\u5bc6\u96c6\u5b50\u5757\uff0c\u4f46\u6211\u4eec\u5bf9\u6b64\u6ca1\u6709\u4ec0\u4e48\u529e\u6cd5\u3002\n\n    const ComponentMask density_mask = \n      fe.component_mask(ValueExtractors::densities<dim>); \n    const IndexSet density_dofs = \n      DoFTools::extract_dofs(dof_handler, density_mask); \n\n    types::global_dof_index last_density_dof = \n      density_dofs.nth_index_in_set(density_dofs.n_elements() - 1); \n    constraints.clear(); \n    constraints.add_line(last_density_dof); \n    for (unsigned int i = 0; i < density_dofs.n_elements() - 1; ++i) \n      constraints.add_entry(last_density_dof, \n                            density_dofs.nth_index_in_set(i), \n                            -1); \n    constraints.set_inhomogeneity(last_density_dof, 0); \n\n    constraints.close(); \n\n// \u73b0\u5728\u6211\u4eec\u7ec8\u4e8e\u53ef\u4ee5\u4e3a\u77e9\u9635\u521b\u5efa\u7a00\u758f\u6a21\u5f0f\u4e86\uff0c\u8003\u8651\u5230\u54ea\u4e9b\u53d8\u91cf\u4e0e\u54ea\u4e9b\u5176\u4ed6\u53d8\u91cf\u8026\u5408\uff0c\u4ee5\u53ca\u6211\u4eec\u5bf9\u5bc6\u5ea6\u7684\u7ea6\u675f\u3002\n\n    DoFTools::make_sparsity_pattern(dof_handler, coupling, dsp, constraints); \n\n// \u77e9\u9635\u4e2d\u552f\u4e00\u6ca1\u6709\u5904\u7406\u7684\u90e8\u5206\u662f\u8fc7\u6ee4\u77e9\u9635\u548c\u5b83\u7684\u8f6c\u7f6e\u3002\u8fd9\u4e9b\u90fd\u662f\u975e\u5c40\u90e8\uff08\u79ef\u5206\uff09\u8fd0\u7b97\u7b26\uff0c\u76ee\u524ddeal.II\u8fd8\u6ca1\u6709\u76f8\u5173\u7684\u51fd\u6570\u3002\u6211\u4eec\u6700\u7ec8\u9700\u8981\u505a\u7684\u662f\u904d\u5386\u6240\u6709\u5355\u5143\uff0c\u5e76\u5c06\u6b64\u5355\u5143\u4e0a\u7684\u672a\u8fc7\u6ee4\u5bc6\u5ea6\u4e0e\u5c0f\u4e8e\u9608\u503c\u8ddd\u79bb\u7684\u76f8\u90bb\u5355\u5143\u7684\u6240\u6709\u8fc7\u6ee4\u5bc6\u5ea6\u8054\u7cfb\u8d77\u6765\uff0c\u53cd\u4e4b\u4ea6\u7136\uff1b\u76ee\u524d\uff0c\u6211\u4eec\u53ea\u5173\u5fc3\u5efa\u7acb\u4e0e\u8fd9\u79cd\u77e9\u9635\u76f8\u5bf9\u5e94\u7684\u7a00\u758f\u6a21\u5f0f\uff0c\u6240\u4ee5\u6211\u4eec\u6267\u884c\u7b49\u6548\u5faa\u73af\uff0c\u4ee5\u540e\u6211\u4eec\u5c06\u5199\u8fdb\u77e9\u9635\u7684\u4e00\u4e2a\u6761\u76ee\uff0c\u73b0\u5728\u6211\u4eec\u53ea\u9700\u5411\u7a00\u758f\u77e9\u9635\u6dfb\u52a0\u4e00\u4e2a\u6761\u76ee\u3002\n\n    for (const auto &cell : dof_handler.active_cell_iterators()) \n      { \n        const unsigned int i = cell->active_cell_index(); \n        for (const auto &check_cell : find_relevant_neighbors(cell)) \n          { \n            const double distance = \n              cell->center().distance(check_cell->center()); \n            if (distance < filter_r) \n              { \n                dsp \n                  .block(SolutionBlocks::unfiltered_density, \n                         SolutionBlocks::unfiltered_density_multiplier) \n                  .add(i, check_cell->active_cell_index()); \n                dsp \n                  .block(SolutionBlocks::unfiltered_density_multiplier, \n                         SolutionBlocks::unfiltered_density) \n                  .add(i, check_cell->active_cell_index()); \n              } \n          } \n      } \n\n// \u5728\u751f\u6210\u4e86 \"\u52a8\u6001 \"\u7a00\u758f\u5ea6\u6a21\u5f0f\u4e4b\u540e\uff0c\u6211\u4eec\u7ec8\u4e8e\u53ef\u4ee5\u5c06\u5176\u590d\u5236\u5230\u7528\u4e8e\u5c06\u77e9\u9635\u4e0e\u7a00\u758f\u5ea6\u6a21\u5f0f\u8054\u7cfb\u8d77\u6765\u7684\u7ed3\u6784\u4e2d\u3002\u7531\u4e8e\u7a00\u758f\u6a21\u5f0f\u5f88\u5927\u5f88\u590d\u6742\uff0c\u6211\u4eec\u8fd8\u5c06\u5176\u8f93\u51fa\u5230\u4e00\u4e2a\u81ea\u5df1\u7684\u6587\u4ef6\u4e2d\uff0c\u4ee5\u8fbe\u5230\u53ef\u89c6\u5316\u7684\u76ee\u7684--\u6362\u53e5\u8bdd\u8bf4\uff0c\u662f\u4e3a\u4e86 \"\u53ef\u89c6\u5316\u8c03\u8bd5\"\u3002\n\n    sparsity_pattern.copy_from(dsp); \n\n    std::ofstream out(\"sparsity.plt\"); \n    sparsity_pattern.print_gnuplot(out); \n\n    system_matrix.reinit(sparsity_pattern); \n\n// \u5269\u4e0b\u7684\u5c31\u662f\u6b63\u786e\u786e\u5b9a\u5404\u79cd\u5411\u91cf\u53ca\u5176\u5757\u7684\u5927\u5c0f\uff0c\u4ee5\u53ca\u4e3a\uff08\u975e\u7ebf\u6027\uff09\u89e3\u5411\u91cf\u7684\u4e00\u4e9b\u5206\u91cf\u8bbe\u7f6e\u521d\u59cb\u731c\u6d4b\u3002\u6211\u4eec\u5728\u8fd9\u91cc\u4f7f\u7528\u89e3\u5411\u91cf\u5404\u4e2a\u533a\u5757\u7684\u7b26\u53f7\u5206\u91cf\u540d\u79f0\uff0c\u4e3a\u4e86\u7b80\u6d01\u8d77\u89c1\uff0c\u4f7f\u7528\u4e0e\u4e0a\u9762\u7684 \"\u4f7f\u7528\u547d\u540d\u7a7a\u95f4 \"\u76f8\u540c\u7684\u6280\u5de7\u3002\n\n    nonlinear_solution.reinit(block_sizes); \n    system_rhs.reinit(block_sizes); \n\n    { \n      using namespace SolutionBlocks; \n      nonlinear_solution.block(density).add(density_ratio); \n      nonlinear_solution.block(unfiltered_density).add(density_ratio); \n      nonlinear_solution.block(unfiltered_density_multiplier) \n        .add(density_ratio); \n      nonlinear_solution.block(density_lower_slack).add(density_ratio); \n      nonlinear_solution.block(density_lower_slack_multiplier).add(50); \n      nonlinear_solution.block(density_upper_slack).add(1 - density_ratio); \n      nonlinear_solution.block(density_upper_slack_multiplier).add(50); \n    } \n  } \n// @sect3{Creating the filter matrix}  \n\n// \u63a5\u4e0b\u6765\u662f\u4e00\u4e2a\u5728\u7a0b\u5e8f\u5f00\u59cb\u65f6\u4f7f\u7528\u4e00\u6b21\u7684\u51fd\u6570\u3002\u5b83\u521b\u5efa\u4e86\u4e00\u4e2a\u77e9\u9635 $H$ \uff0c\u4f7f\u8fc7\u6ee4\u540e\u7684\u5bc6\u5ea6\u5411\u91cf\u7b49\u4e8e $H$ \u4e58\u4ee5\u672a\u8fc7\u6ee4\u7684\u5bc6\u5ea6\u3002 \u8fd9\u4e2a\u77e9\u9635\u7684\u521b\u5efa\u662f\u975e\u540c\u5c0f\u53ef\u7684\uff0c\u5b83\u5728\u6bcf\u6b21\u8fed\u4ee3\u4e2d\u90fd\u4f1a\u88ab\u4f7f\u7528\uff0c\u56e0\u6b64\uff0c\u4e0e\u5176\u50cf\u6211\u4eec\u5bf9\u725b\u987f\u77e9\u9635\u90a3\u6837\u5bf9\u5176\u8fdb\u884c\u6539\u9020\uff0c\u4e0d\u5982\u53ea\u505a\u4e00\u6b21\u5e76\u5355\u72ec\u5b58\u50a8\u3002\n\n// \u8fd9\u4e2a\u77e9\u9635\u7684\u8ba1\u7b97\u65b9\u5f0f\u9075\u5faa\u4e0a\u9762\u5df2\u7ecf\u4f7f\u7528\u8fc7\u7684\u5927\u7eb2\uff0c\u4ee5\u5f62\u6210\u5176\u7a00\u758f\u6a21\u5f0f\u3002\u6211\u4eec\u5728\u8fd9\u91cc\u5bf9\u8fd9\u4e2a\u5355\u72ec\u5f62\u6210\u7684\u77e9\u9635\u7684\u7a00\u758f\u6027\u6a21\u5f0f\u91cd\u590d\u8fd9\u4e2a\u8fc7\u7a0b\uff0c\u7136\u540e\u5b9e\u9645\u5efa\u7acb\u77e9\u9635\u672c\u8eab\u3002\u4f60\u53ef\u80fd\u60f3\u770b\u770b\u672c\u7a0b\u5e8f\u4ecb\u7ecd\u4e2d\u5173\u4e8e\u8fd9\u4e2a\u77e9\u9635\u7684\u5b9a\u4e49\u3002\n\n  template <int dim> \n  void SANDTopOpt<dim>::setup_filter_matrix() \n  { \n\n// \u6ee4\u6ce2\u5668\u7684\u7a00\u758f\u6a21\u5f0f\u5df2\u7ecf\u5728setup_system()\u51fd\u6570\u4e2d\u786e\u5b9a\u5e76\u5b9e\u73b0\u3002\u6211\u4eec\u4ece\u76f8\u5e94\u7684\u5757\u4e2d\u590d\u5236\u8be5\u7ed3\u6784\uff0c\u5e76\u5728\u8fd9\u91cc\u518d\u6b21\u4f7f\u7528\u5b83\u3002\n\n    filter_sparsity_pattern.copy_from( \n      sparsity_pattern.block(SolutionBlocks::unfiltered_density, \n                             SolutionBlocks::unfiltered_density_multiplier)); \n    filter_matrix.reinit(filter_sparsity_pattern); \n\n// \u5728\u5efa\u7acb\u4e86\u7a00\u758f\u6a21\u5f0f\u4e4b\u540e\uff0c\u73b0\u5728\u6211\u4eec\u91cd\u65b0\u505a\u6240\u6709\u8fd9\u4e9b\u5faa\u73af\uff0c\u4ee5\u5b9e\u9645\u8ba1\u7b97\u77e9\u9635\u9879\u7684\u5fc5\u8981\u503c\u3002\n\n    for (const auto &cell : dof_handler.active_cell_iterators()) \n      { \n        const unsigned int i = cell->active_cell_index(); \n        for (const auto &check_cell : find_relevant_neighbors(cell)) \n          { \n            const double distance = \n              cell->center().distance(check_cell->center()); \n            if (distance < filter_r) \n              { \n                filter_matrix.add(i, \n                                  check_cell->active_cell_index(), \n                                  filter_r - distance); \n\n//      \n\n              } \n          } \n      } \n\n// \u6700\u540e\u4e00\u6b65\u662f\u5bf9\u77e9\u9635\u8fdb\u884c\u6807\u51c6\u5316\u5904\u7406\uff0c\u4f7f\u6bcf\u4e00\u884c\u7684\u6761\u76ee\u4e4b\u548c\u7b49\u4e8e1\u3002\n\n    for (unsigned int i = 0; i < filter_matrix.m(); ++i) \n      { \n        double denominator = 0; \n        for (SparseMatrix<double>::iterator iter = filter_matrix.begin(i); \n             iter != filter_matrix.end(i); \n             iter++) \n          denominator = denominator + iter->value(); \n        for (SparseMatrix<double>::iterator iter = filter_matrix.begin(i); \n             iter != filter_matrix.end(i); \n             iter++) \n          iter->value() = iter->value() / denominator; \n      } \n  } \n\n// \u8fd9\u4e2a\u51fd\u6570\u7528\u4e8e\u5efa\u7acb\u8fc7\u6ee4\u77e9\u9635\u3002\u6211\u4eec\u521b\u5efa\u4e00\u4e2a\u8f93\u5165\u5355\u5143\u7684\u4e00\u5b9a\u534a\u5f84\u5185\u7684\u6240\u6709\u5355\u5143\u8fed\u4ee3\u5668\u7684\u96c6\u5408\u3002\u8fd9\u4e9b\u662f\u4e0e\u8fc7\u6ee4\u5668\u6709\u5173\u7684\u90bb\u8fd1\u5355\u5143\u3002\n\n  template <int dim> \n  std::set<typename Triangulation<dim>::cell_iterator> \n  SANDTopOpt<dim>::find_relevant_neighbors( \n    typename Triangulation<dim>::cell_iterator cell) const \n  { \n    std::set<unsigned int>                               neighbor_ids; \n    std::set<typename Triangulation<dim>::cell_iterator> cells_to_check; \n\n    neighbor_ids.insert(cell->active_cell_index()); \n    cells_to_check.insert(cell); \n\n    bool new_neighbors_found; \n    do \n      { \n        new_neighbors_found = false; \n        for (const auto &check_cell : \n             std::vector<typename Triangulation<dim>::cell_iterator>( \n               cells_to_check.begin(), cells_to_check.end())) \n          { \n            for (const auto n : check_cell->face_indices()) \n              { \n                if (!(check_cell->face(n)->at_boundary())) \n                  { \n                    const auto & neighbor = check_cell->neighbor(n); \n                    const double distance = \n                      cell->center().distance(neighbor->center()); \n                    if ((distance < filter_r) && \n                        !(neighbor_ids.count(neighbor->active_cell_index()))) \n                      { \n                        cells_to_check.insert(neighbor); \n                        neighbor_ids.insert(neighbor->active_cell_index()); \n                        new_neighbors_found = true; \n                      } \n                  } \n              } \n          } \n      } \n    while (new_neighbors_found); \n    return cells_to_check; \n  } \n// @sect3{Assembling the Newton matrix}  \n\n// setup_filter_matrix\u51fd\u6570\u5efa\u7acb\u4e86\u4e00\u4e2a\u53ea\u8981\u7f51\u683c\u4e0d\u6539\u53d8\u5c31\u4e0d\u53d8\u7684\u77e9\u9635\uff08\u5728\u8fd9\u4e2a\u7a0b\u5e8f\u4e2d\u6211\u4eec\u53cd\u6b63\u4e0d\u6539\u53d8\uff09\uff0c\u800c\u4e0b\u4e00\u4e2a\u51fd\u6570\u5efa\u7acb\u4e86\u6bcf\u6b21\u8fed\u4ee3\u90fd\u8981\u89e3\u51b3\u7684\u77e9\u9635\u3002\u8fd9\u5c31\u662f\u5947\u8ff9\u53d1\u751f\u7684\u5730\u65b9\u3002\u63cf\u8ff0\u725b\u987f\u6c42\u89e3KKT\u6761\u4ef6\u7684\u65b9\u6cd5\u7684\u7ebf\u6027\u65b9\u7a0b\u7ec4\u7684\u7ec4\u6210\u90e8\u5206\u5728\u8fd9\u91cc\u5b9e\u73b0\u3002\n\n// \u8fd9\u4e2a\u51fd\u6570\u7684\u9876\u90e8\u4e0e\u5927\u591a\u6570\u6b64\u7c7b\u51fd\u6570\u4e00\u6837\uff0c\u53ea\u662f\u8bbe\u7f6e\u4e86\u5b9e\u9645\u88c5\u914d\u6240\u9700\u7684\u5404\u79cd\u53d8\u91cf\uff0c\u5305\u62ec\u4e00\u5927\u5806\u63d0\u53d6\u5668\u3002\u5982\u679c\u4f60\u4ee5\u524d\u770b\u8fc7  step-22  \uff0c\u6574\u4e2a\u8bbe\u7f6e\u5e94\u8be5\u770b\u8d77\u6765\u5f88\u719f\u6089\uff0c\u5c3d\u7ba1\u6709\u4e9b\u5197\u957f\u3002\n\n  template <int dim> \n  void SANDTopOpt<dim>::assemble_system() \n  { \n    TimerOutput::Scope t(timer, \"assembly\"); \n\n    system_matrix = 0; \n    system_rhs    = 0; \n\n    MappingQGeneric<dim> mapping(1); \n    QGauss<dim>          quadrature_formula(fe.degree + 1); \n    QGauss<dim - 1>      face_quadrature_formula(fe.degree + 1); \n    FEValues<dim>        fe_values(mapping, \n                            fe, \n                            quadrature_formula, \n                            update_values | update_gradients | \n                              update_quadrature_points | update_JxW_values); \n    FEFaceValues<dim>    fe_face_values(mapping, \n                                     fe, \n                                     face_quadrature_formula, \n                                     update_values | update_quadrature_points | \n                                       update_normal_vectors | \n                                       update_JxW_values); \n\n    const unsigned int dofs_per_cell = fe.dofs_per_cell; \n    const unsigned int n_q_points    = quadrature_formula.size(); \n\n    FullMatrix<double> cell_matrix(dofs_per_cell, dofs_per_cell); \n    Vector<double>     dummy_cell_rhs(dofs_per_cell); \n\n    std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell); \n\n    std::vector<double>                    lambda_values(n_q_points); \n    std::vector<double>                    mu_values(n_q_points); \n    const Functions::ConstantFunction<dim> lambda(1.); \n    const Functions::ConstantFunction<dim> mu(1.); \n    std::vector<Tensor<1, dim>>            rhs_values(n_q_points); \n\n// \u5728\u8fd9\u4e00\u70b9\u4e0a\uff0c\u6211\u4eec\u5bf9\u672a\u8fc7\u6ee4\u7684\u5bc6\u5ea6\u8fdb\u884c\u8fc7\u6ee4\uff0c\u5e76\u5bf9\u672a\u8fc7\u6ee4\u7684\u5bc6\u5ea6\u4e58\u6cd5\u5668\u8fdb\u884c\u90bb\u63a5\uff08\u8f6c\u7f6e\uff09\u64cd\u4f5c\uff0c\u90fd\u662f\u5bf9\u5f53\u524d\u975e\u7ebf\u6027\u89e3\u51b3\u65b9\u6848\u7684\u6700\u4f73\u731c\u6d4b\u3002\u540e\u6765\u6211\u4eec\u7528\u5b83\u6765\u544a\u8bc9\u6211\u4eec\uff0c\u6211\u4eec\u8fc7\u6ee4\u7684\u5bc6\u5ea6\u4e0e\u5e94\u7528\u4e8e\u672a\u8fc7\u6ee4\u5bc6\u5ea6\u7684\u8fc7\u6ee4\u5668\u6709\u591a\u5927\u7684\u504f\u5dee\u3002\u8fd9\u662f\u56e0\u4e3a\u5728\u975e\u7ebf\u6027\u95ee\u9898\u7684\u89e3\u4e2d\uff0c\u6211\u4eec\u6709 $\\rho=H\\varrho$ \uff0c\u4f46\u5728\u4e2d\u95f4\u8fed\u4ee3\u4e2d\uff0c\u6211\u4eec\u4e00\u822c\u6709 $\\rho^k\\neq H\\varrho^k$ \uff0c\u7136\u540e \"\u6b8b\u5dee\" $\\rho^k-H\\varrho^k$ \u5c06\u51fa\u73b0\u5728\u6211\u4eec\u4e0b\u9762\u8ba1\u7b97\u7684\u725b\u987f\u66f4\u65b0\u65b9\u7a0b\u4e2d\u7684\u53f3\u8fb9\u3002\n\n    BlockVector<double> filtered_unfiltered_density_solution = \n      nonlinear_solution; \n    BlockVector<double> filter_adjoint_unfiltered_density_multiplier_solution = \n      nonlinear_solution; \n\n    filter_matrix.vmult(filtered_unfiltered_density_solution.block( \n                          SolutionBlocks::unfiltered_density), \n                        nonlinear_solution.block( \n                          SolutionBlocks::unfiltered_density)); \n    filter_matrix.Tvmult( \n      filter_adjoint_unfiltered_density_multiplier_solution.block( \n        SolutionBlocks::unfiltered_density_multiplier), \n      nonlinear_solution.block(SolutionBlocks::unfiltered_density_multiplier)); \n\n    std::vector<double>                  old_density_values(n_q_points); \n    std::vector<Tensor<1, dim>>          old_displacement_values(n_q_points); \n    std::vector<double>                  old_displacement_divs(n_q_points); \n    std::vector<SymmetricTensor<2, dim>> old_displacement_symmgrads(n_q_points); \n    std::vector<Tensor<1, dim>> old_displacement_multiplier_values(n_q_points); \n    std::vector<double>         old_displacement_multiplier_divs(n_q_points); \n    std::vector<SymmetricTensor<2, dim>> old_displacement_multiplier_symmgrads( \n      n_q_points); \n    std::vector<double> old_lower_slack_multiplier_values(n_q_points); \n    std::vector<double> old_upper_slack_multiplier_values(n_q_points); \n    std::vector<double> old_lower_slack_values(n_q_points); \n    std::vector<double> old_upper_slack_values(n_q_points); \n    std::vector<double> old_unfiltered_density_values(n_q_points); \n    std::vector<double> old_unfiltered_density_multiplier_values(n_q_points); \n    std::vector<double> filtered_unfiltered_density_values(n_q_points); \n    std::vector<double> filter_adjoint_unfiltered_density_multiplier_values( \n      n_q_points); \n\n    using namespace ValueExtractors; \n    for (const auto &cell : dof_handler.active_cell_iterators()) \n      { \n        cell_matrix = 0; \n\n        cell->get_dof_indices(local_dof_indices); \n\n        fe_values.reinit(cell); \n\n        lambda.value_list(fe_values.get_quadrature_points(), lambda_values); \n        mu.value_list(fe_values.get_quadrature_points(), mu_values); \n\n// \u4f5c\u4e3a\u6784\u5efa\u7cfb\u7edf\u77e9\u9635\u7684\u4e00\u90e8\u5206\uff0c\u6211\u4eec\u9700\u8981\u4ece\u6211\u4eec\u76ee\u524d\u5bf9\u89e3\u51b3\u65b9\u6848\u7684\u731c\u6d4b\u4e2d\u83b7\u53d6\u6570\u503c\u3002\u4ee5\u4e0b\u51e0\u884c\u4ee3\u7801\u5c06\u68c0\u7d22\u51fa\u6240\u9700\u7684\u503c\u3002\n\n        fe_values[densities<dim>].get_function_values(nonlinear_solution, \n                                                      old_density_values); \n        fe_values[displacements<dim>].get_function_values( \n          nonlinear_solution, old_displacement_values); \n        fe_values[displacements<dim>].get_function_divergences( \n          nonlinear_solution, old_displacement_divs); \n        fe_values[displacements<dim>].get_function_symmetric_gradients( \n          nonlinear_solution, old_displacement_symmgrads); \n        fe_values[displacement_multipliers<dim>].get_function_values( \n          nonlinear_solution, old_displacement_multiplier_values); \n        fe_values[displacement_multipliers<dim>].get_function_divergences( \n          nonlinear_solution, old_displacement_multiplier_divs); \n        fe_values[displacement_multipliers<dim>] \n          .get_function_symmetric_gradients( \n            nonlinear_solution, old_displacement_multiplier_symmgrads); \n        fe_values[density_lower_slacks<dim>].get_function_values( \n          nonlinear_solution, old_lower_slack_values); \n        fe_values[density_lower_slack_multipliers<dim>].get_function_values( \n          nonlinear_solution, old_lower_slack_multiplier_values); \n        fe_values[density_upper_slacks<dim>].get_function_values( \n          nonlinear_solution, old_upper_slack_values); \n        fe_values[density_upper_slack_multipliers<dim>].get_function_values( \n          nonlinear_solution, old_upper_slack_multiplier_values); \n        fe_values[unfiltered_densities<dim>].get_function_values( \n          nonlinear_solution, old_unfiltered_density_values); \n        fe_values[unfiltered_density_multipliers<dim>].get_function_values( \n          nonlinear_solution, old_unfiltered_density_multiplier_values); \n        fe_values[unfiltered_densities<dim>].get_function_values( \n          filtered_unfiltered_density_solution, \n          filtered_unfiltered_density_values); \n        fe_values[unfiltered_density_multipliers<dim>].get_function_values( \n          filter_adjoint_unfiltered_density_multiplier_solution, \n          filter_adjoint_unfiltered_density_multiplier_values); \n\n        for (const auto q_point : fe_values.quadrature_point_indices()) \n          { \n\n// \u6211\u4eec\u8fd8\u9700\u8981\u51e0\u4e2a\u4e0e\u6765\u81ea\u62c9\u683c\u6717\u65e5\u7684\u7b2c\u4e00\u5bfc\u6570\u7684\u6d4b\u8bd5\u51fd\u6570\u76f8\u5bf9\u5e94\u7684\u6570\u503c\uff0c\u4e5f\u5c31\u662f $d_{\\bullet}$ \u51fd\u6570\u3002\u8fd9\u4e9b\u90fd\u662f\u5728\u8fd9\u91cc\u8ba1\u7b97\u7684\u3002\n\n            for (const auto i : fe_values.dof_indices()) \n              { \n                const SymmetricTensor<2, dim> displacement_phi_i_symmgrad = \n                  fe_values[displacements<dim>].symmetric_gradient(i, q_point); \n                const double displacement_phi_i_div = \n                  fe_values[displacements<dim>].divergence(i, q_point); \n\n                const SymmetricTensor<2, dim> \n                  displacement_multiplier_phi_i_symmgrad = \n                    fe_values[displacement_multipliers<dim>].symmetric_gradient( \n                      i, q_point); \n                const double displacement_multiplier_phi_i_div = \n                  fe_values[displacement_multipliers<dim>].divergence(i, \n                                                                      q_point); \n\n                const double density_phi_i = \n                  fe_values[densities<dim>].value(i, q_point); \n                const double unfiltered_density_phi_i = \n                  fe_values[unfiltered_densities<dim>].value(i, q_point); \n                const double unfiltered_density_multiplier_phi_i = \n                  fe_values[unfiltered_density_multipliers<dim>].value(i, \n                                                                       q_point); \n\n                const double lower_slack_multiplier_phi_i = \n                  fe_values[density_lower_slack_multipliers<dim>].value( \n                    i, q_point); \n\n                const double lower_slack_phi_i = \n                  fe_values[density_lower_slacks<dim>].value(i, q_point); \n\n                const double upper_slack_phi_i = \n                  fe_values[density_upper_slacks<dim>].value(i, q_point); \n\n                const double upper_slack_multiplier_phi_i = \n                  fe_values[density_upper_slack_multipliers<dim>].value( \n                    i, q_point); \n\n                for (const auto j : fe_values.dof_indices()) \n                  { \n\n// \u6700\u540e\uff0c\u6211\u4eec\u9700\u8981\u6765\u81ea\u62c9\u683c\u6717\u65e5\u7684\u7b2c\u4e8c\u8f6e\u5bfc\u6570\u7684\u6570\u503c\uff0c\u5373 $c_{\\bullet}$ \u51fd\u6570\u3002\u8fd9\u4e9b\u662f\u5728\u8fd9\u91cc\u8ba1\u7b97\u7684\u3002\n\n                    const SymmetricTensor<2, dim> displacement_phi_j_symmgrad = \n                      fe_values[displacements<dim>].symmetric_gradient(j, \n                                                                       q_point); \n                    const double displacement_phi_j_div = \n                      fe_values[displacements<dim>].divergence(j, q_point); \n\n                    const SymmetricTensor<2, dim> \n                      displacement_multiplier_phi_j_symmgrad = \n                        fe_values[displacement_multipliers<dim>] \n                          .symmetric_gradient(j, q_point); \n                    const double displacement_multiplier_phi_j_div = \n                      fe_values[displacement_multipliers<dim>].divergence( \n                        j, q_point); \n\n                    const double density_phi_j = \n                      fe_values[densities<dim>].value(j, q_point); \n\n                    const double unfiltered_density_phi_j = \n                      fe_values[unfiltered_densities<dim>].value(j, q_point); \n                    const double unfiltered_density_multiplier_phi_j = \n                      fe_values[unfiltered_density_multipliers<dim>].value( \n                        j, q_point); \n\n                    const double lower_slack_phi_j = \n                      fe_values[density_lower_slacks<dim>].value(j, q_point); \n\n                    const double upper_slack_phi_j = \n                      fe_values[density_upper_slacks<dim>].value(j, q_point); \n\n                    const double lower_slack_multiplier_phi_j = \n                      fe_values[density_lower_slack_multipliers<dim>].value( \n                        j, q_point); \n\n                    const double upper_slack_multiplier_phi_j = \n                      fe_values[density_upper_slack_multipliers<dim>].value( \n                        j, q_point); \n\n// \u8fd9\u5c31\u662f\u5b9e\u9645\u5de5\u4f5c\u7684\u5f00\u59cb\u3002\u5728\u4e0b\u6587\u4e2d\uff0c\u6211\u4eec\u5c06\u5efa\u7acb\u77e9\u9635\u7684\u6240\u6709\u9879--\u5b83\u4eec\u6570\u91cf\u4f17\u591a\uff0c\u800c\u4e14\u4e0d\u5b8c\u5168\u662f\u4e0d\u8a00\u81ea\u660e\u7684\uff0c\u4e5f\u53d6\u51b3\u4e8e\u4e4b\u524d\u7684\u89e3\u548c\u5b83\u7684\u5bfc\u6570\uff08\u6211\u4eec\u5df2\u7ecf\u5728\u4e0a\u9762\u8bc4\u4f30\u4e86\u8fd9\u4e9b\u5bfc\u6570\uff0c\u5e76\u5c06\u5176\u653e\u5165\u540d\u4e3a`old_*`\u7684\u53d8\u91cf\u4e2d\uff09\u3002\u4e3a\u4e86\u7406\u89e3\u8fd9\u4e9b\u6761\u6b3e\u7684\u6bcf\u4e00\u4e2a\u5bf9\u5e94\u7684\u5185\u5bb9\uff0c\u4f60\u8981\u770b\u4e00\u4e0b\u4e0a\u9762\u4ecb\u7ecd\u4e2d\u8fd9\u4e9b\u6761\u6b3e\u7684\u660e\u786e\u5f62\u5f0f\u3002                    \u88ab\u9a71\u52a8\u52300\u7684\u65b9\u7a0b\u7684\u53f3\u8fb9\u7ed9\u51fa\u4e86\u5bfb\u627e\u5c40\u90e8\u6700\u5c0f\u503c\u7684\u6240\u6709KKT\u6761\u4ef6--\u6bcf\u4e2a\u5355\u72ec\u65b9\u7a0b\u7684\u63cf\u8ff0\u90fd\u662f\u968f\u7740\u53f3\u8fb9\u7684\u8ba1\u7b97\u7ed9\u51fa\u7684\u3002\n\n                    /* \u65b9\u7a0b1  */ \n                    cell_matrix(i, j) += \n                      fe_values.JxW(q_point) * \n                      ( \n                        -density_phi_i * unfiltered_density_multiplier_phi_j \n                        + density_penalty_exponent * \n                            (density_penalty_exponent - 1) * \n                            std::pow(old_density_values[q_point], \n                                     density_penalty_exponent - 2) * \n                            density_phi_i * density_phi_j * \n                            (old_displacement_multiplier_divs[q_point] * \n                               old_displacement_divs[q_point] * \n                               lambda_values[q_point] + \n                             2 * mu_values[q_point] * \n                               (old_displacement_symmgrads[q_point] * \n                                old_displacement_multiplier_symmgrads[q_point])) \n                        + density_penalty_exponent * \n                            std::pow(old_density_values[q_point], \n                                     density_penalty_exponent - 1) * \n                            density_phi_i * \n                            (displacement_multiplier_phi_j_div * \n                               old_displacement_divs[q_point] * \n                               lambda_values[q_point] + \n                             2 * mu_values[q_point] * \n                               (old_displacement_symmgrads[q_point] * \n                                displacement_multiplier_phi_j_symmgrad)) \n                        + density_penalty_exponent * \n                            std::pow(old_density_values[q_point], \n                                     density_penalty_exponent - 1) * \n                            density_phi_i * \n                            (displacement_phi_j_div * \n                               old_displacement_multiplier_divs[q_point] * \n                               lambda_values[q_point] + \n                             2 * mu_values[q_point] * \n                               (old_displacement_multiplier_symmgrads[q_point] * \n                                displacement_phi_j_symmgrad))); \n                   \n                    /* \u65b9\u7a0b2  */ \n                    cell_matrix(i, j) += \n                      fe_values.JxW(q_point) * \n                      (density_penalty_exponent * \n                         std::pow(old_density_values[q_point], \n                                  density_penalty_exponent - 1) * \n                         density_phi_j * \n                         (old_displacement_multiplier_divs[q_point] * \n                            displacement_phi_i_div * lambda_values[q_point] + \n                          2 * mu_values[q_point] * \n                            (old_displacement_multiplier_symmgrads[q_point] * \n                             displacement_phi_i_symmgrad)) \n                       + std::pow(old_density_values[q_point], \n                                  density_penalty_exponent) * \n                           (displacement_multiplier_phi_j_div * \n                              displacement_phi_i_div * lambda_values[q_point] + \n                            2 * mu_values[q_point] * \n                              (displacement_multiplier_phi_j_symmgrad * \n                               displacement_phi_i_symmgrad)) \n                      ); \n\n                   /*\u65b9\u7a0b3\uff0c\u8fd9\u4e0e\u8fc7\u6ee4\u5668\u6709\u5173 */ \n                    cell_matrix(i, j) += \n                      fe_values.JxW(q_point) * \n                      (-1 * unfiltered_density_phi_i * \n                         lower_slack_multiplier_phi_j + \n                       unfiltered_density_phi_i * upper_slack_multiplier_phi_j); \n\n                     /* \u65b9\u7a0b4\uff1a\u539f\u59cb\u53ef\u884c\u6027  */ \n                    cell_matrix(i, j) += \n                      fe_values.JxW(q_point) * \n                      ( \n                        density_penalty_exponent * \n                          std::pow(old_density_values[q_point], \n                                   density_penalty_exponent - 1) * \n                          density_phi_j * \n                          (old_displacement_divs[q_point] * \n                             displacement_multiplier_phi_i_div * \n                             lambda_values[q_point] + \n                           2 * mu_values[q_point] * \n                             (old_displacement_symmgrads[q_point] * \n                              displacement_multiplier_phi_i_symmgrad)) \n\n                        + std::pow(old_density_values[q_point], \n                                   density_penalty_exponent) * \n                            (displacement_phi_j_div * \n                               displacement_multiplier_phi_i_div * \n                               lambda_values[q_point] + \n                             2 * mu_values[q_point] * \n                               (displacement_phi_j_symmgrad * \n                                displacement_multiplier_phi_i_symmgrad))); \n\n                   /*\u7b49\u5f0f5\uff1a\u539f\u59cb\u53ef\u884c\u6027  */ \n                    cell_matrix(i, j) += \n                      -1 * fe_values.JxW(q_point) * \n                      lower_slack_multiplier_phi_i * \n                      (unfiltered_density_phi_j - lower_slack_phi_j); \n                  /* \u7b49\u5f0f6\uff1a\u539f\u59cb\u53ef\u884c\u6027  */ \n                    cell_matrix(i, j) += \n                      -1 * fe_values.JxW(q_point) * \n                      upper_slack_multiplier_phi_i * \n                      (-1 * unfiltered_density_phi_j - upper_slack_phi_j); \n                    /* Equation 7: Primal feasibility - the part with the filter\n                     * is added later */\n                    cell_matrix(i, j) += -1 * fe_values.JxW(q_point) * \n                                         unfiltered_density_multiplier_phi_i * \n                                         (density_phi_j); \n                    /* Equation 8: Complementary slackness */\n                    cell_matrix(i, j) += \n                      fe_values.JxW(q_point) * \n                      (lower_slack_phi_i * lower_slack_multiplier_phi_j \n\n                       + lower_slack_phi_i * lower_slack_phi_j * \n                           old_lower_slack_multiplier_values[q_point] / \n                           old_lower_slack_values[q_point]); \n                    /* Equation 9: Complementary slackness */\n                    cell_matrix(i, j) += \n                      fe_values.JxW(q_point) * \n                      (upper_slack_phi_i * upper_slack_multiplier_phi_j \n\n                       + upper_slack_phi_i * upper_slack_phi_j * \n                           old_upper_slack_multiplier_values[q_point] / \n                           old_upper_slack_values[q_point]); \n                  } \n              } \n          } \n\n// \u73b0\u5728\u6211\u4eec\u5df2\u7ecf\u628a\u6240\u6709\u7684\u4e1c\u897f\u90fd\u7ec4\u88c5\u597d\u4e86\uff0c\u6211\u4eec\u8981\u505a\u7684\u5c31\u662f\u5904\u7406\uff08Dirichlet\uff09\u8fb9\u754c\u6761\u4ef6\u7684\u5f71\u54cd\u548c\u5176\u4ed6\u7ea6\u675f\u3002\u6211\u4eec\u5c06\u524d\u8005\u4e0e\u5f53\u524d\u5355\u5143\u7684\u8d21\u732e\u7ed3\u5408\u5728\u4e00\u8d77\uff0c\u7136\u540e\u8ba9AffineConstraint\u7c7b\u6765\u5904\u7406\u540e\u8005\uff0c\u540c\u65f6\u5c06\u5f53\u524d\u5355\u5143\u7684\u8d21\u732e\u590d\u5236\u5230\u5168\u5c40\u7ebf\u6027\u7cfb\u7edf\u4e2d\u3002\n\n        MatrixTools::local_apply_boundary_values(boundary_values, \n                                                 local_dof_indices, \n                                                 cell_matrix, \n                                                 dummy_cell_rhs, \n                                                 true); \n\n        constraints.distribute_local_to_global(cell_matrix, \n                                               local_dof_indices, \n                                               system_matrix); \n      } \n\n// \u5728\u79ef\u7d2f\u4e86\u6240\u6709\u5c5e\u4e8e\u725b\u987f\u77e9\u9635\u7684\u9879\u4e4b\u540e\uff0c\u6211\u4eec\u73b0\u5728\u8fd8\u5fc5\u987b\u8ba1\u7b97\u53f3\u624b\u8fb9\u7684\u9879\uff08\u5373\u8d1f\u6b8b\u5dee\uff09\u3002\u6211\u4eec\u5df2\u7ecf\u5728\u53e6\u4e00\u4e2a\u51fd\u6570\u4e2d\u505a\u4e86\u8fd9\u4e2a\u5de5\u4f5c\uff0c\u6240\u4ee5\u6211\u4eec\u5728\u8fd9\u91cc\u8c03\u7528\u5b83\u3002\n\n    system_rhs = calculate_test_rhs(nonlinear_solution); \n\n// \u8fd9\u91cc\u6211\u4eec\u4f7f\u7528\u6211\u4eec\u5df2\u7ecf\u6784\u5efa\u597d\u7684\u8fc7\u6ee4\u5668\u77e9\u9635\u3002\u6211\u4eec\u53ea\u9700\u8981\u6574\u5408\u8fd9\u4e2a\u5e94\u7528\u4e8e\u6d4b\u8bd5\u51fd\u6570\u7684\u8fc7\u6ee4\u5668\uff0c\u5b83\u662f\u7247\u72b6\u5e38\u6570\uff0c\u6240\u4ee5\u6574\u5408\u53d8\u6210\u4e86\u7b80\u5355\u7684\u4e58\u4ee5\u5355\u5143\u683c\u7684\u5ea6\u91cf\u3002 \u904d\u5386\u9884\u5236\u7684\u8fc7\u6ee4\u5668\u77e9\u9635\u53ef\u4ee5\u8ba9\u6211\u4eec\u4f7f\u7528\u54ea\u4e9b\u5355\u5143\u683c\u5728\u8fc7\u6ee4\u5668\u4e2d\u6216\u4e0d\u5728\u8fc7\u6ee4\u5668\u4e2d\u7684\u4fe1\u606f\uff0c\u800c\u4e0d\u9700\u8981\u518d\u6b21\u91cd\u590d\u68c0\u67e5\u90bb\u5c45\u5355\u5143\u683c\u3002\n\n    for (const auto &cell : dof_handler.active_cell_iterators()) \n      { \n        const unsigned int i = cell->active_cell_index(); \n        for (typename SparseMatrix<double>::iterator iter = \n               filter_matrix.begin(i); \n             iter != filter_matrix.end(i); \n             ++iter) \n          { \n            const unsigned int j     = iter->column(); \n            const double       value = iter->value() * cell->measure(); \n\n            system_matrix \n              .block(SolutionBlocks::unfiltered_density_multiplier, \n                     SolutionBlocks::unfiltered_density) \n              .add(i, j, value); \n            system_matrix \n              .block(SolutionBlocks::unfiltered_density, \n                     SolutionBlocks::unfiltered_density_multiplier) \n              .add(j, i, value); \n          } \n      } \n  } \n// @sect3{Solving the Newton linear system}  \n\n// \u6211\u4eec\u5c06\u9700\u8981\u5728\u6bcf\u6b21\u8fed\u4ee3\u4e2d\u89e3\u51b3\u4e00\u4e2a\u7ebf\u6027\u7cfb\u7edf\u3002\u6211\u4eec\u6682\u65f6\u4f7f\u7528\u4e00\u4e2a\u76f4\u63a5\u6c42\u89e3\u5668--\u5bf9\u4e8e\u4e00\u4e2a\u6709\u8fd9\u4e48\u591a\u975e\u96f6\u503c\u7684\u77e9\u9635\u6765\u8bf4\uff0c\u8fd9\u663e\u7136\u4e0d\u662f\u4e00\u4e2a\u6709\u6548\u7684\u9009\u62e9\uff0c\u800c\u4e14\u5b83\u4e0d\u4f1a\u6269\u5c55\u5230\u4efb\u4f55\u6709\u8da3\u7684\u5730\u65b9\u3002\u5bf9\u4e8e \"\u771f\u6b63\u7684 \"\u5e94\u7528\uff0c\u6211\u4eec\u5c06\u9700\u8981\u4e00\u4e2a\u8fed\u4ee3\u6c42\u89e3\u5668\uff0c\u4f46\u7cfb\u7edf\u7684\u590d\u6742\u6027\u610f\u5473\u7740\u4e00\u4e2a\u8fed\u4ee3\u6c42\u89e3\u5668\u7684\u7b97\u6cd5\u5c06\u9700\u8981\u5927\u91cf\u7684\u5de5\u4f5c\u3002\u56e0\u4e3a\u8fd9\u4e0d\u662f\u5f53\u524d\u7a0b\u5e8f\u7684\u91cd\u70b9\uff0c\u6240\u4ee5\u6211\u4eec\u7b80\u5355\u5730\u575a\u6301\u4f7f\u7528\u6211\u4eec\u5728\u8fd9\u91cc\u7684\u76f4\u63a5\u6c42\u89e3\u5668--\u8be5\u51fd\u6570\u9075\u5faa\u4e0e step-29 \u4e2d\u4f7f\u7528\u7684\u76f8\u540c\u7ed3\u6784\u3002\n\n  template <int dim> \n  BlockVector<double> SANDTopOpt<dim>::solve() \n  { \n    TimerOutput::Scope t(timer, \"solver\"); \n\n    BlockVector<double> linear_solution; \n    linear_solution.reinit(nonlinear_solution); \n\n    SparseDirectUMFPACK A_direct; \n    A_direct.initialize(system_matrix); \n    A_direct.vmult(linear_solution, system_rhs); \n\n    constraints.distribute(linear_solution); \n\n    return linear_solution; \n  } \n// @sect3{Details of the optimization algorithm}  \n\n// \u63a5\u4e0b\u6765\u7684\u51e0\u4e2a\u51fd\u6570\u5904\u7406\u4f18\u5316\u7b97\u6cd5\u7684\u5177\u4f53\u90e8\u5206\uff0c\u6700\u4e3b\u8981\u7684\u662f\u51b3\u5b9a\u901a\u8fc7\u6c42\u89e3\u7ebf\u6027\u5316\uff08\u725b\u987f\uff09\u7cfb\u7edf\u8ba1\u7b97\u51fa\u7684\u65b9\u5411\u662f\u5426\u53ef\u884c\uff0c\u5982\u679c\u53ef\u884c\uff0c\u6211\u4eec\u8981\u5728\u8fd9\u4e2a\u65b9\u5411\u4e0a\u8d70\u591a\u8fdc\u3002\n\n//  @sect4{Computing step lengths}  \n\n// \u6211\u4eec\u5148\u7528\u4e00\u4e2a\u51fd\u6570\u8fdb\u884c\u4e8c\u8fdb\u5236\u641c\u7d22\uff0c\u627e\u51fa\u7b26\u5408\u5bf9\u5076\u53ef\u884c\u6027\u7684\u6700\u5927\u6b65\u9aa4--\u4e5f\u5c31\u662f\u8bf4\uff0c\u6211\u4eec\u80fd\u8d70\u591a\u8fdc\uff0c\u4f7f  $s>0$  \u548c  $z>0$  \u3002\u8be5\u51fd\u6570\u8fd4\u56de\u4e00\u5bf9\u6570\u503c\uff0c\u5206\u522b\u4ee3\u8868 $s$ \u548c $z$ \u7684\u677e\u5f1b\u53d8\u91cf\u3002\n\n  template <int dim> \n  std::pair<double, double> SANDTopOpt<dim>::calculate_max_step_size( \n    const BlockVector<double> &state, \n    const BlockVector<double> &step) const \n  { \n    double       fraction_to_boundary; \n    const double min_fraction_to_boundary = .8; \n    const double max_fraction_to_boundary = 1. - 1e-5; \n\n    if (min_fraction_to_boundary < 1 - barrier_size) \n      { \n        if (1 - barrier_size < max_fraction_to_boundary) \n          fraction_to_boundary = 1 - barrier_size; \n        else \n          fraction_to_boundary = max_fraction_to_boundary; \n      } \n    else \n      fraction_to_boundary = min_fraction_to_boundary; \n\n    double step_size_s_low  = 0; \n    double step_size_z_low  = 0; \n    double step_size_s_high = 1; \n    double step_size_z_high = 1; \n    double step_size_s, step_size_z; \n\n    const int max_bisection_method_steps = 50; \n    for (unsigned int k = 0; k < max_bisection_method_steps; ++k) \n      { \n        step_size_s = (step_size_s_low + step_size_s_high) / 2; \n        step_size_z = (step_size_z_low + step_size_z_high) / 2; \n\n        const BlockVector<double> state_test_s = \n          (fraction_to_boundary * state) + (step_size_s * step); \n\n        const BlockVector<double> state_test_z = \n          (fraction_to_boundary * state) + (step_size_z * step); \n\n        const bool accept_s = \n          (state_test_s.block(SolutionBlocks::density_lower_slack) \n             .is_non_negative()) && \n          (state_test_s.block(SolutionBlocks::density_upper_slack) \n             .is_non_negative()); \n        const bool accept_z = \n          (state_test_z.block(SolutionBlocks::density_lower_slack_multiplier) \n             .is_non_negative()) && \n          (state_test_z.block(SolutionBlocks::density_upper_slack_multiplier) \n             .is_non_negative()); \n\n        if (accept_s) \n          step_size_s_low = step_size_s; \n        else \n          step_size_s_high = step_size_s; \n\n        if (accept_z) \n          step_size_z_low = step_size_z; \n        else \n          step_size_z_high = step_size_z; \n      } \n\n    return {step_size_s_low, step_size_z_low}; \n  } \n// @sect4{Computing residuals}  \n\n// \u4e0b\u4e00\u4e2a\u51fd\u6570\u8ba1\u7b97\u4e00\u4e2a\u56f4\u7ed5 \"\u6d4b\u8bd5\u89e3\u5411\u91cf \"\u7ebf\u6027\u5316\u7684\u53f3\u624b\u5411\u91cf\uff0c\u6211\u4eec\u53ef\u4ee5\u7528\u5b83\u6765\u89c2\u5bdfKKT\u6761\u4ef6\u7684\u5927\u5c0f\u3002 \u7136\u540e\uff0c\u8fd9\u5c06\u7528\u4e8e\u5728\u7f29\u5c0f\u969c\u788d\u5927\u5c0f\u4e4b\u524d\u6d4b\u8bd5\u6536\u655b\u6027\uff0c\u4ee5\u53ca\u8ba1\u7b97 $l_1$ \u7684\u4f18\u70b9\u3002\n\n// \u8fd9\u4e2a\u51fd\u6570\u5197\u957f\u800c\u590d\u6742\uff0c\u4f46\u5b83\u5b9e\u9645\u4e0a\u53ea\u662f\u590d\u5236\u4e86\u4e0a\u9762`assemble_system()`\u51fd\u6570\u7684\u53f3\u4fa7\u90e8\u5206\u7684\u5185\u5bb9\u3002\n\n  template <int dim> \n  BlockVector<double> SANDTopOpt<dim>::calculate_test_rhs( \n    const BlockVector<double> &test_solution) const \n  { \n\n// \u6211\u4eec\u9996\u5148\u521b\u5efa\u4e00\u4e2a\u96f6\u5411\u91cf\uff0c\u5176\u5927\u5c0f\u548c\u963b\u585e\u4e3asystem_rhs\n\n    BlockVector<double> test_rhs; \n    test_rhs.reinit(system_rhs); \n\n    MappingQGeneric<dim>  mapping(1); \n    const QGauss<dim>     quadrature_formula(fe.degree + 1); \n    const QGauss<dim - 1> face_quadrature_formula(fe.degree + 1); \n    FEValues<dim>         fe_values(mapping, \n                            fe, \n                            quadrature_formula, \n                            update_values | update_gradients | \n                              update_quadrature_points | update_JxW_values); \n    FEFaceValues<dim>     fe_face_values(mapping, \n                                     fe, \n                                     face_quadrature_formula, \n                                     update_values | update_quadrature_points | \n                                       update_normal_vectors | \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    Vector<double>     cell_rhs(dofs_per_cell); \n    FullMatrix<double> dummy_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> lambda_values(n_q_points); \n    std::vector<double> mu_values(n_q_points); \n\n    const Functions::ConstantFunction<dim> lambda(1.), mu(1.); \n    std::vector<Tensor<1, dim>>            rhs_values(n_q_points); \n\n    BlockVector<double> filtered_unfiltered_density_solution = test_solution; \n    BlockVector<double> filter_adjoint_unfiltered_density_multiplier_solution = \n      test_solution; \n    filtered_unfiltered_density_solution.block( \n      SolutionBlocks::unfiltered_density) = 0; \n    filter_adjoint_unfiltered_density_multiplier_solution.block( \n      SolutionBlocks::unfiltered_density_multiplier) = 0; \n\n    filter_matrix.vmult(filtered_unfiltered_density_solution.block( \n                          SolutionBlocks::unfiltered_density), \n                        test_solution.block( \n                          SolutionBlocks::unfiltered_density)); \n    filter_matrix.Tvmult( \n      filter_adjoint_unfiltered_density_multiplier_solution.block( \n        SolutionBlocks::unfiltered_density_multiplier), \n      test_solution.block(SolutionBlocks::unfiltered_density_multiplier)); \n\n    std::vector<double>                  old_density_values(n_q_points); \n    std::vector<Tensor<1, dim>>          old_displacement_values(n_q_points); \n    std::vector<double>                  old_displacement_divs(n_q_points); \n    std::vector<SymmetricTensor<2, dim>> old_displacement_symmgrads(n_q_points); \n    std::vector<Tensor<1, dim>> old_displacement_multiplier_values(n_q_points); \n    std::vector<double>         old_displacement_multiplier_divs(n_q_points); \n    std::vector<SymmetricTensor<2, dim>> old_displacement_multiplier_symmgrads( \n      n_q_points); \n    std::vector<double> old_lower_slack_multiplier_values(n_q_points); \n    std::vector<double> old_upper_slack_multiplier_values(n_q_points); \n    std::vector<double> old_lower_slack_values(n_q_points); \n    std::vector<double> old_upper_slack_values(n_q_points); \n    std::vector<double> old_unfiltered_density_values(n_q_points); \n    std::vector<double> old_unfiltered_density_multiplier_values(n_q_points); \n    std::vector<double> filtered_unfiltered_density_values(n_q_points); \n    std::vector<double> filter_adjoint_unfiltered_density_multiplier_values( \n      n_q_points); \n\n    using namespace ValueExtractors; \n    for (const auto &cell : dof_handler.active_cell_iterators()) \n      { \n        cell_rhs = 0; \n\n        cell->get_dof_indices(local_dof_indices); \n\n        fe_values.reinit(cell); \n\n \n        mu.value_list(fe_values.get_quadrature_points(), mu_values); \n\n        fe_values[densities<dim>].get_function_values(test_solution, \n                                                      old_density_values); \n        fe_values[displacements<dim>].get_function_values( \n          test_solution, old_displacement_values); \n        fe_values[displacements<dim>].get_function_divergences( \n          test_solution, old_displacement_divs); \n        fe_values[displacements<dim>].get_function_symmetric_gradients( \n          test_solution, old_displacement_symmgrads); \n        fe_values[displacement_multipliers<dim>].get_function_values( \n          test_solution, old_displacement_multiplier_values); \n        fe_values[displacement_multipliers<dim>].get_function_divergences( \n          test_solution, old_displacement_multiplier_divs); \n        fe_values[displacement_multipliers<dim>] \n          .get_function_symmetric_gradients( \n            test_solution, old_displacement_multiplier_symmgrads); \n        fe_values[density_lower_slacks<dim>].get_function_values( \n          test_solution, old_lower_slack_values); \n        fe_values[density_lower_slack_multipliers<dim>].get_function_values( \n          test_solution, old_lower_slack_multiplier_values); \n        fe_values[density_upper_slacks<dim>].get_function_values( \n          test_solution, old_upper_slack_values); \n        fe_values[density_upper_slack_multipliers<dim>].get_function_values( \n          test_solution, old_upper_slack_multiplier_values); \n        fe_values[unfiltered_densities<dim>].get_function_values( \n          test_solution, old_unfiltered_density_values); \n        fe_values[unfiltered_density_multipliers<dim>].get_function_values( \n          test_solution, old_unfiltered_density_multiplier_values); \n        fe_values[unfiltered_densities<dim>].get_function_values( \n          filtered_unfiltered_density_solution, \n          filtered_unfiltered_density_values); \n        fe_values[unfiltered_density_multipliers<dim>].get_function_values( \n          filter_adjoint_unfiltered_density_multiplier_solution, \n          filter_adjoint_unfiltered_density_multiplier_values); \n\n        for (const auto q_point : fe_values.quadrature_point_indices()) \n          { \n            for (const auto i : fe_values.dof_indices()) \n              { \n                const SymmetricTensor<2, dim> displacement_phi_i_symmgrad = \n                  fe_values[displacements<dim>].symmetric_gradient(i, q_point); \n                const double displacement_phi_i_div = \n                  fe_values[displacements<dim>].divergence(i, q_point); \n\n                const SymmetricTensor<2, dim> \n                  displacement_multiplier_phi_i_symmgrad = \n                    fe_values[displacement_multipliers<dim>].symmetric_gradient( \n                      i, q_point); \n                const double displacement_multiplier_phi_i_div = \n                  fe_values[displacement_multipliers<dim>].divergence(i, \n                                                                      q_point); \n\n                const double density_phi_i = \n                  fe_values[densities<dim>].value(i, q_point); \n                const double unfiltered_density_phi_i = \n                  fe_values[unfiltered_densities<dim>].value(i, q_point); \n                const double unfiltered_density_multiplier_phi_i = \n                  fe_values[unfiltered_density_multipliers<dim>].value(i, \n                                                                       q_point); \n\n                const double lower_slack_multiplier_phi_i = \n                  fe_values[density_lower_slack_multipliers<dim>].value( \n                    i, q_point); \n\n                const double lower_slack_phi_i = \n                  fe_values[density_lower_slacks<dim>].value(i, q_point); \n\n                const double upper_slack_phi_i = \n                  fe_values[density_upper_slacks<dim>].value(i, q_point); \n\n                const double upper_slack_multiplier_phi_i = \n                  fe_values[density_upper_slack_multipliers<dim>].value( \n                    i, q_point); \n\n                /* \u65b9\u7a0b1\uff1a\u8fd9\u4e2a\u65b9\u7a0b\u4ee5\u53ca\u65b9\u7a0b\n                 * 2 and 3, are the variational derivatives of the \n                 * Lagrangian with respect to the decision \n                 * variables - the density, displacement, and \n                 * unfiltered density. */ \n\n\n                cell_rhs(i) += \n                  -1 * fe_values.JxW(q_point) * \n                  (density_penalty_exponent * \n                     std::pow(old_density_values[q_point], \n                              density_penalty_exponent - 1) * \n                     density_phi_i * \n                     (old_displacement_multiplier_divs[q_point] * \n                        old_displacement_divs[q_point] * \n                        lambda_values[q_point] + \n                      2 * mu_values[q_point] * \n                        (old_displacement_symmgrads[q_point] * \n                         old_displacement_multiplier_symmgrads[q_point])) - \n                   density_phi_i * \n                     old_unfiltered_density_multiplier_values[q_point]); \n\n                /*\u65b9\u7a0b2\uff1b\u8fb9\u754c\u9879\u5c06\u88ab\u8fdb\u4e00\u6b65\u6dfb\u52a0\u3002\n                 * below. */ \n\n\n                cell_rhs(i) += \n                  -1 * fe_values.JxW(q_point) * \n                  (std::pow(old_density_values[q_point], \n                            density_penalty_exponent) * \n                   (old_displacement_multiplier_divs[q_point] * \n                      displacement_phi_i_div * lambda_values[q_point] + \n                    2 * mu_values[q_point] * \n                      (old_displacement_multiplier_symmgrads[q_point] * \n                       displacement_phi_i_symmgrad))); \n//           \n               /* \u65b9\u7a0b3  */ \n                cell_rhs(i) += \n                  -1 * fe_values.JxW(q_point) * \n                  (unfiltered_density_phi_i * \n                     filter_adjoint_unfiltered_density_multiplier_values \n                       [q_point] + \n                   unfiltered_density_phi_i * \n                     old_upper_slack_multiplier_values[q_point] + \n                   -1 * unfiltered_density_phi_i * \n                     old_lower_slack_multiplier_values[q_point]); \n\n               /* \u65b9\u7a0b4\uff1b\u8fb9\u754c\u9879\u5c06\u518d\u6b21\u88ab\u5904\u7406\u3002with below. \n                * This equation being driven to 0 ensures that the elasticity \n                * equation is met as a constraint. */ \n                cell_rhs(i) += -1 * fe_values.JxW(q_point) * \n                               (std::pow(old_density_values[q_point], \n                                         density_penalty_exponent) * \n                                (old_displacement_divs[q_point] * \n                                   displacement_multiplier_phi_i_div * \n                                   lambda_values[q_point] + \n                                 2 * mu_values[q_point] * \n                                   (displacement_multiplier_phi_i_symmgrad * \n                                    old_displacement_symmgrads[q_point]))); \n\n                /* \u65b9\u7a0b5\uff1a\u8be5\u65b9\u7a0b\u8bbe\u5b9a\u4e86\u4e0b\u9650\u7684\u677e\u5f1b\u91cf\uff0c giving a minimum density of 0. */ \n                cell_rhs(i) += fe_values.JxW(q_point) * \n                               (lower_slack_multiplier_phi_i * \n                                (old_unfiltered_density_values[q_point] - \n                                 old_lower_slack_values[q_point])); \n\n                /* \u65b9\u7a0b6\uff1a\u8be5\u65b9\u7a0b\u8bbe\u5b9a\u4e86\u4e0a\u5c42\u677e\u5f1b\u91cfvariable equal to one minus the unfiltered density. */ \n                cell_rhs(i) += fe_values.JxW(q_point) * \n                               (upper_slack_multiplier_phi_i * \n                                (1 - old_unfiltered_density_values[q_point] - \n                                 old_upper_slack_values[q_point])); \n\n                /*\u7b49\u5f0f7\uff1a\u8fd9\u662f\u5728\n                 * density and the filter applied to the \n                 * unfiltered density. This being driven to 0 by \n                 * the Newton steps ensures that the filter is \n                 * applied correctly. */ \n                cell_rhs(i) += fe_values.JxW(q_point) * \n                               (unfiltered_density_multiplier_phi_i * \n                                (old_density_values[q_point] - \n                                 filtered_unfiltered_density_values[q_point])); \n\n                /*\u65b9\u7a0b8\uff1a\u8fd9\u4e0e\u65b9\u7a0b9\u4e00\u8d77\u7ed9\u51fa\u4e86\n                 * requirement that $s*z = \\alpha$ for the barrier \n                 * size alpha, and gives complementary slackness \n                 * from KKT conditions when $\\alpha$ goes to 0. */ \n                cell_rhs(i) += \n                  -1 * fe_values.JxW(q_point) * \n                  (lower_slack_phi_i * \n                   (old_lower_slack_multiplier_values[q_point] - \n                    barrier_size / old_lower_slack_values[q_point])); \n\n                /*\u65b9\u7a0b9  */ \n                cell_rhs(i) += \n                  -1 * fe_values.JxW(q_point) * \n                  (upper_slack_phi_i * \n                   (old_upper_slack_multiplier_values[q_point] - \n                    barrier_size / old_upper_slack_values[q_point])); \n              } \n          } \n\n        for (const auto &face : cell->face_iterators()) \n          { \n            if (face->at_boundary() && \n                face->boundary_id() == BoundaryIds::down_force) \n              { \n                fe_face_values.reinit(cell, face); \n\n                for (const auto face_q_point : \n                     fe_face_values.quadrature_point_indices()) \n                  { \n                    for (const auto i : fe_face_values.dof_indices()) \n                      { \n                        Tensor<1, dim> traction; \n                        traction[1] = -1.; \n\n                        cell_rhs(i) += \n                          -1 * \n                          (traction * fe_face_values[displacements<dim>].value( \n                                        i, face_q_point)) * \n                          fe_face_values.JxW(face_q_point); \n\n                        cell_rhs(i) += \n                          (traction * \n                           fe_face_values[displacement_multipliers<dim>].value( \n                             i, face_q_point)) * \n                          fe_face_values.JxW(face_q_point); \n                      } \n                  } \n              } \n          } \n\n        MatrixTools::local_apply_boundary_values(boundary_values, \n                                                 local_dof_indices, \n                                                 dummy_cell_matrix, \n                                                 cell_rhs, \n                                                 true); \n\n        constraints.distribute_local_to_global(cell_rhs, \n                                               local_dof_indices, \n                                               test_rhs); \n      } \n\n    return test_rhs; \n  } \n  // @sect4{Computing the merit function}  \n\n  // \u6211\u4eec\u5728\u8fd9\u91cc\u4f7f\u7528\u7684\u7b97\u6cd5\u4f7f\u7528\u4e00\u4e2a \"\u770b\u95e8\u72d7 \"\u7b56\u7565\u6765\u786e\u5b9a\u4ece\u5f53\u524d\u8fed\u4ee3\u7684\u4f4d\u7f6e\u548c\u7a0b\u5ea6\u3002 \u6211\u4eec\u5c06\u770b\u95e8\u72d7\u7b56\u7565\u5efa\u7acb\u5728\u4e00\u4e2a\u7cbe\u786e\u7684 $l_1$ \u529f\u7ee9\u51fd\u6570\u4e0a\u3002\u8fd9\u4e2a\u51fd\u6570\u8ba1\u7b97\u4e00\u4e2a\u7ed9\u5b9a\u7684\u3001\u5047\u5b9a\u7684\u3001\u4e0b\u4e00\u4e2a\u8fed\u4ee3\u7684\u7cbe\u786e $l_1$ \u529f\u7ee9\u3002\n\n  //\u4f18\u70b9\u51fd\u6570\u7531\u76ee\u6807\u51fd\u6570\u7684\u603b\u548c\uff08\u7b80\u5355\u6765\u8bf4\u5c31\u662f\u5916\u529b\u7684\u79ef\u5206\uff08\u5728\u57df\u7684\u8fb9\u754c\u4e0a\uff09\u4e58\u4ee5\u6d4b\u8bd5\u89e3\u7684\u4f4d\u79fb\u503c\uff08\u901a\u5e38\u662f\u5f53\u524d\u89e3\u52a0\u4e0a\u725b\u987f\u66f4\u65b0\u7684\u67d0\u4e2a\u500d\u6570\uff09\uff0c\u4ee5\u53ca\u6b8b\u5dee\u5411\u91cf\u7684\u62c9\u683c\u6717\u65e5\u4e58\u6570\u5206\u91cf\u7684 $l_1$ \u51c6\u5219\u7ec4\u6210\u3002\u4e0b\u9762\u7684\u4ee3\u7801\u4f9d\u6b21\u8ba1\u7b97\u8fd9\u4e9b\u90e8\u5206\u3002\n\n  template <int dim> \n  double SANDTopOpt<dim>::calculate_exact_merit( \n    const BlockVector<double> &test_solution) \n  { \n    TimerOutput::Scope t(timer, \"merit function\"); \n\n    // \u4ece\u8ba1\u7b97\u76ee\u6807\u51fd\u6570\u5f00\u59cb\u3002\n    double objective_function_merit = 0; \n    { \n      MappingQGeneric<dim>  mapping(1); \n      const QGauss<dim>     quadrature_formula(fe.degree + 1); \n      const QGauss<dim - 1> face_quadrature_formula(fe.degree + 1); \n      FEValues<dim>         fe_values(mapping, \n                              fe, \n                              quadrature_formula, \n                              update_values | update_gradients | \n                                update_quadrature_points | update_JxW_values); \n      FEFaceValues<dim>     fe_face_values(mapping, \n                                       fe, \n                                       face_quadrature_formula, \n                                       update_values | \n                                         update_quadrature_points | \n                                         update_normal_vectors | \n                                         update_JxW_values); \n\n      const unsigned int n_face_q_points = face_quadrature_formula.size(); \n\n      std::vector<Tensor<1, dim>> displacement_face_values(n_face_q_points); \n\n      for (const auto &cell : dof_handler.active_cell_iterators()) \n        { \n          for (const auto &face : cell->face_iterators()) \n            { \n              if (face->at_boundary() && \n                  face->boundary_id() == BoundaryIds::down_force) \n                { \n                  fe_face_values.reinit(cell, face); \n                  fe_face_values[ValueExtractors::displacements<dim>] \n                    .get_function_values(test_solution, \n                                         displacement_face_values); \n                  for (unsigned int face_q_point = 0; \n                       face_q_point < n_face_q_points; \n                       ++face_q_point) \n                    { \n                      Tensor<1, dim> traction; \n                      traction[1] = -1.; \n\n                      objective_function_merit += \n                        (traction * displacement_face_values[face_q_point]) * \n                        fe_face_values.JxW(face_q_point); \n                    } \n                } \n            } \n        } \n    } \n\n    for (const auto &cell : triangulation.active_cell_iterators()) \n      { \n        objective_function_merit = \n          objective_function_merit - \n          barrier_size * cell->measure() * \n            std::log(test_solution.block( \n              SolutionBlocks::density_lower_slack)[cell->active_cell_index()]); \n        objective_function_merit = \n          objective_function_merit - \n          barrier_size * cell->measure() * \n            std::log(test_solution.block( \n              SolutionBlocks::density_upper_slack)[cell->active_cell_index()]); \n      } \n    //\u7136\u540e\n    //\u8ba1\u7b97\u6b8b\u5dee\uff0c\u5e76\u53d6\u5bf9\u5e94\u4e8e\u62c9\u683c\u6717\u65e5\u591a\u8fb9\u5f62\u7684\u7ec4\u4ef6\u7684 $l_1$ \u51c6\u5219\u3002\u6211\u4eec\u628a\u8fd9\u4e9b\u52a0\u5230\u4e0a\u9762\u8ba1\u7b97\u7684\u76ee\u6807\u51fd\u6570\u4e2d\uff0c\u5e76\u5728\u5e95\u90e8\u8fd4\u56de\u603b\u548c\u3002\n    const BlockVector<double> test_rhs = calculate_test_rhs(test_solution); \n\n    const double elasticity_constraint_merit = \n      penalty_multiplier * \n      test_rhs.block(SolutionBlocks::displacement_multiplier).l1_norm(); \n    const double filter_constraint_merit = \n      penalty_multiplier * \n      test_rhs.block(SolutionBlocks::unfiltered_density_multiplier).l1_norm(); \n    const double lower_slack_merit = \n      penalty_multiplier * \n      test_rhs.block(SolutionBlocks::density_lower_slack_multiplier).l1_norm(); \n    const double upper_slack_merit = \n      penalty_multiplier * \n      test_rhs.block(SolutionBlocks::density_upper_slack_multiplier).l1_norm(); \n\n    const double total_merit = \n      objective_function_merit + elasticity_constraint_merit + \n      filter_constraint_merit + lower_slack_merit + upper_slack_merit; \n    return total_merit; \n  } \n\n  //  @sect4{Finding a search direction}  \n\n  // \u63a5\u4e0b\u6765\u662f\u5b9e\u9645\u8ba1\u7b97\u4ece\u5f53\u524d\u72b6\u6001\uff08\u4f5c\u4e3a\u7b2c\u4e00\u4e2a\u53c2\u6570\u4f20\u9012\uff09\u5f00\u59cb\u7684\u641c\u7d22\u65b9\u5411\u5e76\u8fd4\u56de\u7ed3\u679c\u5411\u91cf\u7684\u51fd\u6570\u3002\u4e3a\u6b64\uff0c\u8be5\u51fd\u6570\u9996\u5148\u8c03\u7528\u4e0e\u725b\u987f\u7cfb\u7edf\u76f8\u5bf9\u5e94\u7684\u7ebf\u6027\u7cfb\u7edf\u7684\u7ec4\u5408\u51fd\u6570\uff0c\u5e76\u5bf9\u5176\u8fdb\u884c\u6c42\u89e3\u3002\n\n  // \u8fd9\u4e2a\u51fd\u6570\u8fd8\u66f4\u65b0\u4e86\u4f18\u70b9\u51fd\u6570\u4e2d\u7684\u60e9\u7f5a\u4e58\u6570\uff0c\u7136\u540e\u8fd4\u56de\u6700\u5927\u6bd4\u4f8b\u7684\u53ef\u884c\u6b65\u9aa4\u3002\u5b83\u4f7f\u7528`calculate_max_step_sizes()`\u51fd\u6570\u6765\u627e\u5230\u6ee1\u8db3  $s>0$  \u548c  $z>0$  \u7684\u6700\u5927\u53ef\u884c\u6b65\u9aa4\u3002\n\n  template <int dim> \n  BlockVector<double> SANDTopOpt<dim>::find_max_step() \n  { \n    assemble_system(); \n    BlockVector<double> step = solve(); \n\n    // \u63a5\u4e0b\u6765\u6211\u4eec\u8981\u66f4\u65b0punice_multiplier\u3002 \u4ece\u672c\u8d28\u4e0a\u8bb2\uff0c\u66f4\u5927\u7684\u60e9\u7f5a\u4e58\u6570\u4f7f\u6211\u4eec\u66f4\u591a\u8003\u8651\u7ea6\u675f\u6761\u4ef6\u3002 \u89c2\u5bdf\u4e0e\u6211\u4eec\u7684\u51b3\u7b56\u53d8\u91cf\u6709\u5173\u7684Hessian\u548c\u68af\u5ea6\uff0c\u5e76\u5c06\u5176\u4e0e\u6211\u4eec\u7684\u7ea6\u675f\u8bef\u5dee\u7684\u89c4\u8303\u76f8\u6bd4\u8f83\uff0c\u53ef\u4ee5\u786e\u4fdd\u6211\u4eec\u7684\u4f18\u70b9\u51fd\u6570\u662f \"\u7cbe\u786e\u7684\"\n\n    // \u4e5f\u5c31\u662f\u8bf4\uff0c\u5b83\u5728\u4e0e\u76ee\u6807\u51fd\u6570\u76f8\u540c\u7684\u4f4d\u7f6e\u6709\u4e00\u4e2a\u6700\u5c0f\u503c\u3002 \u7531\u4e8e\u6211\u4eec\u7684\u4f18\u70b9\u51fd\u6570\u5bf9\u4efb\u4f55\u8d85\u8fc7\u67d0\u4e2a\u6700\u5c0f\u503c\u7684\u60e9\u7f5a\u4e58\u6570\u90fd\u662f\u7cbe\u786e\u7684\uff0c\u6240\u4ee5\u6211\u4eec\u53ea\u4fdd\u7559\u8ba1\u7b97\u503c\uff0c\u5982\u679c\u5b83\u589e\u52a0\u4e86\u60e9\u7f5a\u4e58\u6570\u3002\n\n    const std::vector<unsigned int> decision_variables = { \n      SolutionBlocks::density, \n      SolutionBlocks::displacement, \n      SolutionBlocks::unfiltered_density, \n      SolutionBlocks::density_upper_slack, \n      SolutionBlocks::density_lower_slack}; \n    double hess_part = 0; \n    double grad_part = 0; \n    for (const unsigned int decision_variable_i : decision_variables) \n      { \n        for (const unsigned int decision_variable_j : decision_variables) \n          { \n            Vector<double> temp_vector(step.block(decision_variable_i).size()); \n            system_matrix.block(decision_variable_i, decision_variable_j) \n              .vmult(temp_vector, step.block(decision_variable_j)); \n            hess_part += step.block(decision_variable_i) * temp_vector; \n          } \n        grad_part -= system_rhs.block(decision_variable_i) * \n                     step.block(decision_variable_i); \n      } \n\n    const std::vector<unsigned int> equality_constraint_multipliers = { \n      SolutionBlocks::displacement_multiplier, \n      SolutionBlocks::unfiltered_density_multiplier, \n      SolutionBlocks::density_lower_slack_multiplier, \n      SolutionBlocks::density_upper_slack_multiplier}; \n    double constraint_norm = 0; \n    for (unsigned int multiplier_i : equality_constraint_multipliers) \n      constraint_norm += system_rhs.block(multiplier_i).linfty_norm(); \n\n    double test_penalty_multiplier; \n    if (hess_part > 0) \n      test_penalty_multiplier = \n        (grad_part + .5 * hess_part) / (.05 * constraint_norm); \n    else \n      test_penalty_multiplier = (grad_part) / (.05 * constraint_norm); \n\n    penalty_multiplier = std::max(penalty_multiplier, test_penalty_multiplier); \n\n    // \u57fa\u4e8e\u6240\u6709\u8fd9\u4e9b\uff0c\u6211\u4eec\u73b0\u5728\u53ef\u4ee5\u8ba1\u7b97\u51fa\u539f\u59cb\u53d8\u91cf\u548c\u5bf9\u5076\u53d8\u91cf\uff08\u62c9\u683c\u6717\u65e5\u4e58\u6570\uff09\u7684\u6b65\u957f\u3002\u4e00\u65e6\u6211\u4eec\u6709\u4e86\u8fd9\u4e9b\uff0c\u6211\u4eec\u5c31\u53ef\u4ee5\u5bf9\u89e3\u5411\u91cf\u7684\u5206\u91cf\u8fdb\u884c\u7f29\u653e\uff0c\u8fd9\u5c31\u662f\u8fd9\u4e2a\u51fd\u6570\u7684\u56de\u62a5\u3002\n\n    const std::pair<double, double> max_step_sizes = \n      calculate_max_step_size(nonlinear_solution, step); \n    const double step_size_s = max_step_sizes.first; \n    const double step_size_z = max_step_sizes.second; \n\n    step.block(SolutionBlocks::density) *= step_size_s; \n    step.block(SolutionBlocks::displacement) *= step_size_s; \n    step.block(SolutionBlocks::unfiltered_density) *= step_size_s; \n    step.block(SolutionBlocks::displacement_multiplier) *= step_size_z; \n    step.block(SolutionBlocks::unfiltered_density_multiplier) *= step_size_z; \n    step.block(SolutionBlocks::density_lower_slack) *= step_size_s; \n    step.block(SolutionBlocks::density_lower_slack_multiplier) *= step_size_z; \n    step.block(SolutionBlocks::density_upper_slack) *= step_size_s; \n    step.block(SolutionBlocks::density_upper_slack_multiplier) *= step_size_z; \n\n    return step; \n  } \n\n  //  @sect4{Computing a scaled step}  \n\n  // \u4e0b\u4e00\u4e2a\u51fd\u6570\u63a5\u7740\u5b9e\u73b0\u4e86\u76f4\u7ebf\u641c\u7d22\u7684\u53cd\u5411\u8ddf\u8e2a\u7b97\u6cd5\u3002\u5b83\u4e0d\u65ad\u7f29\u5c0f\u6b65\u957f\uff0c\u76f4\u5230\u627e\u5230\u4e00\u4e2a\u4f18\u70b9\u51cf\u5c11\u7684\u6b65\u957f\uff0c\u7136\u540e\u6839\u636e\u5f53\u524d\u7684\u72b6\u6001\u5411\u91cf\uff0c\u4ee5\u53ca\u8981\u8fdb\u5165\u7684\u65b9\u5411\uff0c\u4e58\u4ee5\u6b65\u957f\uff0c\u8fd4\u56de\u65b0\u7684\u4f4d\u7f6e\u3002\n\n  template <int dim> \n  BlockVector<double> \n  SANDTopOpt<dim>::compute_scaled_step(const BlockVector<double> &state, \n                                       const BlockVector<double> &max_step, \n                                       const double descent_requirement) \n  { \n    const double merit_derivative = \n      (calculate_exact_merit(state + 1e-4 * max_step) - \n       calculate_exact_merit(state)) / \n      1e-4; \n    double       step_size                 = 1; \n    unsigned int max_linesearch_iterations = 10; \n    for (unsigned int k = 0; k < max_linesearch_iterations; ++k) \n      { \n        if (calculate_exact_merit(state + step_size * max_step) < \n            calculate_exact_merit(state) + \n              step_size * descent_requirement * merit_derivative) \n          break; \n        else \n          step_size = step_size / 2; \n      } \n    return state + (step_size * max_step); \n  } \n\n  // @sect4{Checking for convergence}  \n\n  // \u672c\u5757\u4e2d\u7684\u6700\u540e\u4e00\u4e2a\u8f85\u52a9\u51fd\u6570\u662f\u68c0\u67e5\u662f\u5426\u5145\u5206\u6ee1\u8db3KKT\u6761\u4ef6\uff0c\u4ee5\u4fbf\u6574\u4e2a\u7b97\u6cd5\u53ef\u4ee5\u964d\u4f4e\u969c\u788d\u7269\u7684\u5927\u5c0f\u3002\u5b83\u901a\u8fc7\u8ba1\u7b97\u6b8b\u5dee\u7684 $l_1$ \u51c6\u5219\u6765\u5b9e\u73b0\uff0c\u8fd9\u5c31\u662f`calculate_test_rhs()`\u7684\u8ba1\u7b97\u3002\n\n  template <int dim> \n  bool SANDTopOpt<dim>::check_convergence(const BlockVector<double> &state) \n  { \n    const BlockVector<double> test_rhs      = calculate_test_rhs(state); \n    const double              test_rhs_norm = test_rhs.l1_norm(); \n\n    const double convergence_condition = 1e-2; \n    const double target_norm           = convergence_condition * barrier_size; \n\n    std::cout << \"    Checking convergence. Current rhs norm is \" \n              << test_rhs_norm << \", target is \" << target_norm << std::endl; \n\n    return (test_rhs_norm < target_norm); \n  } \n\n  // @sect3{Postprocessing the solution}  \n\n  // \u540e\u5904\u7406\u51fd\u6570\u4e2d\u7684\u7b2c\u4e00\u4e2a\u51fd\u6570\u5728VTU\u6587\u4ef6\u4e2d\u8f93\u51fa\u4fe1\u606f\uff0c\u7528\u4e8e\u53ef\u89c6\u5316\u3002\u5b83\u770b\u8d77\u6765\u5f88\u957f\uff0c\u4f46\u5b9e\u9645\u4e0a\u4e0e  step-22  \u4e2d\u6240\u505a\u7684\u4e00\u6837\uff0c\u4f8b\u5982\uff0c\u53ea\u662f\u589e\u52a0\u4e86\uff08\u5f88\u591a\uff09\u89e3\u51b3\u65b9\u6848\u7684\u53d8\u91cf\u3002\n\n  template <int dim> \n  void SANDTopOpt<dim>::output_results(const unsigned int iteration) const \n  { \n    std::vector<std::string> solution_names(1, \"density\"); \n    std::vector<DataComponentInterpretation::DataComponentInterpretation> \n      data_component_interpretation( \n        1, DataComponentInterpretation::component_is_scalar); \n    for (unsigned int i = 0; i < dim; ++i) \n      { \n        solution_names.emplace_back(\"displacement\"); \n        data_component_interpretation.push_back( \n          DataComponentInterpretation::component_is_part_of_vector); \n      } \n    solution_names.emplace_back(\"unfiltered_density\"); \n    data_component_interpretation.push_back( \n      DataComponentInterpretation::component_is_scalar); \n    for (unsigned int i = 0; i < dim; ++i) \n      { \n        solution_names.emplace_back(\"displacement_multiplier\"); \n        data_component_interpretation.push_back( \n          DataComponentInterpretation::component_is_part_of_vector); \n      } \n    solution_names.emplace_back(\"unfiltered_density_multiplier\"); \n    data_component_interpretation.push_back( \n      DataComponentInterpretation::component_is_scalar); \n    solution_names.emplace_back(\"low_slack\"); \n    data_component_interpretation.push_back( \n      DataComponentInterpretation::component_is_scalar); \n    solution_names.emplace_back(\"low_slack_multiplier\"); \n    data_component_interpretation.push_back( \n      DataComponentInterpretation::component_is_scalar); \n    solution_names.emplace_back(\"high_slack\"); \n    data_component_interpretation.push_back( \n      DataComponentInterpretation::component_is_scalar); \n    solution_names.emplace_back(\"high_slack_multiplier\"); \n    data_component_interpretation.push_back( \n      DataComponentInterpretation::component_is_scalar); \n\n    DataOut<dim> data_out; \n    data_out.attach_dof_handler(dof_handler); \n    data_out.add_data_vector(nonlinear_solution, \n                             solution_names, \n                             DataOut<dim>::type_dof_data, \n                             data_component_interpretation); \n    data_out.build_patches(); \n\n    std::ofstream output(\"solution\" + std::to_string(iteration) + \".vtu\"); \n    data_out.write_vtu(output); \n  } \n\n  // \u5176\u4e2d\u7b2c\u4e8c\u4e2a\u51fd\u6570\u5c06\u89e3\u51b3\u65b9\u6848\u8f93\u51fa\u4e3a`.stl`\u6587\u4ef6\uff0c\u7528\u4e8e3D\u6253\u5370\u3002STL](https:en.wikipedia.org/wiki/STL_(file_format))\u6587\u4ef6\u662f\u7531\u4e09\u89d2\u5f62\u548c\u6cd5\u7ebf\u5411\u91cf\u7ec4\u6210\u7684\uff0c\u6211\u4eec\u5c06\u7528\u5b83\u6765\u663e\u793a\u6240\u6709\u90a3\u4e9b\u5bc6\u5ea6\u503c\u5927\u4e8e0\u7684\u5355\u5143\uff0c\u9996\u5148\u5c06\u7f51\u683c\u4ece $z$ \u503c\u6324\u51fa\u5230 $z=0.25$  \uff0c\u7136\u540e\u4e3a\u5bc6\u5ea6\u503c\u8db3\u591f\u5927\u7684\u5355\u5143\u7684\u6bcf\u4e2a\u9762\u751f\u6210\u4e24\u4e2a\u4e09\u89d2\u5f62\u3002\u5f53\u4ece\u5916\u9762\u770b\u65f6\uff0c\u4e09\u89d2\u5f62\u8282\u70b9\u5fc5\u987b\u9006\u65f6\u9488\u8d70\uff0c\u6cd5\u5411\u91cf\u5fc5\u987b\u662f\u6307\u5411\u5916\u90e8\u7684\u5355\u4f4d\u5411\u91cf\uff0c\u8fd9\u9700\u8981\u8fdb\u884c\u4e00\u4e9b\u68c0\u67e5\u3002\n  template <int dim> \n  void SANDTopOpt<dim>::write_as_stl() \n  { \n    static_assert(dim == 2, \n                  \"This function is not implemented for anything \" \n                  \"other than the 2d case.\"); \n\n    std::ofstream stlfile; \n    stlfile.open(\"bridge.stl\"); \n\n    stlfile << \"solid bridge\\n\" << std::scientific; \n    double height = .25; \n\n    for (const auto &cell : dof_handler.active_cell_iterators()) \n      { \n        if (nonlinear_solution.block( \n              SolutionBlocks::density)[cell->active_cell_index()] > 0.5) \n          { \n            // \u6211\u4eec\u73b0\u5728\u5df2\u7ecf\u627e\u5230\u4e86\u4e00\u4e2a\u5bc6\u5ea6\u503c\u5927\u4e8e0\u7684\u5355\u5143\u3002\u8ba9\u6211\u4eec\u5148\u5199\u51fa\u5e95\u90e8\u548c\u9876\u90e8\u7684\u9762\u3002\u7531\u4e8e\u4e0a\u9762\u63d0\u5230\u7684\u6392\u5e8f\u95ee\u9898\uff0c\u6211\u4eec\u5fc5\u987b\u786e\u4fdd\u4e86\u89e3\u4e00\u4e2a\u5355\u5143\u7684\u5750\u6807\u7cfb\u662f\u53f3\u65cb\u7684\u8fd8\u662f\u5de6\u65cb\u7684\u3002\u6211\u4eec\u901a\u8fc7\u8be2\u95ee\u4ece\u9876\u70b90\u5f00\u59cb\u7684\u4e24\u6761\u8fb9\u7684\u65b9\u5411\u4ee5\u53ca\u5b83\u4eec\u662f\u5426\u5f62\u6210\u4e00\u4e2a\u53f3\u624b\u5750\u6807\u7cfb\u6765\u505a\u5230\u8fd9\u4e00\u70b9\u3002\n            const Tensor<1, dim> edge_directions[2] = {cell->vertex(1) - \n                                                         cell->vertex(0), \n                                                       cell->vertex(2) - \n                                                         cell->vertex(0)}; \n            const Tensor<2, dim> edge_tensor( \n              {{edge_directions[0][0], edge_directions[0][1]}, \n               {edge_directions[1][0], edge_directions[1][1]}}); \n            const bool is_right_handed_cell = (determinant(edge_tensor) > 0); \n\n            if (is_right_handed_cell) \n              { \n\n               /*\u5728z=0\u5904\u5199\u51fa\u4e00\u4e2a\u8fb9\u3002  */ \n                stlfile << \"   facet normal \" << 0.000000e+00 << \" \" \n                        << 0.000000e+00 << \" \" << -1.000000e+00 << \"\\n\"; \n                stlfile << \"      outer loop\\n\"; \n                stlfile << \"         vertex \" << cell->vertex(0)[0] << \" \" \n                        << cell->vertex(0)[1] << \" \" << 0.000000e+00 << \"\\n\"; \n                stlfile << \"         vertex \" << cell->vertex(2)[0] << \" \" \n                        << cell->vertex(2)[1] << \" \" << 0.000000e+00 << \"\\n\"; \n                stlfile << \"         vertex \" << cell->vertex(1)[0] << \" \" \n                        << cell->vertex(1)[1] << \" \" << 0.000000e+00 << \"\\n\"; \n                stlfile << \"      endloop\\n\"; \n                stlfile << \"   endfacet\\n\"; \n                stlfile << \"   facet normal \" << 0.000000e+00 << \" \" \n                        << 0.000000e+00 << \" \" << -1.000000e+00 << \"\\n\"; \n                stlfile << \"      outer loop\\n\"; \n                stlfile << \"         vertex \" << cell->vertex(1)[0] << \" \" \n                        << cell->vertex(1)[1] << \" \" << 0.000000e+00 << \"\\n\"; \n                stlfile << \"         vertex \" << cell->vertex(2)[0] << \" \" \n                        << cell->vertex(2)[1] << \" \" << 0.000000e+00 << \"\\n\"; \n                stlfile << \"         vertex \" << cell->vertex(3)[0] << \" \" \n                        << cell->vertex(3)[1] << \" \" << 0.000000e+00 << \"\\n\"; \n                stlfile << \"      endloop\\n\"; \n                stlfile << \"   endfacet\\n\"; \n\n               /*\u5728z=\u9ad8\u5ea6\u5904\u5199\u4e0b\u4e00\u4e2a\u8fb9\u3002  */  \n                stlfile << \"   facet normal \" << 0.000000e+00 << \" \" \n                        << 0.000000e+00 << \" \" << 1.000000e+00 << \"\\n\"; \n                stlfile << \"      outer loop\\n\"; \n                stlfile << \"         vertex \" << cell->vertex(0)[0] << \" \" \n                        << cell->vertex(0)[1] << \" \" << height << \"\\n\"; \n                stlfile << \"         vertex \" << cell->vertex(1)[0] << \" \" \n                        << cell->vertex(1)[1] << \" \" << height << \"\\n\"; \n                stlfile << \"         vertex \" << cell->vertex(2)[0] << \" \" \n                        << cell->vertex(2)[1] << \" \" << height << \"\\n\"; \n                stlfile << \"      endloop\\n\"; \n                stlfile << \"   endfacet\\n\"; \n                stlfile << \"   facet normal \" << 0.000000e+00 << \" \" \n                        << 0.000000e+00 << \" \" << 1.000000e+00 << \"\\n\"; \n                stlfile << \"      outer loop\\n\"; \n                stlfile << \"         vertex \" << cell->vertex(1)[0] << \" \" \n                        << cell->vertex(1)[1] << \" \" << height << \"\\n\"; \n                stlfile << \"         vertex \" << cell->vertex(3)[0] << \" \" \n                        << cell->vertex(3)[1] << \" \" << height << \"\\n\"; \n                stlfile << \"         vertex \" << cell->vertex(2)[0] << \" \" \n                        << cell->vertex(2)[1] << \" \" << height << \"\\n\"; \n                stlfile << \"      endloop\\n\"; \n                stlfile << \"   endfacet\\n\"; \n              } \n            else /* The cell has a left-handed set up */ \n              { \n               /* \u5728z=0\u5904\u5199\u51fa\u4e00\u8fb9\u3002  */ \n                stlfile << \"   facet normal \" << 0.000000e+00 << \" \"\n                        << 0.000000e+00 << \" \" << -1.000000e+00 << \"\\n\"; \n                stlfile << \"      outer loop\\n\"; \n                stlfile << \"         vertex \" << cell->vertex(0)[0] << \" \" \n                        << cell->vertex(0)[1] << \" \" << 0.000000e+00 << \"\\n\"; \n                stlfile << \"         vertex \" << cell->vertex(1)[0] << \" \" \n                        << cell->vertex(1)[1] << \" \" << 0.000000e+00 << \"\\n\"; \n                stlfile << \"         vertex \" << cell->vertex(2)[0] << \" \" \n                        << cell->vertex(2)[1] << \" \" << 0.000000e+00 << \"\\n\"; \n                stlfile << \"      endloop\\n\"; \n                stlfile << \"   endfacet\\n\"; \n                stlfile << \"   facet normal \" << 0.000000e+00 << \" \" \n                        << 0.000000e+00 << \" \" << -1.000000e+00 << \"\\n\"; \n                stlfile << \"      outer loop\\n\"; \n                stlfile << \"         vertex \" << cell->vertex(1)[0] << \" \" \n                        << cell->vertex(1)[1] << \" \" << 0.000000e+00 << \"\\n\"; \n                stlfile << \"         vertex \" << cell->vertex(3)[0] << \" \" \n                        << cell->vertex(3)[1] << \" \" << 0.000000e+00 << \"\\n\"; \n                stlfile << \"         vertex \" << cell->vertex(2)[0] << \" \" \n                        << cell->vertex(2)[1] << \" \" << 0.000000e+00 << \"\\n\"; \n                stlfile << \"      endloop\\n\"; \n                stlfile << \"   endfacet\\n\"; \n\n               /*\u5728z=\u9ad8\u5ea6\u5904\u5199\u51fa\u4e00\u4e2a\u8fb9\u3002  */ \n                stlfile << \"   facet normal \" << 0.000000e+00 << \" \" \n                        << 0.000000e+00 << \" \" << 1.000000e+00 << \"\\n\"; \n                stlfile << \"      outer loop\\n\"; \n                stlfile << \"         vertex \" << cell->vertex(0)[0] << \" \" \n                        << cell->vertex(0)[1] << \" \" << height << \"\\n\"; \n                stlfile << \"         vertex \" << cell->vertex(2)[0] << \" \" \n                        << cell->vertex(2)[1] << \" \" << height << \"\\n\"; \n                stlfile << \"         vertex \" << cell->vertex(1)[0] << \" \" \n                        << cell->vertex(1)[1] << \" \" << height << \"\\n\"; \n                stlfile << \"      endloop\\n\"; \n                stlfile << \"   endfacet\\n\"; \n                stlfile << \"   facet normal \" << 0.000000e+00 << \" \" \n                        << 0.000000e+00 << \" \" << 1.000000e+00 << \"\\n\"; \n                stlfile << \"      outer loop\\n\"; \n                stlfile << \"         vertex \" << cell->vertex(1)[0] << \" \" \n                        << cell->vertex(1)[1] << \" \" << height << \"\\n\"; \n                stlfile << \"         vertex \" << cell->vertex(2)[0] << \" \" \n                        << cell->vertex(2)[1] << \" \" << height << \"\\n\"; \n                stlfile << \"         vertex \" << cell->vertex(3)[0] << \" \" \n                        << cell->vertex(3)[1] << \" \" << height << \"\\n\"; \n                stlfile << \"      endloop\\n\"; \n                stlfile << \"   endfacet\\n\"; \n              } \n\n            // \u63a5\u4e0b\u6765\u6211\u4eec\u9700\u8981\u5904\u7406\u5355\u5143\u683c\u7684\u56db\u4e2a\u9762\uff0c\u6269\u5c55\u5230 $z$ \u65b9\u5411\u3002\u7136\u800c\uff0c\u6211\u4eec\u53ea\u9700\u8981\u5199\u8fd9\u4e9b\u9762\uff0c\u5982\u679c\u8be5\u9762\u5728\u57df\u7684\u8fb9\u754c\u4e0a\uff0c\u6216\u8005\u5b83\u662f\u5bc6\u5ea6\u5927\u4e8e0.5\u7684\u5355\u5143\u548c\u5bc6\u5ea6\u5c0f\u4e8e0.5\u7684\u5355\u5143\u4e4b\u95f4\u7684\u754c\u9762\u3002\n\n            for (unsigned int face_number = 0; \n                 face_number < GeometryInfo<dim>::faces_per_cell; \n                 ++face_number) \n              { \n                const typename DoFHandler<dim>::face_iterator face = \n                  cell->face(face_number); \n\n                if ((face->at_boundary()) || \n                    (!face->at_boundary() && \n                     (nonlinear_solution.block( \n                        0)[cell->neighbor(face_number)->active_cell_index()] < \n                      0.5))) \n                  { \n                    const Tensor<1, dim> normal_vector = \n                      (face->center() - cell->center()); \n                    const double normal_norm = normal_vector.norm(); \n                    if ((face->vertex(0)[0] - face->vertex(0)[0]) * \n                            (face->vertex(1)[1] - face->vertex(0)[1]) * \n                            0.000000e+00 + \n                          (face->vertex(0)[1] - face->vertex(0)[1]) * (0 - 0) * \n                            normal_vector[0] + \n                          (height - 0) * \n                            (face->vertex(1)[0] - face->vertex(0)[0]) * \n                            normal_vector[1] - \n                          (face->vertex(0)[0] - face->vertex(0)[0]) * (0 - 0) * \n                            normal_vector[1] - \n                          (face->vertex(0)[1] - face->vertex(0)[1]) * \n                            (face->vertex(1)[0] - face->vertex(0)[0]) * \n                            normal_vector[0] - \n                          (height - 0) * \n                            (face->vertex(1)[1] - face->vertex(0)[1]) * 0 > \n                        0) \n                      { \n                        stlfile << \"   facet normal \" \n                                << normal_vector[0] / normal_norm << \" \" \n                                << normal_vector[1] / normal_norm << \" \" \n                                << 0.000000e+00 << \"\\n\"; \n                        stlfile << \"      outer loop\\n\"; \n                        stlfile << \"         vertex \" << face->vertex(0)[0] \n                                << \" \" << face->vertex(0)[1] << \" \" \n                                << 0.000000e+00 << \"\\n\"; \n                        stlfile << \"         vertex \" << face->vertex(0)[0] \n                                << \" \" << face->vertex(0)[1] << \" \" << height \n                                << \"\\n\"; \n                        stlfile << \"         vertex \" << face->vertex(1)[0] \n                                << \" \" << face->vertex(1)[1] << \" \" \n                                << 0.000000e+00 << \"\\n\"; \n                        stlfile << \"      endloop\\n\"; \n                        stlfile << \"   endfacet\\n\"; \n                        stlfile << \"   facet normal \" \n                                << normal_vector[0] / normal_norm << \" \" \n                                << normal_vector[1] / normal_norm << \" \" \n                                << 0.000000e+00 << \"\\n\"; \n                        stlfile << \"      outer loop\\n\"; \n                        stlfile << \"         vertex \" << face->vertex(0)[0] \n                                << \" \" << face->vertex(0)[1] << \" \" << height \n                                << \"\\n\"; \n                        stlfile << \"         vertex \" << face->vertex(1)[0] \n                                << \" \" << face->vertex(1)[1] << \" \" << height \n                                << \"\\n\"; \n                        stlfile << \"         vertex \" << face->vertex(1)[0] \n                                << \" \" << face->vertex(1)[1] << \" \" \n                                << 0.000000e+00 << \"\\n\"; \n                        stlfile << \"      endloop\\n\"; \n                        stlfile << \"   endfacet\\n\"; \n                      } \n                    else \n                      { \n                        stlfile << \"   facet normal \" \n                                << normal_vector[0] / normal_norm << \" \" \n                                << normal_vector[1] / normal_norm << \" \" \n                                << 0.000000e+00 << \"\\n\"; \n                        stlfile << \"      outer loop\\n\"; \n                        stlfile << \"         vertex \" << face->vertex(0)[0] \n                                << \" \" << face->vertex(0)[1] << \" \" \n                                << 0.000000e+00 << \"\\n\"; \n                        stlfile << \"         vertex \" << face->vertex(1)[0] \n                                << \" \" << face->vertex(1)[1] << \" \" \n                                << 0.000000e+00 << \"\\n\"; \n                        stlfile << \"         vertex \" << face->vertex(0)[0] \n                                << \" \" << face->vertex(0)[1] << \" \" << height \n                                << \"\\n\"; \n                        stlfile << \"      endloop\\n\"; \n                        stlfile << \"   endfacet\\n\"; \n                        stlfile << \"   facet normal \" \n                                << normal_vector[0] / normal_norm << \" \" \n                                << normal_vector[1] / normal_norm << \" \" \n                                << 0.000000e+00 << \"\\n\"; \n                        stlfile << \"      outer loop\\n\"; \n                        stlfile << \"         vertex \" << face->vertex(0)[0] \n                                << \" \" << face->vertex(0)[1] << \" \" << height \n                                << \"\\n\"; \n                        stlfile << \"         vertex \" << face->vertex(1)[0] \n                                << \" \" << face->vertex(1)[1] << \" \" \n                                << 0.000000e+00 << \"\\n\"; \n                        stlfile << \"         vertex \" << face->vertex(1)[0] \n                                << \" \" << face->vertex(1)[1] << \" \" << height \n                                << \"\\n\"; \n                        stlfile << \"      endloop\\n\"; \n                        stlfile << \"   endfacet\\n\"; \n                      } \n                  } \n              } \n          } \n      } \n    stlfile << \"endsolid bridge\"; \n  } \n\n  //  @sect3{The run() function driving the overall algorithm}  \n\n  // \u8fd9\u4e2a\u51fd\u6570\u6700\u7ec8\u63d0\u4f9b\u4e86\u6574\u4f53\u7684\u9a71\u52a8\u903b\u8f91\u3002\u4ece\u603b\u4f53\u4e0a\u770b\uff0c\u8fd9\u662f\u4e00\u4e2a\u76f8\u5f53\u590d\u6742\u7684\u51fd\u6570\uff0c\u4e3b\u8981\u662f\u56e0\u4e3a\u4f18\u5316\u7b97\u6cd5\u5f88\u56f0\u96be\uff1a\u5b83\u4e0d\u4ec5\u4ec5\u662f\u50cf step-15 \u4e2d\u90a3\u6837\u627e\u5230\u4e00\u4e2a\u725b\u987f\u65b9\u5411\uff0c\u7136\u540e\u5728\u8fd9\u4e2a\u65b9\u5411\u4e0a\u518d\u8d70\u4e00\u4e2a\u56fa\u5b9a\u7684\u8ddd\u79bb\uff0c\u800c\u662f\u8981\uff08i\uff09\u786e\u5b9a\u5f53\u524d\u6b65\u9aa4\u4e2d\u7684\u6700\u4f73\u5bf9\u6570\u969c\u788d\u60e9\u7f5a\u53c2\u6570\u5e94\u8be5\u662f\u4ec0\u4e48\uff0c\uff08ii\uff09\u901a\u8fc7\u590d\u6742\u7684\u7b97\u6cd5\u6765\u786e\u5b9a\u6211\u4eec\u8981\u8d70\u591a\u8fdc\uff0c\u8fd8\u6709\u5176\u4ed6\u6210\u5206\u3002\u8ba9\u6211\u4eec\u770b\u770b\u5982\u4f55\u5728\u4e0b\u9762\u7684\u6587\u4ef6\u4e2d\u628a\u5b83\u5206\u89e3\u6210\u5c0f\u5757\u3002\n\n  // \u8be5\u51fd\u6570\u4e00\u5f00\u59cb\u5c31\u5f88\u7b80\u5355\uff0c\u9996\u5148\u8bbe\u7f6e\u4e86\u7f51\u683c\u3001DoFHandler\uff0c\u7136\u540e\u662f\u4e0b\u9762\u6240\u9700\u7684\u5404\u79cd\u7ebf\u6027\u4ee3\u6570\u5bf9\u8c61\u3002\n\n  template <int dim> \n  void SANDTopOpt<dim>::run() \n  { \n    std::cout << \"filter r is: \" << filter_r << std::endl; \n\n    { \n      TimerOutput::Scope t(timer, \"setup\"); \n\n      create_triangulation(); \n\n      dof_handler.distribute_dofs(fe); \n      DoFRenumbering::component_wise(dof_handler); \n\n      setup_boundary_values(); \n      setup_block_system(); \n      setup_filter_matrix(); \n    } \n\n  // \u7136\u540e\uff0c\u6211\u4eec\u8bbe\u7f6e\u4e00\u4e9b\u5f71\u54cd\u4f18\u5316\u7b97\u6cd5\u7684\u5bf9\u6570\u5c4f\u969c\u548c\u76f4\u7ebf\u641c\u7d22\u90e8\u5206\u7684\u53c2\u6570\u3002\n\n    barrier_size                  = 25; \n    const double min_barrier_size = .0005; \n\n    const unsigned int max_uphill_steps    = 8; \n    const double       descent_requirement = .0001; \n\n    // \u73b0\u5728\u5f00\u59cb\u8fdb\u884c\u4e3b\u8fed\u4ee3\u3002\u6574\u4e2a\u7b97\u6cd5\u901a\u8fc7\u4f7f\u7528\u4e00\u4e2a\u5916\u5faa\u73af\u6765\u5de5\u4f5c\uff0c\u5728\u8fd9\u4e2a\u5916\u5faa\u73af\u4e2d\uff0c\u6211\u4eec\u4e00\u76f4\u5faa\u73af\u5230\uff08i\uff09\u5bf9\u6570\u969c\u788d\u53c2\u6570\u53d8\u5f97\u8db3\u591f\u5c0f\uff0c\u6216\u8005\uff08ii\uff09\u6211\u4eec\u5df2\u7ecf\u8fbe\u5230\u6536\u655b\u3002\u5728\u4efb\u4f55\u60c5\u51b5\u4e0b\uff0c\u5982\u679c\u6700\u7ec8\u7684\u8fed\u4ee3\u6b21\u6570\u8fc7\u591a\uff0c\u6211\u4eec\u5c31\u4f1a\u7ec8\u6b62\u3002\u8fd9\u4e2a\u6574\u4f53\u7ed3\u6784\u88ab\u7f16\u7801\u4e3a\u4e00\u4e2a \"do{ ... } while (...)`\u5faa\u73af\uff0c\u5176\u4e2d\u6536\u655b\u6761\u4ef6\u5728\u5e95\u90e8\u3002\n\n    unsigned int       iteration_number = 0; \n    const unsigned int max_iterations   = 10000; \n\n    do \n      { \n        std::cout << \"Starting outer step in iteration \" << iteration_number \n                  << \" with barrier parameter \" << barrier_size << std::endl; \n\n        // \u5728\u8fd9\u4e2a\u5916\u5faa\u73af\u4e2d\uff0c\u6211\u4eec\u6709\u4e00\u4e2a\u5185\u5faa\u73af\uff0c\u5728\u8fd9\u4e2a\u5185\u5faa\u73af\u4e2d\uff0c\u6211\u4eec\u8bd5\u56fe\u4f7f\u7528\u4ecb\u7ecd\u4e2d\u63cf\u8ff0\u7684\u770b\u95e8\u72d7\u7b97\u6cd5\u627e\u5230\u4e00\u4e2a\u66f4\u65b0\u65b9\u5411\u3002\n\n        // \u770b\u95e8\u72d7\u7b97\u6cd5\u672c\u8eab\u7684\u603b\u4f53\u601d\u8def\u662f\u8fd9\u6837\u7684\u3002\u5bf9\u4e8e\u6700\u5927\u7684`max_uphill_steps`\uff08\u5373\u4e0a\u8ff0 \"\u5185\u5faa\u73af \"\u4e2d\u7684\u4e00\u4e2a\u5faa\u73af\uff09\u7684\u5c1d\u8bd5\uff0c\u6211\u4eec\u4f7f\u7528`find_max_step()`\u6765\u8ba1\u7b97\u725b\u987f\u66f4\u65b0\u6b65\u9aa4\uff0c\u5e76\u5728`nonlinear_solution`\u5411\u91cf\u4e2d\u52a0\u4e0a\u8fd9\u4e9b\u3002 \u5728\u6bcf\u4e00\u6b21\u5c1d\u8bd5\u4e2d\uff08\u4ece\u4e0a\u4e00\u6b21\u5c1d\u8bd5\u7ed3\u675f\u65f6\u5230\u8fbe\u7684\u5730\u65b9\u5f00\u59cb\uff09\uff0c\u6211\u4eec\u68c0\u67e5\u6211\u4eec\u662f\u5426\u5df2\u7ecf\u8fbe\u5230\u4e86\u4e0a\u8ff0\u4f18\u70b9\u51fd\u6570\u7684\u76ee\u6807\u503c\u3002\u76ee\u6807\u503c\u662f\u6839\u636e\u672c\u7b97\u6cd5\u7684\u8d77\u59cb\u4f4d\u7f6e\uff08\u770b\u95e8\u72d7\u5faa\u73af\u5f00\u59cb\u65f6\u7684`nonlinear_solution'\uff0c\u4fdd\u5b58\u4e3a`\u770b\u95e8\u72d7_state'\uff09\u548c\u672c\u5faa\u73af\u7b2c\u4e00\u4e2a\u56de\u5408\u4e2d`find_max_step()'\u63d0\u4f9b\u7684\u7b2c\u4e00\u4e2a\u5efa\u8bae\u65b9\u5411\uff08`k=0'\u60c5\u51b5\uff09\u8ba1\u7b97\u7684\u3002\n\n        do \n          { \n            std::cout << \"  Starting inner step in iteration \" \n                      << iteration_number \n                      << \" with merit function penalty multiplier \" \n                      << penalty_multiplier << std::endl; \n\n            bool watchdog_step_found = false; \n\n            const BlockVector<double> watchdog_state = nonlinear_solution; \n            BlockVector<double>       first_step; \n            double target_merit     = numbers::signaling_nan<double>(); \n            double merit_derivative = numbers::signaling_nan<double>(); \n\n            for (unsigned int k = 0; k < max_uphill_steps; ++k) \n              { \n                ++iteration_number; \n                const BlockVector<double> update_step = find_max_step(); \n\n                if (k == 0) \n                  { \n                    first_step = update_step; \n                    merit_derivative = \n                      ((calculate_exact_merit(watchdog_state + \n                                              .0001 * first_step) - \n                        calculate_exact_merit(watchdog_state)) / \n                       .0001); \n                    target_merit = calculate_exact_merit(watchdog_state) + \n                                   descent_requirement * merit_derivative; \n                  } \n\n                nonlinear_solution += update_step; \n                const double current_merit = \n                  calculate_exact_merit(nonlinear_solution); \n\n                std::cout << \"    current watchdog state merit is: \" \n                          << current_merit << \"; target merit is \" \n                          << target_merit << std::endl; \n\n                if (current_merit < target_merit) \n                  { \n                    watchdog_step_found = true; \n                    std::cout << \"    found workable step after \" << k + 1 \n                              << \" iterations\" << std::endl; \n                    break; \n                  } \n              } \n            //\u7136\u540e\n            //\u7b97\u6cd5\u7684\u4e0b\u4e00\u90e8\u5206\u53d6\u51b3\u4e8e\u4e0a\u9762\u7684\u770b\u95e8\u72d7\u5faa\u73af\u662f\u5426\u6210\u529f\u3002\u5982\u679c\u6210\u529f\u4e86\uff0c\u90a3\u4e48\u6211\u4eec\u5c31\u6ee1\u610f\u4e86\uff0c\u4e0d\u9700\u8981\u8fdb\u4e00\u6b65\u7684\u884c\u52a8\u3002\u6211\u4eec\u53ea\u662f\u505c\u7559\u5728\u539f\u5730\u3002\u7136\u800c\uff0c\u5982\u679c\u6211\u4eec\u5728\u4e0a\u9762\u7684\u5faa\u73af\u4e2d\u91c7\u53d6\u4e86\u6700\u5927\u6570\u91cf\u7684\u4e0d\u6210\u529f\u7684\u6b65\u9aa4\uff0c\u90a3\u4e48\u6211\u4eec\u5c31\u9700\u8981\u505a\u4e00\u4e9b\u522b\u7684\u4e8b\u60c5\uff0c\u8fd9\u5c31\u662f\u4e0b\u9762\u7684\u4ee3\u7801\u5757\u6240\u505a\u7684\u3002    \u5177\u4f53\u6765\u8bf4\uff0c\u4ece\u4e0a\u8ff0\u5faa\u73af\u7684\u6700\u540e\uff08\u4e0d\u6210\u529f\u7684\uff09\u72b6\u6001\u5f00\u59cb\uff0c\u6211\u4eec\u518d\u5bfb\u627e\u4e00\u4e2a\u66f4\u65b0\u65b9\u5411\uff0c\u5e76\u91c7\u53d6\u6240\u8c13\u7684 \"\u4f38\u5c55\u6b65\u9aa4\"\u3002\u5982\u679c\u8be5\u62c9\u4f38\u72b6\u6001\u6ee1\u8db3\u6d89\u53ca\u4f18\u70b9\u51fd\u6570\u7684\u6761\u4ef6\uff0c\u90a3\u4e48\u6211\u4eec\u5c31\u53bb\u90a3\u91cc\u3002\u53e6\u4e00\u65b9\u9762\uff0c\u5982\u679c\u62c9\u4f38\u72b6\u6001\u4e5f\u662f\u4e0d\u53ef\u63a5\u53d7\u7684\uff08\u5c31\u50cf\u4e0a\u9762\u6240\u6709\u7684\u770b\u95e8\u72d7\u6b65\u9aa4\u4e00\u6837\uff09\uff0c\u90a3\u4e48\u6211\u4eec\u5c31\u653e\u5f03\u4e0a\u9762\u6240\u6709\u7684\u770b\u95e8\u72d7\u6b65\u9aa4\uff0c\u5728\u6211\u4eec\u5f00\u59cb\u770b\u95e8\u72d7\u8fed\u4ee3\u7684\u5730\u65b9\u91cd\u65b0\u5f00\u59cb--\u90a3\u4e2a\u5730\u65b9\u88ab\u5b58\u50a8\u5728\u4e0a\u9762\u7684`\u770b\u95e8\u72d7_\u72b6\u6001`\u53d8\u91cf\u4e2d\u3002\u66f4\u5177\u4f53\u5730\u8bf4\uff0c\u4e0b\u9762\u7684\u6761\u4ef6\u9996\u5148\u6d4b\u8bd5\u6211\u4eec\u662f\u5426\u4ece`\u770b\u95e8\u72d7_state`\u65b9\u5411\u7684`first_step`\u8d70\u4e86\u4e00\u6b65\uff0c\u6216\u8005\u6211\u4eec\u662f\u5426\u53ef\u4ee5\u4ece\u62c9\u4f38\u72b6\u6001\u518d\u505a\u4e00\u6b21\u66f4\u65b0\u6765\u627e\u5230\u4e00\u4e2a\u65b0\u7684\u5730\u65b9\u3002\u6709\u53ef\u80fd\u8fd9\u4e24\u79cd\u60c5\u51b5\u5b9e\u9645\u4e0a\u90fd\u4e0d\u6bd4\u6211\u4eec\u5728\u770b\u95e8\u72d7\u7b97\u6cd5\u5f00\u59cb\u65f6\u7684\u72b6\u6001\u597d\uff0c\u4f46\u5373\u4f7f\u662f\u8fd9\u6837\uff0c\u90a3\u4e2a\u5730\u65b9\u663e\u7136\u662f\u4e2a\u56f0\u96be\u7684\u5730\u65b9\uff0c\u79bb\u5f00\u540e\u4ece\u53e6\u4e00\u4e2a\u5730\u65b9\u5f00\u59cb\u4e0b\u4e00\u6b21\u8fed\u4ee3\u53ef\u80fd\u662f\u4e00\u4e2a\u6709\u7528\u7684\u7b56\u7565\uff0c\u6700\u7ec8\u6536\u655b\u3002    \u6211\u4eec\u4e0d\u65ad\u91cd\u590d\u4e0a\u9762\u7684\u770b\u95e8\u72d7\u6b65\u9aa4\u4ee5\u53ca\u4e0b\u9762\u7684\u903b\u8f91\uff0c\u76f4\u5230\u8fd9\u4e2a\u5185\u90e8\u8fed\u4ee3\u6700\u7ec8\u6536\u655b\uff08\u6216\u8005\u5982\u679c\u6211\u4eec\u9047\u5230\u6700\u5927\u7684\u8fed\u4ee3\u6b21\u6570--\u5728\u8fd9\u91cc\u6211\u4eec\u628a\u7ebf\u6027\u6c42\u89e3\u7684\u6b21\u6570\u7b97\u4f5c\u8fed\u4ee3\u6b21\u6570\uff0c\u5e76\u5728\u6bcf\u6b21\u8c03\u7528`find_max_step()`\u65f6\u589e\u52a0\u8ba1\u6570\u5668\uff0c\u56e0\u4e3a\u8fd9\u5c31\u662f\u7ebf\u6027\u6c42\u89e3\u5b9e\u9645\u53d1\u751f\u7684\u5730\u65b9\uff09\u3002\u5728\u4efb\u4f55\u60c5\u51b5\u4e0b\uff0c\u5728\u8fd9\u4e9b\u5185\u90e8\u8fed\u4ee3\u7684\u6bcf\u4e00\u6b21\u7ed3\u675f\u65f6\uff0c\u6211\u4eec\u4e5f\u4f1a\u4ee5\u9002\u5408\u53ef\u89c6\u5316\u7684\u5f62\u5f0f\u8f93\u51fa\u89e3\u51b3\u65b9\u6848\u3002\n\n            if (watchdog_step_found == false) \n              { \n                ++iteration_number; \n                const BlockVector<double> update_step = find_max_step(); \n                const BlockVector<double> stretch_state = \n                  compute_scaled_step(nonlinear_solution, \n                                      update_step, \n                                      descent_requirement); \n\n                // \u5982\u679c\u6211\u4eec\u6ca1\u6709\u5f97\u5230\u4e00\u4e2a\u6210\u529f\u7684\u770b\u95e8\u72d7\u6b65\u9aa4\uff0c\u6211\u4eec\u73b0\u5728\u9700\u8981\u51b3\u5b9a\u662f\u56de\u5230\u6211\u4eec\u5f00\u59cb\u7684\u5730\u65b9\uff0c\u8fd8\u662f\u4f7f\u7528\u6700\u7ec8\u72b6\u6001\u3002 \u6211\u4eec\u6bd4\u8f83\u8fd9\u4e24\u4e2a\u4f4d\u7f6e\u7684\u4f18\u52a3\uff0c\u7136\u540e\u4ece\u54ea\u4e2a\u4f4d\u7f6e\u53d6\u4e00\u4e2a\u6309\u6bd4\u4f8b\u7684\u6b65\u957f\u3002 \u7531\u4e8e\u6309\u6bd4\u4f8b\u7684\u6b65\u957f\u53ef\u4ee5\u4fdd\u8bc1\u964d\u4f4e\u4f18\u70b9\uff0c\u6240\u4ee5\u6211\u4eec\u6700\u7ec8\u4f1a\u4fdd\u7559\u8fd9\u4e24\u4e2a\u4f4d\u7f6e\u4e2d\u7684\u4e00\u4e2a\u3002\n\n                if ((calculate_exact_merit(nonlinear_solution) < \n                     calculate_exact_merit(watchdog_state)) || \n                    (calculate_exact_merit(stretch_state) < target_merit)) \n                  { \n                    std::cout << \"    Taking scaled step from end of watchdog\" \n                              << std::endl; \n                    nonlinear_solution = stretch_state; \n                  } \n                else \n                  { \n                    std::cout \n                      << \"    Taking scaled step from beginning of watchdog\" \n                      << std::endl; \n                    if (calculate_exact_merit(stretch_state) > \n                        calculate_exact_merit(watchdog_state)) \n                      { \n                        nonlinear_solution = \n                          compute_scaled_step(watchdog_state, \n                                              first_step, \n                                              descent_requirement); \n                      } \n                    else \n                      { \n                        ++iteration_number; \n                        nonlinear_solution = stretch_state; \n                        const BlockVector<double> stretch_step = \n                          find_max_step(); \n                        nonlinear_solution = \n                          compute_scaled_step(nonlinear_solution, \n                                              stretch_step, \n                                              descent_requirement); \n                      } \n                  } \n              } \n\n            output_results(iteration_number); \n          } \n        while ((iteration_number < max_iterations) && \n               (check_convergence(nonlinear_solution) == false)); \n\n        // \u5728\u5916\u5faa\u73af\u7ed3\u675f\u65f6\uff0c\u6211\u4eec\u5fc5\u987b\u66f4\u65b0\u5c4f\u969c\u53c2\u6570\uff0c\u4e3a\u6b64\u6211\u4eec\u4f7f\u7528\u4ee5\u4e0b\u516c\u5f0f\u3002\u8be5\u51fd\u6570\u7684\u5176\u4f59\u90e8\u5206\u53ea\u662f\u68c0\u67e5\u5916\u5faa\u73af\u7684\u6536\u655b\u6761\u4ef6\uff0c\u5982\u679c\u6211\u4eec\u51b3\u5b9a\u7ec8\u6b62\u8ba1\u7b97\uff0c\u5c31\u628a\u6700\u7ec8\u7684 \"\u8bbe\u8ba1 \"\u5199\u6210STL\u6587\u4ef6\uff0c\u7528\u4e8e3D\u6253\u5370\uff0c\u5e76\u8f93\u51fa\u4e00\u4e9b\u65f6\u95f4\u4fe1\u606f\u3002\n\n        const double barrier_size_multiplier = .8; \n        const double barrier_size_exponent   = 1.2; \n\n        barrier_size = \n          std::max(std::min(barrier_size * barrier_size_multiplier, \n                            std::pow(barrier_size, barrier_size_exponent)), \n                   min_barrier_size); \n\n        std::cout << std::endl; \n      } \n    while (((barrier_size > min_barrier_size) || \n            (check_convergence(nonlinear_solution) == false)) && \n           (iteration_number < max_iterations)); \n\n    write_as_stl(); \n    timer.print_summary(); \n  } \n} // namespace SAND \n// @sect3{The main function}  \n\n// \u4f59\u4e0b\u7684\u4ee3\u7801\uff0c\u5373`main()`\u51fd\u6570\uff0c\u548c\u5e73\u5e38\u4e00\u6837\u3002\n\nint main() \n{ \n  try \n    { \n      SAND::SANDTopOpt<2> elastic_problem_2d; \n      elastic_problem_2d.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      return 1;\n    }\n  return 0;\n}\n", "meta": {"hexsha": "2c1bd1cb9e57b3b8e3b20efac58b79f5524a6c61", "size": 93327, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-79/step-79.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-79/step-79.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-79/step-79.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": 44.5900621118, "max_line_length": 635, "alphanum_fraction": 0.5522196149, "num_tokens": 26291, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.4680972437179087}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n\ntemplate <typename SPARSE_MAT1, typename SPARSE_MAT2, typename VEC_SRC, typename VEC_DST>\nvoid\nsparse_outer_product_multiply(VEC_DST& dst_vec,\n                              const SPARSE_MAT1& M1,\n                              const SPARSE_MAT2& M2,\n                              const VEC_SRC& src_vec)\n{\n  // apply M2\n  typedef Eigen::VectorXd vec_t;\n  typedef Eigen::Map<vec_t> vvec_t;\n  typedef Eigen::Map<const vec_t> const_vvec_t;\n\n  unsigned int Nx = M2.cols();\n  unsigned int Ny = M2.rows();\n  unsigned int Ly = dst_vec.size() / Ny;\n  unsigned int Lx = src_vec.size() / Nx;\n  assert(src_vec.size() % Nx == 0);\n  assert(dst_vec.size() % Ny == 0);\n\n  typedef typename SPARSE_MAT1::InnerIterator InnerIterator1;\n  typedef typename SPARSE_MAT2::InnerIterator InnerIterator2;\n\n  for (unsigned int i = 0; i < Lx; ++i) {\n    vvec_t ldest(dst_vec.data() + i * Ny, Ny);\n    const_vvec_t lsrc(src_vec.data() + i * Nx, Nx);\n\n    ldest = M2 * lsrc;\n  }\n\n  // copy\n  vec_t tmp = dst_vec;\n  dst_vec *= 0;\n\n  // apply M1\n  for (int k = 0; k < M1.outerSize(); ++k) {\n    for (InnerIterator1 it(M1, k); it; ++it) {\n      vvec_t ldst(dst_vec.data() + it.row() * Ny, Ny);\n      const_vvec_t lsrc(tmp.data() + it.col() * Ny, Ny);\n      ldst += it.value() * lsrc;\n    }\n  }\n}\n", "meta": {"hexsha": "5d927e1051dcaaa3f056c58d0bb4e037603937ce", "size": 1324, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "applications/convergence_plots/outer_product_helper.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": "applications/convergence_plots/outer_product_helper.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": "applications/convergence_plots/outer_product_helper.hpp", "max_forks_repo_name": "simonpintarelli/2dBoltzmann", "max_forks_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5833333333, "max_line_length": 89, "alphanum_fraction": 0.6057401813, "num_tokens": 401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185944046238981, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.468059961173583}}
{"text": "/*!\n * @file\n *\n * @section LICENSE\n *\n * Copyright (C) 2017 by the Georgia Tech Research Institute (GTRI)\n *\n * This file is part of SCRIMMAGE.\n *\n *   SCRIMMAGE is free software: you can redistribute it and/or modify it under\n *   the terms of the GNU Lesser General Public License as published by the\n *   Free Software Foundation, either version 3 of the License, or (at your\n *   option) any later version.\n *\n *   SCRIMMAGE is distributed in the hope that it will be useful, but WITHOUT\n *   ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n *   FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public\n *   License for more details.\n *\n *   You should have received a copy of the GNU Lesser General Public License\n *   along with SCRIMMAGE.  If not, see <http://www.gnu.org/licenses/>.\n *\n * @author Kevin DeMarco <kevin.demarco@gtri.gatech.edu>\n * @author Eric Squires <eric.squires@gtri.gatech.edu>\n * @date 31 July 2017\n * @version 0.1.0\n * @brief Brief file description.\n * @section DESCRIPTION\n * A Long description goes here.\n *\n */\n#include <smallbets/plugins/interaction/OceanParameters/OceanMap.h>\n#include <scrimmage/proto/ProtoConversions.h>\n\n#include <boost/algorithm/clamp.hpp>\n\nnamespace sc = scrimmage;\nnamespace sp = scrimmage_proto;\n\nusing std::cout;\nusing std::endl;\n\nusing boost::algorithm::clamp;\n\nnamespace scrimmage {\nnamespace interaction {\n\nOceanMap::OceanMap() {}\n\nOceanMap::OceanMap(const Technique &technique,const double &x_length,\n             const double &y_length, const double &z_length,\n             const double &x_resolution, const double &y_resolution,\n             const double &z_resolution) :\n        technique_(technique),\n        x_length_(x_length),\n        y_length_(y_length),\n        z_length_(z_length),\n        x_resolution_(x_resolution),\n        y_resolution_(y_resolution),\n        z_resolution_(z_resolution),\n        grid_(std::vector<double>(x_length_*y_length_*z_length_)) {\n    generate();\n}\n\nOceanMap::OceanMap(const smallbets::msgs::Ocean &Ocean) :\n        x_length_(Ocean.x_length()), y_length_(Ocean.y_length()),\n        z_length_(Ocean.z_length()), x_resolution_(Ocean.x_resolution()),\n        y_resolution_(Ocean.y_resolution()), z_resolution_(Ocean.z_resolution()),\n        grid_(std::vector<double>(x_length_*y_length_*z_length_)) {\n\n    // Populate the grid\n    for (int r = 0; r < Ocean.map().row_size(); ++r) {\n            grid_[r] = Ocean.map().row(r);\n    }\n}\n\nbool OceanMap::generate() {\n    if (technique_ == Technique::MUNK) {\n        return generate_Munk();\n    } return false;\n}\n\nbool OceanMap::generate_Munk() {\n    // Force the altitude center to be at the midpoint between z_max and z_min\n    double C_z_ = 1500; //Sound Speed\n    double z = 0;\n    // MUNK Profile C(z) = 1500 * (1 + E * (zt - 1 + E^-zt)); zt = (2 * (z - zc))/zc;\n    double ep = 0.00737;\n    double zc = 500; //m depth of minimum sound speed\n    for (unsigned int row = 0; row < y_length_; ++row) {\n        for (unsigned int col = 0; col < x_length_; ++col) {\n            for (unsigned int depth = 0; depth < z_length_; ++depth) {\n                z = depth * z_resolution_;\n                C_z_ = 1500 * (1 + ep * ((2 * (z - zc))/zc - 1 + exp((-(2 * (z - zc))/zc))));\n                grid_[(row*x_length_*z_length_)+(col*z_length_)+depth] = C_z_;\n                //grid_[(row*x_length_*z_length_)+(col*z_length_)+depth].is_set = true;\n            }\n        }\n    }\n    return true;\n}\n\nsmallbets::msgs::Ocean OceanMap::proto() {\n    smallbets::msgs::Ocean Ocean;\n    Ocean.set_x_length(x_length_);\n    Ocean.set_y_length(y_length_);\n    Ocean.set_z_length(z_length_);\n    Ocean.set_x_resolution(x_resolution_);\n    Ocean.set_y_resolution(y_resolution_);\n    Ocean.set_z_resolution(z_resolution_);\n    for (unsigned int r = 0; r < y_length_; ++r) {\n        for (unsigned int c = 0; c < x_length_; ++c) {\n            for (unsigned int d = 0; d < z_length_; ++d) {\n                int idx = (r*x_length_*z_length_)+(c*z_length_)+d;\n                Ocean.mutable_map()->add_row(grid_[idx]);\n                //std::cout << \"(Depth,Speed) : (\" << (d * z_resolution_) << \", \" << grid_[idx] << \")\" << std::endl;\n            }\n        }\n    }\n    return Ocean;\n}\n\n//Method to get parameters at XYZ location\ndouble OceanMap::param_at(const double &x, const double &y,const double &z) {\n// get nearest neighbor (Add on later interp around value)\n    std::vector<int> idx_dist(x_length_*y_length_*z_length_);\n    std::vector<double> dist(x_length_*y_length_*z_length_);\n    for (unsigned int r = 0; r < y_length_; ++r) {\n        for (unsigned int c = 0; c < x_length_; ++c) {\n            for (unsigned int d = 0; d < z_length_; ++d) {\n                int idx_cnt = (r*x_length_*z_length_)+(c*z_length_)+d;\n                double x2 = c * x_resolution_ - (x_length_ * x_resolution_ * 0.5);\n                double y2 = r * y_resolution_ - (y_length_ * y_resolution_ * 0.5);\n                double z2 = d * z_resolution_;\n                double xSqr = (x - x2) * (x - x2);\n                double ySqr = (y - y2) * (y - y2);\n                double zSqr = ((-z) - z2) * ((-z) - z2);\n                dist[idx_cnt] = sqrt(xSqr + ySqr + zSqr);\n                idx_dist[idx_cnt] = idx_cnt;\n            }\n        }\n    }\n    double dist_min = (std::min_element(dist.begin(), dist.end())) - dist.begin();\n    int idx_min = idx_dist[dist_min];\n\n    if (dist_min >= 0) {\n        return grid_[idx_min];\n    }\n    std::cout << \"Error: Sound Speed Data out of Range\" << std::endl;\n    return 9999;\n    //grid_[(row*x_length_*z_length_)+(col*z_length_)+depth] = C_z_;\n}\n} // namespace interaction\n} // namespace scrimmage\n", "meta": {"hexsha": "eb05d4d19dceeda1244be4ba4c5ea6c32f190922", "size": 5677, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "smallbets/src/plugins/interaction/OceanParameters/OceanMap.cpp", "max_stars_repo_name": "sarapierson234/SMALLBETS", "max_stars_repo_head_hexsha": "f78add47dada5848b4a44053011bc52bf4edbf2d", "max_stars_repo_licenses": ["Naumen", "Condor-1.1", "MS-PL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "smallbets/src/plugins/interaction/OceanParameters/OceanMap.cpp", "max_issues_repo_name": "sarapierson234/SMALLBETS", "max_issues_repo_head_hexsha": "f78add47dada5848b4a44053011bc52bf4edbf2d", "max_issues_repo_licenses": ["Naumen", "Condor-1.1", "MS-PL"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-03-19T19:51:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-19T19:51:38.000Z", "max_forks_repo_path": "smallbets/src/plugins/interaction/OceanParameters/OceanMap.cpp", "max_forks_repo_name": "sarapierson234/SMALLBETS", "max_forks_repo_head_hexsha": "f78add47dada5848b4a44053011bc52bf4edbf2d", "max_forks_repo_licenses": ["Naumen", "Condor-1.1", "MS-PL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.6258064516, "max_line_length": 116, "alphanum_fraction": 0.6152897657, "num_tokens": 1543, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.6513548714339145, "lm_q1q2_score": 0.46805995818612184}}
{"text": "#include <cstdint>\r\n#include <algorithm>\r\n#include <fstream>\r\n#include <functional>\r\n#include <iomanip>\r\n#include <iostream>\r\n#include <random>\r\n#include <sstream>\r\n#include <string>\r\n#include <unordered_map>\r\n#include <utility>\r\n\r\n#include <boost/math/distributions/gamma.hpp>\r\n#include <boost/math/distributions/negative_binomial.hpp>\r\n#include <boost/cast.hpp>\r\n#include <boost/random/negative_binomial_distribution.hpp>\r\n\r\nnamespace {\r\n    using ParamType = double;\r\n    using ResultType = int;\r\n    using DensityType = double;\r\n    using RandEngine = std::mt19937;\r\n    using SizeType = size_t;\r\n    using SeedType = std::mt19937::result_type;\r\n\r\n    struct ParamSet {\r\n        ParamType size;\r\n        ParamType prob;\r\n    };\r\n\r\n    struct FileSet {\r\n        SizeType n;\r\n        std::string filename;\r\n    };\r\n\r\n    const std::vector<ParamType> SizeSet {2, 4, 6, 8};\r\n    const std::vector<ParamType> ProbSet {0.1, 0.15, 0.25, 0.5};\r\n    const std::vector<FileSet> AllFileSet {\r\n        {100, \"nbinom100.csv\"},\r\n        {1000, \"nbinom1k.csv\"},\r\n        {10000, \"nbinom10k.csv\"},\r\n        {100000, \"nbinom100k.csv\"},\r\n    };\r\n}\r\n\r\nvoid rnbinomCpp(const auto& paramSet, SizeType n, SeedType seed, std::ofstream& ofs) {\r\n    const ParamType alpha = paramSet.size;\r\n    // Notice that prob for R means 1 - prob in C++\r\n    const ParamType prob = paramSet.prob;\r\n    const ParamType beta = (1 - prob) / prob;\r\n    std::mt19937 gen(seed);\r\n\r\n    std::gamma_distribution<double> distGamma(alpha, beta);\r\n    std::unordered_map<ResultType, SizeType> count;\r\n\r\n    // Cannot use alpha as integers\r\n    using StdAlpha = int;\r\n    const auto stdAlpha = boost::numeric_cast<StdAlpha>(alpha);\r\n    std::negative_binomial_distribution<StdAlpha> distNB(stdAlpha, beta);\r\n\r\n    // Makes random values\r\n    ResultType maxValue = 0;\r\n    for (decltype(n) i=0; i<n; ++i) {\r\n        std::poisson_distribution<ResultType> dist(distGamma(gen));\r\n        const auto value = dist(gen);\r\n        count[value] += 1;\r\n        maxValue = std::max(maxValue, value);\r\n    }\r\n\r\n    // Can eliminate outliers\r\n    const SizeType sizeLimit = n + 100; //  n / 100;\r\n    SizeType totalCount = 0;\r\n    for (ResultType value=0; value<=maxValue; ++value) {\r\n        // Writes densities in a long format\r\n        const auto binCount = count[value];\r\n        totalCount += binCount;\r\n        const DensityType density = static_cast<DensityType>(binCount) / static_cast<DensityType>(n);\r\n        ofs << alpha << \",\" << beta << \",\" << prob << \",\" << value << \",\" << density << \"\\n\";\r\n        if (totalCount >= sizeLimit) {\r\n            break;\r\n        }\r\n    }\r\n    return;\r\n}\r\n\r\nvoid rnbinomCppAll(void) {\r\n    constexpr SeedType seed = 123;\r\n\r\n    for(const auto& fileSet :AllFileSet) {\r\n        // Writes titles\r\n        std::ofstream ofs(fileSet.filename);\r\n        ofs << \"alpha,beta,prob,x,density\" << std::endl;\r\n\r\n        for(const auto& size : SizeSet) {\r\n            for(const auto& prob : ProbSet) {\r\n                const ParamSet paramSet {size, prob};\r\n                rnbinomCpp(paramSet, fileSet.n, seed, ofs);\r\n            }\r\n        }\r\n    }\r\n}\r\n\r\ntemplate <typename CdfGenerator>\r\nstd::vector<DensityType> GenerateCdf(ResultType count, CdfGenerator& cdfGenerator) {\r\n    std::vector<DensityType> vec;\r\n    for(ResultType i=0; i<count; ++i) {\r\n        vec.push_back(cdfGenerator(i));\r\n    }\r\n    return vec;\r\n}\r\n\r\ntemplate <typename Vec>\r\nvoid PrintVec(const Vec& vec, std::ostream& os) {\r\n    const auto size = vec.size();\r\n    for(auto i = decltype(size){0}; i<size; ++i) {\r\n        os << vec.at(i);\r\n        if ((i + 1) < size) {\r\n            os << \",\";\r\n        }\r\n    }\r\n    os << \"\\n\";\r\n    return;\r\n}\r\n\r\nvoid nbinomCppCdf(void) {\r\n    constexpr DensityType nbSize = 2.0;\r\n    constexpr DensityType nbProb = 0.25;\r\n\r\n    boost::math::negative_binomial distNB(nbSize, nbProb);\r\n    auto funcNB = [&distNB](ResultType i) {\r\n        return boost::math::cdf(distNB, i);\r\n    };\r\n\r\n    auto cdfNB = std::bind(funcNB, std::placeholders::_1);\r\n    constexpr ResultType count = 10;\r\n    std::ostringstream osNB;\r\n    const auto actualNB = GenerateCdf(count, cdfNB);\r\n    PrintVec(actualNB, osNB);\r\n\r\n    // R pnbinom(seq(0, 9, 1), size=2.0, prob=0.25)\r\n    // [1] 0.0625000 0.1562500 0.2617188 0.3671875 0.4660645 0.5550537 0.6329193 0.6996613\r\n    // [9] 0.7559748 0.8029027\r\n    std::cout << osNB.str();\r\n\r\n    constexpr DensityType shape = 1.0;\r\n    constexpr DensityType scale = 2.0;\r\n\r\n    boost::math::gamma_distribution<double> distGamma(shape, scale);\r\n    auto funcGamma = [&distGamma](ResultType i) {\r\n        return boost::math::cdf(distGamma, i);\r\n    };\r\n\r\n    auto cdfGamma = std::bind(funcGamma, std::placeholders::_1);\r\n    const auto actualGamma = GenerateCdf(count, cdfGamma);\r\n\r\n    // R pgamma(seq(0, 9, 1), shape=1.0, scale=2.0)\r\n    // [1] 0.0000000 0.3934693 0.6321206 0.7768698 0.8646647 0.9179150 0.9502129 0.9698026\r\n    // [9] 0.9816844 0.9888910\r\n    std::ostringstream osGamma;\r\n    PrintVec(actualGamma, osGamma);\r\n    std::cout << osGamma.str() << std::endl;\r\n}\r\n\r\nvoid cppRandombinom(void) {\r\n    constexpr int size = 2;\r\n    constexpr double prob = 0.5;\r\n    std::negative_binomial_distribution<int> dist(size, prob);\r\n//  std::negative_binomial_distribution<double> dist(size, prob);\r\n    std::mt19937 randGen;\r\n    for(int i=0; i<10000; ++i) {\r\n       std::cout << dist(randGen);\r\n    }\r\n}\r\n\r\nvoid boostMathCppNbinom(void) {\r\n    constexpr double size = 0.99;\r\n    constexpr double prob = 0.5;\r\n    boost::math::negative_binomial dist(size, prob);\r\n\r\n    for(double p=0.1; p<0.91; p += 0.1) {\r\n       std::cout << boost::math::cdf(dist, p);\r\n    };\r\n}\r\n\r\nvoid boostRandombinomLarge(void) {\r\n    constexpr int size = 2;\r\n    constexpr double prob = 0.5;\r\n    boost::random::negative_binomial_distribution<int, double> dist(size, prob);\r\n//  boost::random::negative_binomial_distribution<double, double> dist(size, prob);\r\n    std::mt19937 randGen;\r\n    for(int i=0; i<10000; ++i) {\r\n       std::cout << dist(randGen);\r\n    }\r\n}\r\n\r\n// This code occurs a runtime assertion failure\r\nvoid boostRandombinomSmall(void) {\r\n#if 0\r\n    constexpr int size = 0.4;\r\n    constexpr double prob = 0.3;\r\n    boost::random::negative_binomial_distribution<int, double> dist(size, prob);\r\n    std::mt19937 randGen;\r\n    for(int i=0; i<10000; ++i) {\r\n       std::cout << dist(randGen);\r\n    }\r\n#endif\r\n}\r\n\r\nint main(int argc, char* argv[]) {\r\n    std::cout << \"BOOST_VERSION=\" << BOOST_VERSION << \"\\n\";\r\n    cppRandombinom();\r\n    boostMathCppNbinom();\r\n    boostRandombinomLarge();\r\n    boostRandombinomSmall();\r\n\r\n    rnbinomCppAll();\r\n    nbinomCppCdf();\r\n    std::cout << \"Everything is OK\\n\";\r\n    return 0;\r\n}\r\n\r\n/*\r\nLocal Variables:\r\nmode: c++\r\ncoding: utf-8-dos\r\ntab-width: nil\r\nc-file-style: \"stroustrup\"\r\nEnd:\r\n*/\r\n", "meta": {"hexsha": "3bf9026a6ef4da5a5db4c08ffb234c1010dbf5f6", "size": 6820, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "scripts/stock_price/negative_binomial_cpp.cpp", "max_stars_repo_name": "zettsu-t/cPlusPlusFriend", "max_stars_repo_head_hexsha": "5399065abe2c0eda2b9aec26e6435d8c27cda9cd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2017-04-15T00:05:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-10T05:11:14.000Z", "max_issues_repo_path": "scripts/stock_price/negative_binomial_cpp.cpp", "max_issues_repo_name": "zettsu-t/cPlusPlusFriend", "max_issues_repo_head_hexsha": "5399065abe2c0eda2b9aec26e6435d8c27cda9cd", "max_issues_repo_licenses": ["MIT"], "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/stock_price/negative_binomial_cpp.cpp", "max_forks_repo_name": "zettsu-t/cPlusPlusFriend", "max_forks_repo_head_hexsha": "5399065abe2c0eda2b9aec26e6435d8c27cda9cd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-02-23T22:47:08.000Z", "max_forks_repo_forks_event_max_datetime": "2018-02-23T22:47:08.000Z", "avg_line_length": 29.652173913, "max_line_length": 102, "alphanum_fraction": 0.6071847507, "num_tokens": 1913, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.6513548714339145, "lm_q1q2_score": 0.46805995818612184}}
{"text": "//\n// Copyright 2020 Debabrata Mandal <mandaldebabrata123@gmail.com>\n//\n// Use, modification and distribution are subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//\n\n#ifndef BOOST_GIL_IMAGE_PROCESSING_ADAPTIVE_HISTOGRAM_EQUALIZATION_HPP\n#define BOOST_GIL_IMAGE_PROCESSING_ADAPTIVE_HISTOGRAM_EQUALIZATION_HPP\n\n#include <boost/gil/algorithm.hpp>\n#include <boost/gil/histogram.hpp>\n#include <boost/gil/image.hpp>\n#include <boost/gil/image_processing/histogram_equalization.hpp>\n#include <boost/gil/image_view_factory.hpp>\n\n#include <cmath>\n#include <map>\n#include <vector>\n\nnamespace boost { namespace gil {\n\n/////////////////////////////////////////\n/// Adaptive Histogram Equalization(AHE)\n/////////////////////////////////////////\n/// \\defgroup AHE AHE\n/// \\brief Contains implementation and description of the algorithm used to compute\n///        adaptive histogram equalization of input images. Naming for the AHE functions\n///        are done in the following way \n///             <feature-1>_<feature-2>_.._<feature-n>ahe\n///        For example, for AHE done using local (non-overlapping) tiles/blocks and \n///        final output interpolated among tiles , it is called\n///             non_overlapping_interpolated_clahe\n///\n\nnamespace detail {\n\n/// \\defgroup AHE-helpers AHE-helpers\n/// \\brief AHE helper functions\n\n/// \\fn double actual_clip_limit\n/// \\ingroup AHE-helpers\n/// \\brief Computes the actual clip limit given a clip limit value using binary search.\n///        Reference -  Adaptive Histogram Equalization and Its Variations\n///                     (http://www.cs.unc.edu/techreports/86-013.pdf, Pg - 15)\n///\ntemplate <typename SrcHist>\ndouble actual_clip_limit(SrcHist const& src_hist, double cliplimit = 0.03)\n{\n    double epsilon       = 1.0;\n    using value_t        = typename SrcHist::value_type;\n    double sum           = src_hist.sum();\n    std::size_t num_bins = src_hist.size();\n\n    cliplimit = sum * cliplimit;\n    long low = 0, high = cliplimit, middle = low;\n    while (high - low >= 1)\n    {\n        middle      = (low + high + 1) >> 1;\n        long excess = 0;\n        std::for_each(src_hist.begin(), src_hist.end(), [&](value_t const& v) {\n            if (v.second > middle)\n                excess += v.second - middle;\n        });\n        if (std::abs(excess - (cliplimit - middle) * num_bins) < epsilon)\n            break;\n        else if (excess > (cliplimit - middle) * num_bins)\n            high = middle - 1;\n        else\n            low = middle + 1;\n    }\n    return middle / sum;\n}\n\n/// \\fn void clip_and_redistribute\n/// \\ingroup AHE-helpers\n/// \\brief Clips and redistributes excess pixels based on the actual clip limit value \n///        obtained from the other helper function actual_clip_limit\n///        Reference - Graphic Gems 4, Pg. 474\n///        (http://cas.xav.free.fr/Graphics%20Gems%204%20-%20Paul%20S.%20Heckbert.pdf)\n/// \ntemplate <typename SrcHist, typename DstHist>\nvoid clip_and_redistribute(SrcHist const& src_hist, DstHist& dst_hist, double clip_limit = 0.03)\n{\n    using value_t            = typename SrcHist::value_type;\n    double sum               = src_hist.sum();\n    double actual_clip_value = detail::actual_clip_limit(src_hist, clip_limit);\n    // double actual_clip_value = clip_limit;\n    long actual_clip_limit = actual_clip_value * sum;\n    double excess          = 0;\n    std::for_each(src_hist.begin(), src_hist.end(), [&](value_t const& v) {\n        if (v.second > actual_clip_limit)\n            excess += v.second - actual_clip_limit;\n    });\n    std::for_each(src_hist.begin(), src_hist.end(), [&](value_t const& v) {\n        if (v.second >= actual_clip_limit)\n            dst_hist[dst_hist.key_from_tuple(v.first)] = clip_limit * sum;\n        else\n            dst_hist[dst_hist.key_from_tuple(v.first)] = v.second + excess / src_hist.size();\n    });\n    long rem = long(excess) % src_hist.size();\n    if (rem == 0)\n        return;\n    long period       = round(src_hist.size() / rem);\n    std::size_t index = 0;\n    while (rem)\n    {\n        if (dst_hist(index) >= clip_limit * sum)\n        {\n            index = (index + 1) % src_hist.size();\n        }\n        dst_hist(index)++;\n        rem--;\n        index = (index + period) % src_hist.size();\n    }\n}\n\n}  // namespace detail\n\n\n/// \\fn void non_overlapping_interpolated_clahe\n/// \\ingroup AHE\n/// @param src_view      Input   Source image view\n/// @param dst_view      Output  Output image view\n/// @param tile_width_x  Input   Tile width along x-axis to apply HE\n/// @param tile_width_y  Input   Tile width along x-axis to apply HE\n/// @param clip_limit    Input   Clipping limit to be applied\n/// @param bin_width     Input   Bin widths for histogram\n/// @param mask          Input   Specify if mask is to be used\n/// @param src_mask      Input   Mask on input image to ignore specified pixels\n/// \\brief Performs local histogram equalization on tiles of size (tile_width_x, tile_width_y)\n///        Then uses the clip limit to redistribute excess pixels above the limit uniformly to\n///        other bins. The clip limit is specified as a fraction i.e. a bin's value is clipped \n///        if bin_value >= clip_limit * (Total number of pixels in the tile) \n///\ntemplate <typename SrcView, typename DstView>\nvoid non_overlapping_interpolated_clahe(\n    SrcView const& src_view,\n    DstView const& dst_view,\n    std::size_t tile_width_x                = 20,\n    std::size_t tile_width_y                = 20,\n    double clip_limit                       = 0.03,\n    std::size_t bin_width                   = 1.0,\n    bool mask                               = false,\n    std::vector<std::vector<bool>> src_mask = {})\n{\n    gil_function_requires<ImageViewConcept<SrcView>>();\n    gil_function_requires<MutableImageViewConcept<DstView>>();\n\n    static_assert(\n        color_spaces_are_compatible<\n            typename color_space_type<SrcView>::type,\n            typename color_space_type<DstView>::type>::value,\n        \"Source and destination views must have same color space\");\n    \n    using source_channel_t = typename channel_type<SrcView>::type;\n    using dst_channel_t    = typename channel_type<DstView>::type;\n    using coord_t          = typename SrcView::x_coord_t;\n\n    std::size_t const channels = num_channels<SrcView>::value;\n    coord_t const width        = src_view.width();\n    coord_t const height       = src_view.height();\n\n    // Find control points\n\n    std::vector<coord_t> sample_x;\n    coord_t sample_x1 = tile_width_x / 2;\n    coord_t sample_x2 = (tile_width_x + 1) / 2;\n    coord_t sample_y1 = tile_width_y / 2;\n    coord_t sample_y2 = (tile_width_y + 1) / 2;\n\n    auto extend_left   = tile_width_x;\n    auto extend_top    = tile_width_y;\n    auto extend_right  = (tile_width_x - width % tile_width_x) % tile_width_x + tile_width_x;\n    auto extend_bottom = (tile_width_y - height % tile_width_y) % tile_width_y + tile_width_y;\n\n    auto new_width  = width + extend_left + extend_right;\n    auto new_height = height + extend_top + extend_bottom;\n\n    image<typename SrcView::value_type> padded_img(new_width, new_height);\n\n    auto top_left_x     = tile_width_x;\n    auto top_left_y     = tile_width_y;\n    auto bottom_right_x = tile_width_x + width;\n    auto bottom_right_y = tile_width_y + height;\n\n    copy_pixels(src_view, subimage_view(view(padded_img), top_left_x, top_left_y, width, height));\n\n    for (std::size_t k = 0; k < channels; k++)\n    {\n        std::vector<histogram<source_channel_t>> prev_row(new_width / tile_width_x),\n            next_row((new_width / tile_width_x));\n        std::vector<std::map<source_channel_t, source_channel_t>> prev_map(\n            new_width / tile_width_x),\n            next_map((new_width / tile_width_x));\n        \n        coord_t prev = 0, next = 1;\n        auto channel_view = nth_channel_view(view(padded_img), k);\n\n        for (std::ptrdiff_t i = top_left_y; i < bottom_right_y; ++i)\n        {\n            if ((i - sample_y1) / tile_width_y >= next || i == top_left_y)\n            {\n                if (i != top_left_y)\n                {\n                    prev = next;\n                    next++;\n                }\n                prev_row = next_row;\n                prev_map = next_map;\n                for (std::ptrdiff_t j = sample_x1; j < new_width; j += tile_width_x)\n                {\n                    auto img_view = subimage_view(\n                        channel_view, j - sample_x1, next * tile_width_y,\n                        std::max<int>(\n                            std::min<int>(tile_width_x + j - sample_x1, bottom_right_x) -\n                                (j - sample_x1),\n                            0),\n                        std::max<int>(\n                            std::min<int>((next + 1) * tile_width_y, bottom_right_y) -\n                                next * tile_width_y,\n                            0));\n\n                    fill_histogram(\n                        img_view, next_row[(j - sample_x1) / tile_width_x], bin_width, false,\n                        false);\n                    \n                    detail::clip_and_redistribute(\n                        next_row[(j - sample_x1) / tile_width_x],\n                        next_row[(j - sample_x1) / tile_width_x], clip_limit);\n\n                    next_map[(j - sample_x1) / tile_width_x] =\n                        histogram_equalization(next_row[(j - sample_x1) / tile_width_x]);\n                }\n            }\n            bool prev_row_mask = 1, next_row_mask = 1;\n            if (prev == 0)\n                prev_row_mask = false;\n            else if (next + 1 == new_height / tile_width_y)\n                next_row_mask = false;\n            for (std::ptrdiff_t j = top_left_x; j < bottom_right_x; ++j)\n            {\n                bool prev_col_mask = true, next_col_mask = true;\n                if ((j - sample_x1) / tile_width_x == 0)\n                    prev_col_mask = false;\n                else if ((j - sample_x1) / tile_width_x + 1 == new_width / tile_width_x - 1)\n                    next_col_mask = false;\n                \n                // Bilinear interpolation\n                point_t top_left(\n                    (j - sample_x1) / tile_width_x * tile_width_x + sample_x1,\n                                    prev * tile_width_y + sample_y1);\n                point_t top_right(top_left.x + tile_width_x, top_left.y);\n                point_t bottom_left(top_left.x, top_left.y + tile_width_y);\n                point_t bottom_right(top_left.x + tile_width_x, top_left.y + tile_width_y);\n                \n                long double x_diff = top_right.x - top_left.x;\n                long double y_diff = bottom_left.y - top_left.y;\n\n                long double x1 = (j - top_left.x) / x_diff;\n                long double x2 = (top_right.x - j) / x_diff;\n                long double y1 = (i - top_left.y) / y_diff;\n                long double y2 = (bottom_left.y - i) / y_diff;\n\n                if (prev_row_mask == 0)\n                    y1 = 1;\n                else if (next_row_mask == 0)\n                    y2 = 1;\n                if (prev_col_mask == 0)\n                    x1 = 1;\n                else if (next_col_mask == 0)\n                    x2 = 1;\n\n                long double numerator =\n                    ((prev_row_mask & prev_col_mask) * x2 *\n                         prev_map[(top_left.x - sample_x1) / tile_width_x][channel_view(j, i)] +\n                     (prev_row_mask & next_col_mask) * x1 *\n                         prev_map[(top_right.x - sample_x1) / tile_width_x][channel_view(j, i)]) *\n                        y2 +\n                    ((next_row_mask & prev_col_mask) * x2 *\n                         next_map[(bottom_left.x - sample_x1) / tile_width_x][channel_view(j, i)] +\n                     (next_row_mask & next_col_mask) * x1 *\n                         next_map[(bottom_right.x - sample_x1) / tile_width_x][channel_view(j, i)]) *\n                        y1;\n                \n                if (mask && !src_mask[i - top_left_y][j - top_left_x])\n                {\n                    dst_view(j - top_left_x, i - top_left_y) = \n                        channel_convert<dst_channel_t>(\n                            static_cast<source_channel_t>(channel_view(i, j)));\n                }\n                else\n                {\n                    dst_view(j - top_left_x, i - top_left_y) = \n                        channel_convert<dst_channel_t>(static_cast<source_channel_t>(numerator));\n                }\n            }\n        }\n    }\n}\n\n}}  //namespace boost::gil\n\n#endif\n", "meta": {"hexsha": "b1c189d94846d4eb862c0544c4712d3b307efdef", "size": 12633, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/gil/image_processing/adaptive_histogram_equalization.hpp", "max_stars_repo_name": "harsh-4/gil", "max_stars_repo_head_hexsha": "6da59cc3351e5657275d3a536e0b6e7a1b6ac738", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 153.0, "max_stars_repo_stars_event_min_datetime": "2015-02-03T06:03:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T15:06:34.000Z", "max_issues_repo_path": "include/boost/gil/image_processing/adaptive_histogram_equalization.hpp", "max_issues_repo_name": "harsh-4/gil", "max_issues_repo_head_hexsha": "6da59cc3351e5657275d3a536e0b6e7a1b6ac738", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 429.0, "max_issues_repo_issues_event_min_datetime": "2015-03-22T09:49:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T08:32:08.000Z", "max_forks_repo_path": "include/boost/gil/image_processing/adaptive_histogram_equalization.hpp", "max_forks_repo_name": "harsh-4/gil", "max_forks_repo_head_hexsha": "6da59cc3351e5657275d3a536e0b6e7a1b6ac738", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-03-15T09:20:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T12:40:07.000Z", "avg_line_length": 41.2843137255, "max_line_length": 101, "alphanum_fraction": 0.5696192512, "num_tokens": 2980, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185944046238982, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.46805995144689005}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n// Unit Test\r\n\r\n// Copyright (c) 2007-2011 Barend Gehrels, Amsterdam, the Netherlands.\r\n// Copyright (c) 2008-2011 Bruno Lalande, Paris, France.\r\n// Copyright (c) 2009-2011 Mateusz Loskot, London, UK.\r\n\r\n// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library\r\n// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n\r\n#include <geometry_test_common.hpp>\r\n\r\n\r\n#include <boost/geometry/algorithms/assign.hpp>\r\n#include <boost/geometry/algorithms/distance.hpp>\r\n\r\n#include <boost/geometry/strategies/spherical/distance_haversine.hpp>\r\n#include <boost/geometry/strategies/spherical/distance_cross_track.hpp>\r\n\r\n#include <boost/geometry/strategies/concepts/distance_concept.hpp>\r\n\r\n#include <boost/geometry/geometries/point.hpp>\r\n#include <boost/geometry/geometries/segment.hpp>\r\n\r\n\r\n// This test is GIS oriented. \r\n\r\n\r\ntemplate <typename Point, typename LatitudePolicy>\r\nvoid test_distance(\r\n            typename bg::coordinate_type<Point>::type const& lon1, \r\n            typename bg::coordinate_type<Point>::type const& lat1,\r\n            typename bg::coordinate_type<Point>::type const& lon2, \r\n            typename bg::coordinate_type<Point>::type const& lat2,\r\n            typename bg::coordinate_type<Point>::type const& lon3, \r\n            typename bg::coordinate_type<Point>::type const& lat3,\r\n            typename bg::coordinate_type<Point>::type const& radius, \r\n            typename bg::coordinate_type<Point>::type const& expected, \r\n            typename bg::coordinate_type<Point>::type const& tolerance)\r\n{\r\n    typedef bg::strategy::distance::cross_track\r\n        <\r\n            Point,\r\n            Point\r\n        > strategy_type;\r\n    typedef typename bg::strategy::distance::services::return_type\r\n        <\r\n            strategy_type\r\n        >::type return_type;\r\n\r\n\r\n    BOOST_CONCEPT_ASSERT\r\n        (\r\n            (bg::concept::PointSegmentDistanceStrategy<strategy_type>)\r\n        );\r\n\r\n\r\n    Point p1, p2, p3;\r\n    bg::assign_values(p1, lon1, LatitudePolicy::apply(lat1));\r\n    bg::assign_values(p2, lon2, LatitudePolicy::apply(lat2));\r\n    bg::assign_values(p3, lon3, LatitudePolicy::apply(lat3));\r\n\r\n\r\n    strategy_type strategy;\r\n    return_type d = strategy.apply(p1, p2, p3);\r\n\r\n    BOOST_CHECK_CLOSE(radius * d, expected, tolerance);\r\n\r\n    // Test specifying radius explicitly\r\n    strategy_type strategy_radius(radius);\r\n    d = strategy_radius.apply(p1, p2, p3);\r\n    BOOST_CHECK_CLOSE(d, expected, tolerance);\r\n\r\n\r\n    // Test the \"default strategy\" registration\r\n    bg::model::referring_segment<Point const> segment(p2, p3);\r\n    d = bg::distance(p1, segment);\r\n    BOOST_CHECK_CLOSE(radius * d, expected, tolerance);\r\n}\r\n\r\n\r\ntemplate <typename Point, typename LatitudePolicy>\r\nvoid test_all()\r\n{\r\n    typename bg::coordinate_type<Point>::type const average_earth_radius = 6372795.0;\r\n\r\n    // distance (Paris <-> Amsterdam/Barcelona), \r\n    // with coordinates rounded as below ~87 km\r\n    // is equal to distance (Paris <-> Barcelona/Amsterdam)\r\n    typename bg::coordinate_type<Point>::type const p_to_ab = 86.798321 * 1000.0;\r\n    test_distance<Point, LatitudePolicy>(2, 48, 4, 52, 2, 41, average_earth_radius, p_to_ab, 0.1);\r\n    test_distance<Point, LatitudePolicy>(2, 48, 2, 41, 4, 52, average_earth_radius, p_to_ab, 0.1);\r\n}\r\n\r\n\r\nint test_main(int, char* [])\r\n{\r\n    test_all<bg::model::point<double, 2, bg::cs::spherical_equatorial<bg::degree> >, geographic_policy >();\r\n\r\n    // NYI: haversine for mathematical spherical coordinate systems\r\n    // test_all<bg::model::point<double, 2, bg::cs::spherical<bg::degree> >, mathematical_policya >();\r\n\r\n#if defined(HAVE_TTMATH)\r\n    typedef ttmath::Big<1,4> tt;\r\n    //test_all<bg::model::point<tt, 2, bg::cs::geographic<bg::degree> >, geographic_policy>();\r\n#endif\r\n\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "a75905aaa5af03d4eb75c7b177132ad4d395d931", "size": 4065, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/test/strategies/cross_track.cpp", "max_stars_repo_name": "Ron2014/boost_1_48_0", "max_stars_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "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/geometry/test/strategies/cross_track.cpp", "max_issues_repo_name": "Ron2014/boost_1_48_0", "max_issues_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "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/geometry/test/strategies/cross_track.cpp", "max_forks_repo_name": "Ron2014/boost_1_48_0", "max_forks_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.347826087, "max_line_length": 108, "alphanum_fraction": 0.6777367774, "num_tokens": 1017, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943805178139, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.46805994060862144}}
{"text": "#include <boost/math/special_functions/beta.hpp>\n", "meta": {"hexsha": "dc982e7bbcfbbc74182a2b9720355a9e5a710468", "size": 49, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_special_functions_beta.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_special_functions_beta.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_special_functions_beta.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 24.5, "max_line_length": 48, "alphanum_fraction": 0.8163265306, "num_tokens": 11, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.46804781862519196}}
{"text": "/**\n * @file Tools/Math/Rotation.hpp\n * Rotation related functionality\n * @author <a href=\"mailto:alexists@tzi.de\">Alexis Tsogias</a>\n */\n\n#pragma once\n\n#include <Eigen/Dense>\n#include \"nao_ik/bhuman/Angle.hpp\"\n#include \"nao_ik/bhuman/Approx.hpp\"\n\nusing namespace Eigen;\n\nusing Vector3a = Matrix<Angle, 3, 1>;\ntypedef Quaternion<float> Quaternionf;\n\nnamespace Rotation\n{\n  Quaternionf aroundX(float angle);\n  Quaternionf aroundY(float angle);\n  Quaternionf aroundZ(float angle);\n\n  /**\n   * The spherical linear interpolation (slerp) between the two rotations.\n   * Where interpolate(0.0f, q1, q2) = q1 and interpolate(1.0f, q1, q2) = q2.\n   * @param t interpolation factor. Range: [0.0f, 1.0f].\n   */\n  Quaternionf interpolate(float t, const Quaternionf& q1, const Quaternionf& q2);\n\n  Quaternionf removeZRotation(const Quaternionf& rotation);\n  Quaternionf splitOffZRotation(const Quaternionf& rotation, Quaternionf& zRot);\n\n  namespace Euler\n  {\n    // Euler angles are expressed in z y x manner.\n\n    Quaternionf fromAngles(float x, float y, float z);\n    Quaternionf fromAngles(const Vector3a& rotation);\n    Quaternionf fromAngles(const Vector3f& rotation);\n    Vector3f getAngles(const Quaternionf& rot);\n    float getXAngle(const Quaternionf& rot);\n    float getYAngle(const Quaternionf& rot);\n    float getZAngle(const Quaternionf& rot);\n  }\n\n  namespace Aldebaran\n  {\n    // Aldebaran uses these angles when calculating the orientation of the robot via the imu\n    float getXAngle(const Quaternionf& rot);\n    float getXAngle(const Matrix3f& rot);\n    float getYAngle(const Quaternionf& rot);\n    float getYAngle(const Matrix3f& rot);\n  }\n\n  namespace AngleAxis\n  {\n    // Do not missinterpret the vectors as Euler angles!\n    // Vector3f pack(const AngleAxisf& angleAxis);\n    AngleAxisf unpack(const Vector3f& angleAxisVec);\n  }\n}\n\ninline Quaternionf Rotation::aroundX(float angle)\n{\n  return Quaternionf(AngleAxisf(angle, Vector3f::UnitX()));\n}\n\ninline Quaternionf Rotation::aroundY(float angle)\n{\n  return Quaternionf(AngleAxisf(angle, Vector3f::UnitY()));\n}\n\ninline Quaternionf Rotation::aroundZ(float angle)\n{\n  return Quaternionf(AngleAxisf(angle, Vector3f::UnitZ()));\n}\n\ninline Quaternionf Rotation::interpolate(float t, const Quaternionf& q1, const Quaternionf& q2)\n{\n  return q1.slerp(t, q2);\n}\n\ninline Quaternionf Rotation::removeZRotation(const Quaternionf& rotation)\n{\n  const Vector3f& z = Vector3f::UnitZ();\n  const Vector3f zR = rotation.inverse() * z;\n  const Vector3f c = zR.cross(z);\n  const float sin = c.norm();\n  const float cos = zR.dot(z);\n  if(Approx::isZero(sin))\n    if(cos < 0.f) // 180 degree rotation\n      return rotation; // There's no unique decomposition.\n    else\n      return Quaternionf::Identity();\n  else\n  {\n    const float angle = std::atan2(sin, cos);\n    return Quaternionf(AngleAxisf(angle, c.normalized()));\n  }\n}\n\ninline Quaternionf Rotation::splitOffZRotation(const Quaternionf& rotation, Quaternionf& zRot)\n{\n  const Quaternionf xyRot = removeZRotation(rotation);\n  zRot = rotation * xyRot.inverse();\n  return xyRot;\n}\n\ninline Quaternionf Rotation::Euler::fromAngles(float x, float y, float z)\n{\n  return AngleAxisf(z, Vector3f::UnitZ()) * AngleAxisf(y, Vector3f::UnitY()) * AngleAxisf(x, Vector3f::UnitX());\n}\n\ninline Quaternionf Rotation::Euler::fromAngles(const Vector3a& rotation)\n{\n  return fromAngles(rotation.x(), rotation.y(), rotation.z());\n}\n\ninline Quaternionf Rotation::Euler::fromAngles(const Vector3f& rotation)\n{\n  return fromAngles(rotation.x(), rotation.y(), rotation.z());\n}\n\ninline Vector3f Rotation::Euler::getAngles(const Quaternionf& rot)\n{\n  const Matrix3f mat = rot.normalized().toRotationMatrix();\n  const float m20 = mat(2, 0);\n\n  if(std::abs(m20) < 0.999999f)\n  {\n    const float m00 = mat(0, 0);\n    const float m10 = mat(1, 0);\n    const float m21 = mat(2, 1);\n    const float m22 = mat(2, 2);\n\n    const float y1 = -std::asin(m20);\n    const float y2 = pi - y1;\n    const float cy1 = std::cos(y1);\n    const float cy2 = std::cos(y2);\n    const float x1 = std::atan2(m21 / cy1, m22 / cy1);\n    const float x2 = std::atan2(m21 / cy2, m22 / cy2);\n    const float z1 = std::atan2(m10 / cy1, m00 / cy1);\n    const float z2 = std::atan2(m10 / cy2, m00 / cy2);\n\n    Vector3f v1(x1, y1, z1);\n    Vector3f v2(x2, y2, z2);\n\n    return v1.norm() < v2.norm() ? v1 : v2;\n  }\n  else\n  {\n    const float x = std::atan2(mat(0, 1), mat(0, 2)); // x = +-z + atan2(...) , but we set z = 0...\n    const float y = -std::asin(m20);\n\n    return Vector3f(x, y, 0.f);\n  }\n}\n\ninline float Rotation::Euler::getXAngle(const Quaternionf& rot)\n{\n  return getAngles(rot).x();\n}\n\ninline float Rotation::Euler::getYAngle(const Quaternionf& rot)\n{\n  return getAngles(rot).y();\n}\n\ninline float Rotation::Euler::getZAngle(const Quaternionf& rot)\n{\n  return getAngles(rot).z();\n}\n\ninline float Rotation::Aldebaran::getXAngle(const Quaternionf& rot)\n{\n  //     | a b c |        | a d g |        | 0 |   | g |\n  // A = | d e f |   At = | b e h |   At * | 0 | = | h | = v\n  //     | g h i |        | c f i |        | 1 |   | i |\n\n  // Project        | 0 |\n  // v into  : v -> | h | = v'\n  // yz plane       | i |\n\n  // calculate angle      | 0 |       angleX = acos((v' * z) / (|v'| * |z|))\n  // bewteen v' and : z = | 0 |,  <=> angleX = acos(i / |v'|)\n  // z-axis of A          | 1 |   <=> angleX = acos(i / sqrt(h * h + i * i))\n\n  const float tx = 2.f * rot.x();\n  const float h = 2.f * rot.z() * rot.y() + tx * rot.w();\n  const float i = 1.f - (tx * rot.x() + 2.f * rot.y() * rot.y());\n\n  const float len = std::sqrt(h * h + i * i);\n  return len > 1e-5f ? std::acos(i / len) * (h > 0.f ? 1.f : -1.f) : 0.f;\n}\n\ninline float Rotation::Aldebaran::getXAngle(const Matrix3f& rot)\n{\n  //     | a b c |        | a d g |        | 0 |   | g |\n  // A = | d e f |   At = | b e h |   At * | 0 | = | h | = v\n  //     | g h i |        | c f i |        | 1 |   | i |\n\n  // Project        | 0 |\n  // v into  : v -> | h | = v'\n  // yz plane       | i |\n\n  // calculate angle      | 0 |       angleX = acos((v' * z) / (|v'| * |z|))\n  // bewteen v' and : z = | 0 |,  <=> angleX = acos(i / |v'|)\n  // z-axis of A          | 1 |   <=> angleX = acos(i / sqrt(h * h + i * i))\n\n  const float h = rot(2, 1);\n  const float i = rot(2, 2);\n\n  const float len = std::sqrt(h * h + i * i);\n  return len > 1e-5f ? std::acos(i / len) * (h > 0.f ? 1.f : -1.f) : 0.f;\n}\n\ninline float Rotation::Aldebaran::getYAngle(const Quaternionf& rot)\n{\n  //     | a b c |        | a d g |        | 0 |   | g |\n  // A = | d e f |   At = | b e h |   At * | 0 | = | h | = v\n  //     | g h i |        | c f i |        | 1 |   | i |\n\n  // Project        | g |\n  // v into  : v -> | 0 | = v'\n  // xz plane       | i |\n\n  // calculate angle      | 0 |       angleX = acos((v' * z) / (|v'| * |z|))\n  // bewteen v' and : z = | 0 |,  <=> angleX = acos(i / |v'|)\n  // z-axis of A          | 1 |   <=> angleX = acos(i / sqrt(g * g + i * i))\n\n  // calculate g and i\n\n  const float ty = 2.f * rot.y();\n  const float g = 2.f * rot.z() * rot.x() - ty * rot.w();\n  const float i = 1.f - (2.f * rot.x() * rot.x() + ty * rot.y());\n\n  const float len = std::sqrt(g * g + i * i);\n  return len > 1e-5f ? std::acos(i / len) * (g > 0.f ? -1.f : 1.f) : 0.f;\n}\n\ninline float Rotation::Aldebaran::getYAngle(const Matrix3f& rot)\n{\n  //     | a b c |        | a d g |        | 0 |   | g |\n  // A = | d e f |   At = | b e h |   At * | 0 | = | h | = v\n  //     | g h i |        | c f i |        | 1 |   | i |\n\n  // Project        | g |\n  // v into  : v -> | 0 | = v'\n  // xz plane       | i |\n\n  // calculate angle      | 0 |       angleX = acos((v' * z) / (|v'| * |z|))\n  // bewteen v' and : z = | 0 |,  <=> angleX = acos(i / |v'|)\n  // z-axis of A          | 1 |   <=> angleX = acos(i / sqrt(g * g + i * i))\n\n  const float g = rot(2, 0);\n  const float i = rot(2, 2);\n\n  const float len = std::sqrt(g * g + i * i);\n  return len > 1e-5f ? std::acos(i / len) * (g > 0.f ? -1.f : 1.f) : 0.f;\n}\n\n// inline Vector3f Rotation::AngleAxis::pack(const AngleAxisf& angleAxis)\n// {\n//   const float angle = angleAxis.angle();\n//   if(Approx::isZero(angle))\n//     return Vector3f::Zero();\n//   else\n//     return angleAxis.axis().normalized(angle);\n// }\n\ninline AngleAxisf Rotation::AngleAxis::unpack(const Vector3f& angleAxisVec)\n{\n  const float angle = angleAxisVec.norm();\n  if(Approx::isZero(angle))\n    return AngleAxisf::Identity();\n  else\n    return AngleAxisf(angle, angleAxisVec.normalized());\n}\n", "meta": {"hexsha": "04f1ff6f23b540e78efc26b33cf4abf69210a7f1", "size": 8468, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "nao_ik/include/nao_ik/bhuman/Rotation.hpp", "max_stars_repo_name": "ijnek/nao_ik", "max_stars_repo_head_hexsha": "f417ce46092d2375fca6bdedba38bf90a8458f5d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "nao_ik/include/nao_ik/bhuman/Rotation.hpp", "max_issues_repo_name": "ijnek/nao_ik", "max_issues_repo_head_hexsha": "f417ce46092d2375fca6bdedba38bf90a8458f5d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nao_ik/include/nao_ik/bhuman/Rotation.hpp", "max_forks_repo_name": "ijnek/nao_ik", "max_forks_repo_head_hexsha": "f417ce46092d2375fca6bdedba38bf90a8458f5d", "max_forks_repo_licenses": ["Apache-2.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.2428571429, "max_line_length": 112, "alphanum_fraction": 0.5788852149, "num_tokens": 2760, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257653, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4680478186251919}}
{"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_ACOSPI_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_ACOSPI_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 inverse cosine in \\f$\\pi\\f$ multiples.\n\n\n    @par Header <boost/simd/function/acospi.hpp>\n\n    @par Decorators\n\n       - pedantic_     is similar to Invpi<T>*pedantic_(acos)(x);\n\n    @see acos, acospi, cosd\n\n\n    @par Example:\n\n      @snippet acospi.cpp acospi\n\n    @par Possible output:\n\n      @snippet acospi.txt acospi\n\n  **/\n  IEEEValue acospi(IEEEValue const & x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/acospi.hpp>\n#include <boost/simd/function/simd/acospi.hpp>\n\n#endif\n", "meta": {"hexsha": "51fad134ddab8f98b37ad9b7c366ded78812e720", "size": 1115, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/acospi.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/acospi.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/acospi.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.7551020408, "max_line_length": 100, "alphanum_fraction": 0.5820627803, "num_tokens": 247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.4680478133379659}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\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/*! \\file sabrvolsurface.hpp\n    \\brief SABR volatility (smile) surface\n*/\n\n#ifndef quantlib_sabr_vol_surface_hpp\n#define quantlib_sabr_vol_surface_hpp\n\n#include <ql/experimental/volatility/interestratevolsurface.hpp>\n#include <ql/experimental/volatility/blackatmvolcurve.hpp>\n#include <ql/quote.hpp>\n#include <ql/termstructures/volatility/sabrinterpolatedsmilesection.hpp>\n#include <boost/array.hpp>\n\nnamespace QuantLib {\n\n\n    //! SABR volatility (smile) surface\n    /*! blah blah\n    */\n    class SabrVolSurface : public InterestRateVolSurface {\n      public:\n        SabrVolSurface(\n                const ext::shared_ptr<InterestRateIndex>&,\n                const Handle<BlackAtmVolCurve>&,\n                const std::vector<Period>& optionTenors,\n                const std::vector<Spread>& atmRateSpreads,\n                const std::vector<std::vector<Handle<Quote> > >& volSpreads);\n        //@}\n        // All virtual methods of base classes must be forwarded\n        //! \\name TermStructure interface\n        //@{\n        DayCounter dayCounter() const override;\n        Date maxDate() const override;\n        Time maxTime() const override;\n        const Date& referenceDate() const override;\n        Calendar calendar() const override;\n        Natural settlementDays() const override;\n        //@}\n        //! \\name VolatilityTermStructure interface\n        //@{\n        Real minStrike() const override;\n        Real maxStrike() const override;\n        //@}\n        const Handle<BlackAtmVolCurve>& atmCurve() const;\n        //! \\name Visitability\n        //@{\n        void accept(AcyclicVisitor&) override;\n        //@}\n        std::vector<Volatility> volatilitySpreads(const Period&) const;\n        std::vector<Volatility> volatilitySpreads(const Date&) const;\n      protected:\n        boost::array<Real, 4> sabrGuesses(const Date&) const;\n      public:\n        //@}\n        //! \\name BlackVolSurface interface\n        //@{\n        ext::shared_ptr<SmileSection> smileSectionImpl(Time) const override;\n        //@}\n      protected:\n        //@}\n        //! \\name LazyObject interface\n        //@{\n        void performCalculations () const;\n        void update() override;\n        //@}\n      private:\n        void registerWithMarketData();\n        void checkInputs() const;\n        void updateSabrGuesses(const Date& d, boost::array<Real, 4> newGuesses) const;\n        Handle<BlackAtmVolCurve> atmCurve_;\n        std::vector<Period> optionTenors_;\n        std::vector<Time> optionTimes_;\n        std::vector<Date> optionDates_;\n        std::vector<Spread> atmRateSpreads_;\n        std::vector<std::vector<Handle<Quote> > > volSpreads_;\n        //\n        bool isAlphaFixed_;\n        bool isBetaFixed_;\n        bool isNuFixed_;\n        bool isRhoFixed_;\n        bool vegaWeighted_;\n        //\n        mutable std::vector<boost::array<Real,4> > sabrGuesses_;\n    };\n\n    // inline\n\n    inline DayCounter SabrVolSurface::dayCounter() const {\n        return atmCurve_->dayCounter();\n    }\n\n    inline Date SabrVolSurface::maxDate() const {\n        return atmCurve_->maxDate();\n    }\n\n    inline Time SabrVolSurface::maxTime() const {\n        return atmCurve_->maxTime();\n    }\n\n    inline const Date& SabrVolSurface::referenceDate() const {\n        return atmCurve_->referenceDate();\n    }\n\n    inline Calendar SabrVolSurface::calendar() const {\n        return atmCurve_->calendar();\n    }\n\n    inline Natural SabrVolSurface::settlementDays() const {\n        return atmCurve_->settlementDays();\n    }\n\n    inline Real SabrVolSurface::minStrike() const {\n        return QL_MIN_REAL;\n    }\n\n    inline Real SabrVolSurface::maxStrike() const {\n        return QL_MAX_REAL;\n    }\n\n    inline const Handle<BlackAtmVolCurve>& SabrVolSurface::atmCurve() const {\n        return atmCurve_;\n    }\n\n    inline std::vector<Volatility>\n    SabrVolSurface::volatilitySpreads(const Period& p) const {\n        return volatilitySpreads(optionDateFromTenor(p));\n    }\n}\n\n#endif\n", "meta": {"hexsha": "3e7261316a4a26241f8c4a55ddb367ae5c296238", "size": 4768, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/experimental/volatility/sabrvolsurface.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/volatility/sabrvolsurface.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/volatility/sabrvolsurface.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": 31.7866666667, "max_line_length": 86, "alphanum_fraction": 0.6503775168, "num_tokens": 1109, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788995148791, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.46804780805073987}}
{"text": "#include <boost/test/unit_test.hpp>\n\n#include <crave/utils/Evaluator.hpp>\n#include <crave/ir/UserConstraint.hpp>\n#include <crave/ir/UserExpression.hpp>\n\n#include <set>\n#include <iostream>\n\n// using namespace std;\nusing namespace crave;\n\nBOOST_FIXTURE_TEST_SUITE(Evaluations_t, Context_Fixture)\n\nBOOST_AUTO_TEST_CASE(logical_not_t1) {\n  Variable<unsigned int> a;\n  Evaluator evaluator;\n\n  evaluator.assign(a, 0u);\n\n  BOOST_REQUIRE(evaluator.evaluate(!(a != 0)));\n  BOOST_REQUIRE(evaluator.result<bool>());\n\n  evaluator.assign(a, 42u);\n\n  BOOST_REQUIRE(evaluator.evaluate(!(a == 0)));\n  BOOST_REQUIRE(evaluator.result<bool>());\n}\n\nBOOST_AUTO_TEST_CASE(logical_not_t2) {\n  Variable<unsigned char> a;\n  Variable<unsigned int> b;\n  Evaluator eval;\n  expression expr = make_expression(if_then_else(!(a % 2 == 0), b > 0 && b <= 50, b > 50 && b <= 100));\n\n  eval.assign(a, 1u);\n\n  BOOST_REQUIRE(!eval.evaluate(expr));\n\n  eval.assign(b, 35u);\n\n  BOOST_REQUIRE(eval.evaluate(expr));\n  BOOST_REQUIRE(eval.result<bool>());\n\n  eval.assign(a, 2u);\n  eval.assign(b, 75u);\n\n  BOOST_REQUIRE(eval.evaluate(expr));\n  BOOST_REQUIRE(eval.result<bool>());\n\n  eval.assign(a, 1u);\n\n  BOOST_REQUIRE(eval.evaluate(expr));\n  BOOST_REQUIRE(!eval.result<bool>());\n}\n\nBOOST_AUTO_TEST_CASE(logical_and_t1) {\n  Variable<bool> a;\n  Variable<bool> b;\n  Variable<bool> c;\n  Evaluator eval;\n\n  eval.assign(a, true);\n  eval.assign(b, true);\n\n  BOOST_REQUIRE(eval.evaluate(a && b));\n  BOOST_REQUIRE(eval.result<bool>());\n\n  eval.assign(c, false);\n\n  BOOST_REQUIRE(eval.evaluate(c == (a && b)));\n  BOOST_REQUIRE(!eval.result<bool>());\n\n  eval.assign(a, false);\n  eval.assign(b, false);\n\n  BOOST_REQUIRE(eval.evaluate(c == (a && b)));\n  BOOST_REQUIRE(eval.result<bool>());\n}\n\nBOOST_AUTO_TEST_CASE(logical_or_t1) {\n  Variable<bool> a;\n  Variable<bool> b;\n  Variable<bool> c;\n  Evaluator eval;\n\n  eval.assign(a, false);\n  eval.assign(b, false);\n\n  BOOST_REQUIRE(eval.evaluate(a || b));\n  BOOST_REQUIRE(!eval.result<bool>());\n\n  eval.assign(c, false);\n\n  BOOST_REQUIRE(eval.evaluate(c == (a || b)));\n  BOOST_REQUIRE(eval.result<bool>());\n\n  eval.assign(a, true);\n  eval.assign(c, true);\n\n  BOOST_REQUIRE(eval.evaluate(c == (a || b)));\n  BOOST_REQUIRE(eval.result<bool>());\n}\n\nBOOST_AUTO_TEST_CASE(equal_t1) {\n  Variable<unsigned int> a;\n  Variable<unsigned int> b;\n  Evaluator eval;\n\n  eval.assign(a, 65535);\n\n  BOOST_REQUIRE(eval.evaluate(a));\n  BOOST_REQUIRE_EQUAL(eval.result<unsigned int>(), 65535);\n  BOOST_REQUIRE(eval.evaluate(a == 65535));\n  BOOST_REQUIRE(eval.result<bool>());\n\n  eval.assign(b, 5);\n\n  BOOST_REQUIRE(eval.evaluate(a == b));\n  BOOST_REQUIRE(!eval.result<bool>());\n}\n\nBOOST_AUTO_TEST_CASE(not_equal_t1) {\n  Variable<unsigned int> a;\n  Variable<unsigned int> b;\n  Evaluator eval;\n\n  eval.assign(a, 25u);\n\n  for (unsigned int i = 0; i < 50u; ++i) {\n    eval.assign(b, i);\n    BOOST_REQUIRE(eval.evaluate(a != b));\n\n    if (i != 25u)\n      BOOST_REQUIRE(eval.result<bool>());\n    else\n      BOOST_REQUIRE(!eval.result<bool>());\n  }\n}\n\nBOOST_AUTO_TEST_CASE(less) {\n  Variable<unsigned> a;\n  Variable<unsigned> b;\n  Evaluator eval;\n\n  for (unsigned int i = 0u; i < 50u; ++i) {\n    eval.assign(a, i);\n    BOOST_REQUIRE(eval.evaluate(a < 50u));\n    BOOST_REQUIRE(eval.result<bool>());\n\n    eval.assign(b, i);\n    BOOST_REQUIRE(eval.evaluate(b < 50u));\n    BOOST_REQUIRE(eval.result<bool>());\n  }\n}\n\nBOOST_AUTO_TEST_CASE(less_equal) {\n  Variable<unsigned> a;\n  Variable<unsigned> b;\n  Evaluator eval;\n\n  for (unsigned int i = 0u; i <= 50u; ++i) {\n    eval.assign(a, i);\n    BOOST_REQUIRE(eval.evaluate(a <= 50u));\n    BOOST_REQUIRE(eval.result<bool>());\n\n    eval.assign(b, i);\n    BOOST_REQUIRE(eval.evaluate(b <= 50u));\n    BOOST_REQUIRE(eval.result<bool>());\n  }\n}\n\nBOOST_AUTO_TEST_CASE(greater) {\n  Variable<unsigned> a;\n  Variable<unsigned> b;\n  Evaluator eval;\n\n  for (int i = 50; i > 0; --i) {\n    eval.assign(a, i);\n    BOOST_REQUIRE(eval.evaluate(a > 0u));\n    BOOST_REQUIRE(eval.result<bool>());\n\n    eval.assign(b, i);\n    BOOST_REQUIRE(eval.evaluate(b > 0u));\n    BOOST_REQUIRE(eval.result<bool>());\n  }\n}\n\nBOOST_AUTO_TEST_CASE(greater_equal) {\n  Variable<unsigned> a;\n  Variable<unsigned> b;\n  Evaluator eval;\n\n  for (int i = 50; i >= 0; --i) {\n    eval.assign(a, i);\n    BOOST_REQUIRE(eval.evaluate(a >= 0u));\n    BOOST_REQUIRE(eval.result<bool>());\n\n    eval.assign(b, i);\n    BOOST_REQUIRE(eval.evaluate(b >= 0u));\n    BOOST_REQUIRE(eval.result<bool>());\n  }\n}\n\nBOOST_AUTO_TEST_CASE(neg_t1) {\n  Variable<int> a;\n  Variable<int> b;\n  Evaluator eval;\n\n  eval.assign(a, 1337);\n  BOOST_REQUIRE(eval.evaluate(-a == 1337));\n  BOOST_REQUIRE(!eval.result<bool>());\n\n  eval.assign(b, -1337);\n  BOOST_REQUIRE(eval.evaluate(a == -b));\n  BOOST_REQUIRE(eval.result<bool>());\n}\n\nBOOST_AUTO_TEST_CASE(neg_t2) {\n  int a = 1337;\n  Variable<int> b;\n  Evaluator eval;\n\n  eval.assign(b, -a);\n  BOOST_REQUIRE(eval.evaluate(b));\n  BOOST_REQUIRE_EQUAL(eval.result<int>(), -1337);\n}\n\nBOOST_AUTO_TEST_CASE(complement_t1) {\n  Variable<int> a;\n  Variable<int> b;\n  Evaluator eval;\n\n  eval.assign(a, 0);\n  eval.assign(b, -1);\n  BOOST_REQUIRE(eval.evaluate(~a == b));\n  BOOST_REQUIRE(eval.result<bool>());\n}\n\nBOOST_AUTO_TEST_CASE(complement_t2) {\n  int a = 42;\n  Variable<int> b;\n  Evaluator eval;\n  eval.assign(b, a);\n  BOOST_REQUIRE(eval.evaluate(~b));\n  BOOST_REQUIRE_EQUAL(eval.result<int>(), -43);\n}\n\nBOOST_AUTO_TEST_CASE(bitwise_and_t1) {\n  Variable<unsigned int> a;\n  Variable<unsigned int> b;\n  Evaluator eval;\n\n  eval.assign(a, 42);\n  eval.assign(b, 1337);\n\n  BOOST_REQUIRE(eval.evaluate(a & b));\n  BOOST_REQUIRE_EQUAL(eval.result<unsigned int>(), 40);\n}\n\nBOOST_AUTO_TEST_CASE(bitwise_or_t1) {\n  Variable<unsigned int> a;\n  Variable<unsigned int> b;\n  Evaluator eval;\n\n  eval.assign(a, 42);\n  eval.assign(b, 1337);\n\n  BOOST_REQUIRE(eval.evaluate(a | b));\n  BOOST_REQUIRE_EQUAL(eval.result<unsigned int>(), 1339);\n}\n\nBOOST_AUTO_TEST_CASE(xor_t1) {\n  Variable<bool> a;\n  Variable<bool> b;\n  Evaluator eval;\n\n  eval.assign(a, false);\n  eval.assign(b, false);\n\n  BOOST_REQUIRE(eval.evaluate(a ^ b));\n  BOOST_REQUIRE_EQUAL(eval.result<bool>(), false);\n\n  eval.assign(b, true);\n\n  BOOST_REQUIRE(eval.evaluate(a ^ b));\n  BOOST_REQUIRE_EQUAL(eval.result<bool>(), true);\n}\n\nBOOST_AUTO_TEST_CASE(xor_t2) {\n  Variable<unsigned int> a;\n  Variable<unsigned int> b;\n  Evaluator eval;\n\n  eval.assign(a, 65535);\n  eval.assign(b, 4080);\n\n  BOOST_REQUIRE(eval.evaluate(a ^ b));\n  BOOST_REQUIRE_EQUAL(eval.result<unsigned int>(), 61455);\n}\n\nBOOST_AUTO_TEST_CASE(shiftleft) {\n  Variable<unsigned> a;\n  Variable<char> b;\n  Evaluator eval;\n\n  int count = 0;\n  while (++count < 256) {\n    eval.assign(a, count);\n    eval.assign(b, count % (sizeof(unsigned) << 3u));\n\n    BOOST_REQUIRE(eval.evaluate(a << b));\n    BOOST_REQUIRE_EQUAL(eval.result<unsigned>(), count << (count % (sizeof(unsigned) << 3u)));\n  }\n}\n\nBOOST_AUTO_TEST_CASE(shiftright) {\n  Variable<unsigned> a;\n  Variable<char> b;\n  Evaluator eval;\n\n  int count = 0;\n  while (256 > ++count) {\n    eval.assign(a, count + 256);\n    eval.assign(b, count % 8);\n\n    BOOST_REQUIRE(eval.evaluate(a >> b));\n    BOOST_REQUIRE_EQUAL(eval.result<unsigned>(), (count + 256) >> (count % 8));\n  }\n}\n\nBOOST_AUTO_TEST_CASE(plus_minus) {\n  Variable<unsigned int> a;\n  Variable<unsigned int> b;\n  Evaluator eval;\n\n  unsigned int cnt = 0;\n  while (cnt++ < 300) {\n    eval.assign(a, cnt * cnt);\n    eval.assign(b, cnt + cnt);\n\n    BOOST_REQUIRE(eval.evaluate(a + b));\n    BOOST_REQUIRE_EQUAL(eval.result<unsigned>(), (cnt * cnt) + (cnt + cnt));\n\n    BOOST_REQUIRE(eval.evaluate(a - b));\n    BOOST_REQUIRE_EQUAL(eval.result<unsigned>(), (cnt * cnt) - (cnt + cnt));\n  }\n}\n\nBOOST_AUTO_TEST_CASE(mult_mod) {\n  Variable<int> a;\n  Variable<int> b;\n  Evaluator eval;\n\n  for (int i = -3; i <= 3; i++) {\n    for (int j = -3; j <= 3; j++) {\n      eval.assign(a, i);\n      eval.assign(b, j);\n\n      BOOST_REQUIRE(eval.evaluate(a * b % 6));\n      BOOST_REQUIRE_EQUAL(eval.result<int>(), i * j % 6);\n    }\n  }\n\n  eval.assign(b, 0);\n\n  BOOST_REQUIRE(!eval.evaluate(a % b));\n}\n\nBOOST_AUTO_TEST_CASE(divide) {\n  Variable<short> a;\n  Variable<short> b;\n  Evaluator eval;\n\n  unsigned int cnt = 1;\n  while (cnt++ < 256) {\n    eval.assign(a, cnt * cnt);\n    eval.assign(b, cnt + cnt);\n\n    BOOST_REQUIRE(eval.evaluate(a / b));\n    BOOST_REQUIRE_EQUAL(eval.result<short>(), (cnt * cnt) / (cnt + cnt));\n\n    BOOST_REQUIRE(eval.evaluate(a % b));\n    BOOST_REQUIRE_EQUAL(eval.result<short>(), (cnt * cnt) % (cnt + cnt));\n  }\n\n  eval.assign(b, 0u);\n  BOOST_REQUIRE(!eval.evaluate(a / b));\n}\n\nBOOST_AUTO_TEST_CASE(element_inside_set) {\n  std::set<unsigned> s;\n  s.insert(1);\n  s.insert(7);\n  s.insert(9);\n\n  Variable<unsigned> x;\n  Evaluator eval;\n\n  eval.assign(x, 1);\n\n  BOOST_REQUIRE(eval.evaluate(inside(x, s)));\n  BOOST_REQUIRE(eval.result<bool>());\n\n  eval.assign(x, 5);\n\n  BOOST_REQUIRE(eval.evaluate(inside(x, s)));\n  BOOST_REQUIRE(!eval.result<bool>());\n}\n\nBOOST_AUTO_TEST_CASE(element_inside_vec) {\n  std::vector<unsigned> v;\n  v.push_back(1);\n  v.push_back(7);\n  v.push_back(9);\n\n  Variable<unsigned> x;\n  Evaluator eval;\n\n  eval.assign(x, 7u);\n\n  BOOST_REQUIRE(eval.evaluate(inside(x, v)));\n  BOOST_REQUIRE(eval.result<bool>());\n\n  eval.assign(x, 5u);\n\n  BOOST_REQUIRE(eval.evaluate(inside(x, v)));\n  BOOST_REQUIRE(!eval.result<bool>());\n}\n\nBOOST_AUTO_TEST_CASE(element_inside_array) {\n  unsigned a[3];\n  a[0] = 1;\n  a[1] = 7;\n  a[2] = 9;\n\n  Variable<unsigned> x;\n  Evaluator eval;\n\n  eval.assign(x, 9);\n\n  BOOST_REQUIRE(eval.evaluate(inside(x, a)));\n  BOOST_REQUIRE(eval.result<bool>());\n\n  eval.assign(x, 5u);\n\n  BOOST_REQUIRE(eval.evaluate(inside(x, a)));\n  BOOST_REQUIRE(!eval.result<bool>());\n}\n\nBOOST_AUTO_TEST_CASE(element_inside_list) {\n  std::list<unsigned> l;\n  l.push_back(1);\n  l.push_back(7);\n  l.push_back(9);\n\n  Variable<unsigned> x;\n  Evaluator eval;\n\n  eval.assign(x, 7u);\n\n  BOOST_REQUIRE(eval.evaluate(inside(x, l)));\n  BOOST_REQUIRE(eval.result<bool>());\n\n  eval.assign(x, 5u);\n\n  BOOST_REQUIRE(eval.evaluate(inside(x, l)));\n  BOOST_REQUIRE(!eval.result<bool>());\n}\n\nBOOST_AUTO_TEST_CASE(element_not_inside) {\n  Evaluator eval;\n  {\n    std::set<unsigned> s;\n    Variable<unsigned> x;\n    eval.assign(x, 1u);\n\n    BOOST_REQUIRE(eval.evaluate(inside(x, s)));\n    BOOST_REQUIRE(!eval.result<bool>());\n\n    s.insert(1u);\n\n    BOOST_REQUIRE(eval.evaluate(inside(x, s)));\n    BOOST_REQUIRE(eval.result<bool>());\n  }\n  {\n    std::vector<unsigned> v;\n\n    Variable<unsigned> x;\n    eval.assign(x, 1u);\n\n    BOOST_REQUIRE(eval.evaluate(inside(x, v)));\n    BOOST_REQUIRE(!eval.result<bool>());\n\n    v.push_back(1u);\n\n    BOOST_REQUIRE(eval.evaluate(inside(x, v)));\n    BOOST_REQUIRE(eval.result<bool>());\n  }\n  {\n    std::vector<unsigned> l;\n    Variable<unsigned> x;\n    eval.assign(x, 1u);\n\n    BOOST_REQUIRE(eval.evaluate(inside(x, l)));\n    BOOST_REQUIRE(!eval.result<bool>());\n\n    l.push_back(1u);\n\n    BOOST_REQUIRE(eval.evaluate(inside(x, l)));\n    BOOST_REQUIRE(eval.result<bool>());\n  }\n}\n\nBOOST_AUTO_TEST_CASE(if_then_else_t1) {\n  Variable<unsigned int> a;\n  Variable<unsigned int> b;\n  Evaluator eval;\n  expression expr = make_expression(if_then_else(a<5, b> 0 && b <= 50, b > 50 && b <= 100));\n\n  for (int i = 0; i < 10; ++i) {\n    eval.assign(a, i);\n    eval.assign(b, 25);\n    BOOST_REQUIRE(eval.evaluate(expr));\n\n    if (i < 5) {\n      BOOST_REQUIRE(eval.result<bool>());\n    } else {\n      BOOST_REQUIRE(!eval.result<bool>());\n    }\n    eval.assign(b, 75);\n    BOOST_REQUIRE(eval.evaluate(expr));\n\n    if (i < 5) {\n      BOOST_REQUIRE(!eval.result<bool>());\n    } else {\n      BOOST_REQUIRE(eval.result<bool>());\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE(if_then_t1) {\n  Variable<unsigned int> a;\n  Variable<unsigned int> b;\n  Evaluator eval;\n  expression expr = make_expression(if_then(a<5, b> 0 && b <= 100));\n\n  for (int i = 0; i < 10; ++i) {\n    eval.assign(a, i);\n    eval.assign(b, 25u);\n    BOOST_REQUIRE(eval.evaluate(expr));\n    BOOST_REQUIRE(eval.result<bool>());\n\n    eval.assign(b, 705u);\n    BOOST_REQUIRE(eval.evaluate(expr));\n\n    if (i < 5) {\n      BOOST_REQUIRE(!eval.result<bool>());\n    } else {\n      BOOST_REQUIRE(eval.result<bool>());\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE(equal_t2) {\n  Variable<unsigned int> a;\n  Variable<unsigned int> b;\n  Evaluator eval;\n\n  eval.assign(a, 1);\n  eval.assign(b, 2);\n\n  BOOST_REQUIRE(eval.evaluate(a == b));\n  BOOST_REQUIRE(!eval.result<bool>());\n}\n\nBOOST_AUTO_TEST_CASE(equal_t3) {\n  Variable<unsigned int> a;\n  Variable<unsigned int> b;\n  Variable<unsigned int> c;\n  Evaluator eval;\n\n  eval.assign(a, 1);\n  eval.assign(b, 2);\n  eval.assign(c, 3);\n\n  BOOST_REQUIRE(eval.evaluate(a + b == c));\n  BOOST_REQUIRE(eval.result<bool>());\n}\n\nBOOST_AUTO_TEST_SUITE_END()  // Evaluations\n", "meta": {"hexsha": "95f1856a9e739b0ee391196e5cd61ba6f755dadb", "size": 12722, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/core/test_Evaluations.cpp", "max_stars_repo_name": "quadric-io/crave", "max_stars_repo_head_hexsha": "8096d8b151cbe0d2ba437657f42d8bb0e05f5436", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2015-05-11T02:38:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T07:31:26.000Z", "max_issues_repo_path": "tests/core/test_Evaluations.cpp", "max_issues_repo_name": "quadric-io/crave", "max_issues_repo_head_hexsha": "8096d8b151cbe0d2ba437657f42d8bb0e05f5436", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2018-06-08T14:44:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-19T16:07:21.000Z", "max_forks_repo_path": "tests/core/test_Evaluations.cpp", "max_forks_repo_name": "quadric-io/crave", "max_forks_repo_head_hexsha": "8096d8b151cbe0d2ba437657f42d8bb0e05f5436", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2019-05-29T21:40:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-01T09:31:15.000Z", "avg_line_length": 21.4898648649, "max_line_length": 103, "alphanum_fraction": 0.6539852224, "num_tokens": 3425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680199891789, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.4680283480242004}}
{"text": "/*\n * Copyright 2019,\n * Olivier Stasse,\n *\n * CNRS/AIST\n *\n */\n\n#include <iostream>\n#include <sot/core/debug.hh>\n\n#ifndef WIN32\n#include <unistd.h>\n#endif\n\nusing namespace std;\n\n#include <dynamic-graph/entity.h>\n#include <dynamic-graph/factory.h>\n#include <sot/core/madgwickahrs.hh>\n#include <sstream>\n\nusing namespace dynamicgraph;\nusing namespace dynamicgraph::sot;\n\n#define BOOST_TEST_MODULE test - filter - differentiator\n\n#include <boost/test/output_test_stream.hpp>\n#include <boost/test/unit_test.hpp>\n\nusing boost::test_tools::output_test_stream;\n\nBOOST_AUTO_TEST_CASE(test_filter_differentiator) {\n  sot::MadgwickAHRS *aFilter = new MadgwickAHRS(\"MadgwickAHRS\");\n\n  double timestep = 0.001, beta = 0.01;\n  aFilter->init(timestep);\n  aFilter->set_beta(beta);\n\n  srand(0);\n  dynamicgraph::Vector acc(3);\n  dynamicgraph::Vector angvel(3);\n  acc(0) = 0.3;\n  acc(1) = 0.2;\n  acc(2) = 0.3;\n  aFilter->m_accelerometerSIN = acc;\n  angvel(0) = 0.1;\n  angvel(1) = -0.1;\n  angvel(2) = 0.3;\n  aFilter->m_gyroscopeSIN = angvel;\n  aFilter->m_imu_quatSOUT.recompute(0);\n  output_test_stream output;\n  ostringstream anoss;\n  aFilter->m_imu_quatSOUT.get(output);\n  aFilter->m_imu_quatSOUT.get(anoss);\n\n  BOOST_CHECK(output.is_equal(\"1 \"\n                              \"5.5547e-05 \"\n                              \"-5.83205e-05 \"\n                              \"0.00015\"));\n}\n", "meta": {"hexsha": "8227239833a982b3a83ee78404c659f5a34bddd0", "size": 1364, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/filters/test_madgwick_ahrs.cpp", "max_stars_repo_name": "machines-in-motion/sot-core", "max_stars_repo_head_hexsha": "9c0b1b3cd2bc03d36179cc8e47e11f7d42c1d4a5", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2016-03-28T07:15:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-05T13:41:06.000Z", "max_issues_repo_path": "tests/filters/test_madgwick_ahrs.cpp", "max_issues_repo_name": "machines-in-motion/sot-core", "max_issues_repo_head_hexsha": "9c0b1b3cd2bc03d36179cc8e47e11f7d42c1d4a5", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 121.0, "max_issues_repo_issues_event_min_datetime": "2015-02-17T08:38:25.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-01T10:54:05.000Z", "max_forks_repo_path": "tests/filters/test_madgwick_ahrs.cpp", "max_forks_repo_name": "machines-in-motion/sot-core", "max_forks_repo_head_hexsha": "9c0b1b3cd2bc03d36179cc8e47e11f7d42c1d4a5", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2015-07-01T16:25:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-08T15:06:58.000Z", "avg_line_length": 22.0, "max_line_length": 64, "alphanum_fraction": 0.6664222874, "num_tokens": 413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.46802834085944506}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   Utility_GeneralSphericalSpatialCoordinateConversionPolicy.hpp\n//! \\author Alex Robinson\n//! \\brief  General spherical spatial coordinate conversion policy declaration\n//!\n//---------------------------------------------------------------------------//\n\n#ifndef UTILITY_GENERAL_SPHERICAL_SPATIAL_COORDINATE_CONVERSION_POLICY_HPP\n#define UTILITY_GENERAL_SPHERICAL_SPATIAL_COORDINATE_CONVERSION_POLICY_HPP\n\n// Boost Includes\n#include <boost/serialization/array_wrapper.hpp>\n\n// FRENSIE Includes\n#include \"Utility_SphericalSpatialCoordinateConversionPolicy.hpp\"\n\nnamespace Utility{\n\n//! The general spherical spatial coordinate conversion policy class\nclass GeneralSphericalSpatialCoordinateConversionPolicy : public SphericalSpatialCoordinateConversionPolicy\n{\n\npublic:\n\n  //! Constructor\n  GeneralSphericalSpatialCoordinateConversionPolicy( const double origin[3],\n                                                     const double axis[3] );\n\n  //! Destructor\n  ~GeneralSphericalSpatialCoordinateConversionPolicy()\n  { /* ... */ }\n\n  //! Convert the spatial coordinates to cartesian coordinates\n  void convertToCartesianSpatialCoordinates(\n                                      const double primary_spatial_coord,\n                                      const double secondary_spatial_coord,\n                                      const double tertiary_spatial_coord,\n                                      double& x_spatial_coord,\n                                      double& y_spatial_coord,\n                                      double& z_spatial_coord ) const override;\n\n  //! Convert the cartesian coordinates to the spatial coordinate system\n  void convertFromCartesianSpatialCoordinates(\n                               const double x_spatial_coord,\n                               const double y_spatial_coord,\n                               const double z_spatial_coord,\n                               double& primary_spatial_coord,\n                               double& secondary_spatial_coord,\n                               double& tertiary_spatial_coord ) const override;\n\n  //! Convert the spatial coordinates to cartesian coordinates\n  using SphericalSpatialCoordinateConversionPolicy::convertToCartesianSpatialCoordinates;\n\n  //! Convert the cartesian coordinates to the spatial coordinate system\n  using SphericalSpatialCoordinateConversionPolicy::convertFromCartesianSpatialCoordinates;\n\nprivate:\n\n  // The default constructor should not be used - if the axis and origin\n  // correspond to the global coordinate system use the basic conversion\n  // policy\n  GeneralSphericalSpatialCoordinateConversionPolicy()\n  { /* ... */ }\n\n  // We have C-arrays as members - hide the copy constructor and assignment\n  // operator\n  GeneralSphericalSpatialCoordinateConversionPolicy( const GeneralSphericalSpatialCoordinateConversionPolicy& that );\n  GeneralSphericalSpatialCoordinateConversionPolicy& operator=( const GeneralSphericalSpatialCoordinateConversionPolicy& that );\n\n  // Save the policy to an archive\n  template<typename Archive>\n  void save( Archive& ar, const unsigned version ) const;\n\n  // Load the policy from an archive\n  template<typename Archive>\n  void load( Archive& ar, const unsigned version );\n\n  BOOST_SERIALIZATION_SPLIT_MEMBER();\n\n  // Declare the boost serialization access object as a friend\n  friend class boost::serialization::access;\n\n  // The origin of the spherical coordinate system w.r.t. the global Cartesian\n  // coordinate system\n  double d_origin[3];\n\n  // The z-axis (unit vector) of the spherical coordinate system w.r.t. the\n  // global Cartesian coordinate system\n  double d_axis[3];\n};\n\n// Save the policy to an archive\ntemplate<typename Archive>\nvoid GeneralSphericalSpatialCoordinateConversionPolicy::save( Archive& ar, const unsigned version ) const\n{\n  // Save the base class\n  ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP( SphericalSpatialCoordinateConversionPolicy );\n\n  // Save the local data\n  ar & boost::serialization::make_nvp( \"d_origin\", boost::serialization::make_array( d_origin, 3 ) );\n  ar & boost::serialization::make_nvp( \"d_axis\", boost::serialization::make_array( d_axis, 3 ) );\n}\n\n// Load the policy from an archive\ntemplate<typename Archive>\nvoid GeneralSphericalSpatialCoordinateConversionPolicy::load( Archive& ar, const unsigned version )\n{\n  // Load the base class\n  ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP( SphericalSpatialCoordinateConversionPolicy );\n\n  // Load the local data\n  ar & boost::serialization::make_nvp( \"d_origin\", boost::serialization::make_array( d_origin, 3 ) );\n  ar & boost::serialization::make_nvp( \"d_axis\", boost::serialization::make_array( d_axis, 3 ) );\n}\n\n} // end Utility namespace\n\nBOOST_SERIALIZATION_CLASS_VERSION( GeneralSphericalSpatialCoordinateConversionPolicy, Utility, 0 );\nBOOST_SERIALIZATION_CLASS_EXPORT_STANDARD_KEY( GeneralSphericalSpatialCoordinateConversionPolicy, Utility );\nEXTERN_EXPLICIT_CLASS_SAVE_LOAD_INST( Utility, GeneralSphericalSpatialCoordinateConversionPolicy );\n\n#endif // end UTILITY_GENERAL_SPHERICAL_SPATIAL_COORDINATE_CONVERSION_POLICY_HPP\n\n//---------------------------------------------------------------------------//\n// end Utility_GeneralSphericalSpatialCoordinateConversionPolicy.hpp\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "c848d08af6c472086e40640128eee20f7612ce7a", "size": 5396, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "packages/utility/system/src/Utility_GeneralSphericalSpatialCoordinateConversionPolicy.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/system/src/Utility_GeneralSphericalSpatialCoordinateConversionPolicy.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/system/src/Utility_GeneralSphericalSpatialCoordinateConversionPolicy.hpp", "max_forks_repo_name": "bam241/FRENSIE", "max_forks_repo_head_hexsha": "e1760cd792928699c84f2bdce70ff54228e88094", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-02-12T17:37:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-08T18:59:51.000Z", "avg_line_length": 42.15625, "max_line_length": 128, "alphanum_fraction": 0.6910674574, "num_tokens": 995, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.468028340859445}}
{"text": "#pragma once\n\n//#define BOOST_RESULT_OF_USE_DECLTYPE\n#include <type_traits>\n#include <array>\n\n#include<Eigen/Core>\n#include<Eigen/StdVector>\n\n#ifdef NDEBUG\n#define BOOST_DISABLE_ASSERTS\n#endif\n\n#include <boost/multi_array.hpp>\n#include <boost/iterator/transform_iterator.hpp>\n#include <boost/iterator/iterator_facade.hpp>\n\n#include \"tuple_tools.hpp\"\n\nnamespace gftools { \n\n/// container_base is a base class, that provides an interface of multidimensional array \n/// with arithmetic operations (element-wise addition, multiplication, etc)\n/// it is a wrapper over boost::multi_array and has 3 types : type of the stored numbers, rank and boost::multi_array type \n/// TODO ValueType is a duplication here\ntemplate <typename ValueType, size_t N, typename BoostContainerType>\nstruct container_base;\n\n/// container is a multidimensional array with math operations, that allocates and stores memory\ntemplate <typename ValueType, size_t N>\nstruct container;\n\n/// container_view is a \"view\" of a container_base that allows to access elements with a different storage order\ntemplate<typename ContainerType, size_t M = ContainerType::N_>\nusing container_view = container_base<typename ContainerType::value_type, ContainerType::N_, typename ContainerType::boost_t::template array_view<M>::type>;\n\n/// container_ref is a container without allocation of memory, i.e. it serves as an interface to an outside chunk of memory with all container operations\ntemplate <typename ValueType, size_t N>\nusing container_ref = container_base<ValueType, N, boost::multi_array_ref<ValueType,N>>;\n\n/// container_traits is a helper ''traits'' class that provides type definitions\ntemplate <typename, bool View=false> struct container_traits; \n\ntemplate <typename ValueType, size_t N, typename BoostContainerType>\nstruct container_base \n{\n    /// total rank (number of dimensions) of the container_base\n    constexpr static size_t N_ = N;\n    /// a helper flag that is true, when the container_base is a view\n    constexpr static bool is_view_ = (N != BoostContainerType::dimensionality);\n\n    // typedefs\n    /// typedef for stored values\n    typedef ValueType value_type;\n    /// typedef for a result of const operator[] operation (i.e. can be an array or a number) \n    typedef typename container_traits<container_base, is_view_>::type under_type;\n    /// typedef for a result of operator[] operation (i.e. can be an array or a number) \n    typedef typename container_traits<container_base, is_view_>::ref_type under_ref_type;\n    /// typedef for a resukt of operator[] of underlying boost::multi_array type\n    typedef typename container_traits<container_base, is_view_>::boost_under_type boost_under_type;\n    /// typedef wrapped boost::multi_array \n    typedef BoostContainerType boost_t;\n    /// typedef for a flattened array (Eigen::Array type) \n    typedef Eigen::Array<ValueType, Eigen::Dynamic, 1> EigenArray;\n    /// typedef for an Eigen::Map object that provides arithmetic operations on flattened arrays\n    typedef Eigen::Map<EigenArray> EigenMap;\n    /// typedef for a matrix with value_type values\n    typedef Eigen::Matrix<ValueType,Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> MatrixType;\n    /// typedef for a flattened Eigen::Vector, that provides vector*matrix operations\n    typedef Eigen::Matrix<ValueType,Eigen::Dynamic, 1> VectorType;\n\n    // helper type structues\n    /// TODO : move to traits\n    /// Is2d defines true_type if the objectr is 2d -> allows matrix operations\n    template <size_t N2 = N, typename DT = boost_t>\n    using Is2d = typename std::enable_if<N2==2,DT>::type;\n    // helper typedefs for math operations (to be able to multiply container and a ref, container and container, container and a number etc)\n    /// BaseRefIfContainer defines container_base type if the template parameter T is a container_base \n    template <typename T>\n    using BaseRefIfContainer = typename std::enable_if<T::N_>=1, container_base<ValueType,N,boost_t>&>::type;\n    /// ContaierIfContainer defines container type if the template parameter T is a container_base \n    template <typename T>\n    using ContainerIfContainer = typename std::enable_if<T::N_>=1, container<ValueType,N>>::type;\n    /// BaseRefIfValue defines container_base if the template parameter T is a number\n    template <typename T>\n    using BaseRefIfValue = typename std::enable_if<std::is_convertible<T,ValueType>::value, container_base<ValueType,N,boost_t>&>::type;\n    /// BaseRefIfValue defines container if the template parameter T is a number\n    template <typename T>\n    using ContainerIfValue = typename std::enable_if<std::is_convertible<T,ValueType>::value, container<ValueType,N>>::type;\n\n    // iterators\n    /// typedef for an operation that converts a operator[] of wrapped multi_array into operator[] of container\n    typedef std::function<under_type(boost_under_type)> action_type;\n    /// iterator (operates as a wrapper over multi_array)\n    typedef boost::transform_iterator<action_type,typename boost_t::iterator> iterator; \n    /// const_iterator\n    typedef boost::transform_iterator<action_type,typename boost_t::iterator> const_iterator; \n\n    // constructors\n    /// Constructor from the boost::multi_array (view, ref) type\n    container_base(const boost_t &in):storage_(in){};\n    /// Copy constructor\n    container_base(const container_base<ValueType,N,boost_t> &rhs):storage_(rhs.storage_){};\n    /// copy constructor from a different container_base\n    template <typename BT2>\n        container_base(const container_base<ValueType,N,BT2> &rhs):storage_(rhs.boost_container_()){};\n    /// move constructor (C++11)\n    container_base(container_base<ValueType,N,boost_t> &&rhs):storage_(std::forward<boost_t>(rhs.storage_)){ }\n    /// swap operation\n    void swap(container_base& rhs) {std::swap(storage_,rhs.storage_);}\n\n    // assigments\n    /// assignment operator from a differenet container base\n    template <typename BT2>\n        container_base& operator=(const container_base<ValueType,N,BT2> &rhs){storage_ = rhs.boost_container_(); return (*this);};\n    /// assignment operator\n    container_base& operator=(const container_base<ValueType,N,boost_t> &rhs){storage_ = rhs.storage_; return (*this);};\n    /// move assignment (C++11)\n    container_base& operator=(container_base<ValueType,N,boost_t> &&rhs){std::swap(storage_,rhs.storage_); return (*this);};\n    /// assign from a number\n    template <typename T> \n        typename std::enable_if<std::is_convertible<T,ValueType>::value,container_base&>::type operator=(T rhs);// { Base(*this) = rhs; return (*this);}\n    /// assign from matrix (2d containers only)\n    template<size_t N2 = N, typename U = Is2d<N2>>\n    container_base<ValueType,N,boost_t>& operator=(MatrixType rhs);\n\n    // access operations\n    /// access rank N-1 object\n    auto operator[](size_t i) -> under_ref_type { return under_ref_type(storage_[i]); }\n    /// const access rank N-1 object\n    auto operator[](size_t i) const -> under_ref_type const { return under_ref_type(storage_[i]); }\n    /// return value ref from an array of indices\n    ValueType& operator()(std::array<size_t, N> indices){return storage_(indices);}\n    /// return value const-ref from an array of indices\n    const ValueType& operator() (std::array<size_t, N> indices) const {return storage_(indices);}\n\n    // view modifiers\n    /// copy into a matrix \n    /// TODO consider viewing using Eigen::Map instead of copying\n    template<size_t N2 = N, typename U = Is2d<N2>>\n    MatrixType as_matrix() const;\n    /// copy into a diagonal matrix\n    MatrixType as_diagonal_matrix() const;\n    /// copy flattened container into a vector\n    VectorType as_vector() const;\n\n    // global operations\n    /// return a reference to this container as a flattened array \n    container_base<ValueType,1,boost::multi_array_ref<ValueType,1>> flatten();\n    /// conjugate copy for complex number objects\n    template<typename T=ValueType> typename std::enable_if< std::is_same<T, complex_type>::value, container<ValueType,N>>::type conj() const;\n    /// conjugate copy non-complex number objects (does nothing)\n    template<typename T=ValueType> typename std::enable_if<!std::is_same<T, complex_type>::value, container<ValueType,N>>::type conj() const;\n    /// return transposed copy (2d only)\n    template<size_t N2 = N, typename U = Is2d<N2>>\n    container<ValueType,N> transpose() const { return container<ValueType, N>( this->as_matrix().transpose()); }\n    /// return hermite conjugate copy (2d only)\n    template<size_t N2 = N, typename U = Is2d<N2>>\n    container<ValueType,N> hermite_conj() const { return this->transpose().conj(); }\n\n    /// Sum of all values in the container.\n    ValueType sum() const; \n    /// return the total size (sum of all dimensions) of the container\n    int size() const;\n    /// returns the shape of the container\n    std::array<size_t,N> shape() const;\n    /// returns the squared norm difference between 2 containers \n    template <typename V2, typename DT> double diff(const container_base<V2,N,DT>& r, bool norm = true) const; \n\n    /// returns a pointer to the first element in the container\n    ValueType* data() { return storage_.origin(); }\n    /// returns a const pointer to the first element in the container\n    const ValueType* data() const { return storage_.origin(); }\n    /** Make the object streamable. */\n    template <typename V1, size_t M, typename B>\n    friend std::ostream& operator<<(std::ostream& lhs, const container_base<V1, M, B> &in);\n\n    // iterator accessors\n    /// Begin const iterator./\n    const_iterator begin() const;\n    /// Begin iterator./\n    iterator begin();\n    /// End const iterator.\n    const_iterator end() const;\n    /// End iterator.\n    iterator end();\n    \n    // Mathematical operations\n    template <typename R>\n        BaseRefIfContainer<R> operator+=(const R &rhs); \n    template <typename R> \n        ContainerIfContainer<R> operator+(const R &rhs) const;\n    template <typename R2>\n        BaseRefIfValue<R2> operator+=(const R2& rhs);\n    template <typename R2> \n        ContainerIfValue<R2> operator+(const R2& rhs) const;\n\n    template <typename R>\n        BaseRefIfContainer<R> operator-=(const R &rhs); \n    template <typename R> \n        ContainerIfContainer<R> operator-(const R &rhs) const;\n    template <typename R2> \n        BaseRefIfValue<R2> operator-=(const R2& rhs);\n    template <typename R2> \n        ContainerIfValue<R2> operator-(const R2& rhs) const;\n\n    template <typename R>\n        BaseRefIfContainer<R> operator*=(const R &rhs); \n    template <typename R> \n        ContainerIfContainer<R> operator*(const R &rhs) const;\n    template <typename R2> \n        BaseRefIfValue<R2> operator*=(const R2& rhs);\n    template <typename R2> \n        ContainerIfValue<R2> operator*(const R2& rhs) const;\n\n    template <typename R>\n        BaseRefIfContainer<R> operator/=(const R &rhs); \n    template <typename R> \n        ContainerIfContainer<R> operator/(const R &rhs) const;\n    template <typename R2> \n        BaseRefIfValue<R2> operator/=(const R2& rhs);\n    template <typename R2> \n        ContainerIfValue<R2> operator/(const R2& rhs) const;\n\n    friend container<ValueType,N> operator* (const ValueType & lhs, const container_base<ValueType,N,boost_t> & rhs) {return rhs*lhs;};\n    friend container<ValueType,N> operator+ (const ValueType & lhs, const container_base<ValueType,N,boost_t> & rhs) {return rhs+lhs;};\n    friend container<ValueType,N> operator- (const ValueType & lhs, const container_base<ValueType,N,boost_t> & rhs) {return rhs*(-1.0)+lhs;};\n    friend container<ValueType,N> operator/ (const ValueType & lhs, const container_base<ValueType,N,boost_t> & rhs) {\n        container<ValueType,N> out(rhs); out=lhs; return out/rhs;};\n    \n    /// An exception provided for incorrect indices \n    class ex_wrong_index : public std::exception { virtual const char* what() const throw(){return \"Index out of bounds\";}}; \n    \n    /// return underlying boost container\n    /// underscore is added to discourage from using the method\n    boost_t& boost_container_() const {return storage_; }\nprotected:\n    /// allow other container t access internal storage\n    friend struct container<ValueType,N>;\n    /// wrapped boost multi_array\n    // it is mutable, because Eigen::Map operates with * pointers\n    // FIXME - remove mutable\n    mutable boost_t storage_;\n};\n\ntemplate <typename ValueType, size_t N>\nstruct container : container_base<ValueType,N,typename boost::multi_array<ValueType, N>> {\n    typedef boost::multi_array<ValueType, N> boost_t;\n    typedef container_base<ValueType,N,boost_t> Base;\n    using Base::storage_;\n    typedef typename Base::MatrixType MatrixType;\n\n    /// IsNotContainer defines true_type if the template parameter T is not a container_base type\n    template <typename T>\n    using IsNotContainer = typename std::enable_if<!(T::N_>=1)>::type;\n\n    /// construct container from a given shape of ints (initialize with zeros)\n    container(std::array<int,N> shape):container_base<ValueType,N,typename boost::multi_array<ValueType, N>>(boost::multi_array<ValueType, N>(shape)) {};\n    /// construct container from a given shape of size_t (initialize with zeros) \n    explicit container(std::array<size_t,N> shape):container_base<ValueType,N,typename boost::multi_array<ValueType, N>>(boost::multi_array<ValueType, N>(shape)) {};\n    /// construct container from an initializer list of ints, aka container<double, 2> a({{1,2}})\n    container(std::initializer_list<int> shape):container_base<ValueType,N,typename boost::multi_array<ValueType, N>>(boost::multi_array<ValueType, N>(std::array<int, N>(shape))) {};\n\n    /// construct from a different container_base \n    // using value here is safe with a move constructor\n    template <typename CT>\n        container(container_base<ValueType,N,CT> in) : container_base<ValueType,N,typename boost::multi_array<ValueType, N>>(in.storage_) {};\n    container(container const&) = default;\n    container(container &&) = default;\n    container& operator=(container &&) = default;\n    container& operator=(container const&) = default;\n\n    /// construct container from given variable amount of numbers, aka container<double, 4> a(1,2,4,2)\n    template<typename ...ShapeArgs,\n        typename = typename std::enable_if<sizeof...(ShapeArgs) == N \n               && (std::is_convertible<std::tuple<ShapeArgs...>, typename tuple_tools::repeater<int,N>::tuple_type>::value // Arguments have to be strictly ints\n               || std::is_convertible<std::tuple<ShapeArgs...>, typename tuple_tools::repeater<size_t,N>::tuple_type>::value) // or size_t\n        ,int>::type>\n        container(ShapeArgs...in):container_base<ValueType,N,typename boost::multi_array<ValueType, N>>(boost::multi_array<ValueType, N>(std::array<int,N>({{static_cast<int>(in)...}}))) {\n            static_assert(sizeof...(in) == N,\"arg mismatch\");\n        };\n    /// construct 2d container from matrix\n    template<size_t N2 = N, typename U = typename std::enable_if<N2==2, bool>::type> \n        container<ValueType,N> (MatrixType rhs);\n\n    // inherit math from base\n    using Base::operator+=;\n    using Base::operator-=;\n    using Base::operator*=;\n    using Base::operator/=;\n    using Base::operator=;\n    /// assign from a number\n    /*template <typename T> typename std::enable_if<std::is_convertible<T,ValueType>::value,container&>::type operator=(T rhs) { \n        typename std::add_lvalue_reference<Base>::type(*this) = rhs; return (*this);}\n    */\n};\n\n/// type traits for container/container_base of rank>1\ntemplate <typename ValueType, size_t N, typename BoostContainerType>\nstruct container_traits<container_base<ValueType,N,BoostContainerType>,false>\n{\n    /// typedef boost multi_array type\n    typedef BoostContainerType boost_t;\n    /// typedef for a result of const operator[] operation (i.e. can be an array or a number) \n    typedef typename boost_t::reference boost_under_type;\n    /// typedef for a result of operator[] operation (i.e. can be an array or a number) \n    typedef container_base<ValueType,N-1,boost_under_type> type;\n    /// typedef for a resukt of operator[] of underlying boost::multi_array type\n    typedef container_base<ValueType,N-1,boost_under_type> ref_type;\n};\n\n/// type traits for container/container_base of rank==1\ntemplate <typename ValueType, typename BoostContainerType>\nstruct container_traits<container_base<ValueType,1,BoostContainerType>,false>\n{\n    typedef BoostContainerType boost_t;\n    typedef typename boost_t::reference boost_under_type;\n    typedef ValueType type;\n    typedef ValueType& ref_type;\n};\n\n/// type traits for container views\ntemplate <typename ValueType, size_t N, typename BoostViewType>\nstruct container_traits<container_base<ValueType,N,BoostViewType>,true>\n{\n    typedef BoostViewType boost_t;\n    typedef typename boost_t::reference boost_under_type;\n    typedef ValueType type;\n    typedef ValueType& ref_type;\n};\n\n\n\n}; // end of namespace gftools\n\n#include \"container.hxx\"\n", "meta": {"hexsha": "7259d3170ce58c9372d0ad07e3f2b099333b8bc0", "size": 17001, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "gftools/container.hpp", "max_stars_repo_name": "hmenke/gftools", "max_stars_repo_head_hexsha": "d79810dd705b8e2efa802321382ebb7658e5f452", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2015-02-10T01:30:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-18T14:29:32.000Z", "max_issues_repo_path": "gftools/container.hpp", "max_issues_repo_name": "hmenke/gftools", "max_issues_repo_head_hexsha": "d79810dd705b8e2efa802321382ebb7658e5f452", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2015-04-01T12:38:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-17T21:21:38.000Z", "max_forks_repo_path": "gftools/container.hpp", "max_forks_repo_name": "hmenke/gftools", "max_forks_repo_head_hexsha": "d79810dd705b8e2efa802321382ebb7658e5f452", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2015-05-11T16:45:59.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-11T04:44:44.000Z", "avg_line_length": 50.4480712166, "max_line_length": 187, "alphanum_fraction": 0.7181930475, "num_tokens": 3983, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743167997235783, "lm_q2_score": 0.6297746074044135, "lm_q1q2_score": 0.4680283336946895}}
{"text": "\n#include <test_common.h>\n#include <igl/per_face_normals.h>\n#include <Eigen/Geometry>\n\nclass per_face_normals : public ::testing::TestWithParam<std::string> {};\n\nTEST_P(per_face_normals, dot)\n{\n  Eigen::MatrixXd V,N;\n  Eigen::MatrixXi F;\n  // Load example mesh: GetParam() will be name of mesh file\n  test_common::load_mesh(GetParam(), V, F);\n  igl::per_face_normals(V,F,N);\n  ASSERT_EQ(F.rows(),N.rows());\n  for(int f = 0;f<N.rows();f++)\n  {\n    for(int c = 0;c<3;c++)\n    {\n      // Every half-edge dot the normal should be 0\n      ASSERT_LT(\n        std::abs((V.row(F(f,c))-V.row(F(f,(c+1)%3))).dot(N.row(f))),\n        1e-12);\n    }\n  }\n  // ASSERT_EQ(a,b);\n  // ASSERT_TRUE(a==b);\n  // ASSERT_NEAR(a,b,1e-15)\n  // ASSERT_LT(a,1e-12);\n}\n\nINSTANTIATE_TEST_CASE_P\n(\n  all_meshes,\n  per_face_normals,\n  ::testing::ValuesIn(test_common::all_meshes()),\n  test_common::string_test_name\n);\n", "meta": {"hexsha": "f44bf647dc0e549ba10cea48a9d251c04c16842c", "size": 886, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "isometric-deformation/ext/libigl/tests/include/igl/per_face_normals.cpp", "max_stars_repo_name": "jiayaozhang/CS-370-Mesh-Processing", "max_stars_repo_head_hexsha": "26646d29af8cbc0d461302afa137f12b508b8b1b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-03T11:30:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-03T11:30:05.000Z", "max_issues_repo_path": "isometric-deformation/ext/libigl/tests/include/igl/per_face_normals.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/tests/include/igl/per_face_normals.cpp", "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": 22.7179487179, "max_line_length": 73, "alphanum_fraction": 0.6320541761, "num_tokens": 275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.6297745935070808, "lm_q1q2_score": 0.46802833053139203}}
{"text": "#include \"ship.hpp\"\n\n#include <boost/units/io.hpp>\n\nstd::ostream& operator<<(std::ostream& os, const Vector2d<Units::Force>& value)\n{\n    os << \"(\" << value(0) << \", \" << value(1) << \")\";\n    return os;\n}\n\n#include <catch2/catch.hpp>\n\nTEST_CASE(\"Test Ship with only one thruster\", \"[engine]\")\n{\n    using namespace boost::units::si;\n\n    SECTION(\"Basic ship with a thruster pointing straight up\")\n    {\n        Ship ship({{Thruster{1 * newtons}, {{0 * meters, -1 * meters}}, pi / 4 * radians}}, 1000 * kilograms);\n        CHECK(ship.numbeOfThrusters() == 1);\n        ship.setThrust(0, 0.);\n        CHECK(ship.thrust() == Vector2d<Units::Force>{{0 * newtons, 0 * newtons}});\n        ship.setThrust(0, 1.);\n        CHECK(ship.thrust() == Vector2d<Units::Force>{{0 * newtons, 1 * newtons}});\n    }\n}", "meta": {"hexsha": "6c032fd5d8997de9652454eafb304727b612f0b9", "size": 796, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/test_ship.cpp", "max_stars_repo_name": "julienlopez/DeepSpaceRacer", "max_stars_repo_head_hexsha": "ecde30fbd5f520c1919233e2d07437531151259e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "unit_tests/test_ship.cpp", "max_issues_repo_name": "julienlopez/DeepSpaceRacer", "max_issues_repo_head_hexsha": "ecde30fbd5f520c1919233e2d07437531151259e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-06-12T05:27:47.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-13T07:23:24.000Z", "max_forks_repo_path": "unit_tests/test_ship.cpp", "max_forks_repo_name": "julienlopez/DeepSpaceRacer", "max_forks_repo_head_hexsha": "ecde30fbd5f520c1919233e2d07437531151259e", "max_forks_repo_licenses": ["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.6153846154, "max_line_length": 110, "alphanum_fraction": 0.5866834171, "num_tokens": 234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118111485244, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.46793420837560384}}
{"text": "#include <boost/math/distributions/exponential.hpp>\n", "meta": {"hexsha": "44c06410aa116fe8e0d1dbc342d4ade3f92d4fe9", "size": 52, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_distributions_exponential.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_distributions_exponential.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_distributions_exponential.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 26.0, "max_line_length": 51, "alphanum_fraction": 0.8269230769, "num_tokens": 10, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317475, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4679341938760333}}
{"text": "/**\n * @file tests/main_tests/emst_test.cpp\n * @author Manish Kumar\n *\n * Test RUN_BINDING() of emst_main.cpp.\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#define BINDING_TYPE BINDING_TYPE_TEST\n\n#include <mlpack/core.hpp>\n#include <mlpack/methods/emst/emst_main.cpp>\n#include <mlpack/core/util/mlpack_main.hpp>\n#include \"main_test_fixture.hpp\"\n\n#include \"../catch.hpp\"\n\n#include <boost/math/special_functions/round.hpp>\n\nusing namespace mlpack;\n\nBINDING_TEST_FIXTURE(EMSTTestFixture);\n\n/**\n * Make sure that Output has 3 Dimensions and\n * check the number of output edges.\n */\nTEST_CASE_METHOD(EMSTTestFixture, \"EMSTOutputDimensionTest\",\n                 \"[EMSTMainTest][BindingTests]\")\n{\n  arma::mat x;\n  if (!data::Load(\"test_data_3_1000.csv\", x))\n    FAIL(\"Cannot load test dataset test_data_3_1000.csv!\");\n\n  // Input random data points.\n  SetInputParam(\"input\", std::move(x));\n  SetInputParam(\"leaf_size\", (int) 2);\n\n  RUN_BINDING();\n\n  // Now check that the output has 3 dimensions.\n  REQUIRE(params.Get<arma::mat>(\"output\").n_rows == 3);\n  // Check number of output points.\n  REQUIRE(params.Get<arma::mat>(\"output\").n_cols == 999);\n}\n\n/**\n * Check Naive algorithm Output has 3 Dimensions and\n * check the number of output edges.\n */\nTEST_CASE_METHOD(EMSTTestFixture, \"EMSTNaiveOutputDimensionTest\",\n                 \"[EMSTMainTest][BindingTests]\")\n{\n  arma::mat x;\n  if (!data::Load(\"test_data_3_1000.csv\", x))\n    FAIL(\"Cannot load test dataset test_data_3_1000.csv!\");\n\n  // Input random data points.\n  SetInputParam(\"input\", std::move(x));\n  SetInputParam(\"naive\", true);\n\n  RUN_BINDING();\n\n  // Now check that the output has 3 dimensions.\n  REQUIRE(params.Get<arma::mat>(\"output\").n_rows == 3);\n  // Check number of output points.\n  REQUIRE(params.Get<arma::mat>(\"output\").n_cols == 999);\n}\n\n/**\n * Ensure that we can't specify an invalid leaf size.\n */\nTEST_CASE_METHOD(EMSTTestFixture, \"EMSTInvalidLeafSizeTest\",\n                 \"[EMSTMainTest][BindingTests]\")\n{\n  arma::mat x;\n  if (!data::Load(\"test_data_3_1000.csv\", x))\n    FAIL(\"Cannot load test dataset test_data_3_1000.csv!\");\n\n  // Input random data points.\n  SetInputParam(\"input\", std::move(x));\n  SetInputParam(\"leaf_size\", (int) -1); // Invalid leaf size.\n\n  Log::Fatal.ignoreInput = true;\n  REQUIRE_THROWS_AS(RUN_BINDING(), std::runtime_error);\n  Log::Fatal.ignoreInput = false;\n}\n\n/**\n * Check that all elements of first two output rows are close to integers.\n */\nTEST_CASE_METHOD(EMSTTestFixture, \"EMSTFirstTwoOutputRowsIntegerTest\",\n                 \"[EMSTMainTest][BindingTests]\")\n{\n  arma::mat x;\n  if (!data::Load(\"test_data_3_1000.csv\", x))\n    FAIL(\"Cannot load test dataset test_data_3_1000.csv!\");\n\n  // Input random data points.\n  SetInputParam(\"input\", std::move(x));\n  SetInputParam(\"leaf_size\", (int) 2);\n\n  for (size_t i = 0; i < params.Get<arma::mat>(\"output\").n_cols; ++i)\n  {\n    REQUIRE(params.Get<arma::mat>(\"output\")(0, i) ==\n        Approx(boost::math::iround(params.Get<arma::mat>(\"output\")(0, i))).\n        epsilon(1e-7));\n    REQUIRE(params.Get<arma::mat>(\"output\")(1, i) ==\n        Approx(boost::math::iround(params.Get<arma::mat>(\"output\")(1, i))).\n        epsilon(1e-7));\n  }\n}\n", "meta": {"hexsha": "3cf3a8802a46ce4ae6830886f424e26dae7be4ca", "size": 3432, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/main_tests/emst_test.cpp", "max_stars_repo_name": "oblanchet/mlpack", "max_stars_repo_head_hexsha": "e02ab3be544694294d2f73bd12a98d0d162ef3af", "max_stars_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_stars_count": 4216.0, "max_stars_repo_stars_event_min_datetime": "2015-01-01T02:06:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T19:12:06.000Z", "max_issues_repo_path": "src/mlpack/tests/main_tests/emst_test.cpp", "max_issues_repo_name": "oblanchet/mlpack", "max_issues_repo_head_hexsha": "e02ab3be544694294d2f73bd12a98d0d162ef3af", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_issues_count": 2621.0, "max_issues_repo_issues_event_min_datetime": "2015-01-01T01:41:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T19:01:26.000Z", "max_forks_repo_path": "src/mlpack/tests/main_tests/emst_test.cpp", "max_forks_repo_name": "oblanchet/mlpack", "max_forks_repo_head_hexsha": "e02ab3be544694294d2f73bd12a98d0d162ef3af", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": 1972.0, "max_forks_repo_forks_event_min_datetime": "2015-01-01T23:37:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T06:03:41.000Z", "avg_line_length": 29.5862068966, "max_line_length": 78, "alphanum_fraction": 0.6809440559, "num_tokens": 936, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.46791484779702874}}
{"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 <Eigen/Core>\n#include <Eigen/Geometry>\n#include <glog/logging.h>\n#include <algorithm>\n#include <vector>\n#include \"gtest/gtest.h\"\n\n#include \"theia/alignment/alignment.h\"\n#include \"theia/math/util.h\"\n#include \"theia/util/random.h\"\n#include \"theia/util/util.h\"\n#include \"theia/sfm/pose/dls_pnp.h\"\n#include \"theia/sfm/pose/test_util.h\"\n#include \"theia/sfm/types.h\"\n\nnamespace theia {\nnamespace {\nusing Eigen::AngleAxisd;\nusing Eigen::Map;\nusing Eigen::Matrix3d;\nusing Eigen::Quaterniond;\nusing Eigen::Vector2d;\nusing Eigen::Vector3d;\n\nvoid TestDlsPnpWithNoise(const std::vector<Vector3d>& world_points,\n                         const double projection_noise_std_dev,\n                         const Quaterniond& expected_rotation,\n                         const Vector3d& expected_translation,\n                         const double max_reprojection_error,\n                         const double max_rotation_difference,\n                         const double max_translation_difference) {\n  InitRandomGenerator();\n\n  const int num_points = world_points.size();\n\n  Matrix3x4d expected_transform;\n  expected_transform << expected_rotation.toRotationMatrix(),\n      expected_translation;\n\n  std::vector<Vector2d> feature_points;\n  feature_points.reserve(num_points);\n  for (int i = 0; i < num_points; i++) {\n    // Reproject 3D points into camera frame.\n    feature_points.push_back(\n        (expected_transform * world_points[i].homogeneous())\n            .eval().hnormalized());\n  }\n\n  if (projection_noise_std_dev) {\n    // Adds noise to both of the rays.\n    for (int i = 0; i < num_points; i++) {\n      AddNoiseToProjection(projection_noise_std_dev, &feature_points[i]);\n    }\n  }\n\n  // Run DLS PnP.\n  std::vector<Quaterniond> soln_rotation;\n  std::vector<Vector3d> soln_translation;\n  DlsPnp(feature_points, world_points, &soln_rotation, &soln_translation);\n\n  // Check solutions and verify at least one is close to the actual solution.\n  const int num_solutions = soln_rotation.size();\n  EXPECT_GT(num_solutions, 0);\n  bool matched_transform = false;\n  for (int i = 0; i < num_solutions; i++) {\n    // Check that reprojection errors are small.\n    Matrix3x4d soln_transform;\n    soln_transform <<\n        soln_rotation[i].toRotationMatrix(), soln_translation[i];\n\n    for (int j = 0; j < num_points; j++) {\n      const Vector2d reprojected_point =\n          (soln_transform * world_points[j].homogeneous()).eval().hnormalized();\n      const double reprojection_error =\n          (feature_points[j] - reprojected_point).squaredNorm();\n      ASSERT_LE(reprojection_error, max_reprojection_error);\n    }\n\n    // Check that the solution is accurate.\n    const double rotation_difference =\n        expected_rotation.angularDistance(soln_rotation[i]);\n    const bool matched_rotation =\n        (rotation_difference < max_rotation_difference);\n    const double translation_difference =\n        (expected_translation - soln_translation[i]).squaredNorm();\n    const bool matched_translation =\n        (translation_difference < max_translation_difference);\n\n    if (matched_translation && matched_rotation) {\n      matched_transform = true;\n    }\n  }\n  EXPECT_TRUE(matched_transform);\n}\n\nvoid BasicTest() {\n  const std::vector<Vector3d> points_3d = { Vector3d(-1.0, 3.0, 3.0),\n                                            Vector3d(1.0, -1.0, 2.0),\n                                            Vector3d(-1.0, 1.0, 2.0),\n                                            Vector3d(2.0, 1.0, 3.0) };\n  const Quaterniond soln_rotation = Quaterniond(\n      AngleAxisd(DegToRad(13.0), Vector3d(0.0, 0.0, 1.0)));\n  const Vector3d soln_translation(1.0, 1.0, 1.0);\n  const double kNoise = 0.0;\n  const double kMaxReprojectionError = 1e-4;\n  const double kMaxAllowedRotationDifference = 1e-5;\n  const double kMaxAllowedTranslationDifference = 1e-8;\n\n  TestDlsPnpWithNoise(points_3d,\n                      kNoise,\n                      soln_rotation,\n                      soln_translation,\n                      kMaxReprojectionError,\n                      kMaxAllowedRotationDifference,\n                      kMaxAllowedTranslationDifference);\n}\n\nTEST(DlsPnp, Basic) {\n  BasicTest();\n}\n\nTEST(DlsPnp, NoiseTest) {\n    const std::vector<Vector3d> points_3d = { Vector3d(-1.0, 3.0, 3.0),\n                                              Vector3d(1.0, -1.0, 2.0),\n                                              Vector3d(-1.0, 1.0, 2.0),\n                                              Vector3d(2.0, 1.0, 3.0),\n                                              Vector3d(-1.0, -3.0, 2.0),\n                                              Vector3d(1.0, -2.0, 1.0),\n                                              Vector3d(-1.0, 4.0, 2.0),\n                                              Vector3d(-2.0, 2.0, 3.0)\n    };\n  const Quaterniond soln_rotation = Quaterniond(\n      AngleAxisd(DegToRad(13.0), Vector3d(0.0, 0.0, 1.0)));\n  const Vector3d soln_translation(1.0, 1.0, 1.0);\n  const double kNoise = 1.0 / 512.0;\n  const double kMaxReprojectionError = 5e-3;\n  const double kMaxAllowedRotationDifference = DegToRad(0.25);\n  const double kMaxAllowedTranslationDifference = 1e-2;\n\n  TestDlsPnpWithNoise(points_3d,\n                      kNoise,\n                      soln_rotation,\n                      soln_translation,\n                      kMaxReprojectionError,\n                      kMaxAllowedRotationDifference,\n                      kMaxAllowedTranslationDifference);\n}\n\nTEST(DlsPnp, ManyPoints) {\n// Sets some test rotations and translations.\n  static const Vector3d kAxes[] = {\n      Vector3d(0.0, 0.0, 1.0).normalized(),\n      Vector3d(0.0, 1.0, 0.0).normalized(),\n      Vector3d(1.0, 0.0, 0.0).normalized(),\n      Vector3d(1.0, 0.0, 1.0).normalized(),\n      Vector3d(0.0, 1.0, 1.0).normalized(),\n      Vector3d(1.0, 1.0, 1.0).normalized(),\n      Vector3d(0.0, 1.0, 1.0).normalized(),\n      Vector3d(1.0, 1.0, 1.0).normalized()\n  };\n\n  static const double kRotationAngles[THEIA_ARRAYSIZE(kAxes)] = {\n      DegToRad(7.0),\n      DegToRad(12.0),\n      DegToRad(15.0),\n      DegToRad(20.0),\n      DegToRad(11.0),\n      DegToRad(0.0),  // Tests no rotation.\n      DegToRad(5.0),\n      DegToRad(0.0)  // Tests no rotation and no translation.\n  };\n\n  static const Vector3d kTranslations[THEIA_ARRAYSIZE(kAxes)] = {\n      Vector3d(1.0, 1.0, 1.0),\n      Vector3d(3.0, 2.0, 13.0),\n      Vector3d(4.0, 5.0, 11.0),\n      Vector3d(1.0, 2.0, 15.0),\n      Vector3d(3.0, 1.5, 18.0),\n      Vector3d(1.0, 7.0, 11.0),\n      Vector3d(0.0, 0.0, 0.0),  // Tests no translation.\n      Vector3d(0.0, 0.0, 0.0)  // Tests no translation and no rotation.\n  };\n\n  static const int num_points[3] = { 100, 500, 1000 };\n  const double kNoise = 1.0 / 512.0;\n  const double kMaxReprojectionError = 1e-2;\n  const double kMaxAllowedRotationDifference = DegToRad(0.3);\n  const double kMaxAllowedTranslationDifference = 5e-3;\n\n  for (int i = 0; i < THEIA_ARRAYSIZE(kAxes); i++) {\n    const Quaterniond soln_rotation(AngleAxisd(kRotationAngles[i], kAxes[i]));\n    for (int j = 0; j < THEIA_ARRAYSIZE(num_points); j++) {\n      std::vector<Vector3d> points_3d;\n      points_3d.reserve(num_points[j]);\n      for (int k = 0; k < num_points[j]; k++) {\n        points_3d.push_back(Vector3d(RandDouble(-5.0, 5.0),\n                                     RandDouble(-5.0, 5.0),\n                                     RandDouble(2.0, 10.0)));\n      }\n\n      TestDlsPnpWithNoise(points_3d,\n                          kNoise,\n                          soln_rotation,\n                          kTranslations[i],\n                          kMaxReprojectionError,\n                          kMaxAllowedRotationDifference,\n                          kMaxAllowedTranslationDifference);\n    }\n  }\n}\n\nTEST(DlsPnp, NoRotation) {\n    const std::vector<Vector3d> points_3d = { Vector3d(-1.0, 3.0, 3.0),\n                                              Vector3d(1.0, -1.0, 2.0),\n                                              Vector3d(-1.0, 1.0, 2.0),\n                                              Vector3d(2.0, 1.0, 3.0),\n                                              Vector3d(-1.0, -3.0, 2.0),\n                                              Vector3d(1.0, -2.0, 1.0),\n                                              Vector3d(-1.0, 4.0, 2.0),\n                                              Vector3d(-2.0, 2.0, 3.0)\n    };\n  const Quaterniond soln_rotation = Quaterniond(\n      AngleAxisd(DegToRad(0.0), Vector3d(0.0, 0.0, 1.0)));\n  const Vector3d soln_translation(1.0, 1.0, 1.0);\n  const double kNoise = 1.0 / 512.0;\n  const double kMaxReprojectionError = 5e-3;\n  const double kMaxAllowedRotationDifference = DegToRad(0.25);\n  const double kMaxAllowedTranslationDifference = 5e-4;\n\n  TestDlsPnpWithNoise(points_3d,\n                      kNoise,\n                      soln_rotation,\n                      soln_translation,\n                      kMaxReprojectionError,\n                      kMaxAllowedRotationDifference,\n                      kMaxAllowedTranslationDifference);\n}\n\nTEST(DlsPnp, NoTranslation) {\n      const std::vector<Vector3d> points_3d = { Vector3d(-1.0, 3.0, 3.0),\n                                              Vector3d(1.0, -1.0, 2.0),\n                                              Vector3d(-1.0, 1.0, 2.0),\n                                              Vector3d(2.0, 1.0, 3.0),\n                                              Vector3d(-1.0, -3.0, 2.0),\n                                              Vector3d(1.0, -2.0, 1.0),\n                                              Vector3d(-1.0, 4.0, 2.0),\n                                              Vector3d(-2.0, 2.0, 3.0)\n    };\n  const Quaterniond soln_rotation = Quaterniond(\n      AngleAxisd(DegToRad(13.0), Vector3d(0.0, 0.0, 1.0)));\n  const Vector3d soln_translation(0.0, 0.0, 0.0);\n  const double kNoise = 1.0 / 512.0;\n  const double kMaxReprojectionError = 1e-2;\n  const double kMaxAllowedRotationDifference = DegToRad(0.2);\n  const double kMaxAllowedTranslationDifference = 5e-3;\n\n  TestDlsPnpWithNoise(points_3d,\n                      kNoise,\n                      soln_rotation,\n                      soln_translation,\n                      kMaxReprojectionError,\n                      kMaxAllowedRotationDifference,\n                      kMaxAllowedTranslationDifference);\n}\n\nTEST(DlsPnp, OrthogonalRotation) {\n    const std::vector<Vector3d> points_3d = { Vector3d(-1.0, 3.0, 3.0),\n                                              Vector3d(1.0, -1.0, 2.0),\n                                              Vector3d(-1.0, 1.0, 2.0),\n                                              Vector3d(2.0, 1.0, 3.0),\n                                              Vector3d(-1.0, -3.0, 2.0),\n                                              Vector3d(1.0, -2.0, 1.0),\n                                              Vector3d(-1.0, 4.0, 2.0),\n                                              Vector3d(-2.0, 2.0, 3.0)\n    };\n  const Quaterniond soln_rotation = Quaterniond(\n      AngleAxisd(DegToRad(90.0), Vector3d(0.0, 0.0, 1.0)));\n  const Vector3d soln_translation(1.0, 1.0, 1.0);\n  const double kNoise = 1.0 / 512.0;\n  const double kMaxReprojectionError = 5e-3;\n  const double kMaxAllowedRotationDifference = DegToRad(0.25);\n  const double kMaxAllowedTranslationDifference = 5e-3;\n\n  TestDlsPnpWithNoise(points_3d,\n                      kNoise,\n                      soln_rotation,\n                      soln_translation,\n                      kMaxReprojectionError,\n                      kMaxAllowedRotationDifference,\n                      kMaxAllowedTranslationDifference);\n}\n\n}  // namespace\n}  // namespace theia\n", "meta": {"hexsha": "0e491cb0190bdbbcc8c42cf2ce571640792a4cb4", "size": 13352, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/sfm/pose/dls_pnp_test.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/pose/dls_pnp_test.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/pose/dls_pnp_test.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": 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": 40.5835866261, "max_line_length": 80, "alphanum_fraction": 0.5749700419, "num_tokens": 3580, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.46791484779702874}}
{"text": "// Copyright Abel Sinkovics (abel@sinkovics.hu) 2012.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n#include <mpllibs/metamonad/list.hpp>\n\n#include <mpllibs/metamonad/mzero.hpp>\n#include <mpllibs/metamonad/mplus.hpp>\n\n#include <boost/test/unit_test.hpp>\n\n#include \"common.hpp\"\n\n#include <boost/mpl/equal.hpp>\n#include <boost/mpl/assert.hpp>\n\nBOOST_AUTO_TEST_CASE(test_list_monad_plus)\n{\n  using mpllibs::metamonad::list_tag;\n  using mpllibs::metamonad::mplus;\n  using mpllibs::metamonad::mzero;\n  \n  using boost::mpl::equal;\n  using boost::mpl::list;\n  \n  typedef mzero<list_tag>::type zero;\n\n  // test mzero\n  BOOST_MPL_ASSERT((equal<zero, list<> >));\n\n  // test mzero + mzero\n  BOOST_MPL_ASSERT((equal<zero, mplus<list_tag, zero, zero>::type>));\n\n  // test mzero + x\n  BOOST_MPL_ASSERT((\n    equal<list<int13>, mplus<list_tag, zero, list<int13> >::type>\n  ));\n\n  // test x + mzero\n  BOOST_MPL_ASSERT((\n    equal<list<int13>, mplus<list_tag, list<int13>, zero>::type>\n  ));\n\n  // test x + y\n  BOOST_MPL_ASSERT((\n    equal<list<int11, int13>, mplus<list_tag, list<int11>, list<int13> >::type>\n  ));\n}\n\n", "meta": {"hexsha": "92a573ada434a12c736af3eb4870564ca05c70d7", "size": 1225, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/metamonad/test/list_monad_plus.cpp", "max_stars_repo_name": "sabel83/mpllibs", "max_stars_repo_head_hexsha": "8e245aedcf658fe77bb29537aeba1d4e1a619a19", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 70.0, "max_stars_repo_stars_event_min_datetime": "2015-01-15T09:05:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-08T15:49:31.000Z", "max_issues_repo_path": "libs/metamonad/test/list_monad_plus.cpp", "max_issues_repo_name": "sabel83/mpllibs", "max_issues_repo_head_hexsha": "8e245aedcf658fe77bb29537aeba1d4e1a619a19", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-06-18T19:25:34.000Z", "max_issues_repo_issues_event_max_datetime": "2016-05-13T19:49:51.000Z", "max_forks_repo_path": "libs/metamonad/test/list_monad_plus.cpp", "max_forks_repo_name": "sabel83/mpllibs", "max_forks_repo_head_hexsha": "8e245aedcf658fe77bb29537aeba1d4e1a619a19", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2015-07-10T08:18:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-01T07:17:57.000Z", "avg_line_length": 24.0196078431, "max_line_length": 79, "alphanum_fraction": 0.6889795918, "num_tokens": 370, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583124210896, "lm_q2_score": 0.6723316991792861, "lm_q1q2_score": 0.4679148347480197}}
{"text": "#include \"ValueWithError.hpp\"\n#include \"precompiled.hpp\"\n#include \"common.hpp\"\n\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Wglobal-constructors\"\n#endif // __clang__\n\n#if defined __GNUC__ \\\n            && ( __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 7) ) \\\n            && !defined __clang__\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wunused-local-typedefs\"\n#endif // __GNUC__\n\n#include <boost/test/unit_test.hpp>\n\nusing namespace error_propagation;\n\nnamespace {\n\n  typedef ValueWithError<double,CompareWithinErrorIntervalsPolicy> VD;\n  typedef ValueWithError<float,CompareWithinErrorIntervalsPolicy> PVF;\n\n  struct CompareWithinErrorFixture{ };\n\n} // anonymous namespace\n\nBOOST_FIXTURE_TEST_SUITE(Test_CompareWithinErrorIntervalsPolicy,CompareWithinErrorFixture)\n\nBOOST_AUTO_TEST_CASE(operator_equal)\n{\n  // no overlap\n  BOOST_CHECK(!CompareWithinErrorIntervalsPolicy::Equal(VD(1.0,0.4),VD(2.0,0.4)));\n  // point overlap\n  BOOST_CHECK(CompareWithinErrorIntervalsPolicy::Equal(VD(1.0,1.0), VD(2.0,0.4)));\n  // range overlap\n  BOOST_CHECK(CompareWithinErrorIntervalsPolicy::Equal(VD(1.0,1.3), VD(2.0,0.4)));\n\n  // test overloads\n  BOOST_CHECK(CompareWithinErrorIntervalsPolicy::Equal(VD(1.0), 1.0));\n  BOOST_CHECK(CompareWithinErrorIntervalsPolicy::Equal(VD(1.0,0.4), 1.0));\n  BOOST_CHECK(CompareWithinErrorIntervalsPolicy::Equal(1.0, VD(1.0,0.4)));\n}\n// not equal defined in terms of equal therefore skipping for now\n\nBOOST_AUTO_TEST_CASE(operator_greaterOrEqualThan)\n{\n  // no overlap\n  BOOST_CHECK(!CompareWithinErrorIntervalsPolicy::GreaterOrEqual(VD(1.0,0.4), VD(2.0,0.4)));\n  BOOST_CHECK(CompareWithinErrorIntervalsPolicy::GreaterOrEqual(VD(2.0,0.4), VD(1.0,0.4)));\n  // point overlap\n  BOOST_CHECK(CompareWithinErrorIntervalsPolicy::GreaterOrEqual(VD(1.0,1.0), VD(2.0,0.4)));\n  // range overlap\n  BOOST_CHECK(CompareWithinErrorIntervalsPolicy::GreaterOrEqual(VD(1.0,1.3), VD(2.0,0.4)));\n\n  // test overloads\n  BOOST_CHECK(CompareWithinErrorIntervalsPolicy::GreaterOrEqual(VD(1.0), 1.0));\n  BOOST_CHECK(CompareWithinErrorIntervalsPolicy::GreaterOrEqual(VD(2.0), 1.0));\n  BOOST_CHECK(CompareWithinErrorIntervalsPolicy::GreaterOrEqual(VD(1.0,0.4), 1.0));\n  BOOST_CHECK(CompareWithinErrorIntervalsPolicy::GreaterOrEqual(VD(2.0,0.4), 1.0));\n  BOOST_CHECK(CompareWithinErrorIntervalsPolicy::GreaterOrEqual(1.0, VD(1.0,0.4)));\n  BOOST_CHECK(CompareWithinErrorIntervalsPolicy::GreaterOrEqual(2.0, VD(1.0,0.4)));\n}\n\nBOOST_AUTO_TEST_CASE(operator_greaterThan)\n{\n  // no overlap\n  BOOST_CHECK(!CompareWithinErrorIntervalsPolicy::GreaterThan(VD(1.0,0.4), VD(2.0,0.4)));\n  BOOST_CHECK(CompareWithinErrorIntervalsPolicy::GreaterThan(VD(2.0,0.4), VD(1.0,0.4)));\n  // point overlap\n  BOOST_CHECK(!CompareWithinErrorIntervalsPolicy::GreaterThan(VD(1.0,1.0), VD(2.0,0.4)));\n  // range overlap\n  BOOST_CHECK(!CompareWithinErrorIntervalsPolicy::GreaterThan(VD(1.0,1.3), VD(2.0,0.4)));\n\n  // test overloads\n  BOOST_CHECK(CompareWithinErrorIntervalsPolicy::GreaterThan(VD(2.0), 1.0));\n  BOOST_CHECK(CompareWithinErrorIntervalsPolicy::GreaterThan(VD(2.0,0.4), 1.0));\n  BOOST_CHECK(CompareWithinErrorIntervalsPolicy::GreaterThan(2.0, VD(1.0,0.4)));\n}\n\nBOOST_AUTO_TEST_SUITE_END() // Test_CompareWithinErrorIntervalsPolicy\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif // __clang__\n\n#if defined __GNUC__ \\\n            && ( __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 7) ) \\\n            && !defined __clang__\n#pragma GCC diagnostic pop\n#endif // __GNUC__\n\n", "meta": {"hexsha": "6ae80591c09521a4df7510651500941026821b33", "size": 3517, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/Test_CompareWithinErrorIntervalsPolicy.cpp", "max_stars_repo_name": "t-b/value-with-error", "max_stars_repo_head_hexsha": "ede8325d3572ac53601d0d7aabc09518850c8455", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-09-07T10:58:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-16T01:09:50.000Z", "max_issues_repo_path": "tests/Test_CompareWithinErrorIntervalsPolicy.cpp", "max_issues_repo_name": "t-b/value-with-error", "max_issues_repo_head_hexsha": "ede8325d3572ac53601d0d7aabc09518850c8455", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/Test_CompareWithinErrorIntervalsPolicy.cpp", "max_forks_repo_name": "t-b/value-with-error", "max_forks_repo_head_hexsha": "ede8325d3572ac53601d0d7aabc09518850c8455", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.0210526316, "max_line_length": 92, "alphanum_fraction": 0.7514927495, "num_tokens": 1084, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723316991792861, "lm_q2_score": 0.6959583124210896, "lm_q1q2_score": 0.4679148347480197}}
{"text": "/* vim: set tabstop=4 expandtab shiftwidth=4 softtabstop=4: */\n\n/**\n * \\file libs/numeric/ublasx/test/tril.cpp\n *\n * \\brief Test suite for the lower-triangular view operation.\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n *\n * <hr/>\n *\n * Copyright (c) 2011, Marco Guazzone\n *\n * Distributed under the Boost Software License, Version 1.0. (See\n * accompwhiching file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/triangular.hpp>\n#include <boost/numeric/ublasx/detail/debug.hpp>\n#include <boost/numeric/ublasx/operation/tril.hpp>\n#include <complex>\n#include <cstddef>\n#include \"libs/numeric/ublasx/test/utils.hpp\"\n\n\nnamespace ublas = ::boost::numeric::ublas;\nnamespace ublasx = ::boost::numeric::ublasx;\n\n\nstatic const double tol = 1e-5;\n\n\nBOOST_UBLASX_TEST_DEF( real_square_matrix_row_major_keq0 )\n{\n    BOOST_UBLASX_DEBUG_TRACE( \"Test Case: Real - Square - Row Major - k == 0\" );\n\n    typedef double value_type;\n    typedef ublas::matrix<value_type,ublas::row_major> matrix_type;\n\n    const ::std::size_t n(4);\n\n    matrix_type A(n,n, value_type(1));\n\n\n    matrix_type X;\n    matrix_type E;\n\n    X = ublasx::tril(A);\n    E = ublasx::triangular_matrix<value_type,ublas::lower>(n,n);\n    E(0,0) = \n    E(1,0) = E(1,1) =\n    E(2,0) = E(2,1) = E(2,2) =\n    E(3,0) = E(3,1) = E(3,2) = E(3,3) = value_type(1);\n\n    BOOST_UBLASX_DEBUG_TRACE( \"Input Matrix A=\" << A );\n    //BOOST_UBLASX_DEBUG_TRACE( \"E=\" << E );\n    BOOST_UBLASX_DEBUG_TRACE( \"tril(A)=\" << X );\n    BOOST_UBLASX_TEST_CHECK_MATRIX_CLOSE( X, E, n, n, tol );\n}\n\n\nBOOST_UBLASX_TEST_DEF( real_square_matrix_col_major_keq0 )\n{\n    BOOST_UBLASX_DEBUG_TRACE( \"Test Case: Real - Square - Column Major - k == 0\" );\n\n    typedef double value_type;\n    typedef ublas::matrix<value_type,ublas::column_major> matrix_type;\n\n    const ::std::size_t n(4);\n\n    matrix_type A(n,n, value_type(1));\n\n\n    matrix_type X;\n    matrix_type E;\n\n    X = ublasx::tril(A);\n    E = ublasx::triangular_matrix<value_type,ublas::lower>(n,n);\n    E(0,0) = \n    E(1,0) = E(1,1) =\n    E(2,0) = E(2,1) = E(2,2) =\n    E(3,0) = E(3,1) = E(3,2) = E(3,3) = value_type(1);\n\n    BOOST_UBLASX_DEBUG_TRACE( \"Input Matrix A=\" << A );\n    //BOOST_UBLASX_DEBUG_TRACE( \"E=\" << E );\n    BOOST_UBLASX_DEBUG_TRACE( \"tril(A)=\" << X );\n    BOOST_UBLASX_TEST_CHECK_MATRIX_CLOSE( X, E, n, n, tol );\n}\n\n\nBOOST_UBLASX_TEST_DEF( real_square_matrix_row_major_kgt0 )\n{\n    BOOST_UBLASX_DEBUG_TRACE( \"Test Case: Real - Square - Row Major - k > 0\" );\n\n    typedef double value_type;\n    typedef ublas::matrix<value_type,ublas::row_major> matrix_type;\n\n    const ::std::size_t n(4);\n\n    matrix_type A(n,n, value_type(1));\n\n\n    matrix_type X;\n    matrix_type E;\n\n    E = ublasx::scalar_matrix<value_type,ublas::lower>(n,n,value_type(1));\n\n    for (::std::ptrdiff_t k = n-1; k >= 0; --k)\n    {\n        X = ublasx::tril(A, k);\n\n        for (::std::size_t i = 0; i < (n-k-1); ++i)\n        {\n            E(i,i+k+1) = value_type(0);\n        }\n\n        //BOOST_UBLASX_DEBUG_TRACE( \"E=\" << E );\n        BOOST_UBLASX_DEBUG_TRACE( \"tril(A,\" << k << \")=\" << X );\n        BOOST_UBLASX_TEST_CHECK_MATRIX_CLOSE( X, E, n, n, tol );\n    }\n}\n\n\nBOOST_UBLASX_TEST_DEF( real_square_matrix_col_major_kgt0 )\n{\n    BOOST_UBLASX_DEBUG_TRACE( \"Test Case: Real - Square - Column Major - k > 0\" );\n\n    typedef double value_type;\n    typedef ublas::matrix<value_type,ublas::column_major> matrix_type;\n\n    const ::std::size_t n(4);\n\n    matrix_type A(n,n, value_type(1));\n\n\n    matrix_type X;\n    matrix_type E;\n\n    E = ublasx::scalar_matrix<value_type,ublas::lower>(n,n,value_type(1));\n\n    for (::std::ptrdiff_t k = n-1; k >= 0; --k)\n    {\n        X = ublasx::tril(A, k);\n\n        for (::std::size_t i = 0; i < (n-k-1); ++i)\n        {\n            E(i,i+k+1) = value_type(0);\n        }\n\n        //BOOST_UBLASX_DEBUG_TRACE( \"E=\" << E );\n        BOOST_UBLASX_DEBUG_TRACE( \"tril(A,\" << k << \")=\" << X );\n        BOOST_UBLASX_TEST_CHECK_MATRIX_CLOSE( X, E, n, n, tol );\n    }\n}\n\n\nBOOST_UBLASX_TEST_DEF( real_square_matrix_row_major_klt0 )\n{\n    BOOST_UBLASX_DEBUG_TRACE( \"Test Case: Real - Square - Row Major - k < 0\" );\n\n    typedef double value_type;\n    typedef ublas::matrix<value_type,ublas::row_major> matrix_type;\n\n    const ::std::size_t n(4);\n\n    matrix_type A(n,n, value_type(1));\n\n\n    matrix_type X;\n    matrix_type E;\n\n    E = ublasx::triangular_matrix<value_type,ublas::lower>(n, n);\n    E(0,0) =\n    E(1,0) = E(1,1) =\n    E(2,0) = E(2,1) = E(2,2) =\n    E(3,0) = E(3,1) = E(3,2) = E(3,3) = value_type(1);\n\n    for (::std::size_t k = 0; k < n; ++k)\n    {\n        X = ublasx::tril(A, -static_cast< ::std::ptrdiff_t >(k));\n\n        for (::std::size_t i = k-1; k > 0 && i < n; ++i)\n        {\n            E(i,static_cast< ::std::ptrdiff_t >(i+1-k)) = value_type(0);\n        }\n\n        //BOOST_UBLASX_DEBUG_TRACE( \"E=\" << E );\n        BOOST_UBLASX_DEBUG_TRACE( \"tril(A,\" << -static_cast< ::std::ptrdiff_t >(k) << \")=\" << X );\n        BOOST_UBLASX_TEST_CHECK_MATRIX_CLOSE( X, E, n, n, tol );\n    }\n}\n\n\nBOOST_UBLASX_TEST_DEF( real_square_matrix_col_major_klt0 )\n{\n    BOOST_UBLASX_DEBUG_TRACE( \"Test Case: Real - Square - Column Major - k < 0\" );\n\n    typedef double value_type;\n    typedef ublas::matrix<value_type,ublas::column_major> matrix_type;\n\n    const ::std::size_t n(4);\n\n    matrix_type A(n,n, value_type(1));\n\n\n    matrix_type X;\n    matrix_type E;\n\n    E = ublasx::triangular_matrix<value_type,ublas::lower>(n, n);\n    E(0,0) =\n    E(1,0) = E(1,1) =\n    E(2,0) = E(2,1) = E(2,2) =\n    E(3,0) = E(3,1) = E(3,2) = E(3,3) = value_type(1);\n\n    for (::std::size_t k = 0; k < n; ++k)\n    {\n        X = ublasx::tril(A, -static_cast< ::std::ptrdiff_t >(k));\n\n        for (::std::size_t i = k-1; k > 0 && i < n; ++i)\n        {\n            E(i,static_cast< ::std::ptrdiff_t >(i+1-k)) = value_type(0);\n        }\n\n        //BOOST_UBLASX_DEBUG_TRACE( \"E=\" << E );\n        BOOST_UBLASX_DEBUG_TRACE( \"tril(A,\" << -static_cast< ::std::ptrdiff_t >(k) << \")=\" << X );\n        BOOST_UBLASX_TEST_CHECK_MATRIX_CLOSE( X, E, n, n, tol );\n    }\n}\n\n\nBOOST_UBLASX_TEST_DEF( real_horizontal_matrix_row_major_keq0 )\n{\n    BOOST_UBLASX_DEBUG_TRACE( \"Test Case: Real - Horizontal - Row Major - k == 0\" );\n\n    typedef double value_type;\n    typedef ublas::matrix<value_type,ublas::row_major> matrix_type;\n\n    const ::std::size_t nr(4);\n    const ::std::size_t nc(6);\n\n    matrix_type A(nr,nc, value_type(1));\n\n\n    matrix_type X;\n    matrix_type E;\n\n    X = ublasx::tril(A);\n    E = ublasx::triangular_matrix<value_type,ublas::lower>(nr,nc);\n    E(0,0) = \n    E(1,0) = E(1,1) =\n    E(2,0) = E(2,1) = E(2,2) =\n    E(3,0) = E(3,1) = E(3,2) = E(3,3) = value_type(1);\n\n    BOOST_UBLASX_DEBUG_TRACE( \"Input Matrix A=\" << A );\n    BOOST_UBLASX_DEBUG_TRACE( \"tril(A)=\" << X );\n    BOOST_UBLASX_TEST_CHECK_MATRIX_CLOSE( X, E, nr, nc, tol );\n}\n\n\nBOOST_UBLASX_TEST_DEF( real_horizontal_matrix_col_major_keq0 )\n{\n    BOOST_UBLASX_DEBUG_TRACE( \"Test Case: Real - Horizontal - Column Major - k == 0\" );\n\n    typedef double value_type;\n    typedef ublas::matrix<value_type,ublas::column_major> matrix_type;\n\n    const ::std::size_t nr(4);\n    const ::std::size_t nc(6);\n\n    matrix_type A(nr,nc, value_type(1));\n\n\n    matrix_type X;\n    matrix_type E;\n\n    X = ublasx::tril(A);\n    E = ublasx::triangular_matrix<value_type,ublas::lower>(nr,nc);\n    E(0,0) = \n    E(1,0) = E(1,1) =\n    E(2,0) = E(2,1) = E(2,2) =\n    E(3,0) = E(3,1) = E(3,2) = E(3,3) = value_type(1);\n\n    BOOST_UBLASX_DEBUG_TRACE( \"Input Matrix A=\" << A );\n    BOOST_UBLASX_DEBUG_TRACE( \"tril(A)=\" << X );\n    BOOST_UBLASX_TEST_CHECK_MATRIX_CLOSE( X, E, nr, nc, tol );\n}\n\n\nBOOST_UBLASX_TEST_DEF( real_horizontal_matrix_row_major_kgt0 )\n{\n    BOOST_UBLASX_DEBUG_TRACE( \"Test Case: Real - Horizontal - Row Major - k > 0\" );\n\n    typedef double value_type;\n    typedef ublas::matrix<value_type,ublas::row_major> matrix_type;\n\n    const ::std::size_t nr(4);\n    const ::std::size_t nc(6);\n\n    matrix_type A(nr,nc, value_type(1));\n\n\n    matrix_type X;\n    matrix_type E;\n\n    E = ublasx::scalar_matrix<value_type,ublas::lower>(nr,nc,value_type(1));\n\n    for (::std::ptrdiff_t k = nc-1; k >= 0; --k)\n    {\n        X = ublasx::tril(A, k);\n\n        for (::std::size_t i = 0; i < ::std::min(nr,static_cast< ::std::size_t >(::std::max(static_cast<int>(nc-k-1),0))); ++i)\n        {\n            E(i,i+k+1) = value_type(0);\n        }\n\n        //BOOST_UBLASX_DEBUG_TRACE( \"E=\" << E );\n        BOOST_UBLASX_DEBUG_TRACE( \"tril(A,\" << k << \")=\" << X );\n        BOOST_UBLASX_TEST_CHECK_MATRIX_CLOSE( X, E, nr, nc, tol );\n    }\n}\n\n\nBOOST_UBLASX_TEST_DEF( real_horizontal_matrix_col_major_kgt0 )\n{\n    BOOST_UBLASX_DEBUG_TRACE( \"Test Case: Real - Horizontal - Column Major - k > 0\" );\n\n    typedef double value_type;\n    typedef ublas::matrix<value_type,ublas::column_major> matrix_type;\n\n    const ::std::size_t nr(4);\n    const ::std::size_t nc(6);\n\n    matrix_type A(nr,nc, value_type(1));\n\n\n    matrix_type X;\n    matrix_type E;\n\n    E = ublasx::scalar_matrix<value_type,ublas::lower>(nr,nc,value_type(1));\n\n    for (::std::ptrdiff_t k = nc-1; k >= 0; --k)\n    {\n        X = ublasx::tril(A, k);\n\n        for (::std::size_t i = 0; i < ::std::min(nr,static_cast< ::std::size_t >(::std::max(static_cast<int>(nc-k-1),0))); ++i)\n        {\n            E(i,i+k+1) = value_type(0);\n        }\n\n        //BOOST_UBLASX_DEBUG_TRACE( \"E=\" << E );\n        BOOST_UBLASX_DEBUG_TRACE( \"tril(A,\" << k << \")=\" << X );\n        BOOST_UBLASX_TEST_CHECK_MATRIX_CLOSE( X, E, nr, nc, tol );\n    }\n}\n\n\nBOOST_UBLASX_TEST_DEF( real_horizontal_matrix_row_major_klt0 )\n{\n    BOOST_UBLASX_DEBUG_TRACE( \"Test Case: Real - Horizontal - Row Major - k < 0\" );\n\n    typedef double value_type;\n    typedef ublas::matrix<value_type,ublas::row_major> matrix_type;\n\n    const ::std::size_t nr(4);\n    const ::std::size_t nc(6);\n\n    matrix_type A(nr,nc, value_type(1));\n\n\n    matrix_type X;\n    matrix_type E;\n\n    E = ublasx::triangular_matrix<value_type,ublas::lower>(nr, nc);\n    E(0,0) =\n    E(1,0) = E(1,1) =\n    E(2,0) = E(2,1) = E(2,2) =\n    E(3,0) = E(3,1) = E(3,2) = E(3,3) = value_type(1);\n\n    for (::std::size_t k = 0; k < nr; ++k)\n    {\n        X = ublasx::tril(A, -static_cast< ::std::ptrdiff_t >(k));\n\n        for (::std::size_t i = k-1; k > 0 && i < nr; ++i)\n        {\n            E(i,static_cast< ::std::ptrdiff_t >(i+1-k)) = value_type(0);\n        }\n\n        //BOOST_UBLASX_DEBUG_TRACE( \"E=\" << E );\n        BOOST_UBLASX_DEBUG_TRACE( \"tril(A,\" << -static_cast< ::std::ptrdiff_t >(k) << \")=\" << X );\n        BOOST_UBLASX_TEST_CHECK_MATRIX_CLOSE( X, E, nr, nc, tol );\n    }\n}\n\n\nBOOST_UBLASX_TEST_DEF( real_horizontal_matrix_col_major_klt0 )\n{\n    BOOST_UBLASX_DEBUG_TRACE( \"Test Case: Real - Horizontal - Column Major - k < 0\" );\n\n    typedef double value_type;\n    typedef ublas::matrix<value_type,ublas::column_major> matrix_type;\n\n    const ::std::size_t nr(4);\n    const ::std::size_t nc(6);\n\n    matrix_type A(nr,nc, value_type(1));\n\n\n    matrix_type X;\n    matrix_type E;\n\n    E = ublasx::triangular_matrix<value_type,ublas::lower>(nr, nc);\n    E(0,0) =\n    E(1,0) = E(1,1) =\n    E(2,0) = E(2,1) = E(2,2) =\n    E(3,0) = E(3,1) = E(3,2) = E(3,3) = value_type(1);\n\n    for (::std::size_t k = 0; k < nr; ++k)\n    {\n        X = ublasx::tril(A, -static_cast< ::std::ptrdiff_t >(k));\n\n        for (::std::size_t i = k-1; k > 0 && i < nr; ++i)\n        {\n            E(i,static_cast< ::std::ptrdiff_t >(i+1-k)) = value_type(0);\n        }\n\n        //BOOST_UBLASX_DEBUG_TRACE( \"E=\" << E );\n        BOOST_UBLASX_DEBUG_TRACE( \"tril(A,\" << -static_cast< ::std::ptrdiff_t >(k) << \")=\" << X );\n        BOOST_UBLASX_TEST_CHECK_MATRIX_CLOSE( X, E, nr, nc, tol );\n    }\n}\n\n\nBOOST_UBLASX_TEST_DEF( real_vertical_matrix_row_major_keq0 )\n{\n    BOOST_UBLASX_DEBUG_TRACE( \"Test Case: Real - Vertical - Row Major - k == 0\" );\n\n    typedef double value_type;\n    typedef ublas::matrix<value_type,ublas::row_major> matrix_type;\n\n    const ::std::size_t nr(6);\n    const ::std::size_t nc(4);\n\n    matrix_type A(nr,nc, value_type(1));\n\n\n    matrix_type X;\n    matrix_type E;\n\n    X = ublasx::tril(A);\n    E = ublasx::triangular_matrix<value_type,ublas::lower>(nr,nc);\n    E(0,0) = \n    E(1,0) = E(1,1) =\n    E(2,0) = E(2,1) = E(2,2) =\n    E(3,0) = E(3,1) = E(3,2) = E(3,3) =\n    E(4,0) = E(4,1) = E(4,2) = E(4,3) =\n    E(5,0) = E(5,1) = E(5,2) = E(5,3) = value_type(1);\n\n    BOOST_UBLASX_DEBUG_TRACE( \"Input Matrix A=\" << A );\n    BOOST_UBLASX_DEBUG_TRACE( \"tril(A)=\" << X );\n    BOOST_UBLASX_TEST_CHECK_MATRIX_CLOSE( X, E, nr, nc, tol );\n}\n\n\nBOOST_UBLASX_TEST_DEF( real_vertical_matrix_col_major_keq0 )\n{\n    BOOST_UBLASX_DEBUG_TRACE( \"Test Case: Real - Vertical - Column Major - k == 0\" );\n\n    typedef double value_type;\n    typedef ublas::matrix<value_type,ublas::column_major> matrix_type;\n\n    const ::std::size_t nr(6);\n    const ::std::size_t nc(4);\n\n    matrix_type A(nr,nc, value_type(1));\n\n\n    matrix_type X;\n    matrix_type E;\n\n    X = ublasx::tril(A);\n    E = ublasx::triangular_matrix<value_type,ublas::lower>(nr,nc);\n    E(0,0) = \n    E(1,0) = E(1,1) =\n    E(2,0) = E(2,1) = E(2,2) =\n    E(3,0) = E(3,1) = E(3,2) = E(3,3) =\n    E(4,0) = E(4,1) = E(4,2) = E(4,3) =\n    E(5,0) = E(5,1) = E(5,2) = E(5,3) = value_type(1);\n\n    BOOST_UBLASX_DEBUG_TRACE( \"Input Matrix A=\" << A );\n    BOOST_UBLASX_DEBUG_TRACE( \"tril(A)=\" << X );\n    BOOST_UBLASX_TEST_CHECK_MATRIX_CLOSE( X, E, nr, nc, tol );\n}\n\n\nBOOST_UBLASX_TEST_DEF( real_vertical_matrix_row_major_kgt0 )\n{\n    BOOST_UBLASX_DEBUG_TRACE( \"Test Case: Real - Vertical - Row Major - k > 0\" );\n\n    typedef double value_type;\n    typedef ublas::matrix<value_type,ublas::row_major> matrix_type;\n\n    const ::std::size_t nr(6);\n    const ::std::size_t nc(4);\n\n    matrix_type A(nr,nc, value_type(1));\n\n\n    matrix_type X;\n    matrix_type E;\n\n    X = ublasx::tril(A);\n    E = ublasx::scalar_matrix<value_type,ublas::lower>(nr,nc,value_type(1));\n\n    for (::std::ptrdiff_t k = nc-1; k >= 0; --k)\n    {\n        X = ublasx::tril(A, k);\n\n        for (::std::size_t i = 0; i < ::std::min(nr,static_cast< ::std::size_t >(::std::max(static_cast<int>(nc-k-1),0))); ++i)\n        {\n            E(i,i+k+1) = value_type(0);\n        }\n\n        //BOOST_UBLASX_DEBUG_TRACE( \"E=\" << E );\n        BOOST_UBLASX_DEBUG_TRACE( \"tril(A,\" << k << \")=\" << X );\n        BOOST_UBLASX_TEST_CHECK_MATRIX_CLOSE( X, E, nr, nc, tol );\n    }\n}\n\n\nBOOST_UBLASX_TEST_DEF( real_vertical_matrix_col_major_kgt0 )\n{\n    BOOST_UBLASX_DEBUG_TRACE( \"Test Case: Real - Vertical - Column Major - k > 0\" );\n\n    typedef double value_type;\n    typedef ublas::matrix<value_type,ublas::column_major> matrix_type;\n\n    const ::std::size_t nr(6);\n    const ::std::size_t nc(4);\n\n    matrix_type A(nr,nc, value_type(1));\n\n\n    matrix_type X;\n    matrix_type E;\n\n    E = ublasx::scalar_matrix<value_type,ublas::lower>(nr,nc,value_type(1));\n\n    for (::std::ptrdiff_t k = nc-1; k >= 0; --k)\n    {\n        X = ublasx::tril(A, k);\n\n        for (::std::size_t i = 0; i < ::std::min(nr,static_cast< ::std::size_t >(::std::max(static_cast<int>(nc-k-1),0))); ++i)\n        {\n            E(i,i+k+1) = value_type(0);\n        }\n\n        //BOOST_UBLASX_DEBUG_TRACE( \"E=\" << E );\n        BOOST_UBLASX_DEBUG_TRACE( \"tril(A,\" << k << \")=\" << X );\n        BOOST_UBLASX_TEST_CHECK_MATRIX_CLOSE( X, E, nr, nc, tol );\n    }\n}\n\n\nBOOST_UBLASX_TEST_DEF( real_vertical_matrix_row_major_klt0 )\n{\n    BOOST_UBLASX_DEBUG_TRACE( \"Test Case: Real - Vertical - Row Major - k < 0\" );\n\n    typedef double value_type;\n    typedef ublas::matrix<value_type,ublas::row_major> matrix_type;\n\n    const ::std::size_t nr(6);\n    const ::std::size_t nc(4);\n\n    matrix_type A(nr,nc, value_type(1));\n\n\n    matrix_type X;\n    matrix_type E;\n\n    E = ublasx::triangular_matrix<value_type,ublas::lower>(nr, nc);\n    E(0,0) =\n    E(1,0) = E(1,1) =\n    E(2,0) = E(2,1) = E(2,2) =\n    E(3,0) = E(3,1) = E(3,2) = E(3,3) =\n    E(4,0) = E(4,1) = E(4,2) = E(4,3) =\n    E(5,0) = E(5,1) = E(5,2) = E(5,3) = value_type(1);\n\n    for (::std::size_t k = 0; k < nr; ++k)\n    {\n        X = ublasx::tril(A, -static_cast< ::std::ptrdiff_t >(k));\n\n        for (::std::size_t i = k-1; k > 0 && i < ::std::min(nr,nc+k-1); ++i)\n        {\n            E(i,i+1-k) = value_type(0);\n        }\n\n        //BOOST_UBLASX_DEBUG_TRACE( \"E=\" << E );\n        BOOST_UBLASX_DEBUG_TRACE( \"tril(A,\" << -static_cast< ::std::ptrdiff_t >(k) << \")=\" << X );\n        BOOST_UBLASX_TEST_CHECK_MATRIX_CLOSE( X, E, nr, nc, tol );\n    }\n}\n\n\nBOOST_UBLASX_TEST_DEF( real_vertical_matrix_col_major_klt0 )\n{\n    BOOST_UBLASX_DEBUG_TRACE( \"Test Case: Real - Vertical - Column Major - k < 0\" );\n\n    typedef double value_type;\n    typedef ublas::matrix<value_type,ublas::column_major> matrix_type;\n\n    const ::std::size_t nr(6);\n    const ::std::size_t nc(4);\n\n    matrix_type A(nr,nc, value_type(1));\n\n\n    matrix_type X;\n    matrix_type E;\n\n    E = ublasx::triangular_matrix<value_type,ublas::lower>(nr, nc);\n    E(0,0) =\n    E(1,0) = E(1,1) =\n    E(2,0) = E(2,1) = E(2,2) =\n    E(3,0) = E(3,1) = E(3,2) = E(3,3) =\n    E(4,0) = E(4,1) = E(4,2) = E(4,3) =\n    E(5,0) = E(5,1) = E(5,2) = E(5,3) = value_type(1);\n\n    for (::std::size_t k = 0; k < nr; ++k)\n    {\n        X = ublasx::tril(A, -static_cast< ::std::ptrdiff_t >(k));\n\n        for (::std::size_t i = k-1; k > 0 && i < ::std::min(nr,nc+k-1); ++i)\n        {\n            E(i,i+1-k) = value_type(0);\n        }\n\n        //BOOST_UBLASX_DEBUG_TRACE( \"E=\" << E );\n        BOOST_UBLASX_DEBUG_TRACE( \"tril(A,\" << -static_cast< ::std::ptrdiff_t >(k) << \")=\" << X );\n        BOOST_UBLASX_TEST_CHECK_MATRIX_CLOSE( X, E, nr, nc, tol );\n    }\n}\n\n\nBOOST_UBLASX_TEST_DEF( complex_square_matrix_row_major_keq0 )\n{\n    BOOST_UBLASX_DEBUG_TRACE( \"Test Case: Complex - Square - Row Major - k == 0\" );\n\n    typedef double real_type;\n    typedef ::std::complex<real_type> value_type;\n    typedef ublas::matrix<value_type,ublas::row_major> matrix_type;\n\n    const ::std::size_t n(4);\n\n    matrix_type A(n,n, value_type(1));\n\n\n    matrix_type X;\n    matrix_type E;\n\n    X = ublasx::tril(A);\n    E = ublasx::triangular_matrix<value_type,ublas::lower>(n,n);\n    E(0,0) = \n    E(1,0) = E(1,1) =\n    E(2,0) = E(2,1) = E(2,2) =\n    E(3,0) = E(3,1) = E(3,2) = E(3,3) = value_type(1);\n\n    BOOST_UBLASX_DEBUG_TRACE( \"Input Matrix A=\" << A );\n    //BOOST_UBLASX_DEBUG_TRACE( \"E=\" << E );\n    BOOST_UBLASX_DEBUG_TRACE( \"tril(A)=\" << X );\n    BOOST_UBLASX_TEST_CHECK_MATRIX_CLOSE( X, E, n, n, tol );\n}\n\n\nBOOST_UBLASX_TEST_DEF( complex_square_matrix_col_major_keq0 )\n{\n    BOOST_UBLASX_DEBUG_TRACE( \"Test Case: Complex - Square - Column Major - k == 0\" );\n\n    typedef double real_type;\n    typedef ::std::complex<real_type> value_type;\n    typedef ublas::matrix<value_type,ublas::column_major> matrix_type;\n\n    const ::std::size_t n(4);\n\n    matrix_type A(n,n, value_type(1));\n\n\n    matrix_type X;\n    matrix_type E;\n\n    X = ublasx::tril(A);\n    E = ublasx::triangular_matrix<value_type,ublas::lower>(n,n);\n    E(0,0) = \n    E(1,0) = E(1,1) =\n    E(2,0) = E(2,1) = E(2,2) =\n    E(3,0) = E(3,1) = E(3,2) = E(3,3) = value_type(1);\n\n    BOOST_UBLASX_DEBUG_TRACE( \"Input Matrix A=\" << A );\n    //BOOST_UBLASX_DEBUG_TRACE( \"E=\" << E );\n    BOOST_UBLASX_DEBUG_TRACE( \"tril(A)=\" << X );\n    BOOST_UBLASX_TEST_CHECK_MATRIX_CLOSE( X, E, n, n, tol );\n}\n\n\nBOOST_UBLASX_TEST_DEF( complex_square_matrix_row_major_kgt0 )\n{\n    BOOST_UBLASX_DEBUG_TRACE( \"Test Case: Complex - Square - Row Major - k > 0\" );\n\n    typedef double real_type;\n    typedef ::std::complex<real_type> value_type;\n    typedef ublas::matrix<value_type,ublas::row_major> matrix_type;\n\n    const ::std::size_t n(4);\n\n    matrix_type A(n,n, value_type(1));\n\n\n    matrix_type X;\n    matrix_type E;\n\n    E = ublasx::scalar_matrix<value_type,ublas::lower>(n,n,value_type(1));\n\n    for (::std::ptrdiff_t k = n-1; k >= 0; --k)\n    {\n        X = ublasx::tril(A, k);\n\n        for (::std::size_t i = 0; i < (n-k-1); ++i)\n        {\n            E(i,i+k+1) = value_type(0);\n        }\n\n        //BOOST_UBLASX_DEBUG_TRACE( \"E=\" << E );\n        BOOST_UBLASX_DEBUG_TRACE( \"tril(A,\" << k << \")=\" << X );\n        BOOST_UBLASX_TEST_CHECK_MATRIX_CLOSE( X, E, n, n, tol );\n    }\n}\n\n\nBOOST_UBLASX_TEST_DEF( complex_square_matrix_col_major_kgt0 )\n{\n    BOOST_UBLASX_DEBUG_TRACE( \"Test Case: Complex - Square - Column Major - k > 0\" );\n\n    typedef double real_type;\n    typedef ::std::complex<real_type> value_type;\n    typedef ublas::matrix<value_type,ublas::column_major> matrix_type;\n\n    const ::std::size_t n(4);\n\n    matrix_type A(n,n, value_type(1));\n\n\n    matrix_type X;\n    matrix_type E;\n\n    E = ublasx::scalar_matrix<value_type,ublas::lower>(n,n,value_type(1));\n\n    for (::std::ptrdiff_t k = n-1; k >= 0; --k)\n    {\n        X = ublasx::tril(A, k);\n\n        for (::std::size_t i = 0; i < (n-k-1); ++i)\n        {\n            E(i,i+k+1) = value_type(0);\n        }\n\n        ////BOOST_UBLASX_DEBUG_TRACE( \"E=\" << E );\n        BOOST_UBLASX_DEBUG_TRACE( \"tril(A,\" << k << \")=\" << X );\n        BOOST_UBLASX_TEST_CHECK_MATRIX_CLOSE( X, E, n, n, tol );\n    }\n}\n\n\nBOOST_UBLASX_TEST_DEF( complex_square_matrix_row_major_klt0 )\n{\n    BOOST_UBLASX_DEBUG_TRACE( \"Test Case: Complex - Square - Row Major - k < 0\" );\n\n    typedef double real_type;\n    typedef ::std::complex<real_type> value_type;\n    typedef ublas::matrix<value_type,ublas::row_major> matrix_type;\n\n    const ::std::size_t n(4);\n\n    matrix_type A(n,n, value_type(1));\n\n\n    matrix_type X;\n    matrix_type E;\n\n    E = ublasx::triangular_matrix<value_type,ublas::lower>(n, n);\n    E(0,0) =\n    E(1,0) = E(1,1) =\n    E(2,0) = E(2,1) = E(2,2) =\n    E(3,0) = E(3,1) = E(3,2) = E(3,3) = value_type(1);\n\n    for (::std::size_t k = 0; k < n; ++k)\n    {\n        X = ublasx::tril(A, -static_cast< ::std::ptrdiff_t >(k));\n\n        for (::std::size_t i = k-1; k > 0 && i < n; ++i)\n        {\n            E(i,static_cast< ::std::ptrdiff_t >(i+1-k)) = value_type(0);\n        }\n\n        //BOOST_UBLASX_DEBUG_TRACE( \"E=\" << E );\n        BOOST_UBLASX_DEBUG_TRACE( \"tril(A,\" << -static_cast< ::std::ptrdiff_t >(k) << \")=\" << X );\n        BOOST_UBLASX_TEST_CHECK_MATRIX_CLOSE( X, E, n, n, tol );\n    }\n}\n\n\nBOOST_UBLASX_TEST_DEF( complex_square_matrix_col_major_klt0 )\n{\n    BOOST_UBLASX_DEBUG_TRACE( \"Test Case: Complex - Square - Column Major - k < 0\" );\n\n    typedef double real_type;\n    typedef ::std::complex<real_type> value_type;\n    typedef ublas::matrix<value_type,ublas::column_major> matrix_type;\n\n    const ::std::size_t n(4);\n\n    matrix_type A(n,n, value_type(1));\n\n\n    matrix_type X;\n    matrix_type E;\n\n    E = ublasx::triangular_matrix<value_type,ublas::lower>(n, n);\n    E(0,0) =\n    E(1,0) = E(1,1) =\n    E(2,0) = E(2,1) = E(2,2) =\n    E(3,0) = E(3,1) = E(3,2) = E(3,3) = value_type(1);\n\n    for (::std::size_t k = 0; k < n; ++k)\n    {\n        X = ublasx::tril(A, -static_cast< ::std::ptrdiff_t >(k));\n\n        for (::std::size_t i = k-1; k > 0 && i < n; ++i)\n        {\n            E(i,static_cast< ::std::ptrdiff_t >(i+1-k)) = value_type(0);\n        }\n\n        ////BOOST_UBLASX_DEBUG_TRACE( \"E=\" << E );\n        BOOST_UBLASX_DEBUG_TRACE( \"tril(A,\" << -static_cast< ::std::ptrdiff_t >(k) << \")=\" << X );\n        BOOST_UBLASX_TEST_CHECK_MATRIX_CLOSE( X, E, n, n, tol );\n    }\n}\n\n\nBOOST_UBLASX_TEST_DEF( complex_horizontal_matrix_row_major_keq0 )\n{\n    BOOST_UBLASX_DEBUG_TRACE( \"Test Case: Complex - Horizontal - Row Major - k == 0\" );\n\n    typedef double real_type;\n    typedef ::std::complex<real_type> value_type;\n    typedef ublas::matrix<value_type,ublas::row_major> matrix_type;\n\n    const ::std::size_t nr(4);\n    const ::std::size_t nc(6);\n\n    matrix_type A(nr,nc, value_type(1));\n\n\n    matrix_type X;\n    matrix_type E;\n\n    X = ublasx::tril(A);\n    E = ublasx::triangular_matrix<value_type,ublas::lower>(nr,nc);\n    E(0,0) = \n    E(1,0) = E(1,1) =\n    E(2,0) = E(2,1) = E(2,2) =\n    E(3,0) = E(3,1) = E(3,2) = E(3,3) = value_type(1);\n\n    BOOST_UBLASX_DEBUG_TRACE( \"Input Matrix A=\" << A );\n    BOOST_UBLASX_DEBUG_TRACE( \"tril(A)=\" << X );\n    BOOST_UBLASX_TEST_CHECK_MATRIX_CLOSE( X, E, nr, nc, tol );\n}\n\n\nBOOST_UBLASX_TEST_DEF( complex_horizontal_matrix_col_major_keq0 )\n{\n    BOOST_UBLASX_DEBUG_TRACE( \"Test Case: Complex - Horizontal - Column Major - k == 0\" );\n\n    typedef double real_type;\n    typedef ::std::complex<real_type> value_type;\n    typedef ublas::matrix<value_type,ublas::column_major> matrix_type;\n\n    const ::std::size_t nr(4);\n    const ::std::size_t nc(6);\n\n    matrix_type A(nr,nc, value_type(1));\n\n\n    matrix_type X;\n    matrix_type E;\n\n    X = ublasx::tril(A);\n    E = ublasx::triangular_matrix<value_type,ublas::lower>(nr,nc);\n    E(0,0) = \n    E(1,0) = E(1,1) =\n    E(2,0) = E(2,1) = E(2,2) =\n    E(3,0) = E(3,1) = E(3,2) = E(3,3) = value_type(1);\n\n    BOOST_UBLASX_DEBUG_TRACE( \"Input Matrix A=\" << A );\n    BOOST_UBLASX_DEBUG_TRACE( \"tril(A)=\" << X );\n    BOOST_UBLASX_TEST_CHECK_MATRIX_CLOSE( X, E, nr, nc, tol );\n}\n\n\nBOOST_UBLASX_TEST_DEF( complex_horizontal_matrix_row_major_kgt0 )\n{\n    BOOST_UBLASX_DEBUG_TRACE( \"Test Case: Complex - Horizontal - Row Major - k > 0\" );\n\n    typedef double real_type;\n    typedef ::std::complex<real_type> value_type;\n    typedef ublas::matrix<value_type,ublas::row_major> matrix_type;\n\n    const ::std::size_t nr(4);\n    const ::std::size_t nc(6);\n\n    matrix_type A(nr,nc, value_type(1));\n\n\n    matrix_type X;\n    matrix_type E;\n\n    E = ublasx::scalar_matrix<value_type,ublas::lower>(nr,nc,value_type(1));\n\n    for (::std::ptrdiff_t k = nc-1; k >= 0; --k)\n    {\n        X = ublasx::tril(A, k);\n\n        for (::std::size_t i = 0; i < ::std::min(nr,static_cast< ::std::size_t >(::std::max(static_cast<int>(nc-k-1),0))); ++i)\n        {\n            E(i,i+k+1) = value_type(0);\n        }\n\n        //BOOST_UBLASX_DEBUG_TRACE( \"E=\" << E );\n        BOOST_UBLASX_DEBUG_TRACE( \"tril(A,\" << k << \")=\" << X );\n        BOOST_UBLASX_TEST_CHECK_MATRIX_CLOSE( X, E, nr, nc, tol );\n    }\n}\n\n\nBOOST_UBLASX_TEST_DEF( complex_horizontal_matrix_col_major_kgt0 )\n{\n    BOOST_UBLASX_DEBUG_TRACE( \"Test Case: Complex - Horizontal - Column Major - k > 0\" );\n\n    typedef double real_type;\n    typedef ::std::complex<real_type> value_type;\n    typedef ublas::matrix<value_type,ublas::column_major> matrix_type;\n\n    const ::std::size_t nr(4);\n    const ::std::size_t nc(6);\n\n    matrix_type A(nr,nc, value_type(1));\n\n\n    matrix_type X;\n    matrix_type E;\n\n    E = ublasx::scalar_matrix<value_type,ublas::lower>(nr,nc,value_type(1));\n\n    for (::std::ptrdiff_t k = nc-1; k >= 0; --k)\n    {\n        X = ublasx::tril(A, k);\n\n        for (::std::size_t i = 0; i < ::std::min(nr,static_cast< ::std::size_t >(::std::max(static_cast<int>(nc-k-1),0))); ++i)\n        {\n            E(i,i+k+1) = value_type(0);\n        }\n\n        //BOOST_UBLASX_DEBUG_TRACE( \"E=\" << E );\n        BOOST_UBLASX_DEBUG_TRACE( \"tril(A,\" << k << \")=\" << X );\n        BOOST_UBLASX_TEST_CHECK_MATRIX_CLOSE( X, E, nr, nc, tol );\n    }\n}\n\n\nBOOST_UBLASX_TEST_DEF( complex_horizontal_matrix_row_major_klt0 )\n{\n    BOOST_UBLASX_DEBUG_TRACE( \"Test Case: Complex - Horizontal - Row Major - k < 0\" );\n\n    typedef double real_type;\n    typedef ::std::complex<real_type> value_type;\n    typedef ublas::matrix<value_type,ublas::row_major> matrix_type;\n\n    const ::std::size_t nr(4);\n    const ::std::size_t nc(6);\n\n    matrix_type A(nr,nc, value_type(1));\n\n\n    matrix_type X;\n    matrix_type E;\n\n    E = ublasx::triangular_matrix<value_type,ublas::lower>(nr, nc);\n    E(0,0) =\n    E(1,0) = E(1,1) =\n    E(2,0) = E(2,1) = E(2,2) =\n    E(3,0) = E(3,1) = E(3,2) = E(3,3) = value_type(1);\n\n    for (::std::size_t k = 0; k < nr; ++k)\n    {\n        X = ublasx::tril(A, -static_cast< ::std::ptrdiff_t >(k));\n\n        for (::std::size_t i = k-1; k > 0 && i < nr; ++i)\n        {\n            E(i,static_cast< ::std::ptrdiff_t >(i+1-k)) = value_type(0);\n        }\n\n        ////BOOST_UBLASX_DEBUG_TRACE( \"E=\" << E );\n        BOOST_UBLASX_DEBUG_TRACE( \"tril(A,\" << -static_cast< ::std::ptrdiff_t >(k) << \")=\" << X );\n        BOOST_UBLASX_TEST_CHECK_MATRIX_CLOSE( X, E, nr, nc, tol );\n    }\n}\n\n\nBOOST_UBLASX_TEST_DEF( complex_horizontal_matrix_col_major_klt0 )\n{\n    BOOST_UBLASX_DEBUG_TRACE( \"Test Case: Complex - Horizontal - Column Major - k < 0\" );\n\n    typedef double real_type;\n    typedef ::std::complex<real_type> value_type;\n    typedef ublas::matrix<value_type,ublas::column_major> matrix_type;\n\n    const ::std::size_t nr(4);\n    const ::std::size_t nc(6);\n\n    matrix_type A(nr,nc, value_type(1));\n\n\n    matrix_type X;\n    matrix_type E;\n\n    E = ublasx::triangular_matrix<value_type,ublas::lower>(nr, nc);\n    E(0,0) =\n    E(1,0) = E(1,1) =\n    E(2,0) = E(2,1) = E(2,2) =\n    E(3,0) = E(3,1) = E(3,2) = E(3,3) = value_type(1);\n\n    for (::std::size_t k = 0; k < nr; ++k)\n    {\n        X = ublasx::tril(A, -static_cast< ::std::ptrdiff_t >(k));\n\n        for (::std::size_t i = k-1; k > 0 && i < nr; ++i)\n        {\n            E(i,static_cast< ::std::ptrdiff_t >(i+1-k)) = value_type(0);\n        }\n\n        //BOOST_UBLASX_DEBUG_TRACE( \"E=\" << E );\n        BOOST_UBLASX_DEBUG_TRACE( \"tril(A,\" << -static_cast< ::std::ptrdiff_t >(k) << \")=\" << X );\n        BOOST_UBLASX_TEST_CHECK_MATRIX_CLOSE( X, E, nr, nc, tol );\n    }\n}\n\n\nBOOST_UBLASX_TEST_DEF( complex_vertical_matrix_row_major_keq0 )\n{\n    BOOST_UBLASX_DEBUG_TRACE( \"Test Case: Complex - Vertical - Row Major - k == 0\" );\n\n    typedef double real_type;\n    typedef ::std::complex<real_type> value_type;\n    typedef ublas::matrix<value_type,ublas::row_major> matrix_type;\n\n    const ::std::size_t nr(6);\n    const ::std::size_t nc(4);\n\n    matrix_type A(nr,nc, value_type(1));\n\n\n    matrix_type X;\n    matrix_type E;\n\n    X = ublasx::tril(A);\n    E = ublasx::triangular_matrix<value_type,ublas::lower>(nr,nc);\n    E(0,0) = \n    E(1,0) = E(1,1) =\n    E(2,0) = E(2,1) = E(2,2) =\n    E(3,0) = E(3,1) = E(3,2) = E(3,3) =\n    E(4,0) = E(4,1) = E(4,2) = E(4,3) =\n    E(5,0) = E(5,1) = E(5,2) = E(5,3) = value_type(1);\n\n    BOOST_UBLASX_DEBUG_TRACE( \"Input Matrix A=\" << A );\n    BOOST_UBLASX_DEBUG_TRACE( \"tril(A)=\" << X );\n    BOOST_UBLASX_TEST_CHECK_MATRIX_CLOSE( X, E, nr, nc, tol );\n}\n\n\nBOOST_UBLASX_TEST_DEF( complex_vertical_matrix_col_major_keq0 )\n{\n    BOOST_UBLASX_DEBUG_TRACE( \"Test Case: Complex - Vertical - Column Major - k == 0\" );\n\n    typedef double real_type;\n    typedef ::std::complex<real_type> value_type;\n    typedef ublas::matrix<value_type,ublas::column_major> matrix_type;\n\n    const ::std::size_t nr(6);\n    const ::std::size_t nc(4);\n\n    matrix_type A(nr,nc, value_type(1));\n\n\n    matrix_type X;\n    matrix_type E;\n\n    X = ublasx::tril(A);\n    E = ublasx::triangular_matrix<value_type,ublas::lower>(nr,nc);\n    E(0,0) = \n    E(1,0) = E(1,1) =\n    E(2,0) = E(2,1) = E(2,2) =\n    E(3,0) = E(3,1) = E(3,2) = E(3,3) =\n    E(4,0) = E(4,1) = E(4,2) = E(4,3) =\n    E(5,0) = E(5,1) = E(5,2) = E(5,3) = value_type(1);\n\n    BOOST_UBLASX_DEBUG_TRACE( \"Input Matrix A=\" << A );\n    BOOST_UBLASX_DEBUG_TRACE( \"tril(A)=\" << X );\n    BOOST_UBLASX_TEST_CHECK_MATRIX_CLOSE( X, E, nr, nc, tol );\n}\n\n\nBOOST_UBLASX_TEST_DEF( complex_vertical_matrix_row_major_kgt0 )\n{\n    BOOST_UBLASX_DEBUG_TRACE( \"Test Case: Complex - Vertical - Row Major - k > 0\" );\n\n    typedef double real_type;\n    typedef ::std::complex<real_type> value_type;\n    typedef ublas::matrix<value_type,ublas::row_major> matrix_type;\n\n    const ::std::size_t nr(6);\n    const ::std::size_t nc(4);\n\n    matrix_type A(nr,nc, value_type(1));\n\n\n    matrix_type X;\n    matrix_type E;\n\n    X = ublasx::tril(A);\n    E = ublasx::scalar_matrix<value_type,ublas::lower>(nr,nc,value_type(1));\n\n    for (::std::ptrdiff_t k = nc-1; k >= 0; --k)\n    {\n        X = ublasx::tril(A, k);\n\n        for (::std::size_t i = 0; i < ::std::min(nr,static_cast< ::std::size_t >(::std::max(static_cast<int>(nc-k-1),0))); ++i)\n        {\n            E(i,i+k+1) = value_type(0);\n        }\n\n        //BOOST_UBLASX_DEBUG_TRACE( \"E=\" << E );\n        BOOST_UBLASX_DEBUG_TRACE( \"tril(A,\" << k << \")=\" << X );\n        BOOST_UBLASX_TEST_CHECK_MATRIX_CLOSE( X, E, nr, nc, tol );\n    }\n}\n\n\nBOOST_UBLASX_TEST_DEF( complex_vertical_matrix_col_major_kgt0 )\n{\n    BOOST_UBLASX_DEBUG_TRACE( \"Test Case: Complex - Vertical - Column Major - k > 0\" );\n\n    typedef double real_type;\n    typedef ::std::complex<real_type> value_type;\n    typedef ublas::matrix<value_type,ublas::column_major> matrix_type;\n\n    const ::std::size_t nr(6);\n    const ::std::size_t nc(4);\n\n    matrix_type A(nr,nc, value_type(1));\n\n\n    matrix_type X;\n    matrix_type E;\n\n    E = ublasx::scalar_matrix<value_type,ublas::lower>(nr,nc,value_type(1));\n\n    for (::std::ptrdiff_t k = nc-1; k >= 0; --k)\n    {\n        X = ublasx::tril(A, k);\n\n        for (::std::size_t i = 0; i < ::std::min(nr,static_cast< ::std::size_t >(::std::max(static_cast<int>(nc-k-1),0))); ++i)\n        {\n            E(i,i+k+1) = value_type(0);\n        }\n\n        //BOOST_UBLASX_DEBUG_TRACE( \"E=\" << E );\n        BOOST_UBLASX_DEBUG_TRACE( \"tril(A,\" << k << \")=\" << X );\n        BOOST_UBLASX_TEST_CHECK_MATRIX_CLOSE( X, E, nr, nc, tol );\n    }\n}\n\n\nBOOST_UBLASX_TEST_DEF( complex_vertical_matrix_row_major_klt0 )\n{\n    BOOST_UBLASX_DEBUG_TRACE( \"Test Case: Complex - Vertical - Row Major - k < 0\" );\n\n    typedef double real_type;\n    typedef ::std::complex<real_type> value_type;\n    typedef ublas::matrix<value_type,ublas::row_major> matrix_type;\n\n    const ::std::size_t nr(6);\n    const ::std::size_t nc(4);\n\n    matrix_type A(nr,nc, value_type(1));\n\n\n    matrix_type X;\n    matrix_type E;\n\n    E = ublasx::triangular_matrix<value_type,ublas::lower>(nr, nc);\n    E(0,0) =\n    E(1,0) = E(1,1) =\n    E(2,0) = E(2,1) = E(2,2) =\n    E(3,0) = E(3,1) = E(3,2) = E(3,3) =\n    E(4,0) = E(4,1) = E(4,2) = E(4,3) =\n    E(5,0) = E(5,1) = E(5,2) = E(5,3) = value_type(1);\n\n    for (::std::size_t k = 0; k < nr; ++k)\n    {\n        X = ublasx::tril(A, -static_cast< ::std::ptrdiff_t >(k));\n\n        for (::std::size_t i = k-1; k > 0 && i < ::std::min(nr,nc+k-1); ++i)\n        {\n            E(i,i+1-k) = value_type(0);\n        }\n\n        //BOOST_UBLASX_DEBUG_TRACE( \"E=\" << E );\n        BOOST_UBLASX_DEBUG_TRACE( \"tril(A,\" << -static_cast< ::std::ptrdiff_t >(k) << \")=\" << X );\n        BOOST_UBLASX_TEST_CHECK_MATRIX_CLOSE( X, E, nr, nc, tol );\n    }\n}\n\n\nBOOST_UBLASX_TEST_DEF( complex_vertical_matrix_col_major_klt0 )\n{\n    BOOST_UBLASX_DEBUG_TRACE( \"Test Case: Complex - Vertical - Column Major - k < 0\" );\n\n    typedef double real_type;\n    typedef ::std::complex<real_type> value_type;\n    typedef ublas::matrix<value_type,ublas::column_major> matrix_type;\n\n    const ::std::size_t nr(6);\n    const ::std::size_t nc(4);\n\n    matrix_type A(nr,nc, value_type(1));\n\n\n    matrix_type X;\n    matrix_type E;\n\n    E = ublasx::triangular_matrix<value_type,ublas::lower>(nr, nc);\n    E(0,0) =\n    E(1,0) = E(1,1) =\n    E(2,0) = E(2,1) = E(2,2) =\n    E(3,0) = E(3,1) = E(3,2) = E(3,3) =\n    E(4,0) = E(4,1) = E(4,2) = E(4,3) =\n    E(5,0) = E(5,1) = E(5,2) = E(5,3) = value_type(1);\n\n    for (::std::size_t k = 0; k < nr; ++k)\n    {\n        X = ublasx::tril(A, -static_cast< ::std::ptrdiff_t >(k));\n\n        for (::std::size_t i = k-1; k > 0 && i < ::std::min(nr,nc+k-1); ++i)\n        {\n            E(i,i+1-k) = value_type(0);\n        }\n\n        //BOOST_UBLASX_DEBUG_TRACE( \"E=\" << E );\n        BOOST_UBLASX_DEBUG_TRACE( \"tril(A,\" << -static_cast< ::std::ptrdiff_t >(k) << \")=\" << X );\n        BOOST_UBLASX_TEST_CHECK_MATRIX_CLOSE( X, E, nr, nc, tol );\n    }\n}\n\n\nint main()\n{\n    BOOST_UBLASX_TEST_BEGIN();\n\n    BOOST_UBLASX_TEST_DO( real_square_matrix_row_major_keq0 );\n    BOOST_UBLASX_TEST_DO( real_square_matrix_col_major_keq0 );\n    BOOST_UBLASX_TEST_DO( real_square_matrix_row_major_kgt0 );\n    BOOST_UBLASX_TEST_DO( real_square_matrix_col_major_kgt0 );\n    BOOST_UBLASX_TEST_DO( real_square_matrix_row_major_klt0 );\n    BOOST_UBLASX_TEST_DO( real_square_matrix_col_major_klt0 );\n\n    BOOST_UBLASX_TEST_DO( real_horizontal_matrix_row_major_keq0 );\n    BOOST_UBLASX_TEST_DO( real_horizontal_matrix_col_major_keq0 );\n    BOOST_UBLASX_TEST_DO( real_horizontal_matrix_row_major_kgt0 );\n    BOOST_UBLASX_TEST_DO( real_horizontal_matrix_col_major_kgt0 );\n    BOOST_UBLASX_TEST_DO( real_horizontal_matrix_row_major_klt0 );\n    BOOST_UBLASX_TEST_DO( real_horizontal_matrix_col_major_klt0 );\n\n    BOOST_UBLASX_TEST_DO( real_vertical_matrix_row_major_keq0 );\n    BOOST_UBLASX_TEST_DO( real_vertical_matrix_col_major_keq0 );\n    BOOST_UBLASX_TEST_DO( real_vertical_matrix_row_major_kgt0 );\n    BOOST_UBLASX_TEST_DO( real_vertical_matrix_col_major_kgt0 );\n    BOOST_UBLASX_TEST_DO( real_vertical_matrix_row_major_klt0 );\n    BOOST_UBLASX_TEST_DO( real_vertical_matrix_col_major_klt0 );\n\n    BOOST_UBLASX_TEST_DO( complex_square_matrix_col_major_keq0 );\n    BOOST_UBLASX_TEST_DO( complex_square_matrix_row_major_keq0 );\n    BOOST_UBLASX_TEST_DO( complex_square_matrix_col_major_kgt0 );\n    BOOST_UBLASX_TEST_DO( complex_square_matrix_row_major_kgt0 );\n    BOOST_UBLASX_TEST_DO( complex_square_matrix_row_major_klt0 );\n    BOOST_UBLASX_TEST_DO( complex_square_matrix_col_major_klt0 );\n\n    BOOST_UBLASX_TEST_DO( complex_horizontal_matrix_row_major_keq0 );\n    BOOST_UBLASX_TEST_DO( complex_horizontal_matrix_col_major_keq0 );\n    BOOST_UBLASX_TEST_DO( complex_horizontal_matrix_row_major_kgt0 );\n    BOOST_UBLASX_TEST_DO( complex_horizontal_matrix_col_major_kgt0 );\n    BOOST_UBLASX_TEST_DO( complex_horizontal_matrix_row_major_klt0 );\n    BOOST_UBLASX_TEST_DO( complex_horizontal_matrix_col_major_klt0 );\n\n    BOOST_UBLASX_TEST_DO( complex_vertical_matrix_row_major_keq0 );\n    BOOST_UBLASX_TEST_DO( complex_vertical_matrix_col_major_keq0 );\n    BOOST_UBLASX_TEST_DO( complex_vertical_matrix_row_major_kgt0 );\n    BOOST_UBLASX_TEST_DO( complex_vertical_matrix_col_major_kgt0 );\n    BOOST_UBLASX_TEST_DO( complex_vertical_matrix_row_major_klt0 );\n    BOOST_UBLASX_TEST_DO( complex_vertical_matrix_col_major_klt0 );\n\n    BOOST_UBLASX_TEST_END();\n}\n", "meta": {"hexsha": "071cb23d9a1e8205de8ba385718628e1b86b8a2c", "size": 37989, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/ublasx/test/tril.cpp", "max_stars_repo_name": "sguazt/boost-ublasx", "max_stars_repo_head_hexsha": "21c9b393d33a6ec2a8071ba8d48680073d766409", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2016-05-14T11:08:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-05T14:22:20.000Z", "max_issues_repo_path": "libs/numeric/ublasx/test/tril.cpp", "max_issues_repo_name": "sguazt/boost-ublasx", "max_issues_repo_head_hexsha": "21c9b393d33a6ec2a8071ba8d48680073d766409", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-12-28T18:36:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-06T11:28:51.000Z", "max_forks_repo_path": "libs/numeric/ublasx/test/tril.cpp", "max_forks_repo_name": "sguazt/boost-ublasx", "max_forks_repo_head_hexsha": "21c9b393d33a6ec2a8071ba8d48680073d766409", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-12-23T02:53:27.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-23T02:53:27.000Z", "avg_line_length": 28.6925981873, "max_line_length": 127, "alphanum_fraction": 0.60322725, "num_tokens": 13139, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.6959583124210896, "lm_q1q2_score": 0.4679148347480196}}
{"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    testRegularImplicitSchurFactor.cpp\n * @brief   unit test implicit jacobian factors\n * @author  Frank Dellaert\n * @date    Oct 20, 2013\n */\n\n#include <gtsam/slam/JacobianFactorQ.h>\n#include <gtsam/slam/JacobianFactorQR.h>\n#include <gtsam/slam/RegularImplicitSchurFactor.h>\n#include <gtsam/geometry/CalibratedCamera.h>\n#include <gtsam/geometry/Point2.h>\n\n#include <gtsam/linear/VectorValues.h>\n#include <gtsam/linear/NoiseModel.h>\n#include <gtsam/linear/GaussianFactor.h>\n#include <gtsam/base/timing.h>\n\n#include <boost/assign/list_of.hpp>\n#include <boost/assign/std/vector.hpp>\n#include <boost/range/iterator_range.hpp>\n#include <boost/range/adaptor/map.hpp>\n#include <CppUnitLite/TestHarness.h>\n\nusing namespace std;\nusing namespace boost::assign;\nusing namespace gtsam;\n\n// F\nconst Matrix26 F0 = Matrix26::Ones();\nconst Matrix26 F1 = 2 * Matrix26::Ones();\nconst Matrix26 F3 = 3 * Matrix26::Ones();\nconst vector<Matrix26, Eigen::aligned_allocator<Matrix26> > FBlocks = list_of<Matrix26>(F0)(F1)(F3);\nconst KeyVector keys {0, 1, 3};\n// RHS and sigmas\nconst Vector b = (Vector(6) << 1., 2., 3., 4., 5., 6.).finished();\n\n//*************************************************************************************\nTEST( regularImplicitSchurFactor, creation ) {\n  // Matrix E = Matrix::Ones(6,3);\n  Matrix E = Matrix::Zero(6, 3);\n  E.block<2,2>(0, 0) = I_2x2;\n  E.block<2,3>(2, 0) = 2 * Matrix::Ones(2, 3);\n  Matrix3 P = (E.transpose() * E).inverse();\n  RegularImplicitSchurFactor<CalibratedCamera> expected(keys, FBlocks, E, P, b);\n  Matrix expectedP = expected.getPointCovariance();\n  EXPECT(assert_equal(expectedP, P));\n}\n\n/* ************************************************************************* */\nTEST( regularImplicitSchurFactor, addHessianMultiply ) {\n\n  Matrix E = Matrix::Zero(6, 3);\n  E.block<2,2>(0, 0) = I_2x2;\n  E.block<2,3>(2, 0) = 2 * Matrix::Ones(2, 3);\n  E.block<2,2>(4, 1) = I_2x2;\n  Matrix3 P = (E.transpose() * E).inverse();\n\n  double alpha = 0.5;\n  VectorValues xvalues = map_list_of //\n  (0, Vector::Constant(6, 2))//\n  (1, Vector::Constant(6, 4))//\n  (2, Vector::Constant(6, 0))// distractor\n  (3, Vector::Constant(6, 8));\n\n  VectorValues yExpected = map_list_of//\n  (0, Vector::Constant(6, 27))//\n  (1, Vector::Constant(6, -40))//\n  (2, Vector::Constant(6, 0))// distractor\n  (3, Vector::Constant(6, 279));\n\n  // Create full F\n  size_t M=4, m = 3, d = 6;\n  Matrix F(2 * m, d * M);\n  F << F0, Matrix::Zero(2, d * 3), Matrix::Zero(2, d), F1, Matrix::Zero(2, d*2), Matrix::Zero(2, d * 3), F3;\n\n  // Calculate expected result F'*alpha*(I - E*P*E')*F*x\n  KeyVector keys2{0,1,2,3};\n  Vector x = xvalues.vector(keys2);\n  Vector expected = Vector::Zero(24);\n  RegularImplicitSchurFactor<CalibratedCamera>::multiplyHessianAdd(F, E, P, alpha, x, expected);\n  EXPECT(assert_equal(expected, yExpected.vector(keys2), 1e-8));\n\n  // Create ImplicitSchurFactor\n  RegularImplicitSchurFactor<CalibratedCamera> implicitFactor(keys, FBlocks, E, P, b);\n\n  VectorValues zero = 0 * yExpected;// quick way to get zero w right structure\n  { // First Version\n    VectorValues yActual = zero;\n    implicitFactor.multiplyHessianAdd(alpha, xvalues, yActual);\n    EXPECT(assert_equal(yExpected, yActual, 1e-8));\n    implicitFactor.multiplyHessianAdd(alpha, xvalues, yActual);\n    EXPECT(assert_equal(2 * yExpected, yActual, 1e-8));\n    implicitFactor.multiplyHessianAdd(-1, xvalues, yActual);\n    EXPECT(assert_equal(zero, yActual, 1e-8));\n  }\n\n  typedef Eigen::Matrix<double, 24, 1> DeltaX;\n  typedef Eigen::Map<DeltaX> XMap;\n  double* y = new double[24];\n  double* xdata = x.data();\n\n  { // Raw memory Version\n    std::fill(y, y + 24, 0);// zero y !\n    implicitFactor.multiplyHessianAdd(alpha, xdata, y);\n    EXPECT(assert_equal(expected, XMap(y), 1e-8));\n    implicitFactor.multiplyHessianAdd(alpha, xdata, y);\n    EXPECT(assert_equal(Vector(2 * expected), XMap(y), 1e-8));\n    implicitFactor.multiplyHessianAdd(-1, xdata, y);\n    EXPECT(assert_equal(Vector(0 * expected), XMap(y), 1e-8));\n  }\n\n  // Create JacobianFactor with same error\n  const SharedDiagonal model;\n  JacobianFactorQ<6, 2> jfQ(keys, FBlocks, E, P, b, model);\n\n  // error\n  double expectedError = 11875.083333333334;\n  {\n    EXPECT_DOUBLES_EQUAL(expectedError,jfQ.error(xvalues),1e-7)\n    EXPECT_DOUBLES_EQUAL(expectedError,implicitFactor.errorJF(xvalues),1e-7)\n    EXPECT_DOUBLES_EQUAL(11903.500000000007,implicitFactor.error(xvalues),1e-7)\n  }\n\n  {\n    VectorValues yActual = zero;\n    jfQ.multiplyHessianAdd(alpha, xvalues, yActual);\n    EXPECT(assert_equal(yExpected, yActual, 1e-8));\n    jfQ.multiplyHessianAdd(alpha, xvalues, yActual);\n    EXPECT(assert_equal(2 * yExpected, yActual, 1e-8));\n    jfQ.multiplyHessianAdd(-1, xvalues, yActual);\n    EXPECT(assert_equal(zero, yActual, 1e-8));\n  }\n\n  { // check hessian Diagonal\n    VectorValues diagExpected = jfQ.hessianDiagonal();\n    VectorValues diagActual = implicitFactor.hessianDiagonal();\n    EXPECT(assert_equal(diagExpected, diagActual, 1e-8));\n  }\n\n  { // check hessian Block Diagonal\n    map<Key,Matrix> BD = jfQ.hessianBlockDiagonal();\n    map<Key,Matrix> actualBD = implicitFactor.hessianBlockDiagonal();\n    LONGS_EQUAL(3,actualBD.size());\n    EXPECT(assert_equal(BD[0],actualBD[0]));\n    EXPECT(assert_equal(BD[1],actualBD[1]));\n    EXPECT(assert_equal(BD[3],actualBD[3]));\n  }\n\n  { // Raw memory Version\n    std::fill(y, y + 24, 0);// zero y !\n    jfQ.multiplyHessianAdd(alpha, xdata, y);\n    EXPECT(assert_equal(expected, XMap(y), 1e-8));\n    jfQ.multiplyHessianAdd(alpha, xdata, y);\n    EXPECT(assert_equal(Vector(2 * expected), XMap(y), 1e-8));\n    jfQ.multiplyHessianAdd(-1, xdata, y);\n    EXPECT(assert_equal(Vector(0 * expected), XMap(y), 1e-8));\n  }\n\n  VectorValues expectedVV;\n  expectedVV.insert(0,-3.5*Vector::Ones(6));\n  expectedVV.insert(1,10*Vector::Ones(6)/3);\n  expectedVV.insert(3,-19.5*Vector::Ones(6));\n  { // Check gradientAtZero\n    VectorValues actual = implicitFactor.gradientAtZero();\n    EXPECT(assert_equal(expectedVV, jfQ.gradientAtZero(), 1e-8));\n    EXPECT(assert_equal(expectedVV, implicitFactor.gradientAtZero(), 1e-8));\n  }\n\n  // Create JacobianFactorQR\n  JacobianFactorQR<6, 2> jfQR(keys, FBlocks, E, P, b, model);\n    EXPECT_DOUBLES_EQUAL(expectedError, jfQR.error(xvalues),1e-7)\n  EXPECT(assert_equal(expectedVV,  jfQR.gradientAtZero(), 1e-8));\n  {\n    const SharedDiagonal model;\n    VectorValues yActual = zero;\n    jfQR.multiplyHessianAdd(alpha, xvalues, yActual);\n    EXPECT(assert_equal(yExpected, yActual, 1e-8));\n    jfQR.multiplyHessianAdd(alpha, xvalues, yActual);\n    EXPECT(assert_equal(2 * yExpected, yActual, 1e-8));\n    jfQR.multiplyHessianAdd(-1, xvalues, yActual);\n    EXPECT(assert_equal(zero, yActual, 1e-8));\n  }\n\n  { // Raw memory Version\n    std::fill(y, y + 24, 0);// zero y !\n    jfQR.multiplyHessianAdd(alpha, xdata, y);\n    EXPECT(assert_equal(expected, XMap(y), 1e-8));\n    jfQR.multiplyHessianAdd(alpha, xdata, y);\n    EXPECT(assert_equal(Vector(2 * expected), XMap(y), 1e-8));\n    jfQR.multiplyHessianAdd(-1, xdata, y);\n    EXPECT(assert_equal(Vector(0 * expected), XMap(y), 1e-8));\n  }\n  delete [] y;\n}\n\n/* ************************************************************************* */\nTEST(regularImplicitSchurFactor, hessianDiagonal)\n{\n  /* TESTED AGAINST MATLAB\n   *  F = [Vector::Ones(2,6) zeros(2,6) zeros(2,6)\n        zeros(2,6) 2*Vector::Ones(2,6) zeros(2,6)\n        zeros(2,6) zeros(2,6) 3*Vector::Ones(2,6)]\n      E = [[1:6] [1:6] [0.5 1:5]];\n      E = reshape(E',3,6)'\n      P = inv(E' * E)\n      H = F' * (eye(6) - E * P * E') * F\n      diag(H)\n   */\n  Matrix E(6,3);\n  E.block<2,3>(0, 0) << 1,2,3,4,5,6;\n  E.block<2,3>(2, 0) << 1,2,3,4,5,6;\n  E.block<2,3>(4, 0) << 0.5,1,2,3,4,5;\n  Matrix3 P = (E.transpose() * E).inverse();\n  RegularImplicitSchurFactor<CalibratedCamera> factor(keys, FBlocks, E, P, b);\n\n  // hessianDiagonal\n  VectorValues expected;\n  expected.insert(0, 1.195652*Vector::Ones(6));\n  expected.insert(1, 4.782608*Vector::Ones(6));\n  expected.insert(3, 7.043478*Vector::Ones(6));\n  EXPECT(assert_equal(expected, factor.hessianDiagonal(),1e-5));\n\n  // hessianBlockDiagonal\n  map<Key,Matrix> actualBD = factor.hessianBlockDiagonal();\n  LONGS_EQUAL(3,actualBD.size());\n  Matrix FtE0 = F0.transpose() * E.block<2,3>(0, 0);\n  Matrix FtE1 = F1.transpose() * E.block<2,3>(2, 0);\n  Matrix FtE3 = F3.transpose() * E.block<2,3>(4, 0);\n\n  // variant one\n  EXPECT(assert_equal(F0.transpose()*F0-FtE0*P*FtE0.transpose(),actualBD[0]));\n  EXPECT(assert_equal(F1.transpose()*F1-FtE1*P*FtE1.transpose(),actualBD[1]));\n  EXPECT(assert_equal(F3.transpose()*F3-FtE3*P*FtE3.transpose(),actualBD[3]));\n\n  // variant two\n  Matrix I2 = I_2x2;\n  Matrix E0 = E.block<2,3>(0, 0);\n  Matrix F0t = F0.transpose();\n  EXPECT(assert_equal(F0t*F0-F0t*E0*P*E0.transpose()*F0,actualBD[0]));\n  EXPECT(assert_equal(F0t*(F0-E0*P*E0.transpose()*F0),actualBD[0]));\n\n  Matrix M1 = F0t*(F0-E0*P*E0.transpose()*F0);\n  Matrix M2 = F0t*F0-F0t*E0*P*E0.transpose()*F0;\n\n  EXPECT(assert_equal(  M1 , actualBD[0] ));\n  EXPECT(assert_equal(  M1 , M2 ));\n\n  Matrix M1b = F0t*(E0*P*E0.transpose()*F0);\n  Matrix M2b = F0t*E0*P*E0.transpose()*F0;\n  EXPECT(assert_equal(  M1b , M2b ));\n\n  EXPECT(assert_equal(F0t*(I2-E0*P*E0.transpose())*F0,actualBD[0]));\n  EXPECT(assert_equal(F1.transpose()*F1-FtE1*P*FtE1.transpose(),actualBD[1]));\n  EXPECT(assert_equal(F3.transpose()*F3-FtE3*P*FtE3.transpose(),actualBD[3]));\n\n  // augmentedInformation (test just checks diagonals)\n  Matrix actualInfo = factor.augmentedInformation();\n  EXPECT(assert_equal(actualBD[0],actualInfo.block<6,6>(0,0)));\n  EXPECT(assert_equal(actualBD[1],actualInfo.block<6,6>(6,6)));\n  EXPECT(assert_equal(actualBD[3],actualInfo.block<6,6>(12,12)));\n\n  // information (test just checks diagonals)\n  Matrix actualInfo2 = factor.information();\n  EXPECT(assert_equal(actualBD[0],actualInfo2.block<6,6>(0,0)));\n  EXPECT(assert_equal(actualBD[1],actualInfo2.block<6,6>(6,6)));\n  EXPECT(assert_equal(actualBD[3],actualInfo2.block<6,6>(12,12)));\n}\n\n/* ************************************************************************* */\nint main(void) {\n  TestResult tr;\n  int result = TestRegistry::runAllTests(tr);\n  return result;\n}\n//*************************************************************************************\n", "meta": {"hexsha": "b85dd891aa29ce9f07cd46efc8874c1eb39753ea", "size": 10649, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/slam/tests/testRegularImplicitSchurFactor.cpp", "max_stars_repo_name": "kvmanohar22/gtsam", "max_stars_repo_head_hexsha": "8194b931fe07fb1bd346cdcf116a35f9c4e208ba", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2019-12-11T18:33:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T04:52:45.000Z", "max_issues_repo_path": "gtsam/slam/tests/testRegularImplicitSchurFactor.cpp", "max_issues_repo_name": "kvmanohar22/gtsam", "max_issues_repo_head_hexsha": "8194b931fe07fb1bd346cdcf116a35f9c4e208ba", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-10-30T21:17:33.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-18T18:47:40.000Z", "max_forks_repo_path": "gtsam/slam/tests/testRegularImplicitSchurFactor.cpp", "max_forks_repo_name": "kvmanohar22/gtsam", "max_forks_repo_head_hexsha": "8194b931fe07fb1bd346cdcf116a35f9c4e208ba", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T16:24:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-24T11:10:49.000Z", "avg_line_length": 36.9756944444, "max_line_length": 108, "alphanum_fraction": 0.6444736595, "num_tokens": 3424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583124210896, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.46791483017870195}}
{"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_ROUND2EVEN_HPP_INCLUDED\n#define BOOST_SIMD_ARITHMETIC_FUNCTIONS_SCALAR_ROUND2EVEN_HPP_INCLUDED\n\n#include <boost/simd/arithmetic/functions/round2even.hpp>\n#include <boost/simd/include/functions/scalar/abs.hpp>\n#include <boost/simd/include/constants/twotonmb.hpp>\n#include <boost/simd/include/constants/zero.hpp>\n#include <boost/simd/sdk/config/enforce_precision.hpp>\n#include <boost/dispatch/attributes.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT          ( round2even_, tag::cpu_\n                                    , (A0)\n                                    , (scalar_< floating_<A0> >)\n                                    )\n  {\n    typedef A0 result_type;\n\n    BOOST_FORCEINLINE BOOST_SIMD_FUNCTOR_CALL(1)\n    {\n      boost::simd::config::enforce_precision<A0> enforcer;\n\n      const result_type v = boost::simd::abs(a0);\n      const result_type t2n = boost::simd::Twotonmb<result_type>();\n      result_type d0 = (v+t2n);\n      result_type d = (d0-t2n);\n      d = (v < t2n)?d:v;\n      return a0 < Zero<A0>() ? -d : d;\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT          ( round2even_, tag::cpu_\n                                    , (A0)\n                                    , (scalar_< integer_<A0> >)\n                                    )\n  {\n    typedef A0 result_type;\n\n    BOOST_FORCEINLINE BOOST_SIMD_FUNCTOR_CALL(1)\n    {\n      return a0;\n    }\n  };\n} } }\n\n#endif\n", "meta": {"hexsha": "847b824d1dbcbf734a98d729134cd2e64c0f1cf0", "size": 1959, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/scalar/round2even.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/round2even.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/round2even.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 34.9821428571, "max_line_length": 80, "alphanum_fraction": 0.5456865748, "num_tokens": 452, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289836, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.46786698542691557}}
{"text": "\n/*\n * From:\n * http://stackoverflow.com/questions/6142576/sample-from-multivariate-normal-gaussian-distribution-in-c\n */\n\n#include <iostream>\n#include <random>                                                                                \n#include <Eigen/Dense>\n#include <omp.h>\n#include <chrono>\n\n#include \"mvnormal.h\"\n\nusing namespace std;\nusing namespace Eigen;\nusing namespace std::chrono;\n\nstd::mt19937 **bmrngs;\n\n/*\n  We need a functor that can pretend it's const,\n  but to be a good random number generator \n  it needs mutable state.\n*/\n\n#ifdef __INTEL_COMPILER\nstd::random_device srd;\n#pragma omp threadprivate(srd)\n#else\n// use thread_local for gcc \nthread_local static std::random_device srd;\n#endif\n\n#ifndef __clang__\nthread_local \n#endif \nstatic std::mt19937 rng(srd());\n\n#ifndef __clang__\nthread_local \n#endif \nstatic std::normal_distribution<> nd;\n\ndouble randn(double) {\n  return nd(rng);\n}\n\ndouble randn0() {\n  return nd(rng);\n}\n\nauto\nnrandn(int n) -> decltype( VectorXd::NullaryExpr(n, std::cref(randn)) ) \n{\n    return VectorXd::NullaryExpr(n, std::cref(randn));\n}\n\nvoid init_bmrng(int seed) {\n   int nthreads = -1;\n#pragma omp parallel \n   {\n#pragma omp single\n      {\n         nthreads = omp_get_num_threads();\n      }\n   }\n   bmrngs = new std::mt19937*[nthreads];\n   for (int i = 0; i < nthreads; i++) {\n      bmrngs[i] = new std::mt19937(seed + i * 1999);\n   }\n}\n\nvoid init_bmrng() {\n   auto ms = (duration_cast< milliseconds >(\n             system_clock::now().time_since_epoch()\n         )).count();\n   init_bmrng(ms);\n}\n\nvoid bmrandn(double* x, long n) {\n#pragma omp parallel \n  {\n    std::uniform_real_distribution<double> unif(-1.0, 1.0);\n    std::mt19937* bmrng = bmrngs[omp_get_thread_num()];\n#pragma omp for schedule(static)\n    for (long i = 0; i < n; i += 2) {\n      double x1, x2, w;\n      do {\n        x1 = unif(*bmrng);\n        x2 = unif(*bmrng);\n        w = x1 * x1 + x2 * x2;\n      } while ( w >= 1.0 );\n\n      w = sqrt( (-2.0 * log( w ) ) / w );\n      x[i] = x1 * w;\n      if (i + 1 < n) {\n        x[i+1] = x2 * w;\n      }\n    }\n  }\n}\n\ndouble rand_unif() {\n  std::uniform_real_distribution<double> unif(0.0, 1.0);\n\tstd::mt19937* bmrng = bmrngs[omp_get_thread_num()];\n\treturn unif(*bmrng);\n}\n\ndouble rand_unif(double low, double high) {\n  std::uniform_real_distribution<double> unif(low, high);\n\tstd::mt19937* bmrng = bmrngs[omp_get_thread_num()];\n\treturn unif(*bmrng);\n}\n\nvoid bmrandn(MatrixXd & X) {\n  long n = X.rows() * (long)X.cols();\n  bmrandn(X.data(), n);\n}\n\n// to be called within OpenMP parallel loop (also from serial code is fine)\nvoid bmrandn_single(double* x, long n) {\n  std::uniform_real_distribution<double> unif(-1.0, 1.0);\n  std::mt19937* bmrng = bmrngs[omp_get_thread_num()];\n  for (long i = 0; i < n; i += 2) {\n    double x1, x2, w;\n    do {\n      x1 = unif(*bmrng);\n      x2 = unif(*bmrng);\n      w = x1 * x1 + x2 * x2;\n    } while ( w >= 1.0 );\n\n    w = sqrt( (-2.0 * log( w ) ) / w );\n    x[i] = x1 * w;\n    if (i + 1 < n) {\n      x[i+1] = x2 * w;\n    }\n  }\n}\n\ndouble bmrandn_single() {\n  //TODO: add bmrng as input\n  std::uniform_real_distribution<double> unif(-1.0, 1.0);\n  std::mt19937* bmrng = bmrngs[omp_get_thread_num()];\n  \n    double x1, x2, w;\n    do {\n      x1 = unif(*bmrng);\n      x2 = unif(*bmrng);\n      w = x1 * x1 + x2 * x2;\n    } while ( w >= 1.0 );\n\n    w = sqrt( (-2.0 * log( w ) ) / w );\n    return x1 * w;\n}\n\nvoid bmrandn_single(Eigen::VectorXd & x) {\n  bmrandn_single(x.data(), x.size());\n}\n\n/** returns random number according to Gamma distribution\n *  with the given shape (k) and scale (theta). See wiki. */\ndouble rgamma(double shape, double scale) {\n  std::gamma_distribution<double> gamma(shape, scale);\n  return gamma(*bmrngs[0]);\n}\n\n/** Normal(0, Lambda^-1) for nn columns */\nMatrixXd MvNormal_prec(const MatrixXd & Lambda, int nn = 1)\n{\n  int size = Lambda.rows(); // Dimensionality (rows)\n\n  LLT<MatrixXd> chol(Lambda);\n\n  MatrixXd r = MatrixXd::NullaryExpr(size, nn, std::cref(randn));\n\tchol.matrixU().solveInPlace(r);\n  return r;\n}\n\nMatrixXd MvNormal_prec(const MatrixXd & Lambda, const VectorXd & mean, int nn = 1)\n{\n  MatrixXd r = MvNormal_prec(Lambda, nn);\n  return r.colwise() + mean;\n}\n\nMatrixXd MvNormal_prec_omp(const MatrixXd & Lambda, int nn = 1)\n{\n  int size = Lambda.rows(); // Dimensionality (rows)\n\n  LLT<MatrixXd> chol(Lambda);\n\n  MatrixXd r(size, nn);\n  bmrandn(r);\n  // TODO: check if solveInPlace is parallelized:\n\tchol.matrixU().solveInPlace(r);\n  return r;\n}\n\n/*\n  Draw nn samples from a size-dimensional normal distribution\n  with a specified mean and covariance\n*/\nMatrixXd MvNormal(const MatrixXd covar, const VectorXd mean, int nn = 1) \n{\n  int size = mean.rows(); // Dimensionality (rows)\n  MatrixXd normTransform(size,size);\n\n  LLT<MatrixXd> cholSolver(covar);\n  normTransform = cholSolver.matrixL();\n\n  auto normSamples = MatrixXd::NullaryExpr(size, nn, std::cref(randn));\n  MatrixXd samples = (normTransform * normSamples).colwise() + mean;\n\n  return samples;\n}\n\nMatrixXd WishartUnit(int m, int df)\n{\n    MatrixXd c(m,m);\n    c.setZero();\n\n    for ( int i = 0; i < m; i++ ) {\n        std::gamma_distribution<> gam(0.5*(df - i));\n        c(i,i) = sqrt(2.0 * gam(rng));\n        VectorXd r = nrandn(m-i-1);\n        c.block(i,i+1,1,m-i-1) = r.transpose();\n    }\n\n    MatrixXd ret = c.transpose() * c;\n\n#ifdef TEST_MVNORMAL\n    cout << \"WISHART UNIT {\\n\" << endl;\n    cout << \"  m:\\n\" << m << endl;\n    cout << \"  df:\\n\" << df << endl;\n    cout << \"  ret;\\n\" << ret << endl;\n    cout << \"  c:\\n\" << c << endl;\n    cout << \"}\\n\" << ret << endl;\n#endif\n\n    return ret;\n}\n\nMatrixXd Wishart(const MatrixXd &sigma, const int df)\n{\n//  Get R, the upper triangular Cholesky factor of SIGMA.\n  auto chol = sigma.llt();\n\n//  Get AU, a sample from the unit Wishart distribution.\n  MatrixXd au = WishartUnit(sigma.cols(), df);\n\n//  Construct the matrix A = R' * AU * R.\n  MatrixXd a = chol.matrixL() * au * chol.matrixU();\n\n#ifdef TEST_MVNORMAL\n    cout << \"WISHART {\\n\" << endl;\n    cout << \"  sigma::\\n\" << sigma << endl;\n    cout << \"  r:\\n\" << r << endl;\n    cout << \"  au:\\n\" << au << endl;\n    cout << \"  df:\\n\" << df << endl;\n    cout << \"  a:\\n\" << a << endl;\n    cout << \"}\\n\" << endl;\n#endif\n\n\n  return a;\n}\n\n\n// from julia package Distributions: conjugates/normalwishart.jl\nstd::pair<VectorXd, MatrixXd> NormalWishart(const VectorXd & mu, double kappa, const MatrixXd & T, double nu)\n{\n  MatrixXd Lam = Wishart(T, nu);\n  MatrixXd mu_o = MvNormal_prec(Lam * kappa, mu);\n\n#ifdef TEST_MVNORMAL\n    cout << \"NORMAL WISHART {\\n\" << endl;\n    cout << \"  mu:\\n\" << mu << endl;\n    cout << \"  kappa:\\n\" << kappa << endl;\n    cout << \"  T:\\n\" << T << endl;\n    cout << \"  nu:\\n\" << nu << endl;\n    cout << \"  mu_o\\n\" << mu_o << endl;\n    cout << \"  Lam\\n\" << Lam << endl;\n    cout << \"}\\n\" << endl;\n#endif\n\n  return std::make_pair(mu_o , Lam);\n}\n\nstd::pair<VectorXd, MatrixXd> OldCondNormalWishart(const MatrixXd &U, const VectorXd &mu, const double kappa, const MatrixXd &T, const int nu)\n{\n  int N = U.cols();\n\n  auto Um = U.rowwise().mean();\n\n  // http://stackoverflow.com/questions/15138634/eigen-is-there-an-inbuilt-way-to-calculate-sample-covariance\n  MatrixXd C = U.colwise() - Um;\n  MatrixXd S = (C * C.adjoint()) / double(N - 1);\n  VectorXd mu_c = (kappa*mu + N*Um) / (kappa + N);\n  double kappa_c = kappa + N;\n  MatrixXd T_c = ( T + N * S.transpose() + (kappa * N)/(kappa + N) * (mu - Um) * ((mu - Um).transpose())).inverse();\n  int nu_c = nu + N;\n\n#ifdef TEST_MVNORMAL\n  cout << \"mu_c:\\n\" << mu_c << endl;\n  cout << \"kappa_c:\\n\" << kappa_c << endl;\n  cout << \"T_c:\\n\" << T_c << endl;\n  cout << \"nu_c:\\n\" << nu_c << endl;\n#endif\n\n  return NormalWishart(mu_c, kappa_c, T_c, nu_c);\n}\n\n// from bpmf.jl -- verified\nstd::pair<VectorXd, MatrixXd> CondNormalWishart(const MatrixXd &U, const VectorXd &mu, const double kappa, const MatrixXd &T, const int nu)\n{\n  /// TODO: parallelize (for computing C and C * C')\n  int N = U.cols();\n\n\tauto NU = U.rowwise().sum();\n\tauto NS = U * U.adjoint();\n\n\tint nu_c = nu + N;\n\tdouble kappa_c = kappa + N;\n\tauto mu_c = (kappa * mu + NU) / (kappa + N);\n\tauto X    = (T + NS + kappa * mu * mu.adjoint() - kappa_c * mu_c * mu_c.adjoint());\n\tEigen::MatrixXd T_c = X.inverse();\n\n#ifdef TEST_MVNORMAL\n  cout << \"mu_c:\\n\" << mu_c << endl;\n  cout << \"kappa_c:\\n\" << kappa_c << endl;\n  cout << \"T_c:\\n\" << T_c << endl;\n  cout << \"nu_c:\\n\" << nu_c << endl;\n#endif\n\n  return NormalWishart(mu_c, kappa_c, T_c, nu_c);\n}\n\n#if defined(TEST_MVNORMAL) || defined (BENCH_MVNORMAL)\n\nint main()\n{\n\n    MatrixXd U(32,32 * 1024);\n    U.setOnes();\n\n    VectorXd mu(32);\n    mu.setZero();\n\n    double kappa = 2;\n\n    MatrixXd T(32,32);\n    T.setIdentity(32,32);\n    T.array() /= 4;\n\n    int nu = 3;\n\n    VectorXd mu_out;\n    MatrixXd T_out;\n\n#ifdef BENCH_MVNORMAL\n    for(int i=0; i<300; ++i) {\n        tie(mu_out, T_out) = CondNormalWishart(U, mu, kappa, T, nu);\n        cout << i << \"\\r\" << flush;\n    }\n    cout << endl << flush;\n\n    for(int i=0; i<7; ++i) {\n        cout << i << \": \" << (int)(100.0 * acc[i] / acc[7])  << endl;\n    }\n    cout << \"total: \" << acc[7] << endl;\n\n    for(int i=0; i<300; ++i) {\n        tie(mu_out, T_out) = OldCondNormalWishart(U, mu, kappa, T, nu);\n        cout << i << \"\\r\" << flush;\n    }\n    cout << endl << flush;\n\n    cout << \"total: \" << acc[8] << endl;\n\n\n#else\n#if 1\n    cout << \"COND NORMAL WISHART\\n\" << endl;\n\n    tie(mu_out, T_out) = CondNormalWishart(U, mu, kappa, T, nu);\n\n    cout << \"mu_out:\\n\" << mu_out << endl;\n    cout << \"T_out:\\n\" << T_out << endl;\n\n    cout << \"\\n-----\\n\\n\";\n#endif\n\n#if 0\n    cout << \"NORMAL WISHART\\n\" << endl;\n\n    tie(mu_out, T_out) = NormalWishart(mu, kappa, T, nu);\n    cout << \"mu_out:\\n\" << mu_out << endl;\n    cout << \"T_out:\\n\" << T_out << endl;\n\n#endif\n\n#if 0\n    cout << \"MVNORMAL\\n\" << endl;\n    MatrixXd out = MvNormal(T, mu, 10);\n    cout << \"mu:\\n\" << mu << endl;\n    cout << \"T:\\n\" << T << endl;\n    cout << \"out:\\n\" << out << endl;\n#endif\n#endif\n}\n\n#endif\n", "meta": {"hexsha": "f0350dd16e1bd7410c86b36d4171c5da75fe0b13", "size": 9974, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/macau-cpp/mvnormal.cpp", "max_stars_repo_name": "edebrouwer/macau", "max_stars_repo_head_hexsha": "0b22d21ed954209406246e70178523102e98f922", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 38.0, "max_stars_repo_stars_event_min_datetime": "2016-02-27T22:18:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T12:17:39.000Z", "max_issues_repo_path": "lib/macau-cpp/mvnormal.cpp", "max_issues_repo_name": "edebrouwer/macau", "max_issues_repo_head_hexsha": "0b22d21ed954209406246e70178523102e98f922", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2016-05-23T14:14:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-16T08:12:40.000Z", "max_forks_repo_path": "lib/macau-cpp/mvnormal.cpp", "max_forks_repo_name": "edebrouwer/macau", "max_forks_repo_head_hexsha": "0b22d21ed954209406246e70178523102e98f922", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19.0, "max_forks_repo_forks_event_min_datetime": "2016-04-12T12:13:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-01T15:05:59.000Z", "avg_line_length": 24.1501210654, "max_line_length": 142, "alphanum_fraction": 0.5842189693, "num_tokens": 3233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289836, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.46786698542691557}}
{"text": "/*\n Copyright (C) 2017 Quaternion Risk Management Ltd\n All rights reserved.\n\n This file is part of ORE, a free-software/open-source library\n for transparent pricing and risk analysis - http://opensourcerisk.org\n\n ORE is free software: you can redistribute it and/or modify it\n under the terms of the Modified BSD License.  You should have received a\n copy of the license along with this program.\n The license is also available online at <http://opensourcerisk.org>\n\n This program is distributed on the basis that it will form a useful\n contribution to risk analytics and model standardisation, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.\n*/\n\n/*! \\file fxvolsmile.cpp\n    \\brief filling non-complete matrix\n*/\n\n#include \"toplevelfixture.hpp\"\n#include <boost/test/unit_test.hpp>\n#include <qle/math/fillemptymatrix.hpp>\n\nusing namespace QuantLib;\nusing namespace QuantExt;\nusing namespace boost::unit_test_framework;\nusing namespace std;\n\nBOOST_FIXTURE_TEST_SUITE(QuantExtTestSuite, qle::test::TopLevelFixture)\n\nBOOST_AUTO_TEST_SUITE(fillIncompleteMatrixTest)\n\nBOOST_AUTO_TEST_CASE(testBlankLineFill) {\n    BOOST_TEST_MESSAGE(\"Testing filling matrices with blank lines\");\n\n    Real non_val = -1;\n\n    // empty row matrix & empty col matrix\n    Matrix empty_row, empty_col;\n    empty_row = Matrix(5, 5, Real(22.5));\n    empty_col = Matrix(5, 5, Real(22.5));\n\n    for (int i = 0; i < 5; i++) {\n        empty_row[2][i] = non_val;\n        empty_col[i][2] = non_val;\n    }\n\n    // check fails + successes\n    Matrix tmp_mat_r = empty_row;\n    Matrix tmp_mat_c = empty_col;\n    BOOST_CHECK_THROW(fillIncompleteMatrix(tmp_mat_r, true, non_val), QuantLib::Error);\n    BOOST_CHECK_THROW(fillIncompleteMatrix(tmp_mat_c, false, non_val), QuantLib::Error);\n\n    tmp_mat_r = empty_row;\n    tmp_mat_c = empty_col;\n    BOOST_CHECK_NO_THROW(fillIncompleteMatrix(tmp_mat_r, false, non_val));\n    BOOST_CHECK_NO_THROW(fillIncompleteMatrix(tmp_mat_c, true, non_val));\n\n    // check vals\n    Real tol = 1.0E-8;\n    for (int i = 0; i < 5; i++) {\n        BOOST_CHECK_CLOSE(tmp_mat_r[2][i], Real(22.5), tol);\n        BOOST_CHECK_CLOSE(tmp_mat_c[i][2], Real(22.5), tol);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(testInterpolateOnly) {\n    BOOST_TEST_MESSAGE(\"Testing interpolation only\");\n\n    Real non_val = -1;\n    Matrix incomplete_m;\n    // incomplete matrix of the form:\n    /*\n    1   2   3   4   5\n    2   3   4   5   6\n    3   4   5   6   7\n    4   5   6   7   8\n    5   6   7   8   9\n    */\n    // But center block is non_values.\n\n    incomplete_m = Matrix(5, 5, non_val);\n    for (int i = 0; i < 5; i++) {\n        for (int j = 0; j < 5; j++) {\n            if (i == 0 || j == 0 || i == 4 || j == 4) {\n                incomplete_m[i][j] = j + i + 1;\n            }\n        }\n    }\n\n    // fill matrix\n    Matrix to_fill_row = incomplete_m;\n    Matrix to_fill_col = incomplete_m;\n    fillIncompleteMatrix(to_fill_row, true, non_val);\n    fillIncompleteMatrix(to_fill_col, false, non_val);\n\n    // check results\n    Real tol = 1.0E-8;\n    for (int i = 0; i < 5; i++) {\n        for (int j = 0; j < 5; j++) {\n            BOOST_CHECK_CLOSE(to_fill_row[i][j], j + i + 1, tol);\n            BOOST_CHECK_CLOSE(to_fill_col[i][j], j + i + 1, tol);\n        }\n    }\n}\n\nBOOST_AUTO_TEST_CASE(testExtrapolateOnly) {\n    BOOST_TEST_MESSAGE(\"Testing extrapolation of edges in filling the matrix\");\n\n    Real non_val = -1;\n    Matrix missing_rows, missing_cols;\n    vector<vector<Real> > test_cases; // for different test cases, different missing lines\n    for (int i = 0; i < 4; i++) {\n        vector<Real> tmp;\n        for (int j = 0; j <= i; j++) {\n            tmp.push_back(j);\n        }\n        test_cases.push_back(tmp);\n    }\n\n    // incomplete matricies of the form:\n    /*\n    '   2   3   4   5       '   '   '   '   '\n    '   3   4   5   6       2   3   4   5   6\n    '   4   5   6   7       3   4   5   6   7\n    '   5   6   7   8       4   5   6   7   8\n    '   6   7   8   9       5   6   7   8   9\n    */\n    // incomplete_rows: some rows at leading edge are missing.\n    // incomplete_cols: some cols at leading edge are missing.\n\n    // loop over cases with different missing rows/cols\n    vector<vector<Real> >::iterator cs;\n    for (cs = test_cases.begin(); cs != test_cases.end(); cs++) {\n\n        // set up empty matrices\n        missing_rows = Matrix(5, 5, non_val);\n        missing_cols = Matrix(5, 5, non_val);\n        for (int i = 0; i < 5; i++) {\n            for (int j = 0; j < 5; j++) {\n\n                // ignore empty lines\n                bool set_row = find(cs->begin(), cs->end(), i) == cs->end();\n                bool set_col = find(cs->begin(), cs->end(), j) == cs->end();\n                if (set_row) {\n                    missing_rows[i][j] = j + i + 1;\n                }\n                if (set_col) {\n                    missing_cols[i][j] = j + i + 1;\n                }\n            }\n        }\n\n        // fill matrices\n        Matrix to_fill_rows = missing_rows;\n        Matrix to_fill_cols = missing_cols;\n        fillIncompleteMatrix(to_fill_rows, false, non_val);\n        fillIncompleteMatrix(to_fill_cols, true, non_val);\n\n        // check results\n        for (int i = 0; i < 5; i++) {\n            for (int j = 0; j < 5; j++) {\n                int last_val = cs->size();\n                Real expectedVal_row;\n                Real expectedVal_col;\n                if (j < last_val) {\n                    expectedVal_col = missing_cols[i][last_val];\n                } else {\n                    expectedVal_col = missing_cols[i][j];\n                }\n                if (i < last_val) {\n                    expectedVal_row = missing_rows[last_val][j];\n                } else {\n                    expectedVal_row = missing_rows[i][j];\n                }\n                bool check_row = to_fill_rows[i][j] == expectedVal_row;\n                bool check_col = to_fill_cols[i][j] == expectedVal_col;\n\n                if (!check_row || !check_col) {\n                    BOOST_FAIL(\"FillIncomplete matrix failed on extrapolation only tests.\");\n                }\n            }\n        }\n    }\n}\n\nBOOST_AUTO_TEST_CASE(testInterpExtrap) {\n    BOOST_TEST_MESSAGE(\"Testing interpolation and extrapolation\");\n\n    Real non_val = -1;\n    Matrix incomplete_m;\n    // incomplete matrix of the form:\n    /*\n    1   '   '   '   '\n    '   2   '   '   '\n    '   '   3   '   '\n    '   '   '   4   '\n    '   '   '   '   5\n    */\n\n    incomplete_m = Matrix(5, 5, non_val);\n    for (int i = 0; i < 5; i++) {\n        incomplete_m[i][i] = i;\n    }\n\n    // fill matrix\n    Matrix to_fill_rows = incomplete_m;\n    Matrix to_fill_cols = incomplete_m;\n    fillIncompleteMatrix(to_fill_rows, true, non_val);\n    fillIncompleteMatrix(to_fill_cols, false, non_val);\n\n    // check results\n    for (int i = 0; i < 5; i++) {\n        for (int j = 0; j < 5; j++) {\n            BOOST_CHECK_EQUAL(to_fill_rows[i][j], incomplete_m[i][i]);\n            BOOST_CHECK_EQUAL(to_fill_cols[i][j], incomplete_m[j][j]);\n        }\n    }\n}\n\nBOOST_AUTO_TEST_CASE(testSingleEntry) {\n\n    Matrix inc = Matrix(1, 1, 22.5);\n    Matrix tmp1 = inc, tmp2 = inc, tmp3 = inc, tmp4 = inc;\n\n    // non-blank value.\n    BOOST_TEST_MESSAGE(\"Testing single non-blank entry\");\n    BOOST_CHECK_NO_THROW(fillIncompleteMatrix(tmp1, true, -1));\n    BOOST_CHECK_NO_THROW(fillIncompleteMatrix(tmp2, false, -1));\n    BOOST_CHECK_EQUAL(tmp1[0][0], inc[0][0]);\n    BOOST_CHECK_EQUAL(tmp2[0][0], inc[0][0]);\n\n    // blank value.\n    BOOST_TEST_MESSAGE(\"Testing single blank entry\");\n    BOOST_CHECK_THROW(fillIncompleteMatrix(tmp3, true, 22.5), QuantLib::Error);\n    BOOST_CHECK_THROW(fillIncompleteMatrix(tmp4, false, 22.5), QuantLib::Error);\n}\n\nBOOST_AUTO_TEST_CASE(testEmptyMatrix) {\n    BOOST_TEST_MESSAGE(\"testing empty matrices\");\n\n    Matrix m;\n    BOOST_CHECK_THROW(fillIncompleteMatrix(m, true, -1), QuantLib::Error);\n    BOOST_CHECK_THROW(fillIncompleteMatrix(m, false, -1), QuantLib::Error);\n}\n\nBOOST_AUTO_TEST_CASE(testFullMatrix) {\n    BOOST_TEST_MESSAGE(\"tesing full matrices\");\n\n    // set up matrices\n    Matrix full_single = Matrix(1, 1, 22.5);\n    Matrix full = Matrix(5, 5, 22.5);\n    Matrix tmp_single_r = full_single;\n    Matrix tmp_single_c = full_single;\n    Matrix tmp_r = full;\n    Matrix tmp_c = full;\n\n    // \"fill\"\n    BOOST_CHECK_NO_THROW(fillIncompleteMatrix(tmp_single_r, true, -1));\n    BOOST_CHECK_NO_THROW(fillIncompleteMatrix(tmp_single_c, false, -1));\n    BOOST_CHECK_NO_THROW(fillIncompleteMatrix(tmp_r, true, -1));\n    BOOST_CHECK_NO_THROW(fillIncompleteMatrix(tmp_c, false, -1));\n\n    // check results\n    BOOST_CHECK_EQUAL(tmp_single_r[0][0], full_single[0][0]);\n    BOOST_CHECK_EQUAL(tmp_single_c[0][0], full_single[0][0]);\n    for (int i = 0; i < 5; i++) {\n        for (int j = 0; j < 5; j++) {\n            BOOST_CHECK_EQUAL(tmp_r[i][j], full[i][j]);\n            BOOST_CHECK_EQUAL(tmp_c[i][j], full[i][j]);\n        }\n    }\n}\n\nBOOST_AUTO_TEST_CASE(testSingleRowCol) {\n    Matrix single_row = Matrix(1, 5, 22.5);\n    Matrix single_col = Matrix(5, 1, 22.5);\n    single_row[0][3] = -1; // single blank entry\n    single_col[3][0] = -1; // single blank entry\n    Matrix tmp_row = single_row;\n    Matrix tmp_col = single_col;\n\n    BOOST_CHECK_THROW(fillIncompleteMatrix(tmp_row, false, -1), QuantLib::Error);\n    BOOST_CHECK_THROW(fillIncompleteMatrix(tmp_col, true, -1), QuantLib::Error);\n\n    BOOST_CHECK_NO_THROW(fillIncompleteMatrix(tmp_row, true, -1));\n    BOOST_CHECK_NO_THROW(fillIncompleteMatrix(tmp_col, false, -1));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "06479783afab7020b6e076015c0eaf0e5350a735", "size": 9644, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QuantExt/test/fillemptymatrix.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/test/fillemptymatrix.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/test/fillemptymatrix.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": 32.5810810811, "max_line_length": 92, "alphanum_fraction": 0.5991289921, "num_tokens": 2683, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.7606506635289836, "lm_q1q2_score": 0.46786698542691557}}
{"text": "#include \"Bezier.h\"\r\n\r\n#include <boost/test/unit_test.hpp>\r\n\r\nusing namespace boost;\r\nusing namespace Eigen;\r\n\r\nnamespace\r\n{\r\n\ttemplate<typename T>\r\n\tbool InRange(T x, T min, T max)\r\n\t{\r\n\t\treturn x >= min && x <= max;\r\n\t}\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(Bezier_Range)\r\n{\r\n\tBezier spline({0.93f, 0.55f}, {0.25f, 0.79f});\r\n\tfloat epsilon(0.001f);\r\n\r\n\tBOOST_CHECK_EQUAL(spline.Solve(0.0f, epsilon), 0.0f);\r\n\tBOOST_CHECK_EQUAL(spline.Solve(1.0f, epsilon), 1.0f);\r\n\r\n\tfor (float x(0.0f); x <= 1.0f; x += 0.125f)\r\n\t\tBOOST_CHECK(InRange(spline.Solve(x, epsilon), 0.0f, 1.0f));\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(Bezier_Line)\r\n{\r\n\tBezier spline({0.1f, 0.1f}, {0.9f, 0.9f});\r\n\tfloat epsilon(0.001f);\r\n\r\n\tfor (float x(0.0f); x <= 1.0f; x += 0.125f)\r\n\t\tBOOST_CHECK_CLOSE(x, spline.Solve(x, epsilon), 1.0f);\r\n}", "meta": {"hexsha": "ebdbf2fc168ba3ceb62280c78e1c458c6196f0dd", "size": 785, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "render/RenderTest/TestBezier.cpp", "max_stars_repo_name": "don-reba/colors-visualization", "max_stars_repo_head_hexsha": "fe3937087be79715307127591a06f38b4647254f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "render/RenderTest/TestBezier.cpp", "max_issues_repo_name": "don-reba/colors-visualization", "max_issues_repo_head_hexsha": "fe3937087be79715307127591a06f38b4647254f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "render/RenderTest/TestBezier.cpp", "max_forks_repo_name": "don-reba/colors-visualization", "max_forks_repo_head_hexsha": "fe3937087be79715307127591a06f38b4647254f", "max_forks_repo_licenses": ["BSD-3-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.8055555556, "max_line_length": 62, "alphanum_fraction": 0.6356687898, "num_tokens": 284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.46786697875216965}}
{"text": "/*\n*   Copyright (c) 2010-2016, MIT Probabilistic Computing Project\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// Program to generate test values for the modified Bessel function of\n// the first kind using boost.  Usage:\n//\n//      c++ -o bessel bessel.cpp\n//      ./bessel\n\n#include <boost/math/distributions/normal.hpp>\n#include <boost/math/special_functions/bessel.hpp>\n#include <cstdio>\n\nint main(int argc, char **argv) {\n    const size_t n = 100;\n    const double lo = -709;\n    const double hi = +709;\n    const double w = (hi - lo)/n;\n    unsigned nu;\n    size_t i;\n\n    (void)argc;\n    (void)argv;\n\n    for (nu = 0; nu < 2; nu++) {\n        if (printf(\"static const double i%ue[][2] = {\\n\", nu) < 0) {\n            perror(\"printf\");\n            return 1;\n        }\n        if (printf(\"    // Uniform [-709, +709] grid\\n\") < 0) {\n            perror(\"printf\");\n            return 1;\n        }\n        for (i = 0; i < n; i++) {\n            const double x = lo + i*w;\n            const double y = boost::math::cyl_bessel_i(nu, x);\n            if (printf(\"    { %.17e, %.17e },\\n\", x, y) < 0) {\n                perror(\"printf\");\n                return 1;\n            }\n        }\n        if (printf(\"    // N(0, 1e-4) grid\\n\") < 0) {\n            perror(\"printf\");\n            return 1;\n        }\n        for (i = 0; i < n; i++) {\n            boost::math::normal norm(0, 1e-4);\n            const double p = static_cast<double>(i + 1)/(n + 2);\n            const double x = boost::math::quantile(norm, p);\n            const double y = boost::math::cyl_bessel_i(nu, x);\n            if (printf(\"    { %.17e, %.17e },\\n\", x, y) < 0) {\n                perror(\"printf\");\n                return 1;\n            }\n        }\n        if (printf(\"    // N(15, 1e-4) grid\\n\") < 0) {\n            perror(\"printf\");\n            return 1;\n        }\n        for (i = 0; i < n; i++) {\n            boost::math::normal norm(15, 1e-4);\n            const double p = static_cast<double>(i + 1)/(n + 2);\n            const double x = boost::math::quantile(norm, p);\n            const double y = boost::math::cyl_bessel_i(nu, x);\n            if (printf(\"    { %.17e, %.17e },\\n\", x, y) < 0) {\n                perror(\"printf\");\n                return 1;\n            }\n        }\n        if (printf(\"};\\n\") < 0) {\n            perror(\"printf\");\n            return 1;\n        }\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "9b8842ec19b77dc653bae280c23b3c74992f39e7", "size": 2892, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp_code/tests/bessel.cpp", "max_stars_repo_name": "vishalbelsare/crosscat", "max_stars_repo_head_hexsha": "1f2ac5a43a50ebd7aaa89f0c5ac3815a170848c5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 207.0, "max_stars_repo_stars_event_min_datetime": "2015-09-23T08:35:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-24T23:05:55.000Z", "max_issues_repo_path": "cpp_code/tests/bessel.cpp", "max_issues_repo_name": "vishalbelsare/crosscat", "max_issues_repo_head_hexsha": "1f2ac5a43a50ebd7aaa89f0c5ac3815a170848c5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 52.0, "max_issues_repo_issues_event_min_datetime": "2015-09-18T21:19:54.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-15T21:17:32.000Z", "max_forks_repo_path": "cpp_code/tests/bessel.cpp", "max_forks_repo_name": "vishalbelsare/crosscat", "max_forks_repo_head_hexsha": "1f2ac5a43a50ebd7aaa89f0c5ac3815a170848c5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 33.0, "max_forks_repo_forks_event_min_datetime": "2015-10-30T22:50:30.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-01T00:29:55.000Z", "avg_line_length": 31.7802197802, "max_line_length": 76, "alphanum_fraction": 0.5003457815, "num_tokens": 816, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.46786697875216954}}
{"text": "#include <boost/integer/common_factor_ct.hpp>\n", "meta": {"hexsha": "693d84f24646006a8186408cda7e6aa11769ec4f", "size": 46, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_integer_common_factor_ct.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_integer_common_factor_ct.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_integer_common_factor_ct.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 23.0, "max_line_length": 45, "alphanum_fraction": 0.8260869565, "num_tokens": 10, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255928, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4678669720774235}}
{"text": "//==================================================================================================\n/**\n  EVE - Expressive Vector Engine\n  Copyright : EVE Contributors & Maintainers\n  SPDX-License-Identifier: MIT\n**/\n//==================================================================================================\n#include <eve/function/ellint_3.hpp>\n#include <boost/math/special_functions/ellint_3.hpp>\n#include <boost/math/special_functions/ellint_1.hpp>\n#include <eve/wide.hpp>\n\n\nTTS_CASE_TPL(\"Check eve::ellint_3 behavior\", EVE_TYPE)\n{\n  auto boost_el3 = [](auto n,  auto phi,  auto k){return boost::math::ellint_3(k, n, phi);};\n\n  using elt_t = eve::element_type_t<T>;\n  TTS_ULP_EQUAL(eve::ellint_3(T(0.4), T(0), T(0.2)),       T(boost_el3(elt_t(0.4), elt_t(0), elt_t(0.2) )),      1.0);\n  TTS_ULP_EQUAL(eve::ellint_3(T(1.0), T(0.25), T(0.5)),    T(boost_el3(elt_t(1),   elt_t(0.25), elt_t(0.5) )),   1.0);\n  TTS_ULP_EQUAL(eve::ellint_3(T(0.0), T(0.25), T(0.5)),    T(boost_el3(elt_t(0),   elt_t(0.25), elt_t(0.5) )),   1.0);\n  TTS_ULP_EQUAL(eve::ellint_3(T(0.3), T(0.25), T(0)  ),    T(boost_el3(elt_t(0.3), elt_t(0.25), elt_t(0)   )),   1.0);\n  TTS_ULP_EQUAL(eve::ellint_3(T(1.2), T(0.25), T(0.25)),   T(boost_el3(elt_t(1.2), elt_t(0.25), elt_t(0.25) )),  1.0);\n  TTS_ULP_EQUAL(eve::ellint_3(T(0),   T(1.5), T(1)),       T(boost_el3(elt_t(0), elt_t(1.5), elt_t(1) )),      1.0);\n  TTS_ULP_EQUAL(eve::ellint_3(T(0),   T(2), T(1)),       T(eve::inf(eve::as<T>())),      1.0);\n}\n\nTTS_CASE_TPL(\"Check eve::ellint_3 behavior\", EVE_TYPE)\n{\n  auto boost_el3 = [](auto n, auto k){return boost::math::ellint_3(k, n);};\n\n  using elt_t = eve::element_type_t<T>;\n  TTS_ULP_EQUAL(eve::ellint_3(T(0.4), T(0.2)),    T(boost_el3(elt_t(0.4),  elt_t(0.2) )),   1.0);\n  TTS_ULP_EQUAL(eve::ellint_3(T(0.9), T(0.5)),    T(boost_el3(elt_t(0.9),  elt_t(0.5) )),   1.0);\n  TTS_ULP_EQUAL(eve::ellint_3(T(0.0), T(0.5)),    T(boost_el3(elt_t(0),    elt_t(0.5) )),   1.0);\n  TTS_ULP_EQUAL(eve::ellint_3(T(0.3), T(0)  ),    T(boost_el3(elt_t(0.3),  elt_t(0)   )),   1.0);\n  TTS_ULP_EQUAL(eve::ellint_3(T(0.8), T(0.25)),   T(boost_el3(elt_t(0.8),  elt_t(0.25) )),  1.0);\n}\n", "meta": {"hexsha": "870ef9ded7f5d88de5bf8e1f3a6efd9557136d18", "size": 2155, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/unit/module/real/elliptic/ellint_3/regular/ellint_3.hpp", "max_stars_repo_name": "orao/eve", "max_stars_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_stars_repo_licenses": ["MIT"], "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/unit/module/real/elliptic/ellint_3/regular/ellint_3.hpp", "max_issues_repo_name": "orao/eve", "max_issues_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_issues_repo_licenses": ["MIT"], "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/unit/module/real/elliptic/ellint_3/regular/ellint_3.hpp", "max_forks_repo_name": "orao/eve", "max_forks_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 55.2564102564, "max_line_length": 118, "alphanum_fraction": 0.5512761021, "num_tokens": 897, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255927, "lm_q2_score": 0.6150878555160666, "lm_q1q2_score": 0.4678669720774235}}
{"text": "#include <mitsuba/render/fresnel.h>\n#include <mitsuba/layer/microfacet.h>\n#include <mitsuba/layer/fourier.h>\n#include <mitsuba/core/frame.h>\n#include <mitsuba/core/math.h>\n#include <enoki/special.h>\n#include <Eigen/SVD>\n#include <Eigen/LU>\n#include <cmath>\n#include <chrono>\n#include <atomic>\n\nusing namespace std::chrono;\n\n#if defined HAVE_FFTW\n    #include <fftw3.h>\n    // #define USE_FFTW\n#endif\n\nNAMESPACE_BEGIN(mitsuba)\n\nstd::atomic<double> microfacet_timer;\n\ndouble microfacet(double mu_o, double mu_i, double phi_s, double phi_d,\n                  double alpha_u, double alpha_v,\n                  std::complex<double> eta_,\n                  bool isotropic_g) {\n    double phi_i = 0.5 * (phi_s - phi_d);\n    double phi_o = 0.5 * (phi_s + phi_d);\n\n    double sin_theta_i = safe_sqrt(1-mu_i*mu_i),\n           sin_theta_o = safe_sqrt(1-mu_o*mu_o),\n           cos_phi_i = std::cos(phi_i),\n           sin_phi_i = std::sin(phi_i),\n           cos_phi_o = std::cos(phi_o),\n           sin_phi_o = std::sin(phi_o);\n\n    Vector3f wi(-sin_theta_i*cos_phi_i,\n                -sin_theta_i*sin_phi_i,\n                -mu_i);\n    Vector3f wo(sin_theta_o*cos_phi_o,\n                sin_theta_o*sin_phi_o,\n                mu_o);\n\n    bool reflect = -mu_i*mu_o > 0;\n\n    if (mu_o == 0 || mu_i == 0)\n        return 0;\n\n    bool conductor = (std::imag(eta_) != 0);\n    if (conductor && !reflect)\n        return 0;\n    std::complex<double> eta = (-mu_i > 0 || conductor) ? eta_ : std::complex<double>(1) / eta_;\n\n    Vector3f wh = normalize(wi + wo * (reflect ? 1.0 : std::real(eta)));\n    wh = enoki::mulsign(wh, Frame3f::cos_theta(wh));\n\n    /* The following two visibility checks are usually part of the smith_G1\n       implementations, but are considered to be part of the \"Fresnel + Remainder\"\n       term in this framework. */\n    if (dot(wi, wh) * Frame3f::cos_theta(wi) <= 0 || dot(wo, wh) * Frame3f::cos_theta(wo) <= 0)\n        return 0;\n\n    double cos_theta_h = (double)Frame3f::cos_theta(wh),\n           cos_theta_h_2 = cos_theta_h * cos_theta_h;\n\n    double exponent = ((double) (wh.x() * wh.x()) / (alpha_u * alpha_u) +\n                       (double) (wh.y() * wh.y()) / (alpha_v * alpha_v)) / cos_theta_h_2;\n\n    /* For the isotropic shadowing-masking function, take max{alpha_u, alpha_v} to ensure energy conservation. */\n    double alpha_u_g = isotropic_g ? std::max(alpha_u, alpha_v) : alpha_u;\n    double alpha_v_g = isotropic_g ? alpha_u_g : alpha_v;\n\n    double eta_real = std::real(eta),\n           eta_imag = std::imag(eta);\n\n    double D = cos_theta_h <= 0 ? 0.0\n                                : std::exp(-exponent) / (math::Pi<double> * alpha_u * alpha_v * cos_theta_h_2 * cos_theta_h_2),\n           F = !conductor ? (double) std::get<0>(fresnel(float(dot(wi, wh)), float(std::real(eta_))))\n                          : (double) fresnel_conductor(float(dot(wi, wh)), enoki::Complex<float>(eta_real, eta_imag)),\n           G = smith_G1(wi, wh, alpha_u_g, alpha_v_g) * smith_G1(wo, wh, alpha_u_g, alpha_v_g);\n\n    if (reflect) {\n        return F * D * G / (4 * std::abs(mu_i*mu_o));\n    } else {\n        double sqrt_denom = (double) dot(wi, wh) + std::real(eta) * (double) dot(wo, wh);\n\n        return std::abs(((1 - F) * D * G * std::real(eta) * std::real(eta) * (double) dot(wi, wh)\n                         * (double) dot(wo, wh)) / (mu_i*mu_o * sqrt_denom * sqrt_denom));\n    }\n}\n\ndouble microfacet_exp(double mu_o, double mu_i, double phi_s, double phi_d,\n                      double alpha_u, double alpha_v,\n                      std::complex<double> eta_) {\n    double phi_i = 0.5 * (phi_s - phi_d);\n    double phi_o = 0.5 * (phi_s + phi_d);\n\n    double sin_theta_i = safe_sqrt(1-mu_i*mu_i),\n           sin_theta_o = safe_sqrt(1-mu_o*mu_o),\n           cos_phi_i = std::cos(phi_i),\n           sin_phi_i = std::sin(phi_i),\n           cos_phi_o = std::cos(phi_o),\n           sin_phi_o = std::sin(phi_o);\n\n    Vector3f wi(-sin_theta_i*cos_phi_i,\n                -sin_theta_i*sin_phi_i,\n                -mu_i);\n    Vector3f wo(sin_theta_o*cos_phi_o,\n                sin_theta_o*sin_phi_o,\n                mu_o);\n\n    bool reflect = -mu_i*mu_o > 0;\n\n    if (mu_o == 0 || mu_i == 0)\n        return 0;\n\n    bool conductor = (std::imag(eta_) != 0);\n    if (conductor && !reflect)\n        return 0;\n    std::complex<double> eta = (-mu_i > 0 || conductor) ? eta_ : std::complex<double>(1) / eta_;\n\n    Vector3f wh = normalize(wi + wo * (reflect ? 1.0 : std::real(eta)));\n    wh = enoki::mulsign(wh, Frame3f::cos_theta(wh));\n\n    double cos_theta_h_2 = (double) Frame3f::cos_theta_2(wh);\n\n    double exponent = ((double) (wh.x() * wh.x()) / (alpha_u * alpha_u) +\n                       (double) (wh.y() * wh.y()) / (alpha_v * alpha_v)) / cos_theta_h_2;\n\n    return std::exp(-exponent);\n}\n\ndouble microfacet_fresnel(double mu_o, double mu_i, double phi_s, double phi_d,\n                          double alpha_u, double alpha_v,\n                          std::complex<double> eta_,\n                          bool fresnel_only) {\n    (void)phi_s; // Unused\n\n    double sin_theta_i = safe_sqrt(1-mu_i*mu_i),\n           sin_theta_o = safe_sqrt(1-mu_o*mu_o),\n           cos_phi = std::cos(phi_d),\n           sin_phi = std::sin(phi_d);\n\n    Vector3f wi(-sin_theta_i, 0, -mu_i);\n    Vector3f wo(sin_theta_o*cos_phi, sin_theta_o*sin_phi, mu_o);\n\n    bool reflect = -mu_i*mu_o > 0;\n\n    if (mu_o == 0 || mu_i == 0)\n        return 0;\n\n    bool conductor = (std::imag(eta_) != 0);\n    if (conductor && !reflect)\n        return 0;\n    std::complex<double> eta = (-mu_i > 0 || conductor) ? eta_ : std::complex<double>(1) / eta_;\n\n    Vector3f wh = normalize(wi + wo * (reflect ? 1.0 : std::real(eta)));\n    wh = enoki::mulsign(wh, Frame3f::cos_theta(wh));\n\n    /* The following two visibility checks are usually part of the smith_G1\n       implementations, but are considered to be part of the \"Fresnel + Remainder\"\n       term in this framework. */\n    if (dot(wi, wh) * Frame3f::cos_theta(wi) <= 0 || dot(wo, wh) * Frame3f::cos_theta(wo) <= 0)\n        return 0;\n\n    double cos_theta_h = (double) Frame3f::cos_theta(wh),\n           cos_theta_h_2 = cos_theta_h * cos_theta_h;\n\n    double eta_real = std::real(eta),\n           eta_imag = std::imag(eta);\n\n    double D = cos_theta_h == 0 ? 0.0\n                                : 1.0 / (math::Pi<double> * alpha_u * alpha_v * cos_theta_h_2 * cos_theta_h_2),\n           F = !conductor ? (double) std::get<0>(fresnel(float(dot(wi, wh)), float(std::real(eta_))))\n                          : (double) fresnel_conductor(float(dot(wi, wh)), enoki::Complex<float>(eta_real, eta_imag));\n\n    if (fresnel_only) {\n        if (reflect) {\n            return F;\n        } else {\n            return std::abs(1-F);\n        }\n    }\n\n    if (reflect) {\n        return F * D / (4.0 * std::abs(mu_i*mu_o));\n    } else {\n        double sqrt_denom = (double) dot(wi, wh) + std::real(eta) * (double) dot(wo, wh);\n        return std::abs(((1 - F) * D * std::real(eta) * std::real(eta) * (double) dot(wi, wh)\n                        * (double) dot(wo, wh)) / (mu_i*mu_o * sqrt_denom * sqrt_denom));\n    }\n}\n\ndouble microfacet_G(double mu_o, double mu_i, double phi_s, double phi_d,\n                    double alpha_u, double alpha_v,\n                    std::complex<double> eta_,\n                    bool isotropic_g ) {\n    double phi_i = 0.5 * (phi_s - phi_d);\n    double phi_o = 0.5 * (phi_s + phi_d);\n\n    double sin_theta_i = safe_sqrt(1-mu_i*mu_i),\n           sin_theta_o = safe_sqrt(1-mu_o*mu_o),\n           cos_phi_i = std::cos(phi_i),\n           sin_phi_i = std::sin(phi_i),\n           cos_phi_o = std::cos(phi_o),\n           sin_phi_o = std::sin(phi_o);\n\n    Vector3f wi(-sin_theta_i*cos_phi_i,\n                -sin_theta_i*sin_phi_i,\n                -mu_i);\n    Vector3f wo(sin_theta_o*cos_phi_o,\n                sin_theta_o*sin_phi_o,\n                mu_o);\n\n    bool reflect = -mu_i*mu_o > 0;\n\n    if (mu_o == 0 || mu_i == 0)\n        return 0;\n\n    bool conductor = (std::imag(eta_) != 0);\n    if (conductor && !reflect)\n        return 0;\n    std::complex<double> eta = (-mu_i > 0 || conductor) ? eta_ : std::complex<double>(1.0) / eta_;\n\n    Vector3f wh = normalize(wi + wo * (reflect ? 1.0 : std::real(eta)));\n    wh = enoki::mulsign(wh, Frame3f::cos_theta(wh));\n\n    /* For the isotropic shadowing-masking function, take max{alpha_u, alpha_v}\n       to ensure energy conservation. */\n    double alpha_u_g = isotropic_g ? std::max(alpha_u, alpha_v) : alpha_u;\n    double alpha_v_g = isotropic_g ? alpha_u_g : alpha_v;\n\n    return smith_G1(wi, wh, alpha_u_g, alpha_v_g) *\n           smith_G1(wo, wh, alpha_u_g, alpha_v_g);\n}\n\ndouble smith_G1(const Vector3f &v, const Vector3f &m, double alpha_u, double alpha_v) {\n    (void)m; // Unused\n\n    /* The following visibility check usually found in smith_G1 implementations is\n       treated in the \"Fresnel + Remainder\" term in this framework. */\n    // if (dot(v, m) * Frame3f::cos_theta(v) <= 0)\n    //     return 0;\n\n    const double tan_theta = (double) std::abs(Frame3f::tan_theta(v));\n    if (tan_theta == 0)\n        return 1;\n\n    double alpha = project_roughness(v, alpha_u, alpha_v);\n\n    double a = 1.0 / (alpha * tan_theta);\n    if (a < 1.6) {\n        /* Use a fast and accurate (<0.35% rel. error) rational\n           approximation to the shadowing-masking function */\n        const double a_sqr = a * a;\n        return (3.535 * a + 2.181 * a_sqr)\n             / (1.0 + 2.276 * a + 2.577 * a_sqr);\n    }\n\n    return 1.0;\n}\n\nVectorX smith_G1_fourier_series(double mu, double alpha_u, double alpha_v,\n                                size_t order, size_t n_samples) {\n    /* Here we compute the Fourier series of the Smith Shadowing-Masking component,\n       for one of the directions phi_i, phi_o via Filon integration.\n       Note that we need to sample the function in the domain [0, pi] and perform\n       the integration over [0, 2pi] s.t. the \"diagonal\" versions of these series\n       end up being 2pi-periodic in phi_s, phi_d. */\n    double cos_theta     = std::abs(mu),\n           sin_theta     = std::sqrt(1.0 - cos_theta*cos_theta),\n           tan_theta     = sin_theta / cos_theta;\n\n    double phi_step     =  math::Pi<double> / (n_samples - 1),\n           cos_phi_prev =  std::cos(phi_step), cos_phi_cur = 1.0,\n           sin_phi_prev = -std::sin(phi_step), sin_phi_cur = 0.0,\n           two_cos_phi  =  2.0 * cos_phi_prev;\n\n    VectorXc values(n_samples);\n\n    for (size_t i = 0; i < n_samples; ++i) {\n        double cos_phi_next = two_cos_phi*cos_phi_cur - cos_phi_prev,\n               sin_phi_next = two_cos_phi*sin_phi_cur - sin_phi_prev;\n\n        double cos_phi_2 = cos_phi_cur*cos_phi_cur;\n        double sin_phi_2 = sin_phi_cur*sin_phi_cur;\n\n        double alpha = std::sqrt(cos_phi_2 * alpha_u * alpha_u +\n                                 sin_phi_2 * alpha_v * alpha_v);\n\n        double result = 1.0;\n        double a = 1.0 / (alpha * tan_theta);\n        if (a < 1.6) {\n            /* Use a fast and accurate (<0.35% rel. error) rational\n               approximation to the shadowing-masking function */\n            double a_sqr = a * a;\n            result = (3.535 * a + 2.181 * a_sqr)\n                 / (1.0 + 2.276 * a + 2.577 * a_sqr);\n        }\n        values[i] = result;\n\n        cos_phi_prev = cos_phi_cur; cos_phi_cur = cos_phi_next;\n        sin_phi_prev = sin_phi_cur; sin_phi_cur = sin_phi_next;\n    }\n\n    VectorXc coeffs(order);\n    coeffs.setZero();\n    filon_integrate_exp(values.data(), n_samples, coeffs.data(), order, 0, 2*math::Pi<double>);\n\n    return coeffs.real();\n}\n\ndouble project_roughness(const Vector3f &v, double alpha_u, double alpha_v) {\n    double inv_sin_theta_2 = 1.0 / (double) Frame3f::sin_theta_2(v);\n\n    if ((alpha_u == alpha_v) || inv_sin_theta_2 < 0)\n        return alpha_u;\n\n    double cos_phi_2 = (double) (v.x() * v.x()) * inv_sin_theta_2;\n    double sin_phi_2 = (double) (v.y() * v.y()) * inv_sin_theta_2;\n\n    return std::sqrt(cos_phi_2 * alpha_u * alpha_u +\n                     sin_phi_2 * alpha_v * alpha_v);\n}\n\nstatic int expcos_coefficient_count(double B, double relerr) {\n    double prod = 1, invB = 1 / B;\n    if (B == 0)\n        return 1;\n\n    for (int i = 0; ; ++i) {\n        prod /= 1 + i * invB;\n\n        if (prod < relerr)\n            return 2*i+1;\n    }\n}\n\nstatic double mod_bessel_ratio(double z, double k) {\n    const double eps = std::numeric_limits<double>::epsilon(),\n                 inv_two_b = 2 / z;\n\n    double i  = (double) k,\n           D  = 1 / (inv_two_b * i++),\n           Cd = D,\n           C  = Cd;\n\n    while (std::abs(Cd) > eps * std::abs(C)) {\n        double coeff = inv_two_b * i++;\n        D = 1 / (D + coeff);\n        Cd *= coeff*D - 1;\n        C += Cd;\n    }\n\n    return C;\n}\n\nstatic void bessel_functions(double c, double z, int n, VectorX &bessel) {\n    bessel.resize(n);\n\n    /* Determine the last ratio and work downwards */\n    bessel[n-1] = mod_bessel_ratio(z, n - 1);\n    for (int i = n-2; i > 0; --i)\n        bessel[i] = z / (2*i + z*bessel[i+1]);\n\n    /* Evaluate the exponentially scaled I0 and correct scaling */\n    bessel[0] = enoki::i0e(z) * std::exp(z + c);\n\n    /* Apply the ratios upwards */\n    double prod = bessel[0];\n    for (int i = 1; i < n; ++i) {\n        prod *= bessel[i];\n        bessel[i] = prod;\n    }\n}\n\nstatic double max_B_heuristic(size_t m, double relerr) {\n    if (relerr >= 1e-1)\n        return 0.1662*std::pow((double) m, 2.05039);\n    else if (relerr >= 1e-2)\n        return 0.0818*std::pow((double) m, 2.04982);\n    else if (relerr >= 1e-3)\n        return 0.0538*std::pow((double) m, 2.05001);\n    else if (relerr >= 1e-4)\n        return 0.0406*std::pow((double) m, 2.04686);\n    else if (relerr >= 1e-5)\n        return 0.0337*std::pow((double) m, 2.03865);\n    else if (relerr >= 1e-6)\n        return 0.0299*std::pow((double) m, 2.02628);\n    else {\n        Log(Warn, \"max_B(): unknown relative error bound!\");\n        return math::Infinity<double>;\n    }\n}\n\nvoid microfacet_reflection_exp_coeffs(double mu_o, double mu_i, double alpha_u, double alpha_v, double phi_s, VectorX &c) {\n    c.resize(3);\n\n    double denom = 1.0 / (alpha_u * alpha_v * (mu_i - mu_o)),\n           alpha_sqr_sum = (alpha_u * alpha_u + alpha_v * alpha_v),\n           alpha_sqr_dif = (alpha_u * alpha_u - alpha_v * alpha_v),\n           root = safe_sqrt((1 - mu_i * mu_i) * (1 - mu_o * mu_o)),\n           tmp = (mu_i * mu_i + mu_o * mu_o - 2);\n\n    double c0 = 0.5 * denom * denom * alpha_sqr_sum * tmp,\n           c1 = denom * denom * alpha_sqr_sum * root,\n           c2 = denom * denom * -alpha_sqr_dif * root,\n           c3 = 0.5 * denom * denom * -alpha_sqr_dif * (mu_o * mu_o - 1),\n           c4 = 0.5 * denom * denom * -alpha_sqr_dif * (mu_i * mu_i - 1);\n\n    std::complex<double> z(c1 + (c3 + c4) * std::cos(phi_s),\n                                (c3 - c4) * std::sin(phi_s));\n\n    double A = c0 + c2 * std::cos(phi_s),\n           B = std::abs(z),\n           C = std::arg(z);\n\n    c[0] = A;\n    c[1] = B;\n    c[2] = C;\n}\n\nvoid microfacet_refraction_exp_coeffs(double mu_o, double mu_i, double alpha_u, double alpha_v, double phi_s, double eta, VectorX &c) {\n    c.resize(3);\n\n    double denom = 1.0 / (alpha_u * alpha_v * (mu_i - eta * mu_o)),\n           alpha_sqr_sum = (alpha_u * alpha_u + alpha_v * alpha_v),\n           alpha_sqr_dif = (alpha_u * alpha_u - alpha_v * alpha_v),\n           root = safe_sqrt((1 - mu_i * mu_i) * (1 - mu_o * mu_o));\n\n    double c0 = 0.5 * denom * denom * alpha_sqr_sum * (mu_i * mu_i - 1 + eta * eta * (mu_o * mu_o - 1)),\n           c1 = denom * denom * alpha_sqr_sum * eta * root,\n           c2 = denom * denom * -alpha_sqr_dif * eta * root,\n           c3 = 0.5 * denom * denom * -alpha_sqr_dif * eta * eta * (mu_o * mu_o - 1),\n           c4 = 0.5 * denom * denom * -alpha_sqr_dif * (mu_i * mu_i - 1);\n\n    std::complex<double> z(c1 + (c3 + c4) * std::cos(phi_s),\n                                (c3 - c4) * std::sin(phi_s));\n\n    double A = c0 + c2 * std::cos(phi_s),\n           B = std::abs(z),\n           C = std::arg(z);\n\n    c[0] = A;\n    c[1] = B;\n    c[2] = C;\n}\n\nVectorXc exp_cos_fourier_series(double A, double B, double C, double relerr) {\n    VectorXc result;\n    int md = expcos_coefficient_count(B, relerr);\n    int mdh = md / 2;\n\n    // Create Fourier Series for exp(A + B * cos(phi_d + 0))\n    VectorX bessel;\n    bessel_functions(A, B, mdh + 1, bessel);\n\n    int truncated_size = bessel.size();\n    for (int i = 1; i < bessel.size(); ++i) {\n         if (2*std::abs(bessel[i]) < bessel[0] * relerr) {\n            truncated_size = i;\n            break;\n        }\n    }\n    VectorX bessel_trunc = bessel.head(truncated_size);\n    mdh = bessel_trunc.size() - 1;\n    md = 2*mdh+1;\n\n    result.resize(md);\n\n    result.head(mdh) = bessel_trunc.tail(mdh).reverse().cast<std::complex<double>>();\n    result.tail(mdh + 1) = bessel_trunc.cast<std::complex<double>>();\n\n    if (std::abs(C) > 0) {\n        // Shift Fourier Series by phase C\n        std::complex<double> exp_phase_inc = std::exp(1i * C);\n        std::complex<double> exp_phase = std::exp(-1i * (double) mdh * C);\n        for (int i = 0; i < md; ++i) {\n            result[i] *= exp_phase;\n            exp_phase *= exp_phase_inc;\n        }\n    }\n\n    return result;\n}\n\ninline void sample_function(const std::function<double(double)> &f,\n                            double *values, size_t size,\n                            double a, double b) {\n    double delta = (b - a) / (size - 1);\n    for (size_t i = 0; i < size; ++i) {\n        double x = a + i*delta;\n        values[i] = f(x);\n    }\n}\n\ninline MatrixX coefficient_conversion_matrix(int m, double phi_a, double phi_b) {\n    /* Precompute some sines and cosines */\n    VectorX cos_phi_a(m), sin_phi_a(m), cos_phi_b(m), sin_phi_b(m);\n    for (int i = 0; i < m; ++i) {\n        std::tie(sin_phi_a[i], cos_phi_a[i]) = enoki::sincos(i*phi_a);\n        std::tie(sin_phi_b[i], cos_phi_b[i]) = enoki::sincos(i*phi_b);\n    }\n\n    MatrixX A(m, m);\n    for (int i = 0; i < m; ++i) {\n        for (int j = 0; j <= i; ++j) {\n            if (i != j) {\n                A(i, j) = A(j, i) = (i * cos_phi_b[j] * sin_phi_b[i] +\n                                     j * cos_phi_a[i] * sin_phi_a[j] -\n                                     i * cos_phi_a[j] * sin_phi_a[i] -\n                                     j * cos_phi_b[i] * sin_phi_b[j]) / (i*i - j*j);\n            } else if (i != 0) {\n                A(i, i) = (std::sin(2*i * phi_b) -\n                           std::sin(2*i * phi_a) +\n                           2*i * (phi_b - phi_a)) / (4*i);\n            } else {\n                A(i, i) = phi_b - phi_a;\n            }\n        }\n    }\n    return A;\n}\n\nVectorX fresnel_fourier_series(double mu_o, double mu_i,\n                                double alpha_u, double alpha_v,\n                                std::complex<double> eta_,\n                                int md, double phi_max,\n                                bool svd_reg, bool fresnel_only) {\n    int m = md / 2 + 1; // Number of Cosine series coefficients\n    VectorX result;\n\n    bool reflect = -mu_i * mu_o > 0;\n\n    double sin_mu_2 = safe_sqrt((1.0 - mu_i * mu_i) * (1.0 - mu_o * mu_o)),\n           phi_critical = 0.0;\n\n    bool conductor = (std::imag(eta_) != 0);\n    std::complex<double> eta = (-mu_i > 0 || conductor) ? eta_ : std::complex<double>(1) / eta_;\n\n    if (reflect) {\n        if (!conductor) {\n            double tmp = (2.0*std::real(eta)*std::real(eta) - mu_i*mu_o - 1.0) / sin_mu_2;\n            phi_critical = safe_acos(tmp);\n        }\n    } else if (!reflect) {\n        if (conductor) {\n            Throw(\"microfacet_no_exp_fourier_series(): Encountered refraction case for a conductor!\");\n        }\n        double eta_denser = (std::real(eta) > 1 ? std::real(eta) : 1 / std::real(eta));\n        double tmp = (1 - eta_denser * mu_i * mu_o) / (eta_denser * sin_mu_2);\n        phi_critical = safe_acos(tmp);\n    }\n\n    bool phi_critical_inside_interval;\n    if (reflect && mu_i > 0) {\n        /* For reflection from bottom, phi_critical = 0 results in a high-frequency feature that should be captured. */\n        phi_critical_inside_interval = phi_critical < phi_max - math::Epsilon<double>;\n    } else {\n        phi_critical_inside_interval = phi_critical > math::Epsilon<double> && phi_critical < phi_max - math::Epsilon<double>;\n    }\n\n    if (!conductor && phi_critical_inside_interval) {\n        /* Uh oh, some high frequency content (critical angle) leaked in the\n           generally low frequency part. Increase the number of coefficients so\n           that we can capture it. Fortunately, this happens very rarely. */\n        m = std::max(m, 100);\n        md = 2*m-1;\n    }\n\n    VectorX coeffs;\n    if (svd_reg) {\n        coeffs.resize(m);\n    } else {\n        coeffs.resize(2*m); // Allocate two times the space for QR regularization below\n    }\n    coeffs.setZero();\n\n    const int samples = 200;\n    auto integrand = std::bind(&microfacet_fresnel, mu_o, mu_i, 0.0, std::placeholders::_1, alpha_u, alpha_v, eta_, fresnel_only);\n\n    if (reflect) {\n        if (phi_critical_inside_interval) {\n            filon_integrate_cosine(integrand, samples, coeffs.data(), m, 0, phi_critical);\n            filon_integrate_cosine(integrand, samples, coeffs.data(), m, phi_critical, phi_max);\n        } else {\n            filon_integrate_cosine(integrand, samples, coeffs.data(), m, 0, phi_max);\n        }\n    } else {\n        filon_integrate_cosine(integrand, samples, coeffs.data(), m, 0, std::min(phi_critical, phi_max));\n    }\n\n    if (phi_max < math::Pi<double> - math::Epsilon<double>) {\n        /* The fit only occurs on a subset [0, phi_max], where the Fourier\n           basis functions are not orthogonal anymore! The following then\n           does a change of basis to proper Fourier coefficients. */\n\n        auto start = high_resolution_clock::now();\n\n        if (svd_reg) {\n            MatrixX A = coefficient_conversion_matrix(m, 0, phi_max);\n\n            auto svd = A.jacobiSvd(Eigen::ComputeFullU | Eigen::ComputeFullV);\n            const MatrixX &U = svd.matrixU();\n            const MatrixX &V = svd.matrixV();\n            const VectorX &sigma = svd.singularValues();\n\n            if (sigma[0] == 0) {\n                result.resize(1);\n                result(0) = 0;\n                return result;\n            }\n\n            VectorX temp = VectorX::Zero(m);\n            coeffs[0] *= math::Pi<double>;\n            coeffs.tail(m-1) *= 0.5 * math::Pi<double>;\n            for (int i = 0; i < m; ++i) {\n                if (sigma[i] < 1e-9 * sigma[0])\n                    break;\n                temp += V.col(i) * U.col(i).dot(coeffs) / sigma[i];\n            }\n            result = temp;\n        } else {\n            double eps = 1e-5;\n            MatrixX A(2*m, m);\n\n            /* We want the fit to be as close-as-possible on the interval [0, phi_max].\n             We then add soft regularization constraints for the series to be small outside. */\n            A.block(0, 0, m, m) = coefficient_conversion_matrix(m, 0, phi_max);\n            A.block(m, 0, m, m) = coefficient_conversion_matrix(m, phi_max, math::Pi<double>) * eps;\n\n            // Scale coefficients\n            coeffs *= 0.5*math::Pi<double>;\n            coeffs[0] *= 2;\n\n            // QR factorization\n            result = A.colPivHouseholderQr().solve(coeffs);\n        }\n\n        auto end = high_resolution_clock::now();\n        duration<double> diff = (end-start);\n\n        while (true) {\n            double old = microfacet_timer;\n            double update = old + diff.count();\n            if (microfacet_timer.compare_exchange_strong(old, update))\n                break;\n        }\n\n    } else {\n        result = coeffs.head(m);   // No regularization necessary, just get rid of the zero padding from before again.\n    }\n\n    VectorX result_exp(md);\n    result_exp.head(m - 1) = 0.5*result.tail(m - 1).reverse();\n    result_exp[m-1] = result[0];\n    result_exp.tail(m - 1) = 0.5*result.tail(m - 1);\n\n    return result_exp;\n}\n\nvoid microfacet_fourier_series(double mu_o, double mu_i,\n                               double alpha_u, double alpha_v,\n                               std::complex<double> eta_,\n                               int ms, int md, double relerr, MatrixX &result,\n                               int component, int n_samples_phi_s, bool svd_reg) {\n    bool reflect = -mu_i * mu_o > 0;\n\n    bool conductor = (std::imag(eta_) != 0.0);\n    std::complex<double> eta = (-mu_i > 0 || conductor) ? eta_ : std::complex<double>(1) / eta_;\n\n    if (!reflect) {\n        if (conductor) {\n            /* No refraction in conductors */\n            result.resize(1, 1);\n            result(0, 0) = 0;\n            return;\n        }\n    }\n\n    if (component == 2) {\n        /* Only compute shadowing-masking component */\n        VectorX smith_G1_coeffs_i = smith_G1_fourier_series(mu_i, alpha_u, alpha_v, 9);\n        VectorX smith_G1_coeffs_o = smith_G1_fourier_series(mu_o, alpha_u, alpha_v, 9);\n\n        MatrixX G1_coeffs(9, 9);\n        G1_coeffs.setZero();\n        G1_coeffs.diagonal(0) = smith_G1_coeffs_o;\n\n        MatrixX G2_coeffs;\n        convolve_fourier_series_antidiagonal(smith_G1_coeffs_i, G1_coeffs, G2_coeffs);\n\n        result = G2_coeffs;\n        return;\n    }\n\n    /* At grazing angles, microfacet BSDFs can contain arbitrarily high frequencies.\n       This value sets an upper bound on exponential cosine series parameter 'B' to\n       prevent ringing in such cases. */\n    double max_B = max_B_heuristic(md/2+1, relerr);\n\n    /* Here we compute the Fourier coefficients of the Microfacet \"remainder term\", i.e.\n       Fresnel and some normalizations. This is isotropic and thus invariant over phi_s,\n       so we only compute it once here.\n       This part is later convolved with the exponential component, so it makes sense to\n       only compute it accurately for the interval [0, phi_max] in which the exponential\n       component takes large enough values.\n       We find such a conservative interval (useful for all phi_s) with a golden section search here. */\n    VectorX fresnel_coeffs;\n    if (component == 0 || component == 3) {\n        auto gss = [] (const std::function<double(double)>& f, double a, double b, double tol=1e-3) {\n            double gr = 0.5*(std::sqrt(5.0) + 1.0);\n            double inv_gr = 1.0 / gr;\n\n            while (true) {\n                double x1 = b - (b - a) * inv_gr,\n                       x2 = a + (b - a) * inv_gr;\n\n                if (std::abs(b - a) < tol)\n                    break;\n                else if (f(x1) < f(x2))\n                    b = x2;\n                else\n                    a = x1;\n            }\n\n            return 0.5*(a + b);\n        };\n\n        auto get_phi = [&] (double phi_s) {\n            VectorX c;\n            if (reflect) {\n                microfacet_reflection_exp_coeffs(mu_o, mu_i, alpha_u, alpha_v, phi_s, c);\n            } else {\n                microfacet_refraction_exp_coeffs(mu_o, mu_i, alpha_u, alpha_v, phi_s, std::real(eta), c);\n            }\n            double A = c[0];\n            double B = c[1];\n            double C = c[2];\n\n            if (B > max_B && (std::abs(mu_i) < 0.2 || std::abs(mu_o) < 0.2)) {\n                A = A + B - max_B + std::log(enoki::i0e(B) / enoki::i0e(max_B));\n                B = max_B;\n            }\n\n            double phi_max = safe_acos(1.0 + std::log(relerr) / B);\n            return -phi_max - C;\n        };\n\n        double phi_s = gss(get_phi, -math::Pi<double>, math::Pi<double>);\n        double phi_max = std::min(-get_phi(phi_s), math::Pi<double>);\n\n        fresnel_coeffs = fresnel_fourier_series(mu_o, mu_i,\n                                                alpha_u, alpha_v, eta_,\n                                                23, phi_max, svd_reg, component==3);\n    }\n\n    /* Sample phi_s dimension with regular samples and for each, create a Fourier series in phi_d. */\n\n#ifdef USE_FFTW\n    n_samples_phi_s = ms;   // Need as many samples as Fourier orders requested for FFTW integration\n#else\n    n_samples_phi_s = std::max(2, n_samples_phi_s); // Need at least 2 samples in order to do Filon integration.\n#endif\n\n    bool isotropic = false;\n    if (alpha_u == alpha_v) {\n        /* Isotropic Microfacet model. Only compute a 1D Fourier series and\n           zero pad coefficient matrix to have dimension ms x md later. */\n        n_samples_phi_s = 1;\n        isotropic = true;\n    }\n\n    int md_max = 0;\n    std::vector<VectorXc> coeffs;\n    for (int s = 0; s < n_samples_phi_s; ++s) {\n        #ifdef USE_FFTW\n            int n_steps = n_samples_phi_s;\n        #else\n            int n_steps = n_samples_phi_s - 1;\n        #endif\n\n        double phi_s = 2 * math::Pi<double> * s / n_steps;\n\n        if (n_samples_phi_s == 1) phi_s = 0;    // Handle division by zero for isotropic cases where ms == 1\n\n        VectorX c;\n        if (reflect) {\n            microfacet_reflection_exp_coeffs(mu_o, mu_i, alpha_u, alpha_v, phi_s, c);\n        } else {\n            microfacet_refraction_exp_coeffs(mu_o, mu_i, alpha_u, alpha_v, phi_s, std::real(eta), c);\n        }\n        double A = c[0];\n        double B = c[1];\n        double C = c[2];\n\n        /* Minor optimization: don't even bother computing the Fourier series\n           if the contribution to the scattering model is miniscule */\n        if (enoki::i0e(B) * std::exp(A + B) < 1e-10 && component == 0) {\n            VectorXc final_coeffs(1);\n            final_coeffs.setZero();\n            md_max = std::max(md_max, (int) final_coeffs.size());\n            coeffs.push_back(final_coeffs);\n            continue;\n        }\n\n        if (B > max_B && (std::abs(mu_i) < 0.2 || std::abs(mu_o) < 0.2)) {\n            A = A + B - max_B + std::log(enoki::i0e(B) / enoki::i0e(max_B));\n            B = max_B;\n        }\n\n        /* Compute Fourier coefficients of the exponential term */\n        VectorXc exp_coeffs = exp_cos_fourier_series(A, B, C, relerr);\n\n        /* Perform discrete convolution of the exponential & Fresnel series, if requested */\n        VectorXc final_coeffs;\n        if (component == 0) {\n            /* full model */\n            convolve_fourier_series(fresnel_coeffs, exp_coeffs, final_coeffs);\n        } else if (component == 1) {\n            /* exponential part only */\n            final_coeffs = exp_coeffs;\n        } else if (component == 3) {\n            /* Fresnel + remainder part */\n            final_coeffs = fresnel_coeffs.cast<std::complex<double>>();\n        }\n\n        /* Already truncate very low coefficients before considering integration over phi_s */\n        int md_tmp = final_coeffs.size(),\n            mdh_tmp = md_tmp / 2;\n        double zero_coeff = std::abs(final_coeffs[mdh_tmp]);\n        double ref = zero_coeff * relerr;\n\n        if (zero_coeff < relerr) {\n            final_coeffs.resize(1);\n            final_coeffs[0] = 0;\n        } else {\n            int md_trunc = md_tmp;\n            for (int d = mdh_tmp; d >= 0; --d) {\n                int od = d + mdh_tmp;\n                if (std::abs(final_coeffs[od]) >= ref) {\n                    md_trunc = 2*d+1;\n                    break;\n                }\n            }\n            int mdh_trunc = md_trunc / 2;\n\n            VectorXc truncated = final_coeffs.segment(mdh_tmp - mdh_trunc, md_trunc);\n            final_coeffs.resize(truncated.size());\n            final_coeffs = truncated;\n        }\n\n        md_max = std::max(md_max, (int) final_coeffs.size());\n        coeffs.push_back(final_coeffs);\n    }\n\n    /* Collect data in matrix */\n    int md_max_half = md_max / 2;\n    MatrixXc temp(n_samples_phi_s, md_max);\n    temp.setZero();\n    for (int i = 0; i < n_samples_phi_s; ++i) {\n        int md = coeffs[i].size();\n        int mdh = md / 2;\n        temp.block(i, md_max_half - mdh, 1, md) = coeffs[i].transpose();\n    }\n\n    MatrixX result_tmp(ms, md_max);\n    result_tmp.setZero();\n\n    /* Integrate the sampled Fourier series over phi_s. */\n\n    if (ms == 1) {\n        /* We only have a 1D Fourier series, thus no integration over phi_s needed. */\n        result_tmp.row(0) = temp.row(0).real();\n    } else {\n        #ifdef USE_FFTW\n            /* Use FFT to compute Fourier Series of phi_s dimension */\n            std::complex<double> *data       = (std::complex<double> *) fftw_malloc(sizeof(std::complex<double>) * ms),\n                                 *spectrum   = (std::complex<double> *) fftw_malloc(sizeof(std::complex<double>) * ms);\n\n            fftw_plan_with_nthreads(1);\n            fftw_plan plan = fftw_plan_dft_1d(ms, (fftw_complex *) data, (fftw_complex *) spectrum, FFTW_FORWARD, FFTW_ESTIMATE);\n\n            for (int d = 0; d < md_max; ++d) {\n                for (int s = 0; s < ms; ++s) {\n                    data[s] = temp(s, d);\n                }\n                fftw_execute(plan);\n                for (int s = 0; s < ms; ++s) {\n                    temp(s, d) = spectrum[s] / (double) ms;\n                }\n            }\n\n            fftw_destroy_plan(plan);\n            fftw_free(spectrum);\n            fftw_free(data);\n\n            /* Reorder Fourier coefficients. And we know that the coefficients must be real. */\n            int msh = ms / 2;\n            result_tmp.row(msh) = temp.row(0).real();\n            result_tmp.block(0, 0, msh, md_max) = temp.block(msh + 1, 0, msh, md_max).real();\n            result_tmp.block(msh + 1, 0, msh, md_max) = temp.block(1, 0, msh, md_max).real();\n        #else\n            if (isotropic || component == 3) {\n                /* No integration over phi_s necessary */\n                int msh = ms / 2;\n                result_tmp.block(msh, 0, 1, md_max) = temp.real();\n            } else {\n                /* Compute Fourier series over phi_s with Filon integration.\n                   We can save some time here by exploiting symmetry. Only integrate\n                   one half of the data and then mirror it. */\n                MatrixXc result_tmp_complex(ms, md_max);\n                result_tmp_complex.setZero();\n                for (int d = 0; d <= md_max_half; ++d) {\n                    int od = d + md_max_half;\n                    filon_integrate_exp(temp.col(od).data(), n_samples_phi_s, result_tmp_complex.col(od).data(), ms);\n                }\n                result_tmp_complex.block(0, 0, ms, md_max_half) = result_tmp_complex.block(0, md_max_half+1, ms, md_max_half);\n                result_tmp_complex.block(0, 0, ms, md_max_half) = result_tmp_complex.block(0, 0, ms, md_max_half).colwise().reverse().eval();\n                result_tmp_complex.block(0, 0, ms, md_max_half) = result_tmp_complex.block(0, 0, ms, md_max_half).rowwise().reverse().eval();\n\n                /* We know that the coefficients must be real. */\n                result_tmp = result_tmp_complex.real();\n            }\n\n        #endif\n    }\n\n    for (int s = 0; s < ms; ++s) {\n      for (int d = 0; d < md_max; ++d) {\n        if (std::abs(result_tmp(s, d)) < 1e-9) result_tmp(s, d) = 0;\n      }\n    }\n\n    /* Truncate Fourier series */\n    int md_trunc = md_max,\n        ms_trunc = ms;\n\n    int msh = ms / 2,\n        mdh = md_max_half;\n\n    double zero_coeff = std::abs(result_tmp(msh, mdh));\n    double ref = zero_coeff * relerr * 0.01;\n\n    // Check in phi_s dimension\n    for (int s = 0; s <= msh; ++s) {\n        bool keep = false;\n        for (int d = -mdh; d <= mdh; ++d) {\n            double value = std::abs(result_tmp(s + msh, d + mdh));\n            if (value > ref) keep = true;\n        }\n        if (keep) {\n            ms_trunc = 2*s+1;\n        } else {\n            break;\n        }\n    }\n\n    // Check in phi_d dimension\n    for (int d = 0; d <= mdh; ++d) {\n        bool keep = false;\n        for (int s = -msh; s <= msh; ++s) {\n            double value = std::abs(result_tmp(s + msh, d + mdh));\n            if (value > ref) keep = true;\n        }\n        if (keep) {\n            md_trunc = 2*d+1;\n        } else {\n            break;\n        }\n    }\n\n    int msh_trunc = ms_trunc / 2,\n        mdh_trunc = md_trunc / 2;\n    result.resize(ms_trunc, md_trunc);\n\n    result = result_tmp.block(msh - msh_trunc, mdh - mdh_trunc, ms_trunc, md_trunc);\n\n    if (component == 0) {\n        /* Requested full model: add Smith Shadowing-masking term via 2 diagonal convolutions */\n        VectorX smith_G1_coeffs_i = smith_G1_fourier_series(mu_i, alpha_u, alpha_v, 19);\n        VectorX smith_G1_coeffs_o = smith_G1_fourier_series(mu_o, alpha_u, alpha_v, 19);\n\n        MatrixX tmp;\n        convolve_fourier_series_diagonal(smith_G1_coeffs_o, result, tmp);\n        convolve_fourier_series_antidiagonal(smith_G1_coeffs_i, tmp, result);\n    }\n}\n\nbool microfacet_inside_lowfreq_interval(double mu_o, double mu_i, double phi_s,\n                                        double alpha_u, double alpha_v,\n                                        std::complex<double> eta,\n                                        double phi_d, double relerr) {\n    bool reflect = -mu_i * mu_o > 0;\n\n    VectorX c;\n    if (reflect) {\n        microfacet_reflection_exp_coeffs(mu_o, mu_i, alpha_u, alpha_v, phi_s, c);\n    } else {\n        microfacet_refraction_exp_coeffs(mu_o, mu_i, alpha_u, alpha_v, phi_s, std::real(eta), c);\n    }\n    double B = c[1];\n    double C = c[2];\n\n    /* Ideally, we would also remove high frequencies here,\n       but then this would have to depend on our chosen md as well. */\n    // if (B > max_B) {\n    //     A = A + B - max_B + std::log(enoki::i0e(B) / enoki::i0e(max_B));\n    //     B = max_B;\n    // }\n\n    double phi_max = safe_acos(1.0 + std::log(relerr) / B),\n           phi_a = -phi_max - C,\n           phi_b = +phi_max - C;\n\n    if (phi_d > phi_a && phi_d < phi_b)\n        return true;\n\n    return false;\n}\n\nNAMESPACE_END(mitsuba)\n", "meta": {"hexsha": "2e7a86350fcad550e54c83639c6cf4d4be998f32", "size": 37711, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/liblayer/microfacet.cpp", "max_stars_repo_name": "tizian/layer-laboratory", "max_stars_repo_head_hexsha": "008cc94b76127e9eb74227fcd3d0145da8ddec30", "max_stars_repo_licenses": ["CNRI-Python"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2020-07-24T03:19:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T10:56:12.000Z", "max_issues_repo_path": "src/liblayer/microfacet.cpp", "max_issues_repo_name": "tizian/layer-laboratory", "max_issues_repo_head_hexsha": "008cc94b76127e9eb74227fcd3d0145da8ddec30", "max_issues_repo_licenses": ["CNRI-Python"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-04-07T22:30:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-08T00:55:36.000Z", "max_forks_repo_path": "src/liblayer/microfacet.cpp", "max_forks_repo_name": "tizian/layer-laboratory", "max_forks_repo_head_hexsha": "008cc94b76127e9eb74227fcd3d0145da8ddec30", "max_forks_repo_licenses": ["CNRI-Python"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-06-08T08:25:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-05T22:13:08.000Z", "avg_line_length": 36.8271484375, "max_line_length": 141, "alphanum_fraction": 0.5516162393, "num_tokens": 10724, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045817875225, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.46783763559461916}}
{"text": "#include <string>\n#include <sstream>\n#include <Eigen/Dense>\n#include <boost/array.hpp>\n#include <boost/multi_array.hpp>\n#include <boost/python.hpp>\n\nusing namespace boost::python;\ntypedef float fptype;\n\n#ifndef TRI_CUBIC_INTERPOLATOR_H\n#define TRI_CUBIC_INTERPOLATOR_H\n\n//This code is adapted from https://github.com/deepzot/likely\nclass TriCubicInterpolator{\n  // Performs tri-cubic interpolation within a 3D periodic grid.\n  // Based on http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.89.7835\n  public:\n    TriCubicInterpolator(list data, list nkpoints);\n    fptype ip(list xyz);\n  private:\n    boost::multi_array<fptype,1> _data;\n    fptype _spacing;\n    int _n1, _n2, _n3;\n    int _i1, _i2, _i3;\n    bool _initialized;\n    Eigen::Matrix<fptype,64,1> _coefs;\n    Eigen::Matrix<fptype,64,64> _C;\n    inline int _index(int i1, int i2, int i3) const {\n        if((i1 %= _n1) < 0) i1 += _n1;\n        if((i2 %= _n2) < 0) i2 += _n2;\n        if((i3 %= _n3) < 0) i3 += _n3;\n        return i1 + _n1*(i2 + _n2*i3);\n\t}\n};\n\n#endif\n", "meta": {"hexsha": "2b39714cce18d1b41d1fc8920690fbd3102a38bb", "size": 1030, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "AlGDock/ForceFields/Grid/original-pytricubic/tricubic.hpp", "max_stars_repo_name": "CCBatIIT/AlGDock", "max_stars_repo_head_hexsha": "25c376e9d860d50696f5e20f1b107d289ec0903c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2015-06-16T19:25:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-27T05:50:47.000Z", "max_issues_repo_path": "AlGDock/ForceFields/Grid/original-pytricubic/tricubic.hpp", "max_issues_repo_name": "biocheming/AlGDock", "max_issues_repo_head_hexsha": "25c376e9d860d50696f5e20f1b107d289ec0903c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2015-05-06T21:05:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-11T09:51:45.000Z", "max_forks_repo_path": "AlGDock/ForceFields/Grid/original-pytricubic/tricubic.hpp", "max_forks_repo_name": "biocheming/AlGDock", "max_forks_repo_head_hexsha": "25c376e9d860d50696f5e20f1b107d289ec0903c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 23.0, "max_forks_repo_forks_event_min_datetime": "2015-04-13T21:11:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T00:25:42.000Z", "avg_line_length": 27.1052631579, "max_line_length": 77, "alphanum_fraction": 0.6689320388, "num_tokens": 347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4677955635723806}}
{"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_FUNCTION_DIVFLOOR_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_DIVFLOOR_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-arithmetic\n    Function object implementing divfloor capabilities\n\n    Computes the floor of the division.\n\n    @par semantic:\n    For any given value @c x,  @c y of type @c T:\n\n    @code\n    T r = divfloor(x, y);\n    @endcode\n\n    The code is similar to:\n\n    @code\n    T r = floor(x/y);\n    @endcode\n\n    for integral types, if y is @ref Zero, it returns @ref Valmax or @ref Valmin\n    if x is positive (resp. negative) and @ref Zero if x is @ref Zero.\n    Take also care that dividing @ref Valmin by -1 for signed integral types has\n    undefined behaviour.\n\n    @see  divides, rec, divs, divfix, divround, divround2even\n\n  **/\n  const boost::dispatch::functor<tag::divfloor_> divfloor = {};\n} }\n#endif\n\n#include <boost/simd/function/scalar/divfloor.hpp>\n#include <boost/simd/function/simd/divfloor.hpp>\n\n#endif\n", "meta": {"hexsha": "6a0b2216babeff69ee6124ba764391a9e74bd6b5", "size": 1427, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/divfloor.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/function/divfloor.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/function/divfloor.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": 25.9454545455, "max_line_length": 100, "alphanum_fraction": 0.6040644709, "num_tokens": 335, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4677955635723806}}
{"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/**\n * @file odeint.cpp ODE numerical integration example.\n */\n\n#include <boost/numeric/odeint.hpp>\n\n#include <matplot/matplot.h>\n\n#include \"smooth/bundle.hpp\"\n#include \"smooth/compat/odeint.hpp\"\n#include \"smooth/so3.hpp\"\n#include \"smooth/tn.hpp\"\n\n#include \"plot_tools.hpp\"\n\nusing matplot::plot;\nusing std::views::transform;\n\n/**\n * @brief Numerically solve the following ODE on \\f$ \\mathbb{SO}(3) \\times \\mathbb{R}^3 \\f$:\n */\nint main(int argc, char const * argv[])\n{\n  using state_t = smooth::Bundle<smooth::SO3d, smooth::SO3d>;\n  using deriv_t = typename state_t::Tangent;\n\n  std::srand(2);\n\n  // equilibrium point\n  const smooth::SO3d Xc = smooth::SO3d::Identity();\n\n  const smooth::SO3d X1 = smooth::SO3d::Random();\n  const smooth::SO3d X2 = smooth::SO3d::Random();\n  const smooth::SO3d::Tangent d = 0.1 * smooth::SO3d::Tangent::Random();\n\n  auto ode = [&](const state_t & state, deriv_t & deriv, double) {\n    deriv.head<3>() = 0.1 * (state.part<0>() - Xc);\n    deriv.tail<3>() = 0.1 * (state.part<1>() - Xc);\n  };\n\n  auto stepper = boost::numeric::odeint::\n    runge_kutta4<state_t, double, deriv_t, double, boost::numeric::odeint::vector_space_algebra>();\n\n  std::vector<double> tvec;\n  std::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d>> v1, v2;\n\n  state_t state1(X1, X1 + d), state2(X2, X2 + d);\n\n  boost::numeric::odeint::integrate_const(\n    stepper, ode, state1, 0., 10., 0.01, [&](const state_t & s, double t) {\n      tvec.push_back(t);\n      v1.push_back(s.part<1>() - s.part<0>());\n    });\n\n  boost::numeric::odeint::integrate_const(\n    stepper, ode, state2, 0., 10., 0.01, [&](const state_t & s, double t) {\n      v2.push_back(s.part<1>() - s.part<0>());\n    });\n\n  matplot::figure();\n  matplot::hold(matplot::on);\n  plot(tvec, r2v(v1 | transform([](auto s) { return s(0); })), \"r\") ->line_width(2);\n  plot(tvec, r2v(v2 | transform([](auto s) { return s(0); })), \":r\") ->line_width(2);\n  plot(tvec, r2v(v1 | transform([](auto s) { return s(1); })), \"g\") ->line_width(2);\n  plot(tvec, r2v(v2 | transform([](auto s) { return s(1); })), \":g\") ->line_width(2);\n  plot(tvec, r2v(v1 | transform([](auto s) { return s(2); })), \"b\") ->line_width(2);\n  plot(tvec, r2v(v2 | transform([](auto s) { return s(2); })), \":b\") ->line_width(2);\n  matplot::title(\"Difference\");\n\n  matplot::show();\n\n  return 0;\n}\n", "meta": {"hexsha": "922e02a862e4fbac56d27a88ba490956bc881aa8", "size": 3595, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/odeint_diff.cpp", "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": "examples/odeint_diff.cpp", "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": "examples/odeint_diff.cpp", "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": 36.3131313131, "max_line_length": 99, "alphanum_fraction": 0.6695410292, "num_tokens": 1061, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.46779556357238056}}
{"text": "#include <iostream>\n#include <mist/mist.h>\n#include <itkSignedMaurerDistanceMapImageFilter.h>\n#include <Eigen/Core>\n#include \"ItkImageIO.h\"\n#include \"dataIO.h\"\n#include \"configs.h\"\n\ntypedef unsigned char label_t;\ntypedef unsigned char mask_t;\ntypedef double feat_t;\ntypedef double atlas_t;\n\nint main(int argc, char **argv) {\n\n\tif(argc != 8) {\n\t\tstd::cerr << \"Usage:\" << std::endl;\n\t\tstd::cerr << argv[0] << \" <input feature directory> <input label directory> \"\n\t\t\t\t  << \" <input abdominal cavity mask directory> \"\n\t\t\t\t  << \" <output directory> <filename list> <feature name list> <distance margin>\"\n\t\t\t      << std::endl;\n\t\treturn EXIT_FAILURE;\n\t}\n\n\tstd::cout << \"----- Read data list -----\" << std::endl;\n\tconst std::string input_feat_dir = std::string(argv[1]) + \"/\";\n\tconst std::string input_label_dir = std::string(argv[2]) + \"/\";\n\tconst std::string input_abd_mask_dir = std::string(argv[3]) + \"/\";\n\tconst std::string output_dir = std::string(argv[4]) + \"/\";\n\tconst std::string filename_list_path = argv[5];\n\tconst std::string feature_name_list_path = argv[6];\n\tconst double margin = std::stod(argv[7]);\n\n\tstd::list<std::string> filename_list;\n\tstd::list<std::string> feature_name_list;\n\tif (!get_data_list(filename_list_path, filename_list) || \n\t\t!get_data_list(feature_name_list_path, feature_name_list)) {\n\t\treturn EXIT_FAILURE;\n\t}\n\tconst int num_cases = filename_list.size();\n\tconst int num_features = feature_name_list.size();\n\n\tstd::cout << \"----- Compute initial value for each organs -----\" << std::endl;\n\tfor (int l = 0; l < NUM_LABELS; ++l) {\n\t\tstd::cout << \"Label: \" << LABEL_NAMES[l] << std::endl;\n\t\tEigen::MatrixXd total_feat_mean = Eigen::MatrixXd::Zero(num_features, 1);\n\t\tEigen::MatrixXd total_feat_covariance = Eigen::MatrixXd::Zero(num_features, num_features);\n\n\t\tfor (auto case_itr = filename_list.begin(); case_itr != filename_list.end(); ++case_itr) {\n\t\t\tstd::cout << \"Case: \" << *case_itr << std::endl;\n\n\t\t\tstd::cout << \"---- Load feature img ----\" << std::endl;\n\t\t\tstd::vector<std::vector<feat_t>> feature_img_list(num_features);\n\t\t\tstd::vector<ImageIO<NDIMS>> feature_mhd_list(num_features);\n\t\t\tfor (auto feat_itr = feature_name_list.begin(); feat_itr != feature_name_list.end(); ++feat_itr) {\n\t\t\t\tsize_t i = std::distance(feature_name_list.begin(), feat_itr);\n\t\t\t\tfeature_mhd_list[i].Read(feature_img_list[i], \n\t\t\t\t\t\t\t\t\t\t\tinput_feat_dir + *feat_itr + \"/\" + *case_itr);\n\t\t\t}\n\n\t\t\tstd::cout << \"---- Load label img ----\" << std::endl;\n\t\t\tstd::vector<label_t> label_img;\n\t\t\tImageIO<NDIMS> label_mhd;\n\t\t\tlabel_mhd.Read(label_img, input_label_dir + *case_itr);\n\t\t\tconst int xe = label_mhd.Size(0);\n\t\t\tconst int ye = label_mhd.Size(1);\n\t\t\tconst int ze = label_mhd.Size(2);\n\t\t\tconst int se = xe*ye*ze;\n\t\t\tconst double x_spacing = label_mhd.Spacing(0);\n\t\t\tconst double y_spacing = label_mhd.Spacing(1);\n\t\t\tconst double z_spacing = label_mhd.Spacing(2);\n\t\t\t\n\t\t\tstd::vector<mask_t> abd_mask_img;\n\t\t\tImageIO<NDIMS> abd_mask_mhd;\n\t\t\tabd_mask_mhd.Read(abd_mask_img, input_abd_mask_dir + *case_itr);\n\n\t\t\tstd::cout << \"----- Preprocessing for label -----\" << std::endl;\n\t\t\tif (l == NUM_LABELS - 1) { // for others\n\t\t\t\tfor (int s = 0; s < se; s++) {\n\t\t\t\t\tif (label_img.at(s) == REMOVE_LABEL_NUM) label_img.at(s) = 0;\n\t\t\t\t\telse if (abd_mask_img.at(s) && !label_img.at(s)) label_img.at(s) = 1;\n\t\t\t\t\telse label_img.at(s) = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse { // for organs\n\t\t\t\tfor (int s = 0; s < se; s++) {\n\t\t\t\t\tif (label_img.at(s) == l + 1) label_img.at(s) = 1;\n\t\t\t\t\telse label_img.at(s) = 0;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tstd::cout << \"----- Distance transformation -----\" << std::endl;\n\t\t\tusing DistPixelType = double;\n\t\t\tusing LabelPixelType = label_t;\n\t\t\tusing DistImageType = itk::Image<DistPixelType, NDIMS>;\n\t\t\tusing LabelImageType = itk::Image<LabelPixelType, NDIMS>;\n\t\t\tusing SignedMaurerDistanceMapImageFilterType = \n\t\t\t\titk::SignedMaurerDistanceMapImageFilter<LabelImageType, DistImageType>;\n\t\t\tSignedMaurerDistanceMapImageFilterType::Pointer distanceMapImageFilter =\n\t\t\t\tSignedMaurerDistanceMapImageFilterType::New();\n\t\t\tdistanceMapImageFilter->SetInput(label_mhd.ConvertVector2Itk(label_img));\n\t\t\ttry {\n\t\t\t\tdistanceMapImageFilter->Update();\n\t\t\t}\n\t\t\tcatch (itk::ExceptionObject & error)\n\t\t\t{\n\t\t\t\tstd::cerr << \"Error:\" << error << std::endl;\n\t\t\t\treturn EXIT_FAILURE;\n\t\t\t}\n\t\t\tstd::vector<DistPixelType> dist_img;\n\t\t\tlabel_mhd.ConvertItk2Vector(distanceMapImageFilter->GetOutput(), dist_img);\n\n\t\t\tstd::cout << \"----- Calculate parameter ------\" << std::endl;\n\t\t\tint label_counter = 0;\n\t\t\tEigen::MatrixXd feat_mean = Eigen::MatrixXd::Zero(num_features, 1);\n\t\t\tEigen::MatrixXd feat_covariance = Eigen::MatrixXd::Zero(num_features, num_features);\n\t\t\tfor (int s = 0; s < se; s++) {\n\t\t\t\tif (dist_img.at(s) < -(double)(margin / x_spacing)) {\n\t\t\t\t\tlabel_counter++;\n\t\t\t\t\tfor (int f = 0; f < num_features; f++) {\n\t\t\t\t\t\tfeat_mean(f, 0) += feature_img_list[f].at(s);\n\t\t\t\t\t\tfor (int ff = f; ff < num_features; ff++) {\n\t\t\t\t\t\t\tfeat_covariance(f, ff) += feature_img_list[f].at(s) * feature_img_list[ff].at(s);\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\tfeat_mean /= label_counter;\n\t\t\tfor (int f = 0; f < num_features; f++) {\n\t\t\t\tfor (int ff = 0; ff < num_features; ff++) {\n\t\t\t\t\tfeat_covariance(f, ff) = feat_covariance(f, ff) / label_counter - feat_mean(f, 0) * feat_mean(ff, 0);\n\t\t\t\t}\n\t\t\t}\n\t\t\ttotal_feat_mean += feat_mean;\n\t\t\ttotal_feat_covariance += feat_covariance;\n\n\t\t}/* Case loop */\n\t\ttotal_feat_mean /= (double)num_cases;\n\t\ttotal_feat_covariance /= (double)num_cases;\n\t\tstd::cout << \"----- Save param -----\" << std::endl;\n\t\tstd::string result_dir = output_dir + LABEL_NAMES[l];\n\t\tmake_dir(result_dir);\n\t\tsave_param_as_csv(total_feat_mean, result_dir + \"/mean_param.csv\");\n\t\tsave_param_as_csv(total_feat_covariance, result_dir + \"/covariance_param.csv\");\n\t\twrite_raw_and_txt(total_feat_mean, result_dir + \"/mean_param\");\n\t\twrite_raw_and_txt(total_feat_covariance, result_dir + \"/covariance_param\");\n\n\t} /* Label loop */\n\n\treturn EXIT_SUCCESS;\n}", "meta": {"hexsha": "bbfb87dea1410a7b45d20aa98aed1ccd6c7ad47b", "size": 5914, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "calc_init_val/main.cpp", "max_stars_repo_name": "simizlab/atlas-guided-em-algorithm", "max_stars_repo_head_hexsha": "54dd2df19f65724b1ac6957c06faca39d5b40215", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-05-30T07:32:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-02T02:43:19.000Z", "max_issues_repo_path": "calc_init_val/main.cpp", "max_issues_repo_name": "simizlab/atlas-guided-em-algorithm", "max_issues_repo_head_hexsha": "54dd2df19f65724b1ac6957c06faca39d5b40215", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "calc_init_val/main.cpp", "max_forks_repo_name": "simizlab/atlas-guided-em-algorithm", "max_forks_repo_head_hexsha": "54dd2df19f65724b1ac6957c06faca39d5b40215", "max_forks_repo_licenses": ["Apache-2.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.1655629139, "max_line_length": 106, "alphanum_fraction": 0.6670612107, "num_tokens": 1676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.46779556357238045}}
{"text": "#include <Eigen/Dense>\r\n#include <cmath>\r\n#include <random>\r\n#include \"thermostats.h\"\r\n#include \"constants.h\"\r\n\r\nstd::random_device g_device;\r\nstd::mt19937 g_mt_rand(g_device());\r\nstd::uniform_real_distribution<double> distribution(0.0, 1.0);\r\n  \r\nThermostat::Thermostat(double aim_temp) {\r\n    m_aim_temp = aim_temp;\r\n}\r\n\r\nVelocityRescale::VelocityRescale(int steps, double aim_temp) {\r\n    m_steps = steps;\r\n    m_aim_temp = aim_temp;\r\n}\r\n\r\nBerendsen::Berendsen(double timescale, double aim_temp) {\r\n    m_timescale = timescale;\r\n    m_aim_temp = aim_temp;\r\n}\r\n\r\nAndersen::Andersen(double freq, double timestep, double aim_temp) {\r\n    // The user provides us with a timestep in ps\r\n    // and a collision frequency in ps^-1\r\n   \r\n    m_cutoff = freq * timestep;\r\n    m_aim_temp = aim_temp;\r\n}\r\n\r\nvoid Berendsen::apply(Eigen::ArrayXXd &velocities, const Eigen::ArrayXd &masses) {\r\n    auto velocities_squared = (velocities * velocities).rowwise().sum();\r\n    auto effective_temp = (0.5 * masses * velocities_squared).sum() / constants::boltzHar;\r\n    auto delta_T = effective_temp - m_aim_temp / m_timescale;\r\n}\r\n      \r\nvoid VelocityRescale::apply(Eigen::ArrayXXd &velocities, const Eigen::ArrayXd &masses) {\r\n    auto velocities_squared = (velocities * velocities).rowwise().sum();\r\n    auto translational_energy = (0.5 * masses * velocities_squared).sum();\r\n    double thermal_energy = constants::boltzHar * m_aim_temp;\r\n    double velocity_factor = sqrt(thermal_energy / translational_energy);\r\n    velocities *= velocity_factor;\r\n}\r\n\r\nvoid Andersen::apply(Eigen::ArrayXXd &velocities, const Eigen::ArrayXd &masses) {\r\n    //Implements an Andersen thermostat. This keeps the system at\r\n    //constant temperature by the following method:\r\n    //    1) For each atom, calculate a \"collision chance\" in the last\r\n    //       timestep. If this chance > collision frequency * timestep,\r\n    //       then progress to 2\r\n    //    2) Simulate a \"collision\" with an external heat bath. This\r\n    //       randomly selects the velocity from a Maxwell-Boltzmann distribution\r\n\r\n\r\n    for (int atom = 0; atom < velocities.rows(); ++atom) {\r\n        double random_num = distribution(g_mt_rand);\r\n        \r\n        if (random_num > m_cutoff) {\r\n            // The lucky atom is hit!\r\n            double mean = 0.0;\r\n            double variance = std::sqrt(constants::boltz * m_aim_temp / masses(atom));\r\n            std::normal_distribution<double> gaussian(mean, variance);\r\n            for (int dim=0; dim < velocities.cols(); ++dim) {\r\n                velocities(atom, dim) = gaussian(g_mt_rand);\r\n            }\r\n        }\r\n    }\r\n}", "meta": {"hexsha": "eebe97ad37adbfad9fa5a1cc8423f642c947ac3d", "size": 2631, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/thermostats.cpp", "max_stars_repo_name": "Matt-HJ-Bailey/TinyMD", "max_stars_repo_head_hexsha": "71df0712b916083394fb259a380300b6b613cde7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/thermostats.cpp", "max_issues_repo_name": "Matt-HJ-Bailey/TinyMD", "max_issues_repo_head_hexsha": "71df0712b916083394fb259a380300b6b613cde7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/thermostats.cpp", "max_forks_repo_name": "Matt-HJ-Bailey/TinyMD", "max_forks_repo_head_hexsha": "71df0712b916083394fb259a380300b6b613cde7", "max_forks_repo_licenses": ["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.5857142857, "max_line_length": 91, "alphanum_fraction": 0.6583048271, "num_tokens": 640, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4677955572871366}}
{"text": "// Copyright 2020 Erik Teichmann <kontakt.teichmann@gmail.com>\n\n#ifndef INCLUDE_SAM_ANALYSIS_SAVITZKY_GOLAY_HPP_\n#define INCLUDE_SAM_ANALYSIS_SAVITZKY_GOLAY_HPP_\n\n#include <Eigen/Dense>\n\n#include <stdexcept>\n#include <vector>\n\nnamespace sam {\n\ntemplate<typename state_type = std::vector<double>>\nstd::vector<std::vector<double>> SavitzkyGolayFilter(double stepsize,\n                                                     state_type state,\n                                                     unsigned int n_points,\n                                                     unsigned int derivatives);\n\n\n// Implementation\n\nEigen::MatrixXd CalculateConvolutionCoefficients(unsigned int n_points,\n                                                 unsigned int derivatives) {\n  unsigned int n_left = n_points/2;\n  Eigen::MatrixXd J(n_points, derivatives);\n  for (unsigned int i = 0; i < n_points; ++i) {\n    double z = static_cast<int>(i) - static_cast<int>(n_left);\n    for (unsigned int j = 0; j < derivatives; ++j) {\n      J(i, j) = pow(z, j);\n    }\n  }\n  return (J.transpose()*J).inverse()*J.transpose();\n}\n\nint factorial(unsigned int n) {\n  int factorial = 1.;\n  for (unsigned int i = 1; i < n+1; ++i) factorial *= i;\n  return factorial;\n}\n\ntemplate<typename state_type>\nstd::vector<std::vector<double>> SavitzkyGolayFilter(double stepsize,\n                                                     state_type state,\n                                                     unsigned int n_points,\n                                                     unsigned int derivatives) {\n  if (n_points%2 == 0) {\n    throw std::invalid_argument(\"Number of points for Savitzky-Golay Filter \"\n        \"has to be uneven.\");\n  }\n  if (n_points < derivatives) {\n    throw std::invalid_argument(\"Number of points has to be bigger than \"\n        \"number of derivatives in Savitzky-Golay Filter.\");\n  }\n  Eigen::MatrixXd coefficients = CalculateConvolutionCoefficients(n_points,\n      derivatives);\n  std::vector<std::vector<double>> a(derivatives);\n  for (size_t point = n_points/2; point < state.size() - n_points/2; ++point) {\n    for (size_t deriv = 0; deriv < derivatives; ++deriv) {\n      double sum = 0.;\n      for (int i = -static_cast<int>(n_points)/2;\n           i <= static_cast<int>(n_points)/2; ++i) {\n        sum += coefficients(deriv, i + n_points/2)*state[point + i];\n      }\n      sum *= factorial(deriv)/pow(stepsize, deriv);\n      a[deriv].push_back(sum);\n    }\n  }\n  return a;\n}\n\n}  // namespace sam\n\n#endif  // INCLUDE_SAM_ANALYSIS_SAVITZKY_GOLAY_HPP_\n", "meta": {"hexsha": "51379a2ae87b8557ff2b9fed32ad9b7c304c2bce", "size": 2538, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/sam/analysis/savitzky_golay.hpp", "max_stars_repo_name": "boundter/SAM", "max_stars_repo_head_hexsha": "658b822e6b3eb01f478a6181ff526cfc8f32aa5d", "max_stars_repo_licenses": ["MIT"], "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/sam/analysis/savitzky_golay.hpp", "max_issues_repo_name": "boundter/SAM", "max_issues_repo_head_hexsha": "658b822e6b3eb01f478a6181ff526cfc8f32aa5d", "max_issues_repo_licenses": ["MIT"], "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/sam/analysis/savitzky_golay.hpp", "max_forks_repo_name": "boundter/SAM", "max_forks_repo_head_hexsha": "658b822e6b3eb01f478a6181ff526cfc8f32aa5d", "max_forks_repo_licenses": ["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.2972972973, "max_line_length": 80, "alphanum_fraction": 0.5886524823, "num_tokens": 596, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4677955572871366}}
{"text": "// SPDX-License-Identifier: Apache-2.0\n// \n// Copyright 2015 Conrad Sanderson (http://conradsanderson.id.au)\n// Copyright 2015 National ICT Australia (NICTA)\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS 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 <armadillo>\n#include \"catch.hpp\"\n\nusing namespace arma;\n\n\nTEST_CASE(\"gen_randu_1\")\n  {\n  const uword n_rows = 100;\n  const uword n_cols = 101;\n\n  mat A(n_rows,n_cols, fill::randu);\n\n  mat B(n_rows,n_cols); B.randu();\n\n  mat C; C.randu(n_rows,n_cols);\n\n  REQUIRE( (accu(A)/A.n_elem) == Approx(0.5).margin(0.02) );\n  REQUIRE( (accu(B)/A.n_elem) == Approx(0.5).margin(0.02) );\n  REQUIRE( (accu(C)/A.n_elem) == Approx(0.5).margin(0.02) );\n\n  REQUIRE( (mean(vectorise(A))) == Approx(0.5).margin(0.02) );\n  }\n\n\n\nTEST_CASE(\"gen_randu_2\")\n  {\n  mat A(50,60,fill::zeros);\n\n  A(span(1,48),span(1,58)).randu();\n\n  REQUIRE( accu(A.head_cols(1)) == Approx(0.0).margin(0.001) );\n  REQUIRE( accu(A.head_rows(1)) == Approx(0.0).margin(0.001) );\n\n  REQUIRE( accu(A.tail_cols(1)) == Approx(0.0).margin(0.001) );\n  REQUIRE( accu(A.tail_rows(1)) == Approx(0.0).margin(0.001) );\n\n  REQUIRE( mean(vectorise(A(span(1,48),span(1,58)))) == Approx(double(0.5)).margin(0.02) );\n  }\n\n", "meta": {"hexsha": "b84d3249370ac080e5b1aeadef896a3c078c7f89", "size": 1752, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests2/gen_randu.cpp", "max_stars_repo_name": "getfiit/armadillo-code", "max_stars_repo_head_hexsha": "3a896deca12a0f596b52d84185ebfad65df650b7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests2/gen_randu.cpp", "max_issues_repo_name": "getfiit/armadillo-code", "max_issues_repo_head_hexsha": "3a896deca12a0f596b52d84185ebfad65df650b7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests2/gen_randu.cpp", "max_forks_repo_name": "getfiit/armadillo-code", "max_forks_repo_head_hexsha": "3a896deca12a0f596b52d84185ebfad65df650b7", "max_forks_repo_licenses": ["Apache-2.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.2, "max_line_length": 91, "alphanum_fraction": 0.6455479452, "num_tokens": 529, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.467717483415474}}
{"text": "//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\file BlockMatrixBase.hpp\n///\n/// \\author Sean Anderson, ASRL\n//////////////////////////////////////////////////////////////////////////////////////////////\n\n#ifndef STEAM_BLOCK_MATRIX_BASE_HPP\n#define STEAM_BLOCK_MATRIX_BASE_HPP\n\n#include <vector>\n\n#include <Eigen/Core>\n\n#include <steam/blockmat/BlockMatrixHelpers.hpp>\n\nnamespace steam {\n\n/////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Interface for a block matrix\n/////////////////////////////////////////////////////////////////////////////////////////////\nclass BlockMatrixBase\n{\n public:\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Default constructor, matrix size must still be set before using\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  BlockMatrixBase();\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Rectangular matrix constructor\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  BlockMatrixBase(const std::vector<unsigned int>& blkRowSizes,\n                  const std::vector<unsigned int>& blkColSizes);\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Block-size-symmetric matrix constructor, pure scalar symmetry is still optional\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  BlockMatrixBase(const std::vector<unsigned int>& blkSqSizes, bool symmetric = false);\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Interface for zero'ing all entries\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  virtual void zero() = 0;\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Get indexing object\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  const BlockMatrixIndexing& getIndexing() const;\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Get if matrix is symmetric on a scalar level\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  bool isSymmetric() const;\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Adds the matrix to the block entry at index (r,c), block dim must match\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  virtual void add(unsigned int r, unsigned int c, const Eigen::MatrixXd& m) = 0;\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Returns a reference to the value at (r,c), if it exists\n  ///        *Note this throws an exception if matrix is symmetric and you request a lower\n  ///         triangular entry. For read operations, use copyAt(r,c).\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  virtual Eigen::MatrixXd& at(unsigned int r, unsigned int c) = 0;\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Returns a copy of the entry at index (r,c)\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  virtual Eigen::MatrixXd copyAt(unsigned int r, unsigned int c) const = 0;\n\n private:\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Whether matrix is symmetric\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  bool symmetric_;\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Block matrix indexing object\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  BlockMatrixIndexing indexing_;\n\n};\n\n} // steam\n\n#endif // STEAM_BLOCK_MATRIX_BASE_HPP\n", "meta": {"hexsha": "c6f454e70dbfadfe5132eea1ca02c93fb3b7a499", "size": 4340, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/steam/blockmat/BlockMatrixBase.hpp", "max_stars_repo_name": "neophack/steam", "max_stars_repo_head_hexsha": "28f0637e3ae4ff2c21ad12b2331c535e9873c997", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 38.0, "max_stars_repo_stars_event_min_datetime": "2019-10-17T01:37:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T03:55:47.000Z", "max_issues_repo_path": "include/steam/blockmat/BlockMatrixBase.hpp", "max_issues_repo_name": "neophack/steam", "max_issues_repo_head_hexsha": "28f0637e3ae4ff2c21ad12b2331c535e9873c997", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-12-21T21:25:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-01T23:08:57.000Z", "max_forks_repo_path": "include/steam/blockmat/BlockMatrixBase.hpp", "max_forks_repo_name": "neophack/steam", "max_forks_repo_head_hexsha": "28f0637e3ae4ff2c21ad12b2331c535e9873c997", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-12-21T21:13:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T23:42:14.000Z", "avg_line_length": 48.2222222222, "max_line_length": 96, "alphanum_fraction": 0.3016129032, "num_tokens": 553, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544335934766, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.4677174829920863}}
{"text": "#include \"Octopus.h\"\n#include <vector>\n#include <Eigen/Core>\n#include <tinyxml.h>\n\nusing namespace FEM;\n\nOctopus::\nOctopus()\n\t:mMuscleStiffness(2E6),mYoungsModulus(1E7),mPoissonRatio(0.3),mMesh(),mTarget()\n{\n\t// mMesh = new RectangleMesh(0.2,1,2,20);\n\tmMesh = new OBJLoader(\"../octocon2D/export/octo_ver4.obj\");\n}\n\nvoid \nOctopus::\nAddTarget(const Target& target) {\n\tmTarget.push_back(target);\n\t// std::cout << mTarget.size() << std::endl;\n\t// std::cout << target.idx << std::endl;\n}\n\nstd::vector<Target>\nOctopus::\nGetTarget() {\n\treturn mTarget;\n}\n\nvoid \nOctopus::\nSolveSoftIK(FEM::World* world) {\n\tstd::cout << \"SolveSoftIK\" << std::endl;\n\tEigen::VectorXd X = world->GetPositions();\n\n\tEigen::VectorXd X_prime(world->GetNumVertices()*2);\n\tX_prime.setZero();\n\tfor(int i=0; i<mTarget.size(); i++) {\n\t\tX_prime.block<2,1>(mTarget[i].idx*2,0) = X.block<2,1>(mTarget[i].idx*2,0) - mTarget[i].coord;\n\t}\n\n\t\n}\n\nvoid\nOctopus::\nAddMuscle(\n\tconst std::vector<Eigen::Vector3i> indexList,\n\tconst Eigen::Vector2d& fiber_direction\n\t)\n{\n\tmMuscles.push_back(new Muscle());\n\tauto muscle = mMuscles.back();\n\tconst auto& vertices = mMesh->GetVertices();\n\tconst auto& triangles = mMesh->GetTriangles();\n\tstd::vector<FEM::Constraint*> constraints;\n\tEigen::VectorXd v(vertices.size()*2);\n\n\tfor(const auto& idx : indexList)\n\t{\n\t\tint i0,i1,i2;\n\t\tEigen::Vector2d p0,p1,p2;\n\t\t\n\t\ti0 = idx[0];\n\t\ti1 = idx[2];\n\t\ti2 = idx[1];\n\t\tp0 = vertices[i0];\n\t\tp1 = vertices[i1];\n\t\tp2 = vertices[i2];\n\n\t\tEigen::Matrix2d Dm;\n\n\t\tDm.block<2,1>(0,0) = p1 - p0;\n\t\tDm.block<2,1>(0,1) = p2 - p0;\n\t\tif(Dm.determinant()<0)\n\t\t{\n\t\t\ti0 = idx[0];\n\t\t\ti1 = idx[1];\n\t\t\ti2 = idx[2];\n\n\t\t\tp0 = vertices[i0];\n\t\t\tp1 = vertices[i1];\n\t\t\tp2 = vertices[i2];\n\t\t\tDm.block<2,1>(0,0) = p1 - p0;\n\t\t\tDm.block<2,1>(0,1) = p2 - p0;\n\n\t\t\t// muscle->constraints.push_back(new CorotateFEMConstraint(mYoungsModulus,mPoissonRatio,i0,i1,i2,1.0/6.0*(Dm.determinant()),Dm.inverse()));\n\t\t\t// muscle->constraints.push_back(new SpringConstraint(10000.0,i0,i1,(p0-p1).norm()));\n\t\t\t// muscle->constraints.push_back(new SpringConstraint(10000.0,i1,i2,(p1-p2).norm()));\n\t\t\t// muscle->constraints.push_back(new SpringConstraint(10000.0,i2,i0,(p2-p0).norm()));\n\t\t\tmuscle->muscleConstraints.push_back(new LinearMuscleConstraint(mMuscleStiffness,fiber_direction,i0,i1,i2,1.0/6.0*(Dm.determinant()),Dm.inverse()));\t\n\t\t\t// muscle->muscleConstraints.push_back(new HillTypeMuscleConstraint(mMuscleStiffness,fiber_direction,i0,i1,i2,1.0/6.0*(Dm.determinant()),Dm.inverse()));\t\n\t\t}\n\t}\n\n\t// Add Attachment \n\t// AttachmentConstraint* ground = new AttachmentConstraint(1E8,0,Eigen::Vector2d(0,-0.5));\n\t// mAttachementConstraintVector.push_back(ground);\n\tstd::vector<AttachmentConstraint*> ground;\n\tstd::vector<int> groundIdx;\n\n\tfor(int i=981; i<=995; i++) {\n\t\tgroundIdx.push_back(i);\n\t}\n\n\tfor(int i=0; i<groundIdx.size(); i++) {\t\t\n\t\tEigen::Vector2d fixed; \n\t\tfixed[0] = i / 20.0 - 0.35;\n\t\tfixed[1] = 1.15;\n\t\tmAttachementConstraintVector.push_back(new AttachmentConstraint(1E8,groundIdx[i],fixed));\n\t}\n\n\n\tmuscle->activationLevel = 0.0;\n}\nvoid\nOctopus::\nInitialize(FEM::World* world)\n{\n\tconst auto& vertices = mMesh->GetVertices();\n\tconst auto& triangles = mMesh->GetTriangles();\n\n\tfor(const auto& tri : triangles)\n\t{\n\t\tint i0,i1,i2;\n\t\tEigen::Vector2d p0,p1,p2;\n\t\t\n\t\ti0 = tri[0];\n\t\ti1 = tri[2];\n\t\ti2 = tri[1];\n\t\tp0 = vertices[i0];\n\t\tp1 = vertices[i1];\n\t\tp2 = vertices[i2];\n\n\t\tEigen::Matrix2d Dm;\n\n\t\tDm.block<2,1>(0,0) = p1 - p0;\n\t\tDm.block<2,1>(0,1) = p2 - p0;\n\t\tif(Dm.determinant()<0)\n\t\t{\n\t\t\ti0 = tri[0];\n\t\t\ti1 = tri[1];\n\t\t\ti2 = tri[2];\n\t\t\tp0 = vertices[i0];\n\t\t\tp1 = vertices[i1];\n\t\t\tp2 = vertices[i2];\n\t\t\tDm.block<2,1>(0,0) = p1 - p0;\n\t\t\tDm.block<2,1>(0,1) = p2 - p0;\n\n\t\t\tmConstraints.push_back(new CorotateFEMConstraint(mYoungsModulus,mPoissonRatio,i0,i1,i2,1.0/6.0*(Dm.determinant()),Dm.inverse()));\n\t\t}\n\t}\n\n\tEigen::VectorXd v(vertices.size()*2);\n\tfor(int i =0;i<vertices.size();i++)\n\t\tv.block<2,1>(i*2,0) = vertices[i];\n\n\tworld->AddBody(v,mConstraints,1.0);\n\t\n\tfor(auto& c: mAttachementConstraintVector)\n\t\t\tworld->AddConstraint(c);\n\n\t\n\tfor(int i=0;i<mMuscles.size();i++)\n\t{\n\t\tMuscle* muscle = mMuscles[i];\n\n\t\tfor(auto& c: muscle->muscleConstraints)\n\t\t\tworld->AddConstraint(c);\t\t\n\t}\n\n\tmActivationLevel.resize(mMuscles.size());\n\tmActivationLevel.setZero();\n}\n\nvoid\nOctopus::\nSetActivationLevel(const Eigen::VectorXd& a)\n{\n\t// std::cout << \"****\" << mMuscles.size() << std::endl;\n\tmActivationLevel = a;\n\tfor(int i=0;i<mMuscles.size();i++)\n\t\tfor(auto& mc : mMuscles[i]->muscleConstraints)\n\t\t\tmc->SetActivationLevel(a[i]);\n}\n\nvoid\nMakeMuscles(const std::string& path,Octopus* ms)\n{\n\tTiXmlDocument doc;\n\tif(!doc.LoadFile(path))\n    {\n        std::cout<<\"Cant open XML file : \"<<path<<std::endl;\n        return;\n    }  \n\n    TiXmlElement* muscles = doc.FirstChildElement(\"Muscles\");\n\n    for(TiXmlElement* leg = muscles->FirstChildElement(\"leg\");leg!=nullptr;leg = leg->NextSiblingElement(\"leg\")) {\n    \tfor(TiXmlElement* fiber = leg->FirstChildElement(\"fiber\");fiber!=nullptr;fiber = fiber->NextSiblingElement(\"fiber\")) {\n    \t\n\t    \tint start_num, end_num;\n\t    \tint start_idx1, end_idx1;\n\t    \tint start_idx2, end_idx2;\n\t    \tint start_idx3, end_idx3;\n\n\t    \tfor(TiXmlElement* start = fiber->FirstChildElement(\"start\");start!=nullptr;start = start->NextSiblingElement(\"start\")) {\n\t        \tstart_num = std::stod(start->Attribute(\"num\"));\n\t        \tstart_idx1 = std::stod(start->Attribute(\"idx1\"));\n\t\t\t\tstart_idx2 = std::stod(start->Attribute(\"idx2\"));\n\t\t\t\tstart_idx3 = std::stod(start->Attribute(\"idx3\"));\t\t\t\n\t   \t    }\n\n\t   \t    for(TiXmlElement* end = fiber->FirstChildElement(\"end\");end!=nullptr;end = end->NextSiblingElement(\"end\")) {\n\t        \tend_num = std::stod(end->Attribute(\"num\"));\n\t        \tend_idx1 = std::stod(end->Attribute(\"idx1\"));\n\t\t\t\tend_idx2 = std::stod(end->Attribute(\"idx2\"));\n\t\t\t\tend_idx3 = std::stod(end->Attribute(\"idx3\"));\n\t   \t    }   \n\n\t   \t    int cellNum = end_num - start_num + 1;\n\t   \t    int dist = start_idx3 - start_idx1;\n\n\t   \t    std::vector<Eigen::Vector3i> muscleIndex;\n\n\t   \t    for(int i=0; i<cellNum/2; i++) {\n\t   \t    \tint idx1 = start_idx1 + dist*i;\n\t   \t    \tint idx2 = start_idx2 + dist*i;\n\t   \t    \tint idx3 = start_idx3 + dist*i;\n\n\t   \t    \tmuscleIndex.push_back(Eigen::Vector3i(idx1,idx2,idx3));\n\t   \t    }\n\n\t\t\tfor(int i=0; i<cellNum/2; i++) {\n\t\t\t\tint idx1 = end_idx1 - dist*i;\n\t   \t    \tint idx2 = end_idx2 - dist*i;\n\t   \t    \tint idx3 = end_idx3 - dist*i;\n\n\t   \t    \tmuscleIndex.push_back(Eigen::Vector3i(idx1,idx2,idx3));    \n\t   \t    }   \t\n\n\t   \t    ms->AddMuscle(muscleIndex,Eigen::Vector2d::UnitY());\n   \t    }     \t    \n    }\n\n    // std::cout << \"# (Muscle Fiber) : \" << muscleIndex.size() << std::endl;\n}\n\n", "meta": {"hexsha": "e046e9c38b0831ef86a9c532f702a1f2724797f8", "size": 6656, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "octocon2D/Octopus.cpp", "max_stars_repo_name": "snumrl/volcon2D", "max_stars_repo_head_hexsha": "4b4277cef2caa0f62429781acedc71d9f8b6bd0d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "octocon2D/Octopus.cpp", "max_issues_repo_name": "snumrl/volcon2D", "max_issues_repo_head_hexsha": "4b4277cef2caa0f62429781acedc71d9f8b6bd0d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "octocon2D/Octopus.cpp", "max_forks_repo_name": "snumrl/volcon2D", "max_forks_repo_head_hexsha": "4b4277cef2caa0f62429781acedc71d9f8b6bd0d", "max_forks_repo_licenses": ["Apache-2.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.7309236948, "max_line_length": 156, "alphanum_fraction": 0.6355168269, "num_tokens": 2206, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199754937771, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.4676658433127105}}
{"text": "\n#include \"modules/bio_base/dna_sequence.h\"\n#include \"modules/bio_base/kmer.h\"\n#include <gtest/gtest.h>\n#include <bitset>\n#include <unordered_set>\n#include <deque>\n\nconstexpr kmer_t fives = 0x5555555555555555l;\n\n#include <boost/multiprecision/cpp_int.hpp>\n\ntypedef boost::multiprecision::uint128_t big_kmer_t;\ntypedef std::vector<big_kmer_t> big_kmers_t;\n\n/*\nclass patterns\n{\npublic:\n\tpatterns(const std::vector<dna_sequnce> patterns)\n\t{\n\t\tm_fives.resize(patterns.size());\n\t\tm_matches.resize(patterns.size());\n\t\tm_masks.resize(patterns.size());\n\t\tfor(size_t i = 0; i < patterns.size(); i++)\n\t\t{\n\t\t\tfor(size_t \n\n\tbig_kmers_t apply_base(const big_kmers_t& errs, int base);\n\tbig_kmers_t m_fives;\n\tbig_kmers_t m_matches;\n\tbig_kmers_t m_masks;\n};\n\nbig_kmers_t apply_base(const big_kmers_t& errs, const big_kmers_t& patterns, const big_kmers_t& patterns,\n*/\n\nkmer_t apply_base(kmer_t errs, kmer_t match, kmer_t mask, kmer_t base) \n{\n\terrs >>= 2;\n\tkmer_t base_rep = fives * base;\n\tkmer_t diff = base_rep ^ match;\n\tkmer_t diff_bit = (diff | (diff >> 1)) & fives;\n\tkmer_t saturate = errs & (errs >> 1);\n\tkmer_t to_add = diff_bit & ~saturate;\n\terrs += to_add;\n\terrs &= mask;\n\treturn errs;\n}\n\nTEST(tiny_align, test_it) \n{\n\tdna_sequence match_seq(\"CTGTCTCTTATACACATCT\");\n\tdna_sequence seek_seq(\"ACCGTCTGTCTCTTATTACTGTCTCTTATACACATCTGGGTAGA\");\n\tsize_t kmer_size = match_seq.size();\n\tkmer_t mask = (uint64_t(1) << (2*kmer_size)) - 1;\n\tkmer_t errs = mask;\n\tkmer_t match = match_seq.as_kmer();\n\tfor(size_t i = 0; i < seek_seq.size(); i++) {\n\t\tkmer_t base = (int) seek_seq[i];\n\t\terrs = apply_base(errs, match, mask, base);\n\t\tprintf(\"%c: %s\\n\", char(seek_seq[i]),\n\t\t\tstd::bitset<64>(errs).to_string().c_str());\n\t}\n}\n\nTEST(tiny_align, test_combin)\n{\n\tdna_sequence match_seq(\"CTGTCTCTTATACACATCT\");\n\tsize_t kmer_size = match_seq.size();\n\tkmer_t mask = (uint64_t(1) << (2*kmer_size)) - 1;\n\tkmer_t match = match_seq.as_kmer();\n\tstd::set<kmer_t> found;\n\tstd::deque<kmer_t> to_do;\n\tfound.emplace(mask);\n\tto_do.push_back(mask);\n\twhile(!to_do.empty()) {\n\t\tif (found.size() % 1000 == 0) {\n\t\t\tprintf(\"Found = %d: to_do = %d\", int(found.size()), int(to_do.size()));\n\t\t}\n\t\tkmer_t errs = to_do.front();\n\t\tto_do.pop_front();\n\t\tfor(kmer_t b = 0; b < 4; b++) {\n\t\t\tkmer_t new_err = apply_base(errs, match, mask, b);\n\t\t\tif (found.count(new_err)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfound.emplace(new_err);\n\t\t\tto_do.push_back(new_err);\n\t\t}\n\t}\n\tprintf(\"Total found size: %d\\n\", int(found.size()));\t\n\tfor(kmer_t k : found) {\n\t\tprintf(\"%s\\n\", std::bitset<64>(k).to_string().c_str());\n\t}\n}\n\n", "meta": {"hexsha": "5e391138ab96ce8f00d5990fc126232cad0a8078", "size": 2538, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/bio_base/tiny_align_test.cpp", "max_stars_repo_name": "spiralgenetics/biograph", "max_stars_repo_head_hexsha": "33c78278ce673e885f38435384f9578bfbf9cdb8", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2021-07-14T23:32:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T16:25:15.000Z", "max_issues_repo_path": "modules/bio_base/tiny_align_test.cpp", "max_issues_repo_name": "spiralgenetics/biograph", "max_issues_repo_head_hexsha": "33c78278ce673e885f38435384f9578bfbf9cdb8", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2021-07-20T20:39:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-16T20:57:59.000Z", "max_forks_repo_path": "modules/bio_base/tiny_align_test.cpp", "max_forks_repo_name": "spiralgenetics/biograph", "max_forks_repo_head_hexsha": "33c78278ce673e885f38435384f9578bfbf9cdb8", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2021-07-15T19:38:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T19:24:56.000Z", "avg_line_length": 25.8979591837, "max_line_length": 105, "alphanum_fraction": 0.6863672183, "num_tokens": 828, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262966, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.46766583199682904}}
{"text": "/*=============================================================================================================\n                                                BDSimulations.cpp\n===============================================================================================================\n\n Simulations of genetic rescue\n\n C++-code accompanying:\n\n\t\t(ms. in prep).\n\n Written by:\n        F.J.H. de Haas\n       \tTheoretical Biology Group\n        University of British Columbia\n        the Netherlands\n\n Program version\n\t\txx/xx/xxxx\t:\n\n=============================================================================================================*/\n\n#include <assert.h>\n#include <stdlib.h>\n#include <iomanip>\n#include <string>\n#include <iostream>\n#include \"random.h\"\n#include \"utils.h\"\n#include <progress.hpp>\n#include <mutex>\n#include <Rcpp.h>\n#include <atomic>\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/mean.hpp>\n#include <boost/accumulators/statistics/variance.hpp>\n\n#ifdef _OPENMP\n    #include <omp.h>\n#endif\n\nenum typenames {AB,Ab,aB,ab};\nusing namespace boost::accumulators;\n\nstruct Parameters{\n    Parameters(const int &in_AB0, const int &in_Ab0,const int &in_aB0, const int &in_ab0, const double &in_bA, const double &in_ba, double const& in_dA, double const& in_da, double const&in_r){\n        AB0 = in_AB0;\n        Ab0 = in_Ab0;\n        aB0 = in_aB0;\n        ab0 = in_ab0;\n        bA = in_bA;\n        ba = in_ba;\n        dA = in_dA;\n        da = in_da;\n        r = in_r;\n    }\n\n    Parameters(Rcpp::List parslist){\n        AB0 = parslist[\"AB0\"];\n        Ab0 = parslist[\"Ab0\"];\n        aB0 = parslist[\"aB0\"];\n        ab0 = parslist[\"ab0\"];\n        bA = parslist[\"bA\"];\n        ba = parslist[\"ba\"];\n        dA = parslist[\"dA\"];\n        da = parslist[\"da\"];\n        r = parslist[\"r\"];\n    }\n\n    int AB0,Ab0,aB0,ab0;\n    double bA,ba,dA,da;\n    double r;\n};\n\nclass BDPopulation{\n    public:\n    BDPopulation(const Parameters &pars) {\n        type[AB].push_back(pars.AB0);\n        type[Ab].push_back(pars.Ab0);\n        type[aB].push_back(pars.aB0);\n        type[ab].push_back(pars.ab0); \n    }\n    bool Iterate(const Parameters &pars){\n        /*parents become offspring*/\n        type[AB].push_back(type[AB].back());\n        type[Ab].push_back(type[Ab].back());\n        type[aB].push_back(type[aB].back());\n        type[ab].push_back(type[ab].back());\n        /*offspring changes*/ \n        static double f[4];\n        assert(pars.da>=0.0);\n        assert(pars.dA>=0.0);\n        if(CalculateFrequencies(f)==false) {extinct = true; return false;};\n        const double sumdeathrate = (f[AB]+f[Ab])*pars.dA+(f[aB]+f[ab])*pars.da;\n        const double sumbirthrate = (f[AB]+f[Ab])*pars.bA+(f[aB]+f[ab])*pars.ba;\n        const double Pdeath = sumdeathrate/(sumbirthrate+sumdeathrate);\n        const double Pbirth = 1-Pdeath;\n        const double rD = pars.r*(f[AB]*f[ab]-f[Ab]*f[aB]);\n        const double PAB_death = f[AB]*pars.dA/sumdeathrate;\n        const double PAb_death = f[Ab]*pars.dA/sumdeathrate;\n        const double PaB_death = f[aB]*pars.da/sumdeathrate;\n        const double Pab_death = f[ab]*pars.da/sumdeathrate;\n        const double PAB_birth = f[AB]-rD;\n        const double PAb_birth = f[Ab]+rD;\n        const double PaB_birth = f[aB]+rD;\n        const double Pab_birth = f[ab]-rD;\n\n        rnd::discrete_distribution birthdeathevent(8);\n        birthdeathevent[birth_AB] = Pbirth * PAB_birth;\n        birthdeathevent[birth_Ab] = Pbirth * PAb_birth;\n        birthdeathevent[birth_aB] = Pbirth * PaB_birth;\n        birthdeathevent[birth_ab] = Pbirth * Pab_birth;\n        \n        birthdeathevent[death_AB] = Pdeath * PAB_death;\n        birthdeathevent[death_Ab] = Pdeath * PAb_death;\n        birthdeathevent[death_aB] = Pdeath * PaB_death;\n        birthdeathevent[death_ab] = Pdeath * Pab_death;\n        \n        const int sample = birthdeathevent.sample();\n        switch(sample) {\n            case birth_AB:      ++type[AB].back(); break;\n            case birth_Ab:      ++type[Ab].back(); break;\n            case birth_aB:      ++type[aB].back(); break;\n            case birth_ab:      ++type[ab].back(); break;\n            case death_AB:      --type[AB].back(); break;\n            case death_Ab:      --type[Ab].back(); break;\n            case death_aB:      --type[aB].back(); break;\n            case death_ab:      --type[ab].back(); break;\n        }\n        return true;\n    }\n    inline int returnTypes(const int &index, const int &gen){\n        return type[index][gen];\n    }\n    inline bool getextinction(const int &gen){\n        return (type[AB][gen]+type[Ab][gen])!=0 ? false : true;\n    }\n    inline double getFA(const int &gen){\n        //assert(type[AB][gen]+type[Ab][gen] != 0);\n        return (double)type[AB][gen] / (double)(type[AB][gen]+type[Ab][gen]);\n    }\n\n    inline double getFa(const int &gen){\n        //assert(type[aB][gen]+type[aB][gen] != 0);\n        return (double)type[aB][gen] / (double)(type[aB][gen]+type[ab][gen]);\n    }\n\n    private:\n    bool extinct = false;\n    enum distribution {birth_AB,birth_Ab,birth_aB,birth_ab,death_AB,death_Ab,death_aB,death_ab};        \n    std::vector<int> type[4];\n    bool CalculateFrequencies(double *f){\n        const double sum=(double)(type[AB].back()+type[Ab].back()+type[aB].back()+type[ab].back());\n        if(sum<=0){return false;}\n        f[AB] = (double)type[AB].back()/sum;\n        f[Ab] = (double)type[Ab].back()/sum;\n        f[aB] = (double)type[aB].back()/sum;\n        f[ab] = (double)type[ab].back()/sum;\n        return true;\n    }\n};\n\nstruct RcppOutput{\n    RcppOutput(const unsigned int &ngen) : ngennr(ngen) {\n        nofixcounter = 0;\n        fixcounter = 0;\n        type[AB].resize(ngen);\n        type[Ab].resize(ngen);\n        type[aB].resize(ngen);\n        type[ab].resize(ngen);\n        FA.resize(ngen);\n        Fa.resize(ngen);\n    };\n    void pushback_protect(BDPopulation* pop){\n        if(pop->getextinction(ngennr)){\n            ++nofixcounter;\n        }\n        else{\n            ++fixcounter;\n            mu_acc.lock();\n            for(int t = 0; t < ngennr; ++t){\n                type[AB][t](pop->returnTypes(AB,t));\n                type[Ab][t](pop->returnTypes(Ab,t));\n                type[aB][t](pop->returnTypes(aB,t));\n                type[ab][t](pop->returnTypes(ab,t));\n                FA[t](pop->getFA(t));\n                if(pop->getFa(t) >= 0.0){\n                    Fa[t](pop->getFa(t));\n                }\n            }\n            distribution[AB].push_back(pop->returnTypes(AB,ngennr));\n            distribution[Ab].push_back(pop->returnTypes(AB,ngennr));\n            distribution[aB].push_back(pop->returnTypes(AB,ngennr));\n            distribution[ab].push_back(pop->returnTypes(AB,ngennr));\n            mu_acc.unlock();\n        }\n    };\n    Rcpp::List pushout(){\n        /* make a Rcpp Vector for first 4 entries of the Rlist. */\n        Rcpp::NumericVector RcppAB(ngennr);    \n        Rcpp::NumericVector RcppAb(ngennr);    \n        Rcpp::NumericVector RcppaB(ngennr);    \n        Rcpp::NumericVector Rcppab(ngennr);    \n        Rcpp::NumericVector RcppFA(ngennr);\n        Rcpp::NumericVector RcppFa(ngennr);\n        Rcpp::NumericVector RcppAB_var(ngennr);    \n        Rcpp::NumericVector RcppAb_var(ngennr);    \n        Rcpp::NumericVector RcppaB_var(ngennr);    \n        Rcpp::NumericVector Rcppab_var(ngennr);    \n        Rcpp::NumericVector RcppFA_var(ngennr);\n        Rcpp::NumericVector RcppFa_var(ngennr);\n        Rcpp::NumericVector Time(ngennr);\n\n        for(int t = 0; t < ngennr; ++t){\n            RcppAB[t] = mean(type[AB][t]);\n            RcppAb[t] = mean(type[Ab][t]);\n            RcppaB[t] = mean(type[aB][t]);\n            Rcppab[t] = mean(type[ab][t]);\n            RcppFA[t] = mean(FA[t]);\n            RcppFa[t] = mean(Fa[t]);\n\n            RcppAB_var[t] = variance(type[AB][t]);\n            RcppAb_var[t] = variance(type[Ab][t]);\n            RcppaB_var[t] = variance(type[aB][t]);\n            Rcppab_var[t] = variance(type[ab][t]);\n            RcppFA_var[t] = variance(FA[t]);\n            RcppFa_var[t] = variance(Fa[t]);\n\n            Time[t] = t;\n        }   \n\n        return Rcpp::List::create(\n            Rcpp::_[\"t\"] = Time,\n            Rcpp::_[\"AB_mean\"] = RcppAB,\n            Rcpp::_[\"Ab_mean\"] = RcppAb,\n            Rcpp::_[\"aB_mean\"] = RcppaB,\n            Rcpp::_[\"ab_mean\"] = Rcppab,\n            Rcpp::_[\"FA_mean\"] = RcppFA,\n            Rcpp::_[\"Fa_mean\"] = RcppFa,\n\n            Rcpp::_[\"AB_var\"] = RcppAB_var,\n            Rcpp::_[\"Ab_var\"] = RcppAb_var,\n            Rcpp::_[\"aB_var\"] = RcppaB_var,\n            Rcpp::_[\"ab_var\"] = Rcppab_var,\n            Rcpp::_[\"FA_var\"] = RcppFA_var,\n            Rcpp::_[\"Fa_var\"] = RcppFa_var,\n\n            Rcpp::_[\"extinct\"] = static_cast<double>(nofixcounter) / (static_cast<double>(nofixcounter)+static_cast<double>(fixcounter))\n        );\n    }\n\n    private:\n    const int ngennr;\n    std::mutex mu_acc;\n    std::atomic<int> nofixcounter, fixcounter;\n    std::vector<accumulator_set<int, stats<tag::mean, tag::variance > > > type[4];\n    std::vector<accumulator_set<double, stats<tag::mean, tag::variance > > > FA,Fa; // Genetic rescue AB/(AB+Ab) & aB/(aB+ab) (a will go extinct)\n    std::vector<int> distribution[4];\n};\n\n// [[Rcpp::export]]\nRcpp::List BDSim(const int &nrep, const int &tend, const Rcpp::List &parslist, int setthreads = 0, bool progressbar = true){\n    rnd::set_seed();\n    Parameters pars(parslist);\n    #ifdef _OPENMP\n        const static int maxthreads = omp_get_max_threads();\n        if(setthreads>0) omp_set_num_threads(setthreads);\n        else omp_set_num_threads(maxthreads);\n        //REprintf(\"Parallel activated : Number of threads=%i\\n\",omp_get_max_threads());   \n    #endif\n    Progress p(nrep, progressbar);\n\n    /*collect data */    \n    RcppOutput dataframe(tend);\n    BDPopulation* arrayPopulation[nrep];\n\n    #pragma omp parallel for /* threadprivate(OUTPUT)*/\n    for(int j = 0; j < nrep; ++j){\n        /* run simulations in parallel*/\n        arrayPopulation[j] = new BDPopulation(pars);\n        for(int i = 0; i < tend; ++i){arrayPopulation[j]->Iterate(pars);}\n        dataframe.pushback_protect(arrayPopulation[j]);\n        delete arrayPopulation[j];\n        p.increment();\n    }\n\n    /*rservoire*/\n    return dataframe.pushout();\n}\n", "meta": {"hexsha": "023c138d563427022d802360686df566978ccd6e", "size": 10369, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Rpackage/pkgIntrogression/src/BDSimulations.cpp", "max_stars_repo_name": "freekdh/GeneticRescue", "max_stars_repo_head_hexsha": "62226b4fd2ba25a1891bf02e3d0272b67897409f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Rpackage/pkgIntrogression/src/BDSimulations.cpp", "max_issues_repo_name": "freekdh/GeneticRescue", "max_issues_repo_head_hexsha": "62226b4fd2ba25a1891bf02e3d0272b67897409f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Rpackage/pkgIntrogression/src/BDSimulations.cpp", "max_forks_repo_name": "freekdh/GeneticRescue", "max_forks_repo_head_hexsha": "62226b4fd2ba25a1891bf02e3d0272b67897409f", "max_forks_repo_licenses": ["Apache-2.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.7551724138, "max_line_length": 193, "alphanum_fraction": 0.5519336484, "num_tokens": 2918, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199471193039, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.46766582747047625}}
{"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 Functions to test the algorithms that route on Benes and AS-Waksman networks.\n//---------------------------------------------------------------------------//\n\n#define BOOST_TEST_MODULE routing_algorithms_test\n\n#include <boost/test/unit_test.hpp>\n\n#include <cassert>\n\n#include <nil/crypto3/zk/snark/routing/as_waksman.hpp>\n#include <nil/crypto3/zk/snark/routing/benes.hpp>\n\nusing namespace nil::crypto3::zk::snark;\n\n/**\n * Test Benes network routing for all permutations on 2^static_cast<std::size_t>(std::ceil(std::log2(N))) elements.\n */\nvoid test_benes(const std::size_t N) {\n    integer_permutation permutation(1ul << static_cast<std::size_t>(std::ceil(std::log2(N))));\n\n    do {\n        const benes_routing routing = get_benes_routing(permutation);\n        assert(valid_benes_routing(permutation, routing));\n    } while (permutation.next_permutation());\n}\n\n/**\n * Test AS-Waksman network routing for all permutations on N elements.\n */\nvoid test_as_waksman(const std::size_t N) {\n    integer_permutation permutation(N);\n\n    do {\n        const as_waksman_routing routing = get_as_waksman_routing(permutation);\n        assert(valid_as_waksman_routing(permutation, routing));\n    } while (permutation.next_permutation());\n}\n\nBOOST_AUTO_TEST_SUITE(routing_algorithms_test_suite)\n\nBOOST_AUTO_TEST_CASE(routing_algorithms_test) {\n    std::size_t bn_size = 8;\n    printf(\"* for all permutations on %zu elements\\n\", bn_size);\n    test_benes(bn_size);\n\n    std::size_t asw_max_size = 9;\n    for (std::size_t i = 2; i <= asw_max_size; ++i) {\n        test_as_waksman(i);\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "3e7442675b3264b777ff3cb63110cec2557b08be", "size": 2994, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/routing_algorithms/test_routing_algorithms.cpp", "max_stars_repo_name": "NilFoundation/zk", "max_stars_repo_head_hexsha": "60c63ba8e719620e9fe68d68621c84afded2a809", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-12-31T06:01:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T09:31:02.000Z", "max_issues_repo_path": "test/routing_algorithms/test_routing_algorithms.cpp", "max_issues_repo_name": "NilFoundation/zk", "max_issues_repo_head_hexsha": "60c63ba8e719620e9fe68d68621c84afded2a809", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2020-09-15T18:32:40.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T08:53:01.000Z", "max_forks_repo_path": "test/routing_algorithms/test_routing_algorithms.cpp", "max_forks_repo_name": "NilFoundation/zk", "max_forks_repo_head_hexsha": "60c63ba8e719620e9fe68d68621c84afded2a809", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-06-22T16:05:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T09:31:07.000Z", "avg_line_length": 39.3947368421, "max_line_length": 115, "alphanum_fraction": 0.6837007348, "num_tokens": 666, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195152660688, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.4676567481710876}}
{"text": "//==================================================================================================\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#include <boost/simd/function/exponent.hpp>\n#include <boost/simd/constant/nan.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/minf.hpp>\n#include <boost/simd/pack.hpp>\n#include <simd_test.hpp>\n\nnamespace bs = boost::simd;\nnamespace bd = boost::dispatch;\n\ntemplate <typename T, std::size_t N, typename Env>\nvoid test(Env& $)\n{\n  using p_t = bs::pack<T, N>;\n  using iT =  bd::as_integer_t<T>;\n  using ip_t = bs::pack<iT, N>;\n\n  T a1[N];\n  iT b[N];\n\n  for(std::size_t i = 0; i < N; ++i)\n  {\n    a1[i] = (i%2) ? T(i) : T(37.98*i);\n    b[i] = bs::exponent(a1[i]) ;\n  }\n  p_t aa1(&a1[0], &a1[0]+N);\n  ip_t bb (&b[0], &b[0]+N);\n\n  STF_IEEE_EQUAL(bs::exponent(aa1), bb);\n}\n\nSTF_CASE_TPL(\"Check exponent on pack\" , STF_IEEE_TYPES)\n{\n  static const std::size_t N = bs::pack<T>::static_size;\n  test<T, N>($);\n  test<T, N/2>($);\n  test<T, N*2>($);\n}\n\ntemplate <typename T, std::size_t N, typename Env>\nvoid test_invalid(Env& $)\n{\n  using p_t  = bs::pack<T, N>;\n  using ip_t = bs::pack<bd::as_integer_t<T>, N>;\n\n  STF_IEEE_EQUAL(bs::exponent(bs::Nan<p_t>()), ip_t(0));\n  STF_IEEE_EQUAL(bs::exponent(bs::Inf<p_t>()), ip_t(0));\n  STF_IEEE_EQUAL(bs::exponent(bs::Minf<p_t>()), ip_t(0));\n}\n\nSTF_CASE_TPL(\"Check exponent on invalid values\" , STF_IEEE_TYPES)\n{\n  static const std::size_t N = bs::pack<T>::static_size;\n  test_invalid<T, N>($);\n  test_invalid<T, N/2>($);\n  test_invalid<T, N*2>($);\n}\n", "meta": {"hexsha": "443f227a5b0097bf2f8bc28d172545f321f37410", "size": 1788, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/simd/exponent.cpp", "max_stars_repo_name": "nickporubsky/boost-simd-clone", "max_stars_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_stars_repo_licenses": ["BSL-1.0"], "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": "test/function/simd/exponent.cpp", "max_issues_repo_name": "timblechmann/boost.simd", "max_issues_repo_head_hexsha": "2217f1d0102193799469b533e3a7118bf4a77dde", "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/function/simd/exponent.cpp", "max_forks_repo_name": "timblechmann/boost.simd", "max_forks_repo_head_hexsha": "2217f1d0102193799469b533e3a7118bf4a77dde", "max_forks_repo_licenses": ["BSL-1.0"], "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": 27.0909090909, "max_line_length": 100, "alphanum_fraction": 0.567114094, "num_tokens": 561, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.734119526900183, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.46765674546478664}}
{"text": "#include <boost/hana/cartesian_product.hpp>\n", "meta": {"hexsha": "c0d378d0a9b401005111c82b78a0d592e48a9e5d", "size": 44, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_hana_cartesian_product.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_hana_cartesian_product.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_hana_cartesian_product.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 22.0, "max_line_length": 43, "alphanum_fraction": 0.8181818182, "num_tokens": 10, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.734119526900183, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.4676567454647866}}
{"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_POLYNOMIALS_FUNCTIONS_SCALAR_LAGUERRE_HPP_INCLUDED\n#define NT2_POLYNOMIALS_FUNCTIONS_SCALAR_LAGUERRE_HPP_INCLUDED\n\n#include <nt2/polynomials/functions/laguerre.hpp>\n#include <nt2/include/functions/scalar/oneplus.hpp>\n#include <nt2/include/constants/one.hpp>\n#include <boost/dispatch/meta/as_floating.hpp>\n\n\n/////////////////////////////////////////////////////////////////////////////\n// Implementation when type A1 is arithmetic_\n/////////////////////////////////////////////////////////////////////////////\nnamespace nt2 { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT  ( laguerre_, tag::cpu_\n                            , (A0)(A1)\n                            , (scalar_< integer_<A0> >)(scalar_< arithmetic_<A1> >)\n                            )\n  {\n\n    typedef typename boost::dispatch::meta::as_floating<A0,A1>::type result_type;\n\n    NT2_FUNCTOR_CALL(2)\n    {\n      return nt2::laguerre(a0, result_type(a1));\n    }\n  };\n\n  /////////////////////////////////////////////////////////////////////////////\n  // Implementation when type A1 is floating_\n  /////////////////////////////////////////////////////////////////////////////\n  BOOST_DISPATCH_IMPLEMENT  (laguerre_, tag::cpu_,\n                            (A0)(A1),\n                            ((scalar_<integer_<A0> >))((scalar_<floating_<A1> > ))\n                            )\n  {\n    typedef typename boost::dispatch::meta::as_floating<A0,A1>::type result_type;\n    NT2_FUNCTOR_CALL(2)\n    {\n      A1 p0 = One<A1>();\n      if(a0 == 0) return p0;\n      A1 p1 = p0-a1;\n      A0 c = 1;\n      while(c < a0)\n      {\n        std::swap(p0, p1);\n        p1 = laguerre_next(c, a1, p0, p1);\n        ++c;\n      }\n      return p1;\n    }\n  private:\n    template <class T, class T1, class T2>\n    static inline T\n    laguerre_next(const uint32_t& n, const T& x, const T1 &Ln, const T2& Lnm1)\n    {\n      const T np1 = T(oneplus(n));\n      return ((T(n) + np1 - x) * Ln - n *Lnm1) / np1;\n    }\n  };\n} }\n\n#endif\n", "meta": {"hexsha": "e73616dbacb31bcc3039b9f21c11e97624efe71a", "size": 2468, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/polynomials/include/nt2/polynomials/functions/scalar/laguerre.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/polynomials/include/nt2/polynomials/functions/scalar/laguerre.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/polynomials/include/nt2/polynomials/functions/scalar/laguerre.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 34.2777777778, "max_line_length": 83, "alphanum_fraction": 0.4688006483, "num_tokens": 589, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195152660687, "lm_q2_score": 0.6370308013713525, "lm_q1q2_score": 0.46765674311229255}}
{"text": "// Copyright (c) 2015\n// Author: Chrono Law\n#include <std.hpp>\nusing namespace std;\n\n//#define BOOST_DATE_TIME_POSIX_TIME_STD_CONFIG\n#include <boost/date_time/gregorian/gregorian.hpp>\nusing namespace boost::gregorian;\n#include <boost/date_time/posix_time/posix_time.hpp>\nusing namespace boost::posix_time;\n\n//////////////////////////////////////////\n\nvoid case1()\n{\n    {\n        time_duration td = duration_from_string(\"1:10:30:001\");\n        cout << td << endl;\n\n        time_duration td1(1,10,30,1000);\n        time_duration td2(1,60,60,1000*1000* 6 + 1000);\n    }\n\n    hours h(1);\n    minutes m(10);\n    seconds s(30);\n    millisec ms(1);\n\n    time_duration td = h + m + s + ms;\n    time_duration td2 = hours(2) + seconds(10);\n\n    cout << td << td2 << endl;\n}\n\n//////////////////////////////////////////\nvoid case2()\n{\n    time_duration td(1,10,30,1000);\n    assert(td.hours() == 1 && td.minutes() == 10 && td.seconds() == 30);\n    assert(td.total_seconds() == 1*3600+ 10*60 + 30);\n    assert(td.total_milliseconds() == td.total_seconds()*1000 + 1);\n    assert(td.fractional_seconds() == 1000);\n\n    hours h(-10);\n    assert(h.is_negative());\n\n    time_duration h2 = h.invert_sign();\n    assert(!h2.is_negative() && h2.hours() == 10);\n\n    time_duration td1(not_a_date_time);\n    assert(td1.is_special() && td1.is_not_a_date_time());\n\n    time_duration td2(neg_infin);\n    assert(td2.is_negative() && td2.is_neg_infinity());\n\n}\n\n//////////////////////////////////////////\nvoid case3()\n{\n    time_duration td1 = hours(1);\n    time_duration td2 = hours(2) + minutes(30);\n    assert(td1 < td2);\n    assert((td1+td2).hours() == 3);\n    assert((td1-td2).is_negative());\n    assert(td1 * 5 == td2 * 2);\n    assert((td1/2).minutes() == td2.minutes());\n\n    time_duration td(1,10,30,1000);\n    cout << to_simple_string(td) << endl;\n    cout << to_iso_string(td) << endl;\n\n}\n\n//////////////////////////////////////////\nvoid case4()\n{\n#ifdef BOOST_DATE_TIME_POSIX_TIME_STD_CONFIG\n    time_duration td(1,10,30,1000);\n    cout << td;\n    assert(td.total_milliseconds() ==\n            td.total_seconds()*1000);\n\n    assert(td.fractional_seconds() ==1000);\n    assert(time_duration::unit()*1000*1000*1000 == seconds(1));\n\n    assert(td.resolution() == boost::date_time::nano);\n    assert(td.num_fractional_digits() == 9);\n\n\n#endif\n}\n\n//////////////////////////////////////////\nvoid case5()\n{\n    ptime p(date(2014,6,8), hours(1));\n    ptime p1 = time_from_string(\"2014-6-8 01:00:00\");\n    ptime p2 = from_iso_string(\"20140608T010000\");\n\n    cout << p1 << endl << p2;\n    {\n        ptime p1 = second_clock::local_time();\n        ptime p2 = microsec_clock::universal_time();\n        cout << p1 << endl << p2;\n\n    }\n}\n\n//////////////////////////////////////////\nvoid case6()\n{\n    ptime p(date(2010,3,20), hours(12)+minutes(30));\n\n    date d = p.date();\n    time_duration td = p.time_of_day();\n    assert(d.month() == 3 && d.day() == 20);\n    assert(td.total_seconds() == 12*3600 + 30*60);\n\n    ptime p1(date(2010,3,20), hours(12)+minutes(30));\n    ptime p2 = p1 + hours(3);\n\n    assert(p1 < p2);\n    assert(p2 - p1 == hours(3));\n    p2 += months(1);\n    assert(p2.date().month() == 4);\n\n    cout << endl;\n    {\n        ptime p(date(2014,2,14), hours(20));\n        cout << to_simple_string(p) << endl;\n        cout << to_iso_string(p) << endl;\n        cout << to_iso_extended_string(p) << endl;\n    }\n}\n\n//////////////////////////////////////////\nvoid case7()\n{\n    ptime p(date(2010,2,14), hours(20));\n    tm t = to_tm(p);\n    assert(t.tm_year == 110 && t.tm_hour == 20);\n\n    ptime p2 = from_time_t(std::time(0));\n    assert(p2.date() == day_clock::local_day());\n}\n\n//////////////////////////////////////////\nvoid case8()\n{\n    ptime p(date(2014,1,1),hours(12)) ;\n    time_period tp1(p, hours(8));\n    time_period tp2(p + hours(8), hours(1));\n    assert(tp1.end() == tp2.begin() && tp1.is_adjacent(tp2));\n    assert(!tp1.intersects(tp2));\n\n    tp1.shift(hours(1));\n    assert(tp1.is_after(p));\n    assert(tp1.intersects(tp2));\n\n    tp2.expand(hours(10));\n    assert(tp2.contains(p) && tp2.contains(tp1));\n}\n\n//////////////////////////////////////////\nvoid case9()\n{\n    ptime p(date(2014,11,3),hours(10)) ;\n    for (time_iterator t_iter(p, minutes(10));\n            t_iter < p + hours(1); ++ t_iter)\n    {\n            cout << *t_iter << endl;\n    }\n\n}\n\n//////////////////////////////////////////\ntemplate<typename Clock = microsec_clock>\nclass basic_ptimer\n{\n    public:\n        basic_ptimer()\n        {   restart();}\n        void restart()\n        {   _start_time = Clock::local_time();  }\n        void elapsed() const\n        {   cout << Clock::local_time() - _start_time;  }\n        ~basic_ptimer()\n        {   elapsed();  }\n    private:\n        ptime _start_time;\n};\ntypedef basic_ptimer<microsec_clock> ptimer;\ntypedef basic_ptimer<second_clock>   sptimer;\n\nclass work_time\n{\npublic:\n    typedef map<time_period, string> map_t;\nprivate:\n    map_t map_ts;\n    void init()\n    {\n        ptime p(day_clock::local_day());\n\n        map_ts[time_period(p, hours(9))] = \"It's too early, just relax.\\n\";\n        p += hours(9);\n        map_ts[time_period(p, hours(3)+ minutes(30))] = \"It's AM, please work hard.\\n\";\n        p += hours(3)+ minutes(30);\n        map_ts[time_period(p, hours(1))] = \"It's lunch time, are you hungry?\\n\";\n        p += hours(1);\n        map_ts[time_period(p, hours(4)+minutes(30))] = \"It's PM, ready to go home.\\n\";\n        p += hours(4)+ minutes(30);\n        map_ts[time_period(p, hours(6))] = \"Are you still working? you do need a rest.\\n\";\n    }\npublic:\n    work_time()\n    {   init(); }\n\n    void greeting(const ptime& t)\n    {\n        for (auto& x : map_ts)\n        {\n            if (x.first.contains(t))\n            {\n                cout << x.second << endl;\n                break;\n            }\n        }\n    }\n};\n\nvoid case10()\n{\n    ptimer t;\n\n    work_time wt;\n    wt.greeting(second_clock::local_time());\n}\n\n\n//////////////////////////////////////////\n\nint main()\n{\n    case1();\n    case2();\n    case3();\n    case4();\n    case5();\n    case6();\n    case7();\n    case8();\n    case9();\n    case10();\n}\n", "meta": {"hexsha": "a9191a64b670704b7f953e2d28b2c6bb943dc55e", "size": 6124, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "date_time/posix_time.cpp", "max_stars_repo_name": "210843013/boost_guide", "max_stars_repo_head_hexsha": "48f7936812018d695b065a6b7dadab482526b6d3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "date_time/posix_time.cpp", "max_issues_repo_name": "210843013/boost_guide", "max_issues_repo_head_hexsha": "48f7936812018d695b065a6b7dadab482526b6d3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "date_time/posix_time.cpp", "max_forks_repo_name": "210843013/boost_guide", "max_forks_repo_head_hexsha": "48f7936812018d695b065a6b7dadab482526b6d3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-01-29T13:08:23.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-29T13:08:23.000Z", "avg_line_length": 23.8287937743, "max_line_length": 90, "alphanum_fraction": 0.5305355976, "num_tokens": 1731, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.6370307875894139, "lm_q1q2_score": 0.4676567404059916}}
{"text": "#ifndef NBT_OCTREE_HPP\n#define NBT_OCTREE_HPP\n\n#include <Eigen>\n#include \"rigidbody.hpp\"\n\n/**\n * @brief Node struct for Octree.\n */\nstruct OctreeNode {\n    OctreeNode* children[2][2][2]; //<! 3d Array to store child pointers (Axes in order: z y x)\n\n    bool isEmpty;       //<! True if no objects are in this node.\n    bool isExternal;    //<! True if this node is external (has no children).\n\n    double xMin, xMax;  //!< Bounds in x dimension\n    double yMin, yMax;  //!< Bounds in y dimension\n    double zMin, zMax;  //!< Bounds in z dimension\n\n    double totalMass;               //!< Total mass in the region bounded by the node.\n    Eigen::Vector3d centerOfMass;   //!< Center of mass of the objects within this node.\n\n    //!< Constructs an OctreeNode object from x, y, z bounds\n    OctreeNode(double xMin, double xMax, double yMin, double yMax, double zMin, double zMax);\n\n    //!< Destroys OctreeNode object by destroying children\n    ~OctreeNode();\n\n    //!< Recursively adds an object into the subtree that has this node as root.\n    void addObject(double m, const Eigen::Ref<const Eigen::Vector3d> pos);\n\n    //<! Deletes all children below this node.\n    void prune();\n};\n\n#endif", "meta": {"hexsha": "e336c31059e2f7683751ecc68fe33dcbaee777cc", "size": 1192, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/octree.hpp", "max_stars_repo_name": "tdude92/nbody-tool", "max_stars_repo_head_hexsha": "cf8feedb974c5d23a0ab6981d8ccbeab35aeacb0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-11-12T08:20:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-06T19:37:44.000Z", "max_issues_repo_path": "include/octree.hpp", "max_issues_repo_name": "tdude92/nbody-tool", "max_issues_repo_head_hexsha": "cf8feedb974c5d23a0ab6981d8ccbeab35aeacb0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/octree.hpp", "max_forks_repo_name": "tdude92/nbody-tool", "max_forks_repo_head_hexsha": "cf8feedb974c5d23a0ab6981d8ccbeab35aeacb0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.1111111111, "max_line_length": 95, "alphanum_fraction": 0.6669463087, "num_tokens": 302, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.6370307875894138, "lm_q1q2_score": 0.4676567404059915}}
{"text": "//  (C) Copyright Gennadiy Rozental 2001-2004.\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/test for the library home page.\r\n//\r\n//  File        : $RCSfile: floating_point_comparison.hpp,v $\r\n//\r\n//  Version     : $Revision: 1.18 $\r\n//\r\n//  Description : defines algoirthms for comparing 2 floating point values\r\n// ***************************************************************************\r\n\r\n#ifndef BOOST_FLOATING_POINT_COMPARISON_HPP_071894GER\r\n#define BOOST_FLOATING_POINT_COMPARISON_HPP_071894GER\r\n\r\n#include <boost/limits.hpp>  // for std::numeric_limits\r\n\r\n#include <boost/test/detail/class_properties.hpp>\r\n\r\nnamespace boost {\r\n\r\nnamespace test_tools {\r\n\r\nusing unit_test::readonly_property;\r\n\r\n// ************************************************************************** //\r\n// **************        floating_point_comparison_type        ************** //\r\n// ************************************************************************** //\r\n\r\nenum floating_point_comparison_type { FPC_STRONG, FPC_WEAK };\r\n\r\n// ************************************************************************** //\r\n// **************                    details                   ************** //\r\n// ************************************************************************** //\r\n\r\nnamespace tt_detail {\r\n\r\ntemplate<typename FPT>\r\ninline FPT\r\nfpt_abs( FPT arg ) \r\n{\r\n    return arg < 0 ? -arg : arg;\r\n}\r\n\r\n//____________________________________________________________________________//\r\n\r\n// both f1 and f2 are unsigned here\r\ntemplate<typename FPT>\r\ninline FPT \r\nsafe_fpt_division( FPT f1, FPT f2 )\r\n{\r\n    return  (f2 < 1 && f1 > f2 * (std::numeric_limits<FPT>::max)())               ? (std::numeric_limits<FPT>::max)()\r\n            : ((f2 > 1 && f1 < f2 * (std::numeric_limits<FPT>::min)() || f1 == 0) ? 0\r\n                                                                                  : f1/f2 );\r\n}\r\n\r\n//____________________________________________________________________________//\r\n\r\n} // namespace tt_detail\r\n\r\n// ************************************************************************** //\r\n// **************             close_at_tolerance               ************** //\r\n// ************************************************************************** //\r\n\r\ntemplate<typename FPT, typename PersentType = FPT >\r\nclass close_at_tolerance {\r\npublic:\r\n    explicit    close_at_tolerance( PersentType percentage_tolerance, floating_point_comparison_type fpc_type = FPC_STRONG ) \r\n    : p_fraction_tolerance( static_cast<FPT>(0.01)*percentage_tolerance ), p_strong_or_weak( fpc_type ==  FPC_STRONG ) {}\r\n\r\n    bool        operator()( FPT left, FPT right ) const\r\n    {\r\n        FPT diff = tt_detail::fpt_abs( left - right );\r\n        FPT d1   = tt_detail::safe_fpt_division( diff, tt_detail::fpt_abs( right ) );\r\n        FPT d2   = tt_detail::safe_fpt_division( diff, tt_detail::fpt_abs( left ) );\r\n        \r\n        return p_strong_or_weak ? (d1 <= p_fraction_tolerance.get() && d2 <= p_fraction_tolerance.get()) \r\n                                : (d1 <= p_fraction_tolerance.get() || d2 <= p_fraction_tolerance.get());\r\n    }\r\n\r\n    // Public properties\r\n    readonly_property<FPT>  p_fraction_tolerance;\r\n    readonly_property<bool> p_strong_or_weak;\r\n};\r\n\r\n//____________________________________________________________________________//\r\n\r\n// ************************************************************************** //\r\n// **************               check_is_close                 ************** //\r\n// ************************************************************************** //\r\n\r\ntemplate<typename FPT, typename PersentType>\r\ninline bool\r\ncheck_is_close( FPT left, FPT right, PersentType percentage_tolerance, floating_point_comparison_type fpc_type = FPC_STRONG )\r\n{\r\n    close_at_tolerance<FPT,PersentType> pred( percentage_tolerance, fpc_type );\r\n\r\n    return pred( left, right );\r\n}\r\n\r\n//____________________________________________________________________________//\r\n\r\ntemplate<typename FPT>\r\ninline FPT\r\ncompute_tolerance( FPT percentage_tolerance )\r\n{\r\n    close_at_tolerance<FPT> pred( percentage_tolerance );\r\n\r\n    return pred.p_fraction_tolerance.get();\r\n}\r\n\r\n//____________________________________________________________________________//\r\n\r\n} // namespace test_tools\r\n} // namespace boost\r\n\r\n// ***************************************************************************\r\n//  Revision History :\r\n//  \r\n//  $Log: floating_point_comparison.hpp,v $\r\n//  Revision 1.18  2004/07/19 12:14:09  rogeeff\r\n//  guard rename\r\n//  tolerance parameter renamed for clarity\r\n//\r\n//  Revision 1.17  2004/06/07 07:33:49  rogeeff\r\n//  detail namespace renamed\r\n//\r\n//  Revision 1.16  2004/05/21 06:19:35  rogeeff\r\n//  licence update\r\n//\r\n//  Revision 1.15  2004/05/11 11:00:34  rogeeff\r\n//  basic_cstring introduced and used everywhere\r\n//  class properties reworked\r\n//\r\n//  Revision 1.14  2004/02/26 18:26:57  eric_niebler\r\n//  remove minmax hack from win32.hpp and fix all places that could be affected by the minmax macros\r\n//\r\n//  Revision 1.13  2003/12/01 00:41:56  rogeeff\r\n//  prerelease cleaning\r\n//\r\n// ***************************************************************************\r\n\r\n#endif // BOOST_FLOATING_POINT_COMAPARISON_HPP_071894GER\r\n", "meta": {"hexsha": "167d5dfbe9a68df0a348ab1973f801a59944a9ef", "size": 5403, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "CvGameCoreDLL/Boost-1.32.0/include/boost/test/floating_point_comparison.hpp", "max_stars_repo_name": "macaurther/DOCUSA", "max_stars_repo_head_hexsha": "40586727c351d1b1130c05c2d4648cca3a8bacf5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 93.0, "max_stars_repo_stars_event_min_datetime": "2015-11-20T04:13:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T00:03:08.000Z", "max_issues_repo_path": "CvGameCoreDLL/Boost-1.32.0/include/boost/test/floating_point_comparison.hpp", "max_issues_repo_name": "macaurther/DOCUSA", "max_issues_repo_head_hexsha": "40586727c351d1b1130c05c2d4648cca3a8bacf5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 206.0, "max_issues_repo_issues_event_min_datetime": "2015-11-09T00:27:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-04T19:05:18.000Z", "max_forks_repo_path": "CvGameCoreDLL/Boost-1.32.0/include/boost/test/floating_point_comparison.hpp", "max_forks_repo_name": "dguenms/Dawn-of-Civilization", "max_forks_repo_head_hexsha": "1c4f510af97a869637cddb4c0859759158cea5ce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 117.0, "max_forks_repo_forks_event_min_datetime": "2015-11-08T02:43:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-12T06:29:00.000Z", "avg_line_length": 37.0068493151, "max_line_length": 126, "alphanum_fraction": 0.5454377198, "num_tokens": 1115, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.6370307875894138, "lm_q1q2_score": 0.4676567404059915}}
{"text": "//\n// $Id$\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#ifndef DETERMINEBINWIDTHUTILITIES_H\n#define DETERMINEBINWIDTHUTILITIES_H\n\n#include <functional>\n#include <boost/cstdint.hpp>\n#include <algorithm>\n\nnamespace ralab\n{\n  namespace base\n  {\n    namespace resample\n    {\n\n      typedef boost::int32_t int32_t;\n      namespace utilities{\n\n        template<class T>\n        struct meanfunctor : std::binary_function<T,T,T>{\n          T operator()(const T & x, const T& y){\n            return (x+y)/2.;\n          }\n        };\n\n\n        template <\n            typename InputIterator,\n            typename OutputIterator,\n            typename TN //= int32_t\n            >\n        OutputIterator summ\n        (\n            InputIterator begin, //!< [in] begin\n            InputIterator end, //!< [in] end\n            OutputIterator destBegin, //!< [out] dest begin\n            TN lag = 1//!< [in] an integer indicating which lag to use.\n            )\n        {\n          return( std::transform(begin + lag\n                                 , end\n                                 , begin\n                                 , destBegin\n                                 , meanfunctor<typename InputIterator::value_type>())\n                  );\n        }\n\n        template<typename TRealI>\n        double determine(TRealI begin, TRealI end,double maxj=5.){\n          //BOOST_ASSERT(!boost::range::is_sorted(begin,end));\n          double j = 1.;\n          double average = *begin;\n          double sum = average;\n          int32_t i = 1;\n          for(; begin != end ; ++begin, ++i){\n              while(*begin > (j+0.5) *average){\n                  ++j;\n                }\n              if(j > maxj){\n                  break;\n                }\n              sum += *begin/j;\n              average = sum/static_cast<double>(i);\n            }\n          return average;\n\n        }\n      }\n\n\n    }\n  }\n}\n#endif\n", "meta": {"hexsha": "c171eecaeecf60a3da19184e69dc2651fb96b076", "size": 2504, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pwiz/utility/findmf/base/resample/utilities/determinebinwidth.hpp", "max_stars_repo_name": "austinkeller/pwiz", "max_stars_repo_head_hexsha": "aa8e575cb40fd5e97cc7d922e4d8da44c9277cca", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pwiz/utility/findmf/base/resample/utilities/determinebinwidth.hpp", "max_issues_repo_name": "austinkeller/pwiz", "max_issues_repo_head_hexsha": "aa8e575cb40fd5e97cc7d922e4d8da44c9277cca", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pwiz/utility/findmf/base/resample/utilities/determinebinwidth.hpp", "max_forks_repo_name": "austinkeller/pwiz", "max_forks_repo_head_hexsha": "aa8e575cb40fd5e97cc7d922e4d8da44c9277cca", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6382978723, "max_line_length": 85, "alphanum_fraction": 0.5303514377, "num_tokens": 548, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432182679956, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.4675439804281146}}
{"text": "//\n// Copyright \u00a9 2017 Arm Ltd. All rights reserved.\n// SPDX-License-Identifier: MIT\n//\n#include \"DriverTestHelpers.hpp\"\n\n#include \"../1.0/HalPolicy.hpp\"\n\n#include <boost/test/unit_test.hpp>\n\n#include <log/log.h>\n\nBOOST_AUTO_TEST_SUITE(FullyConnectedTests)\n\nusing namespace android::hardware;\nusing namespace driverTestHelpers;\nusing namespace armnn_driver;\n\nusing HalPolicy = hal_1_0::HalPolicy;\n\n// Add our own test here since we fail the fc tests which Google supplies (because of non-const weights)\nBOOST_AUTO_TEST_CASE(FullyConnected)\n{\n    // this should ideally replicate fully_connected_float.model.cpp\n    // but that uses slightly weird dimensions which I don't think we need to support for now\n\n    auto driver = std::make_unique<ArmnnDriver>(DriverOptions(armnn::Compute::CpuRef));\n    HalPolicy::Model model = {};\n\n    // add operands\n    int32_t actValue      = 0;\n    float   weightValue[] = {2, 4, 1};\n    float   biasValue[]   = {4};\n\n    AddInputOperand<HalPolicy>(model, hidl_vec<uint32_t>{1, 3});\n    AddTensorOperand<HalPolicy>(model, hidl_vec<uint32_t>{1, 3}, weightValue);\n    AddTensorOperand<HalPolicy>(model, hidl_vec<uint32_t>{1}, biasValue);\n    AddIntOperand<HalPolicy>(model, actValue);\n    AddOutputOperand<HalPolicy>(model, hidl_vec<uint32_t>{1, 1});\n\n    // make the fully connected operation\n    model.operations.resize(1);\n    model.operations[0].type = HalPolicy::OperationType::FULLY_CONNECTED;\n    model.operations[0].inputs  = hidl_vec<uint32_t>{0, 1, 2, 3};\n    model.operations[0].outputs = hidl_vec<uint32_t>{4};\n\n    // make the prepared model\n    android::sp<V1_0::IPreparedModel> preparedModel = PrepareModel(model, *driver);\n\n    // construct the request\n    V1_0::DataLocation inloc = {};\n    inloc.poolIndex = 0;\n    inloc.offset    = 0;\n    inloc.length    = 3 * sizeof(float);\n    RequestArgument input = {};\n    input.location = inloc;\n    input.dimensions = hidl_vec<uint32_t>{};\n\n    V1_0::DataLocation outloc = {};\n    outloc.poolIndex = 1;\n    outloc.offset    = 0;\n    outloc.length    = 1 * sizeof(float);\n    RequestArgument output = {};\n    output.location  = outloc;\n    output.dimensions = hidl_vec<uint32_t>{};\n\n    V1_0::Request request = {};\n    request.inputs  = hidl_vec<RequestArgument>{input};\n    request.outputs = hidl_vec<RequestArgument>{output};\n\n    // set the input data (matching source test)\n    float indata[] = {2, 32, 16};\n    AddPoolAndSetData<float>(3, request, indata);\n\n    // add memory for the output\n    android::sp<IMemory> outMemory = AddPoolAndGetData<float>(1, request);\n    float* outdata = static_cast<float*>(static_cast<void*>(outMemory->getPointer()));\n\n    // run the execution\n    if (preparedModel.get() != nullptr)\n    {\n        Execute(preparedModel, request);\n    }\n\n    // check the result\n    BOOST_TEST(outdata[0] == 152);\n}\n\nBOOST_AUTO_TEST_CASE(TestFullyConnected4dInput)\n{\n    auto driver = std::make_unique<ArmnnDriver>(DriverOptions(armnn::Compute::CpuRef));\n\n    V1_0::ErrorStatus error;\n    std::vector<bool> sup;\n\n    ArmnnDriver::getSupportedOperations_cb cb = [&](V1_0::ErrorStatus status, const std::vector<bool>& supported)\n        {\n            error = status;\n            sup = supported;\n        };\n\n    HalPolicy::Model model = {};\n\n    // operands\n    int32_t actValue      = 0;\n    float   weightValue[] = {1, 0, 0, 0, 0, 0, 0, 0,\n                             0, 1, 0, 0, 0, 0, 0, 0,\n                             0, 0, 1, 0, 0, 0, 0, 0,\n                             0, 0, 0, 1, 0, 0, 0, 0,\n                             0, 0, 0, 0, 1, 0, 0, 0,\n                             0, 0, 0, 0, 0, 1, 0, 0,\n                             0, 0, 0, 0, 0, 0, 1, 0,\n                             0, 0, 0, 0, 0, 0, 0, 1}; //identity\n    float   biasValue[]   = {0, 0, 0, 0, 0, 0, 0, 0};\n\n    // fully connected operation\n    AddInputOperand<HalPolicy>(model, hidl_vec<uint32_t>{1, 1, 1, 8});\n    AddTensorOperand<HalPolicy>(model, hidl_vec<uint32_t>{8, 8}, weightValue);\n    AddTensorOperand<HalPolicy>(model, hidl_vec<uint32_t>{8}, biasValue);\n    AddIntOperand<HalPolicy>(model, actValue);\n    AddOutputOperand<HalPolicy>(model, hidl_vec<uint32_t>{1, 8});\n\n    model.operations.resize(1);\n\n    model.operations[0].type = HalPolicy::OperationType::FULLY_CONNECTED;\n    model.operations[0].inputs  = hidl_vec<uint32_t>{0,1,2,3};\n    model.operations[0].outputs = hidl_vec<uint32_t>{4};\n\n    // make the prepared model\n    android::sp<V1_0::IPreparedModel> preparedModel = PrepareModel(model, *driver);\n\n    // construct the request\n    V1_0::DataLocation inloc = {};\n    inloc.poolIndex          = 0;\n    inloc.offset             = 0;\n    inloc.length             = 8 * sizeof(float);\n    RequestArgument input    = {};\n    input.location           = inloc;\n    input.dimensions         = hidl_vec<uint32_t>{};\n\n    V1_0::DataLocation outloc = {};\n    outloc.poolIndex          = 1;\n    outloc.offset             = 0;\n    outloc.length             = 8 * sizeof(float);\n    RequestArgument output    = {};\n    output.location           = outloc;\n    output.dimensions         = hidl_vec<uint32_t>{};\n\n    V1_0::Request request = {};\n    request.inputs  = hidl_vec<RequestArgument>{input};\n    request.outputs = hidl_vec<RequestArgument>{output};\n\n    // set the input data\n    float indata[] = {1,2,3,4,5,6,7,8};\n    AddPoolAndSetData(8, request, indata);\n\n    // add memory for the output\n    android::sp<IMemory> outMemory = AddPoolAndGetData<float>(8, request);\n    float* outdata = static_cast<float*>(static_cast<void*>(outMemory->getPointer()));\n\n    // run the execution\n    if (preparedModel != nullptr)\n    {\n        Execute(preparedModel, request);\n    }\n\n    // check the result\n    BOOST_TEST(outdata[0] == 1);\n    BOOST_TEST(outdata[1] == 2);\n    BOOST_TEST(outdata[2] == 3);\n    BOOST_TEST(outdata[3] == 4);\n    BOOST_TEST(outdata[4] == 5);\n    BOOST_TEST(outdata[5] == 6);\n    BOOST_TEST(outdata[6] == 7);\n    BOOST_TEST(outdata[7] == 8);\n}\n\nBOOST_AUTO_TEST_CASE(TestFullyConnected4dInputReshape)\n{\n    auto driver = std::make_unique<ArmnnDriver>(DriverOptions(armnn::Compute::CpuRef));\n\n    V1_0::ErrorStatus error;\n    std::vector<bool> sup;\n\n    ArmnnDriver::getSupportedOperations_cb cb = [&](V1_0::ErrorStatus status, const std::vector<bool>& supported)\n        {\n            error = status;\n            sup = supported;\n        };\n\n    HalPolicy::Model model = {};\n\n    // operands\n    int32_t actValue      = 0;\n    float   weightValue[] = {1, 0, 0, 0, 0, 0, 0, 0,\n                             0, 1, 0, 0, 0, 0, 0, 0,\n                             0, 0, 1, 0, 0, 0, 0, 0,\n                             0, 0, 0, 1, 0, 0, 0, 0,\n                             0, 0, 0, 0, 1, 0, 0, 0,\n                             0, 0, 0, 0, 0, 1, 0, 0,\n                             0, 0, 0, 0, 0, 0, 1, 0,\n                             0, 0, 0, 0, 0, 0, 0, 1}; //identity\n    float   biasValue[]   = {0, 0, 0, 0, 0, 0, 0, 0};\n\n    // fully connected operation\n    AddInputOperand<HalPolicy>(model, hidl_vec<uint32_t>{1, 2, 2, 2});\n    AddTensorOperand<HalPolicy>(model, hidl_vec<uint32_t>{8, 8}, weightValue);\n    AddTensorOperand<HalPolicy>(model, hidl_vec<uint32_t>{8}, biasValue);\n    AddIntOperand<HalPolicy>(model, actValue);\n    AddOutputOperand<HalPolicy>(model, hidl_vec<uint32_t>{1, 8});\n\n    model.operations.resize(1);\n\n    model.operations[0].type = HalPolicy::OperationType::FULLY_CONNECTED;\n    model.operations[0].inputs  = hidl_vec<uint32_t>{0,1,2,3};\n    model.operations[0].outputs = hidl_vec<uint32_t>{4};\n\n    // make the prepared model\n    android::sp<V1_0::IPreparedModel> preparedModel = PrepareModel(model, *driver);\n\n    // construct the request\n    V1_0::DataLocation inloc = {};\n    inloc.poolIndex          = 0;\n    inloc.offset             = 0;\n    inloc.length             = 8 * sizeof(float);\n    RequestArgument input    = {};\n    input.location           = inloc;\n    input.dimensions         = hidl_vec<uint32_t>{};\n\n    V1_0::DataLocation outloc = {};\n    outloc.poolIndex          = 1;\n    outloc.offset             = 0;\n    outloc.length             = 8 * sizeof(float);\n    RequestArgument output    = {};\n    output.location           = outloc;\n    output.dimensions         = hidl_vec<uint32_t>{};\n\n    V1_0::Request request = {};\n    request.inputs  = hidl_vec<RequestArgument>{input};\n    request.outputs = hidl_vec<RequestArgument>{output};\n\n    // set the input data\n    float indata[] = {1,2,3,4,5,6,7,8};\n    AddPoolAndSetData(8, request, indata);\n\n    // add memory for the output\n    android::sp<IMemory> outMemory = AddPoolAndGetData<float>(8, request);\n    float* outdata = static_cast<float*>(static_cast<void*>(outMemory->getPointer()));\n\n    // run the execution\n    if (preparedModel != nullptr)\n    {\n        Execute(preparedModel, request);\n    }\n\n    // check the result\n    BOOST_TEST(outdata[0] == 1);\n    BOOST_TEST(outdata[1] == 2);\n    BOOST_TEST(outdata[2] == 3);\n    BOOST_TEST(outdata[3] == 4);\n    BOOST_TEST(outdata[4] == 5);\n    BOOST_TEST(outdata[5] == 6);\n    BOOST_TEST(outdata[6] == 7);\n    BOOST_TEST(outdata[7] == 8);\n}\n\nBOOST_AUTO_TEST_CASE(TestFullyConnectedWeightsAsInput)\n{\n    auto driver = std::make_unique<ArmnnDriver>(DriverOptions(armnn::Compute::CpuRef));\n\n    V1_0::ErrorStatus error;\n    std::vector<bool> sup;\n\n    ArmnnDriver::getSupportedOperations_cb cb = [&](V1_0::ErrorStatus status, const std::vector<bool>& supported)\n    {\n        error = status;\n        sup = supported;\n    };\n\n    HalPolicy::Model model = {};\n\n    // operands\n    int32_t actValue      = 0;\n    float   weightValue[] = {1, 0, 0, 0, 0, 0, 0, 0,\n                             0, 1, 0, 0, 0, 0, 0, 0,\n                             0, 0, 1, 0, 0, 0, 0, 0,\n                             0, 0, 0, 1, 0, 0, 0, 0,\n                             0, 0, 0, 0, 1, 0, 0, 0,\n                             0, 0, 0, 0, 0, 1, 0, 0,\n                             0, 0, 0, 0, 0, 0, 1, 0,\n                             0, 0, 0, 0, 0, 0, 0, 1}; //identity\n    float   biasValue[]   = {0, 0, 0, 0, 0, 0, 0, 0};\n\n    // fully connected operation\n    AddInputOperand<HalPolicy>(model, hidl_vec<uint32_t>{1, 1, 1, 8});\n    AddInputOperand<HalPolicy>(model, hidl_vec<uint32_t>{8, 8});\n    AddInputOperand<HalPolicy>(model, hidl_vec<uint32_t>{8});\n    AddIntOperand<HalPolicy>(model, actValue);\n    AddOutputOperand<HalPolicy>(model, hidl_vec<uint32_t>{1, 8});\n\n    model.operations.resize(1);\n\n    model.operations[0].type = HalPolicy::OperationType::FULLY_CONNECTED;\n    model.operations[0].inputs  = hidl_vec<uint32_t>{0,1,2,3};\n    model.operations[0].outputs = hidl_vec<uint32_t>{4};\n\n    // make the prepared model\n    android::sp<V1_0::IPreparedModel> preparedModel = PrepareModel(model, *driver);\n\n    // construct the request for input\n    V1_0::DataLocation inloc = {};\n    inloc.poolIndex          = 0;\n    inloc.offset             = 0;\n    inloc.length             = 8 * sizeof(float);\n    RequestArgument input    = {};\n    input.location           = inloc;\n    input.dimensions         = hidl_vec<uint32_t>{1, 1, 1, 8};\n\n    // construct the request for weights as input\n    V1_0::DataLocation wloc = {};\n    wloc.poolIndex          = 1;\n    wloc.offset             = 0;\n    wloc.length             = 64 * sizeof(float);\n    RequestArgument weights = {};\n    weights.location        = wloc;\n    weights.dimensions      = hidl_vec<uint32_t>{8, 8};\n\n    // construct the request for bias as input\n    V1_0::DataLocation bloc = {};\n    bloc.poolIndex          = 2;\n    bloc.offset             = 0;\n    bloc.length             = 8 * sizeof(float);\n    RequestArgument bias    = {};\n    bias.location           = bloc;\n    bias.dimensions         = hidl_vec<uint32_t>{8};\n\n    V1_0::DataLocation outloc = {};\n    outloc.poolIndex          = 3;\n    outloc.offset             = 0;\n    outloc.length             = 8 * sizeof(float);\n    RequestArgument output    = {};\n    output.location           = outloc;\n    output.dimensions         = hidl_vec<uint32_t>{1, 8};\n\n    V1_0::Request request = {};\n    request.inputs  = hidl_vec<RequestArgument>{input, weights, bias};\n    request.outputs = hidl_vec<RequestArgument>{output};\n\n    // set the input data\n    float indata[] = {1,2,3,4,5,6,7,8};\n    AddPoolAndSetData(8, request, indata);\n\n    // set the weights data\n    AddPoolAndSetData(64, request, weightValue);\n    // set the bias data\n    AddPoolAndSetData(8, request, biasValue);\n\n    // add memory for the output\n    android::sp<IMemory> outMemory = AddPoolAndGetData<float>(8, request);\n    float* outdata = static_cast<float*>(static_cast<void*>(outMemory->getPointer()));\n\n    // run the execution\n    if (preparedModel != nullptr)\n    {\n        Execute(preparedModel, request);\n    }\n\n    // check the result\n    BOOST_TEST(outdata[0] == 1);\n    BOOST_TEST(outdata[1] == 2);\n    BOOST_TEST(outdata[2] == 3);\n    BOOST_TEST(outdata[3] == 4);\n    BOOST_TEST(outdata[4] == 5);\n    BOOST_TEST(outdata[5] == 6);\n    BOOST_TEST(outdata[6] == 7);\n    BOOST_TEST(outdata[7] == 8);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "a68a587066f0def43abf8acbdabe76706dbb173c", "size": 13053, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/FullyConnected.cpp", "max_stars_repo_name": "QPC-database/android-nn-driver", "max_stars_repo_head_hexsha": "42d0f1f5b17857259e4de60357a12464ef9e1752", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-03T23:50:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-03T23:50:52.000Z", "max_issues_repo_path": "test/FullyConnected.cpp", "max_issues_repo_name": "QPC-database/android-nn-driver", "max_issues_repo_head_hexsha": "42d0f1f5b17857259e4de60357a12464ef9e1752", "max_issues_repo_licenses": ["MIT"], "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/FullyConnected.cpp", "max_forks_repo_name": "QPC-database/android-nn-driver", "max_forks_repo_head_hexsha": "42d0f1f5b17857259e4de60357a12464ef9e1752", "max_forks_repo_licenses": ["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.35, "max_line_length": 113, "alphanum_fraction": 0.5922010266, "num_tokens": 3927, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.6477982247516797, "lm_q1q2_score": 0.46754396776616924}}
{"text": "//\n// Created by Anshuman Mishra on 11/25/19.\n//\n\n// These statements are saying to include source code that is stored somewhere else (these come with most compilers)\n#include <iostream>\t\t// For console i/o\n#include <vector>\t\t// For arrays that we don't use for linear algebra\n#include <string>\t\t// For strings used in file names\n#include <fstream>\t\t// For file i/o\n#include <iomanip>\t\t// For setprecision when printing numbers to the console or files\n\n\n#include <boost/math/special_functions/beta.hpp>\n#include <algorithm>\n#include <Eigen/Dense>\n\n#include \"headers/MathUtils.h\"\n#include \"headers/Policy.h\"\n#include \"headers/Cartpole.h\"\n#include \"headers/Gridworld.hpp\"\n#include \"headers/Walk.h\"\n#include \"headers/FourierBasis.h\"\n#include \"headers/HelperFunctions.hh\"\n\nusing namespace std;\t\t\t// Some terms below are \"inside\" std. For example, cout, cin, and endl. Normally you have to write std::cout. This line makes it so that you don't have to write std:: before everything you are using from standard libraries.\nusing namespace Eigen;\nusing namespace boost::math;\n\nvoid checkpoint(){\n  cout << \"Checkpoint\"; getchar();\n}\n\nstruct HistoryElement{\n  vector<double> state;\n  int action;\n  double reward;\n\n  HistoryElement (vector<double> s, int a, double r){\n    state = s;\n    action = a;\n    reward = r;\n  }\n};\n\ndouble PDIS(const vector<HistoryElement>& history, const Policy piE, const Policy piB, double gamma, const FourierBasis& fb){\n//  cout << \"Called PDIS for history\" << endl;\n  double value = 0;\n  double gammaCoeff = 1.0;\n  double piCoeff = 1.0;\n  for (HistoryElement el : history){\n//    cout << el.state[0] << el.action << el.reward << endl;\n    vector<double> phi_vec = fb.basify(el.state);\n    Map<VectorXd> phi = VectorXd::Map(&phi_vec[0], phi_vec.size());\n    piCoeff *= (piE.getActionProbability(phi, el.action) / piB.getActionProbability(phi, el.action));\n    value += gammaCoeff * piCoeff * el.reward;\n//    cout << \"Gamma: \" << gammaCoeff << \" Pi: \" << piCoeff << \" Value: \" << value << endl;\n//    getchar();\n    gammaCoeff *= gamma;\n    if (isnan(value)){\n      cout << \"PDIS is nan\" << endl;\n      cout << \"piCoeff: \" << piCoeff << \" gammaCoeff: \" << gammaCoeff << \" Reward: \" << el.reward << endl;\n      getchar();\n    }\n  }\n//  cout << \"PDIS = \" << value << endl;\n  return value;\n}\n\nVectorXd PDIS(const vector<vector<HistoryElement> >& data, const Policy& piE, const Policy& piB, double gamma, const FourierBasis& fb){\n//  cout << \"Called PDIS for data\" << endl;\n  VectorXd pdis(data.size());\n  for (int h=0; h<data.size(); h++)\n    pdis[h] = PDIS(data[h], piE, piB, gamma, fb);\n  return pdis;\n}\n\nvoid splitData(\n    const vector<vector<HistoryElement> >& data,\n    vector<vector<HistoryElement> >& Dc,\n    vector<vector<HistoryElement> >& Ds,\n    double ratio){\n  int d = data.size();\n  int i=0;\n  while (i<d*ratio){\n    Dc.push_back(data[i++]);\n  }\n  while (i<data.size()){\n    Ds.push_back(data[i++]);\n  }\n  cout << \"Split: \" << data.size() << \" => \" << Dc.size() << \",\" << Ds.size() << endl;\n}\n\nbool candidatePassesTest(const vector<vector<HistoryElement>>& Ds, const Policy piE, const Policy piB, const FourierBasis& fb, const double delta, const double confBound){\n  cout << \"Testing Candidate\" << endl;\n  VectorXd j = PDIS(Ds, piE, piB, 1.0, fb); // Get the primary objective\n  double ub = ttestLowerBound(j, delta);\n  cout << \"Target: \" << confBound << \" UB: \" << ub << endl;\n  return ub > confBound;\n}\n\n// The objective function maximized by getCandidateSolution.\ndouble candidateObjective(\n    const VectorXd& theta,                // The solution to evaluate\n    const void * params[],                // Other terms that we need to compute the objective value, packed into one object - an array of const pointers to objects of unknown types (unknown to CMA-ES, but known to us here as we packed this object)\n    mt19937_64& generator)                // The random number generator to use)\n{\n//  cout << \"Evaluating Candidate\" << endl;\n  const vector<vector<HistoryElement>>* data = (vector<vector<HistoryElement>>*) params[0];\n  Policy* piE = (Policy*) params[1];\n  const Policy* piB = (Policy*) params[2];\n  const FourierBasis* fb = (FourierBasis*) params[3];\n  const int* safetyDataSize = (int*) params[4];\n  const double* c = (double*) params[5];\n  const double* delta = (double*) params[6];\n\n  piE->setTheta(theta);\n//  checkpoint();\n  VectorXd j = PDIS(*data, *piE, *piB, 1.0, *fb); // Get the primary objective\n  double ub = ttestLowerBound(j, *delta, *safetyDataSize);\n  double result;\n  cout << \" Mean: \" << j.mean() << \" StdDev: \" << stddev(j) << \" ttest: \" << ub << endl;\n  if (ub < *c) {\n    cout << \"Failed Barrier Function\" << endl;\n    result = -100;\n  }\n  else\n    result = j.mean();\n//  cout << \"Result : \" << result << endl;\n  return result;\n}\n\n// Use the provided data to get a solution expected to pass the safety test\nVectorXd getCandidateSolution(\n    const vector<vector<HistoryElement> >& data,\n    const double delta,\n    const int safetyDataSize,\n    Policy& piE,\n    const Policy& piB,\n    const FourierBasis& fb,\n    const double c,\n    mt19937_64 & generator) {\n  VectorXd initialSolution = piE.getTheta();\n  double initialSigma = 2.0*(initialSolution.dot(initialSolution) + 1.0); // A heuristic to select the width of the search based on the weight magnitudes we expect to see.\n  int numIterations = 100;                          // Number of iterations that CMA-ES should run. Larger is better, but takes longer.\n  bool minimize = false;                            // We want to maximize the candidate objective.\n  // Pack parameters of candidate objective into params. In candidateObjective we need to unpack in the same order.\n  const void* params[7];\n\n  params[0] = &data;\n  params[1] = &piE;\n  params[2] = &piB;\n  params[3] = &fb;\n  params[4] = &safetyDataSize;\n  params[5] = &c;\n  params[6] = &delta;\n\n  cout << \"Calling CMAES\" << endl;\n  // Use CMA-ES to get a solution that approximately maximizes candidateObjective\n  return CMAES(initialSolution, initialSigma, numIterations, candidateObjective, params, minimize, generator);\n}\n\ndouble getTarget(const vector<vector<HistoryElement>>& data){\n  double gamma = 1.0;\n  int numEpisodes = data.size();\n  VectorXd returns(data.size());\n  for (int e = 0; e<data.size(); e++){\n    double episodeReturn = 0.0;\n    double gammaCoeff = 1.0;\n    for (HistoryElement he : data[e]){\n      episodeReturn += gammaCoeff*he.reward;\n      gammaCoeff *= gamma;\n    }\n    returns[e] = episodeReturn;\n//    if (data[e].size() > 10 || episodeReturn < -10)\n//      checkpoint();\n  }\n  double avgReturn = returns.mean();\n  return (avgReturn > 0 ? 1.1 : 0.9)*avgReturn;\n}\n\ntemplate <typename Environment>\ndouble getAverageReturn(Environment& e, Policy& pi, int numEpisodes, int maxEpisodeLength, const FourierBasis& fb){\n//  Cartpole e;\n  mt19937_64 gen(0);\n  double gamma = 1.0;\n  VectorXd returns(numEpisodes);\n\n  for (int eps = 0; eps < numEpisodes; eps++){\n    double curGamma = 1.0;\t\t\t\t\t// We plot the discounted return - this stores gamma^t, which starts at 1.\n    bool inTerminalState = false;\t\t\t// We will use this flag to determine when we should terminate the loop below. If environment[trial].inTerminalState() is slow to call, this saves us from calling it a couple times. For our MDPs it really doesn't matter that we're doing this more efficiently.\n    e.newEpisode(gen);\t// Reset the environment, telling it to start a new episode.\n    vector<double> state = e.getState(gen);\t// Get the initial state.\n    double episodeReturn = 0.0;\n    for (int t = 0; (t < maxEpisodeLength) && (!inTerminalState); t++) { // Loop over time steps in the episode, stopping when we hit the max episode length or when we enter a terminal state.\n      vector<double> phi_vec = fb.basify(state);\n      VectorXd phi = VectorXd::Map(&phi_vec[0], phi_vec.size());\n      int action = pi.getAction(phi);\n      double reward = e.update(action, gen); // Apply the action by updating the environment with the chosen action, and get the resulting reward.\n\n      vector<double> nextState = e.getState(gen); // Get the resulting state of the environment from this transition\n      inTerminalState = e.inTerminalState(); // Store whether this is next-state is a terminal state.\n\n      episodeReturn += curGamma*reward;\n      state = nextState; // Prepare for the next iteration of the loop with this line and the next.\n      curGamma *= gamma;\n    }\n    returns[eps] = episodeReturn;\n  }\n  cout << \"AvgReturn: \" << returns.mean() << endl;\n  return returns.mean();\n}\n\ntemplate <typename Environment>\nvoid generateData(Environment& e, int numEpisodes, int maxEpisodeLength, int order){\n  cout << \"Generating Data\" << endl;\n  // Generate Histories for some policy\n  // Write to file\n  ofstream out(\"../../../output/data.csv\");\n//  Cartpole e;\n  int stateDim = e.getStateDim();\n//  int order = 3;\n  int numActions = e.getNumActions();\n  FourierBasis fb;\n  fb.init(stateDim, 0, order);\n  mt19937_64 gen(0);\n\n  out << stateDim << endl;\n//  cout << \"StateDim in env \" << stateDim << \" \" << e.getState(gen).size() << endl;\n//  checkpoint();\n  out << numActions << endl;\n  out << order << endl;\n\n  Policy p(numActions, fb.getNumOutputs(), 1234);\n//  VectorXd params(numActions*fb.getNumOutputs());\n//  params << 0.452687,-0.123691,-0.187805,-0.0419247,-0.3103,0.0169222,-0.440849,0.171773,0.122356,-0.0208773,-0.377911,0.24458,-0.345339,0.221081,0.181478,0.0931315,0.316947,-0.237248,-0.0783118,0.102174,0.197309,0.0129477,0.237053,-0.283958,0.0931003,-0.159108,-0.11468,-0.0336945,-0.312665,0.0494717,-0.437631,0.185128,0.13921,0.124541,0.269549,-0.0445983,-0.311025,0.186034,0.181678,0.065481,0.311506,-0.245937,0.320217,-0.266973,-0.10468,-0.0398326,0.24824,-0.237777,0.0789096,-0.109312,-0.131987,-0.0215236,-0.190011,0.263565,-0.391198,0.144332,0.109239,0.0786274,0.245533,-0.0450382,0.407343,-0.221437,-0.0711912,-0.023617,0.332143,-0.184834,0.315291,-0.193174,-0.122204,-0.08163,-0.262694,0.218761,0.136993,-0.0538062,-0.220642,0.0300469,-0.256064,0.217929,-0.118554,0.118296,0.102564,0.289925,-0.14454,0.0308677,-0.036806,-0.119257,-0.000854144,-0.27288,0.174216,-0.101032,0.0331704,-0.236314,0.194932,-0.219322,0.183163,-0.00102567,0.0264519,0.160525,-0.151711,-0.0274355,0.101995,0.0911902,-0.0420769,0.179202,-0.249171,0.0371926,-0.122774,-0.0147314,-0.0374526,-0.1332,0.0527589,-0.267015,0.200302,-0.0525608,0.117418,0.0845154,-0.0264594,-0.182052,0.195832,0.0153543,0.0274128,0.176015,-0.22169,0.192534,-0.244502,0.0506698,-0.0728419,0.158957,-0.293461,-0.0106893,-0.141654,-0.00546437,0.0100509,-0.113205,0.273374,-0.185785,0.167286,-0.0742353,0.0805248,0.0537695,-0.0490843,0.207685,-0.225989,0.101884,-0.0554201,0.15327,-0.205815,0.138937,-0.206245,0.060542,-0.052369,-0.0965512,0.20772,-0.0393728,-0.0666479,-0.00757391,0.10165,-0.104987,0.26088,0.0429262,0.137972,-0.0754444;\n//  p.setTheta(params);\n  VectorXd params = p.getTheta();\n  for (int i=0; i<params.size(); i++){\n    out << params[i] << \",\";\n  }\n  out << endl;\n\n  out << numEpisodes << endl;\n\n  double gamma = 1.0;\n\n  vector<HistoryElement> firstEps;\n  for (int eps = 0; eps < numEpisodes; eps++){\n    double curGamma = 1.0;\t\t\t\t\t// We plot the discounted return - this stores gamma^t, which starts at 1.\n    bool inTerminalState = false;\t\t\t// We will use this flag to determine when we should terminate the loop below. If environment[trial].inTerminalState() is slow to call, this saves us from calling it a couple times. For our MDPs it really doesn't matter that we're doing this more efficiently.\n    e.newEpisode(gen);\t// Reset the environment, telling it to start a new episode.\n    vector<double> state = e.getState(gen);\t// Get the initial state.\n    for (int t = 0; (t < maxEpisodeLength) && (!inTerminalState); t++) { // Loop over time steps in the episode, stopping when we hit the max episode length or when we enter a terminal state.\n      vector<double> phi_vec = fb.basify(state);\n      VectorXd phi = VectorXd::Map(&phi_vec[0], phi_vec.size());\n      int action = p.getAction(phi);\n      double reward = e.update(action, gen); // Apply the action by updating the environment with the chosen action, and get the resulting reward.\n\n      for (double val : state)\n        out << val << \",\";\n      out << action << \",\";\n      out << reward;\n\n      if (eps == 0)\n        firstEps.push_back(HistoryElement(state, action, reward));\n\n      vector<double> nextState = e.getState(gen); // Get the resulting state of the environment from this transition\n      inTerminalState = e.inTerminalState(); // Store whether this is next-state is a terminal state.\n\n      if ((t < maxEpisodeLength-1) && (!inTerminalState))\n        out << \",\";\n\n      state = nextState; // Prepare for the next iteration of the loop with this line and the next.\n      curGamma *= gamma;\n    }\n    out<<endl;\n  }\n\n  for (int t=0; t<firstEps.size(); t++){\n    HistoryElement ht = firstEps[t];\n    vector<double> phi_vec = fb.basify(ht.state);\n    VectorXd phi = VectorXd::Map(&phi_vec[0], phi_vec.size());\n    out<< p.getActionProbability(phi, ht.action);\n    out << ((t==firstEps.size()-1) ? '\\n' : ',');\n  }\n\n  cout << \"Data Generation Complete\" << endl;\n}\n\nvector<Policy> HCOPE(\n    vector<vector<HistoryElement>>& data,\n    const int numPolicies,\n    const double delta,\n    const double target,\n    const Policy& piB,\n    const FourierBasis& fb,\n    const string outputDir){\n  // Split Data into Ds and Dc\n  vector<vector<HistoryElement> > Ds, Dc;\n  double dataSplitRatio = 0.6;\n  splitData(data, Dc, Ds, dataSplitRatio);\n\n//  int numPolicies = 100;\n\n  mt19937_64 generator(123);\n  cout << \"Target: \" << target << endl;\n//  Policy piE(numActions, fb.getNumOutputs(), 123);\n//  Policy piE (piB, 123);\n\n//  VectorXd theta(numActions*fb.getNumOutputs());\n//  theta << 1, 1, 0.01, -0.01;\n//  piE.setTheta(theta);\n//  VectorXd pdis = PDIS(data, piE, piB, 1.0, fb);\n//  cout << \"PDIS \" << pdis.mean() << endl;\n//\n//  pdis = PDIS(data, piB, piB, 1.0, fb);\n//  cout << \"PDIS \" << pdis.mean() << endl;\n//\n//  cout << \"Mean Return in Data \" << target/1.1 << endl;\n//  checkpoint();\n\n  // Loop while more policies need to be found\n//  ofstream policyOut(\"../../../output/result.csv\");\n\n  vector<Policy> policies(numPolicies, Policy(piB, 123));\n  #pragma omp parallel for\n  for (int p=0; p<numPolicies; p++){\n//  while(policies.size() < numPolicies){\n    bool passedTest = false;\n    VectorXd candidate;\n    while(!passedTest) {\n      //   Select Candidate Policy\n      policies[p].setTheta(piB.getTheta());\n      candidate = getCandidateSolution(Dc, delta, Ds.size(), policies[p], piB,\n                                       fb, target, generator);\n\n      cout << \"Generated Candidate\" << endl;\n      policies[p].setTheta(candidate);\n\n      passedTest = candidatePassesTest(Ds, policies[p], piB, fb, delta, target);\n      if (passedTest)\n        cout << \"****************** CANDIDATE PASSED TEST ******************\" << endl;\n      else\n        cout << \"****************** CANDIDATE FAILED TEST ******************\" << endl;\n    }\n    //   Store Candidate Policy if Test Passed\n    ofstream policyOut(outputDir + to_string(p) + \".csv\");\n    for (int i=0; i<candidate.size(); i++){\n      policyOut << candidate[i];\n      policyOut << (i == candidate.size()-1 ? \"\\n\":\",\") << flush;\n      cout << candidate[i];\n      cout << (i == candidate.size()-1 ? \"\\n\":\",\");\n    }\n    //checkpoint()\n  }\n  return policies;\n}\n\nvoid readData(\n    string filename,\n    int& stateDim,\n    int& numActions,\n    int& order,\n    Policy& piB,\n    int& numEpisodes,\n    FourierBasis& fb,\n    vector<vector<HistoryElement> >& data){\n  cout << \"Reading Data\" << endl;\n//  ifstream in(\"../../../output/data.csv\");\n//  ifstream in(\"../../../input/data.csv\");\n  ifstream in(filename);\n\n  in >> stateDim;\n  in >> numActions;\n  in >> order;\n\n  fb.init(stateDim, 0, order);\n\n  VectorXd thetaB(numActions*fb.getNumOutputs());\n//  cout << \"ThetaB \" << thetaB.size() << endl;\n\n  cout << \"Reading Policy\" << endl;\n  string s;\n  for (int i=0; i<thetaB.size(); i++){\n    char delim = (i == thetaB.size()-1 ? '\\n': ',');\n    getline(in, s, delim);\n    thetaB[i] = stod(s);\n//    cout << thetaB[i] << delim;\n  }\n  // Complete reading the line\n//  getline(in, s);\n\n  piB = Policy(thetaB, numActions, fb.getNumOutputs(), 123);\n\n  in >> numEpisodes;\n\n  for (int eps = 0; eps < numEpisodes; eps++){\n    vector<HistoryElement> episode;\n//    cout << \"Reading Episode \" << eps << endl;\n    string ep;\n    in >> ep;\n//    cout << ep << endl;\n\n    stringstream ss(ep);\n    while(ss.good()){\n      vector<double> state(stateDim, 0.0);\n//      cout << \"State: \";\n      for (int st = 0; st < stateDim; st++) {\n        getline(ss, s, ',');\n        state[st] = stod(s);\n//        cout << state[st] << \",\";\n      }\n//      cout << \" Action: \";\n\n      getline(ss, s, ',');\n      int action = stoi(s);\n//      cout << action << \", Reward: \";\n//      cout << action << \",\";\n\n      getline(ss, s, ',');\n      double reward = stod(s);\n//      cout << reward << \",\";\n//      cout << endl;\n//      cin >> s;\n      episode.push_back(HistoryElement(state, action, reward));\n    }\n//    cout << endl;\n    data.push_back(episode);\n  }\n\n  cout << \"Validating Policy Representation\" << endl;\n  string valPi;\n  in >> valPi;\n  stringstream ss(valPi);\n  VectorXd expectedPi(data[0].size());\n  VectorXd actualPi(data[0].size());\n  bool match = true;\n  for (int t=0; t<data[0].size(); t++){\n    HistoryElement ht = data[0][t];\n    vector<double> phi_vec = fb.basify(ht.state);\n    VectorXd phi = VectorXd::Map(&phi_vec[0], phi_vec.size());\n    actualPi[t] = piB.getActionProbability(phi, ht.action);\n\n    string s;\n    getline(ss, s, ',');\n//    cout << s << \", \";\n    expectedPi[t] = stod(s);\n\n    if (abs(expectedPi[t] - actualPi[t]) > 1e-5)\n      match = false;\n  }\n\n  if (!match){\n    cout << \"Policies Dont Match!\"  << endl;\n    cout << \"Expected: \" << expectedPi.transpose() << endl;\n    cout << \"Actual: \" << actualPi.transpose() << endl;\n    checkpoint();\n    return;\n  }\n\n  cout << \"Data Read Complete\" << endl;\n}\n\nvoid run() {\n\n  bool test = true;\n\n  /****************************************************************/\n\n  bool genData = false;\n  int genEpisodes = 100000, genMaxEpisodeLength = 15, genOrder = 1;\n//  Cartpole genEnv;\n  Gridworld genEnv;\n//  Walk genEnv;\n  if (test && genData)\n    generateData(genEnv, genEpisodes, genMaxEpisodeLength, genOrder);\n\n  /*********************** End of Data Prep ***********************/\n\n  int stateDim, numActions, order, numEpisodes;\n  Policy piB(0,0,0);\n  FourierBasis fb;\n  vector<vector<HistoryElement> > data;\n  if (test)\n    readData(\"../../../output/data.csv\", stateDim, numActions, order, piB, numEpisodes, fb, data);\n  else\n    readData(\"../../../input/data.csv\", stateDim, numActions, order, piB, numEpisodes, fb, data);\n\n  cout << \"stateDim: \" << stateDim << endl;\n  cout << \"numActions: \" << numActions << endl;\n  cout << \"order: \" << order << endl;\n  cout << \"Policy: \" << piB.getTheta().transpose() << endl;\n  cout << \"numEpisodes: \" << numEpisodes << endl;\n\n  /*********************** End of Data Read ***********************/\n\n//  VectorXd testTheta(piB.getTheta().size());\n//  testTheta << 0.33304397, -1.3536084, -0.391217, -2.93140976, -4.07265164, -2.13137546, -1.94398795, 2.53769193;\n//  Policy testPolicy (piB);\n//  testPolicy.setTheta(testTheta);\n//  double avgReturn = getAverageReturn(genEnv, testPolicy, genEpisodes, genMaxEpisodeLength, fb);\n//  return;\n\n  /********************* End of Testing Space *********************/\n\n  int numPolicies = 50;\n  double delta = 0.05;\n  double target = getTarget(data);\n  string outputDir;\n  if (test)\n    outputDir = \"../../../result/\" + to_string(delta) + \"_\";\n  else\n    outputDir = \"../../../final_result/\";\n  vector<Policy> policies = HCOPE(data, numPolicies, delta, target, piB, fb, outputDir);\n\n  /********************* End of Policy Search *********************/\n\n  if (test) {\n      // Validate policies found\n      cout << \"Validating Result Policies\" << endl;\n      int worked = 0;\n      for (auto policy : policies){\n        double avgReturn = getAverageReturn(genEnv, policy, genEpisodes, genMaxEpisodeLength, fb);\n        if (avgReturn >= target/1.1)\n          worked++;\n      }\n\n      cout << \"Reality Check! #Policies that worked: \" << worked << \"/\" << policies.size() << endl;\n  }\n}\n\nint main(int argc, char* argv[])\n{\n  run();\n//  VectorXd a(4);\n//  a  << 1.0, 2.0, 3.0, 4.0;\n//  cout << a << endl;\n//  MatrixXd m = MatrixXd::Map(a.data(), 2,2);\n//  cout << m << endl;\n//\n//  VectorXd b(4);\n//  b << 2.0,3.0,4.0,5.0;\n//  m = MatrixXd::Map(b.data(), m.rows(), m.cols());\n//  cout << m << endl;\n  cout << \"Done.\" << endl;\n}", "meta": {"hexsha": "e1697a6567e03ce5c55b7078411b557d748530b4", "size": 20707, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Project/main.cpp", "max_stars_repo_name": "anshuman1811/cs687-reinforcementlearning", "max_stars_repo_head_hexsha": "cf30cc0ab2b0e515cd4b643fc55c60cc5f38a481", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Project/main.cpp", "max_issues_repo_name": "anshuman1811/cs687-reinforcementlearning", "max_issues_repo_head_hexsha": "cf30cc0ab2b0e515cd4b643fc55c60cc5f38a481", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Project/main.cpp", "max_forks_repo_name": "anshuman1811/cs687-reinforcementlearning", "max_forks_repo_head_hexsha": "cf30cc0ab2b0e515cd4b643fc55c60cc5f38a481", "max_forks_repo_licenses": ["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.9249084249, "max_line_length": 1595, "alphanum_fraction": 0.6289177573, "num_tokens": 6113, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217431943271999, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.46754395510422375}}
{"text": "/*\n * Copyright (c) 2012 Jonathan Perry\n * This code is released under the MIT license (see LICENSE file).\n */\n#include \"codes/strider/LayerSuperposition.h\"\n\n#include <assert.h>\n#include <boost/numeric/ublas/operation.hpp>\n\nusing namespace boost::numeric::ublas;\n\nLayerSuperposition::LayerSuperposition(unsigned int layerLength,\n\t\t\t\t\t\t\t\t std::complex<double>* matrixG,\n\t\t\t\t\t\t\t\t int rowsG,\n\t\t\t\t\t\t\t\t int colsG)\n  :\tm_G(rowsG, colsG),\n   \tm_layerSymbols(colsG, layerLength),\n   \tm_nextSymbol(0),\n   \tm_currentPass(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\nvoid LayerSuperposition::setLayer(\n\t\tunsigned int layerInd,\n\t\tconst std::vector<ComplexSymbol> & layer)\n{\n\tassert(layerInd < m_layerSymbols.size1());\n\tassert(layer.size() == m_layerSymbols.size2());\n\n\tfor(unsigned int i = 0; i < m_layerSymbols.size2(); i++) {\n\t\tm_layerSymbols(layerInd,i) = layer[i];\n\t}\n}\n\nvoid LayerSuperposition::reset() {\n\tm_nextSymbol = 0;\n\tm_currentPass = 0;\n}\n\nComplexSymbol LayerSuperposition::next() {\n\tComplexSymbol res = inner_prod(row(m_G, m_currentPass),\n\t\t\t\t\t\t\t\t   column(m_layerSymbols, m_nextSymbol));\n\n\tm_nextSymbol++;\n\tif(m_nextSymbol == m_layerSymbols.size2()) {\n\t\tm_nextSymbol = 0;\n\t\tm_currentPass++;\n\t}\n\n\treturn res;\n}\n\n", "meta": {"hexsha": "b0ec0a5e0e2cfe42466ee41042dc87dd22ffa192", "size": 1297, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/codes/strider/LayerSuperposition.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/LayerSuperposition.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/LayerSuperposition.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": 22.3620689655, "max_line_length": 66, "alphanum_fraction": 0.6792598304, "num_tokens": 354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217431943271999, "lm_q2_score": 0.647798211152541, "lm_q1q2_score": 0.4675439501966809}}
{"text": "#include <iostream>\n#include <algorithm>\n#include <cmath>\n#include <vector>\n#include <map>\n#include <set>\n#include <tuple>\n#include <stdbool.h>\n#include <bitset>\n#include <string>\n#include <boost/multiprecision/cpp_int.hpp>\n\nnamespace mp = boost::multiprecision;\nusing namespace std;\n\n\nint main(void) {\n    int n;\n    cin >> n;\n\n    int i;\n    int highest = 0;\n    int miss = 0;\n    for(i = 0 ; i < n ; ++i) {\n        int h;\n        cin >> h;\n        if (highest <= h) {\n            highest = h;\n        } else {\n            miss++;\n        }\n    }\n    cout << (n - miss) << endl;\n    return 0;\n}", "meta": {"hexsha": "6c98b062c88a30db7f6476a2769aeb4c69c0d663", "size": 596, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "abc124/b/main.cpp", "max_stars_repo_name": "kamiyaowl/atcoder", "max_stars_repo_head_hexsha": "30521be1684e72e75c7ba21312c5f96ae81bf25a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "abc124/b/main.cpp", "max_issues_repo_name": "kamiyaowl/atcoder", "max_issues_repo_head_hexsha": "30521be1684e72e75c7ba21312c5f96ae81bf25a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-20T11:51:59.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-20T11:51:59.000Z", "max_forks_repo_path": "abc124/b/main.cpp", "max_forks_repo_name": "kamiyaowl/atcoder", "max_forks_repo_head_hexsha": "30521be1684e72e75c7ba21312c5f96ae81bf25a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.0285714286, "max_line_length": 43, "alphanum_fraction": 0.5302013423, "num_tokens": 160, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410572017153, "lm_q2_score": 0.7025300511670689, "lm_q1q2_score": 0.4674709232063191}}
{"text": "//\n// Created by haohanwang on 2/8/16.\n//\n\n#ifndef ALGORITHMS_MATH_HPP\n#define ALGORITHMS_MATH_HPP\n\n#include <Eigen/Dense>\n#include <vector>\n#include <unordered_map>\n\nusing namespace Eigen;\nusing namespace std;\n\nstruct treeNode{\n    vector<long> trait;\n    vector<treeNode*> children;\n    float s;\n    float weight;\n};\n\nstruct minXY{\n    long x;\n    long y;\n};\n\nclass Tree{\nprivate:\n    treeNode* root;\npublic:\n    treeNode* getRoot();\n    treeNode* buildParentFromChildren(vector<treeNode*>);\n    treeNode* buildLeafNode(long);\n\n    void setRoot(treeNode*);\n\n    void setWeight();\n\n    Tree();\n    ~Tree();\n};\n\nclass Math {\nprivate:\n    Math() {};\n    Math(Math const &);  // don't implement\n    void operator=(Math const &); // don't implement\n\n    minXY searchMin(MatrixXf);\n    MatrixXf appendColRow(MatrixXf, minXY);\n    void updateMap(unordered_map<long, treeNode*>*, minXY);\n\n\npublic:\n    static Math &getInstance() {\n        static Math instance;\n        return instance;\n    }\n    // statistics\n    float variance(VectorXf);\n    float std(VectorXf);\n    float covariance(VectorXf, VectorXf);\n    float correlation(VectorXf, VectorXf);\n    // matrix\n    void removeCol(MatrixXf*, long);\n    void removeRow(MatrixXf*, long);\n    void removeColRow(MatrixXf*, minXY);\n\n    MatrixXf pseudoInverse(MatrixXf& matrix);\n\n    VectorXf L2Thresholding(VectorXf in);\n\n    Tree* hierarchicalClustering(MatrixXf);\n};\n\n\n#endif //ALGORITHMS_MATH_HPP\n", "meta": {"hexsha": "94372a65db806b8bf08e02c4bf2107c6b6e6d4ed", "size": 1442, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Math/Math.hpp", "max_stars_repo_name": "blengerich/jenkins_test", "max_stars_repo_head_hexsha": "512aec681577063e3d68f699d19f53374e59585a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2016-10-20T00:36:31.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-06T16:40:52.000Z", "max_issues_repo_path": "src/Math/Math.hpp", "max_issues_repo_name": "blengerich/jenkins_test", "max_issues_repo_head_hexsha": "512aec681577063e3d68f699d19f53374e59585a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 44.0, "max_issues_repo_issues_event_min_datetime": "2016-11-11T22:41:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-04T21:55:57.000Z", "max_forks_repo_path": "src/Math/Math.hpp", "max_forks_repo_name": "blengerich/jenkins_test", "max_forks_repo_head_hexsha": "512aec681577063e3d68f699d19f53374e59585a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-02-01T09:19:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-28T14:40:43.000Z", "avg_line_length": 18.4871794872, "max_line_length": 59, "alphanum_fraction": 0.6699029126, "num_tokens": 363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.4674709221720425}}
{"text": "#pragma once\n// value.hpp: definition of a (sign, scale, fraction) representation of an approximation to a real value\n//\n// Copyright (C) 2017-2018 Stillwater Supercomputing, Inc.\n//\n// This file is part of the universal numbers project, which is released under an MIT Open Source license.\n#include <cassert>\n#include <limits>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n\n#include \"bit_functions.hpp\"\n#include \"trace_constants.hpp\"\n\nusing boost::multiprecision::cpp_dec_float_50;\nusing boost::multiprecision::cpp_dec_float_100;\n\nnamespace sw {\n\tnamespace unum {\n\n\t\t// Forward definitions\n\t\ttemplate<size_t fbits> class value;\n\t\ttemplate<size_t fbits> value<fbits> abs(const value<fbits>& v);\n\n\t\t// template class representing a value in scientific notation, using a template size for the number of fraction bits\n\t\ttemplate<size_t fbits>\n\t\tclass value {\n\t\tpublic:\n\t\t\tstatic constexpr size_t fhbits = fbits + 1;    // number of fraction bits including the hidden bit\n\t\t\tvalue() : _sign(false), _scale(0), _nrOfBits(fbits), _zero(true), _inf(false), _nan(false) {}\n\t\t\tvalue(bool sign, int scale, const bitblock<fbits>& fraction_without_hidden_bit, bool zero = true, bool inf = false) : _sign(sign), _scale(scale), _nrOfBits(fbits), _fraction(fraction_without_hidden_bit), _inf(inf), _zero(zero), _nan(false) {}\n\t\t\tvalue(signed char initial_value) {\n\t\t\t\t*this = initial_value;\n\t\t\t}\n\t\t\tvalue(short initial_value) {\n\t\t\t\t*this = initial_value;\n\t\t\t}\n\t\t\tvalue(int initial_value) {\n\t\t\t\t*this = initial_value;\n\t\t\t}\n\t\t\tvalue(long long initial_value) {\n\t\t\t\t*this = initial_value;\n\t\t\t}\n\t\t\tvalue(unsigned long long initial_value) {\n\t\t\t\t*this = initial_value;\n\t\t\t}\n\t\t\tvalue(float initial_value) {\n\t\t\t\t*this = initial_value;\n\t\t\t}\n\t\t\tvalue(double initial_value) {\n\t\t\t\t*this = initial_value;\n\t\t\t}\n\t\t\tvalue(long double initial_value) {\n\t\t\t\t*this = initial_value;\n\t\t\t}\n\t\t\tvalue(cpp_dec_float_50 initial_value) {\n\t\t\t\t*this = initial_value;\n\t\t\t}\n\t\t\tvalue(cpp_dec_float_100 initial_value) {\n\t\t\t\t*this = initial_value;\n\t\t\t}\n\t\t\tvalue(const value& rhs) {\n\t\t\t\t*this = rhs;\n\t\t\t}\n\t\t\tvalue& operator=(const value& rhs) {\n\t\t\t\t_sign\t  = rhs._sign;\n\t\t\t\t_scale\t  = rhs._scale;\n\t\t\t\t_fraction = rhs._fraction;\n\t\t\t\t_nrOfBits = rhs._nrOfBits;\n\t\t\t\t_inf      = rhs._inf;\n\t\t\t\t_zero     = rhs._zero;\n\t\t\t\t_nan      = rhs._nan;\n\t\t\t\treturn *this;\n\t\t\t}\n\t\t\tvalue<fbits>& operator=(signed char rhs) {\n\t\t\t\t*this = (long long)(rhs);\n\t\t\t\treturn *this;\n\t\t\t}\n\t\t\tvalue<fbits>& operator=(short rhs) {\n\t\t\t\t*this = (long long)(rhs);\n\t\t\t\treturn *this;\n\t\t\t}\n\t\t\tvalue<fbits>& operator=(int rhs) {\n\t\t\t\t*this = (long long)(rhs);\n\t\t\t\treturn *this;\n\t\t\t}\n\t\t\tvalue<fbits>& operator=(long long rhs) {\n\t\t\t\tif (_trace_conversion) std::cout << \"---------------------- CONVERT -------------------\" << std::endl;\n\t\t\t\tif (rhs == 0) {\n\t\t\t\t\tsetToZero();\n\t\t\t\t\treturn *this;\n\t\t\t\t}\n\t\t\t\treset();\n\t\t\t\t_sign = (0x8000000000000000 & rhs);  // 1 is negative, 0 is positive\n\t\t\t\tif (_sign) {\n\t\t\t\t\t// process negative number: process 2's complement of the input\n\t\t\t\t\t_scale = findMostSignificantBit(-rhs) - 1;\n\t\t\t\t\tuint64_t _fraction_without_hidden_bit = (-rhs << (64 - _scale));\n\t\t\t\t\t_fraction = copy_integer_fraction<fbits>(_fraction_without_hidden_bit);\n\t\t\t\t\t//take_2s_complement();\n\t\t\t\t\t_nrOfBits = fbits;\n\t\t\t\t\tif (_trace_conversion) std::cout << \"int64 \" << rhs << \" sign \" << _sign << \" scale \" << _scale << \" fraction b\" << _fraction << std::dec << std::endl;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t// process positive number\n\t\t\t\t\tif (rhs != 0) {\n\t\t\t\t\t\t_scale = findMostSignificantBit(rhs) - 1;\n\t\t\t\t\t\tuint64_t _fraction_without_hidden_bit = (rhs << (64 - _scale));\n\t\t\t\t\t\t_fraction = copy_integer_fraction<fbits>(_fraction_without_hidden_bit);\n\t\t\t\t\t\t_nrOfBits = fbits;\n\t\t\t\t\t\tif (_trace_conversion) std::cout << \"int64 \" << rhs << \" sign \" << _sign << \" scale \" << _scale << \" fraction b\" << _fraction << std::dec << std::endl;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn *this;\n\t\t\t}\n\t\t\tvalue<fbits>& operator=(unsigned long long rhs) {\n\t\t\t\tif (_trace_conversion) std::cout << \"---------------------- CONVERT -------------------\" << std::endl;\n\t\t\t\tif (rhs == 0) {\n\t\t\t\t\tsetToZero();\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\treset();\n\t\t\t\t\t_scale = findMostSignificantBit(rhs) - 1;\n\t\t\t\t\tuint64_t _fraction_without_hidden_bit = (rhs << (64 - _scale));\n\t\t\t\t\t_fraction = copy_integer_fraction<fbits>(_fraction_without_hidden_bit);\n\t\t\t\t\t_nrOfBits = fbits;\n\t\t\t\t}\n\t\t\t\tif (_trace_conversion) std::cout << \"uint64 \" << rhs << \" sign \" << _sign << \" scale \" << _scale << \" fraction b\" << _fraction << std::dec << std::endl;\n\t\t\t\treturn *this;\n\t\t\t}\n\t\t\tvalue<fbits>& operator=(float rhs) {\n\t\t\t\treset();\n\t\t\t\tif (_trace_conversion) std::cout << \"---------------------- CONVERT -------------------\" << std::endl;\n\n\t\t\t\tswitch (std::fpclassify(rhs)) {\n\t\t\t\tcase FP_ZERO:\n\t\t\t\t\t_nrOfBits = fbits;\n\t\t\t\t\t_zero = true;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FP_INFINITE:\n\t\t\t\t\t_inf  = true;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FP_NAN:\n\t\t\t\t\t_nan = true;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FP_SUBNORMAL:\n\t\t\t\t\tstd::cerr << \"TODO: subnormal number: returning 0\" << std::endl;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FP_NORMAL:\n\t\t\t\t{\n\t\t\t\t\tfloat _fr;\n\t\t\t\t\tunsigned int _23b_fraction_without_hidden_bit;\n\t\t\t\t\tint _exponent;\n\t\t\t\t\textract_fp_components(rhs, _sign, _exponent, _fr, _23b_fraction_without_hidden_bit);\n\t\t\t\t\t_scale = _exponent - 1;\n\t\t\t\t\t_fraction = extract_23b_fraction<fbits>(_23b_fraction_without_hidden_bit);\n\t\t\t\t\t_nrOfBits = fbits;\n\t\t\t\t\tif (_trace_conversion) std::cout << \"float \" << rhs << \" sign \" << _sign << \" scale \" << _scale << \" 23b fraction 0x\" << std::hex << _23b_fraction_without_hidden_bit << \" _fraction b\" << _fraction << std::dec << std::endl;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\treturn *this;\n\t\t\t}\n\t\t\tvalue<fbits>& operator=(double rhs) {\n\t\t\t\treset();\n\t\t\t\tif (_trace_conversion) std::cout << \"---------------------- CONVERT -------------------\" << std::endl;\n\n\t\t\t\tswitch (std::fpclassify(rhs)) {\n\t\t\t\tcase FP_ZERO:\n\t\t\t\t\t_nrOfBits = fbits;\n\t\t\t\t\t_zero = true;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FP_INFINITE:\n\t\t\t\t\t_inf = true;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FP_NAN:\n\t\t\t\t\t_nan = true;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FP_SUBNORMAL:\n\t\t\t\t\tstd::cerr << \"TODO: subnormal number: returning 0\" << std::endl;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FP_NORMAL:\n\t\t\t\t{\n\t\t\t\t\tdouble _fr;\n\t\t\t\t\tunsigned long long _52b_fraction_without_hidden_bit;\n\t\t\t\t\tint _exponent;\n\t\t\t\t\textract_fp_components(rhs, _sign, _exponent, _fr, _52b_fraction_without_hidden_bit);\n\t\t\t\t\t_scale = _exponent - 1;\n\t\t\t\t\t_fraction = extract_52b_fraction<fbits>(_52b_fraction_without_hidden_bit);\n\t\t\t\t\t_nrOfBits = fbits;\n\t\t\t\t\tif (_trace_conversion) std::cout << \"double \" << rhs << \" sign \" << _sign << \" scale \" << _scale << \" 52b fraction 0x\" << std::hex << _52b_fraction_without_hidden_bit << \" _fraction b\" << _fraction << std::dec << std::endl;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\treturn *this;\n\t\t\t}\n\t\t\tvalue<fbits>& operator=(long double rhs) {\n\t\t\t\treset();\n\t\t\t\tif (_trace_conversion) std::cout << \"---------------------- CONVERT -------------------\" << std::endl;\n\n\t\t\t\tswitch (std::fpclassify(rhs)) {\n\t\t\t\tcase FP_ZERO:\n\t\t\t\t\t_nrOfBits = fbits;\n\t\t\t\t\t_zero = true;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FP_INFINITE:\n\t\t\t\t\t_inf = true;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FP_NAN:\n\t\t\t\t\t_nan = true;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FP_SUBNORMAL:\n\t\t\t\t\tstd::cerr << \"TODO: subnormal number: returning 0\" << std::endl;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FP_NORMAL:\n\t\t\t\t{\n\t\t\t\t\tlong double _fr;\n\t\t\t\t\tunsigned long long _63b_fraction_without_hidden_bit;\n\t\t\t\t\tint _exponent;\n\t\t\t\t\textract_fp_components(rhs, _sign, _exponent, _fr, _63b_fraction_without_hidden_bit);\n\t\t\t\t\t_scale = _exponent - 1;\n\t\t\t\t\t// how to interpret the fraction bits: TODO: this should be a static compile-time code block\n\t\t\t\t\tif (sizeof(long double) == 8) {\n\t\t\t\t\t\t// we are just a double and thus only have 52bits of fraction\n\t\t\t\t\t\t_fraction = extract_52b_fraction<fbits>(_63b_fraction_without_hidden_bit);\n\t\t\t\t\t\tif (_trace_conversion) std::cout << \"long double \" << rhs << \" sign \" << _sign << \" scale \" << _scale << \" 52b fraction 0x\" << std::hex << _63b_fraction_without_hidden_bit << \" _fraction b\" << _fraction << std::dec << std::endl;\n\n\t\t\t\t\t}\n\t\t\t\t\telse if (sizeof(long double) == 16) {\n\t\t\t\t\t\t// how to differentiate between 80bit and 128bit formats?\n\t\t\t\t\t\t_fraction = extract_63b_fraction<fbits>(_63b_fraction_without_hidden_bit);\n\t\t\t\t\t\tif (_trace_conversion) std::cout << \"long double \" << rhs << \" sign \" << _sign << \" scale \" << _scale << \" 63b fraction 0x\" << std::hex << _63b_fraction_without_hidden_bit << \" _fraction b\" << _fraction << std::dec << std::endl;\n\n\t\t\t\t\t}\n\t\t\t\t\t_nrOfBits = fbits;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\treturn *this;\n\t\t\t}\n\n\t\t\t// operators\n\t\t\tvalue<fbits> operator-() const {\n\t\t\t\treturn value<fbits>(!_sign, _scale, _fraction, _zero, _inf);\n\t\t\t}\n\n\t\t\t// modifiers\n\t\t\tvoid reset() {\n\t\t\t\t_sign  = false;\n\t\t\t\t_scale = 0;\n\t\t\t\t_nrOfBits = 0;\n\t\t\t\t_inf = false;\n\t\t\t\t_zero = false;\n\t\t\t\t_nan = false;\n\t\t\t\t_fraction.reset();\n\t\t\t}\n\t\t\tvoid set(bool sign, int scale, bitblock<fbits> fraction_without_hidden_bit, bool zero, bool inf, bool nan = false) {\n\t\t\t\t_sign     = sign;\n\t\t\t\t_scale    = scale;\n\t\t\t\t_fraction = fraction_without_hidden_bit;\n\t\t\t\t_zero     = zero;\n\t\t\t\t_inf      = inf;\n\t\t\t\t_nan      = nan;\n\t\t\t}\n\t\t\tvoid setToZero() {\n\t\t\t\t_zero     = true;\n\t\t\t\t_sign     = false;\n\t\t\t\t_inf      = false;\n\t\t\t\t_nan      = false;\n\t\t\t\t_scale    = 0;\n\t\t\t\t_nrOfBits = fbits;\n\t\t\t\t_fraction.reset();\n\t\t\t}\n\t\t\tvoid setToInfinite() {\n\t\t\t\t_inf      = true;\n\t\t\t\t_sign     = false;\n\t\t\t\t_zero     = false;\n\t\t\t\t_nan      = false;\n\t\t\t\t_scale    = 0;\n\t\t\t\t_nrOfBits = fbits;\n\t\t\t\t_fraction.reset();\n\t\t\t}\n\t\t\tvoid setToNan() {\n\t\t\t\t_nan      = true;\n\t\t\t\t_sign     = false;\n\t\t\t\t_zero     = false;\n\t\t\t\t_inf      = false;\n\t\t\t\t_scale    = 0;\n\t\t\t\t_nrOfBits = fbits;\n\t\t\t\t_fraction.reset();\n\t\t\t}\n\t\t\tinline void setExponent(int e) { _scale = e; }\n\t\t\tinline bool isNegative() const { return _sign; }\n\t\t\tinline bool isZero() const { return _zero; }\n\t\t\tinline bool isInfinite() const { return _inf; }\n\t\t\tinline bool isNaN() const { return _nan; }\n\t\t\tinline bool sign() const { return _sign; }\n\t\t\tinline int scale() const { return _scale; }\n\t\t\tbitblock<fbits> fraction() const { return _fraction; }\n\t\t\t/// Normalized shift (e.g., for addition).\n\t\t\ttemplate <size_t Size>\n\t\t\tbitblock<Size> nshift(long shift) const {\n\t\t\t\tbitblock<Size> number;\n\n\t\t\t\t// Check range\n\t\t\t\tif (long(fbits) + shift >= long(Size))\n\t\t\t\t\tthrow shift_too_large{};\n\n\t\t\t\tconst long hpos = fbits + shift;       // position of hidden bit\n\n\t\t\t\tif (hpos <= 0) {   // If hidden bit is LSB or beyond just set uncertainty bit and call it a day\n\t\t\t\t\tnumber[0] = true;\n\t\t\t\t\treturn number;\n\t\t\t\t}\n\t\t\t\tnumber[hpos] = true;                   // hidden bit now safely set\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t   // Copy fraction bits into certain part\n\t\t\t\tfor (long npos = hpos - 1, fpos = long(fbits) - 1; npos > 0 && fpos >= 0; --npos, --fpos)\n\t\t\t\t\tnumber[npos] = _fraction[fpos];\n\n\t\t\t\t// Set uncertainty bit\n\t\t\t\tbool uncertainty = false;\n\t\t\t\tfor (long fpos = std::min(long(fbits) - 1, -shift); fpos >= 0 && !uncertainty; --fpos)\n\t\t\t\t\tuncertainty |= _fraction[fpos];\n\t\t\t\tnumber[0] = uncertainty;\n\t\t\t\treturn number;\n\t\t\t}\n\t\t\t// get a fixed point number by making the hidden bit explicit: useful for multiply units\n\t\t\tbitblock<fhbits> get_fixed_point() const {\n\t\t\t\tbitblock<fbits + 1> fixed_point_number;\n\t\t\t\tfixed_point_number.set(fbits, true); // make hidden bit explicit\n\t\t\t\tfor (unsigned int i = 0; i < fbits; i++) {\n\t\t\t\t\tfixed_point_number[i] = _fraction[i];\n\t\t\t\t}\n\t\t\t\treturn fixed_point_number;\n\t\t\t}\n\t\t\t// get the fraction value including the implicit hidden bit (this is at an exponent level 1 smaller)\n\t\t\ttemplate<typename Ty = double>\n\t\t\tTy get_implicit_fraction_value() const {\n\t\t\t\tif (_zero) return (long double)0.0;\n\t\t\t\tTy v = 1.0;\n\t\t\t\tTy scale = 0.5;\n\t\t\t\tfor (int i = int(fbits) - 1; i >= 0; i--) {\n\t\t\t\t\tif (_fraction.test(i)) v += scale;\n\t\t\t\t\tscale *= 0.5;\n\t\t\t\t\tif (scale == 0.0) break;\n\t\t\t\t}\n\t\t\t\treturn v;\n\t\t\t}\n\t\t\tint sign_value() const { return (_sign ? -1 : 1); }\n\t\t\tdouble scale_value() const {\n\t\t\t\tif (_zero) return (long double)(0.0);\n\t\t\t\treturn std::pow((long double)2.0, (long double)_scale);\n\t\t\t}\n\t\t\ttemplate<typename Ty = double>\n\t\t\tTy fraction_value() const {\n\t\t\t\tif (_zero) return (long double)0.0;\n\t\t\t\tTy v = 1.0;\n\t\t\t\tTy scale = 0.5;\n\t\t\t\tfor (int i = int(fbits) - 1; i >= 0; i--) {\n\t\t\t\t\tif (_fraction.test(i)) v += scale;\n\t\t\t\t\tscale *= 0.5;\n\t\t\t\t\tif (scale == 0.0) break;\n\t\t\t\t}\n\t\t\t\treturn v;\n\t\t\t}\n\t\t\tcpp_dec_float_50 to_cpp_dec_float_50() const {\n\t\t\t\treturn sign_value() * scale_value() * fraction_value<cpp_dec_float_50>();\n\t\t\t}\n\t\t\tcpp_dec_float_100 to_cpp_dec_float_100() const {\n\t\t\t\treturn sign_value() * scale_value() * fraction_value<cpp_dec_float_100>();\n\t\t\t}\n\t\t\tlong double to_long_double() const {\n\t\t\t\treturn sign_value() * scale_value() * fraction_value<long double>();\n\t\t\t}\n\t\t\tdouble to_double() const {\n\t\t\t\treturn sign_value() * scale_value() * fraction_value<double>();\n\t\t\t}\n\t\t\tfloat to_float() const {\n\t\t\t\treturn float(sign_value() * scale_value() * fraction_value<float>());\n\t\t\t}\n\t\t\t// Maybe remove explicit\n\t\t\texplicit operator cpp_dec_float_50() const { return to_cpp_dec_float_50(); }\n\t\t\texplicit operator cpp_dec_float_100() const { return to_cpp_dec_float_100(); }\n\t\t\texplicit operator long double() const { return to_long_double(); }\n\t\t\texplicit operator double() const { return to_double(); }\n\t\t\texplicit operator float() const { return to_float(); }\n\n\t\t\ttemplate<size_t tgt_size>\n\t\t\tvalue<tgt_size> round_to() {\n\t\t\t\tbitblock<tgt_size> rounded_fraction;\n\t\t\t\tif (tgt_size == 0) {\n\t\t\t\t\tbool round_up = false;\n\t\t\t\t\tif (fbits >= 2) {\n\t\t\t\t\t\tbool blast = _fraction[int(fbits) - 1];\n\t\t\t\t\t\tbool sb = anyAfter(_fraction, int(fbits) - 2);\n\t\t\t\t\t\tif (blast && sb) round_up = true;\n\t\t\t\t\t}\n\t\t\t\t\telse if (fbits == 1) {\n\t\t\t\t\t\tround_up = _fraction[0];\n\t\t\t\t\t}\n\t\t\t\t\treturn value<tgt_size>(_sign, (round_up ? _scale + 1 : _scale), rounded_fraction, _zero, _inf);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tif (!_zero || !_inf) {\n\t\t\t\t\t\tif (tgt_size < fbits) {\n\t\t\t\t\t\t\tint rb = int(tgt_size) - 1;\n\t\t\t\t\t\t\tint lb = int(fbits) - int(tgt_size) - 1;\n\t\t\t\t\t\t\tfor (int i = int(fbits) - 1; i > lb; i--, rb--) {\n\t\t\t\t\t\t\t\trounded_fraction[rb] = _fraction[i];\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbool blast = _fraction[lb];\n\t\t\t\t\t\t\tbool sb = false;\n\t\t\t\t\t\t\tif (lb > 0) sb = anyAfter(_fraction, lb-1);\n\t\t\t\t\t\t\tif (blast || sb) rounded_fraction[0] = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tint rb = int(tgt_size) - 1;\n\t\t\t\t\t\t\tfor (int i = int(fbits) - 1; i >= 0; i--, rb--) {\n\t\t\t\t\t\t\t\trounded_fraction[rb] = _fraction[i];\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn value<tgt_size>(_sign, _scale, rounded_fraction, _zero, _inf);\n\t\t\t}\n\t\tprivate:\n\t\t\tbool\t\t\t\t_sign;\n\t\t\tint\t\t\t\t\t_scale;\n\t\t\tbitblock<fbits>\t    _fraction;\n\t\t\tint\t\t\t\t\t_nrOfBits;  // in case the fraction is smaller than the full fbits\n\t\t\tbool                _inf;\n\t\t\tbool                _zero;\n\t\t\tbool                _nan;\n\n\t\t\t// template parameters need names different from class template parameters (for gcc and clang)\n\t\t\ttemplate<size_t nfbits>\n\t\t\tfriend std::ostream& operator<< (std::ostream& ostr, const value<nfbits>& r);\n\t\t\ttemplate<size_t nfbits>\n\t\t\tfriend std::istream& operator>> (std::istream& istr, value<nfbits>& r);\n\n\t\t\ttemplate<size_t nfbits>\n\t\t\tfriend bool operator==(const value<nfbits>& lhs, const value<nfbits>& rhs);\n\t\t\ttemplate<size_t nfbits>\n\t\t\tfriend bool operator!=(const value<nfbits>& lhs, const value<nfbits>& rhs);\n\t\t\ttemplate<size_t nfbits>\n\t\t\tfriend bool operator< (const value<nfbits>& lhs, const value<nfbits>& rhs);\n\t\t\ttemplate<size_t nfbits>\n\t\t\tfriend bool operator> (const value<nfbits>& lhs, const value<nfbits>& rhs);\n\t\t\ttemplate<size_t nfbits>\n\t\t\tfriend bool operator<=(const value<nfbits>& lhs, const value<nfbits>& rhs);\n\t\t\ttemplate<size_t nfbits>\n\t\t\tfriend bool operator>=(const value<nfbits>& lhs, const value<nfbits>& rhs);\n\t\t};\n\n\t\t////////////////////// VALUE operators\n\t\ttemplate<size_t nfbits>\n\t\tinline std::ostream& operator<<(std::ostream& ostr, const value<nfbits>& v) {\n\t\t\tif (v._inf) {\n\t\t\t\tostr << FP_INFINITE;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tostr << (long double)v;\n\t\t\t}\n\t\t\treturn ostr;\n\t\t}\n\n\t\ttemplate<size_t nfbits>\n\t\tinline std::istream& operator>> (std::istream& istr, const value<nfbits>& v) {\n\t\t\tistr >> v._fraction;\n\t\t\treturn istr;\n\t\t}\n\n\t\ttemplate<size_t nfbits>\n\t\tinline bool operator==(const value<nfbits>& lhs, const value<nfbits>& rhs) { return lhs._sign == rhs._sign && lhs._scale == rhs._scale && lhs._fraction == rhs._fraction && lhs._nrOfBits == rhs._nrOfBits && lhs._zero == rhs._zero && lhs._inf == rhs._inf; }\n\t\ttemplate<size_t nfbits>\n\t\tinline bool operator!=(const value<nfbits>& lhs, const value<nfbits>& rhs) { return !operator==(lhs, rhs); }\n\t\ttemplate<size_t nfbits>\n\t\tinline bool operator< (const value<nfbits>& lhs, const value<nfbits>& rhs) { return lhs.to_long_double() < rhs.to_long_double(); }\n\t\ttemplate<size_t nfbits>\n\t\tinline bool operator> (const value<nfbits>& lhs, const value<nfbits>& rhs) { return  operator< (rhs, lhs); }\n\t\ttemplate<size_t nfbits>\n\t\tinline bool operator<=(const value<nfbits>& lhs, const value<nfbits>& rhs) { return !operator> (lhs, rhs); }\n\t\ttemplate<size_t nfbits>\n\t\tinline bool operator>=(const value<nfbits>& lhs, const value<nfbits>& rhs) { return !operator< (lhs, rhs); }\n\n\t\ttemplate<size_t fbits>\n\t\tinline std::string components(const value<fbits>& v) {\n\t\t\tstd::stringstream s;\n\t\t\tif (v.isZero()) {\n\t\t\t\ts << \" zero b\" << std::setw(fbits) << v.fraction();\n\t\t\t\treturn s.str();\n\t\t\t}\n\t\t\telse if (v.isInfinite()) {\n\t\t\t\ts << \" infinite b\" << std::setw(fbits) << v.fraction();\n\t\t\t\treturn s.str();\n\t\t\t}\n\t\t\ts << \"(\" << (v.sign() ? \"-\" : \"+\") << \",\" << v.scale() << \",\" << v.fraction() << \")\";\n\t\t\treturn s.str();\n\t\t}\n\n\t\t/// Magnitude of a scientific notation value (equivalent to turning the sign bit off).\n\t\ttemplate<size_t nfbits>\n\t\tvalue<nfbits> abs(const value<nfbits>& v) {\n\t\t\treturn value<nfbits>(false, v.scale(), v.fraction(), v.isZero());\n\t\t}\n\n\t\t// add module\n\t\ttemplate<size_t fbits, size_t abits>\n\t\tvoid module_add(const value<fbits>& lhs, const value<fbits>& rhs, value<abits + 1>& result) {\n\t\t\t// with sign/magnitude adders it is customary to organize the computation\n\t\t\t// along the four quadrants of sign combinations\n\t\t\t//  + + = +\n\t\t\t//  + - =   lhs > rhs ? + : -\n\t\t\t//  - + =   lhs > rhs ? - : +\n\t\t\t//  - - =\n\t\t\t// to simplify the result processing assign the biggest\n\t\t\t// absolute value to R1, then the sign of the result will be sign of the value in R1.\n\n\t\t\tif (lhs.isInfinite() || rhs.isInfinite()) {\n\t\t\t\tresult.setToInfinite();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tint lhs_scale = lhs.scale(), rhs_scale = rhs.scale(), scale_of_result = std::max(lhs_scale, rhs_scale);\n\n\t\t\t// align the fractions\n\t\t\tbitblock<abits> r1 = lhs.template nshift<abits>(lhs_scale - scale_of_result + 3);\n\t\t\tbitblock<abits> r2 = rhs.template nshift<abits>(rhs_scale - scale_of_result + 3);\n\t\t\tbool r1_sign = lhs.sign(), r2_sign = rhs.sign();\n\t\t\tbool signs_are_different = r1_sign != r2_sign;\n\n\t\t\tif (signs_are_different && sw::unum::abs(lhs) < sw::unum::abs(rhs)) {\n\t\t\t\tstd::swap(r1, r2);\n\t\t\t\tstd::swap(r1_sign, r2_sign);\n\t\t\t}\n\n\t\t\tif (signs_are_different) r2 = twos_complement(r2);\n\n\t\t\tif (_trace_add) {\n\t\t\t\tstd::cout << (r1_sign ? \"sign -1\" : \"sign  1\") << \" scale \" << std::setw(3) << scale_of_result << \" r1       \" << r1 << std::endl;\n\t\t\t\tstd::cout << (r2_sign ? \"sign -1\" : \"sign  1\") << \" scale \" << std::setw(3) << scale_of_result << \" r2       \" << r2 << std::endl;\n\t\t\t}\n\n\t\t\tbitblock<abits + 1> sum;\n\t\t\tconst bool carry = add_unsigned(r1, r2, sum);\n\n\t\t\tif (_trace_add) std::cout << (r1_sign ? \"sign -1\" : \"sign  1\") << \" carry \" << std::setw(3) << (carry ? 1 : 0) << \" sum     \" << sum << std::endl;\n\n\t\t\tlong shift = 0;\n\t\t\tif (carry) {\n\t\t\t\tif (r1_sign == r2_sign) {  // the carry && signs== implies that we have a number bigger than r1\n\t\t\t\t\tshift = -1;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t// the carry && signs!= implies r2 is complement, result < r1, must find hidden bit (in the complement)\n\t\t\t\t\tfor (int i = abits - 1; i >= 0 && !sum[i]; i--) {\n\t\t\t\t\t\tshift++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tassert(shift >= -1);\n\n\t\t\tif (shift >= long(abits)) {            // we have actual 0\n\t\t\t\tsum.reset();\n\t\t\t\tresult.set(false, 0, sum, true, false, false);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tscale_of_result -= shift;\n\t\t\tconst int hpos = abits - 1 - shift;         // position of the hidden bit\n\t\t\tsum <<= abits - hpos + 1;\n\t\t\tif (_trace_add) std::cout << (r1_sign ? \"sign -1\" : \"sign  1\") << \" scale \" << std::setw(3) << scale_of_result << \" sum     \" << sum << std::endl;\n\t\t\tresult.set(r1_sign, scale_of_result, sum, false, false, false);\n\t\t}\n\n\t\t// subtract module: use ADDER\n\t\ttemplate<size_t fbits, size_t abits>\n\t\tvoid module_subtract(const value<fbits>& lhs, const value<fbits>& rhs, value<abits + 1>& result) {\n\t\t\tif (lhs.isInfinite() || rhs.isInfinite()) {\n\t\t\t\tresult.setToInfinite();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tint lhs_scale = lhs.scale(), rhs_scale = rhs.scale(), scale_of_result = std::max(lhs_scale, rhs_scale);\n\n\t\t\t// align the fractions\n\t\t\tbitblock<abits> r1 = lhs.template nshift<abits>(lhs_scale - scale_of_result + 3);\n\t\t\tbitblock<abits> r2 = rhs.template nshift<abits>(rhs_scale - scale_of_result + 3);\n\t\t\tbool r1_sign = lhs.sign(), r2_sign = !rhs.sign();\n\t\t\tbool signs_are_different = r1_sign != r2_sign;\n\n\t\t\tif (sw::unum::abs(lhs) < sw::unum::abs(rhs)) {\n\t\t\t\tstd::swap(r1, r2);\n\t\t\t\tstd::swap(r1_sign, r2_sign);\n\t\t\t}\n\n\t\t\tif (signs_are_different) r2 = twos_complement(r2);\n\n\t\t\tif (_trace_sub) {\n\t\t\t\tstd::cout << (r1_sign ? \"sign -1\" : \"sign  1\") << \" scale \" << std::setw(3) << scale_of_result << \" r1       \" << r1 << std::endl;\n\t\t\t\tstd::cout << (r2_sign ? \"sign -1\" : \"sign  1\") << \" scale \" << std::setw(3) << scale_of_result << \" r2       \" << r2 << std::endl;\n\t\t\t}\n\n\t\t\tbitblock<abits + 1> sum;\n\t\t\tconst bool carry = add_unsigned(r1, r2, sum);\n\n\t\t\tif (_trace_sub) std::cout << (r1_sign ? \"sign -1\" : \"sign  1\") << \" carry \" << std::setw(3) << (carry ? 1 : 0) << \" sum     \" << sum << std::endl;\n\n\t\t\tlong shift = 0;\n\t\t\tif (carry) {\n\t\t\t\tif (r1_sign == r2_sign) {  // the carry && signs== implies that we have a number bigger than r1\n\t\t\t\t\tshift = -1;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t// the carry && signs!= implies r2 is complement, result < r1, must find hidden bit (in the complement)\n\t\t\t\t\tfor (int i = abits - 1; i >= 0 && !sum[i]; i--) {\n\t\t\t\t\t\tshift++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tassert(shift >= -1);\n\n\t\t\tif (shift >= long(abits)) {            // we have actual 0\n\t\t\t\tsum.reset();\n\t\t\t\tresult.set(false, 0, sum, true, false, false);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tscale_of_result -= shift;\n\t\t\tconst int hpos = abits - 1 - shift;         // position of the hidden bit\n\t\t\tsum <<= abits - hpos + 1;\n\t\t\tif (_trace_sub) std::cout << (r1_sign ? \"sign -1\" : \"sign  1\") << \" scale \" << std::setw(3) << scale_of_result << \" sum     \" << sum << std::endl;\n\t\t\tresult.set(r1_sign, scale_of_result, sum, false, false, false);\n\t\t}\n\n\t\t// subtract module using SUBTRACTOR: CURRENTLY BROKEN FOR UNKNOWN REASON\n\t\ttemplate<size_t fbits, size_t abits>\n\t\tvoid module_subtract_BROKEN(const value<fbits>& lhs, const value<fbits>& rhs, value<abits + 1>& result) {\n\n\t\t\tif (lhs.isInfinite() || rhs.isInfinite()) {\n\t\t\t\tresult.setToInfinite();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tint lhs_scale = lhs.scale(), rhs_scale = rhs.scale(), scale_of_result = std::max(lhs_scale, rhs_scale);\n\n\t\t\t// align the fractions\n\t\t\tbitblock<abits> r1 = lhs.template nshift<abits>(lhs_scale - scale_of_result + 3);\n\t\t\tbitblock<abits> r2 = rhs.template nshift<abits>(rhs_scale - scale_of_result + 3);\n\t\t\tbool r1_sign = lhs.sign(), r2_sign = rhs.sign();\n\t\t\tbool signs_are_equal = r1_sign == r2_sign;\n\n\t\t\tif (r1_sign) r1 = twos_complement(r1);\n\t\t\tif (r1_sign) r2 = twos_complement(r2);\n\n\t\t\tif (_trace_sub) {\n\t\t\t\tstd::cout << (r1_sign ? \"sign -1\" : \"sign  1\") << \" scale \" << std::setw(3) << scale_of_result << \" r1       \" << r1 << std::endl;\n\t\t\t\tstd::cout << (r2_sign ? \"sign -1\" : \"sign  1\") << \" scale \" << std::setw(3) << scale_of_result << \" r2       \" << r2 << std::endl;\n\t\t\t}\n\n\t\t\tbitblock<abits + 1> difference;\n\t\t\tconst bool borrow = subtract_unsigned(r1, r2, difference);\n\n\t\t\tif (_trace_sub) std::cout << (r1_sign ? \"sign -1\" : \"sign  1\") << \" borrow\" << std::setw(3) << (borrow ? 1 : 0) << \" diff    \" << difference << std::endl;\n\n\t\t\tlong shift = 0;\n\t\t\tif (borrow) {   // we have a negative value result\n\t\t\t\tdifference = twos_complement(difference);\n\t\t\t}\n\t\t\t// find hidden bit\n\t\t\tfor (int i = abits - 1; i >= 0 && difference[i]; i--) {\n\t\t\t\tshift++;\n\t\t\t}\n\t\t\tassert(shift >= -1);\n\n\t\t\tif (shift >= long(abits)) {            // we have actual 0\n\t\t\t\tdifference.reset();\n\t\t\t\tresult.set(false, 0, difference, true, false, false);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tscale_of_result -= shift;\n\t\t\tconst int hpos = abits - 1 - shift;         // position of the hidden bit\n\t\t\tdifference <<= abits - hpos + 1;\n\t\t\tif (_trace_sub) std::cout << (borrow ? \"sign -1\" : \"sign  1\") << \" scale \" << std::setw(3) << scale_of_result << \" result  \" << difference << std::endl;\n\t\t\tresult.set(borrow, scale_of_result, difference, false, false, false);\n\t\t}\n\n\t\t// multiply module\n\t\ttemplate<size_t fbits, size_t mbits>\n\t\tvoid module_multiply(const value<fbits>& lhs, const value<fbits>& rhs, value<mbits>& result) {\n\t\t\tstatic constexpr size_t fhbits = fbits + 1;  // fraction + hidden bit\n\t\t\tif (_trace_mul) std::cout << \"lhs  \" << components(lhs) << std::endl << \"rhs  \" << components(rhs) << std::endl;\n\n\t\t\tif (lhs.isInfinite() || rhs.isInfinite()) {\n\t\t\t\tresult.setToInfinite();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (lhs.isZero() || rhs.isZero()) {\n\t\t\t\tresult.setToZero();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tbool new_sign = lhs.sign() ^ rhs.sign();\n\t\t\tint new_scale = lhs.scale() + rhs.scale();\n\t\t\tbitblock<mbits> result_fraction;\n\n\t\t\tif (fbits > 0) {\n\t\t\t\t// fractions are without hidden bit, get_fixed_point adds the hidden bit back in\n\t\t\t\tbitblock<fhbits> r1 = lhs.get_fixed_point();\n\t\t\t\tbitblock<fhbits> r2 = rhs.get_fixed_point();\n\t\t\t\tmultiply_unsigned(r1, r2, result_fraction);\n\n\t\t\t\tif (_trace_mul) std::cout << \"r1  \" << r1 << std::endl << \"r2  \" << r2 << std::endl << \"res \" << result_fraction << std::endl;\n\t\t\t\t// check if the radix point needs to shift\n\t\t\t\tint shift = 2;\n\t\t\t\tif (result_fraction.test(mbits - 1)) {\n\t\t\t\t\tshift = 1;\n\t\t\t\t\tif (_trace_mul) std::cout << \" shift \" << shift << std::endl;\n\t\t\t\t\tnew_scale += 1;\n\t\t\t\t}\n\t\t\t\tresult_fraction <<= shift;    // shift hidden bit out\n\t\t\t}\n\t\t\telse {   // posit<3,0>, <4,1>, <5,2>, <6,3>, <7,4> etc are pure sign and scale\n\t\t\t\t// multiply the hidden bits together, i.e. 1*1: we know the answer a priori\n\t\t\t}\n\t\t\tif (_trace_mul) std::cout << \"sign \" << (new_sign ? \"-1 \" : \" 1 \") << \"scale \" << new_scale << \" fraction \" << result_fraction << std::endl;\n\n\t\t\tresult.set(new_sign, new_scale, result_fraction, false, false, false);\n\t\t}\n\n\t\t// divide module\n\t\ttemplate<size_t fbits, size_t divbits>\n\t\tvoid module_divide(const value<fbits>& lhs, const value<fbits>& rhs, value<divbits>& result) {\n\t\t\tstatic constexpr size_t fhbits = fbits + 1;  // fraction + hidden bit\n\t\t\tif (_trace_div) std::cout << \"lhs  \" << components(lhs) << std::endl << \"rhs  \" << components(rhs) << std::endl;\n\n\t\t\tif (lhs.isInfinite() || rhs.isInfinite()) {\n\t\t\t\tresult.setToInfinite();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (lhs.isZero() || rhs.isInfinite()) {\n\t\t\t\tresult.setToZero();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tbool new_sign = lhs.sign() ^ rhs.sign();\n\t\t\tint new_scale = lhs.scale() - rhs.scale();\n\t\t\tbitblock<divbits> result_fraction;\n\n\t\t\tif (fbits > 0) {\n\t\t\t\t// fractions are without hidden bit, get_fixed_point adds the hidden bit back in\n\t\t\t\tbitblock<fhbits> r1 = lhs.get_fixed_point();\n\t\t\t\tbitblock<fhbits> r2 = rhs.get_fixed_point();\n\t\t\t\tdivide_with_fraction(r1, r2, result_fraction);\n\t\t\t\tif (_trace_div) std::cout << \"r1     \" << r1 << std::endl << \"r2     \" << r2 << std::endl << \"result \" << result_fraction << std::endl << \"scale  \" << new_scale << std::endl;\n\t\t\t\t// check if the radix point needs to shift\n\t\t\t\t// radix point is at divbits - fhbits\n\t\t\t\tint msb = divbits - fhbits;\n\t\t\t\tint shift = fhbits;\n\t\t\t\tif (!result_fraction.test(msb)) {\n\t\t\t\t\tmsb--; shift++;\n\t\t\t\t\twhile (!result_fraction.test(msb)) { // search for the first 1\n\t\t\t\t\t\tmsb--; shift++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tresult_fraction <<= shift;    // shift hidden bit out\n\t\t\t\tnew_scale -= (shift - fhbits);\n\t\t\t\tif (_trace_div) std::cout << \"shift  \" << shift << std::endl << \"result \" << result_fraction << std::endl << \"scale  \" << new_scale << std::endl;;\n\t\t\t}\n\t\t\telse {   // posit<3,0>, <4,1>, <5,2>, <6,3>, <7,4> etc are pure sign and scale\n\t\t\t\t\t // no need to multiply the hidden bits together, i.e. 1*1: we know the answer a priori\n\t\t\t}\n\t\t\tif (_trace_div) std::cout << \"sign \" << (new_sign ? \"-1 \" : \" 1 \") << \"scale \" << new_scale << \" fraction \" << result_fraction << std::endl;\n\n\t\t\tresult.set(new_sign, new_scale, result_fraction, false, false, false);\n\t\t}\n\n\t}  // namespace unum\n\n}  // namespace sw\n", "meta": {"hexsha": "e6191de43d62c5db38373536342e098b9a906ecd", "size": 28484, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "posit/value.hpp", "max_stars_repo_name": "lvandam/universal", "max_stars_repo_head_hexsha": "a60558cce12213afa166904d774905df0684fb3f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "posit/value.hpp", "max_issues_repo_name": "lvandam/universal", "max_issues_repo_head_hexsha": "a60558cce12213afa166904d774905df0684fb3f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "posit/value.hpp", "max_forks_repo_name": "lvandam/universal", "max_forks_repo_head_hexsha": "a60558cce12213afa166904d774905df0684fb3f", "max_forks_repo_licenses": ["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.5648267009, "max_line_length": 257, "alphanum_fraction": 0.6063052942, "num_tokens": 8568, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.4674709180277749}}
{"text": "/* ---------------------------------------------------------------------\n *\n * Copyright (C) 1999 - 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 * <br>\n *\n * <i>\n * This program was contributed by Peter Munch. This work and the required\n * generalizations of the internal data structures of deal.II form part of the\n * project \"Virtual Materials Design\" funded by the Helmholtz Association of\n * German Research Centres.\n * </i>\n *\n *\n * <a name=\"Intro\"></a>\n * <h1>Introduction</h1>\n *\n * <h3>Motivation</h3>\n *\n * Many freely available mesh-generation tools produce meshes that consist of\n * simplices (triangles in 2D; tetrahedra in 3D). The reason for this is that\n * generating such kind of meshes for complex geometries is simpler than the\n * generation of hex-only meshes. This tutorial shows how to work on such kind\n * of meshes with the experimental simplex features in deal.II. For this\n * purpose, we solve the Poisson problem from step-3 in 2D with a mesh only\n * consisting of triangles.\n *\n *\n * <h3>Working on simplex meshes</h3>\n *\n * To be able to work on simplex meshes, one has to select appropriate finite\n * elements, quadrature rules, and mapping objects. In step-3, we used FE_Q,\n * QGauss, and (implicitly by not specifying a mapping) MappingQ1. The\n * equivalent classes for the first two classes in the context of simplices are\n * FE_SimplexP and QGaussSimplex, which we will utilize here. For mapping\n * purposes, we use the class MappingFE, which implements an isoparametric\n * mapping. We initialize it with an FE_SimplexP object so that it can be\n * applied on simplex meshes.\n *\n *\n * <h3>Mesh generation</h3>\n *\n * In contrast to step-3, we do not use a function from the GridGenerator\n * namespace, but rather read an externally generated mesh. For this tutorial,\n * we have created the mesh (square with width and height of one) with Gmsh with\n * the following journal file \"box_2D_tri.geo\":\n *\n * @code\n * Rectangle(1) = {0, 0, 0, 1, 1, 0};\n * Mesh 2;\n * Save \"box_2D_tri.msh\";\n * @endcode\n *\n * The journal file can be processed by Gmsh generating the actual mesh with the\n * ending \".geo\":\n *\n * @code\n * gmsh box_2D_tri.geo\n * @endcode\n *\n * We have included in the tutorial folder both the journal file and the mesh\n * file in the event that one does not have access to Gmsh.\n *\n * The mesh can be simply read by deal.II with methods provided by the GridIn\n * class, as shown below.\n *\n */\n\n\n// @sect3{Include files}\n\n// Include files, as used in step-3:\n#include <deal.II/base/function.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_values.h>\n\n#include <deal.II/grid/tria.h>\n\n#include <deal.II/lac/dynamic_sparsity_pattern.h>\n#include <deal.II/lac/full_matrix.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 <deal.II/numerics/data_out.h>\n#include <deal.II/numerics/matrix_tools.h>\n#include <deal.II/numerics/vector_tools.h>\n\n#include <fstream>\n#include <iostream>\n\n// Include files that contain appropriate quadrature rules, finite elements,\n// and mapping objects for simplex meshes.\n#include <deal.II/base/quadrature_lib.h>\n\n#include <deal.II/fe/fe_simplex_p.h>\n#include <deal.II/fe/mapping_fe.h>\n\n// The following file contains the class GridIn, which allows us to read\n// external meshes.\n#include <deal.II/grid/grid_in.h>\n\nusing namespace dealii;\n\n// @sect3{The <code>Step3</code> class}\n//\n// This is the main class of the tutorial. Since it is very similar to the\n// version from step-3, we will only point out and explain the relevant\n// differences that allow to perform simulations on simplex meshes.\n\nclass Step3\n{\npublic:\n  Step3();\n\n  void run();\n\nprivate:\n  void make_grid();\n  void setup_system();\n  void assemble_system();\n  void solve();\n  void output_results() const;\n\n  Triangulation<2> triangulation;\n\n  // Here, we select a mapping object, a finite element, and a quadrature rule\n  // that are compatible with simplex meshes.\n  const MappingFE<2>     mapping;\n  const FE_SimplexP<2>   fe;\n  const QGaussSimplex<2> quadrature_formula;\n\n  DoFHandler<2> dof_handler;\n\n  SparsityPattern      sparsity_pattern;\n  SparseMatrix<double> system_matrix;\n\n  Vector<double> solution;\n  Vector<double> system_rhs;\n};\n\n\n// @sect4{Step3::Step3}\n//\n// In the constructor, we set the polynomial degree of the finite element and\n// the number of quadrature points. Furthermore, we initialize the MappingFE\n// object with a (linear) FE_SimplexP object so that it can work on simplex\n// meshes.\nStep3::Step3()\n  : mapping(FE_SimplexP<2>(1))\n  , fe(2)\n  , quadrature_formula(3)\n  , dof_handler(triangulation)\n{}\n\n\n// @sect4{Step3::make_grid}\n//\n// Read the external mesh file \"box_2D_tri.msh\" as in step-3.\nvoid Step3::make_grid()\n{\n  GridIn<2>(triangulation).read(\"box_2D_tri.msh\");\n\n  std::cout << \"Number of active cells: \" << triangulation.n_active_cells()\n            << std::endl;\n}\n\n\n// @sect4{Step3::setup_system}\n//\n// From here on, nothing has changed. Not even, the\n// cell integrals have been changed depending on whether one operates on\n// hypercube or simplex meshes. This is astonishing and is possible due to the\n// design of the following two classes:\n//  - DoFHandler: this class stores degrees of freedom in a flexible way and\n//    allows simple access to them depending on the element type independent of\n//    the cell type.\n//  - FEValues: this class hides the details of finite element, quadrature rule,\n//    and mapping (even if the implementations are inherently different)\n//    behind a unified interface.\nvoid Step3::setup_system()\n{\n  dof_handler.distribute_dofs(fe);\n  std::cout << \"Number of degrees of freedom: \" << dof_handler.n_dofs()\n            << std::endl;\n  DynamicSparsityPattern dsp(dof_handler.n_dofs());\n  DoFTools::make_sparsity_pattern(dof_handler, dsp);\n  sparsity_pattern.copy_from(dsp);\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// @sect4{Step3::assemble_system}\n//\n// Nothing has changed here.\nvoid Step3::assemble_system()\n{\n  FEValues<2> fe_values(mapping,\n                        fe,\n                        quadrature_formula,\n                        update_values | update_gradients | update_JxW_values);\n\n  const unsigned int dofs_per_cell = fe.n_dofs_per_cell();\n  FullMatrix<double> cell_matrix(dofs_per_cell, dofs_per_cell);\n  Vector<double>     cell_rhs(dofs_per_cell);\n  std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell);\n\n  for (const auto &cell : dof_handler.active_cell_iterators())\n    {\n      fe_values.reinit(cell);\n\n      cell_matrix = 0;\n      cell_rhs    = 0;\n\n      for (const unsigned int q_index : fe_values.quadrature_point_indices())\n        {\n          for (const unsigned int i : fe_values.dof_indices())\n            for (const unsigned int j : fe_values.dof_indices())\n              cell_matrix(i, j) +=\n                (fe_values.shape_grad(i, q_index) * // grad phi_i(x_q)\n                 fe_values.shape_grad(j, q_index) * // grad phi_j(x_q)\n                 fe_values.JxW(q_index));           // dx\n\n          for (const unsigned int i : fe_values.dof_indices())\n            cell_rhs(i) += (fe_values.shape_value(i, q_index) * // phi_i(x_q)\n                            1. *                                // f(x_q)\n                            fe_values.JxW(q_index));            // dx\n        }\n      cell->get_dof_indices(local_dof_indices);\n\n      for (const unsigned int i : fe_values.dof_indices())\n        for (const unsigned int j : fe_values.dof_indices())\n          system_matrix.add(local_dof_indices[i],\n                            local_dof_indices[j],\n                            cell_matrix(i, j));\n\n      for (const unsigned int i : fe_values.dof_indices())\n        system_rhs(local_dof_indices[i]) += cell_rhs(i);\n    }\n\n\n  std::map<types::global_dof_index, double> boundary_values;\n  VectorTools::interpolate_boundary_values(\n    mapping, dof_handler, 0, Functions::ZeroFunction<2>(), boundary_values);\n  MatrixTools::apply_boundary_values(boundary_values,\n                                     system_matrix,\n                                     solution,\n                                     system_rhs);\n}\n\n\n// @sect4{Step3::solve}\n//\n// Nothing has changed here.\nvoid Step3::solve()\n{\n  SolverControl            solver_control(1000, 1e-12);\n  SolverCG<Vector<double>> solver(solver_control);\n  solver.solve(system_matrix, solution, system_rhs, PreconditionIdentity());\n}\n\n\n// @sect4{Step3::output_results}\n//\n// Nothing has changed here.\nvoid Step3::output_results() const\n{\n  DataOut<2> data_out;\n\n  DataOutBase::VtkFlags flags;\n  flags.write_higher_order_cells = true;\n  data_out.set_flags(flags);\n\n  data_out.attach_dof_handler(dof_handler);\n  data_out.add_data_vector(solution, \"solution\");\n  data_out.build_patches(mapping, 2);\n  std::ofstream output(\"solution.vtk\");\n  data_out.write_vtk(output);\n}\n\n\n// @sect4{Step3::run}\n//\n// Nothing has changed here.\nvoid Step3::run()\n{\n  make_grid();\n  setup_system();\n  assemble_system();\n  solve();\n  output_results();\n}\n\n\n// @sect3{The <code>main</code> function}\n//\n// Nothing has changed here.\nint main()\n{\n  deallog.depth_console(2);\n\n  Step3 laplace_problem;\n  laplace_problem.run();\n\n  return 0;\n}\n\n/*\n * <h1>Results</h1>\n *\n * The following figures show the mesh and the result obtained by executing this\n * program:\n *\n * <table align=\"center\" class=\"doxtable\" style=\"width:65%\">\n *   <tr>\n *     <td>\n *         @image html step_3_simplex_0.png\n *     </td>\n *     <td>\n *         @image html step_3_simplex_1.png\n *     </td>\n *   </tr>\n * </table>\n *\n * Not surprisingly, the result looks as expected.\n *\n *\n * <h3>Possibilities for extensions</h3>\n *\n * In this tutorial, we presented how to use the deal.II simplex infrastructure\n * to solve a simple Poisson problem on a simplex mesh in 2D. In this scope, we\n * could only present a small section of the capabilities. In the following, we\n * point out further capabilities briefly.\n *\n *\n * <h4>3D meshes and codim-1 meshes in 3D</h4>\n *\n * An extension to 3D is quite straightforward. Both FE_SimplexP and\n * QGaussSimplex are implemented in a dimensional-independent way so that simply\n * replacing everywhere dim=2 with dim=3 should work out of the box.\n *\n * Furthermore, embedding of a 2D mesh consisting of triangles in 3D space is\n * possible.\n *\n *\n * <h4>Mixed meshes</h4>\n *\n * In step-3, we considered meshes only consisting of quadrilaterals. In this\n * tutorial, we took a look at the case that the mesh only consists of\n * triangles. In the general case (also known as mixed mesh), the mesh consists\n * of both cell types. In 3D, meshes might even consist of more cell types, like\n * wedges/prisms and pyramids. We consider such meshes in the tutorial\n * step-3mixed.\n *\n *\n * <h4>Alternative finite elements, quadrature rules, and mapping objects</h4>\n *\n * In this tutorial, we used the most basic finite-element, quadrature-rule, and\n * mapping classes. However, more classes are compatible with simplices. The\n * following list gives an overview of these classes:\n * - finite elements: FE_SimplexP, FE_SimplexDGP, FE_SimplexP_Bubbles\n * - quadrature rules: QGaussSimplex, QWitherdenVincentSimplex, QDuffy\n * - mapping objects: MappingFE, MappingFEField\n *\n * It should be also pointed out that FESystems can also handle simplex finite\n * elements which is crucial to solve vector-valued problems, as needed, e.g.,\n * to solve elasticity and fluid problems (see also step-17).\n *\n *\n * <h4>Alternative mesh generation approaches</h4>\n *\n * In this tutorial, we have created the mesh externally and read it with the\n * help of GridIn. Since we believe that the main motivation to work on simplex\n * meshes is that one has a complex geometry that can only be meshed with\n * an external tool with simplices, deal.II does not have too many functions in\n * the GridGenerator namespace, targeting simplex meshes. However, we would like\n * to point out the following functions:\n *  - GridGenerator::subdivided_hyper_cube_with_simplices() and\n *    GridGenerator::subdivided_hyper_rectangle_with_simplices(), which fill a\n *    hypercube and a hyperrectangle domain with simplices\n *  - GridGenerator::convert_hypercube_to_simplex_mesh(), which converts meshes\n *    consisting of hypercube cells to simplex meshes by replacing one\n *    quadrilateral with 4 triangles and one hexahedron with 24 tetrahedrons\n *\n *\n * <h4>hp-adaptivity</h4>\n *\n * Here, we considered a mesh without refinements and with all cells assigned\n * the same type of element with the same polynomial degree. However, one is not\n * restricted to this. For further details on hp-methods, see step-27.\n *\n *\n * <h4>Parallelization</h4>\n *\n * To parallelize the code, one needs to replace the Triangulation object either\n * with parallel::shared::Triangulation or\n * parallel::fullydistributed::Triangulation and make some minor adjustments, as\n * discussed in step-6.\n *\n *\n * <h4>Face integrals and discontinuous Galerkin methods</h4>\n *\n * The classes FEFaceValues and FEInterfaceValues are also compatible with\n * simplex meshes.\n *\n *\n * <h4>Matrix-free operator evaluation</h4>\n *\n * In this tutorial, we showed a matrix-based approach. However, one could also\n * rewrite the code using MatrixFree, FEEvaluation, and FEFaceEvaluation, which\n * are also compatible with simplex meshes.\n *\n */\n", "meta": {"hexsha": "c695fe654cd51444d16eeaf40ef55e81c633a128", "size": 14009, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/doxygen/step_3_simplex.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/doxygen/step_3_simplex.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/doxygen/step_3_simplex.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": 32.3533487298, "max_line_length": 80, "alphanum_fraction": 0.6945535013, "num_tokens": 3532, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.6654105454764747, "lm_q1q2_score": 0.46747090870496266}}
{"text": "//\r\n// Created by \u0421\u0435\u0440\u0433\u0435\u0439 \u041a\u0440\u0438\u0432\u043e\u043d\u043e\u0441 on 01.09.17.\r\n//\r\n#include \"Exponentiation.h\"\r\n\r\n#include \"Valuable.h\"\r\n#include \"e.h\"\r\n#include \"i.h\"\r\n#include \"Infinity.h\"\r\n#include \"pi.h\"\r\n#include \"Integer.h\"\r\n#include \"Sum.h\"\r\n#include \"Product.h\"\r\n\r\n#include <cmath>\r\n#include <limits>\r\n\r\n#include <boost/numeric/conversion/cast.hpp>\r\n\r\nnamespace omnn{\r\nnamespace math {\r\n\r\n    Exponentiation::Exponentiation(const Valuable& b, const Valuable& exponentiation)\r\n        : base(b, exponentiation)\r\n    {\r\n        InitVars();\r\n    }\r\n\r\n    max_exp_t Exponentiation::getMaxVaExp(const Valuable& b, const Valuable& e)\r\n    {\r\n        if (e.IsInt()) {\r\n            return b.getMaxVaExp() * e.ca();\r\n        } else if (e.FindVa()) {\r\n            auto i = b.getMaxVaExp();\r\n            if (i) {\r\n                auto _ = e;\r\n                const Variable* v;\r\n                while ((v = _.FindVa())) {\r\n                    _.Eval(*v, 0);\r\n                }\r\n                _.optimize();\r\n                i *= static_cast<a_int>(_);\r\n            }\r\n            return i;\r\n        } else {\r\n            auto maxVaExp = e * b.getMaxVaExp();\r\n            if (maxVaExp.IsInt()) {\r\n                return maxVaExp.ca();\r\n            } else if (maxVaExp.IsSimpleFraction()) {\r\n                auto& f = maxVaExp.as<Fraction>();\r\n                return {f.getNumerator().ca(), f.getDenominator().ca()};\r\n            } else if(!optimizations) {\r\n                optimizations = true;\r\n                maxVaExp.optimize();\r\n                optimizations = {};\r\n                if (maxVaExp.IsInt()) {\r\n                    return maxVaExp.ca();\r\n                }\r\n            }\r\n        }\r\n\r\n        IMPLEMENT\r\n    }\r\n\r\n    max_exp_t Exponentiation::getMaxVaExp() const\r\n    {\r\n        return getMaxVaExp(getBase(), getExponentiation());\r\n    }\r\n    \r\n    Valuable Exponentiation::varless() const\r\n    {\r\n        if(getBase().IsVa()) {\r\n            return constants::one;\r\n        } else if (FindVa()) {\r\n            IMPLEMENT;\r\n        }\r\n        else\r\n            return *this;\r\n    }\r\n\r\n    void Exponentiation::InitVars() {\r\n        v.clear();\r\n        if (ebase().IsVa())\r\n            v[ebase().as<Variable>()] = eexp();\r\n    }\r\n\r\n    void Exponentiation::optimize()\r\n    {\r\n        if (optimized) {\r\n            return;\r\n        }\r\n\r\n        if (!optimizations)\r\n        {\r\n            hash = ebase().Hash() ^ eexp().Hash();\r\n            InitVars();\r\n            return;\r\n        }\r\n\r\n        ebase().optimize();\r\n        eexp().optimize();\r\n\r\n        if (ebase().IsExponentiation() || ebase().IsProduct())\r\n        {\r\n            ebase() ^= eexp();\r\n            Become(std::move(ebase()));\r\n            return;\r\n        }\r\n        \r\n        if (eexp().IsSum())\r\n        {\r\n            auto& s = eexp().as<Sum>();\r\n            auto sz = s.size();\r\n            auto v = 1_v;\r\n            for(auto it = s.begin(), e = s.end();\r\n                it != e; )\r\n            {\r\n                if (it->IsInt()) {\r\n                    v *= ebase()^*it;\r\n                    s.Delete(it);\r\n                }\r\n                else\r\n                    ++it;\r\n            }\r\n            if (sz != s.size()) {\r\n                Become(*this * v);\r\n                return;\r\n            }\r\n        }\r\n\r\n        // todo : check it, comment this and try System test\r\n//        if (ebase().IsSum() && eexp().IsFraction())\r\n//        {\r\n//            auto f = Fraction::cast(eexp());\r\n//            auto& d = f->getDenominator();\r\n//            if (d == ebase().getMaxVaExp()) {\r\n//                auto vars = ebase().Vars();\r\n//                if (vars.size() == 1) {\r\n//                    auto va = *vars.begin();\r\n//                    auto baseToSolve = ebase();\r\n//                    baseToSolve.SetView(View::Solving);\r\n//                    baseToSolve.optimize();\r\n//                    auto eq = va - baseToSolve(va);\r\n//                    auto sq = eq ^ d;\r\n//                    auto check = ebase()/sq;\r\n//                    if (check.IsInt() || check.IsSimpleFraction()) {\r\n//                        ebase() = eq;\r\n//                        eexp() = f->getNumerator();\r\n//                    } else {\r\n//                        // TODO : IMPLEMENT\r\n//                    }\r\n//                }\r\n//            }\r\n//        }\r\n//\r\n//        if (ebase().IsSum() && eexp().IsFraction())\r\n//        {\r\n//            auto f = Fraction::cast(eexp());\r\n//            auto& d = f->getDenominator();\r\n//            auto e = ebase() ^ f->getNumerator();\r\n//            if (d == e.getMaxVaExp()) {\r\n//                auto vars = e.Vars();\r\n//                if (vars.size() == 1) {\r\n//                    auto va = *vars.begin();\r\n//                    auto eq = va - e(va);\r\n//                    auto sq = eq ^ d;\r\n//                    auto check = e / sq;\r\n//                    if (check.IsInt() || check.IsSimpleFraction()) {\r\n//                        Become(std::move(eq));\r\n//                        return;\r\n//                    } else {\r\n//                        // TODO : IMPLEMENT\r\n//                    }\r\n//                }\r\n//            }\r\n//        }\r\n        \r\n        if (ebase().IsFraction() && eexp().IsMultival()==YesNoMaybe::No) {\r\n            auto& f = ebase().as<Fraction>();\r\n            auto _ = (f.getNumerator() ^ eexp()) / (f.getDenominator() ^ eexp());\r\n            if (_.IsExponentiation()) {\r\n                auto& e = _.as<Exponentiation>();\r\n                if (!(e.ebase()==ebase() && eexp()==e.eexp())) {\r\n                    IMPLEMENT\r\n                }\r\n            } else {\r\n                Become(std::move(_));\r\n                return;\r\n            }\r\n        }\r\n\r\n        if (ebase().IsFraction() && eexp().IsInt() && eexp() < 0_v) {\r\n            eexp() = -eexp();\r\n            ebase() = ebase().as<Fraction>().Reciprocal();\r\n        }\r\n\r\n\t\t// e^(i*pi) = -1\r\n                // it is a fundamental equation that gives us a hint on cross-dimmensional relations\r\n                // because i and -1 are 1 of different signs/dimmensions\r\n        if (ebase().Is_e()) {\r\n            if (eexp().IsProduct()) {\r\n                auto& p = eexp().as<Product>();\r\n                if (p.Has(constants::pi) &&\r\n                    p.Has(constants::i)) { // TODO : sequence does matter :\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t // e^(i*pi) =?= e^(pi*i)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t // https://en.wikipedia.org/wiki/Commutative_property#Division,_subtraction,_and_exponentiation \r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t // what about Commutativity on irrationals product?\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t // lets assume yes for this particular expression, but there are some doubts, need a prove\r\n\r\n\t\t\t\t\t\t// here is implementation for case of no commutativity:\r\n                                    // auto e = p.end();\r\n                                    // auto it = std::find(p.begin(), e, constant::i);\r\n                                    // auto has_i = it != e;\r\n                                    // if (has_i) {\r\n                                    //     it = std::find(++it, e, constant::pi);\r\n                                    //     auto has_pi_next_to_i = it != e; // maybe sequence does matter\r\n                                    // }\r\n\r\n                    p /= constant::i;\r\n                    p /= constant::pi;\r\n                    Become(Exponentiation{-1, p});\r\n                    return;\r\n                }\r\n            }\r\n        }\r\n        // todo : check\r\n        if (ebase().IsSimple()) {\r\n            if (eexp().IsProduct()) {\r\n                auto& p = eexp().as<Product>();\r\n                auto it = p.GetFirstOccurence<Integer>();\r\n                auto in = ebase() ^ *it;  // IsExponentiationSimplifiable\r\n                if (in.IsInt()) {\r\n                    ebase() = in;\r\n                    p.Delete(it);\r\n                    if (p.size() == 1) {\r\n                        eexp().optimize();\r\n                    }\r\n                }\r\n            }\r\n            if (ebase()==1) {\r\n                if (eexp().IsInt()) {\r\n                    Become(std::move(ebase()));\r\n                    return;\r\n                } else if (eexp().IsSimpleFraction() && eexp() > 0_v) {\r\n                    auto& f = eexp().as<Fraction>();\r\n                    auto& n = f.getNumerator();\r\n                    if (n.IsEven() == YesNoMaybe::Yes) {\r\n                        auto&& toOptimize = std::move(eexp());\r\n                        toOptimize.optimize();\r\n                        setExponentiation(std::move(toOptimize));\r\n                        optimize();\r\n                        return;\r\n                    }\r\n                    auto& dn = f.getDenominator();\r\n                    if (dn.bit(0)) {\r\n                        Become(std::move(ebase()));\r\n                        return;\r\n                    } else if (n != 1_v) {\r\n                        hash ^= f.Hash();\r\n                        f.update1(1_v);\r\n                        hash ^= f.Hash();\r\n\t\t\t\t\t}\r\n                } else if (!!eexp().IsMultival()) {\r\n                } else if (!(eexp().IsInfinity() || eexp().IsMInfinity())) {\r\n                    Become(std::move(ebase()));\r\n                    return;\r\n                } else\r\n                    IMPLEMENT;\r\n            } else if (ebase() == -1 && eexp().IsInt() && eexp() > 0 && eexp() != 1) {\r\n                    eexp() = eexp().bit(0);\r\n            } else if (eexp()==-1) {\r\n                Become(Fraction{1,ebase()});\r\n                return;\r\n            } else if (eexp().IsInfinity()) {\r\n                IMPLEMENT\r\n            } else if (eexp().IsFraction()) {\r\n                auto& f = eexp().as<Fraction>();\r\n                auto& n = f.getNumerator();\r\n                if (n != 1) {\r\n                    // TODO: auto is = ebase().IsExponentiationSimplifiable(n);\r\n                    auto newBase = ebase() ^ n;\r\n                    if(!newBase.IsExponentiation()){\r\n                        Become(newBase ^ (1_v / f.getDenominator()));\r\n                        return;\r\n                    }\r\n                }\r\n            }\r\n        }\r\n\r\n        bool ebz = ebase() == 0_v;\r\n        bool exz = eexp() == 0_v;\r\n        if(exz)\r\n        {\r\n            if (ebase().IsInfinity() || ebase().IsMInfinity()) {\r\n                IMPLEMENT\r\n            }\r\n            if(ebz)\r\n                throw \"NaN\";\r\n\r\n            Become(1_v);\r\n            return;\r\n        }\r\n        else if(eexp() == 1_v)\r\n        {\r\n            Become(std::move(ebase()));\r\n            return;\r\n        }\r\n        else if (ebz)\r\n        {\r\n            if (exz)\r\n                throw \"NaN\";\r\n            Become(0_v);\r\n            return;\r\n        }\r\n        else if (ebase().IsInfinity())\r\n        {\r\n            if (eexp() > 0) {\r\n                Become(std::move(ebase()));\r\n            } else\r\n                IMPLEMENT\r\n        }\r\n        else if (ebase().IsMInfinity())\r\n        {\r\n            if (eexp() > 0) {\r\n                if ((eexp() % 2) > 0) // TODO : test with non-ints\r\n                    Become(std::move(ebase()));\r\n                else\r\n                    Become(Infinity());\r\n            } else\r\n                IMPLEMENT\r\n        }\r\n        else if (ebase().IsVa() && eexp().IsSimple())\r\n        {\r\n        }\r\n        else\r\n        {\r\n            switch(view)\r\n            {\r\n                case View::Solving:\r\n\r\n                case View::None:\r\n                case View::Calc:\r\n                {\r\n                    if (eexp().IsInt() && eexp()>0) {\r\n                        auto b = 1_v;\r\n                        for (; eexp()--;) {\r\n                            b *= ebase();\r\n                        }\r\n                        Become(std::move(b));\r\n                        return;\r\n                    }\r\n                    if (ebase().IsInt() && eexp().IsInt()) {\r\n                        Become(ebase() ^ eexp());\r\n                        return;\r\n                    }\r\n                    break;\r\n                }\r\n                case View::Flat: {\r\n\r\n                    if(eexp().IsInt())\r\n                    {\r\n                        if (ebase().IsVa()) {\r\n                            break;\r\n                        }\r\n                        if (eexp() != 0_v) {\r\n                            if (eexp() > 1) {\r\n                                Valuable x = ebase();\r\n                                Valuable n = eexp();\r\n                                if (n < 0_v)\r\n                                {\r\n                                    x = 1_v / x;\r\n                                    n = -n;\r\n                                }\r\n                                if (n == 0_v)\r\n                                {\r\n                                    Become(1_v);\r\n                                    return;\r\n                                }\r\n                                auto y = 1_v;\r\n                                while(n > 1)\r\n                                {\r\n                                    bool isInt = n.IsInt();\r\n                                    if (!isInt)\r\n                                        IMPLEMENT\r\n                                    if (isInt && n.bit(0) == 0_v)\r\n                                    {\r\n                                        x.sq();\r\n                                        n /= 2;\r\n                                    }\r\n                                    else\r\n                                    {\r\n                                        y *= x;\r\n                                        x.sq();\r\n                                        --n;\r\n                                        n /= 2;\r\n                                    }\r\n                                }\r\n                                x *= y;\r\n                                Become(std::move(x));\r\n                            } else if (eexp()!=-1){\r\n                                // negative\r\n                                Become(1_v/(ebase()^(-eexp())));\r\n                            }\r\n                        }\r\n                        else { // zero\r\n                            if (ebase() == 0_v)\r\n                            {\r\n                                IMPLEMENT\r\n                                throw \"NaN\"; // feel free to handle this properly\r\n                            }\r\n                            else\r\n                            {\r\n                                Become(1_v);\r\n                            }\r\n                        }\r\n                    }\r\n//                    else\r\n//                    IMPLEMENT\r\n                    break;\r\n                }\r\n                case View::Equation: {\r\n                    if(eexp().IsSimple())\r\n                        Become(std::move(ebase()));\r\n                    break;\r\n                }\r\n                default:\r\n                \tLOG_AND_IMPLEMENT(str() << \" mode is \" << view);\r\n            }\r\n        }\r\n\r\n        if(IsExponentiation() && ebase().IsExponentiation())\r\n        {\r\n            auto& e = ebase().as<Exponentiation>();\r\n            auto& eeexp = e.getExponentiation();\r\n            if ((eeexp.FindVa() == nullptr) == (eexp().FindVa() == nullptr)) {\r\n                eexp() *= eeexp;\r\n                // todo : copy if it shared\r\n                ebase() = std::move(const_cast<Valuable&>((e.getBase())));\r\n            }\r\n        }\r\n\r\n        if (IsExponentiation()) {\r\n            hash = ebase().Hash() ^ eexp().Hash();\r\n            optimized = true;\r\n            InitVars();\r\n        }\r\n    }\r\n    \r\n    Valuable& Exponentiation::operator +=(const Valuable& v)\r\n    {\r\n        return Become(Sum {*this, v});\r\n    }\r\n\r\n    Valuable& Exponentiation::operator *=(const Valuable& v)\r\n    {\r\n        const Exponentiation* e;\r\n        const Fraction* f;\r\n        const Product* fdn = {};\r\n        const Exponentiation* fdne;\r\n        auto isProdHasExpWithSameBase = [this](const Product* p) -> const Exponentiation*\r\n        {\r\n            for(auto& it : *p){\r\n                if (it.IsExponentiation()) {\r\n                    auto& e = it.as<Exponentiation>();\r\n                    if (ebase() == e.getBase()) {\r\n                        return &e;\r\n                    }\r\n                }\r\n            }\r\n            return {};\r\n        };\r\n        auto& b = ebase();\r\n        if (v.IsExponentiation()\r\n            && b == (e = &v.as<Exponentiation>())->getBase()\r\n            && (eexp().IsInt() || eexp().IsSimpleFraction()) && eexp() > 0\r\n            && (e->eexp().IsInt() || e->eexp().IsSimpleFraction()) && e->eexp() > 0\r\n            )\r\n        {\r\n            updateExponentiation(eexp() + e->getExponentiation());\r\n            optimized={};\r\n        }\r\n        else if(v.IsFraction()\r\n                && (f = &v.as<Fraction>())->getDenominator() == ebase())\r\n        {\r\n            --eexp();\r\n            optimized={};\r\n            optimize();\r\n            return *this *= f->getNumerator();\r\n        }\r\n        else if(v.IsFraction()\r\n                && f->getDenominator().IsProduct()\r\n                && (fdn = &f->getDenominator().as<Product>())->Has(ebase()))\r\n        {\r\n            --eexp();\r\n            optimized={};\r\n            optimize();\r\n            return *this *= f->getNumerator() / (*fdn / ebase());\r\n        }\r\n        else if(fdn\r\n                && (fdne = isProdHasExpWithSameBase(fdn)))\r\n        {\r\n            eexp() -= fdne->getExponentiation();\r\n            optimized={};\r\n            optimize();\r\n            return *this *= f->getNumerator() / (*fdn / *fdne);\r\n        }\r\n        else if(b == v && v.FindVa())\r\n        {\r\n            updateExponentiation(eexp()+1);\r\n            optimized={};\r\n        }\r\n        else if(-b == v && v.FindVa())\r\n        {\r\n            updateExponentiation(eexp()+1);\r\n            optimized = {};\r\n            return Become(Product{-1, *this});\r\n        }\r\n        else if(v.IsProduct())\r\n        {\r\n            return Become(v * *this);\r\n        }\r\n        else if(v.IsInt())\r\n        {\r\n            if(v==1)\r\n                return *this;\r\n            else if(eexp()==-1 && ebase().IsInt())\r\n                return Become(v/ebase());\r\n            else\r\n                return Become(Product{v, *this});\r\n        }\r\n        else\r\n            return Become(Product{v, *this});\r\n\r\n        optimize();\r\n        return *this;\r\n    }\r\n\r\n    bool Exponentiation::MultiplyIfSimplifiable(const Valuable& v)\r\n    {\r\n        auto is = v == getBase();\r\n        if (is) {\r\n            ++eexp();\r\n            optimized = {};\r\n            optimize();\r\n        } else if (v == constants::one) {\r\n            is = true;\r\n        } else if (!FindVa() && IsMultival() == YesNoMaybe::Yes && !v.FindVa()) {\r\n            solutions_t values;\r\n            for (auto& value : Distinct()) {\r\n                auto&& extract = std::move(const_cast<Valuable&>(value));\r\n                if (extract.MultiplyIfSimplifiable(v)) {\r\n                    is = true;\r\n\t\t\t\t} else {\r\n                    extract *= v;\r\n\t\t\t\t}\r\n                values.emplace(std::move(extract));\r\n            }\r\n            Become(Valuable(std::move(values)));\r\n        } else if (v.IsExponentiation()) {\r\n            auto& vexpo = v.as<Exponentiation>();\r\n            is = vexpo.getBase() == getBase();\r\n            if (is) {\r\n                eexp() += vexpo.eexp();\r\n                optimized = {};\r\n                optimize();\r\n            } // TODO : else if ? (base^2 == v.base)\r\n            else {\r\n                is = vexpo.getExponentiation() == getExponentiation();\r\n                if (is) {\r\n                    auto wasBaseHash = ebase().Hash();\r\n                    is = ebase().MultiplyIfSimplifiable(vexpo.getBase());\r\n                    if (is) {\r\n                        Valuable::hash ^= wasBaseHash ^ ebase().Hash();\r\n                        optimized = {};\r\n                        optimize();\r\n                    }\r\n                }\r\n            }\r\n        } else if (v.IsMultival() == YesNoMaybe::Yes) {\r\n            LOG_AND_IMPLEMENT(str() << \" Exponentiation::MultiplyIfSimplifiable \" << v);\r\n        } else if (v.IsInt()) {\r\n            IMPLEMENT\r\n        } else {\r\n//            std::cout << str() << \" * \" << v.str() << std::endl;\r\n        }\r\n        return is;\r\n    }\r\n\r\n    std::pair<bool,Valuable> Exponentiation::IsMultiplicationSimplifiable(const Valuable& v) const\r\n    {\r\n        std::pair<bool,Valuable> is, expSumSimplifiable = {};\r\n        is.first = v == getBase()\r\n            && (expSumSimplifiable = eexp().IsSummationSimplifiable(constants::one)).first;\r\n        if (is.first) {\r\n            is.second = getBase() ^ expSumSimplifiable.second;\r\n        } else if (v.IsExponentiation()) {\r\n            auto& vexpo = v.as<Exponentiation>();\r\n            is.first = vexpo.getBase() == getBase();\r\n            if (is.first) {\r\n                is.second = ebase() ^ (eexp() + vexpo.eexp());\r\n            } // TODO : else if ? (base^2 == v.base)\r\n        } else if (v.IsSimple()) {\r\n            auto& ee = getExponentiation();\r\n            //is = v.IsExponentiationSimplifiable(ee);  // TODO: Implement IsExponentiationSimplifiable\r\n            // FIXME: Until IsExponentiationSimplifiable ready:\r\n            if (ee.IsSimpleFraction()) {\r\n                is.second = v ^ ee.as<Fraction>().Reciprocal(); // v.IsExponentiationSimplifiable(ee)\r\n                is.first = is.second.MultiplyIfSimplifiable(getBase());\r\n                if(is.first){\r\n                    auto copy = *this;\r\n                    copy.updateBase(std::move(is.second));\r\n                    is.second = copy;\r\n                }\r\n            }\r\n            else if (ee == constants::minus_1)\r\n            {\r\n                is.second = v ^ constants::minus_1; // v.IsExponentiationSimplifiable(ee)\r\n                is.first = is.second.MultiplyIfSimplifiable(getBase());\r\n                if(is.first){\r\n                    auto copy = *this;\r\n                    copy.updateBase(std::move(is.second));\r\n                    is.second = copy;\r\n                }\r\n            }\r\n            else if (ee.IsInt() && (ee > constants::zero)) // TODO: ee < 0 too\r\n            {\r\n//                is.second = v ^ (ee ^ constants::minus_1); // v.IsExponentiationSimplifiable(ee)\r\n//                is.first = is.second.MultiplyIfSimplifiable(getBase());\r\n//                if(is.first){\r\n//                    auto copy = *this;\r\n//                    copy.updateBase(std::move(is.second));\r\n//                    is.second = copy;\r\n//                }\r\n            }\r\n//            if (getBase().IsVa()) {\r\n//            } else if (getExponentiation().IsSimpleFraction()) {\r\n//                auto\r\n//                is.first = IsMultiplicationSimplifiable()\r\n//            } else if (getExponentiation().IsSimple()) {\r\n//                is = base::IsMultiplicationSimplifiable(v);\r\n//            } else {\r\n//                IMPLEMENT\r\n//            }\r\n        } else if (v.IsVa()) {\r\n            // covered by (v==base()) case\r\n        } else if (v.IsProduct()) {\r\n            is=v.IsMultiplicationSimplifiable(*this);\r\n        } else if (v.IsSum()) {\r\n            auto& sum=v.as<Sum>();\r\n            is.first=sum==getBase()||-sum==getBase();\r\n            if(is.first){\r\n                is.second=*this*sum;\r\n            }else{\r\n                is=sum.IsMultiplicationSimplifiable(*this);\r\n            }\r\n        } else {\r\n#ifndef NDEBUG\r\n            std::cout << \"IsMultiplication simplifiable?: \" << str() << \" * \" << v.str() << std::endl;\r\n#endif\r\n        }\r\n        return is;\r\n    }\r\n\r\n    bool Exponentiation::SumIfSimplifiable(const Valuable& v)\r\n    {\r\n        auto is = !v.IsSimple() && !v.IsFraction() && !v.IsExponentiation();\r\n        if(is){\r\n            auto sumIfSimplifiable = v.IsSummationSimplifiable(*this);\r\n            is = sumIfSimplifiable.first;\r\n            if (is)\r\n                Become(std::move(sumIfSimplifiable.second));\r\n        }\r\n        return is;\r\n    }\r\n\r\n    std::pair<bool,Valuable> Exponentiation::IsSummationSimplifiable(const Valuable& v) const\r\n    {\r\n        std::pair<bool,Valuable> is;\r\n        is.first = operator==(v);\r\n        if (is.first) {\r\n            is.second = *this * 2;\r\n        } else if ((is.first = operator==(-v))) {\r\n                is.second = 0;\r\n        } else if (v.IsSimple()\r\n                || v.IsExponentiation()\r\n                || v.IsVa()\r\n                || v.IsFraction())\r\n        {\r\n        } else {\r\n            is = v.IsSummationSimplifiable(*this);\r\n        }\r\n        return is;\r\n    }\r\n\r\n    Valuable& Exponentiation::operator /=(const Valuable& v)\r\n    {\r\n        auto isMultival = IsMultival()==YesNoMaybe::Yes;\r\n        auto vIsMultival = v.IsMultival()==YesNoMaybe::Yes;\r\n        if(isMultival && vIsMultival) {\r\n            solutions_t vals, thisValues;\r\n            Values([&](auto& thisVal){\r\n                thisValues.insert(thisVal);\r\n                return true;\r\n            });\r\n            \r\n            v.Values([&](auto&vVal){\r\n                for(auto& tv:thisValues)\r\n                    vals.insert(tv/vVal);\r\n                return true;\r\n            });\r\n            \r\n            return Become(Valuable(std::move(vals)));\r\n        }\r\n        else if (v.IsExponentiation())\r\n        {\r\n            auto& e = v.as<Exponentiation>();\r\n            if(ebase() == e.ebase() && (ebase().IsVa() || !ebase().IsMultival()))\r\n            {\r\n                eexp() -= e.eexp();\r\n            }\r\n            else\r\n            {\r\n                Become(Fraction(*this, v));\r\n                return *this;\r\n            }\r\n        }\r\n        else if(v.IsFraction())\r\n        {\r\n            *this *= v.as<Fraction>().Reciprocal();\r\n            return *this;\r\n        }\r\n        else if(ebase() == v)\r\n        {\r\n            --eexp();\r\n        }\r\n        else\r\n        {\r\n            Become(Fraction(*this, v));\r\n            return *this;\r\n        }\r\n\r\n        optimized={};\r\n        optimize();\r\n        return *this;\r\n    }\r\n\r\n    Valuable& Exponentiation::operator^=(const Valuable& v)\r\n    {\r\n        eexp() *= v;\r\n        optimized={};\r\n        optimize();\r\n        return *this;\r\n    }\r\n    \r\n    bool Exponentiation::operator ==(const Valuable& v) const\r\n    {\r\n        auto eq = v.IsExponentiation() && Hash()==v.Hash();\r\n        if(eq){\r\n            auto& e = v.as<Exponentiation>();\r\n            eq = _1.Hash() == e._1.Hash()\r\n                && _2.Hash() == e._2.Hash()\r\n                && _1 == e._1\r\n                && _2 == e._2;\r\n        } else if (v.IsFraction()) {\r\n            eq = eexp().IsInt()\r\n                 && eexp() < 0\r\n                 && ebase() == (v.as<Fraction>().getDenominator() ^ (-eexp()));\r\n        }\r\n        return eq;\r\n    }\r\n    \r\n    Exponentiation::operator double() const\r\n    {\r\n        return std::pow(static_cast<double>(ebase()), static_cast<double>(eexp()));\r\n    }\r\n\r\n    Valuable& Exponentiation::d(const Variable& x)\r\n    {\r\n        optimized={};\r\n        bool bhx = ebase().HasVa(x);\r\n        bool ehx = eexp().HasVa(x);\r\n        if(ehx) {\r\n            IMPLEMENT\r\n            if(bhx){\r\n                \r\n            }else{\r\n                \r\n            }\r\n        } else if (bhx) {\r\n            if(ebase() == x)\r\n                Become(eexp() * (ebase() ^ (eexp()-1)));\r\n            else\r\n                IMPLEMENT\r\n        } else\r\n            Become(0_v);\r\n        optimize();\r\n        return *this;\r\n    }\r\n    \r\n    void Exponentiation::integral(const Variable& x, const Variable& C)\r\n    {\r\n        if ((eexp().IsInt() || eexp().IsSimpleFraction()) && ebase()==x) {\r\n            ++eexp();\r\n            operator/=(eexp());\r\n            operator+=(C);\r\n        } else {\r\n            IMPLEMENT\r\n        }\r\n        \r\n        optimize();\r\n    }\r\n\r\n    bool Exponentiation::operator <(const Valuable& v) const\r\n    {\r\n        if (v.IsExponentiation())\r\n        {\r\n            auto& e = v.as<Exponentiation>();\r\n            if (e.getBase() == getBase())\r\n                return getExponentiation() < e.getExponentiation();\r\n            if (e.getExponentiation() == getExponentiation())\r\n                return getBase() < e.getBase();\r\n        }\r\n        \r\n        return base::operator <(v);\r\n    }\r\n\r\n    std::ostream& Exponentiation::print_sign(std::ostream& out) const\r\n    {\r\n        return out << \"^\";\r\n    }\r\n\r\n    Valuable::YesNoMaybe Exponentiation::IsMultival() const\r\n    {\r\n        auto is = _1.IsMultival() || _2.IsMultival();\r\n        if (is != YesNoMaybe::Yes && _2.IsFraction())\r\n            is = _2.as<Fraction>().getDenominator().IsEven() || is;\r\n        return is;\r\n    }\r\n    \r\n    void Exponentiation::Values(const std::function<bool(const Valuable&)>& fun) const\r\n    {\r\n        if (fun) {\r\n            auto cache = optimized; // TODO: multival caching (inspect all optimized and optimization transisions) auto isCached =\r\n            \r\n            std::set<Valuable> vals;\r\n            {\r\n            std::deque<Valuable> d1;\r\n            _1.Values([&](auto& v){\r\n                d1.push_back(v);\r\n                return true;\r\n            });\r\n            \r\n            _2.Values([&](auto& v){\r\n                auto vIsFrac = v.IsFraction();\r\n                const Fraction* f;\r\n                if(vIsFrac)\r\n                    f = &v.template as<Fraction>();\r\n                auto vMakesMultival = vIsFrac && f->getDenominator().IsEven()==YesNoMaybe::Yes;\r\n                \r\n                for(auto& item1:d1){\r\n                    if(vMakesMultival){\r\n                        static const Variable x;\r\n                        auto& dn = f->getDenominator();\r\n                        auto solutions = (x ^ dn).Equals(*this ^ dn).Solutions(x);\r\n                        for(auto&& s:solutions)\r\n                            vals.insert(s);\r\n                    } else {\r\n                        auto value=item1^v;\r\n                        if(value.IsMultival()==YesNoMaybe::No)\r\n                            vals.insert(value);\r\n                        else {\r\n                            IMPLEMENT\r\n                        }\r\n                    }\r\n                }\r\n                return true;\r\n            });\r\n            }\r\n            \r\n            for(auto& v:vals)\r\n                fun(v);\r\n        }\r\n    }\r\n\r\n    std::ostream& Exponentiation::code(std::ostream& out) const\r\n    {\r\n        if(!getExponentiation().IsInt())\r\n            IMPLEMENT;\r\n\r\n        out << \"(1\";\r\n        for (auto i=getExponentiation(); i-->0;) {\r\n            out << '*' << getBase();\r\n        }\r\n        out << ')';\r\n        \r\n        return out;\r\n    }\r\n    \r\n    bool Exponentiation::IsComesBefore(const Valuable& v) const\r\n    {\r\n        auto mve = getMaxVaExp();\r\n        auto vmve = v.getMaxVaExp();\r\n        auto is = mve > vmve;\r\n        if (mve != vmve)\r\n        {}\r\n        else if (v.IsExponentiation())\r\n        {\r\n            auto& e = v.as<Exponentiation>();\r\n            bool baseIsVa = getBase().IsVa();\r\n            bool vbaseIsVa = e.getBase().IsVa();\r\n            if (baseIsVa && vbaseIsVa)\r\n                is = getExponentiation() == e.getExponentiation() ? getBase().IsComesBefore(e.getBase()) : getExponentiation() > e.getExponentiation();\r\n            else if(baseIsVa)\r\n                is = false;\r\n            else if(vbaseIsVa)\r\n                is = true;\r\n            else if(getBase() == e.ebase())\r\n                is = getExponentiation().IsComesBefore(e.getExponentiation());\r\n            else if(getExponentiation() == e.getExponentiation())\r\n                is = getBase().IsComesBefore(e.getBase());\r\n            else\r\n            {\r\n                auto c = Complexity();\r\n                auto ec = e.Complexity();\r\n                if (c != ec)\r\n                    is = c > ec;\r\n                else {\r\n                    is = getBase().IsComesBefore(e.getBase()) || \r\n                        (!e.ebase().IsComesBefore(ebase()) && getExponentiation().IsComesBefore(e.getExponentiation())); //  || str().length() > e->str().length();\r\n    //                auto expComesBefore = eexp().IsComesBefore(e->eexp());\r\n    //                auto ebase()ComesBefore = ebase().IsComesBefore(e->ebase());\r\n    //                is = expComesBefore==ebase()ComesBefore || str().length() > e->str().length();\r\n                }\r\n            }\r\n        }\r\n        else if(v.IsProduct())\r\n        {\r\n            is = !(v.IsComesBefore(*this) || operator==(v));\r\n        }\r\n        else if(v.IsInt())\r\n            is = true;\r\n//        else if(v.IsFraction())\r\n//        {is=}\r\n        else if(v.IsVa())\r\n            is = !!FindVa();\r\n        else if(v.IsSum())\r\n            is = IsComesBefore(*v.as<Sum>().begin());\r\n        else\r\n            IMPLEMENT\r\n\r\n        return is;\r\n    }\r\n    \r\n    Valuable Exponentiation::calcFreeMember() const\r\n    {\r\n        Valuable c;\r\n        if(getBase().IsSum() && getExponentiation().IsInt()){\r\n            c = getBase().calcFreeMember() ^ getExponentiation();\r\n        } else if(getBase().IsVa()) {\r\n            c = 0_v;\r\n        } else\r\n            IMPLEMENT;\r\n        return c;\r\n    }\r\n\r\n    Valuable & Exponentiation::sq()\r\n    {\r\n        eexp() *= 2;\r\n        optimized = {};\r\n        optimize();\r\n        return *this;\r\n    }\r\n\r\n    const Valuable::vars_cont_t& Exponentiation::getCommonVars() const\r\n    {\r\n#ifndef NDEBUG\r\n        auto& b = ebase();\r\n        if (b.IsVa()) { // TODO: FindVa too\r\n            auto va = b.as<Variable>();\r\n            auto it = v.find(va);\r\n            if (it != v.end() && !it->second.Same(eexp()))\r\n                LOG_AND_IMPLEMENT(*this << \" Exponentiation::getCommonVars not ready\");\r\n        }\r\n#endif\r\n        return v;\r\n    }\r\n    \r\n    Valuable Exponentiation::InCommonWith(const Valuable& v) const\r\n    {\r\n        auto c = 1_v;\r\n        if (v.IsProduct()) {\r\n            for(auto& m: v.as<Product>()){\r\n                c = InCommonWith(m);\r\n                if (c != 1_v) {\r\n                    break;\r\n                }\r\n            }\r\n        } else if (v.IsExponentiation()) {\r\n            auto& e = v.as<Exponentiation>();\r\n            if (e.getBase() == getBase()) {\r\n                if (e.getExponentiation() == getExponentiation()) {\r\n                    c = e;\r\n                } else if (getExponentiation().IsSimple() && e.getExponentiation().IsSimple()) {\r\n                    if (getExponentiation() > 0 || e.getExponentiation() > 0) {\r\n                        if (e.getExponentiation() >= getExponentiation()) {\r\n                            c = *this;\r\n                        } else\r\n                            c = e;\r\n                    } else if (getExponentiation() < 0 || e.getExponentiation() < 0) {\r\n                        if (e.getExponentiation() >= getExponentiation()) {\r\n                            c = e;\r\n                        } else\r\n                            c = *this;\r\n                    } else {\r\n                        IMPLEMENT\r\n                    }\r\n                } else if (getExponentiation().IsSimpleFraction() && e.getExponentiation().IsSimpleFraction()) {\r\n                    if (getExponentiation()<0 == e.getExponentiation()<0) {\r\n                        c = getBase() ^ getExponentiation().InCommonWith(e.getExponentiation());\r\n                    }\r\n                } else if (getExponentiation().IsSum()) {\r\n                    auto sz = getExponentiation().as<Sum>().size();\r\n                    auto diff = getExponentiation() - e.getExponentiation();\r\n                    if (!diff.IsSum() || diff.as<Sum>().size() < sz)\r\n                        c = v;\r\n                } else if (e.getExponentiation().IsSum()) {\r\n                    c = e.InCommonWith(*this);\r\n                } else if (e.getExponentiation().IsProduct()) {\r\n                    c = ebase() ^ e.eexp().InCommonWith(eexp());\r\n                } else {\r\n                    IMPLEMENT\r\n                }\r\n            }\r\n        } else if (getExponentiation().IsInt()) {\r\n            if(getExponentiation() > 0)\r\n                c = getBase().InCommonWith(v);\r\n        } else if (getExponentiation().IsFraction()) {\r\n        } else if (v.IsVa()) {\r\n            c = v.InCommonWith(*this);\r\n        } else if (v.IsInt() || v.IsSimpleFraction()) {\r\n        } else if (getExponentiation().IsVa()) {\r\n        } else {\r\n            IMPLEMENT\r\n        }\r\n        return c;\r\n    }\r\n    \r\n    Valuable Exponentiation::operator()(const Variable& va) const\r\n    {\r\n        return operator()(va, 0_v);\r\n    }\r\n\r\n    Valuable Exponentiation::operator()(const Variable& v, const Valuable& augmentation) const\r\n    {\r\n        if (!getExponentiation().FindVa() && getExponentiation()!=0 && augmentation==0) {\r\n            return getBase()(v,augmentation);\r\n        } else if (getExponentiation().IsSimpleFraction()) {\r\n            auto& f = getExponentiation().as<Fraction>();\r\n            return (getBase()^f.getNumerator())(v,augmentation^f.getDenominator());\r\n        } else {\r\n            IMPLEMENT\r\n        }\r\n    }\r\n\r\n    Valuable::solutions_t Exponentiation::Distinct() const\r\n    {\r\n        solutions_t branches;\r\n        if (eexp().IsSimpleFraction()){\r\n            auto& f = eexp().as<Fraction>();\r\n            auto& denom = f.denominator();\r\n            if (denom.IsEven() == YesNoMaybe::Yes) {\r\n                // TODO : de-recoursefy:\r\n//                auto branchesSz = boost::multiprecision::msb(denom); // the largest bit\r\n//                branches.reserve(branchesSz);\r\n//                ...\r\n                auto& exponentiationBase = ebase();\r\n                if(!exponentiationBase.IsSimple()){\r\n                    if (!exponentiationBase.FindVa() && exponentiationBase.IsMultival() == YesNoMaybe::Yes) {\r\n                        for (auto&& branch : ebase().Distinct()) {\r\n                            auto branchDistinct = (branch ^ eexp()).Distinct();\r\n                            branches.insert(branchDistinct.begin(), branchDistinct.end());\r\n                        }\r\n                    } else {\r\n                        LOG_AND_IMPLEMENT(\"Distinct for \" << *this);\r\n                    }\r\n                } else {\r\n                    auto b = ebase() ^ f.numerator();\r\n                    auto d = denom;\r\n                    do {\r\n                        b.sqrt();\r\n                        d.shr();\r\n                    } while(d.IsEven() == Valuable::YesNoMaybe::Yes);\r\n                    auto _ = b ^ (1_v / d);\r\n                    auto distinct = _.Distinct();\r\n                    if(denom==2)\r\n                        for (auto& branch : distinct)\r\n                        {\r\n                            branches.emplace(-branch);\r\n                            branches.emplace(std::move(const_cast<decltype(distinct)::reference>(branch)));\r\n                        }\r\n                    else if(denom==4)\r\n                        for (auto& branch : distinct)\r\n                        {\r\n                            branches.emplace(-branch * constants::i);\r\n                            branches.emplace(branch * constants::i);\r\n                            branches.emplace(-branch);\r\n                            branches.emplace(std::move(const_cast<decltype(distinct)::reference>(branch)));\r\n                        }\r\n                    else\r\n                        LOG_AND_IMPLEMENT(\"Implement support for \" << denom << \" dimmensions\");\r\n                }\r\n            }\r\n        } else {\r\n            branches.emplace(*this);\r\n        }\r\n        return branches;\r\n    }\r\n}}\r\n", "meta": {"hexsha": "d56ebae6c02c7a1ca28dde824d7b3cbf6bbfa0a2", "size": 39349, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "omnn/math/Exponentiation.cpp", "max_stars_repo_name": "iHateInventNames/openmind", "max_stars_repo_head_hexsha": "2587b811e594daf9d9c235cb63eeae2950e93ff0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "omnn/math/Exponentiation.cpp", "max_issues_repo_name": "iHateInventNames/openmind", "max_issues_repo_head_hexsha": "2587b811e594daf9d9c235cb63eeae2950e93ff0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2016-05-21T08:48:41.000Z", "max_issues_repo_issues_event_max_datetime": "2017-02-22T19:37:03.000Z", "max_forks_repo_path": "omnn/math/Exponentiation.cpp", "max_forks_repo_name": "iHateInventNames/openmind", "max_forks_repo_head_hexsha": "2587b811e594daf9d9c235cb63eeae2950e93ff0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.164432529, "max_line_length": 164, "alphanum_fraction": 0.3858039594, "num_tokens": 8420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.46734174114667076}}
{"text": "#include <iostream>\n#include <algorithm>\n#include <cmath>\n#include <vector>\n#include <map>\n#include <set>\n#include <tuple>\n#include <stdbool.h>\n#include <bitset>\n#include <string>\n#include <boost/multiprecision/cpp_int.hpp>\n\nnamespace mp = boost::multiprecision;\nusing namespace std;\n\nint main(void) {\n    mp::cpp_int n, m;\n    cin >> n; // \u5e97\u306e\u4ef6\u6570\n    cin >> m; // \u30c9\u30ea\u30f3\u30af\u672c\u6570\n    map<mp::cpp_int,mp::cpp_int> drinks; // price -> counts\n\n    for(mp::cpp_int i = 0 ; i < n ; ++i) {\n        mp::cpp_int  a, b;\n        cin >> a;\n        cin >> b;\n        drinks[a] = b;\n    }\n    // count\u304c\u6b8b\u308a\u672c\u6570, sum=\u5408\u8a08\u91d1\u984d\n    mp::cpp_int count = m;\n    mp::cpp_int sum = 0;\n    for(const auto& d: drinks) {\n        if(d.second < count) {\n            // \u8cb7\u3044\u5360\u3081\n            count -= d.second;\n            sum += d.first * d.second;\n        } else {\n            sum += d.first * count;\n            count = 0;\n            break;\n        }\n    }\n    cout << sum.str() << endl;\n    return 0;\n}", "meta": {"hexsha": "1c0c842e1b8cc173fb25aca5729f32922d1d31d1", "size": 957, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "abc121/c/main.cpp", "max_stars_repo_name": "kamiyaowl/atcoder", "max_stars_repo_head_hexsha": "30521be1684e72e75c7ba21312c5f96ae81bf25a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "abc121/c/main.cpp", "max_issues_repo_name": "kamiyaowl/atcoder", "max_issues_repo_head_hexsha": "30521be1684e72e75c7ba21312c5f96ae81bf25a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-20T11:51:59.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-20T11:51:59.000Z", "max_forks_repo_path": "abc121/c/main.cpp", "max_forks_repo_name": "kamiyaowl/atcoder", "max_forks_repo_head_hexsha": "30521be1684e72e75c7ba21312c5f96ae81bf25a", "max_forks_repo_licenses": ["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.75, "max_line_length": 59, "alphanum_fraction": 0.5161964472, "num_tokens": 291, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4673417347142304}}
{"text": "#include <fstream>\n#include <string>\n#include <math.h>\n#include <time.h>\n#include \"model.h\"\n#include <stdlib.h>\n#include <armadillo>\n#include \"model_fancy.h\"\n\nusing namespace arma;\n\nint initStateFile(char *file)\n{\n        std::ofstream out(file,std::ios_base::trunc);\n\n        if (!out)\n        {\n            perror(\"output file error\\n\");\n                return -1;\n        }\n\n        out.close();\n\n        return 0;\n}\n\n\nvoid addState(char *file, fmat u)\n{\n        std::ofstream out(file,std::ios_base::app);\n        for(unsigned int i=0; i < u.n_rows; ++i){\n                out << u[i] << \" \";\n        }\n        out << std::endl;\n        out.close();\n}\n\n\nint main (int argc, char* argv[]){\n        int num = 0;\n        if (argc<3){\n                perror(\"Error\");\n                printf(\"Please call program like:\\n\");\n                printf(\"./datagen filename_original filename_measurement numberOfStates\\n\");\n                return -1;\n        }\n        char *file_original = argv[1];\n        char *file_out = argv[2];\n        num = atoi(argv[3]);\n\n        Model *process = new ModelFancy();\n        process->initialize();\n\n        printf(\"Dimension of state: %d\\n\",process->getProcessDimension());\n\n        fmat state(process->getProcessDimension(),1);\n\n        fmat measurement(process->getMeasurementDimension(),1);\n       \n        state.zeros();\n\n        initStateFile(file_out);\t// initialize output file\n        initStateFile(file_original);\n\n        addState(file_out, state);\n\n\n        for (int k=0; k<num;k++)\n        {\n            state = process->ffun(&state);\n            printf(\"x: %e  y: %e\\n\",state(0),state(1));\n            addState(file_original,state);\n            measurement = process->hfun(&state);\n            printf(\"x: %e  y: %e\\n\\n\",measurement(0),measurement(1));\n            addState(file_out, measurement);\n        }\n\n        printf(\"Done!\");\n\n        return 0;\n}\n\n", "meta": {"hexsha": "0a7eb9877566224f094dc49d4dad1dfcca49ae42", "size": 1899, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/data_generators/model_fancy/dataGenerator_fancy.cpp", "max_stars_repo_name": "chingoduc/parallel-bayesian-toolbox", "max_stars_repo_head_hexsha": "20c06a823c714a51a51e5b59c3232cd1260b0fa4", "max_stars_repo_licenses": ["BSD-4-Clause-UC"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-12-01T13:15:14.000Z", "max_stars_repo_stars_event_max_datetime": "2015-12-01T13:15:14.000Z", "max_issues_repo_path": "src/data_generators/model_fancy/dataGenerator_fancy.cpp", "max_issues_repo_name": "chingoduc/parallel-bayesian-toolbox", "max_issues_repo_head_hexsha": "20c06a823c714a51a51e5b59c3232cd1260b0fa4", "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/data_generators/model_fancy/dataGenerator_fancy.cpp", "max_forks_repo_name": "chingoduc/parallel-bayesian-toolbox", "max_forks_repo_head_hexsha": "20c06a823c714a51a51e5b59c3232cd1260b0fa4", "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": 22.8795180723, "max_line_length": 92, "alphanum_fraction": 0.5281727225, "num_tokens": 445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4673417347142304}}
{"text": "/*!\n * Copyright (C) tkornuta, IBM Corporation 2015-2019\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: MatrixTests.cpp\n * @Author: Tomasz Kornuta <tkornut@us.ibm.com>\n * @Date:   Nov 22, 2016\n *\n * Copyright (c) 2016, IBM Corporation. All rights reserved.\n *\n */\n\n#include <gtest/gtest.h>\n\n#include <fstream>\n// Include headers that implement a archive in simple text format\n#include <boost/archive/text_iarchive.hpp>\n#include <boost/archive/text_oarchive.hpp>\n\n// Redefine word \"public\" so every class field/method will be accessible for tests.\n#define private public\n#include <types/Matrix.hpp>\n\n/*!\n * Tests whether matrix has proper dimensions (2x5).\n */\nTEST(Matrix, Dimensions2x5) {\n\t// Default sizes of matrices.\n\tconst size_t N = 2;\n\tconst size_t M = 5;\n\n\tmic::types::Matrix<float> nm(N, M);\n\n\tASSERT_EQ(nm.rows(), N);\n\tASSERT_EQ(nm.cols(), M);\n\n}\n\n\n/*!\n * Tests matrix serialization.\n */\nTEST(Matrix, Serialization) {\n\t// Default sizes of matrices.\n\tconst size_t N = 2;\n\tconst size_t M = 5;\n\n\tmic::types::Matrix<float> nm(N, M);\n\tnm.randn();\n\n\tconst char* fileName = \"saved.txt\";\n\t// Save data\n\t{\n\t\t// Create an output archive\n\t\tstd::ofstream ofs(fileName);\n\t\tboost::archive::text_oarchive ar(ofs);\n\t\t// Write data\n\t\tar & nm;\n//\t\tstd::cout << \"Saved matrix = \" << nm << std::endl;\n\t}\n\n\t// Restore data\n\tmic::types::Matrix<float> restored_mat;\n\trestored_mat.randn();\n\n\t{\n\t\t// Create and input archive\n\t\tstd::ifstream ifs(fileName);\n\t\tboost::archive::text_iarchive ar(ifs);\n\t\t// Load data\n\t\tar & restored_mat;\n//\t\tstd::cout << \"Restored matrix = \" << restored_mat << std::endl;\n\t}\n\n\tfor (size_t i =0; i< (size_t)nm.size(); i++)\n\t\tASSERT_EQ(nm(i), restored_mat(i));\n\n}\n\n/*!\n * Tests assignment operator.\n */\nTEST(Matrix, OperatorAssignmentFloat) {\n\t// Default sizes of matrices.\n\tconst size_t N = 2;\n\tconst size_t M = 5;\n\n\tmic::types::Matrix<float> nm(N, M);\n\tfor (size_t i= 0; i<N; i++)\n\t\tfor (size_t j= 0; j<M; j++)\n\t\t\tnm(i,j) = i*j;\n\t\n\n\tmic::types::Matrix<float> nm2 = nm;\n\tfor (size_t i= 0; i<N; i++)\n\t\tfor (size_t j= 0; j<M; j++)\n\t\t\tASSERT_EQ(nm2(i,j), i*j);\n\n}\n\n\n/*!\n * Tests enumeration.\n */\nTEST(Matrix, Enumeration2x3) {\n\t// Default sizes of matrices.\n\tconst size_t N = 2;\n\tconst size_t M = 3;\n\n\tmic::types::Matrix<float> nm(N, M);\n\tnm.enumerate();\n\n\tfor (size_t i =0; i< N*M; i++)\n\t\tASSERT_EQ(nm(i), i);\n\n\t/*for(size_t row=0; row<N; row++) {\n\t\tfor(size_t col=0; col<M; col++)\n\t\t\tstd::cout << \" nm(\" << row << \",\" << col << \") = \" << nm(row,col);\n\t\tstd::cout << std::endl;\n\t}//: for*/\n\n\tASSERT_EQ(nm(0,0), 0);\n\tASSERT_EQ(nm(0,1), 2);\n\tASSERT_EQ(nm(0,2), 4);\n\tASSERT_EQ(nm(1,0), 1);\n\tASSERT_EQ(nm(1,1), 3);\n\tASSERT_EQ(nm(1,2), 5);\n\n\tnm.resize(M,N);\n\n\t/*for(size_t row=0; row<M; row++) {\n\t\tfor(size_t col=0; col<N; col++)\n\t\t\tstd::cout << \" nm(\" << row << \",\" << col << \") = \" << nm(row,col);\n\t\tstd::cout << std::endl;\n\t}//: for*/\n\n}\n\n\n\n\n/*!\n * Tests functions added to make Eigen-derived Matrix as much compatible to Armadillo-derived Matrix as possible.\n */\nTEST(Matrix, ArmadilloCompatibilityTest) {\n\t// Default sizes of matrices.\n\tconst size_t N = 4;\n\tconst size_t M = 5;\n\n\tmic::types::Matrix<float> nm(N, M);\n\tnm.zeros();\n\n\tfor (size_t i =0; i< N*M; i++)\n\t\tASSERT_EQ(nm[i], 0);\n}\n\n\nint main(int argc, char **argv) {\n    testing::InitGoogleTest(&argc, argv);\n    return RUN_ALL_TESTS();\n}\n\n\n", "meta": {"hexsha": "f95852b0c1f3a989e7920e9178d951aaa5e6eec5", "size": 3838, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/types/MatrixTests.cpp", "max_stars_repo_name": "kant/mi-algorithms", "max_stars_repo_head_hexsha": "7e510577f57cb5e7d36c9d2506b61395739b0bef", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/types/MatrixTests.cpp", "max_issues_repo_name": "kant/mi-algorithms", "max_issues_repo_head_hexsha": "7e510577f57cb5e7d36c9d2506b61395739b0bef", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/types/MatrixTests.cpp", "max_forks_repo_name": "kant/mi-algorithms", "max_forks_repo_head_hexsha": "7e510577f57cb5e7d36c9d2506b61395739b0bef", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-30T09:51:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-30T09:51:14.000Z", "avg_line_length": 21.8068181818, "max_line_length": 113, "alphanum_fraction": 0.6370505472, "num_tokens": 1150, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.46734173149801017}}
{"text": "#include <iostream>\n#include <memory>\n#include <string>\n#include <vector>\n#include <algorithm>\n#include <unordered_map>\n#include <functional>\n#include <Eigen/Dense>\n#include \"../include/model.h\"\n#include \"../include/numerical_gradient.h\"\n\nnamespace MyDL\n{\n\n    using namespace Eigen;\n    using std::cout;\n    using std::endl;\n    using std::make_shared;\n    using std::shared_ptr;\n    using std::string;\n    using std::unordered_map;\n    using std::vector;\n\n    TwoLayerMLP::TwoLayerMLP(int input_size, int hidden_size, int output_size, double weight_init_std)\n    {\n        // \u5185\u90e8\u4fdd\u6301\u30d1\u30e9\u30e1\u30fc\u30bf\n        _input_size = input_size;\n        _hidden_size = hidden_size;\n        _output_size = output_size;\n        _weight_init_std = weight_init_std;\n\n        // Affine Layer\u7528\u306e\u30d1\u30e9\u30e1\u30fc\u30bf -> \u30b9\u30de\u30fc\u30c8\u30dd\u30a4\u30f3\u30bf\u3067\u4fdd\u6301\u3057\u3001\u305d\u308c\u3092\u30d1\u30e9\u30e1\u30fc\u30bf\u306e\u30ea\u30b9\u30c8\u306b\u683c\u7d0d\n        auto W1 = make_shared<MatrixXd>(input_size, hidden_size);\n        auto W2 = make_shared<MatrixXd>(hidden_size, output_size);\n        auto b1 = make_shared<MatrixXd>(1, hidden_size);\n        auto b2 = make_shared<MatrixXd>(1, output_size);\n\n        *W1 = weight_init_std * MatrixXd::Random(input_size, hidden_size);\n        *W2 = weight_init_std * MatrixXd::Random(hidden_size, output_size);\n        *b1 = MatrixXd::Zero(1, hidden_size);\n        *b2 = MatrixXd::Zero(1, output_size);\n\n        // Layer\u4f5c\u6210 -> \u30b9\u30de\u30fc\u30c8\u30dd\u30a4\u30f3\u30bf\u3067\u5b9f\u88c5(\u30b3\u30f3\u30b9\u30c8\u30e9\u30af\u30bf\u3092\u629c\u3051\u305f\u6642\u306b\u3001\u5b9f\u4f53\u304c\u6d88\u3055\u308c\u306a\u3044\u3088\u3046\u306b\u3059\u308b\u305f\u3081)\n        // \u5de6\u8fba\u306e\u578b\u306fauto\u306b\u3057\u3066\u306f\u3044\u3051\u306a\u3044(BaseLayer\u3067\u7d71\u4e00\u3057\u3001\u30b3\u30f3\u30c6\u30ca\u306b\u683c\u7d0d\u3059\u308b \u203b\u30dd\u30ea\u30e2\u30fc\u30d5\u30a3\u30ba\u30e0\u306e\u5b9f\u73fe)\n        shared_ptr<BaseLayer> affine1 = make_shared<MyDL::Affine>(W1, b1);\n        shared_ptr<BaseLayer> affine2 = make_shared<MyDL::Affine>(W2, b2);\n        shared_ptr<BaseLayer> relu1 = make_shared<ReLU>();\n        shared_ptr<BaseLayer> last_layer = make_shared<SoftmaxWithLoss>(); // predict\u3067\u306faffine2\u306e\u51fa\u529b\u3001loss\u3067\u306flastlayer\u306e\u51fa\u529b\u3092\u4f7f\u3046\u306e\u3067\u5206\u3051\u308b\n\n        // \u751f\u306e\u30dd\u30a4\u30f3\u30bf\u3092\u683c\u7d0d\u3059\u308b\u3068\u5b9f\u4f53\u304c\u30b9\u30b3\u30fc\u30d7\u5916\u3068\u306a\u308a\u89e3\u653e\u3055\u308c\u3066\u3057\u307e\u3046\u306e\u3067\u3001shared_ptr\u3067\u5bfe\u51e6\n        _layers[\"Affine1\"] = affine1;\n        _layers[\"ReLU1\"] = relu1;\n        _layers[\"Affine2\"] = affine2;\n        _last_layer = last_layer;\n\n        // \u5404\u30d1\u30e9\u30e1\u30fc\u30bf\u3078\u306e\u30dd\u30a4\u30f3\u30bf\u3092\u683c\u7d0d\n        if (auto cast_affine1 = std::dynamic_pointer_cast<MyDL::Affine>(_layers[\"Affine1\"]))\n        {\n            params[\"W1\"] = cast_affine1->pW;\n            params[\"b1\"] = cast_affine1->pb;\n        }\n        if (auto cast_affine2 = std::dynamic_pointer_cast<MyDL::Affine>(_layers[\"Affine2\"]))\n        {\n            params[\"W2\"] = cast_affine2->pW;\n            params[\"b2\"] = cast_affine2->pb;\n        }\n\n        // unordered_map\u3067\u306f\u8ffd\u52a0\u9806\u304c\u4fdd\u5b58\u3055\u308c\u306a\u3044\u306e\u3067\u3001\u5225\u9014\u9806\u756a\u901a\u308a\u540d\u79f0\u3092\u683c\u7d0d\u3057\u305f\u30b3\u30f3\u30c6\u30ca\u3092\u7528\u610f\n        _layer_list.push_back(\"Affine1\");\n        // _layer_list.push_back(\"BatchNorm\"); // for batchnorm debug 21/03/21\u8ffd\u52a0\n        _layer_list.push_back(\"ReLU1\");\n        _layer_list.push_back(\"Affine2\");\n\n        // ------------------------------------------------\n        // for batchnorm debug 21/03/21\u8ffd\u52a0\n        // ------------------------------------------------\n        // auto gamma = make_shared<MatrixXd>(1, hidden_size);\n        // auto beta = make_shared<MatrixXd>(1, hidden_size);\n        // *gamma = weight_init_std * MatrixXd::Random(1, hidden_size);\n        // *beta = MatrixXd::Zero(1, hidden_size);\n        // shared_ptr<BaseLayer> batch_norm = make_shared<BatchNorm>(gamma, beta);\n        // _layers[\"BatchNorm\"] = batch_norm;\n        // if (auto cast_batchnorm = std::dynamic_pointer_cast<BatchNorm>(_layers[\"BatchNorm\"]))\n        // {\n        //     params[\"gamma\"] = cast_batchnorm->pgamma;\n        //     params[\"beta\"] = cast_batchnorm->pbeta;\n        // }\n    }\n\n    vector<MatrixXd> TwoLayerMLP::predict(vector<MatrixXd> inputs)\n    {\n        // input\u306e\u30d0\u30ea\u30c7\u30fc\u30b7\u30e7\u30f3\u3092\u3057\u3066\u304a\u304f\u304b\uff1f\n        vector<MatrixXd> X = inputs; // \u5165\u529b\u3082vector\u306a\u306e\u3067\u3001\u305d\u306e\u307e\u307e\u53d7\u3051\u308c\u3070OK\n        vector<MatrixXd> tmp_X;\n\n        // map\u306erange-for\u306f\u5185\u90e8\u7684\u306bstd::pair\u304c\u8fd4\u3055\u308c\u308b\n        for (auto layer : _layer_list)\n        {\n            // cout << layer << endl;\n            tmp_X = _layers[layer]->forward(X);\n            X.swap(tmp_X); // \u4e2d\u8eab\u5165\u308c\u66ff\u3048\n        }\n        return X;\n    }\n\n    vector<MatrixXd> TwoLayerMLP::loss(vector<MatrixXd> inputs, MatrixXd& t)\n    {\n        vector<MatrixXd> pred_input, pred_out, loss_inputs, loss_output;\n        pred_input.push_back(inputs[0]);\n        pred_out = predict(pred_input);\n\n        loss_inputs.push_back(pred_out[0]);\n        loss_inputs.push_back(t);\n\n        loss_output = _last_layer->forward(loss_inputs);\n        return loss_output;\n    }\n\n    double TwoLayerMLP::accuracy(vector<MatrixXd> inputs, MatrixXd& t)\n    {\n        vector<MatrixXd> pred_out;\n        pred_out = predict(inputs);\n\n        MatrixXd y;\n        y = pred_out[0];\n        double batch_size = t.rows();\n        double accuracy = 0;\n\n        MatrixXd::Index y_row, y_col, t_row, t_col;\n        for (int i = 0; i < batch_size; i++)\n        {\n            y.row(i).maxCoeff(&y_row, &y_col);\n            t.row(i).maxCoeff(&t_row, &t_col);\n\n            accuracy += (double)(y_col == t_col);\n        }\n\n        return accuracy / batch_size;\n    }\n\n    unordered_map<string, MatrixXd> TwoLayerMLP::gradient(vector<MatrixXd> inputs, MatrixXd& t)\n    {\n        // Forward\n        vector<MatrixXd> output;\n        output = loss(inputs, t); // forward -> \u9006\u4f1d\u64ad\u8a08\u7b97\u306b\u5fc5\u8981\u306a\u60c5\u5831\u3092\u5404\u30ec\u30a4\u30e4\u306b\u30ad\u30e3\u30c3\u30b7\u30e5\n\n        // Backward\n        vector<MatrixXd> dout, tmp_dout;\n        dout.push_back(MatrixXd::Ones(1, 1));\n\n        dout = _last_layer->backward(dout);\n\n        // \u9006\u9806\u30eb\u30fc\u30d7 \u2192 Boost\u30e9\u30a4\u30d6\u30e9\u30ea\u306eboost::adaptors::reverse()\u3092\u4f7f\u3046\u65b9\u304cEasy\u3067\u306f\u3042\u308b\n        for (auto it = _layer_list.rbegin(); it != _layer_list.rend(); it++)\n        {\n            string layer = *it;\n            tmp_dout = _layers[layer]->backward(dout);\n            dout.swap(tmp_dout);\n        }\n\n        unordered_map<string, MatrixXd> grads;\n        // _layers\u306b\u683c\u7d0d\u3057\u3066\u3044\u308b\u5909\u6570\u306fBaseLayer\u306b\u30a2\u30c3\u30d7\u30ad\u30e3\u30b9\u30c8\u3057\u3066\u3044\u308b\u306e\u3067\u3001\u30c0\u30a6\u30f3\u30ad\u30e3\u30b9\u30c8\u304c\u5fc5\u8981 -> nullptr\u306e\u3068\u304d\u306f\u5b9f\u884c\u3057\u306a\u3044\u3088\u3046\u306b\u3059\u308b\n        if (shared_ptr<MyDL::Affine> affine1 = std::dynamic_pointer_cast<MyDL::Affine>(_layers[\"Affine1\"]))\n        {\n            grads[\"W1\"] = affine1->dW;\n            grads[\"b1\"] = affine1->db;\n        }\n        if (shared_ptr<MyDL::Affine> affine2 = std::dynamic_pointer_cast<MyDL::Affine>(_layers[\"Affine2\"]))\n        {\n            grads[\"W2\"] = affine2->dW;\n            grads[\"b2\"] = affine2->db;\n        }\n\n        // for batchnorm debug 21/03/21\u8ffd\u52a0\n        if (auto batchnorm = std::dynamic_pointer_cast<BatchNorm>(_layers[\"BatchNorm\"]))\n        {\n            grads[\"gamma\"] = batchnorm->dgamma;\n            grads[\"beta\"] = batchnorm->dbeta;\n        }\n\n        return grads;\n    }\n\n    // unordered_map<string, MatrixXd> TwoLayerMLP::numerical_gradient(vector<MatrixXd> inputs)\n    // {\n    //     // [&]\u306f\u3001\u30b9\u30b3\u30fc\u30d7\u5916\u306e\u5909\u6570\u3092\u53c2\u7167\u3059\u308b\u3068\u3044\u3046\u30ad\u30e3\u30d7\u30c1\u30e3\u30fc(\u3053\u3053\u3067\u306fthis\u30dd\u30a4\u30f3\u30bf\u3092\u4f7f\u3046\u305f\u3081\u306b\u6307\u5b9a)\n    //     std::function<vector<MatrixXd>(MatrixXd)> loss_W = [this, &inputs](MatrixXd W) -> vector<MatrixXd> { return this->loss(inputs); };\n    //     std::function<vector<MatrixXd>(VectorXd)> loss_W2 = [this, &inputs](VectorXd W) -> vector<MatrixXd> { return this->loss(inputs); };\n    //     unordered_map<string, MatrixXd> grads;\n\n    //     MatrixXd dW1, dW2, db1, db2;\n\n    //     // \u76f4\u63a5\u5185\u90e8\u306e\u30ec\u30a4\u30e4\u306e\u30d1\u30e9\u30e1\u30fc\u30bf\u306b\u30a2\u30af\u30bb\u30b9\u3059\u308b\u306e\u3067\u3001\u30c0\u30a6\u30f3\u30ad\u30e3\u30b9\u30c8\u304c\u5fc5\u8981\n    //     if (shared_ptr<MyDL::Affine> affine1 = std::dynamic_pointer_cast<MyDL::Affine>(_layers[\"Affine1\"]))\n    //     {\n    //         dW1 = MyDL::numerical_gradient(loss_W, affine1->_W);\n    //         db1 = MyDL::numerical_gradient(loss_W2, affine1->_b);\n    //     }\n    //     if (shared_ptr<MyDL::Affine> affine2 = std::dynamic_pointer_cast<MyDL::Affine>(_layers[\"Affine2\"]))\n    //     {\n    //         dW2 = MyDL::numerical_gradient(loss_W, affine2->_W);\n    //         db2 = MyDL::numerical_gradient(loss_W2, affine2->_b);\n    //     }\n\n    //     grads[\"dW1\"] = dW1;\n    //     grads[\"dW2\"] = dW2;\n    //     grads[\"db1\"] = db1;\n    //     grads[\"db2\"] = db2;\n\n    //     return grads;\n    // }\n\n    // -----------------------------------------------------------\n    // MultiLayerModel: Weight Decay \u306e\u691c\u8a3c\u7528\n    // \u301021/04/06\u3011\n    // \u3068\u308a\u3042\u3048\u305a\u52d5\u4f5c\u3059\u308b\u3053\u3068\u3092\u76ee\u6307\u3059\u306e\u3067\u3001\u6700\u521d\u306frelu\u3067\u69cb\u6210\n    // \u5f8c\u307b\u3069sigmoid\u542b\u3081\u3066\u52d5\u304f\u3088\u3046\u306b\u5909\u66f4\u3002\u521d\u671f\u5024\u3082 Xavier\u3068He\u306e\u4e21\u65b9\u3092\u9078\u629e\u3067\u304d\u308b\u3088\u3046\u306b\u3059\u308b\u3002\n    // -----------------------------------------------------------\n\n    MultiLayerModel::MultiLayerModel(const int input_size,\n                                     const vector<int> hidden_size,\n                                     const int output_size,\n                                     const double weight_decay_lambda,\n                                     string activation,\n                                     const string weight_initializer,\n                                     const bool use_dropout,\n                                     const double dropout_ratio,\n                                     const bool use_batchnorm)\n    {\n        _input_size = input_size;\n        _hidden_size_list = hidden_size;\n        _output_size = output_size;\n        _weight_decay_lambda = weight_decay_lambda;\n\n        _all_size_list.insert(_all_size_list.end(), {_input_size});\n        _all_size_list.insert(_all_size_list.end(), _hidden_size_list.begin(), _hidden_size_list.end());\n        _all_size_list.insert(_all_size_list.end(), {_output_size});\n\n        std::transform(activation.begin(), activation.end(), activation.begin(), ::tolower);\n\n        // Create Layers\n        for (int i = 1; i < _hidden_size_list.size()+1; i++)\n        {\n            string tmp_num_str = std::to_string(i);\n            _layers[\"Affine\" + tmp_num_str] = make_shared<MyDL::Affine>(_all_size_list[i-1], _all_size_list[i]);\n            _layer_list.push_back(\"Affine\" + tmp_num_str);\n\n            // BatchNormalization\n            if (use_batchnorm)\n            {\n                _layers[\"BatchNorm\" + tmp_num_str] = make_shared<BatchNorm>(_all_size_list[i], 0.9); // \u30d1\u30e9\u30e1\u30fc\u30bf\u3082\u6307\u5b9a\u3067\u304d\u308b\u3088\u3046\u306b\u3059\u308b\uff1f\n                _layer_list.push_back(\"BatchNorm\" + tmp_num_str);\n            }\n\n            // Activation\n            if (activation == \"relu\")\n            {\n                _layers[\"ReLU\" + tmp_num_str] = make_shared<ReLU>();\n                _layer_list.push_back(\"ReLU\" + tmp_num_str);\n            }\n            else if(activation == \"sigmoid\") \n            {\n                _layers[\"Sigmoid\" + tmp_num_str] = make_shared<Sigmoid>();\n                _layer_list.push_back(\"Sigmoid\" + tmp_num_str);\n            }\n\n            // Dropout\n            if (use_dropout)\n            {\n                _layers[\"Dropout\" + tmp_num_str] = make_shared<Dropout>(dropout_ratio);\n                _layer_list.push_back(\"Dropout\" + tmp_num_str);\n            }\n\n        }\n        int last_num = _hidden_size_list.size()+1;\n        string last_num_str = std::to_string(last_num);\n        _layers[\"Affine\" + last_num_str] = make_shared<MyDL::Affine>(_all_size_list[last_num-1], _all_size_list[last_num]);\n        _layer_list.push_back(\"Affine\" + last_num_str);\n\n        _last_layer = make_shared<SoftmaxWithLoss>(); // Loss Layer\n\n\n        // Get pointer to Layer Parameters\n        for (int layer_num = 1; layer_num < _all_size_list.size(); layer_num++)\n        {\n            if (auto cast_affine = std::dynamic_pointer_cast<MyDL::Affine>(_layers[\"Affine\" + std::to_string(layer_num)]))\n            {\n                params[\"W\" + std::to_string(layer_num)] = cast_affine->pW;\n                params[\"b\" + std::to_string(layer_num)] = cast_affine->pb;\n            }\n        }\n\n        // Affine Layer\u306e\u5909\u6570\u521d\u671f\u5316\n        this->_init_weight(weight_initializer);\n\n    }\n\n\n    void MultiLayerModel::_init_weight(string weight_initializer)\n    {\n        // weight_initializer\u306e\u6587\u5b57\u5217\u3092\u5c0f\u6587\u5b57\u306b\u5909\u63db\n        std::transform(weight_initializer.begin(),\n                       weight_initializer.end(),\n                       weight_initializer.begin(),\n                       ::tolower);\n        \n        double scale = 1;\n\n        if (weight_initializer == \"relu\" or weight_initializer == \"he\")\n        {\n            for (int layer_num = 1; layer_num <= _hidden_size_list.size()+1; layer_num++)\n            {\n                scale = sqrt(2.0 / _all_size_list[layer_num-1]);\n                *(params[\"W\" + std::to_string(layer_num)]) = scale * MatrixXd::Random(_all_size_list[layer_num-1], _all_size_list[layer_num]);        \n            }\n        }\n        else if (weight_initializer == \"sigmoid\" or weight_initializer == \"xavier\")\n        {\n            for (int layer_num = 1; layer_num <= _hidden_size_list.size() + 1; layer_num++)\n            {\n                scale = sqrt(1.0 / _all_size_list[layer_num - 1]);\n                *(params[\"W\" + std::to_string(layer_num)]) = scale * MatrixXd::Random(_all_size_list[layer_num - 1], _all_size_list[layer_num]);\n            }\n        }\n    }\n\n\n    vector<MatrixXd> MultiLayerModel::predict(vector<MatrixXd> inputs)\n    {\n        vector<MatrixXd> X = inputs;\n        vector<MatrixXd> tmp_X;\n\n        for (auto layer : _layer_list)\n        {\n            tmp_X = _layers[layer]->forward(X);\n            X.swap(tmp_X);\n        }\n        return X;\n    }\n\n    vector<MatrixXd> MultiLayerModel::loss(vector<MatrixXd> inputs, MatrixXd &t)\n    {\n        vector<MatrixXd> pred_input, pred_out, loss_inputs, loss_output;\n        pred_input.push_back(inputs[0]);\n        pred_out = predict(pred_input);\n\n        loss_inputs.push_back(pred_out[0]);\n        loss_inputs.push_back(t);\n\n        loss_output = _last_layer->forward(loss_inputs);\n\n        // \u3042\u3068\u306f Weight Decay \u306e\u9805\u3082\u8a08\u7b97\u3057\u3066Loss\u306b\u52a0\u3048\u308b\n        double weight_decay = 0;\n        for (auto param : params)\n        {\n            weight_decay += 0.5 * _weight_decay_lambda * (*(param.second)).sum();\n        }\n\n        loss_output[0](0) = loss_output[0](0) + weight_decay;\n\n        return loss_output;\n    }\n\n    double MultiLayerModel::accuracy(vector<MatrixXd> inputs, MatrixXd &t)\n    {\n        vector<MatrixXd> pred_out;\n        pred_out = predict(inputs);\n\n        MatrixXd y;\n        y = pred_out[0];\n        double batch_size = t.rows();\n        double accuracy = 0;\n\n        MatrixXd::Index y_row, y_col, t_row, t_col;\n        for (int i = 0; i < batch_size; i++)\n        {\n            y.row(i).maxCoeff(&y_row, &y_col);\n            t.row(i).maxCoeff(&t_row, &t_col);\n\n            accuracy += (double)(y_col == t_col);\n        }\n\n        return accuracy / batch_size;\n    }\n\n    unordered_map<string, MatrixXd> MultiLayerModel::gradient(vector<MatrixXd> inputs, MatrixXd &t)\n    {\n        // Forward\n        vector<MatrixXd> output;\n        output = loss(inputs, t);\n\n        // Backward\n        vector<MatrixXd> dout, tmp_dout;\n        dout.push_back(MatrixXd::Ones(1, 1));\n\n        dout = _last_layer->backward(dout);\n\n        for (auto it = _layer_list.rbegin(); it != _layer_list.rend(); it++)\n        {\n            string layer = *it;\n            tmp_dout = _layers[layer]->backward(dout);\n            dout.swap(tmp_dout);\n        }\n\n        unordered_map<string, MatrixXd> grads;\n\n        for (int i = 1; i <= _hidden_size_list.size() + 1; i++)\n        {\n            if (auto tmp_affine = std::dynamic_pointer_cast<MyDL::Affine>(_layers[\"Affine\" + std::to_string(i)]))\n            {\n                grads[\"W\" + std::to_string(i)] = tmp_affine->dW + _weight_decay_lambda * (*(tmp_affine->pW));\n                grads[\"b\" + std::to_string(i)] = tmp_affine->db;\n            }\n        }\n\n        return grads;\n    }\n\n    // -----------------------------------------------------------\n    // SimpleConvModel: Convolution\u306e\u691c\u8a3c\u7528\n    // -----------------------------------------------------------\n\n    SimpleConvModel::SimpleConvModel(const int input_channels,\n                                     const int input_height,\n                                     const int input_width,\n                                     const int filter_num,\n                                     const int filter_size,\n                                     const int pad,\n                                     const int stride,\n                                     const int hidden_size,\n                                     const int output_size,\n                                     const double weight_init_std)\n    : _C(input_channels), _H(input_height), _W(input_width), _filter_num(filter_num), _filter_size(filter_size), _pad(pad), _stride(stride), _hidden_size(hidden_size), _output_size(output_size)\n    {\n        int Oh = (_pad*2 + _H - _filter_size) / _stride + 1;\n        int Ow = (_pad*2 + _W - _filter_size) / _stride + 1;\n        int Ph = 2;\n        int Pw = 2; // Pooling\u306e\u30b5\u30a4\u30ba\u306f\u56fa\u5b9a\n        int p_stride = 2;\n        int p_pad = 0;\n\n        int pool_output_size = _filter_num * (Oh / 2) * (Ow / 2);\n\n        _layers[\"Conv1\"] = make_shared<Conv2D>(_C, _H, _W, _filter_size, _filter_size, _filter_num, _stride, _pad, weight_init_std);\n        _layers[\"Relu1\"] = make_shared<ReLU>();\n        _layers[\"Pool1\"] = make_shared<Pooling>(_filter_num, Oh, Ow, Ph, Pw, p_stride, p_pad);\n        _layers[\"Affine1\"] = make_shared<MyDL::Affine>(pool_output_size, _hidden_size, weight_init_std);\n        _layers[\"Affine2\"] = make_shared<MyDL::Affine>(hidden_size, output_size, weight_init_std);\n\n        _last_layer = make_shared<SoftmaxWithLoss>();\n\n        _layer_list.push_back(\"Conv1\");\n        _layer_list.push_back(\"Relu1\");\n        _layer_list.push_back(\"Pool1\");\n        _layer_list.push_back(\"Affine1\");\n        _layer_list.push_back(\"Affine2\");\n\n        if (auto cast_conv = std::dynamic_pointer_cast<Conv2D>(_layers[\"Conv1\"]))\n        {\n            params[\"W1\"] = cast_conv->pW;\n            params[\"b1\"] = cast_conv->pb;\n        }\n\n        if (auto cast_affine1 = std::dynamic_pointer_cast<MyDL::Affine>(_layers[\"Affine1\"]))\n        {\n            params[\"W2\"] = cast_affine1->pW;\n            params[\"b2\"] = cast_affine1->pb;\n        }\n\n        if (auto cast_affine2 = std::dynamic_pointer_cast<MyDL::Affine>(_layers[\"Affine2\"]))\n        {\n            params[\"W3\"] = cast_affine2->pW;\n            params[\"b3\"] = cast_affine2->pb;\n        }\n\n    }\n\n    vector<MatrixXd> SimpleConvModel::predict(vector<MatrixXd> inputs)\n    {\n        vector<MatrixXd> X = inputs;\n        vector<MatrixXd> tmp_X;\n\n        for (auto layer : _layer_list)\n        {\n            tmp_X = _layers[layer]->forward(X);\n            X.swap(tmp_X);\n        }\n        return X;\n    }\n\n    vector<MatrixXd> SimpleConvModel::loss(vector<MatrixXd> inputs, MatrixXd &t)\n    {\n        vector<MatrixXd> pred_input, pred_out, loss_inputs, loss_output;\n        pred_input.push_back(inputs[0]);\n        pred_out = predict(pred_input);\n\n        loss_inputs.push_back(pred_out[0]);\n        loss_inputs.push_back(t);\n\n        loss_output = _last_layer->forward(loss_inputs);\n\n        return loss_output;\n    }\n\n    double SimpleConvModel::accuracy(vector<MatrixXd> inputs, MatrixXd &t)\n    {\n        vector<MatrixXd> pred_out;\n        pred_out = predict(inputs);\n\n        MatrixXd y;\n        y = pred_out[0];\n        double batch_size = t.rows();\n        double accuracy = 0;\n\n        MatrixXd::Index y_row, y_col, t_row, t_col;\n        for (int i = 0; i < batch_size; i++)\n        {\n            y.row(i).maxCoeff(&y_row, &y_col);\n            t.row(i).maxCoeff(&t_row, &t_col);\n\n            accuracy += (double)(y_col == t_col);\n        }\n\n        return accuracy / batch_size;\n    }\n\n    unordered_map<string, MatrixXd> SimpleConvModel::gradient(vector<MatrixXd> inputs, MatrixXd &t)\n    {\n        // Forward\n        vector<MatrixXd> output;\n        output = loss(inputs, t);\n\n        // Backward\n        vector<MatrixXd> dout, tmp_dout;\n        dout.push_back(MatrixXd::Ones(1, 1));\n\n        dout = _last_layer->backward(dout);\n\n        for (auto it = _layer_list.rbegin(); it != _layer_list.rend(); it++)\n        {\n            string layer = *it;\n            tmp_dout = _layers[layer]->backward(dout);\n            dout.swap(tmp_dout);\n        }\n\n        unordered_map<string, MatrixXd> grads;\n\n        if (auto cast_conv = std::dynamic_pointer_cast<Conv2D>(_layers[\"Conv1\"]))\n        {\n            grads[\"W1\"] = cast_conv->dW;\n            grads[\"b1\"] = cast_conv->db;\n        }\n\n        if (auto cast_affine1 = std::dynamic_pointer_cast<MyDL::Affine>(_layers[\"Affine1\"]))\n        {\n            grads[\"W2\"] = cast_affine1->dW;\n            grads[\"b2\"] = cast_affine1->db;\n        }\n\n        if (auto cast_affine2 = std::dynamic_pointer_cast<MyDL::Affine>(_layers[\"Affine2\"]))\n        {\n            grads[\"W3\"] = cast_affine2->dW;\n            grads[\"b3\"] = cast_affine2->db;\n        }\n\n        return grads;\n    }\n}", "meta": {"hexsha": "6397c9ad8926020ae14322b73dd0599e58d50c11", "size": 20168, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/model.cpp", "max_stars_repo_name": "potedo/zeroDL_cpp", "max_stars_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-22T15:26:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-22T15:26:20.000Z", "max_issues_repo_path": "src/model.cpp", "max_issues_repo_name": "potedo/zeroDL_cpp", "max_issues_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_issues_repo_licenses": ["MIT"], "max_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.cpp", "max_forks_repo_name": "potedo/zeroDL_cpp", "max_forks_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_forks_repo_licenses": ["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.5070422535, "max_line_length": 193, "alphanum_fraction": 0.5620289568, "num_tokens": 5404, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851919, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4673417282817899}}
{"text": "#pragma once\n\n#pragma warning(push)\n#pragma warning(disable: 4819)\n#include <boost/geometry/core/access.hpp>\n\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/box.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n\n#include <boost/geometry/geometries/multi_point.hpp>\n#include <boost/geometry/geometries/multi_polygon.hpp>\n\n#include <boost/geometry/strategies/strategies.hpp>\n#pragma warning(pop)\n\n\nnamespace ompu { namespace geo {\n\nnamespace bg = boost::geometry;\n\nusing Point = bg::model::d2::point_xy<double>;\nusing MultiPoint = bg::model::multi_point<Point>;\n\nusing Polygon = bg::model::polygon<Point>;\nusing MultiPolygon = bg::model::multi_polygon<Polygon>;\nusing Box = bg::model::box<Point>;\n\nstruct Size\n{\n    unsigned w, h;\n};\n\nstruct CircleSize\n{\n    bg::strategy::buffer::distance_symmetric<double>\n    radius;\n};\n\n}} // ompu\n\n", "meta": {"hexsha": "fcabd832edb3d69fe4a7c4f3bdfee65843e640c5", "size": 877, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ompu/geo/geo.hpp", "max_stars_repo_name": "ompu/ompu", "max_stars_repo_head_hexsha": "c45d292a0af1b50039db9aa79e444fb7019615e9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2017-09-28T13:53:32.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-14T21:29:25.000Z", "max_issues_repo_path": "include/ompu/geo/geo.hpp", "max_issues_repo_name": "ompu/ompu", "max_issues_repo_head_hexsha": "c45d292a0af1b50039db9aa79e444fb7019615e9", "max_issues_repo_licenses": ["MIT"], "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/ompu/geo/geo.hpp", "max_forks_repo_name": "ompu/ompu", "max_forks_repo_head_hexsha": "c45d292a0af1b50039db9aa79e444fb7019615e9", "max_forks_repo_licenses": ["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.880952381, "max_line_length": 55, "alphanum_fraction": 0.7457240593, "num_tokens": 215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7690802264851918, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4673417282817898}}
{"text": "//==================================================================================================\n/*\n  Copyright 2017 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//! [direct_trigonometric]\n#include <boost/simd/trigonometric.hpp>\n#include <boost/simd/pack.hpp>\n#include <boost/simd/function/enumerate.hpp>\n#include <boost/simd/constant/pi.hpp>\n#include <iostream>\n\nnamespace bs =  boost::simd;\nusing pack_ft =  bs::pack <float, 8>;\n\nint main()\n{\n  pack_ft p_pi = bs::enumerate<pack_ft>(-1.0f, 0.25f);\n  pack_ft p_ra = p_pi*bs::Pi<pack_ft>();\n  pack_ft p_dg = bs::indeg(p_ra);\n  std::cout << \" p_ra =  \" << p_ra << std::endl\n            << \" p_pi =  \" << p_pi << std::endl\n            << \" p_dg =  \" << p_dg << std::endl\n            << \" -> bs::cos(p_ra) =   \" << bs::cos(p_ra)   << std::endl\n            << \" -> bs::cospi(p_pi) = \" << bs::cospi(p_pi) << std::endl\n            << \" -> bs::cosd(p_dg) =  \" << bs::cosd(p_dg)  << std::endl;\n  return 0;\n}\n//! [direct_trigonometric]\n", "meta": {"hexsha": "282af9dba5050a76fddd0b76390ec4af06779508", "size": 1196, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/doc/trigonometric/direct_trigonometric.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": "test/doc/trigonometric/direct_trigonometric.cpp", "max_issues_repo_name": "remymuller/boost.simd", "max_issues_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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/doc/trigonometric/direct_trigonometric.cpp", "max_forks_repo_name": "remymuller/boost.simd", "max_forks_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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": 36.2424242424, "max_line_length": 100, "alphanum_fraction": 0.4882943144, "num_tokens": 332, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.831143031127974, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4672490809751404}}
{"text": "#include \"gr/algorithms/match4pcsBase.h\"\n#include \"gr/algorithms/FunctorSuper4pcs.h\"\n#include \"gr/utils/geometry.h\"\n#include <gr/algorithms/PointPairFilter.h>\n\n#include <Eigen/Dense>\n\n\nint main(int argc, char **argv) {\n  using namespace gr;\n  using namespace std;\n\n  using TrVisitor = gr::DummyTransformVisitor;\n\n  using MatcherType = gr::Match4pcsBase<gr::FunctorSuper4PCS, gr::Point3D<float>, TrVisitor, gr::AdaptivePointFilter, gr::AdaptivePointFilter::Options>;\n  using OptionType  = typename MatcherType::OptionsType;\n  using SamplerType = gr::UniformDistSampler<gr::Point3D<float> >;\n\n  vector<Point3D<float> > set1, set2;\n  vector<Eigen::Matrix2f> tex_coords1, tex_coords2;\n  vector<typename Point3D<float>::VectorType> normals1, normals2;\n  vector<std::string> mtls1, mtls2;\n\n  // dummy calls, to test symbols accessibility\n  // check availability of the Utils functions\n  Utils::CleanInvalidNormals(set1, normals1);\n\n  // Our matcher.\n  OptionType options;\n\n  // Set parameters.\n  typename MatcherType::MatrixType mat;\n  double overlap (1);\n  options.configureOverlap(overlap);\n\n  typename Point3D<float>::Scalar score = 0;\n\n  constexpr Utils::LogLevel loglvl = Utils::Verbose;\n  Utils::Logger logger(loglvl);\n  SamplerType sampler;\n  TrVisitor visitor;\n\n  MatcherType matcher(options, logger);\n  score = matcher.ComputeTransformation(set1, set2, mat, sampler, visitor);\n\n  logger.Log<Utils::Verbose>( \"Score: \", score );\n\n  return 0;\n}\n\n", "meta": {"hexsha": "62a5b3279fcaaebdbff538bc6ab6ac7092809514", "size": 1447, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/externalAppTest/main.cpp", "max_stars_repo_name": "sgiraudot/OpenGR", "max_stars_repo_head_hexsha": "ad80cacbdb5cc9bf034e9a9613f1982105e6708d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 242.0, "max_stars_repo_stars_event_min_datetime": "2018-05-25T12:46:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T09:12:58.000Z", "max_issues_repo_path": "tests/externalAppTest/main.cpp", "max_issues_repo_name": "sgiraudot/OpenGR", "max_issues_repo_head_hexsha": "ad80cacbdb5cc9bf034e9a9613f1982105e6708d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 69.0, "max_issues_repo_issues_event_min_datetime": "2018-07-16T17:29:25.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-03T16:45:08.000Z", "max_forks_repo_path": "tests/externalAppTest/main.cpp", "max_forks_repo_name": "sgiraudot/OpenGR", "max_forks_repo_head_hexsha": "ad80cacbdb5cc9bf034e9a9613f1982105e6708d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 66.0, "max_forks_repo_forks_event_min_datetime": "2018-06-06T12:54:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T06:15:21.000Z", "avg_line_length": 28.3725490196, "max_line_length": 152, "alphanum_fraction": 0.7436074637, "num_tokens": 379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118221, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4672183863314466}}
{"text": "#include <string>\n#include <cassert>\n#include <map>\n#include <cstdint>\n#include <vector>\n#include <boost/algorithm/string.hpp>\n#include \"crypto/crypto.h\"  // for declaration of crypto::secret_key\n\n#include \"crypto/electrum-words.h\"\n\nnamespace crypto\n{\n  namespace ElectrumWords\n  {\n\n    /* convert words to bytes, 3 words -> 4 bytes\n     * returns:\n     *    false if not a multiple of 3 words, or if a words is not in the\n     *    words list\n     *\n     *    true otherwise\n     */\n    bool words_to_bytes(const std::string& words, crypto::secret_key& dst)\n    {\n      int n = NUMWORDS; // hardcoded because this is what electrum uses\n\n      std::vector<std::string> wlist;\n\n      boost::split(wlist, words, boost::is_any_of(\" \"));\n\n      // error on non-compliant word list\n      if (wlist.size() != 12 && wlist.size() != 24) return false;\n\n      for (unsigned int i=0; i < wlist.size() / 3; i++)\n      {\n        uint32_t val;\n        uint32_t w1, w2, w3;\n\n        // verify all three words exist in the word list\n        if (wordsMap.count(wlist[i*3]) == 0 ||\n            wordsMap.count(wlist[i*3 + 1]) == 0 ||\n            wordsMap.count(wlist[i*3 + 2]) == 0)\n        {\n          return false;\n        }\n\n        w1 = wordsMap.at(wlist[i*3]);\n        w2 = wordsMap.at(wlist[i*3 + 1]);\n        w3 = wordsMap.at(wlist[i*3 + 2]);\n\n        val = w1 + n * (((n - w1) + w2) % n) + n * n * (((n - w2) + w3) % n);\n\n        if (!(val % n == w1)) return false;\n\n        memcpy(dst.data + i * 4, &val, 4);  // copy 4 bytes to position\n      }\n\n      std::string wlist_copy = words;\n      if (wlist.size() == 12)\n      {\n        memcpy(dst.data, dst.data + 16, 16);  // if electrum 12-word seed, duplicate\n        wlist_copy += ' ';\n        wlist_copy += words;\n      }\n\n      return true;\n    }\n\n    /* convert bytes to words, 4 bytes-> 3 words\n     * returns:\n     *    false if wrong number of bytes (shouldn't be possible)\n     *    true otherwise\n     */\n    bool bytes_to_words(const crypto::secret_key& src, std::string& words)\n    {\n      int n = NUMWORDS; // hardcoded because this is what electrum uses\n\n      if (sizeof(src.data) % 4 != 0) return false;\n\n      // 8 bytes -> 3 words.  8 digits base 16 -> 3 digits base 1626\n      for (unsigned int i=0; i < sizeof(src.data)/4; i++, words += ' ')\n      {\n        uint32_t w1, w2, w3;\n        \n        uint32_t val;\n\n        memcpy(&val, (src.data) + (i * 4), 4);\n\n        w1 = val % n;\n        w2 = ((val / n) + w1) % n;\n        w3 = (((val / n) / n) + w2) % n;\n\n        words += wordsArray[w1];\n        words += ' ';\n        words += wordsArray[w2];\n        words += ' ';\n        words += wordsArray[w3];\n      }\n      return false;\n    }\n\n  }  // namespace ElectrumWords\n\n}  // namespace crypto\n", "meta": {"hexsha": "d9dc76aa7b2f73dad1ccba167ee92a03e2326041", "size": 2749, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/crypto/electrum-words.cpp", "max_stars_repo_name": "tedchain/tedcoin-secure", "max_stars_repo_head_hexsha": "d6850d0b6d32b4e0d8ae50f7246e717e47290478", "max_stars_repo_licenses": ["OLDAP-2.6", "OLDAP-2.8"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-06-06T05:30:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-11T10:07:07.000Z", "max_issues_repo_path": "src/crypto/electrum-words.cpp", "max_issues_repo_name": "tedchain/tedcoin-secure", "max_issues_repo_head_hexsha": "d6850d0b6d32b4e0d8ae50f7246e717e47290478", "max_issues_repo_licenses": ["OLDAP-2.6", "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": "src/crypto/electrum-words.cpp", "max_forks_repo_name": "tedchain/tedcoin-secure", "max_forks_repo_head_hexsha": "d6850d0b6d32b4e0d8ae50f7246e717e47290478", "max_forks_repo_licenses": ["OLDAP-2.6", "OLDAP-2.8"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2018-05-23T16:15:36.000Z", "max_forks_repo_forks_event_max_datetime": "2018-06-06T05:46:12.000Z", "avg_line_length": 26.180952381, "max_line_length": 84, "alphanum_fraction": 0.5292833758, "num_tokens": 816, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933183101078, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.46721838131576643}}
{"text": "// clang++ -std=c++11 main.cpp -I include -I $LIBIGL/include -I /usr/local/libigl/external/eigen/ -framework OpenGL -L/usr/local/lib/ -lglfw && ./a.out\n//\n\n// make sure the modern opengl headers are included before any others\n#include \"gl.h\"\n#define GLFW_INCLUDE_GLU\n#include <GLFW/glfw3.h>\n\n#include \"read_json.h\"\n#include \"icosahedron.h\"\n#include \"mesh_to_vao.h\"\n#include \"print_opengl_info.h\"\n#include \"get_seconds.h\"\n#include \"report_gl_error.h\"\n#include \"create_shader_program_from_files.h\"\n#include \"last_modification_time.h\"\n#ifdef USE_SOLUTION\n#  include \"find_and_replace_all.h\"\n#endif\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include <thread>\n#include <iostream>\n#include <sstream>\n#include <fstream>\n#include <cstdlib>\n#include <vector>\n\n// Default width and height\nbool wire_frame = false;\nbool mouse_down = false;\nbool is_animating = true;\ndouble last_time = get_seconds();\ndouble animation_seconds = 0;\nint width =  640;\nint height = 360;\n// Whether display has high dpi (e.g., Mac retinas)\nint highdpi = 1;\nGLuint prog_id=0;\n\nEigen::Affine3f view = \n  Eigen::Affine3f::Identity() * \n  Eigen::Translation3f(Eigen::Vector3f(0,0,-10));\nEigen::Matrix4f proj = Eigen::Matrix4f::Identity();\n\nGLuint VAO;\n// Mesh data: RowMajor is important to directly use in OpenGL\nEigen::Matrix< float,Eigen::Dynamic,3,Eigen::RowMajor> V;\nEigen::Matrix<GLuint,Eigen::Dynamic,3,Eigen::RowMajor> F;\n\nint main(int argc, char * argv[])\n{\n\n  std::vector<std::string> vertex_shader_paths;\n  std::vector<std::string> tess_control_shader_paths;\n  std::vector<std::string> tess_evaluation_shader_paths;\n  std::vector<std::string> fragment_shader_paths;\n\n  // Initialize glfw window\n  if(!glfwInit())\n  {\n    std::cerr<<\"Could not initialize glfw\"<<std::endl;\n     return EXIT_FAILURE;\n  }\n  const auto & error = [] (int error, const char* description)\n  {\n    std::cerr<<description<<std::endl;\n  };\n  glfwSetErrorCallback(error);\n  glfwWindowHint(GLFW_SAMPLES, 4);\n  glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);\n  glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);\n  glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);\n  glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);\n  GLFWwindow* window = glfwCreateWindow(width, height, \"shader-pipeline\", NULL, NULL);\n  if(!window)\n  {\n    glfwTerminate();\n    std::cerr<<\"Could not create glfw window\"<<std::endl;\n    return EXIT_FAILURE;\n  }\n  std::cout<<R\"(\nUsage:\n  [Click and drag]  to orbit view\n  [Scroll]  to translate view in and out\n  A,a  toggle animation\n  L,l  toggle wireframe rending\n  Z,z  reset view to look along z-axis\n)\";\n  glfwSetWindowPos(window,0,0);\n  glfwMakeContextCurrent(window);\n  // Load OpenGL and its extensions\n  if (!gladLoadGLLoader((GLADloadproc) glfwGetProcAddress))\n  {\n    std::cerr<<\"Failed to load OpenGL and its extensions\"<<std::endl;\n    return EXIT_FAILURE;\n  }\n  print_opengl_info(window);\n  igl::opengl::report_gl_error(\"init\");\n\n\n  icosahedron(V,F);\n  mesh_to_vao(V,F,VAO);\n  igl::opengl::report_gl_error(\"mesh_to_vao\");\n\n  const auto & reshape = [](\n    GLFWwindow* window,\n    int _width,\n    int _height)\n  {\n    ::width=_width,::height=_height;\n\n    // augh, windows can't handle variables named near and far.\n    float nearVal = 0.01;\n    float farVal = 100;\n    float top = tan(35./360.*M_PI)*nearVal;\n    float right = top * (double)::width/(double)::height;\n    float left = -right;\n    float bottom = -top;\n    proj.setConstant(4,4,0.);\n    proj(0,0) = (2.0 * nearVal) / (right - left);\n    proj(1,1) = (2.0 * nearVal) / (top - bottom);\n    proj(0,2) = (right + left) / (right - left);\n    proj(1,2) = (top + bottom) / (top - bottom);\n    proj(2,2) = -(farVal + nearVal) / (farVal - nearVal);\n    proj(3,2) = -1.0;\n    proj(2,3) = -(2.0 * farVal * nearVal) / (farVal - nearVal);\n  };\n  // Set up window resizing\n  glfwSetWindowSizeCallback(window,reshape);\n  {\n    int width_window, height_window;\n    glfwGetWindowSize(window, &width_window, &height_window);\n    reshape(window,width_window,height_window);\n  }\n\n  // Close the window if user presses ESC or CTRL+C\n  glfwSetKeyCallback(\n    window,\n    [](GLFWwindow* window, int key, int scancode, int action, int mods)\n    {\n      if(key == 256 || (key == 67 && (mods & GLFW_MOD_CONTROL)))\n      {\n        glfwSetWindowShouldClose(window,true);\n      }\n    });\n  glfwSetCharModsCallback(\n    window,\n    [](GLFWwindow* window, unsigned int codepoint, int modifier)\n    {\n      switch(codepoint)\n      {\n        case 'A':\n        case 'a':\n          is_animating ^= 1;\n          if(is_animating)\n          {\n            last_time = get_seconds();\n          }\n          break;\n        case 'L':\n        case 'l':\n          wire_frame ^= 1;\n          if (wire_frame) {\n            glDisable(GL_CULL_FACE);\n          } else {\n            glEnable(GL_CULL_FACE);\n          }\n          break;\n        case 'Z':\n        case 'z':\n          view.matrix().block(0,0,3,3).setIdentity();\n          break;\n        default:\n          std::cout<<\"Unrecognized key: \"<<(unsigned char) codepoint<<std::endl;\n          break;\n      }\n    });\n  glfwSetMouseButtonCallback(\n    window,\n    [](GLFWwindow * window, int button, int action, int mods)\n    {\n      mouse_down = action == GLFW_PRESS;\n    });\n  glfwSetCursorPosCallback(\n    window,\n    [](GLFWwindow * window, double x, double y)\n    {\n      static double mouse_last_x = x;\n      static double mouse_last_y = y;\n      double dx = x-mouse_last_x;\n      double dy = y-mouse_last_y;\n      if(mouse_down)\n      {\n        // Two axis valuator with fixed up\n        float factor = std::abs(view.matrix()(2,3));\n        view.rotate(\n          Eigen::AngleAxisf(\n            dx*factor/float(width),\n            Eigen::Vector3f(0,1,0)));\n        view.rotate(\n          Eigen::AngleAxisf(\n            dy*factor/float(height),\n            view.matrix().topLeftCorner(3,3).inverse()*Eigen::Vector3f(1,0,0)));\n      }\n      mouse_last_x = x;\n      mouse_last_y = y;\n    });\n  glfwSetScrollCallback(window,\n    [](GLFWwindow * window, double xoffset, double yoffset)\n    {\n      view.matrix()(2,3) =\n        std::min(std::max(view.matrix()(2,3)+(float)yoffset,-100.0f),-2.0f);\n    });\n\n  glEnable(GL_DEPTH_TEST);\n  glEnable(GL_CULL_FACE);\n  // Force compilation on first iteration through loop\n  double time_of_last_shader_compilation = 0;\n  double time_of_last_json_load = 0;\n  const auto any_changed = \n    [](\n        const std::vector<std::string> &paths,\n        const double time_of_last_shader_compilation\n        )->bool\n  {\n    for(const auto & path : paths)\n    {\n      if(last_modification_time(path) > time_of_last_shader_compilation)\n      {\n        std::cout<<path<<\" has changed since last compilation attempt.\"<<std::endl;\n        return true;\n      }\n    }\n    return false;\n  };\n\n  float start_time = get_seconds();\n  // Main display routine\n  while (!glfwWindowShouldClose(window))\n  {\n    double tic = get_seconds();\n\n    if(any_changed({argv[1]},time_of_last_json_load))\n    {\n      std::cout<<\"-----------------------------------------------\"<<std::endl;\n      time_of_last_json_load = get_seconds();\n      if(!read_json(argv[1],\n            vertex_shader_paths,\n            tess_control_shader_paths,\n            tess_evaluation_shader_paths,\n            fragment_shader_paths))\n      {\n        std::cerr<<\"Failed to read \"<<argv[1]<<std::endl;\n      }\n#ifdef USE_SOLUTION\n      {\n        const auto replace_all = [](std::vector<std::string> & paths)\n        {\n          for(auto & path : paths)\n          {\n            find_and_replace_all(\"/src/\",\"/solution/\",path);\n          }\n        };\n        replace_all(vertex_shader_paths);\n        replace_all(tess_control_shader_paths);\n        replace_all(tess_evaluation_shader_paths);\n        replace_all(fragment_shader_paths);\n      }\n#endif\n      // force reload of shaders\n      time_of_last_shader_compilation = 0;\n    }\n    if(\n      any_changed(vertex_shader_paths         ,time_of_last_shader_compilation) ||\n      any_changed(tess_control_shader_paths   ,time_of_last_shader_compilation) ||\n      any_changed(tess_evaluation_shader_paths,time_of_last_shader_compilation) ||\n      any_changed(fragment_shader_paths       ,time_of_last_shader_compilation))\n    {\n      std::cout<<\"-----------------------------------------------\"<<std::endl;\n      // remember the time we tried to compile\n      time_of_last_shader_compilation = get_seconds();\n      if(\n          !create_shader_program_from_files(\n            vertex_shader_paths,\n            tess_control_shader_paths,\n            tess_evaluation_shader_paths,\n            fragment_shader_paths,\n            prog_id))\n      {\n        // Force null shader to visually indicate failure\n        glDeleteProgram(prog_id);\n        prog_id = 0;\n        std::cout<<\"-----------------------------------------------\"<<std::endl;\n      }\n    }\n\n    // clear screen and set viewport\n    glClearColor(0,0,0,0);\n    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n    glfwGetFramebufferSize(window, &::width, &::height);\n    glViewport(0,0,::width,::height);\n    // select program \n    glUseProgram(prog_id);\n    // Attach uniforms\n    {\n      if(is_animating)\n      {\n        double now = get_seconds();\n        animation_seconds += now - last_time;\n        last_time = now;\n      }\n      glUniform1f(glGetUniformLocation(prog_id,\"animation_seconds\"),animation_seconds);\n    }\n    glUniformMatrix4fv(\n      glGetUniformLocation(prog_id,\"proj\"),1,false,proj.data());\n    glUniformMatrix4fv(\n      glGetUniformLocation(prog_id,\"view\"),1,false,view.matrix().data());\n    // Draw mesh as wireframe\n    if(wire_frame)\n    {\n      glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);\n    }else\n    {\n      glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);\n    }\n    for(int i = 0;i<2;i++)\n    {\n      glUniform1i(glGetUniformLocation(prog_id, \"is_moon\"), i==1);\n      glBindVertexArray(VAO);\n      glDrawElements(GL_PATCHES, F.size(), GL_UNSIGNED_INT, 0);\n      glBindVertexArray(0);\n    }\n\n\n    glfwSwapBuffers(window);\n\n    // 60 fps\n    {\n      glfwPollEvents();\n      // In microseconds\n      double duration = 1000000.*(get_seconds()-tic);\n      const double min_duration = 1000000./60.;\n      if(duration<min_duration)\n      {\n        std::this_thread::sleep_for(std::chrono::microseconds((int)(min_duration-duration)));\n      }\n    }\n  }\n\n  // Graceful exit\n  glfwDestroyWindow(window);\n  glfwTerminate();\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "f6d482bc03890b858393b7287005826eab65195e", "size": 10422, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "ericpko/computer-graphics-shader-pipeline", "max_stars_repo_head_hexsha": "67fd0682cca76b69f453b747b759180240353e16", "max_stars_repo_licenses": ["MIT"], "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": "ericpko/computer-graphics-shader-pipeline", "max_issues_repo_head_hexsha": "67fd0682cca76b69f453b747b759180240353e16", "max_issues_repo_licenses": ["MIT"], "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": "ericpko/computer-graphics-shader-pipeline", "max_forks_repo_head_hexsha": "67fd0682cca76b69f453b747b759180240353e16", "max_forks_repo_licenses": ["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.1117318436, "max_line_length": 151, "alphanum_fraction": 0.6266551526, "num_tokens": 2654, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.4671756701783066}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// Unit Test\n\n// Copyright (c) 2019 Tinko Bartels, Berlin, Germany.\n\n// Contributed and/or modified by Tinko Bartels,\n//   as part of Google Summer of Code 2019 program.\n\n// 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#include <geometry_test_common.hpp>\n\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/extensions/triangulation/strategies/cartesian/side_robust.hpp>\n\ntemplate <typename P>\nvoid test_all()\n{\n    typedef bg::strategy::side::side_robust<double, 3> side3;\n    typedef bg::strategy::side::side_robust<double, 2> side2;\n    typedef bg::strategy::side::side_robust<double, 1> side1;\n    typedef bg::strategy::side::side_robust<double, 0> side0;\n\n    P col1(1.0, 1.0), col2(2.0, 2.0), col3(3.0, 3.0);\n    int col3r = side3::apply(col1, col2, col3);\n    BOOST_CHECK_EQUAL(0, col3r);\n    int col2r = side2::apply(col1, col2, col3);\n    BOOST_CHECK_EQUAL(0, col2r);\n    int col1r = side1::apply(col1, col2, col3);\n    BOOST_CHECK_EQUAL(0, col1r);\n    int col0r = side0::apply(col1, col2, col3);\n    BOOST_CHECK_EQUAL(0, col0r);\n\n    P easy1(0.0, 0.0), easy2(1.0, 1.0), easy3(0.0, 1.0);\n    int easy3r = side3::apply(easy1, easy2, easy3);\n    BOOST_CHECK_GT(easy3r, 0);\n    int easy2r = side2::apply(easy1, easy2, easy3);\n    BOOST_CHECK_GT(easy2r, 0);\n    int easy1r = side1::apply(easy1, easy2, easy3);\n    BOOST_CHECK_GT(easy1r, 0);\n    int easy0r = side0::apply(easy1, easy2, easy3);\n    BOOST_CHECK_GT(easy0r, 0);\n\n    P medium1(1.0, 1.0), medium2(1.0e20, 1.0e20), medium3(1.0, 2.0);\n    int medium3r = side3::apply(medium1, medium2, medium3);\n    BOOST_CHECK_GT(medium3r, 0);\n    int medium2r = side2::apply(medium1, medium2, medium3);\n    BOOST_CHECK_GT(medium2r, 0);\n\n    P hard1(1.0e-20, 1.0e-20), hard2(1.0e20, 1.0e20), hard3(1.0, 2.0);\n    int hard3r = side3::apply(hard1, hard2, hard3);\n    BOOST_CHECK_GT(hard3r, 0);\n}\n\n\nint test_main(int, char* [])\n{\n    test_all<bg::model::d2::point_xy<double> >();\n    return 0;\n}\n", "meta": {"hexsha": "64f9787515b68a8aafd5a595469baaad20397f32", "size": 2158, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "extensions/test/triangulation/side_robust.cpp", "max_stars_repo_name": "tinko92/geometry", "max_stars_repo_head_hexsha": "56a9f79036dc3bce8dcd0483cfa728a196997f81", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-05-15T20:30:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T08:14:05.000Z", "max_issues_repo_path": "extensions/test/triangulation/side_robust.cpp", "max_issues_repo_name": "tinko92/geometry", "max_issues_repo_head_hexsha": "56a9f79036dc3bce8dcd0483cfa728a196997f81", "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": "extensions/test/triangulation/side_robust.cpp", "max_forks_repo_name": "tinko92/geometry", "max_forks_repo_head_hexsha": "56a9f79036dc3bce8dcd0483cfa728a196997f81", "max_forks_repo_licenses": ["BSL-1.0"], "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": 34.253968254, "max_line_length": 87, "alphanum_fraction": 0.6788693234, "num_tokens": 783, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.6261241842048092, "lm_q1q2_score": 0.46717566831477686}}
{"text": "#include \"FileIO.h\"\n#include <math.h>\n#include \"Types.h\"\n\n#include <boost/filesystem.hpp>\n#include <boost/filesystem/fstream.hpp>\n#include <vector>\n#include <iostream>\n#include <sstream>\n\n/**\n * Class for loading and saving for 3d modeler\n *\n * @author Ryan Hamilton\n */\n\n/**\n * Parses geometric vertex from line of OBJ file\n *\n * @param str - string containing geometric vertex\n *        refGeometricVertices - referance to a 2d vector for storing geometric vertex\n */\nvoid FileIO::mParseGeometricVertex( std::string str, std::vector< std::vector< double > > &refGeometricVertices )\n{\n\tdouble x, y, z;\n\tstd::stringstream ss( str );\n\tchar temp;\n\tss >> temp;\n\tss >> x;\n\tss >> y;\n\tss >> z;\n\n\trefGeometricVertices[ refGeometricVertices.size( ) - 1 ].push_back( x );\n\trefGeometricVertices[ refGeometricVertices.size( ) - 1 ].push_back( y );\n\trefGeometricVertices[ refGeometricVertices.size( ) - 1 ].push_back( z );\n}\n \n /**\n * Parses texture coordinates from line of OBJ file\n *\n * @param str - string containing texture coordinates\n *        refTextureCoordinates - referance to a 2d vector for storing texture coordinates\n */\n void FileIO::mParseTextureCoordinates( std::string str, std::vector< std::vector< double > > &refTextureCoordinates )\n{\n\tdouble x, y;\n\tstd::stringstream ss( str );\n\tchar temp;\n\tss >> temp;\n\tss >> temp;\n\tss >> x;\n\tss >> y;\n\n\trefTextureCoordinates[ refTextureCoordinates.size( ) - 1 ].push_back( x );\n\trefTextureCoordinates[ refTextureCoordinates.size( ) - 1 ].push_back( y );\n}\n\n/**\n * Parses Normal Vertex from line of OBJ file\n *\n * @param str - string containing normal vertex\n *        refNormalVertices - referance to a 2d vector for storing Gnormal Vertices\n */\nvoid FileIO::mParseNormalVertex( std::string str, std::vector< std::vector< double > > &refNormalVertices )\n{\n\tdouble x, y, z;\n\tstd::stringstream ss( str );\n\tchar temp;\n\tss >> temp;\n\tss >> temp;\n\tss >> x;\n\tss >> y;\n\tss >> z;\n\n\trefNormalVertices[ refNormalVertices.size( ) - 1 ].push_back( x );\n\trefNormalVertices[ refNormalVertices.size( ) - 1 ].push_back( y );\n\trefNormalVertices[ refNormalVertices.size( ) - 1 ].push_back( z );\n\n}\n \n/**\n * Parses face elements from line of OBJ file\n *\n * @param str - string containingface elements\n *        refFaceElements - referance to a 2d vector for storing face elements\n */\n void FileIO::mParseFaceElements( std::string str, std::vector< std::vector< std::vector< int > > > &refFaceElements )\n{\n\tint v1, v2, v3;\n\tstd::stringstream ss( str );\n\tuint FirstIndexOfLine = refFaceElements.size();\n\tuint index = 0;\n\tchar temp;\n\tss >> temp;\n\twhile( ss.tellg() != -1 )\n\t{\n\t\tif(index > 2 || index == 0)\n\t\t{\n\t\t\tstd::vector< int > vertexSet1;\n\t\t\tstd::vector< int > vertexSet2;\n\t\t\tstd::vector< int > vertexSet3;\n\n\t\t\tstd::vector< std::vector< int > > faceVertices;\n\n\t\t\tfaceVertices.push_back( vertexSet1 );\n\t\t\tfaceVertices.push_back( vertexSet2 );\n\t\t\tfaceVertices.push_back( vertexSet3 );\n\n\t\t\trefFaceElements.push_back( faceVertices );\n\t\t}\n\t\t\tss >> v1;\n\n\t\t\tif( ss.peek( ) == '/' )\n\t\t\t\tss >> temp;\n\n\t\t\tif( ss.peek( ) != '/' && ss.peek( ) != ' ' )\n\t\t\t\tss >> v2;\n\t\t\telse\n\t\t\t\tv2 = 0;\n\n\t\t\tif( ss.peek( ) == '/' )\n\t\t\t\tss >> temp;\n\n\t\t\tif( ss.peek( ) != '/' && ss.peek( ) != ' ' )\n\t\t\t\tss >> v3;\n\t\t\telse\n\t\t\t\tv3 = 0;\n\n\t\t\tif(index > 2)\n\t\t\t{\n\t\t\t\trefFaceElements[refFaceElements.size( ) - 1][0].push_back(refFaceElements[FirstIndexOfLine][0].at(0));\n\t\t\t\trefFaceElements[refFaceElements.size( ) - 1][0].push_back(refFaceElements[FirstIndexOfLine][0].at(1));\n\t\t\t\trefFaceElements[refFaceElements.size( ) - 1][0].push_back(refFaceElements[FirstIndexOfLine][0].at(2));\n\n\t\t\t\trefFaceElements[refFaceElements.size( ) - 1][1].push_back(refFaceElements[refFaceElements.size( ) - 2][2].at(0));\n\t\t\t\trefFaceElements[refFaceElements.size( ) - 1][1].push_back(refFaceElements[refFaceElements.size( ) - 2][2].at(1));\n\t\t\t\trefFaceElements[refFaceElements.size( ) - 1][1].push_back(refFaceElements[refFaceElements.size( ) - 2][2].at(2));\n\n\t\t\t\trefFaceElements[ refFaceElements.size( ) - 1 ][ 2 ].push_back( v1 );\n\t\t\t\trefFaceElements[ refFaceElements.size( ) - 1 ][ 2 ].push_back( v2 );\n\t\t\t\trefFaceElements[ refFaceElements.size( ) - 1 ][ 2 ].push_back( v3 );\n\n\t\t\t\tindex = index + 1;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\trefFaceElements[ refFaceElements.size( ) - 1 ][ index ].push_back( v1 );\n\t\t\t\trefFaceElements[ refFaceElements.size( ) - 1 ][ index ].push_back( v2 );\n\t\t\t\trefFaceElements[ refFaceElements.size( ) - 1 ][ index ].push_back( v3 );\n\n\t\t\t\tindex = index + 1;\n\t\t\t}\n\n\t}\n}\n \n /**\n  * Save 3d model as a .obj\n  *\n  * @param p - A path\n  */\n void FileIO::SaveObj(std::string filename)\n {\n\t // Adds the obj file extension to the filename\n\t  \tstd::string file = filename + \".obj\";\n\t  \tboost::filesystem::ofstream outputFile;\n\t  \t// Opens the output file for writing\n\t  \toutputFile.open(file);\n\n\t  \t// Check to see if any vertices were read in, if not then skips outputing this line\n\t  \tif ( (*mGeometricVertices).size() > 0 ) {\n\t  \t\toutputFile << \"# Vertices \\n\";\n\t  \t}\n\n\t  \t// Vertices written to a .obj file.\n\t  \tfor ( uint i = 0; i < (*mGeometricVertices).size(); i++ ) {\n\t  \t\toutputFile << \"v \" << (*mGeometricVertices)[i].at(0) << \" \" << (*mGeometricVertices)[i].at(1) << \" \" << (*mGeometricVertices)[i].at(2) << \"\\n\";\n\t  \t}\n\n\t  \t// Check to see if any textures were read in, if not then skips outputing this line\n\t  \tif ( (*mTextureCoordinates).size() > 0 ) {\n\t  \t\toutputFile << \"\\n\";\n\t  \t\toutputFile << \"# Texture Coordinates \\n\";\n\t  \t}\n\n\t  \t// Texture Coordinates written to a .obj file.\n\t  \tfor ( uint i = 0; i < (*mTextureCoordinates).size(); i++ ) {\n\t  \t\toutputFile << \"vt \" << (*mTextureCoordinates)[i].at(0) << \" \" << (*mTextureCoordinates)[i].at(1) << \"\\n\";\n\t  \t}\n\n\t  \t// Check to see if any normals were read in, if not then skips outputing this line\n\t  \tif ( (*mNormalVertices).size() > 0 ) {\n\t  \t\toutputFile << \"\\n\";\n\t  \t\toutputFile << \"# Normals \\n\";\n\t  \t}\n\n\t  \t// Normal vertices written to a .obj file.\n\t  \tfor ( uint i = 0; i < (*mNormalVertices).size(); i++ ) {\n\t  \t\toutputFile << \"vn \" << (*mNormalVertices)[i].at(0) << \" \" << (*mNormalVertices)[i].at(1) << \" \" << (*mNormalVertices)[i].at(2) << \"\\n\";\n\t  \t}\n\n\t  \t// Check to see if any faces were read in, if not then skips outputing this line\n\t  \tif ( (*mFaceElements).size() > 0 ) {\n\t  \t\toutputFile << \"\\n\";\n\t  \t\toutputFile << \"# Faces (vertex/texcoord/normal) \\n\";\n\t  \t}\n\n\t  \t// Faces written to a .obj file.\n\t  \tfor ( uint i = 0; i < (*mFaceElements).size(); i++ ) {\n\t  \t\t// Cycles through each row of faces\n\t  \t\toutputFile << \"f \";\n\t  \t\tfor ( uint j = 0; j < 3; j++ ) {\n\t  \t\t\t// Cycles through each elements of a line of faces\n\t  \t\t\t// IF statements to check for zeros in face vectors\n\t  \t\t\tif ( (*mFaceElements)[i][j].at(1) == 0 && (*mFaceElements)[i][j].at(2) == 0 && j < 2) {\n\t  \t\t\t\toutputFile << (*mFaceElements)[i][j].at(0) << \" \";\n\t  \t\t\t} else if ( (*mFaceElements)[i][j].at(1) == 0 && (*mFaceElements)[i][j].at(2) == 0 ) {\n\t  \t\t\t\toutputFile << (*mFaceElements)[i][j].at(0);\n\t  \t\t\t} else if ( (*mFaceElements)[i][j].at(1) == 0 && j < 2 ) {\n\t  \t\t\t\toutputFile << (*mFaceElements)[i][j].at(0) << \"//\" << (*mFaceElements)[i][j].at(2) << \" \";\n\t  \t\t\t} else if ( (*mFaceElements)[i][j].at(1) == 0 ) {\n\t  \t\t\t\toutputFile << (*mFaceElements)[i][j].at(0) << \"//\" << (*mFaceElements)[i][j].at(2);\n\t  \t\t\t} else if ( j < 2 ){ // Prevents extra space at end of line\n\t  \t\t\t\toutputFile << (*mFaceElements)[i][j].at(0) << \"/\" << (*mFaceElements)[i][j].at(1) << \"/\" << (*mFaceElements)[i][j].at(2) << \" \";\n\t  \t\t\t} else {\n\t  \t\t\t\toutputFile << (*mFaceElements)[i][j].at(0) << \"/\" << (*mFaceElements)[i][j].at(1) << \"/\" << (*mFaceElements)[i][j].at(2);\n\t  \t\t\t}\n\t  \t\t}\n\t  \t\t\toutputFile << \"\\n\";\n\t  \t}\n\n\t  \t// Closes the output file buffer\n\t  \toutputFile.close();\n }\n\n/**\n * Loads a .obj file and parses the file for the geometric vertices, texture coordinates, normal vertices, and face elements from the .obj file\n *\n * @param p - path of .obj file\n */\n /*\nvoid FileIO::LoadObj(boost::filesystem::path p)\n{\n\tboost::filesystem::ifstream File(p);\n\tstd::string FileLine;\n\t\n\t//loops through entire .obj file\n\twhile(std::getline(File, FileLine))\n\t{\n\t\t//std::cout<<FileLine<<\"\\n\";\n\t\tif(FileLine.size() > 2){\n\t\t\t\n\t\t\t//checks for Geometric vertex coordinates\n\t\t\tif(FileLine.at(0) == 'v' && FileLine.at(1) == ' ')\n\t\t\t{\n\t\t\t\tdouble X, Y, Z;\n\t\t\t\tstd::stringstream S(FileLine);\n\t\t\t\tchar Temp;\n\t\t\t\tS >> Temp;\n\t\t\t\tS >> X;\n\t\t\t\tS >> Y;\n\t\t\t\tS >> Z;\n\n\t\t\t\tstd::vector<double> GeometricVector;\n\t\t\t\tGeometricVector.push_back(X);\n\t\t\t\tGeometricVector.push_back(Y);\n\t\t\t\tGeometricVector.push_back(Z);\n\n\t\t\t\tmGeometricVertices.push_back(GeometricVector);\n\t\t\t}\n\n\t\t\t//checks for texture coordinates\n\t\t\tif(FileLine.at(0) == 'v' && FileLine.at(1) == 't')\n\t\t\t{\n\t\t\t\tdouble X, Y;\n\t\t\t\tstd::stringstream S(FileLine);\n\t\t\t\tchar Temp;\n\t\t\t\tchar Temp2;\n\t\t\t\tS >> Temp;\n\t\t\t\tS >> Temp2;\n\t\t\t\tS >> X;\n\t\t\t\tS >> Y;\n\n\t\t\t\tstd::vector<double> TextureVector;\n\n\t\t\t\tTextureVector.push_back(X);\n\t\t\t\tTextureVector.push_back(Y);\n\n\t\t\t\tmTextureCoordinates.push_back(TextureVector);\n\t\t\t}\n\n\t\t\t//checks for normal vertex coordinates\n\t\t\tif(FileLine.at(0) == 'v' && FileLine.at(1) == 'n')\n\t\t\t{\n\t\t\t\tdouble X, Y, Z;\n\t\t\t\tstd::stringstream S(FileLine);\n\t\t\t\tchar Temp;\n\t\t\t\tchar Temp2;\n\t\t\t\tS >> Temp;\n\t\t\t\tS >> Temp2;\n\t\t\t\tS >> X;\n\t\t\t\tS >> Y;\n\t\t\t\tS >> Z;\n\n\t\t\t\tstd::vector<double> NormalVector;\n\n\t\t\t\tNormalVector.push_back(X);\n\t\t\t\tNormalVector.push_back(Y);\n\t\t\t\tNormalVector.push_back(Z);\n\n\t\t\t\tmNormalVertices.push_back(NormalVector);\n\t\t\t}\n\n\t\t\t//checks for face elements\n\t\t\tif(FileLine.at(0) == 'f' && FileLine.at(1) == ' ')\n\t\t\t{\n\t\t\t\tint V1, V2, V3;\n\t\t\t\tstd::stringstream S(FileLine);\n\t\t\t\tchar Temp;\n\t\t\t\tS >> Temp;\n\t\t\t\tstd::vector<int> VerticeVector1;\n\t\t\t\tstd::vector<std::vector<int>> FaceVector;\n\t\t\t\t\n\t\t\t\t//parses through first set of vertices\n\t\t\t\tS >> V1;\n\t\t\t\tVerticeVector1.push_back(V1);\n\n\t\t\t\tif(S.peek() == '/')\n\t\t\t\t\tS >> Temp;\n\n\t\t\t\tif(S.peek() != '/' || S.peek() != ' ')\n\t\t\t\t{\n\t\t\t\t\tS >> V2;\n\t\t\t\t\tVerticeVector1.push_back(V2);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tVerticeVector1.push_back(0);\n\n\t\t\t\tif(S.peek() == '/')\n\t\t\t\t\tS >> Temp;\n\n\t\t\t\tif(S.peek() != '/' || S.peek() != ' ')\n\t\t\t\t{\n\t\t\t\t\tS >> V3;\n\t\t\t\t\tVerticeVector1.push_back(V3);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tVerticeVector1.push_back(0);\n\n\t\t\t\tFaceVector.push_back(VerticeVector1);\n\t\t\t\tstd::vector<int> VerticeVector2;\n\n\t\t\t\t// parses through second set of vertices\n\t\t\t\tS >> V1;\n\t\t\t\tVerticeVector2.push_back(V1);\n\t\t\t\t\n\t\t\t\tif(S.peek() == '/')\n\t\t\t\t\tS >> Temp;\n\n\t\t\t\tif(S.peek() != '/' || S.peek() != ' ')\n\t\t\t\t{\n\t\t\t\t\tS >> V2;\n\t\t\t\t\tVerticeVector2.push_back(V2);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tVerticeVector2.push_back(0);\n\n\t\t\t\tif(S.peek() == '/')\n\t\t\t\t\tS >> Temp;\n\n\t\t\t\tif(S.peek() != '/' || S.peek() != ' ')\n\t\t\t\t{\n\t\t\t\t\tS >> V3;\n\t\t\t\t\tVerticeVector2.push_back(V3);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tVerticeVector2.push_back(0);\n\n\t\t\t\tFaceVector.push_back(VerticeVector2);\n\t\t\t\tstd::vector<int> VerticeVector3;\n\n\t\t\t\t//parses through the third set of vertices\n\t\t\t\tS >> V1;\n\t\t\t\tVerticeVector3.push_back(V1);\n\t\t\t\t\t\n\t\t\t\tif(S.peek() == '/')\n\t\t\t\t\tS >> Temp;\n\n\t\t\t\tif(S.peek() != '/' || S.peek() != ' ')\n\t\t\t\t{\n\t\t\t\t\tS >> V2;\n\t\t\t\t\tVerticeVector3.push_back(V2);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tVerticeVector3.push_back(0);\n\t\n\t\t\t\tif(S.peek() == '/')\n\t\t\t\t\tS >> Temp;\n\t\n\t\t\t\tif(S.peek() != '/' || S.peek() != ' ')\n\t\t\t\t{\n\t\t\t\t\tS >> V3;\n\t\t\t\t\tVerticeVector3.push_back(V3);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tVerticeVector3.push_back(0);\n\n\t\t\t\tFaceVector.push_back(VerticeVector3);\n\t\t\t\tmFaceElements.push_back(FaceVector);\n\t\t\t}\n\t\t}\n\t}\n}\n*/\n\n/**\n * Loads a .obj file and parses the file for the geometric vertices, texture coordinates, normal vertices, and face elements from the .obj file\n *\n * @param p - path of .obj file\n\t\t  refGeometricVertices\n\t\t  refTextureCoordinates\n\t\t  refNormalVertices\n\t\t  refFaceElements\n */\nvoid FileIO::LoadObj2( boost::filesystem::path p, std::vector< std::vector< double > > &refGeometricVertices,\n\t\tstd::vector< std::vector< double > > &refTextureCoordinates, std::vector< std::vector<double > > &refNormalVertices,\n\t\tstd::vector< std::vector< std::vector< int > > > &refFaceElements )\n{\n\t\tboost::filesystem::ifstream file( p );\n\t\tstd::string fileLine;\n\n\t\twhile( std::getline( file, fileLine ) )\n\t\t{\n\t\t\tif( fileLine.size( ) > 2 )\n\t\t\t{\n\n\t\t\t\tif( fileLine.at( 0 ) == 'v' && fileLine.at( 1 ) == ' ' )\n\t\t\t\t{\n\t\t\t\t\tstd::vector< double > geometricVertex;\n\t\t\t\t\trefGeometricVertices.push_back( geometricVertex );\n\t\t\t\t\tmParseGeometricVertex( fileLine, refGeometricVertices );\n\t\t\t\t}\n\n\t\t\t\tif( fileLine.at( 0 ) == 'v' && fileLine.at( 1 ) == 't' )\n\t\t\t\t{\n\t\t\t\t\tstd::vector< double > TextureCoordinate;\n\t\t\t\t\trefTextureCoordinates.push_back( TextureCoordinate );\n\t\t\t\t\tmParseTextureCoordinates( fileLine, refTextureCoordinates );\n\t\t\t\t}\n\n\t\t\t\tif( fileLine.at( 0 ) == 'v' && fileLine.at( 1 ) == 'n' )\n\t\t\t\t{\n\t\t\t\t\tstd::vector< double > NormalVertex;\n\t\t\t\t\trefNormalVertices.push_back( NormalVertex );\n\t\t\t\t\tmParseNormalVertex( fileLine, refNormalVertices );\n\t\t\t\t}\n\n\t\t\t\tif( fileLine.at( 0 ) == 'f' && fileLine.at( 1 ) == ' ' )\n\t\t\t\t{\n\t\t\t\t\tmParseFaceElements( fileLine, refFaceElements );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n}\n\n", "meta": {"hexsha": "de955d460e6cef30360f74db246a09af71d21131", "size": 12925, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Source/FileIO.cpp", "max_stars_repo_name": "nhamil/modeler-3d", "max_stars_repo_head_hexsha": "1f5bb3a16cdfc25db1081d8df461685385fa88c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-09-29T23:41:45.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-29T23:41:45.000Z", "max_issues_repo_path": "Source/FileIO.cpp", "max_issues_repo_name": "nhamil/modeler-3d", "max_issues_repo_head_hexsha": "1f5bb3a16cdfc25db1081d8df461685385fa88c4", "max_issues_repo_licenses": ["MIT"], "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/FileIO.cpp", "max_forks_repo_name": "nhamil/modeler-3d", "max_forks_repo_head_hexsha": "1f5bb3a16cdfc25db1081d8df461685385fa88c4", "max_forks_repo_licenses": ["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.7360515021, "max_line_length": 148, "alphanum_fraction": 0.5986073501, "num_tokens": 3954, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389817407017, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.4671756664512468}}
{"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    Rot3.cpp\n * @brief   Rotation, common code between Rotation matrix and Quaternion\n * @author  Alireza Fathi\n * @author  Christian Potthast\n * @author  Frank Dellaert\n * @author  Richard Roberts\n */\n\n#include <gtsam/geometry/Rot3.h>\n#include <gtsam/geometry/SO3.h>\n#include <boost/math/constants/constants.hpp>\n\n#include <cmath>\n#include <random>\n\nusing namespace std;\n\nnamespace gtsam {\n\n/* ************************************************************************* */\nvoid Rot3::print(const std::string& s) const {\n  gtsam::print((Matrix)matrix(), s);\n}\n\n/* ************************************************************************* */\nRot3 Rot3::Random(std::mt19937& rng) {\n  // TODO allow any engine without including all of boost :-(\n  Unit3 axis = Unit3::Random(rng);\n  uniform_real_distribution<double> randomAngle(-M_PI, M_PI);\n  double angle = randomAngle(rng);\n  return AxisAngle(axis, angle);\n}\n\n\n\n/* ************************************************************************* */\nRot3 Rot3::AlignPair(const Unit3& axis, const Unit3& a_p, const Unit3& b_p) {\n  // if a_p is already aligned with b_p, return the identity rotation\n  if (std::abs(a_p.dot(b_p)) > 0.999999999) {\n    return Rot3();\n  }\n\n  // Check axis was not degenerate cross product\n  const Vector3 z = axis.unitVector();\n  if (z.hasNaN())\n    throw std::runtime_error(\"AlignSinglePair: axis has Nans\");\n\n  // Now, calculate rotation that takes b_p to a_p\n  const Matrix3 P = I_3x3 - z * z.transpose();  // orthogonal projector\n  const Vector3 a_po = P * a_p.unitVector();    // point in a orthogonal to axis\n  const Vector3 b_po = P * b_p.unitVector();    // point in b orthogonal to axis\n  const Vector3 x = a_po.normalized();          // x-axis in axis-orthogonal plane, along a_p vector\n  const Vector3 y = z.cross(x);                 // y-axis in axis-orthogonal plane\n  const double u = x.dot(b_po);                 // x-coordinate for b_po\n  const double v = y.dot(b_po);                 // y-coordinate for b_po\n  double angle = std::atan2(v, u);\n  return Rot3::AxisAngle(z, -angle);\n}\n\n/* ************************************************************************* */\nRot3 Rot3::AlignTwoPairs(const Unit3& a_p, const Unit3& b_p,  //\n                         const Unit3& a_q, const Unit3& b_q) {\n  // there are three frames in play:\n  // a: the first frame in which p and q are measured\n  // b: the second frame in which p and q are measured\n  // i: intermediate, after aligning first pair\n\n  // First, find rotation around that aligns a_p and b_p\n  Rot3 i_R_b = AlignPair(a_p.cross(b_p), a_p, b_p);\n\n  // Rotate points in frame b to the intermediate frame,\n  // in which we expect the point p to be aligned now\n  Unit3 i_q = i_R_b * b_q;\n  assert(assert_equal(a_p, i_R_b * b_p, 1e-6));\n\n  // Now align second pair: we need to align i_q to a_q\n  Rot3 a_R_i = AlignPair(a_p, a_q, i_q);\n  assert(assert_equal(a_p, a_R_i * a_p, 1e-6));\n  assert(assert_equal(a_q, a_R_i * i_q, 1e-6));\n\n  // The desired rotation is the product of both\n  Rot3 a_R_b = a_R_i * i_R_b;\n  return a_R_b;\n}\n\n/* ************************************************************************* */\nbool Rot3::equals(const Rot3 & R, double tol) const {\n  return equal_with_abs_tol(matrix(), R.matrix(), tol);\n}\n\n/* ************************************************************************* */\nPoint3 Rot3::operator*(const Point3& p) const {\n  return rotate(p);\n}\n\n/* ************************************************************************* */\nUnit3 Rot3::rotate(const Unit3& p,\n    OptionalJacobian<2,3> HR, OptionalJacobian<2,2> Hp) const {\n  Matrix32 Dp;\n  Unit3 q = Unit3(rotate(p.point3(Hp ? &Dp : 0)));\n  if (Hp) *Hp = q.basis().transpose() * matrix() * Dp;\n  if (HR) *HR = -q.basis().transpose() * matrix() * p.skew();\n  return q;\n}\n\n/* ************************************************************************* */\nUnit3 Rot3::unrotate(const Unit3& p,\n    OptionalJacobian<2,3> HR, OptionalJacobian<2,2> Hp) const {\n  Matrix32 Dp;\n  Unit3 q = Unit3(unrotate(p.point3(Dp)));\n  if (Hp) *Hp = q.basis().transpose() * matrix().transpose () * Dp;\n  if (HR) *HR = q.basis().transpose() * q.skew();\n  return q;\n}\n\n/* ************************************************************************* */\nUnit3 Rot3::operator*(const Unit3& p) const {\n  return rotate(p);\n}\n\n/* ************************************************************************* */\n// see doc/math.lyx, SO(3) section\nPoint3 Rot3::unrotate(const Point3& p, OptionalJacobian<3,3> H1,\n    OptionalJacobian<3,3> H2) const {\n  const Matrix3& Rt = transpose();\n  Point3 q(Rt * p); // q = Rt*p\n  const double wx = q.x(), wy = q.y(), wz = q.z();\n  if (H1)\n    *H1 << 0.0, -wz, +wy, +wz, 0.0, -wx, -wy, +wx, 0.0;\n  if (H2)\n    *H2 = Rt;\n  return q;\n}\n\n/* ************************************************************************* */\nPoint3 Rot3::column(int index) const{\n  if(index == 3)\n    return r3();\n  else if(index == 2)\n    return r2();\n  else if(index == 1)\n    return r1(); // default returns r1\n  else\n    throw invalid_argument(\"Argument to Rot3::column must be 1, 2, or 3\");\n}\n\n/* ************************************************************************* */\nVector3 Rot3::xyz() const {\n  Matrix3 I;Vector3 q;\n  boost::tie(I,q)=RQ(matrix());\n  return q;\n}\n\n/* ************************************************************************* */\nVector3 Rot3::ypr() const {\n  Vector3 q = xyz();\n  return Vector3(q(2),q(1),q(0));\n}\n\n/* ************************************************************************* */\nVector3 Rot3::rpy() const {\n  return xyz();\n}\n\n/* ************************************************************************* */\nVector Rot3::quaternion() const {\n  gtsam::Quaternion q = toQuaternion();\n  Vector v(4);\n  v(0) = q.w();\n  v(1) = q.x();\n  v(2) = q.y();\n  v(3) = q.z();\n  return v;\n}\n\n/* ************************************************************************* */\nMatrix3 Rot3::ExpmapDerivative(const Vector3& x) {\n  return SO3::ExpmapDerivative(x);\n}\n\n/* ************************************************************************* */\nMatrix3 Rot3::LogmapDerivative(const Vector3& x)    {\n  return SO3::LogmapDerivative(x);\n}\n\n/* ************************************************************************* */\npair<Matrix3, Vector3> RQ(const Matrix3& A) {\n\n  double x = -atan2(-A(2, 1), A(2, 2));\n  Rot3 Qx = Rot3::Rx(-x);\n  Matrix3 B = A * Qx.matrix();\n\n  double y = -atan2(B(2, 0), B(2, 2));\n  Rot3 Qy = Rot3::Ry(-y);\n  Matrix3 C = B * Qy.matrix();\n\n  double z = -atan2(-C(1, 0), C(1, 1));\n  Rot3 Qz = Rot3::Rz(-z);\n  Matrix3 R = C * Qz.matrix();\n\n  Vector xyz = Vector3(x, y, z);\n  return make_pair(R, xyz);\n}\n\n/* ************************************************************************* */\nostream &operator<<(ostream &os, const Rot3& R) {\n  os << \"\\n\";\n  os << '|' << R.r1().x() << \", \" << R.r2().x() << \", \" << R.r3().x() << \"|\\n\";\n  os << '|' << R.r1().y() << \", \" << R.r2().y() << \", \" << R.r3().y() << \"|\\n\";\n  os << '|' << R.r1().z() << \", \" << R.r2().z() << \", \" << R.r3().z() << \"|\\n\";\n  return os;\n}\n\n/* ************************************************************************* */\nRot3 Rot3::slerp(double t, const Rot3& other) const {\n  return interpolate(*this, other, t);\n}\n\n/* ************************************************************************* */\n\n} // namespace gtsam\n\n", "meta": {"hexsha": "b1e8dd14b03fabb135659931a53f014c1063d364", "size": 7711, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/geometry/Rot3.cpp", "max_stars_repo_name": "ori-drs/gtsam", "max_stars_repo_head_hexsha": "4294f6852e13c51215d96a9de7acc680116cb100", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gtsam/geometry/Rot3.cpp", "max_issues_repo_name": "ori-drs/gtsam", "max_issues_repo_head_hexsha": "4294f6852e13c51215d96a9de7acc680116cb100", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-03-02T17:39:13.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-02T17:39:13.000Z", "max_forks_repo_path": "gtsam/geometry/Rot3.cpp", "max_forks_repo_name": "ori-drs/gtsam", "max_forks_repo_head_hexsha": "4294f6852e13c51215d96a9de7acc680116cb100", "max_forks_repo_licenses": ["BSD-3-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.8127659574, "max_line_length": 100, "alphanum_fraction": 0.4723122812, "num_tokens": 2041, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389817407017, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.4671756664512468}}
{"text": "/*\n * Copyright 2015 Christoph Jud (christoph.jud@unibas.ch)\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 <memory>\n#include <ctime>\n#include <cmath>\n\n#include <boost/random.hpp>\n\n#include \"GaussianProcess.h\"\n#include \"Kernel.h\"\n#include \"MatrixIO.h\"\n\nusing namespace gpr;\n\n\ntemplate<typename T>\nvoid Test1(){\n    /*\n     * Test 1.1: perform regression\n     * Test 1.2: save/load product kernel\n     */\n    std::cout << \"Test 1.1: regression test with product kernel... \" << std::flush;\n\n\n    // typedefs\n    typedef GaussianKernel<T>                   GaussianKernelType;\n    typedef std::shared_ptr<GaussianKernelType> GaussianKernelTypePointer;\n    typedef PeriodicKernel<T>                   PeriodicKernelType;\n    typedef std::shared_ptr<PeriodicKernelType> PeriodicKernelTypePointer;\n    typedef ProductKernel<T>                    ProductKernelType;\n    typedef std::shared_ptr<ProductKernelType>  ProductKernelTypePointer;\n\n    typedef GaussianProcess<T>                  GaussianProcessType;\n    typedef std::shared_ptr<GaussianProcessType>GaussianProcessTypePointer;\n\n    typedef typename GaussianProcessType::VectorType     VectorType;\n    typedef typename GaussianProcessType::MatrixType     MatrixType;\n\n\n    // ground truth function\n    auto f = [](double x)->double { return x/2.0 * std::sin(x)*std::cos(2.2*std::sin(x)); };\n\n    double interval_start = 0;\n    double interval_end = 5 * 2*M_PI; // full interval\n    double interval_step = 0.1;\n\n    //--------------------------------------------------------------------------------\n    // generating ground truth\n    unsigned gt_size = (interval_end-interval_start) / interval_step;\n    VectorType y(gt_size);\n    for(unsigned i=0; i<gt_size; i++){\n        y[i] = f(interval_start + i*interval_step);\n    }\n\n\n    //--------------------------------------------------------------------------------\n    // perform training\n    double noise = 0.04;\n    static boost::minstd_rand randgen(static_cast<unsigned>(time(0)));\n    static boost::normal_distribution<> dist(0, noise);\n    static boost::variate_generator<boost::minstd_rand, boost::normal_distribution<> > r(randgen, dist);\n\n    double interval_training_end = 3 * 2*M_PI; // interval to train\n    unsigned number_of_samples = 50;\n\n    PeriodicKernelTypePointer   pk(new PeriodicKernelType(5, 0.5, 0.4));\n    GaussianKernelTypePointer   gk(new GaussianKernelType(65, 10));\n    ProductKernelTypePointer    cpk(new ProductKernelType(pk, gk));\n\n    GaussianProcessTypePointer gp(new GaussianProcessType(cpk));\n    gp->SetSigma(noise);\n\n    // add samples\n    double training_step_size = (interval_training_end - interval_start) / number_of_samples;\n    for(unsigned i=0; i<number_of_samples; i++){\n        VectorType x(1);\n        x(0) = interval_start + i*training_step_size;\n\n        VectorType y(1);\n        y(0) = f(x(0)) + r();\n\n        gp->AddSample(x, y);\n    }\n    gp->Initialize();\n\n\n    //--------------------------------------------------------------------------------\n    // predict full intervall\n    VectorType y_predict(gt_size);\n    for(unsigned i=0; i<gt_size; i++){\n        VectorType x(1);\n        x(0) = interval_start + i*interval_step;\n        y_predict[i] = gp->Predict(x)(0);\n    }\n\n\n    double err = (y-y_predict).norm() / gt_size;\n    if(err>0.02){\n        std::stringstream ss; ss<<err; throw ss.str();\n    }\n    else{\n        std::cout << \" [passed].\" << std::endl;\n    }\n\n    std::cout << \"Test 1.2: save/load product kernel... \" << std::flush;\n\n    gp->Save(\"/tmp/gp_io_test-\");\n\n\n    GaussianKernelTypePointer k_dummy(new GaussianKernelType(1, 1));\n    GaussianProcessTypePointer gp_read(new GaussianProcessType(k_dummy));\n    gp_read->Load(\"/tmp/gp_io_test-\");\n\n    if(*gp.get() == *gp_read.get()){\n        std::cout << \" [passed].\" << std::endl;\n    }\n    else{\n        throw std::string(\"gps are not equal\");\n    }\n}\n\n\ntemplate<typename T>\nvoid Test2(){\n    // typedefs\n    typedef GaussianKernel<T>                   GaussianKernelType;\n    typedef std::shared_ptr<GaussianKernelType>         GaussianKernelTypePointer;\n    typedef PeriodicKernel<T>                   PeriodicKernelType;\n    typedef std::shared_ptr<PeriodicKernelType>         PeriodicKernelTypePointer;\n    typedef ProductKernel<T>                        ProductKernelType;\n    typedef std::shared_ptr<ProductKernelType>      ProductKernelTypePointer;\n\n\n    PeriodicKernelTypePointer   pk(new PeriodicKernelType(0.59, 0.5, 0.4));\n    GaussianKernelTypePointer   gk(new GaussianKernelType(132, M_PI));\n    ProductKernelTypePointer        sk(new ProductKernelType(pk, gk));\n\n    ProductKernelTypePointer sk2(new ProductKernelType(PeriodicKernelTypePointer(new PeriodicKernelType(1, 1, 1)),\n                                               GaussianKernelTypePointer(new GaussianKernelType(1, 1))));\n\n    sk2->SetParameters(sk->GetParameters());\n\n    if((*sk) != (*sk2)){\n        throw std::string(\"kernels are not equal\");\n    }\n    else{\n        std::cout << \" [passed].\" << std::endl;\n    }\n\n}\n\nint main (int argc, char *argv[]){\n\n    try{\n        std::cout << \"Test 1: Product kernel test (float): \" << std::endl;\n        Test1<float>();\n        std::cout << \"Test 1: Product kernel test (double): \" << std::endl;\n        Test1<double>();\n\n        std::cout << \"Test 2: parameter test with product kernel (float) \" << std::flush;\n        Test2<float>();\n        std::cout << \"Test 2: parameter test with product kernel (double) \" << std::flush;\n        Test2<double>();\n    }\n    catch(std::string& s){\n        std::cout << \"[failed] Error: \" << s << std::endl;\n        return -1;\n    }\n\n    return 0;\n}\n\n\n", "meta": {"hexsha": "8d1b04dfe2550e5e10d241de3d1fbc051068ca42", "size": 6171, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/ProductKernelTest.cpp", "max_stars_repo_name": "ChristophJud/GPR", "max_stars_repo_head_hexsha": "62c60aca697ae7614356b1f6db06568f0c4085d2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2015-04-20T14:30:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-18T21:44:06.000Z", "max_issues_repo_path": "tests/ProductKernelTest.cpp", "max_issues_repo_name": "ChristophJud/GPR", "max_issues_repo_head_hexsha": "62c60aca697ae7614356b1f6db06568f0c4085d2", "max_issues_repo_licenses": ["Apache-2.0"], "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/ProductKernelTest.cpp", "max_forks_repo_name": "ChristophJud/GPR", "max_forks_repo_head_hexsha": "62c60aca697ae7614356b1f6db06568f0c4085d2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2015-11-16T00:50:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-23T02:00:18.000Z", "avg_line_length": 32.4789473684, "max_line_length": 114, "alphanum_fraction": 0.6174039864, "num_tokens": 1491, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.46717566310933384}}
{"text": "/* ----------------------------------------------------------------------------\n\n * amsi Copyright 2019, Positioning and Navigation Laboratory,\n * Hong Kong Polytechnic University\n * All Rights Reserved\n * Authors: Weisong Wen, et al. (see THANKS for the full author list)\n\n * See LICENSE for the license information\n\n * -------------------------------------------------------------------------- */\n\n/**\n * @file gps_imu_loose_ekf.cpp\n * @brief fuse gps (ENU) and imu (ENU) using ekf (loosely coupling)\n * @author Weisong Wen (weisong.wen@connect.polyu.hk)\n */\n\n/**\n * Example of use of the imuFactors (imuFactor and combinedImuFactor) in conjunction with GPS\n \n *  - we read IMU and GPS data from rosbag, with the following format:\n *  A topic with \"/imu/data\" is an imu measurement\n *  linAccN, linAccE, linAccD, angVelN, angVelE, angVelD\n *  A topic with \"/ublox_gps_node/fix\" is a gps correction formatted with\n *  lat, lon, altitude\n */\n#include <ros/ros.h>\n#include <visualization_msgs/MarkerArray.h>\n#include <vector>\n#include <iostream>\n\n#include <Eigen/Dense>\n#include<Eigen/Core>\n#include<Eigen/Geometry>\n// fstream\n#include <fstream>\n#include<sstream>\n#include <stdlib.h>\n#include <iomanip>\n\n#include <tf/tf.h>\n#include <tf/transform_broadcaster.h>\n#include <tf/transform_datatypes.h>\n#include <tf/transform_listener.h>\n\n\n// math\n#include <math.h>\n//time \n#include <time.h>\n//algorithm \n#include <algorithm>\n// Define Infinite (Using INT_MAX caused overflow problems)\n\n#include <ros/ros.h>\n#include <std_msgs/Bool.h>\n#include <nav_msgs/Odometry.h>\n#include <sensor_msgs/Imu.h>\n#include <sensor_msgs/PointCloud2.h>\n#include <sensor_msgs/NavSatFix.h>\n#include <novatel_msgs/BESTPOS.h> // novatel_msgs/INSPVAX\n\n#include <amsi/gnss_tools.hpp>\n\n\n#include <std_msgs/Time.h>\n#include <nav_msgs/Odometry.h>\n#include <nmea_msgs/Sentence.h>\n#include <sensor_msgs/PointCloud2.h>\n#include <geographic_msgs/GeoPointStamped.h>\n#include <visualization_msgs/MarkerArray.h>\n\n\n#include <amsi/gnss_tools.hpp>\n\n\n\n#define INF 10000\n#define pi 3.1415926\n\nusing namespace Eigen;\n\nusing namespace std;\n\nFILE* fp_out_loose_ekf = fopen(\"/home/husai/gps_imu_loose_ekf.csv\", \"w+\");\n\n// FILE* generateData = fopen(\"/home/wenws/libRSF/datasets/smartLoc/data_kowloon_rang3.txt\", \"w+\");\n\n// FILE* generateData_odom = fopen(\"/home/wenws/libRSF/datasets/smartLoc/data_kowloon_odom.txt\", \"w+\");\n\n// FILE* generateData_gt3 = fopen(\"/home/wenws/libRSF/datasets/smartLoc/data_kowloon_gt3.txt\", \"w+\");\n\n// FILE* generateData_imu = fopen(\"/home/wenws/libRSF/datasets/smartLoc/data_kowloon_imu.txt\", \"w+\");\n\n\n\n\n\n\n\nclass ekf_loose\n{\n  ros::NodeHandle nh;\n\npublic:\n\n  typedef struct\n  {\n    double wx;\n    double wy;\n    double wz;\n    double ax;\n    double ay;\n    double az;\n  }imu_bias; // imu bias\n\n  typedef struct\n  {\n    double wx;\n    double wy;\n    double wz;\n    double ax;\n    double ay;\n    double az;\n  }imu_noise; // imu bias\n\n  typedef struct\n  {\n    imu_bias bias;\n    imu_noise noise;\n  }imu_para; // imu bias\n\n  typedef struct\n  {\n    double mean;\n    double std;\n  }statistical_para; // imu bias || positioning evaluation\n\n\n  typedef struct\n  {\n    double x;\n    double y;\n    double z;\n    double ID;\n  }bp; // building point \n\n  ros::Subscriber imu_sub;\n  ros::Subscriber gps_sub;\n  ros::Subscriber gps_raw_sub;\n  ros::Subscriber span_BP_sub, dgps_nmea_sub;\n\n  ros::Publisher ekf_loose_Pose_pub;\n  ros::Publisher ekf_GNSS_odom_pub;\n  ros::Publisher ekf_span_odom_pub;\n  ros::Publisher gnss_navsat_pose_pub;\n\n  sensor_msgs::Imu imu_track;\n  bool imu_up =0 ;\n  int imu_co=0;\n\n  bool gps_up = 0;\n  nav_msgs::Odometry odom_track; // GNSS SPP in ENU\n  nav_msgs::Odometry span_odom; // span_cpt in ENU\n  double span_gps_week_sec = 0;\n  nav_msgs::Odometry ekf_pose_odom; // ekf pose in ENU\n  // gnss_tools\n  GNSS_Tools gnss_tools_;\n  Eigen::MatrixXd originllh,originllh_span; // origin llh\n  Eigen::MatrixXd referencellh; // origin llh\n  sensor_msgs::NavSatFix ini_navf,ini_navf_span ; // initial sensor msg\n\n  imu_bias offline_cal= {-0.00231128, 0.0019349, -0.000309033, \n                        -0.0000563799, -0.0004587, 0.0979159}; // offiline calibrated imu bias and noise\n\n  imu_para imu_parameter; // online calibrated imu parameters using begin 2000 frames of imu raw measurements\n  bool use_online_imu_cal = 1;\n  bool online_cal_success = 0;\n  vector<sensor_msgs::Imu> imu_queue;\n  int imu_queue_size = 100;\n\n  // EKF related parameters\n  Eigen::MatrixXd imu_noise_matrix;\n\n  Eigen::MatrixXd Q_matrix, G_matrix, sigma_matrix, R_matrix, K_matrix, H_matrix, orientation_matrix, acceleration_rotation;\n \n  VectorXd ekf_state; // state:  px, py, pz, vx, vy, vz, bax, bzy, baz\n  VectorXd ekf_u_t; // ax, ay, az\n  VectorXd ekf_z_t; // px, py, pz\n\n  double prediction_pre_t=0;\n\n  vector<double> posi_err, posi_err_gps;\n\n  Eigen::MatrixXd span_ecef; // \n\n  double nstamps_ = 0;\n\n  double x,y,z,w;\n\n\n\npublic:\n  /**\n   * @brief constructor\n   * @param imu_msg\n   */\n  ekf_loose(bool state)\n  {\n    std::cout<<\"----------------constructor-----------------\"<<std::endl;\n    // imu_sub = nh.subscribe(\"/imu/data\", 50, &ekf_loose::imu_callback,this); // imu_rt\n    imu_sub = nh.subscribe(\"/imu_raw\", 50, &ekf_loose::imu_callback,this); // imu_rt\n    gps_sub = nh.subscribe(\"/ublox_gps_node/fix\", 50, &ekf_loose::ubloxFix_callback,this); \n    dgps_nmea_sub =nh.subscribe(\"/nmea_sentence\", 50, &ekf_loose::nmea_callback,this);\n\n    gnss_navsat_pose_pub = nh.advertise<sensor_msgs::NavSatFix>(\"/ublox_gps_node/fix2\", 10);\n\n    ekf_loose_Pose_pub = nh.advertise<nav_msgs::Odometry>(\"/ekf_loose_Pose\", 10);\n    ekf_GNSS_odom_pub = nh.advertise<nav_msgs::Odometry>(\"/ekf_gnss_odom\", 10);\n    ekf_span_odom_pub = nh.advertise<nav_msgs::Odometry>(\"/ekf_span_odom\", 10);\n\n    onInitEKF(); // initialize EKF related parameters\n    // fprintf(fp_out_loose_ekf, \"%s ,%s ,%s ,%s ,%s ,%s, %s, %s, %s \\n\", \"epoch\", \"GPS_Eror\", \"GPS_IMU_loose__Eror\", \"gps_E\", \"gps_N\", \"loose_E\", \"loose_N\", \"Gt_E\", \"Gt_N\");\n    // fprintf(generateData, \"%s %s %s %s %s %s %s %s %s \\n\", \"epoch\", \"GPS_Eror\", \"GPS_IMU_loose__Eror\", \"gps_E\", \"gps_N\", \"loose_E\", \"loose_N\", \"Gt_E\", \"Gt_N\");\n    \n\n  }\n\n  ~ekf_loose()\n  {\n  }\n\n\n  /**\n   * @brief imu callback\n   * @param imu msg\n   * @return void\n   @ \n   */\n  void onInitEKF(void)\n  {\n    ekf_state.resize(9);\n    ekf_state << 0,0,0,\n                 0,0,0,\n                 0,0,0;\n    \n    ekf_u_t.resize(3);\n    ekf_u_t << 0,0,0;\n\n    ekf_z_t.resize(3);\n    ekf_z_t << 0,0,0;\n\n    Q_matrix.resize(9,9);\n    Q_matrix << 0.0002, 0, 0, 0, 0, 0, 0, 0, 0,\n                0, 0.0002, 0, 0, 0, 0, 0, 0, 0,\n                0, 0, 0.0002, 0, 0, 0, 0, 0, 0,\n                0, 0, 0, 0.0001, 0, 0, 0, 0, 0,\n                0, 0, 0, 0, 0.0001, 0, 0, 0, 0,\n                0, 0, 0, 0, 0, 0.0001, 0, 0, 0,\n                0, 0, 0, 0, 0, 0, 0.05, 0, 0,\n                0, 0, 0, 0, 0, 0, 0, 0.05, 0,\n                0, 0, 0, 0, 0, 0, 0, 0, 0.05; \n    Q_matrix = Q_matrix * 1;\n\n    sigma_matrix.resize(9,9);\n    sigma_matrix << 3.0, 0, 0, 0, 0, 0, 0, 0, 0,\n                    0, 3.0, 0, 0, 0, 0, 0, 0, 0,\n                    0, 0, 3.2, 0, 0, 0, 0, 0, 0,\n                    0, 0, 0, 0.3, 0, 0, 0, 0, 0,\n                    0, 0, 0, 0, 0.3, 0, 0, 0, 0,\n                    0, 0, 0, 0, 0, 0.3, 0, 0, 0,\n                    0, 0, 0, 0, 0, 0, 0.07, 0, 0,\n                    0, 0, 0, 0, 0, 0, 0, 0.07, 0,\n                    0, 0, 0, 0, 0, 0, 0, 0, 0.07; \n    \n    G_matrix.resize(9,9);\n\n    R_matrix.resize(3,3);\n    R_matrix << 50,0,0,\n                0,50,0,\n                0,0,50;\n\n    K_matrix.resize(9,3);\n    H_matrix.resize(3,9);\n    H_matrix << 1, 0, 0, 0, 0, 0, 0, 0, 0,\n                0, 1, 0, 0, 0, 0, 0, 0, 0,\n                0, 0, 1, 0, 0, 0, 0, 0, 0;\n  }\n\n  /**\n   * @brief imu callback\n   * @param imu msg\n   * @return void\n   @ \n   */\n  void imu_callback(const sensor_msgs::Imu::Ptr& input)\n  {\n    // std::cout << \" IMU data call back\" << input->angular_velocity.x << std::endl;\n    imu_track = * input;\n    x = imu_track.orientation.x;\n    y = imu_track.orientation.y;\n    z = imu_track.orientation.z;\n    w = imu_track.orientation.w;\n\n    double imu_roll, imu_pitch, imu_yaw;\n    tf::Quaternion imu_orientation;\n    tf::quaternionMsgToTF(input->orientation, imu_orientation);\n    tf::Matrix3x3(imu_orientation).getRPY(imu_roll, imu_pitch, imu_yaw);\n    cout<<\"yaw : = \" <<imu_yaw*(180/3.14)<<endl;\n    // cout<<imu_track.orientation.x<<endl;\n    cout<<\"imu_track.linear_acceleration.x : = \" <<endl<<imu_track.linear_acceleration.x<<endl;\n    \n    Eigen::Quaterniond q(w,x,y,z);\n    q.normalized();\n    Eigen::Matrix3d rotation_matrix;\n    rotation_matrix=q.toRotationMatrix();\n    orientation_matrix.resize(3,1);\n    orientation_matrix<<imu_track.linear_acceleration.x,\n                        imu_track.linear_acceleration.y,\n                        imu_track.linear_acceleration.z;\n    acceleration_rotation = rotation_matrix.transpose() * orientation_matrix;\n\n    cout<<\"acceleration_rotation : = \" <<endl<<acceleration_rotation<<endl;\n    imu_track.linear_acceleration.x = acceleration_rotation(0,0);\n    imu_track.linear_acceleration.y = acceleration_rotation(1,0);\n    imu_track.linear_acceleration.z = acceleration_rotation(2,0);\n    cout<<\"imu_track.linear_acceleration.x after rotation: = \" <<endl<<imu_track.linear_acceleration.x<<endl;\n    cout<<\"imu_track.linear_acceleration.y after rotation: = \" <<endl<<imu_track.linear_acceleration.y<<endl;\n    cout<<\"imu_track.linear_acceleration.z after rotation: = \" <<endl<<imu_track.linear_acceleration.z<<endl;\n    cout<<\"-----------------------------\" <<endl;\n\n\n    imu_queue.push_back(imu_track);\n    // cout<<\"imu_queue_size -> \"<<imu_queue.size()<<endl;\n    if( (imu_queue.size() > imu_queue_size) && (online_cal_success ==0) && (use_online_imu_cal ==1))\n    {\n      online_cal_success = 1;\n      const clock_t begin_time = clock();\n      cout<<\"-------------------start calibrate imu------------------------ \"<<endl;\n      imu_parameter = imu_calibtation(imu_queue);\n      std::cout << \"imu Calibration used  time -> \" << double(clock() - begin_time) / CLOCKS_PER_SEC << \"\\n\\n\";\n      // cout<<\"bias ax ->\" <<imu_parameter.bias.ax<<endl;\n      // cout<<\"bias ay ->\" <<imu_parameter.bias.ay<<endl;\n      // cout<<\"bias az ->\" <<imu_parameter.bias.az<<endl;\n\n      // cout<<\"bias wx ->\" <<imu_parameter.bias.wx<<endl;\n      // cout<<\"bias wy ->\" <<imu_parameter.bias.wy<<endl;\n      // cout<<\"bias wz ->\" <<imu_parameter.bias.wz<<endl;\n    }\n    if(use_online_imu_cal)\n    {\n        // decrease the bias \n      imu_track.angular_velocity.x = imu_track.angular_velocity.x - (imu_parameter.bias.wx);\n      imu_track.angular_velocity.y = imu_track.angular_velocity.y - (imu_parameter.bias.wy);\n      imu_track.angular_velocity.z = imu_track.angular_velocity.z - (imu_parameter.bias.wz);\n\n      imu_track.linear_acceleration.x = imu_track.linear_acceleration.x - (imu_parameter.bias.ax);\n      imu_track.linear_acceleration.y = imu_track.linear_acceleration.y - (imu_parameter.bias.ay);\n      imu_track.linear_acceleration.z = imu_track.linear_acceleration.z - (imu_parameter.bias.az);\n    }\n    else if(!use_online_imu_cal) // if do not online calibrate, use offiline calibration (1h statistical static data)\n    {\n        // decrease the bias \n      imu_track.angular_velocity.x = imu_track.angular_velocity.x - (-0.00231128);\n      imu_track.angular_velocity.y = imu_track.angular_velocity.y - (0.0019349);\n      imu_track.angular_velocity.z = imu_track.angular_velocity.z - (-0.000309033);\n\n      imu_track.linear_acceleration.x = imu_track.linear_acceleration.x - (-0.0000563799);\n      imu_track.linear_acceleration.y = imu_track.linear_acceleration.y - (-0.0004587);\n      imu_track.linear_acceleration.z = imu_track.linear_acceleration.z - (0.0979159);\n    }\n    \n    \n\n    imu_up =1;\n    imu_co++;\n\n    ekf_u_t(0) = imu_track.linear_acceleration.x;\n    ekf_u_t(1) = imu_track.linear_acceleration.y;\n    ekf_u_t(2) = imu_track.linear_acceleration.z;\n\n    if(prediction_pre_t == 0)\n    {\n      prediction_pre_t = imu_track.header.stamp.toSec();\n    }\n\n    double delta_t = imu_track.header.stamp.toSec() -  prediction_pre_t;\n\n\n    if(online_cal_success)\n    {\n      // cout<< \"delta_t-> \"<<delta_t;\n        // position prediction\n      ekf_state(0) = ekf_state(0) + ekf_state(3) * delta_t + 1/2 * (ekf_u_t(0) - \n        ekf_state(6)) * pow(delta_t, 2);\n      ekf_state(1) = ekf_state(1) + ekf_state(4) * delta_t + 1/2 * (ekf_u_t(1) - \n        ekf_state(7)) * pow(delta_t, 2);\n      ekf_state(2) = ekf_state(2) + ekf_state(5) * delta_t + 1/2 * (ekf_u_t(2) - \n        ekf_state(8)) * pow(delta_t, 2);\n\n      // velocity estimation\n      ekf_state(3) = ekf_state(3) + (ekf_u_t(0) - ekf_state(6)) * delta_t;\n      ekf_state(4) = ekf_state(4) + (ekf_u_t(1) - ekf_state(7)) * delta_t;\n      ekf_state(5) = ekf_state(5) + (ekf_u_t(2) - ekf_state(8)) * delta_t;\n\n      // bias prediction\n      ekf_state(6) = ekf_state(6);\n      ekf_state(7) = ekf_state(7);\n      ekf_state(8) = ekf_state(8);\n\n      G_matrix << 1, 0, 0, delta_t, 0, 0, -1/2 * pow(delta_t,2), 0, 0,\n                  0, 1, 0, 0, delta_t, 0, 0, -1/2 * pow(delta_t,2), 0,\n                  0, 0, 1, 0, 0, delta_t, 0, 0, -1/2 * pow(delta_t,2),\n                  0, 0, 0, 1, 0, 0, -delta_t, 0, 0,\n                  0, 0, 0, 0, 1, 0, 0, -delta_t, 0,\n                  0, 0, 0, 0, 0, 1, 0, 0, -delta_t,\n                  0, 0, 0, 0, 0, 0, 1, 0, 0,\n                  0, 0, 0, 0, 0, 0, 0, 1, 0,\n                  0, 0, 0, 0, 0, 0, 0, 0, 1; \n\n      // sigma matrix prediction\n      sigma_matrix = G_matrix * sigma_matrix * G_matrix.transpose() + Q_matrix;\n      // cout<< \"sigma_matrix-> \"<<sigma_matrix<<endl;\n\n      ekf_pose_odom.header = imu_track.header;\n      ekf_pose_odom.header.frame_id = \"odom\";\n      ekf_pose_odom.pose.pose.position.x = ekf_state(0);\n      ekf_pose_odom.pose.pose.position.y = ekf_state(1);\n      ekf_pose_odom.pose.pose.position.z = ekf_state(2);\n      // ekf_loose_Pose_pub.publish(ekf_pose_odom);\n    }\n\n    prediction_pre_t = imu_track.header.stamp.toSec();\n  }\n\n   /**\n   * @brief imu bias, noise calculation (calibration)\n   * @param imu queue \n   * @return imu_para\n   @ \n   */\n  imu_para imu_calibtation(vector<sensor_msgs::Imu> input)\n  {\n    imu_para para; // bias + noise\n    imu_bias bias; // bias of imu \n    imu_noise noise; // noise of imu\n\n    // cout<<\"imu bias calculation (calibration)\"<<endl;\n    vector<double> wx_queue;\n    double wx_sum = 0, wx_mean = 0;\n\n    vector<double> wy_queue;\n    double wy_sum = 0, wy_mean = 0;\n\n    vector<double> wz_queue;\n    double wz_sum = 0, wz_mean = 0;\n\n    vector<double> ax_queue;\n    double ax_sum = 0, ax_mean = 0;\n\n    vector<double> ay_queue;\n    double ay_sum = 0, ay_mean = 0;\n\n    vector<double> az_queue;\n    double az_sum = 0, az_mean = 0;\n\n    for(int i = 0; i < input.size()-1; i ++)\n    {\n      wx_queue.push_back(input[i].angular_velocity.x);\n      wy_queue.push_back(input[i].angular_velocity.y);\n      wz_queue.push_back(input[i].angular_velocity.z);\n\n      ax_queue.push_back(input[i].linear_acceleration.x);\n      ay_queue.push_back(input[i].linear_acceleration.y);\n      az_queue.push_back(input[i].linear_acceleration.z);\n    }\n\n    statistical_para result = statis_cal(wx_queue);\n    para.bias.wx = result.mean;\n    para.noise.wx = result.std;\n\n    result = statis_cal(wy_queue);\n    para.bias.wy = result.mean;\n    para.noise.wy = result.std;\n\n    result = statis_cal(wz_queue);\n    para.bias.wz = result.mean;\n    para.noise.wz = result.std;\n\n    result = statis_cal(ax_queue);\n    para.bias.ax = result.mean;\n    para.noise.ax = result.std;\n\n    result = statis_cal(ay_queue);\n    para.bias.ay = result.mean;\n    para.noise.ay = result.std;\n\n    result = statis_cal(az_queue);\n    para.bias.az = result.mean;\n    para.noise.az = result.std;\n\n    return para;\n  }\n\n  /**\n   * @brief statistical parameters inference\n   * @param vector<double>  \n   * @return statistical_para\n   @ \n   */\n  statistical_para statis_cal(vector<double> input)\n  {\n    statistical_para result;\n    double sum = std::accumulate(std::begin(input), std::end(input), 0.0);\n    double mean =  sum / input.size(); \n   \n    double accum  = 0.0;\n    std::for_each (std::begin(input), std::end(input), [&](const double d) {\n      accum  += (d-mean)*(d-mean);\n    });\n   \n    double stdev = sqrt(accum/(input.size()-1));\n\n    result.mean = mean;\n    result.std = stdev;\n    return result;\n  }\n\n \n\nvoid nmea_callback(const nmea_msgs::SentenceConstPtr& nmea_msg) {\n    std::vector<std::string> str_vec_ptr;\n    std::string token;\n    std::stringstream ss(nmea_msg->sentence);\n    bool find_SOL_COMPUTED =0;\n    while (getline(ss, token, ' '))\n    {\n      if(token == \"SOL_COMPUTED\") // solutions are computed \n      {\n        // std::cout<<\"message obtained\"<<std::endl;\n        find_SOL_COMPUTED = true;\n      }\n      if( find_SOL_COMPUTED ) // find flag SOL_COMPUTED\n      {\n        str_vec_ptr.push_back(token);\n      }\n    }\n        if(find_SOL_COMPUTED)\n    {\n      sensor_msgs::NavSatFix navfix_ ;\n      navfix_.header = nmea_msg->header;\n      std::cout << std::setprecision(17);\n      double lat = strtod((str_vec_ptr[2]).c_str(), NULL);\n      double lon = strtod((str_vec_ptr[3]).c_str(), NULL);\n      double alt = strtod((str_vec_ptr[4]).c_str(), NULL);\n      std::cout << std::setprecision(17);\n\n      navfix_.latitude = lat;\n      navfix_.longitude = lon;\n      navfix_.altitude = alt;\n      if(ini_navf.latitude == NULL)\n      {\n        ini_navf = navfix_;\n        std::cout<<\"ini_navf.header  -> \"<<ini_navf.header<<std::endl;\n        originllh_span.resize(3, 1); \n        originllh_span(0) = navfix_.longitude;\n        originllh_span(1) = navfix_.latitude;\n        originllh_span(2) = navfix_.altitude;\n        std::cout<<\"reference longitude: \"<<navfix_.longitude<<std::endl;\n        std::cout<<\"reference latitude: \"<<navfix_.latitude<<std::endl;\n      }\n      Eigen::MatrixXd curLLh; // \n      curLLh.resize(3, 1);\n      curLLh(0) = navfix_.longitude;\n      curLLh(1) = navfix_.latitude;\n      curLLh(2) = navfix_.altitude;\n\n      Eigen::MatrixXd ecef; // \n      ecef.resize(3, 1);\n      ecef = gnss_tools_.llh2ecef(curLLh);\n      Eigen::MatrixXd eigenENU;; // \n      eigenENU.resize(3, 1);\n      eigenENU = gnss_tools_.ecef2enu(originllh_span,ecef);\n\n      span_odom.header.frame_id = \"odom\";\n      span_odom.pose.pose.position.x = eigenENU(0);\n      span_odom.pose.pose.position.y = eigenENU(1);\n      span_odom.pose.pose.position.z = eigenENU(2);\n      span_odom.pose.pose.orientation.x = 0;\n      span_odom.pose.pose.orientation.y = 0;\n      span_odom.pose.pose.orientation.z = 0;\n      span_odom.pose.pose.orientation.w = 0;\n      ekf_span_odom_pub.publish(span_odom);\n\n      std::cout<<\"push back message to gps_queue...\"<<std::endl;\n    }\n  }\n\n\n\n  /**\n   * @brief gps callback\n   * @param gps fix msg\n   * @return void\n   @ \n   */\n  void ubloxFix_callback(const sensor_msgs::NavSatFixConstPtr& fix_msg) // update \n  {\n    cout<<\"ubloxFix_callback received \"<<endl;\n    sensor_msgs::NavSatFix navfix_ ;\n    navfix_.header = fix_msg->header;\n    navfix_.latitude = fix_msg->latitude;\n    navfix_.longitude = fix_msg->longitude;\n    navfix_.altitude = fix_msg->altitude;\n\n    if(ini_navf.latitude == NULL)\n      {\n        ini_navf = navfix_;\n        // std::cout<<\"ini_navf.header  -> \"<<ini_navf.header<<std::endl;\n        originllh.resize(3, 1);\n        originllh(0) = navfix_.longitude;\n        originllh(1) = navfix_.latitude;\n        originllh(2) = navfix_.altitude;\n        // std::cout<<\"reference longitude: \"<<navfix_.longitude<<std::endl;\n        // std::cout<<\"reference latitude: \"<<navfix_.latitude<<std::endl;\n      }\n      Eigen::MatrixXd curLLh; // \n      curLLh.resize(3, 1);\n      curLLh(0) = navfix_.longitude;\n      curLLh(1) = navfix_.latitude;\n      curLLh(2) = navfix_.altitude;\n\n      Eigen::MatrixXd ecef; // \n      ecef.resize(3, 1);\n      ecef = gnss_tools_.llh2ecef(curLLh);\n      Eigen::MatrixXd eigenENU;; // \n      eigenENU.resize(3, 1);\n      eigenENU = gnss_tools_.ecef2enu(originllh_span,ecef);\n      /*\n      gps(0) = odom_track.pose.pose.position.x;\n      gps(1) = odom_track.pose.pose.position.y;\n      gps(2) = odom_track.pose.pose.position.z;\n      gps(3) = odom_track.pose.pose.orientation.x;\n      gps(4) = odom_track.pose.pose.orientation.y;\n      gps(5) = odom_track.pose.pose.orientation.z;\n      gps(6) = 1;\n      */\n      odom_track.header.frame_id = \"odom\";\n      odom_track.pose.pose.position.x = eigenENU(0);\n      odom_track.pose.pose.position.y = eigenENU(1);\n      odom_track.pose.pose.position.z = 0;\n      odom_track.pose.pose.orientation.x = 0;\n      odom_track.pose.pose.orientation.y = 0;\n      odom_track.pose.pose.orientation.z = 0;\n      odom_track.pose.pose.orientation.w = 0;\n      if(originllh_span.size()) // initial llh from span-cpt is available \n      {\n        gps_up = 1;\n      }\n      \n      ekf_GNSS_odom_pub.publish(odom_track);\n\n      ekf_z_t(0) = odom_track.pose.pose.position.x; \n      ekf_z_t(1) = odom_track.pose.pose.position.y; \n      ekf_z_t(2) = odom_track.pose.pose.position.z; \n\n      if(online_cal_success) // imu calibration ready\n      {\n        // update \n\n        // update K_matrix\n        Eigen::MatrixXd I_matrix;\n        I_matrix.resize(9,9);\n        I_matrix.setIdentity();\n        K_matrix = sigma_matrix * H_matrix.transpose() * (H_matrix * sigma_matrix * \n          H_matrix.transpose() + R_matrix).inverse();\n        ekf_state = ekf_state + K_matrix * (ekf_z_t - H_matrix * ekf_state);\n        sigma_matrix = (I_matrix - K_matrix * H_matrix) * sigma_matrix;\n        cout<<\"ekf_state-> \" <<ekf_state<<endl;\n        \n        ekf_pose_odom.header = navfix_.header;\n        ekf_pose_odom.header.frame_id = \"odom\";\n        ekf_pose_odom.pose.pose.position.x = ekf_state(0);\n        ekf_pose_odom.pose.pose.position.y = ekf_state(1);\n        ekf_pose_odom.pose.pose.position.z = ekf_state(2);\n        ekf_loose_Pose_pub.publish(ekf_pose_odom);\n\n        //2D position error between loose ekf and span\n        double error_ekf = sqrt(pow(ekf_pose_odom.pose.pose.position.x - span_odom.pose.pose.position.x,2) + pow(ekf_pose_odom.pose.pose.position.y - span_odom.pose.pose.position.y,2));\n        posi_err.push_back(error_ekf);\n        statistical_para result = statis_cal(posi_err);\n        cout<<\" positioning error (loose ekf) mean:->\" << result.mean \n          << \" positioning error (loose ekf) std: ->\" << result.std;\n        //2D position error between gps and span\n        double error_gps = sqrt(pow(odom_track.pose.pose.position.x - span_odom.pose.pose.position.x,2) + pow(odom_track.pose.pose.position.y - span_odom.pose.pose.position.y,2));\n        posi_err_gps.push_back(error_gps);\n        result = statis_cal(posi_err_gps);\n        cout<<\" positioning error (gps) mean:->\" << result.mean <<\n         \" positioning error (gps) std: ->\" << result.std;\n\n        fprintf(fp_out_loose_ekf, \"%d ,%3.2f ,%3.2f ,%3.2f,%3.2f,%3.2f,%3.2f,%3.2f,%3.2f \\n\", posi_err.size(), error_gps, error_ekf, \n          odom_track.pose.pose.position.x, odom_track.pose.pose.position.y, ekf_pose_odom.pose.pose.position.x, ekf_pose_odom.pose.pose.position.y, \n          span_odom.pose.pose.position.x , span_odom.pose.pose.position.y);\n\n      }\n      \n  }\n\n  /**\n   * @brief  least square for signle point positioning\n   * @param eAllSVPositions ((n,4) prn, sx, sy, sz, )     eAllSVPositions ((n,3) PRN CNO Pseudorange)\n   * @return eWLSSolution 5 unknowns with two clock bias variables\n   @ \n  */\n  Eigen::MatrixXd LeastSquare(Eigen::MatrixXd eAllSVPositions, Eigen::MatrixXd eAllMeasurement){\n  \n    Eigen::MatrixXd eWLSSolution;\n    eWLSSolution.resize(5, 1);\n\n    /**after read the obs file, one measure is not right**/\n    int validNumMeasure=0;\n    std::vector<int> validMeasure;\n    for (int idx = 0; idx < eAllMeasurement.rows(); idx++){\n      for (int jdx = 0; jdx < eAllSVPositions.rows(); jdx++){\n        if (int(eAllMeasurement(idx, 0)) == int(eAllSVPositions(jdx, 0))){\n          validNumMeasure++;\n          validMeasure.push_back(int(eAllMeasurement(idx, 0)));\n        }\n      }\n    }\n\n    Eigen::MatrixXd validMeasurement; // for WLS \n    validMeasurement.resize(validNumMeasure,eAllMeasurement.cols());\n    for (int idx = 0; idx < eAllMeasurement.rows(); idx++){\n      for (int jdx = 0; jdx < eAllSVPositions.rows(); jdx++){\n        if (int(eAllMeasurement(idx, 0)) == int(eAllSVPositions(jdx, 0))){\n          for (int kdx = 0; kdx < eAllMeasurement.cols(); kdx++){\n            // std::cout<<\"satellite prn -> \"<<eAllMeasurement(idx, 0)<<\"\\n\"<<std::endl;\n            validMeasurement(idx, kdx) = eAllMeasurement(idx, kdx);\n            \n          }\n        }\n      }\n    }\n\n\n\n    int iNumSV = validMeasurement.rows();\n\n    /*Find the received SV and Sort based on the order of Measurement matrix*/\n    Eigen::MatrixXd eExistingSVPositions; // for WLS\n    eExistingSVPositions.resize(iNumSV, eAllSVPositions.cols());\n\n    for (int idx = 0; idx < validMeasurement.rows(); idx++){\n      for (int jdx = 0; jdx < eAllSVPositions.rows(); jdx++){\n        if (int(validMeasurement(idx, 0)) == int(eAllSVPositions(jdx, 0))){\n          for (int kdx = 0; kdx < eAllSVPositions.cols(); kdx++){\n            // std::cout<<\"satellite prn -> \"<<eAllMeasurement(idx, 0)<<\"\\n\"<<std::endl;\n            eExistingSVPositions(idx, kdx) = eAllSVPositions(jdx, kdx);\n            \n          }\n        }\n      }\n    } \n    //for (int idx = 0; idx < eExistingSVPositions.rows(); idx++){\n    //  printf(\"%2d-[%3d] - (%10.2f,%10.2f,%10.2f) %f\\n\", idx, int(eExistingSVPositions(idx, 0)), eExistingSVPositions(idx, 1), eExistingSVPositions(idx, 2), eExistingSVPositions(idx, 3), eExistingSVPositions(idx, 4)*CLIGHT);\n    //}\n\n    //Intialize the result by guessing.\n    for (int idx = 0; idx < eWLSSolution.rows(); idx++){\n      eWLSSolution(idx, 0) = 0;\n    }\n    \n    // for the case of insufficient satellite\n    if (iNumSV < 5){\n      return eWLSSolution;\n    }\n\n    bool bWLSConverge = false;\n\n    int count = 0;\n    while (!bWLSConverge)\n    {\n      Eigen::MatrixXd eH_Matrix;\n      eH_Matrix.resize(iNumSV, eWLSSolution.rows());\n\n      Eigen::MatrixXd eDeltaPr;\n      eDeltaPr.resize(iNumSV, 1);\n\n      Eigen::MatrixXd eDeltaPos;\n      eDeltaPos.resize(eWLSSolution.rows(), 1);\n\n      for (int idx = 0; idx < iNumSV; idx++){\n\n        int prn = int(validMeasurement(idx, 0));\n        double pr = validMeasurement(idx, 2);\n        \n        // Calculating Geometric Distance\n        double rs[3], rr[3], e[3];\n        double dGeoDistance;\n\n        rs[0] = eExistingSVPositions(idx, 1);\n        rs[1] = eExistingSVPositions(idx, 2);\n        rs[2] = eExistingSVPositions(idx, 3);\n\n        rr[0] = eWLSSolution(0);\n        rr[1] = eWLSSolution(1);\n        rr[2] = eWLSSolution(2);\n\n        // dGeoDistance = geodist(rs, rr, e);\n        dGeoDistance = sqrt(pow((rs[0] - rr[0]),2) + pow((rs[1] - rr[1]),2) +pow((rs[2] - rr[2]),2));\n\n        // Making H matrix      \n        eH_Matrix(idx, 0) = -(rs[0] - rr[0]) / dGeoDistance;\n        eH_Matrix(idx, 1) = -(rs[1] - rr[1]) / dGeoDistance;\n        eH_Matrix(idx, 2) = -(rs[2] - rr[2]) / dGeoDistance;\n\n        if (PRNisGPS(prn)){\n          eH_Matrix(idx, 3) = 1;\n          eH_Matrix(idx, 4) = 0;\n        }\n        else if (PRNisBeidou(prn))\n        {\n          eH_Matrix(idx, 3) = 1;\n          eH_Matrix(idx, 4) = 1;\n        }\n\n        // Making delta pseudorange\n        double rcv_clk_bias;\n        if (PRNisGPS(prn)){\n          rcv_clk_bias = eWLSSolution(3);       \n        }\n        else if (PRNisBeidou(prn))\n        {\n          rcv_clk_bias = eWLSSolution(4);\n        }\n        // double sv_clk_bias = eExistingSVPositions(idx, 4) * CLIGHT;\n        eDeltaPr(idx, 0) = pr - dGeoDistance + rcv_clk_bias;\n        //printf(\"%2d - %f %f %f %f \\n\", prn, pr, dGeoDistance, eDeltaPr(idx, 0), rcv_clk_bias);\n      }\n\n      // Least Square Estimation \n      eDeltaPos = (eH_Matrix.transpose() * eH_Matrix).ldlt().solve(eH_Matrix.transpose() *  eDeltaPr);\n      //eDeltaPos = (eH_Matrix.transpose() * eH_Matrix).inverse() * eH_Matrix.transpose() *  eDeltaPr;\n      //eDeltaPos = eH_Matrix.householderQr().solve(eDeltaPr);\n\n      //for (int idx = 0; idx < eDeltaPos.rows(); idx++)\n      //  printf(\"%f \", eDeltaPos(idx));\n      //printf(\"\\n\");\n\n      eWLSSolution(0) += eDeltaPos(0);\n      eWLSSolution(1) += eDeltaPos(1);\n      eWLSSolution(2) += eDeltaPos(2);\n      eWLSSolution(3) += eDeltaPos(3);\n      eWLSSolution(4) += eDeltaPos(4);\n\n      for (int i = 0; i < 3; ++i){\n        //printf(\"%f\\n\", fabs(eDeltaPos(i)));\n        if (fabs(eDeltaPos(i)) >1e-4)\n        {\n          bWLSConverge = false;\n        }\n        else { \n          bWLSConverge = true;\n        };\n        \n      }\n      count += 1;\n      if (count > 6)\n        bWLSConverge = true;\n    }\n    // printf(\"WLS -> (%11.2f,%11.2f,%11.2f)\\n\\n\", eWLSSolution(0), eWLSSolution(1), eWLSSolution(2));\n    std::cout << std::setprecision(12);\n    // cout<< \"---------------WLS (ECEF) x, y, z, bias_gps, bias_beidou-----------------  \\n\"<<eWLSSolution<<endl;\n\n    return eWLSSolution;\n  }\n  \n \n  /**\n   * @brief satellite set validation\n   * @param prn\n   * @return ture/false\n   @ \n   */\n  bool PRNisGPS(int prn)\n  {\n    if (prn <= 32 || prn == 84)\n      return true;\n    else{\n      return false;\n    } \n  }\n\n  /**\n   * @brief satellite set validation\n   * @param prn\n   * @return ture/false\n   @ \n   */\n  bool PRNisGLONASS(int prn)\n  {\n    if (prn > 32 && prn <= 56)\n      return true;\n    else{\n      return false;\n    }\n  }\n\n  /**\n   * @brief satellite set validation\n   * @param prn\n   * @return ture/false\n   @ \n   */\n  bool PRNisBeidou(int prn)\n  {\n    if ((prn <= 121) && (prn >= 87))\n      return true;\n    else{\n      return false;\n    }\n  }\n\n  /**\n   * @brief covariance estimation\n   * @param nlosExclusion::GNSS_Raw_Array GNSS_data\n   * @return weight_matrix\n   @ \n   */\n  double cofactorMatrixCal_single_satellite(double ele, double snr)\n  {\n    double cofactor_ = 0;\n    double snr_1 = 50.0; // T = 50\n    double snr_A = 30.0; // A = 30\n    double snr_a = 30.0;// a = 30\n    double snr_0 = 10.0; // F = 10\n\n    double snr_R = snr;\n    double elR = ele;\n    double q_R_1 = 1 / (pow(( sin(elR * pi/180.0 )),2));\n    double q_R_2 = pow(10,(-(snr_R - snr_1) / snr_a));\n    double q_R_3 = (((snr_A / (pow(10,(-(snr_0 - snr_1) / snr_a))) - 1) / (snr_0 - snr_1)) * (snr_R - snr_1) + 1);\n    double q_R = q_R_1* (q_R_2 * q_R_3);\n    cofactor_ = (float(q_R)); // uncertainty: cofactor_[i] larger, larger uncertainty\n\n    return cofactor_;\n  }\n\n \n  /**\n   * @brief delay function\n   * @param seconds for delay\n   * @return void\n   @ \n   */\n  void wait(int seconds) // delay function\n  {\n    clock_t endwait,start;\n    start = clock();\n    endwait = clock() + seconds * CLOCKS_PER_SEC;\n    while (clock() < endwait) {\n      if(clock() - start > CLOCKS_PER_SEC)\n      {\n        start = clock();\n        std::cout<<\".......1 s\"<<std::endl;\n      }\n    }\n  }  \n\nprivate:\n  int reserve1;\n\nprivate:\n  ros::Publisher pub_debug_marker_; // marker publisher\n  ros::Publisher marker_pub;\n  visualization_msgs::MarkerArray markers; // markers for building models\n\n  \n\n};\n\nint main(int argc, char** argv)\n{\n  ros::init(argc, argv, \"ekf_loose\");\n  std::cout<<\"ekf_loose......\"<<std::endl;\n\n  // printf(\"obss.n = %d\\n\", obss.n);\n  ekf_loose ekf_loose_(1);\n  ros::spin();\n  while (ros::ok()) {\n  }\n  return 0;\n}", "meta": {"hexsha": "ef5ec51c0ba9af9826608775038a83f2e030febd", "size": 31468, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "amsi/apps/gps_imu_loose_ekf_husai.cpp", "max_stars_repo_name": "xiaoshitou4/GNSS-INS", "max_stars_repo_head_hexsha": "6ea16568d85eb1ed6b5cc49fb192dcba0e0f7491", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-07-27T05:31:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T02:16:46.000Z", "max_issues_repo_path": "amsi/apps/gps_imu_loose_ekf_husai.cpp", "max_issues_repo_name": "yxw027/GNSS-INS", "max_issues_repo_head_hexsha": "e5c5b7901b270a9c4d3a0ffd5555843d969f4018", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "amsi/apps/gps_imu_loose_ekf_husai.cpp", "max_forks_repo_name": "yxw027/GNSS-INS", "max_forks_repo_head_hexsha": "e5c5b7901b270a9c4d3a0ffd5555843d969f4018", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-12-25T07:47:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-03T03:24:46.000Z", "avg_line_length": 31.6579476861, "max_line_length": 225, "alphanum_fraction": 0.60671158, "num_tokens": 9785, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.46717566310933384}}
{"text": "\n#include \"test_data.hpp\"\n#include <boost/test/unit_test.hpp>\n#include \"libs/ml_models/K_nearest.h\"\n#include <iostream>\n\nBOOST_AUTO_TEST_CASE(empty_data_knear_test)\n{\n    mlmodels::K_nearest model;\n    auto m = model.train(mlmodels::training_data{}, \n            mlmodels::class_data{},\n            mlmodels::K_nearest::args{}\n        );\n    BOOST_TEST((m.get() == nullptr), \"the model that we should get back from empty data set should be empty as well\");\n    mlmodels::testing_result out;\n    auto r = model.predict(m, mlmodels::testing_data{}, out);\n    BOOST_TEST(r == false, \"should failed because training did not run\");\n    BOOST_TEST(out.empty(), \"there should not be any data from the test\");\n}\n\nBOOST_AUTO_TEST_CASE(test_model_create_knear)\n{\n    const auto& samples = ut_data::unittest_data();\n    const auto& classes = ut_data::classes4ut();\n    BOOST_TEST_REQUIRE(mlmodels::rows(samples) == classes.size());\n    \n    mlmodels::K_nearest knear;\n    auto m = knear.train(samples,\n                classes, \n                mlmodels::K_nearest::args{}\n        );\n    BOOST_TEST_REQUIRE((m.get() != nullptr), \"we are expecting that this train would succeed\");\n    const auto& test_samples = ut_data::samples4test();\n    BOOST_TEST_REQUIRE(mlmodels::rows(test_samples) < mlmodels::rows(samples));\n    BOOST_TEST_REQUIRE(mlmodels::columns(test_samples) == mlmodels::columns(samples));\n    auto p = knear.test(m, test_samples, ut_data::NUMBER_OF_CLASSES);\n    BOOST_TEST_REQUIRE(!p.empty(), \"we are expecting to get entries from the test\");\n    BOOST_TEST_REQUIRE(p.size() == mlmodels::rows(test_samples));\n    //mlmodels::save_model(m);\n#ifdef PRINT_MODEL_RESULTS\n    std::cout<<\"model prediction for k nearest\\n\";\n    for (auto f : p) {\n        std::cout<<\"[\"<<f<<\"]\";\n    }\n    std::cout<<std::endl;\n#endif\n}\n#if 0\nBOOST_AUTO_TEST_CASE(test_model_create_knear_to_remove)\n{\n    const auto& samples = ut_data::unittest_data();\n    const auto& classes = ut_data::classes4ut();\n    BOOST_TEST_REQUIRE(mlmodels::rows(samples) == classes.size());\n    \n    mlmodels::K_nearest knear;\n    auto m = knear.train(samples,\n                    classes, mlmodels::K_nearest::args{}\n        );\n    BOOST_TEST_REQUIRE((m.get() != nullptr), \"we are expecting that this train would succeed\");\n    const auto& test_samples = ut_data::samples4test();\n    BOOST_TEST_REQUIRE(mlmodels::rows(test_samples) < mlmodels::rows(samples));\n    BOOST_TEST_REQUIRE(mlmodels::columns(test_samples) == mlmodels::columns(samples));\n    //auto p = knear.test(m, test_samples, ut_data::NUMBER_OF_CLASSES);\n    mlmodels::class_data res, dist, nr;\n    BOOST_TEST_REQUIRE(knear.test(m, test_samples, res, dist, nr));\n    BOOST_TEST_REQUIRE(!res.empty(), \"we are expecting to get entries from the test\");\n    BOOST_TEST_REQUIRE(res.size() == mlmodels::rows(test_samples));\n    //mlmodels::save_model(m);\n    std::cout<<\"model prediction for k nearest\\n\";\n    for (auto f : res) {\n        std::cout<<\"[\"<<f<<\"]\";\n    }\n    std::cout<<std::endl;\n    std::cout<<\"distance array of size \"<<dist.size()<<std::endl;\n    auto i = 0u;\n    for (auto d : dist) {\n        std::cout<<\"[\"<<d<<\"]\";\n        if ((++i % res.size()) == 0) {\n            std::cout<<\"\\n\";\n        }\n    }\n    std::cout<<std::endl;\n    std::cout<<\"neighbor responses array of size \"<<dist.size()<<std::endl;\n    i = 0u;\n    for (auto r : nr) {\n        std::cout<<\"[\"<<r<<\"]\";\n        if ((++i % res.size()) == 0) {\n            std::cout<<\"\\n\";\n        }\n    }\n}\n#endif\n", "meta": {"hexsha": "92c6796b5e0de3e1f3b5605e4b0053eb1811fb64", "size": 3500, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/libs/ml_models/ut/test_knearest.cpp", "max_stars_repo_name": "boazsade/machine_learinig_models", "max_stars_repo_head_hexsha": "eb1f9eda0e4e25a6d028b25682dfb20628a20624", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/libs/ml_models/ut/test_knearest.cpp", "max_issues_repo_name": "boazsade/machine_learinig_models", "max_issues_repo_head_hexsha": "eb1f9eda0e4e25a6d028b25682dfb20628a20624", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libs/ml_models/ut/test_knearest.cpp", "max_forks_repo_name": "boazsade/machine_learinig_models", "max_forks_repo_head_hexsha": "eb1f9eda0e4e25a6d028b25682dfb20628a20624", "max_forks_repo_licenses": ["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.6344086022, "max_line_length": 118, "alphanum_fraction": 0.6357142857, "num_tokens": 886, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.6261241702517976, "lm_q1q2_score": 0.46717565790389076}}
{"text": "//  (C) Copyright Eric Niebler 2008.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include <boost/test/unit_test.hpp>\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/rolling_sum.hpp>\n\nusing namespace boost;\nusing namespace unit_test;\nusing namespace accumulators;\n\n///////////////////////////////////////////////////////////////////////////////\n// test_stat\n//\nvoid test_stat()\n{\n    accumulator_set<int, stats<tag::rolling_sum> > acc(tag::rolling_window::window_size = 3);\n\n    BOOST_CHECK_EQUAL(0, rolling_sum(acc));\n\n    acc(1);\n    BOOST_CHECK_EQUAL(1, rolling_sum(acc));\n\n    acc(2);\n    BOOST_CHECK_EQUAL(3, rolling_sum(acc));\n\n    acc(3);\n    BOOST_CHECK_EQUAL(6, rolling_sum(acc));\n\n    acc(4);\n    BOOST_CHECK_EQUAL(9, rolling_sum(acc));\n\n    acc(5);\n    BOOST_CHECK_EQUAL(12, rolling_sum(acc));\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// init_unit_test_suite\n//\ntest_suite* init_unit_test_suite( int argc, char* argv[] )\n{\n    test_suite *test = BOOST_TEST_SUITE(\"rolling sum test\");\n\n    test->add(BOOST_TEST_CASE(&test_stat));\n\n    return test;\n}\n", "meta": {"hexsha": "6e20d4707ebcc30d5e5e8220797bf7371987f9bb", "size": 1339, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/accumulators/test/rolling_sum.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "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": "boost/libs/accumulators/test/rolling_sum.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "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": "boost/libs/accumulators/test/rolling_sum.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "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": 26.2549019608, "max_line_length": 93, "alphanum_fraction": 0.6333084391, "num_tokens": 305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850402140659, "lm_q2_score": 0.661922862511608, "lm_q1q2_score": 0.46717525413636485}}
{"text": "#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Surface_mesh.h>\n#include <CGAL/Polygon_mesh_processing/orientation.h>\n#include <CGAL/boost/graph/Face_filtered_graph.h>\n#include <CGAL/Polygon_mesh_processing/transform.h>\n#include <boost/core/ref.hpp>\n\n#include <iostream>\n#include <fstream>\n#include <sstream>\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel;\ntypedef CGAL::Surface_mesh<Kernel::Point_3> Surface_mesh;\ntypedef Kernel::Aff_transformation_3 Trsfrm;\n\nnamespace PMP = CGAL::Polygon_mesh_processing;\nnamespace params = CGAL::parameters;\n\nint main()\n{\n  Surface_mesh base_cube;\n  std::ifstream input(\"data-coref/cube.off\");\n  input >> base_cube;\n\n  Surface_mesh input_mesh;\n  Surface_mesh::Property_map<Surface_mesh::Face_index, std::size_t> vol_id_map =\n    input_mesh.add_property_map<Surface_mesh::Face_index, std::size_t>().first;\n\n  // add large cube\n  input_mesh.join(base_cube);\n\n  // add middle cube\n  Surface_mesh middle_cube = base_cube;\n  PMP::transform(Trsfrm(CGAL::SCALING, 0.5), middle_cube);\n  PMP::transform(Trsfrm(CGAL::TRANSLATION, Kernel::Vector_3(0.25,0.25,0.25)), middle_cube);\n  input_mesh.join(middle_cube);\n\n  // add central cube\n  Surface_mesh small_cube = base_cube;\n  PMP::transform(Trsfrm(CGAL::SCALING, 0.1), small_cube);\n  PMP::transform(Trsfrm(CGAL::TRANSLATION, Kernel::Vector_3(0.5,0.5,0.5)), small_cube);\n  input_mesh.join(small_cube);\n\n  // test using orientation\n  std::vector<PMP::Volume_error_code> expected_result;\n  expected_result.push_back(PMP::VALID_VOLUME);\n  expected_result.push_back(PMP::INCOMPATIBLE_ORIENTATION);\n  expected_result.push_back(PMP::INCOMPATIBLE_ORIENTATION);\n  std::vector<PMP::Volume_error_code>  error_codes;\n  std::size_t nb_vol = PMP::volume_connected_components(input_mesh, vol_id_map,\n                                                        params::error_codes(boost::ref(error_codes)));\n  assert(nb_vol==3);\n  std::sort(error_codes.begin(), error_codes.end());\n  assert( error_codes==expected_result );\n\n  // test ignoring orientation\n  nb_vol = PMP::volume_connected_components(input_mesh, vol_id_map,\n                                            params::do_orientation_tests(false)\n                                            .error_codes(boost::ref(error_codes)));\n  assert(nb_vol==2);\n  expected_result.clear();\n  expected_result.resize(2, PMP::VALID_VOLUME);\n  assert( error_codes==expected_result );\n\n\n  // test surface component self-intersection\n  {\n  Surface_mesh tmp = input_mesh;\n  Surface_mesh::Property_map<Surface_mesh::Face_index, std::size_t> tmp_vol_id_map =\n    tmp.add_property_map<Surface_mesh::Face_index, std::size_t>().first;\n  // create a self-intersection\n  Surface_mesh::Halfedge_index h = *tmp.halfedges().begin();\n  h = CGAL::Euler::split_edge(h, tmp);\n  tmp.point( target(h, tmp) ) = tmp.point( target( tmp.next(h), tmp) );\n  CGAL::Euler::split_face(h, next( next(h, tmp), tmp), tmp);\n  h = opposite(h, tmp);\n  CGAL::Euler::split_face(h, next( next(h, tmp), tmp), tmp);\n\n  nb_vol = PMP::volume_connected_components(tmp, tmp_vol_id_map,\n                                            params::do_orientation_tests(false)\n                                            .error_codes(boost::ref(error_codes))\n                                            .do_self_intersection_tests(true));\n\n  assert(nb_vol==2);\n  expected_result.clear();\n  expected_result.push_back(PMP::VALID_VOLUME);\n  expected_result.push_back(PMP::SURFACE_WITH_SELF_INTERSECTIONS);\n  std::sort(error_codes.begin(), error_codes.end());\n  assert( error_codes==expected_result );\n  }\n\n  // test single cc\n  {\n  Surface_mesh tmp = base_cube;\n  Surface_mesh::Property_map<Surface_mesh::Face_index, std::size_t> tmp_vol_id_map =\n    tmp.add_property_map<Surface_mesh::Face_index, std::size_t>().first;\n\n  nb_vol = PMP::volume_connected_components(tmp, tmp_vol_id_map,\n                                            params::do_orientation_tests(false)\n                                            .error_codes(boost::ref(error_codes))\n                                            .do_self_intersection_tests(true));\n\n  assert(nb_vol==1);\n  expected_result.clear();\n  expected_result.push_back(PMP::VALID_VOLUME);\n  assert( error_codes==expected_result );\n  }\n\n  // test intersection between cc\n  {\n  Surface_mesh tmp = input_mesh;\n  // create surface intersection\n  tmp.join(base_cube);\n  Surface_mesh::Property_map<Surface_mesh::Face_index, std::size_t> tmp_vol_id_map =\n    tmp.add_property_map<Surface_mesh::Face_index, std::size_t>().first;\n\n  nb_vol = PMP::volume_connected_components(tmp, tmp_vol_id_map,\n                                            params::do_orientation_tests(false)\n                                            .error_codes(boost::ref(error_codes))\n                                            .do_self_intersection_tests(true));\n\n  assert(nb_vol==4);\n  expected_result.clear();\n  expected_result.resize(4, PMP::VOLUME_INTERSECTION);\n  assert( error_codes==expected_result );\n  }\n  {\n  Surface_mesh tmp = input_mesh;\n  // create surface intersection\n  tmp.join(middle_cube);\n  tmp.join(middle_cube);\n  Surface_mesh::Property_map<Surface_mesh::Face_index, std::size_t> fccmap =\n    tmp.add_property_map<Surface_mesh::Face_index, std::size_t>(\"f:CC\").first;\n\n  Surface_mesh::Property_map<Surface_mesh::Face_index, std::size_t> tmp_vol_id_map =\n    tmp.add_property_map<Surface_mesh::Face_index, std::size_t>().first;\n  std::vector< std::vector<std::size_t> > nested_cc_per_cc;\n\n  nb_vol = PMP::volume_connected_components(tmp, tmp_vol_id_map,\n                                            params::do_orientation_tests(false)\n                                            .error_codes(boost::ref(error_codes))\n                                            .face_connected_component_map(fccmap)\n                                            .do_self_intersection_tests(true)\n                                            .volume_inclusions(boost::ref(nested_cc_per_cc)));\n\n  assert(nb_vol==5);\n  expected_result.clear();\n  expected_result.push_back(PMP::VALID_VOLUME);\n  expected_result.resize(5, PMP::VOLUME_INTERSECTION);\n  std::sort(error_codes.begin(), error_codes.end());\n  assert( error_codes==expected_result );\n  std::size_t sum=0;\n  for (int i=0; i<5; ++i)\n  {\n    sum+=nested_cc_per_cc[i].size();\n    assert(nested_cc_per_cc[i].size()==1 ||\n           nested_cc_per_cc[i].size()==3 ||\n           nested_cc_per_cc[i].size()==0);\n  }\n  assert(sum == 0+3*1+3);\n  }\n\n  // test level 0 orientation\n  {\n  Surface_mesh tmp = base_cube;\n  PMP::transform(Trsfrm(CGAL::TRANSLATION, Kernel::Vector_3(2,0,0)), tmp);\n  tmp.join(base_cube);\n  PMP::reverse_face_orientations(tmp);\n  Surface_mesh::Property_map<Surface_mesh::Face_index, std::size_t> tmp_vol_id_map =\n    tmp.add_property_map<Surface_mesh::Face_index, std::size_t>().first;\n  // create a self-intersection\n  nb_vol = PMP::volume_connected_components(tmp, tmp_vol_id_map,\n                                            params::do_orientation_tests(false));\n\n  assert(nb_vol==2);\n  nb_vol = PMP::volume_connected_components(tmp, tmp_vol_id_map,\n                                            params::do_orientation_tests(true));\n\n  assert(nb_vol==1);\n  }\n  // debug code\n  /*\n    std::cout << \"  found \" << nb_vol << \" volumes\\n\";\n    typedef CGAL::Face_filtered_graph<Surface_mesh> Filtered_graph;\n    Filtered_graph vol_mesh(sm, 0, vol_id_map);\n    for(std::size_t id = 0; id < nb_vol; ++id)\n    {\n      if(id > 0)\n        vol_mesh.set_selected_faces(id, vol_id_map);\n      Surface_mesh out;\n      CGAL::copy_face_graph(vol_mesh, out);\n      std::ostringstream oss;\n      oss << \"vol_\" << id <<\".off\";\n      std::ofstream os(oss.str().data());\n      os << out;\n    }\n  */\n}\n", "meta": {"hexsha": "167625a4bb5f8c4007a7bf77cf73ff4cf244b9e1", "size": 7742, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Polygon_mesh_processing/test/Polygon_mesh_processing/test_split_volume.cpp", "max_stars_repo_name": "ffteja/cgal", "max_stars_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-19T03:07:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-19T03:07:22.000Z", "max_issues_repo_path": "Polygon_mesh_processing/test/Polygon_mesh_processing/test_split_volume.cpp", "max_issues_repo_name": "ffteja/cgal", "max_issues_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "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": "Polygon_mesh_processing/test/Polygon_mesh_processing/test_split_volume.cpp", "max_forks_repo_name": "ffteja/cgal", "max_forks_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "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.9045226131, "max_line_length": 102, "alphanum_fraction": 0.6578403513, "num_tokens": 1859, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.6619228625116081, "lm_q1q2_score": 0.4671752459437095}}
{"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 shape evaluation\n *  \\author Bastien Durix\n */\n\n#include <boost/program_options.hpp>\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\n#include <algorithm/extractboundary/NaiveBoundary.h>\n#include <algorithm/evaluation/ShapeError.h>\n\nint main(int argc, char** argv)\n{\n\tstd::string imgref, imgcmp;\n\n\tboost::program_options::options_description desc(\"OPTIONS\");\n\t\n\tdesc.add_options()\n\t\t(\"help\", \"Help message\")\n\t\t(\"imgref\", boost::program_options::value<std::string>(&imgref)->default_value(\"img1.png\"), \"Reference binary image file\")\n\t\t(\"imgcmp\", boost::program_options::value<std::string>(&imgcmp)->default_value(\"img2.png\"), \"Compaired binary image file\")\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\tcv::Mat shprefgray = cv::imread(imgref,cv::ImreadModes::IMREAD_GRAYSCALE);\n\tcv::Mat shpref;\n\tcv::threshold(shprefgray,shpref,1,255,cv::THRESH_BINARY);\n\tshape::DiscreteShape<2>::Ptr disshref = shape::DiscreteShape<2>::Ptr(new shape::DiscreteShape<2>(shpref.cols,shpref.rows));\n\n\tcv::Mat shpcmpgray = cv::imread(imgcmp,cv::ImreadModes::IMREAD_GRAYSCALE);\n\tcv::Mat shpcmp;\n\tcv::threshold(shpcmpgray,shpcmp,1,255,cv::THRESH_BINARY);\n\tshape::DiscreteShape<2>::Ptr disshcmp = shape::DiscreteShape<2>::Ptr(new shape::DiscreteShape<2>(shpcmp.cols,shpcmp.rows));\n\t\n\tdouble symdiff = algorithm::evaluation::SymDiffArea(disshref,disshcmp);\n\n\tstd::cout << \"Symmetric area difference :  \" << symdiff << std::endl;\n\n\tboundary::DiscreteBoundary<2>::Ptr bndref = algorithm::extractboundary::NaiveBoundary(disshref);\n\tboundary::DiscreteBoundary<2>::Ptr bndcmp = algorithm::extractboundary::NaiveBoundary(disshcmp);\n\n\tdouble hausdist = algorithm::evaluation::HausDist(bndref,bndcmp);\n\n\tstd::cout << \"Hausdorff Distance :  \" << hausdist << std::endl;\n\n\treturn 0;\n}\n", "meta": {"hexsha": "033d9b82311073f885c4020c010132517226589a", "size": 3227, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/soft/soft_evalshape/main.cpp", "max_stars_repo_name": "Ibujah/evalshape", "max_stars_repo_head_hexsha": "345d95184a47a87e6aae2f2de126b88b9edd3ac6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-02-01T09:03:40.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-01T09:03:40.000Z", "max_issues_repo_path": "src/soft/soft_evalshape/main.cpp", "max_issues_repo_name": "Ibujah/evalshape", "max_issues_repo_head_hexsha": "345d95184a47a87e6aae2f2de126b88b9edd3ac6", "max_issues_repo_licenses": ["MIT"], "max_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_evalshape/main.cpp", "max_forks_repo_name": "Ibujah/evalshape", "max_forks_repo_head_hexsha": "345d95184a47a87e6aae2f2de126b88b9edd3ac6", "max_forks_repo_licenses": ["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.523255814, "max_line_length": 124, "alphanum_fraction": 0.7570498915, "num_tokens": 829, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.661922862511608, "lm_q1q2_score": 0.46717524594370946}}
{"text": "/* Copyright (c) 2015, Julian Straub <jstraub@csail.mit.edu> Licensed\n * under the MIT license. See the license file LICENSE.\n */\n#pragma once\n\n#include <Eigen/Dense>\n#include <iostream>\n\n#include <tdp/eigen/std_vector.h>\n\nnamespace tdp {\n/// This is a simple version of the DPvMFmeansSimple algorithm in dpmeans.hpp\n/// without inheritance or the use of CLData structures which can make\n/// it a bit hard to read the other algorithm.\n///\n/// This implementation is ment as a lightweight alternative for small\n/// number of datapoints or if you just want to have a look at how the\n/// algorithm works.\ntemplate<class T, int D, int Options>\nclass DPvMFmeansSimple\n{\npublic:\n  /// Constructor\n  /// \n  /// lambda = cos(lambda_in_degree * M_PI/180.) - 1.\n  DPvMFmeansSimple(T lambda);\n  virtual ~DPvMFmeansSimple();\n\n  /// Adds an observation (adds obs, computes label, and potentially\n  /// adds new cluster depending on label assignment).\n  virtual void addObservation(Eigen::Matrix<T,D,1,Options>* x, uint16_t* z);\n  /// Updates all labels of all data currently stored with the object.\n  virtual void updateLabels();\n  /// Updates all centers based on the current data and label\n  /// assignments.\n  virtual void updateCenters();\n\n  /// Iterate updates for centers and labels until cost function\n  /// convergence.\n  virtual bool iterateToConvergence(uint32_t maxIter, T eps);\n  /// Compuyte the current cost function value.\n  virtual T cost();\n\n  uint32_t GetK() const {return K_;};\n  const std::vector<int32_t>& GetNs() const {return Ns_;};\n  bool GetCenter(uint32_t k, Eigen::Matrix<T,D,1,Options>& mu) const {\n    if (k<K_) {mu = mus_[k]; return true; } else { return false; } };\n  const Eigen::Matrix<T,D,1,Options>& GetCenter(uint32_t k) const {\n    if (k<K_) {return mus_[k]; } else { return Eigen::Matrix<T,D,1,Options>::Zero(); } };\n  const std::vector<uint16_t*>& GetZs() const { return zs_;};\n  bool GetX(uint32_t i, Eigen::Matrix<T,D,1,Options>& x) const {\n    if (i<xs_.size()) {x=*xs_[i]; return true; } else { return false; } };\n\nprotected:\n  T lambda_;\n  uint32_t K_;\n  std::vector<Eigen::Matrix<T,D,1,Options>*> xs_;\n  std::vector<uint16_t*> zs_;\n  eigen_vector<Eigen::Matrix<T,D,1,Options>> mus_;\n  eigen_vector<Eigen::Matrix<T,D,1,Options>> xSums_;\n  std::vector<int32_t> Ns_;\n\n  /// resets all clusters (mus_ and Ks_) and resizes them to K_\n  void resetClusters();\n  /// Removes all empty clusters.\n  void removeEmptyClusters();\n  /// Computes the index of the closest cluster (may be K_ in which\n  /// case a new cluster has to be added).\n  uint16_t indOfClosestCluster(const Eigen::Matrix<T,D,1,Options>& x, T& sim_closest,\n      uint16_t* zExclude=nullptr);\n};\n\ntypedef DPvMFmeansSimple<float,3,Eigen::DontAlign> DPvMFmeansSimple3fda; \ntypedef DPvMFmeansSimple<float,4,Eigen::DontAlign> DPvMFmeansSimple4fda; \n\n// -------------------------------- impl ----------------------------------\ntemplate<class T, int D, int Options>\nDPvMFmeansSimple<T,D,Options>::DPvMFmeansSimple(T lambda)\n  : lambda_(lambda), K_(0)\n{}\ntemplate<class T, int D, int Options>\nDPvMFmeansSimple<T,D,Options>::~DPvMFmeansSimple()\n{}\n\ntemplate<class T, int D, int Options>\nvoid DPvMFmeansSimple<T,D,Options>::addObservation(Eigen::Matrix<T,D,1,Options>* x, uint16_t* z) {\n  xs_.push_back(x); \n  T sim_closest = 0;\n  zs_.push_back(z);\n//  if (*z == 0xFFFF) return;\n  *z = indOfClosestCluster(*x, sim_closest);\n  if (*z == K_) {\n    mus_.push_back(*x);\n    xSums_.push_back(*x);\n    Ns_.push_back(0);\n    ++K_;\n//    std::cout << \"adding cluster \" << mus_.size() << \" \"\n//      << xSums_.size() << \" \" << K_ << \" \"\n//      << x.transpose() << std::endl;\n  }\n  Ns_[*z] ++;\n};\n\ntemplate<class T, int D, int Options>\nuint16_t DPvMFmeansSimple<T,D,Options>::indOfClosestCluster(const\n    Eigen::Matrix<T,D,1,Options>& x, T& sim_closest, uint16_t* zExclude)\n{\n  uint16_t z_i = K_;\n  sim_closest = lambda_;\n  for (uint32_t k=0; k<K_; ++k) {\n    if (zExclude && k == *zExclude)\n      continue;\n    T sim_k = mus_[k].dot(x);\n    if(sim_k > sim_closest) {\n      sim_closest = sim_k;\n      z_i = k;\n    }\n  }\n  return z_i;\n};\n\ntemplate<class T, int D, int Options>\nvoid DPvMFmeansSimple<T,D,Options>::updateLabels()\n{\n  if (xs_.size() == 0) return;\n  for(uint32_t i=0; i<xs_.size(); ++i) {\n    T sim_closest = 0;\n    uint16_t zPrev = *zs_[i];\n//    if (zPrev == 0xFFFF) continue;\n    uint16_t z = indOfClosestCluster(*xs_[i], sim_closest);\n    if (z==zPrev && Ns_[z] == 1) {\n      z = indOfClosestCluster(*xs_[i], sim_closest, &z);\n//      std::cout << \"single cluster \" << z << \" \" << zPrev << std::endl;\n    }\n    if (z == K_) {\n//      std::cout << \"adding cluster \" << mus_.size() << \" \"\n//        << xSums_.size() << \" \" << K_ << \" \"\n//        << xs_[i].transpose() << std::endl;\n      mus_.push_back(*xs_[i]);\n      xSums_.push_back(Eigen::Matrix<T,D,1,Options>::Zero());\n      Ns_.push_back(0);\n      ++K_;\n    }\n    if (z != zPrev) {\n      Ns_[zPrev] --;\n      xSums_[zPrev] -= *xs_[i];\n      Ns_[z] ++; \n      xSums_[z] += *xs_[i];\n    }\n    *zs_[i] = z;\n  }\n};\n\n// General update centers assumes Euclidean\ntemplate<class T, int D, int Options>\nvoid DPvMFmeansSimple<T,D,Options>::updateCenters()\n{\n  if (xs_.size() == 0) return;\n//  resetClusters();\n//  for(uint32_t i=0; i<xs_.size(); ++i) {\n//    ++Ns_[zs_[i]]; \n//    mus_[zs_[i]] += xs_[i];\n//  }\n  // Spherical mean computation\n  for(uint32_t k=0; k<K_; ++k) {\n//    mus_[k] /= mus_[k].norm();\n    mus_[k] = xSums_[k].normalized();\n  }\n  removeEmptyClusters();\n};\n\ntemplate<class T, int D, int Options>\nvoid DPvMFmeansSimple<T,D,Options>::resetClusters() {\n  Ns_.resize(K_, 0);\n  for(uint32_t k=0; k<K_; ++k) {\n    mus_[k].fill(0);\n    Ns_[k] = 0;\n  }\n};\n\ntemplate<class T, int D, int Options>\nvoid DPvMFmeansSimple<T,D,Options>::removeEmptyClusters() {\n  if (K_ < 1) return;\n  uint32_t kNew = K_;\n  std::vector<bool> toDelete(K_,false);\n  for(int32_t k=K_-1; k>-1; --k)\n    if(Ns_[k] == 0) {\n      toDelete[k] = true;\n//      std::cout<<\"cluster k \"<<k<<\" empty\"<<std::endl;\n//#pragma omp parallel for \n      for(uint32_t i=0; i<xs_.size(); ++i)\n//        if(static_cast<int32_t>(*zs_[i]) >= k && *zs_[i] != 0xFFFF) *zs_[i] -= 1;\n        if(static_cast<int32_t>(*zs_[i]) >= k) *zs_[i] -= 1;\n      kNew --;\n    }\n  uint32_t j=0;\n  for(uint32_t k=0; k<K_; ++k) {\n    mus_[j] = mus_[k];\n    xSums_[j] = xSums_[k];\n    Ns_[j] = Ns_[k];\n    if(!toDelete[k]) { \n      ++j;\n    }\n  }\n//  std::cout << \"K \" << K_ << \" -> \" << kNew << std::endl;\n  K_ = kNew;\n  Ns_.resize(K_);\n  mus_.resize(K_);\n  xSums_.resize(K_);\n//  for(uint32_t k=0; k<K_; ++k) \n//    std::cout << mus_[k].transpose() << std::endl;\n};\n\ntemplate<class T, int D, int Options>\nT DPvMFmeansSimple<T,D,Options>::cost() {\n  T f = lambda_*K_; \n//  std::cout << \"f=\"<<f<< std::endl;\n  for(uint32_t i=0; i<xs_.size(); ++i)  {\n//    if (*zs_[i] == 0xFFFF) continue;\n    f += mus_[*zs_[i]].dot(*xs_[i]);\n//    std::cout << zs_[i] << \", \" << xs_[i].transpose() << \", \" \n//      << mus_[zs_[i]].transpose();\n//    std::cout << \" f=\"<<f<< std::endl;\n  }\n  return f;\n}\n\ntemplate<class T, int D, int Options>\nbool DPvMFmeansSimple<T,D,Options>::iterateToConvergence(uint32_t maxIter, T eps) {\n  uint32_t iter = 0;\n  T fPrev = 1e9;\n  T f = cost();\n  updateCenters();\n//  std::cout << \"f=\" << f << \" fPrev=\" << fPrev << std::endl;\n  while (iter < maxIter && fabs(fPrev - f)/f > eps) {\n    updateLabels();\n    updateCenters();\n    fPrev = f;\n    f = cost();\n    ++iter;\n//    std::cout << iter << \": f=\" << f << \" fPrev=\" << fPrev << \": \";\n//    int32_t Nall = 0;\n//    for (const auto& N : Ns_) {\n//      std::cout << N << \" \";\n//      Nall += N;\n//    } std::cout << \" sum= \" << Nall << std::endl;\n  }\n//  if (f != f || fPrev != fPrev || f > 1e9 || iter == maxIter-1) {\n  std::cout << iter << \": f=\" << f << \" fPrev=\" << fPrev << \": \";\n  int32_t Nall = 0;\n  for (const auto& N : Ns_) {\n    std::cout << N << \" \";\n    Nall += N;\n  } std::cout << \" sum= \" << Nall << std::endl;\n//  }\n  return iter < maxIter;\n}\n\n}\n\n", "meta": {"hexsha": "5ccb861f0f8587d2fc398999808ce90de3b7fd77", "size": 8007, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/tdp/clustering/dpvmfmeans_simple.hpp", "max_stars_repo_name": "jstraub/tdp", "max_stars_repo_head_hexsha": "dcab53662be5b88db1538cf831707b07ab96e387", "max_stars_repo_licenses": ["MIT-feh"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-10-17T19:25:47.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-17T19:25:47.000Z", "max_issues_repo_path": "include/tdp/clustering/dpvmfmeans_simple.hpp", "max_issues_repo_name": "jstraub/tdp", "max_issues_repo_head_hexsha": "dcab53662be5b88db1538cf831707b07ab96e387", "max_issues_repo_licenses": ["MIT-feh"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-05-02T06:04:06.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-02T06:04:06.000Z", "max_forks_repo_path": "include/tdp/clustering/dpvmfmeans_simple.hpp", "max_forks_repo_name": "jstraub/tdp", "max_forks_repo_head_hexsha": "dcab53662be5b88db1538cf831707b07ab96e387", "max_forks_repo_licenses": ["MIT-feh"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2017-09-17T18:46:20.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-11T12:52:57.000Z", "avg_line_length": 30.6781609195, "max_line_length": 98, "alphanum_fraction": 0.5927313601, "num_tokens": 2638, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370111, "lm_q2_score": 0.6619228625116081, "lm_q1q2_score": 0.46717524594370946}}
{"text": "// This file is part of PolyMPC, a lightweight C++ template library\n// for real-time nonlinear optimization and optimal control.\n//\n// Copyright (C) 2020 Listov Petr <petr.listov@epfl.ch>\n//\n// This Source Code Form is subject to the terms of the Mozilla\n// Public License v. 2.0. If a copy of the MPL was not distributed\n// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.\n\n#include <Eigen/Dense>\n#include <vector>\n#include <fstream>\n\nusing namespace Eigen;\n\n/*\n\n\nSource : https://stackoverflow.com/questions/34247057/how-to-read-csv-file-and-assign-to-eigen-matrix/39146048\nUsage:\nMatrixXd A = load_csv<MatrixXd>(\"C:/Users/.../A.csv\");\nMatrix3d B = load_csv<Matrix3d>(\"C:/Users/.../B.csv\");\nVectorXd v = load_csv<VectorXd>(\"C:/Users/.../v.csv\");\n*/\n\n//const double inf = std::numeric_limits<double>::infinity();\n\ntemplate<typename M>\nM 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    //const char *exp[] = { \"\", \"inf\", \"NaN\" };\n    while (std::getline(indata, line)) {\n        std::stringstream lineStream(line);\n        std::string cell;\n        while (std::getline(lineStream, cell, ',')) {\n            bool is_inf = false;\n            /* for (int i=0; i < 3; i++)\n            {\n                if (exp[i] == cell){values.push_back(inf); is_inf=true; break;}\n            }*/\n            if (!is_inf) {values.push_back(std::stod(cell));}\n        }\n        ++rows;\n    }\n    //std::cout << rows << \" \" << values.size() << std::endl;\n\n    return Eigen::Map<const Matrix<typename M::Scalar, M::RowsAtCompileTime, M::ColsAtCompileTime, RowMajor>>(values.data(), rows, values.size()/rows);\n\n}\n", "meta": {"hexsha": "9d22f2280440f27e568e691f027d1023cfd7838c", "size": 1725, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "polympc/tests/solvers/qp/load_matrix_from_csv.hpp", "max_stars_repo_name": "alexandreguerradeoliveira/rocket_gnc", "max_stars_repo_head_hexsha": "164e96daca01d9edbc45bfaac0f6b55fe7324f24", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "polympc/tests/solvers/qp/load_matrix_from_csv.hpp", "max_issues_repo_name": "alexandreguerradeoliveira/rocket_gnc", "max_issues_repo_head_hexsha": "164e96daca01d9edbc45bfaac0f6b55fe7324f24", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "polympc/tests/solvers/qp/load_matrix_from_csv.hpp", "max_forks_repo_name": "alexandreguerradeoliveira/rocket_gnc", "max_forks_repo_head_hexsha": "164e96daca01d9edbc45bfaac0f6b55fe7324f24", "max_forks_repo_licenses": ["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.9444444444, "max_line_length": 151, "alphanum_fraction": 0.6214492754, "num_tokens": 464, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228625116081, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.4671752418473817}}
{"text": "/**\n * @file function_test.cpp\n * @author Ryan Curtin\n * @author Shikhar Bhardwaj\n *\n * Test the Function<> class to see that it properly adds functionality.\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#include <mlpack/core.hpp>\n#include <mlpack/core/optimizers/function.hpp>\n#include <mlpack/methods/logistic_regression/logistic_regression_function.hpp>\n#include <mlpack/core/optimizers/sdp/sdp.hpp>\n#include <mlpack/core/optimizers/sdp/lrsdp.hpp>\n#include <mlpack/core/optimizers/aug_lagrangian/aug_lagrangian.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n\nusing namespace mlpack;\nusing namespace mlpack::optimization;\nusing namespace mlpack::optimization::traits; // For some SFINAE checks.\nusing namespace mlpack::regression;\n\n/**\n * Utility class with no functions.\n */\nclass EmptyTestFunction { };\n\n/**\n * Utility class with Evaluate() but no Evaluate().\n */\nclass EvaluateTestFunction\n{\n public:\n  double Evaluate(const arma::mat& coordinates)\n  {\n    return arma::accu(coordinates);\n  }\n\n  double Evaluate(const arma::mat& coordinates,\n                  const size_t begin,\n                  const size_t batchSize)\n  {\n    return arma::accu(coordinates) + begin + batchSize;\n  }\n};\n\n/**\n * Utility class with Gradient() but no Evaluate().\n */\nclass GradientTestFunction\n{\n public:\n  void Gradient(const arma::mat& coordinates, arma::mat& gradient)\n  {\n    gradient.ones(coordinates.n_rows, coordinates.n_cols);\n  }\n\n  void Gradient(const arma::mat& coordinates,\n                const size_t /* begin */,\n                arma::mat& gradient,\n                const size_t /* batchSize */)\n  {\n    gradient.ones(coordinates.n_rows, coordinates.n_cols);\n  }\n};\n\n/**\n * Utility class with Gradient() and Evaluate().\n */\nclass EvaluateGradientTestFunction\n{\n public:\n  double Evaluate(const arma::mat& coordinates)\n  {\n    return arma::accu(coordinates);\n  }\n\n  double Evaluate(const arma::mat& coordinates,\n                  const size_t /* begin */,\n                  const size_t /* batchSize */)\n  {\n    return arma::accu(coordinates);\n  }\n\n  void Gradient(const arma::mat& coordinates, arma::mat& gradient)\n  {\n    gradient.ones(coordinates.n_rows, coordinates.n_cols);\n  }\n\n  void Gradient(const arma::mat& coordinates,\n                const size_t /* begin */,\n                arma::mat& gradient,\n                const size_t /* batchSize */)\n  {\n    gradient.ones(coordinates.n_rows, coordinates.n_cols);\n  }\n};\n\n/**\n * Utility class with EvaluateWithGradient().\n */\nclass EvaluateWithGradientTestFunction\n{\n public:\n  double EvaluateWithGradient(const arma::mat& coordinates, arma::mat& gradient)\n  {\n    gradient.ones(coordinates.n_rows, coordinates.n_cols);\n    return arma::accu(coordinates);\n  }\n\n  double EvaluateWithGradient(const arma::mat& coordinates,\n                              const size_t /* begin */,\n                              arma::mat& gradient,\n                              const size_t /* batchSize */)\n  {\n    gradient.ones(coordinates.n_rows, coordinates.n_cols);\n    return arma::accu(coordinates);\n  }\n};\n\n/**\n * Utility class with all three functions.\n */\nclass EvaluateAndWithGradientTestFunction\n{\n public:\n  double Evaluate(const arma::mat& coordinates)\n  {\n    return arma::accu(coordinates);\n  }\n\n  double Evaluate(const arma::mat& coordinates,\n                  const size_t begin,\n                  const size_t batchSize)\n  {\n    return arma::accu(coordinates) + batchSize + begin;\n  }\n\n  void Gradient(const arma::mat& coordinates, arma::mat& gradient)\n  {\n    gradient.ones(coordinates.n_rows, coordinates.n_cols);\n  }\n\n  void Gradient(const arma::mat& coordinates,\n                const size_t /* begin */,\n                arma::mat& gradient,\n                const size_t /* batchSize */)\n  {\n    gradient.ones(coordinates.n_rows, coordinates.n_cols);\n  }\n\n  double EvaluateWithGradient(const arma::mat& coordinates, arma::mat& gradient)\n  {\n    gradient.ones(coordinates.n_rows, coordinates.n_cols);\n    return arma::accu(coordinates);\n  }\n\n  double EvaluateWithGradient(const arma::mat& coordinates,\n                              const size_t /* begin */,\n                              arma::mat& gradient,\n                              const size_t /* batchSize */)\n  {\n    gradient.ones(coordinates.n_rows, coordinates.n_cols);\n    return arma::accu(coordinates);\n  }\n};\n\n/**\n * Utility class with const Evaluate() and non-const Gradient().\n */\nclass EvaluateAndNonConstGradientTestFunction\n{\n public:\n  double Evaluate(const arma::mat& coordinates) const\n  {\n    return arma::accu(coordinates);\n  }\n\n  void Gradient(const arma::mat& coordinates, arma::mat& gradient)\n  {\n    gradient.ones(coordinates.n_rows, coordinates.n_cols);\n  }\n};\n\n/**\n * Utility class with const Evaluate() and non-const Gradient().\n */\nclass EvaluateAndStaticGradientTestFunction\n{\n public:\n  double Evaluate(const arma::mat& coordinates) const\n  {\n    return arma::accu(coordinates);\n  }\n\n  static void Gradient(const arma::mat& coordinates, arma::mat& gradient)\n  {\n    gradient.ones(coordinates.n_rows, coordinates.n_cols);\n  }\n};\n\nBOOST_AUTO_TEST_SUITE(FunctionTest);\n\n/**\n * Make sure that an empty class doesn't have any methods added to it.\n */\nBOOST_AUTO_TEST_CASE(AddEvaluateWithGradientEmptyTest)\n{\n  const bool hasEvaluate = HasEvaluate<Function<EmptyTestFunction>,\n                                       EvaluateForm>::value;\n  const bool hasGradient = HasGradient<Function<EmptyTestFunction>,\n                                       GradientForm>::value;\n  const bool hasEvaluateWithGradient =\n      HasEvaluateWithGradient<Function<EmptyTestFunction>,\n                              EvaluateWithGradientForm>::value;\n\n  BOOST_REQUIRE_EQUAL(hasEvaluate, false);\n  BOOST_REQUIRE_EQUAL(hasGradient, false);\n  BOOST_REQUIRE_EQUAL(hasEvaluateWithGradient, false);\n}\n\n/**\n * Make sure we don't add any functions if we only have Evaluate().\n */\nBOOST_AUTO_TEST_CASE(AddEvaluateWithGradientEvaluateOnlyTest)\n{\n  const bool hasEvaluate = HasEvaluate<Function<EvaluateTestFunction>,\n                                       EvaluateForm>::value;\n  const bool hasGradient = HasGradient<Function<EvaluateTestFunction>,\n                                       GradientForm>::value;\n  const bool hasEvaluateWithGradient =\n      HasEvaluateWithGradient<Function<EvaluateTestFunction>,\n                              EvaluateWithGradientForm>::value;\n\n  BOOST_REQUIRE_EQUAL(hasEvaluate, true);\n  BOOST_REQUIRE_EQUAL(hasGradient, false);\n  BOOST_REQUIRE_EQUAL(hasEvaluateWithGradient, false);\n}\n\n/**\n * Make sure we don't add any functions if we only have Gradient().\n */\nBOOST_AUTO_TEST_CASE(AddEvaluateWithGradientGradientOnlyTest)\n{\n  const bool hasEvaluate = HasEvaluate<Function<GradientTestFunction>,\n                                       EvaluateForm>::value;\n  const bool hasGradient = HasGradient<Function<GradientTestFunction>,\n                                       GradientForm>::value;\n  const bool hasEvaluateWithGradient =\n      HasEvaluateWithGradient<Function<GradientTestFunction>,\n                              EvaluateWithGradientForm>::value;\n\n  BOOST_REQUIRE_EQUAL(hasEvaluate, false);\n  BOOST_REQUIRE_EQUAL(hasGradient, true);\n  BOOST_REQUIRE_EQUAL(hasEvaluateWithGradient, false);\n}\n\n/**\n * Make sure we add EvaluateWithGradient() when we have both Evaluate() and\n * Gradient().\n */\nBOOST_AUTO_TEST_CASE(AddEvaluateWithGradientBothTest)\n{\n  const bool hasEvaluate =\n      HasEvaluate<Function<EvaluateGradientTestFunction>,\n                           EvaluateForm>::value;\n  const bool hasGradient =\n      HasGradient<Function<EvaluateGradientTestFunction>,\n                           GradientForm>::value;\n  const bool hasEvaluateWithGradient =\n      HasEvaluateWithGradient<Function<EvaluateGradientTestFunction>,\n                              EvaluateWithGradientForm>::value;\n\n  BOOST_REQUIRE_EQUAL(hasEvaluate, true);\n  BOOST_REQUIRE_EQUAL(hasGradient, true);\n  BOOST_REQUIRE_EQUAL(hasEvaluateWithGradient, true);\n}\n\n/**\n * Make sure we add Evaluate() and Gradient() when we have only\n * EvaluateWithGradient().\n */\nBOOST_AUTO_TEST_CASE(AddEvaluateWithGradientEvaluateWithGradientTest)\n{\n  const bool hasEvaluate =\n      HasEvaluate<Function<EvaluateWithGradientTestFunction>,\n                           EvaluateForm>::value;\n  const bool hasGradient =\n      HasGradient<Function<EvaluateWithGradientTestFunction>,\n                           GradientForm>::value;\n  const bool hasEvaluateWithGradient =\n      HasEvaluateWithGradient<Function<EvaluateWithGradientTestFunction>,\n                              EvaluateWithGradientForm>::value;\n\n  BOOST_REQUIRE_EQUAL(hasEvaluate, true);\n  BOOST_REQUIRE_EQUAL(hasGradient, true);\n  BOOST_REQUIRE_EQUAL(hasEvaluateWithGradient, true);\n}\n\n/**\n * Make sure we add no methods when we already have all three.\n */\nBOOST_AUTO_TEST_CASE(AddEvaluateWithGradientAllThreeTest)\n{\n  const bool hasEvaluate =\n      HasEvaluate<Function<EvaluateAndWithGradientTestFunction>,\n                           EvaluateForm>::value;\n  const bool hasGradient =\n      HasGradient<Function<EvaluateAndWithGradientTestFunction>,\n                           GradientForm>::value;\n  const bool hasEvaluateWithGradient =\n      HasEvaluateWithGradient<Function<EvaluateAndWithGradientTestFunction>,\n                              EvaluateWithGradientForm>::value;\n\n  BOOST_REQUIRE_EQUAL(hasEvaluate, true);\n  BOOST_REQUIRE_EQUAL(hasGradient, true);\n  BOOST_REQUIRE_EQUAL(hasEvaluateWithGradient, true);\n}\n\nBOOST_AUTO_TEST_CASE(LogisticRegressionEvaluateWithGradientTest)\n{\n  const bool hasEvaluate =\n      HasEvaluate<Function<LogisticRegressionFunction<>>,\n                           EvaluateConstForm>::value;\n  const bool hasGradient =\n      HasGradient<Function<LogisticRegressionFunction<>>,\n                           GradientConstForm>::value;\n  const bool hasEvaluateWithGradient =\n      HasEvaluateWithGradient<Function<LogisticRegressionFunction<>>,\n                              EvaluateWithGradientConstForm>::value;\n\n  BOOST_REQUIRE_EQUAL(hasEvaluate, true);\n  BOOST_REQUIRE_EQUAL(hasGradient, true);\n  BOOST_REQUIRE_EQUAL(hasEvaluateWithGradient, true);\n}\n\nBOOST_AUTO_TEST_CASE(SDPTest)\n{\n  typedef AugLagrangianFunction<LRSDPFunction<SDP<arma::mat>>> FunctionType;\n\n  const bool hasEvaluate =\n      HasEvaluate<Function<FunctionType>, EvaluateConstForm>::value;\n  const bool hasGradient =\n      HasGradient<Function<FunctionType>, GradientConstForm>::value;\n  const bool hasEvaluateWithGradient =\n      HasEvaluateWithGradient<Function<FunctionType>,\n                              EvaluateWithGradientConstForm>::value;\n\n  BOOST_REQUIRE_EQUAL(hasEvaluate, true);\n  BOOST_REQUIRE_EQUAL(hasGradient, true);\n  BOOST_REQUIRE_EQUAL(hasEvaluateWithGradient, true);\n}\n\n/**\n * Make sure that an empty class doesn't have any methods added to it.\n */\nBOOST_AUTO_TEST_CASE(AddDecomposableEvaluateWithGradientEmptyTest)\n{\n  const bool hasEvaluate = HasEvaluate<Function<EmptyTestFunction>,\n                                       DecomposableEvaluateForm>::value;\n  const bool hasGradient = HasGradient<Function<EmptyTestFunction>,\n                                       DecomposableGradientForm>::value;\n  const bool hasEvaluateWithGradient =\n      HasEvaluateWithGradient<Function<EmptyTestFunction>,\n                              DecomposableEvaluateWithGradientForm>::value;\n\n  BOOST_REQUIRE_EQUAL(hasEvaluate, false);\n  BOOST_REQUIRE_EQUAL(hasGradient, false);\n  BOOST_REQUIRE_EQUAL(hasEvaluateWithGradient, false);\n}\n\n/**\n * Make sure we don't add any functions if we only have Evaluate().\n */\nBOOST_AUTO_TEST_CASE(AddDecomposableEvaluateWithGradientEvaluateOnlyTest)\n{\n  const bool hasEvaluate = HasEvaluate<Function<EvaluateTestFunction>,\n                                       DecomposableEvaluateForm>::value;\n  const bool hasGradient = HasGradient<Function<EvaluateTestFunction>,\n                                       DecomposableGradientForm>::value;\n  const bool hasEvaluateWithGradient =\n      HasEvaluateWithGradient<Function<EvaluateTestFunction>,\n                              DecomposableEvaluateWithGradientForm>::value;\n\n  BOOST_REQUIRE_EQUAL(hasEvaluate, true);\n  BOOST_REQUIRE_EQUAL(hasGradient, false);\n  BOOST_REQUIRE_EQUAL(hasEvaluateWithGradient, false);\n}\n\n/**\n * Make sure we don't add any functions if we only have Gradient().\n */\nBOOST_AUTO_TEST_CASE(AddDecomposableEvaluateWithGradientGradientOnlyTest)\n{\n  const bool hasEvaluate = HasEvaluate<Function<GradientTestFunction>,\n                                       DecomposableEvaluateForm>::value;\n  const bool hasGradient = HasGradient<Function<GradientTestFunction>,\n                                       DecomposableGradientForm>::value;\n  const bool hasEvaluateWithGradient =\n      HasEvaluateWithGradient<Function<GradientTestFunction>,\n                              DecomposableEvaluateWithGradientForm>::value;\n\n  BOOST_REQUIRE_EQUAL(hasEvaluate, false);\n  BOOST_REQUIRE_EQUAL(hasGradient, true);\n  BOOST_REQUIRE_EQUAL(hasEvaluateWithGradient, false);\n}\n\n/**\n * Make sure we add EvaluateWithGradient() when we have both Evaluate() and\n * Gradient().\n */\nBOOST_AUTO_TEST_CASE(AddDecomposableEvaluateWithGradientBothTest)\n{\n  const bool hasEvaluate =\n      HasEvaluate<Function<EvaluateGradientTestFunction>,\n                           DecomposableEvaluateForm>::value;\n  const bool hasGradient =\n      HasGradient<Function<EvaluateGradientTestFunction>,\n                           DecomposableGradientForm>::value;\n  const bool hasEvaluateWithGradient =\n      HasEvaluateWithGradient<Function<EvaluateGradientTestFunction>,\n                              DecomposableEvaluateWithGradientForm>::value;\n\n  BOOST_REQUIRE_EQUAL(hasEvaluate, true);\n  BOOST_REQUIRE_EQUAL(hasGradient, true);\n  BOOST_REQUIRE_EQUAL(hasEvaluateWithGradient, true);\n}\n\n/**\n * Make sure we add Evaluate() and Gradient() when we have only\n * EvaluateWithGradient().\n */\nBOOST_AUTO_TEST_CASE(AddDecomposableEvaluateWGradientEvaluateWithGradientTest)\n{\n  const bool hasEvaluate =\n      HasEvaluate<Function<EvaluateWithGradientTestFunction>,\n                           DecomposableEvaluateForm>::value;\n  const bool hasGradient =\n      HasGradient<Function<EvaluateWithGradientTestFunction>,\n                           DecomposableGradientForm>::value;\n  const bool hasEvaluateWithGradient =\n      HasEvaluateWithGradient<Function<EvaluateWithGradientTestFunction>,\n                              DecomposableEvaluateWithGradientForm>::value;\n\n  Function<EvaluateWithGradientTestFunction> f;\n  arma::mat coordinates(10, 10, arma::fill::ones);\n  arma::mat gradient;\n  f.Gradient(coordinates, 0, gradient, 5);\n\n  BOOST_REQUIRE_EQUAL(hasEvaluate, true);\n  BOOST_REQUIRE_EQUAL(hasGradient, true);\n  BOOST_REQUIRE_EQUAL(hasEvaluateWithGradient, true);\n}\n\n/**\n * Make sure we add no methods when we already have all three.\n */\nBOOST_AUTO_TEST_CASE(AddDecomposableEvaluateWithGradientAllThreeTest)\n{\n  const bool hasEvaluate =\n      HasEvaluate<Function<EvaluateAndWithGradientTestFunction>,\n                  DecomposableEvaluateForm>::value;\n  const bool hasGradient =\n      HasGradient<Function<EvaluateAndWithGradientTestFunction>,\n                           DecomposableGradientForm>::value;\n  const bool hasEvaluateWithGradient =\n      HasEvaluateWithGradient<Function<EvaluateAndWithGradientTestFunction>,\n                              DecomposableEvaluateWithGradientForm>::value;\n\n  BOOST_REQUIRE_EQUAL(hasEvaluate, true);\n  BOOST_REQUIRE_EQUAL(hasGradient, true);\n  BOOST_REQUIRE_EQUAL(hasEvaluateWithGradient, true);\n}\n\n/**\n * Make sure we can properly create EvaluateWithGradient() even when one of the\n * functions is non-const.\n */\nBOOST_AUTO_TEST_CASE(AddEvaluateWithGradientMixedTypesTest)\n{\n  const bool hasEvaluate =\n      HasEvaluate<Function<EvaluateAndNonConstGradientTestFunction>,\n                  EvaluateConstForm>::value;\n  const bool hasGradient =\n      HasGradient<Function<EvaluateAndNonConstGradientTestFunction>,\n                  GradientForm>::value;\n  const bool hasEvaluateWithGradient =\n      HasEvaluateWithGradient<Function<EvaluateAndNonConstGradientTestFunction>,\n                              EvaluateWithGradientForm>::value;\n\n  BOOST_REQUIRE_EQUAL(hasEvaluate, true);\n  BOOST_REQUIRE_EQUAL(hasGradient, true);\n  BOOST_REQUIRE_EQUAL(hasEvaluateWithGradient, true);\n}\n\n/**\n * Make sure we can properly create EvaluateWithGradient() even when one of the\n * functions is static.\n */\nBOOST_AUTO_TEST_CASE(AddEvaluateWithGradientMixedTypesStaticTest)\n{\n  const bool hasEvaluate =\n      HasEvaluate<Function<EvaluateAndStaticGradientTestFunction>,\n                  EvaluateConstForm>::value;\n  const bool hasGradient =\n      HasGradient<Function<EvaluateAndStaticGradientTestFunction>,\n                  GradientStaticForm>::value;\n  const bool hasEvaluateWithGradient =\n      HasEvaluateWithGradient<Function<EvaluateAndStaticGradientTestFunction>,\n                              EvaluateWithGradientConstForm>::value;\n\n  BOOST_REQUIRE_EQUAL(hasEvaluate, true);\n  BOOST_REQUIRE_EQUAL(hasGradient, true);\n  BOOST_REQUIRE_EQUAL(hasEvaluateWithGradient, true);\n}\n\nclass A\n{\n public:\n  size_t NumFunctions() const;\n  size_t NumFeatures() const;\n  double Evaluate(const arma::mat&, const size_t, const size_t) const;\n  void Gradient(const arma::mat&, const size_t, arma::mat&, const size_t) const;\n  void Gradient(const arma::mat&, const size_t, arma::sp_mat&, const size_t)\n      const;\n  void PartialGradient(const arma::mat&, const size_t, arma::sp_mat&) const;\n};\n\nclass B\n{\n public:\n  size_t NumFunctions();\n  size_t NumFeatures();\n  double Evaluate(const arma::mat&, const size_t, const size_t);\n  void Gradient(const arma::mat&, const size_t, arma::mat&, const size_t);\n  void Gradient(const arma::mat&, const size_t, arma::sp_mat&, const size_t);\n  void PartialGradient(const arma::mat&, const size_t, arma::sp_mat&);\n};\n\nclass C\n{\n public:\n  size_t NumConstraints() const;\n  double Evaluate(const arma::mat&) const;\n  void Gradient(const arma::mat&, arma::mat&) const;\n  double EvaluateConstraint(const size_t, const arma::mat&) const;\n  void GradientConstraint(const size_t, const arma::mat&, arma::mat&) const;\n};\n\nclass D\n{\n public:\n  size_t NumConstraints();\n  double Evaluate(const arma::mat&);\n  void Gradient(const arma::mat&, arma::mat&);\n  double EvaluateConstraint(const size_t, const arma::mat&);\n  void GradientConstraint(const size_t, const arma::mat&, arma::mat&);\n};\n\n\n/**\n * Test the correctness of the static check for DecomposableFunctionType API.\n */\nBOOST_AUTO_TEST_CASE(DecomposableFunctionTypeCheckTest)\n{\n  static_assert(CheckNumFunctions<A>::value,\n      \"CheckNumFunctions static check failed.\");\n  static_assert(CheckNumFunctions<B>::value,\n      \"CheckNumFunctions static check failed.\");\n  static_assert(!CheckNumFunctions<C>::value,\n      \"CheckNumFunctions static check failed.\");\n  static_assert(!CheckNumFunctions<D>::value,\n      \"CheckNumFunctions static check failed.\");\n\n  static_assert(CheckDecomposableEvaluate<A>::value,\n      \"CheckDecomposableEvaluate static check failed.\");\n  static_assert(CheckDecomposableEvaluate<B>::value,\n      \"CheckDecomposableEvaluate static check failed.\");\n  static_assert(!CheckDecomposableEvaluate<C>::value,\n      \"CheckDecomposableEvaluate static check failed.\");\n  static_assert(!CheckDecomposableEvaluate<D>::value,\n      \"CheckDecomposableEvaluate static check failed.\");\n\n  static_assert(CheckDecomposableGradient<A>::value,\n      \"CheckDecomposableGradient static check failed.\");\n  static_assert(CheckDecomposableGradient<B>::value,\n      \"CheckDecomposableGradient static check failed.\");\n  static_assert(!CheckDecomposableGradient<C>::value,\n      \"CheckDecomposableGradient static check failed.\");\n  static_assert(!CheckDecomposableGradient<D>::value,\n      \"CheckDecomposableGradient static check failed.\");\n}\n\n/**\n * Test the correctness of the static check for LagrangianFunctionType API.\n */\nBOOST_AUTO_TEST_CASE(LagrangianFunctionTypeCheckTest)\n{\n  static_assert(!CheckEvaluate<A>::value, \"CheckEvaluate static check failed.\");\n  static_assert(!CheckEvaluate<B>::value, \"CheckEvaluate static check failed.\");\n  static_assert(CheckEvaluate<C>::value, \"CheckEvaluate static check failed.\");\n  static_assert(CheckEvaluate<D>::value, \"CheckEvaluate static check failed.\");\n\n  static_assert(!CheckGradient<A>::value, \"CheckGradient static check failed.\");\n  static_assert(!CheckGradient<B>::value, \"CheckGradient static check failed.\");\n  static_assert(CheckGradient<C>::value, \"CheckGradient static check failed.\");\n  static_assert(CheckGradient<D>::value, \"CheckGradient static check failed.\");\n\n  static_assert(!CheckNumConstraints<A>::value,\n      \"CheckNumConstraints static check failed.\");\n  static_assert(!CheckNumConstraints<B>::value,\n      \"CheckNumConstraints static check failed.\");\n  static_assert(CheckNumConstraints<C>::value,\n      \"CheckNumConstraints static check failed.\");\n  static_assert(CheckNumConstraints<D>::value,\n      \"CheckNumConstraints static check failed.\");\n\n  static_assert(!CheckEvaluateConstraint<A>::value,\n      \"CheckEvaluateConstraint static check failed.\");\n  static_assert(!CheckEvaluateConstraint<B>::value,\n      \"CheckEvaluateConstraint static check failed.\");\n  static_assert(CheckEvaluateConstraint<C>::value,\n      \"CheckEvaluateConstraint static check failed.\");\n  static_assert(CheckEvaluateConstraint<D>::value,\n      \"CheckEvaluateConstraint static check failed.\");\n\n  static_assert(!CheckGradientConstraint<A>::value,\n      \"CheckGradientConstraint static check failed.\");\n  static_assert(!CheckGradientConstraint<B>::value,\n      \"CheckGradientConstraint static check failed.\");\n  static_assert(CheckGradientConstraint<C>::value,\n      \"CheckGradientConstraint static check failed.\");\n  static_assert(CheckGradientConstraint<D>::value,\n      \"CheckGradientConstraint static check failed.\");\n}\n\n/**\n * Test the correctness of the static check for SparseFunctionType API.\n */\nBOOST_AUTO_TEST_CASE(SparseFunctionTypeCheckTest)\n{\n  static_assert(CheckSparseGradient<A>::value,\n      \"CheckSparseGradient static check failed.\");\n  static_assert(CheckSparseGradient<B>::value,\n      \"CheckSparseGradient static check failed.\");\n  static_assert(!CheckSparseGradient<C>::value,\n      \"CheckSparseGradient static check failed.\");\n  static_assert(!CheckSparseGradient<D>::value,\n      \"CheckSparseGradient static check failed.\");\n}\n\n/**\n * Test the correctness of the static check for SparseFunctionType API.\n */\nBOOST_AUTO_TEST_CASE(ResolvableFunctionTypeCheckTest)\n{\n  static_assert(CheckNumFeatures<A>::value,\n      \"CheckNumFeatures static check failed.\");\n  static_assert(CheckNumFeatures<B>::value,\n      \"CheckNumFeatures static check failed.\");\n  static_assert(!CheckNumFeatures<C>::value,\n      \"CheckNumFeatures static check failed.\");\n  static_assert(!CheckNumFeatures<D>::value,\n      \"CheckNumFeatures static check failed.\");\n\n  static_assert(CheckPartialGradient<A>::value,\n      \"CheckPartialGradient static check failed.\");\n  static_assert(CheckPartialGradient<B>::value,\n      \"CheckPartialGradient static check failed.\");\n  static_assert(!CheckPartialGradient<C>::value,\n      \"CheckPartialGradient static check failed.\");\n  static_assert(!CheckPartialGradient<D>::value,\n      \"CheckPartialGradient static check failed.\");\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "922714a076af4e2585f52063d65e2f2776effbb0", "size": 23636, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/function_test.cpp", "max_stars_repo_name": "chigur/mlpack", "max_stars_repo_head_hexsha": "aff1eda03b7c279acb6d3e660d5c5a6f697d3735", "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/tests/function_test.cpp", "max_issues_repo_name": "chigur/mlpack", "max_issues_repo_head_hexsha": "aff1eda03b7c279acb6d3e660d5c5a6f697d3735", "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/tests/function_test.cpp", "max_forks_repo_name": "chigur/mlpack", "max_forks_repo_head_hexsha": "aff1eda03b7c279acb6d3e660d5c5a6f697d3735", "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": 34.6568914956, "max_line_length": 80, "alphanum_fraction": 0.712768658, "num_tokens": 4817, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149978955811, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.46712662983756537}}
{"text": "//\n//  Copyright Toon Knapen, Karl Meerbergen\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#include \"ublas_heev.hpp\"\n\n#include <boost/numeric/bindings/lapack/driver/hbev.hpp>\n#include <boost/numeric/bindings/lapack/driver/sbev.hpp>\n#include <boost/numeric/bindings/ublas/matrix.hpp>\n#include <boost/numeric/bindings/ublas/matrix_proxy.hpp>\n#include <boost/numeric/bindings/ublas/vector.hpp>\n#include <boost/numeric/bindings/ublas/vector_proxy.hpp>\n#include <boost/numeric/bindings/ublas/banded.hpp>\n#include <boost/numeric/bindings/ublas/hermitian.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/type_traits/is_complex.hpp>\n#include <boost/mpl/if.hpp>\n\n#include <iostream>\n\n\nnamespace ublas = boost::numeric::ublas;\nnamespace lapack = boost::numeric::bindings::lapack;\nnamespace bindings = boost::numeric::bindings;\n\ntemplate <typename U>\nint lower()\n{\n  return 0;\n}\n\ntemplate <>\nint lower<ublas::lower>()\n{\n  return 2;\n}\n\n\ntemplate <typename U>\nint upper()\n{\n  return 0;\n}\n\ntemplate <>\nint upper<ublas::upper>()\n{\n  return 2;\n}\n\n\ntemplate <typename T, typename W, typename UPLO, typename Orientation>\nint do_memory_uplo(int n, W& workspace)\n{\n  typedef typename bindings::remove_imaginary<T>::type real_type ;\n\n  typedef ublas::banded_matrix<T, Orientation>      banded_type ;\n  typedef ublas::matrix<T, ublas::column_major>     matrix_type ;\n  typedef ublas::vector<real_type>                  vector_type ;\n\n  // Set matrix\n  banded_type a(n, n, lower<UPLO>(), upper<UPLO>());\n  a.clear(); // Make upper triangular band matrix\n  matrix_type z(n, n);\n  vector_type e1(n);\n  vector_type e2(n);\n\n  fill_banded(a);\n  banded_type a2(a);\n\n  ublas::hermitian_adaptor<banded_type, UPLO> h(a), h2(a2);\n\n  // Compute Schur decomposition.\n  lapack::hbev('V',\n               h, e1, z, workspace) ;\n\n  if(check_residual(h2, e1, z)) return 255 ;\n\n  matrix_type dummy_z(n, n);\n  lapack::hbev('N',\n               h2, e2, dummy_z, workspace) ;\n  if(norm_2(e1 - e2) > n * norm_2(e1) * std::numeric_limits< real_type >::epsilon()) return 255 ;\n\n  // Test for a matrix range\n  fill_banded(a);\n  a2.assign(a);\n\n  typedef ublas::matrix_range< banded_type > banded_range ;\n\n  ublas::range r(1,n-1) ;\n  banded_range a_r(a, r, r);\n  ublas::hermitian_adaptor< banded_range, UPLO> h_r(a_r);\n  ublas::vector_range< vector_type> e_r(e1, r);\n  ublas::matrix_range< matrix_type> z_r(z, r, r);\n\n  lapack::hbev('V',\n               h_r, e_r, z_r, workspace);\n\n  banded_range a2_r(a2, r, r);\n  ublas::hermitian_adaptor< banded_range, UPLO> h2_r(a2_r);\n  if(check_residual(h2_r, e_r, z_r)) return 255 ;\n\n  return 0 ;\n} // do_memory_uplo()\n\n\ntemplate <typename T, typename W>\nint do_memory_type(int n, W workspace)\n{\n  std::cout << \"  upper\\n\" ;\n  if(do_memory_uplo<T,W,ublas::upper, ublas::row_major>(n, workspace)) return 255 ;\n  std::cout << \"  lower\\n\" ;\n  if(do_memory_uplo<T,W,ublas::lower, ublas::row_major>(n, workspace)) return 255 ;\n  return 0 ;\n}\n\n\ntemplate <typename T>\nstruct Workspace\n{\n  typedef ublas::vector<T>                         array_type ;\n  typedef lapack::detail::workspace1< array_type > type ;\n\n  Workspace(size_t n)\n    : work_(3*n-2)\n  {}\n\n  type operator()()\n  {\n    return lapack::workspace(work_) ;\n  }\n\n  array_type work_ ;\n};\n\n\ntemplate <typename T>\nstruct Workspace< std::complex<T> >\n{\n  typedef ublas::vector<T>                                                 real_array_type ;\n  typedef ublas::vector< std::complex<T> >                                 complex_array_type ;\n  typedef lapack::detail::workspace2< complex_array_type,real_array_type > type ;\n\n  Workspace(size_t n)\n    : work_(n)\n    , rwork_(3*n-2)\n  {}\n\n  type operator()()\n  {\n    return lapack::workspace(work_, rwork_) ;\n  }\n\n  complex_array_type work_ ;\n  real_array_type    rwork_ ;\n};\n\n\ntemplate <typename T>\nint do_value_type()\n{\n  const int n = 8 ;\n\n  std::cout << \" optimal workspace\\n\";\n  if(do_memory_type<T,lapack::optimal_workspace>(n, lapack::optimal_workspace())) return 255 ;\n\n  std::cout << \" minimal workspace\\n\";\n  if(do_memory_type<T,lapack::minimal_workspace>(n, lapack::minimal_workspace())) return 255 ;\n\n  std::cout << \" workspace array\\n\";\n  Workspace<T> work(n);\n  if(do_memory_type<T,typename Workspace<T>::type >(n, work())) return 255 ;\n  return 0;\n} // do_value_type()\n\n\nint main()\n{\n  // Run tests for different value_types\n  std::cout << \"float\\n\" ;\n  if(do_value_type<float>()) return 255;\n\n  std::cout << \"double\\n\" ;\n  if(do_value_type<double>()) return 255;\n\n  std::cout << \"complex<float>\\n\" ;\n  if(do_value_type< std::complex<float> >()) return 255;\n\n  std::cout << \"complex<double>\\n\" ;\n  if(do_value_type< std::complex<double> >()) return 255;\n\n  std::cout << \"Regression test succeeded\\n\" ;\n  return 0;\n}\n\n", "meta": {"hexsha": "e318feab050f8618edae6f3690bb8d6747f47dac", "size": 4847, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "externals/numeric_bindings/libs/numeric/bindings/lapack/test/ublas_hbev.cpp", "max_stars_repo_name": "fperignon/sandbox", "max_stars_repo_head_hexsha": "649f09d6db7bbd84c2418de74eb9453c0131f070", "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/lapack/test/ublas_hbev.cpp", "max_issues_repo_name": "fperignon/sandbox", "max_issues_repo_head_hexsha": "649f09d6db7bbd84c2418de74eb9453c0131f070", "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/lapack/test/ublas_hbev.cpp", "max_forks_repo_name": "fperignon/sandbox", "max_forks_repo_head_hexsha": "649f09d6db7bbd84c2418de74eb9453c0131f070", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 30.0, "max_forks_repo_forks_event_min_datetime": "2015-08-06T22:57:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T20:30:20.000Z", "avg_line_length": 24.235, "max_line_length": 97, "alphanum_fraction": 0.6663915824, "num_tokens": 1400, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.754914997895581, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.46712662983756525}}
{"text": "/*\n@copyright Louis Dionne 2014\nDistributed under the Boost Software License, Version 1.0.\n(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n */\n\n#include <boost/hana/detail/assert.hpp>\n#include <boost/hana/list/instance.hpp>\n#include <boost/hana/maybe.hpp>\nusing namespace boost::hana;\n\n\nint main() {\n    //! [main]\n    BOOST_HANA_CONSTEXPR_ASSERT(\n        sequence<Maybe>(list(just(1), just('2'), just(3.3))) == just(list(1, '2', 3.3))\n    );\n\n    BOOST_HANA_CONSTANT_ASSERT(\n        sequence<Maybe>(list(just(1), nothing, just(3.3))) == nothing\n    );\n\n    // This is a generalized Cartesian product.\n    BOOST_HANA_CONSTEXPR_ASSERT(\n        sequence<List>(list(list(1, 2, 3), list(4), list(5, 6)))\n        ==\n        list(\n            list(1, 4, 5), list(1, 4, 6),\n            list(2, 4, 5), list(2, 4, 6),\n            list(3, 4, 5), list(3, 4, 6)\n        )\n    );\n    //! [main]\n}\n", "meta": {"hexsha": "5bfffc2a18226bea52be8be8a3ec7c287135b028", "size": 915, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/traversable/sequence.cpp", "max_stars_repo_name": "rbock/hana", "max_stars_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-05-07T14:29:13.000Z", "max_stars_repo_stars_event_max_datetime": "2015-07-04T10:59:46.000Z", "max_issues_repo_path": "example/traversable/sequence.cpp", "max_issues_repo_name": "rbock/hana", "max_issues_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/traversable/sequence.cpp", "max_forks_repo_name": "rbock/hana", "max_forks_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.1428571429, "max_line_length": 87, "alphanum_fraction": 0.5890710383, "num_tokens": 285, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.6187804407739559, "lm_q1q2_score": 0.4671266283208162}}
{"text": "#include <boost/random/negative_binomial_distribution.hpp>\n", "meta": {"hexsha": "7d8cc3828bbb092031cc660f14fd056d5aecf57b", "size": 59, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_random_negative_binomial_distribution.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_random_negative_binomial_distribution.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_random_negative_binomial_distribution.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 29.5, "max_line_length": 58, "alphanum_fraction": 0.8644067797, "num_tokens": 11, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059707450326, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4670514857188199}}
{"text": "#include <Eigen/Dense>\n\n#include <ros/ros.h>\n#include <vector>\n#include <ros/node_handle.h>\n#include <ros/package.h>\n#include \"sensor_msgs/JointState.h\"\n\n#include \"panda_simulation/NE_matrix.hpp\"\n\nusing namespace std;\nusing namespace Eigen;\n\ntypedef Matrix<double, 7, 1> V7d;\ntypedef Matrix<double, 7, 7> M7d;\n\nclass Impedance{\n  private:\n    int argc;\n    char **argv;\n    \n  public:\n    Impedance(int argc, char ** argv);\n    void startControl();\n    Model *model;\n    void impedanceControl();\n    vector<ros::Publisher> publisher_vec;\n    ros::Subscriber robot_state_sub;\n    V7d q, dq;\n    void JointStateCallback(const sensor_msgs::JointState& msg);\n};\n\n", "meta": {"hexsha": "86ad59bef503fb4286872631be7416ec9c8c2d10", "size": 659, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/panda_simulation/impedance.hpp", "max_stars_repo_name": "Mingg8/panda_simulation", "max_stars_repo_head_hexsha": "465ae4bdd79937e43d14fe127f46cac5b3f00833", "max_stars_repo_licenses": ["MIT"], "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/panda_simulation/impedance.hpp", "max_issues_repo_name": "Mingg8/panda_simulation", "max_issues_repo_head_hexsha": "465ae4bdd79937e43d14fe127f46cac5b3f00833", "max_issues_repo_licenses": ["MIT"], "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/panda_simulation/impedance.hpp", "max_forks_repo_name": "Mingg8/panda_simulation", "max_forks_repo_head_hexsha": "465ae4bdd79937e43d14fe127f46cac5b3f00833", "max_forks_repo_licenses": ["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.9696969697, "max_line_length": 64, "alphanum_fraction": 0.6980273141, "num_tokens": 172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.46705147995921314}}
{"text": "#include \"SimilarityImageGrouper.h\"\n\n#include <boost/filesystem.hpp>\n#include <opencv2/core.hpp>\n#include <opencv2/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n\nusing namespace cgcolle::encoder;\n\nstatic cv::Mat calcHist(const cv::Mat &image)\n{\n    cv::Mat hsvImage;\n    cvtColor(image, hsvImage, cv::COLOR_BGR2HSV);\n\n    int hBins = 50;\n    int sBins = 60;\n    int histSize[] = { hBins, sBins };\n    float hRanges[] = { 0, 180 };\n    float sRanges[] = { 0, 256 };\n    const float *ranges[] = { hRanges, sRanges };\n    int channels[] = { 0, 1 };\n\n    cv::Mat hist;\n    cv::calcHist(&hsvImage, 1, channels, cv::Mat(), hist, 2, histSize,\n                 ranges, true, false);\n    cv::normalize(hist, hist, 0, 1, cv::NORM_MINMAX, -1, cv::Mat());\n\n    return hist;\n}\n\nstd::vector<ImageGroup*> SimilarityImageGrouper::group(const std::vector<std::string>& imagePaths)\n{\n    typedef std::pair<cv::Mat, cv::Size> HistPair;\n\n    // Calc histograms\n    std::vector<HistPair> histograms(imagePaths.size());\n    std::transform(imagePaths.begin(), imagePaths.end(), histograms.begin(), [](const std::string &imagePath) -> HistPair {\n        cv::Mat image = cv::imread(imagePath);\n        cv::Mat hist = calcHist(image);\n\n        return HistPair(hist, image.size());\n    });\n\n    // Partition sizes\n    std::vector<int> sizeLabels(histograms.size());\n    int sizeLabelsCnt = cv::partition(histograms, sizeLabels, [](const HistPair &left, const HistPair &right) {\n        const cv::Size &lsize = left.second;\n        const cv::Size &rsize = right.second;\n\n        return lsize.width == rsize.width && lsize.height == rsize.height;\n    });\n\n    // Paritition histograms\n    std::vector<int> histLabels(imagePaths.size());\n    int histLabelsCnt = cv::partition(histograms, histLabels, [this](const HistPair &left, const HistPair &right) -> bool {\n        return cv::compareHist(left.first, right.first, 0) >= 0.95;\n    });\n\n    typedef std::tuple<int, int, int> ImageInfo; // idx, size, hist\n    std::vector<std::tuple<int, int, int> > imageInfos;\n    for (int i = 0; i < imagePaths.size(); ++i) {\n        imageInfos.push_back(std::make_tuple(i, sizeLabels[i], histLabels[i]));\n    }\n\n    // Sort by labels\n    std::sort(imageInfos.begin(), imageInfos.end(), [](const ImageInfo &l, const ImageInfo &r) -> bool {\n        // Compare size\n        if (std::get<1>(l) != std::get<1>(r)) {\n            return std::get<1>(l) > std::get<1>(r);\n        }\n\n        // Compare hist\n        return std::get<2>(l) > std::get<2>(r);\n    });\n\n    // Build groups\n    std::vector<ImageGroup*> groups;\n    int curSizeLabel = 0;\n    int curHistLabel = 0;\n    ImageGroup *group = nullptr;\n    for (const ImageInfo &imageInfo : imageInfos) {\n        int index, sizeLabel, histLabel;\n        std::tie(index, sizeLabel, histLabel) = imageInfo;\n\n        const boost::filesystem::path imagePath(imagePaths[index]);\n        const std::string fileName = imagePath.filename().string();\n        cgcolle::ImageEntry *entry = new cgcolle::ImageEntry(fileName, imagePath.string());\n\n        bool isGroupChanged = sizeLabel != curSizeLabel || histLabel != curHistLabel;\n        if (group == nullptr || isGroupChanged) {\n            // Main frame\n            group = new ImageGroup();\n            groups.push_back(group);\n\n            group->mainFrame = entry;\n            curSizeLabel = sizeLabel;\n            curHistLabel = histLabel;\n        } else {\n            // Sub frame\n            group->subFrames.push_back(entry);\n        }\n    }\n\n    return groups;\n}\n", "meta": {"hexsha": "35b0e825bd2a23551bcb87f0edbd3ba3d4b83458", "size": 3522, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "encoder/SimilarityImageGrouper.cpp", "max_stars_repo_name": "ArchangelSDY/cgcolle", "max_stars_repo_head_hexsha": "843bdef42e72a157197fb55203f70f30eb31704b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "encoder/SimilarityImageGrouper.cpp", "max_issues_repo_name": "ArchangelSDY/cgcolle", "max_issues_repo_head_hexsha": "843bdef42e72a157197fb55203f70f30eb31704b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "encoder/SimilarityImageGrouper.cpp", "max_forks_repo_name": "ArchangelSDY/cgcolle", "max_forks_repo_head_hexsha": "843bdef42e72a157197fb55203f70f30eb31704b", "max_forks_repo_licenses": ["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.2264150943, "max_line_length": 123, "alphanum_fraction": 0.60959682, "num_tokens": 943, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.46705147419960624}}
{"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 *    Notes\n *      This unit test does not include testing with the function\n *      testFunctionWithLargeRootDifferences, because this test function does not provide a second\n *      derivative.\n *\n */\n\n#include <boost/bind.hpp>\n#include <boost/make_shared.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/unit_test.hpp>\n\n#include \"Tudat/Mathematics/RootFinders/halleyRootFinder.h\"\n#include \"Tudat/Mathematics/RootFinders/UnitTests/testFunction1.h\"\n#include \"Tudat/Mathematics/RootFinders/UnitTests/testFunction2.h\"\n#include \"Tudat/Mathematics/RootFinders/UnitTests/testFunction3.h\"\n#include \"Tudat/Mathematics/RootFinders/UnitTests/testFunctionWithZeroRoot.h\"\n\nnamespace tudat\n{\nnamespace unit_tests\n{\n\nBOOST_AUTO_TEST_SUITE( testsuite_rootfinders )\n\nusing namespace tudat;\nusing namespace root_finders;\nusing namespace root_finders::termination_conditions;\n\n//! Check if Halley method converges on test function #1 (TestFunction1).\nBOOST_AUTO_TEST_CASE( test_halleyRootFinder_testFunction1 )\n{\n    // Create object containing the test functions.\n    std::shared_ptr< TestFunction1 > testFunction = std::make_shared< TestFunction1 >( 2 );\n\n    // The termination condition.\n    HalleyRootFinder::TerminationFunction terminationConditionFunction =\n            std::bind( &RootAbsoluteToleranceTerminationCondition< double >::checkTerminationCondition,\n                         std::make_shared< RootAbsoluteToleranceTerminationCondition< double > >(\n                             testFunction->getTrueRootAccuracy( ) ), std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4, std::placeholders::_5 );\n\n    // Test Halley object.\n    HalleyRootFinder halleyRootFinder( terminationConditionFunction );\n\n    // Let the Halley method search for the root.\n    const double root = halleyRootFinder.execute( testFunction, testFunction->getInitialGuess( ) );\n\n    // Check if the result is within the requested accuracy.\n    BOOST_CHECK_CLOSE_FRACTION( root, testFunction->getTrueRootLocation( ), 1.0e-15 );\n    BOOST_CHECK_LT( testFunction->evaluate( root ), testFunction->getTrueRootAccuracy( ) );\n}\n\n//! Check if Halley method converges on test function #2 (TestFunction2).\nBOOST_AUTO_TEST_CASE( test_halleyRootFinder_testFunction2 )\n{\n    // Create object containing the test functions.\n    std::shared_ptr< TestFunction2 > testFunction = std::make_shared< TestFunction2 >( 2 );\n\n    // The termination condition.\n    HalleyRootFinder::TerminationFunction terminationConditionFunction =\n            std::bind( &RootAbsoluteToleranceTerminationCondition< double >::checkTerminationCondition,\n                         std::make_shared< RootAbsoluteToleranceTerminationCondition< double > >(\n                             testFunction->getTrueRootAccuracy( ) ), std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4, std::placeholders::_5 );\n\n    // Test Halley object.\n    HalleyRootFinder halleyRootFinder( terminationConditionFunction );\n\n    // Let the Halley method search for the root.\n    const double root = halleyRootFinder.execute( testFunction, testFunction->getInitialGuess( ) );\n\n    // Check if the result is within the requested accuracy.\n    BOOST_CHECK_CLOSE_FRACTION( root, testFunction->getTrueRootLocation( ), 1.0e-15 );\n    BOOST_CHECK_LT( testFunction->evaluate( root ), testFunction->getTrueRootAccuracy( ) );\n}\n\n//! Check if Halley method converges on test function #3 (TestFunction3).\nBOOST_AUTO_TEST_CASE( test_halleyRootFinder_testFunction3 )\n{\n    // Create object containing the test functions.\n    std::shared_ptr< TestFunction3 > testFunction = std::make_shared< TestFunction3 >( 2 );\n\n    // The termination condition.\n    HalleyRootFinder::TerminationFunction terminationConditionFunction =\n            std::bind( &RootAbsoluteToleranceTerminationCondition< double >::checkTerminationCondition,\n                         std::make_shared< RootAbsoluteToleranceTerminationCondition< double > >(\n                             testFunction->getTrueRootAccuracy( ) ), std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4, std::placeholders::_5 );\n\n    // Test Halley object.\n    HalleyRootFinder halleyRootFinder( terminationConditionFunction );\n\n    // Let the Halley method search for the root.\n    const double root = halleyRootFinder.execute( testFunction, testFunction->getInitialGuess( ) );\n\n    // Check if the result is within the requested accuracy.\n    BOOST_CHECK_CLOSE_FRACTION( root, testFunction->getTrueRootLocation( ), 1.0e-15 );\n    BOOST_CHECK_LT( testFunction->evaluate( root ), testFunction->getTrueRootAccuracy( ) );\n}\n\n//! Check if Halley method converges on function with zero root (testFunctionWithZeroRoot).\n// Not the best test case. Inheritance from old code. Not really relevant anymore. The basic\n// idea is that Halley's method should work for both a function that becomes zero, as well as for a\n// function that does not become zero. A better case should be written.\nBOOST_AUTO_TEST_CASE( test_halleyRootFinder_testFunctionWithZeroRoot )\n{\n    // Create object containing the test functions.\n    std::shared_ptr< TestFunctionWithZeroRoot > testFunction =\n            std::make_shared< TestFunctionWithZeroRoot >( 2 );\n\n    // The termination condition.\n    HalleyRootFinder::TerminationFunction terminationConditionFunction\n            = std::bind( &RootAbsoluteToleranceTerminationCondition< double >::\n                           checkTerminationCondition,\n                           std::make_shared< RootAbsoluteToleranceTerminationCondition< double > >(\n                               1.0e-150 ), std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4, std::placeholders::_5 );\n\n    // Test Halley object.\n    HalleyRootFinder halleyRootFinder( terminationConditionFunction );\n\n    // Let the Halley method search for the root.\n    const double root = halleyRootFinder.execute( testFunction, testFunction->getInitialGuess( ) );\n\n    // Check if the result is within the requested accuracy.\n    BOOST_CHECK_SMALL( root, 1.0e-100 );\n    BOOST_CHECK_SMALL( testFunction->evaluate( root ), 1.0e-200 );\n}\n\nBOOST_AUTO_TEST_SUITE_END( ) // testsuite_rootfinders\n\n} // namespace unit_tests\n} // namespace tudat\n", "meta": {"hexsha": "4d34d2a43846fb95cf835f75faff7f1ee0307830", "size": 6763, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Mathematics/RootFinders/UnitTests/unitTestHalleyRootFinder.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/Mathematics/RootFinders/UnitTests/unitTestHalleyRootFinder.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/Mathematics/RootFinders/UnitTests/unitTestHalleyRootFinder.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": 48.3071428571, "max_line_length": 185, "alphanum_fraction": 0.733698063, "num_tokens": 1538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105941403651, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4670514684399991}}
{"text": "#pragma once\n\n#include <stdio.h>\n#include <Eigen/Dense>\n#include <dart/dart.hpp>\n#include <dart/utils/urdf/urdf.hpp>\n#include <dart/utils/utils.hpp>\n\n#include <Utils/IO/IOUtilities.hpp>\n\nclass RobotSystem {\n protected:\n  dart::dynamics::SkeletonPtr skel_ptr_;\n  int num_dof_;\n  int num_virtual_dof_;\n  int num_actuated_dof_;\n  Eigen::MatrixXd I_cent_;\n  Eigen::MatrixXd J_cent_;\n  Eigen::MatrixXd A_cent_;\n\n  /*\n   * Update I_cent_, A_cent_, J_cent_\n   * , where\n   * centroid_momentum = I_cent_ * centroid_velocity = A_cent_ * qdot\n   *           J_cent_ = inv(I_cent_) * A_cent_\n   * centroid_velocity = J_cent_ * qdot\n   */\n  void _updateCentroidFrame(const Eigen::VectorXd& q_,\n                            const Eigen::VectorXd& qdot_);\n\n public:\n  RobotSystem(int numVirtual_, std::string file);\n  virtual ~RobotSystem(void);\n\n  dart::dynamics::SkeletonPtr getSkeleton() { return skel_ptr_; };\n  dart::dynamics::BodyNodePtr getBodyNode(const std::string& _link_name) {\n    return skel_ptr_->getBodyNode(_link_name);\n  }\n  dart::dynamics::BodyNodePtr getBodyNode(const int& _bn_idx) {\n    return skel_ptr_->getBodyNode(_bn_idx);\n  }\n\n  Eigen::VectorXd getQ() { return skel_ptr_->getPositions(); };\n  Eigen::VectorXd getQdot() { return skel_ptr_->getVelocities(); };\n  void printRobotInfo();\n  double getRobotMass() { return skel_ptr_->getMass(); }\n  int getNumDofs() { return num_dof_; };\n  int getNumVirtualDofs() { return num_virtual_dof_; };\n  int getNumActuatedDofs() { return num_actuated_dof_; };\n\n  int getJointIdx(const std::string& jointName_);\n  int getDofIdx(const std::string& dofName_);\n\n  // Position Limits\n  Eigen::VectorXd getPositionLowerLimits() {\n    return skel_ptr_->getPositionLowerLimits();\n  }\n  Eigen::VectorXd getPositionUpperLimits() {\n    return skel_ptr_->getPositionUpperLimits();\n  }\n  // Velocity Limits\n  Eigen::VectorXd getVelocityLowerLimits() {\n    return skel_ptr_->getVelocityLowerLimits();\n  }\n  Eigen::VectorXd getVelocityUpperLimits() {\n    return skel_ptr_->getVelocityUpperLimits();\n  }\n  // Force Torque Limits\n  Eigen::VectorXd GetTorqueLowerLimits() {\n    return skel_ptr_->getForceLowerLimits();\n  }\n  Eigen::VectorXd GetTorqueUpperLimits() {\n    return skel_ptr_->getForceUpperLimits();\n  }\n\n  Eigen::MatrixXd getMassMatrix();\n  Eigen::MatrixXd getInvMassMatrix();\n  Eigen::VectorXd getGravity();\n  Eigen::VectorXd getCoriolis();\n  Eigen::VectorXd getCoriolisGravity();\n\n  Eigen::MatrixXd getCentroidJacobian();\n  Eigen::MatrixXd getCentroidInertiaTimesJacobian();\n  Eigen::MatrixXd getCentroidInertia();\n  Eigen::VectorXd getCentroidVelocity();\n  Eigen::VectorXd getCentroidMomentum();\n  Eigen::Vector3d getCoMPosition(\n      dart::dynamics::Frame* wrt_ = dart::dynamics::Frame::World());\n  Eigen::Vector3d getCoMVelocity(\n      dart::dynamics::Frame* rl_ = dart::dynamics::Frame::World(),\n      dart::dynamics::Frame* wrt_ = dart::dynamics::Frame::World());\n  Eigen::MatrixXd getCoMJacobian(\n      dart::dynamics::Frame* wrt_ = dart::dynamics::Frame::World());\n  Eigen::MatrixXd getCoMJacobianDot();\n  void updateSystem(const Eigen::VectorXd& q_, const Eigen::VectorXd& qdot_,\n                    bool isUpdatingCentroid_ = true);\n  void updateCentroidFrame();\n\n  Eigen::Isometry3d getBodyNodeIsometry(\n      const std::string& name_,\n      dart::dynamics::Frame* wrt_ = dart::dynamics::Frame::World());\n  Eigen::Isometry3d getBodyNodeCoMIsometry(\n      const std::string& name_,\n      dart::dynamics::Frame* wrt_ = dart::dynamics::Frame::World());\n  Eigen::Vector6d getBodyNodeSpatialVelocity(\n      const std::string& name_,\n      dart::dynamics::Frame* rl_ = dart::dynamics::Frame::World(),\n      dart::dynamics::Frame* wrt_ = dart::dynamics::Frame::World());\n  Eigen::Vector6d getBodyNodeCoMSpatialVelocity(\n      const std::string& name_,\n      dart::dynamics::Frame* rl_ = dart::dynamics::Frame::World(),\n      dart::dynamics::Frame* wrt_ = dart::dynamics::Frame::World());\n  Eigen::MatrixXd getBodyNodeJacobian(\n      const std::string& name_,\n      Eigen::Vector3d localOffset_ = Eigen::Vector3d::Zero(3),\n      dart::dynamics::Frame* wrt_ = dart::dynamics::Frame::World());\n  Eigen::MatrixXd getBodyNodeJacobianDot(\n      const std::string& name_,\n      Eigen::Vector3d localOffset_ = Eigen::Vector3d::Zero(3),\n      dart::dynamics::Frame* wrt_ = dart::dynamics::Frame::World());\n  Eigen::MatrixXd getBodyNodeCoMJacobian(\n      const std::string& name_,\n      dart::dynamics::Frame* wrt_ = dart::dynamics::Frame::World());\n  Eigen::MatrixXd getBodyNodeCoMJacobianDot(\n      const std::string& name_,\n      dart::dynamics::Frame* wrt_ = dart::dynamics::Frame::World());\n\n  Eigen::Isometry3d getBodyNodeIsometry(\n      const int& _bn_idx,\n      dart::dynamics::Frame* wrt_ = dart::dynamics::Frame::World());\n  Eigen::Isometry3d getBodyNodeCoMIsometry(\n      const int& _bn_idx,\n      dart::dynamics::Frame* wrt_ = dart::dynamics::Frame::World());\n  Eigen::Vector6d getBodyNodeSpatialVelocity(\n      const int& _bn_idx,\n      dart::dynamics::Frame* rl_ = dart::dynamics::Frame::World(),\n      dart::dynamics::Frame* wrt_ = dart::dynamics::Frame::World());\n  Eigen::Vector6d getBodyNodeCoMSpatialVelocity(\n      const int& _bn_idx,\n      dart::dynamics::Frame* rl_ = dart::dynamics::Frame::World(),\n      dart::dynamics::Frame* wrt_ = dart::dynamics::Frame::World());\n  Eigen::MatrixXd getBodyNodeJacobian(\n      const int& _bn_idx,\n      Eigen::Vector3d localOffset_ = Eigen::Vector3d::Zero(3),\n      dart::dynamics::Frame* wrt_ = dart::dynamics::Frame::World());\n  Eigen::MatrixXd getBodyNodeJacobianDot(\n      const int& _bn_idx,\n      Eigen::Vector3d localOffset_ = Eigen::Vector3d::Zero(3),\n      dart::dynamics::Frame* wrt_ = dart::dynamics::Frame::World());\n  Eigen::MatrixXd getBodyNodeCoMJacobian(\n      const int& _bn_idx,\n      dart::dynamics::Frame* wrt_ = dart::dynamics::Frame::World());\n  Eigen::MatrixXd getBodyNodeCoMJacobianDot(\n      const int& _bn_idx,\n      dart::dynamics::Frame* wrt_ = dart::dynamics::Frame::World());\n};\n", "meta": {"hexsha": "ef868fa77981f37b220dcf1d98b7b418a5df15d1", "size": 6005, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "PnC/RobotSystem/RobotSystem.hpp", "max_stars_repo_name": "BharathMasetty/PnC", "max_stars_repo_head_hexsha": "3800bd7e3c5dd5ffa00e6a5f09d48d21c405206f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PnC/RobotSystem/RobotSystem.hpp", "max_issues_repo_name": "BharathMasetty/PnC", "max_issues_repo_head_hexsha": "3800bd7e3c5dd5ffa00e6a5f09d48d21c405206f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PnC/RobotSystem/RobotSystem.hpp", "max_forks_repo_name": "BharathMasetty/PnC", "max_forks_repo_head_hexsha": "3800bd7e3c5dd5ffa00e6a5f09d48d21c405206f", "max_forks_repo_licenses": ["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.2484076433, "max_line_length": 76, "alphanum_fraction": 0.6959200666, "num_tokens": 1672, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.46702001054299636}}
{"text": "#include <boost/math/tools/polynomial_gcd.hpp>\n", "meta": {"hexsha": "99752e42c7d604d633fc229f0237347974c4984e", "size": 47, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_tools_polynomial_gcd.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_tools_polynomial_gcd.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_tools_polynomial_gcd.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 23.5, "max_line_length": 46, "alphanum_fraction": 0.8085106383, "num_tokens": 11, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.46702000492521023}}
{"text": "//  Copyright Nick Thompson 2018.\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#include <boost/math/concepts/std_real_concept.hpp>\n#include <boost/math/interpolators/catmull_rom.hpp>\n\nvoid compile_and_link_test()\n{\n    std::vector<boost::math::concepts::std_real_concept> p0{0.1, 0.2, 0.3};\n    std::vector<boost::math::concepts::std_real_concept> p1{0.2, 0.3, 0.4};\n    std::vector<boost::math::concepts::std_real_concept> p2{0.3, 0.4, 0.5};\n    std::vector<boost::math::concepts::std_real_concept> p3{0.4, 0.5, 0.6};\n    std::vector<boost::math::concepts::std_real_concept> p4{0.5, 0.6, 0.7};\n    std::vector<boost::math::concepts::std_real_concept> p5{0.6, 0.7, 0.8};\n    std::vector<std::vector<boost::math::concepts::std_real_concept>> v{p0, p1, p2, p3, p4, p5};\n    boost::math::catmull_rom<std::vector<boost::math::concepts::std_real_concept>> cat(v.data(), v.size());\n    cat(0.0);\n    cat.prime(0.0);\n}\n", "meta": {"hexsha": "a9bd2840514f899c6037828e060d2bea6d2136bc", "size": 1061, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/test/compile_test/catmull_rom_concept_test.cpp", "max_stars_repo_name": "ztchu/boost_1_70_0", "max_stars_repo_head_hexsha": "f86bf1a4ad9efe7b2d76e4878ea240ac35ca4250", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 44.0, "max_stars_repo_stars_event_min_datetime": "2020-12-21T05:14:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T11:27:32.000Z", "max_issues_repo_path": "libs/math/test/compile_test/catmull_rom_concept_test.cpp", "max_issues_repo_name": "ztchu/boost_1_70_0", "max_issues_repo_head_hexsha": "f86bf1a4ad9efe7b2d76e4878ea240ac35ca4250", "max_issues_repo_licenses": ["BSL-1.0"], "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": "libs/math/test/compile_test/catmull_rom_concept_test.cpp", "max_forks_repo_name": "ztchu/boost_1_70_0", "max_forks_repo_head_hexsha": "f86bf1a4ad9efe7b2d76e4878ea240ac35ca4250", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 21.0, "max_forks_repo_forks_event_min_datetime": "2020-12-22T09:40:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-07T18:16:00.000Z", "avg_line_length": 48.2272727273, "max_line_length": 107, "alphanum_fraction": 0.6918001885, "num_tokens": 380, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.46702000492521023}}
{"text": "#include <CGAL/algorithm.h>\n#include <CGAL/function_objects.h>\n#include <vector>\n#include <iostream>\n#include <boost/functional.hpp>\n\n\nint main()\n{\n  std::vector< int > v;\n  v.push_back(3);\n  v.push_back(5);\n  v.push_back(2);\n  std::cout << \"min_odd = \"\n            << *CGAL::min_element_if(v.begin(),\n                                     v.end(),\n                                     CGAL::compose1_1(boost::bind2nd(std::greater< int >(), 0),\n                                                      boost::bind2nd(std::modulus< int >(), 2)))\n            << std::endl;\n  return 0;\n}\n", "meta": {"hexsha": "a2a9801553362a8bbc8cfdc5e5ab20ee50317d34", "size": 581, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "STL_Extension/examples/STL_Extension/min_element_if_example.cpp", "max_stars_repo_name": "gaschler/cgal", "max_stars_repo_head_hexsha": "d1fe2afa18da5524db6d4946f42ca4b8d00e0bda", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 187.0, "max_stars_repo_stars_event_min_datetime": "2019-01-23T04:07:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T03:44:58.000Z", "max_issues_repo_path": "STL_Extension/examples/STL_Extension/min_element_if_example.cpp", "max_issues_repo_name": "gaschler/cgal", "max_issues_repo_head_hexsha": "d1fe2afa18da5524db6d4946f42ca4b8d00e0bda", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-03-22T13:27:38.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-18T13:23:23.000Z", "max_forks_repo_path": "STL_Extension/examples/STL_Extension/min_element_if_example.cpp", "max_forks_repo_name": "gaschler/cgal", "max_forks_repo_head_hexsha": "d1fe2afa18da5524db6d4946f42ca4b8d00e0bda", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 34.0, "max_forks_repo_forks_event_min_datetime": "2019-02-13T01:11:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T03:29:40.000Z", "avg_line_length": 26.4090909091, "max_line_length": 96, "alphanum_fraction": 0.4767641997, "num_tokens": 143, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.46702000492521023}}
{"text": "/***************************************************************************\n *   Software License Agreement (BSD License)                              *\n *   Copyright (C) 2015 by Horatiu George Todoran <todorangrg@gmail.com>   *\n *                                                                         *\n *   Redistribution and use in source and binary forms, with or without    *\n *   modification, are permitted provided that the following conditions    *\n *   are met:                                                              *\n *                                                                         *\n *   1. Redistributions of source code must retain the above copyright     *\n *      notice, this list of conditions and the following disclaimer.      *\n *   2. Redistributions in binary form must reproduce the above copyright  *\n *      notice, this list of conditions and the following disclaimer in    *\n *      the documentation and/or other materials provided with the         *\n *      distribution.                                                      *\n *   3. Neither the name of the copyright holder nor the names of its      *\n *      contributors may be used to endorse or promote products derived    *\n *      from this software without specific prior written permission.      *\n *                                                                         *\n *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS   *\n *   \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT     *\n *   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS     *\n *   FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE        *\n *   COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 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 ANY *\n *   WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE           *\n *   POSSIBILITY OF SUCH DAMAGE.                                           *\n ***************************************************************************/\n\n\n#include \"utils/base_classes.h\"\n#include \"utils/math.h\"\n#include <boost/random.hpp>\n#include <boost/random/uniform_01.hpp>\n\n\nusing namespace cv;\n\nboost::minstd_rand gIntGenStd;\nboost::mt19937 gIntGen19937;\nboost::variate_generator<boost::mt19937, boost::normal_distribution<> > gNormal(gIntGen19937, boost::normal_distribution<>(0,1));\nboost::uniform_01<boost::minstd_rand> gUniform(gIntGenStd);\n\ndouble  Distributions::normalDist() {\n    return gNormal();\n}\ndouble  Distributions::normalDist(double sigma) {\n    return sigma * gNormal();\n}\ndouble  Distributions::normalDist(double mean, double sigma) {\n    return mean + sigma * gNormal();\n}\nvoid Distributions::normalDist(cv::Vec<double,3> &mean, cv::Vec<double,3> sigma) {\n    mean[0] = normalDist(mean[0], sigma[0]);\n    mean[1] = normalDist(mean[1], sigma[1]);\n    mean[2] = normalDist(mean[2], sigma[2]);\n}\ndouble Distributions::uniformDist(double min, double max){\n    double s = max - min;\n    return min + s * gUniform();\n}\nvoid Distributions::uniformDist(double min, double max, cv::Vec<double,3> &des){\n    des[0] = uniformDist(min, max);\n    des[1] = uniformDist(min, max);\n    des[2] = uniformDist(min, max);\n}\n\n\nvoid Gauss::add_w_sample(double val, double w){\n    entry_no++;\n    double temp  = w + sumweight;\n    double delta = val - mean;\n    double r = delta * w /temp;\n    mean += r;\n    m2 += sumweight * delta * r;\n    sumweight = temp;\n}\n\ndouble Gauss::getMean(){\n    return mean;\n}\ndouble Gauss::getVariance(){\n    if(entry_no<=1){\n        //std::cout<<\"WARNING: requesting variance of less than 2 entries\"<<std::endl;\n        return 0;\n    }\n    return (m2/sumweight)* (double)entry_no/((double)entry_no - 1.0);\n}\ndouble Gauss::getSampleVariance(){\n    return m2/sumweight;\n}\n\nvoid NormalFunc::set(double _mean, double _deviation, double _no_sigma_dev){\n    mean = _mean;\n    sigma = _deviation / _no_sigma_dev;\n}\n\ndouble NormalFunc::f(double x){\n    return std::exp( - sqr( x - mean ) / ( 2.0 * sqr( sigma ) ) );\n}\n\n///------------------------------------------------------------------------------------------------------------------------------------------------///\n\nLine get_line_param(xy p1,xy p2){\n    double a=p2.y-p1.y;\n    double b=p1.x-p2.x;\n    double c=-(a*p2.x+b*p2.y);\n\n    return Line(a,b,c);\n}\nxy get_line_inters(Line l,xy p){\n    return xy( (l.b*(l.b*p.x-l.a*p.y)-l.a*l.c)/(sqr(l.a)+sqr(l.b)), (l.a*(-l.b*p.x+l.a*p.y)-l.b*l.c)/(sqr(l.a)+sqr(l.b)));\n}\n\ndouble get_dist_p(Line l,xy p0, xy* p_d){\n    *p_d = xy((l.b * (   l.b * p0.x - l.a * p0.y) - l.a * l.c) / (sqr(l.a) + sqr(l.b)),\n              (l.a * ( - l.b * p0.x + l.a * p0.y) - l.b * l.c) / (sqr(l.a) + sqr(l.b)));\n    return fabs(l.a * p0.x + l.b * p0.y + l.c) / sqrt(sqr(l.a) + sqr(l.b));\n}\n\nxy get_line_inters(Line l1,Line l2){\n    double x=10000,y=10000;\n    if(l1.a*l2.b!=l1.b*l2.a){\n        x=(l2.b*l1.c-l2.c*l1.b)/(l2.a*l1.b-l1.a*l2.b);\n        y=(l2.c*l1.a-l1.c*l2.a)/(l2.a*l1.b-l1.a*l2.b);\n        return xy(x,y);\n    }\n    else if((l1.a==l2.a)&&(l1.b==l2.b)&&(l1.c==l2.c)){\n        std::cout<<\"paralel overlapping lines when computing get_line_intersection\"<<std::endl;\n    }\n    else{\n        std::cout<<\"paralel NONoverlapping lines when computing get_line_intersection\"<<std::endl;\n    }\n    return xy(0,0);\n}\n\n///------------------------------------------------------------------------------------------------------------------------------------------------///\n\n\npolar::polar() {\n    r=0;angle=0;\n}\npolar::polar(double _r, double _angle) {\n    r=_r;angle=_angle;\n}\npolar::polar(const polar &_p){\n    r=_p.r;angle=_p.angle;\n}\npolar::polar(PointData &_p){\n    r=_p.r;angle=_p.angle;\n}\n\n\n\npolar polar_diff(polar p1,polar p2){\n    return polar(sqrt(sqr(p2.r*cos(p2.angle)-p1.r*cos(p1.angle))+sqr(p2.r*sin(p2.angle)-p1.r*sin(p1.angle))),\n                 atan2(p2.r*sin(p2.angle)-p1.r*sin(p1.angle),p2.r*cos(p2.angle)-p1.r*cos(p1.angle)));\n}\n\npolar polar_diff(polar p1,PointData &p2){\n    return polar_diff(p1,polar(p2.r,p2.angle));\n}\npolar polar_diff(PointData &p1,polar p2){\n    return polar_diff(polar(p1.r,p1.angle),p2);\n}\n\npolar polar_diff(PointData p1,PointData &p2){\n    return polar_diff(polar(p1.r,p1.angle),polar(p2.r,p2.angle));\n}\n\npolar radial_diff(polar p1,polar p2){\n    double d_angle=fabs(p1.angle-p2.angle);\n    normalizeAngle(d_angle);\n    return polar(d_angle*p1.r,d_angle);\n}\npolar radial_diff(polar p1,PointData &p2){\n    return radial_diff(p1,polar(p2.r,p2.angle));\n}\n\nxy to_xy(polar p){\n    return xy(p.r*cos(p.angle),p.r*sin(p.angle));\n}\nxy to_xy(PointData &p){\n    return to_xy(polar(p.r,p.angle));\n}\n\npolar to_polar(xy c){\n    return polar(sqrt(c.x*c.x+c.y*c.y),atan2(c.y,c.x));\n}\n\n///------------------------------------------------------------------------------------------------------------------------------------------------///\n\ndouble normalizeAngle(double &angle) {\n    while(angle > M_PI){\n      angle = angle - (2*M_PI);\n    }\n    while(angle <= -M_PI){\n      angle = angle + (2*M_PI);\n    }\n    return angle;\n}\n\ndouble deg_to_rad(double angle_deg){\n    return (angle_deg*M_PI)/180.0;\n}\n\ndouble rad_to_deg(double angle_rad){\n    return (angle_rad*180.0)/(double)M_PI;\n}\n\ndouble sqr(double x){\n    return x*x;\n}\n\ndouble sgn(double x){\n    if(x>=0){\n        return 1;\n    }\n    else{\n        return -1;\n    }\n}\n\nvoid angular_bounds(polar p, double circle_rad, double* search_angle){\n    search_angle[0] = p.angle;\n    search_angle[1] = search_angle[0];\n    if( fabs( circle_rad / p.r ) > 1.0  ){\n        search_angle[0] -= 2 * M_PI;\n        search_angle[1] += 2 * M_PI;\n    }\n    else{\n        search_angle[0] -= asin( circle_rad / p.r );\n        search_angle[1] += asin( circle_rad / p.r );\n    }\n}\nvoid angular_bounds(PointData &p,double circle_rad, double* search_angle){\n    return angular_bounds(polar(p.r,p.angle),circle_rad,search_angle);\n}\n\nvoid angular_bounds(PointDataCpy &p,double circle_rad, double* search_angle){\n    return angular_bounds(polar(p.r,p.angle),circle_rad,search_angle);\n}\n\n///------------------------------------------------------------------------------------------------------------------------------------------------///\n\n\nvoid set_tf_mat(cv::Matx<double,3,3>& tf, xy trans, double rot){\n    cv::Matx<double,3,3> R ( cos(rot), -sin(rot),   0,\n                             sin(rot),  cos(rot),   0,\n                                      0,           0,   1);    // Rotate\n    cv::Matx<double,3,3> T (          1,           0, trans.x,\n                                      0,           1, trans.y,\n                                      0,           0,   1);    // Translate\n    // Calculate final transformation matrix\n    tf = T * R;\n    //Mptf = Mptf.inv();\n    //std::cout <<  \"Ms2r = \" << std::endl << Ms2r << std::endl;\n    //std::cout <<  \"Mr2s = \" << std::endl << Mr2s << std::endl;\n}\n\nxy   mat_mult(cv::Matx<double,3,3>& tf,xy p){\n    cv::Matx<double,3,1> pw (p.x, p.y, 1.0);\n    cv::Matx<double,3,1> pi = tf * pw;\n    return  xy (pi(0,0), pi(1,0));\n}\n\ncv::RotatedRect cov2rect(cv::Matx<double, 2, 2> _C,xy _center){\n    cv::RotatedRect ellipse;\n    cv::Mat_<double> eigval, eigvec;\n    cv::eigen(_C, eigval, eigvec);\n\n    /// Exercise4\n    bool index_x;\n    ellipse.center = _center;\n    if(_C(0,0)>_C(1,1)){\n        index_x=0;\n    }\n    else{\n        index_x=1;\n    }\n    ellipse.size.height=sqrt(fabs(eigval(0,!index_x)))*2.4477;//y\n    ellipse.size.width=sqrt(fabs(eigval(0,index_x)))*2.4477;//x\n    if((eigval(0,index_x)!=0)&&(eigval(0,!index_x)!=0))\n        ellipse.angle=atan2(eigvec(index_x,1),eigvec(index_x,0))*(180/M_PI);\n\n    return ellipse;\n}\n", "meta": {"hexsha": "9d62c3c92427969894a5ed6bb3087ef2556a792d", "size": 9971, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/utils/math.cpp", "max_stars_repo_name": "todorangrg/objectify", "max_stars_repo_head_hexsha": "6575698fbb5200fa85a8c8f7f6bef270f9f08847", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_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/math.cpp", "max_issues_repo_name": "todorangrg/objectify", "max_issues_repo_head_hexsha": "6575698fbb5200fa85a8c8f7f6bef270f9f08847", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/math.cpp", "max_forks_repo_name": "todorangrg/objectify", "max_forks_repo_head_hexsha": "6575698fbb5200fa85a8c8f7f6bef270f9f08847", "max_forks_repo_licenses": ["BSD-3-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.264604811, "max_line_length": 150, "alphanum_fraction": 0.5447798616, "num_tokens": 2686, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867681382279, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.467019999307424}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_EULER_FUNCTIONS_SIMD_COMMON_STIRLING_HPP_INCLUDED\n#define NT2_EULER_FUNCTIONS_SIMD_COMMON_STIRLING_HPP_INCLUDED\n\n#include <nt2/euler/functions/stirling.hpp>\n#include <nt2/euler/functions/details/stirling_kernel.hpp>\n#include <nt2/include/constants/half.hpp>\n#include <nt2/include/constants/one.hpp>\n#include <nt2/include/constants/sqrt_2pi.hpp>\n#include <nt2/include/constants/stirlingsplitlim.hpp>\n#include <nt2/include/functions/simd/exp.hpp>\n#include <nt2/include/functions/simd/fma.hpp>\n#include <nt2/include/functions/simd/if_else.hpp>\n#include <nt2/include/functions/simd/is_less.hpp>\n#include <nt2/include/functions/simd/minus.hpp>\n#include <nt2/include/functions/simd/multiplies.hpp>\n#include <nt2/include/functions/simd/pow.hpp>\n#include <nt2/include/functions/simd/rec.hpp>\n#include <nt2/include/functions/simd/unary_minus.hpp>\n#include <nt2/sdk/meta/as_logical.hpp>\n\n#include <boost/simd/sdk/config.hpp>\n\n#ifndef BOOST_SIMD_NO_INFINITIES\n#include <nt2/include/constants/inf.hpp>\n#include <nt2/include/functions/simd/is_equal.hpp>\n#endif\n\nnamespace nt2 { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT  ( stirling_, tag::cpu_\n                            , (A0)(X)\n                            , ((simd_<floating_<A0>,X>))\n                            )\n  {\n    typedef A0 result_type;\n    NT2_FUNCTOR_CALL(1)\n    {\n      typedef typename meta::as_logical<A0>::type bA0;\n      A0 w = nt2::rec(a0);\n      w = fma(w,details::stirling_kernel<A0>::stirling1(w), nt2::One<A0>());\n      A0 y = nt2::exp(-a0);\n      bA0 test = is_less(a0, nt2::Stirlingsplitlim<A0>());\n      A0 z =  a0 - nt2::Half<A0>();\n      z =  if_else(test, z, Half<A0>()*z);\n      A0 v =  nt2::pow(a0,z);\n      y *= v;\n      y = if_else(test,y, y*v); /* Avoid overflow in pow() */\n      y *= nt2::Sqrt_2pi<A0>()*w;\n      #ifndef BOOST_SIMD_NO_INFINITIES\n      y = if_else(eq(a0, Inf<A0>()), a0, y);\n      #endif\n      return y;\n    }\n  };\n} }\n\n#endif\n", "meta": {"hexsha": "37d53a9d2117650be5d67b5a5269ce1494e754ef", "size": 2436, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/euler/include/nt2/euler/functions/simd/common/stirling.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/core/euler/include/nt2/euler/functions/simd/common/stirling.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/core/euler/include/nt2/euler/functions/simd/common/stirling.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.9090909091, "max_line_length": 80, "alphanum_fraction": 0.6153530378, "num_tokens": 645, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867681382279, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.467019999307424}}
{"text": "#ifndef TEST_UNIT_TORSTEN_PK_CPT_MODEL_TEST_FIXTURE\n#define TEST_UNIT_TORSTEN_PK_CPT_MODEL_TEST_FIXTURE\n\n#include <stan/math/rev/mat.hpp>\n#include <gtest/gtest.h>\n#include <boost/numeric/odeint.hpp>\n#include <stan/math/torsten/pmx_onecpt_model.hpp>\n#include <stan/math/torsten/pmx_twocpt_model.hpp>\n#include <stan/math/torsten/pmx_linode_model.hpp>\n#include <stan/math/torsten/pmx_ode_model.hpp>\n#include <test/unit/math/torsten/pmx_ode_test_fixture.hpp>\n#include <iostream>\n#include <sstream>\n#include <vector>\n#include <string>\n\nstruct CoupledOneCptODE {\n  /*\n   * Coupled model functor\n   */\n  template <typename T0, typename T1, typename T2, typename T3>\n  inline\n  std::vector<typename boost::math::tools::promote_args<T0, T1, T2, T3>::type>\n  operator()(const T0& t,\n             const std::vector<T1>& x,\n             const std::vector<T2>& x_pk,\n             const std::vector<T3>& theta,\n             const std::vector<double>& x_r,\n             const std::vector<int>& x_i,\n             std::ostream* pstream_) const {\n    typedef typename boost::math::tools::promote_args<T0, T1, T2, T3>::type\n      scalar;\n\n    scalar\n      VC = theta[1],\n      Mtt = theta[3],\n      circ0 = theta[4],\n      alpha = theta[5],\n      gamma = theta[6],\n      ktr = 4 / Mtt,\n      prol = x[0] + circ0,\n      transit = x[1] + circ0,\n      circ = x[2] + circ0,\n      conc = x_pk[1] / VC,\n      Edrug = alpha * conc;\n\n    std::vector<scalar> dxdt(3);\n    dxdt[0] = ktr * prol * ((1 - Edrug) * pow(circ0 / circ, gamma) - 1);\n    dxdt[1] = ktr * (prol - transit);\n    dxdt[2] = ktr * (transit - circ);\n\n    return dxdt;\n  }\n\n  /*\n   * full ODE model functor\n   */\n  template <typename T0, typename T1, typename T2>\n  inline\n  std::vector<typename boost::math::tools::promote_args<T0, T1, T2>::type>\n  operator()(const T0& t,\n             const std::vector<T1>& x,\n             const std::vector<T2>& theta,\n             const std::vector<double>& x_r,\n             const std::vector<int>& x_i,\n             std::ostream* pstream_) const {\n    typedef typename boost::math::tools::promote_args<T0, T1, T2>::type\n      scalar;\n    \n    scalar\n      CL = theta[0],\n      VC = theta[1],\n      ka = theta[2],\n      Mtt = theta[3],\n      circ0 = theta[4],\n      alpha = theta[5],\n      gamma = theta[6],\n      ktr = 4 / Mtt,\n      prol = x[2] + circ0,\n      transit = x[3] + circ0,\n      circ = x[4] + circ0,\n      Edrug;\n\n    std::vector<scalar> dxdt(5);\n    dxdt[0] = - ka * x[0];\n    dxdt[1] = ka * x[0] - CL / VC * x[1];\n    \n    Edrug = alpha * x[1] / VC;\n    \n    dxdt[2] = ktr * prol * ((1 - Edrug) * pow(circ0 / circ, gamma) - 1);\n    dxdt[3] = ktr * (prol - transit);\n    dxdt[4] = ktr * (transit - circ);\n    \n    return dxdt;\n  }\n};\n\nstruct CoupledTwoCptODE {\n  /*\n   * Coupled model functor\n   */\n  template <typename T0, typename T1, typename T2, typename T3>\n  inline\n  std::vector<typename boost::math::tools::promote_args<T0, T1, T2, T3>::type>\n  operator()(const T0& t,\n             const std::vector<T1>& y,\n             const std::vector<T2>& y_pk,\n             const std::vector<T3>& theta,\n             const std::vector<double>& x_r,\n             const std::vector<int>& x_i,\n             std::ostream* pstream_) const {\n    typedef typename boost::math::tools::promote_args<T0, T1, T2, T3>::type\n      scalar;\n\n    scalar VC = theta[2],\n      Mtt = theta[5],\n      circ0 = theta[6],\n      alpha = theta[7],\n      gamma = theta[8],\n      ktr = 4 / Mtt,\n      prol = y[0] + circ0,\n      transit = y[1] + circ0,\n      circ = y[2] + circ0,\n      conc = y_pk[1] / VC,\n      Edrug = alpha * conc;\n\n    std::vector<scalar> dxdt(3);\n    dxdt[0] = ktr * prol * ((1 - Edrug) * pow(circ0 / circ, gamma) - 1);\n    dxdt[1] = ktr * (prol - transit);\n    dxdt[2] = ktr * (transit - circ);\n\n    return dxdt;\n  }\n\n  /*\n   * full ODE model functor\n   */\n  template <typename T0, typename T1, typename T2>\n  inline\n    std::vector<typename boost::math::tools::promote_args<T0, T1, T2>::type>\n  operator()(const T0& t,\n           const std::vector<T1>& x,\n           const std::vector<T2>& theta,\n           const std::vector<double>& x_r,\n           const std::vector<int>& x_i,\n           std::ostream* pstream_) const {\n    typedef typename boost::math::tools::promote_args<T0, T1, T2>::type\n    scalar;\n\n    scalar\n      CL = theta[0],\n      Q = theta[1],\n      VC = theta[2],\n      VP = theta[3],\n      ka = theta[4],\n      k10 = CL / VC,\n      k12 = Q / VC,\n      k21 = Q / VP,\n      Mtt = theta[5],\n      circ0 = theta[6],\n      alpha = theta[7],\n      gamma = theta[8],\n      ktr = 4 / Mtt,\n      prol = x[3] + circ0,\n      transit = x[4] + circ0,\n      circ = x[5] + circ0,\n      Edrug;\n\n    std::vector<scalar> dxdt(6);\n    dxdt[0] = -ka * x[0];\n    dxdt[1] = ka * x[0] - (k10 + k12) * x[1] + k21 * x[2];\n    dxdt[2] = k12 * x[1] - k21 * x[2];\n    Edrug = alpha * x[1] / VC;\n    dxdt[3] = ktr * prol * ((1 - Edrug) * pow(circ0 / circ, gamma) - 1);\n    dxdt[4] = ktr * (prol - transit);\n    dxdt[5] = ktr * (transit - circ);\n\n    return dxdt;\n  }\n};\n\nstruct TorstenCoupledOneCptTest : public testing::Test {\n  // for events generation\n  const int nt;\n  const int nOde;\n  const int nPD;\n  std::vector<double> time;\n  std::vector<double> amt;\n  std::vector<double> rate;\n  std::vector<int> cmt;\n  std::vector<int> evid;\n  std::vector<double> ii;\n  std::vector<int> addl;\n  std::vector<int> ss;\n  std::vector<std::vector<double> > parameters;\n  std::vector<std::vector<double> > biovar;\n  std::vector<std::vector<double> > tlag;\n\n  // for ODE integrator\n  double t0;\n  std::vector<double> x_r;\n  std::vector<int> x_i;\n  double rtol;\n  double atol;\n  int max_num_steps;\n  std::ostream* msgs;\n\n  void SetUp() {\n    // make sure memory's clean before starting each test\n    stan::math::recover_memory();\n  }\n  TorstenCoupledOneCptTest() :\n    nt(10),\n    nOde(5),\n    nPD(3),\n    time(nt),\n    amt(nt, 0),\n    rate(nt, 0),\n    cmt(nt, 2),\n    evid(nt, 0),\n    ii(nt, 0),\n    addl(nt, 0),\n    ss(nt, 0),\n    // params: // CL // VC // ka // Mtt // Circ0 // alpha // gamma\n    parameters{ {10, 35, 2.0, 125, 5, 3e-4, 0.17} },\n    biovar{ { 1, 1, 1, 1, 1 } },\n    tlag{ { 0, 0, 0, 0, 0 } },\n    t0(0.0),\n    rtol             {1.E-10},\n    atol             {1.E-10},\n    max_num_steps    {100000},\n    msgs             {nullptr} {\n      for (int i = 0; i < nt; ++i) {\n        time[i] = i * 0.25;\n      }\n      time.back() = 4.0;\n      amt[0]  = 10000;\n      cmt[0]  = 1;\n      evid[0] = 1;\n      SetUp();\n  }\n};\n\nstruct TorstenCoupledTwoCptTest : public testing::Test {\n  // for events generation\n  const int nt;\n  const int nOde;\n  const int nPD;\n  std::vector<double> time;\n  std::vector<double> amt;\n  std::vector<double> rate;\n  std::vector<int> cmt;\n  std::vector<int> evid;\n  std::vector<double> ii;\n  std::vector<int> addl;\n  std::vector<int> ss;\n  std::vector<std::vector<double> > parameters;\n  std::vector<std::vector<double> > biovar;\n  std::vector<std::vector<double> > tlag;\n\n  // for ODE integrator\n  double t0;\n  std::vector<double> x_r;\n  std::vector<int> x_i;\n  double rtol;\n  double atol;\n  int max_num_steps;\n  std::ostream* msgs;\n\n  void SetUp() {\n    // make sure memory's clean before starting each test\n    stan::math::recover_memory();\n  }\n  TorstenCoupledTwoCptTest() :\n    nt(10),\n    nOde(6),\n    nPD(3),\n    time(nt),\n    amt(nt, 0),\n    rate(nt, 0),\n    cmt(nt, 2),\n    evid(nt, 0),\n    ii(nt, 0),\n    addl(nt, 0),\n    ss(nt, 0),\n    // CL // Q // VC // VP // ka // Mtt // Circ0 // alpha // gamma\n    parameters{ {10, 15, 35, 105, 2.0, 125, 5, 3e-4, 0.17} },\n    biovar{ { 1, 1, 1, 1, 1, 1 } },\n    tlag{ { 0, 0, 0, 0, 0, 0 } },\n    t0(0.0),\n    rtol             {1.E-10},\n    atol             {1.E-10},\n    max_num_steps    {100000},\n    msgs             {nullptr} {\n      for (int i = 0; i < nt; ++i) {\n        time[i] = i * 0.25;\n      }\n      time.back() = 4.0;\n      amt[0]  = 10000;\n      cmt[0]  = 1;\n      evid[0] = 1;\n      SetUp();\n  }\n};\n\n#endif\n", "meta": {"hexsha": "286c7c38c2618123c4bd5f1ab9c1be0dcc79034e", "size": 7968, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/torsten/pmx_coupled_model_fixture.hpp", "max_stars_repo_name": "csetraynor/Torsten", "max_stars_repo_head_hexsha": "55b59b8068e2a539346f566ec698c755a9e3536c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/torsten/pmx_coupled_model_fixture.hpp", "max_issues_repo_name": "csetraynor/Torsten", "max_issues_repo_head_hexsha": "55b59b8068e2a539346f566ec698c755a9e3536c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/torsten/pmx_coupled_model_fixture.hpp", "max_forks_repo_name": "csetraynor/Torsten", "max_forks_repo_head_hexsha": "55b59b8068e2a539346f566ec698c755a9e3536c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9543973941, "max_line_length": 78, "alphanum_fraction": 0.5406626506, "num_tokens": 2733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867681382279, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.467019999307424}}
{"text": "#include <iostream>\r\n#include <fstream>\r\n#include <sstream>\r\n#include <vector>\r\n#include <array>\r\n#include <unordered_set>\r\n#include <unordered_map>\r\n#include <boost/format.hpp>\r\n#include \"decision_tree.h\"\r\n#include \"utils.h\"\r\n\r\nusing namespace std;\r\nusing namespace Eigen;\r\n\r\nDecisionTree::DecisionTree(int min_samples_split, double min_impurity, int max_depth) : min_samples_split(min_samples_split), min_impurity(min_impurity), max_depth(max_depth) {}\r\n\r\nDecisionTree::~DecisionTree() {}\r\n\r\n\r\nvoid DecisionTree::fit(const MatrixXd& X, const VectorXd& y){\r\n\troot = build_tree(X, y, 0);\r\n}\r\n\r\nDecisionNode* DecisionTree::build_tree(const MatrixXd& X, const VectorXd& y, int current_depth){\r\n\tdouble largest_impurity = 0.0;\r\n\t//cout << \"start...\" << endl;\r\n\tMatrixXd Xy = MatrixXd(X.rows(), X.cols()+1);\r\n\tXy << X, y;\r\n\t//cout << \"its ok?\"<<endl;\r\n\t//cout << \"...............\" <<endl;\r\n\t//cout << \"X.rows: \" << X.rows() << \"  X.cols:\" << X.cols() << \" y.size:\" << y.size() << \"  ..Xy.rows:\" << Xy.rows() << \"..Xy.cols:\" << Xy.cols() << endl;\r\n\tint n_samples = X.rows();\r\n\tint n_features = X.cols();\r\n\r\n\tarray<double, 2> best_criteria;\r\n\tarray<MatrixXd, 4> best_sets;\r\n\r\n\tif(n_samples >= min_samples_split && current_depth < max_depth){\r\n\t\t// calculate the impurity for each feature\r\n\t\tfor(int i = 0; i < n_features; i++){\r\n\t\t\t// all values of feature index i\r\n\t\t\tVectorXd feature_values = X.col(i);\r\n\t\t\tunordered_set<double> unique_values;\r\n\t\t\tfor(int j = 0; j < feature_values.size(); j++){\r\n\t\t\t\tunique_values.insert(feature_values[j]);\r\n\t\t\t}\r\n\r\n\t\t\t// iterate through all unique values of feature column i and\r\n\t\t\t// calculate the impurity\r\n\t\t\tfor(auto p = unique_values.begin(); p != unique_values.end(); p++){\r\n\t\t\t\t//cout << \"start div...\" << endl;\r\n\t\t\t\tarray<MatrixXd,2> X_div = Utils::divide_on_feature(Xy, i, *p);\r\n\t\t\t\tMatrixXd Xy1 = X_div[0];\r\n\t\t\t\tMatrixXd Xy2 = X_div[1];\r\n\t\t\t\t//cout << \"Xy1: \" << Xy1.rows() << \"..\" << Xy1.cols() << endl;\r\n\t\t\t\t//cout << \"Xy2: \" << Xy2.rows() << \"..\" << Xy2.cols() << endl;\r\n\r\n\t\t\t\tif(Xy1.rows() > 0 && Xy2.rows() > 0){\r\n\t\t\t\t\t// select the y_values of the two sets\r\n\t\t\t\t\tVectorXd y1 = Xy1.col(Xy1.cols()-1);\r\n\t\t\t\t\tVectorXd y2 = Xy2.col(Xy2.cols()-1);\r\n\t\t\t\t\t//cout << \"y1:\" << y1.size() << \"y2: \" << y2.size() << endl;\r\n\t\t\t\t\t// calculate impurity\r\n\t\t\t\t\tdouble impurity = impurity_calculation(y, y1, y2);\r\n\t\t\t\t\t//cout << \"impurity done \" << impurity << endl;\r\n\t\t\t\t\t// if this threshold resulted in a higher information gain than previously\r\n\t\t\t\t\t// recorded save the threshod value and the feature\r\n\t\t\t\t\tif(impurity > largest_impurity){\r\n\t\t\t\t\t\tlargest_impurity = impurity;\r\n\t\t\t\t\t\tbest_criteria[0] = i;\r\n\t\t\t\t\t\tbest_criteria[1] = *p;\r\n\t\t\t\t\t\t//cout << \"best_criteria \" << best_criteria[0] << \" \" << best_criteria[1] << endl;\r\n\r\n\t\t\t\t\t\t//MatrixXd Xy1_feature = Xy1.leftCols(Xy1.cols()-1);\r\n\t\t\t\t\t\t//MatrixXd Xy2_feature = Xy2.leftCols(Xy2.cols()-1);\r\n\r\n\t\t\t\t\t\tMatrixXd Xy1_feature(Xy1.rows(), Xy1.cols()-1), Xy2_feature(Xy2.rows(), Xy2.cols()-1);\r\n\t\t\t\t\t\tfor(int k = 0; k < Xy1.cols()-1; k++){\r\n\t\t\t\t\t\t\tXy1_feature.col(k) = Xy1.col(k);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tfor(int k = 0; k < Xy2.cols()-1; k++){\r\n\t\t\t\t\t\t\tXy2_feature.col(k) = Xy2.col(k);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tbest_sets[0] = Xy1_feature;\r\n\t\t\t\t\t\tbest_sets[1] = y1;\r\n\t\t\t\t\t\tbest_sets[2] = Xy2_feature;\r\n\t\t\t\t\t\tbest_sets[3] = y2;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t//cout << \"bulid tree next\" << endl;\r\n\tif(largest_impurity > min_impurity){\r\n\t\tDecisionNode* true_branch = build_tree(best_sets[0], best_sets[1], current_depth+1);\r\n\t\tDecisionNode* false_branch = build_tree(best_sets[2], best_sets[3], current_depth+1);\r\n\t\treturn new DecisionNode(static_cast<int>(best_criteria[0]), best_criteria[1], -1, true_branch, false_branch);\r\n\t}\r\n\t// we're at leaf ==> determind value\r\n\tdouble leaf_value = leaf_value_calculation(y);\r\n\tcout << \"leaf value: \" << leaf_value << endl;\r\n\treturn new DecisionNode(leaf_value);\r\n}\r\n\r\nint DecisionTree::predict(const VectorXd& X, DecisionNode* r){\r\n\tif(r == nullptr){\r\n\t\tr = root;\r\n\t}\r\n\tif(r->value != -1){\r\n\t\treturn r->value;\r\n\t}\r\n\t//cout << \"r->feature:\" << r->feature << endl;\r\n\tdouble feature_value = X(r->feature);\r\n\t//cout << \"nani ...\" << endl;\r\n\tDecisionNode* branch = r->false_branch;\r\n\tif(feature_value >= r->threshold){\r\n\t\tbranch = r->true_branch;\r\n\t}\r\n\treturn predict(X, branch);\r\n}\r\n\r\nVectorXi DecisionTree::predict(const MatrixXd& X){\r\n\tVectorXi ret(X.rows());\r\n\tfor(int i = 0; i < X.rows(); i++){\r\n\t\tret(i) = predict(X.row(i), root);\r\n\t}\r\n\treturn ret;\r\n}\r\n\r\ndouble DecisionTree::impurity_calculation(const VectorXd& y, const VectorXd& y1, const VectorXd& y2){\r\n\t// calculate information gain\r\n\tdouble prob = y1.size()/double(y2.size());\r\n\tdouble entropy = Utils::calculate_entropy(y);\r\n\tdouble info_gain = entropy - prob*Utils::calculate_entropy(y1) - (1-prob)*Utils::calculate_entropy(y2);\r\n\treturn info_gain;\r\n}\r\n\r\nint DecisionTree::leaf_value_calculation(const VectorXd& y){\r\n\tint most_common;\r\n\tint max_count = 0;\r\n\tunordered_map<int,int> m;\r\n\tfor(int i = 0; i < y.size(); i++){\r\n\t\tm[y(i)]++;\r\n\t}\r\n\tfor(auto p = m.begin(); p != m.end(); p++){\r\n\t\tif(p->second > max_count){\r\n\t\t\tmost_common = p->first;\r\n\t\t\tmax_count = p->second;\r\n\t\t}\r\n\t}\r\n\treturn most_common;\r\n}\r\n\r\n", "meta": {"hexsha": "dd19a3592e29cfa4cbaca1205ccf127620168642", "size": 5175, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/decision_tree.cc", "max_stars_repo_name": "KaiminLai/tiny-machine-learning-system", "max_stars_repo_head_hexsha": "e29625dfb513032b40712663b63f874e2ae6f924", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-09T16:03:50.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-09T16:03:50.000Z", "max_issues_repo_path": "src/decision_tree.cc", "max_issues_repo_name": "KaiminLai/tiny-machine-learning-system", "max_issues_repo_head_hexsha": "e29625dfb513032b40712663b63f874e2ae6f924", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/decision_tree.cc", "max_forks_repo_name": "KaiminLai/tiny-machine-learning-system", "max_forks_repo_head_hexsha": "e29625dfb513032b40712663b63f874e2ae6f924", "max_forks_repo_licenses": ["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.6038961039, "max_line_length": 178, "alphanum_fraction": 0.6142995169, "num_tokens": 1507, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867585368343, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.46701999368963754}}
{"text": "#include <cmath>\r\n#include <cstring>\r\n#include <cassert>\r\n#include <complex>\r\n#include <filesystem>\r\n\r\n#include <signal.h>\r\n#include <boost/fiber/buffered_channel.hpp>\r\n\r\n#include <scluk/language_extension.hpp>\r\n#include <scluk/math.hpp>\r\n#include <scluk/array.hpp>\r\n#include <scluk/functional.hpp>\r\n#include <scluk/sliding_queue.hpp>\r\n\r\n#include \"dft/sliding_dft.hpp\"\r\n#include \"sdl_gui_thread.hpp\"\r\n#include \"audio_params.hpp\"\r\n\r\nint main() {\r\n    using namespace scluk::language_extension;\r\n\r\n    std::filesystem::current_path(EXECUTABLE_DIR);\r\n\r\n    sdl_gui_thread gui_thread;\r\n\r\n\t//interrupt signal handling\r\n    signal(SIGINT, scluk::lambda_to_fnptr<void(int)>([&gui_thread](int) {\r\n        out(\"caught sigint!\");\r\n        gui_thread.data.do_exit = true;\r\n    }));\r\n\r\n    audio::sliding_dft dft;\r\n    audio::duplex_chan cb_chan;\r\n    portaudio::async_stream stream({ .frames_per_buffer=audio::ft_dist, .rate=audio::rate, .log=EXECUTABLE_DIR\"/log.txt\" }, audio::cb, cb_chan);\r\n\r\n    scluk::sliding_queue<audio::ift_chunk, audio::ift_overlap> ift_queue(audio::ift_chunk(0.f));\r\n    //first iteration, just to populate the arrays\r\n    dft.push_frames(cb_chan.cb_to_main.value_pop());\r\n    audio::dft_array phase_adjusted_dft(dft), old_dft(dft);\r\n\r\n    //main loop\r\n    while(!gui_thread.data.do_exit) {\r\n        //push the frames received from portaudio\r\n        dft.push_frames_fft(cb_chan.cb_to_main.value_pop());\r\n\r\n        const f32 pitch_mul = gui_thread.data.do_apply_effect ? std::pow(2.f, f32(gui_thread.data.pitch)/12.f) : 1.f;\r\n        //phase adjustment to avoid artifacts (this is what makes this a phase vocoder)\r\n        for(u64 i : index(dft)) {\r\n            using std::abs, std::arg;\r\n            using scluk::math::pi;\r\n\r\n            //p means phase, A means amplitude\r\n            const f32 p_new = arg(dft[i]), p_old = arg(old_dft[i]), \r\n                      p_old_adj = arg(phase_adjusted_dft[i]), A_new = abs(dft[i]);\r\n\r\n            //integer division allows me to automatically floor without additional cost\r\n            const f32 unwrap_addend = 2.f*pi * f32(i / audio::ift_overlap);\r\n\r\n            const f32 raw_p_delta = p_new - p_old;\r\n            const f32 mod_p_delta = raw_p_delta + std::signbit(raw_p_delta) * 2.f*pi;\r\n\r\n            const f32 adj_p_delta = (unwrap_addend + mod_p_delta) * pitch_mul;\r\n            const f32 p_new_adj = p_old_adj + adj_p_delta;\r\n\r\n            phase_adjusted_dft[i] = std::polar(A_new, p_new_adj);\r\n        }\r\n\r\n        //calculate the latest ift, apply the hann window and enqueue it\r\n        ift_queue << scluk::math::hann_window(phase_adjusted_dft.ifft<audio::ft_win>(pitch_mul));\r\n\r\n        audio::frame_chunk frames(0.f);\r\n\r\n        for(u64 n : index(ift_queue)) {\r\n            u64 starting_index = (audio::ift_overlap-1 - n) * audio::ft_dist;\r\n\r\n            for(u64 i : range(audio::ft_dist))\r\n                frames[i] += ift_queue[n][starting_index + i];\r\n        }\r\n\r\n        //send the frames to the callback\r\n        if(gui_thread.data.do_output_audio)\r\n            cb_chan.main_to_cb.push(std::move(frames));\r\n        else cb_chan.main_to_cb.push(audio::frame_chunk(0.f));\r\n\r\n        //send the old dft to the gui and repopulate it\r\n        gui_thread.channel.try_push(std::move(old_dft));\r\n        old_dft = dft;\r\n    }\r\n}\r\n", "meta": {"hexsha": "f426187befe0552ad56f3eaf2634652199fd2a3e", "size": 3302, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "circled-square/helium", "max_stars_repo_head_hexsha": "97b2f3079ca435554b86a235ff3ff2b4ae8a880c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-24T19:58:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-24T19:58:13.000Z", "max_issues_repo_path": "src/main.cpp", "max_issues_repo_name": "circled-square/helium", "max_issues_repo_head_hexsha": "97b2f3079ca435554b86a235ff3ff2b4ae8a880c", "max_issues_repo_licenses": ["Apache-2.0"], "max_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": "circled-square/helium", "max_forks_repo_head_hexsha": "97b2f3079ca435554b86a235ff3ff2b4ae8a880c", "max_forks_repo_licenses": ["Apache-2.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.2857142857, "max_line_length": 145, "alphanum_fraction": 0.6365838886, "num_tokens": 836, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314617436728, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.46700810340223764}}
{"text": "#ifndef __SWIG_CPP\n#define __SWIG_CPP\n\n#include \"swig_mod.hpp\"\n#include <Eigen/Cholesky>\n\nEigen::MatrixXd cholesky_swig_eigen(const Eigen::MatrixXd &M) {\n    Eigen::LLT<Eigen::MatrixXd> lltOfM(M);\n  return lltOfM.matrixL();\n}\n#endif\n", "meta": {"hexsha": "f363918d9a85018318bee7195c11b6d43708d40d", "size": 233, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cholesky/swig_eigen/swig_mod.cpp", "max_stars_repo_name": "Chachay/python_bench", "max_stars_repo_head_hexsha": "10ce8a93c498f24306d93160be6a000eb2b4f2a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cholesky/swig_eigen/swig_mod.cpp", "max_issues_repo_name": "Chachay/python_bench", "max_issues_repo_head_hexsha": "10ce8a93c498f24306d93160be6a000eb2b4f2a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cholesky/swig_eigen/swig_mod.cpp", "max_forks_repo_name": "Chachay/python_bench", "max_forks_repo_head_hexsha": "10ce8a93c498f24306d93160be6a000eb2b4f2a9", "max_forks_repo_licenses": ["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.4166666667, "max_line_length": 63, "alphanum_fraction": 0.7424892704, "num_tokens": 73, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4669805027194194}}
{"text": "// This file is a part of the OpenSurgSim project.\n// Copyright 2016, SimQuest Solutions Inc.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <boost/filesystem.hpp>\n#include <boost/program_options.hpp>\n#include <boost/property_tree/ini_parser.hpp>\n#include <boost/property_tree/ptree.hpp>\n#include <string>\n#include <vector>\n#include <yaml-cpp/yaml.h>\n\n#include \"SurgSim/DataStructures/Vertices.h\"\n#include \"SurgSim/Framework/Log.h\"\n#include \"SurgSim/Math/CardinalSplines.h\"\n#include \"SurgSim/Math/Vector.h\"\n\n/// Function to generate points on a circle with radius 'radius'.\n/// \\note The points always start from the origin and go on the circle to 'angle'.\n/// \\param subdivisions Number of interpolated points on the circle.\n/// \\param radius Radius of the circle on which points are generated.\n/// \\param angle How much (of the circle) should points occupy, in radian.\n/// \\return A list of points on the circle.\nstd::vector<SurgSim::Math::Vector3d> generateNeedle(size_t subdivisions, double radius, double angle)\n{\n\tSURGSIM_ASSERT(0 < angle && angle < 2.0 * M_PI) << __FUNCTION__ << \" 'angle' must be in the range (0, 2PI)\";\n\tSURGSIM_ASSERT(2 <= subdivisions) << __FUNCTION__ << \" 'subdivisions' must be at least 2\";\n\n\tdouble increment = angle / static_cast<double>(subdivisions);\n\tdouble controlAngle = 0.0;\n\n\tstd::vector<SurgSim::Math::Vector3d> vertices(subdivisions+1);\n\tfor (size_t i = 0; i < subdivisions; ++i)\n\t{\n\t\tvertices[i] = radius * SurgSim::Math::Vector3d(std::cos(controlAngle) - 1.0, std::sin(controlAngle), 0.0);\n\t\tcontrolAngle += increment;\n\t}\n\tvertices[subdivisions] =\n\t\tradius * SurgSim::Math::Vector3d(std::cos(controlAngle) - 1.0, std::sin(controlAngle), 0.0);\n\n\treturn vertices;\n}\n\n/// Function to generate a suture, starting from the origin and wraps around 'axis' in circles.\n/// A circle (formed by the suture when wraps 'axis') is defined by four markers.\n/// Each marker is rotated 45 degrees along 'axis' from previous one.\n/// 'subdivisions' controls how many points to interpolate between each pair of markers.\n/// In the returned list, the origin will always be the first point.\n/// \\param subdivisions Number of points between makers.\n/// \\param radius Radius of the circle the suture forms.\n/// \\param length Length of the suture.\n/// \\param circles Number of circles the suture forms wrapping around 'axis'.\n/// \\param axis The axis around which the suture wraps.\n/// \\return A list of points representing the suture.\nstd::vector<SurgSim::Math::Vector3d> generateSuture(size_t subdivisions, double radius, double length, size_t circles,\n\t\t\t\t\t\t\t\t\t\tconst SurgSim::Math::Vector3d& axis = SurgSim::Math::Vector3d(1.0, 0.0, 0.0))\n{\n\t// Increment on X-axis.\n\tdouble increment = length / circles / 4.0;\n\n\tSurgSim::Math::Vector3d direction = axis;\n\tdirection.normalize();\n\tauto rotateXToAxis = SurgSim::Math::makeRotationQuaternion(\n\t\t\t\t\t\t\t\t\t\t\t -std::acos(direction.dot(SurgSim::Math::Vector3d(1.0, 0.0, 0.0))),\n\t\t\t\t\t\t\t\t\t\t\t\t\t  direction.cross(SurgSim::Math::Vector3d(1.0, 0.0, 0.0)));\n\n\tstd::vector<SurgSim::Math::Vector3d> controlPoints;\n\tcontrolPoints.push_back(SurgSim::Math::Vector3d(0.0, 0.0, 0.0) - increment * direction);\n\tcontrolPoints.push_back(SurgSim::Math::Vector3d(0.0, 0.0, 0.0));\n\n\t// Used to control the rotation between markers.\n\tSurgSim::Math::Quaterniond rotation =\n\t\t\t\t\t\t\t\tSurgSim::Math::makeRotationQuaternion(M_PI_2, SurgSim::Math::Vector3d(1.0, 0.0, 0.0));\n\tauto point = SurgSim::Math::Vector3d(increment, radius, 0.0);\n\tfor (size_t i = 0; i < circles * 4; ++i)\n\t{\n\t\tcontrolPoints.push_back(rotateXToAxis * point);\n\t\tpoint = rotation * point;\n\t\tpoint.x() += increment;\n\t}\n\n\tstd::vector<SurgSim::Math::Vector3d> result;\n\tSurgSim::Math::CardinalSplines::interpolate(subdivisions, controlPoints, &result);\n\n\treturn result;\n}\n\n/// Save a list of needle and a list of suture as one ply file.\n/// Points in 'needle' will be output first, as the order they appear in 'needle' and\n/// points in 'suture' will be output second, as the order they appear in 'suture'.\n/// The caller of this function needs to make sure\n/// the needle and the suture connects (smoothly) at needle[last] and suture[begin].\n/// \\param fileName Name of the ply file.\n/// \\param needle List of points representing the needle.\n/// \\param suture List of points representing the suture.\n/// \\param asPhysics Boolean to decide whether or not to save physics properties.\n/// \\param needleMassDensity Mass density of needle.\n/// \\param needlepoissonRatio Poisson ratio of needle.\n/// \\param needleYoungModulus Young modulus of needle.\n/// \\param sutureMassDensity Mass density of suture.\n/// \\param suturepoissonRatio Poisson ratio of suture.\n/// \\param sutureYoungModulus Young modulus of suture.\n/// \\param radius Radius used for fem1d beam.\nvoid saveNeedleSuturePly(const std::string& fileName,\n\t\t\t\t\t\t const std::vector<SurgSim::Math::Vector3d>& needle,\n\t\t\t\t\t\t const std::vector<SurgSim::Math::Vector3d>& suture,\n\t\t\t\t\t\t bool asPhysics,\n\t\t\t\t\t\t double needleMassDensity, double needlePoissonRatio, double needleYoungModulus,\n\t\t\t\t\t\t double sutureMassDensity, double suturePoissonRatio, double sutureYoungModulus,\n\t\t\t\t\t\t double radius = 0.0001)\n{\n\tstd::ofstream out(fileName);\n\n\tsize_t numOfPoints = needle.size() + suture.size();\n\tif (out.is_open())\n\t{\n\t\tout << \"ply\" << std::endl;\n\t\tout << \"format ascii 1.0\" << std::endl;\n\t\tout << \"comment Created by OpenSurgSim, www.opensurgsim.org\" << std::endl;\n\t\tout << \"element vertex \" << numOfPoints << std::endl;\n\t\tout << \"property float x\\nproperty float y\\nproperty float z\" << std::endl;\n\t\tif (asPhysics)\n\t\t{\n\t\t\tout << \"element 1d_element \" << numOfPoints - 1 << std::endl;\n\t\t\tout << \"property list uint uint vertex_indices\" << std::endl;\n\t\t\tout << \"property double mass_density\" << std::endl;\n\t\t\tout << \"property double poisson_ratio\" << std::endl;\n\t\t\tout << \"property double young_modulus\" << std::endl;\n\t\t}\n\t\tout << \"element radius 1\" << std::endl;\n\t\tout << \"property double value\" << std::endl;\n\t\tout << \"element boundary_condition 0\" << std::endl;\n\t\tout << \"property uint vertex_index\" << std::endl;\n\t\tout << \"end_header\" << std::endl;\n\t\tfor (const auto& vertex : needle)\n\t\t{\n\t\t\tout << vertex[0] << \" \" << vertex[1] << \" \" << vertex[2] << std::endl;\n\t\t}\n\t\tfor (const auto& vertex : suture)\n\t\t{\n\t\t\tout << vertex[0] << \" \" << vertex[1] << \" \" << vertex[2] << std::endl;\n\t\t}\n\n\t\tif (asPhysics)\n\t\t{\n\t\t\tint index = 0;\n\t\t\tfor (const auto& vertex : needle)\n\t\t\t{\n\t\t\t\tout << \"2 \" << index << \" \" << index + 1 << \" \" <<\n\t\t\t\t\tneedleMassDensity << \" \" << needlePoissonRatio << \" \" << needleYoungModulus << std::endl;\n\t\t\t\t++index;\n\t\t\t}\n\t\t\tfor (const auto& vertex : suture)\n\t\t\t{\n\t\t\t\tout << \"2 \" << index << \" \" << index + 1 << \" \" <<\n\t\t\t\t\tsutureMassDensity << \" \" << suturePoissonRatio << \" \" << sutureYoungModulus << std::endl;\n\t\t\t\t++index;\n\t\t\t}\n\t\t}\n\n\t\tout << radius << std::endl;\n\n\t\tif (out.bad())\n\t\t{\n\t\t\tSURGSIM_LOG_WARNING(SurgSim::Framework::Logger::getDefaultLogger()) << __FUNCTION__\n\t\t\t\t<< \"There was a problem writing \" << fileName;\n\t\t}\n\n\t\tout.close();\n\t}\n\telse\n\t{\n\t\tSURGSIM_LOG_WARNING(SurgSim::Framework::Logger::getDefaultLogger()) << __FUNCTION__\n\t\t\t<< \"Could not open \" << fileName << \" for writing.\";\n\t}\n};\n\n// Utility to generate a ply file for needle suture.\n// Command line input are supported.\nint main(int argc, char* argv[])\n{\n\tnamespace po = boost::program_options;\n\n\tpo::options_description commandLine(\"Allowed options\");\n\tcommandLine.add_options()(\"help\", \"produce help message\")\n\t(\"filename\", po::value<std::string>()->default_value(\"needlesuture.ply\"),\n\t\t\t\t\t\t\t\t\t\"File name to save the generated needle suture.\")\n\t(\"needleSubdivisions\", po::value<int>()->default_value(10),\n\t\t\t\t\t\t\t\t\t\"Number of interpolated points for the needle (default 10)\")\n\t(\"needleRadius\", po::value<double>()->default_value(0.019), \"Radius of the needle (in m) (default 0.019)\")\n\t(\"needleAngle\", po::value<double>()->default_value(135),\n\t\t\t\t\t\t\t\t\t\"How big is the arc (common values: 90, 135, 180, 225) in degrees (default 135)\")\n\t(\"sutureSubdivisions\", po::value<int>()->default_value(20),\n\t\t\t\t\t\t\t\t\t\"Number of interpolated points for each pair of markers on the suture (default 20)\")\n\t(\"sutureRadius\", po::value<double>()->default_value(0.01), \"Radius of the suture (default 0.01\")\n\t(\"sutureLength\", po::value<double>()->default_value(0.45), \"Length of th suture (in m) (default 0.45)\")\n\t(\"sutureCircles\", po::value<int>()->default_value(2), \"Number of circles formed by suture going around the axis\")\n\t(\"savePhysicsProperty\", po::value<bool>()->default_value(true),\n\t\t\t\t\t\t\t\t\t\"Output physics properties for the needle and suture in ply file\")\n\t(\"physicsProperty\", po::value<std::string>(),\n\t\t\t\t\t\t\t\t\t\"File name for physics properties. Note that command line values have priority: \"\n\t\t\t\t\t\t\t\t\t\"program will use value(s) from command line if specified.\")\n\t(\"needleMassDensity\", po::value<double>(), \"Mass density for the needle (default 7500 Kg.m-3)\")\n\t(\"needlePoissonRatio\", po::value<double>(), \"Poisson ratio for the needle (default 0.305)\")\n\t(\"needleYoungModulus\", po::value<double>(), \"Young Modulus for the needle (default (1.8e11 Pa)\")\n\t(\"sutureMassDensity\", po::value<double>(), \"Mass density for the suture (default 900 Kg.m-3)\")\n\t(\"suturePoissonRatio\", po::value<double>(), \"Poisson ratio for the suture (default 0.45)\")\n\t(\"sutureYoungModulus\", po::value<double>(), \"Young Modulus for the suture (default 1.75e9 Pa)\");\n\n\tpo::variables_map variables;\n\ttry\n\t{\n\t\tpo::store(po::parse_command_line(argc, argv, commandLine), variables);\n\t}\n\tcatch (po::error& e)\n\t{\n\t\tstd::cerr << \"ERROR: \" << e.what() << std::endl << std::endl;\n\t\tstd::cerr << commandLine << std::endl;\n\t\treturn 1;\n\t}\n\n\tif (variables.count(\"help\"))\n\t{\n\t\tstd::cout << commandLine << \"\\n\";\n\t\treturn 1;\n\t}\n\n\tdouble needleMassDensity = 7500, needlePoissonRatio = 0.305, needleYoungModulus = 180 * 1e9;\n\tdouble sutureMassDensity = 900,  suturePoissonRatio = 0.45,  sutureYoungModulus = 1.75 * 1e9;\n\tif (variables.count(\"physicsProperty\"))\n\t{\n\t\tboost::filesystem::path fileName(\"Data/\" + variables[\"physicsProperty\"].as<std::string>());\n\t\tboost::filesystem::path filePath = boost::filesystem::complete(fileName);\n\t\tstd::cout << \"File path: \" << filePath << std::endl;\n\t\tif (!boost::filesystem::exists(filePath))\n\t\t{\n\t\t\tstd::cout << \"Can't find my file!\" << std::endl;\n\t\t\treturn -1;\n\t\t}\n\n\t\tboost::property_tree::ptree parameters;\n\t\tboost::property_tree::ini_parser::read_ini(filePath.string(), parameters);\n\t\tneedleMassDensity  = parameters.get<double>(\"PhysicsProperty.needleMassDensity\");\n\t\tneedlePoissonRatio = parameters.get<double>(\"PhysicsProperty.needlePoissonRatio\");\n\t\tneedleYoungModulus = parameters.get<double>(\"PhysicsProperty.needleYoungModulus\");\n\t\tsutureMassDensity  = parameters.get<double>(\"PhysicsProperty.sutureMassDensity\");\n\t\tsuturePoissonRatio = parameters.get<double>(\"PhysicsProperty.suturePoissonRatio\");\n\t\tsutureYoungModulus = parameters.get<double>(\"PhysicsProperty.sutureYoungModulus\");\n\t}\n\n\t// Command line values for physics properties will take precedence if specified.\n\tif (variables.count(\"needleMassDensity\"))  needleMassDensity  = variables[\"needleMassDensity\"].as<double>();\n\tif (variables.count(\"needlePoissonRatio\")) needlePoissonRatio = variables[\"needlePoissonRatio\"].as<double>();\n\tif (variables.count(\"needleYoungModulus\")) needleYoungModulus = variables[\"needleYoungModulus\"].as<double>();\n\tif (variables.count(\"sutureMassDensity\"))  sutureMassDensity  = variables[\"sutureMassDensity\"].as<double>();\n\tif (variables.count(\"suturePoissonRatio\")) suturePoissonRatio = variables[\"suturePoissonRatio\"].as<double>();\n\tif (variables.count(\"sutureYoungModulus\")) sutureYoungModulus = variables[\"sutureYoungModulus\"].as<double>();\n\n\tauto needlePoints = generateNeedle(variables[\"needleSubdivisions\"].as<int>(),\n\t\t\t\t\t\t\t\t\t   variables[\"needleRadius\"].as<double>(),\n\t\t\t\t\t\t\t\t\t   variables[\"needleAngle\"].as<double>() / 180 * M_PI);\n\n\tauto suturePoints = generateSuture(variables[\"sutureSubdivisions\"].as<int>(),\n\t\t\t\t\t\t\t\t\t   variables[\"sutureRadius\"].as<double>(),\n\t\t\t\t\t\t\t\t\t   variables[\"sutureLength\"].as<double>(),\n\t\t\t\t\t\t\t\t\t   variables[\"sutureCircles\"].as<int>(),\n\t\t\t\t\t\t\t\t\t   needlePoints[0] - needlePoints[1]);\n\n\t// Points generated are starting from the origin, when constructing the needle suture,\n\t// the list of needle points need to be reversed and the origin is removed to avoid duplication.\n\tstd::vector<SurgSim::Math::Vector3d> needlePointsReversed(needlePoints.rbegin(), needlePoints.rend()-1);\n\n\tsaveNeedleSuturePly(variables[\"filename\"].as<std::string>(), needlePointsReversed, suturePoints,\n\t\t\t\t\t\tvariables[\"savePhysicsProperty\"].as<bool>(),\n\t\t\t\t\t\tneedleMassDensity, needlePoissonRatio, needleYoungModulus,\n\t\t\t\t\t\tsutureMassDensity, suturePoissonRatio, sutureYoungModulus);\n\treturn 0;\n}\n", "meta": {"hexsha": "4aa67ec7af01d66c7e84506a4e6b13066c18b2cc", "size": 13317, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tools/NeedleSutureGeneration/NeedleSutureGeneration.cpp", "max_stars_repo_name": "dbungert/opensurgsim", "max_stars_repo_head_hexsha": "bd30629f2fd83f823632293959b7654275552fa9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2015-01-19T16:18:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T03:29:11.000Z", "max_issues_repo_path": "Tools/NeedleSutureGeneration/NeedleSutureGeneration.cpp", "max_issues_repo_name": "dbungert/opensurgsim", "max_issues_repo_head_hexsha": "bd30629f2fd83f823632293959b7654275552fa9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-12-21T14:54:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-14T12:38:07.000Z", "max_forks_repo_path": "Tools/NeedleSutureGeneration/NeedleSutureGeneration.cpp", "max_forks_repo_name": "dbungert/opensurgsim", "max_forks_repo_head_hexsha": "bd30629f2fd83f823632293959b7654275552fa9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-04-10T19:45:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-02T17:00:59.000Z", "avg_line_length": 45.4505119454, "max_line_length": 118, "alphanum_fraction": 0.7007584291, "num_tokens": 3590, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4669805027194194}}
{"text": "/* Copyright (C) 2012-2020 IBM Corp.\n * This program is Licensed under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *   http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License. See accompanying LICENSE file.\n */\n#include <NTL/ZZ.h>\n#include <algorithm>\n#include <complex>\n\n#include <helib/norms.h>\n#include <helib/helib.h>\n#include <helib/debugging.h>\n\n#include \"gtest/gtest.h\"\n#include \"test_common.h\"\n\nnamespace {\nstruct Parameters\n{\n  Parameters(long R, long m, long r, long L, double epsilon) :\n      R(R), m(m), r(r), L(L), epsilon(epsilon){};\n\n  const long R; // number of rounds\n  const long m;\n  const long r;\n  const long L;\n  const double epsilon;\n\n  friend std::ostream& operator<<(std::ostream& os, const Parameters& params)\n  {\n    return os << \"{\"\n              << \"R=\" << params.R << \",\"\n              << \"m=\" << params.m << \",\"\n              << \"r=\" << params.r << \",\"\n              << \"L=\" << params.L << \",\"\n              << \"epsilon=\" << params.epsilon << \"}\";\n  }\n};\n\n// Utility functions for the tests\n\n// Compute the L-infinity distance between two vectors\ndouble calcMaxDiff(const std::vector<std::complex<double>>& v1,\n                   const std::vector<std::complex<double>>& v2)\n{\n  if (helib::lsize(v1) != helib::lsize(v2)) {\n    throw std::runtime_error(\"Vector sizes differ.\");\n  }\n\n  double maxDiff = 0.0;\n  for (long i = 0; i < helib::lsize(v1); i++) {\n    double diffAbs = std::abs(v1[i] - v2[i]);\n    if (diffAbs > maxDiff)\n      maxDiff = diffAbs;\n  }\n  return maxDiff;\n}\n// Compute the max relative difference between two vectors\ndouble calcMaxRelDiff(const std::vector<std::complex<double>>& v1,\n                      const std::vector<std::complex<double>>& v2)\n{\n  if (helib::lsize(v1) != helib::lsize(v2)) {\n    throw std::runtime_error(\"Vector sizes differ.\");\n  }\n\n  // Compute the largest-magnitude value in the vector\n  double maxAbs = 0.0;\n  for (const auto& x : v1) {\n    if (std::abs(x) > maxAbs)\n      maxAbs = std::abs(x);\n  }\n  if (maxAbs < 1e-10)\n    maxAbs = 1e-10;\n\n  double maxDiff = 0.0;\n  for (long i = 0; i < helib::lsize(v1); i++) {\n    double relDiff = std::abs(v1[i] - v2[i]) / maxAbs;\n    if (relDiff > maxDiff)\n      maxDiff = relDiff;\n  }\n\n  return maxDiff;\n}\n\ninline bool cx_equals(const std::vector<std::complex<double>>& v1,\n                      const std::vector<std::complex<double>>& v2,\n                      double epsilon)\n{\n  return (calcMaxRelDiff(v1, v2) < epsilon);\n}\n\n::testing::AssertionResult ciphertextMatches(\n    const helib::EncryptedArrayCx& ea,\n    const helib::SecKey& sk,\n    const std::vector<std::complex<double>>& p,\n    const helib::Ctxt& c,\n    double epsilon)\n{\n  std::vector<std::complex<double>> pp;\n  ea.decrypt(c, sk, pp);\n  if (helib_test::verbose) {\n    std::cout << \"    relative-error=\" << calcMaxRelDiff(p, pp)\n              << \", absolute-error=\" << calcMaxRelDiff(p, pp) << std::endl;\n  }\n\n  if (cx_equals(pp, p, epsilon)) {\n    return ::testing::AssertionSuccess();\n  } else {\n    return ::testing::AssertionFailure()\n           << \"Ciphertext does not match plaintext:\" << std::endl\n           << \"p = \" << helib::vecToStr(p) << std::endl\n           << \"pp = \" << helib::vecToStr(pp) << std::endl;\n  }\n}\n\nvoid negateVec(std::vector<std::complex<double>>& p1)\n{\n  for (auto& x : p1)\n    x = -x;\n}\nvoid add(std::vector<std::complex<double>>& to,\n         const std::vector<std::complex<double>>& from)\n{\n  if (to.size() < from.size())\n    to.resize(from.size(), 0);\n  for (std::size_t i = 0; i < from.size(); i++)\n    to[i] += from[i];\n}\nvoid sub(std::vector<std::complex<double>>& to,\n         const std::vector<std::complex<double>>& from)\n{\n  if (to.size() < from.size())\n    to.resize(from.size(), 0);\n  for (std::size_t i = 0; i < from.size(); i++)\n    to[i] -= from[i];\n}\nvoid mul(std::vector<std::complex<double>>& to,\n         const std::vector<std::complex<double>>& from)\n{\n  if (to.size() < from.size())\n    to.resize(from.size(), 0);\n  for (std::size_t i = 0; i < from.size(); i++)\n    to[i] *= from[i];\n}\nvoid rotate(std::vector<std::complex<double>>& p, long amt)\n{\n  long sz = p.size();\n  std::vector<std::complex<double>> tmp(sz);\n  for (long i = 0; i < sz; i++)\n    tmp[((i + amt) % sz + sz) % sz] = p[i];\n  p = tmp;\n}\n\nclass GTestApproxNums : public ::testing::TestWithParam<Parameters>\n{\nprotected:\n  const long R;\n  const long m;\n  const long r;\n  const long L;\n  const double epsilon;\n\n  helib::Context context;\n  helib::SecKey secretKey;\n  const helib::PubKey publicKey;\n  const helib::EncryptedArrayCx& ea;\n\n  GTestApproxNums() :\n      R(GetParam().R),\n      m(GetParam().m),\n      r(GetParam().r),\n      L(GetParam().L),\n      epsilon(GetParam().epsilon),\n      context(m, /*p=*/-1, r),\n      secretKey(\n          (context.scale = 4, buildModChain(context, L, /*c=*/2), context)),\n      publicKey(\n          (secretKey.GenSecKey(), addSome1DMatrices(secretKey), secretKey)),\n      ea(context.ea->getCx())\n  {}\n\n  virtual void SetUp() override\n  {\n    if (helib_test::verbose) {\n      ea.getPAlgebra().printout();\n      std::cout << \"r = \" << context.alMod.getR() << std::endl;\n      std::cout << \"ctxtPrimes=\" << context.ctxtPrimes\n                << \", specialPrimes=\" << context.specialPrimes << std::endl\n                << std::endl;\n    }\n\n    helib::setupDebugGlobals(&secretKey, context.ea);\n  }\n\n  virtual void TearDown() override { helib::cleanupDebugGlobals(); }\n};\n\nTEST_P(GTestApproxNums, basicArithmeticWorks)\n{\n  if (helib_test::verbose)\n    std::cout << \"Test Arithmetic \";\n  // Test objects\n\n  helib::Ctxt c1(publicKey), c2(publicKey), c3(publicKey);\n\n  std::vector<std::complex<double>> vd;\n  std::vector<std::complex<double>> vd1, vd2, vd3;\n  ea.random(vd1);\n  ea.random(vd2);\n\n  // test encoding of shorter vectors\n  vd1.resize(vd1.size() - 2);\n  ea.encrypt(c1, publicKey, vd1, /*size=*/1.0);\n  vd1.resize(vd1.size() + 2, 0.0);\n\n  ea.encrypt(c2, publicKey, vd2, /*size=*/1.0);\n\n  // Test - Multiplication\n  c1 *= c2;\n  for (long i = 0; i < helib::lsize(vd1); i++)\n    vd1[i] *= vd2[i];\n\n  NTL::ZZX poly;\n  ea.random(vd3);\n  ea.encode(poly, vd3, /*size=*/1.0);\n  c1.addConstant(poly); // vd1*vd2 + vd3\n  for (long i = 0; i < helib::lsize(vd1); i++)\n    vd1[i] += vd3[i];\n\n  // Test encoding, encryption of a single number\n  double xx = NTL::RandomLen_long(16) / double(1L << 16); // random in [0,1]\n  ea.encryptOneNum(c2, publicKey, xx);\n  c1 += c2;\n  for (auto& x : vd1)\n    x += xx;\n\n  // Test - Multiply by a mask\n  std::vector<long> mask(helib::lsize(vd1), 1);\n  for (long i = 0; i * (i + 1) < helib::lsize(mask); i++) {\n    mask[i * i] = 0;\n    mask[i * (i + 1)] = -1;\n  }\n\n  ea.encode(poly, mask, /*size=*/1.0);\n  c1.multByConstant(poly); // mask*(vd1*vd2 + vd3)\n  for (long i = 0; i < helib::lsize(vd1); i++)\n    vd1[i] *= mask[i];\n\n  // Test - Addition\n  ea.random(vd3);\n  ea.encrypt(c3, publicKey, vd3, /*size=*/1.0);\n  c1 += c3;\n  for (long i = 0; i < helib::lsize(vd1); i++)\n    vd1[i] += vd3[i];\n\n  c1.negate();\n  c1.addConstant(NTL::to_ZZ(1));\n  for (long i = 0; i < helib::lsize(vd1); i++)\n    vd1[i] = 1.0 - vd1[i];\n\n  // Diff between approxNums HE scheme and plaintext floating\n  ea.decrypt(c1, secretKey, vd);\n#ifdef HELIB_DEBUG\n  helib::printVec(std::cout << \"res=\", vd, 10) << std::endl;\n  helib::printVec(std::cout << \"vec=\", vd1, 10) << std::endl;\n#endif\n  if (helib_test::verbose)\n    std::cout << \"(max |res-vec|_{infty}=\" << calcMaxDiff(vd, vd1) << \"): \";\n\n  EXPECT_TRUE(cx_equals(vd, vd1, NTL::conv<double>(epsilon * c1.getPtxtMag())))\n      << \"  max(vd)=\" << helib::largestCoeff(vd)\n      << \", max(vd1)=\" << helib::largestCoeff(vd1)\n      << \", maxDiff=\" << calcMaxDiff(vd, vd1) << std::endl\n      << std::endl;\n}\n\nTEST_P(GTestApproxNums, complexArithmeticWorks)\n{\n  // Test complex conjugate\n  helib::Ctxt c1(publicKey), c2(publicKey);\n\n  std::vector<std::complex<double>> vd;\n  std::vector<std::complex<double>> vd1, vd2;\n  ea.random(vd1);\n  ea.random(vd2);\n\n  ea.encrypt(c1, publicKey, vd1, /*size=*/1.0);\n  ea.encrypt(c2, publicKey, vd2, /*size=*/1.0);\n\n  if (helib_test::verbose)\n    std::cout << \"Test Conjugate: \";\n  for_each(vd1.begin(), vd1.end(), [](std::complex<double>& d) {\n    d = std::conj(d);\n  });\n  c1.complexConj();\n  ea.decrypt(c1, secretKey, vd);\n#ifdef HELIB_DEBUG\n  helib::printVec(std::cout << \"vd1=\", vd1, 10) << std::endl;\n  helib::printVec(std::cout << \"res=\", vd, 10) << std::endl;\n#endif\n  EXPECT_TRUE(cx_equals(vd, vd1, NTL::conv<double>(epsilon * c1.getPtxtMag())))\n      << \"  max(vd)=\" << helib::largestCoeff(vd)\n      << \", max(vd1)=\" << helib::largestCoeff(vd1)\n      << \", maxDiff=\" << calcMaxDiff(vd, vd1) << std::endl\n      << std::endl;\n  ;\n\n  // Test that real and imaginary parts are actually extracted.\n  helib::Ctxt realCtxt(c2), imCtxt(c2);\n  std::vector<std::complex<double>> realParts(vd2), real_dec;\n  std::vector<std::complex<double>> imParts(vd2), im_dec;\n\n  if (helib_test::verbose)\n    std::cout << \"Test Real and Im parts: \";\n  for_each(realParts.begin(), realParts.end(), [](std::complex<double>& d) {\n    d = std::real(d);\n  });\n  for_each(imParts.begin(), imParts.end(), [](std::complex<double>& d) {\n    d = std::imag(d);\n  });\n\n  ea.extractRealPart(realCtxt);\n  ea.decrypt(realCtxt, secretKey, real_dec);\n\n  ea.extractImPart(imCtxt);\n  ea.decrypt(imCtxt, secretKey, im_dec);\n\n#ifdef HELIB_DEBUG\n  helib::printVec(std::cout << \"vd2=\", vd2, 10) << std::endl;\n  helib::printVec(std::cout << \"real=\", realParts, 10) << std::endl;\n  helib::printVec(std::cout << \"res=\", real_dec, 10) << std::endl;\n  helib::printVec(std::cout << \"im=\", imParts, 10) << std::endl;\n  helib::printVec(std::cout << \"res=\", im_dec, 10) << std::endl;\n#endif\n  EXPECT_TRUE(cx_equals(realParts,\n                        real_dec,\n                        NTL::conv<double>(epsilon * realCtxt.getPtxtMag())))\n      << \"  max(re)=\" << helib::largestCoeff(realParts)\n      << \", max(re1)=\" << helib::largestCoeff(real_dec)\n      << \", maxDiff=\" << calcMaxDiff(realParts, real_dec) << std::endl;\n  EXPECT_TRUE(cx_equals(imParts,\n                        im_dec,\n                        NTL::conv<double>(epsilon * imCtxt.getPtxtMag())))\n      << \"  max(im)=\" << helib::largestCoeff(imParts)\n      << \", max(im1)=\" << helib::largestCoeff(im_dec)\n      << \", maxDiff=\" << calcMaxDiff(imParts, im_dec) << std::endl\n      << std::endl;\n}\n\nTEST_P(GTestApproxNums, rotatesAndShiftsWork)\n{\n  std::srand(std::time(0)); // set seed, current time.\n  int nplaces = rand() % static_cast<int>(ea.size() / 2.0) + 1;\n\n  if (helib_test::verbose)\n    std::cout << \"Test Rotation of \" << nplaces << \": \";\n\n  helib::Ctxt c1(publicKey);\n  std::vector<std::complex<double>> vd1;\n  std::vector<std::complex<double>> vd_dec;\n  ea.random(vd1);\n  ea.encrypt(c1, publicKey, vd1, /*size=*/1.0);\n\n#ifdef HELIB_DEBUG\n  helib::printVec(std::cout << \"vd1=\", vd1, 10) << std::endl;\n#endif\n  std::rotate(vd1.begin(), vd1.end() - nplaces, vd1.end());\n  ea.rotate(c1, nplaces);\n  c1.reLinearize();\n  ea.decrypt(c1, secretKey, vd_dec);\n#ifdef HELIB_DEBUG\n  helib::printVec(std::cout << \"vd1(rot)=\", vd1, 10) << std::endl;\n  helib::printVec(std::cout << \"res: \", vd_dec, 10) << std::endl;\n#endif\n\n  EXPECT_TRUE(\n      cx_equals(vd1, vd_dec, NTL::conv<double>(epsilon * c1.getPtxtMag())))\n      << \"  max(vd)=\" << helib::largestCoeff(vd_dec)\n      << \", max(vd1)=\" << helib::largestCoeff(vd1)\n      << \", maxDiff=\" << calcMaxDiff(vd_dec, vd1) << std::endl\n      << std::endl;\n}\n\nTEST_P(GTestApproxNums, generalOpsWorks)\n{\n  /************** Each round consists of the following:\n   1. c1.multiplyBy(c0)\n   2. c0 += random constant\n   3. c2 *= random constant\n   4. tmp = c1\n   5. ea.rotate(tmp, random amount in [-nSlots/2, nSlots/2])\n   6. c2 += tmp\n   7. ea.rotate(c2, random amount in [1-nSlots, nSlots-1])\n   8. c1.negate()\n   9. c3.multiplyBy(c2)\n   10. c0 -= c3\n   **************/\n  long nslots = ea.size();\n  char buffer[32];\n\n  std::vector<std::complex<double>> p0, p1, p2, p3;\n  ea.random(p0);\n  ea.random(p1);\n  ea.random(p2);\n  ea.random(p3);\n\n  helib::Ctxt c0(publicKey), c1(publicKey), c2(publicKey), c3(publicKey);\n  ea.encrypt(c0, publicKey, p0, /*size=*/1.0);\n  ea.encrypt(c1, publicKey, p1, /*size=*/1.0);\n  ea.encrypt(c2, publicKey, p2, /*size=*/1.0);\n  ea.encrypt(c3, publicKey, p3, /*size=*/1.0);\n\n  helib::resetAllTimers();\n  HELIB_NTIMER_START(Circuit);\n\n  for (long i = 0; i < R; i++) {\n\n    if (helib_test::verbose)\n      std::cout << \"*** round \" << i << \"...\" << std::endl;\n\n    long shamt = NTL::RandomBnd(2 * (nslots / 2) + 1) - (nslots / 2);\n    // random number in [-nslots/2..nslots/2]\n    long rotamt = NTL::RandomBnd(2 * nslots - 1) - (nslots - 1);\n    // random number in [-(nslots-1)..nslots-1]\n\n    // two random constants\n    std::vector<std::complex<double>> const1, const2;\n    ea.random(const1);\n    ea.random(const2);\n\n    NTL::ZZX const1_poly, const2_poly;\n    ea.encode(const1_poly, const1, /*size=*/1.0);\n    ea.encode(const2_poly, const2, /*size=*/1.0);\n\n    mul(p1, p0); // c1.multiplyBy(c0)\n    c1.multiplyBy(c0);\n    if (helib_test::verbose) {\n      CheckCtxt(c1, \"c1*=c0\");\n    }\n    EXPECT_TRUE(ciphertextMatches(ea, secretKey, p1, c1, epsilon));\n\n    add(p0, const1); // c0 += random constant\n    c0.addConstant(const1_poly);\n    if (helib_test::verbose) {\n      CheckCtxt(c0, \"c0+=k1\");\n    }\n    EXPECT_TRUE(ciphertextMatches(ea, secretKey, p0, c0, epsilon));\n\n    mul(p2, const2); // c2 *= random constant\n    c2.multByConstant(const2_poly);\n    if (helib_test::verbose) {\n      CheckCtxt(c2, \"c2*=k2\");\n    }\n    EXPECT_TRUE(ciphertextMatches(ea, secretKey, p2, c2, epsilon));\n\n    std::vector<std::complex<double>> tmp_p(p1); // tmp = c1\n    helib::Ctxt tmp(c1);\n    sprintf(buffer, \"tmp=c1>>=%d\", (int)shamt);\n    rotate(tmp_p,\n           shamt); // ea.shift(tmp, random amount in [-nSlots/2,nSlots/2])\n    ea.rotate(tmp, shamt);\n    if (helib_test::verbose) {\n      CheckCtxt(tmp, buffer);\n    }\n    EXPECT_TRUE(ciphertextMatches(ea, secretKey, tmp_p, tmp, epsilon));\n\n    add(p2, tmp_p); // c2 += tmp\n    c2 += tmp;\n    if (helib_test::verbose) {\n      CheckCtxt(c2, \"c2+=tmp\");\n    }\n    EXPECT_TRUE(ciphertextMatches(ea, secretKey, p2, c2, epsilon));\n\n    sprintf(buffer, \"c2>>>=%d\", (int)rotamt);\n    rotate(p2, rotamt); // ea.rotate(c2, random amount in [1-nSlots, nSlots-1])\n    ea.rotate(c2, rotamt);\n    if (helib_test::verbose) {\n      CheckCtxt(c2, buffer);\n    }\n    EXPECT_TRUE(ciphertextMatches(ea, secretKey, p2, c2, epsilon));\n\n    negateVec(p1); // c1.negate()\n    c1.negate();\n    if (helib_test::verbose) {\n      CheckCtxt(c1, \"c1=-c1\");\n    }\n    EXPECT_TRUE(ciphertextMatches(ea, secretKey, p1, c1, epsilon));\n\n    mul(p3, p2); // c3.multiplyBy(c2)\n    c3.multiplyBy(c2);\n    if (helib_test::verbose) {\n      CheckCtxt(c3, \"c3*=c2\");\n    }\n    EXPECT_TRUE(ciphertextMatches(ea, secretKey, p3, c3, epsilon));\n\n    sub(p0, p3); // c0 -= c3\n    c0 -= c3;\n    if (helib_test::verbose) {\n      CheckCtxt(c0, \"c0=-c3\");\n    }\n    EXPECT_TRUE(ciphertextMatches(ea, secretKey, p0, c0, epsilon));\n  }\n\n  c0.cleanUp();\n  c1.cleanUp();\n  c2.cleanUp();\n  c3.cleanUp();\n\n  HELIB_NTIMER_STOP(Circuit);\n\n  std::vector<std::complex<double>> pp0, pp1, pp2, pp3;\n\n  ea.decrypt(c0, secretKey, pp0);\n  ea.decrypt(c1, secretKey, pp1);\n  ea.decrypt(c2, secretKey, pp2);\n  ea.decrypt(c3, secretKey, pp3);\n\n  if (helib_test::verbose) {\n    std::cout << \"Test \" << R << \" rounds of mixed operations, \";\n  }\n  EXPECT_TRUE(\n      cx_equals(pp0, p0, NTL::conv<double>(epsilon * c0.getPtxtMag())) &&\n      cx_equals(pp1, p1, NTL::conv<double>(epsilon * c1.getPtxtMag())) &&\n      cx_equals(pp2, p2, NTL::conv<double>(epsilon * c2.getPtxtMag())) &&\n      cx_equals(pp3, p3, NTL::conv<double>(epsilon * c3.getPtxtMag())))\n      << \"  max(p0)=\" << helib::largestCoeff(p0)\n      << \", max(pp0)=\" << helib::largestCoeff(pp0)\n      << \", maxDiff=\" << calcMaxDiff(p0, pp0) << std::endl\n      << \"  max(p1)=\" << helib::largestCoeff(p1)\n      << \", max(pp1)=\" << helib::largestCoeff(pp1)\n      << \", maxDiff=\" << calcMaxDiff(p1, pp1) << std::endl\n      << \"  max(p2)=\" << helib::largestCoeff(p2)\n      << \", max(pp2)=\" << helib::largestCoeff(pp2)\n      << \", maxDiff=\" << calcMaxDiff(p2, pp2) << std::endl\n      << \"  max(p3)=\" << helib::largestCoeff(p3)\n      << \", max(pp3)=\" << helib::largestCoeff(pp3)\n      << \", maxDiff=\" << calcMaxDiff(p3, pp3) << std::endl\n      << std::endl;\n\n  if (helib_test::verbose) {\n    std::cout << std::endl;\n    helib::printAllTimers();\n    std::cout << std::endl;\n  }\n  helib::resetAllTimers();\n}\n\nINSTANTIATE_TEST_SUITE_P(typicalParameters,\n                         GTestApproxNums,\n                         ::testing::Values(\n                             // SLOW\n                             Parameters(1, 1024, 8, 150, 0.01)\n                             // FAST\n                             // Parameters(1, 128, 8, 150, 0.01)\n                             ));\n// if (R<=0) R=1;\n// if (R<=2)\n//  L = 100*R;\n// else\n//  L = 220*(R-1);\n\n} // namespace\n", "meta": {"hexsha": "cb8df421dd1ac8218a435eac5fb97838b42aca98", "size": 17408, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/GTestApproxNums.cpp", "max_stars_repo_name": "andrey-mindrin/HElib", "max_stars_repo_head_hexsha": "6b9ae8b5ab43af3b566598c095d4edaba6d6a775", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1360.0, "max_stars_repo_stars_event_min_datetime": "2015-01-02T23:57:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T01:25:28.000Z", "max_issues_repo_path": "tests/GTestApproxNums.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": "tests/GTestApproxNums.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": 30.5940246046, "max_line_length": 79, "alphanum_fraction": 0.5869140625, "num_tokens": 5572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.4669796407615126}}
{"text": "#include <stan/math/prim.hpp>\n#include <test/unit/math/prim/prob/util.hpp>\n#include <test/unit/math/prim/prob/vector_rng_test_helper.hpp>\n#include <boost/math/distributions.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <gtest/gtest.h>\n#include <limits>\n#include <vector>\n\nclass StdNormalTestRig : public VectorRealRNGTestRig {\n public:\n  /*\n   * The default StdNormalTestRig constructor initializes the TestRig with\n   * valid and invalid parameters for a random number generator with no\n   * arguments.\n   */\n  StdNormalTestRig() : VectorRealRNGTestRig(10000, 10) {}\n\n  /*\n   * This function wraps up the random number generator for testing.\n   *\n   * The tested rng can have up to three parameters. Any unused parameters can\n   * be ignored.\n   */\n  template <typename T1, typename T2, typename T3, typename T_rng>\n  auto generate_samples(const T1&, const T2&, const T3&, T_rng& rng) const {\n    return stan::math::std_normal_rng(rng);\n  }\n\n  /*\n   * This function builds the quantiles that we will supply to\n   * assert_matches_quantiles to test the std_normal_rng\n   */\n  std::vector<double> generate_quantiles(double, double, double) const {\n    std::vector<double> quantiles;\n    double K = stan::math::round(2 * std::pow(N_, 0.4));\n    boost::math::normal_distribution<> dist(0, 1);\n\n    for (int i = 1; i < K; ++i) {\n      double frac = i / K;\n      quantiles.push_back(quantile(dist, frac));\n    }\n    quantiles.push_back(std::numeric_limits<double>::max());\n\n    return quantiles;\n  }\n};\n\nTEST(ProbDistributionsStdNormal, errorCheck) {\n  /*\n   * This test verifies that std_normal_rng throws errors in the right places.\n   *\n   * It does so by calling test_rig::generate_samples for all possible\n   * combinations of calling arguments.\n   */\n  check_dist_throws_all_types(StdNormalTestRig());\n}\n\nTEST(ProbDistributionsStdNormal, distributionTest) {\n  /*\n   * This test checks that the std_normal_rng is actually generating numbers\n   * from the correct distributions. Quantiles are computed from\n   * test_rig::generate_quantiles\n   *\n   * It does so for all possible combinations of calling arguments.\n   */\n  check_quantiles_no_params(StdNormalTestRig());\n}\n\nTEST(ProbDistributionsStdNormal, error_check) {\n  boost::random::mt19937 rng;\n  EXPECT_NO_THROW(stan::math::std_normal_rng(rng));\n}\n\nTEST(ProbDistributionsStdNormal, chiSquareGoodnessFitTest) {\n  boost::random::mt19937 rng;\n  int N = 10000;\n  int K = stan::math::round(2 * std::pow(N, 0.4));\n\n  std::vector<double> samples;\n  for (int i = 0; i < N; ++i) {\n    samples.push_back(stan::math::std_normal_rng(rng));\n  }\n\n  // Generate quantiles from boost's normal distribution\n  boost::math::normal_distribution<> dist(0.0, 1.0);\n  std::vector<double> quantiles;\n  for (int i = 1; i < K; ++i) {\n    double frac = static_cast<double>(i) / K;\n    quantiles.push_back(quantile(dist, frac));\n  }\n  quantiles.push_back(std::numeric_limits<double>::max());\n\n  // Assert that they match\n  assert_matches_quantiles(samples, quantiles, 1e-6);\n}\n", "meta": {"hexsha": "3ed4aa6500f17844a9f9cdce0d7d3cae4faa2917", "size": 3017, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/prim/prob/std_normal_test.cpp", "max_stars_repo_name": "LaudateCorpus1/math", "max_stars_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-18T13:10:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-18T13:10:50.000Z", "max_issues_repo_path": "test/unit/math/prim/prob/std_normal_test.cpp", "max_issues_repo_name": "LaudateCorpus1/math", "max_issues_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "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": "test/unit/math/prim/prob/std_normal_test.cpp", "max_forks_repo_name": "LaudateCorpus1/math", "max_forks_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-05-10T12:55:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-10T12:55:07.000Z", "avg_line_length": 31.1030927835, "max_line_length": 78, "alphanum_fraction": 0.7086509778, "num_tokens": 808, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768249, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.46697963085881916}}
{"text": "/*\n \n [begin_description]\n Test case for issue 147\n [end_description]\n\n Copyright 2011-2015 Karsten Ahnert\n Copyright 2011-2015 Mario Mulansky\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// disable checked iterator warning for msvc\n\n#include <boost/config.hpp>\n#ifdef BOOST_MSVC\n    #pragma warning(disable:4996)\n#endif\n\n#define BOOST_TEST_MODULE odeint_regression_147\n\n#include <utility>\n\n#include <boost/array.hpp>\n\n#include <boost/test/unit_test.hpp>\n\n#include <boost/mpl/vector.hpp>\n\n#include <boost/numeric/odeint.hpp>\n\nusing namespace boost::unit_test;\nusing namespace boost::numeric::odeint;\nnamespace mpl = boost::mpl;\n\ntypedef double state_type;\n\nvoid rhs( const state_type &x , state_type &dxdt , const double t )\n{\n    dxdt = 1;\n}\n\n\ntemplate<class Stepper, class InitStepper>\nstruct perform_init_test\n{\n    void operator()( void )\n    {\n        double t = 0;\n        const double dt = 0.1;\n\n        state_type x = 0;\n\n        Stepper stepper;\n        InitStepper init_stepper;\n        stepper.initialize( init_stepper, rhs, x, t, dt ); \n\n        // ab-stepper needs order-1 init steps: t and x should be (order-1)*dt\n        BOOST_CHECK_CLOSE( t , (stepper.order()-1)*dt , 1E-16 );\n        BOOST_CHECK_CLOSE( x, ( stepper.order() - 1 ) * dt, 2E-14 );\n    }\n};\n\ntypedef mpl::vector<\n    euler< state_type > ,\n    modified_midpoint< state_type > ,\n    runge_kutta4< state_type > ,\n    runge_kutta4_classic< state_type > ,\n    runge_kutta_cash_karp54_classic< state_type > ,\n    runge_kutta_cash_karp54< state_type > ,\n    runge_kutta_dopri5< state_type > ,\n    runge_kutta_fehlberg78< state_type >\n    > runge_kutta_steppers;\n\n\nBOOST_AUTO_TEST_SUITE( regression_147_test )\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( init_test , InitStepper, \n                               runge_kutta_steppers )\n{\n    perform_init_test< adams_bashforth<4, state_type>, InitStepper > tester;\n    tester();\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "7373782dfb2f3cac642471ed96c82a60fe2867e9", "size": 2031, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/odeint/test/regression/regression_147.cpp", "max_stars_repo_name": "cpp-pm/boost", "max_stars_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "libs/numeric/odeint/test/regression/regression_147.cpp", "max_issues_repo_name": "cpp-pm/boost", "max_issues_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "libs/numeric/odeint/test/regression/regression_147.cpp", "max_forks_repo_name": "cpp-pm/boost", "max_forks_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 22.8202247191, "max_line_length": 78, "alphanum_fraction": 0.6971935007, "num_tokens": 545, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.63341027751814, "lm_q1q2_score": 0.46692355636539656}}
{"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__LIE_GROUP_HPP_\n#define SMOOTH__LIE_GROUP_HPP_\n\n#include <Eigen/Core>\n\n#include <concepts>\n\n#include \"manifold.hpp\"\n\n/**\n * @file lie_group.hpp Internal and external LieGroup interfaces and free LieGroup functions.\n */\n\nnamespace smooth {\n\nnamespace traits {\n\n/**\n * @brief Trait class for making a class a LieGroup instance via specialization.\n */\ntemplate<typename T>\nstruct lie;\n\n}  // namespace traits\n\n// clang-format off\n\n/**\n * @brief Class-external Lie group interface defined through the traits::lie trait class.\n */\ntemplate<typename G>\nconcept LieGroup =\nrequires (Eigen::Index dof) {\n  // Underlying scalar type\n  typename traits::lie<G>::Scalar;\n  // Default representation\n  typename traits::lie<G>::PlainObject;\n  // Compile-time degrees of freedom (tangent space dimension). Can be dynamic (equal to -1)\n  {traits::lie<G>::Dof}->std::convertible_to<Eigen::Index>;\n  // Commutativity\n  {traits::lie<G>::IsCommutative}->std::convertible_to<bool>;\n  // Return the identity element (dof = Dof for static size)\n  {traits::lie<G>::Identity(dof)}->std::convertible_to<typename traits::lie<G>::PlainObject>;\n  // Return a random element (dof = Dof for static size)\n  {traits::lie<G>::Random(dof)}->std::convertible_to<typename traits::lie<G>::PlainObject>;\n} &&\n// GROUP INTERFACE\nrequires(const G & g1, const G & g2, typename traits::lie<G>::Scalar eps) {\n  // Group adjoint\n  {traits::lie<G>::Ad(g1)}->std::convertible_to<Eigen::Matrix<typename traits::lie<G>::Scalar, traits::lie<G>::Dof, traits::lie<G>::Dof>>;\n  // Group composition\n  {traits::lie<G>::composition(g1, g2)}->std::convertible_to<typename traits::lie<G>::PlainObject>;\n  // Run-time degrees of freedom (tangent space dimension).\n  {traits::lie<G>::dof(g1)}->std::convertible_to<Eigen::Index>;\n  // Group inverse\n  {traits::lie<G>::inverse(g1)}->std::convertible_to<typename traits::lie<G>::PlainObject>;\n  // Check if two elements are (approximately) equal\n  {traits::lie<G>::isApprox(g1, g2, eps)}->std::convertible_to<bool>;\n  // Group logarithm (maps from group to algebra)\n  {traits::lie<G>::log(g1)}->std::convertible_to<Eigen::Vector<typename traits::lie<G>::Scalar, traits::lie<G>::Dof>>;\n} &&\n// TANGENT INTERFACE\nrequires(const Eigen::Vector<typename traits::lie<G>::Scalar, traits::lie<G>::Dof> & a) {\n  // Algebra adjoint\n  {traits::lie<G>::ad(a)}->std::convertible_to<Eigen::Matrix<typename traits::lie<G>::Scalar, traits::lie<G>::Dof, traits::lie<G>::Dof>>;\n  // Algebra exponential (maps from algebra to group)\n  {traits::lie<G>::exp(a)}->std::convertible_to<typename traits::lie<G>::PlainObject>;\n  // Right derivative of the exponential map\n  {traits::lie<G>::dr_exp(a)}->std::convertible_to<Eigen::Matrix<typename traits::lie<G>::Scalar, traits::lie<G>::Dof, traits::lie<G>::Dof>>;\n  // Right derivative of the exponential map inverse\n  {traits::lie<G>::dr_expinv(a)}->std::convertible_to<Eigen::Matrix<typename traits::lie<G>::Scalar, traits::lie<G>::Dof, traits::lie<G>::Dof>>;\n  // Second right derivative of the exponential map\n  {traits::lie<G>::d2r_exp(a)}->std::convertible_to<Eigen::Matrix<typename traits::lie<G>::Scalar, traits::lie<G>::Dof, (traits::lie<G>::Dof > 0 ? traits::lie<G>::Dof * traits::lie<G>::Dof : -1)>>;\n  // Second right derivative of the exponential map inverse\n  {traits::lie<G>::d2r_expinv(a)}->std::convertible_to<Eigen::Matrix<typename traits::lie<G>::Scalar, traits::lie<G>::Dof, (traits::lie<G>::Dof > 0 ? traits::lie<G>::Dof * traits::lie<G>::Dof : -1)>>;\n} && (\n  // Cast to different scalar type\n  !std::is_convertible_v<typename traits::lie<G>::Scalar, double> ||\n  requires (const G & g) {\n    {traits::lie<G>::template cast<double>(g)};\n  }\n) && (\n  !std::is_convertible_v<typename traits::lie<G>::Scalar, float> ||\n  requires (const G & g) {\n    {traits::lie<G>::template cast<double>(g)};\n  }\n) &&\n// PlainObject must be default-constructible\nstd::is_default_constructible_v<typename traits::lie<G>::PlainObject> &&\nstd::is_copy_constructible_v<typename traits::lie<G>::PlainObject> &&\n// PlainObject must be assignable from G\nstd::is_assignable_v<typename traits::lie<G>::PlainObject &, G>;\n\n////////////////////////////////////////////////\n//// Lie group interface for NativeLieGroup ////\n////////////////////////////////////////////////\n\n/**\n * @brief Concept defining class with an internal Lie group interface.\n *\n * Concept satisfied if G has members that correspond to the LieGroup concept.\n */\ntemplate<typename G>\nconcept NativeLieGroup = requires\n{\n  typename G::Scalar;\n  typename G::Tangent;\n  typename G::PlainObject;\n  {G::Dof}->std::convertible_to<Eigen::Index>;\n  {G::IsCommutative}->std::convertible_to<bool>;\n} &&\n(!(G::Dof > 0) || requires {\n  {G::Identity()}->std::convertible_to<typename G::PlainObject>;\n  {G::Random()}->std::convertible_to<typename G::PlainObject>;\n}) &&\n(!(G::Dof == -1) || requires (Eigen::Index dof) {\n  {G::Identity(dof)}->std::convertible_to<typename G::PlainObject>;\n  {G::Random(dof)}->std::convertible_to<typename G::PlainObject>;\n}) &&\n(G::Tangent::SizeAtCompileTime == G::Dof) &&\nrequires(const G & g1, const G & g2, typename G::Scalar eps) {\n  {g1.dof()}->std::convertible_to<Eigen::Index>;  // degrees of freedom at runtime\n  {g1.Ad()}->std::convertible_to<Eigen::Matrix<typename G::Scalar, G::Dof, G::Dof>>;\n  {g1 * g2}->std::convertible_to<typename G::PlainObject>;\n  {g1.inverse()}->std::convertible_to<typename G::PlainObject>;\n  {g1.isApprox(g2, eps)}->std::convertible_to<bool>;\n  {g1.log()}->std::convertible_to<Eigen::Vector<typename G::Scalar, G::Dof>>;\n} &&\nrequires(const Eigen::Vector<typename G::Scalar, G::Dof> & a) {\n  {G::ad(a)}->std::convertible_to<Eigen::Matrix<typename G::Scalar, G::Dof, G::Dof>>;\n  {G::exp(a)}->std::convertible_to<typename G::PlainObject>;\n  {G::dr_exp(a)}->std::convertible_to<Eigen::Matrix<typename G::Scalar, G::Dof, G::Dof>>;\n  {G::dr_expinv(a)}->std::convertible_to<Eigen::Matrix<typename G::Scalar, G::Dof, G::Dof>>;\n  {G::d2r_exp(a)}->std::convertible_to<Eigen::Matrix<typename G::Scalar, G::Dof, G::Dof * G::Dof>>;\n  {G::d2r_expinv(a)}->std::convertible_to<Eigen::Matrix<typename G::Scalar, G::Dof, G::Dof * G::Dof>>;\n};\n\n// clang-format on\n\nnamespace traits\n{\n\n/**\n * @brief LieGroup interface for NativeLieGroup\n */\ntemplate<NativeLieGroup G>\nstruct lie<G>\n{\n  // \\cond\n  using Scalar = typename G::Scalar;\n  template<typename NewScalar>\n  using CastT       = typename G::template CastT<NewScalar>;\n  using PlainObject = typename G::PlainObject;\n\n  static constexpr Eigen::Index Dof   = G::Dof;\n  static constexpr bool IsCommutative = G::IsCommutative;\n\n  // group interface\n\n  static inline PlainObject Identity([[maybe_unused]] Eigen::Index dof)\n  {\n    if constexpr (G::Dof == -1) {\n      return G::Identity(dof);\n    } else {\n      return G::Identity();\n    }\n  }\n  static inline PlainObject Random([[maybe_unused]] Eigen::Index dof)\n  {\n    if constexpr (G::Dof == -1) {\n      return G::Random(dof);\n    } else {\n      return G::Random();\n    }\n  }\n  static inline typename G::TangentMap Ad(const G & g) { return g.Ad(); }\n  template<NativeLieGroup Go>\n  static inline PlainObject composition(const G & g1, const Go & g2)\n  {\n    return g1.operator*(g2);\n  }\n  static inline Eigen::Index dof(const G &) { return G::Dof; }\n  static inline PlainObject inverse(const G & g) { return g.inverse(); }\n  template<NativeLieGroup Go>\n  static inline bool isApprox(const G & g, const Go & go, Scalar eps)\n  {\n    return g.isApprox(go, eps);\n  }\n  static inline typename G::Tangent log(const G & g) { return g.log(); }\n  template<typename NewScalar>\n  static inline CastT<NewScalar> cast(const G & g)\n  {\n    return g.template cast<NewScalar>();\n  }\n\n  // tangent interface\n\n  template<typename Derived>\n  static inline typename G::TangentMap ad(const Eigen::MatrixBase<Derived> & a)\n  {\n    return G::ad(a);\n  }\n  template<typename Derived>\n  static inline PlainObject exp(const Eigen::MatrixBase<Derived> & a)\n  {\n    return G::exp(a);\n  }\n  template<typename Derived>\n  static inline typename G::TangentMap dr_exp(const Eigen::MatrixBase<Derived> & a)\n  {\n    return G::dr_exp(a);\n  }\n  template<typename Derived>\n  static inline typename G::TangentMap dr_expinv(const Eigen::MatrixBase<Derived> & a)\n  {\n    return G::dr_expinv(a);\n  }\n  template<typename Derived>\n  static inline typename G::Hessian d2r_exp(const Eigen::MatrixBase<Derived> & a)\n  {\n    return G::d2r_exp(a);\n  }\n  template<typename Derived>\n  static inline typename G::Hessian d2r_expinv(const Eigen::MatrixBase<Derived> & a)\n  {\n    return G::d2r_expinv(a);\n  }\n  // \\endcond\n};\n\n///////////////////////////////////////////////\n//// Lie group interface for Eigen vectors ////\n///////////////////////////////////////////////\n\n/**\n * @brief LieGroup interface for RnType\n */\ntemplate<RnType G>\nstruct lie<G>\n{\n  // \\cond\n  static constexpr int Dof            = G::SizeAtCompileTime;\n  static constexpr bool IsCommutative = true;\n\n  using Scalar      = typename G::Scalar;\n  using PlainObject = Eigen::Vector<Scalar, Dof>;\n  template<typename NewScalar>\n  using CastT = Eigen::Vector<NewScalar, Dof>;\n\n  // group interface\n\n  static inline PlainObject Identity(Eigen::Index dof) { return G::Zero(dof); }\n  static inline PlainObject Random(Eigen::Index dof) { return G::Random(dof); }\n  static inline Eigen::Matrix<Scalar, Dof, Dof> Ad(const G & g)\n  {\n    return Eigen::Matrix<Scalar, Dof, Dof>::Identity(g.size(), g.size());\n  }\n  template<typename Derived>\n  static inline PlainObject composition(const G & g1, const Eigen::MatrixBase<Derived> & g2)\n  {\n    return g1 + g2;\n  }\n  static inline Eigen::Index dof(const G & g) { return g.size(); }\n  static inline PlainObject inverse(const G & g) { return -g; }\n  template<typename Derived>\n  static inline bool isApprox(const G & g, const Eigen::MatrixBase<Derived> & g2, Scalar eps)\n  {\n    return g.isApprox(g2, eps);\n  }\n  static inline Eigen::Vector<Scalar, Dof> log(const G & g) { return g; }\n  template<typename NewScalar>\n  static inline Eigen::Vector<NewScalar, Dof> cast(const G & g)\n  {\n    return g.template cast<NewScalar>();\n  }\n\n  // tangent interface\n\n  template<typename Derived>\n  static inline Eigen::Matrix<Scalar, Dof, Dof> ad(const Eigen::MatrixBase<Derived> & a)\n  {\n    return Eigen::Matrix<Scalar, Dof, Dof>::Zero(a.size(), a.size());\n  }\n  template<typename Derived>\n  static inline PlainObject exp(const Eigen::MatrixBase<Derived> & a)\n  {\n    return a;\n  }\n  template<typename Derived>\n  static inline Eigen::Matrix<Scalar, Dof, Dof> dr_exp(const Eigen::MatrixBase<Derived> & a)\n  {\n    return Eigen::Matrix<Scalar, Dof, Dof>::Identity(a.size(), a.size());\n  }\n  template<typename Derived>\n  static inline Eigen::Matrix<Scalar, Dof, Dof> dr_expinv(const Eigen::MatrixBase<Derived> & a)\n  {\n    return Eigen::Matrix<Scalar, Dof, Dof>::Identity(a.size(), a.size());\n  }\n  template<typename Derived>\n  static inline Eigen::Matrix<Scalar, Dof, (Dof > 0 ? Dof * Dof : -1)>\n  d2r_exp(const Eigen::MatrixBase<Derived> & a)\n  {\n    return Eigen::Matrix<Scalar, Dof, (Dof > 0 ? Dof * Dof : -1)>::Zero(\n      a.size(), a.size() * a.size());\n  }\n  template<typename Derived>\n  static inline Eigen::Matrix<Scalar, Dof, (Dof > 0 ? Dof * Dof : -1)>\n  d2r_expinv(const Eigen::MatrixBase<Derived> & a)\n  {\n    return Eigen::Matrix<Scalar, Dof, (Dof > 0 ? Dof * Dof : -1)>::Zero(\n      a.size(), a.size() * a.size());\n  }\n  // \\endcond\n};\n\n///////////////////////////////////////////////////////////////\n//// Lie group interface for built-in floating point types ////\n///////////////////////////////////////////////////////////////\n\n/**\n * @brief LieGroup interface for ScalarType\n */\ntemplate<ScalarType G>\nstruct lie<G>\n{\n  // \\cond\n  using Scalar      = G;\n  using PlainObject = G;\n  template<typename NewScalar>\n  using CastT = NewScalar;\n\n  static constexpr int Dof            = 1;\n  static constexpr bool IsCommutative = true;\n\n  // group interface\n\n  static inline PlainObject Identity(Eigen::Index) { return G(0); }\n  static inline PlainObject Random(Eigen::Index)\n  {\n    return G(Scalar(-1) + static_cast<Scalar>(rand()) / static_cast<Scalar>(RAND_MAX / 2));\n  }\n  static inline Eigen::Matrix<Scalar, 1, 1> Ad(G) { return Eigen::Matrix<Scalar, 1, 1>{1}; }\n  static inline PlainObject composition(G g1, G g2) { return g1 + g2; }\n  static inline Eigen::Index dof(G) { return 1; }\n  static inline PlainObject inverse(G g) { return -g; }\n  static inline bool isApprox(G g1, G g2, Scalar eps)\n  {\n    using std::abs;\n    return abs<G>(g1 - g2) <= eps * abs<G>(g1);\n  }\n  static inline Eigen::Matrix<Scalar, 1, 1> log(G g) { return Eigen::Matrix<Scalar, 1, 1>{g}; }\n  template<typename NewScalar>\n  static inline NewScalar cast(G g)\n  {\n    return static_cast<NewScalar>(g);\n  }\n\n  // tangent interface\n\n  template<typename Derived>\n  static inline Eigen::Matrix<Scalar, 1, 1> ad(const Eigen::MatrixBase<Derived> &)\n  {\n    return Eigen::Matrix<Scalar, 1, 1>::Zero();\n  }\n  template<typename Derived>\n  static inline PlainObject exp(const Eigen::MatrixBase<Derived> & a)\n  {\n    return a(0);\n  }\n  template<typename Derived>\n  static inline Eigen::Matrix<Scalar, 1, 1> dr_exp(const Eigen::MatrixBase<Derived> &)\n  {\n    return Eigen::Matrix<Scalar, 1, 1>::Identity();\n  }\n  template<typename Derived>\n  static inline Eigen::Matrix<Scalar, 1, 1> dr_expinv(const Eigen::MatrixBase<Derived> &)\n  {\n    return Eigen::Matrix<Scalar, 1, 1>::Identity();\n  }\n  template<typename Derived>\n  static inline Eigen::Matrix<Scalar, 1, 1> d2r_exp(const Eigen::MatrixBase<Derived> &)\n  {\n    return Eigen::Matrix<Scalar, 1, 1>::Zero();\n  }\n  template<typename Derived>\n  static inline Eigen::Matrix<Scalar, 1, 1> d2r_expinv(const Eigen::MatrixBase<Derived> &)\n  {\n    return Eigen::Matrix<Scalar, 1, 1>::Zero();\n  }\n  // \\endcond\n};\n\n/**\n * @brief Manifold interface for LieGroup that are not already Manifold.\n */\ntemplate<LieGroup G>\n  requires(!RnType<G> && !ScalarType<G>)\nstruct man<G>\n{\n  // \\cond\n  using Scalar      = typename traits::lie<G>::Scalar;\n  using PlainObject = typename traits::lie<G>::PlainObject;\n  template<typename NewScalar>\n  using CastT = typename traits::lie<G>::template CastT<NewScalar>;\n\n  static constexpr Eigen::Index Dof = traits::lie<G>::Dof;\n\n  static inline PlainObject Default(Eigen::Index dof) { return traits::lie<G>::Identity(dof); }\n\n  static inline Eigen::Index dof(const G & g) { return traits::lie<G>::dof(g); }\n\n  template<typename NewScalar>\n  static inline CastT<NewScalar> cast(const G & g)\n  {\n    return traits::lie<G>::template cast<NewScalar>(g);\n  }\n\n  template<typename Derived>\n  static inline PlainObject rplus(const G & g, const Eigen::MatrixBase<Derived> & a)\n  {\n    return traits::lie<G>::composition(g, traits::lie<G>::exp(a));\n  }\n\n  template<LieGroup Go = G>\n  static inline Eigen::Matrix<Scalar, Dof, 1> rminus(const G & g1, const Go & g2)\n  {\n    return traits::lie<G>::log(traits::lie<Go>::composition(traits::lie<Go>::inverse(g2), g1));\n  }\n  // \\endcond\n};\n\n}  // namespace traits\n\n////////////////////////////////////////////////////////\n//// Free functions that dispatch to traits::lie<G> ////\n////////////////////////////////////////////////////////\n\n// Group interface\n\ntemplate<LieGroup G>\nstatic constexpr bool IsCommutative = traits::lie<G>::IsCommutative;\n\n/**\n * @brief Identity in Lie group\n *\n * @param dof degrees of freedom\n */\ntemplate<LieGroup G>\ninline PlainObject<G> Identity(Eigen::Index dof)\n{\n  return traits::lie<G>::Identity(dof);\n}\n\n/**\n * @brief Identity in Lie group with static Dof\n */\ntemplate<LieGroup G>\n  requires(Dof<G> > 0)\ninline PlainObject<G> Identity() { return traits::lie<G>::Identity(Dof<G>); }\n\n/**\n * @brief Random element in Lie group\n *\n * @param dof degrees of freedom\n */\ntemplate<LieGroup G>\ninline PlainObject<G> Random(Eigen::Index dof)\n{\n  return traits::lie<G>::Random(dof);\n}\n\n/**\n * @brief Random element in Lie group with static Dof\n */\ntemplate<LieGroup G>\n  requires(Dof<G> > 0)\ninline PlainObject<G> Random() { return traits::lie<G>::Random(Dof<G>); }\n\n/**\n * @brief Group adjoint \\f$ Ad_g a \\coloneq (G * \\hat(a) * G^{-1})^{\\wedge} \\f$\n */\ntemplate<LieGroup G>\ninline TangentMap<G> Ad(const G & g)\n{\n  return traits::lie<G>::Ad(g);\n}\n\n/**\n * @brief Group binary composition\n */\ntemplate<LieGroup G, typename Arg>\ninline PlainObject<G> composition(const G & g, Arg && a)\n{\n  return traits::lie<G>::composition(g, std::forward<Arg>(a));\n}\n\n/**\n * @brief Group multinary composition\n */\ntemplate<LieGroup G, typename Arg, typename... Args>\ninline PlainObject<G> composition(const G & g, Arg && a, Args &&... as)\n{\n  return composition(composition(g, std::forward<Arg>(a)), std::forward<Args>(as)...);\n}\n\n/**\n * @brief Group inverse\n */\ntemplate<LieGroup G>\ninline PlainObject<G> inverse(const G & g)\n{\n  return traits::lie<G>::inverse(g);\n}\n\n/**\n * @brief Check if two group elements are approximately equal\n */\ntemplate<LieGroup G, typename Arg>\ninline bool isApprox(\n  const G & g,\n  Arg && a,\n  typename traits::lie<G>::Scalar eps =\n    Eigen::NumTraits<typename traits::lie<G>::Scalar>::dummy_precision())\n{\n  return traits::lie<G>::isApprox(g, std::forward<Arg>(a), eps);\n}\n\n/**\n * @brief Group logarithm\n *\n * @see exp()\n */\ntemplate<LieGroup G>\ninline Tangent<G> log(const G & g)\n{\n  return traits::lie<G>::log(g);\n}\n\n// Tangent interface\n\n/**\n * @brief Lie algebra adjoint \\f$ ad_a b = [a, b] \\f$\n */\ntemplate<LieGroup G, typename Arg>\ninline TangentMap<G> ad(Arg && a)\n{\n  return traits::lie<G>::ad(std::forward<Arg>(a));\n}\n\n/**\n * @brief Lie algebra exponential\n *\n * @see log()\n */\ntemplate<LieGroup G, typename Arg>\ninline PlainObject<G> exp(Arg && a)\n{\n  return traits::lie<G>::exp(std::forward<Arg>(a));\n}\n\n/**\n * @brief Right Jacobian of exponential map\n */\ntemplate<LieGroup G, typename Arg>\ninline TangentMap<G> dr_exp(Arg && a)\n{\n  return traits::lie<G>::dr_exp(std::forward<Arg>(a));\n}\n\n/**\n * @brief Right Jacobian of exponential map inverse\n */\ntemplate<LieGroup G, typename Arg>\ninline TangentMap<G> dr_expinv(Arg && a)\n{\n  return traits::lie<G>::dr_expinv(std::forward<Arg>(a));\n}\n\n/**\n * @brief Right Hessian of exponential map\n */\ntemplate<LieGroup G, typename Arg>\ninline Hessian<G> d2r_exp(Arg && a)\n{\n  return traits::lie<G>::d2r_exp(std::forward<Arg>(a));\n}\n\n/**\n * @brief Right Hessian of exponential map inverse\n */\ntemplate<LieGroup G, typename Arg>\ninline Hessian<G> d2r_expinv(Arg && a)\n{\n  return traits::lie<G>::d2r_expinv(std::forward<Arg>(a));\n}\n\n// Convenience methods\n\n/**\n * @brief Left-plus\n */\ntemplate<LieGroup G, typename Derived>\ninline PlainObject<G> lplus(const G & g, const Eigen::MatrixBase<Derived> & a)\n{\n  return composition(::smooth::exp<G>(a), g);\n}\n\n/**\n * @brief Left-minus\n */\ntemplate<LieGroup G, LieGroup Go>\ninline Tangent<G> lminus(const G & g1, const Go & g2)\n{\n  return log(composition(g1, inverse(g2)));\n}\n\n/**\n * @brief Left Jacobian of exponential map\n */\ntemplate<LieGroup G, typename Derived>\ninline TangentMap<G> dl_exp(const Eigen::MatrixBase<Derived> & a)\n{\n  return dr_exp<G>(-a);\n}\n\n/**\n * @brief Left Jacobian of exponential map inverse\n */\ntemplate<LieGroup G, typename Derived>\ninline TangentMap<G> dl_expinv(const Eigen::MatrixBase<Derived> & a)\n{\n  return dr_expinv<G>(-a);\n}\n\n/**\n * @brief Left Hessian of exponential map\n */\ntemplate<LieGroup G, typename Derived>\ninline Hessian<G> d2l_exp(const Eigen::MatrixBase<Derived> & a)\n{\n  return -d2r_exp<G>(-a);\n}\n\n/**\n * @brief Left Hessian of exponential map inverse\n */\ntemplate<LieGroup G, typename Derived>\ninline Hessian<G> d2l_expinv(const Eigen::MatrixBase<Derived> & a)\n{\n  return -d2r_expinv<G>(-a);\n}\n\n}  // namespace smooth\n\n#endif  // SMOOTH__LIE_GROUP_HPP_\n", "meta": {"hexsha": "e47ef9e0753216b926ea702fc9572fff685b59d8", "size": 20946, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/smooth/lie_group.hpp", "max_stars_repo_name": "tgurriet/smooth", "max_stars_repo_head_hexsha": "c19e35e23c8e0084314726729d0cf6729192240f", "max_stars_repo_licenses": ["MIT"], "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/lie_group.hpp", "max_issues_repo_name": "tgurriet/smooth", "max_issues_repo_head_hexsha": "c19e35e23c8e0084314726729d0cf6729192240f", "max_issues_repo_licenses": ["MIT"], "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/lie_group.hpp", "max_forks_repo_name": "tgurriet/smooth", "max_forks_repo_head_hexsha": "c19e35e23c8e0084314726729d0cf6729192240f", "max_forks_repo_licenses": ["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.7577092511, "max_line_length": 200, "alphanum_fraction": 0.665043445, "num_tokens": 5774, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.63341027751814, "lm_q1q2_score": 0.46692355636539656}}
{"text": "/*\n * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n#define BOOST_TEST_MAIN\n\n#define BOOST_TEST_MODULE table_test\n\n// Standard includes\n#include <exception>\n#include <iostream>\n\n// Third party includes\n#include <boost/lexical_cast.hpp>\n#include <boost/test/unit_test.hpp>\n\n// Local VOTCA includes\n#include \"votca/tools/table.h\"\n\nusing namespace std;\nusing namespace votca::tools;\n\nBOOST_AUTO_TEST_SUITE(table_test)\n\nBOOST_AUTO_TEST_CASE(create_test) {\n  Table tb;\n  Table tb2(tb);\n}\n\nBOOST_AUTO_TEST_CASE(size_test) {\n  Table tb;\n  BOOST_CHECK_EQUAL(tb.size(), 0);\n}\n\nBOOST_AUTO_TEST_CASE(pushback_test) {\n  Table tb;\n  for (double x = 0; x < 10; ++x) {\n    double y = 2 * x;\n    tb.push_back(x, y);\n  }\n  BOOST_CHECK_EQUAL(tb.size(), 10);\n}\n\nBOOST_AUTO_TEST_CASE(resize_test) {\n  Table tb;\n  tb.resize(0);\n  tb.resize(10);\n\n  bool error_thrown = false;\n  try {\n    tb.resize(-5);\n  } catch (...) {\n    error_thrown = true;\n  }\n  BOOST_CHECK(error_thrown);\n}\n\nBOOST_AUTO_TEST_CASE(xy_test) {\n  Table tb;\n  for (double x = 0; x < 10; ++x) {\n    double y = 2 * x;\n    tb.push_back(x, y);\n  }\n\n  auto x_v = tb.x();\n  auto y_v = tb.y();\n  for (votca::Index i = 0; i < 10; ++i) {\n    votca::Index x = i;\n    votca::Index y = 2 * x;\n    BOOST_CHECK_EQUAL(static_cast<votca::Index>(x_v(i)),\n                      static_cast<votca::Index>(tb.x(i)));\n    BOOST_CHECK_EQUAL(static_cast<votca::Index>(y_v(i)),\n                      static_cast<votca::Index>(tb.y(i)));\n    BOOST_CHECK_EQUAL(x, static_cast<votca::Index>(tb.x(i)));\n    BOOST_CHECK_EQUAL(y, static_cast<votca::Index>(tb.y(i)));\n    BOOST_CHECK_EQUAL(x, static_cast<votca::Index>(x_v(i)));\n    BOOST_CHECK_EQUAL(y, static_cast<votca::Index>(y_v(i)));\n  }\n}\n\nBOOST_AUTO_TEST_CASE(getMinMax_test) {\n  Table tb;\n  for (double x = 0; x < 10; ++x) {\n    double y = 2 * x;\n    tb.push_back(x, y);\n  }\n\n  BOOST_CHECK_EQUAL(static_cast<votca::Index>(tb.getMinX()), 0);\n  BOOST_CHECK_EQUAL(static_cast<votca::Index>(tb.getMaxX()), 9);\n  BOOST_CHECK_EQUAL(static_cast<votca::Index>(tb.getMinY()), 0);\n  BOOST_CHECK_EQUAL(static_cast<votca::Index>(tb.getMaxY()), 18);\n}\n\nBOOST_AUTO_TEST_CASE(generate_grid_spacing_test) {\n  Table tb;\n  double min_v = 1.2;\n  double max_v = 2.0;\n\n  tb.GenerateGridSpacing(min_v, max_v, 0.2);\n\n  BOOST_CHECK_EQUAL(tb.size(), 5);\n  BOOST_CHECK_CLOSE(tb.getMinX(), 1.2, 1e-5);\n  BOOST_CHECK_CLOSE(tb.getMaxX(), 2.0, 1e-5);\n}\n\nBOOST_AUTO_TEST_CASE(generate_grid_spacing_test_low) {\n  Table tb;\n  double min_v = 1.2;\n  double max_v = 2.0;\n\n  tb.GenerateGridSpacing(min_v, max_v, 0.3);\n\n  BOOST_CHECK_EQUAL(tb.size(), 3);\n  BOOST_CHECK_CLOSE(tb.getMinX(), 1.2, 1e-5);\n  BOOST_CHECK_CLOSE(tb.getMaxX(), 2.0, 1e-5);\n}\n\nBOOST_AUTO_TEST_CASE(generate_grid_spacing_test_high) {\n  Table tb;\n  double min_v = 1.2;\n  double max_v = 2.0;\n\n  tb.GenerateGridSpacing(min_v, max_v, 0.15);\n\n  BOOST_CHECK_EQUAL(tb.size(), 6);\n  BOOST_CHECK_CLOSE(tb.getMinX(), 1.2, 1e-5);\n  BOOST_CHECK_CLOSE(tb.getMaxX(), 2.0, 1e-5);\n}\n\nBOOST_AUTO_TEST_CASE(smoothing_test) {\n  Table tb;\n  double min_v = 1.2;\n  double max_v = 2.0;\n\n  tb.GenerateGridSpacing(min_v, max_v, 0.1);\n\n  BOOST_CHECK_EQUAL(tb.size(), 9);\n  tb.y() = tb.x().array().sinh();\n  tb.Smooth(2);\n  Eigen::VectorXd refy = Eigen::VectorXd::Zero(9);\n  refy << 1.50946, 1.70595, 1.91384, 2.13995, 2.38747, 2.65889, 2.95692,\n      3.28227, 3.62686;\n\n  bool equal = tb.y().isApprox(refy, 1e-5);\n\n  if (!equal) {\n    std::cout << \"result value\" << std::endl;\n    std::cout << tb.y().transpose() << std::endl;\n    std::cout << \"ref value\" << std::endl;\n    std::cout << refy.transpose() << std::endl;\n  }\n  BOOST_CHECK_EQUAL(equal, true);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "9a153298f371c88bf0986d21f8159262c44e7ca6", "size": 4258, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/tests/test_table.cc", "max_stars_repo_name": "MrTheodor/tools", "max_stars_repo_head_hexsha": "9bb95454a188e827bdf25a6de8302cde70355ecb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/tests/test_table.cc", "max_issues_repo_name": "MrTheodor/tools", "max_issues_repo_head_hexsha": "9bb95454a188e827bdf25a6de8302cde70355ecb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tests/test_table.cc", "max_forks_repo_name": "MrTheodor/tools", "max_forks_repo_head_hexsha": "9bb95454a188e827bdf25a6de8302cde70355ecb", "max_forks_repo_licenses": ["Apache-2.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.3452380952, "max_line_length": 75, "alphanum_fraction": 0.6679192109, "num_tokens": 1313, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102775181399, "lm_q2_score": 0.7371581568543043, "lm_q1q2_score": 0.4669235527078454}}
{"text": "//  Copyright (c) 2014 John Biddiscombe\n//\n//  Distributed under the Boost Software License, Version 1.0. (See accompanying\n//  file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include <hpx/hpx_init.hpp>\n#include <hpx/include/runtime.hpp>\n#include <hpx/lcos/when_all.hpp>\n#include <hpx/include/iostreams.hpp>\n//\n#include <random>\n#include <utility>\n#include <vector>\n\n#include  <boost/nondet_random.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_int_distribution.hpp>\n\n//\n// This is a simple example which generates random numbers and returns\n// pass or fail from a routine.\n// When called by many threads returning a vector of futures - if the user wants to\n// reduce the vector of pass/fails into a single pass fail based on a simple\n// any fail = !pass rule, then this example shows how to do it.\n// The user can experiment with the failure rate to see if the statistics match\n// their expectations.\n// Also. Routine can use either a lambda, or a function under control of USE_LAMBDA\n\n#define TEST_SUCCESS 1\n#define TEST_FAIL    0\n//\n#define FAILURE_RATE_PERCENT 5\n#define SAMPLES_PER_LOOP     10\n#define TEST_LOOPS           1000\n//\nboost::random::random_device rseed;\nboost::random::mt19937 gen(rseed());\nboost::random::uniform_int_distribution<int> dist(0,99); // interval [0,100)\n\n#define USE_LAMBDA\n\n//----------------------------------------------------------------------------\nint reduce(hpx::future<std::vector<hpx::future<int> > > &&futvec)\n{\n  int res = TEST_SUCCESS;\n  std::vector<hpx::future<int> > vfs = futvec.get();\n  for (hpx::future<int>& f: vfs) {\n    if (f.get() == TEST_FAIL) return TEST_FAIL;\n  }\n  return res;\n}\n\n//----------------------------------------------------------------------------\nint generate_one()\n{\n  // generate roughly x% fails\n  int result = TEST_SUCCESS;\n  if (dist(gen)>=(100-FAILURE_RATE_PERCENT)) {\n    result = TEST_FAIL;\n  }\n  return result;\n}\n\n//----------------------------------------------------------------------------\nhpx::future<int> test_reduce()\n{\n  std::vector<hpx::future<int> > req_futures;\n  //\n  for (int i=0; i<SAMPLES_PER_LOOP; i++) {\n    // generate random sequence of pass/fails using % fail rate per incident\n    hpx::future<int> result = hpx::async(generate_one);\n    req_futures.push_back(std::move(result));\n  }\n\n  hpx::future<std::vector<hpx::future<int> > > all_ready = hpx::when_all(req_futures);\n\n#ifdef USE_LAMBDA\n  hpx::future<int> result = all_ready.then(\n    [](hpx::future<std::vector<hpx::future<int> > > &&futvec) -> int {\n      // futvec is ready or the lambda would not be called\n      std::vector<hpx::future<int> > vfs = futvec.get();\n      // all futures in v are ready as fut is ready\n      int res = TEST_SUCCESS;\n      for (hpx::future<int>& f: vfs) {\n        if (f.get() == TEST_FAIL) return TEST_FAIL;\n      }\n      return res;\n  });\n#else\n  hpx::future<int> result = all_ready.then(reduce);\n#endif\n  //\n  return result;\n}\n\n//----------------------------------------------------------------------------\nint hpx_main()\n{\n  hpx::util::high_resolution_timer htimer;\n  // run N times and see if we get approximately the right amount of fails\n  int count = 0;\n  for (int i=0; i<TEST_LOOPS; i++) {\n    int result = test_reduce().get();\n    count += result;\n  }\n  double pr_pass  = std::pow(1.0 - FAILURE_RATE_PERCENT/100.0, SAMPLES_PER_LOOP);\n  double exp_pass = TEST_LOOPS*pr_pass;\n  hpx::cout << \"From \" << TEST_LOOPS << \" tests, we got \"\n    << \"\\n \" << count << \" passes\"\n    << \"\\n \" << exp_pass << \" expected \\n\"\n    << \"\\n \" << htimer.elapsed() << \" seconds \\n\" << hpx::flush;\n  // Initiate shutdown of the runtime system.\n  return hpx::finalize();\n}\n\n//----------------------------------------------------------------------------\nint main(int argc, char* argv[])\n{\n  // Initialize and run HPX.\n  return hpx::init(argc, argv);\n}\n\n", "meta": {"hexsha": "2977e07022521736dec49042ce40928ac46b439a", "size": 3879, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/future_reduce/rnd_future_reduce.cpp", "max_stars_repo_name": "brycelelbach/hpx", "max_stars_repo_head_hexsha": "94582f5dc26e889cdcf80913975ff33b7f975285", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-04-06T16:36:38.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-19T11:28:54.000Z", "max_issues_repo_path": "examples/future_reduce/rnd_future_reduce.cpp", "max_issues_repo_name": "atrantan/hpx", "max_issues_repo_head_hexsha": "6c214b2f3e3fc58648513c9f1cfef37fde59333c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-08-13T17:42:55.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-13T18:20:23.000Z", "max_forks_repo_path": "examples/future_reduce/rnd_future_reduce.cpp", "max_forks_repo_name": "atrantan/hpx", "max_forks_repo_head_hexsha": "6c214b2f3e3fc58648513c9f1cfef37fde59333c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-05-25T06:33:50.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-25T20:09:13.000Z", "avg_line_length": 31.5365853659, "max_line_length": 86, "alphanum_fraction": 0.6055684455, "num_tokens": 983, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.4669235461629065}}
{"text": "// Copyright (c) 2017 Franka Emika GmbH\n// Use of this source code is governed by the Apache-2.0 license, see LICENSE\n\n// Librerie standard\n#include <array>\n#include <cmath>\n#include <functional>\n#include <iostream>\n#include <vector>\n#include <thread>\n\n// Libreria Eigen Dense\n#include <Eigen/Dense>\n\n// Librerie Libfranka\n#include <franka/duration.h>\n#include <franka/exception.h>\n#include <franka/model.h>\n#include <franka/robot.h>\n\n// Contiene definizioni di funzioni utili \n#include \"../examples/examples_common.h\"\n\n// Header file con le dichiarazioni delle funzioni custom\n#include \"CustomLibrary/StateSaver.h\"\n\nconst int t_fin = 20; // 20 s\nconst int fs = 1000; // 1 KHz\nconst int ncampioni = t_fin*fs; \n\n\n\n/**\n * Esempio programma C++ per il controllo in coppia del robot Panda. \n * Tale esempio \u00e8 una modifica del file examples/cartesian_impedance_control.cpp.\n * E' stato realizzato un controllo di tipo PD con compensazione di gravit\u00e0 in cui la posa \n * desiderata \u00e8 pari alla posa iniziale del robot.\n * \n * Nota: l'orientamento dell'EndEffector rispetto alla terna base \u00e8 espresso attraverso quaternione unitario.\n * Nota: il Panda Robot compensa da se le coppie gravitazionali e gli attriti quindi non \u00e8 \n * necessario compensare le coppie gravitazionali. Inoltre, l'esempio prevede la compensazione \n * delle coppie di Coriolis e Centrifughe. \n * \n *\n * \n * Struttura del codice:\n * 1. Setup del robot\n * 2. Definizione dei parametri.\n * 3. Definizione del loop di controllo.\n * 4. Esecuzione del loop di controllo.\n * \n * Osservazione: il loop di controllo DEVE essere eseguito ad una frequenza di 1 Khz.\n * Per tale motivo la scrittura su file viene rimandata alla fine del loop di controllo.\n * \n */\n\n// Funzione per compattare posizione e quaternione sotto un unico vettore posa 7x1\nEigen::Matrix<double,7,1> posquat2mat(const Eigen::Vector3d& position, const Eigen::Quaterniond quaternion){\n    \n    Eigen::Matrix<double,7,1> pose;\n    pose(0,0) = position(0);\n    pose(1,0) = position(1);\n    pose(2,0) = position(2);\n    pose(3,0) = quaternion.w();\n    pose(4,0) = quaternion.x();\n    pose(5,0) = quaternion.y();\n    pose(6,0) = quaternion.z();\n    \n    return pose;\n}\n\n\n// Per utilizzare le variabili static della classe StateSaver serve istanziarle fuori dal main\n  double** StateSaver::buffer_6 = nullptr;\n  double** StateSaver::buffer_7 = nullptr; \n\n  Eigen::Matrix<double, 6, 1> StateSaver::error;\n  Eigen::Matrix<double,7,1> StateSaver::tau_measured;\n  Eigen::Matrix<double,7,1> StateSaver::q;\n  Eigen::Matrix<double, 7, 1> StateSaver::qdot;\n  Eigen::Matrix<double, 7, 1> StateSaver::pose;\n\n\nint main(int argc, char** argv) {\n\n  \n    if (argc != 2) {\n        std::cerr << \"Specificare l'indirizzo IP del robot.\" << std::endl;\n        return -1;\n    }\n\n    \n\n  // Controllo di cedevolezza attiva (PD + compensazione di gravit\u00e0)\n    const double rigidezza_translazionale{150.0};\n    const double rigidezza_torsionale{10.0};\n    Eigen::MatrixXd rigidezza(6, 6), smorzamento(6, 6);\n\n  // Costruzione di Kp = [K_t O ; O K_o] = rigidezza\n    rigidezza.setZero();\n    rigidezza.topLeftCorner(3, 3) << rigidezza_translazionale * Eigen::MatrixXd::Identity(3, 3);\n    rigidezza.bottomRightCorner(3, 3) << rigidezza_torsionale * Eigen::MatrixXd::Identity(3, 3);\n  \n  // Costruzione di Kd = [K_d_t O ; O K_d_o] = smorzamento\n    smorzamento.setZero();\n    smorzamento.topLeftCorner(3, 3) << 2.0 * sqrt(rigidezza_translazionale) *\n                                        Eigen::MatrixXd::Identity(3, 3);\n    smorzamento.bottomRightCorner(3, 3) << 2.0 * sqrt(rigidezza_torsionale) *\n                                            Eigen::MatrixXd::Identity(3, 3);\n\n    try {\n\n      // Connessione al robot (inizializzazione variabile robot)\n        franka::Robot robot(argv[1]);\n      \n\n      // Inizializzazione oggetto StateSaver per salvare su file\n        StateSaver::buffer_7 = new double*[ncampioni* 7];\n        StateSaver::buffer_6 = new double*[ncampioni * 6];\n\n        for(int i = 0; i< ncampioni * 7; i++)\n            StateSaver::buffer_7[i] = new double[lenght_buffer7]; // tau_m, q, dq, pose, pose_dot\n        \n        for(int i = 0; i< ncampioni * 6; i++)\n            StateSaver::buffer_6[i] = new double[lenght_buffer6]; // error\n\n        StateSaver sv;\n\n      // Set collision behavior (https://frankaemika.github.io/libfranka/classfranka_1_1Robot.html#a168e1214ac36d74ac64f894332b84534)\n        robot.setCollisionBehavior({{100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0}},\n                                {{100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0}},\n                                {{100.0, 100.0, 100.0, 100.0, 100.0, 100.0}},\n                                {{100.0, 100.0, 100.0, 100.0, 100.0, 100.0}});    \n        robot.setJointImpedance({{3000, 3000, 3000, 2500, 2500, 2000, 2000}});\n        robot.setCartesianImpedance({{3000, 3000, 3000, 300, 300, 300}});\n\n      // Modello cinematico e dinamico del robot\n        franka::Model model = robot.loadModel();\n\n      // Lettura dello stato attuale del robot\n        franka::RobotState initial_state = robot.readOnce();\n      \n        Eigen::Affine3d initial_transform(Eigen::Matrix4d::Map(initial_state.O_T_EE.data()));\n\n      // Estrazione della posizione dalla matrice di trasformazione\n        Eigen::Vector3d position_d(initial_transform.translation());\n\n      // Estrazione dell'orientamento in forma di quaternione a partire dalla matrice di rotazione\n        Eigen::Quaterniond orientation_d(initial_transform.linear());\n\n\n      // Variabile per tenere traccia del tempo trascorso\n\n        double time = 0.0;\n\n      // Definizione della callback per il loop di controllo in coppia:\n        \n        std::function<franka::Torques(const franka::RobotState&, franka::Duration)>\n        impedance_control_callback = [&](const franka::RobotState& robot_state,\n                                          franka::Duration duration) -> franka::Torques {\n\n      \n      // Update time.\n        time += duration.toSec();\n        \n      // Calcolo delle coppie di Coriolis a partire dal modello dinamico e dallo stato del robot\n        std::array<double, 7> coriolis_array = model.coriolis(robot_state);\n\n      // Jacobiano geometrico del manipolatore\n        std::array<double, 42> jacobian_array = \n        model.zeroJacobian(franka::Frame::kEndEffector, robot_state);\n\n      // Conversione a Eigen Map\n        Eigen::Map<const Eigen::Matrix<double, 7, 1>> coriolis(coriolis_array.data());\n        Eigen::Map<const Eigen::Matrix<double, 6, 7>> jacobian(jacobian_array.data());\n        Eigen::Map<const Eigen::Matrix<double, 7, 1>> q(robot_state.q.data());\n        Eigen::Map<const Eigen::Matrix<double, 7, 1>> dq(robot_state.dq.data());\n\n      // Estrazione di posizione e orientamento attuali  \n        Eigen::Affine3d transform(Eigen::Matrix4d::Map(robot_state.O_T_EE.data()));\n        Eigen::Vector3d position(transform.translation());\n        Eigen::Quaterniond orientation(transform.linear());\n        \n      // Calcolo errore in posizione:\n        Eigen::Matrix<double, 6, 1> error;\n        error.head(3) << position - position_d;\n\n      \n      // Calcolo errore in orientamento:\n        if (orientation_d.coeffs().dot(orientation.coeffs()) < 0.0) {\n            orientation.coeffs() << -orientation.coeffs();\n        }\n\n        Eigen::Quaterniond error_quaternion(orientation.inverse() * orientation_d);\n        error.tail(3) << error_quaternion.x(), error_quaternion.y(), error_quaternion.z();\n\n        error.tail(3) << -transform.linear() * error.tail(3);\n\n      // Costruzione delle coppie di controllo\n        Eigen::VectorXd tau_task(7), tau_d(7);\n\n      // L'errore \u00e8 stato definito con il segno opposto quindi serve invertire i segni.\n        tau_task << jacobian.transpose() * (-rigidezza * error - smorzamento * (jacobian * dq));\n        \n        \n      // Salvataggio dello stato del robot attuale\n      \n        sv.tau_measured = (Eigen::Matrix<double, 7, 1>) robot_state.tau_J.data();\n        sv.q = q;\n        sv.qdot = dq;\n        sv.pose = posquat2mat(position,orientation);\n        sv.error = error;\n        \n        \n        \n        \n\n      // Si lanciano due thread che bufferizzano i dati raccolti\n        sv.fill_buffer();\n        \n      // Compensazione delle coppie di Coriolis\n        tau_d << tau_task + coriolis;\n\n        std::array<double, 7> tau_d_array{};\n        Eigen::VectorXd::Map(&tau_d_array[0], 7) = tau_d;\n\n      // Si attende che i thread terminino la scrittura nei buffer\n        sv.wait_filler();\n        \n        if (time >= t_fin) {\n          franka::Torques tau_m = tau_d_array;\n          std::cout << std::endl << \"Fine controllo di impedenza\" << std::endl;\n          return franka::MotionFinished(tau_m);\n        }      \n        return tau_d_array;\n\n        };\n\n      \n      // Start del loop di controllo real-time\n        robot.control(impedance_control_callback);\n\n\n      // Scrittura su file\n         sv.scrivi_su_file(ncampioni);\n\n      // Free memory\n        for(int i = 0; i< ncampioni*7; i++)\n            delete[] StateSaver::buffer_7[i];\n        delete[] StateSaver::buffer_7;\n\n        for(int i = 0; i< ncampioni*6; i++)\n            delete[] StateSaver::buffer_6[i];\n        delete[] StateSaver::buffer_6;\n\n      } catch (const franka::Exception& ex) {\n          // print exception\n          std::cout << ex.what() << std::endl;\n      }\n\n\n      \n\n\n      return 0;\n}\n", "meta": {"hexsha": "640e14f5daaced540fe40fd5b06b74fe41e7eed4", "size": 9411, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CustomPrograms/Cartesian_Impedance_Control.cpp", "max_stars_repo_name": "Vanvitelli-Robotics/libfranka_demo", "max_stars_repo_head_hexsha": "0776e0630aed3a2e2d1bfe63ce53d86e07f19711", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CustomPrograms/Cartesian_Impedance_Control.cpp", "max_issues_repo_name": "Vanvitelli-Robotics/libfranka_demo", "max_issues_repo_head_hexsha": "0776e0630aed3a2e2d1bfe63ce53d86e07f19711", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CustomPrograms/Cartesian_Impedance_Control.cpp", "max_forks_repo_name": "Vanvitelli-Robotics/libfranka_demo", "max_forks_repo_head_hexsha": "0776e0630aed3a2e2d1bfe63ce53d86e07f19711", "max_forks_repo_licenses": ["Apache-2.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.2471910112, "max_line_length": 133, "alphanum_fraction": 0.6357454043, "num_tokens": 2669, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.4669235461629065}}
{"text": "//==================================================================================================\n/*\n  Copyright 2017 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//! [significants]\n#include <boost/simd/exponential.hpp>\n#include <boost/simd/pack.hpp>\n#include <iostream>\n\nnamespace bs = boost::simd;\nusing iT = std::int32_t;\nusing pack_it = bs::pack<iT, 4>;\nusing pack_ft = bs::pack<float, 4>;\n\nint main() {\n  pack_ft pf(1234.567f);\n  pack_it qi = {1, 2, 3, 4};\n\n  std::cout << \"---- simd\" << '\\n'\n            << \"<- pf =                       \" << pf << '\\n'\n            << \"<- qi =                       \" << qi << '\\n'\n            << \"-> bs::significants(pf, qi) = \" << bs::significants(pf, qi)\n            << '\\n';\n\n  float xf = 2.345678f;\n  iT yi = 3;\n\n  std::cout << \"---- scalar\" << '\\n'\n            << \"<- xf =                       \" << xf << '\\n'\n            << \"<- yi =                       \" << yi << '\\n'\n            << \"-> bs::significants(xf, yi) = \" << bs::significants(xf, yi)\n            << '\\n';\n  return 0;\n}\n//! [significants]\n", "meta": {"hexsha": "a2aa43bb20848988d7fb39eb34772537bea2fcd5", "size": 1267, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/doc/exponential/significants.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": "test/doc/exponential/significants.cpp", "max_issues_repo_name": "remymuller/boost.simd", "max_issues_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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/doc/exponential/significants.cpp", "max_forks_repo_name": "remymuller/boost.simd", "max_forks_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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": 31.675, "max_line_length": 100, "alphanum_fraction": 0.3883188635, "num_tokens": 325, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286833, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.46692354616290643}}
{"text": "#include \"fileread.hpp\"\n#include \"pairwiseICP.hpp\"\n#include \"pointCloudDeal.hpp\"\n#include \"viz.hpp\"\n#include \"loopdetect.hpp\"\n//#include \"types.hpp\"\n#include <boost/graph/graph_concepts.hpp>\n#include<Eigen/Dense>\n\nusing namespace std;\n\nostream& operator<<(ostream& out, const Eigen::Quaternion<float>& s)\n{\n  out<<s.x()<<\" \"<<s.y()<<\" \"<<s.z()<<\" \"<<s.w();\n  return out;\n}\n\nostream& operator<<(ostream& out, const Eigen::Vector3f & s)\n{\n  for(int i=0;i<s.rows();i++)\n  {\n    if(i<s.rows()-1)\n    {\n    out<<s(i)<<\" \";\n    }\n    else{\n     out<<s(i);\n    }\n  }\n  return out;\n}\n\n\nint main(int argc, char**argv)\n{\n  string dir=\"/home/shaoan/projects/SLAM6D/dat_et4/\";\n  const int maxnumFile=15;\n  vector<Eigen::Vector3f> historyTrans;\n  vector<Eigen::Matrix3f> historyRotations;\n\n  Eigen::Matrix3f R_current;\n  Eigen::Vector3f t_current;\n  vector<pcl::PointCloud<pcl::PointXYZ>::Ptr> historyPointCloudPtr;\n  vector<map3d::vertix<map3d::pose> > initialVertix;\n  vector<map3d::edge<map3d::pose> >  edges;\n  for(int nfile=0;nfile<maxnumFile;nfile++)\n  {\n    pcl::PointCloud<pcl::PointXYZ>::Ptr currentPointCloud(new pcl::PointCloud<pcl::PointXYZ>);\n    map3d::readfile(dir.c_str(),nfile,currentPointCloud,R_current,t_current);\n    \n    //store the VERTEX_SE3\n    map3d::pose tempose;\n    tempose.q=R_current;\n    tempose.t=t_current;\n    map3d::vertix<map3d::pose>  temVertix;\n    temVertix.Header=\"VERTEX_SE3:QUAT\";\n    temVertix.pose_ID=nfile;\n    temVertix.initialPose=tempose;\n    initialVertix.push_back(temVertix);\n    //store the indexes of PointCloud\n    historyPointCloudPtr.push_back(currentPointCloud);\n    \n    //if number of file bigger than 1, examine whether a edge can be detected from history trace. \n    vector<int> indexes;\n     map3d::backend::Loop loop(300);  \n    if(nfile>0)\n    {\n      if(loop.flagLoop(historyTrans,t_current))\n      {\n\tcout<<\"label 1\";\n\tloop.getLoopIndex(indexes);\n      for(int i=0;i<indexes.size();i++)\n      {\n\tmap3d::edge<map3d::pose> temedge;\n\tEigen::Matrix3f R_delta=R_current.transpose()*historyRotations[indexes[i]];\n\tEigen::Vector3f t_delta=R_current.transpose()*(historyTrans[indexes[i]]-t_current);\n\t//cout<<\" label 2\";\n\tmap3d::ICP pairwiseicp(500,1010,10,25);\n\tpairwiseicp.setInputCloud(historyPointCloudPtr[indexes[i]],currentPointCloud);\n        pairwiseicp.setParamsConvergence();\n\tpairwiseicp.solve(R_delta,t_delta);\n\t//cout<<\" label 3\";\n      //If a edge is added, we need to compute related InformationMatrix and store it.\n        if(pairwiseicp.flag==true)\n\t{\n\t  map3d::pose tempose;\n\t  tempose.q=R_delta;\n\t  tempose.t=t_delta;\n\t  Eigen::Matrix<float,6,6> InformationMatrix;\n\t  //cout<<\"label 5\";\n\t  pairwiseicp.getInformationMatrix(InformationMatrix);\n\t // cout<<\" label 4\";\n\t  temedge.a_ID=nfile;\n\t  temedge.b_ID=indexes[i];\n\t  temedge.Header=\"EDGE_SE3:QUAT\";\n\t  temedge.pose_ab=tempose;\n\t  temedge.informationMatrix_ab=InformationMatrix;\n\t  edges.push_back(temedge);\n\t}\n       }\n      }\n    }    \n     historyTrans.push_back(t_current); \n     historyRotations.push_back(R_current);\n  }\n  \n  \n     ofstream file;\n     //ios_base::out is same as ios_base::trunc.Open the file for output. if the file existed, it will be discarded.\n     file.open(\"indoor.g2o\",ios_base::out);\n     if(file.good())\n     {\n       for(int i=0;i<initialVertix.size();i++)\n       {\n\t file<<initialVertix[i].Header<<\" \"<<initialVertix[i].pose_ID<<\" \"<< initialVertix[i].initialPose.t<<\" \"<<initialVertix[i].initialPose.q<<endl;\n\t}\n\tfor(int i=0;i<edges.size();i++)\n\t{\n\t  file<<edges[i].Header<<\" \"<<edges[i].a_ID<<\" \"<<edges[i].b_ID;\n\t  file<<\" \"<<edges[i].pose_ab.t<<\" \"<<edges[i].pose_ab.q<<\" \";\n\t  for(int k=0;k<6;k++)\n\t  {\n\t    for(int l=k;l<6;l++)\n\t    {\n\t      file<<edges[i].informationMatrix_ab(k,l)<<\" \";\n\t    }\n\t  }\n\t  file<<endl;\n\t}\n    }\n    \n\n}", "meta": {"hexsha": "08897f6a65fbb92df9c0f7f15f1d2156d47a7c2d", "size": 3788, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "posegraph.cpp", "max_stars_repo_name": "zoumaguanxin/3DMapping", "max_stars_repo_head_hexsha": "ca85508c5c0740100d04b66f01e76bba525faa20", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-02-06T09:08:05.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-06T09:08:05.000Z", "max_issues_repo_path": "posegraph.cpp", "max_issues_repo_name": "zoumaguanxin/3DMapping", "max_issues_repo_head_hexsha": "ca85508c5c0740100d04b66f01e76bba525faa20", "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": "posegraph.cpp", "max_forks_repo_name": "zoumaguanxin/3DMapping", "max_forks_repo_head_hexsha": "ca85508c5c0740100d04b66f01e76bba525faa20", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4812030075, "max_line_length": 144, "alphanum_fraction": 0.6583949314, "num_tokens": 1101, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.4668972977301806}}
{"text": "#include <cmath>\n#include <functional>\n#include <iostream>\n\n#include <Eigen/Dense>\n\n#include <franka/duration.h>\n#include <franka/exception.h>\n#include <franka/model.h>\n#include <franka/robot.h>\n\n#include <plug_in_controller.h>\n\nnamespace plug_in_controller {\n\nvoid run(const std::string& robot_ip,\n         const Parameters plug_in_params,\n         const double duration,  // in seconds\n         const std::array<double, 3> target_position_array,\n         const std::array<double, 3> target_tolerance_array) {\n  // Parameters for stopping criterion\n  Eigen::Vector3d target_position(Eigen::Vector3d::Map(target_position_array.data()));\n  Eigen::Vector3d target_tolerance(Eigen::Vector3d::Map(target_tolerance_array.data()));\n\n  // Compliance parameters\n  Eigen::MatrixXd cartesian_stiffness(6, 6), cartesian_damping(6, 6);\n  cartesian_stiffness.setZero();\n  cartesian_stiffness.topLeftCorner(3, 3)\n      << plug_in_params.translational_stiffness * Eigen::MatrixXd::Identity(3, 3);\n  cartesian_stiffness.bottomRightCorner(3, 3)\n      << plug_in_params.rotational_stiffness * Eigen::MatrixXd::Identity(3, 3);\n  cartesian_damping.setZero();\n  cartesian_damping.topLeftCorner(3, 3)\n      << 2.0 * sqrt(plug_in_params.translational_stiffness) * Eigen::MatrixXd::Identity(3, 3);\n  cartesian_damping.bottomRightCorner(3, 3)\n      << 2.0 * sqrt(plug_in_params.rotational_stiffness) * Eigen::MatrixXd::Identity(3, 3);\n\n  // Force parameters\n  Eigen::VectorXd force_error_integral(6);\n  // force control P, I gain\n  double k_p{0.0};\n  double k_i{1.0};\n\n  franka::Robot robot(robot_ip);\n  // load the kinematics and dynamics model\n  franka::Model model = robot.loadModel();\n\n  // initial robot state\n  franka::RobotState initial_state = robot.readOnce();\n  Eigen::Map<Eigen::Matrix<double, 6, 1>> force_initial(initial_state.O_F_ext_hat_K.data());\n  force_error_integral.setZero();\n\n  // equilibrium point is the initial position\n  Eigen::Affine3d initial_transform(Eigen::Matrix4d::Map(initial_state.O_T_EE.data()));\n  Eigen::Vector3d position_d(initial_transform.translation());\n  Eigen::Quaterniond orientation_initial(initial_transform.linear());\n\n  double time = 0.0;\n\n  // define callback for the torque control loop\n  std::function<franka::Torques(const franka::RobotState&, franka::Duration)>\n      plug_in_control_callback =\n          [&](const franka::RobotState& robot_state, franka::Duration period) -> franka::Torques {\n    time += period.toSec();\n\n    // get state variables\n    std::array<double, 7> coriolis_array = model.coriolis(robot_state);\n    std::array<double, 42> jacobian_array =\n        model.zeroJacobian(franka::Frame::kEndEffector, robot_state);\n\n    // convert to Eigen\n    Eigen::Map<const Eigen::Matrix<double, 7, 1>> coriolis(coriolis_array.data());\n    Eigen::Map<const Eigen::Matrix<double, 6, 7>> jacobian(jacobian_array.data());\n    Eigen::Map<const Eigen::Matrix<double, 6, 1>> force(robot_state.O_F_ext_hat_K.data());\n    Eigen::Map<const Eigen::Matrix<double, 7, 1>> dq(robot_state.dq.data());\n    Eigen::Affine3d transform(Eigen::Matrix4d::Map(robot_state.O_T_EE.data()));\n    Eigen::Vector3d position(transform.translation());\n    Eigen::Quaterniond orientation(transform.linear());\n\n    // Compute desired orientation of equilibrium pose and desired forces\n    // wiggle motion\n    Eigen::AngleAxisd angle_axis_wiggle_x;\n    angle_axis_wiggle_x.axis() << 1, 0, 0;\n    angle_axis_wiggle_x.angle() = sin(2.0 * M_PI * time * plug_in_params.wiggle_frequency_x) *\n                                  plug_in_params.wiggle_amplitude_x;\n    Eigen::AngleAxisd angle_axis_wiggle_y;\n    angle_axis_wiggle_y.axis() << 0, 1, 0;\n    angle_axis_wiggle_y.angle() = sin(2.0 * M_PI * time * plug_in_params.wiggle_frequency_y) *\n                                  plug_in_params.wiggle_amplitude_y;\n    Eigen::Quaterniond wiggle_x(angle_axis_wiggle_x);\n    Eigen::Quaterniond wiggle_y(angle_axis_wiggle_y);\n    Eigen::Quaterniond orientation_d(wiggle_y * (wiggle_x * orientation_initial));\n\n    // desired forces\n    Eigen::VectorXd desired_force(6);\n    desired_force.setZero();\n    desired_force(2) = -plug_in_params.desired_force;\n\n    // Compute error to desired equilibrium pose\n    // position error\n    Eigen::Matrix<double, 6, 1> error;\n    error.head(3) << position - position_d;\n\n    // orientation error\n    if (orientation_d.coeffs().dot(orientation.coeffs()) < 0.0) {\n      orientation.coeffs() << -orientation.coeffs();\n    }\n    // \"difference\" quaternion\n    Eigen::Quaterniond error_quaternion(orientation.inverse() * orientation_d);\n    error.tail(3) << error_quaternion.x(), error_quaternion.y(), error_quaternion.z();\n    // Transform to base frame\n    error.tail(3) << -transform.linear() * error.tail(3);\n\n    // Compute error to desired force removing initial bias\n    Eigen::VectorXd force_error;\n    force_error = desired_force - force + force_initial;\n    force_error_integral = force_error_integral + period.toSec() * force_error;\n\n    // Compute control\n    Eigen::VectorXd force_control(6), tau_force(7), tau_cart(7), tau_cmd(7);\n\n    // Force control term\n    force_control = desired_force + k_p * force_error + k_i * force_error_integral;\n    force_control << 0, 0, force_control(2), 0, 0, 0;\n    tau_force = jacobian.transpose() * force_control;\n\n    // Cartesian control term\n    tau_cart << jacobian.transpose() *\n                    (-cartesian_stiffness * error - cartesian_damping * (jacobian * dq));\n\n    // Commanded torque\n    tau_cmd << tau_cart + tau_force + coriolis;\n\n    std::array<double, 7> tau_d_array{};\n    Eigen::VectorXd::Map(&tau_d_array[0], 7) = tau_cmd;\n\n    // check if motion is completed\n    Eigen::Matrix<double, 3, 1> target_error((target_position - position).cwiseAbs());\n    bool is_inserted =\n        (target_error[0] <= target_tolerance[0] && target_error[1] <= target_tolerance[1] &&\n         target_error[2] <= target_tolerance[2]);\n    if (time <= duration && is_inserted) {\n      return franka::MotionFinished(franka::Torques(tau_d_array));\n    }\n    if (time > duration) {\n      throw franka::Exception(\"Timeout: Plug in controller failed!\");\n    }\n    return tau_d_array;\n  };\n\n  robot.control(plug_in_control_callback);\n}\n\n}  // namespace plug_in_controller\n", "meta": {"hexsha": "3135b58971e9a1bdc4f447b1c94ef13368ded1cf", "size": 6241, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3_FCI/standalone/src/plug_in_controller.cpp", "max_stars_repo_name": "frankaemika/air_tutorial", "max_stars_repo_head_hexsha": "97427e535ac1a3997289686ed844c3d9fc9d1001", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2021-07-26T09:32:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T10:51:05.000Z", "max_issues_repo_path": "3_FCI/standalone/src/plug_in_controller.cpp", "max_issues_repo_name": "frankaemika/air_tutorial", "max_issues_repo_head_hexsha": "97427e535ac1a3997289686ed844c3d9fc9d1001", "max_issues_repo_licenses": ["Apache-2.0"], "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_FCI/standalone/src/plug_in_controller.cpp", "max_forks_repo_name": "frankaemika/air_tutorial", "max_forks_repo_head_hexsha": "97427e535ac1a3997289686ed844c3d9fc9d1001", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-11-15T02:39:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T12:42:06.000Z", "avg_line_length": 40.264516129, "max_line_length": 98, "alphanum_fraction": 0.7022912995, "num_tokens": 1618, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.4668972977301806}}
{"text": "#include <stan/math/rev.hpp>\n#include <gtest/gtest.h>\n#include <boost/numeric/odeint.hpp>\n#include <test/unit/math/rev/functor/util_rk45.hpp>\n#include <test/unit/math/prim/functor/harmonic_oscillator.hpp>\n#include <test/unit/math/prim/functor/forced_harmonic_oscillator.hpp>\n#include <test/unit/math/prim/functor/lorenz.hpp>\n#include <iostream>\n#include <sstream>\n#include <vector>\n\ntemplate <typename F, typename T_y0, typename T_theta>\nvoid sho_value_test(F harm_osc, std::vector<double>& y0, double t0,\n                    std::vector<double>& ts, std::vector<double>& theta,\n                    std::vector<double>& x, std::vector<int>& x_int) {\n  using stan::math::promote_scalar;\n  using stan::math::var;\n\n  std::vector<std::vector<var>> ode_res_vd = stan::math::integrate_ode_rk45(\n      harm_osc, promote_scalar<T_y0>(y0), t0, ts,\n      promote_scalar<T_theta>(theta), x, x_int, 0);\n  EXPECT_NEAR(0.995029, ode_res_vd[0][0].val(), 1e-5);\n  EXPECT_NEAR(-0.0990884, ode_res_vd[0][1].val(), 1e-5);\n\n  EXPECT_NEAR(-0.421907, ode_res_vd[99][0].val(), 1e-5);\n  EXPECT_NEAR(0.246407, ode_res_vd[99][1].val(), 1e-5);\n}\n\nvoid sho_finite_diff_test(double t0) {\n  using stan::math::var;\n  harm_osc_ode_fun harm_osc;\n\n  std::vector<double> theta;\n  theta.push_back(0.15);\n\n  std::vector<double> y0;\n  y0.push_back(1.0);\n  y0.push_back(0.0);\n\n  std::vector<double> ts;\n  for (int i = 0; i < 100; i++)\n    ts.push_back(t0 + 0.1 * (i + 1));\n\n  std::vector<double> x;\n  std::vector<int> x_int;\n\n  test_ode(harm_osc, t0, ts, y0, theta, x, x_int, 1e-8, 1e-4);\n\n  sho_value_test<harm_osc_ode_fun, double, var>(harm_osc, y0, t0, ts, theta, x,\n                                                x_int);\n  sho_value_test<harm_osc_ode_fun, var, double>(harm_osc, y0, t0, ts, theta, x,\n                                                x_int);\n  sho_value_test<harm_osc_ode_fun, var, var>(harm_osc, y0, t0, ts, theta, x,\n                                             x_int);\n}\n\nvoid sho_data_finite_diff_test(double t0) {\n  using stan::math::var;\n  harm_osc_ode_data_fun harm_osc;\n\n  std::vector<double> theta;\n  theta.push_back(0.15);\n\n  std::vector<double> y0;\n  y0.push_back(1.0);\n  y0.push_back(0.0);\n\n  std::vector<double> ts;\n  for (int i = 0; i < 100; i++)\n    ts.push_back(t0 + 0.1 * (i + 1));\n\n  std::vector<double> x(3, 1);\n  std::vector<int> x_int(2, 0);\n\n  test_ode(harm_osc, t0, ts, y0, theta, x, x_int, 1e-8, 1e-4);\n\n  sho_value_test<harm_osc_ode_data_fun, double, var>(harm_osc, y0, t0, ts,\n                                                     theta, x, x_int);\n  sho_value_test<harm_osc_ode_data_fun, var, double>(harm_osc, y0, t0, ts,\n                                                     theta, x, x_int);\n  sho_value_test<harm_osc_ode_data_fun, var, var>(harm_osc, y0, t0, ts, theta,\n                                                  x, x_int);\n}\n\nTEST(StanAgradRevOde_integrate_ode_rk45, harmonic_oscillator_finite_diff) {\n  sho_finite_diff_test(0);\n  sho_finite_diff_test(1.0);\n  sho_finite_diff_test(-1.0);\n\n  sho_data_finite_diff_test(0);\n  sho_data_finite_diff_test(1.0);\n  sho_data_finite_diff_test(-1.0);\n}\n\nTEST(StanAgradRevOde_integrate_ode_rk45, lorenz_finite_diff) {\n  lorenz_ode_fun lorenz;\n\n  std::vector<double> y0;\n  std::vector<double> theta;\n  double t0;\n  std::vector<double> ts;\n\n  t0 = 0;\n\n  theta.push_back(10.0);\n  theta.push_back(28.0);\n  theta.push_back(8.0 / 3.0);\n  y0.push_back(10.0);\n  y0.push_back(1.0);\n  y0.push_back(1.0);\n\n  std::vector<double> x;\n  std::vector<int> x_int;\n\n  for (int i = 0; i < 100; i++)\n    ts.push_back(0.1 * (i + 1));\n\n  test_ode(lorenz, t0, ts, y0, theta, x, x_int, 1e-8, 1e-1);\n}\n\nTEST(StanAgradRevOde_integrate_ode_rk45, time_steps_as_param) {\n  using stan::math::integrate_ode_rk45;\n  using stan::math::to_var;\n  using stan::math::value_of;\n\n  const double t0 = 0.0;\n  forced_harm_osc_ode_fun ode;\n  std::vector<double> theta{0.15, 0.25};\n  std::vector<double> y0{1.0, 0.0};\n  std::vector<stan::math::var> ts;\n  for (int i = 0; i < 100; i++)\n    ts.push_back(t0 + 0.1 * (i + 1));\n  std::vector<double> x;\n  std::vector<int> x_int;\n  std::vector<stan::math::var> y0v = to_var(y0);\n  std::vector<stan::math::var> thetav = to_var(theta);\n  stan::math::var t0v = 0.0;\n\n  std::vector<std::vector<stan::math::var>> res;\n\n  std::vector<std::vector<double>> res_d\n      = integrate_ode_rk45(ode, y0, t0, value_of(ts), theta, x, x_int);\n\n  // here we only test first & last steps, and rely on the\n  // fact that results in-between affect the initial\n  // condition of the last step to check their validity.\n  auto test_val = [&res_d, &res]() {\n    EXPECT_NEAR(res_d[0][0], res[0][0].val(), 1e-5);\n    EXPECT_NEAR(res_d[0][1], res[0][1].val(), 1e-5);\n    EXPECT_NEAR(res_d[99][0], res[99][0].val(), 1e-5);\n    EXPECT_NEAR(res_d[99][1], res[99][1].val(), 1e-5);\n  };\n  res = integrate_ode_rk45(ode, y0, t0, ts, theta, x, x_int);\n  test_val();\n  res = integrate_ode_rk45(ode, y0v, t0, ts, theta, x, x_int);\n  test_val();\n  res = integrate_ode_rk45(ode, y0, t0, ts, thetav, x, x_int);\n  test_val();\n  res = integrate_ode_rk45(ode, y0v, t0, ts, thetav, x, x_int);\n  test_val();\n  res = integrate_ode_rk45(ode, y0, t0v, ts, theta, x, x_int);\n  test_val();\n  res = integrate_ode_rk45(ode, y0v, t0v, ts, theta, x, x_int);\n  test_val();\n  res = integrate_ode_rk45(ode, y0, t0v, ts, thetav, x, x_int);\n  test_val();\n  res = integrate_ode_rk45(ode, y0v, t0v, ts, thetav, x, x_int);\n  test_val();\n}\n\nTEST(StanAgradRevOde_integrate_ode_rk45, time_steps_as_param_AD) {\n  using stan::math::integrate_ode_rk45;\n  using stan::math::to_var;\n  using stan::math::value_of;\n  using stan::math::var;\n  const double t0 = 0.0;\n  const int nt = 100;  // nb. of time steps\n  const int ns = 2;    // nb. of states\n  std::ostream* msgs = NULL;\n\n  forced_harm_osc_ode_fun ode;\n\n  std::vector<double> theta{0.15, 0.25};\n  std::vector<double> y0{1.0, 0.0};\n  std::vector<stan::math::var> ts;\n  for (int i = 0; i < nt; i++)\n    ts.push_back(t0 + 0.1 * (i + 1));\n\n  std::vector<double> x;\n  std::vector<int> x_int;\n  std::vector<stan::math::var> y0v = to_var(y0);\n  std::vector<stan::math::var> thetav = to_var(theta);\n  stan::math::var t0v = 0.0;\n\n  std::vector<std::vector<stan::math::var>> res;\n  std::vector<double> g;\n  auto test_ad = [&res, &g, &ts, &ode, &nt, &ns, &theta, &x, &x_int, &msgs]() {\n    for (auto i = 0; i < nt; ++i) {\n      std::vector<double> res_d = value_of(res[i]);\n      for (auto j = 0; j < ns; ++j) {\n        g.clear();\n        res[i][j].grad(ts, g);\n        for (auto k = 0; k < nt; ++k) {\n          if (k != i) {\n            EXPECT_FLOAT_EQ(g[k], 0.0);\n          } else {\n            std::vector<double> y0(res_d.begin(), res_d.begin() + ns);\n            EXPECT_FLOAT_EQ(g[k],\n                            ode(ts[i].val(), y0, theta, x, x_int, msgs)[j]);\n          }\n        }\n        stan::math::set_zero_all_adjoints();\n      }\n    }\n  };\n  res = integrate_ode_rk45(ode, y0, t0, ts, theta, x, x_int);\n  test_ad();\n  res = integrate_ode_rk45(ode, y0v, t0, ts, theta, x, x_int);\n  test_ad();\n  res = integrate_ode_rk45(ode, y0, t0, ts, thetav, x, x_int);\n  test_ad();\n  res = integrate_ode_rk45(ode, y0v, t0, ts, thetav, x, x_int);\n  test_ad();\n}\n\nTEST(StanAgradRevOde_integrate_ode_rk45, t0_as_param_AD) {\n  using stan::math::integrate_ode_rk45;\n  using stan::math::to_var;\n  using stan::math::value_of;\n  using stan::math::var;\n  const double t0 = 0.0;\n  std::ostream* msgs = NULL;\n\n  harm_osc_ode_fun ode;\n\n  std::vector<double> theta{0.15};\n  std::vector<double> y0{1.0, 0.0};\n  std::vector<double> ts = {5.0, 10.0};\n\n  std::vector<double> x;\n  std::vector<int> x_int;\n  std::vector<stan::math::var> y0v = to_var(y0);\n  std::vector<stan::math::var> thetav = to_var(theta);\n  stan::math::var t0v = to_var(t0);\n\n  std::vector<std::vector<stan::math::var>> res;\n  auto test_ad = [&res, &t0v, &ode, &theta, &x, &x_int, &msgs]() {\n    res[0][0].grad();\n    EXPECT_FLOAT_EQ(t0v.adj(), -0.66360742442816977871);\n    stan::math::set_zero_all_adjoints();\n    res[0][1].grad();\n    EXPECT_FLOAT_EQ(t0v.adj(), 0.23542843380353062344);\n    stan::math::set_zero_all_adjoints();\n    res[1][0].grad();\n    EXPECT_FLOAT_EQ(t0v.adj(), -0.2464078910913158893);\n    stan::math::set_zero_all_adjoints();\n    res[1][1].grad();\n    EXPECT_FLOAT_EQ(t0v.adj(), -0.38494826636037426937);\n    stan::math::set_zero_all_adjoints();\n  };\n  res = integrate_ode_rk45(ode, y0, t0v, ts, theta, x, x_int, nullptr, 1e-10,\n                           1e-10, 1e6);\n  test_ad();\n  res = integrate_ode_rk45(ode, y0v, t0v, ts, theta, x, x_int, nullptr, 1e-10,\n                           1e-10, 1e6);\n  test_ad();\n  res = integrate_ode_rk45(ode, y0, t0v, ts, thetav, x, x_int, nullptr, 1e-10,\n                           1e-10, 1e6);\n  test_ad();\n  res = integrate_ode_rk45(ode, y0v, t0v, ts, thetav, x, x_int, nullptr, 1e-10,\n                           1e-10, 1e6);\n  test_ad();\n}\n", "meta": {"hexsha": "1847bc7bb8d2a637987b393b2b754d19c54e63bd", "size": 8884, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/rev/functor/integrate_ode_rk45_rev_test.cpp", "max_stars_repo_name": "bayesmix-dev/math", "max_stars_repo_head_hexsha": "3616f7195adc95ef8e719a2af845d61102bc9272", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-14T14:33:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-14T14:33:37.000Z", "max_issues_repo_path": "test/unit/math/rev/functor/integrate_ode_rk45_rev_test.cpp", "max_issues_repo_name": "bayesmix-dev/math", "max_issues_repo_head_hexsha": "3616f7195adc95ef8e719a2af845d61102bc9272", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/unit/math/rev/functor/integrate_ode_rk45_rev_test.cpp", "max_forks_repo_name": "bayesmix-dev/math", "max_forks_repo_head_hexsha": "3616f7195adc95ef8e719a2af845d61102bc9272", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-05-10T12:55:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-10T12:55:07.000Z", "avg_line_length": 32.4233576642, "max_line_length": 79, "alphanum_fraction": 0.6131247186, "num_tokens": 3224, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795402, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.46688741562420216}}
{"text": "#ifndef PRECONDITIONED_CONJUGATE_GRADIENT_H\n#define PRECONDITIONED_CONJUGATE_GRADIENT_H\n#include <Eigen/Dense>\n#include <mtao/logging/timer.hpp>\n#include <iostream>\n\n\ntemplate <typename Matrix>\nstruct DenseLDLT\n{\n    typedef typename Matrix::Scalar Scalar;\n    template <typename A, typename B, typename C>\n    inline Scalar tripleVectorProduct(const A & a, const B & b, const C & c) const {\n        return a.cwiseProduct(b).dot(c);\n    }\n    inline Scalar tripleProduct(const Matrix & a, uint i, uint j) const\n    {\n        return tripleVectorProduct(a.row(i).head(j),a.row(j).head(j),a.diagonal().head(j));\n    }\n    DenseLDLT(const Matrix & A)\n    {\n        LD=A.template triangularView<Eigen::Lower>();\n        int i,j;\n        for(i=0; i<A.rows(); ++i)\n        {\n            for(j=0; j<i; ++j)\n                if(std::abs(LD(j,j))>0.0001)\n                {\n                    LD(i,j)-=tripleProduct(LD,i,j);\n                    LD(i,j)/=LD(j,j);\n                }\n                else\n                {\n                    LD(i,j)=0;\n                }\n            LD(i,i) -= tripleProduct(LD,i,i);\n        }\n\n    }\n    template <typename Vector>\n    void solve(const Vector & b, Vector & x) const\n    {\n        x = LD.template triangularView<Eigen::UnitLower>().solve(b);\n        x.noalias() = x.cwiseQuotient(LD.diagonal());//safe beacuse it's a dot\n        LD.template triangularView<Eigen::UnitLower>().transpose().solveInPlace(x);\n    }\n    Matrix getA() const\n    {\n        Matrix A = LD.template triangularView<Eigen::UnitLower>().transpose();\n        A = LD.diagonal().asDiagonal() * A;\n        A = LD.template triangularView<Eigen::UnitLower>() * A;\n\n        return A;\n    }\nprivate:\n    Matrix LD;\n};\n\n\n\n\n\ntemplate <typename Matrix, typename Vector>\nstruct SparseLDLT\n{\n    typedef typename Matrix::Scalar Scalar;\n    SparseLDLT() {}\n    SparseLDLT(const Matrix & A)\n    {\n        // L=tril(A);\n        L=A.template triangularView<Eigen::StrictlyLower>();//Don't copy the diagonal\n        for(int i=0; i<L.rows(); ++i)\n        {\n            if(L.coeff(i,i)!=0)\n                L.coeffRef(i,i)=0;\n        }\n        Dinv=D=A.diagonal();\n\n\n\n        // for k=1:size(L,2)\n        for(int k=0; k<A.rows(); ++k)//k is the column that we're infecting the remaining columns with\n        {//L(:,k)\n\n\n\n            //Solidify the current column values\n            //==================================\n            if(D(k)==0) continue;\n            if(Dinv(k)<0.25*D(k))//If D has shrunk too much since it started\n                Dinv(k)=1/D(k);\n            else\n                Dinv(k)=1/Dinv(k);\n            L.innerVector(k) *= Dinv(k);\n\n            //Add k terms to all of the following columns\n            //===========================================\n            for(typename Matrix::InnerIterator it(L,k); it; ++it)// -L(i,k)*D(k)*L(j,k)\n            {\n                int j = it.row();//j>k\n                if(j<=k) continue;\n                Scalar missing=0;\n                Scalar multiplier=it.value();//L(j,k)*D(k)\n\n                typename Matrix::InnerIterator k_it(L,k);\n                typename Matrix::InnerIterator j_it(L,j);\n                //move down teh column of L(:,k) to collect missing elements in the match with A(:,j)\n                //i=k_it.row()\n\n                while (k_it && k_it.row()<j){//L(i,k)\n                    while(j_it)//L(i,j) occasionally\n                    {\n                        if(j_it.row() < k_it.row())\n                            ++j_it;\n                        else if(j_it.row() == k_it.row())//L(i,k) are L(i,j) are nonzero\n                            break;\n                        else\n                        {\n                            missing += k_it.value();//L(i,k) will fill something not in L(i,j)\n                            break;\n                        }\n                    }\n                    ++k_it;\n                }\n\n\n                if(k_it && j_it.row() == j)\n                {\n                    Dinv(j) -= it.value() * multiplier;\n                }\n\n\n                typename Matrix::InnerIterator j_it2(L,j);\n                while(k_it && j_it2)\n                {\n                    if(j_it2.row() < k_it.row())\n                        ++j_it2;\n                    else if(j_it2.row() == k_it.row())//L(i,k) and L(i,j) are both nonzero, -=L(i,k)*L(j,k)*D(k)\n                    {\n                        j_it2.valueRef() -= multiplier * k_it.value() ;//k_it.value()=L(i,k)\n                        ++j_it2;\n                        ++k_it;\n                    }\n                    else\n                    {\n                        missing+=k_it.value();\n                        ++k_it;\n                    }\n                }\n\n                while(k_it)\n                {\n                    missing+=k_it.value();\n                    ++k_it;\n                }\n                Dinv(j)-=0.97*missing*multiplier;\n            }\n        }\n\n        /*\n           std::cout << L << std::endl;\n           */\n\n    }\n    void solve(const Vector & b, Vector & x) const\n    {\n        x = L.template triangularView<Eigen::UnitLower>().solve(b);\n        x.noalias() = x.cwiseProduct(Dinv);//safe beacuse it's a dot\n        L.transpose().template triangularView<Eigen::UnitUpper>().solveInPlace(x);\n    }\n    Matrix getA()\n    {\n        Matrix\n                A = L.template triangularView<Eigen::UnitLower>();\n        A = A * D.asDiagonal();\n        A = A * L.template triangularView<Eigen::UnitLower>().transpose();\n\n        return A;\n    }\nprivate:\n    Matrix L;\n    Vector D,Dinv;\n};\n\ntemplate <typename MatrixType, typename VectorType, typename Preconditioner>\nstruct PreconditionedConjugateGradient\n{\n    typedef MatrixType Matrix;\n    typedef VectorType Vector;\n    typedef typename Vector::Scalar Scalar;\n    PreconditionedConjugateGradient(const Matrix & A): A(A)\n    {\n        mtao::logging::timer(\"Preconditioner\",false);\n        precond = Preconditioner(A);\n    }\n    PreconditionedConjugateGradient(PreconditionedConjugateGradient&&) = default;\n    auto solve(const Vector& b) const {\n        mtao::logging::timer(\"Solve\",false);\n        auto x = b.eval();\n        x.setZero();\n        Vector r = b-A*x;\n        Vector z;\n        precond.solve(r,z);\n        Vector p = z;\n        Vector Ap = A*p;\n        Scalar rdz = r.dot(z);\n        Scalar alpha, beta;\n        auto error = [&]() { return r.template lpNorm<Eigen::Infinity>(); };\n\n        uint iterations = 0;\n        Scalar eps = error() * epsilon;\n        while(++iterations < 10 &&\n        //while(++iterations < b.rows() &&\n                error() > eps)\n        {\n            alpha = (rdz)/(p.dot(Ap));\n            x+=alpha * p;\n            r-=alpha * Ap;\n            precond.solve(r,z);\n            beta=1/rdz;\n            rdz = r.dot(z);\n            beta*=rdz;\n            p=z+beta*p;\n            Ap=A*p;\n        }\n        return x;\n    }\n    Scalar error()\n    {\n    }\nprivate:\n    const Matrix A;\n    Preconditioner precond;\n\n    Scalar epsilon = 1e-5;\n\n};\n\ntemplate <typename Matrix, typename Vector>\nauto ldlt_pcg_solver(const Matrix & A, const Vector& b)\n{\n    return PreconditionedConjugateGradient<Matrix,Vector, SparseLDLT<Matrix, mtao::Vector<typename Vector::Scalar, Vector::RowsAtCompileTime>>>(A);\n    //auto solver = IterativeLinearSolver<PreconditionedConjugateGradientCapsule<Matrix,Vector, Preconditioner> >(A.rows(), 1e-5);\n}\ntemplate <typename Matrix, typename Vector>\nauto ldlt_pcg_solve(const Matrix & A, const Vector & b)\n{\n    auto solver = ldlt_pcg_solver(A,b);\n    //auto solver = IterativeLinearSolver<PreconditionedConjugateGradientCapsule<Matrix,Vector, Preconditioner> >(A.rows(), 1e-5);\n    return solver.solve(b);\n}\n\n\n\n\n\n#endif\n", "meta": {"hexsha": "e8f5e45ee102f504d9651ece85f1519a7a33b5ee", "size": 7706, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "examples/laplacian/solver.hpp", "max_stars_repo_name": "mtao/mandoline", "max_stars_repo_head_hexsha": "79438c5b210a2ca4b9f72cbfd2879a9ae6a665da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 54.0, "max_stars_repo_stars_event_min_datetime": "2019-11-12T11:07:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T11:09:19.000Z", "max_issues_repo_path": "examples/laplacian/solver.hpp", "max_issues_repo_name": "mtao/mandoline", "max_issues_repo_head_hexsha": "79438c5b210a2ca4b9f72cbfd2879a9ae6a665da", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-12-17T01:49:44.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-29T19:46:36.000Z", "max_forks_repo_path": "examples/laplacian/solver.hpp", "max_forks_repo_name": "mtao/mandoline", "max_forks_repo_head_hexsha": "79438c5b210a2ca4b9f72cbfd2879a9ae6a665da", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2019-11-29T02:30:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-19T06:15:22.000Z", "avg_line_length": 29.8682170543, "max_line_length": 147, "alphanum_fraction": 0.4913054763, "num_tokens": 1843, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4668874101467931}}
{"text": "/*************************************************************************\n * SceneML, Copyright (C) 2007, 2008  J.D. Yamokoski\n * All rights reserved.\n * Email: yamokosk at gmail dot com\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 License as\n * published by the Free Software Foundation; either version 2.1 of the License, \n * or (at your option) any later version. The text of the GNU Lesser General \n * Public License is included with this library in the file LICENSE.TXT.\n *\n * This library is distributed in the hope that it will be useful, but WITHOUT \n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY \n * or FITNESS FOR A PARTICULAR PURPOSE. See the file LICENSE.TXT for \n * more details.\n *\n *************************************************************************/\n\n#include \"transform.h\"\n#include \"pose_estimation.h\"\n#include \"matrix.h\"\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\nusing namespace sceneml;\n\nCoordinateTransform::CoordinateTransform() :\n\tpos_(3),\n\tori_(0,0,0,0)\n{ }\n\nSimpleTransform::~SimpleTransform()\n{ }\n\n//const dReal* SimpleTransform::compute()\nconst dReal* SimpleTransform::compute()\n{\n\t//using namespace boost::numeric::ublas;\n\n\t//identity_matrix<double> eye(4);\n\t//matrix<double> tmatrix(4,4);\n\tdTSetIdentity(tmatrix_);\n\t\n\t// Compute transform - using pos and quaternion\n\tif ( !type_.compare(\"translation\") ) {\n\t\tdTFromTrans(tmatrix_, (data_.get())[0], (data_.get())[1], (data_.get())[2]);\n\t\t//for (int n=0; n < 3; ++n) tmatrix(n,3) = pos_(n);\n\t\t//subrange(tmatrix, 0, 2, 3, 3) = pos_;\n\t} else if ( !type_.compare(\"rotation\") ) {\n\t\tif ( !subtype_.compare(\"x\") ) \t\tdTFromAxisAndAngle(tmatrix_, REAL(1.0), REAL(0.0), REAL(0.0), (data_.get())[0]); \n\t\telse if ( !subtype_.compare(\"y\") ) \tdTFromAxisAndAngle(tmatrix_, REAL(0.0), REAL(1.0), REAL(0.0), (data_.get())[0]); \n\t\telse if ( !subtype_.compare(\"z\") ) \tdTFromAxisAndAngle(tmatrix_, REAL(0.0), REAL(0.0), REAL(1.0), (data_.get())[0]);\n\t\telse if ( !subtype_.compare(\"e123\") )\tdTFromEuler123(tmatrix_, (data_.get())[0], (data_.get())[1], (data_.get())[2]);\n\t\telse if ( !subtype_.compare(\"t123\") )\tdTFromEuler123(tmatrix_, -(data_.get())[0], -(data_.get())[1], -(data_.get())[2]);\n\t\telse throw std::runtime_error(\"\");\n\t} else {\n\t\n\t}\n\treturn tmatrix_;\n\t/*if ( !type_.compare(\"translation\") ) {\n\t\tdTFromTrans(tmatrix_, (data_.get())[0], (data_.get())[1], (data_.get())[2]);\n\t} else if ( !type_.compare(\"rotation\") ) {\n\t\tif ( !subtype_.compare(\"x\") ) \t\tdTFromAxisAndAngle(tmatrix_, REAL(1.0), REAL(0.0), REAL(0.0), (data_.get())[0]); \n\t\telse if ( !subtype_.compare(\"y\") ) \tdTFromAxisAndAngle(tmatrix_, REAL(0.0), REAL(1.0), REAL(0.0), (data_.get())[0]); \n\t\telse if ( !subtype_.compare(\"z\") ) \tdTFromAxisAndAngle(tmatrix_, REAL(0.0), REAL(0.0), REAL(1.0), (data_.get())[0]);\n\t\telse if ( !subtype_.compare(\"e123\") )\tdTFromEuler123(tmatrix_, (data_.get())[0], (data_.get())[1], (data_.get())[2]);\n\t\telse if ( !subtype_.compare(\"t123\") )\tdTFromEuler123(tmatrix_, -(data_.get())[0], -(data_.get())[1], -(data_.get())[2]);\n\t\telse throw std::runtime_error(\"\");\n\t} else  {\n\t\tthrow std::runtime_error(\"\");\n\t}\n\t\n\treturn tmatrix_;*/\n}\n\n\nMarkerTransform::~MarkerTransform()\n{\n\t/*for (unsigned int n=0; n < localCoords_.size(); ++n)\n\t{\n\t\tdelete [] localCoords_[n];\n\t\tdelete [] globalCoords_[n];\n\t}*/\n}\n\nconst dReal* MarkerTransform::compute()\n{\n\t// Number of local and global coords is ASSUMED to be the same.. no error \n\t// checking done here\n\tint nNumCoords = localCoords_.size();\n\t\n\t// Allocate temp storage for markers and fill up with data\n\tdRealPtr lCoords( new dReal[3 * nNumCoords] );\n\tdRealPtr gCoords( new dReal[3 * nNumCoords] );\n\n\tfor (int n=0; n < nNumCoords; ++n)\n\t{\n\t\t//dReal* lCoord = localCoords_[n], gCoord = globalCoords[n];\n\t\t\n\t\tmemcpy( (lCoords.get()+n*3), localCoords_[n].get(), 3*sizeof(dReal) );\n\t\tmemcpy( (gCoords.get()+n*3), globalCoords_[n].get(), 3*sizeof(dReal) );\n\t}\n\t\n\t// Do estimation and get answer\n\tSVDEstimator estimator;\n\testimator.estimate(gCoords.get(), lCoords.get(), nNumCoords);\n\testimator.getPose(tmatrix_);\n\t\n\treturn tmatrix_;\n}\n\n\nCompositeTransform::~CompositeTransform()\n{\n\t//CoordinateTransformList_t::iterator it = childTransforms_.begin();\n\t//for (; it != childTransforms_.end(); ++it) delete (*it);\n}\n\n\nconst dReal* CompositeTransform::compute() \n{\n\tdTSetIdentity(tmatrix_);\n\tCoordinateTransformList_t::iterator it = childTransforms_.begin();\n\tfor (; it != childTransforms_.end(); ++it)\n\t{\n\t\tdMatrix4 Tr;\n\t\tdMultiply0(Tr, tmatrix_, (*it)->compute(), 4, 4, 4);\n\t\tmemcpy(tmatrix_, Tr, sizeof(dMatrix4));\n\t}\n\tmNeedsUpdate = false;\n\treturn tmatrix_;\n};\n", "meta": {"hexsha": "9f0ccf1b536152ce3fe246c17427ff4d13211a4a", "size": 4716, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "addons/sml2tsg/transform.cpp", "max_stars_repo_name": "yamokosk/tinysg", "max_stars_repo_head_hexsha": "0243220bf5e015981257e261acfb6e764f296de2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-06-04T17:58:02.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-02T11:33:20.000Z", "max_issues_repo_path": "addons/sml2tsg/transform.cpp", "max_issues_repo_name": "yamokosk/tinysg", "max_issues_repo_head_hexsha": "0243220bf5e015981257e261acfb6e764f296de2", "max_issues_repo_licenses": ["MIT"], "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/sml2tsg/transform.cpp", "max_forks_repo_name": "yamokosk/tinysg", "max_forks_repo_head_hexsha": "0243220bf5e015981257e261acfb6e764f296de2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-18T08:49:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-18T08:49:12.000Z", "avg_line_length": 35.7272727273, "max_line_length": 122, "alphanum_fraction": 0.6490670059, "num_tokens": 1425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737775116229, "lm_q2_score": 0.5813030906443134, "lm_q1q2_score": 0.46688739919197453}}
{"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#define BOOST_TEST_MAIN\n\n#include <limits>\n#include <Eigen/LU>\n\n#include <boost/test/unit_test.hpp>\n\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/timeConversions.h\"\n#include \"Tudat/External/SofaInterface/fundamentalArguments.h\"\n#include \"Tudat/External/SofaInterface/earthOrientation.h\"\n\n\nnamespace tudat\n{\nnamespace unit_tests\n{\n\nusing namespace tudat::sofa_interface;\n\nBOOST_AUTO_TEST_SUITE( test_sofa_fundamental_arguments )\n\n//! Test calculation of Delaunay/Doodson arguments used for calculation of e.g. Earth-tide effects\nBOOST_AUTO_TEST_CASE( testSofaFundamentalArguments )\n{\n    // Test whether Doodson <-> Delaunay argument conversion matrices are each other's inverse.\n    Eigen::Matrix< double, 5, 5 > conversionMatrixComparison =\n            delaunayToDoodsonArguments - doodsonToDelaunayArguments.inverse( );\n    for( unsigned int i = 0; i < 5; i++ )\n    {\n        for( unsigned int j = 0; j < 5; j++ )\n        {\n            BOOST_CHECK_EQUAL( conversionMatrixComparison( i, j ), 0.0 );\n        }\n    }\n\n    // Use test case from FUNDARG.F code (provided with IERS 2010 conventions) to calculate Delaunay arguments\n    double testModifiedJulianDay1 = 54465.0;\n    double testSecondsSinceJ2000 = ( testModifiedJulianDay1 -\n            ( - basic_astrodynamics::JULIAN_DAY_AT_0_MJD + basic_astrodynamics::JULIAN_DAY_ON_J2000 ) ) *\n            physical_constants::JULIAN_DAY;\n    Eigen::Matrix< double, 5, 1 > expectedFundamentalArgumentValues;\n    expectedFundamentalArgumentValues << 2.291187512612069099, 6.212931111003726414, 3.658025792050572989,\n            4.554139562402433228, -0.5167379217231804489;\n\n    // Calculate Delaunay arguments.\n    Eigen::Matrix< double, 5, 1 > fundamentalArgumentValues =\n            calculateDelaunayFundamentalArguments( testSecondsSinceJ2000 );\n\n    // Compare against IERS results.\n    for( unsigned int i = 0; i < 5; i++ )\n    {\n        BOOST_CHECK_SMALL( std::fabs( expectedFundamentalArgumentValues( i ) - fundamentalArgumentValues( i ) ), 2.0E-13  );\n    }\n\n    // Calculate Delaunay arguments with GMST.\n    Eigen::Matrix< double, 6, 1 > fundamentalArgumentValuesWithGmst =\n            calculateApproximateDelaunayFundamentalArgumentsWithGmst( testSecondsSinceJ2000 );\n    for( unsigned int i = 0; i < 5; i++ )\n    {\n        BOOST_CHECK_SMALL( std::fabs( fundamentalArgumentValuesWithGmst( i + 1 ) - fundamentalArgumentValues( i ) ), 1.0E-15  );\n    }\n\n    // Manually compute GMST\n    double expectedGmst = calculateGreenwichMeanSiderealTime(\n                testSecondsSinceJ2000,\n                convertTTtoUTC( testSecondsSinceJ2000 ),\n                basic_astrodynamics::JULIAN_DAY_ON_J2000, basic_astrodynamics::iau_2006 );\n\n    BOOST_CHECK_SMALL( std::fabs( expectedGmst + mathematical_constants::PI - fundamentalArgumentValuesWithGmst( 0 ) ), 1.0E-15  );\n\n    // Calculate Doodson arguments directly and from Delaunay arguments and compare.\n    Eigen::Matrix< double, 6, 1 > doodsonArguments = calculateDoodsonFundamentalArguments( testSecondsSinceJ2000 );\n    Eigen::Matrix< double, 5, 1 > reconstructedFundamentalArguments =\n            doodsonToDelaunayArguments * doodsonArguments.segment( 1, 5 );\n    for( unsigned int i = 0; i < 5; i++ )\n    {\n        BOOST_CHECK_SMALL( std::fabs( fundamentalArgumentValues( i ) - reconstructedFundamentalArguments( i ) ), 1.0E-15  );\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END( )\n\n} // namespace unit_tests\n\n} // namespace tudat\n\n\n\n", "meta": {"hexsha": "a918f55b1bb63340366218b816e7e31562cf68dd", "size": 3865, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/External/SofaInterface/UnitTests/unitTestFundamentalArguments.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/External/SofaInterface/UnitTests/unitTestFundamentalArguments.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/External/SofaInterface/UnitTests/unitTestFundamentalArguments.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": 39.0404040404, "max_line_length": 131, "alphanum_fraction": 0.7130659767, "num_tokens": 1060, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127678225575, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.46686668863537173}}
{"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 *    References\n *      Wakker, K. F. (2007), Lecture Notes Astrodynamics II (Chapter 18), TU Delft course AE4-874,\n *          Delft University of technology, Delft, The Netherlands.\n *\n */\n\n#define BOOST_TEST_MAIN\n\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/unit_test.hpp>\n#include <Eigen/Dense>\n#include <cmath>\n#include <iostream>\n\n#include \"Tudat/Astrodynamics/LowThrustTrajectories/ShapeBasedMethods/compositeFunctionHodographicShaping.h\"\n#include \"Tudat/Astrodynamics/LowThrustTrajectories/ShapeBasedMethods/hodographicShaping.h\"\n#include \"Tudat/Astrodynamics/LowThrustTrajectories/ShapeBasedMethods/baseFunctionsHodographicShaping.h\"\n#include \"Tudat/Astrodynamics/LowThrustTrajectories/ShapeBasedMethods/createBaseFunctionHodographicShaping.h\"\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/physicalConstants.h\"\n#include \"Tudat/Mathematics/BasicMathematics/mathematicalConstants.h\"\n#include \"Tudat/Mathematics/BasicMathematics/basicMathematicsFunctions.h\"\n#include \"Tudat/Mathematics/BasicMathematics/coordinateConversions.h\"\n#include \"Tudat/Astrodynamics/Ephemerides/approximatePlanetPositions.h\"\n#include \"Tudat/SimulationSetup/tudatSimulationHeader.h\"\n#include \"Tudat/External/SpiceInterface/spiceEphemeris.h\"\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/celestialBodyConstants.h\"\n\nnamespace tudat\n{\nnamespace unit_tests\n{\n\nusing namespace shape_based_methods;\nusing namespace simulation_setup;\nusing namespace propagators;\n\n//! Test hodographic shaping implementation.\nBOOST_AUTO_TEST_SUITE( test_hodographic_shaping )\n\ndouble getPeakAcceleration( const double timeOfFlight, HodographicShaping& hodographicShaping )\n{\n    int numberOfSteps = 500;\n    double stepSize = ( timeOfFlight * physical_constants::JULIAN_DAY ) / static_cast< double >( numberOfSteps );\n    double peakAcceleration = 0.0;\n    for ( int currentStep = 0 ; currentStep <= numberOfSteps ; currentStep++ )\n    {\n        double currentTime = currentStep * stepSize;\n        double currentAccelerationMagnitude = hodographicShaping.computeThrustAccelerationVector( currentTime ).norm( );\n\n        if ( currentAccelerationMagnitude > peakAcceleration )\n        {\n            peakAcceleration = currentAccelerationMagnitude;\n        }\n    }\n\n    return peakAcceleration;\n}\n//! Test Earth-Mars transfers, based on the thesis by Gondelach (ADD PROPER REFERENCE).\nBOOST_AUTO_TEST_CASE( test_hodographic_shaping_earth_mars_transfer_1 )\n{\n    spice_interface::loadStandardSpiceKernels( );\n\n\n    // Basic settings\n    int numberOfRevolutions = 2;\n    double julianDate = 9264.5 * physical_constants::JULIAN_DAY;\n    double timeOfFlight = 1070.0;\n    double frequency = 2.0 * mathematical_constants::PI / ( timeOfFlight * physical_constants::JULIAN_DAY );\n    double scaleFactor = 1.0 / ( timeOfFlight * physical_constants::JULIAN_DAY );\n\n    // Initialize free coefficients vector for radial, normal and axial velocity function.\n    Eigen::VectorXd freeCoefficientsRadialVelocityFunction = Eigen::VectorXd::Zero( 0 );\n    Eigen::VectorXd freeCoefficientsNormalVelocityFunction = Eigen::VectorXd::Zero( 0 );\n    Eigen::VectorXd freeCoefficientsAxialVelocityFunction = Eigen::VectorXd::Zero( 0 );\n\n    // Create base function settings for the components of the radial velocity composite function.\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > firstRadialVelocityBaseFunctionSettings =\n            std::make_shared< BaseFunctionHodographicShapingSettings >( );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > secondRadialVelocityBaseFunctionSettings =\n            std::make_shared< PowerFunctionHodographicShapingSettings >( 1.0, scaleFactor );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > thirdRadialVelocityBaseFunctionSettings =\n            std::make_shared< TrigonometricFunctionHodographicShapingSettings >( frequency );\n\n    // Create components of the radial velocity composite function.\n    std::vector< std::shared_ptr< BaseFunctionHodographicShaping > > radialVelocityFunctionComponents;\n    radialVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( constant, firstRadialVelocityBaseFunctionSettings ) );\n    radialVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( scaledPower, secondRadialVelocityBaseFunctionSettings ) );\n    radialVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( cosine, thirdRadialVelocityBaseFunctionSettings ) );\n\n    // Create base function settings for the components of the normal velocity composite function.\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > firstNormalVelocityBaseFunctionSettings =\n            std::make_shared< BaseFunctionHodographicShapingSettings >( );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > secondNormalVelocityBaseFunctionSettings =\n            std::make_shared< PowerFunctionHodographicShapingSettings >( 1.0, scaleFactor );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > thirdNormalVelocityBaseFunctionSettings =\n            std::make_shared< TrigonometricFunctionHodographicShapingSettings >( frequency );\n\n    // Create components of the normal velocity composite function.\n    std::vector< std::shared_ptr< BaseFunctionHodographicShaping > > normalVelocityFunctionComponents;\n    normalVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( constant, firstNormalVelocityBaseFunctionSettings ) );\n    normalVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( scaledPower, secondNormalVelocityBaseFunctionSettings ) );\n    normalVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( cosine, thirdNormalVelocityBaseFunctionSettings ) );\n\n    // Create base function settings for the components of the axial velocity composite function.\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > firstAxialVelocityBaseFunctionSettings =\n            std::make_shared< TrigonometricFunctionHodographicShapingSettings >( ( numberOfRevolutions + 0.5 ) * frequency );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > secondAxialVelocityBaseFunctionSettings =\n            std::make_shared< PowerTimesTrigonometricFunctionHodographicShapingSettings >\n            ( 3.0, ( numberOfRevolutions + 0.5 ) * frequency, scaleFactor );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > thirdAxialVelocityBaseFunctionSettings =\n            std::make_shared< PowerTimesTrigonometricFunctionHodographicShapingSettings >(\n                3.0, ( numberOfRevolutions + 0.5 ) * frequency, scaleFactor );\n\n    // Set components for the axial velocity function.\n    std::vector< std::shared_ptr< BaseFunctionHodographicShaping > > axialVelocityFunctionComponents;\n    axialVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( cosine, firstAxialVelocityBaseFunctionSettings ) );\n    axialVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( scaledPowerCosine, secondAxialVelocityBaseFunctionSettings ) );\n    axialVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( scaledPowerSine, thirdAxialVelocityBaseFunctionSettings ) );\n\n    // Retrieve cartesian state at departure and arrival.\n    ephemerides::EphemerisPointer pointerToDepartureBodyEphemeris = std::make_shared< ephemerides::ApproximatePlanetPositions>(\n                ephemerides::ApproximatePlanetPositionsBase::BodiesWithEphemerisData::earthMoonBarycenter );\n    ephemerides::EphemerisPointer pointerToArrivalBodyEphemeris = std::make_shared< ephemerides::ApproximatePlanetPositions >(\n                ephemerides::ApproximatePlanetPositionsBase::BodiesWithEphemerisData::mars );\n    Eigen::Vector6d cartesianStateDepartureBody =\n            pointerToDepartureBodyEphemeris->getCartesianState( julianDate );\n    Eigen::Vector6d cartesianStateArrivalBody =\n            pointerToArrivalBodyEphemeris->getCartesianState( julianDate + timeOfFlight  * physical_constants::JULIAN_DAY );\n\n    // Create hodographic-shaping object with defined velocity functions and boundary conditions.\n    HodographicShaping hodographicShaping = HodographicShaping(\n                cartesianStateDepartureBody, cartesianStateArrivalBody,\n                timeOfFlight * physical_constants::JULIAN_DAY,\n                spice_interface::getBodyGravitationalParameter( \"Sun\" ),  numberOfRevolutions,\n                radialVelocityFunctionComponents, normalVelocityFunctionComponents, axialVelocityFunctionComponents,\n                freeCoefficientsRadialVelocityFunction, freeCoefficientsNormalVelocityFunction,\n                freeCoefficientsAxialVelocityFunction );\n\n    // Check results consistency w.r.t. thesis from D. Gondelach (ADD PROPER REFERENCE)\n    double expectedDeltaV = 7751.0;\n    double expectedPeakAcceleration = 2.64e-4;\n\n    // DeltaV provided with a precision of 1 m/s\n    BOOST_CHECK_SMALL( std::fabs(  hodographicShaping.computeDeltaV( ) - expectedDeltaV ), 1.0 );\n    // Peak acceleration provided with a precision 1.0e-6 m/s^2\n    BOOST_CHECK_SMALL( std::fabs(  getPeakAcceleration( timeOfFlight, hodographicShaping ) - expectedPeakAcceleration ), 1e-6 );\n\n}\n\nBOOST_AUTO_TEST_CASE( test_hodographic_shaping_earth_mars_transfer_2 )\n{\n\n    // Basic settings\n    int numberOfRevolutions = 2;\n    double julianDate = 10034.5 * physical_constants::JULIAN_DAY;\n    double timeOfFlight = 1070.0;\n    double frequency = 2.0 * mathematical_constants::PI / ( timeOfFlight * physical_constants::JULIAN_DAY );\n    double scaleFactor = 1.0 / ( timeOfFlight * physical_constants::JULIAN_DAY );\n\n    // Initialize free coefficients vector for radial, normal and axial velocity function.\n    Eigen::VectorXd freeCoefficientsRadialVelocityFunction = Eigen::VectorXd::Zero( 0 );\n    Eigen::VectorXd freeCoefficientsNormalVelocityFunction = Eigen::VectorXd::Zero( 0 );\n    Eigen::VectorXd freeCoefficientsAxialVelocityFunction = Eigen::VectorXd::Zero( 0 );\n\n    // Create base function settings for the components of the radial velocity composite function.\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > firstRadialVelocityBaseFunctionSettings =\n            std::make_shared< BaseFunctionHodographicShapingSettings >( );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > secondRadialVelocityBaseFunctionSettings =\n            std::make_shared< PowerFunctionHodographicShapingSettings >( 1.0, scaleFactor );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > thirdRadialVelocityBaseFunctionSettings =\n            std::make_shared< TrigonometricFunctionHodographicShapingSettings >( 0.5 * frequency );\n\n    // Create components of the radial velocity composite function.\n    std::vector< std::shared_ptr< BaseFunctionHodographicShaping > > radialVelocityFunctionComponents;\n    radialVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( constant, firstRadialVelocityBaseFunctionSettings ) );\n    radialVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( scaledPower, secondRadialVelocityBaseFunctionSettings ) );\n    radialVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( sine, thirdRadialVelocityBaseFunctionSettings ) );\n\n    // Create base function settings for the components of the normal velocity composite function.\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > firstNormalVelocityBaseFunctionSettings =\n            std::make_shared< BaseFunctionHodographicShapingSettings >( );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > secondNormalVelocityBaseFunctionSettings =\n            std::make_shared< PowerFunctionHodographicShapingSettings >( 1.0, scaleFactor );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > thirdNormalVelocityBaseFunctionSettings =\n            std::make_shared< TrigonometricFunctionHodographicShapingSettings >( 0.5 * frequency );\n\n    // Create components of the normal velocity composite function.\n    std::vector< std::shared_ptr< BaseFunctionHodographicShaping > > normalVelocityFunctionComponents;\n    normalVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( constant, firstNormalVelocityBaseFunctionSettings ) );\n    normalVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( scaledPower, secondNormalVelocityBaseFunctionSettings ) );\n    normalVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( sine, thirdNormalVelocityBaseFunctionSettings ) );\n\n    // Create base function settings for the components of the axial velocity composite function.\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > firstAxialVelocityBaseFunctionSettings =\n            std::make_shared< TrigonometricFunctionHodographicShapingSettings >\n            ( ( numberOfRevolutions + 0.5 ) * frequency );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > secondAxialVelocityBaseFunctionSettings =\n            std::make_shared< PowerTimesTrigonometricFunctionHodographicShapingSettings >\n            ( 3.0, ( numberOfRevolutions + 0.5 ) * frequency, scaleFactor );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > thirdAxialVelocityBaseFunctionSettings =\n            std::make_shared< PowerTimesTrigonometricFunctionHodographicShapingSettings >(\n                3.0, ( numberOfRevolutions + 0.5 ) * frequency, scaleFactor );\n\n    // Set components for the axial velocity function.\n    std::vector< std::shared_ptr< BaseFunctionHodographicShaping > > axialVelocityFunctionComponents;\n    axialVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( cosine, firstAxialVelocityBaseFunctionSettings ) );\n    axialVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( scaledPowerCosine, secondAxialVelocityBaseFunctionSettings ) );\n    axialVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( scaledPowerSine, thirdAxialVelocityBaseFunctionSettings ) );\n\n    // Retrieve cartesian state at departure and arrival.\n    ephemerides::EphemerisPointer pointerToDepartureBodyEphemeris = std::make_shared< ephemerides::ApproximatePlanetPositions>(\n                ephemerides::ApproximatePlanetPositionsBase::BodiesWithEphemerisData::earthMoonBarycenter );\n    ephemerides::EphemerisPointer pointerToArrivalBodyEphemeris = std::make_shared< ephemerides::ApproximatePlanetPositions >(\n                ephemerides::ApproximatePlanetPositionsBase::BodiesWithEphemerisData::mars );\n    Eigen::Vector6d cartesianStateDepartureBody =\n            pointerToDepartureBodyEphemeris->getCartesianState( julianDate );\n    Eigen::Vector6d cartesianStateArrivalBody =\n            pointerToArrivalBodyEphemeris->getCartesianState( julianDate + timeOfFlight  * physical_constants::JULIAN_DAY );\n\n    // Create hodographic-shaping object with defined velocity functions and boundary conditions.\n    HodographicShaping hodographicShaping = HodographicShaping(\n                cartesianStateDepartureBody,\n                cartesianStateArrivalBody,\n                timeOfFlight * physical_constants::JULIAN_DAY,\n                spice_interface::getBodyGravitationalParameter( \"Sun\" ), numberOfRevolutions,\n                radialVelocityFunctionComponents, normalVelocityFunctionComponents, axialVelocityFunctionComponents,\n                freeCoefficientsRadialVelocityFunction, freeCoefficientsNormalVelocityFunction,\n                freeCoefficientsAxialVelocityFunction );\n\n    // Check results consistency w.r.t. thesis from D. Gondelach (ADD PROPER REFERENCE)\n    double expectedDeltaV = 6742.0;\n    double expectedPeakAcceleration = 1.46e-4;\n\n    // DeltaV provided with a precision of 1 m/s\n    BOOST_CHECK_SMALL( std::fabs(  hodographicShaping.computeDeltaV( ) - expectedDeltaV ), 1.0 );\n    // Peak acceleration provided with a precision 1.0e-6 m/s^2\n    BOOST_CHECK_SMALL( std::fabs(  getPeakAcceleration( timeOfFlight, hodographicShaping ) - expectedPeakAcceleration ), 1e-6 );\n\n}\n\nBOOST_AUTO_TEST_CASE( test_hodographic_shaping_earth_mars_transfer_3 )\n{\n\n    // Basic settings\n    int numberOfRevolutions = 2;\n    double julianDate = 9244.5 * physical_constants::JULIAN_DAY;\n    double timeOfFlight = 1090.0;\n    double frequency = 2.0 * mathematical_constants::PI / ( timeOfFlight * physical_constants::JULIAN_DAY );\n    double scaleFactor = 1.0 / ( timeOfFlight * physical_constants::JULIAN_DAY );\n\n    // Initialize free coefficients vector for radial, normal and axial velocity function.\n    Eigen::VectorXd freeCoefficientsRadialVelocityFunction = Eigen::VectorXd::Zero( 0 );\n    Eigen::VectorXd freeCoefficientsNormalVelocityFunction = Eigen::VectorXd::Zero( 0 );\n    Eigen::VectorXd freeCoefficientsAxialVelocityFunction = Eigen::VectorXd::Zero( 0 );\n\n    // Create base function settings for the components of the radial velocity composite function.\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > firstRadialVelocityBaseFunctionSettings =\n            std::make_shared< BaseFunctionHodographicShapingSettings >( );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > secondRadialVelocityBaseFunctionSettings =\n            std::make_shared< PowerFunctionHodographicShapingSettings >( 1.0, scaleFactor );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > thirdRadialVelocityBaseFunctionSettings =\n            std::make_shared< PowerFunctionHodographicShapingSettings >( 2.0, scaleFactor );\n\n    // Create components of the radial velocity composite function.\n    std::vector< std::shared_ptr< BaseFunctionHodographicShaping > > radialVelocityFunctionComponents;\n    radialVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( constant, firstRadialVelocityBaseFunctionSettings ) );\n    radialVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( scaledPower, secondRadialVelocityBaseFunctionSettings ) );\n    radialVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( scaledPower, thirdRadialVelocityBaseFunctionSettings ) );\n\n    // Create base function settings for the components of the normal velocity composite function.\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > firstNormalVelocityBaseFunctionSettings =\n            std::make_shared< BaseFunctionHodographicShapingSettings >( );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > secondNormalVelocityBaseFunctionSettings =\n            std::make_shared< PowerFunctionHodographicShapingSettings >( 1.0, scaleFactor );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > thirdNormalVelocityBaseFunctionSettings =\n            std::make_shared< TrigonometricFunctionHodographicShapingSettings >( frequency );\n\n    // Create components of the normal velocity composite function.\n    std::vector< std::shared_ptr< BaseFunctionHodographicShaping > > normalVelocityFunctionComponents;\n    normalVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( constant, firstNormalVelocityBaseFunctionSettings ) );\n    normalVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( scaledPower, secondNormalVelocityBaseFunctionSettings ) );\n    normalVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( cosine, thirdNormalVelocityBaseFunctionSettings ) );\n\n    // Create base function settings for the components of the axial velocity composite function.\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > firstAxialVelocityBaseFunctionSettings =\n            std::make_shared< TrigonometricFunctionHodographicShapingSettings >( ( numberOfRevolutions + 0.5 ) * frequency );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > secondAxialVelocityBaseFunctionSettings =\n            std::make_shared< PowerTimesTrigonometricFunctionHodographicShapingSettings >\n            ( 3.0, ( numberOfRevolutions + 0.5 ) * frequency, scaleFactor );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > thirdAxialVelocityBaseFunctionSettings =\n            std::make_shared< PowerTimesTrigonometricFunctionHodographicShapingSettings >(\n                3.0, ( numberOfRevolutions + 0.5 ) * frequency, scaleFactor );\n\n    // Set components for the axial velocity function.\n    std::vector< std::shared_ptr< BaseFunctionHodographicShaping > > axialVelocityFunctionComponents;\n    axialVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( cosine, firstAxialVelocityBaseFunctionSettings ) );\n    axialVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( scaledPowerCosine, secondAxialVelocityBaseFunctionSettings ) );\n    axialVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( scaledPowerSine, thirdAxialVelocityBaseFunctionSettings ) );\n\n    // Retrieve cartesian state at departure and arrival.\n    ephemerides::EphemerisPointer pointerToDepartureBodyEphemeris = std::make_shared< ephemerides::ApproximatePlanetPositions>(\n                ephemerides::ApproximatePlanetPositionsBase::BodiesWithEphemerisData::earthMoonBarycenter );\n    ephemerides::EphemerisPointer pointerToArrivalBodyEphemeris = std::make_shared< ephemerides::ApproximatePlanetPositions >(\n                ephemerides::ApproximatePlanetPositionsBase::BodiesWithEphemerisData::mars );\n    Eigen::Vector6d cartesianStateDepartureBody =\n            pointerToDepartureBodyEphemeris->getCartesianState( julianDate );\n    Eigen::Vector6d cartesianStateArrivalBody =\n            pointerToArrivalBodyEphemeris->getCartesianState( julianDate + timeOfFlight  * physical_constants::JULIAN_DAY );\n\n    // Create hodographic-shaping object with defined velocity functions and boundary conditions.\n    HodographicShaping hodographicShaping = HodographicShaping(\n                cartesianStateDepartureBody, cartesianStateArrivalBody,\n                timeOfFlight * physical_constants::JULIAN_DAY,\n                spice_interface::getBodyGravitationalParameter( \"Sun\" ), numberOfRevolutions,\n                radialVelocityFunctionComponents, normalVelocityFunctionComponents, axialVelocityFunctionComponents,\n                freeCoefficientsRadialVelocityFunction, freeCoefficientsNormalVelocityFunction,\n                freeCoefficientsAxialVelocityFunction );\n\n    // Check results consistency w.r.t. thesis from D. Gondelach (ADD PROPER REFERENCE)\n    double expectedDeltaV = 6686.0;\n    double expectedPeakAcceleration = 2.46e-4;\n\n    // DeltaV provided with a precision of 1 m/s\n    BOOST_CHECK_SMALL( std::fabs(  hodographicShaping.computeDeltaV( ) - expectedDeltaV ), 1.0 );\n    // Peak acceleration provided with a precision 1.0e-6 m/s^2\n    BOOST_CHECK_SMALL( std::fabs(  getPeakAcceleration( timeOfFlight, hodographicShaping ) - expectedPeakAcceleration ), 1e-6 );\n}\n\nBOOST_AUTO_TEST_CASE( test_hodographic_shaping_earth_mars_transfer_4 )\n{\n\n    // Basic settings\n    int numberOfRevolutions = 2;\n    double julianDate = 10024.5 * physical_constants::JULIAN_DAY;\n    double timeOfFlight = 1050.0;\n    double frequency = 2.0 * mathematical_constants::PI / ( timeOfFlight * physical_constants::JULIAN_DAY );\n    double scaleFactor = 1.0 / ( timeOfFlight * physical_constants::JULIAN_DAY );\n\n    // Initialize free coefficients vector for radial, normal and axial velocity function.\n    Eigen::VectorXd freeCoefficientsRadialVelocityFunction = Eigen::VectorXd::Zero( 0 );\n    Eigen::VectorXd freeCoefficientsNormalVelocityFunction = Eigen::VectorXd::Zero( 0 );\n    Eigen::VectorXd freeCoefficientsAxialVelocityFunction = Eigen::VectorXd::Zero( 0 );\n\n    // Create base function settings for the components of the radial velocity composite function.\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > firstRadialVelocityBaseFunctionSettings =\n            std::make_shared< BaseFunctionHodographicShapingSettings >( );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > secondRadialVelocityBaseFunctionSettings =\n            std::make_shared< PowerFunctionHodographicShapingSettings >( 1.0, scaleFactor );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > thirdRadialVelocityBaseFunctionSettings =\n            std::make_shared< PowerFunctionHodographicShapingSettings >( 2.0, scaleFactor );\n\n    // Create components of the radial velocity composite function.\n    std::vector< std::shared_ptr< BaseFunctionHodographicShaping > > radialVelocityFunctionComponents;\n    radialVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( constant, firstRadialVelocityBaseFunctionSettings ) );\n    radialVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( scaledPower, secondRadialVelocityBaseFunctionSettings ) );\n    radialVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( scaledPower, thirdRadialVelocityBaseFunctionSettings ) );\n\n    // Create base function settings for the components of the normal velocity composite function.\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > firstNormalVelocityBaseFunctionSettings =\n            std::make_shared< BaseFunctionHodographicShapingSettings >( );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > secondNormalVelocityBaseFunctionSettings =\n            std::make_shared< PowerFunctionHodographicShapingSettings >( 1.0, scaleFactor );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > thirdNormalVelocityBaseFunctionSettings =\n            std::make_shared< TrigonometricFunctionHodographicShapingSettings >( 0.5 * frequency );\n\n    // Create components of the normal velocity composite function.\n    std::vector< std::shared_ptr< BaseFunctionHodographicShaping > > normalVelocityFunctionComponents;\n    normalVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( constant, firstNormalVelocityBaseFunctionSettings ) );\n    normalVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( scaledPower, secondNormalVelocityBaseFunctionSettings ) );\n    normalVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( sine, thirdNormalVelocityBaseFunctionSettings ) );\n\n    // Create base function settings for the components of the axial velocity composite function.\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > firstAxialVelocityBaseFunctionSettings =\n            std::make_shared< TrigonometricFunctionHodographicShapingSettings >( ( numberOfRevolutions + 0.5 ) * frequency );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > secondAxialVelocityBaseFunctionSettings =\n            std::make_shared< PowerTimesTrigonometricFunctionHodographicShapingSettings >\n            ( 3.0, ( numberOfRevolutions + 0.5 ) * frequency, scaleFactor );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > thirdAxialVelocityBaseFunctionSettings =\n            std::make_shared< PowerTimesTrigonometricFunctionHodographicShapingSettings >(\n                3.0, ( numberOfRevolutions + 0.5 ) * frequency, scaleFactor );\n\n    // Set components for the axial velocity function.\n    std::vector< std::shared_ptr< BaseFunctionHodographicShaping > > axialVelocityFunctionComponents;\n    axialVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( cosine, firstAxialVelocityBaseFunctionSettings ) );\n    axialVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( scaledPowerCosine, secondAxialVelocityBaseFunctionSettings ) );\n    axialVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( scaledPowerSine, thirdAxialVelocityBaseFunctionSettings ) );\n\n    // Retrieve cartesian state at departure and arrival.\n    ephemerides::EphemerisPointer pointerToDepartureBodyEphemeris = std::make_shared< ephemerides::ApproximatePlanetPositions>(\n                ephemerides::ApproximatePlanetPositionsBase::BodiesWithEphemerisData::earthMoonBarycenter );\n    ephemerides::EphemerisPointer pointerToArrivalBodyEphemeris = std::make_shared< ephemerides::ApproximatePlanetPositions >(\n                ephemerides::ApproximatePlanetPositionsBase::BodiesWithEphemerisData::mars );\n    Eigen::Vector6d cartesianStateDepartureBody =\n            pointerToDepartureBodyEphemeris->getCartesianState( julianDate );\n    Eigen::Vector6d cartesianStateArrivalBody =\n            pointerToArrivalBodyEphemeris->getCartesianState( julianDate + timeOfFlight  * physical_constants::JULIAN_DAY );\n\n    // Create hodographic-shaping object with defined velocity functions and boundary conditions.\n    HodographicShaping hodographicShaping = HodographicShaping(\n                cartesianStateDepartureBody, cartesianStateArrivalBody,\n                timeOfFlight * physical_constants::JULIAN_DAY,\n                spice_interface::getBodyGravitationalParameter( \"Sun\" ), numberOfRevolutions,\n                radialVelocityFunctionComponents, normalVelocityFunctionComponents, axialVelocityFunctionComponents,\n                freeCoefficientsRadialVelocityFunction, freeCoefficientsNormalVelocityFunction, freeCoefficientsAxialVelocityFunction );\n\n    // Check results consistency w.r.t. thesis from D. Gondelach (ADD PROPER REFERENCE)\n    double expectedDeltaV = 6500.0;\n    double expectedPeakAcceleration = 1.58e-4;\n\n    // DeltaV provided with a precision of 1 m/s\n    BOOST_CHECK_SMALL( std::fabs(  hodographicShaping.computeDeltaV( ) - expectedDeltaV ), 1.0 );\n\n    // Peak acceleration provided with a precision 1.0e-6 m/s^2\n    BOOST_CHECK_SMALL( std::fabs(  getPeakAcceleration( timeOfFlight, hodographicShaping ) - expectedPeakAcceleration ), 1e-6 );\n\n}\n\nBOOST_AUTO_TEST_CASE( test_hodographic_shaping_earth_mars_transfer_5 )\n{\n    // Basic settings\n    int numberOfRevolutions = 2;\n    double julianDate = 10024.5 * physical_constants::JULIAN_DAY;\n    double timeOfFlight = 1050.0;\n    double frequency = 2.0 * mathematical_constants::PI / ( timeOfFlight * physical_constants::JULIAN_DAY );\n    double scaleFactor = 1.0 / ( timeOfFlight * physical_constants::JULIAN_DAY );\n\n    // Initialize free coefficients vector for radial, normal and axial velocity function.\n    Eigen::VectorXd freeCoefficientsRadialVelocityFunction = Eigen::VectorXd::Zero( 0 );\n    Eigen::VectorXd freeCoefficientsNormalVelocityFunction = Eigen::VectorXd::Zero( 0 );\n    Eigen::VectorXd freeCoefficientsAxialVelocityFunction = Eigen::VectorXd::Zero( 0 );\n\n    // Create base function settings for the components of the radial velocity composite function.\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > firstRadialVelocityBaseFunctionSettings =\n            std::make_shared< BaseFunctionHodographicShapingSettings >( );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > secondRadialVelocityBaseFunctionSettings =\n            std::make_shared< PowerFunctionHodographicShapingSettings >( 1.0, scaleFactor );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > thirdRadialVelocityBaseFunctionSettings =\n            std::make_shared< PowerFunctionHodographicShapingSettings >( 2.0, scaleFactor );\n\n    // Create components of the radial velocity composite function.\n    std::vector< std::shared_ptr< BaseFunctionHodographicShaping > > radialVelocityFunctionComponents;\n    radialVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( constant, firstRadialVelocityBaseFunctionSettings ) );\n    radialVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( scaledPower, secondRadialVelocityBaseFunctionSettings ) );\n    radialVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( scaledPower, thirdRadialVelocityBaseFunctionSettings ) );\n\n    // Create base function settings for the components of the normal velocity composite function.\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > firstNormalVelocityBaseFunctionSettings =\n            std::make_shared< BaseFunctionHodographicShapingSettings >( );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > secondNormalVelocityBaseFunctionSettings =\n            std::make_shared< PowerFunctionHodographicShapingSettings >( 1.0, scaleFactor );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > thirdNormalVelocityBaseFunctionSettings =\n            std::make_shared< PowerFunctionHodographicShapingSettings >( 2.0, scaleFactor );\n\n    // Create components of the normal velocity composite function.\n    std::vector< std::shared_ptr< BaseFunctionHodographicShaping > > normalVelocityFunctionComponents;\n    normalVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( constant, firstNormalVelocityBaseFunctionSettings ) );\n    normalVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( scaledPower, secondNormalVelocityBaseFunctionSettings ) );\n    normalVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( scaledPower, thirdNormalVelocityBaseFunctionSettings ) );\n\n    // Create base function settings for the components of the axial velocity composite function.\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > firstAxialVelocityBaseFunctionSettings =\n            std::make_shared< TrigonometricFunctionHodographicShapingSettings >( ( numberOfRevolutions + 0.5 ) * frequency );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > secondAxialVelocityBaseFunctionSettings =\n            std::make_shared< PowerTimesTrigonometricFunctionHodographicShapingSettings >\n            ( 3.0, ( numberOfRevolutions + 0.5 ) * frequency, scaleFactor );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > thirdAxialVelocityBaseFunctionSettings =\n            std::make_shared< PowerTimesTrigonometricFunctionHodographicShapingSettings >(\n                3.0, ( numberOfRevolutions + 0.5 ) * frequency, scaleFactor );\n\n    // Set components for the axial velocity function.\n    std::vector< std::shared_ptr< BaseFunctionHodographicShaping > > axialVelocityFunctionComponents;\n    axialVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( cosine, firstAxialVelocityBaseFunctionSettings ) );\n    axialVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( scaledPowerCosine, secondAxialVelocityBaseFunctionSettings ) );\n    axialVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( scaledPowerSine, thirdAxialVelocityBaseFunctionSettings ) );\n\n    // Retrieve cartesian state at departure and arrival.\n    ephemerides::EphemerisPointer pointerToDepartureBodyEphemeris = std::make_shared< ephemerides::ApproximatePlanetPositions>(\n                ephemerides::ApproximatePlanetPositionsBase::BodiesWithEphemerisData::earthMoonBarycenter );\n    ephemerides::EphemerisPointer pointerToArrivalBodyEphemeris = std::make_shared< ephemerides::ApproximatePlanetPositions >(\n                ephemerides::ApproximatePlanetPositionsBase::BodiesWithEphemerisData::mars );\n    Eigen::Vector6d cartesianStateDepartureBody =\n            pointerToDepartureBodyEphemeris->getCartesianState( julianDate );\n    Eigen::Vector6d cartesianStateArrivalBody =\n            pointerToArrivalBodyEphemeris->getCartesianState( julianDate + timeOfFlight  * physical_constants::JULIAN_DAY );\n\n    // Create hodographic-shaping object with defined velocity functions and boundary conditions.\n    HodographicShaping hodographicShaping = HodographicShaping(\n                cartesianStateDepartureBody, cartesianStateArrivalBody,\n                timeOfFlight * physical_constants::JULIAN_DAY,\n                spice_interface::getBodyGravitationalParameter( \"Sun\" ), numberOfRevolutions,\n                radialVelocityFunctionComponents, normalVelocityFunctionComponents, axialVelocityFunctionComponents,\n                freeCoefficientsRadialVelocityFunction, freeCoefficientsNormalVelocityFunction, freeCoefficientsAxialVelocityFunction );\n\n    // Check results consistency w.r.t. thesis from D. Gondelach (ADD PROPER REFERENCE)\n    double expectedDeltaV = 6342.0;\n    double expectedPeakAcceleration = 1.51e-4;\n\n    // DeltaV provided with a precision of 1 m/s\n    BOOST_CHECK_SMALL( std::fabs(  hodographicShaping.computeDeltaV( ) - expectedDeltaV ), 1.0 );\n    // Peak acceleration provided with a precision 1.0e-6 m/s^2\n    BOOST_CHECK_SMALL( std::fabs(  getPeakAcceleration( timeOfFlight, hodographicShaping ) - expectedPeakAcceleration ), 1e-6 );\n\n\n}\n\n\n//! Test Earth-Mercury transfer, based on the thesis by Gondelach.\nBOOST_AUTO_TEST_CASE( test_hodographic_shaping_earth_mercury_transfer )\n{\n    using namespace shape_based_methods;\n\n    /// First Earth-Mercury transfer.\n\n    int numberOfRevolutions = 1;\n    double julianDate = 5025 * physical_constants::JULIAN_DAY;\n    double timeOfFlight = 440.0;\n    double frequency = 2.0 * mathematical_constants::PI / ( timeOfFlight * physical_constants::JULIAN_DAY );\n    double scaleFactor = 1.0 / ( timeOfFlight * physical_constants::JULIAN_DAY );\n\n    // Create base function settings for the components of the radial velocity composite function.\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > firstRadialVelocityBaseFunctionSettings =\n            std::make_shared< BaseFunctionHodographicShapingSettings >( );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > secondRadialVelocityBaseFunctionSettings =\n            std::make_shared< PowerFunctionHodographicShapingSettings >( 1.0, scaleFactor );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > thirdRadialVelocityBaseFunctionSettings =\n            std::make_shared< TrigonometricFunctionHodographicShapingSettings >( frequency );\n\n    // Create components of the radial velocity composite function.\n    std::vector< std::shared_ptr< BaseFunctionHodographicShaping > > radialVelocityFunctionComponents;\n    radialVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( constant, firstRadialVelocityBaseFunctionSettings ) );\n    radialVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( scaledPower, secondRadialVelocityBaseFunctionSettings ) );\n    radialVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( cosine, thirdRadialVelocityBaseFunctionSettings ) );\n\n    // Create base function settings for the components of the normal velocity composite function.\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > firstNormalVelocityBaseFunctionSettings =\n            std::make_shared< BaseFunctionHodographicShapingSettings >( );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > secondNormalVelocityBaseFunctionSettings =\n            std::make_shared< PowerFunctionHodographicShapingSettings >( 1.0, scaleFactor );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > thirdNormalVelocityBaseFunctionSettings =\n            std::make_shared< TrigonometricFunctionHodographicShapingSettings >( frequency );\n\n    // Create components of the normal velocity composite function.\n    std::vector< std::shared_ptr< BaseFunctionHodographicShaping > > normalVelocityFunctionComponents;\n    normalVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( constant, firstNormalVelocityBaseFunctionSettings ) );\n    normalVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( scaledPower, secondNormalVelocityBaseFunctionSettings ) );\n    normalVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( cosine, thirdNormalVelocityBaseFunctionSettings ) );\n\n    // Create base function settings for the components of the axial velocity composite function.\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > firstAxialVelocityBaseFunctionSettings =\n            std::make_shared< TrigonometricFunctionHodographicShapingSettings >( ( numberOfRevolutions + 0.5 ) * frequency );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > secondAxialVelocityBaseFunctionSettings =\n            std::make_shared< PowerTimesTrigonometricFunctionHodographicShapingSettings >\n            ( 6.0, ( numberOfRevolutions + 0.5 ) * frequency, scaleFactor );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > thirdAxialVelocityBaseFunctionSettings =\n            std::make_shared< PowerTimesTrigonometricFunctionHodographicShapingSettings >(\n                6.0, ( numberOfRevolutions + 0.5 ) * frequency, scaleFactor );\n\n    // Set components for the axial velocity function.\n    std::vector< std::shared_ptr< BaseFunctionHodographicShaping > > axialVelocityFunctionComponents;\n    axialVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( cosine, firstAxialVelocityBaseFunctionSettings ) );\n    axialVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( scaledPowerCosine, secondAxialVelocityBaseFunctionSettings ) );\n    axialVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( scaledPowerSine, thirdAxialVelocityBaseFunctionSettings ) );\n\n    // Initialize free coefficients vectors\n    Eigen::VectorXd freeCoefficientsRadialVelocityFunction = Eigen::VectorXd::Zero( 0 );\n    Eigen::VectorXd freeCoefficientsNormalVelocityFunction = Eigen::VectorXd::Zero( 0 );\n    Eigen::VectorXd freeCoefficientsAxialVelocityFunction = Eigen::VectorXd::Zero( 0 );\n\n\n    // Retrieve cartesian state at departure and arrival.\n    ephemerides::EphemerisPointer pointerToDepartureBodyEphemeris = std::make_shared< ephemerides::ApproximatePlanetPositions>(\n                ephemerides::ApproximatePlanetPositionsBase::BodiesWithEphemerisData::earthMoonBarycenter );\n    ephemerides::EphemerisPointer pointerToArrivalBodyEphemeris = std::make_shared< ephemerides::ApproximatePlanetPositions >(\n                ephemerides::ApproximatePlanetPositionsBase::BodiesWithEphemerisData::mercury );\n    Eigen::Vector6d cartesianStateDepartureBody =\n            pointerToDepartureBodyEphemeris->getCartesianState( julianDate );\n    Eigen::Vector6d cartesianStateArrivalBody =\n            pointerToArrivalBodyEphemeris->getCartesianState( julianDate + timeOfFlight  * physical_constants::JULIAN_DAY );\n\n    // Create hodographic-shaping object with defined velocity functions and boundary conditions.\n    HodographicShaping hodographicShaping(\n                cartesianStateDepartureBody, cartesianStateArrivalBody,\n                timeOfFlight * physical_constants::JULIAN_DAY,\n                spice_interface::getBodyGravitationalParameter( \"Sun\" ), numberOfRevolutions,\n                radialVelocityFunctionComponents, normalVelocityFunctionComponents, axialVelocityFunctionComponents,\n                freeCoefficientsRadialVelocityFunction, freeCoefficientsNormalVelocityFunction, freeCoefficientsAxialVelocityFunction );\n\n\n    // Check results consistency w.r.t. thesis from D. Gondelach (ADD PROPER REFERENCE)\n    // The expected differences are a bit larger than for Earth-Mars transfer due to the higher uncertainty in the used Mercury ephemeris.\n    double expectedDeltaV = 28082.0;\n    double expectedPeakAcceleration = 64.1e-4;\n\n    // DeltaV provided with a precision of 1 m/s\n    BOOST_CHECK_SMALL( std::fabs(  hodographicShaping.computeDeltaV( ) - expectedDeltaV ), 100.0 );\n\n    // Peak acceleration provided with a precision 1.0e-6 m/s^2\n    BOOST_CHECK_SMALL( std::fabs(  getPeakAcceleration( timeOfFlight, hodographicShaping ) - expectedPeakAcceleration ), 1e-5 );\n\n}\n\n//    /// Second Earth-Mercury transfer.\n\n//    numberOfRevolutions = 1;\n\n//    julianDate = 5015 * physical_constants::JULIAN_DAY;\n\n//    timeOfFlight = 450.0;\n\n//    // Set vehicle mass.\n//    bodyMap[ \"Vehicle\" ]->setConstantBodyMass( 400.0 );\n\n//    // Define integrator settings.\n//    integratorSettings = std::make_shared< numerical_integrators::IntegratorSettings< double > > (\n//                numerical_integrators::rungeKutta4, 0.0, timeOfFlight * physical_constants::JULIAN_DAY / 500.0 );\n\n//    // Retrieve cartesian state at departure and arrival.\n//    cartesianStateDepartureBody = pointerToDepartureBodyEphemeris->getCartesianState( julianDate );\n//    cartesianStateArrivalBody =\n//            pointerToArrivalBodyEphemeris->getCartesianState( julianDate + timeOfFlight  * physical_constants::JULIAN_DAY );\n\n//    frequency = 2.0 * mathematical_constants::PI / ( timeOfFlight * physical_constants::JULIAN_DAY );\n\n//    scaleFactor = 1.0 / ( timeOfFlight * physical_constants::JULIAN_DAY );\n\n//    // Create base function settings for the components of the radial velocity composite function.\n//    firstRadialVelocityBaseFunctionSettings = std::make_shared< BaseFunctionHodographicShapingSettings >( );\n//    secondRadialVelocityBaseFunctionSettings = std::make_shared< PowerFunctionHodographicShapingSettings >( 1.0, scaleFactor );\n//    thirdRadialVelocityBaseFunctionSettings = std::make_shared< PowerFunctionHodographicShapingSettings >( 2.0, scaleFactor );\n\n//    // Create components of the radial velocity composite function.\n//    radialVelocityFunctionComponents.clear( );\n//    radialVelocityFunctionComponents.push_back(\n//                createBaseFunctionHodographicShaping( constant, firstRadialVelocityBaseFunctionSettings ) );\n//    radialVelocityFunctionComponents.push_back(\n//                createBaseFunctionHodographicShaping( scaledPower, secondRadialVelocityBaseFunctionSettings ) );\n//    radialVelocityFunctionComponents.push_back(\n//                createBaseFunctionHodographicShaping( scaledPower, thirdRadialVelocityBaseFunctionSettings ) );\n\n//    // Create base function settings for the components of the normal velocity composite function.\n//    firstNormalVelocityBaseFunctionSettings =\n//            std::make_shared< BaseFunctionHodographicShapingSettings >( );\n//    secondNormalVelocityBaseFunctionSettings =\n//            std::make_shared< PowerFunctionHodographicShapingSettings >( 1.0, scaleFactor );\n//    thirdNormalVelocityBaseFunctionSettings =\n//            std::make_shared< TrigonometricFunctionHodographicShapingSettings >( frequency );\n\n//    // Create components of the normal velocity composite function.\n//    normalVelocityFunctionComponents.clear( );\n//    normalVelocityFunctionComponents.push_back(\n//                createBaseFunctionHodographicShaping( constant, firstNormalVelocityBaseFunctionSettings ) );\n//    normalVelocityFunctionComponents.push_back(\n//                createBaseFunctionHodographicShaping( scaledPower, secondNormalVelocityBaseFunctionSettings ) );\n//    normalVelocityFunctionComponents.push_back(\n//                createBaseFunctionHodographicShaping( cosine, thirdNormalVelocityBaseFunctionSettings ) );\n\n\n//    // Create hodographic-shaping object with defined velocity functions and boundary conditions.\n//    hodographicShaping = HodographicShaping(\n//                cartesianStateDepartureBody, cartesianStateArrivalBody,\n//                timeOfFlight * physical_constants::JULIAN_DAY, numberOfRevolutions,\n//                bodyMap, \"Vehicle\", \"Sun\",\n//                radialVelocityFunctionComponents, normalVelocityFunctionComponents, axialVelocityFunctionComponents,\n//                freeCoefficientsRadialVelocityFunction, freeCoefficientsNormalVelocityFunction, freeCoefficientsAxialVelocityFunction,\n//                integratorSettings );\n\n//    stepSize = ( timeOfFlight * physical_constants::JULIAN_DAY ) / static_cast< double >( 500 );\n//    peakAcceleration = 0.0;\n\n//    for ( int currentStep = 0 ; currentStep <= 500 ; currentStep++ ){\n//        double currentTime = currentStep * stepSize;\n\n//        double currentAcceleration = hodographicShaping.computeThrustAccelerationVector( currentTime ).norm( );\n//        if ( currentAcceleration > peakAcceleration )\n//        {\n//            peakAcceleration = currentAcceleration;\n//        }\n\n//    }\n\n\n//    // Check results consistency w.r.t. thesis from D. Gondelach (ADD PROPER REFERENCE)\n//    // The expected differences are a bit larger than for Earth-Mars transfer due to the higher uncertainty in Mercury's ephemeris.\n//    expectedDeltaV = 26997.0;\n//    expectedPeakAcceleration = 63.5e-4;\n\n//    // DeltaV provided with a precision of 1 m/s\n//    BOOST_CHECK_SMALL( std::fabs(  hodographicShaping.computeDeltaV( ) - expectedDeltaV ), 100.0 );\n//    // Peak acceleration provided with a precision 1.0e-6 m/s^2\n//    BOOST_CHECK_SMALL( std::fabs(  peakAcceleration - expectedPeakAcceleration ), 1e-5 );\n\n\n//    /// Third Earth-Mercury transfer.\n\n//    numberOfRevolutions = 0;\n\n//    julianDate = 4675 * physical_constants::JULIAN_DAY;\n\n//    timeOfFlight = 190.0;\n\n//    // Set vehicle mass.\n//    bodyMap[ \"Vehicle\" ]->setConstantBodyMass( 400.0 );\n\n//    // Define integrator settings.\n//    integratorSettings = std::make_shared< numerical_integrators::IntegratorSettings< double > > (\n//                numerical_integrators::rungeKutta4, 0.0, timeOfFlight * physical_constants::JULIAN_DAY / 500.0 );\n\n//    // Retrieve cartesian state at departure and arrival.\n//    cartesianStateDepartureBody = pointerToDepartureBodyEphemeris->getCartesianState( julianDate );\n//    cartesianStateArrivalBody =\n//            pointerToArrivalBodyEphemeris->getCartesianState( julianDate + timeOfFlight  * physical_constants::JULIAN_DAY );\n\n//    frequency = 2.0 * mathematical_constants::PI / ( timeOfFlight * physical_constants::JULIAN_DAY );\n\n//    scaleFactor = 1.0 / ( timeOfFlight * physical_constants::JULIAN_DAY );\n\n//    // Create base function settings for the components of the radial velocity composite function.\n//    firstRadialVelocityBaseFunctionSettings = std::make_shared< BaseFunctionHodographicShapingSettings >( );\n//    secondRadialVelocityBaseFunctionSettings = std::make_shared< PowerFunctionHodographicShapingSettings >( 1.0, scaleFactor );\n//    thirdRadialVelocityBaseFunctionSettings = std::make_shared< PowerFunctionHodographicShapingSettings >( 2.0, scaleFactor );\n\n//    // Create components of the radial velocity composite function.\n//    radialVelocityFunctionComponents.clear( );\n//    radialVelocityFunctionComponents.push_back(\n//                createBaseFunctionHodographicShaping( constant, firstRadialVelocityBaseFunctionSettings ) );\n//    radialVelocityFunctionComponents.push_back(\n//                createBaseFunctionHodographicShaping( scaledPower, secondRadialVelocityBaseFunctionSettings ) );\n//    radialVelocityFunctionComponents.push_back(\n//                createBaseFunctionHodographicShaping( scaledPower, thirdRadialVelocityBaseFunctionSettings ) );\n\n//    // Create base function settings for the components of the normal velocity composite function.\n//    firstNormalVelocityBaseFunctionSettings =\n//            std::make_shared< BaseFunctionHodographicShapingSettings >( );\n//    secondNormalVelocityBaseFunctionSettings =\n//            std::make_shared< PowerFunctionHodographicShapingSettings >( 1.0, scaleFactor );\n//    thirdNormalVelocityBaseFunctionSettings =\n//            std::make_shared< TrigonometricFunctionHodographicShapingSettings >( frequency * 0.5 );\n\n//    // Create components of the normal velocity composite function.\n//    normalVelocityFunctionComponents.clear( );\n//    normalVelocityFunctionComponents.push_back(\n//                createBaseFunctionHodographicShaping( constant, firstNormalVelocityBaseFunctionSettings ) );\n//    normalVelocityFunctionComponents.push_back(\n//                createBaseFunctionHodographicShaping( scaledPower, secondNormalVelocityBaseFunctionSettings ) );\n//    normalVelocityFunctionComponents.push_back(\n//                createBaseFunctionHodographicShaping( sine, thirdNormalVelocityBaseFunctionSettings ) );\n\n\n//    // Create hodographic-shaping object with defined velocity functions and boundary conditions.\n//    hodographicShaping = HodographicShaping(\n//                cartesianStateDepartureBody, cartesianStateArrivalBody,\n//                timeOfFlight * physical_constants::JULIAN_DAY, numberOfRevolutions,\n//                bodyMap, \"Vehicle\", \"Sun\",\n//                radialVelocityFunctionComponents, normalVelocityFunctionComponents, axialVelocityFunctionComponents,\n//                freeCoefficientsRadialVelocityFunction, freeCoefficientsNormalVelocityFunction, freeCoefficientsAxialVelocityFunction,\n//                integratorSettings );\n\n//    stepSize = ( timeOfFlight * physical_constants::JULIAN_DAY ) / static_cast< double >( 500 );\n//    peakAcceleration = 0.0;\n\n//    for ( int currentStep = 0 ; currentStep <= 500 ; currentStep++ ){\n//        double currentTime = currentStep * stepSize;\n\n//        double currentAcceleration = hodographicShaping.computeThrustAccelerationVector( currentTime ).norm( );\n//        if ( currentAcceleration > peakAcceleration )\n//        {\n//            peakAcceleration = currentAcceleration;\n//        }\n\n//    }\n\n\n//    // Check results consistency w.r.t. thesis from D. Gondelach (ADD PROPER REFERENCE)\n//    // The expected differences are a bit larger than for Earth-Mars transfer due to the higher uncertainty in Mercury's ephemeris.\n//    expectedDeltaV = 22683.0;\n//    expectedPeakAcceleration = 56.0e-4;\n\n//    // DeltaV provided with a precision of 1 m/s\n//    BOOST_CHECK_SMALL( std::fabs(  hodographicShaping.computeDeltaV( ) - expectedDeltaV ), 100.0 );\n//    // Peak acceleration provided with a precision 1.0e-6 m/s^2\n//    BOOST_CHECK_SMALL( std::fabs(  peakAcceleration - expectedPeakAcceleration ), 1e-5 );\n\n\n\n//    /// Fourth Earth-Mercury transfer.\n\n//    numberOfRevolutions = 0;\n\n//    julianDate = 4675 * physical_constants::JULIAN_DAY;\n\n//    timeOfFlight = 190.0;\n\n//    // Set vehicle mass.\n//    bodyMap[ \"Vehicle\" ]->setConstantBodyMass( 400.0 );\n\n//    // Define integrator settings.\n//    integratorSettings = std::make_shared< numerical_integrators::IntegratorSettings< double > > (\n//                numerical_integrators::rungeKutta4, 0.0, timeOfFlight * physical_constants::JULIAN_DAY / 500.0 );\n\n//    // Retrieve cartesian state at departure and arrival.\n//    cartesianStateDepartureBody = pointerToDepartureBodyEphemeris->getCartesianState( julianDate );\n//    cartesianStateArrivalBody =\n//            pointerToArrivalBodyEphemeris->getCartesianState( julianDate + timeOfFlight  * physical_constants::JULIAN_DAY );\n\n//    frequency = 2.0 * mathematical_constants::PI / ( timeOfFlight * physical_constants::JULIAN_DAY );\n\n//    scaleFactor = 1.0 / ( timeOfFlight * physical_constants::JULIAN_DAY );\n\n//    // Create base function settings for the components of the radial velocity composite function.\n//    firstRadialVelocityBaseFunctionSettings = std::make_shared< BaseFunctionHodographicShapingSettings >( );\n//    secondRadialVelocityBaseFunctionSettings = std::make_shared< PowerFunctionHodographicShapingSettings >( 1.0, scaleFactor );\n//    thirdRadialVelocityBaseFunctionSettings = std::make_shared< TrigonometricFunctionHodographicShapingSettings >( frequency * 0.5 );\n\n//    // Create components of the radial velocity composite function.\n//    radialVelocityFunctionComponents.clear( );\n//    radialVelocityFunctionComponents.push_back(\n//                createBaseFunctionHodographicShaping( constant, firstRadialVelocityBaseFunctionSettings ) );\n//    radialVelocityFunctionComponents.push_back(\n//                createBaseFunctionHodographicShaping( scaledPower, secondRadialVelocityBaseFunctionSettings ) );\n//    radialVelocityFunctionComponents.push_back(\n//                createBaseFunctionHodographicShaping( sine, thirdRadialVelocityBaseFunctionSettings ) );\n\n//    // Create base function settings for the components of the normal velocity composite function.\n//    firstNormalVelocityBaseFunctionSettings = std::make_shared< BaseFunctionHodographicShapingSettings >( );\n//    secondNormalVelocityBaseFunctionSettings = std::make_shared< PowerFunctionHodographicShapingSettings >( 1.0, scaleFactor );\n//    thirdNormalVelocityBaseFunctionSettings = std::make_shared< TrigonometricFunctionHodographicShapingSettings >( 0.5 * frequency );\n\n//    // Create components of the normal velocity composite function.\n//    normalVelocityFunctionComponents.clear( );\n//    normalVelocityFunctionComponents.push_back(\n//                createBaseFunctionHodographicShaping( constant, firstNormalVelocityBaseFunctionSettings ) );\n//    normalVelocityFunctionComponents.push_back(\n//                createBaseFunctionHodographicShaping( scaledPower, secondNormalVelocityBaseFunctionSettings ) );\n//    normalVelocityFunctionComponents.push_back(\n//                createBaseFunctionHodographicShaping( sine, thirdNormalVelocityBaseFunctionSettings ) );\n\n\n//    // Create hodographic-shaping object with defined velocity functions and boundary conditions.\n//    hodographicShaping = HodographicShaping(\n//                cartesianStateDepartureBody, cartesianStateArrivalBody,\n//                timeOfFlight * physical_constants::JULIAN_DAY, numberOfRevolutions,\n//                bodyMap, \"Vehicle\", \"Sun\",\n//                radialVelocityFunctionComponents, normalVelocityFunctionComponents, axialVelocityFunctionComponents,\n//                freeCoefficientsRadialVelocityFunction, freeCoefficientsNormalVelocityFunction, freeCoefficientsAxialVelocityFunction,\n//                integratorSettings );\n\n//    stepSize = ( timeOfFlight * physical_constants::JULIAN_DAY ) / static_cast< double >( 500 );\n//    peakAcceleration = 0.0;\n\n//    for ( int currentStep = 0 ; currentStep <= 500 ; currentStep++ ){\n//        double currentTime = currentStep * stepSize;\n\n//        double currentAcceleration = hodographicShaping.computeThrustAccelerationVector( currentTime ).norm( );\n//        if ( currentAcceleration > peakAcceleration )\n//        {\n//            peakAcceleration = currentAcceleration;\n//        }\n\n//    }\n\n\n//    // Check results consistency w.r.t. thesis from D. Gondelach (ADD PROPER REFERENCE)\n//    // The expected differences are a bit larger than for Earth-Mars transfer due to the higher uncertainty in Mercury's ephemeris.\n//    expectedDeltaV = 22613.0;\n//    expectedPeakAcceleration = 56.0e-4;\n\n//    // DeltaV provided with a precision of 1 m/s\n//    BOOST_CHECK_SMALL( std::fabs(  hodographicShaping.computeDeltaV( ) - expectedDeltaV ), 100.0 );\n//    // Peak acceleration provided with a precision 1.0e-6 m/s^2\n//    BOOST_CHECK_SMALL( std::fabs(  peakAcceleration - expectedPeakAcceleration ), 1e-5 );\n\n\n\n//    /// Fifth Earth-Mercury transfer.\n\n//    numberOfRevolutions = 0;\n\n//    julianDate = 4355 * physical_constants::JULIAN_DAY;\n\n//    timeOfFlight = 160.0;\n\n//    // Set vehicle mass.\n//    bodyMap[ \"Vehicle\" ]->setConstantBodyMass( 400.0 );\n\n//    // Define integrator settings.\n//    integratorSettings = std::make_shared< numerical_integrators::IntegratorSettings< double > > (\n//                numerical_integrators::rungeKutta4, 0.0, timeOfFlight * physical_constants::JULIAN_DAY / 500.0 );\n\n//    // Retrieve cartesian state at departure and arrival.\n//    cartesianStateDepartureBody = pointerToDepartureBodyEphemeris->getCartesianState( julianDate );\n//    cartesianStateArrivalBody =\n//            pointerToArrivalBodyEphemeris->getCartesianState( julianDate + timeOfFlight  * physical_constants::JULIAN_DAY );\n\n//    frequency = 2.0 * mathematical_constants::PI / ( timeOfFlight * physical_constants::JULIAN_DAY );\n\n//    scaleFactor = 1.0 / ( timeOfFlight * physical_constants::JULIAN_DAY );\n\n//    // Create base function settings for the components of the radial velocity composite function.\n//    firstRadialVelocityBaseFunctionSettings = std::make_shared< BaseFunctionHodographicShapingSettings >( );\n//    secondRadialVelocityBaseFunctionSettings = std::make_shared< PowerFunctionHodographicShapingSettings >( 1.0, scaleFactor );\n//    thirdRadialVelocityBaseFunctionSettings = std::make_shared< PowerFunctionHodographicShapingSettings >( 2.0, scaleFactor );\n\n//    // Create components of the radial velocity composite function.\n//    radialVelocityFunctionComponents.clear( );\n//    radialVelocityFunctionComponents.push_back(\n//                createBaseFunctionHodographicShaping( constant, firstRadialVelocityBaseFunctionSettings ) );\n//    radialVelocityFunctionComponents.push_back(\n//                createBaseFunctionHodographicShaping( scaledPower, secondRadialVelocityBaseFunctionSettings ) );\n//    radialVelocityFunctionComponents.push_back(\n//                createBaseFunctionHodographicShaping( scaledPower, thirdRadialVelocityBaseFunctionSettings ) );\n\n//    // Create base function settings for the components of the normal velocity composite function.\n//    firstNormalVelocityBaseFunctionSettings = std::make_shared< BaseFunctionHodographicShapingSettings >( );\n//    secondNormalVelocityBaseFunctionSettings = std::make_shared< PowerFunctionHodographicShapingSettings >( 1.0, scaleFactor );\n//    thirdNormalVelocityBaseFunctionSettings = std::make_shared< PowerFunctionHodographicShapingSettings >( 2.0, scaleFactor );\n\n//    // Create components of the normal velocity composite function.\n//    normalVelocityFunctionComponents.clear( );\n//    normalVelocityFunctionComponents.push_back(\n//                createBaseFunctionHodographicShaping( constant, firstNormalVelocityBaseFunctionSettings ) );\n//    normalVelocityFunctionComponents.push_back(\n//                createBaseFunctionHodographicShaping( scaledPower, secondNormalVelocityBaseFunctionSettings ) );\n//    normalVelocityFunctionComponents.push_back(\n//                createBaseFunctionHodographicShaping( scaledPower, thirdNormalVelocityBaseFunctionSettings ) );\n\n\n//    // Create hodographic-shaping object with defined velocity functions and boundary conditions.\n//    hodographicShaping = HodographicShaping(\n//                cartesianStateDepartureBody, cartesianStateArrivalBody,\n//                timeOfFlight * physical_constants::JULIAN_DAY, numberOfRevolutions,\n//                bodyMap, \"Vehicle\", \"Sun\",\n//                radialVelocityFunctionComponents, normalVelocityFunctionComponents, axialVelocityFunctionComponents,\n//                freeCoefficientsRadialVelocityFunction, freeCoefficientsNormalVelocityFunction, freeCoefficientsAxialVelocityFunction,\n//                integratorSettings );\n\n//    stepSize = ( timeOfFlight * physical_constants::JULIAN_DAY ) / static_cast< double >( 500 );\n//    peakAcceleration = 0.0;\n\n//    for ( int currentStep = 0 ; currentStep <= 500 ; currentStep++ ){\n//        double currentTime = currentStep * stepSize;\n\n//        double currentAcceleration = hodographicShaping.computeThrustAccelerationVector( currentTime ).norm( );\n//        if ( currentAcceleration > peakAcceleration )\n//        {\n//            peakAcceleration = currentAcceleration;\n//        }\n\n//    }\n\n\n//    // Check results consistency w.r.t. thesis from D. Gondelach (ADD PROPER REFERENCE)\n//    // The expected differences are a bit larger than for Earth-Mars transfer due to the higher uncertainty in Mercury's ephemeris.\n//    expectedDeltaV = 21766.0;\n//    expectedPeakAcceleration = 50.3e-4;\n\n//    // DeltaV provided with a precision of 1 m/s\n//    BOOST_CHECK_SMALL( std::fabs(  hodographicShaping.computeDeltaV( ) - expectedDeltaV ), 100.0 );\n//    // Peak acceleration provided with a precision 1.0e-6 m/s^2\n//    BOOST_CHECK_SMALL( std::fabs(  peakAcceleration - expectedPeakAcceleration ), 1e-5 );\n\n//}\n\nNamedBodyMap getTestBodyMap( )\n{\n    spice_interface::loadStandardSpiceKernels( );\n\n    // Create central, departure and arrival bodies.\n    std::vector< std::string > bodiesToCreate;\n    bodiesToCreate.push_back( \"Sun\" );\n    bodiesToCreate.push_back( \"Earth\" );\n    bodiesToCreate.push_back( \"Mars\" );\n    bodiesToCreate.push_back( \"Jupiter\" );\n\n    std::map< std::string, std::shared_ptr< BodySettings > > bodySettings =\n            getDefaultBodySettings( bodiesToCreate );\n\n    std::string frameOrigin = \"SSB\";\n    std::string frameOrientation = \"ECLIPJ2000\";\n\n\n    // Define central body ephemeris settings.\n    bodySettings[ \"Sun\" ]->ephemerisSettings = std::make_shared< ConstantEphemerisSettings >(\n                ( Eigen::Vector6d( ) << 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 ).finished( ), frameOrigin, frameOrientation );\n\n    bodySettings[ \"Sun\" ]->ephemerisSettings->resetFrameOrientation( frameOrientation );\n    bodySettings[ \"Sun\" ]->rotationModelSettings->resetOriginalFrame( frameOrientation );\n\n\n    // Create body map.\n    NamedBodyMap bodyMap = createBodies( bodySettings );\n\n    bodyMap[ \"Vehicle\" ] = std::make_shared< Body >( );\n    bodyMap.at( \"Vehicle\" )->setEphemeris( std::make_shared< ephemerides::TabulatedCartesianEphemeris< > >(\n                                               std::shared_ptr< interpolators::OneDimensionalInterpolator\n                                               < double, Eigen::Vector6d > >( ), frameOrigin, frameOrientation ) );\n\n\n    setGlobalFrameBodyEphemerides( bodyMap, frameOrigin, frameOrientation );\n    return bodyMap;\n}\n\n//! Test.\nBOOST_AUTO_TEST_CASE( test_hodographic_shaping_full_propagation )\n{\n\n    double numberOfRevolutions = 1.0;\n    double julianDate = 2458849.5;\n    double timeOfFlight = 500.0;\n    double frequency = 2.0 * mathematical_constants::PI / ( timeOfFlight * physical_constants::JULIAN_DAY );\n    double scaleFactor = 1.0 / ( timeOfFlight * physical_constants::JULIAN_DAY );\n\n    // Create base function settings for the components of the radial velocity composite function.\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > firstRadialVelocityBaseFunctionSettings =\n            std::make_shared< BaseFunctionHodographicShapingSettings >( );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > secondRadialVelocityBaseFunctionSettings =\n            std::make_shared< PowerFunctionHodographicShapingSettings >( 1.0, scaleFactor );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > thirdRadialVelocityBaseFunctionSettings =\n            std::make_shared< PowerFunctionHodographicShapingSettings >( 2.0, scaleFactor );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > fourthRadialVelocityBaseFunctionSettings =\n            std::make_shared< PowerTimesTrigonometricFunctionHodographicShapingSettings >( 1.0, 0.5 * frequency, scaleFactor );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > fifthRadialVelocityBaseFunctionSettings =\n            std::make_shared< PowerTimesTrigonometricFunctionHodographicShapingSettings >( 1.0, 0.5 * frequency, scaleFactor );\n\n    // Create components of the radial velocity composite function.\n    std::vector< std::shared_ptr< BaseFunctionHodographicShaping > > radialVelocityFunctionComponents;\n    radialVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( constant, firstRadialVelocityBaseFunctionSettings ) );\n    radialVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( scaledPower, secondRadialVelocityBaseFunctionSettings ) );\n    radialVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( scaledPower, thirdRadialVelocityBaseFunctionSettings ) );\n    radialVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( scaledPowerSine, fourthRadialVelocityBaseFunctionSettings ) );\n    radialVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( scaledPowerCosine, fifthRadialVelocityBaseFunctionSettings ) );\n\n    // Create base function settings for the components of the normal velocity composite function.\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > firstNormalVelocityBaseFunctionSettings =\n            std::make_shared< BaseFunctionHodographicShapingSettings >( );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > secondNormalVelocityBaseFunctionSettings =\n            std::make_shared< PowerFunctionHodographicShapingSettings >( 1.0, scaleFactor );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > thirdNormalVelocityBaseFunctionSettings =\n            std::make_shared< PowerFunctionHodographicShapingSettings >( 2.0, scaleFactor );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > fourthNormalVelocityBaseFunctionSettings =\n            std::make_shared< PowerTimesTrigonometricFunctionHodographicShapingSettings >( 1.0, 0.5 * frequency, scaleFactor );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > fifthNormalVelocityBaseFunctionSettings =\n            std::make_shared< PowerTimesTrigonometricFunctionHodographicShapingSettings >( 1.0, 0.5 * frequency, scaleFactor );\n\n    // Create components of the normal velocity composite function.\n    std::vector< std::shared_ptr< BaseFunctionHodographicShaping > > normalVelocityFunctionComponents;\n    normalVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( constant, firstNormalVelocityBaseFunctionSettings ) );\n    normalVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( scaledPower, secondNormalVelocityBaseFunctionSettings ) );\n    normalVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( scaledPower, thirdNormalVelocityBaseFunctionSettings ) );\n    normalVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( scaledPowerSine, fourthNormalVelocityBaseFunctionSettings ) );\n    normalVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( scaledPowerCosine, fifthNormalVelocityBaseFunctionSettings ) );\n\n    // Create base function settings for the components of the axial velocity composite function.\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > firstAxialVelocityBaseFunctionSettings =\n            std::make_shared< TrigonometricFunctionHodographicShapingSettings >( ( numberOfRevolutions + 0.5 ) * frequency );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > secondAxialVelocityBaseFunctionSettings =\n            std::make_shared< PowerTimesTrigonometricFunctionHodographicShapingSettings >\n            ( 3.0, ( numberOfRevolutions + 0.5 ) * frequency, scaleFactor );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > thirdAxialVelocityBaseFunctionSettings =\n            std::make_shared< PowerTimesTrigonometricFunctionHodographicShapingSettings >(\n                3.0, ( numberOfRevolutions + 0.5 ) * frequency, scaleFactor );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > fourthAxialVelocityBaseFunctionSettings =\n            std::make_shared< PowerTimesTrigonometricFunctionHodographicShapingSettings >(\n                4.0, ( numberOfRevolutions + 0.5 ) * frequency, scaleFactor );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > fifthAxialVelocityBaseFunctionSettings =\n            std::make_shared< PowerTimesTrigonometricFunctionHodographicShapingSettings >(\n                4.0, ( numberOfRevolutions + 0.5 ) * frequency, scaleFactor );\n\n    // Set components for the axial velocity function.\n    std::vector< std::shared_ptr< BaseFunctionHodographicShaping > > axialVelocityFunctionComponents;\n    axialVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( cosine, firstAxialVelocityBaseFunctionSettings ) );\n    axialVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( scaledPowerCosine, secondAxialVelocityBaseFunctionSettings ) );\n    axialVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( scaledPowerSine, thirdAxialVelocityBaseFunctionSettings ) );\n    axialVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( scaledPowerCosine, fourthAxialVelocityBaseFunctionSettings ) );\n    axialVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( scaledPowerSine, fifthAxialVelocityBaseFunctionSettings ) );\n\n    // Initialize free coefficients vector for radial velocity function.\n    Eigen::VectorXd freeCoefficientsRadialVelocityFunction = Eigen::VectorXd::Zero( 2 );\n    freeCoefficientsRadialVelocityFunction[ 0 ] = 500.0;\n    freeCoefficientsRadialVelocityFunction[ 1 ] = 500.0;\n\n    // Initialize free coefficients vector for normal velocity function.\n    Eigen::VectorXd freeCoefficientsNormalVelocityFunction = Eigen::VectorXd::Zero( 2 );\n    freeCoefficientsNormalVelocityFunction[ 0 ] = 500.0;\n    freeCoefficientsNormalVelocityFunction[ 1 ] = -200.0;\n\n    // Initialize free coefficients vector for axial velocity function.\n    Eigen::VectorXd freeCoefficientsAxialVelocityFunction = Eigen::VectorXd::Zero( 2 );\n    freeCoefficientsAxialVelocityFunction[ 0 ] = 500.0;\n    freeCoefficientsAxialVelocityFunction[ 1 ] = 2000.0;\n\n\n    // Retrieve cartesian state at departure and arrival.\n    ephemerides::EphemerisPointer pointerToDepartureBodyEphemeris = std::make_shared< ephemerides::ApproximatePlanetPositions>(\n                ephemerides::ApproximatePlanetPositionsBase::BodiesWithEphemerisData::earthMoonBarycenter );\n    ephemerides::EphemerisPointer pointerToArrivalBodyEphemeris = std::make_shared< ephemerides::ApproximatePlanetPositions >(\n                ephemerides::ApproximatePlanetPositionsBase::BodiesWithEphemerisData::mars );\n    Eigen::Vector6d cartesianStateDepartureBody = pointerToDepartureBodyEphemeris->getCartesianState( julianDate );\n    Eigen::Vector6d cartesianStateArrivalBody =\n            pointerToArrivalBodyEphemeris->getCartesianState( julianDate + timeOfFlight * physical_constants::JULIAN_DAY );\n\n    // Create hodographic-shaping object with defined velocity functions and boundary conditions.\n    HodographicShaping hodographicShaping(\n                cartesianStateDepartureBody, cartesianStateArrivalBody,\n                timeOfFlight * physical_constants::JULIAN_DAY,\n                spice_interface::getBodyGravitationalParameter( \"Sun\" ), numberOfRevolutions,\n                radialVelocityFunctionComponents, normalVelocityFunctionComponents, axialVelocityFunctionComponents,\n                freeCoefficientsRadialVelocityFunction, freeCoefficientsNormalVelocityFunction, freeCoefficientsAxialVelocityFunction );\n\n    // Create environment\n    NamedBodyMap bodyMap = getTestBodyMap( );\n\n    // Define mass function of the vehicle.\n    std::function< double( const double ) > newMassFunction = [ = ]( const double ){ return 2000.0; }; // - 50.0 / ( timeOfFlight * physical_constants::JULIAN_DAY ) * currentTime ;\n    bodyMap[ \"Vehicle\" ]->setBodyMassFunction( newMassFunction );\n\n    // Define integrator settings.\n    std::shared_ptr< numerical_integrators::IntegratorSettings< double > > integratorSettings =\n            std::make_shared< numerical_integrators::IntegratorSettings< double > > (\n                numerical_integrators::rungeKutta4, 0.0,  timeOfFlight * physical_constants::JULIAN_DAY / 1000.0 );\n\n    // Create object with list of dependent variables\n    std::vector< std::shared_ptr< SingleDependentVariableSaveSettings > > dependentVariablesList;\n    dependentVariablesList.push_back( std::make_shared< SingleAccelerationDependentVariableSaveSettings >(\n                                          basic_astrodynamics::thrust_acceleration, \"Vehicle\", \"Vehicle\", 0 ) );\n    std::shared_ptr< DependentVariableSaveSettings > dependentVariablesToSave =\n            std::make_shared< DependentVariableSaveSettings >( dependentVariablesList, false );\n\n    // Create termination conditions settings.\n    std::pair< std::shared_ptr< PropagationTerminationSettings >,\n            std::shared_ptr< PropagationTerminationSettings > > terminationConditions = std::make_pair(\n                std::make_shared< PropagationTimeTerminationSettings >( 0.0 ),\n                std::make_shared< PropagationTimeTerminationSettings >( timeOfFlight * physical_constants::JULIAN_DAY ) );\n\n    // Create complete propagation settings (backward and forward propagations).\n    std::function< double( const double ) > specificImpulseFunction = [ = ]( const double ){ return 3000.0; };\n    basic_astrodynamics::AccelerationMap lowThrustAccelerationsMap =\n            hodographicShaping.retrieveLowThrustAccelerationMap(\n                bodyMap, \"Vehicle\", \"Sun\", specificImpulseFunction, integratorSettings );\n\n    std::pair< std::shared_ptr< PropagatorSettings< double > >,\n            std::shared_ptr< PropagatorSettings< double > > > propagatorSettings =\n            hodographicShaping.createLowThrustTranslationalStatePropagatorSettings(\n                \"Vehicle\", \"Sun\", lowThrustAccelerationsMap, dependentVariablesToSave );\n\n    // Compute shaped trajectory and propagated trajectory.\n    std::map< double, Eigen::VectorXd > fullPropagationResults;\n    std::map< double, Eigen::Vector6d > shapingMethodResults;\n    std::map< double, Eigen::VectorXd > dependentVariablesHistory;\n    hodographicShaping.computeSemiAnalyticalAndFullPropagation(\n                bodyMap, integratorSettings, propagatorSettings,\n                fullPropagationResults, shapingMethodResults, dependentVariablesHistory );\n\n    // Check that boundary conditions are still fulfilled when free parameters are added.\n    for ( int i = 0 ; i < 6 ; i++ )\n    {\n        BOOST_CHECK_SMALL( std::fabs( shapingMethodResults.begin( )->second[ i ] - cartesianStateDepartureBody[ i ] )\n                           / shapingMethodResults.begin( )->second[ i ], 1.0e-8 );\n        BOOST_CHECK_SMALL( std::fabs( shapingMethodResults.rbegin( )->second[ i ] - cartesianStateArrivalBody[ i ] )\n                           / shapingMethodResults.rbegin( )->second[ i ], 1.0e-8 );\n    }\n\n    // Check results consistency between full propagation and shaped trajectory at departure and arrival.\n    for ( int i = 0 ; i < 6 ; i++ )\n    {\n        BOOST_CHECK_SMALL( std::fabs( shapingMethodResults.begin( )->second[ i ] - fullPropagationResults.begin( )->second[ i ] )\n                           / shapingMethodResults.begin( )->second[ i ], 2.0e-7 );\n        BOOST_CHECK_SMALL( std::fabs( shapingMethodResults.rbegin( )->second[ i ] - fullPropagationResults.rbegin( )->second[ i ] )\n                           / shapingMethodResults.rbegin( )->second[ i ], 2.0e-7 );\n    }\n\n}\n\n\n//! Test full propagation while propagating the spacecraft mass too.\nBOOST_AUTO_TEST_CASE( test_hodographic_shaping_full_propagation_mass_propagation )\n{\n    double numberOfRevolutions = 1.0;\n    double julianDate = 2458849.5;\n    double timeOfFlight = 500.0;\n    double initialBodyMass = 2000.0;\n    double frequency = 2.0 * mathematical_constants::PI / ( timeOfFlight * physical_constants::JULIAN_DAY );\n    double scaleFactor = 1.0 / ( timeOfFlight * physical_constants::JULIAN_DAY );\n\n    std::function< double( const double ) > specificImpulseFunction = [ = ]( const double )\n    { return 3000.0; };\n\n    // Retrieve cartesian state at departure and arrival.\n    ephemerides::EphemerisPointer pointerToDepartureBodyEphemeris = std::make_shared< ephemerides::ApproximatePlanetPositions>(\n                ephemerides::ApproximatePlanetPositionsBase::BodiesWithEphemerisData::earthMoonBarycenter );\n    ephemerides::EphemerisPointer pointerToArrivalBodyEphemeris = std::make_shared< ephemerides::ApproximatePlanetPositions >(\n                ephemerides::ApproximatePlanetPositionsBase::BodiesWithEphemerisData::mars );\n    Eigen::Vector6d cartesianStateDepartureBody =\n            pointerToDepartureBodyEphemeris->getCartesianState( julianDate );\n    Eigen::Vector6d cartesianStateArrivalBody =\n            pointerToArrivalBodyEphemeris->getCartesianState( julianDate + timeOfFlight * physical_constants::JULIAN_DAY );\n\n    // Create base function settings for the components of the radial velocity composite function.\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > firstRadialVelocityBaseFunctionSettings =\n            std::make_shared< BaseFunctionHodographicShapingSettings >( );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > secondRadialVelocityBaseFunctionSettings =\n            std::make_shared< PowerFunctionHodographicShapingSettings >( 1.0, scaleFactor );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > thirdRadialVelocityBaseFunctionSettings =\n            std::make_shared< PowerFunctionHodographicShapingSettings >( 2.0, scaleFactor );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > fourthRadialVelocityBaseFunctionSettings =\n            std::make_shared< PowerTimesTrigonometricFunctionHodographicShapingSettings >( 1.0, 0.5 * frequency, scaleFactor );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > fifthRadialVelocityBaseFunctionSettings =\n            std::make_shared< PowerTimesTrigonometricFunctionHodographicShapingSettings >( 1.0, 0.5 * frequency, scaleFactor );\n\n    // Create components of the radial velocity composite function.\n    std::vector< std::shared_ptr< BaseFunctionHodographicShaping > > radialVelocityFunctionComponents;\n    radialVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( constant, firstRadialVelocityBaseFunctionSettings ) );\n    radialVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( scaledPower, secondRadialVelocityBaseFunctionSettings ) );\n    radialVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( scaledPower, thirdRadialVelocityBaseFunctionSettings ) );\n    radialVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( scaledPowerSine, fourthRadialVelocityBaseFunctionSettings ) );\n    radialVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( scaledPowerCosine, fifthRadialVelocityBaseFunctionSettings ) );\n\n    // Create base function settings for the components of the normal velocity composite function.\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > firstNormalVelocityBaseFunctionSettings =\n            std::make_shared< BaseFunctionHodographicShapingSettings >( );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > secondNormalVelocityBaseFunctionSettings =\n            std::make_shared< PowerFunctionHodographicShapingSettings >( 1.0, scaleFactor );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > thirdNormalVelocityBaseFunctionSettings =\n            std::make_shared< PowerFunctionHodographicShapingSettings >( 2.0, scaleFactor );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > fourthNormalVelocityBaseFunctionSettings =\n            std::make_shared< PowerTimesTrigonometricFunctionHodographicShapingSettings >( 1.0, 0.5 * frequency, scaleFactor );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > fifthNormalVelocityBaseFunctionSettings =\n            std::make_shared< PowerTimesTrigonometricFunctionHodographicShapingSettings >( 1.0, 0.5 * frequency, scaleFactor );\n\n    // Create components of the normal velocity composite function.\n    std::vector< std::shared_ptr< BaseFunctionHodographicShaping > > normalVelocityFunctionComponents;\n    normalVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( constant, firstNormalVelocityBaseFunctionSettings ) );\n    normalVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( scaledPower, secondNormalVelocityBaseFunctionSettings ) );\n    normalVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( scaledPower, thirdNormalVelocityBaseFunctionSettings ) );\n    normalVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( scaledPowerSine, fourthNormalVelocityBaseFunctionSettings ) );\n    normalVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( scaledPowerCosine, fifthNormalVelocityBaseFunctionSettings ) );\n\n    // Create base function settings for the components of the axial velocity composite function.\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > firstAxialVelocityBaseFunctionSettings =\n            std::make_shared< TrigonometricFunctionHodographicShapingSettings >( ( numberOfRevolutions + 0.5 ) * frequency );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > secondAxialVelocityBaseFunctionSettings =\n            std::make_shared< PowerTimesTrigonometricFunctionHodographicShapingSettings >\n            ( 3.0, ( numberOfRevolutions + 0.5 ) * frequency, scaleFactor );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > thirdAxialVelocityBaseFunctionSettings =\n            std::make_shared< PowerTimesTrigonometricFunctionHodographicShapingSettings >(\n                3.0, ( numberOfRevolutions + 0.5 ) * frequency, scaleFactor );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > fourthAxialVelocityBaseFunctionSettings =\n            std::make_shared< PowerTimesTrigonometricFunctionHodographicShapingSettings >(\n                4.0, ( numberOfRevolutions + 0.5 ) * frequency, scaleFactor );\n    std::shared_ptr< BaseFunctionHodographicShapingSettings > fifthAxialVelocityBaseFunctionSettings =\n            std::make_shared< PowerTimesTrigonometricFunctionHodographicShapingSettings >(\n                4.0, ( numberOfRevolutions + 0.5 ) * frequency, scaleFactor );\n\n    // Set components for the axial velocity function.\n    std::vector< std::shared_ptr< BaseFunctionHodographicShaping > > axialVelocityFunctionComponents;\n    axialVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( cosine, firstAxialVelocityBaseFunctionSettings ) );\n    axialVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( scaledPowerCosine, secondAxialVelocityBaseFunctionSettings ) );\n    axialVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( scaledPowerSine, thirdAxialVelocityBaseFunctionSettings ) );\n    axialVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( scaledPowerCosine, fourthAxialVelocityBaseFunctionSettings ) );\n    axialVelocityFunctionComponents.push_back(\n                createBaseFunctionHodographicShaping( scaledPowerSine, fifthAxialVelocityBaseFunctionSettings ) );\n\n    // Initialize free coefficients vector for radial velocity function.\n    Eigen::VectorXd freeCoefficientsRadialVelocityFunction = Eigen::VectorXd::Zero( 2 );\n    freeCoefficientsRadialVelocityFunction[ 0 ] = 500.0;\n    freeCoefficientsRadialVelocityFunction[ 1 ] = 500.0;\n\n    // Initialize free coefficients vector for normal velocity function.\n    Eigen::VectorXd freeCoefficientsNormalVelocityFunction = Eigen::VectorXd::Zero( 2 );\n    freeCoefficientsNormalVelocityFunction[ 0 ] = 500.0;\n    freeCoefficientsNormalVelocityFunction[ 1 ] = - 200.0;\n\n    // Initialize free coefficients vector for axial velocity function.\n    Eigen::VectorXd freeCoefficientsAxialVelocityFunction = Eigen::VectorXd::Zero( 2 );\n    freeCoefficientsAxialVelocityFunction[ 0 ] = 500.0;\n    freeCoefficientsAxialVelocityFunction[ 1 ] = 2000.0;\n\n\n    // Create hodographic-shaping object with defined velocity functions and boundary conditions.\n    HodographicShaping hodographicShaping(\n                cartesianStateDepartureBody, cartesianStateArrivalBody,\n                timeOfFlight * physical_constants::JULIAN_DAY,\n                spice_interface::getBodyGravitationalParameter( \"Sun\" ), 1,\n                radialVelocityFunctionComponents, normalVelocityFunctionComponents, axialVelocityFunctionComponents,\n                freeCoefficientsRadialVelocityFunction, freeCoefficientsNormalVelocityFunction, freeCoefficientsAxialVelocityFunction,\n                initialBodyMass );\n\n    // Create environment\n    NamedBodyMap bodyMap = getTestBodyMap( );\n    bodyMap[ \"Vehicle\" ]->setConstantBodyMass( initialBodyMass );\n\n    // Define integrator settings.\n    double stepSize = ( timeOfFlight * physical_constants::JULIAN_DAY ) / static_cast< double >( 50 );\n    std::shared_ptr< numerical_integrators::IntegratorSettings< double > > integratorSettings =\n            std::make_shared< numerical_integrators::IntegratorSettings< double > >(\n                numerical_integrators::rungeKutta4, 0.0, stepSize / 400.0 );\n\n\n    // Define list of dependent variables to save.\n    std::vector< std::shared_ptr< SingleDependentVariableSaveSettings > > dependentVariablesList;\n    dependentVariablesList.push_back( std::make_shared< SingleAccelerationDependentVariableSaveSettings >(\n                                          basic_astrodynamics::thrust_acceleration, \"Vehicle\", \"Vehicle\", 0 ) );\n    dependentVariablesList.push_back( std::make_shared< SingleDependentVariableSaveSettings >(\n                                          total_mass_rate_dependent_variables, \"Vehicle\" ) );\n\n    // Create object with list of dependent variables\n    std::shared_ptr< DependentVariableSaveSettings > dependentVariablesToSave =\n            std::make_shared< DependentVariableSaveSettings >( dependentVariablesList, false );\n\n    // Create termination conditions settings.\n    std::pair< std::shared_ptr< PropagationTerminationSettings >, std::shared_ptr< PropagationTerminationSettings > > terminationConditions;\n    terminationConditions.first = std::make_shared< PropagationTimeTerminationSettings >( 0.0 );\n    terminationConditions.second = std::make_shared< PropagationTimeTerminationSettings >( timeOfFlight * physical_constants::JULIAN_DAY );\n\n    // Create complete propagation settings (backward and forward propagations).\n    std::pair< std::shared_ptr< PropagatorSettings< double > >,\n            std::shared_ptr< PropagatorSettings< double > > > propagatorSettings = hodographicShaping.createLowThrustPropagatorSettings(\n                bodyMap, \"Vehicle\", \"Sun\", specificImpulseFunction, basic_astrodynamics::AccelerationMap( ), integratorSettings,\n                dependentVariablesToSave );\n\n    // Compute shaped trajectory and propagated trajectory.\n    std::map< double, Eigen::VectorXd > fullPropagationResults;\n    std::map< double, Eigen::Vector6d > shapingMethodResults;\n    std::map< double, Eigen::VectorXd > dependentVariablesHistory;\n    hodographicShaping.computeSemiAnalyticalAndFullPropagation(\n                bodyMap, integratorSettings, propagatorSettings,\n                fullPropagationResults, shapingMethodResults, dependentVariablesHistory );\n\n    // Check that boundary conditions are still fulfilled when free parameters are added.\n    for ( int i = 0 ; i < 6 ; i++ )\n    {\n        BOOST_CHECK_SMALL( std::fabs( shapingMethodResults.begin( )->second[ i ] - cartesianStateDepartureBody[ i ] )\n                           / shapingMethodResults.begin( )->second[ i ], 1.0e-8 );\n        BOOST_CHECK_SMALL( std::fabs( shapingMethodResults.rbegin( )->second[ i ] - cartesianStateArrivalBody[ i ] )\n                           / shapingMethodResults.rbegin( )->second[ i ], 1.0e-8 );\n    }\n\n    // Check results consistency between full propagation and shaped trajectory at departure and arrival.\n    for ( int i = 0 ; i < 6 ; i++ )\n    {\n        BOOST_CHECK_SMALL( std::fabs( shapingMethodResults.begin( )->second[ i ] - fullPropagationResults.begin( )->second[ i ] )\n                           / shapingMethodResults.begin( )->second[ i ], 2.0e-7 );\n        BOOST_CHECK_SMALL( std::fabs( shapingMethodResults.rbegin( )->second[ i ] - fullPropagationResults.rbegin( )->second[ i ] )\n                           / shapingMethodResults.rbegin( )->second[ i ], 2.0e-7 );\n    }\n\n    // Check consistency between current and expected mass rates.\n    for ( std::map< double, Eigen::VectorXd >::iterator itr = dependentVariablesHistory.begin( ) ; itr != dependentVariablesHistory.end( ) ; itr++ )\n    {\n        Eigen::Vector3d currentThrustVector = itr->second.segment( 0, 3 );\n        double currentMass = fullPropagationResults.at( itr->first )( 6 );\n        double currentMassRate = - itr->second( 3 );\n        double expectedMassRate = currentThrustVector.norm( ) * currentMass /\n                ( specificImpulseFunction( itr->first ) * physical_constants::SEA_LEVEL_GRAVITATIONAL_ACCELERATION );\n\n        BOOST_CHECK_SMALL( std::fabs( currentMassRate - expectedMassRate ), 1.0e-15 );\n\n    }\n\n\n    // Test trajectory function.\n    std::vector< double > epochsVector;\n    epochsVector.push_back( 0.0 );\n    epochsVector.push_back( timeOfFlight / 4.0 * physical_constants::JULIAN_DAY );\n    epochsVector.push_back( timeOfFlight / 2.0 * physical_constants::JULIAN_DAY );\n    epochsVector.push_back( 3.0 * timeOfFlight / 4.0 * physical_constants::JULIAN_DAY );\n    epochsVector.push_back( timeOfFlight * physical_constants::JULIAN_DAY );\n\n    std::map< double, Eigen::Vector6d > trajectory;\n    std::map< double, Eigen::VectorXd > massProfile;\n    std::map< double, Eigen::VectorXd > thrustProfile;\n    std::map< double, Eigen::VectorXd > thrustAccelerationProfile;\n\n    hodographicShaping.getTrajectory( epochsVector, trajectory );\n    hodographicShaping.getMassProfile( epochsVector, massProfile, specificImpulseFunction, integratorSettings );\n    hodographicShaping.getThrustForceProfile( epochsVector, thrustProfile, specificImpulseFunction, integratorSettings );\n    hodographicShaping.getThrustAccelerationProfile( epochsVector, thrustAccelerationProfile, specificImpulseFunction, integratorSettings );\n\n    for ( int i = 0 ; i < 3 ; i ++ )\n    {\n        BOOST_CHECK_SMALL( std::fabs( trajectory.begin( )->second[ i ] - cartesianStateDepartureBody[ i ] ), 1.0e-3 );\n        BOOST_CHECK_SMALL( std::fabs( trajectory.begin( )->second[ i + 3 ] - cartesianStateDepartureBody[ i + 3 ] ), 1.0e-10 );\n        BOOST_CHECK_SMALL( std::fabs( trajectory.rbegin( )->second[ i ] - cartesianStateArrivalBody[ i ] ), 1.0e-3 );\n        BOOST_CHECK_SMALL( std::fabs( trajectory.rbegin( )->second[ i + 3 ] - cartesianStateArrivalBody[ i + 3 ] ), 1.0e-10 );\n    }\n\n    for ( std::map< double, Eigen::Vector6d >::iterator itr = trajectory.begin( ) ; itr != trajectory.end( ) ; itr++ )\n    {\n        Eigen::Vector6d stateVector = hodographicShaping.computeCurrentStateVector( itr->first );\n        Eigen::Vector3d thrustAccelerationVector = hodographicShaping.computeCurrentThrustAcceleration(\n                    itr->first, specificImpulseFunction, integratorSettings );\n        Eigen::Vector3d thrustVector = hodographicShaping.computeCurrentThrustForce(\n                    itr->first, specificImpulseFunction, integratorSettings );\n        double mass = hodographicShaping.computeCurrentMass( itr->first, specificImpulseFunction, integratorSettings );\n\n        for ( int i = 0 ; i < 3 ; i++ )\n        {\n            BOOST_CHECK_SMALL( std::fabs( itr->second[ i ] - stateVector[ i ] ), 1.0e-6 );\n            BOOST_CHECK_SMALL( std::fabs( itr->second[ i + 3 ] - stateVector[ i + 3 ] ), 1.0e-12 );\n            BOOST_CHECK_SMALL( std::fabs( thrustAccelerationProfile[ itr->first ][ i ] - thrustAccelerationVector[ i ] ), 1.0e-6 );\n            BOOST_CHECK_SMALL( std::fabs( thrustProfile[ itr->first ][ i ] - thrustVector[ i ] ), 1.0e-12 );\n        }\n        BOOST_CHECK_SMALL( std::fabs( massProfile[ itr->first ][ 0 ] - mass ), 1.0e-12 );\n    }\n}\n\n\nBOOST_AUTO_TEST_SUITE_END( )\n\n} // namespace unit_tests\n} // namespace tudat\n", "meta": {"hexsha": "de03b896f3751a6adeba3a3b2898f274817127ee", "size": 96416, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/LowThrustTrajectories/ShapeBasedMethods/UnitTests/unitTestHodographicShaping.cpp", "max_stars_repo_name": "sebranchett/tudat", "max_stars_repo_head_hexsha": "24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tudat/Astrodynamics/LowThrustTrajectories/ShapeBasedMethods/UnitTests/unitTestHodographicShaping.cpp", "max_issues_repo_name": "sebranchett/tudat", "max_issues_repo_head_hexsha": "24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tudat/Astrodynamics/LowThrustTrajectories/ShapeBasedMethods/UnitTests/unitTestHodographicShaping.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": 64.1490352628, "max_line_length": 180, "alphanum_fraction": 0.7543250083, "num_tokens": 21609, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127678225575, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.46686668863537173}}
{"text": "#include <armadillo>\n\nint main() {\n\n    const size_t dim = 3;\n\n    arma::mat A(dim, dim, arma::fill::ones);\n    A.print(\"A\");\n    arma::mat B = A;\n    arma::vec b(dim);\n    for (size_t i = 0; i < dim; i++)\n        b(i) = (i + 2);\n    b.print(\"b\");\n\n    // error: element-wise multiplication: incompatible matrix dimensions: 3x3 and 3x1\n    // (A % b).print(\"A % b\");\n\n    // This seems silly but it's ok from a memory access standpoint.\n    for (size_t j = 0; j < dim; j++)\n        A.col(j) *= b(j);\n    A.print(\"% (1)\");\n\n    // error: no match for \u2018operator*=\u2019 (operand types are \u2018arma::subview_row<double>\u2019 and \u2018arma::vec {aka arma::Col<double>}\u2019)\n    // for (size_t i = 0; i < dim; i++)\n    //     B.row(i) *= b;\n    // error: element-wise multiplication: incompatible matrix dimensions: 1x3 and 3x1\n    // for (size_t i = 0; i < dim; i++)\n    //     B.row(i) = B.row(i) % b;\n    // This is matrix multiplication!\n    // B *= b;\n\n    // order doesn't matter\n    arma::mat C = B.each_row() % b.t();\n    C.print(\"% (2)\");\n\n    return 0;\n}\n", "meta": {"hexsha": "958cd400b1c231642d4b5391823beb01da76af8e", "size": 1041, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/armadillo/schur_matrix_vector.cpp", "max_stars_repo_name": "berquist/eg", "max_stars_repo_head_hexsha": "4c368b12eaaffcf0af8032f10348cf8bc1c3957a", "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": "cpp/armadillo/schur_matrix_vector.cpp", "max_issues_repo_name": "berquist/eg", "max_issues_repo_head_hexsha": "4c368b12eaaffcf0af8032f10348cf8bc1c3957a", "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": "cpp/armadillo/schur_matrix_vector.cpp", "max_forks_repo_name": "berquist/eg", "max_forks_repo_head_hexsha": "4c368b12eaaffcf0af8032f10348cf8bc1c3957a", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3947368421, "max_line_length": 127, "alphanum_fraction": 0.530259366, "num_tokens": 336, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850933, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.46683061542181664}}
{"text": "//\n// Created by Chi Keen Tan on 17/12/2020.\n//\n\n#pragma once\n\n#include <iostream>\n#include <NTL/ZZ_p.h>\n#include <NTL/vec_ZZ_p.h>\n#include <vector>\n#include <cassert>\n#include <unordered_map>\n#include <NTL/matrix.h>\n#include <NTL/mat_ZZ_p.h>\n#include <NTL/tools.h>\n#include \"global.hpp\"\n\n\n// Common typedef\n\ntypedef NTL::ZZ CGSW_long;\n\ntypedef NTL::ZZ_p CGSW_mod;\n\ntypedef NTL::vec_ZZ_p CGSW_vec;\n\ntypedef NTL::mat_ZZ_p CGSW_mat;\n\ntypedef NTL::Mat<uint64_t> CGSW_mat_uint;\n\n\n// Exception Type\n\nclass NotImplemented : public std::logic_error {\n    public:\n        NotImplemented() : std::logic_error(\"Function not yet implemented\") { };\n};\n\nclass NotSupported : public std::logic_error {\n    public:\n        NotSupported() : std::logic_error(\"Current schemes doesn't not support this function\") {};\n};\n\n// NTL extensions\nnamespace NTL {\n    inline CGSW_long sqrt(const CGSW_long &x){\n        return SqrRoot(x);\n    }\n\n    inline double log2(const CGSW_long &x){\n        double tmp = log(x);\n        double tmp2 = log10(2);\n        return log(x) / log(CGSW_long (2));\n    }\n\n    inline CGSW_mat_uint operator+(const CGSW_mat_uint &a, const CGSW_mat_uint &b){\n        assert(a.NumCols() == b.NumCols());\n        assert(a.NumRows() == b.NumRows());\n\n        CGSW_mat_uint ans;\n        ans.SetDims(a.NumRows(), a.NumCols());\n        for (auto i = 0; i < a.NumRows(); i ++){\n            for (auto j = 0; j < a.NumCols(); j ++){\n                ans[i][j] = a[i][j] + b[i][j];\n            }\n        }\n\n        return ans;\n    }\n\n    inline CGSW_mat_uint operator-(const CGSW_mat_uint &a, const CGSW_mat_uint &b){\n        assert(a.NumCols() == b.NumCols());\n        assert(a.NumRows() == b.NumRows());\n\n        CGSW_mat_uint ans;\n        ans.SetDims(a.NumRows(), a.NumCols());\n        for (auto i = 0; i < a.NumRows(); i ++){\n            for (auto j = 0; j < a.NumCols(); j ++){\n                ans[i][j] = a[i][j] - b[i][j];\n            }\n        }\n\n        return ans;\n    }\n\n// This is temporary scaffolding for cgsw2 encryption params\n}", "meta": {"hexsha": "494cf7da75bf93ea156e1fb0208b43b643b016d8", "size": 2032, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/cgsw/common.hpp", "max_stars_repo_name": "chikeen/CGSW", "max_stars_repo_head_hexsha": "10d159a9daf8ad1af5006602454b7e82c5e561c3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-12T07:12:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-12T07:12:23.000Z", "max_issues_repo_path": "include/cgsw/common.hpp", "max_issues_repo_name": "chikeen/CGSW", "max_issues_repo_head_hexsha": "10d159a9daf8ad1af5006602454b7e82c5e561c3", "max_issues_repo_licenses": ["Apache-2.0"], "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/cgsw/common.hpp", "max_forks_repo_name": "chikeen/CGSW", "max_forks_repo_head_hexsha": "10d159a9daf8ad1af5006602454b7e82c5e561c3", "max_forks_repo_licenses": ["Apache-2.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.3563218391, "max_line_length": 98, "alphanum_fraction": 0.5861220472, "num_tokens": 564, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.4668306154218166}}
{"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 <Eigen/Core>\n#include <Eigen/Geometry>\n#include <glog/logging.h>\n\n#include \"gtest/gtest.h\"\n#include \"theia/math/util.h\"\n#include \"theia/util/random.h\"\n#include \"theia/sfm/transformation/align_point_clouds.h\"\n\nnamespace theia {\nusing Eigen::Matrix;\nusing Eigen::Matrix3d;\nusing Eigen::RowMajor;\nusing Eigen::Vector3d;\n\nnamespace {\ndouble kEpsilon = 1e-6;\n\nvoid UmeyamaSimpleTest() {\n  std::vector<Vector3d> left = {\n      Vector3d(0.4, -3.105, 2.147),  Vector3d(1.293, 7.1982, -.068),\n      Vector3d(-5.34, 0.708, -3.69), Vector3d(-.345, 1.987, 0.936),\n      Vector3d(0.93, 1.45, 1.079),   Vector3d(-3.15, -4.73, 2.49),\n      Vector3d(2.401, -2.03, -1.87), Vector3d(3.192, -.573, 0.1),\n      Vector3d(-2.53, 3.07, -5.19)};\n\n  const Matrix3d rotation_mat =\n      Eigen::AngleAxisd(DegToRad(15.0), Vector3d(1.0, -2.7, 1.9).normalized())\n          .toRotationMatrix();\n  const Vector3d translation_vec(0, 2, 2);\n  const double expected_scale = 1.5;\n\n  // Transform the points.\n  std::vector<Vector3d> right;\n  for (int i = 0; i < left.size(); i++) {\n    Vector3d transformed_point =\n        expected_scale * rotation_mat * left[i] + translation_vec;\n    right.emplace_back(transformed_point);\n  }\n\n  // Compute the similarity transformation.\n  Matrix3d rotation;\n  Vector3d translation;\n  double scale;\n  AlignPointCloudsUmeyama(left, right, &rotation, &translation, &scale);\n\n  // Ensure the calculated transformation is the same as the one we set.\n  for (int i = 0; i < 3; i++) {\n    for (int j = 0; j < 3; j++) {\n      ASSERT_LT(std::abs(rotation(i, j) - rotation_mat(i, j)), kEpsilon);\n    }\n    ASSERT_LT(std::abs(translation(i) - translation_vec(i)), kEpsilon);\n  }\n  ASSERT_LT(fabs(expected_scale - scale), kEpsilon);\n}\n\n// It is not easy to find a formula for the weights that always works\n// We need to make some statistics to see if the function works in most cases\n//\n// This test adds some noise on a given fraction of the points\n// We try to estimate the weights from the errors of the first pass (setting\n// weights to 1)\n// We can expect that the errors are where the noise was added\n// From this first result we can set a weight for each point.\n// The weight is given by 1.0/(1.0 + distance)\n// Where distance is the distance between right[i] and s * R * left[i] + T\n// estimated by a first pass\n// To see if the new estimation from these weights is better\n// we need to check that the new parameters are closer to the expected\n// parameters\nvoid UmeyamaWithWeigthsAndNoise() {\n  // Make some statistics\n  // 1000 is not a problem the algorith is fast\n  static const size_t kNumIterations = 1000;\n\n  // 15 % of noise\n  static const float kNoiseRatio = 0.15f;\n\n  // Percentage to consider the test succeeds (is it enough ?)\n  static const float kTestsSucceeded = 95.0f;\n\n  size_t succeeded = 0;\n  for (size_t iteration = 0; iteration < kNumIterations; ++iteration) {\n    // 4 pts required\n    const size_t num_points = static_cast<size_t>(theia::RandInt(4, 1000));\n    std::vector<Vector3d> left(num_points);\n    std::vector<double> weights(num_points, 1.0);\n\n    for (size_t i = 0; i < num_points; ++i) {\n      left[i] = Eigen::Vector3d::Random();\n    }\n\n    const Matrix3d rotation_mat =\n        Eigen::AngleAxisd(DegToRad(theia::RandDouble(0.0, 360.0)),\n                          Eigen::Vector3d::Random().normalized())\n            .toRotationMatrix();\n    const Vector3d translation_vec = Eigen::Vector3d::Random();\n    const double expected_scale = theia::RandDouble(0.001, 10);\n\n    // Transform the points.\n    std::vector<Vector3d> right;\n    for (size_t i = 0; i < left.size(); i++) {\n      const Vector3d transformed_point =\n          expected_scale * rotation_mat * left[i] + translation_vec;\n      right.emplace_back(transformed_point);\n    }\n\n    // Add noise on scale, point and translation\n    for (size_t i = 0, end = (size_t)(kNoiseRatio * num_points); i < end; ++i) {\n      const size_t k = static_cast<size_t>(theia::RandInt(0, num_points - 1));\n      const double noiseOnScale = expected_scale + theia::RandDouble(0, 10);\n      right[k] = noiseOnScale * rotation_mat * (left[k] + Vector3d::Random()) +\n                 translation_vec + Vector3d::Random();\n    }\n\n    // We need to find some weights\n    Matrix3d rotation_noisy;\n    Vector3d translation_noisy;\n    double scale_noisy;\n    AlignPointCloudsUmeyamaWithWeights(left, right, weights, &rotation_noisy,\n                                       &translation_noisy, &scale_noisy);\n    for (size_t i = 0; i < num_points; ++i) {\n      const double dist = (right[i] - (scale_noisy * rotation_noisy * left[i] +\n                                       translation_noisy))\n                              .norm();\n      weights[i] = 1.0 / (1.0 + dist);\n    }\n    //\n\n    Matrix3d rotation_weighted;\n    Vector3d translation_weighted;\n    double scale_weighted;\n    AlignPointCloudsUmeyamaWithWeights(left, right, weights, &rotation_weighted,\n                                       &translation_weighted, &scale_weighted);\n\n    // Check if the parameters are closer to real parameters ?\n    const bool condition_on_scale = (std::abs(scale_weighted - expected_scale) <\n                                     std::abs(scale_noisy - expected_scale));\n    const bool condition_on_translation =\n        (translation_vec - translation_weighted).norm() <\n        (translation_vec - translation_noisy).norm();\n    const bool condition_on_rotation =\n        (rotation_mat - rotation_weighted).norm() <\n        (rotation_mat - rotation_noisy).norm();\n\n    if (condition_on_scale && condition_on_translation && condition_on_rotation)\n      ++succeeded;\n  }\n\n  ASSERT_LE(kTestsSucceeded, 100.0 * succeeded / (0.0 + kNumIterations));\n}\n\n}  // namespace\n\nTEST(AlignPointCloudsUmeyama, SimpleTest) {\n    UmeyamaSimpleTest();\n}\n\nTEST(AlignPointCloudsUmeyamaWithWeights, WeightsAndNoise) {\n  UmeyamaWithWeigthsAndNoise();\n}\n\n}  // namespace theia\n", "meta": {"hexsha": "4f49df73213bb5733b6e81811c39e818eb3b788e", "size": 7713, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/sfm/transformation/align_point_clouds_test.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/transformation/align_point_clouds_test.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/transformation/align_point_clouds_test.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": 38.9545454545, "max_line_length": 80, "alphanum_fraction": 0.6796317905, "num_tokens": 1999, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6584175139669998, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.4668306113735056}}
{"text": "// Static blocked LU Decomposition\r\n\r\n#include <stdio.h>\r\n#include <hpx/hpx_init.hpp>\r\n#include <hpx/include/threads.hpp>\r\n#include <hpx/include/lcos.hpp>\r\n#include <hpx/lcos/local/dataflow.hpp>\r\n#include <hpx/util/unwrapped.hpp>\r\n\r\n#include \"lu-local.h\"\r\n\r\n#include <boost/assign.hpp>\r\n\r\nusing std::vector;\r\nusing hpx::util::unwrapped;\r\nusing hpx::lcos::shared_future;\r\nusing hpx::lcos::wait_all;\r\nusing hpx::async;\r\nusing hpx::lcos::local::dataflow;\r\nusing hpx::when_all;\r\nusing hpx::make_ready_future;\r\n\r\n\r\nvector<double> A;\r\nauto diag_op  = unwrapped( &ProcessDiagonalBlock );\r\nauto row_op   = unwrapped( &ProcessBlockOnRow );\r\nauto col_op   = unwrapped( &ProcessBlockOnColumn );\r\nauto inner_op = unwrapped( &ProcessInnerBlock );\r\n\r\n\r\nvoid init_df(vector<vector<vector<shared_future<block>>>> &dfArray, int numBlocks, int size) {\r\n    vector<vector<block>> blockList;\r\n    getBlockList(blockList, numBlocks, size);\r\n    \r\n    dfArray[0].resize(numBlocks);\r\n    dfArray[1].resize(numBlocks);\r\n\r\n    for(int i = 0; i < numBlocks; i++){\r\n        dfArray[0][i].resize( numBlocks );\r\n        dfArray[1][i].resize( numBlocks );\r\n    }\r\n\r\n    shared_future<int> fsize = make_ready_future(size);\r\n\r\n    dfArray[0][0][0] = async( ProcessDiagonalBlock, size, blockList[0][0] );\r\n    \r\n    for(int i = 1; i < numBlocks; i++) {\r\n        dfArray[0][0][i] = dataflow( row_op, fsize, make_ready_future( blockList[0][i] ), dfArray[0][0][0]);\r\n    }\r\n    for(int i = 1; i < numBlocks; i++) {\r\n        dfArray[0][i][0] = dataflow( col_op, fsize, make_ready_future( blockList[i][0] ), dfArray[0][0][0]);\r\n        for(int j = 1; j < numBlocks; j++) {\r\n            dfArray[0][i][j] = dataflow( inner_op, fsize, make_ready_future( blockList[i][j] ),\r\n                                                   dfArray[0][0][j], dfArray[0][i][0] );\r\n        }\r\n    }\r\n}\r\n\r\nvoid LU( int size, int numBlocks)\r\n{\r\n    vector<vector<vector<shared_future<block>>>> dfArray(2);\r\n    shared_future<int> fsize = make_ready_future(size);\r\n\r\n    init_df(dfArray, numBlocks, size);\r\n\r\n    for(int i = 1; i < numBlocks; i++) {\r\n        dfArray[i%2][i][i] = dataflow( diag_op, fsize, dfArray[(i-1)%2][i][i]);\r\n        for(int j = i + 1; j < numBlocks; j++){\r\n            dfArray[i%2][i][j] = dataflow( row_op , fsize, \r\n                                           dfArray[(i-1)%2][i][j], \r\n                                           dfArray[ i   %2][i][i] );\r\n        }\r\n        for(int j = i + 1; j < numBlocks; j++){\r\n            dfArray[i%2][j][i] = dataflow( col_op, fsize, \r\n                                           dfArray[(i-1)%2][j][i], \r\n                                           dfArray[ i   %2][i][i] );\r\n            \r\n            for(int k = i + 1; k < numBlocks; k++) {\r\n                dfArray[i%2][j][k] = dataflow( inner_op, fsize, \r\n                                               dfArray[(i-1)%2][j][k], \r\n                                               dfArray[ i   %2][i][k],\r\n                                               dfArray[ i   %2][j][i] );\r\n            }\r\n        }\r\n    }\r\n    wait_all(dfArray[(numBlocks-1)%2][numBlocks-1][numBlocks-1]);\r\n}\r\n\r\nint hpx_main(int argc, char *argv[])\r\n{\r\n    vector<double> originalA;\r\n    int size = 1000;\r\n    int numBlocks = 10;\r\n    unsigned long t1, t2;\r\n    bool runCheck = false;\r\n\r\n    if( argc > 1 )\r\n        size = atoi(argv[1]);\r\n    if( argc > 2 )\r\n        numBlocks = atoi(argv[2]);\r\n    if( argc > 3 )\r\n        runCheck = true;\r\n    printf(\"size = %d, numBlocks = %d\\n\", size, numBlocks);\r\n\r\n    A.resize(size*size, 0);\r\n    if(runCheck) {\r\n        printf(\"Error checking enabled\\n\");\r\n        InitMatrix3( size );\r\n        originalA.reserve(size*size);\r\n        for(int i = 0; i < size * size; i++) {\r\n            originalA[i] = A[i];\r\n        }\r\n    } else {\r\n        printf(\"fast initialization\\n\");\r\n        fastInitMatrix(size);\r\n    }\r\n    printf(\"initialization complete\\n\");\r\n\r\n    if(numBlocks == 1) {\r\n        t1 = GetTickCount();\r\n        ProcessDiagonalBlock( size, block(size, 0, size));\r\n        t2 = GetTickCount();\r\n    } else if( numBlocks > 1) {\r\n        t1 = GetTickCount();\r\n        LU( size, numBlocks);\r\n        t2 = GetTickCount();\r\n    } else { \r\n        printf(\"Error: numBlocks must be greater than 0.\\n\");\r\n        return hpx::finalize();\r\n    }\r\n    printf(\"Time for LU-decomposition in secs: %f \\n\", (t2-t1)/1000000.0);\r\n    \r\n    if(runCheck) {\r\n        checkResult( originalA,  size );\r\n    }\r\n    return hpx::finalize();\r\n}\r\n\r\nint main(int argc, char *argv[])\r\n{\r\n    using namespace boost::assign;\r\n    std::vector<std::string> cfg;\r\n    cfg += \"hpx.os_threads=\" +\r\n        boost::lexical_cast<std::string>(hpx::threads::hardware_concurrency());\r\n\r\n    return hpx::init(argc, argv, cfg);\r\n}\r\n", "meta": {"hexsha": "9c56c57a9d3e34092488e774fe2d02b1321dd299", "size": 4761, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/hpx/bench/lu/lu-hpx-dataflow.cpp", "max_stars_repo_name": "tianyi93/hpxMP_mirror", "max_stars_repo_head_hexsha": "668e8881a6f2f437a614ae92e205ae49f083691e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2018-07-16T14:39:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-08T11:25:09.000Z", "max_issues_repo_path": "examples/hpx/bench/lu/lu-hpx-dataflow.cpp", "max_issues_repo_name": "tianyi93/hpxMP_mirror", "max_issues_repo_head_hexsha": "668e8881a6f2f437a614ae92e205ae49f083691e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 25.0, "max_issues_repo_issues_event_min_datetime": "2018-06-18T14:59:09.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-16T20:43:57.000Z", "max_forks_repo_path": "examples/hpx/bench/lu/lu-hpx-dataflow.cpp", "max_forks_repo_name": "tianyi93/hpxMP_mirror", "max_forks_repo_head_hexsha": "668e8881a6f2f437a614ae92e205ae49f083691e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2018-06-22T18:44:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-21T11:17:28.000Z", "avg_line_length": 32.1689189189, "max_line_length": 109, "alphanum_fraction": 0.520478891, "num_tokens": 1324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.4668306059171906}}
{"text": "\r\n//  Copyright 2017 Peter Dimov.\r\n//\r\n// Distributed under the Boost Software License, Version 1.0.\r\n//\r\n// See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt\r\n\r\n\r\n#include <boost/mp11/algorithm.hpp>\r\n#include <boost/core/lightweight_test.hpp>\r\n#include <boost/config.hpp>\r\n#include <boost/config/workaround.hpp>\r\n#include <tuple>\r\n\r\nusing boost::mp11::mp_size_t;\r\nusing boost::mp11::mp_for_each;\r\nusing boost::mp11::mp_with_index;\r\nusing boost::mp11::mp_iota_c;\r\n\r\nstruct F\r\n{\r\n    std::size_t i_;\r\n\r\n    explicit F( std::size_t i ): i_( i ) {}\r\n\r\n    template<std::size_t I> bool operator()( mp_size_t<I> ) const\r\n    {\r\n        BOOST_TEST_EQ( I, i_ );\r\n        return false;\r\n    }\r\n};\r\n\r\nstruct G\r\n{\r\n    void operator()( mp_size_t<0> ) const\r\n    {\r\n    }\r\n\r\n    template<std::size_t N> void operator()( mp_size_t<N> ) const\r\n    {\r\n        for( std::size_t i = 0; i < N; ++i )\r\n        {\r\n            mp_with_index<N>( i, F(i) );\r\n            mp_with_index<mp_size_t<N>>( i, F(i) );\r\n        }\r\n    }\r\n};\r\n\r\nint main()\r\n{\r\n#if BOOST_WORKAROUND( BOOST_MSVC, < 1900 )\r\n\r\n    G()( mp_size_t<1>{} );\r\n    G()( mp_size_t<2>{} );\r\n    G()( mp_size_t<3>{} );\r\n    G()( mp_size_t<4>{} );\r\n    G()( mp_size_t<5>{} );\r\n    G()( mp_size_t<6>{} );\r\n    G()( mp_size_t<7>{} );\r\n    G()( mp_size_t<8>{} );\r\n    G()( mp_size_t<9>{} );\r\n    G()( mp_size_t<10>{} );\r\n    G()( mp_size_t<11>{} );\r\n    G()( mp_size_t<12>{} );\r\n    G()( mp_size_t<13>{} );\r\n    G()( mp_size_t<14>{} );\r\n    G()( mp_size_t<15>{} );\r\n    G()( mp_size_t<16>{} );\r\n\r\n    G()( mp_size_t<32+1>{} );\r\n\r\n    G()( mp_size_t<48+2>{} );\r\n\r\n    G()( mp_size_t<64+3>{} );\r\n\r\n    G()( mp_size_t<96+4>{} );\r\n\r\n    G()( mp_size_t<112+5>{} );\r\n\r\n    G()( mp_size_t<128+6>{} );\r\n\r\n#else\r\n\r\n    mp_for_each<mp_iota_c<134>>( G() );\r\n\r\n#endif\r\n\r\n    return boost::report_errors();\r\n}\r\n", "meta": {"hexsha": "cda4d6f7a4911f2d91310114ec99509e861cf6f9", "size": 1873, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/mp11/test/mp_with_index.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": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/mp11/test/mp_with_index.cpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/mp11/test/mp_with_index.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.5824175824, "max_line_length": 66, "alphanum_fraction": 0.5210891618, "num_tokens": 592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191460821871, "lm_q2_score": 0.6584174871563662, "lm_q1q2_score": 0.4668306045091861}}
{"text": "//  Copyright Nick Thompson 2017.\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// Basic sanity check that header <boost/math/special_functions/gamma.hpp>\n// #includes all the files that it needs to.\n//\n#include <boost/math/differentiation/autodiff.hpp>\n//\n// Note this header includes no other headers, this is\n// important if this test is to be meaningful:\n//\n#include \"test_compile_result.hpp\"\n\ntemplate <typename T>\nT fourth_power(T const& x) {\n   T x4 = x * x;  // retval in operator*() uses x4's memory via NRVO.\n   x4 *= x4;      // No copies of x4 are made within operator*=() even when squaring.\n   return x4;     // x4 uses y's memory in main() via NRVO.\n}\n\nvoid compile_and_link_test()\n{\n   using namespace boost::math::differentiation;\n   auto const x = make_fvar<double, 5>(2.0);  // Find derivatives at x=2.\n   auto const y = fourth_power(x);\n   \n   check_result<double>(y.derivative(1));\n}\n", "meta": {"hexsha": "11e65895a5c91f52f152e774c5029f9e22c90f06", "size": 1053, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/compile_test/diff_autodiff_incl_test.cpp", "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": "3rdparty/boost_1_73_0/libs/math/test/compile_test/autodiff_incl_test.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "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": "3rdparty/boost_1_73_0/libs/math/test/compile_test/autodiff_incl_test.cpp", "max_forks_repo_name": "qingkouwei/mediaones", "max_forks_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_forks_repo_licenses": ["MIT"], "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": 33.9677419355, "max_line_length": 85, "alphanum_fraction": 0.7008547009, "num_tokens": 284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191214879992, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.4668306025728816}}
{"text": "/*=============================================================================\n    Copyright (c) 2001-2011 Joel de Guzman\n\n    Distributed under the Boost Software License, Version 1.0. (See accompanying\n    file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n=============================================================================*/\n///////////////////////////////////////////////////////////////////////////////\n//\n//  A calculator example demonstrating the grammar and semantic actions\n//  using phoenix to do the actual expression evaluation. The parser is\n//  essentially an \"interpreter\" that evaluates expressions on the fly.\n//\n//  [ JDG June 29, 2002 ]   spirit1\n//  [ JDG March 5, 2007 ]   spirit2\n//\n///////////////////////////////////////////////////////////////////////////////\n\n// Spirit v2.5 allows you to suppress automatic generation\n// of predefined terminals to speed up complation. With\n// BOOST_SPIRIT_NO_PREDEFINED_TERMINALS defined, you are\n// responsible in creating instances of the terminals that\n// you need (e.g. see qi::uint_type uint_ below).\n#define BOOST_SPIRIT_NO_PREDEFINED_TERMINALS\n\n#include <boost/config/warning_disable.hpp>\n#include <boost/spirit/include/qi.hpp>\n#include <boost/spirit/include/phoenix_operator.hpp>\n\n#include <iostream>\n#include <string>\n\nnamespace client\n{\n    namespace qi = boost::spirit::qi;\n    namespace ascii = boost::spirit::ascii;\n\n    ///////////////////////////////////////////////////////////////////////////\n    //  Our calculator grammar\n    ///////////////////////////////////////////////////////////////////////////\n    template <typename Iterator>\n    struct calculator : qi::grammar<Iterator, int(), ascii::space_type>\n    {\n        calculator() : calculator::base_type(expression)\n        {\n            qi::_val_type _val;\n            qi::_1_type _1;\n            qi::uint_type uint_;\n\n            expression =\n                term                            [_val = _1]\n                >> *(   ('+' >> term            [_val += _1])\n                    |   ('-' >> term            [_val -= _1])\n                    )\n                ;\n\n            term =\n                factor                          [_val = _1]\n                >> *(   ('*' >> factor          [_val *= _1])\n                    |   ('/' >> factor          [_val /= _1])\n                    )\n                ;\n\n            factor =\n                uint_                           [_val = _1]\n                |   '(' >> expression           [_val = _1] >> ')'\n                |   ('-' >> factor              [_val = -_1])\n                |   ('+' >> factor              [_val = _1])\n                ;\n        }\n\n        qi::rule<Iterator, int(), ascii::space_type> expression, term, factor;\n    };\n}\n\n///////////////////////////////////////////////////////////////////////////////\n//  Main program\n///////////////////////////////////////////////////////////////////////////////\nint\nmain()\n{\n    std::cout << \"/////////////////////////////////////////////////////////\\n\\n\";\n    std::cout << \"Expression parser...\\n\\n\";\n    std::cout << \"/////////////////////////////////////////////////////////\\n\\n\";\n    std::cout << \"Type an expression...or [q or Q] to quit\\n\\n\";\n\n    typedef std::string::const_iterator iterator_type;\n    typedef client::calculator<iterator_type> calculator;\n\n    boost::spirit::ascii::space_type space; // Our skipper\n    calculator calc; // Our grammar\n\n    std::string str;\n    int result;\n    while (std::getline(std::cin, str))\n    {\n        if (str.empty() || str[0] == 'q' || str[0] == 'Q')\n            break;\n\n        std::string::const_iterator iter = str.begin();\n        std::string::const_iterator end = str.end();\n        bool r = phrase_parse(iter, end, calc, space, result);\n\n        if (r && iter == end)\n        {\n            std::cout << \"-------------------------\\n\";\n            std::cout << \"Parsing succeeded\\n\";\n            std::cout << \"result = \" << result << std::endl;\n            std::cout << \"-------------------------\\n\";\n        }\n        else\n        {\n            std::string rest(iter, end);\n            std::cout << \"-------------------------\\n\";\n            std::cout << \"Parsing failed\\n\";\n            std::cout << \"stopped at: \\\" \" << rest << \"\\\"\\n\";\n            std::cout << \"-------------------------\\n\";\n        }\n    }\n\n    std::cout << \"Bye... :-) \\n\\n\";\n    return 0;\n}\n\n\n", "meta": {"hexsha": "4f214e30fbf687a307ec5530a8b70ed6b187913c", "size": 4403, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/spirit/example/qi/compiler_tutorial/calc3.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "boost/libs/spirit/example/qi/compiler_tutorial/calc3.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "boost/libs/spirit/example/qi/compiler_tutorial/calc3.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 35.224, "max_line_length": 81, "alphanum_fraction": 0.4085850556, "num_tokens": 883, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6584174871563662, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.4668306004608753}}
{"text": "// (C) Copyright Jeremy Siek 2000. Permission to copy, use, modify, sell and\r\n// distribute this software is granted provided this copyright notice appears\r\n// in all copies. This software is provided \"as is\" without express or implied\r\n// warranty, and with no claim as to its suitability for any purpose.\r\n\r\n\r\n#include <functional>\r\n#include <algorithm>\r\n#include <iostream>\r\n#include <boost/iterator_adaptors.hpp>\r\n#include <boost/pending/integer_range.hpp>\r\n\r\nint\r\nmain(int, char*[])\r\n{\r\n  // This is a simple example of using the transform_iterators class to\r\n  // generate iterators that multiply the value returned by dereferencing\r\n  // the iterator. In this case we are multiplying by 2.\r\n  // Would be cooler to use lambda library in this example.\r\n\r\n  int x[] = { 1, 2, 3, 4, 5, 6, 7, 8 };\r\n\r\n  typedef std::binder1st< std::multiplies<int> > Function;\r\n  typedef boost::transform_iterator_generator<Function, int* \r\n  >::type doubling_iterator;\r\n\r\n  doubling_iterator i(x, std::bind1st(std::multiplies<int>(), 2)),\r\n    i_end(x + sizeof(x)/sizeof(int), std::bind1st(std::multiplies<int>(), 2));\r\n\r\n  std::cout << \"multiplying the array by 2:\" << std::endl;\r\n  while (i != i_end)\r\n    std::cout << *i++ << \" \";\r\n  std::cout << std::endl;\r\n\r\n  // Here is an example of counting from 0 to 5 using the integer_range class.\r\n\r\n  boost::integer_range<int> r(0,5);\r\n\r\n  std::cout << \"counting to from 0 to 4:\" << std::endl;\r\n  std::copy(r.begin(), r.end(), std::ostream_iterator<int>(std::cout, \" \"));\r\n  std::cout << std::endl;\r\n\r\n  return 0;\r\n}\r\n\r\n\r\n", "meta": {"hexsha": "0457d177713c2ffade9b04ec3727efc39dcd3dc5", "size": 1556, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sdk/boost_1_30_0/libs/utility/iterator_adaptor_examples.cpp", "max_stars_repo_name": "acidicMercury8/xray-1.0", "max_stars_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-01-30T12:51:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-31T08:36:49.000Z", "max_issues_repo_path": "sdk/boost_1_30_0/libs/utility/iterator_adaptor_examples.cpp", "max_issues_repo_name": "acidicMercury8/xray-1.0", "max_issues_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_issues_repo_licenses": ["Linux-OpenIB"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sdk/boost_1_30_0/libs/utility/iterator_adaptor_examples.cpp", "max_forks_repo_name": "acidicMercury8/xray-1.0", "max_forks_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.1063829787, "max_line_length": 79, "alphanum_fraction": 0.6658097686, "num_tokens": 418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191214879991, "lm_q2_score": 0.6584175005616829, "lm_q1q2_score": 0.46683059782056857}}
{"text": "#include <chrono>\n#include <filesystem>\n#include <iostream>\n#include <iterator>\n#include <vector>\n\n#include <Eigen/Sparse>\n#include <unsupported/Eigen/SparseExtra>\n\n#include <memory_xplatform.h>\n\n#ifdef DEBUG\n    #define D(x) (std::cerr << x << std::endl)\n#else\n    #define D(x) do{}while(0)\n#endif\n\n#define CSV_EOL \"\\n\"\n\n#if defined(_WIN32) || defined(__CYGWIN__)\n    #define OUTPUT_FILE \"windows-output.csv\"\n#elif defined(__linux__) || defined(unix) || defined(__unix__) || defined(__unix)\n    #define OUTPUT_FILE \"unix-output.csv\"\n#else\n    #error Unknown environment!\n#endif\n\ntypedef unsigned long long ull;\ntypedef Eigen::SparseMatrix<double> SpMat;\n\nstruct result {\n    unsigned int size;\n    ull memory_delta;\n    std::chrono::duration<double> solve_time;\n    double relative_error;\n};\n\nresult analyze_matrix(std::string filename);\nstd::ostream& operator<<(std::ostream& stream, const result& r);\n\nint main() {\n    result _result;\n    std::ofstream output(OUTPUT_FILE, std::ofstream::out);\n\n    // Write headers\n    output << \"filename\" << \",\"\n        << \"size\" << \",\"\n        << \"memory_delta\" << \",\"\n        << \"solve_time\" << \",\"\n        << \"relative_error\" << CSV_EOL;\n\n    // Look for matrix in ../matlab/matrix_mtx folder\n    std::string path = \"../matlab/matrix_mtx\";\n    for (const auto& entry : std::filesystem::directory_iterator(path)) {\n        if (entry.path().extension() == \".mtx\") {\n            if (! output.is_open()) {\n                output.open(OUTPUT_FILE, std::ofstream::app);\n            }\n\n            std::cout << entry.path() << std::endl;\n            _result = analyze_matrix(entry.path().string());\n\n            D(\"Writing output...\");\n            output << entry.path().stem() << \",\" << _result << CSV_EOL;\n            D(\"\");\n\n            output.close();\n        }\n    }\n\n    return 0;\n}\n\n/**\n * Analyze a single matrix given it's filename\n * The matrix will be imported assuming it's in .mtx format.\n *\n * @param std::string filename\n * @return result\n */\nresult analyze_matrix(std::string filename) {\n    result r;\n    ull start_tot_virtual, start_proc_virtual, start_proc_physical, start_tot_physical,\n        end_tot_virtual, end_proc_virtual, end_proc_physical, end_tot_physical;\n\n    SpMat A; // Eigen::SparseMatrix<double>\n    D(\"Loading matrix file: \" << filename);\n    Eigen::loadMarket(A, filename);\n\n    // Debug memory usage to cout\n    D(\"Memory Usage (proc/total):\");\n    start_proc_virtual = memory::process_current_virtual();\n    start_tot_virtual = memory::total_virtual();\n    D(\"> Virtual: \" << start_proc_virtual << \" / \" << start_tot_virtual);\n    start_proc_physical = memory::process_current_physical();\n    start_tot_physical = memory::total_physical();\n    D(\"> Physical: \" << start_proc_physical << \" / \" << start_tot_physical);\n    D(\"\");\n\n    D(\"Solve:\");\n    D(\"> Calculating b vector...\");\n    Eigen::VectorXd x_es = Eigen::VectorXd::Ones(A.rows());\n    Eigen::VectorXd b(A.rows());\n    b = A*x_es;\n\n    D(\"> Applying CholeskySimplicial solver...\");\n    auto chol_start = std::chrono::high_resolution_clock::now();\n    Eigen::SimplicialCholesky<SpMat> chol(A);\n    Eigen::VectorXd x_ap = chol.solve(b);\n    auto chol_finish = std::chrono::high_resolution_clock::now();\n    D(\"\");\n\n    D(\"Memory Usage (proc/total):\");\n    end_proc_virtual = memory::process_current_virtual();\n    end_tot_virtual = memory::total_virtual();\n    D(\"> Virtual: \" << end_proc_virtual << \" / \" << end_tot_virtual);\n    end_proc_physical = memory::process_current_physical();\n    end_tot_physical = memory::total_physical();\n    D(\"> Physical: \" << end_proc_physical << \" / \" << end_tot_physical);\n    D(\"\");\n\n    r.size = A.rows();\n    r.memory_delta = end_proc_physical - start_proc_physical;\n    r.solve_time = chol_finish - chol_start;\n    r.relative_error = (x_ap - x_es).norm() / x_es.norm();\n\n    D(\"Results\");\n    D(\"> Solve time in seconds: \" << r.solve_time.count());\n    D(\"> Relative error: \" << r.relative_error);\n    D(\"\");\n\n    return r;\n}\n\n/**\n * Override the << operator to allow an easy print of\n * the results struct to stdout or output file.\n *\n * @params std::ostream& stream\n * @params const result& r\n * @return std::ostream&\n */\nstd::ostream& operator<<(std::ostream& stream, const result& r) {\n    stream << r.size << \",\"\n        << r.memory_delta << \",\"\n        << r.solve_time.count() << \",\"\n        << r.relative_error;\n\n    return stream;\n}\n", "meta": {"hexsha": "314b9bce57c644d0eacbb4fa259772970390cf05", "size": 4413, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/main.cpp", "max_stars_repo_name": "dvdmarchetti/unimib-mdcs-cholesky-decomposition-for-sparse-linear-system", "max_stars_repo_head_hexsha": "c6e886163acf9fab0edaaaa812e21b41db09e532", "max_stars_repo_licenses": ["MIT"], "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/main.cpp", "max_issues_repo_name": "dvdmarchetti/unimib-mdcs-cholesky-decomposition-for-sparse-linear-system", "max_issues_repo_head_hexsha": "c6e886163acf9fab0edaaaa812e21b41db09e532", "max_issues_repo_licenses": ["MIT"], "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/main.cpp", "max_forks_repo_name": "dvdmarchetti/unimib-mdcs-cholesky-decomposition-for-sparse-linear-system", "max_forks_repo_head_hexsha": "c6e886163acf9fab0edaaaa812e21b41db09e532", "max_forks_repo_licenses": ["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.2251655629, "max_line_length": 87, "alphanum_fraction": 0.6276909132, "num_tokens": 1059, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417487156366, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.46683059641256436}}
{"text": "/*\nCopyright 2013 The Robotics Group, The Maersk Mc-Kinney Moller Institute,\n\n    Licensed under the Apache License, Version 2.0 (the \"License\");\n    you may not use this file except in compliance with the License.\n    You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n*/\n\n#ifndef RWLIBS_SOFTBODY_FDUTIL_HPP\n#define RWLIBS_SOFTBODY_FDUTIL_HPP\n\n#include <Eigen/Core>\n\nnamespace rwlibs { namespace softbody {\n    /** @addtogroup softbody */\n    /*@{*/\n\n    /**\n     * @brief Various numerical methods using finite-differences\n     **/\n    class FdUtil\n    {\n      public:\n        /**\n         * @brief calculates the derivatives of a vector\n         *\n         * calculates the derivatives of a vector using second-order accurate, centered FD\n         *expressions at the interior points and first-order accurate forward/backward differences\n         * at the endpoints\n         *\n         * @param f vector of function values\n         * @param df vector to put the derivatives in\n         * @param h stepsize\n         **/\n        static void vectorDerivative (const Eigen::VectorXd& f, Eigen::VectorXd& df,\n                                      const double h);\n    };\n    /*@}*/\n}}    // namespace rwlibs::softbody\n\n#endif    // FDUTIL_HPP\n", "meta": {"hexsha": "eff79fe056b25ef10e00d634d69875d16df9b97a", "size": 1610, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "RobWork/src/rwlibs/softbody/numerics/FdUtil.hpp", "max_stars_repo_name": "ZLW07/RobWork", "max_stars_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-29T14:16:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T14:16:27.000Z", "max_issues_repo_path": "RobWork/src/rwlibs/softbody/numerics/FdUtil.hpp", "max_issues_repo_name": "ZLW07/RobWork", "max_issues_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RobWork/src/rwlibs/softbody/numerics/FdUtil.hpp", "max_forks_repo_name": "ZLW07/RobWork", "max_forks_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.568627451, "max_line_length": 98, "alphanum_fraction": 0.6559006211, "num_tokens": 346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7090191214879991, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.46683058831594254}}
{"text": "/**************************************************************************************************/\n// PNGpp copyright 2017 Foster Brereton. See LICENSE.txt for license details.\n/**************************************************************************************************/\n\n// stdc++\n#include <iostream>\n#include <numeric>\n#include <random>\n\n// tbb\n#include <tbb/parallel_for_each.h>\n\n// boost\n#include <boost/program_options.hpp>\n\n// application\n#include <pngpp/files.hpp>\n#include <pngpp/png.hpp>\n#include <pngpp/rgba.hpp>\n#include <pngpp/image_utils.hpp>\n\n/**************************************************************************************************/\n\nusing namespace pngpp;\n\n/**************************************************************************************************/\n\ntypedef std::vector<std::size_t> indexed_histogram_t;\n\nindexed_histogram_t indexed_histogram(const image_t& image) {\n    indexed_histogram_t result(PNG_MAX_PALETTE_LENGTH, 0);\n\n    for (auto entry : image)\n        ++result[entry];\n\n    return result;\n}\n\n/**************************************************************************************************/\n\ntypedef std::pair<std::size_t, std::uint8_t> indexed_histogram_pair_t;\ntypedef std::vector<indexed_histogram_pair_t> indexed_histogram_table_t;\n\nindexed_histogram_table_t make_indexed_histogram_table(const image_t& image) {\n    std::size_t               count(image.color_table().size());\n    indexed_histogram_table_t result(count);\n    indexed_histogram_t       image_hist(indexed_histogram(image));\n\n    for (std::size_t i(0); i < count; ++i) {\n        result[i] = indexed_histogram_pair_t(image_hist[i], i);\n    }\n\n    return result;\n}\n\n/**************************************************************************************************/\n\ntypedef std::vector<std::uint8_t> index_map_t;\n\nimage_t reindex_image(image_t image, const index_map_t& map) {\n    for (auto& entry : image)\n        entry = map[entry];\n\n    const auto&   src_table(image.color_table());\n    color_table_t dst_table(src_table);\n    std::size_t   count(image.color_table().size());\n\n    for (std::size_t i(0); i < count; ++i)\n        dst_table[map[i]] = src_table[i];\n\n    image.set_color_table(dst_table);\n\n    return image;\n}\n\nimage_t reindex_image(const image_t& image, const indexed_histogram_table_t& table) {\n    std::size_t count(image.color_table().size());\n    index_map_t sorted_map(count);\n\n    for (std::size_t i(0); i < count; ++i) {\n        sorted_map[table[i].second] = i;\n    }\n\n    return reindex_image(image, sorted_map);\n}\n\n/**************************************************************************************************/\n\ninline double grey(const rgba_t& c) {\n    double r = c._r / 255.;\n    double g = c._g / 255.;\n    double b = c._b / 255.;\n    double a = c._a / 255.;\n\n    return 0.2126 * r + 0.7152 * g + 0.0722 * b * a;\n}\n\n/**************************************************************************************************/\n\ntypedef std::map<rgba_t, std::size_t> truecolor_histogram_t;\n\ntruecolor_histogram_t truecolor_histogram(const image_t& image) {\n    truecolor_histogram_t result;\n    auto                  bpp(image.bpp());\n    auto                  p(image.begin());\n    auto                  last(image.end());\n\n    if (bpp == 3) {\n        while (p != last) {\n            rgba_t rgb{\n                *p++, *p++, *p++, 255,\n            };\n\n            ++result[rgb];\n        }\n    } else if (bpp == 4) {\n        while (p != last) {\n            rgba_t rgb{\n                *p++, *p++, *p++, *p++,\n            };\n\n            ++result[rgb];\n        }\n    }\n\n    return result;\n}\n\n/**************************************************************************************************/\n\ninline auto sq_distance(std::int64_t x, std::int64_t y) {\n    std::int64_t diff(x - y);\n\n    return diff * diff;\n}\n\n/**************************************************************************************************/\n\ninline auto sq_distance(const rgba_t& x, const rgba_t& y) {\n    return sq_distance(x._r, y._r) + sq_distance(x._g, y._g) + sq_distance(x._b, y._b) +\n           sq_distance(x._a, y._a);\n}\n\n/**************************************************************************************************/\n\ninline auto euclidean_distance(const rgba_t& x, const rgba_t& y) {\n    return std::sqrt(sq_distance(x, y));\n}\n\n/**************************************************************************************************/\n\nstd::vector<std::int64_t> compute_sq_d(const std::vector<rgba_t>& colors,\n                                       const std::vector<rgba_t>& seeds) {\n    std::size_t               count(colors.size());\n    std::vector<std::int64_t> values(count);\n\n    tbb::parallel_for<std::size_t>(0,\n                                   count,\n                                   1,\n                                   [& _colors = colors, &_seeds = seeds, &_values = values](\n                                       std::size_t i) {\n                                       const auto&  color = _colors[i];\n                                       std::int64_t d(std::numeric_limits<std::int64_t>::max());\n\n                                       for (const auto& seed : _seeds) {\n                                           d = std::min(d, sq_distance(color, seed));\n\n                                           // color is a seed; we're done here.\n                                           if (d == 0)\n                                               break;\n                                       }\n\n                                       _values[i] = d;\n                                   });\n\n    return values;\n}\n\n/**************************************************************************************************/\n\nstd::vector<rgba_t> k_means_pp(const std::vector<rgba_t>& v, std::size_t n) {\n    if (v.empty() || v.size() <= n)\n        return v;\n\n    static std::random_device rd;\n    static std::mt19937       gen(rd());\n\n    std::uniform_int_distribution<> i_dist(0, v.size() - 1);\n    std::vector<rgba_t>             result(1, v[i_dist(gen)]);\n\n    while (result.size() < n) {\n        auto                         d(compute_sq_d(v, result));\n        std::discrete_distribution<> dist(d.begin(), d.end());\n        std::size_t                  index(dist(gen));\n\n        result.push_back(v[index]);\n    }\n\n    return result;\n}\n\n/**************************************************************************************************/\n\ncolor_table_t make_grad_table() {\n    // grayscale gradient color table from black to white. It might be better to\n    // make this e.g., a green or yellow gradient instead, to ease visibility in\n    // the dark range.\n    std::size_t   count(PNG_MAX_PALETTE_LENGTH);\n    color_table_t result(count);\n\n    for (std::size_t i(0); i < count; ++i) {\n        result[i]._r = i;\n        result[i]._g = i;\n        result[i]._b = i;\n        result[i]._a = 255;\n    }\n\n    return result;\n}\n\n/**************************************************************************************************/\n\nstd::pair<std::size_t, double> quantize(const rgba_t& c, const color_table_t& table) {\n    std::size_t  index{0};\n    std::int64_t min_error{std::numeric_limits<std::int64_t>::max()};\n    std::size_t  count(table.size());\n\n    for (std::size_t i(0); i < count; ++i) {\n        std::int64_t error(sq_distance(c, table[i]));\n\n        if (error >= min_error)\n            continue;\n\n        index     = i;\n        min_error = error;\n\n        // exact match; no need to keep looking\n        if (min_error == 0)\n            break;\n    }\n\n    return std::make_pair(index, std::sqrt(min_error));\n}\n\n/**************************************************************************************************/\n\ntypedef std::pair<image_t, image_t> quantization_t;\n\nquantization_t quantize(const image_t& image, color_table_t color_table) {\n    image_t result(image.width(),\n                   image.height(),\n                   image.depth(),\n                   image.width(),\n                   PNG_COLOR_TYPE_PALETTE);\n    image_t error_result(image.width(),\n                         image.height(),\n                         image.depth(),\n                         image.width(),\n                         PNG_COLOR_TYPE_PALETTE);\n    auto dst(result.begin());\n    auto err_dst(error_result.begin());\n    auto area(image.area());\n\n    tbb::parallel_for<decltype(\n        area)>(0,\n               area,\n               1,\n               [& _image = image, _dst = dst, _err_dst = err_dst, &_color_table = color_table](\n                   auto i) {\n                   auto q(quantize(_image.pixel<std::uint8_t>(i), _color_table));\n\n                   _dst[i]     = q.first;\n                   _err_dst[i] = static_cast<std::uint8_t>(\n                       std::min<std::uint16_t>(std::lround(q.second), 255));\n               });\n\n    result.set_color_table(std::move(color_table));\n    error_result.set_color_table(make_grad_table());\n\n    return std::make_pair(std::move(result), std::move(error_result));\n}\n\n/**************************************************************************************************/\n\nvoid palette_optimizations(const image_t& image, const path_t& output) {\n    if (image.color_type() != PNG_COLOR_TYPE_PALETTE)\n        return;\n\n    indexed_histogram_table_t hist_table(make_indexed_histogram_table(image));\n\n    std::sort(hist_table.begin(), hist_table.end(), [& _image = image](auto& x, auto& y) {\n        // first compare histogram counts (then the actual colors if the counts\n        // are the same).\n        if (x.first < y.first) {\n            return true;\n        } else if (y.first < x.first) {\n            return false;\n        }\n\n        const auto& color_table(_image.color_table());\n        const auto& x_color(color_table[x.second]);\n        const auto& y_color(color_table[y.second]);\n\n#if 1\n        return grey(x_color) < grey(y_color);\n#else\n        return x_color < y_color;\n#endif\n    });\n\n    dump_image(reindex_image(image, hist_table),\n               derived_filename(output, \"sorted\"),\n               save_mode::max).get();\n\n    std::reverse(hist_table.begin(), hist_table.end());\n\n    dump_image(reindex_image(image, hist_table),\n               derived_filename(output, \"sorted_reverse\"),\n               save_mode::max).get();\n}\n\n/**************************************************************************************************/\n\nvoid dump_quantization(const image_t& image, const image_t& error_image, const path_t& output) {\n    dump_image(image, output, save_mode::one);\n    save_png(error_image, associated_filename(output, \"error\"), save_options_t());\n}\n\n/**************************************************************************************************/\n\ninline void dump_quantization(const quantization_t& q, const path_t& output) {\n    dump_quantization(q.first, q.second, output);\n}\n\n/**************************************************************************************************/\n\nstruct centroid_cache_t {\n    std::vector<rgba64_t>      _colors; // cumulative region color\n    std::vector<std::uint64_t> _count;  // number of region members\n\n    centroid_cache_t() = default;\n\n    explicit centroid_cache_t(std::size_t count) : _colors(count), _count(count) {}\n\n    std::size_t size() const {\n        return _colors.size();\n    }\n\n    rgba64_t& centroid(std::size_t index) {\n        return _colors[index];\n    }\n    const rgba64_t& centroid(std::size_t index) const {\n        return _colors[index];\n    }\n\n    std::uint64_t& count(std::size_t index) {\n        return _count[index];\n    }\n    std::uint64_t count(std::size_t index) const {\n        return _count[index];\n    }\n\n    void add_member(std::size_t index, const rgba64_t& color) {\n        ++count(index);\n\n        centroid(index) += color;\n    }\n\n    void remove_member(std::size_t index, const rgba64_t& color) {\n        --count(index);\n\n        centroid(index) -= color;\n    }\n\n    void move_member(std::size_t src_index, std::size_t dst_index, const rgba64_t& color) {\n        if (src_index == dst_index)\n            return;\n\n        remove_member(src_index, color);\n        add_member(dst_index, color);\n    }\n\n    rgba_t color(std::size_t index) const {\n        rgba_t result{0, 0, 0, 255};\n        double c(count(index));\n\n        if (c) {\n            result = shorten<rgba_t>(centroid(index) / c);\n        }\n\n        return result;\n    }\n\n    color_table_t table() const {\n        auto          count(size());\n        color_table_t result;\n\n        for (std::size_t i(0); i < count; ++i)\n            result.push_back(color(i));\n\n        return result;\n    }\n};\n\n/**************************************************************************************************/\n\nstruct round_state_t {\n    round_state_t() = default;\n\n    explicit round_state_t(std::size_t count) : _centroids(count) {}\n\n    auto size() const {\n        return _centroids.size();\n    }\n\n    color_table_t centroid_table() const {\n        return _centroids.table();\n    }\n\n    std::uint64_t error() const {\n        return std::accumulate(_image_error.begin(), _image_error.end(), std::uint64_t(0));\n    }\n\n    std::size_t      _r{0};        // iteration count\n    image_t          _image;       // original image quantized with current color table\n    image_t          _image_error; // rounded per-pixel quantization error\n    centroid_cache_t _centroids;   // cache of cumulative centroid values\n};\n\n/**************************************************************************************************/\n\nvoid dump_round(const round_state_t& round, const path_t& output) {\n    auto error(round.error());\n    auto epp(static_cast<double>(error) / round._image.area());\n\n    std::cout << \"r\" << round._r << \" error: \" << round.error() << \" (\" << epp << \")\\n\";\n\n    dump_quantization(round._image, // image contains this round's color table\n                      round._image_error,\n                      derived_filename(output, \"_r\" + std::to_string(round._r)));\n}\n\n/**************************************************************************************************/\n\nround_state_t k_means_init_state(const image_t& original, color_table_t seed) {\n    round_state_t result(seed.size());\n\n    std::tie(result._image, result._image_error) = quantize(original, std::move(seed));\n\n    auto bpp(original.bpp());\n    auto p_index(result._image.begin());\n    auto p(original.begin());\n    auto last(original.end());\n\n    while (p != last) {\n        std::size_t index(*p_index++);\n        rgba64_t color{p[0], p[1], p[2], static_cast<rgba64_t::value_type>(bpp == 4 ? p[3] : 255)};\n\n        result._centroids.add_member(index, color);\n\n        p += bpp;\n    }\n\n    return result;\n}\n\n/**************************************************************************************************/\n\nround_state_t k_means_round(const image_t& original,\n                            const image_t& prev_image,\n                            round_state_t  state) {\n    ++state._r;\n\n    // requantize the original image with the updated centroid color table\n    std::tie(state._image, state._image_error) = quantize(original, state.centroid_table());\n\n    auto bpp(original.bpp());\n    auto p_prior_index(prev_image.begin());\n    auto p_index(state._image.begin());\n    auto p(original.begin());\n    auto last(original.end());\n\n    while (p != last) {\n        std::size_t prior_index(*p_prior_index++);\n        std::size_t index(*p_index++);\n\n        if (prior_index == index) {\n            p += bpp;\n            continue;\n        }\n\n        rgba64_t color{*p++, *p++, *p++, std::uint64_t(bpp == 4 ? *p++ : 255)};\n\n        state._centroids.move_member(prior_index, index, color);\n    }\n\n    return state;\n}\n\n/**************************************************************************************************/\n\ncolor_table_t k_means(const image_t& image, color_table_t color_table, const path_t& output) {\n    round_state_t round_state(k_means_init_state(image, std::move(color_table)));\n    std::uint64_t best_error(std::numeric_limits<std::uint64_t>::max());\n    color_table_t best_table;\n    image_t       prev_image;\n\n    while (true) {\n        dump_round(round_state, output);\n\n        std::uint64_t error(round_state.error());\n\n        if (error < best_error) {\n            best_table = round_state._image.color_table(); // copy\n            best_error = error;\n\n            // exact quantization found\n            if (best_error == 0)\n                break;\n        }\n\n        if (prev_image == round_state._image)\n            break;\n\n        prev_image = std::move(round_state._image);\n\n        round_state._image_error = image_t();\n\n        round_state = k_means_round(image, prev_image, std::move(round_state));\n    };\n\n    return best_table;\n}\n\n/**************************************************************************************************/\n\nvoid k_means_quantization(const image_t& image, const path_t& output) {\n    truecolor_histogram_t histogram(truecolor_histogram(image));\n    std::vector<rgba_t>   colors;\n\n    for (const auto& color : histogram)\n        colors.push_back(color.first);\n\n    //auto tests = {2, 4, 8, 16, 32, 64, 128, 256};\n    auto tests = {256};\n\n    for (const auto& table_size : tests) {\n        std::vector<rgba_t> seed_table(k_means_pp(colors, table_size));\n\n        dump_quantization(quantize(image, seed_table),\n                          derived_filename(output, std::to_string(table_size) + \"_seed\"));\n\n        color_table_t km_table(k_means(image, seed_table, output));\n        auto          km(quantize(image, km_table));\n\n        dump_quantization(km, derived_filename(output, std::to_string(table_size) + \"_km\"));\n\n        palette_optimizations(km.first, output);\n    }\n}\n\n/**************************************************************************************************/\n\nvoid truecolor_optimizations(const image_t& image, const path_t& output) {\n    if (image.color_type() == PNG_COLOR_TYPE_PALETTE)\n        return;\n\n#if 0\n    k_means_quantization(image, output);\n#else\n    k_means_quantization(premultiply(image), output);\n#endif\n}\n\n/**************************************************************************************************/\n\nint main(int argc, char** argv) try {\n    if (argc <= 1)\n        throw std::runtime_error(\"Source file not specified\");\n\n    if (argc <= 2)\n        throw std::runtime_error(\"Destination directory not specified\");\n\n    path_t        input(canonical(argv[1]));\n    path_t        output(argv[2]);\n    const image_t original(read_png(input.string()));\n\n    // make the output directory fresh\n    remove_all(output);\n    create_directory(output);\n\n    output = canonical(output) / input.leaf();\n\n    dump_image(original, output, save_mode::max);\n\n    truecolor_optimizations(original, output);\n\n    palette_optimizations(original, output);\n\n    return 0;\n} catch (const std::exception& error) {\n    std::cerr << \"Fatal error: \" << error.what() << '\\n';\n    return 0;\n} catch (...) {\n    std::cerr << \"Fatal error: unknown\\n\";\n    return 0;\n}\n/**************************************************************************************************/\n", "meta": {"hexsha": "f28a5b961167970b12d2ec637285b3efb755e256", "size": 19130, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "fosterbrereton/pngpp", "max_stars_repo_head_hexsha": "e50cefc9dffb55d6709e99cbd079e7b318b92957", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/main.cpp", "max_issues_repo_name": "fosterbrereton/pngpp", "max_issues_repo_head_hexsha": "e50cefc9dffb55d6709e99cbd079e7b318b92957", "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/main.cpp", "max_forks_repo_name": "fosterbrereton/pngpp", "max_forks_repo_head_hexsha": "e50cefc9dffb55d6709e99cbd079e7b318b92957", "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.4121510673, "max_line_length": 100, "alphanum_fraction": 0.495033978, "num_tokens": 3948, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624890918021, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4668058508323266}}
{"text": "#define CATCH_CONFIG_MAIN\n\n#include \"CALPHADFreeEnergyFunctionsBinary3Ph2Sl.h\"\n#include \"InterpolationType.h\"\n\n#include \"catch.hpp\"\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 <fstream>\n#include <iostream>\n#include <string>\n\nnamespace pt = boost::property_tree;\n\nTEST_CASE(\"CALPHAD binary three phase, two sublattice KKS\",\n    \"[binary three phase, two sublattice kks]\")\n{\n    Thermo4PFM::EnergyInterpolationType energy_interp_func_type\n        = Thermo4PFM::EnergyInterpolationType::PBG;\n    Thermo4PFM::ConcInterpolationType conc_interp_func_type\n        = Thermo4PFM::ConcInterpolationType::PBG;\n\n    double temperature = 820.;\n\n    std::cout << \" Read CALPHAD database...\" << std::endl;\n    pt::ptree calphad_db;\n    try\n    {\n        pt::read_json(\n            \"../thermodynamic_data/calphadAlCuLFccTheta.json\", calphad_db);\n    }\n    catch (std::exception& e)\n    {\n        std::cerr << \"exception caught: \" << e.what() << std::endl;\n    }\n\n    pt::ptree newton_db;\n    newton_db.put(\"alpha\", 0.5);\n    newton_db.put(\"max_its\", 100);\n\n    Thermo4PFM::CALPHADFreeEnergyFunctionsBinary3Ph2Sl cafe(\n        calphad_db, newton_db, energy_interp_func_type, conc_interp_func_type);\n\n    // initial guesses\n    double c_init0 = 0.8;\n    double c_init1 = 0.6;\n    double c_init2 = 0.67;\n\n    double sol[3] = { c_init0, c_init1, c_init2 };\n\n    // compute concentrations satisfying KKS equations\n    // I think the system at 820K is best behaved in the conc = 0.67-0.8 range\n    double conc = 0.7;\n\n    // This phi doesn't quite give Sum(h(phi)) = 1, but it is close\n    double phi[3] = { 0.3, 0.45, 0.5 };\n\n    cafe.computePhaseConcentrations(temperature, &conc, phi, sol);\n\n    std::cout << \"-------------------------------\" << std::endl;\n    std::cout << \"Temperature = \" << temperature << std::endl;\n    std::cout << \"Result for c = \" << conc << \" and phi = \" << phi[0] << \" \"\n              << phi[1] << \" \" << phi[2] << std::endl;\n    std::cout << \"   cL = \" << sol[0] << std::endl;\n    std::cout << \"   cA = \" << sol[1] << std::endl;\n    std::cout << \"   cB = \" << sol[2] << std::endl;\n\n    const Thermo4PFM::PhaseIndex pi0 = Thermo4PFM::PhaseIndex::phaseL;\n    const Thermo4PFM::PhaseIndex pi1 = Thermo4PFM::PhaseIndex::phaseA;\n    const Thermo4PFM::PhaseIndex pi2 = Thermo4PFM::PhaseIndex::phaseB;\n\n    std::cout << \"Verification:\" << std::endl;\n\n    double derivL;\n    cafe.computeDerivFreeEnergy(temperature, &sol[0], pi0, &derivL);\n    std::cout << \"   dfL/dcL = \" << derivL << std::endl;\n\n    double derivS1;\n    cafe.computeDerivFreeEnergy(temperature, &sol[1], pi1, &derivS1);\n    std::cout << \"   dfS1/dcS1 = \" << derivS1 << std::endl;\n\n    REQUIRE(derivS1 == Approx(derivL).margin(1.e-5));\n\n    double derivS2;\n    cafe.computeDerivFreeEnergy(temperature, &sol[2], pi2, &derivS2);\n    std::cout << \"   dfS2/dcS2 = \" << derivS2 << std::endl;\n\n    REQUIRE(derivS2 == Approx(derivL).margin(1.e-5));\n}\n\nTEST_CASE(\"CALPHAD binary three phase, two sublattice KKS #2\",\n    \"[binary three phase, two sublattice kks #2]\")\n{\n    Thermo4PFM::EnergyInterpolationType energy_interp_func_type\n        = Thermo4PFM::EnergyInterpolationType::PBG;\n    Thermo4PFM::ConcInterpolationType conc_interp_func_type\n        = Thermo4PFM::ConcInterpolationType::PBG;\n\n    double temperature = 820.;\n\n    std::cout << \" Read CALPHAD database...\" << std::endl;\n    pt::ptree calphad_db;\n    try\n    {\n        pt::read_json(\n            \"../thermodynamic_data/calphadAlCuLFccTheta.json\", calphad_db);\n    }\n    catch (std::exception& e)\n    {\n        std::cerr << \"exception caught: \" << e.what() << std::endl;\n    }\n\n    pt::ptree newton_db;\n    newton_db.put(\"alpha\", 1.0);\n    newton_db.put(\"max_its\", 20000);\n\n    Thermo4PFM::CALPHADFreeEnergyFunctionsBinary3Ph2Sl cafe(\n        calphad_db, newton_db, energy_interp_func_type, conc_interp_func_type);\n\n    // initial guesses\n    double c_init0 = 0.79267;\n    double c_init1 = 0.79267;\n    double c_init2 = 0.79267;\n\n    double sol[3] = { c_init0, c_init1, c_init2 };\n\n    // compute concentrations satisfying KKS equations\n    // I think the system at 820K is best behaved in the conc = 0.67-0.8 range\n    double conc = 0.79267;\n\n    // This phi doesn't quite give Sum(h(phi)) = 1, but it is close\n    double phi[3] = { 0.938956, 5.88418e-15, 0.0610444 };\n\n    cafe.computePhaseConcentrations(temperature, &conc, phi, sol);\n\n    std::cout << \"-------------------------------\" << std::endl;\n    std::cout << \"Temperature = \" << temperature << std::endl;\n    std::cout << \"Result for c = \" << conc << \" and phi = \" << phi[0] << \" \"\n              << phi[1] << \" \" << phi[2] << std::endl;\n    std::cout << \"   cL = \" << sol[0] << std::endl;\n    std::cout << \"   cA = \" << sol[1] << std::endl;\n    std::cout << \"   cB = \" << sol[2] << std::endl;\n\n    const Thermo4PFM::PhaseIndex pi0 = Thermo4PFM::PhaseIndex::phaseL;\n    const Thermo4PFM::PhaseIndex pi1 = Thermo4PFM::PhaseIndex::phaseA;\n    const Thermo4PFM::PhaseIndex pi2 = Thermo4PFM::PhaseIndex::phaseB;\n\n    std::cout << \"Verification:\" << std::endl;\n\n    double derivL;\n    cafe.computeDerivFreeEnergy(temperature, &sol[0], pi0, &derivL);\n    std::cout << \"   dfL/dcL = \" << derivL << std::endl;\n\n    double derivS1;\n    cafe.computeDerivFreeEnergy(temperature, &sol[1], pi1, &derivS1);\n    std::cout << \"   dfS1/dcS1 = \" << derivS1 << std::endl;\n\n    // REQUIRE(derivS1 == Approx(derivL).margin(1.e-5));\n\n    double derivS2;\n    cafe.computeDerivFreeEnergy(temperature, &sol[2], pi2, &derivS2);\n    std::cout << \"   dfS2/dcS2 = \" << derivS2 << std::endl;\n\n    REQUIRE(derivS2 == Approx(derivL).margin(1.e-5));\n}\n\nTEST_CASE(\"CALPHAD binary three phase, two sublattice KKS #3\",\n    \"[binary three phase, two sublattice kks #3]\")\n{\n    // This case may require a restart of the solver with new initial conditions\n    // to pass.\n\n    Thermo4PFM::EnergyInterpolationType energy_interp_func_type\n        = Thermo4PFM::EnergyInterpolationType::PBG;\n    Thermo4PFM::ConcInterpolationType conc_interp_func_type\n        = Thermo4PFM::ConcInterpolationType::PBG;\n\n    double temperature = 820.;\n\n    std::cout << \" Read CALPHAD database...\" << std::endl;\n    pt::ptree calphad_db;\n    try\n    {\n        pt::read_json(\n            \"../thermodynamic_data/calphadAlCuLFccTheta.json\", calphad_db);\n    }\n    catch (std::exception& e)\n    {\n        std::cerr << \"exception caught: \" << e.what() << std::endl;\n    }\n\n    pt::ptree newton_db;\n    newton_db.put(\"alpha\", 1.0);\n    newton_db.put(\"max_its\", 30);\n\n    Thermo4PFM::CALPHADFreeEnergyFunctionsBinary3Ph2Sl cafe(\n        calphad_db, newton_db, energy_interp_func_type, conc_interp_func_type);\n\n    // initial guesses\n    double c_init0 = 0.800000011921;\n    double c_init1 = 0.800000011921;\n    double c_init2 = 0.800000011921;\n\n    double sol[3] = { c_init0, c_init1, c_init2 };\n\n    // compute concentrations satisfying KKS equations\n    // I think the system at 820K is best behaved in the conc = 0.67-0.8 range\n    double conc = 0.800000011921;\n\n    // Want phi that corresponds to hphi = [0.982551, 0.0174491, 4.79499e-25]\n    // Want phi that corresponds to hphi = [1.0, 6.18271e-09, 3.69779e-32]\n    // double phi[3] = { 0.998, 8.5e-4, 1.5e-11 };\n    double phi[3] = { 0.998, 8.5e-4, 1.5e-11 };\n\n    cafe.computePhaseConcentrations(temperature, &conc, phi, sol);\n\n    std::cout << \"-------------------------------\" << std::endl;\n    std::cout << \"Temperature = \" << temperature << std::endl;\n    std::cout << \"Result for c = \" << conc << \" and phi = \" << phi[0] << \" \"\n              << phi[1] << \" \" << phi[2] << std::endl;\n    std::cout << \"   cL = \" << sol[0] << std::endl;\n    std::cout << \"   cA = \" << sol[1] << std::endl;\n    std::cout << \"   cB = \" << sol[2] << std::endl;\n\n    const Thermo4PFM::PhaseIndex pi0 = Thermo4PFM::PhaseIndex::phaseL;\n    const Thermo4PFM::PhaseIndex pi1 = Thermo4PFM::PhaseIndex::phaseA;\n    const Thermo4PFM::PhaseIndex pi2 = Thermo4PFM::PhaseIndex::phaseB;\n\n    std::cout << \"Verification:\" << std::endl;\n\n    double derivL;\n    cafe.computeDerivFreeEnergy(temperature, &sol[0], pi0, &derivL);\n    std::cout << \"   dfL/dcL = \" << derivL << std::endl;\n\n    double derivS1;\n    cafe.computeDerivFreeEnergy(temperature, &sol[1], pi1, &derivS1);\n    std::cout << \"   dfS1/dcS1 = \" << derivS1 << std::endl;\n\n    REQUIRE(derivS1 == Approx(derivL).margin(1.e-5));\n\n    double derivS2;\n    cafe.computeDerivFreeEnergy(temperature, &sol[2], pi2, &derivS2);\n    std::cout << \"   dfS2/dcS2 = \" << derivS2 << std::endl;\n\n    REQUIRE(derivS2 == Approx(derivL).margin(1.e-5));\n}\n", "meta": {"hexsha": "d4f851948d117c0dfa1e571591811c149d7b8d05", "size": 8637, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tests/testCALPHADbinaryKKS3Ph2Sl.cc", "max_stars_repo_name": "TApplencourt/Thermo4PFM", "max_stars_repo_head_hexsha": "6e98249d1b871e017c4a15052aed9d00ec2d6d96", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/testCALPHADbinaryKKS3Ph2Sl.cc", "max_issues_repo_name": "TApplencourt/Thermo4PFM", "max_issues_repo_head_hexsha": "6e98249d1b871e017c4a15052aed9d00ec2d6d96", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/testCALPHADbinaryKKS3Ph2Sl.cc", "max_forks_repo_name": "TApplencourt/Thermo4PFM", "max_forks_repo_head_hexsha": "6e98249d1b871e017c4a15052aed9d00ec2d6d96", "max_forks_repo_licenses": ["BSD-3-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.548, "max_line_length": 80, "alphanum_fraction": 0.6208174135, "num_tokens": 2791, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624890918021, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4668058508323266}}
{"text": "#ifndef OTHELLO_AI_ALPHABETAPRUNINGPLAYER_HPP\n#define OTHELLO_AI_ALPHABETAPRUNINGPLAYER_HPP\n\n//Boost headers:\n#include <boost/random.hpp>\n//Othello headers:\n#include <othello/game/IPlayer.hpp>\n#include <othello/game/Game.hpp>\n#include <othello/util/WorkerThreadManager.hpp>\n\n\nnamespace othello\n{\n    \n    namespace ai\n    {\n        \n        ////////////////////////////////////////////////////////////////\n        /// \\class AlphaBetaPruningPlayer\n        ///\n        /// \\brief An AI player that plays moves using the minimax and\n        ///        alpha-beta pruning algorithms\n        ///\n        ////////////////////////////////////////////////////////////////\n        class AlphaBetaPruningPlayer : public game::IPlayer\n        {\n            private:\n        \n                ////////////////////////////////////////////////////////////////\n                /// \\brief The search depth in number of moves ahead\n                ///\n                ////////////////////////////////////////////////////////////////\n                unsigned int searchDepth;\n                \n                \n                ////////////////////////////////////////////////////////////////\n                /// \\brief A mersenne_twister_engine for generating random\n                ///        numbers\n                ///\n                ////////////////////////////////////////////////////////////////\n                boost::random::mt19937 randomNumberGenerator;\n        \n        \n                ////////////////////////////////////////////////////////////////\n                /// \\brief The alpha-beta recursive algorithm\n                ///\n                ////////////////////////////////////////////////////////////////\n                static int64_t alphaBeta(const game::Board& board, const uint8_t& player, const game::Move& move,\n                        uint8_t depth, int64_t alpha, int64_t beta);\n                \n        \n                ////////////////////////////////////////////////////////////////\n                /// \\brief The worker thread manager\n                ///\n                ////////////////////////////////////////////////////////////////\n                util::WorkerThreadManager<int64_t, const game::Board&, const uint8_t&,\n                        const game::Move&, uint8_t, int64_t, int64_t> workerManager;\n        \n                \n            public:\n        \n                ////////////////////////////////////////////////////////////////\n                /// \\brief Class constructor that initialises the members\n                ///\n                /// \\param game A const reference to the game\n                /// \\param player The player number. 0 = player1, 1 = player2\n                /// \\param searchDepth The search depth of the AI\n                /// \\param numThreads The number of worker threads\n                /// \\param seed The seed for the random generator\n                ///\n                ////////////////////////////////////////////////////////////////\n                AlphaBetaPruningPlayer(const unsigned int& searchDepth, const uint8_t& numThreads, const unsigned int& seed)\n                    : searchDepth(searchDepth), randomNumberGenerator(seed),\n                        workerManager(&AlphaBetaPruningPlayer::alphaBeta, numThreads) {}\n                \n                \n                ////////////////////////////////////////////////////////////////\n                /// \\brief Function that is called when the player should make a\n                ///        move. This function uses the negamax and alpha-beta\n                ///        pruning algorithms to make a decision\n                ///\n                /// \\param game A const reference to the game to make a move in\n                /// \\param player The index of this player in the game. (0 is\n                ///        player 1, 1 is player 2)\n                /// \\param possibleMoves A vector of the possible moves\n                ///\n                /// \\return A const pointer to a const move that will be played\n                ///         by the current player. This pointer must point to a\n                ///         move in possibleMoves\n                ///\n                ////////////////////////////////////////////////////////////////\n                const game::Move* makeMove(const game::Game& game, const uint8_t& player,\n                        const std::vector<game::Move>& possibleMoves) override;\n        \n        };\n        \n    }\n    \n}\n\n#endif //OTHELLO_AI_ALPHABETAPRUNINGPLAYER_HPP\n", "meta": {"hexsha": "129e9014303a043c4735605f5ef4db963bcaadfa", "size": 4518, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/othello/ai/AlphaBetaPruningPlayer.hpp", "max_stars_repo_name": "Orfby/Othello-MMP", "max_stars_repo_head_hexsha": "72be0ee38a329eff536b17d1e5334353cfd58c6f", "max_stars_repo_licenses": ["MIT"], "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/othello/ai/AlphaBetaPruningPlayer.hpp", "max_issues_repo_name": "Orfby/Othello-MMP", "max_issues_repo_head_hexsha": "72be0ee38a329eff536b17d1e5334353cfd58c6f", "max_issues_repo_licenses": ["MIT"], "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/othello/ai/AlphaBetaPruningPlayer.hpp", "max_forks_repo_name": "Orfby/Othello-MMP", "max_forks_repo_head_hexsha": "72be0ee38a329eff536b17d1e5334353cfd58c6f", "max_forks_repo_licenses": ["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.2941176471, "max_line_length": 124, "alphanum_fraction": 0.3955289951, "num_tokens": 725, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.782662489091802, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.46680585083232656}}
{"text": "#include <assert.h>\n#include <stdio.h>\n#include <stdint.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include <algorithm>\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\n#define NELEMS(arr) ((sizeof arr) / (sizeof arr[0]))\n\nvoid initfield(void)\n{\n    GF2X gf2e128mod;\n\n    // builds the right poly for GMAC's GF(2^128) modulus\n    BuildIrred(gf2e128mod, 128);\n    GF2E::init(gf2e128mod);\n}\n\nvoid asserthex(const char *s)\n{\n    size_t i, len;\n\n    len = strlen(s);\n    assert(len % 2 == 0);\n    for (i = 0; i < len; i += 1) {\n        char c;\n\n        c = s[i];\n        assert((c >= '0' && c <= '9') ||\n               (c >= 'a' && c <= 'f') ||\n               (c >= 'A' && c <= 'F'));\n    }\n}\n\nvoid hex2bytes(struct slice *s, const char *hex)\n{\n    size_t i;\n    unsigned tmp;\n\n    asserthex(hex);\n\n    s->len = strlen(hex) / 2;\n    s->data = (uint8_t *)malloc(s->len);\n\n    for (i = 0; i < s->len; i += 1) {\n        sscanf(hex + (2*i), \"%02x\", &tmp);\n        s->data[i] = tmp;\n    }\n}\n\nvoid block2felem(GF2E &x, const struct slice *block)\n{\n    GF2X p;\n    size_t i, j;\n\n    for (i = 0; i < block->len; i += 1) {\n        uint8_t b = block->data[i];\n        for (j = 0; j < 8; j += 1) {\n            SetCoeff(p, 8*i + j, b >> (7-j));\n        }\n    }\n\n    conv(x, p);\n}\n\nvoid packuint64(uint8_t *buf, uint64_t x)\n{\n    size_t i;\n\n    for (i = 0; i < 8; i += 1) {\n        buf[i] = x >> (8*(7-i));\n    }\n}\n\nvoid buildpoly(GF2EX &p, const struct slice *a,\n               const struct slice *c, const struct slice *t)\n{\n    GF2E x;\n    const struct slice *sp[] = {a, c};\n    struct slice s, block;\n    size_t i, j;\n    uint8_t lenblock[blocklen];\n\n    i = 0;\n    for (j = 0; j < NELEMS(sp); j += 1) {\n        s = *sp[j];\n        while (s.len > 0) {\n            block.data = s.data;\n            block.len = min(blocklen, s.len);\n\n            block2felem(x, &block);\n            SetCoeff(p, i, x);\n\n            i += 1;\n            s.data += block.len;\n            s.len -= block.len;\n        }\n    }\n\n    block.data = &lenblock[0];\n    block.len = blocklen;\n    packuint64(block.data, a->len << 3);\n    packuint64(block.data + 8, c->len << 3);\n\n    block2felem(x, &block);\n    SetCoeff(p, i, x);\n\n    i += 1;\n\n    assert(t->len == blocklen);\n\n    block2felem(x, t);\n    SetCoeff(p, i, x);\n\n    reverse(p, p);\n}\n\nvoid felem2hex(char *out, const GF2E &x)\n{\n    GF2X p;\n    size_t i;\n    uint b;\n    const char *hex = \"0123456789abcdef\";\n\n    p = rep(x);\n\n    for (i = 0; i < 32; i += 1) {\n        size_t j;\n\n        j = 4 * i;\n        b = ((conv<uint>(coeff(p, j+0)) << 3) |\n             (conv<uint>(coeff(p, j+1)) << 2) |\n             (conv<uint>(coeff(p, j+2)) << 1) |\n             (conv<uint>(coeff(p, j+3))));\n        out[i] = hex[b];\n    }\n\n    out[32] = '\\0';\n}\n", "meta": {"hexsha": "93b71ff0ab19f31f1908b34b7fd5e4b06e22c715", "size": 2899, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tool/gcm.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/gcm.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/gcm.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": 19.0723684211, "max_line_length": 60, "alphanum_fraction": 0.4794756813, "num_tokens": 1007, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.4668058447851718}}
{"text": "#include <boost/cstdint.hpp>\n#include <boost/mpl/int.hpp>\n#include <boost/mpl/assert.hpp>\n#include <nt2/sdk/aligned/is_power_of_2.hpp>\n\nusing nt2::meta::is_power_of_2_c;\n\nint main()\n{\n  BOOST_MPL_ASSERT(( is_power_of_2_c<2>::type ));\n  BOOST_MPL_ASSERT(( is_power_of_2_c<4>::type ));\n  BOOST_MPL_ASSERT(( is_power_of_2_c<8>::type ));\n  BOOST_MPL_ASSERT_NOT(( is_power_of_2_c<0>::type ));\n  BOOST_MPL_ASSERT_NOT(( is_power_of_2_c<10>::type ));\n}\n", "meta": {"hexsha": "6345db41bc00d8dd5453fa75e8bd838ae35d7519", "size": 445, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/sdk/examples/memory/is_power_of_2_c.cpp", "max_stars_repo_name": "brycelelbach/nt2", "max_stars_repo_head_hexsha": "73d7e8dd390fa4c8d251c6451acdae65def70e0b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-24T03:35:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T03:35:10.000Z", "max_issues_repo_path": "modules/sdk/examples/memory/is_power_of_2_c.cpp", "max_issues_repo_name": "brycelelbach/nt2", "max_issues_repo_head_hexsha": "73d7e8dd390fa4c8d251c6451acdae65def70e0b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/sdk/examples/memory/is_power_of_2_c.cpp", "max_forks_repo_name": "brycelelbach/nt2", "max_forks_repo_head_hexsha": "73d7e8dd390fa4c8d251c6451acdae65def70e0b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8125, "max_line_length": 54, "alphanum_fraction": 0.7325842697, "num_tokens": 142, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.4668058447851718}}
{"text": "#ifndef CONCEPTS_DIMENSIONS_MONOID_HPP_INCLUDED\n#define CONCEPTS_DIMENSIONS_MONOID_HPP_INCLUDED\n\n#include <limits>\n\n#include <boost/hana/assert.hpp>\n#include <boost/hana/zero.hpp>\n#include <boost/hana/plus.hpp>\n#include <boost/hana/less.hpp>\n\n#include <gem/fwd/dimensions.hpp>\n\nnamespace boost::hana {\n\ntemplate<typename T>\nstatic constexpr\nauto safe_add(const T & v1, const T & v2)\n{\n    return v1 < std::numeric_limits<T>::max() - v2 ?\n        v1 + v2 : std::numeric_limits<T>::max();\n}\n\ngem::concepts::detail::Dimension {T, cv, max, min}\nstruct zero_impl<gem::Dimension<T, cv, max, min>>\n{\n    static constexpr auto apply(void) -> gem::Dimension<T, 0, 0, 0>\n    {\n        return {};\n    }\n};\n\ngem::concepts::detail::DimensionPair {T1, cv1, max1, min1, T2, cv2, max2, min2}\nstruct plus_impl<gem::Dimension<T1, cv1, max1, min1>,\n                 gem::Dimension<T2, cv2, max2, min2>>\n{\nprivate:\n    using ctype = typename boost::hana::common<T1, T2>::type;\n\npublic:\n    static constexpr auto\n    apply(const gem::Dimension<T1, cv1, max1, min1>& d1,\n          const gem::Dimension<T2, cv2, max2, min2>& d2)\n    {\n        BOOST_HANA_RUNTIME_CHECK_MSG(d1.value() <\n                                     std::numeric_limits<ctype>::max() -\n                                     d2.value(),\n                                     \"Dimension overflow...\");\n        return gem::Dimension<ctype, safe_add<ctype>(cv1, cv2),\n                                     safe_add<ctype>(max1, max2),\n                                     safe_add<ctype>(min1, min2)> {d1.value() +\n                                                                   d2.value()};\n    }\n};\n\ntemplate<typename T1, T1 cv1, typename T2, T2 cv2>\nstruct plus_impl<gem::Dimension<T1, cv1, cv1, cv1>,\n                 gem::Dimension<T2, cv2, cv2, cv2>>\n{\nprivate:\n    using ctype = typename boost::hana::common<T1, T2>::type;\n\npublic:\n    static constexpr auto\n    apply(const gem::Dimension<T1, cv1, cv1, cv1> &,\n          const gem::Dimension<T2, cv2, cv2, cv2> &)\n    {\n        constexpr auto c = integral_c<ctype, cv1>;\n        constexpr auto m = integral_c<ctype,\n                                      std::numeric_limits<ctype>::max() - cv2>;\n        BOOST_HANA_CONSTANT_CHECK_MSG(c < m, \"Dimension overflow...\");\n        constexpr ctype s = static_cast<ctype>(cv1) +\n                            static_cast<ctype>(cv2);\n        return gem::Dimension<ctype, s, s, s> {};\n    }\n};\n\n}  // namespace boost::hana\n\nnamespace gem {\n\ntemplate <typename T1, T1 cv1, T1 cv_max1, T1 cv_min1,\n          typename T2, T2 cv2, T2 cv_max2, T2 cv_min2>\nconstexpr inline auto\noperator+(const gem::Dimension<T1, cv1, cv_max1, cv_min1> & d1,\n          const gem::Dimension<T2, cv2, cv_max2, cv_min2> & d2)\n{\n    return boost::hana::plus(d1, d2);\n}\n\n}  // namespace gem\n\n#endif  // !CONCEPTS_DIMENSIONS_MONOID_HPP_INCLUDED\n", "meta": {"hexsha": "ccbefb22a641ea59514d141bf90ee8241c7c8c3b", "size": 2858, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/gem/concept/dimensions_monoid.hpp", "max_stars_repo_name": "RomainBrault/Gem", "max_stars_repo_head_hexsha": "0eff3cb034a0faaca894316b72f4b005e72e0f5d", "max_stars_repo_licenses": ["MIT"], "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/gem/concept/dimensions_monoid.hpp", "max_issues_repo_name": "RomainBrault/Gem", "max_issues_repo_head_hexsha": "0eff3cb034a0faaca894316b72f4b005e72e0f5d", "max_issues_repo_licenses": ["MIT"], "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/gem/concept/dimensions_monoid.hpp", "max_forks_repo_name": "RomainBrault/Gem", "max_forks_repo_head_hexsha": "0eff3cb034a0faaca894316b72f4b005e72e0f5d", "max_forks_repo_licenses": ["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.7311827957, "max_line_length": 79, "alphanum_fraction": 0.5801259622, "num_tokens": 783, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4668058447851717}}
{"text": "#include <stan/math/prim.hpp>\n#include <boost/math/special_functions/digamma.hpp>\n#include <gtest/gtest.h>\n#include <cmath>\n#include <limits>\n\nTEST(MathFunctions, digamma) {\n  EXPECT_FLOAT_EQ(boost::math::digamma(0.5), stan::math::digamma(0.5));\n  EXPECT_FLOAT_EQ(boost::math::digamma(-1.5), stan::math::digamma(-1.5));\n}\n\nTEST(MathFunctions, digamma_nan) {\n  double nan = std::numeric_limits<double>::quiet_NaN();\n\n  EXPECT_TRUE(std::isnan(stan::math::digamma(nan)));\n\n  EXPECT_TRUE(std::isnan(stan::math::digamma(-1)));\n\n  EXPECT_TRUE(std::isnormal(stan::math::digamma(1.0E50)));\n}\n\nTEST(MathFunctions, digamma_works_with_other_functions) {\n  Eigen::VectorXd a(5);\n  a << 1.1, 1.2, 1.3, 1.4, 1.5;\n  Eigen::RowVectorXd b(5);\n  b << 1.1, 1.2, 1.3, 1.4, 1.5;\n  stan::math::multiply(a, stan::math::digamma(b));\n}\n", "meta": {"hexsha": "b0d37f98b7e149e96bc4f268646021f2314b58f3", "size": 811, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/prim/fun/digamma_test.cpp", "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": "test/unit/math/prim/fun/digamma_test.cpp", "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": "test/unit/math/prim/fun/digamma_test.cpp", "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": 27.9655172414, "max_line_length": 73, "alphanum_fraction": 0.683107275, "num_tokens": 275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4667802099398684}}
{"text": "/*** \n * @Author: JoeyforJoy\n * @Date: 2021-05-06 21:55:55\n * @LastEditTime: 2021-10-23 00:13:45\n * @LastEditors: JoeyforJoy\n * @Description: A simple KD Tree implementation\n * @Usage:\n *      Eigen::MatrixXd cloud_eigen; \n *      cloud_eigen = ... ; // assign point cloud for cloud_eigen\n *      int leaf_size = 5; // the minimum number of points in the leaf nodes\n *      KDTree kdtree(cloud_eigen, leaf_size); // build kdtree\n *      // knn search\n *      std::vector<int> pts_idx; // indices of result points\n *      std::vector<double> pts_dist; // distance of result points\n *      int k = 5;\n *      kdtree.knnSearch(point, k, pts_idx, pts_dist);\n *      // radius search\n *      int radius = 5;\n *      kdtree.radiusSearch(point, radius, pts_idx, pts_dist);\n */\n\n#ifndef KDTREE_HPP\n#define KDTREE_HPP\n#include <memory>\n#include <numeric>\n#include <Eigen/Core>\n\n#include \"resultSet.hpp\"\n\nnamespace NNSearch {\n    struct KDNode {\n        typedef std::shared_ptr<KDNode> Ptr;\n        public:\n            int dim; // 0 for X, 1 for Y, 2 for X\n            double value;\n            KDNode::Ptr left;\n            KDNode::Ptr right;\n            bool isLeaf;\n            std::vector<int> points_idx;\n        public:\n            KDNode(): dim(0), value(0), isLeaf(false), left(nullptr), right(nullptr){}\n            KDNode(int dim_): dim(dim_), value(0), left(nullptr), right(nullptr), isLeaf(false) {}\n    };\n\n    class KDTree {\n        EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n        public:\n            KDTree(): _root(nullptr), _leaf_size(0) {}\n            // copy constructor\n            KDTree(const KDTree& tree): _root(tree.getRoot()), _leaf_size(tree._leaf_size) {}\n            // copy assign\n            KDTree& operator=(const KDTree& tree) {_root = tree.getRoot(); _leaf_size = tree._leaf_size;}\n            // build KDTree\n            KDTree(Eigen::MatrixXd &points, int leaf_size): _points(points), _leaf_size(leaf_size) {\n                std::vector<int> pts_idx(points.rows(), 0);\n                std::iota(pts_idx.begin(), pts_idx.end(), 0);\n                _root = _buildKDTree(pts_idx, 0, pts_idx.size(), 0);\n            }\n\n            ~KDTree() {}\n\n            KDNode::Ptr getRoot() const {return _root;}\n            int getLeafSize() const {return _leaf_size;}\n\n            // knn search\n            void knnSearch(const Eigen::Vector3d &point, int k, std::vector<int> &pts_idx, std::vector<double> &pts_dist) {\n                // KNN search\n                KNNResultSet result_set(k);\n                _SearchIdxDist(_root, point, result_set);\n                // unpack result\n                result_set.unpackResultSet(pts_idx, pts_dist);\n            }\n\n            // radius search\n            void radiusSearch(const Eigen::Vector3d &point, double radius, std::vector<int> &pts_idx, std::vector<double> &pts_dist) {\n                // radius search\n                RadiusResultSet result_set(radius);\n                _SearchIdxDist(_root, point, result_set);\n                // unpack result\n                result_set.unpackResultSet(pts_idx, pts_dist);\n            }\n\n        private:\n            void _SearchIdxDist(KDNode::Ptr root, const Eigen::Vector3d &point, AbstractResultSet &result_set) {\n                if (!root) return;\n                if (root->isLeaf) {\n                    // process leaf\n                    for (int idx: root->points_idx) {\n                        double dist = (_points.row(idx) - point.transpose()).norm();\n                        result_set.addOnePoint(idx, dist);\n                    }\n                } else {\n                    if (point(root->dim) <= root->value) { // If the value is less than the root, search the left.\n                        _SearchIdxDist(root->left, point, result_set);\n                        // If the point is too far, don't search the right tree.\n                        if (fabs(point(root->dim) - root->value) <= result_set.worst_dist()) {\n                            _SearchIdxDist(root->right, point, result_set);\n                        }\n                    } else {\n                        _SearchIdxDist(root->right, point, result_set);\n                        // If the point is too far, don't search the left tree.\n                        if (fabs(point(root->dim) - root->value) <= result_set.worst_dist()) {\n                            _SearchIdxDist(root->left, point, result_set);\n                        }\n                    }\n                }\n            }\n\n            // \u6784\u9020 KD \u6811\n            KDNode::Ptr _buildKDTree(std::vector<int> &pts_idx, \n                                    int left, int right, int dim) {\n                if (right - left <= 0) return nullptr;\n                KDNode::Ptr root(new KDNode(dim));\n                if (right - left <= _leaf_size ) {\n                    root->isLeaf = true;\n                    root->points_idx.assign(pts_idx.begin()+left, pts_idx.begin()+right);\n                } else {\n                    // current splitting axis\n                    auto min_max_x = std::minmax_element(\n                        pts_idx.begin() + left,\n                        pts_idx.begin() + right,\n                        [&](int lhs, int rhs) { return _points(lhs, 0) < _points(rhs, 0); });\n                    auto min_max_y = std::minmax_element(\n                        pts_idx.begin() + left,\n                        pts_idx.begin() + right,\n                        [&](int lhs, int rhs) { return _points(lhs, 1) < _points(rhs, 1); });\n                    auto min_max_z = std::minmax_element(\n                        pts_idx.begin() + left,\n                        pts_idx.begin() + right,\n                        [&](int lhs, int rhs) { return _points(lhs, 2) < _points(rhs, 2); });\n                    auto dx = _points((*min_max_x.second),0) - _points((*min_max_x.first),0);\n                    auto dy = _points((*min_max_x.second),1) - _points((*min_max_x.first),1);\n                    auto dz = _points((*min_max_x.second),2) - _points((*min_max_x.first),2);\n                    dim = (dx > dy ? (dx > dz ? 0 : 2) : (dy > dz ? 1 : 2));\n\n                    // find middle o(NlogN)\n                    std::nth_element (\n                        pts_idx.begin() + left,\n                        pts_idx.begin() + (right - left) / 2 + left,\n                        pts_idx.begin() + right,\n                        [&]\n                        (int lhs, int rhs) \n                        { return _points(lhs, dim) < _points(rhs, dim);});\n\n                    // find the middle and split\n                    int mid = (right - left) / 2 + left;\n\n                    root->value = (_points(pts_idx[mid], dim) + _points(pts_idx[mid+1], dim) + 1e-3) /2 ;\n                    root->left = _buildKDTree(pts_idx, left, mid, dim);\n                    root->right = _buildKDTree(pts_idx, mid, right, dim);\n                }\n                return root;\n            }\n\n        private:\n            Eigen::MatrixXd _points;\n            KDNode::Ptr _root;\n            int _leaf_size;\n    };\n}\n#endif\n", "meta": {"hexsha": "5d1a8ab5d6676b11b4183a45bd309eaed6274bd1", "size": 7032, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/kdtree.hpp", "max_stars_repo_name": "JoeyforJoy/Eigen-Based-KD-Tree", "max_stars_repo_head_hexsha": "61b718460d950bb7e8fe47329ed8d27f8a7b9227", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kdtree.hpp", "max_issues_repo_name": "JoeyforJoy/Eigen-Based-KD-Tree", "max_issues_repo_head_hexsha": "61b718460d950bb7e8fe47329ed8d27f8a7b9227", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kdtree.hpp", "max_forks_repo_name": "JoeyforJoy/Eigen-Based-KD-Tree", "max_forks_repo_head_hexsha": "61b718460d950bb7e8fe47329ed8d27f8a7b9227", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-29T02:19:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-29T02:19:57.000Z", "avg_line_length": 43.4074074074, "max_line_length": 134, "alphanum_fraction": 0.4927474403, "num_tokens": 1632, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4667802099398684}}
{"text": "/**\n *  @copyright Copyright 2018 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 HelperMathFunctionsTest.h\n */\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE HelperMathFunctionsTest\n\n#include \"JPetSimplePhysSignalReco/HelperMathFunctions.h\"\n#include <boost/test/unit_test.hpp>\n\nusing namespace boost::numeric::ublas;\n\nBOOST_AUTO_TEST_SUITE(FirstSuite)\n\nBOOST_AUTO_TEST_CASE(polynomialFitTest1)\n{\n  vector<float> time(4);\n  vector<float> volt(4);\n  int alfa = 1;\n  float v0 = -0.10;\n  time(0) = 1035.0;\n  time(1) = 1542.0;\n  time(2) = 2282.0;\n  time(3) = 2900.0;\n  volt(0) = -0.06;\n  volt(1) = -0.20;\n  volt(2) = -0.35;\n  volt(3) = -0.50;\n  float result = polynomialFit(time, volt, alfa, v0);\n  float epsilon = 0.1;\n  BOOST_REQUIRE_CLOSE(result, 1171.98, epsilon);\n}\n\nBOOST_AUTO_TEST_CASE(polynomialFitTest2)\n{\n  vector<float> time(4);\n  vector<float> volt(4);\n  int alfa = 2;\n  float v0 = -0.05;\n  time(0) = 1035.0;\n  time(1) = 1542.0;\n  time(2) = 2282.0;\n  time(3) = 2900.0;\n  volt(0) = -0.06;\n  volt(1) = -0.20;\n  volt(2) = -0.35;\n  volt(3) = -0.50;\n  float result = polynomialFit(time, volt, alfa, v0);\n  float epsilon = 0.1;\n  BOOST_REQUIRE_CLOSE(result, 793.1, epsilon);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "837dcdbdd69965cf0bf471627cb0a8b9f5ef2850", "size": 1757, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/Tasks/JPetSimplePhysSignalReco/HelperMathFunctionsTest.cpp", "max_stars_repo_name": "BlurredChoise/j-pet-framework", "max_stars_repo_head_hexsha": "f6728e027fae2b6ac0bdf274141254689894aa08", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2016-07-04T14:54:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-11T14:19:29.000Z", "max_issues_repo_path": "tests/Tasks/JPetSimplePhysSignalReco/HelperMathFunctionsTest.cpp", "max_issues_repo_name": "BlurredChoise/j-pet-framework", "max_issues_repo_head_hexsha": "f6728e027fae2b6ac0bdf274141254689894aa08", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 119.0, "max_issues_repo_issues_event_min_datetime": "2016-06-17T20:22:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T08:50:22.000Z", "max_forks_repo_path": "tests/Tasks/JPetSimplePhysSignalReco/HelperMathFunctionsTest.cpp", "max_forks_repo_name": "BlurredChoise/j-pet-framework", "max_forks_repo_head_hexsha": "f6728e027fae2b6ac0bdf274141254689894aa08", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 30.0, "max_forks_repo_forks_event_min_datetime": "2016-06-17T17:56:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-30T22:20:19.000Z", "avg_line_length": 27.0307692308, "max_line_length": 79, "alphanum_fraction": 0.6943653956, "num_tokens": 563, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4667802099398684}}
{"text": "#include <boost/random/mersenne_twister.hpp>\r\n#include <boost/random/uniform_real.hpp>\r\n#include <boost/graph/graph_traits.hpp>\r\n#include <boost/graph/adjacency_list.hpp>\r\n#include <boost/graph/random.hpp>\r\n#include <queue>\r\n#include <vector>\r\n#include <chrono>\r\n#include <boost/graph/graphviz.hpp>\r\n#include \"boostHelper/squareboost.h\"\r\n#include \"leda/ledaRandomBiMaxFlow.h\"\r\nusing namespace boost;\r\nstruct NodeInfo;\r\nstruct EdgeInfo;\r\ntypedef boost::adjacency_list<vecS, vecS, bidirectionalS, NodeInfo, EdgeInfo> Graph;\r\ntypedef boost::graph_traits<Graph>::vertex_descriptor vertex_d;\r\ntypedef boost::graph_traits<Graph>::edge_descriptor edge_d;\r\nvertex_d s, t;\r\nGraph G_random;\r\n\r\nstd::queue<vertex_d> overflowQ;\r\n\r\n\r\n// vertex_d A = add_vertex(G_random);\r\n// vertex_d B = add_vertex(G_random);\r\n// vertex_d C = add_vertex(G_random);\r\n// vertex_d D = add_vertex(G_random);\r\n// vertex_d E = add_vertex(G_random);\r\n// vertex_d F = add_vertex(G_random);\r\n\r\n// std::pair<edge_d, bool> AB = add_boost::edge(A, B, G_random);\r\n// std::pair<edge_d, bool> AC = add_boost::edge(A, C, G_random);\r\n// std::pair<edge_d, bool> BD = add_boost::edge(B, D, G_random);\r\n// std::pair<edge_d, bool> CE = add_boost::edge(C, E, G_random);\r\n// std::pair<edge_d, bool> DC = add_boost::edge(D, C, G_random);\r\n// std::pair<edge_d, bool> EF = add_boost::edge(E, F, G_random);\r\n\r\n// std::pair<edge_d, bool> BA = add_boost::edge(B, A, G_random);\r\n// std::pair<edge_d, bool> CA = add_boost::edge(C, A, G_random);\r\n// std::pair<edge_d, bool> DB = add_boost::edge(D, B, G_random);\r\n// std::pair<edge_d, bool> EC = add_boost::edge(E, C, G_random);\r\n// std::pair<edge_d, bool> CD = add_boost::edge(C, D, G_random);\r\n// std::pair<edge_d, bool> FE = add_boost::edge(F, E, G_random);\r\n\r\n\r\nint main()\r\n{\r\n\tint n1_length = 0;\r\n\tbool logging;\r\n\tint a_vertices = 0, b_vertices = 0, m_edges = 0;\r\n\tstd::cout << \"Num of A vertices?\\n\";\r\n\tstd::cin >> a_vertices;\r\n\tstd::cout << \"Num of B vertices?\\n\";\r\n\tstd::cin >> b_vertices;\r\n\tstd::cout << \"Logging (1/0)\\n\";\r\n\tstd::cin >> logging;\r\n\t// std::cout << \"Num of M edges?\\n\";\r\n\t// std::cin >> m_edges;\r\n\tledaRandomBiMaxFlow(G_random, s, t, a_vertices, b_vertices, m_edges, n1_length); //generate_square_bipartite(8, s, t, n1_length);\r\n\t// std::cout << \"Returned\";\r\n\tboost::property_map<Graph, int EdgeInfo::*>::type residual = get(&EdgeInfo::residual_flow, G_random);\r\n\tboost::property_map<Graph, int NodeInfo::*>::type v_id = get(&NodeInfo::id, G_random);\r\n\tboost::property_map<Graph, int NodeInfo::*>::type height = get(&NodeInfo::height, G_random);\r\n\tboost::property_map<Graph, int NodeInfo::*>::type excess = get(&NodeInfo::excess, G_random);\r\n\t// write_graphviz(std::cout, G_random, make_label_writer(v_id), make_label_writer(residual));\r\n\tauto end = std::chrono::system_clock::now(); //declaring timers\r\n\tauto start = std::chrono::system_clock::now();\r\n\tauto duration = std::chrono::duration_cast<std::chrono::microseconds>(end - start);\r\n\tstart = std::chrono::system_clock::now();\r\n\r\n\tgraph_traits<Graph>::vertex_iterator vi, vi_end;\r\n\tgraph_traits<Graph>::edge_iterator ei, ei_end;\r\n\t// -----------------------------Initialization----------------------------------\r\n\tint nums = 0;\r\n\tfor (tie(vi, vi_end) = vertices(G_random); vi != vi_end; vi++)\r\n\t{ //initialise heights and excess\r\n\t\tv_id[*vi] = nums;\r\n\t\theight[*vi] = 1000000;\r\n\t\texcess[*vi] = 0;\r\n\t\tnums++;\r\n\t}\r\n\t// std::cout << \"S is: \" << v_id[s] << \" and t is: \" << v_id[t] << \"\\n\";\r\n\r\n\t// residual[AB.first] = 5;\r\n\t// residual[AC.first] = 4;\r\n\t// residual[BD.first] = 4;\r\n\t// residual[DC.first] = 2;\r\n\t// residual[CE.first] = 4;\r\n\t// residual[EF.first] = 4;\r\n\t// residual[BA.first] = 0;\r\n\t// residual[CA.first] = 0;\r\n\t// residual[DB.first] = 0;\r\n\t// residual[CD.first] = 0;\r\n\t// residual[EC.first] = 0;\r\n\t// residual[FE.first] = 0;\r\n\t// std::cout << \"inited heights and excess\\n\";\r\n\theight[t] = 0;\r\n\tgraph_traits<Graph>::out_edge_iterator edgei, edgei_end;\r\n\tgraph_traits<Graph>::out_edge_iterator edgej, edgej_end;\r\n\tgraph_traits<Graph>::in_edge_iterator bi, bi_end;\r\n\r\n\tfor (tie(edgei, edgei_end) = out_edges(s, G_random); edgei != edgei_end; edgei++) // max flow on outgoing edges of S and update excess of S's neighbours, add residual edge\r\n\t{\r\n\t\t// std::cout << \"from S to : \" << target(*edgei, G_random) << \"\\n The edge is: \" << residual[*edgei] << \"\\n\";\r\n\t\texcess[target(*edgei, G_random)] = residual[*edgei];\r\n\t\t// std::cout << \"updated excess of node\\n\";\r\n\t\tif (excess[target(*edgei, G_random)] != 0 && target(*edgei, G_random) != t)\r\n\t\t\toverflowQ.push(target(*edgei, G_random));\r\n\t\t// std::cout << \"prob added q\\n\";\r\n\t\t// std::pair<edge_d, bool> resEdge = boost::edge(target(*edgei, G_random), s, G_random);\r\n\t\t// std::cout << \"made edge to back\\n\";\r\n\t\tresidual[boost::edge(target(*edgei, G_random), s, G_random).first] = residual[*edgei];\r\n\t\t// std::cout << \"updated rev cap\\n\";\r\n\t\tresidual[*edgei] = 0;\r\n\t\t// std::cout << \"zeroed cap\\n\";\r\n\t}\r\n\t// std::cout << \"inited S things\\n\";\r\n\tstd::queue<vertex_d> q;\r\n\tq.push(t);\r\n\tvertex_d temp;\r\n\r\n\twhile (!q.empty())\r\n\t{\r\n\t\ttemp = q.front();\r\n\t\tq.pop();\r\n\t\tint alt = 0;\r\n\t\tfor (tie(bi, bi_end) = in_edges(temp, G_random); bi != bi_end; bi++)\r\n\t\t{\r\n\t\t\t// std::cout << \"Reading Edge: \" << source(*bi, G_random) << \" ---> \" << target(*bi, G_random);\r\n\t\t\talt = height[temp] + 1;\r\n\t\t\tif (alt < height[source(*bi, G_random)])\r\n\t\t\t{\r\n\t\t\t\theight[source(*bi, G_random)] = alt;\r\n\t\t\t\tq.push(source(*bi, G_random));\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t// std::cout << \"n1_length: \" << n1_length << \"\\n\";\r\n\theight[s] = 2 * n1_length + 1;\r\n\r\n\t//-----------------------------------------------------------------------------------------\r\n\t//--------------------------Algorithm------------------------------------------------------\r\n\tbool admissableEdge1 = false;\r\n\tbool admissableEdge2 = false;\r\n\tbool elementExistsInQ = false;\r\n\r\n\tint j_minimum_height = 10000, i_minimum_height = 10000;\r\n\tint minimum_flow = 0;\r\n\tint times = 0;\r\n\tvertex_d k, j, i;\r\n\tstd::pair<edge_d, bool> newEdge;\r\n\twhile (!overflowQ.empty())\r\n\t{\r\n\t\t// std::cout << \"The q has: \" << overflowQ.size() << \"elements \\n\";\r\n\t\tvertex_d overflower = overflowQ.front();\r\n\t\toverflowQ.pop();\r\n\t\t// std::cout << \"The excess node is: \" << overflower << \"\\n and it's excess is: \" << excess[overflower] << \"\\n\";\r\n\t\tadmissableEdge1 = false;\r\n\t\tif (overflower == s || overflower == t || excess[overflower] == 0)\r\n\t\t\tcontinue;\r\n\r\n\r\n\t\tfor (tie(edgei, edgei_end) = out_edges(overflower, G_random); edgei != edgei_end; edgei++) // max flow on outgoing edges of S and update excess of S's neighbours, add residual edge\r\n\t\t{\r\n\t\t\tj = target(*edgei, G_random);\r\n\t\t\ti = overflower;\r\n\t\t\t// std::cout << \"the edge goes from \" << i << \" To \" << j << \"and has a residual of: \" << residual[*edgei] << \"\\n\";\r\n\r\n\t\t\tif (height[i] > height[j] && residual[*edgei] > 0)\r\n\t\t\t{\r\n\r\n\t\t\t\tadmissableEdge1 = true;\r\n\t\t\t\t// std::cout << \"admissable i-j: \" << i << \"-\" << j << \"\\n\";\r\n\t\t\t\tadmissableEdge2 = false;\r\n\t\t\t\tfor (tie(edgej, edgej_end) = out_edges(j, G_random); edgej != edgej_end; edgej++)\r\n\t\t\t\t{\r\n\t\t\t\t\tif (j == s)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\t// std::cout << \"found only S to push\";\r\n\t\t\t\t\t\tminimum_flow = std::min(excess[i], residual[*edgei]);\r\n\t\t\t\t\t\tresidual[*edgei] -= minimum_flow;\r\n\t\t\t\t\t\t// std::cout << \"MINFLOW: \" << minimum_flow << \"\\n\";\r\n\t\t\t\t\t\tresidual[boost::edge(s, i, G_random).first] += minimum_flow;\r\n\t\t\t\t\t\t// std::cout << \"Pushing from \" << i << \"to s, flow: \" << minimum_flow << \"\\n\";\r\n\t\t\t\t\t\texcess[i] -= minimum_flow;\r\n\t\t\t\t\t\texcess[s] += minimum_flow;\r\n\t\t\t\t\t\tadmissableEdge2 = true;\r\n\t\t\t\t\t\tcontinue;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (height[j] > height[target(*edgej, G_random)] && residual[*edgej] > 0)\r\n\t\t\t\t\t{\r\n\r\n\t\t\t\t\t\tk = target(*edgej, G_random);\r\n\t\t\t\t\t\t// std::cout << \"admissable j-k :\" << j << \"-\" << k << \"\\n\";\r\n\t\t\t\t\t\tadmissableEdge2 = true;\r\n\t\t\t\t\t\tminimum_flow = std::min({excess[i], residual[*edgei], residual[*edgej]});\r\n\t\t\t\t\t\t// std::cout << \"minimum flow is: \" << minimum_flow << \"\\n\";\r\n\t\t\t\t\t\texcess[i] -= minimum_flow;\r\n\t\t\t\t\t\tresidual[boost::edge(j, i, G_random).first] += minimum_flow;\r\n\t\t\t\t\t\tresidual[*edgei] -= minimum_flow;\r\n\r\n\t\t\t\t\t\tresidual[boost::edge(k, j, G_random).first] += minimum_flow;\r\n\t\t\t\t\t\tresidual[boost::edge(j, k, G_random).first] -= minimum_flow;\r\n\t\t\t\t\t\texcess[k] += minimum_flow;\r\n\t\t\t\t\t\tif (k != t && k != s)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\toverflowQ.push(k);\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t// std::cout << \"pushed: \" << minimum_flow << \"\\n\";\r\n\t\t\t\t\t\t// excess[j] = 0;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tif (!admissableEdge2)\r\n\t\t\t\t{\r\n\t\t\t\t\t// std::cout << \"Relabel J\\n\";\r\n\r\n\t\t\t\t\tfor (tie(edgej, edgej_end) = out_edges(j, G_random); edgej != edgej_end; edgej++)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\t// std::cout << \"MinHJ: \" << j_minimum_height << \" and targetJ: \" << height[target(*edgej, G_random)] << \"\\n\";\r\n\t\t\t\t\t\tif (residual[*edgej] == 0)\r\n\t\t\t\t\t\t\tcontinue;\r\n\t\t\t\t\t\tif (j_minimum_height > height[target(*edgej, G_random)])\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tj_minimum_height = height[target(*edgej, G_random)];\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\t// std::cout << \"The j minimum height is: \" << j_minimum_height << \" so j's height becomes: \" << j_minimum_height + 1 << \"\\n\";\r\n\t\t\t\t\theight[j] = j_minimum_height + 1;\r\n\t\t\t\t\tj_minimum_height = 10000;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (!admissableEdge1)\r\n\t\t{\r\n\t\t\t// std::cout << \"Relabel I, the overflower: \" << overflower << \"\\n\";\r\n\t\t\tfor (tie(edgei, edgei_end) = out_edges(i, G_random); edgei != edgei_end; edgei++)\r\n\t\t\t{\r\n\t\t\t\t// std::cout << \"MinH: \" << i_minimum_height << \" and target: \" << height[target(*edgei, G_random)] << \"\\n\";\r\n\t\t\t\tif (residual[*edgei] == 0)\r\n\t\t\t\t\tcontinue;\r\n\t\t\t\tif (i_minimum_height > height[target(*edgei, G_random)])\r\n\t\t\t\t{\r\n\t\t\t\t\ti_minimum_height = height[target(*edgei, G_random)];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t// std::cout << \"The i minimum height is: \" << i_minimum_height << \" so i's height becomes: \" << i_minimum_height + 1 << \"\\n\";\r\n\t\t\theight[i] = i_minimum_height + 1;\r\n\t\t\ti_minimum_height = 10000;\r\n\t\t}\r\n\t\tif (excess[overflower] > 0 && overflower != s && overflower != t)\r\n\t\t{\r\n\t\t\toverflowQ.push(overflower);\r\n\t\t}\r\n\r\n\t\t// // \r\n\t\tif (logging){\r\n\t\t\tstd::cout << \"--------------------------------\\n\";\r\n\t\t\twrite_graphviz(std::cout, G_random, make_label_writer(excess), make_label_writer(residual));\r\n\t\t}\r\n\t}\r\n\t// std::cout << \"Done\";\r\n\t// write_graphviz(std::cout, G_random, make_label_writer(excess), make_label_writer(residual));\r\n\r\n\tend = std::chrono::system_clock::now();\r\n\tduration = std::chrono::duration_cast<std::chrono::microseconds>(end - start);\r\n\tstd::cout << \"-------------BOOST-------------\\n\";\r\n\tstd::cout << \"Duration :\" << duration.count() << \"\\n\";\r\n\tstd::cout << \"S is: \" << s << \"and t is: \" << t << \"\\n\";\r\n\tstd::cout << \"Maximum Flow is: \" << excess[t] << \"\\n\";\r\n\tstd::cout << \"To visualise the graphs visit: https://dreampuf.github.io/GraphvizOnline \\n and paste the dot code which looks like digraph G {...}\\n\";\r\n\treturn 0;\r\n}\r\n", "meta": {"hexsha": "df5660556285a525ac745034331f48df219c2bb0", "size": 10760, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "sphantom99/BoostLedaMaxFlow", "max_stars_repo_head_hexsha": "845edd46380c496cec08e9ad0e6d369911958f8b", "max_stars_repo_licenses": ["MIT"], "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": "sphantom99/BoostLedaMaxFlow", "max_issues_repo_head_hexsha": "845edd46380c496cec08e9ad0e6d369911958f8b", "max_issues_repo_licenses": ["MIT"], "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": "sphantom99/BoostLedaMaxFlow", "max_forks_repo_head_hexsha": "845edd46380c496cec08e9ad0e6d369911958f8b", "max_forks_repo_licenses": ["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.2700729927, "max_line_length": 183, "alphanum_fraction": 0.5893122677, "num_tokens": 3223, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4667802099398684}}
{"text": "\n#include <cellogram/image_reader.h>\n#include <Eigen/Dense>\n#include <iostream>\n\nint main(int argc, char** argv) {\n\tconst std::string root = DATA_DIR;\n\tconst std::string filename = root + \"cell.tif\";\n\n\n\tEigen::MatrixXd img;\n\tcellogram::read_tif_image(filename, img);\n\tstd::cout<<img<<std::endl;\n\n\n\treturn 0;\n}\n", "meta": {"hexsha": "037c7bfcd60aa3327c65b95532a6258fc5a8f654", "size": 310, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "misc/tif_test.cpp", "max_stars_repo_name": "cellogram/cellogram", "max_stars_repo_head_hexsha": "d378e9b87e56b879b2fb352b08b0fed714481968", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-09-25T15:04:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-20T08:17:44.000Z", "max_issues_repo_path": "misc/tif_test.cpp", "max_issues_repo_name": "cellogram/cellogram", "max_issues_repo_head_hexsha": "d378e9b87e56b879b2fb352b08b0fed714481968", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "misc/tif_test.cpp", "max_forks_repo_name": "cellogram/cellogram", "max_forks_repo_head_hexsha": "d378e9b87e56b879b2fb352b08b0fed714481968", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-10-14T01:36:20.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-11T20:27:57.000Z", "avg_line_length": 17.2222222222, "max_line_length": 48, "alphanum_fraction": 0.6967741935, "num_tokens": 85, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.46678020993986835}}
{"text": "#include \"IntegratorTrap.hh\"\n\n#include <Eigen/Dense>\n#include <iterator>\n\n#include \"TypesFunctions.hh\"\n\nusing namespace Eigen;\nusing namespace std;\n\nIntegratorTrap::IntegratorTrap(int orders) : IntegratorBase(orders, true)\n{\n  init_sampler();\n}\n\nIntegratorTrap::IntegratorTrap(size_t bins, int orders, double* edges) : IntegratorBase(bins, orders, edges, true)\n{\n  init_sampler();\n}\n\nIntegratorTrap::IntegratorTrap(size_t bins, int* orders, double* edges) : IntegratorBase(bins, orders, edges, true)\n{\n  init_sampler();\n}\n\nvoid IntegratorTrap::sample(FunctionArgs& fargs) {\n  auto& rets=fargs.rets;\n  rets[1].x = m_edges.cast<double>();\n  rets[2].x = 0.0;\n  auto npoints=m_edges.size()-1;\n  rets[3].x = 0.5*(m_edges.tail(npoints)+m_edges.head(npoints));\n\n  auto& abscissa=rets[0].x;\n\n  auto nbins=m_edges.size()-1;\n  auto& binwidths=m_edges.tail(nbins) - m_edges.head(nbins);\n  ArrayXd samplewidths=binwidths/(m_orders.cast<double>()-1.0);\n\n  auto* edge_a=m_edges.data();\n  auto* edge_b{next(edge_a)};\n\n  size_t offset=0;\n  for (size_t i = 0; i < static_cast<size_t>(m_orders.size()); ++i) {\n    auto n=m_orders[i];\n    abscissa.segment(offset, n)=ArrayXd::LinSpaced(n, *edge_a, *edge_b);\n\n    auto swidth=samplewidths[i];\n    m_weights[offset]=swidth*0.5;\n    if(n>2) {\n      m_weights.segment(offset+1, n-2)=swidth;\n    }\n\n    offset+=n-1;\n    advance(edge_a, 1);\n    advance(edge_b, 1);\n  }\n  m_weights.tail(1)=samplewidths.tail(1)*0.5;\n  rets.untaint();\n  rets.freeze();\n}\n", "meta": {"hexsha": "b30234f1ac238c14cca8f04eea5d619d7e9803da", "size": 1477, "ext": "cc", "lang": "C++", "max_stars_repo_path": "transformations/integrator/IntegratorTrap.cc", "max_stars_repo_name": "gnafit/gna", "max_stars_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-10-14T01:06:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-02T16:33:06.000Z", "max_issues_repo_path": "transformations/integrator/IntegratorTrap.cc", "max_issues_repo_name": "gnafit/gna", "max_issues_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "transformations/integrator/IntegratorTrap.cc", "max_forks_repo_name": "gnafit/gna", "max_forks_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_forks_repo_licenses": ["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.2131147541, "max_line_length": 115, "alphanum_fraction": 0.6858496953, "num_tokens": 464, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.46678020993986835}}
{"text": "/*-----------------------------------------------------------------------------+\nCopyright (c) 2010-2010: Joachim Faulhaber\n+------------------------------------------------------------------------------+\n   Distributed under the Boost Software License, Version 1.0.\n      (See accompanying file LICENCE.txt or copy at\n           http://www.boost.org/LICENSE_1_0.txt)\n+-----------------------------------------------------------------------------*/\n#ifndef BOOST_ICL_DETAIL_EXCLUSIVE_LESS_THAN_HPP_JOFA_100929\n#define BOOST_ICL_DETAIL_EXCLUSIVE_LESS_THAN_HPP_JOFA_100929\n\n#include <boost/icl/concept/interval.hpp>\n\nnamespace boost{ namespace icl\n{\n\n/// Comparison functor on intervals implementing an overlap free less \ntemplate <class IntervalT>\nstruct exclusive_less_than \n{\n    /** Operator <tt>operator()</tt> implements a strict weak ordering on intervals. */\n    bool operator()(const IntervalT& left, const IntervalT& right)const\n    { \n        return icl::non_empty::exclusive_less(left, right); \n    }\n};\n\n}} // namespace boost icl\n\n#endif\n\n\n", "meta": {"hexsha": "3a4aa6505a40ec6fcf9f17add5cb654f04d53e0d", "size": 1051, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/boost/icl/detail/exclusive_less_than.hpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "boost/boost/icl/detail/exclusive_less_than.hpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "boost/boost/icl/detail/exclusive_less_than.hpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 32.84375, "max_line_length": 87, "alphanum_fraction": 0.5746907707, "num_tokens": 208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.46678020993986835}}
{"text": "/********************************************************************************\n * Author:   Gerrit Wellecke\n * Project:  Chimera states in populations of Kuramoto oscillators\n * Date:     March 2020\n *\n * Main function for the project on chimera states. As this project grew\n * gradually I only wrote one main for both systems (explicit and reduced). In\n * order to run the program properly only one of the two integration blocks\n * should be active at once, see below.\n * The integration functions were left here to simplify adaptations of code. All\n * functions that are \"set in stone\" are outsourced to other files.\n *\n * If no parallelisation is wanted the #pragma's in main can simply be commented\n * out.\n * Further the makefile might need to be adapted, depending on whether or not\n * parallelisation is wanted and what system architecture is used.\n *\n * OUTPUT is written to binary files. Each timestep of pop*osci oscillators is\n * written in sequence using 8-byte double precision floats.\n *******************************************************************************/\n#include \"functions.hpp\"        // functions used in integration() and main()\n#include \"kuramoto.hpp\"         // kuramoto model class\n#include \"ottantonsen.hpp\"      // Ott-Antonsen reduction\n\n#include <boost/numeric/odeint.hpp>\n#include <omp.h>\n\n#include <chrono>\n#include <cmath>\n#include <ctime>\n#include <fstream>\n#include <iostream>\n#include <string>\n#include <vector>\n\nusing namespace boost::numeric::odeint;\n\nusing state_type = std::vector<double>;\n\n/* *************************************************************************** */\n\n// integration of explicit Kuramoto system\nvoid integration(const double omega, const double alpha, const int pop, const int osci,\n        std::vector< std::vector<double> > &K, const uint maxIteration, std::string simName,\n        const std::vector<double> phase, const std::vector<double> variance, const double dt,\n        const Distribution dist, const long seedGiven\n        ) {\n    // state vector with initial phases\n    state_type x;\n    x.resize(pop * osci);\n\n    // set initial conditions and return seed of RNG\n    long seed {setInitCond(x, pop, osci, variance, phase, dist, seedGiven)};\n\n\n    // filename w/ given parameters\n    std::string fileName {\"data/\" + simName};\n\n    // fileIO\n    std::ofstream output(fileName, std::ios::binary);\n    std::ofstream ordParamOut(\"data/\" + simName + \".order\", std::ios::binary);\n\n    // initialize stepper\n    runge_kutta4<state_type> stepper;\n\n    // initialize system\n    Kuramoto kuramoto_func{omega, K, alpha, pop, osci};\n\n    // write log-file\n    kuramoto_func.writeLog(simName, maxIteration, dt, seed);\n\n    // write initial time step\n    output.write(reinterpret_cast<char*>(x.data()), x.size() * sizeof(double));\n\n    // write initial order parameter\n    std::vector<double> ordP {orderParam(x, pop, osci)};\n    ordParamOut.write(reinterpret_cast<char*>(ordP.data()), ordP.size() * sizeof(double));\n\n    // integration loop\n    uint iteration {0};\n\n    while (iteration < maxIteration) {\n        // as t isn't explicitly considered it is just set 0 here\n        stepper.do_step(kuramoto_func, x, 0., dt);\n\n        // renormalize phases in state vector\n        renorm(x);\n\n        // write time step to file\n        output.write(reinterpret_cast<char*>(x.data()), x.size() * sizeof(double));\n\n        // compute order parameter -- write to separate file\n        ordP = orderParam(x, pop, osci);\n        ordParamOut.write(reinterpret_cast<char*>(ordP.data()), ordP.size() * sizeof(double));\n\n        // iterate integration step\n        iteration++;\n    }\n\n    output.close();\n    ordParamOut.close();\n}\n\n// integration of reduced OA system (analogous to integration of Kuramoto sys.)\nvoid integrationOA(const double omega, const double alpha, const int pop, const int osci,\n        std::vector< std::vector<double> > &K, const uint maxIteration, std::string simName,\n        const double dt, /* const std::string Kname, */ const long seed\n        ) {\n    // state vector with init. cond.\n    state_type x;\n    x.resize(3);\n\n    // set initial conditions and get seed\n    // uncomment line below if wanting to reproduce initial state of Kuramoto sys.\n\n    // long seed {setInitCondOAfromKuramoto(x, pop, osci, Kname)};\n\n    // if using above line, comment the line below\n    setInitCondOA(x, seed);\n\n    // filename w/ given parameters\n    std::string fileName {\"data/\" + simName + \".order\"};\n\n    // fileIO\n    std::ofstream output(fileName, std::ios::binary);\n\n    // initialize stepper\n    runge_kutta4<state_type> stepper;\n\n    // initialize system\n    OttAntonsen OA_func{omega, K, alpha, pop, osci};\n\n    // write log-file\n    OA_func.writeLog(simName, maxIteration, dt, seed);\n\n    // write initial time step\n    output.write(reinterpret_cast<char*>(x.data()), x.size() * sizeof(double));\n\n    // integration loop\n    uint iteration {0};\n\n    while (iteration < maxIteration) {\n        // as t isn't explicitly considered it is just set 0 here\n        stepper.do_step(OA_func, x, 0., dt);\n\n        // renormalize mean phase difference\n        x[2] = fmod(x[2], 2*M_PI);\n        if (x[2] < 0)\n            x[2] += 2*M_PI;\n\n        // write time step\n        output.write(reinterpret_cast<char*>(x.data()), x.size() * sizeof(double));\n\n        // iterate integration step\n        iteration++;\n    }\n\n    output.close();\n}\n\n/* *************************************************************************** */\n\nint main(void) {\n    // system parameters as needed by Kuramoto and OttAntonsen\n    double omega {0.};\n    double beta {.01}; // for beta -> 0, P(Chimera) -> 1;\n    double alpha {.5 * M_PI - beta};\n    int pop {2};\n    int osci {128};\n\n    // parameters for initial conditions\n    std::vector<double> phase{0., 0.}; // (0, 0) -- in phase\n    std::vector<double> variance{.2, M_PI};\n    Distribution distribution {Distribution::NORMAL}; // only for explicit case\n\n    // parameters for integration\n    uint maxIteration {500000};\n    double dt{.1};\n\n    // vectors to iterate over\n    std::vector<double> Avec {.05, .15, .20, .40};\n    std::vector<long> seedVec {4578, 130547, 1337, 4578};\n\n    std::vector<std::string> Kname {\"data/seed_4578_A_0.050000\",\n        \"data/seed_130547_A_0.150000\", \"data/seed_1337_A_0.200000\",\n        \"data/seed_4578_A_0.400000\"};\n\n    // Numerical solution of explicit Kuramoto system\n    /*\n#pragma omp parallel for\n    for (int par = 0; par < static_cast<int>(Avec.size()); par++) {\n        // set seed\n        long seedGiven {seedVec[par]};\n\n        // coupling matrix\n        double A {Avec[par]};\n        double mu {.5 + A/2.};\n        double nu {.5 - A/2.};\n\n        std::vector< std::vector<double> > K {{mu, nu}, {nu, mu}};\n\n        // name for given integration\n        // std::string simName {\"seed_\" + std::to_string(seedGiven) + \"_A_\" + std::to_string(A)};\n        std::string simName{\"OttAntonsen_1\"};\n\n        // just benchmarking fun\n        auto start {std::chrono::high_resolution_clock::now()};\n\n        // integration of Kuramoto system w/ above setup\n        integration(omega, alpha, pop, osci, K, maxIteration, simName,\n                    phase, variance, dt, distribution, seedGiven);\n\n        // continue benchmarking fun\n        auto stop {std::chrono::high_resolution_clock::now()};\n\n        auto benchmark {std::chrono::duration_cast<std::chrono::microseconds>(stop - start)};\n\n        std::cout.precision(6);\n        // std::cout << \"Thread \" << omp_get_thread_num() << \" has finished calculation \"\n                  // << par + 1 << '\\n';\n        std::cout << \"Execution time: \" << std::fixed << benchmark.count() * 1e-6 << \"s\\n\";\n    }\n    */\n\n    // Numerical solution of Ott-Antonsen reduction\n    // set seed\n    long seedGiven {std::time(nullptr)};\n\n#pragma omp parallel for\n    //for (int par = 0; par < static_cast<int>(Avec.size()); par++) {\n    for (int par = 0; par <= 50 ; par++) {\n        //seedGiven = seedVec[par];\n\n        // coupling matrix\n        //double A {Avec[par]};\n        double A {.01 * par};\n        double mu {.5 + A/2.};\n        double nu {.5 - A/2.};\n\n        std::vector< std::vector<double> > K {{mu, nu}, {nu, mu}};\n\n        // name for given integration\n        std::string simName{\"OttAntonsen_A\" + std::to_string(A)};\n\n        // just benchmarking fun\n        auto start {std::chrono::high_resolution_clock::now()};\n\n        integrationOA(omega, alpha, pop, osci, K, maxIteration, simName,\n                        dt, /* Kname[par], */ seedGiven);\n\n        // continue benchmarking fun\n        auto stop {std::chrono::high_resolution_clock::now()};\n\n        auto benchmark {std::chrono::duration_cast<std::chrono::microseconds>(stop - start)};\n\n        std::cout.precision(6);\n        std::cout << \"Execution time: \" << std::fixed << benchmark.count() * 1e-6 << \"s\\n\";\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "037118eb6fd99dc002e9f478ed545e45f0d2d83f", "size": 8881, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "wavecorner/ChimeraStates", "max_stars_repo_head_hexsha": "8eef44ad36c591f7c71dac45a55ad06288a0b3e7", "max_stars_repo_licenses": ["MIT"], "max_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": "wavecorner/ChimeraStates", "max_issues_repo_head_hexsha": "8eef44ad36c591f7c71dac45a55ad06288a0b3e7", "max_issues_repo_licenses": ["MIT"], "max_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": "wavecorner/ChimeraStates", "max_forks_repo_head_hexsha": "8eef44ad36c591f7c71dac45a55ad06288a0b3e7", "max_forks_repo_licenses": ["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.8969465649, "max_line_length": 97, "alphanum_fraction": 0.6087152348, "num_tokens": 2204, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.46678020993986835}}
{"text": "#include <sys/stat.h>\n#include <sys/types.h>\n#include <unistd.h>\n#include <random>\n#include <Eigen/Cholesky>\n#include <fstream>\n#include <iomanip>\n#include <srrg_system_utils/parse_command_line.h>\n#include <srrg_boss/deserializer.h>\n#include <srrg_config/configurable_manager.h>\n\n#include \"srrg_solver/solver_core/instances.h\"\n#include \"srrg_solver/solver_core/factor_graph.h\"\n#include \"srrg_solver/variables_and_factors/types_2d/instances.h\"\n#include \"srrg_solver/variables_and_factors/types_2d/variable_se2_ad.h\"\n#include \"srrg_solver/variables_and_factors/types_2d/variable_point2_ad.h\"\n#include \"srrg_solver/variables_and_factors/types_2d/se2_pose_pose_geodesic_error_factor.h\"\n#include \"srrg_solver/variables_and_factors/types_2d/se2_pose_point_error_factor.h\"\n\n#include \"srrg_solver/variables_and_factors/types_3d/instances.h\"\n#include \"srrg_solver/variables_and_factors/types_3d/variable_se3_ad.h\"\n#include \"srrg_solver/variables_and_factors/types_3d/variable_point3_ad.h\"\n#include \"srrg_solver/variables_and_factors/types_3d/se3_pose_pose_geodesic_error_factor.h\"\n#include \"srrg_solver/variables_and_factors/types_3d/se3_pose_point_offset_error_factor.h\"\n\n#include \"srrg_solver/variables_and_factors/types_projective/instances.h\"\n#include \"srrg_solver/variables_and_factors/types_projective/se3_pose_point_omni_ba_error_factor.h\"\n#include \"srrg_solver/variables_and_factors/types_projective/sim3_pose_pose_error_factor_ad.h\"\n\n#include \"srrg_solver/utils/solver_evaluator.h\"\n#include \"srrg_solver/solver_core/solver.h\"\n\nusing namespace srrg2_core;\nusing namespace srrg2_solver;\nusing namespace std;\n\nextern char** environ;\nconst std::string exe_name = environ[0];\n#define LOG std::cerr << exe_name << \"|\"\n\n\nstatic const char* banner[] = {\n  \"evaluates a  factor graph,  by registering the poses in the input graph with the corresponding poses of the gt\",\n  0\n};\n\nstruct AssignerBase{\n  virtual bool assign(FactorBase* factor) = 0;\n};\nusing AssignerBasePtr=std::unique_ptr<AssignerBase>;\n\ntemplate <typename FactorType_>\nstruct Assigner_ : public AssignerBase {\n  using FactorType=FactorType_;\n  bool assign(FactorBase* factor_) {\n    FactorType* factor=dynamic_cast<FactorType*>(factor_);\n    if (! factor)\n      return false;\n    do_assign(*factor);\n    return true;\n  }\n  virtual void do_assign(FactorType& factor) = 0;\n};\n\nstruct AssignerSE3PosePoseGeodesicErrorFactor: public Assigner_<SE3PosePoseGeodesicErrorFactor> {\n  void do_assign(SE3PosePoseGeodesicErrorFactor& factor) override {\n    VariableSE3Base* from=factor.variables().at<0>();\n    VariableSE3Base* to=factor.variables().at<1>();\n    factor.setMeasurement(from->estimate().inverse()*to->estimate());\n  }\n};\n\nstruct AssignerSE2PosePoseGeodesicErrorFactor: public Assigner_<SE2PosePoseGeodesicErrorFactor> {\n  void do_assign(SE2PosePoseGeodesicErrorFactor& factor) override {\n    VariableSE2Base* from=factor.variables().at<0>();\n    VariableSE2Base* to=factor.variables().at<1>();\n    factor.setMeasurement(from->estimate().inverse()*to->estimate());\n  }\n};\n\nstruct AssignerSE3PosePointOffsetErrorFactor: public Assigner_<SE3PosePointOffsetErrorFactor> {\n  void do_assign(SE3PosePointOffsetErrorFactor& factor) override {\n    VariableSE3Base* pose=factor.variables().at<0>();\n    VariablePoint3*  point=factor.variables().at<1>();\n    VariableSE3Base* offset=factor.variables().at<2>();\n    Vector3f p_local=offset->estimate().inverse()*pose->estimate().inverse()*point->estimate();\n    factor.setMeasurement(p_local);\n  }\n};\n\nstruct AssignerSE3PosePointOmniBAErrorFactor: public Assigner_<SE3PosePointOmniBAErrorFactor> {\n  void do_assign(SE3PosePointOmniBAErrorFactor& factor) override {\n    VariableSE3Base* pose=factor.variables().at<0>();\n    VariablePoint3*  point=factor.variables().at<1>();\n    VariableSE3Base* offset=factor.variables().at<2>();\n    Vector3f p_local=offset->estimate().inverse()*pose->estimate().inverse()*point->estimate();\n    p_local.normalize();\n    factor.setMeasurement(p_local);\n  }\n};\n\n\nstruct AssignerSim3PosePoseErrorFactorAD: public Assigner_<Sim3PosePoseErrorFactorAD> {\n  void do_assign(Sim3PosePoseErrorFactorAD& factor) override {\n    VariableSim3Base* from=factor.variables().at<0>();\n    VariableSim3Base* to=factor.variables().at<1>();\n    factor.setMeasurement(from->estimate().inverse()*to->estimate());\n  }\n};\n\nstd::list<AssignerBasePtr> assigners;\n\nvoid constructAssigners() {\n  assigners.push_back(AssignerBasePtr(new(AssignerSE3PosePoseGeodesicErrorFactor)));\n  assigners.push_back(AssignerBasePtr(new(AssignerSE2PosePoseGeodesicErrorFactor)));\n  assigners.push_back(AssignerBasePtr(new(AssignerSE3PosePointOffsetErrorFactor)));\n  assigners.push_back(AssignerBasePtr(new(AssignerSE3PosePointOmniBAErrorFactor)));\n  assigners.push_back(AssignerBasePtr(new(AssignerSim3PosePoseErrorFactorAD)));\n}\n\nbool assign(FactorBase* factor) {\n  for (auto& a: assigners) {\n    if (a->assign(factor))\n      return true;\n  }\n  cerr << \"error in setting factor of type [ \" << factor->className() << \"]\" << endl;\n  return false;\n}\n\n// ia register types\nvoid initTypes() {\n  variables_and_factors_2d_registerTypes();\n  variables_and_factors_3d_registerTypes();\n  variables_and_factors_projective_registerTypes();\n  solver_registerTypes();\n}\n\n  \n// ia THE PROGRAM\nint main(int argc, char** argv) {\n  initTypes();\n  constructAssigners();\n  using namespace std;\n  ParseCommandLine cmd_line(argv, banner);\n  ArgumentString input_file          (&cmd_line, \"i\",    \"input-file\",             \"file where to read the input \", \"\");\n  ArgumentString output_file          (&cmd_line, \"o\",    \"output-file\",             \"file where to write the output \", \"\");\n  ArgumentString config_file          (&cmd_line, \"c\",    \"config-file\",           \"solver config file\", \"solver.config\");\n  ArgumentString solver_name          (&cmd_line, \"sn\",    \"solver-name\",           \"solver name in the config\", \"solver\");\n  cmd_line.parse();\n\n  FactorGraphPtr graph;\n\n  std::cerr << \"loading file: [\" << input_file.value() << \"]... \";\n  graph = FactorGraph::read(input_file.value());\n  std::cerr << \"done, factors:\" << graph->factors().size() << \" vars: \" << graph->variables().size() << std::endl;\n\n  VariableBase* v0=graph->variable(0);\n  if (! v0) {\n    cerr << \"dunno which variable to fix\" << endl;\n  } else {\n    v0->setStatus(VariableBase::Fixed);\n  }\n      \n  ConfigurableManager manager;\n  manager.read(config_file.value());\n\n  // ia check if solver with this specific name exists\n  LOG << \"loading solver [ \" << config_file.value() << \" ]\\n\";\n  SolverPtr solver = manager.getByName<Solver>(solver_name.value());\n  if (!solver) {\n    throw std::runtime_error(exe_name + \"|ERROR, cannot find solver with name [ \" +\n                             solver_name.value() + \" ] in configuration file [ \" +\n                             config_file.value() + \" ]\");\n  }\n  solver->param_actions.pushBack(SolverVerboseActionPtr(new SolverVerboseAction));\n  solver->setGraph(graph);\n  solver->compute();\n\n  cerr << \"setting measurements... \";\n  for (auto f_it: graph->factors()) {\n    if (! assign(f_it.second)) {\n      throw std::runtime_error(\"fatal\");\n    }\n  }\n  cerr << \"done\" << endl;\n\n  if (output_file.isSet()) {\n    cerr << \"saving optimized graph\" << endl;\n    graph->write(output_file.value());\n  }\n  return 0;\n}\n", "meta": {"hexsha": "05f8921d9fc786845b65f775f9d6f78f97cd529a", "size": 7297, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "catkin_ws/src/srrg2_solver/srrg2_solver/app/graph_manipulators/solver_app_graph_gt_generator.cpp", "max_stars_repo_name": "laaners/progetto-labiagi_pick_e_delivery", "max_stars_repo_head_hexsha": "3453bfbc1dd7562c78ba06c0f79b069b0a952c0e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "catkin_ws/src/srrg2_solver/srrg2_solver/app/graph_manipulators/solver_app_graph_gt_generator.cpp", "max_issues_repo_name": "laaners/progetto-labiagi_pick_e_delivery", "max_issues_repo_head_hexsha": "3453bfbc1dd7562c78ba06c0f79b069b0a952c0e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "catkin_ws/src/srrg2_solver/srrg2_solver/app/graph_manipulators/solver_app_graph_gt_generator.cpp", "max_forks_repo_name": "laaners/progetto-labiagi_pick_e_delivery", "max_forks_repo_head_hexsha": "3453bfbc1dd7562c78ba06c0f79b069b0a952c0e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.8082901554, "max_line_length": 124, "alphanum_fraction": 0.7324928053, "num_tokens": 1885, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911056, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.46678020335945}}
{"text": "#pragma once\r\n\r\n#include <skynet/config.hpp>\r\n\r\n#include <Eigen/Core>\r\n\r\nnamespace skynet{namespace statistics{\r\n\tnamespace detail{\r\n\r\n\t\tpair<Eigen::MatrixXd, Eigen::MatrixXd>\tget_missing_data_covariance_sub_matrixes(\r\n\t\t\tconst Eigen::MatrixXd &mat, const std::vector<size_t> &missing_indexes)\r\n\t\t{\r\n\t\t\tASSERT(mat.cols() == mat.rows(), \"The rols is not equal to cols!.\");\r\n\r\n\t\t\tstd::vector<size_t> observed_indexes;\r\n\t\t\tfor (int i = 0, j = 0; (i <mat.rows()) && (j < missing_indexes.size()); ++i){\r\n\t\t\t\tif (i != missing_indexes[j]){\r\n\t\t\t\t\tobserved_indexes.push_back(i);\r\n\t\t\t\t}\r\n\t\t\t\telse{\r\n\t\t\t\t\t++j;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tEigen::MatrixXd Sigma_oo(observed_indexes.size(), observed_indexes.size());\r\n\t\t\tfor (int i = 0; i < observed_indexes.size(); ++i){\r\n\t\t\t\tfor (int j = 0; j < observed_indexes.size(); ++j){\r\n\t\t\t\t\tSigma_oo(i, j) = mat(observed_indexes[i], observed_indexes[j]);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tEigen::MatrixXd Sigma_mo(missing_indexes.size(), observed_indexes.size());\r\n\t\t\tfor (int i = 0; i < missing_indexes.size(); ++i){\r\n\t\t\t\tfor (int j = 0; j < observed_indexes.size(); ++j){\r\n\t\t\t\t\tSigma_mo(i,j) = mat(missing_indexes[i], observed_indexes[j]);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\treturn  make_pair(Sigma_oo, Sigma_mo);\r\n\t\t}\r\n\r\n\t\tpair<Eigen::VectorXd, Eigen::VectorXd> get_missing_data_means(\r\n\t\t\tconst Eigen::MatrixXd &mat, const std::vector<size_t> &missing_indexes)\r\n\t\t{\r\n\t\t\tstd::vector<size_t> observed_indexes;\r\n\t\t\tfor (int i = 0, j = 0; (i <mat.rows()) && (j < missing_indexes.size()); ++i){\r\n\t\t\t\tif (i != missing_indexes[j]){\r\n\t\t\t\t\tobserved_indexes.push_back(i);\r\n\t\t\t\t}\r\n\t\t\t\telse{\r\n\t\t\t\t\t++j;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tEigen::VectorXd mean_o(observed_indexes.size());\r\n\t\t\tfor (int i = 0; i < observed_indexes.size(); ++i){\r\n\t\t\t\tmean_o[i] = mat.row(observed_indexes[i]).mean();\r\n\t\t\t}\r\n\r\n\t\t\tEigen::VectorXd mean_m(missing_indexes.size());\r\n\t\t\tfor (int i = 0; i < missing_indexes.size(); ++i){\r\n\t\t\t\tmean_m[i] = mat.row(missing_indexes[i]).mean();\r\n\t\t\t}\r\n\r\n\t\t\treturn make_pair(mean_o, mean_m);\r\n\t\t}\r\n\r\n\t\ttemplate <typename V>\r\n\t\tEigen::VectorXd get_observed_values(const V &vec, const std::vector<size_t> &missing_indexes){\r\n\t\t\tstd::vector<size_t> observed_indexes;\r\n\t\t\tfor (int i = 0, j = 0; (i <vec.size()) && (j < missing_indexes.size()); ++i){\r\n\t\t\t\tif (i != missing_indexes[j]){\r\n\t\t\t\t\tobserved_indexes.push_back(i);\r\n\t\t\t\t}\r\n\t\t\t\telse{\r\n\t\t\t\t\t++j;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tEigen::VectorXd observed_values(observed_indexes.size());\r\n\t\t\tfor (int i = 0; i < observed_indexes.size(); ++i){\r\n\t\t\t\tobserved_values[i] = vec[observed_indexes[i]];\r\n\t\t\t}\r\n\r\n\t\t\treturn observed_values;\r\n\t\t}\r\n\r\n\t}\r\n\r\n\tclass missing_data_EM{\r\n\tpublic:\r\n\t\tmissing_data_EM(const  Eigen::MatrixXd &mat_data, const Eigen::Matrix<byte, -1, -1, 0,-1,-1> &mat_observed)\r\n\t\t\t: _mat_data(mat_data), _mat_observed(mat_observed)\r\n\t\t{\r\n\t\t\tASSERT(mat_data.cols() == mat_observed.cols() && mat_data.rows() == mat_observed.rows(),\r\n\t\t\t\t\"The size not match!\");\r\n\t\t\t_missing_indexes_vec.resize(mat_data.cols());\r\n\r\n\t\t\tfor (int col = 0; col < mat_observed.cols(); ++col){\r\n\t\t\t\tfor (int row = 0; row < mat_observed.rows(); ++row){\r\n\t\t\t\t\tif (!mat_observed(row, col)){\r\n\t\t\t\t\t\t_missing_indexes_vec[col].push_back(row);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tEigen::MatrixXd em(size_t  iter_num){\r\n\t\t\tfor (int iter = 0; iter < iter_num; ++iter){\r\n\t\t\t\trefresh_covariance_matrix();\r\n\t\t\t\tfor (size_t  sample_i = 0; sample_i < _mat_data.cols(); ++sample_i){\r\n\t\t\t\t\tauto missing_indexes = _missing_indexes_vec[sample_i];\r\n\r\n\t\t\t\t\tif (missing_indexes.empty()) continue;\r\n\r\n\t\t\t\t\tauto sub_matrixes = \r\n\t\t\t\t\t\tdetail::get_missing_data_covariance_sub_matrixes(_mat_covariance, missing_indexes);\r\n\t\t\t\t\tauto means = detail::get_missing_data_means(_mat_data, missing_indexes);\r\n\r\n\t\t\t\t\tauto y_o = detail::get_observed_values(_mat_data.col(sample_i), missing_indexes);\r\n\t\t\t\t\tauto y_m = means.second + \r\n\t\t\t\t\t\tsub_matrixes.second * sub_matrixes.first.inverse() * (y_o - means.first);\r\n\r\n\t\t\t\t\tfor (int i = 0; i < missing_indexes.size(); ++i){\r\n\t\t\t\t\t\t_mat_data.col(sample_i)[missing_indexes[i]] = y_m[i];\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\treturn _mat_data;\r\n\t\t}\r\n\r\n\tprotected:\r\n\r\n\t\tvoid refresh_covariance_matrix(){\r\n\t\t\t_mat_covariance = _mat_data * _mat_data.transpose();\r\n\t\t\t_mat_covariance /= _mat_covariance.cols();\r\n\t\t}\r\n\r\n\tprivate:\r\n\t\tEigen::MatrixXd\t\t\t\t\t\t\t\t_mat_data;\r\n\t\tEigen::Matrix<byte, -1, -1, 0, -1, -1>\t\t_mat_observed;\r\n\t\tEigen::MatrixXd\t\t\t\t\t\t\t\t_mat_covariance;\r\n\r\n\t\tstd::vector<std::vector<size_t>>\t_missing_indexes_vec;\r\n\t};\r\n\r\n}}\r\n", "meta": {"hexsha": "370c9a215c00ffabc3bec4378c2214b75f30ea81", "size": 4434, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "skynet/statistics/missing_data.hpp", "max_stars_repo_name": "zhangzhimin/skynet", "max_stars_repo_head_hexsha": "a311b86433821a071002dd279d57333baba1f973", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2015-08-02T03:10:26.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-16T01:07:55.000Z", "max_issues_repo_path": "skynet/statistics/missing_data.hpp", "max_issues_repo_name": "zhangzhimin/skynet", "max_issues_repo_head_hexsha": "a311b86433821a071002dd279d57333baba1f973", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "skynet/statistics/missing_data.hpp", "max_forks_repo_name": "zhangzhimin/skynet", "max_forks_repo_head_hexsha": "a311b86433821a071002dd279d57333baba1f973", "max_forks_repo_licenses": ["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.7583892617, "max_line_length": 110, "alphanum_fraction": 0.6238159675, "num_tokens": 1242, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911056, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.46678020335945}}
{"text": "/* ----------------------------------------------------------------------------\n * Copyright 2020, Jesus Tordesillas Torres, Aerospace Controls Laboratory\n * Massachusetts Institute of Technology\n * All Rights Reserved\n * Authors: Jesus Tordesillas, et al.\n * See LICENSE file for the license information\n * -------------------------------------------------------------------------- */\n\n#ifndef SOLVER_NLOPT_HPP\n#define SOLVER_NLOPT_HPP\n#include <Eigen/Dense>\n\n#include <iomanip>  //set precision\n#include <nlopt.hpp>\n#include \"mader_types.hpp\"\n#include \"utils.hpp\"\n#include \"timer.hpp\"\n#include <decomp_geometry/polyhedron.h>  //For Polyhedron  and Hyperplane definition\n#include \"separator.hpp\"\n#include \"octopus_search.hpp\"\n#include \"solver_params.hpp\"\n\ntypedef MADER_timers::Timer MyTimer;\n\nclass SolverNlopt\n{\npublic:\n  SolverNlopt(ms::par_solver &par);\n\n  ~SolverNlopt();\n\n  bool optimize();\n\n  // setters\n  void setMaxRuntimeKappaAndMu(double runtime, double kappa, double mu);\n  bool setInitStateFinalStateInitTFinalT(mt::state initial_state, mt::state final_state, double t_init,\n                                         double &t_final);\n  void setHulls(mt::ConvexHullsOfCurves_Std &hulls);\n\n  mt::trajectory traj_solution_;\n\n  // getters\n  void getPlanes(std::vector<Hyperplane3D> &planes);\n  int getNumOfLPsRun();\n  int getNumOfQCQPsRun();\n  void getSolution(mt::PieceWisePol &solution);\n  double getTimeNeeded();\n\n  int B_SPLINE = 1;  // B-Spline Basis\n  int MINVO = 2;     // Minimum volume basis\n  int BEZIER = 3;    // Bezier basis\n\n  bool checkGradientsUsingFiniteDiff();\n\n  double improvement_ = 0.0;\n\nprotected:\nprivate:\n  void saturateQ(std::vector<Eigen::Vector3d> &q);\n\n  bool isDegenerate(const std::vector<double> &x);\n\n  void transformPosBSpline2otherBasis(const Eigen::Matrix<double, 3, 4> &Qbs, Eigen::Matrix<double, 3, 4> &Qmv,\n                                      int interval);\n  void transformVelBSpline2otherBasis(const Eigen::Matrix<double, 3, 3> &Qbs, Eigen::Matrix<double, 3, 3> &Qmv,\n                                      int interval);\n\n  void generateRandomGuess();\n  void generateAStarGuess();\n  void generateStraightLineGuess();\n\n  void sampleFeasible(Eigen::Vector3d &qiP1, std::vector<Eigen::Vector3d> &q);\n\n  void printStd(const std::vector<Eigen::Vector3d> &v);\n  void printStd(const std::vector<double> &v);\n  void generateGuessNDFromQ(const std::vector<Eigen::Vector3d> &q, std::vector<Eigen::Vector3d> &n,\n                            std::vector<double> &d);\n\n  void fillPlanesFromNDQ(std::vector<Hyperplane3D> &planes_, const std::vector<Eigen::Vector3d> &n,\n                         const std::vector<double> &d, const std::vector<Eigen::Vector3d> &q);\n\n  void generateRandomD(std::vector<double> &d);\n  void generateRandomN(std::vector<Eigen::Vector3d> &n);\n  void generateRandomQ(std::vector<Eigen::Vector3d> &q);\n\n  nlopt::algorithm getSolver(std::string &solver);\n\n  bool isADecisionCP(int i);\n\n  template <class T>\n  bool isFeasible(const T x);\n\n  bool isFeasible(const std::vector<Eigen::Vector3d> &q, const std::vector<Eigen::Vector3d> &n,\n                  const std::vector<double> &d);\n\n  void printQVA(const std::vector<Eigen::Vector3d> &q);\n\n  void assignEigenToVector(double *grad, int index, const Eigen::Vector3d &tmp);\n\n  template <class T>\n  void x2qnd(T &x, std::vector<Eigen::Vector3d> &q, std::vector<Eigen::Vector3d> &n, std::vector<double> &d);\n\n  void qnd2x(const std::vector<Eigen::Vector3d> &q, const std::vector<Eigen::Vector3d> &n, const std::vector<double> &d,\n             std::vector<double> &x);\n\n  int gIndexQ(int i);  // Element jth of control point ith\n  int gIndexN(int i);  // Element jth of normal ith\n  int gIndexD(int i);\n\n  void printQND(std::vector<Eigen::Vector3d> &q, std::vector<Eigen::Vector3d> &n, std::vector<double> &d);\n\n  // r is the constraint index\n  // nn is the number of variables\n  // var_gindex is the index of the variable of the first element of the vector\n  void toGradDiffConstraintsDiffVariables(int var_gindex, const Eigen::Vector3d &tmp, double *grad, int r, int nn);\n\n  void toGradSameConstraintDiffVariables(int var_gindex, const Eigen::Vector3d &tmp, double *grad, int r, int nn);\n\n  void assignValueToGradConstraints(int var_gindex, const double &tmp, double *grad, int r, int nn);\n\n  // This function has to be static, see example\n  // https://github.com/HKUST-Aerial-Robotics/Fast-Planner/blob/master/fast_planner/bspline_opt/src/bspline_optimizer.cpp\n  // and here: https://github.com/stevengj/nlopt/issues/246\n  static double myObjFunc(unsigned nn, const double *x, double *grad, void *my_func_data);\n\n  // See example https://github.com/stevengj/nlopt/issues/168\n  static void myIneqConstraints(unsigned m, double *result, unsigned nn, const double *x, double *grad, void *f_data);\n\n  // double computeObjFunction(unsigned nn, double *grad, std::vector<Eigen::Vector3d> &q, std::vector<Eigen::Vector3d>\n  // &n,\n  //                           std::vector<double> &d);\n\n  double computeObjFunctionJerk(unsigned nn, double *grad, std::vector<Eigen::Vector3d> &q,\n                                std::vector<Eigen::Vector3d> &n, std::vector<double> &d);\n\n  void computeConstraints(unsigned m, double *constraints, unsigned nn, double *grad,\n                          const std::vector<Eigen::Vector3d> &q, const std::vector<Eigen::Vector3d> &n,\n                          const std::vector<double> &d);\n\n  void initializeNumOfConstraints();\n\n  void printInfeasibleConstraints(std::vector<Eigen::Vector3d> &q, std::vector<Eigen::Vector3d> &n,\n                                  std::vector<double> &d);\n\n  // template <class T>\n  // void printInfeasibleConstraints(const T x);\n\n  template <class T>\n  int getNumberOfInfeasibleConstraints(const T &constraints);\n\n  template <class T>\n  bool areTheseConstraintsFeasible(const T &constraints);\n\n  template <class T>\n  void printInfeasibleConstraints(const T &constraints);\n\n  std::string getResultCode(int &result);\n\n  void findCentroidHull(const mt::Polyhedron_Std &hull, Eigen::Vector3d &centroid);\n\n  int lastDecCP();\n\n  // bool intersects();\n\n  // void computeVeli(Eigen::Vector3d &vel, std::vector<Eigen::Vector3d> &q);\n\n  // void computeAcceli(Eigen::Vector3d &accel, std::vector<Eigen::Vector3d> &q);\n\n  // bool satisfiesVmaxAmax(std::vector<Eigen::Vector3d> &q);\n\n  void printIndexesConstraints();\n  void printIndexesVariables();\n\n  mt::PieceWisePol solution_;\n\n  int basis_ = B_SPLINE;\n\n  int deg_pol_ = 3;\n  int num_pol_ = 5;\n  int p_ = 5;\n  int i_min_;\n  int i_max_;\n  int j_min_;\n  int j_max_;\n  int k_min_;\n  int k_max_;\n  int M_;\n  int N_;\n\n  int num_of_variables_;\n  int num_of_normals_;\n  int num_of_constraints_;\n  int num_of_obst_;\n  int num_of_segments_;\n\n  nlopt::algorithm solver_;\n\n  bool got_a_feasible_solution_ = false;\n  double time_first_feasible_solution_ = 0.0;\n\n  double best_cost_so_far_ = std::numeric_limits<double>::max();\n\n  std::vector<double> best_feasible_sol_so_far_;\n\n  std::vector<Hyperplane3D> planes_;\n\n  double epsilon_tol_constraints_;\n  double xtol_rel_;\n  double ftol_rel_;\n\n  std::vector<double> x_;  // Here the initial guess, and the solution, are stored\n\n  double lowest_cost_so_far_;\n  double dc_;\n  Eigen::RowVectorXd knots_;\n  double t_init_;\n  double t_final_;\n  double deltaT_;\n  Eigen::Vector3d v_max_;\n  Eigen::Vector3d a_max_;\n\n  double weight_ = 10000;\n  double weight_modified_ = 10000;\n\n  // bool force_final_state_ = true;\n\n  mt::state initial_state_;\n  mt::state final_state_;\n\n  // double constraints_[10000];  // this number should be very big!! (hack, TODO)\n\n  Eigen::Vector3d q0_, q1_, q2_, qNm2_, qNm1_, qN_;\n\n  mt::ConvexHullsOfCurves_Std hulls_;\n\n  MyTimer opt_timer_;\n\n  double max_runtime_ = 2;  //[seconds]\n\n  // Eigen::Vector3d initial_point_;\n  // Eigen::Vector3d final_point_;\n  // nlopt::opt *opt_ = nullptr;\n  // nlopt::opt *local_opt_ = nullptr;\n\n  // nlopt::opt opt_;\n  // nlopt::opt local_opt_;\n\n  // Guesses\n  std::vector<Eigen::Vector3d> n_guess_;  // Guesses for the normals\n  std::vector<Eigen::Vector3d> q_guess_;  // Guesses for the normals\n  std::vector<double> d_guess_;           // Guesses for the normals\n\n  Eigen::MatrixXd R_;  // This matrix is [r0, r1, r2, r3, r0, r1, r2, r3] (for two segments)\n\n  // separator::Separator *separator_solver;\n\n  int index_const_obs_ = 0;\n  int index_const_vel_ = 0;\n  int index_const_accel_ = 0;\n  int index_const_normals_ = 0;\n\n  double kappa_ = 0.2;  // kappa_*max_runtime_ is spent on the initial guess\n  double mu_ = 0.5;     // mu_*max_runtime_ is spent on the optimization\n\n  double x_min_ = -std::numeric_limits<double>::max();\n  double x_max_ = std::numeric_limits<double>::max();\n\n  double y_min_ = -std::numeric_limits<double>::max();\n  double y_max_ = std::numeric_limits<double>::max();\n\n  double z_min_ = -std::numeric_limits<double>::max();\n  double z_max_ = std::numeric_limits<double>::max();\n\n  int num_of_LPs_run_ = 0;\n  int num_of_QCQPs_run_ = 0;\n\n  int a_star_samp_x_ = 7;\n  int a_star_samp_y_ = 7;\n  int a_star_samp_z_ = 7;\n\n  double time_needed_;\n  double dist_to_use_straight_guess_ = std::numeric_limits<double>::max();\n\n  // transformation between the B-spline control points and other basis\n  std::vector<Eigen::Matrix<double, 4, 4>> M_pos_bs2basis_;\n  std::vector<Eigen::Matrix<double, 3, 3>> M_vel_bs2basis_;\n  std::vector<Eigen::Matrix<double, 4, 4>> A_pos_bs_;\n\n  double a_star_bias_ = 1.0;\n  double a_star_fraction_voxel_size_ = 0.5;\n  bool allow_infeasible_guess_ = false;\n\n  separator::Separator *separator_solver_;\n  OctopusSearch *octopusSolver_;\n\n  double Ra_ = 1e10;\n};\n#endif", "meta": {"hexsha": "2d6ac8bc8843b3bf7710b37542262efce09bd698", "size": 9606, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "mader/include/solver_nlopt.hpp", "max_stars_repo_name": "shubham-shahh/mader", "max_stars_repo_head_hexsha": "7cbe46438b348a1ad9545146734083d0b6436bd4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 222.0, "max_stars_repo_stars_event_min_datetime": "2020-12-23T01:45:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T22:46:02.000Z", "max_issues_repo_path": "mader/include/solver_nlopt.hpp", "max_issues_repo_name": "shubham-shahh/mader", "max_issues_repo_head_hexsha": "7cbe46438b348a1ad9545146734083d0b6436bd4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2021-02-18T15:19:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-01T14:19:54.000Z", "max_forks_repo_path": "mader/include/solver_nlopt.hpp", "max_forks_repo_name": "shubham-shahh/mader", "max_forks_repo_head_hexsha": "7cbe46438b348a1ad9545146734083d0b6436bd4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 48.0, "max_forks_repo_forks_event_min_datetime": "2020-12-21T01:00:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T22:46:04.000Z", "avg_line_length": 32.2348993289, "max_line_length": 121, "alphanum_fraction": 0.6866541745, "num_tokens": 2740, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.6113819591324416, "lm_q1q2_score": 0.46678019912763313}}
{"text": "/* ScaFES\n * Copyright (c) 2011-2015, ZIH, TU Dresden, Federal Republic of Germany.\n * For details, see the files COPYING and LICENSE in the base directory\n * of the package.\n */\n\n/**\n *  @file ScaFES_Ntuple.hpp\n *  @brief Contains the class template Ntuple.\n */\n#ifndef SCAFES_NTUPLE_HPP_\n#define SCAFES_NTUPLE_HPP_\n\n#include \"ScaFES_Config.hpp\"\n\n//#include <cstdint>\n#include <iomanip>\n#include <iostream>\n#include <ios>\n#include <vector>\n#include <cmath>\n#include <type_traits>\n#include <stdexcept>\n\n#ifdef SCAFES_HAVE_BOOST\n#include <boost/version.hpp>\n#endif\n\n#ifdef SCAFES_HAVE_BOOST_SERIALIZATION\nnamespace boost\n{\nnamespace serialization\n{\n    class access;\n}\n}\n#include <boost/serialization/version.hpp>\n#if BOOST_VERSION < 105900\n   #include <boost/serialization/pfto.hpp>\n#endif\n#endif\n\nnamespace ScaFES\n{\n\n/*******************************************************************************\n ******************************************************************************/\n/** \\class Ntuple\n * @brief The class template \\c Ntuple represents a\n * \\c NN dimensional vector of a given type \\c TT.\n *\n * All important unary and binary operators are implemented resp. overloaded\n * and behave as expected. Especially, many operators work componentwise.\n *\n * Usually, the memory for the vector elements must be allocated dynamically,\n * because the number of elements is known at run time. This is related\n * with additional effort for creating and deleting the elements on the\n * heap.\n * Due to the nontype template parameter \\c NN the number of vector elements\n * is known at compile time. Thus, it is possible to allocate the memory\n * for the vector elements statically.\n *\n * Advantages:\n * - Automatic compiler SIMD vectorizations can be better applied.\n * - Using the class template \\c Ntuple with three elements\n * instead of a class containing explicitly three elements does not affect\n * the performance, but will give more flexibility in solving other than\n * three-dimensional problems.\n *\n * \\code\n * // Constructors.\n * ScaFES::Ntuple<double,3> a(1.1, 2.2, 3.3);  // a = (1.1, 2.2, 3.3)\n * ScaFES::Ntuple<double,3> b(6.0, 6.0, 4.0);  // b = (3.0, 3.0, 2.0)\n * ScaFES::Ntuple<double,3> c = a + 2 * b;     // c = (7.1, 8.2, 7.3)\n *\n * // Arithmetic operators.\n * a += 2.0;                                   // a = (3.1, 4.2, 5.3)\n * c = b * b;                                  // c = (9.0, 9.0, 4.0)\n *\n * // Relational operators\n * a < b;                                      // false: 3.3 > 2.0\n * b *= 2.0;                                   // b = (6.0, 6.0, 4.0)\n * b > a;                                      // true\n * \\endcode\n */\ntemplate <typename TT, std::size_t NN = 3> class Ntuple\n{\n\npublic:\n    /*----------------------------------------------------------------------\n    | TYPE DEFINITIONS.\n    ----------------------------------------------------------------------*/\n    /** Re-export typename TT STL-like. */\n    typedef TT value_type;\n\n    /*----------------------------------------------------------------------\n    | FRIEND CLASSES.\n    ----------------------------------------------------------------------*/\n#ifdef SCAFES_HAVE_BOOST_SERIALIZATION\n    friend class boost::serialization::access;\n#endif\n\n    /*----------------------------------------------------------------------\n    | LIFE CYCLE METHODS.\n    ----------------------------------------------------------------------*/\n    /** Creates the default constructor.\n     *  All elements are initialized by zero.*/\n    Ntuple<TT, NN>();\n\n    /** Creates a special constructor for twodimensional vectors:\n     *  The elements are initialized by given values. */\n    Ntuple<TT, NN>(const TT& a, const TT& b);\n\n    /** Creates a special constructor for threedimensional vectors:\n     *  The elements are initialized by given values. */\n    Ntuple<TT, NN>(const TT& a, const TT& b, const TT& c);\n\n    /** Creates own constructor:\n     *  All elements are initalized by the same value. */\n    Ntuple<TT, NN>(const TT& scal);\n\n    /** Creates own constructor: Conversion method.\n     *  All elements are set by a given STL vector. */\n    Ntuple<TT, NN>(const std::vector<TT>& vec);\n\n    /** Creates copy constructor.\n     * \\remarks Use copy-and-swap idiom.\n     */\n    Ntuple<TT, NN>(const Ntuple<TT, NN>& rhs);\n\n    /** Creates copy assignment operator.\n     * All elements of the rhs. vector will be assigned. */\n    Ntuple<TT, NN>& operator=(Ntuple<TT, NN> rhs);\n\n    /** Creates the destructor. */\n    ~Ntuple() {};\n\n    /*----------------------------------------------------------------------\n    | GETTER METHODS.\n    ----------------------------------------------------------------------*/\n    /** Returns the dimension (= number of elements) of the n-tuple. */\n    size_t dim() const;\n\n    /** Returns a reference to the element at idx \\c ii in the n-tuple.\n     * \\remarks With range check!\n     */\n    const TT& elem(const std::size_t& ii) const;\n\n    /** Returns the element at idx \\c ii in the n-tuple.\n     * \\remarks Without range check! */\n    const TT& operator[](const std::size_t& ii) const;\n\n    /*----------------------------------------------------------------------\n    | SETTER METHODS.\n    ----------------------------------------------------------------------*/\n    /** Returns a reference to the element at idx ii in the Ntuple.\n     * \\remarks With range check!\n     */\n    TT& elem(const std::size_t& ii);\n\n    /** Returns a reference to the element at idx \\c ii in the n-tuple.\n     * \\remarks Without range check! */\n    TT& operator[](const std::size_t& ii);\n\n    /*----------------------------------------------------------------------\n    | ARITHMETIC METHODS.\n    ----------------------------------------------------------------------*/\n    /** Creates an assignment operator.\n     * All elements will be assigned to a given scalar.*/\n    ScaFES::Ntuple<TT, NN>& operator=(const TT& sca);\n\n    /** Multiplies this n-tuple by a given scalar (elementwise). */\n    template <typename CT> ScaFES::Ntuple<TT, NN>& operator*=(const CT& sca);\n\n    /** Divides this n-tuple by a given scalar (elementwise). */\n    template <typename CT> ScaFES::Ntuple<TT, NN>& operator/=(const CT& sca);\n\n    /** Adds a given rhs n-tuple to this n-tuple. */\n    ScaFES::Ntuple<TT, NN>& operator+=(const ScaFES::Ntuple<TT, NN>& rhs);\n\n    /** Subtracts a given rhs n-tuple from this n-tuple. */\n    ScaFES::Ntuple<TT, NN>& operator-=(const ScaFES::Ntuple<TT, NN>& rhs);\n\n    /** Multiplies this n-tuple by a given rhs n-tuple. */\n    ScaFES::Ntuple<TT, NN>& operator*=(const ScaFES::Ntuple<TT, NN>& rhs);\n\n    /** Divides this n-tuple by a given rhs n-tuple. */\n    ScaFES::Ntuple<TT, NN>& operator/=(const ScaFES::Ntuple<TT, NN>& rhs);\n\n    /*----------------------------------------------------------------------\n    | COMPARISON METHODS.\n    ----------------------------------------------------------------------*/\n    /** Compares elementwise if this n-tuple is smaller than a a given rhs\n     *  n-tuple. */\n    bool operator<(const ScaFES::Ntuple<TT, NN>& rhs) const;\n\n    /** Compares elementwise if this n-tuple is greater or equal\n     *  than a a given rhs n-tuple. */\n    bool operator>=(const ScaFES::Ntuple<TT, NN>& rhs) const;\n\n    /** Compares elementwise if this n-tuple is smaller or equal\n     *  than a a given rhs n-tuple. */\n    bool operator<=(const ScaFES::Ntuple<TT, NN>& rhs) const;\n\n    /** Compares elementwise if this n-tuple is greater than a a given rhs\n     *  n-tuple. */\n    bool operator>(const ScaFES::Ntuple<TT, NN>& rhs) const;\n\n    /** Compares elementwise if this n-tuple is equal to a given rhs\n     *  n-tuple. */\n    bool operator==(const ScaFES::Ntuple<TT, NN>& rhs) const;\n\n    /** Compares elementwise if this n-tuple is unequal to a given rhs\n     *  n-tuple. */\n    bool operator!=(const ScaFES::Ntuple<TT, NN>& rhs) const;\n\n    /*----------------------------------------------------------------------\n    | WORK METHODS.\n    ----------------------------------------------------------------------*/\n    /** Returns the index of the element with maximal value. */\n    std::size_t idxMaxElem() const;\n\n    /** Computes the dimension of the n-tuple,\n     * i.e., all elements will be multiplied. */\n    TT size() const;\n\n    /** Computes the 1-norm. */\n    double norm1() const;\n\n#ifdef SCAFES_HAVE_BOOST_SERIALIZATION\n    /** Serializes this class. */\n    template <class Archive>\n    void serialize(Archive& ar, unsigned int const version);\n#endif\n\n    /*----------------------------------------------------------------------\n    | FREE METHODS WHICH ARE FRIENDS OF THIS CLASS.\n    ----------------------------------------------------------------------*/\n    /** Overloads the output operator \\c operator<<.\n     * An n-tuple is printed this way: '(a_0, a_1,..., a_{n-1})' */\n    template <typename ST, std::size_t MM>\n    friend std::ostream& operator<<(std::ostream& output,\n                                    const ScaFES::Ntuple<ST, MM>& t);\n\n    /** Method to swap members of two ScaFES::Ntuples. */\n    template <typename ST, std::size_t MM>\n    friend void swap(ScaFES::Ntuple<ST, MM>& first,\n                     ScaFES::Ntuple<ST, MM>& second);\n\n    /*----------------------------------------------------------------------\n    | CONSTANTS.\n    ----------------------------------------------------------------------*/\n    /** Dimension of n-tuple. */\n    static const std::size_t DIM = NN;\n\nprivate:\n    /*----------------------------------------------------------------------\n    | MEMBER VARIABLES.\n    ----------------------------------------------------------------------*/\n    /** Static array for storing the elements of an n-tuple. */\n    TT mElem[NN];\n\n}; // End of class //\n\n/*******************************************************************************\n * FREE METHODS.\n ******************************************************************************/\n/** Swaps two objects of the class \\c ScaFES::Ntuple. */\ntemplate <typename TT, std::size_t NN>\nvoid swap(ScaFES::Ntuple<TT, NN>& first, ScaFES::Ntuple<TT, NN>& second);\n/*----------------------------------------------------------------------------*/\n/** Preprares writing an object of the class \\c ScaFES::Ntuple to output. */\ntemplate <typename TT, std::size_t NN>\nstd::ostream& operator<<(std::ostream& output, const ScaFES::Ntuple<TT, NN>& t);\n\n/*******************************************************************************\n * LIFE CYCLE METHODS.\n ******************************************************************************/\ntemplate <typename TT, std::size_t NN> inline Ntuple<TT, NN>::Ntuple()\n{\n    for (std::size_t iii = 0; iii < NN; ++iii)\n    {\n        this->mElem[iii] = static_cast<TT>(0);\n    }\n}\n/*----------------------------------------------------------------------------*/\ntemplate <typename TT, std::size_t NN>\ninline Ntuple<TT, NN>::Ntuple(const TT& scal)\n{\n    for (std::size_t iii = 0; iii < NN; ++iii)\n    {\n        this->mElem[iii] = scal;\n    }\n}\n/*----------------------------------------------------------------------------*/\ntemplate <typename TT, std::size_t NN>\ninline Ntuple<TT, NN>::Ntuple(const TT& a, const TT& b)\n{\n    static_assert((NN == 2), \"Constructor is valid in case NN=2, only.\");\n    this->mElem[0] = a;\n    this->mElem[1] = b;\n}\n/*----------------------------------------------------------------------------*/\ntemplate <typename TT, std::size_t NN>\ninline Ntuple<TT, NN>::Ntuple(const TT& a, const TT& b, const TT& c)\n{\n    static_assert((NN == 3), \"Constructor is valid in case NN=3, only.\");\n    this->mElem[0] = a;\n    this->mElem[1] = b;\n    this->mElem[2] = c;\n}\n/*----------------------------------------------------------------------------*/\ntemplate <typename TT, std::size_t NN>\ninline Ntuple<TT, NN>::Ntuple(const std::vector<TT>& vec)\n{\n    for (std::size_t iii = 0; iii < NN; ++iii)\n    {\n        this->mElem[iii] = vec.at(iii);\n    }\n}\n/*----------------------------------------------------------------------------*/\ntemplate <typename TT, std::size_t NN>\ninline Ntuple<TT, NN>::Ntuple(const ScaFES::Ntuple<TT, NN>& rhs)\n{\n    for (std::size_t iii = 0; iii < rhs.dim(); ++iii)\n    {\n        this->mElem[iii] = rhs.elem(iii);\n    }\n}\n/*----------------------------------------------------------------------------*/\ntemplate <typename TT, std::size_t NN>\ninline ScaFES::Ntuple<TT, NN>& Ntuple<TT, NN>::\noperator=(ScaFES::Ntuple<TT, NN> rhs)\n{\n    swap(*this, rhs);\n    return *this;\n}\n\n/*******************************************************************************\n * GETTER METHODS.\n ******************************************************************************/\ntemplate <typename TT, std::size_t NN>\ninline std::size_t Ntuple<TT, NN>::dim() const\n{\n    return NN;\n}\n/*----------------------------------------------------------------------------*/\ntemplate <typename TT, std::size_t NN>\ninline const TT& ScaFES::Ntuple<TT, NN>::elem(const std::size_t& idx) const\n{\n    return this->mElem[idx];\n}\n/*----------------------------------------------------------------------------*/\ntemplate <typename TT, std::size_t NN>\ninline const TT& ScaFES::Ntuple<TT, NN>::\noperator[](const std::size_t& idx) const\n{\n    return this->mElem[idx];\n}\n\n/*******************************************************************************\n * SETTER METHODS.\n ******************************************************************************/\ntemplate <typename TT, std::size_t NN>\ninline TT& Ntuple<TT, NN>::elem(const std::size_t& idx)\n{\n    return this->mElem[idx];\n    // const_cast<TT&>(static_cast<const\n    // ScaFES::Ntuple<TT,NN>&>(*this).elem(idx));\n}\n/*----------------------------------------------------------------------------*/\ntemplate <typename TT, std::size_t NN>\ninline TT& Ntuple<TT, NN>::operator[](const std::size_t& idx)\n{\n    return this->mElem[idx];\n    // const_cast<TT&>(static_cast<const ScaFES::Ntuple<TT,NN>&>(*this)[idx]);\n}\n\n/*******************************************************************************\n * COMPARISON METHODS.\n ******************************************************************************/\ntemplate <typename TT, std::size_t NN>\ninline bool Ntuple<TT, NN>::operator<(const ScaFES::Ntuple<TT, NN>& rhs) const\n{\n    bool res = true;\n\n    for (std::size_t iii = 0; iii < NN; ++iii)\n    {\n        if (!(this->mElem[iii] < rhs.elem(iii)))\n        {\n            res = false;\n            break;\n        }\n    }\n\n    return res;\n}\n/*----------------------------------------------------------------------------*/\ntemplate <typename TT, std::size_t NN>\ninline bool Ntuple<TT, NN>::operator<=(const ScaFES::Ntuple<TT, NN>& rhs) const\n{\n    bool res = true;\n\n    for (std::size_t iii = 0; iii < NN; ++iii)\n    {\n        if (this->mElem[iii] > rhs.elem(iii))\n        {\n            res = false;\n            break;\n        }\n    }\n\n    return res;\n}\n/*----------------------------------------------------------------------------*/\ntemplate <typename TT, std::size_t NN>\ninline bool Ntuple<TT, NN>::operator>=(const ScaFES::Ntuple<TT, NN>& rhs) const\n{\n    bool res = true;\n\n    for (std::size_t iii = 0; iii < NN; ++iii)\n    {\n        if ((this->mElem[iii] < rhs.elem(iii)))\n        {\n            res = false;\n            break;\n        }\n    }\n\n    return res;\n    // return !(*this < rhs); Does not work because we are working elementwise!\n}\n\n/*----------------------------------------------------------------------------*/\ntemplate <typename TT, std::size_t NN>\ninline bool Ntuple<TT, NN>::operator>(const ScaFES::Ntuple<TT, NN>& rhs) const\n{\n    bool res = true;\n\n    for (std::size_t iii = 0; iii < NN; ++iii)\n    {\n        if (!(this->mElem[iii] > rhs.elem(iii)))\n        {\n            res = false;\n            break;\n        }\n    }\n\n    return res;\n    // return !(*this <= rhs); Does not work because we are working elementwise!\n}\n/*----------------------------------------------------------------------------*/\ntemplate <typename TT, std::size_t NN>\ninline bool Ntuple<TT, NN>::operator==(const ScaFES::Ntuple<TT, NN>& rhs) const\n{\n    bool res = true;\n\n    for (std::size_t iii = 0; iii < NN; ++iii)\n    {\n        if (!(::fabs(this->mElem[iii] - rhs.elem(iii)) < 2.2e-15))\n        {\n            res = false;\n            break;\n        }\n    }\n\n    return res;\n}\n/*----------------------------------------------------------------------------*/\ntemplate <typename TT, std::size_t NN>\ninline bool Ntuple<TT, NN>::operator!=(const ScaFES::Ntuple<TT, NN>& rhs) const\n{\n    return !(*this == rhs);\n}\n\n/*******************************************************************************\n * WORK METHODS.\n ******************************************************************************/\ntemplate <typename TT, std::size_t NN>\ninline std::size_t Ntuple<TT, NN>::idxMaxElem() const\n{\n    std::size_t idx = 0;\n    TT maxElem = this->mElem[0];\n\n    for (std::size_t iii = 1; iii < NN; ++iii)\n    {\n        if (maxElem < this->mElem[iii])\n        {\n            maxElem = this->mElem[iii];\n            idx = iii;\n        }\n    }\n\n    return idx;\n}\n/*----------------------------------------------------------------------------*/\ntemplate <typename TT, std::size_t NN> inline TT Ntuple<TT, NN>::size() const\n{\n    TT prod = this->mElem[0];\n\n    for (std::size_t iii = 1; iii < NN; ++iii)\n    {\n        prod *= this->mElem[iii];\n    }\n\n    return prod;\n}\n/*----------------------------------------------------------------------------*/\ntemplate <typename TT, std::size_t NN>\ninline double Ntuple<TT, NN>::norm1() const\n{\n    double res = ::fabs(this->mElem[0]);\n\n    for (std::size_t iii = 1; iii < NN; ++iii)\n    {\n        res += ::fabs(this->mElem[iii]);\n    }\n\n    return res;\n}\n/*----------------------------------------------------------------------------*/\n#ifdef SCAFES_HAVE_BOOST_SERIALIZATION\ntemplate <typename TT, std::size_t NN>\ntemplate <class Archive>\ninline void Ntuple<TT, NN>::serialize(Archive& ar, unsigned int const version)\n{\n    if (1 <= version)\n    {\n        ar&(this->mElem);\n    }\n}\n#endif\n\n/*******************************************************************************\n * ARITHMETIC METHODS.\n ******************************************************************************/\ntemplate <typename TT, std::size_t NN>\ninline ScaFES::Ntuple<TT, NN>& Ntuple<TT, NN>::operator=(const TT& sca)\n{\n    for (std::size_t iii = 0; iii < NN; ++iii)\n    {\n        this->mElem[iii] = static_cast<TT>(sca);\n    }\n\n    return *this;\n}\n/*----------------------------------------------------------------------------*/\ntemplate <typename TT, std::size_t NN>\ntemplate <typename CT>\ninline ScaFES::Ntuple<TT, NN>& Ntuple<TT, NN>::operator*=(const CT& sca)\n{\n    for (std::size_t iii = 0; iii < NN; ++iii)\n    {\n        this->mElem[iii] *= static_cast<TT>(sca);\n    }\n\n    return *this;\n}\n/*----------------------------------------------------------------------------*/\ntemplate <typename TT, std::size_t NN>\ntemplate <typename CT>\ninline ScaFES::Ntuple<TT, NN>& Ntuple<TT, NN>::operator/=(const CT& sca)\n{\n    if (::fabs(sca) < 2.2e-12)\n    {\n        throw std::runtime_error(\"Given scalar is very near to zero.\");\n    }\n    for (std::size_t iii = 0; iii < NN; ++iii)\n    {\n        this->mElem[iii] /= static_cast<TT>(sca);\n    }\n\n    return *this;\n}\n/*----------------------------------------------------------------------------*/\ntemplate <typename TT, std::size_t NN>\ninline ScaFES::Ntuple<TT, NN>& Ntuple<TT, NN>::\noperator+=(const ScaFES::Ntuple<TT, NN>& rhs)\n{\n    for (std::size_t iii = 0; iii < NN; ++iii)\n    {\n        this->mElem[iii] += rhs.elem(iii);\n    }\n\n    return *this;\n}\n/*----------------------------------------------------------------------------*/\ntemplate <typename TT, std::size_t NN>\ninline ScaFES::Ntuple<TT, NN>& Ntuple<TT, NN>::\noperator-=(const ScaFES::Ntuple<TT, NN>& rhs)\n{\n    for (std::size_t iii = 0; iii < NN; ++iii)\n    {\n        this->mElem[iii] -= rhs.elem(iii);\n    }\n\n    return *this;\n}\n/*----------------------------------------------------------------------------*/\ntemplate <typename TT, std::size_t NN>\ninline ScaFES::Ntuple<TT, NN>& Ntuple<TT, NN>::\noperator*=(const ScaFES::Ntuple<TT, NN>& rhs)\n{\n    for (std::size_t iii = 0; iii < NN; ++iii)\n    {\n        this->mElem[iii] *= rhs.elem(iii);\n    }\n\n    return *this;\n}\n/*----------------------------------------------------------------------------*/\ntemplate <typename TT, std::size_t NN>\ninline ScaFES::Ntuple<TT, NN>& Ntuple<TT, NN>::\noperator/=(const ScaFES::Ntuple<TT, NN>& rhs)\n{\n    for (std::size_t iii = 0; iii < NN; ++iii)\n    {\n        if (::fabs(rhs.elem(iii)) < 2.2e-12)\n        {\n            throw std::runtime_error(\"Element of rhs is very near to zero.\");\n        }\n    }\n    for (std::size_t iii = 0; iii < NN; ++iii)\n    {\n        this->mElem[iii] /= rhs.elem(iii);\n    }\n\n    return *this;\n}\n\n/*******************************************************************************\n* FREE METHODS WHICH ARE FRIENDS OF THIS CLASS.\n ******************************************************************************/\ntemplate <typename TT, std::size_t NN>\ninline void swap(ScaFES::Ntuple<TT, NN>& first, ScaFES::Ntuple<TT, NN>& second)\n{\n    TT tmp;\n\n    for (std::size_t iii = 0; iii < second.dim(); ++iii)\n    {\n        tmp = second.mElem[iii];\n        second.mElem[iii] = first.mElem[iii];\n        first.mElem[iii] = tmp;\n    }\n}\n/*----------------------------------------------------------------------------*/\ntemplate <typename TT, std::size_t NN>\ninline std::ostream& operator<<(std::ostream& output,\n                                const ScaFES::Ntuple<TT, NN>& t)\n{\n    output << \"[\";\n    for (std::size_t iii = 0; iii < NN; ++iii)\n    {\n        output << ::std::setw(4) << ::std::right << t.elem(iii);\n\n        if (NN - 1 > iii)\n        {\n            output << \"; \";\n        }\n    }\n\n    output << \"]\";\n    return output;\n}\n\n} // End of namespace. //\n\n/*******************************************************************************\n ******************************************************************************/\n#ifdef SCAFES_HAVE_BOOST_SERIALIZATION\nnamespace boost\n{\nnamespace serialization\n{\n    /** Designed to set the boost serialization version of a class template. */\n    template <typename TT, std::size_t NN>\n    struct version<ScaFES::Ntuple<TT, NN>>\n    {\n        /** Sets the version number for serialization. */\n        BOOST_STATIC_CONSTANT(unsigned long int, value = 2);\n    };\n}\n}\n#endif\n\n#endif\n", "meta": {"hexsha": "640372659b29c3e55dcc66ef73f18fa7374ffca3", "size": 22409, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/ScaFES_Ntuple.hpp", "max_stars_repo_name": "nih23/MRIDrivenHeatSimulation", "max_stars_repo_head_hexsha": "de6d16853df1faf44c700d1fc06584351bf6c816", "max_stars_repo_licenses": ["BSL-1.0", "BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ScaFES_Ntuple.hpp", "max_issues_repo_name": "nih23/MRIDrivenHeatSimulation", "max_issues_repo_head_hexsha": "de6d16853df1faf44c700d1fc06584351bf6c816", "max_issues_repo_licenses": ["BSL-1.0", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ScaFES_Ntuple.hpp", "max_forks_repo_name": "nih23/MRIDrivenHeatSimulation", "max_forks_repo_head_hexsha": "de6d16853df1faf44c700d1fc06584351bf6c816", "max_forks_repo_licenses": ["BSL-1.0", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.6186317322, "max_line_length": 80, "alphanum_fraction": 0.4603953769, "num_tokens": 5301, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6113819591324418, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.46678019583742414}}
{"text": "/////////////////////////////////////////////////////////////////////////////////\n// distribution::toolkit::distributions::poisson::random.hpp               \t   //\n//                                                                             //\n//  (C) Copyright 2010 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_POISSON_RANDOM_HPP_ER_2010\n#define BOOST_STATISTICS_DETAIL_DISTRIBUTION_TOOLKIT_POISSON_RANDOM_HPP_ER_2010\n#include <boost/math/distributions/poisson.hpp>\n#include <boost/random/poisson_distribution.hpp>\n#include <boost/statistics/detail/distribution_common/meta/random/distribution.hpp>\n\nnamespace boost{\nnamespace statistics{\nnamespace detail{\nnamespace distribution{\nnamespace meta{\n\n    template<typename T,typename P>\n    struct random_distribution< \n        boost::math::poisson_distribution<T,P> \n    >{\n        typedef boost::math::poisson_distribution<T,P> dist_;\n        typedef boost::poisson_distribution<int,T> type;\n        \n        static type call(const dist_& d){ \n            return type(d.mean()); \n        }\n    };\n    \n}// meta\n}// distribution\n}// detail\n}// statistics\n}// boost\n\n#endif", "meta": {"hexsha": "ab6de4a2a1028083507f07077610dd876f63cc69", "size": 1518, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "distribution_toolkit/boost/statistics/detail/distribution_toolkit/distributions/poisson/random.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/distributions/poisson/random.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/distributions/poisson/random.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": 38.9230769231, "max_line_length": 83, "alphanum_fraction": 0.5619235837, "num_tokens": 282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256631249076, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.4667674668484875}}
{"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 *    References\n *      Craidon, C.B. A Desription of the Langley Wireframe Geometry Standard (LaWGS) format, NASA\n *          TECHNICAL MEMORANDUM 85767.\n *\n */\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MAIN\n\n#include <boost/make_shared.hpp>\n#include <memory>\n#include <boost/test/unit_test.hpp>\n\n#include <Eigen/Core>\n\n#include \"tudat/math/basic/mathematicalConstants.h\"\n\n#include \"tudat/math/geometric/lawgsPartGeometry.h\"\n#include \"tudat/math/geometric/sphereSegment.h\"\n\nnamespace tudat\n{\nnamespace unit_tests\n{\n\nBOOST_AUTO_TEST_SUITE( test_Lawgs_Surface_Geometry )\n\n//! Test implementation of Lawgs surface geometry.\nBOOST_AUTO_TEST_CASE( testLawgsSurfaceGeometry )\n{\n    using namespace tudat;\n    using namespace geometric_shapes;\n\n    // Create a full sphere as test geometry, with a radius of 2.0.\n    const double sphereRadius = 2.0;\n    std::shared_ptr< SphereSegment > sphere = std::make_shared< SphereSegment >(\n                sphereRadius );\n\n    // Create a Lawgs mesh of the sphere.\n    LawgsPartGeometry lawgsSurface;\n    const int numberOfLines = 21;\n    const int numberOfPoints = 21;\n    lawgsSurface.setMesh( sphere, numberOfLines, numberOfPoints );\n\n    // Retrieve the total surface area and check if it is sufficiently close\n    // to the expected value.\n    using mathematical_constants::PI;\n    const double totalArea = lawgsSurface.getTotalArea( );\n    BOOST_CHECK_SMALL( std::fabs( totalArea - 4.0 * PI\n                                  * ( std::pow( sphereRadius, 2.0 ) ) ), 0.6 );\n\n    // Test if number of lines on mesh is correct.\n    BOOST_CHECK_EQUAL( lawgsSurface.getNumberOfLines( ), numberOfLines );\n\n    // Test if number of points per line on mesh is correct.\n    BOOST_CHECK_EQUAL( lawgsSurface.getNumberOfPoints( ), numberOfPoints );\n\n    // Set part name.\n    std::string partName = \"sphere\";\n    lawgsSurface.setName( partName );\n\n    // Test if part name is properly retrieved.\n    BOOST_CHECK_EQUAL( lawgsSurface.getName( ), partName );\n\n    // Retrieve normal and centroid for panel 0, 0.\n    Eigen::Vector3d testNormal = lawgsSurface.getPanelSurfaceNormal( 0, 0 );\n    Eigen::Vector3d testCentroid = lawgsSurface.getPanelCentroid( 0, 0 );\n\n    // Test whether centroid and normal are collinear for panel 0, 0.\n    BOOST_CHECK_SMALL( std::fabs( testCentroid.normalized( ).dot(\n                                      testNormal.normalized( ) ) ) - 1.0, 1.0e-5 );\n\n    // Test if the position of the x- and y-coordinate of panel 0, 0 is correct.\n    BOOST_CHECK_SMALL( std::fabs( std::atan( testCentroid.y( ) / testCentroid.x( ) ) - PI / 20.0 ),\n                       std::numeric_limits< double >::epsilon( ) );\n}\n\nBOOST_AUTO_TEST_SUITE_END( )\n\n} // namespace unit_tests\n} // namespace tudat\n", "meta": {"hexsha": "16fc0c2cb4d7cf257751717f8b0c46e032b731f9", "size": 3174, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/src/math/geometric/unitTestLawgsSurfaceGeometry.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": "tests/src/math/geometric/unitTestLawgsSurfaceGeometry.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": "tests/src/math/geometric/unitTestLawgsSurfaceGeometry.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": 34.8791208791, "max_line_length": 99, "alphanum_fraction": 0.6912413359, "num_tokens": 798, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637361282707, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.46667987821893525}}
{"text": "\n#include <NTL/LLL.h>\n\nNTL_CLIENT\n\nlong SubsetSumSolution(const vec_ZZ& z)\n{\n   long n = z.length()-3;\n   long j;\n\n   if (z(n+1) != 0) return 0;\n   if (z(n+2) != -1 && z(n+2) != 1) return 0;\n   for (j = 1; j <= n; j++) \n      if (z(j) != -1 && z(j) != 1) return 0;\n\n   return 1;\n}\n\n\n\nint main()\n{\n   RR::SetPrecision(150);\n   long n, b, size;\n\n   cerr << \"n: \";\n   cin >> n;\n\n   cerr << \"b: \";\n   cin >> b;\n\n   cerr << \"size: \";\n   cin >> size;\n\n   cerr << \"prune: \";\n   long prune;\n   cin >> prune;\n\n   ZZ seed;\n   cerr << \"seed: \";\n   cin >> seed;\n\n   if (seed != 0)\n      SetSeed(seed);\n\n   char alg;\n   cerr << \"alg [fqQxr]: \";\n   cin >> alg;\n\n   double TotalTime = 0;\n   long TotalSucc = 0;\n\n   long iter;\n\n   for (iter = 1; iter <= 20; iter++) {\n      vec_ZZ a;\n      a.SetLength(n);\n   \n      ZZ bound;\n   \n      LeftShift(bound, to_ZZ(1), b);\n   \n      long i;\n      for (i = 1; i <= n; i++) {\n         RandomBnd(a(i), bound);\n         a(i) += 1;\n      }\n   \n      ZZ S;\n   \n      do {\n         RandomLen(S, n+1);\n      } while (weight(S) != n/2+1);\n   \n      ZZ s;\n      clear(s);\n      for (i = 1; i <= n; i++)\n         if (bit(S, i-1))\n            s += a(i);\n   \n      mat_ZZ B(INIT_SIZE, n+1, n+3);\n   \n      for (i = 1; i <= n; i++) {\n         B(i, i) = 2;\n         B(i, n+1) = a(i) * n;\n         B(i, n+3) = n;\n      }\n   \n      for (i = 1; i <= n; i++)\n         B(n+1, i) = 1;\n   \n      B(n+1, n+1) = s * n;\n      B(n+1, n+2) = 1;\n      B(n+1, n+3) = n;\n      B(n+1, n+3) *= n/2;\n   \n      swap(B(1), B(n+1)); \n   \n      for (i = 2; i <= n; i++) {\n         long j = RandomBnd(n-i+2) + i;\n         swap(B(i), B(j));\n      }\n   \n      double t;\n\n      LLLStatusInterval = 10;\n   \n      t = GetTime();\n      switch (alg) {\n      case 'f':\n         BKZ_FP(B, 0.99, size, prune, SubsetSumSolution);\n         break;\n      case 'q':\n         BKZ_QP(B, 0.99, size, prune, SubsetSumSolution);\n         break;\n      case 'Q':\n         BKZ_QP1(B, 0.99, size, prune, SubsetSumSolution);\n         break;\n      case 'x':\n         BKZ_XD(B, 0.99, size, prune, SubsetSumSolution);\n         break;\n      case 'r':\n         BKZ_RR(B, 0.99, size, prune, SubsetSumSolution);\n         break;\n      default:\n         Error(\"invalid algorithm\");\n      }\n\n\n      t = GetTime()-t;\n   \n      long succ = 0;\n      for (i = 1; i <= n+1; i++)\n         if (SubsetSumSolution(B(i)))\n            succ = 1;\n\n      TotalTime += t;\n      TotalSucc += succ;\n\n      if (succ)\n         cerr << \"+\";\n      else\n         cerr << \"-\";\n   }\n\n   cerr << \"\\n\";\n\n   cerr << \"number of success: \" << TotalSucc << \"\\n\";\n   cerr << \"average time: \" << TotalTime/20 << \"\\n\";\n\n   return 0;\n}\n      \n\n\n", "meta": {"hexsha": "cbae1c216c3942819bf9bbeb67e63d44ff7dd443", "size": 2666, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "RUNETag/WinNTL/tests/subset.cpp", "max_stars_repo_name": "vshesh/RUNEtag", "max_stars_repo_head_hexsha": "800e93fb7c0560ea5a6261ffc60c02638a8cc8c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "RUNETag/WinNTL/tests/subset.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/tests/subset.cpp", "max_forks_repo_name": "vshesh/RUNEtag", "max_forks_repo_head_hexsha": "800e93fb7c0560ea5a6261ffc60c02638a8cc8c9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.0897435897, "max_line_length": 58, "alphanum_fraction": 0.4036009002, "num_tokens": 938, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4666607367752398}}
{"text": "#ifndef STAN_MATH_PRIM_MAT_FUN_LOG_SUM_EXP_HPP\n#define STAN_MATH_PRIM_MAT_FUN_LOG_SUM_EXP_HPP\n\n#include <stan/math/prim/scal/fun/log1p.hpp>\n#include <stan/math/prim/mat/fun/Eigen.hpp>\n#include <boost/math/tools/promotion.hpp>\n#include <limits>\n#include <vector>\n\nnamespace stan {\nnamespace math {\n\n/**\n * Return the log of the sum of the exponentiated values of the specified\n * matrix of values.  The matrix may be a full matrix, a vector,\n * or a row vector.\n *\n * The function is defined as follows to prevent overflow in exponential\n * calculations.\n *\n * \\f$\\log \\sum_{n=1}^N \\exp(x_n) = \\max(x) + \\log \\sum_{n=1}^N \\exp(x_n -\n * \\max(x))\\f$.\n *\n * @param[in] x Matrix of specified values\n * @return The log of the sum of the exponentiated vector values.\n */\ntemplate <int R, int C>\ndouble log_sum_exp(const Eigen::Matrix<double, R, C>& x) {\n  using std::exp;\n  using std::log;\n  using std::numeric_limits;\n  double max = -numeric_limits<double>::infinity();\n  for (int i = 0; i < x.size(); i++)\n    if (x(i) > max)\n      max = x(i);\n\n  double sum = 0.0;\n  for (int i = 0; i < x.size(); i++)\n    if (x(i) != -numeric_limits<double>::infinity())\n      sum += exp(x(i) - max);\n\n  return max + log(sum);\n}\n\n}  // namespace math\n}  // namespace stan\n\n#endif\n", "meta": {"hexsha": "5af75f18ad06268efbc795026eff50969a18b812", "size": 1259, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/prim/mat/fun/log_sum_exp.hpp", "max_stars_repo_name": "jrmie/math", "max_stars_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "stan/math/prim/mat/fun/log_sum_exp.hpp", "max_issues_repo_name": "jrmie/math", "max_issues_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stan/math/prim/mat/fun/log_sum_exp.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": 25.693877551, "max_line_length": 74, "alphanum_fraction": 0.6600476569, "num_tokens": 370, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765706, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4666607318926225}}
{"text": "#ifndef qlex_sabr_interpolation_hpp\n#define qlex_sabr_interpolation_hpp\n\n#include <math/interpolations/xabrinterpolation.hpp>\n#include <ql/termstructures/volatility/sabr.hpp>\n\n#include <boost/make_shared.hpp>\n#include <boost/assign/list_of.hpp>\n\nusing namespace QuantLib;\n\nnamespace QLExtension {\n\nnamespace detail {\n\n    class SABRWrapper {\n      public:\n        SABRWrapper(const Time t, const Real &forward,\n                    const std::vector<Real> &params)\n        : t_(t), forward_(forward), params_(params) {\n            validateSabrParameters(params[0], params[1], params[2], params[3]);\n        }\n        Real volatility(const Real x) {\n            return sabrVolatility(x, forward_, t_, params_[0], params_[1],\n                                  params_[2], params_[3]);\n        }\n\n      private:\n        const Real t_, &forward_;\n        const std::vector<Real> &params_;\n    };\n\n    struct SABRSpecs {\n        Size dimension() { return 4; }\n        void defaultValues(std::vector<Real> &params, std::vector<bool> &,\n                           const Real &forward, const Real expiryTIme) {\n            if (params[1] == Null<Real>())\n                params[1] = 0.5;\n            if (params[0] == Null<Real>())\n                // adapt alpha to beta level\n                params[0] =\n                    0.2 *\n                    (params[1] < 0.9999 ? std::pow(forward, 1.0 - params[1]) : 1.0);\n            if (params[2] == Null<Real>())\n                params[2] = std::sqrt(0.4);\n            if (params[3] == Null<Real>())\n                params[3] = 0.0;\n        }\n        void guess(Array &values, const std::vector<bool> &paramIsFixed,\n                   const Real &forward, const Real expiryTime,\n                   const std::vector<Real> &r) {\n            Size j = 0;\n            if (!paramIsFixed[1])\n                values[1] = (1.0 - 2E-6) * r[j++] + 1E-6;\n            if (!paramIsFixed[0]) {\n                values[0] =\n                    (1.0 - 2E-6) * r[j++] + 1E-6; // lognormal vol guess\n                // adapt this to beta level\n                if(values[1] < 0.999)\n                    values[0] *=\n                        std::pow(forward,\n                                 1.0 - values[1]);\n            }\n            if (!paramIsFixed[2])\n                values[2] = 1.5 * r[j++] + 1E-6;\n            if (!paramIsFixed[3])\n                values[3] = (2.0 * r[j++] - 1.0) * (1.0 - 1E-6);\n        }\n        Real eps1() { return .0000001; }\n        Real eps2() { return .9999; }\n        Real dilationFactor() { return 0.001; }\n        Array inverse(const Array &y, const std::vector<bool>&,\n                      const std::vector<Real>&, const Real) {\n            Array x(4);\n            x[0] = y[0] < 25.0 + eps1() ? std::sqrt(y[0] - eps1())\n                                        : (y[0] - eps1() + 25.0) / 10.0;\n            // y_[1] = std::tan(M_PI*(x[1] - 0.5))/dilationFactor();\n            x[1] = std::sqrt(-std::log(y[1]));\n            x[2] = y[2] < 25.0 + eps1() ? std::sqrt(y[2] - eps1())\n                                        : (y[2] - eps1() + 25.0) / 10.0;\n            x[3] = std::asin(y[3] / eps2());\n            return x;\n        }\n        Array direct(const Array &x, const std::vector<bool>&,\n                     const std::vector<Real>&, const Real) {\n            Array y(4);\n            y[0] = std::fabs(x[0]) < 5.0\n                       ? x[0] * x[0] + eps1()\n                       : (10.0 * std::fabs(x[0]) - 25.0) + eps1();\n            // y_[1] = std::atan(dilationFactor_*x[1])/M_PI + 0.5;\n            y[1] = std::fabs(x[1]) < std::sqrt(-std::log(eps1()))\n                       ? std::exp(-(x[1] * x[1]))\n                       : eps1();\n            y[2] = std::fabs(x[2]) < 5.0\n                       ? x[2] * x[2] + eps1()\n                       : (10.0 * std::fabs(x[2]) - 25.0) + eps1();\n            y[3] = std::fabs(x[3]) < 2.5 * M_PI\n                       ? eps2() * std::sin(x[3])\n                       : eps2() * (x[3] > 0.0 ? 1.0 : (-1.0));\n            return y;\n        }\n        typedef SABRWrapper type;\n        boost::shared_ptr<type> instance(const Time t, const Real &forward,\n                                         const std::vector<Real> &params) {\n            return boost::make_shared<type>(t, forward, params);\n        }\n    };\n\n}\n\n    //! %SABR smile interpolation between discrete volatility points.\n    class SABRInterpolation : public Interpolation {\n      public:\n        template <class I1, class I2>\n        SABRInterpolation(const I1 &xBegin,  // x = strikes\n                          const I1 &xEnd,\n                          const I2 &yBegin,  // y = volatilities\n                          Time t,            // option expiry\n                          const Real& forward,\n                          Real alpha,\n                          Real beta,\n                          Real nu,\n                          Real rho,\n                          bool alphaIsFixed,\n                          bool betaIsFixed,\n                          bool nuIsFixed,\n                          bool rhoIsFixed,\n                          bool vegaWeighted = true,\n                          const boost::shared_ptr<EndCriteria>& endCriteria\n                                  = boost::shared_ptr<EndCriteria>(),\n                          const boost::shared_ptr<OptimizationMethod>& optMethod\n                                  = boost::shared_ptr<OptimizationMethod>(),\n                          const Real errorAccept = 0.0020,\n                          const bool useMaxError = false,\n                          const Size maxGuesses = 50) {\n\n            impl_ = boost::shared_ptr<Interpolation::Impl>(\n                new detail::XABRInterpolationImpl<I1, I2, detail::SABRSpecs>(\n                    xBegin, xEnd, yBegin, t, forward,\n                    boost::assign::list_of(alpha)(beta)(nu)(rho),\n                    boost::assign::list_of(alphaIsFixed)(betaIsFixed)(nuIsFixed)(rhoIsFixed),\n                    vegaWeighted, endCriteria, optMethod, errorAccept, useMaxError,\n                    maxGuesses));\n            coeffs_ = boost::dynamic_pointer_cast<\n                detail::XABRCoeffHolder<detail::SABRSpecs> >(impl_);\n        }\n        Real expiry()  const { return coeffs_->t_; }\n        Real forward() const { return coeffs_->forward_; }\n        Real alpha()   const { return coeffs_->params_[0]; }\n        Real beta()    const { return coeffs_->params_[1]; }\n        Real nu()      const { return coeffs_->params_[2]; }\n        Real rho()     const { return coeffs_->params_[3]; }\n        Real rmsError() const { return coeffs_->error_; }\n        Real maxError() const { return coeffs_->maxError_; }\n        const std::vector<Real>& interpolationWeights() const {\n            return coeffs_->weights_;\n        }\n        EndCriteria::Type endCriteria() { return coeffs_->XABREndCriteria_; }\n\n      private:\n        boost::shared_ptr<detail::XABRCoeffHolder<detail::SABRSpecs> > coeffs_;\n    };\n\n    //! %SABR interpolation factory and traits\n    class SABR {\n      public:\n        SABR(Time t, Real forward,\n             Real alpha, Real beta, Real nu, Real rho,\n             bool alphaIsFixed, bool betaIsFixed,\n             bool nuIsFixed, bool rhoIsFixed,\n             bool vegaWeighted = false,\n             const boost::shared_ptr<EndCriteria> endCriteria\n                 = boost::shared_ptr<EndCriteria>(),\n             const boost::shared_ptr<OptimizationMethod> optMethod\n                 = boost::shared_ptr<OptimizationMethod>(),\n             const Real errorAccept = 0.0020, const bool useMaxError = false,\n             const Size maxGuesses = 50)\n        : t_(t), forward_(forward),\n          alpha_(alpha), beta_(beta), nu_(nu), rho_(rho),\n          alphaIsFixed_(alphaIsFixed), betaIsFixed_(betaIsFixed),\n          nuIsFixed_(nuIsFixed), rhoIsFixed_(rhoIsFixed),\n          vegaWeighted_(vegaWeighted),\n          endCriteria_(endCriteria),\n          optMethod_(optMethod), errorAccept_(errorAccept),\n          useMaxError_(useMaxError), maxGuesses_(maxGuesses) {}\n        template <class I1, class I2>\n        Interpolation interpolate(const I1 &xBegin, const I1 &xEnd,\n                                  const I2 &yBegin) const {\n            return SABRInterpolation(\n                xBegin, xEnd, yBegin, t_, forward_, alpha_, beta_, nu_, rho_,\n                alphaIsFixed_, betaIsFixed_, nuIsFixed_, rhoIsFixed_, vegaWeighted_,\n                endCriteria_, optMethod_, errorAccept_, useMaxError_, maxGuesses_);\n        }\n        static const bool global = true;\n\n      private:\n        Time t_;\n        Real forward_;\n        Real alpha_, beta_, nu_, rho_;\n        bool alphaIsFixed_, betaIsFixed_, nuIsFixed_, rhoIsFixed_;\n        bool vegaWeighted_;\n        const boost::shared_ptr<EndCriteria> endCriteria_;\n        const boost::shared_ptr<OptimizationMethod> optMethod_;\n        const Real errorAccept_;\n        const bool useMaxError_;\n        const Size maxGuesses_;\n    };\n\n}\n\n#endif\n", "meta": {"hexsha": "98788a5847c7e0133b4d2da7047ca615e031d381", "size": 9000, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "CppCoreLibrary/QLExtension/math/interpolations/sabrinterpolation.hpp", "max_stars_repo_name": "qg0/EliteQuant_Excel", "max_stars_repo_head_hexsha": "987bb670e8be0e60525dde656d5a315e9a6ac718", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2021-05-21T23:06:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T17:29:10.000Z", "max_issues_repo_path": "CppCoreLibrary/QLExtension/math/interpolations/sabrinterpolation.hpp", "max_issues_repo_name": "qg0/EliteQuant_Excel", "max_issues_repo_head_hexsha": "987bb670e8be0e60525dde656d5a315e9a6ac718", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CppCoreLibrary/QLExtension/math/interpolations/sabrinterpolation.hpp", "max_forks_repo_name": "qg0/EliteQuant_Excel", "max_forks_repo_head_hexsha": "987bb670e8be0e60525dde656d5a315e9a6ac718", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-06-24T13:45:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-23T11:13:12.000Z", "avg_line_length": 42.4528301887, "max_line_length": 93, "alphanum_fraction": 0.4953333333, "num_tokens": 2263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619091240702, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4666607221273876}}
{"text": "#ifndef __CONTROL_HH__\n#define __CONTROL_HH__\n/********************************* TRICK HEADER *******************************\nPURPOSE:\n      (Describe the CONTROL Module On Board)\nLIBRARY DEPENDENCY:\n      ((../src/control.cpp))\nPROGRAMMERS:\n      (((Chung-Fan Yang) (Chun-Hsu Lai) () () ))\n*******************************************************************************/\n#include <armadillo>\n#include \"aux.hh\"\n#include \"datadeck.hh\"\n#include \"env/atmosphere76.hh\"\n#include \"env/atmosphere_nasa2002.hh\"\n#include \"matrix_tool.hh\"\n#include \"cadac_constants.hh\"\n#include \"integrate.hh\"\n\nclass Control {\n  TRICK_INTERFACE(Control);\n\n public:\n  Control();\n\n  void initialize();\n\n  void control(double int_step);\n  void set_close_loop_pole(double in1, double in2);\n  void set_factor(double in1, double in2);\n  void set_feedforward_gain(double in1);\n\n  void set_aero_coffe(double in1, double in2, double in3);\n  void set_IBBB0(double in1, double in2, double in3);\n  void set_IBBB1(double in1, double in2, double in3);\n  void set_controller_var(double in1, double in2, double in3, double in4,\n                          double in5, double in6, double in7);\n  void set_NO_CONTROL();\n  void set_acc_control();\n  void set_engnum(double in);\n  void set_reference_point(double in);\n\n  double get_theta_a_cmd();\n  double get_theta_b_cmd();\n  double get_theta_c_cmd();\n  double get_theta_d_cmd();\n  void load_aerotable(const char* filename);\n  void atmosphere_use_nasa();\n  void atmosphere_use_public();\n\n  void set_ancomx(double in);\n  void set_alcomx(double in);\n\n  enum CONTROL_TYPE {\n    NO_CONTROL = 0,\n    S2_PITCH_DOWN_I,\n    S2_PITCH_DOWN_II,\n    S2_ROLL_CONTROL,\n    S3_PITCH_DOWN,\n    S2_AOA,\n    S3_AOA,\n    ACC_CONTROL_ON\n  };\n\n  std::function<int()> grab_thrust_state;\n  std::function<double()> grab_dvbec;\n  std::function<double()> grab_thtvdcx;\n  std::function<double()> grab_thtbdcx;\n  std::function<double()> grab_phibdcx;\n  std::function<double()> grab_psibdcx;\n  std::function<double()> grab_alphacx;\n  std::function<double()> grab_altc;\n\n  std::function<double()> grab_qqcx;\n  std::function<double()> grab_rrcx;\n  std::function<double()> grab_phipcx;\n  std::function<double()> grab_alppcx;\n\n  std::function<arma::vec3()> grab_FSPCB;\n\n  std::function<arma::vec3()> grab_computed_WBIB;\n  std::function<arma::vec4()> grab_TBDQ;\n  std::function<arma::mat33()> grab_TBD;\n  std::function<arma::mat33()> grab_TBICI;\n  std::function<arma::mat33()> grab_TBIC;\n  std::function<arma::vec3()> grab_WBECB;\n  std::function<arma::vec3()> grab_ABICB;\n\n  double get_delecx();\n  double get_delrcx();\n\n  void calculate_xcg_thrust(double int_step);\n\n private:\n  cad::Atmosphere* atmosphere;\n\n  double control_normal_accel(double ancomx_in, double int_step);\n  double control_yaw_accel(double alcomx_in, double int_step);\n  void aerodynamics_der();\n  void Euler_Angle_Control(double Cmd_Input, double P_Gain_1, double P_Gain_2, double Angle_Feedback, double Rate_Feedback, double &Cmd_Output);\n\n  double delecx; /* *io (d)      Pitch command deflection */  // n\n  double delrcx; /* *io (d)      Yaw command deflection */    // n\n\n  enum CONTROL_TYPE maut; /* *io (--)     maut=|mauty|mautp| see table */\n  int mfreeze;   /* *io (--)     =0:Unfreeze; =1:Freeze; increment for more */\n  double waclp;  /* *io (r/s)    Nat freq of accel close loop complex pole */\n  double zaclp;  /* *io (--)     Damping of accel close loop complex pole */\n  double paclp;  /* *io (--)     Close loop real pole */\n  double yyd;    /* *io (m/s2)   Yaw feed-forward derivative variable */\n  double yy;     /* *io (m/s)    Yaw feed-forward integration variable */\n  double zzd;    /* *io (m/s2)   Pitch feed-forward derivative variable */\n  double zz;     /* *io (m/s)    Pitch feed-forward integration variable */\n  double alcomx_actual; /* *io (--)     Later accel com limited by 'betalimx' */\n  double ancomx_actual; /* *io (--)     Normal accel com limited by 'alplimx' */\n  arma::vec GAINFP;  /* *io (--)     Feedback gains of pitch accel controller */\n  double _GAINFP[3]; /* *io (--)     Feedback gains of pitch accel controller */\n  double gainp;  /* *io (s2/m)   Proportional gain in pitch acceleration loop */\n  double gainl;  /* *io (--)     Gain in lateral acceleration loop */\n  double gkp;    /* *io (s)      Gain of roll rate feedback */\n  double gkphi;  /* *io (--)     Gain of roll angle feedback */\n  double isetc2; /* *io (--)     Flag to print freeze variables */\n  double wacly;  /* *io (r/s)    Nat freq of accel close loop pole, yaw */\n  double zacly;  /* *io (--)     Damping of accel close loop pole, yaw */\n  double pacly;  /* *io (--)     Close loop real pole, yaw */\n  double gainy;  /* *io (--)     Gain in lateral acceleration loop */\n  arma::vec GAINFY;  /* *io (--)     Feedback gains of yaw accel controller */\n  double _GAINFY[3]; /* *io (--)     Feedback gains of yaw accel controller */\n  double factwaclp; /* *io (--)     Factor to mod 'waclp': waclp*(1+factwacl) */\n  double factwacly; /* *io (--)     Factor to mod 'wacly': wacly*(1+factwacl) */\n  double alcomx;    /* *io (--)     Lateral (horizontal) acceleration command */\n  double ancomx;    /* *io (--)     Pitch (normal) acceleration command */\n\n  double fmasse;\n  double mdot;\n  double fmass0;\n  double xcg_0;\n  double xcg_1;\n  double isp;\n  double vmass;\n  double vmass0;\n\n  arma::vec IBBB0;\n  double _IBBB0[3];\n\n  arma::vec IBBB1;\n  double _IBBB1[3];\n\n  arma::vec IBBB2;\n  double _IBBB2[3];\n\n  double theta_a_cmd;\n  double theta_b_cmd;\n  double theta_c_cmd;\n  double theta_d_cmd;\n  double lx;\n\n  double xcg;\n  double thrust;\n  double mass_ratio;\n\n  double reference_point;\n  double d;\n\n  // Aerodynamics def()\n  Datadeck aerotable;\n\n  double dla;\n  double dlde;\n  double dma;\n  double dmq;\n  double dmde;\n  double dyb;\n  double dydr;\n  double dnb;\n  double dnr;\n  double dndr;\n  double dllp;\n  double dllda;\n  double dnd;\n  double cla;\n  double clde;\n  double cyb;\n  double cydr;\n  double cllda;\n  double cllp;\n  double cma;\n  double cmde;\n  double cmq;\n  double cnb;\n  double cndr;\n  double cnr;\n  double cn0;\n  // diagnostics\n  double stmarg_yaw;\n  double stmarg_pitch;\n  double realp1;\n  double realp2;\n  double wnp;\n  double zetp;\n  double rpreal;\n  double realy1;\n  double realy2;\n  double wny;\n  double zety;\n  double ryreal;\n  double refa;\n  double refd;\n  double xcp;\n  double pdynmc;\n  double vmach;\n\n  double eng_num;\n};\n\n#endif  // __CONTROL_HH__\n", "meta": {"hexsha": "9e4d9131e380c7b0dc467d371972d4e9aad99fa1", "size": 6418, "ext": "hh", "lang": "C++", "max_stars_repo_path": "modules/gnc/control.hh", "max_stars_repo_name": "mlouielu/mazu-sim", "max_stars_repo_head_hexsha": "fd2da3a9f7ca3ca30d3d3f4bbd6966cb68623225", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-26T07:09:54.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-26T07:09:54.000Z", "max_issues_repo_path": "modules/gnc/control.hh", "max_issues_repo_name": "mlouielu/mazu-sim", "max_issues_repo_head_hexsha": "fd2da3a9f7ca3ca30d3d3f4bbd6966cb68623225", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/gnc/control.hh", "max_forks_repo_name": "mlouielu/mazu-sim", "max_forks_repo_head_hexsha": "fd2da3a9f7ca3ca30d3d3f4bbd6966cb68623225", "max_forks_repo_licenses": ["BSD-3-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.5760368664, "max_line_length": 144, "alphanum_fraction": 0.6556559676, "num_tokens": 1884, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619091240701, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4666607221273875}}
{"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_SINHCOSH_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_SINHCOSH_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n    @ingroup group-hyperbolic\n    This function object computes simultaneously  and at lower cost\n    the @c sinh and @c cosh of the input\n\n    @par Header <boost/simd/function/sinhcosh.hpp>\n\n    @see  sinh, cosh\n\n    @par Example:\n\n      @snippet sinhcosh.cpp sinhcosh\n\n    @par Possible output:\n\n      @snippet sinhcosh.txt sinhcosh\n\n  **/\n  std::pair<IEEEValue, IEEEValue> sinhcosh(IEEEValue const& x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/sinhcosh.hpp>\n#include <boost/simd/function/simd/sinhcosh.hpp>\n\n#endif\n", "meta": {"hexsha": "778210fc74111ea73bc1093adafe9fba36c57611", "size": 1089, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/sinhcosh.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/sinhcosh.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/sinhcosh.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": 24.75, "max_line_length": 100, "alphanum_fraction": 0.5941230487, "num_tokens": 247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971212, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.46665507592390826}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2014 Jose Aparicio\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n#ifndef quantlib_binomial_loss_model_hpp\n#define quantlib_binomial_loss_model_hpp\n\n#include <ql/handle.hpp>\n#include <ql/experimental/credit/basket.hpp>\n#include <ql/experimental/credit/defaultlossmodel.hpp>\n#include <ql/experimental/credit/constantlosslatentmodel.hpp>\n#include <boost/lambda/lambda.hpp>\n#include <boost/lambda/bind.hpp>\n#include <boost/bind.hpp>\n#include <algorithm>\n#include <numeric>\n\nnamespace QuantLib {\n\n    /*! Binomial Defaultable Basket Loss Model\\par\n    Models the portfolio loss distribution by approximatting it to an adjusted \n    binomial. Fits the two moments of the loss distribution through an adapted \n    binomial approximation. This simple model allows for portfolio inhomogeneity\n    with no excesive cost over the LHP.\\par\n    See:\\par\n    <b>Approximating Independent Loss Distributions with an Adjusted Binomial \n    Distribution</b> , Dominic O'Kane, 2007 EDHEC RISK AND ASSET MANAGEMENT \n    RESEARCH CENTRE \\par\n    <b>Modelling single name and multi-name credit derivatives</b> Chapter \n    18.5.2, Dominic O'Kane, Wiley Finance, 2008 \\par\n    The version presented here is adaptated to the multifactorial case\n    by computing a conditional binomial approximation; notice that the Binomial\n    is stable. This way the model can be used also in risk management models\n    rather than only in pricing. The copula is also left \n    undefined/arbitrary. \\par\n    LLM: Loss Latent Model template parameter able to model default and \n    loss.\\par\n    The model is allowed and arbitrary copula, although initially designed for\n    a Gaussian setup. If these exotic versions were not allowed the template \n    parameter can then be dropped but the use of random recoveries should be\n    added in some other way.\n\n    \\todo untested/wip for the random recovery models.\n    \\todo integrate with the previously computed probability inversions of\n    the cumulative functions.\n    */\n    template<class LLM>\n    class BinomialLossModel : public DefaultLossModel {\n    public:\n        typedef typename LLM::copulaType copulaType;\n        BinomialLossModel(\n            const boost::shared_ptr<LLM>& copula)\n        : copula_(copula) { }\n    private:\n        void resetModel() {\n            /* say there are defaults and these havent settled... and this is \n            the engine to compute them.... is this the wrong place?:*/\n            attachAmount_ = basket_->remainingAttachmentAmount();\n            detachAmount_ = basket_->remainingDetachmentAmount();\n\n            copula_->resetBasket(basket_.currentLink());// forces interface\n        }\n    protected:\n        /*! Returns the probability of the default loss values given by the \n            method lossPoints.\n        */\n        Disposable<std::vector<Real> > \n            expectedDistribution(const Date& date) const {\n            // precal date conditional magnitudes:\n            std::vector<Real> notionals = basket_->remainingNotionals(date);\n            std::vector<Probability> invProbs = \n                basket_->remainingProbabilities(date);\n            for(Size iName=0; iName<invProbs.size(); iName++)\n                invProbs[iName] = \n                    copula_->inverseCumulativeY(invProbs[iName], iName);\n\n            return copula_->integratedExpectedValue(\n                boost::function<Disposable<std::vector<Real> > (\n                  const std::vector<Real>& v1)>(\n                    boost::bind(\n                        &BinomialLossModel<LLM>::lossProbability,\n                        this,\n                        boost::cref(date), //d,\n                        boost::cref(notionals),\n                        boost::cref(invProbs),\n                        _1)\n                    )\n                );\n        }\n        //! attainable loss points this model provides\n        Disposable<std::vector<Real> > lossPoints(const Date&) const;\n        //! Returns the cumulative full loss distribution\n        Disposable<std::map<Real, Probability> > \n            lossDistribution(const Date& d) const;\n        //! Loss level for this percentile\n        Real percentile(const Date& d, Real percentile) const;\n        Real expectedShortfall(const Date&d, Real percentile) const;\n        Real expectedTrancheLoss(const Date& d) const;\n    protected:\n        // Model internal workings ----------------\n        //! Average loss per credit.\n        Real averageLoss(const Date&, const std::vector<Real>& reminingNots, \n            const std::vector<Real>&) const;\n        Real condTrancheLoss(const Date&, const std::vector<Real>& lossVals, \n            const std::vector<Real>& bsktNots,\n            const std::vector<Probability>& uncondDefProbs, \n            const std::vector<Real>&) const;\n        // expected as in time-value, not average, see literature\n        Disposable<std::vector<Real> >\n            expConditionalLgd(const Date& d,\n                               const std::vector<Real>& mktFactors) const\n        {\n            std::vector<Real> condLgds;\n            const std::vector<Size>& evalDateLives = basket_->liveList();\n            for(Size i=0; i<evalDateLives.size(); i++) \n                condLgds.push_back(1.-copula_->conditionalRecovery(d, \n                    evalDateLives[i], mktFactors));\n            return condLgds;\n        }\n\n        //! Loss probability density conditional on the market factor value.\n        // Heres where the burden of the algorithm setup lies.\n        Disposable<std::vector<Real> > \n            lossProbability(      \n                const Date& date,\n                // expected exposures at the passed date, no wrong way means\n                //  no dependence of the exposure with the mkt factor \n                const std::vector<Real>& bsktNots,\n                const std::vector<Real>& uncondDefProbInv, \n                            const std::vector<Real>&  mktFactor) const;\n    protected:\n        const boost::shared_ptr<LLM> copula_;\n\n        // cached arguments:\n        // remaining basket magnitudes:\n        mutable Real attachAmount_, detachAmount_;\n    };\n\n    //-------------------------------------------------------------------------\n\n    /* The algorithm to compute the prob. of n defaults in the basket is \n        recursive. For this reason theres no sense in returning the prob \n        distribution of a given number of defaults.\n    */\n    template< class LLM>\n    Disposable<std::vector<Real> > BinomialLossModel<LLM>::lossProbability(\n        const Date& date, \n        const std::vector<Real>& bsktNots,\n        const std::vector<Real>& uncondDefProbInv, \n        const std::vector<Real>& mktFactors) const \n    {   // the model as it is does not model the exposures conditional to the \n        //   mkt factr, otherwise this needs revision\n        /// model does not take the unconditional rr\n        Size bsktSize = basket_->remainingSize();\n        /* The conditional loss per unit notional of each name at time 'date'\n            The spot recovery model is returning for all i's:\n            \\frac{\\int_0^t  [1-rr_i(\\tau; \\xi)] P_{def-i}(0, \\tau; \\xi) d\\tau}\n                 {P_{def-i}(0,t;\\xi)}\n            and the constant recovery model is simply returning: \n            1-RR_i\n        */\n        // conditional fractional LGD expected as given by the recovery model \n        //   for the ramaining(live) names at the current eval date.\n        std::vector<Real> fractionalEL = expConditionalLgd(date, mktFactors);\n        std::vector<Real> lgdsLeft;\n        std::transform(fractionalEL.begin(), fractionalEL.end(), \n            bsktNots.begin(), std::back_inserter(lgdsLeft), \n            std::multiplies<Real>());\n        Real avgLgd = \n            std::accumulate(lgdsLeft.begin(), lgdsLeft.end(), Real(0.)) /\n                bsktSize;\n\n        std::vector<Probability> condDefProb(bsktSize, 0.);\n        for(Size j=0; j<bsktSize; j++)//transform\n            condDefProb[j] = \n                copula_->conditionalDefaultProbabilityInvP(uncondDefProbInv[j],\n                    j, mktFactors);\n        // of full portfolio:\n        Real avgProb = avgLgd <= QL_EPSILON ? 0. : // only if all are 0\n                std::inner_product(condDefProb.begin(), \n                    condDefProb.end(), lgdsLeft.begin(), 0.)\n                / (avgLgd * bsktSize);\n        // model parameters:\n        Real m = avgProb * bsktSize;\n        Real floorAveProb = std::min(Real(bsktSize-1), std::floor(Real(m)));\n        Real ceilAveProb = floorAveProb + 1.;\n        // nu_A\n        Real varianceBinom = avgProb * (1. - avgProb)/bsktSize;\n        // nu_E\n        std::vector<Probability> oneMinusDefProb;//: 1.-condDefProb[j]\n        std::transform(condDefProb.begin(), condDefProb.end(), \n            std::back_inserter(oneMinusDefProb), \n            std::bind1st(std::minus<Real>(), 1.));\n\n        //breaks condDefProb and lgdsLeft to spare memory\n        std::transform(condDefProb.begin(), condDefProb.end(), \n            oneMinusDefProb.begin(), condDefProb.begin(), \n            std::multiplies<Real>());\n        std::transform(lgdsLeft.begin(), lgdsLeft.end(), \n            lgdsLeft.begin(), lgdsLeft.begin(), std::multiplies<Real>());\n        Real variance = std::inner_product(condDefProb.begin(), \n            condDefProb.end(), lgdsLeft.begin(), 0.);\n\n        variance = avgLgd <= QL_EPSILON ? 0. : \n            variance / (bsktSize * bsktSize * avgLgd * avgLgd );\n        Real sumAves = -std::pow(ceilAveProb-m, 2) \n            - (std::pow(floorAveProb-m, 2) - std::pow(ceilAveProb,2.)) \n                * (ceilAveProb-m);\n        Real alpha = (variance * bsktSize + sumAves) \n            / (varianceBinom * bsktSize + sumAves);\n        // Full distribution: \n        // ....DO SOMETHING CHEAPER at least go up to the loss tranche limit.\n        std::vector<Probability> lossProbDensity(bsktSize+1, 0.); \n        if(avgProb >= 1.-QL_EPSILON) {\n           lossProbDensity[bsktSize] = 1.;\n        }else if(avgProb <= QL_EPSILON) {\n           lossProbDensity[0] = 1.;\n        }else{\n            /* FIX ME: With high default probabilities one only gets tiny values\n            at the end and the sum of probabilities in the \n            conditional distribution does not add up to one. It might be due to \n            the fact that recursion should be done in the other direction as \n            pointed out in the book. This is numerical.\n            */\n            Probability probsRatio = avgProb/(1.-avgProb);\n            lossProbDensity[0] = std::pow(1.-avgProb, \n                static_cast<Real>(bsktSize));\n            for(Size i=1; i<bsktSize+1; i++) // recursive to avoid factorial\n                lossProbDensity[i] = lossProbDensity[i-1] * probsRatio \n                    * (bsktSize-i+1.)/i;\n            // redistribute probability:\n            for(Size i=0; i<bsktSize+1; i++)\n                lossProbDensity[i] *= alpha;\n            // adjust average\n            Real epsilon = (1.-alpha)*(ceilAveProb-m);\n            Real epsilonPlus = 1.-alpha-epsilon;\n            lossProbDensity[static_cast<Size>(floorAveProb)] += epsilon;\n            lossProbDensity[static_cast<Size>(ceilAveProb)]  += epsilonPlus;\n        }\n        return lossProbDensity;\n    }\n\n    //-------------------------------------------------------------------------\n\n    template< class LLM>\n    Real BinomialLossModel<LLM>::averageLoss(\n        const Date& d, \n        const std::vector<Real>& reminingNots,\n        const std::vector<Real>& mktFctrs) const \n    {\n        Size bsktSize = basket_->remainingSize();\n        /* The conditional loss per unit notional of each name at time 'date'\n            The spot recovery model is returning for all i's:\n            \\frac{\\int_0^t  [1-rr_i(\\tau; \\xi)] P_{def-i}(0, \\tau; \\xi) d\\tau}\n                 {P_{def-i}(0,t;\\xi)}\n            and the constant recovery model is simply returning: \n            1-RR_i\n        */\n        std::vector<Real> fractionalEL = expConditionalLgd(d, mktFctrs);\n        Real notBskt = std::accumulate(reminingNots.begin(), \n            reminingNots.end(), Real(0.));\n        std::vector<Real> lgdsLeft;\n        std::transform(fractionalEL.begin(), fractionalEL.end(), \n            reminingNots.begin(), std::back_inserter(lgdsLeft),\n            boost::lambda::_1 * boost::lambda::_2 / notBskt);\n        return std::accumulate(lgdsLeft.begin(), lgdsLeft.end(), Real(0.)) \n            / bsktSize;\n    }\n\n    template< class LLM>\n    Disposable<std::vector<Real> >\n        BinomialLossModel<LLM>::lossPoints(const Date& d) const \n    {\n        std::vector<Real> notionals = basket_->remainingNotionals(d);\n\n        Real aveLossFrct = copula_->integratedExpectedValue(\n            boost::function<Real (const std::vector<Real>& v1)>(\n                boost::bind(\n                    &BinomialLossModel<LLM>::averageLoss,\n                    this,\n                    boost::cref(d),\n                    boost::cref(notionals),\n                    _1)\n                )\n            );\n\n        std::vector<Real> data;\n        Size dataSize = basket_->remainingSize() + 1;\n        data.reserve(dataSize);\n        // use std::algorithm\n        Real outsNot = basket_->remainingNotional(d);\n        for(Size i=0; i<dataSize; i++)\n            data.push_back(i * aveLossFrct * outsNot);\n        return data;\n    }\n\n    template< class LLM>\n    Real BinomialLossModel<LLM>::condTrancheLoss(\n        const Date& d, \n        const std::vector<Real>& lossVals, \n        const std::vector<Real>& bsktNots,\n        const std::vector<Real>& uncondDefProbsInv,\n        const std::vector<Real>& mkf) const {\n\n        std::vector<Real> condLProb = \n            lossProbability(d, bsktNots, uncondDefProbsInv, mkf);\n        // \\to do: move to a do-while over attach to detach\n        Real suma = 0.;\n        for(Size i=0; i<lossVals.size(); i++) { \n            suma += condLProb[i] * \n                std::min(std::max(lossVals[i]\n                 - attachAmount_, 0.), detachAmount_ - attachAmount_);\n        }\n        return suma;\n    }\n\n    template< class LLM>\n    Real BinomialLossModel<LLM>::expectedTrancheLoss(const Date& d) const {\n        std::vector<Real> lossVals  = lossPoints(d);\n        std::vector<Real> notionals = basket_->remainingNotionals(d);\n        std::vector<Probability> invProbs = \n            basket_->remainingProbabilities(d);\n        for(Size iName=0; iName<invProbs.size(); iName++)\n            invProbs[iName] = \n                copula_->inverseCumulativeY(invProbs[iName], iName);\n            \n        return copula_->integratedExpectedValue(\n            boost::function<Real (const std::vector<Real>& v1)>(\n                boost::bind(&BinomialLossModel<LLM>::condTrancheLoss,\n                            this,\n                            boost::cref(d), \n                            boost::cref(lossVals), \n                            boost::cref(notionals), \n                            boost::cref(invProbs), \n                            _1))\n            );\n    }\n\n\n    template< class LLM>\n    Disposable<std::map<Real, Probability> > \n        BinomialLossModel<LLM>::lossDistribution(const Date& d) const \n    {\n        std::map<Real, Probability> distrib;\n        std::vector<Real> lossPts = lossPoints(d);\n        std::vector<Real> values  = expectedDistribution(d);\n        Real sum = 0.;\n        for(Size i=0; i<lossPts.size(); i++) {\n            distrib.insert(std::make_pair(lossPts[i], \n                //capped, some situations giving a very small probability over 1\n                std::min(sum+values[i],1.)\n                ));\n            sum+= values[i];\n        }\n        return distrib;\n    }\n\n    template< class LLM>\n    Real BinomialLossModel<LLM>::percentile(const Date& d, Real perc) const {\n        std::map<Real, Probability> dist = lossDistribution(d);\n        // \\todo: Use some of the library interpolators instead\n        if(// included in test below-> (dist.begin()->second >=1.) ||\n            (dist.begin()->second >= perc))return dist.begin()->first;\n\n        // deterministic case (e.g. date requested is todays date)\n        if(dist.size() == 1) return dist.begin()->first;\n\n        if(perc == 1.) return dist.rbegin()->first;\n        if(perc == 0.) return dist.begin()->first;\n        std::map<Real, Probability>::const_iterator itdist = dist.begin();\n        while(itdist->second <= perc) itdist++;\n        Real valPlus = itdist->second;\n        Real xPlus   = itdist->first;\n        itdist--;//we r never 1st or last, because of tests above\n        Real valMin  = itdist->second;\n        Real xMin    = itdist->first;\n\n        Real portfLoss = xPlus-(xPlus-xMin)*(valPlus-perc)/(valPlus-valMin);\n\n        return \n            std::min(std::max(portfLoss - attachAmount_, 0.), \n                detachAmount_ - attachAmount_);\n    }\n\n    template< class LLM>\n    Real BinomialLossModel<LLM>::expectedShortfall(const Date&d, \n        Real perctl) const \n    {\n        //taken from recursive since we have the distribution in both cases.\n        if(d == Settings::instance().evaluationDate()) return 0.;\n            std::map<Real, Probability> distrib = lossDistribution(d);\n\n            std::map<Real, Probability>::iterator \n                itNxt, itDist = distrib.begin();\n            for(; itDist != distrib.end(); itDist++) \n                if(itDist->second >= perctl) break;\n            itNxt = itDist; itDist--;\n\n            // \\todo: I could linearly triangulate the exact point and get \n            //    extra precission on the first(broken) period.\n            if(itNxt != distrib.end()) { \n                Real lossNxt = std::min(std::max(itNxt->first - attachAmount_, \n                    0.), detachAmount_ - attachAmount_);\n                Real lossHere = std::min(std::max(itDist->first - attachAmount_,\n                    0.), detachAmount_ - attachAmount_);\n\n                Real val =  lossNxt - (itNxt->second - perctl) * \n                    (lossNxt - lossHere) / (itNxt->second - itDist->second); \n                Real suma = (itNxt->second - perctl) * (lossNxt + val) * .5;\n                itDist++;itNxt++;\n                do{\n                    lossNxt = std::min(std::max(itNxt->first - attachAmount_, \n                        0.), detachAmount_ - attachAmount_);\n                    lossHere = std::min(std::max(itDist->first - attachAmount_, \n                        0.), detachAmount_ - attachAmount_);\n                    suma += .5 * (lossHere + lossNxt) \n                        * (itNxt->second - itDist->second);\n                    itDist++;itNxt++;\n                }while(itNxt != distrib.end());\n                return suma / (1.-perctl);\n            }\n            QL_FAIL(\"Binomial model fails to calculate ESF.\");\n    }\n\n    // The standard use:\n    typedef BinomialLossModel<GaussianConstantLossLM> GaussianBinomialLossModel;\n    typedef BinomialLossModel<TConstantLossLM> TBinomialLossModel;\n\n}\n\n#endif\n", "meta": {"hexsha": "43e70395595b2ce3bf07873ca675d53b4922869e", "size": 19659, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/experimental/credit/binomiallossmodel.hpp", "max_stars_repo_name": "amaggiulli/QuantLib", "max_stars_repo_head_hexsha": "224a0e6af360cfcc13a63ca28bc182f8022c3507", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-09-13T22:40:22.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-18T12:51:41.000Z", "max_issues_repo_path": "ql/experimental/credit/binomiallossmodel.hpp", "max_issues_repo_name": "amaggiulli/QuantLib", "max_issues_repo_head_hexsha": "224a0e6af360cfcc13a63ca28bc182f8022c3507", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/credit/binomiallossmodel.hpp", "max_forks_repo_name": "amaggiulli/QuantLib", "max_forks_repo_head_hexsha": "224a0e6af360cfcc13a63ca28bc182f8022c3507", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-06-27T19:25:30.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-27T19:25:30.000Z", "avg_line_length": 43.9798657718, "max_line_length": 80, "alphanum_fraction": 0.5861946182, "num_tokens": 4676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.46665507592390815}}
{"text": "#pragma once\r\n#include <numbers>\r\n#include <cmath>\r\n#include <Eigen/Dense>\r\n#include \"Material.hpp\"\r\n#include \"../../utils/random.hpp\"\r\n\r\nclass MaterialDiffuse : public Material\r\n{\r\npublic:\r\n\tMaterialDiffuse(Eigen::Vector3f k_d) : Material(MaterialType::Diffuse), k_d(k_d) {};\r\n\r\n    Eigen::Vector3f calc_brdf(Eigen::Vector3f normal, Eigen::Vector3f in, Eigen::Vector3f out) const override\r\n    {\r\n        // calculate the contribution of diffuse model\r\n        auto cosalpha = normal.dot(out);\r\n        if (cosalpha <= 0.0f)\r\n            return { 0.0f, 0.0f, 0.0f };\r\n\r\n        auto diffuse = k_d / std::numbers::pi;\r\n        return diffuse;\r\n    };\r\n\r\n    Eigen::Vector3f sample(Eigen::Vector3f normal, Eigen::Vector3f in) const override \r\n    {\r\n        // uniform sample on the hemisphere\r\n        auto x_1 = get_random_float();\r\n        auto x_2 = get_random_float();\r\n        auto z = std::abs(1.0f - 2.0f * x_1);\r\n        auto r = std::sqrt(1.0f - z * z);\r\n        auto phi = static_cast<float>(2 * std::numbers::pi_v<float> * x_2);\r\n        Eigen::Vector3f local{ r * std::cos(phi), r * std::sin(phi), z };\r\n        return to_world(local, normal);\r\n    };\r\n\r\n    Eigen::Vector3f at(double u, double v) const override { return k_d; };\r\n\r\nprotected:\r\n    Eigen::Vector3f k_d;\r\n\r\n    Eigen::Vector3f to_world(const Eigen::Vector3f& a, const Eigen::Vector3f& N) const {\r\n        Eigen::Vector3f C;\r\n        if (std::abs(N.x()) > std::abs(N.y()))\r\n        {\r\n            auto lenInv = 1.0f / std::sqrt(N.x() * N.x() + N.z() * N.z());\r\n            C = Eigen::Vector3f(N.z() * lenInv, 0.0f, -N.x() * lenInv);\r\n        }\r\n        else\r\n        {\r\n            auto lenInv = 1.0f / std::sqrt(N.y() * N.y() + N.z() * N.z());\r\n            C = Eigen::Vector3f(0.0f, N.z() * lenInv, -N.y() * lenInv);\r\n        }\r\n        auto B = C.cross(N);\r\n        return a.x() * B + a.y() * C + a.z() * N;\r\n    }\r\n};\r\n", "meta": {"hexsha": "acf1a7f5c2559040b655db0678c716a5fdaaef48", "size": 1899, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/render/material/MaterialDiffuse.hpp", "max_stars_repo_name": "yzx9/NeuronSdfViewer", "max_stars_repo_head_hexsha": "454164dfccf80b806aac3cd7cca09e2cb8bd3c2a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-31T10:29:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-31T10:29:56.000Z", "max_issues_repo_path": "src/render/material/MaterialDiffuse.hpp", "max_issues_repo_name": "yzx9/NeuronSdfViewer", "max_issues_repo_head_hexsha": "454164dfccf80b806aac3cd7cca09e2cb8bd3c2a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/render/material/MaterialDiffuse.hpp", "max_forks_repo_name": "yzx9/NeuronSdfViewer", "max_forks_repo_head_hexsha": "454164dfccf80b806aac3cd7cca09e2cb8bd3c2a", "max_forks_repo_licenses": ["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.3157894737, "max_line_length": 110, "alphanum_fraction": 0.5381779884, "num_tokens": 567, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672043084051, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.46665506524676026}}
{"text": "\n#include \"CandyTransform/Transform.h\"\n#include <iostream>\n#include <string>\n#include <boost/lexical_cast.hpp>\n\n/*\n        Given a prime, what is it's factorization\n */\nnamespace {\n        using namespace CandyTransform;\n\n\n        struct Factorization{\n                friend std::ostream& operator<<(std::ostream& ostr,         Factorization const& self){\n                        typedef std::vector<size_t>::const_iterator CI0;\n                        const char* comma = \"\";\n                        ostr << \"numbers\" << \" = {\";\n                        for(CI0 iter= self.numbers.begin(), end=self.numbers.end();iter!=end;++iter){\n                                ostr << comma << *iter;\n                                comma = \", \";\n                        }\n                        ostr << \"}\";\n                        typedef std::vector<std::string>::const_iterator CI1;\n                        comma = \"\";\n                        ostr << \"tokens\" << \" = {\";\n                        for(CI1 iter= self.tokens.begin(), end=self.tokens.end();iter!=end;++iter){\n                                ostr << comma << *iter;\n                                comma = \", \";\n                        }\n                        ostr << \"}\";\n                        ostr << \", target = \" << self.target;\n                        return ostr;\n                }\n                std::vector<size_t> numbers;\n                std::vector<std::string> tokens;\n                size_t target;\n        };\n\n        struct Operator{\n                virtual ~Operator()=default;\n                virtual void Emit(std::function<void(Factorization const&)> continuation, Factorization const& value)const=0;\n        };\n        enum OperatorArity{\n                AR_Unary,\n                AR_CommutativeBinary,\n                AR_NonCommutativeBinary,\n        };\n        struct NonTerminalOperator : Operator{\n                explicit NonTerminalOperator(OperatorArity arity)\n                        :arity_(arity)\n                {}\n                virtual void Emit(std::function<void(Factorization const&)> continuation, Factorization const& value)const{\n                        std::vector<size_t> p(value.numbers.size());\n                        switch(arity_){\n                                case AR_Unary:\n                                {\n                                        std::vector<size_t> v(1);\n                                        for(size_t idx=0;idx!=value.numbers.size();++idx){\n                                                v[0] = idx;\n                                                EmitPerm(continuation, value, v);\n                                        }\n                                        break;\n                                }\n                                case AR_CommutativeBinary:\n                                case AR_NonCommutativeBinary:\n                                {\n                                        std::vector<size_t> p(value.numbers.size());\n                                        p[0] = 1;\n                                        p[1] = 1;\n                                        std::sort(p.begin(), p.end());\n                                        std::vector<size_t> v(2);\n                                        do{\n                                                size_t* out = &v[0];\n                                                for(size_t idx=0;idx!=value.numbers.size();++idx){\n                                                        if( p[idx] ){\n                                                                *out = idx;\n                                                                ++out;\n                                                                continue;\n                                                        }\n                                                }\n\n                                                EmitPerm(continuation, value, v);\n                                                if( arity_ == AR_NonCommutativeBinary ){\n                                                        std::swap(v[0], v[1]);\n                                                        EmitPerm(continuation, value, v);\n                                                }\n                                        }while(std::next_permutation(p.begin(), p.end()));\n\n                                        break;\n                                }\n                        }\n                }\n                virtual void EmitPerm(std::function<void(Factorization const&)> continuation, Factorization const& value, std::vector<size_t> const perm)const=0;\n        protected:\n                static Factorization CopyExPerm(Factorization const& value, std::vector<size_t> const perm){\n                        Factorization result;\n                        result.target = value.target;\n                        for(size_t idx=0;idx!=value.numbers.size();++idx){\n                                if( perm[0] == idx || perm[1] == idx )\n                                        continue;\n                                result.numbers.push_back(value.numbers[idx]);\n                                result.tokens.push_back(value.tokens[idx]);\n                        }\n                        return result;\n                }\n        private:\n                OperatorArity arity_;\n        };\n\n        struct AddOperator : NonTerminalOperator{\n                AddOperator():NonTerminalOperator(AR_CommutativeBinary){}\n                virtual void EmitPerm(std::function<void(Factorization const&)> continuation, Factorization const& value, std::vector<size_t> const perm)const{\n                        auto next = CopyExPerm(value, perm);\n                        auto a = value.numbers[perm[0]];\n                        auto a_s = value.tokens[perm[0]];\n                        auto b = value.numbers[perm[1]];\n                        auto b_s = value.tokens[perm[1]];\n                        next.numbers.push_back( a + b);\n                        next.tokens.push_back( \"(\" + a_s + \"+\" + b_s + \")\");\n                        continuation(next);\n                }\n        };\n        struct MulOperator : NonTerminalOperator{\n                MulOperator():NonTerminalOperator(AR_CommutativeBinary){}\n                virtual void EmitPerm(std::function<void(Factorization const&)> continuation, Factorization const& value, std::vector<size_t> const perm)const{\n                        auto next = CopyExPerm(value, perm);\n                        auto a = value.numbers[perm[0]];\n                        auto a_s = value.tokens[perm[0]];\n                        auto b = value.numbers[perm[1]];\n                        auto b_s = value.tokens[perm[1]];\n                        next.numbers.push_back( a * b);\n                        next.tokens.push_back( \"(\"+ a_s + \"*\" + b_s + \")\");\n                        continuation(next);\n                }\n        };\n\n\n        struct F : Transform<Factorization, Factorization>{\n                std::vector<std::shared_ptr<Operator> > ops_;\n                F(){\n                        ops_.push_back(std::make_shared<AddOperator>());\n                        ops_.push_back(std::make_shared<MulOperator>());\n                }\n                virtual void Apply(TransformControl* ctrl, ParamType in)override{\n\n                        if( in.numbers.size() == 1){\n                                if(in.numbers.back() == in.target ){\n                                        std::cout << \"in.numbers.back() => \" << in.numbers.back() << \"\\n\"; // __CandyPrint__(cxx-print-scalar,in.numbers.back())\n                                        ctrl->Return(in.tokens.back());\n                                }\n                                return;\n                        }\n\n                        for(auto op : ops_ ){\n                                op->Emit( [&](auto&& f){ ctrl->Emit(f); }, in);\n                        }\n                        \n\n                        ctrl->DeclPath()->Next(std::make_shared<F>());\n                }\n        };\n} // end namespace anon\n\nint main(){\n\n        TransformContext ctx;\n\n        auto path = ctx.Start();\n        path->Next(std::make_shared<F>());\n\n        Factorization init;\n        \n        /*\n         \n           2 + 4 = 6\n\n         */\n        #if 0\n        init.numbers = std::vector<size_t>{2,4};\n        init.target = 6;\n        #endif\n\n\n\n        /*\n         \n          ( 2 * (3 + 4) ) * 5 = 70\n\n         */\n        #if 1\n        init.numbers = std::vector<size_t>{3,4,2,5};\n        init.target = 70;\n        #endif\n        \n        \n        /*\n         \n          ( ( 19*97 % 2 ) * (3 + 4) ) * 5 = 35\n\n         */\n        #if 0\n        init.numbers = std::vector<size_t>{3,4,19,5,2};\n        init.target = 35;\n        #endif\n        for(auto _ : init.numbers ){\n                init.tokens.push_back(boost::lexical_cast<std::string>(_));\n        }\n\n        for(auto const& result : ctx.Execute<std::string>(init) ){\n                std::cout << \"result => \" << result << \"\\n\"; // __CandyPrint__(cxx-print-scalar,result)\n        }\n}\n", "meta": {"hexsha": "d7213c3fcafacc15bf94a6193f4b89e73bc00a91", "size": 9052, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example2.cpp", "max_stars_repo_name": "sweeterthancandy/CandyTransform", "max_stars_repo_head_hexsha": "81a9b95e85754f7d8370021a29e9b8193d10a28d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example2.cpp", "max_issues_repo_name": "sweeterthancandy/CandyTransform", "max_issues_repo_head_hexsha": "81a9b95e85754f7d8370021a29e9b8193d10a28d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example2.cpp", "max_forks_repo_name": "sweeterthancandy/CandyTransform", "max_forks_repo_head_hexsha": "81a9b95e85754f7d8370021a29e9b8193d10a28d", "max_forks_repo_licenses": ["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.2990654206, "max_line_length": 161, "alphanum_fraction": 0.3817940787, "num_tokens": 1592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.808067204308405, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.4666550652467602}}
{"text": "#include <iostream>\n#include <boost/numeric/mtl/mtl.hpp>\n\nint main(int , char**)\n{\n    using namespace mtl;\n    typedef mtl::vec::parameters<tag::col_major, mtl::vec::fixed::dimension<2> > fvec_para;\n    typedef mat::parameters<tag::row_major, mtl::index::c_index, mtl::fixed::dimensions<2, 2> > fmat_para;\n\n    dense2D<float, fmat_para>        A, B; // dimension not needed here\n    dense_vector<float, fvec_para>   v, w; // here neither\n\n    A= 2., 3.,\n       4., 5.;\n    v= 3., 4.;\n\n    w= A * v; // Same syntax as dynamic size\n    B= A * A; \n\n    std::cout << \"A * v is \" << w << \"\\n\\n\";\n    std::cout << \"A * A is\\n\" << B;\n\n    return 0;\n}\n", "meta": {"hexsha": "8d9bb5c3e267cf698c31898a2c9a252de0c1fc25", "size": 645, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/examples/fixed_size_example.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/fixed_size_example.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/fixed_size_example.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": 25.8, "max_line_length": 106, "alphanum_fraction": 0.5736434109, "num_tokens": 221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080671950640465, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4666550599081861}}
{"text": "#include <boost/random/weibull_distribution.hpp>\n", "meta": {"hexsha": "4adbfbb45948e22ae7e0e69b1e66e6b50cb6fe72", "size": 49, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_random_weibull_distribution.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_random_weibull_distribution.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_random_weibull_distribution.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 24.5, "max_line_length": 48, "alphanum_fraction": 0.8367346939, "num_tokens": 10, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.466526328331623}}
{"text": "#include \"../../def_submodule.hpp\"\r\n\r\n#include \"../../../../../type/math/coord.hpp\"\r\n#include \"../../../../../type/math/matrix.hpp\"\r\n#include \"../../../../../type/math/affine.hpp\"\r\n\r\n#include <boost/python.hpp>\r\n\r\ntypedef GS_DDMRM::S_IceRay::S_type::GT_size                GTs_size;\r\ntypedef GS_DDMRM::S_IceRay::S_type::GT_scalar              GTs_scalar;\r\ntypedef GS_DDMRM::S_IceRay::S_type::S_coord::GT_scalar3D   GTs_coord3D;\r\ntypedef GS_DDMRM::S_IceRay::S_type::S_matrix::GT_scalar3D  GTs_matrix3D;\r\ntypedef GS_DDMRM::S_IceRay::S_type::S_affine::GT_scalar3D  GTs_affine3D;\r\n\r\nnamespace{\r\n\r\nGTs_scalar const& GFs_get( GTs_affine3D & P_affine, GTs_size P_row, GTs_size const& P_column )\r\n {\r\n  return P_affine.matrix()[ P_row ][ P_column ];\r\n }\r\n\r\nGTs_affine3D & GFs_set( GTs_affine3D & P_affine, GTs_size P_row, GTs_size const& P_column, GTs_scalar const& P_value )\r\n {\r\n  P_affine.matrix()[ P_row ][ P_column ] = P_value;\r\n   return P_affine;\r\n }\r\n\r\nGTs_coord3D GFs_rowGet( GTs_affine3D & P_affine, GTs_size P_row  )\r\n {\r\n  GTs_coord3D Ir_row;\r\n  Ir_row[0] = P_affine.matrix()[ P_row][ 0 ];\r\n  Ir_row[1] = P_affine.matrix()[ P_row][ 1 ];\r\n  Ir_row[2] = P_affine.matrix()[ P_row][ 2 ];\r\n\r\n  return Ir_row;\r\n }\r\n\r\nGTs_affine3D & GFs_rowSet( GTs_affine3D & P_affine, GTs_size P_row, GTs_coord3D const& P_value )\r\n {\r\n  P_affine.matrix()[ P_row][ 0 ] = P_value[0];\r\n  P_affine.matrix()[ P_row][ 1 ] = P_value[1];\r\n  P_affine.matrix()[ P_row][ 2 ] = P_value[2];\r\n  return P_affine;\r\n }\r\n\r\nGTs_coord3D GFs_columnGet( GTs_affine3D & P_affine, GTs_size P_column  )\r\n {\r\n  GTs_coord3D Ir_column;\r\n\r\n  Ir_column[0] = P_affine.matrix()[ 0 ][ P_column ];\r\n  Ir_column[1] = P_affine.matrix()[ 1 ][ P_column ];\r\n  Ir_column[2] = P_affine.matrix()[ 2 ][ P_column ];\r\n  return Ir_column;\r\n }\r\n\r\nGTs_affine3D &  GFs_columnSet( GTs_affine3D & P_affine, GTs_size P_column, GTs_coord3D const& P_value )\r\n {\r\n  P_affine.matrix()[ 0 ][ P_column ] = P_value[0];\r\n  P_affine.matrix()[ 1 ][ P_column ] = P_value[1];\r\n  P_affine.matrix()[ 2 ][ P_column ] = P_value[2];\r\n  return P_affine;\r\n }\r\n\r\nGTs_affine3D &  GFs_scale1( GTs_affine3D & P_affine, GTs_scalar const& P_value )\r\n {\r\n  P_affine.matrix()[ 0 ][ 0 ] *= P_value;\r\n  P_affine.matrix()[ 1 ][ 1 ] *= P_value;\r\n  P_affine.matrix()[ 2 ][ 2 ] *= P_value;\r\n  return P_affine;\r\n }\r\n\r\nGTs_affine3D &  GFs_scale3( GTs_affine3D & P_affine, GTs_coord3D const& P_value )\r\n {\r\n  P_affine.matrix()[ 0 ][ 0 ] *= P_value[0];\r\n  P_affine.matrix()[ 1 ][ 1 ] *= P_value[1];\r\n  P_affine.matrix()[ 2 ][ 2 ] *= P_value[2];\r\n  return P_affine;\r\n }\r\n\r\nGTs_affine3D &  GFs_load( GTs_affine3D & P_affine, GTs_coord3D const& P_x, GTs_coord3D const& P_y, GTs_coord3D const& P_z, GTs_coord3D const& P_move )\r\n {\r\n  ::math::linear::affine::system( P_affine, P_move, P_x, P_y, P_z );\r\n\r\n  return P_affine;\r\n }\r\n\r\n GTs_affine3D\r\n GFs_lookAt\r\n  (\r\n    GTs_coord3D const& P_eye\r\n   ,GTs_coord3D const& P_view\r\n   ,GTs_coord3D const& P_up\r\n  )\r\n  {\r\n   GTs_affine3D Ir_world;\r\n   ::math::linear::affine::look_at( Ir_world, P_eye, P_view, P_up );\r\n\r\n   return Ir_world;\r\n  }\r\n\r\n}\r\n\r\nvoid expose_math_type_affine()\r\n {\r\n  //MAKE_SUBMODULE( IceRay );\r\n  MAKE_SUBMODULE( library   );\r\n  MAKE_SUBMODULE( math   );\r\n\r\n  typedef  GTs_coord3D const& (GTs_affine3D::*Tf_getCoord3D )(void) const;\r\n  Tf_getCoord3D I_getCoord3D = &GTs_affine3D::vector;\r\n\r\n  //typedef  GTs_affine3D     & (GTs_affine3D::*Tf_setCoord3D )( GTs_coord3D const&);\r\n  //Tf_setCoord3D I_setCoord3D = &GTs_affine3D::vector;\r\n\r\n  typedef  GTs_matrix3D const& (GTs_affine3D::*Tf_getMatrix3D )(void) const;\r\n  Tf_getMatrix3D I_getMatrix3D = &GTs_affine3D::matrix;\r\n\r\n  //typedef  GTs_affine3D     & (GTs_affine3D::*Tf_setMatrix3D )( GTs_matrix3D const&);\r\n  //Tf_setMatrix3D I_setMatrix3D = &GTs_affine3D::matrix;\r\n\r\n  boost::python::class_<GTs_affine3D>( \"MathTypeAffine3D\" )\r\n/*    .def( boost::python::init<>() )\r\n    .def( boost::python::init< GTs_coord3D >() )\r\n    .def( boost::python::init< GTs_matrix3D >() )\r\n    .def( boost::python::init< GTs_matrix3D, GTs_coord3D >() )\r\n    .def( \"load\",     &GFs_load, boost::python::return_value_policy<boost::python::reference_existing_object>()  )\r\n    .def( \"coord\",    I_getCoord3D,  boost::python::return_value_policy<boost::python::copy_const_reference>() )\r\n    //.def( \"coord\",    I_setCoord3D,  boost::python::return_value_policy<boost::python::reference_existing_object>() )\r\n    .def( \"matrix\",   I_getMatrix3D, boost::python::return_value_policy<boost::python::copy_const_reference>() )\r\n    //.def( \"matrix\",   I_setMatrix3D, boost::python::return_value_policy<boost::python::reference_existing_object>() )\r\n\r\n    .def( \"element\", &GFs_get,       boost::python::return_value_policy<boost::python::copy_const_reference>()  )\r\n    .def( \"element\", &GFs_set,       boost::python::return_value_policy<boost::python::reference_existing_object>()  )\r\n    .def( \"row\",     &GFs_rowGet    )\r\n    .def( \"row\",     &GFs_rowSet,    boost::python::return_value_policy<boost::python::reference_existing_object>()  )\r\n    .def( \"column\",  &GFs_columnGet )\r\n    .def( \"column\",  &GFs_columnSet, boost::python::return_value_policy<boost::python::reference_existing_object>()  )\r\n\r\n    .def( \"scale\",  &GFs_scale1, boost::python::return_value_policy<boost::python::reference_existing_object>()  )\r\n    .def( \"scale\",  &GFs_scale3, boost::python::return_value_policy<boost::python::reference_existing_object>()  )\r\n    //.def( \"move\" )\r\n    //.def( \"rotate_x\" )\r\n    //.def( \"rotate_y\" )\r\n    //.def( \"rotate_z\" )\r\n    //.def( \"rotate_axis\" )\r\n    //.def( \"load\",   <GTs_matrix3D, GTs_coord3D > )\r\n\r\n    //.def( boost::python::self + boost::python::self )\r\n    //.def( boost::python::self - boost::python::self )\r\n    //.def( boost::python::self * GTs_scalar3D::T_value() )\r\n    //.def( GTs_scalar3D::T_value() * boost::python::self  )\r\n    //.def( boost::python::self / GTs_scalar3D::T_value() )\r\n    //.def( boost::python::self += boost::python::self )\r\n    //.def( boost::python::self -= boost::python::self )\r\n*/\r\n  ;\r\n\r\n    boost::python::def(\"MathAffine3D_lookAt\",    GFs_lookAt );\r\n\r\n }\r\n", "meta": {"hexsha": "0e0c5d361dc837868e6030953b2abaf432ef45e1", "size": 6100, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/IceRay/main/interface/python/library/math/affine.cpp", "max_stars_repo_name": "dmilos/IceRay", "max_stars_repo_head_hexsha": "4e01f141363c0d126d3c700c1f5f892967e3d520", "max_stars_repo_licenses": ["MIT-0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-09-04T12:27:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-17T14:49:40.000Z", "max_issues_repo_path": "src/IceRay/main/interface/python/library/math/affine.cpp", "max_issues_repo_name": "dmilos/IceRay", "max_issues_repo_head_hexsha": "4e01f141363c0d126d3c700c1f5f892967e3d520", "max_issues_repo_licenses": ["MIT-0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/IceRay/main/interface/python/library/math/affine.cpp", "max_forks_repo_name": "dmilos/IceRay", "max_forks_repo_head_hexsha": "4e01f141363c0d126d3c700c1f5f892967e3d520", "max_forks_repo_licenses": ["MIT-0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-09-04T12:27:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-04T12:27:52.000Z", "avg_line_length": 37.8881987578, "max_line_length": 151, "alphanum_fraction": 0.6559016393, "num_tokens": 1996, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.466526328331623}}
{"text": "#include <iostream>\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/count.hpp>\n#include <boost/accumulators/statistics/mean.hpp>\n\nusing namespace boost::accumulators;\nconst int N = 5;\nconst int M = 2;\n\nint main()\n{\n  accumulator_set<int, features<tag::count, tag::mean>> acc;\n\n  for (int i = 0; i < N; i++) {\n    acc(i);\n  }\n\n  return count(acc) == N && mean(acc) == M ? 0 : -1;\n}\n", "meta": {"hexsha": "2b7bce30213448bd3404bdd5587dc590f1437b27", "size": 420, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/accumulators_test.cc", "max_stars_repo_name": "cirrostratus1/rules_boost", "max_stars_repo_head_hexsha": "8a084196b14a396b6d4ff7c928ffbb6621f0d32c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 214.0, "max_stars_repo_stars_event_min_datetime": "2016-08-24T01:08:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T02:24:55.000Z", "max_issues_repo_path": "test/accumulators_test.cc", "max_issues_repo_name": "cirrostratus1/rules_boost", "max_issues_repo_head_hexsha": "8a084196b14a396b6d4ff7c928ffbb6621f0d32c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 184.0, "max_issues_repo_issues_event_min_datetime": "2017-01-20T22:43:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T16:26:45.000Z", "max_forks_repo_path": "test/accumulators_test.cc", "max_forks_repo_name": "cirrostratus1/rules_boost", "max_forks_repo_head_hexsha": "8a084196b14a396b6d4ff7c928ffbb6621f0d32c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 258.0, "max_forks_repo_forks_event_min_datetime": "2016-08-24T01:08:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T18:07:16.000Z", "avg_line_length": 21.0, "max_line_length": 60, "alphanum_fraction": 0.6642857143, "num_tokens": 122, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.46652632833162294}}
{"text": "//=============================================================================\n//\n//  CLASS NConstraintInterfaceAD\n//\n//=============================================================================\n\n#ifndef COMISO_NCONSTRAINTINTERFACEAD_HH\n#define COMISO_NCONSTRAINTINTERFACEAD_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 <boost/shared_array.hpp>\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#include \"NProblemInterfaceAD.hpp\"\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 NProblemInterfaceAD NProblemInterfaceAD.hpp\n\n    The problem interface using automatic differentiation.\n */\nclass COMISODLLEXPORT NConstraintInterfaceAD : 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    NConstraintInterfaceAD(NProblemInterfaceAD& _problem, int _n_unknowns,\n                           const ConstraintType _type = NC_EQUAL, double _eps = 1e-6) :\n        NConstraintInterface(_type, _eps),\n        problem_(_problem),\n        n_unknowns_(_n_unknowns),\n        type_(_type),\n        function_evaluated_(false),\n        use_tape_(true),\n        constant_hessian_evaluated_(false),\n        tape_(static_cast<short int>(TapeIDSingleton::Instance()->requestId())) {\n\n        for(size_t i = 0; i < 11; ++i) tape_stats_[i] = 0;\n    }\n\n    /// Destructor\n    virtual ~NConstraintInterfaceAD() {\n        TapeIDSingleton::Instance()->releaseId(static_cast<size_t>(tape_));\n    }\n\n    /**\n     * \\brief Only override this function\n     */\n    virtual adouble evaluate(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(!function_evaluated_ || !use_tape_) {\n\n            adouble y_d = 0.0;\n\n            boost::shared_array<adouble> x_d_ptr = problem_.x_d_ptr();\n\n            trace_on(tape_); // Start taping\n\n            // Fill data vector\n            for(int i = 0; i < n_unknowns_; ++i) {\n                x_d_ptr[i] <<= _x[i];\n            }\n\n            // Call virtual function to compute\n            // functional value\n            y_d = evaluate(x_d_ptr.get());\n\n            y_d >>= y;\n\n            trace_off();\n\n#ifdef ADOLC_STATS\n            tapestats(tape_, tape_stats_);\n            std::cout << \"Status values for tape \" << tape_ << std::endl;\n            std::cout << \"===============================================\" << std::endl;\n            std::cout << \"Number of independent variables:\\t\" << tape_stats_[0] << std::endl;\n            std::cout << \"Number of dependent variables:\\t\\t\" << tape_stats_[1] << std::endl;\n            std::cout << \"Max. number of live active variables:\\t\" << tape_stats_[2] << std::endl;\n            std::cout << \"Size of value stack:\\t\\t\\t\" << tape_stats_[3] << std::endl;\n            std::cout << \"Buffer size:\\t\\t\\t\\t\" << tape_stats_[4] << std::endl;\n            std::cout << \"Total number of operations recorded:\\t\" << tape_stats_[5] << std::endl;\n            std::cout << \"Other stats [6]:\\t\\t\\t\" << tape_stats_[6] << std::endl;\n            std::cout << \"Other stats [7]:\\t\\t\\t\" << tape_stats_[7] << std::endl;\n            std::cout << \"Other stats [8]:\\t\\t\\t\" << tape_stats_[8] << std::endl;\n            std::cout << \"Other stats [9]:\\t\\t\\t\" << tape_stats_[9] << std::endl;\n            std::cout << \"Other stats [10]:\\t\\t\\t\" << tape_stats_[10] << std::endl;\n            std::cout << \"===============================================\" << std::endl;\n#endif\n\n            function_evaluated_ = true;\n\n        } else {\n\n            double ay[1] = {0.0};\n\n            int ec = function(tape_, 1, n_unknowns_, const_cast<double*>(_x), ay);\n\n#ifdef ADOLC_RET_CODES\n            std::cout << \"Info: function() returned code \" << ec << std::endl;\n#endif\n\n            y = ay[0];\n        }\n\n        return y;\n    }\n\n    virtual void eval_gradient(const double* _x, SVectorNC& _g) {\n\n        if(!function_evaluated_ || !use_tape_) {\n            // Evaluate original functional\n            eval_constraint(_x);\n        }\n\n        boost::shared_array<double> grad_p = problem_.grad_ptr();\n\n        _g.resize(n_unknowns_);\n        _g.setZero();\n\n        int ec = gradient(tape_, n_unknowns_, _x, grad_p.get());\n\n        if(ec < 0) {\n            // Retape function if return code indicates discontinuity\n            function_evaluated_ = false;\n#ifdef ADOLC_RET_CODES\n            std::cout << __FUNCTION__ << \" invokes retaping of function due to discontinuity! Return code: \" << ec << std::endl;\n#endif\n            eval_constraint(_x);\n            ec = gradient(tape_, n_unknowns_, _x, grad_p.get());\n        }\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\n    virtual void eval_hessian(const double* _x, SMatrixNC& _H) {\n\n        _H.resize(n_unknowns_, n_unknowns_);\n\n        if(constant_hessian() && constant_hessian_evaluated_) {\n            _H = constant_hessian_;\n            return;\n        }\n\n        if(!function_evaluated_ || !use_tape_) {\n            // Evaluate original functional\n            eval_constraint(_x);\n        }\n\n        if(sparse_hessian()) {\n\n            int nz = 0;\n            int opt[2] = {0, 0};\n\n            unsigned int* r_ind = NULL;\n            unsigned int* c_ind = NULL;\n            double* val = NULL;\n\n            int ec = sparse_hess(tape_, n_unknowns_, 0, _x, &nz, &r_ind, &c_ind, &val, opt);\n            if(ec < 0) {\n                // Retape function if return code indicates discontinuity\n                function_evaluated_ = false;\n#ifdef ADOLC_RET_CODES\n                std::cout << __FUNCTION__ << \" invokes retaping of function due to discontinuity! Return code: \" << ec << std::endl;\n#endif\n                eval_constraint(_x);\n                ec = sparse_hess(tape_, n_unknowns_, 0, _x, &nz, &r_ind, &c_ind, &val, opt);\n            }\n\n            assert(nz >= 0);\n            assert(r_ind != NULL);\n            assert(c_ind != NULL);\n            assert(val != NULL);\n\n#ifdef ADOLC_RET_CODES\n            std::cout << \"Info: sparse_hessian() returned code \" << ec << std::endl;\n#endif\n\n            for(int i = 0; i < nz; ++i) {\n\n                _H(r_ind[i], c_ind[i]) += val[i];\n            }\n\n            if(constant_hessian()) {\n                constant_hessian_ = _H;\n                constant_hessian_evaluated_ = true;\n            }\n\n            delete[] r_ind;\n            delete[] c_ind;\n            delete[] val;\n\n        } else {\n\n            double** h_ptr = problem_.dense_hessian_ptr();\n\n            int ec = hessian(tape_, n_unknowns_, const_cast<double*>(_x), h_ptr);\n\n            if(ec < 0) {\n                // Retape function if return code indicates discontinuity\n                function_evaluated_ = false;\n#ifdef ADOLC_RET_CODES\n                std::cout << __FUNCTION__ << \" invokes retaping of function due to discontinuity! Return code: \" << ec << std::endl;\n#endif\n                eval_constraint(_x);\n                ec = hessian(tape_, n_unknowns_, const_cast<double*>(_x), h_ptr);\n            }\n\n#ifdef ADOLC_RET_CODES\n            std::cout << \"Info: hessian() returned code \" << ec << std::endl;\n#endif\n\n            for(int i = 0; i < n_unknowns_; ++i) {\n                for(int j = 0; j <= i; ++j) {\n\n                    _H(i, j) += h_ptr[i][j];\n\n                    if(i != j) {\n                        _H(j, i) += h_ptr[i][j];\n                    }\n                }\n            }\n\n            if(constant_hessian()) {\n                constant_hessian_ = _H;\n                constant_hessian_evaluated_ = true;\n            }\n        }\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 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 sparse_hessian() {\n        return false;\n    }\n\nprivate:\n\n    // Reference to associated objective function\n    NProblemInterfaceAD& problem_;\n\n    // Number of unknowns\n    int n_unknowns_;\n\n    // Constraint type\n    ConstraintType type_;\n\n    size_t tape_stats_[11];\n\n    bool function_evaluated_;\n    bool use_tape_;\n\n    SMatrixNC constant_hessian_;\n    bool constant_hessian_evaluated_;\n\n    const short int tape_;\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": "04daec9838ea171ab80e615d99dddb76ecc8fbf1", "size": 10115, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/libigl/external/CoMISo/NSolver/NConstraintInterfaceAD.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/NConstraintInterfaceAD.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/NConstraintInterfaceAD.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": 30.5589123867, "max_line_length": 132, "alphanum_fraction": 0.5207118141, "num_tokens": 2359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.46652632833162294}}
{"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\u00e4nkt), 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// #define MTL_VERBOSE_TEST\n\n#include <iostream>\n\n#include <boost/numeric/mtl/mtl.hpp>\n#include <boost/numeric/itl/itl.hpp>\n\nconst int size = 3, N = size * size; \n\nint max_iter= 0;\n\ntemplate <typename Matrix, typename Solver>\nvoid test1(const char* solver_name, const char* matrix_name)\n{\n    mtl::io::tout << solver_name << \" on \" << matrix_name << std::endl;;\n\n    Matrix                             A;\n    laplacian_setup(A, size, size);\n       \n    mtl::dense_vector<double>          x(N, 1.0), b(N);    \n    b = A * x;\n    x= 0;\n    \n    Solver s(A);\n    s.iteration_ref().set_max_iterations(N+1);\n\n#ifdef MTL_VERBOSE_TEST\n    s.iteration_ref().set_quite(false);\n    s.iteration_ref().set_cycle(1);\n#else\n    s.iteration_ref().suppress_resume(true);\n#endif\n\n    s(x, b);\n    int i= s.iteration().iterations();\n    if (i > max_iter)\n\tmax_iter= i;\n    // MTL_THROW_IF(size == 3 && i > 9, mtl::runtime_error(\"Too many iterations in solver\"));\n    if (size == 3 && i > 9)\n\tstd::cout << \"Solver \\\"\" << solver_name << \"\\\" converges slowly!\\n\";\n}\n\n// same without iter\ntemplate <typename Matrix, typename Solver>\nvoid test1a(const char* solver_name, const char* matrix_name)\n{\n    mtl::io::tout << solver_name << \" on \" << matrix_name << std::endl;;\n\n    Matrix                             A;\n    laplacian_setup(A, size, size);\n       \n    mtl::dense_vector<double>          x(N, 1.0), b(N);    \n    b = A * x;\n    x= 0;\n    \n    Solver s(A);\n    s.step(x, b);\n}\n\n\n\ntemplate <typename Matrix>\nint test2(const char* matrix_name)\n{\n    test1<Matrix, itl::cg_solver<Matrix> >(\"CG\", matrix_name);\n    test1<Matrix, itl::cg_solver<Matrix, itl::pc::ilu_0<Matrix> > >(\"CG with ILU_0\", matrix_name);\n    test1<Matrix, itl::cgs_solver<Matrix> >(\"CGS\", matrix_name);\n    test1<Matrix, itl::cgs_solver<Matrix, itl::pc::ilu_0<Matrix> > >(\"CGS with ILU_0\", matrix_name);\n\n    test1<Matrix, itl::bicg_solver<Matrix> >(\"BiCG\", matrix_name);\n    test1<Matrix, itl::bicg_solver<Matrix, itl::pc::ilu_0<Matrix> > >(\"BiCG with ILU_0\", matrix_name);\n    test1<Matrix, itl::bicgstab_solver<Matrix> >(\"BiCGStab\", matrix_name);\n    test1<Matrix, itl::bicgstab_solver<Matrix, itl::pc::ilu_0<Matrix> > >(\"BiCGStab with ILU_0\", matrix_name);\n    test1<Matrix, itl::bicgstab_2_solver<Matrix> >(\"BiCGStab(2)\", matrix_name);\n    test1<Matrix, itl::bicgstab_2_solver<Matrix, itl::pc::ilu_0<Matrix> > >(\"BiCGStab(2) with ILU_0\", matrix_name);\n    test1<Matrix, itl::bicgstab_ell_solver<Matrix> >(\"BiCGStab(ell)\", matrix_name);\n    test1<Matrix, itl::bicgstab_ell_solver<Matrix, itl::pc::ilu_0<Matrix> > >(\"BiCGStab(ell) with ILU_0\", matrix_name);\n    test1<Matrix, itl::gmres_solver<Matrix> >(\"GMRES\", matrix_name);\n    test1<Matrix, itl::gmres_solver<Matrix, itl::pc::ilu_0<Matrix> > >(\"GMRES with ILU_0\", matrix_name);\n    test1<Matrix, itl::gmres_solver<Matrix, itl::pc::ilu_0<Matrix>, itl::pc::ilu_0<Matrix> > >(\"GMRES with ILU_0 from left and right\", matrix_name);\n\n    test1<Matrix, itl::qmr_solver<Matrix> >(\"QMR\", matrix_name);\n    test1<Matrix, itl::qmr_solver<Matrix, itl::pc::ilu_0<Matrix> > >(\"QMR with ILU_0\", matrix_name);\n    test1<Matrix, itl::tfqmr_solver<Matrix> >(\"TFQMR\", matrix_name);\n    test1<Matrix, itl::tfqmr_solver<Matrix, itl::pc::ilu_0<Matrix> > >(\"TFQMR with ILU_0\", matrix_name);\n\n    test1<Matrix, itl::idr_s_solver<Matrix> >(\"IDR(s)\", matrix_name);\n    test1<Matrix, itl::idr_s_solver<Matrix, itl::pc::ilu_0<Matrix> > >(\"IDR(s) with ILU_0\", matrix_name);\n\n    typedef itl::cg_solver<Matrix>                           cg1_type;\n    typedef itl::cg_solver<Matrix, itl::pc::ilu_0<Matrix> >  cg2_type;\n    \n    test1a<Matrix, itl::repeating_solver<cg1_type, 3, true> >(\"3 iterations CG\", matrix_name);\n    test1a<Matrix, itl::repeating_solver<cg2_type, 3, true> >(\"3 iterations CG with ILU_0\", matrix_name);\n\n    return 0;\n}\n\nint main()\n{\n    test2<mtl::compressed2D<double> >(\"Compressed2D\");\n    //test<mtl::sparse_banded<double> >();\n    // std::cout << \"Largest iteration number is \" << max_iter << '\\n';\n\n    return 0;\n}\n", "meta": {"hexsha": "7a74b62490238ef3273cad639050d27ac2a8856c", "size": 4466, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/itl/test/solver_classes_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/itl/test/solver_classes_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/itl/test/solver_classes_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": 37.5294117647, "max_line_length": 148, "alphanum_fraction": 0.6489028213, "num_tokens": 1466, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.46652632833162294}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2015 NumScale SAS\n  @copyright 2015 J.T.Lapreste\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_COMMON_DETAIL_GENERIC_D_EXPO_REDUCTION_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_DETAIL_GENERIC_D_EXPO_REDUCTION_HPP_INCLUDED\n\n#include <boost/simd/function/horn.hpp>\n#include <boost/simd/function/horn1.hpp>\n#include <boost/simd/arch/common/detail/tags.hpp>\n#include <boost/simd/constant/invlog10_2.hpp>\n#include <boost/simd/constant/invlog_2.hpp>\n#include <boost/simd/constant/log10_2hi.hpp>\n#include <boost/simd/constant/log10_2lo.hpp>\n#include <boost/simd/constant/log_10.hpp>\n#include <boost/simd/constant/log_2.hpp>\n#include <boost/simd/constant/log_2hi.hpp>\n#include <boost/simd/constant/log_2lo.hpp>\n#include <boost/simd/constant/maxlog.hpp>\n#include <boost/simd/constant/maxlog10.hpp>\n#include <boost/simd/constant/maxlog2.hpp>\n#include <boost/simd/constant/minlog.hpp>\n#include <boost/simd/constant/minlog10.hpp>\n#include <boost/simd/constant/minlog2.hpp>\n#include <boost/simd/constant/two.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/function/simd/is_greater_equal.hpp>\n#include <boost/simd/function/simd/is_less_equal.hpp>\n#include <boost/simd/function/simd/fma.hpp>\n#include <boost/simd/function/simd/fnms.hpp>\n#include <boost/simd/function/simd/inc.hpp>\n#include <boost/simd/function/simd/oneplus.hpp>\n#include <boost/simd/function/simd/oneminus.hpp>\n#include <boost/simd/function/simd/round2even.hpp>\n#include <boost/simd/function/simd/sqr.hpp>\n#include <boost/simd/logical.hpp>\n#include <boost/dispatch/meta/scalar_of.hpp>\n\nnamespace boost { namespace simd\n{\n  namespace detail\n  {\n    namespace bd =  boost::dispatch;\n    namespace bs =  boost::simd;\n\n    template < class A0> struct exp_reduction < A0, bs::tag::exp_, double>\n    {\n      static BOOST_FORCEINLINE auto isgemaxlog(A0 const& a0) BOOST_NOEXCEPT\n        -> decltype(is_greater_equal(a0, Maxlog<A0>()))\n      {\n        return is_greater_equal(a0, Maxlog<A0>());\n      }\n\n      static BOOST_FORCEINLINE auto isleminlog(A0 const& a0) BOOST_NOEXCEPT\n        -> decltype(is_less_equal(a0, Minlog<A0>()))\n      {\n        return is_less_equal(a0, Minlog<A0>());\n      }\n\n      static BOOST_FORCEINLINE A0 reduce( A0 const& a0\n                                        , A0& hi, A0& lo, A0& x) BOOST_NOEXCEPT\n      {\n        A0 k = round2even(Invlog_2<A0>()*a0);\n        hi = fnms(k, Log_2hi<A0>(), a0); //a0-k*L\n        lo = k*Log_2lo<A0>();\n        x  = hi-lo;\n        return k;\n      }\n\n      static BOOST_FORCEINLINE A0 approx(A0 x) BOOST_NOEXCEPT\n      {\n        A0 const t = sqr(x);\n        return fnms(t,\n                    horn<A0\n                         , 0x3fc555555555553eull\n                         , 0xbf66c16c16bebd93ull\n                         , 0x3f11566aaf25de2cull\n                         , 0xbebbbd41c5d26bf1ull\n                         , 0x3e66376972bea4d0ull\n                    >(t), x); //x-h*t\n    }\n\n      static BOOST_FORCEINLINE A0 finalize(A0 x, A0 c, A0 hi, A0 lo) BOOST_NOEXCEPT\n      {\n        return One<A0>()-(((lo-(x*c)/(Two<A0>()-c))-hi));\n      }\n\n    };\n\n    template < class A0 > struct exp_reduction < A0, bs::tag::exp2_, double>\n    {\n      static BOOST_FORCEINLINE auto isgemaxlog(A0 const& a0) BOOST_NOEXCEPT\n        -> decltype(is_greater_equal(a0, Maxlog2<A0>()))\n      {\n        return is_greater_equal(a0, Maxlog2<A0>());\n      }\n\n      static BOOST_FORCEINLINE auto isleminlog(A0 const& a0) BOOST_NOEXCEPT\n        -> decltype(is_less_equal(a0, Minlog2<A0>()))\n      {\n        return is_less_equal(a0, Minlog2<A0>());\n      }\n\n      static BOOST_FORCEINLINE A0 reduce(A0 const& a0, A0, A0, A0& x) BOOST_NOEXCEPT\n      {\n        A0 k = round2even(a0);\n        x = (a0 - k)*Log_2<A0>();\n        return k;\n      }\n\n      static BOOST_FORCEINLINE A0 approx(A0 x) BOOST_NOEXCEPT\n      {\n        const A0 t =  sqr(x);\n        return fnms(t,\n                    horn<A0\n                         , 0x3fc555555555553eull\n                         , 0xbf66c16c16bebd93ull\n                         , 0x3f11566aaf25de2cull\n                         , 0xbebbbd41c5d26bf1ull\n                         , 0x3e66376972bea4d0ull\n                    > (t), x); //x-h*t\n      }\n\n      static BOOST_FORCEINLINE A0 finalize( A0 x, A0 c, A0, A0& ) BOOST_NOEXCEPT\n      {\n        return oneminus(((-(x*c)/(Two<A0>()-c))-x));\n      }\n    };\n\n    template < class A0 > struct exp_reduction < A0, bs::tag::exp10_, double>\n    {\n      static BOOST_FORCEINLINE auto isgemaxlog(A0 const& a0) BOOST_NOEXCEPT\n        -> decltype(is_greater_equal(a0, Maxlog10<A0>()))\n      {\n        return is_greater_equal(a0, Maxlog10<A0>());\n      }\n\n      static BOOST_FORCEINLINE auto isleminlog(A0 const& a0) BOOST_NOEXCEPT\n        -> decltype(is_less_equal(a0, Minlog10<A0>()))\n      {\n        return is_less_equal(a0, Minlog10<A0>());\n      }\n\n      static BOOST_FORCEINLINE A0 reduce(A0 const& a0, A0&, A0&, A0& x) BOOST_NOEXCEPT\n      {\n        A0 k  = round2even(Invlog10_2<A0>()*a0);\n        x = fnms(k, Log10_2hi<A0>(), a0);\n        x = fnms(k, Log10_2lo<A0>(), x);\n        return k;\n      }\n\n      static BOOST_FORCEINLINE A0 approx(A0 x) BOOST_NOEXCEPT\n      {\n        A0 xx = sqr(x);\n        A0 px = x*horn<A0,\n                       0x40a2b4798e134a01ull,\n                       0x40796b7a050349e4ull,\n                       0x40277d9474c55934ull,\n                       0x3fa4fd75f3062dd4ull\n                       > (xx);\n        A0 x2 =  px/(horn1<A0,\n                          0x40a03f37650df6e2ull,\n                          0x4093e05eefd67782ull,\n                          0x405545fdce51ca08ull\n                     //   0x3ff0000000000000ull\n                          > (xx)-px);\n        return oneplus(x2+x2);\n      }\n\n      static BOOST_FORCEINLINE A0 finalize(A0, A0 c, A0,  A0 ) BOOST_NOEXCEPT\n      {\n        return c;\n      }\n    };\n  }\n} }\n#endif\n", "meta": {"hexsha": "2ec8230758cbcf24c1a7ad49052b39900b396898", "size": 6215, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arch/common/detail/generic/d_expo_reduction.hpp", "max_stars_repo_name": "yaeldarmon/boost.simd", "max_stars_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/simd/arch/common/detail/generic/d_expo_reduction.hpp", "max_issues_repo_name": "yaeldarmon/boost.simd", "max_issues_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/arch/common/detail/generic/d_expo_reduction.hpp", "max_forks_repo_name": "yaeldarmon/boost.simd", "max_forks_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5945945946, "max_line_length": 100, "alphanum_fraction": 0.5774738536, "num_tokens": 1784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.835483553488848, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.46647302123606654}}
{"text": "// Copyright 2018 Hans Dembinski\n//\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include <array>\n#include <boost/core/lightweight_test.hpp>\n#include <boost/histogram/accumulators/weighted_sum.hpp>\n#include <boost/histogram/algorithm/sum.hpp>\n#include <boost/histogram/axis/integer.hpp>\n#include <unordered_map>\n#include <vector>\n#include \"throw_exception.hpp\"\n#include \"utility_histogram.hpp\"\n\nusing namespace boost::histogram;\nusing boost::histogram::algorithm::sum;\n\ntemplate <typename Tag>\nvoid run_tests() {\n  auto ax = axis::integer<>(0, 10);\n\n  {\n    auto h = make(Tag(), ax);\n    std::fill(h.begin(), h.end(), 1);\n    BOOST_TEST_EQ(sum(h), 12);\n    BOOST_TEST_EQ(sum(h, coverage::inner), 10);\n  }\n\n  {\n    auto h = make_s(Tag(), std::array<int, 12>(), ax);\n    std::fill(h.begin(), h.end(), 1);\n    BOOST_TEST_EQ(sum(h), 12);\n    BOOST_TEST_EQ(sum(h, coverage::inner), 10);\n  }\n\n  {\n    auto h = make_s(Tag(), std::unordered_map<std::size_t, int>(), ax);\n    std::fill(h.begin(), h.end(), 1);\n    BOOST_TEST_EQ(sum(h), 12);\n    BOOST_TEST_EQ(sum(h, coverage::inner), 10);\n  }\n\n  {\n    auto h = make_s(Tag(), std::vector<double>(), ax, ax);\n    std::fill(h.begin(), h.end(), 1);\n    BOOST_TEST_EQ(sum(h), 12 * 12);\n    BOOST_TEST_EQ(sum(h, coverage::inner), 10 * 10);\n  }\n\n  {\n    using W = accumulators::weighted_sum<>;\n    auto h = make_s(Tag(), std::vector<W>(), axis::integer<>(0, 2),\n                    axis::integer<int, axis::null_type, axis::option::none_t>(2, 4));\n    W w(0, 2);\n    for (auto&& x : h) {\n      x = w;\n      w = W(w.value() + 1, 2);\n    }\n\n    // x-axis has 4 bins, y-axis has 2 = 8 bins total with 4 inner bins\n\n    const auto v1 = algorithm::sum(h);\n    BOOST_TEST_EQ(v1.value(), 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7);\n    BOOST_TEST_EQ(v1.variance(), 8 * 2);\n\n    const auto v2 = algorithm::sum(h, coverage::inner);\n    BOOST_TEST_EQ(v2.value(), 1 + 2 + 5 + 6);\n    BOOST_TEST_EQ(v2.variance(), 4 * 2);\n  }\n}\n\nint main() {\n  run_tests<static_tag>();\n  run_tests<dynamic_tag>();\n\n  return boost::report_errors();\n}\n", "meta": {"hexsha": "4f4b8095e2a33262989b44243f8406845fd9b455", "size": 2155, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/histogram/test/algorithm_sum_test.cpp", "max_stars_repo_name": "uosorio/heroku_face", "max_stars_repo_head_hexsha": "7d6465e71dba17a15d8edaef520adb2fcd09d91e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 188.0, "max_stars_repo_stars_event_min_datetime": "2019-02-08T14:11:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T08:37:05.000Z", "max_issues_repo_path": "3rdparty/boost_1_73_0/libs/histogram/test/algorithm_sum_test.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 186.0, "max_issues_repo_issues_event_min_datetime": "2016-05-05T14:01:09.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-20T22:38:43.000Z", "max_forks_repo_path": "3rdparty/boost_1_73_0/libs/histogram/test/algorithm_sum_test.cpp", "max_forks_repo_name": "qingkouwei/mediaones", "max_forks_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 43.0, "max_forks_repo_forks_event_min_datetime": "2019-02-09T16:16:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-25T20:24:36.000Z", "avg_line_length": 26.9375, "max_line_length": 85, "alphanum_fraction": 0.6134570766, "num_tokens": 656, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.46643711290680157}}
{"text": "/*\nBSD 3-Clause License\nCopyright (c) 2020, Juan S. Campos\nAll rights reserved.\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n1. Redistributions of source code must retain the above copyright notice, this\n   list of conditions and the following disclaimer.\n2. Redistributions in binary form must reproduce the above copyright notice,\n   this list of conditions and the following disclaimer in the documentation\n   and/or other materials provided with the distribution.\n3. 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.\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/*\nThis code calculates the partial and augmented relaxations as described in\n\"Partial Lasserre relaxation for sparse Max-Cut\" by Campos, J.S., Misener R., and Parpas, P. 2020.\n*/\n\n\n#include <iostream>\n#include \"fusion.h\"\n#include <fstream>\n#include <string>\n#include <sstream>\n#include <stdio.h>\n#include <typeinfo>\n#include <chrono>\n#include <math.h> \n#include <algorithm>\n#include <vector>\n#include <iomanip>\n#include <stdlib.h> \n#include <time.h>    \n#include <boost/functional/hash.hpp>\n#include <unordered_map>\n#define BILLION 1e9\n\n\nusing namespace std;\nusing namespace mosek::fusion;\nusing namespace monty;\n\nstruct timespec my_start;\n\n\nvoid read_matrix(const char *, Matrix::t&); \nvoid read_matrix_sparse_format(const char *, Matrix::t&); \n\ntemplate <typename Container>\nstruct container_hash\n{\n\tsize_t operator()(Container const& c) const {\n\t\treturn boost::hash_range(c.begin(), c.end());\n\t}\n};\n\nint main(int argc, char ** argv)\n{\n \t // Order of arguments: max_size_cliques (r), no_subsets to add (p), type of heuristic (H1 to H5), name  of the instance \n\tchar aux_string[300];\t\n\t// Read weight matrix W\n\t// First row must contain the number of nodes and edges\n\tMatrix::t W;\n\tsprintf(aux_string,\"graphs/%s.txt\",argv[4]);\n\tread_matrix_sparse_format(aux_string, W);\t\n    \n   \n\tint n = W->numColumns();\t\t\n\tint max_size_clique = atoi(argv[1]);// 0,2,3 ...\n\tint no_subsets = atoi(argv[2]);// 0,1,2,3 ...\n\tchar heuristic [300]; \n\tsprintf(heuristic,\"%s\",argv[3]);// H1, H2, ..., H5\n\t\n\tint total_cliques;\t\n\tdouble time_creating_mosek = 0;\n\tdouble time_solving_SDP = 0;\n\tdouble time_creating_cliques = 0;\n\tdouble time_generating_LB = 0;\n\tdouble time_total = 0;\n\t\n\tauto start = std::chrono::high_resolution_clock::now();\t\n\tauto start_creating = std::chrono::high_resolution_clock::now();\t\n\t\n    // Read maximal cliques and subset generated from matlab\n    Matrix::t cliques;\n    Matrix::t first_second_order;  \n    \n   \tsprintf(aux_string,\"clique_%s_%d_%d_%s.txt\",argv[4], max_size_clique, no_subsets,heuristic);\n\tread_matrix(aux_string, cliques);\n    sprintf(aux_string,\"clique_aux_%s_%d_%d_%s.txt\",argv[4], max_size_clique, no_subsets,heuristic);\n\tread_matrix(aux_string, first_second_order);\n\tauto finish = std::chrono::high_resolution_clock::now();\n\tstd::chrono::duration<double> elapsed = finish - start;\n\tcout<<\"time reading W, cliques, and first_second_order: \"<<elapsed.count()<<endl;\n\t\n\tstart = std::chrono::high_resolution_clock::now();\n\ttotal_cliques = (cliques->numRows());\n\t\n\tvector <int> size_cliques(total_cliques);\n\tvector <vector<int>> idx_cliques(total_cliques);\n\tvector <int> size_blk(total_cliques);\t\n\tint total_var_all_blocks = 0;\n\tfor (int i = 0; i < total_cliques; i++)\n    {\n\t\tint aux_count = 0;\n\t\t\n\t    for(int j=0; j < n; j++)\n\t    {\n\t\t\tif(cliques->get(i,j)>0)\n\t\t\t{\n\t\t\t\taux_count = aux_count + 1;\n\t\t\t\tidx_cliques[i].push_back(j);\n\t\t\t}\n\t\t}\n\t\tsize_cliques[i] = aux_count;\n\t\tif((first_second_order->get(i,0) == 1) | (aux_count == 1))\n\t\t{\n\t\t\tsize_blk[i] = aux_count + 1;\t\t\t\n\t\t}\n\t\telse\n\t\t{\n\t\t\tsize_blk[i] = (aux_count + 2)*(aux_count + 1)/2 - aux_count;\t\t\t\n\t\t}\t\n\t\ttotal_var_all_blocks = total_var_all_blocks + (size_blk[i]*size_blk[i]);\n    }\n    finish = std::chrono::high_resolution_clock::now();\n\telapsed = finish - start;\n\tcout<<\"time creating size_cliques and idx_cliques: \"<<elapsed.count()<<endl;\t\n\t\n    // Generate unordered_map containing the monomials needed for the cliques \n    start = std::chrono::high_resolution_clock::now();\n    vector <int> alpha (4,0);\n    unordered_map<vector<int>, int, container_hash<vector<int>>> map; \n     \n    for(int i=0; i< n; i++)\n    {\n\t\talpha[0] = i;\n\t\tmap.insert({alpha,i});\n\t} \n\tint value_map = n;\n\t\n    for (int i = 0; i < total_cliques; i++)\n    {\t\t\t\t\n\t\tint degree = 2;\n\t\tif(first_second_order->get(i,0) == 2)\n\t\t{\n\t\t\tdegree = 4;\n\t\t}\n\t\t\n\t\tfor(int j=2; j<=degree; j++)\n\t\t{\n\t\t\tif(j <= size_cliques[i])\n\t\t\t{\t\t\t\t\t\t\t\t\n\t\t\t\tvector <int> perm(size_cliques[i], 0);\n                fill_n(perm.begin(), j, 1);\n                int count_aux = 0;\n                do\n                {\n                    for (int k = 0; k < size_cliques[i]; k++)\n                    {\n                        if (perm[k] == 1)\n                        {\n                            alpha[count_aux] = idx_cliques[i][k];\n                            count_aux = count_aux + 1;\n                        }\n                    }\n                    count_aux = 0;\n                    if(map.find(alpha) == map.end())\n                    {\n                        map.insert({alpha,value_map});\n                        value_map = value_map + 1;\n                    }\n                    fill(alpha.begin(), alpha.end(),0);\n                } while (prev_permutation(perm.begin(), perm.end()));\n\t\t\t}\t\t\t\n\t\t}\n\t}\n\t\n\tint total_y = map.size();\n\tfinish = std::chrono::high_resolution_clock::now();\n\telapsed = finish - start;\n\tcout<<\"time creating unordered_map: \"<<elapsed.count()<<endl;\n          \n    // Generating SDP problem: max b*y, st. Aty - C = S, S>=0\n    \n    // Creating mosek model\n    Model::t M = new Model(\"sdo1\"); \n    // Creating SDP blocks and lifted monomials variable and calculating norm_C\n    double norm_C = 0;\n    Variable::t S[total_cliques];    \n    for(int i=0; i<total_cliques; i++)\n    {\n\t\tsprintf(aux_string,\"S_%d\",i);\t\t\t\n\t    S[i] = M->variable(aux_string, Domain::inPSDCone(size_blk[i]));\t \n\t    norm_C = max(norm_C, sqrt(double(size_blk[i])));  \n\t}\n\t\n\tnorm_C = (max(1.0,norm_C));\n\t\n\t// Creating b\n\tauto bsubi = new_array_ptr<int, 1>(n*(n-1)*0.5 + n);\n\tauto bsubj = new_array_ptr<int, 1>(n*(n-1)*0.5 + n);\n\tauto bcof  = new_array_ptr<double, 1>(n*(n-1)*0.5 + n);\n\tdouble obj_constant = 0;\n\t\n\tfill(alpha.begin(), alpha.end(),0);\n\tdouble norm_b = 0;\n\tvector<double> pert(n);\n\tsrand(time(NULL));\n\tdouble perturbation = 0;//////////////////////////////\n\tfor(int i = 0; i < n; i++)\n\t{\n\t\tpert[i] = perturbation*(double(rand())/RAND_MAX);\n\t\tnorm_b = norm_b + pert[i];\n\t\t\n\t\tfor(int j = i+1; j < n; j++)\n\t\t{\n\t\t\tnorm_b = 0.25*4*W->get(i,j)*W->get(i,j) + norm_b;\n\t\t}\n\t}\t\n\tnorm_b = max(1.0,sqrt(norm_b));\t\n\tint aux_count = 0;\t\n\tfor(int i = 0; i < n; i++)\n\t{\n\t\talpha[0] = i;\n\t\talpha[1] = 0;\n\t\t(*bsubi)[aux_count] = map[alpha];\n\t\t(*bsubj)[aux_count] = 0;\n\t\t(*bcof)[aux_count] = pert[i]/norm_b;\n\t\taux_count = aux_count + 1;\t\t\n\t\tfor(int j = i+1; j < n; j++)\n\t\t{\n\t\t\talpha[0] = i;\n\t\t\talpha[1] = j;\n\t\t\t(*bsubi)[aux_count] = map[alpha];\n\t\t\t(*bsubj)[aux_count] = 0;\n\t\t\t(*bcof)[aux_count] = -0.25*2*(W->get(i,j))/norm_b;\n\t\t\tobj_constant = obj_constant + W->get(i,j);\n\t\t\taux_count = aux_count + 1;\t\t\t\n\t\t}\n\t}\t\n\tobj_constant = 2*obj_constant*0.25;\t\n\tMatrix::t b = Matrix::sparse(total_y, 1, bsubi, bsubj, bcof); \n\t\n\t// Generating A \n    start = std::chrono::high_resolution_clock::now();\n    int total_constraints = total_var_all_blocks;\n    \n\tExpression::t Ax_b;\n\tint count_const;\n\tvector<double> norm_A(total_cliques);\t\n\tfor(int i=0; i < total_cliques; i++)\n    {   \n\t\tint size_vec_blk_i = size_blk[i]*size_blk[i];\n\t\tint size_blk_i = size_blk[i];\n\t\tint size_clique_i = size_cliques[i];\n\t\tint total_constraints = size_blk_i*(size_blk_i - 1);\n\t\tcount_const = 0;\n\t\tauto msubi = new_array_ptr<int, 1>(total_constraints);\n\t    auto msubj = new_array_ptr<int, 1>(total_constraints);\n\t    auto mcof  = new_array_ptr<double, 1>(total_constraints);\n\t    norm_A[i] = max(1.0, sqrt(double(total_constraints)));\n\t    \n\t\tfill(alpha.begin(), alpha.end(),0);\n\t\tdouble const_coef = 1/norm_A[i];\n\t\tfor(int j = 1; j <= size_clique_i; j++)\n\t\t{\t\t\t\n\t\t\talpha[0] = idx_cliques[i][j-1];\t\t\t\n\t\t\t(*msubi)[count_const] = j;\n\t\t\t(*msubj)[count_const] = map[alpha];\t\t\t\t\n\t\t\t(*mcof)[count_const] = const_coef;\n\t\t\t(*msubi)[count_const+1] = j*(size_blk_i);\n\t\t\t(*msubj)[count_const+1] = map[alpha];\n\t\t\t(*mcof)[count_const+1] = const_coef;\n\t\t\tcount_const = count_const + 2;\n\t\t} \t\n\t\t\n\t\tfor(int j = 0; j < size_clique_i; j++)\n\t\t{\t\t\t\n\t\t\tfor(int k = j + 1; k < size_cliques[i]; k++)\n\t\t\t{\n\t\t\t\talpha[0] = idx_cliques[i][j];\n\t\t\t\talpha[1] = idx_cliques[i][k];\n\t\t\t\t(*msubi)[count_const] = (j+1)*(size_blk[i]) + k + 1;\n\t\t\t\t(*msubj)[count_const] = map[alpha];\t\t\t\t\n\t\t\t\t(*mcof)[count_const] = const_coef;\n\t\t\t\t(*msubi)[count_const+1] = (k+1)*(size_blk[i]) + j + 1;\n\t\t\t\t(*msubj)[count_const+1] = map[alpha];\n\t\t\t\t(*mcof)[count_const+1] = const_coef;\n\t\t\t\tcount_const = count_const + 2;\n\t\t\t}\n\t\t} \t\n\t\t\t\t\n\t\tif((first_second_order->get(i,0) == 2) & (size_clique_i > 1))\n\t\t{\n\t\t\tfill(alpha.begin(), alpha.end(),0);\n\t\t\tint count_aux = 1;\n\t\t    for(int k = 0; k < size_clique_i; k++)\n\t\t    {\n\t\t\t\tfor(int l = k+1; l < size_clique_i; l++)\n\t\t\t\t{\t\t\t        \n\t\t\t        alpha[0] = idx_cliques[i][k];\n\t\t\t\t    alpha[1] = idx_cliques[i][l];\n\t\t\t\t    (*msubi)[count_const] = (size_clique_i) + count_aux;\n\t\t\t\t    (*msubj)[count_const] = map[alpha];\t\t\t\t\n\t\t\t\t    (*mcof)[count_const] = const_coef;\n\t\t\t\t    (*msubi)[count_const+1] = ((size_clique_i+count_aux)*size_blk_i);\n\t\t\t\t    (*msubj)[count_const+1] = map[alpha];\n\t\t\t\t    (*mcof)[count_const+1] = const_coef;\n\t\t\t\t    count_const = count_const + 2;\n\t\t\t\t    count_aux = count_aux + 1;\n\t\t\t    }\n\t\t\t}\n\t\t  \n\t\t   \t\t\n\t\t    for(int j = 0; j < size_clique_i; j++)\n\t\t    {\t\t\t\n\t\t\t\tcount_aux = 1;\n\t\t\t    for(int k = 0; k < size_clique_i-1; k++)\n\t\t\t    {\n\t\t\t\t\tfor(int l = k+1; l < size_clique_i; l++)\n\t\t\t\t\t{\n\t\t\t\t        fill(alpha.begin(), alpha.end(),0);\n\t\t\t\t        if(j == k)\n\t\t\t\t        {\n\t\t\t\t\t\t\talpha[0] = idx_cliques[i][l];\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if(j == l)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\talpha[0] = idx_cliques[i][k];\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if(j<k)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\talpha[0] = idx_cliques[i][j];\n\t\t\t\t\t\t\talpha[1] = idx_cliques[i][k];\n\t\t\t\t\t\t\talpha[2] = idx_cliques[i][l];\n\t\t\t\t\t\t}  \n\t\t\t\t\t\telse if (j<l)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\talpha[0] = idx_cliques[i][k];\n\t\t\t\t\t\t\talpha[1] = idx_cliques[i][j];\n\t\t\t\t\t\t\talpha[2] = idx_cliques[i][l];\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\talpha[0] = idx_cliques[i][k];\n\t\t\t\t\t\t\talpha[1] = idx_cliques[i][l];\n\t\t\t\t\t\t\talpha[2] = idx_cliques[i][j];\n\t\t\t\t\t\t} \n\t\t\t\t        \n\t\t\t\t        (*msubi)[count_const] = (j+1)*size_blk_i + size_clique_i + count_aux;\t\t\t\t       \n\t\t\t\t        (*msubj)[count_const] = map[alpha];\t\t\n\t\t\t\t        (*mcof)[count_const] = const_coef;\t\t\t\t       \n\t\t\t\t        (*msubi)[count_const+1] = (size_clique_i + count_aux)*size_blk_i + j + 1;\n\t\t\t\t        (*msubj)[count_const+1] = map[alpha];\n\t\t\t\t        (*mcof)[count_const+1] = const_coef;\n\t\t\t\t        count_const = count_const + 2;\n\t\t\t\t        count_aux = count_aux + 1;\t\t\t\t        \n\t\t\t        }\n\t\t\t\t}\n\t\t    } \t\n\t\t    \n\t\t   \n\t\t    count_aux = 0;\n\t\t    int count_aux2;\n\t\t    for(int j = 0; j < size_clique_i-1; j++)\n\t\t    {\t\t\t\n\t\t\t\tfor(int k = j+1; k < size_clique_i; k++)\n\t\t\t    {\n\t\t\t\t\tcount_aux = count_aux + 1;\n\t\t\t\t\tcount_aux2 = 0;\n\t\t\t\t\tfor(int l = 0; l < size_clique_i-1; l++)\n\t\t\t\t\t{\n\t\t\t\t\t\tfor(int m = l+1; m < size_clique_i; m++)\n\t\t\t\t\t    {\n\t\t\t\t\t\t\tcount_aux2 = count_aux2 + 1;\t\t\t\n\t\t\t\t\t\t\tif((j==l) & (k==m))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tfill(alpha.begin(), alpha.end(),0);\n\t\t\t\t            if(j == l)\n\t\t\t\t            {\n\t\t\t\t\t\t\t\tif(k<m)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t    alpha[0] = idx_cliques[i][k];\n\t\t\t\t\t\t\t\t    alpha[1] = idx_cliques[i][m];\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\talpha[0] = idx_cliques[i][m];\n\t\t\t\t\t\t\t\t    alpha[1] = idx_cliques[i][k];\n\t\t\t\t\t\t\t\t}\t\t\t\t\t\t\t    \n\t\t\t\t\t\t    }\n\t\t\t\t\t\t    else if(k == m)\n\t\t\t\t\t\t    {\n\t\t\t\t\t\t\t    if(j<l)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t    alpha[0] = idx_cliques[i][j];\n\t\t\t\t\t\t\t\t    alpha[1] = idx_cliques[i][l];\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\talpha[0] = idx_cliques[i][l];\n\t\t\t\t\t\t\t\t    alpha[1] = idx_cliques[i][j];\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t    }\n\t\t\t\t\t\t    else if(j == m)\n\t\t\t\t\t\t    {\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t    alpha[0] = idx_cliques[i][l];\n\t\t\t\t\t\t\t    alpha[1] = idx_cliques[i][k];\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t    }\n\t\t\t\t\t\t    else if(k == l)\n\t\t\t\t\t\t    {\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t    alpha[0] = idx_cliques[i][j];\n\t\t\t\t\t\t\t    alpha[1] = idx_cliques[i][m];\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t    }\n\t\t\t\t\t\t    else if(k<l)\n\t\t\t\t\t\t    {\n\t\t\t\t\t\t\t    alpha[0] = idx_cliques[i][j];\n\t\t\t\t\t\t\t    alpha[1] = idx_cliques[i][k];\n\t\t\t\t\t\t\t    alpha[2] = idx_cliques[i][l];\n\t\t\t\t\t\t\t    alpha[3] = idx_cliques[i][m];\t\t\t\t\t\t\t    \n\t\t\t\t\t\t    }  \n\t\t\t\t\t\t    else if(m<j)\n\t\t\t\t\t\t    {\n\t\t\t\t\t\t\t    alpha[0] = idx_cliques[i][l];\n\t\t\t\t\t\t\t    alpha[1] = idx_cliques[i][m];\n\t\t\t\t\t\t\t    alpha[2] = idx_cliques[i][j];\n\t\t\t\t\t\t\t    alpha[3] = idx_cliques[i][k];\t\t\t\t\t\t\t    \n\t\t\t\t\t\t    }\n\t\t\t\t\t\t    else if((j<l) & (m<k))\n\t\t\t\t\t\t    {\n\t\t\t\t\t\t\t    alpha[0] = idx_cliques[i][j];\n\t\t\t\t\t\t\t    alpha[1] = idx_cliques[i][l];\n\t\t\t\t\t\t\t    alpha[2] = idx_cliques[i][m];\n\t\t\t\t\t\t\t    alpha[3] = idx_cliques[i][k];\t\t\t\t\t\t\t    \n\t\t\t\t\t\t    } \n\t\t\t\t\t\t    else if((j<l) & (k<m))\n\t\t\t\t\t\t    {\n\t\t\t\t\t\t\t    alpha[0] = idx_cliques[i][j];\n\t\t\t\t\t\t\t    alpha[1] = idx_cliques[i][l];\n\t\t\t\t\t\t\t    alpha[2] = idx_cliques[i][k];\n\t\t\t\t\t\t\t    alpha[3] = idx_cliques[i][m];\t\t\t\t\t\t\t    \n\t\t\t\t\t\t    } \n\t\t\t\t\t\t    else if((l<j) & (m<k))\n\t\t\t\t\t\t    {\n\t\t\t\t\t\t\t    alpha[0] = idx_cliques[i][l];\n\t\t\t\t\t\t\t    alpha[1] = idx_cliques[i][j];\n\t\t\t\t\t\t\t    alpha[2] = idx_cliques[i][m];\n\t\t\t\t\t\t\t    alpha[3] = idx_cliques[i][k];\t\t\t\t\t\t\t    \n\t\t\t\t\t\t    }  \n\t\t\t\t\t\t    else if((l<j) & (k<m))\n\t\t\t\t\t\t    {\n\t\t\t\t\t\t\t    alpha[0] = idx_cliques[i][l];\n\t\t\t\t\t\t\t    alpha[1] = idx_cliques[i][j];\n\t\t\t\t\t\t\t    alpha[2] = idx_cliques[i][k];\n\t\t\t\t\t\t\t    alpha[3] = idx_cliques[i][m];\t\t\t\t\t\t\t    \n\t\t\t\t\t\t    } \n\t\t\t\t             \n\t\t\t\t            (*msubi)[count_const] = (size_clique_i + count_aux)*size_blk_i + size_clique_i + count_aux2;\t\t\t\t           \n\t\t\t\t            (*msubj)[count_const] = map[alpha];\t\n\t\t\t\t            (*mcof)[count_const] = const_coef;\t\t                   \n\t\t\t\t            count_const = count_const + 1;\t\t\t\t            \n\t\t\t\t\t\t}\n\t\t\t        }\n\t\t\t\t}\n\t\t    }\n\t    }\t    \n\t    \n\t   \n\t    auto msubid = new_array_ptr<int, 1>(size_blk_i);\n\t    auto msubjd = new_array_ptr<int, 1>(size_blk_i);\n\t    auto mcofd  = new_array_ptr<double, 1>(size_blk_i);\n\t    for (int j = 0; j < size_blk[i]; j++)\n\t    {\n\t\t\t(*msubid)[j] = (j*size_blk_i)+j;\n\t\t\t(*msubjd)[j] = 0;\n\t\t\t(*mcofd)[j] = 1.0/(norm_C*norm_A[i]);\n\t\t}\n\t \n\t    Matrix::t A = Matrix::sparse(total_y,size_vec_blk_i, msubj, msubi, mcof);  \n\t    \n\t    if (i==0)\n\t    {\n\t\t\tAx_b = Expr::mul(A, Expr::reshape(Expr::mul(S[i],-1),size_vec_blk_i));\n\t\t}\n\t\telse\n\t\t{\n\t        Ax_b = Expr::add(Ax_b, Expr::mul(A, Expr::reshape(Expr::mul(S[i],-1),size_vec_blk_i)));\n\t    }\n\t   \t\n\t}\n\tAx_b = Expr::sub(Ax_b,b);\n\tConstraint::t con = M->constraint(Ax_b, Domain::equalsTo(0.0));\n\tcout<<\"size map: \"<<map.size()<<endl;\t\n\tcout<<\"Total_constraints: \"<<b->numRows()<<endl;\n\t\n\t\n    finish = std::chrono::high_resolution_clock::now();\n    elapsed = finish - start;\n    cout<<\"Time creating constraints: \"<<elapsed.count()<<endl;\n    \n    \n    // Creating objective function\n    \n    Expression::t obj = Expr::constTerm(0);\n    for (int i=0;i<total_cliques;i++)\n    {\n\t\tint size_blk_i = size_blk[i];\n\t    auto msubid = new_array_ptr<int, 1>(size_blk_i);\n\t    auto msubjd = new_array_ptr<int, 1>(size_blk_i);\n\t    auto mcofd  = new_array_ptr<double, 1>(size_blk_i);\t    \n\t    for (int j = 0; j < size_blk_i; j++)\n\t    {\n\t\t\t(*msubid)[j] = j;\n\t\t\t(*msubjd)[j] = j;\n\t\t\t(*mcofd)[j] = 1.0/(norm_C*norm_A[i]);\n\t\t}\n\t\t\n\t\tMatrix::t D_ones = Matrix::sparse(size_blk_i,size_blk_i, msubid, msubjd, mcofd);\t\t\n\t\tobj = Expr::add(obj, Expr::dot(S[i],D_ones));\t\n\t\t\n\t}\n\t\n    auto finish_creating = std::chrono::high_resolution_clock::now();\n\tstd::chrono::duration<double> elapsed_creating = finish_creating - start_creating;\n    //Solve SDP\n  \tM->setLogHandler([=](const std::string & msg) { std::cout << msg << std::flush; } );\t\t\t\n\tM->objective(ObjectiveSense::Minimize, obj);\t\t\n\tM->setSolverParam(\"optimizerMaxTime\", 10800);\n\t\n\tauto start_solving_SDP = std::chrono::high_resolution_clock::now();\t\n\t\n\tM->solve();\t \t\t\t\n\tfinish = std::chrono::high_resolution_clock::now();\n\telapsed = finish - start_solving_SDP;\t\n\ttime_solving_SDP = elapsed.count();\n\t\n\t\t\n\tstd::cout << std::fixed;\n    std::cout << std::setprecision(4);\n\tcout<<\"time creating problem: \"<<elapsed_creating.count()<<endl;\n\tcout<<\"time solving SDP: \"<<elapsed.count()<<endl;\n\tcout<<\"Obj_value_partial_relaxation: \"<<M->primalObjValue()*norm_b*norm_C + obj_constant<<endl;\n\treturn 0;\n}\n\n\nvoid read_matrix(const char *filename, Matrix::t& result)  \n{\n\tint row, col;    \n\tint i = 0,j = 0;\t\n    ifstream fin(filename); \n\tif (!fin.is_open())\n\t{\n\t\tcout << \"Error opening file: \"<<filename;\n\t\texit(1);\n\t}\n\n\tstring line, aux;\n\t// First line must have in the first two positions the number of rows and columns\n\tgetline(fin, line);\n\tstringstream stream(line);\n\tgetline(stream,aux,',');\n\trow = stoi(aux);\t\t\n\tgetline(stream,aux,',');\n\tcol = stoi(aux);\n\t\n\tauto msubi = new_array_ptr<int, 1>(row*col);\n\tauto msubj = new_array_ptr<int, 1>(row*col);\n\tauto mcof  = new_array_ptr<double, 1>(row*col);\n\tint aux2 = 0;\n\twhile (getline(fin, line))\n   \t{\t\n\t\tstringstream stream(line);\n\t\twhile(stream.good())\n\t\t{\n\t\t\tgetline(stream,aux,',');\n\t\t\t(*msubi)[aux2] = i;\n\t\t\t(*msubj)[aux2] = j;\n\t\t\t(*mcof)[aux2] = stod(aux);\t\t\t\t\t\t\t\t\t\n\t\t\tj++;\n\t\t\taux2 = aux2 + 1;\n\t\t\tif (j == col)\n\t\t\t{\n\t\t\t\ti = i+1;\n\t\t\t\tj = 0;\n\t\t\t}\n\t\t}\n\t}\n\tresult = Matrix::sparse(row, col, msubi, msubj, mcof);\n}\n\nvoid read_matrix_sparse_format(const char *filename, Matrix::t& result)  \n{\n\t// reads symmetric  matrix in sparse format given as \n\t// n nnz\n\t// i_1 j_1 val_1\n\t// i_2 j_2 val_2\n\t// ...\n\t// i1_nnz j1_nnz val_nnz\n\t// where n is the dimension of the matrix, and nnz the non-zero elements.\n\t// It gives only the upper triangular values.\n\t\n\tint row, col;    \t\n\tstring val, i, j;\t\n    ifstream fin(filename); \n\tif (!fin.is_open())\n\t{\n\t\tcout << \"Error opening file: \"<<filename;\n\t\texit(1);\n\t}\n\n\tstring line, aux;\n\t// First line must have the dimension of the square matrix and the number of non-zeros\n\tgetline(fin, line);\n\tstringstream stream(line);\n\tgetline(stream,aux,' ');\n\trow = stoi(aux);\n\tcol = row;\n\tgetline(stream,aux,' ');\n\tint nnz = stoi(aux);\n\tauto msubi = new_array_ptr<int, 1>(2*nnz);\n\tauto msubj = new_array_ptr<int, 1>(2*nnz);\n\tauto mcof  = new_array_ptr<double, 1>(2*nnz);\n\tint aux2 = 0;\n\twhile(fin >> i >> j >> val)\n\t{\n\t\t(*msubi)[aux2] = stod(i)-1;\n\t\t(*msubj)[aux2] = stod(j)-1;\n\t\t(*msubi)[aux2+1] = stod(j)-1;\t\n\t\t(*msubj)[aux2+1] = stod(i)-1;\n\t\t(*mcof) [aux2] = stod(val);\n\t\t(*mcof) [aux2+1] = stod(val);\n\t\taux2 = aux2+2;\t\t\t\n\t}\n\t\n\tresult = Matrix::sparse(row, col, msubi, msubj, mcof);\n}\n", "meta": {"hexsha": "0f85801925ac09b9b0f2f3818e8cdffe78e25694", "size": 19648, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Partial_relaxation/maxcut_partial.cpp", "max_stars_repo_name": "cog-imperial/Partial-Lasserre-relaxation-sparse-maxcut", "max_stars_repo_head_hexsha": "b8f447ce40b85ce9a078587d9be2a9a7b1315e93", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-03-05T11:27:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T16:28:02.000Z", "max_issues_repo_path": "Partial_relaxation/maxcut_partial.cpp", "max_issues_repo_name": "cog-imperial/Partial-Lasserre-relaxation-sparse-maxcut", "max_issues_repo_head_hexsha": "b8f447ce40b85ce9a078587d9be2a9a7b1315e93", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Partial_relaxation/maxcut_partial.cpp", "max_forks_repo_name": "cog-imperial/Partial-Lasserre-relaxation-sparse-maxcut", "max_forks_repo_head_hexsha": "b8f447ce40b85ce9a078587d9be2a9a7b1315e93", "max_forks_repo_licenses": ["BSD-3-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.9512195122, "max_line_length": 123, "alphanum_fraction": 0.5680476384, "num_tokens": 5999, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321964553657, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.4664371113127161}}
{"text": "static bool eigen_did_assert = false;\n#define eigen_assert(X) if(!eigen_did_assert && !(X)){ std::cout << \"### Assertion raised in \" << __FILE__ << \":\" << __LINE__ << \":\\n\" #X << \"\\n### The following would happen without assertions:\\n\"; eigen_did_assert = true;}\n\n#include <iostream>\n#include <Eigen/Eigen>\n\n#ifndef M_PI\n#define M_PI 3.1415926535897932384626433832795\n#endif\n\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n  int data[] = {1,2,3,4,5,6,7,8,9};\nMap<RowVectorXi> v(data,4);\ncout << \"The mapped vector v is: \" << v << \"\\n\";\nnew (&v) Map<RowVectorXi>(data+4,5);\ncout << \"Now v is: \" << v << \"\\n\";\n  return 0;\n}\n", "meta": {"hexsha": "522101af031b676fd2e935a5c9be306d981ef2b8", "size": 666, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/snippets/compile_Map_placement_new.cpp", "max_stars_repo_name": "mousepawmedia/libdeps", "max_stars_repo_head_hexsha": "b004d58d5b395ceaf9fdc993cfb00e91334a5d36", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2021-02-27T11:00:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T10:31:46.000Z", "max_issues_repo_path": "doc/snippets/compile_Map_placement_new.cpp", "max_issues_repo_name": "mousepawmedia/libdeps", "max_issues_repo_head_hexsha": "b004d58d5b395ceaf9fdc993cfb00e91334a5d36", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-11-14T23:14:58.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-14T23:14:58.000Z", "max_forks_repo_path": "doc/snippets/compile_Map_placement_new.cpp", "max_forks_repo_name": "mousepawmedia/libdeps", "max_forks_repo_head_hexsha": "b004d58d5b395ceaf9fdc993cfb00e91334a5d36", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-03-13T13:28:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-05T02:26:02.000Z", "avg_line_length": 26.64, "max_line_length": 224, "alphanum_fraction": 0.6441441441, "num_tokens": 215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947425132315, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.4664371089065673}}
{"text": "//==================================================================================================\n/*!\n\n  Copyright 2015 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#include <boost/simd/function/scalar/predecessor.hpp>\n#include <simd_test.hpp>\n#include <boost/dispatch/meta/as_integer.hpp>\n#include <boost/simd/constant/inf.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/zero.hpp>\n#include <boost/simd/constant/eps.hpp>\n#include <boost/simd/constant/halfeps.hpp>\n#include <boost/simd/constant/valmin.hpp>\n#include <boost/simd/constant/valmax.hpp>\n#include <boost/simd/constant/bitincrement.hpp>\n#include <boost/simd/constant/two.hpp>\n#include <boost/simd/constant/four.hpp>\n#include <boost/simd/constant/mthree.hpp>\n\nSTF_CASE_TPL (\" predecessor real\",  STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::predecessor;\n  using r_t = decltype(predecessor(T()));\n\n  STF_TYPE_IS(r_t, T);\n\n  // specific values tests\n#ifndef STF_NO_INVALIDS\n  STF_EQUAL(predecessor(bs::Inf<T>()), bs::Valmax<r_t>());\n  STF_IEEE_EQUAL(predecessor(bs::Minf<T>()), bs::Nan<r_t>());\n  STF_IEEE_EQUAL(predecessor(bs::Nan<T>()), bs::Nan<r_t>());\n#endif\n  STF_EQUAL(predecessor(bs::Mone<T>()), bs::Mone<r_t>()-bs::Eps<r_t>());\n  STF_EQUAL(predecessor(bs::One<T>()), bs::One<r_t>()-bs::Halfeps<r_t>());\n  STF_EQUAL(predecessor(bs::Valmin<T>()), bs::Minf<r_t>());\n#if !defined(STF_NO_DENORMALS)\n  STF_EQUAL(predecessor(bs::Zero<T>()), -bs::Bitincrement<T>());\n#endif\n} // end of test for floating_\n\nSTF_CASE_TPL (\" predecessor ui \",  STF_UNSIGNED_INTEGRAL_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::predecessor;\n  using r_t = decltype(predecessor(T()));\n\n  // return type conformity test\n  STF_TYPE_IS(r_t, T);\n\n  // specific values tests\n  STF_EQUAL(predecessor(bs::One<T>()), bs::Zero<r_t>());\n  STF_EQUAL(predecessor(bs::Valmin<T>()), bs::Valmin<r_t>());\n  STF_EQUAL(predecessor(bs::Zero<T>()), bs::Zero<r_t>());\n} // end of test for unsigned_int_\n\nSTF_CASE_TPL (\" predecessor si\",  STF_SIGNED_INTEGRAL_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n\n  using bs::predecessor;\n\n  using r_t = decltype(predecessor(T()));\n\n  // return type conformity test\n  STF_TYPE_IS(r_t, T);\n\n  // specific values tests\n  STF_EQUAL(predecessor(bs::Mone<T>()), -bs::Two<r_t>());\n  STF_EQUAL(predecessor(bs::One<T>()), bs::Zero<r_t>());\n  STF_EQUAL(predecessor(bs::Valmin<T>()), bs::Valmin<r_t>());\n  STF_EQUAL(predecessor(bs::Zero<T>()), bs::Mone<r_t>());\n} // end of test for signed_int_\n\nSTF_CASE_TPL (\" predecessor real 2\",  STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::predecessor;\n\n  using iT = bd::as_integer_t<T>;\n  using r_t = decltype(predecessor(T(), iT()));\n\n  // return type conformity test\n  STF_TYPE_IS(r_t, T);\n\n#ifndef STF_NO_INVALIDS\n  STF_IEEE_EQUAL(predecessor(bs::Minf<T>(), bs::Two<iT>()), bs::Nan<r_t>());\n  STF_IEEE_EQUAL(predecessor(bs::Nan<T>(), bs::Two<iT>()), bs::Nan<r_t>());\n#endif\n  STF_EQUAL(predecessor(bs::Mone<T>(), bs::Two<iT>()), bs::Mone<r_t>()-bs::Eps<r_t>()-bs::Eps<r_t>());\n  STF_EQUAL(predecessor(bs::One<T>(), bs::Two<iT>()), bs::One<r_t>()-bs::Eps<r_t>());\n  STF_IEEE_EQUAL(predecessor(bs::Valmin<T>(), bs::Two<iT>()), bs::Nan<r_t>());\n  STF_IEEE_EQUAL(predecessor(bs::Valmin<T>(), bs::Four<iT>()), bs::Nan<r_t>());\n#if !defined(STF_NO_DENORMALS)\n  STF_EQUAL(predecessor(bs::Zero<T>(), bs::Two<iT>()), -bs::Bitincrement<r_t>()-bs::Bitincrement<r_t>());\n#endif\n}\n\nSTF_CASE_TPL (\" predecessorui_2\",  STF_UNSIGNED_INTEGRAL_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::predecessor;\n  using iT = bd::as_integer_t<T>;\n  using r_t = decltype(predecessor(T(), iT()));\n\n  // return type conformity test\n  STF_TYPE_IS(r_t, T);\n  STF_EQUAL(predecessor(bs::Four<T>(), bs::Two<iT>()), bs::Two<r_t>());\n  STF_EQUAL(predecessor(bs::One<T>(), bs::Two<iT>()), bs::Zero<r_t>());\n  STF_EQUAL(predecessor(bs::Valmin<T>(), bs::Two<iT>()), bs::Valmin<r_t>());\n  STF_EQUAL(predecessor(bs::Valmin<T>(), bs::Four<iT>()), bs::Valmin<r_t>());\n}\n\nSTF_CASE_TPL (\" predecessorsi_2\",  STF_SIGNED_INTEGRAL_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::predecessor;\n  using iT = bd::as_integer_t<T>;\n  using r_t = decltype(predecessor(T(), iT()));\n\n  // return type conformity test\n  STF_TYPE_IS(r_t, T);\n  STF_EQUAL(predecessor(bs::Mone<T>(), bs::Two<iT>()), bs::Mthree<r_t>());\n  STF_EQUAL(predecessor(bs::One<T>(), bs::Two<iT>()), bs::Mone<r_t>());\n  STF_EQUAL(predecessor(bs::Valmin<T>(), bs::Two<iT>()), bs::Valmin<r_t>());\n  STF_EQUAL(predecessor(bs::Valmin<T>(), bs::Four<iT>()), bs::Valmin<r_t>());\n} // end of test for signed_int_\n", "meta": {"hexsha": "799d7281b19d05bba2c01e9659c43f1ac6260561", "size": 5107, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/scalar/predecessor.cpp", "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": "test/function/scalar/predecessor.cpp", "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": "test/function/scalar/predecessor.cpp", "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": 35.9647887324, "max_line_length": 105, "alphanum_fraction": 0.6512629724, "num_tokens": 1539, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.6548947357776796, "lm_q1q2_score": 0.46643710810952477}}
{"text": "//==================================================================================================\n/**\n  EVE - Expressive Vector Engine\n  Copyright : EVE Contributors & Maintainers\n  SPDX-License-Identifier: MIT\n**/\n//==================================================================================================\n#include \"test.hpp\"\n#include <boost/math/special_functions/hermite.hpp>\n#include <eve/function/hermite.hpp>\n#include <eve/function/diff/hermite.hpp>\n\n//==================================================================================================\n//== Types tests\n//==================================================================================================\nEVE_TEST_TYPES( \"Check return types of hermite on wide\"\n        , eve::test::simd::ieee_reals\n\n        )\n<typename T>(eve::as<T>)\n{\n  using v_t = eve::element_type_t<T>;\n  using wi_t = eve::as_integer_t<T>;\n  using i_t  = eve::as_integer_t<v_t>;\n  TTS_EXPR_IS( eve::hermite(i_t(), T())  , T);\n  TTS_EXPR_IS( eve::hermite(wi_t(), T())  , T);\n  TTS_EXPR_IS( eve::hermite(i_t(), v_t())  , v_t);\n  TTS_EXPR_IS( eve::hermite(wi_t(), v_t())  , T);\n\n};\n\n//==================================================================================================\n//== hermite tests\n//==================================================================================================\nEVE_TEST( \"Check behavior of hermite on wide\"\n        , eve::test::simd::ieee_reals\n        , eve::test::generate(eve::test::between(-1.0, 1.0), eve::test::as_integer(eve::test::ramp(0)))\n        )\n  <typename T, typename I>(T const& a0,I const & i0)\n{\n using v_t = eve::element_type_t<T>;\n  auto eve__hermitev  =  [](auto n, auto x) { return eve::hermite(n, x); };\n  for(unsigned int n=0; n < 5; ++n)\n  {\n    auto boost_hermite =  [&](auto i, auto) { return boost::math::hermite(n, a0.get(i)); };\n    TTS_ULP_EQUAL(eve__hermitev(n, a0), T(boost_hermite), 16);\n  }\n  auto boost_hermitev =  [&](auto i, auto) { return boost::math::hermite(i0.get(i), a0.get(i)); };\n  TTS_ULP_EQUAL(eve__hermitev(i0    , a0), T(boost_hermitev), 16);\n  for(unsigned int j=0; j < eve::cardinal_v<T>; ++j)\n  {\n    auto boost_hermite2 =  [&](auto i, auto) { return boost::math::hermite(i0.get(i), a0.get(j)); };\n    TTS_ULP_EQUAL(eve__hermitev(i0 , a0.get(j)), T(boost_hermite2), 32);\n  }\n  for(unsigned int j=0; j < eve::cardinal_v<T>; ++j)\n  {\n    for(unsigned int n=0; n < eve::cardinal_v<T>; ++n)\n    {\n      TTS_ULP_EQUAL(eve__hermitev(i0.get(j) , a0.get(n)), v_t(boost::math::hermite(i0.get(j), a0.get(n))), 32);\n    }\n  }\n};\n\n\n//==================================================================================================\n//== hermite diff tests\n//==================================================================================================\nEVE_TEST( \"Check behavior of diff hermite on wide\"\n        , eve::test::simd::ieee_reals\n        , eve::test::generate(eve::test::between(-1.0, 1.0), eve::test::as_integer(eve::test::ramp(0)))\n        )\n  <typename T, typename I>(T const& a0,I const & i0)\n{\n  auto boost_hermderiv = [](auto n,  auto x){return 2*x*boost::math::hermite(n, x)-boost::math::hermite(n+1, x); };\n\n  using v_t = eve::element_type_t<T>;\n  auto eve__hermitev  =  [](auto n, auto x) { return eve::diff(eve::hermite)(n, x); };\n  for(unsigned int n=0; n < 5; ++n)\n  {\n    auto boost_hermite =  [&](auto i, auto) { return boost_hermderiv(n, a0.get(i)); };\n    TTS_ULP_EQUAL(eve__hermitev(n, a0), T(boost_hermite), 32);\n  }\n  auto boost_hermitev =  [&](auto i, auto) { return boost_hermderiv(i0.get(i), a0.get(i)); };\n  TTS_ULP_EQUAL(eve__hermitev(i0    , a0), T(boost_hermitev), 32);\n  for(unsigned int j=0; j < eve::cardinal_v<T>; ++j)\n  {\n    auto boost_hermite2 =  [&](auto i, auto) { return boost_hermderiv(i0.get(i), a0.get(j)); };\n    TTS_ULP_EQUAL(eve__hermitev(i0 , a0.get(j)), T(boost_hermite2), 48);\n  }\n  for(unsigned int j=0; j < eve::cardinal_v<T>; ++j)\n  {\n    for(unsigned int n=0; n < eve::cardinal_v<T>; ++n)\n    {\n      TTS_ULP_EQUAL(eve__hermitev(i0.get(j) , a0.get(n)), v_t(boost_hermderiv(i0.get(j), a0.get(n))), 100);\n    }\n  }\n};\n", "meta": {"hexsha": "a09af8241e62c517c8c8c1808e431dc06bbd9476", "size": 4117, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/module/polynomial/hermite.cpp", "max_stars_repo_name": "the-moisrex/eve", "max_stars_repo_head_hexsha": "80b52663eefee11460abb0aedf4158a5067cf7dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 340.0, "max_stars_repo_stars_event_min_datetime": "2020-09-16T21:12:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T15:40:33.000Z", "max_issues_repo_path": "test/unit/module/polynomial/hermite.cpp", "max_issues_repo_name": "the-moisrex/eve", "max_issues_repo_head_hexsha": "80b52663eefee11460abb0aedf4158a5067cf7dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 383.0, "max_issues_repo_issues_event_min_datetime": "2020-09-17T06:56:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T15:58:53.000Z", "max_forks_repo_path": "test/unit/module/polynomial/hermite.cpp", "max_forks_repo_name": "the-moisrex/eve", "max_forks_repo_head_hexsha": "80b52663eefee11460abb0aedf4158a5067cf7dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 28.0, "max_forks_repo_forks_event_min_datetime": "2021-02-27T23:11:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T12:31:29.000Z", "avg_line_length": 42.0102040816, "max_line_length": 115, "alphanum_fraction": 0.4981782852, "num_tokens": 1192, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.46643710810952477}}
{"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#ifndef NORMAL_DISTRIBUTION_PARAMETER_HPP_\n#define NORMAL_DISTRIBUTION_PARAMETER_HPP_\n\n#include <boost/property_tree/ptree.hpp>\n#include \"clotho/utility/clotho_strings.hpp\"\n\n\ntemplate < class RealType >\nstruct normal_distribution_parameter {\n    static constexpr RealType   DEFAULT_MEAN = 0.0;\n    static constexpr RealType   DEFAULT_SIGMA = 1.0;\n\n    RealType m_mean, m_sigma;\n\n    normal_distribution_parameter( RealType m = DEFAULT_MEAN, RealType s = DEFAULT_SIGMA ):\n        m_mean(m)\n        , m_sigma(s)\n    {}\n\n    normal_distribution_parameter( boost::property_tree::ptree & config ) :\n        m_mean( DEFAULT_MEAN )\n        , m_sigma( DEFAULT_SIGMA )\n    {\n        m_mean = config.get< RealType >( MEAN_K, m_mean );\n        m_sigma = config.get< RealType >( SIGMA_K, m_sigma );\n\n        config.put( MEAN_K, m_mean );\n        config.put( SIGMA_K, m_sigma );\n    }\n\n    void write_parameter( boost::property_tree::ptree & l ) {\n        l.put( MEAN_K, m_mean );\n        l.put( SIGMA_K, m_sigma );\n    }\n\n    virtual ~normal_distribution_parameter() {}\n};\n\n#endif  // NORMAL_DISTRIBUTION_PARAMETER_HPP_\n", "meta": {"hexsha": "e49a877a0d3a675db6fecb4d45f7ced046896607", "size": 1719, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/clotho/random/normal_distribution_parameter.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/random/normal_distribution_parameter.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/random/normal_distribution_parameter.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": 32.4339622642, "max_line_length": 91, "alphanum_fraction": 0.695753345, "num_tokens": 412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.46643710731248195}}
{"text": "//==================================================================================================\n/*!\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#include <boost/simd/function/scalar/sincospi.hpp>\n#include <scalar_test.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/minf.hpp>\n#include <boost/simd/constant/nan.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/mone.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/constant/mzero.hpp>\n#include <boost/simd/function/sinpi.hpp>\n#include <boost/simd/function/cospi.hpp>\n\n\nSTF_CASE_TPL (\" sincospi\",  STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n\n  using bs::sincospi;\n  T a[] = {bs::Zero<T>(), bs::One<T>(), T(120), T(180),\n           T(90), bs::Inf<T>(), bs::Minf<T>(), bs::Nan<T>()};\n  size_t N =  sizeof(a)/sizeof(T);\n\n  STF_EXPR_IS( (sincospi(T()))\n             , (std::pair<T,T>)\n             );\n\n  {\n    for(size_t i=0; i < N; ++i)\n    {\n      std::pair<T,T> p = sincospi(a[i]);\n      STF_IEEE_EQUAL(p.first,  bs::sinpi(a[i]));\n      STF_IEEE_EQUAL(p.second, bs::cospi(a[i]));\n      std::pair<T,T> q = bs::restricted_(sincospi)(a[i]);\n      STF_IEEE_EQUAL(q.first,  bs::restricted_(bs::sinpi)(a[i]));\n      STF_IEEE_EQUAL(q.second, bs::restricted_(bs::cospi)(a[i]));\n    }\n  }\n\n}\n", "meta": {"hexsha": "28d1b1762a60b24a0dc3e0ba53f4e6ac78b28fe7", "size": 1574, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/scalar/sincospi.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": "test/function/scalar/sincospi.cpp", "max_issues_repo_name": "remymuller/boost.simd", "max_issues_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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/function/scalar/sincospi.cpp", "max_forks_repo_name": "remymuller/boost.simd", "max_forks_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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": 31.48, "max_line_length": 100, "alphanum_fraction": 0.5552731893, "num_tokens": 434, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321720225278, "lm_q2_score": 0.6548947425132314, "lm_q1q2_score": 0.4664371049063329}}
{"text": "#ifndef VOLINT_H\r\n#define VOLINT_H\r\n\r\n        /*******************************************************\r\n        *                                                      *\r\n        *  volInt.c                                            *\r\n        *                                                      *\r\n        *  This code computes volume integrals needed for      *\r\n        *  determining mass properties of polyhedral bodies.   *\r\n        *                                                      *\r\n        *  For more information, see the accompanying README   *\r\n        *  file, and the paper                                 *\r\n        *                                                      *\r\n        *  Brian Mirtich, \"Fast and Accurate Computation of    *\r\n        *  Polyhedral Mass Properties,\" journal of graphics    *\r\n        *  tools, volume 1, number 1, 1996.                    *\r\n        *                                                      *\r\n        *  This source code is public domain, and may be used  *\r\n        *  in any way, shape or form, free of charge.          *\r\n        *                                                      *\r\n        *  Copyright 1995 by Brian Mirtich                     *\r\n        *                                                      *\r\n        *  mirtich@cs.berkeley.edu                             *\r\n        *  http://www.cs.berkeley.edu/~mirtich                 *\r\n        *                                                      *\r\n        *******************************************************/\r\n\r\n/*\r\n        Revision history\r\n\r\n        26 Jan 1996     Program creation.\r\n\r\n         3 Aug 1996     Corrected bug arising when polyhedron density\r\n                        is not 1.0.  Changes confined to function main().\r\n                        Thanks to Zoran Popovic for catching this one.\r\n\r\n        27 May 1997     Corrected sign error in translation of inertia\r\n                        product terms to center of mass frame.  Changes \r\n                        confined to function main().  Thanks to \r\n                        Chris Hecker.\r\n*/\r\n\r\n\r\n\r\n// Modified for tractor_converter\r\n\r\n\r\n\r\n#include <boost/container_hash/hash.hpp>\r\n\r\n#include <stdexcept>\r\n\r\n#include <algorithm>\r\n#include <cmath>\r\n#include <utility>\r\n#include <limits>\r\n#include <vector>\r\n#include <deque>\r\n#include <map>\r\n#include <unordered_map>\r\n#include <unordered_set>\r\n#include <string>\r\n#include <functional>\r\n#include <numeric>\r\n#include <iterator>\r\n\r\n\r\n\r\nnamespace volInt{\r\n\r\n\r\n\r\nnamespace exception{\r\n  struct negative_volume : public virtual std::runtime_error\r\n  {\r\n    using std::runtime_error::runtime_error;\r\n  };\r\n  struct zero_volume : public virtual std::runtime_error\r\n  {\r\n    using std::runtime_error::runtime_error;\r\n  };\r\n} // namespace exception\r\n\r\n\r\n\r\nnamespace invalid{\r\n  const int vert_id =         -1;\r\n  const int vertNorm_id =     -1;\r\n\r\n  const int bodyColorOffset = -1;\r\n  const int bodyColorShift =  -1;\r\n\r\n  const int ref_vert_ind =    -1;\r\n\r\n  const int wheel_id =        -1;\r\n  const int weapon_id =       -1;\r\n  const int wheel_weapon_id = -1;\r\n} // namespace invalid\r\n\r\n\r\n\r\nenum class rotation_axis : std::size_t {x = 0, y = 1, z = 2};\r\n\r\n\r\n\r\ndouble degrees_to_radians(double degrees);\r\n\r\ndouble sicher_angle_to_radians(int sicher_angle);\r\nint radians_to_sicher_angle(double radians);\r\n\r\nvoid rotate_point_by_axis(std::vector<double> &point,\r\n                          double angle_sin,\r\n                          double angle_cos,\r\n                          rotation_axis axis);\r\nvoid rotate_point_by_axis(std::vector<double> &point,\r\n                          double angle,\r\n                          rotation_axis axis);\r\n\r\n\r\n\r\nstd::vector<double> vector_scale(double norm, const std::vector<double> &vec);\r\nvoid vector_scale_self(double norm, std::vector<double> &vec);\r\n\r\nvoid vector_invert_self(std::vector<double> &vec);\r\n\r\nstd::vector<double> vector_plus(const std::vector<double> &first,\r\n                                const std::vector<double> &second);\r\nvoid vector_plus_self(std::vector<double> &first,\r\n                      const std::vector<double> &second);\r\nstd::vector<double> vector_minus(const std::vector<double> &first,\r\n                                 const std::vector<double> &second);\r\nvoid vector_minus_self(std::vector<double> &first,\r\n                       const std::vector<double> &second);\r\n\r\nstd::vector<double> vector_multiply(const std::vector<double> &first,\r\n                                    const std::vector<double> &second);\r\nvoid vector_multiply_self(std::vector<double> &first,\r\n                          const std::vector<double> &second);\r\nstd::vector<double> vector_multiply(const std::vector<double> &vec,\r\n                                    double num);\r\nvoid vector_multiply_self(std::vector<double> &vec,\r\n                          double num);\r\n\r\nstd::vector<double> vector_divide(const std::vector<double> &first,\r\n                                  const std::vector<double> &second);\r\nvoid vector_divide_self(std::vector<double> &first,\r\n                        const std::vector<double> &second);\r\nstd::vector<double> vector_divide(const std::vector<double> &vec,\r\n                                  double num);\r\nvoid vector_divide_self(std::vector<double> &vec,\r\n                        double num);\r\n\r\ndouble vector_length(const std::vector<double> &vec);\r\n\r\ndouble vector_length_between(\r\n  const std::vector<double> &first,\r\n  const std::vector<double> &second);\r\n\r\ndouble vector_dot_product(\r\n  const std::vector<double> &first,\r\n  const std::vector<double> &second);\r\n\r\ndouble vector_angle(\r\n  const std::vector<double> &first,\r\n  const std::vector<double> &second);\r\n\r\nstd::vector<double> vector_2d_divide(const std::vector<double> &vec,\r\n                                     double num);\r\n\r\ndouble vector_2d_length(const std::vector<double> &vec);\r\n\r\n\r\n\r\n\r\n\r\ntemplate<typename T>\r\nstd::vector<std::vector<T>> get_groups_of_connected_items(\r\n  std::vector<T> orig_vec,\r\n  std::function<bool(T first, T second)> check_connected_func)\r\n{\r\n  std::vector<std::vector<T>> groups;\r\n  std::size_t orig_vec_size = orig_vec.size();\r\n  groups.reserve(orig_vec_size);\r\n\r\n  std::unordered_set<T> items_to_check(orig_vec.begin(), orig_vec.end());\r\n\r\n  for(std::size_t cur_group_id = 0; !items_to_check.empty(); ++cur_group_id)\r\n  {\r\n    groups.push_back(std::vector<T>());\r\n    groups[cur_group_id].reserve(orig_vec_size);\r\n\r\n    T cur_item = *items_to_check.begin();\r\n    items_to_check.erase(items_to_check.begin());\r\n\r\n    std::unordered_set<T> connected_items_to_check({cur_item});\r\n    connected_items_to_check.reserve(orig_vec_size);\r\n\r\n    // Iterating over first element in group and all connected elements.\r\n    while(!connected_items_to_check.empty())\r\n    {\r\n      T cur_item = *connected_items_to_check.begin();\r\n      connected_items_to_check.erase(connected_items_to_check.begin());\r\n      groups[cur_group_id].push_back(cur_item);\r\n\r\n      std::unordered_set<T> new_connected_items;\r\n      new_connected_items.reserve(orig_vec_size);\r\n\r\n      for(auto cur_item_to_cmp : items_to_check)\r\n      {\r\n        if(check_connected_func(cur_item, cur_item_to_cmp))\r\n        {\r\n          new_connected_items.insert(cur_item_to_cmp);\r\n        }\r\n      }\r\n\r\n      // Erasing all newly found connected items from items_to_check.\r\n      for(auto new_connected_item : new_connected_items)\r\n      {\r\n        items_to_check.erase(items_to_check.find(new_connected_item));\r\n      }\r\n\r\n      connected_items_to_check.insert(new_connected_items.begin(),\r\n                                      new_connected_items.end());\r\n    }\r\n  }\r\n\r\n  groups.shrink_to_fit();\r\n\r\n  return groups;\r\n}\r\n\r\n\r\n\r\nnamespace calc_norms{\r\n  unsigned long long int normal_to_key(const std::vector<double> &norm);\r\n  std::vector<double> key_to_normal(unsigned long long int key);\r\n} // namespace calc_norms\r\n\r\n\r\n\r\n// ============================================================================\r\n// Macros.\r\n// ============================================================================\r\n\r\n#define VOLINT_SQR(x)  ((x) * (x))\r\n#define VOLINT_CUBE(x) ((x) * (x) * (x))\r\n\r\n// ============================================================================\r\n// Constants.\r\n// ============================================================================\r\n\r\n#define VOLINT_X 0\r\n#define VOLINT_Y 1\r\n#define VOLINT_Z 2\r\n\r\n\r\n\r\nconst double vector_scale_val = 1.0;\r\n\r\n\r\n\r\n//// VANGERS SOURCE\r\n//// How angle conversions work in Vangers code.\r\n//#define M_PI 3.14159265358979323846\r\n//\r\n//Pi_len = 11\r\n//const int Pi = 1 << Pi_len;\r\n//2048\r\n//\r\n//#define GTOR(x) (double(x) * (M_PI / double(Pi)))\r\n//#define RTOG(x) (round(x *   (double(Pi) / M_PI)))\r\n\r\n#ifndef M_PI\r\n  #define M_PI 3.14159265358979323846\r\n#endif\r\nconst int sicher_angle_Pi = 2048; // \"1 << Pi_len\" where \"Pi_len = 11\".\r\n\r\n\r\n\r\nconst unsigned int min_float_precision = 3;\r\nconst double distinct_distance = 1.0 / std::pow(10, min_float_precision);\r\nconst double sqr_distinct_distance = VOLINT_SQR(distinct_distance);\r\nconst double density = 1.0;\r\n\r\nconst std::size_t axes_num = 3;\r\nconst std::size_t axes_2d_num = 2;\r\n\r\nconst std::vector<std::vector<std::size_t>> axes_by_plane =\r\n  {\r\n    {1, 2}, // x axis.\r\n    {0, 2}, // y axis.\r\n    {0, 1}, // z axis.\r\n  };\r\n\r\nconst std::vector<std::vector<std::size_t>> axes_by_plane_continuous =\r\n  {\r\n    {1, 2}, // x axis.\r\n    {2, 0}, // y axis.\r\n    {0, 1}, // z axis.\r\n  };\r\n\r\nnamespace color_ids {\r\n  const unsigned int zero_reserved =    0;\r\n  const unsigned int body =             1;\r\n  const unsigned int max_colors_ids =   25;\r\n  const unsigned int invalid_color_id = 1000003;\r\n} // namespace color_ids\r\n\r\nnamespace calc_norms{\r\n  const std::size_t expected_connected_polygons_per_vertex = 10;\r\n  const std::size_t expected_connected_polygons_per_polygon = 10;\r\n\r\n  const double to_integer_multiply = std::pow(10, min_float_precision);\r\n  const unsigned long long int upper_bound =\r\n    std::round(2 * vector_scale_val * to_integer_multiply);\r\n\r\n  const unsigned long long int upper_bound_shift =\r\n    static_cast<unsigned long long int>(std::log2(upper_bound)) + 1;\r\n\r\n  const std::vector<unsigned long long int> to_key_shift =\r\n    {\r\n      0,\r\n      upper_bound_shift,\r\n      2 * upper_bound_shift,\r\n    };\r\n\r\n  const unsigned long long int key_to_normal_mask =\r\n    (1 << upper_bound_shift) - 1;\r\n} // namespace calc_norms\r\n\r\nnamespace generate_bound{\r\n  typedef std::deque<std::size_t> layer_vert_inds;\r\n  typedef std::map<std::size_t, layer_vert_inds> layers_inds_of_axis;\r\n  typedef std::vector<layers_inds_of_axis> layers_inds_by_axis;\r\n\r\n  const std::size_t expected_inter_verts_per_edge = 10;\r\n\r\n  const std::size_t plane_extrs_num = 4;\r\n  // Assumes that get_planes_4_extreme_points() generates points in this order.\r\n  //   y\r\n  // 3   2\r\n  //       x\r\n  // 0   1\r\n  const std::vector<std::vector<std::size_t>> extr_lines =\r\n    {\r\n      {0, 1},\r\n      {1, 2},\r\n      {2, 3},\r\n      {3, 0},\r\n      {0, 1, 2, 3},\r\n    };\r\n  const std::size_t plane_middle_extr_num = extr_lines.size();\r\n\r\n\r\n  const std::size_t end_z_layers_num_mechos = 2;\r\n  const std::size_t end_z_layers_num_other = 3;\r\n\r\n  enum class model_type{mechos, other};\r\n\r\n  namespace model{\r\n\r\n    const std::size_t verts_per_poly = 4;\r\n\r\n    const std::vector<std::size_t> zero_reserved_face_inds = {4, 5, 6, 7};\r\n\r\n    const std::size_t z_layers_num = 3;\r\n    const std::size_t num_verts_per_z_layer = 9;\r\n    const std::size_t num_verts = z_layers_num * num_verts_per_z_layer;\r\n    // 6 sides * 4 polygons per side.\r\n    const std::size_t num_faces = 6 * 4;\r\n\r\n    //    y\r\n    // e3 m2 e2\r\n    // m3 m4 m1 x\r\n    // e0 m0 e1\r\n    // Converting to:\r\n    //   y\r\n    // 0 1 2\r\n    // 3 4 5 x\r\n    // 6 7 8\r\n    const std::vector<std::size_t> extr_to_end =   {6, 8, 2, 0};\r\n    const std::vector<std::size_t> middle_to_end = {7, 5, 1, 3, 4};\r\n\r\n\r\n    const std::vector<std::vector<int>> face_ind_to_vert_inds =\r\n      {\r\n        // Getting top and low sides.\r\n        // top\r\n        // <-\r\n        //  /\\\r\n        // 0 1 2\r\n        // 3 4 5\r\n        // 6 7 8\r\n        {0, 3, 4, 1},\r\n        {1, 4, 5, 2},\r\n        {3, 6, 7, 4},\r\n        {4, 7, 8, 5},\r\n        // low\r\n        // ->\r\n        //  \\/\r\n        // 18 19 20\r\n        // 21 22 23\r\n        // 24 25 26\r\n        {18, 19, 22, 21},\r\n        {19, 20, 23, 22},\r\n        {21, 22, 25, 24},\r\n        {22, 23, 26, 25},\r\n\r\n\r\n        // Getting front and back sides.\r\n        // back\r\n        // <-\r\n        //  /\\\r\n        // 6  7  8\r\n        // 15 16 17\r\n        // 24 25 26\r\n        {6,  15, 16, 7},\r\n        {7,  16, 17, 8},\r\n        {15, 24, 25, 16},\r\n        {16, 25, 26, 17},\r\n        // front\r\n        // ->\r\n        //  \\/\r\n        // 0  1  2\r\n        // 9  10 11\r\n        // 18 19 20\r\n        {0,  1,  10, 9},\r\n        {1,  2,  11, 10},\r\n        {9,  10, 19, 18},\r\n        {10, 11, 20, 19},\r\n\r\n\r\n\r\n        // Getting left and right sides.\r\n        // left\r\n        // <-\r\n        //  /\\\r\n        // 0  3  6\r\n        // 9  12 15\r\n        // 18 21 24\r\n        {0,  9,  12, 3},\r\n        {3,  12, 15, 6},\r\n        {9,  18, 21, 12},\r\n        {12, 21, 24, 15},\r\n        // right\r\n        // ->\r\n        //  \\/\r\n        // 2  5  8\r\n        // 11 14 17\r\n        // 20 23 26\r\n        {2,  5,  14, 11},\r\n        {5,  8,  17, 14},\r\n        {11, 14, 23, 20},\r\n        {14, 17, 26, 23},\r\n      };\r\n\r\n    // low\r\n    //        y\r\n    //     18 19 20\r\n    // -x  21 22 23  x\r\n    //     24 25 26\r\n    //       -y\r\n    const std::vector<std::vector<std::size_t>> min_verts_to_adjust_by_wheel =\r\n      {\r\n        {18, 21, 24}, // -x\r\n        {24, 25, 26}, // -y\r\n      };\r\n    const std::vector<std::vector<std::size_t>> max_verts_to_adjust_by_wheel =\r\n      {\r\n        {20, 23, 26}, // x\r\n        {18, 19, 20}, // y\r\n      };\r\n    const std::unordered_map<std::size_t, std::vector<std::size_t>>\r\n      min_layer_verts_to_center_by_extremes =\r\n        {\r\n          {22, {18, 20, 24, 26}},\r\n          {19, {18, 20}},\r\n          {23, {20, 26}},\r\n          {25, {24, 26}},\r\n          {21, {18, 24}},\r\n        };\r\n  } // namespace model\r\n} // namespace generate_bound\r\n\r\n// ============================================================================\r\n// Data structures.\r\n// ============================================================================\r\n\r\nstruct model_extreme_points\r\n{\r\n\r\n  model_extreme_points();\r\n  model_extreme_points(const std::vector<double> &max,\r\n                       const std::vector<double> &min);\r\n  model_extreme_points(std::vector<double> &&max, std::vector<double> &&min);\r\n\r\n  std::vector<double>       &max();\r\n  const std::vector<double> &max() const;\r\n  std::vector<double>       &min();\r\n  const std::vector<double> &min() const;\r\n\r\n  double xmax() const;\r\n  double ymax() const;\r\n  double zmax() const;\r\n\r\n  double xmin() const;\r\n  double ymin() const;\r\n  double zmin() const;\r\n\r\n  void set_xmax(double new_xmax);\r\n  void set_ymax(double new_ymax);\r\n  void set_zmax(double new_zmax);\r\n\r\n  void set_xmin(double new_xmin);\r\n  void set_ymin(double new_ymin);\r\n  void set_zmin(double new_zmin);\r\n\r\n  void get_most_extreme_cmp_cur(const model_extreme_points &other);\r\n  void get_most_extreme_cmp_cur(const std::vector<double>  &point);\r\n  void get_most_extreme(const std::vector<std::vector<double>> &points);\r\n\r\n  std::vector<double> get_center();\r\n\r\n  std::pair<std::vector<double>, std::vector<double>> extreme_points_pair;\r\n\r\n};\r\n\r\nstruct model_offset\r\n{\r\n\r\n  model_offset();\r\n  model_offset(const std::vector<double> &offset_point_arg);\r\n  model_offset(std::vector<double>      &&offset_point_arg);\r\n\r\n  double x_off() const;\r\n  double y_off() const;\r\n  double z_off() const;\r\n\r\n  void set_x_off(double new_x_off);\r\n  void set_y_off(double new_y_off);\r\n  void set_z_off(double new_z_off);\r\n\r\n  std::vector<double> offset_point;\r\n\r\n};\r\n\r\ntypedef struct face\r\n{\r\n  face(int numVerts_arg);\r\n\r\n  int numVerts;\r\n  unsigned int color_id;\r\n  int wheel_id;\r\n  int weapon_id;\r\n  std::vector<double> norm;\r\n  double w;\r\n  std::vector<int> verts;\r\n  std::vector<int> vertNorms;\r\n} FACE;\r\n\r\ntypedef struct polyhedron\r\n{\r\n\r\n  polyhedron();\r\n  polyhedron(\r\n    int numVerts_arg,\r\n    int numVertNorms_arg,\r\n    int numFaces_arg,\r\n    int verts_per_poly_arg);\r\n\r\n  void invertVertNorms();\r\n  void reverse_polygons_orientation();\r\n\r\n  std::vector<double> face_calc_normal(std::size_t face_ind);\r\n  double face_calc_offset_w(           std::size_t face_ind);\r\n  void faces_calc_params(); // Must be called again if model was moved.\r\n  void faces_calc_params_inv_neg_vol();\r\n\r\n  double get_vertex_angle(std::size_t face_ind, std::size_t vert_ind);\r\n\r\n  void recalc_vertNorms(double max_smooth_angle);\r\n\r\n  double check_volume();\r\n\r\n  void get_extreme_points();\r\n\r\n\r\n  std::vector<double> get_model_center();\r\n\r\n  void move_model_to_point(const std::vector<double> &point);\r\n  void move_model_to_point_inv_neg_vol(const std::vector<double> &point);\r\n\r\n  void move_coord_system_to_point(const std::vector<double> &point);\r\n  void move_coord_system_to_point_inv_neg_vol(\r\n    const std::vector<double> &point);\r\n  void move_coord_system_to_center();\r\n\r\n  void rotate_by_axis(double angle, rotation_axis axis);\r\n\r\n  void set_color_id(unsigned int new_color_id,\r\n                    int new_wheel_id =  invalid::wheel_id,\r\n                    int new_weapon_id = invalid::weapon_id);\r\n\r\n\r\n  bool find_ref_points();\r\n\r\n\r\n  void calculate_rmax();\r\n  void calculate_c3d_properties();\r\n\r\n\r\n  std::vector<std::vector<std::vector<double>>>\r\n    get_planes_4_extreme_points() const;\r\n  static std::vector<std::unordered_map<std::size_t, double>>\r\n    get_verts_plane_lengths_rel_points(\r\n      std::size_t perpendicular_axis,\r\n      const std::vector<std::vector<double>> &verts_arg,\r\n      const std::vector<std::vector<double>> &points_2d,\r\n      const generate_bound::layer_vert_inds &vert_inds);\r\n  static generate_bound::layer_vert_inds get_min_length_layer_points(\r\n    const std::vector<std::unordered_map<std::size_t, double>> &\r\n      verts_plane_lengths_rel_points);\r\n  static double get_plane_area_from_points(\r\n    std::size_t perpendicular_axis,\r\n    const std::vector<std::vector<double>> &verts_arg,\r\n    const generate_bound::layer_vert_inds &vert_inds);\r\n  static std::vector<std::vector<double>> get_extr_middle_points(\r\n    std::size_t perpendicular_axis,\r\n    const std::vector<std::vector<double>> &verts_arg,\r\n    const generate_bound::layer_vert_inds &layer_extrs);\r\n  polyhedron extr_inds_to_bound(\r\n    const std::vector<std::vector<double>> &verts_arg,\r\n    const generate_bound::layers_inds_of_axis &extr_inds,\r\n    const generate_bound::layers_inds_of_axis &middle_inds,\r\n    generate_bound::model_type type,\r\n    const model_extreme_points *wheel_params_extremes = nullptr) const;\r\n  polyhedron generate_bound_model(\r\n    const generate_bound::model_type type,\r\n    const std::size_t layers_num,\r\n    const double area_threshold_multiplier,\r\n    const model_extreme_points *wheel_params_extremes = nullptr) const;\r\n\r\n  std::pair<std::vector<double>, std::vector<double>> &extreme_points_pair();\r\n  const std::pair<std::vector<double>, std::vector<double>> &\r\n    extreme_points_pair() const;\r\n  std::vector<double>       &max_point();\r\n  const std::vector<double> &max_point() const;\r\n  std::vector<double>       &min_point();\r\n  const std::vector<double> &min_point() const;\r\n\r\n  double xmax() const;\r\n  double ymax() const;\r\n  double zmax() const;\r\n\r\n  double xmin() const;\r\n  double ymin() const;\r\n  double zmin() const;\r\n\r\n  void set_xmax(double new_xmax);\r\n  void set_ymax(double new_ymax);\r\n  void set_zmax(double new_zmax);\r\n\r\n  void set_xmin(double new_xmin);\r\n  void set_ymin(double new_ymin);\r\n  void set_zmin(double new_zmin);\r\n\r\n\r\n  std::vector<double>       &offset_point();\r\n  const std::vector<double> &offset_point() const;\r\n\r\n  double x_off() const;\r\n  double y_off() const;\r\n  double z_off() const;\r\n\r\n  void set_x_off(double new_x_off);\r\n  void set_y_off(double new_y_off);\r\n  void set_z_off(double new_z_off);\r\n\r\n\r\n  int numVerts, numVertNorms, numFaces, numVertTotal, numVertsPerPoly;\r\n  model_extreme_points extreme_points;\r\n  model_offset offset;\r\n  double rmax;\r\n  double volume;\r\n  std::vector<double> rcm;\r\n  std::vector<std::vector<double>> J;\r\n  int bodyColorOffset, bodyColorShift;\r\n  std::vector<std::vector<double>> verts;\r\n  std::vector<std::vector<double>> vertNorms;\r\n  std::vector<face> faces;\r\n\r\n\r\n\r\n  std::pair<int, int>        ref_vert_one_ind;\r\n  const std::vector<double> *ref_vert_one;\r\n  std::pair<int, int>        ref_vert_two_ind;\r\n  const std::vector<double> *ref_vert_two;\r\n  std::pair<int, int>        ref_vert_three_ind;\r\n  const std::vector<double> *ref_vert_three;\r\n\r\n  std::vector<double> ref_vert_two_rel_to_one;\r\n  std::vector<double> ref_vert_three_rel_to_one;\r\n\r\n  double ref_angle;\r\n\r\n  std::unordered_set<std::size_t> wheels;\r\n  std::unordered_set<std::size_t> wheels_steer;\r\n  std::unordered_set<std::size_t> wheels_non_steer;\r\n  std::unordered_set<std::size_t> wheels_ghost;\r\n  std::unordered_set<std::size_t> wheels_non_ghost;\r\n\r\n  // Holds wheel id in case model itself is a wheel.\r\n  // Otherwise value is invalid::wheel_id, which is -1.\r\n  int wheel_id;\r\n\r\n  // Used only when converting from *.obj to *.m3d/*.a3d.\r\n  std::string wavefront_obj_path;\r\n\r\n  // Used only when converting from *.m3d/*.a3d to *.obj.\r\n  bool volume_overwritten;\r\n  bool rcm_overwritten;\r\n  bool J_overwritten;\r\n} POLYHEDRON;\r\n\r\n\r\n\r\n// ============================================================================\r\n// Globals.\r\n// ============================================================================\r\n\r\nstatic int A; // alpha\r\nstatic int B; // beta\r\nstatic int C; // gamma\r\n\r\n// Projection integrals.\r\nstatic double P1, Pa, Pb, Paa, Pab, Pbb, Paaa, Paab, Pabb, Pbbb;\r\n\r\n// Face integrals.\r\nstatic double Fa, Fb, Fc, Faa, Fbb, Fcc, Faaa, Fbbb, Fccc, Faab, Fbbc, Fcca;\r\n\r\n// Volume integrals.\r\nstatic double T0, T1[3], T2[3], TP[3];\r\n\r\n\r\n\r\n// ============================================================================\r\n// Compute mass properties.\r\n// ============================================================================\r\n\r\n\r\n\r\n// Compute various integrations over projection of face.\r\nvoid compProjectionIntegrals(POLYHEDRON *p, FACE *f);\r\n\r\nvoid compFaceIntegrals(FACE *f);\r\n\r\nvoid compVolumeIntegrals(POLYHEDRON *p);\r\n\r\n\r\n\r\n} // namespace volInt\r\n\r\n#endif // VOLINT_H\r\n", "meta": {"hexsha": "eff788ae47dfd8015417b001b094db617e09c0dd", "size": 22476, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/volInt/volInt.hpp", "max_stars_repo_name": "tractortractor/tractor-converter", "max_stars_repo_head_hexsha": "470b9b8a83661d9b08696fb0f6a54d89f7c5adfa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-04-08T19:53:25.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-09T21:09:47.000Z", "max_issues_repo_path": "lib/volInt/volInt.hpp", "max_issues_repo_name": "tractortractor/tractor-converter", "max_issues_repo_head_hexsha": "470b9b8a83661d9b08696fb0f6a54d89f7c5adfa", "max_issues_repo_licenses": ["MIT"], "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/volInt/volInt.hpp", "max_forks_repo_name": "tractortractor/tractor-converter", "max_forks_repo_head_hexsha": "470b9b8a83661d9b08696fb0f6a54d89f7c5adfa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-26T18:48:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-26T18:48:19.000Z", "avg_line_length": 29.4188481675, "max_line_length": 80, "alphanum_fraction": 0.5739900338, "num_tokens": 5560, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.4664371033122478}}
{"text": "/* \n\tAuthors: Darya Filippova, Geet Duggal, Rob Patro\n\tdfilippo | geet | robp @cs.cmu.edu\n        See LICENSE.txt included with this distribution.\n*/\n\n\n#include <iomanip>\n#include <limits>\n\n#include <fstream>\n\n#include <boost/range/adaptors.hpp>\n#include <boost/range/irange.hpp>\n#include <boost/numeric/ublas/io.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/median.hpp>\n\n#include \"ArmatusParams.hpp\"\n\nArmatusParams::ArmatusParams(std::shared_ptr<SparseMatrix> Ap, double gammap, size_t Kp, int minMeanSamples) :\n    A(Ap), \n    sums(ArmatusParams::SymmetricMatrix(Ap->size1(), Ap->size2())), \n    n(Ap->size1()), \n    K(Kp), \n    minMeanSamples(minMeanSamples),\n    gamma(gammap), \n    mu(std::vector<double>(Ap->size1()+1))\n{\n computeSumMuSigma_();\n}\n\nvoid ArmatusParams::computeSumMuSigma_() {\n\tusing namespace boost::accumulators;\n\tusing namespace boost::range;\n\t// Vector to hold accumulators that will compute the mean\n\t// for domains of each size.\n\tstd::vector<accumulator_set<double,stats<tag::mean, tag::count>>> acc(n+1);\n\t//std::vector<accumulator_set<double,stats<tag::median(with_p_square_quantile), tag::count>>> acc(n+1);\n\n\t// A reference will be easier to work with here\n\tSparseMatrix& M = *A;\n\n\tfor (size_t i : boost::irange(size_t{0}, n)) {\n\t\tsums(i, i) = M(i, i);\n\t}\n\n\tfor (size_t i : boost::irange(size_t{1}, n)) {\n\t\tstd::vector<double> columnSums(i+1);\n\t\tcolumnSums[i] = M(i, i);\n\t\tfor (size_t j : boost::adaptors::reverse(boost::irange(size_t{0}, i))) {\n\t\t\tcolumnSums[j] = columnSums[j+1] + M(j, i);\n\t\t\tsums(j, i) = sums(j, i-1) + columnSums[j];\n\t\t\tint d_i = d(j,i);\n\t\t\tassert(d_i >= 0);\n\t\t\tdouble s = sums(j, i) / std::pow(static_cast<double>(d_i), gamma);\n\t\t    acc[d_i](s);\n\t\t}\n\t}\n\n\tfor (size_t i : boost::irange(size_t{0}, n+1)) {\n\t\tmu[i] = mean(acc[i]);\n        //mu[i] = median(acc[i]);\n\t\t// Require at least 100 samples to compute a Z-score\n\t\tif (boost::accumulators::count(acc[i]) < minMeanSamples) { \n\t\t\tmu[i] = std::numeric_limits<double>::max();\n\t\t}\n\t}\n}\n", "meta": {"hexsha": "7ac3428e575d6b865fa520c01ba5767d7ad16939", "size": 2135, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ArmatusParams.cpp", "max_stars_repo_name": "cosmoskaluga/armatus", "max_stars_repo_head_hexsha": "baa7234096cad439cf7035a40c9a392015a395ac", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2015-05-21T18:19:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-08T14:15:04.000Z", "max_issues_repo_path": "src/ArmatusParams.cpp", "max_issues_repo_name": "Khrameeva-Lab/ArmatusParallel", "max_issues_repo_head_hexsha": "9e3f36230e8443da980920a633b5501964d388e3", "max_issues_repo_licenses": ["BSD-2-Clause", "MIT"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2015-01-22T23:24:21.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-13T13:59:58.000Z", "max_forks_repo_path": "src/ArmatusParams.cpp", "max_forks_repo_name": "Khrameeva-Lab/ArmatusParallel", "max_forks_repo_head_hexsha": "9e3f36230e8443da980920a633b5501964d388e3", "max_forks_repo_licenses": ["BSD-2-Clause", "MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2015-01-06T18:34:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-05T01:46:04.000Z", "avg_line_length": 29.6527777778, "max_line_length": 110, "alphanum_fraction": 0.6697892272, "num_tokens": 657, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.4664371033122478}}
{"text": "//==================================================================================================\n/**\n  EVE - Expressive Vector Engine\n  Copyright : EVE Contributors & Maintainers\n  SPDX-License-Identifier: MIT\n**/\n//==================================================================================================\n#include \"test.hpp\"\n#include <eve/module/polynomial.hpp>\n#include <boost/math/special_functions/chebyshev.hpp>\n\n// //==================================================================================================\n// //== Types tests\n// //==================================================================================================\n// EVE_TEST_TYPES( \"Check return types of tchebytchev on wide\"\n//         , eve::test::simd::ieee_reals\n\n//         )\n// <typename T>(eve::as<T>)\n// {\n//   using v_t = eve::element_type_t<T>;\n//   using wi_t = eve::as_integer_t<T>;\n//   using i_t  = eve::as_integer_t<v_t>;\n//   TTS_EXPR_IS( eve::tchebytchev(i_t(), T())  , T);\n//   TTS_EXPR_IS( eve::tchebytchev(wi_t(), T())  , T);\n//   TTS_EXPR_IS( eve::tchebytchev(i_t(), v_t())  , v_t);\n//   TTS_EXPR_IS( eve::tchebytchev(wi_t(), v_t())  , T);\n\n//   using eve::kind_1;\n//   TTS_EXPR_IS( kind_1(eve::tchebytchev)(i_t(), T())  , T);\n//   TTS_EXPR_IS( kind_1(eve::tchebytchev)(wi_t(), T())  , T);\n//   TTS_EXPR_IS( kind_1(eve::tchebytchev)(i_t(), v_t())  , v_t);\n//   TTS_EXPR_IS( kind_1(eve::tchebytchev)(wi_t(), v_t())  , T);\n\n//   using eve::kind_2;\n//   TTS_EXPR_IS( kind_2(eve::tchebytchev)(i_t(), T())  , T);\n//   TTS_EXPR_IS( kind_2(eve::tchebytchev)(wi_t(), T())  , T);\n//   TTS_EXPR_IS( kind_2(eve::tchebytchev)(i_t(), v_t())  , v_t);\n//   TTS_EXPR_IS( kind_2(eve::tchebytchev)(wi_t(), v_t())  , T);\n// };\n\n// //==================================================================================================\n// //== tchebytchev tests\n// //==================================================================================================\n// EVE_TEST( \"Check behavior of tchebytchev on wide\"\n//         , eve::test::simd::ieee_reals\n//         , eve::test::generate(eve::test::between(-1.0, 1.0), eve::test::between(1.0, 10.0), eve::test::as_integer(eve::test::ramp(0)))\n//         )\n//   <typename T, typename I>(T const& a0, T const& a1, I const & i0)\n// {\n// // using v_t = eve::element_type_t<T>;\n//   auto eve__tchebytchev  =  [](uint32_t n, auto x) { return eve::tchebytchev(n, x); };\n//   for(unsigned int n=0; n < 6; ++n)\n//   {\n//     auto boost_tchebytchev =  [&](auto i, auto e) { return boost::math::chebyshev_t((unsigned int)i, e); };\n//     TTS_ULP_EQUAL(eve__tchebytchev(n, a0), map(boost_tchebytchev, n, a0), 32);\n//     TTS_ULP_EQUAL(eve__tchebytchev(n, a1), map(boost_tchebytchev, n, a1), 32);\n//   }\n//   auto boost_tchebytchev =  [&](auto i, auto e) { return boost::math::chebyshev_t(i, e); };\n//   TTS_ULP_EQUAL(eve::tchebytchev(i0    , a0), map(boost_tchebytchev, i0, a0), 64);\n//   TTS_ULP_EQUAL(eve::tchebytchev(i0    , a1), map(boost_tchebytchev, i0, a1), 64);\n// };\n\n// EVE_TEST( \"Check behavior of kind_2(tchebytchev) on wide\"\n//         , eve::test::simd::ieee_reals\n//         , eve::test::generate(eve::test::between(-1.0, 1.0), eve::test::between(1.0, 10.0), eve::test::as_integer(eve::test::ramp(0)))\n//         )\n//   <typename T, typename I>(T const& a0, T const& a1, I const & i0)\n// {\n//   using eve::kind_2;\n//   auto eve__tchebytchev  =  [](uint32_t n, auto x) { return eve::kind_2(eve::tchebytchev)(n, x); };\n//   for(unsigned int n=0; n < 6; ++n)\n//   {\n//     auto boost_tchebytchev_u =  [&](auto i, auto e) { return boost::math::chebyshev_u((unsigned int)i, e); };\n//     TTS_ULP_EQUAL(eve__tchebytchev(n, a0), map(boost_tchebytchev_u, n, a0), 1000);\n//     TTS_ULP_EQUAL(eve__tchebytchev(n, a1), map(boost_tchebytchev_u, n, a1), 1000);\n//   }\n//   auto boost_tchebytchev_u =  [&](auto i, auto e) { return boost::math::chebyshev_u(i, e); };\n//   TTS_ULP_EQUAL(kind_2(eve::tchebytchev)(i0    , a0), map(boost_tchebytchev_u, i0, a0), 64);\n//   TTS_ULP_EQUAL(kind_2(eve::tchebytchev)(i0    , a1), map(boost_tchebytchev_u, i0, a1), 64);\n// };\n\n// EVE_TEST( \"Check behavior of successor(tchebytchev)\"\n//         , eve::test::simd::ieee_reals\n//         , eve::test::generate(eve::test::between(-1.0, 1.0), eve::test::between(1.0, 10.0))\n//         )\n//   <typename T>(T const& a0, T const&)\n// {\n//   auto t3 = eve::tchebytchev(3, a0);\n//   auto t4 = eve::tchebytchev(4, a0);\n//   auto t5 = eve::tchebytchev(5, a0);\n//   TTS_ULP_EQUAL(eve::successor(eve::tchebytchev)(a0, t4, t3), t5, 64);\n//   using eve::kind_2;\n//   auto u3 = kind_2(eve::tchebytchev)(3, a0);\n//   auto u4 = kind_2(eve::tchebytchev)(4, a0);\n//   auto u5 = kind_2(eve::tchebytchev)(5, a0);\n//  TTS_ULP_EQUAL(eve::successor(eve::tchebytchev)(a0, u4, u3), u5, 100);\n// };\n\n\n//==================================================================================================\n//== tchebytchev diff tests\n//==================================================================================================\nEVE_TEST( \"Check behavior of diff tchebytchev on wide\"\n        , eve::test::simd::ieee_reals\n        , eve::test::generate(eve::test::between(-1.0, 1.0))\n        )\n  <typename T>(T const& a0)\n{\n\n for(int i=1; i < 10 ; ++i)\n {\n   auto dt = eve::diff(eve::tchebytchev)(i, a0);\n   auto u =  eve::kind_2(eve::tchebytchev)(i-1, a0);\n   auto bdt1 = [&i](auto e){return boost::math::chebyshev_t_prime(i, e); };\n   TTS_ULP_EQUAL(dt, u*i, 10);\n   TTS_ULP_EQUAL(dt, eve::detail::map(bdt1, a0), 1000);\n }\n\n // there is no implementation in boost of chebyshev_u_prime so we will defer the test to the availability of\n // complex (vand) or ad (der) to test the derivative of second kind polynomials.\n//  for(int i=1; i < 10 ; ++i)\n//  {\n//    auto dt = eve::diff(eve::tchebytchev)(i, a0);\n//    auto bdt2 = [&i](auto e){return boost::math::chebyshev_u_prime(i, e); };\n//    TTS_ULP_EQUAL(dt, eve::detail::map(bdt2, a0), 1000);\n//  }\n};\n", "meta": {"hexsha": "8bebeb684a7586c895a6d016aa815f8d89b28564", "size": 5951, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/module/polynomial/tchebytchev.cpp", "max_stars_repo_name": "mshojatalab/eve", "max_stars_repo_head_hexsha": "9fc1f46e695b05e2e72f7e2083729621e6bdb57e", "max_stars_repo_licenses": ["MIT"], "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/unit/module/polynomial/tchebytchev.cpp", "max_issues_repo_name": "mshojatalab/eve", "max_issues_repo_head_hexsha": "9fc1f46e695b05e2e72f7e2083729621e6bdb57e", "max_issues_repo_licenses": ["MIT"], "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/unit/module/polynomial/tchebytchev.cpp", "max_forks_repo_name": "mshojatalab/eve", "max_forks_repo_head_hexsha": "9fc1f46e695b05e2e72f7e2083729621e6bdb57e", "max_forks_repo_licenses": ["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.1317829457, "max_line_length": 137, "alphanum_fraction": 0.5261300622, "num_tokens": 2076, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.46643710331224775}}
{"text": "/**\n * @file octree_test.cpp\n * @author Ryan Curtin\n *\n * Test various properties of the Octree.\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#include <mlpack/core.hpp>\n#include <mlpack/core/tree/octree.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n#include \"serialization.hpp\"\n\nusing namespace mlpack;\nusing namespace mlpack::math;\nusing namespace mlpack::tree;\nusing namespace mlpack::metric;\nusing namespace mlpack::bound;\n\nBOOST_AUTO_TEST_SUITE(OctreeTest);\n\n/**\n * Build a quad-tree (2-d octree) on 4 points, and guarantee four points are\n * created.\n */\nBOOST_AUTO_TEST_CASE(SimpleQuadtreeTest)\n{\n  // Four corners of the unit square.\n  arma::mat dataset(\"0 0 1 1; 0 1 0 1\");\n\n  Octree<> t(dataset, 1);\n\n  BOOST_REQUIRE_EQUAL(t.NumChildren(), 4);\n  BOOST_REQUIRE_EQUAL(t.Dataset().n_cols, 4);\n  BOOST_REQUIRE_EQUAL(t.Dataset().n_rows, 2);\n  BOOST_REQUIRE_EQUAL(t.NumDescendants(), 4);\n  BOOST_REQUIRE_EQUAL(t.NumPoints(), 0);\n  for (size_t i = 0; i < 4; ++i)\n  {\n    BOOST_REQUIRE_EQUAL(t.Child(i).NumDescendants(), 1);\n    BOOST_REQUIRE_EQUAL(t.Child(i).NumPoints(), 1);\n  }\n}\n\n/**\n * Build an octree on 3 points and make sure that only three children are\n * created.\n */\nBOOST_AUTO_TEST_CASE(OctreeMissingChildTest)\n{\n  // Only three corners of the unit square.\n  arma::mat dataset(\"0 0 1; 0 1 1\");\n\n  Octree<> t(dataset, 1);\n\n  BOOST_REQUIRE_EQUAL(t.NumChildren(), 3);\n  BOOST_REQUIRE_EQUAL(t.Dataset().n_cols, 3);\n  BOOST_REQUIRE_EQUAL(t.Dataset().n_rows, 2);\n  BOOST_REQUIRE_EQUAL(t.NumDescendants(), 3);\n  BOOST_REQUIRE_EQUAL(t.NumPoints(), 0);\n  for (size_t i = 0; i < 3; ++i)\n  {\n    BOOST_REQUIRE_EQUAL(t.Child(i).NumDescendants(), 1);\n    BOOST_REQUIRE_EQUAL(t.Child(i).NumPoints(), 1);\n  }\n}\n\n/**\n * Ensure that building an empty octree does not fail.\n */\nBOOST_AUTO_TEST_CASE(EmptyOctreeTest)\n{\n  arma::mat dataset;\n  Octree<> t(dataset);\n\n  BOOST_REQUIRE_EQUAL(t.NumChildren(), 0);\n  BOOST_REQUIRE_EQUAL(t.Dataset().n_cols, 0);\n  BOOST_REQUIRE_EQUAL(t.Dataset().n_rows, 0);\n  BOOST_REQUIRE_EQUAL(t.NumDescendants(), 0);\n  BOOST_REQUIRE_EQUAL(t.NumPoints(), 0);\n}\n\n/**\n * Ensure that maxLeafSize is respected.\n */\nBOOST_AUTO_TEST_CASE(MaxLeafSizeTest)\n{\n  arma::mat dataset(5, 15, arma::fill::randu);\n  Octree<> t1(dataset, 20);\n  Octree<> t2(std::move(dataset), 20);\n\n  BOOST_REQUIRE_EQUAL(t1.NumChildren(), 0);\n  BOOST_REQUIRE_EQUAL(t1.NumDescendants(), 15);\n  BOOST_REQUIRE_EQUAL(t1.NumPoints(), 15);\n\n  BOOST_REQUIRE_EQUAL(t2.NumChildren(), 0);\n  BOOST_REQUIRE_EQUAL(t2.NumDescendants(), 15);\n  BOOST_REQUIRE_EQUAL(t2.NumPoints(), 15);\n}\n\n/**\n * Check that the mappings given are correct.\n */\nBOOST_AUTO_TEST_CASE(MappingsTest)\n{\n  // Test with both constructors.\n  arma::mat dataset(3, 5, arma::fill::randu);\n  arma::mat datacopy(dataset);\n  std::vector<size_t> oldFromNewCopy, oldFromNewMove;\n\n  Octree<> t1(dataset, oldFromNewCopy, 1);\n  Octree<> t2(std::move(dataset), oldFromNewMove, 1);\n\n  for (size_t i = 0; i < oldFromNewCopy.size(); ++i)\n  {\n    BOOST_REQUIRE_SMALL(arma::norm(datacopy.col(oldFromNewCopy[i]) -\n        t1.Dataset().col(i)), 1e-3);\n    BOOST_REQUIRE_SMALL(arma::norm(datacopy.col(oldFromNewMove[i]) -\n        t2.Dataset().col(i)), 1e-3);\n  }\n}\n\n/**\n * Check that the reverse mappings are correct too.\n */\nBOOST_AUTO_TEST_CASE(ReverseMappingsTest)\n{\n  // Test with both constructors.\n  arma::mat dataset(3, 300, arma::fill::randu);\n  arma::mat datacopy(dataset);\n  std::vector<size_t> oldFromNewCopy, oldFromNewMove, newFromOldCopy,\n      newFromOldMove;\n\n  Octree<> t1(dataset, oldFromNewCopy, newFromOldCopy);\n  Octree<> t2(std::move(dataset), oldFromNewMove, newFromOldMove);\n\n  for (size_t i = 0; i < oldFromNewCopy.size(); ++i)\n  {\n    BOOST_REQUIRE_SMALL(arma::norm(datacopy.col(oldFromNewCopy[i]) -\n        t1.Dataset().col(i)), 1e-3);\n    BOOST_REQUIRE_SMALL(arma::norm(datacopy.col(oldFromNewMove[i]) -\n        t2.Dataset().col(i)), 1e-3);\n\n    BOOST_REQUIRE_EQUAL(newFromOldCopy[oldFromNewCopy[i]], i);\n    BOOST_REQUIRE_EQUAL(newFromOldMove[oldFromNewMove[i]], i);\n  }\n}\n\n/**\n * Make sure no children at the same level are overlapping.\n */\ntemplate<typename TreeType>\nvoid CheckOverlap(TreeType& node)\n{\n  // Check each combination of children.\n  for (size_t i = 0; i < node.NumChildren(); ++i)\n    for (size_t j = i + 1; j < node.NumChildren(); ++j)\n      BOOST_REQUIRE_EQUAL(node.Child(i).Bound().Overlap(node.Child(j).Bound()),\n          0.0); // We need exact equality here.\n\n  for (size_t i = 0; i < node.NumChildren(); ++i)\n    CheckOverlap(node.Child(i));\n}\n\nBOOST_AUTO_TEST_CASE(OverlapTest)\n{\n  // Test with both constructors.\n  arma::mat dataset(3, 300, arma::fill::randu);\n\n  Octree<> t1(dataset);\n  Octree<> t2(std::move(dataset));\n\n  CheckOverlap(t1);\n  CheckOverlap(t2);\n}\n\n/**\n * Make sure no points are further than the furthest point distance, and that no\n * descendants are further than the furthest descendant distance.\n */\ntemplate<typename TreeType>\nvoid CheckFurthestDistances(TreeType& node)\n{\n  arma::vec center;\n  node.Center(center);\n\n  // Compare points held in the node.\n  for (size_t i = 0; i < node.NumPoints(); ++i)\n  {\n    // Handle floating-point inaccuracies.\n    BOOST_REQUIRE_LE(metric::EuclideanDistance::Evaluate(node.Dataset().col(node.Point(i)),\n        center), node.FurthestPointDistance() * (1 + 1e-5));\n  }\n\n  // Compare descendants held in the node.\n  for (size_t i = 0; i < node.NumDescendants(); ++i)\n  {\n    // Handle floating-point inaccuracies.\n    BOOST_REQUIRE_LE(metric::EuclideanDistance::Evaluate(node.Dataset().col(node.Descendant(i)),\n        center), node.FurthestDescendantDistance() * (1 + 1e-5));\n  }\n\n  for (size_t i = 0; i < node.NumChildren(); ++i)\n    CheckFurthestDistances(node.Child(i));\n}\n\nBOOST_AUTO_TEST_CASE(FurthestDistanceTest)\n{\n  // Test with both constructors.\n  arma::mat dataset(3, 500, arma::fill::randu);\n\n  Octree<> t1(dataset);\n  Octree<> t2(std::move(dataset));\n\n  CheckFurthestDistances(t1);\n  CheckFurthestDistances(t2);\n}\n\n/**\n * The maximum number of children a node can have is limited by the\n * dimensionality.  So we test to make sure there are no cases where we have too\n * many children.\n */\ntemplate<typename TreeType>\nvoid CheckNumChildren(TreeType& node)\n{\n  BOOST_REQUIRE_LE(node.NumChildren(), std::pow(2, node.Dataset().n_rows));\n  for (size_t i = 0; i < node.NumChildren(); ++i)\n    CheckNumChildren(node.Child(i));\n}\n\nBOOST_AUTO_TEST_CASE(MaxNumChildrenTest)\n{\n  for (size_t d = 1; d < 10; ++d)\n  {\n    arma::mat dataset(d, 1000 * d, arma::fill::randu);\n    Octree<> t(std::move(dataset));\n\n    CheckNumChildren(t);\n  }\n}\n\n/**\n * Test the copy constructor.\n */\ntemplate<typename TreeType>\nvoid CheckSameNode(TreeType& node1, TreeType& node2)\n{\n  BOOST_REQUIRE_EQUAL(node1.NumChildren(), node2.NumChildren());\n  BOOST_REQUIRE_NE(&node1.Dataset(), &node2.Dataset());\n\n  // Make sure the children actually got copied.\n  for (size_t i = 0; i < node1.NumChildren(); ++i)\n    BOOST_REQUIRE_NE(&node1.Child(i), &node2.Child(i));\n\n  // Check that all the points are the same.\n  BOOST_REQUIRE_EQUAL(node1.NumPoints(), node2.NumPoints());\n  BOOST_REQUIRE_EQUAL(node1.NumDescendants(), node2.NumDescendants());\n  for (size_t i = 0; i < node1.NumPoints(); ++i)\n    BOOST_REQUIRE_EQUAL(node1.Point(i), node2.Point(i));\n  for (size_t i = 0; i < node1.NumDescendants(); ++i)\n    BOOST_REQUIRE_EQUAL(node1.Descendant(i), node2.Descendant(i));\n\n  // Check that the bound is the same.\n  BOOST_REQUIRE_EQUAL(node1.Bound().Dim(), node2.Bound().Dim());\n  for (size_t d = 0; d < node1.Bound().Dim(); ++d)\n  {\n    BOOST_REQUIRE_CLOSE(node1.Bound()[d].Lo(), node2.Bound()[d].Lo(), 1e-5);\n    BOOST_REQUIRE_CLOSE(node1.Bound()[d].Hi(), node2.Bound()[d].Hi(), 1e-5);\n  }\n\n  // Check that the furthest point and descendant distance are the same.\n  BOOST_REQUIRE_CLOSE(node1.FurthestPointDistance(),\n      node2.FurthestPointDistance(), 1e-5);\n  BOOST_REQUIRE_CLOSE(node1.FurthestDescendantDistance(),\n      node2.FurthestDescendantDistance(), 1e-5);\n}\n\nBOOST_AUTO_TEST_CASE(CopyConstructorTest)\n{\n  // Use a small random dataset.\n  arma::mat dataset(3, 100, arma::fill::randu);\n\n  Octree<> t(dataset);\n  Octree<> t2(t);\n\n  CheckSameNode(t, t2);\n}\n\n/**\n * Test the move constructor.\n */\nBOOST_AUTO_TEST_CASE(MoveConstructorTest)\n{\n  // Use a small random dataset.\n  arma::mat dataset(3, 100, arma::fill::randu);\n\n  Octree<> t(std::move(dataset));\n  Octree<> tcopy(t);\n\n  // Move the tree.\n  Octree<> t2(std::move(t));\n\n  // Make sure the original tree has no data.\n  BOOST_REQUIRE_EQUAL(t.Dataset().n_rows, 0);\n  BOOST_REQUIRE_EQUAL(t.Dataset().n_cols, 0);\n  BOOST_REQUIRE_EQUAL(t.NumChildren(), 0);\n  BOOST_REQUIRE_EQUAL(t.NumPoints(), 0);\n  BOOST_REQUIRE_EQUAL(t.NumDescendants(), 0);\n  BOOST_REQUIRE_SMALL(t.FurthestPointDistance(), 1e-5);\n  BOOST_REQUIRE_SMALL(t.FurthestDescendantDistance(), 1e-5);\n  BOOST_REQUIRE_EQUAL(t.Bound().Dim(), 0);\n\n  // Check that the new tree is the same as our copy.\n  CheckSameNode(tcopy, t2);\n}\n\n/**\n * Test serialization.\n */\nBOOST_AUTO_TEST_CASE(SerializationTest)\n{\n  // Use a small random dataset.\n  arma::mat dataset(3, 500, arma::fill::randu);\n  Octree<> t(std::move(dataset));\n\n  Octree<>* xmlTree;\n  Octree<>* binaryTree;\n  Octree<>* textTree;\n\n  SerializePointerObjectAll(&t, xmlTree, binaryTree, textTree);\n\n  CheckSameNode(t, *xmlTree);\n  CheckSameNode(t, *binaryTree);\n  CheckSameNode(t, *textTree);\n\n  delete xmlTree;\n  delete binaryTree;\n  delete textTree;\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "4f3bca5e749d1333679943d4ed22fd5b539384be", "size": 9740, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/octree_test.cpp", "max_stars_repo_name": "NaxAlpha/mlpack-build", "max_stars_repo_head_hexsha": "1f0c1454d4b35eb97ff115669919c205cee5bd1c", "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": "2018-05-21T11:08:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T07:52:14.000Z", "max_issues_repo_path": "src/mlpack/tests/octree_test.cpp", "max_issues_repo_name": "okmegy/Mlpack", "max_issues_repo_head_hexsha": "ac9abef3c1353f483ed1af42ba5a7432f291ca1a", "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/tests/octree_test.cpp", "max_forks_repo_name": "okmegy/Mlpack", "max_forks_repo_head_hexsha": "ac9abef3c1353f483ed1af42ba5a7432f291ca1a", "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": 27.9885057471, "max_line_length": 96, "alphanum_fraction": 0.6941478439, "num_tokens": 2762, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.6548947223065754, "lm_q1q2_score": 0.4664370985149708}}
{"text": "#include <iostream>\n#include <typeinfo>\r\n#define BOOST_TEST_MODULE MixedMIAMultTests\n#include \"MIAConfig.h\"\r\n#ifdef MIA_USE_HEADER_ONLY_TESTS\r\n#include <boost/test/included/unit_test.hpp>\r\n#else\r\n#include <boost/test/unit_test.hpp>\r\n#endif\r\n\n#include \"SparseMIA.h\"\r\n#include \"DenseMIA.h\"\n#include \"Index.h\"\n\n\n\n\n\r\ntemplate<class _data_type>\r\nvoid mult_work(size_t dim1, size_t dim2){\r\n\r\n    LibMIA::MIAINDEX i;\n    LibMIA::MIAINDEX j;\n    LibMIA::MIAINDEX k;\r\n    LibMIA::MIAINDEX l;\r\n    LibMIA::MIAINDEX m;\r\n    LibMIA::MIAINDEX n;\n\n    LibMIA::DenseMIA<_data_type,4> temp_a(dim1,dim2,dim1,dim2);\r\n    LibMIA::DenseMIA<_data_type,4> dense_b(dim2,dim2,dim1,dim1);\r\n    LibMIA::DenseMIA<_data_type,4> dense_c;\r\n    LibMIA::DenseMIA<_data_type,2> dense_c2;\r\n    LibMIA::DenseMIA<_data_type,2> dense_b2(dim2,dim2);\r\n    LibMIA::DenseMIA<_data_type,1> dense_d(dim2);\r\n    LibMIA::DenseMIA<_data_type,2> dense_d2(dim2,dim2);\r\n    LibMIA::DenseMIA<_data_type,4> c_mixed;\r\n    LibMIA::DenseMIA<_data_type,2> c2_mixed;\r\n\r\n    LibMIA::SparseMIA<_data_type,4> a(dim1,dim2,dim1,dim2);\r\n    LibMIA::SparseMIA<_data_type,4> b(dim2,dim2,dim1,dim1);\r\n\r\n    LibMIA::SparseMIA<_data_type,2> b2(dim2,dim2);\r\n    LibMIA::SparseMIA<_data_type,1> d(dim2);\r\n    LibMIA::SparseMIA<_data_type,2> d2(dim2,dim2);\r\n    LibMIA::SparseMIA<_data_type,4> c;\r\n\r\n\r\n    temp_a.randu(0,20);\r\n    dense_b.randu(0,20);\r\n    dense_b2.randu(0,20);\r\n    dense_d.randu(0,20);\r\n    dense_d2.randu(0,20);\r\n\r\n    for(auto it=temp_a.data_begin();it<temp_a.data_end();++it)\r\n        if(*it<15)\r\n            *it=0;\r\n    for(auto it=dense_b.data_begin();it<dense_b.data_end();++it)\r\n        if(*it<15)\r\n            *it=0;\r\n    for(auto it=dense_b2.data_begin();it<dense_b2.data_end();++it)\r\n        if(*it<15)\r\n            *it=0;\r\n    for(auto it=dense_d.data_begin();it<dense_d.data_end();++it)\r\n        if(*it<15)\r\n            *it=0;\r\n    for(auto it=dense_d2.data_begin();it<dense_d2.data_end();++it)\r\n        if(*it<15)\r\n            *it=0;\r\n\r\n    const LibMIA::DenseMIA<_data_type,4> dense_a(temp_a);\r\n    a=dense_a;\r\n    b=dense_b;\r\n    b2=dense_b2;\r\n    d=dense_d;\r\n    d2=dense_d2;\r\n\r\n    dense_c(i,k,m,n)=dense_a(i,j,k,l)*dense_b(j,l,m,n);\r\n    c_mixed(i,k,m,n)=a(i,j,k,l)*dense_b(j,l,m,n);\r\n\r\n    BOOST_CHECK_MESSAGE(c_mixed.fuzzy_equals(dense_c,test_precision<_data_type>()),std::string(\"Inner/Outer Product 1a for \")+typeid(_data_type).name() );\r\n\r\n\r\n    c_mixed(i,k,m,n)=dense_a(i,j,k,l)*b(j,l,m,n);\r\n    BOOST_CHECK_MESSAGE(c_mixed.fuzzy_equals(dense_c,test_precision<_data_type>()),std::string(\"Inner/Outer Product 1b for \")+typeid(_data_type).name() );\r\n\r\n\r\n    dense_c(i,k,m,n)=dense_a(i,l,k,j)*dense_b(l,j,m,n);\r\n\r\n    c_mixed(i,k,m,n)=a(i,l,k,j)*dense_b(l,j,m,n);\r\n\r\n\r\n    BOOST_CHECK_MESSAGE(c_mixed.fuzzy_equals(dense_c,test_precision<_data_type>()),std::string(\"Inner/Outer Product 2a for \")+typeid(_data_type).name());\r\n\r\n    c_mixed(i,k,m,n)=dense_a(i,l,k,j)*b(l,j,m,n);\r\n    BOOST_CHECK_MESSAGE(c_mixed.fuzzy_equals(dense_c,test_precision<_data_type>()),std::string(\"Inner/Outer Product 2b for \")+typeid(_data_type).name());\r\n\r\n    dense_c(i,k,m,n)=dense_a(i,l,k,j)*dense_b(l,j,m,n);\r\n    c_mixed(i,k,m,n)=a(i,l,k,j)*dense_b(l,j,m,n);\r\n    BOOST_CHECK_MESSAGE(c_mixed.fuzzy_equals(dense_c,test_precision<_data_type>()),std::string(\"Inner/Outer Product 3a for \")+typeid(_data_type).name());\r\n    c_mixed(i,k,m,n)=dense_a(i,l,k,j)*b(l,j,m,n);\r\n    BOOST_CHECK_MESSAGE(c_mixed.fuzzy_equals(dense_c,test_precision<_data_type>()),std::string(\"Inner/Outer Product 3b for \")+typeid(_data_type).name());\r\n\r\n\r\n    dense_c2(i,j)=dense_a(!i,k,!j,l)*dense_b(k,l,!i,!j);\r\n    c2_mixed(i,j)=a(!i,k,!j,l)*dense_b(k,l,!i,!j);\r\n    BOOST_CHECK_MESSAGE(c2_mixed.fuzzy_equals(dense_c2,test_precision<_data_type>()),std::string(\"Inner/Element-Wise Product 1a for \")+typeid(_data_type).name());\r\n    c2_mixed(i,j)=dense_a(!i,k,!j,l)*b(k,l,!i,!j);\r\n    BOOST_CHECK_MESSAGE(c2_mixed.fuzzy_equals(dense_c2,test_precision<_data_type>()),std::string(\"Inner/Element-Wise Product 1b for \")+typeid(_data_type).name());\r\n\r\n    dense_c2(i,j)=dense_a(!i,l,!j,k)*dense_b(k,l,!i,!j);\r\n    c2_mixed(i,j)=a(!i,l,!j,k)*dense_b(k,l,!i,!j);\r\n    BOOST_CHECK_MESSAGE(c2_mixed.fuzzy_equals(dense_c2,test_precision<_data_type>()),std::string(\"Inner/Element-Wise Product 2a for \")+typeid(_data_type).name());\r\n    c2_mixed(i,j)=dense_a(!i,l,!j,k)*b(k,l,!i,!j);\r\n    BOOST_CHECK_MESSAGE(c2_mixed.fuzzy_equals(dense_c2,test_precision<_data_type>()),std::string(\"Inner/Element-Wise Product 2b for \")+typeid(_data_type).name());\r\n\r\n    dense_c2(j,i)=dense_a(!j,l,!i,k)*dense_b(k,l,!j,!i);\r\n    c2_mixed(j,i)=a(!j,l,!i,k)*dense_b(k,l,!j,!i);\r\n\r\n    BOOST_CHECK_MESSAGE(c2_mixed.fuzzy_equals(dense_c2,test_precision<_data_type>()),std::string(\"Inner/Element-Wise Product 3a for \")+typeid(_data_type).name());\r\n    c2_mixed(j,i)=dense_a(!j,l,!i,k)*b(k,l,!j,!i);\r\n    BOOST_CHECK_MESSAGE(c2_mixed.fuzzy_equals(dense_c2,test_precision<_data_type>()),std::string(\"Inner/Element-Wise Product 3b for \")+typeid(_data_type).name());\r\n\r\n\r\n\r\n    dense_c(i,j,k,l)=dense_b2(i,j)*dense_d2(k,l);\r\n    c(i,j,k,l)=b2(i,j)*dense_d2(k,l);\r\n    BOOST_CHECK_MESSAGE(c.fuzzy_equals(dense_c,test_precision<_data_type>()),std::string(\"Outer/Outer Product 1a for \")+typeid(_data_type).name());\r\n\r\n    c(i,j,k,l)=dense_b2(i,j)*d2(k,l);\r\n    BOOST_CHECK_MESSAGE(c.fuzzy_equals(dense_c,test_precision<_data_type>()),std::string(\"Outer/Outer Product 1b for \")+typeid(_data_type).name());\r\n//    std::cout << \"Sparse \" << std::endl;\r\n//    c.print();\r\n//    std::cout << \"Dense \" << std::endl;\r\n//    dense_c.print();\r\n\r\n    dense_c(i,k,l,j)=dense_b2(k,j)*dense_d2(l,i);\r\n    c(i,k,l,j)=b2(k,j)*dense_d2(l,i);\r\n    BOOST_CHECK_MESSAGE(c.fuzzy_equals(dense_c,test_precision<_data_type>()),std::string(\"Outer/Outer Product 2a for \")+typeid(_data_type).name());\r\n    c(i,k,l,j)=dense_b2(k,j)*d2(l,i);\r\n    BOOST_CHECK_MESSAGE(c.fuzzy_equals(dense_c,test_precision<_data_type>()),std::string(\"Outer/Outer Product 2b for \")+typeid(_data_type).name());\r\n\r\n    dense_c(i,k,l,j)=dense_d2(l,i)*dense_b2(k,j);\r\n    c(i,k,l,j)=d2(l,i)*dense_b2(k,j);\r\n    BOOST_CHECK_MESSAGE(c.fuzzy_equals(dense_c,test_precision<_data_type>()),std::string(\"Outer/Outer Product 3a for \")+typeid(_data_type).name());\r\n    c(i,k,l,j)=dense_d2(l,i)*b2(k,j);\r\n\r\n//    dense_c.print();\r\n//    c.print();\r\n//    c.reset_linIdx_sequence();\r\n//    c.print();\r\n    BOOST_CHECK_MESSAGE(c.fuzzy_equals(dense_c,test_precision<_data_type>()),std::string(\"Outer/Outer Product 3b for \")+typeid(_data_type).name());\r\n\r\n    dense_c(i,j,k,l)=dense_a(i,!j,k,!l)*dense_b2(!j,!l);\r\n    c(i,j,k,l)=a(i,!j,k,!l)*dense_b2(!j,!l);\r\n    BOOST_CHECK_MESSAGE(c.fuzzy_equals(dense_c,test_precision<_data_type>()),std::string(\"Outer/Element-Wise Product 1a for \")+typeid(_data_type).name());\r\n\r\n\r\n    c(i,j,k,l)=dense_a(i,!j,k,!l)*b2(!j,!l);\r\n    BOOST_CHECK_MESSAGE(c.fuzzy_equals(dense_c,test_precision<_data_type>()),std::string(\"Outer/Element-Wise Product 1b for \")+typeid(_data_type).name());\r\n\r\n    dense_c(i,j,k,l)=dense_a(k,!j,i,!l)*dense_b2(!j,!l);\r\n    c(i,j,k,l)=a(k,!j,i,!l)*dense_b2(!j,!l);\r\n    BOOST_CHECK_MESSAGE(c.fuzzy_equals(dense_c,test_precision<_data_type>()),std::string(\"Outer/Element-Wise Product 2a for \")+typeid(_data_type).name());\r\n    c(i,j,k,l)=dense_a(k,!j,i,!l)*b2(!j,!l);\r\n    BOOST_CHECK_MESSAGE(c.fuzzy_equals(dense_c,test_precision<_data_type>()),std::string(\"Outer/Element-Wise Product 2b for \")+typeid(_data_type).name());\r\n\r\n    dense_c(i,j,k,l)=dense_a(k,!l,i,!j)*dense_b2(!j,!l);\r\n    c(i,j,k,l)=a(k,!l,i,!j)*dense_b2(!j,!l);\r\n    BOOST_CHECK_MESSAGE(c.fuzzy_equals(dense_c,test_precision<_data_type>()),std::string(\"Outer/Element-Wise Product 3a for \")+typeid(_data_type).name());\r\n    c(i,j,k,l)=dense_a(k,!l,i,!j)*b2(!j,!l);\r\n    BOOST_CHECK_MESSAGE(c.fuzzy_equals(dense_c,test_precision<_data_type>()),std::string(\"Outer/Element-Wise Product 3b for \")+typeid(_data_type).name());\r\n//    std::cout << \"Sparse \" << std::endl;\r\n//    c.print();\r\n//    std::cout << \"Dense \" << std::endl;\r\n//    dense_c.print();\r\n\r\n    dense_c(i,j,k,l)=~(dense_a(i,!j,k,!!l)*dense_b2(!j,!!l))*dense_d(!l);\r\n    c(i,j,k,l)=~(a(i,!j,k,!!l)*dense_b2(!j,!!l))*d(!l);\r\n    BOOST_CHECK_MESSAGE(c.fuzzy_equals(dense_c,test_precision<_data_type>()),std::string(\"Repeated Element-Wise Product 1a for \")+typeid(_data_type).name());\r\n    c(i,j,k,l)=~(dense_a(i,!j,k,!!l)*b2(!j,!!l))*d(!l);\r\n    BOOST_CHECK_MESSAGE(c.fuzzy_equals(dense_c,test_precision<_data_type>()),std::string(\"Repeated Element-Wise Product 1b for \")+typeid(_data_type).name());\r\n    c(i,j,k,l)=~(a(i,!j,k,!!l)*b2(!j,!!l))*dense_d(!l);\r\n    BOOST_CHECK_MESSAGE(c.fuzzy_equals(dense_c,test_precision<_data_type>()),std::string(\"Repeated Element-Wise Product 1c for \")+typeid(_data_type).name());\r\n\r\n\r\n    dense_c(i,k,m,n)=~(dense_a(i,!j,k,!l)*dense_b(!j,!l,m,n))*dense_d2(j,l);\r\n    c(i,k,m,n)=~(a(i,!j,k,!l)*dense_b(!j,!l,m,n))*d2(j,l);\r\n    BOOST_CHECK_MESSAGE(c.fuzzy_equals(dense_c,test_precision<_data_type>()),std::string(\"Ternary Inner Product 1a for \")+typeid(_data_type).name() );\r\n    c(i,k,m,n)=~(dense_a(i,!j,k,!l)*b(!j,!l,m,n))*d2(j,l);\r\n    BOOST_CHECK_MESSAGE(c.fuzzy_equals(dense_c,test_precision<_data_type>()),std::string(\"Ternary Inner Product 1b for \")+typeid(_data_type).name() );\r\n\r\n    c(i,k,m,n)=~(a(i,!j,k,!l)*b(!j,!l,m,n))*dense_d2(j,l);\r\n    BOOST_CHECK_MESSAGE(c.fuzzy_equals(dense_c,test_precision<_data_type>()),std::string(\"Ternary Inner Product 1c for \")+typeid(_data_type).name() );\r\n\r\n    dense_c(i,k,m,n)=~(dense_a(i,!j,k,!l)*dense_b(!j,!l,m,n))*dense_d2(l,j);\r\n    c(i,k,m,n)=~(a(i,!j,k,!l)*dense_b(!j,!l,m,n))*d2(l,j);\r\n    BOOST_CHECK_MESSAGE(c.fuzzy_equals(dense_c,test_precision<_data_type>()),std::string(\"Ternary Inner Product 2a for \")+typeid(_data_type).name() );\r\n    c(i,k,m,n)=~(dense_a(i,!j,k,!l)*b(!j,!l,m,n))*d2(l,j);\r\n    BOOST_CHECK_MESSAGE(c.fuzzy_equals(dense_c,test_precision<_data_type>()),std::string(\"Ternary Inner Product 2b for \")+typeid(_data_type).name() );\r\n    c(i,k,m,n)=~(a(i,!j,k,!l)*b(!j,!l,m,n))*dense_d2(l,j);\r\n    BOOST_CHECK_MESSAGE(c.fuzzy_equals(dense_c,test_precision<_data_type>()),std::string(\"Ternary Inner Product 2c for \")+typeid(_data_type).name() );\r\n\r\n    dense_c(i,k,m,n)=~(dense_a(i,!l,k,!j)*dense_b(!j,!l,m,n))*dense_d2(l,j);\r\n    c(i,k,m,n)=~(a(i,!l,k,!j)*dense_b(!j,!l,m,n))*d2(l,j);\r\n    BOOST_CHECK_MESSAGE(c.fuzzy_equals(dense_c,test_precision<_data_type>()),std::string(\"Ternary Inner Product 3a for \")+typeid(_data_type).name() );\r\n    c(i,k,m,n)=~(dense_a(i,!l,k,!j)*b(!j,!l,m,n))*d2(l,j);\r\n    BOOST_CHECK_MESSAGE(c.fuzzy_equals(dense_c,test_precision<_data_type>()),std::string(\"Ternary Inner Product 3b for \")+typeid(_data_type).name() );\r\n    c(i,k,m,n)=~(a(i,!l,k,!j)*b(!j,!l,m,n))*dense_d2(l,j);\r\n    BOOST_CHECK_MESSAGE(c.fuzzy_equals(dense_c,test_precision<_data_type>()),std::string(\"Ternary Inner Product 3c for \")+typeid(_data_type).name() );\r\n\r\n\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE( MixedMIAMultTests )\n{\n\n    //mult_work<double>(3,3);\n    //mult_work<float>(3,3);\r\n    //mult_work<int>(3,3);\r\n    //mult_work<long>(3,3);\r\n//\r\n//\r\n\r\n\r\n    mult_work<double>(8,5);\n    mult_work<float>(8,5);\r\n    mult_work<int>(8,5);\r\n    mult_work<long>(8,5);\r\n\r\n\r\n\r\n    mult_work<double>(5,8);\n    mult_work<float>(5,8);\r\n    mult_work<int>(5,8);\r\n    mult_work<long>(5,8);\r\n\n\n}\n", "meta": {"hexsha": "fccde0052b33390ea8bc7a3088bf8e6b7a468cef", "size": 11384, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tests/MIA/mixed_mia_mult_test.cpp", "max_stars_repo_name": "extragoya/LibNT", "max_stars_repo_head_hexsha": "60372bf4e3c5d6665185358c4756da4fe547f093", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-26T05:11:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-26T05:11:32.000Z", "max_issues_repo_path": "src/tests/MIA/mixed_mia_mult_test.cpp", "max_issues_repo_name": "extragoya/LibNT", "max_issues_repo_head_hexsha": "60372bf4e3c5d6665185358c4756da4fe547f093", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/MIA/mixed_mia_mult_test.cpp", "max_forks_repo_name": "extragoya/LibNT", "max_forks_repo_head_hexsha": "60372bf4e3c5d6665185358c4756da4fe547f093", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-09-21T15:38:23.000Z", "max_forks_repo_forks_event_max_datetime": "2017-09-21T15:38:23.000Z", "avg_line_length": 47.6317991632, "max_line_length": 163, "alphanum_fraction": 0.6553056922, "num_tokens": 3787, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321720225278, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.4664370953117793}}
{"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#define FUSION_MAX_VECTOR_SIZE 25\n#include <iostream>\n//#include <fstream>\n\n#include <boost/timer/timer.hpp>\n\n#include \"dune/grid/config.h\"\n#include \"dune/grid/uggrid.hh\"\n#include \"dune/istl/solvers.hh\"\n\n#include \"algorithm/giant_gbit.hh\"\n#include \"fem/gridmanager.hh\"\n#include \"fem/lagrangespace.hh\"\n//#include \"fem/hierarchicspace.hh\"   // ContinuousHierarchicMapper\n#include \"io/vtk.hh\"\n#include \"utilities/kaskopt.hh\"\n#include \"utilities/gridGeneration.hh\" //  createUnitSquare\n\nusing namespace Kaskade;\n\n#include \"sst.hh\"\n\nstruct InitialValue \n{\n  using Scalar = double;\n  static constexpr int components = 1;\n  using ValueType = Dune::FieldVector<Scalar,components>;\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::Geometry::ctype,Cell::Geometry::coorddimension> const& localCoordinate) const\n  {\n  // Dune::FieldVector<typename Cell::Geometry::ctype,Cell::Geometry::coorddimension> x = cell.geometry().global(localCoordinate);\n  if (component==0) \n    return 1.0e9;\n  else if (component==1) \n    return 1.0e9;\n  else if (component==2) \n    return 1.0e13;\n  else if (component==3) \n    return 1.0e7;\n  else\n    assert(\"wrong index!\\n\"==0);\n  return 0;\n  \n  }\n\nprivate:\n  int component;\n};\n\nint main(int argc, char *argv[])\n{\n  using Scalar = double;\n  using namespace boost::fusion;\n\n  std::cout << \"Start sst transfer tutorial program with inexact damped Newton iteration \" << std::endl;\n\n  boost::timer::cpu_timer totalTimer;\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  int refinements = getParameter(pt, \"refinement\", 5),\n      order =  getParameter(pt, \"order\", 2);\n//      verbosity   = getParameter(pt, \"verbosity\", 0);\n  Scalar tol = getParameter(pt, \"tolerance\", 1.0e-10),\n         rho = getParameter(pt, \"safetyfactor\",0.0625);\n  //   IterateType iterateType = IterateType::CG;\n  //   PrecondType precondType = PrecondType::NONE;\n  std::string empty;\n\n  std::cout << \"refinements of original mesh   : \" << refinements << std::endl;\n  std::cout << \"discretization order           : \" << order << std::endl;\n  std::cout << \"tolerance for Newton iteration : \" << tol << std::endl;\n\n  std::string s(\"names.type.\");\n  s += getParameter(pt, \"solver.type\", empty);\n  //direct = getParameter(pt, s, 0);\n\n  //   s = \"names.iterate.\" + getParameter(pt, \"solver.iterate\", empty);\n  //   iterateType = static_cast<IterateType>(getParameter(pt, s, 0));\n  //   s = \"names.preconditioner.\" + getParameter(pt, \"solver.preconditioner\", empty);\n  //   precondType = static_cast<PrecondType>(getParameter(pt, s, 0));\n\n  constexpr int dim=2;    \n  using Grid = Dune::UGGrid<dim>;\n  using LeafView = Grid::LeafGridView;\n  using H1Space = FEFunctionSpace<ContinuousLagrangeMapper<Scalar,LeafView> >;\n// using H1Space = FEFunctionSpace<ContinuousHierarchicMapper<Scalar,LeafView> >;\n  using Spaces = boost::fusion::vector<H1Space const*>;\n  using VariableDescriptions = boost::fusion::vector<Variable<SpaceIndex<0>,Components<1>,VariableId<0> >,\n                               Variable<SpaceIndex<0>,Components<1>,VariableId<1> >,\n                               Variable<SpaceIndex<0>,Components<1>,VariableId<2> >,\n                               Variable<SpaceIndex<0>,Components<1>,VariableId<3> > >;\n  using VariableSet = VariableSetDescription<Spaces,VariableDescriptions>;\n  using Functional = SSTFunctional<Scalar,VariableSet>;\n  using NonlinearSolver = Giant<Grid,Functional,VariableSet,Spaces>;\n\n  GridManager<Grid> gridManager( createUnitSquare<Grid>() );\n  gridManager.globalRefine(refinements);\n  std::cout << std::endl << \"Grid: \" << gridManager.grid().size(0) << \" triangles, \" << std::endl;\n  std::cout << \"      \" << gridManager.grid().size(1) << \" edges, \" << std::endl;\n  std::cout << \"      \" << gridManager.grid().size(2) << \" points\" << std::endl;\n\n  // construction of finite element space for the scalar solution T\n  H1Space temperatureSpace(gridManager,gridManager.grid().leafGridView(),\n               order);\n  Spaces spaces(&temperatureSpace);\n  // VariableDescription<int spaceId, int components, int Id>\n  // spaceId: number of associated FEFunctionSpace\n  // components: number of components in this variable\n  // Id: number of this variable\n  std::string varNames[4] = { \"u0\", \"u1\", \"u2\", \"u3\" };\n  VariableSet variableSet(spaces,varNames);\n\n  Functional F;\n  VariableSet::VariableSet x(variableSet);\n  \n  F.scaleInitialValue<0>(InitialValue(0),x);\n  F.scaleInitialValue<1>(InitialValue(1),x);\n  F.scaleInitialValue<2>(InitialValue(2),x);\n  F.scaleInitialValue<3>(InitialValue(3),x);\n  \n  LeafView leafGridView = gridManager.grid().leafGridView();\n  writeVTKFile(x,\"graph/sst_giant_start\",IoOptions().setOrder(std::min(order,2)).setPrecision(7));\n  gridManager.enforceConcurrentReads(false);\n  \n//   constexpr int nvars = Functional::AnsatzVars::noOfVariables;\n//   constexpr int n     = variableSet.degreesOfFreedom(0,nvars);\n//   std::vector<double> scale(n);\n//   x.write(scale.begin());\n//   for (int i=0;i<n;i++) scale[i]=2*scale[i];\n\n//   std::fstream monitorStream;\n//   monitorStream.open(\"sst_giant.mon\",std::fstream::out);\n//   if ( !monitorStream.is_open() )\n//   {\n//      std::cout << \" Failed to open monitorStream file sst_giant.mon\" << std::endl;\n//      exit(-1);\n//   };\n\n  NonlinearSolver nonlinearSolver;\n  \n  s = \"names.nonlinType.\" + getParameter(pt, \"solver.nonlinType\", empty);\n  NonlinearSolver::NonlinProblemType \n    nonlinType=static_cast<NonlinearSolver::NonlinProblemType>(getParameter(pt,s,(int) NonlinearSolver::NonlinProblemType::highlyNonlinear));\n\n  int preconFillLevel=getParameter(pt,\"preconlevel\",0);\n  nonlinearSolver.setTolerance(tol);\n//   nonlinearSolver.setMaximumNoIterations(50);\n  nonlinearSolver.setPreconFillLevel(preconFillLevel);\n  nonlinearSolver.setSafetyFactor(rho);\n//   nonlinearSolver.setErrorLevel(NonlinearSolver::verbose);\n  nonlinearSolver.setMonitorLevel(NonlinearSolver::verbose);\n  nonlinearSolver.setDataLevel(NonlinearSolver::verbose);\n//  nonlinearSolver.setErrorStream(std::cout);\n//  nonlinearSolver.setMonitorStream(std::cout);\n//   nonlinearSolver.setMonitorStream(monitorStream);\n   nonlinearSolver.setNonlinProblemType( nonlinType );\n//   nonlinearSolver.setRestricted(false);\n//  nonlinearSolver.setScalingVector(&scale);\n  nonlinearSolver.setOutFilePrefix((std::string) \"graph/sst_giant_\");\n\n  boost::timer::cpu_timer nonlinTimer;\n  nonlinearSolver.giantGbit(gridManager,F,variableSet,&x,spaces);\n  std::cout << \"computing time for nonlinear solver: \" << boost::timer::format(nonlinTimer.elapsed()) << \"\\n\";\n  struct NonlinearSolver::NleqInfo info=nonlinearSolver.getInfo();\n//  monitorStream << \" The total number of iterative linear solver steps done is \" << \n  std::cout << \" The total number of iterative linear solver steps done is \" << \n               info.noOrdLinIt+info.noSimLinIt << std::endl;\n  std::string finalOutputFilename;\n  if ( info.returnCode==0 ) \n    finalOutputFilename=\"graph/sst_giant_solution\";\n  else \n    finalOutputFilename=\"graph/sst_giant_final\";\n  writeVTKFile(x,finalOutputFilename,IoOptions().setOrder(std::min(order,2)).setPrecision(7));\n\n  std::cout << \"total computing time: \" << boost::timer::format(totalTimer.elapsed()) << \"\\n\";\n  std::cout << \"End sst transfer tutorial program\" << std::endl;\n}\n", "meta": {"hexsha": "c8161588cf6333b518c018aaa764240d4253f841", "size": 8407, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Kaskade/tutorial/sst_pollution/sst_giant.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/sst_pollution/sst_giant.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:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-09T22:02:36.000Z", "max_forks_repo_path": "Kaskade/tutorial/sst_pollution/sst_giant.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": 42.4595959596, "max_line_length": 141, "alphanum_fraction": 0.6519567027, "num_tokens": 2196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754371026367, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.4663671764401745}}
{"text": "// Author(s): Wieger Wesselink\n// Copyright: see the accompanying file COPYING or copy at\n// https://github.com/mCRL2org/mCRL2/blob/master/COPYING\n//\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//\n/// \\file boolean_operator.cpp\n/// \\brief Test for boolean expressions.\n\n#include \"mcrl2/bes/bes2pbes.h\"\n#include \"mcrl2/bes/boolean_equation_system.h\"\n#include \"mcrl2/bes/io.h\"\n#include \"mcrl2/bes/print.h\"\n#include <boost/test/minimal.hpp>\n#include <cstdio>\n#include <iostream>\n#include <string>\n\nusing namespace mcrl2;\n\nvoid test_boolean_expressions()\n{\n  using namespace bes;\n  typedef core::term_traits<boolean_expression> tr;\n\n  boolean_variable X1(\"X1\");\n  boolean_variable X2(\"X2\");\n  boolean_expression t1 = tr::and_(X1, X2);\n  boolean_equation e1(fixpoint_symbol::mu(), X1, tr::imp(X1, X2));\n  boolean_equation e2(fixpoint_symbol::nu(), X2, tr::or_(X1, X2));\n  std::cout << bes::pp(e1) << std::endl;\n  std::cout << bes::pp(e2) << std::endl;\n\n  boolean_equation_system p;\n  p.equations().push_back(e1);\n  p.equations().push_back(e2);\n  p.initial_state() = X1;\n  std::cout << \"----------------\" << std::endl;\n  std::cout << bes::pp(p) << std::endl;\n\n  std::string filename = \"boolean_expression_test.out\";\n  save_bes(p, filename);\n  boolean_equation_system q;\n  load_bes(q, filename);\n  BOOST_CHECK(p == q);\n  remove(filename.c_str());\n}\n\nvoid test_bes2pbes()\n{\n  using namespace bes;\n  typedef core::term_traits<boolean_expression> tr;\n\n  boolean_variable X1(\"X1\");\n  boolean_variable X2(\"X2\");\n  boolean_variable X3(\"X3\");\n  boolean_expression t1 = tr::and_(X1, X2);\n  boolean_equation e1(fixpoint_symbol::mu(), X1, tr::imp(X1, X2));\n  boolean_equation e2(fixpoint_symbol::nu(), X2, tr::or_(X1, X2));\n  boolean_equation e3(fixpoint_symbol::nu(), X3, tr::false_());\n  std::cout << bes::pp(e1) << std::endl;\n  std::cout << bes::pp(e2) << std::endl;\n  std::cout << bes::pp(e3) << std::endl;\n\n  boolean_equation_system p;\n  p.equations().push_back(e1);\n  p.equations().push_back(e2);\n  p.equations().push_back(e3);\n  p.initial_state() = X1;\n  std::cout << \"----------------\" << std::endl;\n  std::cout << bes::pp(p) << std::endl;\n\n  pbes_system::pbes q = bes2pbes(p);\n  std::cout << \"----------------\" << std::endl;\n  std::cout << q << std::endl;\n}\n\nvoid test_precedence()\n{\n  using namespace bes;\n  typedef core::term_traits<boolean_expression> tr;\n\n  boolean_variable X1(\"X1\");\n  boolean_variable X2(\"X2\");\n  boolean_expression t = tr::and_(X1, X2);\n  BOOST_CHECK(left_precedence(t) == 4);\n\n  std::string s = bes::pp(t);\n  BOOST_CHECK(s == \"X1 && X2\");\n}\n\nint test_main(int argc, char* argv[])\n{\n  test_boolean_expressions();\n  test_bes2pbes();\n  test_precedence();\n\n  return 0;\n}\n", "meta": {"hexsha": "d6ffde99b1c196eadc4cbe307d56fa2b0d314170", "size": 2796, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libraries/bes/test/boolean_expression_test.cpp", "max_stars_repo_name": "tneele/mCRL2", "max_stars_repo_head_hexsha": "8f2d730d650ffec15130d6419f69c50f81e5125c", "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": "libraries/bes/test/boolean_expression_test.cpp", "max_issues_repo_name": "tneele/mCRL2", "max_issues_repo_head_hexsha": "8f2d730d650ffec15130d6419f69c50f81e5125c", "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": "libraries/bes/test/boolean_expression_test.cpp", "max_forks_repo_name": "tneele/mCRL2", "max_forks_repo_head_hexsha": "8f2d730d650ffec15130d6419f69c50f81e5125c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4117647059, "max_line_length": 66, "alphanum_fraction": 0.6655937053, "num_tokens": 860, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059775, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.46636717401233946}}
{"text": "// This example is heavily based on the tutorial at https://open.gl\n\n// OpenGL Helpers to reduce the clutter\n#include \"Helpers.h\"\n#include <iostream>\n#include <fstream>\n#include \"math.h\"\n// GLFW is necessary to handle the OpenGL context\n#include <GLFW/glfw3.h>\n\n// Linear Algebra Library\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <thread>\n\n\n// Timer\n#include <chrono>\n#include <OpenGL/OpenGL.h>\n\n// VertexBufferObject wrapper\nVertexBufferObject VBO;\nVertexBufferObject VBO_C;\n\n// Contains the vertex positions\nEigen::MatrixXf V(2,3);\nEigen::MatrixXf V_C(2,3);\nEigen::MatrixXf temp2(2,3);\nEigen::Matrix4f view(4,4);\nEigen::MatrixXf animatematrix(3,6);\nusing namespace std;\nint tri_count=0;\nint mode=-1;\nint tri_num=-1;\ndouble globalx=0;\ndouble globaly=0;\ndouble arr[6];\nint tri_rotate=-1;\nint ver_color=-1;\nint tri_animate=-1;\nint counter = -1;\n\ndouble arrz[9];\n\nvoid mouse_button_callback(GLFWwindow* window, int button, int action, int mods)\n{\n    // Get the position of the mouse in the window\n    double xpos, ypos;\n    glfwGetCursorPos(window, &xpos, &ypos);\n\n    // Get the size of the window\n    int width, height;\n    glfwGetWindowSize(window, &width, &height);\n\n    Eigen::Vector4f p_screen(xpos,height-1-ypos,0,1);\n    Eigen::Vector4f p_canonical((p_screen[0]/width)*2-1,(p_screen[1]/height)*2-1,0,1);\n    Eigen::Vector4f p_world = view.inverse()*p_canonical;\n\n    // Update the position of the first vertex if the left button is pressed\n    if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_PRESS)\n        V.col(0) << p_world[0], p_world[1],1;\n\n    // Upload the change to the GPU\n    VBO.update(V);\n}\n\nvoid mouse_button_make_triangle(GLFWwindow* window, int button, int action, int mods)\n{\n    double xpos, ypos;\n    glfwGetCursorPos(window, &xpos, &ypos);\n    // Get the size of the window\n    int width, height;\n    glfwGetWindowSize(window, &width, &height);\n\n\n    Eigen::Vector4f p_screen(xpos,height-1-ypos,0,1);\n    Eigen::Vector4f p_canonical((p_screen[0]/width)*2-1,(p_screen[1]/height)*2-1,0,1);\n    Eigen::Vector4f p_world = view.inverse()*p_canonical;\n\n    if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_PRESS) {\n        Eigen::MatrixXf temp(V.rows(),V.cols());\n        temp=V;\n        //cout<<\"Temp is \"<<temp<<endl;\n        int size = V.cols()+1;\n        V.resize(V.rows(),size);\n        for(int i=0;i<temp.cols();i++)\n        {\n            V.col(i) = temp.col(i);\n        }\n        //cout<<\"V aftr copying is\"<<V<<endl;\n        //cout<<\"Adding to V values\"<<xworld<< yworld<< 1.0<<endl;\n        V.col(size - 1) << p_world[0], p_world[1], 1.0;\n\n        Eigen::MatrixXf tempc(V_C.rows(),V_C.cols());\n        tempc=V_C;\n//        cout<<\"Tempc is \"<<tempc<<endl;\n        int sizec = V_C.cols()+1;\n        V_C.resize(V_C.rows(),sizec);\n        for(int i=0;i<tempc.cols();i++)\n        {\n            V_C.col(i) = tempc.col(i);\n        }\n        //cout<<\"V aftr copying is\"<<V<<endl;\n        //cout<<\"Adding to V values\"<<xworld<< yworld<< 1.0<<endl;\n        V_C.col(sizec - 1) << 1,0,0;\n\n\n        //cout<<\"V is --> \"<<V<<endl;\n        tri_count++;\n        if(tri_count==3)\n        {\n\n            tri_count=0;\n            VBO_C.update(V_C);\n        }\n        VBO.update(V);\n\n\n\n\n    }\n\n\n\n}\nfloat area(float x1, float y1, float x2, float y2, float x3, float y3)\n{\n    return abs((x1*(y2-y3) + x2*(y3-y1)+ x3*(y1-y2))/2.0);\n}\n\n/* A function to check whether point P(x, y) lies inside the triangle formed\n   by A(x1, y1), B(x2, y2) and C(x3, y3) */\nbool isInside(float x1, float y1, float x2, float y2, float x3, float y3, float x, float y)\n{   cout<<\"INSIDE is inside X,Y\"<<x<<\",\"<<y<<endl;\n    /* Calculate area of triangle ABC */\n    float A = area (x1, y1, x2, y2, x3, y3);\n\n    /* Calculate area of triangle PBC */\n    float A1 = area (x, y, x2, y2, x3, y3);\n\n    /* Calculate area of triangle PAC */\n    float A2 = area (x1, y1, x, y, x3, y3);\n\n    /* Calculate area of triangle PAB */\n    float A3 = area (x1, y1, x2, y2, x, y);\n\n    /* Check if sum of A1, A2 and A3 is same as A */\n    return (A == A1 + A2 + A3);\n}\n\nbool pointInTriangle(float x1, float y1, float x2, float y2, float x3, float y3, float x, float y)\n{\n    float denominator = ((y2 -y3)*(x1 - x3) + (x3 -x2) * (y1 -y3));\n    float alpha = ((y2 - y3)*(x - x3) + (x3 - x2)*(y - y3))/denominator;\n    float beta = ((y3 - y1)* (x - x3) + (x1 - x3)*(y - y3))/denominator;\n    float gamma = 1 - alpha - beta;\n\n    return (0 <= alpha && alpha <= 1 && 0 <= beta && beta <= 1 && 0 <= gamma && gamma <= 1);\n\n}\n\nint inside_triangle(float xworld,float yworld)\n{\n    for(int i=3;i<V.cols();i+=3)\n    {\n        if(pointInTriangle(V(0,i),V(1,i),V(0,i+1),V(1,i+1),V(0,i+2),V(1,i+2),xworld,yworld) ||\n           isInside(V(0,i),V(1,i),V(0,i+1),V(1,i+1),V(0,i+2),V(1,i+2),xworld,yworld))\n        {\n            arr[0]=V(0,i);\n            arr[1]=V(1,i);\n            arr[2]=V(0,i+1);\n            arr[3]=V(1,i+1);\n            arr[4]=V(0,i+2);\n            arr[5]=V(1,i+2);\n            return i;\n        }\n    }\n    return -1;\n}\nfloat distance(float dX0, float dY0, float dX1, float dY1)\n{\n    return sqrt(abs((dX1 - dX0)*(dX1 - dX0) + (dY1 - dY0)*(dY1 - dY0)));\n}\nint nearest_vertex(float xworld,float yworld)\n{\n    int vertex=0;\n    float dist=std::numeric_limits<float>::max();\n    for(int i=3;i<V.cols();i++)\n    {   float tempd = distance(xworld,yworld,V(0,i),V(1,i));\n        if(tempd<dist)\n        {\n            vertex=i;\n            dist=tempd;\n        }\n    }\n    cout<<\"Nearest vertex is \"<<vertex<<endl;\n    return vertex;\n\n}\nvoid mouse_button_move_triangle(GLFWwindow* window, int button, int action, int mods) {\n    cout << \"Calling PRESSED----\" <<view <<endl;\n    double xpos, ypos;\n    glfwGetCursorPos(window, &xpos, &ypos);\n    // Get the size of the window\n    int width, height;\n    glfwGetWindowSize(window, &width, &height);\n\n\n\n    // Convert screen position to world coordinates\n    Eigen::Vector4f p_screen(xpos,height-1-ypos,0,1);\n    Eigen::Vector4f p_canonical((p_screen[0]/width)*2-1,(p_screen[1]/height)*2-1,0,1);\n    Eigen::Vector4f p_world = view.inverse()*p_canonical;\n\n    if (inside_triangle((float)p_world[0],(float) p_world[1]) > 0) {\n        int start = inside_triangle(p_world[0], p_world[1]);\n        if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_PRESS) {\n\n            mode = 1;\n            tri_rotate=start;\n            tri_num = start;\n            globalx = p_world[0];\n            globaly = p_world[1];\n\n            arrz[0]=V_C(0,start);\n            arrz[1]=V_C(1,start);\n            arrz[2]=V_C(2,start);\n            arrz[3]=V_C(0,start+1);\n            arrz[4]=V_C(1,start+1);\n            arrz[5]=V_C(2,start+1);\n            arrz[6]=V_C(0,start+2);\n            arrz[7]=V_C(1,start+2);\n            arrz[8]=V_C(2,start+2);\n\n            V_C(0,start)=0;\n            V_C(1,start)=0;\n            V_C(2,start)=1;\n            V_C(0,start+1)=0;\n            V_C(1,start+1)=0;\n            V_C(2,start+1)=1;\n            V_C(0,start+2)=0;\n            V_C(1,start+2)=0;\n            V_C(2,start+2)=1;\n            VBO_C.update(V_C);\n\n        } else if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_RELEASE) {\n            cout << \"Calling Released\" <<view<< endl;\n            mode = 2;\n            globalx = 0;\n            globaly = 0;\n            tri_num = -1;\n            V_C(0,start)=arrz[0];\n            V_C(1,start)=arrz[1];\n            V_C(2,start)=arrz[2];\n            V_C(0,start+1)=arrz[3];\n            V_C(1,start+1)=arrz[4];\n            V_C(2,start+1)=arrz[5];\n            V_C(0,start+2)=arrz[6];\n            V_C(1,start+2)=arrz[7];\n            V_C(2,start+2)=arrz[8];\n            VBO_C.update(V_C);\n        }\n\n    } else\n    {\n        tri_count = -1;\n    }\n}\nvoid mouse_button_delete_triangle(GLFWwindow* window, int button, int action, int mods) {\n    double xpos, ypos;\n    glfwGetCursorPos(window, &xpos, &ypos);\n    // Get the size of the window\n    int width, height;\n    glfwGetWindowSize(window, &width, &height);\n\n\n\n    // Convert screen position to world coordinates\n    Eigen::Vector4f p_screen(xpos,height-1-ypos,0,1);\n    Eigen::Vector4f p_canonical((p_screen[0]/width)*2-1,(p_screen[1]/height)*2-1,0,1);\n    Eigen::Vector4f p_world = view.inverse()*p_canonical;\n\n    if (inside_triangle(p_world[0], p_world[1]) > 0) {\n        int start = inside_triangle(p_world[0], p_world[1]);\n        if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_PRESS) {\n            int x = V.cols();\n            Eigen::MatrixXf tempz(V.rows(), x - 3);\n            for (int i = 0; i < start; i++) {\n                tempz.col(i) = V.col(i);\n            }\n            for (int i = start; (i < x) && (i+3 <V.cols()) ; i++) {\n                tempz.col(i) = V.col(i + 3);\n            }\n            V.resize(V.rows(), x - 3);\n            V = tempz;\n            VBO.update(V);\n\n\n            x = V_C.cols();\n            tempz.resize(V_C.rows(), x - 3);\n            for (int i = 0; i < start; i++) {\n                tempz.col(i) = V_C.col(i);\n            }\n            for (int i = start; (i < x) && (i+3 <V_C.cols()) ; i++) {\n                tempz.col(i) = V_C.col(i + 3);\n            }\n            V_C.resize(V_C.rows(), x - 3);\n            V_C = tempz;\n            VBO_C.update(V_C);\n\n\n\n\n\n        }\n\n\n    }\n}\n\nvoid mouse_button_animate_triangle(GLFWwindow* window, int button, int action, int mods) {\n    cout << \"Calling Animation Selection----\" <<view <<endl;\n    double xpos, ypos;\n    glfwGetCursorPos(window, &xpos, &ypos);\n    // Get the size of the window\n    int width, height;\n    glfwGetWindowSize(window, &width, &height);\n\n\n\n    // Convert screen position to world coordinates\n    Eigen::Vector4f p_screen(xpos,height-1-ypos,0,1);\n    Eigen::Vector4f p_canonical((p_screen[0]/width)*2-1,(p_screen[1]/height)*2-1,0,1);\n    Eigen::Vector4f p_world = view.inverse()*p_canonical;\n\n    if (inside_triangle((float)p_world[0],(float) p_world[1]) > 0) {\n        int start = inside_triangle(p_world[0], p_world[1]);\n        if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_PRESS) {\n\n            mode = 9;\n            tri_animate=start;\n\n\n        }\n\n    } else\n    {\n        tri_animate = -1;\n    }\n}\n//void mouse_button_rotate_triangle(GLFWwindow* window, int button, int action, int mods) {\n//    double xpos, ypos;\n//    glfwGetCursorPos(window, &xpos, &ypos);\n//    // Get the size of the window\n//    int width, height;\n//    glfwGetWindowSize(window, &width, &height);\n//\n//\n//\n//    // Convert screen position to world coordinates\n//    double xworld = ((xpos / double(width)) * 2) - 1;\n//    double yworld = (((height - 1 - ypos) / double(height)) * 2) - 1; // NOTE: y axis is flipped in glfw\n//    if (inside_triangle(xworld, yworld) > 0) {\n//        int start = inside_triangle(xworld, yworld);\n//        if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_PRESS) {\n//           tri_rotate=start;\n//            cout<<\"Setting triangle to\"<<tri_rotate<<endl;\n//        }\n//    }\n//    else\n//    {\n//        tri_rotate=-1;\n//    }\n//}\n\nvoid mouse_button_color_triangle(GLFWwindow* window, int button, int action, int mods) {\n    double xpos, ypos;\n    glfwGetCursorPos(window, &xpos, &ypos);\n    // Get the size of the window\n    int width, height;\n    glfwGetWindowSize(window, &width, &height);\n\n\n\n    // Convert screen position to world coordinates\n    Eigen::Vector4f p_screen(xpos,height-1-ypos,0,1);\n    Eigen::Vector4f p_canonical((p_screen[0]/width)*2-1,(p_screen[1]/height)*2-1,0,1);\n    Eigen::Vector4f p_world = view.inverse()*p_canonical;\n\n\n    ver_color=nearest_vertex(p_world[0],p_world[1]);\n}\n\n\nvoid change_color(int vertex,float r, float g , float b)\n{\n    if(mode==4)\n    {\n        V_C(0,vertex)=r;\n        V_C(1,vertex)=g;\n        V_C(2,vertex)=b;\n    }\n    VBO_C.update(V_C);\n\n}\n\nvoid moveTriangle(GLFWwindow* window)\n{\n//    cout<<\"Starting point--\"<<globalx<<\",\"<<globaly<<endl;\n    double xpos, ypos;\n    glfwGetCursorPos(window, &xpos, &ypos);\n    // Get the size of the window\n    int width, height;\n    glfwGetWindowSize(window, &width, &height);\n\n    Eigen::Vector4f p_screen(xpos,height-1-ypos,0,1);\n    Eigen::Vector4f p_canonical((p_screen[0]/width)*2-1,(p_screen[1]/height)*2-1,0,1);\n    Eigen::Vector4f p_world = view.inverse()*p_canonical;\n\n    double xworldn = p_world[0]-globalx;\n    double yworldn = p_world[1]-globaly;\n//            cout<<\"Moving by--\"<<xworldn<<\",\"<<yworldn<<endl;\n    V(0,tri_num)=arr[0]+xworldn;\n    V(1,tri_num)=arr[1]+yworldn;\n    V(0,tri_num+1)=arr[2]+xworldn;\n    V(1,tri_num+1)=arr[3]+yworldn;\n    V(0,tri_num+2)=arr[4]+xworldn;\n    V(1,tri_num+2)=arr[5]+yworldn;\n    VBO.update(V);\n\n}\n\nvoid drawline(GLFWwindow* window)\n{\n\n    double xpos, ypos;\n    glfwGetCursorPos(window, &xpos, &ypos);\n    // Get the size of the window\n    int width, height;\n    glfwGetWindowSize(window, &width, &height);\n\n    Eigen::Vector4f p_screen2(xpos,height-1-ypos,0,1);\n    Eigen::Vector4f p_canonical2((p_screen2[0]/width)*2-1,(p_screen2[1]/height)*2-1,0,1);\n    Eigen::Vector4f p_world2 = view.inverse()*p_canonical2;\n\n    temp2.resize(V.rows(),V.cols()+1);\n    for(int i=0;i<V.cols();i++)\n    {\n        temp2.col(i) = V.col(i);\n    }\n    temp2.col(temp2.cols() - 1) << p_world2[0], p_world2[1], 1.0;\n    VBO.update(temp2);\n\n\n\n\n}\n\n\nvoid rotate_point(float cx,float cy,float angle,float &px,float &py)\n{\n    float s = sin(angle);\n    float c = cos(angle);\n\n    // translate point back to origin:\n    px -= cx;\n    py -= cy;\n\n    // rotate point\n    float xnew = px * c - py * s;\n    float ynew = px * s + py * c;\n\n    // translate point back:\n    px = xnew + cx;\n    py = ynew + cy;\n\n}\n\nvoid scale_point(float cx,float cy,float scale,float &px,float &py)\n{\n\n    px = cx + (px-cx)*scale;\n    py = cy + (py-cy)*scale;\n\n}\n\n\nvoid rotate(GLFWwindow* window, float angle)\n{\n    if(tri_rotate>=0) {\n        float centerX = (V(0, tri_rotate) + V(0, tri_rotate + 1) + V(0, tri_rotate + 2)) / 3;\n        float centerY = (V(1, tri_rotate) + V(1, tri_rotate + 1) + V(1, tri_rotate + 2)) / 3;\n        cout<<\"X,Y before-->\"<<V(0, tri_rotate)<<\",\"<<V(1, tri_rotate)<<endl;\n        rotate_point(centerX,centerY,angle,V(0, tri_rotate),V(1, tri_rotate));\n        rotate_point(centerX,centerY,angle,V(0, tri_rotate+1),V(1, tri_rotate+1));\n        rotate_point(centerX,centerY,angle,V(0, tri_rotate+2),V(1, tri_rotate+2));\n        cout<<\"X,Y after-->\"<<V(0, tri_rotate)<<\",\"<<V(1, tri_rotate)<<endl;\n        VBO.update(V);\n\n    }\n\n}\nvoid scale(GLFWwindow* window, float scale)\n{\n    if(tri_rotate>=0) {\n        float centerX = (V(0, tri_rotate) + V(0, tri_rotate + 1) + V(0, tri_rotate + 2)) / 3;\n        float centerY = (V(1, tri_rotate) + V(1, tri_rotate + 1) + V(1, tri_rotate + 2)) / 3;\n        cout<<\"Scale X,Y before-->\"<<V(0, tri_rotate)<<\",\"<<V(1, tri_rotate)<<endl;\n        scale_point(centerX,centerY,scale,V(0, tri_rotate),V(1, tri_rotate));\n        scale_point(centerX,centerY,scale,V(0, tri_rotate+1),V(1, tri_rotate+1));\n        scale_point(centerX,centerY,scale,V(0, tri_rotate+2),V(1, tri_rotate+2));\n        cout<<\"Scale X,Y after-->\"<<V(0, tri_rotate)<<\",\"<<V(1, tri_rotate)<<endl;\n        VBO.update(V);\n\n    }\n\n}\n\nvoid zoomout()\n{\n    view << view(0,0)*0.8,0,0,view(0,3),\n            0,view(1,1)*0.8,0,view(1,3),\n            0,0,view(2,2),0,\n            0,0,0,view(3,3);\n\n}\n\nvoid zoomin()\n{\n    cout<<\"Calling zoomin--> View before -->\"<<view<<endl;\n    view << view(0,0)*1.2,0,0,view(0,3),\n            0,view(1,1)*1.2,0,view(1,3),\n            0,0,view(2,2),0,\n            0,0,0,view(3,3);\n\n    cout<<\"View After -->\"<<view<<endl;\n\n}\n\n\nvoid pan(GLFWwindow* window,char key)\n{\n\n\n    if(key=='d')\n    {\n        view << view(0,0),0,0,view(0,3)+0.2,\n                0,view(1,1),0,view(1,3),\n                0,0,view(2,2),0,\n                0,0,0,view(3,3);\n    }\n    if(key=='a')\n    {\n        view << view(0,0),0,0,view(0,3)-0.2,\n                0,view(1,1),0,view(1,3),\n                0,0,view(2,2),0,\n                0,0,0,view(3,3);\n    }\n    if(key=='w')\n    {\n        view << view(0,0),0,0,view(0,3),\n                0,view(1,1),0,view(1,3)+0.2,\n                0,0,view(2,2),0,\n                0,0,0,view(3,3);\n    }\n    if(key=='s')\n    {\n        view << view(0,0),0,0,view(0,3),\n                0,view(1,1),0,view(1,3)-0.2,\n                0,0,view(2,2),0,\n                0,0,0,view(3,3);\n    }\n}\n\nvoid store_before()\n{\n\n        if(tri_animate>0)\n        {\n            animatematrix.col(0)=V.col(tri_animate);\n            animatematrix.col(1)=V.col(tri_animate+1);\n            animatematrix.col(2)=V.col(tri_animate+2);\n\n        }\n\n    cout<<\"Stored before\"<<animatematrix<<endl;\n\n}\n\nvoid store_after()\n{\n\n        if(tri_animate>0)\n        {\n            animatematrix.col(3)=V.col(tri_animate);\n            animatematrix.col(4)=V.col(tri_animate+1);\n            animatematrix.col(5)=V.col(tri_animate+2);\n        }\n    cout<<\"Stored After\"<<animatematrix<<endl;\n}\n\nvoid animateposition()\n{\n    if(mode==9)\n    {\n        if(tri_animate>0)\n        {\n//            float stepsx0=(animatematrix(0,3)-animatematrix(0,0))/10;\n//            float stepsy0=(animatematrix(1,3)-animatematrix(1,0))/10;\n//            float stepsz0=(animatematrix(2,3)-animatematrix(2,0))/10;\n//            float stepsx1=(animatematrix(0,4)-animatematrix(0,1))/10;\n//            float stepsy1=(animatematrix(1,4)-animatematrix(1,1))/10;\n//            float stepsz1=(animatematrix(2,4)-animatematrix(2,1))/10;\n//            float stepsx2=(animatematrix(0,5)-animatematrix(0,2))/10;\n//            float stepsy2=(animatematrix(1,5)-animatematrix(1,2))/10;\n//            float stepsz2=(animatematrix(2,5)-animatematrix(2,2))/10;\n//            for(float i = 0;i<10;i++)\n//            {   cout<<\"Running animation\"<<endl;\n//                V(0,tri_animate)-=stepsx0;\n//                V(1,tri_animate)-=stepsy0;\n//                V(2,tri_animate)-=stepsz0;\n//                V(0,tri_animate+1)-=stepsx1;\n//                V(1,tri_animate+1)-=stepsy1;\n//                V(2,tri_animate+1)-=stepsz1;\n//                V(0,tri_animate+2)-=stepsx2;\n//                V(1,tri_animate+2)-=stepsy2;\n//                V(2,tri_animate+2)-=stepsz2;\n//\n//                std::this_thread::sleep_for(std::chrono::seconds(5));\n//\n//                VBO.update(V);\n//            }\n            counter=1;\n        }\n    }\n}\n\n\nvoid writetosvg(GLFWwindow* window)\n{\n    int width, height;\n    glfwGetWindowSize(window, &width, &height);\n    ofstream myfile;\n    myfile.open (\"/Users/Rachit/Desktop/example.svg\");\n    myfile << \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\" standalone=\\\"no\\\"?>\\n\";\n    myfile << \"<svg width=\\\"\"<<width<<\"\\\" height=\\\"\"<<height<<\"\\\" version=\\\"1.200000\\\" xmlns=\\\"http://www.w3.org/2000/svg\\\"\"\n            \" xmlns:xlink=\\\"http://www.w3.org/1999/xlink\\\"  >\\n\";\n\n    for(int i=3;i<V.cols();i=i+3)\n    {\n        Eigen::Vector4f a(V(0,i),V(1,i),0,1);\n        Eigen::Vector4f b(V(0,i+1),V(1,i+1),0,1);\n        Eigen::Vector4f c(V(0,i+2),V(1,i+2),0,1);\n        a= view * a;\n        b= view * b;\n        c= view * c;\n\n        float ax,ay,bx,by,cx,cy;\n        ax=((( a[0] + 1 ) / 2.0) *\n            width );\n        ay=((( 1 - a[1] ) / 2.0) *\n            height );\n        bx=((( b[0] + 1 ) / 2.0) *\n            width );\n        by=((( 1 - b[1] ) / 2.0) *\n            height ) ;\n        cx=((( c[0] + 1 ) / 2.0) *\n            width );\n        cy=((( 1 - c[1] ) / 2.0) *\n            height );\n\n\n        myfile << \" <defs>\\n\"\n                \"      <linearGradient id=\\\"fadeA-1\"<<i<<\"\\\" gradientUnits=\\\"objectBoundingBox\\\" x1=\\\"0.5\\\" y1=\\\"0\\\" x2=\\\"1\\\" y2=\\\"1\\\">\\n\"\n                \"        <stop offset=\\\"0%\\\" stop-color=\\\"rgb(\"<<roundf((float)V_C(0,i)*255)<<\",\"<<roundf((float)V_C(1,i)*255)<<\",\"<<roundf((float)V_C(2,i)*255)<<\")\\\"/>\\n\"\n                \"        <stop offset=\\\"100%\\\" stop-color=\\\"rgb(\"<<roundf((float)V_C(0,i+2)*255)<<\",\"<<roundf((float)V_C(1,i+2)*255)<<\",\"<<roundf((float)V_C(2,i+2)*255)<<\")\\\"/>\\n\"\n                \"      </linearGradient>\\n\"\n                \"      <linearGradient id=\\\"fadeB-1\"<<i<<\"\\\" gradientUnits=\\\"objectBoundingBox\\\" x1=\\\"0\\\" y1=\\\"1\\\" x2=\\\"0.75\\\" y2=\\\"0.5\\\">\\n\"\n                \"        <stop offset=\\\"0%\\\" stop-color=\\\"rgb(\"<<roundf((float)V_C(0,i+1)*255)<<\",\"<<roundf((float)V_C(1,i+1)*255)<<\",\"<<roundf((float)V_C(2,i+1)*255)<<\")\\\"/>\\n\"\n                \"        <stop offset=\\\"100%\\\" stop-color=\\\"rgb(\"<<roundf((float)V_C(0,i+1)*255)<<\",\"<<roundf((float)V_C(1,i+1)*255)<<\",\"<<roundf((float)V_C(2,i+1)*255)<<\")\\\" stop-opacity=\\\"0\\\" />\\n\"\n                \"      </linearGradient>\\n\"\n                \"      </defs>\\n\"\n                \"      <path id=\\\"pathA-1\"<<i<<\"\\\" d=\\\"M \"<<ax<<\",\"<<ay<<\" L \"<<bx<<\",\"<<by<<\" \"<<cx<<\",\"<<cy<<\" Z\\\" fill=\\\"url(#fadeA-1\"<<i<<\")\\\"/>\\n\"\n                \"      <path id=\\\"pathB-1\"<<i<<\"\\\" d=\\\"M \"<<ax<<\",\"<<ay<<\" L \"<<bx<<\",\"<<by<<\" \"<<cx<<\",\"<<cy<<\" Z\\\" fill=\\\"url(#fadeB-1\"<<i<<\")\\\"/>\\n\";\n    }\n\n\n    myfile <<\"</svg>\\n\";\n    myfile.close();\n    cout<<\"Done writing\";\n\n}\n\n\nvoid key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)\n{\n    // Update the position of the first vertex if the keys 1,2, or 3 are pressed\n    if(action==GLFW_PRESS)\n        switch (key)\n        {\n            case  GLFW_KEY_1:\n                change_color(ver_color,1.0f,0.0f,0.0f);\n                break;\n            case GLFW_KEY_2:\n                change_color(ver_color,0.0f,1.0f,0.0f);\n                break;\n            case  GLFW_KEY_3:\n                change_color(ver_color,0.0f,0.0f,1.0f);\n                break;\n            case  GLFW_KEY_4:\n                change_color(ver_color,1.0f,1.0f,1.0f);\n                break;\n            case  GLFW_KEY_5:\n                change_color(ver_color,0.0f,0.0f,0.0f);\n                break;\n            case  GLFW_KEY_6:\n                change_color(ver_color,0.5f,0.5f,0.0f);\n                break;\n            case  GLFW_KEY_7:\n                change_color(ver_color,0.0f,0.5f,0.5f);\n                break;\n            case  GLFW_KEY_8:\n                change_color(ver_color,0.5f,0.0f,0.5f);\n                break;\n            case  GLFW_KEY_9:\n                change_color(ver_color,0.25f,0.5f,0.25f);\n                break;\n            case GLFW_KEY_I:\n                mode=0;\n                tri_count=0;\n                glfwSetMouseButtonCallback(window, mouse_button_make_triangle);\n                break;\n            case GLFW_KEY_O:\n                mode=1;\n                glfwSetMouseButtonCallback(window, mouse_button_move_triangle);\n                break;\n            case GLFW_KEY_P:\n                mode=3;\n                glfwSetMouseButtonCallback(window, mouse_button_delete_triangle);\n                break;\n            case GLFW_KEY_C:\n                mode=4;\n                glfwSetMouseButtonCallback(window, mouse_button_color_triangle);\n                break;\n//        case GLFW_KEY_T:\n//            mode = -1;\n//            glfwSetMouseButtonCallback(window, mouse_button_rotate_triangle);\n//            break;\n            case GLFW_KEY_H:\n                //positive\n                rotate(window,0.174533);\n                break;\n            case GLFW_KEY_J:\n                //negative\n                rotate(window,-0.174533);\n                break;\n            case GLFW_KEY_K:\n                //scaleup\n                scale(window,1.25);\n                break;\n            case GLFW_KEY_L:\n                //scaledown\n                scale(window,0.75);\n                break;\n            case GLFW_KEY_EQUAL:\n                //Zoomin\n                zoomin();\n                break;\n            case GLFW_KEY_MINUS:\n                //Zoomout\n                zoomout();\n                break;\n            case GLFW_KEY_W:\n                pan(window,'w');\n                break;\n            case GLFW_KEY_S:\n                pan(window,'s');\n                break;\n            case GLFW_KEY_A:\n                pan(window,'a');\n                break;\n            case GLFW_KEY_D:\n                pan(window,'d');\n                break;\n\n            case GLFW_KEY_Q:\n                mode=9;\n                glfwSetMouseButtonCallback(window, mouse_button_animate_triangle);\n                break;\n\n            case GLFW_KEY_Z:\n                store_before();\n                break;\n            case GLFW_KEY_X:\n                mode=9;\n                store_after();\n                animateposition();\n                break;\n            case GLFW_KEY_U:\n                writetosvg(window);\n                break;\n             default:\n                break;\n        }\n\n    // Upload the change to the GPU\n    VBO.update(V);\n}\n\nint main(void)\n{\n    GLFWwindow* window;\n\n    // Initialize the library\n    if (!glfwInit())\n        return -1;\n\n    // Activate supersampling\n    glfwWindowHint(GLFW_SAMPLES, 8);\n\n    // Ensure that we get at least a 3.2 context\n    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);\n    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);\n\n    // On apple we have to load a core profile with forward compatibility\n#ifdef __APPLE__\n    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);\n    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);\n#endif\n\n    // Create a windowed mode window and its OpenGL context\n    window = glfwCreateWindow(700, 700, \"Hello World\", NULL, NULL);\n    if (!window)\n    {\n        glfwTerminate();\n        return -1;\n    }\n\n    // Make the window's context current\n    glfwMakeContextCurrent(window);\n\n    // Initialize the VAO\n    // A Vertex Array Object (or VAO) is an object that describes how the vertex\n    // attributes are stored in a Vertex Buffer Object (or VBO). This means that\n    // the VAO is not the actual object storing the vertex data,\n    // but the descriptor of the vertex data.\n    VertexArrayObject VAO;\n    VAO.init();\n    VAO.bind();\n\n    // Initialize the VBO with the vertices data\n    // A VBO is a data container that lives in the GPU memory\n    VBO.init();\n\n//    V.resize(2,3);\n//    V << -0.5,  0.5, 0.5, 0.5, 0.5, -0.5;\n//\n//    VBO.update(V);\n\n    // Initialize the OpenGL Program\n    // A program controls the OpenGL pipeline and it must contains\n    // at least a vertex shader and a fragment shader to be valid\n    Program program;\n    const GLchar* vertex_shader =\n            \"#version 150 core\\n\"\n                    \"in vec2 position;\"\n                    \"in vec3 color;\"\n                    \"out vec3 f_color;\"\n                    \"uniform mat4 view;\"\n                    \"void main()\"\n                    \"{\"\n                    \"    gl_Position =  view * vec4(position, 0.0, 1.0) ;\"\n                    \"    f_color = color;\"\n                    \"}\";\n    const GLchar* fragment_shader =\n            \"#version 150 core\\n\"\n                    \"in vec3 f_color;\"\n                    \"out vec4 outColor;\"\n                    \"uniform vec3 triangleColor;\"\n                    \"void main()\"\n                    \"{\"\n                    \"    outColor = vec4(f_color, 1.0);\"\n                    \"}\";\n\n    // Compile the two shaders and upload the binary to the GPU\n    // Note that we have to explicitly specify that the output \"slot\" called outColor\n    // is the one that we want in the fragment buffer (and thus on screen)\n    program.init(vertex_shader,fragment_shader,\"outColor\");\n    program.bind();\n\n    // The vertex shader wants the position of the vertices as an input.\n    // The following line connects the VBO we defined above with the position \"slot\"\n    // in the vertex shader\n//    program.bindVertexAttribArray(\"position\",VBO);\n\n    //custom code\n    VBO.init();\n    V.resize(3,3);\n//    cout<<\"Values after resize are \"<<V<<endl;\n    V  << 0,0,0,0,0,0,1,1,1;\n\n\n//    cout<<\"orignal V is\"<<V<<endl;\n//V << 0.5,  -0.5, -0.5,-0.5,0.5,0.5, -0.5, -0.5, 0.5,0.5,0.5,-0.5,1,1,1,1,1,1;\n//            -0.5,  0.5, 0.5, 0.5, 0.5, -0.5,1;\n    VBO.update(V);\n\n    VBO_C.init();\n    V_C.resize(3,3);\n    V_C<<\n       1,  0, 0,\n            1,  0, 0,\n            1,  0, 0;\n\n    VBO_C.update(V_C);\n\n    view << 1,0,0,0,\n            0,1,0,0,\n            0,0,1,0,\n            0,0,0,1;\n\n\n\n\n    program.bindVertexAttribArray(\"position\",VBO);\n    program.bindVertexAttribArray(\"color\",VBO_C);\n\n    // Save the current time --- it will be used to dynamically change the triangle color\n    auto t_start = std::chrono::high_resolution_clock::now();\n\n    // Register the keyboard callback\n    glfwSetKeyCallback(window, key_callback);\n\n    // Register the mouse callback\n//    glfwSetMouseButtonCallback(window, mouse_button_callback);\n\n    // Loop until the user closes the window\n    int widths, heights;\n    glfwGetWindowSize(window, &widths, &heights);\n    float aspect_start=float(heights)/float(widths);\n    int i=0;\n    while (!glfwWindowShouldClose(window))\n    {\n        // Bind your VAO (not necessary if you have only one)\n//        VAO.bind();\n        int width, height;\n        glfwGetWindowSize(window, &width, &height);\n        float aspect_ratiox = float(height)/float(heights); // corresponds to the necessary width scaling\n        float aspect_ratioy = float(width)/float(widths); // corresponds to the necessary width scaling\n        float aspect_ratio=float(height)/float(width);\n        if(aspect_ratio!=aspect_start) {\n            view(0, 0) = view(0, 0) * aspect_ratioy;\n            view(1,1) *= aspect_ratiox;\n            aspect_start=aspect_ratio;\n            widths=width;\n            heights=height;\n        }\n        // Bind your program\n        program.bind();\n\n        // Set the uniform value depending on the time difference\n//        auto t_now = std::chrono::high_resolution_clock::now();\n//        float time = std::chrono::duration_cast<std::chrono::duration<float>>(t_now - t_start).count();\n//        glUniform3f(program.uniform(\"triangleColor\"), (float)(sin(time * 4.0f) + 1.0f) / 2.0f, 0.0f, 0.0f);\n//        glUniform3f(program.uniform(\"triangleColor\"), 1.0f, 0.0f, 0.0f);\n        // Clear the framebuffer\n        glClearColor(0.5f, 0.5f, 0.5f, 1.0f);\n        glClear(GL_COLOR_BUFFER_BIT);\n\n        // Draw a triangle\n//        if(V.cols()%3==0)\n        glDrawArrays(GL_TRIANGLES, 0, V.cols());\n//        glDrawArrays(GL_TRIANGLES, 3, 3);\n        // Swap front and back buffers\n        if(tri_count==1 && mode==0) {\n\n            drawline(window);\n            glDrawArrays(GL_LINE_LOOP, temp2.cols()-2, 2);\n//            cout<<\"temp 2 is --> \"<<temp2<<endl;\n        }\n        if(tri_count==2 && mode==0) {\n\n            drawline(window);\n            glDrawArrays(GL_LINE_LOOP, temp2.cols()-3, 3);\n//            cout<<\"temp 2 is --> \"<<temp2<<endl;\n        }\n        if(mode==1 && tri_num > 0)\n        {\n            moveTriangle(window);\n            int state = glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT);\n            if(state == GLFW_RELEASE)\n            {\n                cout<<\"Calling Released\"<<endl;\n                mode = 2;\n                globalx=0;\n                globaly=0;\n                tri_num=-1;\n                arr[0]=0;\n                arr[1]=0;\n                arr[2]=0;\n                arr[3]=0;\n                arr[4]=0;\n                arr[5]=0;\n            }\n        }\n        if(mode==9 && counter==1)\n        {\n            float stepsx0=(animatematrix(0,3)-animatematrix(0,0))/20;\n            float stepsy0=(animatematrix(1,3)-animatematrix(1,0))/20;\n            float stepsz0=(animatematrix(2,3)-animatematrix(2,0))/20;\n            float stepsx1=(animatematrix(0,4)-animatematrix(0,1))/20;\n            float stepsy1=(animatematrix(1,4)-animatematrix(1,1))/20;\n            float stepsz1=(animatematrix(2,4)-animatematrix(2,1))/20;\n            float stepsx2=(animatematrix(0,5)-animatematrix(0,2))/20;\n            float stepsy2=(animatematrix(1,5)-animatematrix(1,2))/20;\n            float stepsz2=(animatematrix(2,5)-animatematrix(2,2))/20;\n            if (i<=19)\n            {   cout<<\"Running animation\"<<endl;\n                V(0,tri_animate)-=stepsx0;\n                V(1,tri_animate)-=stepsy0;\n                V(2,tri_animate)-=stepsz0;\n                V(0,tri_animate+1)-=stepsx1;\n                V(1,tri_animate+1)-=stepsy1;\n                V(2,tri_animate+1)-=stepsz1;\n                V(0,tri_animate+2)-=stepsx2;\n                V(1,tri_animate+2)-=stepsy2;\n                V(2,tri_animate+2)-=stepsz2;\n\n                std::this_thread::sleep_for(std::chrono::milliseconds(100));\n\n                VBO.update(V);\n                i++;\n            }\n            if(i==20) {\n                counter = 0;\n                i=0;\n            }\n        }\n\n\n        //Binding the view matrix\n        glUniformMatrix4fv(program.uniform(\"view\"),1,GL_FALSE,view.data());\n\n        glfwSwapBuffers(window);\n\n        // Poll for and process events\n        glfwPollEvents();\n    }\n\n    // Deallocate opengl memory\n    program.free();\n    VAO.free();\n    VBO.free();\n\n    // Deallocate glfw internals\n    glfwTerminate();\n    return 0;\n}", "meta": {"hexsha": "96719b0c62f7e208af5ddae124c87952996f337a", "size": 32801, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "App/src/main.cpp", "max_stars_repo_name": "rachitmehrotra1/triangle-soup-editor", "max_stars_repo_head_hexsha": "e5b18827523e97e09a826a4dd0cf03f8f978834b", "max_stars_repo_licenses": ["MIT"], "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/src/main.cpp", "max_issues_repo_name": "rachitmehrotra1/triangle-soup-editor", "max_issues_repo_head_hexsha": "e5b18827523e97e09a826a4dd0cf03f8f978834b", "max_issues_repo_licenses": ["MIT"], "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/main.cpp", "max_forks_repo_name": "rachitmehrotra1/triangle-soup-editor", "max_forks_repo_head_hexsha": "e5b18827523e97e09a826a4dd0cf03f8f978834b", "max_forks_repo_licenses": ["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.0028355388, "max_line_length": 199, "alphanum_fraction": 0.5315691595, "num_tokens": 9855, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059775, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.46636717401233946}}
{"text": "/*\n@copyright Louis Dionne 2015\nDistributed under the Boost Software License, Version 1.0.\n(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n */\n\n#include <boost/hana/assert.hpp>\n#include <boost/hana/config.hpp>\n#include <boost/hana/maybe.hpp>\n#include <boost/hana/tuple.hpp>\n#include <boost/hana/type.hpp>\n\n#include <sstream>\n#include <string>\n#include <type_traits>\nusing namespace boost::hana;\nusing namespace std::literals;\n\n\nint main() {\n\n{\n\n//! [adjust_if]\nBOOST_HANA_CONSTEXPR_LAMBDA auto negative = [](auto x) {\n    return x < 0;\n};\n\nBOOST_HANA_CONSTEXPR_LAMBDA auto negate = [](auto x) {\n    return -x;\n};\n\nBOOST_HANA_CONSTEXPR_CHECK(\n    adjust_if(make<Tuple>(-3, -2, -1, 0, 1, 2, 3), negative, negate)\n    ==\n    make<Tuple>(3, 2, 1, 0, 1, 2, 3)\n);\n//! [adjust_if]\n\n}{\n\n//! [adjust]\nBOOST_HANA_CONSTEXPR_LAMBDA auto negate = [](auto x) {\n    return -x;\n};\n\nBOOST_HANA_CONSTEXPR_CHECK(\n    adjust(make<Tuple>(1, 4, 9, 2, 3, 4), 4, negate)\n    ==\n    make<Tuple>(1, -4, 9, 2, 3, -4)\n);\n//! [adjust]\n\n}{\n\n//! [fill]\nBOOST_HANA_CONSTEXPR_CHECK(\n    fill(make<Tuple>(1, '2', 3.3, nullptr), 'x') == make<Tuple>('x', 'x', 'x', 'x')\n);\n\nBOOST_HANA_CONSTANT_CHECK(fill(nothing, 'x') == nothing);\nBOOST_HANA_CONSTEXPR_CHECK(fill(just('y'), 'x') == just('x'));\n//! [fill]\n\n}{\n\n//! [transform]\nauto to_string = [](auto x) {\n    return static_cast<std::ostringstream const&>(std::ostringstream{} << x).str();\n};\n\nBOOST_HANA_RUNTIME_CHECK(\n    transform(make<Tuple>(1, '2', \"345\", std::string{\"67\"}), to_string)\n    ==\n    make<Tuple>(\"1\", \"2\", \"345\", \"67\")\n);\n\nBOOST_HANA_CONSTANT_CHECK(transform(nothing, to_string) == nothing);\nBOOST_HANA_RUNTIME_CHECK(transform(just(123), to_string) == just(\"123\"s));\n\nBOOST_HANA_CONSTANT_CHECK(\n    transform(tuple_t<void, int(), char[10]>, template_<std::add_pointer_t>)\n            ==\n    tuple_t<void*, int(*)(), char(*)[10]>\n);\n//! [transform]\n\n}{\n\n//! [replace_if]\nBOOST_HANA_CONSTEXPR_LAMBDA auto negative = [](auto x) {\n    return x < 0;\n};\n\nBOOST_HANA_CONSTEXPR_CHECK(\n    replace_if(make<Tuple>(-3, -2, -1, 0, 1, 2, 3), negative, 0)\n    ==\n    make<Tuple>(0, 0, 0, 0, 1, 2, 3)\n);\n//! [replace_if]\n\n}{\n\n//! [replace]\nBOOST_HANA_CONSTEXPR_CHECK(\n    replace(make<Tuple>(1, 1, 1, 2, 3, 1, 4, 5), 1, 0)\n    ==\n    make<Tuple>(0, 0, 0, 2, 3, 0, 4, 5)\n);\n//! [replace]\n\n}\n\n}\n", "meta": {"hexsha": "e9f17d8e2990f8af0a1b148b77181b84da4f99e6", "size": 2343, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/functor.cpp", "max_stars_repo_name": "josephwinston/hana", "max_stars_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/functor.cpp", "max_issues_repo_name": "josephwinston/hana", "max_issues_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/functor.cpp", "max_forks_repo_name": "josephwinston/hana", "max_forks_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.3739130435, "max_line_length": 83, "alphanum_fraction": 0.6248399488, "num_tokens": 766, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.46636717401233935}}
{"text": "#include <iostream>                      // std::cout/endl/dec/hex\n#include <boost/multiprecision/gmp.hpp>  // boost::multiprecision::gmp_int\n\nusing namespace std;\n\nint main()\n{\n    typedef boost::multiprecision::number<boost::multiprecision::gmp_int,\n                                          boost::multiprecision::et_off>\n        int_type;\n\n    int_type a{\"0x123456789abcdef0\"};\n    int_type b = 16;\n    int_type c{\"0400\"};\n    int_type result = a * b / c;\n    cout << hex << result << endl;\n    cout << dec << result << endl;\n}\n", "meta": {"hexsha": "be5b2db5e72d52a6b2ac6da7173b17510f92d124", "size": 532, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "23/boost_multiprecision/test02_gmp_int.cpp", "max_stars_repo_name": "qsyttkx/geek_time_cpp", "max_stars_repo_head_hexsha": "7650fb6f073822710609da31fc8206f1055bb05a", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 171.0, "max_stars_repo_stars_event_min_datetime": "2020-02-11T01:12:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T07:12:48.000Z", "max_issues_repo_path": "23/boost_multiprecision/test02_gmp_int.cpp", "max_issues_repo_name": "qsyttkx/geek_time_cpp", "max_issues_repo_head_hexsha": "7650fb6f073822710609da31fc8206f1055bb05a", "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": "23/boost_multiprecision/test02_gmp_int.cpp", "max_forks_repo_name": "qsyttkx/geek_time_cpp", "max_forks_repo_head_hexsha": "7650fb6f073822710609da31fc8206f1055bb05a", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 69.0, "max_forks_repo_forks_event_min_datetime": "2020-02-16T08:50:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T07:12:13.000Z", "avg_line_length": 28.0, "max_line_length": 74, "alphanum_fraction": 0.5770676692, "num_tokens": 134, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.6406358479787609, "lm_q1q2_score": 0.4663671690176}}
{"text": "#ifndef STAN_OPTIMIZATION_NEWTON_HPP\n#define STAN_OPTIMIZATION_NEWTON_HPP\n\n#include <stan/model/grad_hess_log_prob.hpp>\n#include <stan/model/log_prob_grad.hpp>\n#include <Eigen/Dense>\n#include <Eigen/Cholesky>\n#include <Eigen/Eigenvalues>\n#include <vector>\n\nnamespace stan {\nnamespace optimization {\n\ntypedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> matrix_d;\ntypedef Eigen::Matrix<double, Eigen::Dynamic, 1> vector_d;\n\n// Negates any positive eigenvalues in H so that H is negative\n// definite, and then solves Hu = g and stores the result into\n// g. Avoids problems due to non-log-concave distributions.\ninline void make_negative_definite_and_solve(matrix_d& H, vector_d& g) {\n  Eigen::SelfAdjointEigenSolver<matrix_d> solver(H);\n  matrix_d eigenvectors = solver.eigenvectors();\n  vector_d eigenvalues = solver.eigenvalues();\n  vector_d eigenprojections = eigenvectors.transpose() * g;\n  for (int i = 0; i < g.size(); i++) {\n    eigenprojections[i] = -eigenprojections[i] / fabs(eigenvalues[i]);\n  }\n  g = eigenvectors * eigenprojections;\n}\n\ntemplate <typename M>\ndouble newton_step(M& model, std::vector<double>& params_r,\n                   std::vector<int>& params_i,\n                   std::ostream* output_stream = 0) {\n  std::vector<double> gradient;\n  std::vector<double> hessian;\n\n  double f0 = stan::model::grad_hess_log_prob<true, false>(\n      model, params_r, params_i, gradient, hessian);\n  matrix_d H(params_r.size(), params_r.size());\n  for (size_t i = 0; i < hessian.size(); i++) {\n    H(i) = hessian[i];\n  }\n  vector_d g(params_r.size());\n  for (size_t i = 0; i < gradient.size(); i++)\n    g(i) = gradient[i];\n  make_negative_definite_and_solve(H, g);\n  //         H.ldlt().solveInPlace(g);\n\n  std::vector<double> new_params_r(params_r.size());\n  double step_size = 2;\n  double min_step_size = 1e-50;\n  double f1 = -1e100;\n\n  while (f1 < f0) {\n    step_size *= 0.5;\n    if (step_size < min_step_size)\n      return f0;\n\n    for (size_t i = 0; i < params_r.size(); i++)\n      new_params_r[i] = params_r[i] - step_size * g[i];\n    try {\n      f1 = stan::model::log_prob_grad<true, false>(model, new_params_r,\n                                                   params_i, gradient);\n    } catch (std::exception& e) {\n      // FIXME:  this is not a good way to handle a general exception\n      f1 = -1e100;\n    }\n  }\n  for (size_t i = 0; i < params_r.size(); i++)\n    params_r[i] = new_params_r[i];\n\n  return f1;\n}\n\n}  // namespace optimization\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "f64dd41b3fbe05e403b04314d607437b3ccd8fe9", "size": 2498, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/stan/optimization/newton.hpp", "max_stars_repo_name": "Dr-G/stan", "max_stars_repo_head_hexsha": "c2dfa08f30d3bd5db936fcc4327cd056cfc1dcbb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/stan/optimization/newton.hpp", "max_issues_repo_name": "Dr-G/stan", "max_issues_repo_head_hexsha": "c2dfa08f30d3bd5db936fcc4327cd056cfc1dcbb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/stan/optimization/newton.hpp", "max_forks_repo_name": "Dr-G/stan", "max_forks_repo_head_hexsha": "c2dfa08f30d3bd5db936fcc4327cd056cfc1dcbb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.6202531646, "max_line_length": 72, "alphanum_fraction": 0.6589271417, "num_tokens": 699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673359709796, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.4663244387699958}}
{"text": "#include <cmath>\n#include <complex>\n#include <ctime>\n#include <string>\n// Boost random generator\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n// Eigen dense matrices\n#include <Eigen/Dense>\n\n#include \"function_dispatcher.h\"\n#include \"json_object.h\"\n#include \"numeric_utils.h\"\n#include \"wittig_sinha.h\"\n\nstochastic::WittigSinha::WittigSinha(std::string exposure_category,\n                                     double gust_speed, double height,\n                                     unsigned int num_floors, double total_time)\n    : StochasticModel(),\n      exposure_category_{exposure_category},\n      gust_speed_{gust_speed * 0.44704}, // Convert from mph to m/s\n      bldg_height_{height},\n      num_floors_{num_floors},\n      seed_value_{std::numeric_limits<int>::infinity()},\n      local_x_{std::vector<double>(1, 1.0)},\n      local_y_{std::vector<double>(1, 1.0)},\n      freq_cutoff_{5.0},\n      time_step_{1.0 / (2.0 * freq_cutoff_)} {\n  model_name_ = \"WittigSinha\";\n  num_times_ =\n      static_cast<unsigned int>(std::ceil(total_time / time_step_)) % 2 == 0\n          ? static_cast<unsigned int>(std::ceil(total_time / time_step_))\n          : static_cast<unsigned int>(std::ceil(total_time / time_step_) + 1);\n\n  // Calculate range of frequencies based on cutoff frequency\n  num_freqs_ = num_times_ / 2;\n  frequencies_.resize(num_freqs_);\n\n  for (unsigned int i = 0; i < frequencies_.size(); ++i) {\n    frequencies_[i] = (i + 1) * freq_cutoff_ / num_freqs_;\n  }\n  \n  // Calculate heights of each floor\n  heights_ = std::vector<double>(num_floors_);  \n  heights_[0] = bldg_height_ / num_floors_;\n\n  for (unsigned int i = 1; i < heights_.size(); ++i) {\n    heights_[i] = heights_[i - 1] + bldg_height_ / num_floors_;\n  }\n\n  // Calculate velocity profile\n  friction_velocity_ =\n      Dispatcher<double, const std::string&, const std::vector<double>&, double,\n                 double, std::vector<double>&>::instance()\n          ->dispatch(\"ExposureCategoryVel\", exposure_category, heights_, 0.4,\n                     gust_speed, wind_velocities_);\n}\n\nstochastic::WittigSinha::WittigSinha(std::string exposure_category,\n                                     double gust_speed, double height,\n                                     unsigned int num_floors, double total_time,\n                                     int seed_value)\n    : WittigSinha(exposure_category, gust_speed, height, num_floors,\n                  total_time)\n{\n  seed_value_ = seed_value;\n}\n\nstochastic::WittigSinha::WittigSinha(std::string exposure_category,\n                                     double gust_speed,\n                                     const std::vector<double>& heights,\n                                     const std::vector<double>& x_locations,\n                                     const std::vector<double>& y_locations,\n                                     double total_time)\n    : StochasticModel(),\n      exposure_category_{exposure_category},\n      gust_speed_{gust_speed * 0.44704}, // Convert from mph to m/s\n      seed_value_{std::numeric_limits<int>::infinity()},\n      heights_{heights},\n      local_x_{x_locations},\n      local_y_{y_locations},\n      freq_cutoff_{5.0},\n      time_step_{1.0 / (2.0 * freq_cutoff_)}\n{\n  model_name_ = \"WittigSinha\";\n  num_times_ =\n      static_cast<unsigned int>(std::ceil(total_time / time_step_)) % 2 == 0\n          ? static_cast<unsigned int>(std::ceil(total_time / time_step_))\n          : static_cast<unsigned int>(std::ceil(total_time / time_step_) + 1);\n\n  // Calculate range of frequencies based on cutoff frequency\n  num_freqs_ = num_times_ / 2;\n  frequencies_.resize(num_freqs_);\n\n  for (unsigned int i = 0; i < frequencies_.size(); ++i) {\n    frequencies_[i] = i * freq_cutoff_ / num_freqs_;\n  }\n\n  // Calculate velocity profile\n  friction_velocity_ =\n      Dispatcher<double, const std::string&, const std::vector<double>&, double,\n                 double, std::vector<double>&>::instance()\n          ->dispatch(\"ExposureCategoryVel\", exposure_category, heights_, 0.4,\n                     gust_speed, wind_velocities_);  \n}\n\nstochastic::WittigSinha::WittigSinha(std::string exposure_category,\n                                     double gust_speed,\n                                     const std::vector<double>& heights,\n                                     const std::vector<double>& x_locations,\n                                     const std::vector<double>& y_locations,\n                                     double total_time, int seed_value)\n  : WittigSinha(exposure_category, gust_speed, heights, x_locations, y_locations, total_time)\n{\n  seed_value_ = seed_value;\n}\n\nutilities::JsonObject stochastic::WittigSinha::generate(const std::string& event_name, bool units) {\n  // Initialize wind velocity vectors\n  std::vector<std::vector<std::vector<std::vector<double>>>> wind_vels(\n      local_x_.size(),\n      std::vector<std::vector<std::vector<double>>>(\n          local_y_.size(),\n          std::vector<std::vector<double>>(\n              heights_.size(), std::vector<double>(num_times_, 0.0))));\n\n  Eigen::MatrixXcd complex_random_vals(num_freqs_, heights_.size());\n  \n  // Loop over heights to find time histories\n  try {\n    for (unsigned int i = 0; i < local_x_.size(); ++i) {\n      for (unsigned int j = 0; j < local_y_.size(); ++j) {\n        // Generate complex random numbers to use for calculation of discrete\n        // time series\n        complex_random_vals = complex_random_numbers();\n        for (unsigned int k = 0; k < heights_.size(); ++k) {\n          wind_vels[i][j][k] = gen_location_hist(complex_random_vals, k, units);\n        }\n      }\n    }\n  } catch (const std::exception& e) {\n    std::cerr << \"\\nERROR: In stochastic::WittigSinha::generate: \"\n              << e.what() << std::endl;\n  }\n\n  // Create JsonObject for event\n  auto event = utilities::JsonObject();\n  event.add_value(\"dT\", time_step_);\n  event.add_value(\"numSteps\", num_times_);\n  \n  // Consider case when only looking at floor loads, so only have time histories as\n  // one location along the z-axis\n  if (local_x_.size() == 1 && local_y_.size() == 1) {\n    // Arrays of patterns and time histories for each floor\n    std::vector<utilities::JsonObject> pattern_array(heights_.size());\n    std::vector<utilities::JsonObject> event_array(1);\n    std::vector<utilities::JsonObject> time_history_array(heights_.size());\n    auto time_history = utilities::JsonObject();\n    event_array[0].add_value(\"type\", \"Wind\");\n    event_array[0].add_value(\"subtype\", model_name_);\n\n    for (unsigned int i = 0; i < heights_.size(); ++i) {\n      // Create pattern\n      pattern_array[i].add_value(\"name\", std::to_string(i + 1));\n      pattern_array[i].add_value(\"timeSeries\", std::to_string(i + 1));\n      pattern_array[i].add_value(\"type\", \"WindFloorLoad\");\n      pattern_array[i].add_value(\"floor\", std::to_string(i + 1));\n      pattern_array[i].add_value(\"dof\", 1);\n      pattern_array[i].add_value(\"profileVelocity\", wind_velocities_[i]);\n      \n      // Create time histories\n      time_history.add_value(\"name\", std::to_string(i + 1));\n      time_history.add_value(\"dT\", time_step_);\n      time_history.add_value(\"type\", \"Value\");\n      time_history.add_value(\"data\", wind_vels[0][0][i]);\n      time_history_array[i] = time_history;\n      time_history.clear();\n    }\n    \n    event_array[0].add_value(\"timeSeries\", time_history_array);\n    event_array[0].add_value(\"pattern\", pattern_array);\n    event.add_value(\"Events\", event_array);   \n  } else {\n    throw std::runtime_error(\n        \"ERROR: In stochastic::WittigSinha::generate: Currently, only supports \"\n        \"time histories along z-axis at single location\\n\");\n  }\n\n  return event;\n}\n\nbool stochastic::WittigSinha::generate(const std::string& event_name,\n                                       const std::string& output_location,\n                                       bool units) {\n\n  bool status = true;\n  // Generate time histories at specified locations\n  try {\n    auto json_output = generate(event_name, units);\n    json_output.write_to_file(output_location);\n  } catch (const std::exception& e) {\n    std::cerr << e.what();\n    status = false;\n    throw;\n  }\n\n  return status;\n}\n\nEigen::MatrixXd stochastic::WittigSinha::cross_spectral_density(double frequency) const {\n  // Coefficient for coherence function\n  double coherence_coeff = 10.0;\n  Eigen::MatrixXd cross_spectral_density =\n      Eigen::MatrixXd::Zero(heights_.size(), heights_.size());\n  \n  for (unsigned int i = 0; i < cross_spectral_density.rows(); ++i) {\n    cross_spectral_density(i, i) =\n        200.0 * friction_velocity_ * friction_velocity_ * heights_[i] /\n        (wind_velocities_[i] *\n         std::pow(1.0 + 50.0 * frequency * heights_[i] / wind_velocities_[i],\n                  5.0 / 3.0));\n  }\n\n  for (unsigned int i = 0; i < cross_spectral_density.rows(); ++i) {\n    for (unsigned int j = i + 1; j < cross_spectral_density.cols(); ++j) {\n      cross_spectral_density(i, j) =\n          std::sqrt(cross_spectral_density(i, i) *\n                    cross_spectral_density(j, j)) *\n          std::exp(-coherence_coeff * frequency *\n                   std::abs(heights_[i] - heights_[j]) /\n                   (0.5 * (wind_velocities_[i] + wind_velocities_[j]))) *\n          0.999;\n    }\n  }\n\n  // Get diagonal of cross spectral density matrix--avoids compiler errors where type\n  // of diagonal matrix is not correctly deduced\n  Eigen::MatrixXd diag_mat = cross_spectral_density.diagonal().asDiagonal();\n\n  return cross_spectral_density.transpose() + cross_spectral_density - diag_mat;\n}\n\nEigen::MatrixXcd stochastic::WittigSinha::complex_random_numbers() const {\n  // Construct random number generator for standard normal distribution\n  static unsigned int history_seed = static_cast<unsigned int>(std::time(nullptr));\n  history_seed = history_seed + 10;\n\n  auto generator =\n    seed_value_ != std::numeric_limits<int>::infinity()\n    ? boost::random::mt19937(static_cast<unsigned int>(seed_value_ + 10))\n    : boost::random::mt19937(history_seed);\n  \n  boost::random::normal_distribution<> distribution;\n  boost::random::variate_generator<boost::random::mt19937&,\n                                   boost::random::normal_distribution<>>\n      distribution_gen(generator, distribution);\n\n  // Generate white noise consisting of complex numbers\n  Eigen::MatrixXcd white_noise(heights_.size(), num_freqs_);\n\n  for (unsigned int i = 0; i < white_noise.rows(); ++i) {\n    for (unsigned int j = 0; j < white_noise.cols(); ++j) {\n      white_noise(i, j) = std::complex<double>(\n          distribution_gen() * std::sqrt(0.5),\n          distribution_gen() * std::sqrt(std::complex<double>(-0.5)).imag());\n    }\n  }\n\n  // Iterator over all frequencies and generate complex random numbers\n  // for discrete time series simulation\n  Eigen::MatrixXd cross_spec_density_matrix(heights_.size(), heights_.size());\n  Eigen::MatrixXcd complex_random(num_freqs_, heights_.size());\n\n  for (unsigned int i = 0; i < frequencies_.size(); ++i) {\n    // Calculate cross-spectral density matrix for current frequency\n    cross_spec_density_matrix = cross_spectral_density(frequencies_[i]);\n\n    // Find lower Cholesky factorization of cross-spectral density\n    Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> lower_cholesky;\n\n    try {\n      auto llt = cross_spec_density_matrix.llt();\n      lower_cholesky = llt.matrixL();\n\n      if (llt.info() == Eigen::NumericalIssue) {\n        throw std::runtime_error(\n            \"\\nERROR: In stochastic::WittigSinha::generate method: Cross-Spectral Density \"\n            \"matrix is not positive semi-definite\\n\");\n      }\n    } catch (const std::exception& e) {\n      std::cerr << \"\\nERROR: In time history generation: \" << e.what()\n                << std::endl;\n    }\n    \n    // This is Equation 5(a) from Wittig & Sinha (1975)\n    complex_random.row(i) = num_freqs_ *\n                            std::sqrt(2.0 * freq_cutoff_ / num_freqs_) *\n                            lower_cholesky * white_noise.col(i);\n  }\n\n  return complex_random;\n}\n\nstd::vector<double> stochastic::WittigSinha::gen_location_hist(\n    const Eigen::MatrixXcd& random_numbers, unsigned int column_index,\n    bool units) const {\n\n  // This following block implements what is expressed in Equations 7 & 8\n  Eigen::VectorXcd complex_full_range = Eigen::VectorXcd::Zero(2 * num_freqs_);\n\n  complex_full_range.segment(1, num_freqs_) =\n      random_numbers.block(0, column_index, num_freqs_, 1);\n\n  complex_full_range.segment(num_freqs_ + 1, num_freqs_ - 1) =\n      random_numbers.block(0, column_index, num_freqs_ - 1, 1)\n          .reverse()\n          .conjugate();\n \n  complex_full_range(num_freqs_) = std::abs(random_numbers(num_freqs_ - 1, column_index)); \n\n  // Calculate wind speed using real portion of inverse Fast Fourier Transform\n  // full range of random numbers\n  std::vector<double> node_time_history(complex_full_range.size());\n  numeric_utils::inverse_fft(complex_full_range, node_time_history);\n\n  // Check if time histories need to be converted to ft/s\n  if (units) {\n    for (auto & val : node_time_history) {\n      val = val * 3.28084;\n    }\n  }\n  \n  return node_time_history;\n}\n", "meta": {"hexsha": "8c41f83984a236073f6de0f815d60df12455aaa6", "size": 13254, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/wittig_sinha.cc", "max_stars_repo_name": "charlesxwang/smelt", "max_stars_repo_head_hexsha": "da1f66ec857dd8ff8e9de104fbb3ecbd0ec84367", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-05-07T03:14:27.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-19T07:10:52.000Z", "max_issues_repo_path": "src/wittig_sinha.cc", "max_issues_repo_name": "charlesxwang/smelt", "max_issues_repo_head_hexsha": "da1f66ec857dd8ff8e9de104fbb3ecbd0ec84367", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-04-11T19:29:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-11T19:29:47.000Z", "max_forks_repo_path": "src/wittig_sinha.cc", "max_forks_repo_name": "charlesxwang/smelt", "max_forks_repo_head_hexsha": "da1f66ec857dd8ff8e9de104fbb3ecbd0ec84367", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-03-25T20:08:22.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-04T13:02:31.000Z", "avg_line_length": 39.4464285714, "max_line_length": 100, "alphanum_fraction": 0.6410140335, "num_tokens": 3252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4663244283672521}}
{"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_FAST_HYPOT_HPP_INCLUDED\n#define BOOST_SIMD_ARITHMETIC_FUNCTIONS_SCALAR_FAST_HYPOT_HPP_INCLUDED\n\n#include <boost/simd/arithmetic/functions/fast_hypot.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/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/functions/scalar/fma.hpp>\n#include <boost/simd/include/constants/eps.hpp>\n#include <boost/simd/include/constants/inf.hpp>\n#include <boost/simd/include/constants/nan.hpp>\n#include <boost/simd/include/constants/one.hpp>\n#include <boost/dispatch/meta/as_integer.hpp>\n#include <boost/dispatch/meta/as_floating.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::fast_hypot_, tag::cpu_\n                            , (A0)\n                            , (scalar_< arithmetic_<A0> >)\n                              (scalar_< arithmetic_<A0> >)\n                            )\n  {\n    typedef typename boost::dispatch::meta::as_floating<A0>::type result_type;\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    {\n      return boost::simd::fast_hypot(static_cast<result_type>(a0),\n                                     static_cast<result_type>(a1));\n    }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::fast_hypot_, tag::cpu_\n                            , (A0)\n                            , (scalar_< double_<A0> >)\n                              (scalar_< double_<A0> >)\n                            )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    {\n#if !defined(BOOST_SIMD_NO_NANS) && !defined(BOOST_SIMD_NO_INFINITIES)\n      A0 x =  boost::simd::abs(a0);\n      A0 y =  boost::simd::abs(a1);\n      if (boost::simd::is_inf(x+y)) return Inf<float>();\n      if (boost::simd::is_inf(x)) return Inf<float>();\n      if (boost::simd::is_inf(y)) return Inf<float>();\n      if (y > x) std::swap(x, y);\n      if (x*Eps<A0>() >=  y) return x;\n      return x*boost::simd::sqrt(One<A0>()+boost::simd::sqr(y/x));\n#else\n      return boost::simd::sqrt(boost::simd::fma(a0, a0, a1*a1));\n#endif\n    }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::fast_hypot_, tag::cpu_\n                            , (A0)\n                            , (scalar_< single_<A0> >)\n                              (scalar_< single_<A0> >)\n                            )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    {\n#if !defined(BOOST_SIMD_NO_NANS) && !defined(BOOST_SIMD_NO_INFINITIES)\n      // flibc do that in ::fast_hypotf(a0, a1) in asm with no more speed!\n      // proper impl as for double is 30% slower\n      return static_cast<result_type>(boost::simd::sqrt(fma(static_cast<double>(a0), static_cast<double>(a0),\n                                                            boost::simd::sqr(static_cast<double>(a1)))));\n#else\n      return boost::simd::sqrt(boost::simd::fma(a0, a0, a1*a1));\n#endif\n    }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "1dfa6fdf775be514ade6f466bb45b91e16236eba", "size": 3629, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/arithmetic/include/boost/simd/arithmetic/functions/scalar/fast_hypot.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/scalar/fast_hypot.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/scalar/fast_hypot.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": 40.7752808989, "max_line_length": 109, "alphanum_fraction": 0.5794984844, "num_tokens": 906, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708698, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.46632442316587996}}
{"text": "// ---------------------------------------------------------------------\n//\n// Copyright (c) 2014 - 2019 by the IBAMR developers\n// All rights reserved.\n//\n// This file is part of IBAMR.\n//\n// IBAMR is free software and is distributed under the 3-clause BSD\n// license. The full text of the license can be found in the file\n// COPYRIGHT at the top level directory of IBAMR.\n//\n// ---------------------------------------------------------------------\n\n/////////////////////////////// INCLUDES /////////////////////////////////////\n\n#include \"ibamr/IBFEPatchRecoveryPostProcessor.h\"\n#include \"ibamr/IBHierarchyIntegrator.h\"\n#include \"ibamr/namespaces.h\" // IWYU pragma: keep\n\n#include \"ibtk/IBTK_CHKERRQ.h\"\n#include \"ibtk/IndexUtilities.h\"\n#include \"ibtk/LEInteractor.h\"\n#include \"ibtk/libmesh_utilities.h\"\n\n#include \"SAMRAI_config.h\"\n\n#include \"libmesh/boundary_info.h\"\n#include \"libmesh/dense_vector.h\"\n#include \"libmesh/dof_map.h\"\n#include \"libmesh/equation_systems.h\"\n#include \"libmesh/fe_base.h\"\n#include \"libmesh/fe_interface.h\"\n#include \"libmesh/mesh.h\"\n#include \"libmesh/periodic_boundaries.h\"\n#include \"libmesh/periodic_boundary.h\"\n#include \"libmesh/petsc_vector.h\"\n#include \"libmesh/quadrature.h\"\n#include \"libmesh/string_to_enum.h\"\n\nIBTK_DISABLE_EXTRA_WARNINGS\n#include <boost/multi_array.hpp>\nIBTK_ENABLE_EXTRA_WARNINGS\n\nIBTK_DISABLE_EXTRA_WARNINGS\n#include \"Eigen/Dense\"\nIBTK_ENABLE_EXTRA_WARNINGS\n\nusing namespace libMesh;\n\n/////////////////////////////// NAMESPACE ////////////////////////////////////\n\nnamespace IBAMR\n{\n/////////////////////////////// STATIC ///////////////////////////////////////\n\nnamespace\n{\nunsigned int\nnum_polynomial_basis_fcns(const unsigned int dim, const unsigned int order)\n{\n    unsigned int num_basis_fcns = 0;\n    unsigned int order_p_1 = order + 1;\n    switch (dim)\n    {\n    case 1:\n        num_basis_fcns = order_p_1;\n        break;\n    case 2:\n        num_basis_fcns = order_p_1 * order_p_1 + order_p_1;\n        num_basis_fcns /= 2;\n        break;\n    case 3:\n        num_basis_fcns = order_p_1 * order_p_1 * order_p_1 + 3 * order_p_1 * order_p_1 + 2 * order_p_1;\n        num_basis_fcns /= 6;\n        break;\n    default:\n        TBOX_ERROR(\"only supports dim = 1, 2, or 3\\n\");\n    }\n    return num_basis_fcns;\n} // num_polynomial_basis_fcns\n\nvoid\nevaluate_polynomial_basis_fcns(Eigen::VectorXd& P,\n                               const libMesh::Point& x_center,\n                               const libMesh::Point& x_eval,\n                               const unsigned int dim,\n                               const unsigned int order)\n{\n    TBOX_ASSERT(static_cast<unsigned int>(P.size()) == num_polynomial_basis_fcns(dim, order));\n\n    // Compute powers of the components of x up to the specified order.\n    libMesh::Point x = x_center - x_eval;\n    boost::multi_array<double, 2> x_pow(boost::extents[dim][order + 1]);\n    for (unsigned int d = 0; d < dim; ++d)\n    {\n        x_pow[d][0] = 1.0;\n        for (unsigned int k = 1; k <= order; ++k)\n        {\n            x_pow[d][k] = x(d) * x_pow[d][k - 1];\n        }\n    }\n\n    // Evaluate the complete polynomial basis functions of the specified order.\n    static const unsigned int X_IDX = 0;\n    static const unsigned int Y_IDX = 1;\n    static const unsigned int Z_IDX = 2;\n    switch (dim)\n    {\n    case 1:\n        for (unsigned int total_pow = 0, k = 0; total_pow <= order; ++total_pow, ++k)\n        {\n            unsigned int x_exp = total_pow;\n            P(k) = x_pow[X_IDX][x_exp];\n        }\n        break;\n    case 2:\n        for (unsigned int total_pow = 0, k = 0; total_pow <= order; ++total_pow)\n        {\n            for (unsigned int x_exp = 0; x_exp <= total_pow; ++x_exp, ++k)\n            {\n                unsigned int y_exp = total_pow - x_exp;\n                P(k) = x_pow[X_IDX][x_exp] * x_pow[Y_IDX][y_exp];\n            }\n        }\n        break;\n    case 3:\n        for (unsigned int total_pow = 0, k = 0; total_pow <= order; ++total_pow)\n        {\n            for (unsigned int x_exp = 0; x_exp <= total_pow; ++x_exp)\n            {\n                for (unsigned int y_exp = 0; y_exp <= total_pow - x_exp; ++y_exp, ++k)\n                {\n                    unsigned int z_exp = total_pow - (x_exp + y_exp);\n                    P(k) = x_pow[X_IDX][x_exp] * x_pow[Y_IDX][y_exp] * x_pow[Z_IDX][z_exp];\n                }\n            }\n        }\n        break;\n    default:\n        TBOX_ERROR(\"only supports dim = 1, 2, or 3\\n\");\n    }\n    return;\n} // evaluate_polynomial_basis_fcns\n} // namespace\n\n/////////////////////////////// PUBLIC ///////////////////////////////////////\n\nIBFEPatchRecoveryPostProcessor::IBFEPatchRecoveryPostProcessor(MeshBase* mesh, FEDataManager* fe_data_manager)\n    : d_mesh(mesh),\n      d_fe_data_manager(fe_data_manager),\n      d_periodic_boundaries(nullptr),\n      d_interp_order(INVALID_ORDER),\n      d_quad_order(INVALID_ORDER)\n{\n    // Active local elements.\n    const MeshBase::const_element_iterator el_begin = d_mesh->active_local_elements_begin();\n    const MeshBase::const_element_iterator el_end = d_mesh->active_local_elements_end();\n\n    // Determine the number of quadrature/interpolation points in each element.\n    //\n    // We use full-order Gaussian quadrature rules (i.e. third-order Gauss\n    // quadrature for first-order elements and fifth-order Gauss quadrature for\n    // second-order elements) in all elements to avoid special treatment at\n    // boundary nodes.\n    bool first_order_elems = false;\n    bool second_order_elems = false;\n    for (MeshBase::const_element_iterator el_it = el_begin; el_it != el_end; ++el_it)\n    {\n        const Elem* const elem = *el_it;\n        const unsigned int dim = elem->dim();\n        TBOX_ASSERT(dim == d_mesh->mesh_dimension());\n        Order elem_order = elem->default_order();\n        if (elem_order == FIRST) first_order_elems = true;\n        if (elem_order == SECOND) second_order_elems = true;\n        TBOX_ASSERT(elem_order == FIRST || elem_order == SECOND);\n    }\n    if (first_order_elems && second_order_elems)\n    {\n        TBOX_ERROR(\n            \"cannot have both first- and second-order elements in the same \"\n            \"mesh.\\n\");\n    }\n    d_interp_order = first_order_elems ? FIRST : SECOND;\n    d_quad_order = first_order_elems ? THIRD : FIFTH;\n    return;\n} // IBFEPatchRecoveryPostProcessor\n\nIBFEPatchRecoveryPostProcessor::~IBFEPatchRecoveryPostProcessor()\n{\n    // intentionally blank\n    return;\n} // ~IBFEPatchRecoveryPostProcessor\n\nvoid\nIBFEPatchRecoveryPostProcessor::initializeFEData(const PeriodicBoundaries* const periodic_boundaries)\n{\n    d_periodic_boundaries = periodic_boundaries;\n\n    const Parallel::Communicator& comm = d_mesh->comm();\n    const int mpi_rank = comm.rank();\n    const int mpi_size = comm.size();\n\n    // Active local elements.\n    const MeshBase::const_element_iterator el_begin = d_mesh->active_local_elements_begin();\n    const MeshBase::const_element_iterator el_end = d_mesh->active_local_elements_end();\n\n    // Determine the element patches associated with each node N, which is\n    // defined to be the collection of elements that contain node N.\n    //\n    // Unlike the standard Z-Z patch recovery algorithm, we use \"tight\" element\n    // patches for non-vertex nodes.\n    std::unique_ptr<PointLocatorBase> point_locator = PointLocatorBase::build(TREE, *d_mesh);\n    for (MeshBase::const_element_iterator el_it = el_begin; el_it != el_end; ++el_it)\n    {\n        const Elem* const elem = *el_it;\n        for (unsigned int n = 0; n < elem->n_nodes(); ++n)\n        {\n            // Only set up patches for local nodes.\n            const Node* const node = elem->get_node_ptr(n);\n            if (node->processor_id() != mpi_rank) continue;\n\n            // Only set up patches once for each node.\n            const dof_id_type node_id = node->id();\n            if (d_local_elem_patches.find(node_id) != d_local_elem_patches.end()) continue;\n\n            // Find the elements that touch this node.\n            ElemPatch& elem_patch = d_local_elem_patches[node_id];\n            std::set<const Elem*> elems;\n            elem->find_point_neighbors(*node, elems);\n            for (std::set<const Elem*>::const_iterator it = elems.begin(); it != elems.end(); ++it)\n            {\n                elem_patch.insert(boost::make_tuple(*it, CompositePeriodicMapping(), CompositePeriodicMapping()));\n            }\n\n            // Account for periodic boundaries.\n            bool done = false || !d_periodic_boundaries;\n            while (!done)\n            {\n                ElemPatch periodic_neighbors;\n                for (ElemPatch::const_iterator it = elem_patch.begin(); it != elem_patch.end(); ++it)\n                {\n                    const Elem* const elem = it->get<0>();\n                    const CompositePeriodicMapping& forward_mapping = it->get<1>();\n                    const CompositePeriodicMapping& inverse_mapping = it->get<2>();\n                    const libMesh::Point p = apply_composite_periodic_mapping(forward_mapping, *node);\n                    TBOX_ASSERT(elem->contains_point(p));\n                    for (unsigned int i = 0; i < elem->n_neighbors(); ++i)\n                    {\n                        if (!elem->neighbor_ptr(i))\n                        {\n                            const std::vector<boundary_id_type>& boundary_ids =\n                                d_mesh->boundary_info->boundary_ids(elem, i);\n                            for (std::vector<boundary_id_type>::const_iterator j = boundary_ids.begin();\n                                 j != boundary_ids.end();\n                                 ++j)\n                            {\n                                const boundary_id_type boundary_id = *j;\n                                const PeriodicBoundaryBase* const periodic_boundary =\n                                    d_periodic_boundaries->boundary(boundary_id);\n                                if (periodic_boundary)\n                                {\n                                    const libMesh::Point periodic_image = periodic_boundary->get_corresponding_pos(p);\n                                    const Elem* neighbor =\n                                        d_periodic_boundaries->neighbor_ptr(boundary_id, *point_locator, elem, i);\n                                    if (elem->level() < neighbor->level())\n                                    {\n                                        neighbor = neighbor->parent();\n                                    }\n                                    if (neighbor->contains_point(periodic_image))\n                                    {\n                                        std::set<const Elem*> elems;\n                                        neighbor->find_point_neighbors(periodic_image, elems);\n                                        for (std::set<const Elem*>::const_iterator k = elems.begin(); k != elems.end();\n                                             ++k)\n                                        {\n                                            const Elem* const elem = *k;\n                                            if (elem_patch.find(elem) == elem_patch.end() &&\n                                                periodic_neighbors.find(elem) == periodic_neighbors.end())\n                                            {\n                                                CompositePeriodicMapping forward = forward_mapping;\n                                                CompositePeriodicMapping inverse = inverse_mapping;\n                                                forward.insert(\n                                                    forward.end(),\n                                                    periodic_boundary->clone(PeriodicBoundaryBase::FORWARD).release());\n                                                inverse.insert(\n                                                    inverse.begin(),\n                                                    periodic_boundary->clone(PeriodicBoundaryBase::INVERSE).release());\n                                                periodic_neighbors.insert(boost::make_tuple(elem, forward, inverse));\n                                            }\n                                        }\n                                    }\n                                }\n                            }\n                        }\n                    }\n                }\n                elem_patch.insert(periodic_neighbors.begin(), periodic_neighbors.end());\n                periodic_neighbors.clear();\n                done = periodic_neighbors.empty();\n            }\n        }\n    }\n\n    // Setup mappings used to fill global indexing data structures.\n    //\n    // We use full-order Gaussian quadrature rules (i.e. third-order Gauss\n    // quadrature for first-order elements and fifth-order Gauss quadrature for\n    // second-order elements) in all elements to avoid special treatment at\n    // boundary nodes.\n    d_n_qp_global = 0;\n    d_n_qp_local = 0;\n    d_qp_global_offset = 0;\n    const unsigned int n_elem = d_mesh->n_elem();\n    d_elem_n_qp.resize(n_elem, 0);\n    d_elem_qp_global_offset.resize(n_elem, 0);\n    d_elem_qp_local_offset.resize(n_elem, 0);\n    std::unique_ptr<QBase> qrule;\n    for (MeshBase::const_element_iterator el_it = el_begin; el_it != el_end; ++el_it)\n    {\n        const Elem* const elem = *el_it;\n        const unsigned int dim = elem->dim();\n        bool reinit_qrule = false;\n        if (!qrule.get() || qrule->get_dim() != dim || qrule->get_order() != d_quad_order)\n        {\n            qrule = QBase::build(QGAUSS, dim, d_quad_order);\n            reinit_qrule = true;\n        }\n        else if (qrule->get_elem_type() != elem->type() || qrule->get_p_level() != elem->p_level())\n        {\n            reinit_qrule = true;\n        }\n        if (reinit_qrule) qrule->init(elem->type(), elem->p_level());\n        unsigned int n_qp = qrule->n_points();\n        const dof_id_type elem_id = elem->id();\n        d_elem_n_qp[elem_id] = n_qp;\n        d_elem_qp_local_offset[elem_id] = d_n_qp_local;\n        d_n_qp_local += n_qp;\n        d_elem_sigma[elem->id()].resize(n_qp);\n        d_elem_pressure[elem->id()].resize(n_qp);\n    }\n    std::vector<int> n_qp_per_proc(mpi_size);\n    n_qp_per_proc[mpi_rank] = d_n_qp_local;\n    comm.sum(n_qp_per_proc);\n    d_qp_global_offset = std::accumulate(n_qp_per_proc.begin(), n_qp_per_proc.begin() + mpi_rank, 0);\n    d_n_qp_global = std::accumulate(n_qp_per_proc.begin() + mpi_rank, n_qp_per_proc.end(), d_qp_global_offset);\n    for (MeshBase::const_element_iterator el_it = el_begin; el_it != el_end; ++el_it)\n    {\n        const Elem* const elem = *el_it;\n        const dof_id_type elem_id = elem->id();\n        d_elem_qp_global_offset[elem_id] = d_elem_qp_local_offset[elem_id] + d_qp_global_offset;\n    }\n    comm.sum(d_elem_qp_global_offset);\n    comm.sum(d_elem_qp_local_offset);\n\n    // Set up element patch L2 projection matrices.\n    unsigned int dim = d_mesh->mesh_dimension();\n    const unsigned int num_basis_fcns = num_polynomial_basis_fcns(dim, d_interp_order);\n    Eigen::MatrixXd M(num_basis_fcns, num_basis_fcns);\n    Eigen::VectorXd P(num_basis_fcns);\n    std::unique_ptr<FEBase> fe(FEBase::build(dim, FEType(d_interp_order, LAGRANGE)));\n    const std::vector<libMesh::Point>& q_point = fe->get_xyz();\n    qrule = QBase::build(QGAUSS, dim, d_quad_order);\n    fe->attach_quadrature_rule(qrule.get());\n    d_local_patch_proj_solver.resize(d_local_elem_patches.size());\n    unsigned int k = 0;\n    for (std::map<dof_id_type, ElemPatch>::iterator it = d_local_elem_patches.begin(); it != d_local_elem_patches.end();\n         ++it, ++k)\n    {\n        const dof_id_type node_id = it->first;\n        const Node& node = d_mesh->node(node_id);\n        ElemPatch& elem_patch = it->second;\n        M.setZero();\n        for (ElemPatch::const_iterator el_it = elem_patch.begin(); el_it != elem_patch.end(); ++el_it)\n        {\n            const Elem* const elem = el_it->get<0>();\n            const CompositePeriodicMapping& inverse_mapping = el_it->get<2>();\n            fe->reinit(elem);\n            for (unsigned int qp = 0; qp < qrule->n_points(); ++qp)\n            {\n                evaluate_polynomial_basis_fcns(\n                    P, node, apply_composite_periodic_mapping(inverse_mapping, q_point[qp]), dim, d_interp_order);\n                M += P * P.transpose();\n            }\n        }\n        d_local_patch_proj_solver[k] = M.colPivHouseholderQr();\n        if (!d_local_patch_proj_solver[k].isInvertible())\n        {\n            TBOX_ERROR(\n                \"IBFEPatchRecoveryPostProcessor could not construct L2 \"\n                \"reconstruction for element patch associated with node \"\n                << node_id << \"\\n\");\n        }\n    }\n    return;\n} // initializeFEData\n\nSystem*\nIBFEPatchRecoveryPostProcessor::initializeCauchyStressSystem()\n{\n    EquationSystems* equation_systems = d_fe_data_manager->getEquationSystems();\n    System* sigma_system = &equation_systems->add_system<System>(\"CAUCHY_STRESS_RECOVERY_SYSTEM\");\n    for (unsigned int i = 0; i < NDIM; ++i)\n    {\n        for (unsigned int j = i; j < NDIM; ++j)\n        {\n            std::string var_name = \"sigma_\";\n            var_name += (i == 0 ? 'x') : i == 1 ? 'y' : 'z');\n            var_name += (j == 0 ? 'x') : j == 1 ? 'y' : 'z');\n\n            sigma_system->add_variable(var_name), d_interp_order, LAGRANGE);\n        }\n    }\n    return sigma_system;\n} // initializeCauchyStressSystem\n\nSystem*\nIBFEPatchRecoveryPostProcessor::initializePressureSystem()\n{\n    EquationSystems* equation_systems = d_fe_data_manager->getEquationSystems();\n    System* p_system = &equation_systems->add_system<System>(\"PRESSURE_RECOVERY_SYSTEM\");\n    p_system->add_variable(\"p\", d_interp_order, LAGRANGE);\n    return p_system;\n} // initializePressureSystem\n\nvoid\nIBFEPatchRecoveryPostProcessor::registerCauchyStressValue(const Elem* const elem,\n                                                          const QBase* const qrule,\n                                                          const unsigned int qp,\n                                                          const TensorValue<double>& sigma)\n{\n    const Parallel::Communicator& comm = d_mesh->comm();\n    if (elem->processor_id() != comm.rank() || !elem->active())\n    {\n        TBOX_ERROR(\"must register stresses only for active local elements\\n\");\n    }\n    TBOX_ASSERT(elem->default_order() == d_interp_order);\n    TBOX_ASSERT(qrule->type() == QGAUSS);\n    TBOX_ASSERT(qrule->get_order() == d_quad_order);\n    TBOX_ASSERT(qrule->get_elem_type() == elem->type());\n    TBOX_ASSERT(qrule->get_p_level() == elem->p_level());\n    TBOX_ASSERT(qp < d_elem_n_qp[elem->id()]);\n    d_elem_sigma[elem->id()][qp] = sigma;\n    return;\n} // registerCauchyStressValue\n\nvoid\nIBFEPatchRecoveryPostProcessor::registerPressureValue(const Elem* const elem,\n                                                      const QBase* const qrule,\n                                                      const unsigned int qp,\n                                                      const double p)\n{\n    const Parallel::Communicator& comm = d_mesh->comm();\n    if (elem->processor_id() != comm.rank() || !elem->active())\n    {\n        TBOX_ERROR(\"must register pressures only for active local elements\\n\");\n    }\n    TBOX_ASSERT(elem->default_order() == d_interp_order);\n    TBOX_ASSERT(qrule->type() == QGAUSS);\n    TBOX_ASSERT(qrule->get_order() == d_quad_order);\n    TBOX_ASSERT(qrule->get_elem_type() == elem->type());\n    TBOX_ASSERT(qrule->get_p_level() == elem->p_level());\n    TBOX_ASSERT(qp < d_elem_n_qp[elem->id()]);\n    d_elem_pressure[elem->id()][qp] = p;\n    return;\n} // registerPressureValue\n\nvoid\nIBFEPatchRecoveryPostProcessor::reconstructCauchyStress(System& sigma_system)\n{\n    const unsigned int sigma_sys_num = sigma_system.number();\n    NumericVector<double>& sigma_vec = *sigma_system.solution;\n\n    // Communicate the stored values of the Cauchy stress.\n    static const unsigned int NVARS = (NDIM * (NDIM + 1)) / 2;\n    std::vector<double> sigma_vals(NVARS * d_n_qp_global, 0.0);\n    const MeshBase::const_element_iterator el_begin = d_mesh->active_local_elements_begin();\n    const MeshBase::const_element_iterator el_end = d_mesh->active_local_elements_end();\n    for (MeshBase::const_element_iterator el_it = el_begin; el_it != el_end; ++el_it)\n    {\n        const Elem* const elem = *el_it;\n        const dof_id_type elem_id = elem->id();\n        const int global_offset = d_elem_qp_global_offset[elem_id];\n        for (unsigned int qp = 0; qp < d_elem_n_qp[elem_id]; ++qp)\n        {\n            const TensorValue<double>& stress = d_elem_sigma[elem_id][qp];\n            for (unsigned int i = 0, k = 0; i < NDIM; ++i)\n            {\n                for (unsigned int j = i; j < NDIM; ++j, ++k)\n                {\n                    sigma_vals[NVARS * (global_offset + qp) + k] = stress(i, j);\n                }\n            }\n        }\n    }\n    const Parallel::Communicator& comm = d_mesh->comm();\n    comm.sum(sigma_vals);\n\n    // Perform element patch L2 projections.\n    const unsigned int dim = d_mesh->mesh_dimension();\n    const unsigned int num_basis_fcns = num_polynomial_basis_fcns(dim, d_interp_order);\n    Eigen::VectorXd P(num_basis_fcns), a(num_basis_fcns), f(num_basis_fcns);\n    std::unique_ptr<FEBase> fe(FEBase::build(dim, FEType(d_interp_order, LAGRANGE)));\n    const std::vector<libMesh::Point>& q_point = fe->get_xyz();\n    std::unique_ptr<QBase> qrule = QBase::build(QGAUSS, dim, d_quad_order);\n    fe->attach_quadrature_rule(qrule.get());\n    unsigned int k = 0;\n    for (std::map<dof_id_type, ElemPatch>::const_iterator it = d_local_elem_patches.begin();\n         it != d_local_elem_patches.end();\n         ++it, ++k)\n    {\n        const dof_id_type node_id = it->first;\n        const Node& node = d_mesh->node(node_id);\n        const ElemPatch& elem_patch = it->second;\n        Eigen::ColPivHouseholderQR<Eigen::MatrixXd>& patch_proj_solver = d_local_patch_proj_solver[k];\n        for (unsigned int var = 0; var < NVARS; ++var)\n        {\n            // Solve for the coefficients of the reconstruction.\n            f.setZero();\n            for (ElemPatch::const_iterator el_it = elem_patch.begin(); el_it != elem_patch.end(); ++el_it)\n            {\n                const Elem* const elem = el_it->get<0>();\n                const CompositePeriodicMapping& inverse_mapping = el_it->get<2>();\n                const dof_id_type elem_id = elem->id();\n                const int global_offset = d_elem_qp_global_offset[elem_id];\n                fe->reinit(elem);\n                for (unsigned int qp = 0; qp < qrule->n_points(); ++qp)\n                {\n                    evaluate_polynomial_basis_fcns(\n                        P, node, apply_composite_periodic_mapping(inverse_mapping, q_point[qp]), dim, d_interp_order);\n                    f += P * sigma_vals[NVARS * (global_offset + qp) + var];\n                }\n            }\n            a = patch_proj_solver.solve(f);\n\n            // Evaluate the reconstruction at the node.\n            const int dof_index = node.dof_number(sigma_sys_num, var, 0);\n            sigma_vec.set(dof_index, a(0));\n        }\n    }\n    return;\n} // reconstructCauchyStress\n\nvoid\nIBFEPatchRecoveryPostProcessor::reconstructPressure(System& p_system)\n{\n    const unsigned int p_sys_num = p_system.number();\n    NumericVector<double>& p_vec = *p_system.solution;\n\n    // Communicate the stored values of the Cauchy stress.\n    std::vector<double> pressure_vals(d_n_qp_global, 0.0);\n    const MeshBase::const_element_iterator el_begin = d_mesh->active_local_elements_begin();\n    const MeshBase::const_element_iterator el_end = d_mesh->active_local_elements_end();\n    for (MeshBase::const_element_iterator el_it = el_begin; el_it != el_end; ++el_it)\n    {\n        const Elem* const elem = *el_it;\n        const dof_id_type elem_id = elem->id();\n        const int global_offset = d_elem_qp_global_offset[elem_id];\n        for (unsigned int qp = 0; qp < d_elem_n_qp[elem_id]; ++qp)\n        {\n            pressure_vals[global_offset + qp] = d_elem_pressure[elem_id][qp];\n        }\n    }\n    const Parallel::Communicator& comm = d_mesh->comm();\n    comm.sum(pressure_vals);\n\n    // Perform element patch L2 projections.\n    const unsigned int dim = d_mesh->mesh_dimension();\n    const unsigned int num_basis_fcns = num_polynomial_basis_fcns(dim, d_interp_order);\n    Eigen::VectorXd P(num_basis_fcns), a(num_basis_fcns), f(num_basis_fcns);\n    std::unique_ptr<FEBase> fe(FEBase::build(dim, FEType(d_interp_order, LAGRANGE)));\n    const std::vector<libMesh::Point>& q_point = fe->get_xyz();\n    std::unique_ptr<QBase> qrule = QBase::build(QGAUSS, dim, d_quad_order);\n    fe->attach_quadrature_rule(qrule.get());\n    unsigned int k = 0;\n    for (std::map<dof_id_type, ElemPatch>::const_iterator it = d_local_elem_patches.begin();\n         it != d_local_elem_patches.end();\n         ++it, ++k)\n    {\n        const dof_id_type node_id = it->first;\n        const Node& node = d_mesh->node(node_id);\n        const ElemPatch& elem_patch = it->second;\n        Eigen::ColPivHouseholderQR<Eigen::MatrixXd>& patch_proj_solver = d_local_patch_proj_solver[k];\n\n        // Solve for the coefficients of the reconstruction.\n        f.setZero();\n        for (ElemPatch::const_iterator el_it = elem_patch.begin(); el_it != elem_patch.end(); ++el_it)\n        {\n            const Elem* const elem = el_it->get<0>();\n            const CompositePeriodicMapping& inverse_mapping = el_it->get<2>();\n            const dof_id_type elem_id = elem->id();\n            const int global_offset = d_elem_qp_global_offset[elem_id];\n            fe->reinit(elem);\n            for (unsigned int qp = 0; qp < qrule->n_points(); ++qp)\n            {\n                evaluate_polynomial_basis_fcns(\n                    P, node, apply_composite_periodic_mapping(inverse_mapping, q_point[qp]), dim, d_interp_order);\n                f += P * pressure_vals[global_offset + qp];\n            }\n        }\n        a = patch_proj_solver.solve(f);\n\n        // Evaluate the reconstruction at the node.\n        const unsigned int var = 0;\n        const int dof_index = node.dof_number(p_sys_num, var, 0);\n        p_vec.set(dof_index, a(0));\n    }\n    return;\n} // reconstructPressure\n\n/////////////////////////////// PROTECTED ////////////////////////////////////\n\n/////////////////////////////// PRIVATE //////////////////////////////////////\n\n/////////////////////////////// NAMESPACE ////////////////////////////////////\n\n} // namespace IBAMR\n\n//////////////////////////////////////////////////////////////////////////////\n", "meta": {"hexsha": "b1a2b8e4207d4deb8e6c9e596194ba81a24216fa", "size": 26623, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/IB/IBFEPatchRecoveryPostProcessor.cpp", "max_stars_repo_name": "hongk45/IBAMR", "max_stars_repo_head_hexsha": "698d419fc6688470a8b9400822ba893da9d07ae2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/IB/IBFEPatchRecoveryPostProcessor.cpp", "max_issues_repo_name": "hongk45/IBAMR", "max_issues_repo_head_hexsha": "698d419fc6688470a8b9400822ba893da9d07ae2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-11-30T14:22:45.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-01T21:28:24.000Z", "max_forks_repo_path": "src/IB/IBFEPatchRecoveryPostProcessor.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": 43.0096930533, "max_line_length": 120, "alphanum_fraction": 0.5755174098, "num_tokens": 6080, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.6224593452091672, "lm_q1q2_score": 0.4662763361799532}}
{"text": "/*\n * \n * Copyright (c) Kresimir Fresl & Toon Knapen 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_SPSV_HPP\n#define BOOST_NUMERIC_BINDINGS_LAPACK_SPSV_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\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    // stored in packed format \n    //\n    /////////////////////////////////////////////////////////////////////\n\n    /*\n     * spsv() computes the solution to a system of linear equations \n     * A * X = B, where A is an N-by-N symmetric matrix stored in packed \n     * format and X and B 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      inline \n      void spsv (char const uplo, int const n, int const nrhs,\n                 float* ap, int* ipiv, \n                 float* b, int const ldb, int* info) \n      {\n        LAPACK_SSPSV (&uplo, &n, &nrhs, ap, ipiv, b, &ldb, info);\n      }\n\n      inline \n      void spsv (char const uplo, int const n, int const nrhs,\n                 double* ap, int* ipiv, \n                 double* b, int const ldb, int* info) \n      {\n        LAPACK_DSPSV (&uplo, &n, &nrhs, ap, ipiv, b, &ldb, info);\n      }\n\n      inline \n      void spsv (char const uplo, int const n, int const nrhs,\n                 traits::complex_f* ap, int* ipiv,  \n                 traits::complex_f* b, int const ldb, int* info) \n      {\n        LAPACK_CSPSV (&uplo, &n, &nrhs, \n                      traits::complex_ptr (ap), ipiv, \n                      traits::complex_ptr (b), &ldb, info);\n      }\n\n      inline \n      void spsv (char const uplo, int const n, int const nrhs,\n                 traits::complex_d* ap, int* ipiv, \n                 traits::complex_d* b, int const ldb, int* info) \n      {\n        LAPACK_ZSPSV (&uplo, &n, &nrhs, \n                      traits::complex_ptr (ap), ipiv, \n                      traits::complex_ptr (b), &ldb, info);\n      }\n\n      template <typename SymmA, typename MatrB, typename IVec>\n      inline\n      int spsv (SymmA& a, IVec& 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_packed_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        int const n = traits::matrix_size1 (a);\n        assert (n == traits::matrix_size2 (a)); \n        assert (n == traits::matrix_size1 (b)); \n\n        char uplo = traits::matrix_uplo_tag (a);\n        int info; \n        spsv (uplo, n, traits::matrix_size2 (b), \n              traits::matrix_storage (a), \n              traits::vector_storage (i),  \n              traits::matrix_storage (b),\n              traits::leading_dimension (b),\n              &info);\n        return info; \n      }\n\n    }\n\n    template <typename SymmA, typename MatrB, typename IVec>\n    inline\n    int spsv (SymmA& a, IVec& i, MatrB& b) {\n      assert (traits::matrix_size1 (a) == traits::vector_size (i)); \n      return detail::spsv (a, i, b); \n    }\n\n    template <typename SymmA, typename MatrB>\n    inline\n    int spsv (SymmA& a, MatrB& b) {\n      // with 'internal' pivot vector\n\n      int info = -101; \n      traits::detail::array<int> i (traits::matrix_size1 (a)); \n\n      if (i.valid()) \n        info = detail::spsv (a, i, b); \n      return info; \n    }\n\n\n    /*\n     * sptrf() computes the factorization of a symmetric matrix A \n     * in packed storage using the  Bunch-Kaufman diagonal pivoting \n     * method. The form of the 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 sptrf (char const uplo, int const n, \n                  float* ap, int* ipiv, int* info) \n      {\n        LAPACK_SSPTRF (&uplo, &n, ap, ipiv, info);\n      }\n\n      inline \n      void sptrf (char const uplo, int const n, \n                  double* ap, int* ipiv, int* info) \n      {\n        LAPACK_DSPTRF (&uplo, &n, ap, ipiv, info);\n      }\n\n      inline \n      void sptrf (char const uplo, int const n, \n                  traits::complex_f* ap, int* ipiv, int* info) \n      {\n        LAPACK_CSPTRF (&uplo, &n, traits::complex_ptr (ap), ipiv, info);\n      }\n\n      inline \n      void sptrf (char const uplo, int const n, \n                  traits::complex_d* ap, int* ipiv, int* info) \n      {\n        LAPACK_ZSPTRF (&uplo, &n, traits::complex_ptr (ap), ipiv, info);\n      }\n\n    }\n\n    template <typename SymmA, typename IVec>\n    inline\n    int sptrf (SymmA& a, IVec& i) {\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_packed_t\n      >::value));\n#endif\n\n      int const n = traits::matrix_size1 (a);\n      assert (n == traits::matrix_size2 (a)); \n      assert (n == traits::vector_size (i)); \n\n      char uplo = traits::matrix_uplo_tag (a);\n      int info; \n      detail::sptrf (uplo, n, traits::matrix_storage (a), \n                     traits::vector_storage (i), &info);\n      return info; \n    }\n\n\n    /*\n     * sptrs() solves a system of linear equations A*X = B with \n     * a symmetric matrix A in packed storage using the factorization \n     *    A = U * D * U^T   or  A = L * D * L^T\n     * computed by sptrf().\n     */\n\n    namespace detail {\n\n      inline \n      void sptrs (char const uplo, int const n, int const nrhs,\n                  float const* a, int const* ipiv, \n                  float* b, int const ldb, int* info) \n      {\n        LAPACK_SSPTRS (&uplo, &n, &nrhs, a, ipiv, b, &ldb, info);\n      }\n\n      inline \n      void sptrs (char const uplo, int const n, int const nrhs,\n                  double const* a, int const* ipiv, \n                  double* b, int const ldb, int* info) \n      {\n        LAPACK_DSPTRS (&uplo, &n, &nrhs, a, ipiv, b, &ldb, info);\n      }\n\n      inline \n      void sptrs (char const uplo, int const n, int const nrhs,\n                  traits::complex_f const* a, int const* ipiv,  \n                  traits::complex_f* b, int const ldb, int* info) \n      {\n        LAPACK_CSPTRS (&uplo, &n, &nrhs, \n                      traits::complex_ptr (a), ipiv, \n                      traits::complex_ptr (b), &ldb, info);\n      }\n\n      inline \n      void sptrs (char const uplo, int const n, int const nrhs,\n                  traits::complex_d const* a, int const* ipiv, \n                  traits::complex_d* b, int const ldb, int* info) \n      {\n        LAPACK_ZSPTRS (&uplo, &n, &nrhs, \n                       traits::complex_ptr (a), ipiv, \n                       traits::complex_ptr (b), &ldb, info);\n      }\n\n    }\n\n    template <typename SymmA, typename MatrB, typename IVec>\n    inline\n    int sptrs (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_packed_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      int 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      char uplo = traits::matrix_uplo_tag (a);\n      int info; \n      detail::sptrs (uplo, n, traits::matrix_size2 (b), \n#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n                     traits::matrix_storage (a), \n                     traits::vector_storage (i),  \n#else\n                     traits::matrix_storage_const (a), \n                     traits::vector_storage_const (i),  \n#endif \n                     traits::matrix_storage (b),\n                     traits::leading_dimension (b), \n                     &info);\n      return info; \n    }\n\n\n    namespace detail {\n      inline \n      void sptri (char const uplo, int const n, \n          float* ap, int* ipiv, float* work, int* info) \n      {\n        LAPACK_SSPTRI (&uplo, &n, ap, ipiv, work, info);\n      }\n\n      inline \n      void sptri (char const uplo, int const n, \n          double* ap, int* ipiv, double* work, int* info) \n      {\n        LAPACK_DSPTRI (&uplo, &n, ap, ipiv, work, info);\n      }\n\n      inline \n      void sptri (char const uplo, int const n, \n          traits::complex_f* ap, int* ipiv, traits::complex_f* work, int* info) \n      {\n        LAPACK_CSPTRI (&uplo, &n, traits::complex_ptr (ap), \n            ipiv, traits::complex_ptr (work), info);\n      }\n\n      inline \n      void sptri (char const uplo, int const n, \n          traits::complex_d* ap, int* ipiv, traits::complex_d* work, int* info) \n      {\n        LAPACK_ZSPTRI (&uplo, &n, traits::complex_ptr (ap), \n            ipiv, traits::complex_ptr (work), info);\n      }\n    } // namespace detail\n\n    template <typename SymmA, typename IVec>\n    inline\n    int sptri (SymmA& a, IVec& ipiv) \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_packed_t\n      >::value));\n#endif\n\n      int const n = traits::matrix_size1 (a);\n      assert (n == traits::matrix_size2 (a)); \n      assert (n == traits::vector_size (ipiv)); \n\n      char uplo = traits::matrix_uplo_tag (a);\n      int info; \n\n      typedef typename SymmA::value_type value_type;\n      traits::detail::array<value_type> work(traits::matrix_size1(a));\n\n      detail::sptri (uplo, n, traits::matrix_storage (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 lapack\n\n}}} // namespace boost::numeric::bindings\n\n\n\n\n#endif \n", "meta": {"hexsha": "c863bf6068cddc20ebf193dab3647d80307d0c74", "size": 11371, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/bindings/lapack/spsv.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/spsv.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/spsv.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": 30.9836512262, "max_line_length": 80, "alphanum_fraction": 0.5637147129, "num_tokens": 3092, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872243177518, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4662763326606814}}
{"text": "// Copyright Andr\u00e1s Vukics 2006\u20132020. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.txt)\n#include \"LazyDensityOperatorFFT.h\"\n\n#include \"FFT.tcc\"\n#include \"VectorFromMatrixSliceIterator.h\"\n\n#include <boost/range/algorithm/for_each.hpp>\n\n\nusing namespace fft; using namespace linalg;\n\n\nnamespace {\n\n  \nvoid ffTransformCV(CVector& psi, Direction dir)\n{\n  struct Helper\n  {\n    static void _(CVector& psi, int i1, int i2, double norm)\n    {\n      dcomp temp(psi(i1));\n      psi(i1)=norm*psi(i2);\n      psi(i2)=norm*temp;\n    }\n  };\n\n  int size=psi.size();\n\n  if (size<2) return;\n\n  transform(psi,dir);\n\n  int halfnumber=psi.size()>>1;\n\n  // NEEDS_WORK express the following with blitz\n  for (int j=0; j<halfnumber; j++ ) Helper::_(psi,j,j+halfnumber,pow(size,-.5));\n  for (int j=1; j<size      ; j+=2) psi(j)*=-1;\n\n}\n\n\n}\n\n\nvoid quantumdata::ffTransform(CVector& psi, fft::Direction dir)\n{\n  ffTransformCV(psi,dir);\n}\n\n\n\nvoid quantumdata::ffTransform(CMatrix& rho, fft::Direction dir)\n{\n  using namespace blitzplusplus::vfmsi;\n\n  for(auto& v : fullRange<Left >(rho)) ffTransformCV(v,dir);\n  for(auto& v : fullRange<Right>(rho)) ffTransformCV(v,reverse(dir));\n\n}\n\n\n", "meta": {"hexsha": "e614e81fc3a812efec82ba8df5b565a09070cd9d", "size": 1203, "ext": "cc", "lang": "C++", "max_stars_repo_path": "CPPQEDcore/quantumdata/LazyDensityOperatorFFT.cc", "max_stars_repo_name": "bartoszek/cppqed", "max_stars_repo_head_hexsha": "712b601e377642885f40cbf8a65eb1525360f654", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-02-21T14:00:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-29T15:12:11.000Z", "max_issues_repo_path": "CPPQEDcore/quantumdata/LazyDensityOperatorFFT.cc", "max_issues_repo_name": "bartoszek/cppqed", "max_issues_repo_head_hexsha": "712b601e377642885f40cbf8a65eb1525360f654", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2020-04-14T11:18:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-04T20:11:23.000Z", "max_forks_repo_path": "CPPQEDcore/quantumdata/LazyDensityOperatorFFT.cc", "max_forks_repo_name": "bartoszek/cppqed", "max_forks_repo_head_hexsha": "712b601e377642885f40cbf8a65eb1525360f654", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-25T10:16:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-28T18:29:01.000Z", "avg_line_length": 19.0952380952, "max_line_length": 132, "alphanum_fraction": 0.6783042394, "num_tokens": 352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872243177519, "lm_q2_score": 0.6224593241981982, "lm_q1q2_score": 0.4662763274143319}}
{"text": "#include \"TerrainOps.h\"\n\n#include <armadillo/armadillo>\n\nnamespace world {\n\nvoid TerrainOps::fill(Terrain &terrain, double value) {\n    terrain._array.fill(value);\n}\n\nvoid TerrainOps::applyOffset(Terrain &terrain, const arma::mat &offset) {\n    if (offset.n_rows != terrain._array.n_rows ||\n        offset.n_cols != terrain._array.n_cols) {\n        throw std::runtime_error(\n            \"TerrainManipulator::applyOffset : bad matrix dimensions\");\n    }\n\n    terrain._array += offset;\n}\n\nvoid TerrainOps::applyOffset(world::Terrain &terrain, double offset) {\n    terrain._array += offset;\n}\n\nvoid TerrainOps::multiply(Terrain &terrain, const arma::mat &factor) {\n    if (factor.n_rows != terrain._array.n_rows ||\n        factor.n_cols != terrain._array.n_cols) {\n        throw std::runtime_error(\n            \"TerrainManipulator::multiply : bad matrix dimensions\");\n    }\n\n    terrain._array %= factor;\n}\n\nvoid TerrainOps::multiply(Terrain &terrain, double factor) {\n    terrain._array *= factor;\n}\n\nvoid TerrainOps::copyNeighbours(Terrain &terrain, const TileCoordinates &coords,\n                                const TerrainGrid &storage) {\n    // TODO unit test this method\n    int m = terrain.getResolution() - 1;\n\n    // corners\n    TerrainElement *neighbour;\n    if (storage.tryGet(coords + vec2i{-1, -1}, &neighbour)) {\n        terrain(0, 0) = neighbour->_terrain(m, m);\n    }\n\n    if (storage.tryGet(coords + vec2i{-1, 1}, &neighbour)) {\n        terrain(0, m) = neighbour->_terrain(m, 0);\n    }\n\n    if (storage.tryGet(coords + vec2i{1, -1}, &neighbour)) {\n        terrain(m, 0) = neighbour->_terrain(0, m);\n    }\n\n    if (storage.tryGet(coords + vec2i{1, 1}, &neighbour)) {\n        terrain(m, m) = neighbour->_terrain(0, 0);\n    }\n\n    // sides\n    if (storage.tryGet(coords + vec2i{-1, 0}, &neighbour)) {\n        for (int i = 0; i <= m; ++i) {\n            terrain(0, i) = neighbour->_terrain(m, i);\n        }\n    }\n\n    if (storage.tryGet(coords + vec2i{1, 0}, &neighbour)) {\n        for (int i = 0; i <= m; ++i) {\n            terrain(m, i) = neighbour->_terrain(0, i);\n        }\n    }\n\n    if (storage.tryGet(coords + vec2i{0, -1}, &neighbour)) {\n        for (int i = 0; i <= m; ++i) {\n            terrain(i, 0) = neighbour->_terrain(i, m);\n        }\n    }\n\n    if (storage.tryGet(coords + vec2i{0, 1}, &neighbour)) {\n        for (int i = 0; i <= m; ++i) {\n            terrain(i, m) = neighbour->_terrain(i, 0);\n        }\n    }\n}\n} // namespace world\n", "meta": {"hexsha": "14dae4667382a79f9774d0ba5bbc392c1eddce9e", "size": 2461, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "projects/world/terrain/TerrainOps.cpp", "max_stars_repo_name": "stefannesic/world", "max_stars_repo_head_hexsha": "44c01623ab1777c3224f83f53b74d50b58372fb1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "projects/world/terrain/TerrainOps.cpp", "max_issues_repo_name": "stefannesic/world", "max_issues_repo_head_hexsha": "44c01623ab1777c3224f83f53b74d50b58372fb1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "projects/world/terrain/TerrainOps.cpp", "max_forks_repo_name": "stefannesic/world", "max_forks_repo_head_hexsha": "44c01623ab1777c3224f83f53b74d50b58372fb1", "max_forks_repo_licenses": ["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.9659090909, "max_line_length": 80, "alphanum_fraction": 0.5798455912, "num_tokens": 696, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.46627632568725436}}
{"text": "#ifndef BOOST_METAPARSE_GETTING_STARTED_8_1_HPP\n#define BOOST_METAPARSE_GETTING_STARTED_8_1_HPP\n\n// Automatically generated header file\n\n// Definitions before section 8\n#include \"8.hpp\"\n\n// Definitions of section 8\n#include <boost/mpl/divides.hpp>\n\ntemplate <class L, class R> struct eval_binary_op<L, '/', R> : boost::mpl::divides<L, R>::type {};\n\nusing divides_token = token<lit_c<'/'>>;\n\nusing mult_exp2 =\n foldl_start_with_parser<\n   sequence<one_of<times_token, divides_token>, int_token>,\n   int_token,\n   boost::mpl::quote2<binary_op>\n >;\n\nusing exp_parser16 =\n build_parser<\n   foldl_start_with_parser<\n     sequence<one_of<plus_token, minus_token>, mult_exp2>,\n     mult_exp2,\n     boost::mpl::quote2<binary_op>\n   >\n >;\n\n// query:\n//    exp_parser16::apply<BOOST_METAPARSE_STRING(\"8 / 4\")>::type\n\n#endif\n", "meta": {"hexsha": "d00463b30af0096c359e5ef0b6764c4e8fee275f", "size": 814, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/libs/metaparse/example/getting_started/8_1.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/libs/metaparse/example/getting_started/8_1.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/libs/metaparse/example/getting_started/8_1.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": 22.6111111111, "max_line_length": 98, "alphanum_fraction": 0.7297297297, "num_tokens": 225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.749087201911703, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.46627631871382724}}
{"text": "#pragma once\n\n#include <list>\n\n#include <Eigen/Core>\n\n#include \"rcvio/macros.h\"\n#include \"rcvio/input_buffer.hpp\"\n\nnamespace rcvio\n{\n    class PreIntegrator\n    {\n    public:\n        POINTER_TYPEDEFS(PreIntegrator);\n        EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n        PreIntegrator(const cv::FileStorage &fs_settings);\n\n        void propagate(Eigen::VectorXd &xkk,\n                       Eigen::MatrixXd &Pkk,\n                       std::list<ImuData *> &imu_data);\n\n    public:\n        Eigen::VectorXd xk1k;\n        Eigen::MatrixXd Pk1k;\n\n    private:\n        double gravity_;\n        double small_angle_;\n\n        double gyro_noise_sigma_;\n        double gyro_rand_walk_sigma_;\n        double accel_noise_sigma_;\n        double accel_rand_walk_sigma_;\n\n        Eigen::Matrix<double, 12, 12> imu_noise_matrix_;\n    };\n}", "meta": {"hexsha": "3e4bc1e154550dc42b43440bb1970093425f4d5e", "size": 817, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/rcvio/pre_integrator.hpp", "max_stars_repo_name": "sufalroy/RC-VIO", "max_stars_repo_head_hexsha": "139a423190e87018e060dfc630cd6790aa2357fc", "max_stars_repo_licenses": ["MIT"], "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/rcvio/pre_integrator.hpp", "max_issues_repo_name": "sufalroy/RC-VIO", "max_issues_repo_head_hexsha": "139a423190e87018e060dfc630cd6790aa2357fc", "max_issues_repo_licenses": ["MIT"], "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/rcvio/pre_integrator.hpp", "max_forks_repo_name": "sufalroy/RC-VIO", "max_forks_repo_head_hexsha": "139a423190e87018e060dfc630cd6790aa2357fc", "max_forks_repo_licenses": ["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.9487179487, "max_line_length": 58, "alphanum_fraction": 0.6230110159, "num_tokens": 187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.749087201911703, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.46627631871382724}}
{"text": "#include <boost/python.hpp>\n#include <scitbx/array_family/tiny_types.h>\n#include <scitbx/array_family/small.h>\n#include <scitbx/array_family/versa.h>\n#include <scitbx/array_family/shared.h>\n#include <scitbx/array_family/ref.h>\n#include <scitbx/array_family/accessors/c_grid.h>\n#include <scitbx/array_family/shared.h>\n#include <scitbx/array_family/flex_types.h>\n#include <scitbx/array_family/boost_python/flex_wrapper.h>\n#include <scitbx/array_family/accessors/c_grid.h>\n#include <scitbx/vec3.h>\n#include <scitbx/mat3.h>\n#include <cctype>\n#include <complex>\n#include <cmath>\n\nnamespace fractbx {\n  namespace ext {\n\n    // discover mandelbrot set\n\n    static size_t iterations(std::complex<double> c)\n    {\n      std::complex<double> z = 0;\n      size_t jmax = 2048;\n      for (size_t j = 0; j < jmax; j++) {\n        z = z * z + c;\n        if (std::abs(z) > 2) {\n          return j;\n        }\n      }\n      return jmax;\n    }\n\n    static scitbx::af::versa< int, scitbx::af::c_grid<2> > make_flex(size_t n)\n    {\n      scitbx::af::c_grid<2> grid(n, n);\n      scitbx::af::versa< int, scitbx::af::c_grid<2> > result(grid, 0);\n      double scale = 4.0 / (n - 1);\n      int off = (n - 1) / 2;\n      for(int j = 0; j < n; j++) {\n        for(int i = 0; i < n; i++) {\n          std::complex<double> c(scale * (i - off), scale * (j - off));\n          result(j, i) = iterations(c);\n        }\n      }\n      return result;\n    }\n\n    void init_module()\n    {\n      using namespace boost::python;\n      def(\"make_flex\", make_flex, (arg(\"size\")));\n    }\n\n  }\n} // namespace fractbx::ext\n\nBOOST_PYTHON_MODULE(fractbx_ext)\n{\n  fractbx::ext::init_module();\n}\n", "meta": {"hexsha": "3c8eb08c9d3aa699b0277100cb5257c761a71f1e", "size": 1640, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ext.cpp", "max_stars_repo_name": "graeme-winter/fractbx", "max_stars_repo_head_hexsha": "c372bf1f3f861087707d8fbdf16666be57e8bc6b", "max_stars_repo_licenses": ["BSD-3-Clause"], "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.cpp", "max_issues_repo_name": "graeme-winter/fractbx", "max_issues_repo_head_hexsha": "c372bf1f3f861087707d8fbdf16666be57e8bc6b", "max_issues_repo_licenses": ["BSD-3-Clause"], "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.cpp", "max_forks_repo_name": "graeme-winter/fractbx", "max_forks_repo_head_hexsha": "c372bf1f3f861087707d8fbdf16666be57e8bc6b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.625, "max_line_length": 78, "alphanum_fraction": 0.6030487805, "num_tokens": 504, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743735019595, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.46614303576945354}}
{"text": "/*******************************************************************************\n *         Copyright 2003 & onward LASMEA UMR 6602 CNRS/Univ. Clermont II\n *         Copyright 2009 & onward LRI    UMR 8623 CNRS/Univ Paris Sud XI\n *\n *          Distributed under the Boost Software License, Version 1.0.\n *                 See accompanying file LICENSE.txt or copy at\n *                     http://www.boost.org/LICENSE_1_0.txt\n ******************************************************************************/\n#ifndef NT2_SDK_CONSTANT_DSL_REAL_HPP_INCLUDED\n#define NT2_SDK_CONSTANT_DSL_REAL_HPP_INCLUDED\n\n////////////////////////////////////////////////////////////////////////////////\n// Turn some digits consatnt into DSL terminals\n////////////////////////////////////////////////////////////////////////////////\n#include <boost/proto/proto.hpp>\n#include <nt2/sdk/constant/real.hpp>\n#include <nt2/sdk/constant/category.hpp>\n\nnamespace nt2\n{\n  boost::proto::terminal< constant_<tag::pi_ > >::type          pi_         = {{}};\n  boost::proto::terminal< constant_<tag::nan_> >::type          nan_        = {{}};\n  boost::proto::terminal< constant_<tag::sqrt_2_o_2_> >::type   sqrt_2_o_2_ = {{}};\n  boost::proto::terminal< constant_<tag::sqrt_2_> >::type       sqrt_2_     = {{}};\n  boost::proto::terminal< constant_<tag::gold_> >::type         gold_       = {{}};\n  boost::proto::terminal< constant_<tag::c_gold_> >::type       cgold_      = {{}};\n  boost::proto::terminal< constant_<tag::m_half_> >::type       mhalf_      = {{}};\n  boost::proto::terminal< constant_<tag::m_zero_> >::type       mzero_      = {{}};\n  boost::proto::terminal< constant_<tag::half_> >::type         half_       = {{}};\n  boost::proto::terminal< constant_<tag::third_> >::type        third_      = {{}};\n  boost::proto::terminal< constant_<tag::quarter_> >::type      quarter_    = {{}};\n}\n\n#endif\n", "meta": {"hexsha": "b57e1119e824b3d9293cf0bcc24d9aea1790f799", "size": 1875, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/sdk/include/nt2/sdk/constant/dsl/real.hpp", "max_stars_repo_name": "brycelelbach/nt2", "max_stars_repo_head_hexsha": "73d7e8dd390fa4c8d251c6451acdae65def70e0b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-24T03:35:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T03:35:10.000Z", "max_issues_repo_path": "modules/sdk/include/nt2/sdk/constant/dsl/real.hpp", "max_issues_repo_name": "brycelelbach/nt2", "max_issues_repo_head_hexsha": "73d7e8dd390fa4c8d251c6451acdae65def70e0b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/sdk/include/nt2/sdk/constant/dsl/real.hpp", "max_forks_repo_name": "brycelelbach/nt2", "max_forks_repo_head_hexsha": "73d7e8dd390fa4c8d251c6451acdae65def70e0b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 53.5714285714, "max_line_length": 83, "alphanum_fraction": 0.5066666667, "num_tokens": 426, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743735019595, "lm_q2_score": 0.6297746143530797, "lm_q1q2_score": 0.4661430306262289}}
{"text": "/*\n@copyright Louis Dionne 2015\nDistributed under the Boost Software License, Version 1.0.\n(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n */\n\n#include <boost/hana/assert.hpp>\n\n#include \"matrix/comparable.hpp\"\nusing namespace boost::hana;\nusing namespace cppcon;\n\n\nint main() {\n    BOOST_HANA_CONSTEXPR_CHECK(equal(\n        matrix(row(1, 2)),\n        matrix(row(1, 2))\n    ));\n    BOOST_HANA_CONSTEXPR_CHECK(not_(equal(\n        matrix(row(1, 2)),\n        matrix(row(1, 5))\n    )));\n\n    BOOST_HANA_CONSTEXPR_CHECK(equal(\n        matrix(row(1, 2),\n               row(3, 4)),\n        matrix(row(1, 2),\n               row(3, 4))\n    ));\n    BOOST_HANA_CONSTEXPR_CHECK(not_(equal(\n        matrix(row(1, 2),\n               row(3, 4)),\n        matrix(row(1, 2),\n               row(0, 4))\n    )));\n    BOOST_HANA_CONSTEXPR_CHECK(not_(equal(\n        matrix(row(1, 2),\n               row(3, 4)),\n        matrix(row(0, 2),\n               row(3, 4))\n    )));\n\n    BOOST_HANA_CONSTANT_CHECK(not_(equal(\n        matrix(row(1),\n               row(2)),\n        matrix(row(3, 4),\n               row(5, 6))\n    )));\n    BOOST_HANA_CONSTANT_CHECK(not_(equal(\n        matrix(row(1),\n               row(2)),\n        matrix(row(3, 4))\n    )));\n}\n\n", "meta": {"hexsha": "6204220d95be454f0fe5e10a025398f3d57bb587", "size": 1258, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/cppcon_2014/comparable.cpp", "max_stars_repo_name": "josephwinston/hana", "max_stars_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/cppcon_2014/comparable.cpp", "max_issues_repo_name": "josephwinston/hana", "max_issues_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/cppcon_2014/comparable.cpp", "max_forks_repo_name": "josephwinston/hana", "max_forks_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.4642857143, "max_line_length": 78, "alphanum_fraction": 0.5286168521, "num_tokens": 352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743735019595, "lm_q2_score": 0.6297746143530797, "lm_q1q2_score": 0.4661430306262289}}
{"text": "/**\n * @file Vandermonde.h\n *\n */\n\n#include \"math/vandermonde/QuadSolver.h\"\n#include \"math/vandermonde/FFTSolver.h\"\n\n#include \"operation/field/setup.h\"\n//#include <boost/timer.hpp>\n#include <boost/test/unit_test.hpp>\n\n\nBOOST_AUTO_TEST_SUITE( Vandermonde );\n\n//******************************************************************************\nBOOST_AUTO_TEST_CASE_TEMPLATE( vand_quad_simple, F, math::FieldTypes ) {\n  math::FieldFixture<F> f; BOOST_CHECK( f ); // avoid unreferenced local variable warning\n\n  BOOST_TEST_MESSAGE( \"  Testing \" << F::getName() );\n\n  unsigned int size = 3;\n  boost::scoped_array<F> entries(new F[size+1]);\n  entries[0].template setTo<-1>();\n  entries[1].template setTo<0>();\n  entries[2].template setTo<1>();\n\n  BOOST_CHECK(entries[0].template is<-1>());\n\n  math::vandermonde::QuadSolver<F> qSolver(size, entries.get());\n\n  BOOST_CHECK_EQUAL(qSolver.getMatrixSize(),size);\n\n  BOOST_CHECK_EQUAL(qSolver.getEntry(0),F(-1));\n  BOOST_CHECK_EQUAL(qSolver.getEntry(1),F(0));\n  BOOST_CHECK_EQUAL(qSolver.getEntry(2),F(1));\n\n  boost::scoped_array<F> values(new F[size]);\n\n  values[0].template setTo<1>();\n  values[1].template setTo<0>();\n  values[2].template setTo<1>();\n\n  boost::scoped_array<F> result(new F[size]);\n\n  qSolver.solveTranspose(values.get(), result.get());\n\n  BOOST_CHECK_EQUAL(result[0],F(1)/F(2));\n  BOOST_CHECK_EQUAL(result[1],F(0));\n  BOOST_CHECK_EQUAL(result[2],F(1)/F(2));\n\n}\n\n//******************************************************************************\nBOOST_AUTO_TEST_CASE_TEMPLATE( vand_fft_simple, F, math::FieldTypes ) {\n  math::FieldFixture<F> f; BOOST_CHECK( f ); // avoid unreferenced local variable warning\n\n  BOOST_TEST_MESSAGE( \"  Testing \" << F::getName() );\n\n  unsigned int size = 3;\n  boost::scoped_array<F> entries(new F[size]);\n  entries[0].template setTo<-1>();\n  entries[1].template setTo<0>();\n  entries[2].template setTo<1>();\n\n  BOOST_CHECK(entries[0].template is<-1>());\n  BOOST_CHECK(entries[1].template is<0>());\n  BOOST_CHECK(entries[2].template is<1>());\n\n  math::vandermonde::FFTSolver<F> fftSolver(size, entries.get());\n\n  BOOST_CHECK_EQUAL(fftSolver.getMatrixSize(), size);\n\n  BOOST_CHECK_EQUAL(fftSolver.getEntry(0), F(-1));\n  BOOST_CHECK_EQUAL(fftSolver.getEntry(1), F(0));\n  BOOST_CHECK_EQUAL(fftSolver.getEntry(2), F(1));\n\n  boost::scoped_array<F> coeffs(new F[size]);\n  coeffs[0] = F(1)/F(2);\n  coeffs[1] = F(0);\n  coeffs[2] = F(1)/F(2);\n\n  boost::scoped_array<F> values(new F[size]);\n\n  values[0].template setTo<1>();\n  values[1].template setTo<0>();\n  values[2].template setTo<1>();\n\n  boost::scoped_array<F> result(new F[size]);\n\n  fftSolver.evaluate(coeffs.get(),result.get());\n\n  BOOST_CHECK_EQUAL(result[0], F(1));\n  BOOST_CHECK_EQUAL(result[1], F(1)/F(2));\n  BOOST_CHECK_EQUAL(result[2], F(1));\n\n\n  fftSolver.solveTranspose(values.get(), result.get());\n\n  BOOST_CHECK_EQUAL(result[0], F(1)/F(2));\n  BOOST_CHECK_EQUAL(result[1], F(0));\n  BOOST_CHECK_EQUAL(result[2], F(1)/F(2));\n\n}\n\n\nBOOST_AUTO_TEST_SUITE_END();\n\n\nbool init_unit_test() {\n  return true;\n}\n\n", "meta": {"hexsha": "92692bd82944967ffc7e256e43d630bea4bcbb5f", "size": 3041, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/math/Vandermonde.t.cpp", "max_stars_repo_name": "cherba29/slp-poly", "max_stars_repo_head_hexsha": "0812e433c19c3ae036610c50ce54bf2d8cb8bf93", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/math/Vandermonde.t.cpp", "max_issues_repo_name": "cherba29/slp-poly", "max_issues_repo_head_hexsha": "0812e433c19c3ae036610c50ce54bf2d8cb8bf93", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/math/Vandermonde.t.cpp", "max_forks_repo_name": "cherba29/slp-poly", "max_forks_repo_head_hexsha": "0812e433c19c3ae036610c50ce54bf2d8cb8bf93", "max_forks_repo_licenses": ["Apache-2.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.6754385965, "max_line_length": 89, "alphanum_fraction": 0.6517592897, "num_tokens": 843, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743735019595, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.4661430254830042}}
{"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 robust_gaussian_filter_test.cpp\n * \\date August 2015\n * \\author Jan Issac (jan.issac@gmail.com)\n */\n\n#include <gtest/gtest.h>\n\n#include <Eigen/Dense>\n\n#include \"../typecast.hpp\"\n#include \"gaussian_filter_test_suite.hpp\"\n#include <fl/util/meta.hpp>\n#include <fl/filter/gaussian/gaussian_filter.hpp>\n#include <fl/filter/gaussian/robust_gaussian_filter.hpp>\n#include <fl/model/sensor/linear_cauchy_sensor.hpp>\n#include <fl/model/sensor/body_tail_sensor.hpp>\n#include <fl/model/sensor/linear_gaussian_sensor.hpp>\n\nusing namespace fl;\n\ntemplate <\n    int StateDimension,\n    int InputDimension,\n    int ObsrvDimension,\n    int FilterIterations\n>\nstruct RobutGaussianFilterTestConfiguration\n{\n    enum : signed int\n    {\n        StateDim = StateDimension,\n        InputDim = InputDimension,\n        ObsrvDim = ObsrvDimension,\n        Iterations = FilterIterations\n    };\n\n    template <typename ModelFactory>\n    struct FilterDefinition\n    {\n        typedef typename ModelFactory::LinearObservation::Obsrv Obsrv;\n        typedef typename ModelFactory::LinearObservation::State State;\n\n        typedef fl::LinearCauchySensor<Obsrv, State> CauchyModel;\n\n        typedef fl::BodyTailSensor<\n                    typename ModelFactory::LinearObservation,\n                    CauchyModel\n                > BodyTailSensor;\n\n        typedef UnscentedQuadrature Quadrature;\n//        typedef fl::SigmaPointQuadrature<\n//                    fl::MonteCarloTransform<\n//                        fl::ConstantPointCountPolicy<1000>>> Quadrature;\n\n        typedef RobustGaussianFilter<\n                    typename ModelFactory::LinearTransition,\n                    BodyTailSensor,\n                    Quadrature\n                > Type;\n    };\n\n    template <typename ModelFactory>\n    static typename FilterDefinition<ModelFactory>::Type\n    create_filter(ModelFactory&& factory)\n    {\n        typedef FilterDefinition<ModelFactory> Definition;\n        typedef typename Definition::Type Filter;\n        typedef typename Definition::CauchyModel CauchyModel;\n        typedef typename Definition::BodyTailSensor BodyTailSensor;\n\n        auto body_model = factory.create_sensor();\n        auto tail_model = CauchyModel();\n        tail_model.noise_covariance(tail_model.noise_covariance() * 10.);\n\n        return Filter(\n            factory.create_linear_state_model(),\n            BodyTailSensor(body_model, tail_model, 0.1),\n            typename Definition::Quadrature());\n    }\n};\n\n\ntypedef ::testing::Types<\n            StaticTest<RobutGaussianFilterTestConfiguration<1, 1, 1, 30>>\n        > TestTypes;\n\nINSTANTIATE_TYPED_TEST_CASE_P(RobustGaussianFilterTest,\n                              GaussianFilterTest,\n                              TestTypes);\n", "meta": {"hexsha": "d5a6ea24848571ae9964922474f0c146f2c821bc", "size": 3165, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/gaussian_filter/robust_gaussian_filter_test.cpp", "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": "test/gaussian_filter/robust_gaussian_filter_test.cpp", "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": "test/gaussian_filter/robust_gaussian_filter_test.cpp", "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": 30.4326923077, "max_line_length": 79, "alphanum_fraction": 0.6669826224, "num_tokens": 677, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.6297746074044135, "lm_q1q2_score": 0.46614301826393373}}
{"text": "#pragma once\n\n#include <armadillo>\n\nclass Pipeline;\n\n/*!\n * \\brief Discretizer is an abstract class, the base class the implementation of\n * the discretization of the two different sets of governing equations; internal\n * energy and enthalpy.\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 finite difference scheme discretizes the governing properties flow,\n * pressure and temperature onto a grid. The derivatives and values for each\n * grid section \\f$I\\f$ are approximated by different combination of the flow,\n * pressure and temperatures at the grid points, \\f$y_i\\f$ and \\f$y_{i+1}\\f$,\n * as follows\n *\n * \\f[\n *     \\frac{\\partial y(I, t_{n+1})}{\\partial t} = \\frac{y_{i+1}^{n+1} + y_{i}^{n+1} - y_{i+1}^{n} - y_{i}^{n}}{2\\Delta t}\n * \\f]\n *\n * \\f[\n *     \\frac{\\partial y(I, t_{n+1})}{\\partial x} = \\frac{y_{i+1}^{n+1} - y_{i}^{n+1}}{\\Delta x}\n * \\f]\n *\n * \\f[\n *     y(I, t_{n+1}) = \\frac{y_{i+1}^{n+1} + y_{i}^{n+1}}{2}\n * \\f]\n *\n * This sets up a matrix equation \\f$Ax = b\\f$, where the matrix \\f$A\\f$\n * contains the coeffcients of each term \\f$y_i\\f$, the vector \\f$x\\f$ contain\n * the unknowns \\f$\\dot m_i\\f$ (flow), \\f$p_i\\f$ (pressure) and \\f$T_i\\f$\n * (temperature), and the vector \\f$b\\f$ contain the constant/known terms\n * (from boundary conditions and other knowns).\n *\n * \\see MatrixEquation\n */\nclass Discretizer\n{\npublic:\n    //! Have to declare virtual destructor to avoid compiler warnings.\n    //! Only declared here, to avoid the inline compiler-generated default destructor.\n    virtual ~Discretizer();\n\n    /*!\n     * \\brief Construct from number of grid points and number of equations and\n     * variables.\n     *\n     * Allocates the matrices Discretizer::m_term_i, Discretizer::m_term_ipp,\n     * and the vector Discretizer::m_boundaryTerm.\n     *\n     * \\param nGridPoints Number of grid points\n     * \\param nEquationsAndVariables Number of equations and variables\n     */\n    Discretizer(\n            const arma::uword nGridPoints,\n            const arma::uword nEquationsAndVariables);\n\n    /*!\n     * \\brief Pure virtual function, stencil for subclasses. This method\n     * calculates in the coefficients of \\f$y_i\\f$ and \\f$y_{i+1}\\f$ and stores\n     * them in Discretizer::m_term_i and Discretizer::m_term_ipp.\n     * \\param dt Time step\n     * \\param currentState Current pipeline state\n     * \\param newState New/guess pipeline state\n     */\n    virtual void discretize(\n            const arma::uword dt,\n            const Pipeline& currentState,\n            const Pipeline& newState) = 0;\n\n    const arma::cube& term_i() const { return m_term_i; } //!< Get coefficients of \\f$y_i\\f$\n    const arma::cube& term_ipp() const { return m_term_ipp; } //!< Get coefficients of \\f$y_{i+1}\\f$\n    const arma::mat& boundaryTerms() const { return m_boundaryTerm; } //!< Get constant terms\n\nprotected:\n    // TODO: better description of how m_term_i and m_term_ipp are organized\n    /*!\n     * \\brief The coefficients of \\f$y_i\\f$ in the discretized governing equations.\n     *\n     * This is an `arma::cube`, which is organized as follows.\n     * `m_term_i(grid point, equation number, variable number)`,\n     * where grid points are the usual grid points, equations are the\n     * continuity (0), momentum (1) and energy equations (2), and the variables\n     * are in order flow (0), pressure (1) and temperature(1).\n     * So for example if you want the coefficient at grid point number 5, in the\n     * energy equation, for flow, you want\n     * `m_term_i(4, 2, 0)` (zero-indexed).\n     */\n    arma::cube m_term_i;\n\n    /*!\n     * \\brief The coefficients of \\f$y_i\\f$ in the discretized governing equations.\n     *\n     * See Discretizer::m_term_i for a description of the organization of this.\n     */\n    arma::cube m_term_ipp;\n\n    /*!\n     * \\brief The constant/known terms in the discretized governing equations.\n     *\n     * This is a matrix, organized as\n     * `m_boundaryTerm(grid point, equation number)`.\n     */\n    arma::mat m_boundaryTerm;\n\n    double m_gravity = 9.81; //!< Gravity\n};\n", "meta": {"hexsha": "2ebb53565582ae0b3009261d1094f9a3aa602b5f", "size": 4305, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/solver/discretizer/discretizer.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/discretizer/discretizer.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/discretizer/discretizer.hpp", "max_forks_repo_name": "kewin1983/transient-pipeline-flow", "max_forks_repo_head_hexsha": "4ffe0b61d3d40d9bcb82a3743b2c2e403521835d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.0973451327, "max_line_length": 195, "alphanum_fraction": 0.6587688734, "num_tokens": 1202, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.4661430182639336}}
{"text": "//  Copyright John Maddock 2006, 2007\r\n//  Copyright Paul A. Bristow 2007\r\n\r\n//  Use, modification and distribution are subject to the\r\n//  Boost Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#include <pch.hpp>\r\n\r\n#ifdef _MSC_VER\r\n#  pragma warning(disable : 4127) // conditional expression is constant\r\n#  pragma warning(disable : 4512) // assignment operator could not be generated\r\n#  pragma warning(disable : 4756) // overflow in constant arithmetic\r\n// Constants are too big for float case, but this doesn't matter for test.\r\n#endif\r\n\r\n#include <boost/math/concepts/real_concept.hpp>\r\n#include <boost/test/test_exec_monitor.hpp>\r\n#include <boost/test/floating_point_comparison.hpp>\r\n#include <boost/math/special_functions/hermite.hpp>\r\n#include <boost/math/constants/constants.hpp>\r\n#include <boost/array.hpp>\r\n#include \"functor.hpp\"\r\n\r\n#include \"handle_test_result.hpp\"\r\n#include \"test_legendre_hooks.hpp\"\r\n\r\n//\r\n// DESCRIPTION:\r\n// ~~~~~~~~~~~~\r\n//\r\n// This file tests the Hermite polynomials.  \r\n// There are two sets of tests, spot\r\n// tests which compare our results with selected values computed\r\n// using the online special function calculator at \r\n// functions.wolfram.com, while the bulk of the accuracy tests\r\n// use values generated with NTL::RR at 1000-bit precision\r\n// and our generic versions of these functions.\r\n//\r\n// Note that when this file is first run on a new platform many of\r\n// these tests will fail: the default accuracy is 1 epsilon which\r\n// is too tight for most platforms.  In this situation you will \r\n// need to cast a human eye over the error rates reported and make\r\n// a judgement as to whether they are acceptable.  Either way please\r\n// report the results to the Boost mailing list.  Acceptable rates of\r\n// error are marked up below as a series of regular expressions that\r\n// identify the compiler/stdlib/platform/data-type/test-data/test-function\r\n// along with the maximum expected peek and RMS mean errors for that\r\n// test.\r\n//\r\n\r\nvoid expected_results()\r\n{\r\n   //\r\n   // Define the max and mean errors expected for\r\n   // various compilers and platforms.\r\n   //\r\n   const char* largest_type;\r\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\r\n   if(boost::math::policies::digits<double, boost::math::policies::policy<> >() == boost::math::policies::digits<long double, boost::math::policies::policy<> >())\r\n   {\r\n      largest_type = \"(long\\\\s+)?double\";\r\n   }\r\n   else\r\n   {\r\n      largest_type = \"long double\";\r\n   }\r\n#else\r\n   largest_type = \"(long\\\\s+)?double\";\r\n#endif\r\n\r\n   //\r\n   // Catch all cases come last:\r\n   //\r\n   add_expected_result(\r\n      \".*\",                          // compiler\r\n      \".*\",                          // stdlib\r\n      \".*\",                          // platform\r\n      largest_type,                  // test type(s)\r\n      \".*\",      // test data group\r\n      \"boost::math::hermite\", 10, 5);  // test function\r\n   add_expected_result(\r\n      \".*\",                          // compiler\r\n      \".*\",                          // stdlib\r\n      \".*\",                          // platform\r\n      \"real_concept\",                  // test type(s)\r\n      \".*\",      // test data group\r\n      \"boost::math::hermite\", 10, 5);  // test function\r\n   //\r\n   // Finish off by printing out the compiler/stdlib/platform names,\r\n   // we do this to make it easier to mark up expected error rates.\r\n   //\r\n   std::cout << \"Tests run with \" << BOOST_COMPILER << \", \" \r\n      << BOOST_STDLIB << \", \" << BOOST_PLATFORM << std::endl;\r\n}\r\n\r\ntemplate <class T>\r\nvoid do_test_hermite(const T& data, const char* type_name, const char* test_name)\r\n{\r\n   typedef typename T::value_type row_type;\r\n   typedef typename row_type::value_type value_type;\r\n\r\n   typedef value_type (*pg)(unsigned, value_type);\r\n#if defined(BOOST_MATH_NO_DEDUCED_FUNCTION_POINTERS)\r\n   pg funcp = boost::math::hermite<value_type>;\r\n#else\r\n   pg funcp = boost::math::hermite;\r\n#endif\r\n\r\n   typedef unsigned (*cast_t)(value_type);\r\n\r\n   boost::math::tools::test_result<value_type> result;\r\n\r\n   std::cout << \"Testing \" << test_name << \" with type \" << type_name\r\n      << \"\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\";\r\n\r\n   //\r\n   // test hermite against data:\r\n   //\r\n   result = boost::math::tools::test(\r\n      data, \r\n      bind_func_int1(funcp, 0, 1), \r\n      extract_result(2));\r\n   handle_test_result(result, data[result.worst()], result.worst(), type_name, \"boost::math::hermite\", test_name);\r\n\r\n   std::cout << std::endl;\r\n}\r\n\r\ntemplate <class T>\r\nvoid test_hermite(T, const char* name)\r\n{\r\n   //\r\n   // The actual test data is rather verbose, so it's in a separate file\r\n   //\r\n   // The contents are as follows, each row of data contains\r\n   // three items, input value a, input value b and erf(a, b):\r\n   // \r\n#  include \"hermite.ipp\"\r\n\r\n   do_test_hermite(hermite, name, \"Hermite Polynomials\");\r\n}\r\n\r\ntemplate <class T>\r\nvoid test_spots(T, const char* t)\r\n{\r\n   std::cout << \"Testing basic sanity checks for type \" << t << std::endl;\r\n   //\r\n   // basic sanity checks, tolerance is 100 epsilon:\r\n   // These spots were generated by MathCAD, precision is \r\n   // 14-16 digits.\r\n   //\r\n   T tolerance = (std::max)(boost::math::tools::epsilon<T>() * 100, static_cast<T>(1e-14));\r\n   BOOST_CHECK_CLOSE_FRACTION(::boost::math::hermite(0, static_cast<T>(1)), static_cast<T>(1.L), tolerance);\r\n   BOOST_CHECK_CLOSE_FRACTION(::boost::math::hermite(1, static_cast<T>(1)), static_cast<T>(2.L), tolerance);\r\n   BOOST_CHECK_CLOSE_FRACTION(::boost::math::hermite(1, static_cast<T>(2)), static_cast<T>(4.L), tolerance);\r\n   BOOST_CHECK_CLOSE_FRACTION(::boost::math::hermite(1, static_cast<T>(10)), static_cast<T>(20), tolerance);\r\n   BOOST_CHECK_CLOSE_FRACTION(::boost::math::hermite(1, static_cast<T>(100)), static_cast<T>(200), tolerance);\r\n   BOOST_CHECK_CLOSE_FRACTION(::boost::math::hermite(1, static_cast<T>(1e6)), static_cast<T>(2e6), tolerance);\r\n   if(std::numeric_limits<T>::max_exponent >= std::numeric_limits<double>::max_exponent)\r\n   {\r\n      BOOST_CHECK_CLOSE_FRACTION(::boost::math::hermite(1, static_cast<T>(1e307)), static_cast<T>(2e307), tolerance);\r\n      BOOST_CHECK_CLOSE_FRACTION(::boost::math::hermite(99, static_cast<T>(100)), static_cast<T>(4.967223743011310E+227L), tolerance);\r\n   }\r\n   BOOST_CHECK_CLOSE_FRACTION(::boost::math::hermite(10, static_cast<T>(30)), static_cast<T>(5.896624628001300E+17L), tolerance);\r\n   BOOST_CHECK_CLOSE_FRACTION(::boost::math::hermite(10, static_cast<T>(1000)), static_cast<T>(1.023976960161280E+33L), tolerance);\r\n   BOOST_CHECK_CLOSE_FRACTION(::boost::math::hermite(10, static_cast<T>(10)), static_cast<T>(8.093278209760000E+12L), tolerance);\r\n   BOOST_CHECK_CLOSE_FRACTION(::boost::math::hermite(10, static_cast<T>(-10)), static_cast<T>(8.093278209760000E+12L), tolerance);\r\n   BOOST_CHECK_CLOSE_FRACTION(::boost::math::hermite(3, static_cast<T>(-10)), static_cast<T>(-7.880000000000000E+3L), tolerance);\r\n   BOOST_CHECK_CLOSE_FRACTION(::boost::math::hermite(3, static_cast<T>(-1000)), static_cast<T>(-7.999988000000000E+9L), tolerance);\r\n   BOOST_CHECK_CLOSE_FRACTION(::boost::math::hermite(3, static_cast<T>(-1000000)), static_cast<T>(-7.999999999988000E+18L), tolerance);\r\n}\r\n\r\nint test_main(int, char* [])\r\n{\r\n   BOOST_MATH_CONTROL_FP;\r\n\r\n   boost::math::hermite(51, 915.0);\r\n\r\n#ifndef BOOST_MATH_BUGGY_LARGE_FLOAT_CONSTANTS\r\n   test_spots(0.0F, \"float\");\r\n#endif\r\n   test_spots(0.0, \"double\");\r\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\r\n   test_spots(0.0L, \"long double\");\r\n   test_spots(boost::math::concepts::real_concept(0.1), \"real_concept\");\r\n#endif\r\n\r\n   expected_results();\r\n\r\n#ifndef BOOST_MATH_BUGGY_LARGE_FLOAT_CONSTANTS\r\n   test_hermite(0.1F, \"float\");\r\n#endif\r\n   test_hermite(0.1, \"double\");\r\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\r\n   test_hermite(0.1L, \"long double\");\r\n#ifndef BOOST_MATH_NO_REAL_CONCEPT_TESTS\r\n   test_hermite(boost::math::concepts::real_concept(0.1), \"real_concept\");\r\n#endif\r\n#else\r\n   std::cout << \"<note>The long double tests have been disabled on this platform \"\r\n      \"either because the long double overloads of the usual math functions are \"\r\n      \"not available at all, or because they are too inaccurate for these tests \"\r\n      \"to pass.</note>\" << std::cout;\r\n#endif\r\n   return 0;\r\n}\r\n\r\n\r\n\r\n", "meta": {"hexsha": "440e7645b40b12470dfe8a764482be314bca62b2", "size": 8363, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/test/test_hermite.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/math/test/test_hermite.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/math/test/test_hermite.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": 39.8238095238, "max_line_length": 163, "alphanum_fraction": 0.661485113, "num_tokens": 2175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.4661430182639336}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n#include <fstream>\n#include <boost/dynamic_bitset.hpp>\n#include <boost/container/vector.hpp>\n#include <boost/unordered_map.hpp>\n#include <boost/random/uniform_01.hpp>\n#include <boost/random/niederreiter_base2.hpp>\n#include <./Timer.cpp>\n\ntypedef boost::dynamic_bitset<> Vetor;\ntypedef boost::container::vector<Vetor> Matriz;\n\n/*\n*\n* Ht: Matriz de verifica\u00e7\u00e3o de paridade original\n*\n* Ht_long: Refer\u00eancia de onde guardar o array em que cada elemento \u00e9 uma linha de Ht\n* \n* Erros_1: Refer\u00eancia de onde guardar o\n    array em que cada elemento \u00e9 um erro de peso=1 (mas s\u00f3 a por\u00e7\u00e3o de informa\u00e7\u00e3o desse erro)\n*   exemplo: se h\u00e1 5 bits na palavra-c\u00f3digo e os 2 primeiros s\u00e3o de informa\u00e7\u00e3o, ent\u00e3o um elemento \n*   de Erros_1 pode ser 3=0b11, significando erro em cada um dos 2 bits de informa\u00e7\u00e3o\n*\n* n_linhas, n_colunas, n_informacao: Quantas linhas e colunas tem Ht, e quantos bits s\u00e3o de informa\u00e7\u00e3o\n*   na palavra c\u00f3digo (assume-se que s\u00e3o correspondem \u00e0s primeiras linhas de Ht)\n*/\nvoid __gera_auxiliares(\n    const Matriz& Ht,\n    unsigned long* Ht_long,\n    unsigned long* Erros_1,\n    int n_linhas,\n    int n_colunas,\n    int n_informacao\n) {\n    /**\n    * S\u00f3 necess\u00e1rios os ulongs correspondentes a cada s\u00edndrome\n    */\n    for (int i = 0; i < n_linhas; ++i)\n    {\n        Ht_long[i] = Ht[i].to_ulong();\n    }\n\n    /** \n    * Por\u00e7\u00e3o de informa\u00e7\u00e3o dos erros associados a cada s\u00edndrome\n    * (por isso s\u00f3 importam os erros em bits de informa\u00e7\u00e3o)\n    */\n    for (int i = 0; i < n_linhas; ++i)\n    {\n        // Erros depois de n_informacao linhas correspondem somente a erros de bit\n        // de paridade, portanto aparecem como 0 j\u00e1 que s\u00f3 se coletam os erros de informa\u00e7\u00e3o\n        Erros_1[i] = i < n_informacao ? ((unsigned long)1) << (n_informacao - i - 1) : 0;\n    }\n}\n\n\n\n\n\n/**\n* input_csv: Espera-se formato de valores 0 ou 1 separados por v\u00edrgula e \\n, sem espa\u00e7os\n*\n* M: Matriz onde armazenar a leitura. \n*   Restri\u00e7\u00e3o: linha/coluna pode ter, no m\u00e1ximo (inclusive), 64 bits (cabe num unsigned long)\n*/\nvoid carrega_matriz(\n    std::ifstream& input_csv,\n    Matriz& M\n) {\n    std::string numero_string;\n\n    while (getline(input_csv, numero_string)) {\n    \n        int commaPos;\n        \n        while ((commaPos = numero_string.find(\",\")) != std::string::npos)\n            numero_string.erase(commaPos, 1);\n\n        Vetor numero (numero_string.length(), stoul(numero_string, 0, 2));\n\n        // std::cout << numero << \"\\n\";\n\n        M.push_back(numero);\n\n    }\n}\n\nint testa_carrega_matriz() {\n    std::string Htcsv = \"./dados/Ht.csv\";\n    std::ifstream input {Htcsv};\n\n    // if(!input)\n    //     std::error(\"could not open \" + Htcsv);\n\n    std::string numero_string;\n    Matriz Ht;\n\n    while (getline(input, numero_string)) {\n    \n        int commaPos;\n        \n        while ((commaPos = numero_string.find(\",\")) != std::string::npos)\n            numero_string.erase(commaPos, 1);\n\n        Vetor numero (numero_string.length(), stoul(numero_string, 0, 2));\n\n        std::cout << numero << \"\\n\";\n\n        Ht.push_back(numero);\n\n    }\n\n    std::cout << \"Finished loading. Now replicating:\" << std::endl;\n\n    std::for_each(Ht.begin(), Ht.end(), [](Vetor line) {\n        std::cout << line << std::endl;\n    });\n}\n\n/**\n* Auxiliar para `popular_dict`\n*\n*/\nvoid __popular_dict(\n    boost::unordered_map<unsigned long, unsigned long>& dict,\n    unsigned long* Ht_long,\n    unsigned long* Erros_1,\n    int n_linhas,\n    int n_colunas,\n    int n_informacao,\n    unsigned long sindrome_parcial,\n    unsigned long erro_parcial,\n    int linha_inicio,\n    int niveis_restantes\n) {\n    if (niveis_restantes == 1) {\n        unsigned long sindrome, erro;\n        for (int i = linha_inicio; i < n_linhas; ++i)\n        {\n            sindrome = sindrome_parcial ^ Ht_long[i];\n            erro = erro_parcial ^ Erros_1[i];\n            if (dict.find(sindrome) == dict.end())\n                dict[sindrome] = erro;\n        }\n        return;\n    }\n\n    for (int i = linha_inicio; i < n_linhas - (niveis_restantes - 1) /*iterar todas as s\u00edndromes*/; ++i)\n    {\n        __popular_dict(\n            dict,\n            Ht_long,\n            Erros_1,\n            n_linhas,\n            n_colunas,\n            n_informacao,\n            sindrome_parcial ^ Ht_long[i],\n            erro_parcial ^ Erros_1[i],\n            i+1,\n            niveis_restantes-1\n        );\n    }\n\n}\n\n/**\n* \n* dict: Onde guardar o mapa \"s\u00edndrome->erro\"\n*\n* Ht: Matriz de verifica\u00e7\u00e3o de paridade (transposta). Assume-se que suas \u00faltimas linhas\n* correspondem aos bits de informa\u00e7\u00e3o (identidade em cima, outras linhas embaixo)\n*\n* n_linhas, n_colunas, n_informacao: Quantas linhas e colunas tem Ht, e quantos bits s\u00e3o de informa\u00e7\u00e3o\n*   na palavra c\u00f3digo (assume-se que s\u00e3o correspondem \u00e0s primeiras linhas de Ht)\n*\n* peso_maximo: O peso dos maiores erros de informa\u00e7\u00e3o a serem catalogados em `dict`\n* \n*/\nvoid popular_dict(\n    boost::unordered_map<unsigned long, unsigned long>& dict,\n    const Matriz& Ht,\n    int n_linhas,\n    int n_colunas,\n    int n_informacao,\n    int peso_maximo\n) {\n\n    unsigned long *Ht_long = new unsigned long[n_linhas];\n    unsigned long *Erros_1 = new unsigned long[n_linhas];\n    __gera_auxiliares(\n        Ht,\n        Ht_long,\n        Erros_1,\n        n_linhas,\n        n_colunas,\n        n_informacao\n    );\n\n    for (int i = 1; i <= peso_maximo; ++i)\n    {\n        __popular_dict(\n        dict,\n        Ht_long,\n        Erros_1,\n        n_linhas,\n        n_colunas,\n        n_informacao,\n        0,\n        0,\n        0,\n        i\n    );\n    }\n\n}\n\nvoid testa_popular_dict() {\n    std::ifstream Htcsv(\"dados/Ht.csv\");\n    Matriz Ht;\n    boost::unordered_map<unsigned long, unsigned long> dict;\n\n    carrega_matriz(Htcsv, Ht);\n    int n_linhas = Ht.size();\n    int n_colunas =  Ht[0].size();\n    int n_informacao = n_linhas - n_colunas;\n    \n    popular_dict(\n        dict,\n        Ht,\n        n_linhas,\n        n_colunas,\n        n_informacao,\n        3\n    );\n\n    assert(dict.find(0) == dict.end());\n    assert(dict.at(1099511595008) == 34359738368); // 1\u00aa linha de Ht -> erro s\u00f3 no 1\u00ba bit de info\n    assert(dict.at(1064615018496) == 17179869184); // 2\u00aa linha de Ht -> erro s\u00f3 no 2\u00ba bit de info\n    assert(dict.at(34896576512) == 51539607552); // 1\u00aa+2\u00aa linhas de Ht -> erros nos 2 MSB de info\n    assert(dict.at(1052568944640) == 55834574848); // 1\u00aa+2\u00aa+4\u00aa linhas de Ht -> erros nos 1\u00ba,2\u00ba,4\u00ba bits de info\n    assert(dict.at(549755813888) == 0); // erro composto s\u00f3 pela 37\u00aa linha de Ht n\u00e3o aparece nos bits de info\n    assert(dict.at(481038172167) == 1); // mas se erro for de 36\u00aa+37\u00aa linhas de Ht -> erro no \u00faltimo bit de info \n                                         // (e ignora o bit de paridade)\n}\n\n\n/**\n* Retorna nova matriz em que cada linha \u00e9 uma coluna da matriz original.\n*/\nMatriz& transposta(\n    const Matriz& M\n) {\n    int antes_colunas = M[0].size();\n    int antes_linhas = M.size();\n    Matriz* resultado = new Matriz(antes_colunas);\n    \n    for (int i = 0; i < antes_colunas; ++i)\n    {\n        (*resultado)[i] = Vetor (antes_linhas);\n        // Se n\u00e3o for Vetor&, boost copia implicitamente\n        Vetor& linha = (*resultado)[i];\n        for (int j = 0; j < antes_linhas; ++j)\n        {\n            linha[antes_linhas - j - 1] = M[j][antes_colunas - i - 1];\n        };\n    }\n    return *resultado;\n}\n\nvoid testa_transposta() {\n    Matriz m = Matriz(3);\n    /* \n    * m == [1 1; 0 1; 0 0]\n    */\n    m[0] = Vetor(2, 3);\n    m[1] = Vetor(2, 1);\n    m[2] = Vetor(2, 0);\n\n    Matriz mt = transposta(m);\n\n    assert(mt[0] == Vetor(3, 4));\n    assert(mt[1] == Vetor(3, 6));\n}\n\n/**\n* Calcula M.v\n*/\nVetor& mult(const Matriz& M, const Vetor& v) {\n    int n_linhas = M.size(), n_colunas = v.size();\n    Vetor* resultado = new Vetor(n_linhas);\n\n    for (int i = 0; i < n_linhas; ++i)\n    {\n        (*resultado)[n_linhas - i - 1] =  (M[i] & v).count() & 1;\n    }\n\n    return *resultado;\n}\n\n/**\n* Calcula M.N\n*/\nMatriz& mult(const Matriz& M, const Matriz& N) {\n    int n_linhas = M.size();\n    int n_colunas = N[0].size();\n    Matriz pre_resultado = Matriz(n_colunas);\n\n    Matriz Nt = transposta(N);\n\n    for (int i = 0; i < n_colunas; ++i)\n    {\n        pre_resultado[i] = mult(M, Nt[i]);\n    }\n\n    Matriz& resultado = transposta(pre_resultado);\n\n    return resultado;\n}\n\nvoid testa_mult() {\n    // M == [1 0 1; 0 0 1]\n    Matriz M = Matriz(2);\n    M[0] = Vetor(3, 5);\n    M[1] = Vetor(3, 1);\n\n    // v == [0 1 1]\n    Vetor v = Vetor(3, 3);\n\n    // resultado deve ser [1 1]\n    assert(mult(M, v) == Vetor(2, 3));\n\n    // [1 1; 0 0; 1 1]\n    Matriz N = Matriz(3);\n    N[0] = Vetor(2, 3);\n    N[1] = Vetor(2, 0);\n    N[2] = Vetor(2, 3);\n\n    assert(mult(M, N).size() == 2);\n    assert(mult(M, N)[0] == Vetor(2, 0));\n    assert(mult(M, N)[1] == Vetor(2, 7));\n}\n\n/**\n* Modifica `Transmitido`, com chance `p` de inverter cada bit\n* de cada palavra c\u00f3digo.\n*\n* Transmitido: Assume-se que cada linha \u00e9 uma palavra-c\u00f3digo\n*/\nvoid canal(Matriz& Transmitido, double p) {\n    int count=0;\n    int n_linhas = Transmitido.size();\n    int n_colunas = Transmitido[0].size();\n    Vetor* linha;\n    boost::random::niederreiter_base2 gen(4);\n    boost::random::uniform_01<double> random;\n    for (int i = 0; i < n_linhas; ++i)\n    {\n        linha = &Transmitido[i];\n        for (int j = 0; j < n_colunas; ++j)\n        {\n            if (random(gen) < p) {\n                (*linha)[j].flip();\n                count++;\n            }\n        }\n    }\n    // std::cout << \"p \u2243 \" << ((double) count) / (n_linhas*n_colunas) << std::endl;\n}\n\n/**\n* amostras_informacao: Lista de palavras de informacao a serem enviadas\n*   Espera-se uma palavra por linha, elementos separados por v\u00edrgulas (sem espa\u00e7o)\n* \n* Ht_csv: Matriz de verifica\u00e7\u00e3o de paridade (transposta). Mesmo formato de `amostras_informacao_csv`\n*\n* Gt_csv: Matriz de gera\u00e7\u00e3o do c\u00f3digo (transposta). Mesmo formato de `amostras_informacao_csv`\n*\n* p: Lista de chances de o canal BSC inverter um bit transmitido\n*\n* peso_maximo_memorizado: Caso se encontre s\u00edndrome com peso maior que isto, ela n\u00e3o ser\u00e1 corrigida\n* \n* Retorna lista de chances de erro de bit (uma para cada valor de p)\n*/\nboost::container::vector<double> desempenho(\n    std::ifstream& amostras_informacao_csv,\n    std::ifstream& Ht_csv,\n    std::ifstream& Gt_csv,\n    const boost::container::vector<double>& p,\n    int peso_maximo_memorizado\n) {\n    boost::container::vector<double>* resultado = new boost::container::vector<double>(p.size());\n\n    Matriz Ht;\n    carrega_matriz(Ht_csv, Ht);\n\n    /**\n    * Exemplo de chave e valor:\n    * - chave: 0b1001 , valor: 0b101 significa uma s\u00edndrome [1, 0, 0, 1] com erro associado [1, 0, 1, ...]\n    *   em que as retic\u00eancias indicam a parte do erro concernente aos bits de paridade (n\u00e3o importam)\n    */\n    boost::unordered_map<unsigned long, unsigned long> dict;\n\n    int n_linhas = Ht.size();\n    int n_colunas = Ht[0].size();\n    int n_informacao = n_linhas - n_colunas;\n\n\n    popular_dict(\n        dict,\n        Ht,\n        n_linhas,\n        n_colunas,\n        n_informacao,\n        peso_maximo_memorizado\n    );\n\n    Matriz Info;\n    carrega_matriz(amostras_informacao_csv, Info);\n\n    int n_amostras = Info.size();\n\n    Matriz Gt;\n    carrega_matriz(Gt_csv, Gt);\n    Matriz G = transposta(Gt);\n\n    for (int i_p = 0; i_p < p.size(); ++i_p)\n    {\n        Matriz Transmitido = mult(Info, G);\n\n        canal(Transmitido, p[i_p]);\n\n        Matriz Sindromes = mult(Transmitido, Ht);\n\n        Matriz Transmitido_informacao = Matriz(n_amostras);\n        for (int i = 0; i < n_amostras; ++i)\n        {\n            Transmitido_informacao[i] = Vetor(n_informacao);\n            for (int j = 0; j < n_informacao; ++j)\n            {\n                Transmitido_informacao[i][n_informacao - j - 1] = Transmitido[i][n_linhas - j - 1];\n            }\n            // assert(Transmitido_informacao.size() == Transmitido.size());\n            // assert(Transmitido_informacao[0].size() == Info[0].size());\n            // assert(Transmitido_informacao[i] == Info[i]);\n        }\n\n        int n_erros = 0;\n        int incr=0;\n        unsigned long sindrome;\n        Vetor correcao_nula = Vetor(n_informacao, 0);\n        Vetor correcao;\n        for (int i = 0; i < n_amostras; ++i)\n        {\n            sindrome = Sindromes[i].to_ulong();\n            if (dict.find(sindrome) == dict.end())\n                correcao = correcao_nula;\n            else \n                correcao = Vetor(n_informacao, dict.at(sindrome));\n            incr = (Transmitido_informacao[i] ^ correcao ^ Info[i]).count();\n            // if (incr != 0) {\n            //     std::cout << correcao << \": \" << Transmitido_informacao[i] << \" versus \" << Info[i] << std::endl;\n            //     std::cout << \"diferen\u00e7a \" << (Transmitido_informacao[i] ^ Info[i]) << std::endl;\n            //     std::cout << \"Originais: \" << Transmitido[i] << \" versus \" << mult(Gt, Info[i]) << std::endl;\n            //     std::cout << \"diferen\u00e7a: \" << (Transmitido[i] ^ mult(Gt, Info[i])) << std::endl;\n            //     std::cout << \"s\u00edndrome: \" << Sindromes[i] << std::endl;\n            //     std::cout << std::endl;\n            // }\n\n            n_erros += incr;\n        }\n\n        (*resultado)[i_p] = n_erros / ((double) n_amostras * n_informacao);\n        std::cout << \"parcial(\" << i_p << \"): \" << (*resultado)[i_p] << std::endl;\n    }\n    return *resultado;\n}\n\nint main(int argc, char** argv) {\n\n    int arg_peso_maximo = std::stoi(argv[1]);\n    std::string arg_resultados = argv[2];\n\n    std::ifstream Htcsv (\"dados/Ht.csv\");\n    std::ifstream amostrasInput(\"dados/amostra-informacao.csv\");\n    std::ifstream GtInput(\"dados/Gt.csv\");\n    std::ofstream Resultados(arg_resultados);\n    std::ofstream P(\"dados/lista-de-p.csv\");\n\n    boost::container::vector<double> p = boost::container::vector<double>(0);\n    double p0 = 0.5;\n    while(p0 > 1 /((double) 1000000)) {\n        p.push_back(p0);\n        p0 *= 0.5;\n    }\n\n    boost::container::vector<double> des = desempenho(amostrasInput, Htcsv, GtInput, p, arg_peso_maximo);\n    Resultados << des[0];\n    P << p[0];\n    for (int i = 1; i < des.size(); ++i)\n    {\n        Resultados << \",\";\n        Resultados << des[i];\n        P << \",\";\n        P << p[i];\n    }\n    Resultados << std::endl;\n    P << std::endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "b70be8a5d9602e682ae5ccd0cc4b8fdead4fd1db", "size": 14304, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "benchmark.cpp", "max_stars_repo_name": "megatron0000/ELE-32-codigos-de-bloco", "max_stars_repo_head_hexsha": "70a0818e303f2154862b1772d317fdbcc7dfb5c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "benchmark.cpp", "max_issues_repo_name": "megatron0000/ELE-32-codigos-de-bloco", "max_issues_repo_head_hexsha": "70a0818e303f2154862b1772d317fdbcc7dfb5c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "benchmark.cpp", "max_forks_repo_name": "megatron0000/ELE-32-codigos-de-bloco", "max_forks_repo_head_hexsha": "70a0818e303f2154862b1772d317fdbcc7dfb5c0", "max_forks_repo_licenses": ["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.9921722114, "max_line_length": 116, "alphanum_fraction": 0.5859899329, "num_tokens": 4399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390162, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.46614301826393356}}
{"text": "/*****************************************************************************\n*\n* Rokko: Integrated Interface for libraries of eigenvalue decomposition\n*\n* Copyright (C) 2012-2015 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#include <rokko/rokko.hpp>\n#include <rokko/collective.hpp>\n#include <rokko/utility/xyz_hamiltonian_mpi.hpp>\n#include <boost/tuple/tuple.hpp>\n#include <fstream>\n#include <iostream>\n\ntypedef rokko::matrix_col_major matrix_major;\n\nint main(int argc, char *argv[]) {\n  int provided;\n  MPI_Init_thread(&argc, &argv, MPI_THREAD_MULTIPLE, &provided);\n  MPI_Comm comm = MPI_COMM_WORLD;\n  std::string solver_name(rokko::parallel_dense_solver::default_solver());\n  std::string lattice_file(\"xyz.dat\");\n  if (argc >= 2) solver_name = argv[1];\n  if (argc >= 3) lattice_file = argv[2];\n\n  rokko::grid g(comm);\n  int myrank = g.get_myrank();\n\n  std::cout.precision(5);\n\n  std::ifstream ifs(lattice_file.c_str());\n  if (!ifs) {\n    std::cout << \"can't open file\" << std::endl;\n    exit(1);\n  }\n  int num_sites, num_bonds;\n  std::vector<std::pair<int, int> > lattice;\n  std::vector<boost::tuple<double, double, double> > coupling;\n  ifs >> num_sites >> num_bonds;\n  int dim = 1 << num_sites;\n  for (int i = 0; i < num_bonds; ++i) {\n    int j, k;\n    ifs >> j >> k;\n    lattice.push_back(std::make_pair(j, k));\n  }\n  for (int i = 0; i < num_bonds; ++i) {\n    double jx, jy, jz;\n    ifs >> jx >> jy >> jz;\n    coupling.push_back(boost::make_tuple(jx, jy, jz));\n  }\n\n  rokko::parallel_dense_solver solver(solver_name);\n  solver.initialize(argc, argv);\n  if (myrank == 0)\n    std::cout << \"Eigenvalue decomposition of XYZ model\" << std::endl\n              << \"num_procs = \" << g.get_nprocs() << std::endl\n              #ifdef _OPENMP\n              << \"num_threads per process = \" << omp_get_max_threads() << std::endl\n              #endif\n              << \"solver = \" << solver_name << std::endl\n              << \"lattice file = \" << lattice_file << std::endl\n              << \"number of sites = \" << num_sites << std::endl\n              << \"number of bonds = \" << num_bonds << std::endl\n              << \"dimension = \" << dim << std::endl;\n\n  rokko::distributed_matrix<double, matrix_major> mat(dim, dim, g, solver);\n  rokko::xyz_hamiltonian::generate(num_sites, lattice, coupling, mat);\n  rokko::localized_matrix<double, matrix_major> mat_loc(dim, dim);\n  rokko::gather(mat, mat_loc, 0);\n\n  rokko::localized_vector<double> eigval(dim);\n  rokko::distributed_matrix<double, matrix_major> eigvec(dim, dim, g, solver);\n  try {\n    solver.diagonalize(mat, eigval, eigvec);\n  }\n  catch (const char *e) {\n    if (myrank == 0) std::cout << \"Exception : \" << e << std::endl;\n    MPI_Abort(MPI_COMM_WORLD, 22);\n  }\n\n  rokko::localized_matrix<double, matrix_major> eigvec_loc(dim, dim);\n  rokko::gather(eigvec, eigvec_loc, 0);\n  if (myrank == 0) {\n    std::cout << \"smallest eigenvalues:\";\n    for (int i = 0; i < std::min(dim, 10); ++i) std::cout << ' ' << eigval(i);\n    std::cout << std::endl;\n    std::cout << \"residual of the smallest eigenvalue/vector: |x A x - lambda| = \"\n              << std::abs(eigvec_loc.col(0).transpose() * mat_loc * eigvec_loc.col(0) - eigval(0))\n              << std::endl;\n  }\n\n  solver.finalize();\n  MPI_Finalize();\n}\n", "meta": {"hexsha": "c1da6fc6e396e19cd5809a319c721909a2f126a8", "size": 3494, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/cxx/dense/xyz_mpi.cpp", "max_stars_repo_name": "wistaria/rokko", "max_stars_repo_head_hexsha": "7cd9d5155e82f038039a46c1dc8f382b3fe7e2b7", "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": "example/cxx/dense/xyz_mpi.cpp", "max_issues_repo_name": "wistaria/rokko", "max_issues_repo_head_hexsha": "7cd9d5155e82f038039a46c1dc8f382b3fe7e2b7", "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": "example/cxx/dense/xyz_mpi.cpp", "max_forks_repo_name": "wistaria/rokko", "max_forks_repo_head_hexsha": "7cd9d5155e82f038039a46c1dc8f382b3fe7e2b7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.2929292929, "max_line_length": 98, "alphanum_fraction": 0.599885518, "num_tokens": 1001, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.6297746004557471, "lm_q1q2_score": 0.466143013120709}}
{"text": "#ifndef CAFFE_UTIL_PREDICTION_H_\n#define CAFFE_UTIL_PREDICTION_H_\n\n#include <vector>\n#include <Eigen/Core>\n#include <Eigen/LU>\n#include <iostream>\n#include \"caffe/blob.hpp\"\n\nnamespace caffe {\n\n\ttemplate <typename Dtype>\n\tusing Slice = Eigen::Matrix<Dtype,Eigen::Dynamic,Eigen::Dynamic, Eigen::RowMajor>;\n\ttemplate <typename Dtype>\n\tusing Grid = std::vector<Slice<Dtype> >;\n\n\ttemplate <typename Dtype>\n\tGrid<Dtype> rotate_voxels_prediction(const Grid<Dtype> &vox,\n\t\t\t\t\t\t\t\t\t\t const Eigen::Matrix<Dtype,4,4> &model1,\n\t\t\t\t\t\t\t\t\t\t const Eigen::Matrix<Dtype,4,4> &view1,\n\t\t\t\t\t\t\t\t\t\t const Eigen::Matrix<Dtype,4,4> &model2,\n\t\t\t\t\t\t\t\t\t\t const Eigen::Matrix<Dtype,4,4> &view2,\n\t\t\t\t\t\t\t\t\t\t const Eigen::Matrix<Dtype,4,4> &proj);\n\n\ttemplate <typename Dtype>\n\tDtype rotated_proba_value(const Grid<Dtype> &vox,\n\t\t\t\t\t\t\t  const Eigen::Matrix<Dtype,4,4> &model1,\n\t\t\t\t\t\t\t  const Eigen::Matrix<Dtype,4,4> &view1,\n\t\t\t\t\t\t\t  const Eigen::Matrix<Dtype,4,4> &model2,\n\t\t\t\t\t\t\t  const Eigen::Matrix<Dtype,4,4> &view2,\n\t\t\t\t\t\t\t  const Eigen::Matrix<Dtype,4,4> &proj,\n\t\t\t\t\t\t\t  Dtype z,Dtype x, Dtype y);\n\n\ttemplate <typename Dtype>\n\tDtype z_to_depth(int z, int size, const Eigen::Matrix<Dtype,4,4> &proj);\n\ttemplate <typename Dtype>\n\tint depth_to_z(Dtype depth, int size, const Eigen::Matrix<Dtype,4,4> &proj);\n\n\ttemplate <typename Dtype>\n\tEigen::Matrix<Dtype,3,1> rotate_coords(Dtype x, Dtype y, Dtype z,\n\t\t\t\t\t\t\t\t\t\t   const Eigen::Matrix<Dtype,4,4> &model1,\n\t\t\t\t\t\t\t\t\t\t   const Eigen::Matrix<Dtype,4,4> &view1,\n\t\t\t\t\t\t\t\t\t\t   const Eigen::Matrix<Dtype,4,4> &model2,\n\t\t\t\t\t\t\t\t\t\t   const Eigen::Matrix<Dtype,4,4> &view2,\n\t\t\t\t\t\t\t\t\t\t   const Eigen::Matrix<Dtype,4,4> &proj);\n\ttemplate <typename Dtype>\n\tvoid rotate_blobs(const Blob<Dtype> * pred,\n\t\t\t\t\t  const Dtype* model1,\n\t\t\t\t\t  const Dtype* view_mat1,\n\t\t\t\t\t  const Dtype* model2,\n\t\t\t\t\t  const Dtype* view_mat2,\n\t\t\t\t\t  const Dtype* proj_mat,\n\t\t\t\t\t  Dtype * output) ;\n\n\t\ttemplate <typename Dtype>\n\t\tGrid<Dtype> unpack_pred_in_image( cv::Mat &image, int grid_rows, int grid_cols);\n\ttemplate <typename Dtype>\n\tint CV_type();\n\n\t\n}\n\n#endif\n", "meta": {"hexsha": "427fcb79692a69d4460c1f50f9bb009ddc7d9a72", "size": 2048, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/caffe/util/prediction.hpp", "max_stars_repo_name": "antonymarion/caffe", "max_stars_repo_head_hexsha": "0c9f2e500c6f971b2de45d08021c26d55cabc91b", "max_stars_repo_licenses": ["Intel", "BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-07-09T03:46:41.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-14T18:12:59.000Z", "max_issues_repo_path": "include/caffe/util/prediction.hpp", "max_issues_repo_name": "antonymarion/caffe", "max_issues_repo_head_hexsha": "0c9f2e500c6f971b2de45d08021c26d55cabc91b", "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": "include/caffe/util/prediction.hpp", "max_forks_repo_name": "antonymarion/caffe", "max_forks_repo_head_hexsha": "0c9f2e500c6f971b2de45d08021c26d55cabc91b", "max_forks_repo_licenses": ["Intel", "BSD-2-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-05-04T13:47:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-31T19:23:59.000Z", "avg_line_length": 32.0, "max_line_length": 83, "alphanum_fraction": 0.6611328125, "num_tokens": 574, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.4661430110448629}}
{"text": "/*\n [auto_generated]\n libs/numeric/odeint/test/integrate.cpp\n\n [begin_description]\n This file tests the integrate function and its variants.\n [end_description]\n\n Copyright 2009-2012 Karsten Ahnert\n Copyright 2009-2012 Mario Mulansky\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#define BOOST_TEST_MODULE odeint_integrate_functions\n\n#include <vector>\n#include <cmath>\n#include <iostream>\n\n#include <boost/numeric/odeint/config.hpp>\n\n#include <boost/array.hpp>\n#include <boost/ref.hpp>\n#include <boost/iterator/counting_iterator.hpp>\n\n#include <boost/test/unit_test.hpp>\n\n#include <boost/mpl/vector.hpp>\n\n// nearly everything from odeint is used in these tests\n#include <boost/numeric/odeint/integrate/integrate_const.hpp>\n#include <boost/numeric/odeint/integrate/integrate_adaptive.hpp>\n#include <boost/numeric/odeint/integrate/integrate_times.hpp>\n#include <boost/numeric/odeint/integrate/integrate_n_steps.hpp>\n#include <boost/numeric/odeint/stepper/euler.hpp>\n#include <boost/numeric/odeint/stepper/modified_midpoint.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/runge_kutta_dopri5.hpp>\n#include <boost/numeric/odeint/stepper/runge_kutta_fehlberg78.hpp>\n#include <boost/numeric/odeint/stepper/controlled_runge_kutta.hpp>\n#include <boost/numeric/odeint/stepper/bulirsch_stoer.hpp>\n#include <boost/numeric/odeint/stepper/dense_output_runge_kutta.hpp>\n#include <boost/numeric/odeint/stepper/bulirsch_stoer_dense_out.hpp>\n\n#include <boost/numeric/odeint/util/detail/less_with_sign.hpp>\n\nusing namespace boost::unit_test;\nusing namespace boost::numeric::odeint;\nnamespace mpl = boost::mpl;\n\n\ntypedef double value_type;\ntypedef std::vector< value_type > state_type;\n\nvoid lorenz( const state_type &x , state_type &dxdt , const value_type t )\n{\n    //const value_type sigma( 10.0 );\n    const value_type R( 28.0 );\n    const value_type b( value_type( 8.0 ) / value_type( 3.0 ) );\n\n    // first component trivial\n    dxdt[0] = 1.0; //sigma * ( x[1] - x[0] );\n    dxdt[1] = R * x[0] - x[1] - x[0] * x[2];\n    dxdt[2] = -b * x[2] + x[0] * x[1];\n}\n\nstruct push_back_time\n{\n    std::vector< double >& m_times;\n\n    state_type& m_x;\n\n    push_back_time( std::vector< double > &times , state_type &x )\n    :  m_times( times ) , m_x( x ) { }\n\n    void operator()( const state_type &x , double t )\n    {\n        m_times.push_back( t );\n        boost::numeric::odeint::copy( x , m_x );\n    }\n};\n\ntemplate< class Stepper >\nstruct perform_integrate_const_test\n{\n    void operator()( const value_type t_end , const value_type dt )\n    {\n        std::cout << \"Testing integrate_const with \" << typeid( Stepper ).name() << std::endl;\n\n        state_type x( 3 , 10.0 ) , x_end( 3 );\n\n        std::vector< value_type > times;\n\n        integrate_const( Stepper() , lorenz , x , 0.0 , t_end ,\n                                        dt , push_back_time( times , x_end ) );\n\n        // int steps = times.size()-1;\n\n        //std::cout << t_end << \" (\" << dt << \"), \" << steps << \" , \" << times.size() << \" , \" << 10.0+dt*steps << \"=\" << x_end[0] << std::endl;\n\n        BOOST_CHECK_EQUAL( static_cast<int>(times.size()) , static_cast<int>(floor(t_end/dt))+1 );\n\n        for( size_t i=0 ; i<times.size() ; ++i )\n        {\n            //std::cout << i << \" , \" << times[i] << \" , \" << static_cast< value_type >(i)*dt << std::endl;\n            // check if observer was called at times 0,1,2,...\n            BOOST_CHECK_SMALL( times[i] - static_cast< value_type >(i)*dt , (i+1) * 2E-16 );\n        }\n\n        // check first, trivial, component\n        BOOST_CHECK_SMALL( (10.0 + times[times.size()-1]) - x_end[0] , 1E-6 ); // precision of steppers: 1E-6\n        //BOOST_CHECK_EQUAL( x[1] , x_end[1] );\n        //BOOST_CHECK_EQUAL( x[2] , x_end[2] );\n    }\n};\n\ntemplate< class Stepper >\nstruct perform_integrate_adaptive_test\n{\n    void operator()( const value_type t_end = 10.0 , const value_type dt = 0.03 )\n    {\n        std::cout << \"Testing integrate_adaptive with \" << typeid( Stepper ).name() << std::endl;\n\n        state_type x( 3 , 10.0 ) , x_end( 3 );\n\n        std::vector< value_type > times;\n\n        size_t steps = integrate_adaptive( Stepper() , lorenz , x , 0.0 , t_end ,\n                                        dt , push_back_time( times , x_end ) );\n\n//        std::cout << t_end << \" , \" << steps << \" , \" << times.size() << \" , \" << 10.0+dt*steps << \"=\" << x_end[0] << std::endl;\n\n        BOOST_CHECK_EQUAL( times.size() , steps+1 );\n\n        BOOST_CHECK_SMALL( times[0] - 0.0 , 2E-16 );\n        BOOST_CHECK_SMALL( times[times.size()-1] - t_end , times.size() * 2E-16 );\n\n        // check first, trivial, component\n        BOOST_CHECK_SMALL( (10.0 + t_end) - x_end[0] , 1E-6 ); // precision of steppers: 1E-6\n//        BOOST_CHECK_EQUAL( x[1] , x_end[1] );\n//        BOOST_CHECK_EQUAL( x[2] , x_end[2] );\n    }\n};\n\n\ntemplate< class Stepper >\nstruct perform_integrate_times_test\n{\n    void operator()( const int n = 10 , const int dn=1 , const value_type dt = 0.03 )\n    {\n        std::cout << \"Testing integrate_times with \" << typeid( Stepper ).name() << std::endl;\n\n        state_type x( 3 ) , x_end( 3 );\n        x[0] = x[1] = x[2] = 10.0;\n\n        std::vector< double > times;\n\n        std::vector< double > obs_times( abs(n) );\n        for( int i=0 ; boost::numeric::odeint::detail::less_with_sign( static_cast<double>(i) ,\n                       static_cast<double>(obs_times.size()) ,\n                       dt ) ; i+=dn )\n        {\n            obs_times[i] = i;\n        }\n        // simple stepper\n        integrate_times( Stepper() , lorenz , x , obs_times.begin() , obs_times.end() ,\n                    dt , push_back_time( times , x_end ) );\n\n        BOOST_CHECK_EQUAL( static_cast<int>(times.size()) , abs(n) );\n\n        for( size_t i=0 ; i<times.size() ; ++i )\n            // check if observer was called at times 0,1,2,...\n            BOOST_CHECK_EQUAL( times[i] , static_cast<double>(i) );\n\n        // check first, trivial, component\n        BOOST_CHECK_SMALL( (10.0 + 1.0*times[times.size()-1]) - x_end[0] , 1E-6 ); // precision of steppers: 1E-6\n//        BOOST_CHECK_EQUAL( x[1] , x_end[1] );\n//        BOOST_CHECK_EQUAL( x[2] , x_end[2] );\n    }\n};\n\ntemplate< class Stepper >\nstruct perform_integrate_n_steps_test\n{\n    void operator()( const int n = 200 , const value_type dt = 0.01 )\n    {\n        std::cout << \"Testing integrate_n_steps with \" << typeid( Stepper ).name() << std::endl;\n\n        state_type x( 3 ) , x_end( 3 );\n        x[0] = x[1] = x[2] = 10.0;\n\n        std::vector< double > times;\n\n        // simple stepper\n        value_type end_time = integrate_n_steps( Stepper() , lorenz , x , 0.0 , dt , n , push_back_time( times , x_end ) );\n\n        BOOST_CHECK_SMALL( end_time - n*dt , 2E-16 );\n        BOOST_CHECK_EQUAL( static_cast<int>(times.size()) , n+1 );\n\n        for( size_t i=0 ; i<times.size() ; ++i )\n            // check if observer was called at times 0,1,2,...\n            BOOST_CHECK_SMALL( times[i] - static_cast< value_type >(i)*dt , 2E-16 );\n\n        // check first, trivial, component\n        BOOST_CHECK_SMALL( (10.0 + end_time) - x_end[0] , 1E-6 ); // precision of steppers: 1E-6\n//        BOOST_CHECK_EQUAL( x[1] , x_end[1] );\n//        BOOST_CHECK_EQUAL( x[2] , x_end[2] );\n\n    }\n};\n\n\n\nclass stepper_methods : public mpl::vector<\n    euler< state_type > ,\n    modified_midpoint< state_type > ,\n    runge_kutta4< state_type > ,\n    runge_kutta_cash_karp54< state_type > ,\n    runge_kutta_dopri5< state_type > ,\n    runge_kutta_fehlberg78< state_type > ,\n    controlled_runge_kutta< runge_kutta_cash_karp54< state_type > > ,\n    controlled_runge_kutta< runge_kutta_dopri5< state_type > > ,\n    controlled_runge_kutta< runge_kutta_fehlberg78< state_type > > ,\n    bulirsch_stoer< state_type > ,\n    dense_output_runge_kutta< controlled_runge_kutta< runge_kutta_dopri5< state_type > > >\n    //bulirsch_stoer_dense_out< state_type >\n> { };\n\n\n\nBOOST_AUTO_TEST_SUITE( integrate_test )\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( integrate_const_test_case , Stepper, stepper_methods )\n{\n    perform_integrate_const_test< Stepper > tester;\n    tester( 1.005 , 0.01 );\n    tester( 1.0 , 0.01 );\n    tester( 1.1 , 0.01 );\n    tester( -1.005 , -0.01 );\n}\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( integrate_adaptive_test_case , Stepper, stepper_methods )\n{\n    perform_integrate_adaptive_test< Stepper > tester;\n    tester( 1.005 , 0.01 );\n    tester( 1.0 , 0.01 );\n    tester( 1.1 , 0.01 );\n    tester( -1.005 , -0.01 );\n}\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( integrate_times_test_case , Stepper, stepper_methods )\n{\n    perform_integrate_times_test< Stepper > tester;\n    tester();\n    //tester( -10 , -0.01 );\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( integrate_n_steps_test_case , Stepper, stepper_methods )\n{\n    perform_integrate_n_steps_test< Stepper > tester;\n    tester();\n    tester( 200 , 0.01 );\n    tester( 200 , 0.01 );\n    tester( 200 , 0.01 );\n    tester( 200 , -0.01 );\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "4f4f2107e77806d286cdb3dd24c33cc218f848b3", "size": 9153, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Src/ros_simulator/src/quadrotor_simulator/include/odeint-v2/libs/numeric/odeint/test/integrate.cpp", "max_stars_repo_name": "Drona-Org/Drona-DMR", "max_stars_repo_head_hexsha": "ecc756ec137aee90ab5ac9ea97f09b6e030066f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-05-14T14:49:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T06:53:28.000Z", "max_issues_repo_path": "Src/ros_simulator/src/quadrotor_simulator/include/odeint-v2/libs/numeric/odeint/test/integrate.cpp", "max_issues_repo_name": "Dronacharya-Org/Dronacharya", "max_issues_repo_head_hexsha": "ecc756ec137aee90ab5ac9ea97f09b6e030066f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Src/ros_simulator/src/quadrotor_simulator/include/odeint-v2/libs/numeric/odeint/test/integrate.cpp", "max_forks_repo_name": "Dronacharya-Org/Dronacharya", "max_forks_repo_head_hexsha": "ecc756ec137aee90ab5ac9ea97f09b6e030066f0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-12-15T20:18:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-31T19:26:57.000Z", "avg_line_length": 33.1630434783, "max_line_length": 144, "alphanum_fraction": 0.6276630613, "num_tokens": 2695, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6039318479832805, "lm_q2_score": 0.7718435083355188, "lm_q1q2_score": 0.46614087634296847}}
{"text": "// Copyright Abel Sinkovics (abel@sinkovics.hu) 2013.\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 \"print_values.hpp\"\n\n#include <mpllibs/metamonad/lambda_c.hpp>\n#include <mpllibs/metamonad/name.hpp>\n#include <mpllibs/metamonad/metafunction.hpp>\n#include <mpllibs/metamonad/lazy_metafunction.hpp>\n#include <mpllibs/metamonad/lazy.hpp>\n#include <mpllibs/metamonad/lazy_protect_args.hpp>\n#include <mpllibs/metamonad/if_.hpp>\n#include <mpllibs/metamonad/tmp_value.hpp>\n#include <mpllibs/metamonad/apply.hpp>\n\n#include <boost/mpl/int.hpp>\n#include <boost/mpl/plus.hpp>\n#include <boost/mpl/minus.hpp>\n#include <boost/mpl/list_c.hpp>\n#include <boost/mpl/insert_range.hpp>\n#include <boost/mpl/begin_end.hpp>\n#include <boost/mpl/equal_to.hpp>\n\n#include <iostream>\n\nusing boost::mpl::int_;\nusing boost::mpl::plus;\nusing boost::mpl::minus;\nusing boost::mpl::list_c;\nusing boost::mpl::insert_range;\nusing boost::mpl::end;\nusing boost::mpl::equal_to;\n\nusing mpllibs::metamonad::lambda_c;\nusing mpllibs::metamonad::lazy;\nusing mpllibs::metamonad::lazy_protect_args;\nusing mpllibs::metamonad::if_;\nusing mpllibs::metamonad::tmp_value;\nusing mpllibs::metamonad::apply;\n\nusing namespace mpllibs::metamonad::name;\n\n/*\n * The typeclass\n */\ntemplate <class Tag>\nstruct addable;\n// Requires:\n//   struct add { template <class, class> struct apply; };\n\nMPLLIBS_METAFUNCTION(add, (Tag)(A)(B))\n((apply<typename addable<Tag>::add, A, B>));\n\nMPLLIBS_METAFUNCTION(double_, (Tag)(X))\n((apply<typename addable<Tag>::double_, X>));\n\ntemplate <class Tag>\nstruct addable_defaults\n{\n  typedef lambda_c<n, add<Tag, n, n> > double_;\n};\n\n/*\n * Integers\n */\ntypedef int_<0>::tag int_tag;\n\ntemplate <>\nstruct addable<int_tag> : addable_defaults<int_tag>\n{\n  struct add : tmp_value<add>\n  {\n    MPLLIBS_LAZY_METAFUNCTION(apply, (A)(B)) ((int_<A::value + B::value>));\n  };\n};\n\n/*\n * Lists\n */\ntypedef list_c<int>::tag list_tag;\n\ntemplate <>\nstruct addable<list_tag> : addable_defaults<list_tag>\n{\n  typedef\n    lambda_c<a, b,\n      lazy<\n        insert_range<\n          lazy_protect_args<a>,\n          end<lazy_protect_args<a> >,\n          lazy_protect_args<b>\n        >\n      >\n    >\n    add;\n};\n\n/*\n * Generic function\n */\nMPLLIBS_LAZY_METAFUNCTION(mult, (T)(N))\n((\n  if_<\n    equal_to<int_<1>, N>,\n    T,\n    add<typename T::tag, mult<T, minus<N, int_<1> > >, T>\n  >\n));\n\n\nint main()\n{\n  using std::cout;\n  using std::endl;\n\n  cout\n    << \"add<int_tag, 11, 2> = \" << add<int_tag, int_<11>, int_<2> >::type::value\n    << endl;\n\n  cout\n    << \"double_<int_tag, 3> = \" << double_<int_tag, int_<3> >::type::value\n    << endl;\n    \n  cout\n    << \"mult<3, 4> = \" << mult<int_<3>, int_<4> >::type::value\n    << endl;\n\n  cout << \"add<list_tag, [1, 2], [3, 4]> = \";\n  print_values<add<list_tag, list_c<int, 1, 2>, list_c<int, 3, 4> > >();\n  cout << endl;\n\n  cout << \"double_<list_tag, [1, 2]> = \";\n  print_values<double_<list_tag, list_c<int, 1, 2> > >();\n  cout << endl;\n\n  cout << \"mult<[1, 2], 4> = \";\n  print_values<mult<list_c<int, 1, 2>, int_<4> > >();\n  cout << endl;\n}\n\n\n", "meta": {"hexsha": "dca2014192bc51b45242b7297018e7eeb29d79a5", "size": 3166, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/metamonad/example/typeclass/main.cpp", "max_stars_repo_name": "sabel83/mpllibs", "max_stars_repo_head_hexsha": "8e245aedcf658fe77bb29537aeba1d4e1a619a19", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 70.0, "max_stars_repo_stars_event_min_datetime": "2015-01-15T09:05:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-08T15:49:31.000Z", "max_issues_repo_path": "libs/metamonad/example/typeclass/main.cpp", "max_issues_repo_name": "sabel83/mpllibs", "max_issues_repo_head_hexsha": "8e245aedcf658fe77bb29537aeba1d4e1a619a19", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-06-18T19:25:34.000Z", "max_issues_repo_issues_event_max_datetime": "2016-05-13T19:49:51.000Z", "max_forks_repo_path": "libs/metamonad/example/typeclass/main.cpp", "max_forks_repo_name": "sabel83/mpllibs", "max_forks_repo_head_hexsha": "8e245aedcf658fe77bb29537aeba1d4e1a619a19", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2015-07-10T08:18:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-01T07:17:57.000Z", "avg_line_length": 21.9861111111, "max_line_length": 80, "alphanum_fraction": 0.656664561, "num_tokens": 984, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435083355188, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4661408653385469}}
{"text": "// Copyright 2019, Collabora, Ltd.\n// SPDX-License-Identifier: BSL-1.0\n/*!\n * @file\n * @brief  Low-pass IIR filter on vectors\n * @author Ryan Pavlik <ryan.pavlik@collabora.com>\n * @ingroup aux_tracking\n */\n\n#pragma once\n\n#ifndef __cplusplus\n#error \"This header is C++-only.\"\n#endif\n\n#include \"tracking/t_lowpass.hpp\"\n\n#include <Eigen/Core>\n\n\nnamespace xrt::auxiliary::tracking {\n\n/*!\n * A very simple low-pass filter, using a \"one-pole infinite impulse response\"\n * design (one-pole IIR).\n *\n * Configurable in dimension and scalar type.\n */\ntemplate <size_t Dim, typename Scalar> class LowPassIIRVectorFilter\n{\npublic:\n\tEIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n\tusing Vector = Eigen::Matrix<Scalar, Dim, 1>;\n\n\t/*!\n\t * Constructor\n\t *\n\t * @param cutoff_hz A cutoff frequency in Hertz: signal changes much\n\t * lower in frequency will be passed through the filter, while signal\n\t * changes much higher in frequency will be blocked.\n\t */\n\texplicit LowPassIIRVectorFilter(Scalar cutoff_hz) noexcept : impl_(cutoff_hz, Vector::Zero()) {}\n\n\n\t/*!\n\t * Reset the filter to just-created state.\n\t */\n\tvoid\n\treset() noexcept\n\t{\n\t\timpl_.reset(Vector::Zero());\n\t}\n\n\t/*!\n\t * Filter a sample, with an optional weight.\n\t *\n\t * @param sample The value to filter\n\t * @param timestamp_ns The time that this sample was measured.\n\t * @param weight An optional value between 0 and 1. The smaller this\n\t * value, the less the current sample influences the filter state. For\n\t * the first call, this is always assumed to be 1.\n\t */\n\tvoid\n\taddSample(Vector const &sample, std::uint64_t timestamp_ns, Scalar weight = 1)\n\t{\n\t\timpl_.addSample(sample, timestamp_ns, weight);\n\t}\n\n\t/*!\n\t * Access the filtered value.\n\t */\n\tVector const &\n\tgetState() const noexcept\n\t{\n\t\treturn impl_.state;\n\t}\n\n\t/*!\n\t * Access the time of last update.\n\t */\n\tstd::uint64_t\n\tgetTimestampNs() const noexcept\n\t{\n\t\treturn impl_.filter_timestamp_ns;\n\t}\n\n\t/*!\n\t * Access whether we have initialized state.\n\t */\n\tbool\n\tisInitialized() const noexcept\n\t{\n\t\treturn impl_.initialized;\n\t}\n\nprivate:\n\tdetail::LowPassIIR<Vector, Scalar> impl_;\n};\n\n} // namespace xrt::auxiliary::tracking\n", "meta": {"hexsha": "c8b6d7f71770b7785d50b97d668baecf65c7dc2f", "size": 2116, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/xrt/auxiliary/tracking/t_lowpass_vector.hpp", "max_stars_repo_name": "SimulaVR/monado", "max_stars_repo_head_hexsha": "b5d46eebf5f9b7f96a52639484a1b35d8ab3cd21", "max_stars_repo_licenses": ["Unlicense", "Apache-2.0", "BSD-2-Clause", "MIT", "BSL-1.0", "BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-11-08T05:17:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T12:50:59.000Z", "max_issues_repo_path": "src/xrt/auxiliary/tracking/t_lowpass_vector.hpp", "max_issues_repo_name": "SimulaVR/monado", "max_issues_repo_head_hexsha": "b5d46eebf5f9b7f96a52639484a1b35d8ab3cd21", "max_issues_repo_licenses": ["Unlicense", "Apache-2.0", "BSD-2-Clause", "MIT", "BSL-1.0", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/xrt/auxiliary/tracking/t_lowpass_vector.hpp", "max_forks_repo_name": "SimulaVR/monado", "max_forks_repo_head_hexsha": "b5d46eebf5f9b7f96a52639484a1b35d8ab3cd21", "max_forks_repo_licenses": ["Unlicense", "Apache-2.0", "BSD-2-Clause", "MIT", "BSL-1.0", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.7450980392, "max_line_length": 97, "alphanum_fraction": 0.7036862004, "num_tokens": 554, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.46614085899941016}}
{"text": "/*\n * ***** BEGIN GPL LICENSE BLOCK *****\n *\n * This program is free software; you can redistribute it and/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 2\n * of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\n * The Original Code is Copyright (C) 2018 by Blender Foundation.\n * All rights reserved.\n *\n * Contributor(s): MARUI-PlugIn\n *\n * ***** END GPL LICENSE BLOCK *****\n */\n\n/** \\file blender/vr/intern/vr_math.cpp\n *   \\ingroup vr\n *\n * Collection of VR math-related utility functions.\n */\n\n#include \"vr_types.h\"\n\n#include \"vr_math.h\"\n\n#include <Eigen/Dense>\n\n/* Externed in vr_types.h */\nbool mat44_inverse(float inv[4][4], const float m[4][4])\n{\n  Eigen::Map<Eigen::Matrix4f> mat = Eigen::Map<Eigen::Matrix4f>((float *)m);\n  Eigen::Matrix4f out;\n  bool invertible = true;\n  mat.computeInverseWithCheck(out, invertible, 0.0f);\n  if (!invertible) {\n    out = out.Zero();\n  }\n  memcpy(inv, out.data(), sizeof(float) * 4 * 4);\n  return invertible;\n}\n\n/* Externed in vr_types.h */\nbool mat44_inverse(double inv[4][4], const double m[4][4])\n{\n  Eigen::Map<Eigen::Matrix4d> mat = Eigen::Map<Eigen::Matrix4d>((double *)m);\n  Eigen::Matrix4d out;\n  bool invertible = true;\n  mat.computeInverseWithCheck(out, invertible, 0.0f);\n  if (!invertible) {\n    out = out.Zero();\n  }\n  memcpy(inv, out.data(), sizeof(double) * 4 * 4);\n  return invertible;\n}\n\nstatic void mat44_multiply_unique(float R[4][4], const float A[4][4], const float B[4][4])\n{\n  /* matrix product: R[j][k] = A[j][i] . B[i][k] */\n  __m128 A0 = _mm_loadu_ps(A[0]);\n  __m128 A1 = _mm_loadu_ps(A[1]);\n  __m128 A2 = _mm_loadu_ps(A[2]);\n  __m128 A3 = _mm_loadu_ps(A[3]);\n\n  for (int i = 0; i < 4; i++) {\n    __m128 B0 = _mm_set1_ps(B[i][0]);\n    __m128 B1 = _mm_set1_ps(B[i][1]);\n    __m128 B2 = _mm_set1_ps(B[i][2]);\n    __m128 B3 = _mm_set1_ps(B[i][3]);\n\n    __m128 sum = _mm_add_ps(_mm_add_ps(_mm_mul_ps(B0, A0), _mm_mul_ps(B1, A1)),\n                            _mm_add_ps(_mm_mul_ps(B2, A2), _mm_mul_ps(B3, A3)));\n\n    _mm_storeu_ps(R[i], sum);\n  }\n}\nstatic void mat44_pre_multiply(float R[4][4], const float A[4][4])\n{\n  float B[4][4];\n  std::memcpy(B, R, sizeof(float) * 4 * 4);\n  mat44_multiply_unique(R, A, B);\n}\nstatic void mat44_post_multiply(float R[4][4], const float B[4][4])\n{\n  float A[4][4];\n  std::memcpy(A, R, sizeof(float) * 4 * 4);\n  mat44_multiply_unique(R, A, B);\n}\n/* Externed in vr_types.h */\nvoid mat44_multiply(float R[4][4], const float A[4][4], const float B[4][4])\n{\n  if (A == R) {\n    mat44_post_multiply(R, B);\n  }\n  else if (B == R) {\n    mat44_pre_multiply(R, A);\n  }\n  else {\n    mat44_multiply_unique(R, A, B);\n  }\n}\n\nstatic void mat44_multiply_unique(double R[4][4], const double A[4][4], const double B[4][4])\n{\n  /* matrix product: R[j][k] = A[j][i] . B[i][k] */\n  __m128d A0 = _mm_loadu_pd(A[0]);\n  __m128d A1 = _mm_loadu_pd(A[1]);\n  __m128d A2 = _mm_loadu_pd(A[2]);\n  __m128d A3 = _mm_loadu_pd(A[3]);\n\n  for (int i = 0; i < 4; i++) {\n    __m128d B0 = _mm_set1_pd(B[i][0]);\n    __m128d B1 = _mm_set1_pd(B[i][1]);\n    __m128d B2 = _mm_set1_pd(B[i][2]);\n    __m128d B3 = _mm_set1_pd(B[i][3]);\n\n    __m128d sum = _mm_add_pd(_mm_add_pd(_mm_mul_pd(B0, A0), _mm_mul_pd(B1, A1)),\n                             _mm_add_pd(_mm_mul_pd(B2, A2), _mm_mul_pd(B3, A3)));\n\n    _mm_storeu_pd(R[i], sum);\n  }\n}\nstatic void mat44_pre_multiply(double R[4][4], const double A[4][4])\n{\n  double B[4][4];\n  std::memcpy(B, R, sizeof(double) * 4 * 4);\n  mat44_multiply_unique(R, A, B);\n}\nstatic void mat44_post_multiply(double R[4][4], const double B[4][4])\n{\n  double A[4][4];\n  std::memcpy(A, R, sizeof(double) * 4 * 4);\n  mat44_multiply_unique(R, A, B);\n}\n/* Externed in vr_types.h */\nvoid mat44_multiply(double R[4][4], const double A[4][4], const double B[4][4])\n{\n  if (A == R) {\n    mat44_post_multiply(R, B);\n  }\n  else if (B == R) {\n    mat44_pre_multiply(R, A);\n  }\n  else {\n    mat44_multiply_unique(R, A, B);\n  }\n}\n\nfloat ident_f[4][4] = {1.0f,\n                       0.0f,\n                       0.0f,\n                       0.0f,\n                       0.0f,\n                       1.0f,\n                       0.0f,\n                       0.0f,\n                       0.0f,\n                       0.0f,\n                       1.0f,\n                       0.0f,\n                       0.0f,\n                       0.0f,\n                       0.0f,\n                       1.0f};\nconst Mat44f VR_Math::identity_f = ident_f;\n\ndouble ident_d[4][4] = {\n    1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0};\nconst Mat44d VR_Math::identity_d = ident_d;\n\nvoid VR_Math::multiply_mat44_coord3D(Coord3Df &r, const Mat44f &m, const Coord3Df &v)\n{\n  const float &x = v.x;\n  const float &y = v.y;\n  const float &z = v.z;\n\n  r.x = x * m.m[0][0] + y * m.m[1][0] + z * m.m[2][0] + m.m[3][0];\n  r.y = x * m.m[0][1] + y * m.m[1][1] + z * m.m[2][1] + m.m[3][1];\n  r.z = x * m.m[0][2] + y * m.m[1][2] + z * m.m[2][2] + m.m[3][2];\n}\n\nfloat VR_Math::matrix_distance(const Mat44f &a, const Mat44f &b)\n{\n  float dx = a.m[3][0] - b.m[3][0];\n  float dy = a.m[3][1] - b.m[3][1];\n  float dz = a.m[3][2] - b.m[3][2];\n  return sqrt(dx * dx + dy * dy + dz * dz);\n}\n\nfloat VR_Math::matrix_rotation(const Mat44f &a, const Mat44f &b, Coord3Df *axis)\n{\n  Coord3Df _axis;\n  float angle = 0.0f;\n  Quatf a_rotation(a);\n  Quatf b_rotation(b);\n  (a_rotation.inverse() * b_rotation).to_axis_angle(_axis, angle);\n  angle = (float)RADTODEG(angle);\n  float counter_angle = 360.0f - angle; /* rotation in opposite direction */\n  if (angle > counter_angle) {\n    angle = counter_angle;\n  }\n  if (axis) {\n    *axis = _axis;\n  }\n  return angle;\n}\n\nvoid VR_Math::orient_matrix_z(Mat44f &m, Coord3Df z)\n{\n  z.normalize_in_place();\n  Coord3Df x(m.m[0][0], m.m[0][1], m.m[0][2]); /* x-axis */\n  Coord3Df y(m.m[1][0], m.m[1][1], m.m[1][2]); /* y-axis */\n  float scale = x.length();\n  y = (z ^ x).normalize() * scale; /* rectify y */\n  x = (y ^ z).normalize() * scale; /* rectify x */\n  z *= scale;                      /* give z the correct length */\n  m.m[0][0] = x.x;\n  m.m[0][1] = x.y;\n  m.m[0][2] = x.z;\n  m.m[1][0] = y.x;\n  m.m[1][1] = y.y;\n  m.m[1][2] = y.z;\n  m.m[2][0] = z.x;\n  m.m[2][1] = z.y;\n  m.m[2][2] = z.z;\n}", "meta": {"hexsha": "621be5872050cc7fbc3a135e89d13952d83864b0", "size": 6743, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/blender/vr/intern/vr_math.cpp", "max_stars_repo_name": "sigmike/blender", "max_stars_repo_head_hexsha": "f7f4c42a71d5c69362d9ef0b757216accebf56f3", "max_stars_repo_licenses": ["Naumen", "Condor-1.1", "MS-PL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/blender/vr/intern/vr_math.cpp", "max_issues_repo_name": "sigmike/blender", "max_issues_repo_head_hexsha": "f7f4c42a71d5c69362d9ef0b757216accebf56f3", "max_issues_repo_licenses": ["Naumen", "Condor-1.1", "MS-PL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/blender/vr/intern/vr_math.cpp", "max_forks_repo_name": "sigmike/blender", "max_forks_repo_head_hexsha": "f7f4c42a71d5c69362d9ef0b757216accebf56f3", "max_forks_repo_licenses": ["Naumen", "Condor-1.1", "MS-PL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6936170213, "max_line_length": 93, "alphanum_fraction": 0.5742251223, "num_tokens": 2421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4661408589994101}}
{"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_QUADRANT_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_QUADRANT_HPP_INCLUDED\n#include <boost/simd/detail/overload.hpp>\n\n#include <boost/simd/meta/hierarchy/simd.hpp>\n#include <boost/simd/function/floor.hpp>\n#include <boost/simd/constant/four.hpp>\n#include <boost/simd/constant/quarter.hpp>\n#include <boost/simd/constant/three.hpp>\n#include <boost/simd/function/toint.hpp>\n#include <boost/simd/function/tofloat.hpp>\n\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  namespace bs = boost::simd;\n  BOOST_DISPATCH_OVERLOAD_IF(quadrant_\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 a = a0*Quarter<A0>();\n      return (a-floor(a))*Four<A0>();\n    }\n  };\n  BOOST_DISPATCH_OVERLOAD_IF(quadrant_\n                            , (typename A0, typename X)\n                            , (detail::is_native<X>)\n                            , bd::cpu_\n                            , bs::pack_<bd::single_<A0>, X>\n                            )\n  {\n    BOOST_FORCEINLINE A0 operator()( const A0& a0) const BOOST_NOEXCEPT\n    {\n\n      return tofloat(quadrant(toint(a0)));\n    }\n  };\n  BOOST_DISPATCH_OVERLOAD_IF( quadrant_\n                            , (typename A0, typename X)\n                            , (detail::is_native<X>)\n                            , bd::cpu_\n                            , bs::pack_< bd::integer_<A0>, X >\n                            )\n  {\n    BOOST_FORCEINLINE A0 operator()(A0 const& a0) const BOOST_NOEXCEPT\n    {\n      return a0&Three<A0>();\n    }\n  };\n} } }\n\n#endif\n\n", "meta": {"hexsha": "c2f72710a97272cbfcfe11516c872bebeea4822b", "size": 2253, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/simd/function/quadrant.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/quadrant.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/quadrant.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.1857142857, "max_line_length": 100, "alphanum_fraction": 0.5090989791, "num_tokens": 490, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390746, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4661408589994101}}
{"text": "// test_alg1.cpp - original U(N)->U(3) reduction implemented by LSU3shell\n// \n// License: BSD 2-Clause (https://opensource.org/licenses/BSD-2-Clause)\n//\n// Copyright (c) 2019, Daniel Langr\n// All rights reserved.\n//\n// Program implements the U(N) to U(3) the input irrep [f] specified by the HO level n, N=(n+1)*(n+2)/2, \n// and its number of twos, ones, and zeros read from the standard input.\n// For instance, for the input U(21) irrep [f] = [2,2,2,2,2,2,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0],\n// the user should provide the following numbers: 5 6 1 14.\n//\n// The program performs the U(N) to U(3) reduction and calculates the sum of the dimensions\n// of resulting U(3) irrpes multiplied by their level dimensionalities, and print it to the\n// standard output. For instance, for the input irrep specified above, the output should read:\n// U(3) irreps total dim = 2168999910\n//\n// This sum should be equal to dim[f], which can be calculated analytically with the support \n// of rational numbers. The program performs this calculcation as well if the Boost library \n// is available and uses its Boost.Rational sublibrary. Availabitliy of Boost is indicated by\n// users by definition of HAVE_BOOST preprocessor symbol. \n// For the input irrep [f] specified above, the program should first print out:\n// U(N) irrep dim = 2168999910\n\n#include <algorithm>\n#include <functional>\n#include <iostream>\n#include <iterator>\n#include <map>\n#include <stdexcept>\n#include <vector>\n\n#ifdef HAVE_BOOST\n#include <boost/rational.hpp>\n#endif\n\nnamespace U3 {\n   using LABELS = std::array<uint32_t, 3>;\n   using SPS = std::array<std::vector<uint32_t>, 3>;\n   enum { NZ, NX, NY };\n};\n\nnamespace UN {\n   using LABELS = std::vector<uint8_t>;\n   using BASIS_STATE_WEIGHT_VECTOR = std::vector<uint8_t>;\n   using U3MULT_LIST = std::map<U3::LABELS, uint32_t>;\n}\n\nenum { MULT, LM, MU, S2 };\n\nvoid Weight2U3Label(const UN::BASIS_STATE_WEIGHT_VECTOR& vWeights, const U3::SPS& ShellSPS,\n                    U3::LABELS& vU3Labels) {\n   vU3Labels[U3::NZ] =\n       std::inner_product(ShellSPS[U3::NZ].begin(), ShellSPS[U3::NZ].end(), vWeights.begin(), 0);\n   vU3Labels[U3::NX] =\n       std::inner_product(ShellSPS[U3::NX].begin(), ShellSPS[U3::NX].end(), vWeights.begin(), 0);\n   vU3Labels[U3::NY] =\n       std::inner_product(ShellSPS[U3::NY].begin(), ShellSPS[U3::NY].end(), vWeights.begin(), 0);\n}\n\nvoid GenerateU3Labels(const UN::LABELS& vGelfandParentRow, uint32_t uSumGelfandParentRow,\n                      const U3::SPS& ShellSPS, UN::BASIS_STATE_WEIGHT_VECTOR& vWeights,\n                      UN::U3MULT_LIST& mU3LabelsOccurance) {\n   size_t N = vGelfandParentRow.size() - 1;\n\n   std::vector<UN::LABELS> vvAllowedLabels;\n   UN::LABELS vGelfandRow(N);\n   std::vector<uint32_t> vElemsPerChange(N, 1);  // Fill with 1 cause vElemsPerChange[0] = 1;\n   std::vector<size_t> vNLabels(N);\n\n   // evaluate all allowed Gelfand patterns based on a parent Gelfand row\n   // (vGelfandParentRow) and store them in vvAllowedLabels\n   // iNAllowedCombinations is equal to the number of allowed Gelfand patterns\n   uint32_t iNAllowedCombinations = 1;\n   for (size_t i = 0; i < N; i++) {\n      uint32_t uLabelMin = std::min(vGelfandParentRow[i + 1], vGelfandParentRow[i]);\n      uint32_t uLabelMax = std::max(vGelfandParentRow[i + 1], vGelfandParentRow[i]);\n      UN::LABELS vLabels(uLabelMax - uLabelMin + 1);\n      std::iota(vLabels.begin(), vLabels.end(), uLabelMin);\n      vNLabels[i] = vLabels.size();\n      iNAllowedCombinations *= vNLabels[i];\n      vvAllowedLabels.push_back(std::move(vLabels));\n   }\n\n   for (size_t i = 1; i < N; i++) {\n      vElemsPerChange[i] = vElemsPerChange[i - 1] *\n                           vNLabels[i - 1];  // if i == 0 => vElemsPerChange[0]=1 since constructor\n   }\n\n   for (uint32_t index = 0; index < iNAllowedCombinations; index++) {\n      for (size_t i = 0; i < N; i++) {\n         size_t iElement = (index / vElemsPerChange[i]) % vNLabels[i];\n         vGelfandRow[i] = vvAllowedLabels[i][iElement];\n      }\n      uint32_t uSumGelfandRow = std::accumulate(vGelfandRow.begin(), vGelfandRow.end(), 0);\n      vWeights[N] = uSumGelfandParentRow - uSumGelfandRow;\n      if (N > 1) {  // this condition is due to n = 0 case when N = 0 and hence one wants to keep\n                    // vWeights[0] = uSumGelfandRow;\n         GenerateU3Labels(vGelfandRow, uSumGelfandRow, ShellSPS, vWeights, mU3LabelsOccurance);\n      } else {\n         if (N == 1) {\n            vWeights[0] = uSumGelfandRow;\n         }\n         U3::LABELS vU3Labels = {0, 0, 0};\n         Weight2U3Label(vWeights, ShellSPS, vU3Labels);\n         mU3LabelsOccurance[vU3Labels] += 1;\n      }\n   }\n}\n\nuint32_t GetMultiplicity(const U3::LABELS u3_labels, const UN::U3MULT_LIST& u3_mult_map) {\n   auto u3_mult = u3_mult_map.find(u3_labels);\n   assert(u3_mult != u3_mult_map.end());\n\n   uint32_t f1 = u3_labels[0], f2 = u3_labels[1], f3 = u3_labels[2];\n   uint32_t mult = u3_mult->second;\n\n   u3_mult = u3_mult_map.find({f1 + 1, f2 + 1, f3 - 2});\n   mult += (u3_mult == u3_mult_map.end()) ? 0 : u3_mult->second;\n\n   u3_mult = u3_mult_map.find({f1 + 2, f2 - 1, f3 - 1});\n   mult += (u3_mult == u3_mult_map.end()) ? 0 : u3_mult->second;\n\n   u3_mult = u3_mult_map.find({f1 + 2, f2, f3 - 2});\n   mult -= (u3_mult == u3_mult_map.end()) ? 0 : u3_mult->second;\n\n   u3_mult = u3_mult_map.find({f1 + 1, f2 - 1, f3});\n   mult -= (u3_mult == u3_mult_map.end()) ? 0 : u3_mult->second;\n\n   u3_mult = u3_mult_map.find({f1, f2 + 1, f3 - 1});\n   mult -= (u3_mult == u3_mult_map.end()) ? 0 : u3_mult->second;\n\n   return mult;\n}\n\nvoid GenerateU3SPS(int n, U3::SPS& ShellSPS) {\n   for (int k = 0; k <= n; k++) {\n      uint32_t nz = n - k;\n      for (int nx = k; nx >= 0; nx--) {\n         ShellSPS[U3::NX].push_back(nx);\n         ShellSPS[U3::NY].push_back(n - nz - nx);\n         ShellSPS[U3::NZ].push_back(nz);\n      }\n   }\n}\n\n#ifdef HAVE_BOOST\ntemplate <typename T>\nunsigned long dim(const T & irrep) {\n   const auto N = irrep.size();\n   boost::rational<unsigned long> result{1};\n   for (uint32_t l = 2; l <= N; l++)\n      for (uint32_t k = 1; k <= l - 1; k++)\n         result *= { irrep[k - 1] - irrep[l - 1] + l - k, l - k };\n\n   assert(result.denominator() == 1);\n   return result.numerator();\n}\n#endif\n\n// special case for U(3) irreps (does not require Boost rational numbers)\nunsigned long dim(const U3::LABELS & irrep) {\n   return (irrep[0] - irrep[1] + 1) * (irrep[0] - irrep[2] + 2) * (irrep[1] - irrep[2] + 1) / 2;\n}\n\n\nint main() {\n   unsigned long n;\n   unsigned short n2, n1, n0;\n   std::cin >> n >> n2 >> n1 >> n0;\n   unsigned long N = (n + 1) * (n + 2) / 2;\n\n   if ((n2 + n1 + n0) != N)\n      throw std::invalid_argument(\"Arguments mismatch!\");\n\n   U3::SPS ShellSPS;\n   GenerateU3SPS(n, ShellSPS);\n\n   UN::LABELS UNLabels(n2, 2);\n   std::fill_n(std::back_inserter(UNLabels), n1, 1);\n   std::fill_n(std::back_inserter(UNLabels), n0, 0);\n\n#ifdef HAVE_BOOST\n   std::cout << \"U(N) irrep dim = \" << dim(UNLabels) << std::endl;\n#endif\n\n   uint32_t sumUNLabels = std::accumulate(UNLabels.begin(), UNLabels.end(), 0);\n\n   UN::U3MULT_LIST mU3_mult;\n   UN::BASIS_STATE_WEIGHT_VECTOR Weight(UNLabels.size());\n\n   GenerateU3Labels(UNLabels, sumUNLabels, ShellSPS, Weight, mU3_mult);\n\n   unsigned long sum = 0;\n   for (const auto& u3labels_mult : mU3_mult) {\n      U3::LABELS U3Labels(u3labels_mult.first);\n\n      if (U3Labels[U3::NZ] >= U3Labels[U3::NX] && U3Labels[U3::NX] >= U3Labels[U3::NY]) \n         if (uint32_t u3_mult = GetMultiplicity(U3Labels, mU3_mult))\n            sum += u3_mult * dim(U3Labels);\n   }\n   std::cout << \"U(3) irreps total dim = \" << sum << std::endl;\n}\n", "meta": {"hexsha": "95cba17ea68ace7c644eb7d96834a9d14b973ee6", "size": 7605, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "alg1/test_alg1.cpp", "max_stars_repo_name": "kc9jud/UNtoU3", "max_stars_repo_head_hexsha": "999d12d73909c483a9dc92842badee515e814997", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-24T22:53:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-24T22:53:11.000Z", "max_issues_repo_path": "alg1/test_alg1.cpp", "max_issues_repo_name": "kc9jud/UNtoU3", "max_issues_repo_head_hexsha": "999d12d73909c483a9dc92842badee515e814997", "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": "alg1/test_alg1.cpp", "max_forks_repo_name": "kc9jud/UNtoU3", "max_forks_repo_head_hexsha": "999d12d73909c483a9dc92842badee515e814997", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-25T04:34:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-25T04:34:59.000Z", "avg_line_length": 37.2794117647, "max_line_length": 105, "alphanum_fraction": 0.6382642998, "num_tokens": 2547, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145998, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4661101214785006}}
{"text": "/* vim: set tabstop=4 expandtab shiftwidth=4 softtabstop=4: */\n\n/**\n * \\file libs/numeric/ublasx/any.cpp\n * \\brief Test the \\c any operation.\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n *\n * <hr/>\n *\n * Copyright (c) 2010, Marco Guazzone\n * \n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#include <boost/numeric/ublas/fwd.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_expression.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/vector_expression.hpp>\n#include <boost/numeric/ublasx/operation/any.hpp>\n#include <functional>\n#include <iostream>\n#include \"libs/numeric/ublasx/test/utils.hpp\"\n\n\nnamespace ublas = ::boost::numeric::ublas;\nnamespace ublasx = ::boost::numeric::ublasx;\n\n\nBOOST_UBLASX_TEST_DEF( test_vector_container )\n{\n    BOOST_UBLASX_DEBUG_TRACE( \"TEST Vector Container\" );\n\n    typedef double value_type;\n    typedef ublas::vector<value_type> vector_type;\n    typedef ublas::zero_vector<value_type> zero_vector_type;\n\n    vector_type v(5);\n\n    v(0) = 0.555950;\n    v(1) = 0.108929;\n    v(2) = 0.948014;\n    v(3) = 0.023787;\n    v(4) = 1.023787;\n\n    zero_vector_type z(5);\n\n    value_type val(0);\n    bool expect(false);\n    bool res(false);\n\n\n    // any(z)\n    expect = false;\n    res = ublasx::any(z);\n    BOOST_UBLASX_DEBUG_TRACE( \"any(\" << z << \") = \" << ::std::boolalpha << res << \" ==> \" << expect );\n    BOOST_UBLASX_TEST_CHECK( res == expect );\n\n    // any(v)\n    expect = true;\n    res = ublasx::any(v);\n    BOOST_UBLASX_DEBUG_TRACE( \"any(\" << v << \") = \" << ::std::boolalpha << res << \" ==> \" << expect );\n    BOOST_UBLASX_TEST_CHECK( res == expect );\n\n    // any(v, > .5)\n    val = 0.5;\n    expect = true;\n    res = ublasx::any(v, ::std::bind2nd(::std::greater<value_type>(), val));\n    BOOST_UBLASX_DEBUG_TRACE( \"any(\" << v << \", > \" << val << \") = \" << ::std::boolalpha << res << \" ==> \" << expect );\n    BOOST_UBLASX_TEST_CHECK( res == expect );\n\n    // any(v, > 1.5)\n    val = 1.5;\n    expect = false;\n    res = ublasx::any(v, ::std::bind2nd(::std::greater<value_type>(), val));\n    BOOST_UBLASX_DEBUG_TRACE( \"any(\" << v << \", > \" << val << \") = \" << ::std::boolalpha << res << \" ==> \" << expect );\n    BOOST_UBLASX_TEST_CHECK( res == expect );\n}\n\n\nBOOST_UBLASX_TEST_DEF( test_vector_expression )\n{\n    BOOST_UBLASX_DEBUG_TRACE( \"TEST Vector Expression\" );\n\n    typedef double value_type;\n    typedef ublas::vector<value_type> vector_type;\n\n    vector_type v(5);\n\n    v(0) = 0.555950;\n    v(1) = 0.108929;\n    v(2) = 0.948014;\n    v(3) = 0.023787;\n    v(4) = 1.023787;\n\n    value_type val(0);\n    bool expect(false);\n    bool res(false);\n\n\n    // any(-v)\n    expect = true;\n    res = ublasx::any(-v);\n    BOOST_UBLASX_DEBUG_TRACE( \"any(\" << -v << \") = \" << ::std::boolalpha << res << \" ==> \" << expect );\n    BOOST_UBLASX_TEST_CHECK( res == expect );\n\n    // any(-v, > -.5)\n    val = -0.5;\n    expect = true;\n    res = ublasx::any(-v, ::std::bind2nd(::std::greater<value_type>(), val));\n    BOOST_UBLASX_DEBUG_TRACE( \"any(\" << -v << \", > \" << val << \") = \" << ::std::boolalpha << res << \" ==> \" << expect );\n    BOOST_UBLASX_TEST_CHECK( res == expect );\n\n    // any(-v, > -.0)\n    val = 0;\n    expect = false;\n    res = ublasx::any(-v, ::std::bind2nd(::std::greater<value_type>(), val));\n    BOOST_UBLASX_DEBUG_TRACE( \"any(\" << -v << \", > \" << val << \") = \" << ::std::boolalpha << res << \" ==> \" << expect );\n    BOOST_UBLASX_TEST_CHECK( res == expect );\n}\n\n\nBOOST_UBLASX_TEST_DEF( test_vector_reference )\n{\n    BOOST_UBLASX_DEBUG_TRACE( \"TEST Vector Reference\" );\n\n    typedef double value_type;\n    typedef ublas::vector<value_type> vector_type;\n    typedef ublas::vector_reference<vector_type> vector_reference_type;\n\n    vector_type v(5);\n\n    v(0) = 0.555950;\n    v(1) = 0.108929;\n    v(2) = 0.948014;\n    v(3) = 0.023787;\n    v(4) = 1.023787;\n\n\n    value_type val(0);\n    bool expect(false);\n    bool res(false);\n\n    // any(ref(v))\n    expect = true;\n    res = ublasx::any(vector_reference_type(v));\n    BOOST_UBLASX_DEBUG_TRACE( \"any(reference(\" << vector_reference_type(v) << \")) = \" << ::std::boolalpha << res << \" ==> \" << expect );\n    BOOST_UBLASX_TEST_CHECK( res == expect );\n\n    // any(ref(v), > .5)\n    val = 0.5;\n    expect = true;\n    res = ublasx::any(vector_reference_type(v), ::std::bind2nd(::std::greater<value_type>(), val));\n    BOOST_UBLASX_DEBUG_TRACE( \"any(reference(\" << vector_reference_type(v) << \"), > \" << val << \") = \" << ::std::boolalpha << res << \" ==> \" << expect );\n    BOOST_UBLASX_TEST_CHECK( res == expect );\n\n    // any(ref(v), > 1.5)\n    val = 1.5;\n    expect = false;\n    res = ublasx::any(vector_reference_type(v), ::std::bind2nd(::std::greater<value_type>(), val));\n    BOOST_UBLASX_DEBUG_TRACE( \"any(reference(\" << vector_reference_type(v) << \"), > \" << val << \") = \" << ::std::boolalpha << res << \" ==> \" << expect );\n    BOOST_UBLASX_TEST_CHECK( res == expect );\n}\n\n\nBOOST_UBLASX_TEST_DEF( test_row_major_matrix_container )\n{\n    BOOST_UBLASX_DEBUG_TRACE( \"TEST Row-major Matrix Container\" );\n\n    typedef double value_type;\n    typedef ublas::matrix<value_type, ublas::row_major> matrix_type;\n    typedef ublas::zero_matrix<value_type> zero_matrix_type;\n\n    matrix_type A(5,4);\n\n    A(0,0) = 0.555950; A(0,1) = 0.274690; A(0,2) = 0.540605; A(0,3) = 0.798938;\n    A(1,0) = 0.108929; A(1,1) = 0.830123; A(1,2) = 0.891726; A(1,3) = 0.895283;\n    A(2,0) = 0.948014; A(2,1) = 0.973234; A(2,2) = 0.216504; A(2,3) = 0.883152;\n    A(3,0) = 0.023787; A(3,1) = 0.675382; A(3,2) = 0.231751; A(3,3) = 0.450332;\n    A(4,0) = 1.023787; A(4,1) = 1.675382; A(4,2) = 1.231751; A(4,3) = 1.450332;\n\n    zero_matrix_type Z(5, 4);\n\n\n    value_type val(0);\n    bool expect(false);\n    bool res(false);\n\n\n    // any(Z)\n    expect = false;\n    res = ublasx::any(Z);\n    BOOST_UBLASX_DEBUG_TRACE( \"any(\" << Z << \") = \" << ::std::boolalpha << res << \" ==> \" << expect );\n    BOOST_UBLASX_TEST_CHECK( res == expect );\n\n    // any(A)\n    expect = true;\n    res = ublasx::any(A);\n    BOOST_UBLASX_DEBUG_TRACE( \"any(\" << A << \") = \" << ::std::boolalpha << res << \" ==> \" << expect );\n    BOOST_UBLASX_TEST_CHECK( res == expect );\n\n    // any(A, > .5)\n    val = 0.5;\n    expect = true;\n    res = ublasx::any(A, ::std::bind2nd(::std::greater<value_type>(), val));\n    BOOST_UBLASX_DEBUG_TRACE( \"any(\" << A << \", > \" << val << \") = \" << ::std::boolalpha << res << \" ==> \" << expect );\n    BOOST_UBLASX_TEST_CHECK( res == expect );\n\n    // any(A, > 2.5)\n    val = 2.5;\n    expect = false;\n    res = ublasx::any(A, ::std::bind2nd(::std::greater<value_type>(), val));\n    BOOST_UBLASX_DEBUG_TRACE( \"any(\" << A << \", > \" << val << \") = \" << ::std::boolalpha << res << \" ==> \" << expect );\n    BOOST_UBLASX_TEST_CHECK( res == expect );\n}\n\n\nBOOST_UBLASX_TEST_DEF( test_col_major_matrix_container )\n{\n    BOOST_UBLASX_DEBUG_TRACE( \"TEST Column-major Matrix Container\" );\n\n    typedef double value_type;\n    typedef ublas::matrix<value_type, ublas::column_major> matrix_type;\n\n    matrix_type A(5,4);\n\n    A(0,0) = 0.555950; A(0,1) = 0.274690; A(0,2) = 0.540605; A(0,3) = 0.798938;\n    A(1,0) = 0.108929; A(1,1) = 0.830123; A(1,2) = 0.891726; A(1,3) = 0.895283;\n    A(2,0) = 0.948014; A(2,1) = 0.973234; A(2,2) = 0.216504; A(2,3) = 0.883152;\n    A(3,0) = 0.023787; A(3,1) = 0.675382; A(3,2) = 0.231751; A(3,3) = 0.450332;\n    A(4,0) = 1.023787; A(4,1) = 1.675382; A(4,2) = 1.231751; A(4,3) = 1.450332;\n\n    value_type val(0);\n    bool expect(false);\n    bool res(false);\n\n\n    // any(A)\n    expect = true;\n    res = ublasx::any(A);\n    BOOST_UBLASX_DEBUG_TRACE( \"any(\" << A << \") = \" << ::std::boolalpha << res << \" ==> \" << expect );\n    BOOST_UBLASX_TEST_CHECK( res == expect );\n\n    // any(A, > .5)\n    val = 0.5;\n    expect = true;\n    res = ublasx::any(A, ::std::bind2nd(::std::greater<value_type>(), val));\n    BOOST_UBLASX_DEBUG_TRACE( \"any(\" << A << \", > \" << val << \") = \" << ::std::boolalpha << res << \" ==> \" << expect );\n    BOOST_UBLASX_TEST_CHECK( res == expect );\n\n    // any(A, > 2.5)\n    val = 2.5;\n    expect = false;\n    res = ublasx::any(A, ::std::bind2nd(::std::greater<value_type>(), val));\n    BOOST_UBLASX_DEBUG_TRACE( \"any(\" << A << \", > \" << val << \") = \" << ::std::boolalpha << res << \" ==> \" << expect );\n    BOOST_UBLASX_TEST_CHECK( res == expect );\n}\n\n\nBOOST_UBLASX_TEST_DEF( test_matrix_expression )\n{\n    BOOST_UBLASX_DEBUG_TRACE( \"TEST Matrix Expression\" );\n\n    typedef double value_type;\n    typedef ublas::matrix<value_type> matrix_type;\n\n    matrix_type A(5,4);\n\n    A(0,0) = 0.555950; A(0,1) = 0.274690; A(0,2) = 0.540605; A(0,3) = 0.798938;\n    A(1,0) = 0.108929; A(1,1) = 0.830123; A(1,2) = 0.891726; A(1,3) = 0.895283;\n    A(2,0) = 0.948014; A(2,1) = 0.973234; A(2,2) = 0.216504; A(2,3) = 0.883152;\n    A(3,0) = 0.023787; A(3,1) = 0.675382; A(3,2) = 0.231751; A(3,3) = 0.450332;\n    A(4,0) = 1.023787; A(4,1) = 1.675382; A(4,2) = 1.231751; A(4,3) = 1.450332;\n\n    value_type val(0);\n    bool expect(false);\n    bool res(false);\n\n\n    // any(A')\n    expect = true;\n    res = ublasx::any(ublas::trans(A));\n    BOOST_UBLASX_DEBUG_TRACE( \"any(\" << A << \"') = \" << ::std::boolalpha << res << \" ==> \" << expect );\n    BOOST_UBLASX_TEST_CHECK( res == expect );\n\n    // any(A', > .5)\n    val = 0.5;\n    expect = true;\n    res = ublasx::any(ublas::trans(A), ::std::bind2nd(::std::greater<value_type>(), val));\n    BOOST_UBLASX_DEBUG_TRACE( \"any(\" << A << \"', > \" << val << \") = \" << ::std::boolalpha << res << \" ==> \" << expect );\n    BOOST_UBLASX_TEST_CHECK( res == expect );\n\n    // any(A', > 2.5)\n    val = 2.5;\n    expect = false;\n    res = ublasx::any(ublas::trans(A), ::std::bind2nd(::std::greater<value_type>(), val));\n    BOOST_UBLASX_DEBUG_TRACE( \"any(\" << A << \"', > \" << val << \") = \" << ::std::boolalpha << res << \" ==> \" << expect );\n    BOOST_UBLASX_TEST_CHECK( res == expect );\n}\n\n\nBOOST_UBLASX_TEST_DEF( test_matrix_reference )\n{\n    BOOST_UBLASX_DEBUG_TRACE( \"TEST Matrix Reference\" );\n\n    typedef double value_type;\n    typedef ublas::matrix<value_type> matrix_type;\n    typedef ublas::matrix_reference<matrix_type> matrix_reference_type;\n\n    matrix_type A(5,4);\n\n    A(0,0) = 0.555950; A(0,1) = 0.274690; A(0,2) = 0.540605; A(0,3) = 0.798938;\n    A(1,0) = 0.108929; A(1,1) = 0.830123; A(1,2) = 0.891726; A(1,3) = 0.895283;\n    A(2,0) = 0.948014; A(2,1) = 0.973234; A(2,2) = 0.216504; A(2,3) = 0.883152;\n    A(3,0) = 0.023787; A(3,1) = 0.675382; A(3,2) = 0.231751; A(3,3) = 0.450332;\n    A(4,0) = 1.023787; A(4,1) = 1.675382; A(4,2) = 1.231751; A(4,3) = 1.450332;\n\n    value_type val(0);\n    bool expect(false);\n    bool res(false);\n\n\n    // any(ref(A))\n    expect = true;\n    res = ublasx::any(matrix_reference_type(A));\n    BOOST_UBLASX_DEBUG_TRACE( \"any(reference(\" << A << \")) = \" << ::std::boolalpha << res << \" ==> \" << expect );\n    BOOST_UBLASX_TEST_CHECK( res == expect );\n\n    // any(ref(A), > .5)\n    val = 0.5;\n    expect = true;\n    res = ublasx::any(matrix_reference_type(A), ::std::bind2nd(::std::greater<value_type>(), val));\n    BOOST_UBLASX_DEBUG_TRACE( \"any(reference(\" << A << \"), > \" << val << \") = \" << ::std::boolalpha << res << \" ==> \" << expect );\n    BOOST_UBLASX_TEST_CHECK( res == expect );\n\n    // any(ref(A), > 2.5)\n    val = 2.5;\n    expect = false;\n    res = ublasx::any(matrix_reference_type(A), ::std::bind2nd(::std::greater<value_type>(), val));\n    BOOST_UBLASX_DEBUG_TRACE( \"any(reference(\" << A << \"), > \" << val << \") = \" << ::std::boolalpha << res << \" ==> \" << expect );\n    BOOST_UBLASX_TEST_CHECK( res == expect );\n}\n\n\nint main()\n{\n    BOOST_UBLASX_DEBUG_TRACE(\"Test Suite: 'any' operation\");\n\n    BOOST_UBLASX_TEST_BEGIN();\n\n    BOOST_UBLASX_TEST_DO( test_vector_container );\n    BOOST_UBLASX_TEST_DO( test_vector_expression );\n    BOOST_UBLASX_TEST_DO( test_vector_reference );\n    BOOST_UBLASX_TEST_DO( test_row_major_matrix_container );\n    BOOST_UBLASX_TEST_DO( test_col_major_matrix_container );\n    BOOST_UBLASX_TEST_DO( test_matrix_expression );\n    BOOST_UBLASX_TEST_DO( test_matrix_reference );\n\n    BOOST_UBLASX_TEST_END();\n}\n", "meta": {"hexsha": "a7f7f2a63d880a0efb605394e3304c5543fe5de0", "size": 12204, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/ublasx/test/any.cpp", "max_stars_repo_name": "sguazt/boost-ublasx", "max_stars_repo_head_hexsha": "21c9b393d33a6ec2a8071ba8d48680073d766409", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2016-05-14T11:08:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-05T14:22:20.000Z", "max_issues_repo_path": "libs/numeric/ublasx/test/any.cpp", "max_issues_repo_name": "sguazt/boost-ublasx", "max_issues_repo_head_hexsha": "21c9b393d33a6ec2a8071ba8d48680073d766409", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-12-28T18:36:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-06T11:28:51.000Z", "max_forks_repo_path": "libs/numeric/ublasx/test/any.cpp", "max_forks_repo_name": "sguazt/boost-ublasx", "max_forks_repo_head_hexsha": "21c9b393d33a6ec2a8071ba8d48680073d766409", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-12-23T02:53:27.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-23T02:53:27.000Z", "avg_line_length": 33.4356164384, "max_line_length": 153, "alphanum_fraction": 0.5839888561, "num_tokens": 4318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6150878555160666, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.46611011811398273}}
{"text": "#ifndef STAN_MATH_REV_MAT_FUN_VARIANCE_HPP\n#define STAN_MATH_REV_MAT_FUN_VARIANCE_HPP\n\n#include <boost/math/tools/promotion.hpp>\n#include <stan/math/prim/mat/fun/Eigen.hpp>\n#include <stan/math/prim/mat/fun/mean.hpp>\n#include <stan/math/rev/core.hpp>\n#include <stan/math/prim/arr/err/check_nonzero_size.hpp>\n#include <vector>\n\nnamespace stan {\nnamespace math {\n\nnamespace {\n\ninline var calc_variance(size_t size, const var* dtrs) {\n  vari** varis = reinterpret_cast<vari**>(\n      ChainableStack::instance().memalloc_.alloc(size * sizeof(vari*)));\n  for (size_t i = 0; i < size; ++i)\n    varis[i] = dtrs[i].vi_;\n  double sum = 0.0;\n  for (size_t i = 0; i < size; ++i)\n    sum += dtrs[i].vi_->val_;\n  double mean = sum / size;\n  double sum_of_squares = 0;\n  for (size_t i = 0; i < size; ++i) {\n    double diff = dtrs[i].vi_->val_ - mean;\n    sum_of_squares += diff * diff;\n  }\n  double variance = sum_of_squares / (size - 1);\n  double* partials = reinterpret_cast<double*>(\n      ChainableStack::instance().memalloc_.alloc(size * sizeof(double)));\n  double two_over_size_m1 = 2 / (size - 1);\n  for (size_t i = 0; i < size; ++i)\n    partials[i] = two_over_size_m1 * (dtrs[i].vi_->val_ - mean);\n  return var(new stored_gradient_vari(variance, size, varis, partials));\n}\n\n}  // namespace\n\n/**\n * Return the sample variance of the specified standard\n * vector.  Raise domain error if size is not greater than zero.\n *\n * @param[in] v a vector\n * @return sample variance of specified vector\n */\ninline var variance(const std::vector<var>& v) {\n  check_nonzero_size(\"variance\", \"v\", v);\n  if (v.size() == 1)\n    return 0;\n  return calc_variance(v.size(), &v[0]);\n}\n\n/*\n * Return the sample variance of the specified vector, row vector,\n * or matrix.  Raise domain error if size is not greater than\n * zero.\n *\n * @tparam R number of rows\n * @tparam C number of columns\n * @param[in] m input matrix\n * @return sample variance of specified matrix\n */\ntemplate <int R, int C>\nvar variance(const Eigen::Matrix<var, R, C>& m) {\n  check_nonzero_size(\"variance\", \"m\", m);\n  if (m.size() == 1)\n    return 0;\n  return calc_variance(m.size(), &m(0));\n}\n\n}  // namespace math\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "4b2b73d8926e2fc9b3dec70f3ac445d5b75e4c7a", "size": 2185, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/rev/mat/fun/variance.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/variance.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/variance.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": 28.75, "max_line_length": 73, "alphanum_fraction": 0.671395881, "num_tokens": 644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746407, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4661101147494646}}
{"text": "//==================================================================================================\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#include <simd_test.hpp>\n#include <boost/simd/function/sincosd.hpp>\n#include <boost/simd/pack.hpp>\n#include <boost/simd/function/std.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/minf.hpp>\n#include <boost/simd/constant/nan.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/mone.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/constant/mzero.hpp>\n#include <boost/simd/function/sind.hpp>\n#include <boost/simd/function/cosd.hpp>\n\nnamespace bs = boost::simd;\n\ntemplate <typename T, std::size_t N, typename Env>\nvoid test(Env& runtime)\n{\n  using p_t = bs::pack<T, N>;\n\n  T a1[N], c[N], s[N];\n  for(std::size_t i = 0; i < N; ++i)\n  {\n    a1[i] = (i%2) ? T(i*27) : -T(i*27);\n    std::tie(s[i], c[i])= bs::sincosd(a1[i]) ;\n  }\n\n  p_t aa1(&a1[0], &a1[0]+N);\n  p_t ss (&s[0], &s[0]+N);\n  p_t cc (&c[0], &c[0]+N);\n  p_t ss1, cc1;\n  std::tie(ss1, cc1)= bs::sincosd(aa1);\n\n  STF_ULP_EQUAL(ss1, ss, 0.5);\n  STF_ULP_EQUAL(cc1, cc, 0.5);\n}\n\nSTF_CASE_TPL(\"Check sincosd on pack\" , STF_IEEE_TYPES)\n{\n  static const std::size_t N = bs::pack<T>::static_size;\n\n  test<T, N>(runtime);\n  test<T, N/2>(runtime);\n  test<T, N*2>(runtime);\n}\n\ntemplate <typename T, std::size_t N, typename Env>\nvoid testr(Env& runtime)\n{\n  using p_t = bs::pack<T, N>;\n\n  T a1[N], c[N], s[N];\n  for(std::size_t i = 0; i < N; ++i)\n  {\n    a1[i] = ((i%2) ? T(i) : -T(i))*T(45.0)/N;\n    std::tie(s[i], c[i])= bs::restricted_(bs::sincosd)(a1[i]);\n  }\n\n  p_t aa1(&a1[0], &a1[0]+N);\n  p_t ss (&s[0], &s[0]+N);\n  p_t cc (&c[0], &c[0]+N);\n  p_t ss1, cc1;\n  std::tie(ss1, cc1)= bs::restricted_(bs::sincosd)(aa1);\n\n  STF_ULP_EQUAL(ss1, ss,0.5);\n  STF_ULP_EQUAL(cc1, cc,0.5);\n}\n\nSTF_CASE_TPL(\"Check restricted sincosd on pack\" , STF_IEEE_TYPES)\n{\n  static const std::size_t N = bs::pack<T>::static_size;\n\n  testr<T, N>(runtime);\n  testr<T, N/2>(runtime);\n  testr<T, N*2>(runtime);\n}\n\n\nSTF_CASE_TPL (\" sincosd\",  STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using p_t = bs::pack<T>;\n\n  using bs::sincosd;\n  p_t a[] = {bs::Zero<p_t>(), bs::One<p_t>(), p_t(120), p_t(180),\n           p_t(90), bs::Inf<p_t>(), bs::Minf<p_t>(), bs::Nan<p_t>()};\n  size_t N =  sizeof(a)/sizeof(p_t);\n\n  STF_EXPR_IS( (sincosd(p_t()))\n             , (std::pair<p_t,p_t>)\n             );\n\n  {\n    for(size_t i=0; i < N; ++i)\n    {\n      std::pair<p_t,p_t> p = sincosd(a[i]);\n      STF_IEEE_EQUAL(p.first,  bs::sind(a[i]));\n      STF_IEEE_EQUAL(p.second, bs::cosd(a[i]));\n      std::pair<p_t,p_t> q = bs::restricted_(sincosd)(a[i]);\n      STF_IEEE_EQUAL(q.first,  bs::restricted_(bs::sind)(a[i]));\n      STF_IEEE_EQUAL(q.second, bs::restricted_(bs::cosd)(a[i]));\n    }\n  }\n}\n\ntemplate <typename T, std::size_t N, typename Env>\nvoid testc(Env& runtime)\n{\n  namespace bst = bs::tag;\n  using p_t = bs::pack<T, N>;\n\n  T a1[N], c[N], s[N];\n  for(std::size_t i = 0; i < N; ++i)\n  {\n    a1[i] = ((i%2) ? T(i) : -T(i))*T(45.0)/N;\n    std::tie(s[i], c[i])= bs::sincosd(a1[i], bst::clipped_medium_);\n  }\n\n  p_t aa1(&a1[0], &a1[0]+N);\n  p_t ss (&s[0], &s[0]+N);\n  p_t cc (&c[0], &c[0]+N);\n  p_t ss1, cc1;\n  std::tie(ss1, cc1)= bs::sincosd(aa1, bst::clipped_medium_);\n\n  STF_ULP_EQUAL(ss1, ss,0.5);\n  STF_ULP_EQUAL(cc1, cc,0.5);\n}\n\nSTF_CASE_TPL(\"Check clipped sincosd on pack\" , STF_IEEE_TYPES)\n{\n  static const std::size_t N = bs::pack<T>::static_size;\n\n  testc<T, N>(runtime);\n  testc<T, N/2>(runtime);\n  testc<T, N*2>(runtime);\n}\n", "meta": {"hexsha": "82fe39b4d30f5a143170a802b61f39cb701d093c", "size": 3830, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/simd/sincosd.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": "test/function/simd/sincosd.cpp", "max_issues_repo_name": "remymuller/boost.simd", "max_issues_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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/function/simd/sincosd.cpp", "max_forks_repo_name": "remymuller/boost.simd", "max_forks_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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": 26.0544217687, "max_line_length": 100, "alphanum_fraction": 0.5660574413, "num_tokens": 1403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.46611011474946457}}
{"text": "\n#include \"gtest/gtest.h\"\n#include \"buddy/bdd.h\"\n\n// ::std\n#include <iostream>\n#include <vector>\n#include <utility>\n#include <limits>\n#include <sstream>\n#include <string>\n#include <cstdlib>\n#include <map>\n\n#include <boost/cast.hpp>\n\n#include <boost/static_assert.hpp>\n\n// ::wali::domains::binrel\n#include \"wali/domains/binrel/BinRel.hpp\"\n#include \"wali/domains/binrel/nwa_detensor.hpp\"\n#include \"wali/domains/binrel/ProgramBddContext.hpp\"\n\n\nusing namespace std;\nusing namespace wali;\nusing namespace wali::domains::binrel;\nusing namespace wali::domains::binrel::details;\n#if (NWA_DETENSOR == 1)\nnamespace\n{\n  TEST(Nwa_detensor, paperExample){\n    program_bdd_context_t brm = new ProgramBddContext();\n    map<string, int> vars;\n    vars[\"x1\"] = 2;\n    vars[\"x2\"] = 2;\n    brm->setIntVars(vars);\n\n    bdd b = brm->Assign(\"x1\", brm->Not(brm->From(\"x1\")));\n    binrel_t M = new BinRel(brm.get_ptr(), b);\n    binrel_t eye = boost::polymorphic_downcast<BinRel*>(M->one().get_ptr());\n    binrel_t s = boost::polymorphic_downcast<BinRel*>(((M->tensor(M.get_ptr()))->combine(eye->tensor(eye.get_ptr()).get_ptr())).get_ptr());\n    bdd z = s->getBdd();\n    //bdd_fnprintdot_levels(\"mtmpiti.dot\", z);\n    binrel_t x = boost::polymorphic_downcast<BinRel*>(s->detensorTranspose().get_ptr());\n    z = x->getBdd();\n    ASSERT_TRUE(x->equal(x->one().get_ptr()));\n    //bdd_fnprintdot_levels(\"detensored.dot\", z);\n\n    //b = brm->Assume(brm->From(\"x1\"), brm->From(\"x1\"));\n    //bdd_fnprintdot_levels(\"id.dot\", b);\n  }\n\n  TEST(Nwa_detensor, alltrue)\n  {\n    program_bdd_context_t brm = new ProgramBddContext();\n    map<string, int> vars;\n    vars[\"x1\"] = 2;\n    vars[\"x2\"] = 2;\n    vars[\"x3\"] = 2;\n    brm->setIntVars(vars);\n    sem_elem_tensor_t b1 = new BinRel(brm.get_ptr(), bddtrue);\n    sem_elem_tensor_t b2 = new BinRel(brm.get_ptr(), bddtrue);\n    sem_elem_tensor_t b3 = b2->transpose();\n    sem_elem_tensor_t b4 = b3->tensor(b1.get_ptr());\n    sem_elem_tensor_t b5 = b4->detensorTranspose();\n    sem_elem_tensor_t b6 = boost::polymorphic_downcast<SemElemTensor*>(b2->extend(boost::polymorphic_downcast<SemElem*>(b1.get_ptr())).get_ptr());\n    ASSERT_TRUE(b6->equal(b5));\n  }\n\n  TEST(Nwa_detensor, failing1)\n  {\n    program_bdd_context_t brm = new ProgramBddContext();\n    map<string, int> vars;\n    vars[\"x1\"] = 2;\n    vars[\"x2\"] = 2;\n    vars[\"x3\"] = 2;\n    brm->setIntVars(vars);\n    bdd b = brm->setPost(\"x2\") & brm->setPre(\"x3\") & brm->unsetPost(\"x3\");\n    sem_elem_tensor_t b1 = new BinRel(brm.get_ptr(), b);\n    sem_elem_tensor_t b2 = new BinRel(brm.get_ptr(), b);\n    sem_elem_tensor_t b3 = b2->transpose();\n    sem_elem_tensor_t b4 = b3->tensor(b1.get_ptr());\n    sem_elem_tensor_t b5 = b4->detensorTranspose();\n    sem_elem_tensor_t b6 = boost::polymorphic_downcast<SemElemTensor*>(b2->extend(boost::polymorphic_downcast<SemElem*>(b1.get_ptr())).get_ptr());\n    ASSERT_TRUE(b6->equal(b5));\n  }\n\n  TEST(Nwa_detensor, smallRandom)\n  {\n    program_bdd_context_t brm = new ProgramBddContext();\n    map<string, int> vars;\n    vars[\"x1\"] = 2;\n    vars[\"x2\"] = 2;\n    vars[\"x3\"] = 2;\n    vars[\"x4\"] = 2;\n    vars[\"x5\"] = 2;\n    brm->setIntVars(vars);\n    for(unsigned i =0; i < 1000; ++i){\n      sem_elem_tensor_t b1 = new BinRel(brm.get_ptr(), brm->tGetRandomTransformer(false, 0));\n      sem_elem_tensor_t b2 = new BinRel(brm.get_ptr(), brm->tGetRandomTransformer(false, 0));\n      sem_elem_tensor_t b3 = b2->transpose();\n      sem_elem_tensor_t b4 = b3->tensor(b1.get_ptr());\n      sem_elem_tensor_t b5 = b4->detensorTranspose();\n      sem_elem_tensor_t b6 = boost::polymorphic_downcast<SemElemTensor*>(b2->extend(boost::polymorphic_downcast<SemElem*>(b1.get_ptr())).get_ptr());\n      ASSERT_TRUE(b6->equal(b5));\n    }\n  }\n\n}\n#endif\n// Yo, Emacs!\n// Local Variables:\n//   c-file-style: \"ellemtel\"\n//   c-basic-offset: 2\n// End:\n", "meta": {"hexsha": "d69a772520592b964fb138897f69c5a9dc2b64d1", "size": 3822, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tests/unit-tests/Source/AddOns/Domains/binrel/nwa_detensor.cpp", "max_stars_repo_name": "jusito/WALi-OpenNWA", "max_stars_repo_head_hexsha": "2bb4aca02c5a5d444fd038e8aa3eecd7d1ccbb99", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2015-03-07T17:25:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-04T20:17:00.000Z", "max_issues_repo_path": "Tests/unit-tests/Source/AddOns/Domains/binrel/nwa_detensor.cpp", "max_issues_repo_name": "jusito/WALi-OpenNWA", "max_issues_repo_head_hexsha": "2bb4aca02c5a5d444fd038e8aa3eecd7d1ccbb99", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-03-03T05:58:55.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-03T12:26:10.000Z", "max_forks_repo_path": "Tests/unit-tests/Source/AddOns/Domains/binrel/nwa_detensor.cpp", "max_forks_repo_name": "jusito/WALi-OpenNWA", "max_forks_repo_head_hexsha": "2bb4aca02c5a5d444fd038e8aa3eecd7d1ccbb99", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2015-09-25T17:44:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-18T18:25:38.000Z", "avg_line_length": 32.6666666667, "max_line_length": 148, "alphanum_fraction": 0.6614338043, "num_tokens": 1219, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.46611011474946457}}
{"text": "/*\n * NormalVectorsFilter.cpp\n *\n *  Created on: May 05, 2015\n *      Author: Peter Fankhauser, Martin Wermelinger\n *   Institute: ETH Zurich, ANYbotics\n */\n\n#include <grid_map_filters/NormalVectorsFilter.hpp>\n\n#include <pluginlib/class_list_macros.h>\n#include <grid_map_core/grid_map_core.hpp>\n\n#include <Eigen/Dense>\n#include <stdexcept>\n\nusing namespace filters;\n\nnamespace grid_map {\n\ntemplate <typename T>\nNormalVectorsFilter<T>::NormalVectorsFilter() : method_(Method::Raster), estimationRadius_(0.0) {}\n\ntemplate <typename T>\nNormalVectorsFilter<T>::~NormalVectorsFilter() {}\n\ntemplate <typename T>\nbool NormalVectorsFilter<T>::configure() {\n  if (!FilterBase<T>::getParam(std::string(\"radius\"), estimationRadius_)) {\n    ROS_DEBUG(\"Normal vectors filter did not find parameter `radius`.\");\n    method_ = Method::Raster;\n  } else {\n    method_ = Method::Area;\n    if (estimationRadius_ < 0.0) {\n      ROS_ERROR(\"Normal vectors filter estimation radius must be greater than zero.\");\n      return false;\n    }\n    ROS_DEBUG(\"Normal vectors estimation radius = %f\", estimationRadius_);\n  }\n\n  std::string normalVectorPositiveAxis;\n  if (!FilterBase<T>::getParam(std::string(\"normal_vector_positive_axis\"), normalVectorPositiveAxis)) {\n    ROS_ERROR(\"Normal vectors filter did not find parameter `normal_vector_positive_axis`.\");\n    return false;\n  }\n  if (normalVectorPositiveAxis == \"z\") {\n    normalVectorPositiveAxis_ = Vector3::UnitZ();\n  } else if (normalVectorPositiveAxis == \"y\") {\n    normalVectorPositiveAxis_ = Vector3::UnitY();\n  } else if (normalVectorPositiveAxis == \"x\") {\n    normalVectorPositiveAxis_ = Vector3::UnitX();\n  } else {\n    ROS_ERROR(\"The normal vector positive axis '%s' is not valid.\", normalVectorPositiveAxis.c_str());\n    return false;\n  }\n\n  if (!FilterBase<T>::getParam(std::string(\"input_layer\"), inputLayer_)) {\n    ROS_ERROR(\"Normal vectors filter did not find parameter `input_layer`.\");\n    return false;\n  }\n  ROS_DEBUG(\"Normal vectors filter input layer is = %s.\", inputLayer_.c_str());\n\n  if (!FilterBase<T>::getParam(std::string(\"output_layers_prefix\"), outputLayersPrefix_)) {\n    ROS_ERROR(\"Normal vectors filter did not find parameter `output_layers_prefix`.\");\n    return false;\n  }\n  ROS_DEBUG(\"Normal vectors filter output_layer = %s.\", outputLayersPrefix_.c_str());\n\n  return true;\n}\n\ntemplate <typename T>\nbool NormalVectorsFilter<T>::update(const T& mapIn, T& mapOut) {\n  std::vector<std::string> normalVectorsLayers;\n  normalVectorsLayers.push_back(outputLayersPrefix_ + \"x\");\n  normalVectorsLayers.push_back(outputLayersPrefix_ + \"y\");\n  normalVectorsLayers.push_back(outputLayersPrefix_ + \"z\");\n\n  mapOut = mapIn;\n  for (const auto& layer : normalVectorsLayers) {\n    mapOut.add(layer);\n  }\n  switch (method_) {\n    case Method::Area:\n      computeWithArea(mapOut, inputLayer_, outputLayersPrefix_);\n      break;\n    case Method::Raster:\n      computeWithRaster(mapOut, inputLayer_, outputLayersPrefix_);\n      break;\n  }\n\n  return true;\n}\n\ntemplate <typename T>\nvoid NormalVectorsFilter<T>::computeWithArea(GridMap& map, const std::string& inputLayer, const std::string& outputLayersPrefix) {\n  // For each cell in requested area.\n  for (GridMapIterator iterator(map); !iterator.isPastEnd(); ++iterator) {\n    // Check if this is an empty cell (hole in the map).\n    if (!map.isValid(*iterator, inputLayer)) {\n      continue;\n    }\n\n    // Requested position (center) of circle in map.\n    Position center;\n    map.getPosition(*iterator, center);\n\n    // Prepare data computation. Check if area is bigger than cell.\n    const double minAllowedEstimationRadius = 0.5 * map.getResolution();\n    if (estimationRadius_ <= minAllowedEstimationRadius) {\n      ROS_WARN(\"Estimation radius is smaller than allowed by the map resolution (%d < %d)\", estimationRadius_, minAllowedEstimationRadius);\n    }\n\n    // Gather surrounding data.\n    size_t nPoints = 0;\n    Position3 sum = Position3::Zero();\n    Eigen::Matrix3d sumSquared = Eigen::Matrix3d::Zero();\n    for (CircleIterator circleIterator(map, center, estimationRadius_); !circleIterator.isPastEnd(); ++circleIterator) {\n      Position3 point;\n      if (!map.getPosition3(inputLayer, *circleIterator, point)) {\n        continue;\n      }\n      nPoints++;\n      sum += point;\n      sumSquared.noalias() += point * point.transpose();\n    }\n\n    Vector3 unitaryNormalVector = Vector3::Zero();\n    if (nPoints < 3) {\n      ROS_DEBUG(\"Not enough points to establish normal direction (nPoints = %i)\", nPoints);\n      unitaryNormalVector = {0, 0, 1};\n    } else {\n      const Position3 mean = sum / nPoints;\n      const Eigen::Matrix3d covarianceMatrix = sumSquared / nPoints - mean * mean.transpose();\n\n      // Compute Eigenvectors.\n      // Eigenvalues are ordered small to large\n      // Worst case bound for zero eigenvalue from : https://eigen.tuxfamily.org/dox/classEigen_1_1SelfAdjointEigenSolver.html\n      Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> solver;\n      solver.computeDirect(covarianceMatrix, Eigen::DecompositionOptions::ComputeEigenvectors);\n      if (solver.eigenvalues()(1) > 1e-8) {\n        unitaryNormalVector = solver.eigenvectors().col(0);\n      } else {  // If second eigenvalue is zero, the normal is not defined\n        ROS_DEBUG(\n            \"Covariance matrix needed for eigen decomposition is degenerated. Expected cause: data is on a straight line (nPoints = %i)\",\n            nPoints);\n        unitaryNormalVector = {0, 0, 1};\n      }\n    }\n\n    // Check direction of the normal vector and flip the sign towards the user defined direction.\n    if (unitaryNormalVector.dot(normalVectorPositiveAxis_) < 0.0) {\n      unitaryNormalVector = -unitaryNormalVector;\n    }\n\n    map.at(outputLayersPrefix + \"x\", *iterator) = unitaryNormalVector.x();\n    map.at(outputLayersPrefix + \"y\", *iterator) = unitaryNormalVector.y();\n    map.at(outputLayersPrefix + \"z\", *iterator) = unitaryNormalVector.z();\n  }\n}\n\ntemplate <typename T>\nvoid NormalVectorsFilter<T>::computeWithRaster(GridMap& map, const std::string& inputLayer, const std::string& outputLayersPrefix) {\n  throw std::runtime_error(\"NormalVectorsFilter::computeWithRaster() is not yet implemented!\");\n  // TODO: http://www.flipcode.com/archives/Calculating_Vertex_Normals_for_Height_Maps.shtml\n}\n\n}  // namespace grid_map\n\nPLUGINLIB_EXPORT_CLASS(grid_map::NormalVectorsFilter<grid_map::GridMap>, filters::FilterBase<grid_map::GridMap>)\n", "meta": {"hexsha": "3c3e357df9be90a674d722d8c27e2de1b18dfe24", "size": 6424, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "grid_map_filters/src/NormalVectorsFilter.cpp", "max_stars_repo_name": "mktk1117/grid_map", "max_stars_repo_head_hexsha": "1ee4c5dd78d029f4ef7e209c4080e57e18b081fb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-11T16:47:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-11T16:47:52.000Z", "max_issues_repo_path": "grid_map_filters/src/NormalVectorsFilter.cpp", "max_issues_repo_name": "mktk1117/grid_map", "max_issues_repo_head_hexsha": "1ee4c5dd78d029f4ef7e209c4080e57e18b081fb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "grid_map_filters/src/NormalVectorsFilter.cpp", "max_forks_repo_name": "mktk1117/grid_map", "max_forks_repo_head_hexsha": "1ee4c5dd78d029f4ef7e209c4080e57e18b081fb", "max_forks_repo_licenses": ["BSD-3-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.567251462, "max_line_length": 139, "alphanum_fraction": 0.7078144458, "num_tokens": 1575, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.82893881677331, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.46600992346203324}}
{"text": "/*\n * @Description: ceres sliding window optimizer, interface\n * @Author: Ge Yao\n * @Date: 2021-01-03 14:53:21\n */\n\n#ifndef LIDAR_LOCALIZATION_MODELS_SLIDING_WINDOW_CERES_SLIDING_WINDOW_HPP_\n#define LIDAR_LOCALIZATION_MODELS_SLIDING_WINDOW_CERES_SLIDING_WINDOW_HPP_\n\n#include <memory>\n\n#include <string>\n\n#include <vector>\n#include <deque>\n\n#include <Eigen/Eigen>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n#include \"lidar_localization/sensor_data/key_frame.hpp\"\n\n#include \"lidar_localization/models/pre_integrator/imu_pre_integrator.hpp\"\n\n#include <ceres/ceres.h>\n\n#include \"lidar_localization/models/sliding_window/params/param_prvag.hpp\"\n\n#include \"lidar_localization/models/sliding_window/factors/factor_prvag_marginalization.hpp\"\n#include \"lidar_localization/models/sliding_window/factors/factor_prvag_relative_pose.hpp\"\n#include \"lidar_localization/models/sliding_window/factors/factor_prvag_map_matching_pose.hpp\"\n#include \"lidar_localization/models/sliding_window/factors/factor_prvag_imu_pre_integration.hpp\"\n\nnamespace lidar_localization {\n\nclass CeresSlidingWindow {\npublic:\n    static const int INDEX_P = 0;\n    static const int INDEX_R = 3;\n    static const int INDEX_V = 6;\n    static const int INDEX_A = 9;\n    static const int INDEX_G = 12;\n\n    struct OptimizedKeyFrame {\n      double time;\n      double prvag[15];\n      bool fixed = false;\n    };\n    \n    struct ResidualMapMatchingPose {\n      int param_index;\n\n      Eigen::VectorXd m;\n      Eigen::MatrixXd I;\n    };\n\n    struct ResidualRelativePose {\n      int param_index_i;\n      int param_index_j;\n\n      Eigen::VectorXd m;\n      Eigen::MatrixXd I;\n    };\n\n    struct ResidualIMUPreIntegration {\n      int param_index_i;\n      int param_index_j;\n\n      double T;\n      Eigen::Vector3d g;\n      Eigen::VectorXd m;\n      Eigen::MatrixXd I;\n      Eigen::MatrixXd J;\n    };\n\n    CeresSlidingWindow(const int N);\n    ~CeresSlidingWindow();\n\n    /**\n     * @brief  add parameter block for LIO key frame\n     * @param  lio_key_frame, LIO key frame with (pos, ori, vel, b_a and b_g)\n     * @param  fixed, shall the param block be fixed to eliminate trajectory estimation ambiguity\n     * @return true if success false otherwise\n     */\n    void AddPRVAGParam(\n      const KeyFrame &lio_key_frame, const bool fixed\n    );\n\n    /**\n     * @brief  add residual block for relative pose constraint from lidar frontend\n     * @param  param_index_i, param block ID of previous key frame\n     * @param  param_index_j, param block ID of current key frame\n     * @param  relative_pose, relative pose measurement\n     * @param  noise, relative pose measurement noise\n     * @return void\n     */\n    void AddPRVAGRelativePoseFactor(\n      const int param_index_i, const int param_index_j,\n      const Eigen::Matrix4d &relative_pose, const Eigen::VectorXd &noise\n    );\n\n    /**\n     * @brief  add residual block for prior pose constraint from map matching\n     * @param  param_index, param block ID of current key frame\n     * @param  prior_pose, prior pose measurement\n     * @param  noise, prior pose measurement noise\n     * @return void\n     */\n    void AddPRVAGMapMatchingPoseFactor(\n      const int param_index,\n      const Eigen::Matrix4d &prior_pose, const Eigen::VectorXd &noise\n    );\n\n    /**\n     * @brief  add residual block for IMU pre-integration constraint from IMU measurement\n     * @param  param_index_i, param block ID of previous key frame\n     * @param  param_index_j, param block ID of current key frame\n     * @param  imu_pre_integration, IMU pre-integration measurement\n     * @return void\n     */\n    void AddPRVAGIMUPreIntegrationFactor(\n      const int param_index_i, const int param_index_j,\n      const IMUPreIntegrator::IMUPreIntegration &imu_pre_integration\n    );\n\n    // do optimization\n    bool Optimize();\n\n    // get num. of parameter blocks:\n    int GetNumParamBlocks();\n\n    /**\n     * @brief  get optimized odometry estimation\n     * @param  optimized_key_frame, output latest optimized key frame\n     * @return true if success false otherwise\n     */\n    bool GetLatestOptimizedKeyFrame(KeyFrame &optimized_key_frame);\n\n    /**\n     * @brief  get optimized LIO key frame state estimation\n     * @param  optimized_key_frames, output optimized LIO key frames\n     * @return true if success false otherwise\n     */\n    bool GetOptimizedKeyFrames(std::deque<KeyFrame> &optimized_key_frames);\n\nprivate:\n    /**\n     * @brief  create information matrix from measurement noise specification\n     * @param  noise, measurement noise covariances\n     * @return information matrix as square Eigen::MatrixXd\n     */\n    Eigen::MatrixXd GetInformationMatrix(Eigen::VectorXd noise);\n\n    // a. sliding window config:\n    const int kWindowSize;\n\n    // b. optimizer config:\n    struct {\n      // 1. loss function:\n      std::unique_ptr<ceres::LossFunction> loss_function_ptr;\n      // 2. solver:\n      ceres::Solver::Options options;\n    } config_;\n\n    // c. data buffer:\n    // c.1. param blocks:\n    std::vector<OptimizedKeyFrame> optimized_key_frames_;\n\n    // c.2. residual blocks:\n    sliding_window::FactorPRVAGMapMatchingPose *GetResMapMatchingPose(const ResidualMapMatchingPose &res_map_matching_pose);\n    sliding_window::FactorPRVAGRelativePose *GetResRelativePose(const ResidualRelativePose &res_relative_pose);\n    sliding_window::FactorPRVAGIMUPreIntegration *GetResIMUPreIntegration(const ResidualIMUPreIntegration &res_imu_pre_integration);\n\n    struct {\n      std::deque<ResidualMapMatchingPose> map_matching_pose;\n      std::deque<ResidualRelativePose> relative_pose;\n      std::deque<ResidualIMUPreIntegration> imu_pre_integration;\n    } residual_blocks_;\n};\n\n} // namespace lidar_localization\n\n#endif // LIDAR_LOCALIZATION_MODELS_SLIDING_WINDOW_CERES_SLIDING_WINDOW_HPP_", "meta": {"hexsha": "f3bbed1631d9079ef9b1838b963f4ee0d5fecfa2", "size": 5774, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "GraphOptimize/09-sliding-window/src/lidar_localization/include/lidar_localization/models/sliding_window/ceres_sliding_window.hpp", "max_stars_repo_name": "lanqing30/SensorFusionCourse", "max_stars_repo_head_hexsha": "3fcf935d6a4191563afcf2d95b34718fba7f705a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "GraphOptimize/09-sliding-window/src/lidar_localization/include/lidar_localization/models/sliding_window/ceres_sliding_window.hpp", "max_issues_repo_name": "lanqing30/SensorFusionCourse", "max_issues_repo_head_hexsha": "3fcf935d6a4191563afcf2d95b34718fba7f705a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GraphOptimize/09-sliding-window/src/lidar_localization/include/lidar_localization/models/sliding_window/ceres_sliding_window.hpp", "max_forks_repo_name": "lanqing30/SensorFusionCourse", "max_forks_repo_head_hexsha": "3fcf935d6a4191563afcf2d95b34718fba7f705a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-08T01:05:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T01:05:31.000Z", "avg_line_length": 31.5519125683, "max_line_length": 132, "alphanum_fraction": 0.7185659855, "num_tokens": 1413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4660099139591201}}
{"text": "\n#include <cassert>\n\n// Before doing anything else, grab in the definitions of the test\n// space and trial spaces that make up the finite element system.\n#include <qdove/base/test_space.h>\n#include <qdove/base/trial_space.h>\n#include <qdove/materials/constants.h>\n\n// Use the *solution* to a fick equation as a material function\n#include <qdove/models/fick.h>\n\n// Start by solving Schroedinger's problem\n#include <qdove/models/schroedinger.h>\n\n// and next by solving Poissons's problem\n#include <qdove/models/poisson.h>\n\n// Let's use a function from the qdove library for a psudo potential.\n#include <qdove/psuedopotentials/function_library.h>\n\n// Also make use of the predefined generalised eigenspectrum system -\n// we need this for the Schroedinger problem.\n#include <qdove/generic_linear_algebra/eigenspectrum_system.h>\n\n// Also make use of the predefined linear algebra system - we need\n// this for the Poisson problem.\n#include <qdove/generic_linear_algebra/linear_algebra_system.h>\n\n// Next up are some deal.II objects that have not been generalised\n// away yet...\n#include <deal.II/grid/tria.h>\n#include <deal.II/grid/grid_generator.h>\n#include <deal.II/numerics/data_out.h>\n\n// The purpose of this example is to have a working (dimensionless)\n// Schroedinger-Poisson solver that can be generalised piecewise to\n// the qdove library.\n//\ntemplate<int dim>\nclass SelfConsistentProblem\n{\npublic:\n  SelfConsistentProblem (dealii::Triangulation<dim> &triangulation);\n  ~SelfConsistentProblem ();\n\n  void write_gnuplot (const dealii::PETScWrappers::Vector &vector,\n          const std::string                   &name,\n          const unsigned int                   cycle);\n  void run ();\n\nprivate:\n  // The description of the finite element basis\n  qdove::TrialSpace<dim> trial_space;\n\n  // Geometry description and boundary constraints\n  qdove::TestSpace<dim> test_space;\n\n  // Fick's problem, which is used to obtain a material profile.\n  qdove::Fick::Solution<1> fick_solution;\n\n  // The eigenspectrum system that will be solved by SLEPc\n  qdove::Schroedinger::Problem<dim> schroedinger_problem;\n\n  // The system of equations that will be solved by PETSc\n  qdove::Poisson::Problem<dim> poisson_problem;\n\n  // The eigenpairs from schroedinger's problem\n  std::vector<dealii::PETScWrappers::Vector> eigenvectors;\n  std::vector<double>                        eigenvalues;\n\n  // The solution from poisson's problem\n  dealii::PETScWrappers::Vector solution;\n\n};\n\ntemplate<int dim>\nSelfConsistentProblem<dim>::SelfConsistentProblem (dealii::Triangulation<dim> &triangulation)\n  :\n  trial_space (triangulation),\n  test_space (trial_space),\n  fick_solution (trial_space, test_space),\n  schroedinger_problem (trial_space, test_space, 10),\n  poisson_problem (trial_space, test_space)\n{}\n\ntemplate<int dim>\nSelfConsistentProblem<dim>::~SelfConsistentProblem ()\n{}\n\ntemplate<int dim>\nvoid\nSelfConsistentProblem<dim>::write_gnuplot (const dealii::PETScWrappers::Vector &vector,\n             const std::string                   &name,\n             const unsigned int                   cycle)\n{\n  // Output a vector to gnuplot style file.\n  std::ostringstream filename;\n  filename << \"solution-\" << name << \"-\" << cycle << \".gpl\";\n  std::ofstream output (filename.str ().c_str ());\n\n  dealii::DataOut<dim> data_out;\n  data_out.attach_dof_handler (test_space.dofs ());\n  data_out.add_data_vector (vector, name);\n\n  // generate default patches and output.\n  data_out.build_patches ();\n  data_out.write_gnuplot (output);\n}\n\n\ntemplate<int dim>\nvoid\nSelfConsistentProblem<dim>::run ()\n{\n  std::cout << \"Test space:\" << std::endl\n      << \"   Finite element type:          \"\n      << test_space.fe ().get_name ()\n      << std::endl\n      << \"   Number of degrees of freedom: \"\n      << test_space.n_dofs ()\n      << std::endl;\n\n  const double energy_height = 0.5 * qdove::E0;\n  const double doping = 1e25;\n\n  //\n  // Setup a material function\n  //\n  fick_solution.reinit ();\n  fick_solution.set_initial_height (1.);\n  fick_solution.set_initial_rate(2e-10);\n  fick_solution.set_symmetric_profile(false);\n\n  dealii::PETScWrappers::Vector transition_1 (test_space.n_dofs ());\n  fick_solution.set_initial_length (50e-10);\n  fick_solution.interpolate_analytic_solution (transition_1);\n\n  dealii::PETScWrappers::Vector transition_2 (test_space.n_dofs ());\n  fick_solution.set_initial_length (100e-10);\n  fick_solution.interpolate_analytic_solution (transition_2);\n\n  dealii::PETScWrappers::Vector transition_3 (test_space.n_dofs ());\n  fick_solution.set_initial_length (150e-10);\n  fick_solution.interpolate_analytic_solution (transition_3);\n\n\n  dealii::PETScWrappers::Vector material_function (test_space.n_dofs ());\n  for (std::size_t i=0; i<material_function.size(); ++i)\n    material_function[i] =  (1.0 - transition_1[i])\n                           + transition_2[i] * 0.20/0.35  // for Al_{0.20}Ga_{0.80}As\n                           + transition_3[i] * 0.15/0.35;      // for Al_{0.35}Ga_{0.65}As\n  write_gnuplot (material_function, \"material_function\", 0);\n\n\n  // set up the effective mass\n  dealii::PETScWrappers::Vector kinetic_energy_prefactor (test_space.n_dofs ());\n  for (std::size_t i=0; i<kinetic_energy_prefactor.size(); ++i)\n    kinetic_energy_prefactor[i] = (qdove::HBAR*qdove::HBAR) / (2.*(qdove::mstar_GaAs + 0.35*material_function[i]*0.083)*qdove::M0);\n  write_gnuplot (kinetic_energy_prefactor, \"kinetic_energy_prefactor\", 0);\n\n  // set up the initial guess for the electron potential (i.e. electrostatic potential multiplied by elementary charge)\n  dealii::PETScWrappers::Vector potential (test_space.n_dofs ());\n  potential = material_function;\n  potential *= 0.9 * energy_height; //start with no space charge region by selecting the potential right below the the Fer\n\n  double E_bonding = 0.005 * qdove::E0; //5meV bonding energy of the ions\n  double E_fermi = energy_height - E_bonding;\n\n  //\n  // Main iteration Schroedinger <-> Poisson\n  //\n  for (std::size_t cycle = 0; cycle < 100; ++cycle)\n  {\n    write_gnuplot (potential, \"potential\", cycle);\n\n    // Get started on Schroedinger's problem\n    std::cout << \"Schroedinger's problem:\" << std::endl;\n    schroedinger_problem.reinit ();\n\n    schroedinger_problem.assemble (kinetic_energy_prefactor, potential);\n    schroedinger_problem.solve ();\n    schroedinger_problem.get_solution_eigenpairs (eigenvalues, eigenvectors);\n    write_gnuplot (eigenvectors[0], \"electron_function\", cycle);\n\n    // output\n    std::cout << \"   Eigenvalues:                  \";\n    for (unsigned int i=0; i<eigenvalues.size (); ++i)\n      std::cout << eigenvalues[i] << \" \";\n    std::cout << std::endl;\n\n    std::cout << \"   Scaled values (meV):           \";\n    for (unsigned int i=0; i<eigenvalues.size (); ++i)\n      std::cout << eigenvalues[i]/(1e-03*qdove::E0) << \" \";\n    std::cout << std::endl;\n\n    // Compute density from the eigenfunctions and eigenvalues:\n    double kBT = 300.0 * qdove::KB;\n    dealii::PETScWrappers::Vector density(test_space.n_dofs());\n    for (unsigned int i=0; i<eigenvectors.size (); ++i)\n    {\n      double E_wavefunction = eigenvalues[i];\n      double occupancy      =  kBT * std::log(1.0+std::exp((E_fermi - E_wavefunction)/kBT)); //integrated Fermi-Dirac statistic\n      for (unsigned int j=0; j<eigenvectors[0].size (); ++j)\n      {\n        double density_of_states = (qdove::mstar_GaAs + 0.35*material_function[i]*0.083) * qdove::M0 / (qdove::HBAR*qdove::HBAR*qdove::PI);\n        density[j] += density_of_states * eigenvectors[i][j] * eigenvectors[i][j] * occupancy;\n      }\n    }\n    write_gnuplot (density, \"density\", cycle);\n\n    // Set up RHS for Poisson's equation\n    dealii::PETScWrappers::Vector rho(density.size());\n    for (std::size_t i=0; i<solution.size(); ++i)\n      if (potential[i] > E_fermi)\n        rho[i] = -doping;\n    rho += density;\n    rho *= qdove::E0 * qdove::E0 / (qdove::permittivity_GaAs);\n    write_gnuplot (rho, \"rho\", cycle);\n\n    // Solve Poisson:\n    std::cout << \"Poisson's problem:\" << std::endl;\n    poisson_problem.reinit ();\n    poisson_problem.assemble (rho);\n    poisson_problem.solve ();\n    poisson_problem.get_solution_vector (solution);\n    write_gnuplot (solution, \"poisson_solution\", cycle);\n\n    // Update potential:\n    double max_update = 0;\n    for (std::size_t i=0; i<solution.size(); ++i)\n    {\n      double old_value = potential[i] - 0.9 * energy_height * material_function[i];\n      max_update = std::max(max_update, std::fabs(solution[i] - old_value));\n    }\n\n    double cutoff_update_value = 0.02 * qdove::E0;\n    double alpha = (max_update > cutoff_update_value) ? cutoff_update_value / max_update : 1.0; //update by at most 10 mV for stability reasons\n\n    alpha = 0.2;\n    std::cout << \"alpha: \" << alpha << std::endl;\n\n    for (std::size_t i=0; i<potential.size(); ++i)\n    {\n      double old_value = potential[i] - 0.9 * energy_height * material_function[i];\n      double update = solution[i] - old_value;\n      potential[i] += alpha * update;\n    }\n  }\n}\n\nint main (int argc, char **argv)\n{\n  try\n    {\n      dealii::Utilities::MPI::MPI_InitFinalize mpi_initialization (argc, argv, 1);\n      {\n  // Create a grid\n  dealii::Triangulation<1> triangulation;\n  dealii::GridGenerator::hyper_cube (triangulation, 0, 200e-10);\n  triangulation.refine_global (8);\n\n  // Run Schroedinger's problem on that grid\n  SelfConsistentProblem<1> self_consistent_problem (triangulation);\n  self_consistent_problem.run ();\n      }\n    }\n  catch (std::exception &exc)\n    {\n      std::cerr << std::endl << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      std::cerr << \"Exception on processing: \" << std::endl\n                << exc.what() << std::endl\n                << \"Aborting!\" << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n\n      return 1;\n    }\n  catch (...)\n    {\n      std::cerr << std::endl << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      std::cerr << \"Unknown exception!\" << std::endl\n                << \"Aborting!\" << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      return 1;\n    }\n\n  return 0;\n}\n", "meta": {"hexsha": "15e8120bc62db11aa963d34778364fef1911ca3d", "size": 10316, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/step-2/step-2.cc", "max_stars_repo_name": "QuantumDove/QuantumDove", "max_stars_repo_head_hexsha": "6220570364d953fdecd0173a35a6b59976239cbb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-09-03T01:56:17.000Z", "max_stars_repo_stars_event_max_datetime": "2016-09-03T01:56:17.000Z", "max_issues_repo_path": "examples/step-2/step-2.cc", "max_issues_repo_name": "QuantumDove/QuantumDove", "max_issues_repo_head_hexsha": "6220570364d953fdecd0173a35a6b59976239cbb", "max_issues_repo_licenses": ["MIT"], "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/step-2/step-2.cc", "max_forks_repo_name": "QuantumDove/QuantumDove", "max_forks_repo_head_hexsha": "6220570364d953fdecd0173a35a6b59976239cbb", "max_forks_repo_licenses": ["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.9694915254, "max_line_length": 143, "alphanum_fraction": 0.6511244668, "num_tokens": 2784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387914176258, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.46600990920766333}}
{"text": "//  Copyright (c) 2006, Stephan Diederich\n//\n//  This code may be used under either of the following two licences:\n//\n//    Permission is hereby granted, free of charge, to any person\n//    obtaining a copy of this software and associated documentation\n//    files (the \"Software\"), to deal in the Software without\n//    restriction, including without limitation the rights to use,\n//    copy, modify, merge, publish, distribute, sublicense, and/or\n//    sell copies of the Software, and to permit persons to whom the\n//    Software is furnished to do so, subject to the following\n//    conditions:\n//\n//    The above copyright notice and this permission notice shall be\n//    included in all copies or substantial portions of the Software.\n//\n//    THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n//    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n//    OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n//    NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n//    HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n//    WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n//    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n//    OTHER DEALINGS IN THE SOFTWARE. OF SUCH DAMAGE.\n//\n//  Or:\n//\n//    Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//    http://www.boost.org/LICENSE_1_0.txt)\n\n#include <boost/config.hpp>\n#include <iostream>\n#include <string>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/boykov_kolmogorov_max_flow.hpp>\n#include <boost/graph/read_dimacs.hpp>\n#include <boost/graph/graph_utility.hpp>\n\n// Use a DIMACS network flow file as stdin.\n// boykov_kolmogorov-eg < max_flow.dat\n//\n// Sample output:\n// c  The total flow:\n// s 13\n//\n// c flow values:\n// f 0 6 3\n// f 0 1 6\n// f 0 2 4\n// f 1 5 1\n// f 1 0 0\n// f 1 3 5\n// f 2 4 4\n// f 2 3 0\n// f 2 0 0\n// f 3 7 5\n// f 3 2 0\n// f 3 1 0\n// f 4 5 0\n// f 4 6 4\n// f 5 4 0\n// f 5 7 1\n// f 6 7 7\n// f 6 4 0\n// f 7 6 0\n// f 7 5 0\n\nint main()\n{\n    using namespace boost;\n\n    typedef adjacency_list_traits< vecS, vecS, directedS > Traits;\n    typedef adjacency_list< vecS, vecS, directedS,\n        property< vertex_name_t, std::string,\n            property< vertex_index_t, long,\n                property< vertex_color_t, boost::default_color_type,\n                    property< vertex_distance_t, long,\n                        property< vertex_predecessor_t,\n                            Traits::edge_descriptor > > > > >,\n\n        property< edge_capacity_t, long,\n            property< edge_residual_capacity_t, long,\n                property< edge_reverse_t, Traits::edge_descriptor > > > >\n        Graph;\n\n    Graph g;\n    property_map< Graph, edge_capacity_t >::type capacity\n        = get(edge_capacity, g);\n    property_map< Graph, edge_residual_capacity_t >::type residual_capacity\n        = get(edge_residual_capacity, g);\n    property_map< Graph, edge_reverse_t >::type rev = get(edge_reverse, g);\n    Traits::vertex_descriptor s, t;\n    read_dimacs_max_flow(g, capacity, rev, s, t);\n\n    std::vector< default_color_type > color(num_vertices(g));\n    std::vector< long > distance(num_vertices(g));\n    long flow = boykov_kolmogorov_max_flow(g, s, t);\n\n    std::cout << \"c  The total flow:\" << std::endl;\n    std::cout << \"s \" << flow << std::endl << std::endl;\n\n    std::cout << \"c flow values:\" << std::endl;\n    graph_traits< Graph >::vertex_iterator u_iter, u_end;\n    graph_traits< Graph >::out_edge_iterator ei, e_end;\n    for (boost::tie(u_iter, u_end) = vertices(g); u_iter != u_end; ++u_iter)\n        for (boost::tie(ei, e_end) = out_edges(*u_iter, g); ei != e_end; ++ei)\n            if (capacity[*ei] > 0)\n                std::cout << \"f \" << *u_iter << \" \" << target(*ei, g) << \" \"\n                          << (capacity[*ei] - residual_capacity[*ei])\n                          << std::endl;\n\n    return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "5dd8d03e42f41277aa4f19007e5becd645a4e7f0", "size": 3976, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/graph/example/boykov_kolmogorov-eg.cpp", "max_stars_repo_name": "uosorio/heroku_face", "max_stars_repo_head_hexsha": "7d6465e71dba17a15d8edaef520adb2fcd09d91e", "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": "3rdparty/boost_1_73_0/libs/graph/example/boykov_kolmogorov-eg.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 130.0, "max_issues_repo_issues_event_min_datetime": "2016-06-22T22:11:25.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-29T20:24:09.000Z", "max_forks_repo_path": "3rdparty/boost_1_73_0/libs/graph/example/boykov_kolmogorov-eg.cpp", "max_forks_repo_name": "qingkouwei/mediaones", "max_forks_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2015-07-08T19:18:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-14T16:39:56.000Z", "avg_line_length": 34.5739130435, "max_line_length": 78, "alphanum_fraction": 0.6405935614, "num_tokens": 1091, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.4659949096361711}}
{"text": "/**\n * @file\n * @brief NPDE homework ElementMatrixComputation code\n * @author Janik Sch\u00fcttler, edited by Oliver Rietmann\n * @date 06.03.2019\n * @copyright Developed at ETH Zurich\n */\n\n#include \"solve.h\"\n\n#include <Eigen/Core>\n#include <iostream>\n\n#include \"mylinearfeelementmatrix.h\"\n#include \"mylinearloadvector.h\"\n\nnamespace ElementMatrixComputation {\n\n/* SAM_LISTING_BEGIN_2 */\nEigen::VectorXd solvePoissonBVP() {\n  // Convert the globally defined function f to a LehrFEM++ mesh function object\n  lf::mesh::utils::MeshFunctionGlobal mf_f{f};\n\n  // The basis expansion coefficient vector for the finite-element solution\n  Eigen::VectorXd solution = Eigen::VectorXd::Zero(1);\n\n  //====================\n  // Your code goes here\n  //====================\n\n  return solution;\n}\n/* SAM_LISTING_END_2 */\n\nEigen::VectorXd solveNeumannEq() {\n  // Define the solution vector\n  Eigen::VectorXd solution;\n\n  //====================\n  // Your code goes here\n  //====================\n\n  return solution;\n}\n\n}  // namespace ElementMatrixComputation\n", "meta": {"hexsha": "d4f4a5627106cef33e330440c0e6d4dafb162433", "size": 1035, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/ElementMatrixComputation/templates/solve.cc", "max_stars_repo_name": "padomu/NPDECODES", "max_stars_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/ElementMatrixComputation/templates/solve.cc", "max_issues_repo_name": "padomu/NPDECODES", "max_issues_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/ElementMatrixComputation/templates/solve.cc", "max_forks_repo_name": "padomu/NPDECODES", "max_forks_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 22.0212765957, "max_line_length": 80, "alphanum_fraction": 0.6666666667, "num_tokens": 251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.6513548714339145, "lm_q1q2_score": 0.4659949047942816}}
{"text": "#include \"pytheia/solvers/solvers.h\"\n\n#include <pybind11/eigen.h>\n#include <pybind11/pybind11.h>\n#include <pybind11/stl.h>\n\n#include <Eigen/Core>\n#include <iostream>\n#include <pybind11/numpy.h>\n#include <vector>\n\n#include \"theia/solvers/evsac.h\"\n#include \"theia/solvers/evsac_sampler.h\"\n#include \"theia/solvers/exhaustive_ransac.h\"\n#include \"theia/solvers/exhaustive_sampler.h\"\n#include \"theia/solvers/inlier_support.h\"\n#include \"theia/solvers/lmed.h\"\n#include \"theia/solvers/lmed_quality_measurement.h\"\n#include \"theia/solvers/mle_quality_measurement.h\"\n#include \"theia/solvers/prosac.h\"\n#include \"theia/solvers/prosac_sampler.h\"\n#include \"theia/solvers/quality_measurement.h\"\n#include \"theia/solvers/random_sampler.h\"\n#include \"theia/solvers/sample_consensus_estimator.h\"\n#include \"theia/solvers/sampler.h\"\n#include \"theia/util/random.h\"\n\nnamespace py = pybind11;\n\nnamespace pytheia {\nnamespace solvers {\n\nvoid pytheia_solvers_classes(py::module& m) {\n  // RandomNumberGenerator\n  py::class_<theia::RandomNumberGenerator>(m, \"RandomNumberGenerator\")\n      .def(py::init<>())\n      .def(py::init<int>())\n      .def(\"Seed\", &theia::RandomNumberGenerator::Seed)\n      .def(\"RandDouble\", &theia::RandomNumberGenerator::RandDouble)\n      .def(\"RandFloat\", &theia::RandomNumberGenerator::RandFloat)\n      .def(\"RandInt\", &theia::RandomNumberGenerator::RandInt)\n      .def(\"RandGaussian\", &theia::RandomNumberGenerator::RandGaussian)\n\n      ;\n\n  // RansacSummary\n  py::class_<theia::RansacSummary>(m, \"RansacSummary\")\n      .def_readwrite(\"inliers\", &theia::RansacSummary::inliers)\n      .def_readwrite(\"num_input_data_points\",\n                     &theia::RansacSummary::num_input_data_points)\n      .def_readwrite(\"num_iterations\", &theia::RansacSummary::num_iterations)\n      .def_readwrite(\"confidence\", &theia::RansacSummary::confidence)\n\n      ;\n\n  py::class_<theia::RansacParameters>(m, \"RansacParameters\")\n      .def(py::init<>())\n      .def_readwrite(\"error_thresh\", &theia::RansacParameters::error_thresh)\n      .def_readwrite(\"failure_probability\",\n                     &theia::RansacParameters::failure_probability)\n      .def_readwrite(\"min_inlier_ratio\",\n                     &theia::RansacParameters::min_inlier_ratio)\n      .def_readwrite(\"min_iterations\", &theia::RansacParameters::min_iterations)\n      .def_readwrite(\"max_iterations\", &theia::RansacParameters::max_iterations)\n      .def_readwrite(\"use_mle\", &theia::RansacParameters::use_mle)\n      .def_readwrite(\"use_Tdd_test\", &theia::RansacParameters::use_Tdd_test);\n  /*\n  py::enum_<theia::FittingMethod>(m, \"FittingMethod\")\n    .value(\"MLE\", theia::FittingMethod::MLE)\n    .value(\"QUANTILE_NLS\", theia::FittingMethod::QUANTILE_NLS)\n    .export_values()\n  ;\n\n\n  py::class_<theia::Sampler> sampler(m, \"Sampler\");\n\n\n  py::class_<theia::ProsacSampler>(m, \"ProsacSampler\", sampler)\n    .def(py::init<std::shared_ptr<theia::RandomNumberGenerator>, int>())\n    .def(\"SetSampleNumber\", &theia::ProsacSampler::SetSampleNumber)\n    .def(\"Sample\", &theia::ProsacSampler::Sample)\n    .def(\"Initialize\", &theia::ProsacSampler::Initialize)\n\n  ;\n\n  py::class_<theia::ExhaustiveSampler>(m, \"ExhaustiveSampler\", sampler)\n    .def(py::init<std::shared_ptr<theia::RandomNumberGenerator>, int>())\n    .def(\"Sample\", &theia::ExhaustiveSampler::Sample)\n    .def(\"Initialize\", &theia::ExhaustiveSampler::Initialize)\n\n  ;\n\n  py::class_<theia::RandomSampler>(m, \"RandomSampler\", sampler)\n    .def(py::init<std::shared_ptr<theia::RandomNumberGenerator>, int>())\n    .def(\"Sample\", &theia::RandomSampler::Sample)\n    .def(\"Initialize\", &theia::RandomSampler::Initialize)\n\n  ;\n\n\n  // templated subclass\n\n  py::class_<theia::EvsacSampler<Eigen::Vector2d>>(m, \"EvsacSampler\", sampler)\n    .def(py::init<int, Eigen::MatrixXd, double, theia::FittingMethod>())\n    .def(\"Initialize\", &theia::EvsacSampler<Eigen::Vector2d>::Initialize)\n    .def(\"Sample\", &theia::EvsacSampler<Eigen::Vector2d>::Sample)\n\n  ;\n\n  py::class_<theia::QualityMeasurement>(m, \"QualityMeasurement\")\n\n    .def(\"Initialize\", &theia::QualityMeasurement::Initialize)\n  ;\n\n  py::class_<theia::LmedQualityMeasurement, theia::QualityMeasurement>(m,\n  \"LmedQualityMeasurement\") .def(py::init<int>()) .def(\"ComputeCost\",\n  &theia::LmedQualityMeasurement::ComputeCost)\n  ;\n\n\n  py::class_<theia::MLEQualityMeasurement, theia::QualityMeasurement>(m,\n  \"MLEQualityMeasurement\") .def(py::init<double>()) .def(\"ComputeCost\",\n  &theia::MLEQualityMeasurement::ComputeCost)\n  ;\n\n  py::class_<theia::InlierSupport, theia::QualityMeasurement>(m,\n  \"InlierSupport\") .def(py::init<double>()) .def(\"ComputeCost\",\n  &theia::InlierSupport::ComputeCost)\n  ;\n  */\n  /*\n  py::class_<theia::SampleConsensusEstimator>(m, \"SampleConsensusEstimator\")\n\n    .def(\"Initialize\", &theia::SampleConsensusEstimator::Initialize)\n    .def(\"Estimate\", &theia::SampleConsensusEstimator::Estimate)\n  ;\n  */\n}\n\nvoid pytheia_solvers(py::module& m) {\n  py::module m_submodule = m.def_submodule(\"solvers\");\n  pytheia_solvers_classes(m_submodule);\n}\n\n}  // namespace solvers\n}  // namespace pytheia", "meta": {"hexsha": "d52cc9c76e892a5a99b284ce37310f214bea0c02", "size": 5060, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/pytheia/solvers/solvers.cc", "max_stars_repo_name": "urbste/TheiaSfM", "max_stars_repo_head_hexsha": "a92fa27e90b6182e2a2511a46d24283afad1a995", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T03:01:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-04T08:08:45.000Z", "max_issues_repo_path": "src/pytheia/solvers/solvers.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/pytheia/solvers/solvers.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": 34.6575342466, "max_line_length": 80, "alphanum_fraction": 0.7138339921, "num_tokens": 1451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548646660543, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.465994899952392}}
{"text": "//  (C) Copyright Matt Borland 2021.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_MATH_CCMATH_FMOD_HPP\n#define BOOST_MATH_CCMATH_FMOD_HPP\n\n#include <cmath>\n#include <cstdint>\n#include <limits>\n#include <type_traits>\n#include <boost/math/tools/is_constant_evaluated.hpp>\n#include <boost/math/ccmath/abs.hpp>\n#include <boost/math/ccmath/isinf.hpp>\n#include <boost/math/ccmath/isnan.hpp>\n#include <boost/math/ccmath/isfinite.hpp>\n\nnamespace boost::math::ccmath {\n\nnamespace detail {\n\ntemplate <typename ReturnType, typename T1, typename T2>\ninline constexpr ReturnType fmod_impl(T1 x, T2 y) noexcept\n{\n    if(x == y)\n    {\n        return ReturnType(0);\n    }\n    else\n    {\n        while(x >= y)\n        {\n            x -= y;\n        }\n\n        return static_cast<ReturnType>(x);\n    }\n}\n\n} // Namespace detail\n\ntemplate <typename Real, std::enable_if_t<!std::is_integral_v<Real>, bool> = true>\ninline constexpr Real fmod(Real x, Real y) noexcept\n{\n    if(BOOST_MATH_IS_CONSTANT_EVALUATED(x))\n    {\n        return boost::math::ccmath::abs(x) == Real(0) && y != Real(0) ? x :\n               boost::math::ccmath::isinf(x) && !boost::math::ccmath::isnan(y) ? std::numeric_limits<Real>::quiet_NaN() :\n               boost::math::ccmath::abs(y) == Real(0) && !boost::math::ccmath::isnan(x) ? std::numeric_limits<Real>::quiet_NaN() :\n               boost::math::ccmath::isinf(y) && boost::math::ccmath::isfinite(x) ? x :\n               boost::math::ccmath::isnan(x) ? std::numeric_limits<Real>::quiet_NaN() :\n               boost::math::ccmath::isnan(y) ? std::numeric_limits<Real>::quiet_NaN() :\n               boost::math::ccmath::detail::fmod_impl<Real>(x, y);\n    }\n    else\n    {\n        using std::fmod;\n        return fmod(x, y);\n    }\n}\n\ntemplate <typename T1, typename T2>\ninline constexpr auto fmod(T1 x, T2 y) noexcept\n{\n    if(BOOST_MATH_IS_CONSTANT_EVALUATED(x))\n    {\n        // If the type is an integer (e.g. epsilon == 0) then set the epsilon value to 1 so that type is at a minimum \n        // cast to double\n        constexpr auto T1p = std::numeric_limits<T1>::epsilon() > 0 ? std::numeric_limits<T1>::epsilon() : 1;\n        constexpr auto T2p = std::numeric_limits<T2>::epsilon() > 0 ? std::numeric_limits<T2>::epsilon() : 1;\n        \n        using promoted_type = \n                              #ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n                              std::conditional_t<T1p <= LDBL_EPSILON && T1p <= T2p, T1,\n                              std::conditional_t<T2p <= LDBL_EPSILON && T2p <= T1p, T2,\n                              #endif\n                              std::conditional_t<T1p <= DBL_EPSILON && T1p <= T2p, T1,\n                              std::conditional_t<T2p <= DBL_EPSILON && T2p <= T1p, T2, double\n                              #ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n                              >>>>;\n                              #else\n                              >>;\n                              #endif\n\n        return boost::math::ccmath::fmod(promoted_type(x), promoted_type(y));\n    }\n    else\n    {\n        using std::fmod;\n        return fmod(x, y);\n    }\n}\n\ninline constexpr float fmodf(float x, float y) noexcept\n{\n    return boost::math::ccmath::fmod(x, y);\n}\n\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\ninline constexpr long double fmodl(long double x, long double y) noexcept\n{\n    return boost::math::ccmath::fmod(x, y);\n}\n#endif\n\n} // Namespaces\n\n#endif // BOOST_MATH_CCMATH_FMOD_HPP\n", "meta": {"hexsha": "12e67d8c06c0d4e57de18c3bff1813a83ee62af5", "size": 3633, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/boost_1.78.0/boost/math/ccmath/fmod.hpp", "max_stars_repo_name": "LaudateCorpus1/math", "max_stars_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_stars_repo_licenses": ["BSD-3-Clause"], "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": "lib/boost_1.78.0/boost/math/ccmath/fmod.hpp", "max_issues_repo_name": "LaudateCorpus1/math", "max_issues_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_issues_repo_licenses": ["BSD-3-Clause"], "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": "lib/boost_1.78.0/boost/math/ccmath/fmod.hpp", "max_forks_repo_name": "LaudateCorpus1/math", "max_forks_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_forks_repo_licenses": ["BSD-3-Clause"], "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": 33.0272727273, "max_line_length": 130, "alphanum_fraction": 0.5904211396, "num_tokens": 952, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.465994899952392}}
{"text": "/**\n * @file    LineSegment3D.hpp\n *\n * @author  btran\n *\n */\n\n#pragma once\n\n#include <pcl/ModelCoefficients.h>\n#include <pcl/common/common.h>\n#include <pcl/common/distances.h>\n#include <pcl/filters/project_inliers.h>\n\n#include <Eigen/Dense>\n\nnamespace geometry\n{\ntemplate <typename POINT_CLOUD_TYPE> class LineSegment3D\n{\n public:\n    using PointCloudType = POINT_CLOUD_TYPE;\n    using PointCloud = pcl::PointCloud<PointCloudType>;\n    using PointCloudPtr = typename PointCloud::Ptr;\n\n    LineSegment3D(const PointCloudPtr& cloud, const pcl::ModelCoefficients& coeffs)\n        : m_cloud(cloud)\n        , m_coeffs(coeffs)\n        , m_inlierIndices()\n    {\n        if (m_coeffs.values.size() != 6) {\n            throw std::runtime_error(\"invalid size of line coefficients\");\n        }\n    }\n\n    static std::vector<int> getPointIndicesCloseToLine(const PointCloudPtr& cloud, const pcl::ModelCoefficients& coeffs,\n                                                       const float distanceToLineThresh,\n                                                       const std::vector<char>& ignorePointIndices);\n\n    bool refine(const float distanceToLineThresh, const std::vector<char>& ignorePointIndices);\n\n    const auto& coeffs() const\n    {\n        return m_coeffs;\n    }\n\n    const auto& inlierIndices() const\n    {\n        return m_inlierIndices;\n    }\n\n    PointCloudPtr projectPointsOnLine(const bool sortAlongLinePositiveDirection = true) const;\n\n private:\n    template <typename T>\n    bool almostEquals(const T val, const T correctVal, const T epsilon = std::numeric_limits<T>::epsilon())\n    {\n        const T maxXYOne = std::max({static_cast<T>(1.0f), std::fabs(val), std::fabs(correctVal)});\n        return std::fabs(val - correctVal) <= epsilon * maxXYOne;\n    }\n\n private:\n    const PointCloudPtr& m_cloud;\n    pcl::ModelCoefficients m_coeffs;\n    std::vector<int> m_inlierIndices;\n};\n}  // namespace geometry\n\n#include \"impl/LineSegment3D.ipp\"\n", "meta": {"hexsha": "5d6a103b0a94db30ec7c52e114ae5aa9e620dbfa", "size": 1953, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/3d_line_detection/LineSegment3D.hpp", "max_stars_repo_name": "xmba15/3d_line_detection", "max_stars_repo_head_hexsha": "a287339caa88b257427dc5ec7c292d7e4695cf67", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-15T12:04:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-15T12:04:00.000Z", "max_issues_repo_path": "include/3d_line_detection/LineSegment3D.hpp", "max_issues_repo_name": "TANHAIYU/3d_line_detection", "max_issues_repo_head_hexsha": "c62d9252b1e379b295e619a26afea88e03d556be", "max_issues_repo_licenses": ["MIT"], "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/3d_line_detection/LineSegment3D.hpp", "max_forks_repo_name": "TANHAIYU/3d_line_detection", "max_forks_repo_head_hexsha": "c62d9252b1e379b295e619a26afea88e03d556be", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-09-15T12:07:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T06:09:10.000Z", "avg_line_length": 27.9, "max_line_length": 120, "alphanum_fraction": 0.6528417819, "num_tokens": 455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548646660543, "lm_q2_score": 0.7154239836484143, "lm_q1q2_score": 0.46599489204816236}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2013   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2013   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#include <nt2/euler/include/functions/digamma.hpp>\n\n#include <nt2/sdk/functor/meta/call.hpp>\n#include <boost/simd/sdk/simd/native.hpp>\n#include <nt2/sdk/unit/tests/ulp.hpp>\n#include <nt2/include/functions/splat.hpp>\n#include <nt2/sdk/unit/module.hpp>\n#include <boost/simd/sdk/config.hpp>\n#include <boost/simd/sdk/simd/io.hpp>\n#include <boost/math/special_functions/digamma.hpp>\n\n#include <nt2/include/constants/one.hpp>\n#include <nt2/include/constants/zero.hpp>\n#include <nt2/include/constants/mzero.hpp>\n#include <nt2/include/constants/inf.hpp>\n#include <nt2/include/constants/minf.hpp>\n#include <nt2/include/constants/nan.hpp>\n\nNT2_TEST_CASE_TPL ( digamma_real,  NT2_SIMD_REAL_TYPES)\n{\n  using nt2::digamma;\n  using nt2::tag::digamma_;\n  using boost::simd::native;\n  typedef BOOST_SIMD_DEFAULT_EXTENSION  ext_t;\n  typedef native<T,ext_t>                  vT;\n\n\n  // specific values tests\n  NT2_TEST_ULP_EQUAL(digamma(nt2::Zero<vT>()), nt2::Inf<vT>(), 0.5);\n  NT2_TEST_ULP_EQUAL(digamma(nt2::Mzero<vT>()), nt2::Minf<vT>(), 0.5);\n  NT2_TEST_ULP_EQUAL(digamma(nt2::One<vT>()), nt2::splat<vT>(-0.57721566490153286555), 0.5);\n  NT2_TEST_ULP_EQUAL(digamma(nt2::splat<vT>(1.4669020846486091614)),nt2::splat<vT>(boost::math::digamma(double(T(1.4669020846486091614)))), 0.5);\n  NT2_TEST_ULP_EQUAL(digamma(nt2::splat<vT>(1.461632133e+00)),      nt2::splat<vT>(boost::math::digamma(double(T(1.461632133e+00)))), 7.5);\n  NT2_TEST_ULP_EQUAL(digamma(nt2::splat<vT>(-3.5)),                 nt2::splat<vT>(boost::math::digamma(double(T(-3.5)))), 0.5);\n  NT2_TEST_ULP_EQUAL(digamma(nt2::splat<vT>(-3.51)),                nt2::splat<vT>(boost::math::digamma(double(T(-3.51)))), 0.5);\n  NT2_TEST_ULP_EQUAL(digamma(nt2::splat<vT>(-3.51)),                nt2::splat<vT>(boost::math::digamma(       T(-3.51))) , 0.5);\n  NT2_TEST_ULP_EQUAL(digamma(nt2::splat<vT>(-6)),  nt2::Nan<vT>(), 0.5);\n  NT2_TEST_ULP_EQUAL(digamma(nt2::splat<vT>(6)) ,   nt2::splat<vT>(1.706117668431801e+00), 1);\n\n}\n", "meta": {"hexsha": "2b93e9cd517b158033a129255c1bb70c66376a27", "size": 2477, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/core/euler/unit/simd/digamma.cpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/core/euler/unit/simd/digamma.cpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/core/euler/unit/simd/digamma.cpp", "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": 50.5510204082, "max_line_length": 145, "alphanum_fraction": 0.6338312475, "num_tokens": 790, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737473266735, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.4659069117245817}}
{"text": "#include \"scenario.h\"\r\n#include <iostream>\r\n#include <math.h>\r\n#include <boost/math/distributions/normal.hpp>\r\n\r\ndouble IndustryScenario::calcIndustryDraw(NormalRandomNumberGenerator& randGen, IndustryEntry& industryEntry)\r\n{\r\n\tdouble random1 = randGen.rand();\r\n\tdouble random2 = randGen.rand();\r\n\treturn (industryEntry.correl * random1) + (sqrt(1 - (industryEntry.correl*industryEntry.correl)) * random2);\r\n}\r\nIndustryScenario::IndustryScenario(NormalRandomNumberGenerator& randGen, IndustryEntry& industryEntry) :\r\n\tindustry(industryEntry.industry),\r\n\tindustryDraw(calcIndustryDraw(randGen, industryEntry))\r\n{}\r\nIndustryScenarioData::IndustryScenarioData(NormalRandomNumberGenerator& randGen, IndustryData& industryData)\r\n{\r\n\tfor (size_t i = 0, n = industryData.size(); i < n; i++)\r\n\t{\r\n\t\tIndustryEntry& entry = industryData[i];\r\n\t\tpush_back(IndustryScenario(randGen, entry));\r\n\t}\r\n}\r\nIndustryScenario* IndustryScenarioData::getByName(string industry)\r\n{\r\n\tfor (size_t i = 0, n = size(); i < n; i++)\r\n\t{\r\n\t\tIndustryScenario& entry = at(i);\r\n\t\tif (entry.industry == industry)\r\n\t\t\treturn &entry;\r\n\t}\r\n\treturn nullptr;\r\n}\r\nScenarioEntry::ScenarioEntry(NormalRandomNumberGenerator& randGen, IssuerEntry& issuerEntry, IndustryScenario& industryScenario, TransitionMatrix& transitionMatrix) :\r\n\tname(issuerEntry.name),\r\n\tpercentile(calculatePercentile(randGen, issuerEntry, industryScenario)),\r\n\trating(calculateRating(randGen, issuerEntry, industryScenario, transitionMatrix)) { }\r\nconst size_t ScenarioEntry::calculateRating(NormalRandomNumberGenerator& randGen, IssuerEntry& issuerEntry, IndustryScenario& industryScenario, TransitionMatrix& transitionMatrix)\r\n{\r\n\tsize_t rating = convertRating(issuerEntry.rating);\r\n\t//Assumes rating >= 0 && <= 7\r\n\tMatrixRow& row = transitionMatrix.cumSumMatrix[rating];\r\n\tsize_t i = row.size() - 1;\r\n\tfor(size_t j = 0, n = row.size(); j<n; j++)\r\n\t{\r\n\t\tif(percentile <= row[i])\r\n\t\t\treturn i;\r\n\t\ti--;\r\n\t}\r\n\tcout << \"Failed to find the rating. Using original rating: \" << to_string(rating) << endl;\r\n\tthrow new runtime_error(\"Bad rating\");\r\n}\r\nconst double ScenarioEntry::calculatePercentile(NormalRandomNumberGenerator& randGen, IssuerEntry& issuerEntry, IndustryScenario& industryScenario)\r\n{\r\n\tdouble random3 = randGen.rand();\r\n\tdouble assetReturn =  (issuerEntry.correl * industryScenario.industryDraw) + (sqrt(1 - (issuerEntry.correl*issuerEntry.correl)) * random3);\r\n\tboost::math::normal norm;\r\n\tdouble percentile = boost::math::cdf(norm, assetReturn);\r\n\treturn percentile;\r\n}\r\nconst size_t ScenarioEntry::convertRating(string rating)\r\n{\r\n\tsize_t convertedRating;\r\n\tif (rating == \"AAA\")\r\n\t\tconvertedRating = 0;\r\n\telse if (rating == \"AA\")\r\n\t\tconvertedRating = 1;\r\n\telse if (rating == \"A\")\r\n\t\tconvertedRating = 2;\r\n\telse if (rating == \"BBB\")\r\n\t\tconvertedRating = 3;\r\n\telse if (rating == \"BB\")\r\n\t\tconvertedRating = 4;\r\n\telse if (rating == \"B\")\r\n\t\tconvertedRating = 5;\r\n\telse if (rating == \"CCC\")\r\n\t\tconvertedRating = 6;\r\n\telse if (rating == \"C\")\r\n\t\tconvertedRating = 6;\r\n\telse if (rating == \"D\")\r\n\t\tconvertedRating = 7;\r\n\treturn convertedRating;\r\n}\r\nScenario::Scenario(NormalRandomNumberGenerator& randGen, IssuerData& issuerData, IndustryData& industryData, TransitionMatrix& transitionMatrix)\r\n{\r\n\tIndustryScenarioData industryScenarioData(randGen, industryData);\r\n\tfor (size_t i = 0, n = issuerData.size(); i < n; i++)\r\n\t{\r\n\t\tIssuerEntry& issuerEntry = issuerData.at(i);\r\n\t\tIndustryScenario* industryScenario = industryScenarioData.getByName(issuerEntry.industry);\r\n\t\tif (!industryScenario)\r\n\t\t\tthrow runtime_error(\"No known industry entry for \\\"\" + issuerEntry.industry + \"\\\"\");\r\n\t\tpush_back(ScenarioEntry(randGen, issuerEntry, *industryScenario, transitionMatrix));\r\n\t}\r\n}\r\nScenarioEntry* Scenario::getByName(string name)\r\n{\r\n\tfor (size_t i = 0, n = size(); i < n; i++)\r\n\t{\r\n\t\tScenarioEntry& entry = at(i);\r\n\t\tif (entry.name == name)\r\n\t\t\treturn &entry;\r\n\t}\r\n\treturn nullptr;\r\n}\r\n", "meta": {"hexsha": "e5020d9968336014fdf4f3ee13fe6c0f13a5ad4d", "size": 3919, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CreditMetrics/scenario.cpp", "max_stars_repo_name": "mbarnhill/CreditMetrics", "max_stars_repo_head_hexsha": "1086f563ca8ea957b5b0ff76e1f87fa676a53da1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CreditMetrics/scenario.cpp", "max_issues_repo_name": "mbarnhill/CreditMetrics", "max_issues_repo_head_hexsha": "1086f563ca8ea957b5b0ff76e1f87fa676a53da1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CreditMetrics/scenario.cpp", "max_forks_repo_name": "mbarnhill/CreditMetrics", "max_forks_repo_head_hexsha": "1086f563ca8ea957b5b0ff76e1f87fa676a53da1", "max_forks_repo_licenses": ["Apache-2.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.9716981132, "max_line_length": 180, "alphanum_fraction": 0.7231436591, "num_tokens": 978, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744939732856, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.46589699311926464}}
{"text": "/**\n *          Copyright Matthias Walter 2010.\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 MATRIX_HPP_\n#define MATRIX_HPP_\n\n#include <boost/numeric/ublas/matrix.hpp>\n\n#include \"matrix_transposed.hpp\"\n#include <iomanip>\n\nnamespace unimod\n{\n\n  /**\n   * Exception to indicate a pivot on a zero element.\n   */\n\n  class matrix_binary_pivot_exception: public std::exception\n  {\n  public:\n    const char* what() const throw ()\n    {\n      return \"Cannot pivot on a zero entry!\";\n    }\n  };\n\n  /**\n   * Free function to set a matrix value of a permuted matrix.\n   *\n   * @param matrix The permuted matrix\n   * @param row Row index\n   * @param column Column index\n   * @param value New value\n   */\n\n  template <typename MatrixType>\n  inline void matrix_set_value(MatrixType& matrix, size_t row, size_t column, typename MatrixType::value_type value)\n  {\n    matrix(row, column) = value;\n  }\n\n  /**\n   * Dummy function for the version with writable orignal matrix.\n   */\n\n  template <typename MatrixType>\n  inline void matrix_set_value(const MatrixType& matrix, size_t row, size_t column, typename MatrixType::value_type value)\n  {\n    assert (false);\n  }\n\n  /**\n   * Free function to permute two rows of a permuted matrix.\n   *\n   * @param matrix The permuted matrix\n   * @param index1 First index\n   * @param index2 Second index\n   */\n\n  template <typename MatrixType>\n  inline void matrix_permute1(MatrixType& matrix, size_t index1, size_t index2)\n  {\n    for (size_t index = 0; index < matrix.size2(); ++index)\n    {\n      std::swap(matrix(index1, index), matrix(index2, index));\n    }\n  }\n\n  /**\n   * Free function to permute two columns of a permuted matrix.\n   *\n   * @param matrix The permuted matrix\n   * @param index1 First index\n   * @param index2 Second index\n   */\n\n  template <typename MatrixType>\n  inline void matrix_permute2(MatrixType& matrix, size_t index1, size_t index2)\n  {\n    for (size_t index = 0; index < matrix.size1(); ++index)\n    {\n      std::swap(matrix(index, index1), matrix(index, index2));\n    }\n  }\n\n  /**\n   * Free function to perform a binary pivot on a matrix.\n   *\n   * @param matrix The matrix\n   * @param i Row index\n   * @param j Column index\n   */\n\n  template <typename MatrixType>\n  void matrix_binary_pivot(MatrixType& matrix, size_t i, size_t j)\n  {\n    typedef typename MatrixType::value_type value_type;\n    const value_type& base_value = matrix(i, j);\n\n    if (base_value == 0)\n    {\n      throw matrix_binary_pivot_exception();\n    }\n\n    for (size_t row = 0; row < matrix.size1(); ++row)\n    {\n      if (row == i)\n      {\n        continue;\n      }\n      const value_type& first = matrix(row, j);\n      if (first == 0)\n      {\n        continue;\n      }\n\n      for (size_t column = 0; column < matrix.size2(); ++column)\n      {\n        if (column == j)\n        {\n          continue;\n        }\n        const value_type& second = matrix(i, column);\n        if (second == 0)\n        {\n          continue;\n        }\n        matrix(row, column) = 1 - matrix(row, column);\n      }\n    }\n  }\n\n  /**\n   * Free function to perform a ternary pivot on a matrix.\n   *\n   * @param matrix The matrix\n   * @param i Row index\n   * @param j Column index\n   */\n\n  template <typename MatrixType>\n  void matrix_ternary_pivot(MatrixType& matrix, size_t i, size_t j)\n  {\n    typedef typename MatrixType::value_type value_type;\n    const value_type& base_value = matrix(i, j);\n\n    if (base_value == 0)\n    {\n      throw matrix_binary_pivot_exception();\n    }\n\n    for (size_t row = 0; row < matrix.size1(); ++row)\n    {\n      if (row == i)\n      {\n        continue;\n      }\n      const value_type& first = matrix(row, j);\n      if (first == 0)\n      {\n        continue;\n      }\n\n      for (size_t column = 0; column < matrix.size2(); ++column)\n      {\n        if (column == j)\n        {\n          continue;\n        }\n        const value_type& second = matrix(i, column);\n        if (second == 0)\n        {\n          continue;\n        }\n        value_type value = matrix(row, column) - first * second / base_value;\n        while (value > 1)\n          value -= 3;\n        while (value < -1)\n          value += 3;\n        matrix(row, column) = value;\n      }\n    }\n  }\n\n  /**\n   * Counts how many of the rows in the specified range have a property.\n   *\n   * @param matrix The given matrix\n   * @param row_first First row in range\n   * @param row_beyond Beyond row in range\n   * @param column_first First column for property check\n   * @param column_beyond Beyond column for property check\n   * @param check Property checking routine\n   * @return Number of rows with the property\n   */\n\n  template <typename MatrixType, typename PropertyCheck>\n  inline size_t matrix_count_property_row_series(const MatrixType& matrix, size_t row_first, size_t row_beyond, size_t column_first,\n      size_t column_beyond, PropertyCheck check)\n  {\n    for (size_t row = row_first; row < row_beyond; ++row)\n    {\n      for (size_t column = column_first; column < column_beyond; ++column)\n        check(matrix(row, column));\n      if (!check())\n        return row - row_first;\n    }\n    return row_beyond - row_first;\n  }\n\n  /**\n   * Counts how many of the columns in the specified range have a property.\n   *\n   * @param matrix The given matrix\n   * @param row_first First column for property check\n   * @param row_beyond Beyond column for property check\n   * @param column_first First row in range\n   * @param column_beyond Beyond row in range\n   * @param check Property checking routine\n   * @return Number of rows with the property\n   */\n\n  template <typename MatrixType, typename PropertyCheck>\n  inline size_t matrix_count_property_column_series(const MatrixType& matrix, size_t row_first, size_t row_beyond, size_t column_first,\n      size_t column_beyond, PropertyCheck check)\n  {\n    matrix_transposed <const MatrixType> transposed(matrix);\n    return matrix_count_property_row_series(transposed, column_first, column_beyond, row_first, row_beyond, check);\n  }\n\n  /**\n   * Prints a matrix\n   *\n   * @param matrix The matrix to be printed\n   */\n\n  template <typename MatrixType>\n  inline void matrix_print(const MatrixType& matrix)\n  {\n    for (size_t row = 0; row < matrix.size1(); ++row)\n    {\n      for (size_t column = 0; column < matrix.size2(); ++column)\n      {\n        std::cout << \" \" << std::setw(2) << matrix(row, column);\n      }\n      std::cout << \"\\n\";\n    }\n    std::cout << std::flush;\n  }\n\n  /**\n   * Tests two matrices for exact equality.\n   *\n   * @param matrix1 First matrix\n   * @param matrix2 Second matrix\n   * @return true if and only if all entries match\n   */\n\n  template <typename MatrixType1, typename MatrixType2>\n  inline bool matrix_equals(const MatrixType1& matrix1, const MatrixType2& matrix2)\n  {\n    if (matrix1.size1() != matrix2.size1())\n      return false;\n    if (matrix1.size2() != matrix2.size2())\n      return false;\n\n    for (size_t row = 0; row < matrix1.size1(); ++row)\n    {\n      for (size_t column = 0; column < matrix1.size2(); ++column)\n      {\n        if (matrix1(row, column) != matrix2(row, column))\n          return false;\n      }\n    }\n    return true;\n  }\n\n  template <typename Matrix>\n  bool matrix_row_zero(const Matrix& matrix, size_t row, size_t column_first, size_t column_beyond)\n  {\n    for (size_t c = column_first; c != column_beyond; ++c)\n      if (matrix(row, c) != 0)\n        return false;\n    return true;\n  }\n\n  template <typename Matrix>\n  bool matrix_column_zero(const Matrix& matrix, size_t column, size_t row_first, size_t row_beyond)\n  {\n    return matrix_row_zero(make_transposed_matrix(matrix), column, row_first, row_beyond);\n  }\n\n  template <typename Matrix>\n  bool find_smallest_nonzero_matrix_entry(const Matrix& matrix, size_t row_first, size_t row_beyond, size_t column_first, size_t column_beyond,\n      size_t& row, size_t& column)\n  {\n    bool result = false;\n    int current_value = 0;\n    for (size_t r = row_first; r != row_beyond; ++r)\n    {\n      for (size_t c = column_first; c != column_beyond; ++c)\n      {\n        int value = matrix(r, c);\n        if (value == 0)\n          continue;\n\n        value = value >= 0 ? value : -value;\n\n        if (!result || value < current_value)\n        {\n          result = true;\n          row = r;\n          column = c;\n          current_value = value;\n        }\n      }\n    }\n    return result;\n  }\n\n  template <typename Matrix1, typename Matrix2>\n  bool equals(const Matrix1& first, const Matrix2& second)\n  {\n    if (first.size1() != second.size1())\n      return false;\n    if (first.size2() != second.size2())\n      return false;\n    for (size_t r = 0; r < first.size1(); ++r)\n    {\n      for (size_t c = 0; c < first.size2(); ++c)\n      {\n        if (first(r, c) != second(r, c))\n          return false;\n      }\n    }\n    return true;\n  }\n}\n\n#endif /* MATRIX_HPP_ */\n", "meta": {"hexsha": "cd74d56ef4b15114a37e6b873969cf8088504255", "size": 8941, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "unimodularity-library-1.2c/src/matrix.hpp", "max_stars_repo_name": "vios-fish/CompetitiveProgramming", "max_stars_repo_head_hexsha": "6953f024e4769791225c57ed852cb5efc03eb94b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-07-05T21:14:40.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-08T01:33:12.000Z", "max_issues_repo_path": "src/matrix.hpp", "max_issues_repo_name": "vbraun/unimodularity-library", "max_issues_repo_head_hexsha": "d329571908a84ed98713721a2fe873ad534901c8", "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/matrix.hpp", "max_forks_repo_name": "vbraun/unimodularity-library", "max_forks_repo_head_hexsha": "d329571908a84ed98713721a2fe873ad534901c8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.8410404624, "max_line_length": 143, "alphanum_fraction": 0.6191701152, "num_tokens": 2317, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834648, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4658969880533766}}
{"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_FILTERING_FILTER_ROTATION_HPP\n#define PIC_FILTERING_FILTER_ROTATION_HPP\n\n#include \"../filtering/filter.hpp\"\n#include \"../image_samplers/image_sampler_bilinear.hpp\"\n\n#ifndef PIC_DISABLE_EIGEN\n\n#ifndef PIC_EIGEN_NOT_BUNDLED\n    #include \"../externals/Eigen/Dense\"\n    #include \"../externals/Eigen/Geometry\"\n#else\n    #include <Eigen/Dense>\n    #include <Eigen/Geometry>\n#endif\n\n#endif\n\nnamespace pic {\n#ifndef PIC_DISABLE_EIGEN\n\n/**\n * @brief The FilterRotation class\n */\nclass FilterRotation: public Filter\n{\nprotected:\n\n    ImageSamplerBilinear isb;\n\n    //rotation\n    float angleX, angleY, angleZ;\n\n    //the rotation matrix of (theta, phi)\n    Eigen::Matrix3f mtxRot, mtxRot_inv;\n\n    /**\n     * @brief ProcessBBox\n     * @param dst\n     * @param src\n     * @param box\n     */\n    void ProcessBBox(Image *dst, ImageVec src, BBox *box)\n    {\n        float c1 = C_PI   / dst->heightf;\n        float c2 = C_PI_2 / dst->widthf;\n\n        for(int j = box->y0; j < box->y1; j++) {\n            float theta = float(j) * c1;\n            float sinTheta = sinf(theta);\n            float cosTheta = cosf(theta);\n\n            Eigen::Vector3f d;\n\n            for(int i = box->x0; i < box->x1; i++) {\n                float phi = float(i) * c2;\n\n                d[0] = sinTheta * cosf(phi);\n                d[1] = cosTheta;\n                d[2] = sinTheta * sinf(phi);\n\n                auto Rd = (mtxRot_inv * d).normalized();\n\n\n          /*    printf(\"\\nwrong: %f correct: %f Rd: %f\\n\",\n                       sinTheta * cosf(phi + this->phi),\n                       sinTheta * cosf(phi - this->phi),\n                       Rd[0]\n                       );*/\n\n                float xt = 1.0f - ((atan2f(Rd[2], -Rd[0]) * C_INV_PI) * 0.5f + 0.5f);\n                float yt = (acosf(Rd[1]) * C_INV_PI);\n\n                float *data_dst = (*dst)(i, j);\n                isb.SampleImage(src[0], xt, yt, data_dst);\n            }\n        }\n    }\n\n    /**\n     * @brief fromAnglesToVector\n     * @param theta\n     * @param phi\n     * @return\n     */\n    Eigen::Vector3f fromAnglesToVector(float theta, float phi)\n    {\n        Eigen::Vector3f ret;\n        float sinTheta = sinf(theta);\n        float cosTheta = cosf(theta);\n\n        ret[0] = sinTheta * cosf(phi);\n        ret[1] = cosTheta;\n        ret[2] = sinTheta * sinf(phi);\n\n        return ret;\n    }\n\npublic:\n\n    /**\n     * @brief FilterRotation\n     */\n    FilterRotation() : Filter()\n    {\n        update(0.0f, 0.0f, 0.0f);\n    }\n\n    /**\n     * @brief FilterRotation\n     * @param angleX\n     * @param angleY\n     * @param angleZ\n     */\n    FilterRotation(float angleX, float angleY, float angleZ) : Filter()\n    {\n        update(angleX, angleY, angleZ);\n    }\n\n    /**\n     * @brief FilterRotation\n     * @param mtx\n     */\n    FilterRotation(Eigen::Matrix3f mtx) : Filter()\n    {\n        update(mtx);\n    }\n\n    /**\n     * @brief update\n     * @param angleX\n     * @param angleY\n     * @param angleZ\n     */\n    void update(float angleX, float angleY, float angleZ)\n    {\n        this->angleX = angleX;\n        this->angleY = angleY;\n        this->angleZ = angleZ;\n\n        Eigen::Matrix3f mtx;\n        mtx = Eigen::AngleAxisf(angleZ, Eigen::Vector3f::UnitZ()) *\n              Eigen::AngleAxisf(angleY, Eigen::Vector3f::UnitY()) *\n              Eigen::AngleAxisf(angleX, Eigen::Vector3f::UnitX());\n\n        update(mtx);\n    }\n\n    /**\n     * @param theta\n     * @brief update\n     * @param phi\n     */\n    void update(Eigen::Matrix3f mtx)\n    {\n        this->mtxRot = mtx;\n        this->mtxRot_inv = Eigen::Transpose< Eigen::Matrix3f >(mtx);\n    }\n\n    /**\n     * @brief getMtxRot\n     * @return\n     */\n    Eigen::Matrix3f getMtxRot()\n    {\n        return mtxRot;\n    }\n\n    /**\n     * @brief execute\n     * @param imgIn\n     * @param imgOut\n     * @param theta\n     * @param phi\n     * @return\n     */\n    static Image *execute(Image *imgIn, Image *imgOut, float angleX, float angleY, float angleZ)\n    {\n        FilterRotation fltRot(angleX, angleY, angleZ);\n        return fltRot.Process(Single(imgIn), imgOut);\n    }\n\n    /**\n     * @brief execute\n     * @param imgIn\n     * @param imgOut\n     * @param mtx\n     * @return\n     */\n    static Image *execute(Image *imgIn, Image *imgOut, Eigen::Matrix3f &mtx)\n    {\n        FilterRotation fltRot(mtx);\n        return fltRot.Process(Single(imgIn), imgOut);\n    }\n};\n\n#endif\n\n} // end namespace pic\n\n#endif /* PIC_FILTERING_FILTER_ROTATION_HPP */\n\n", "meta": {"hexsha": "38b0daa108004e1e4ee4c88815693f7bcf1645a0", "size": 4843, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/filtering/filter_rotation.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/filtering/filter_rotation.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/filtering/filter_rotation.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": 22.0136363636, "max_line_length": 96, "alphanum_fraction": 0.5490398513, "num_tokens": 1368, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038221, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4658969779216001}}
{"text": "/**\n * \\file      ekf-flexibility-estimator-base.hpp\n * \\author    Mehdi Benallegue\n * \\date      2013\n * \\brief     Declare the class of the flexibility estimation using the extended\n *            Kalman Filter.\n *\n * \\details\n *\n *\n */\n\n#ifndef FLEXIBILITYESTIMATION_EKFFLEXIBILITYESTIMATORBASE_H\n#define FLEXIBILITYESTIMATION_EKFFLEXIBILITYESTIMATORBASE_H\n\n#include <boost/utility.hpp>\n\n#include <state-observation/api.h>\n#include <state-observation/observer/extended-kalman-filter.hpp>\n\n#include <state-observation/flexibility-estimation/flexibility-estimator-base.hpp>\n\nnamespace stateObservation\n{\nnamespace flexibilityEstimation\n{\n/**\n * \\class  EKFFlexibilityEstimatorBase\n * \\brief  This class is the base class of the flexibility estimators that\n *         use an extended Kalman Filter. Several methods require to be overloaded\n *         to derive an implementation from this base class.\n *\n */\n\nclass STATE_OBSERVATION_DLLAPI EKFFlexibilityEstimatorBase : public FlexibilityEstimatorBase\n{\npublic:\n  /// The constructor.\n  ///  \\li stateSize : size of the state vector\n  ///  \\li measurementSize : size of the measurements vector\n  ///  \\li inputSize : size of the input vector\n  ///  \\li dx gives the derivation step for a finite differences derivation method\n\n  EKFFlexibilityEstimatorBase(Index stateSize,\n                              Index measurementSize,\n                              Index inputSize,\n                              const Vector & dx = Vector::Zero(0));\n\n  /// virtual destructor\n  virtual ~EKFFlexibilityEstimatorBase();\n\n  /// Sets a value of the flexibility x_k provided from another source\n  /// can be used for initialization of the estimator\n  /// This is a pure virtual function that requires to be overloaded in\n  /// implementation\n  virtual void setFlexibilityGuess(const Matrix &) = 0;\n\n  /// Sets the covariance matrix of the flexibility Guess\n  virtual void setFlexibilityCovariance(const Matrix & P);\n\n  /// Gets the covariance matrix of the flexibility\n  virtual Matrix getFlexibilityCovariance() const;\n\n  /// Sets the covariance matrices for the process noises\n  /// \\li Q process noise\n  virtual void setProcessNoiseCovariance(const Matrix & Q);\n\n  /// Sets the covariance matrices for the sensor noises\n  /// \\li R sensor noise\n  virtual void setMeasurementNoiseCovariance(const Matrix & R);\n\n  /// gets the covariance matrices for the process noises\n  virtual Matrix getProcessNoiseCovariance() const;\n\n  /// gets the covariance matrices for the sensor noises\n  virtual Matrix getMeasurementNoiseCovariance() const;\n\n  /// Sets the value of the next sensor measurement y_{k+1}\n  virtual void setMeasurement(const Vector & y);\n\n  virtual Vector getMeasurement();\n\n  /// Sets the value of the next input for the state process dynamics\n  /// i.e. : gives u_k such that x_{k+1} = f(x_k,u_k)\n  virtual void setInput(const Vector & u);\n\n  /// Sets the value of the next  measurement\n  /// i.e. : gives u_{k+1} such that y_{k+1}=h(x_{k+1},u_{k+1})\n  virtual void setMeasurementInput(const Vector & u);\n\n  virtual Vector getInput();\n\n  virtual Vector getMeasurementInput();\n\n  /// Gets an estimation of the flexibility in the form of a state vector \\hat{x_{k+1}}\n  virtual const Vector & getFlexibilityVector();\n\n  /// Gets an estimation of the flexibility in the form of a homogeneous matrix\n  virtual Matrix4 getFlexibility() = 0;\n\n  /// Gets a const reference on the extended Kalman filter\n  virtual const stateObservation::ExtendedKalmanFilter & getEKF() const;\n\n  /// Gets a reference on the extended Kalman filter\n  virtual stateObservation::ExtendedKalmanFilter & getEKF();\n\n  /// Gets the state size\n  /// this method is pure virtual and reauires to be overloaded in implementation\n  virtual Index getStateSize() const = 0;\n\n  /// Gets the measurements size\n  /// this method is pure virtual and reauires to be overloaded in implementation\n  virtual Index getMeasurementSize() const = 0;\n\n  /// Gets the input size\n  /// this method is pure virtual and reauires to be overloaded in implementation\n  virtual Index getInputSize() const = 0;\n\n  /// Gets a simulation of the\n  virtual Vector getSimulatedMeasurement();\n\n  /// Resets the covariance matrices to their original values\n  virtual void resetCovarianceMatrices() = 0;\n\n  /// Get the last vector of inovation of the Kalman filter\n  virtual Vector getInnovation();\n\n  /// Get the simulated measurement of the predicted state\n  virtual Vector getPredictedMeasurement();\n\n  /// Get the predicted state\n  virtual Vector getPrediction();\n\n  /// Get the last simulated measurement\n  virtual Vector getLastPredictedMeasurement();\n\n  /// Get the last predicted state\n  virtual Vector getLastPrediction();\n\nprotected:\n  virtual void setJacobians(const Matrix & A, const Matrix & C);\n\n  virtual void useFiniteDifferencesJacobians(Vector dx);\n\n  stateObservation::ExtendedKalmanFilter ekf_;\n\n  bool finiteDifferencesJacobians_;\n\n  Vector dx_;\n\n  Vector lastX_;\n\n  TimeIndex k_;\n\nprivate:\n};\n} // namespace flexibilityEstimation\n} // namespace stateObservation\n#endif // FLEXIBILITYESTIMATION_EKFFLEXIBILITYESTIMATORBASE_H\n", "meta": {"hexsha": "d30e8c1f50af72bdfcbae390ed49d0c16c18496b", "size": 5122, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/state-observation/flexibility-estimation/ekf-flexibility-estimator-base.hpp", "max_stars_repo_name": "mmurooka/state-observation", "max_stars_repo_head_hexsha": "4a6b8eb6fa841cf706a074132fb24b50e8534e35", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2018-11-01T16:10:48.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-09T00:03:46.000Z", "max_issues_repo_path": "include/state-observation/flexibility-estimation/ekf-flexibility-estimator-base.hpp", "max_issues_repo_name": "mmurooka/state-observation", "max_issues_repo_head_hexsha": "4a6b8eb6fa841cf706a074132fb24b50e8534e35", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2019-10-18T09:06:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-26T04:22:09.000Z", "max_forks_repo_path": "include/state-observation/flexibility-estimation/ekf-flexibility-estimator-base.hpp", "max_forks_repo_name": "mmurooka/state-observation", "max_forks_repo_head_hexsha": "4a6b8eb6fa841cf706a074132fb24b50e8534e35", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2018-06-19T09:00:17.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-11T06:14:51.000Z", "avg_line_length": 32.0125, "max_line_length": 92, "alphanum_fraction": 0.7336977743, "num_tokens": 1177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744584140003, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4658969728557116}}
{"text": "/**\n * @file   NumpyEigenConverter.hpp\n * @author Paul Furgale <paul.furgale@utoronto.ca>\n * @date   Fri Feb  4 11:17:25 2011\n * \n * @brief  Classes to support conversion from numpy arrays in Python\n *         to Eigen3 matrices in c++\n * \n * \n */\n\n#ifndef NUMPY_EIGEN_CONVERTER_HPP\n#define NUMPY_EIGEN_CONVERTER_HPP\n\n#include <numpy_eigen/boost_python_headers.hpp>\n//#include <iostream>\n\n\n#define PY_ARRAY_UNIQUE_SYMBOL NP_Eigen_AS\n// #include <numpy/npy_no_deprecated_api.h>\n#include <numpy/arrayobject.h> \n\n#include \"type_traits.hpp\"\n#include <boost/lexical_cast.hpp>\n#include \"copy_routines.hpp\"\n\n\n\n/**\n * @class NumpyEigenConverter\n * @tparam the Eigen3 matrix type this class is specialized for\n * \n * adapted from http://misspent.wordpress.com/2009/09/27/how-to-write-boost-python-converters/\n * General help available http://docs.scipy.org/doc/numpy/reference/c-api.array.html\n *\n * To use: \n * \n * #include <NumpyEigenConverter.hpp>\n * \n * \n * BOOST_PYTHON_MODULE(libmy_module_python)\n * {\n *   // The converters will cause a segfault unless import_array() is called before the first one\n *   import_array();\n *   NumpyEigenConverter<Eigen::Matrix< double, 1, 1 > >::register_converter();\n *   NumpyEigenConverter<Eigen::Matrix< double, 2, 1 > >::register_converter();\n * }\n * \n */\ntemplate<typename EIGEN_MATRIX_T>\nstruct NumpyEigenConverter\n{\n\n  typedef EIGEN_MATRIX_T matrix_t;\n  typedef typename matrix_t::Scalar scalar_t;\n\n  enum {\n    RowsAtCompileTime = matrix_t::RowsAtCompileTime,\n    ColsAtCompileTime = matrix_t::ColsAtCompileTime,\n    MaxRowsAtCompileTime = matrix_t::MaxRowsAtCompileTime,\n    MaxColsAtCompileTime = matrix_t::MaxColsAtCompileTime,\n    NpyType = TypeToNumPy<scalar_t>::NpyType,\n    //Flags = ei_compute_matrix_flags<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols>::ret,\n    //CoeffReadCost = NumTraits<Scalar>::ReadCost,\n    Options = matrix_t::Options\n    //InnerStrideAtCompileTime = 1,\n    //OuterStrideAtCompileTime = (Options&RowMajor) ? ColsAtCompileTime : RowsAtCompileTime\n  };\n\n  static std::string castSizeOption(int option)\n  {\n    if(option == Eigen::Dynamic)\n      return \"Dynamic\";\n    else\n      return boost::lexical_cast<std::string>(option);\n  }\n\n  static std::string toString()\n  {\n    return std::string() + \"Eigen::Matrix<\" + TypeToNumPy<scalar_t>::typeString() + \", \" +\n      castSizeOption(RowsAtCompileTime) + \", \" +\n      castSizeOption(ColsAtCompileTime) + \", \" +\n      boost::lexical_cast<std::string>((int)Options) + \", \" +\n      castSizeOption(MaxRowsAtCompileTime) + \", \" +\n      castSizeOption(MaxColsAtCompileTime) + \">\";\n  }\n\n  // The \"Convert from C to Python\" API\n  static PyObject * convert(const matrix_t & M)\n  {\n    PyObject * P = NULL;\n    if(RowsAtCompileTime == 1 || ColsAtCompileTime == 1)\n      {\n\t// Create a 1D array\n\tnpy_intp dimensions[1];\n\tdimensions[0] = M.size();\n\tP = PyArray_SimpleNew(1, dimensions, TypeToNumPy<scalar_t>::NpyType);\t    \t\n\tnumpyTypeDemuxer< CopyEigenToNumpyVector<const matrix_t> >(&M,P);\t\n      }\n    else\n      {\n\t// create a 2D array.\n\tnpy_intp dimensions[2];\n\tdimensions[0] = M.rows();\n\tdimensions[1] = M.cols();\n\tP = PyArray_SimpleNew(2, dimensions, TypeToNumPy<scalar_t>::NpyType);\n\tnumpyTypeDemuxer< CopyEigenToNumpyMatrix<const matrix_t> >(&M,P);\t\n      }\n    \n    // incrementing the reference seems to cause a memory leak.\n    // boost::python::incref(P);\n    // This agrees with the sample code found here:\n    // http://mail.python.org/pipermail/cplusplus-sig/2008-October/013825.html\n    return P;\n  }\n\n  static bool isDimensionValid(int requestedSize, int sizeAtCompileTime, int maxSizeAtCompileTime)\n  {\n    bool valid = true;\n    if(sizeAtCompileTime == Eigen::Dynamic)\n      {\n\t// Check for dynamic fixed size\n\t// http://eigen.tuxfamily.org/dox-devel/TutorialMatrixClass.html#TutorialMatrixOptTemplParams\n\tif(!(maxSizeAtCompileTime == Eigen::Dynamic || requestedSize <= maxSizeAtCompileTime))\n\t  {\n\t    valid = false;\n\t  }\n      }\n    else if(sizeAtCompileTime != requestedSize)\n      {\n\tvalid = false;\n      }\n    return valid;\n  }\n      \n  static void checkMatrixSizes(PyObject * obj_ptr)\n  {\n    int rows = PyArray_DIM(obj_ptr, 0);\n    int cols = PyArray_DIM(obj_ptr, 1);\n\n    bool rowsValid = isDimensionValid(rows, RowsAtCompileTime, MaxRowsAtCompileTime);\n    bool colsValid = isDimensionValid(cols, ColsAtCompileTime, MaxColsAtCompileTime);\n    if(!rowsValid || !colsValid)\n    {\n\tTHROW_TYPE_ERROR(\"Can not convert \" << npyArrayTypeString(obj_ptr) << \" to \" << toString() \n\t\t\t << \". Mismatched sizes.\");\n      }\n  }\n\n  static void checkRowVectorSizes(PyObject * obj_ptr, int cols)\n  {\n    if(!isDimensionValid(cols, ColsAtCompileTime, MaxColsAtCompileTime))\n      {\n\tTHROW_TYPE_ERROR(\"Can not convert \" << npyArrayTypeString(obj_ptr) << \" to \" << toString() \n\t\t\t << \". Mismatched sizes.\");\n      }\n  }\n\n  static void checkColumnVectorSizes(PyObject * obj_ptr, int rows)\n  {\n    // Check if the type can accomidate one column.\n    if(ColsAtCompileTime == Eigen::Dynamic || ColsAtCompileTime == 1)\n      {\n\tif(!isDimensionValid(rows, RowsAtCompileTime, MaxRowsAtCompileTime))\n\t  {\n\t    THROW_TYPE_ERROR(\"Can not convert \" << npyArrayTypeString(obj_ptr) << \" to \" << toString() \n\t\t\t     << \". Mismatched sizes.\");\n\t  }\n      }\n    else\n      {\n\tTHROW_TYPE_ERROR(\"Can not convert \" << npyArrayTypeString(obj_ptr) << \" to \" << toString() \n\t\t\t << \". Mismatched sizes.\");\n      }\n\n  }\n\n  static void checkVectorSizes(PyObject * obj_ptr)\n  {\n\tint size = PyArray_DIM(obj_ptr, 0);\n\n    // If the number of rows is fixed at 1, assume that is the sense of the vector.\n    // Otherwise, assume it is a column.\n    if(RowsAtCompileTime == 1)\n      {\n\tcheckRowVectorSizes(obj_ptr, size);\n      }\n    else\n      {\n\tcheckColumnVectorSizes(obj_ptr, size);\n      }\n  }\n\n    \n  static void* convertible(PyObject *obj_ptr)\n  {\n    // Check for a null pointer.\n    if(!obj_ptr)\n      {\n        //THROW_TYPE_ERROR(\"PyObject pointer was null\");\n        return 0;\n      }\n\n    // Make sure this is a numpy array.\n    if (!PyArray_Check(obj_ptr))\n      {\n        //THROW_TYPE_ERROR(\"Conversion is only defined for numpy array and matrix types\");\n        return 0;\n      }\n\n    // Check the type of the array.\n    int npyType = PyArray_ObjectType(obj_ptr, 0);\n    \n    if(!TypeToNumPy<scalar_t>::canConvert(npyType))\n      {\n        //THROW_TYPE_ERROR(\"Can not convert \" << npyArrayTypeString(obj_ptr) << \" to \" << toString() \n        //                 << \". Mismatched types.\");\n        return 0;\n      }\n\n    \n\n    // Check the array dimensions.\n    int nd = PyArray_NDIM(obj_ptr);\n    \n    if(nd != 1 && nd != 2)\n      {\n\tTHROW_TYPE_ERROR(\"Conversion is only valid for arrays with 1 or 2 dimensions. Argument has \" << nd << \" dimensions\");\n      }\n\n    if(nd == 1)\n      {\n\tcheckVectorSizes(obj_ptr);\n      }\n    else \n      {\n\t// Two-dimensional matrix type.\n\tcheckMatrixSizes(obj_ptr);\n      }\n\n\n    return obj_ptr;\n  }\n  \n\n  static void construct(PyObject *obj_ptr, boost::python::converter::rvalue_from_python_stage1_data *data)\n  {\n    boost::python::converter::rvalue_from_python_storage<matrix_t> * matData = reinterpret_cast<boost::python::converter::rvalue_from_python_storage<matrix_t> * >(data);\n    void* storage = matData->storage.bytes;\n    \n    // Make sure storage is 16byte aligned. With help from code from Memory.h\n    void * aligned = reinterpret_cast<void*>((reinterpret_cast<size_t>(storage) & ~(size_t(15))) + 16);\n    \n    matrix_t * Mp = new (aligned) matrix_t();\n    // Stash the memory chunk pointer for later use by boost.python\n    // This signals boost::python that the new value must be deleted eventually\n    data->convertible = storage;\n\n    \n    // std::cout << \"Creating aligned pointer \" << aligned << \" from storage \" << storage << std::endl;\n    // std::cout << \"matrix size: \" << sizeof(matrix_t) << std::endl;\n    // std::cout << \"referent size: \" << boost::python::detail::referent_size< matrix_t & >::value << std::endl;\n    // std::cout << \"sizeof(storage): \" << sizeof(matData->storage) << std::endl;\n    // std::cout << \"sizeof(bytes): \" << sizeof(matData->storage.bytes) << std::endl;\n    \n    \n\n    matrix_t & M = *Mp;\n\n    int nd = PyArray_NDIM(obj_ptr);\n    if(nd == 1)\n      {\n\tint size = PyArray_DIM(obj_ptr, 0);\n\t// This is a vector type\n\tif(RowsAtCompileTime == 1)\n\t  {\n\t    // Row Vector\n\t    M.resize(1,size);\n\t  }\n\telse\n\t  {\n\t    // Column Vector\n\t    M.resize(size,1);\n\t  }\n\tnumpyTypeDemuxer< CopyNumpyToEigenVector<matrix_t> >(&M,obj_ptr);\t\n      }\n    else\n      {\n\tint rows = PyArray_DIM(obj_ptr, 0);\n\tint cols = PyArray_DIM(obj_ptr, 1);\n\t\n\tM.resize(rows,cols);\n\tnumpyTypeDemuxer< CopyNumpyToEigenMatrix<matrix_t> >(&M,obj_ptr);\t\n      }\n\n    \n\n\n  }\n\n\n  // The registration function.\n  static void register_converter()\n  {\n    boost::python::to_python_converter<matrix_t,NumpyEigenConverter>();\n    boost::python::converter::registry::push_back(\n\t\t\t\t\t\t  &NumpyEigenConverter::convertible,\n\t\t\t\t\t\t  &NumpyEigenConverter::construct,\n\t\t\t\t\t\t  boost::python::type_id<matrix_t>());\n\n  }\n  \n};\n\n\n\n\n#endif /* NUMPY_EIGEN_CONVERTER_HPP */\n", "meta": {"hexsha": "230148efb8dc167f999a788b2f538db0a404a33b", "size": 9103, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Schweizer-Messer/numpy_eigen/include/numpy_eigen/NumpyEigenConverter.hpp", "max_stars_repo_name": "huangqinjin/kalibr", "max_stars_repo_head_hexsha": "5bc7b73ce8185c734152def716e7d657a2736ec5", "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": "Schweizer-Messer/numpy_eigen/include/numpy_eigen/NumpyEigenConverter.hpp", "max_issues_repo_name": "huangqinjin/kalibr", "max_issues_repo_head_hexsha": "5bc7b73ce8185c734152def716e7d657a2736ec5", "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": "Schweizer-Messer/numpy_eigen/include/numpy_eigen/NumpyEigenConverter.hpp", "max_forks_repo_name": "huangqinjin/kalibr", "max_forks_repo_head_hexsha": "5bc7b73ce8185c734152def716e7d657a2736ec5", "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": 28.5360501567, "max_line_length": 169, "alphanum_fraction": 0.6581346809, "num_tokens": 2464, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081926, "lm_q2_score": 0.679178686187839, "lm_q1q2_score": 0.4658822496437285}}
{"text": "\n#include \"linear_elastic_energy.hpp\"\n#include <Eigen/Dense>\n\nusing namespace std;\nusing namespace Eigen;\n\n\n\nvoid LinearElasticEnergy::precompute(const TriMesh& mesh)\n{\n    A_.resize(mesh.f.rows());\n    DmInverse_.resize(mesh.f.rows());\n\n    for (int idx=0; idx<mesh.f.rows(); idx++) {\n        int i0 = mesh.f(idx, 0);\n        int i1 = mesh.f(idx, 1);\n        int i2 = mesh.f(idx, 2);\n\n        Mat2d Dm;\n        Dm.col(0) = mesh.u.segment<2>(2*i1) - mesh.u.segment<2>(2*i0);\n        Dm.col(1) = mesh.u.segment<2>(2*i2) - mesh.u.segment<2>(2*i0);\n\n        DmInverse_[idx] = Dm.inverse();\n\n        A_[idx] = 0.5 * (Vec3d() << Dm.col(0), 0.0).finished().cross(\n                        (Vec3d() << Dm.col(1), 0.0).finished()).norm();\n    }\n\n    lambda_ = VecXd::Zero(3*mesh.f.rows());\n}\n\nvoid LinearElasticEnergy::getForceAndHessian(const TriMesh& mesh,\n                                                const VecXd& x,\n                                                VecXd& F,\n                                                SparseMatrixd& dFdx,\n                                                SparseMatrixd& dFdv) const {\n    assert(F.size() >= x.size());\n\n    for (int idx=0; idx<mesh.f.rows(); idx++) {\n    }\n}\n\nvoid LinearElasticEnergy::getHessianPattern(const TriMesh& mesh, vector<SparseTripletd> &triplets) const {\n    for (int idx=0; idx<mesh.f.rows(); idx++) {\n        int idxs[3] = { mesh.f(idx,0), mesh.f(idx,1), mesh.f(idx,2) };\n        for (size_t j=0; j<3; ++j)\n            for (size_t k=0; k<3; ++k)\n                for (size_t l=0; l<3; ++l)\n                    for (size_t n=0; n<3; ++n)\n                        triplets.push_back(SparseTripletd(3*idxs[j]+l,3*idxs[k]+n, 1.0));\n    }\n}\n\nvoid LinearElasticEnergy::perVertexCount(const TriMesh& mesh, std::vector<int>& counts) const {\n    for (int idx=0; idx<mesh.f.rows(); idx++) {\n        for (int j=0; j<3; j++) {\n            counts[mesh.f(idx,j)]++;\n        }\n    }\n}\n\nvoid LinearElasticEnergy::update(const TriMesh& mesh, const VecXd& x, double dt, VecXd& dx) {\n    const double a = (1.0 / ksx_) / (dt * dt);\n\n    for (int idx=0; idx<mesh.f.rows(); idx++) {\n        const int idxs[3] = { mesh.f(idx,0), mesh.f(idx,1), mesh.f(idx,2) };\n\n        Mat3x2d Dw;\n        for (int i=0; i<2; i++) {\n            Dw.col(i) = x.segment<3>(3*idxs[i+1]) - x.segment<3>(3*idxs[0]);// +\n                            //dx.segment<3>(3*idxs[i+1]) - dx.segment<3>(3*idxs[0]); // Jacobi\n        }\n\n        // Deformation gradient\n        Mat3x2d F = Dw * DmInverse_[idx];\n\n        const double wu_mag = F.col(0).norm();\n        const double wv_mag = F.col(1).norm();\n\n        Vec3d wu = F.col(0) / wu_mag;\n        Vec3d wv = F.col(1) / wv_mag;\n\n        // C(x) = A ( || wu || - bu  || wv || - bv    wu . wv )\n        Vec3d C = A_[idx] * Vec3d(wu_mag - 1.0, wv_mag - 1.0, F.col(0).dot(F.col(1)));\n\n        // grad C is 3, 3x3 matrices, where each is w.r.t a different vertex\n        // Each column is the derivative of the respective C\n        Mat3d gradC[3];\n\n        gradC[1].col(0) = A_[idx] * DmInverse_[idx](0,0) * wu;\n        gradC[1].col(1) = A_[idx] * DmInverse_[idx](0,1) * wv;\n        gradC[1].col(2) = A_[idx] * (DmInverse_[idx](0,0) * F.col(1) + DmInverse_[idx](0,1) * F.col(0));\n        gradC[2].col(0) = A_[idx] * DmInverse_[idx](1,0) * wu;\n        gradC[2].col(1) = A_[idx] * DmInverse_[idx](1,1) * wv;\n        gradC[2].col(2) = A_[idx] * (DmInverse_[idx](1,0) * F.col(1) + DmInverse_[idx](1,1) * F.col(0));\n        gradC[0] = -(gradC[1] + gradC[2]);\n\n\tdouble den1 = (gradC[0].col(0).squaredNorm() / mesh.m[3*idxs[0]] +\n\t               gradC[1].col(0).squaredNorm() / mesh.m[3*idxs[1]] +\n\t               gradC[2].col(0).squaredNorm() / mesh.m[3*idxs[2]] + a);\n\tdouble den2 = (gradC[0].col(1).squaredNorm() / mesh.m[3*idxs[0]] +\n\t               gradC[1].col(1).squaredNorm() / mesh.m[3*idxs[1]] +\n\t               gradC[2].col(1).squaredNorm() / mesh.m[3*idxs[2]] + a);\n\tdouble den3 = (gradC[0].col(2).squaredNorm() / mesh.m[3*idxs[0]] +\n\t               gradC[1].col(2).squaredNorm() / mesh.m[3*idxs[1]] +\n\t               gradC[2].col(2).squaredNorm() / mesh.m[3*idxs[2]] + a);\n\n\tVec3d dl = (-C - lambda_.segment<3>(3*idx) * a).array() / Eigen::Array3d(den1, den2, den3);\n\n\tdx.segment<3>(3*idxs[0]) += gradC[0] * dl / mesh.m[3*idxs[0]];\n\tdx.segment<3>(3*idxs[1]) += gradC[1] * dl / mesh.m[3*idxs[1]];\n\tdx.segment<3>(3*idxs[2]) += gradC[2] * dl / mesh.m[3*idxs[2]];\n\n\tlambda_.segment<3>(3*idx) += dl;\n    }\n}\n", "meta": {"hexsha": "701f08c1b08981df669c23f391422a623e98401d", "size": 4464, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/linear_elastic_energy.cpp", "max_stars_repo_name": "liuwei792966953/stitch", "max_stars_repo_head_hexsha": "108e3dbd3410331c741c7cb166f93bbffa11b369", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-23T05:20:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-23T05:20:09.000Z", "max_issues_repo_path": "src/linear_elastic_energy.cpp", "max_issues_repo_name": "liuwei792966953/stitch", "max_issues_repo_head_hexsha": "108e3dbd3410331c741c7cb166f93bbffa11b369", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/linear_elastic_energy.cpp", "max_forks_repo_name": "liuwei792966953/stitch", "max_forks_repo_head_hexsha": "108e3dbd3410331c741c7cb166f93bbffa11b369", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.8305084746, "max_line_length": 106, "alphanum_fraction": 0.5082885305, "num_tokens": 1602, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934406, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.465855226698791}}
{"text": "#include <UnitTest++/UnitTest++.h>\n#include <stdexcept>\n#include <iostream>\n#include <cmath>\n#include <limits>\n#include <boost/filesystem.hpp>\n#include <fstream>\n\n#include \"coela_utility/src/string_utils.h\"\n#include \"coela_utility/src/histogram_container.h\"\n\n#include \"coela_core/src/ccd_image.h\"\n#include \"../psf_characterisation.h\"\n\nusing namespace coela;\nusing namespace std;\n\nSUITE(psf_characterisation)\n{\n    using namespace psf_characterisation;\n\n    string test_suite_output_dir= string(UnitTestSuite::GetSuiteName()) + \"_tests/\";\n    TEST(Run_Standard_Suite_Setup) {\n        cout << \"*** \\\"\"<< UnitTestSuite::GetSuiteName() <<\"\\\" unit tests running ***\" <<endl;\n        boost::filesystem::create_directories(test_suite_output_dir);\n    }\n\n\n    struct cone_shaped_PSF_image {\n        double cone_peak;\n        PixelArray2d<double> cone_img;\n        PixelPosition cone_centre;\n        PixelIndex cone_centre_pixel;\n\n        cone_shaped_PSF_image() {\n\n            cone_img = PixelArray2d<double> (100, 100, 0);\n            cone_peak = cone_img.range().x_dim()/2.0 - 5.0;\n            cone_centre = PixelPosition(cone_img.range().x_dim()/2.0 +0.5 ,\n                                        cone_img.range().y_dim()/2.0 +0.5);\n            cone_centre_pixel = PixelPosition::pixel_containing_point(cone_centre);\n\n            //Cone shape determined by:\n            // y = x (x=radius)\n            // for x < cone_peak\n            //y = 0; thereafter\n\n            for (PixelIterator i(cone_img.range()); i!=i.end; ++i) {\n                cone_img(i) =\n                    max(0.0,\n                        cone_peak - coord_distance(PixelPosition::centre_of_pixel(i), cone_centre)\n                       );\n            }\n\n\n\n        }\n\n    };\n\n    TEST_FIXTURE(cone_shaped_PSF_image, write_image_for_visual_check) {\n        cone_img.write_to_file(test_suite_output_dir+\"cone_img.fits\");\n    }\n\n    TEST_FIXTURE(cone_shaped_PSF_image, sanity_check) {\n        //Therefore, enclosed flux at x< cone peak\n        // EF = 1/3*PI*x^3\n\n        double analytical_sum_flux=M_PI*cone_peak*cone_peak*cone_peak / 3.0;\n\n//        cout<<\"Analytic sum: \" <<analytical_sum_flux<<\"; actual: \"<< cone_img.sum()<<endl;\n\n        CHECK_CLOSE(analytical_sum_flux, cone_img.sum(),  analytical_sum_flux/100.0);\n    }\n\n    TEST_FIXTURE(cone_shaped_PSF_image, test_get_radial_data_unmasked) {\n        using namespace psf_characterisation::detail;\n        std::vector<std::pair <double, double>  > radial_data =\n            get_radial_data(cone_img, cone_centre, cone_img.range().x_dim());\n        //Oversized range should be ok.\n\n        CHECK(radial_data.empty()==false);\n\n        sort(radial_data.begin(), radial_data.end(), double_pair_first_member_predicate);\n        ofstream datfile(string(test_suite_output_dir+\"raw_radial_data.txt\").c_str());\n        for (size_t i=0; i!=radial_data.size(); ++i) {\n            datfile<< radial_data[i].first <<\" \"<<radial_data[i].second<<endl;\n\n        }\n        datfile.close();\n    }\n\n    TEST_FIXTURE(cone_shaped_PSF_image, test_get_radial_data_unmasked_and_bin) {\n        using namespace psf_characterisation::detail;\n        std::vector<std::pair <double, double>  > radial_data =\n            get_radial_data(cone_img, cone_centre, cone_img.range().x_dim());\n        //Oversized range should be ok.\n\n\n        vector<psf_profile_point> proFileInfo =\n            bin_average_radial_data(radial_data);\n\n//        cout<<\"Get \" << proFileInfo.size()<<\" bins\"<<endl;\n        CHECK(proFileInfo.size() > cone_img.range().x_dim()/2.0);\n        //expect a few extra along the diagonal\n    }\n\n\n    TEST_FIXTURE(cone_shaped_PSF_image, test_FWHM_estimation) {\n        double est_fwhm = estimate_fwhm_in_image_pix(cone_img,\n                          cone_centre,\n                          cone_peak,\n                          cone_img.range().x_dim()/2.0\n                                                    );\n\n        //45 degree angle slope ->\n        //half-width at base = max height.\n        //Therefore; full-width at half-height = max height.\n\n        double calculated_FWHM = cone_peak;\n//        cout<<\"FWHM est: \" << est_fwhm<<endl;\n        CHECK_CLOSE(calculated_FWHM, est_fwhm, cone_peak / 20);\n    }\n\n    //Doesn't quite work, because we end up trying to interpolate past known points... not worth fixing, throws a sensible exception.\n//    TEST_FIXTURE(cone_shaped_PSF_image, test_full_enclosed_flux_radius_estimation){\n//        double full_flux_est_radius =\n//        estimate_radius_to_enclose_flux(cone_img,\n//                cone_centre,\n//                cone_img.sum(),\n//                cone_img.range().x_dim() );\n//\n////        cout<<\"Est radius 100pc flux: \"<<full_flux_est_radius<<\"; expected: \"<< cone_peak<<endl;\n//        CHECK_CLOSE(cone_peak, full_flux_est_radius, cone_peak*0.01);\n//    }\n\n    TEST_FIXTURE(cone_shaped_PSF_image, test_10p_enclosed_flux_radius_estimation) {\n//        double flux_10p_est_radius =\n//        estimate_radius_to_enclose_flux(cone_img,\n//                cone_centre,\n//                cone_img.sum()*0.1,\n//                cone_img.range().x_dim() );\n\n//        cout<<\"Est radius 10pc flux: \"<<full_flux_est_radius<<endl;\n//        cout<<\"; expected: \"<< cone_peak<<endl;\n//        CHECK_CLOSE(cone_peak, full_flux_est_radius, cone_peak*0.01);\n    }\n\n    TEST_FIXTURE(cone_shaped_PSF_image, test_FWEF_estimation) {\n        double est_fwhef = estimate_FWHEF_in_image_pix(cone_img,\n                           cone_centre,\n                           cone_img.sum(),\n                           cone_img.range().x_dim()\n                                                      );\n\n//       cout<<\"est FWHEF: \"<<est_fwhef<<endl;\n\n        //EF = PI*X^2*A - (2/3 * PI * X^3 / 3)\n        double x= est_fwhef /2.0;\n\n        double analytic_ef  = M_PI*x*x*cone_peak - (2.0/3.0) *M_PI*x*x*x ;\n\n//       cout<<\"Est HWHEF \"<<x<<endl;\n//       cout<<\"Resulting analytic flux proportion: \" <<analytic_ef / cone_img.sum()<<endl;\n\n        CHECK_CLOSE(0.5, analytic_ef/ cone_img.sum(), 0.02);\n    }\n\n    TEST_FIXTURE(cone_shaped_PSF_image, test_fully_encircled_flux_estimation) {\n\n//        PixelArray2d<double>& cone_img_ref = cone_img;\n\n        double  fully_encircled =\n            estimate_encircled_flux_at_pixel_radius(\n                cone_img,\n                cone_centre,\n                cone_img.range().x_dim()/2.0 - 3.5\n            );\n\n//        cout<<\"Estimate total flux via encircled_flux_at_pixel_radius: \"<< fully_encircled<<endl;\n//        cout<<\"Actual total flux \"<< cone_img.sum()<<endl;\n        CHECK_CLOSE(cone_img.sum(), fully_encircled, fully_encircled*0.01);\n    }\n\n    TEST_FIXTURE(cone_shaped_PSF_image, test_encircled_flux_estimation) {\n\n        double ap_radius =   cone_img.range().x_dim()/5.0;\n\n        double  EF = estimate_encircled_flux_at_pixel_radius(cone_img,\n                     cone_centre,\n                     ap_radius\n                                                            );\n\n        double x = ap_radius;\n        double analytic_ef= M_PI*x*x*cone_peak - (2.0/3.0) *M_PI*x*x*x ;\n\n//        cout<<\"Estimate encircled_flux_at_pixel_radius: \"<< ap_radius<<\": \"<< EF<<endl;\n//\n//        cout<<\"Analytic calculation: \"<< analytic_ef<<endl;\n//\n//        cout<<\"Percent diff: \" << (EF - analytic_ef )/ analytic_ef<<endl;\n\n        CHECK_CLOSE(analytic_ef, EF, analytic_ef*0.035);\n    }\n\n\n\n}\n", "meta": {"hexsha": "299601b57ed25800800fb8e98c8f08ed7a48fa16", "size": 7375, "ext": "cc", "lang": "C++", "max_stars_repo_path": "coela_analysis/src/unit_tests/psf_characterisation_unit_tests.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/unit_tests/psf_characterisation_unit_tests.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/unit_tests/psf_characterisation_unit_tests.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": 35.2870813397, "max_line_length": 133, "alphanum_fraction": 0.6014915254, "num_tokens": 1817, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646010190477, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.4658083351072055}}
{"text": "#include <Eigen/Core>\n#include <iostream>\nusing namespace Eigen;\nusing namespace std;\n\ntemplate<typename Derived>\nEigen::VectorBlock<Derived, 2>\nfirstTwo(MatrixBase<Derived>& v)\n{\n  return Eigen::VectorBlock<Derived, 2>(v.derived(), 0);\n}\n\ntemplate<typename Derived>\nconst Eigen::VectorBlock<const Derived, 2>\nfirstTwo(const MatrixBase<Derived>& v)\n{\n  return Eigen::VectorBlock<const Derived, 2>(v.derived(), 0);\n}\n\nint main(int, char**)\n{\n  Matrix<int,1,6> v; v << 1,2,3,4,5,6;\n  cout << firstTwo(4*v) << endl; // calls the const version\n  firstTwo(v) *= 2;              // calls the non-const version\n  cout << \"Now the vector v is:\" << endl << v << endl;\n  return 0;\n}\n", "meta": {"hexsha": "c88c9fbf1a8ff0c098ee8efdd2ccc43bd6eec73c", "size": 673, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Eigen-3.3/doc/examples/class_FixedVectorBlock.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/doc/examples/class_FixedVectorBlock.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/doc/examples/class_FixedVectorBlock.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": 24.0357142857, "max_line_length": 63, "alphanum_fraction": 0.6686478455, "num_tokens": 199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.689305616785446, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.46580833510720543}}
{"text": "#pragma once\n\n#include <Eigen/Core>\n#include <string>\n\n\n///\n/// \\brief Contains data from the IMU mesaurements.\n///\nclass ImuMeasurement{\npublic:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n  uint64_t t;       ///< ROS time message received (nanoseconds).\n\n  Eigen::Vector3d I_a_WI;  ///< Raw acceleration from the IMU (m/s/s)\n  Eigen::Vector3d I_w_WI;  ///< Raw angular velocity from the IMU (deg/s)\n\n  ~ImuMeasurement() {}\n  ImuMeasurement();\n  ImuMeasurement(const uint64_t _t,\n                 const Eigen::Vector3d& _I_a_WI,\n                 const Eigen::Vector3d& _I_w_WI);\n  friend std::ostream& operator<< (std::ostream& stream, const ImuMeasurement& meas);\n};\n\n", "meta": {"hexsha": "0f32c22a114abc9da899ab66b1e3db4e7bc7ee97", "size": 661, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/allan_variance_ros/ImuMeasurement.hpp", "max_stars_repo_name": "mintar/allan_variance_ros", "max_stars_repo_head_hexsha": "25a33882f1fafddc910dbbdb0e2d4858cde009fc", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/allan_variance_ros/ImuMeasurement.hpp", "max_issues_repo_name": "mintar/allan_variance_ros", "max_issues_repo_head_hexsha": "25a33882f1fafddc910dbbdb0e2d4858cde009fc", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/allan_variance_ros/ImuMeasurement.hpp", "max_forks_repo_name": "mintar/allan_variance_ros", "max_forks_repo_head_hexsha": "25a33882f1fafddc910dbbdb0e2d4858cde009fc", "max_forks_repo_licenses": ["BSD-3-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.4814814815, "max_line_length": 85, "alphanum_fraction": 0.671709531, "num_tokens": 182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757645879592641, "lm_q2_score": 0.6893056104028797, "lm_q1q2_score": 0.46580832179191106}}
{"text": "//\n// Created by Vasiliy Ershov on 08/11/2016.\n//\n\n#ifndef PROJECT_GAMMA_POISSON_MODEL_HPP\n#define PROJECT_GAMMA_POISSON_MODEL_HPP\n\n#include <common/utils/parallel/openmp_wrapper.h>\n#include <boost/math/special_functions/binomial.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/math/special_functions/trigamma.hpp>\n#include <vector>\n#include \"kmer_data.hpp\"\n#include \"thread_utils.h\"\n#include \"valid_hkmer_generator.hpp\"\n//\n\nnamespace n_gamma_poisson_model {\n\nstruct QualFunc {\n  double alpha_;\n  double beta_;\n\n  double operator()(double x) const { return alpha_ * x + beta_; }\n\n  double GenomicLogLikelihood(double x) const {\n    const double val = (*this)(x);\n    const double exp_point = exp(val);\n    return val - (std::isfinite(exp_point) ? log(1 + exp_point) : val);\n  }\n};\n\nclass GammaDistribution {\n private:\n  double shape_;\n  double rate_;\n  double log_gamma_at_shape_;\n\n public:\n  GammaDistribution(const GammaDistribution&) = default;\n\n  GammaDistribution& operator=(const GammaDistribution&) = default;\n\n  GammaDistribution(const double shape = 1, const double rate = 1)\n      : shape_(shape), rate_(rate) {\n    log_gamma_at_shape_ = boost::math::lgamma(shape_);\n  }\n\n  inline double GetShape() const { return shape_; }\n\n  inline double GetRate() const { return rate_; }\n\n  inline double LogGammaAtShape() const { return log_gamma_at_shape_; }\n};\n\nclass GammaMixture {\n private:\n  GammaDistribution first_;\n  GammaDistribution second_;\n  double first_weight_;\n\n public:\n  GammaMixture() : first_(1, 1), second_(1, 1), first_weight_(-1) {}\n\n  GammaMixture(const GammaDistribution& first,\n                const GammaDistribution& second,\n                double firstWeight)\n      : first_(first), second_(second), first_weight_(firstWeight) {}\n\n  const GammaDistribution& GetFirst() const { return first_; }\n\n  const GammaDistribution& GetSecond() const { return second_; }\n\n  double GetFirstWeight() const { return first_weight_; }\n};\n\nclass PoissonGammaDistribution {\n private:\n  const GammaDistribution& prior_;\n  static std::array<double, 100000> log_gamma_integer_cache_;\n\n private:\n  inline double IntLogGamma(size_t count) const {\n    if (count < log_gamma_integer_cache_.size()) {\n      return log_gamma_integer_cache_[count];\n    } else {\n      return boost::math::lgamma(((double)count) + 1);\n    }\n  }\n\n public:\n  PoissonGammaDistribution(const GammaDistribution& prior) : prior_(prior) {}\n\n  inline double PartialLogLikelihood(size_t count) const {\n    const double a = prior_.GetShape();\n    const double b = prior_.GetRate();\n\n    double ll = 0.0;\n    ll += a * log(b) - (a + (double)count) * log(b + 1);\n    ll +=\n        boost::math::lgamma(prior_.GetShape() + (double)count) - prior_.LogGammaAtShape();\n    return ll;\n  }\n\n  inline double LogLikelihood(size_t count) const {\n    const double a = prior_.GetShape();\n    const double b = prior_.GetRate();\n\n    double ll = 0.0;\n    ll += a * log(b) - (a + (double)count) * log(b + 1);\n    ll += boost::math::lgamma(prior_.GetShape() + ((double)count)) - IntLogGamma(count) -\n          prior_.LogGammaAtShape();\n\n    return ll;\n  }\n\n  inline double Quantile(double p) const {\n    const double a = prior_.GetShape();\n    const double b = prior_.GetRate();\n    return boost::math::ibeta_inva(a, 1.0 / (1.0 + b), 1.0 - p);\n  }\n\n  inline double Cumulative(size_t count) const {\n    const double a = prior_.GetShape();\n    const double b = prior_.GetRate();\n\n    return 1.0 - boost::math::ibeta((double)count + 1, a, 1.0 / (1.0 + b));\n  }\n};\n\nconstexpr int RunSizeLimit = 8;\n\nclass ParametricClusterModel {\n private:\n  GammaMixture prior_;\n  QualFunc qual_func_;\n  double count_threshold_;\n  std::array<double, RunSizeLimit> alphas_;\n\n public:\n public:\n  ParametricClusterModel() : count_threshold_(100000) {}\n\n  double ErrorRate(const int runSize) const {\n    auto idx = runSize - 1;\n    idx = std::max(idx, 0);\n    idx = std::min(idx, (int)(alphas_.size() - 1));\n    return alphas_[idx] * (runSize == 0 ? 0.5 : 1);\n  }\n\n  double ExpectedErrorRate(const hammer::HKMer& from,\n                           const hammer::HKMer& to) const {\n    double errRate = 0;\n    for (unsigned i = 0; i < hammer::K; ++i) {\n      errRate +=\n          std::abs(from[i].len - to[i].len) * log(ErrorRate(from[i].len));\n      //      errRate += std::abs(from[i].len - to[i].len) *\n      //      log(ErrorRate(from[i].len)) - log(1.0 - ErrorRate(from[i].len));\n    }\n    return exp(errRate);\n  }\n\n  ParametricClusterModel(const GammaMixture& prior,\n                         const QualFunc& qualFunc,\n                         const double countThreshold,\n                         const std::array<double, RunSizeLimit>& alphas)\n      : prior_(prior), qual_func_(qualFunc), count_threshold_(countThreshold) {\n    std::copy(alphas.begin(), alphas.end(), alphas_.begin());\n    for (unsigned i = 0; i < RunSizeLimit; ++i) {\n      INFO(\"Run length \" << i << \" estimated error rate \" << alphas_[i]);\n    }\n  }\n\n  ParametricClusterModel(const ParametricClusterModel& other) = default;\n\n  ParametricClusterModel& operator=(const ParametricClusterModel&) = default;\n\n  double QualityLogPrior(double qual) const {\n    return std::max(std::min(qual_func_.GenomicLogLikelihood(qual), -1e-10), -1000.0);\n  }\n\n  bool NeedSubcluster(const hammer::KMerStat& stat) const {\n    return qual_func_.GenomicLogLikelihood(stat.qual) > -0.1 &&\n           stat.count >= count_threshold_;\n  }\n\n  const GammaDistribution& GenomicPrior() const { return prior_.GetFirst(); }\n\n  const GammaDistribution& NoisePrior() const { return prior_.GetSecond(); }\n\n  double GenerateLogLikelihood(double expectedNoiseCount,\n                               size_t noiseCount) const {\n    const auto& prior = NoisePrior();\n\n    GammaDistribution posterior(prior.GetShape() + expectedNoiseCount,\n                                 prior.GetRate() + 1);\n    return PoissonGammaDistribution(posterior).LogLikelihood(noiseCount);\n  }\n\n  double GenomicLogLikelihood(size_t count) const {\n    const auto& prior = GenomicPrior();\n    const double a = prior.GetShape();\n    const double b = prior.GetRate();\n\n    double ll = a * log(b) - (a + (double)count) * log(b + 1);\n    ll += boost::math::lgamma(prior.GetShape() + ((double)count)) -\n          prior.LogGammaAtShape() - boost::math::lgamma(((double)count) + 1);\n    return ll;\n  }\n};\n\n// this class estimate prior distribution.\nclass TClusterModelEstimator {\n private:\n  const KMerData& data_;\n  double threshold_;\n  unsigned num_threads_;\n  size_t max_terations_;\n  bool calc_likelihood_;\n\n private:\n\n  struct TClusterSufficientStat {\n    double count_ = 0;\n    double qualtiy_ = 0;\n    double genomic_class_prob_ = 0;\n  };\n\n  struct TQualityStat {\n    double quality_ = 0;\n    double class_ = 0;\n\n    TQualityStat(double quality, double cls) : quality_(quality), class_(cls) {}\n  };\n\n  struct TRunErrorStats {\n    const KMerData* data_;\n    std::array<double, RunSizeLimit> error_counts_;\n    std::array<double, RunSizeLimit> total_count_;\n\n    TRunErrorStats(const KMerData& data)\n        : data_(&data){\n\n          };\n\n    std::array<double, RunSizeLimit> EstimateAlphas(\n        size_t priorSize = 100) const {\n      const double priors[] = {0.002, 0.004, 0.01, 0.02,\n                               0.035, 0.05,  0.09, 0.11};\n\n      std::array<double, RunSizeLimit> alphas;\n      for (unsigned i = 0; i < RunSizeLimit; ++i) {\n        alphas[i] = (error_counts_[i] + priors[i] * (double)priorSize) /\n                    (total_count_[i] + (double)priorSize);\n      }\n      alphas[0] *= 2;\n      return alphas;\n    };\n\n    TRunErrorStats& operator+=(const TRunErrorStats& other) {\n      if (this != &other) {\n        for (unsigned i = 0; i < RunSizeLimit; ++i) {\n          error_counts_[i] += other.error_counts_[i];\n          total_count_[i] += other.total_count_[i];\n        }\n      }\n      return *this;\n    }\n\n    void Add(const std::vector<size_t>& indices, size_t centerIdx) {\n      const auto& center = (*data_)[centerIdx].kmer;\n\n      for (auto idx : indices) {\n        if (idx == centerIdx) {\n          continue;\n        }\n        double errKmerCount = (double)(*data_)[idx].count;\n        const auto& errKmer = (*data_)[idx].kmer;\n        for (unsigned i = 0; i < hammer::K; ++i) {\n          if (center[i].len > RunSizeLimit) {\n            continue;\n          }\n          const int len = center[i].len - 1;\n          total_count_[len] += errKmerCount;\n          if (center[i].len != errKmer[i].len) {\n            error_counts_[len] += errKmerCount;\n          }\n        }\n      }\n      for (unsigned i = 0; i < hammer::K; ++i) {\n        if (center[i].len > RunSizeLimit) {\n          continue;\n        }\n        total_count_[center[i].len - 1] += (*data_)[centerIdx].count;\n      }\n    }\n  };\n\n  inline void Expectation(const PoissonGammaDistribution& first,\n                          const PoissonGammaDistribution& second,\n                          const QualFunc& qualFunc,\n                          TClusterSufficientStat& center) const {\n    const double logPrior = qualFunc.GenomicLogLikelihood(center.qualtiy_) +\n                            log(boost::math::gamma_q(center.count_, threshold_));\n\n    const double firstLL = first.PartialLogLikelihood((size_t)center.count_) + logPrior;\n    const double secondLL = second.PartialLogLikelihood((size_t)center.count_) +\n                            log(std::max(1.0 - exp(logPrior), 1e-20));\n\n    const double posterior = 1.0 / (1.0 + exp(secondLL - firstLL));\n    center.genomic_class_prob_ = posterior;\n  }\n\n  inline void QualityExpectation(const QualFunc& qualFunc,\n                                 TClusterSufficientStat& center) const {\n    center.genomic_class_prob_ =\n        exp(qualFunc.GenomicLogLikelihood(center.qualtiy_));\n  }\n\n  inline TClusterSufficientStat Create(const size_t centerIdx) const {\n    TClusterSufficientStat stat;\n    stat.genomic_class_prob_ =\n        data_[centerIdx].count > 0\n            ? boost::math::gamma_q(data_[centerIdx].count, threshold_)\n            : 0;\n    stat.count_ = data_[centerIdx].count;\n    stat.qualtiy_ = data_[centerIdx].qual;\n    return stat;\n  }\n\n  std::vector<TClusterSufficientStat> CreateSufficientStats(\n      const std::vector<size_t>& clusterCenters) const {\n    std::vector<TClusterSufficientStat> clusterSufficientStat;\n    clusterSufficientStat.reserve(clusterCenters.size());\n\n    for (size_t i = 0; i < clusterCenters.size(); ++i) {\n      const size_t centerIdx = clusterCenters[i];\n      auto stat = Create(centerIdx);\n      if (stat.count_ > 0) {\n        clusterSufficientStat.push_back(stat);\n      }\n    }\n    return clusterSufficientStat;\n  }\n\n  std::vector<TQualityStat> CreateQualityStats(\n      const std::vector<std::vector<size_t>>& clusters,\n      const std::vector<size_t>& clusterCenters) const {\n    std::vector<TQualityStat> qualities;\n    qualities.reserve(clusterCenters.size());\n\n    for (size_t i = 0; i < clusterCenters.size(); ++i) {\n      const size_t centerIdx = clusterCenters[i];\n      if (data_[centerIdx].count >= threshold_) {\n        for (auto idx : clusters[i]) {\n          if (idx != centerIdx) {\n            qualities.push_back(TQualityStat(data_[idx].qual, 0));\n          }\n        }\n        qualities.push_back(TQualityStat(data_[centerIdx].qual, 1));\n      }\n    }\n    return qualities;\n  }\n\n  template <bool WEIGHTED = true>\n  class TCountsStat {\n   private:\n    double count_ = 0;\n    double count2_ = 0;\n    double weight_ = 0;\n\n   public:\n    void Add(const TClusterSufficientStat& stat) {\n      const double w = (WEIGHTED ? stat.genomic_class_prob_ : 1.0);\n      count_ += w * stat.count_;\n      count2_ += w * stat.count_ * stat.count_;\n      weight_ += w;\n    }\n\n    TCountsStat& operator+=(const TCountsStat& other) {\n      if (this != &other) {\n        count_ += other.count_;\n        count2_ += other.count2_;\n        weight_ += other.weight_;\n      }\n      return *this;\n    }\n\n    double GetWeightedSum() const { return count_; }\n\n    double GetWeightedSum2() const { return count2_; }\n\n    double GetWeight() const { return weight_; }\n  };\n\n  class TLogGammaStat {\n   private:\n    double genomic_shape_;\n    double non_genomic_shape_;\n    double genomic_log_gamma_sum_ = 0;\n    double non_genomic_log_gamma_sum_ = 0;\n\n   public:\n    TLogGammaStat(double genomicShape, double nonGenomicShape)\n        : genomic_shape_(genomicShape), non_genomic_log_gamma_sum_(nonGenomicShape) {}\n\n    void Add(const TClusterSufficientStat& stat) {\n      genomic_log_gamma_sum_ += stat.genomic_class_prob_ *\n                            boost::math::lgamma(stat.count_ + genomic_shape_);\n      non_genomic_log_gamma_sum_ +=\n          (1.0 - stat.genomic_class_prob_) *\n          boost::math::lgamma(stat.count_ + non_genomic_shape_);\n    }\n\n    TLogGammaStat& operator+=(const TLogGammaStat& other) {\n      if (this != &other) {\n        genomic_log_gamma_sum_ += other.genomic_log_gamma_sum_;\n        non_genomic_log_gamma_sum_ += other.non_genomic_log_gamma_sum_;\n      }\n      return *this;\n    }\n\n    double GetGenomicLogGammaSum() const { return genomic_log_gamma_sum_; }\n\n    double GetNonGenomicLogGammaSum() const { return non_genomic_log_gamma_sum_; }\n  };\n\n  class TQualityLogitLinearRegressionPoint {\n   private:\n    // p(genomic) = exp(Alpha qual + beta) / (1.0 + exp(Alpha qual + beta))\n    QualFunc func_;\n\n    double likelihood_ = 0;\n\n    double der_alpha_ = 0;\n    double der_beta_ = 0;\n\n    double der2_alpha_ = 0;\n    double der2_beta_ = 0;\n    double der2_alpha_beta_ = 0;\n\n   public:\n    TQualityLogitLinearRegressionPoint(QualFunc func) : func_(func) {}\n\n    void Add(const TClusterSufficientStat& statistic) {\n      Add(statistic.genomic_class_prob_, statistic.qualtiy_);\n    }\n\n    void Add(const TQualityStat& statistic) {\n      Add(statistic.class_, statistic.quality_);\n    }\n\n    void Add(const double firstClassProb, double qual) {\n      const double val = func_(qual);\n      const double expPoint = exp(val);\n      const double p =\n          std::isfinite(expPoint) ? expPoint / (1.0 + expPoint) : 1.0;\n\n      der_alpha_ += (firstClassProb - p) * qual;\n      der_beta_ += firstClassProb - p;\n\n      der2_alpha_ -= sqr(qual) * p * (1 - p);\n      der2_beta_ -= p * (1 - p);\n      der2_alpha_beta_ -= qual * p * (1 - p);\n\n      likelihood_ += firstClassProb * val -\n                    (std::isfinite(expPoint) ? log(1 + expPoint) : val);\n    }\n\n    TQualityLogitLinearRegressionPoint& operator+=(\n        const TQualityLogitLinearRegressionPoint& other) {\n      if (this != &other) {\n        likelihood_ += other.likelihood_;\n\n        der_alpha_ += other.der_alpha_;\n        der_beta_ += other.der_beta_;\n\n        der2_alpha_ += other.der2_alpha_;\n        der2_beta_ += other.der2_beta_;\n        der2_alpha_beta_ += other.der2_alpha_beta_;\n      }\n      return *this;\n    }\n\n    double GetLikelihood() const { return likelihood_; }\n\n    double GetDerAlpha() const { return der_alpha_; }\n\n    double GetDerBeta() const { return der_beta_; }\n\n    double GetDer2Alpha() const { return der2_alpha_; }\n\n    double GetDer2Beta() const { return der2_beta_; }\n\n    double GetDer2AlphaBeta() const { return der2_alpha_beta_; }\n  };\n\n  QualFunc Update(const QualFunc& current,\n                   const TQualityLogitLinearRegressionPoint& pointStats) const {\n    const double dera = pointStats.GetDerAlpha();\n    const double derb = pointStats.GetDerBeta();\n\n    const double daa = pointStats.GetDer2Alpha() + 1e-3;\n    const double dbb = pointStats.GetDer2Beta() + 1e-3;\n    const double dab = pointStats.GetDer2AlphaBeta();\n    const double det = daa * dbb - sqr(dab);\n\n    double stepAlpha = (dbb * dera - dab * derb) / det;\n    double stepBeta = (daa * derb - dab * dera) / det;\n\n    INFO(\"Quality estimation iteration gradient: \" << dera << \" \" << derb);\n    INFO(\"Quality estimation likelihood: \" << pointStats.GetLikelihood());\n\n    return {current.alpha_ - stepAlpha, current.beta_ - stepBeta};\n  }\n\n  class TGammaDerivativesStats {\n   private:\n    double first_class_shift_;\n    double second_class_shift_;\n\n    double digamma_sum_first_ = 0;\n    double trigamma_sum_first_ = 0;\n\n    double digamma_sum_second_ = 0;\n    double trigamma_sum_second_ = 0;\n\n   public:\n    TGammaDerivativesStats(double firstShift, double secondShift)\n        : first_class_shift_(firstShift), second_class_shift_(secondShift) {}\n\n    void Add(const TClusterSufficientStat& statistic) {\n      const double p = statistic.genomic_class_prob_;\n      digamma_sum_first_ +=\n          p > 1e-3 ? p * boost::math::digamma(statistic.count_ + first_class_shift_)\n                   : 0;\n      trigamma_sum_first_ +=\n          p > 1e-3\n              ? p * boost::math::trigamma(statistic.count_ + first_class_shift_)\n              : 0;\n\n      digamma_sum_second_ +=\n          p < (1.0 - 1e-3) ? (1.0 - p) * boost::math::digamma(statistic.count_ +\n                                                              second_class_shift_)\n                           : 0;\n      trigamma_sum_second_ +=\n          p < (1.0 - 1e-3) ? (1.0 - p) * boost::math::trigamma(statistic.count_ +\n                                                               second_class_shift_)\n                           : 0;\n    }\n\n    TGammaDerivativesStats& operator+=(const TGammaDerivativesStats& other) {\n      if (this != &other) {\n        digamma_sum_first_ += other.digamma_sum_first_;\n        trigamma_sum_first_ += other.trigamma_sum_first_;\n\n        digamma_sum_second_ = other.digamma_sum_second_;\n        trigamma_sum_second_ += other.trigamma_sum_second_;\n      }\n      return *this;\n    }\n\n    double GetDigammaSumFirst() const { return digamma_sum_first_; }\n\n    double GetTrigammaSumFirst() const { return trigamma_sum_first_; }\n\n    double GetDigammaSumSecond() const { return digamma_sum_second_; }\n\n    double GetTrigammaSumSecond() const { return trigamma_sum_second_; }\n  };\n\n  static inline double sqr(double x) { return x * x; }\n\n  struct TDirection {\n    double Direction;\n    double GradientNorm;\n    double Mu;\n  };\n\n  static TDirection MoveDirection(double shape, const double weightedSum,\n                                  const double weight, const double digammaSum,\n                                  const double trigammaSum,\n                                  double regularizer = 1e-4) {\n    const double mu = weight / weightedSum;\n    const double digammaAtShape = boost::math::digamma(shape);\n    const double trigammaAtShape = boost::math::trigamma(shape);\n\n    const double b = mu * shape;\n\n    const double der =\n        weight * (log(b) - log(b + 1) - digammaAtShape) + digammaSum;\n    const double der2 =\n        trigammaSum + weight * (1.0 / shape - mu / (b + 1) - trigammaAtShape);\n\n    return {-der / (der2 + regularizer), std::abs(der), mu};\n  }\n\n  double Likelihood(GammaDistribution& prior, double weightedSum,\n                    double weight, double lgammaSum) {\n    const double a = prior.GetShape();\n    const double b = prior.GetRate();\n    return weight * a * (log(b) - log(b + 1)) + weightedSum * log(b + 1) +\n           lgammaSum - weight * prior.LogGammaAtShape();\n  }\n\n public:\n  TClusterModelEstimator(const KMerData& data, double threshold,\n                         unsigned num_threads = 16,\n                         size_t maxIterations = 40,\n                         bool calcLikelihood = false)\n      : data_(data),\n        threshold_(threshold),\n        num_threads_(num_threads),\n        max_terations_(maxIterations),\n        calc_likelihood_(calcLikelihood) {}\n\n  static inline GammaDistribution Update(const GammaDistribution& point,\n                                          const TDirection& direction,\n                                          double minShape = 0.01) {\n    double shape = std::max(point.GetShape() + direction.Direction, minShape);\n    double rate = shape * direction.Mu;\n    return GammaDistribution(shape, rate);\n  }\n\n  static GammaDistribution MomentMethodEstimator(const double sum,\n                                                  const double sum2,\n                                                  const double weight) {\n    const double m = sum / weight;\n    const double var = sum2 / weight - m * m;\n    const double rate = 1.0 / std::max(var / m - 1, 1e-3);\n    const double shape = m * rate;\n    return GammaDistribution(shape, rate);\n  }\n\n  ParametricClusterModel Estimate(\n      const std::vector<std::vector<size_t>>& clusters,\n      const std::vector<size_t>& clusterCenter, const bool useEM = false,\n      const size_t sample = 0) {\n    if (sample && clusters.size() > sample) {\n      std::vector<std::vector<size_t>> sampledClusters;\n      std::vector<size_t> sampledCenters;\n    }\n\n    const auto qualityFunc = [&]() -> QualFunc {\n      auto qualStats = CreateQualityStats(clusters, clusterCenter);\n\n      QualFunc cursor = {-1e-5, 0.0};\n\n      for (unsigned i = 0; i < 15; ++i) {\n        const auto qualDerStats =\n            n_computation_utils::TAdditiveStatisticsCalcer<\n                TQualityStat, TQualityLogitLinearRegressionPoint>(qualStats,\n                                                                  num_threads_)\n                .Calculate([&]() -> TQualityLogitLinearRegressionPoint {\n                  return TQualityLogitLinearRegressionPoint(cursor);\n                });\n\n        cursor = Update(cursor, qualDerStats);\n\n        if ((std::abs(qualDerStats.GetDerAlpha()) +\n             std::abs(qualDerStats.GetDerBeta())) < 1e-2) {\n          break;\n        }\n      }\n\n      INFO(\"Quality function: \" << cursor.alpha_ << \"q + \" << cursor.beta_);\n      return cursor;\n    }();\n\n    auto alphas = [&]() -> std::array<double, RunSizeLimit> {\n      TRunErrorStats errorStats =\n          n_computation_utils::ParallelStatisticsCalcer<TRunErrorStats>(\n              num_threads_)\n              .Calculate(\n                  clusters.size(),\n                  [&]() -> TRunErrorStats { return TRunErrorStats(data_); },\n                  [&](TRunErrorStats& stat, size_t k) {\n                    if (data_[clusterCenter[k]].count >= threshold_) {\n                      stat.Add(clusters[k], clusterCenter[k]);\n                    }\n                  });\n      return errorStats.EstimateAlphas();\n    }();\n\n    std::vector<TClusterSufficientStat> clusterSufficientStat =\n        CreateSufficientStats(clusterCenter);\n\n    const auto totalStats =\n        n_computation_utils::TAdditiveStatisticsCalcer<TClusterSufficientStat,\n                                                     TCountsStat<false>>(\n            clusterSufficientStat, num_threads_)\n            .Calculate([]() -> TCountsStat<false> {\n              return TCountsStat<false>();\n            });\n\n#pragma omp parallel for num_threads(num_threads_)\n    for (size_t k = 0; k < clusterSufficientStat.size(); ++k) {\n      QualityExpectation(qualityFunc, clusterSufficientStat[k]);\n    }\n\n    auto countsStats =\n        n_computation_utils::TAdditiveStatisticsCalcer<TClusterSufficientStat,\n                                                     TCountsStat<true>>(\n            clusterSufficientStat, num_threads_)\n            .Calculate([]() -> TCountsStat<true> {\n              return TCountsStat<true>();\n            });\n\n    GammaDistribution genomicPrior = [&]() -> GammaDistribution {\n      const double m = countsStats.GetWeightedSum() / countsStats.GetWeight();\n      const double var =\n          countsStats.GetWeightedSum2() / countsStats.GetWeight() - m * m;\n      const double rate = 1.0 / std::max(var / m - 1, 1e-3);\n      const double shape = m * rate;\n      return GammaDistribution(shape, rate);\n    }();\n\n    GammaDistribution nonGenomicPrior = [&]() -> GammaDistribution {\n      const double m =\n          (totalStats.GetWeightedSum() - countsStats.GetWeightedSum()) /\n          (totalStats.GetWeight() - countsStats.GetWeight());\n      const double var =\n          (totalStats.GetWeightedSum2() - countsStats.GetWeightedSum2()) /\n              (totalStats.GetWeight() - countsStats.GetWeight()) -\n          m * m;\n      const double rate = 1.0 / std::max(var / m - 1, 1e-3);\n      const double shape = m * rate;\n      return GammaDistribution(shape, rate);\n    }();\n\n    for (unsigned i = 0, steps = 0; i < max_terations_; ++i, ++steps) {\n      auto gammaDerStats =\n          n_computation_utils::TAdditiveStatisticsCalcer<TClusterSufficientStat,\n                                                       TGammaDerivativesStats>(\n              clusterSufficientStat, num_threads_)\n              .Calculate([&]() -> TGammaDerivativesStats {\n                return TGammaDerivativesStats(genomicPrior.GetShape(),\n                                              nonGenomicPrior.GetShape());\n              });\n\n      auto genomicDirection = MoveDirection(\n          genomicPrior.GetShape(), countsStats.GetWeightedSum(),\n          countsStats.GetWeight(), gammaDerStats.GetDigammaSumFirst(),\n          gammaDerStats.GetTrigammaSumFirst());\n\n      auto nonGenomicDirection = MoveDirection(\n          nonGenomicPrior.GetShape(),\n          totalStats.GetWeightedSum() - countsStats.GetWeightedSum(),\n          totalStats.GetWeight() - countsStats.GetWeight(),\n          gammaDerStats.GetDigammaSumSecond(),\n          gammaDerStats.GetTrigammaSumSecond());\n\n      auto gradientNorm =\n          genomicDirection.GradientNorm + nonGenomicDirection.GradientNorm;\n\n      INFO(\"Iteration #\" << i << \" gradient norm \" << gradientNorm);\n\n      genomicPrior = Update(genomicPrior, genomicDirection);\n      nonGenomicPrior = Update(nonGenomicPrior, nonGenomicDirection);\n\n      if (calc_likelihood_) {\n        auto logGammaStats =\n            n_computation_utils::TAdditiveStatisticsCalcer<TClusterSufficientStat,\n                                                         TLogGammaStat>(\n                clusterSufficientStat, num_threads_)\n                .Calculate([&]() -> TLogGammaStat {\n                  return TLogGammaStat(genomicPrior.GetShape(),\n                                       nonGenomicPrior.GetShape());\n                });\n\n        INFO(\"Genomic likelihood: \" << Likelihood(\n                 genomicPrior, countsStats.GetWeightedSum(),\n                 countsStats.GetWeight(),\n                 logGammaStats.GetGenomicLogGammaSum()));\n\n        INFO(\"NonGenomic likelihood: \" << Likelihood(\n                 nonGenomicPrior,\n                 totalStats.GetWeightedSum() - countsStats.GetWeightedSum(),\n                 totalStats.GetWeight() - countsStats.GetWeight(),\n                 logGammaStats.GetNonGenomicLogGammaSum()));\n      }\n\n      {\n        INFO(\"Genomic gamma prior estimation step: shape \"\n             << genomicPrior.GetShape() << \" and rate \"\n             << genomicPrior.GetRate());\n        INFO(\"Nongenomic gamma prior estimation step: shape \"\n             << nonGenomicPrior.GetShape() << \" and rate \"\n             << nonGenomicPrior.GetRate());\n      }\n\n      double shapeDiff = std::abs(genomicDirection.Direction) +\n                         std::abs(nonGenomicDirection.Direction);\n\n      if (useEM) {\n        if ((shapeDiff < 1e-2) || gradientNorm < 1e-1 ||\n            (steps == 5 && (i < max_terations_ - 10))) {\n          PoissonGammaDistribution genomic(genomicPrior);\n          PoissonGammaDistribution nonGenomic(nonGenomicPrior);\n#pragma omp parallel for num_threads(num_threads_)\n          for (size_t k = 0; k < clusterSufficientStat.size(); ++k) {\n            Expectation(genomic, nonGenomic, qualityFunc,\n                        clusterSufficientStat[k]);\n          }\n\n          countsStats = n_computation_utils::TAdditiveStatisticsCalcer<\n                            TClusterSufficientStat, TCountsStat<true>>(\n                            clusterSufficientStat, num_threads_)\n                            .Calculate([]() -> TCountsStat<true> {\n                              return TCountsStat<true>();\n                            });\n          steps = 0;\n        }\n      } else {\n        if ((shapeDiff < 1e-4) || gradientNorm < 1e-2) {\n          break;\n        }\n      }\n    }\n\n    INFO(\"Genomic gamma prior genomic estimated with shape \"\n         << genomicPrior.GetShape() << \" and rate \" << genomicPrior.GetRate());\n    INFO(\"Nongenomic Gamma prior estimated with shape \"\n         << nonGenomicPrior.GetShape() << \" and rate \"\n         << nonGenomicPrior.GetRate());\n\n    return ParametricClusterModel(\n        GammaMixture(genomicPrior, nonGenomicPrior,\n                      countsStats.GetWeight() / totalStats.GetWeight()),\n        qualityFunc, threshold_, alphas);\n  }\n\n  static GammaDistribution EstimatePrior(const std::vector<size_t>& counts) {\n    const size_t observations = counts.size();\n    double sum = 0;\n    double sum2 = 0;\n    for (auto count : counts) {\n      sum += (double)count;\n      sum2 += (double)count * (double)count;\n    }\n\n    GammaDistribution prior =\n        TClusterModelEstimator::MomentMethodEstimator(sum, sum2, (double)observations);\n\n    for (unsigned i = 0, steps = 0; i < 10; ++i, ++steps) {\n      double digammaSum = 0;\n      double trigammaSum = 0;\n      for (auto count : counts) {\n        digammaSum += boost::math::digamma((double)count + prior.GetShape());\n        trigammaSum += boost::math::trigamma((double)count + prior.GetShape());\n      }\n\n      auto direction = MoveDirection(prior.GetShape(), sum, (double)observations,\n                                     digammaSum, trigammaSum);\n\n      const double shapeDiff = std::abs(direction.Direction);\n      if (shapeDiff < 1e-3 || (direction.GradientNorm < 1e-4)) {\n        break;\n      }\n      prior = Update(prior, direction, 1e-2);\n    }\n    return prior;\n  }\n};\n\n}  // namespace NGammaPoissonModel\n\n#endif  // PROJECT_GAMMA_POISSON_MODEL_HPP\n", "meta": {"hexsha": "f59403dbc6117e1bd91146eb94d97f239af3f535", "size": 29675, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/metaspades/src/projects/ionhammer/gamma_poisson_model.hpp", "max_stars_repo_name": "STRIDES-Codes/Exploring-the-Microbiome-", "max_stars_repo_head_hexsha": "bd29c8c74d8f40a58b63db28815acb4081f20d6b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/metaspades/src/projects/ionhammer/gamma_poisson_model.hpp", "max_issues_repo_name": "STRIDES-Codes/Exploring-the-Microbiome-", "max_issues_repo_head_hexsha": "bd29c8c74d8f40a58b63db28815acb4081f20d6b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/metaspades/src/projects/ionhammer/gamma_poisson_model.hpp", "max_forks_repo_name": "STRIDES-Codes/Exploring-the-Microbiome-", "max_forks_repo_head_hexsha": "bd29c8c74d8f40a58b63db28815acb4081f20d6b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-06-05T07:40:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-05T08:02:58.000Z", "avg_line_length": 34.1091954023, "max_line_length": 90, "alphanum_fraction": 0.612064027, "num_tokens": 7273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424334245618, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.4657821346623684}}
{"text": "#ifndef MLT_MODELS_REGRESSORS_REGRESSOR_HPP\n#define MLT_MODELS_REGRESSORS_REGRESSOR_HPP\n\n#include <Eigen/Core>\n\n#include \"../base.hpp\"\n\nnamespace mlt {\nnamespace models {\nnamespace regressors {\n\ttemplate <class ConcreteType>\n\tclass Regressor : public Predictor<ConcreteType, MatrixXd> {\n\tpublic:\n\t\tinline auto score(Features input, Target target) const {\n\t\t\treturn (1 - ((y - _self().predict(input)).array().pow(2).rowwise().sum().array() / (y.colwise() - (y.rowwise().mean())).array().pow(2).rowwise().sum().array())).mean();\n\t\t}\n\n\tprotected:\n\t\tRegressor() = default;\n\t\tRegressor(const Regressor&) = default;\n\t\tRegressor(Regressor&&) = default;\n\t\tRegressor& operator=(const Regressor&) = default;\n\t\t~Regressor() = default;\n\n\t\tinline auto _to_target_matrix(Target target) {\n\t\t\treturn target;\n\t\t}\n\t};\n}\n}\n}\n#endif", "meta": {"hexsha": "878c041c3074ba60d6464691ac334c4c26037643", "size": 812, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/mlt/models/regressors/regressor.hpp", "max_stars_repo_name": "fedeallocati/MachineLearningToolkit", "max_stars_repo_head_hexsha": "8614ee2c8c5211a3eefceb10a50576e0485cefd9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-08-31T11:43:19.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-22T11:03:47.000Z", "max_issues_repo_path": "src/mlt/models/regressors/regressor.hpp", "max_issues_repo_name": "fedeallocati/MachineLearningToolkit", "max_issues_repo_head_hexsha": "8614ee2c8c5211a3eefceb10a50576e0485cefd9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mlt/models/regressors/regressor.hpp", "max_forks_repo_name": "fedeallocati/MachineLearningToolkit", "max_forks_repo_head_hexsha": "8614ee2c8c5211a3eefceb10a50576e0485cefd9", "max_forks_repo_licenses": ["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.375, "max_line_length": 171, "alphanum_fraction": 0.7019704433, "num_tokens": 218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424217727027, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.465782128246769}}
{"text": "#define EIGEN_USE_MKL_ALL\n\n#include <iostream> // for standard output\n#include <fstream> // for file input\n#include <iomanip> // some nice printing functions\n#include <random> // for randomness\n#include <boost/algorithm/string.hpp> // string manipulation library\n#include <boost/filesystem.hpp> // filesystem path manipulation library\n#include <boost/program_options.hpp> // options parsing library\n#include <eigen3/Eigen/Dense> // linear algebra library\n\n#include \"constants.h\"\n#include \"qp-math.h\"\n#include \"gates.h\"\n#include \"nv-math.h\"\n#include \"nv-control.h\"\n\nusing namespace std;\nusing namespace Eigen;\nnamespace fs = boost::filesystem;\nnamespace po = boost::program_options;\n\nint main(const int arg_num, const char *arg_vec[]) {\n\n  // -------------------------------------------------------------------------------------\n  // Set input options\n  // -------------------------------------------------------------------------------------\n\n  const uint help_text_length = 90;\n\n  unsigned long long int seed;\n\n  po::options_description general(\"General options\", help_text_length);\n  general.add_options()\n    (\"help,h\", \"produce help message\")\n    (\"seed\", po::value<unsigned long long int>(&seed)->default_value(0),\n     \"seed for random number generator\")\n    ;\n\n  bool pair_search;\n  bool coherence_scan;\n  bool coherence_signal;\n  bool angular_coherence_signal;\n  bool rotation;\n  bool coupling;\n  bool iswap;\n  bool swap;\n  bool identity;\n  bool swap_nvst;\n  bool larmor_identity;\n  bool initialize;\n  bool initialize_x;\n  bool initialize_larmor;\n  bool testing_mode;\n\n  po::options_description simulations(\"Available simulations\",help_text_length);\n  simulations.add_options()\n    (\"pair_search\",\n     po::value<bool>(&pair_search)->default_value(false)->implicit_value(true),\n     \"identify and characterize addressable larmor pairs\")\n    (\"scan\", po::value<bool>(&coherence_scan)->default_value(false)->implicit_value(true),\n     \"perform NV coherence scan for effective larmor frequencies\")\n    (\"signal\",\n     po::value<bool>(&coherence_signal)->default_value(false)->implicit_value(true),\n     \"measure NV coherence signal as a function of the coupling constant\"\n     \" at the frequency of a target nucleus\")\n    (\"angular_signal\", po::value<bool>(&angular_coherence_signal)\n     ->default_value(false)->implicit_value(true),\n     \"measure NV coherence signal as a function of the coupling constant\"\n     \" and angle of a control field at the frequency of a target nucleus\")\n    (\"rotate\", po::value<bool>(&rotation)->default_value(false)->implicit_value(true),\n     \"rotate an individual nucleus\")\n    (\"couple\", po::value<bool>(&coupling)->default_value(false)->implicit_value(true),\n     \"couple an individual nucleus to NV center\")\n    (\"iswap\", po::value<bool>(&iswap)->default_value(false)->implicit_value(true),\n     \"compute iSWAP fidelities\")\n    (\"swap\", po::value<bool>(&swap)->default_value(false)->implicit_value(true),\n     \"compute SWAP fidelities\")\n    (\"identity\", po::value<bool>(&identity)->default_value(false)->implicit_value(true),\n     \"compute fidelity of an identity operation on a single spin\")\n    (\"swap_nvst\", po::value<bool>(&swap_nvst)->default_value(false)->implicit_value(true),\n     \"compute SWAP_NVST fidelity\")\n    (\"larmor_identity\",\n     po::value<bool>(&larmor_identity)->default_value(false)->implicit_value(true),\n     \"compute fidelity of an identity operation on a larmor qubit\")\n    (\"initialize\",\n     po::value<bool>(&initialize)->default_value(false)->implicit_value(true),\n     \"compute fidelity of a deterministic initialization of a thermalized nucleus\"\n     \" into |u> or |d>\")\n    (\"initialize_x\",\n     po::value<bool>(&initialize_x)->default_value(false)->implicit_value(true),\n     \"compute fidelity of a probabalistic initialization of a thermalized nucleus\"\n     \" into |u> +/- |d>\")\n    (\"initialize_larmor\",\n     po::value<bool>(&initialize_larmor)->default_value(false)->implicit_value(true),\n     \"compute fidelity of a probabalistic initialization of a larmor pair\"\n     \" from |dd> into |ud> +/- |du>\")\n    (\"test\" ,po::value<bool>(&testing_mode)->default_value(false)->implicit_value(true),\n     \"enable testing mode\")\n    ;\n\n  double c13_abundance;\n  double c13_factor;\n  double nuclear_isolation;\n  double larmor_isolation;\n  double larmor_isolation_in_kHz;\n  double min_hyperfine_xy;\n  double min_hyperfine_xy_in_kHz;\n  uint max_cluster_size;\n  double hyperfine_cutoff;\n  double hyperfine_cutoff_in_kHz;\n  int ms;\n  uint k_DD_int;\n  axy_harmonic k_DD;\n  double static_Bz;\n  double static_Bz_in_gauss;\n  double identity_time;\n  double scale_factor;\n  double integration_factor;\n  bool no_nn;\n\n  po::options_description simulation_options(\"Simulation options\",help_text_length);\n  simulation_options.add_options()\n    (\"c13_factor\", po::value<double>(&c13_factor)->default_value(1),\n     \"abundance of C-13 relative to its natural abundance\")\n    (\"nuclear_isolation\", po::value<double>(&nuclear_isolation)->default_value(100),\n     \"maximum internuclear coupling factor for an 'isolated' nucleus (Hz)\")\n    (\"larmor_isolation\", po::value<double>(&larmor_isolation_in_kHz)->default_value(0),\n     \"isolation factor of parallel component of hyperfine field\"\n     \" for an 'isolated' nucleus (kHz)\")\n    (\"min_hyperfine_xy\", po::value<double>(&min_hyperfine_xy_in_kHz)->default_value(0),\n     \"minimum magnitude of hyperfine field perpendicular to the NV axis\"\n     \" for a larmor pair to be counted in a pair search (kHz)\")\n    (\"max_cluster_size\", po::value<uint>(&max_cluster_size)->default_value(6),\n     \"maximum allowable size of C-13 clusters\")\n    (\"hyperfine_cutoff\", po::value<double>(&hyperfine_cutoff_in_kHz)->default_value(10),\n     \"set cutoff scale for hyperfine field (kHz)\")\n    (\"ms\", po::value<int>(&ms)->default_value(1),\n     \"NV center spin state used with |0> for an effective two-level system (+/-1)\")\n    (\"k_DD\", po::value<uint>(&k_DD_int)->default_value(1),\n     \"resonance harmonic used in spin addressing (1 or 3)\")\n    (\"static_Bz\", po::value<double>(&static_Bz_in_gauss)->default_value(140.1,\"140.1\"),\n     \"strength of static magnetic field along the NV axis (gauss)\")\n    (\"identity_time\", po::value<double>(&identity_time)->default_value(1),\n     \"time of identity operation (s)\")\n    (\"scale_factor\", po::value<double>(&scale_factor)->default_value(10),\n     \"factor used to define different scales (i.e. if a << b, then a = b/scale_factor)\")\n    (\"integration_factor\", po::value<double>(&integration_factor)->default_value(10),\n     \"factor used to determine size of integration step size\")\n    (\"no_nn\" ,po::value<bool>(&no_nn)->default_value(false)->implicit_value(true),\n     \"turn off internuclear couplings\")\n    ;\n\n  vector<uint> target_nuclei;\n  bool target_pairs;\n  double angle;\n  double angle_over_pi;\n  double target_polar;\n  double target_pitch_over_pi;\n  double target_azimuth;\n  double target_azimuth_over_pi;\n  double nv_polar;\n  double nv_pitch_over_pi;\n  double nv_azimuth;\n  double nv_azimuth_over_pi;\n\n  po::options_description addressing_options(\"Nuclear spin addressing options\"\n                                             \" (all angles are in units of pi radians)\",\n                                             help_text_length);\n  addressing_options.add_options()\n    (\"target\", po::value<vector<uint>>(&target_nuclei)->multitoken(),\n     \"indices of nuclei to target\")\n    (\"target_pairs\",\n     po::value<bool>(&target_pairs)->default_value(false)->implicit_value(true),\n     \"target only one nucleus in each larmor pair\")\n    (\"angle\", po::value<double>(&angle_over_pi)->default_value(1),\n     \"angle of operation to perform\")\n    (\"target_pitch\", po::value<double>(&target_pitch_over_pi)->default_value(0),\n     \"pitch (angle above x-y plane) of target rotation axis\")\n    (\"target_azimuth\", po::value<double>(&target_azimuth_over_pi)->default_value(0),\n     \"azimuthal angle of target rotation axis\")\n    (\"nv_pitch\", po::value<double>(&nv_pitch_over_pi)->default_value(0.5),\n     \"pitch (angle above x-y plane) of NV rotation axis\")\n    (\"nv_azimuth\", po::value<double>(&nv_azimuth_over_pi)->default_value(0),\n     \"azimuthal angle of NV rotation axis\")\n    ;\n\n  uint coherence_bins;\n  double scan_time;\n  double scan_time_in_ms;\n  double f_DD;\n  uint angular_resolution;\n  double signal_gB_factor;\n  double max_f_factor;\n\n  po::options_description scan_options(\"Coherence measurement options\",help_text_length);\n  scan_options.add_options()\n    (\"bins\", po::value<uint>(&coherence_bins)->default_value(500),\n     \"number of bins in coherence measurements\")\n    (\"scan_time\", po::value<double>(&scan_time_in_ms)->default_value(1),\n     \"time for each measurement in the coherence scan (microseconds)\")\n    (\"f_DD\", po::value<double>(&f_DD)->default_value(0.06,\"0.06\"),\n     \"magnitude of fourier component used in coherence scanning\")\n    (\"angular_resolution\", po::value<uint>(&angular_resolution)->default_value(20),\n     \"angular resolution for magnetic field direction during signal measurement\"\n     \" (1/[pi radians])\")\n    (\"signal_gB_factor\", po::value<double>(&signal_gB_factor)->default_value(100),\n     \"sets signal field strength to static_gBz/signal_gB_factor\")\n    (\"max_f_factor\", po::value<double>(&max_f_factor)->default_value(0.5),\n     \"factor scaling maximum value of f_DD in coherence signal measurement\")\n    ;\n\n  string lattice_file;\n\n  po::options_description file_io(\"File IO\",help_text_length);\n  file_io.add_options()\n    (\"lattice_file\", po::value<string>(&lattice_file),\n     \"input file defining system configuration\")\n    ;\n\n  bool print_lattice;\n  bool target_info;\n\n  po::options_description print_options(\"Available printing options\",help_text_length);\n  print_options.add_options()\n    (\"print_lattice\",\n     po::value<bool>(&print_lattice)->default_value(false)->implicit_value(true),\n     \"print C-13 lattice to a file\")\n    (\"target_info\",\n     po::value<bool>(&target_info)->default_value(false)->implicit_value(true),\n     \"print information about target nuclei\")\n    ;\n\n  po::options_description all(\"Allowed options\");\n  all.add(general);\n  all.add(simulations);\n  all.add(simulation_options);\n  all.add(addressing_options);\n  all.add(scan_options);\n  all.add(file_io);\n  all.add(print_options);\n\n  // collect inputs\n  po::variables_map inputs;\n  po::store(parse_command_line(arg_num, arg_vec, all), inputs);\n  po::notify(inputs);\n\n\n  // if requested, print help text\n  if (inputs.count(\"help\")) {\n    cout << all;\n    return 0;\n  }\n\n\n  // -------------------------------------------------------------------------------------\n  // Run a sanity check on inputs\n  // -------------------------------------------------------------------------------------\n\n  // determine whether certain options were used\n  bool using_input_lattice = inputs.count(\"lattice_file\");\n  bool set_hyperfine_cutoff = !inputs[\"hyperfine_cutoff\"].defaulted();\n  bool set_c13_factor = !inputs[\"c13_factor\"].defaulted();\n  bool set_target_nuclei = inputs.count(\"target\");\n\n  // make sure we are either printing something, or performing a simulation\n  if (!testing_mode) {\n    const bool printing = print_lattice || target_info;\n    if (!printing) {\n      if (int(pair_search)\n          + int(coherence_scan)\n          + int(coherence_signal)\n          + int(angular_coherence_signal)\n          + int(rotation)\n          + int(coupling)\n          + int(iswap)\n          + int(swap)\n          + int(identity)\n          + int(swap_nvst)\n          + int(larmor_identity)\n          + int(initialize)\n          + int(initialize_x)\n          + int(initialize_larmor)\n          != 1) {\n        cout << \"Please choose one simulation to perform\\n\";\n        return -1;\n      }\n    }\n  }\n\n  // check lattice options\n  assert(!(print_lattice && using_input_lattice));\n  assert(!(using_input_lattice && !fs::exists(lattice_file)));\n  assert(!(using_input_lattice && set_hyperfine_cutoff));\n  assert(!(using_input_lattice && set_c13_factor));\n\n  // check targeting options\n  assert(!(set_target_nuclei && target_pairs));\n\n  // verify validity of other values\n  assert(hyperfine_cutoff_in_kHz > 0);\n  assert(c13_factor >= 0);\n  assert(nuclear_isolation >= 0);\n  assert(larmor_isolation_in_kHz >= 0);\n  assert(min_hyperfine_xy_in_kHz >= 0);\n  assert(max_cluster_size > 0);\n  assert(ms == 1 || ms == -1);\n  assert((k_DD_int == 1) || (k_DD_int == 3));\n  assert(scale_factor > 1);\n  assert(integration_factor > 1);\n\n  if (coherence_scan) {\n    assert(coherence_bins > 0);\n    assert(scan_time_in_ms > 0);\n  }\n  assert(angular_resolution > 2);\n  assert(signal_gB_factor > 1);\n  assert(max_f_factor <= 1);\n\n  // set some variables based on iputs\n  c13_abundance = c13_factor*c13_natural_abundance;\n  larmor_isolation = larmor_isolation_in_kHz * 1e3;\n  min_hyperfine_xy = min_hyperfine_xy_in_kHz * 1e3;\n  hyperfine_cutoff = hyperfine_cutoff_in_kHz * 1e3;\n  k_DD = (k_DD_int == 1 ? first : third);\n  static_Bz = static_Bz_in_gauss * gauss;\n  scan_time = scan_time_in_ms * 1e-3;\n\n  angle = angle_over_pi * pi;\n  target_polar = pi/2 - target_pitch_over_pi * pi;\n  target_azimuth = target_azimuth_over_pi * pi;\n  nv_polar = pi/2 - nv_pitch_over_pi * pi;\n  nv_azimuth = nv_azimuth_over_pi * pi;\n\n  uniform_real_distribution<double> rnd(0.0,1.0); // uniform distribution on [0,1)\n  mt19937_64 generator(seed); // use and seed the 64-bit Mersenne Twister 19937 generator\n\n  // -------------------------------------------------------------------------------------\n  // Construct lattice of nuclei\n  // -------------------------------------------------------------------------------------\n\n  vector<Vector3d> nuclei;\n\n  if (!using_input_lattice) { // place nuclei at lattice sites\n\n    // number of fcc cells to simulate out from the origin\n    const int cell_radius\n      = round(pow(abs(g_e*g_C13)/(4*pi*a0*a0*a0*hyperfine_cutoff),1.0/3));\n\n    // set positions of nuclei at lattice sites\n    for (uint b: {0,1}) {\n      for (int l = -2*cell_radius; l <= 2*cell_radius; l++) {\n        for (int m = -2*cell_radius; m <= 2*cell_radius; m++) {\n          for (int n = -2*cell_radius; n <= 2*cell_radius; n++) {\n            if (rnd(generator) < c13_abundance) { // check for C-13 isotopic abundance\n              if (l != 0 || m != 0 || n != 0) { // don't place C-13 nucleus on NV sites\n                const Vector3d pos = b*ao+l*a1+m*a2+n*a3;\n                // only place C-13 nuclei with a hyperfine field strength above the cutoff\n                if (hyperfine(pos).norm() > hyperfine_cutoff) {\n                  nuclei.push_back(pos);\n                }\n              }\n            }\n          }\n        }\n      }\n    }\n    cout << \"Placed \" << nuclei.size() << \" C-13 nuclei\\n\\n\";\n    if (nuclei.size() == 0) return 0;\n\n    if (print_lattice) {\n      for (uint i = 0; i < nuclei.size(); i++) {\n        cout << nuclei.at(i)(0) << \" \"\n             << nuclei.at(i)(1) << \" \"\n             << nuclei.at(i)(2) << endl;\n      }\n    }\n\n  } else { // if using_input_lattice, read in the lattice\n\n    string line;\n    ifstream lattice(lattice_file);\n\n    // get C-13 positions\n    double x,y,z;\n    while (getline(lattice,line,' ')) {\n      x = stod(line);\n      getline(lattice,line,' ');\n      y = stod(line);\n      getline(lattice,line);\n      z = stod(line);\n      nuclei.push_back((Vector3d() << x,y,z).finished());\n    }\n    lattice.close();\n\n    // assert that no C-13 nuclei lie at the NV lattice sites\n    for (uint i = 0; i < nuclei.size(); i++) {\n      if ((nuclei.at(i) == n_pos) || (nuclei.at(i) == e_pos)) {\n        cout << \"The input lattice places a C-13 nucleus at one of the NV lattice sites!\"\n             << endl;\n        return -1;\n      }\n    }\n  }\n\n  // -------------------------------------------------------------------------------------\n  // Characterize nuclei and targets\n  // -------------------------------------------------------------------------------------\n\n  // identify nuclei which cannot be addressed\n  vector<uint> addressable_nuclei;\n  vector<uint> unaddressable_nuclei;\n  for (uint n = 0; n < nuclei.size(); n++) {\n    if (can_address(nuclei,n)) {\n      addressable_nuclei.push_back(n);\n    } else {\n      unaddressable_nuclei.push_back(n);\n    }\n  }\n  if (unaddressable_nuclei.size() > 0) {\n    cout << \"The following nuclei cannot be addressed:\";\n    for (uint n: unaddressable_nuclei) {\n      cout << \" \" << n;\n    }\n    cout << endl << endl;\n  }\n\n  // identify larmor pairs\n  vector<uint> larmor_nuclei;\n  vector<vector<uint>> larmor_pairs;\n  for (uint i = 0; i < addressable_nuclei.size(); i++) {\n    const uint n_i = addressable_nuclei.at(i);\n    for (uint j = i+1; j < addressable_nuclei.size(); j++) {\n      const uint n_j = addressable_nuclei.at(j);\n      if (is_larmor_pair(nuclei,n_i,n_j)) {\n        larmor_nuclei.push_back(n_i);\n        larmor_nuclei.push_back(n_j);\n        larmor_pairs.push_back({n_i,n_j});\n        continue;\n      }\n    }\n  }\n\n  // if we are only doing a search for isolated larmor pairs, do it now\n  if (pair_search) {\n    cout << \"Starting search for isolated larmor pairs...\" << endl;\n    cout << \"idx1 idx2 hyperfine_xy\" << endl;\n    for (vector<uint> larmor_pair: larmor_pairs) {\n      const uint ln_1 = larmor_pair.at(0);\n      const uint ln_2 = larmor_pair.at(1);\n      const double A_z = hyperfine_z(nuclei.at(ln_1));\n      const double A_xy = hyperfine_xy(nuclei.at(ln_1));\n\n      if (A_xy <= min_hyperfine_xy) continue;\n\n      bool isolated_pair = (strong_field_coupling(nuclei, ln_1, ln_2)\n                            <= nuclear_isolation);\n      if (!isolated_pair) continue;\n\n      for (uint n = 0; n < nuclei.size(); n++) {\n        if (n == ln_1 || n == ln_2) continue;\n        if (strong_field_coupling(nuclei, n, ln_1) > nuclear_isolation ||\n            strong_field_coupling(nuclei, n, ln_2) > nuclear_isolation ||\n            (abs(hyperfine_z(nuclei.at(n)) - A_z) < larmor_isolation)) {\n          isolated_pair = false;\n          break;\n        }\n      }\n      if (!isolated_pair) continue;\n\n      cout << ln_1 << \" \" << ln_2 << \" \" << A_xy << endl;\n    }\n    return 0;\n  }\n\n  // determine which nuclei to target\n  if (!set_target_nuclei) {\n    if (target_pairs) target_nuclei = larmor_nuclei;\n    else target_nuclei = addressable_nuclei;\n\n  } else { // if (set_target_nuclei)\n    vector<uint> unaddressable_targets;\n    for (uint t_i = 0; t_i < target_nuclei.size(); t_i++) {\n      if (in_vector(target_nuclei.at(t_i),unaddressable_nuclei)) {\n        unaddressable_targets.push_back(target_nuclei.at(t_i));\n        target_nuclei.erase(target_nuclei.begin()+t_i);\n        t_i--;\n      }\n    }\n    if (unaddressable_targets.size() > 0) {\n      cout << \"(WARNING) Ignoring following target nuclei:\";\n      for (uint n: unaddressable_targets) {\n        cout << \" \" << n;\n      }\n      cout << endl << endl;\n    }\n  }\n  if (target_nuclei.size() == 0) {\n    cout << \"There are no target nuclei.\" << endl;\n    return 0;\n  }\n\n  // identify targeted larmor pairs\n  vector<vector<uint>> targeted_larmor_pairs;\n  for (uint i = 0; i < target_nuclei.size(); i++) {\n    const uint n_i = target_nuclei.at(i);\n    for (uint j = i+1; j < target_nuclei.size(); j++) {\n      const uint n_j = target_nuclei.at(j);\n      if (is_larmor_pair(nuclei,n_i,n_j)) {\n        targeted_larmor_pairs.push_back({n_i,n_j});\n        continue;\n      }\n    }\n  }\n\n  if (swap_nvst || larmor_identity) {\n    if (targeted_larmor_pairs.size() == 0) {\n      if (larmor_pairs.size() == 0) {\n        cout << \"There are no larmor pairs in this system\\n\";\n      } else {\n        cout << \"No larmor pairs are targeted\\n\";\n      }\n      return -1;\n    }\n  }\n\n  // -------------------------------------------------------------------------------------\n  // Cluster C-13 nuclei\n  // -------------------------------------------------------------------------------------\n\n  // unless we are performing a coherence scan, we will be grouping together clusters by\n  //  the larmor frequencies of the nuclei, so first we check whether doing so is possible\n  //  for the given min_cluster_size_cap\n  const uint min_cluster_size_cap = smallest_possible_cluster_size(nuclei);\n  const bool cluster_larmor_pairs =\n    !(coherence_scan || (max_cluster_size < min_cluster_size_cap));\n  if (!coherence_scan) {\n    cout << \"The minimum cluster size cap is \" << min_cluster_size_cap << endl;\n    if (!testing_mode && (max_cluster_size < min_cluster_size_cap)) return -1;\n  }\n\n  const vector<vector<uint>> clusters = cluster_nuclei(nuclei, max_cluster_size,\n                                                       cluster_larmor_pairs);\n  const double cluster_coupling = get_cluster_coupling(nuclei,clusters);\n\n  cout << \"Nuclei grouped into \" << clusters.size() << \" clusters\"\n       << \" with a coupling factor of \" << cluster_coupling << \" Hz\\n\";\n\n  // collect and print histogram of cluster sizes\n  vector<uint> size_hist(largest_cluster_size(clusters));\n  for (uint i = 0; i < clusters.size(); i++) {\n    size_hist.at(clusters.at(i).size()-1) += 1;\n  }\n  cout << \"Cluster size histogram:\\n\";\n  for (uint i = 0; i < size_hist.size(); i++) {\n    cout << \"  \" << i+1 << \": \" << size_hist.at(i) << endl;\n  }\n  cout << endl;\n\n  // initialize nv_system object\n  const nv_system nv(nuclei, clusters, ms, g_C13*static_Bz, k_DD,\n                     scale_factor, integration_factor, no_nn);\n\n  // -------------------------------------------------------------------------------------\n  // Print info about target nuclei\n  // -------------------------------------------------------------------------------------\n\n  if (target_info) {\n    cout << \"Target info:\\n\\n\";\n    for (uint n: target_nuclei) {\n      cout << \"index: \" << n << endl\n           << \"position (nm): \"\n           << in_crystal_basis(nv.nuclei.at(n)).transpose() * a0/2 / nm << endl\n           << \"effective_larmor (kHz): \" << effective_larmor(nv,n).norm() * 1e-3 << endl\n           << \"hyperfine (kHz): \" << hyperfine(nv,n).norm() * 1e-3 << endl\n           << \"hyperfine_perp (kHz): \" << hyperfine_perp(nv,n).norm() * 1e-3 << endl\n           << endl;\n    }\n    for (uint i = 0; i < target_nuclei.size(); i++) {\n      const Vector3d pos_i = nv.nuclei.at(target_nuclei.at(i));\n      for (uint j = i + 1; j < target_nuclei.size(); j++) {\n        const Vector3d pos_j = nv.nuclei.at(target_nuclei.at(j));\n        cout << \"indices: \" << i << \" \" << j << endl\n             << \"displacement (nm): \"\n             << in_crystal_basis(pos_j-pos_i).transpose() * a0/2 / nm << endl\n             << \"coupling (Hz): \" << coupling_strength(pos_i,pos_j) << endl\n             << \"strong field coupling (Hz): \"\n             <<  strong_field_coupling(pos_i,pos_j) << endl\n             << endl;\n      }\n    }\n  }\n\n\n  // -------------------------------------------------------------------------------------\n  // Coherence scan\n  // -------------------------------------------------------------------------------------\n\n  if (coherence_scan) {\n    cout << endl\n         << \"Larmor and hyperfine frequency data:\" << endl\n         << \"# format: w_larmor A_perp\" << endl;\n\n    double w_max = 0, w_min = DBL_MAX;\n    for (uint i = 0; i < nv.nuclei.size(); i++) {\n      const double A_perp = hyperfine_perp(nv,i).norm();\n      const double w_larmor = effective_larmor(nv,i).norm();\n      cout << i << \" \" << w_larmor << \" \" << A_perp << endl;\n\n      if (w_larmor < w_min) w_min = w_larmor;\n      if (w_larmor > w_max) w_max = w_larmor;\n    }\n\n    cout << endl\n         << \"Coherence scan results:\" << endl\n         << \"# format: w_scan coherence\" << endl;\n    const double w_range = max(w_max - w_min, 1e5);\n    const double w_start = max(w_min - w_range/10, 0.);\n    const double w_end = w_max + w_range/10;\n    for (uint i = 0; i < coherence_bins; i++) {\n      const double w_scan = w_start + (i+0.5)*(w_end-w_start)/coherence_bins;\n      const double coherence = coherence_measurement(nv, w_scan, f_DD, scan_time);\n      cout << w_scan << \" \" << coherence << endl;\n    }\n\n  }\n\n  // -------------------------------------------------------------------------------------\n  // Coherence signal\n  // -------------------------------------------------------------------------------------\n\n  if (coherence_signal || angular_coherence_signal) {\n    cout << \"Coherence signal results:\" << endl\n         << \"# k_DD: \" << nv.k_DD << endl;\n    cout << \"# format: f_DD coherence(s)\" << endl;\n\n    for (uint target: target_nuclei) {\n      // only perform this measurement once for larmor pairs\n      vector<uint> targets = {target};\n      for (uint nn: target_nuclei) {\n        if (nn == target) continue;\n        if (is_larmor_pair(nv,nn,target)) targets.push_back(nn);\n      }\n      if (targets.size() == 2 && targets.at(0) > targets.at(1)) continue;\n\n      cout << \"# targets:\";\n      for (uint nn: targets) cout << \" \" << nn;\n      cout << endl;\n      if (angular_coherence_signal) {\n        cout << \"# azimuths/pi:\";\n        for (uint nn: targets) {\n          const double angular_pos = atan2(dot(nv.nuclei.at(nn),yhat),\n                                           dot(nv.nuclei.at(nn),xhat));\n          cout << \" \" << angular_pos/pi;\n        }\n        cout << endl;\n      }\n\n      // determine control field to use during coherence signal measurement\n      const double w_signal = effective_larmor(nv,target).norm();\n      const double phi_dec = [&]() -> double {\n        if (!angular_coherence_signal) return angle;\n        else return 0;\n      }();\n      const control_fields controls(nv.static_gBz/signal_gB_factor*xhat,\n                                    w_signal, phi_dec);\n      cout << \"# phi_dec/pi: \" << phi_dec/pi << endl;\n\n      // fix coherence signal measurement time\n      const double measurement_time = 4*pi / (axy_f_max(nv.k_DD) * max_f_factor\n                                              * hyperfine_perp(nv,target).norm() / 4);\n      cout << \"# measurement_time (ms): \" << measurement_time * 1e3 << endl;\n\n      for (uint ii = 0; ii < coherence_bins; ii++) {\n        const double f_DD = (ii+0.5)/coherence_bins * axy_f_max(nv.k_DD) * max_f_factor;\n\n        if (!angular_coherence_signal) {\n          const double coherence =\n            coherence_measurement(nv, w_signal, f_DD, measurement_time, controls);\n          cout << f_DD << \" \" << coherence << endl;\n\n        } else {\n          cout << f_DD;\n          for (uint jj = 0; jj < angular_resolution; jj++) {\n            const double phi_DD = (jj+0.5)/angular_resolution * pi;\n            const double coherence =\n              coherence_measurement(nv, w_signal, f_DD, measurement_time,\n                                    controls, phi_DD);\n            cout << \" \" << coherence;\n          }\n          cout << endl;\n        }\n      }\n    }\n  }\n\n  // -------------------------------------------------------------------------------------\n  // Individual addressing -- control\n  // -------------------------------------------------------------------------------------\n\n  if (rotation) {\n    cout << \"target fidelity time pulses\\n\";\n    for (uint target: target_nuclei) {\n      const Vector3d target_axis = axis(target_polar,target_azimuth);\n      vector<protocol> P(2);\n      for (bool exact : {true,false}) {\n        P.at(exact) = rotate_target(nv, target, angle, target_axis, exact);\n      }\n      const uint subsystem_target = get_index_in_subsystem(nv, target);\n      cout << target << \" \"\n           << protocol_fidelity(P, {subsystem_target}) << \" \"\n           << P.at(false).time << \" \"\n           << P.at(false).pulses << endl;\n    }\n  }\n\n  // -------------------------------------------------------------------------------------\n  // Individual addressing -- NV coupling\n  // -------------------------------------------------------------------------------------\n\n  if (coupling) {\n    cout << \"target fidelity time pulses\\n\";\n    const Vector3d nv_axis = axis(nv_polar, nv_azimuth);\n    for (uint target: target_nuclei) {\n      const Vector3d target_axis = axis(target_polar, target_azimuth);\n      vector<protocol> P(2);\n      for (bool exact : {true,false}) {\n        P.at(exact) = couple_target(nv, target, angle, nv_axis, target_axis, exact);\n      }\n      const uint subsystem_target = get_index_in_subsystem(nv, target);\n      cout << target << \" \"\n           << protocol_fidelity(P, {0, subsystem_target}) << \" \"\n           << P.at(false).time << \" \"\n           << P.at(false).pulses << endl;\n    }\n  }\n\n  // -------------------------------------------------------------------------------------\n  // NV/nucleus iSWAP fidelity\n  // -------------------------------------------------------------------------------------\n\n  if (iswap) {\n    cout << \"target fidelity time pulses\\n\";\n    for (uint target: target_nuclei) {\n      vector<protocol> P(2);\n      for (bool exact : {true,false}) {\n        P.at(exact) = iSWAP(nv, target, exact);\n      }\n      const uint subsystem_target = get_index_in_subsystem(nv, target);\n      cout << target << \" \"\n           << protocol_fidelity(P, {0, subsystem_target}) << \" \"\n           << P.at(false).time << \" \"\n           << P.at(false).pulses << endl;\n    }\n  }\n\n  // -------------------------------------------------------------------------------------\n  // SWAP fidelity: NV electron spin and single nuclear spin\n  // -------------------------------------------------------------------------------------\n\n  if (swap) {\n    cout << \"target fidelity time pulses\\n\";\n    for (uint target: target_nuclei) {\n      vector<protocol> P(2);\n      for (bool exact : {true,false}) {\n        P.at(exact) = SWAP(nv, target, exact);\n      }\n      const uint subsystem_target = get_index_in_subsystem(nv, target);\n      cout << target << \" \"\n           << protocol_fidelity(P, {0, subsystem_target}) << \" \"\n           << P.at(false).time << \" \"\n           << P.at(false).pulses << endl;\n    }\n  }\n\n  // -------------------------------------------------------------------------------------\n  // Fidelity of identity operation on a single spin\n  // -------------------------------------------------------------------------------------\n\n  if (identity) {\n    cout << \"target fidelity\\n\";\n    for (uint target: target_nuclei) {\n      vector<protocol> P(2);\n      for (bool exact : {true,false}) {\n        P.at(exact) = target_identity(nv, target, identity_time, exact);\n      }\n      const uint cluster_target = get_index_in_cluster(nv, target);\n      cout << target << \" \"\n           << protocol_fidelity(P, {cluster_target}) << endl;\n    }\n  }\n\n  // -------------------------------------------------------------------------------------\n  // SWAP fidelity: NV electron spin and singlet-triplet subspace of two nuclear spins\n  // -------------------------------------------------------------------------------------\n\n  if (swap_nvst) {\n    cout << \"idx1 idx2 fidelity time pulses\\n\";\n    for (vector<uint> idxs: targeted_larmor_pairs) {\n      const uint idx1 = idxs.at(0);\n      const uint idx2 = idxs.at(1);\n      vector<protocol> P(2);\n      for (bool exact : {true,false}) {\n        P.at(exact) = SWAP_NVST(nv, idx1, idx2, exact);\n      }\n      const uint ss_idx1 = get_index_in_subsystem(nv,idx1);\n      const uint ss_idx2 = get_index_in_subsystem(nv,idx2);\n      cout << idx1 << \" \" << idx2 << \" \"\n           << protocol_fidelity(P, {0, ss_idx1, ss_idx2}) << \" \"\n           << P.at(false).time << \" \"\n           << P.at(false).pulses << endl;\n    }\n  }\n\n  // -------------------------------------------------------------------------------------\n  // Fidelity of identity operation on a larmor qubit\n  // -------------------------------------------------------------------------------------\n\n  if (larmor_identity) {\n    cout << \"idx1 idx2 fidelity\\n\";\n    const bool targeting_pair = true;\n    for (vector<uint> idxs: targeted_larmor_pairs) {\n      const uint idx1 = idxs.at(0);\n      const uint idx2 = idxs.at(1);\n      vector<protocol> P(2);\n      for (bool exact : {true,false}) {\n        P.at(exact) = target_identity(nv, idx1, identity_time, exact, targeting_pair);\n      }\n      const uint cluster_idx1 = get_index_in_cluster(nv,idx1);\n      const uint cluster_idx2 = get_index_in_cluster(nv,idx2);\n      cout << idx1 << \" \" << idx2 << \" \"\n           << protocol_fidelity(P, {cluster_idx1, cluster_idx2}) << endl;\n    }\n  }\n\n  // -------------------------------------------------------------------------------------\n  // Fidelity of deterministically initializing a thermalized nucleus into |u> or |d>\n  // -------------------------------------------------------------------------------------\n\n  if (initialize) {\n    cout << \"target fidelity time pulses\\n\";\n    for (uint target: target_nuclei) {\n      vector<protocol> P(2);\n      for (bool exact : {true,false}) {\n        P.at(exact) = initialize_spin(nv, target, exact);\n      }\n      const uint subsystem_target = get_index_in_subsystem(nv, target);\n      cout << target << \" \"\n           << protocol_fidelity(P, {0, subsystem_target}) << \" \"\n           << P.at(false).time << \" \"\n           << P.at(false).pulses << endl;\n    }\n  }\n\n  // -------------------------------------------------------------------------------------\n  // Fidelity of probabalistically initializing a thermalized nucleus into |u> +/- |d>\n  // -------------------------------------------------------------------------------------\n\n  if (initialize_x) {\n    cout << \"target fidelity time pulses\\n\";\n    for (uint target: target_nuclei) {\n      vector<protocol> P(2);\n      for (bool exact : {true,false}) {\n        P.at(exact) = initialize_spin_X(nv, target, exact);\n      }\n      const uint subsystem_target = get_index_in_subsystem(nv, target);\n      cout << target << \" \"\n           << protocol_fidelity(P, {0, subsystem_target}) << \" \"\n           << P.at(false).time << \" \"\n           << P.at(false).pulses << endl;\n    }\n  }\n\n  // -------------------------------------------------------------------------------------\n  // Fidelity of probabalistically initializing a larmor pair from |dd> into |ud> +/- |du>\n  // -------------------------------------------------------------------------------------\n\n  if (initialize_larmor) {\n    cout << \"idx1 idx2 fidelity time pulses\\n\";\n    for (vector<uint> idxs: targeted_larmor_pairs) {\n      const uint idx1 = idxs.at(0);\n      const uint idx2 = idxs.at(1);\n      vector<protocol> P(2);\n      for (bool exact : {true,false}) {\n        P.at(exact) = initialize_larmor_qubit(nv, idx1, idx2, exact);\n      }\n      const uint ss_idx1 = get_index_in_subsystem(nv,idx1);\n      const uint ss_idx2 = get_index_in_subsystem(nv,idx2);\n      cout << idx1 << \" \" << idx2 << \" \"\n           << protocol_fidelity(P, {0, ss_idx1, ss_idx2}) << \" \"\n           << P.at(false).time << \" \"\n           << P.at(false).pulses << endl;\n    }\n  }\n\n}\n", "meta": {"hexsha": "f60cd99f4dc111be63aec7cf58475a62ad7cca0d", "size": 34680, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "simulation.cpp", "max_stars_repo_name": "perlinm/qcdg-nv-simulation", "max_stars_repo_head_hexsha": "a41091f9715bb29bf4fc2b6acb9d22a04bb2c6e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "simulation.cpp", "max_issues_repo_name": "perlinm/qcdg-nv-simulation", "max_issues_repo_head_hexsha": "a41091f9715bb29bf4fc2b6acb9d22a04bb2c6e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "simulation.cpp", "max_forks_repo_name": "perlinm/qcdg-nv-simulation", "max_forks_repo_head_hexsha": "a41091f9715bb29bf4fc2b6acb9d22a04bb2c6e2", "max_forks_repo_licenses": ["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.6622073579, "max_line_length": 90, "alphanum_fraction": 0.5690311419, "num_tokens": 8407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038785, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.46575648273374215}}
{"text": "#include <boost/program_options.hpp>\n#include <frovedis.hpp>\n#include <frovedis/ml/clustering/gmm.hpp>\n\nusing namespace boost;\nusing namespace frovedis;\nusing namespace std;\n\ntemplate <class T>\nvoid do_gmm(const string& input, const string& output, int k, \n            const string& cov_type, const string& init_params, \n            int n_init, int num_iteration, \n            double eps, long seed, bool binary) {\n  rowmajor_matrix<T> mat;\n  time_spent t(DEBUG);\n  if (binary) {\n    mat = make_rowmajor_matrix_loadbinary<T>(input);\n    t.show(\"load matrix: \");\n  } else {\n    mat = make_rowmajor_matrix_load<T>(input);\n    t.show(\"load matrix: \");\n  }\n  auto gmm_model = frovedis::gaussian_mixture<T>(k, cov_type, \n                   eps, num_iteration, init_params, seed);\n  gmm_model.fit(mat);\n  t.show(\"train: \");\n  LOG(DEBUG) << \"number of loops until convergence: \" << gmm_model.n_iter_()\n             << std::endl;\n  LOG(DEBUG) << \"likelihood: \" << gmm_model.lower_bound_() << std::endl;\n  binary ? gmm_model.savebinary(output) : gmm_model.save(output);\n  t.show(\"model save: \");\n}\n\ntemplate <class T>\nvoid do_assign(const string& input, const string& input_cluster,\n               const string& output, int k, bool binary) {\n  auto gmm_model = frovedis::gaussian_mixture<T>(k);\n  if (!directory_exists(output)) make_directory(output);\n  if (binary) {\n    time_spent t(DEBUG);\n    auto mat = make_rowmajor_matrix_loadbinary<T>(input);\n    t.show(\"load matrix: \");\n    gmm_model.loadbinary(input_cluster);  \n    t.show(\"load model: \");  \n    auto pred = gmm_model.predict(mat);\n    auto prob = gmm_model.predict_proba(mat);\n    t.show(\"prediction time: \");\n    auto score = gmm_model.score(mat); \n    std::cout << \"score: \" << score << std::endl;\n    make_dvector_scatter(pred).savebinary(output + \"/prediction\");\n    prob.savebinary(output + \"/probability\");\n    t.show(\"prediction save: \");\n  } else {\n    time_spent t(DEBUG);\n    auto mat = make_rowmajor_matrix_load<T>(input);\n    t.show(\"load matrix: \");\n    gmm_model.load(input_cluster);  \n    t.show(\"load model: \");  \n    auto pred = gmm_model.predict(mat);\n    auto prob = gmm_model.predict_proba(mat);\n    t.show(\"prediction time: \");\n    auto score = gmm_model.score(mat); \n    std::cout << \"score: \" << score << std::endl;\n    make_dvector_scatter(pred).saveline(output + \"/predict\");\n    prob.save(output + \"/predict_prob\");\n    t.show(\"prediction save: \");\n  }\n}\n\nint main(int argc, char* argv[]) {\n  use_frovedis use(argc, argv);\n\n  using namespace boost::program_options;\n\n  options_description opt(\"option\");\n  // clang-format off\n  opt.add_options()(\"help,h\", \"print help\")\n    (\"assign,a\", \"assign data to cluster mode\")\n    (\"input,i\", value<string>(),\"input matrix\")\n    (\"cluster,c\", value<string>(), \"input model,cov,pi for assignment\")\n    (\"output,o\", value<string>(), \"output centroids or cluster\")\n    (\"k,k\", value<int>(), \"number of clusters\")\n    (\"cov-type,v\", value<string>(), \"covariance type (default: full)\")  \n    (\"num-init,t\", value<int>(),\"number of time for running with different centroid seeds (default: 1)\")\n    (\"num-iteration,n\", value<int>(),\"maximum number of iteration (default: 300)\")\n    (\"eps,e\", value<double>(),\"epsilon to stop the iteration (default: 0.001)\")\n    (\"init-params,p\", value<string>(), \"initialization method [kmeans or random] (default: kmeans)\")  \n    (\"seed,r\", value<long>(), \"seed for init randomizer (default: 123)\")\n    (\"float\", \"for float type input\")\n    (\"double\",\"for double type input (default)\")\n    (\"verbose\", \"set loglevel to DEBUG\")\n    (\"verbose2\", \"set loglevel to TRACE\")\n    (\"binary,b\", \"use binary input/output\");\n  // clang-format on\n  variables_map argmap;\n  store(command_line_parser(argc, argv).options(opt).allow_unregistered().run(),\n        argmap);\n  notify(argmap);\n\n  string input, output, input_cluster;\n  string cov_type = \"full\", init_params = \"kmeans\";  \n  int k = 0;\n  int num_iteration = 300, n_init = 1;\n  double eps = 0.001;\n  long seed = 123;\n  bool assign = false;\n  bool binary = false;\n\n  if (argmap.count(\"help\")) {\n    cerr << opt << endl;\n    exit(1);\n  }\n\n  if (argmap.count(\"input\")) {\n    input = argmap[\"input\"].as<string>();\n  } else {\n    cerr << \"input is not specified\" << endl;\n    cerr << opt << endl;\n    exit(1);\n  }\n\n  if (argmap.count(\"output\")) {\n    output = argmap[\"output\"].as<string>();\n  } else {\n    cerr << \"output is not specified\" << endl;\n    cerr << opt << endl;\n    exit(1);\n  }\n\n  if (argmap.count(\"assign\")) {\n    assign = true;\n  }\n\n  if (argmap.count(\"cluster\")) {\n    input_cluster = argmap[\"cluster\"].as<string>();\n  } else {\n    if (assign == true) {\n      cerr << \"cluster is not specified\" << endl;\n      cerr << opt << endl;\n      exit(1);\n    }\n  }\n\n  if (argmap.count(\"k\")) {\n    k = argmap[\"k\"].as<int>();\n  } else {\n    if (assign == false) {\n      cerr << \"number of cluster is not specified\" << endl;\n      cerr << opt << endl;\n      exit(1);\n    }\n  }\n\n  if(argmap.count(\"cov-type\")) {\n    cov_type = argmap[\"cov-type\"].as<string>();\n  }\n    \n  if(argmap.count(\"init-params\")){\n    init_params = argmap[\"init-params\"].as<string>();\n  }    \n    \n  if (argmap.count(\"num-iteration\")) {\n    num_iteration = argmap[\"num-iteration\"].as<int>();\n  }\n\n  if (argmap.count(\"num-init\")) {\n    n_init = argmap[\"num-init\"].as<int>();\n  }\n\n  if (argmap.count(\"epsilon\")) {\n    eps = argmap[\"epsilon\"].as<double>();\n  }\n\n  if (argmap.count(\"seed\")) {\n    seed = argmap[\"seed\"].as<long>();\n  }\n  if (argmap.count(\"binary\")) {\n    binary = true;\n  }\n  if (argmap.count(\"verbose\")) {\n    set_loglevel(DEBUG);\n  }\n  if (argmap.count(\"verbose2\")) {\n    set_loglevel(TRACE);\n  }\n\n  if (assign) {\n    if(argmap.count(\"double\")) \n      do_assign<double>(input, input_cluster, output, k, binary);\n    else \n      do_assign<float>(input, input_cluster, output, k, binary);\n  }\n  else {\n    if(argmap.count(\"double\")) \n      do_gmm<double>(input, output, k, cov_type, init_params, \n                     n_init, num_iteration, eps, seed, binary);\n    else \n      do_gmm<float>(input, output, k, cov_type, init_params, \n                    n_init, num_iteration, eps, seed, binary);\n  }\n}\n", "meta": {"hexsha": "619aa929b26993acd9d0a632422b4955079e5cc6", "size": 6178, "ext": "cc", "lang": "C++", "max_stars_repo_path": "samples/gmm/gmm.cc", "max_stars_repo_name": "XpressAI/frovedis", "max_stars_repo_head_hexsha": "bda0f2c688fb832671c5b542dd8df1c9657642ff", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 63.0, "max_stars_repo_stars_event_min_datetime": "2018-06-21T14:11:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T11:24:36.000Z", "max_issues_repo_path": "samples/gmm/gmm.cc", "max_issues_repo_name": "XpressAI/frovedis", "max_issues_repo_head_hexsha": "bda0f2c688fb832671c5b542dd8df1c9657642ff", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2018-09-22T14:01:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-27T16:11:05.000Z", "max_forks_repo_path": "samples/gmm/gmm.cc", "max_forks_repo_name": "XpressAI/frovedis", "max_forks_repo_head_hexsha": "bda0f2c688fb832671c5b542dd8df1c9657642ff", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2018-08-23T15:59:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T06:47:22.000Z", "avg_line_length": 30.5841584158, "max_line_length": 104, "alphanum_fraction": 0.6136290062, "num_tokens": 1671, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.4657068372317761}}
{"text": "/**\n * @file systematic.hpp\n * @author Vahid Bastani\n *\n * Systematic resampling method\n */\n#ifndef SSMPACK_FILTER_RESAMPLER_SYSTEMATIC\n#define SSMPACK_FILTER_RESAMPLER_SYSTEMATIC\n\n#include \"ssmkit/filter/resampler/base.hpp\"\n#include \"ssmkit/random/generator.hpp\"\n\n#include <armadillo>\n\n#include <random>\n\nnamespace ssmkit {\nnamespace filter {\nnamespace resampler {\n\n/** Implements systematic resampling method\n */\ntemplate <class Criterion>\nclass Systematic : public BaseResampler<Systematic<Criterion>> {\n  friend class BaseResampler<Systematic<Criterion>>;\n\n private:\n  std::uniform_real_distribution<double> uniform_;\n\n protected:\n  arma::vec generateOrderedNumbers(const int &num_par) {\n    double u0 = uniform_(random::Generator::get().getGenerator());\n    arma::vec u(num_par);\n    int k = 0;\n    u.imbue([&u0, &num_par, &k]() { return (k++ + u0) / num_par; });\n    return u;\n  }\n\n public:\n  Systematic(Criterion criterion)\n      : BaseResampler<Systematic<Criterion>>(criterion) {}\n};\n\ntemplate<class Criterion>\nSystematic<Criterion> makeSystematic(Criterion criterion){\n  return Systematic<Criterion>(criterion);\n}\n\n} // namespace resampler\n} // namespace filter\n} // namespace ssmkit\n#endif // SSMPACK_FILTER_RESAMPLER_SYSTEMATIC\n", "meta": {"hexsha": "83f656dad4ab4df573742d1d8c51eadee99198b5", "size": 1240, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/ssmkit/filter/resampler/systematic.hpp", "max_stars_repo_name": "vahid-bastani/ssmpack", "max_stars_repo_head_hexsha": "68aed98b1c661a7d1c9e5610656de57f6a967532", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2016-07-08T09:18:49.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-10T06:46:55.000Z", "max_issues_repo_path": "src/ssmkit/filter/resampler/systematic.hpp", "max_issues_repo_name": "vahidbas/ssmkit", "max_issues_repo_head_hexsha": "68aed98b1c661a7d1c9e5610656de57f6a967532", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ssmkit/filter/resampler/systematic.hpp", "max_forks_repo_name": "vahidbas/ssmkit", "max_forks_repo_head_hexsha": "68aed98b1c661a7d1c9e5610656de57f6a967532", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-01-03T17:46:08.000Z", "max_forks_repo_forks_event_max_datetime": "2018-01-03T17:46:08.000Z", "avg_line_length": 23.3962264151, "max_line_length": 68, "alphanum_fraction": 0.739516129, "num_tokens": 305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.4657068372317761}}
{"text": "//=======================================================================\r\n// Copyright 2002 Jeremy G. Siek, Andrew Lumsdaine, Lie-Quan Lee, \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#include <string>\r\n#include <boost/graph/adjacency_list.hpp>\r\n#include <boost/graph/undirected_dfs.hpp>\r\n#include <boost/cstdlib.hpp>\r\n#include <iostream>\r\n\r\n/*\r\n  Example graph from Tarjei Knapstad.\r\n\r\n                   H15\r\n                   |\r\n          H8       C2\r\n            \\     /  \\\r\n          H9-C0-C1    C3-O7-H14\r\n            /   |     |\r\n          H10   C6    C4\r\n               /  \\  /  \\\r\n              H11  C5    H13\r\n                   |\r\n                   H12\r\n*/\r\n\r\nstd::string name[] = { \"C0\", \"C1\", \"C2\", \"C3\", \"C4\", \"C5\", \"C6\", \"O7\",\r\n                       \"H8\", \"H9\", \"H10\", \"H11\", \"H12\", \"H13\", \"H14\", \"H15\"};\r\n\r\n\r\nstruct detect_loops : public boost::dfs_visitor<>\r\n{\r\n  template <class Edge, class Graph>\r\n  void back_edge(Edge e, const Graph& g) {\r\n    std::cout << name[source(e, g)]\r\n              << \" -- \"\r\n              << name[target(e, g)] << \"\\n\";\r\n  }\r\n};\r\n\r\nint main(int, char*[])\r\n{\r\n  using namespace boost;\r\n  typedef adjacency_list< vecS, vecS, undirectedS,\r\n    no_property,\r\n    property<edge_color_t, default_color_type> > graph_t;\r\n  typedef graph_traits<graph_t>::vertex_descriptor vertex_t;\r\n  \r\n  const std::size_t N = sizeof(name)/sizeof(std::string);\r\n  graph_t g(N);\r\n  \r\n  add_edge(0, 1, g);\r\n  add_edge(0, 8, g);\r\n  add_edge(0, 9, g);\r\n  add_edge(0, 10, g);\r\n  add_edge(1, 2, g);\r\n  add_edge(1, 6, g);\r\n  add_edge(2, 15, g);\r\n  add_edge(2, 3, g);\r\n  add_edge(3, 7, g);\r\n  add_edge(3, 4, g);\r\n  add_edge(4, 13, g);\r\n  add_edge(4, 5, g);\r\n  add_edge(5, 12, g);\r\n  add_edge(5, 6, g);\r\n  add_edge(6, 11, g);\r\n  add_edge(7, 14, g);\r\n  \r\n  std::cout << \"back edges:\\n\";\r\n  detect_loops vis;\r\n  undirected_dfs(g, root_vertex(vertex_t(0)).visitor(vis)\r\n                 .edge_color_map(get(edge_color, g)));\r\n  std::cout << std::endl;\r\n  \r\n  return boost::exit_success;\r\n}\r\n", "meta": {"hexsha": "6430b6e499042c834f503a8465e1a7f5374d57bf", "size": 2206, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/graph/example/undirected_dfs.cpp", "max_stars_repo_name": "zyiacas/boost-doc-zh", "max_stars_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 198.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T05:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:46:46.000Z", "max_issues_repo_path": "libs/graph/example/undirected_dfs.cpp", "max_issues_repo_name": "sdfict/boost-doc-zh", "max_issues_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/graph/example/undirected_dfs.cpp", "max_forks_repo_name": "sdfict/boost-doc-zh", "max_forks_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 27.2345679012, "max_line_length": 78, "alphanum_fraction": 0.4918404352, "num_tokens": 661, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6370308082623217, "lm_q2_score": 0.7310585727705126, "lm_q1q2_score": 0.46570683349909897}}
{"text": "#include <kd_tree.h>\n#include <iostream>\n#include <Eigen/Dense>\n#include <vector>\n#include <cstdlib>\n#include <ctime>\n\nusing namespace std;\nusing namespace Eigen;\n\nint main(int argc, char * argv[]) {\n    int n = 100;\n    int range = 1;\n    if (argc > 1) {\n        n = atoi(argv[1]);\n    }\n    \n    vector<Vector3d> points;\n    points.clear();\n    \n    double random(double,double);\n    srand(unsigned(time(0)));\n    for(int icnt = 0; icnt != n; ++icnt) {\n        points.push_back(Vector3d(random(0, range), random(0, range), random(0,range)));\n    }\n\n    Vector3d nn;\n    Vector3d target;\n\n    KDTree kdtree(points); \n\n\n    vector<double> ddist(n);\n    // int ans2[KNN_NUM];\n    // double best = INFINITY;\n    // double dist;\n    // int best_index;\n\n    for(int k = 0; k < n; ++k) {\n        target = Vector3d(random(0, range), random(0, range), random(0,range));\n\n        vector<int> ans = kdtree.GetKNN(target, 5, 0, -1);\n\n\n\n        // for(int i = 0; i < n; ++i) {\n        //     ddist[i] = (points[i]-target).norm();\n        // }\n        // for(int i = 0; i < KNN_NUM; ++i) {\n        //     best = INFINITY;\n        //     best_index = -1;\n        //     for(int j = 0; j < n; ++j) {\n        //         if (ddist[j] < best && (i == 0 || ddist[j] > ddist[ans2[i-1]])) {\n        //             best = ddist[j];\n        //             best_index = j;\n        //         }\n        //     }\n\n        //     ans2[i] = best_index;            \n        // }\n\n        // for(int j = 0; j < KNN_NUM; ++j) {\n        //     if (ans[j] != ans2[KNN_NUM - 1 - j]) {\n        //         cout << \"wrong!\" << endl;\n        //         cout << \"target: \" << target.transpose() << endl;\n\n        //         for(int m = 0; m < KNN_NUM; ++m){   \n        //             cout << ans[m] << ',' << ans2[KNN_NUM - 1 - m] << \" : \" << ddist[ans[m]] << ',' << ddist[ans2[KNN_NUM - 1 - m]] << endl;\n        //         }\n        //         cout << ddist[0] << endl;\n\n        //         break;\n        //     }\n        // }\n        \n    }\n\n    return 1;\n}\n\ndouble random(double start, double end)\n{\n    return start+(end-start)*rand()/(RAND_MAX + 1.0);\n}\n", "meta": {"hexsha": "c9d861e54f5c1a907f3e462d02f2f653195ae8c9", "size": 2121, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/testkdtree.cpp", "max_stars_repo_name": "fly2mato/quadswarms", "max_stars_repo_head_hexsha": "9633ef02cad6f2e4a2f510d5bda0fb9e437c31ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-03-04T07:28:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-20T10:54:48.000Z", "max_issues_repo_path": "test/testkdtree.cpp", "max_issues_repo_name": "fly2mato/quadswarms", "max_issues_repo_head_hexsha": "9633ef02cad6f2e4a2f510d5bda0fb9e437c31ac", "max_issues_repo_licenses": ["MIT"], "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/testkdtree.cpp", "max_forks_repo_name": "fly2mato/quadswarms", "max_forks_repo_head_hexsha": "9633ef02cad6f2e4a2f510d5bda0fb9e437c31ac", "max_forks_repo_licenses": ["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.9529411765, "max_line_length": 143, "alphanum_fraction": 0.4375294672, "num_tokens": 642, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.46570682715637174}}
{"text": "//#define BACKWARD_HAS_DW 1\n//#include \"backward.hpp\"\n// namespace backward\n//{\n// backward::SignalHandling sh;\n//}\n#include <mutex>\n#include <queue>\n#include <iostream>\n\n#include <opencv2/opencv.hpp>\n\n#include <boost/foreach.hpp>\n#define foreach BOOST_FOREACH\n\n#include <ros/ros.h>\n#include <sensor_msgs/Imu.h>\n#include <geometry_msgs/Vector3Stamped.h>\n\n#include <rosbag/bag.h>\n#include <rosbag/view.h>\n\n#include <code_utils/ros_utils.h>\n\n#include \"acc_lib/allan_acc.h\"\n#include \"acc_lib/fitallan_acc.h\"\n#include \"gyr_lib/allan_gyr.h\"\n#include \"gyr_lib/fitallan_gyr.h\"\n\nstd::mutex m_buf;\n\nstd::queue<sensor_msgs::ImuConstPtr> imu_buf;\nimu::AllanGyr* gyr_x;\nimu::AllanGyr* gyr_y;\nimu::AllanGyr* gyr_z;\nimu::AllanAcc* acc_x;\nimu::AllanAcc* acc_y;\nimu::AllanAcc* acc_z;\ndouble start_t;\nbool start = true;\nbool end = false;\nint max_time_min = 10;\nstd::string data_save_path;\n\nvoid imu_callback(const sensor_msgs::ImuConstPtr& imu_msg) {\n    //    m_buf.lock( );\n    //    imu_buf.push( imu_msg );\n    //    m_buf.unlock( );\n    double time = imu_msg->header.stamp.toSec();\n    gyr_x->pushRadPerSec(imu_msg->angular_velocity.x, time);\n    gyr_y->pushRadPerSec(imu_msg->angular_velocity.y, time);\n    gyr_z->pushRadPerSec(imu_msg->angular_velocity.z, time);\n    acc_x->pushMPerSec2(imu_msg->linear_acceleration.x, time);\n    acc_y->pushMPerSec2(imu_msg->linear_acceleration.y, time);\n    acc_z->pushMPerSec2(imu_msg->linear_acceleration.z, time);\n\n    if (start) {\n        start_t = time;\n        start = false;\n    } else {\n        double time_min = (time - start_t) / 60;\n        if (time_min > max_time_min)\n            end = true;\n    }\n}\n\nvoid writeData1(\n        const std::string sensor_name, //\n        const std::vector<double>& gyro_ts_x,\n        const std::vector<double>& gyro_d) {\n    std::ofstream out_t;\n    std::ofstream out_x;\n    out_t.open(data_save_path + \"data_\" + sensor_name + \"_t.txt\",\n            std::ios::trunc);\n    out_x.open(data_save_path + \"data_\" + sensor_name + \"_x.txt\",\n            std::ios::trunc);\n    out_t << std::setprecision(10);\n    out_x << std::setprecision(10);\n    for (unsigned int index = 0; index < gyro_ts_x.size(); ++index) {\n        out_t << gyro_ts_x[index] << '\\n';\n        out_x << gyro_d[index] << '\\n';\n    }\n    out_t.close();\n    out_x.close();\n}\n\nvoid writeData3(const std::string sensor_name,\n        const std::vector<double>& gyro_ts_x,\n        const std::vector<double>& gyro_d_x,\n        const std::vector<double>& gyro_d_y,\n        const std::vector<double>& gyro_d_z) {\n    std::ofstream out_t;\n    std::ofstream out_x;\n    std::ofstream out_y;\n    std::ofstream out_z;\n    out_t.open(data_save_path + \"data_\" + sensor_name + \"_t.txt\",\n            std::ios::trunc);\n    out_x.open(data_save_path + \"data_\" + sensor_name + \"_x.txt\",\n            std::ios::trunc);\n    out_y.open(data_save_path + \"data_\" + sensor_name + \"_y.txt\",\n            std::ios::trunc);\n    out_z.open(data_save_path + \"data_\" + sensor_name + \"_z.txt\",\n            std::ios::trunc);\n    out_t << std::setprecision(10);\n    out_x << std::setprecision(10);\n    out_y << std::setprecision(10);\n    out_z << std::setprecision(10);\n\n    for (int index = 0; index < gyro_ts_x.size(); ++index) {\n        out_t << gyro_ts_x[index] << '\\n';\n        out_x << gyro_d_x[index] << '\\n';\n        out_y << gyro_d_y[index] << '\\n';\n        out_z << gyro_d_z[index] << '\\n';\n    }\n\n    out_t.close();\n    out_x.close();\n    out_y.close();\n    out_z.close();\n}\n\nvoid writeYAML(const std::string data_path, const std::string sensor_name,\n        const imu::FitAllanGyr& gyr_x, const imu::FitAllanGyr& gyr_y,\n        const imu::FitAllanGyr& gyr_z, const imu::FitAllanAcc& acc_x,\n        const imu::FitAllanAcc& acc_y, const imu::FitAllanAcc& acc_z) {\n    cv::FileStorage fs(data_path + sensor_name + \"_imu_param.yaml\",\n            cv::FileStorage::WRITE);\n\n    fs << \"type\" << \"IMU\";\n\n    fs << \"name\" << sensor_name;\n\n    fs << \"Gyr\";\n    fs << \"{\";\n    fs << \"unit\" << \" rad/s\";\n\n    fs << \"avg-axis\";\n    fs << \"{\";\n    fs << std::string(\"gyr_n\")\n            << (gyr_x.getWhiteNoise() + gyr_y.getWhiteNoise()\n                    + gyr_z.getWhiteNoise()) / 3;\n    fs << std::string(\"gyr_w\")\n            << (gyr_x.getBiasInstability() + gyr_y.getBiasInstability()\n                    + gyr_z.getBiasInstability()) / 3;\n\n    fs << \"}\";\n\n    fs << \"x-axis\";\n    fs << \"{\";\n    fs << std::string(\"gyr_n\") << gyr_x.getWhiteNoise();\n    fs << std::string(\"gyr_w\") << gyr_x.getBiasInstability();\n    fs << \"}\";\n\n    fs << \"y-axis\";\n    fs << \"{\";\n    fs << std::string(\"gyr_n\") << gyr_y.getWhiteNoise();\n    fs << std::string(\"gyr_w\") << gyr_y.getBiasInstability();\n    fs << \"}\";\n\n    fs << \"z-axis\";\n    fs << \"{\";\n    fs << std::string(\"gyr_n\") << gyr_z.getWhiteNoise();\n    fs << std::string(\"gyr_w\") << gyr_z.getBiasInstability();\n    fs << \"}\";\n\n    fs << \"}\";\n\n    fs << \"Acc\";\n    fs << \"{\";\n    fs << \"unit\" << \" m/s^2\";\n\n    fs << \"avg-axis\";\n    fs << \"{\";\n    fs << std::string(\"acc_n\")\n            << (acc_x.getWhiteNoise() + acc_y.getWhiteNoise()\n                    + acc_z.getWhiteNoise()) / 3;\n    fs << std::string(\"acc_w\")\n            << (acc_x.getBiasInstability() + acc_y.getBiasInstability()\n                    + acc_z.getBiasInstability()) / 3;\n    fs << \"}\";\n\n    fs << \"x-axis\";\n    fs << \"{\";\n    fs << std::string(\"acc_n\") << acc_x.getWhiteNoise();\n    fs << std::string(\"acc_w\") << acc_x.getBiasInstability();\n    fs << \"}\";\n\n    fs << \"y-axis\";\n    fs << \"{\";\n    fs << std::string(\"acc_n\") << acc_y.getWhiteNoise();\n    fs << std::string(\"acc_w\") << acc_y.getBiasInstability();\n    fs << \"}\";\n\n    fs << \"z-axis\";\n    fs << \"{\";\n    fs << std::string(\"acc_n\") << acc_z.getWhiteNoise();\n    fs << std::string(\"acc_w\") << acc_z.getBiasInstability();\n    fs << \"}\";\n\n    fs << \"}\";\n\n    fs.release();\n}\n\nint main(int argc, char** argv) {\n    ros::init(argc, argv, \"gyro_test\");\n    ros::NodeHandle nh(\"~\");\n    ros::console::set_logger_level( ROSCONSOLE_DEFAULT_NAME,\n            ros::console::levels::Debug);\n\n    std::string IMU_TOPIC;\n    std::string IMU_NAME;\n    int max_cluster;\n\n    IMU_TOPIC = ros_utils::readParam<std::string>(nh, \"imu_topic\");\n    IMU_NAME = ros_utils::readParam<std::string>(nh, \"imu_name\");\n    data_save_path = ros_utils::readParam<std::string>(nh, \"data_save_path\");\n    max_time_min = ros_utils::readParam<int>(nh, \"max_time_min\");\n    max_cluster = ros_utils::readParam<int>(nh, \"max_cluster\");\n\n    ros::Subscriber sub_imu = nh.subscribe(IMU_TOPIC, //\n            20000000, imu_callback, ros::TransportHints().tcpNoDelay());\n    //    ros::Publisher pub = n.advertise< geometry_msgs::Vector3Stamped >( ALLAN_TOPIC,\n    //    2000 );\n\n    /* use bag file */\n    std::cout << \"Loading bag file...\" << std::flush;\n    std::string bag_path = ros_utils::readParam<std::string>(nh, \"bag_path\");\n    double bag_skip_second = ros_utils::readParam<double>(nh,\n            \"bag_skip_second\");\n    rosbag::Bag bag;\n    bag.open(bag_path, rosbag::bagmode::Read);\n    std::vector<std::string> topics;\n    topics.push_back(IMU_TOPIC);\n    rosbag::View* view = NULL;\n    view = new rosbag::View(bag, rosbag::TopicQuery(topics));\n    if (bag_skip_second > 0) {\n        ros::Time start_time = view->getBeginTime()\n                + ros::Duration(bag_skip_second);\n        delete view;\n        view = new rosbag::View(bag, rosbag::TopicQuery(topics), start_time);\n    }\n    std::cout << \"OK\" << std::endl;\n\n    gyr_x = new imu::AllanGyr(\"gyr x\", max_cluster);\n    gyr_y = new imu::AllanGyr(\"gyr y\", max_cluster);\n    gyr_z = new imu::AllanGyr(\"gyr z\", max_cluster);\n    acc_x = new imu::AllanAcc(\"acc x\", max_cluster);\n    acc_y = new imu::AllanAcc(\"acc y\", max_cluster);\n    acc_z = new imu::AllanAcc(\"acc z\", max_cluster);\n    std::cout << \"wait for imu data.\" << std::endl;\n\n    auto last_print = std::chrono::steady_clock::now();\n    uint64_t count_imu = 0;\n    std::cout << \"Message count: \" << count_imu << std::flush;\n\n    foreach(rosbag::MessageInstance const msg, *view) {\n        sensor_msgs::Imu::ConstPtr msg_imu =\n                msg.instantiate<sensor_msgs::Imu>();\n\n        if (msg_imu != NULL) {\n            imu_callback(msg_imu);\n            count_imu++;\n        }\n\n        if (std::chrono::steady_clock::now() - last_print\n                >= std::chrono::seconds(1)) {\n            last_print = std::chrono::steady_clock::now();\n            std::cout << '\\r' << \"Message count: \" << count_imu << std::flush;\n        }\n\n        if (end) {\n            break;\n        }\n    }\n    std::cout << std::endl;\n\n    std::cout << \"Finished \" << count_imu << std::endl;\n\n    //    ros::spin( );\n//    while (!end && ros::ok()) {\n//        ros::spinOnce();\n//    }\n//    std::cout << \"ok \" << acc_x->numData << std::endl;\n\n    ///\n    gyr_x->calc();\n    std::vector<double> gyro_v_x = gyr_x->getVariance();\n    std::vector<double> gyro_d_x = gyr_x->getDeviation();\n    std::vector<double> gyro_ts_x = gyr_x->getTimes();\n\n    gyr_y->calc();\n    std::vector<double> gyro_v_y = gyr_y->getVariance();\n    std::vector<double> gyro_d_y = gyr_y->getDeviation();\n    std::vector<double> gyro_ts_y = gyr_y->getTimes();\n\n    gyr_z->calc();\n    std::vector<double> gyro_v_z = gyr_z->getVariance();\n    std::vector<double> gyro_d_z = gyr_z->getDeviation();\n    std::vector<double> gyro_ts_z = gyr_z->getTimes();\n\n    std::cout << \"Gyro X \" << std::endl;\n    imu::FitAllanGyr fit_gyr_x(gyro_v_x, gyro_ts_x, gyr_x->getFreq());\n    std::cout << \"  bias \" << gyr_x->getAvgValue() / 3600 << \" degree/s\"\n            << std::endl;\n    std::cout << \"-------------------\" << std::endl;\n\n    std::cout << \"Gyro y \" << std::endl;\n    imu::FitAllanGyr fit_gyr_y(gyro_v_y, gyro_ts_y, gyr_y->getFreq());\n    std::cout << \"  bias \" << gyr_y->getAvgValue() / 3600 << \" degree/s\"\n            << std::endl;\n    std::cout << \"-------------------\" << std::endl;\n\n    std::cout << \"Gyro z \" << std::endl;\n    imu::FitAllanGyr fit_gyr_z(gyro_v_z, gyro_ts_z, gyr_z->getFreq());\n    std::cout << \"  bias \" << gyr_z->getAvgValue() / 3600 << \" degree/s\"\n            << std::endl;\n    std::cout << \"-------------------\" << std::endl;\n\n    std::vector<double> gyro_sim_d_x = fit_gyr_x.calcSimDeviation(gyro_ts_x);\n    std::vector<double> gyro_sim_d_y = fit_gyr_y.calcSimDeviation(gyro_ts_y);\n    std::vector<double> gyro_sim_d_z = fit_gyr_z.calcSimDeviation(gyro_ts_z);\n\n    writeData3(IMU_NAME + \"_sim_gyr\", gyro_ts_x, gyro_sim_d_x, gyro_sim_d_y,\n            gyro_sim_d_z);\n    writeData3(IMU_NAME + \"_gyr\", gyro_ts_x, gyro_d_x, gyro_d_y, gyro_d_z);\n\n    std::cout << \"==============================================\" << std::endl;\n    std::cout << \"==============================================\" << std::endl;\n\n    acc_x->calc();\n    std::vector<double> acc_v_x = acc_x->getVariance();\n    std::vector<double> acc_d_x = acc_x->getDeviation();\n    std::vector<double> acc_ts_x = acc_x->getTimes();\n\n    acc_y->calc();\n    std::vector<double> acc_v_y = acc_y->getVariance();\n    std::vector<double> acc_d_y = acc_y->getDeviation();\n    std::vector<double> acc_ts_y = acc_y->getTimes();\n\n    acc_z->calc();\n    std::vector<double> acc_v_z = acc_z->getVariance();\n    std::vector<double> acc_d_z = acc_z->getDeviation();\n    std::vector<double> acc_ts_z = acc_z->getTimes();\n\n    std::cout << \"acc X \" << std::endl;\n    imu::FitAllanAcc fit_acc_x(acc_v_x, acc_ts_x, acc_x->getFreq());\n    std::cout << \"-------------------\" << std::endl;\n\n    std::cout << \"acc y \" << std::endl;\n    imu::FitAllanAcc fit_acc_y(acc_v_y, acc_ts_y, acc_y->getFreq());\n    std::cout << \"-------------------\" << std::endl;\n\n    std::cout << \"acc z \" << std::endl;\n    imu::FitAllanAcc fit_acc_z(acc_v_z, acc_ts_z, acc_z->getFreq());\n    std::cout << \"-------------------\" << std::endl;\n\n    std::vector<double> acc_sim_d_x = fit_acc_x.calcSimDeviation(acc_ts_x);\n    std::vector<double> acc_sim_d_y = fit_acc_y.calcSimDeviation(acc_ts_x);\n    std::vector<double> acc_sim_d_z = fit_acc_z.calcSimDeviation(acc_ts_x);\n\n    writeData3(IMU_NAME + \"_sim_acc\", acc_ts_x, acc_sim_d_x, acc_sim_d_y,\n            acc_sim_d_z);\n    writeData3(IMU_NAME + \"_acc\", acc_ts_x, acc_d_x, acc_d_y, acc_d_z);\n\n    writeYAML(data_save_path, IMU_NAME, fit_gyr_x, fit_gyr_y, fit_gyr_z,\n            fit_acc_x, fit_acc_y, fit_acc_z);\n\n    return 0;\n}\n", "meta": {"hexsha": "f5ef806c76bb4294ab4e13e8a4f8218d81c0ec22", "size": 12318, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/imu_an.cpp", "max_stars_repo_name": "bxwllzz/imu_utils", "max_stars_repo_head_hexsha": "3390700dca831069a0ca96b78e150fdc9ecfb2f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/imu_an.cpp", "max_issues_repo_name": "bxwllzz/imu_utils", "max_issues_repo_head_hexsha": "3390700dca831069a0ca96b78e150fdc9ecfb2f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/imu_an.cpp", "max_forks_repo_name": "bxwllzz/imu_utils", "max_forks_repo_head_hexsha": "3390700dca831069a0ca96b78e150fdc9ecfb2f4", "max_forks_repo_licenses": ["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.2021563342, "max_line_length": 89, "alphanum_fraction": 0.5863776587, "num_tokens": 3636, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585669110203, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.4657068196910177}}
{"text": "#pragma once\n\n#include <deal.II/base/tensor.h>\n#include <type_traits>\n\n\nnamespace dealii {\n// ----------------------------------------------------------------------\ntemplate <int dim, typename NUMBER>\ninline Tensor<1, dim, NUMBER>\nouter_product(NUMBER alpha, const Tensor<1, dim, NUMBER>& t)\n{\n  return alpha * t;\n}\n\n// ----------------------------------------------------------------------\ntemplate <int dim, typename NUMBER>\nTensor<1, dim, NUMBER>\nouter_product(const Tensor<1, dim, NUMBER>& t, NUMBER alpha)\n{\n  return alpha * t;\n}\n\n// ----------------------------------------------------------------------\ntemplate <int dim, typename NUMBER>\ninline Tensor<1, dim, NUMBER>\nouter_product(const Tensor<1, dim, NUMBER>& t, const Tensor<0, dim, NUMBER>& alpha)\n{\n  return t * alpha;\n}\n\n// ----------------------------------------------------------------------\ntemplate <int dim, typename NUMBER>\nTensor<1, dim, NUMBER> inline outer_product(const Tensor<0, dim, NUMBER>& alpha,\n                                            const Tensor<1, dim, NUMBER>& t)\n{\n  return t * alpha;\n}\n\n// ----------------------------------------------------------------------\ntemplate <int dim, typename NUMBER>\ninline void outer_product(Tensor<1, dim, NUMBER>& dst,\n                          const Tensor<0, dim, NUMBER> alpha,\n                          const Tensor<1, dim, NUMBER>& t)\n{\n  // hack to extract alpha as a number...\n\n  dst = NUMBER(alpha) * t;\n}\n\ntemplate <int dim, typename NUMBER>\ninline void outer_product(Tensor<0, dim, NUMBER>& dst,\n                          const Tensor<0, dim, NUMBER> alpha,\n                          const Tensor<0, dim, NUMBER>& t)\n{\n  dst = alpha * t;\n}\n\n#if (DEAL_II_VERSION_MAJOR >= 8 && DEAL_II_VERSION_MINOR <= 3)\n// ----------------------------------------------------------------------\ntemplate <int dim, typename NUMBER>\ninline void outer_product(Tensor<1, dim, NUMBER>& dst,\n                          const Tensor<1, dim, NUMBER>& t,\n                          const Tensor<0, dim, NUMBER>& alpha)\n{\n  dst = alpha[0] * t;\n}\n\n// ----------------------------------------------------------------------\ntemplate <int dim, class NUMBER>\ninline NUMBER\nscalar_product(const Tensor<1, dim, NUMBER>& t1, const Tensor<1, dim, NUMBER>& t2)\n{\n  NUMBER sum = 0;\n  for (int i = 0; i < dim; ++i) sum += t1[i] * t2[i];\n\n  return sum;\n}\n\n// ----------------------------------------------------------------------\ntemplate <int dim, class NUMBER>\ninline NUMBER\nscalar_product(const Tensor<0, dim, NUMBER>& t1, const Tensor<0, dim, NUMBER>& t2)\n{\n  return t1 * t2;\n}\n#endif  // DEAL_II_VERSION_MAJOR >= 8 && DEAL_II_VERSION_MINOR <= 3\n\n// ----------------------------------------------------------------------\ntemplate <class NUMBER>\ninline typename std::enable_if<std::is_scalar<NUMBER>::value, NUMBER>::type\nscalar_product(const NUMBER& t1, const NUMBER& t2)\n{\n  return t1 * t2;\n}\n\n}  // end namespace dealii\n", "meta": {"hexsha": "8366d0e76b7b4724e392f2f51eda2204404b0755", "size": 2918, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/aux/tensor_helpers.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/aux/tensor_helpers.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/aux/tensor_helpers.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": 29.7755102041, "max_line_length": 83, "alphanum_fraction": 0.4880054832, "num_tokens": 626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585669110202, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.4657068196910176}}
{"text": "#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE \"test_tensor\"\n\n#include <boost/test/unit_test.hpp>\n#include \"nanocv/tensor.h\"\n\nnamespace\n{\n        using namespace ncv;\n\n        void check_tensor(tensor_t& tensor, size_t dims, size_t rows, size_t cols, scalar_t constant)\n        {\n                tensor.resize(dims, rows, cols);\n\n                BOOST_CHECK_EQUAL(tensor.dims(), dims);\n                BOOST_CHECK_EQUAL(tensor.rows(), rows);\n                BOOST_CHECK_EQUAL(tensor.cols(), cols);\n                BOOST_CHECK_EQUAL(tensor.size(), dims * rows * cols);\n                BOOST_CHECK_EQUAL(tensor.planeSize(), rows * cols);\n\n                BOOST_CHECK_EQUAL(tensor.vector().size(), tensor.size());\n                BOOST_CHECK_EQUAL(tensor.vector(dims / 2).size(), tensor.planeSize());\n\n                BOOST_CHECK_EQUAL(tensor.matrix(dims - 1).rows(), tensor.rows());\n                BOOST_CHECK_EQUAL(tensor.matrix(dims - 1).cols(), tensor.cols());\n\n                tensor.setConstant(constant);\n\n                BOOST_CHECK_EQUAL(tensor.vector().minCoeff(), constant);\n                BOOST_CHECK_EQUAL(tensor.vector().maxCoeff(), constant);\n        }\n}\n\nBOOST_AUTO_TEST_CASE(test_tensor)\n{\n        using namespace ncv;\n\n        const size_t dims = 4;\n        const size_t rows = 7;\n        const size_t cols = 3;\n\n        tensor_t tensor;\n\n        check_tensor(tensor, dims, rows, cols, 0);\n        check_tensor(tensor, dims, rows, cols, 1);\n\n        check_tensor(tensor, 4 * dims, rows, cols, 3);\n        check_tensor(tensor, dims, 3 * rows, 7 * cols, -2.3);\n}\n\n", "meta": {"hexsha": "25054b0b9e2f82557e04c3f76b9e9c433b6c42f3", "size": 1586, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_tensor.cpp", "max_stars_repo_name": "0x0all/nanocv", "max_stars_repo_head_hexsha": "dc58dea6b4eb7be2089b168d39c2b02aa2730741", "max_stars_repo_licenses": ["MIT"], "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_tensor.cpp", "max_issues_repo_name": "0x0all/nanocv", "max_issues_repo_head_hexsha": "dc58dea6b4eb7be2089b168d39c2b02aa2730741", "max_issues_repo_licenses": ["MIT"], "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_tensor.cpp", "max_forks_repo_name": "0x0all/nanocv", "max_forks_repo_head_hexsha": "dc58dea6b4eb7be2089b168d39c2b02aa2730741", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-08-02T02:41:37.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-02T02:41:37.000Z", "avg_line_length": 31.0980392157, "max_line_length": 101, "alphanum_fraction": 0.5989911728, "num_tokens": 345, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585669110202, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.46570680961561317}}
{"text": "//  Copyright John Maddock 2010.\n//  Copyright Paul A. Bristow 2010.\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_INVERSE_GAUSSIAN_HPP\n#define BOOST_STATS_INVERSE_GAUSSIAN_HPP\n\n#ifdef _MSC_VER\n#pragma warning(disable: 4512) // assignment operator could not be generated\n#endif\n\n// http://en.wikipedia.org/wiki/Normal-inverse_Gaussian_distribution\n// http://mathworld.wolfram.com/InverseGaussianDistribution.html\n\n// The normal-inverse Gaussian distribution\n// also called the Wald distribution (some sources limit this to when mean = 1).\n\n// It is the continuous probability distribution\n// that is defined as the normal variance-mean mixture where the mixing density is the \n// inverse Gaussian distribution. The tails of the distribution decrease more slowly\n// than the normal distribution. It is therefore suitable to model phenomena\n// where numerically large values are more probable than is the case for the normal distribution.\n\n// The Inverse Gaussian distribution was first studied in relationship to Brownian motion.\n// In 1956 M.C.K. Tweedie used the name 'Inverse Gaussian' because there is an inverse \n// relationship between the time to cover a unit distance and distance covered in unit time.\n\n// Examples are returns from financial assets and turbulent wind speeds. \n// The normal-inverse Gaussian distributions form\n// a subclass of the generalised hyperbolic distributions.\n\n// See also\n\n// http://en.wikipedia.org/wiki/Normal_distribution\n// http://www.itl.nist.gov/div898/handbook/eda/section3/eda3661.htm\n// Also:\n// Weisstein, Eric W. \"Normal Distribution.\"\n// From MathWorld--A Wolfram Web Resource.\n// http://mathworld.wolfram.com/NormalDistribution.html\n\n// http://www.jstatsoft.org/v26/i04/paper General class of inverse Gaussian distributions.\n// ig package - withdrawn but at http://cran.r-project.org/src/contrib/Archive/ig/\n\n// http://www.stat.ucl.ac.be/ISdidactique/Rhelp/library/SuppDists/html/inverse_gaussian.html\n// R package for dinverse_gaussian, ...\n\n// http://www.statsci.org/s/inverse_gaussian.s  and http://www.statsci.org/s/inverse_gaussian.html\n\n//#include <boost/math/distributions/fwd.hpp>\n#include <boost/math/special_functions/erf.hpp> // for erf/erfc.\n#include <boost/math/distributions/complement.hpp>\n#include <boost/math/distributions/detail/common_error_handling.hpp>\n#include <boost/math/distributions/normal.hpp>\n#include <boost/math/distributions/gamma.hpp> // for gamma function\n// using boost::math::gamma_p;\n\n#include <boost/math/tools/tuple.hpp>\n//using std::tr1::tuple;\n//using std::tr1::make_tuple;\n#include <boost/math/tools/roots.hpp>\n//using boost::math::tools::newton_raphson_iterate;\n\n#include <utility>\n\nnamespace boost{ namespace math{\n\ntemplate <class RealType = double, class Policy = policies::policy<> >\nclass inverse_gaussian_distribution\n{\npublic:\n   typedef RealType value_type;\n   typedef Policy policy_type;\n\n   inverse_gaussian_distribution(RealType mean = 1, RealType scale = 1)\n      : m_mean(mean), m_scale(scale)\n   { // Default is a 1,1 inverse_gaussian distribution.\n     static const char* function = \"boost::math::inverse_gaussian_distribution<%1%>::inverse_gaussian_distribution\";\n\n     RealType result;\n     detail::check_scale(function, scale, &result, Policy());\n     detail::check_location(function, mean, &result, Policy());\n   }\n\n   RealType mean()const\n   { // alias for location.\n      return m_mean; // aka mu\n   }\n\n   // Synonyms, provided to allow generic use of find_location and find_scale.\n   RealType location()const\n   { // location, aka mu.\n      return m_mean;\n   }\n   RealType scale()const\n   { // scale, aka lambda.\n      return m_scale;\n   }\n\n   RealType shape()const\n   { // shape, aka phi = lambda/mu.\n      return m_scale / m_mean;\n   }\n\nprivate:\n   //\n   // Data members:\n   //\n   RealType m_mean;  // distribution mean or location, aka mu.\n   RealType m_scale;    // distribution standard deviation or scale, aka lambda.\n}; // class normal_distribution\n\ntypedef inverse_gaussian_distribution<double> inverse_gaussian;\n\ntemplate <class RealType, class Policy>\ninline const std::pair<RealType, RealType> range(const inverse_gaussian_distribution<RealType, Policy>& /*dist*/)\n{ // Range of permissible values for random variable x, zero to max.\n   using boost::math::tools::max_value;\n   return std::pair<RealType, RealType>(static_cast<RealType>(0.), max_value<RealType>()); // - to + max value.\n}\n\ntemplate <class RealType, class Policy>\ninline const std::pair<RealType, RealType> support(const inverse_gaussian_distribution<RealType, Policy>& /*dist*/)\n{ // Range of supported values for random variable x, zero to max.\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>()); // - to + max value.\n}\n\ntemplate <class RealType, class Policy>\ninline RealType pdf(const inverse_gaussian_distribution<RealType, Policy>& dist, const RealType& x)\n{ // Probability Density Function\n   BOOST_MATH_STD_USING  // for ADL of std functions\n\n   RealType scale = dist.scale();\n   RealType mean = dist.mean();\n   RealType result = 0;\n   static const char* function = \"boost::math::pdf(const inverse_gaussian_distribution<%1%>&, %1%)\";\n   if(false == detail::check_scale(function, scale, &result, Policy()))\n   {\n      return result;\n   }\n   if(false == detail::check_location(function, mean, &result, Policy()))\n   {\n      return result;\n   }\n   if(false == detail::check_positive_x(function, x, &result, Policy()))\n   {\n      return result;\n   }\n\n   if (x == 0)\n   {\n     return 0; // Convenient, even if not defined mathematically.\n   }\n\n   result =\n     sqrt(scale / (constants::two_pi<RealType>() * x * x * x))\n    * exp(-scale * (x - mean) * (x - mean) / (2 * x * mean * mean));\n   return result;\n} // pdf\n\ntemplate <class RealType, class Policy>\ninline RealType cdf(const inverse_gaussian_distribution<RealType, Policy>& dist, const RealType& x)\n{ // Cumulative Density Function.\n   BOOST_MATH_STD_USING  // for ADL of std functions.\n\n   RealType scale = dist.scale();\n   RealType mean = dist.mean();\n   static const char* function = \"boost::math::cdf(const inverse_gaussian_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, mean, &result, Policy()))\n   {\n      return result;\n   }\n   if(false == detail::check_positive_x(function, x, &result, Policy()))\n   {\n     return result;\n   }\n   if (x == 0)\n   {\n     return 0; // Convenient, even if not defined mathematically.\n   }\n   // Problem with this formula for large scale > 1000 or small x, \n   //result = 0.5 * (erf(sqrt(scale / x) * ((x / mean) - 1) / constants::root_two<RealType>(), Policy()) + 1)\n   //  + exp(2 * scale / mean) / 2 \n   //  * (1 - erf(sqrt(scale / x) * (x / mean + 1) / constants::root_two<RealType>(), Policy()));\n   // so use normal distribution version:\n   // Wikipedia CDF equation http://en.wikipedia.org/wiki/Inverse_Gaussian_distribution.\n\n   normal_distribution<RealType> n01;\n\n   RealType n0 = sqrt(scale / x);\n   n0 *= ((x / mean) -1);\n   RealType n1 = cdf(n01, n0);\n   RealType expfactor = exp(2 * scale / mean);\n   RealType n3 = - sqrt(scale / x);\n   n3 *= (x / mean) + 1;\n   RealType n4 = cdf(n01, n3);\n   result = n1 + expfactor * n4;\n   return result;\n} // cdf\n\ntemplate <class RealType, class Policy>\nstruct inverse_gaussian_quantile_functor\n{ \n\n  inverse_gaussian_quantile_functor(const boost::math::inverse_gaussian_distribution<RealType, Policy> dist, RealType const& p)\n    : distribution(dist), prob(p)\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::inverse_gaussian_distribution<RealType, Policy> distribution;\n  RealType prob; \n};\n\ntemplate <class RealType, class Policy>\nstruct inverse_gaussian_quantile_complement_functor\n{ \n    inverse_gaussian_quantile_complement_functor(const boost::math::inverse_gaussian_distribution<RealType, Policy> dist, RealType const& p)\n    : distribution(dist), prob(p)\n  {\n  }\n  boost::math::tuple<RealType, RealType> operator()(RealType const& x)\n  {\n    RealType c = cdf(complement(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 std::tr1::make_tuple(fx, dx); if available.\n    return boost::math::make_tuple(fx, dx);\n  }\n  private:\n  const boost::math::inverse_gaussian_distribution<RealType, Policy> distribution;\n  RealType prob; \n};\n\nnamespace detail\n{\n  template <class RealType>\n  inline RealType guess_ig(RealType p, RealType mu = 1, RealType lambda = 1)\n  { // guess at random variate value x for inverse gaussian quantile.\n      BOOST_MATH_STD_USING\n      using boost::math::policies::policy;\n      // Error type.\n      using boost::math::policies::overflow_error;\n      // Action.\n      using boost::math::policies::ignore_error;\n\n      typedef policy<\n        overflow_error<ignore_error> // Ignore overflow (return infinity)\n      > no_overthrow_policy;\n\n    RealType x; // result is guess at random variate value x.\n    RealType phi = lambda / mu;\n    if (phi > 2.)\n    { // Big phi, so starting to look like normal Gaussian distribution.\n      //    x=(qnorm(p,0,1,true,false) - 0.5 * sqrt(mu/lambda)) / sqrt(lambda/mu);\n      // Whitmore, G.A. and Yalovsky, M.\n      // A normalising logarithmic transformation for inverse Gaussian random variables,\n      // Technometrics 20-2, 207-208 (1978), but using expression from\n      // V Seshadri, Inverse Gaussian distribution (1998) ISBN 0387 98618 9, page 6.\n \n      normal_distribution<RealType, no_overthrow_policy> n01;\n      x = mu * exp(quantile(n01, p) / sqrt(phi) - 1/(2 * phi));\n     }\n    else\n    { // phi < 2 so much less symmetrical with long tail,\n      // so use gamma distribution as an approximation.\n      using boost::math::gamma_distribution;\n\n      // Define the distribution, using gamma_nooverflow:\n      typedef gamma_distribution<RealType, no_overthrow_policy> gamma_nooverflow;\n\n      gamma_distribution<RealType, no_overthrow_policy> g(static_cast<RealType>(0.5), static_cast<RealType>(1.));\n\n      // gamma_nooverflow g(static_cast<RealType>(0.5), static_cast<RealType>(1.));\n      // R qgamma(0.2, 0.5, 1)  0.0320923\n      RealType qg = quantile(complement(g, p));\n      //RealType qg1 = qgamma(1.- p, 0.5, 1.0, true, false);\n      x = lambda / (qg * 2);\n      // \n      if (x > mu/2) // x > mu /2?\n      { // x too large for the gamma approximation to work well.\n        //x = qgamma(p, 0.5, 1.0); // qgamma(0.270614, 0.5, 1) = 0.05983807\n        RealType q = quantile(g, p);\n       // x = mu * exp(q * static_cast<RealType>(0.1));  // Said to improve at high p\n       // x = mu * x;  // Improves at high p?\n        x = mu * exp(q / sqrt(phi) - 1/(2 * phi));\n      }\n    }\n    return x;\n  }  // guess_ig\n} // namespace detail\n\ntemplate <class RealType, class Policy>\ninline RealType quantile(const inverse_gaussian_distribution<RealType, Policy>& dist, const RealType& p)\n{\n   BOOST_MATH_STD_USING  // for ADL of std functions.\n   // No closed form exists so guess and use Newton Raphson iteration.\n\n   RealType mean = dist.mean();\n   RealType scale = dist.scale();\n   static const char* function = \"boost::math::quantile(const inverse_gaussian_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, mean, &result, Policy()))\n      return result;\n   if(false == detail::check_probability(function, p, &result, Policy()))\n      return result;\n   if (p == 0)\n   {\n     return 0; // Convenient, even if not defined mathematically?\n   }\n   if (p == 1)\n   { // overflow \n      result = policies::raise_overflow_error<RealType>(function,\n        \"probability parameter is 1, but must be < 1!\", Policy());\n      return result; // std::numeric_limits<RealType>::infinity();\n   }\n\n  RealType guess = detail::guess_ig(p, dist.mean(), dist.scale());\n  using boost::math::tools::max_value;\n\n  RealType min = 0.; // Minimum possible value is bottom of range of distribution.\n  RealType max = max_value<RealType>();// Maximum possible value is top of range. \n  // int digits = std::numeric_limits<RealType>::digits; // Maximum possible binary digits accuracy for type T.\n  // digits used to control how accurate to try to make the result.\n  // To allow user to control accuracy versus speed,\n  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  using boost::math::tools::newton_raphson_iterate;\n  result =\n    newton_raphson_iterate(inverse_gaussian_quantile_functor<RealType, Policy>(dist, p), guess, min, max, get_digits, m);\n   return result;\n} // quantile\n\ntemplate <class RealType, class Policy>\ninline RealType cdf(const complemented2_type<inverse_gaussian_distribution<RealType, Policy>, RealType>& c)\n{\n   BOOST_MATH_STD_USING  // for ADL of std functions.\n\n   RealType scale = c.dist.scale();\n   RealType mean = c.dist.mean();\n   RealType x = c.param;\n   static const char* function = \"boost::math::cdf(const complement(inverse_gaussian_distribution<%1%>&), %1%)\";\n   // infinite arguments not supported.\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, mean, &result, Policy()))\n      return result;\n   if(false == detail::check_positive_x(function, x, &result, Policy()))\n      return result;\n\n   normal_distribution<RealType> n01;\n   RealType n0 = sqrt(scale / x);\n   n0 *= ((x / mean) -1);\n   RealType cdf_1 = cdf(complement(n01, n0));\n\n   RealType expfactor = exp(2 * scale / mean);\n   RealType n3 = - sqrt(scale / x);\n   n3 *= (x / mean) + 1;\n\n   //RealType n5 = +sqrt(scale/x) * ((x /mean) + 1); // note now positive sign.\n   RealType n6 = cdf(complement(n01, +sqrt(scale/x) * ((x /mean) + 1)));\n   // RealType n4 = cdf(n01, n3); // = \n   result = cdf_1 - expfactor * n6; \n   return result;\n} // cdf complement\n\ntemplate <class RealType, class Policy>\ninline RealType quantile(const complemented2_type<inverse_gaussian_distribution<RealType, Policy>, RealType>& c)\n{\n   BOOST_MATH_STD_USING  // for ADL of std functions\n\n   RealType scale = c.dist.scale();\n   RealType mean = c.dist.mean();\n   static const char* function = \"boost::math::quantile(const complement(inverse_gaussian_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, mean, &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   RealType guess = detail::guess_ig(q, mean, scale);\n   // Complement.\n   using boost::math::tools::max_value;\n\n  RealType min = 0.; // Minimum possible value is bottom of range of distribution.\n  RealType max = max_value<RealType>();// Maximum possible value is top of range. \n  // int digits = std::numeric_limits<RealType>::digits; // Maximum possible binary digits accuracy for type T.\n  // digits used to control how accurate to try to make the result.\n  int get_digits = policies::digits<RealType, Policy>();\n  boost::uintmax_t m = policies::get_max_root_iterations<Policy>();\n  using boost::math::tools::newton_raphson_iterate;\n  result =\n    newton_raphson_iterate(inverse_gaussian_quantile_complement_functor<RealType, Policy>(c.dist, q), guess, min, max, get_digits, m);\n   return result;\n} // quantile\n\ntemplate <class RealType, class Policy>\ninline RealType mean(const inverse_gaussian_distribution<RealType, Policy>& dist)\n{ // aka mu\n   return dist.mean();\n}\n\ntemplate <class RealType, class Policy>\ninline RealType scale(const inverse_gaussian_distribution<RealType, Policy>& dist)\n{ // aka lambda\n   return dist.scale();\n}\n\ntemplate <class RealType, class Policy>\ninline RealType shape(const inverse_gaussian_distribution<RealType, Policy>& dist)\n{ // aka phi\n   return dist.shape();\n}\n\ntemplate <class RealType, class Policy>\ninline RealType standard_deviation(const inverse_gaussian_distribution<RealType, Policy>& dist)\n{\n  BOOST_MATH_STD_USING\n  RealType scale = dist.scale();\n  RealType mean = dist.mean();\n  RealType result = sqrt(mean * mean * mean / scale);\n  return result;\n}\n\ntemplate <class RealType, class Policy>\ninline RealType mode(const inverse_gaussian_distribution<RealType, Policy>& dist)\n{\n  BOOST_MATH_STD_USING\n  RealType scale = dist.scale();\n  RealType  mean = dist.mean();\n  RealType result = mean * (sqrt(1 + (9 * mean * mean)/(4 * scale * scale)) \n      - 3 * mean / (2 * scale));\n  return result;\n}\n\ntemplate <class RealType, class Policy>\ninline RealType skewness(const inverse_gaussian_distribution<RealType, Policy>& dist)\n{\n  BOOST_MATH_STD_USING\n  RealType scale = dist.scale();\n  RealType  mean = dist.mean();\n  RealType result = 3 * sqrt(mean/scale);\n  return result;\n}\n\ntemplate <class RealType, class Policy>\ninline RealType kurtosis(const inverse_gaussian_distribution<RealType, Policy>& dist)\n{\n  RealType scale = dist.scale();\n  RealType  mean = dist.mean();\n  RealType result = 15 * mean / scale -3;\n  return result;\n}\n\ntemplate <class RealType, class Policy>\ninline RealType kurtosis_excess(const inverse_gaussian_distribution<RealType, Policy>& dist)\n{\n  RealType scale = dist.scale();\n  RealType  mean = dist.mean();\n  RealType result = 15 * mean / scale;\n  return result;\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_INVERSE_GAUSSIAN_HPP\n\n\n", "meta": {"hexsha": "ba850773126334c052f694ee7ecd0209bf253192", "size": 19234, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/boost/math/distributions/inverse_gaussian.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/math/distributions/inverse_gaussian.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/math/distributions/inverse_gaussian.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": 37.4931773879, "max_line_length": 140, "alphanum_fraction": 0.6955391494, "num_tokens": 5005, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419704455588, "lm_q2_score": 0.672331705744791, "lm_q1q2_score": 0.4656851574600956}}
{"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#define NT2_UNIT_MODULE \"nt2 polynom toolbox - polyvalm/scalar Mode\"\n\n//////////////////////////////////////////////////////////////////////////////\n// unit test behavior of polynom components in scalar mode\n//////////////////////////////////////////////////////////////////////////////\n/// created  by jt the 06/03/2011\n///\n#include <nt2/include/functions/polyvalm.hpp>\n#include <nt2/include/functions/eye.hpp>\n#include <nt2/include/functions/ones.hpp>\n#include <nt2/include/functions/isequal.hpp>\n#include <boost/type_traits/is_same.hpp>\n#include <nt2/sdk/functor/meta/call.hpp>\n#include <nt2/sdk/unit/tests.hpp>\n#include <nt2/sdk/unit/module.hpp>\n#include <nt2/sdk/memory/buffer.hpp>\n#include <nt2/include/constants/real.hpp>\n#include <nt2/table.hpp>\n\n\nNT2_TEST_CASE_TPL ( polyvalm_real__1_0,  NT2_REAL_TYPES)\n{\n\n  using nt2::polyvalm;\n  using nt2::tag::polyvalm_;\n  nt2::table<T> p =  nt2::_(T(1), T(4));\n  nt2::table<T> a =  nt2::eye(3, nt2::meta::as_<T>());\n  NT2_DISPLAY(polyvalm(p, a));\n  NT2_TEST(nt2::isequal(polyvalm(p, a), T(10)*a));\n  nt2::table<T> b = T(15)*nt2::eye(2, nt2::meta::as_<T>());\n  b(2) = b(3) = T(11);\n  nt2::table<T> c =  nt2::ones(2, nt2::meta::as_<T>());\n  NT2_TEST(nt2::isequal(polyvalm(p, c), b));\n  NT2_DISPLAY(polyvalm(p, c));\n  NT2_DISPLAY(b);\n} // end of test for floating_\n\n", "meta": {"hexsha": "30934c010602ad6115b165ebf97e5b1a9557c13a", "size": 1819, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/core/polynom/unit/scalar/polyvalm.cpp", "max_stars_repo_name": "pbrunet/nt2", "max_stars_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "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/polynom/unit/scalar/polyvalm.cpp", "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/polynom/unit/scalar/polyvalm.cpp", "max_forks_repo_name": "pbrunet/nt2", "max_forks_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.5434782609, "max_line_length": 80, "alphanum_fraction": 0.5486531061, "num_tokens": 498, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6926419704455588, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.46568515746009553}}
{"text": "//\n//  MatrixFactory.hpp\n//  Eigen_test\n//\n//  Created by Emil Iliev on 17.10.19.\n//  Copyright \u00a9 2019 Emil Iliev. All rights reserved.\n//\n\n#ifndef MatrixFactory_hpp\n#define MatrixFactory_hpp\n\n#include <stdio.h>\n#include <Eigen/Dense>\n#define PI 3.14159265\n#define CONVERT_TO_RAD(x) x*(M_PI/180)\n\nclass MatrixFactory {\n    MatrixFactory() {}\n\n    static MatrixFactory* _instance;\npublic:\n\n/***********************************************************************\n    Rotation matrix\n***********************************************************************/\n\n    Eigen::Matrix4f createRotationMatrixAroundZ(float alpha );\n    Eigen::Matrix4f createRotationMatrixAroundY(float beta );\n    Eigen::Matrix4f createRotationMatrixAroundX(float gamma );\n\n\n/************************************************************************/\n/* Translation matrix                                                   */\n/************************************************************************/\n    \n    Eigen::Matrix4f createTranslateMatrixX(float dx );\n    Eigen::Matrix4f createTranslateMatrixY(float dy );\n    Eigen::Matrix4f createTranslateMatrixZ(float dz );\n\n/************************************************************************/\n/* Transformation matrix from frame i to i-1                            */\n/************************************************************************/\n\n    Eigen::Matrix4f calculateHTranslationMatrix(float alpha, float a, float d, float theta);\n\n    /************************************************************************/\n/* Help functions                                                       */\n/************************************************************************/\n    Eigen::Matrix3f extractRotationMatrix(Eigen::Matrix4f & hm );\n    Eigen::Vector3f extractTranslationVector (Eigen::Matrix4f & hm );\n    Eigen::Vector3f multiplyVectors(Eigen::Vector3f& vec_one ,Eigen::Vector3f& vec_two);\n    float getLengthOfVector(Eigen::VectorXf& invec);\n/************************************************************************/\n/* Full calculation algo                                                */\n/************************************************************************/\n\n    static MatrixFactory* getInstance();\n};\n\n#endif /* MatrixFactory_hpp */\n", "meta": {"hexsha": "a13861d5d27113457f41fd11723066534b4011f8", "size": 2271, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Eigen_test/Eigen_test/Solvers/MatrixFactory.hpp", "max_stars_repo_name": "emiliev/RoboticArm", "max_stars_repo_head_hexsha": "69d0a73166c819d93cef28b7a6b6cc267345dd68", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Eigen_test/Eigen_test/Solvers/MatrixFactory.hpp", "max_issues_repo_name": "emiliev/RoboticArm", "max_issues_repo_head_hexsha": "69d0a73166c819d93cef28b7a6b6cc267345dd68", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Eigen_test/Eigen_test/Solvers/MatrixFactory.hpp", "max_forks_repo_name": "emiliev/RoboticArm", "max_forks_repo_head_hexsha": "69d0a73166c819d93cef28b7a6b6cc267345dd68", "max_forks_repo_licenses": ["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.2295081967, "max_line_length": 92, "alphanum_fraction": 0.4328489652, "num_tokens": 356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.46568515689634327}}
{"text": "\ufeff// File: geometry.cpp\n// Project: lib\n// Created Date: 08/06/2016\n// Author: Seki Inoue\n// -----\n// Last Modified: 27/12/2020\n// Modified By: Shun Suzuki (suzuki@hapis.k.u-tokyo.ac.jp)\n// -----\n// Copyright (c) 2016-2020 Hapis Lab. All rights reserved.\n//\n\n#if WIN32\n#include <codeanalysis/warnings.h>  // NOLINT\n#pragma warning(push)\n#pragma warning(disable : ALL_CODE_ANALYSIS_WARNINGS)\n#endif\n#include <Eigen/Geometry>\n#if WIN32\n#pragma warning(pop)\n#endif\n\n#include <map>\n\n#include \"autd3.hpp\"\n#include \"autd_logic.hpp\"\n#include \"geometry.hpp\"\n\nusing autd::IsMissingTransducer;\nusing autd::NUM_TRANS_IN_UNIT;\nusing autd::NUM_TRANS_X;\nusing autd::NUM_TRANS_Y;\nusing autd::TRANS_SIZE_MM;\n\nnamespace autd {\nstruct Device {\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n  static Device Create(const Vector3& position, const Quaternion& quaternion) {\n    const Eigen::Transform<Float, 3, Eigen::Affine> transform_matrix = Eigen::Translation<Float, 3>(position) * quaternion;\n    const auto x_direction = quaternion * Vector3(1, 0, 0);\n    const auto y_direction = quaternion * Vector3(0, 1, 0);\n    const auto z_direction = quaternion * Vector3(0, 0, 1);\n\n    Eigen::Matrix<Float, 3, NUM_TRANS_IN_UNIT> local_trans_positions;\n\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 (!IsMissingTransducer(x, y))\n          local_trans_positions.col(index++) = Vector3(static_cast<Float>(x) * TRANS_SIZE_MM, static_cast<Float>(y) * TRANS_SIZE_MM, 0);\n\n    const auto global_trans_positions = transform_matrix * local_trans_positions;\n\n    return Device{x_direction, y_direction, z_direction, global_trans_positions};\n  }\n\n  static Device Create(const Vector3& position, const Vector3& euler_angles) {\n    const auto quaternion = Eigen::AngleAxis<Float>(euler_angles.x(), Vector3::UnitZ()) *\n                            Eigen::AngleAxis<Float>(euler_angles.y(), Vector3::UnitY()) * Eigen::AngleAxis<Float>(euler_angles.z(), Vector3::UnitZ());\n\n    return Create(position, quaternion);\n  }\n\n  Vector3 x_direction;\n  Vector3 y_direction;\n  Vector3 z_direction;\n  Eigen::Matrix<Float, 3, NUM_TRANS_IN_UNIT> global_trans_positions;\n};\n\nclass AUTDGeometry final : public Geometry {\n public:\n  AUTDGeometry() : _wavelength(8.5) {}\n  ~AUTDGeometry() override = default;\n  AUTDGeometry(const AUTDGeometry& v) noexcept = default;\n  AUTDGeometry& operator=(const AUTDGeometry& obj) = default;\n  AUTDGeometry(AUTDGeometry&& obj) = default;\n  AUTDGeometry& operator=(AUTDGeometry&& obj) = default;\n\n  size_t AddDevice(Vector3 position, Vector3 euler_angles, size_t group = 0) override;\n  size_t AddDeviceQuaternion(Vector3 position, Quaternion quaternion, size_t group = 0) override;\n\n  Float wavelength() noexcept override;\n  void set_wavelength(Float wavelength) noexcept override;\n\n  size_t num_devices() noexcept override;\n  size_t num_transducers() noexcept override;\n  size_t group_id_for_device_idx(size_t device_idx) override;\n  Vector3 position(size_t global_transducer_idx) override;\n  Vector3 position(size_t device, size_t local_transducer_idx) override;\n  Vector3 local_position(size_t device_idx, Vector3 global_position) override;\n\n  Vector3 direction(size_t device_idx) override;\n  Vector3 x_direction(size_t device_idx) override;\n  Vector3 y_direction(size_t device_idx) override;\n  Vector3 z_direction(size_t device_idx) override;\n  size_t device_idx_for_trans_idx(size_t transducer_idx) override;\n\n private:\n  std::vector<Device> _devices;\n  std::map<size_t, size_t> _group_map;\n  Float _wavelength;\n};\n\nGeometryPtr Geometry::Create() { return std::make_shared<AUTDGeometry>(); }\n\nsize_t AUTDGeometry::AddDevice(const Vector3 position, const Vector3 euler_angles, const size_t group) {\n  const auto device_id = this->_devices.size();\n  this->_devices.emplace_back(Device::Create(position, euler_angles));\n  this->_group_map[device_id] = group;\n  return device_id;\n}\n\nsize_t AUTDGeometry::AddDeviceQuaternion(const Vector3 position, const Quaternion quaternion, const size_t group) {\n  const auto device_id = this->_devices.size();\n  this->_devices.emplace_back(Device::Create(position, quaternion));\n  this->_group_map[device_id] = group;\n  return device_id;\n}\n\nFloat AUTDGeometry::wavelength() noexcept { return this->_wavelength; }\nvoid AUTDGeometry::set_wavelength(const Float wavelength) noexcept { this->_wavelength = wavelength; }\n\nsize_t AUTDGeometry::num_devices() noexcept { return this->_devices.size(); }\n\nsize_t AUTDGeometry::num_transducers() noexcept { return this->num_devices() * NUM_TRANS_IN_UNIT; }\n\nsize_t AUTDGeometry::group_id_for_device_idx(const size_t device_idx) { return this->_group_map[device_idx]; }\n\nVector3 AUTDGeometry::position(const size_t global_transducer_idx) {\n  const auto local_trans_id = global_transducer_idx % NUM_TRANS_IN_UNIT;\n  return position(this->device_idx_for_trans_idx(global_transducer_idx), local_trans_id);\n}\n\nVector3 AUTDGeometry::position(const size_t device, const size_t local_transducer_idx) {\n  const auto& dev = this->_devices[device];\n  return dev.global_trans_positions.col(local_transducer_idx);\n}\n\nVector3 AUTDGeometry::local_position(const size_t device_idx, const Vector3 global_position) {\n  const auto& device = this->_devices[device_idx];\n  const auto& local_origin = device.global_trans_positions.col(0);\n  const auto& x_dir = device.x_direction;\n  const auto& y_dir = device.y_direction;\n  const auto& z_dir = device.z_direction;\n  const auto rv = global_position - local_origin;\n  return Vector3(rv.dot(x_dir), rv.dot(y_dir), rv.dot(z_dir));\n}\n\nVector3 AUTDGeometry::direction(const size_t device_idx) { return z_direction(device_idx); }\n\nVector3 AUTDGeometry::x_direction(const size_t device_idx) {\n  const auto& dir = this->_devices[device_idx].x_direction;\n  return dir;\n}\n\nVector3 AUTDGeometry::y_direction(const size_t device_idx) {\n  const auto& dir = this->_devices[device_idx].x_direction;\n  return dir;\n}\n\nVector3 AUTDGeometry::z_direction(const size_t device_idx) {\n  const auto& dir = this->_devices[device_idx].x_direction;\n  return dir;\n}\n\nsize_t AUTDGeometry::device_idx_for_trans_idx(const size_t transducer_idx) { return transducer_idx / NUM_TRANS_IN_UNIT; }\n}  // namespace autd\n", "meta": {"hexsha": "b1954e64e22b942df3a49ac02d347ffc588d74e9", "size": 6229, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "client/lib/geometry.cpp", "max_stars_repo_name": "sssssssuzuki/autd3-library-software", "max_stars_repo_head_hexsha": "9f8382d099a38c0feb48176896db2f4db251ce40", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "client/lib/geometry.cpp", "max_issues_repo_name": "sssssssuzuki/autd3-library-software", "max_issues_repo_head_hexsha": "9f8382d099a38c0feb48176896db2f4db251ce40", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "client/lib/geometry.cpp", "max_forks_repo_name": "sssssssuzuki/autd3-library-software", "max_forks_repo_head_hexsha": "9f8382d099a38c0feb48176896db2f4db251ce40", "max_forks_repo_licenses": ["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.2994011976, "max_line_length": 150, "alphanum_fraction": 0.7587092631, "num_tokens": 1567, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.46565080967558586}}
{"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#define BOOST_SYSTEM_NO_DEPRECATED\n#define BOOST_FILESYSTEM_NO_DEPRECATED\n#include \"boost/filesystem.hpp\"\n#include \"boost/program_options.hpp\"\n\n#include \"Molassembler/Shapes/Data.h\"\n#include \"Molassembler/Shapes/ContinuousMeasures.h\"\n#include \"Molassembler/Shapes/InertialMoments.h\"\n#include \"Molassembler/Shapes/Diophantine.h\"\n\n#include \"Molassembler/Temple/Adaptors/Iota.h\"\n#include \"Molassembler/Temple/Functional.h\"\n#include \"Molassembler/Temple/Stringify.h\"\n#include \"Molassembler/Temple/constexpr/Jsf.h\"\n#include \"Molassembler/Temple/constexpr/Numeric.h\"\n\n#include <Eigen/Core>\n#include <random>\n#include <iostream>\n#include <iomanip>\n\nusing namespace Scine;\nusing namespace Molassembler;\nusing namespace Shapes;\n\ntemplate<typename PRNG>\nEigen::Vector3d randomVectorOnSphere(const double radius, PRNG& prng) {\n  std::normal_distribution<double> normal {};\n  Eigen::Vector3d v = Eigen::Vector3d::Zero();\n\n  while(v.norm() < 0.01) {\n    v << normal(prng),\n         normal(prng),\n         normal(prng);\n  }\n\n  return radius * v / v.norm();\n}\n\ntemplate<typename PRNG>\nEigen::Vector3d randomVectorInSphere(const double radius, PRNG& prng) {\n  std::uniform_real_distribution<double> uniform {};\n  std::normal_distribution<double> normal {};\n  const double u = std::cbrt(uniform(prng));\n  Eigen::Vector3d v = Eigen::Vector3d::Zero();\n\n  while(v.norm() < 0.01) {\n    v << normal(prng),\n         normal(prng),\n         normal(prng);\n  }\n\n  return radius * u * v / v.norm();\n}\n\ntemplate<typename PRNG>\nEigen::Vector3d normallyDistributedVectorInSphere(const double radius, PRNG& prng) {\n  std::normal_distribution<double> radiusDistribution {1.0, 0.2};\n  std::normal_distribution<double> normal {};\n  Eigen::Vector3d v = Eigen::Vector3d::Zero();\n\n  while(v.norm() < 0.01) {\n    v << normal(prng),\n         normal(prng),\n         normal(prng);\n  }\n\n  return radius * (1 + radiusDistribution(prng)) * v / v.norm();\n}\n\ntemplate<typename PRNG>\nEigen::Matrix<double, 3, Eigen::Dynamic> generateCoordinates(unsigned P, PRNG& prng) {\n  Eigen::Matrix<double, 3, Eigen::Dynamic> positions(3, P + 1);\n  positions.col(0) = Eigen::Vector3d::Zero();\n  for(unsigned i = 1; i <= P; ++i) {\n    positions.col(i) = normallyDistributedVectorInSphere(1.0, prng);\n  }\n  return positions;\n}\n\nconstexpr unsigned nExperiments = 1000;\n\ntemplate<typename PRNG, typename F>\nstd::vector<double> averageRandomCsm(const unsigned N, PRNG& prng, F&& f) {\n  assert(N >= 2);\n  return Temple::map(\n    Temple::Adaptors::range(nExperiments),\n    [&](unsigned /* i */) -> double {\n      auto normalized = Continuous::normalize(generateCoordinates(N, prng));\n      Top top = standardizeTop(normalized);\n      if(top == Top::Asymmetric) {\n        reorientAsymmetricTop(normalized);\n      }\n      return f(normalized);\n    }\n  );\n}\n\nstd::ostream& operator << (std::ostream& os, const std::vector<double>& values) {\n  const auto end = std::end(values);\n  for(auto it = std::begin(values); it != end; ++it) {\n    os << *it;\n    if(it != end - 1) {\n      os << \", \";\n    }\n  }\n\n  return os;\n}\n\n/* Does it make more sense to just maximize the CSM using two parameters at\n * each point and use LBFGS with numerical derivatives? More principled than\n * many random points, no guarantee maximum CSM is actually found.\n *\n * Procedure for finding upper bounds on the CSM for which clear distinctions\n * can be made between unrelated point groups (unrelated meaning neither is a\n * subset of the other).\n * - Generate points P for which CSM(P, D3h) = 0, and points Q for which CSM(Q, Oh) = 0.\n * - Add uniform direction fixed magnitude (fuzz) distortions to P and Q, making P' and Q'\n * - Find the maximum CSM(P', D3h) and maximum CSM(Q', Oh)\n * - Find the minimum CSM(Q', D3h) and minimum CSM(P', Oh)\n * - If the maximum CSM(P', D3h) < minimum CSM(Q', D3h)\n *   and the maximum CSM(Q', Oh) < minimum CSM(P', Oh),\n *   increase the fuzz magnitude\n *\n * To find the maximum and minimum CSM for a particular fuzziness of a set of\n * group symmetric points by numerical optimization:\n * - Generate A-symmetric points: Go through each solution of the diophantine\n *   for the usable group sizes and the required number of points (exclude\n *   groups whose probe point is the origin):\n *   - If only a single group size has multiplier > 0, generate group-symmetric\n *     points by applying a symmetry element from each group to the normalized\n *     probe point.\n *   - If there are multiple group sizes with multiplier > 0, the norms of each\n *     probe point are meta-parameters that need to be optimized too.\n */\n\nstruct RScriptWriter {\n  std::ofstream file;\n\n  RScriptWriter(const std::string& str) : file(str) {\n    writeHeader();\n  }\n\n  void writeHeader() {\n    file << \"symmetryNames <- c(\\\"\" << Temple::condense(\n      Temple::map(Shapes::allShapes, [](auto name) { return Shapes::name(name); }),\n      \"\\\",\\\"\"\n    ) << \"\\\")\\n\";\n    file << \"symmetrySizes <- c(\" << Temple::condense(\n      Temple::map(Shapes::allShapes, [](auto name) { return Shapes::size(name); })\n    ) << \")\\n\";\n    file << \"results <- array(numeric(), c(\" << Shapes::allShapes.size() << \", \" << nExperiments << \"))\\n\";\n  }\n\n  void writeSeed(int seed) {\n    file << \"seed <- \" << seed << \"\\n\";\n  }\n\n  void addResults(const Shapes::Shape name, const std::vector<double>& results) {\n    const unsigned symmetryIndex = nameIndex(name) + 1;\n    file << \"results[\" << symmetryIndex << \",] <- c(\" << results << \")\\n\";\n  }\n\n  template<typename F, typename PRNG>\n  void addElementArray(const std::string& nameBase, F&& f, PRNG&& prng) {\n    file << std::scientific;\n    file << nameBase << \"Array <- array(numeric(), c(7, \" << nExperiments << \"))\\n\";\n\n    std::array<int, 7> seeds;\n    for(unsigned i = 0; i < 7; ++i) {\n      seeds[i] = prng();\n    }\n\n#pragma omp parallel for\n    for(unsigned N = 2; N <= 8; ++N) {\n      Temple::JSF64 localPrng {seeds.at(N - 2)};\n      const auto values = averageRandomCsm(N, localPrng, std::forward<F>(f));\n\n#pragma omp critical\n      {\n        std::cout << \"CSM(\" << nameBase << \", \" << N << \") = \" << Temple::average(values) << \" +- \" << Temple::stddev(values) << \"\\n\";\n        file << nameBase << \"Array[\" << (N - 1) << \",] <- c(\" << values << \")\\n\";\n      }\n    }\n\n    file << \"elementArrays[[\\\"\" << nameBase << \"\\\"]] <- \" << nameBase << \"Array)\\n\";\n  }\n};\n\nint main(int argc, char* argv[]) {\n  bool showElements = false;\n  /* Set up program options */\n  boost::program_options::options_description options_description(\"Recognized options\");\n  options_description.add_options()\n    (\"help,h\", \"Produce help message\")\n    (\n      \"seed,s\",\n      boost::program_options::value<int>(),\n      \"Seed to initialize PRNG with.\"\n    )\n    (\n      \"elements,e\",\n      boost::program_options::bool_switch(&showElements),\n      \"Show element CSM statistics instead of point groups\"\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  RScriptWriter writer {\n    showElements ? \"elements.R\" : \"point_groups_data.R\"\n  };\n  Temple::JSF64 prng;\n  if(options_variables_map.count(\"seed\") > 0) {\n    const int seed = options_variables_map[\"seed\"].as<int>();\n    prng.seed(seed);\n    writer.writeSeed(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    writer.writeSeed(seed);\n  }\n\n  writer.file << std::scientific;\n\n  if(showElements) {\n    writer.file << \"elementArrays <- list()\\n\";\n\n    /* Inversion */\n    writer.addElementArray(\n      \"inversion\",\n      [](const Continuous::PositionCollection& positions) -> double {\n        return Continuous::element(positions, Elements::Inversion {});\n      },\n      prng\n    );\n\n    /* Cinf */\n    writer.addElementArray(\n      \"Cinf\",\n      [](const Continuous::PositionCollection& positions) -> double {\n        return Continuous::Cinf(positions);\n      },\n      prng\n    );\n\n    /* Sigma */\n    writer.addElementArray(\n      \"sigma\",\n      [](const Continuous::PositionCollection& positions) -> double {\n        return Continuous::element(positions, Elements::Reflection {Eigen::Vector3d::UnitZ()}).first;\n      },\n      prng\n    );\n\n    /* Cn axes */\n    for(unsigned order = 2; order <= 8; ++order) {\n      writer.addElementArray(\n        \"C\" + std::to_string(order),\n        [order](const Continuous::PositionCollection& positions) -> double {\n          return Continuous::element(positions,\n            Elements::Rotation::Cn(Eigen::Vector3d::UnitZ(), order)\n          ).first;\n        },\n        prng\n      );\n    }\n\n    /* Sn axes */\n    for(unsigned order = 4; order <= 8; order += 2) {\n      writer.addElementArray(\n        \"S\" + std::to_string(order),\n        [order](const Continuous::PositionCollection& positions) -> double {\n          return Continuous::element(positions,\n            Elements::Rotation::Sn(Eigen::Vector3d::UnitZ(), order)\n          ).first;\n        },\n        prng\n      );\n    }\n  }\n\n  if(!showElements) {\n    std::cout << \"Average CSM for uniform coordinates in sphere:\\n\";\n    for(const Shape shape : allShapes) {\n      const PointGroup group = pointGroup(shape);\n      for(unsigned N = 2; N < 8; ++N) {\n        /* Generate 100 random coordinates within a uniform sphere for each\n         * symmetry and evaluate the CSM\n         */\n        const auto values = Temple::map(\n          Temple::Adaptors::range(nExperiments),\n          [&](unsigned /* i */) -> double {\n            auto normalized = Continuous::normalize(generateCoordinates(N, prng));\n            Top top = standardizeTop(normalized);\n            if(top == Top::Asymmetric) {\n              reorientAsymmetricTop(normalized);\n            }\n            return Continuous::pointGroup(normalized, group);\n          }\n        );\n        const double csmAverage = Temple::average(values);\n        const double csmStddev = Temple::stddev(values);\n\n        writer.addResults(shape, values);\n        std::cout << name(shape) << \" - \" << N << \": \" << csmAverage << \" +- \" << csmStddev << \"\\n\";\n      }\n    }\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "2f9d43af069f43103717e36dc7667b12e7c842a7", "size": 10826, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "analysis/Shapes/csm.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/csm.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/csm.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": 31.9351032448, "max_line_length": 134, "alphanum_fraction": 0.6304267504, "num_tokens": 2798, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.46564842418040875}}
{"text": "/// HEADER\n#include \"path_follower/utils/extended_kalman_filter.h\"\n\n/// SYSTEM\n#include <Eigen/Dense>\n#include <ros/console.h>\n\n#include<tf/tf.h>\n#include<ros/ros.h>\n#include <tf2/LinearMath/Quaternion.h>\n\nnamespace {\n\ndouble angleDiff(const double a1, const double a2)\n{\n    return std::atan2(std::sin(a1 - a2), std::cos(a1 - a2)) ;\n}\n\n}\n\nEKF::EKF()\n{\n    x_ = Eigen::Matrix<double, 6, 1>::Zero();\n\n    x_(0,0) = 0;\n    x_(1,0) = 0;\n    x_(2,0) = 0;\n    x_(3,0) = -0.45;\n    x_(4,0) = 0.45;\n    x_(5,0) = -0.004;\n\n\n    F = Eigen::Matrix<double, 6, 6>::Zero();\n    P = Eigen::Matrix<double, 6, 6>::Identity();\n    R = Eigen::Matrix<double, 3, 3>::Zero();\n    Q = Eigen::Matrix<double, 6, 6>::Zero();\n\n    R(0,0) = pow(0.01, 2);\n    R(1,1) = pow(0.01, 2);\n    R(2,2) = pow(M_PI/180, 2);\n\n    Q(0,0) = pow(0.1, 2);\n    Q(1,1) = pow(0.1, 2);\n    Q(2,2) = pow(5*M_PI/180, 2);\n    Q(3,3) = pow(0.001, 2);\n    Q(4,4) = pow(0.001, 2);\n    Q(5,5) = pow(0.001, 2);\n\n}\n\nvoid EKF::reset()\n{\n    x_ = Eigen::Matrix<double, 6, 1>::Zero();\n    F = Eigen::Matrix<double, 6, 6>::Zero();\n    P = Eigen::Matrix<double, 6, 6>::Identity();\n}\n\n\nvoid EKF::predict(const std_msgs::Float64MultiArray::ConstPtr& array, double dt)\n{\n\n    double flw = array->data[0];\n    double frw = array->data[1];\n    double brw = array->data[2];\n    double blw = array->data[3];\n\n    double Vl = (flw + blw)/2.0;\n    double Vr = (frw + brw)/2.0;\n\n    double theta = x_(2,0);\n    double y_ICRr = x_(3,0);\n    double y_ICRl = x_(4,0);\n    double x_ICR = x_(5,0);\n\n    double vx = (Vr*y_ICRl - Vl*y_ICRr)/(y_ICRl - y_ICRr);\n    double vy = x_ICR*(Vl-Vr)/std::abs(y_ICRl - y_ICRr);\n    double omega = -(Vl - Vr)/std::abs(y_ICRl - y_ICRr);\n\n    x_(0,0) = x_(0,0) + dt*(vx*std::cos(theta) - vy*std::sin(theta));\n    x_(1,0) = x_(1,0) + dt*(vy*std::cos(theta) + vx*std::sin(theta));\n    x_(2,0) = theta + dt*omega;\n    x_(3,0) = y_ICRr;\n    x_(4,0) = y_ICRl;\n    x_(5,0) = x_ICR;\n\n    Eigen::Matrix<double, 6, 6> L;\n    L = dt*Eigen::Matrix<double, 6, 6>::Identity();\n\n    F.block(0,0,3,3) = Eigen::Matrix<double, 3, 3>::Identity();\n    F(0,2) = dt*(-vx*std::sin(theta) - vy*std::cos(theta));\n    F(1,2) = dt*(vx*std::cos(theta) - vy*std::sin(theta));\n    F.block(3,0,3,3) = Eigen::Matrix<double, 3, 3>::Zero();\n    F.block(3,3,3,3) = Eigen::Matrix<double, 3, 3>::Identity();\n    F(0,3) = dt*((y_ICRl*(Vr-Vl)/(pow((y_ICRl-y_ICRr),2)))*std::cos(theta)\n                 - (x_ICR*(Vl-Vr)/(pow(y_ICRl-y_ICRr,2)))*std::sin(theta));\n    F(0,4) = dt*((y_ICRr*(Vl-Vr)/(pow((y_ICRl-y_ICRr),2)))*std::cos(theta)\n                 + (x_ICR*(Vl-Vr)/(pow((y_ICRl-y_ICRr),2)))*std::sin(theta));\n    F(0,5) = -dt*((Vl-Vr)/(y_ICRl-y_ICRr))*std::sin(theta);\n    F(1,3) = dt*((y_ICRl*(Vr-Vl)/(pow((y_ICRl-y_ICRr),2)))*std::sin(theta)\n                 + (x_ICR*(Vl-Vr)/(pow((y_ICRl-y_ICRr),2)))*std::cos(theta));\n    F(1,4) = dt*((y_ICRr*(Vl-Vr)/(pow((y_ICRl-y_ICRr),2)))*std::sin(theta)\n                 - (x_ICR*(Vl-Vr)/(pow((y_ICRl-y_ICRr),2)))*std::cos(theta));\n    F(1,5) = dt*((Vl-Vr)/(y_ICRl-y_ICRr))*std::cos(theta);\n    F(2,3) = -dt*(Vl-Vr)/(pow((y_ICRl-y_ICRr),2));\n    F(2,4) = dt*(Vl-Vr)/(pow((y_ICRl-y_ICRr),2));\n    F(2,5) = 0;\n\n\n    P = F*P*F.transpose() + L*Q*L.transpose();\n}\n\n\nvoid EKF::correct(const Eigen::Vector3d& delta)\n{\n\n    Eigen::MatrixXd M = Eigen::Matrix<double, 3,3>::Identity();\n\n    Eigen::Matrix<double, 3, 6> H;\n    H.block(0,0,3,3) = M;\n    H.block(0,3,3,3) = Eigen::Matrix<double, 3, 3>::Zero();\n\n    Eigen::Matrix<double, 6, 3> K;\n    Eigen::Matrix<double, 3, 3> T;\n\n    T = H*P*H.transpose() + M*R*M.transpose();\n\n    K = P*H.transpose()*T.inverse();\n\n    Eigen::Vector3d innovation = delta - x_.block(0,0,3,1);\n\n    innovation(2) = angleDiff(delta(2), x_(2));\n\n    x_ += K*innovation;\n\n    Eigen::Matrix<double, 6, 6> I = Eigen::Matrix<double, 6, 6>::Identity();\n\n    P = (I - K*H)*P;\n}\n", "meta": {"hexsha": "f4ef4d02ecaab1d7f582452aa31855f3c802bb41", "size": 3860, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "path_follower/src/utils/extended_kalman_filter.cpp", "max_stars_repo_name": "sunarditay/gerona", "max_stars_repo_head_hexsha": "7ca6bb169571d498c4a2d627faddc8cbe590d2c9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 296.0, "max_stars_repo_stars_event_min_datetime": "2017-06-19T07:06:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T01:27:44.000Z", "max_issues_repo_path": "path_follower/src/utils/extended_kalman_filter.cpp", "max_issues_repo_name": "sunarditay/gerona", "max_issues_repo_head_hexsha": "7ca6bb169571d498c4a2d627faddc8cbe590d2c9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 29.0, "max_issues_repo_issues_event_min_datetime": "2017-11-07T08:49:12.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-21T22:18:28.000Z", "max_forks_repo_path": "path_follower/src/utils/extended_kalman_filter.cpp", "max_forks_repo_name": "sunarditay/gerona", "max_forks_repo_head_hexsha": "7ca6bb169571d498c4a2d627faddc8cbe590d2c9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 117.0, "max_forks_repo_forks_event_min_datetime": "2017-05-30T10:50:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-09T01:27:23.000Z", "avg_line_length": 27.7697841727, "max_line_length": 80, "alphanum_fraction": 0.5396373057, "num_tokens": 1628, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.46564842418040875}}
{"text": "#include <cassert>\n#include <cstdlib>\n#include <iostream>\n\n#include <boost/smart_ptr/scoped_ptr.hpp>\n\n#include <BnSimulator/core/BooleanNetwork.hpp>\n#include <BnSimulator/core/Trajectory.hpp>\n#include <BnSimulator/core/Attractor.hpp>\n#include <BnSimulator/experiment/TrajectoryRunner.hpp>\n\nint main(int argc, char **argv) {\n\tusing namespace bn;\n\t// network and parameter initialization\n\tconst uint maxSteps = std::atoi(argv[4]);\n\tBooleanNetwork net = BooleanNetwork::makeNetwork(std::atoi(argv[1]),\n\t\t\targv[2], argv[3]);\n\tstd::srand(std::atoi(argv[5]));\n\t// experiment initialization\n\tTrajectoryRunner runner(maxSteps);\n\t// run experiment\n\tboost::scoped_ptr<const Trajectory> t(runner.findAttractor(net));\n\t// post-process results\n\tstd::cout << *t << std::endl; // print the whole trajectory\n\tstd::cout << \"Cycle:\\n\" << t->printCycle(); // print only the cycle\n\tif (t->cycleLength() > 0) {\n\t\tconst Attractor a(*t);\n\t\tstd::cout << \"Attractor representant:\\n\" << a << std::endl;\n\t\tstd::cout << \"Attractor length: \" << a.getLength() << std::endl;\n\t\tboost::scoped_ptr<ExplicitAttractor> ax(new ExplicitAttractor(*t));\n\t\tstd::cout << \"Attractor states:\\n\" << *ax;\n\t\tt.reset(runner.findAttractor(net, a.getRepresentant()));\n\t\tassert(t->getTransient().empty());\n\t\tassert(t->getCycle().size() == a.getLength());\n\t\tstd::cout << \"Cycle:\\n\" << t->printCycle();\n\t}\n\treturn EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "06e9396d71bc0dac6477e519d64db406f06d644e", "size": 1377, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "booleannetwork-code-66-trunk/booleannetwork-code-66-trunk/example/BnSimulator/attractor_basics.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/example/BnSimulator/attractor_basics.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/example/BnSimulator/attractor_basics.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": 35.3076923077, "max_line_length": 69, "alphanum_fraction": 0.6964415396, "num_tokens": 375, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.46564842418040875}}
{"text": "#pragma once\n\n#include <cmath>\n#include <ros/ros.h>\n#include <ct/optcon/optcon.h>\n#include <lqr_controller/declarations_euler.hpp>\n#include <lqr_controller/quadModelParameters.hpp>\n#include <nav_msgs/Odometry.h>\n#include <Eigen/Geometry>\n#include <mavros/frame_tf.h>\n#include <mav_msgs/eigen_mav_msgs.h>\n#include <lqr_controller/trajectory.hpp>\n#include <mav_trajectory_generation/polynomial_optimization_linear.h>\n#include <mav_trajectory_generation/polynomial_optimization_nonlinear.h>\n#include <mav_trajectory_generation/trajectory.h>\n#include <mav_trajectory_generation/trajectory_sampling.h>\n#include <mav_trajectory_generation_ros/ros_visualization.h>\n#include <visualization_msgs/MarkerArray.h>\n#include <mavros_msgs/RCIn.h>\n#include <ros/package.h>\n\nnamespace lqr {\nclass LQR_Euler {\n  public:\n    /*!\n     * Constructor.\n     * @param nodeHandle the ROS node handle.\n     */\n    LQR_Euler(ros::NodeHandle& nodeHandle);\n\n    /*!\n     * Destructor.\n     */\n    virtual ~LQR_Euler();\n\n    control_vector_t getTrajectoryControl();\n    state_vector_t getError();\n    ct::core::FeedbackMatrix<nStates, nControls> getGain();\n    void setOutput(control_vector_t output);\n    control_vector_t getOutput();\n    state_vector_t getRefStates();\n    double getMotorCmd();\n\n   private:\n\n    double k1_; // quadratic first coefficient\n    double k2_; // quadratic second coefficient\n    double k3_; // quadratic third coefficient\n\n\n    /*!\n     * ROS topic callback method.\n     * @param message the received message.\n     */\n    void setRCIn(const mavros_msgs::RCIn::ConstPtr& msg);\n    void topicCallback(const nav_msgs::Odometry::ConstPtr& msg);\n    void setStates(const nav_msgs::Odometry::ConstPtr& msg, state_vector_t& x);\n    void setError(const state_vector_t& xref, const state_vector_t& x, state_vector_t& xerror);\n    bool setTrajectoryReference(state_vector_t& xref,control_vector_t& uref, int trajectory_type);\n    bool setStaticReference(state_vector_t& xref,control_vector_t& uref,Eigen::Vector4d& flat_states);\n    //Eigen::Vector3d quaternion_to_rpy_wrap(const Eigen::Quaterniond &q);\n    void generateTrajectory(mav_msgs::EigenTrajectoryPoint::Vector& states, int trajectory_type);\n    bool readParameters();\n    //! ROS node handle.\n    ros::NodeHandle& nodeHandle_;\n\n    //! ROS topic subscriber.\n    ros::Subscriber odom_sub_;\n    ros::Subscriber RCIn_sub_;\n\n    //Marker publisher\n    ros::Publisher marker_pub_;\n\n    //! State and control matrix dimensions\n    const size_t state_dim = nStates;\n    const size_t control_dim = nControls;\n\n    //Trajectory\n    double sampling_interval = 0.1;\n    const double v_max = 6;\n    const double a_max = 3;\n    const int dimension = 3;\n    int traj_index;\n    bool ref_reached_ = false;\n    bool initiated;\n    std::vector<uint16_t> channels_;\n    mav_msgs::EigenTrajectoryPoint::Vector states_;\n    visualization_msgs::MarkerArray markers;\n    bool closed_traj_;\n    enum trajectory_type {POLYNOMIAL, CIRCLE};\n\n    Eigen::Vector3d position_enu_;\n    Eigen::Vector3d velocity_enu_;\n    Eigen::Quaterniond q_enu_;\n    Eigen::Quaterniond q_ned_;\n    state_matrix_t A_;\n    control_gain_matrix_t B_;\n    ct::core::FeedbackMatrix<nStates, nControls> Kold_;\n    ct::core::FeedbackMatrix<nStates, nControls> Knew_;\n    ros::Time callBack_;\n    double init_time_;\n    state_vector_t x_;\n    control_vector_t u_;\n    state_vector_t xref_;\n    control_vector_t uref_;\n    state_vector_t xerror_;\n    control_vector_t output_;\n\n    ct::optcon::TermQuadratic<nStates, nControls> quadraticCost_;\n    ct::optcon::TermQuadratic<nStates, nControls>::state_matrix_t Q_;\n    ct::optcon::TermQuadratic<nStates, nControls>::control_matrix_t R_;\n    ct::optcon::LQR<nStates, nControls> lqrSolver_;\n\n    state_matrix_t A_quadrotor(const state_vector_t& x, const control_vector_t& u);\n    control_gain_matrix_t B_quadrotor(const state_vector_t& x, const control_vector_t& u);\n  };\n\n} /* namespace */\n", "meta": {"hexsha": "85817de6ea6a7605fa9c74e54e4b9de8a0495fa6", "size": 3934, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/lqr_controller/lqr_euler.hpp", "max_stars_repo_name": "llanesc/lqr-tracking", "max_stars_repo_head_hexsha": "270f2f5164a668bfb77e19f5191595f1d3913a16", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-12-17T10:00:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-19T22:17:36.000Z", "max_issues_repo_path": "include/lqr_controller/lqr_euler.hpp", "max_issues_repo_name": "llanesc/lqr-tracking", "max_issues_repo_head_hexsha": "270f2f5164a668bfb77e19f5191595f1d3913a16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-11-30T18:12:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-28T05:08:35.000Z", "max_forks_repo_path": "include/lqr_controller/lqr_euler.hpp", "max_forks_repo_name": "llanesc/lqr-tracking", "max_forks_repo_head_hexsha": "270f2f5164a668bfb77e19f5191595f1d3913a16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-04-22T09:00:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T09:33:58.000Z", "avg_line_length": 33.0588235294, "max_line_length": 102, "alphanum_fraction": 0.7374173869, "num_tokens": 976, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115012, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.46564841769393345}}
{"text": "#include <boost/test/unit_test.hpp>\n#include <pose_estimation/GeographicProjection.hpp>\n#include <Eigen/Core>\n#include <ogr_spatialref.h>\n\nusing namespace pose_estimation;\n\nBOOST_AUTO_TEST_CASE(test_coordinate_projection)\n{\n    // DFKI Bremen\n    double latitude = 0.92698121;\n    double longitude = 0.154595663;\n    GeographicProjection projection(latitude, longitude);\n\n    // test identity\n    Eigen::Vector2d pos;\n    BOOST_CHECK(projection.worldToNav(latitude, longitude, pos.x(), pos.y()));\n\n    BOOST_CHECK(pos.x() == 0);\n    BOOST_CHECK(pos.y() == 0);\n\n    double latitude2, longitude2;\n    BOOST_CHECK(projection.navToWorld(pos.x(), pos.y(), latitude2, longitude2));\n\n    BOOST_CHECK(latitude2 == latitude);\n    BOOST_CHECK(longitude2 == longitude);\n\n    // test with pos offset\n    GeographicProjection projection2(latitude, longitude, -500., 1234.);\n\n    BOOST_CHECK(projection2.worldToNav(latitude, longitude, pos.x(), pos.y()));\n\n    BOOST_CHECK(pos.x() == -500.);\n    BOOST_CHECK(pos.y() == 1234.);\n\n    // inverse\n    BOOST_CHECK(projection2.navToWorld(pos.x(), pos.y(), latitude2, longitude2));\n\n    BOOST_CHECK(latitude2 == latitude);\n    BOOST_CHECK(longitude2 == longitude);\n\n    // add 0.1 degree in gps frame\n    Eigen::Vector2d pos2;\n    BOOST_CHECK(projection2.worldToNav(latitude + 0.1, longitude + 0.1, pos2.x(), pos2.y()));\n\n    BOOST_CHECK(pos2.x() > pos.x());\n    BOOST_CHECK(pos2.y() < pos.y());\n\n    // substract 10000m in nav frame\n    BOOST_CHECK(projection2.navToWorld(pos.x() - 10000, pos.y() - 10000, latitude2, longitude2));\n\n    BOOST_CHECK(latitude2 < latitude);\n    BOOST_CHECK(longitude2 > longitude);\n}", "meta": {"hexsha": "efbb299dcef75c2cd754c1403dda1ae4acbb7ec5", "size": 1643, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_coordinate_projection.cpp", "max_stars_repo_name": "rock-slam/slam-pose_estimation", "max_stars_repo_head_hexsha": "66c516b2bed5f9a826811e34cf24b08b0483e508", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2017-06-13T07:26:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T02:51:09.000Z", "max_issues_repo_path": "test/test_coordinate_projection.cpp", "max_issues_repo_name": "rock-slam/slam-pose_estimation", "max_issues_repo_head_hexsha": "66c516b2bed5f9a826811e34cf24b08b0483e508", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2016-04-26T16:46:41.000Z", "max_issues_repo_issues_event_max_datetime": "2016-04-27T16:10:23.000Z", "max_forks_repo_path": "test/test_coordinate_projection.cpp", "max_forks_repo_name": "rock-slam/slam-pose_estimation", "max_forks_repo_head_hexsha": "66c516b2bed5f9a826811e34cf24b08b0483e508", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-04-20T12:29:02.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-05T14:47:10.000Z", "avg_line_length": 30.4259259259, "max_line_length": 97, "alphanum_fraction": 0.6883749239, "num_tokens": 420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.46564841769393345}}
{"text": "/*-------------determinant.cpp------------------------------------------------//\n*\n* Purpose: Simple multiplication to help visualize eigenvectors\n*\n*   Notes: compile with:\n*            g++ -I /usr/include/eigen3/ eigentest.cpp -Wno-ignored-attributes -Wno-deprecated-declarations\n*\n*-----------------------------------------------------------------------------*/\n\n#include <iostream>\n#include <Eigen/Core>\n#include <vector>\n#include <fstream>\n\nusing namespace Eigen;\n\nint main(){\n\n    // Opening file to writing\n    std::ofstream output;\n    output.open(\"out.dat\");\n\n    int size = 2, count=0;\n\n    // setting up positions of all the desired points to transform\n    double x[size*size*size], y[size*size*size], z[size*size*size], \n           x2[size*size*size], y2[size*size*size], z2[size*size*size],\n           xval = -1, yval = -1, zval = -1;\n    MatrixXd Arr(3, 3);\n    MatrixXd pos(3, 1);\n\n    // Putting in \"random\" values for matrix\n    Arr << 1, 2, 0,\n           2, 1, 0,\n           0, 0, -3;\n/*\n    Arr << 1, 0, 0,\n           0, 1, 0,\n           0, 0, 1;\n*/\n    std::cout << Arr << '\\n';\n\n    // Creating initial x, y, and z locations\n    for (int i = 0; i < size; ++i){\n        for (int j = 0; j < size; ++j){\n            for (int k = 0; k < size; ++k){\n                xval = -1 + 2 * ((double)i / ((double)size - 1));\n                yval = -1 + 2 * ((double)j / ((double)size - 1));\n                zval = -1 + 2 * ((double)k / ((double)size - 1));\n                x[count] = xval;\n                y[count] = yval;\n                z[count] = zval;\n\n                // Performing multiplication / setting up vector\n                pos(0) = xval;\n                pos(1) = yval;\n                pos(2) = zval;\n                pos = Arr * pos;\n\n                // Storing values in x2, y2, and z2\n                x2[count] = pos(0);\n                y2[count] = pos(1);\n                z2[count] = pos(2);\n                count += 1;\n            }\n        }\n    }\n    count = 8;\n    for (int i = 0; i < count; ++i){\n        std::cout << x[i] << '\\t' << y[i] << '\\t' << z[i] << '\\n';\n        pos(0) = x[i];\n        pos(1) = y[i];\n        pos(2) = z[i];\n\n        pos = Arr * pos;\n\n        // Storing values in x2, y2, and z2\n        x2[i] = pos(0);\n        y2[i] = pos(1);\n        z2[i] = pos(2);\n\n    }\n/*\n\n    // Creating initial x, y, and z locations\n    for (int i = 0; i < size; ++i){\n        for (int j = 0; j < size; ++j){\n            for (int k = 0; k < size; ++k){\n                xval = -1 + 2 * ((double)i / (double)size);\n                yval = -1 + 2 * ((double)j / (double)size);\n                zval = -1 + 2 * ((double)k / (double)size);\n                x[count] = xval;\n                y[count] = yval;\n                z[count] = zval;\n\n                // Performing multiplication / setting up vector\n                pos(0) = xval;\n                pos(1) = yval;\n                pos(2) = zval;\n                pos = Arr * pos;\n\n                // Storing values in x2, y2, and z2\n                x2[count] = pos(0);\n                y2[count] = pos(1);\n                z2[count] = pos(2);\n                count += 1;\n            }\n        }\n    }\n\n\n    // Writing to file in correct format\n    count = 0;\n    for (int i = 0; i < size; ++i){\n        for (int j = 0; j < size; ++j){\n            for (int k = 0; k < size; ++k){\n                output << x[count] << '\\t' << y[count]\n                       << '\\t' << z[count] << '\\t' << count << '\\n';\n                count++;\n            }\n        }\n    } \n\n    output << '\\n' << '\\n';\n\n    count = 0;\n    for (int i = 0; i < size; ++i){\n        for (int j = 0; j < size; ++j){\n            for (int k = 0; k < size; ++k){\n                output << x2[count] << '\\t' << y2[count]\n                       << '\\t' << z2[count] << '\\t' << count << '\\n';\n                count++;\n            }\n        }\n    } \n*/\n\n    int frames = 60;\n    count = 0;\n    double xvel[size*size*size], yvel[size*size*size], zvel[size*size*size];\n    double vid_time = 1.0;\n\n    count = 8;\n\n    for (int i = 0; i < count; ++i){\n        xvel[i] = (x[i] - x2[i]) / vid_time;\n        yvel[i] = (y[i] - y2[i]) / vid_time;\n        zvel[i] = (z[i] - z2[i]) / vid_time;\n    }\n\n    for (int f = 0; f < frames; ++f){\n        for (int i = 0; i < count; ++i){\n            xval = x[i] + ((x2[i] - x[i])\n                   * ((double)f / (double)frames));\n            yval = y[i] + ((y2[i] - y[i])\n                   * ((double)f / (double)frames));\n            zval = z[i] + ((z2[i] - z[i])\n                   * ((double)f / (double)frames));\n\n            output << xval << '\\t' << yval\n                   << '\\t' << zval << '\\t'\n                   << xvel[i] << '\\t' << yvel[i] << '\\t'\n                   << zvel[i] << '\\t' << 1 << '\\t' << i << '\\n';\n\n        }\n        output << '\\n' << '\\n';\n    }\n\n    /*\n    for (int i = 0; i < size; ++i){\n        for (int j = 0; j < size; ++j){\n            for (int k = 0; k < size; ++k){\n                xvel[count] = (x[count] - x2[count]) / vid_time;\n                yvel[count] = (y[count] - y2[count]) / vid_time;\n                zvel[count] = (z[count] - z2[count]) / vid_time;\n                count = count + 1;\n            }\n        }\n    }\n\n    for (int f = 0; f < frames; ++f){\n        count = 0;\n        for (int i = 0; i < size; ++i){\n            for (int j = 0; j < size; ++j){\n                for (int k = 0; k < size; ++k){\n                    xval = x[count] + ((x2[count] - x[count])\n                           * ((double)f / (double)frames));\n                    yval = y[count] + ((y2[count] - y[count])\n                           * ((double)f / (double)frames));\n                    zval = z[count] + ((z2[count] - z[count])\n                           * ((double)f / (double)frames));\n\n                    output << xval << '\\t' << yval\n                           << '\\t' << zval << '\\t'\n                           << xvel[count] << '\\t' << yvel[count] << '\\t'\n                           << zvel[count] << '\\t' << 1 << '\\t' << count << '\\n';\n                    count++;\n                }\n            }\n        }\n\n        output << '\\n' << '\\n';\n    }\n    */\n\n    output.close();\n\n}\n", "meta": {"hexsha": "12ef742d3c9a363edfe3a16ac10836266ef09723", "size": 6179, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "visualization/determinant/determinant.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": "visualization/determinant/determinant.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": "visualization/determinant/determinant.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.5645933014, "max_line_length": 107, "alphanum_fraction": 0.3621945299, "num_tokens": 1829, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.46560768349829096}}
{"text": "#include <geometry.h>\n#include <tiny.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n\n\n#include <vector>\n\ntypedef tiny::MathTypes<float> MT;\ntypedef MT::vector3_type       V;\ntypedef MT::quaternion_type    Q;\ntypedef MT::real_type          T;\ntypedef MT::value_traits       VT;\n\nclass ContactInfo\n{\npublic:\n\n  V m_point;\n  V m_normal;\n  T m_distance;\n\n};\n\n\nclass MyCallback\n  : public geometry::ContactsCallback<V>\n{\npublic:\n\n  std::vector<ContactInfo> m_contacts;\n\npublic:\n\n  void operator()(\n                  V const & point\n                  , V const & normal\n                  , typename V::real_type const & distance\n                  )\n  {\n    ContactInfo info;\n\n    info.m_point = point;\n    info.m_normal = normal;\n    info.m_distance = distance;\n\n    m_contacts.push_back(info);\n  }\n\n};\n\n\n\nBOOST_AUTO_TEST_SUITE(geometry);\n\nBOOST_AUTO_TEST_CASE(contacts_obb_cylinder_test)\n{\n  {\n    V const center    = V::make(0.0, 0.0, 0.0);\n    V const half_ext  = V::make(1.0, 1.0, 1.0);\n    Q const q         = Q::identity();\n\n    V const center2   = V::zero();\n    V const axis      = V::i();\n    T const height    = 1.0;\n    T const radius    = 1.0;\n\n    geometry::OBB<MT>     const & obb = geometry::make_obb<MT>(center, q, half_ext);\n    geometry::Cylinder<V> const & cyl = geometry::make_cylinder(radius, height, axis, center2);\n\n    MyCallback mycallback;\n\n    bool const test = geometry::contacts_obb_cylinder(obb, cyl, 0.0, mycallback, false );\n\n    BOOST_CHECK(!test);\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "367fbc0978272806cadd801ee5b9cead00ffb007", "size": 1670, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/FOUNDATION/GEOMETRY/unit_tests/geometry_contacts_obb_cylinder/geometry_contacts_obb_cylinder.cpp", "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/FOUNDATION/GEOMETRY/unit_tests/geometry_contacts_obb_cylinder/geometry_contacts_obb_cylinder.cpp", "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/FOUNDATION/GEOMETRY/unit_tests/geometry_contacts_obb_cylinder/geometry_contacts_obb_cylinder.cpp", "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": 19.880952381, "max_line_length": 95, "alphanum_fraction": 0.6383233533, "num_tokens": 444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505964, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.46560767905052686}}
{"text": "\n#include \"headers/Reader.hpp\"\n#include \"headers/Hittable.hpp\"\n#include \"headers/Ambient.hpp\"\n#include \"headers/Sphere.hpp\"\n#include \"headers/Triangle.hpp\"\n#include <armadillo>\n#include <vector>\n\nusing namespace arma;\nusing namespace std;\n\nReader::Reader(const char *txt, vector<Object *> &objetos, vector<Light> &luz, Ambient &ambiente, mat &keye, int &cont_tri){\n    \n  double cont, k, j, z[3], cont_obj=0;\n  vec aux1, aux2;\n  mat vertice, face;\n  char tipo_objeto[2], tmp[32];\n  float valor, valor1, valor2, valor3;\n  char barra1[16], barra2[16], barra3[16];\n  vector<Sphere *> bola;\n  \n  ifstream arq (txt, ios_base::in);\n \n  arq >> cont;\n \n  for (k=0; k<cont; k++){\n      \n      arq >> tipo_objeto;\n     \n      if (strcmp(tipo_objeto, \"t\")==0){\n          \n\t  for (j=0;j<28;j++){\n              \n\t    arq >> valor;\n\t    aux1 << valor;\n\t    aux2 = join_cols(aux2,aux1);\n\t  }\n          \n\t  objetos.push_back(new Triangle(aux2)); \n\t  aux2.reset(); cont_tri++;\n\t}\n \n      else if (strcmp(tipo_objeto, \"s\")==0){\n          \n\t  for (j=0;j<23;j++){\n              \n\t    arq >> valor;\n\t    aux1 << valor;\n\t    aux2 = join_cols(aux2,aux1);\n\t  }\n          \n\t  bola.push_back(new Sphere(aux2));\n\t  aux2.reset();   \n\t}\n    }\n    \n    arq >> cont;\n\n    for (k=0; k<cont; k++){\n        \n\tarq >> tipo_objeto;\n\n\tif (strcmp(tipo_objeto, \"o\")==0){\n            \n\t    arq >> tmp;\n\t    \n\t    for (j=0;j<19;j++){\n\t\tarq >> valor;\n\t\taux1 << valor;\n\t\taux2 = join_cols(aux2,aux1);\n\t    }\n\t  \n\t    ifstream obj (tmp, ios_base::in);\n\t    \n\t    while (obj){\n\t\tobj >> tipo_objeto;\n\n\t\tif (strcmp(tipo_objeto,\"v\")==0){\n\t\t    obj >> valor1 >> valor2 >> valor3;\n\t\t    \n\t\t    aux1 << valor1 << valor2 << valor3; \n\t\t    vertice = join_cols(vertice,aux1.t());\n\t\t}\n     \n\t\telse if (strcmp(tipo_objeto,\"f\")==0){\n\t\t    obj >> barra1 >> barra2 >> barra3;\n\t\t    \n\t\t    z[0]=(atoi(barra1));  z[1]=(atoi(barra2));  z[2]=(atoi(barra3));\n\t\t    if (z[0]<0) { z[0] = z[0] * -1; }\n\t\t    if (z[1]<0) { z[1] = z[1] * -1; }\n\t\t    if (z[2]<0) { z[2] = z[2] * -1; }\n\t \n\t\t    aux1 << z[0] << z[1] << z[2];\n\t\t    face = join_cols(face,aux1.t()); cont_obj++;\n\t\t}\n\t      }\n\t    obj.close();\n\t    \n\t    for (j=0;j<cont_obj;j++){ \n\t\taux1 << vertice(face(j,0)-1,0) << vertice(face(j,0)-1,1) << vertice(face(j,0)-1,2) \n\t\t     << vertice(face(j,1)-1,0) << vertice(face(j,1)-1,1) << vertice(face(j,1)-1,2) \n\t\t     << vertice(face(j,2)-1,0) << vertice(face(j,2)-1,1) << vertice(face(j,2)-1,2);\n\t\taux1 = join_cols(aux1,aux2);\n\n\t\tobjetos.push_back(new Triangle(aux1));\n\t\tcont_tri++;\n\t    }\n\t      vertice.reset(); face.reset(); cont_obj=0;\n\t}\n\taux2.reset();\n     }\n     \n  for(unsigned int a=0;a<bola.size();a++){\n    objetos.push_back(bola[a]);\n  }   \n     \n  arq >> cont;\n\n  for (k=0; k<cont; k++){\n      for (j=0;j<18;j++){\n\t  arq >> valor;\n\t  aux1 << valor;\n\t  aux2 = join_cols(aux2,aux1);\n      }\n      \n    luz.push_back(aux2);\n    aux2.reset();\n  }\n  \n  for (j=0;j<4;j++){\n      arq >> valor;\n      aux1 << valor;\n      aux2 = join_cols(aux2,aux1);\n  }\n  \n  aux1 << aux2(0) << aux2(1) << aux2(2);\n  \n  ambiente.SetKa(aux1);\n  ambiente.SetIa(aux2(3));\n  aux2.reset();\n  \n  for (j=0;j<9;j++){\n      arq >> valor;\n      aux1 << valor;\n      aux2 = join_cols(aux2,aux1);\n  }\n  \n  keye << aux2(2)/aux2(0) << aux2(1) \t     << aux2(2)/2 << endr\n       << aux2(3) \t  << aux2(5)/aux2(4) << aux2(5)/2 << endr\n       << aux2(6) \t  << aux2(7)         << aux2(8)   << endr;\n  \n  arq.close(); \n\n}\n", "meta": {"hexsha": "c988c00cabc8dc5cc4a231a446ca9632f3c6f0ff", "size": 3424, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "raytracing/Reader.cpp", "max_stars_repo_name": "arthurflor/RayTracing", "max_stars_repo_head_hexsha": "8deedf33446bed259d8f7e2895024fd1300eb439", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-08-19T09:38:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-27T02:04:22.000Z", "max_issues_repo_path": "raytracing/Reader.cpp", "max_issues_repo_name": "arthurflor23/ray-tracing", "max_issues_repo_head_hexsha": "8deedf33446bed259d8f7e2895024fd1300eb439", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "raytracing/Reader.cpp", "max_forks_repo_name": "arthurflor23/ray-tracing", "max_forks_repo_head_hexsha": "8deedf33446bed259d8f7e2895024fd1300eb439", "max_forks_repo_licenses": ["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.9487179487, "max_line_length": 124, "alphanum_fraction": 0.5035046729, "num_tokens": 1211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.5851011542032313, "lm_q1q2_score": 0.46554047836825707}}
{"text": "/**\n *  Copyright (C) 2012  \n *    Ekaterina Potapova, Andreas Richtsfeld, Johann Prankl, Thomas M\u00f6rwald, Michael Zillich\n *    Automation and Control Institute\n *    Vienna University of Technology\n *    Gusshausstra\u00dfe 25-29\n *    1170 Vienna, Austria\n *    ari(at)acin.tuwien.ac.at\n *\n *  This program is free software: you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n *\n *  This program is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n *\n *  You should have received a copy of the GNU General Public License\n *  along with this program.  If not, see http://www.gnu.org/licenses/\n */\n\n/**\n * @file trainSVM.cpp\n * @author Andreas Richtsfeld, Ekaterina Potapova\n * @date January 2014\n * @version 0.1\n * @brief Trains svm based on scaled features.\n */\n\n\n#include <stdio.h>      /* printf, scanf, puts, NULL */\n#include <stdlib.h>     /* srand, rand */\n#include <time.h>       /* time */\n#include <fstream>\n\n#include <pcl/io/pcd_io.h>\n\n#include <boost/filesystem/fstream.hpp>\n#include <boost/filesystem.hpp>\n\n#include \"v4r/attention_segmentation/SVMTrainModel.h\"\n\nvoid trainFeatures(double gamma, double C, int kernel, int n_folds, double &RecRate, std::vector<int> &ConfusionTable, \n                   std::string &train_ST_file_name_scaled, std::string &model_file_name)\n{\n  svm::SVMTrainModel svmTrainModel;\n  svmTrainModel.setInputFileName(train_ST_file_name_scaled);\n  svmTrainModel.setModelFileName(model_file_name);\n  svmTrainModel.setKernelType(kernel);\n  svmTrainModel.setSVMType(svm::C_SVC);\n  svmTrainModel.setGamma(gamma);\n  svmTrainModel.setC(C);\n  svmTrainModel.setProbability(1);\n  svmTrainModel.setCrossValidation(n_folds);\n  svmTrainModel.setNoPrint(true);\n  svmTrainModel.train(RecRate,ConfusionTable);\n}\n\nvoid trainSVM(std::string &train_ST_file_name_scaled, std::string &model_file_name)\n{\n  int kernels[4] = {svm::RBF, svm::LINEAR, svm::POLY, svm::SIGMOID};\n  std::vector<std::string> kernel_names;\n  kernel_names.resize(4);\n  kernel_names.at(0) = \"rbf\";\n  kernel_names.at(1) = \"linear\";\n  kernel_names.at(2) = \"polynomial\";\n  kernel_names.at(3) = \"sigmoid\";\n\n  printf(\"Classifier: LibSVM\\nParameters (LibSVM): KernelType,C,Gamma,RecRate,ConfusionTable\\n--\\n\");\n\n  double RecRateBest = 0;\n  int kernelBest;\n  std::vector<int> ConfusionTableBest;\n  ConfusionTableBest.resize(4);\n  int gammaBest = 0;\n  int CBest = 0;\n\n  for(int k = 0; k < 1; ++k)\n  {\n    for(int C = -5; C <= 15; C = C+2)\n    {\n      for(int gamma = -15; gamma <= 3; gamma = gamma + 2)\n      {\n        double RecRate;\n        std::vector<int> ConfusionTable;\n        ConfusionTable.resize(4);\n        trainFeatures(pow(2.0,gamma),pow(2.0,C),kernels[k],2,RecRate,ConfusionTable,train_ST_file_name_scaled,model_file_name);\n\n        printf(\"%s;%8.6f;%8.6f;%8.6f;%3.1f/%3.1f/%3.1f/%3.1f/\\n\",kernel_names.at(k).c_str(),pow(2.0,C),pow(2.0,gamma),RecRate,\n               (double)(ConfusionTable.at(0)),(double)(ConfusionTable.at(1)),(double)(ConfusionTable.at(2)),(double)(ConfusionTable.at(3)));\n\n        if(RecRate>RecRateBest)\n        {\n          RecRateBest = RecRate;\n          kernelBest = k;\n          gammaBest = gamma;\n          CBest = C;\n          ConfusionTableBest = ConfusionTable;\n        }\n      }\n    }\n  }\n\n  printf(\"--\\nGlobalBest (LibSVM):\\n\");\n  printf(\"%s;%8.6f;%8.6f;%8.6f;%3.1f/%3.1f/%3.1f/%3.1f/\\n\",kernel_names.at(kernelBest).c_str(),pow(2.0,CBest),pow(2.0,gammaBest),RecRateBest,\n         (double)(ConfusionTableBest.at(0)),(double)(ConfusionTableBest.at(1)),(double)(ConfusionTableBest.at(2)),(double)(ConfusionTableBest.at(3)));\n\n  printf(\"Training final classifier...\\n\");\n  trainFeatures(pow(2.0,gammaBest),pow(2.0,CBest),kernels[kernelBest],0,RecRateBest,ConfusionTableBest,train_ST_file_name_scaled,model_file_name);\n  printf(\"%s;%8.6f;%8.6f;%8.6f;%3.1f/%3.1f/%3.1f/%3.1f/\\n\",kernel_names.at(kernelBest).c_str(),pow(2.0,CBest),pow(2.0,gammaBest),RecRateBest,\n         (double)(ConfusionTableBest.at(0)),(double)(ConfusionTableBest.at(1)),(double)(ConfusionTableBest.at(2)),(double)(ConfusionTableBest.at(3)));\n\n}\n\nvoid printUsage(char *av)\n{\n  printf(\"Usage: %s training_data.txt.scaled model.txt\\n\"\n    \" Options:\\n\"\n    \"   [-h] ... show this help.\\n\"\n    \"   training_data.txt.scaled ... filename with scaled training samples\\n\"\n    \"   model.txt                ... output model\\n\", av);\n  std::cout << \" Example: \" << av << \" training_data.txt.scaled model.txt\" << std::endl;\n}\n\nint main(int argc, char *argv[])\n{\n  if(argc != 3)\n  {\n    printUsage(argv[0]);\n    exit(0);\n  }\n  \n  std::string train_ST_file_name_scaled = argv[1];\n  std::string model_file_name = argv[2];\n  \n  trainSVM(train_ST_file_name_scaled,model_file_name);\n  \n  return(0);\n}\n\n\n", "meta": {"hexsha": "cbaedc4dc66db7f00f17c8405239df490378643b", "size": 5023, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "apps/AttentionSegmentation/trainSVM.cpp", "max_stars_repo_name": "ToMadoRe/v4r", "max_stars_repo_head_hexsha": "7cb817e05cb9d99cb2f68db009c27d7144d07f09", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2015-11-16T14:21:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-09T02:57:33.000Z", "max_issues_repo_path": "apps/AttentionSegmentation/trainSVM.cpp", "max_issues_repo_name": "ToMadoRe/v4r", "max_issues_repo_head_hexsha": "7cb817e05cb9d99cb2f68db009c27d7144d07f09", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 35.0, "max_issues_repo_issues_event_min_datetime": "2015-07-27T15:04:43.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-22T10:52:35.000Z", "max_forks_repo_path": "apps/AttentionSegmentation/trainSVM.cpp", "max_forks_repo_name": "ToMadoRe/v4r", "max_forks_repo_head_hexsha": "7cb817e05cb9d99cb2f68db009c27d7144d07f09", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2015-08-06T09:26:27.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-03T01:31:00.000Z", "avg_line_length": 34.8819444444, "max_line_length": 150, "alphanum_fraction": 0.6774835756, "num_tokens": 1512, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.46554047836825696}}
{"text": "#ifndef __solver_HCod_h__\n#define __solver_HCod_h__\n\n#include <Eigen/Dense>\n#include <vector>\n#include <iostream>\n#include <weighted_hqp/cod.hpp>\n\n\nnamespace hcod{\n    typedef struct H_structure {   \n        Eigen::MatrixXd A;\n        Eigen::MatrixXd b;\n        Eigen::VectorXi btype;\n\n        int mmax;\n        int m;\n        int r;\n        int n;\n        int ra;\n        int rp;\n\n        Eigen::VectorXi iw;\n        Eigen::VectorXi im;\n        Eigen::MatrixXd W;\n        Eigen::MatrixXd H;\n        Eigen::VectorXi fw;\n        Eigen::VectorXi fm;\n\n        Eigen::VectorXi active, activeb, idx_nh_vec;\n        Eigen::VectorXi bound;\n\n        Eigen::MatrixXd A_act;\n\n        // for weighted function\n        Eigen::MatrixXd Wk;\n        Eigen::MatrixXd AkWk;\n        Eigen::VectorXd sol;\n\n        Eigen::MatrixXd Lj;\n        Eigen::MatrixXd Y, Yupj, Ydownj;\n        Eigen::MatrixXd Hj_c, Wj_c;\n\n        std::vector<int> mj, nj, rj, rpj, raj;\n        std::vector<Eigen::VectorXi> iwj, imj, fwj, fmj;\n        std::vector<Eigen::MatrixXd> Aj, Wj, Hj;\n        int rupj;\n\n    } h_structure;   \n\n    class HCod{\n        public:\n            HCod(const std::vector<Eigen::MatrixXd> &A, const std::vector<Eigen::MatrixXd> &b, const std::vector<Eigen::VectorXi> &btype, const std::vector<Eigen::VectorXi> &aset_init, const std::vector<Eigen::VectorXi> &aset_bound);\n            HCod(const std::vector<Eigen::MatrixXd> &A, const std::vector<Eigen::MatrixXd> &b, const std::vector<Eigen::VectorXi> &btype, const std::vector<Eigen::VectorXi> &aset_init, const std::vector<Eigen::VectorXi> &aset_bound, const std::vector<Eigen::MatrixXd> &W);\n            ~HCod(){};\n        \n        private: \n            void set_h_structure(const unsigned int & index);\n            void compute_hcod();\n            void clear_submatrix(){\n                for (int i=0; i<p_; i++){\n                    h_[i].mj.clear();\n                    h_[i].imj.clear();\n                    h_[i].iwj.clear();\n                    h_[i].fwj.clear();\n                    h_[i].fmj.clear();\n                    h_[i].nj.clear();\n                    h_[i].rj.clear();\n                    h_[i].rpj.clear();\n                    h_[i].raj.clear();\n                    h_[i].Aj.clear();\n                    h_[i].Hj.clear();\n                    h_[i].Wj.clear();\n                }\n            }\n\n        public:\n            void print_h_structure(const unsigned int & index);\n            std::vector<H_structure> geth(){\n                return h_;\n            }\n            Eigen::MatrixXd getY(){\n                return Y_;\n            };\n            \n        private:\n            std::vector<Eigen::MatrixXd> A_;\n            std::vector<Eigen::MatrixXd> b_;\n            std::vector<Eigen::VectorXi> btype_;\n            std::vector<Eigen::MatrixXd> W_;\n            std::vector<Eigen::VectorXi> aset_init_, aset_bound_;\n\n            int p_, nh_;\n            std::vector<H_structure> h_;\n            Cod* cod_; \n            Eigen::MatrixXd  Y_;\n            bool _isweighted;\n    };\n}\n\n#endif", "meta": {"hexsha": "7600d5080237a74293344b230dc127fd3e8ec604", "size": 3039, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dyros_jet_controller/include/weighted_hqp/HCod.hpp", "max_stars_repo_name": "Junhyung-Kim/dyros_jet", "max_stars_repo_head_hexsha": "63bff65137a4e3bb85d22a71ea90d9850b12e69e", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-01-31T05:33:39.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-14T08:56:45.000Z", "max_issues_repo_path": "dyros_jet_controller/include/weighted_hqp/HCod.hpp", "max_issues_repo_name": "Junhyung-Kim/dyros_jet", "max_issues_repo_head_hexsha": "63bff65137a4e3bb85d22a71ea90d9850b12e69e", "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": "dyros_jet_controller/include/weighted_hqp/HCod.hpp", "max_forks_repo_name": "Junhyung-Kim/dyros_jet", "max_forks_repo_head_hexsha": "63bff65137a4e3bb85d22a71ea90d9850b12e69e", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-10T04:22:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-10T04:22:39.000Z", "avg_line_length": 30.0891089109, "max_line_length": 272, "alphanum_fraction": 0.5077328068, "num_tokens": 750, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.46554047836825696}}
{"text": "#include \"globimap/counting_globimap.hpp\"\n#include \"globimap_test_config.hpp\"\n#include <algorithm>\n#include <chrono>\n#include <filesystem>\n#include <fstream>\n#include <iostream>\n#include <limits>\n#include <math.h>\n#include <string>\n\n#include <highfive/H5File.hpp>\n#include <tqdm.hpp>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n\n#include \"archive.h\"\n#include \"loc.hpp\"\n#include \"rasterizer.hpp\"\n#include \"shapefile.hpp\"\n\n#include <H5Cpp.h>\n\nnamespace fs = std::filesystem;\n\nnamespace bg = boost::geometry;\nnamespace bgi = boost::geometry::index;\nnamespace bgt = boost::geometry::strategy::transform;\ntypedef bg::model::point<double, 2, bg::cs::cartesian> point_t;\ntypedef bg::model::box<point_t> box_t;\ntypedef bg::model::polygon<point_t> polygon_t;\n\ntypedef std::vector<polygon_t> poly_collection_t;\n\n#ifndef TUM1_ICAML_ORG\nconst std::string base_path = \"/mnt/G/datasets/atlas/\";\nconst std::string vector_base_path = \"/mnt/G/datasets/vector/\";\nconst std::string experiments_path =\n    \"/home/moritz/workspace/bgdm/globimap/experiments/\";\n#else\nconst std::string base_path = \"/home/moritz/tf/pointclouds_2d/data/\";\nconst std::string experiments_path = \"/home/moritz/tf/globimap/experiments/\";\nconst std::string vector_base_path = \"/home/moritz/tf/vector/\";\n#endif\n\nstd::vector<std::string> datasets{\"twitter_1mio_coords.h5\",\n                                  \"twitter_10mio_coords.h5\"};\n\n// std::vector<std::string> datasets{\"twitter_200mio_coords.h5\",\n//                                   \"asia_200mio_coords.h5\"};\nstd::vector<std::string> polygon_sets{\"tl_2017_us_zcta510\",\n                                      \"Global_LSIB_Polygons_Detailed\"};\ntemplate <typename T> std::string render_hist(std::vector<T> hist) {\n  std::stringstream ss;\n  ss << \"[\";\n  for (auto i = 0; i < hist.size(); ++i) {\n    ss << hist[i] << ((i < (hist.size() - 1)) ? \", \" : \"\");\n  }\n  ss << \"]\";\n  return ss.str();\n}\n\ntemplate <typename T>\nstd::string render_stat(const std::string &name, std::vector<T> stat) {\n  double stat_min = FLT_MAX;\n  double stat_max = 0;\n  double stat_mean = 0;\n  double stat_std = 0;\n\n  for (double v : stat) {\n    stat_min = std::min(stat_min, v);\n    stat_max = std::max(stat_max, v);\n    stat_mean += v;\n  }\n  stat_mean /= stat.size();\n\n  for (double v : stat) {\n    stat_std += pow((stat_mean - v), 2);\n  }\n  stat_std /= stat.size();\n  stat_std = sqrt(stat_std);\n\n  std::stringstream ss;\n  ss << \"\\\"\" << name << \"\\\": {\\n\";\n  ss << \"\\\"min\\\": \" << stat_min << \",\\n\";\n  ss << \"\\\"max\\\": \" << stat_max << \",\\n\";\n  ss << \"\\\"mean\\\": \" << stat_mean << \",\\n\";\n  ss << \"\\\"std\\\": \" << stat_std << \",\\n\";\n  ss << \"\\\"hist\\\": \" << render_hist(globimap::make_histogram(stat, 1000))\n     << \"\\n\";\n  ss << \"}\";\n  return ss.str();\n}\n\nint main() {\n  uint width = 2 * 8192, height = 2 * 8192;\n  std::string exp_name = \"polygons_stat\";\n  mkdir((experiments_path + exp_name).c_str(), 0777);\n  for (auto shp : polygon_sets) {\n    std::stringstream ss1;\n    ss1 << shp << \"-\" << width << \"x\" << height;\n    auto polyset_name = ss1.str();\n    std::stringstream ss;\n    ss << vector_base_path << polyset_name;\n    auto poly_path = ss.str();\n\n    int poly_count = 0;\n    for (auto e : fs::directory_iterator(poly_path)) {\n      poly_count += (e.is_regular_file() ? 1 : 0);\n    }\n    std::vector<uint64_t> polysizes;\n    for (auto idx = 0; idx < poly_count; idx++) {\n      std::vector<uint64_t> raster;\n      std::stringstream ss;\n      ss << poly_path << \"/\" << std::setw(8) << std::setfill('0') << idx;\n      auto filename = ss.str();\n      std::ifstream ifile(filename, std::ios::binary);\n      if (!ifile.is_open()) {\n        std::cout << \"ERROR file doesn't exist: \" << filename << std::endl;\n      }\n      Archive<std::ifstream> a(ifile);\n      a >> raster;\n      polysizes.push_back(raster.size());\n      ifile.close();\n    }\n    std::stringstream fss;\n    fss << experiments_path << exp_name << \"/\" << polyset_name << \".json\";\n    std::ofstream out(fss.str());\n    out << \"{\" << render_stat(\"polysizes\", polysizes) << \",\\n\";\n    out << \"\\\"size\\\": \" << poly_count << \"\" << std::endl;\n    out << \"}\" << std::endl;\n\n    out.close();\n    std::cout << \"end: \" << shp << std::endl;\n  }\n};\n", "meta": {"hexsha": "dfa93d569a8b2bf42f95efbcb48d33b8c6b669c3", "size": 4255, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "experiments/src/globimap_print_poly_stats.cpp", "max_stars_repo_name": "mlaass/globimap", "max_stars_repo_head_hexsha": "6bbcbf33cc39ed343662e6b98871dc6dfbc4648f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "experiments/src/globimap_print_poly_stats.cpp", "max_issues_repo_name": "mlaass/globimap", "max_issues_repo_head_hexsha": "6bbcbf33cc39ed343662e6b98871dc6dfbc4648f", "max_issues_repo_licenses": ["MIT"], "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/src/globimap_print_poly_stats.cpp", "max_forks_repo_name": "mlaass/globimap", "max_forks_repo_head_hexsha": "6bbcbf33cc39ed343662e6b98871dc6dfbc4648f", "max_forks_repo_licenses": ["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.6115107914, "max_line_length": 77, "alphanum_fraction": 0.6105757932, "num_tokens": 1202, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.5851011542032313, "lm_q1q2_score": 0.4655404726981016}}
{"text": "/*\n * adjointness.cpp\n *\n *  Created on: 22.07.2017\n *      Author: thies\n */\n\n#include <base/ConstantMesh.h>\n#include <base/DiscretizedFunction.h>\n#include <base/SpaceTimeMesh.h>\n#include <base/Util.h>\n#include <deal.II/base/exceptions.h>\n#include <deal.II/base/function.h>\n#include <deal.II/base/logstream.h>\n#include <deal.II/base/numbers.h>\n#include <deal.II/base/point.h>\n#include <deal.II/base/quadrature_lib.h>\n#include <deal.II/fe/fe_q.h>\n#include <deal.II/grid/grid_generator.h>\n#include <deal.II/grid/grid_tools.h>\n#include <deal.II/grid/tria.h>\n#include <forward/L2RightHandSide.h>\n#include <forward/VectorRightHandSide.h>\n#include <forward/WaveEquation.h>\n#include <forward/WaveEquationAdjoint.h>\n#include <forward/WaveEquationBase.h>\n#include <gtest/gtest.h>\n#include <norms/H1L2.h>\n#include <norms/L2L2.h>\n#include <stddef.h>\n#include <fstream>\n#include <iostream>\n#include <memory>\n#include <vector>\n\nnamespace {\n\nusing namespace dealii;\nusing namespace wavepi::forward;\nusing namespace wavepi::base;\nusing namespace wavepi;\n\n/*****\nNOTE: This module is used for automatic figure generation \nand should therefore only be changed together with the thesis! \n*****/\n\ntemplate <int dim>\nclass TestF : public LightFunction<dim> {\n public:\n  virtual ~TestF() = default;\n  virtual double evaluate(const Point<dim> &p, const double t) const {\n    // if (p.norm() < 0.5)\n    return std::sin(t * 2 * numbers::PI);\n    // else\n    // return 0.0;\n  }\n};\n\ntemplate <int dim>\nclass TestG : public LightFunction<dim> {\n public:\n  virtual ~TestG() = default;\n  virtual double evaluate(const Point<dim> &p, const double t) const {\n    Point<dim> pc = Point<dim>::unit_vector(0);\n    pc *= 0.5;\n\n    return t * std::sin(p.distance(pc) * 2 * numbers::PI);\n  }\n};\n\ntemplate <int dim>\nclass TestH : public LightFunction<dim> {\n public:\n  virtual ~TestH() = default;\n  virtual double evaluate(const Point<dim> &p, const double t) const { return p.norm() * t; }\n};\n\ntemplate <int dim>\nclass TestC : public LightFunction<dim> {\n public:\n  virtual ~TestC() = default;\n  virtual double evaluate(const Point<dim> &p, const double t) const { return p[0] * cos(t) + 1.5; }\n};\n\ntemplate <int dim>\nclass TestRho : public LightFunction<dim> {\n public:\n  virtual ~TestRho() = default;\n  virtual double evaluate(const Point<dim> &p, const double t) const { return p.norm() + sin(t) + 1.5; }\n};\n\ntemplate <int dim>\nclass TestNu : public LightFunction<dim> {\n public:\n  virtual ~TestNu() = default;\n  virtual double evaluate(const Point<dim> &p, const double t) const {\n    // if (t > 1.0) return 0.0;\n\n    return std::abs(p[1]) * sin(t);\n  }\n};\n\ntemplate <int dim>\nclass TestQ : public LightFunction<dim> {\n public:\n  virtual ~TestQ() = default;\n  virtual double evaluate(const Point<dim> &p, const double t) const {\n    return p.norm() < 0.5 ? std::sin(t / 2 * 2 * numbers::PI) : 0.0;\n  }\n\n  static const Point<dim> q_position;\n};\n\ntemplate <int dim>\nvoid run_wave_adjoint_test(int fe_order, int quad_order, int refines, int n_steps,\n                           typename WaveEquationBase<dim>::L2AdjointSolver adjoint_solver, bool trivial, double tol,\n                           std::shared_ptr<std::ofstream> log = nullptr) {\n  AssertThrow(adjoint_solver == WaveEquationBase<dim>::WaveEquationAdjoint ||\n                  adjoint_solver == WaveEquationBase<dim>::WaveEquationBackwards,\n              ExcInternalError());\n\n  auto triangulation = std::make_shared<Triangulation<dim>>();\n  GridGenerator::hyper_cube(*triangulation, -1, 1);\n  Util::set_all_boundary_ids(*triangulation, 0);\n  triangulation->refine_global(refines);\n\n  double t_start = 0.0, t_end = 2.0, dt = t_end / (n_steps - 1);\n  std::vector<double> times;\n\n  for (size_t i = 0; t_start + i * dt <= t_end; i++)\n    times.push_back(t_start + i * dt);\n\n  std::shared_ptr<SpaceTimeMesh<dim>> mesh =\n      std::make_shared<ConstantMesh<dim>>(times, FE_Q<dim>(fe_order), QGauss<dim>(quad_order), triangulation);\n\n  deallog << std::endl << \"----------  n_dofs / timestep: \" << mesh->get_dof_handler(0)->n_dofs();\n  deallog << \", n_steps: \" << times.size() << \"  ----------\" << std::endl;\n\n  WaveEquation<dim> wave_eq(mesh);\n\n  if (!trivial) {\n    wave_eq.set_param_rho(std::make_shared<TestRho<dim>>());\n    wave_eq.set_param_c(std::make_shared<TestC<dim>>());\n    wave_eq.set_param_q(std::make_shared<TestQ<dim>>());\n    wave_eq.set_param_nu(std::make_shared<TestNu<dim>>());\n  }\n\n  WaveEquationAdjoint<dim> wave_eq_adj(wave_eq);\n\n  bool use_adj   = adjoint_solver == WaveEquationBase<dim>::WaveEquationAdjoint;\n  double err_avg = 0.0;\n  double err_simple;\n\n  for (size_t i = 0; i < 1 + 10; i++) {\n    std::shared_ptr<DiscretizedFunction<dim>> f, g;\n\n    if (i == 0) {\n      TestF<dim> f_cont;\n      f = std::make_shared<DiscretizedFunction<dim>>(mesh, f_cont);\n\n      TestG<dim> g_cont;\n      g = std::make_shared<DiscretizedFunction<dim>>(mesh, g_cont);\n    } else {\n      f = std::make_shared<DiscretizedFunction<dim>>(DiscretizedFunction<dim>::noise(mesh));\n      g = std::make_shared<DiscretizedFunction<dim>>(DiscretizedFunction<dim>::noise(mesh));\n\n      if (n_steps > 7) {\n        // make f and g a slightly smoother, random noise might be a too harsh\n\n        f->set_norm(std::make_shared<norms::H1L2<dim>>(0.1));\n        f->dot_transform_inverse();\n\n        g->set_norm(std::make_shared<norms::H1L2<dim>>(0.1));\n        g->dot_transform_inverse();\n      }\n    }\n\n    f->set_norm(std::make_shared<norms::L2L2<dim>>());\n    *f *= 1.0 / f->norm();\n\n    g->set_norm(std::make_shared<norms::L2L2<dim>>());\n    *g *= 1.0 / g->norm();\n\n    DiscretizedFunction<dim> sol_f = wave_eq.run(std::make_shared<L2RightHandSide<dim>>(f), WaveEquation<dim>::Forward);\n    sol_f.throw_away_derivative();\n    sol_f.set_norm(std::make_shared<norms::L2L2<dim>>());\n    EXPECT_GT(sol_f.norm(), 0.0);\n\n    auto g_time_mass = std::make_shared<DiscretizedFunction<dim>>(*g);\n    g_time_mass->set_norm(std::make_shared<norms::L2L2<dim>>());\n\n    DiscretizedFunction<dim> adj_g(mesh);\n    if (use_adj) {\n      // if L2RightHandSide would be used, we would also need a call to solve_mass\n      g_time_mass->dot_transform();\n\n      adj_g = wave_eq_adj.run(std::make_shared<VectorRightHandSide<dim>>(g_time_mass));\n\n      // wave_eq_adj does everything except the multiplication with the mass matrix (to allow for optimization)\n      adj_g.set_norm(std::make_shared<norms::L2L2<dim>>());\n      adj_g.dot_mult_mass_and_transform_inverse();\n    } else {\n      // dot_transforms not needed here, wave_eq backwards should be the L^2([0,T], L^2)-Adjoint\n\n      adj_g = wave_eq.run(std::make_shared<L2RightHandSide<dim>>(g_time_mass), WaveEquation<dim>::Backward);\n      adj_g.throw_away_derivative();\n      adj_g.set_norm(std::make_shared<norms::L2L2<dim>>());\n    }\n\n    EXPECT_GT(adj_g.norm(), 0.0);\n\n    double dot_solf_g = sol_f * (*g);\n    double dot_f_adjg = (*f) * adj_g;\n    double fg_err     = std::abs(dot_solf_g - dot_f_adjg) / (std::abs(dot_solf_g) + 1e-300);\n\n    if (i == 0) {\n      // deallog << \"simple f,g: \" << std::scientific << \"(Lf, g) = \" << dot_solf_g << \", (f, L*g) = \" << dot_f_adjg\n      //         << std::endl;\n      err_simple = fg_err;\n      deallog << std::scientific << \"        relative error for simple f,g = \" << fg_err << std::endl;\n    } else\n      err_avg = ((i - 1) * err_avg + fg_err) / i;\n\n    // deallog << std::scientific << \"(Lf, g) = \" << dot_solf_g << \", (f, L*g) = \" << dot_f_adjg\n    //        << \", rel. error = \" << fg_err << std::endl;\n\n    // EXPECT_LT(zz_err, tol);\n  }\n\n  deallog << std::scientific << \"average relative error for random f,g = \" << err_avg << std::endl;\n\n  double h = dealii::GridTools::maximal_cell_diameter(*mesh->get_triangulation(0));\n\n  if (log)\n    *log << std::scientific << mesh->length() << \" \" << dt << \" \" << refines << \" \" << h << \" \" << err_avg << std::endl;\n\n  EXPECT_LT(err_simple, tol);\n  EXPECT_LT(err_avg, tol);\n}\n}  // namespace\n\n// TEST(WaveEquationAdjointness, Adjoint1DFE1) {\n//   for (int i = 3; i < 10; i++)\n//     run_wave_adjoint_test<1>(1, 5, 6, 1 << i, WaveEquationBase<1>::WaveEquationAdjoint, false, 1e-4);\n// }\n\n// TEST(WaveEquationAdjointness, Adjoint1DFE2) {\n//   for (int i = 3; i < 10; i++)\n//     run_wave_adjoint_test<1>(2, 5, 4, 1 << i, WaveEquationBase<1>::WaveEquationAdjoint, false, 1e-4);\n// }\n\nTEST(WaveEquationAdjointness, Backwards2DFE1) {\n  auto f = std::make_shared<std::ofstream>(\"./WaveEquationAdjointness_Backwards2DFE1.dat\", std::ios_base::trunc);\n  ASSERT_TRUE(*f) << \"could not open file for output\";\n\n  for (int i = 3; i < 10; i++)\n    run_wave_adjoint_test<2>(1, 5, 5, 1 << i, WaveEquationBase<2>::WaveEquationBackwards, false, 1e+2, f);\n}\n\nTEST(WaveEquationAdjointness, BackwardsTrivial2DFE1) {\n  auto f = std::make_shared<std::ofstream>(\"./WaveEquationAdjointness_BackwardsTrivial2DFE1.dat\", std::ios_base::trunc);\n  ASSERT_TRUE(*f) << \"could not open file for output\";\n\n  for (int i = 3; i < 10; i++)\n    run_wave_adjoint_test<2>(1, 5, 5, 1 << i, WaveEquationBase<2>::WaveEquationBackwards, true, 1e+2, f);\n}\n\nTEST(WaveEquationAdjointness, Adjoint2DFE1) {\n  auto f = std::make_shared<std::ofstream>(\"./WaveEquationAdjointness_Adjoint2DFE1.dat\", std::ios_base::trunc);\n  ASSERT_TRUE(*f) << \"could not open file for output\";\n\n  for (int i = 3; i < 10; i++)\n    run_wave_adjoint_test<2>(1, 5, 5, 1 << i, WaveEquationBase<2>::WaveEquationAdjoint, false, 1e-4, f);\n}\n\nTEST(WaveEquationAdjointness, AdjointTrivial2DFE1) {\n  auto f = std::make_shared<std::ofstream>(\"./WaveEquationAdjointness_AdjointTrivial2DFE1.dat\", std::ios_base::trunc);\n  ASSERT_TRUE(*f) << \"could not open file for output\";\n\n  for (int i = 3; i < 10; i++)\n    run_wave_adjoint_test<2>(1, 5, 5, 1 << i, WaveEquationBase<2>::WaveEquationAdjoint, true, 1e-4, f);\n}\n\n// TEST(WaveEquationAdjointness, Adjoint2DFE2) {\n//   auto f = std::make_shared<std::ofstream>(\"./WaveEquationAdjointness_Adjoint2DFE2.dat\", std::ios_base::trunc);\n//   ASSERT_TRUE(*f) << \"could not open file for output\";\n\n//   for (int i = 3; i < 10; i++)\n//     run_wave_adjoint_test<2>(2, 5, 5, 1 << i, WaveEquationBase<2>::WaveEquationAdjoint, false, 1e-4, f);\n// }\n\nTEST(WaveEquationAdjointness, Adjoint3DFE1) {\n  auto f = std::make_shared<std::ofstream>(\"./WaveEquationAdjointness_Adjoint3DFE1.dat\", std::ios_base::trunc);\n  ASSERT_TRUE(*f) << \"could not open file for output\";\n\n  for (int i = 3; i < 9; i++)\n    run_wave_adjoint_test<3>(1, 5, 3, 1 << i, WaveEquationBase<3>::WaveEquationAdjoint, false, 1e-4, f);\n}\n\nTEST(WaveEquationAdjointness, Backwards3DFE1) {\n  auto f = std::make_shared<std::ofstream>(\"./WaveEquationAdjointness_Backwards3DFE1.dat\", std::ios_base::trunc);\n  ASSERT_TRUE(*f) << \"could not open file for output\";\n\n  for (int i = 3; i < 9; i++)\n    run_wave_adjoint_test<3>(1, 5, 3, 1 << i, WaveEquationBase<3>::WaveEquationBackwards, false, 1e+2, f);\n}\n\nTEST(WaveEquationAdjointness, AdjointTrivial3DFE1) {\n  auto f = std::make_shared<std::ofstream>(\"./WaveEquationAdjointness_AdjointTrivial3DFE1.dat\", std::ios_base::trunc);\n  ASSERT_TRUE(*f) << \"could not open file for output\";\n\n  for (int i = 3; i < 9; i++)\n    run_wave_adjoint_test<3>(1, 5, 3, 1 << i, WaveEquationBase<3>::WaveEquationAdjoint, true, 1e-4, f);\n}\n\nTEST(WaveEquationAdjointness, BackwardsTrivial3DFE1) {\n  auto f = std::make_shared<std::ofstream>(\"./WaveEquationAdjointness_BackwardsTrivial3DFE1.dat\", std::ios_base::trunc);\n  ASSERT_TRUE(*f) << \"could not open file for output\";\n\n  for (int i = 3; i < 9; i++)\n    run_wave_adjoint_test<3>(1, 5, 3, 1 << i, WaveEquationBase<3>::WaveEquationBackwards, true, 1e+2, f);\n}", "meta": {"hexsha": "f55a6ba05225b969bb175298b78e8a2c3890b1a4", "size": 11587, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/wave_equation_adjointness.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": "test/wave_equation_adjointness.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": "test/wave_equation_adjointness.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.8730650155, "max_line_length": 120, "alphanum_fraction": 0.6626391646, "num_tokens": 3646, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4655404726981015}}
{"text": "#include <gtest/gtest.h>\n\n#include \"mfem.hpp\"\nusing namespace mfem;\n\n#include <iostream>\n#include <fstream>\n#include <random>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n#include \"../include/core/config.hpp\"\n#include \"../include/stokes/assembly.hpp\"\n#include \"../include/incompNS/test_cases_factory.hpp\"\n#include \"../include/incompNS/coefficients.hpp\"\n#include \"../include/incompNS/pobserver.hpp\"\n#include \"../include/incompNS/putilities.hpp\"\n#include \"../include/uq/scheduler/communicator.hpp\"\n#include \"../include/uq/scheduler/scheduler.hpp\"\n#include \"../include/uq/sampler/sampler.hpp\"\n\n\nTEST (IncompNSUtils, parDivgFreeVelQuadMesh)\n{\n    int nprocs, myrank;\n    MPI_Comm global_comm = MPI_COMM_WORLD;\n    MPI_Comm_size(global_comm, &nprocs);\n    MPI_Comm_rank(global_comm, &myrank);\n\n    // config\n    std::string filename\n            = \"../config_files/unit_tests/\"\n              \"pincompNS_svs.json\";\n    auto config = get_global_config(filename);\n\n    // mesh file\n    std::string base_mesh_dir(\"../meshes/\");\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+\"quad_mesh_l0.mesh\";\n\n    const int nparams = 10;\n    const int nsamples = 3;\n    if (nprocs == 6)\n    {\n        int nprocsPerGroup = 2;\n\n        // make communicators\n        MPI_Comm intra_group_comm, inter_group_comm;\n        std::tie (intra_group_comm, inter_group_comm)\n                = make_communicators(global_comm,\n                                     nprocsPerGroup);\n        int mygroup, mygrouprank;\n        MPI_Comm_rank(inter_group_comm, &mygroup);\n        MPI_Comm_rank(intra_group_comm, &mygrouprank);\n\n        // make schedule\n        int mynsamples;\n        Array<int> dist_nsamples;\n        std::tie(mynsamples, dist_nsamples)\n                = make_schedule(inter_group_comm, nsamples);\n\n        // make samples\n        std::string samplerType = \"uniform\";\n        DenseMatrix all_myomegas;\n        Array<int> all_mysampleIds;\n        std::tie(all_myomegas, all_mysampleIds)\n                = make_samples(intra_group_comm,\n                               inter_group_comm,\n                               samplerType,\n                               nparams, mynsamples,\n                               dist_nsamples);\n\n        // test case\n        std::shared_ptr<IncompNSTestCases> testCase\n            = make_incompNS_test_case(config);\n\n        // mesh\n        const int lx = config[\"level_x\"];\n        Mesh *mesh = new Mesh(mesh_file.c_str());\n        for (int k=0; k<lx; k++) {\n            mesh->UniformRefinement();\n        }\n        std::shared_ptr<ParMesh> pmesh\n                = std::make_shared<ParMesh>\n                (intra_group_comm, *mesh);\n        delete mesh;\n\n        // FE spaces\n        int deg = config[\"deg_x\"];\n        int ndim = pmesh->Dimension();\n        FiniteElementCollection *hdiv_coll\n                = new RT_FECollection(deg, ndim);\n        ParFiniteElementSpace *R_space\n                = new ParFiniteElementSpace(pmesh.get(),\n                                            hdiv_coll);\n\n        FiniteElementCollection *l2_coll\n                = new L2_FECollection(deg, ndim);\n        ParFiniteElementSpace *W_space\n                = new ParFiniteElementSpace(pmesh.get(),\n                                            l2_coll);\n\n        // Divergence operator\n        // \\int_{\\Omega} div(u_h) q_h d_{\\Omega}\n        ParMixedBilinearForm *div_form\n                = new ParMixedBilinearForm(R_space,\n                                           W_space);\n        ConstantCoefficient one(-1.0);\n        div_form->AddDomainIntegrator\n                (new VectorFEDivergenceIntegrator(one));\n        div_form->Assemble();\n        div_form->Finalize();\n        HypreParMatrix *div = div_form->ParallelAssemble();\n        delete div_form;\n\n        // observer\n        std::shared_ptr<IncompNSParObserver> observer\n                = std::make_shared<IncompNSParObserver>\n                (intra_group_comm, config, lx);\n\n        // velocity\n        std::shared_ptr <ParGridFunction> v\n                = std::make_shared<ParGridFunction>(R_space);\n        Vector omegas;\n        all_myomegas.GetColumn(0, omegas);\n        IncompNSInitialVelocityCoeff v0_coeff(testCase);\n        testCase->set_perturbations(omegas);\n        v0_coeff.SetTime(0);\n        v->ProjectCoefficient(v0_coeff);\n        //(*observer) (v);\n\n        double div_old = measure_divergence(div, v.get());\n        std::cout << \"My group: \" << mygroup\n                  << \"\\tMy group rank: \" << mygrouprank\n                  << \"\\tWeak divergence before cleaning: \"\n                  << div_old << std::endl;\n\n        // make divergence free\n        ParDivergenceFreeVelocity divFreeVel (config, pmesh);\n        divFreeVel (v.get());\n\n        double div_new = measure_divergence(div, v.get());\n        std::cout << \"My group: \" << mygroup\n                  << \"\\tMy group rank: \" << mygrouprank\n                  << \"\\tWeak divergence after cleaning: \"\n                  << div_new << std::endl;\n\n        double TOL=1E-5;\n        ASSERT_LE(div_new, TOL);\n    }\n}\n\nTEST (IncompNSUtils, parDivgFreeVelTriMesh)\n{\n    int nprocs, myrank;\n    MPI_Comm global_comm = MPI_COMM_WORLD;\n    MPI_Comm_size(global_comm, &nprocs);\n    MPI_Comm_rank(global_comm, &myrank);\n\n    // config\n    std::string filename\n            = \"../config_files/unit_tests/\"\n              \"pincompNS_svs.json\";\n    auto config = get_global_config(filename);\n\n    // mesh file\n    std::string base_mesh_dir(\"../meshes/\");\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_l0.mesh\";\n\n    const int nparams = 10;\n    const int nsamples = 3;\n    if (nprocs == 6)\n    {\n        int nprocsPerGroup = 2;\n\n        // make communicators\n        MPI_Comm intra_group_comm, inter_group_comm;\n        std::tie (intra_group_comm, inter_group_comm)\n                = make_communicators(global_comm,\n                                     nprocsPerGroup);\n        int mygroup, mygrouprank;\n        MPI_Comm_rank(inter_group_comm, &mygroup);\n        MPI_Comm_rank(intra_group_comm, &mygrouprank);\n\n        // make schedule\n        int mynsamples;\n        Array<int> dist_nsamples;\n        std::tie(mynsamples, dist_nsamples)\n                = make_schedule(inter_group_comm, nsamples);\n\n        // make samples\n        std::string samplerType = \"uniform\";\n        DenseMatrix all_myomegas;\n        Array<int> all_mysampleIds;\n        std::tie(all_myomegas, all_mysampleIds)\n                = make_samples(intra_group_comm,\n                               inter_group_comm,\n                               samplerType,\n                               nparams, mynsamples,\n                               dist_nsamples);\n\n        // test case\n        std::shared_ptr<IncompNSTestCases> testCase\n            = make_incompNS_test_case(config);\n\n        // mesh\n        const int lx = config[\"level_x\"];\n        Mesh *mesh = new Mesh(mesh_file.c_str());\n        for (int k=0; k<lx; k++) {\n            mesh->UniformRefinement();\n        }\n        std::shared_ptr<ParMesh> pmesh\n                = std::make_shared<ParMesh>\n                (intra_group_comm, *mesh);\n        delete mesh;\n\n        // FE spaces\n        int deg = config[\"deg_x\"];\n        int ndim = pmesh->Dimension();\n        FiniteElementCollection *hdiv_coll\n                = new RT_FECollection(deg, ndim);\n        ParFiniteElementSpace *R_space\n                = new ParFiniteElementSpace(pmesh.get(),\n                                            hdiv_coll);\n\n        FiniteElementCollection *l2_coll\n                = new L2_FECollection(deg, ndim);\n        ParFiniteElementSpace *W_space\n                = new ParFiniteElementSpace(pmesh.get(),\n                                            l2_coll);\n\n        // Divergence operator\n        // \\int_{\\Omega} div(u_h) q_h d_{\\Omega}\n        ParMixedBilinearForm *div_form\n                = new ParMixedBilinearForm(R_space,\n                                           W_space);\n        ConstantCoefficient one(-1.0);\n        div_form->AddDomainIntegrator\n                (new VectorFEDivergenceIntegrator(one));\n        div_form->Assemble();\n        div_form->Finalize();\n        HypreParMatrix *div = div_form->ParallelAssemble();\n        delete div_form;\n\n        // observer\n        std::shared_ptr<IncompNSParObserver> observer\n                = std::make_shared<IncompNSParObserver>\n                (intra_group_comm, config, lx);\n\n        // velocity\n        std::shared_ptr <ParGridFunction> v\n                = std::make_shared<ParGridFunction>(R_space);\n        Vector omegas;\n        all_myomegas.GetColumn(0, omegas);\n        IncompNSInitialVelocityCoeff v0_coeff(testCase);\n        testCase->set_perturbations(omegas);\n        v0_coeff.SetTime(0);\n        v->ProjectCoefficient(v0_coeff);\n        //(*observer) (v);\n\n        double div_old = measure_divergence(div, v.get());\n        std::cout << \"My group: \" << mygroup\n                  << \"\\tMy group rank: \" << mygrouprank\n                  << \"\\tWeak divergence before cleaning: \"\n                  << div_old << std::endl;\n\n        // make divergence free\n        ParDivergenceFreeVelocity divFreeVel (config, pmesh);\n        divFreeVel (v.get());\n\n        double div_new = measure_divergence(div, v.get());\n        std::cout << \"My group: \" << mygroup\n                  << \"\\tMy group rank: \" << mygrouprank\n                  << \"\\tWeak divergence after cleaning: \"\n                  << div_new << std::endl;\n\n        double TOL=1E-4;\n        ASSERT_LE(div_new, TOL);\n    }\n}\n", "meta": {"hexsha": "5fbc8e646a381f2bf59be574ff16f1ce3bc6d851", "size": 9725, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_pdivergence.cpp", "max_stars_repo_name": "pratyuksh/NumHypSys", "max_stars_repo_head_hexsha": "29e03f9cc0572178701525210561b152d89999d4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/test_pdivergence.cpp", "max_issues_repo_name": "pratyuksh/NumHypSys", "max_issues_repo_head_hexsha": "29e03f9cc0572178701525210561b152d89999d4", "max_issues_repo_licenses": ["MIT"], "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/test_pdivergence.cpp", "max_forks_repo_name": "pratyuksh/NumHypSys", "max_forks_repo_head_hexsha": "29e03f9cc0572178701525210561b152d89999d4", "max_forks_repo_licenses": ["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.8850174216, "max_line_length": 61, "alphanum_fraction": 0.5667866324, "num_tokens": 2263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4655404726981015}}
{"text": "#ifndef OSRM_LOCATION_DEPENDENT_DATA_HPP\n#define OSRM_LOCATION_DEPENDENT_DATA_HPP\n\n#include <boost/filesystem/path.hpp>\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/index/rtree.hpp>\n\n#include <osmium/osm/way.hpp>\n\n#include <string>\n#include <unordered_map>\n\nnamespace osrm\n{\nnamespace extractor\n{\n\nstruct LocationDependentData\n{\n    using point_t = boost::geometry::model::d2::\n        point_xy<double, boost::geometry::cs::spherical_equatorial<boost::geometry::degree>>;\n    using segment_t = boost::geometry::model::segment<point_t>;\n    using polygon_t = boost::geometry::model::polygon<point_t>;\n    using polygon_bands_t = std::vector<std::vector<segment_t>>;\n    using box_t = boost::geometry::model::box<point_t>;\n\n    using polygon_position_t = std::size_t;\n    using rtree_t = boost::geometry::index::rtree<std::pair<box_t, polygon_position_t>,\n                                                  boost::geometry::index::rstar<8>>;\n\n    using property_t = boost::variant<boost::blank, double, std::string, bool>;\n    using properties_t = std::unordered_map<std::string, property_t>;\n\n    LocationDependentData(const std::vector<boost::filesystem::path> &file_paths);\n\n    bool empty() const { return rtree.empty(); }\n\n    std::vector<std::size_t> GetPropertyIndexes(const point_t &point) const;\n\n    property_t FindByKey(const std::vector<std::size_t> &property_indexes, const char *key) const;\n\n  private:\n    void loadLocationDependentData(const boost::filesystem::path &file_path,\n                                   std::vector<rtree_t::value_type> &bounding_boxes);\n\n    rtree_t rtree;\n    std::vector<std::pair<polygon_bands_t, std::size_t>> polygons;\n    std::vector<properties_t> properties;\n};\n}\n}\n\n#endif\n", "meta": {"hexsha": "c8f4b9af9426ec8cdd197afaf6cb2f8f3790e176", "size": 1781, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/extractor/location_dependent_data.hpp", "max_stars_repo_name": "asaveljevs/osrm-backend", "max_stars_repo_head_hexsha": "15f0ca8ddaa35c5b4d93c25afa72e81e1fb40c3e", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2019-02-21T02:02:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-09T13:49:31.000Z", "max_issues_repo_path": "include/extractor/location_dependent_data.hpp", "max_issues_repo_name": "serarca/osrm-backend", "max_issues_repo_head_hexsha": "3b4e2e83ef85983df1381dbeacd0ea5d4b9bbbcb", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 288.0, "max_issues_repo_issues_event_min_datetime": "2019-02-21T01:34:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-27T12:19:10.000Z", "max_forks_repo_path": "include/extractor/location_dependent_data.hpp", "max_forks_repo_name": "serarca/osrm-backend", "max_forks_repo_head_hexsha": "3b4e2e83ef85983df1381dbeacd0ea5d4b9bbbcb", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-06-21T20:51:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-13T09:22:24.000Z", "avg_line_length": 32.3818181818, "max_line_length": 98, "alphanum_fraction": 0.7035373386, "num_tokens": 431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4655404726981015}}
{"text": "/***********************************************************************\nThis file is part of the librjmcmc project source files.\n\nCopyright : Institut Geographique National (2008-2012)\nContributors : Mathieu Br\u00e9dif, Olivier Tournaire, Didier Boldo\nemail : librjmcmc@ign.fr\n\nThis software is a generic C++ library for stochastic optimization.\n\nThis software is governed by the CeCILL license under French law and\nabiding by the rules of distribution of free software. You can use,\nmodify and/or redistribute the software under the terms of the CeCILL\nlicense as circulated by CEA, CNRS and INRIA at the following URL\n\"http://www.cecill.info\".\n\nAs a counterpart to the access to the source code and rights to copy,\nmodify and redistribute granted by the license, users are provided only\nwith a limited warranty and the software's author, the holder of the\neconomic rights, and the successive licensors have only limited liability.\n\nIn this respect, the user's attention is drawn to the risks associated\nwith loading, using, modifying and/or developing or reproducing the\nsoftware by the user in light of its specific status of free software,\nthat may mean that it is complicated to manipulate, and that also\ntherefore means that it is reserved for developers and experienced\nprofessionals having in-depth computer knowledge. Users are therefore\nencouraged to load and test the software's suitability as regards their\nrequirements in conditions enabling the security of their systems and/or\ndata to be ensured and, more generally, to use and operate it in the\nsame conditions as regards security.\n\nThe fact that you are presently reading this means that you have had\nknowledge of the CeCILL license and that you accept its terms.\n\n***********************************************************************/\n\n#ifndef GEOMETRY_RECTANGLE_2_INTEGRATED_FLUX_HPP\n#define GEOMETRY_RECTANGLE_2_INTEGRATED_FLUX_HPP\n\n#include \"rjmcmc/geometry/Rectangle_2.hpp\"\n#include \"rjmcmc/geometry/Segment_2_iterator.hpp\"\n#include \"rjmcmc/geometry/Iso_rectangle_2_Segment_2_clip.hpp\"\n#include <boost/gil/image.hpp>\n#include <boost/gil/extension/matis/float_images.hpp>\n\ntemplate<typename K, typename OrientedImage, typename Segment, typename Functor>\nvoid integrated_flux(const OrientedImage& v, const Segment& s0, Functor& f)\n{\n    typedef typename OrientedImage::view_t view_t;\n    typedef typename view_t::xy_locator xy_locator;\n\n    view_t view = v.view();\n    int x0 = v.x0();\n    int y0 = v.y0();\n\n    int x1 = x0+view.width();\n    int y1 = y0+view.height();\n    Segment s(s0);\n    typename K::Iso_rectangle_2 bbox(x0,y0,x1,y1);\n    if(!clip(bbox,s)) return;\n\n    geometry::Segment_2_iterator<K> it(s);\n\n    xy_locator loc = view.xy_at(\n            (typename xy_locator::x_coord_t) (it.x()-x0),\n            (typename xy_locator::y_coord_t) (it.y()-y0)\n            );\n\n    boost::gil::point2<std::ptrdiff_t> movement[2] = {\n        boost::gil::point2<std::ptrdiff_t> (it.step(0), 0),\n        boost::gil::point2<std::ptrdiff_t> (0, it.step(1))\n    };\n    typename K::Vector_2 edge(s.target()-s.source());\n    typename K::Vector_2 normal(edge.y(),-edge.x());\n    for (; !it.end() ; ++it)\n    {\n        if(it.x()>=x0 && it.x()<x1 && it.y()>=y0 && it.y()<y1) {\n            typename K::RT length = it.length();\n            f(length,normal,loc);\n        }\n        loc += movement[it.axis()];\n    }\n}\n\n\nclass Flux_functor\n{\npublic:\n    template<typename RT, typename Vector, typename Locator>\n    void operator()(RT length, const Vector& normal, const Locator& loc)\n    {\n        Vector g(boost::gil::at_c<0> (*loc), boost::gil::at_c<1> (*loc));\n        double dot = length*geometry::to_double(normal * g);\n        // res += std::abs(dot)-2.;\n        m_value += std::max(0.,dot);\n    }\n    Flux_functor() : m_value(0) {}\n    double value() const { return m_value; }\nprivate:\n    double m_value;\n};\n\n\ntemplate<typename OrientedImage, typename K>\ndouble integrated_flux(const OrientedImage& view, const geometry::Rectangle_2<K>& r)\n{\n    Flux_functor f;\n    integrated_flux<K>(view,r.segment(0),f);\n    integrated_flux<K>(view,r.segment(1),f);\n    integrated_flux<K>(view,r.segment(2),f);\n    integrated_flux<K>(view,r.segment(3),f);\n    return f.value();\n}\n\n#endif // GEOMETRY_RECTANGLE_2_INTEGRATED_FLUX_HPP\n", "meta": {"hexsha": "e41bb6be76e062666522e1d7c045e7eee440c5f1", "size": 4279, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/rjmcmc/geometry/integrated_flux/Rectangle_2_integrated_flux.hpp", "max_stars_repo_name": "qc2105/librjmcmc", "max_stars_repo_head_hexsha": "6e031a9f6f3612394f8918c745700ae41d2aa586", "max_stars_repo_licenses": ["CECILL-B"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2015-02-17T17:07:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-02T16:49:02.000Z", "max_issues_repo_path": "include/rjmcmc/geometry/integrated_flux/Rectangle_2_integrated_flux.hpp", "max_issues_repo_name": "qc2105/librjmcmc", "max_issues_repo_head_hexsha": "6e031a9f6f3612394f8918c745700ae41d2aa586", "max_issues_repo_licenses": ["CECILL-B"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2015-09-24T09:39:33.000Z", "max_issues_repo_issues_event_max_datetime": "2016-01-03T13:22:49.000Z", "max_forks_repo_path": "include/rjmcmc/geometry/integrated_flux/Rectangle_2_integrated_flux.hpp", "max_forks_repo_name": "qc2105/librjmcmc", "max_forks_repo_head_hexsha": "6e031a9f6f3612394f8918c745700ae41d2aa586", "max_forks_repo_licenses": ["CECILL-B"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2015-03-18T17:32:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-04T21:38:16.000Z", "avg_line_length": 36.8879310345, "max_line_length": 84, "alphanum_fraction": 0.6873101192, "num_tokens": 1048, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4655404726981015}}
{"text": "#include <fstream>\n#include <iostream>\n#include <cmath>\n#include <algorithm>\n#include <vector>\n\n#include <vtkMath.h>\n#include <vtkSmartPointer.h>\n#include <vtkNew.h>\n#include <vtkObjectFactory.h>\n#include <vtkTransform.h>\n#include <vtkMath.h>\n\n#include <Eigen/SVD>\n#include <Eigen/Eigenvalues>\n\n#include \"vtkConversions.h\"\n#include \"vtkCustomTransformInterpolator.h\"\n#include \"vtkTimeCalibration.h\"\n#include \"statistics.h\"\n#include \"eigenFFTCorrelation.h\"\n#include \"interpolator1D.h\"\n\nstd::string ToString(CorrelationStrategy correlationStrategy)\n{\n  switch (correlationStrategy)\n  {\n    case CorrelationStrategy::DPOS:\n      return \"dpos\";\n    case CorrelationStrategy::SPEED_WINDOW:\n      return \"speed_window\";\n    case CorrelationStrategy::ACC_WINDOW:\n      return \"acc_window\";\n    case CorrelationStrategy::JERK_WINDOW:\n      return \"jerk_window\";\n    case CorrelationStrategy::LENGTH:\n      return \"length\";\n    case CorrelationStrategy::DERIVATED_LENGTH:\n      return \"derivated_length\";\n    case CorrelationStrategy::DROT:\n      return \"drot\";\n    case CorrelationStrategy::TRAJECTORY_ANGLE:\n      return \"trajectory_angle\";\n    case CorrelationStrategy::ORIENTATION_ANGLE:\n      return \"orientation_angle\";\n    case CorrelationStrategy::DERIVATED_ORIENTATION_ARC:\n      return \"derivated_orientation_arc\";\n    default:\n      return \"unkown\";\n  }\n}\n\nInterpolator1D<double> compute_speed_window(\n    const vtkSmartPointer<vtkCustomTransformInterpolator>& transform,\n    double window_width)\n{\n  std::vector<double> times = std::vector<double>();\n  std::vector<double> speeds = std::vector<double>();\n  vtkSmartPointer<vtkTransform> prev = vtkSmartPointer<vtkTransform>::New();\n  vtkSmartPointer<vtkTransform> next = vtkSmartPointer<vtkTransform>::New();\n\n  double minMidWindowTime = transform->GetMinimumT() + 0.5 * window_width;\n  double maxMidWindowTime = transform->GetMaximumT() - 0.5 * window_width;\n  double period = transform->GetPeriod();\n  double time = minMidWindowTime;\n  while (time < maxMidWindowTime)\n  {\n    transform->InterpolateTransform(time - 0.5 * window_width, prev);\n    transform->InterpolateTransform(time + 0.5 * window_width, next);\n    speeds.push_back((PositionVectorFromTransform(next)\n\t\t\t    - PositionVectorFromTransform(prev)).norm() / window_width);\n    times.push_back(time);\n    time = time + period;\n  }\n\n  return Interpolator1D<double>(times, speeds);\n}\n\nInterpolator1D<double> compute_acc_window(\n    const vtkSmartPointer<vtkCustomTransformInterpolator>& transform,\n    double window_width)\n{\n  std::vector<double> times = std::vector<double>();\n  std::vector<double> accs = std::vector<double>();\n  vtkSmartPointer<vtkTransform> prev = vtkSmartPointer<vtkTransform>::New();\n  vtkSmartPointer<vtkTransform> next = vtkSmartPointer<vtkTransform>::New();\n  vtkSmartPointer<vtkTransform> curr = vtkSmartPointer<vtkTransform>::New();\n\n  double minMidWindowTime = transform->GetMinimumT() + 0.5 * window_width;\n  double maxMidWindowTime = transform->GetMaximumT() - 0.5 * window_width;\n  double period = transform->GetPeriod();\n  double time = minMidWindowTime;\n  while (time < maxMidWindowTime)\n  {\n    transform->InterpolateTransform(time - 0.5 * window_width, prev);\n    transform->InterpolateTransform(time, curr);\n    transform->InterpolateTransform(time + 0.5 * window_width, next);\n    Eigen::Vector3d a = (PositionVectorFromTransform(next)\n\t\t    + PositionVectorFromTransform(prev)\n\t\t    - 2 * PositionVectorFromTransform(curr)) / (window_width * window_width);\n    accs.push_back(a.norm());\n    times.push_back(time);\n    time = time + period;\n  }\n\n  return Interpolator1D<double>(times, accs);\n}\n\nInterpolator1D<double> compute_jerk_window(\n    const vtkSmartPointer<vtkCustomTransformInterpolator>& transform,\n    double window_width)\n{\n  std::vector<double> times = std::vector<double>();\n  std::vector<double> jerks = std::vector<double>();\n  vtkSmartPointer<vtkTransform> t1 = vtkSmartPointer<vtkTransform>::New();\n  vtkSmartPointer<vtkTransform> t2 = vtkSmartPointer<vtkTransform>::New();\n  vtkSmartPointer<vtkTransform> t3 = vtkSmartPointer<vtkTransform>::New();\n  vtkSmartPointer<vtkTransform> t4 = vtkSmartPointer<vtkTransform>::New();\n\n  double minMidWindowTime = transform->GetMinimumT() + 0.5 * window_width;\n  double maxMidWindowTime = transform->GetMaximumT() - 0.5 * window_width;\n  double period = transform->GetPeriod();\n  double time = minMidWindowTime;\n  while (time < maxMidWindowTime)\n  {\n    transform->InterpolateTransform(time - 0.5 * window_width, t1);\n    transform->InterpolateTransform(time + (- 0.5 + 1.0/3.0) * window_width, t2);\n    transform->InterpolateTransform(time + (- 0.5 + 2.0/3.0) * window_width, t3);\n    transform->InterpolateTransform(time + (- 0.5 + 3.0/3.0) * window_width, t4);\n    Eigen::Vector3d j = (PositionVectorFromTransform(t4)\n\t\t   - 3 * PositionVectorFromTransform(t3)\n\t\t   + 3 * PositionVectorFromTransform(t2)\n\t\t   - PositionVectorFromTransform(t1))\n\t    / std::pow(window_width, 3.0);\n    jerks.push_back(j.norm());\n    times.push_back(time);\n    time = time + period;\n  }\n\n  return Interpolator1D<double>(times, jerks);\n}\n\nInterpolator1D<double> compute_dPos(\n    const vtkSmartPointer<vtkCustomTransformInterpolator>& transform)\n{\n  std::vector<std::vector<double>> transforms = transform->GetTransformList();\n  std::vector<double> t = std::vector<double>(transforms.size() - 1);\n  std::vector<double> x = std::vector<double>(transforms.size() - 1);\n  vtkSmartPointer<vtkTransform> prev = vtkSmartPointer<vtkTransform>::New();\n  vtkSmartPointer<vtkTransform> curr = vtkSmartPointer<vtkTransform>::New();\n  for (unsigned int i = 0; i < transforms.size() - 1; i++)\n  {\n    double t0 = transforms[i][0];\n    double t1 = transforms[i+1][0];\n    t[i] = 0.5 * (t0 + t1);\n    transform->InterpolateTransform(t0, prev);\n    transform->InterpolateTransform(t1, curr);\n    if (std::abs(t1 - t0) < 0.0001) {\n      x[i] = 0.0;\n    } else {\n      x[i] = (PositionVectorFromTransform(curr)\n\t\t      - PositionVectorFromTransform(prev)).norm()\n\t      / (t1 - t0);\n    }\n  }\n  return Interpolator1D<double>(t, x);\n}\n\nInterpolator1D<double> compute_length(\n    const vtkSmartPointer<vtkCustomTransformInterpolator>& transform)\n{\n  std::vector<std::vector<double>> transforms = transform->GetTransformList();\n  std::vector<double> t = std::vector<double>(transforms.size());\n  std::vector<double> x = std::vector<double>(transforms.size());\n  vtkSmartPointer<vtkTransform> prev = vtkSmartPointer<vtkTransform>::New();\n  vtkSmartPointer<vtkTransform> curr = vtkSmartPointer<vtkTransform>::New();\n  t[0] = transforms[0][0];\n  x[0] = 0.0;\n  for (unsigned int i = 1; i < transforms.size(); i++)\n  {\n    t[i] = transforms[i][0];\n    transform->InterpolateTransform(t[i-1], prev);\n    transform->InterpolateTransform(t[i], curr);\n    x[i] = x[i - 1] + (PositionVectorFromTransform(curr)\n\t\t    - PositionVectorFromTransform(prev)).norm();\n  }\n\n  return Interpolator1D<double>(t, x);\n}\n\n\nInterpolator1D<double> compute_derivated_length(\n    const vtkSmartPointer<vtkCustomTransformInterpolator>& transform,\n    double window_width)\n{\n  Interpolator1D<double> length = compute_length(transform);\n  double tMin = transform->GetMinimumT() + 0.5 * window_width;\n  double tMax = transform->GetMaximumT() - 0.5 * window_width;\n  int steps = (tMax - tMin) / transform->GetPeriod() + 1;\n  std::vector<double> derivated_length = std::vector<double>(steps);\n  std::vector<double> times = std::vector<double>(steps);\n  for (int i = 0; i < steps; i++)\n  {\n    double time = tMin + i * transform->GetPeriod();\n    times[i] = time;\n    // length is an interpolator so no need to check that the sample instants\n    // are not the same (they are not, even if the interpolation mode of\n    // this->Reference/Aligned is \"NEAREST\")\n    derivated_length[i] = (length.Get(time + 0.5 * window_width)\n                           - length.Get(time - 0.5 * window_width))\n                    / window_width;\n  }\n\n  return Interpolator1D<double>(times, derivated_length);\n}\n\nInterpolator1D<double> compute_dRot(\n    const vtkSmartPointer<vtkCustomTransformInterpolator>& transform)\n{\n  std::vector<std::vector<double>> transforms = transform->GetTransformList();\n  std::vector<double> t = std::vector<double>(transforms.size() - 1);\n  std::vector<double> x = std::vector<double>(transforms.size() - 1);\n  vtkSmartPointer<vtkTransform> prev = vtkSmartPointer<vtkTransform>::New();\n  vtkSmartPointer<vtkTransform> curr = vtkSmartPointer<vtkTransform>::New();\n  for (int i = 0; i < static_cast<int>(transforms.size()) - 1; i++)\n  {\n    double t0 = transforms[i][0];\n    double t1 = transforms[i+1][0];\n    transform->InterpolateTransform(t0, prev);\n    transform->InterpolateTransform(t1, curr);\n    Eigen::AngleAxisd aa = Eigen::AngleAxisd(RotationMatrixFromTransform(curr)\n\t\t    * RotationMatrixFromTransform(prev).transpose());\n    t[i] = 0.5 * (t0 + t1);\n    if (std::abs(t1 - t0) < 0.0001) {\n      x[i] = 0.0;\n    } else {\n      x[i] = std::abs(aa.angle()) / (t1 - t0);\n    }\n  }\n  return Interpolator1D<double>(t, x);\n}\n\n// TODO: handle case where real_sample_time(next) == real_sample_time(prev)\nInterpolator1D<double> compute_trajectory_angle(\n    const vtkSmartPointer<vtkCustomTransformInterpolator>& transform,\n    double window_width)\n{\n  vtkSmartPointer<vtkTransform> prev = vtkSmartPointer<vtkTransform>::New();\n  vtkSmartPointer<vtkTransform> curr = vtkSmartPointer<vtkTransform>::New();\n  vtkSmartPointer<vtkTransform> next = vtkSmartPointer<vtkTransform>::New();\n  double tMin = transform->GetMinimumT() + 0.5 * window_width;\n  double tMax = transform->GetMaximumT() - 0.5 * window_width;\n  int steps = (tMax - tMin) / transform->GetPeriod() + 1;\n  std::vector<double> trajectory_angle = std::vector<double>(steps);\n  std::vector<double> times = std::vector<double>(steps);\n  for (int i = 0; i < steps; i++)\n  {\n    double time = tMin + i * transform->GetPeriod();\n    transform->InterpolateTransform(time - 0.5 * window_width, prev);\n    transform->InterpolateTransform(time, curr);\n    transform->InterpolateTransform(time + 0.5 * window_width, next);\n    times[i] = time;\n    trajectory_angle[i] = SignedAngle(PositionVectorFromTransform(curr)\n\t\t    - PositionVectorFromTransform(prev),\n\t\t    PositionVectorFromTransform(next)\n\t\t    - PositionVectorFromTransform(curr));\n  }\n\n  return Interpolator1D<double>(times, trajectory_angle);\n}\n\n\nInterpolator1D<double> compute_orientation_arc(\n    const vtkSmartPointer<vtkCustomTransformInterpolator>& transform)\n{\n  std::vector<std::vector<double>> transforms = transform->GetTransformList();\n  std::vector<double> t = std::vector<double>(transforms.size());\n  std::vector<double> x = std::vector<double>(transforms.size());\n  vtkSmartPointer<vtkTransform> prev = vtkSmartPointer<vtkTransform>::New();\n  vtkSmartPointer<vtkTransform> curr = vtkSmartPointer<vtkTransform>::New();\n  t[0] = transforms[0][0];\n  x[0] = 0.0;\n  for (unsigned int i = 1; i < transforms.size(); i++)\n  {\n    t[i] = transforms[i][0];\n    transform->InterpolateTransform(t[i-1], prev);\n    transform->InterpolateTransform(t[i], curr);\n    Eigen::AngleAxisd aa = Eigen::AngleAxisd(RotationMatrixFromTransform(curr)\n\t\t    * RotationMatrixFromTransform(prev).transpose());\n    x[i] = x[i - 1] + std::abs(aa.angle());\n  }\n\n  return Interpolator1D<double>(t, x);\n}\n\n\nInterpolator1D<double> compute_derivated_orientation_arc(\n    const vtkSmartPointer<vtkCustomTransformInterpolator>& transform,\n    double window_width)\n{\n  Interpolator1D<double> orientation_arc = compute_orientation_arc(transform);\n  double tMin = transform->GetMinimumT() + 0.5 * window_width;\n  double tMax = transform->GetMaximumT() - 0.5 * window_width;\n  int steps = (tMax - tMin) / transform->GetPeriod() + 1;\n  std::vector<double> derivated_orientation_arc = std::vector<double>(steps);\n  std::vector<double> times = std::vector<double>(steps);\n  for (int i = 0; i < steps; i++)\n  {\n    double time = tMin + i * transform->GetPeriod();\n    times[i] = time;\n    // length is an interpolator so no need to check that the sample instants\n    // are not the same (they are not, even if the interpolation mode of\n    // this->Reference/Aligned is \"NEAREST\")\n    derivated_orientation_arc[i] =\n                    (orientation_arc.Get(time + 0.5 * window_width)\n                     - orientation_arc.Get(time - 0.5 * window_width))\n                    / window_width;\n  }\n\n  return Interpolator1D<double>(times, derivated_orientation_arc);\n}\n\n\n// TODO: handle case where real_sample_time(next) == real_sample_time(prev)\nInterpolator1D<double> compute_orientation_angle(\n    const vtkSmartPointer<vtkCustomTransformInterpolator>& transform,\n    double window_width)\n{\n  vtkSmartPointer<vtkTransform> prev = vtkSmartPointer<vtkTransform>::New();\n  vtkSmartPointer<vtkTransform> next = vtkSmartPointer<vtkTransform>::New();\n  double tMin = transform->GetMinimumT() + 0.5 * window_width;\n  double tMax = transform->GetMaximumT() - 0.5 * window_width;\n  int steps = (tMax - tMin) / transform->GetPeriod() + 1;\n  std::vector<double> orientation_angle = std::vector<double>(steps);\n  std::vector<double> times = std::vector<double>(steps);\n  for (int i = 0; i < steps; i++)\n  {\n    double time = tMin + i * transform->GetPeriod();\n    transform->InterpolateTransform(time - 0.5 * window_width, prev);\n    transform->InterpolateTransform(time + 0.5 * window_width, next);\n    times[i] = time;\n    Eigen::AngleAxisd angleAxis(RotationMatrixFromTransform(next)\n\t\t    * RotationMatrixFromTransform(prev).transpose());\n    orientation_angle[i] = angleAxis.angle();\n  }\n\n  return Interpolator1D<double>(times, orientation_angle);\n}\n\ndouble ComputeTimeShift(vtkSmartPointer<vtkTemporalTransforms> reference,\n                      vtkSmartPointer<vtkTemporalTransforms> aligned,\n                      CorrelationStrategy correlationStrategy,\n                      double time_window_width,\n                      bool substract_mean)\n{\n  vtkSmartPointer<vtkCustomTransformInterpolator> referenceInterpolator\n      = reference->CreateInterpolator();\n  referenceInterpolator->SetInterpolationTypeToLinear();\n  vtkSmartPointer<vtkCustomTransformInterpolator> alignedInterpolator\n      = aligned->CreateInterpolator();\n  alignedInterpolator->SetInterpolationTypeToLinear();\n  Interpolator1D<double> sig_reference;\n  Interpolator1D<double> sig_aligned;\n  // first, compute the signals using the chosen method\n  switch (correlationStrategy)\n  {\n    case CorrelationStrategy::DPOS:\n      sig_reference = compute_dPos(referenceInterpolator);\n      sig_aligned = compute_dPos(alignedInterpolator);\n      break;\n    case CorrelationStrategy::SPEED_WINDOW:\n      sig_reference = compute_speed_window(referenceInterpolator,\n                                               time_window_width);\n      sig_aligned = compute_speed_window(alignedInterpolator,\n                                             time_window_width);\n      break;\n    case CorrelationStrategy::ACC_WINDOW:\n      sig_reference = compute_acc_window(referenceInterpolator,\n                                               time_window_width);\n      sig_aligned = compute_acc_window(alignedInterpolator,\n                                             time_window_width);\n      break;\n    case CorrelationStrategy::JERK_WINDOW:\n      sig_reference = compute_jerk_window(referenceInterpolator,\n                                               time_window_width);\n      sig_aligned = compute_jerk_window(alignedInterpolator,\n                                             time_window_width);\n      break;\n    case CorrelationStrategy::LENGTH:\n      sig_reference = compute_length(referenceInterpolator);\n      sig_aligned = compute_length(alignedInterpolator);\n      break;\n    case CorrelationStrategy::DERIVATED_LENGTH:\n      sig_reference = compute_derivated_length(referenceInterpolator,\n                                               time_window_width);\n      sig_aligned = compute_derivated_length(alignedInterpolator,\n                                             time_window_width);\n      break;\n    case CorrelationStrategy::DROT:\n      sig_reference = compute_dRot(referenceInterpolator);\n      sig_aligned = compute_dRot(alignedInterpolator);\n      break;\n    case CorrelationStrategy::TRAJECTORY_ANGLE:\n      sig_reference = compute_trajectory_angle(referenceInterpolator,\n                                               time_window_width);\n      sig_aligned = compute_trajectory_angle(alignedInterpolator,\n                                             time_window_width);\n      break;\n    case CorrelationStrategy::ORIENTATION_ANGLE:\n      sig_reference = compute_orientation_angle(referenceInterpolator,\n                                                time_window_width);\n      sig_aligned = compute_orientation_angle(alignedInterpolator,\n                                              time_window_width);\n      break;\n    case CorrelationStrategy::DERIVATED_ORIENTATION_ARC:\n      sig_reference = compute_derivated_orientation_arc(\n                              referenceInterpolator,\n                              time_window_width);\n      sig_aligned = compute_derivated_orientation_arc(\n                              alignedInterpolator,\n                              time_window_width);\n      break;\n    default:\n      std::cerr << \"unknown correlation strategy\" << std::endl;\n      return 0.0;\n  }\n\n  if (substract_mean)\n  {\n    sig_reference.ApplyValueShift(- sig_reference.Mean());\n    sig_aligned.ApplyValueShift(- sig_aligned.Mean());\n  }\n\n  // We prefere the two signals to start at t = 0, so we time shift them,\n  // but before that we save the information that we would lose otherwise.\n  double pre_resample = sig_aligned.GetMinimumT() - sig_reference.GetMinimumT();\n  sig_aligned.ApplyTimeShift(- sig_aligned.GetMinimumT());\n  sig_reference.ApplyTimeShift(- sig_reference.GetMinimumT());\n\n  // by construction we now have tMin == 0.0;\n  double tMax = std::max(sig_reference.GetMaximumT(), sig_aligned.GetMaximumT());\n  double period = std::min(sig_reference.GetAveragePeriod(),\n\t\t  sig_aligned.GetAveragePeriod());\n  int steps = std::floor(tMax / period);\n  std::vector<double> reference_resampled = std::vector<double>(steps);\n  std::vector<double> aligned_resampled = std::vector<double>(steps);\n  for (int i = 0; i < steps; i++)\n  {\n    double time = 0.0 + i * period;\n    reference_resampled[i] = sig_reference.Get(time);\n    aligned_resampled[i] = sig_aligned.Get(time);\n  }\n\n  std::vector<double> test = fftcorrelate(reference_resampled, aligned_resampled);\n\n  int correlation = max_fftcorrelation(reference_resampled, aligned_resampled);\n  double correction = correlation * period;\n  double delta_t = pre_resample - correction;\n  return delta_t;\n}\n\nvoid ShowTrajectoryInfo(vtkSmartPointer<vtkTemporalTransforms> reference, vtkSmartPointer<vtkTemporalTransforms> aligned)\n{\n  vtkSmartPointer<vtkCustomTransformInterpolator> referenceI = reference->CreateInterpolator();\n  vtkSmartPointer<vtkCustomTransformInterpolator> alignedI = aligned->CreateInterpolator();\n  std::cout << std::fixed;\n  std::cout << std::setprecision(4);\n  std::cout << \"reference:                 \" << referenceI->GetMaximumT() - referenceI->GetMinimumT()\n            << \"s from \" << referenceI->GetMinimumT() << \" to \" << referenceI->GetMaximumT()\n            << \", period is \" << referenceI->GetPeriod() << std::endl;\n  std::cout << \"aligned:                   \" << alignedI->GetMaximumT() - alignedI->GetMinimumT()\n            << \"s from \" << alignedI->GetMinimumT() << \" to \" << alignedI->GetMaximumT()\n            << \", period is \" << alignedI->GetPeriod() << std::endl;\n}\n\nvoid DemoAllTimesyncMethods(vtkSmartPointer<vtkTemporalTransforms> reference, vtkSmartPointer<vtkTemporalTransforms> aligned) {\n  vtkSmartPointer<vtkCustomTransformInterpolator> referenceI = reference->CreateInterpolator();\n  vtkSmartPointer<vtkCustomTransformInterpolator> alignedI = aligned->CreateInterpolator();\n\n  std::cout << std::fixed;\n  std::cout << std::setprecision(4);\n  ShowTrajectoryInfo(reference, aligned);\n  std::cout << std::endl;\n  std::cout << \"dPos:                      \" << ComputeTimeShift(reference, aligned, CorrelationStrategy::DPOS, 1.0) << std::endl;\n  std::cout << \"speed window:              \" << ComputeTimeShift(reference, aligned, CorrelationStrategy::SPEED_WINDOW, 1.0) << std::endl;\n  std::cout << \"acceleration window:       \" << ComputeTimeShift(reference, aligned, CorrelationStrategy::ACC_WINDOW, 3) << std::endl;\n  std::cout << \"jerk window:               \" << ComputeTimeShift(reference, aligned, CorrelationStrategy::JERK_WINDOW, 6) << std::endl;\n  std::cout << \"derivated length:          \" << ComputeTimeShift(reference, aligned, CorrelationStrategy::DERIVATED_LENGTH, 1.0) << std::endl;\n  std::cout << \"dRot:                      \" << ComputeTimeShift(reference, aligned, CorrelationStrategy::DROT, 1.0) << std::endl;\n  std::cout << \"trajectory angle:          \" << ComputeTimeShift(reference, aligned, CorrelationStrategy::TRAJECTORY_ANGLE, 10.0) << std::endl;\n  std::cout << \"orientation angle:         \" << ComputeTimeShift(reference, aligned, CorrelationStrategy::ORIENTATION_ANGLE, 1.0) << std::endl;\n  std::cout << \"derivated orientation arc: \" << ComputeTimeShift(reference, aligned, CorrelationStrategy::DERIVATED_ORIENTATION_ARC, 1.0) << std::endl;\n}\n\n\ndouble ComputeScale(vtkSmartPointer<vtkTemporalTransforms> reference,\n                  vtkSmartPointer<vtkTemporalTransforms> aligned,\n                  CorrelationStrategy correlationStrategy,\n                  double time_window_width)\n{\n  const double div_epsilon = 1e-4;\n  vtkSmartPointer<vtkCustomTransformInterpolator> referenceInterpolator = reference->CreateInterpolator();\n  referenceInterpolator->SetInterpolationTypeToLinear();\n  vtkSmartPointer<vtkCustomTransformInterpolator> alignedInterpolator = aligned->CreateInterpolator();\n  alignedInterpolator->SetInterpolationTypeToLinear();\n  Interpolator1D<double> sig_reference;\n  Interpolator1D<double> sig_aligned;\n  switch (correlationStrategy)\n  {\n    case CorrelationStrategy::DPOS:\n      sig_reference = compute_dPos(referenceInterpolator);\n      sig_aligned = compute_dPos(alignedInterpolator);\n      break;\n    case CorrelationStrategy::SPEED_WINDOW:\n      sig_reference = compute_speed_window(referenceInterpolator,\n                                               time_window_width);\n      sig_aligned = compute_speed_window(alignedInterpolator,\n                                             time_window_width);\n      break;\n    case CorrelationStrategy::ACC_WINDOW:\n      sig_reference = compute_acc_window(referenceInterpolator,\n                                               time_window_width);\n      sig_aligned = compute_acc_window(alignedInterpolator,\n                                             time_window_width);\n      break;\n    case CorrelationStrategy::JERK_WINDOW:\n      sig_reference = compute_jerk_window(referenceInterpolator,\n                                               time_window_width);\n      sig_aligned = compute_jerk_window(alignedInterpolator,\n                                             time_window_width);\n      break;\n    case CorrelationStrategy::LENGTH:\n      sig_reference = compute_length(referenceInterpolator);\n      sig_aligned = compute_length(alignedInterpolator);\n      break;\n    case CorrelationStrategy::DERIVATED_LENGTH:\n      sig_reference = compute_derivated_length(referenceInterpolator,\n                                               time_window_width);\n      sig_aligned = compute_derivated_length(alignedInterpolator,\n                                             time_window_width);\n      break;\n    default:\n      std::cerr << \"unsuported correlation strategy\" << std::endl;\n      return 0.0;\n  }\n\n  double tMin = std::min(sig_reference.GetMinimumT(), sig_aligned.GetMaximumT());\n  double tMax = std::max(sig_reference.GetMaximumT(), sig_aligned.GetMaximumT());\n  double period = std::min(sig_reference.GetAveragePeriod(),\n\t\t  sig_aligned.GetAveragePeriod());\n  int steps = std::floor((tMax - tMin) / period);\n  std::vector<double> ratios;\n  for (int i = 0; i < steps; i++)\n  {\n    double time = tMin + i * period;\n    double reference_resampled = sig_reference.Get(time);\n    double aligned_resampled = sig_aligned.Get(time);\n    if (reference_resampled < div_epsilon)\n    {\n      continue;\n    }\n    else\n    {\n      ratios.push_back(aligned_resampled / reference_resampled);\n    }\n  }\n\n  return ComputeMedian(ratios);\n}\n", "meta": {"hexsha": "e943fe3291d0bac360fc1fc1f3bc3e4bcf0e7386", "size": 24511, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "LidarPlugin/Common/Calib/Temporal/vtkTimeCalibration.cxx", "max_stars_repo_name": "Pandinosaurus/LidarView", "max_stars_repo_head_hexsha": "9b9b2976e9ac5dcd891a604dabbb79bd6fc6a57a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-13T11:14:18.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-13T11:14:18.000Z", "max_issues_repo_path": "LidarPlugin/Common/Calib/Temporal/vtkTimeCalibration.cxx", "max_issues_repo_name": "yxw027/LidarView", "max_issues_repo_head_hexsha": "9267729e62886a324ba7f2e3fed50db38b24f001", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LidarPlugin/Common/Calib/Temporal/vtkTimeCalibration.cxx", "max_forks_repo_name": "yxw027/LidarView", "max_forks_repo_head_hexsha": "9267729e62886a324ba7f2e3fed50db38b24f001", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-05-30T10:07:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-30T10:07:35.000Z", "avg_line_length": 43.001754386, "max_line_length": 151, "alphanum_fraction": 0.6865080984, "num_tokens": 5685, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4655404726981015}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2015 NumScale SAS\n  @copyright 2015 J.T. Lapreste\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_COMMON_GENERIC_FUNCTION_IROUND_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_GENERIC_FUNCTION_IROUND_HPP_INCLUDED\n\n#include <boost/simd/constant/half.hpp>\n#include <boost/simd/constant/mhalf.hpp>\n#include <boost/simd/function/if_else.hpp>\n#include <boost/simd/function/simd/is_ltz.hpp>\n#include <boost/simd/function/simd/plus.hpp>\n#include <boost/simd/function/simd/toints.hpp>\n#include <boost/dispatch/function/overload.hpp>\n#include <boost/dispatch/meta/as_integer.hpp>\n#include <boost/config.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n BOOST_DISPATCH_OVERLOAD ( iround_\n                         , (typename A0)\n                         , bd::cpu_\n                         , bd::generic_<bd::arithmetic_<A0> >\n                         )\n  {\n    BOOST_FORCEINLINE A0 operator() ( A0 const& a0) const BOOST_NOEXCEPT\n    {\n      return a0;\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( iround_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::generic_<bd::floating_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE bd::as_integer_t<A0> operator() ( A0 const& a0) const BOOST_NOEXCEPT\n    {\n      A0 inc = if_else(is_ltz(a0), Mhalf<A0>(), Half<A0>());\n      return toints(a0+inc);\n    }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "502c9db30bdb200131e86d420a68e6696689fe84", "size": 1766, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arch/common/generic/function/iround.hpp", "max_stars_repo_name": "yaeldarmon/boost.simd", "max_stars_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/simd/arch/common/generic/function/iround.hpp", "max_issues_repo_name": "yaeldarmon/boost.simd", "max_issues_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/arch/common/generic/function/iround.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": 31.5357142857, "max_line_length": 100, "alphanum_fraction": 0.557191393, "num_tokens": 392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.795658090372256, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.46554046702794577}}
{"text": "static char help[] = \"Advance_ small CMEs to benchmark intranode performance.\\n\\n\";\n\n#include <fstream>\n#include <iomanip>\n#include <petscmat.h>\n#include <petscvec.h>\n#include <petscviewer.h>\n#include <armadillo>\n#include <cmath>\n#include <sys/stat.h>\n#include \"pacmensl_all.h\"\n\nnamespace hog1p_cme {\n// stoichiometric matrix of the toggle switch model\narma::Mat<PetscInt> SM{{1,-1,-1,0,0,0,0,0,0},\n                       {0,0,0,1,0,-1,0,0,0},\n                       {0,0,0,0,1,0,-1,0,0},\n                       {0,0,0,0,0,1,0,-1,0},\n                       {0,0,0,0,0,0,1,0,-1},};\n\n// reaction parameters\nconst PetscReal k12{1.29},k23{0.0067},k34{0.133},k32{0.027},k43{0.0381},k21{1.0e0},kr21{0.005},kr31{\n    0.45},      kr41{0.025},kr22{0.0116},kr32{0.987},kr42{0.0538},trans{0.01},gamma1{0.001},gamma2{0.0049},\n// parameters for the time-dependent factors\n                r1{6.9e-5},r2{7.1e-3},eta{3.1},Ahog{9.3e09},Mhog{6.4e-4};\n\n// propensity function\ninline PetscReal hog_propensity(int *X,int k)\n{\n  switch (k)\n  {\n    case 0:return k12 * double(X[0] == 0) + k23 * double(X[0] == 1) + k34 * double(X[0] == 2);\n    case 1:return k32 * double(X[0] == 2) + k43 * double(X[0] == 3);\n    case 2:return k21 * double(X[0] == 1);\n    case 3:return kr21 * double(X[0] == 1) + kr31 * double(X[0] == 2) + kr41 * double(X[0] == 3);\n    case 4:return kr22 * double(X[0] == 1) + kr32 * double(X[0] == 2) + kr42 * double(X[0] == 3);\n    case 5:return trans * double(X[1]);\n    case 6:return trans * double(X[2]);\n    case 7:return gamma1 * double(X[3]);\n    case 8:return gamma2 * double(X[4]);\n    default:return 0.0;\n  }\n}\n\nint propensity(const int reaction,\n               const int num_species,\n               const int num_states,\n               const int *states,\n               PetscReal *outputs,\n               void *args)\n{\n  int (*X)[5] = ( int (*)[5] ) states;\n  for (int i = 0; i < num_states; ++i)\n  {\n    outputs[i] = hog_propensity(X[i],reaction);\n  }\n  return 0;\n}\n\n// function to compute the time-dependent coefficients of the propensity functions\nint t_fun(double t,int num_coefs,PetscReal *outputs,void *args)\n{\n  if (num_coefs != 9) return -1;\n\n  arma::Row<double> u(outputs,9,false,true);\n  u.fill(1.0);\n\n  double h1 = (1.0 - exp(-r1 * t)) * exp(-r2 * t);\n\n  double hog1p = pow(h1 / (1.0 + h1 / Mhog),eta) * Ahog;\n\n  u(2) = std::max(0.0,3200.0 - 7710.0 * (hog1p));\n\n  return 0;\n}\n\n// Function to constraint the shape of the Fsp\nint lhs_constr(PetscInt num_species,PetscInt num_constrs,PetscInt num_states,PetscInt *states,int *vals,\n               void *args)\n{\n  if (num_species != 5)\n  {\n    return -1;\n  }\n  if (num_constrs != 7)\n  {\n    return -1;\n  }\n  for (int j{0}; j < num_states; ++j)\n  {\n    for (int i{0}; i < 5; ++i)\n    {\n      vals[num_constrs * j + i] = (states[num_species * j + i]);\n    }\n    vals[num_constrs * j + 5] = ((states[num_species * j + 1]) + (states[num_species * j + 3]));\n    vals[num_constrs * j + 6] = ((states[num_species * j + 2]) + (states[num_species * j + 4]));\n  }\n  return 0;\n}\n\narma::Row<int>    rhs_constr_hyperrec{3,10,10,10,10};\narma::Row<double> expansion_factors_hyperrec{0.0,0.25,0.25,0.25,0.25};\narma::Row<int>    rhs_constr{3,10,10,10,10,10,10};\narma::Row<double> expansion_factors{0.0,0.2,0.2,0.2,0.2,0.2,0.2};\n}\n\nusing arma::dvec;\nusing arma::Col;\nusing arma::Row;\n\nusing std::cout;\nusing std::endl;\n\nusing namespace hog1p_cme;\nusing namespace pacmensl;\n\nvoid output_marginals(MPI_Comm comm,std::string model_name,PartitioningType fsp_par_type,\n                      PartitioningApproach fsp_repart_approach,std::string constraint_type,\n                      DiscreteDistribution &solution,arma::Row<int> constraints);\n\nvoid output_performance(MPI_Comm comm,std::string &model_name,PartitioningType fsp_par_type,\n                        PartitioningApproach fsp_repart_approach,std::string constraint_type,\n                        ODESolverType ode_type,\n                        FspSolverMultiSinks &fsp_solver);\n\nint ParseOptions(MPI_Comm comm,\n                 PartitioningType &fsp_par_type,\n                 PartitioningApproach &fsp_repart_approach,\n                 PetscBool &output_marginal,\n                 PetscBool &fsp_log_events,\n                 ODESolverType &ode_solver);\n\nint main(int argc,char *argv[])\n{\n  Environment my_env(&argc,&argv,help);\n\n  PetscMPIInt    ierr,myRank,num_procs;\n  PetscErrorCode petsc_err;\n  MPI_Comm       comm;\n  MPI_Comm_dup(PETSC_COMM_WORLD,&comm);\n  MPI_Comm_size(comm,&num_procs);\n  PetscPrintf(comm,\"Solving with %d processors.\\n\",num_procs);\n\n  // Register PETSc stages\n  PetscLogStage stages[2];\n  petsc_err = PetscLogStageRegister(\"Solve with adaptive default state set shape\",&stages[0]);\n  CHKERRQ(petsc_err);\n  petsc_err = PetscLogStageRegister(\"Solve with fixed default state set shape\",&stages[1]);\n  CHKERRQ(petsc_err);\n\n  // Set up CME\n  std::string         model_name = \"hog1p\";\n  Model               hog1p_model(hog1p_cme::SM,hog1p_cme::t_fun,hog1p_cme::propensity,\n                                  nullptr,nullptr,{2});\n  PetscReal           t_final    = 60 * 3.0;\n  PetscReal           fsp_tol    = 1.0e-4;\n  arma::Mat<PetscInt> X0         = {0,0,0,0,0};\n  X0 = X0.t();\n  arma::Col<PetscReal> p0 = {1.0};\n\n\n  // Default options\n  PartitioningType     fsp_par_type        = PartitioningType::GRAPH;\n  PartitioningApproach fsp_repart_approach = PartitioningApproach::REPARTITION;\n  ODESolverType        fsp_odes_type       = CVODE;\n  PetscBool            output_marginal     = PETSC_FALSE;\n  PetscBool            fsp_log_events      = PETSC_FALSE;\n\n  ierr = ParseOptions(comm,fsp_par_type,fsp_repart_approach,output_marginal,fsp_log_events,fsp_odes_type);\n  CHKERRQ(ierr);\n\n  FspSolverMultiSinks fsp_solver(comm,fsp_par_type,fsp_odes_type);\n  fsp_solver.SetModel(hog1p_model);\n  fsp_solver.SetInitialDistribution(X0,p0);\n  fsp_solver.SetFromOptions();\n  DiscreteDistribution solution;\n\n  petsc_err = PetscLogStagePush(stages[0]);\n  CHKERRQ(petsc_err);\n\n  // Solve using adaptive default constraints\n  fsp_solver.SetInitialBounds(rhs_constr_hyperrec);\n  fsp_solver.SetExpansionFactors(expansion_factors_hyperrec);\n  fsp_solver.SetFromOptions();\n  solution = fsp_solver.Solve(t_final,fsp_tol,0);\n  std::shared_ptr<const StateSetConstrained>\n                 fss                   = std::static_pointer_cast<const StateSetConstrained>(fsp_solver.GetStateSet());\n  arma::Row<int> final_hyperrec_constr = fss->GetShapeBounds();\n  if (fsp_log_events)\n  {\n    output_performance(PETSC_COMM_WORLD,model_name,fsp_par_type,fsp_repart_approach,\n                       std::string(\"adaptive_default\"),fsp_odes_type,fsp_solver);\n  }\n  if (output_marginal)\n  {\n    output_marginals(PETSC_COMM_WORLD,model_name,fsp_par_type,fsp_repart_approach,\n                     std::string(\"adaptive_default\"),solution,final_hyperrec_constr);\n  }\n  fsp_solver.ClearState();\n  PetscPrintf(comm,\"\\n ================ \\n\");\n\n  petsc_err = PetscLogStagePop();\n  CHKERRQ(petsc_err);\n  petsc_err = PetscLogStagePush(stages[1]);\n  CHKERRQ(petsc_err);\n  // Solve using fixed default constraints\n  fsp_solver.SetInitialBounds(final_hyperrec_constr);\n  solution = fsp_solver.Solve(t_final,fsp_tol,0);\n  if (fsp_log_events)\n  {\n    output_performance(PETSC_COMM_WORLD,model_name,fsp_par_type,fsp_repart_approach,\n                       std::string(\"fixed_default\"),fsp_odes_type,fsp_solver);\n  }\n  if (output_marginal)\n  {\n    output_marginals(PETSC_COMM_WORLD,model_name,fsp_par_type,fsp_repart_approach,\n                     std::string(\"fixed_default\"),solution,final_hyperrec_constr);\n  }\n  fsp_solver.ClearState();\n  PetscPrintf(comm,\"\\n ================ \\n\");\n  return ierr;\n}\n\nint ParseOptions(MPI_Comm comm,\n                 PartitioningType &fsp_par_type,\n                 PartitioningApproach &fsp_repart_approach,\n                 PetscBool &output_marginal,\n                 PetscBool &fsp_log_events,\n                 ODESolverType &ode_solver)\n{\n  std::string part_type;\n  std::string part_approach;\n  part_type     = part2str(fsp_par_type);\n  part_approach = partapproach2str(fsp_repart_approach);\n\n  // Read options for fsp\n  char      opt[100];\n  PetscBool opt_set;\n  int       ierr;\n  ierr = PetscOptionsGetString(NULL,PETSC_NULL,\"-fsp_partitioning_type\",opt,100,&opt_set);\n  CHKERRQ(ierr);\n  if (opt_set)\n  {\n    fsp_par_type = str2part(std::string(opt));\n  }\n\n  ierr = PetscOptionsGetString(NULL,PETSC_NULL,\"-fsp_repart_approach\",opt,100,&opt_set);\n  CHKERRQ(ierr);\n  if (opt_set)\n  {\n    fsp_repart_approach = str2partapproach(std::string(opt));\n  }\n\n  ierr = PetscOptionsGetString(NULL,PETSC_NULL,\"-fsp_output_marginal\",opt,100,&opt_set);\n  CHKERRQ(ierr);\n  if (opt_set)\n  {\n    if (strcmp(opt,\"1\") == 0 || strcmp(opt,\"true\") == 0)\n    {\n      output_marginal = PETSC_TRUE;\n    }\n  }\n\n  ierr = PetscOptionsGetString(NULL,PETSC_NULL,\"-fsp_log_events\",opt,100,&opt_set);\n  CHKERRQ(ierr);\n  if (opt_set)\n  {\n    if (strcmp(opt,\"1\") == 0 || strcmp(opt,\"true\") == 0)\n    {\n      fsp_log_events = PETSC_TRUE;\n    }\n  }\n\n  ierr = PetscOptionsGetString(NULL,PETSC_NULL,\"-fsp_use_solver\",opt,100,&opt_set);\n  CHKERRQ(ierr);\n  if (opt_set)\n  {\n    if (strcmp(opt,\"krylov\") == 0)\n    {\n      ode_solver = KRYLOV;\n    } else\n    {\n      ode_solver = CVODE;\n    }\n  }\n\n  PetscPrintf(comm,\"Partitiniong option %s \\n\",part2str(fsp_par_type).c_str());\n  PetscPrintf(comm,\"Repartitoning option %s \\n\",partapproach2str(fsp_repart_approach).c_str());\n  return 0;\n}\n\nvoid output_performance(MPI_Comm comm,std::string &model_name,PartitioningType fsp_par_type,\n                        PartitioningApproach fsp_repart_approach,std::string constraint_type,\n                        ODESolverType ode_type,\n                        FspSolverMultiSinks &fsp_solver)\n{\n  int myRank,num_procs;\n  MPI_Comm_rank(comm,&myRank);\n  MPI_Comm_size(comm,&num_procs);\n\n  std::string ode;\n  if (ode_type == KRYLOV)\n  {\n    ode = \"krylov\";\n  } else\n  {\n    ode = \"cvode\";\n  }\n\n  std::string part_type;\n  std::string part_approach;\n  part_type     = part2str(fsp_par_type);\n  part_approach = partapproach2str(fsp_repart_approach);\n\n  // Output time breakdowns\n  FspSolverComponentTiming    sum_times, min_times, max_times;\n  sum_times = fsp_solver.ReduceComponentTiming(\"sum\");\n  min_times = fsp_solver.ReduceComponentTiming(\"min\");\n  max_times = fsp_solver.ReduceComponentTiming(\"max\");\n\n  if (myRank == 0)\n  {\n    struct stat buffer;\n    int fstat;\n\n    std::string   filename =\n                      model_name + \"_time_breakdown.dat\";\n\n    fstat = stat (filename.c_str(), &buffer);\n\n    std::ofstream file;\n    file.open(filename,std::ios_base::app);\n\n    if (fstat != 0){\n      file << \"ncpu,partitioner,fsp_shape,ode_solver,min_cput,max_cput,avg_cput,mat_gen_time,ode_time,state_expand_time,min_flops,max_flops,avg_flops \\n\";\n    }\n\n    file << num_procs << \",\"\n         << part_type << \",\"\n         << constraint_type << \",\"\n         << ode << \",\"\n         << min_times.TotalTime << \",\"\n         << max_times.TotalTime << \",\"\n         << sum_times.TotalTime/num_procs << \",\"\n         << sum_times.MatrixGenerationTime/num_procs << \",\"\n         << sum_times.ODESolveTime/num_procs << \",\"\n         << sum_times.StatePartitioningTime/num_procs  << \",\"\n         << min_times.TotalFlops << \",\"\n         << max_times.TotalFlops << \",\"\n         << sum_times.TotalFlops/num_procs << \"\\n\"\n        ;\n    file.close();\n  }\n\n  FiniteProblemSolverPerfInfo perf_info   = fsp_solver.GetSolverPerfInfo();\n\n  if (myRank == 0){\n    std::string filename =\n                    model_name + \"_perf_info_\" + std::to_string(num_procs) + \"_\" + part_type + \"_\" + part_approach + \"_\" +\n                        constraint_type + \".dat\";\n    std::ofstream file;\n    file.open(filename);\n    file << \"Model time, ODEs size, Average processor time (sec) \\n\";\n    for (auto i{0}; i < perf_info.n_step; ++i)\n    {\n      file << perf_info.model_time[i] << \",\" << perf_info.n_eqs[i] << \",\" << perf_info.cpu_time[i] << \"\\n\";\n    }\n    file.close();\n  }\n}\n\nvoid output_marginals(MPI_Comm comm,std::string model_name,PartitioningType fsp_par_type,\n                      PartitioningApproach fsp_repart_approach,std::string constraint_type,\n                      DiscreteDistribution &solution,arma::Row<int> constraints)\n{\n  int myRank,num_procs;\n  MPI_Comm_rank(comm,&myRank);\n  MPI_Comm_size(comm,&num_procs);\n\n  std::string part_type;\n  std::string part_approach;\n  part_type     = part2str(fsp_par_type);\n  part_approach = partapproach2str(fsp_repart_approach);\n\n  /* Compute the marginal distributions */\n  std::vector<arma::Col<PetscReal>> marginals(solution.states_.n_rows);\n  for (PetscInt                     i{0}; i < marginals.size(); ++i)\n  {\n    marginals[i] = Compute1DMarginal(solution,i);\n  }\n\n  MPI_Comm_rank(PETSC_COMM_WORLD,&myRank);\n  if (myRank == 0)\n  {\n    for (PetscInt i{0}; i < marginals.size(); ++i)\n    {\n      std::string filename =\n                      model_name + \"_marginal_\" + std::to_string(i) + \"_\" + std::to_string(num_procs) + \"_\" +\n                          part_type + \"_\" + part_approach + \"_\" + constraint_type + \".dat\";\n      marginals[i].save(filename,arma::raw_ascii);\n    }\n    std::string   filename =\n                      model_name + \"_constraint_bounds_\" + std::to_string(num_procs) + \"_\" + part_type + \"_\"\n                          + part_approach +\n                          \"_\" + constraint_type + \".dat\";\n    constraints.save(filename,arma::raw_ascii);\n  }\n}\n", "meta": {"hexsha": "93e11315d72268e5e4e474ef179d927dd19344cf", "size": 13455, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/hog1p.cpp", "max_stars_repo_name": "voduchuy/pacmensl", "max_stars_repo_head_hexsha": "d35adb165caef5c8fa992be6fda16e1bfb1dfd4a", "max_stars_repo_licenses": ["MIT"], "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/hog1p.cpp", "max_issues_repo_name": "voduchuy/pacmensl", "max_issues_repo_head_hexsha": "d35adb165caef5c8fa992be6fda16e1bfb1dfd4a", "max_issues_repo_licenses": ["MIT"], "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/hog1p.cpp", "max_forks_repo_name": "voduchuy/pacmensl", "max_forks_repo_head_hexsha": "d35adb165caef5c8fa992be6fda16e1bfb1dfd4a", "max_forks_repo_licenses": ["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.8973105134, "max_line_length": 154, "alphanum_fraction": 0.6348569305, "num_tokens": 3912, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397349, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4655347180193732}}
{"text": "\n#include <memory>\n#include <random>\n#include <vector>\n\n#include <Eigen/Core>\n#include <gtest/gtest.h>\n\n#include \"test/utils.hpp\"\n\n#include \"ldaplusplus/Parameters.hpp\"\n#include \"ldaplusplus/events/ProgressEvents.hpp\"\n#include \"ldaplusplus/em/FastOnlineSupervisedMStep.hpp\"\n#include \"ldaplusplus/em/FastSupervisedEStep.hpp\"\n\nusing namespace Eigen;\nusing namespace ldaplusplus;\n\n\n// T will be available as TypeParam in TYPED_TEST functions\ntemplate <typename T>\nclass TestOnlineMaximizationStep : public ParameterizedTest<T> {};\n\nTYPED_TEST_CASE(TestOnlineMaximizationStep, ForFloatAndDouble);\n\n\nTYPED_TEST(TestOnlineMaximizationStep, Maximization) {\n    // Build the corpus\n    std::mt19937 rng;\n    rng.seed(0);\n    MatrixXi X(100, 50);\n    VectorXi y(50);\n    std::uniform_int_distribution<> class_generator(0, 5);\n    std::exponential_distribution<> words_generator(0.1);\n    for (int d=0; d<50; d++) {\n        for (int w=0; w<100; w++) {\n            X(w, d) = static_cast<int>(words_generator(rng));\n        }\n        y(d) = class_generator(rng);\n    }\n\n    // Create the corpus and the model\n    auto corpus = std::make_shared<corpus::EigenClassificationCorpus>(X, y);\n    MatrixX<TypeParam> beta = MatrixX<TypeParam>::Random(10, 100);\n    beta.array() -= beta.minCoeff();\n    beta.array().rowwise() /= beta.array().colwise().sum();\n    auto model = std::make_shared<parameters::SupervisedModelParameters<TypeParam> >(\n        VectorX<TypeParam>::Constant(10, 0.1),\n        beta,\n        MatrixX<TypeParam>::Zero(10, 6)\n    );\n\n    em::FastSupervisedEStep<TypeParam> e_step(10, 1e-2, 10);\n    em::FastOnlineSupervisedMStep<TypeParam> m_step(\n        6,\n        1e-2,\n        25\n    );\n\n    std::vector<TypeParam> progress;\n    m_step.get_event_dispatcher()->add_listener(\n        [&progress](std::shared_ptr<events::Event> event) {\n            if (event->id() == \"MaximizationProgressEvent\") {\n                auto prog_ev = std::static_pointer_cast<events::MaximizationProgressEvent<TypeParam> >(event);\n                progress.push_back(prog_ev->likelihood());\n            }\n        }\n    );\n\n    size_t N = 4;\n    for (size_t n=0; n<N; n++) {\n        corpus->shuffle();\n\n        for (size_t i=0; i<corpus->size(); i++) {\n            m_step.doc_m_step(\n                corpus->at(i),\n                e_step.doc_e_step(\n                    corpus->at(i),\n                    model\n                ),\n                model\n            );\n        }\n\n        m_step.m_step(\n            model\n        );\n    }\n\n    ASSERT_EQ(progress.size(), 2*N);\n    for (size_t i=0; i<(2*N - 2); i+=2) {\n        EXPECT_LT(\n            progress[i] + progress[i+1],\n            progress[i+2] + progress[i+3]\n        );\n    }\n}\n", "meta": {"hexsha": "9c0f4176be8f8471aa4c5b4e7174d9b376d10d4f", "size": 2714, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_online_maximization_step.cpp", "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": "test/test_online_maximization_step.cpp", "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": "test/test_online_maximization_step.cpp", "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": 27.693877551, "max_line_length": 110, "alphanum_fraction": 0.5972733972, "num_tokens": 711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.465534712207002}}
{"text": "// #include <Eigen/Dense>\n// #include <Eigen/Eigen>\n// #include <Eigen/Geometry>\n// #include <Eigen/SVD>\n// #include <fstream>\n// #include <iostream>\n// #include <linux/input-event-codes.h>\n\n// #include \"ros/package.h\"\n// #include \"math.h\"\n// #include \"myData.h\"\n// #include \"myFunction.h\"\n// #include \"origarm_ros/Sensor.h\"\n// #include \"origarm_ros/States.h\"\n// #include \"origarm_ros/keynumber.h\"\n// #include \"origarm_ros/modenumber.h\"\n// #include \"origarm_ros/segnumber.h\"\n// #include \"origarm_ros/transdiff.h\"\n// #include \"ros/ros.h\"\n// #include <time.h>\n\n// #define DEBUG_DISPLAY 0\n// #define DUMMY_QUAT_USED 0\n\n// using namespace Eigen;\n// using Eigen::Matrix3f;\n// using Eigen::Matrix4f;\n// using Eigen::MatrixXf;\n// using Eigen::Quaternionf;\n// using Eigen::Vector3f;\n// using Eigen::VectorXf;\n\n// using namespace std;\n// static float rad2deg = 180.0f / M_PI;\n\n// // abl from sensor\n// static float alpha[SEGNUM];\n// static float beta[SEGNUM];\n// static float length[SEGNUM];\n\n// static float alphaDeg[SEGNUM];\n// static float betaDeg[SEGNUM];\n// static float lengthAbsMM[SEGNUM];\n\n// // abl from passive sensing\n// static float alpha_passive[SEGNUM];\n// static float beta_passive[SEGNUM];\n// static float length_passive[SEGNUM];\n// static float initLengthTrans[SEGNUM][ACTNUM];\n// static float initPressureTrans[SEGNUM][ACTNUM];\n// static float deadVolume = M_PI * 0.00125 * 0.00125 * 1.5;\n// static float lengthfrompressure[SEGNUM][ACTNUM];\n// static int transSegmentFlag[SEGNUM];\n\n\n// // local definition of pressure, distance, quaternion\n// static int16_t pressureActuator[SEGNUM][ACTNUM];\n// static int16_t lengthActuator[SEGNUM][ACTNUM];\n\n// static Quaternionf QuattInIMU[SEGNUM][ACTNUM];\n// static Quaternionf Quat0InIMU[SEGNUM][ACTNUM];\n\n// static Matrix3f Rtrans[SEGNUM][ACTNUM];\n// static Matrix3f R0InIMU[SEGNUM][ACTNUM], RtInIMU[SEGNUM][ACTNUM];\n// static Matrix3f R0InArm[SEGNUM][ACTNUM], RtInArm[SEGNUM][ACTNUM];\n// static Matrix3f dRInArm[SEGNUM][ACTNUM];\n// static Matrix3f ddRInArm[9][3][SEGNUM];\n\n// static float alphaCandidates[9][3][SEGNUM];\n// static float betaCandidates[9][3][SEGNUM];\n// static float alphaFromActuators[SEGNUM];\n// static float betaFromActuators[SEGNUM];\n\n// static Quaternionf quaternionPlates[SEGMENTNUM];\n// static Matrix3f R0PlateInArm[SEGNUM], RtPlateInArm[SEGNUM], dRPlateInArm[SEGNUM];\n// static float alphaFromPlates[SEGNUM];\n// static float betaFromPlates[SEGNUM];\n\n// /*Flag to control how the alpha is calculated*/\n// static const int calculate_alpha_using_pre_cur_flag = 1;\n// static const int calculate_alpha_using_cur_cur_flag = 0;\n// static const int calculate_alpha_using_cur_nex_flag = 1;\n\n// /*Path to save the IMU data at zero position*/\n\n// static string quat0DefaultFileName = \"default_data_imu0.txt\";\n// static string quattDummyFileName = \"imu_move_segment0.txt\";\n// static string quatSaveFileName = \"data_imu0.txt\";\n// static string quatReadFileName = \"data_imu0.txt\";\n// static string IMUDataPath = \"\";\n// static void InitFrames();\n\n// /*Indication of whether the IMU is working well*/\n// static int goodIMU[SEGNUM][ACTNUM] = {\n//     {0, 1, 0, 0, 1, 1},\n//     {0, 0, 1, 0, 1, 0},\n//     {1, 1, 1, 0, 1, 1},\n//     {1, 0, 0, 1, 0, 0},\n//     {1, 1, 0, 1, 0, 1},\n//     {0, 1, 0, 0, 1, 0}};\n\n// //stiffness of each actuator, unit: hPa/m\n// static float stiffnessMatrix[SEGNUM][ACTNUM] = {\n//     {3000, 3000, 3000, 3000, 3000, 3000},\n//     {3000, 3000, 3000, 3000, 3000, 3000},\n//     {3000, 3000, 3000, 3000, 3000, 3000},\n//     {3000, 3000, 3000, 3000, 3000, 3000},\n//     {3000, 3000, 3000, 3000, 3000, 3000},\n//     {3000, 3000, 3000, 3000, 3000, 3000}};\n\n// // mode indicating whether its normal or failure or with passive sensing\n// static int mode_;\n// // segnumber indicating sensors of which segment are shutdown\n// static int segn_;\n// // actuator transfering from actuation to sensing\n// static int trans_actuator;\n\n// static void InitFrames();\n\n// std::string getTimeString()\n// {\n//     time_t rawtime;\n//     struct tm *timeinfo;\n//     char buffer[100];\n\n//     time(&rawtime);\n//     timeinfo = localtime(&rawtime);\n\n//     strftime(buffer, 100, \"%G_%h_%d_%H_%M_%S\", timeinfo);\n//     std::string ret = buffer;\n//     return ret;\n// }\n\n// /**\n//  * @brief Save IMU data to file\n//  * \n//  * @param filePath The path where the data is to be stored\n//  */\n// static void saveQuatToFile(Quaternionf (&qua)[SEGNUM][ACTNUM], string filePath)\n// {\n//     ofstream data;\n//     data.open(filePath, ios::trunc); // ios::app\n//     // write imu data into yaml file/imu_data.txt\n//     cout << \"Saving current IMU data to\" + filePath << endl;\n//     for (int i = 0; i < SEGNUM; i++)\n//     {\n//         for (int j = 0; j < ACTNUM; j++)\n//         {\n//             data << qua[i][j].w() << \" \" << qua[i][j].x() << \" \" << qua[i][j].y()\n//                  << \" \" << qua[i][j].z() << endl;\n//             cout << qua[i][j].w() << \" \" << qua[i][j].x() << \" \" << qua[i][j].y()\n//                  << \" \" << qua[i][j].z() << endl;\n//         }\n//     }\n//     data.close();\n//     cout << \"IMU data Saved\" << endl;\n// }\n\n// /**\n//  * @brief read IMU data from file\n//  * \n//  * @param filePath The filepath where the original data is stored\n//  */\n// static void readQuatFromFile(string filePath, Quaternionf (&qua)[SEGNUM][ACTNUM])\n// {\n//     ifstream inFile;\n//     inFile.open(filePath, ios::in);\n//     if (inFile.fail())\n//     {\n//         inFile.close();\n//         cout << \"unable to open the IMU file in \" << filePath;\n//         filePath = IMUDataPath + quat0DefaultFileName;\n//         cout << \". The IMU default values will be used in \" << filePath << endl;\n//         inFile.open(filePath, ios::in);\n//     }\n\n//     cout << \"Reading IMU data from\" + filePath << endl;\n//     if (!inFile.eof())\n//     {\n//         for (int p = 0; p < SEGNUM; p++)\n//         {\n//             for (int q = 0; q < ACTNUM; q++)\n//             {\n//                 inFile >> qua[p][q].w() >> qua[p][q].x() >> qua[p][q].y() >> qua[p][q].z();\n//                 cout << qua[p][q].w() << \" \" << qua[p][q].x() << \" \" << qua[p][q].y()\n//                      << \" \" << qua[p][q].z() << endl;\n//             }\n//         }\n//     }\n//     cout << \"IMU data Read completed\" << endl;\n//     inFile.close();\n// }\n\n// /*set DEBUG_DISPLAY=1 to print all the matrices*/\n// static void displayAllMatrix()\n// {\n\n//     for (int i = 0; i < 6; i++)\n//     {\n//         for (int j = 0; j < ACTNUM; j++)\n//         {\n//             cout << \"Rtrans Seg \" << i << \" Act \" << j << endl;\n//             dispMatrix(Rtrans[i][j]);\n//         }\n//     }\n\n//     for (int i = 0; i < 6; i++)\n//     {\n//         for (int j = 0; j < ACTNUM; j++)\n//         {\n\n//             cout << \"R0InIMU Seg \" << i << \" Act \" << j << endl;\n//             cout << Quat0InIMU[i][j].w() << \" \" << Quat0InIMU[i][j].x() << \" \" << Quat0InIMU[i][j].y() << \" \" << Quat0InIMU[i][j].z() << endl;\n//             dispMatrix(R0InIMU[i][j]);\n//         }\n//     }\n\n//     for (int i = 0; i < 6; i++)\n//     {\n//         for (int j = 0; j < ACTNUM; j++)\n//         {\n//             cout << \"RtInIMU Seg \" << i << \" Act \" << j << endl;\n//             dispMatrix(RtInIMU[i][j]);\n//         }\n//     }\n\n//     for (int i = 0; i < 6; i++)\n//     {\n//         for (int j = 0; j < ACTNUM; j++)\n//         {\n//             cout << \"R0InArm Seg \" << i << \" Act \" << j << endl;\n//             dispMatrix(R0InArm[i][j]);\n//         }\n//     }\n\n//     for (int i = 0; i < 6; i++)\n//     {\n//         for (int j = 0; j < ACTNUM; j++)\n//         {\n//             cout << \"RtInArm Seg \" << i << \" Act \" << j << endl;\n//             dispMatrix(RtInArm[i][j]);\n//         }\n//     }\n\n//     for (int i = 0; i < 6; i++)\n//     {\n//         for (int j = 0; j < ACTNUM; j++)\n//         {\n//             cout << \"dRInArm Seg \" << i << \" Act \" << j << endl;\n//             dispMatrix(dRInArm[i][j]);\n//         }\n//     }\n\n//     for (int i = 0; i < 6; i++)\n//     {\n//         cout << \"alphaFromActuator Seg \" << i << endl;\n//         for (int j = 0; j < 3; j++)\n//         {\n//             for (int k = 0; k < 9; k++)\n//             {\n\n//                 cout << alphaCandidates[k][j][i] << \" \";\n//             }\n//             cout << endl;\n//         }\n//     }\n// }\n\n// class State_Estimator\n// {\n// public:\n//     State_Estimator()\n//     {\n//         sub_ = n_.subscribe(\"Sensor\", 300, &State_Estimator::callback, this);\n//         key_sub_ = n_.subscribe(\"key_number\", 1, &State_Estimator::keyCallback, this);\n//         mode_sub_ = n_.subscribe(\"modenumber\", 1, &State_Estimator::modeCallback, this); \n//         segn_sub_ = n_.subscribe(\"segnumber\", 1, &State_Estimator::segnumberCallback, this);\n//         trans_sub_ = n_.subscribe(\"transdiffer\", 1, &State_Estimator::transdiffCallback, this);       \n//         pub_ = n_.advertise<origarm_ros::States>(\"States\", 300);\n//     }\n\n//     void keyCallback(const origarm_ros::keynumber &key)\n//     {\n//         if (key.keycodePressed == KEY_C) // 'C' pressed\n//         {\n//             printf(\" KEY_C pressed!\\r\\n\");\n//             string path = IMUDataPath + quatSaveFileName;\n//             saveQuatToFile(QuattInIMU, path);\n//             InitFrames();\n//         }\n//         else if (key.keycodePressed == KEY_R) // 'r' pressed\n//         {\n//             printf(\" KEY_R pressed! Saving IMU data...\\r\\n\");\n//             std::string path = IMUDataPath + \"Rec_IMU_\" + getTimeString() + \".txt\";\n//             saveQuatToFile(QuattInIMU, path);\n//         }\n//     }\n\n//     void callback(const origarm_ros::Sensor &Sensor_)\n//     {\n//         for (int i = 0; i < SEGNUM; i++)\n//         {\n//             for (int j = 0; j < ACTNUM; j++)\n//             {\n//                 pressureActuator[i][j] = Sensor_.sensor_segment[i].sensor_actuator[j].pressure;\n//                 lengthActuator[i][j] = Sensor_.sensor_segment[i].sensor_actuator[j].distance;\n//                 QuattInIMU[i][j].w() = Sensor_.sensor_segment[i].sensor_actuator[j].pose.orientation.w; // double check\n//                 QuattInIMU[i][j].x() = Sensor_.sensor_segment[i].sensor_actuator[j].pose.orientation.x;\n//                 QuattInIMU[i][j].y() = Sensor_.sensor_segment[i].sensor_actuator[j].pose.orientation.y;\n//                 QuattInIMU[i][j].z() = Sensor_.sensor_segment[i].sensor_actuator[j].pose.orientation.z;\n//                 RtInIMU[i][j] = QuattInIMU[i][j];\n//             }\n//         }\n//     }\n\n//     void modeCallback(const origarm_ros::modenumber &mode_msg)\n//     {\n//         mode_ = mode_msg.modeNumber;\n//     }\n\n//     void segnumberCallback(const origarm_ros::segnumber &segn_msg)\n//     {\n//         segn_ = segn_msg.segmentNumber;\n//     }\n\n//     void transdiffCallback(const origarm_ros::transdiff &msg)\n//     {\n        \n//     }\n\n//     void pub()\n//     {\n//         if (mode_ < 2) // real ABL calculated from sensor\n//         {\n//             for (int i = 0; i < SEGNUM; i++)\n//             {\n//                 states_.ABL.segment[i].A = alpha[i];\n//                 states_.ABL.segment[i].B = beta[i];\n//                 states_.ABL.segment[i].L = length[i];\n//             }\n//         }\n//         else if (mode_ == 2)\n//         {\n//             for (int i = 0; i < SEGNUM; i++)\n//             {\n//                 if (i == segn_) // real ABL calculated from passive sensing\n//                 {\n//                     states_.ABL.segment[i].A = alpha_passive[i];\n//                     states_.ABL.segment[i].B = beta_passive[i];\n//                     states_.ABL.segment[i].L = length_passive[i];\n\n//                     printf(\"ABL of segment[%d] from passive sensing!\\n\", i);\n//                 }\n//                 else\n//                 {\n//                     states_.ABL.segment[i].A = alpha[i];\n//                     states_.ABL.segment[i].B = beta[i];\n//                     states_.ABL.segment[i].L = length[i];\n//                 }\n//             }\n//         }\n\n//         // real pose calculated from sensor\n//         // states_.pose.position.x = ;\n//         // states_.pose.position.y = ;\n//         // states_.pose.position.z = ;\n//         // states_.pose.orientation.w = ;\n//         // states_.pose.orientation.x = ;\n//         // states_.pose.orientation.y = ;\n//         // states_.pose.orientation.z = ;\n\n//         pub_.publish(states_);\n//     }\n\n// private:\n//     ros::NodeHandle n_;\n//     ros::Subscriber sub_;\n//     ros::Subscriber key_sub_;\n//     ros::Subscriber mode_sub_;\n//     ros::Subscriber segn_sub_;\n//     ros::Subscriber trans_sub_;\n//     ros::Publisher pub_;\n\n//     origarm_ros::States states_;\n// };\n\n// /**/\n// /**\n//  * @brief Choose good actuators. More complex rules could be added\n//  * \n//  * @param p the segment number\n//  * @param q the actautor number on the segment\n//  * @return 0: Bad actuators\n//  *         1: Good actuators\n//  */\n// static int goodActuator(int p, int q)\n// {\n//     int ret = 0;\n//     if (p >= 0 && p < SEGNUM && q >= 0 && q < ACTNUM)\n//         if (goodIMU[p][q])\n//             ret = 1;\n//     return ret;\n// }\n\n// /**\n//  * @brief Init all frames\n//  * 1. init the IMU body frame at time 0 in the ARM Base, based on the physical location of the actuators in the arm\n//  * 2. Read the IMU body frame at time 0 in the IMU Base\n//  * 3. Calculate the transformation matrix of IMU Base in the ARM Base\n//  * 4. define the plate pose at time 0 in the Arm base, which are all identities.\n//  */\n// void InitFrames()\n// {\n//     /*set the IMU body frame at time 0 in the ARM Base*/\n\n//     for (int i = 0; i < SEGNUM; i++)\n//     {\n//         R0InArm[i][0] = myRotz(-M_PI / 2);\n//         R0InArm[i][2] = myRotz(-M_PI / 2 + 2 * M_PI / 3);\n//         R0InArm[i][4] = myRotz(-M_PI / 2 + 4 * M_PI / 3);\n\n//         R0InArm[i][1] = myRotz(-M_PI / 6) * myRoty(M_PI);\n//         R0InArm[i][3] = myRotz(-M_PI / 6 + 2 * M_PI / 3) * myRoty(M_PI);\n//         R0InArm[i][5] = myRotz(-M_PI / 6 + 4 * M_PI / 3) * myRoty(M_PI);\n//     }\n\n//     /*Read the IMU body frame at time 0 in the IMU Base*/\n//     string path = IMUDataPath + quatReadFileName;\n//     readQuatFromFile(path, Quat0InIMU);\n//     for (int i = 0; i < SEGNUM; i++)\n//     {\n//         for (int j = 0; j < ACTNUM; j++)\n//         {\n//             R0InIMU[i][j] = Quat0InIMU[i][j];\n//         }\n//     }\n\n// #if DUMMY_QUAT_USED == 1\n//     /*****************Debug Only.  Uncomment in real application***********************/\n//     /*Read dummy IMU body frame at time t in the IMU Base*/\n//     readQuatFromFile(IMUDataPath + quattDummyFileName, QuattInIMU);\n//     for (int i = 0; i < SEGNUM; i++)\n//     {\n//         for (int j = 0; j < ACTNUM; j++)\n//         {\n//             RtInIMU[i][j] = QuattInIMU[i][j];\n//         }\n//     }\n// #endif\n\n//     /*Calculate the transformation matrix of IMU Base in the ARM Base*/\n//     for (int i = 0; i < SEGNUM; i++)\n//     {\n//         for (int j = 0; j < ACTNUM; j++)\n//         {\n//             Rtrans[i][j] = R0InArm[i][j] * R0InIMU[i][j].transpose();\n//         }\n//     }\n\n//     /*define the plate pose at time 0 in the Arm base*/\n//     for (int i = 0; i < SEGNUM; i++)\n//     {\n//         R0PlateInArm[i] = Matrix3f::Identity();\n//     }\n// }\n\n// /*get the IMU body frame at time t in the arm base*/\n// void getRtInArm()\n// {\n//     for (int i = 0; i < SEGNUM; i++)\n//     {\n//         for (int j = 0; j < ACTNUM; j++)\n//         {\n//             RtInArm[i][j] = Rtrans[i][j] * RtInIMU[i][j];\n//         }\n//     }\n// }\n\n// /**\n//  * @brief get the IMU body frame change at time t relative to time 0,  in the Arm Base\n//  * \n//  */\n// void getdRtInArm()\n// {\n//     for (int i = 0; i < SEGNUM; i++)\n//     {\n//         for (int j = 0; j < ACTNUM; j++)\n//         {\n//             dRInArm[i][j] = RtInArm[i][j] * R0InArm[i][j].transpose();\n//         }\n//     }\n// }\n\n// /**\n//  * @brief get ddRtInArm using different actautor pairs. \n//  * There are 3*9 pairs for each segment, that is\n//  * 1. Using Act(1 3 5) in previous segment and Act(2 4 6) in current segment\n//  * 2. Using Act(0 2 4) and Act(1 3 5) in current segment\n//  * 3. Using Act(0 2 4) in current segment and Act(0 2 4) in next segment\n//  * Only Elegible and good Actuators are considered during the process.\n//  */\n// void getddRtInArm()\n// {\n//     int p1 = 0; //segment number of the first chosen actuator\n//     int p2 = 0; //segment number of the second chosen actuator\n//     int k = 0;  //0~8, representing all the 9 possbile actuator combinations in a given flag\n\n//     /*For every segment*/\n//     for (int i = 0; i < SEGNUM; i++)\n//     {\n\n//         /*Using Act(1 3 5) in previous segment and Act(2 4 6) in current segment*/\n//         if (calculate_alpha_using_pre_cur_flag)\n//         {\n//             k = 0;\n//             p1 = i - 1;\n//             p2 = i;\n//             for (int q1 = 1; q1 < ACTNUM; q1 += 2)\n//             {\n//                 for (int q2 = 1; q2 < ACTNUM; q2 += 2)\n//                 {\n//                     /*only Elegible and good Actuator*/\n//                     if (goodActuator(p1, q1) && goodActuator(p2, q2))\n//                         ddRInArm[k++][0][i] = dRInArm[p1][q1].transpose() * dRInArm[p2][q2];\n//                 }\n//             }\n//         }\n\n//         /*Using Act(0 2 4) and Act(1 3 5) in current segment*/\n//         if (calculate_alpha_using_cur_cur_flag)\n//         {\n//             k = 0;\n//             p1 = i;\n//             p2 = i;\n//             for (int q1 = 0; q1 < ACTNUM; q1 += 2)\n//             {\n//                 for (int q2 = 1; q2 < ACTNUM; q2 += 2)\n//                 {\n//                     /*only Elegible and good Actuator*/\n//                     if (goodActuator(p1, q1) && goodActuator(p2, q2))\n//                         ddRInArm[k++][1][i] = dRInArm[p1][q1].transpose() * dRInArm[p2][q2];\n//                 }\n//             }\n//         }\n//         /*Using Act(0 2 4) in current segment and Act(0 2 4) in next segment*/\n//         if (calculate_alpha_using_cur_nex_flag)\n//         {\n//             k = 0;\n//             p1 = i;\n//             p2 = i + 1;\n//             for (int q1 = 0; q1 < ACTNUM; q1 += 2)\n//             {\n//                 for (int q2 = 0; q2 < ACTNUM; q2 += 2)\n//                 {\n//                     /*only Elegible and good Actuator*/\n//                     if (goodActuator(p1, q1) && goodActuator(p2, q2))\n//                         ddRInArm[k++][2][i] = dRInArm[p1][q1].transpose() * dRInArm[p2][q2];\n//                 }\n//             }\n//         }\n//     }\n// }\n\n// /**\n//  * @brief Get the Alpha From R object\n//  * \n//  * @param R \n//  * @return float \n//  */\n// float getAlphaFromR(Matrix3f &R)\n// {\n//     float val = -1000;\n//     float alphaCandi = 0;\n//     if (!R.isZero())\n//     {\n//         val = CONSTRAIN(R(2, 2), -1, 1);\n//         alphaCandi = acos(val);\n//     }\n//     else\n//     {\n//         alphaCandi = -1000;\n//     }\n//     return alphaCandi;\n// }\n// /**\n//  * @brief Get the Beta From a rotation matrix R\n//  * \n//  * @param R The rotation matrix\n//  * @return float beta\n//  */\n// float getBetaFromR(Matrix3f &R)\n// {\n//     float alphaCandi = 0;\n//     float betaCandi = 0;\n//     alphaCandi = getAlphaFromR(R);\n//     if (alphaCandi > 0.05f || alphaCandi < -0.05f)\n//         betaCandi = atan2(R(1, 2) / sin(alphaCandi), R(0, 2) / sin(alphaCandi));\n//     else\n//     {\n//         betaCandi = 0;\n//     }\n//     return betaCandi;\n// }\n// /**\n//  * @brief Get the Alpha Beta From Actuators. \n//  * For every segment, there are 3*9 = 27 candidate transformation matrix ddR for calculating alpha and beta. \n//  * The valid values are chosen and averaged to get the final value\n//  * \n//  */\n// void getAlphaBetaFromActuators()\n// {\n//     float sumAlpha = 0;\n//     int countsAlpha = 0;\n//     float sumBeta = 0;\n//     float countsBeta = 0;\n//     int average_flag[3] = {calculate_alpha_using_pre_cur_flag, calculate_alpha_using_cur_cur_flag, calculate_alpha_using_cur_nex_flag};\n\n//     for (int i = 0; i < SEGNUM; i++)\n//     {\n//         sumAlpha = 0;\n//         countsAlpha = 0;\n//         sumBeta = 0;\n//         countsAlpha = 0;\n//         for (int j = 0; j < 3; j++)\n//         {\n//             if (average_flag[j])\n//             {\n//                 for (int k = 0; k < 9; k++)\n//                 {\n//                     alphaCandidates[k][j][i] = getAlphaFromR(ddRInArm[k][j][i]);\n//                     betaCandidates[k][j][i] = getBetaFromR(ddRInArm[k][j][i]);\n//                     /*unuseful data are set to be -1000*/\n//                     if (alphaCandidates[k][j][i] > -10)\n//                     {\n//                         sumAlpha += alphaCandidates[k][j][i];\n//                         countsAlpha++;\n//                         sumBeta += betaCandidates[k][j][i];\n//                         countsBeta++;\n//                     }\n//                 }\n//             }\n//         }\n//         alphaFromActuators[i] = sumAlpha / countsAlpha;\n//         betaFromActuators[i] = sumBeta / countsBeta;\n//     }\n// }\n\n// /**\n//  * @brief Average quaternions in an array Quats[], starting from index, with a total number of startnum\n//  * \n//  * @param Quats The quaternion array to be averaged\n//  * @param startnum The starting index\n//  * @param num Number of total quaternion to be averaged\n//  * @return Quaternionf Averaged quaternion\n//  */\n// Quaternionf averageQuaternions(Quaternionf *Quats, int startnum, int num)\n// {\n//     Quaternionf avQuat;\n//     Eigen::MatrixXf Qori(4, num);\n//     Eigen::Matrix4f Qmat;\n//     Eigen::Vector4f QmatEigenValue;\n//     Eigen::Matrix4f QmatEigenVector;\n//     SelfAdjointEigenSolver<Matrix4f> es(Qmat);\n//     float coeff = 1.0f / num;\n//     for (int i = 0; i < num; i++)\n//     {\n//         Qori(0, i) = Quats[startnum + i].w() * coeff;\n//         Qori(1, i) = Quats[startnum + i].x() * coeff;\n//         Qori(2, i) = Quats[startnum + i].y() * coeff;\n//         Qori(3, i) = Quats[startnum + i].z() * coeff;\n//     }\n//     Qmat = Qori * Qori.transpose();\n//     QmatEigenValue = es.eigenvalues();\n//     QmatEigenVector = es.eigenvectors();\n//     avQuat.w() = QmatEigenVector(0, 3);\n//     avQuat.x() = QmatEigenVector(1, 3);\n//     avQuat.y() = QmatEigenVector(2, 3);\n//     avQuat.z() = QmatEigenVector(3, 3);\n//     return avQuat;\n// }\n\n// /**\n//  * @brief Get the Plates rotation matrix R in the Arm base\n//  * The plates quaternions are determined by averaging the quaternions of the actuators on it. Physically these actuator share a common quaternion\n//  * The choice of Actuators can choose the three actuators on current segment or the next segment.\n//  */\n// void getPlatesR()\n// {\n//     int use_cur_seg = 1;\n//     int use_nex_seg = 1;\n//     Quaternionf quaternionCandi[6];\n\n//     int startnum = 0;\n//     int num = 0;\n//     for (int i = 0; i < SEGNUM; i++)\n//     {\n\n//         /*The last plate could only use current segment actuators*/\n//         if (use_cur_seg == 1 || i == SEGNUM - 1)\n//         {\n//             quaternionCandi[0] = dRInArm[i][1];\n//             quaternionCandi[1] = dRInArm[i][3];\n//             quaternionCandi[2] = dRInArm[i][5];\n//             startnum = 0;\n//             num = 3;\n//         }\n//         if (use_nex_seg == 1 && (i != SEGNUM - 1))\n//         {\n//             quaternionCandi[3] = dRInArm[i + 1][0];\n//             quaternionCandi[4] = dRInArm[i + 1][2];\n//             quaternionCandi[5] = dRInArm[i + 1][4];\n//             startnum += 3;\n//             num += 3;\n//         }\n//         quaternionPlates[i] = averageQuaternions(quaternionCandi, startnum, num);\n//         RtPlateInArm[i] = quaternionPlates[i];\n//     }\n// }\n\n// /**\n//  * @brief Get the Alpha Beta From the relative rotation matrix between plates\n//  * \n//  */\n// void getAlphaBetaFromPlates()\n// {\n//     Matrix3f dRplate;\n//     for (int i = 0; i < SEGNUM; i++)\n//     {\n//         if (i == 0)\n//             dRplate = RtPlateInArm[i];\n//         else\n//             dRplate = RtPlateInArm[i - 1].transpose() * RtPlateInArm[i];\n//         alphaFromPlates[i] = getAlphaFromR(dRplate);\n//         betaFromPlates[i] = getBetaFromR(dRplate);\n//     }\n// }\n\n// /**\n//  * @brief Get the Alpha of all the segments\n//  * \n//  */\n// static void getAlpha(float (&alphaCandi)[SEGNUM])\n// {\n//     for (int i = 0; i < SEGNUM; i++)\n//     {\n//         alpha[i] = alphaCandi[i];\n//         alphaDeg[i] = alpha[i] * rad2deg;\n//     }\n// }\n\n// /**\n//  * @brief Get the Beta af all the segments\n//  * \n//  */\n// static void getBeta(float (&betaCandi)[SEGNUM])\n// {\n//     for (int i = 0; i < SEGNUM; i++)\n//     {\n//         beta[i] = betaCandi[i];\n//         betaDeg[i] = betaCandi[i] * rad2deg;\n//     }\n// }\n\n// /**\n//  * @brief Get the Length of all the segments\n//  * \n//  */\n// static void getLength()\n// {\n//     float lengthSum = 0;\n//     for (int i = 0; i < SEGNUM; i++)\n//     {\n//         if (i > 5)\n//         {\n//             lengthAbsMM[i] = g_length0MM;\n//             length[i] = g_length0;\n//         }\n//         else\n//         {\n//             lengthSum = 0;\n//             for (int j = 0; j < ACTNUM; j++)\n//             {\n//                 lengthSum += lengthActuator[i][j];\n//             }\n\n//             lengthAbsMM[i] = lengthSum / ACTNUM + g_length0MM;\n//             length[i] = lengthAbsMM[i] / 1000.0f;\n//         }\n//     }\n// }\n\n// /**\n//  * @brief Estmate the alpha, beta, length from IMU data for all the segments\n//  * \n//  */\n// void estimateABL()\n// {\n//     /*Calculation of useful matrices*/\n//     getRtInArm();\n//     getdRtInArm();\n//     getddRtInArm();\n\n//     /*Two methods to obtain alpha and beta*/\n//     getAlphaBetaFromActuators();\n//     getAlphaBetaFromPlates();\n\n//     /*Choose a result for alpha and beta*/\n//     getAlpha(alphaFromActuators);\n//     getBeta(betaFromActuators);\n\n//     /*estimate length*/\n//     getLength();\n// }\n\n// /**\n//  * @brief Estimate the alpha, beta, length from laser sensor\n//  * \n//  */\n// void test()\n// {\n//     for (int i = 0; i < SEGNUM; i++)\n//     {\n//         lengthActuator[i][0] = 51 - g_length0MM;\n//         lengthActuator[i][1] = 6 - g_length0MM;\n//         lengthActuator[i][2] = 10 - g_length0MM;\n//         lengthActuator[i][3] = 59 - g_length0MM;\n//         lengthActuator[i][4] = 103 - g_length0MM;\n//         lengthActuator[i][5] = 99 - g_length0MM;\n//     }\n// }\n\n// static void getArcLength(float (&rotangle)[SEGNUM])\n// {\n//     float lengthSum, Length1, Length2, lambda, arcLength;\n//     for (int i = 0; i < SEGNUM; i++)\n//     {\n//         if (i > 5)\n//         {\n//             lengthAbsMM[i] = g_length0MM;\n//             length[i] = g_length0;\n//         }\n//         else\n//         {\n//             lengthSum = 0;\n//             for (int j = 0; j < ACTNUM; j++)\n//             {\n//                 lengthSum += lengthActuator[i][j];\n//             }\n\n//             if (rotangle[i] == 0)\n//             {\n//                 lengthAbsMM[i] = lengthSum / ACTNUM + g_length0MM;\n//                 length[i] = lengthAbsMM[i] / 1000.0f;\n//             }\n//             else\n//             {\n//                 Length1 = (lengthActuator[i][0] + lengthActuator[i][2] + lengthActuator[i][4]) / 3;\n//                 Length2 = (lengthActuator[i][1] + lengthActuator[i][3] + lengthActuator[i][5]) / 3;\n//                 lambda = (Length1 - Length2 * cos(rotangle[i])) / (1 - cos(rotangle[i]) * cos(rotangle[i]));\n//                 arcLength = (lambda * cos(rotangle[i]) * rotangle[i]) / (2 * sin(rotangle[i] / 2));\n//                 lengthAbsMM[i] = arcLength + g_length0MM;\n//                 length[i] = arcLength / 1000.0f;\n//             }\n//         }\n//     }\n// }\n\n// Eigen::Vector3f getNormalVectfromCovMatrix(Eigen::Matrix3f &CovM)\n// {\n//     Matrix3f U, S, V;\n//     Vector3f normalV;\n//     JacobiSVD<Eigen::Matrix3f> svd(CovM, ComputeFullU | ComputeFullV);\n\n//     static Eigen::IOFormat dispMatFormat(4, 0, \", \", \"\\n\", \"[\", \"]\");\n//     static std::string separator = \"\\n---------------------------------------\\n\";\n\n//     U = svd.matrixU();\n//     V = svd.matrixV();\n\n//     // normal direction of plate should point towards +z\n//     if (V(2, 2) < 0)\n//     {\n//         normalV(0, 0) = -V(0, 2);\n//         normalV(1, 0) = -V(1, 2);\n//         normalV(2, 0) = -V(2, 2);\n//     }\n//     else\n//     {\n//         normalV(0, 0) = V(0, 2);\n//         normalV(1, 0) = V(1, 2);\n//         normalV(2, 0) = V(2, 2);\n//     }\n\n//     return normalV;\n// }\n\n// Eigen::Matrix3f getdRplatefromNormalVect(Eigen::Vector3f &Vn)\n// {\n//     Vector3f V0, crossV;\n//     Matrix3f dRplate;\n//     float rotangle;\n\n//     V0 << 0,\n//         0,\n//         1;\n\n//     if ((Vn - V0).isMuchSmallerThan(1e-3))\n//     {\n//         crossV = V0;\n//     }\n//     else\n//     {\n//         crossV = V0.cross(Vn);\n//     }\n\n//     rotangle = acos(Vn.dot(V0));\n//     dRplate = AngleAxisf(rotangle, crossV);\n\n//     return dRplate;\n// }\n\n// void getAlphaBetafromLaser()\n// {\n//     MatrixXf A(ACTNUM, 3);\n//     Matrix3f Q, dRplate;\n//     Vector3f NormalVect;\n//     float Zc[SEGNUM], z[SEGNUM][ACTNUM];\n//     float Zsum;\n\n//     NormalVect << 0,\n//         0,\n//         1;\n\n//     // compute middle point\n//     for (int i = 0; i < SEGNUM; i++)\n//     {\n//         if (i > 5)\n//         {\n//             alphaFromPlates[i] = 0;\n//             betaFromPlates[i] = 0;\n//         }\n//         else\n//         {\n//             Zsum = 0;\n//             for (int j = 0; j < ACTNUM; j++)\n//             {\n//                 Zsum += lengthActuator[i][j];\n//                 z[i][j] = lengthActuator[i][j];\n//             }\n\n//             Zc[i] = Zsum / ACTNUM;\n\n//             // printf(\"Xc[%d]: %f, Yc[%d]: %f, Zc[%d]: %f\\n\",i, Xc[i], i, Yc[i], i, Zc[i]);\n\n//             A(0, 0) = cos(0 * M_PI / 3) * radRmm;\n//             A(0, 1) = sin(0 * M_PI / 3) * radRmm;\n//             A(0, 2) = z[i][0] - Zc[i];\n//             A(1, 0) = cos(1 * M_PI / 3) * radRmm;\n//             A(1, 1) = sin(1 * M_PI / 3) * radRmm;\n//             A(1, 2) = z[i][1] - Zc[i];\n//             A(2, 0) = cos(2 * M_PI / 3) * radRmm;\n//             A(2, 1) = sin(2 * M_PI / 3) * radRmm;\n//             A(2, 2) = z[i][2] - Zc[i];\n//             A(3, 0) = cos(3 * M_PI / 3) * radRmm;\n//             A(3, 1) = sin(3 * M_PI / 3) * radRmm;\n//             A(3, 2) = z[i][3] - Zc[i];\n//             A(4, 0) = cos(4 * M_PI / 3) * radRmm;\n//             A(4, 1) = sin(4 * M_PI / 3) * radRmm;\n//             A(4, 2) = z[i][4] - Zc[i];\n//             A(5, 0) = cos(5 * M_PI / 3) * radRmm;\n//             A(5, 1) = sin(5 * M_PI / 3) * radRmm;\n//             A(5, 2) = z[i][5] - Zc[i];\n\n//             // covariance matrix Q, to minimize |QX|, where X is normal vector of plate\n//             Q = (A.transpose() * A) / ACTNUM;\n\n//             NormalVect = getNormalVectfromCovMatrix(Q);\n//             dRplate = getdRplatefromNormalVect(NormalVect);\n//             alphaFromPlates[i] = getAlphaFromR(dRplate);\n//             betaFromPlates[i] = getBetaFromR(dRplate);\n\n//             // printf(\"alphaFromLength[%d]: %f\\n\", i, alphaFromPlates[i]);\n//             // printf(\"betaFromLength[%d]: %f\\n\", i, betaFromPlates[i]);\n//         }\n//     }\n// }\n\n// void getABLfromLaser()\n// {\n//     /*estimate alpha & beta*/\n//     getAlphaBetafromLaser();\n//     getAlpha(alphaFromPlates);\n//     getBeta(betaFromPlates);\n\n//     /*estimate length*/\n//     getLength();\n//     // getArcLength(alphaFromPlates);\n// }\n\n\n\n\n\n\n\n// void getLengthFromPressure(int segn,int actn){\n//     //P1*(A*L1 + deadV) =P2*(A*L2 + deadV)\n//     //L2=P1/P2*L1 + (P1/P2-1)*(d/A)\n//     float temp1=initPressureTrans[segn][actn]/pressureActuator[segn][actn];\n//     float temp2=deadVolume/g_actuator_effectiveArea;\n//     lengthfrompressure[segn][actn]=temp1*initLengthTrans[segn][actn]+(temp1-1)*temp2;\n// }\n\n\n// void transCommandCallback(){\n//     if(trans_mode==2){\n//         transSegmentFlag[trans_segment]=1;\n//         for(int i=0;i<ACTNUM;i++){\n//             initLengthTrans[trans_segment][i]=lengthActuator[trans_segment][i];\n//             initPressureTrans[trans_segment][i]=pressureActuator[trans_segment][i];\n//         }\n        \n//     }\n//     else{\n//         transSegmentFlag[trans_segment]=0;\n//     }\n// }\n// /**\n//  * @brief Estimate the alpha, beta, length from pressure data for certain segments\n//  * \n//  */\n// static void passiveSensingOneSeg(int transSeg)\n// {\n//     Matrix3f A, Q, dRplate;\n//     Vector3f Vn;\n//     float lengthsum, lengthc[SEGNUM]\n\n//     alpha_passive[transSeg] = 0;\n//     beta_passive[transSeg] = 0;\n//     length_passive[transSeg] = g_length0;\n\n//     // close [0], [2], [4] actuator for passive sensing\n//     lengthfrompressure[transSeg][0] = getLengthFromPressure(transSeg,0);\n//     lengthfrompressure[transSeg][2] = getLengthFromPressure(transSeg,2);\n//     lengthfrompressure[transSeg][4] = getLengthFromPressure(transSeg,4);\n\n//     // for testing\n//     // lengthfrompressure[transSeg][0] = lengthActuator[transSeg][0];\n//     // lengthfrompressure[transSeg][2] = lengthActuator[transSeg][2];\n//     // lengthfrompressure[transSeg][4] = lengthActuator[transSeg][4];\n//     lengthsum = lengthfrompressure[transSeg][0] + lengthfrompressure[transSeg][2] + lengthfrompressure[transSeg][4];\n\n//     lengthc[transSeg] = lengthsum / 3;\n//     A(0, 0) = cos(0 * M_PI / 3) * radRmm;\n//     A(0, 1) = sin(0 * M_PI / 3) * radRmm;\n//     A(0, 2) = lengthfrompressure[transSeg][0] - lengthc[transSeg];\n//     A(1, 0) = cos(2 * M_PI / 3) * radRmm;\n//     A(1, 1) = sin(2 * M_PI / 3) * radRmm;\n//     A(1, 2) = lengthfrompressure[transSeg][2] - lengthc[transSeg];\n//     A(2, 0) = cos(4 * M_PI / 3) * radRmm;\n//     A(2, 1) = sin(4 * M_PI / 3) * radRmm;\n//     A(2, 2) = lengthfrompressure[transSeg][4] - lengthc[transSeg];\n//     Q = (A.transpose() * A) / 3;\n//     Vn = getNormalVectfromCovMatrix(Q);\n//     dRplate = getdRplatefromNormalVect(Vn);\n//     alpha_passive[transSeg] = getAlphaFromR(dRplate);\n//     beta_passive[transSeg] = getBetaFromR(dRplate);\n//     length_passive[transSeg] = lengthc[transSeg] + g_length0; //unit: m\n\n//     // printf(\"alpha_passive[%d]: %f\\n\", transSeg, alpha_passive[transSeg]);\n//     // printf(\"beta_passive[%d]:  %f\\n\", transSeg, beta_passive[transSeg]);\n//     // printf(\"length_passive[%d]: %f\\n\", transSeg, length_passive[transSeg]);\n// }\n\n// void transSegmentsPassiveSensing(){\n//     for(int i=0;i<SEGNUM;i++){\n//         if(i<6){\n//             if(transSegmentFlag[i]){\n//                 passiveSensingOneSeg(i);\n//                 states_.ABL.segment[i].A = alpha_passive[i];\n//                 states_.ABL.segment[i].B = beta_passive[i];\n//                 states_.ABL.segment[i].L = length_passive[i];\n//             }\n//         }\n//     }\n// }\n\nint main(int argc, char **argv)\n{\n//     ros::init(argc, argv, \"State_Estimator_updated\");\n\n//     IMUDataPath = ros::package::getPath(\"origarm_ros\") + \"/predefined_param/\";\n//     cout << \"IMUDataPath:\" << IMUDataPath << endl;\n\n//     InitFrames();\n\n//     State_Estimator stateEstimator;\n\n//     ros::AsyncSpinner s(4);\n\n//     s.start();\n\n//     ros::Rate loop_rate(100);\n\n//     ROS_INFO(\"Ready for State_Estimator_Node\");\n\n//     int printFre = 0;\n//     while (ros::ok())\n//     {\n//         // estimateABL();\n\n//         // test(); // given sensor information for testing\n//         getABLfromLaser();\n        \n//         transSegmentsPassiveSensing();\n\n\n//         stateEstimator.pub();\n\n//         if (printFre++ > 2)\n//         {\n//             // printf(\"A[0]:%d, [1]:%d, [2]:%d, [3]:%d, [4]:%d, [5]:%d  | B[0]:%d, [1]:%d, [2]:%d, [3]:%d, [4]:%d, [5]:%d  |  L[0]:%d, [1]:%d, [2]:%d, [3]:%d, [4]:%d, [5]:%d\\n\",\n//             //        (int)(alphaDeg[0]),\n//             //        (int)(alphaDeg[1]),\n//             //        (int)(alphaDeg[2]),\n//             //        (int)(alphaDeg[3]),\n//             //        (int)(alphaDeg[4]),\n//             //        (int)(alphaDeg[5]),\n//             //        (int)(betaDeg[0]),\n//             //        (int)(betaDeg[1]),\n//             //        (int)(betaDeg[2]),\n//             //        (int)(betaDeg[3]),\n//             //        (int)(betaDeg[4]),\n//             //        (int)(betaDeg[5]),\n//             //        (int)(lengthAbsMM[0]),\n//             //        (int)(lengthAbsMM[1]),\n//             //        (int)(lengthAbsMM[2]),\n//             //        (int)(lengthAbsMM[3]),\n//             //        (int)(lengthAbsMM[4]),\n//             //        (int)(lengthAbsMM[5]));\n\n//             printf(\"A[0]:%.3f, [1]:%.3f, [2]:%.3f, [3]:%.3f, [4]:%.3f, [5]:%.3f  | B[0]:%.3f, [1]:%.3f, [2]:%.3f, [3]:%.3f, [4]:%.3f, [5]:%.3f  |  L[0]:%.3f, [1]:%.3f, [2]:%.3f, [3]:%.3f, [4]:%.3f, [5]:%.3f\\n\",\n//                    (alpha[0]),\n//                    (alpha[1]),\n//                    (alpha[2]),\n//                    (alpha[3]),\n//                    (alpha[4]),\n//                    (alpha[5]),\n//                    (beta[0]),\n//                    (beta[1]),\n//                    (beta[2]),\n//                    (beta[3]),\n//                    (beta[4]),\n//                    (beta[5]),\n//                    (length[0]),\n//                    (length[1]),\n//                    (length[2]),\n//                    (length[3]),\n//                    (length[4]),\n//                    (length[5]));\n//             printFre = 0;\n//         }\n\n// #if DEBUG_DISPLAY == 1\n//         displayAllMatrix();\n// #endif\n//         ros::spinOnce();\n//         loop_rate.sleep();\n//     }\n\n    return 0;\n}\n", "meta": {"hexsha": "15a16a1dfd738e6ebeaa85396e0bc83950dcbd33", "size": 37497, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/State_Estimator_updated.cpp", "max_stars_repo_name": "XiaojiaoChen/origarm_ros", "max_stars_repo_head_hexsha": "59d1b05e9c13c50a9281ab2a670621f3f04d8cc1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-04-30T10:05:38.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-30T10:05:38.000Z", "max_issues_repo_path": "src/State_Estimator_updated.cpp", "max_issues_repo_name": "XiaojiaoChen/origarm_ros", "max_issues_repo_head_hexsha": "59d1b05e9c13c50a9281ab2a670621f3f04d8cc1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-05-01T08:16:06.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-01T08:16:06.000Z", "max_forks_repo_path": "src/State_Estimator_updated.cpp", "max_forks_repo_name": "XiaojiaoChen/softArmROS", "max_forks_repo_head_hexsha": "59d1b05e9c13c50a9281ab2a670621f3f04d8cc1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-04-30T06:48:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-01T04:27:26.000Z", "avg_line_length": 31.9667519182, "max_line_length": 213, "alphanum_fraction": 0.4890257887, "num_tokens": 11804, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4655347063946307}}
{"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 sample_graph.hpp\n * @brief\n * @author Piotr Wygocki, Piotr Godlewski\n * @version 1.0\n * @date 2013-08-04\n */\n#ifndef PAAL_SAMPLE_GRAPH_HPP\n#define PAAL_SAMPLE_GRAPH_HPP\n\n#include \"paal/data_structures/metric/graph_metrics.hpp\"\n#include \"paal/data_structures/metric/euclidean_metric.hpp\"\n#include \"paal/utils/irange.hpp\"\n\n#include <boost/graph/adjacency_list.hpp>\n\nstruct sample_graphs_metrics {\n    using EdgeProp = boost::property<boost::edge_weight_t, int>;\n    using Graph = boost::adjacency_list<\n        boost::vecS, boost::vecS, boost::undirectedS,\n        boost::property<boost::vertex_color_t, int>, EdgeProp>;\n    using GraphWithoutEdgeWeight = boost::adjacency_list<\n        boost::vecS, boost::vecS, boost::undirectedS,\n        boost::property<boost::vertex_color_t, int>, boost::no_property>;\n    using ListGraph = boost::adjacency_list<\n        boost::listS, boost::listS, boost::undirectedS,\n        boost::property<boost::vertex_color_t, int>, EdgeProp>;\n    using Edge = std::pair<int, int>;\n    using GraphMT = paal::data_structures::graph_metric<Graph, int>;\n    using Terminals = std::vector<int>;\n\n    enum nodes { A, B, C, D, E, F, G, H, I, J, K, L };\n\n    // graph small\n    static Graph get_graph_small() {\n        const int num_nodes = 5;\n        Edge edge_array[] = { Edge(A, C), Edge(B, B), Edge(B, D),\n                              Edge(B, E), Edge(C, B), Edge(C, D),\n                              Edge(D, E), Edge(E, A), Edge(E, B) };\n        int weights[] = { 1, 2, 1, 2, 7, 3, 1, 1, 1 };\n        int num_arcs = sizeof(edge_array) / sizeof(Edge);\n\n        Graph g(edge_array, edge_array + num_arcs, weights, num_nodes);\n\n        return g;\n    }\n\n    static Graph get_graph_medium() {\n        const int num_nodes = 9;\n        Edge edge_array[] = { Edge(A, B), Edge(B, C), Edge(B, D), Edge(B, E),\n                              Edge(D, E), Edge(E, F), Edge(F, G), Edge(G, H),\n                              Edge(E, H), Edge(H, I) };\n\n        int weights[] = {64, 23, 54, 63, 25, 49, 32, 15, 74, 31};\n        int num_arcs = sizeof(edge_array) / sizeof(Edge);\n\n        Graph g(edge_array, edge_array + num_arcs, weights, num_nodes);\n\n        return g;\n    }\n\n    static ListGraph get_list_graph_medium() {\n        const int num_nodes = 9;\n        Edge edge_array[] = { Edge(A, B), Edge(B, C), Edge(B, D), Edge(B, E),\n                              Edge(D, E), Edge(E, F), Edge(F, G), Edge(G, H),\n                              Edge(E, H), Edge(H, I) };\n\n        int weights[] = {64, 23, 54, 63, 25, 49, 32, 15, 74, 31};\n        int num_arcs = sizeof(edge_array) / sizeof(Edge);\n\n        ListGraph g(edge_array, edge_array + num_arcs, weights, num_nodes);\n\n        return g;\n    }\n\n    static Graph get_star_medium() {\n        const int num_nodes = 11;\n        Edge edge_array[] = { Edge(A, B), Edge(A, C), Edge(A, D), Edge(A, E),\n                              Edge(A, F), Edge(A, G), Edge(A, H), Edge(A, I),\n                              Edge(A, J), Edge(A, K) };\n        int weights[] = { 64, 23, 54, 63, 25, 49, 32, 15, 74, 31};\n        int num_arcs = sizeof(edge_array) / sizeof(Edge);\n\n        Graph g(edge_array, edge_array + num_arcs, weights, num_nodes);\n\n        return g;\n    }\n\n    static Graph get_star_random(int seed, int num_nodes, int minW, int maxW) {\n        std::srand(seed);\n\n        int center = std::rand() % num_nodes;\n\n        std::vector< std::pair<int, int> > edges;\n        std::vector<int> weights(num_nodes-1);\n\n        for (int v: paal::irange(num_nodes)) if (v != center) edges.push_back(std::make_pair(center, v));\n        for (int i: paal::irange(num_nodes-1)) weights[i] = rand() % (maxW - minW + 1) + minW;\n\n        Graph g(edges.begin(), edges.end(), weights.begin(), num_nodes);\n\n        return g;\n    }\n\n    static GraphMT get_graph_metric_small() {\n        return GraphMT(get_graph_small());\n    }\n\n    // graph steiner\n    static Graph get_graph_steiner() {\n        const int num_nodes = 6;\n        Edge edge_array[] = { Edge(A, B), Edge(B, C), Edge(C, D),\n                              Edge(D, A), Edge(A, E), Edge(B, E),\n                              Edge(C, E), Edge(D, E), Edge(A, F) };\n        int weights[] = { 2, 2, 2, 2, 1, 1, 1, 1, 1 };\n        int num_arcs = sizeof(edge_array) / sizeof(Edge);\n\n        Graph g(edge_array, edge_array + num_arcs, weights, num_nodes);\n        auto color = get(boost::vertex_color, g);\n        put(color, A, 1);\n        put(color, B, 1);\n        put(color, C, 1);\n        put(color, D, 1);\n\n        return g;\n    }\n\n    static Graph two_points_steiner() {\n        int const  num_nodes = 2;\n        Edge * edge_array = nullptr;\n        int * weights = nullptr;\n        Graph g(edge_array, edge_array, weights, num_nodes);\n        auto color = get(boost::vertex_color, g);\n        put(color, A, 1);\n        put(color, B, 1);\n        return g;\n    }\n\n    static Graph get_graph_steiner_multi_edges() {\n        const int num_nodes = 3;\n        Edge edge_array[] = { Edge(A, B), Edge(A, C), Edge(B, C), Edge(B, C),\n                              Edge(B, C) };\n        int weights[] = { 20, 30, 3, 5, 9 };\n        int num_arcs = sizeof(edge_array) / sizeof(Edge);\n\n        Graph g(edge_array, edge_array + num_arcs, weights, num_nodes);\n        auto color = get(boost::vertex_color, g);\n        put(color, A, 1);\n        put(color, B, 1);\n        put(color, C, 1);\n\n        return g;\n    }\n    static GraphWithoutEdgeWeight get_graph_steiner_edge() {\n\n        const int num_nodes = 2;\n        Edge edge_array[] = { Edge(A, B) };\n        int num_arcs = sizeof(edge_array) / sizeof(Edge);\n\n        GraphWithoutEdgeWeight g(edge_array, edge_array + num_arcs, num_nodes);\n        auto color = get(boost::vertex_color, g);\n        put(color, A, 1);\n        put(color, B, 1);\n\n        return g;\n    }\n\n    static Graph get_graph_stainer_tree_cycle() {\n        const int num_nodes = 5;\n        Edge edge_array[] = { Edge(A, B), Edge(A, C), Edge(B, C), Edge(C, D),\n                              Edge(C, E) };\n        int weights[] = { 4, 2, 2, 2, 2 };\n        int num_arcs = sizeof(edge_array) / sizeof(Edge);\n\n        Graph g(edge_array, edge_array + num_arcs, weights, num_nodes);\n        auto color = get(boost::vertex_color, g);\n        put(color, A, 1);\n        put(color, B, 1);\n        put(color, D, 1);\n        put(color, E, 1);\n\n        return g;\n    }\n\n    static GraphMT get_graph_metric_steiner() {\n        return GraphMT(get_graph_steiner());\n    }\n\n    static std::pair<Terminals, Terminals> get_graph_steiner_vertices() {\n        Terminals terminals = { A, B, C, D }, non_terminals = { E, F };\n        return std::make_pair(terminals, non_terminals);\n    }\n\n    // graph medium\n    static GraphMT get_graph_metric_medium() {\n        const int num_nodes = 8;\n        Edge edge_array[] = { Edge(A, C), Edge(A, F), Edge(B, E), Edge(B, G),\n                              Edge(B, H), Edge(C, E), Edge(C, G), Edge(C, H),\n                              Edge(D, E), Edge(D, G), Edge(D, H), Edge(F, H) };\n        int weights[] = { 4, 2, 1, 2, 7, 3, 1, 8, 1, 3, 4, 10 };\n        int num_arcs = sizeof(edge_array) / sizeof(Edge);\n\n        Graph g(edge_array, edge_array + num_arcs, weights, num_nodes);\n\n        return GraphMT(g);\n    }\n\n    // graph steiner bigger\n    static Graph get_graph_steiner_bigger(int p = 3, int q = 2) {\n        bool b;\n        int n = p + p * q;\n        Graph g(n);\n        for (int i = 0; i < n; i++) {\n            for (int j = i + 1; j < n; j++) {\n                int cost = 3;\n                if (i < p && j < p) {\n                    cost = 1;\n                } else if ((j - p) / q == i) {\n                    cost = 2;\n                }\n                b = add_edge(i, j, EdgeProp(cost), g).second;\n                assert(b);\n            }\n        }\n        return g;\n    }\n\n    static GraphMT get_graph_metric_steiner_bigger() {\n        return GraphMT(get_graph_steiner_bigger());\n    }\n\n    static std::pair<Terminals, Terminals>\n    get_graph_steiner_bigger_vertices(int p = 3, int q = 2) {\n        int n = p + p * q;\n        Terminals terminals, non_terminals;\n        for (int i = 0; i < n; i++) {\n            if (i >= p)\n                terminals.push_back(i);\n            else\n                non_terminals.push_back(i);\n        }\n        return make_pair(terminals, non_terminals);\n    }\n\n    // eucildean steiner\n    template <typename Points = std::vector<std::pair<int, int>>>\n    static std::tuple<paal::data_structures::euclidean_metric<int>, Points,\n                      Points>\n    get_euclidean_steiner_sample() {\n        return std::make_tuple(paal::data_structures::euclidean_metric<int>{},\n                               Points{ { 0, 0 }, { 0, 2 }, { 2, 0 }, { 2, 2 } },\n                               Points{ { 1, 1 } });\n    }\n};\n\n#endif // PAAL_SAMPLE_GRAPH_HPP\n", "meta": {"hexsha": "ef958db35b03c176ad044dd9cde8e424763aea69", "size": 9145, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/test_utils/sample_graph.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": "test/test_utils/sample_graph.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": "test/test_utils/sample_graph.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": 34.6401515152, "max_line_length": 105, "alphanum_fraction": 0.52695462, "num_tokens": 2555, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.46551279024949077}}
{"text": "/**\n * $Id$\n *\n * Copyright (C)\n * 2015 - $Date$\n *     Martin Wolf <ndhist@martin-wolf.org>\n *\n * This file is distributed under the BSD 2-Clause Open Source License\n * (See LICENSE file).\n *\n */\n#include <boost/python.hpp>\n\n#include <ndhist/stats/expectation.hpp>\n\nnamespace bp = boost::python;\n\nnamespace ndhist {\n\nnamespace stats {\n\nvoid register_expectation()\n{\n    bp::def(\"expectation\"\n      , &py::expectation\n      , ( bp::arg(\"hist\")\n        , bp::arg(\"n\")=1\n        , bp::arg(\"axis\")=bp::object()\n        )\n      , \"Calculates the n'th order expectation value along the given axis of \\n\"\n        \"the given ndhist object weighted by the sum of weights in each bin. \\n\"\n        \"It generates a projection along the given axis and then calculates  \\n\"\n        \"the n'th order expectation axis value.                              \\n\"\n        \"In statistics the n'th order expectation is defined as the          \\n\"\n        \"expectation of x^n, i.e. ``E[x^n]``, where x is the bin center axis \\n\"\n        \"value in this case.                                                 \\n\"\n        \"If ``None`` is given as axis argument (the default), the n'th order \\n\"\n        \"expectation value for all individual axes of the ndhist object is   \\n\"\n        \"calculated and returned as a tuple. But if the dimensionality of    \\n\"\n        \"the histogram is 1, a scalar value is returned.                     \\n\"\n        \"                                                                    \\n\"\n        \".. note:: This function is only defined for ndhist objects with POD \\n\"\n        \"          type axis values AND POD type weight values.              \\n\"\n    );\n}\n\n}// namespace stats\n}// namespace ndhist\n", "meta": {"hexsha": "32c3868f87430fe5ab4f0d8ee78d57c7aa7a1b57", "size": 1703, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/pybindings/stats/expectation.cpp", "max_stars_repo_name": "martwo/ndhist", "max_stars_repo_head_hexsha": "193cef3585b5d0277f0721bb9c3a1e78cc67cf1f", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/pybindings/stats/expectation.cpp", "max_issues_repo_name": "martwo/ndhist", "max_issues_repo_head_hexsha": "193cef3585b5d0277f0721bb9c3a1e78cc67cf1f", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pybindings/stats/expectation.cpp", "max_forks_repo_name": "martwo/ndhist", "max_forks_repo_head_hexsha": "193cef3585b5d0277f0721bb9c3a1e78cc67cf1f", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7551020408, "max_line_length": 80, "alphanum_fraction": 0.5502055197, "num_tokens": 404, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.4655127856557468}}
{"text": "// Copyright 2015-2018 Hans Dembinski\n//\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include <boost/core/lightweight_test.hpp>\n#include <boost/histogram/accumulators/ostream.hpp>\n#include <boost/histogram/accumulators/weighted_mean.hpp>\n#include <boost/histogram/weight.hpp>\n#include <sstream>\n#include \"is_close.hpp\"\n#include \"throw_exception.hpp\"\n#include \"utility_str.hpp\"\n\nusing namespace boost::histogram;\nusing namespace std::literals;\n\nint main() {\n  using m_t = accumulators::weighted_mean<double>;\n  using detail::square;\n\n  // basic interface, string conversion\n  {\n    // see https://en.wikipedia.org/wiki/Weighted_arithmetic_mean#Reliability_weights\n\n    m_t a;\n    BOOST_TEST_EQ(a.sum_of_weights(), 0);\n    BOOST_TEST_EQ(a, m_t{});\n\n    a(weight(0.5), 1);\n    a(weight(1.0), 2);\n    a(weight(0.5), 3);\n\n    BOOST_TEST_EQ(a.sum_of_weights(), 1 + 2 * 0.5);\n    BOOST_TEST_EQ(a.sum_of_weights_squared(), 1 + 2 * 0.5 * 0.5);\n    const auto m = a.value();\n    BOOST_TEST_IS_CLOSE(\n        a.variance(),\n        (0.5 * square(1 - m) + square(2 - m) + 0.5 * square(3 - m)) /\n            (a.sum_of_weights() - a.sum_of_weights_squared() / a.sum_of_weights()),\n        1e-3);\n\n    BOOST_TEST_EQ(str(a), \"weighted_mean(2, 2, 0.8)\"s);\n    BOOST_TEST_EQ(str(a, 25, false), \" weighted_mean(2, 2, 0.8)\"s);\n    BOOST_TEST_EQ(str(a, 25, true), \"weighted_mean(2, 2, 0.8) \"s);\n  }\n\n  // addition of zero element\n  {\n    BOOST_TEST_EQ(m_t() += m_t(), m_t());\n    BOOST_TEST_EQ(m_t(1, 2, 3, 4) += m_t(), m_t(1, 2, 3, 4));\n    BOOST_TEST_EQ(m_t() += m_t(1, 2, 3, 4), m_t(1, 2, 3, 4));\n  }\n\n  // addition\n  {\n    m_t a, b, c;\n\n    a(weight(4), 2);\n    a(weight(3), 3);\n    BOOST_TEST_EQ(a.sum_of_weights(), 4 + 3);\n    BOOST_TEST_EQ(a.sum_of_weights_squared(), 4 * 4 + 3 * 3);\n    BOOST_TEST_EQ(a.value(), (4 * 2 + 3 * 3) / 7.);\n    BOOST_TEST_IS_CLOSE(a.variance(), 0.5, 1e-3);\n\n    b(weight(2), 4);\n    b(weight(1), 6);\n    BOOST_TEST_EQ(b.sum_of_weights(), 3);\n    BOOST_TEST_EQ(b.sum_of_weights_squared(), 1 + 2 * 2);\n    BOOST_TEST_EQ(b.value(), (2 * 4 + 1 * 6) / (2. + 1.));\n    BOOST_TEST_IS_CLOSE(b.variance(), 2, 1e-3);\n\n    c(weight(4), 2);\n    c(weight(3), 3);\n    c(weight(2), 4);\n    c(weight(1), 6);\n\n    auto d = a;\n    d += b;\n    BOOST_TEST_EQ(c.sum_of_weights(), d.sum_of_weights());\n    BOOST_TEST_EQ(c.sum_of_weights_squared(), d.sum_of_weights_squared());\n    BOOST_TEST_EQ(c.value(), d.value());\n    BOOST_TEST_IS_CLOSE(c.variance(), d.variance(), 1e-3);\n  }\n\n  // using weights * 2 compared to adding weighted samples twice must\n  // - give same for sum_of_weights and mean\n  // - give twice sum_of_weights_squared\n  // - give half effective count\n  // - variance is complicated, but larger\n  {\n    m_t a, b;\n\n    for (int i = 0; i < 2; ++i) {\n      a(weight(0.5), 1);\n      a(weight(1.0), 2);\n      a(weight(0.5), 3);\n    }\n\n    b(weight(1), 1);\n    b(weight(2), 2);\n    b(weight(1), 3);\n\n    BOOST_TEST_EQ(a.sum_of_weights(), b.sum_of_weights());\n    BOOST_TEST_EQ(2 * a.sum_of_weights_squared(), b.sum_of_weights_squared());\n    BOOST_TEST_EQ(a.value(), b.value());\n    BOOST_TEST_LT(a.variance(), b.variance());\n  }\n\n  return boost::report_errors();\n}\n", "meta": {"hexsha": "c9ee70fbdafe79c9667e5bd37dd0d24a9db5ccd2", "size": 3284, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/histogram/test/accumulators_weighted_mean_test.cpp", "max_stars_repo_name": "anarthal/boost-unix-mirror", "max_stars_repo_head_hexsha": "8c34eb2fe471d6c3113c680c1fbef29e7a8063a0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-15T13:07:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-15T13:07:07.000Z", "max_issues_repo_path": "libs/histogram/test/accumulators_weighted_mean_test.cpp", "max_issues_repo_name": "anarthal/boost-unix-mirror", "max_issues_repo_head_hexsha": "8c34eb2fe471d6c3113c680c1fbef29e7a8063a0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-10-21T12:42:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-03T08:41:31.000Z", "max_forks_repo_path": "Libs/boost_1_76_0/libs/histogram/test/accumulators_weighted_mean_test.cpp", "max_forks_repo_name": "Antd23rus/S2DE", "max_forks_repo_head_hexsha": "47cc7151c2934cd8f0399a9856c1e54894571553", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-24T08:55:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-24T08:55:27.000Z", "avg_line_length": 29.0619469027, "max_line_length": 85, "alphanum_fraction": 0.6205846529, "num_tokens": 1075, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.46551278106200267}}
{"text": "/* Siconos is a program dedicated to modeling, simulation and control\n * of non smooth dynamical systems.\n *\n * Copyright 2020 INRIA.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n*/\n#include \"SiconosConfig.h\"\n\n#include \"SimpleMatrixTest.hpp\"\n#include \"SiconosAlgebra.hpp\"\n#include \"SiconosAlgebraProd.hpp\"\n#include \"SiconosAlgebraScal.hpp\"\n#include \"SimpleMatrixFriends.hpp\"\n#include \"SiconosMatrixSetBlock.hpp\"\n#include \"SiconosVectorFriends.hpp\"\n#include \"NumericsMatrix.h\"\n#include \"NumericsSparseMatrix.h\"\n\n#include <boost/numeric/ublas/matrix_sparse.hpp>\n\n#define CPPUNIT_ASSERT_NOT_EQUAL(message, alpha, omega) \\\n  if ((alpha) == (omega)) CPPUNIT_FAIL(message);\n\nCPPUNIT_TEST_SUITE_REGISTRATION(SimpleMatrixTest);\n\nusing namespace Siconos;\n\n#define DEBUG_MESSAGES\n#include \"debug.h\"\n\n\n// Note FP: tests are (rather) complete for Dense objects but many are missing for other cases (Triang, Symm etc ...).\n\nvoid SimpleMatrixTest::setUp()\n{\n  tol = 1e-9;\n\n  fic1 = \"mat1.dat\"; // 2 X 2\n  fic2 = \"mat2.dat\"; // 2 X 3\n  SicM.reset(new SimpleMatrix(fic1, 1));\n  SimM.reset(new SimpleMatrix(fic2, 1));\n\n  std::vector<double> v3(2, 0);\n  std::vector<double> v4(2, 0);\n  std::vector<double> v5(3, 0);\n  v4[0] = 6;\n  v4[1] = 9;\n  v5[0] = 8;\n  v5[1] = 9;\n  v5[2] = 10;\n\n\n\n  vect1.reset(new SiconosVector(v3));\n  vect2.reset(new SiconosVector(v4)); // vect2 != vect1, but vect2 == SimM second column\n  vect3.reset(new SiconosVector(v5)); // vect3 != vect1, but vect3 == SimM second row\n\n  // Dense\n  D.reset(new DenseMat(2, 2));\n  for(unsigned i = 0; i < D->size1(); ++ i)\n    for(unsigned j = 0; j < D->size2(); ++ j)\n      (*D)(i, j) = 3 * i + j;\n\n  // Triang\n  T.reset(new TriangMat(3, 3));\n  for(unsigned i = 0; i < T->size1(); ++ i)\n    for(unsigned j = i; j < T->size2(); ++ j)\n      (*T)(i, j) = 3 * i + j;\n  T2.reset(new TriangMat(4, 4));\n  for(unsigned i = 0; i < T2->size1(); ++ i)\n    for(unsigned j = i; j < T2->size2(); ++ j)\n      (*T2)(i, j) = 3 * i + j;\n\n  // Sym\n  S.reset(new SymMat(3, 3));\n  for(unsigned i = 0; i < S->size1(); ++ i)\n    for(unsigned j = i; j < S->size2(); ++ j)\n      (*S)(i, j) = 3 * i + j;\n  S2.reset(new SymMat(4, 4));\n  for(unsigned i = 0; i < S2->size1(); ++ i)\n    for(unsigned j = i; j < S2->size2(); ++ j)\n      (*S2)(i, j) = 3 * i + j;\n\n  // Sparse\n  SP.reset(new SparseMat(4, 4));\n  for(unsigned i = 0; i < SP->size1(); ++ i)\n    for(unsigned j = 0; j < SP->size2(); ++ j)\n      (*SP)(i, j) = 3 * i + j;\n\n  SP2.reset(new SparseMat(4, 4));\n  for(unsigned i = 0; i < SP2->size1(); ++ i)\n    for(unsigned j = 0; j < SP->size2()-1; ++ j)\n      if(i != j)\n        (*SP2)(i, j) = 3 * i + j;\n\n  SP3.reset(new SparseMat(3, 3));\n  (*SP3)(0,0) = 1.0;\n  (*SP3)(0,2) = 2.0;\n  (*SP3)(1,2) = 3.0;\n  (*SP3)(2,0) = 4.0;\n  (*SP3)(2,1) = 5.0;\n  (*SP3)(2,2) = 5.0;\n\n  SP4.reset(new SparseMat(3, 3));\n  (*SP4)(0,0) = 1.0;\n  (*SP4)(0,2) = 4.0;\n  (*SP4)(1,1) = 1.0;\n  (*SP4)(1,2) = 5.0;\n  (*SP4)(2,0) = 4.0;\n  (*SP4)(2,1) = 5.0;\n  (*SP4)(2,2) = 77.0;\n\n\n  // Sparse Coordinate\n  SP_coor.reset(new SparseCoordinateMat(4, 4));\n  for(unsigned i = 0; i < SP->size1(); ++ i)\n    for(unsigned j = 0; j < SP->size2(); ++ j)\n      (*SP_coor)(i, j) = 3 * i + j;\n\n  // Banded\n  Band.reset(new BandedMat(4, 4, 1, 1));\n  for(signed i = 0; i < signed(Band->size1()); ++ i)\n    for(signed j = std::max(i - 1, 0); j < std::min(i + 2, signed(Band->size2())); ++ j)\n      (*Band)(i, j) = 3 * i + j;\n  Band2.reset(new BandedMat(4, 3, 1, 1));\n  for(signed i = 0; i < signed(Band2->size1()); ++ i)\n    for(signed j = std::max(i - 1, 0); j < std::min(i + 2, signed(Band2->size2())); ++ j)\n      (*Band2)(i, j) = 3 * i + j;\n\n  // Zero\n  Z.reset(new ZeroMat(3, 3));\n  Z2.reset(new ZeroMat(4, 4));\n  // Identity\n  I.reset(new IdentityMat(3, 3));\n  I2.reset(new IdentityMat(4, 4));\n\n  // BlockMat\n  size = 10;\n  size2 = 10;\n\n  C.reset(new SimpleMatrix(size, size));\n  A.reset(new SimpleMatrix(\"A.dat\"));\n  B.reset(new SimpleMatrix(\"B.dat\"));\n\n  m1.reset(new SimpleMatrix(size - 2, size - 2, 1));\n  m2.reset(new SimpleMatrix(size - 2, 2, 2));\n  m3.reset(new SimpleMatrix(2, size - 2, 3));\n  m4.reset(new SimpleMatrix(2, 2, 4));\n  m5.reset(new SimpleMatrix(size2 - 2, size2 - 2, 1));\n  m6.reset(new SimpleMatrix(size2 - 2, 2, 2));\n  m7.reset(new SimpleMatrix(2, size2 - 2, 3));\n  m8.reset(new SimpleMatrix(2, 2, 4));\n  Ab.reset(new BlockMatrix(m1, m2, m3, m4));\n  Bb.reset(new BlockMatrix(3 * *Ab));\n  Cb.reset(new BlockMatrix(m5, m6, m7, m8));\n\n\n}\n\nvoid SimpleMatrixTest::tearDown()\n{}\n\n//______________________________________________________________________________\n\nvoid SimpleMatrixTest::testConstructor0() // constructor with TYP and dim\n{\n  std::cout << \"====================================\" <<std::endl;\n  std::cout << \"=== Simple Matrix tests start ...=== \" <<std::endl;\n  std::cout << \"====================================\" <<std::endl;\n  std::cout << \"--> Test: constructor 0.\" <<std::endl;\n  SP::SimpleMatrix test(new SimpleMatrix(2, 3));\n\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testConstructor0 : \", test->num() == Siconos::DENSE, true);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testConstructor0 : \", test->size(0) == 2, true);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testConstructor0 : \", test->size(1) == 3, true);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testConstructor0 : \", test->normInf() < tol, true);\n  std::cout << \"--> Constructor 0 test ended with success.\" <<std::endl;\n}\n\nvoid SimpleMatrixTest::testConstructor1() // Copy constructor, from a SimpleMatrix\n{\n  std::cout << \"--> Test: constructor 1.\" <<std::endl;\n  SP::SimpleMatrix test(new SimpleMatrix(*SimM));\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testConstructor1 : \", *test == *SimM, true);\n  std::cout << \"--> Constructor 1 (copy) test ended with success.\" <<std::endl;\n}\n\nvoid SimpleMatrixTest::testConstructor2() // Copy constructor, from a SiconosMatrix\n{\n  std::cout << \"--> Test: constructor 2.\" <<std::endl;\n  SP::SimpleMatrix  test(new SimpleMatrix(*SicM));\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testConstructor2 : \", *test == *SicM, true);\n  std::cout << \"--> Constructor 2 (copy) test ended with success.\" <<std::endl;\n}\n\nvoid SimpleMatrixTest::testConstructor3() // Copy constructor, from a BlockMatrix\n{\n  std::cout << \"--> Test: constructor 3.\" <<std::endl;\n  SP::SimpleMatrix test(new SimpleMatrix(*Ab));\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testConstructor3 : \", *test == *Ab, true);\n  std::cout << \"--> Constructor 3 (copy) test ended with success.\" <<std::endl;\n}\n\n\nvoid SimpleMatrixTest::testConstructor4()\n{\n  std::cout << \"--> Test: constructor 4.\" <<std::endl;\n  SP::SiconosMatrix test(new SimpleMatrix(*D));\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testConstructor4 : \", test->num() == Siconos::DENSE, true);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testConstructor4 : \", norm_inf(test->getDense() - *D) == 0, true);\n  std::cout << \"--> Constructor 4 test ended with success.\" <<std::endl;\n}\n\nvoid SimpleMatrixTest::testConstructor5()\n{\n  std::cout << \"--> Test: constructor 5.\" <<std::endl;\n  SP::SiconosMatrix test(new SimpleMatrix(*T));\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testConstructor5 : \", test->num() == Siconos::TRIANGULAR, true);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testConstructor5 : \", norm_inf(test->getTriang() - *T) == 0, true);\n  std::cout << \"--> Constructor 5 test ended with success.\" <<std::endl;\n}\n\nvoid SimpleMatrixTest::testConstructor6()\n{\n  std::cout << \"--> Test: constructor 6.\" <<std::endl;\n  SP::SiconosMatrix test(new SimpleMatrix(*S));\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testConstructor6 : \", test->num() == Siconos::SYMMETRIC, true);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testConstructor6 : \", norm_inf(test->getSym() - *S) == 0, true);\n  std::cout << \"--> Constructor 6 test ended with success.\" <<std::endl;\n}\n\nvoid SimpleMatrixTest::testConstructor7()\n{\n  std::cout << \"--> Test: constructor 7.\" <<std::endl;\n  SP::SiconosMatrix test(new SimpleMatrix(*SP));\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testConstructor7 : \", test->num() == Siconos::SPARSE, true);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testConstructor7 : \", norm_inf(test->getSparse() - *SP) == 0, true);\n  std::cout << \"--> Constructor 7 test ended with success.\" <<std::endl;\n}\n\nvoid SimpleMatrixTest::testConstructor8()\n{\n  std::cout << \"--> Test: constructor 8.\" <<std::endl;\n  std::cout << \"--> Constructor 8 test ended with success.\" <<std::endl;\n  SP::SiconosMatrix test(new SimpleMatrix(*Band));\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testConstructor8 : \", test->num() == Siconos::BANDED, true);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testConstructor8 : \", norm_inf(test->getBanded() - *Band) == 0, true);\n}\n\nvoid SimpleMatrixTest::testConstructor9() // constructor with TYP and dim and input value\n{\n  std::cout << \"--> Test: constructor 9.\" <<std::endl;\n  SP::SimpleMatrix test(new SimpleMatrix(2, 3, 4.5));\n\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testConstructor9 : \", test->num() == Siconos::DENSE, true);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testConstructor9 : \", test->size(0) == 2, true);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testConstructor9 : \", test->size(1) == 3, true);\n  for(unsigned int i = 0; i < 2; ++i)\n    for(unsigned int j = 0 ; j < 3; ++j)\n    {\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testConstructor9 : \", (*test)(i, j) == 4.5, true);\n    }\n  std::cout << \"--> Constructor 9 test ended with success.\" <<std::endl;\n}\n\nvoid SimpleMatrixTest::testConstructor10()\n{\n  std::cout << \"--> Test: constructor 10.\" <<std::endl;\n  SP::SiconosMatrix test(new SimpleMatrix(fic1));\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testConstructor10 : \", *test == *SicM, true);\n  std::cout << \"--> Constructor 10 test ended with success.\" <<std::endl;\n}\n\nvoid SimpleMatrixTest::testConstructor11()\n{\n  std::cout << \"--> Test: constructor 11.\" <<std::endl;\n  std::cout << \"--> Constructor 11 test ended with success.\" <<std::endl;\n  SP::SiconosMatrix test(new SimpleMatrix(*Z));\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testConstructor11 : \", test->num() == Siconos::ZERO, true);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testConstructor11 : \", test->normInf() == 0, true);\n}\n\nvoid SimpleMatrixTest::testConstructor12()\n{\n  std::cout << \"--> Test: constructor 12.\" <<std::endl;\n  std::cout << \"--> Constructor 12 test ended with success.\" <<std::endl;\n  SP::SiconosMatrix test(new SimpleMatrix(*I));\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testConstructor12 : \", test->num() == Siconos::IDENTITY, true);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testConstructor12 : \", test->normInf() == 1, true);\n}\n\nvoid SimpleMatrixTest::testConstructor13()\n{\n  std::cout << \"--> Test: constructor 13.\" <<std::endl;\n  SP::SimpleMatrix test(new SimpleMatrix(4,4,Siconos::SPARSE));\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testConstructor3 : \",test->num() == Siconos::SPARSE, true);\n  std::cout << \"--> Constructor 13 test ended with success.\" <<std::endl;\n}\nvoid SimpleMatrixTest::testConstructor14()\n{\n  std::cout << \"--> Test: constructor 14.\" <<std::endl;\n  SP::SimpleMatrix test(new SimpleMatrix(4,4,Siconos::SPARSE_COORDINATE));\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testConstructor14 : \",test->num() == Siconos::SPARSE_COORDINATE, true);\n  std::cout << \"--> Constructor 14 test ended with success.\" <<std::endl;\n}\n// Add tests with getDense ...\n\n// Add tests with getDense ...\n\nvoid SimpleMatrixTest::testZero()\n{\n  std::cout << \"--> Test: zero.\" <<std::endl;\n  SP::SiconosMatrix tmp(new SimpleMatrix(*SimM));\n  tmp->zero();\n  unsigned int n1 = tmp->size(0);\n  unsigned int n2 = tmp->size(1);\n  for(unsigned int i = 0; i < n1; ++i)\n    for(unsigned int j = 0; j < n2; ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testZero : \", (*tmp)(i, j) == 0, true);\n  std::cout << \"--> zero test ended with success.\" <<std::endl;\n}\n\nvoid SimpleMatrixTest::testEye()\n{\n  std::cout << \"--> Test: eye.\" <<std::endl;\n  SP::SiconosMatrix tmp(new SimpleMatrix(*SimM));\n  tmp->eye();\n  unsigned int n1 = tmp->size(0);\n  unsigned int n2 = tmp->size(1);\n  for(unsigned int i = 0; i < n1; ++i)\n    for(unsigned int j = 0; j < n2; ++j)\n      if(i != j)\n        CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testEye : \", (*tmp)(i, j) == 0, true);\n      else\n        CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testEye : \", (*tmp)(i, j) == 1, true);\n  std::cout << \"--> eye test ended with success.\" <<std::endl;\n}\n\nvoid SimpleMatrixTest::testResize()\n{\n  std::cout << \"--> Test: resize.\" <<std::endl;\n  SP::SiconosMatrix tmp(new SimpleMatrix(*SicM));\n  tmp->resize(3, 4);\n  unsigned int n1 = SicM->size(0);\n  unsigned int n2 = SicM->size(1);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testResize : \", tmp->size(0) == 3, true);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testResize : \", tmp->size(1) == 4, true);\n\n  for(unsigned int i = 0; i < n1; ++i)\n    for(unsigned int j = 0; j < n2; ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testResize : \", fabs((*tmp)(i, j) - (*SicM)(i, j)) < tol, true);\n  //   for(unsigned int i = n1; i<3; ++i)\n  //     for(unsigned int j=0;j<4;++j)\n  //       CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testResize : \", fabs((*tmp)(i,j)) < tol, true);\n  //   for(unsigned int j = n2; j<4; ++j)\n  //     for(unsigned int i=0;i<3;++i)\n  //       CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testResize : \", fabs((*tmp)(i,j)) < tol, true)\n  ;\n  // Check the effect of bool = false (ie preserve == false in boost resize)\n  //   tmp->resize(6,8, false);\n  //   tmp->display();\n  //   CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testResize : \", tmp->size(0) == 6, true);\n  //   CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testResize : \", tmp->size(1) == 8, true);\n  //   for(unsigned int i = 0; i<6; ++i)\n  //     for(unsigned int j=0;j<8;++j)\n  //       CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testResize : \", (*tmp)(i,j) == 0 , true);\n  //   // Reduction ...\n  //   tmp->resize(1,2, false);\n  //   CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testResize : \", tmp->size(0) == 1, true);\n  //   CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testResize : \", tmp->size(1) == 2, true);\n  //   for(unsigned int i = 0; i<1; ++i)\n  //     for(unsigned int j=0;j<2;++j)\n  //       CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testResize : \", (*tmp)(i,j) == 0 , true);\n  std::cout << \"--> resize test ended with success.\" <<std::endl;\n}\n\nvoid SimpleMatrixTest::testNormInf()\n{\n  std::cout << \"--> Test: normInf.\" <<std::endl;\n  double n = SicM->normInf();\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testNormInf: \", n == 7, true);\n  std::cout << \"--> normInf test ended with success.\" <<std::endl;\n}\n\nvoid SimpleMatrixTest::testSetBlock()\n{\n  std::cout << \"--> Test: testSetBlock.\" <<std::endl;\n\n  // Copy of a sub-block of a Simple into a Simple\n  SP::SiconosMatrix MIn(new SimpleMatrix(10, 10));\n  for(unsigned int i = 0; i < 10; ++i)\n    for(unsigned int j = 0 ; j < 10; ++j)\n      (*MIn)(i, j) = i + j;\n\n  SP::SiconosMatrix MOut(new SimpleMatrix(5, 5));\n\n  Index subDim(2);\n  Index subPos(4);\n  subDim[0] = 2;\n  subDim[1] = 3;\n  subPos[0] = 1;\n  subPos[1] = 2;\n  subPos[2] = 1;\n  subPos[3] = 2;\n\n  setBlock(MIn, MOut, subDim, subPos);\n\n  for(unsigned int i = subPos[2]; i < subPos[2] + subDim[0]; ++i)\n    for(unsigned int j = subPos[3] ; j < subPos[3] + subDim[1]; ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testSetBlock: \", fabs((*MOut)(i, j) - (*MIn)(i, j)) < tol, true);\n\n  // Copy of a sub-block of a Simple into a Block\n  Cb->zero();\n  setBlock(MIn, Cb, subDim, subPos);\n\n  for(unsigned int i = subPos[2]; i < subPos[2] + subDim[0]; ++i)\n    for(unsigned int j = subPos[3] ; j < subPos[3] + subDim[1]; ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testSetBlock: \", fabs((*Cb)(i, j) - (*MIn)(i, j)) < tol, true);\n\n  // Copy of a sub-block of a Block into a Simple\n\n  MOut.reset(new SimpleMatrix(5, 5));\n  setBlock(Ab, MOut, subDim, subPos);\n\n  for(unsigned int i = subPos[2]; i < subPos[2] + subDim[0]; ++i)\n    for(unsigned int j = subPos[3] ; j < subPos[3] + subDim[1]; ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testSetBlock: \", fabs((*MOut)(i, j) - (*Ab)(i, j)) < tol, true);\n\n  std::cout << \"-->  setBlock test ended with success.\" <<std::endl;\n}\n\nvoid SimpleMatrixTest::testSetBlock2()\n{\n  std::cout << \"--> Test: testSetBlock2.\" <<std::endl;\n  // Copy of a Simple into a sub-block of Simple\n  SP::SimpleMatrix MOut(new SimpleMatrix(10, 10));\n\n  SP::SiconosMatrix MIn(new SimpleMatrix(5, 5));\n  for(unsigned int i = 0; i < 5; ++i)\n    for(unsigned int j = 0 ; j < 5; ++j)\n      (*MIn)(i, j) = i + j;\n\n  MOut->setBlock(2, 3, *MIn);\n\n  for(unsigned int i = 2; i < 7; ++i)\n    for(unsigned int j = 3 ; j < 8; ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testSetBlock2: \", fabs((*MOut)(i, j) - (*MIn)(i - 2, j - 3)) < tol, true);\n\n  // Copy of a Block into a sub-block of Simple\n\n  MIn.reset(new BlockMatrix(m4, m4, m4, m4));\n  MOut->setBlock(2, 3, *MIn);\n\n  for(unsigned int i = 2; i < 6; ++i)\n    for(unsigned int j = 3 ; j < 7; ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testSetBlock2: \", fabs((*MOut)(i, j) - (*MIn)(i - 2, j - 3)) < tol, true);\n\n  std::cout << \"-->  setBlock2 test ended with success.\" <<std::endl;\n}\n\n\nvoid SimpleMatrixTest::testGetSetRowCol()\n{\n  std::cout << \"--> Test: get, set Row and Col.\" <<std::endl;\n\n  SP::SiconosVector vIn(new SiconosVector(10, 1.2));\n  SP::BlockVector vBIn(new BlockVector());\n  SP::SiconosVector v1(new SiconosVector(3, 2));\n  SP::SiconosVector v2(new SiconosVector(5, 3));\n  SP::SiconosVector v3(new SiconosVector(2, 4));\n  vBIn->insertPtr(v1);\n  vBIn->insertPtr(v2);\n  vBIn->insertPtr(v3);\n\n  // Set row with a SiconosVector\n  C->setRow(4, *vIn);\n  for(unsigned int i = 0; i < C->size(1); ++i)\n    CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testGetSetRowCol : \", fabs((*C)(4, i) - 1.2) < tol, true);\n\n  // Set col with a SiconosVector\n  C->setCol(4, *vIn);\n  for(unsigned int i = 0; i < C->size(0); ++i)\n    CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testGetSetRowCol : \", fabs((*C)(i, 4) - 1.2) < tol, true);\n\n  //  C->setCol(4, *vBIn);\n  //  for (unsigned int i = 0; i< C->size(1); ++i)\n  //    CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testGetSetRowCol : \", fabs((*C)(4,i)- (*vBIn)(i)) < tol, true);\n\n  *C = *A; //reset C\n  vIn->zero();\n  vBIn->zero();\n  // get row and copy it into a SiconosVector\n  C->getRow(4, *vIn);\n  for(unsigned int i = 0; i < C->size(1); ++i)\n    CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testGetSetRowCol : \", fabs((*C)(4, i) - (*vIn)(i)) < tol, true);\n\n  // get col and copy it into a SiconosVector\n  C->getCol(4, *vIn);\n  for(unsigned int i = 0; i < C->size(0); ++i)\n    CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testGetSetRowCol : \", fabs((*C)(i, 4) - (*vIn)(i)) < tol, true);\n\n  std::cout << \"--> get, set Row and Col tests ended with success.\" <<std::endl;\n}\n\nvoid SimpleMatrixTest::testTrans()\n{\n  std::cout << \"--> Test: trans.\" <<std::endl;\n\n  // Transpose in place ...\n  SP::SimpleMatrix ref(new SimpleMatrix(*D));\n  SP::SimpleMatrix tRef(new SimpleMatrix(*ref));\n\n  tRef->trans();\n  for(unsigned int i = 0; i < ref->size(0); ++i)\n    for(unsigned int j = 0 ; j < ref->size(1); ++j)\n      if(i == j)\n        CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testTrans: \", (*tRef)(i, j) == (*ref)(i, j), true);\n      else\n        CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testTrans: \", (*tRef)(i, j) == (*ref)(j, i), true);\n\n  // Transpose of another matrix ...\n  // Dense\n  tRef->zero();\n\n  tRef->trans(*ref);\n  for(unsigned int i = 0; i < ref->size(0); ++i)\n    for(unsigned int j = 0 ; j < ref->size(1); ++j)\n      if(i == j)\n        CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testTrans: \", (*tRef)(i, j) == (*ref)(i, j), true);\n      else\n        CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testTrans: \", (*tRef)(i, j) == (*ref)(j, i), true);\n\n  // Sym\n  ref.reset(new SimpleMatrix(*S));\n  tRef.reset(new SimpleMatrix(*ref));\n  tRef->trans(*ref);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testTrans: \", (*tRef) == (*ref), true);\n  // Sparse\n  ref.reset(new SimpleMatrix(*SP));\n  tRef.reset(new SimpleMatrix(*ref));\n  tRef->trans(*ref);\n  //   for(unsigned int i = 0; i<ref->size(0); ++i)\n  //     {\n  //       for(unsigned int j = 0 ; j< ref->size(1); ++j)\n  //  if(i==j)\n  //    CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testTrans: \", (*tRef)(i,j) == (*ref)(i,j) , true);\n  //  else\n  //    CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testTrans: \", (*tRef)(i,j) == (*ref)(j,i) , true);\n  //     }\n  // Banded\n  //   ref.reset(new SimpleMatrix(*Band);\n  //   tRef.reset(new SimpleMatrix(*ref);\n  //   *tRef = trans(*ref);\n  //   for(unsigned int i = 0; i<ref->size(0); ++i)\n  //     for(unsigned int j = 0 ; j< ref->size(1); ++j)\n  //       if(i==j)\n  //  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testTrans: \", (*tRef)(i,j) == (*ref)(i,j) , true);\n  //       else\n  //  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testTrans: \", (*tRef)(i,j) == (*ref)(j,i) , true);\n  std::cout << \"-->  test trans ended with success.\" <<std::endl;\n}\n\n\nvoid SimpleMatrixTest::testAssignment0()\n{\n  std::cout << \"--> Test: assignment0.\" <<std::endl;\n\n  // Simple = Simple\n\n  SP::SimpleMatrix ref(new SimpleMatrix(*D));\n  SP::SiconosMatrix tRef(new SimpleMatrix(*SicM));\n  // Dense = any type:\n  *tRef = *ref;\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testAssignment0: \", (*tRef) == (*ref), true);\n  ref.reset(new SimpleMatrix(*T));\n  SP::SiconosMatrix tRef3(new SimpleMatrix(3, 3));\n  *tRef3 = *ref;\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testAssignment0: \", (*tRef3) == (*ref), true);\n\n  ref.reset(new SimpleMatrix(*S));\n  *tRef3 = *ref;\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testAssignment0: \", (*tRef3) == (*ref), true);\n\n  SP::SiconosMatrix tRef4(new SimpleMatrix(4, 4));\n  ref.reset(new SimpleMatrix(*SP));\n  *tRef4 = *ref;\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testAssignment0: \", (*tRef4) == (*ref), true);\n\n\n  ref.reset(new SimpleMatrix(*Band));\n  *tRef4 = *ref;\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testAssignment0: \", (*tRef4) == (*ref), true);\n  ref.reset(new SimpleMatrix(*Z));\n  *tRef3 = *ref;\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testAssignment0: \", (*tRef3) == (*ref), true);\n\n  ref.reset(new SimpleMatrix(*I));\n  *tRef3 = *ref;\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testAssignment0: \", (*tRef3) == (*ref), true);\n\n  // Triang = Triang, Zero or Identity\n  ref.reset(new SimpleMatrix(*T));\n  tRef.reset(new SimpleMatrix(*T));\n  tRef->zero();\n  *tRef = *ref;\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testAssignment0: \", (*tRef) == (*ref), true);\n\n  ref.reset(new SimpleMatrix(*Z));\n  *tRef = *ref;\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testAssignment0: \", (*tRef) == (*ref), true);\n\n  ref.reset(new SimpleMatrix(*I));\n  *tRef = *ref;\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testAssignment0: \", (*tRef) == (*ref), true);\n  // Sym = Sym, Zero or Id\n  ref.reset(new SimpleMatrix(*S));\n  tRef.reset(new SimpleMatrix(*S));\n  tRef->zero();\n  *tRef = *ref;\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testAssignment0: \", (*tRef) == (*ref), true);\n  ref.reset(new SimpleMatrix(*Z));\n  *tRef = *ref;\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testAssignment0: \", (*tRef) == (*ref), true);\n  ref.reset(new SimpleMatrix(*I));\n  *tRef = *ref;\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testAssignment0: \", (*tRef) == (*ref), true);\n\n  // Sparse => Sparse or Zero\n  ref.reset(new SimpleMatrix(*SP));\n  tRef.reset(new SimpleMatrix(*SP));\n  tRef->zero();\n  *tRef = *ref;\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testAssignment0: \", (*tRef) == (*ref), true);\n\n  ref.reset(new SimpleMatrix(*Z2));\n  *tRef = *ref;\n\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testAssignment0: \", (*tRef) == (*ref), true);\n\n  // // Sparse coordinate => Sparse\n  ref.reset(new SimpleMatrix(*SP_coor));\n  //ref->display();\n  tRef.reset(new SimpleMatrix(*SP));\n  tRef->zero();\n  *tRef = *ref;\n  //tRef->displayExpert();\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testAssignment0: \", (*tRef) == (*ref), true);\n\n\n  // Banded = Banded, Id or Zero\n  ref.reset(new SimpleMatrix(*Band));\n  tRef.reset(new SimpleMatrix(*Band));\n  tRef->zero();\n  *tRef = *ref;\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testAssignment0: \", (*tRef) == (*ref), true);\n  ref.reset(new SimpleMatrix(*Z2));\n  *tRef = *ref;\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testAssignment0: \", (*tRef) == (*ref), true);\n  ref.reset(new SimpleMatrix(*I2));\n  *tRef = *ref;\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testAssignment0: \", (*tRef) == (*ref), true);\n\n\n\n  std::cout << \"-->  test assignment0 ended with success.\" <<std::endl;\n}\n\nvoid SimpleMatrixTest::testAssignment1()\n{\n  std::cout << \"--> Test: assignment1.\" <<std::endl;\n\n  // Simple = Siconos(Block)\n\n  *C = *Ab;\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testAssignment1: \", (*C) == (*Ab), true);\n  std::cout << \"-->  test assignment1 ended with success.\" <<std::endl;\n}\n\nvoid SimpleMatrixTest::testAssignment2()\n{\n  std::cout << \"--> Test: assignment2.\" <<std::endl;\n\n  // Simple = Siconos(Simple)\n\n  SP::SiconosMatrix ref(new SimpleMatrix(*D));\n  SP::SiconosMatrix tRef(new SimpleMatrix(*SicM));\n  // Dense = any type:\n  *tRef = *ref;\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testAssignment2: \", (*tRef) == (*ref), true);\n\n  ref.reset(new SimpleMatrix(*T));\n  SP::SiconosMatrix tRef3(new SimpleMatrix(3, 3));\n  *tRef3 = *ref;\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testAssignment2: \", (*tRef3) == (*ref), true);\n\n  ref.reset(new SimpleMatrix(*S));\n  *tRef3 = *ref;\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testAssignment2: \", (*tRef3) == (*ref), true);\n\n  SP::SiconosMatrix tRef4(new SimpleMatrix(4, 4));\n  ref.reset(new SimpleMatrix(*SP));\n  *tRef4 = *ref;\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testAssignment2: \", (*tRef4) == (*ref), true);\n\n  ref.reset(new SimpleMatrix(*Band));\n  *tRef4 = *ref;\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testAssignment2: \", (*tRef4) == (*ref), true);\n  ref.reset(new SimpleMatrix(*Z));\n  *tRef3 = *ref;\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testAssignment2: \", (*tRef3) == (*ref), true);\n\n  ref.reset(new SimpleMatrix(*I));\n  *tRef3 = *ref;\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testAssignment2: \", (*tRef3) == (*ref), true);\n  // Triang = Triang, Zero or Identity\n  ref.reset(new SimpleMatrix(*T));\n  tRef.reset(new SimpleMatrix(*T));\n  tRef->zero();\n  *tRef = *ref;\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testAssignment2: \", (*tRef) == (*ref), true);\n\n  ref.reset(new SimpleMatrix(*Z));\n  *tRef = *ref;\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testAssignment2: \", (*tRef) == (*ref), true);\n\n  ref.reset(new SimpleMatrix(*I));\n  *tRef = *ref;\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testAssignment2: \", (*tRef) == (*ref), true);\n  // Sym = Sym, Zero or Id\n  ref.reset(new SimpleMatrix(*S));\n  tRef.reset(new SimpleMatrix(*S));\n  tRef->zero();\n  *tRef = *ref;\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testAssignment2: \", (*tRef) == (*ref), true);\n  ref.reset(new SimpleMatrix(*Z));\n  *tRef = *ref;\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testAssignment2: \", (*tRef) == (*ref), true);\n\n  ref.reset(new SimpleMatrix(*I));\n  *tRef = *ref;\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testAssignment2: \", (*tRef) == (*ref), true);\n  // Sparse = Sparse or Zero\n  ref.reset(new SimpleMatrix(*SP));\n  tRef.reset(new SimpleMatrix(*SP));\n  tRef->zero();\n  *tRef = *ref;\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testAssignment2: \", (*tRef) == (*ref), true);\n\n  ref.reset(new SimpleMatrix(*Z2));\n  *tRef = *ref;\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testAssignment2: \", (*tRef) == (*ref), true);\n  // Banded = Banded, Id or Zero\n  ref.reset(new SimpleMatrix(*Band));\n  tRef.reset(new SimpleMatrix(*Band));\n  tRef->zero();\n  *tRef = *ref;\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testAssignment2: \", (*tRef) == (*ref), true);\n\n  ref.reset(new SimpleMatrix(*Z2));\n  *tRef = *ref;\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testAssignment2: \", (*tRef) == (*ref), true);\n  ref.reset(new SimpleMatrix(*I2));\n  *tRef = *ref;\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testAssignment2: \", (*tRef) == (*ref), true);\n  std::cout << \"-->  test assignment2 ended with success.\" <<std::endl;\n}\n\nvoid SimpleMatrixTest::testOperators1()\n{\n  std::cout << \"--> Test: operators1.\" <<std::endl;\n  //+=, -=, *=, /=\n\n  SP::SiconosMatrix tmp(new SimpleMatrix(*D));\n  // Dense *=, /=\n  double a = 2.2;\n  int a1 = 2;\n  *tmp *= a;\n  for(unsigned int i = 0; i < tmp->size(0); ++i)\n    for(unsigned int j = 0 ; j < tmp->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*tmp)(i, j) - a * (*D)(i, j)) < tol, true);\n\n  *tmp *= a1;\n  for(unsigned int i = 0; i < tmp->size(0); ++i)\n    for(unsigned int j = 0 ; j < tmp->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*tmp)(i, j) - a * a1 * (*D)(i, j)) < tol, true);\n\n  *tmp /= a;\n  for(unsigned int i = 0; i < tmp->size(0); ++i)\n    for(unsigned int j = 0 ; j < tmp->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*tmp)(i, j) - a1 * (*D)(i, j)) < tol, true);\n\n  *tmp /= a1;\n  for(unsigned int i = 0; i < tmp->size(0); ++i)\n    for(unsigned int j = 0 ; j < tmp->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*tmp)(i, j) - (*D)(i, j)) < tol, true);\n\n  // Dense +=, -= Dense\n\n  *tmp += *SicM;\n  for(unsigned int i = 0; i < tmp->size(0); ++i)\n    for(unsigned int j = 0 ; j < tmp->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*tmp)(i, j) - (*SicM)(i, j) - (*D)(i, j)) < tol, true);\n\n  *tmp -= *SicM;\n  for(unsigned int i = 0; i < tmp->size(0); ++i)\n    for(unsigned int j = 0 ; j < tmp->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*tmp)(i, j) - (*D)(i, j)) < tol, true);\n\n  // Dense +=, -= Block\n  C->zero();\n  *C += *Ab;\n  *C += *Ab;\n  for(unsigned int i = 0; i < C->size(0); ++i)\n    for(unsigned int j = 0 ; j < C->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*C)(i, j) - 2 * (*Ab)(i, j)) < tol, true);\n  *C -= *Ab;\n  for(unsigned int i = 0; i < C->size(0); ++i)\n    for(unsigned int j = 0 ; j < C->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*C)(i, j) - (*Ab)(i, j)) < tol, true);\n\n  std::cout << \"-->  test operators1 ended with success.\" <<std::endl;\n}\n\nvoid SimpleMatrixTest::testOperators2()\n{\n  std::cout << \"--> Test: operators2.\" <<std::endl;\n  // +=, -=, *=, /= triangular\n  SP::SiconosMatrix tmp(new SimpleMatrix(*T));\n  SP::SiconosMatrix tmp2(new SimpleMatrix(*T));\n  *tmp += *tmp2;\n  for(unsigned int i = 0; i < tmp->size(0); ++i)\n    for(unsigned int j = i ; j < tmp->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", (*tmp)(i, j) == 2.0 * (*T)(i, j), true);\n\n  int mult = 2;\n  double mult0 = 2.2;\n  *tmp *= mult0;\n  for(unsigned int i = 0; i < tmp->size(0); ++i)\n    for(unsigned int j = i ; j < tmp->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", ((*tmp)(i, j) - 2.0 * mult0 * (*T)(i, j)) < tol, true);\n\n  *tmp *= mult;\n  for(unsigned int i = 0; i < tmp->size(0); ++i)\n    for(unsigned int j = i ; j < tmp->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", ((*tmp)(i, j) - 2.0 * mult * mult0 * (*T)(i, j)) < tol, true);\n\n  *tmp /= mult;\n  for(unsigned int i = 0; i < tmp->size(0); ++i)\n    for(unsigned int j = i ; j < tmp->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", ((*tmp)(i, j) - 2.0 * mult0 * (*T)(i, j)) < tol, true);\n\n  *tmp /= mult0;\n  for(unsigned int i = 0; i < tmp->size(0); ++i)\n    for(unsigned int j = i ; j < tmp->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", (*tmp)(i, j) == 2 * (*T)(i, j), true);\n\n  *tmp -= *tmp2;\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", norm_inf(tmp->getTriang() - *T) == 0, true);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", tmp->num() == Siconos::TRIANGULAR, true);\n\n  std::cout << \"-->  test operators2 ended with success.\" <<std::endl;\n}\n\nvoid SimpleMatrixTest::testOperators3()\n{\n  std::cout << \"--> Test: operators3.\" <<std::endl;\n  // +=, -=, *=, /= Symmetric\n  SP::SiconosMatrix tmp(new SimpleMatrix(*S));\n  SP::SiconosMatrix tmp2(new SimpleMatrix(*S));\n  *tmp += *tmp2;\n  for(unsigned int i = 0; i < tmp->size(0); ++i)\n    for(unsigned int j = i ; j < tmp->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", (*tmp)(i, j) == 2.0 * (*S)(i, j), true);\n\n  int mult = 2;\n  double mult0 = 2.2;\n  *tmp *= mult0;\n  for(unsigned int i = 0; i < tmp->size(0); ++i)\n    for(unsigned int j = i ; j < tmp->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", ((*tmp)(i, j) - 2.0 * mult0 * (*S)(i, j)) < tol, true);\n\n  *tmp *= mult;\n  for(unsigned int i = 0; i < tmp->size(0); ++i)\n    for(unsigned int j = i ; j < tmp->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", ((*tmp)(i, j) - 2.0 * mult * mult0 * (*S)(i, j)) < tol, true);\n\n  *tmp /= mult;\n  for(unsigned int i = 0; i < tmp->size(0); ++i)\n    for(unsigned int j = i ; j < tmp->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", ((*tmp)(i, j) - 2.0 * mult0 * (*S)(i, j)) < tol, true);\n\n  *tmp /= mult0;\n  for(unsigned int i = 0; i < tmp->size(0); ++i)\n    for(unsigned int j = i ; j < tmp->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", (*tmp)(i, j) == 2 * (*S)(i, j), true);\n\n  *tmp -= *tmp2;\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", norm_inf(tmp->getSym() - *S) == 0, true);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", tmp->num() == Siconos::SYMMETRIC, true);\n\n  std::cout << \"-->  test operators3 ended with success.\" <<std::endl;\n}\n\nvoid SimpleMatrixTest::testOperators4()\n{\n  std::cout << \"--> Test: operators4.\" <<std::endl;\n  // +=, -=, *=, /= sparse\n  SP::SiconosMatrix tmp(new SimpleMatrix(*SP));\n  SP::SiconosMatrix tmp2(new SimpleMatrix(*SP));\n  SP::SiconosMatrix tmp3(new SimpleMatrix(*T2));\n\n  SP::SiconosMatrix tmp4(new SimpleMatrix(*Band));\n  SP::SiconosMatrix tmp5(new SimpleMatrix(*S2));\n\n  *tmp += *tmp2;\n  for(unsigned int i = 0; i < tmp->size(0); ++i)\n    for(unsigned int j = 0 ; j < tmp->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", ((*tmp)(i, j) - 2.0 * (*SP)(i, j)) < tol, true);\n\n  int mult = 2;\n  double mult0 = 2.2;\n  *tmp *= mult0;\n  for(unsigned int i = 0; i < tmp->size(0); ++i)\n    for(unsigned int j = 0 ; j < tmp->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", ((*tmp)(i, j) - 2.0 * mult0 * (*SP)(i, j)) < tol, true);\n\n  *tmp *= mult;\n  for(unsigned int i = 0; i < tmp->size(0); ++i)\n    for(unsigned int j = 0 ; j < tmp->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", ((*tmp)(i, j) - 2.0 * mult * mult0 * (*SP)(i, j)) < tol, true);\n\n  *tmp /= mult;\n  for(unsigned int i = 0; i < tmp->size(0); ++i)\n    for(unsigned int j = 0 ; j < tmp->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", ((*tmp)(i, j) - 2.0 * mult0 * (*SP)(i, j)) < tol, true);\n\n  *tmp /= mult0;\n  for(unsigned int i = 0; i < tmp->size(0); ++i)\n    for(unsigned int j = 0 ; j < tmp->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", ((*tmp)(i, j) - 2 * (*SP)(i, j)) < tol, true);\n\n  *tmp -= *tmp2;\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", norm_inf(tmp->getSparse() - *SP) == 0, true);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", tmp->num() == Siconos::SPARSE, true);\n\n  // += -= a triangular\n  *tmp += *tmp3;\n  for(unsigned int i = 0; i < tmp->size(0); ++i)\n  {\n    for(unsigned int j = 0; j < i; ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", ((*tmp)(i, j) - (*SP)(i, j)) < tol, true);\n    for(unsigned int j = i ; j < tmp->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", ((*tmp)(i, j) - (*SP)(i, j) - (*tmp3)(i, j)) < tol, true);\n  }\n\n  *tmp -= *tmp3;\n  for(unsigned int i = 0; i < tmp->size(0); ++i)\n    for(unsigned int j = 0; j < tmp->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", ((*tmp)(i, j) - (*SP)(i, j)) < tol, true);\n\n  // += -= a banded\n  *tmp -= *tmp;\n  *tmp += *tmp4;\n  for(signed i = 0; i < signed(Band->size1()); ++ i)\n    for(signed j = std::max(i - 1, 0); j < std::min(i + 2, signed(Band->size2())); ++ j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", ((*tmp)(i, j) - (*Band)(i, j)) < tol, true);\n\n  *tmp -= *tmp4;\n  for(unsigned int i = 0; i < tmp->size(0); ++i)\n    for(unsigned int j = 0; j < tmp->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", (*tmp)(i, j) < tol, true);\n\n  // += -= a sym\n\n  *tmp += *tmp5;\n  for(unsigned int i = 0; i < tmp->size(0); ++i)\n  {\n    for(unsigned int j = 0; j < i; ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", ((*tmp)(i, j) - (*SP)(i, j) - (*tmp5)(j, i)) < tol, true);\n    for(unsigned int j = i ; j < tmp->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", ((*tmp)(i, j) - (*SP)(i, j) - (*tmp5)(i, j)) < tol, true);\n  }\n\n  *tmp -= *tmp5;\n  for(unsigned int i = 0; i < tmp->size(0); ++i)\n    for(unsigned int j = 0; j < tmp->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", ((*tmp)(i, j) - (*SP)(i, j)) < tol, true);\n\n  std::cout << \"-->  test operators4 ended with success.\" <<std::endl;\n}\nvoid SimpleMatrixTest::testOperators4bis()\n{\n  std::cout << \"--> Test: operators4bis.\" <<std::endl;\n  // +=, -=, *=, /= sparse\n  SP::SiconosMatrix tmp(new SimpleMatrix(*SP_coor));\n  SP::SiconosMatrix tmp2(new SimpleMatrix(*SP_coor));\n  SP::SiconosMatrix tmp3(new SimpleMatrix(*T2));\n\n  SP::SiconosMatrix tmp4(new SimpleMatrix(*Band));\n  SP::SiconosMatrix tmp5(new SimpleMatrix(*S2));\n\n  SP::SiconosMatrix tmp6(new SimpleMatrix(*SP));\n\n\n  *tmp += *tmp2;\n  for(unsigned int i = 0; i < tmp->size(0); ++i)\n    for(unsigned int j = 0 ; j < tmp->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", ((*tmp)(i, j) - 2.0 * (*SP_coor)(i, j)) < tol, true);\n\n  int mult = 2;\n  double mult0 = 2.2;\n  *tmp *= mult0;\n  for(unsigned int i = 0; i < tmp->size(0); ++i)\n    for(unsigned int j = 0 ; j < tmp->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", ((*tmp)(i, j) - 2.0 * mult0 * (*SP_coor)(i, j)) < tol, true);\n\n  *tmp *= mult;\n  for(unsigned int i = 0; i < tmp->size(0); ++i)\n    for(unsigned int j = 0 ; j < tmp->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", ((*tmp)(i, j) - 2.0 * mult * mult0 * (*SP_coor)(i, j)) < tol, true);\n\n  *tmp /= mult;\n  for(unsigned int i = 0; i < tmp->size(0); ++i)\n    for(unsigned int j = 0 ; j < tmp->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", ((*tmp)(i, j) - 2.0 * mult0 * (*SP_coor)(i, j)) < tol, true);\n\n  *tmp /= mult0;\n  for(unsigned int i = 0; i < tmp->size(0); ++i)\n    for(unsigned int j = 0 ; j < tmp->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", ((*tmp)(i, j) - 2 * (*SP_coor)(i, j)) < tol, true);\n\n  *tmp -= *tmp2;\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", norm_inf(tmp->getSparseCoordinate() - *SP_coor) == 0, true);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", tmp->num() == SPARSE_COORDINATE, true);\n\n  // += -= a triangular\n  *tmp += *tmp3;\n  for(unsigned int i = 0; i < tmp->size(0); ++i)\n  {\n    for(unsigned int j = 0; j < i; ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", ((*tmp)(i, j) - (*SP_coor)(i, j)) < tol, true);\n    for(unsigned int j = i ; j < tmp->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", ((*tmp)(i, j) - (*SP_coor)(i, j) - (*tmp3)(i, j)) < tol, true);\n  }\n\n  *tmp -= *tmp3;\n  for(unsigned int i = 0; i < tmp->size(0); ++i)\n    for(unsigned int j = 0; j < tmp->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", ((*tmp)(i, j) - (*SP_coor)(i, j)) < tol, true);\n\n  // += -= a banded\n  *tmp -= *tmp;\n  *tmp += *tmp4;\n  for(signed i = 0; i < signed(Band->size1()); ++ i)\n    for(signed j = std::max(i - 1, 0); j < std::min(i + 2, signed(Band->size2())); ++ j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", ((*tmp)(i, j) - (*Band)(i, j)) < tol, true);\n\n  *tmp -= *tmp4;\n  for(unsigned int i = 0; i < tmp->size(0); ++i)\n    for(unsigned int j = 0; j < tmp->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", (*tmp)(i, j) < tol, true);\n\n  // += -= a sym\n\n  *tmp += *tmp5;\n  for(unsigned int i = 0; i < tmp->size(0); ++i)\n  {\n    for(unsigned int j = 0; j < i; ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", ((*tmp)(i, j) - (*SP_coor)(i, j) - (*tmp5)(j, i)) < tol, true);\n    for(unsigned int j = i ; j < tmp->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", ((*tmp)(i, j) - (*SP_coor)(i, j) - (*tmp5)(i, j)) < tol, true);\n  }\n\n  *tmp -= *tmp5;\n  for(unsigned int i = 0; i < tmp->size(0); ++i)\n    for(unsigned int j = 0; j < tmp->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", ((*tmp)(i, j) - (*SP_coor)(i, j)) < tol, true);\n\n  // += -= a sparse\n\n  *tmp += *tmp6;\n  for(unsigned int i = 0; i < tmp->size(0); ++i)\n  {\n    for(unsigned int j = 0; j < i; ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", ((*tmp)(i, j) - (*SP_coor)(i, j) - (*tmp6)(j, i)) < tol, true);\n    for(unsigned int j = i ; j < tmp->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", ((*tmp)(i, j) - (*SP_coor)(i, j) - (*tmp6)(i, j)) < tol, true);\n  }\n\n  *tmp -= *tmp6;\n  for(unsigned int i = 0; i < tmp->size(0); ++i)\n    for(unsigned int j = 0; j < tmp->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", ((*tmp)(i, j) - (*SP_coor)(i, j)) < tol, true);\n\n  std::cout << \"-->  test operators4bis ended with success.\" <<std::endl;\n}\nvoid SimpleMatrixTest::testOperators5()\n{\n  std::cout << \"--> Test: operators5.\" <<std::endl;\n  // +=, -=, *=, /= banded\n  SP::SiconosMatrix tmp(new SimpleMatrix(*Band));\n  SP::SiconosMatrix tmp2(new SimpleMatrix(*Band));\n  *tmp += *tmp2;\n  for(signed i = 0; i < signed(Band->size1()); ++ i)\n    for(signed j = std::max(i - 1, 0); j < std::min(i + 2, signed(Band->size2())); ++ j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", (*tmp)(i, j) == 2.0 * (*Band)(i, j), true);\n\n  int mult = 2;\n  double mult0 = 2.2;\n  *tmp *= mult0;\n  for(signed i = 0; i < signed(Band->size1()); ++ i)\n    for(signed j = std::max(i - 1, 0); j < std::min(i + 2, signed(Band->size2())); ++ j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", ((*tmp)(i, j) - 2.0 * mult0 * (*Band)(i, j)) < tol, true);\n\n  *tmp *= mult;\n  for(signed i = 0; i < signed(Band->size1()); ++ i)\n    for(signed j = std::max(i - 1, 0); j < std::min(i + 2, signed(Band->size2())); ++ j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", ((*tmp)(i, j) - 2.0 * mult * mult0 * (*Band)(i, j)) < tol, true);\n\n  *tmp /= mult;\n  for(signed i = 0; i < signed(Band->size1()); ++ i)\n    for(signed j = std::max(i - 1, 0); j < std::min(i + 2, signed(Band->size2())); ++ j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", ((*tmp)(i, j) - 2.0 * mult0 * (*Band)(i, j)) < tol, true);\n\n  *tmp /= mult0;\n  for(signed i = 0; i < signed(Band->size1()); ++ i)\n    for(signed j = std::max(i - 1, 0); j < std::min(i + 2, signed(Band->size2())); ++ j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", (*tmp)(i, j) == 2 * (*Band)(i, j), true);\n\n  *tmp -= *tmp2;\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", norm_inf(tmp->getBanded() - *Band) == 0, true);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", tmp->num() == Siconos::BANDED, true);\n\n  std::cout << \"-->  test operators5 ended with success.\" <<std::endl;\n}\n\nvoid SimpleMatrixTest::testOperators6()\n{\n  std::cout << \"--> Test: operator6.\" <<std::endl;\n\n  // ============= C = A + B =============\n\n  // Dense = Dense + Dense\n  C->zero();\n  *C = *A + *B;\n  for(unsigned int i = 0; i < C->size(0); ++i)\n    for(unsigned int j = 0 ; j < C->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators6: \", fabs((*C)(i, j) - (*A)(i, j) - (*B)(i, j)) < tol, true);\n\n  C->zero();\n  // Dense = Dense + Block\n  *C = *A + *Ab;\n  for(unsigned int i = 0; i < C->size(0); ++i)\n    for(unsigned int j = 0 ; j < C->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators6: \", fabs((*C)(i, j) - (*A)(i, j) - (*Ab)(i, j)) < tol, true);\n\n  C->zero();\n  // Dense = Block + Dense\n  *C = *Ab + *A;\n  for(unsigned int i = 0; i < C->size(0); ++i)\n    for(unsigned int j = 0 ; j < C->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators6: \", fabs((*C)(i, j) - (*A)(i, j) - (*Ab)(i, j)) < tol, true);\n\n  C->zero();\n\n  // Dense = Block + Block\n  *C = *Ab + *Ab;\n  for(unsigned int i = 0; i < C->size(0); ++i)\n    for(unsigned int j = 0 ; j < C->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators6: \", fabs((*C)(i, j) - (*Ab)(i, j) - (*Ab)(i, j)) < tol, true);\n\n  C->zero();\n\n  // Block = Dense + Dense\n  Cb->zero();\n  *Cb = *A + *B;\n  for(unsigned int i = 0; i < Cb->size(0); ++i)\n    for(unsigned int j = 0 ; j < Cb->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators6: \", fabs((*Cb)(i, j) - (*A)(i, j) - (*B)(i, j)) < tol, true);\n\n  // Block = Dense + Block\n\n  Cb->zero();\n  *Cb = *A + *Ab;\n  for(unsigned int i = 0; i < Cb->size(0); ++i)\n    for(unsigned int j = 0 ; j < Cb->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators6: \", fabs((*Cb)(i, j) - (*A)(i, j) - (*Ab)(i, j)) < tol, true);\n\n\n  // Block = Block + Dense\n\n  Cb->zero();\n  *Cb = *Ab + *A;\n  for(unsigned int i = 0; i < Cb->size(0); ++i)\n    for(unsigned int j = 0 ; j < Cb->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators6: \", fabs((*Cb)(i, j) - (*Ab)(i, j) - (*A)(i, j)) < tol, true);\n\n\n  // Block = Block + Block\n\n  Cb->zero();\n  *Cb = *Ab + *Bb;\n  for(unsigned int i = 0; i < Cb->size(0); ++i)\n    for(unsigned int j = 0 ; j < Cb->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators6: \", fabs((*Cb)(i, j) - (*Ab)(i, j) - (*Bb)(i, j)) < tol, true);\n  Cb->zero();\n\n  // ============= C = A - B =============\n\n  // Dense = Dense - Dense\n  C->zero();\n  *C = *A - *B;\n  for(unsigned int i = 0; i < C->size(0); ++i)\n    for(unsigned int j = 0 ; j < C->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators6: \", fabs((*C)(i, j) - (*A)(i, j) + (*B)(i, j)) < tol, true);\n\n  C->zero();\n  // Dense = Dense - Block\n  *C = *A - *Ab;\n  for(unsigned int i = 0; i < C->size(0); ++i)\n    for(unsigned int j = 0 ; j < C->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators6: \", fabs((*C)(i, j) - (*A)(i, j) + (*Ab)(i, j)) < tol, true);\n\n  C->zero();\n  // Dense = Block - Dense\n  *C = *Ab - *A;\n  for(unsigned int i = 0; i < C->size(0); ++i)\n    for(unsigned int j = 0 ; j < C->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators6: \", fabs((*C)(i, j) + (*A)(i, j) - (*Ab)(i, j)) < tol, true);\n\n  C->zero();\n\n  // Dense = Block - Block\n  *C = *Ab - *Bb;\n  for(unsigned int i = 0; i < C->size(0); ++i)\n    for(unsigned int j = 0 ; j < C->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators6: \", fabs((*C)(i, j) - (*Ab)(i, j) + (*Bb)(i, j)) < tol, true);\n\n  C->zero();\n\n  // Block = Dense - Dense\n  Cb->zero();\n  *Cb = *A - *B;\n  for(unsigned int i = 0; i < Cb->size(0); ++i)\n    for(unsigned int j = 0 ; j < Cb->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators6: \", fabs((*Cb)(i, j) - (*A)(i, j) + (*B)(i, j)) < tol, true);\n\n  // Block = Dense - Block\n\n  Cb->zero();\n  *Cb = *A - *Ab;\n  for(unsigned int i = 0; i < Cb->size(0); ++i)\n    for(unsigned int j = 0 ; j < Cb->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators6: \", fabs((*Cb)(i, j) - (*A)(i, j) + (*Ab)(i, j)) < tol, true);\n\n\n  // Block = Block - Dense\n\n  Cb->zero();\n  *Cb = *Ab - *A;\n  for(unsigned int i = 0; i < Cb->size(0); ++i)\n    for(unsigned int j = 0 ; j < Cb->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators6: \", fabs((*Cb)(i, j) - (*Ab)(i, j) + (*A)(i, j)) < tol, true);\n\n\n  // Block = Block - Block\n\n  Cb->zero();\n  *Cb = *Ab - *Bb;\n  for(unsigned int i = 0; i < Cb->size(0); ++i)\n    for(unsigned int j = 0 ; j < Cb->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators6: \", fabs((*Cb)(i, j) - (*Ab)(i, j) + (*Bb)(i, j)) < tol, true);\n  Cb->zero();\n  std::cout << \"-->  test operators6 ended with success.\" <<std::endl;\n}\n\nvoid SimpleMatrixTest::testOperators6Bis()\n{\n  std::cout << \"--> Test: operator6Bis.\" <<std::endl;\n\n  // ============= C = A + B =============\n\n  // Dense = Dense + Dense\n  C->zero();\n  add(*A, *B, *C);\n  for(unsigned int i = 0; i < C->size(0); ++i)\n    for(unsigned int j = 0 ; j < C->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators6Bis: \", fabs((*C)(i, j) - (*A)(i, j) - (*B)(i, j)) < tol, true);\n\n  C->zero();\n  // Dense = Dense + Block\n  add(*A, *Ab, *C);\n  for(unsigned int i = 0; i < C->size(0); ++i)\n    for(unsigned int j = 0 ; j < C->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators6Bis: \", fabs((*C)(i, j) - (*A)(i, j) - (*Ab)(i, j)) < tol, true);\n\n  C->zero();\n  // Dense = Block + Dense\n  add(*Ab, *A, *C);\n  for(unsigned int i = 0; i < C->size(0); ++i)\n    for(unsigned int j = 0 ; j < C->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators6Bis: \", fabs((*C)(i, j) - (*A)(i, j) - (*Ab)(i, j)) < tol, true);\n\n  C->zero();\n\n  // Dense = Block + Block\n  add(*Ab, *Ab, *C);\n  for(unsigned int i = 0; i < C->size(0); ++i)\n    for(unsigned int j = 0 ; j < C->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators6Bis: \", fabs((*C)(i, j) - (*Ab)(i, j) - (*Ab)(i, j)) < tol, true);\n\n  C->zero();\n\n  // Block = Dense + Dense\n  Cb->zero();\n  add(*A, *B, *Cb);\n  for(unsigned int i = 0; i < Cb->size(0); ++i)\n    for(unsigned int j = 0 ; j < Cb->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators6Bis: \", fabs((*Cb)(i, j) - (*A)(i, j) - (*B)(i, j)) < tol, true);\n\n  // Block = Dense + Block\n\n  Cb->zero();\n  add(*A, *Ab, *Cb);\n  for(unsigned int i = 0; i < Cb->size(0); ++i)\n    for(unsigned int j = 0 ; j < Cb->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators6Bis: \", fabs((*Cb)(i, j) - (*A)(i, j) - (*Ab)(i, j)) < tol, true);\n\n\n  // Block = Block + Dense\n\n  Cb->zero();\n  add(*Ab, *A, *Cb);\n  for(unsigned int i = 0; i < Cb->size(0); ++i)\n    for(unsigned int j = 0 ; j < Cb->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators6Bis: \", fabs((*Cb)(i, j) - (*Ab)(i, j) - (*A)(i, j)) < tol, true);\n\n\n  // Block = Block + Block\n\n  Cb->zero();\n  add(*Ab, *Bb, *Cb);\n  for(unsigned int i = 0; i < Cb->size(0); ++i)\n    for(unsigned int j = 0 ; j < Cb->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators6Bis: \", fabs((*Cb)(i, j) - (*Ab)(i, j) - (*Bb)(i, j)) < tol, true);\n  Cb->zero();\n\n  // ============= C = A - B =============\n\n  // Dense = Dense - Dense\n  C->zero();\n  sub(*A, *B, *C);\n  for(unsigned int i = 0; i < C->size(0); ++i)\n    for(unsigned int j = 0 ; j < C->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators6Bis: \", fabs((*C)(i, j) - (*A)(i, j) + (*B)(i, j)) < tol, true);\n\n  C->zero();\n  // Dense = Dense - Block\n  sub(*A, *Ab, *C);\n  for(unsigned int i = 0; i < C->size(0); ++i)\n    for(unsigned int j = 0 ; j < C->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators6Bis: \", fabs((*C)(i, j) - (*A)(i, j) + (*Ab)(i, j)) < tol, true);\n\n  C->zero();\n  // Dense = Block - Dense\n  sub(*Ab, *A, *C);\n  for(unsigned int i = 0; i < C->size(0); ++i)\n    for(unsigned int j = 0 ; j < C->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators6Bis: \", fabs((*C)(i, j) + (*A)(i, j) - (*Ab)(i, j)) < tol, true);\n\n  C->zero();\n\n  // Dense = Block - Block\n  sub(*Ab, *Bb, *C);\n  for(unsigned int i = 0; i < C->size(0); ++i)\n    for(unsigned int j = 0 ; j < C->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators6Bis: \", fabs((*C)(i, j) - (*Ab)(i, j) + (*Bb)(i, j)) < tol, true);\n\n  C->zero();\n\n  // Block = Dense - Dense\n  Cb->zero();\n  sub(*A, *B, *Cb);\n  for(unsigned int i = 0; i < Cb->size(0); ++i)\n    for(unsigned int j = 0 ; j < Cb->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators6Bis: \", fabs((*Cb)(i, j) - (*A)(i, j) + (*B)(i, j)) < tol, true);\n\n  // Block = Dense - Block\n\n  Cb->zero();\n  sub(*A, *Ab, *Cb);\n  for(unsigned int i = 0; i < Cb->size(0); ++i)\n    for(unsigned int j = 0 ; j < Cb->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators6Bis: \", fabs((*Cb)(i, j) - (*A)(i, j) + (*Ab)(i, j)) < tol, true);\n\n\n  // Block = Block - Dense\n\n  Cb->zero();\n  sub(*Ab, *A, *Cb);\n  for(unsigned int i = 0; i < Cb->size(0); ++i)\n    for(unsigned int j = 0 ; j < Cb->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators6Bis: \", fabs((*Cb)(i, j) - (*Ab)(i, j) + (*A)(i, j)) < tol, true);\n\n\n  // Block = Block - Block\n\n  Cb->zero();\n  sub(*Ab, *Bb, *Cb);\n  for(unsigned int i = 0; i < Cb->size(0); ++i)\n    for(unsigned int j = 0 ; j < Cb->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators6Bis: \", fabs((*Cb)(i, j) - (*Ab)(i, j) + (*Bb)(i, j)) < tol, true);\n  Cb->zero();\n  std::cout << \"-->  test operators6Bis ended with success.\" <<std::endl;\n}\n\nvoid SimpleMatrixTest::testOperators6Ter()\n{\n  std::cout << \"--> Test: operator6Ter.\" <<std::endl;\n\n  // +, - for non-dense matrices.\n\n  // Triang +,-,* Triang\n  SP::SiconosMatrix tmp(new SimpleMatrix(*T));\n  SP::SiconosMatrix tmp2(new SimpleMatrix(*T));\n  SP::SiconosMatrix res(new SimpleMatrix(3, 3, TRIANGULAR));\n  *res = *tmp + *tmp2;\n  for(unsigned int i = 0; i < res->size(0); ++i)\n    for(unsigned int j = i ; j < res->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators6Ter: \", (*res)(i, j) == ((*T)(i, j) + (*T)(i, j)), true);\n\n  *res = *tmp - *tmp2;\n  for(unsigned int i = 0; i < res->size(0); ++i)\n    for(unsigned int j = i ; j < res->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators6Ter: \", (*res)(i, j) == 0, true);\n\n  // prod(*tmp, *tmp2, *res);\n  // prod(*T,*T, *tmp, true);\n  // CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators6Ter: \", norm_inf(res->getTriang() - *tmp) == 0, true);\n\n\n  // Sym +,-,* Sym\n  tmp.reset(new SimpleMatrix(*S));\n  tmp2.reset(new SimpleMatrix(*S));\n  res.reset(new SimpleMatrix(3, 3, SYMMETRIC));\n  *res = *tmp + *tmp2;\n  for(unsigned int i = 0; i < res->size(0); ++i)\n    for(unsigned int j = i ; j < res->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators6Ter: \", (*res)(i, j) == ((*S)(i, j) + (*S)(i, j)), true);\n\n  *res = *tmp - *tmp2;\n  for(unsigned int i = 0; i < res->size(0); ++i)\n    for(unsigned int j = i ; j < res->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators6Ter: \", (*res)(i, j) == 0, true);\n\n  // prod(*tmp , *tmp2, *res, true);\n\n  // CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators6Ter: \", norm_inf(res->getSym() - prod(*S, *S)) == 0, true);\n\n\n  // Sparse +,-,* Sparse\n  tmp.reset(new SimpleMatrix(*SP));\n  tmp2.reset(new SimpleMatrix(*SP));\n  res.reset(new SimpleMatrix(4, 4, Siconos::SPARSE));\n  *res = *tmp + *tmp2;\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators6Ter: \", (*res) == (2.0 * (*tmp)), true);\n\n  // *res = prod(*tmp , *tmp2);\n  // CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators6Ter: \", norm_inf(*res->sparse() - prod(*SP, *SP)) < tol, true);\n\n  *res = *tmp - *tmp2;\n  tmp->zero();\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators6Ter: \", (*res) == *tmp, true);\n\n  // SparseCoordinate +,-,* SparseCoordinate\n\n  tmp.reset(new SimpleMatrix(*SP_coor));\n  tmp2.reset(new SimpleMatrix(*SP_coor));\n  res.reset(new SimpleMatrix(4, 4, Siconos::SPARSE_COORDINATE));\n  *res = *tmp + *tmp2;\n\n  // res->displayExpert();\n  // tmp->displayExpert();\n  // tmp2->displayExpert();\n\n\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators6Ter: \", (*res) == (2.0 * (*tmp)), true);\n\n  // *res = prod(*tmp , *tmp2);\n  // CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators6Ter: \", norm_inf(*res->sparseCoordinate() - prod(*SP_coor, *SP_coor)) < tol, true);\n\n  *res = *tmp - *tmp2;\n  tmp->zero();\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators6Ter: \", (*res) == *tmp, true);\n\n\n  // Banded +,- Banded\n  tmp.reset(new SimpleMatrix(*Band));\n  tmp2.reset(new SimpleMatrix(*Band));\n  res.reset(new SimpleMatrix(4, 4, BANDED));\n  *res = *tmp + *tmp2;\n  for(signed i = 0; i < signed(Band->size1()); ++ i)\n    for(signed j = std::max(i - 1, 0); j < std::min(i + 2, signed(Band->size2())); ++ j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators6Ter: \", (*res)(i, j) == ((*Band)(i, j) + (*Band)(i, j)), true);\n  *res = *tmp - *tmp2;\n  for(signed i = 0; i < signed(Band->size1()); ++ i)\n    for(signed j = std::max(i - 1, 0); j < std::min(i + 2, signed(Band->size2())); ++ j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators6Ter: \", (*res)(i, j) == 0, true);\n\n  std::cout << \"-->  test operators6Ter6 ended with success.\" <<std::endl;\n}\n\nvoid SimpleMatrixTest::testOperators7()\n{\n  std::cout << \"--> Test: operator7.\" <<std::endl;\n  SP::SiconosMatrix tmp1(new SimpleMatrix(*D));\n  tmp1->resize(4, 4);\n  SP::SiconosMatrix tmp2(new SimpleMatrix(*T2));\n  SP::SiconosMatrix tmp3(new SimpleMatrix(*S2));\n  SP::SiconosMatrix tmp4(new SimpleMatrix(*SP));\n  SP::SiconosMatrix tmp5(new SimpleMatrix(*Band));\n  SP::SiconosMatrix tmp6(new SimpleMatrix(*Z2));\n  SP::SiconosMatrix tmp7(new SimpleMatrix(*I2));\n\n  SP::SiconosMatrix res(new SimpleMatrix(4, 4));\n\n  // dense + ...\n  // ... triang\n  add(*tmp1, * tmp2, *res);\n  for(unsigned int i = 0; i < res->size(0); ++i)\n  {\n    for(unsigned int j = i ; j < res->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp1)(i, j) - (*tmp2)(i, j)) < tol, true);\n    for(unsigned int j = 0 ; j < i; ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp1)(i, j)) < tol, true);\n  }\n  // ... Sym\n  add(*tmp1, * tmp3, *res);\n  for(unsigned int i = 0; i < res->size(0); ++i)\n  {\n    for(unsigned int j = i ; j < res->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp1)(i, j) - (*tmp3)(i, j)) < tol, true);\n    for(unsigned int j = 0 ; j < i; ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp1)(i, j) - (*tmp3)(j, i)) < tol, true);\n  }\n  // ... Sparse\n  add(*tmp1, * tmp4, *res);\n  for(unsigned int i = 0; i < res->size(0); ++i)\n    for(unsigned int j = 0 ; j < res->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp1)(i, j) - (*tmp4)(i, j)) < tol, true);\n  // ... Banded\n  add(*tmp1, * tmp5, *res);\n  for(signed i = 0; i < signed(Band->size1()); ++ i)\n    for(signed j = std::max(i - 1, 0); j < std::min(i + 2, signed(Band->size2())); ++ j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp1)(i, j) - (*Band)(i, j)) < tol, true);\n  // Zero\n  add(*tmp1, * tmp6, *res);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", *res == *tmp1, true);\n\n  // Id\n  add(*tmp1, * tmp7, *res);\n  for(unsigned int i = 0; i < res->size(0); ++i)\n  {\n    for(unsigned int j = 0 ; j < res->size(1); ++j)\n    {\n      if(i == j)\n        CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp1)(i, j) - 1) < tol, true);\n      else\n        CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp1)(i, j)) < tol, true);\n    }\n  }\n\n  // dense - ...\n  // ... triangular\n  sub(*tmp1, * tmp2, *res);\n  for(unsigned int i = 0; i < res->size(0); ++i)\n  {\n    for(unsigned int j = i ; j < res->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp1)(i, j) + (*tmp2)(i, j)) < tol, true);\n    for(unsigned int j = 0 ; j < i; ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp1)(i, j)) < tol, true);\n  }\n  // ... Sym\n  sub(*tmp1, * tmp3, *res);\n  for(unsigned int i = 0; i < res->size(0); ++i)\n  {\n    for(unsigned int j = i ; j < res->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp1)(i, j) + (*tmp3)(i, j)) < tol, true);\n    for(unsigned int j = 0 ; j < i; ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp1)(i, j) + (*tmp3)(j, i)) < tol, true);\n  }\n  // ... Sparse\n  sub(*tmp1, * tmp4, *res);\n  for(unsigned int i = 0; i < res->size(0); ++i)\n    for(unsigned int j = 0 ; j < res->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp1)(i, j) + (*tmp4)(i, j)) < tol, true);\n  // ... Banded\n  sub(*tmp1, * tmp5, *res);\n  for(signed i = 0; i < signed(Band->size1()); ++ i)\n    for(signed j = std::max(i - 1, 0); j < std::min(i + 2, signed(Band->size2())); ++ j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp1)(i, j) + (*Band)(i, j)) < tol, true);\n\n  // Zero\n  sub(*tmp1, * tmp6, *res);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", *res == *tmp1, true);\n\n  // Id\n  sub(*tmp1, * tmp7, *res);\n  for(unsigned int i = 0; i < res->size(0); ++i)\n  {\n    for(unsigned int j = 0 ; j < res->size(1); ++j)\n    {\n      if(i == j)\n        CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp1)(i, j) + 1) < tol, true);\n      else\n        CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp1)(i, j)) < tol, true);\n    }\n  }\n  // triang + ...\n  // ... dense\n  add(*tmp2, * tmp1, *res);\n  for(unsigned int i = 0; i < res->size(0); ++i)\n  {\n    for(unsigned int j = i ; j < res->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp1)(i, j) - (*tmp2)(i, j)) < tol, true);\n    for(unsigned int j = 0 ; j < i; ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp1)(i, j)) < tol, true);\n  }\n  // ... Sym\n  add(*tmp2, * tmp3, *res);\n  for(unsigned int i = 0; i < res->size(0); ++i)\n  {\n    for(unsigned int j = i ; j < res->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp2)(i, j) - (*tmp3)(i, j)) < tol, true);\n    for(unsigned int j = 0 ; j < i; ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp3)(j, i)) < tol, true);\n  }\n  // ... Sparse\n  add(*tmp2, * tmp4, *res);\n  for(unsigned int i = 0; i < res->size(0); ++i)\n  {\n    for(unsigned int j = i ; j < res->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp4)(i, j) - (*tmp2)(i, j)) < tol, true);\n    for(unsigned int j = 0 ; j < i; ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp4)(i, j)) < tol, true);\n  }\n\n  // ... Banded\n  add(*tmp2, * tmp5, *res);\n  for(signed i = 0; i < signed(Band->size1()); ++ i)\n    for(signed j = std::max(i - 1, 0); j < std::min(i + 2, signed(Band->size2())); ++ j)\n      if(j >= i)\n        CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp2)(i, j) - (*Band)(i, j)) < tol, true);\n      else\n        CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*Band)(i, j)) < tol, true);\n\n  // ... Zero\n  add(*tmp2, * tmp6, *res);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", *res == *tmp2, true);\n\n  // ... Identity\n  add(*tmp2, * tmp7, *res);\n  for(unsigned int i = 0; i < res->size(0); ++i)\n  {\n    for(unsigned int j = i ; j < res->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp2)(i, j) - (*tmp7)(i, j)) < tol, true);\n    for(unsigned int j = 0 ; j < i; ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j)) < tol, true);\n  }\n\n  // triang - ...\n  // ... dense\n  sub(*tmp2, * tmp1, *res);\n  for(unsigned int i = 0; i < res->size(0); ++i)\n  {\n    for(unsigned int j = i ; j < res->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp2)(i, j) + (*tmp1)(i, j)) < tol, true);\n    for(unsigned int j = 0 ; j < i; ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) + (*tmp1)(i, j)) < tol, true);\n  }\n  // ... Sym\n  sub(*tmp2, * tmp3, *res);\n  for(unsigned int i = 0; i < res->size(0); ++i)\n  {\n    for(unsigned int j = i ; j < res->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp2)(i, j) + (*tmp3)(i, j)) < tol, true);\n    for(unsigned int j = 0 ; j < i; ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) + (*tmp3)(j, i)) < tol, true);\n  }\n  // ... Sparse\n  sub(*tmp2, * tmp4, *res);\n  for(unsigned int i = 0; i < res->size(0); ++i)\n  {\n    for(unsigned int j = i ; j < res->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp2)(i, j) + (*tmp4)(i, j)) < tol, true);\n    for(unsigned int j = 0 ; j < i; ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) + (*tmp4)(i, j)) < tol, true);\n  }\n\n  // ... Banded\n  sub(*tmp2, * tmp5, *res);\n  for(signed i = 0; i < signed(Band->size1()); ++ i)\n    for(signed j = std::max(i - 1, 0); j < std::min(i + 2, signed(Band->size2())); ++ j)\n      if(j >= i)\n        CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp2)(i, j) + (*Band)(i, j)) < tol, true);\n      else\n        CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) + (*Band)(i, j)) < tol, true);\n\n  // ... Zero\n  sub(*tmp2, * tmp6, *res);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", *res == *tmp2, true);\n\n  // Identity\n  sub(*tmp2, * tmp7, *res);\n  for(unsigned int i = 0; i < res->size(0); ++i)\n  {\n    for(unsigned int j = i ; j < res->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp2)(i, j) + (*tmp7)(i, j)) < tol, true);\n    for(unsigned int j = 0 ; j < i; ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j)) < tol, true);\n  }\n\n  // sym + ...\n  // ... dense\n  add(*tmp3, * tmp1, *res);\n  for(unsigned int i = 0; i < res->size(0); ++i)\n  {\n    for(unsigned int j = i ; j < res->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp1)(i, j) - (*tmp3)(i, j)) < tol, true);\n    for(unsigned int j = 0 ; j < i; ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp1)(i, j) - (*tmp3)(j, i)) < tol, true);\n  }\n  // ... triang\n  add(*tmp3, * tmp2, *res);\n  for(unsigned int i = 0; i < res->size(0); ++i)\n  {\n    for(unsigned int j = i ; j < res->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp3)(i, j) - (*tmp2)(i, j)) < tol, true);\n    for(unsigned int j = 0 ; j < i; ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp3)(j, i)) < tol, true);\n  }\n  // ... Sparse\n  add(*tmp3, * tmp4, *res);\n  for(unsigned int i = 0; i < res->size(0); ++i)\n  {\n    for(unsigned int j = i ; j < res->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp4)(i, j) - (*tmp3)(i, j)) < tol, true);\n    for(unsigned int j = 0 ; j < i; ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp4)(i, j) - (*tmp3)(j, i)) < tol, true);\n  }\n\n  // ... Banded\n  add(*tmp3, * tmp5, *res);\n  for(signed i = 0; i < signed(Band->size1()); ++ i)\n    for(signed j = std::max(i - 1, 0); j < std::min(i + 2, signed(Band->size2())); ++ j)\n      if(j >= i)\n        CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp3)(i, j) - (*Band)(i, j)) < tol, true);\n      else\n        CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp3)(j, i) - (*Band)(i, j)) < tol, true);\n\n\n  // ... Zero\n  add(*tmp3, * tmp6, *res);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", *res == *tmp3, true);\n\n  // ... identity\n  add(*tmp3, * tmp7, *res);\n  for(unsigned int i = 0; i < res->size(0); ++i)\n  {\n    for(unsigned int j = i ; j < res->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp7)(i, j) - (*tmp3)(i, j)) < tol, true);\n    for(unsigned int j = 0 ; j < i; ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp7)(i, j) - (*tmp3)(j, i)) < tol, true);\n  }\n\n  // sym - ...\n  // ... dense\n  sub(*tmp3, * tmp1, *res);\n  for(unsigned int i = 0; i < res->size(0); ++i)\n  {\n    for(unsigned int j = i ; j < res->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp3)(i, j) + (*tmp1)(i, j)) < tol, true);\n    for(unsigned int j = 0 ; j < i; ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp3)(j, i) + (*tmp1)(i, j)) < tol, true);\n  }\n  // ... triang\n  sub(*tmp3, * tmp2, *res);\n  for(unsigned int i = 0; i < res->size(0); ++i)\n  {\n    for(unsigned int j = i ; j < res->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp3)(i, j) + (*tmp2)(i, j)) < tol, true);\n    for(unsigned int j = 0 ; j < i; ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp3)(j, i)) < tol, true);\n  }\n  // ... Sparse\n  sub(*tmp3, * tmp4, *res);\n  for(unsigned int i = 0; i < res->size(0); ++i)\n  {\n    for(unsigned int j = i ; j < res->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp3)(i, j) + (*tmp4)(i, j)) < tol, true);\n    for(unsigned int j = 0 ; j < i; ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp3)(j, i) + (*tmp4)(i, j)) < tol, true);\n  }\n\n  // ... Banded\n  sub(*tmp3, * tmp5, *res);\n  for(signed i = 0; i < signed(Band->size1()); ++ i)\n    for(signed j = std::max(i - 1, 0); j < std::min(i + 2, signed(Band->size2())); ++ j)\n      if(j >= i)\n        CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp3)(i, j) + (*Band)(i, j)) < tol, true);\n      else\n        CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp3)(j, i) + (*Band)(i, j)) < tol, true);\n\n  // ... Zero\n  sub(*tmp3, * tmp6, *res);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", *res == *tmp3, true);\n  // Identity\n  sub(*tmp3, * tmp7, *res);\n  for(unsigned int i = 0; i < res->size(0); ++i)\n  {\n    for(unsigned int j = i ; j < res->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp3)(i, j) + (*tmp7)(i, j)) < tol, true);\n    for(unsigned int j = 0 ; j < i; ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp3)(j, i) + (*tmp7)(i, j)) < tol, true);\n  }\n\n  // sparse + ...\n  // ... dense\n  add(*tmp4, * tmp1, *res);\n  for(unsigned int i = 0; i < res->size(0); ++i)\n    for(unsigned int j = 0 ; j < res->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp1)(i, j) - (*tmp4)(i, j)) < tol, true);\n  // ... triang\n  add(*tmp4, * tmp2, *res);\n  for(unsigned int i = 0; i < res->size(0); ++i)\n  {\n    for(unsigned int j = i ; j < res->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp4)(i, j) - (*tmp2)(i, j)) < tol, true);\n    for(unsigned int j = 0 ; j < i; ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp4)(i, j)) < tol, true);\n  }\n  // ... Sym\n  add(*tmp4, * tmp3, *res);\n  for(unsigned int i = 0; i < res->size(0); ++i)\n  {\n    for(unsigned int j = i ; j < res->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp4)(i, j) - (*tmp3)(i, j)) < tol, true);\n    for(unsigned int j = 0 ; j < i; ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp4)(i, j) - (*tmp3)(j, i)) < tol, true);\n  }\n  // ... Banded\n  add(*tmp4, * tmp5, *res);\n  for(signed i = 0; i < signed(Band->size1()); ++ i)\n    for(signed j = std::max(i - 1, 0); j < std::min(i + 2, signed(Band->size2())); ++ j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp4)(i, j) - (*Band)(i, j)) < tol, true);\n\n  // ... zero\n  add(*tmp4, * tmp6, *res);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", *res == *tmp4, true);\n\n  // sparse - ...\n  // ... dense\n  sub(*tmp4, * tmp1, *res);\n  for(unsigned int i = 0; i < res->size(0); ++i)\n    for(unsigned int j = 0 ; j < res->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp4)(i, j) + (*tmp1)(i, j)) < tol, true);\n  // ... triangular\n  sub(*tmp4, * tmp2, *res);\n  for(unsigned int i = 0; i < res->size(0); ++i)\n  {\n    for(unsigned int j = i ; j < res->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp4)(i, j) + (*tmp2)(i, j)) < tol, true);\n    for(unsigned int j = 0 ; j < i; ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp4)(i, j)) < tol, true);\n  }\n  // ... Sym\n  sub(*tmp4, * tmp3, *res);\n  for(unsigned int i = 0; i < res->size(0); ++i)\n  {\n    for(unsigned int j = i ; j < res->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp4)(i, j) + (*tmp3)(i, j)) < tol, true);\n    for(unsigned int j = 0 ; j < i; ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp4)(i, j) + (*tmp3)(j, i)) < tol, true);\n  }\n\n  // ... Banded\n  sub(*tmp4, * tmp5, *res);\n  for(signed i = 0; i < signed(Band->size1()); ++ i)\n    for(signed j = std::max(i - 1, 0); j < std::min(i + 2, signed(Band->size2())); ++ j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp4)(i, j) + (*Band)(i, j)) < tol, true);\n\n  // ... zero\n  sub(*tmp4, * tmp6, *res);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", *res == *tmp4, true);\n\n  // Banded + ...\n  // ... dense\n  add(*tmp5, * tmp1, *res);\n  for(signed i = 0; i < signed(Band->size1()); ++ i)\n  {\n    for(signed j = 0; j < std::max(i - 1, 0); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp1)(i, j)) < tol, true);\n    for(signed j = std::max(i - 1, 0); j < std::min(i + 2, signed(Band->size2())); ++ j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp1)(i, j) - (*tmp5)(i, j)) < tol, true);\n    for(signed j = std::min(i + 2, signed(Band->size2())); j < signed(Band->size2()); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp1)(i, j)) < tol, true);\n  }\n  // ... triang\n  add(*tmp5, * tmp2, *res);\n  for(signed i = 0; i < signed(Band->size1()); ++ i)\n  {\n    for(signed j = 0; j < std::max(i - 1, 0); ++j)\n      if(j >= i) CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp2)(i, j)) < tol, true);\n    for(signed j = std::max(i - 1, 0); j < std::min(i + 2, signed(Band->size2())); ++ j)\n      if(j >= i)\n        CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp2)(i, j) - (*tmp5)(i, j)) < tol, true);\n      else\n        CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp5)(i, j)) < tol, true);\n    for(signed j = std::min(i + 2, signed(Band->size2())); j < signed(Band->size2()); ++j)\n      if(j >= i) CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp2)(i, j)) < tol, true);\n  }\n\n  // ...sym\n  add(*tmp5, * tmp3, *res);\n  for(signed i = 0; i < signed(Band->size1()); ++ i)\n  {\n    for(signed j = 0; j < std::max(i - 1, 0); ++j)\n      if(j >= i) CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp3)(i, j)) < tol, true);\n      else  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp3)(j, i)) < tol, true);\n    for(signed j = std::max(i - 1, 0); j < std::min(i + 2, signed(Band->size2())); ++ j)\n      if(j >= i)\n        CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp3)(i, j) - (*tmp5)(i, j)) < tol, true);\n      else\n        CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp3)(j, i) - (*tmp5)(i, j)) < tol, true);\n    for(signed j = std::min(i + 2, signed(Band->size2())); j < signed(Band->size2()); ++j)\n      if(j >= i) CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp3)(i, j)) < tol, true);\n      else  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp3)(j, i)) < tol, true);\n  }\n\n  //... sparse\n  add(*tmp5, * tmp4, *res);\n  for(signed i = 0; i < signed(Band->size1()); ++ i)\n  {\n    for(signed j = 0; j < std::max(i - 1, 0); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp4)(i, j)) < tol, true);\n    for(signed j = std::max(i - 1, 0); j < std::min(i + 2, signed(Band->size2())); ++ j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp4)(i, j) - (*tmp5)(i, j)) < tol, true);\n    for(signed j = std::min(i + 2, signed(Band->size1())); j < signed(Band->size1()); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp4)(i, j)) < tol, true);\n  }\n\n  // ... zero\n  add(*tmp5, * tmp6, *res);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", *res == *tmp5, true);\n  // ... identity\n  add(*tmp5, * tmp7, *res);\n  for(signed i = 0; i < signed(Band->size1()); ++ i)\n  {\n    for(signed j = 0; j < std::max(i - 1, 0); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp7)(i, j)) < tol, true);\n    for(signed j = std::max(i - 1, 0); j < std::min(i + 2, signed(Band->size2())); ++ j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp7)(i, j) - (*tmp5)(i, j)) < tol, true);\n    for(signed j = std::min(i + 2, signed(Band->size2())); j < signed(Band->size2()); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp7)(i, j)) < tol, true);\n  }\n\n  // Banded - ...\n  // ... dense\n\n  sub(*tmp5, * tmp1, *res);\n  for(signed i = 0; i < signed(Band->size1()); ++ i)\n  {\n    for(signed j = 0; j < std::max(i - 1, 0); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) + (*tmp1)(i, j)) < tol, true);\n    for(signed j = std::max(i - 1, 0); j < std::min(i + 2, signed(Band->size2())); ++ j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp5)(i, j) + (*tmp1)(i, j)) < tol, true);\n    for(signed j = std::min(i + 2, signed(Band->size2())); j < signed(Band->size2()); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) + (*tmp1)(i, j)) < tol, true);\n  }\n\n  // ... triang\n  sub(*tmp5, * tmp2, *res);\n  for(signed i = 0; i < signed(Band->size1()); ++ i)\n  {\n    for(signed j = 0; j < std::max(i - 1, 0); ++j)\n      if(j >= i) CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \",  fabs((*res)(i, j) + (*tmp2)(i, j)) < tol, true);\n    for(signed j = std::max(i - 1, 0); j < std::min(i + 2, signed(Band->size2())); ++ j)\n      if(j >= i)\n        CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp5)(i, j) + (*tmp2)(i, j)) < tol, true);\n      else\n        CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp5)(i, j)) < tol, true);\n    for(signed j = std::min(i + 2, signed(Band->size2())); j < signed(Band->size2()); ++j)\n      if(j >= i) CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) + (*tmp2)(i, j)) < tol, true);\n  }\n\n  // ...sym\n  sub(*tmp5, * tmp3, *res);\n  for(signed i = 0; i < signed(Band->size1()); ++ i)\n  {\n    for(signed j = 0; j < std::max(i - 1, 0); ++j)\n      if(j >= i) CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) + (*tmp3)(i, j)) < tol, true);\n      else  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) + (*tmp3)(j, i)) < tol, true);\n    for(signed j = std::max(i - 1, 0); j < std::min(i + 2, signed(Band->size2())); ++ j)\n      if(j >= i)\n        CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp5)(i, j) + (*tmp3)(i, j)) < tol, true);\n      else\n        CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp5)(i, j) + (*tmp3)(j, i)) < tol, true);\n    for(signed j = std::min(i + 2, signed(Band->size2())); j < signed(Band->size2()); ++j)\n      if(j >= i) CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) + (*tmp3)(i, j)) < tol, true);\n      else  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) + (*tmp3)(j, i)) < tol, true);\n  }\n\n  //... sparse\n  sub(*tmp5, * tmp4, *res);\n  for(signed i = 0; i < signed(Band->size1()); ++ i)\n  {\n    for(signed j = 0; j < std::max(i - 1, 0); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) + (*tmp4)(i, j)) < tol, true);\n    for(signed j = std::max(i - 1, 0); j < std::min(i + 2, signed(Band->size2())); ++ j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) + (*tmp4)(i, j) - (*tmp5)(i, j)) < tol, true);\n    for(signed j = std::min(i + 2, signed(Band->size1())); j < signed(Band->size1()); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) + (*tmp4)(i, j)) < tol, true);\n  }\n\n  // ... zero\n  sub(*tmp5, * tmp6, *res);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", *res == *tmp5, true);\n  // ... identity\n  sub(*tmp5, * tmp7, *res);\n  for(signed i = 0; i < signed(Band->size1()); ++ i)\n  {\n    for(signed j = 0; j < std::max(i - 1, 0); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) + (*tmp7)(i, j)) < tol, true);\n    for(signed j = std::max(i - 1, 0); j < std::min(i + 2, signed(Band->size2())); ++ j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) - (*tmp5)(i, j) + (*tmp7)(i, j)) < tol, true);\n    for(signed j = std::min(i + 2, signed(Band->size2())); j < signed(Band->size2()); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*res)(i, j) + (*tmp7)(i, j)) < tol, true);\n  }\n\n  std::cout << \"-->  test operators7 ended with success.\" <<std::endl;\n}\n\n\n\n//void SimpleMatrixTest::testOperators8()\n// {\n//   std::cout << \"--> Test: operator8.\" <<std::endl;\n\n//   // // Simple = Simple * Simple\n//   // *C = prod(*A, *B);\n//   // CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8: \", norm_inf(*C->dense() - prod(*A->dense(), *B->dense())) < tol, true);\n\n//   // Block = Simple * Simple\n//   // *Cb = prod(*A, *B);\n//   // DenseMat Dtmp = prod(*A->dense(), *B->dense());\n//   // SP::SimpleMatrix tmp(new SimpleMatrix(Dtmp));\n//   // for (unsigned int i = 0; i < C->size(0); ++i)\n//   //   for (unsigned int j = i ; j < C->size(1); ++j)\n//   //     CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*Cb)(i, j) - (*tmp)(i, j)) < tol, true);\n\n//   // Others ...\n\n//   SP::SiconosMatrix tmp1(new SimpleMatrix(4, 4, 2.3));\n//   SP::SiconosMatrix tmp2(new SimpleMatrix(*T2));\n//   SP::SiconosMatrix tmp3(new SimpleMatrix(*S2));\n//   SP::SiconosMatrix tmp4(new SimpleMatrix(*SP));\n//   SP::SiconosMatrix tmp5(new SimpleMatrix(*Band));\n\n//   SP::SiconosMatrix res(new SimpleMatrix(4, 4, 0));\n\n//   // Dense * ...\n//   // triang\n//   *res = prod(*tmp1, *tmp2);\n//   CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", norm_inf(*res->dense() - prod(tmp1->getDense(), tmp2->getTriang())) < tol, true);\n//   // Sym\n//   *res = prod(*tmp1, *tmp3);\n//   CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", norm_inf(*res->dense() - prod(tmp1->getDense(), tmp3->getSym())) < tol, true);\n//   // Sparse\n//   *res = prod(*tmp1, *tmp4);\n//   CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", norm_inf(*res->dense() - prod(tmp1->getDense(), tmp4->getSparse())) < tol, true);\n//   // Banded\n//   *res = prod(*tmp1, *tmp5);\n//   CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", norm_inf(*res->dense() - prod(tmp1->getDense(), tmp5->getBanded())) < tol, true);\n//   // triang * ...\n//   // dense\n//   *res = prod(*tmp2, *tmp1);\n//   CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", norm_inf(*res->dense() - prod(tmp2->getTriang(), tmp1->getDense())) < tol, true);\n//   // Sym\n//   *res = prod(*tmp2, *tmp3);\n//   CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", norm_inf(*res->dense() - prod(tmp2->getTriang(), tmp3->getSym())) < tol, true);\n//   // Sparse\n//   *res = prod(*tmp2, *tmp4);\n//   CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", norm_inf(*res->dense() - prod(tmp2->getTriang(), tmp4->getSparse())) < tol, true);\n//   // Banded\n//   *res = prod(*tmp2, *tmp5);\n//   CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", norm_inf(*res->dense() - prod(tmp2->getTriang(), tmp5->getBanded())) < tol, true);\n//   // sym * ...\n//   // dense\n//   *res = prod(*tmp3, *tmp1);\n//   CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", norm_inf(*res->dense() - prod(tmp3->getSym(), tmp1->getDense())) < tol, true);\n//   // triang\n//   *res = prod(*tmp3, *tmp2);\n//   CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", norm_inf(*res->dense() - prod(tmp3->getSym(), tmp2->getTriang())) < tol, true);\n//   // Sparse\n//   *res = prod(*tmp3, *tmp4);\n//   CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", norm_inf(*res->dense() - prod(tmp3->getSym(), tmp4->getSparse())) < tol, true);\n//   // Banded\n//   *res = prod(*tmp3, *tmp5);\n//   CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", norm_inf(*res->dense() - prod(tmp3->getSym(), tmp5->getBanded())) < tol, true);\n//   // Sparse * ...\n//   // dense\n//   *res = prod(*tmp4, *tmp1);\n//   CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", norm_inf(*res->dense() - prod(tmp4->getSparse(), tmp1->getDense())) < tol, true);\n//   // triang\n//   *res = prod(*tmp4, *tmp2);\n//   CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", norm_inf(*res->dense() - prod(tmp4->getSparse(), tmp2->getTriang())) < tol, true);\n//   // Sym\n//   *res = prod(*tmp4, *tmp3);\n//   CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", norm_inf(*res->dense() - prod(tmp4->getSparse(), tmp3->getSym())) < tol, true);\n//   // Banded\n//   *res = prod(*tmp4, *tmp5);\n//   CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", norm_inf(*res->dense() - prod(tmp4->getSparse(), tmp5->getBanded())) < tol, true);\n//   // Banded * ...\n//   // dense\n//   *res = prod(*tmp5, *tmp1);\n//   CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", norm_inf(*res->dense() - prod(tmp5->getBanded(), tmp1->getDense())) < tol, true);\n//   // triang\n//   *res = prod(*tmp5, *tmp2);\n//   CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", norm_inf(*res->dense() - prod(tmp5->getBanded(), tmp2->getTriang())) < tol, true);\n//   // Sparse\n//   *res = prod(*tmp5, *tmp4);\n//   CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", norm_inf(*res->dense() - prod(tmp5->getBanded(), tmp4->getSparse())) < tol, true);\n//   // Sym\n//   *res = prod(*tmp5, *tmp3);\n//   CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", norm_inf(*res->dense() - prod(tmp5->getBanded(), tmp3->getSym())) < tol, true);\n\n//   std::cout << \"-->  test operators8 ended with success.\" <<std::endl;\n// }\n\nvoid SimpleMatrixTest::testOperators8Bis()\n{\n  std::cout << \"--> Test: operator8Bis.\" <<std::endl;\n  // Simple = Simple * Simple\n  prod(*A, *B, *C);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8Bis: \", norm_inf(*C->dense() - prod(*A->dense(), *B->dense())) < tol, true);\n\n  // Block = Simple * Simple\n  prod(*A, *B, *Cb);\n  DenseMat Dtmp = prod(*A->dense(), *B->dense());\n  SP::SimpleMatrix tmp(new SimpleMatrix(Dtmp));\n  for(unsigned int i = 0; i < Cb->size(0); ++i)\n    for(unsigned int j = i ; j < Cb->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*Cb)(i, j) - (*tmp)(i, j)) < tol, true);\n\n  // Others ...\n\n  // Others ...\n  SP::SiconosMatrix tmp1(new SimpleMatrix(4, 4, 2.4));\n  SP::SiconosMatrix tmp2(new SimpleMatrix(*T2));\n  SP::SiconosMatrix tmp3(new SimpleMatrix(*S2));\n  SP::SiconosMatrix tmp4(new SimpleMatrix(*SP));\n  SP::SiconosMatrix tmp5(new SimpleMatrix(*Band));\n\n  SP::SiconosMatrix res(new SimpleMatrix(4, 4));\n\n  // Dense * ...\n  // triang\n  prod(*tmp1, *tmp2, *res);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8Bis: \", norm_inf(*res->dense() - prod(tmp1->getDense(), tmp2->getTriang())) < tol, true);\n  // Sym\n  prod(*tmp1, *tmp3, *res);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8Bis: \", norm_inf(*res->dense() - prod(tmp1->getDense(), tmp3->getSym())) < tol, true);\n  // Sparse\n  prod(*tmp1, *tmp4, *res);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8Bis: \", norm_inf(*res->dense() - prod(tmp1->getDense(), tmp4->getSparse())) < tol, true);\n  // Banded\n  prod(*tmp1, *tmp5, *res);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8Bis: \", norm_inf(*res->dense() - prod(tmp1->getDense(), tmp5->getBanded())) < tol, true);\n  // triang * ...\n  // dense\n  prod(*tmp2, *tmp1, *res);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8Bis: \", norm_inf(*res->dense() - prod(tmp2->getTriang(), tmp1->getDense())) < tol, true);\n  // Sym\n  prod(*tmp2, *tmp3, *res);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8Bis: \", norm_inf(*res->dense() - prod(tmp2->getTriang(), tmp3->getSym())) < tol, true);\n  // Sparse\n  prod(*tmp2, *tmp4, *res);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8Bis: \", norm_inf(*res->dense() - prod(tmp2->getTriang(), tmp4->getSparse())) < tol, true);\n  // Banded\n  prod(*tmp2, *tmp5, *res);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8Bis: \", norm_inf(*res->dense() - prod(tmp2->getTriang(), tmp5->getBanded())) < tol, true);\n  // sym * ...\n  // dense\n  prod(*tmp3, *tmp1, *res);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8Bis: \", norm_inf(*res->dense() - prod(tmp3->getSym(), tmp1->getDense())) < tol, true);\n  // triang\n  prod(*tmp3, *tmp2, *res);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8Bis: \", norm_inf(*res->dense() - prod(tmp3->getSym(), tmp2->getTriang())) < tol, true);\n  // Sparse\n  prod(*tmp3, *tmp4, *res);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8Bis: \", norm_inf(*res->dense() - prod(tmp3->getSym(), tmp4->getSparse())) < tol, true);\n  // Banded\n  prod(*tmp3, *tmp5, *res);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8Bis: \", norm_inf(*res->dense() - prod(tmp3->getSym(), tmp5->getBanded())) < tol, true);\n  // Sparse * ...\n  // dense\n  prod(*tmp4, *tmp1, *res);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8Bis: \", norm_inf(*res->dense() - prod(tmp4->getSparse(), tmp1->getDense())) < tol, true);\n  // triang\n  prod(*tmp4, *tmp2, *res);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8Bis: \", norm_inf(*res->dense() - prod(tmp4->getSparse(), tmp2->getTriang())) < tol, true);\n  // Sym\n  prod(*tmp4, *tmp3, *res);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8Bis: \", norm_inf(*res->dense() - prod(tmp4->getSparse(), tmp3->getSym())) < tol, true);\n  // Banded\n  prod(*tmp4, *tmp5, *res);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8Bis: \", norm_inf(*res->dense() - prod(tmp4->getSparse(), tmp5->getBanded())) < tol, true);\n  // Banded * ...\n  // dense\n  prod(*tmp5, *tmp1, *res);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8Bis: \", norm_inf(*res->dense() - prod(tmp5->getBanded(), tmp1->getDense())) < tol, true);\n  // triang\n  prod(*tmp5, *tmp2, *res);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8Bis: \", norm_inf(*res->dense() - prod(tmp5->getBanded(), tmp2->getTriang())) < tol, true);\n  // Sparse\n  prod(*tmp5, *tmp4, *res);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8Bis: \", norm_inf(*res->dense() - prod(tmp5->getBanded(), tmp4->getSparse())) < tol, true);\n  // Sym\n  prod(*tmp5, *tmp3, *res);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8Bis: \", norm_inf(*res->dense() - prod(tmp5->getBanded(), tmp3->getSym())) < tol, true);\n\n  std::cout << \"-->  test operators8Bis ended with success.\" <<std::endl;\n}\n\nvoid SimpleMatrixTest::testOperators8Ter()\n{\n  std::cout << \"--> Test: operator8Ter.\" <<std::endl;\n  // Simple = Simple * Simple\n  axpy_prod(*A, *B, *C, true);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8Ter: \", norm_inf(*C->dense() - prod(*A->dense(), *B->dense())) < tol, true);\n\n  // Simple += Simple * Simple\n  SP::SiconosMatrix backUp(new SimpleMatrix(*C));\n\n  axpy_prod(*A, *B, *C, false);\n\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8Ter: \", norm_inf(*C->dense() - prod(*A->dense(), *B->dense()) - *backUp->dense()) < tol, true);\n  // Block = Simple * Simple\n  axpy_prod(*A, *B, *Cb, true);\n  DenseMat Dtmp = prod(*A->dense(), *B->dense());\n  SP::SimpleMatrix tmp(new SimpleMatrix(Dtmp));\n  for(unsigned int i = 0; i < Cb->size(0); ++i)\n    for(unsigned int j = i ; j < Cb->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*Cb)(i, j) - (*tmp)(i, j)) < tol, true);\n\n  *backUp = *Cb;\n  // Block += Simple * Simple\n  axpy_prod(*A, *B, *Cb, false);\n  Dtmp = prod(*A->dense(), *B->dense());\n  *tmp = Dtmp;\n  for(unsigned int i = 0; i < Cb->size(0); ++i)\n    for(unsigned int j = i ; j < Cb->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*Cb)(i, j) - (*tmp)(i, j) - (*backUp)(i, j)) < tol, true);\n\n  std::cout << \"-->  test operators8Ter ended with success.\" <<std::endl;\n}\n\nvoid SimpleMatrixTest::testOperators8_4() // C += A*B\n{\n  std::cout << \"--> Test: operator8_4.\" <<std::endl;\n  // Simple = Simple * Simple\n  C->zero();\n  prod(*A, *B, *C, false);\n  prod(*A, *B, *C, false);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8_4: \", norm_inf(*C->dense() - 2 * prod(*A->dense(), *B->dense())) < tol, true);\n\n  // Block = Simple * Simple\n  Cb->zero();\n  prod(*A, *B, *Cb, false);\n  prod(*A, *B, *Cb, false);\n  DenseMat Dtmp = prod(*A->dense(), *B->dense());\n  SP::SimpleMatrix tmp(new SimpleMatrix(Dtmp));\n  for(unsigned int i = 0; i < Cb->size(0); ++i)\n    for(unsigned int j = i ; j < Cb->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", fabs((*Cb)(i, j) - 2 * (*tmp)(i, j)) < tol, true);\n  std::cout << \"-->  test operators8_4 ended with success.\" <<std::endl;\n}\n\nvoid SimpleMatrixTest::testOperators8_5()\n{\n  // == Test subprod ==\n\n  std::cout << \"--> Test: operator8_5.\" <<std::endl;\n  Index coord(8);\n  SP::SiconosVector x1(new SiconosVector(2));\n  SP::SiconosVector x2(new SiconosVector(3));\n  SP::SiconosVector x3(new SiconosVector(5));\n  SP::SiconosVector y(new SiconosVector(size));\n  SP::BlockVector x(new BlockVector());\n  SP::SiconosVector v(new SiconosVector(size));\n  x->insertPtr(x1);\n  x->insertPtr(x2);\n  x->insertPtr(x3);\n  for(unsigned int i = 0 ; i < size; ++i)\n  {\n    (*x)(i) = (double)i + 3;\n    (*v)(i) = (double)i + 3;\n  }\n\n  // v == x but x is a 3-blocks vector.\n\n  // Simple = Simple * Simple, all dense\n  // subprod but with full matrix/vectors\n  coord[0] = 0;\n  coord[1] = size;\n  coord[2] = 0;\n  coord[3] = size;\n  coord[4] = 0;\n  coord[5] = size;\n  coord[6] = 0;\n  coord[7] = size;\n  subprod(*A, *v, *y, coord, true);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8_5: \", norm_inf(*y->dense() - prod(*A->dense(), *v->dense())) < tol, true);\n\n  // Simple = Simple * Block, all dense\n  // subprod but with full matrix/vectors\n  //  subprod(*A,*x,*y, coord, true);\n  //  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8_5: \", norm_inf(*y->dense()- prod(*A->dense(),*v->dense()))<tol, true);\n\n  coord[0] = 0;\n  coord[1] = 2;\n  coord[2] = 1;\n  coord[3] = 3;\n  coord[4] = 3;\n  coord[5] = 5;\n  coord[6] = 2;\n  coord[7] = 4;\n  y->zero();\n  // Simple = Simple * Simple, all dense\n  subprod(*A, *v, *y, coord, true);\n  double res = (*A)(0, 1) * (*v)(3) + (*A)(0, 2) * (*v)(4);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8_5: \", fabs(res - (*y)(2)) < tol, true);\n  res = (*A)(1, 1) * (*v)(3) + (*A)(1, 2) * (*v)(4);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8_5: \", fabs(res - (*y)(3)) < tol, true);\n  for(unsigned int i = 0; i < size; ++i)\n  {\n    if(i != 2 && i != 3)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8_5: \", fabs((*y)(i)) < tol, true);\n  }\n  y->zero();\n  // Simple = Simple * Block, all dense\n  //  subprod(*A,*x,*y, coord, true);\n  //  res = (*A)(0,1)*(*x)(3) + (*A)(0,2)*(*x)(4);\n  //  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8_5: \", fabs(res-(*y)(2))<tol, true);\n  //  res = (*A)(1,1)*(*x)(3) + (*A)(1,2)*(*x)(4);\n  //  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8_5: \", fabs(res-(*y)(3))<tol, true);\n  //  for (unsigned int i=0; i<size; ++i)\n  //  {\n  //    if (i!=2 && i!=3)\n  //      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8_5: \", fabs((*y)(i))<tol, true);\n  //  }\n  //   // Others ...\n  // Triang\n\n  SP::SiconosMatrix A2(new SimpleMatrix(10, 10, TRIANGULAR));\n  for(unsigned i = 0; i < A2->size(0); ++ i)\n    for(unsigned j = i; j < A2->size(1); ++ j)\n      (*A2)(i, j) = 3 * i + j;\n\n  subprod(*A2, *v, *y, coord, true);\n  res = (*A2)(0, 1) * (*v)(3) + (*A2)(0, 2) * (*v)(4);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8_5: \", fabs(res - (*y)(2)) < tol, true);\n  res = (*A2)(1, 1) * (*v)(3) + (*A2)(1, 2) * (*v)(4);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8_5: \", fabs(res - (*y)(3)) < tol, true);\n  for(unsigned int i = 0; i < size; ++i)\n  {\n    if(i != 2 && i != 3)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8_5: \", fabs((*y)(i)) < tol, true);\n  }\n  // Sym\n  A2.reset(new SimpleMatrix(10, 10, SYMMETRIC));\n  for(unsigned i = 0; i < A2->size(0); ++ i)\n    for(unsigned j = i; j < A2->size(1); ++ j)\n      (*A2)(i, j) = 3 * i + j;\n\n  subprod(*A2, *v, *y, coord, true);\n  res = (*A2)(0, 1) * (*v)(3) + (*A2)(0, 2) * (*v)(4);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8_5: \", fabs(res - (*y)(2)) < tol, true);\n  res = (*A2)(1, 1) * (*v)(3) + (*A2)(1, 2) * (*v)(4);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8_5: \", fabs(res - (*y)(3)) < tol, true);\n  for(unsigned int i = 0; i < size; ++i)\n  {\n    if(i != 2 && i != 3)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8_5: \", fabs((*y)(i)) < tol, true);\n  }\n\n  // Sparse\n  A2.reset(new SimpleMatrix(10, 10, Siconos::SPARSE));\n  for(unsigned i = 0; i < A2->size(0); ++ i)\n    for(unsigned j = i; j < A2->size(1); ++ j)\n      A2->setValue(i, j, 3 * i + j);\n\n  subprod(*A2, *v, *y, coord, true);\n  res = (*A2)(0, 1) * (*v)(3) + (*A2)(0, 2) * (*v)(4);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8_5: \", fabs(res - (*y)(2)) < tol, true);\n  res = (*A2)(1, 1) * (*v)(3) + (*A2)(1, 2) * (*v)(4);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8_5: \", fabs(res - (*y)(3)) < tol, true);\n  for(unsigned int i = 0; i < size; ++i)\n  {\n    if(i != 2 && i != 3)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8_5: \", fabs((*y)(i)) < tol, true);\n  }\n\n  // Banded\n  A2.reset(new SimpleMatrix(10, 10, BANDED));\n  for(signed i = 0; i < signed(A2->size(0)); ++ i)\n    for(signed j = std::max(i - 1, 0); j < std::min(i + 2, signed(A2->size(1))); ++ j)\n      (*A2)(i, j) = 3 * i + j;\n  subprod(*A2, *v, *y, coord, true);\n  res = (*A2)(0, 1) * (*v)(3);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8_5: \", fabs(res - (*y)(2)) < tol, true);\n  res = (*A2)(1, 1) * (*v)(3) + (*A2)(1, 2) * (*v)(4);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8_5: \", fabs(res - (*y)(3)) < tol, true);\n  for(unsigned int i = 0; i < size; ++i)\n  {\n    if(i != 2 && i != 3)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8_5: \", fabs((*y)(i)) < tol, true);\n  }\n\n  std::cout << \"-->  test operators8_5 ended with success.\" <<std::endl;\n}\n\nvoid SimpleMatrixTest::testOperators8_6()\n{\n  // == Test subprod, with += ==\n\n  std::cout << \"--> Test: operator8_6.\" <<std::endl;\n  Index coord(8);\n  SP::SiconosVector x1(new SiconosVector(2));\n  SP::SiconosVector x2(new SiconosVector(3));\n  SP::SiconosVector x3(new SiconosVector(5));\n  SP::SiconosVector y(new SiconosVector(size));\n  SP::BlockVector x(new BlockVector());\n  SP::SiconosVector v(new SiconosVector(size));\n  x->insertPtr(x1);\n  x->insertPtr(x2);\n  x->insertPtr(x3);\n  for(unsigned int i = 0 ; i < size; ++i)\n  {\n    (*x)(i) = (double)i + 3;\n    (*v)(i) = (double)i + 3;\n  }\n\n  // v == x but x is a 3-blocks vector.\n\n  *y = *v;\n\n  // Simple = Simple * Simple, all dense\n  // subprod but with full matrix/vectors\n  coord[0] = 0;\n  coord[1] = size;\n  coord[2] = 0;\n  coord[3] = size;\n  coord[4] = 0;\n  coord[5] = size;\n  coord[6] = 0;\n  coord[7] = size;\n  subprod(*A, *v, *y, coord, false);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8_6: \", norm_inf(*y->dense() - prod(*A->dense(), *v->dense()) - *v->dense()) < tol, true);\n\n  // Simple = Simple * Block, all dense\n  // subprod but with full matrix/vectors\n  *y = *v;\n  //  subprod(*A,*x,*y, coord, false);\n  //  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8_6: \", norm_inf(*y->dense()- prod(*A->dense(),*v->dense())- *v->dense())<tol, true);\n\n  coord[0] = 0;\n  coord[1] = 2;\n  coord[2] = 1;\n  coord[3] = 3;\n  coord[4] = 3;\n  coord[5] = 5;\n  coord[6] = 2;\n  coord[7] = 4;\n\n  // Simple = Simple * Simple, all dense\n  *y = *v;\n  subprod(*A, *v, *y, coord, false);\n  double res = (*A)(0, 1) * (*v)(3) + (*A)(0, 2) * (*v)(4) + (*v)(2);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8_6: \", fabs(res - (*y)(2)) < tol, true);\n  res = (*A)(1, 1) * (*v)(3) + (*A)(1, 2) * (*v)(4) + (*v)(3);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8_6: \", fabs(res - (*y)(3)) < tol, true);\n  for(unsigned int i = 0; i < size; ++i)\n  {\n    if(i != 2 && i != 3)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8_6: \", fabs((*y)(i) - (*v)(i)) < tol, true);\n  }\n  *y = *v;\n  // Simple = Simple * Block, all dense\n  //  subprod(*A,*x,*y, coord, false);\n  //  res = (*A)(0,1)*(*x)(3) + (*A)(0,2)*(*x)(4) + (*v)(2);\n  //  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8_6: \", fabs(res-(*y)(2))<tol, true);\n  //  res = (*A)(1,1)*(*x)(3) + (*A)(1,2)*(*x)(4) + (*v)(3);\n  //  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8_6: \", fabs(res-(*y)(3))<tol, true);\n  //  for (unsigned int i=0; i<size; ++i)\n  //  {\n  //    if (i!=2 && i!=3)\n  //      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8_6: \", fabs((*y)(i)-(*v)(i))<tol, true);\n  //  }\n\n  //   // Others ...\n  // Triang\n\n  SP::SiconosMatrix A2(new SimpleMatrix(10, 10, TRIANGULAR));\n  for(unsigned i = 0; i < A2->size(0); ++ i)\n    for(unsigned j = i; j < A2->size(1); ++ j)\n      (*A2)(i, j) = 3 * i + j;\n\n  *y = *v;\n  subprod(*A2, *v, *y, coord, false);\n  res = (*A2)(0, 1) * (*v)(3) + (*A2)(0, 2) * (*v)(4) + (*v)(2);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8_6: \", fabs(res - (*y)(2)) < tol, true);\n  res = (*A2)(1, 1) * (*v)(3) + (*A2)(1, 2) * (*v)(4) + (*v)(3);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8_6: \", fabs(res - (*y)(3)) < tol, true);\n  for(unsigned int i = 0; i < size; ++i)\n  {\n    if(i != 2 && i != 3)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8_6: \", fabs((*y)(i) - (*v)(i)) < tol, true);\n  }\n\n  // Sym\n  A2.reset(new SimpleMatrix(10, 10, SYMMETRIC));\n  for(unsigned i = 0; i < A2->size(0); ++ i)\n    for(unsigned j = i; j < A2->size(1); ++ j)\n      (*A2)(i, j) = 3 * i + j;\n\n  *y = *v;\n  subprod(*A2, *v, *y, coord, false);\n  res = (*A2)(0, 1) * (*v)(3) + (*A2)(0, 2) * (*v)(4) + (*v)(2);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8_6: \", fabs(res - (*y)(2)) < tol, true);\n  res = (*A2)(1, 1) * (*v)(3) + (*A2)(1, 2) * (*v)(4) + (*v)(3);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8_6: \", fabs(res - (*y)(3)) < tol, true);\n  for(unsigned int i = 0; i < size; ++i)\n  {\n    if(i != 2 && i != 3)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8_6: \", fabs((*y)(i) - (*v)(i)) < tol, true);\n  }\n\n  // Sparse\n  A2.reset(new SimpleMatrix(10, 10, Siconos::SPARSE));\n  for(unsigned i = 0; i < A2->size(0); ++ i)\n    for(unsigned j = i; j < A2->size(1); ++ j)\n      A2->setValue(i, j, 3 * i + j);\n\n  *y = *v;\n  subprod(*A2, *v, *y, coord, false);\n  res = (*A2)(0, 1) * (*v)(3) + (*A2)(0, 2) * (*v)(4) + (*v)(2);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8_6: \", fabs(res - (*y)(2)) < tol, true);\n  res = (*A2)(1, 1) * (*v)(3) + (*A2)(1, 2) * (*v)(4) + (*v)(3);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8_6: \", fabs(res - (*y)(3)) < tol, true);\n  for(unsigned int i = 0; i < size; ++i)\n  {\n    if(i != 2 && i != 3)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8_6: \", fabs((*y)(i) - (*v)(i)) < tol, true);\n  }\n\n  // Banded\n  A2.reset(new SimpleMatrix(10, 10, BANDED));\n  for(signed i = 0; i < signed(A2->size(0)); ++ i)\n    for(signed j = std::max(i - 1, 0); j < std::min(i + 2, signed(A2->size(1))); ++ j)\n      (*A2)(i, j) = 3 * i + j;\n  *y = *v;\n  subprod(*A2, *v, *y, coord, false);\n  res = (*A2)(0, 1) * (*v)(3) + (*v)(2);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8_6: \", fabs(res - (*y)(2)) < tol, true);\n  res = (*A2)(1, 1) * (*v)(3) + (*A2)(1, 2) * (*v)(4) + (*v)(3);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8_6: \", fabs(res - (*y)(3)) < tol, true);\n  for(unsigned int i = 0; i < size; ++i)\n  {\n    if(i != 2 && i != 3)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators8_6: \", fabs((*y)(i) - (*v)(i)) < tol, true);\n  }\n\n  std::cout << \"-->  test operators8_6 ended with success.\" <<std::endl;\n}\n\nvoid SimpleMatrixTest::testOperators9()\n{\n  std::cout << \"--> Test: operator9.\" <<std::endl;\n\n  // C = a*A or A/a\n\n  double a = 2.2;\n  int a1 = 3;\n\n  // Simple = a * Simple or Simple/a\n  *C = a * *A;\n  for(unsigned int i = 0; i < C->size(0); ++i)\n    for(unsigned int j = i ; j < C->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators9: \", fabs((*C)(i, j) - a * (*A)(i, j)) < tol, true);\n  *C = a1 * *A;\n  for(unsigned int i = 0; i < C->size(0); ++i)\n    for(unsigned int j = i ; j < C->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators9: \", fabs((*C)(i, j) - a1 * (*A)(i, j)) < tol, true);\n\n  // *C = *A / a;\n  // for (unsigned int i = 0; i < C->size(0); ++i)\n  //   for (unsigned int j = i ; j < C->size(1); ++j)\n  //     CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators9: \", fabs((*C)(i, j) - (*A)(i, j) / a) < tol, true);\n  // *C = *A / a1;\n  // for (unsigned int i = 0; i < C->size(0); ++i)\n  //   for (unsigned int j = i ; j < C->size(1); ++j)\n  //     CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators9: \", fabs((*C)(i, j) - (*A)(i, j) / a1) < tol, true);\n\n  // Simple = a * Block\n\n  *C = a * *Ab;\n  for(unsigned int i = 0; i < C->size(0); ++i)\n    for(unsigned int j = i ; j < C->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators9: \", fabs((*C)(i, j) - a * (*Ab)(i, j)) < tol, true);\n  ;\n  *C = a1 * *Ab;\n  for(unsigned int i = 0; i < C->size(0); ++i)\n    for(unsigned int j = i ; j < C->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators9: \", fabs((*C)(i, j) - a1 * (*Ab)(i, j)) < tol, true);\n\n  // *C = *Ab / a;\n  // for (unsigned int i = 0; i < C->size(0); ++i)\n  //   for (unsigned int j = i ; j < C->size(1); ++j)\n  //     CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators9: \", fabs((*C)(i, j) - (*Ab)(i, j) / a) < tol, true);\n  // *C = *Ab / a1;\n  // for (unsigned int i = 0; i < C->size(0); ++i)\n  //   for (unsigned int j = i ; j < C->size(1); ++j)\n  //     CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators9: \", fabs((*C)(i, j) - (*Ab)(i, j) / a1) < tol, true);\n\n  // Block = a * Block\n  *Cb = a * *Ab;\n  for(unsigned int i = 0; i < Cb->size(0); ++i)\n    for(unsigned int j = i ; j < Cb->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators9: \", fabs((*Cb)(i, j) - a * (*Ab)(i, j)) < tol, true);\n  *Cb = a1 * *Ab;\n  for(unsigned int i = 0; i < Cb->size(0); ++i)\n    for(unsigned int j = i ; j < Cb->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators9: \", fabs((*Cb)(i, j) - a1 * (*Ab)(i, j)) < tol, true);\n\n  // *Cb = *Ab / a;\n  // for (unsigned int i = 0; i < Cb->size(0); ++i)\n  //   for (unsigned int j = i ; j < Cb->size(1); ++j)\n  //     CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators9: \", fabs((*Cb)(i, j) - (*Ab)(i, j) / a) < tol, true);\n  // *Cb = *Ab / a1;\n  // for (unsigned int i = 0; i < Cb->size(0); ++i)\n  //   for (unsigned int j = i ; j < Cb->size(1); ++j)\n  //     CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators9: \", fabs((*Cb)(i, j) - (*Ab)(i, j) / a1) < tol, true);\n\n  // Block = a * Simple\n  *Cb = a * *A;\n  for(unsigned int i = 0; i < Cb->size(0); ++i)\n    for(unsigned int j = i ; j < Cb->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators9: \", fabs((*Cb)(i, j) - a * (*A)(i, j)) < tol, true);\n  *Cb = a1 * *A;\n  for(unsigned int i = 0; i < Cb->size(0); ++i)\n    for(unsigned int j = i ; j < Cb->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators9: \", fabs((*Cb)(i, j) - a1 * (*A)(i, j)) < tol, true);\n\n  // *Cb = *A / a;\n  // for (unsigned int i = 0; i < Cb->size(0); ++i)\n  //   for (unsigned int j = i ; j < Cb->size(1); ++j)\n  //     CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators9: \", fabs((*Cb)(i, j) - (*A)(i, j) / a) < tol, true);\n  // *Cb = *A / a1;\n  // for (unsigned int i = 0; i < Cb->size(0); ++i)\n  //   for (unsigned int j = i ; j < Cb->size(1); ++j)\n  //     CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators9: \", fabs((*Cb)(i, j) - (*A)(i, j) / a1) < tol, true);\n  std::cout << \"-->  test operators9 ended with success.\" <<std::endl;\n}\n\nvoid SimpleMatrixTest::testOperators9Bis()\n{\n  std::cout << \"--> Test: operator9Bis.\" <<std::endl;\n\n  // C = a*A or A/a\n\n  double a = 2.2;\n\n  // Simple = a * Simple or Simple/a\n  scal(a, *A, *C);\n  for(unsigned int i = 0; i < C->size(0); ++i)\n    for(unsigned int j = i ; j < C->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators9Bis: \", fabs((*C)(i, j) - a * (*A)(i, j)) < tol, true);\n\n  scal(1.0 / a, *A, *C);\n  for(unsigned int i = 0; i < C->size(0); ++i)\n    for(unsigned int j = i ; j < C->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators9Bis: \", fabs((*C)(i, j) - (*A)(i, j) / a) < tol, true);\n  // Simple = a * Block\n\n  scal(a, *Ab, *C);\n  for(unsigned int i = 0; i < C->size(0); ++i)\n    for(unsigned int j = i ; j < C->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators9Bis: \", fabs((*C)(i, j) - a * (*Ab)(i, j)) < tol, true);\n\n  scal(1.0 / a, *Ab, *C);\n  for(unsigned int i = 0; i < C->size(0); ++i)\n    for(unsigned int j = i ; j < C->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators9Bis: \", fabs((*C)(i, j) - (*Ab)(i, j) / a) < tol, true);\n\n  // Block = a * Block\n  scal(a, *Ab, *Cb);\n  for(unsigned int i = 0; i < Cb->size(0); ++i)\n    for(unsigned int j = i ; j < Cb->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators9Bis: \", fabs((*Cb)(i, j) - a * (*Ab)(i, j)) < tol, true);\n\n  scal(1.0 / a, *Ab, *Cb);\n  for(unsigned int i = 0; i < Cb->size(0); ++i)\n    for(unsigned int j = i ; j < Cb->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators9Bis: \", fabs((*Cb)(i, j) - (*Ab)(i, j) / a) < tol, true);\n\n  // Block = a * Simple\n  scal(a, *A, *Cb);\n  for(unsigned int i = 0; i < Cb->size(0); ++i)\n    for(unsigned int j = i ; j < Cb->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators9Bis: \", fabs((*Cb)(i, j) - a * (*A)(i, j)) < tol, true);\n\n  scal(1.0 / a, *A, *Cb);\n  for(unsigned int i = 0; i < Cb->size(0); ++i)\n    for(unsigned int j = i ; j < Cb->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators9Bis: \", fabs((*Cb)(i, j) - (*A)(i, j) / a) < tol, true);\n  std::cout << \"-->  test operators9Bis ended with success.\" <<std::endl;\n}\n\nvoid SimpleMatrixTest::testOperators9Ter()\n{\n  std::cout << \"--> Test: operator9Ter.\" <<std::endl;\n\n  // C += a*A or A/a\n\n  double a = 2.2;\n  C->zero();\n  // Simple = a * Simple or Simple/a\n  scal(a, *A, *C, false);\n  scal(a, *A, *C, false);\n  for(unsigned int i = 0; i < C->size(0); ++i)\n    for(unsigned int j = i ; j < C->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators9Ter: \", fabs((*C)(i, j) - 2 * a * (*A)(i, j)) < tol, true);\n\n  // Simple = a * Block\n  C->zero();\n  scal(a, *Ab, *C, false);\n  scal(a, *Ab, *C, false);\n  for(unsigned int i = 0; i < C->size(0); ++i)\n    for(unsigned int j = i ; j < C->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators9Ter: \", fabs((*C)(i, j) - 2 * a * (*Ab)(i, j)) < tol, true);\n\n  // Block = a * Block\n  Cb->zero();\n  scal(a, *Ab, *Cb, false);\n  scal(a, *Ab, *Cb, false);\n  for(unsigned int i = 0; i < Cb->size(0); ++i)\n    for(unsigned int j = i ; j < Cb->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators9Ter: \", fabs((*Cb)(i, j) - 2 * a * (*Ab)(i, j)) < tol, true);\n\n  // Block = a * Simple\n  Cb->zero();\n  scal(a, *A, *Cb, false);\n  scal(a, *A, *Cb, false);\n  for(unsigned int i = 0; i < Cb->size(0); ++i)\n    for(unsigned int j = i ; j < Cb->size(1); ++j)\n      CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators9Ter: \", fabs((*Cb)(i, j) - 2 * a * (*A)(i, j)) < tol, true);\n\n  std::cout << \"-->  test operators9Ter ended with success.\" <<std::endl;\n}\n\nvoid SimpleMatrixTest::testOperators10()\n{\n  std::cout << \"--> Test: operator10.\" <<std::endl;\n  double m = 2.2;\n  int i = 3;\n  SP::SiconosMatrix tmp1(new SimpleMatrix(*T));\n  SP::SiconosMatrix res(new SimpleMatrix(3, 3, TRIANGULAR));\n  *res = m ** tmp1;\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", norm_inf(res->getTriang() - tmp1->getTriang()*m) < tol, true);\n  *res = i ** tmp1;\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", norm_inf(res->getTriang() - tmp1->getTriang()*i) < tol, true);\n  // *res = *tmp1 / m;\n  // CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", norm_inf(res->getTriang() - tmp1->getTriang() / m) < tol, true);\n  // *res = *tmp1 / i;\n  // CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", norm_inf(res->getTriang() - tmp1->getTriang() / i) < tol, true);\n  std::cout << \"-->  test operators10 ended with success.\" <<std::endl;\n}\n\nvoid SimpleMatrixTest::testOperators11()\n{\n  std::cout << \"--> Test: operator11.\" <<std::endl;\n  double m = 2.2;\n  int i = 3;\n  SP::SiconosMatrix tmp1(new SimpleMatrix(*S));\n  SP::SiconosMatrix res(new SimpleMatrix(3, 3, SYMMETRIC));\n  *res = m ** tmp1;\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", norm_inf(res->getSym() - tmp1->getSym()*m) < tol, true);\n  *res = i ** tmp1;\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", norm_inf(res->getSym() - tmp1->getSym()*i) < tol, true);\n  // *res = *tmp1 / m;\n  // CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", norm_inf(res->getSym() - tmp1->getSym() / m) < tol, true);\n  // *res = *tmp1 / i;\n  // CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", norm_inf(res->getSym() - tmp1->getSym() / i) < tol, true);\n  std::cout << \"-->  test operator11 ended with success.\" <<std::endl;\n}\n\nvoid SimpleMatrixTest::testOperators12()\n{\n  std::cout << \"--> Test: operator12.\" <<std::endl;\n  double m = 2.2;\n  int i = 3;\n  SP::SiconosMatrix tmp1(new SimpleMatrix(*SP));\n  SP::SiconosMatrix res(new SimpleMatrix(4, 4, Siconos::SPARSE));\n  *res = m ** tmp1;\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", norm_inf(res->getSparse() - tmp1->getSparse()*m) < tol, true);\n  *res = i ** tmp1;\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", norm_inf(res->getSparse() - tmp1->getSparse()*i) < tol, true);\n  // *res = *tmp1 / m;\n  // CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", norm_inf(res->getSparse() - tmp1->getSparse() / m) < tol, true);\n  // *res = *tmp1 / i;\n  // CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", norm_inf(res->getSparse() - tmp1->getSparse() / i) < tol, true);\n  std::cout << \"-->  test operators12 ended with success.\" <<std::endl;\n}\n\nvoid SimpleMatrixTest::testOperators13()\n{\n  std::cout << \"--> Test: operator13.\" <<std::endl;\n  //   double m = 2.2;\n  //   int i = 3;\n  //   SP::SiconosMatrix tmp1(new SimpleMatrix(*Band);\n  //   SP::SiconosMatrix res(new SimpleMatrix(*Band);//4,4,BANDED,1,1);\n  //   *res = m * *tmp1;\n  //   CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", norm_inf(res->getBanded()- tmp1->getBanded()*m)<tol, true);\n  //   *res = i ** tmp1;\n  //   CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", norm_inf(res->getBanded()- tmp1->getBanded()*i)<tol, true);\n  //   *res = *tmp1 * m;\n  //   CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", norm_inf(res->getBanded()- tmp1->getBanded()*m)<tol, true);\n  //   *res = *tmp1 * i;\n  //   CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", norm_inf(res->getBanded()- tmp1->getBanded()*i)<tol, true);\n  //   *res = *tmp1 / m;\n  //   CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", norm_inf(res->getBanded()- tmp1->getBanded()/m)<tol, true);\n  //   *res = *tmp1 / i;\n  //   CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testOperators: \", norm_inf(res->getBanded()- tmp1->getBanded()/i)<tol, true);\n  std::cout << \"-->  test operators13 ended with success.\" <<std::endl;\n}\n\nvoid SimpleMatrixTest::testProd() // y = A*x\n{\n  std::cout << \"--> Test: prod. mat-vect\" <<std::endl;\n\n  SP::SiconosVector y(new SiconosVector(size));\n  SP::SiconosVector x(new SiconosVector(size, 4.3));\n  SP::SiconosVector x1(new SiconosVector(size - 2, 2.3));\n  SP::SiconosVector x2(new SiconosVector(2, 3.1));\n\n  SP::BlockVector xB(new BlockVector(x1, x2));\n  SP::BlockVector yB(new BlockVector(*xB));\n  yB->zero();\n\n  // Matrix - vector product\n\n  // Simple = Simple * Simple\n  *y = prod(*A, *x);\n  double sum;\n  for(unsigned int i = 0; i < size; ++i)\n  {\n    sum = 0;\n    for(unsigned int j = 0; j < A->size(1); ++j)\n      sum += (*A)(i, j) * (*x)(j);\n    CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testProd: \", fabs((*y)(i) - sum) < tol, true);\n  }\n  // Simple = Simple * Block\n  //  *y = prod(*A , *xB);\n  //  for (unsigned int i = 0; i< size; ++i)\n  //  {\n  //    sum = 0;\n  //    for (unsigned int j=0; j< A->size(1); ++j)\n  //      sum += (*A)(i,j)*(*xB)(j);\n  //   CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testProd: \", fabs((*y)(i) - sum)< tol, true);\n  //  }\n\n\n  // Block = Simple * Simple\n  *yB = prod(*A, *x);\n  for(unsigned int i = 0; i < size; ++i)\n  {\n    sum = 0;\n    for(unsigned int j = 0; j < A->size(1); ++j)\n      sum += (*A)(i, j) * (*x)(j);\n    CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testProd: \", fabs((*yB)(i) - sum) < tol, true);\n  }\n\n  // Block = Simple * Block\n  //  *yB = prod(*A ,*xB);\n  //  for (unsigned int i = 0; i< size; ++i)\n  //  {\n  //    sum = 0;\n  //    for (unsigned int j=0; j< A->size(1); ++j)\n  //      sum += (*A)(i,j)*(*xB)(j);\n  //    CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testProd: \", fabs((*yB)(i) - sum)< tol, true);\n  //  }\n\n  // Others or old stuff ...\n\n  SP::SiconosMatrix tmp2(new SimpleMatrix(*T));\n  SP::SiconosMatrix tmp3(new SimpleMatrix(*S));\n  SP::SiconosMatrix tmp4(new SimpleMatrix(*SP));\n  SP::SiconosMatrix tmp5(new SimpleMatrix(*Band2));\n  SP::SiconosVector v(new SiconosVector(3));\n  (*v)(0) = 1;\n  (*v)(1) = 2;\n  (*v)(2) = 3;\n  SP::SiconosVector vv(new SiconosVector(4));\n  (*vv)(0) = 1;\n  (*vv)(1) = 2;\n  (*vv)(2) = 3;\n  SparseVect * sv(new SparseVect(3));\n  (*sv)(0) = 4;\n  (*sv)(1) = 5;\n  (*sv)(2) = 6;\n  SparseVect * sv2(new SparseVect(4));\n  (*sv2)(0) = 4;\n  (*sv2)(1) = 5;\n  (*sv2)(2) = 6;\n  SP::SiconosVector w(new SiconosVector(*sv));\n  SP::SiconosVector ww(new SiconosVector(*sv2));\n  SP::SiconosVector res(new SiconosVector(4));\n  SP::SiconosVector res2(new SiconosVector(3));\n\n  // Triang * ...\n  *res2 = prod(*tmp2, *v);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testProd: \", norm_2(*res2->dense() - prod(tmp2->getTriang(), *v->dense())) < tol, true);\n  *res2 = prod(*tmp2, *w);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testProd: \", norm_2(*res2->dense() - prod(tmp2->getTriang(), *w->sparse())) < tol, true);\n  //   Sym * ...\n  *res2 = prod(*tmp3, *v);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testProd: \", norm_2(*res2->dense() - prod(tmp3->getSym(), *v->dense())) < tol, true);\n  *res2 = prod(*tmp3, *w);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testProd: \", norm_2(*res2->dense() - prod(tmp3->getSym(), *w->sparse())) < tol, true);\n  // Sparse * ...\n  *res = prod(*tmp4, *vv);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testProd: \", norm_2(*res->dense() - prod(tmp4->getSparse(), *vv->dense())) < tol, true);\n  *res = prod(*tmp4, *ww);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testProd: \", norm_2(*res->dense() - prod(tmp4->getSparse(), *ww->sparse())) < tol, true);\n  // Triang * ...\n  *res = prod(*tmp5, *v);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testProd: \", norm_2(*res->dense() - prod(tmp5->getBanded(), *v->dense())) < tol, true);\n  *res = prod(*tmp5, *w);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testProd: \", norm_2(*res->dense() - prod(tmp5->getBanded(), *w->sparse())) < tol, true);\n  std::cout << \"-->  test prod ended with success.\" <<std::endl;\n\n  delete sv2;\n  delete sv;\n}\n\nvoid SimpleMatrixTest::testProdBis()\n{\n  std::cout << \"--> Test: prod. mat-vect (bis)\" <<std::endl;\n\n  SP::SiconosVector y(new SiconosVector(size));\n  SP::SiconosVector x(new SiconosVector(size, 4.3));\n  SP::SiconosVector x1(new SiconosVector(size - 2, 2.3));\n  SP::SiconosVector x2(new SiconosVector(2, 3.1));\n\n  SP::BlockVector xB(new BlockVector(x1, x2));\n  SP::BlockVector yB(new BlockVector(*xB));\n  yB->zero();\n\n  // Matrix - vector product\n\n  // Simple = Simple * Simple\n  prod(*A, *x, *y);\n  double sum;\n  for(unsigned int i = 0; i < size; ++i)\n  {\n    sum = 0;\n    for(unsigned int j = 0; j < A->size(1); ++j)\n      sum += (*A)(i, j) * (*x)(j);\n    CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testProdBis: \", fabs((*y)(i) - sum) < tol, true);\n  }\n  // Simple = Simple * Block\n  prod(*A, *xB, *y);\n  for(unsigned int i = 0; i < size; ++i)\n  {\n    sum = 0;\n    for(unsigned int j = 0; j < A->size(1); ++j)\n      sum += (*A)(i, j) * (*xB)(j);\n    CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testProdBis: \", fabs((*y)(i) - sum) < tol, true);\n  }\n\n  // Block = Simple * Simple\n  prod(*A, *x, *yB);\n  for(unsigned int i = 0; i < size; ++i)\n  {\n    sum = 0;\n    for(unsigned int j = 0; j < A->size(1); ++j)\n      sum += (*A)(i, j) * (*x)(j);\n    CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testProdBis: \", fabs((*yB)(i) - sum) < tol, true);\n  }\n\n  // Block = Simple * Block\n  //  prod(*A ,*xB,*yB);\n  //  for (unsigned int i = 0; i< size; ++i)\n  //  {\n  //    sum = 0;\n  //    for (unsigned int j=0; j< A->size(1); ++j)\n  //      sum += (*A)(i,j)*(*xB)(j);\n  //    CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testProdBis: \", fabs((*yB)(i) - sum)< tol, true);\n  //  }\n  //\n  // Others or old stuff ...\n\n  SP::SiconosMatrix tmp2(new SimpleMatrix(*T));\n  SP::SiconosMatrix tmp3(new SimpleMatrix(*S));\n  SP::SiconosMatrix tmp4(new SimpleMatrix(*SP));\n  SP::SiconosMatrix tmp5(new SimpleMatrix(*Band2));\n  SP::SiconosVector v(new SiconosVector(3));\n  (*v)(0) = 1;\n  (*v)(1) = 2;\n  (*v)(2) = 3;\n  SP::SiconosVector vv(new SiconosVector(4));\n  (*vv)(0) = 1;\n  (*vv)(1) = 2;\n  (*vv)(2) = 3;\n  SP::SparseVect sv(new SparseVect(3));\n  (*sv)(0) = 4;\n  (*sv)(1) = 5;\n  (*sv)(2) = 6;\n  SP::SparseVect sv2(new SparseVect(4));\n  (*sv2)(0) = 4;\n  (*sv2)(1) = 5;\n  (*sv2)(2) = 6;\n  SP::SiconosVector w(new SiconosVector(*sv));\n  SP::SiconosVector ww(new SiconosVector(*sv2));\n  SP::SiconosVector res(new SiconosVector(4));\n  SP::SiconosVector res2(new SiconosVector(3));\n\n  // Triang * ...\n  prod(*tmp2, *v, *res2);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testProdBis: \", norm_2(*res2->dense() - prod(tmp2->getTriang(), *v->dense())) < tol, true);\n  prod(*tmp2, *w, *res2);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testProdBis: \", norm_2(*res2->dense() - prod(tmp2->getTriang(), *w->sparse())) < tol, true);\n  //   Sym * ...\n  prod(*tmp3, *v, *res2);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testProdBis: \", norm_2(*res2->dense() - prod(tmp3->getSym(), *v->dense())) < tol, true);\n  prod(*tmp3, *w, *res2);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testProdBis: \", norm_2(*res2->dense() - prod(tmp3->getSym(), *w->sparse())) < tol, true);\n  // Sparse * ...\n  prod(*tmp4, *vv, *res);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testProdBis: \", norm_2(*res->dense() - prod(tmp4->getSparse(), *vv->dense())) < tol, true);\n  prod(*tmp4, *ww, *res);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testProdBis: \", norm_2(*res->dense() - prod(tmp4->getSparse(), *ww->sparse())) < tol, true);\n  // Banded * ...\n  prod(*tmp5, *v, *res);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testProdBis: \", norm_2(*res->dense() - prod(tmp5->getBanded(), *v->dense())) < tol, true);\n  prod(*tmp5, *w, *res);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testProdBis: \", norm_2(*res->dense() - prod(tmp5->getBanded(), *w->sparse())) < tol, true);\n  std::cout << \"-->  test prodBis ended with success.\" <<std::endl;\n}\n\nvoid SimpleMatrixTest::testProdTer()\n{\n  std::cout << \"--> Test: prod. mat-vect (ter)\" <<std::endl;\n\n  SP::SiconosVector y(new SiconosVector(size));\n  SP::SiconosVector x(new SiconosVector(size, 4.3));\n  SP::SiconosVector x1(new SiconosVector(size - 2, 2.3));\n  SP::SiconosVector x2(new SiconosVector(2, 3.1));\n\n  SP::BlockVector xB(new BlockVector(x1, x2));\n  SP::BlockVector yB(new BlockVector(*xB));\n  yB->zero();\n\n  // Matrix - vector product\n\n  // Simple = Simple * Simple\n  // axpy_prod(*A, *x, *y, true);\n  // double sum;\n  // for (unsigned int i = 0; i < size; ++i)\n  // {\n  //   sum = 0;\n  //   for (unsigned int j = 0; j < A->size(1); ++j)\n  //     sum += (*A)(i, j) * (*x)(j);\n  //   CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testProdTer: \", fabs((*y)(i) - sum) < tol, true);\n  // }\n\n  //SP::SiconosVector backUp(new SiconosVector(*y));\n  // // Simple += Simple * Simple\n  // axpy_prod(*A, *x, *y, false);\n  // for (unsigned int i = 0; i < size; ++i)\n  // {\n  //   sum = 0;\n  //   for (unsigned int j = 0; j < A->size(1); ++j)\n  //     sum += (*A)(i, j) * (*x)(j);\n  //   CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testProdTer: \", fabs((*y)(i) - sum - (*backUp)(i)) < tol, true);\n  // }\n\n  // Simple = Simple * Block\n  //  axpy_prod(*A ,*xB,*y, true);\n  //  for (unsigned int i = 0; i< size; ++i)\n  //  {\n  //    sum = 0;\n  //    for (unsigned int j=0; j< A->size(1); ++j)\n  //      sum += (*A)(i,j)*(*xB)(j);\n  //    CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testProdTer: \", fabs((*y)(i) - sum)< tol, true);\n  //  }\n  //\n  //*backUp = *y;\n  // Simple += Simple * Block\n  //  axpy_prod(*A ,*xB,*y, false);\n  //  for (unsigned int i = 0; i< size; ++i)\n  //  {\n  //    sum = 0;\n  //    for (unsigned int j=0; j< A->size(1); ++j)\n  //      sum += (*A)(i,j)*(*xB)(j);\n  //    CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testProdTer: \", fabs((*y)(i) - sum - (*backUp)(i))< tol, true);\n  //  }\n  //\n  //  // Block = Simple * Simple\n  //  axpy_prod(*A ,*x,*yB, true);\n  //  for (unsigned int i = 0; i< size; ++i)\n  //  {\n  //    sum = 0;\n  //    for (unsigned int j=0; j< A->size(1); ++j)\n  //      sum += (*A)(i,j)*(*x)(j);\n  //    CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testProdTer: \", fabs((*yB)(i) - sum)< tol, true);\n  //  }\n  //\n  //  // Block += Simple * Simple\n  //  *backUp = *yB;\n  //  axpy_prod(*A ,*x,*yB, false);\n  //  for (unsigned int i = 0; i< size; ++i)\n  //  {\n  //    sum = 0;\n  //    for (unsigned int j=0; j< A->size(1); ++j)\n  //      sum += (*A)(i,j)*(*x)(j);\n  //    CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testProdTer: \", fabs((*yB)(i) - sum - (*backUp)(i))< tol, true);\n  //  }\n  //\n  //  // Block = Simple * Block\n  //  axpy_prod(*A ,*xB,*yB,true);\n  //  for (unsigned int i = 0; i< size; ++i)\n  //  {\n  //    sum = 0;\n  //    for (unsigned int j=0; j< A->size(1); ++j)\n  //      sum += (*A)(i,j)*(*xB)(j);\n  //    CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testProdTer: \", fabs((*yB)(i) - sum)< tol, true);\n  //  }\n  //\n  //  // Block += Simple * Block\n  //  *backUp = *yB;\n  //  axpy_prod(*A ,*xB,*yB,false);\n  //  for (unsigned int i = 0; i< size; ++i)\n  //  {\n  //    sum = 0;\n  //    for (unsigned int j=0; j< A->size(1); ++j)\n  //      sum += (*A)(i,j)*(*xB)(j);\n  //    CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testProdTer: \", fabs((*yB)(i) - sum - (*backUp)(i))< tol, true);\n  //  }\n  //  // Others or old stuff ...\n\n  SP::SiconosMatrix tmp2(new SimpleMatrix(*T));\n  SP::SiconosMatrix tmp3(new SimpleMatrix(*S));\n  SP::SiconosMatrix tmp4(new SimpleMatrix(*SP));\n  SP::SiconosMatrix tmp5(new SimpleMatrix(*Band2));\n  SP::SiconosVector v(new SiconosVector(3));\n  (*v)(0) = 1;\n  (*v)(1) = 2;\n  (*v)(2) = 3;\n  SP::SiconosVector vv(new SiconosVector(4));\n  (*vv)(0) = 1;\n  (*vv)(1) = 2;\n  (*vv)(2) = 3;\n  SP::SparseVect sv(new SparseVect(3));\n  (*sv)(0) = 4;\n  (*sv)(1) = 5;\n  (*sv)(2) = 6;\n  SP::SparseVect sv2(new SparseVect(4));\n  (*sv2)(0) = 4;\n  (*sv2)(1) = 5;\n  (*sv2)(2) = 6;\n  SP::SiconosVector w(new SiconosVector(*sv));\n  SP::SiconosVector ww(new SiconosVector(*sv2));\n  SP::SiconosVector res(new SiconosVector(4));\n  SP::SiconosVector res2(new SiconosVector(3));\n\n  // Triang * ...\n  prod(*tmp2, *v, *res2);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testProdTer: \", norm_2(*res2->dense() - prod(tmp2->getTriang(), *v->dense())) < tol, true);\n  prod(*tmp2, *w, *res2);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testProdTer: \", norm_2(*res2->dense() - prod(tmp2->getTriang(), *w->sparse())) < tol, true);\n  //   Sym * ...\n  prod(*tmp3, *v, *res2);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testProdTer: \", norm_2(*res2->dense() - prod(tmp3->getSym(), *v->dense())) < tol, true);\n  prod(*tmp3, *w, *res2);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testProdTer: \", norm_2(*res2->dense() - prod(tmp3->getSym(), *w->sparse())) < tol, true);\n  // Sparse * ...\n  prod(*tmp4, *vv, *res);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testProdTer: \", norm_2(*res->dense() - prod(tmp4->getSparse(), *vv->dense())) < tol, true);\n  prod(*tmp4, *ww, *res);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testProdTer: \", norm_2(*res->dense() - prod(tmp4->getSparse(), *ww->sparse())) < tol, true);\n  // Banded * ...\n  prod(*tmp5, *v, *res);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testProdTer: \", norm_2(*res->dense() - prod(tmp5->getBanded(), *v->dense())) < tol, true);\n  prod(*tmp5, *w, *res);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testProdTer: \", norm_2(*res->dense() - prod(tmp5->getBanded(), *w->sparse())) < tol, true);\n  std::cout << \"-->  test prodTer ended with success.\" <<std::endl;\n}\n\nvoid SimpleMatrixTest::testProd4() // y += A*x\n{\n  std::cout << \"--> Test: prod. mat-vect (4)\" <<std::endl;\n\n  SP::SiconosVector y(new SiconosVector(size));\n  SP::SiconosVector x(new SiconosVector(size, 4.3));\n  SP::SiconosVector x1(new SiconosVector(size - 2, 2.3));\n  SP::SiconosVector x2(new SiconosVector(2, 3.1));\n\n  SP::BlockVector xB(new BlockVector(x1, x2));\n  SP::BlockVector yB(new BlockVector(*xB));\n  yB->zero();\n\n  // Matrix - vector product\n\n  // Simple = Simple * Simple\n  y->zero();\n  prod(*A, *x, *y, false);\n  prod(*A, *x, *y, false);\n  double sum;\n  for(unsigned int i = 0; i < size; ++i)\n  {\n    sum = 0;\n    for(unsigned int j = 0; j < A->size(1); ++j)\n      sum += 2 * (*A)(i, j) * (*x)(j);\n    CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testProd4: \", fabs((*y)(i) - sum) < tol, true);\n  }\n  // Simple = Simple * Block\n  y->zero();\n  prod(*A, *xB, *y, false);\n  prod(*A, *xB, *y, false);\n  for(unsigned int i = 0; i < size; ++i)\n  {\n    sum = 0;\n    for(unsigned int j = 0; j < A->size(1); ++j)\n      sum += 2 * (*A)(i, j) * (*xB)(j);\n    CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testProd4: \", fabs((*y)(i) - sum) < tol, true);\n  }\n\n  // Block = Simple * Simple\n  yB->zero();\n  prod(*A, *x, *yB, false);\n  prod(*A, *x, *yB, false);\n  for(unsigned int i = 0; i < size; ++i)\n  {\n    sum = 0;\n    for(unsigned int j = 0; j < A->size(1); ++j)\n      sum += 2 * (*A)(i, j) * (*x)(j);\n    CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testProd4: \", fabs((*yB)(i) - sum) < tol, true);\n  }\n\n  // Block = Simple * Block\n  yB->zero();\n  //  prod(*A ,*xB,*yB,false);\n  //  prod(*A ,*xB,*yB,false);\n  //  for (unsigned int i = 0; i< size; ++i)\n  //  {\n  //    sum = 0;\n  //    for (unsigned int j=0; j< A->size(1); ++j)\n  //      sum += 2*(*A)(i,j)*(*xB)(j);\n  //    CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testProd4: \", fabs((*yB)(i) - sum)< tol, true);\n  //  }\n  std::cout << \"-->  test prod4 ended with success.\" <<std::endl;\n}\n\nvoid SimpleMatrixTest::testProd5() // y += a*A*x\n{\n  std::cout << \"--> Test: prod. mat-vect (5)\" <<std::endl;\n\n  SP::SiconosVector y(new SiconosVector(size));\n  SP::SiconosVector x(new SiconosVector(size, 4.3));\n  SP::SiconosVector x1(new SiconosVector(size - 2, 2.3));\n  SP::SiconosVector x2(new SiconosVector(2, 3.1));\n\n  SP::BlockVector xB(new BlockVector(x1, x2));\n  SP::BlockVector yB(new BlockVector(*xB));\n  yB->zero();\n\n  // Matrix - vector product\n  double a = 3.0;\n  // Simple = Simple * Simple\n  y->zero();\n  prod(a, *A, *x, *y, false);\n  prod(a, *A, *x, *y, false);\n  double sum;\n  for(unsigned int i = 0; i < size; ++i)\n  {\n    sum = 0;\n    for(unsigned int j = 0; j < A->size(1); ++j)\n      sum += 2 * a * (*A)(i, j) * (*x)(j);\n    CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testProd5: \", fabs((*y)(i) - sum) < tol, true);\n  }\n  // Simple = Simple * Block\n  y->zero();\n  //  prod(a,*A ,*xB,*y,false);\n  //  prod(a,*A ,*xB,*y,false);\n  //  for (unsigned int i = 0; i< size; ++i)\n  //  {\n  //    sum = 0;\n  //    for (unsigned int j=0; j< A->size(1); ++j)\n  //      sum += a*2*(*A)(i,j)*(*xB)(j);\n  //    CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testProd5: \", fabs((*y)(i) - sum)< tol, true);\n  //  }\n\n  // Block = Simple * Simple\n  yB->zero();\n  //  prod(a,*A ,*x,*yB,false);\n  //  prod(a,*A ,*x,*yB,false);\n  //  for (unsigned int i = 0; i< size; ++i)\n  //  {\n  //    sum = 0;\n  //    for (unsigned int j=0; j< A->size(1); ++j)\n  //      sum += a*2*(*A)(i,j)*(*x)(j);\n  //    CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testProd5: \", fabs((*yB)(i) - sum)< tol, true);\n  //  }\n  //\n  // Block = Simple * Block\n  yB->zero();\n  //  prod(a,*A ,*xB,*yB,false);\n  //  prod(a,*A ,*xB,*yB,false);\n  //  for (unsigned int i = 0; i< size; ++i)\n  //  {\n  //    sum = 0;\n  //    for (unsigned int j=0; j< A->size(1); ++j)\n  //      sum += a*2*(*A)(i,j)*(*xB)(j);\n  //    CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testProd5: \", fabs((*yB)(i) - sum)< tol, true);\n  //  }\n  std::cout << \"-->  test prod5 ended with success.\" <<std::endl;\n}\n\nvoid SimpleMatrixTest::testProd6() // y += trans(A)*x\n{\n  std::cout << \"--> Test: prod. mat-vect (6)\" <<std::endl;\n\n  SP::SiconosVector y(new SiconosVector(size));\n  SP::SiconosVector x(new SiconosVector(size, 4.3));\n  SP::SiconosVector x1(new SiconosVector(size - 2, 2.3));\n  SP::SiconosVector x2(new SiconosVector(2, 3.1));\n\n  SP::BlockVector xB(new BlockVector(x1, x2));\n  SP::BlockVector yB(new BlockVector(*xB));\n  yB->zero();\n\n  SP::SiconosMatrix tmp(new SimpleMatrix(*A));\n  tmp->trans();\n  // Matrix - vector product\n\n  // Simple = Simple * Simple\n  y->zero();\n  prod(*x, *A, *y);\n  prod(*x, *A, *y, false);\n  double sum;\n  for(unsigned int i = 0; i < size; ++i)\n  {\n    sum = 0;\n    for(unsigned int j = 0; j < A->size(1); ++j)\n      sum += 2 * (*tmp)(i, j) * (*x)(j);\n    CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testProd6: \", fabs((*y)(i) - sum) < tol, true);\n  }\n  // Simple = Simple * Block\n  y->zero();\n  //  prod(*xB,*A,*y);\n  //  prod(*xB,*A,*y,false);\n  //\n  //  for (unsigned int i = 0; i< size; ++i)\n  //  {\n  //    sum = 0;\n  //    for (unsigned int j=0; j< size; ++j)\n  //      sum += 2*(*tmp)(i,j)*(*xB)(j);\n  //    CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testProd6: \", fabs((*y)(i) - sum)< tol, true);\n  //  }\n\n  // Block = Simple * Simple\n  yB->zero();\n  prod(*x, *A, *yB);\n  prod(*x, *A, *yB, false);\n  for(unsigned int i = 0; i < size; ++i)\n  {\n    sum = 0;\n    for(unsigned int j = 0; j < A->size(1); ++j)\n      sum += 2 * (*tmp)(i, j) * (*x)(j);\n    CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testProd6: \", fabs((*yB)(i) - sum) < tol, true);\n  }\n\n  // Block = Simple * Block\n  yB->zero();\n  //  prod(*xB,*A ,*yB);\n  //  prod(*xB,*A ,*yB,false);\n  //  for (unsigned int i = 0; i< size; ++i)\n  //  {\n  //    sum = 0;\n  //    for (unsigned int j=0; j< A->size(1); ++j)\n  //      sum += 2*(*tmp)(i,j)*(*xB)(j);\n  //    CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testProd6: \", fabs((*yB)(i) - sum)< tol, true);\n  //  }\n  std::cout << \"-->  test prod6 ended with success.\" <<std::endl;\n}\n\n// void SimpleMatrixTest::testGemv()\n// {\n//   std::cout << \"--> Test: gemv\" <<std::endl;\n\n//   SP::SiconosVector y(new SiconosVector(size, 1.0));\n//   SP::SiconosVector x(new SiconosVector(size, 4.3));\n\n//   SP::SiconosVector backUp(new SiconosVector(*y));\n\n//   double a = 2.3;\n//   double b = 1.5;\n//   double sum;\n//   gemv(a, *A, *x, b, *y);\n\n//   for (unsigned int i = 0; i < size; ++i)\n//   {\n//     sum = b * (*backUp)(i);\n//     for (unsigned int j = 0; j < A->size(1); ++j)\n//       sum += a * (*A)(i, j) * (*x)(j) ;\n//     CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testgemv: \", fabs((*y)(i) - sum) < tol, true);\n//   }\n\n//   *y = *backUp;\n//   gemvtranspose(a, *A, *x, b, *y);\n//   for (unsigned int i = 0; i < size; ++i)\n//   {\n//     sum = b * (*backUp)(i);\n//     for (unsigned int j = 0; j < A->size(0); ++j)\n//       sum += a * (*A)(j, i) * (*x)(j);\n//     CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testgemv (trans): \", fabs((*y)(i) - sum) < tol, true);\n//   }\n//   std::cout << \"-->  test gemv ended with success.\" <<std::endl;\n// }\n\n// void SimpleMatrixTest::testGemm()\n// {\n//   std::cout << \"--> Test: gemm.\" <<std::endl;\n\n//   double a = 2.3;\n//   double b = 1.5;\n//   *C = *A;\n//   SP::SiconosMatrix backUp(new SimpleMatrix(*C));\n\n//   gemm(a, *A, *B, b, *C);\n//   CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testGemm: \", norm_inf(*C->dense() - a * prod(*A->dense(), *B->dense()) - b**backUp->dense()) < tol, true);\n\n//   *C = *backUp;\n//   gemmtranspose(a, *A, *B, b, *C);\n//   CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testGemm (trans): \", norm_inf(*C->dense() - a * prod(trans(*A->dense()), trans(*B->dense())) - b**backUp->dense()) < tol, true);\n//   std::cout << \"-->  test gemm ended with success.\" <<std::endl;\n// }\n\n\nvoid SimpleMatrixTest::testFromAndFillCSC()\n{\n  std::cout << \"Start SimpleMatrixTest::testFromAndFillCSC() \"<< std::endl;\n  SP::SiconosMatrix Sparse4(new SimpleMatrix(*SP4));\n  Sparse4->updateNumericsMatrix();\n  NumericsMatrix *NM = Sparse4->numericsMatrix();\n  NM_display(NM);\n//  NumericsMatrix *NM_1 = NM_create(4,4, NM_SPARSE);\n\n  SP::SiconosMatrix Sparse1(new SimpleMatrix(4,4,Siconos::SPARSE));\n  Sparse1->fromCSC(NM_csc(NM));\n  Sparse1->displayExpert();\n\n  NumericsMatrix *NM_1 = NM_create(NM_SPARSE, 4,4);\n  NM_1->matrix2->origin = NSM_CSC;\n  NM_csc_alloc(NM_1, Sparse4->nnz());\n  Sparse4->fillCSC(NM_csc(NM_1));\n  //NM_display(NM_1);  --> Note FP : fails when exiting the function ... To be investigating ...\n  NM_1 = NM_free(NM_1);\n  std::cout << \"End SimpleMatrixTest::testFromAndFillCSC() \"<< std::endl;\n\n}\nvoid SimpleMatrixTest::testPLUFactorizationInPlace()\n{\n  std::cout << \"--> Test: PLUFactorizationInPlace.\" <<std::endl;\n\n  SP::SiconosMatrix Dense(new SimpleMatrix(*D));\n  Dense->display();\n  Dense->PLUFactorizationInPlace();\n  Dense->display();\n  //CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testPLUFactorizationInPlace: \",  < tol, true);\n\n  SP::SiconosMatrix Sparse(new SimpleMatrix(4,4,SPARSE));\n  Sparse->eye();\n  Sparse->display();\n  Sparse->PLUFactorizationInPlace();\n  Sparse->display();\n\n  SP::SimpleMatrix Sparse2(new SimpleMatrix(*SP4));\n  DEBUG_EXPR(Sparse2->display(););\n  Sparse2->PLUFactorizationInPlace();\n  DEBUG_EXPR(Sparse2->display(););\n\n  std::cout << \"-->  test PLUFactorizationInPlace ended with success.\" <<std::endl;\n}\n\nvoid SimpleMatrixTest::testFactorize()\n{\n  std::cout << \"--> Test: Factorize (LU).\" <<std::endl;\n\n  SP::SiconosMatrix Dense(new SimpleMatrix(*D));\n  Dense->display();\n  Dense->Factorize();\n  Dense->display();\n  //CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testFactorize: \",  < tol, true);\n\n\n  SP::SimpleMatrix Sparse(new SimpleMatrix(4,4,SPARSE));\n  Sparse->eye();\n  Sparse->display();\n  Sparse->Factorize();\n\n\n  Sparse.reset(new SimpleMatrix(*SP3));\n  Sparse->display();\n  Sparse->displayExpert();\n  Sparse->Factorize();\n  Sparse->display();\n\n \n\n  // Other types than SPARSE are not working since fillCSC is not implemented.\n  // std::cout << \"--> Test: Factorize -- Triangle\" <<std::endl;\n  // SP::SimpleMatrix Triangle(new SimpleMatrix(*T2));\n  // Triangle->display();\n  // Triangle->displayExpert();\n  // Triangle->Factorize();\n  // Triangle->display();\n\n\n\n  /* A last column full of zero caused memory corruption in cs_lusol\n     since ublas does not fill the last entry correctly*/\n  // Sparse.reset(new SimpleMatrix(*SP2));\n  // Sparse->display();\n  // Sparse->displayExpert();\n  // Sparse->PLUFactorizationInPlace();\n  // Sparse->display();\n\n  std::cout << \"--> Test: Factorize (Cholesky).\" <<std::endl;\n\n  Dense.reset(new SimpleMatrix(*D));\n  /* conpute DD^T */\n  SP::SiconosMatrix DenseT(new SimpleMatrix(*Dense));\n  DenseT->trans();\n  SP::SiconosMatrix DDT(new SimpleMatrix(Dense->size(0), Dense->size(1)));\n  prod(*Dense, *DenseT, *DDT);\n  DDT->display();\n  DDT->setIsSymmetric(true);\n  DDT->setIsPositiveDefinite(true);\n  DDT->Factorize();\n  \n  DDT->display();\n  //CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testFactorize: \",  < tol, true);\n\n  std::cout << \"-->  test Factorize ended with success.\" <<std::endl;\n}\nvoid SimpleMatrixTest::testSolve()\n{\n  std::cout << \"\\n--> Test: Solve. Dense. LU.\" <<std::endl;\n\n  // Test dense matrix\n  SP::SiconosMatrix Dense(new SimpleMatrix(*D));\n  SP::SiconosVector b (new SiconosVector(Dense->size(0)));\n  for( int i =0; i <Dense->size(0); i++)\n  {\n    (*b)(i)=1.0;\n  }\n  SP::SiconosVector backup (new SiconosVector(*b));\n  SP::SiconosMatrix D_backup (new SimpleMatrix(*Dense));\n  Dense->display();\n  Dense->Solve(*b);\n  Dense->display();\n  b->display();\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testSolve: \", (prod(*D_backup,*b) - *backup).norm2()  < tol, true);\n\n  // // Test dense matrix and sparse rhs\n  // Dense.reset(new SimpleMatrix(*D));\n  // SP::SiconosVector b_sparse (new SiconosVector(Dense->size(0), SPARSE));\n  // for( int i =0; i <Dense->size(0); i++)\n  // {\n  //   (*b_sparse)(i)=1.0;\n  // }\n  // backup.reset(new SiconosVector(*b_sparse));\n  // Dense->Solve(*b_sparse);\n  // b_sparse->display();\n\n  // CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testSolve: \", (prod(*D_backup,*b_sparse) - *backup).norm2()  < tol, true);\n\n\n  std::cout << \"\\n\\n--> Test: Solve. Dense. Cholesky.\" <<std::endl;\n  Dense.reset(new SimpleMatrix(*D));\n  b.reset(new SiconosVector(Dense->size(0)));\n  for( int i =0; i <Dense->size(0); i++)\n  {\n    (*b)(i)=1.0;\n  }\n  SP::SiconosMatrix DenseT(new SimpleMatrix(*Dense));\n  DenseT->trans();\n  SP::SiconosMatrix DDT(new SimpleMatrix(Dense->size(0), Dense->size(1)));\n  prod(*Dense, *DenseT, *DDT);\n  SP::SiconosMatrix DDT_backup (new SimpleMatrix(*DDT));\n  DDT->setIsSymmetric(true);\n  DDT->setIsPositiveDefinite(true);\n  DDT->Solve(*b);\n  b->display();\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testSolve: \", (prod(*DDT_backup,*b) - *backup).norm2()  < tol, true);\n\n\n  std::cout << \"\\n\\n--> Test: Solve. Sparse. LU.\" <<std::endl;\n\n  // Test sparse matrix identity\n  SP::SimpleMatrix Sparse(new SimpleMatrix(4,4,SPARSE));\n  SP::SimpleMatrix Sparse_backup(new SimpleMatrix(4,4,SPARSE));\n  b.reset(new SiconosVector(Sparse->size(0)));\n  for( int i =0; i <Sparse->size(0); i++)\n  {\n    (*b)(i)=1.0;\n  }\n  backup.reset (new SiconosVector(*b));\n  Sparse_backup->eye();\n  Sparse->eye();\n  Sparse->Solve(*b);\n  b->display();\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testSolve: \", (prod(*Sparse_backup,*b) - *backup).norm2()  < tol, true);\n\n  // test sparse matrix 3x3\n  Sparse.reset(new SimpleMatrix(*SP3));\n  b.reset(new SiconosVector(Sparse->size(0)));\n  for( int i =0; i <Sparse->size(0); i++)\n  {\n    (*b)(i)=1.0;\n  }\n  backup.reset (new SiconosVector(*b));\n  Sparse->Solve(*b);\n  b->display();\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testSolve: \", (prod(*Sparse,*b) - *backup).norm2()  < tol, true);\n\n  // Solve again with another r.h.s.\n  b.reset(new SiconosVector(Sparse->size(0)));\n  for( int i =0; i <Sparse->size(0); i++)\n  {\n    (*b)(i)=2.0;\n  }\n  backup.reset (new SiconosVector(*b));\n  Sparse->Solve(*b);\n  b->display();\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testSolve: \", (prod(*Sparse,*b) - *backup).norm2()  < tol, true);\n\n\n  // test sparse matrix 4x4 SP4\n  Sparse.reset(new SimpleMatrix(*SP4));\n  b.reset(new SiconosVector(Sparse->size(0)));\n  for( int i =0; i <Sparse->size(0); i++)\n  {\n    (*b)(i)=1.0;\n  }\n  backup.reset (new SiconosVector(*b));\n  Sparse->Solve(*b);\n  b->display();\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testSolve: \", (prod(*Sparse,*b) - *backup).norm2()  < tol, true);\n\n\n  std::cout << \"\\n\\n--> Test: Solve. Sparse. LU.  Sparse rhs\" <<std::endl;\n\n  \n  // test sparse matrix 3x3 sparse RhS. trivial solution (Id)\n  Sparse.reset(new SimpleMatrix(*SP3));\n  SP::SimpleMatrix Sparse_rhs (new SimpleMatrix(*SP3));\n  Sparse->Solve(*Sparse_rhs);\n  // std::cout << \"Sparse_rhs :\" << std::endl;\n  // Sparse_rhs->display();\n  // std::cout << \"Sparse :\" << std::endl;\n  // Sparse->display();\n  // std::cout << \"A A^{-1}\" << std::endl;\n  // (prod(*Sparse,*Sparse_rhs)).display();\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testSolve: \", (prod(*Sparse,*Sparse_rhs) - *Sparse ).normInf()  < tol, true);\n\n  // test sparse matrix 3x3 sparse RhS. inverse\n  Sparse.reset(new SimpleMatrix(*SP3));\n  Sparse_rhs.reset(new SimpleMatrix(3,3));\n  Sparse_rhs->eye();\n  Sparse->Solve(*Sparse_rhs);\n  SP::SiconosMatrix Id (new SimpleMatrix(3,3));\n  Id->eye();\n\n  // Sparse_rhs->display();\n  // std::cout << \"A A^{-1}\" << std::endl;\n\n  // (prod(*Sparse,*Sparse_rhs)).display();\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testSolve: \", (prod(*Sparse,*Sparse_rhs) - *Id ).normInf()  < tol, true);\n\n\n  \n  std::cout << \"\\n\\n--> Test: Solve. Sparse. Cholesky.\" <<std::endl;\n\n  // Test sparse matrix identity\n  Sparse.reset(new SimpleMatrix(4,4,SPARSE));\n  Sparse_backup.reset(new SimpleMatrix(4,4,SPARSE));\n  b.reset(new SiconosVector(Sparse->size(0)));\n  for( int i =0; i <Sparse->size(0); i++)\n  {\n    (*b)(i)=1.0;\n  }\n  backup.reset (new SiconosVector(*b));\n  Sparse_backup->eye();\n  Sparse->eye();\n  Sparse->setIsSymmetric(true);\n  Sparse->setIsPositiveDefinite(true);\n  Sparse->Solve(*b);\n  b->display();\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testSolve: \", (prod(*Sparse_backup,*b) - *backup).norm2()  < tol, true);\n\n  // test sparse matrix 3x3\n  Sparse.reset(new SimpleMatrix(*SP3));\n  b.reset(new SiconosVector(Sparse->size(0)));\n  for( int i =0; i <Sparse->size(0); i++)\n  {\n    (*b)(i)=1.0;\n  }\n  backup.reset (new SiconosVector(*b));\n  SP::SimpleMatrix SparseT (new SimpleMatrix(*SP3));\n  SparseT->trans();\n  SP::SimpleMatrix SST (new SimpleMatrix(Sparse->size(0), Sparse->size(1), SPARSE));\n  prod(*Sparse, *SparseT, *SST);\n  SST->setIsSymmetric(true);\n  SST->setIsPositiveDefinite(true);\n  SST->Solve(*b);\n  b->display();\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testSolve: \", (prod(*SST,*b) - *backup).norm2()  < tol, true);\n\n  // Solve again with another r.h.s.\n  b.reset(new SiconosVector(Sparse->size(0)));\n  for( int i =0; i <Sparse->size(0); i++)\n  {\n    (*b)(i)=2.0;\n  }\n  backup.reset (new SiconosVector(*b));\n  SST->Solve(*b);\n  b->display();\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testSolve: \", (prod(*SST,*b) - *backup).norm2()  < tol, true);\n\n  // test sparse matrix 4x4 SP4\n  Sparse.reset(new SimpleMatrix(*SP4));\n  b.reset(new SiconosVector(Sparse->size(0)));\n  for( int i =0; i <Sparse->size(0); i++)\n  {\n    (*b)(i)=1.0;\n  }\n  backup.reset (new SiconosVector(*b));\n  SparseT.reset(new SimpleMatrix(*SP4));\n  SparseT->trans();\n  SST.reset (new SimpleMatrix(Sparse->size(0), Sparse->size(1), SPARSE));\n  prod(*Sparse, *SparseT, *SST);\n  SST->setIsSymmetric(true);\n  SST->setIsPositiveDefinite(true);\n  SST->Solve(*b);\n  b->display();\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testSolve: \", (prod(*SST,*b) - *backup).norm2()  < tol, true);\n\n\n  std::cout << \"\\n\\n--> Test: Solve. Sparse. Cholesky.  Sparse rhs\" <<std::endl;\n  \n  // test sparse matrix 3x3 sparse RhS. trivial solution (Id)\n  Sparse.reset(new SimpleMatrix(*SP3));\n  SparseT.reset(new SimpleMatrix(*SP3));\n  SparseT->trans();\n  SST.reset (new SimpleMatrix(Sparse->size(0), Sparse->size(1), SPARSE));\n  prod(*Sparse, *SparseT, *SST);\n  Sparse_rhs.reset (new SimpleMatrix(*SST));\n  // std::cout << \"SST\" << std::endl;\n  // SST->display();\n  SST->setIsSymmetric(true);\n  SST->setIsPositiveDefinite(true);\n  SST->Solve(*Sparse_rhs);\n  // Sparse_rhs->display();\n  // std::cout << \"A A^{-1}\" << std::endl;\n  // (prod(*SST,*Sparse_rhs)).display();\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testSolve: \", (prod(*SST,*Sparse_rhs) - *SST ).normInf()  < tol, true);\n\n  // test sparse matrix 3x3 sparse RhS. inverse\n  SST.reset (new SimpleMatrix(Sparse->size(0), Sparse->size(1), SPARSE));\n  prod(*Sparse, *SparseT, *SST);\n  Sparse_rhs.reset(new SimpleMatrix(3,3, SPARSE));\n  Sparse_rhs->eye();\n  // std::cout << \"SST\" << std::endl;\n  // SST->display();\n  SST->setIsSymmetric(true);\n  SST->setIsPositiveDefinite(true);\n  SST->Solve(*Sparse_rhs);\n  // Sparse_rhs->display();\n\n  // Sparse_rhs->display();\n  // std::cout << \"A A^{-1}\" << std::endl;\n\n  // (prod(*SST,*Sparse_rhs)).display();\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testSolve: \", (prod(*SST,*Sparse_rhs) - *Id ).normInf()  < tol, true);\n\n\n\n  std::cout << \"-->  test Solve ended with success.\" <<std::endl;\n}\n\n\n\nvoid SimpleMatrixTest::End()\n{\n  std::cout << \"======================================\" <<std::endl;\n  std::cout << \" ===== End of SimpleMatrix Tests ===== \" <<std::endl;\n  std::cout << \"======================================\" <<std::endl;\n}\n", "meta": {"hexsha": "74c024c7d4d20515ed1e778504d4d3317463ee4a", "size": 145779, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kernel/src/utils/SiconosAlgebra/test/SimpleMatrixTest.cpp", "max_stars_repo_name": "fperignon/sandbox", "max_stars_repo_head_hexsha": "649f09d6db7bbd84c2418de74eb9453c0131f070", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "kernel/src/utils/SiconosAlgebra/test/SimpleMatrixTest.cpp", "max_issues_repo_name": "fperignon/sandbox", "max_issues_repo_head_hexsha": "649f09d6db7bbd84c2418de74eb9453c0131f070", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kernel/src/utils/SiconosAlgebra/test/SimpleMatrixTest.cpp", "max_forks_repo_name": "fperignon/sandbox", "max_forks_repo_head_hexsha": "649f09d6db7bbd84c2418de74eb9453c0131f070", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.0226917058, "max_line_length": 163, "alphanum_fraction": 0.5743900013, "num_tokens": 51322, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185944046238981, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.4655041845179838}}
{"text": "/**\n * @file parallel_sgd_test.cpp\n * @author Shikhar Bhardwaj\n *\n * Test file for Parallel SGD.\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#include <mlpack/core.hpp>\n#include <mlpack/core/optimizers/parallel_sgd/decay_policies/constant_step.hpp>\n#include <mlpack/core/optimizers/parallel_sgd/decay_policies/exponential_backoff.hpp>\n#include <mlpack/core/optimizers/parallel_sgd/sparse_test_function.hpp>\n#include <mlpack/core/optimizers/lbfgs/test_functions.hpp>\n// We need some thorough testing\n#define private public\n#include <mlpack/core/optimizers/parallel_sgd/parallel_sgd.hpp>\n#undef private\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n\nusing namespace std;\nusing namespace arma;\nusing namespace mlpack;\nusing namespace mlpack::optimization;\nusing namespace mlpack::optimization::test;\n\nBOOST_AUTO_TEST_SUITE(ParallelSGDTest);\n\n/**\n * Test the correctness of the Parallel SGD implementation using a specified\n * sparse test function, with guaranteed disjoint updates between different\n * threads.\n */\nBOOST_AUTO_TEST_CASE(SimpleParallelSGDTest)\n{\n  SparseTestFunction f;\n\n  ConstantStep decayPolicy(0.4);\n\n  // The batch size for this test should be chosen according to the threads\n  // available on the system. If the update does not touch each datapoint, the\n  // test will fail.\n\n  size_t threadsAvailable = omp_get_max_threads();\n\n  for (size_t i = threadsAvailable; i > 0; --i)\n  {\n    omp_set_num_threads(i);\n\n    size_t batchSize = std::ceil((float) f.NumFunctions() / i);\n\n    ParallelSGD<ConstantStep> s(10000, batchSize, 1e-5, true, decayPolicy);\n\n    arma::mat coordinates = f.GetInitialPoint();\n    double result = s.Optimize(f, coordinates);\n\n    // The final value of the objective function should be close to the optimal\n    // value, that is the sum of values at the vertices of the parabolas.\n    BOOST_REQUIRE_CLOSE(result, 123.75, 0.01);\n\n    // The co-ordinates should be the vertices of the parabolas.\n    BOOST_REQUIRE_CLOSE(coordinates[0], 2, 0.02);\n    BOOST_REQUIRE_CLOSE(coordinates[1], 1, 0.02);\n    BOOST_REQUIRE_CLOSE(coordinates[2], 1.5, 0.02);\n    BOOST_REQUIRE_CLOSE(coordinates[3], 4, 0.02);\n  }\n}\n\n/**\n * When run with a single thread, parallel SGD should be identical to normal\n * SGD.\n */\nBOOST_AUTO_TEST_CASE(GeneralizedRosenbrockTest)\n{\n  // Loop over several variants.\n  for (size_t i = 10; i < 50; i += 5)\n  {\n    // Create the generalized Rosenbrock function.\n    GeneralizedRosenbrockFunction f(i);\n\n    ConstantStep decayPolicy(0.001);\n\n    ParallelSGD<ConstantStep> s(0, f.NumFunctions(), 1e-12, true, decayPolicy);\n\n    arma::mat coordinates = f.GetInitialPoint();\n\n    omp_set_num_threads(1);\n    double result = s.Optimize(f, coordinates);\n\n    BOOST_REQUIRE_SMALL(result, 1e-8);\n    for (size_t j = 0; j < i; ++j)\n      BOOST_REQUIRE_CLOSE(coordinates[j], (double) 1.0, 0.01);\n  }\n}\n\n/**\n * Test the correctness of the Exponential backoff stepsize decay policy.\n */\nBOOST_AUTO_TEST_CASE(ExponentialBackoffDecayTest)\n{\n  ExponentialBackoff decayPolicy(100, 100, 0.9);\n\n  // At the first iteration, stepsize should be unchanged\n  BOOST_REQUIRE_EQUAL(decayPolicy.StepSize(1), 100);\n  // At the 99th iteration, stepsize should be unchanged\n  BOOST_REQUIRE_EQUAL(decayPolicy.StepSize(99), 100);\n  // At the 100th iteration, stepsize should be changed\n  BOOST_REQUIRE_EQUAL(decayPolicy.StepSize(100), 90);\n  // At the 210th iteration, stepsize should be unchanged\n  BOOST_REQUIRE_EQUAL(decayPolicy.StepSize(210), 90);\n  // At the 211th iteration, stepsize should be changed\n  BOOST_REQUIRE_EQUAL(decayPolicy.StepSize(211), 81);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "17746ad78582a94ecbdbad2a89863911b6c92a84", "size": 3878, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/parallel_sgd_test.cpp", "max_stars_repo_name": "17minutes/mlpack", "max_stars_repo_head_hexsha": "8f4af1ec454a662dd7c990cf2146bfeb1bd0cb3a", "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": "2021-09-22T18:12:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-17T10:39:58.000Z", "max_issues_repo_path": "src/mlpack/tests/parallel_sgd_test.cpp", "max_issues_repo_name": "17minutes/mlpack", "max_issues_repo_head_hexsha": "8f4af1ec454a662dd7c990cf2146bfeb1bd0cb3a", "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/tests/parallel_sgd_test.cpp", "max_forks_repo_name": "17minutes/mlpack", "max_forks_repo_head_hexsha": "8f4af1ec454a662dd7c990cf2146bfeb1bd0cb3a", "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": 32.3166666667, "max_line_length": 85, "alphanum_fraction": 0.7421351212, "num_tokens": 1024, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185944046238981, "lm_q2_score": 0.6477982315512488, "lm_q1q2_score": 0.46550418451798375}}
{"text": "#include <boost/graph/undirected_graph.hpp>\n#include <iostream>\nusing namespace boost;\nusing namespace std;\nint main( )\n{\n    undirected_graph<>  g;\n    //A vertex descriptor corresponds to a unique vertex in an abstract graph instance.\n    undirected_graph<>::vertex_descriptor u = g.add_vertex();\n    undirected_graph<>::vertex_descriptor v = g.add_vertex();\n    undirected_graph<>::vertex_descriptor w = g.add_vertex();\n    undirected_graph<>::vertex_descriptor x = g.add_vertex();\n\n    //Adds edge (u,v) to the graph and returns the edge descriptor for the new edge. \n    add_edge(u, v, g);\n    add_edge(u, w, g);\n    add_edge(v, x, g);\n\n    cout << \"Degree of u: \" << degree(u, g)<<\"\\n\";\n    \n    return 0;\n}\n", "meta": {"hexsha": "051e751592de27078c6a8c4442ac5ff17038d885", "size": 714, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3Creating_an_undirected_graph_using_undirected_graph_hpp.cpp", "max_stars_repo_name": "mohsenuss91/BGL_workshop", "max_stars_repo_head_hexsha": "03d2bea291d4c6d67e7ddcd562694a0b7ecc5130", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-02-12T18:40:32.000Z", "max_stars_repo_stars_event_max_datetime": "2015-02-12T18:40:32.000Z", "max_issues_repo_path": "3Creating_an_undirected_graph_using_undirected_graph_hpp.cpp", "max_issues_repo_name": "mohsenuss91/IBM_BGL", "max_issues_repo_head_hexsha": "03d2bea291d4c6d67e7ddcd562694a0b7ecc5130", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "3Creating_an_undirected_graph_using_undirected_graph_hpp.cpp", "max_forks_repo_name": "mohsenuss91/IBM_BGL", "max_forks_repo_head_hexsha": "03d2bea291d4c6d67e7ddcd562694a0b7ecc5130", "max_forks_repo_licenses": ["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.0434782609, "max_line_length": 87, "alphanum_fraction": 0.6736694678, "num_tokens": 181, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185944046238981, "lm_q2_score": 0.6477982247516797, "lm_q1q2_score": 0.4655041796318514}}
{"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#include <nt2/trigonometric/include/functions/rem_2pi.hpp>\n#include <boost/simd/sdk/simd/native.hpp>\n#include <nt2/sdk/functor/meta/call.hpp>\n#include <nt2/sdk/meta/scalar_of.hpp>\n#include <nt2/include/constants/pi.hpp>\n#include <nt2/include/constants/pio_2.hpp>\n#include <nt2/include/constants/twopi.hpp>\n#include <nt2/include/constants/zero.hpp>\n#include <nt2/include/constants/ten.hpp>\n#include <nt2/include/constants/eps.hpp>\n\n#include <nt2/sdk/unit/module.hpp>\n#include <nt2/sdk/unit/tests/ulp.hpp>\n\nNT2_TEST_CASE_TPL ( rem_2pi_real__1_0,  NT2_SIMD_REAL_TYPES)\n{\n  using nt2::rem_2pi;\n  using nt2::tag::rem_2pi_;\n\n  {\n    T res = rem_2pi(nt2::Zero<T>());\n    NT2_TEST_ULP_EQUAL( res, nt2::Zero<T>(), 1.5);\n    res = rem_2pi(nt2::Pi<T>()-nt2::Ten<T>()*nt2::Eps<T>());\n    NT2_TEST_ULP_EQUAL( res, nt2::Pi<T>()-nt2::Ten<T>()*nt2::Eps<T>(), 1.5);\n    res = rem_2pi(nt2::Pi<T>()+nt2::Ten<T>()*nt2::Eps<T>());\n    NT2_TEST_ULP_EQUAL( res, nt2::Ten<T>()*nt2::Eps<T>()-nt2::Pi<T>(), 1.5);\n    res = rem_2pi(nt2::Twopi<T>());\n    NT2_TEST_ULP_EQUAL( res, nt2::Zero<T>(), 1.5);\n    res = rem_2pi(nt2::Pio_2<T>());\n    NT2_TEST_ULP_EQUAL( res, nt2::Pio_2<T>(), 1.5);\n  }\n} // end of test for floating_\n\nNT2_TEST_CASE_TPL ( rem_2pi_targeted,  NT2_SIMD_REAL_TYPES)\n{\n\n  using nt2::rem_2pi;\n  using nt2::tag::rem_2pi_;\n\n  T x = nt2::Twopi<T>(), xr;\n  xr = rem_2pi(x, nt2::meta::as_<nt2::big_>());\n  NT2_TEST_ULP_EQUAL( xr, nt2::Zero<T>(), 1.5);\n\n\n  xr = rem_2pi(x, nt2::meta::as_<nt2::medium_>());\n  NT2_TEST_ULP_EQUAL( xr, nt2::Zero<T>(), 1.5);\n\n\n  xr = rem_2pi(x, nt2::meta::as_<nt2::small_>());\n  NT2_TEST_ULP_EQUAL( xr, nt2::Zero<T>(), 1.5);\n\n\n  xr = rem_2pi(x, nt2::meta::as_<nt2::very_small_>());\n  NT2_TEST_ULP_EQUAL( xr, nt2::Zero<T>(), 1.5);\n\n}\n", "meta": {"hexsha": "f63403da63c374732ee061d2c90c510d80de19f7", "size": 2254, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/core/trigonometric/unit/scalar/rem_2pi.cpp", "max_stars_repo_name": "pbrunet/nt2", "max_stars_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/core/trigonometric/unit/scalar/rem_2pi.cpp", "max_issues_repo_name": "pbrunet/nt2", "max_issues_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/core/trigonometric/unit/scalar/rem_2pi.cpp", "max_forks_repo_name": "pbrunet/nt2", "max_forks_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 34.6769230769, "max_line_length": 80, "alphanum_fraction": 0.5953859805, "num_tokens": 763, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708562, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.46550416693777985}}
{"text": "//\n// \tCopyright (c) 2018-2020, Cem Bassoy, cem.bassoy@gmail.com\n// \tCopyright (c) 2019-2020, Amit Singh, amitsingh19975@gmail.com\n//\n//  Distributed under the Boost Software License, Version 1.0. (See\n//  accompanying file LICENSE_1_0.txt or copy at\n//  http://www.boost.org/LICENSE_1_0.txt)\n//\n//  The authors gratefully acknowledge the support of\n//  Google and Fraunhofer IOSB, Ettlingen, Germany\n//\n\n\n\n#include <boost/numeric/ublas/tensor.hpp>\n#include \"utility.hpp\"\n#include <boost/test/unit_test.hpp>\n\n#include <functional>\n\nBOOST_AUTO_TEST_SUITE(test_tensor_static_expression)\n\nusing test_types = zip<int,float,std::complex<float>>::with_t<boost::numeric::ublas::layout::first_order, boost::numeric::ublas::layout::last_order>;\n\n\nstruct fixture\n{\n  template<std::size_t N1,size_t... N>\n  using extents_type = boost::numeric::ublas::extents<N1,N...>;\n\n  std::tuple<\n    extents_type<1,1>, \t\t// 1\n    extents_type<2,3>, \t\t// 2\n    extents_type<4,1,3>, \t// 3\n    extents_type<4,2,3>, \t// 4\n    extents_type<4,2,3,5>  \t// 5\n    > extents;\n};\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_static_expression_retrieve_extents, value,  test_types, fixture)\n{\n  namespace ublas  = boost::numeric::ublas;\n    using value_type  = typename value::first_type;\n    using layout_type = typename value::second_type;\n\n    auto uplus1 = [](auto const& a){return a + value_type(1);};\n    auto uplus2 = [](auto const& a){return value_type(2) + a;};\n    auto bplus  = std::plus <value_type>{};\n    auto bminus = std::minus<value_type>{};\n\n    for_each_in_tuple(extents, [&](auto const& /*unused*/, auto& e){\n        using extents_type = std::decay_t<decltype(e)>;\n        using tensor_type = ublas::tensor_static<value_type,extents_type,layout_type>;\n        \n\n        auto t = tensor_type();\n        auto v = value_type{};\n        for(auto& tt: t){ tt = v; v+=value_type{1}; }\n\n\n        BOOST_CHECK( ublas::detail::retrieve_extents( t ) == e );\n\n\n        // uexpr1 = t+1\n        // uexpr2 = 2+t\n        auto uexpr1 = ublas::detail::make_unary_tensor_expression<tensor_type>( t, uplus1 );\n        auto uexpr2 = ublas::detail::make_unary_tensor_expression<tensor_type>( t, uplus2 );\n\n        BOOST_CHECK( ublas::detail::retrieve_extents( uexpr1 ) == e );\n        BOOST_CHECK( ublas::detail::retrieve_extents( uexpr2 ) == e );\n\n        // bexpr_uexpr = (t+1) + (2+t)\n        auto bexpr_uexpr = ublas::detail::make_binary_tensor_expression<tensor_type>( uexpr1, uexpr2, bplus );\n\n        BOOST_CHECK( ublas::detail::retrieve_extents( bexpr_uexpr ) == e );\n\n\n        // bexpr_bexpr_uexpr = ((t+1) + (2+t)) - t\n        auto bexpr_bexpr_uexpr = ublas::detail::make_binary_tensor_expression<tensor_type>( bexpr_uexpr, t, bminus );\n\n        BOOST_CHECK( ublas::detail::retrieve_extents( bexpr_bexpr_uexpr ) == e );\n\n    });\n\n    for_each_in_tuple(extents, [&](auto I, auto& e1){\n        \n        if ( I >= std::tuple_size_v<decltype(extents)> - 1){\n            return;\n        }\n        \n        using extents_type1 = std::decay_t<decltype(e1)>;\n        using tensor_type1 = ublas::tensor_static<value_type, extents_type1, layout_type>;\n\n        for_each_in_tuple(extents, [&](auto J, auto& e2){\n\n            if( J != I + 1 ){\n                return;\n            }\n            \n            using extents_type2 = std::decay_t<decltype(e2)>;\n            using tensor_type2 = ublas::tensor_static<value_type, extents_type2, layout_type>;\n\n            auto v = value_type{};\n\n            tensor_type1 t1;\n            for(auto& tt: t1){ tt = v; v+=value_type{1}; }\n\n            tensor_type2 t2;\n            for(auto& tt: t2){ tt = v; v+=value_type{2}; }\n\n            BOOST_CHECK( ublas::detail::retrieve_extents( t1 ) != ublas::detail::retrieve_extents( t2 ) );\n\n            // uexpr1 = t1+1\n            // uexpr2 = 2+t2\n            auto uexpr1 = ublas::detail::make_unary_tensor_expression<tensor_type1>( t1, uplus1 );\n            auto uexpr2 = ublas::detail::make_unary_tensor_expression<tensor_type2>( t2, uplus2 );\n\n            BOOST_CHECK( ublas::detail::retrieve_extents( t1 )     == ublas::detail::retrieve_extents( uexpr1 ) );\n            BOOST_CHECK( ublas::detail::retrieve_extents( t2 )     == ublas::detail::retrieve_extents( uexpr2 ) );\n            BOOST_CHECK( ublas::detail::retrieve_extents( uexpr1 ) != ublas::detail::retrieve_extents( uexpr2 ) );\n\n        });\n    });\n}\n\n\n\n\n\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_static_expression_all_extents_equal, value,  test_types, fixture)\n{\n  namespace ublas  = boost::numeric::ublas;\n    using value_type  = typename value::first_type;\n    using layout_type = typename value::second_type;\n\n    auto uplus1 = [](auto const& a){return a + value_type(1);};\n    auto uplus2 = [](auto const& a){return value_type(2) + a;};\n    auto bplus  = std::plus <value_type>{};\n    auto bminus = std::minus<value_type>{};\n\n    for_each_in_tuple(extents, [&](auto const& /*unused*/, auto& e){\n        using extents_type = std::decay_t<decltype(e)>;\n        using tensor_type = ublas::tensor_static<value_type,extents_type,layout_type>;\n        \n\n        auto t = tensor_type{};\n        auto v = value_type{};\n        for(auto& tt: t){ tt = v; v+=value_type{1}; }\n\n\n        BOOST_CHECK( ublas::detail::all_extents_equal( t , e ) );\n\n\n        // uexpr1 = t+1\n        // uexpr2 = 2+t\n        auto uexpr1 = ublas::detail::make_unary_tensor_expression<tensor_type>( t, uplus1 );\n        auto uexpr2 = ublas::detail::make_unary_tensor_expression<tensor_type>( t, uplus2 );\n\n        BOOST_CHECK( ublas::detail::all_extents_equal( uexpr1, e ) );\n        BOOST_CHECK( ublas::detail::all_extents_equal( uexpr2, e ) );\n\n        // bexpr_uexpr = (t+1) + (2+t)\n        auto bexpr_uexpr = ublas::detail::make_binary_tensor_expression<tensor_type>( uexpr1, uexpr2, bplus );\n\n        BOOST_CHECK( ublas::detail::all_extents_equal( bexpr_uexpr, e ) );\n\n\n        // bexpr_bexpr_uexpr = ((t+1) + (2+t)) - t\n        auto bexpr_bexpr_uexpr = ublas::detail::make_binary_tensor_expression<tensor_type>( bexpr_uexpr, t, bminus );\n\n        BOOST_CHECK( ublas::detail::all_extents_equal( bexpr_bexpr_uexpr , e ) );\n\n    });\n\n\n    for_each_in_tuple(extents, [&](auto I, auto& e1){\n\n        if ( I >= std::tuple_size_v<decltype(extents)> - 1){\n            return;\n        }\n        \n        using extents_type1 = std::decay_t<decltype(e1)>;\n        using tensor_type1 = ublas::tensor_static<value_type, extents_type1, layout_type>;\n\n        for_each_in_tuple(extents, [&](auto J, auto& e2){\n\n            if( J != I + 1 ){\n                return;\n            }\n\n            using extents_type2 = std::decay_t<decltype(e2)>;\n            using tensor_type2 = ublas::tensor_static<value_type, extents_type2, layout_type>;\n\n            auto v = value_type{};\n\n            tensor_type1 t1;\n            for(auto& tt: t1){ tt = v; v+=value_type{1}; }\n\n            tensor_type2 t2;\n            for(auto& tt: t2){ tt = v; v+=value_type{2}; }\n\n            BOOST_CHECK( ublas::detail::all_extents_equal( t1, ublas::detail::retrieve_extents(t1) ) );\n            BOOST_CHECK( ublas::detail::all_extents_equal( t2, ublas::detail::retrieve_extents(t2) ) );\n\n            // uexpr1 = t1+1\n            // uexpr2 = 2+t2\n            auto uexpr1 = ublas::detail::make_unary_tensor_expression<tensor_type1>( t1, uplus1 );\n            auto uexpr2 = ublas::detail::make_unary_tensor_expression<tensor_type2>( t2, uplus2 );\n\n            BOOST_CHECK( ublas::detail::all_extents_equal( uexpr1, ublas::detail::retrieve_extents(uexpr1) ) );\n            BOOST_CHECK( ublas::detail::all_extents_equal( uexpr2, ublas::detail::retrieve_extents(uexpr2) ) );\n\n        });\n    });\n\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "7412eef01da1feb71e556d318aab8c3d5fe1c37f", "size": 7675, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/tensor/test_static_expression_evaluation.cpp", "max_stars_repo_name": "samd2/ublas", "max_stars_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 96.0, "max_stars_repo_stars_event_min_datetime": "2015-01-23T10:15:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T18:31:02.000Z", "max_issues_repo_path": "test/tensor/test_static_expression_evaluation.cpp", "max_issues_repo_name": "samd2/ublas", "max_issues_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 105.0, "max_issues_repo_issues_event_min_datetime": "2015-01-14T09:01:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-05T06:10:39.000Z", "max_forks_repo_path": "test/tensor/test_static_expression_evaluation.cpp", "max_forks_repo_name": "samd2/ublas", "max_forks_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 157.0, "max_forks_repo_forks_event_min_datetime": "2015-01-26T13:35:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T11:12:27.000Z", "avg_line_length": 34.7285067873, "max_line_length": 149, "alphanum_fraction": 0.6248859935, "num_tokens": 2175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943805178139, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.4655041591298405}}
{"text": "#include <stan/math/prim/scal.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <gtest/gtest.h>\n#include <limits>\n\nTEST(MathFunctions, round) {\n  using stan::math::round;\n  EXPECT_FLOAT_EQ(-27, round(-27.3239));\n  EXPECT_FLOAT_EQ(-1, round(-0.5));\n  EXPECT_FLOAT_EQ(0, round(0));\n  EXPECT_FLOAT_EQ(0, round(0.0));\n  EXPECT_FLOAT_EQ(1, round(0.5));\n  EXPECT_FLOAT_EQ(27, round(27.3239));\n}\n\nTEST(MathFunctions, roundNaN) {\n  double nan = std::numeric_limits<double>::quiet_NaN();\n  EXPECT_PRED1(boost::math::isnan<double>, stan::math::round(nan));\n}\n", "meta": {"hexsha": "29892e59ce2b4a1bc22a920916b1fcf0be91d800", "size": 568, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/prim/scal/fun/round_test.cpp", "max_stars_repo_name": "jrmie/math", "max_stars_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "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": "test/unit/math/prim/scal/fun/round_test.cpp", "max_issues_repo_name": "jrmie/math", "max_issues_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "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": "test/unit/math/prim/scal/fun/round_test.cpp", "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": 28.4, "max_line_length": 67, "alphanum_fraction": 0.7112676056, "num_tokens": 168, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.7185943805178138, "lm_q1q2_score": 0.46550415912984044}}
{"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_CONVLAYER_HH\n#define NETKET_CONVLAYER_HH\n\n#include <time.h>\n#include <Eigen/Dense>\n#include <algorithm>\n#include <complex>\n#include <fstream>\n#include <random>\n#include <vector>\n\n#include \"Graph/graph.hpp\"\n#include \"Lookup/lookup.hpp\"\n#include \"Utils/all_utils.hpp\"\n#include \"abstract_layer.hpp\"\n\nnamespace netket {\n/** Convolutional layer with spin 1/2 hidden units.\n Important: In order for this to work correctly, VectorType and MatrixType must\n be column major.\n */\ntemplate <typename Activation, typename T>\nclass Convolutional : public AbstractLayer<T> {\n  using VectorType = typename AbstractLayer<T>::VectorType;\n\n  using MatrixType = typename AbstractLayer<T>::MatrixType;\n  static_assert(!MatrixType::IsRowMajor, \"MatrixType must be column-major\");\n\n  Activation activation_;  // activation function class\n\n  bool usebias_;  // boolean to turn or off bias\n\n  int nv_;            // number of visible units in the full network\n  int in_channels_;   // number of input channels\n  int in_size_;       // input size: should be multiple of no. of sites\n  int out_channels_;  // number of output channels\n  int out_size_;      // output size: should be multiple of no. of sites\n  int npar_;          // number of parameters in layer\n\n  int dist_;         // Distance to include in one convolutional image\n  int kernel_size_;  // Size of convolutional kernel (depends on dist_)\n  std::vector<std::vector<int>>\n      neighbours_;  // list of neighbours for each site\n  std::vector<std::vector<int>>\n      flipped_neighbours_;  // list of reverse neighbours for each site\n  MatrixType kernels_;      // Weight parameters, W(in_size x out_size)\n  VectorType bias_;         // Bias parameters, b(out_size x 1)\n\n  // Note that input of this layer is also the output of\n  // previous layer\n\n  MatrixType lowered_image_;\n  MatrixType lowered_image2_;\n  MatrixType lowered_der_;\n  MatrixType flipped_kernels_;\n\n public:\n  using StateType = typename AbstractLayer<T>::StateType;\n  using LookupType = typename AbstractLayer<T>::LookupType;\n\n  /// Constructor\n  Convolutional(const Graph &graph, const int input_channel,\n                const int output_channel, const int dist = 1,\n                const bool use_bias = true)\n      : activation_(),\n        usebias_(use_bias),\n        nv_(graph.Nsites()),\n        in_channels_(input_channel),\n        out_channels_(output_channel),\n        dist_(dist) {\n    in_size_ = in_channels_ * nv_;\n    out_size_ = out_channels_ * nv_;\n\n    Init(graph);\n  }\n\n  explicit Convolutional(const Graph &graph, const json &pars)\n      : activation_(), nv_(graph.Nsites()) {\n    in_channels_ = FieldVal(pars, \"InputChannels\");\n    in_size_ = in_channels_ * nv_;\n\n    out_channels_ = FieldVal(pars, \"OutputChannels\");\n    out_size_ = out_channels_ * nv_;\n\n    dist_ = FieldVal(pars, \"Distance\");\n\n    usebias_ = FieldOrDefaultVal(pars, \"UseBias\", true);\n\n    Init(graph);\n  }\n\n  void Init(const Graph &graph) {\n    // Construct neighbourhood of all nodes with distance of at most dist_ from\n    // each node i kernel(k) will act on neighbours_[i][k]\n    for (int i = 0; i < nv_; ++i) {\n      std::vector<int> neigh;\n      graph.BreadthFirstSearch(i, dist_, [&neigh](int node, int /*depth*/) {\n        neigh.push_back(node);\n      });\n      neighbours_.push_back(neigh);\n    }\n\n    // Check that all sites have same number of neighbours\n    int check;\n    kernel_size_ = neighbours_[0].size();\n    for (int i = 1; i < nv_; i++) {\n      check = neighbours_[i].size();\n      if (check != kernel_size_) {\n        throw InvalidInputError(\n            \"number of neighbours of each site is not the same for chosen \"\n            \"lattice\");\n      }\n    }\n    // Construct flipped_neighbours_\n    // flipped_neighbours_[i][k] should be acted on by kernel(k)\n    // Let neighbours_[i][k] = l\n    // i.e. look for the direction k' where neighbours_[l][k'] = i\n    // then neighbours_[i][k'] will be acted on by kernel(k)\n    // so flipped_neighbours_[i][k] = neighbours_[i][k']\n    for (int i = 0; i < nv_; ++i) {\n      std::vector<int> flippedneigh;\n      for (int k = 0; k < kernel_size_; ++k) {\n        int l = neighbours_[i][k];\n        for (int kp = 0; kp < kernel_size_; ++kp) {\n          if (neighbours_[l][kp] == i) {\n            flippedneigh.push_back(neighbours_[i][kp]);\n          }\n        }\n      }\n      flipped_neighbours_.push_back(flippedneigh);\n    }\n\n    for (int i = 1; i < nv_; i++) {\n      check = flipped_neighbours_[i].size();\n      if (check != kernel_size_) {\n        throw InvalidInputError(\n            \"number of neighbours of each site is not the same for chosen \"\n            \"lattice\");\n      }\n    }\n\n    kernels_.resize(in_channels_ * kernel_size_, out_channels_);\n    bias_.resize(out_channels_);\n\n    lowered_image_.resize(in_channels_ * kernel_size_, nv_);\n    lowered_image2_.resize(nv_, in_channels_ * kernel_size_);\n    lowered_der_.resize(kernel_size_ * out_channels_, nv_);\n    flipped_kernels_.resize(kernel_size_ * out_channels_, in_channels_);\n\n    npar_ = in_channels_ * kernel_size_ * out_channels_;\n\n    if (usebias_) {\n      npar_ += out_channels_;\n    } else {\n      bias_.setZero();\n    }\n\n    std::string buffer = \"\";\n\n    InfoMessage(buffer) << \"Convolutional Layer: \" << in_size_ << \" --> \"\n                        << out_size_ << std::endl;\n    InfoMessage(buffer) << \"# # InputChannels = \" << in_channels_ << std::endl;\n    InfoMessage(buffer) << \"# # OutputChannels = \" << out_channels_\n                        << std::endl;\n    InfoMessage(buffer) << \"# # Filter Distance = \" << dist_ << std::endl;\n    InfoMessage(buffer) << \"# # Filter Size = \" << kernel_size_ << std::endl;\n    InfoMessage(buffer) << \"# # UseBias = \" << usebias_ << std::endl;\n  }\n\n  void InitRandomPars(int seed, double sigma) override {\n    VectorType par(npar_);\n\n    netket::RandomGaussian(par, seed, sigma);\n\n    SetParameters(par, 0);\n  }\n\n  int Npar() const override { return npar_; }\n\n  int Ninput() const override { return in_size_; }\n\n  int Noutput() const override { return out_size_; }\n\n  void GetParameters(VectorType &pars, int start_idx) const override {\n    int k = start_idx;\n\n    if (usebias_) {\n      for (int i = 0; i < out_channels_; ++i) {\n        pars(k) = bias_(i);\n        ++k;\n      }\n    }\n\n    for (int j = 0; j < out_channels_; ++j) {\n      for (int i = 0; i < in_channels_ * kernel_size_; ++i) {\n        pars(k) = kernels_(i, j);\n        ++k;\n      }\n    }\n  }\n\n  void SetParameters(const VectorType &pars, int start_idx) override {\n    int k = start_idx;\n\n    if (usebias_) {\n      for (int i = 0; i < out_channels_; ++i) {\n        bias_(i) = pars(k);\n        ++k;\n      }\n    }\n\n    for (int j = 0; j < out_channels_; ++j) {\n      for (int i = 0; i < in_channels_ * kernel_size_; ++i) {\n        kernels_(i, j) = pars(k);\n        ++k;\n      }\n    }\n  }\n\n  void InitLookup(const VectorType &v, LookupType &lt,\n                  VectorType &output) override {\n    lt.resize(1);\n    lt[0].resize(out_size_);\n\n    Forward(v, lt, output);\n  }\n\n  void UpdateLookup(const VectorType &input,\n                    const std::vector<int> &input_changes,\n                    const VectorType &new_input, LookupType &theta,\n                    const VectorType & /*output*/,\n                    std::vector<int> &output_changes,\n                    VectorType &new_output) override {\n    // At the moment the light cone structure of the convolution is not\n    // exploited. To do so we would to change the part\n    // else if (num_of_changes >0) {...}\n    const int num_of_changes = input_changes.size();\n    if (num_of_changes == in_size_) {\n      output_changes.resize(out_size_);\n      new_output.resize(out_size_);\n      Forward(new_input, theta, new_output);\n    } else if (num_of_changes > 0) {\n      UpdateTheta(input, input_changes, new_input, theta);\n      output_changes.resize(out_size_);\n      new_output.resize(out_size_);\n      Forward(theta, new_output);\n    } else {\n      output_changes.resize(0);\n      new_output.resize(0);\n    }\n  }\n\n  void UpdateLookup(const Eigen::VectorXd &input,\n                    const std::vector<int> &tochange,\n                    const std::vector<double> &newconf, LookupType &theta,\n                    const VectorType & /*output*/,\n                    std::vector<int> &output_changes,\n                    VectorType &new_output) override {\n    const int num_of_changes = tochange.size();\n    if (num_of_changes > 0) {\n      UpdateTheta(input, tochange, newconf, theta);\n      output_changes.resize(out_size_);\n      new_output.resize(out_size_);\n      Forward(theta, new_output);\n    } else {\n      output_changes.resize(0);\n      new_output.resize(0);\n    }\n  }\n\n  // Feedforward\n  void Forward(const VectorType &prev_layer_output, LookupType &theta,\n               VectorType &output) override {\n    LinearTransformation(prev_layer_output, theta);\n    NonLinearTransformation(theta, output);\n  }\n\n  // Feedforward Using lookup\n  void Forward(const LookupType &theta, VectorType &output) override {\n    // Apply activation function\n    NonLinearTransformation(theta, output);\n  }\n\n  // performs the convolution of the kernel onto the image and writes into z\n  inline void Convolve(const VectorType &image, VectorType &z) {\n    // im2col method\n    for (int i = 0; i < nv_; ++i) {\n      int j = 0;\n      for (auto n : neighbours_[i]) {\n        for (int in = 0; in < in_channels_; ++in) {\n          lowered_image_(in * kernel_size_ + j, i) = image(in * nv_ + n);\n        }\n        j++;\n      }\n    }\n    Eigen::Map<MatrixType> output_image(z.data(), nv_, out_channels_);\n    output_image.noalias() = lowered_image_.transpose() * kernels_;\n  }\n\n  // Performs the linear transformation for the layer.\n  inline void LinearTransformation(const VectorType &input, LookupType &theta) {\n    Convolve(input, theta[0]);\n\n    if (usebias_) {\n      int k = 0;\n      for (int out = 0; out < out_channels_; ++out) {\n        for (int i = 0; i < nv_; ++i) {\n          theta[0](k) += bias_(out);\n          ++k;\n        }\n      }\n    }\n  }\n\n  // Performs the nonlinear transformation for the layer.\n  inline void NonLinearTransformation(const LookupType &theta,\n                                      VectorType &output) {\n    activation_(theta[0], output);\n  }\n\n  inline void UpdateTheta(const VectorType &v,\n                          const std::vector<int> &input_changes,\n                          const VectorType &new_input, LookupType &theta) {\n    const int num_of_changes = input_changes.size();\n    for (int s = 0; s < num_of_changes; ++s) {\n      const int sf = input_changes[s];\n      int kout = 0;\n      for (int out = 0; out < out_channels_; ++out) {\n        for (int k = 0; k < kernel_size_; ++k) {\n          theta[0](flipped_neighbours_[sf][k] + kout) +=\n              kernels_(k, out) * (new_input(s) - v(sf));\n        }\n        kout += nv_;\n      }\n    }\n  }\n\n  inline void UpdateTheta(const VectorType &prev_input,\n                          const std::vector<int> &tochange,\n                          const std::vector<double> &newconf,\n                          LookupType &theta) {\n    const int num_of_changes = tochange.size();\n    for (int s = 0; s < num_of_changes; ++s) {\n      const int sf = tochange[s];\n      int kout = 0;\n      for (int out = 0; out < out_channels_; ++out) {\n        for (int k = 0; k < kernel_size_; ++k) {\n          theta[0](flipped_neighbours_[sf][k] + kout) +=\n              kernels_(k, out) * (newconf[s] - prev_input(sf));\n        }\n        kout += nv_;\n      }\n    }\n  }\n\n  void Backprop(const VectorType &prev_layer_output,\n                const VectorType &this_layer_output,\n                const LookupType &this_layer_theta, const VectorType &dout,\n                VectorType &din, VectorType &der, int start_idx) override {\n    // Compute dL/dz\n    VectorType dLz(out_size_);\n    activation_.ApplyJacobian(this_layer_theta[0], this_layer_output, dout,\n                              dLz);\n\n    int kd = start_idx;\n\n    // Derivative for bias, d(L) / d(b) = d(L) / d(z)\n    if (usebias_) {\n      int k = 0;\n      for (int out = 0; out < out_channels_; ++out) {\n        der(kd) = 0;\n        for (int i = 0; i < nv_; ++i) {\n          der(kd) += dLz(k);\n          ++k;\n        }\n        ++kd;\n      }\n    }\n\n    // Derivative for weights, d(L) / d(W) = [d(L) / d(z)] * in'\n    // Reshape dLdZ\n    Eigen::Map<MatrixType> dLz_reshaped(dLz.data(), nv_, out_channels_);\n\n    // Reshape image\n    for (int in = 0; in < in_channels_; ++in) {\n      for (int k = 0; k < kernel_size_; ++k) {\n        for (int i = 0; i < nv_; ++i) {\n          lowered_image2_(i, k + in * kernel_size_) =\n              prev_layer_output(in * nv_ + neighbours_[i][k]);\n        }\n      }\n    }\n    Eigen::Map<MatrixType> der_w(der.data() + kd, in_channels_ * kernel_size_,\n                                 out_channels_);\n    der_w.noalias() = lowered_image2_.transpose() * dLz_reshaped;\n\n    // Compute d(L) / d_in = W * [d(L) / d(z)]\n    int kout = 0;\n    for (int out = 0; out < out_channels_; ++out) {\n      for (int in = 0; in < in_channels_; ++in) {\n        for (int k = 0; k < kernel_size_; ++k) {\n          flipped_kernels_(k + kout, in) = kernels_(k + in * kernel_size_, out);\n        }\n      }\n      kout += kernel_size_;\n    }\n\n    for (int i = 0; i < nv_; i++) {\n      int j = 0;\n      for (auto n : flipped_neighbours_[i]) {\n        for (int out = 0; out < out_channels_; ++out) {\n          lowered_der_(out * kernel_size_ + j, i) = dLz(out * nv_ + n);\n        }\n        j++;\n      }\n    }\n\n    din.resize(in_size_);\n    Eigen::Map<MatrixType> der_in(din.data(), nv_, in_channels_);\n    der_in.noalias() = lowered_der_.transpose() * flipped_kernels_;\n  }\n\n  void to_json(json &pars) const override {\n    json layerpar;\n    layerpar[\"Name\"] = \"Convolutional\";\n    layerpar[\"UseBias\"] = usebias_;\n    layerpar[\"Inputs\"] = in_size_;\n    layerpar[\"Outputs\"] = out_size_;\n    layerpar[\"InputChannels\"] = in_channels_;\n    layerpar[\"OutputChannels\"] = out_channels_;\n    layerpar[\"Bias\"] = bias_;\n    layerpar[\"Kernels\"] = kernels_;\n\n    pars[\"Machine\"][\"Layers\"].push_back(layerpar);\n  }\n\n  void from_json(const json &pars) override {\n    if (FieldExists(pars, \"Kernels\")) {\n      kernels_ = pars[\"Kernels\"];\n    } else {\n      kernels_.setZero();\n    }\n    if (FieldExists(pars, \"Bias\")) {\n      bias_ = pars[\"Bias\"];\n    } else {\n      bias_.setZero();\n    }\n  }\n};\n}  // namespace netket\n\n#endif\n", "meta": {"hexsha": "96d2f7a0e1cc3c6ae074f7e4a39b495ffda95485", "size": 15067, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "NetKet/Machine/conv_layer.hpp", "max_stars_repo_name": "stavros11/netket", "max_stars_repo_head_hexsha": "1cec25a4884bdbd2fddb5d24daae627cd89316d8", "max_stars_repo_licenses": ["Apache-2.0"], "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/conv_layer.hpp", "max_issues_repo_name": "stavros11/netket", "max_issues_repo_head_hexsha": "1cec25a4884bdbd2fddb5d24daae627cd89316d8", "max_issues_repo_licenses": ["Apache-2.0"], "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/conv_layer.hpp", "max_forks_repo_name": "stavros11/netket", "max_forks_repo_head_hexsha": "1cec25a4884bdbd2fddb5d24daae627cd89316d8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-10-26T21:05:38.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-26T21:05:38.000Z", "avg_line_length": 32.2633832976, "max_line_length": 80, "alphanum_fraction": 0.6004513174, "num_tokens": 3928, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.800692021119887, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4654447465312321}}
{"text": "#include <mass.h>\n\n#include <algorithm> // needed for std::min and std::max\n#include <cmath>     // needed for std::fabs\n\n#define BOOST_AUTO_TEST_MAIN\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n\ntemplate<typename T>\nclass BoxMesh \n: public mass::FaceCallbackInterface<T>\n{\npublic:\n  \n  T m_x1[4];  T m_y1[4];  T m_z1[4];\n  T m_x2[4];  T m_y2[4];  T m_z2[4];\n  T m_x3[4];  T m_y3[4];  T m_z3[4];\n  T m_x4[4];  T m_y4[4];  T m_z4[4];\n  T m_x5[4];  T m_y5[4];  T m_z5[4];\n  T m_x6[4];  T m_y6[4];  T m_z6[4];\n  \n  T * m_x[6];  T * m_y[6];  T * m_z[6];\n  \npublic:\n  \n  size_t get_number_of_vertices(size_t const & ) const\n  {\n    return 4u;\n  }\n  \n  void get_x_coords(size_t const & face_no, double * coords) const\n  {\n    coords[0] = m_x[face_no][0];\n    coords[1] = m_x[face_no][1];\n    coords[2] = m_x[face_no][2];\n    coords[3] = m_x[face_no][3];\n  }\n  \n  void get_y_coords(size_t const & face_no, double * coords) const\n  {\n    coords[0] = m_y[face_no][0];\n    coords[1] = m_y[face_no][1];\n    coords[2] = m_y[face_no][2];\n    coords[3] = m_y[face_no][3];\n  }\n  \n  void get_z_coords(size_t const & face_no, double * coords) const\n  {\n    coords[0] = m_z[face_no][0];\n    coords[1] = m_z[face_no][1];\n    coords[2] = m_z[face_no][2];\n    coords[3] = m_z[face_no][3];\n  }\n  \npublic:\n  \n  BoxMesh()\n  {\n    this->set_box( 2.0, 2.0, 2.0, 2.0, 2.0  );\n  }    \n  \n  BoxMesh(\n          T const & top_width\n          , T const & top_depth\n          , T const & bottom_width\n          , T const & bottom_depth\n          , T const & height\n          )\n  {          \n    this->set_box( top_width, top_depth, bottom_width, bottom_depth, height  );\n  }\n  \nprotected:\n  \n  void set_box(\n               T const & top_width\n               , T const & top_depth\n               , T const & bottom_width\n               , T const & bottom_depth\n               , T const & height)\n  {          \n    T const H     = height       * 0.5;\n    T const top_W = top_width    * 0.5;\n    T const top_D = top_depth    * 0.5;\n    T const bot_W = bottom_width * 0.5;\n    T const bot_D = bottom_depth * 0.5;\n    \n    // front face\t       \n    m_x1[0] = -bot_W; m_y1[0] = -H; m_z1[0] =  bot_D;\n    m_x1[1] =  bot_W; m_y1[1] = -H; m_z1[1] =  bot_D;\n    m_x1[2] =  top_W; m_y1[2] =  H; m_z1[2] =  top_D;   \n    m_x1[3] = -top_W; m_y1[3] =  H; m_z1[3] =  top_D;   \n    \n    // back face\t       \n    m_x2[0] = -top_W; m_y2[0] =  H; m_z2[0] = -top_D;\n    m_x2[1] =  top_W; m_y2[1] =  H; m_z2[1] = -top_D;   \n    m_x2[2] =  bot_W; m_y2[2] = -H; m_z2[2] = -bot_D;      \n    m_x2[3] = -bot_W; m_y2[3] = -H; m_z2[3] = -bot_D;\n    \n    // top face\n    m_x3[0] = -top_W; m_y3[0] =  H; m_z3[0] =  top_D;   \n    m_x3[1] =  top_W; m_y3[1] =  H; m_z3[1] =  top_D;   \n    m_x3[2] =  top_W; m_y3[2] =  H; m_z3[2] = -top_D;   \n    m_x3[3] = -top_W; m_y3[3] =  H; m_z3[3] = -top_D;   \n    \n    // bottom face\t       \n    m_x4[0] = -bot_W; m_y4[0] = -H; m_z4[0] = -bot_D;\n    m_x4[1] =  bot_W; m_y4[1] = -H; m_z4[1] = -bot_D;\n    m_x4[2] =  bot_W; m_y4[2] = -H; m_z4[2] =  bot_D;\n    m_x4[3] = -bot_W; m_y4[3] = -H; m_z4[3] =  bot_D;\n    \n    // left face\t       \n    m_x5[0] = -bot_W; m_y5[0] = -H; m_z5[0] = -bot_D;\n    m_x5[1] = -bot_W; m_y5[1] = -H; m_z5[1] =  bot_D;\n    m_x5[2] = -top_W; m_y5[2] =  H; m_z5[2] =  top_D;   \n    m_x5[3] = -top_W; m_y5[3] =  H; m_z5[3] = -top_D;   \n    \n    // right face\t       \n    m_x6[0] =  bot_W; m_y6[0] = -H; m_z6[0] =  bot_D;\n    m_x6[1] =  bot_W; m_y6[1] = -H; m_z6[1] = -bot_D;\n    m_x6[2] =  top_W; m_y6[2] =  H; m_z6[2] = -top_D;   \n    m_x6[3] =  top_W; m_y6[3] =  H; m_z6[3] =  top_D;   \n    \n    m_x[0] = &m_x1[0]; m_x[1] = &m_x2[0]; m_x[2] = &m_x3[0]; m_x[3] = &m_x4[0]; m_x[4] = &m_x5[0]; m_x[5] = &m_x6[0];\n    m_y[0] = &m_y1[0]; m_y[1] = &m_y2[0]; m_y[2] = &m_y3[0]; m_y[3] = &m_y4[0]; m_y[4] = &m_y5[0]; m_y[5] = &m_y6[0];\n    m_z[0] = &m_z1[0]; m_z[1] = &m_z2[0]; m_z[2] = &m_z3[0]; m_z[3] = &m_z4[0]; m_z[4] = &m_z5[0]; m_z[5] = &m_z6[0];\n  }\n  \n};\n\nBOOST_AUTO_TEST_SUITE(mass);\n\nBOOST_AUTO_TEST_CASE(box_mesh)\n{\n  BoxMesh<double> const callback;\n  \n  double const rho = 1.0;\n  \n  mass::Properties<double> Ibox = compute_box( rho, 1.0, 1.0, 1.0 );  // Compute ground truth value using analytical solution \n    \n  // Compute numerical solution\n  mass::Properties<double> Imesh = compute_mesh( rho, 6, &callback);\n  \n  // Compare numerical solution to ground truth solution -- they should be the same\n  BOOST_CHECK( Imesh.m_m   > 0.0 ); \n  BOOST_CHECK( Imesh.m_Ixx > 0.0 ); \n  BOOST_CHECK( Imesh.m_Iyy > 0.0 ); \n  BOOST_CHECK( Imesh.m_Izz > 0.0 );   \n  BOOST_CHECK_CLOSE( Imesh.m_Ixx, Imesh.m_Iyy, 0.01 );\n  BOOST_CHECK_CLOSE( Imesh.m_Iyy, Imesh.m_Izz, 0.01 );\n  BOOST_CHECK_CLOSE(   Imesh.m_x, 0.0, 0.01 );\n  BOOST_CHECK_CLOSE(   Imesh.m_y, 0.0, 0.01 );\n  BOOST_CHECK_CLOSE(   Imesh.m_z, 0.0, 0.01 );\n  BOOST_CHECK_CLOSE(   Imesh.m_m, Ibox.m_m, 0.01 );\n  BOOST_CHECK_CLOSE( Imesh.m_Ixx, Ibox.m_Ixx, 0.01 );\n  BOOST_CHECK_CLOSE( Imesh.m_Iyy, Ibox.m_Iyy, 0.01 );\n  BOOST_CHECK_CLOSE( Imesh.m_Izz, Ibox.m_Izz, 0.01 );\n  BOOST_CHECK_CLOSE( Imesh.m_Ixy, 0.0, 0.01 );\n  BOOST_CHECK_CLOSE( Imesh.m_Ixz, 0.0, 0.01 );\n  BOOST_CHECK_CLOSE( Imesh.m_Iyz, 0.0, 0.01 );\n  \n  BOOST_CHECK( Imesh.is_body_space() );  \n  BOOST_CHECK( !Imesh.is_model_space() );  \n}\n\n\nBOOST_AUTO_TEST_CASE(cuboid_mesh)\n{\n  using std::min;\n  using std::max;\n  using std::fabs;\n  \n  double const rho = 1.0;\n  \n  double tw = 1.0;\n  double td = 1.0;\n  double bw = 1.0;\n  double bd = 1.0;\n  double h  = 1.0;\n  \n  double old_y = 0.0;\n  \n  for(size_t i=0;i<10u;++i)\n  {\n    BoxMesh<double> const callback = BoxMesh<double>(tw,td,bw,bd,h);\n    \n    tw *= 0.1;\n    td *= 0.1;\n    \n    double iw = min(tw,bw)*0.5;\n    double id = min(td,bd)*0.5;  \n    mass::Properties<double> I = compute_box( rho, iw, h, id ); \n    \n    double ow = max(tw,bw)*0.5;\n    double od = max(td,bd)*0.5;\n    mass::Properties<double> O = compute_box( rho, ow, h, od );  \n        \n    // Compute numerical solution\n    mass::Properties<double> M = compute_mesh( rho, 6, &callback);\n    \n    BOOST_CHECK( M.m_m   >= I.m_m );\n    BOOST_CHECK( M.m_m   <= O.m_m );\n\n    \n    BOOST_CHECK( M.m_Ixx   >= I.m_Ixx );\n    BOOST_CHECK( M.m_Ixx   <= O.m_Ixx );\n\n    BOOST_CHECK( M.m_Iyy   >= I.m_Iyy );\n    BOOST_CHECK( M.m_Iyy   <= O.m_Iyy );\n    \n    BOOST_CHECK( M.m_Izz   >= I.m_Izz );\n    BOOST_CHECK( M.m_Izz   <= O.m_Izz );\n    \n    BOOST_CHECK( fabs( M.m_Ixy ) < 10e-10 );\n    BOOST_CHECK( fabs( M.m_Ixz ) < 10e-10 );\n    BOOST_CHECK( fabs( M.m_Iyz ) < 10e-10 );\n    \n    BOOST_CHECK( fabs( M.m_x ) < 10e-10 );\n    BOOST_CHECK( fabs( M.m_z ) < 10e-10 );\n    \n    BOOST_CHECK( M.m_y   <= old_y );\n\n    old_y = M.m_y;\n  }\n}\n\n\n\n\n\n\n\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "7d2a61de2b15c5b460add62300b26cf2705a3e29", "size": 6818, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/SIMULATION/MASS/unit_tests/mass_mesh/mass_mesh.cpp", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-11-27T09:44:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-13T00:24:21.000Z", "max_issues_repo_path": "PROX/SIMULATION/MASS/unit_tests/mass_mesh/mass_mesh.cpp", "max_issues_repo_name": "erleben/matchstick", "max_issues_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_issues_repo_licenses": ["MIT"], "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/SIMULATION/MASS/unit_tests/mass_mesh/mass_mesh.cpp", "max_forks_repo_name": "erleben/matchstick", "max_forks_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_forks_repo_licenses": ["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.6470588235, "max_line_length": 126, "alphanum_fraction": 0.551774714, "num_tokens": 2829, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079209, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4654447410018968}}
{"text": "//\n// Created by huangkun on 2020/9/18.\n//\n#include <Eigen/Eigen>\n#include <opencv2/core/eigen.hpp>\n#include <algorithm>\n#include <limits>\n\n#include <cv_calib.hpp>\n#include <dbscan.h>\n#include <opengv2/utility/utility.hpp>\n#include <opengv2/event_camera_calib/CirclesEventFrame.hpp>\n#include <opengv2/event_camera_calib/CalibCircle.hpp>\n#include <opengv2/sensor/PinholeCamera.hpp>\n\nopengv2::CirclesEventFrame::CirclesEventFrame(EventContainer::Ptr container, const std::pair<double, double> &duration,\n                                              CirclePatternParameters::Ptr pattern, Params params) :\n        EventFrame(container, duration), pattern_(pattern), params_(params) {\n    auto camera = dynamic_cast<CameraBase *>(sensor_.get());\n    if (pattern_->isAsymmetric) {\n        circleRadiusThreshold_ = std::min(\n                std::max(camera->size()[0], camera->size()[1]) /\n                std::max(pattern_->rows, 2 * pattern_->cols),\n                std::min(camera->size()[0], camera->size()[1]) /\n                std::min(pattern_->rows, 2 * pattern_->cols)) / pattern->squareSize * pattern->circleRadius * 1.5;\n    } else {\n        circleRadiusThreshold_ = std::min(\n                std::max(camera->size()[0], camera->size()[1]) /\n                std::max(pattern_->rows, pattern_->cols),\n                std::min(camera->size()[0], camera->size()[1]) /\n                std::min(pattern_->rows, pattern_->cols)) / pattern->squareSize * pattern->circleRadius * 1.5;\n    }\n}\n\nopengv2::CirclesEventFrame::Params::Params() {\n    dbscan_eps = 4;\n    dbscan_startMinSample = 2;\n    clusterMinSample = 5;\n    knn_num = 3;\n}\n\nopengv2::CirclesEventFrame::Params::Params(const cv::FileStorage &node) {\n    node[\"dbscan_eps\"] >> dbscan_eps;\n    node[\"dbscan_startMinSample\"] >> dbscan_startMinSample;\n    node[\"clusterMinSample\"] >> clusterMinSample;\n    node[\"knn_num\"] >> knn_num;\n    node[\"fitCircle\"] >> fitCircle;\n}\n\nstruct CircleErr {\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n    CircleErr(double fitErr, double radius, const Eigen::Ref<const Eigen::Vector2d> &center) :\n            fitErr(fitErr), radius(radius), center(center) {}\n\n    double fitErr;\n    double radius;\n    Eigen::Vector2d center;\n};\n\nbool opengv2::CirclesEventFrame::extractFeatures() {\n    if (positiveEvents_.empty() || negativeEvents_.empty()) {\n        return false;\n    }\n\n    auto dbscan = DBSCAN<Eigen::Vector2d, double>();\n    dbscan.Run(&positiveEvents_, 2, params_.dbscan_eps, params_.dbscan_startMinSample);\n    auto p_noise = std::move(dbscan.Noise);\n    auto p_clusters = std::move(dbscan.Clusters);\n    dbscan.Run(&negativeEvents_, 2, params_.dbscan_eps, params_.dbscan_startMinSample);\n    auto n_noise = std::move(dbscan.Noise);\n    auto n_clusters = std::move(dbscan.Clusters);\n\n    /** Draw the result and filter data **/\n    auto camera = dynamic_cast<CameraBase *>(sensor_.get());\n    image_ = cv::Mat(camera->size()[1], camera->size()[0], CV_8UC3, cv::Vec3b(0, 0, 0));\n\n    //debug\n    eventImage = image_.clone();\n    for (const Eigen::Vector2d &p: positiveEvents_) {\n        cv::Point loc(p[0], p[1]);\n        eventImage.at<cv::Vec3b>(loc) = cv::Vec3b(0, 0, 255);\n    }\n    for (const Eigen::Vector2d &p: negativeEvents_) {\n        cv::Point loc(p[0], p[1]);\n        eventImage.at<cv::Vec3b>(loc) = cv::Vec3b(0, 255, 0);\n    }\n\n    for (auto itr = p_clusters.begin(); itr != p_clusters.end();) {\n        // remove cluster with too few samples\n        if (itr->size() < params_.clusterMinSample) {\n            itr = p_clusters.erase(itr);\n        } else {\n            unsigned int color = 20 * (itr - p_clusters.begin());\n            for (unsigned int idx : *itr) {\n                cv::Point loc(positiveEvents_[idx][0], positiveEvents_[idx][1]);\n                image_.at<cv::Vec3b>(loc) = cv::Vec3b(color / 256, color % 256, 200);\n            }\n\n            itr++;\n        }\n    }\n\n    for (auto itr = n_clusters.begin(); itr != n_clusters.end();) {\n        // remove cluster with too few samples\n        if (itr->size() < params_.clusterMinSample) {\n            itr = n_clusters.erase(itr);\n        } else {\n            unsigned int color = 20 * (itr - n_clusters.begin());\n            for (unsigned int idx : *itr) {\n                cv::Point loc(negativeEvents_[idx][0], negativeEvents_[idx][1]);\n                image_.at<cv::Vec3b>(loc) = cv::Vec3b(color / 256, color % 256, 100);\n            }\n\n            itr++;\n        }\n    }\n\n    // store\n    nClusters_ = n_clusters;\n    pClusters_ = p_clusters;\n\n    // debug\n    clusterImage = image_.clone();\n\n    // too few events\n    if (p_clusters.size() < pattern_->rows * pattern_->cols || n_clusters.size() < pattern_->rows * pattern_->cols) {\n        return false;\n    }\n\n    /** find candidate circles **/\n    std::vector<std::pair<size_t, size_t>> candidates;\n    vectorofEigenMatrix<Eigen::Vector2d> candidateCenters;\n    std::vector<double> candidatesRadius;\n\n    // calculate each cluster center (median)\n    std::vector<uint> p_centers, n_centers;\n    auto p_compare_fun = [&](uint lhs, uint rhs) { return positiveEvents_[lhs].norm() < positiveEvents_[rhs].norm(); };\n    auto n_compare_fun = [&](uint lhs, uint rhs) { return negativeEvents_[lhs].norm() < negativeEvents_[rhs].norm(); };\n    for (auto &pCluster: p_clusters) {\n        std::nth_element(pCluster.begin(), pCluster.begin() + pCluster.size() / 2, pCluster.end(), p_compare_fun);\n        p_centers.push_back(pCluster[pCluster.size() / 2]);\n    }\n    for (auto &nCluster: n_clusters) {\n        std::nth_element(nCluster.begin(), nCluster.begin() + nCluster.size() / 2, nCluster.end(), n_compare_fun);\n        n_centers.push_back(nCluster[nCluster.size() / 2]);\n    }\n\n    /*// draw cluster centers\n    for (auto center: p_centers) {\n        cv::Point loc(positiveEvents_[center][0], positiveEvents_[center][1]);\n        cv::circle(image_, loc, 2, cv::Vec3b(255, 255, 255));\n    }\n    for (auto center: n_centers) {\n        cv::Point loc(negativeEvents_[center][0], negativeEvents_[center][1]);\n        cv::circle(image_, loc, 2, cv::Vec3b(255, 255, 255));\n    }*/\n\n    // building k-d tree\n    vectorofEigenMatrix<Eigen::Vector2d> pCenters(p_centers.size()), nCenters(n_centers.size());\n    for (int i = 0; i < p_centers.size(); ++i) {\n        pCenters[i] = positiveEvents_[p_centers[i]];\n    }\n    for (int i = 0; i < n_centers.size(); ++i) {\n        nCenters[i] = negativeEvents_[n_centers[i]];\n    }\n    KDTreeVectorOfVectorsAdaptor<vectorofEigenMatrix<Eigen::Vector2d>, double, 2, nanoflann::metric_L2_Simple>\n            p_kdTree(2, pCenters, 10), n_kdTree(2, nCenters, 10);\n\n    // Store fitError for Reusing\n    std::unordered_map<std::pair<size_t, size_t>, CircleErr, pair_hash> fitErrandRadiusMap;\n\n    const size_t num_results = params_.fitCircle ? params_.knn_num : 1;\n    std::vector<size_t> n_idx(num_results);\n    std::vector<size_t> p_idx(num_results);\n    std::vector<double> out_dists_sqr(num_results);\n    vectorofEigenMatrix<Eigen::Vector2d> centers(num_results);\n    std::vector<double> radius(num_results);\n    std::vector<double> fitErrs;\n    if (params_.fitCircle) {\n        for (size_t pi = 0; pi < p_centers.size(); ++pi) {\n            size_t realNum_results = num_results;\n            // search knn in opposite polarity cluster\n            n_kdTree.query(positiveEvents_[p_centers[pi]].data(), num_results, n_idx.data(), out_dists_sqr.data());\n\n            // remove cluster too far away\n            for (int oi = 0; oi < out_dists_sqr.size(); ++oi) {\n                if (out_dists_sqr[oi] > out_dists_sqr[0] * 4 ||\n                    out_dists_sqr[oi] > 4 * circleRadiusThreshold_ * circleRadiusThreshold_) {\n                    realNum_results = oi;\n                    break;\n                }\n            }\n            if (realNum_results == 0)\n                continue;\n\n            // connect two centers as diameter, verify circle fitting error\n            fitErrs.assign(realNum_results, 0);\n            for (int j = 0; j < realNum_results; ++j) {\n                auto itr = fitErrandRadiusMap.find(std::pair<size_t, size_t>(pi, n_idx[j]));\n                if (itr == fitErrandRadiusMap.end()) {\n                    fitCircle(p_clusters[pi], n_clusters[n_idx[j]], centers[j], radius[j]);\n\n                    double approxRadius =\n                            (positiveEvents_[p_centers[pi]] - negativeEvents_[n_centers[n_idx[j]]]).norm() / 2;\n                    if (radius[j] > circleRadiusThreshold_ || radius[j] > 2 * approxRadius) {\n                        fitErrs[j] = std::numeric_limits<double>::max();\n                    } else {\n                        for (auto pEvent: p_clusters[pi]) {\n                            fitErrs[j] += std::abs((positiveEvents_[pEvent] - centers[j]).norm() - radius[j]);\n                        }\n                        for (auto nEvent: n_clusters[n_idx[j]]) {\n                            fitErrs[j] += std::abs((negativeEvents_[nEvent] - centers[j]).norm() - radius[j]);\n                        }\n\n                        fitErrs[j] /= (p_clusters[pi].size() + n_clusters[n_idx[j]].size()) * radius[j];\n                    }\n                    fitErrandRadiusMap.emplace(std::pair<size_t, size_t>(pi, n_idx[j]),\n                                               CircleErr(fitErrs[j], radius[j], centers[j]));\n                } else {\n                    fitErrs[j] = itr->second.fitErr;\n                    radius[j] = itr->second.radius;\n                    centers[j] = itr->second.center;\n                }\n            }\n            int n_minIdx = std::min_element(fitErrs.begin(), fitErrs.end()) - fitErrs.begin();\n\n            // Do circle check for the minimum, if the fitting error greater than Expectation(assume gaussian noise)\n            const double gaussianNoise = 2 / radius[n_minIdx]; // TODO: considering ellipse\n            if (fitErrs[n_minIdx] < gaussianNoise) {\n                /* Double Direction Check */\n                realNum_results = num_results;\n                p_kdTree.query(negativeEvents_[n_centers[n_idx[n_minIdx]]].data(), num_results, p_idx.data(),\n                               out_dists_sqr.data());\n                for (int oi = 0; oi < out_dists_sqr.size(); ++oi) {\n                    if (out_dists_sqr[oi] > out_dists_sqr[0] * 4 ||\n                        out_dists_sqr[oi] > 4 * circleRadiusThreshold_ * circleRadiusThreshold_) {\n                        realNum_results = oi;\n                        break;\n                    }\n                }\n                if (realNum_results == 0)\n                    continue;\n                fitErrs.assign(realNum_results, 0);\n                for (int i = 0; i < realNum_results; ++i) {\n                    auto itr = fitErrandRadiusMap.find(std::pair<size_t, size_t>(p_idx[i], n_idx[n_minIdx]));\n                    if (itr == fitErrandRadiusMap.end()) {\n                        fitCircle(p_clusters[p_idx[i]], n_clusters[n_idx[n_minIdx]], centers[i], radius[i]);\n\n                        double approxRadius = (positiveEvents_[p_centers[p_idx[i]]] -\n                                               negativeEvents_[n_centers[n_idx[n_minIdx]]]).norm() / 2;\n                        if (radius[i] > circleRadiusThreshold_ || radius[i] > 2 * approxRadius) {\n                            fitErrs[i] = std::numeric_limits<double>::max();\n                        } else {\n                            for (auto pEvent: p_clusters[p_idx[i]]) {\n                                fitErrs[i] += std::abs((positiveEvents_[pEvent] - centers[i]).norm() - radius[i]);\n                            }\n                            for (auto nEvent: n_clusters[n_idx[n_minIdx]]) {\n                                fitErrs[i] += std::abs((negativeEvents_[nEvent] - centers[i]).norm() - radius[i]);\n                            }\n                            fitErrs[i] /=\n                                    (p_clusters[p_idx[i]].size() + n_clusters[n_idx[n_minIdx]].size()) * radius[i];\n                        }\n                        fitErrandRadiusMap.emplace(std::pair<size_t, size_t>(p_idx[i], n_idx[n_minIdx]),\n                                                   CircleErr(fitErrs[i], radius[i], centers[i]));\n                    } else {\n                        fitErrs[i] = itr->second.fitErr;\n                        radius[i] = itr->second.radius;\n                        centers[i] = itr->second.center;\n                    }\n                }\n                int p_minIdx = std::min_element(fitErrs.begin(), fitErrs.end()) - fitErrs.begin();\n\n                // if the same, add to candidate\n                if (p_idx[p_minIdx] == pi) {\n                    candidates.emplace_back(pi, n_idx[n_minIdx]);\n                    candidateCenters.push_back(centers[p_minIdx]);\n                    candidatesRadius.push_back(radius[p_minIdx]);\n                }\n            }\n        }\n    } else {\n        for (size_t pi = 0; pi < p_centers.size(); ++pi) {\n            n_kdTree.query(positiveEvents_[p_centers[pi]].data(), num_results, n_idx.data(), out_dists_sqr.data());\n            // remove cluster too far away\n            if (out_dists_sqr[0] > 4 * circleRadiusThreshold_ * circleRadiusThreshold_) {\n                continue;\n            }\n            p_kdTree.query(negativeEvents_[n_centers[n_idx[0]]].data(), num_results, p_idx.data(),\n                           out_dists_sqr.data());\n            if (p_idx[0] == pi) {\n                // check circle\n                Eigen::Vector2d center =\n                        (positiveEvents_[p_centers[p_idx[0]]] + negativeEvents_[n_centers[n_idx[0]]]) / 2;\n                double r = (positiveEvents_[p_centers[p_idx[0]]] - negativeEvents_[n_centers[n_idx[0]]]).norm() / 2;\n                double fitErr = 0;\n                for (auto pEvent: p_clusters[p_idx[0]]) {\n                    fitErr += std::abs((positiveEvents_[pEvent] - center).norm() - r);\n                }\n                for (auto nEvent: n_clusters[n_idx[0]]) {\n                    fitErr += std::abs((negativeEvents_[nEvent] - center).norm() - r);\n                }\n                fitErr /= (p_clusters[p_idx[0]].size() + n_clusters[n_idx[0]].size()) * r;\n\n                if (fitErr < 10 / r) {\n                    candidates.emplace_back(pi, n_idx[0]);\n                    candidateCenters.push_back(center);\n                    candidatesRadius.push_back(r);\n                }\n            }\n        }\n    }\n\n    // draw candidate circle\n    for (int i = 0; i < candidates.size(); ++i) {\n        cv::Point loc(candidateCenters[i][0], candidateCenters[i][1]);\n        cv::circle(image_, loc, candidatesRadius[i], cv::Vec3b(0, 255, 0));\n    }\n\n    /** use prior pattern to match the candidate **/\n    std::vector<cv::Point2f> points, outCenters;\n    for (const Eigen::Vector2d &center: candidateCenters) {\n        points.emplace_back(center[0], center[1]);\n    }\n    // TODO: 1. improve the sensitivity to additional nearby outlier\n    //  2. we should assume there are absence,\n    //  (even wrong pairs inside the pattern (seems too hard, maybe solved previously by more samples)),\n    //  also the centers are not accurate.\n    //  (solution) maybe optimization liangzu;\n    //  or maybe solved by mul-spline segment(just ignore the error segment) and ignore with go on;\n    //  user interaction (note: find sample in raw data)\n    bool isFound = cv::findCirclesGrid(points, cv::Size(pattern_->cols, pattern_->rows), outCenters,\n                                       cv::CALIB_CB_ASYMMETRIC_GRID);\n    if (!isFound)\n        isFound = cv::findCirclesGrid(points, cv::Size(pattern_->cols, pattern_->rows), outCenters,\n                                      cv::CALIB_CB_ASYMMETRIC_GRID | cv::CALIB_CB_CLUSTERING);\n    /*if (isFound)\n        circleExtractionImage = image_.clone();*/\n    drawChessboardCorners(image_, cv::Size(pattern_->cols, pattern_->rows), cv::Mat(outCenters), isFound);\n    if (isFound) {\n        KDTreeVectorOfVectorsAdaptor<vectorofEigenMatrix<Eigen::Vector2d>, double, 2, nanoflann::metric_L2_Simple>\n                kdTree(2, candidateCenters, 10);\n        std::vector<size_t> orderIdxs(pattern_->rows * pattern_->cols);\n        std::vector<double> out_dist_sqr(1);\n        for (int i = 0; i < outCenters.size(); ++i) {\n            Eigen::Vector2d c(outCenters[i].x, outCenters[i].y);\n            kdTree.query(c.data(), 1, orderIdxs.data() + i, out_dist_sqr.data());\n        }\n\n        // features_\n        for (auto idx: orderIdxs) {\n            features_.push_back(std::make_shared<CalibCircle>(candidateCenters[idx], candidatesRadius[idx]));\n        }\n\n        //detectionImage = image_.clone();\n    }\n\n    return isFound;\n}\n\nvoid opengv2::CirclesEventFrame::fitCircle(const std::vector<uint> &pSet,\n                                           const std::vector<uint> &nSet,\n                                           Eigen::Ref<Eigen::Vector2d> center, double &radius) {\n    double sum_x = 0, sum_y = 0;\n    double sum_xx = 0, sum_yy = 0, sum_xy = 0;\n    double sum_xxx = 0, sum_yyy = 0, sum_xyy = 0, sum_xxy = 0;\n    for (auto p_idx: pSet) {\n        const Eigen::Vector2d &sample = positiveEvents_[p_idx];\n\n        sum_x += sample[0];\n        sum_y += sample[1];\n\n        double xx = sample[0] * sample[0];\n        double yy = sample[1] * sample[1];\n        double xy = sample[0] * sample[1];\n\n        sum_xx += xx;\n        sum_yy += yy;\n        sum_xy += xy;\n\n        sum_xxx += xx * sample[0];\n        sum_yyy += yy * sample[1];\n        sum_xyy += xy * sample[1];\n        sum_xxy += sample[0] * xy;\n    }\n    for (auto n_idx: nSet) {\n        const Eigen::Vector2d &sample = negativeEvents_[n_idx];\n\n        sum_x += sample[0];\n        sum_y += sample[1];\n\n        double xx = sample[0] * sample[0];\n        double yy = sample[1] * sample[1];\n        double xy = sample[0] * sample[1];\n\n        sum_xx += xx;\n        sum_yy += yy;\n        sum_xy += xy;\n\n        sum_xxx += xx * sample[0];\n        sum_yyy += yy * sample[1];\n        sum_xyy += xy * sample[1];\n        sum_xxy += sample[0] * xy;\n    }\n\n    Eigen::Matrix3d A;\n    A << 2 * sum_x, 2 * sum_y, pSet.size() + nSet.size(),\n            2 * sum_xx, 2 * sum_xy, sum_x,\n            2 * sum_xy, 2 * sum_yy, sum_y;\n    Eigen::Vector3d b(sum_xx + sum_yy, sum_xxx + sum_xyy, sum_xxy + sum_yyy);\n\n    Eigen::Vector3d x = A.lu().solve(b);\n    center = x.block<2, 1>(0, 0);\n    radius = std::sqrt(x[0] * x[0] + x[1] * x[1] + x[2]);\n}\n\nbool\nopengv2::CirclesEventFrame::rectifyFeatures(const std::unordered_set<int> &outlierIdxs,\n                                            const Eigen::Ref<const Eigen::Matrix3d> &Rcw,\n                                            const Eigen::Ref<const Eigen::Vector3d> &tcw) {\n    KDTreeVectorOfVectorsAdaptor<vectorofEigenMatrix<Eigen::Vector2d>, double, 2, nanoflann::metric_L2_Simple>\n            p_kdTree(2, positiveEvents_, 10), n_kdTree(2, negativeEvents_, 10);\n\n    Eigen::Matrix3d Rsw = Rcw;\n    Eigen::Vector3d tsw = tcw;\n    auto camera = dynamic_cast<PinholeCamera *>(sensor_.get());\n    cv::Mat tvec, rvec, Rvec, distCoeffs, cameraMatrix;\n    cv::eigen2cv(Rsw, Rvec);\n    cv::Rodrigues(Rvec, rvec);\n    cv::eigen2cv(tsw, tvec);\n    cv::eigen2cv(camera->distCoeffs(), distCoeffs);\n    cv::eigen2cv(camera->K(), cameraMatrix);\n    for (int kIdx = 0; kIdx < features_.size(); kIdx++) {\n        auto f = dynamic_cast<CalibCircle *>(features_[kIdx].get());\n        auto lm = f->landmark();\n        Eigen::Vector3d center = lm->position();\n\n        std::vector<cv::Point3f> objectPoints;\n        objectPoints.reserve(5);\n        objectPoints.emplace_back(center[0], center[1], center[2]);\n        double skewR = pattern_->circleRadius / std::sqrt(2);\n        // Four quadrant, considering circle distortion\n        objectPoints.emplace_back(center[0] + skewR, center[1] + skewR, center[2]);\n        objectPoints.emplace_back(center[0] + skewR, center[1] - skewR, center[2]);\n        objectPoints.emplace_back(center[0] - skewR, center[1] - skewR, center[2]);\n        objectPoints.emplace_back(center[0] - skewR, center[1] + skewR, center[2]);\n\n        std::vector<cv::Point2f> imagePoints;\n        cv::projectPoints(objectPoints, rvec, tvec, cameraMatrix, distCoeffs, imagePoints);\n        vectorofEigenMatrix<Eigen::Vector2d> eigenImagePoints;\n        eigenImagePoints.reserve(5);\n        for (const auto &p: imagePoints) {\n            eigenImagePoints.emplace_back(p.x, p.y);\n        }\n\n        // if center exceed image bound, delete feature\n        if (imagePoints[0].x >= camera->size()[0] || imagePoints[0].y >= camera->size()[1] ||\n            imagePoints[0].x < 0 || imagePoints[0].y < 0) {\n            features_[kIdx] = nullptr;\n            continue;\n        }\n\n        std::vector<double> radius;\n        double maxRadius = 0;\n        radius.reserve(4);\n        for (int i = 1; i < 5; ++i) {\n            radius.push_back((eigenImagePoints[i] - eigenImagePoints[0]).norm());\n            if (radius.back() > maxRadius) {\n                maxRadius = radius.back();\n            }\n        }\n\n        double inlierThreshold = 3; // pixel unit\n        std::vector<std::pair<size_t, double>> p_IndicesDists, n_IndicesDists;\n        p_kdTree.index->radiusSearch(eigenImagePoints[0].data(), std::pow(maxRadius + inlierThreshold, 2),\n                                     p_IndicesDists,\n                                     nanoflann::SearchParams(32, 0, false));\n        n_kdTree.index->radiusSearch(eigenImagePoints[0].data(), std::pow(maxRadius + inlierThreshold, 2),\n                                     n_IndicesDists,\n                                     nanoflann::SearchParams(32, 0, false));\n\n        // collect inliers\n        std::pair<std::vector<uint>, std::vector<uint>> patternCircle;\n        for (const auto &pair: p_IndicesDists) {\n            Eigen::Vector2d direction = positiveEvents_[pair.first] - eigenImagePoints[0];\n            double distance = std::sqrt(pair.second);\n            int idx = 0;\n            if (direction[0] >= 0 && direction[1] >= 0) {\n                idx = 0;\n            } else if (direction[0] >= 0 && direction[1] <= 0) {\n                idx = 1;\n            } else if (direction[0] <= 0 && direction[1] <= 0) {\n                idx = 2;\n            } else if (direction[0] <= 0 && direction[1] >= 0) {\n                idx = 3;\n            }\n\n            if (std::abs(distance - radius[idx]) <= inlierThreshold) {\n                patternCircle.first.push_back(pair.first);\n            }\n        }\n        for (const auto &pair: n_IndicesDists) {\n            Eigen::Vector2d direction = negativeEvents_[pair.first] - eigenImagePoints[0];\n            double distance = std::sqrt(pair.second);\n            int idx = 0;\n            if (direction[0] >= 0 && direction[1] >= 0) {\n                idx = 0;\n            } else if (direction[0] >= 0 && direction[1] <= 0) {\n                idx = 1;\n            } else if (direction[0] <= 0 && direction[1] <= 0) {\n                idx = 2;\n            } else if (direction[0] <= 0 && direction[1] >= 0) {\n                idx = 3;\n            }\n\n            if (std::abs(distance - radius[idx]) <= inlierThreshold) {\n                patternCircle.second.push_back(pair.first);\n            }\n        }\n\n        // expand sample set by clustering\n        std::set<uint> pClusterSet, nClusterSet;\n        std::unordered_map<uint, uint> pSample2Set, nSample2Set;\n        for (int i = 0; i < pClusters_.size(); ++i) {\n            for (int j = 0; j < pClusters_[i].size(); ++j) {\n                pSample2Set.emplace(pClusters_[i][j], i);\n            }\n        }\n        for (int i = 0; i < nClusters_.size(); ++i) {\n            for (int j = 0; j < nClusters_[i].size(); ++j) {\n                nSample2Set.emplace(nClusters_[i][j], i);\n            }\n        }\n        for (const auto &p : patternCircle.first) {\n            if (pSample2Set.find(p) != pSample2Set.end())\n                pClusterSet.insert(pSample2Set[p]);\n        }\n        for (const auto &n : patternCircle.second) {\n            if (nSample2Set.find(n) != nSample2Set.end())\n                nClusterSet.insert(nSample2Set[n]);\n        }\n        patternCircle.first.clear();\n        for (const auto &pCluster: pClusterSet) {\n            for (const auto &p: pClusters_[pCluster]) {\n                patternCircle.first.push_back(p);\n            }\n        }\n        patternCircle.second.clear();\n        for (const auto &nCluster: nClusterSet) {\n            for (const auto &n: nClusters_[nCluster]) {\n                patternCircle.second.push_back(n);\n            }\n        }\n\n        // remove feature with too few measurements\n        if (patternCircle.first.size() < 5 || patternCircle.second.size() < 5) {\n            features_[kIdx] = nullptr;\n            continue;\n        }\n\n        Eigen::Vector2d rectifiedCenter;\n        double rectifiedRadius;\n        fitCircle(patternCircle.first, patternCircle.second, rectifiedCenter,\n                  rectifiedRadius);\n\n        std::nth_element(radius.begin(), radius.begin() + radius.size() / 2, radius.end());\n        // if fit result not good, delete feature\n        if ((rectifiedCenter - eigenImagePoints[0]).norm() > 2 * inlierThreshold ||\n            std::abs(rectifiedRadius - radius[radius.size() / 2]) > 1.5 * inlierThreshold) {\n            features_[kIdx] = nullptr;\n            continue;\n        }\n\n        f->setLocation(rectifiedCenter);\n        f->radius = rectifiedRadius;\n    }\n\n    // release no longer used member\n    positiveEvents_.clear();\n    negativeEvents_.clear();\n\n    // outlier features in the edges are more important\n    std::vector<std::unordered_set<int>> edgePattern(4);\n    std::vector<int> score(4, 0);\n    for (int i = 0; i < pattern_->cols; ++i) // 1st row\n        edgePattern[0].insert(i);\n    for (int i = (pattern_->rows - 1) * pattern_->cols; i < (pattern_->rows * pattern_->cols); ++i) // last row\n        edgePattern[1].insert(i);\n    for (int i = 0;\n         i < (pattern_->rows * pattern_->cols); i += (pattern_->isAsymmetric ? 2 : 1) * pattern_->cols) // 1st col\n        edgePattern[2].insert(i);\n    for (int i = pattern_->isAsymmetric ? (2 * pattern_->cols - 1) : (pattern_->cols - 1);\n         i < (pattern_->rows * pattern_->cols); i += (pattern_->isAsymmetric ? 2 : 1) * pattern_->cols) // last col\n        edgePattern[3].insert(i);\n\n    int counter = 0, index = 0;\n    for (auto itr = features_.begin(); itr != features_.end(); index++) {\n        if (*itr == nullptr) {\n            itr = features_.erase(itr);\n            for (int i = 0; i < 4; ++i) {\n                if (edgePattern[i].find(index) != edgePattern[i].end())\n                    score[i]++;\n            }\n            counter++;\n        } else {\n            itr++;\n        }\n    }\n\n    // check features on edge\n    if (!params_.fitCircle) {\n        for (int i = 0; i < 4; ++i) {\n            if (score[i] >= (int) (edgePattern[i].size() - 1))\n                return false;\n        }\n    }\n\n    // remove frame with too many features gone\n    if (counter >= 0.2 * (pattern_->cols * pattern_->rows)) {\n        return false;\n    }\n\n    for (auto fb: features_) {\n        auto f = dynamic_cast<CalibCircle *>(fb.get());\n        cv::Point loc(f->location()[0], f->location()[1]);\n        cv::circle(image_, loc, f->radius, cv::Vec3b(255, 255, 255));\n    }\n\n    // Building KD-Tree for neighbor searching on features_, used for establish corresponds for given event.\n    circles_.reserve(features_.size());\n    for (const auto &f: features_) {\n        circles_.push_back(f->location());\n    }\n    circleKdTree_ = std::make_shared<KDTreeVectorOfVectorsAdaptor<vectorofEigenMatrix<Eigen::Vector2d>, double, 2>>\n            (2, circles_, 10);\n\n    return true;\n}", "meta": {"hexsha": "33fd0c76a1b5b927d9596adf3ceea162683c0430", "size": 27660, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/camera_calibration/event_camera_calib/src/CirclesEventFrame.cpp", "max_stars_repo_name": "MobilePerceptionLab/EventCameraCalibration", "max_stars_repo_head_hexsha": "debd774ac989674b500caf27641b7ad4e94681e9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2021-08-06T03:21:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T03:40:54.000Z", "max_issues_repo_path": "modules/camera_calibration/event_camera_calib/src/CirclesEventFrame.cpp", "max_issues_repo_name": "MobilePerceptionLab/EventCameraCalibration", "max_issues_repo_head_hexsha": "debd774ac989674b500caf27641b7ad4e94681e9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-02-25T02:55:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-25T15:18:45.000Z", "max_forks_repo_path": "modules/camera_calibration/event_camera_calib/src/CirclesEventFrame.cpp", "max_forks_repo_name": "MobilePerceptionLab/EventCameraCalibration", "max_forks_repo_head_hexsha": "debd774ac989674b500caf27641b7ad4e94681e9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2021-08-11T12:29:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-25T03:41:01.000Z", "avg_line_length": 43.3542319749, "max_line_length": 119, "alphanum_fraction": 0.5514099783, "num_tokens": 7196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.46544473547256127}}
{"text": "#include <ros/ros.h>\n#include <sensor_msgs/Imu.h>\n#include <message_filters/subscriber.h>\n#include <boost/math/distributions/normal.hpp>\n#include <boost/random.hpp>\n#include <tf/transform_listener.h>\n\nnamespace\n{\nusing namespace std;\nusing namespace geometry_msgs;\nusing namespace std_msgs;\n\nstatic const double MEAN = 0.0;\nstatic const double STD_DEV = 2.0;\n\nclass ImuGaussianNoise\n{\nprivate:\n    //! Node handle\n    ros::NodeHandle nh;\n\n    //! Private nh\n    ros::NodeHandle pnh;\n\n    //! IMU subscription\n    auto_ptr<message_filters::Subscriber<sensor_msgs::Imu> > imuSub;\n\n    //! Publisher for the filterered IMU\n    ros::Publisher filteredPub;\n    boost::normal_distribution<double> dist;\n\n    boost::mt19937 engine;\n\npublic:\n    ImuGaussianNoise() :\n        pnh(\"~\"), dist(MEAN, STD_DEV)\n    {\n        imuSub.reset(new message_filters::Subscriber<sensor_msgs::Imu>(nh, \"/in\", 1));\n        imuSub->registerCallback(boost::bind(&ImuGaussianNoise::imuCallback, this, _1));\n\n        engine.seed(0);\n        filteredPub = nh.advertise<sensor_msgs::Imu>(\"/out\", 1);\n    }\n\nprivate:\n\n    void imuCallback(sensor_msgs::ImuConstPtr data)\n    {\n        ROS_DEBUG(\"Unfiltered angular velocity [%f] [%f] [%f]\", data->angular_velocity.x, data->angular_velocity.y, data->angular_velocity.z);\n\n        // Copy over all fields\n        sensor_msgs::ImuPtr output(new sensor_msgs::Imu(*data));\n\n        // Compute random noise on xyz velocity\n        boost::variate_generator<boost::mt19937&, boost::normal_distribution<> > randNormal(engine, dist);\n\n        double x = randNormal();\n        double y = randNormal();\n        double z = randNormal();\n\n        ROS_DEBUG(\"Generated random parameters for x [%f], y [%f], z [%f]\", x, y, z);\n        output->angular_velocity.x += x;\n        output->angular_velocity.y += y;\n        output->angular_velocity.z += z;\n\n        // Compute random noise on position\n        double r = randNormal() / 20.0;\n        double p = randNormal() / 20.0;\n        double yaw = randNormal() / 20.0;\n        ROS_INFO(\"Generated random parameters for r [%f], p [%f], yaw [%f]\", r, p, yaw);\n\n        tf::Quaternion update = tf::createQuaternionFromRPY(r, p, yaw);\n        tf::Quaternion curr;\n        tf::quaternionMsgToTF(data->orientation, curr);\n        tf::quaternionTFToMsg((curr + update).normalized(), output->orientation);\n\n        filteredPub.publish(output);\n    }\n};\n}\nint main(int argc, char** argv)\n{\n    ros::init(argc, argv, \"imu_gaussian_noise\");\n\n    ImuGaussianNoise imuFilter;\n    ros::spin();\n}\n", "meta": {"hexsha": "9b790f945d1a161384e83bff72fa037c7e24f023", "size": 2531, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/imu_gaussian_noise.cpp", "max_stars_repo_name": "PositronicsLab/humanoid_catching", "max_stars_repo_head_hexsha": "11d42d164c7f19fbd8642c9c0318a630111ec18e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/imu_gaussian_noise.cpp", "max_issues_repo_name": "PositronicsLab/humanoid_catching", "max_issues_repo_head_hexsha": "11d42d164c7f19fbd8642c9c0318a630111ec18e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/imu_gaussian_noise.cpp", "max_forks_repo_name": "PositronicsLab/humanoid_catching", "max_forks_repo_head_hexsha": "11d42d164c7f19fbd8642c9c0318a630111ec18e", "max_forks_repo_licenses": ["Apache-2.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.4382022472, "max_line_length": 142, "alphanum_fraction": 0.6467799289, "num_tokens": 643, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.46544473547256127}}
{"text": "/**\n *  test_dyn_longitudinal.cpp\n *\n *  The longitudinal kinematics of DC9-30.\n *\n *  Created by Yinan Li on Mar.27, 2020.\n *  Hybrid Systems Group, University of Waterloo.\n */\n\n#include <iostream>\n#include <boost/numeric/odeint.hpp>\n\n#include \"src/system.hpp\"\n#include \"src/csolver.h\"\n#include \"src/matlabio.h\"\n\n\ntypedef std::array<double, 3> state_type;\n\n/* Parameters of the model */\ndouble mg = 60000.0*9.81;\ndouble mi = 1.0/60000; /* weight inverse: 1/m */\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\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    \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    /* test the reachable set */\n    // rocs::ivec x= {rocs::interval(60,60.05),\n    // \t\t   rocs::interval(-M_PI/180,-21/22*M_PI/180),\n    // \t\t   rocs::interval(16,16.2)};\n    rocs::ivec x= {rocs::interval(80.0,81.0),\n\t\t   rocs::interval(-0.0196,-0.0131),\n\t\t   rocs::interval(54.25,56.00)};\n    // rocs::Rn u = {0,0};\n    std::vector<rocs::ivec> y(aircraft._ugrid._nv, rocs::ivec(3));\n    std::cout << \"The initial interval: \" << x << '\\n';\n    aircraft.get_reach_set(y, x);\n    std::cout << \"The reachable set of x: \\n\";\n    // std::cout << y[12] << '\\n';\n    for (int i = 0; i < y.size(); ++i)\n    \tstd::cout << y[i] <<'\\n';\n\n    aircraft.release_flows();\n    return 0;\n}\n", "meta": {"hexsha": "1d8a625eeab2795176ae337930a22c0597032e62", "size": 2884, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/aircraft/test_dynlong.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/test_dynlong.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/test_dynlong.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": 28.84, "max_line_length": 75, "alphanum_fraction": 0.5592926491, "num_tokens": 1006, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.46544473547256127}}
{"text": "#include <boost/math/special_functions/sinhc.hpp>\n", "meta": {"hexsha": "ed9801a8b8fb04e61f6189949ee6c3cdecbb98dd", "size": 50, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_special_functions_sinhc.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_special_functions_sinhc.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_special_functions_sinhc.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 25.0, "max_line_length": 49, "alphanum_fraction": 0.82, "num_tokens": 12, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308600986326, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4654261784612531}}
{"text": "\n\n#include <wav_utils.hxx>\n\n\n#include <iostream>\n\n///stats.hpp>\n//#include <boost/accumulators/statistics/mean.hpp>\n//#include <boost/accumulators/statistics/variance.hpp>\n\n// this program is a lot like basic_convolution.cxx in ../fast_fourier.\n// in this one, I read two wav files and find the point of maximum correlation.\n\n// I then FFT both, multiple the results FFT1 * complex_conjugate(FFT2) at each position.\n\n// last, I inverse FFT that and save to channels 3/4 (real/imaginary)\n\n\n// ffmpeg -i sample_video/htc/VIDEO0635.mp4 -map 0:a -ac 1 tmp/htc.wav\n// ffmpeg -i sample_video/s5/VID_20170608_152423.mp4 -map 0:a tmp/s5.wav\n// find . | xargs -I file ffmpeg -i file -map 0:a -ac 1 -ar 10000 -y ../tmp10k/file\n\nint main(int argc, char** argv) {\n\n  if (argc < 3) {\n    std::cerr << \"need two wav filenames\" << std::endl;\n    exit(-1);\n  }\n\n  bool include_cc = false;\n  if (argc > 3) {\n    if (std::string(argv[3]) == \"true\") {\n      include_cc = true;\n    } else {\n      printf(\"unknown third option. expecting true, got %s\\n\", argv[3]);\n      exit(-1);\n    }\n  }\n  \n  wav_samples ws1;\n  ws1.filename = argv[1];\n  read_wav(ws1);\n  wav_samples ws2;\n  ws2.filename = argv[2];\n  read_wav(ws2);\n\n  // I want the fftsize to be twice the sample length. Why?\n  // If ws2 preceeds ws1, then the peak will be in the second\n  // half of the cross-correlation.\n  // What if ws1 preceeds ws2 by more than half of the sample\n  // length? In that case, the peak will also be in the second\n  // half.\n  // By using twice the length, that second case will have a peak\n  // in the first half. A peak in the second half will only be\n  // possible with case 1.\n  int fftsize = std::max(ws1.frames, ws2.frames)*2;\n  std::cout << \"need fft size of \" << fftsize << std::endl;\n\n  add_fft(ws1, fftsize);\n  add_fft(ws2, fftsize);\n\n  correlation_data cd = correlate_wavs(ws1, ws2, fftsize, ws1.samplerate, include_cc);\n\n  std::cout << \"offset is \" << double(cd.offset)/double(ws1.samplerate) << std::endl;\n  \n  const int channels = (include_cc ? 4 : 2);\n\n  // have to divide by two since we multiplied above.\n  const int numaligned = fftsize/2+std::abs(cd.offset);\n  \n  std::vector<double> samples(numaligned*channels,0);\n\n  for(int i=0; i<numaligned; i++) {\n    samples[channels*i] = 0;\n    samples[channels*i+1] = 0;\n  }\n\n  // in correlation_data struct, wss1 will be earlier in the timeline.\n  std::cout << cd.wss1->filename << \" is ahead of \" << cd.wss2->filename\n            << \" by \" << double(cd.offset)/cd.wss1->samplerate << std::endl;\n\n  for(int i=0; i<cd.wss1->frames; i++) {\n    samples[channels*i] =               cd.wss1->samples[cd.wss1->channels*i];\n  }\n  for(int i=0; i<cd.wss2->frames; i++) {\n    // the +1 is because we want the second channel.\n    samples[channels*(i+cd.offset)+1] = cd.wss2->samples[cd.wss2->channels*i];\n  }\n\n  if (include_cc) {\n    double maxval = 0;\n    \n    for(int i=0; i<fftsize/2; i++) {\n      maxval = std::max(maxval, std::abs(cd.cross_correlation[i]));\n    }    \n    for(int i=0; i<fftsize/2; i++) {\n      samples[channels*i+2] =           cd.cross_correlation[i].real()/maxval;\n      samples[channels*i+3] =           cd.cross_correlation[i].imag()/maxval;\n    }\n  }\n  \n  write_wav(samples, numaligned, cd.wss1->samplerate, channels, std::string(\"aligned.wav\"));\n  \n}\n", "meta": {"hexsha": "bb4e36623cea8a0a7fd435c24b80be4bc879828a", "size": 3297, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "audio_sync/sync_wavs.cxx", "max_stars_repo_name": "mmccoo/nerd_mmccoo", "max_stars_repo_head_hexsha": "dc5a152105d65673679ef37ea5d1f7607e4f3b2c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 45.0, "max_stars_repo_stars_event_min_datetime": "2017-06-21T07:46:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T01:39:02.000Z", "max_issues_repo_path": "audio_sync/sync_wavs.cxx", "max_issues_repo_name": "zxh1986123/nerd_mmccoo", "max_issues_repo_head_hexsha": "dc5a152105d65673679ef37ea5d1f7607e4f3b2c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2018-02-08T19:29:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-14T09:27:18.000Z", "max_forks_repo_path": "audio_sync/sync_wavs.cxx", "max_forks_repo_name": "zxh1986123/nerd_mmccoo", "max_forks_repo_head_hexsha": "dc5a152105d65673679ef37ea5d1f7607e4f3b2c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 23.0, "max_forks_repo_forks_event_min_datetime": "2018-02-12T21:18:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-21T23:04:51.000Z", "avg_line_length": 31.1037735849, "max_line_length": 92, "alphanum_fraction": 0.6396724295, "num_tokens": 1022, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4654261725053782}}
{"text": "#include <iostream>\r\n#include <fstream>\r\n#include <sstream>\r\n#include <string>\r\n#include <vector>\r\n#include <iterator>\r\n#include <iomanip>\r\n#include <Eigen/Dense>\r\n#include <cmath>\r\n#include <random>\r\n#include \"constants.h\"\r\n#include \"simulationbox.h\"\r\n#include \"fileinput.h\"\r\n#include \"fileoutput.h\"\r\n#include \"thermostats.h\"\r\n\r\nusing namespace Eigen;\r\n\r\nclass LennardJones\r\n{\r\n    private:\r\n         Vector3d cutoffadjust;\r\n        double sigma;\r\n        double epsilon;\r\n        double cutoff;         \r\n    public:\r\n        LennardJones(double, double, double);\r\n        Vector3d getForce(Vector3d);\r\n};\r\n\r\nLennardJones::LennardJones(double insigma, double inepsilon, double incutoff=10000) {\r\n    // Constructs the Lennard Jones class, converting to atomic units as we go\r\n    // We expect the sigma to be in angstrom,\r\n    // The epsilon to be in Hartrees\r\n    // and the cutoff to also be in angstrom\r\n \r\n    sigma = insigma * constants::bohrAng;\r\n    epsilon = inepsilon * constants::boltzHar;\r\n    cutoff = incutoff * constants::bohrAng;\r\n    double cutoff_pair_virial = 24 * epsilon / pow(cutoff, 2);\r\n    double cutoff_sigma_6 = pow(sigma, 6) / pow(cutoff, 6);\r\n    double cutoff_sigma_12 = pow(cutoff_sigma_6, 2);\r\n    double cutoffadjust_value = cutoff_pair_virial * (2 * cutoff_sigma_12 - cutoff_sigma_6);\r\n    cutoffadjust(0) = cutoffadjust_value;\r\n    cutoffadjust(1) = cutoffadjust_value;\r\n    cutoffadjust(2) = cutoffadjust_value;\r\n}\r\n\r\nVector3d LennardJones::getForce(Vector3d distance)\r\n{\r\n    /* Class function for the Lennard Jones model that takes in\r\n     * a radial distance and outputs the force vector,\r\n     * and the energy in relation to that */\r\n    double radiusSquared=distance.squaredNorm();\r\n    if (radiusSquared > pow(cutoff,2)){\r\n        // We're outside the range we wanted to look at\r\n        // so just return no force and carry on\r\n        Vector3d force(0.0, 0.0, 0.0);\r\n        return force;\r\n    }\r\n    double sigma6 = pow(sigma, 6) / pow(radiusSquared, 3);\r\n    double sigma12 = pow(sigma6, 2);\r\n    //Allen and Tildesey eq 2.59-2.63, then eq 5.3\r\n    double pair_virial = 24.0 * epsilon / radiusSquared;\r\n    Vector3d force = (distance * pair_virial * (2 * sigma12 - sigma6)) + cutoffadjust;\r\n    return force;\r\n}\r\n\r\nvoid implement_boundary_conditions(ArrayXXd &positions, const Box &inputBox) {\r\n    // Mutates the input array to fix any atoms that are outside the\r\n    // boundary conditions\r\n    // Fails when an atom is more than twice the boundary away,\r\n    // but something else has gone wrong then\r\n\r\n    for (int atom=0; atom < positions.rows(); ++atom) {\r\n        for (int dim=0; dim < positions.cols(); ++dim) {\r\n            if (positions(atom, dim) < 0.0) {\r\n                positions(atom, dim) += inputBox.sides(dim);\r\n            }\r\n            else if (positions(atom, dim) > inputBox.sides(dim)) {\r\n                positions(atom, dim) -= inputBox.sides(dim);\r\n            }\r\n        }\r\n    }\r\n}\r\n\r\nArrayXXd populate_velocities(const Box &input_box, const ArrayXd &masses, double temperature){\r\n    // Populates the velocity array with velocities sampled\r\n    // randomly from a Gaussian distribution with mean 0 and\r\n    // variance 1.\r\n    \r\n    // This is then rescaled to match the temperature before\r\n    // it is used\r\n\r\n\r\n    std::random_device device;\r\n    std::mt19937 mt_rand(device());\r\n    \r\n    // This is the normal distribution generator\r\n    double mean = 0.0;\r\n    double var = 1.0;\r\n    std::normal_distribution<double> gaussian(mean, var);\r\n\r\n    ArrayXXd velocities = ArrayXXd::Zero(masses.rows(), input_box.dimensions);\r\n    // Use the number of rows in the masses as a proxy for \r\n    // number of atoms\r\n    for (int atom=0; atom < masses.rows(); ++atom) {\r\n        for (int dim=0; dim < input_box.dimensions; ++dim) {\r\n            velocities(atom, dim) = gaussian(mt_rand);\r\n        }\r\n    }\r\n    \r\n    auto rescaler = VelocityRescale();\r\n    rescaler.apply(velocities, masses, temperature);\r\n    return velocities;\r\n}\r\n\r\nArrayXXd populate_positions(const Box &inputBox, int num_x, int num_y, int num_z) {\r\n    /* Fills the position array with atoms evenly spaced in the box\r\n     * starting from (0, 0) */\r\n    ArrayXXd positions(num_x * num_y * num_z, inputBox.dimensions);\r\n    double x_increment = inputBox.sides(0) / static_cast<double>(num_x);\r\n    double y_increment = inputBox.sides(1) / static_cast<double>(num_y);\r\n    double z_increment = inputBox.sides(2) / static_cast<double>(num_z);\r\n    int counter = 0;\r\n    for (int row=0; row < num_x; ++row) {\r\n        for (int col=0; col < num_y; ++col) {\r\n            for (int plane=0; plane < num_z; ++plane) {\r\n                positions(counter, 0) = row * x_increment;\r\n                positions(counter, 1) = col * y_increment;\r\n                positions(counter, 2) = plane * z_increment;\r\n                ++counter;\r\n            }\r\n        }\r\n    }\r\n    return positions;\r\n}\r\n\r\nVector3d implement_minimum_image(const Vector3d distance, const Box &box) {\r\n    auto new_distance = distance;\r\n    for (int dim=0; dim < box.dimensions; ++dim) {\r\n        if (distance(dim) <= -0.5 * box.sides(dim)) {\r\n            new_distance(dim) += box.sides(dim);\r\n        } else if (distance(dim) > 0.5 * box.sides(dim)) {\r\n            new_distance(dim) -= box.sides(dim);\r\n        }\r\n    }   \r\n    return new_distance;\r\n}\r\n\r\nArrayXXd calculate_forces(ArrayXXd &atoms_array, const Box &box, LennardJones &potential_model) {\r\n    /* Calculates the force according to a Lennard-Jones potential\r\n     * from one atom to its nearest image, and returns\r\n     * an array of these forces */\r\n    ArrayXXd forces = ArrayXXd::Zero(atoms_array.rows(), atoms_array.cols());\r\n    for (int i=0; i < atoms_array.rows(); ++i) {\r\n        for (int j=0; j<i; ++j) {\r\n            Vector3d distance = atoms_array.row(i) - atoms_array.row(j);\r\n            distance = implement_minimum_image(distance, box);\r\n            Vector3d instant_force(potential_model.getForce(distance));\r\n\r\n            for (int dim=0; dim < box.dimensions; ++dim) {\r\n                forces(i, dim) += instant_force(dim);\r\n                forces(j, dim) -= instant_force(dim);\r\n            }\r\n        }\r\n    }\r\n    return forces;\r\n}\r\n\r\nvoid velocityVerlet(ArrayXXd &positions, ArrayXXd &velocities, double timestep, ArrayXd &masses,\r\n                    const Box &box, LennardJones &potentialModel) {\r\n    ArrayXXd accelerations = calculate_forces(positions, box, potentialModel).colwise() / masses;\r\n    ArrayXXd positions_next = positions \r\n                              + (velocities * timestep)\r\n                              + (0.5 * accelerations * pow(timestep, 2));\r\n    ArrayXXd accelerations_next = calculate_forces(positions_next, box, potentialModel).colwise() / masses;\r\n    ArrayXXd velocities_next = velocities \r\n                               + 0.5 * ( accelerations + accelerations_next) * timestep;\r\n    velocities = velocities_next;\r\n    implement_boundary_conditions(positions_next, box);\r\n    positions = positions_next;\r\n}\r\n\r\nint main() {\r\n    auto parameter_map = read_in_from_file(\"input.inpt\");\r\n    LennardJones potentialModel(std::stod(parameter_map[\"LJ_sigma\"]),\r\n                                std::stod(parameter_map[\"LJ_epsilon\"]),\r\n                                std::stod(parameter_map[\"LJ_cutoff\"]));\r\n    Box simulation_box(std::stod(parameter_map[\"length_x\"]),\r\n                       std::stod(parameter_map[\"length_y\"]),\r\n                       std::stod(parameter_map[\"length_z\"]));\r\n    int num_x = stoi(parameter_map[\"num_x\"]);\r\n    int num_y = stoi(parameter_map[\"num_y\"]);\r\n    int num_z = stoi(parameter_map[\"num_z\"]);\r\n    double temperature = std::stod(parameter_map[\"temperature\"]);\r\n    double timestep = std::stod(parameter_map[\"timestep\"]);\r\n    int rescaleStep=std::stoi(parameter_map[\"num_rescale\"]);\r\n    int outputStep=std::stoi(parameter_map[\"num_output\"]);\r\n    int numSteps=std::stoi(parameter_map[\"num_steps\"]);\r\n    \r\n    ArrayXXd atoms = populate_positions(simulation_box, num_x, num_y, num_z);\r\n    ArrayXd masses = ArrayXd::Zero(atoms.rows(), 1);\r\n    masses += std::stod(parameter_map[\"mass\"]);\r\n    \r\n    ArrayXXd velocities = populate_velocities(simulation_box, masses, temperature);\r\n \r\n    clearOutputFiles(parameter_map[\"position_file\"]);\r\n\r\n    for (int step=0; step < numSteps; ++step) {\r\n        velocityVerlet(atoms, velocities, timestep, masses, simulation_box, potentialModel);\r\n        if (step % rescaleStep == 0) {\r\n            rescale_velocities(velocities, masses, temperature);\r\n        }\r\n\r\n        if (step % outputStep == 0) {\r\n            dumpToFile(atoms, parameter_map[\"position_file\"], step);\r\n            std::cout << \"Step \" << step << std::endl;\r\n        }\r\n    }\r\n}\r\n", "meta": {"hexsha": "7fd1d4a2fb13b527e9ff7b7f7867490190eb3b2d", "size": 8747, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "Matt-HJ-Bailey/TinyMD", "max_stars_repo_head_hexsha": "71df0712b916083394fb259a380300b6b613cde7", "max_stars_repo_licenses": ["MIT"], "max_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": "Matt-HJ-Bailey/TinyMD", "max_issues_repo_head_hexsha": "71df0712b916083394fb259a380300b6b613cde7", "max_issues_repo_licenses": ["MIT"], "max_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": "Matt-HJ-Bailey/TinyMD", "max_forks_repo_head_hexsha": "71df0712b916083394fb259a380300b6b613cde7", "max_forks_repo_licenses": ["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.4009009009, "max_line_length": 108, "alphanum_fraction": 0.6207842689, "num_tokens": 2135, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4654261665495032}}
{"text": "#ifndef STAN_MATH_PRIM_SCAL_PROB_FRECHET_RNG_HPP\n#define STAN_MATH_PRIM_SCAL_PROB_FRECHET_RNG_HPP\n\n#include <stan/math/prim/scal/err/check_consistent_sizes.hpp>\n#include <stan/math/prim/scal/err/check_nonnegative.hpp>\n#include <stan/math/prim/scal/err/check_not_nan.hpp>\n#include <stan/math/prim/scal/err/check_positive.hpp>\n#include <stan/math/prim/scal/err/check_positive_finite.hpp>\n#include <stan/math/prim/scal/fun/log1m.hpp>\n#include <stan/math/prim/scal/fun/multiply_log.hpp>\n#include <stan/math/prim/scal/fun/value_of.hpp>\n#include <stan/math/prim/scal/meta/length.hpp>\n#include <stan/math/prim/scal/meta/VectorBuilder.hpp>\n#include <stan/math/prim/scal/meta/return_type.hpp>\n#include <stan/math/prim/scal/fun/constants.hpp>\n#include <stan/math/prim/scal/meta/include_summand.hpp>\n#include <boost/random/weibull_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n\nnamespace stan {\n  namespace math {\n\n    template <class RNG>\n    inline double\n    frechet_rng(double alpha,\n                double sigma,\n                RNG& rng) {\n      using boost::variate_generator;\n      using boost::random::weibull_distribution;\n\n      static const char* function(\"frechet_rng\");\n\n      check_finite(function, \"Shape parameter\", alpha);\n      check_positive(function, \"Shape parameter\", alpha);\n      check_not_nan(function, \"Scale parameter\", sigma);\n      check_positive(function, \"Scale parameter\", sigma);\n\n      variate_generator<RNG&, weibull_distribution<> >\n        weibull_rng(rng, weibull_distribution<>(alpha, 1.0/sigma));\n      return 1.0 / weibull_rng();\n    }\n\n  }\n}\n#endif\n", "meta": {"hexsha": "a10c022e2e0e0560c293b8446d864f9a3abcb9c3", "size": 1599, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/scal/prob/frechet_rng.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/prim/scal/prob/frechet_rng.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/prim/scal/prob/frechet_rng.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.7608695652, "max_line_length": 67, "alphanum_fraction": 0.7373358349, "num_tokens": 404, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.46542616654950314}}
{"text": "#include <boost/math/special_functions/modf.hpp>\n", "meta": {"hexsha": "252f3d5b7e7d6641a5ecdfd3917f08a7cb516deb", "size": 49, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_special_functions_modf.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_special_functions_modf.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_special_functions_modf.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 24.5, "max_line_length": 48, "alphanum_fraction": 0.8163265306, "num_tokens": 11, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384735, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.46542616059362785}}
{"text": "#pragma once\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/IterativeLinearSolvers>\n\n#include <tbb/tbb.h>\n\n#include \"Utilities/Utility.hpp\"\n#include \"Observables/Energy.hpp\"\n#include \"./utils.hpp\"\n\nnamespace yannq\n{\ntemplate<typename Machine, typename Hamiltonian>\nclass SRMat;\n} //namespace yannq\n\nnamespace Eigen { //namespace Eigen\nnamespace internal {\n\ttemplate<typename Machine, typename Hamiltonian>\n\tstruct traits<yannq::SRMat<Machine, Hamiltonian> > \n\t\t:  public Eigen::internal::traits<Eigen::SparseMatrix<typename Machine::Scalar> > {};\n}\n}// namespace Eigen;\n\nnamespace yannq\n{\n//! \\addtogroup GroundState\n\n//! \\ingroup GroundState\n//! This class that generates the quantum Fisher matrix for the stochastic reconfiguration (SR) method.\ntemplate<typename Machine, typename Hamiltonian>\nclass SRMat\n\t: public Eigen::EigenBase<SRMat<Machine, Hamiltonian> >\n{\npublic:\n\tusing Scalar = typename Machine::Scalar;\n\tusing RealScalar = typename remove_complex<Scalar>::type;\n\n\tusing Matrix = typename Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>;\n\tusing Vector = typename Eigen::Matrix<Scalar, Eigen::Dynamic, 1>;\n\n\tusing VectorConstRef = typename Eigen::Ref<const Vector>;\n\tusing RealMatrix = typename Eigen::Matrix<RealScalar, Eigen::Dynamic, Eigen::Dynamic>;\n\tusing RealVector = typename Eigen::Matrix<RealScalar, Eigen::Dynamic, 1>;\n\n\tusing StorageIndex = uint32_t;\n\n\tenum {\n\t\tColsAtCompileTime = Eigen::Dynamic,\n\t\tMaxColsAtCompileTime = Eigen::Dynamic,\n\t\tIsRowMajor = false\n\t};\n\nprivate:\n\tuint32_t n_;\n\n\tconst Machine& qs_;\n\tconst Hamiltonian& ham_;\n\t\n\tEnergy<Scalar, Hamiltonian> energy_;\n\n\tRealScalar shift_;\n\t\n\tMatrix deltas_;\n\tVector deltaMean_;\n\n\tVector energyGrad_;\n\tVector weights_;\n\npublic:\n\t//! \\param qs Machine that describes quantum states\n\t//! \\param ham Hamiltonian for SR\n\tSRMat(const Machine& qs, const Hamiltonian& ham)\n\t  : n_{qs.getN()}, qs_(qs), ham_(ham), energy_(ham)\n\t{\n\t}\n\n\tEigen::Index rows() const { return qs_.getDim(); }\n\tEigen::Index cols() const { return qs_.getDim(); }\n\n\ttemplate<typename Rhs>\n\tEigen::Product<SRMat<Machine, Hamiltonian>, Rhs, Eigen::AliasFreeProduct> \n\t\t\toperator*(const Eigen::MatrixBase<Rhs>& x) const {\n\t  return Eigen::Product<SRMat<Machine, Hamiltonian>, Rhs, Eigen::AliasFreeProduct>(*this, x.derived());\n\t}\n\n\t//! \\param rs Sampling results obtained from samplers.\n\ttemplate<class SamplingResult>\n\tvoid constructFromSamples(SamplingResult&& sr)\n\t{\n\t\tweights_.resize(0);\n\t\tint nsmp = sr.size();\n\n\t\tconstructDelta(qs_, sr, deltas_);\n\t\tconstructObs(qs_, sr, energy_);\n\n\t\tdeltaMean_ = deltas_.colwise().mean();\n\t\tdeltas_ = deltas_.rowwise() - deltaMean_.transpose();\n\t\t\n\t\tenergyGrad_ =  deltas_.adjoint() * energy_.elocs();\n\t\tenergyGrad_ /= nsmp;\n\t}\n\n\ttemplate<class SamplingResult>\n\tvoid constructFromWeightSamples(const Eigen::Ref<const RealVector>& weights, SamplingResult&& sr)\n\t{\n\t\tweights_ = weights;\n\n\t\tconstructDelta(qs_, sr, deltas_);\n\t\tconstructObsWeights(qs_, std::forward<SamplingResult>(sr), weights, energy_);\n\n\t\tdeltaMean_ = weights.transpose()*deltas_;\n\t\tdeltas_ = deltas_.rowwise() - deltaMean_.transpose();\n\t\t\n\t\tenergyGrad_ =  deltas_.adjoint() * weights.asDiagonal()\n\t\t\t* energy_.elocs();\n\t}\n\n\n\tvoid setShift(RealScalar shift)\n\t{\n\t\tshift_ = shift;\n\t}\n\n\tRealScalar getShift() const\n\t{\n\t\treturn shift_;\n\t}\n\n\t//! return \\f$\\langle \\nabla_{\\theta} \\psi_\\theta(\\sigma) \\rangle\\f$ \n\tconst Vector& oloc() const&\n\t{\n\t\treturn deltaMean_;\n\t}\n\n\tVector oloc() &&\n\t{\n\t\treturn deltaMean_;\n\t}\n\n\tMatrix corrMat() \n\t{\n\t\tint nsmp = deltas_.rows();\n\t\tif(weights_.size() == 0)\n\t\t\treturn (deltas_.adjoint() * deltas_)/nsmp;\n\t\telse\n\t\t\treturn (deltas_.adjoint() * weights_.asDiagonal() * deltas_);\n\t}\n\n\tRealScalar eloc() const\n\t{\n\t\treturn std::real(energy_.eloc());\n\t}\n\n\tScalar elocVar() const\n\t{\n\t\treturn std::real(energy_.elocVar());\n\t}\n\t\n\tconst Vector& energyGrad() const&\n\t{\n\t\treturn energyGrad_;\n\t}\n\tVector energyGrad() &&\n\t{\n\t\treturn energyGrad_;\n\t}\n\n\tVector apply(const Vector& rhs) const\n\t{\n\t\tassert(rhs.size() == qs_.getDim());\n\t\tVector r = deltas_*rhs;\n\n\t\tVector res;\n\t\t\n\t\tif(weights_.size() == 0)\n\t\t{\n\t\t\tr /= r.rows();\n\t\t\tres = deltas_.adjoint()*r;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tr.array() *= weights_.array();\n\t\t\tres = deltas_.adjoint() * r;\n\t\t}\n\n\t\treturn res + Scalar(shift_)*rhs;\n\t}\n\n\t/*! \\brief Use conjugate gradient solover to solve the optimizing vector.\n\t *\n\t * We solve \\f$ (S + \\epsilon \\mathbb{1})v = f \\f$ where \\f$ f \\f$ is the gradient of the energy expectation values. \n\t * \\param shift \\f$ \\epsilon \\f$ that controls regularization\n\t * \\param tol tolerance for CG solver\n\t */\n\tVector solveCG(RealScalar shift, RealScalar tol = 1e-4)\n\t{\n\t\tsetShift(shift);\n\t\tEigen::ConjugateGradient<\n\t\t\tSRMat<Machine, Hamiltonian>,\n\t\t\tEigen::Lower|Eigen::Upper,\n\t\t\tEigen::IdentityPreconditioner> cg;\n\t\tcg.compute(*this);\n\t\tcg.setTolerance(tol);\n\t\treturn cg.solve(energyGrad_);\n\t\n\t}\n\n\t/**\n\t * Solve S^{-1}vec using conjugate gradient method\n\t */\n\tVector solveCG(const VectorConstRef& vec, double shift, double tol = 1e-4)\n\t{\n\t\tsetShift(shift);\n\t\tEigen::ConjugateGradient<\n\t\t\tSRMat<Machine, Hamiltonian>,\n\t\t\tEigen::Lower|Eigen::Upper,\n\t\t\tEigen::IdentityPreconditioner> cg;\n\t\tcg.compute(*this);\n\t\tcg.setTolerance(tol);\n\t\treturn cg.solve(vec);\n\t}\n\n\n\t/*! \\brief Solve the optimizing vector by solving the linear equation exactly..\n\t *\n\t * We solve \\f$ (S + \\epsilon \\mathbb{1})v = f \\f$ where \\f$ f \\f$ is the gradient of the energy expectation values. \n\t * \\param shift \\f$ \\epsilon \\f$ that controls regularization\n\t */\n\tVector solveExact(RealScalar shift)\n\t{\n\t\tMatrix mat = corrMat();\n\t\tmat += shift*Matrix::Identity(mat.rows(),mat.cols());\n\t\tEigen::LLT<Matrix> llt{mat};\n\t\treturn llt.solve(energyGrad_);\n\t}\n\n};\n} //namespace yannq\n\n\nnamespace Eigen {\nnamespace internal {\n\ttemplate<typename Rhs, typename Machine, typename Hamiltonian>\n\tstruct generic_product_impl<yannq::SRMat<Machine, Hamiltonian>, Rhs, SparseShape, DenseShape, GemvProduct> // GEMV stands for matrix-vector\n\t: generic_product_impl_base<yannq::SRMat<Machine, Hamiltonian>, Rhs, generic_product_impl<yannq::SRMat<Machine, Hamiltonian>, Rhs> >\n\t{\n\t\ttypedef typename Product<yannq::SRMat<Machine, Hamiltonian>, Rhs>::Scalar Scalar;\n\t\ttemplate<typename Dest>\n\t\tstatic void scaleAndAddTo(Dest& dst, const yannq::SRMat<Machine, Hamiltonian>& lhs, const Rhs& rhs, const Scalar& alpha)\n\t\t{\n\t\t\t// This method should implement \"dst += alpha * lhs * rhs\" inplace,\n\t\t\t// however, for iterative solvers, alpha is always equal to 1, so let's not bother about it.\n\t\t\tassert(alpha==Scalar(1) && \"scaling is not implemented\");\n\t\t\tEIGEN_ONLY_USED_FOR_DEBUG(alpha);\n\n\t\t\tdst += lhs.apply(rhs);\n\t\t}\n\t};\n} //namespace internal\n} //namespace Eigen\n\n", "meta": {"hexsha": "fcb2af36e9fbc3010949d35ecbaf2a91c66f9b99", "size": 6668, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Yannq/GroundState/SRMat.hpp", "max_stars_repo_name": "cecri/yannq", "max_stars_repo_head_hexsha": "b78c1f86a255059f06b34dd5e538449e7261d0ee", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Yannq/GroundState/SRMat.hpp", "max_issues_repo_name": "cecri/yannq", "max_issues_repo_head_hexsha": "b78c1f86a255059f06b34dd5e538449e7261d0ee", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Yannq/GroundState/SRMat.hpp", "max_forks_repo_name": "cecri/yannq", "max_forks_repo_head_hexsha": "b78c1f86a255059f06b34dd5e538449e7261d0ee", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2575757576, "max_line_length": 140, "alphanum_fraction": 0.7041091782, "num_tokens": 1846, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.46537429224439186}}
{"text": "#include <boost\\math\\special_functions.hpp>\n\n#include \"common.h\"\n\n#include \"cusolverOperations.h\"\n\nnamespace matCUDA\n{\n\ttemplate< typename TElement>\n\tcusolverStatus_t cusolverOperations<TElement>::ls( Array<TElement> *A, Array<TElement> *x, Array<TElement> *C )\n\t{\n\t\tcusolverDnHandle_t handle;\n\t\tCUSOLVER_CALL( cusolverDnCreate(&handle) );\n\n\t\tTElement *d_A, *Workspace, *d_C;\n\t\tint INFOh = 2;\n\n\t\tCUDA_CALL( cudaMalloc(&d_A, A->getDim(0) * A->getDim(1) * sizeof(TElement)) );\n\t\tCUDA_CALL( cudaMalloc(&d_C, C->getDim(0) * C->getDim(1) * sizeof(TElement)) );\n\n\t\tCUDA_CALL( cudaMemcpy(d_A, A->data(), A->getDim(0) * A->getDim(1) * sizeof(TElement), cudaMemcpyHostToDevice) );\n\t\tCUDA_CALL( cudaMemcpy(d_C, C->data(), C->getDim(0) * C->getDim(1) * sizeof(TElement), cudaMemcpyHostToDevice) );\n\n\t\tint Lwork = 0;\n\t\tCUSOLVER_CALL( cusolverDnTgetrf_bufferSize(&handle, A->getDim(0), A->getDim(1), d_A, A->getDim(0), &Lwork) );\n\n\t\tCUDA_CALL( cudaMalloc( &Workspace, Lwork * sizeof(TElement) ) );\n\n\t\tint *devIpiv, *devInfo;\n\t\tsize_t size_pivot = std::min(C->getDim(0),C->getDim(1));\n\t\t\n\t\tCUDA_CALL( cudaMalloc( &devIpiv, size_pivot * sizeof(int) ) );\n\t\tCUDA_CALL( cudaMalloc( &devInfo, sizeof(int) ) );\t\t\n\t\t\n\t\t/////***** performance test *****/////\n\t\t//CUDA_CALL( cudaDeviceSynchronize() );\n\t\t//tic();\t\t\n\t\t//for( int i = 0; i < 10; i++ ) {\n\n\t\tCUSOLVER_CALL( cusolverDnTgetrf( &handle, A->getDim(0), A->getDim(1), d_A, A->getDim(0), Workspace, devIpiv, devInfo ) );\n\t\tCUDA_CALL( cudaDeviceSynchronize() );\n\n\t\t// copy from GPU\n\t\tCUDA_CALL( cudaMemcpy( &INFOh, devInfo, sizeof( int ), cudaMemcpyDeviceToHost ) );\n\n\t\tif( INFOh > 0 )\n\t\t{\n\t\t\tprintf(\"Factorization Failed: Matrix is singular\\n\");\n\t\t\treturn CUSOLVER_STATUS_EXECUTION_FAILED;\n\t\t}\n\n\t\tCUSOLVER_CALL( cusolverDnTgetrs( &handle, CUBLAS_OP_N, std::min(A->getDim(0),A->getDim(1)), C->getDim(1), d_A, A->getDim(0), devIpiv, d_C, C->getDim(0), devInfo ) );\n\n\t\t//}\n\t\t//CUDA_CALL( cudaDeviceSynchronize() );\n\t\t//toc();\n\t\t////***** end of performance test *****/////\n\n\t\tCUDA_CALL( cudaDeviceSynchronize() );\n\n\t\t// copy from GPU\n\t\tINFOh = 2;\n\t\tCUDA_CALL( cudaMemcpy( &INFOh, devInfo, sizeof( int ), cudaMemcpyDeviceToHost ) );\n\n\t\tif( INFOh > 0 )\n\t\t{\n\t\t\tprintf(\"Inversion Failed: Matrix is singular\\n\");\n\t\t\treturn CUSOLVER_STATUS_EXECUTION_FAILED;\n\t\t}\n\t\n\t\tCUDA_CALL( cudaMemcpy( C->data(), d_C, C->getNElements()*sizeof( TElement ), cudaMemcpyDeviceToHost ) );\n\t\tfor( int i = 0; i< x->GetDescriptor().GetDim( 0 ); i++ ) {\n\t\t\tfor( int j = 0; j < x->GetDescriptor().GetDim( 1 ); j++ )\n\t\t\t\t(*x)( i, j ) = (*C)( i, j );\n\t\t}\n\n\t\t// free memory\n\t\tCUDA_CALL( cudaFree( d_A ) );\n\t\tCUDA_CALL( cudaFree( d_C ) );\n\t\tCUDA_CALL( cudaFree( Workspace ) );\n\t\tCUDA_CALL( cudaFree( devIpiv ) );\n\t\tCUDA_CALL( cudaFree( devInfo ) );\n\n\t\t// Destroy the handle\n\t\tCUSOLVER_CALL( cusolverDnDestroy(handle) );\n\n\t\treturn CUSOLVER_STATUS_SUCCESS;\n\t}\n\n\ttemplate cusolverStatus_t cusolverOperations<int>::ls( Array<int> *A, Array<int> *x, Array<int> *C );\n\ttemplate cusolverStatus_t cusolverOperations<float>::ls( Array<float> *A, Array<float> *x, Array<float> *C );\n\ttemplate cusolverStatus_t cusolverOperations<double>::ls( Array<double> *A, Array<double> *x, Array<double> *C );\n\ttemplate cusolverStatus_t cusolverOperations<ComplexFloat>::ls( Array<ComplexFloat> *A, Array<ComplexFloat> *x, Array<ComplexFloat> *C );\n\ttemplate cusolverStatus_t cusolverOperations<ComplexDouble>::ls( Array<ComplexDouble> *A, Array<ComplexDouble> *x, Array<ComplexDouble> *C );\n\n\ttemplate< typename TElement>\n\tcusolverStatus_t cusolverOperations<TElement>::invert( Array<TElement> *result, Array<TElement> *data )\n\t{\n\t\tcusolverDnHandle_t handle;\n\t\tCUSOLVER_CALL( cusolverDnCreate(&handle) );\n\n\t\tsize_t M = data->getDim(0);\n\t\tsize_t N = data->getDim(1);\n\t\tsize_t minMN = std::min(M,N);\n\n\t\tTElement *d_A, *Workspace, *d_B;\n\t\tint INFOh = 2;\n\n\t\tCUDA_CALL( cudaMalloc(&d_A, M * N * sizeof(TElement)) );\n\t\tCUDA_CALL( cudaMalloc(&d_B, M * N * sizeof(TElement)) );\n\n\t\tCUDA_CALL( cudaMemcpy(d_A, data->data(), M * N * sizeof(TElement), cudaMemcpyHostToDevice) );\n\t\tcuda_eye<TElement>( d_B, minMN );\n\n\t\tint Lwork = 0;\n\t\tCUSOLVER_CALL( cusolverDnTgetrf_bufferSize(&handle, M, N, d_A, M, &Lwork) );\n\n\t\tCUDA_CALL( cudaMalloc( &Workspace, Lwork * sizeof(TElement) ) );\n\n\t\tint *devIpiv, *devInfo;\n\t\tsize_t size_pivot = std::min(data->getDim(0),data->getDim(1));\n\t\t\n\t\tCUDA_CALL( cudaMalloc( &devIpiv, size_pivot * sizeof(int) ) );\n\t\tCUDA_CALL( cudaMalloc( &devInfo, sizeof(int) ) );\t\t\n\t\t\n\t\t/////***** performance test *****/////\n\t\t//CUDA_CALL( cudaDeviceSynchronize() );\n\t\t//tic();\t\t\n\t\t//for( int i = 0; i < 10; i++ ) {\n\n\t\tCUSOLVER_CALL( cusolverDnTgetrf( &handle, M, N, d_A, M, Workspace, devIpiv, devInfo ) );\n\t\tCUDA_CALL( cudaDeviceSynchronize() );\n\n\t\t// copy from GPU\n\t\tCUDA_CALL( cudaMemcpy( &INFOh, devInfo, sizeof( int ), cudaMemcpyDeviceToHost ) );\n\n\t\tif( INFOh > 0 )\n\t\t{\n\t\t\tprintf(\"Factorization Failed: Matrix is singular\\n\");\n\t\t\treturn CUSOLVER_STATUS_EXECUTION_FAILED;\n\t\t}\n\n\t\tCUSOLVER_CALL( cusolverDnTgetrs( &handle, CUBLAS_OP_N, data->getDim(0), data->getDim(1), d_A, data->getDim(0), devIpiv, d_B, data->getDim(0), devInfo ) );\n\n\t\t//}\n\t\t//CUDA_CALL( cudaDeviceSynchronize() );\n\t\t//toc();\n\t\t////***** end of performance test *****/////\n\n\t\tCUDA_CALL( cudaDeviceSynchronize() );\n\n\t\t// copy from GPU\n\t\tINFOh = 2;\n\t\tCUDA_CALL( cudaMemcpy( &INFOh, devInfo, sizeof( int ), cudaMemcpyDeviceToHost ) );\n\n\t\tif( INFOh > 0 )\n\t\t{\n\t\t\tprintf(\"Inversion Failed: Matrix is singular\\n\");\n\t\t\treturn CUSOLVER_STATUS_EXECUTION_FAILED;\n\t\t}\n\t\n\t\tCUDA_CALL( cudaMemcpy( result->data(), d_B, result->getNElements()*sizeof( TElement ), cudaMemcpyDeviceToHost ) );\n\n\t\t// free memory\n\t\tCUDA_CALL( cudaFree( d_A ) );\n\t\tCUDA_CALL( cudaFree( d_B ) );\n\t\tCUDA_CALL( cudaFree( Workspace ) );\n\t\tCUDA_CALL( cudaFree( devIpiv ) );\n\t\tCUDA_CALL( cudaFree( devInfo ) );\n\n\t\t// Destroy the handle\n\t\tCUSOLVER_CALL( cusolverDnDestroy(handle) );\n\n\t\treturn CUSOLVER_STATUS_SUCCESS;\n\t}\n\n\ttemplate cusolverStatus_t cusolverOperations<int>::invert( Array<int> *result, Array<int> *data );\n\ttemplate cusolverStatus_t cusolverOperations<float>::invert( Array<float> *result, Array<float> *data );\n\ttemplate cusolverStatus_t cusolverOperations<double>::invert( Array<double> *result, Array<double> *data );\n\ttemplate cusolverStatus_t cusolverOperations<ComplexFloat>::invert( Array<ComplexFloat> *result, Array<ComplexFloat> *data );\n\ttemplate cusolverStatus_t cusolverOperations<ComplexDouble>::invert( Array<ComplexDouble> *result, Array<ComplexDouble> *data );\n\t\t\n\ttemplate< typename TElement>\n\tcusolverStatus_t cusolverOperations<TElement>::invert_zerocopy( Array<TElement> *result, Array<TElement> *data )\n\t{\n\t\tcusolverDnHandle_t handle;\n\t\tCUSOLVER_CALL( cusolverDnCreate(&handle) );\n\n\t\tsize_t M = data->getDim(0);\n\t\tsize_t N = data->getDim(1);\n\t\tsize_t minMN = std::min(M,N);\n\n\t\tTElement *d_A, *Workspace, *d_B;\n\n\t\tCUDA_CALL( cudaMalloc(&d_A, M * N * sizeof(TElement)) );\n\n\t\t// pass host pointer to device\n\t\tCUDA_CALL( cudaHostGetDevicePointer( &d_B, result->data(), 0 ) );\n\n\t\tCUDA_CALL( cudaMemcpy(d_A, data->data(), M * N * sizeof(TElement), cudaMemcpyHostToDevice) );\n\t\tcuda_eye<TElement>( d_B, minMN );\n\n\t\tint Lwork = 0;\n\t\tCUSOLVER_CALL( cusolverDnTgetrf_bufferSize(&handle, M, N, d_A, M, &Lwork) );\n\n\t\tCUDA_CALL( cudaMalloc( &Workspace, Lwork * sizeof(TElement) ) );\n\n\t\tint *devIpiv, *devInfo;\n\t\tsize_t size_pivot = std::min(data->getDim(0),data->getDim(1));\n\t\t\n\t\tCUDA_CALL( cudaMalloc( &devIpiv, size_pivot * sizeof(int) ) );\n\t\tCUDA_CALL( cudaMalloc( &devInfo, sizeof(int) ) );\n\n\t\tCUSOLVER_CALL( cusolverDnTgetrf( &handle, M, N, d_A, M, Workspace, devIpiv, devInfo ) );\n\t\tCUDA_CALL( cudaDeviceSynchronize() );\n\n\t\t// copy from GPU\n\t\tint INFOh = 2;\n\t\tCUDA_CALL( cudaMemcpy( &INFOh, devInfo, sizeof( int ), cudaMemcpyDeviceToHost ) );\n\n\t\tif( INFOh > 0 )\n\t\t{\n\t\t\tprintf(\"Factorization Failed: Matrix is singular\\n\");\n\t\t\treturn CUSOLVER_STATUS_EXECUTION_FAILED;\n\t\t}\n\n\t\tCUSOLVER_CALL( cusolverDnTgetrs( &handle, CUBLAS_OP_N, data->getDim(0), data->getDim(1), d_A, data->getDim(0), devIpiv, d_B, data->getDim(0), devInfo ) );\n\t\tCUDA_CALL( cudaDeviceSynchronize() );\n\n\t\t// copy from GPU\n\t\tINFOh = 2;\n\t\tCUDA_CALL( cudaMemcpy( &INFOh, devInfo, sizeof( int ), cudaMemcpyDeviceToHost ) );\n\n\t\tif( INFOh > 0 )\n\t\t{\n\t\t\tprintf(\"Inversion Failed: Matrix is singular\\n\");\n\t\t\treturn CUSOLVER_STATUS_EXECUTION_FAILED;\n\t\t}\n\t\n\t\t// free memory\n\t\tCUDA_CALL( cudaFree( d_A ) );\n\t\tCUDA_CALL( cudaFree( Workspace ) );\n\t\tCUDA_CALL( cudaFree( devIpiv ) );\n\t\tCUDA_CALL( cudaFree( devInfo ) );\n\n\t\t// Destroy the handle\n\t\tCUSOLVER_CALL( cusolverDnDestroy(handle) );\n\n\t\treturn CUSOLVER_STATUS_SUCCESS;\n\t}\n\n\ttemplate cusolverStatus_t cusolverOperations<int>::invert_zerocopy( Array<int> *result, Array<int> *data );\n\ttemplate cusolverStatus_t cusolverOperations<float>::invert_zerocopy( Array<float> *result, Array<float> *data );\n\ttemplate cusolverStatus_t cusolverOperations<double>::invert_zerocopy( Array<double> *result, Array<double> *data );\n\ttemplate cusolverStatus_t cusolverOperations<ComplexFloat>::invert_zerocopy( Array<ComplexFloat> *result, Array<ComplexFloat> *data );\n\ttemplate cusolverStatus_t cusolverOperations<ComplexDouble>::invert_zerocopy( Array<ComplexDouble> *result, Array<ComplexDouble> *data );\n\t\t\n\ttemplate< typename TElement>\n\tcusolverStatus_t cusolverOperations<TElement>::lu( Array<TElement> *A, Array<TElement> *lu, Array<TElement> *Pivot )\n\t{\n\t\tcusolverDnHandle_t handle;\n\t\tCUSOLVER_CALL( cusolverDnCreate(&handle) );\n\n\t\tsize_t M = A->getDim(0);\n\t\tsize_t N = A->getDim(1);\n\t\tsize_t minMN = std::min(M,N);\n\n\t\tTElement *d_A, *Workspace;\n\n\t\tCUDA_CALL( cudaMalloc(&d_A, M * N * sizeof(TElement)) );\n\t\tCUDA_CALL( cudaMemcpy(d_A, A->data(), M * N * sizeof(TElement), cudaMemcpyHostToDevice) );\n\n\t\tint Lwork = 0;\n\t\tCUSOLVER_CALL( cusolverDnTgetrf_bufferSize(&handle, M, N, d_A, M, &Lwork) );\n\n\t\tCUDA_CALL( cudaMalloc( &Workspace, Lwork * sizeof(TElement) ) );\n\n\t\tint *devIpiv, *devInfo;\n\t\tsize_t size_pivot = std::min(A->getDim(0),A->getDim(1));\n\t\t\n\t\tCUDA_CALL( cudaMalloc( &devIpiv, size_pivot * sizeof(int) ) );\n\t\tCUDA_CALL( cudaMalloc( &devInfo, sizeof(int) ) );\n\n\t\tCUSOLVER_CALL( cusolverDnTgetrf( &handle, M, N, d_A, M, Workspace, devIpiv, devInfo ) );\n\t\tCUDA_CALL( cudaDeviceSynchronize() );\n\n\t\t// copy from GPU\n\t\tint INFOh = 2;\n\t\tCUDA_CALL( cudaMemcpy( &INFOh, devInfo, sizeof( int ), cudaMemcpyDeviceToHost ) );\n\n\t\tif( INFOh > 0 )\n\t\t{\n\t\t\tprintf(\"Factorization Failed: Matrix is singular\\n\");\n\t\t\treturn CUSOLVER_STATUS_EXECUTION_FAILED;\n\t\t}\n\t\n\t\tArray<int> pivotVector( size_pivot );\n\t\tCUDA_CALL( cudaMemcpy( lu->data(), d_A, lu->getNElements()*sizeof( TElement ), cudaMemcpyDeviceToHost ) );\n\t\tCUDA_CALL( cudaMemcpy( pivotVector.data(), devIpiv, size_pivot*sizeof( int ), cudaMemcpyDeviceToHost ) );\n\n\t\tfrom_permutation_vector_to_permutation_matrix( Pivot, &pivotVector );\n\n\t\t// free memory\n\t\tCUDA_CALL( cudaFree( d_A ) );\n\t\tCUDA_CALL( cudaFree( Workspace ) );\n\t\tCUDA_CALL( cudaFree( devIpiv ) );\n\t\tCUDA_CALL( cudaFree( devInfo ) );\n\n\t\t// Destroy the handle\n\t\tCUSOLVER_CALL( cusolverDnDestroy(handle) );\n\n\t\treturn CUSOLVER_STATUS_SUCCESS;\n\t}\n\n\ttemplate cusolverStatus_t cusolverOperations<int>::lu( Array<int> *A, Array<int> *lu, Array<int> *Pivot );\n\ttemplate cusolverStatus_t cusolverOperations<float>::lu( Array<float> *A, Array<float> *lu, Array<float> *Pivot );\n\ttemplate cusolverStatus_t cusolverOperations<double>::lu( Array<double> *A, Array<double> *lu, Array<double> *Pivot );\n\ttemplate cusolverStatus_t cusolverOperations<ComplexFloat>::lu( Array<ComplexFloat> *A, Array<ComplexFloat> *lu, Array<ComplexFloat> *Pivot );\n\ttemplate cusolverStatus_t cusolverOperations<ComplexDouble>::lu( Array<ComplexDouble> *A, Array<ComplexDouble> *lu, Array<ComplexDouble> *Pivot );\n\n\ttemplate< typename TElement>\n\tcusolverStatus_t cusolverOperations<TElement>::lu( Array<TElement> *A, Array<TElement> *lu )\n\t{\n\t\tcusolverDnHandle_t handle;\n\t\tCUSOLVER_CALL( cusolverDnCreate(&handle) );\n\n\t\tsize_t M = A->getDim(0);\n\t\tsize_t N = A->getDim(1);\n\t\tsize_t minMN = std::min(M,N);\n\n\t\tTElement *d_A, *Workspace;\n\n\t\tCUDA_CALL( cudaMalloc(&d_A, M * N * sizeof(TElement)) );\n\t\tCUDA_CALL( cudaMemcpy(d_A, A->data(), M * N * sizeof(TElement), cudaMemcpyHostToDevice) );\n\n\t\tint Lwork = 0;\n\t\tCUSOLVER_CALL( cusolverDnTgetrf_bufferSize(&handle, M, N, d_A, M, &Lwork) );\n\n\t\tCUDA_CALL( cudaMalloc( &Workspace, Lwork * sizeof(TElement) ) );\n\n\t\tint *devIpiv, *devInfo;\n\t\tsize_t size_pivot = std::min(A->getDim(0),A->getDim(1));\n\t\t\n\t\tCUDA_CALL( cudaMalloc( &devIpiv, size_pivot * sizeof(int) ) );\n\t\tCUDA_CALL( cudaMalloc( &devInfo, sizeof(int) ) );\n\t\t\n\t\t/////***** performance test *****/////\n\t\t//CUDA_CALL( cudaDeviceSynchronize() );\n\t\t//tic();\t\t\n\t\t//for( int i = 0; i < 10; i++ ) {\n\n\t\tCUSOLVER_CALL( cusolverDnTgetrf( &handle, M, N, d_A, M, Workspace, devIpiv, devInfo ) );\n\n\t\t//}\n\t\t//CUDA_CALL( cudaDeviceSynchronize() );\n\t\t//toc();\n\t\t////***** end of performance test *****/////\n\n\t\tCUDA_CALL( cudaDeviceSynchronize() );\n\n\t\t// copy from GPU\n\t\tint INFOh = 2;\n\t\tCUDA_CALL( cudaMemcpy( &INFOh, devInfo, sizeof( int ), cudaMemcpyDeviceToHost ) );\n\n\t\tif( INFOh > 0 )\n\t\t{\n\t\t\tprintf(\"Factorization Failed: Matrix is singular\\n\");\n\t\t\treturn CUSOLVER_STATUS_EXECUTION_FAILED;\n\t\t}\n\t\n\t\tCUDA_CALL( cudaMemcpy( lu->data(), d_A, lu->getNElements()*sizeof( TElement ), cudaMemcpyDeviceToHost ) );\n\n\t\t// free memory\n\t\tCUDA_CALL( cudaFree( d_A ) );\n\t\tCUDA_CALL( cudaFree( Workspace ) );\n\t\tCUDA_CALL( cudaFree( devIpiv ) );\n\t\tCUDA_CALL( cudaFree( devInfo ) );\n\n\t\t// Destroy the handle\n\t\tCUSOLVER_CALL( cusolverDnDestroy(handle) );\n\n\t\treturn CUSOLVER_STATUS_SUCCESS;\n\t}\n\n\ttemplate cusolverStatus_t cusolverOperations<int>::lu( Array<int> *A, Array<int> *lu );\n\ttemplate cusolverStatus_t cusolverOperations<float>::lu( Array<float> *A, Array<float> *lu );\n\ttemplate cusolverStatus_t cusolverOperations<double>::lu( Array<double> *A, Array<double> *lu );\n\ttemplate cusolverStatus_t cusolverOperations<ComplexFloat>::lu( Array<ComplexFloat> *A, Array<ComplexFloat> *lu );\n\ttemplate cusolverStatus_t cusolverOperations<ComplexDouble>::lu( Array<ComplexDouble> *A, Array<ComplexDouble> *lu );\n\n\ttemplate <typename TElement>\n\tcusolverStatus_t cusolverOperations<TElement>::qr( Array<TElement> *A, Array<TElement> *Q, Array<TElement> *R )\n\t{\n\t\tcusolverDnHandle_t handle;\n\t\tCUSOLVER_CALL( cusolverDnCreate(&handle) );\n\n\t\tint M = A->getDim(0);\n\t\tint N = A->getDim(1);\n\t\tint minMN = std::min(M,N);\n\n\t\tTElement *d_A, *h_A, *TAU, *Workspace, *d_Q;\n\t\th_A = A->data();\n\t\tCUDA_CALL( cudaMalloc(&d_A, M * N * sizeof(TElement)) );\n\t\tCUDA_CALL( cudaMemcpy(d_A, h_A, M * N * sizeof(TElement), cudaMemcpyHostToDevice) );\n\n\t\tint Lwork = 0;\n\t\tCUSOLVER_CALL( cusolverDnTgeqrf_bufferSize(&handle, M, N, d_A, M, &Lwork) );\n\t\tCUDA_CALL( cudaMalloc(&TAU, minMN * sizeof(TElement)) );\n\t\tCUDA_CALL(cudaMalloc(&Workspace, Lwork * sizeof(TElement)));\n\n\t\tint *devInfo;\n\t\tCUDA_CALL( cudaMalloc(&devInfo, sizeof(int)) );\n\t\tCUDA_CALL( cudaMemset( (void*)devInfo, 0, 1 ) );\n\t\t\n\t\tCUSOLVER_CALL( cusolverDnTgeqrf(&handle, M, N, d_A, M, TAU, Workspace, Lwork, devInfo) );\n\t\t\n\t\tint devInfo_h = 0;  \n\t\tCUDA_CALL( cudaMemcpy(&devInfo_h, devInfo, sizeof(int), cudaMemcpyDeviceToHost) );\n\t\tif (devInfo_h != 0)\n\t\t\treturn CUSOLVER_STATUS_INTERNAL_ERROR;\n\n\t\t// CALL CUDA FUNCTION\n\t\tCUDA_CALL( cudaMemcpy( R->data(), d_A, R->getNElements()*sizeof( TElement ), cudaMemcpyDeviceToHost ) );\n\t\tfor(int j = 0; j < M; j++)\n\t\t\tfor(int i = j + 1; i < N; i++)\n\t\t\t\t(*R)(i,j) = 0;\n\n\t\t// --- Initializing the output Q matrix (Of course, this step could be done by a kernel function directly on the device)\n\t\t//*Q = eye<TElement> ( std::min(Q->getDim(0),Q->getDim(1)) );\n\t\tCUDA_CALL( cudaMalloc(&d_Q, M*M*sizeof(TElement)) );\n\t\tcuda_eye<TElement>( d_Q, std::min(Q->getDim(0),Q->getDim(1)) );\n\n\t\t// --- CUDA qr execution\n\t\tCUSOLVER_CALL( cusolverDnTormqr(&handle, CUBLAS_SIDE_LEFT, CUBLAS_OP_N, M, N, std::min(M, N), d_A, M, TAU, d_Q, M, Workspace, Lwork, devInfo) );\n\t\t\n\t\t// --- At this point, d_Q contains the elements of Q. Showing this.\n\t\tCUDA_CALL( cudaMemcpy(Q->data(), d_Q, M*M*sizeof(TElement), cudaMemcpyDeviceToHost) );\n\t\tCUDA_CALL( cudaDeviceSynchronize() );\n  \n\t\tCUSOLVER_CALL( cusolverDnDestroy(handle) );\n\n\t\treturn CUSOLVER_STATUS_SUCCESS;\n\t}\n\t\n\ttemplate cusolverStatus_t cusolverOperations<int>::qr( Array<int> *A, Array<int> *Q, Array<int> *R );\n\ttemplate cusolverStatus_t cusolverOperations<float>::qr( Array<float> *A, Array<float> *Q, Array<float> *R );\n\ttemplate cusolverStatus_t cusolverOperations<double>::qr( Array<double> *A, Array<double> *Q, Array<double> *R );\n\ttemplate cusolverStatus_t cusolverOperations<ComplexFloat>::qr( Array<ComplexFloat> *A, Array<ComplexFloat> *Q, Array<ComplexFloat> *R );\n\ttemplate cusolverStatus_t cusolverOperations<ComplexDouble>::qr( Array<ComplexDouble> *A, Array<ComplexDouble> *Q, Array<ComplexDouble> *R );\n\t\n\ttemplate<> cusolverStatus_t cusolverOperations<ComplexFloat>::dpss( Array<ComplexFloat> *eigenvector, index_t N, double NW, index_t degree )\n\t{\n\t\treturn CUSOLVER_STATUS_NOT_INITIALIZED;\n\t}\n\n\ttemplate<> cusolverStatus_t cusolverOperations<ComplexDouble>::dpss( Array<ComplexDouble> *eigenvector, index_t N, double NW, index_t degree )\n\t{\n\t\treturn CUSOLVER_STATUS_NOT_INITIALIZED;\n\t}\n\n\ttemplate <typename TElement>\n\tcusolverStatus_t cusolverOperations<TElement>::dpss( Array<TElement> *eigenvector, index_t N, double NW, index_t degree )\n\t{\n\t\t// define matrix T (NxN) \n\t\tTElement** T = new TElement*[ N ];\n\t\tfor(int i = 0; i < N; ++i)\n\t\t\tT[ i ] = new TElement[ N ];\n\n\t\t// fill in T as function of ( N, W ) \n\t\t// T is a tridiagonal matrix, i. e., it has diagonal, subdiagonal and superdiagonal\n\t\t// the others elements are 0\n\t\tfor (int i = 0; i < N; i++) {\n\t\t\tfor (int j = 0; j < N; j++) {\n\t\t\t\tif( j == i - 1 ) // subdiagonal\n\t\t\t\t\tT[ i ][ j ] = ( (TElement)N - i )*i/2;\n\t\t\t\telse if( j == i ) // diagonal\n\t\t\t\t\tT[ i ][ j ] = pow( (TElement)(N-1)/2 - i, 2 )*boost::math::cos_pi( 2*NW/(TElement)N/boost::math::constants::pi<TElement>() );\n\t\t\t\telse if( j == i + 1 ) // superdiagonal\n\t\t\t\t\tT[ i ][ j ] = ( i + 1 )*( (TElement)N - 1 - i )/2*( j == i + 1 );\n\t\t\t\telse // others elements\n\t\t\t\t\tT[ i ][ j ] = 0;\n\t\t\t}\n\t\t}\n\t\n\t\t// declarations needed\n\t\tcusolverStatus_t statCusolver = CUSOLVER_STATUS_SUCCESS;\n\t\tcusolverSpHandle_t handleCusolver = NULL;\n\t\tcusparseHandle_t handleCusparse = NULL;\n\t\tcusparseMatDescr_t descrA = NULL;\n\t\tint *h_cooRowIndex = NULL, *h_cooColIndex = NULL;\n\t\tTElement *h_cooVal = NULL; \n\t\tint *d_cooRowIndex = NULL, *d_cooColIndex = NULL, *d_csrRowPtr = NULL; \n\t\tTElement *d_cooVal = NULL; \n\t\tint nnz; \n\t\tTElement *h_eigenvector0 = NULL, *d_eigenvector0 = NULL, *d_eigenvector = NULL;\n\t\tint maxite = 1e6; // number of maximum iteration\n\t\tTElement tol = 1; // tolerance\n\t\tTElement mu, *d_mu;\n\t\tTElement max_lambda;\n\n\t\t// define interval of eigenvalues of T\n\t\t// interval is [-max_lambda,max_lambda]\n\t\tmax_lambda = ( N - 1 )*( N + 2 ) + N*( N + 1 )/8 + 0.25;\n\t\n\t\t// amount of nonzero elements of T\n\t\tnnz = 3*N - 2;\n\n\t\t// allocate host memory\n\t\th_cooRowIndex = new int[ nnz*sizeof( int ) ];\n\t\th_cooColIndex = new int[ nnz*sizeof( int ) ];\n\t\th_cooVal = new TElement[ nnz*sizeof( TElement ) ];\n\t\th_eigenvector0 = new TElement[ N*sizeof( TElement ) ];\n\n\t\t// fill in vectors that describe T as a sparse matrix\n\t\tint counter = 0;\n\t\tfor (int i = 0; i < N; i++ ) {\n\t\t\tfor( int j = 0; j < N; j++ ) {\n\t\t\t\tif( T[ i ][ j ] != 0 ) {\n\t\t\t\t\th_cooRowIndex[counter] = i;\n\t\t\t\t\th_cooColIndex[counter] = j;\n\t\t\t\t\th_cooVal[counter++] = T[ i ][ j ];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\n\t\t// fill in initial eigenvector guess  \n\t\tfor( int i = 0; i < N; i++ )\n\t\t\th_eigenvector0[ i ] =  1/( abs( i - N/2 ) + 1 );\n\n\t\t// allocate device memory\n\t\tCUDA_CALL( cudaMalloc((void**)&d_cooRowIndex,nnz*sizeof( int )) ); \n\t\tCUDA_CALL( cudaMalloc((void**)&d_cooColIndex,nnz*sizeof( int )) ); \n\t\tCUDA_CALL( cudaMalloc((void**)&d_cooVal, nnz*sizeof( TElement )) );\n\t\tCUDA_CALL( cudaMalloc((void**)&d_csrRowPtr, (N+1)*sizeof( int )) );\n\t\tCUDA_CALL( cudaMalloc((void**)&d_eigenvector0, N*sizeof( TElement )) );\n\t\tCUDA_CALL( cudaMalloc((void**)&d_eigenvector, N*sizeof( TElement )) );\n\t\tCUDA_CALL( cudaMalloc( &d_mu, sizeof( TElement ) ) );\n\t\tCUDA_CALL( cudaMemset( d_mu, -max_lambda, sizeof( TElement ) ) );\n\n\t\t// copy data to device\n\t\tCUDA_CALL( cudaMemcpy( d_cooRowIndex, h_cooRowIndex, (size_t)(nnz*sizeof( int )), cudaMemcpyHostToDevice ) );\n\t\tCUDA_CALL( cudaMemcpy( d_cooColIndex, h_cooColIndex, (size_t)(nnz*sizeof( int )), cudaMemcpyHostToDevice ) );\n\t\tCUDA_CALL( cudaMemcpy( d_cooVal, h_cooVal, (size_t)(nnz*sizeof( TElement )), cudaMemcpyHostToDevice ) );\n\t\tCUDA_CALL( cudaMemcpy( d_eigenvector0, h_eigenvector0, (size_t)(N*sizeof( TElement )), cudaMemcpyHostToDevice ) );\n\t\tCUDA_CALL( cudaMemcpy( &mu, d_mu, sizeof( TElement ), cudaMemcpyDeviceToHost ) );\n\t\n\t\t// initialize cusparse and cusolver\n\t\tCUSOLVER_CALL( cusolverSpCreate( &handleCusolver ) );\n\t\tCUSPARSE_CALL( cusparseCreate( &handleCusparse ) );\n\n\t\t// create and define cusparse matrix descriptor\n\t\tCUSPARSE_CALL( cusparseCreateMatDescr(&descrA) );\n\t\tCUSPARSE_CALL( cusparseSetMatType(descrA, CUSPARSE_MATRIX_TYPE_GENERAL ) );\n\t\tCUSPARSE_CALL( cusparseSetMatIndexBase(descrA, CUSPARSE_INDEX_BASE_ZERO ) );\n\n\t\t// transform from coordinates (COO) values to compressed row pointers (CSR) values\n\t\tCUSPARSE_CALL( cusparseXcoo2csr( handleCusparse, d_cooRowIndex, nnz, N, d_csrRowPtr, CUSPARSE_INDEX_BASE_ZERO ) );\n\t\n\t\t// call cusolverSp<type>csreigvsi\n\t\tCUSOLVER_CALL( cusolverSpTcsreigvsi( &handleCusolver, N, nnz, &descrA, d_cooVal, d_csrRowPtr, d_cooColIndex, max_lambda, d_eigenvector0, maxite, tol, d_mu, d_eigenvector ) );\n\n\t\tcudaDeviceSynchronize();\n\t\tCUDA_CALL( cudaGetLastError() );\n\n\t\t// copy from device to host\n\t\tCUDA_CALL( cudaMemcpy( &mu, d_mu, (size_t)sizeof( TElement ), cudaMemcpyDeviceToHost ) );\n\t\tCUDA_CALL( cudaMemcpy( eigenvector->data(), d_eigenvector, (size_t)(N*sizeof( TElement )), cudaMemcpyDeviceToHost ) );\n\t\n\t\t// destroy and free stuff\n\t\tCUSPARSE_CALL( cusparseDestroyMatDescr( descrA ) );\n\t\tCUSPARSE_CALL( cusparseDestroy( handleCusparse ) );\n\t\tCUSOLVER_CALL( cusolverSpDestroy( handleCusolver ) );\n\t\tCUDA_CALL( cudaFree( d_cooRowIndex ) );\n\t\tCUDA_CALL( cudaFree( d_cooColIndex ) );\n\t\tCUDA_CALL( cudaFree( d_cooVal ) );\n\t\tCUDA_CALL( cudaFree( d_csrRowPtr ) );\n\t\tCUDA_CALL( cudaFree( d_eigenvector0 ) );\n\t\tCUDA_CALL( cudaFree( d_eigenvector ) );\n\t\tCUDA_CALL( cudaFree( d_mu ) );\n\t\tdelete[] h_eigenvector0;\n\t\tdelete[] h_cooRowIndex;\n\t\tdelete[] h_cooColIndex;\n\t\tdelete[] h_cooVal;\n\n\t\treturn CUSOLVER_STATUS_SUCCESS;\n\t}\n\n\ttemplate cusolverStatus_t cusolverOperations<float>::dpss( Array<float> *eigenvector, index_t N, double NW, index_t degree );\n\ttemplate cusolverStatus_t cusolverOperations<double>::dpss( Array<double> *eigenvector, index_t N, double NW, index_t degree );\n\t\n\ttemplate <typename TElement>\n\tcusolverStatus_t cusolverOperations<TElement>::qr_zerocopy( Array<TElement> *A, Array<TElement> *Q, Array<TElement> *R )\n\t{\n\t\tcusolverDnHandle_t handle;\n\t\tCUSOLVER_CALL( cusolverDnCreate(&handle) );\n\n\t\tint M = A->getDim(0);\n\t\tint N = A->getDim(1);\n\t\tint minMN = std::min(M,N);\n\n\t\tTElement *d_A, *h_A, *TAU, *Workspace, *d_Q, *d_R;\n\t\th_A = A->data();\n\t\tCUDA_CALL( cudaMalloc(&d_A, M * N * sizeof(TElement)) );\n\t\tCUDA_CALL( cudaMemcpy(d_A, h_A, M * N * sizeof(TElement), cudaMemcpyHostToDevice) );\n\n\t\tint Lwork = 0;\n\t\tCUSOLVER_CALL( cusolverDnTgeqrf_bufferSize(&handle, M, N, d_A, M, &Lwork) );\n\t\tCUDA_CALL( cudaMalloc(&TAU, minMN * sizeof(TElement)) );\n\t\tCUDA_CALL(cudaMalloc(&Workspace, Lwork * sizeof(TElement)));\n\n\t\tint *devInfo;\n\t\tCUDA_CALL( cudaMalloc(&devInfo, sizeof(int)) );\n\t\tCUDA_CALL( cudaMemset( (void*)devInfo, 0, 1 ) );\n\n\t\tCUSOLVER_CALL( cusolverDnTgeqrf(&handle, M, N, d_A, M, TAU, Workspace, Lwork, devInfo) );\n\t\t\n\t\tint devInfo_h = 0;  \n\t\tCUDA_CALL( cudaMemcpy(&devInfo_h, devInfo, sizeof(int), cudaMemcpyDeviceToHost) );\n\t\tif (devInfo_h != 0)\n\t\t\treturn CUSOLVER_STATUS_INTERNAL_ERROR;\n\n\t\t// CALL CUDA FUNCTION\n\t\tCUDA_CALL( cudaMemcpy( R->data(), d_A, R->getNElements()*sizeof( TElement ), cudaMemcpyDeviceToHost ) );\n\n\t\t// pass host pointer to device\n\t\tCUDA_CALL( cudaHostGetDevicePointer( &d_R, R->data(), 0 ) );\n\t\tCUDA_CALL( cudaHostGetDevicePointer( &d_Q, Q->data(), 0 ) );\n\n\t\tzeros_under_diag<TElement>( d_R, std::min(R->getDim(0),R->getDim(1)) );\n\t\t//for(int j = 0; j < M; j++)\n\t\t//\tfor(int i = j + 1; i < N; i++)\n\t\t//\t\t(*R)(i,j) = 0;\n\n\t\t// --- Initializing the output Q matrix (Of course, this step could be done by a kernel function directly on the device)\n\t\t//*Q = eye<TElement> ( std::min(Q->getDim(0),Q->getDim(1)) );\n\t\tcuda_eye<TElement>( d_Q, std::min(Q->getDim(0),Q->getDim(1)) );\n\t\tCUDA_CALL( cudaDeviceSynchronize() );\n\n\t\t// --- CUDA qr_zerocopy execution\n\t\tCUSOLVER_CALL( cusolverDnTormqr(&handle, CUBLAS_SIDE_LEFT, CUBLAS_OP_N, M, N, std::min(M, N), d_A, M, TAU, d_Q, M, Workspace, Lwork, devInfo) );\n\t\tCUDA_CALL( cudaDeviceSynchronize() );\n  \n\t\tCUSOLVER_CALL( cusolverDnDestroy(handle) );\n\n\t\treturn CUSOLVER_STATUS_SUCCESS;\n\t}\n\t\n\ttemplate cusolverStatus_t cusolverOperations<int>::qr_zerocopy( Array<int> *A, Array<int> *Q, Array<int> *R );\n\ttemplate cusolverStatus_t cusolverOperations<float>::qr_zerocopy( Array<float> *A, Array<float> *Q, Array<float> *R );\n\ttemplate cusolverStatus_t cusolverOperations<double>::qr_zerocopy( Array<double> *A, Array<double> *Q, Array<double> *R );\n\ttemplate cusolverStatus_t cusolverOperations<ComplexFloat>::qr_zerocopy( Array<ComplexFloat> *A, Array<ComplexFloat> *Q, Array<ComplexFloat> *R );\n\ttemplate cusolverStatus_t cusolverOperations<ComplexDouble>::qr_zerocopy( Array<ComplexDouble> *A, Array<ComplexDouble> *Q, Array<ComplexDouble> *R );// transform permutation vector into permutation matrix\n\t// TODO (or redo) - too slow!!!\n\n\ttemplate <typename TElement>\n\tvoid cusolverOperations<TElement>::from_permutation_vector_to_permutation_matrix( Array<TElement> *pivotMatrix, Array<int> *pivotVector )\n\t{\n\t\t//pivotVector->print();\n\t\t//*pivotMatrix = eye<TElement>(pivotVector->getDim(0));\n\t\t//index_t idx1, idx2;\n\t\t//for( int i = 0; i < pivotVector->GetDescriptor().GetDim(0); i++ ) {\n\t\t//\tif( i + 1 == (*pivotVector)(i) )\n\t\t//\t\tcontinue;\n\t\t//\telse\n\t\t//\t{\n\t\t//\t\tidx1 = i;\n\t\t//\t\tidx2 = (*pivotVector)(i)-1;\n\t\t//\t\t(*pivotMatrix)( idx1, idx1 ) = 0;\n\t\t//\t\t(*pivotMatrix)( idx2, idx2 ) = 0;\n\t\t//\t\t(*pivotMatrix)( idx1, idx2 ) = 1;\n\t\t//\t\t(*pivotMatrix)( idx2, idx1 ) = 1;\n\t\t//\t}\n\t\t//\tpivotMatrix->print();\n\t\t//}\n\t\t//pivotMatrix->print();\n\t\t//\n\t\t//*pivotMatrix = eye<TElement>(pivotVector->getDim(0));\n\n\n\t\t//pivotVector->print();\n\t\t//eye<double>(pivotVector->getDim(0)).print();\n\t\tArray<TElement> pivotAux = eye<TElement>(pivotVector->GetDescriptor().GetDim(0));\n\t\tindex_t idx1, idx2;\n\t\tfor( int i = 0; i < pivotVector->GetDescriptor().GetDim(0); i++ ) {\n\t\t\tidx1 = i;\n\t\t\tidx2 = (*pivotVector)(i)-1;\n\t\t\tpivotAux( idx1, idx1 ) = 0;\n\t\t\tpivotAux( idx2, idx2 ) = 0;\n\t\t\tpivotAux( idx1, idx2 ) = 1;\n\t\t\tpivotAux( idx2, idx1 ) = 1;\n\n\t\t\t(*pivotMatrix) = pivotAux*(*pivotMatrix);\n\t\t\tpivotAux = eye<TElement>(pivotVector->GetDescriptor().GetDim(0));\n\t\t\t//pivotMatrix->print();\n\t\t}\n\t\t//pivotMatrix->print();\n\t}\n\t\t\n\tcusolverStatus_t cusolverOperations<float>::cusolverSpTcsreigvsi( cusolverSpHandle_t *handle, int m, int nnz, cusparseMatDescr_t *descrA, const float *csrValA, const int *csrRowPtrA, const int *csrColIndA, float mu0, const float *x0, int maxite, float tol, float *mu, float *x )\n\t{\n\t\treturn cusolverSpScsreigvsi( *handle, m ,nnz, *descrA, csrValA, csrRowPtrA, csrColIndA, mu0, x0, maxite, tol, mu, x );;\n\t}\n\n\tcusolverStatus_t cusolverOperations<double>::cusolverSpTcsreigvsi( cusolverSpHandle_t *handle, int m, int nnz, cusparseMatDescr_t *descrA, const double *csrValA, const int *csrRowPtrA, const int *csrColIndA, double mu0, const double *x0, int maxite, double tol, double *mu, double *x )\n\t{\n\t\treturn cusolverSpDcsreigvsi( *handle, m ,nnz, *descrA, csrValA, csrRowPtrA, csrColIndA, mu0, x0, maxite, tol, mu, x );\n\t}\n\t\n\tcusolverStatus_t cusolverOperations<ComplexFloat>::cusolverSpTcsreigvsi( cusolverSpHandle_t *handle, int m, int nnz, cusparseMatDescr_t *descrA, const ComplexFloat *csrValA, const int *csrRowPtrA, const int *csrColIndA, ComplexFloat mu0, const ComplexFloat *x0, int maxite, ComplexFloat tol, ComplexFloat *mu, ComplexFloat *x )\n\t{\n\t\tcuFloatComplex mu02 = make_cuFloatComplex( mu0.real(), mu0.imag() );\n\t\treturn cusolverSpCcsreigvsi( *handle, m ,nnz, *descrA, (const cuFloatComplex*)csrValA, csrRowPtrA, csrColIndA, mu02, (const cuFloatComplex*)x0, maxite, tol.real(), (cuFloatComplex*)mu, (cuFloatComplex*)x );\n\t}\n\t\n\tcusolverStatus_t cusolverOperations<ComplexDouble>::cusolverSpTcsreigvsi( cusolverSpHandle_t *handle, int m, int nnz, cusparseMatDescr_t *descrA, const ComplexDouble *csrValA, const int *csrRowPtrA, const int *csrColIndA, ComplexDouble mu0, const ComplexDouble *x0, int maxite, ComplexDouble tol, ComplexDouble *mu, ComplexDouble *x )\n\t{\n\t\tcuDoubleComplex mu02 = make_cuDoubleComplex( mu0.real(), mu0.imag() );\n\t\treturn cusolverSpZcsreigvsi( *handle, m ,nnz, *descrA, (const cuDoubleComplex*)csrValA, csrRowPtrA, csrColIndA, mu02, (const cuDoubleComplex*)x0, maxite, tol.real(), (cuDoubleComplex*)mu, (cuDoubleComplex*)x );\n\t}\n\n\tcusolverStatus_t cusolverOperations<int>::cusolverDnTgeqrf_bufferSize( cusolverDnHandle_t *handle, int m, int n, int *A, int lda, int *Lwork )\n\t{\n\t\treturn CUSOLVER_STATUS_SUCCESS;\n\t}\t\n\n\tcusolverStatus_t cusolverOperations<float>::cusolverDnTgeqrf_bufferSize( cusolverDnHandle_t *handle, int m, int n, float *A, int lda, int *Lwork )\n\t{\n\t\treturn cusolverDnSgeqrf_bufferSize( *handle, m, n, A, lda, Lwork );\n\t}\t\n\n\tcusolverStatus_t cusolverOperations<double>::cusolverDnTgeqrf_bufferSize( cusolverDnHandle_t *handle, int m, int n, double *A, int lda, int *Lwork )\n\t{\n\t\treturn cusolverDnDgeqrf_bufferSize( *handle, m, n, A, lda, Lwork );\n\t}\t\n\n\tcusolverStatus_t cusolverOperations<ComplexFloat>::cusolverDnTgeqrf_bufferSize( cusolverDnHandle_t *handle, int m, int n, ComplexFloat *A, int lda, int *Lwork )\n\t{\n\t\treturn cusolverDnCgeqrf_bufferSize( *handle, m, n, (cuFloatComplex*)A, lda, Lwork );\n\t}\t\n\n\tcusolverStatus_t cusolverOperations<ComplexDouble>::cusolverDnTgeqrf_bufferSize( cusolverDnHandle_t *handle, int m, int n, ComplexDouble *A, int lda, int *Lwork )\n\t{\n\t\treturn cusolverDnZgeqrf_bufferSize( *handle, m, n, (cuDoubleComplex*)A, lda, Lwork );\n\t}\t\n\n\tcusolverStatus_t cusolverOperations<int>::cusolverDnTgeqrf( cusolverDnHandle_t *handle, int m, int n, int *A, int lda, int *TAU, int *Workspace, int Lwork, int *devInfo )\n\t{\n\t\treturn CUSOLVER_STATUS_SUCCESS;\n\t}\t\n\n\tcusolverStatus_t cusolverOperations<float>::cusolverDnTgeqrf( cusolverDnHandle_t *handle, int m, int n, float *A, int lda, float *TAU, float *Workspace, int Lwork, int *devInfo )\n\t{\n\t\treturn cusolverDnSgeqrf( *handle, m, n, A, lda, TAU, Workspace, Lwork, devInfo );\n\t}\t\n\n\tcusolverStatus_t cusolverOperations<double>::cusolverDnTgeqrf( cusolverDnHandle_t *handle, int m, int n, double *A, int lda, double *TAU, double *Workspace, int Lwork, int *devInfo )\n\t{\n\t\treturn cusolverDnDgeqrf( *handle, m, n, A, lda, TAU, Workspace, Lwork, devInfo );\n\t}\t\n\n\tcusolverStatus_t cusolverOperations<ComplexFloat>::cusolverDnTgeqrf( cusolverDnHandle_t *handle, int m, int n, ComplexFloat *A, int lda, ComplexFloat *TAU, ComplexFloat *Workspace, int Lwork, int *devInfo )\n\t{\n\t\treturn cusolverDnCgeqrf( *handle, m, n, (cuFloatComplex*)A, lda, (cuFloatComplex*)TAU, (cuFloatComplex*)Workspace, Lwork, devInfo );\n\t}\t\n\n\tcusolverStatus_t cusolverOperations<ComplexDouble>::cusolverDnTgeqrf( cusolverDnHandle_t *handle, int m, int n, ComplexDouble *A, int lda, ComplexDouble *TAU, ComplexDouble *Workspace, int Lwork, int *devInfo )\n\t{\n\t\treturn cusolverDnZgeqrf( *handle, m, n, (cuDoubleComplex*)A, lda, (cuDoubleComplex*)TAU, (cuDoubleComplex*)Workspace, Lwork, devInfo );\n\t}\t\n\n\tcusolverStatus_t cusolverOperations<int>::cusolverDnTormqr( cusolverDnHandle_t *handle, cublasSideMode_t side, cublasOperation_t trans, int m, int n, int k, const int *A, int lda, const int *tau, int *C, int ldc, int *work, int lwork, int *devInfo )\n\t{\n\t\treturn CUSOLVER_STATUS_SUCCESS;\n\t}\t\n\n\tcusolverStatus_t cusolverOperations<float>::cusolverDnTormqr( cusolverDnHandle_t *handle, cublasSideMode_t side, cublasOperation_t trans, int m, int n, int k, const float *A, int lda, const float *tau, float *C, int ldc, float *work, int lwork, int *devInfo )\n\t{\n\t\treturn cusolverDnSormqr( *handle, side, trans, m, n, k, A, lda, tau, C, ldc, work, lwork, devInfo );\n\t}\t\n\n\tcusolverStatus_t cusolverOperations<double>::cusolverDnTormqr( cusolverDnHandle_t *handle, cublasSideMode_t side, cublasOperation_t trans, int m, int n, int k, const double *A, int lda, const double *tau, double *C, int ldc, double *work, int lwork, int *devInfo )\n\t{\n\t\treturn cusolverDnDormqr( *handle, side, trans, m, n, k, A, lda, tau, C, ldc, work, lwork, devInfo );\n\t}\t\n\n\tcusolverStatus_t cusolverOperations<ComplexFloat>::cusolverDnTormqr( cusolverDnHandle_t *handle, cublasSideMode_t side, cublasOperation_t trans, int m, int n, int k, const ComplexFloat *A, int lda, const ComplexFloat *tau, ComplexFloat *C, int ldc, ComplexFloat *work, int lwork, int *devInfo )\n\t{\n\t\treturn cusolverDnCunmqr( *handle, side, trans, m, n, k, (const cuFloatComplex*)A, lda, (const cuFloatComplex*)tau, (cuFloatComplex*)C, ldc, (cuFloatComplex*)work, lwork, devInfo );\n\t}\t\n\t\n\tcusolverStatus_t cusolverOperations<ComplexDouble>::cusolverDnTormqr( cusolverDnHandle_t *handle, cublasSideMode_t side, cublasOperation_t trans, int m, int n, int k, const ComplexDouble *A, int lda, const ComplexDouble *tau, ComplexDouble *C, int ldc, ComplexDouble *work, int lwork, int *devInfo )\n\t{\n\t\treturn cusolverDnZunmqr( *handle, side, trans, m, n, k, (const cuDoubleComplex*)A, lda, (const cuDoubleComplex*)tau, (cuDoubleComplex*)C, ldc, (cuDoubleComplex*)work, lwork, devInfo );\n\t}\t\n\n\tcusolverStatus_t cusolverOperations<int>::cusolverDnTgetrf_bufferSize( cusolverDnHandle_t *handle, int m, int n, int *A, int lda, int *Lwork )\n\t{\n\t\treturn CUSOLVER_STATUS_SUCCESS;\n\t}\t\n\n\tcusolverStatus_t cusolverOperations<float>::cusolverDnTgetrf_bufferSize( cusolverDnHandle_t *handle, int m, int n, float *A, int lda, int *Lwork )\n\t{\n\t\treturn cusolverDnSgetrf_bufferSize( *handle, m, n, A, lda, Lwork );\n\t}\t\n\n\tcusolverStatus_t cusolverOperations<double>::cusolverDnTgetrf_bufferSize( cusolverDnHandle_t *handle, int m, int n, double *A, int lda, int *Lwork )\n\t{\n\t\treturn cusolverDnDgetrf_bufferSize( *handle, m, n, A, lda, Lwork );\n\t}\t\n\n\tcusolverStatus_t cusolverOperations<ComplexFloat>::cusolverDnTgetrf_bufferSize( cusolverDnHandle_t *handle, int m, int n, ComplexFloat *A, int lda, int *Lwork )\n\t{\n\t\treturn cusolverDnCgetrf_bufferSize( *handle, m, n, (cuFloatComplex*)A, lda, Lwork );\n\t}\t\n\n\tcusolverStatus_t cusolverOperations<ComplexDouble>::cusolverDnTgetrf_bufferSize( cusolverDnHandle_t *handle, int m, int n, ComplexDouble *A, int lda, int *Lwork )\n\t{\n\t\treturn cusolverDnZgetrf_bufferSize( *handle, m, n, (cuDoubleComplex*)A, lda, Lwork );\n\t}\t\n\n\tcusolverStatus_t cusolverOperations<int>::cusolverDnTgetrf( cusolverDnHandle_t *handle, int m, int n, int *A, int lda, int *Workspace, int *devIpiv, int *devInfo )\n\t{\n\t\treturn CUSOLVER_STATUS_SUCCESS;\n\t}\t\n\n\tcusolverStatus_t cusolverOperations<float>::cusolverDnTgetrf( cusolverDnHandle_t *handle, int m, int n, float *A, int lda, float *Workspace, int *devIpiv, int *devInfo )\n\t{\n\t\treturn cusolverDnSgetrf( *handle, m, n, A, lda, Workspace, devIpiv, devInfo );\n\t}\t\n\n\tcusolverStatus_t cusolverOperations<double>::cusolverDnTgetrf( cusolverDnHandle_t *handle, int m, int n, double *A, int lda, double *Workspace, int *devIpiv, int *devInfo )\n\t{\n\t\treturn cusolverDnDgetrf( *handle, m, n, A, lda, Workspace, devIpiv, devInfo );\n\t}\t\n\n\tcusolverStatus_t cusolverOperations<ComplexFloat>::cusolverDnTgetrf( cusolverDnHandle_t *handle, int m, int n, ComplexFloat *A, int lda, ComplexFloat *Workspace, int *devIpiv, int *devInfo )\n\t{\n\t\treturn cusolverDnCgetrf( *handle, m, n, (cuFloatComplex*)A, lda, (cuFloatComplex*)Workspace, devIpiv, devInfo );\n\t}\t\n\n\tcusolverStatus_t cusolverOperations<ComplexDouble>::cusolverDnTgetrf( cusolverDnHandle_t *handle, int m, int n, ComplexDouble *A, int lda, ComplexDouble *Workspace, int *devIpiv, int *devInfo )\n\t{\n\t\treturn cusolverDnZgetrf( *handle, m, n, (cuDoubleComplex*)A, lda, (cuDoubleComplex*)Workspace, devIpiv, devInfo );\n\t}\t\n\n\tcusolverStatus_t cusolverOperations<int>::cusolverDnTgetrs( cusolverDnHandle_t *handle, cublasOperation_t trans, int n, int nrhs, const int *A, int lda, const int *devIpiv, int *B, int ldb, int *devInfo )\n\t{\n\t\treturn CUSOLVER_STATUS_SUCCESS;\n\t}\t\n\n\tcusolverStatus_t cusolverOperations<float>::cusolverDnTgetrs( cusolverDnHandle_t *handle, cublasOperation_t trans, int n, int nrhs, const float *A, int lda, const int *devIpiv, float *B, int ldb, int *devInfo )\n\t{\n\t\treturn cusolverDnSgetrs( *handle, trans, n, nrhs, A, lda, devIpiv, B, ldb, devInfo );\n\t}\t\n\n\tcusolverStatus_t cusolverOperations<double>::cusolverDnTgetrs( cusolverDnHandle_t *handle, cublasOperation_t trans, int n, int nrhs, const double *A, int lda, const int *devIpiv, double *B, int ldb, int *devInfo )\n\t{\n\t\treturn cusolverDnDgetrs( *handle, trans, n, nrhs, A, lda, devIpiv, B, ldb, devInfo );\n\t}\t\n\n\tcusolverStatus_t cusolverOperations<ComplexFloat>::cusolverDnTgetrs( cusolverDnHandle_t *handle, cublasOperation_t trans, int n, int nrhs, const ComplexFloat *A, int lda, const int *devIpiv, ComplexFloat *B, int ldb, int *devInfo )\n\t{\n\t\treturn cusolverDnCgetrs( *handle, trans, n, nrhs, (const cuFloatComplex*)A, lda, devIpiv, (cuFloatComplex*)B, ldb, devInfo );\n\t}\t\n\n\tcusolverStatus_t cusolverOperations<ComplexDouble>::cusolverDnTgetrs( cusolverDnHandle_t *handle, cublasOperation_t trans, int n, int nrhs, const ComplexDouble *A, int lda, const int *devIpiv, ComplexDouble *B, int ldb, int *devInfo )\n\t{\n\t\treturn cusolverDnZgetrs( *handle, trans, n, nrhs, (const cuDoubleComplex*)A, lda, devIpiv, (cuDoubleComplex*)B, ldb, devInfo );\n\t}\t\n}", "meta": {"hexsha": "eca0e01560d03b8be53c68c5f920023a6b18cf95", "size": 37887, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "matCUDA lib/src/cusolverOperations.cpp", "max_stars_repo_name": "leomiquelutti/matCUDA", "max_stars_repo_head_hexsha": "95bd7917289288b0137ce23a952d4ccfd43e0d1d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "matCUDA lib/src/cusolverOperations.cpp", "max_issues_repo_name": "leomiquelutti/matCUDA", "max_issues_repo_head_hexsha": "95bd7917289288b0137ce23a952d4ccfd43e0d1d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "matCUDA lib/src/cusolverOperations.cpp", "max_forks_repo_name": "leomiquelutti/matCUDA", "max_forks_repo_head_hexsha": "95bd7917289288b0137ce23a952d4ccfd43e0d1d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.5482758621, "max_line_length": 335, "alphanum_fraction": 0.7072082772, "num_tokens": 12498, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219505, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4653742873121907}}
{"text": "// dlib dnn practice\n\n#include <dlib/dnn.h>\n#include <iostream>\n#include <dlib/data_io.h>\n\nusing namespace dlib; // conv layer\n\n// define a resnet block layer\ntemplate<int num_filter,\n    template<typename> class BN,\n    int stride,\n    typename SUBNET>\n    using block = BN < con<num_filter, 3, 3, 1, 1,\n    relu<BN<con<num_filter, 3, 3, stride, stride,\n    SUBNET>>>>>;\n\n// define a resnet residual block\ntemplate<\n    template<int, template<typename> class, int, typename> class block,\n    int num_filter,\n    template<typename> class BN,\n    typename SUBNET>\n    using residual = add_prev1<block<num_filter, BN, 1, tag1<SUBNET>>>;\n\n// define downsampling (stride2) residual block\ntemplate<\n    template<int, template<typename> class, int, typename> class block,\n    int num_filter,\n    template<typename> class BN,\n    typename SUBNET>\n    using residual_down = add_prev2 < avg_pool<2, 2, 2, 2,\n    skip1<tag2<block<num_filter, BN, 2, tag1<SUBNET>>>>>>;\n\n// now define 4 different residual blocks\ntemplate <typename SUBNET> using res = relu<residual<block, 8, bn_con, SUBNET>>;\ntemplate <typename SUBNET> using res_a = relu < residual<block, 8, affine, SUBNET>>;\ntemplate <typename  SUBNET> using res_down = relu<residual_down<block, 8, bn_con, SUBNET>>;\ntemplate <typename SUBNET> using resa_down = relu<residual_down<block, 8, affine, SUBNET>>;\n\n// building the net type\nconst unsigned long num_classes = 10;\nusing net_type = loss_multiclass_log < fc<num_classes,\n    avg_pool_everything<res<res<res<res_down<\n    repeat<9, res,\n    res_down<res<\n    input<matrix<unsigned char>>>>>>>>>>>>;\n\n\nint main(int argc, char**argv)\n{\n    // load data\n    std::vector<matrix<unsigned char>> training_images;\n    std::vector<unsigned long> training_labels;\n    std::vector<matrix<unsigned char>> testing_images;\n    std::vector<unsigned long> testing_labels;\n    load_mnist_dataset(\"D:/Develop/DL/projects/resources/datasets/mnist\", training_images, training_labels, testing_images, testing_labels);\n\n    // use smaller ram\n    set_dnn_prefer_smallest_algorithms();\n\n    // create a net\n    net_type net;\n\n    // print layer info\n    std::cout << \"net has \" << net.num_layers << \" layers\\n\";\n    //std::cout << net << \"\\n\";\n\n    // get output for layer 3 ==>  layer<3>(net).get_output()\n\n    // now set trainer\n    dnn_trainer<net_type, adam> trainer(net, adam(0.0005, 0.9, 0.999));\n    trainer.be_verbose();\n    trainer.set_iterations_without_progress_threshold(2000);\n    trainer.set_learning_rate_shrink_factor(0.1);\n    trainer.set_learning_rate(0.001);\n    trainer.set_synchronization_file(\"D:/Develop/DL/projects/digital-image-processing/temp/mnist_res_sync\",\n        std::chrono::seconds(100));\n\n    // set mini batch\n    std::vector<matrix<unsigned char>> mini_batch_samples;\n    std::vector<unsigned long> mini_batch_labels;\n    dlib::rand rnd(time(0));\n\n    while (trainer.get_learning_rate() >= 1e-6)\n    {\n        mini_batch_samples.clear();\n        mini_batch_labels.clear();\n        // make 128 mini batch\n        while (mini_batch_samples.size() < 128)\n        {\n            auto idx = rnd.get_random_32bit_number() % training_images.size();\n            mini_batch_samples.push_back(training_images[idx]);\n            mini_batch_labels.push_back(training_labels[idx]);\n        }\n        // train mini batch\n        trainer.train_one_step(mini_batch_samples, mini_batch_labels);\n        // can also use test_one_step to show test accuracy\n    }\n\n    // train_one_step is multithreaded implementation. So need to use\n    // trainer.get_net to perform synchronization\n    trainer.get_net();\n\n    // save net\n    net.clean();\n    serialize(\"D:/Develop/DL/projects/digital-image-processing/temp/mnist_res_network.dat\") << net;\n\n    // test net: batchnorm will be replaced by affine layer\n    using test_net_type = loss_multiclass_log < fc < num_classes,\n        avg_pool_everything<res_a<res_a<res_a<resa_down<\n        repeat<9, res_a,\n        resa_down<res_a<\n        input<matrix<unsigned char>>>>>>>>>>>>;\n\n    // can assign trained net to test net\n    test_net_type tnet = net;\n    // or deserialize from saved file\n\n    // run training data\n    std::vector<unsigned long> predicted_labels = tnet(training_images);\n    int num_right = 0;\n    int num_wrong = 0;\n    for (size_t i = 0; i < training_images.size(); i++)\n    {\n        if (predicted_labels[i] == training_labels[i])\n        {\n            num_right++;\n        }\n        else\n        {\n            num_wrong++;\n        }\n    }\n    std::cout << \"training num right= \" << num_right << \"\\n\";\n    std::cout << \"training num wrong= \" << num_wrong << \"\\n\";\n    std::cout << \"training accuracy= \" << num_right / double(num_right + num_wrong) << \"\\n\";\n\n    // run test data\n    predicted_labels = tnet(testing_images);\n    num_right = 0;\n    num_wrong = 0;\n    for (size_t i = 0; i < testing_images.size(); ++i)\n    {\n        if (predicted_labels[i] == testing_labels[i])\n        {\n            num_right++;\n        }\n        else\n        {\n            num_wrong++;\n        }\n    }\n    std::cout << \"testing num right= \" << num_right << \"\\n\";\n    std::cout << \"testing num wrong= \" << num_wrong << \"\\n\";\n    std::cout << \"testing accuracy= \" << num_right / double(num_right + num_wrong) << \"\\n\";\n\n\n    std::system(\"pause\");\n    return 0;\n}\n", "meta": {"hexsha": "26cc8a343c73b65fa0760140143ac72e94ef59db", "size": 5301, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp-projects/tiny-apps/dlib-learning/deep-advanced/main.cpp", "max_stars_repo_name": "juxiangwu/image-processing", "max_stars_repo_head_hexsha": "c644ef3386973b2b983c6b6b08f15dc8d52cd39f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2018-09-07T02:29:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-18T08:40:09.000Z", "max_issues_repo_path": "cpp-projects/tiny-apps/dlib-learning/deep-advanced/main.cpp", "max_issues_repo_name": "juxiangwu/image-processing", "max_issues_repo_head_hexsha": "c644ef3386973b2b983c6b6b08f15dc8d52cd39f", "max_issues_repo_licenses": ["Apache-2.0"], "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-projects/tiny-apps/dlib-learning/deep-advanced/main.cpp", "max_forks_repo_name": "juxiangwu/image-processing", "max_forks_repo_head_hexsha": "c644ef3386973b2b983c6b6b08f15dc8d52cd39f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-06-20T00:09:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-15T10:14:36.000Z", "avg_line_length": 32.7222222222, "max_line_length": 140, "alphanum_fraction": 0.6495000943, "num_tokens": 1365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.46537428731219066}}
{"text": "// This is to check whether I can sidestep having to provide a Jacobian in terms of the overparameterized version\n\n#include <ceres/ceres.h>\n#include <ceres/gradient_checker.h>\n#include <Eigen/Core>\n#include <unsupported/Eigen/MatrixFunctions>\n\n#include \"wave/optimization/ceres/local_params/null_SE3_parameterization.hpp\"\n#include \"wave/wave_test.hpp\"\n#include \"wave/utils/math.hpp\"\n#include \"wave/geometry_og/transformation.hpp\"\n\nnamespace {\n\nclass TestPointToPoint : public ceres::SizedCostFunction<3, 12> {\n private:\n    const double *const P1;\n    const double *const P2;\n\n public:\n    virtual ~TestPointToPoint(){};\n    TestPointToPoint(const double *const p1, const double *const p2) : P1(p1), P2(p2) {}\n\n    virtual bool Evaluate(double const *const *parameters, double *residuals, double **jacobians) const {\n        // modelled as P1 = T*P2\n        // r = T*P2 - P1;\n        // parameters in order:\n        // R11 R21 R31 R12 R22 R32 R13 R23 R33 X Y Z\n        double Tp[3] = {parameters[0][0] * this->P2[0] + parameters[0][3] * this->P2[1] + parameters[0][6] * this->P2[2] + parameters[0][9],\n                        parameters[0][1] * this->P2[0] + parameters[0][4] * this->P2[1] + parameters[0][7] * this->P2[2] + parameters[0][10],\n                        parameters[0][2] * this->P2[0] + parameters[0][5] * this->P2[1] + parameters[0][8] * this->P2[2] + parameters[0][11]};\n\n        residuals[0] = Tp[0] - this->P1[0];\n        residuals[1] = Tp[1] - this->P1[1];\n        residuals[2] = Tp[2] - this->P1[2];\n\n        if(jacobians) {\n            Eigen::Matrix<double, 3, 6> local_jacobian;\n            local_jacobian.setZero();\n            local_jacobian.block<3,3>(0,3).setIdentity();\n            local_jacobian(0,1) = Tp[2];\n            local_jacobian(0,2) = -Tp[1];\n            local_jacobian(1,0) = -Tp[2];\n            local_jacobian(1,2) = Tp[0];\n            local_jacobian(2,0) = Tp[1];\n            local_jacobian(2,1) = -Tp[0];\n\n            Eigen::Matrix<double, 6, 12> bogus_inflation;\n            bogus_inflation.setZero();\n            bogus_inflation.block<6,6>(0,0).setIdentity();\n\n            Eigen::Matrix<double, 3, 12> bogus_jacobian = local_jacobian * bogus_inflation;\n\n            Eigen::Map<Eigen::Matrix<double, 3, 12, Eigen::RowMajor>>(jacobians[0], 3, 12) = bogus_jacobian;\n        }\n        return true;\n    }\n};\n\n}\n\nnamespace wave{\n\nTEST(local_jacobians, fake_lift_jacobian) {\n    Vec6 transformation_twist_parameters;\n    transformation_twist_parameters << 0.068924613882066, 0.213225926957886, 0.288748939228676, 0.965590777183138,\n            1.960945901104432, 3.037052911306709;\n    Transformation<Eigen::Matrix<double, 3, 4>> exact_transform;\n    exact_transform.setFromExpMap(transformation_twist_parameters);\n\n    const int size = 3;\n    Vec3 points[3];\n    Vec3 points_transformed[3];\n    points[0] = Vec3(0, 2, 0);\n    points[1] = Vec3(40, 0, 0);\n    points[2] = Vec3(40, 10, 0);\n\n    double transform[12] = {0};\n    transform[0] = 1;\n    transform[4] = 1;\n    transform[8] = 1;\n\n    ceres::Problem problem;\n    for (int i = 0; i < size; i++) {\n        points_transformed[i] = exact_transform.transform(points[i]);\n        ceres::CostFunction *cost_function = new TestPointToPoint(points_transformed[i].data(), points[i].data());\n        problem.AddResidualBlock(cost_function, NULL, transform);\n    }\n    ceres::LocalParameterization *se3 = new NullSE3Parameterization();\n    problem.SetParameterization(transform, se3);\n\n    ceres::Solver::Options options;\n    ceres::Solver::Summary summary;\n    ceres::Solve(options, &problem, &summary);\n    std::cout << summary.FullReport();\n\n    Transformation<Eigen::Matrix<double, 3, 4>> solved_transform;\n    Mat4 sol_matrix;\n\n    sol_matrix << transform[0], transform[3], transform[6], transform[9],  //\n            transform[1], transform[4], transform[7], transform[10],             //\n            transform[2], transform[5], transform[8], transform[11],             //\n            0, 0, 0, 1;                                                          //\n\n    Mat4 errmat = sol_matrix - exact_transform.getMatrix();\n    ASSERT_LE(errmat.norm(), 1e-9);\n}\n\n/**\n * This test is to verify that this hack breaks the gradient checker in Ceres\n * FYI, hack breaks the gradient checker in Ceres\n */\nTEST(local_jacobians, gradient_checker) {\n    Vec6 transformation_twist_parameters;\n    transformation_twist_parameters << 0.068924613882066, 0.213225926957886, 0.288748939228676, 0.965590777183138,\n            1.960945901104432, 3.037052911306709;\n    Transformation<Eigen::Matrix<double, 3, 4>> exact_transform;\n    exact_transform.setFromExpMap(transformation_twist_parameters);\n\n    Vec3 point;\n    Vec3 points_transformed;\n    point = Vec3(5, 2, 0);\n\n    points_transformed = exact_transform.transform(point);\n    ceres::CostFunction *cost_function = new TestPointToPoint(points_transformed.data(), point.data());\n\n    ceres::LocalParameterization *se3 = new NullSE3Parameterization();\n    std::vector<const ceres::LocalParameterization*> local_param_vec;\n    local_param_vec.emplace_back(se3);\n\n    const double **parameters;\n    parameters = new const double *[1];\n    parameters[0] = exact_transform.storage.data();\n\n    ceres::NumericDiffOptions ndiff_options;\n    ceres::GradientChecker g_check(cost_function, &local_param_vec, ndiff_options);\n    ceres::GradientChecker::ProbeResults g_results;\n    EXPECT_FALSE(g_check.Probe(parameters, 1e-6, &g_results));\n    LOG_INFO(\"%s\", g_results.error_log.c_str());\n}\n\n}\n", "meta": {"hexsha": "f25c693582cc1d64ca5c965ee96300b748e8cc07", "size": 5503, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "wave_optimization/tests/ceres/ceres_local_jacobian_test.cpp", "max_stars_repo_name": "Jebediah/libwave", "max_stars_repo_head_hexsha": "c04998c964f0dc7d414783c6e8cf989a2716ad54", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-06-13T13:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-13T14:54:35.000Z", "max_issues_repo_path": "wave_optimization/tests/ceres/ceres_local_jacobian_test.cpp", "max_issues_repo_name": "Jebediah/libwave", "max_issues_repo_head_hexsha": "c04998c964f0dc7d414783c6e8cf989a2716ad54", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "wave_optimization/tests/ceres/ceres_local_jacobian_test.cpp", "max_forks_repo_name": "Jebediah/libwave", "max_forks_repo_head_hexsha": "c04998c964f0dc7d414783c6e8cf989a2716ad54", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-13T02:27:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-13T02:27:29.000Z", "avg_line_length": 38.4825174825, "max_line_length": 142, "alphanum_fraction": 0.6487370525, "num_tokens": 1574, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189121808099, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.46537428237998923}}
{"text": "// Copyright (c) 2016 The Bitcoin Core developers\n// Distributed under the MIT software license, see the accompanying\n// file COPYING or http://www.opensource.org/licenses/mit-license.php.\n\n#include \"amount.h\"\n#include \"test/test_bitcoin.h\"\n\n#include <boost/test/unit_test.hpp>\n\n#include <array>\n\nBOOST_FIXTURE_TEST_SUITE(amount_tests, BasicTestingSetup)\n\nstatic void CheckAmounts(int64_t aval, int64_t bval) {\n    Amount a(aval), b(bval);\n\n    // Equality\n    BOOST_CHECK_EQUAL(a == b, aval == bval);\n    BOOST_CHECK_EQUAL(b == a, aval == bval);\n\n    BOOST_CHECK_EQUAL(a != b, aval != bval);\n    BOOST_CHECK_EQUAL(b != a, aval != bval);\n\n    // Comparison\n    BOOST_CHECK_EQUAL(a < b, aval < bval);\n    BOOST_CHECK_EQUAL(b < a, bval < aval);\n\n    BOOST_CHECK_EQUAL(a > b, aval > bval);\n    BOOST_CHECK_EQUAL(b > a, bval > aval);\n\n    BOOST_CHECK_EQUAL(a <= b, aval <= bval);\n    BOOST_CHECK_EQUAL(b <= a, bval <= aval);\n\n    BOOST_CHECK_EQUAL(a >= b, aval >= bval);\n    BOOST_CHECK_EQUAL(b >= a, bval >= aval);\n\n    // Unary minus\n    BOOST_CHECK_EQUAL(-a, Amount(-aval));\n    BOOST_CHECK_EQUAL(-b, Amount(-bval));\n\n    // Addition and subtraction.\n    BOOST_CHECK_EQUAL(a + b, b + a);\n    BOOST_CHECK_EQUAL(a + b, Amount(aval + bval));\n\n    BOOST_CHECK_EQUAL(a - b, -(b - a));\n    BOOST_CHECK_EQUAL(a - b, Amount(aval - bval));\n\n    // Multiplication\n    BOOST_CHECK_EQUAL(aval * b, bval * a);\n    BOOST_CHECK_EQUAL(aval * b, Amount(aval * bval));\n\n    // Division\n    if (b != Amount(0)) {\n        BOOST_CHECK_EQUAL(a / b, aval / bval);\n        BOOST_CHECK_EQUAL(a / bval, Amount(a / b));\n    }\n\n    if (a != Amount(0)) {\n        BOOST_CHECK_EQUAL(b / a, bval / aval);\n        BOOST_CHECK_EQUAL(b / aval, Amount(b / a));\n    }\n\n    // Modulus\n    if (b != Amount(0)) {\n        BOOST_CHECK_EQUAL(a % b, aval % bval);\n        BOOST_CHECK_EQUAL(a % bval, Amount(a % b));\n    }\n\n    if (a != Amount(0)) {\n        BOOST_CHECK_EQUAL(b % a, bval % aval);\n        BOOST_CHECK_EQUAL(b % aval, Amount(b % a));\n    }\n\n    // OpAssign\n    Amount v(0);\n    v += a;\n    BOOST_CHECK_EQUAL(v, a);\n    v += b;\n    BOOST_CHECK_EQUAL(v, a + b);\n    v += b;\n    BOOST_CHECK_EQUAL(v, a + 2 * b);\n    v -= 2 * a;\n    BOOST_CHECK_EQUAL(v, 2 * b - a);\n}\n\nBOOST_AUTO_TEST_CASE(AmountTests) {\n    std::array<int64_t, 8> values = {{-23, -1, 0, 1, 2, 3, 42, 99999999}};\n\n    for (int64_t i : values) {\n        for (int64_t j : values) {\n            CheckAmounts(i, j);\n        }\n    }\n\n    BOOST_CHECK_EQUAL(COIN + COIN, 2 * COIN);\n    BOOST_CHECK_EQUAL(2 * COIN + COIN, 3 * COIN);\n    BOOST_CHECK_EQUAL(-1 * COIN + COIN, Amount(0));\n\n    BOOST_CHECK_EQUAL(COIN - COIN, Amount(0));\n    BOOST_CHECK_EQUAL(COIN - 2 * COIN, -1 * COIN);\n}\n\nBOOST_AUTO_TEST_CASE(GetFeeTest) {\n    CFeeRate feeRate;\n\n    feeRate = CFeeRate(Amount(0));\n    // Must always return 0\n    BOOST_CHECK_EQUAL(feeRate.GetFee(0), Amount(0));\n    BOOST_CHECK_EQUAL(feeRate.GetFee(1e5), Amount(0));\n\n    feeRate = CFeeRate(Amount(1000));\n    // Must always just return the arg\n    BOOST_CHECK_EQUAL(feeRate.GetFee(0), Amount(0));\n    BOOST_CHECK_EQUAL(feeRate.GetFee(1), Amount(1));\n    BOOST_CHECK_EQUAL(feeRate.GetFee(121), Amount(121));\n    BOOST_CHECK_EQUAL(feeRate.GetFee(999), Amount(999));\n    BOOST_CHECK_EQUAL(feeRate.GetFee(1000), Amount(1000));\n    BOOST_CHECK_EQUAL(feeRate.GetFee(9000), Amount(9000));\n\n    feeRate = CFeeRate(Amount(-1000));\n    // Must always just return -1 * arg\n    BOOST_CHECK_EQUAL(feeRate.GetFee(0), Amount(0));\n    BOOST_CHECK_EQUAL(feeRate.GetFee(1), Amount(-1));\n    BOOST_CHECK_EQUAL(feeRate.GetFee(121), Amount(-121));\n    BOOST_CHECK_EQUAL(feeRate.GetFee(999), Amount(-999));\n    BOOST_CHECK_EQUAL(feeRate.GetFee(1000), Amount(-1000));\n    BOOST_CHECK_EQUAL(feeRate.GetFee(9000), Amount(-9000));\n\n    feeRate = CFeeRate(Amount(123));\n    // Truncates the result, if not integer\n    BOOST_CHECK_EQUAL(feeRate.GetFee(0), Amount(0));\n    // Special case: returns 1 instead of 0\n    BOOST_CHECK_EQUAL(feeRate.GetFee(8), Amount(1));\n    BOOST_CHECK_EQUAL(feeRate.GetFee(9), Amount(1));\n    BOOST_CHECK_EQUAL(feeRate.GetFee(121), Amount(14));\n    BOOST_CHECK_EQUAL(feeRate.GetFee(122), Amount(15));\n    BOOST_CHECK_EQUAL(feeRate.GetFee(999), Amount(122));\n    BOOST_CHECK_EQUAL(feeRate.GetFee(1000), Amount(123));\n    BOOST_CHECK_EQUAL(feeRate.GetFee(9000), Amount(1107));\n\n    feeRate = CFeeRate(Amount(-123));\n    // Truncates the result, if not integer\n    BOOST_CHECK_EQUAL(feeRate.GetFee(0), Amount(0));\n    // Special case: returns -1 instead of 0\n    BOOST_CHECK_EQUAL(feeRate.GetFee(8), Amount(-1));\n    BOOST_CHECK_EQUAL(feeRate.GetFee(9), Amount(-1));\n\n    // Check full constructor\n    // default value\n    BOOST_CHECK(CFeeRate(Amount(-1), 1000) == CFeeRate(Amount(-1)));\n    BOOST_CHECK(CFeeRate(Amount(0), 1000) == CFeeRate(Amount(0)));\n    BOOST_CHECK(CFeeRate(Amount(1), 1000) == CFeeRate(Amount(1)));\n    // lost precision (can only resolve satoshis per kB)\n    BOOST_CHECK(CFeeRate(Amount(1), 1001) == CFeeRate(Amount(0)));\n    BOOST_CHECK(CFeeRate(Amount(2), 1001) == CFeeRate(Amount(1)));\n    // some more integer checks\n    BOOST_CHECK(CFeeRate(Amount(26), 789) == CFeeRate(Amount(32)));\n    BOOST_CHECK(CFeeRate(Amount(27), 789) == CFeeRate(Amount(34)));\n    // Maximum size in bytes, should not crash\n    CFeeRate(MAX_MONEY, std::numeric_limits<size_t>::max() >> 1).GetFeePerK();\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "d51c55677adcd7ac9229270feda2e7fcc591f245", "size": 5410, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/amount_tests.cpp", "max_stars_repo_name": "unixisevil/bitcoin-abc-log", "max_stars_repo_head_hexsha": "497a1b485ba930c39ce9132d7202137cfec8298f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-07-04T17:57:48.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-24T15:15:26.000Z", "max_issues_repo_path": "src/test/amount_tests.cpp", "max_issues_repo_name": "sighttviewliu/bitcoin-abc", "max_issues_repo_head_hexsha": "497a1b485ba930c39ce9132d7202137cfec8298f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/test/amount_tests.cpp", "max_forks_repo_name": "sighttviewliu/bitcoin-abc", "max_forks_repo_head_hexsha": "497a1b485ba930c39ce9132d7202137cfec8298f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-07T06:28:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-07T06:28:33.000Z", "avg_line_length": 32.987804878, "max_line_length": 78, "alphanum_fraction": 0.6471349353, "num_tokens": 1617, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189121808099, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.46537428237998923}}
{"text": "/*\n * @Description: LIO key frame\n * @Author: Ren Qian\n * @Date: 2020-02-28 19:13:26\n */\n#ifndef LIDAR_LOCALIZATION_SENSOR_DATA_KEY_FRAME_HPP_\n#define LIDAR_LOCALIZATION_SENSOR_DATA_KEY_FRAME_HPP_\n\n#include <Eigen/Eigen>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n#include <sophus/so3.hpp>\n\n#include \"lidar_localization/models/graph_optimizer/g2o/vertex/vertex_prvag.hpp\"\n\nnamespace lidar_localization {\n\nstruct KeyFrame {\npublic:\n    static const int INDEX_P = 0;\n    static const int INDEX_R = 3;\n    static const int INDEX_V = 6;\n    static const int INDEX_A = 9;\n    static const int INDEX_G = 12;\n\n    double time = 0.0;\n\n    // key frame ID:\n    unsigned int index = 0;\n    \n    // a. position & orientation:\n    Eigen::Matrix4f pose = Eigen::Matrix4f::Identity();\n    // b. velocity:\n    struct {\n      Eigen::Vector3f v = Eigen::Vector3f::Zero();\n      Eigen::Vector3f w = Eigen::Vector3f::Zero();\n    } vel;\n    // c. bias:\n    struct {\n      // c.1. accelerometer:\n      Eigen::Vector3f accel = Eigen::Vector3f::Zero();\n      // c.2. gyroscope:\n      Eigen::Vector3f gyro = Eigen::Vector3f::Zero();\n    } bias;\n\n    KeyFrame() {}\n\n    explicit KeyFrame(const int vertex_id, const g2o::PRVAG &prvag) {\n      // set time:\n      time = prvag.time;\n      // set seq. ID:\n      index = vertex_id;\n      // set state:\n      pose.block<3, 1>(0, 3) = prvag.pos.cast<float>();\n      pose.block<3, 3>(0, 0) = prvag.ori.matrix().cast<float>();\n      vel.v = prvag.vel.cast<float>();\n      bias.accel = prvag.b_a.cast<float>();\n      bias.gyro = prvag.b_g.cast<float>();\n    }\n\n    explicit KeyFrame(const int param_index, const double &T, const double *prvag) {\n      // set time:\n      time = T;\n      // set seq. ID:\n      index = param_index;\n      // set state:\n      Eigen::Map<const Eigen::Vector3d>     pos(prvag + INDEX_P);\n      Eigen::Map<const Eigen::Vector3d> log_ori(prvag + INDEX_R);\n      Eigen::Map<const Eigen::Vector3d>       v(prvag + INDEX_V);\n      Eigen::Map<const Eigen::Vector3d>     b_a(prvag + INDEX_A);\n      Eigen::Map<const Eigen::Vector3d>     b_g(prvag + INDEX_G);\n\n      pose.block<3, 1>(0, 3) = pos.cast<float>();\n      pose.block<3, 3>(0, 0) = Sophus::SO3d::exp(log_ori).matrix().cast<float>();\n\n      vel.v = v.cast<float>();\n      \n      bias.accel = b_a.cast<float>();\n      bias.gyro = b_g.cast<float>();\n    }\n\n    Eigen::Quaternionf GetQuaternion() const;\n    Eigen::Vector3f GetTranslation() const;\n};\n\n}\n\n#endif", "meta": {"hexsha": "3d0cd093e31770a0170626ad54ec0795d732775d", "size": 2455, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "GraphOptimize/09-sliding-window/src/lidar_localization/include/lidar_localization/sensor_data/key_frame.hpp", "max_stars_repo_name": "lanqing30/SensorFusionCourse", "max_stars_repo_head_hexsha": "3fcf935d6a4191563afcf2d95b34718fba7f705a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "GraphOptimize/09-sliding-window/src/lidar_localization/include/lidar_localization/sensor_data/key_frame.hpp", "max_issues_repo_name": "lanqing30/SensorFusionCourse", "max_issues_repo_head_hexsha": "3fcf935d6a4191563afcf2d95b34718fba7f705a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GraphOptimize/09-sliding-window/src/lidar_localization/include/lidar_localization/sensor_data/key_frame.hpp", "max_forks_repo_name": "lanqing30/SensorFusionCourse", "max_forks_repo_head_hexsha": "3fcf935d6a4191563afcf2d95b34718fba7f705a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-08T01:05:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T01:05:31.000Z", "avg_line_length": 27.5842696629, "max_line_length": 84, "alphanum_fraction": 0.6105906314, "num_tokens": 720, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125848754472, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.46533067345006307}}
{"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_IEEE_FUNCTIONS_SCALAR_EXPONENT_HPP_INCLUDED\n#define BOOST_SIMD_IEEE_FUNCTIONS_SCALAR_EXPONENT_HPP_INCLUDED\n#include <boost/simd/ieee/functions/exponent.hpp>\n#include <boost/dispatch/meta/adapted_traits.hpp>\n#include <boost/dispatch/meta/as_integer.hpp>\n#include <boost/simd/include/functions/scalar/is_invalid.hpp>\n#include <boost/simd/include/functions/scalar/shri.hpp>\n#include <boost/simd/include/functions/scalar/exponentbits.hpp>\n#include <boost/simd/include/functions/scalar/is_nez.hpp>\n#include <boost/simd/include/functions/scalar/is_eqz.hpp>\n#include <boost/simd/include/functions/scalar/if_else_zero.hpp>\n#include <boost/simd/include/constants/nbmantissabits.hpp>\n#include <boost/simd/include/constants/maxexponent.hpp>\n#include <boost/simd/sdk/math.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n#ifdef BOOST_SIMD_HAS_ILOGB\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::exponent_, tag::cpu_\n                            , (A0)\n                            , (scalar_< double_<A0> >)\n                            )\n  {\n    typedef typename dispatch::meta::as_integer<A0, signed>::type result_type;\n    BOOST_SIMD_FUNCTOR_CALL(1)\n    {\n      if (is_invalid(a0) || is_eqz(a0)) return Zero<result_type>();\n      return ::ilogb(a0);\n    }\n  };\n#endif\n\n#ifdef BOOST_SIMD_HAS_ILOGBF\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::exponent_, tag::cpu_\n                            , (A0)\n                            , (scalar_< single_<A0> >)\n                            )\n  {\n    typedef typename dispatch::meta::as_integer<A0, signed>::type result_type;\n    BOOST_SIMD_FUNCTOR_CALL(1)\n    {\n      if (is_invalid(a0) || is_eqz(a0)) return Zero<result_type>();\n      return ::ilogbf(a0);\n    }\n  };\n#endif\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::exponent_, tag::cpu_\n                            , (A0)\n                            , (scalar_< floating_<A0> >)\n                            )\n  {\n    typedef typename dispatch::meta::as_integer<A0, signed>::type result_type;\n    BOOST_SIMD_FUNCTOR_CALL(1)\n    {\n      if (is_invalid(a0) || is_eqz(a0)) return Zero<result_type>();\n      const int nmb = int(Nbmantissabits<A0>());\n      const result_type x = shri(exponentbits(a0), nmb);\n      return x-if_else_zero(is_nez(a0), Maxexponent<A0>());\n    }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "0f996e3c9400126920ea390bd28ef9628e33597e", "size": 2834, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/ieee/include/boost/simd/ieee/functions/scalar/exponent.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/ieee/include/boost/simd/ieee/functions/scalar/exponent.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/ieee/include/boost/simd/ieee/functions/scalar/exponent.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": 38.2972972973, "max_line_length": 80, "alphanum_fraction": 0.6076217361, "num_tokens": 680, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597971, "lm_q2_score": 0.6187804337438502, "lm_q1q2_score": 0.4653306665719164}}
{"text": "#include <functional>\n#include <iostream>\n#include <memory>\n\n#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN\n#define DOCTEST_CONFIG_SUPER_FAST_ASSERTS\n#include \"doctest/doctest.h\"\n\n#include <tvm/Variable.h>\n#include <tvm/VariableVector.h>\n#include <tvm/constraint/BasicLinearConstraint.h>\n#include <tvm/hint/internal/Substitutions.h>\n#include <tvm/hint/Substitution.h>\n#include <tvm/scheme/internal/Assignment.h>\n#include <tvm/scheme/internal/AssignmentTarget.h>\n\n#include <Eigen/Core>\n#include <Eigen/QR>\n\n//FIXME see src/Assignment.cpp\nstatic const double large = tvm::constant::big_number;\n\nusing namespace tvm;\nusing namespace tvm::constraint;\nusing namespace tvm::hint;\nusing namespace tvm::hint::internal;\nusing namespace tvm::scheme::internal;\nusing namespace tvm::requirements;\nusing namespace Eigen;\n\nusing BLCPtr = std::shared_ptr<BasicLinearConstraint>;\n\nstruct Constraints\n{\n  VectorXd p0;\n  VectorXd pl;\n  VectorXd pu;\n\n  BLCPtr Ax_eq_0;\n  BLCPtr Ax_geq_0;\n  BLCPtr Ax_leq_0;\n  BLCPtr Ax_eq_b;\n  BLCPtr Ax_geq_b;\n  BLCPtr Ax_leq_b;\n  BLCPtr Ax_eq_minus_b;\n  BLCPtr Ax_geq_minus_b;\n  BLCPtr Ax_leq_minus_b;\n  BLCPtr l_leq_Ax_leq_u;\n  BLCPtr minus_l_leq_Ax_leq_minus_u;\n};\n\nstruct Memory\n{\n  Memory(int m, int n) : A(m, n), b(m), l(m), u(m)\n  {\n    reset();\n  }\n\n  void reset()\n  {\n    A.setZero();\n    b.setZero();\n    l.setZero();\n    u.setZero();\n  }\n\n  void randomize()\n  {\n    A.setRandom();\n    b.setRandom();\n    l.setRandom();\n    u.setRandom();\n  }\n\n  MatrixXd A;\n  VectorXd b;\n  VectorXd l;\n  VectorXd u;\n};\n\n//Check if the constraint is satisfied for the current value of the variable\nbool check(BLCPtr c, const VectorXd& x)\n{\n  const double eps = 1e-12;\n  const_cast<VariableVector&>(c->variables()).value(x);\n  c->updateValue();\n  auto v = c->value();\n  if (c->type() == Type::DOUBLE_SIDED)\n  {\n    if (c->rhs() == RHS::AS_GIVEN)\n      return (c->l().array()-eps <= v.array()).all() && (v.array() <= c->u().array()+eps).all();\n    else\n      return (-c->l().array()-eps <= v.array()).all() && (v.array() <= -c->u().array()+eps).all();\n  }\n  else\n  {\n    std::function<bool(const VectorXd&, const VectorXd&)> comp;\n    const VectorXd&(BasicLinearConstraint::*rhs)() const;\n    switch (c->type())\n    {\n    case Type::EQUAL: comp = [](const VectorXd& u, const VectorXd& v) {return u.isApprox(v); }; rhs =& BasicLinearConstraint::e;  break;\n    case Type::GREATER_THAN: comp = [eps](const VectorXd& u, const VectorXd& v) {return (u.array() + eps >= v.array()).all(); }; rhs = &BasicLinearConstraint::l; break;\n    case Type::LOWER_THAN: comp = [eps](const VectorXd& u, const VectorXd& v) {return (u.array() - eps <= v.array()).all(); }; rhs = &BasicLinearConstraint::u; break;\n    default: break;\n    }\n    switch (c->rhs())\n    {\n    case RHS::AS_GIVEN: return comp(v, (c.get()->*rhs)()); break;\n    case RHS::OPPOSITE: return comp(v, -(c.get()->*rhs)()); break;\n    case RHS::ZERO: return comp(v, VectorXd::Zero(c->size())); break;\n    default:\n      return false;\n    }\n  }\n}\n\nbool check(const Memory& mem, Type ct, RHS cr, const VectorXd& x, bool bound=false)\n{\n  const double eps = 1e-12;\n  VectorXd v;\n  if (bound)\n    v = x;\n  else\n    v = mem.A*x;\n\n  if (ct == Type::DOUBLE_SIDED)\n  {\n    if (cr == RHS::AS_GIVEN)\n      return (mem.l.array() - eps <= v.array()).all() && (v.array() <= mem.u.array() + eps).all();\n    else\n      return (-mem.l.array() - eps <= v.array()).all() && (v.array() <= -mem.u.array() + eps).all();\n  }\n  else\n  {\n    std::function<bool(const VectorXd&, const VectorXd&)> comp;\n    switch (ct)\n    {\n    case Type::EQUAL: comp = [](const VectorXd& u, const VectorXd& v) {return u.isApprox(v); };  break;\n    case Type::GREATER_THAN: comp = [eps](const VectorXd& u, const VectorXd& v) {return (u.array() + eps >= v.array()).all(); }; break;\n    case Type::LOWER_THAN: comp = [eps](const VectorXd& u, const VectorXd& v) {return (u.array() - eps <= v.array()).all(); }; break;\n    default: break;\n    }\n    switch (cr)\n    {\n    case RHS::AS_GIVEN: return comp(v, mem.b); break;\n    case RHS::OPPOSITE: return comp(v, -mem.b); break;\n    case RHS::ZERO: return comp(v, VectorXd::Zero(mem.b.rows())); break;\n    default:\n      return false;\n    }\n  }\n}\n\nConstraints buildConstraints(int m, int n)\n{\n  Constraints cstr;\n  VariablePtr x = Space(n).createVariable(\"x\");\n\n  //generate matrix\n  MatrixXd A = MatrixXd::Random(m, n);\n  VectorXd l = -VectorXd::Random(m).cwiseAbs();\n  VectorXd u = VectorXd::Random(m).cwiseAbs();\n\n  //Point p0 such that Ap0 = 0\n  cstr.p0 = A.householderQr().solve(VectorXd::Zero(m));\n  //Point pl such that Apl = l\n  cstr.pl = A.householderQr().solve(l);\n  //Point pu such that Apu = u\n  cstr.pu = A.householderQr().solve(u);\n\n  cstr.Ax_eq_0 = std::make_shared<BasicLinearConstraint>(A, x, Type::EQUAL);\n  cstr.Ax_geq_0 = std::make_shared<BasicLinearConstraint>(A, x, Type::GREATER_THAN);\n  cstr.Ax_leq_0 = std::make_shared<BasicLinearConstraint>(A, x, Type::LOWER_THAN);\n\n  cstr.Ax_eq_b = std::make_shared<BasicLinearConstraint>(A, x, l, Type::EQUAL);\n  cstr.Ax_geq_b = std::make_shared<BasicLinearConstraint>(A, x, l, Type::GREATER_THAN);\n  cstr.Ax_leq_b = std::make_shared<BasicLinearConstraint>(A, x, u, Type::LOWER_THAN);\n\n  cstr.Ax_eq_minus_b = std::make_shared<BasicLinearConstraint>(A, x, -l, Type::EQUAL, RHS::OPPOSITE);\n  cstr.Ax_geq_minus_b = std::make_shared<BasicLinearConstraint>(A, x, -l, Type::GREATER_THAN, RHS::OPPOSITE);\n  cstr.Ax_leq_minus_b = std::make_shared<BasicLinearConstraint>(A, x, -u, Type::LOWER_THAN, RHS::OPPOSITE);\n\n  cstr.l_leq_Ax_leq_u = std::make_shared<BasicLinearConstraint>(A, x, l, u);\n  cstr.minus_l_leq_Ax_leq_minus_u = std::make_shared<BasicLinearConstraint>(A, x, -l, -u, RHS::OPPOSITE);\n  return cstr;\n}\n\n//build constraints x op 0, x op +/-2 such that 0 is feasible, and -2 <= x <= 2\n//if minus = true, we take -x instead of x\nConstraints buildSimpleConstraints(double s = 1, VariablePtr y = nullptr)\n{\n  assert(s != 0);\n  Constraints cstr;\n  VariablePtr x;\n  if (y)\n    x = y;\n  else\n    x = Space(1).createVariable(\"x\");\n\n  tvm::internal::MatrixProperties p;\n  if (s == -1)\n    p = { tvm::internal::MatrixProperties::MINUS_IDENTITY };\n  else if (s == 1)\n    p = { tvm::internal::MatrixProperties::IDENTITY };\n  else\n    p = { tvm::internal::MatrixProperties::MULTIPLE_OF_IDENTITY, \n          tvm::internal::MatrixProperties::Invertibility(s != 0) };\n\n  //generate matrix\n  MatrixXd A = s*MatrixXd::Identity(1, 1);\n  VectorXd l = VectorXd::Constant(1, -2);\n  VectorXd u = VectorXd::Constant(1, 2);\n\n  cstr.Ax_eq_0 = std::make_shared<BasicLinearConstraint>(A, x, Type::EQUAL);\n  cstr.Ax_eq_0->A(A, p);\n  cstr.Ax_geq_0 = std::make_shared<BasicLinearConstraint>(A, x, Type::GREATER_THAN);\n  cstr.Ax_geq_0->A(A, p);\n  cstr.Ax_leq_0 = std::make_shared<BasicLinearConstraint>(A, x, Type::LOWER_THAN);\n  cstr.Ax_leq_0->A(A, p);\n\n  cstr.Ax_eq_b = std::make_shared<BasicLinearConstraint>(A, x, l, Type::EQUAL);\n  cstr.Ax_eq_b->A(A, p);\n  cstr.Ax_geq_b = std::make_shared<BasicLinearConstraint>(A, x, l, Type::GREATER_THAN);\n  cstr.Ax_geq_b->A(A, p);\n  cstr.Ax_leq_b = std::make_shared<BasicLinearConstraint>(A, x, u, Type::LOWER_THAN);\n  cstr.Ax_leq_b->A(A, p);\n\n  cstr.Ax_eq_minus_b = std::make_shared<BasicLinearConstraint>(A, x, -l, Type::EQUAL, RHS::OPPOSITE);\n  cstr.Ax_eq_minus_b->A(A, p);\n  cstr.Ax_geq_minus_b = std::make_shared<BasicLinearConstraint>(A, x, -l, Type::GREATER_THAN, RHS::OPPOSITE);\n  cstr.Ax_geq_minus_b->A(A, p);\n  cstr.Ax_leq_minus_b = std::make_shared<BasicLinearConstraint>(A, x, -u, Type::LOWER_THAN, RHS::OPPOSITE);\n  cstr.Ax_leq_minus_b->A(A, p);\n\n  cstr.l_leq_Ax_leq_u = std::make_shared<BasicLinearConstraint>(A, x, l, u);\n  cstr.l_leq_Ax_leq_u->A(A, p);\n  cstr.minus_l_leq_Ax_leq_minus_u = std::make_shared<BasicLinearConstraint>(A, x, -l, -u, RHS::OPPOSITE);\n  cstr.minus_l_leq_Ax_leq_minus_u->A(A, p);\n  return cstr;\n}\n\n//create a set of constraints -3x+4y op +/-2 and a constraint for substitution\n// -x + 2y - z = 0/1/-1 (the latter value depending on the rhs param).\nstd::pair<Constraints, BLCPtr> buildSimpleSubstitution(RHS rhs)\n{\n  Constraints cstr;\n  VariablePtr x = Space(1).createVariable(\"x\");\n  VariablePtr y = Space(1).createVariable(\"y\");\n  VariablePtr z = Space(1).createVariable(\"z\");\n\n  //generate matrix\n  MatrixXd I = MatrixXd::Identity(1, 1);\n  MatrixXd Ax = -3 * I;\n  MatrixXd Ay = 4 * I;\n  VectorXd l = VectorXd::Constant(1, -2);\n  VectorXd u = VectorXd::Constant(1, 2);\n\n  std::vector<Ref<const MatrixXd>> A = { Ax, Ay };\n  std::vector<VariablePtr> v = { x, y };\n\n  cstr.Ax_eq_0 = std::make_shared<BasicLinearConstraint>( A, v, Type::EQUAL);\n  cstr.Ax_geq_0 = std::make_shared<BasicLinearConstraint>(A, v, Type::GREATER_THAN);\n  cstr.Ax_leq_0 = std::make_shared<BasicLinearConstraint>(A, v, Type::LOWER_THAN);\n\n  cstr.Ax_eq_b = std::make_shared<BasicLinearConstraint>( A, v, l, Type::EQUAL);\n  cstr.Ax_geq_b = std::make_shared<BasicLinearConstraint>(A, v, l, Type::GREATER_THAN);\n  cstr.Ax_leq_b = std::make_shared<BasicLinearConstraint>(A, v, u, Type::LOWER_THAN);\n\n  cstr.Ax_eq_minus_b = std::make_shared<BasicLinearConstraint>( A, v, -l, Type::EQUAL, RHS::OPPOSITE);\n  cstr.Ax_geq_minus_b = std::make_shared<BasicLinearConstraint>(A, v, -l, Type::GREATER_THAN, RHS::OPPOSITE);\n  cstr.Ax_leq_minus_b = std::make_shared<BasicLinearConstraint>(A, v, -u, Type::LOWER_THAN, RHS::OPPOSITE);\n\n  cstr.l_leq_Ax_leq_u = std::make_shared<BasicLinearConstraint>(A, v, l, u);\n  cstr.minus_l_leq_Ax_leq_minus_u = std::make_shared<BasicLinearConstraint>(A, v, -l, -u, RHS::OPPOSITE);\n\n  MatrixXd Cx = -I;\n  MatrixXd Cy = 2 * I;\n  MatrixXd Cz = -I;\n  std::vector<Ref<const MatrixXd>> C = { Cx, Cy, Cz };\n  std::vector<VariablePtr> w = { x, y, z };\n  VectorXd d = VectorXd::Constant(1, 1);\n  if (rhs == RHS::ZERO)\n  {\n    return std::make_pair(cstr, std::make_shared<BasicLinearConstraint>(C, w, Type::EQUAL));\n  }\n  else\n  {\n    return std::make_pair(cstr, std::make_shared<BasicLinearConstraint>(C, w, d, Type::EQUAL, rhs));\n  }\n}\n\n//check that each point -3, -2, -1, 0, 1, 2 and 3 is either verifying at the same time\n//the two descriptions of the constraint or violating both of them.\nvoid checkSimple(BLCPtr cstr, const Memory& mem, Type t, RHS r, bool bound = false)\n{\n  VectorXd pm3 = VectorXd::Constant(1, -3);\n  VectorXd pm2 = VectorXd::Constant(1, -2);\n  VectorXd pm1 = VectorXd::Constant(1, -1);\n  VectorXd p0 = VectorXd::Constant(1, 0);\n  VectorXd p1 = VectorXd::Constant(1, 1);\n  VectorXd p2 = VectorXd::Constant(1, 2);\n  VectorXd p3 = VectorXd::Constant(1, 3);\n\n  FAST_CHECK_EQ(check(cstr, pm3), check(mem, t, r, pm3, bound));\n  FAST_CHECK_EQ(check(cstr, pm2), check(mem, t, r, pm2, bound));\n  FAST_CHECK_EQ(check(cstr, pm1), check(mem, t, r, pm1, bound));\n  FAST_CHECK_EQ(check(cstr, p0), check(mem, t, r, p0, bound));\n  FAST_CHECK_EQ(check(cstr, p1), check(mem, t, r, p1, bound));\n  FAST_CHECK_EQ(check(cstr, p2), check(mem, t, r, p2, bound));\n  FAST_CHECK_EQ(check(cstr, p3), check(mem, t, r, p3, bound));\n}\n\n//check for the intersection of 2 bound constraints\nvoid checkSimple(BLCPtr cstr1, BLCPtr cstr2, const Memory& mem)\n{\n  Type t = Type::DOUBLE_SIDED;\n  RHS r = RHS::AS_GIVEN;\n\n  VectorXd pm3 = VectorXd::Constant(1, -3);\n  VectorXd pm2 = VectorXd::Constant(1, -2);\n  VectorXd pm1 = VectorXd::Constant(1, -1);\n  VectorXd p0 = VectorXd::Constant(1, 0);\n  VectorXd p1 = VectorXd::Constant(1, 1);\n  VectorXd p2 = VectorXd::Constant(1, 2);\n  VectorXd p3 = VectorXd::Constant(1, 3);\n\n  FAST_CHECK_EQ(check(cstr1, pm3) && check(cstr2, pm3), check(mem, t, r, pm3, true));\n  FAST_CHECK_EQ(check(cstr1, pm2) && check(cstr2, pm2), check(mem, t, r, pm2, true));\n  FAST_CHECK_EQ(check(cstr1, pm1) && check(cstr2, pm1), check(mem, t, r, pm1, true));\n  FAST_CHECK_EQ(check(cstr1, p0) && check(cstr2, p0), check(mem, t, r, p0, true));\n  FAST_CHECK_EQ(check(cstr1, p1) && check(cstr2, p1), check(mem, t, r, p1, true));\n  FAST_CHECK_EQ(check(cstr1, p2) && check(cstr2, p2), check(mem, t, r, p2, true));\n  FAST_CHECK_EQ(check(cstr1, p3) && check(cstr2, p3), check(mem, t, r, p3, true));\n}\n\n// Check that each point (x,z) with z=-x, for x = -5,-3,1,0,1,3,5 verifies or violates the\n// substituted constraint in mem at the same time as the corresponding (x, y) point verifies\n// or violates the constraint.\nvoid checkSubstitution(BLCPtr cstr, RHS subRhs, const Memory& mem, Type t, RHS r)\n{\n  double y;\n  switch (subRhs)\n  {\n  case RHS::ZERO: y = 0; break;\n  case RHS::AS_GIVEN: y = 0.5; break;\n  case RHS::OPPOSITE: y = -0.5; break;\n  }\n  VectorXd xym5(2); xym5 << -2, y;\n  VectorXd xym3(2); xym3 << -4./3, y;\n  VectorXd xym1(2); xym1 << -2./3, y;\n  VectorXd xy0(2); xy0 << 0, y;\n  VectorXd xy1(2); xy1 << 2./3, y;\n  VectorXd xy3(2); xy3 << 4./3, y;\n  VectorXd xy5(2); xy5 << 2, y;\n  VectorXd xzm5(2); xzm5 << -2, 2;\n  VectorXd xzm3(2); xzm3 << -4./3, 4./3;\n  VectorXd xzm1(2); xzm1 << -2./3, 2./3;\n  VectorXd xz0(2); xz0 << 0, 0;\n  VectorXd xz1(2); xz1 << 2./3, -2./3;\n  VectorXd xz3(2); xz3 << 4./3, -4./3;\n  VectorXd xz5(2); xz5 << 2, -2;\n\n  //std::cout << check(cstr, xym5) <<\", \" << check(mem, t, r, xzm5, false) << std::endl;\n  //std::cout << check(cstr, xym3) <<\", \" << check(mem, t, r, xzm3, false) << std::endl;\n  //std::cout << check(cstr, xym1) <<\", \" << check(mem, t, r, xzm1, false) << std::endl;\n  //std::cout << check(cstr, xy0)  <<\", \" << check(mem, t, r, xz0, false)  << std::endl;\n  //std::cout << check(cstr, xy1)  <<\", \" << check(mem, t, r, xz1, false)  << std::endl;\n  //std::cout << check(cstr, xy3)  <<\", \" << check(mem, t, r, xz3, false)  << std::endl;\n  //std::cout << check(cstr, xy5)  <<\", \" << check(mem, t, r, xz5, false)  << std::endl;\n\n  FAST_CHECK_EQ(check(cstr, xym5), check(mem, t, r, xzm5, false));\n  FAST_CHECK_EQ(check(cstr, xym3), check(mem, t, r, xzm3, false));\n  FAST_CHECK_EQ(check(cstr, xym1), check(mem, t, r, xzm1, false));\n  FAST_CHECK_EQ(check(cstr, xy0), check(mem, t, r, xz0, false));\n  FAST_CHECK_EQ(check(cstr, xy1), check(mem, t, r, xz1, false));\n  FAST_CHECK_EQ(check(cstr, xy3), check(mem, t, r, xz3, false));\n  FAST_CHECK_EQ(check(cstr, xy5), check(mem, t, r, xz5, false));\n}\n\nvoid checkAssignment(BLCPtr c, const AssignmentTarget& at, Memory& mem, Type t, RHS r, bool throws)\n{\n  auto req = std::make_shared<SolvingRequirements>();\n  VariableVector vars(c->variables());\n  mem.randomize();\n  if (throws)\n  {\n    CHECK_THROWS(Assignment a(c, req, at, vars));\n  }\n  else\n  {\n    Assignment a(c, req, at, vars);\n    a.run();\n    checkSimple(c, mem, t, r);\n  }\n}\n\nvoid checkSubstitutionAssignment(BLCPtr c, Substitutions& s, const AssignmentTarget& at, Memory& mem, Type t, RHS r, bool throws)\n{\n  auto req = std::make_shared<SolvingRequirements>();\n  VariableVector vars;\n  vars.add(s.otherVariables());\n  mem.randomize();\n  if (throws)\n  {\n    CHECK_THROWS(Assignment a(c, req, at, vars, &s));\n  }\n  else\n  {\n    s.updateSubstitutions();\n    Assignment a(c, req, at, vars, &s);\n    a.run();\n    checkSubstitution(c, s.substitutions()[0].constraints()[0]->rhs(), mem, t, r);\n  }\n}\n\nvoid checkBoundAssignment(BLCPtr c, const AssignmentTarget& at, Memory& mem)\n{\n  Assignment a(c, at, c->variables()[0], true);\n  a.run();\n  checkSimple(c, mem, Type::DOUBLE_SIDED, RHS::AS_GIVEN, true);\n}\n\nvoid checkBoundAssignment(BLCPtr c1, BLCPtr c2, const AssignmentTarget& at, Memory& mem)\n{\n  assert(c1->variables()[0] == c2->variables()[0]);\n  Assignment a1(c1, at, c1->variables()[0], true);\n  a1.run();\n  Assignment a2(c2, at, c2->variables()[0], false);\n  a2.run();\n  checkSimple(c1, c2, mem);\n}\n\n/** Check the assignement of a constraint \\p c to a target\n  * \\p throws is a vector of 11 bool indicating if the assignement construction is\n  * expected to throw. The order of the targets conventions are:\n  * Cx=0, Cx=d, Cx=-d, Cx>=0, Cx>=d, Cx>=-d, Cx<=0, Cx<=d, Cx<=-d, l<=Cx<=u, -l<=Cx<=-u\n  */\nvoid checkSimple(BLCPtr c, std::vector<bool> throws)\n{\n  int s = c->type() == Type::DOUBLE_SIDED ? 2 : 1;\n  auto sMem = std::make_shared<Memory>(s, 1);\n  auto sRange = std::make_shared<Range>(0, s);\n  auto dMem = std::make_shared<Memory>(1, 1);\n  auto dRange = std::make_shared<Range>(0, 1);\n\n  // target Cx=0\n  {\n    auto t = Type::EQUAL;\n    auto r = RHS::ZERO;\n    AssignmentTarget at(sRange, sMem->A, t);\n    checkAssignment(c, at, *sMem, t, r, throws[0]);\n  }\n  // target Cx=d\n  {\n    auto t = Type::EQUAL;\n    auto r = RHS::AS_GIVEN;\n    AssignmentTarget at(sRange, sMem->A, sMem->b, t, r);\n    checkAssignment(c, at, *sMem, t, r, throws[1]);\n  }\n  // target Cx=-d\n  {\n    auto t = Type::EQUAL;\n    auto r = RHS::OPPOSITE;\n    sMem->randomize();\n    AssignmentTarget at(sRange, sMem->A, sMem->b, t, r);\n    checkAssignment(c, at, *sMem, t, r, throws[2]);\n  }\n  // target Cx>=0\n  {\n    auto t = Type::GREATER_THAN;\n    auto r = RHS::ZERO;\n    AssignmentTarget at(sRange, sMem->A, t);\n    checkAssignment(c, at, *sMem, t, r, throws[3]);\n  }\n  // target Cx>=d\n  {\n    auto t = Type::GREATER_THAN;\n    auto r = RHS::AS_GIVEN;\n    AssignmentTarget at(sRange, sMem->A, sMem->b, t, r);\n    checkAssignment(c, at, *sMem, t, r, throws[4]);\n  }\n  // target Cx>=-d\n  {\n    auto t = Type::GREATER_THAN;\n    auto r = RHS::OPPOSITE;\n    sMem->randomize();\n    AssignmentTarget at(sRange, sMem->A, sMem->b, t, r);\n    checkAssignment(c, at, *sMem, t, r, throws[5]);\n  }\n  // target Cx<=0\n  {\n    auto t = Type::LOWER_THAN;\n    auto r = RHS::ZERO;\n    AssignmentTarget at(sRange, sMem->A, t);\n    checkAssignment(c, at, *sMem, t, r, throws[6]);\n  }\n  // target Cx<=d\n  {\n    auto t = Type::LOWER_THAN;\n    auto r = RHS::AS_GIVEN;\n    AssignmentTarget at(sRange, sMem->A, sMem->b, t, r);\n    checkAssignment(c, at, *sMem, t, r, throws[7]);\n  }\n  // target Cx<=-d\n  {\n    auto t = Type::LOWER_THAN;\n    auto r = RHS::OPPOSITE;\n    sMem->randomize();\n    AssignmentTarget at(sRange, sMem->A, sMem->b, t, r);\n    checkAssignment(c, at, *sMem, t, r, throws[8]);\n  }\n  // target l<=Cx<=u\n  {\n    auto t = Type::DOUBLE_SIDED;\n    auto r = RHS::AS_GIVEN;\n    AssignmentTarget at(dRange, dMem->A, dMem->l, dMem->u, r);\n    checkAssignment(c, at, *dMem, t, r, throws[9]);\n  }\n  // target -l<=Cx<=-u\n  {\n    auto t = Type::DOUBLE_SIDED;\n    auto r = RHS::AS_GIVEN;\n    AssignmentTarget at(dRange, dMem->A, dMem->l, dMem->u, r);\n    checkAssignment(c, at, *dMem, t, r, throws[10]);\n  }\n}\n\n//same as above but introducing a substitution\nvoid checkSimple(BLCPtr c, const Substitution& sub, std::vector<bool> throws)\n{\n  int s = c->type() == Type::DOUBLE_SIDED ? 2 : 1;\n  auto sMem = std::make_shared<Memory>(s, 2);\n  auto sRange = std::make_shared<Range>(0, s);\n  auto dMem = std::make_shared<Memory>(1, 2);\n  auto dRange = std::make_shared<Range>(0, 1);\n\n  Substitutions subs;\n  subs.add(sub);\n  subs.finalize();\n\n  // target Cx=0\n  {\n    auto t = Type::EQUAL;\n    auto r = RHS::ZERO;\n    AssignmentTarget at(sRange, sMem->A, t);\n    checkSubstitutionAssignment(c, subs, at, *sMem, t, r, throws[0]);\n  }\n  // target Cx=d\n  {\n    auto t = Type::EQUAL;\n    auto r = RHS::AS_GIVEN;\n    AssignmentTarget at(sRange, sMem->A, sMem->b, t, r);\n    checkSubstitutionAssignment(c, subs, at, *sMem, t, r, throws[1]);\n  }\n  // target Cx=-d\n  {\n    auto t = Type::EQUAL;\n    auto r = RHS::OPPOSITE;\n    sMem->randomize();\n    AssignmentTarget at(sRange, sMem->A, sMem->b, t, r);\n    checkSubstitutionAssignment(c, subs, at, *sMem, t, r, throws[2]);\n  }\n  // target Cx>=0\n  {\n    auto t = Type::GREATER_THAN;\n    auto r = RHS::ZERO;\n    AssignmentTarget at(sRange, sMem->A, t);\n    checkSubstitutionAssignment(c, subs, at, *sMem, t, r, throws[3]);\n  }\n  // target Cx>=d\n  {\n    auto t = Type::GREATER_THAN;\n    auto r = RHS::AS_GIVEN;\n    AssignmentTarget at(sRange, sMem->A, sMem->b, t, r);\n    checkSubstitutionAssignment(c, subs, at, *sMem, t, r, throws[4]);\n  }\n  // target Cx>=-d\n  {\n    auto t = Type::GREATER_THAN;\n    auto r = RHS::OPPOSITE;\n    sMem->randomize();\n    AssignmentTarget at(sRange, sMem->A, sMem->b, t, r);\n    checkSubstitutionAssignment(c, subs, at, *sMem, t, r, throws[5]);\n  }\n  // target Cx<=0\n  {\n    auto t = Type::LOWER_THAN;\n    auto r = RHS::ZERO;\n    AssignmentTarget at(sRange, sMem->A, t);\n    checkSubstitutionAssignment(c, subs, at, *sMem, t, r, throws[6]);\n  }\n  // target Cx<=d\n  {\n    auto t = Type::LOWER_THAN;\n    auto r = RHS::AS_GIVEN;\n    AssignmentTarget at(sRange, sMem->A, sMem->b, t, r);\n    checkSubstitutionAssignment(c, subs, at, *sMem, t, r, throws[7]);\n  }\n  // target Cx<=-d\n  {\n    auto t = Type::LOWER_THAN;\n    auto r = RHS::OPPOSITE;\n    sMem->randomize();\n    AssignmentTarget at(sRange, sMem->A, sMem->b, t, r);\n    checkSubstitutionAssignment(c, subs, at, *sMem, t, r, throws[8]);\n  }\n  // target l<=Cx<=u\n  {\n    auto t = Type::DOUBLE_SIDED;\n    auto r = RHS::AS_GIVEN;\n    AssignmentTarget at(dRange, dMem->A, dMem->l, dMem->u, r);\n    checkSubstitutionAssignment(c, subs, at, *dMem, t, r, throws[9]);\n  }\n  // target -l<=Cx<=-u\n  {\n    auto t = Type::DOUBLE_SIDED;\n    auto r = RHS::AS_GIVEN;\n    AssignmentTarget at(dRange, dMem->A, dMem->l, dMem->u, r);\n    checkSubstitutionAssignment(c, subs, at, *dMem, t, r, throws[10]);\n  }\n}\n\n/** Check the assignement of a bound \\p c to a target */\nvoid checkSimpleBound(BLCPtr c)\n{\n  auto dMem = std::make_shared<Memory>(1, 1);\n  auto dRange = std::make_shared<Range>(0, 1);\n  \n  // target l<=x<=u\n  AssignmentTarget at(dRange, dMem->l, dMem->u);\n  checkBoundAssignment(c, at, *dMem);\n}\n\nvoid checkSimpleBound(BLCPtr c1, BLCPtr c2)\n{\n  auto dMem = std::make_shared<Memory>(1, 1);\n  auto dRange = std::make_shared<Range>(0, 1);\n\n  // target l<=x<=u\n  AssignmentTarget at(dRange, dMem->l, dMem->u);\n  checkBoundAssignment(c1, c2, at, *dMem);\n}\n\n// test for correct signs on the matrices and vector\nTEST_CASE(\"Test simple assignment\")\n{\n  Constraints cstr = buildSimpleConstraints();\n  using T = std::vector<bool>;\n  const bool t = true;\n  const bool f = false;\n  // constraint Ax = 0\n  {\n    //     Cx=0,  Cx=d,  Cx=-d,  Cx>=0,  Cx>=d, Cx>=-d,  Cx<=0,  Cx<=d, Cx<=-d,l<=Cx<=u,-l<=Cx<=-u\n    T v = { f,      f,      f,      t,      t,      t,      t,      t,      t,      f,      f };\n    checkSimple(cstr.Ax_eq_0, v);\n  }\n  // constraint Ax >= 0\n  {\n    //     Cx=0,  Cx=d,  Cx=-d,  Cx>=0,  Cx>=d, Cx>=-d,  Cx<=0,  Cx<=d, Cx<=-d,l<=Cx<=u,-l<=Cx<=-u\n    T v = { t,      t,      t,      f,      f,      f,      f,      f,      f,      f,      f };\n    checkSimple(cstr.Ax_geq_0, v);\n  }\n  // constraint Ax <= 0\n  {\n    //     Cx=0,  Cx=d,  Cx=-d,  Cx>=0,  Cx>=d, Cx>=-d,  Cx<=0,  Cx<=d, Cx<=-d,l<=Cx<=u,-l<=Cx<=-u\n    T v = { t,      t,      t,      f,      f,      f,      f,      f,      f,      f,      f };\n    checkSimple(cstr.Ax_leq_0, v);\n  }\n  // constraint Ax = d\n  {\n    //     Cx=0,  Cx=d,  Cx=-d,  Cx>=0,  Cx>=d, Cx>=-d,  Cx<=0,  Cx<=d, Cx<=-d,l<=Cx<=u,-l<=Cx<=-u\n    T v = { t,      f,      f,      t,      t,      t,      t,      t,      t,      f,      f };\n    checkSimple(cstr.Ax_eq_b, v);\n  }\n  // constraint Ax >= d\n  {\n    //     Cx=0,  Cx=d,  Cx=-d,  Cx>=0,  Cx>=d, Cx>=-d,  Cx<=0,  Cx<=d, Cx<=-d,l<=Cx<=u,-l<=Cx<=-u\n    T v = { t,      t,      t,      t,      f,      f,      t,      f,      f,      f,      f };\n    checkSimple(cstr.Ax_geq_b, v);\n  }\n  // constraint Ax <= d\n  {\n    //     Cx=0,  Cx=d,  Cx=-d,  Cx>=0,  Cx>=d, Cx>=-d,  Cx<=0,  Cx<=d, Cx<=-d,l<=Cx<=u,-l<=Cx<=-u\n    T v = { t,      t,      t,      t,      f,      f,      t,      f,      f,      f,      f };\n    checkSimple(cstr.Ax_leq_b, v);\n  }\n  // constraint Ax = -d\n  {\n    //     Cx=0,  Cx=d,  Cx=-d,  Cx>=0,  Cx>=d, Cx>=-d,  Cx<=0,  Cx<=d, Cx<=-d,l<=Cx<=u,-l<=Cx<=-u\n    T v = { t,      f,      f,      t,      t,      t,      t,      t,      t,      f,      f };\n    checkSimple(cstr.Ax_eq_minus_b, v);\n  }\n  // constraint Ax >= -d\n  {\n    //     Cx=0,  Cx=d,  Cx=-d,  Cx>=0,  Cx>=d, Cx>=-d,  Cx<=0,  Cx<=d, Cx<=-d,l<=Cx<=u,-l<=Cx<=-u\n    T v = { t,      t,      t,      t,      f,      f,      t,      f,      f,      f,      f };\n    checkSimple(cstr.Ax_geq_minus_b, v);\n  }\n  // constraint Ax <= -d\n  {\n    //     Cx=0,  Cx=d,  Cx=-d,  Cx>=0,  Cx>=d, Cx>=-d,  Cx<=0,  Cx<=d, Cx<=-d,l<=Cx<=u,-l<=Cx<=-u\n    T v = { t,      t,      t,      t,      f,      f,      t,      f,      f,      f,      f };\n    checkSimple(cstr.Ax_leq_minus_b, v);\n  }\n  // constraint l <= Ax <= u\n  {\n    //     Cx=0,  Cx=d,  Cx=-d,  Cx>=0,  Cx>=d, Cx>=-d,  Cx<=0,  Cx<=d, Cx<=-d,l<=Cx<=u,-l<=Cx<=-u\n    T v = { t,      t,      t,      t,      f,      f,      t,      f,      f,      f,      f };\n    checkSimple(cstr.l_leq_Ax_leq_u, v);\n  }\n  // constraint -l <= Ax <= -u\n  {\n    //     Cx=0,  Cx=d,  Cx=-d,  Cx>=0,  Cx>=d, Cx>=-d,  Cx<=0,  Cx<=d, Cx<=-d,l<=Cx<=u,-l<=Cx<=-u\n    T v = { t,      t,      t,      t,      f,      f,      t,      f,      f,      f,      f };\n    checkSimple(cstr.l_leq_Ax_leq_u, v);\n  }\n\n  //now the bounds\n  checkSimpleBound(cstr.Ax_eq_0);\n  checkSimpleBound(cstr.Ax_geq_0);\n  checkSimpleBound(cstr.Ax_leq_0);\n  checkSimpleBound(cstr.Ax_eq_b);\n  checkSimpleBound(cstr.Ax_geq_b);\n  checkSimpleBound(cstr.Ax_leq_b);\n  checkSimpleBound(cstr.Ax_eq_minus_b);\n  checkSimpleBound(cstr.Ax_geq_minus_b);\n  checkSimpleBound(cstr.Ax_leq_minus_b);\n  checkSimpleBound(cstr.l_leq_Ax_leq_u);\n  checkSimpleBound(cstr.minus_l_leq_Ax_leq_minus_u);\n\n  //with -Identity\n  auto cstr2 = buildSimpleConstraints(-1, cstr.Ax_eq_0->variables()[0]);\n  checkSimpleBound(cstr2.Ax_eq_0);\n  checkSimpleBound(cstr2.Ax_geq_0);\n  checkSimpleBound(cstr2.Ax_leq_0);\n  checkSimpleBound(cstr2.Ax_eq_b);\n  checkSimpleBound(cstr2.Ax_geq_b);\n  checkSimpleBound(cstr2.Ax_leq_b);\n  checkSimpleBound(cstr2.Ax_eq_minus_b);\n  checkSimpleBound(cstr2.Ax_geq_minus_b);\n  checkSimpleBound(cstr2.Ax_leq_minus_b);\n  checkSimpleBound(cstr2.l_leq_Ax_leq_u);\n  checkSimpleBound(cstr2.minus_l_leq_Ax_leq_minus_u);\n\n  // with diagonal\n  auto cstr3 = buildSimpleConstraints(2, cstr.Ax_eq_0->variables()[0]);\n  checkSimpleBound(cstr3.Ax_eq_0);\n  checkSimpleBound(cstr3.Ax_geq_0);\n  checkSimpleBound(cstr3.Ax_leq_0);\n  checkSimpleBound(cstr3.Ax_eq_b);\n  checkSimpleBound(cstr3.Ax_geq_b);\n  checkSimpleBound(cstr3.Ax_leq_b);\n  checkSimpleBound(cstr3.Ax_eq_minus_b);\n  checkSimpleBound(cstr3.Ax_geq_minus_b);\n  checkSimpleBound(cstr3.Ax_leq_minus_b);\n  checkSimpleBound(cstr3.l_leq_Ax_leq_u);\n  checkSimpleBound(cstr3.minus_l_leq_Ax_leq_minus_u);\n\n  // with diagonal (negative)\n  auto cstr4 = buildSimpleConstraints(-2, cstr.Ax_eq_0->variables()[0]);\n  checkSimpleBound(cstr4.Ax_eq_0);\n  checkSimpleBound(cstr4.Ax_geq_0);\n  checkSimpleBound(cstr4.Ax_leq_0);\n  checkSimpleBound(cstr4.Ax_eq_b);\n  checkSimpleBound(cstr4.Ax_geq_b);\n  checkSimpleBound(cstr4.Ax_leq_b);\n  checkSimpleBound(cstr4.Ax_eq_minus_b);\n  checkSimpleBound(cstr4.Ax_geq_minus_b);\n  checkSimpleBound(cstr4.Ax_leq_minus_b);\n  checkSimpleBound(cstr4.l_leq_Ax_leq_u);\n  checkSimpleBound(cstr4.minus_l_leq_Ax_leq_minus_u);\n\n  std::vector<BLCPtr> c1 = {cstr.Ax_eq_0, cstr.Ax_geq_0, cstr.Ax_leq_0, cstr.Ax_eq_b,\n                            cstr.Ax_geq_b, cstr.Ax_leq_b, cstr.Ax_eq_minus_b, cstr.Ax_geq_minus_b,\n                            cstr.Ax_leq_minus_b, cstr.l_leq_Ax_leq_u, cstr.minus_l_leq_Ax_leq_minus_u };\n  std::vector<BLCPtr> c2 = {cstr2.Ax_eq_0, cstr2.Ax_geq_0, cstr2.Ax_leq_0, cstr2.Ax_eq_b,\n                            cstr2.Ax_geq_b, cstr2.Ax_leq_b, cstr2.Ax_eq_minus_b, cstr2.Ax_geq_minus_b,\n                            cstr2.Ax_leq_minus_b, cstr2.l_leq_Ax_leq_u, cstr2.minus_l_leq_Ax_leq_minus_u };\n\n  //check the intersection of bounds constraints\n  for (size_t i = 0; i < 11; ++i)\n  {\n    for (size_t j = 0; j < 11; ++j)\n    {\n      checkSimpleBound(c1[i], c1[j]);\n      checkSimpleBound(c1[i], c2[j]);\n    }\n  }\n}\n\nTEST_CASE(\"Test assignements with substitution\")\n{\n  auto p0 = buildSimpleSubstitution(RHS::ZERO);\n  auto p1 = buildSimpleSubstitution(RHS::AS_GIVEN);\n  auto p2 = buildSimpleSubstitution(RHS::OPPOSITE);\n  Substitution s0(p0.second, p0.second->variables()[1]); //substitution of y\n  Substitution s1(p1.second, p1.second->variables()[1]); //substitution of y\n  Substitution s2(p2.second, p2.second->variables()[1]); //substitution of y\n  \n  using T = std::vector<bool>;\n  const bool t = true;\n  const bool f = false;\n  // constraint Ax = 0\n  {\n    //      Cx=0,  Cx=d,  Cx=-d,  Cx>=0,  Cx>=d, Cx>=-d,  Cx<=0,  Cx<=d, Cx<=-d,l<=Cx<=u,-l<=Cx<=-u\n    T v0 = { f,      f,      f,      t,      t,      t,      t,      t,      t,      f,      f };\n    T v1 = { t,      f,      f,      t,      t,      t,      t,      t,      t,      f,      f };\n    T v2 = { t,      f,      f,      t,      t,      t,      t,      t,      t,      f,      f };\n\n    checkSimple(p0.first.Ax_eq_0, s0, v0);\n    checkSimple(p1.first.Ax_eq_0, s1, v1);\n    checkSimple(p2.first.Ax_eq_0, s2, v2);\n  }\n\n  // constraint Ax >= 0\n  {\n    //      Cx=0,  Cx=d,  Cx=-d,  Cx>=0,  Cx>=d, Cx>=-d,  Cx<=0,  Cx<=d, Cx<=-d,l<=Cx<=u,-l<=Cx<=-u\n    T v0 = { t,      t,      t,      f,      f,      f,      f,      f,      f,      f,      f };\n    T v1 = { t,      t,      t,      t,      f,      f,      t,      f,      f,      f,      f };\n    T v2 = { t,      t,      t,      t,      f,      f,      t,      f,      f,      f,      f };\n\n    checkSimple(p0.first.Ax_geq_0, s0, v0);\n    checkSimple(p1.first.Ax_geq_0, s1, v1);\n    checkSimple(p2.first.Ax_geq_0, s2, v2);\n  }\n\n  // constraint Ax <= 0\n  {\n    //      Cx=0,  Cx=d,  Cx=-d,  Cx>=0,  Cx>=d, Cx>=-d,  Cx<=0,  Cx<=d, Cx<=-d,l<=Cx<=u,-l<=Cx<=-u\n    T v0 = { t,      t,      t,      f,      f,      f,      f,      f,      f,      f,      f };\n    T v1 = { t,      t,      t,      t,      f,      f,      t,      f,      f,      f,      f };\n    T v2 = { t,      t,      t,      t,      f,      f,      t,      f,      f,      f,      f };\n\n    checkSimple(p0.first.Ax_leq_0, s0, v0);\n    checkSimple(p1.first.Ax_leq_0, s1, v1);\n    checkSimple(p2.first.Ax_leq_0, s2, v2);\n  }\n\n  // constraint Ax = 0\n  {\n    //      Cx=0,  Cx=d,  Cx=-d,  Cx>=0,  Cx>=d, Cx>=-d,  Cx<=0,  Cx<=d, Cx<=-d,l<=Cx<=u,-l<=Cx<=-u\n    T v0 = { t,      f,      f,      t,      t,      t,      t,      t,      t,      f,      f };\n    T v1 = { t,      f,      f,      t,      t,      t,      t,      t,      t,      f,      f };\n    T v2 = { t,      f,      f,      t,      t,      t,      t,      t,      t,      f,      f };\n\n    checkSimple(p0.first.Ax_eq_b, s0, v0);\n    checkSimple(p1.first.Ax_eq_b, s1, v1);\n    checkSimple(p2.first.Ax_eq_b, s2, v2);\n  }\n\n  // constraint Ax >= b\n  {\n    //      Cx=0,  Cx=d,  Cx=-d,  Cx>=0,  Cx>=d, Cx>=-d,  Cx<=0,  Cx<=d, Cx<=-d,l<=Cx<=u,-l<=Cx<=-u\n    T v0 = { t,      t,      t,      t,      f,      f,      t,      f,      f,      f,      f };\n    T v1 = { t,      t,      t,      t,      f,      f,      t,      f,      f,      f,      f };\n    T v2 = { t,      t,      t,      t,      f,      f,      t,      f,      f,      f,      f };\n\n    checkSimple(p0.first.Ax_geq_b, s0, v0);\n    checkSimple(p1.first.Ax_geq_b, s1, v1);\n    checkSimple(p2.first.Ax_geq_b, s2, v2);\n  }\n\n  // constraint Ax <= b\n  {\n    //      Cx=0,  Cx=d,  Cx=-d,  Cx>=0,  Cx>=d, Cx>=-d,  Cx<=0,  Cx<=d, Cx<=-d,l<=Cx<=u,-l<=Cx<=-u\n    T v0 = { t,      t,      t,      t,      f,      f,      t,      f,      f,      f,      f };\n    T v1 = { t,      t,      t,      t,      f,      f,      t,      f,      f,      f,      f };\n    T v2 = { t,      t,      t,      t,      f,      f,      t,      f,      f,      f,      f };\n\n    checkSimple(p0.first.Ax_leq_b, s0, v0);\n    checkSimple(p1.first.Ax_leq_b, s1, v1);\n    checkSimple(p2.first.Ax_leq_b, s2, v2);\n  }\n\n  // constraint Ax >= b\n  {\n    //      Cx=0,  Cx=d,  Cx=-d,  Cx>=0,  Cx>=d, Cx>=-d,  Cx<=0,  Cx<=d, Cx<=-d,l<=Cx<=u,-l<=Cx<=-u\n    T v0 = { t,      t,      t,      t,      f,      f,      t,      f,      f,      f,      f };\n    T v1 = { t,      t,      t,      t,      f,      f,      t,      f,      f,      f,      f };\n    T v2 = { t,      t,      t,      t,      f,      f,      t,      f,      f,      f,      f };\n\n    checkSimple(p0.first.l_leq_Ax_leq_u, s0, v0);\n    checkSimple(p1.first.l_leq_Ax_leq_u, s1, v1);\n    checkSimple(p2.first.l_leq_Ax_leq_u, s2, v2);\n  }\n\n  // constraint Ax <= b\n  {\n    //      Cx=0,  Cx=d,  Cx=-d,  Cx>=0,  Cx>=d, Cx>=-d,  Cx<=0,  Cx<=d, Cx<=-d,l<=Cx<=u,-l<=Cx<=-u\n    T v0 = { t,      t,      t,      t,      f,      f,      t,      f,      f,      f,      f };\n    T v1 = { t,      t,      t,      t,      f,      f,      t,      f,      f,      f,      f };\n    T v2 = { t,      t,      t,      t,      f,      f,      t,      f,      f,      f,      f };\n\n    checkSimple(p0.first.minus_l_leq_Ax_leq_minus_u, s0, v0);\n    checkSimple(p1.first.minus_l_leq_Ax_leq_minus_u, s1, v1);\n    checkSimple(p2.first.minus_l_leq_Ax_leq_minus_u, s2, v2);\n  }\n}\n\nTEST_CASE(\"Test assigments\")\n{\n  Constraints cstr = buildConstraints(3, 7);\n\n  {\n    auto mem = std::make_shared<Memory>(6, 7);\n    //assignment to a target with convention l <= Ax <= u, from convention Ax >= -b\n    auto range = std::make_shared<Range>(2, 3);\n    AssignmentTarget at(range, mem->A, mem->l, mem->u , RHS::AS_GIVEN);\n    auto req = std::make_shared<SolvingRequirements>(Weight(2.));\n    VariableVector vv(cstr.Ax_eq_0->variables());\n    Assignment a(cstr.Ax_geq_minus_b, req, at, vv);\n    a.run();\n\n    {\n      const auto & cstr_A = cstr.Ax_geq_minus_b->jacobian(*cstr.Ax_geq_minus_b->variables()[0]);\n      const auto & cstr_l = cstr.Ax_geq_minus_b->l();\n      FAST_CHECK_EQ(mem->A.block(range->start, 0, 3, 7), sqrt(2)*cstr_A);\n      FAST_CHECK_EQ(mem->l.block(range->start, 0, 3, 1), -sqrt(2)*cstr_l);\n      FAST_CHECK_EQ(mem->u.block(range->start, 0, 3, 1), sqrt(2)*VectorXd(3).setConstant(large));\n    }\n\n    FAST_CHECK_EQ(check(cstr.Ax_geq_minus_b, cstr.p0), check(*mem.get(), at.constraintType(), at.constraintRhs(), cstr.p0));\n    FAST_CHECK_EQ(check(cstr.Ax_geq_minus_b, cstr.pl), check(*mem.get(), at.constraintType(), at.constraintRhs(), cstr.pl));\n    FAST_CHECK_EQ(check(cstr.Ax_geq_minus_b, cstr.pu), check(*mem.get(), at.constraintType(), at.constraintRhs(), cstr.pu));\n\n    //now we change the range of the target and refresh the assignment\n    range->start = 0;\n    a.onUpdatedTarget();\n    mem->A.setZero();\n    mem->l.setZero();\n    mem->u.setZero();\n    a.run();\n\n    {\n      const auto & cstr_A = cstr.Ax_geq_minus_b->jacobian(*cstr.Ax_geq_minus_b->variables()[0]);\n      const auto & cstr_l = cstr.Ax_geq_minus_b->l();\n      FAST_CHECK_EQ(mem->A.block(range->start, 0, 3, 7), sqrt(2)*cstr_A);\n      FAST_CHECK_EQ(mem->l.block(range->start, 0, 3, 1), -sqrt(2)*cstr_l);\n      FAST_CHECK_EQ(mem->u.block(range->start, 0, 3, 1), sqrt(2)*VectorXd(3).setConstant(large));\n    }\n  }\n\n  {\n    auto mem = std::make_shared<Memory>(6, 7);\n    //assignment to a target with convention Ax <= b, from convention l <= Ax <= u\n    auto range = std::make_shared<Range>(0, 6); //we need double range\n    AssignmentTarget at(range, mem->A, mem->b, Type::LOWER_THAN, RHS::AS_GIVEN);\n    Vector3d aW = {1., 2., 3.};\n    auto req = std::make_shared<SolvingRequirements>(AnisotropicWeight{ aW });\n    VariableVector vv(cstr.Ax_eq_0->variables());\n    Assignment a(cstr.l_leq_Ax_leq_u, req, at, vv);\n    a.run();\n\n    {\n      const auto & cstr_A = cstr.l_leq_Ax_leq_u->jacobian(*cstr.l_leq_Ax_leq_u->variables()[0]);\n      const auto & cstr_l = cstr.l_leq_Ax_leq_u->l();\n      const auto & cstr_u = cstr.l_leq_Ax_leq_u->u();\n      for(size_t i = 0; i < 3; ++i)\n      {\n        FAST_CHECK_EQ(mem->A.row(i), sqrt(aW(i))*cstr_A.row(i));\n        FAST_CHECK_EQ(mem->A.row(i + 3), -sqrt(aW(i))*cstr_A.row(i));\n        FAST_CHECK_EQ(mem->b(i), sqrt(aW(i))*cstr_u(i));\n        FAST_CHECK_EQ(mem->b(i + 3), -sqrt(aW(i))*cstr_l(i));\n      }\n    }\n\n    FAST_CHECK_EQ(check(cstr.l_leq_Ax_leq_u, cstr.p0), check(*mem.get(), at.constraintType(), at.constraintRhs(), cstr.p0));\n    FAST_CHECK_EQ(check(cstr.l_leq_Ax_leq_u, cstr.pl), check(*mem.get(), at.constraintType(), at.constraintRhs(), cstr.pl));\n    FAST_CHECK_EQ(check(cstr.l_leq_Ax_leq_u, cstr.pu), check(*mem.get(), at.constraintType(), at.constraintRhs(), cstr.pu));\n  }\n}\n", "meta": {"hexsha": "dc3a14ffe314740366100452c73a1064c7d7ef5c", "size": 36001, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/AssignmentTest.cpp", "max_stars_repo_name": "gergondet/tvm", "max_stars_repo_head_hexsha": "e40c11ada9ba8d3e875072d77843e49845b267b9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/AssignmentTest.cpp", "max_issues_repo_name": "gergondet/tvm", "max_issues_repo_head_hexsha": "e40c11ada9ba8d3e875072d77843e49845b267b9", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/AssignmentTest.cpp", "max_forks_repo_name": "gergondet/tvm", "max_forks_repo_head_hexsha": "e40c11ada9ba8d3e875072d77843e49845b267b9", "max_forks_repo_licenses": ["BSD-3-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.0380658436, "max_line_length": 168, "alphanum_fraction": 0.5865948168, "num_tokens": 13187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.46533066657191635}}
{"text": "///////////////////////////////////////////////////////////////\n//  Copyright 2012 John Maddock. Distributed under the Boost\n//  Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_\n\n//\n// Compare arithmetic results using fixed_int to GMP results.\n//\n\n#ifdef _MSC_VER\n#  define _SCL_SECURE_NO_WARNINGS\n#endif\n\n#include <boost/multiprecision/integer.hpp>\n#include \"test.hpp\"\n\n#ifdef BOOST_MSVC\n#pragma warning(disable:4146)\n#endif\n\ntemplate <class I, class H>\nvoid test()\n{\n   using namespace boost::multiprecision;\n\n   I i(0);\n\n   BOOST_CHECK_THROW(lsb(i), std::range_error);\n   BOOST_CHECK(bit_test(bit_set(i, 0), 0));\n   BOOST_CHECK_EQUAL(bit_set(i, 0), 1);\n   BOOST_CHECK_EQUAL(bit_unset(i, 0), 0);\n   BOOST_CHECK_EQUAL(bit_flip(bit_set(i, 0), 0), 0);\n\n   unsigned max_index = (std::numeric_limits<I>::digits) - 1;\n   BOOST_CHECK(bit_test(bit_set(i, max_index), max_index));\n   BOOST_CHECK_EQUAL(bit_unset(i, max_index), 0);\n   BOOST_CHECK_EQUAL(bit_flip(bit_set(i, max_index), max_index), 0);\n\n   if(std::numeric_limits<I>::is_signed)\n   {\n      i = static_cast<I>(-1);\n      BOOST_CHECK_THROW(lsb(i), std::range_error);\n   }\n\n   H mx = (std::numeric_limits<H>::max)();\n\n   BOOST_CHECK_EQUAL(multiply(i, mx, mx), static_cast<I>(mx) * static_cast<I>(mx));\n   BOOST_CHECK_EQUAL(add(i, mx, mx), static_cast<I>(mx) + static_cast<I>(mx));\n   if(std::numeric_limits<I>::is_signed)\n   {\n      BOOST_CHECK_EQUAL(subtract(i, mx, static_cast<H>(-mx)), static_cast<I>(mx) - static_cast<I>(-mx));\n      BOOST_CHECK_EQUAL(add(i, static_cast<H>(-mx), static_cast<H>(-mx)), static_cast<I>(-mx) + static_cast<I>(-mx));\n   }\n\n   i = (std::numeric_limits<I>::max)();\n   I j = 12345;\n   I r, q;\n   divide_qr(i, j, q, r);\n   BOOST_CHECK_EQUAL(q, i / j);\n   BOOST_CHECK_EQUAL(r, i % j);\n   BOOST_CHECK_EQUAL(integer_modulus(i, j), i % j);\n   I p = 456;\n   BOOST_CHECK_EQUAL(powm(i, p, j), pow(cpp_int(i), static_cast<unsigned>(p)) % j);\n}\n\nint main()\n{\n   using namespace boost::multiprecision;\n\n   test<boost::int32_t, boost::int16_t>();\n   test<boost::int64_t, boost::int32_t>();\n   test<boost::uint32_t, boost::uint16_t>();\n   test<boost::uint64_t, boost::uint32_t>();\n   \n   return boost::report_errors();\n}\n\n\n\n", "meta": {"hexsha": "0e55822a39d392ef62ffb64aee7752a157e3b997", "size": 2262, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/multiprecision/test/test_native_integer.cpp", "max_stars_repo_name": "ai-nikolaev/repo-cppboost", "max_stars_repo_head_hexsha": "218c4a977c6d8cd6f2864cdcea1b6ab53160d203", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2016-04-12T16:29:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-28T11:01:57.000Z", "max_issues_repo_path": "libs/multiprecision/test/test_native_integer.cpp", "max_issues_repo_name": "ai-nikolaev/repo-cppboost", "max_issues_repo_head_hexsha": "218c4a977c6d8cd6f2864cdcea1b6ab53160d203", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-10-31T19:35:14.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-04T17:11:27.000Z", "max_forks_repo_path": "libs/multiprecision/test/test_native_integer.cpp", "max_forks_repo_name": "ai-nikolaev/repo-cppboost", "max_forks_repo_head_hexsha": "218c4a977c6d8cd6f2864cdcea1b6ab53160d203", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-09-09T02:38:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-30T00:24:24.000Z", "avg_line_length": 28.275, "max_line_length": 117, "alphanum_fraction": 0.6525198939, "num_tokens": 649, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.46533066657191635}}
{"text": "// Copyright Louis Dionne 2013-2016\r\n// Distributed under the Boost Software License, Version 1.0.\r\n// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\r\n\r\n#include <boost/hana/any_of.hpp>\r\n#include <boost/hana/assert.hpp>\r\n#include <boost/hana/config.hpp>\r\n#include <boost/hana/ext/std/integral_constant.hpp>\r\n#include <boost/hana/integral_constant.hpp>\r\n#include <boost/hana/mod.hpp>\r\n#include <boost/hana/not.hpp>\r\n#include <boost/hana/not_equal.hpp>\r\n#include <boost/hana/tuple.hpp>\r\n#include <boost/hana/type.hpp>\r\n\r\n#include <type_traits>\r\nnamespace hana = boost::hana;\r\nusing namespace hana::literals;\r\n\r\n\r\nBOOST_HANA_CONSTEXPR_LAMBDA auto is_odd = [](auto x) {\r\n    return x % 2_c != 0_c;\r\n};\r\n\r\nint main() {\r\n    BOOST_HANA_CONSTEXPR_CHECK(hana::any_of(hana::make_tuple(1, 2), is_odd));\r\n    BOOST_HANA_CONSTANT_CHECK(!hana::any_of(hana::make_tuple(2_c, 4_c), is_odd));\r\n\r\n    BOOST_HANA_CONSTANT_CHECK(hana::any_of(\r\n        hana::make_tuple(hana::type_c<void>, hana::type_c<char&>), hana::trait<std::is_void>\r\n    ));\r\n    BOOST_HANA_CONSTANT_CHECK(!hana::any_of(\r\n        hana::make_tuple(hana::type_c<void>, hana::type_c<char&>), hana::trait<std::is_integral>\r\n    ));\r\n}\r\n", "meta": {"hexsha": "cb5e743da26fcdc88b3c3b545a3cbf1b888825e3", "size": 1215, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "thirdparty-cpp/boost_1_62_0/libs/hana/example/any_of.cpp", "max_stars_repo_name": "nxplatform/nx-mobile", "max_stars_repo_head_hexsha": "0dc174c893f2667377cb2ef7e5ffeb212fa8b3e5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-12-15T19:57:24.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-15T19:57:24.000Z", "max_issues_repo_path": "thirdparty-cpp/boost_1_62_0/libs/hana/example/any_of.cpp", "max_issues_repo_name": "nxplatform/nx-mobile", "max_issues_repo_head_hexsha": "0dc174c893f2667377cb2ef7e5ffeb212fa8b3e5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thirdparty-cpp/boost_1_62_0/libs/hana/example/any_of.cpp", "max_forks_repo_name": "nxplatform/nx-mobile", "max_forks_repo_head_hexsha": "0dc174c893f2667377cb2ef7e5ffeb212fa8b3e5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.75, "max_line_length": 97, "alphanum_fraction": 0.7020576132, "num_tokens": 336, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.46533066657191635}}
{"text": "#ifndef PA_MATH_VECTOR_FIELD_HPP\n#define PA_MATH_VECTOR_FIELD_HPP\n\n#include <memory>\n\n#include <boost/multi_array.hpp>\n\n#include <pa/math/tensor_field.hpp>\n#include <pa/math/types.hpp>\n#include <pa/export.hpp>\n\nnamespace pa\n{\nstruct PA_EXPORT vector_field\n{\n  bool                          contains   (const vector4& position) const;\n  vector3                       interpolate(const vector4& position) const;\n  std::unique_ptr<tensor_field> gradient   ();\n  \n  boost::multi_array<vector3, 3> data    {};\n  vector3                        offset  {};\n  vector3                        size    {};\n  vector3                        spacing {};\n};\n}\n\n#endif", "meta": {"hexsha": "72c2775ed73827262bfe468725c3fe6786c24b08", "size": 652, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pa/include/pa/math/vector_field.hpp", "max_stars_repo_name": "acdemiralp/pars", "max_stars_repo_head_hexsha": "e78876de860a4cd2751e3a4e314e2a42a10ea10d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-03-12T18:20:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T12:04:14.000Z", "max_issues_repo_path": "pa/include/pa/math/vector_field.hpp", "max_issues_repo_name": "acdemiralp/pars", "max_issues_repo_head_hexsha": "e78876de860a4cd2751e3a4e314e2a42a10ea10d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pa/include/pa/math/vector_field.hpp", "max_forks_repo_name": "acdemiralp/pars", "max_forks_repo_head_hexsha": "e78876de860a4cd2751e3a4e314e2a42a10ea10d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-18T14:35:49.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-18T14:35:49.000Z", "avg_line_length": 24.1481481481, "max_line_length": 75, "alphanum_fraction": 0.5950920245, "num_tokens": 136, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.752012562644147, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.46533065969376947}}
{"text": "//\n//  Copyright Toon Knapen, Karl Meerbergen\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#include \"ublas_heev.hpp\"\n\n#include <boost/numeric/bindings/lapack/hegv.hpp>\n#include <boost/numeric/bindings/traits/ublas_matrix.hpp>\n#include <boost/numeric/bindings/traits/ublas_vector.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/vector_proxy.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n#include <iostream>\n\n\nnamespace ublas = boost::numeric::ublas;\nnamespace lapack = boost::numeric::bindings::lapack;\n\n\ntemplate <typename T, typename W, char UPLO>\nint do_memory_uplo(int n, W& workspace ) {\n   typedef typename boost::numeric::bindings::traits::type_traits<T>::real_type real_type ;\n\n   typedef ublas::matrix<T, ublas::column_major>     matrix_type ;\n   typedef ublas::vector<real_type>                  vector_type ;\n\n   // Set matrix\n   matrix_type a( n, n ); a.clear();\n   vector_type e1( n );\n   vector_type e2( n );\n\n   fill( a );\n   matrix_type a2( a );\n\n   matrix_type b( n, n ); b.clear();\n   for (int i = 0; i < n; ++i) b(i,i) = 1;\n\n   // Compute eigen decomposition.\n   lapack::hegv( 1, 'V', UPLO, a, b, e1, workspace ) ;\n\n   if (check_residual( a2, e1, a )) return 255 ;\n\n   lapack::hegv( 1, 'N', UPLO, a2, b, e2, workspace ) ;\n   if (norm_2( e1 - e2 ) > n * norm_2( e1 ) * std::numeric_limits< real_type >::epsilon()) return 255 ;\n\n   // Test for a matrix range\n   fill( a ); a2.assign( a );\n\n   typedef ublas::matrix_range< matrix_type > matrix_range ;\n\n   ublas::range r(1,n-1) ;\n   matrix_range a_r( a, r, r );\n   ublas::vector_range< vector_type> e_r( e1, r );\n   matrix_range b_r( b, r, r );\n\n   lapack::hegv(1, 'V', UPLO,  a_r, b_r, e_r, workspace );\n\n   matrix_range a2_r( a2, r, r );\n   if (check_residual( a2_r, e_r, a_r )) return 255 ;\n\n   return 0 ;\n} // do_memory_uplo()\n\n\ntemplate <typename T, typename W>\nint do_memory_type(int n, W workspace) {\n   std::cout << \"  upper\\n\" ;\n   if (do_memory_uplo<T,W,'U'>(n, workspace)) return 255 ;\n   std::cout << \"  lower\\n\" ;\n   if (do_memory_uplo<T,W,'L'>(n, workspace)) return 255 ;\n   return 0 ;\n}\n\n\ntemplate <typename T>\nstruct Workspace {\n   typedef ublas::vector<T>                         array_type ;\n   typedef lapack::detail::workspace1< array_type > type ;\n\n   Workspace(size_t n)\n   : work_( 3*n-1 )\n   {}\n\n   type operator() () {\n      return type( work_ );\n   }\n\n   array_type work_ ;\n};\n\ntemplate <typename T>\nstruct Workspace< std::complex<T> > {\n   typedef ublas::vector<T>                                                 real_array_type ;\n   typedef ublas::vector< std::complex<T> >                                 complex_array_type ;\n   typedef lapack::detail::workspace2< complex_array_type,real_array_type > type ;\n\n   Workspace(size_t n)\n   : work_( 2*n-1 )\n   , rwork_( 3*n-2 )\n   {}\n\n   type operator() () {\n      return type( work_, rwork_ );\n   }\n\n   complex_array_type work_ ;\n   real_array_type    rwork_ ;\n};\n\ntemplate <typename T>\nint do_value_type() {\n   const int n = 8 ;\n\n   std::cout << \" optimal workspace\\n\";\n   if (do_memory_type<T,lapack::optimal_workspace>( n, lapack::optimal_workspace() ) ) return 255 ;\n\n   std::cout << \" minimal workspace\\n\";\n   if (do_memory_type<T,lapack::minimal_workspace>( n, lapack::minimal_workspace() ) ) return 255 ;\n\n   std::cout << \" workspace array\\n\";\n   Workspace<T> work( n );\n   do_memory_type<T,typename Workspace<T>::type >( n, work() );\n   return 0;\n} // do_value_type()\n\n\nint main() {\n   // Run tests for different value_types\n   std::cout << \"float\\n\" ;\n   if (do_value_type<float>()) return 255;\n\n   std::cout << \"double\\n\" ;\n   if (do_value_type<double>()) return 255;\n\n   std::cout << \"complex<float>\\n\" ;\n   if (do_value_type< std::complex<float> >()) return 255;\n\n   std::cout << \"complex<double>\\n\" ;\n   if (do_value_type< std::complex<double> >()) return 255;\n\n   std::cout << \"Regression test succeeded\\n\" ;\n   return 0;\n}\n\n", "meta": {"hexsha": "a3b09900d37addb9762fdb5a3cf20374f0aa21d7", "size": 4031, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/bindings/lapack/test/ublas_hegv.cpp", "max_stars_repo_name": "inducer/boost-numeric-bindings", "max_stars_repo_head_hexsha": "1f994e8a2e161cddb6577eacc76b7bc358701cbe", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-14T19:18:21.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-14T19:18:21.000Z", "max_issues_repo_path": "libs/numeric/bindings/lapack/test/ublas_hegv.cpp", "max_issues_repo_name": "inducer/boost-numeric-bindings", "max_issues_repo_head_hexsha": "1f994e8a2e161cddb6577eacc76b7bc358701cbe", "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/numeric/bindings/lapack/test/ublas_hegv.cpp", "max_forks_repo_name": "inducer/boost-numeric-bindings", "max_forks_repo_head_hexsha": "1f994e8a2e161cddb6577eacc76b7bc358701cbe", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-23T09:56:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-23T09:56:06.000Z", "avg_line_length": 26.8733333333, "max_line_length": 103, "alphanum_fraction": 0.6296204416, "num_tokens": 1182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.752012562644147, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.46533065969376947}}
{"text": "#ifndef PWALK_JOHN_WALKER_HPP_\n#define PWALK_JOHN_WALKER_HPP_\n\n#include <cmath>\n#include <Eigen/Dense>\n#include \"util/math_functions.hpp\"\n#include \"walker.hpp\"\n\nnamespace pwalk {\n\ntemplate <typename Dtype>\nclass JohnWalker: public Walker<Dtype> {\npublic:\n  JohnWalker(const Eigen::Matrix<Dtype, Eigen::Dynamic, 1>& initialization, const Eigen::Matrix<Dtype, Eigen::Dynamic, Eigen::Dynamic>& cons_A, const Eigen::Matrix<Dtype, Eigen::Dynamic, 1>& cons_b, const Dtype r) : Walker<Dtype>(initialization, cons_A, cons_b), r_(r), alpha_(1. - 1. / std::log2(2.*Dtype(cons_A.rows())/Dtype(cons_A.cols()))), beta_(Dtype(cons_A.cols())/2./Dtype(cons_A.rows())), curr_weight_(Eigen::Matrix<Dtype, Eigen::Dynamic, 1>::Ones(cons_A.rows())){}\n\n  // getter for radius\n  Dtype getRadius() {\n    return r_;\n  }\n\n  void proposal(Eigen::Matrix<Dtype, Eigen::Dynamic, 1>& new_sample);\n\n  bool acceptRejectReverse(const Eigen::Matrix<Dtype, Eigen::Dynamic, 1>& new_sample);\n\n  bool doSample(Eigen::Matrix<Dtype, Eigen::Dynamic, 1>& new_sample, const Dtype lazy = Dtype(0.5));\n\n  void sqrtInvHessBarrier(const Eigen::Matrix<Dtype, Eigen::Dynamic, 1>& new_sample, Eigen::Matrix<Dtype, Eigen::Dynamic, Eigen::Dynamic>& new_sqrt_inv_hess);\n\nprivate:\n  const Dtype r_;\n  const Dtype alpha_;\n  const Dtype beta_;\n\n  Eigen::Matrix<Dtype, Eigen::Dynamic, 1> curr_weight_;\n};\n\n} // namespace pwalk\n\n#endif // PWALK_JOHN_WALKER_HPP_\n\n", "meta": {"hexsha": "3fb8cce2a6f1bb5f62a412c11eb222d664d7c492", "size": 1404, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "polytopewalk/src/john_walker.hpp", "max_stars_repo_name": "yuachen/polytopewalk", "max_stars_repo_head_hexsha": "7e7431594489b5d5b6fe9947b4ccab21eee11152", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2018-11-16T19:35:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T01:02:56.000Z", "max_issues_repo_path": "polytopewalk/src/john_walker.hpp", "max_issues_repo_name": "yuachen/polytopewalk", "max_issues_repo_head_hexsha": "7e7431594489b5d5b6fe9947b4ccab21eee11152", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-10-06T11:15:29.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-06T11:15:29.000Z", "max_forks_repo_path": "polytopewalk/src/john_walker.hpp", "max_forks_repo_name": "yuachen/polytopewalk", "max_forks_repo_head_hexsha": "7e7431594489b5d5b6fe9947b4ccab21eee11152", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-06-16T18:11:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-12T23:13:27.000Z", "avg_line_length": 34.243902439, "max_line_length": 474, "alphanum_fraction": 0.7272079772, "num_tokens": 399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.752012562644147, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.46533065969376947}}
{"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_GESV_HPP\n#define BOOST_NUMERIC_BINDINGS_LAPACK_GESV_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/lapack/workspace.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\n\nnamespace boost { namespace numeric { namespace bindings {\n\n  namespace lapack {\n\n    ///////////////////////////////////////////////////////////////////\n    //\n    // general system of linear equations A * X = B\n    //\n    ///////////////////////////////////////////////////////////////////\n\n    /*\n     * gesv() computes the solution to a system of linear equations \n     * A * X = B, where A is an N-by-N matrix and X and B are N-by-NRHS \n     * matrices.\n     *\n     * The LU decomposition with partial pivoting and row interchanges\n     * is used to factor A as A = P * L * U, where P is a permutation\n     * matrix, L is unit lower triangular, and U is upper triangular.\n     * The factored form of A is then used to solve the system of\n     * equations A * X = B.\n     */\n\n    namespace detail {\n\n      inline\n      void gesv (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, integer_t* info)\n      {\n        LAPACK_SGESV (&n, &nrhs, a, &lda, ipiv, b, &ldb, info);\n      }\n\n      inline\n      void gesv (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, integer_t* info)\n      {\n        LAPACK_DGESV (&n, &nrhs, a, &lda, ipiv, b, &ldb, info);\n      }\n\n      inline\n      void gesv (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, integer_t* info)\n      {\n        LAPACK_CGESV (&n, &nrhs,\n                      traits::complex_ptr (a), &lda, ipiv,\n                      traits::complex_ptr (b), &ldb, info);\n      }\n\n      inline\n      void gesv (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, integer_t* info)\n      {\n        LAPACK_ZGESV (&n, &nrhs,\n                      traits::complex_ptr (a), &lda, ipiv,\n                      traits::complex_ptr (b), &ldb, info);\n      }\n\n    } //namespace detail\n\n    template <typename MatrA, typename MatrB, typename IVec>\n    int gesv (MatrA& a, IVec& ipiv, MatrB& b) {\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrA>::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      assert (n == traits::matrix_size2 (a));\n      assert (n == traits::matrix_size1 (b));\n      assert (n == traits::vector_size (ipiv));\n\n      integer_t info;\n      detail::gesv (n, traits::matrix_size2 (b),\n                    traits::matrix_storage (a),\n                    traits::leading_dimension (a),\n                    traits::vector_storage (ipiv),\n                    traits::matrix_storage (b),\n                    traits::leading_dimension (b),\n                    &info);\n      return info;\n    }\n\n    template <typename MatrA, typename MatrB>\n    int gesv (MatrA& a, MatrB& b) {\n      // with 'internal' pivot vector\n\n      // gesv() errors:\n      //   if (info == 0), successful\n      //   if (info < 0), the -info argument had an illegal value\n      //   -- we will use -101 if allocation fails\n      //   if (info > 0), U(i-1,i-1) is exactly zero\n      integer_t info = -101;\n      traits::detail::array<integer_t> ipiv (traits::matrix_size1 (a));\n      if (ipiv.valid())\n        info = gesv (a, ipiv, b);\n      return info;\n    }\n\n\n    /*\n     * getrf() computes an LU factorization of a general M-by-N matrix A\n     * using partial pivoting with row interchanges. The factorization\n     * has the form A = P * L * U, where P is a permutation matrix,\n     * L is lower triangular with unit diagonal elements (lower\n     * trapezoidal if M > N), and U is upper triangular (upper\n     * trapezoidal if M < N).\n     */\n\n    namespace detail {\n\n      inline\n      void getrf (integer_t const n, integer_t const m,\n                  float* a, integer_t const lda, integer_t* ipiv, integer_t* info)\n      {\n        LAPACK_SGETRF (&n, &m, a, &lda, ipiv, info);\n      }\n\n      inline\n      void getrf (integer_t const n, integer_t const m,\n                  double* a, integer_t const lda, integer_t* ipiv, integer_t* info)\n      {\n        LAPACK_DGETRF (&n, &m, a, &lda, ipiv, info);\n      }\n\n      inline\n      void getrf (integer_t const n, integer_t const m,\n                  traits::complex_f* a, integer_t const\n                  lda, integer_t* ipiv, integer_t* info)\n      {\n        LAPACK_CGETRF (&n, &m, traits::complex_ptr (a), &lda, ipiv, info);\n      }\n\n      inline\n      void getrf (integer_t const n, integer_t const m,\n                  traits::complex_d* a, integer_t const lda,\n                  integer_t* ipiv, integer_t* info)\n      {\n        LAPACK_ZGETRF (&n, &m, traits::complex_ptr (a), &lda, ipiv, info);\n      }\n\n    } //namespace detail\n\n    template <typename MatrA, typename IVec>\n    int getrf (MatrA& a, IVec& ipiv) {\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrA>::matrix_structure,\n        traits::general_t\n      >::value));\n#endif\n\n      integer_t const n = traits::matrix_size1 (a);\n      integer_t const m = traits::matrix_size2 (a);\n      assert (traits::vector_size (ipiv) == (m < n ? m : n));\n\n      integer_t info;\n      detail::getrf (n, m,\n                     traits::matrix_storage (a),\n                     traits::leading_dimension (a),\n                     traits::vector_storage (ipiv),\n                     &info);\n      return info;\n    }\n\n\n    /*\n     * getrs() solves a system of linear equations A * X = B\n     * or A^T * X = B with a general N-by-N matrix A using\n     * the LU factorization computed by getrf().\n     */\n\n    namespace detail {\n\n      inline\n      void getrs (char const trans, 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_SGETRS (&trans, &n, &nrhs, a, &lda, ipiv, b, &ldb, info);\n      }\n\n      inline\n      void getrs (char const trans, 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_DGETRS (&trans, &n, &nrhs, a, &lda, ipiv, b, &ldb, info);\n      }\n\n      inline\n      void getrs (char const trans, 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_CGETRS (&trans, &n, &nrhs,\n                       traits::complex_ptr (a), &lda, ipiv,\n                       traits::complex_ptr (b), &ldb, info);\n      }\n\n      inline\n      void getrs (char const trans, 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_ZGETRS (&trans, &n, &nrhs,\n                       traits::complex_ptr (a), &lda, ipiv,\n                       traits::complex_ptr (b), &ldb, info);\n      }\n\n    } // namespace detail\n\n    template <typename MatrA, typename MatrB, typename IVec>\n    int getrs (char const trans, MatrA const& a, IVec const& ipiv, MatrB& b)\n    {\n      assert (trans == 'N' || trans == 'T' || trans == 'C');\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrA>::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      assert (n == traits::matrix_size2 (a));\n      assert (n == traits::matrix_size1 (b));\n      assert (n == traits::vector_size (ipiv));\n\n      integer_t info;\n      detail::getrs (trans, 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 (ipiv),\n#else\n                     traits::vector_storage_const (ipiv),\n#endif\n                     traits::matrix_storage (b),\n                     traits::leading_dimension (b),\n                     &info);\n      return info;\n    }\n\n    template <typename MatrA, typename MatrB, typename IVec>\n    inline\n    int getrs (MatrA const& a, IVec const& ipiv, MatrB& b) {\n      char const no_transpose = 'N';\n      return getrs (no_transpose, a, ipiv, b);\n    }\n\n    /*\n     * getri() computes the inverse of a matrix using\n     * the LU factorization computed by getrf().\n     */\n\n    namespace detail {\n\n      inline\n      void getri (integer_t const n, float* a, integer_t const lda, integer_t const* ipiv,\n                  float* work, integer_t const lwork, integer_t* info)\n      {\n        LAPACK_SGETRI (&n, a, &lda, ipiv, work, &lwork, info);\n      }\n\n      inline\n      void getri (integer_t const n, double* a, integer_t const lda, integer_t const* ipiv,\n                  double* work, integer_t const lwork, integer_t* info)\n      {\n        LAPACK_DGETRI (&n, a, &lda, ipiv, work, &lwork, info);\n      }\n\n      inline\n      void getri (integer_t const n, traits::complex_f* a, integer_t const lda,\n          integer_t const* ipiv, traits::complex_f* work, integer_t const lwork,\n          integer_t* info)\n      {\n        LAPACK_CGETRI (&n, traits::complex_ptr (a), &lda, ipiv,\n            traits::complex_ptr (work), &lwork, info);\n      }\n\n      inline\n      void getri (integer_t const n, traits::complex_d* a, integer_t const lda,\n          integer_t const* ipiv, traits::complex_d* work, integer_t const lwork,\n          integer_t* info)\n      {\n        LAPACK_ZGETRI (&n, traits::complex_ptr (a), &lda, ipiv,\n            traits::complex_ptr (work), &lwork, info);\n      }\n\n\n\n      template <typename MatrA, typename IVec, typename Work>\n      int getri (MatrA& a, IVec const& ipiv, Work& work)\n      {\n        #ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK\n        BOOST_STATIC_ASSERT((boost::is_same<\n              typename traits::matrix_traits<MatrA>::matrix_structure,\n              traits::general_t\n              >::value));\n        #endif\n\n        integer_t const n = traits::matrix_size1 (a);\n        assert (n > 0);\n        assert (n <= traits::leading_dimension (a));\n        assert (n == traits::matrix_size2 (a));\n        assert (n == traits::vector_size (ipiv));\n        assert (n <= traits::vector_size (work)); //Minimal workspace size\n\n        integer_t info;\n        //double* dummy = traits::matrix_storage (a);\n        detail::getri (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            traits::vector_size (work),\n            &info);\n        return info;\n      }\n\n\n      inline\n      integer_t getri_block(float)\n      {\n        return lapack::ilaenv(1, \"sgetri\", \"\");\n      }\n\n      inline\n      integer_t getri_block(double)\n      {\n        return lapack::ilaenv(1, \"dgetri\", \"\");\n      }\n\n      inline\n      integer_t getri_block(traits::complex_f)\n      {\n        return lapack::ilaenv(1, \"cgetri\", \"\");\n      }\n\n      inline\n      integer_t getri_block(traits::complex_d)\n      {\n        return lapack::ilaenv(1, \"zgetri\", \"\");\n      }\n\n    } // namespace detail\n\n\n    template <typename MatrA, typename IVec>\n    int getri(MatrA& a, IVec& ipiv, minimal_workspace)\n    {\n      typedef typename MatrA::value_type value_type;\n\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::getri(a, ipiv, work);\n\n    }\n\n\n    // optimal workspace allocation\n    template <typename MatrA, typename IVec>\n    int getri(MatrA& a, IVec& ipiv, optimal_workspace)\n    {\n      typedef typename MatrA::value_type value_type;\n\n      std::ptrdiff_t n = traits::matrix_size1(a);\n      std::ptrdiff_t nb = detail::getri_block(value_type());\n      traits::detail::array<value_type> work(std::max<std::ptrdiff_t>(1,n*nb));\n\n      return detail::getri(a, ipiv, work);\n    }\n\n\n    template <typename MatrA, typename IVec>\n    inline\n    int getri(MatrA& a, IVec& ipiv)\n    {\n      return getri(a, ipiv, optimal_workspace());\n    }\n\n\n    template <typename MatrA, typename IVec, typename Work>\n    inline\n    int getri(MatrA& a, IVec& ipiv, Work& work)\n    {\n      return detail::getri(a, ipiv, work);\n    }\n\n  } // namespace lapack\n\n}}} // namespace boost::numeric::bindings\n\n\n\n\n#endif\n", "meta": {"hexsha": "2e87d4616fd71f327ac4ac087ddf6771ef037c17", "size": 14379, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/boost/numeric/bindings/lapack/gesv.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/gesv.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/gesv.hpp", "max_forks_repo_name": "diku-dk/PROX", "max_forks_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.6021978022, "max_line_length": 91, "alphanum_fraction": 0.5845329995, "num_tokens": 3707, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.752012562644147, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.46533065969376947}}
{"text": "#include <boost/test/unit_test.hpp>\n\n#include \"Werk/Math/DiscreteDistribution.hpp\"\n\nBOOST_AUTO_TEST_SUITE(DiscreteDistributionTest)\n\nBOOST_AUTO_TEST_CASE(TestEmpty)\n{\n\tWerk::DiscreteDistribution<double> d;\n\tBOOST_REQUIRE_EQUAL(d.sampleCount(), 0);\n\tBOOST_REQUIRE_EQUAL(d.weightCount(), 0);\n\tBOOST_REQUIRE_EQUAL(d.weightSum(), 0.0);\n}\n\nBOOST_AUTO_TEST_CASE(TestBasic)\n{\n\tWerk::DiscreteDistribution<double> d;\n\td.sample(1.0, 1.0);\n\td.sample(2.0, 0.5);\n\td.sample(3.0, 1.0);\n\tBOOST_REQUIRE_EQUAL(d.sampleCount(), 3);\n\tBOOST_REQUIRE_EQUAL(d.weightCount(), 3);\n\tBOOST_REQUIRE_EQUAL(d.weightSum(), 2.5);\n\n\td.sample(2.0, 1.5);\n\tBOOST_REQUIRE_EQUAL(d.sampleCount(), 4);\n\tBOOST_REQUIRE_EQUAL(d.weightCount(), 3);\n\tBOOST_REQUIRE_EQUAL(d.weightSum(), 4.0);\n\n\tBOOST_REQUIRE_EQUAL(d.pdf(1.0), 0.25);\n\tBOOST_REQUIRE_EQUAL(d.pdf(2.0), 0.5);\n\tBOOST_REQUIRE_EQUAL(d.pdf(3.0), 0.25);\n\n\tBOOST_REQUIRE_EQUAL(d.cdf(1.0), 0.25);\n\tBOOST_REQUIRE_EQUAL(d.cdf(2.0), 0.75);\n\tBOOST_REQUIRE_EQUAL(d.cdf(2.9), 0.75);\n\tBOOST_REQUIRE_EQUAL(d.cdf(3.0), 1.0);\n\tBOOST_REQUIRE_EQUAL(d.cdf(4.0), 1.0);\n}\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "654720b4d6d608c11031f3b3dfbe736c8e6c4b9d", "size": 1094, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/WerkTest/Math/DiscreteDistribution.cpp", "max_stars_repo_name": "mish24/werk", "max_stars_repo_head_hexsha": "2f8822842fb8f68a4402775d1d3b41021b5a9945", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/WerkTest/Math/DiscreteDistribution.cpp", "max_issues_repo_name": "mish24/werk", "max_issues_repo_head_hexsha": "2f8822842fb8f68a4402775d1d3b41021b5a9945", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/WerkTest/Math/DiscreteDistribution.cpp", "max_forks_repo_name": "mish24/werk", "max_forks_repo_head_hexsha": "2f8822842fb8f68a4402775d1d3b41021b5a9945", "max_forks_repo_licenses": ["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.6829268293, "max_line_length": 47, "alphanum_fraction": 0.7367458867, "num_tokens": 342, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.4653154579348865}}
{"text": "#define BOOST_DISABLE_ASSERTS\r\n#include <boost/config.hpp>\r\n#include <boost/graph/adjacency_list.hpp>\r\n#include <boost/graph/push_relabel_max_flow.hpp>\r\n#include <boost/graph/graph_utility.hpp>\r\n#include <boost/graph/filtered_graph.hpp>\r\n#include <boost/graph/breadth_first_search.hpp>\r\n#include \"MaxFlowDouble.hpp\"\r\nusing namespace std;\r\nusing namespace boost;\r\n\r\nNetwork::Network(): g(), rev(get(edge_reverse, g)), capacity(get(edge_capacity, g)), residual_capacity(get(edge_residual_capacity, g)) {}\r\n\r\nNetwork::Vertex Network::AddVertex() {\r\n  return add_vertex(g);\r\n}\r\n\r\nNetwork::Edge Network::AddEdge(Vertex &v1, Vertex &v2, const double capacity) {\r\n  Traits::edge_descriptor e1 = add_edge(v1, v2, g).first;\r\n  Traits::edge_descriptor e2 = add_edge(v2, v1, g).first;\r\n  put(edge_capacity, g, e1, capacity);\r\n  rev[e1] = e2;\r\n  rev[e2] = e1;\r\n  return e1;\r\n}\r\n\r\ndouble Network::MaxFlow(Vertex &s, Vertex &t) {\r\n  return push_relabel_max_flow(g, s, t); // Boost library also provides boykov_kolmogorov_max_flow (needs \"#include <boost/graph/boykov_kolmogorov_max_flow.hpp>\")\r\n}\r\n\r\nstruct Network::NonSaturatedEdges {\r\n  NonSaturatedEdges() {}\r\n  NonSaturatedEdges(property_map<Graph, edge_residual_capacity_t>::type residual_capacity):\r\n    residual_capacity(residual_capacity) {}\r\n  property_map<Graph, edge_residual_capacity_t>::type residual_capacity;\r\n  bool operator ()(const Edge &e) const {\r\n    return residual_capacity[e] > 1e-9;\r\n  }\r\n};\r\n\r\nvoid Network::BfsOnResidualGraph(Vertex &s) {\r\n  NonSaturatedEdges filter(get(edge_residual_capacity, g));\r\n  filtered_graph<Graph, NonSaturatedEdges> fg(g, filter);\r\n  color = get(vertex_color, g);\r\n  boost::queue<Vertex> Q;\r\n  default_bfs_visitor vis;\r\n  breadth_first_search(fg, s, Q, vis, color);\r\n}\r\n", "meta": {"hexsha": "0afa460fe33778204c8a0a4423ffb80479f2f034", "size": 1761, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "MaxFlowDouble.cpp", "max_stars_repo_name": "btsun/kclistpp", "max_stars_repo_head_hexsha": "2704e72c8fa26a4be1adaa4ee8128456811ade99", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MaxFlowDouble.cpp", "max_issues_repo_name": "btsun/kclistpp", "max_issues_repo_head_hexsha": "2704e72c8fa26a4be1adaa4ee8128456811ade99", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MaxFlowDouble.cpp", "max_forks_repo_name": "btsun/kclistpp", "max_forks_repo_head_hexsha": "2704e72c8fa26a4be1adaa4ee8128456811ade99", "max_forks_repo_licenses": ["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.9387755102, "max_line_length": 163, "alphanum_fraction": 0.7331061897, "num_tokens": 454, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.4653154579348865}}
{"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#ifndef SOLVERS_CUSPARSESOLVER_HPP\n#define SOLVERS_CUSPARSESOLVER_HPP\n\n#include <Eigen/Dense>\n\n#include <solvers/Solver.hpp>\n#include <solvers/SparseSystem.hpp>\n\nnamespace solvers {\n\nenum class CuSparseMethod { QR, Cholesky };\nenum class CuSparseReorder { None, SymRCM, SymAMD, METIS };\n\n/**\n * \\brief CuSparseSolver Direct solver based on cuSPARSE library.\n */\nclass CuSparseSolver : public Solver {\nprivate:\n    /**\n     * \\brief _method Resolution algorithm.\n     */\n    CuSparseMethod _method;\n\n    /**\n     * \\brief _reorder Algorithm of node reordering used to reduce fill-in.\n     */\n    CuSparseReorder _reorder;\n\npublic:\n    explicit CuSparseSolver(\n        const CuSparseMethod method = CuSparseMethod::Cholesky,\n        const CuSparseReorder reorder = CuSparseReorder::METIS)\n        : _method(method), _reorder(reorder){};\n\n    Eigen::VectorXd solve(const SparseSystem& system,\n                          double& duration) const override;\n};\n\n}    // namespace solvers\n\n#endif    // SOLVERS_CUSPARSESOLVER_HPP", "meta": {"hexsha": "8fbd59835d9696371f5b66c6c5db8684b8e00030", "size": 1619, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "solvers/include/solvers/CuSparseSolver.hpp", "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/include/solvers/CuSparseSolver.hpp", "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/include/solvers/CuSparseSolver.hpp", "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": 28.9107142857, "max_line_length": 75, "alphanum_fraction": 0.7164916615, "num_tokens": 380, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.46531545793488643}}
{"text": "/**\n * @file\n * @brief Implementation of the make_QuadRuleNodal.\n * @author Raffael Casagrande\n * @date   2018-12-26 10:25:52\n * @copyright MIT License\n */\n\n#include \"make_quad_rule_nodal.h\"\n#include <boost/core/ref.hpp>\n\nnamespace lf::quad {\nQuadRule make_QuadRuleNodal(base::RefEl ref_el) {\n  double ref_el_vol = 1.0;\n  if (ref_el == base::RefEl::kTria()) {\n    ref_el_vol = 0.5;\n  }\n  return QuadRule(ref_el, ref_el.NodeCoords(),\n                  Eigen::VectorXd::Constant(ref_el.NumNodes(),\n                                            ref_el_vol / ref_el.NumNodes()),\n                  1);\n}\n}  // namespace lf::quad\n", "meta": {"hexsha": "5c8e4f2d2d257f58e9cd2bf3666863b8f5037a95", "size": 622, "ext": "cc", "lang": "C++", "max_stars_repo_path": "lib/lf/quad/make_quad_rule_nodal.cc", "max_stars_repo_name": "Pascal-So/lehrfempp", "max_stars_repo_head_hexsha": "e2716e914169eec7ee59e822ea3ab303143eacd1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib/lf/quad/make_quad_rule_nodal.cc", "max_issues_repo_name": "Pascal-So/lehrfempp", "max_issues_repo_head_hexsha": "e2716e914169eec7ee59e822ea3ab303143eacd1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/lf/quad/make_quad_rule_nodal.cc", "max_forks_repo_name": "Pascal-So/lehrfempp", "max_forks_repo_head_hexsha": "e2716e914169eec7ee59e822ea3ab303143eacd1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9166666667, "max_line_length": 76, "alphanum_fraction": 0.6028938907, "num_tokens": 176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.46531545793488643}}
{"text": "//  Copyright (c) 2021 DNV AS\n//\n//  Distributed under the Boost Software License, Version 1.0.\n//  See accompanying file LICENSE_1_0.txt or copy at\n//  http://www.boost.org/LICENSE_1_0.txt\n\n#include <jsScript/jsMath.h>\n#include <jsScript/jsClass.h>\n#include <jsScript/jsUnitValue.h>\n#include <jsScript/jsQuantity.h>\n#include <limits>\n#include <stdlib.h>\n#include <time.h>\n#include <cmath>\n#include \"Units/Angle.h\"\n#include \"Units/Runtime/DynamicQuantity.h\"\n#include \"Units/Math.h\"\n#include \"Reflection/Classes/Class.h\"\n#include \"Reflection/Attributes/ExampleAttribute.h\"\n#include <Reflection/Containers/ReflectVector.h>\n#include \"Reflection/Members/GlobalType.h\"\n#include \"jsMathImpl.h\"\n\n/*#include <boost/math/special_functions/acosh.hpp>\n#include <boost/math/special_functions/asinh.hpp>\n#include <boost/math/special_functions/atanh.hpp>*/\n//////////////////////////////////////////////////////////////////////\n// Construction/Destruction\n//////////////////////////////////////////////////////////////////////\nusing namespace DNVS::MoFa::Units;\nusing namespace DNVS::MoFa::Units::Runtime;\nusing namespace DNVS::MoFa::Reflection::Classes;\nusing namespace std;\n\nvoid jsMath::init(jsTypeLibrary& typeLibrary)\n{\n    srand((unsigned)time(NULL));\n\n    using namespace DNVS::MoFa::Reflection::Classes;\n    Class<jsMath> cls(typeLibrary.GetReflectionTypeLibrary(), \"Math\");\n    cls.AddDocumentation(\"The Math object - methods\");\n\n    cls.StaticFunction(\"timer\", [](long t0) { return long(time(nullptr) - t0); })\n        .AddDocumentation(\"for performance test, returns the lapsed time in seconds since t0\")\n        .AddSignature(\"t0\")\n        .AddAttribute<ExampleAttribute>(\n            \"Math.timer(0); //Returns time in seconds since 1. January 1970\\n\"\n            \"t0 = Math.timer(0);  //Initialises the variable a\\n\"\n            \"t  = Math.timer(t0); //Computes time difference in seconds since when variable t0 was set\\n\"\n            \"print(t);            //Writes lapsed time to the journal file window\\n\");\n\n    cls.StaticGet(\"E\", 2.7182818284590452354)\n        .AddDocumentation(\"The number value for e, the base of the natural logarithms, which is approximately 2.7182818284590452354\")\n        .AddAttribute<ExampleAttribute>(\n            \"Math.ln(E); //Returns 1\"\n            \"Math.pow(E,5); //The same as Math.exp(5)\");\n    cls.StaticGet(\"LN10\", 2.302585092994046).AddDocumentation(\"The number value for the natural logarithm of 10, which is approximately 2.302585092994046\");\n    cls.StaticGet(\"LN2\", 0.6931471805599453).AddDocumentation(\"The number value for the natural logarithm of 2, which is approximately 0.6931471805599453\");\n    cls.StaticGet(\"LOG2E\", 1.4426950408889634).AddDocumentation(\"The number value for the base-2 logarithm of e, the base of the natural logarithms; this value is approximately 1.4426950408889634\");\n    cls.StaticGet(\"LOG10E\", 0.4342944819032518).AddDocumentation(\"The number value for the base-10 logarithm of e, the base of the natural logarithms; this value is approximately 0.4342944819032518\");\n    cls.StaticGet(\"PI\", 3.1415926535897932).AddDocumentation(\"The number value for &#960;, the ratio of the circumference of a circle to its diameter, which is approximately 3.1415926535897932\");\n    cls.StaticGet(\"SQRT1_2\", 0.7071067811865476).AddDocumentation(\"The number value for the square root of 1/2, which is approximately 0.7071067811865476\");\n    cls.StaticGet(\"SQRT2\", 1.4142135623730951).AddDocumentation(\"The number value for the square root of 2, which is approximately 1.4142135623730951\");\n\n    Class<DNVS::MoFa::Reflection::Members::GlobalType>(typeLibrary.GetReflectionTypeLibrary(), \"\")\n        .StaticGet(\"Math\", jsMath());\n    InitFunctionsForDouble<double>(cls);\n    InitFunctionsForUnits<DynamicQuantity>(cls);\n\n}\n\n", "meta": {"hexsha": "f24ba54acdfbc159ba85a6cc5201bb9282640ff9", "size": 3778, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "jsScript/jsMath.cpp", "max_stars_repo_name": "dnv-opensource/Reflection", "max_stars_repo_head_hexsha": "27effb850e9f0cc6acc2d48630ee6aa5d75fa000", "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": "jsScript/jsMath.cpp", "max_issues_repo_name": "dnv-opensource/Reflection", "max_issues_repo_head_hexsha": "27effb850e9f0cc6acc2d48630ee6aa5d75fa000", "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": "jsScript/jsMath.cpp", "max_forks_repo_name": "dnv-opensource/Reflection", "max_forks_repo_head_hexsha": "27effb850e9f0cc6acc2d48630ee6aa5d75fa000", "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": 52.4722222222, "max_line_length": 200, "alphanum_fraction": 0.7056643727, "num_tokens": 961, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.46531545793488643}}
{"text": "/*\n * BSD 2-Clause License\n *\n * Copyright (c) 2012-2019, CNRS-UM LIRMM, CNRS-AIST JRL\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n *    list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n *    this list of conditions and the following disclaimer in the documentation\n *    and/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n */\n\n// gtest\n#include <gtest/gtest.h>\n\n// Eigen\n#include <Eigen/Dense>\n\n// EigenQP\n#include \"eigen-qld/QLD.h\"\n\nstruct QP1 {\n  QP1() {\n    nrvar = 6;\n    nreq = 3;\n    nrineq = 2;\n\n    Q.resize(nrvar, nrvar);\n    Aeq.resize(nreq, nrvar);\n    Aineq.resize(nrineq, nrvar);\n    A.resize(nreq + nrineq, nrvar);\n\n    C.resize(nrvar);\n    Beq.resize(nreq);\n    Bineq.resize(nrineq);\n    B.resize(nreq + nrineq);\n    XL.resize(nrvar);\n    XU.resize(nrvar);\n    X.resize(nrvar);\n\n    Aeq << 1., -1., 1., 0., 3., 1., -1., 0., -3., -4., 5., 6., 2., 5., 3., 0., 1., 0.;\n    Beq << 1., 2., 3.;\n\n    Aineq << 0., 1., 0., 1., 2., -1., -1., 0., 2., 1., 1., 0.;\n    Bineq << -1., 2.5;\n\n    A.topRows(nreq) = Aeq;\n    A.bottomRows(nrineq) = -Aineq;\n\n    B.head(nreq) = -Beq;\n    B.tail(nrineq) = Bineq;\n\n    // with  x between ci and cs:\n    XL << -1000., -10000., 0., -1000., -1000., -1000.;\n    XU << 10000., 100., 1.5, 100., 100., 1000.;\n\n    // and minimize 0.5*x'*Q*x + p'*x with\n    C << 1., 2., 3., 4., 5., 6.;\n    Q.setIdentity();\n\n    X << 1.7975426, -0.3381487, 0.1633880, -4.9884023, 0.6054943, -3.1155623;\n  }\n\n  int nrvar, nreq, nrineq;\n  Eigen::MatrixXd Q, Aeq, Aineq, A;\n  Eigen::VectorXd C, Beq, Bineq, B, XL, XU, X;\n};\n\nvoid ineqWithXBounds(Eigen::MatrixXd& Aineq, Eigen::VectorXd& Bineq, const Eigen::VectorXd& XL, const Eigen::VectorXd& XU) {\n  double inf = std::numeric_limits<double>::infinity();\n\n  std::vector<std::pair<int, double>> lbounds, ubounds;\n\n  for (int i = 0; i < XL.rows(); ++i) {\n    if (XL[i] != -inf) lbounds.emplace_back(i, XL[i]);\n    if (XU[i] != inf) ubounds.emplace_back(i, XU[i]);\n  }\n\n  long int nrconstr = Bineq.rows() + static_cast<long int>(lbounds.size()) + static_cast<long int>(ubounds.size());\n\n  Eigen::MatrixXd A(Eigen::MatrixXd::Zero(nrconstr, Aineq.cols()));\n  Eigen::VectorXd B(Eigen::VectorXd::Zero(nrconstr));\n\n  A.block(0, 0, Aineq.rows(), Aineq.cols()) = Aineq;\n  B.segment(0, Bineq.rows()) = Bineq;\n\n  int start = static_cast<int>(Aineq.rows());\n\n  for (int i = 0; i < static_cast<int>(lbounds.size()); ++i) {\n    const auto& b = lbounds[i];\n    A(start, b.first) = -1.;\n    B(start) = -b.second;\n    ++start;\n  }\n\n  for (int i = 0; i < static_cast<int>(ubounds.size()); ++i) {\n    const auto& b = ubounds[i];\n    A(start, b.first) = 1.;\n    B(start) = b.second;\n    ++start;\n  }\n\n  Aineq = A;\n  Bineq = B;\n}\n\nTEST(QPTest, QLD) {  // NOLINT\n  QP1 qp1;\n  Eigen::QLD qld(qp1.nrvar, qp1.nreq, qp1.nrineq);\n  qld.solve(qp1.Q, qp1.C, qp1.Aeq, qp1.Beq, qp1.Aineq, qp1.Bineq, qp1.XL, qp1.XU);\n  ASSERT_NEAR((qld.result() - qp1.X).norm(), 0., 1e-6);\n  Eigen::QLDDirect qldd(qp1.nrvar, qp1.nreq, qp1.nrineq);\n  qldd.solve(qp1.Q, qp1.C, qp1.A, qp1.B, qp1.XL, qp1.XU, 3);\n  ASSERT_NEAR((qld.result() - qp1.X).norm(), 0., 1e-6);\n}\n\nTEST(QPTest, QLDSize) {  // NOLINT\n  QP1 qp1;\n  Eigen::QLD qld(qp1.nrvar, qp1.nreq + 10, qp1.nrineq + 22);\n  qld.solve(qp1.Q, qp1.C, qp1.Aeq, qp1.Beq, qp1.Aineq, qp1.Bineq, qp1.XL, qp1.XU);\n  ASSERT_NEAR((qld.result() - qp1.X).norm(), 0., 1e-6);\n}\n\nTEST(QPTest, IneqWithXBounds) {  // NOLINT\n  QP1 qp1;\n  ineqWithXBounds(qp1.Aineq, qp1.Bineq, qp1.XL, qp1.XU);\n  double inf = std::numeric_limits<double>::infinity();\n  for (int i = 0; i < qp1.nrvar; ++i) {\n    qp1.XL[i] = -inf;\n    qp1.XU[i] = inf;\n  }\n  int nrineq = static_cast<int>(qp1.Aineq.rows());\n  Eigen::QLD qld(qp1.nrvar, qp1.nreq, nrineq);\n  qld.solve(qp1.Q, qp1.C, qp1.Aeq, qp1.Beq, qp1.Aineq, qp1.Bineq, qp1.XL, qp1.XU);\n  ASSERT_NEAR((qld.result() - qp1.X).norm(), 0., 1e-6);\n}\n", "meta": {"hexsha": "ab90791945aa87a85abd52d656d314d7e760741e", "size": 4926, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/QPTest.cpp", "max_stars_repo_name": "ANYbotics/eigen-qld", "max_stars_repo_head_hexsha": "c7d2d8b84c59f15eafce5c7548578087f166d61b", "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": "test/QPTest.cpp", "max_issues_repo_name": "ANYbotics/eigen-qld", "max_issues_repo_head_hexsha": "c7d2d8b84c59f15eafce5c7548578087f166d61b", "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": "test/QPTest.cpp", "max_forks_repo_name": "ANYbotics/eigen-qld", "max_forks_repo_head_hexsha": "c7d2d8b84c59f15eafce5c7548578087f166d61b", "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.987012987, "max_line_length": 124, "alphanum_fraction": 0.6307348762, "num_tokens": 1759, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544335934766, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.465291288003294}}
{"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 <ceres/ceres.h>\n#include <ceres/rotation.h>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <glog/logging.h>\n\n#include \"gtest/gtest.h\"\n#include \"theia/math/util.h\"\n#include \"theia/sfm/transformation/align_rotations.h\"\n\nnamespace theia {\n\nnamespace {\n\nvoid ApplyRotation(const Eigen::Matrix3d& rotation_transformation,\n                   const double noise,\n                   Eigen::Vector3d* rotation) {\n  const Eigen::Matrix3d noisy_rotation =\n      Eigen::AngleAxisd(DegToRad(noise), Eigen::Vector3d::Random().normalized())\n          .toRotationMatrix();\n\n  // Apply the transformation to the rotation.\n  Eigen::Matrix3d rotation_mat;\n  ceres::AngleAxisToRotationMatrix(\n      rotation->data(), ceres::ColumnMajorAdapter3x3(rotation_mat.data()));\n  const Eigen::Matrix3d transformed_rotation =\n      rotation_mat * (noisy_rotation * rotation_transformation);\n\n  // Convert back to angle axis.\n  ceres::RotationMatrixToAngleAxis(\n      ceres::ColumnMajorAdapter3x3(transformed_rotation.data()),\n      rotation->data());\n}\n\nvoid TestAlignRotations(const int num_views,\n                        const double noise_degrees,\n                        const double tolerance) {\n  std::vector<Eigen::Vector3d> gt_rotations(num_views);\n  std::vector<Eigen::Vector3d> rotations(num_views);\n\n  Eigen::Matrix3d rotation_transformation = Eigen::AngleAxisd(\n      15.0, Eigen::Vector3d::Random().normalized()).toRotationMatrix();\n  for (int i = 0; i < num_views; i++) {\n    gt_rotations[i] = Eigen::Vector3d::Random();\n    rotations[i] = gt_rotations[i];\n    ApplyRotation(rotation_transformation, noise_degrees, &rotations[i]);\n  }\n\n  AlignRotations(gt_rotations, &rotations);\n\n  for (int i = 0; i < num_views; i++) {\n    EXPECT_LT((gt_rotations[i] - rotations[i]).norm(), tolerance);\n  }\n}\n\n}  // namespace\n\nTEST(AlignRotations, NoNoise) {\n  static const int kNumViews = 20;\n  static const double kTolerance = 1e-8;\n  static const double kNoise = 0.0;\n  TestAlignRotations(kNumViews, kNoise, kTolerance);\n}\n\nTEST(AlignRotations, Noise) {\n  static const int kNumViews = 20;\n  static const double kTolerance = 5e-2;\n  static const double kNoise = 1.0;\n  TestAlignRotations(kNumViews, kNoise, kTolerance);\n}\n\n}  // namespace theia\n", "meta": {"hexsha": "3ed546a18150548b024b6f655bae1ede1810e6d9", "size": 4034, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/sfm/transformation/align_rotations_test.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/transformation/align_rotations_test.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/transformation/align_rotations_test.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": 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": 37.7009345794, "max_line_length": 80, "alphanum_fraction": 0.7216162618, "num_tokens": 944, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.46529127966256}}
{"text": "/*\n *  carpack.hpp\n *  carpack\n *\n *  Created by Dr. Brandon Kelly on 12/19/12.\n *\n *  Header file containing the class definitions and function protoypes\n *  for CARMCMC.\n *\n */\n\n#ifndef __CARPACK_HDEF__\n#define __CARPACK_HDEF__\n\n#include <boost/math/special_functions/binomial.hpp>\n#include <stdexcept>\n#include <string>\n#include <memory>\n#include <random.hpp>\n#include <proposals.hpp>\n#include <samplers.hpp>\n#include <steps.hpp>\n#include <parameters.hpp>\n#include \"kfilter.hpp\"\n\n/*\n First-order continuous time autoregressive process (CAR(1)) class. Note that this is the same\n as an Ornstein-Uhlenbeck process. A CAR(1) process, Y(t), is defined as\n \n dY(t) = -omega * (Y(t) - mu) * dt + sigma * dW(t),\n \n where tau = 1 / omega is the \"characteristic time scale\" of the process, mu is the mean\n of the process, sigma is the amplitude of the driving noise, and the driving noise dW(t)\n is the derivative of the Weiner process (i.e., a white noise process). The variance of the\n process is Var(Y(t)) = sigma^2 / (2 * omega).\n \n The data member of this class include the time series values (y), the 1-sigma uncertainties \n on y (yerr), and the time values (time). Note that it is assumed that the CAR(1) process is \n Gaussian, and that the uncertainties on y are normally distributed with mean zero. The member \n functions of this class include methods to calculate the Kalman filter and the logarithms of the \n posterior probability distribution. The parameters of the CAR(1) process are held in\n the value_ private member, where value_ = (mu, log(omega), sigma) and tau = 1 / omega.\n \n The prior on theta is assumed to be uniform on theta, subject to the an upper bound\n on Var(Y(t)) and omega. The default value of the upper bound on Var(Y(t)) was chosen\n to be 6.9 (i.e., three orders of magnitude when Y(t) is the logarithm of some quantity), \n but this may be overriden through the use of the SetPrior method. The upper bound on\n omega is fixed to be 1 / min(dt), where dt is the vector of time steps.\n*/\n\ntemplate <class OmegaType>\nclass CARMA_Base : public Parameter<arma::vec> {\npublic:\n    // Constructors\n    CARMA_Base() {}\n    CARMA_Base(bool track, std::string name, std::vector<double> time, std::vector<double> y, std::vector<double> yerr,\n               double temperature=1.0) : Parameter<arma::vec>(track, name, temperature)\n    {\n        // default is to do Bayesian inference\n        ignore_prior_ = false;\n        \n        // Set the degrees of freedom for the prior on the measurement error scaling parameter\n        measerr_dof_ = 50;\n        \n        // convert input data to armadillo vectors\n        y_  = arma::conv_to<arma::vec>::from(y);\n        time_ = arma::conv_to<arma::vec>::from(time);\n        yerr_ = arma::conv_to<arma::vec>::from(yerr);\n        \n        // default prior bounds on the standard deviation of the time series\n        SetPrior(10.0 * sqrt(arma::var(y_)));\n    }\n    \n    virtual arma::vec StartingValue() = 0;\n    \n    std::string StringValue()\n    {\n        std::stringstream ss;\n        \n        ss << log_posterior_;\n        for (int i=0; i<value_.n_elem; i++) {\n            ss << \" \" << value_(i);\n        }\n                \n        std::string theta_str = ss.str();\n        return theta_str;\n    }\n\n    \n    void Save(arma::vec& new_value)\n    {\n        // new carma value ---> value_\n        value_ = new_value;\n        \n        // Update the log-posterior using this new value of theta.\n        //\n        // IMPORTANT: This assumes that the Kalman filter was calculated\n        // using the value of new_value.\n        //\n        log_posterior_ = 0.0;\n        double mu = new_value(2);\n        for (int i=0; i<time_.n_elem; i++) {\n            double ycent = y_(i) - pKFilter_->mean(i) - mu;\n            log_posterior_ += -0.5 * log(pKFilter_->var(i)) - 0.5 * ycent * ycent / pKFilter_->var(i);\n        }\n        log_posterior_ += LogPrior(new_value);\n\n    }\n    \n    // extract the lorentzian parameters from the CARMA parameter vector\n    virtual OmegaType ExtractAR(arma::vec theta) = 0;\n    // extract the moving-average parameters from the CARMA parameter vector\n    virtual arma::vec ExtractMA(arma::vec theta) = 0;\n    // extract the variance in the driving noise from the CARMA parameter vector\n    virtual double ExtractSigsqr(arma::vec theta) = 0;\n        \n    // compute the log-prior of the CARMA parameters\n    virtual double LogPrior(arma::vec theta)\n    {\n        double measerr_scale = theta(1);\n        \n        double logprior = -0.5 * measerr_dof_ / measerr_scale -\n        (1.0 + measerr_dof_ / 2.0) * log(measerr_scale);\n        \n        return logprior;\n    }\n    \n    virtual void PrintOmega(OmegaType omega) {};\n    \n    // compute the log-posterior\n    double LogDensity(arma::vec theta)\n    {\n        // Prior bounds satisfied?\n        bool prior_satisfied = CheckPriorBounds(theta);\n        if (!prior_satisfied) {\n            double logpost = -1.0 * arma::datum::inf;\n            return logpost;\n        }\n        \n        OmegaType omega = ExtractAR(theta);\n        arma::vec ma_coefs = ExtractMA(theta);\n        double sigsqr = ExtractSigsqr(theta);\n        double measerr_scale = theta(1);\n        double mu = theta(2);\n        \n        // Run the Kalman filter\n        pKFilter_->SetSigsqr(sigsqr);\n        pKFilter_->SetOmega(omega);\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        try {\n            pKFilter_->Filter();\n        } catch (std::runtime_error& e) {\n            std::cout << \"Caught a runtime error when trying to run the Kalman Filter: \" << e.what() << std::endl;\n            std::cout << \"Rejecting this proposal...\" << std::endl;\n            PrintOmega(omega);\n            bool prior_satisfied = CheckPriorBounds(theta);\n            std::cout << \"Prior satisfied: \" << prior_satisfied << std::endl;\n            double logpost = -1.0 * arma::datum::inf;\n            return logpost;\n        }\n        \n        // calculate the log-likelihood\n        double logpost = 0.0;\n        for (int i=0; i<time_.n_elem; i++) {\n            double ycent = y_(i) - pKFilter_->mean(i) - mu;\n            logpost += -0.5 * log(pKFilter_->var(i)) - 0.5 * ycent * ycent / pKFilter_->var(i);\n        }\n\n        logpost += LogPrior(theta);\n        \n        return logpost;\n    }\n    \n    bool virtual CheckPriorBounds(arma::vec theta)\n    {\n        if (ignore_prior_) {return true;}\n        \n        double ysigma = theta(0);\n        double measerr_scale = theta(1);\n        bool prior_satisfied = true;\n        if ( (ysigma > max_stdev_) || (ysigma < 0) ||\n            (measerr_scale < 0.5) || (measerr_scale > 2.0) )\n        {\n            prior_satisfied = false;\n        }\n        return prior_satisfied;\n    }\n    \n    // Setters and Getters\n    arma::vec GetTime() { return time_; }\n    arma::vec GetTimeSeries() { return y_; }\n    arma::vec GetTimeSeriesErr() { return yerr_; }\n    arma::vec GetKalmanMean() { return value_(2) + pKFilter_->mean; }\n    arma::vec GetKalmanVar() { return pKFilter_->var; }\n    std::shared_ptr<KalmanFilter<OmegaType> > GetKalmanPtr() { return pKFilter_; }\n    \n    virtual void SetPrior(double max_stdev) // set the bounds on the uniform prior\n    {\n        max_stdev_ = max_stdev;\n        arma::vec dt = time_(arma::span(1,time_.n_elem-1)) - time_(arma::span(0,time_.n_elem-2));\n        max_freq_ = 1.0 / dt.min();\n        min_freq_ = 1.0 / (time_.max() - time_.min());\n    }\n    \n    // Return a copy of the MCMC samples\n    std::vector<std::vector<double> > getSamples() {\n        int nx = samples_.size();\n        int ny = samples_[0].n_elem;\n        std::vector<std::vector<double> > samples(nx,std::vector<double>(ny));\n        for (int i = 0; i < nx; i++) {\n            samples[i] = arma::conv_to<std::vector<double> >::from(samples_[i]);\n        }\n        return samples;\n    }\n\n    // grab the log-prior and log-posterior for a std::vector input\n    double getLogPrior(std::vector<double> theta)\n    {\n        arma::vec armaVec = arma::conv_to<arma::vec>::from(theta);\n        return LogPrior(armaVec);\n    }\n    double getLogDensity(std::vector<double> theta)\n    {\n        arma::vec armaVec = arma::conv_to<arma::vec>::from(theta);\n        return LogDensity(armaVec);\n    }\n    \n    // set flag for maximum-likelihood estimation\n    void SetMLE(bool ignore_prior) {ignore_prior_ = ignore_prior;}\n    \nprotected:\n    // time series data\n    arma::vec time_;\n    arma::vec y_;\n    arma::vec yerr_;\n    // pointer to Kalman Filter object. The Kalman filter is the workhorse behind the likelihood calculations.\n    std::shared_ptr<KalmanFilter<OmegaType> > pKFilter_;\n    // prior parameters\n    double max_stdev_; // Maximum value of the standard deviation of the CAR(1) process\n\tdouble max_freq_; // Maximum value of omega = 1 / tau\n\tdouble min_freq_; // Minimum value of omega = 1 / tau\n\tint measerr_dof_; // Degrees of freedom for prior on measurement error scaling parameter\n    bool ignore_prior_; // If true, then do maximum-likelihood estimation\n};\n\n// class for a CAR(1) process\nclass CAR1 : public CARMA_Base<double> {\n\t\npublic:\n\t// Constructors //\n    CAR1() {}\n\tCAR1(bool track, std::string name, std::vector<double> time, std::vector<double> y, std::vector<double> yerr,\n         double temperature=1.0) : CARMA_Base<double>(track, name, time, y, yerr, temperature)\n    {\n        pKFilter_ = std::make_shared<KalmanFilter1>(time_, y_, yerr_);\n        // Set the size of the parameter vector theta=(mu,sigma,measerr_scale,log(omega))\n        value_.set_size(4);\n    }\n    \n    // extract the AR parameters from the parameter vector\n    double ExtractAR(arma::vec theta) { return exp(theta(3)); }\n    arma::vec ExtractMA(arma::vec theta) { return arma::zeros<arma::vec>(1); }\n    \n    // generate starting values of the CAR(1) parameters\n\tarma::vec StartingValue();\n    arma::vec SetStartingValue(arma::vec init);\n    \n    // return the variance of a CAR(1) process\n    double ExtractSigsqr(arma::vec theta) {\n        return 2.0 * theta(0) * theta(0) * exp(theta(3));\n    }\n\n\t// Set the bounds on the uniform prior.\n    bool CheckPriorBounds(arma::vec theta);\n};\n\n/*\n Continuous time autoregressive process of order p.\n*/\n\nclass CARp : public CARMA_Base<arma::cx_vec> {\npublic:\n    // Constructor\n    CARp() {}\n    CARp(bool track, std::string name, std::vector<double> time, std::vector<double> y, std::vector<double> yerr, int p,\n         double temperature=1.0): CARMA_Base<arma::cx_vec>(track, name, time, y, yerr, temperature), p_(p)\n\t{\n        pKFilter_ = std::make_shared<KalmanFilterp>(time_, y_, yerr_);\n\t\tvalue_.set_size(p_+3);\n        ma_coefs_ = arma::zeros(p);\n        ma_coefs_(0) = 1.0;\n        order_lorentzians_ = true;\n        pKFilter_->SetMA(ma_coefs_);\n\t}\n    \n    // calculate the roots of the AR(p) polynomial from the CAR(p) process parameters\n    arma::cx_vec ARRoots(arma::vec theta);\n    \n    // Return the starting value and set log_posterior_\n\tarma::vec StartingValue();\n    arma::vec SetStartingValue(arma::vec init);\n     // return the starting values for the AR and MA parameters\n    arma::vec StartingAR();\n\n    // extract the lorentzian parameters from the CARMA parameter vector\n    arma::cx_vec ExtractAR(arma::vec theta) {\n        return ARRoots(theta);\n    }\n    // extract the moving-average parameters from the CARMA parameter vector\n    arma::vec ExtractMA(arma::vec theta) { return ma_coefs_; }\n    \n    double ExtractSigsqr(arma::vec theta) {\n        arma::cx_vec ar_roots = ARRoots(theta);\n        return theta(0) * theta(0) / Variance(ar_roots, ma_coefs_, 1.0);\n    }\n    \n    // Calculate the variance of the CAR(p) process\n    double Variance(arma::cx_vec alpha_roots, arma::vec ma_coefs, double sigma, double dt=0.0);\n\t\n    // Set the bounds on the uniform prior.\n    bool CheckPriorBounds(arma::vec theta);\n    \n    void PrintOmega(arma::cx_vec omega) {\n        omega.print(\"AR Roots:\");\n    }\n    \nprotected:\n    int p_; // Order of the CAR(p) process\n    bool order_lorentzians_; // force the lorentzian centroids to be in order?\nprivate:\n    arma::vec ma_coefs_;\n};\n\n/*\n Same as CARp class, but using the Belcher et al. (1994) parameterization for the moving average coefficients.\n */\nclass ZCAR : public CARp\n{\npublic:\n    // constructor //\n    ZCAR() {}\n    ZCAR(bool track, std::string name, std::vector<double> time, std::vector<double> y, std::vector<double> yerr, int p,\n         double temperature=1.0) : CARp(track, name, time, y, yerr, p, temperature)\n    {\n        // set value of kappa\n        arma::vec dt = time_(arma::span(1,time_.n_elem-1)) - time_(arma::span(0,time_.n_elem-2));\n        kappa_ = 1.0 / dt.min();\n        // set the moving average coefficients\n        ma_coefs_ = arma::zeros(p_);\n        ma_coefs_(0) = 1.0;\n        for (int i=1; i<p_; i++) {\n            ma_coefs_(i) = boost::math::binomial_coefficient<double>(p_-1, i) / pow(kappa_,i);\n        }\n        pKFilter_->SetMA(ma_coefs_);\n    }\nprivate:\n    double kappa_; // minimum frequency resolved by the observation times\n    arma::vec ma_coefs_;\n};\n\n/*\n Continuous time autoregressive moving average process of order (p,q)\n*/\n\nclass CARMA : public CARp\n{\t\npublic:\n\t// Constructor //\n    CARMA() {}\n\tCARMA(bool track, std::string name, std::vector<double> time, std::vector<double> y, std::vector<double> yerr, int p, int q,\n          double temperature=1.0) : CARp(track, name, time, y, yerr, p, temperature), q_(q)\n    {\n        BOOST_ASSERT_MSG(q < p, \"Order of moving average polynomial must be less than order of autoregressive polynomial\");\n        value_.set_size(p_+q_+3);\n    }\n\n    // Return the starting value and set log_posterior_\n\tarma::vec StartingValue();\n    arma::vec SetStartingValue(arma::vec init);\n \n    // return the starting value for the MA coefficients\n    arma::vec StartingMA();\n    \n    // extract the moving-average parameters from the CARMA parameter vector\n    arma::vec ExtractMA(arma::vec theta);\n    \n    double ExtractSigsqr(arma::vec theta) {\n        arma::cx_vec ar_roots = ARRoots(theta);\n        arma::vec ma_coefs = ExtractMA(theta);\n        return theta(0) * theta(0) / Variance(ar_roots, ma_coefs, 1.0);\n    }\n    \nprivate:\n    int q_; // order of moving average polynomial\n};\n\n/*\n CARMA(p,p-1) model using the z-transformed parameterization (Belcher et al. 1994). This is the same as the ZCAR model, except\n that kappa is a free parameter for the ZCARMA model.\n */\n\nclass ZCARMA : public CARp\n{    \npublic:\n    ZCARMA() {}\n    ZCARMA(bool track, std::string name, std::vector<double> time, std::vector<double> y, std::vector<double> yerr, int p,\n           double temperature=1.0) : CARp(track, name, time, y, yerr, p, temperature)\n    {\n        value_.set_size(p_+4);\n        // set default boundaries on kappa\n        arma::vec dt = time_(arma::span(1,time_.n_elem-1)) - time_(arma::span(0,time_.n_elem-2));\n        kappa_high_ = 1.0 / dt.min();\n        // kappa_low_ = 0.9 / dt.min();\n        // kappa_low_ = 1.0 / (time_.max() - time_.min());\n        kappa_low_ = std::max(1.0 / (time_.max() - time_.min()), 1.0 / (10.0 * arma::median(dt)));\n    }\n    \n    // Return the starting value and set log_posterior_\n\tarma::vec StartingValue();\n    arma::vec SetStartingValue(arma::vec init);\n     // Return the starting value for the kappa parameter\n    double StartingKappa();\n    \n    // extract the moving-average parameters from the CARMA parameter vector\n    arma::vec ExtractMA(arma::vec theta);\n    \n    double ExtractSigsqr(arma::vec theta) {\n        arma::cx_vec ar_roots = ARRoots(theta);\n        arma::vec ma_coefs = ExtractMA(theta);\n        return theta(0) * theta(0) / Variance(ar_roots, ma_coefs, 1.0);\n    }\n\n    // Set bounds on kappa\n    void SetKappaBounds(double kappa_low, double kappa_high) {\n        kappa_low_ = kappa_low;\n        kappa_high_ = kappa_high;\n    }\n    \n    // compute the log-prior of the ZCARMA parameters\n    double LogPrior(arma::vec theta)\n    {\n        // first compute prior for measurement error scaling parameter\n        double measerr_scale = theta(1);\n        double logprior = -0.5 * measerr_dof_ / measerr_scale -\n        (1.0 + measerr_dof_ / 2.0) * log(measerr_scale);\n        \n        // now compute prior on x = logit(kappa_norm), assuming a uniform prior on kappa\n        double logit_kappa = theta(p_+3);\n        logprior += -logit_kappa - 2.0 * log(1.0 + exp(-logit_kappa));\n                \n        return logprior;\n    }\n\n    \nprivate:\n    double kappa_low_, kappa_high_; // prior bounds on the kappa parameter\n};\n\n/********************************\n\tFUNCTION PROTOTYPES\n********************************/\n\ndouble logit(double x);\ndouble inv_logit(double x);\n\n// Check if all of the roots are unique within some fractional tolerance\nbool unique_roots(arma::cx_vec roots, double tolerance);\n\n// Return the coefficients of a polynomial given its roots.\narma::vec polycoefs(arma::cx_vec roots);\n\n#endif\n", "meta": {"hexsha": "d89762a9e75873380153260756b5115fa4d0cdeb", "size": 17065, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/include/carpack.hpp", "max_stars_repo_name": "Jamieryan/carma_pack", "max_stars_repo_head_hexsha": "347ea78818cc808e53e4a46d341829f787198df5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 39.0, "max_stars_repo_stars_event_min_datetime": "2015-01-25T19:24:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T11:55:28.000Z", "max_issues_repo_path": "src/include/carpack.hpp", "max_issues_repo_name": "Jamieryan/carma_pack", "max_issues_repo_head_hexsha": "347ea78818cc808e53e4a46d341829f787198df5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2015-04-29T12:37:45.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-28T23:31:29.000Z", "max_forks_repo_path": "src/include/carpack.hpp", "max_forks_repo_name": "Jamieryan/carma_pack", "max_forks_repo_head_hexsha": "347ea78818cc808e53e4a46d341829f787198df5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19.0, "max_forks_repo_forks_event_min_datetime": "2015-09-15T00:41:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-28T07:28:47.000Z", "avg_line_length": 35.7756813417, "max_line_length": 126, "alphanum_fraction": 0.63000293, "num_tokens": 4577, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.6654105587468141, "lm_q1q2_score": 0.4652912750228885}}
{"text": "\ufeff#pragma once\n#include <QtWidgets>\n#include <Eigen/Dense>\n#include <array>\n#include \"typedefs.h\"\n#include \"graph_typedefs.h\"\n#include <vector>\n#include \"TopoGraphEmbedding.h\"\nclass ImageQuiverViewer : public QLabel {\n\tQ_OBJECT\n\npublic:\n\tImageQuiverViewer(QWidget * parent = Q_NULLPTR);\n\t~ImageQuiverViewer();\n\n\ttemplate <typename T>\n\tQPointF modelToScreen(const T & p)\n\t{\n\t\tT result = (p + T(0.5, 0.5))*scale;\n\t\treturn{ result.x(), result.y() };\n\t}\n\tvoid setRoots(const std::array<Eigen::MatrixXcd, 2>& newRoots);\n\tvoid setExtraRoots(const std::array<Eigen::MatrixXcd, 2>& newRoots);\n\tvoid setPolys(const std::vector<MyPolyline>& newPolys);\n\tvoid drawRoots(const std::array<Eigen::MatrixXcd, 2>& thoseOnes, QPainter & painter);\n\tvoid drawGraphs(QPainter& painter);\n\tvoid drawPolys(QPainter & painter, const std::vector<MyPolyline>& curves, double width, QColor color);\npublic:\n\tdouble scale;\n\tstd::vector<bool> graphHidden;\n\tstd::vector<G> graphs;\n\tstd::vector<std::string> graphTags;\n\tstd::vector<bool> vectorizationsHidden;\n\tbool polysHidden;\n\tbool showCircles;\n\tbool showIncontractibleLoops;\n\t\n\tstd::set<size_t> splitVtx;\n\tstd::vector<std::vector<QPointF>> incontractibleLoops;\n\tstd::unique_ptr<Distances> tmpDistances;\n\tstd::vector<std::vector<MyPolyline>> vectorizations;\nprotected:\n\tbool areGraphsVisible();\n\tvoid paintEvent(QPaintEvent * event);\n\tvoid drawClusters(QPainter & painter);\n\tvirtual void mousePressEvent(QMouseEvent * event);\nprivate:\n\tstd::array<Eigen::MatrixXcd, 2> roots, extraRoots;\n\tstd::vector<MyPolyline> polys;\n\tstd::set<std::pair<int, int>> clustersToDraw;\n\tstd::vector<QColor> colors;\n};\n", "meta": {"hexsha": "127e916c38f3c9f618c49daa57d4650d0e71b6fa", "size": 1617, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/imagequiverviewer.hpp", "max_stars_repo_name": "bmpix/PolyVectorization", "max_stars_repo_head_hexsha": "bceb8e2a08cca29cef1df074eb1a1f6450cc163f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 46.0, "max_stars_repo_stars_event_min_datetime": "2019-07-31T19:12:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T06:46:50.000Z", "max_issues_repo_path": "src/imagequiverviewer.hpp", "max_issues_repo_name": "medmedmedic/PolyVectorization", "max_issues_repo_head_hexsha": "bceb8e2a08cca29cef1df074eb1a1f6450cc163f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2019-07-31T20:37:19.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-14T19:37:19.000Z", "max_forks_repo_path": "src/imagequiverviewer.hpp", "max_forks_repo_name": "medmedmedic/PolyVectorization", "max_forks_repo_head_hexsha": "bceb8e2a08cca29cef1df074eb1a1f6450cc163f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2019-08-02T15:52:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T01:41:40.000Z", "avg_line_length": 30.5094339623, "max_line_length": 103, "alphanum_fraction": 0.745825603, "num_tokens": 443, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544335934766, "lm_q2_score": 0.6654105454764747, "lm_q1q2_score": 0.4652912740842786}}
{"text": "/**\n * @file   main_inflow_source.cpp\n * @author Simon Pintarelli <simon@thinkpadX1>\n * @date   Thu Apr 28 00:22:50 CEST 2016\n *\n * @brief  create sources in physical space and export to hdf\n *\n */\n\n// system includes -----------------------------------------------\n#include <boost/math/constants/constants.hpp>\n#include <boost/program_options.hpp>\n#include <iostream>\n// own includes --------------------------------------------------\n#include <base/eigen2hdf.hpp>\n#include <base/init.hpp>\n#include <base/timer.hpp>\n#include <fft/fft2.hpp>\n#include <fft/fft2_r2c.hpp>\n#include <ridgelet/init_fftw.hpp>\n#include <ridgelet/ridgelet_cell_array.hpp>\n#include <ridgelet/ridgelet_frame.hpp>\n#include <ridgelet/rt.hpp>\n\n#include <boundary_conditions/inflow_bc.hpp>\n#include <operators/operators.hpp>\n#include <solver/cg.hpp>\n#include <solver/ridgelet_solver.hpp>\n#include <spectral/quadrature/gauss_hermite_roots.hpp>\n\nusing namespace std;\n// typedef FFTr2c<PlannerR2C> fft_t;\n// typedef RT<RidgeletFrame, fft_t> RT_t;\n// typedef RT_t::array_t array_t;\n// typedef RT_t::complex_array_t complex_array_t;\n// typedef RT_t::rt_coeff_t rt_coeff_t;\n\nconst double Lx = 1.2;\nconst double Ly = 1.2;\n\n// inflow values\nconst double ql = 0.5;\nconst double qt = 1.0;\n\nint main(int argc, char *argv[])\n{\n  SOURCE_INFO();\n\n  namespace po = boost::program_options;\n\n  unsigned int N;\n  unsigned int K;\n\n  po::options_description options(\"options\");\n  options.add_options()(\"help\", \"produce help message\")\n      (\"size,N\", po::value<unsigned int>(&N)->default_value(128), \"grid size\")\n      (\"deg,K\", po::value<unsigned int>(&K)->default_value(10), \"deg\");\n  po::variables_map vm;\n  po::store(po::parse_command_line(argc, argv, options), vm);\n  po::notify(vm);\n\n  if (vm.count(\"help\")) {\n    std::cout << options << \"\\n\";\n    return 0;\n  }\n\n  cout << \"CMD::\";\n  for (int i = 0; i < argc; ++i) {\n    cout << argv[i] << \" \";\n  }\n  cout << \"\\n\";\n\n  const unsigned int Nx = N;\n  const unsigned int Ny = N;\n  cout << \"Nx: \" << Nx << \"\\n\";\n  cout << \"Ny: \" << Ny << \"\\n\";\n  cout << \"K:  \" << K << \"\\n\";\n  cout << \"ql: \" << ql << \"\\n\";\n  cout << \"qt: \" << qt << \"\\n\";\n  // fft_t fft;\n  // init_fftw(fft, FFTW_MEASURE, rf);\n  // fft.get_plan().create_and_get_plan(f*Ny, f*Nx, PlannerR2C::INV);\n  // fft.get_plan().create_and_get_plan(f*Ny, f*Nx, PlannerR2C::FWD);\n  std::vector<double> qi(K);\n  boltzmann::gauss_hermite_roots(qi, K);\n  Eigen::ArrayXd xi = Eigen::ArrayXd::LinSpaced(Nx + 1, 0, Lx).segment(0, Nx);\n  Eigen::ArrayXd yi = Eigen::ArrayXd::LinSpaced(Ny + 1, 0, Ly).segment(0, Ny);\n\n  typedef Eigen::Array<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> array_t;\n\n  for (int i = 0; i < K; ++i) {\n    cout << qi[i] << \"\\t\";\n  }\n  cout << \"\\n\";\n\n  hid_t file = H5Fcreate(\"inflow_source.h5\", H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);\n  array_t X = xi.transpose().replicate(Ny, 1);\n  array_t Y = yi.replicate(1, Nx);\n#pragma omp parallel for\n  for (int qx = 0; qx < K; ++qx) {\n    for (int qy = 0; qy < K; ++qy) {\n      const double vx = qi[qx];\n      const double vy = qi[qy];\n      array_t Q(Ny, Nx);\n      make_inflow_source(Q, vx, vy, Lx, Ly, ql, qt);\n      Q = ((X > 1 || Y > 1)).select(Q, array_t::Zero(Ny, Nx));\n\n#pragma omp critical\n      {\n        eigen2hdf::save(\n            file, boost::lexical_cast<string>(qx) + \"_\" + boost::lexical_cast<string>(qy), Q);\n      }\n    }\n  }\n  H5Fclose(file);\n\n  return 0;\n}\n", "meta": {"hexsha": "f40de9c3dfcc3d922a8cbbe082ebdb57107de3cc", "size": 3404, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/phase_space/main_inflow_source.cpp", "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": "test/phase_space/main_inflow_source.cpp", "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": "test/phase_space/main_inflow_source.cpp", "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.6050420168, "max_line_length": 94, "alphanum_fraction": 0.6133960047, "num_tokens": 1064, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544085240401, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.46529127132182607}}
{"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#define NT2_UNIT_MODULE \"boost::simd::constants real\"\n\n#include <boost/simd/include/constants/real.hpp>\n#include <boost/simd/sdk/simd/native.hpp>\n#include <nt2/sdk/unit/module.hpp>\n#include <nt2/sdk/unit/tests/relation.hpp>\n\n////////////////////////////////////////////////////////////////////////////////\n// Test value of real constants for every base real types\n////////////////////////////////////////////////////////////////////////////////\nNT2_TEST_CASE_TPL  (  real_value, BOOST_SIMD_REAL_TYPES )\n{\n  NT2_TEST_EQUAL( boost::simd::Mhalf<T>()       , static_cast<T>(-1./2. ) );\n  NT2_TEST_EQUAL( boost::simd::Mzero<T>()       , static_cast<T>(-0.    ) );\n  NT2_TEST_EQUAL( boost::simd::Half<T>()        , static_cast<T>(1./2.  ) );\n  NT2_TEST_EQUAL( boost::simd::Third<T>()       , static_cast<T>(1./3.  ) );\n  NT2_TEST_EQUAL( boost::simd::Quarter<T>()     , static_cast<T>(1./4.  ) );\n  NT2_TEST_EQUAL( boost::simd::Twotom10<T>()    , static_cast<T>(9.765625e-4) );\n  NT2_TEST_EQUAL( boost::simd::Pi<T>()          , static_cast<T>(3.1415926535897930) );\n  NT2_TEST_EQUAL( boost::simd::Sqrt_2o_2<T>()     , static_cast<T>(7.071067811865476e-1) );\n  NT2_TEST_EQUAL( boost::simd::Gold<T>()        , static_cast<T>(1.6180339887498950) );\n  NT2_TEST_EQUAL( boost::simd::Cgold<T>()       , static_cast<T>(3.8196601125010515e-1) );\n}\n\nNT2_TEST_CASE_TPL( real_value_int, BOOST_SIMD_INTEGRAL_TYPES )\n{\n  NT2_TEST_EQUAL( boost::simd::Mhalf<T>()       , static_cast<T>(0) );\n  NT2_TEST_EQUAL( boost::simd::Mzero<T>()       , static_cast<T>(0) );\n  NT2_TEST_EQUAL( boost::simd::Half<T>()        , static_cast<T>(0) );\n  NT2_TEST_EQUAL( boost::simd::Third<T>()       , static_cast<T>(0) );\n  NT2_TEST_EQUAL( boost::simd::Quarter<T>()     , static_cast<T>(0) );\n  NT2_TEST_EQUAL( boost::simd::Twotom10<T>()    , static_cast<T>(0) );\n  NT2_TEST_EQUAL( boost::simd::Pi<T>()          , static_cast<T>(3) );\n  NT2_TEST_EQUAL( boost::simd::Sqrt_2<T>()      , static_cast<T>(1) );\n  NT2_TEST_EQUAL( boost::simd::Sqrt_2o_2<T>()     , static_cast<T>(0) );\n  NT2_TEST_EQUAL( boost::simd::Gold<T>()        , static_cast<T>(1) );\n  NT2_TEST_EQUAL( boost::simd::Cgold<T>()       , static_cast<T>(0) );\n}\n\n////////////////////////////////////////////////////////////////////////////////\n// Test type dependant values\n////////////////////////////////////////////////////////////////////////////////\nNT2_TEST_CASE(type_dependant_real)\n{\n  NT2_TEST_EQUAL( boost::simd::Twotonmb<double>()    , 4503599627370496. );\n  NT2_TEST_EQUAL( boost::simd::Splitfactor<double>(), 134217728.        );\n  NT2_TEST_EQUAL( boost::simd::Twotonmb<float>()     , 8388608.f         );\n  NT2_TEST_EQUAL( boost::simd::Splitfactor<float>() , 8192.f            );\n}\n\nNT2_TEST_CASE(type_dependant_const)\n{\n  NT2_TEST_EQUAL( (boost::simd::Const<double,0x3FF3BE76C8B43958LL>()), 1.234   );\n  NT2_TEST_EQUAL( (boost::simd::Const<float,0x3F9DF3B6>())           , 1.234f );\n}\n\n////////////////////////////////////////////////////////////////////////////////\n// Test real_constant for every base types\n////////////////////////////////////////////////////////////////////////////////\nNT2_TEST_CASE_TPL  (  real_constant, (double)(float) )\n{\n  NT2_TEST_EQUAL( (boost::simd::real_constant < T , 0x3FF3BE76C8B43958LL\n                                          , 0x3F9DF3B6\n                                      >()\n                  )\n                , static_cast<T>(1.234)\n                );\n}\n\nNT2_TEST_CASE(double_constant)\n{\n  NT2_TEST_EQUAL((boost::simd::double_constant<double,0x3FF3BE76C8B43958LL>()), 1.234);\n}\n\nNT2_TEST_CASE(single_constant)\n{\n  NT2_TEST_EQUAL((boost::simd::single_constant<float,0x3F9DF3B6>()),1.234f);\n}\n", "meta": {"hexsha": "232cf7ee90ce3ea3617cad8bf44125eab58e59eb", "size": 4180, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/constant/unit/scalar/real.cpp", "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/constant/unit/scalar/real.cpp", "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/constant/unit/scalar/real.cpp", "max_forks_repo_name": "timblechmann/nt2", "max_forks_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.0459770115, "max_line_length": 91, "alphanum_fraction": 0.5318181818, "num_tokens": 1122, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587586, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.46529127038321677}}
{"text": "/* Author: Wolfgang Bangerth, University of Heidelberg, 2000 */\n\n/*    $Id: step-8.cc 27657 2012-11-21 13:19:08Z bangerth $       */\n/*                                                                */\n/*    Copyright (C) 2000-2004, 2006-2008, 2010-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, the first few include files are already known, so we will not\n// comment on them further.\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_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/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/numerics/error_estimator.h>\n\n// In this example, we need vector-valued finite elements. The support for\n// these can be found in the following include file:\n#include <deal.II/fe/fe_system.h>\n// We will compose the vector-valued finite elements from regular Q1 elements\n// which can be found here, as usual:\n#include <deal.II/fe/fe_q.h>\n\n// This again is C++:\n#include <fstream>\n#include <iostream>\n\n// The last step is as in previous programs. In particular, just like in\n// step-7, we pack everything that's specific to this program into a namespace\n// of its own.\nnamespace Step8\n{\n  using namespace dealii;\n\n  // @sect3{The <code>ElasticProblem</code> class template}\n\n  // The main class is, except for its name, almost unchanged with respect to\n  // the step-6 example.\n  //\n  // The only change is the use of a different class for the <code>fe</code>\n  // variable: Instead of a concrete finite element class such as\n  // <code>FE_Q</code>, we now use a more generic one,\n  // <code>FESystem</code>. In fact, <code>FESystem</code> is not really a\n  // finite element itself in that it does not implement shape functions of\n  // its own.  Rather, it is a class that can be used to stack several other\n  // elements together to form one vector-valued finite element. In our case,\n  // we will compose the vector-valued element of <code>FE_Q(1)</code>\n  // objects, as shown below in the constructor of this class.\n  template <int dim>\n  class ElasticProblem\n  {\n  public:\n    ElasticProblem ();\n    ~ElasticProblem ();\n    void run ();\n\n  private:\n    void setup_system ();\n    void assemble_system ();\n    void solve ();\n    void refine_grid ();\n    void output_results (const unsigned int cycle) const;\n\n    Triangulation<dim>   triangulation;\n    DoFHandler<dim>      dof_handler;\n\n    FESystem<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\n\n  // @sect3{Right hand side values}\n\n  // Before going over to the implementation of the main class, we declare and\n  // define the class which describes the right hand side. This time, the\n  // right hand side is vector-valued, as is the solution, so we will describe\n  // the changes required for this in some more detail.\n  //\n  // The first thing is that vector-valued functions have to have a\n  // constructor, since they need to pass down to the base class of how many\n  // components the function consists. The default value in the constructor of\n  // the base class is one (i.e.: a scalar function), which is why we did not\n  // need not define a constructor for the scalar function used in previous\n  // programs.\n  template <int dim>\n  class RightHandSide :  public Function<dim>\n  {\n  public:\n    RightHandSide ();\n\n    // The next change is that we want a replacement for the\n    // <code>value</code> function of the previous examples. There, a second\n    // parameter <code>component</code> was given, which denoted which\n    // component was requested. Here, we implement a function that returns the\n    // whole vector of values at the given place at once, in the second\n    // argument of the function. The obvious name for such a replacement\n    // function is <code>vector_value</code>.\n    //\n    // Secondly, in analogy to the <code>value_list</code> function, there is\n    // a function <code>vector_value_list</code>, which returns the values of\n    // the vector-valued function at several points at once:\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  // This is the constructor of the right hand side class. As said above, it\n  // only passes down to the base class the number of components, which is\n  // <code>dim</code> in the present case (one force component in each of the\n  // <code>dim</code> space directions).\n  //\n  // Some people would have moved the definition of such a short function\n  // right into the class declaration. We do not do that, as a matter of\n  // style: the deal.II style guides require that class declarations contain\n  // only declarations, and that definitions are always to be found\n  // outside. This is, obviously, as much as matter of taste as indentation,\n  // but we try to be consistent in this direction.\n  template <int dim>\n  RightHandSide<dim>::RightHandSide ()\n    :\n    Function<dim> (dim)\n  {}\n\n\n  // Next the function that returns the whole vector of values at the point\n  // <code>p</code> at once.\n  //\n  // To prevent cases where the return vector has not previously been set to\n  // the right size we test for this case and otherwise throw an exception at\n  // the beginning of the function. Note that enforcing that output arguments\n  // already have the correct size is a convention in deal.II, and enforced\n  // almost everywhere. The reason is that we would otherwise have to check at\n  // the beginning of the function and possibly change the size of the output\n  // vector. This is expensive, and would almost always be unnecessary (the\n  // first call to the function would set the vector to the right size, and\n  // subsequent calls would only have to do redundant checks). In addition,\n  // checking and possibly resizing the vector is an operation that can not be\n  // removed if we can't rely on the assumption that the vector already has\n  // the correct size; this is in contract to the <code>Assert</code> call\n  // that is completely removed if the program is compiled in optimized mode.\n  //\n  // Likewise, if by some accident someone tried to compile and run the\n  // program in only one space dimension (in which the elastic equations do\n  // not make much sense since they reduce to the ordinary Laplace equation),\n  // we terminate the program in the second assertion. The program will work\n  // just fine in 3d, however.\n  template <int dim>\n  inline\n  void RightHandSide<dim>::vector_value (const Point<dim> &p,\n                                         Vector<double>   &values) const\n  {\n    Assert (values.size() == dim,\n            ExcDimensionMismatch (values.size(), dim));\n    Assert (dim >= 2, ExcNotImplemented());\n\n    // The rest of the function implements computing force values. We will use\n    // a constant (unit) force in x-direction located in two little circles\n    // (or spheres, in 3d) around points (0.5,0) and (-0.5,0), and y-force in\n    // an area around the origin; in 3d, the z-component of these centers is\n    // zero as well.\n    //\n    // For this, let us first define two objects that denote the centers of\n    // these areas. Note that upon construction of the <code>Point</code>\n    // objects, all components are set to zero.\n    Point<dim> point_1, point_2;\n    point_1(0) = 0.5;\n    point_2(0) = -0.5;\n\n    // If now the point <code>p</code> is in a circle (sphere) of radius 0.2\n    // around one of these points, then set the force in x-direction to one,\n    // otherwise to zero:\n    if (((p-point_1).square() < 0.2*0.2) ||\n        ((p-point_2).square() < 0.2*0.2))\n      values(0) = 1;\n    else\n      values(0) = 0;\n\n    // Likewise, if <code>p</code> is in the vicinity of the origin, then set\n    // the y-force to 1, otherwise to zero:\n    if (p.square() < 0.2*0.2)\n      values(1) = 1;\n    else\n      values(1) = 0;\n  }\n\n\n\n  // Now, this is the function of the right hand side class that returns the\n  // values at several points at once. The function starts out with checking\n  // that the number of input and output arguments is equal (the sizes of the\n  // individual output vectors will be checked in the function that we call\n  // further down below). Next, we define an abbreviation for the number of\n  // points which we shall work on, to make some things simpler below.\n  template <int dim>\n  void RightHandSide<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    const unsigned int n_points = points.size();\n\n    // Finally we treat each of the points. In one of the previous examples,\n    // we have explained why the\n    // <code>value_list</code>/<code>vector_value_list</code> function had\n    // been introduced: to prevent us from calling virtual functions too\n    // frequently. On the other hand, we now need to implement the same\n    // function twice, which can lead to confusion if one function is changed\n    // but the other is not.\n    //\n    // We can prevent this situation by calling\n    // <code>RightHandSide::vector_value</code> on each point in the input\n    // list. Note that by giving the full name of the function, including the\n    // class name, we instruct the compiler to explicitly call this function,\n    // and not to use the virtual function call mechanism that would be used\n    // if we had just called <code>vector_value</code>. This is important,\n    // since the compiler generally can't make any assumptions which function\n    // is called when using virtual functions, and it therefore can't inline\n    // the called function into the site of the call. On the contrary, here we\n    // give the fully qualified name, which bypasses the virtual function\n    // call, and consequently the compiler knows exactly which function is\n    // called and will inline above function into the present location. (Note\n    // that we have declared the <code>vector_value</code> function above\n    // <code>inline</code>, though modern compilers are also able to inline\n    // functions even if they have not been declared as inline).\n    //\n    // It is worth noting why we go to such length explaining what we\n    // do. Using this construct, we manage to avoid any inconsistency: if we\n    // want to change the right hand side function, it would be difficult to\n    // always remember that we always have to change two functions in the same\n    // way. Using this forwarding mechanism, we only have to change a single\n    // place (the <code>vector_value</code> function), and the second place\n    // (the <code>vector_value_list</code> function) will always be consistent\n    // with it. At the same time, using virtual function call bypassing, the\n    // code is no less efficient than if we had written it twice in the first\n    // place:\n    for (unsigned int p=0; p<n_points; ++p)\n      RightHandSide<dim>::vector_value (points[p],\n                                        value_list[p]);\n  }\n\n\n\n  // @sect3{The <code>ElasticProblem</code> class implementation}\n\n  // @sect4{ElasticProblem::ElasticProblem}\n\n  // Following is the constructor of the main class. As said before, we would\n  // like to construct a vector-valued finite element that is composed of\n  // several scalar finite elements (i.e., we want to build the vector-valued\n  // element so that each of its vector components consists of the shape\n  // functions of a scalar element). Of course, the number of scalar finite\n  // elements we would like to stack together equals the number of components\n  // the solution function has, which is <code>dim</code> since we consider\n  // displacement in each space direction. The <code>FESystem</code> class can\n  // handle this: we pass it the finite element of which we would like to\n  // compose the system of, and how often it shall be repeated:\n\n  template <int dim>\n  ElasticProblem<dim>::ElasticProblem ()\n    :\n    dof_handler (triangulation),\n    fe (FE_Q<dim>(1), dim)\n  {}\n  // In fact, the <code>FESystem</code> class has several more constructors\n  // which can perform more complex operations than just stacking together\n  // several scalar finite elements of the same type into one; we will get to\n  // know these possibilities in later examples.\n\n\n\n  // @sect4{ElasticProblem::~ElasticProblem}\n\n  // The destructor, on the other hand, is exactly as in step-6:\n  template <int dim>\n  ElasticProblem<dim>::~ElasticProblem ()\n  {\n    dof_handler.clear ();\n  }\n\n\n  // @sect4{ElasticProblem::setup_system}\n\n  // Setting up the system of equations is identitical to the function used in\n  // the step-6 example. The <code>DoFHandler</code> class and all other\n  // classes used here are fully aware that the finite element we want to use\n  // is vector-valued, and take care of the vector-valuedness of the finite\n  // element themselves. (In fact, they do not, but this does not need to\n  // bother you: since they only need to know how many degrees of freedom\n  // there are per vertex, line and cell, and they do not ask what they\n  // represent, i.e. whether the finite element under consideration is\n  // vector-valued or whether it is, for example, a scalar Hermite element\n  // with several degrees of freedom on each vertex).\n  template <int dim>\n  void ElasticProblem<dim>::setup_system ()\n  {\n    dof_handler.distribute_dofs (fe);\n    hanging_node_constraints.clear ();\n    DoFTools::make_hanging_node_constraints (dof_handler,\n                                             hanging_node_constraints);\n    hanging_node_constraints.close ();\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  // @sect4{ElasticProblem::assemble_system}\n\n  // The big changes in this program are in the creation of matrix and right\n  // hand side, since they are problem-dependent. We will go through that\n  // process step-by-step, since it is a bit more complicated than in previous\n  // examples.\n  //\n  // The first parts of this function are the same as before, however: setting\n  // up a suitable quadrature formula, initializing an <code>FEValues</code>\n  // object for the (vector-valued) finite element we use as well as the\n  // quadrature object, and declaring a number of auxiliary arrays. In\n  // addition, we declare the ever same two abbreviations:\n  // <code>n_q_points</code> and <code>dofs_per_cell</code>. The number of\n  // degrees of freedom per cell we now obviously ask from the composed finite\n  // element rather than from the underlying scalar Q1 element. Here, it is\n  // <code>dim</code> times the number of degrees of freedom per cell of the\n  // Q1 element, though this is not explicit knowledge we need to care about:\n  template <int dim>\n  void ElasticProblem<dim>::assemble_system ()\n  {\n    QGauss<dim>  quadrature_formula(2);\n\n    FEValues<dim> fe_values (fe, quadrature_formula,\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    = quadrature_formula.size();\n\n    FullMatrix<double>   cell_matrix (dofs_per_cell, dofs_per_cell);\n    Vector<double>       cell_rhs (dofs_per_cell);\n\n    std::vector<unsigned int> local_dof_indices (dofs_per_cell);\n\n    // As was shown in previous examples as well, we need a place where to\n    // store the values of the coefficients at all the quadrature points on a\n    // cell. In the present situation, we have two coefficients, lambda and\n    // mu.\n    std::vector<double>     lambda_values (n_q_points);\n    std::vector<double>     mu_values (n_q_points);\n\n    // Well, we could as well have omitted the above two arrays since we will\n    // use constant coefficients for both lambda and mu, which can be declared\n    // like this. They both represent functions always returning the constant\n    // value 1.0. Although we could omit the respective factors in the\n    // assemblage of the matrix, we use them here for purpose of\n    // demonstration.\n    ConstantFunction<dim> lambda(1.), mu(1.);\n\n    // Then again, we need to have the same for the right hand side. This is\n    // exactly as before in previous examples. However, we now have a\n    // vector-valued right hand side, which is why the data type of the\n    // <code>rhs_values</code> array is changed. We initialize it by\n    // <code>n_q_points</code> elements, each of which is a\n    // <code>Vector@<double@></code> with <code>dim</code> elements.\n    RightHandSide<dim>      right_hand_side;\n    std::vector<Vector<double> > rhs_values (n_q_points,\n                                             Vector<double>(dim));\n\n\n    // Now we can begin with the loop over all cells:\n    typename DoFHandler<dim>::active_cell_iterator cell = dof_handler.begin_active(),\n                                                   endc = dof_handler.end();\n    for (; cell!=endc; ++cell)\n      {\n        cell_matrix = 0;\n        cell_rhs = 0;\n\n        fe_values.reinit (cell);\n\n        // Next we get the values of the coefficients at the quadrature\n        // points. Likewise for the right hand side:\n        lambda.value_list (fe_values.get_quadrature_points(), lambda_values);\n        mu.value_list     (fe_values.get_quadrature_points(), mu_values);\n\n        right_hand_side.vector_value_list (fe_values.get_quadrature_points(),\n                                           rhs_values);\n\n        // Then assemble the entries of the local stiffness matrix and right\n        // hand side vector. This follows almost one-to-one the pattern\n        // described in the introduction of this example.  One of the few\n        // comments in place is that we can compute the number\n        // <code>comp(i)</code>, i.e. the index of the only nonzero vector\n        // component of shape function <code>i</code> using the\n        // <code>fe.system_to_component_index(i).first</code> function call\n        // below.\n        //\n        // (By accessing the <code>first</code> variable of the return value\n        // of the <code>system_to_component_index</code> function, you might\n        // already have guessed that there is more in it. In fact, the\n        // function returns a <code>std::pair@<unsigned int, unsigned\n        // int@></code>, of which the first element is <code>comp(i)</code>\n        // and the second is the value <code>base(i)</code> also noted in the\n        // introduction, i.e.  the index of this shape function within all the\n        // shape functions that are nonzero in this component,\n        // i.e. <code>base(i)</code> in the diction of the introduction. This\n        // is not a number that we are usually interested in, however.)\n        //\n        // With this knowledge, we can assemble the local matrix\n        // contributions:\n        for (unsigned int i=0; i<dofs_per_cell; ++i)\n          {\n            const unsigned int\n            component_i = fe.system_to_component_index(i).first;\n\n            for (unsigned int j=0; j<dofs_per_cell; ++j)\n              {\n                const unsigned int\n                component_j = fe.system_to_component_index(j).first;\n\n                for (unsigned int q_point=0; q_point<n_q_points;\n                     ++q_point)\n                  {\n                    cell_matrix(i,j)\n                    +=\n                      // The first term is (lambda d_i u_i, d_j v_j) + (mu d_i\n                      // u_j, d_j v_i).  Note that\n                      // <code>shape_grad(i,q_point)</code> returns the\n                      // gradient of the only nonzero component of the i-th\n                      // shape function at quadrature point q_point. The\n                      // component <code>comp(i)</code> of the gradient, which\n                      // is the derivative of this only nonzero vector\n                      // component of the i-th shape function with respect to\n                      // the comp(i)th coordinate is accessed by the appended\n                      // brackets.\n                      (\n                        (fe_values.shape_grad(i,q_point)[component_i] *\n                         fe_values.shape_grad(j,q_point)[component_j] *\n                         lambda_values[q_point])\n                        +\n                        (fe_values.shape_grad(i,q_point)[component_j] *\n                         fe_values.shape_grad(j,q_point)[component_i] *\n                         mu_values[q_point])\n                        +\n                        // The second term is (mu nabla u_i, nabla v_j).  We\n                        // need not access a specific component of the\n                        // gradient, since we only have to compute the scalar\n                        // product of the two gradients, of which an\n                        // overloaded version of the operator* takes care, as\n                        // in previous examples.\n                        //\n                        // Note that by using the ?: operator, we only do this\n                        // if comp(i) equals comp(j), otherwise a zero is\n                        // added (which will be optimized away by the\n                        // compiler).\n                        ((component_i == component_j) ?\n                         (fe_values.shape_grad(i,q_point) *\n                          fe_values.shape_grad(j,q_point) *\n                          mu_values[q_point])  :\n                         0)\n                      )\n                      *\n                      fe_values.JxW(q_point);\n                  }\n              }\n          }\n\n        // Assembling the right hand side is also just as discussed in the\n        // introduction:\n        for (unsigned int i=0; i<dofs_per_cell; ++i)\n          {\n            const unsigned int\n            component_i = fe.system_to_component_index(i).first;\n\n            for (unsigned int q_point=0; q_point<n_q_points; ++q_point)\n              cell_rhs(i) += fe_values.shape_value(i,q_point) *\n                             rhs_values[q_point](component_i) *\n                             fe_values.JxW(q_point);\n          }\n\n        // The transfer from local degrees of freedom into the global matrix\n        // and right hand side vector does not depend on the equation under\n        // consideration, and is thus the same as in all previous\n        // examples. The same holds for the elimination of hanging nodes from\n        // the matrix and right hand side, once we are done with assembling\n        // the entire linear system:\n        cell->get_dof_indices (local_dof_indices);\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      }\n\n    hanging_node_constraints.condense (system_matrix);\n    hanging_node_constraints.condense (system_rhs);\n\n    // The interpolation of the boundary values needs a small modification:\n    // since the solution function is vector-valued, so need to be the\n    // boundary values. The <code>ZeroFunction</code> constructor accepts a\n    // parameter that tells it that it shall represent a vector valued,\n    // constant zero function with that many components. By default, this\n    // parameter is equal to one, in which case the <code>ZeroFunction</code>\n    // object would represent a scalar function. Since the solution vector has\n    // <code>dim</code> components, we need to pass <code>dim</code> as number\n    // of components to the zero function as well.\n    std::map<unsigned int,double> boundary_values;\n    VectorTools::interpolate_boundary_values (dof_handler,\n                                              0,\n                                              ZeroFunction<dim>(dim),\n                                              boundary_values);\n    MatrixTools::apply_boundary_values (boundary_values,\n                                        system_matrix,\n                                        solution,\n                                        system_rhs);\n  }\n\n\n\n  // @sect4{ElasticProblem::solve}\n\n  // The solver does not care about where the system of equations comes, as\n  // long as it stays positive definite and symmetric (which are the\n  // requirements for the use of the CG solver), which the system indeed\n  // is. Therefore, we need not change anything.\n  template <int dim>\n  void ElasticProblem<dim>::solve ()\n  {\n    SolverControl           solver_control (1000, 1e-12);\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    hanging_node_constraints.distribute (solution);\n  }\n\n\n  // @sect4{ElasticProblem::refine_grid}\n\n  // The function that does the refinement of the grid is the same as in the\n  // step-6 example. The quadrature formula is adapted to the linear elements\n  // again. Note that the error estimator by default adds up the estimated\n  // obtained from all components of the finite element solution, i.e., it\n  // uses the displacement in all directions with the same weight. If we would\n  // like the grid to be adapted to the x-displacement only, we could pass the\n  // function an additional parameter which tells it to do so and do not\n  // consider the displacements in all other directions for the error\n  // indicators. However, for the current problem, it seems appropriate to\n  // consider all displacement components with equal weight.\n  template <int dim>\n  void ElasticProblem<dim>::refine_grid ()\n  {\n    Vector<float> estimated_error_per_cell (triangulation.n_active_cells());\n\n    typename FunctionMap<dim>::type neumann_boundary;\n    KellyErrorEstimator<dim>::estimate (dof_handler,\n                                        QGauss<dim-1>(2),\n                                        neumann_boundary,\n                                        solution,\n                                        estimated_error_per_cell);\n\n    GridRefinement::refine_and_coarsen_fixed_number (triangulation,\n                                                     estimated_error_per_cell,\n                                                     0.3, 0.03);\n\n    triangulation.execute_coarsening_and_refinement ();\n  }\n\n\n  // @sect4{ElasticProblem::output_results}\n\n  // The output happens mostly as has been shown in previous examples\n  // already. The only difference is that the solution function is vector\n  // valued. The <code>DataOut</code> class takes care of this automatically,\n  // but we have to give each component of the solution vector a different\n  // name.\n  template <int dim>\n  void ElasticProblem<dim>::output_results (const unsigned int cycle) const\n  {\n    std::string filename = \"solution-\";\n    filename += ('0' + cycle);\n    Assert (cycle < 10, ExcInternalError());\n\n    filename += \".vtk\";\n    std::ofstream output (filename.c_str());\n\n    DataOut<dim> data_out;\n    data_out.attach_dof_handler (dof_handler);\n\n\n\n    // As said above, we need a different name for each component of the\n    // solution function. To pass one name for each component, a vector of\n    // strings is used. Since the number of components is the same as the\n    // number of dimensions we are working in, the following\n    // <code>switch</code> statement is used.\n    //\n    // We note that some graphics programs have restriction as to what\n    // characters are allowed in the names of variables. The library therefore\n    // supports only the minimal subset of these characters that is supported\n    // by all programs. Basically, these are letters, numbers, underscores,\n    // and some other characters, but in particular no whitespace and\n    // minus/hyphen. The library will throw an exception otherwise, at least\n    // if in debug mode.\n    //\n    // After listing the 1d, 2d, and 3d case, it is good style to let the\n    // program die if we run upon a case which we did not consider. Remember\n    // that the <code>Assert</code> macro generates an exception if the\n    // condition in the first parameter is not satisfied. Of course, the\n    // condition <code>false</code> can never be satisfied, so the program\n    // will always abort whenever it gets to the default statement:\n    std::vector<std::string> solution_names;\n    switch (dim)\n      {\n      case 1:\n        solution_names.push_back (\"displacement\");\n        break;\n      case 2:\n        solution_names.push_back (\"x_displacement\");\n        solution_names.push_back (\"y_displacement\");\n        break;\n      case 3:\n        solution_names.push_back (\"x_displacement\");\n        solution_names.push_back (\"y_displacement\");\n        solution_names.push_back (\"z_displacement\");\n        break;\n      default:\n        Assert (false, ExcNotImplemented());\n      }\n\n    // After setting up the names for the different components of the solution\n    // vector, we can add the solution vector to the list of data vectors\n    // scheduled for output. Note that the following function takes a vector\n    // of strings as second argument, whereas the one which we have used in\n    // all previous examples accepted a string there. In fact, the latter\n    // function is only a shortcut for the function which we call here: it\n    // puts the single string that is passed to it into a vector of strings\n    // with only one element and forwards that to the other function.\n    data_out.add_data_vector (solution, solution_names);\n    data_out.build_patches ();\n    data_out.write_vtk (output);\n  }\n\n\n\n  // @sect4{ElasticProblem::run}\n\n  // The <code>run</code> function does the same things as in step-6, for\n  // example. This time, we use the square [-1,1]^d as domain, and we refine\n  // it twice globally before starting the first iteration.\n  //\n  // The reason is the following: we use the <code>Gauss</code> quadrature\n  // formula with two points in each direction for integration of the right\n  // hand side; that means that there are four quadrature points on each cell\n  // (in 2D). If we only refine the initial grid once globally, then there\n  // will be only four quadrature points in each direction on the\n  // domain. However, the right hand side function was chosen to be rather\n  // localized and in that case all quadrature points lie outside the support\n  // of the right hand side function. The right hand side vector will then\n  // contain only zeroes and the solution of the system of equations is the\n  // zero vector, i.e. a finite element function that it zero everywhere. We\n  // should not be surprised about such things happening, since we have chosen\n  // an initial grid that is totally unsuitable for the problem at hand.\n  //\n  // The unfortunate thing is that if the discrete solution is constant, then\n  // the error indicators computed by the <code>KellyErrorEstimator</code>\n  // class are zero for each cell as well, and the call to\n  // <code>refine_and_coarsen_fixed_number</code> on the\n  // <code>triangulation</code> object will not flag any cells for refinement\n  // (why should it if the indicated error is zero for each cell?). The grid\n  // in the next iteration will therefore consist of four cells only as well,\n  // and the same problem occurs again.\n  //\n  // The conclusion needs to be: while of course we will not choose the\n  // initial grid to be well-suited for the accurate solution of the problem,\n  // we must at least choose it such that it has the chance to capture the\n  // most striking features of the solution. In this case, it needs to be able\n  // to see the right hand side. Thus, we refine twice globally. (Note that\n  // the <code>refine_global</code> function is not part of the\n  // <code>GridRefinement</code> class in which\n  // <code>refine_and_coarsen_fixed_number</code> is declared, for\n  // example. The reason is first that it is not an algorithm that computed\n  // refinement flags from indicators, but more importantly that it actually\n  // performs the refinement, in contrast to the functions in\n  // <code>GridRefinement</code> that only flag cells without actually\n  // refining the grid.)\n  template <int dim>\n  void ElasticProblem<dim>::run ()\n  {\n    for (unsigned int cycle=0; cycle<8; ++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 (2);\n          }\n        else\n          refine_grid ();\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}\n\n// @sect3{The <code>main</code> function}\n\n// After closing the <code>Step8</code> namespace in the last line above, the\n// following is the main function of the program and is again exactly like in\n// step-6 (apart from the changed class names, of course).\nint main ()\n{\n  try\n    {\n      dealii::deallog.depth_console (0);\n\n      Step8::ElasticProblem<2> elastic_problem_2d;\n      elastic_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\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": "c5ae1d5bfd2e2928ab5bc1fb4b784ab2e6e9e3a3", "size": 36151, "ext": "cc", "lang": "C++", "max_stars_repo_path": "MHD/examples/step-8/step-8.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-8/step-8.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-8/step-8.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.7413366337, "max_line_length": 95, "alphanum_fraction": 0.6435506625, "num_tokens": 8255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6654105454764747, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.4652912699139118}}
{"text": "\n#include<cstdlib>\n#include<iostream>\n#include<iomanip>\n#include<fstream>\n#include<cmath>\n#include<vector>\n#include <boost/filesystem/operations.hpp>\n#include <boost/program_options.hpp>\n\n\nusing namespace std;\nusing namespace boost::program_options;\n\n\n\nint main(int argc, const char *argv[]) {\n\n    /*User Inputs*/\n    //string ligandNumText = \"USERINPUT_LIGAND_NUMBER\";\n    //string npChargeText = \"USERINPUT_NP_CHARGE\";\n    //string mpiText = \"NODESIZE\";\n\n    string ligandNumFileNameText = \"USERINPUT_LIGAND_FILENAME\";\n    string saltText = \"USERINPUTSALT\";\n    string dataSetCountText = \"USERINPUT_DATASETCOUNT\";\n\n    // Dev inputs\n    string vlp1ChargeText = \"DEVINPUT_VLP1_CHARGE\";\n    string vlp2ChargeText = \"DEVINPUT_VLP2_CHARGE\";\n    string ligandChargeText = \"DEVINPUT_LIGAND_CHARGE\";\n\n    const double pi = 3.141593;\n    // big for NP, small for ligand\n    int n, Q_vlp1, Q_vlp2;       //dev input\n    int e2k2ratio; //user input\n    double c;       //user input\n    double D, d;    //dev input, but could be made user input\n    int q;          //dev input\n\n    int mpiProcs;\n\n    //  Details on the datasets to be used (first dumpstep, number of directly subsequent steps):\n    int initDumpStep, dataSetCount;\n\n\n    // Specify variables via command line (-X x):\n    options_description desc(\"Usage:\\nrandom_mesh <options>\");\n    desc.add_options()\n            (\"help,h\", \"print usage message\")\n            (\"Qvlp1,E\", value<int>(&Q_vlp1)->default_value(-1500), \"Q_E2 in e\")\n            (\"Qvlp2,K\", value<int>(&Q_vlp2)->default_value(-600), \"Q_K2 in e\")\n            (\"e2k2ratio,r\", value<int>(&e2k2ratio)->default_value(1), \"e2:k2 in multiples\")\n            (\"NLigand,n\", value<int>(&n)->default_value(100))\n            (\"Salt,c\", value<double>(&c)->default_value(0.150), \"c in Molars\")\n            (\"qnp,q\", value<int>(&q)->default_value(45), \"q in e\")\n            (\"NPDiameter,D\", value<double>(&D)->default_value(56), \"D in nm\")\n            (\"LDiameter,d\", value<double>(&d)->default_value(6.7), \"d in nm\")\n            (\"Mpi_procs,m\", value<int>(&mpiProcs)->default_value(1), \"Number of MPI procs for Lammps\")\n            (\"initDumpStep,i\", boost::program_options::value<int>(&initDumpStep)->default_value(0),\n             \"Specify the initial dump step to be used (dump step, not timestep).\")\n            (\"dataSetCount,N\", boost::program_options::value<int>(&dataSetCount)->default_value(150),\n             \"Specify the number of subsequent datasets to use after the initial dump step.\");\n    //hard code the ratio\n\n    variables_map vm;\n    store(parse_command_line(argc, argv, desc), vm);\n    notify(vm);\n\n\n    /*************************Preprocessing*************************/\n    /*Open a new the template file*/\n\n\n    /******************computations of dev variables****************/\n\n    double devInputQvlp1Charge = Q_vlp1 * (exp((1.64399 * 56) / sqrt(1 / c)) / (1 + ((1.64399 * 56) / sqrt(1 / c))));\n    devInputQvlp1Charge = devInputQvlp1Charge * (1.6018 * 1e-19) / (1.60074 * 1e-19);\n    \n    double devInputQvlp2Charge = Q_vlp2 * (exp((1.64399 * 56) / sqrt(1 / c)) / (1 + ((1.64399 * 56) / sqrt(1 / c))));\n    devInputQvlp2Charge = devInputQvlp2Charge * (1.6018 * 1e-19) / (1.60074 * 1e-19);\n    \n    double devInputLigandCharge = q * (exp((1.64399 * 6.7) / sqrt(1 / c)) / (1 + ((1.64399 * 6.7) / sqrt(1 / c))));\n    devInputLigandCharge = devInputLigandCharge * (1.6018 * 1e-19) / (1.60074 * 1e-19);\n\n    double userInputSalt = 1 / (1e3 * sqrt(1 / (2 * 4 * pi * 0.714295 * (6.022 * 1e23) * c)));\n    //double userInputSalt = 3.2879795708993616*1e9/sqrt(1/c);\n    userInputSalt = userInputSalt * 56 * 1e-9;\n    \n    \n    std::string initcoords = \"initCoords_\" + std::to_string(n);\n    if(e2k2ratio==1)\n        initcoords = initcoords+\"x_1-1\";\n    else if(e2k2ratio == 4)\n        initcoords = initcoords+\"x_1-4\";\n    initcoords = initcoords + \".assembly\";\n    cout<<\"\\n ===>\"<<initcoords;\n    ofstream inputScript(\"in.lammps\", ios::trunc);\n    if (inputScript.is_open()) {\n\n        /*Open the template file*/\n        string line;\n        ifstream inputTemplate(\"infiles/in.lammps.template\", ios::in);\n        if (inputTemplate.is_open()) {\n            while (getline(inputTemplate, line)) {\n//                std::size_t found = line.find(ligandNumText);\n//                if (found != std::string::npos)\n//                    line.replace(found, ligandNumText.length(),  std::to_string(n));\n\n//                found = line.find(npChargeText);\n//                if (found != std::string::npos)\n//                    line.replace(found, npChargeText.length(), std::to_string(userInputNpCharge));\n\n                // Added for bnsl\n                std::size_t found = line.find(vlp1ChargeText);\n                if (found != std::string::npos)\n                    line.replace(found, vlp1ChargeText.length(), std::to_string(devInputQvlp1Charge));\n                found = line.find(vlp2ChargeText);\n                if (found != std::string::npos)\n                    line.replace(found, vlp2ChargeText.length(), std::to_string(devInputQvlp2Charge));\n\n                found = line.find(ligandChargeText);\n                if (found != std::string::npos)\n                    line.replace(found, ligandChargeText.length(), std::to_string(devInputLigandCharge));\n\n                found = line.find(saltText);\n                if (found != std::string::npos)\n                    line.replace(found, saltText.length(), std::to_string(userInputSalt));\n\n                //unsure\n                found = line.find(dataSetCountText);\n                if (found != std::string::npos)\n                    line.replace(found, dataSetCountText.length(), std::to_string(dataSetCount));\n\n               found = line.find(ligandNumFileNameText);\n               if (found != std::string::npos)\n                   line.replace(found, ligandNumFileNameText.length(), initcoords);\n\n                inputScript << line << endl;\n            }\n            inputTemplate.close();\n        } else cout << \"Unable to open the template input script\" << endl;\n        inputScript.close();\n    } else cout << \"Unable create a input Script\" << endl;\n\n\n    /*************************Lammps Call*************************/\n/*\n    //string lammpsExeCMD = \"aprun -n NODESIZE lmp_mpi < in.lammps\"; //This is Bigred and New Lammps\n    //string lammpsExeCMD = \"mpirun -n NODESIZE lmp_g++ < in.lammps\"; //This is RedHat\n    string lammpsExeCMD = \"mpiexec -n NODESIZE lmp_mpi < in.lammps\"; //This is windows and newest Lammps\n    //string lammpsExeCMD = \"aprun -n NODESIZE lmp_xe6  < in.lammps\"; //This is Bigred and OLD lammps\n    std::size_t found = lammpsExeCMD.find(mpiText);\n    if (found != std::string::npos)\n        lammpsExeCMD.replace(found, mpiText.length(), std::to_string(mpiProcs));\n\n    //Creating the char array\n    char lammpsExeCMD_array[lammpsExeCMD.length() + 1];\n    strcpy(lammpsExeCMD_array, lammpsExeCMD.c_str());\n\n    //System call\n    //system(\"ls\");\n    int returnedCode;\n    //Checking if processor is available\n    if (!system(NULL))\n        exit(EXIT_FAILURE);\n\n    returnedCode = system(lammpsExeCMD_array);\n    cout << \"The value returned was: \" << returnedCode << endl;\n\n    if(returnedCode!=0)\n        exit(EXIT_FAILURE);\n*/\n    cout << \"Preprocessing completed.\" << endl;\n    return 0;\n}\n// End of main\n", "meta": {"hexsha": "61877ef47be6bef0fe2db2d978ab264d0ea27e85", "size": 7315, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/preprocessing/main.cpp", "max_stars_repo_name": "vinita84/bnsl_old", "max_stars_repo_head_hexsha": "77ca514d26c890388d55f69727f01c025f968c3f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/preprocessing/main.cpp", "max_issues_repo_name": "vinita84/bnsl_old", "max_issues_repo_head_hexsha": "77ca514d26c890388d55f69727f01c025f968c3f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/preprocessing/main.cpp", "max_forks_repo_name": "vinita84/bnsl_old", "max_forks_repo_head_hexsha": "77ca514d26c890388d55f69727f01c025f968c3f", "max_forks_repo_licenses": ["Apache-2.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.095505618, "max_line_length": 117, "alphanum_fraction": 0.5974025974, "num_tokens": 2011, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246118695629, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.46526762585082554}}
{"text": "#include <igl/per_vertex_normals.h>\n#include <igl/principal_curvature.h>\n#include <igl/avg_edge_length.h>\n#include <igl/massmatrix.h>\n#include <igl/adjacency_list.h>\n#include <igl/per_face_normals.h>\n#include <igl/barycenter.h>\n#include <igl/pinv.h>\n#include <igl/edges.h>\n#include <Eigen/SparseCore>\n#include <igl/adjacency_list.h>\n#include <igl/adjacency_matrix.h>\n#include <igl/per_face_normals.h>\n#include <igl/per_vertex_normals.h>\n#include <igl/avg_edge_length.h>\n#include <igl/edge_flaps.h>\n#include <igl/unique_edge_map.h>\n#include <igl/vertex_triangle_adjacency.h>\n#include <igl/principal_curvature.h>\n#include <igl/collapse_edge.h>\n#include <igl/is_edge_manifold.h>\n#include <igl/C_STR.h>\n#include <igl/circulation.h>\n#include <igl/decimate.h>\n#include <igl/shortest_edge_and_midpoint.h>\n#include <igl/infinite_cost_stopping_condition.h>\nusing namespace std;\n\nvoid collapse_edges(Eigen::MatrixXd & V,Eigen::MatrixXi & F, Eigen::VectorXi & feature, Eigen::VectorXd & high, Eigen::VectorXd & low){\n        using namespace Eigen;\n    MatrixXi E,uE,EI,EF;\n    VectorXi EMAP,I,J;\n    VectorXd data;\n    Eigen::MatrixXd U;\n    Eigen::MatrixXi G;\n    // VectorXd p;\n    std::vector<std::vector<int>> uE2E;\n    std::vector<std::vector<int>> vertex_face_adjacency;\n    std::vector<int> small_edges;\n    int e1,e2,f1,f2,e;\n    int n = V.rows();\n    \n    \n    int num_feature = feature.size();\n    std::vector<std::vector<int>> A;\n    igl::adjacency_list(F,A);\n    \n    std::vector<bool> is_feature_vertex;\n    is_feature_vertex.resize(n);\n    \n    for (int s = 0; s < num_feature; s++) {\n        is_feature_vertex[feature(s)] = true;\n    }\n    \n    //igl::is_edge_manifold(F);\n    \n    std::function<bool(\n                       const Eigen::MatrixXd &,\n                       const Eigen::MatrixXi &,\n                       const Eigen::MatrixXi &,\n                       const Eigen::VectorXi &,\n                       const Eigen::MatrixXi &,\n                       const Eigen::MatrixXi &,\n                       const igl::min_heap< std::tuple<double,int,int> > &,\n                       const Eigen::VectorXi &,\n                       const Eigen::MatrixXd &,\n                       const int,\n                       const int,\n                       const int,\n                       const int,\n                       const int)>  stopping_condition;\n    \n    std::function<void(\n                       const int,\n                       const Eigen::MatrixXd &,\n                       const Eigen::MatrixXi &,\n                       const Eigen::MatrixXi &,\n                       const Eigen::VectorXi &,\n                       const Eigen::MatrixXi &,\n                       const Eigen::MatrixXi &,\n                       double &,\n                       Eigen::RowVectorXd &)> shortest_edge_and_midpoint_lambda = [&A,&feature,&low,&high,&is_feature_vertex](\n                                                                 const int e,\n                                                                 const Eigen::MatrixXd & V,\n                                                                 const Eigen::MatrixXi & F,\n                                                                 const Eigen::MatrixXi & E,\n                                                                 const Eigen::VectorXi & EMAP,\n                                                                 const Eigen::MatrixXi & EF,\n                                                                 const Eigen::MatrixXi & EI,\n                                                                 double & cost,\n                                                                 Eigen::RowVectorXd & p)->void{\n        igl::shortest_edge_and_midpoint(e,V,F,E,EMAP,EF,EI,cost,p);\n        if (is_feature_vertex[E(e,0)] || is_feature_vertex[E(e,1)] ) {\n            cost = std::numeric_limits<double>::infinity();\n            return;\n        }\n        if ( (V.row(E(e,0))-V.row(E(e,1))).norm() > ((low(E(e,0))+low(E(e,1)))/2) ) {\n            cost = std::numeric_limits<double>::infinity();\n            return;\n        }\n        for(int i = 0; i < A[E(e,1)].size(); i++){\n            if((V.row(A[E(e,1)][i])-p).norm() > high(E(e,1))){\n                cost = std::numeric_limits<double>::infinity();\n                return;\n            }\n        }\n        for(int r = 0; r < A[E(e,0)].size(); r++){\n            if((V.row(A[E(e,0)][r])-p).norm() > high(E(e,0))){\n                cost = std::numeric_limits<double>::infinity();\n                return;\n            }\n        }\n        //std::cout << \"Mathing...\" << std::endl;\n        // consider both directions to circulate\n        for(int direction = 0;direction<2;direction++)\n        {\n            // consider each face\n            for(const int f : igl::circulation(e,direction,EMAP,EF,EI))\n            {\n                if (f < 0) {//?????\n                    cost = std::numeric_limits<double>::infinity();\n                    return;\n                }\n                //std::cout << f << std::endl;\n                if( f == 0 || f ==  igl::circulation(e,direction,EMAP,EF,EI).size()-1)\n                {\n                    \n                    // skip\n                    continue;\n                }\n                // Grab the three corners of the face\n                Eigen::RowVector3d p_before[3], p_after[3];\n                for(int c = 0;c<3;c++)\n                {\n                    // vertex index\n//                    std::cout << e << std::endl;\n//                    std::cout << f << std::endl;\n//                    std::cout << c << std::endl;\n                    const int v = F(f,c);\n                    if( v == E(e,0) || v == E(e,1))\n                    {\n                        p_after[c] = p;\n                    }else\n                    {\n                        p_after[c] = V.row(v);\n                    }\n                    p_before[c] = V.row(v);\n                }\n                const Eigen::RowVector3d n_before =\n                ((p_before[1]- p_before[0]).cross(p_before[2]- p_before[0])).normalized();\n                const Eigen::RowVector3d n_after =\n                ((p_after[1]- p_after[0]).cross(p_after[2]- p_after[0])).normalized();\n                if( n_before.dot(n_after) < n_after.norm()/2 )\n                   {\n                       cost = std::numeric_limits<double>::infinity();\n                   }\n                   }\n                   }\n        //std::cout << \"Mathed!\" << std::endl;\n        \n        \n        };\n    \n    igl::infinite_cost_stopping_condition(shortest_edge_and_midpoint_lambda,stopping_condition);\n    \n\n     \n    //std::cout << \"??\" << std::endl;\n    igl::decimate(V,F,shortest_edge_and_midpoint_lambda,stopping_condition,U,G,J,I);\n    //std::cout << \"!!\" << std::endl;\n\n    Eigen::VectorXd high_new,low_new;\n    Eigen::VectorXi feature_new;\n    feature_new.resize(num_feature);\n    high_new.resize(U.rows());\n    low_new.resize(U.rows());\n    int j = 0;\n    for (int s = 0; s<U.rows(); s++) {\n        high_new(s) = high(I(s));\n        low_new(s) = low(I(s));\n        if (is_feature_vertex[I(s)]) {\n            feature_new(j) = s;\n            j = j+1;\n        }\n    }\n    \n    // PLACEHOLDER\n    \n    V = U;\n    F = G;\n    high = high_new;\n    low = low_new;\n    feature = feature_new;\n    \n    \n    \n    \n    \n}\n\n\n// g++ -I/usr/local/libigl/external/eigen -I/usr/local/libigl/include -std=c++11 -framework Accelerate main.cpp remesh_botsch.cpp -o main\n\n", "meta": {"hexsha": "bdf4866a8b76786974a8583214c9a0350504fb3b", "size": 7449, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/collapse_edges.cpp", "max_stars_repo_name": "sgsellan/opening-and-closing-surfaces", "max_stars_repo_head_hexsha": "57127178c2e8d50396c02a853c4456a90e9220c5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2020-10-27T00:03:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T19:44:35.000Z", "max_issues_repo_path": "src/collapse_edges.cpp", "max_issues_repo_name": "sgsellan/opening-and-closing-surfaces", "max_issues_repo_head_hexsha": "57127178c2e8d50396c02a853c4456a90e9220c5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/collapse_edges.cpp", "max_forks_repo_name": "sgsellan/opening-and-closing-surfaces", "max_forks_repo_head_hexsha": "57127178c2e8d50396c02a853c4456a90e9220c5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-10-27T01:40:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-23T13:42:16.000Z", "avg_line_length": 36.5147058824, "max_line_length": 137, "alphanum_fraction": 0.458585045, "num_tokens": 1691, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246118695629, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.46526762585082554}}
{"text": "// **************************************************************************************************\n//\n// The MIT License (MIT)\n// \n// Copyright (c) 2017 Pierre Lebreton\n// \n// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and \n// associated documentation files (the \"Software\"), to deal in the Software without restriction, including \n// without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell \n// copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the \n// following conditions:\n// \n// The above copyright notice and this permission notice shall be included in all copies or substantial \n// portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT \n// LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. \n// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, \n// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE \n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n// **************************************************************************************************\n\n\n\n\n#include <iostream>\n#include <fstream>\n#include <opencv2/highgui.hpp>\n#include <opencv2/imgproc.hpp>\n#include <opencv2/objdetect.hpp>\n#include <boost/program_options.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n\n#include <list>\n\ntemplate<typename T>\nstd::vector<T> polyfit( const std::vector<T>& oX, const std::vector<T>& oY, int nDegree ) {\n\tusing namespace boost::numeric::ublas;\n \n\tif ( oX.size() != oY.size() )\n\t\tthrow std::invalid_argument( \"X and Y vector sizes do not match\" );\n \n\t// more intuative this way\n\tnDegree++;\n\t\n\tsize_t nCount =  oX.size();\n\tmatrix<T> oXMatrix( nCount, nDegree );\n\tmatrix<T> oYMatrix( nCount, 1 );\n\t\n\t// copy y matrix\n\tfor ( size_t i = 0; i < nCount; i++ )\n\t{\n\t\toYMatrix(i, 0) = oY[i];\n\t}\n \n\t// create the X matrix\n\tfor ( size_t nRow = 0; nRow < nCount; nRow++ )\n\t{\n\t\tT nVal = 1.0f;\n\t\tfor ( int nCol = 0; nCol < nDegree; nCol++ )\n\t\t{\n\t\t\toXMatrix(nRow, nCol) = nVal;\n\t\t\tnVal *= oX[nRow];\n\t\t}\n\t}\n \n\t// transpose X matrix\n\tmatrix<T> oXtMatrix( trans(oXMatrix) );\n\t// multiply transposed X matrix with X matrix\n\tmatrix<T> oXtXMatrix( prec_prod(oXtMatrix, oXMatrix) );\n\t// multiply transposed X matrix with Y matrix\n\tmatrix<T> oXtYMatrix( prec_prod(oXtMatrix, oYMatrix) );\n \n\t// lu decomposition\n\tpermutation_matrix<T> pert(oXtXMatrix.size1());\n\tconst std::size_t singular = lu_factorize(oXtXMatrix, pert);\n\t// must be singular\n\tif( singular != 0 ) {\n\t\t// then the regression cannot be done... return an empty vector\n\t\treturn std::vector<T>();\n\t}\n \n\t// backsubstitution\n\tlu_substitute(oXtXMatrix, pert, oXtYMatrix);\n \n\t// copy the result to coeff\n\treturn std::vector<T>( oXtYMatrix.data().begin(), oXtYMatrix.data().end() );\n}\n\n\nfloat simpleShape(cv::Mat &image) {\n\tif(image.empty()) return 0;\n\n\tcv::Mat gray;\n\tcv::cvtColor(image, gray, cv::COLOR_BGR2GRAY);\n\n\tcv::Mat edges;\n\tcv::Canny(gray, edges, 200, 400);\n\n\tcv::Mat result(image.size(), CV_8UC3, cv::Scalar(0,0,0));\n\n\tstd::vector<std::vector<cv::Point> > contours0;\n\tstd::vector<std::vector<cv::Point> > contours;\n\tstd::vector<cv::Vec4i> hierarchy;\n    cv::findContours( edges, contours0, hierarchy, cv::RETR_TREE, cv::CHAIN_APPROX_SIMPLE);\n\n\tstd::cout << contours0.size() << \" \";\n\n\tcv::drawContours( result, contours, 3, cv::Scalar(128,0,255),\n                  3, cv::LINE_AA, hierarchy, std::abs(3) );\n\n    contours.resize(contours0.size());\n    for( size_t k = 0; k < contours0.size(); k++ )\n        cv::approxPolyDP(cv::Mat(contours0[k]), contours[k], 1, true);\n\t\t\n\n\tcv::drawContours( result, contours, 3, cv::Scalar(128,255,255),\n                  3, cv::LINE_AA, hierarchy, std::abs(3) );\n\n\tcv::imshow(\"result\", edges);\n\tcv::waitKey();\n\n\treturn 0;\n}\n\n\n\nfloat  horizonLine(cv::Mat &image) {\n\tif(image.empty()) return 0;\n\n\n\tstd::vector<float> x, y;\n\n\tcv::Mat gray;\n\tcv::cvtColor(image, gray, cv::COLOR_BGR2GRAY);\n\n\tcv::Mat edges;\n\tcv::Canny(gray, edges, 110, 220);\n\n\tstd::vector<cv::Vec4i> lines;\n    cv::HoughLinesP( edges, lines, 1, CV_PI/2, 0, 30, 1 );\n    float meanY = 0; int nbLines = 0;\n    float meanY2 = 0;\n    for( size_t i = 0; i < lines.size(); i++ )\n    {\n    \tif(lines[i][0] == lines[i][2]) continue;\n\n\t\tif(lines[i][1] > (.7 * image.rows)) continue;\n\t\tif(lines[i][1] < (.3 * image.rows)) continue;\n\n        cv::line( image, cv::Point(lines[i][0], lines[i][1]),\n            cv::Point(lines[i][2], lines[i][3]), cv::Scalar(0,0,255), 3, 8 );\n\n        x.push_back(lines[i][0]);\n\t\tx.push_back(lines[i][2]);\n\t\ty.push_back(lines[i][1]);\n\t\ty.push_back(lines[i][3]);\n\n\t\tmeanY += lines[i][1]; ++nbLines;\n\t\tmeanY += lines[i][3]; ++nbLines;\n\n\t\tmeanY2 += lines[i][1] * lines[i][1];\n\t\tmeanY2 += lines[i][3] * lines[i][3];\n\n    }\n    meanY /= nbLines;\n    meanY2 /= nbLines;\n\n    float stdev = std::sqrt(meanY2 - meanY*meanY);\n    float meanValue = meanY;\n    \n    meanY = 0; nbLines = 0;\n    for( size_t i = 0; i < lines.size(); i++ )\n    {\n    \tif(lines[i][0] == lines[i][2]) continue;\n\n\t\tif(lines[i][1] > (.7 * image.rows)) continue;\n\t\tif(lines[i][1] < (.3 * image.rows)) continue;\n\n        if(std::abs(lines[i][1] - meanValue) > 1.3 * stdev) continue;\n\n\t\tmeanY += lines[i][1]; ++nbLines;\n\t\tmeanY += lines[i][3]; ++nbLines;\n\n    }\n    meanY /= nbLines;\n\n\n\n    if(nbLines == 0) {\n    \tmeanY = image.rows/2;\n    } else {\n    \tstd::vector<float> model = polyfit<float>(x, y, 1);\n\n\t    if(std::abs(model[0]- image.rows/2) < std::abs(meanY - image.rows/2))\n\t    \tmeanY = model[0];\n    }\n\n\n\t// cv::line(image, cv::Point_<int>(0, meanY), cv::Point_<int>(image.cols, meanY), cv::Scalar( 0, 255, 0 ), 2);\n\n\n\nreturn meanY;\n\n\n}\n\n\nfloat faceLine(cv::Mat &image) {\n\tcv::Mat gray;\n\tcv::cvtColor(image, gray, cv::COLOR_BGR2GRAY);\n\n\tcv::CascadeClassifier face_cascade;\n\tcv::CascadeClassifier faceProfil_cascade;\n\tbool faceCascadeEnabled = false;\n\tbool faceProfilCascadeEnabled = false;\n\n\t// ------------------------------------------------------------------------------------------------\n\t// init haar cascades framework\n\n\tif(face_cascade.load(\"haarcascade_frontalface_alt.xml\")) {\n\t\tfaceCascadeEnabled = true;\n\t} else {\n\t\tstd::cerr<< \"[I] cannot open: haarcascade_frontalface_alt.xml\" << std::endl;\n\t}\n\n\tif(faceProfil_cascade.load(\"haarcascade_profileface.xml\")) {\n\t\tfaceProfilCascadeEnabled = true;\n\t} else {\n\t\tstd::cerr<< \"[I] cannot open: haarcascade_profileface.xml\" << std::endl;\n\t}\n\n\n\t// ------------------------------------------------------------------------------------------------\n\t// find features\n\n\tstd::list<cv::Rect> allFeatures;\n\tstd::vector<cv::Rect> faceFeatures;\n\tif(faceCascadeEnabled)\n\t\tface_cascade.detectMultiScale( gray, faceFeatures, 2, 2, 0| cv::CASCADE_SCALE_IMAGE, cv::Size(15, 15) );\n\n\tfor(size_t i = 0 ; i < faceFeatures.size() ; ++i) {\n\t\tcv::rectangle(image, faceFeatures[i], cv::Scalar( 0, 0, 255 ));\n\t\tallFeatures.push_back(faceFeatures[i]);\n\t}\n\n\tfaceFeatures.clear();\n\tif(faceProfilCascadeEnabled)\n\t\tfaceProfil_cascade.detectMultiScale( gray, faceFeatures, 2, 2, 0|cv::CASCADE_SCALE_IMAGE, cv::Size(15, 15) );\n\n\tfor(size_t i = 0 ; i < faceFeatures.size() ; ++i) {\n\t\tcv::rectangle(image, faceFeatures[i], cv::Scalar( 255, 255, 0 ));\n\t\tallFeatures.push_back(faceFeatures[i]);\n\t}\n\n\tif(allFeatures.size() < 2) return -1;\n\n\n\tfloat mnX = image.cols;\n\tfloat mxX = 0;\n\tfor( std::list<cv::Rect>::iterator it = allFeatures.begin() ; it != allFeatures.end() ; ++it ) {\n\t\tfloat x = it->x + it->width /2;\n\n\t\tif(x > mxX) mxX = x;\n\t\tif(x < mnX) mnX = x;\n\t}\n\n\tif((mxX-mnX)/image.cols < 0.2) return -1;\t// if the detected faces are collocated in one area, then skip it.\n\n\t// ------------------------------------------------------------------------------------------------\n\t// find equatorial line\n\n\n\n\tfloat meanY = 0; int nbLines = 0;\n    float meanY2 = 0;\n    for( std::list<cv::Rect>::iterator it = allFeatures.begin() ; it != allFeatures.end() ; ++it ) {\n    \tmeanY += it->y + it->height /2;\n    \tmeanY2 += (it->y + it->height /2)*(it->y + it->height /2);\n    \t++nbLines;\n    }\n\n    if(nbLines == 0) return -1;\n\n    meanY /= nbLines;\n    meanY2 /= nbLines;\n\n\n    float stdev = std::sqrt(meanY2 - meanY*meanY);\n    float meanValue = meanY;\n    \n    meanY = 0; nbLines = 0;\n\n    for( std::list<cv::Rect>::iterator it = allFeatures.begin() ; it != allFeatures.end() ; ++it ) {\n    \tfloat y = it->y + it->height /2;\n\n    \tif(std::abs(y-meanValue) > 1.3 * stdev) continue;\n\n    \tmeanY += y;\n    \t++nbLines;\n    }\n\n    if(nbLines == 0) return meanValue;\n\n\n\tmeanY /= nbLines;\n\n\tif(meanY < (gray.rows * 1 / 3) && allFeatures.size() < 2) { // we need at least two faces to justify an equatorial line lower higher the first third of the image\n\t\treturn -1; \n\t}\n\n\n\treturn meanY;\n\n\n}\n\nfloat percentageSaliency(const cv::Mat& image, float slicePosition, float sliceHeightDegree = 10.f) {\n\t\n\tdouble sumImage = cv::sum( image )[0];\n\tfloat sumSlice = 0;\n\n\tfloat sliceHeight = sliceHeightDegree * (image.rows / 180);\n\n\tfor(int i = static_cast<int>(std::max(slicePosition - sliceHeight, 0.f)) ; i < std::min(static_cast<int>(slicePosition + sliceHeight), image.rows) ; ++i) {\n\t\tfor(int j = 0 ; j < image.cols ; ++j) {\n\t\t\tsumSlice += image.at<float>(i,j);\n\t\t}\n\t}\n\n\treturn sumSlice / sumImage;\n\n}\n\n\nfloat salientCenter(const cv::Mat& image, int step = 5) {\n\t\n\tstd::vector<float> histogram(180/step);\n\tint offset = 0; //static_cast<int>(30.f*(step/180.f));\n\n\tfloat sumHist = 0;\n\tfor(int i = offset ; i < 180-offset ; i+=step) {\n\t\tfloat top    = image.rows*static_cast<float>(i)/180;\n\t\tfloat bottom = image.rows*static_cast<float>(i+step)/180;\n\n\t\tfloat sum = 0;\n\t\tfor(int ii = top ; ii < bottom ; ++ii) {\n\t\t\tfor(int jj = 0 ; jj < image.cols ; ++jj) {\n\t\t\t\tsum += image.at<float>(ii,jj);\n\t\t\t}\n\t\t}\n\n\t\tsum /= (bottom-top) * image.cols;\n\t\thistogram[i/step] = sum;\n\t\tsumHist += sum;\n\t}\n\n\tfloat loc = 0;\n\tfor(size_t i = offset ; i < histogram.size() - offset ; ++i) {\n\t\tloc += i*step*histogram[i]/sumHist;\n\t}\n\n\treturn image.rows * static_cast<float>(loc)/180.f;\n\n}\n\n\nvoid applyGaussianEquatorialPrior(cv::Mat& image, float gaussianM = 0.f, float gaussianSD = 500.f, bool central = false) {\n\t\n\tfor(int i = 0 ; i < image.rows ; ++i) {\n\t\tfloat lat = (.5f - static_cast<float>(i)/image.rows) * 180.f;\n\t\tfloat prior = 0.f;\n\n\t\tif(central)\n\t\t\tprior =  (.01 + .40 * exp(-((lat-gaussianM)*(lat-gaussianM))/(gaussianSD))) / .41f;\n\t\telse\n\t\t\tprior =  (.01 + .40 * exp(-((lat-gaussianM)*(lat-gaussianM))/(gaussianSD)) + .75 * exp(-((lat-100)*(lat-100))/(200)) + .75 * exp(-((lat+90)*(lat+90))/(200))) / .41f;\n\n\t\tprior = std::min(1.f, prior);\n\n\t\tfor(int j = 0 ; j < image.cols ; ++j) {\n\t\t\timage.at<float>(i,j) = prior * image.at<float>(i,j);\n\t\t}\n\t}\t\n\n}\n\n\nvoid applyEquatorialPrior(cv::Mat& image, cv::Mat& colorImage, bool central = false, bool print = false) {\n\tfloat scaling_factor = static_cast<float>(image.cols) / 1400.f;\t// normalize the size of the images\n\t\n\tcv::resize(colorImage, colorImage, cv::Size(colorImage.size().width/scaling_factor, colorImage.size().height/scaling_factor));\n\tfloat hz = colorImage.rows / 2;\n\tfloat fc = faceLine(colorImage);\n\n\n\tfloat equatorialLine = hz;\n\n\n\tif(fc > 0) {\n\t\tif(fc > colorImage.rows / 3)\t// prior: faces are not higher than the first third of the image\n\t\t\tequatorialLine = fc;\n\t}\n\n\tfloat slCenter = salientCenter(image);\n\n\tslCenter = std::max(std::min((slCenter - image.rows/2)/image.rows, 0.1f), -0.1f);\n\tslCenter = slCenter * image.rows + image.rows/2;\n\tslCenter = (slCenter/scaling_factor + colorImage.rows / 2) / 2;\n\t\n\n\tif(fc > 0) {\n\t\tif(fc > colorImage.rows / 3)\t// prior: faces are not higher than the first third of the image\n\t\t\tslCenter = fc;\n\t}\n\n\n\tequatorialLine = (.5f - slCenter / colorImage.rows) * 180.f;\n\n\tif(print) std::cout << equatorialLine << std::endl;\n\n\tapplyGaussianEquatorialPrior(image, equatorialLine, 700.f, central);\n\n}\n\n\nvoid bottomThresholdSaliency(cv::Mat &saliency) {\n\tcv::Mat uCharSalmap;\n\tuCharSalmap = 255 * saliency;\n\tuCharSalmap.convertTo(uCharSalmap, CV_8UC1);\n\n\tint histSize[] = {255};\n\tint channels[] = {0};\n\tfloat range[] = { 0, 256 } ;\n \tconst float* histRange = { range };\n\tcv::Mat hist;\n\n\tcv::calcHist(&uCharSalmap, 1, channels, cv::Mat(), hist, 1, histSize, &histRange, true, true);\n\n\tfloat sum = 0;\n\tfloat mid = static_cast<float>(saliency.cols*saliency.rows) * .7;\n\tint theshold = 0;\n\tfor(int i = 0 ; i < hist.rows ; ++i) {\n\t\tsum += hist.at<float>(i,0);\n\n\t\tif(sum > mid) {\n\t\t\ttheshold = i;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tfor(int i = 0 ; i < uCharSalmap.rows ; ++i) {\n\t\tfor(int j = 0 ; j < uCharSalmap.cols ; ++j) {\n\t\t\tif(uCharSalmap.at<unsigned char>(i,j) < theshold) {\n\t\t\t\tuCharSalmap.at<unsigned char>(i,j) = theshold;\n\t\t\t}\n\t\t}\n\t}\n\n\tuCharSalmap.convertTo(saliency, CV_32FC1);\n\tuCharSalmap /= 255;\n\n}\n\n\n\nint main(int argc, char **argv) {\n\n\n\t// ------------------------------------------------------------------------------------------------------------------------------------------\n\t// parse parameters\n\n\tnamespace po = boost::program_options;\n\n\tpo::positional_options_description p;\n\tp.add(\"input-file\", -1);\n\n\tpo::options_description desc(\"Allowed options\");\n\tdesc.add_options()\n\t\t\t(\"help\", \"produce help message\")\n\t\t\t(\"input-file,i\", po::value< std::string >(), \"Saliency input image.\")\n\t\t\t(\"color-file,c\", po::value< std::string >(), \"Color image corresponding to the saliency map.\")\n\t\t\t(\"line,l\", po::value< float >(), \"Add the ground truth equatorial line (in degree [-90,+90]).\")\n\t\t\t(\"output-file,o\", po::value< std::string >(), \"Saliency map with the equatorial prior.\")\n\t\t\t(\"central\", \"Consider only the central part of the Gaussian mixture\")\n\t\t\t(\"no-adapt\", \"No adaptation\")\n\t\t\t(\"print-horizon\", \"Output in the terminal the position of the horizon line\")\n\t;\n\n\n\tpo::variables_map vm;\n\ttry {\n\t\tpo::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm);\n\t\tpo::notify(vm);\n\t} catch(boost::exception &) {\n\t\tstd::cerr << \"Error incorect program options. See --help... \\n\";\n\t\treturn 0;\n\t}\n\n\tif (vm.count(\"help\")) {\n\t\tstd::cout << \"--------------------------------------------------------------------------------\\n\";\n\t\tstd::cout << \"\\t\\tApply the equatorial prior on saliency maps\\n\";\n\t\tstd::cout << \"--------------------------------------------------------------------------------\\n\";\n\t\tstd::cout << \"\\n\\n\";\n\t\tstd::cout << desc << \"\\n\";\n\t\treturn 1;\n\t}\n\n\t\n\tstd::string inputImagePath;\n\tstd::string inputColorImagePath;\n\tstd::string outputPath;\n\n\tbool central = false;\n\tbool noAdapt = false;\n\t\n\tif (vm.count(\"input-file\")) {\n\t\tinputImagePath = vm[\"input-file\"].as< std::string >();\n\t} else {\n\t\tstd::cerr << \"It is required to provide the an input saliency map. See --help\\n\";\n\t\treturn 0;\n\t}\n\n\tif (vm.count(\"color-file\")) {\n\t\tinputColorImagePath = vm[\"color-file\"].as< std::string >();\n\t} else {\n\t\tstd::cerr << \"It is required to provide the an input color image. See --help\\n\";\n\t\treturn 0;\n\t}\n\n\tif (vm.count(\"output-file\")) {\n\t\toutputPath = vm[\"output-file\"].as< std::string >();\n\t} \n\n\tif(vm.count(\"central\")) {\n\t\tcentral = true;\n\t}\n\n\tif(vm.count(\"no-adapt\")) {\n\t\tnoAdapt = true;\n\t}\n\n\tbool printHz = false;\n\tif(vm.count(\"print-horizon\")) {\n\t\tprintHz = true;\n\t}\n\n\n\t// ---------------------------------------------------------------------------------------------------\n\t// Get statistics\n\n\tcv::Mat image = cv::imread(inputImagePath);\n\tif(image.empty()) {\n\t\tstd::cerr << \"Cannot open: \" << inputImagePath << std::endl;\n\t\treturn 0;\n\t}\n\n\tcv::Mat colorImage = cv::imread(inputColorImagePath);\n\tif(colorImage.empty()) {\n\t\tstd::cerr << \"Cannot open: \" << inputColorImagePath << std::endl;\n\t\treturn 0;\n\t}\n\n\n\n\n\tcv::cvtColor(image, image, cv::COLOR_BGR2GRAY);\n\n\timage.convertTo(image, CV_32FC1);\n\timage /= 255;\n\n\n\tif(vm.count(\"second-file\") && vm.count(\"weight\")) {\n\t\tcv::Mat imageW = cv::imread(vm[\"second-file\"].as< std::string >());\n\t\tif(imageW.empty()) {\n\t\t\tstd::cerr << \"cannot open: \" << vm[\"second-file\"].as< std::string >() << std::endl ;\n\t\t} else {\n\t\t\tcv::cvtColor(imageW, imageW, cv::COLOR_BGR2GRAY);\n\t\t\timageW.convertTo(imageW, CV_32FC1);\n\t\t\timageW /= 255;\n\n\t\t\tfloat w = vm[\"weight\"].as< float >();\n\t\t\timage = image * w  + (1 - w) * imageW;\n\t\t}\n\t}\n\n\t// image = cv::Mat(image.size(), CV_32FC1, cv::Scalar(1.0f));\n\n\tif(printHz) std::cout << inputColorImagePath << \", \";\n\n\tif(!noAdapt)\n\t\tapplyEquatorialPrior(image, colorImage, central, printHz);\n\telse\n\t\tapplyGaussianEquatorialPrior(image, 0, 700, central);\n\n\t// bottomThresholdSaliency(image);\n\n\t// if (vm.count(\"line\")) {\n\t// \tfloat line = vm[\"line\"].as< float >();\n\n\n\t// \tline =  image.rows * (90 - line) / 180.f ;\n\n\t// \t// std::cout << line << std::endl;\n\t// applyGaussianEquatorialPrior(image, 0, 500);\n\n\n\tdouble mn, mx;\n\tcv::minMaxLoc(image, &mn, &mx);\n\n\timage = (image - mn) / (mx - mn);\n\n\t// \t// line =  colorImage.rows * (90 - line) / 180.f ;\n\n\t// \t// if(line > 0 && line < colorImage.rows)\n\t// \t// \tcv::line(colorImage, cv::Point_<int>(0, line), cv::Point_<int>(colorImage.cols, line), cv::Scalar( 255, 0, 255), 2);\n\t// } \n\n\t// cv::imshow(\"colorImage\", colorImage);\n\t// cv::waitKey();\n\n\tif(!outputPath.empty()) {\n\t\tcv::Mat tmp;\n\t\tcv::cvtColor(image, tmp, cv::COLOR_GRAY2BGR);\n\t\ttmp *= 255;\n\t\ttmp.convertTo(tmp, CV_8UC3);\n\t\tcv::imwrite(outputPath, tmp);\n\t\t\n\t\treturn 0;\n\t} else {\n\t\tcv::imshow(\"with equatorial prior\", image);\n\t\tcv::waitKey();\n\t}\n\n\n\treturn 0;\n}\n\n", "meta": {"hexsha": "b9df9ad1a9fe8bc9566d19a0d2dae80e1299a379", "size": 17436, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/main-prior.cpp", "max_stars_repo_name": "Telecommunication-Telemedia-Assessment/GBVS360-BMS360-ProSal", "max_stars_repo_head_hexsha": "d0312f54a28e1ef2cf1e1581241571d9612bb36c", "max_stars_repo_licenses": ["MIT", "Unlicense"], "max_stars_count": 26.0, "max_stars_repo_stars_event_min_datetime": "2018-01-23T14:37:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-31T13:53:41.000Z", "max_issues_repo_path": "test/main-prior.cpp", "max_issues_repo_name": "Telecommunication-Telemedia-Assessment/GBVS360-BMS360-ProSal", "max_issues_repo_head_hexsha": "d0312f54a28e1ef2cf1e1581241571d9612bb36c", "max_issues_repo_licenses": ["MIT", "Unlicense"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2018-09-05T23:38:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-27T18:52:18.000Z", "max_forks_repo_path": "test/main-prior.cpp", "max_forks_repo_name": "Telecommunication-Telemedia-Assessment/GBVS360-BMS360-ProSal", "max_forks_repo_head_hexsha": "d0312f54a28e1ef2cf1e1581241571d9612bb36c", "max_forks_repo_licenses": ["MIT", "Unlicense"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-12-13T00:35:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-08T16:55:07.000Z", "avg_line_length": 27.2012480499, "max_line_length": 168, "alphanum_fraction": 0.5998508832, "num_tokens": 5221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907933, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.465267621228565}}
{"text": "#pragma once\n#include <Eigen/Core>\n\n#include \"smoothness_matrix.hpp\"\n#include \"total_derivative.hpp\"\n#include \"../fixed_size_container_type_trait.hpp\"\n#include \"../value_type_trait.hpp\"\n\nnamespace ubs {\n/** @brief Internal namespace */\nnamespace internal {\n\n/**\n * @brief Implementation to evaluate a spline at the specified position.\n *\n * This is implemented using template meta programming (TMP) as one needs to have one sum per dimension. A spline\n * can be evaluated using the following formula.\n * @f[\n * \\mathbf{f}(\\mathbf{t}) = \\sum_{i_1} N_{i_1} \\sum_{i_2} N_{i_2} \\cdots \\sum_{i_M} N_{i_M}\n * \\mathbf{r}(\\mathbf{t})\n * @f]\n *\n * @note As this class uses the internal of the spline, it must be a friend of the UniformBSpline class.\n * @tparam InputDims_ The total number of input dimensions.\n * @tparam CurDim_ The current dimension.\n */\ntemplate <typename Spline_, int InputDims_, int CurDim_>\nstruct EvaluateBSpline {\n    /**\n     * @brief Evaluates the spline at the specified position.\n     *\n     * @param[in] spline The spline.\n     * @param[in] strides The strides of the control points.\n     * @param[in] idx The current flattened index in the control points.\n     * @param[in] basisVal The current basis value.\n     * @param[in] pos The position.\n     * @param[in] basisFunc The basis function.\n     * @param[in] evalFunc The evaluation function.\n     */\n    template <typename T, typename EvalFunc>\n    static void apply(const std::array<typename Spline_::BasisType, Spline_::InputDims>& fullBasis,\n                      const std::array<int, Spline_::InputDims>& strides,\n                      int idx,\n                      T basisVal,\n                      EvalFunc evalFunc) {\n        const auto basis = fullBasis[CurDim_];\n        for (int i = 0; i < Spline_::Order; ++i, idx += strides[CurDim_]) {\n            const T newBasisVal = basisVal * basis[i];\n            EvaluateBSpline<Spline_, InputDims_, CurDim_ + 1>::apply(fullBasis, strides, idx, newBasisVal, evalFunc);\n        }\n    }\n};\n\n/**\n * @brief 'Recursion' end, if the current dimension matches the input dimensions.\n * @tparam InputDims_ The input dimensions.\n */\ntemplate <typename Spline_, int InputDims_>\nstruct EvaluateBSpline<Spline_, InputDims_, InputDims_> {\n    /**\n     * @brief Call the evaluate function.\n     */\n    template <typename T, typename EvalFunc>\n    static void apply(const std::array<typename Spline_::BasisType, Spline_::InputDims>& /*fullBasis*/,\n                      const std::array<int, Spline_::InputDims>& /*strides*/,\n                      int idx,\n                      T basisVal,\n                      EvalFunc evalFunc) {\n        evalFunc(idx, basisVal);\n    }\n};\n\n/**\n * @brief Implementation to evaluate the spline smoothness.\n * @note As this class uses the internal of the spline, it must be a friend of the UniformBSpline class.\n * @tparam TotalDerivative_ The order of the total derivative.\n * @tparam PartialDerivativeIdx_ The current partial derivative index.\n * @tparam InputDims_ The total number of input dimensions.\n * @tparam CurDim_ The current dimension.\n */\ntemplate <int TotalDerivative_, int PartialDerivativeIdx_, int InputDims_, int CurDim_>\nclass EvaluateBSplineSmoothness {\nprivate:\n    static constexpr auto FullPartialDerivatives_ =\n        TotalDerivative<InputDims_, TotalDerivative_>::getPartialDerivatives();\n\n    static constexpr int PartialDerivative_ =\n        FullPartialDerivatives_[PartialDerivativeIdx_].partialDerivatives[CurDim_];\n\npublic:\n    /**\n     * @brief Evaluates the spline smoothness.\n     * @param[in] spline The spline.\n     * @param[in] idx1 The first index.\n     * @param[in] idx2 The seconds index.\n     * @param[in] strides The strides of the control points.\n     * @param[in] factor The multiplication factor of the smoothness matrix.\n     * @param[out] res The resulting smoothness.\n     */\n    template <typename Spline>\n    static void apply(const Spline& spline,\n                      int idx1,\n                      int idx2,\n                      const std::array<int, Spline::InputDims>& strides,\n                      typename Spline::ValueType factor,\n                      typename Spline::OutputType& res) {\n\n        const auto smoothnessMatrix = UniformBSplineSmoothnessBasis<Spline::Order, PartialDerivative_>::matrix()\n                                          .template cast<typename Spline::ValueType>()\n                                          .eval();\n\n        for (int p = 0; p < spline.getNumControlPoints(CurDim_) - Spline::Degree;\n             ++p, idx1 += strides[CurDim_], idx2 += strides[CurDim_]) {\n            int newIdx1 = idx1;\n            for (int i = 0; i < Spline::Order; ++i, newIdx1 += strides[CurDim_]) {\n                int newIdx2 = idx2;\n                for (int j = 0; j < Spline::Order; ++j, newIdx2 += strides[CurDim_]) {\n                    auto newFactor = factor * smoothnessMatrix(i, j);\n                    EvaluateBSplineSmoothness<TotalDerivative_, PartialDerivativeIdx_, InputDims_, CurDim_ + 1>::apply(\n                        spline, newIdx1, newIdx2, strides, newFactor, res);\n                }\n            }\n        }\n    }\n};\n\n/**\n * @brief 'Recursion' end, if the current dimension matches the input dimensions.\n * @tparam TotalDerivative_ The order of the total derivative.\n * @tparam PartialDerivativeIdx_ The current partial derivative index.\n * @tparam InputDims_ The input dimensions.\n */\ntemplate <int TotalDerivative_, int PartialDerivativeIdx_, int InputDims_>\nclass EvaluateBSplineSmoothness<TotalDerivative_, PartialDerivativeIdx_, InputDims_, InputDims_> {\npublic:\n    template <typename Spline>\n    static void apply(const Spline& spline,\n                      int idx1,\n                      int idx2,\n                      const std::array<int, Spline::InputDims>& /*strides*/,\n                      typename Spline::ValueType factor,\n                      typename Spline::OutputType& res) {\n        assert(idx1 < int(spline.controlPoints_.getNumElements()));\n        assert(idx2 < int(spline.controlPoints_.getNumElements()));\n\n        res += FixedSizeContainerTypeTrait<typename Spline::OutputType>::evalSmoothness(\n            factor, spline.controlPoints_.at(idx1), spline.controlPoints_.at(idx2));\n    }\n};\n\n/**\n * @brief Compute the smoothness with respect to the total derivative.\n *\n * To calculate the smoothness of the total derivative, the problem can be split up by calculating the smoothness for\n * each partial derivative, multiply that value by the multiplicity of that derivative and sum them up.\n *\n * @tparam InputDims_ The number of input dimensions.\n * @tparam TotalDerivative_ The order of the total derivative.\n * @tparam NumPartialDerivatives_ The total number of distinct partial derivatives.\n * @tparam PartialDerivativeIdx_ The current number of the partial derivative to compute the smoothness.\n */\ntemplate <int InputDims_, int TotalDerivative_, int NumPartialDerivatives_, int PartialDerivativeIdx_>\nstruct ComputeSmoothness {\nprivate:\n    static constexpr auto FullPartialDerivatives_ =\n        TotalDerivative<InputDims_, TotalDerivative_>::getPartialDerivatives();\n    static constexpr Array<int, InputDims_> PartialDerivatives_ =\n        FullPartialDerivatives_[PartialDerivativeIdx_].partialDerivatives;\n    static constexpr double PartialDerivativesMultiplicity_ =\n        FullPartialDerivatives_[PartialDerivativeIdx_].multiplicity;\n\npublic:\n    /**\n     * @brief Compute the smoothness value of the partial derivatives needed to calculate the total derivative\n     *        smoothness value\n     * @param[in] spline The spline.\n     * @param[in] strides The strides of the control points.\n     * @param[out] res The smoothness value for each dimension.\n     */\n    template <typename Spline>\n    static void apply(const Spline& spline,\n                      const std::array<int, InputDims_>& strides,\n                      typename Spline::OutputType& res) {\n        static_assert(InputDims_ == Spline::InputDims, \"Input dimension missmatch.\");\n        using T = typename Spline::ValueType;\n        using OutputType = typename Spline::OutputType;\n\n        // Calculate the scaling factor. The scaling factor depends on the multiplicity of the partial derivative,\n        // the control points scale and the partial derivative.\n        T scale = T(PartialDerivativesMultiplicity_);\n\n        for (int dim = 0; dim < InputDims_; ++dim) {\n            using ValueTypeTrait = ValueTypeTrait<T>;\n            scale *= ValueTypeTrait::pow(spline.getScale(dim), 2 * PartialDerivatives_[dim] - 1);\n        }\n\n        // Calculate the smoothness value.\n        OutputType smoothness = FixedSizeContainerTypeTrait<OutputType>::zero();\n        EvaluateBSplineSmoothness<TotalDerivative_, PartialDerivativeIdx_, InputDims_, 0>::apply(\n            spline, 0, 0, strides, T(1.0), smoothness);\n        res += scale * smoothness;\n\n        // Compute smoothness value for the next partial derivative.\n        ComputeSmoothness<InputDims_, TotalDerivative_, NumPartialDerivatives_, PartialDerivativeIdx_ + 1>::apply(\n            spline, strides, res);\n    }\n};\n\n/**\n * @brief 'Loop' end, if the current dimension matches the input dimensions.\n * @tparam InputDims_ The input dimensions.\n */\ntemplate <int InputDims_, int TotalDerivative_, int NumPartialDerivatives_>\nstruct ComputeSmoothness<InputDims_, TotalDerivative_, NumPartialDerivatives_, NumPartialDerivatives_> {\n    template <typename Spline>\n    static void apply(const Spline& /*spline*/,\n                      const std::array<int, InputDims_>& /*strides*/,\n                      const typename Spline::OutputType& /*res*/) {\n        // No more partial derivatives left. Nothing more to do.\n    }\n};\n\n} // namespace internal\n} // namespace ubs\n\n#include \"uniform_bspline_eval_impl.hpp\"\n", "meta": {"hexsha": "bdb36b4b9fcb0f144c56438ea962887c3a3998ac", "size": 9814, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/uniform_bspline/internal/uniform_bspline_eval.hpp", "max_stars_repo_name": "KIT-MRT/uniform_bspline", "max_stars_repo_head_hexsha": "158f026f72849088351dc7b31f33ff5b6684965d", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-12-23T00:13:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-28T09:22:33.000Z", "max_issues_repo_path": "include/uniform_bspline/internal/uniform_bspline_eval.hpp", "max_issues_repo_name": "KIT-MRT/uniform_bspline", "max_issues_repo_head_hexsha": "158f026f72849088351dc7b31f33ff5b6684965d", "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/uniform_bspline/internal/uniform_bspline_eval.hpp", "max_forks_repo_name": "KIT-MRT/uniform_bspline", "max_forks_repo_head_hexsha": "158f026f72849088351dc7b31f33ff5b6684965d", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-16T15:17:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-28T09:22:34.000Z", "avg_line_length": 43.2334801762, "max_line_length": 119, "alphanum_fraction": 0.6661911555, "num_tokens": 2250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.4652676166063043}}
{"text": "#include \"catch.hpp\"\n\n#include <boost/graph/betweenness_centrality.hpp>\n#include <boost/graph/exterior_property.hpp>\n#include <boost/graph/graph_concepts.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/properties.hpp>\n\n#include <arlib/details/arlib_utils.hpp>\n#include <arlib/details/esx_impl.hpp>\n#include <arlib/esx.hpp>\n#include <arlib/graph_utils.hpp>\n#include <arlib/routing_kernels/types.hpp>\n#include <arlib/terminators.hpp>\n\n#include \"cittastudi_graph.hpp\"\n#include \"test_types.hpp\"\n#include \"utils.hpp\"\n\n#include <kspwlo_ref/algorithms/kspwlo.hpp>\n#include <kspwlo_ref/exploration/graph_utils.hpp>\n\n#include <chrono>\n#include <experimental/filesystem>\n#include <memory>\n#include <string>\n#include <string_view>\n\nusing namespace arlib::test;\n\ntemplate <typename ForwardIt, typename Edge>\nbool contains(ForwardIt first, ForwardIt last, Edge e) {\n  if (auto search = std::find(first, last, e); search != last) {\n    return true;\n  } else {\n    return false;\n  }\n}\n\nTEST_CASE(\"Edge priority computation\", \"[esx]\") {\n  using namespace boost;\n  using arlib::details::compute_priority;\n\n  auto G = arlib::read_graph_from_string<Graph>(std::string(graph_gr_esx));\n  Vertex s = 0, t = 6;\n\n  // Compute shortest path from s to t\n  auto weight_map = get(edge_weight, G);\n  auto sp_path = *arlib::details::compute_shortest_path(G, weight_map, s, t);\n\n  // Compute lower bounds for AStar\n  auto heuristic = arlib::details::distance_heuristic<Graph, Length>(G, t);\n\n  // We keep a set of deleted-edges\n  using Edge = typename graph_traits<Graph>::edge_descriptor;\n  auto deleted_edges = std::unordered_set<Edge, boost::hash<Edge>>{};\n\n  // Check that (0, 3) was computed in shortest path\n  REQUIRE(contains(sp_path.begin(), sp_path.end(), edge(0, 3, G).first));\n  auto s_n3 = edge(0, 3, G).first;\n\n  int prio_s_n3 = compute_priority(G, s_n3, weight_map, deleted_edges);\n  REQUIRE(prio_s_n3 == 0);\n\n  // Check that (3, 5) was computed in shortest path\n  REQUIRE(contains(sp_path.begin(), sp_path.end(), edge(3, 5, G).first));\n  auto n3_n5 = edge(3, 5, G).first;\n\n  int prio_n3_n5 = compute_priority(G, n3_n5, weight_map, deleted_edges);\n  REQUIRE(prio_n3_n5 == 3);\n\n  // Check that (5, 6) was computed in shortest path\n  REQUIRE(contains(sp_path.begin(), sp_path.end(), edge(5, 6, G).first));\n  auto n5_t = edge(5, 6, G).first;\n\n  int prio_n5_t = compute_priority(G, n5_t, weight_map, deleted_edges);\n  REQUIRE(prio_n5_t == 0);\n}\n\nTEST_CASE(\"esx kspwlo algorithm runs on Boost::Graph\", \"[esx]\") {\n  auto G = arlib::read_graph_from_string<Graph>(std::string{graph_gr_esx});\n  Vertex s = 0, t = 6;\n  auto predecessors = arlib::multi_predecessor_map<Vertex>{};\n  arlib::esx(G, predecessors, s, t, 3, 0.5);\n  auto res = arlib::to_paths(G, predecessors, s, t);\n\n  // Create a new tmp file out of graph_gr_esx\n  namespace fs = std::experimental::filesystem;\n  auto path = fs::temp_directory_path() / std::string(\"graph_gr_esx_file.gr\");\n  auto of = std::ofstream(path.string());\n  of << graph_gr_esx;\n  of.close();\n\n  auto G_regr = std::make_unique<RoadNetwork>(path.c_str());\n  auto res_regression = esx(G_regr.get(), 0, 6, 3, 0.5);\n\n  using boost::edges;\n  using boost::source;\n  using boost::target;\n  std::cout << \"Esx boost::graph result:\\n\";\n  for (auto &p : res) {\n    for (auto it = edges(p).first; it != edges(p).second; ++it) {\n      std::cout << \"(\" << source(*it, p) << \", \" << target(*it, p) << \") \";\n    }\n    std::cout << \"\\n\";\n  }\n\n  std::cout << \"Esx regression result:\\n\";\n  for (auto &regPath : res_regression) {\n    auto es = regPath.getEdges();\n    // Cleaning loops coming from dijkstra algorithm (for no reason)\n    remove_self_loops(es.begin(), es.end());\n\n    for (auto edge : es) {\n      std::cout << \"(\" << edge.first << \", \" << edge.second << \") \";\n    }\n    std::cout << \"\\n\";\n  }\n\n  // Same number of paths are computed\n  REQUIRE(res.size() == res_regression.size());\n\n  // For each k-spwlo check if its edges are in a solution of the regression\n  // test\n  for (auto &p : res) {\n    REQUIRE(one_regression_path_have_edges(res_regression, p));\n  }\n\n  using boost::edge_weight;\n  using boost::get;\n  REQUIRE(alternative_paths_are_dissimilar(res, get(edge_weight, G), 0.5));\n}\n\nTEST_CASE(\"ESX running with bidirectional dijkstra returns same result as \"\n          \"unidirectional dijkstra\",\n          \"[esx]\") {\n  using namespace boost;\n\n  auto G = arlib::read_graph_from_string<Graph>(std::string(graph_gr_esx));\n\n  Vertex s = 0, t = 6;\n  int k = 3;\n  double theta = 0.5;\n\n  auto predecessors_uni = arlib::multi_predecessor_map<Vertex>{};\n  arlib::esx(G, predecessors_uni, s, t, 3, 0.5);\n  auto res_paths_uni = arlib::to_paths(G, predecessors_uni, s, t);\n\n  auto predecessors_bi = arlib::multi_predecessor_map<Vertex>{};\n  arlib::esx(G, predecessors_bi, s, t, 3, 0.5,\n             arlib::routing_kernels::bidirectional_dijkstra);\n  auto res_paths_bi = arlib::to_paths(G, predecessors_bi, s, t);\n\n  REQUIRE(res_paths_uni.size() == res_paths_bi.size());\n\n  for (std::size_t i = 0; i < res_paths_uni.size(); ++i) {\n    REQUIRE(res_paths_uni[i].length() == res_paths_bi[i].length());\n  }\n}\n\nTEST_CASE(\"ESX running with plain dijkstra returns same result as astar\",\n          \"[esx]\") {\n  using namespace boost;\n\n  auto G = arlib::read_graph_from_string<Graph>(std::string(graph_gr_esx));\n\n  Vertex s = 0, t = 6;\n  int k = 3;\n  double theta = 0.5;\n\n  auto predecessors_uni = arlib::multi_predecessor_map<Vertex>{};\n  arlib::esx(G, predecessors_uni, s, t, 3, 0.5);\n  auto res_paths_uni = arlib::to_paths(G, predecessors_uni, s, t);\n\n  auto predecessors_bi = arlib::multi_predecessor_map<Vertex>{};\n  arlib::esx(G, predecessors_bi, s, t, 3, 0.5,\n             arlib::routing_kernels::dijkstra);\n  auto res_paths_bi = arlib::to_paths(G, predecessors_bi, s, t);\n\n  REQUIRE(res_paths_uni.size() == res_paths_bi.size());\n\n  for (std::size_t i = 0; i < res_paths_uni.size(); ++i) {\n    REQUIRE(res_paths_uni[i].length() == res_paths_bi[i].length());\n  }\n}\n\nTEST_CASE(\"ESX times-out on large graph\", \"[esx]\") {\n  using namespace boost;\n  using namespace std::chrono_literals;\n\n  auto G = arlib::read_graph_from_string<Graph>(std::string(cittastudi_gr));\n\n  Vertex s = 0, t = 20;\n  auto k = 3;\n  auto theta = 0.5;\n  auto predecessors = arlib::multi_predecessor_map<Vertex>{};\n\n  REQUIRE_THROWS_AS(arlib::esx(G, predecessors, s, t, k, theta,\n                               arlib::routing_kernels::astar,\n                               arlib::timer{1us}),\n                    arlib::terminator_stop_error);\n}\n\nTEST_CASE(\n    \"ESX with Betweeness-Centrality is functionally equivalent to original one\",\n    \"[esx]\") {\n  using namespace boost;\n\n  auto G = arlib::read_csr_graph_from_string(std::string(graph_gr_esx));\n\n  Vertex s = 0, t = 6;\n  int k = 3;\n  double theta = 0.5;\n\n  using EdgeCentralityProperty =\n      exterior_edge_property<arlib::CSRGraph, double>;\n  using EdgeCentralityContainer =\n      typename EdgeCentralityProperty::container_type;\n  using EdgeCentralityMap = typename EdgeCentralityProperty::map_type;\n\n  // Compute Edge betweeness-centrality\n  auto edge2centrality = EdgeCentralityContainer(num_edges(G));\n  auto edge_centrality_map = EdgeCentralityMap(edge2centrality, G);\n  boost::brandes_betweenness_centrality(\n      G, boost::edge_centrality_map(edge_centrality_map));\n\n  // ARP with Betweeness-Centrality\n  auto predecessors_bc = arlib::multi_predecessor_map<Vertex>{};\n  arlib::esx(G, predecessors_bc, edge_centrality_map, s, t, k, theta);\n  auto res_paths_bc = arlib::to_paths(G, predecessors_bc, s, t);\n\n  // ARP for vanilla ESX\n  auto predecessors_bi = arlib::multi_predecessor_map<Vertex>{};\n  arlib::esx(G, predecessors_bi, s, t, k, theta,\n             arlib::routing_kernels::dijkstra);\n  auto res_paths_bi = arlib::to_paths(G, predecessors_bi, s, t);\n\n  // Require solutions to match\n  REQUIRE(res_paths_bc.size() == res_paths_bi.size());\n\n  for (std::size_t i = 0; i < res_paths_bc.size(); ++i) {\n    REQUIRE(res_paths_bc[i].length() == res_paths_bi[i].length());\n  }\n}\n", "meta": {"hexsha": "8260fe5f5553f960b1a7e196c32695a0671316b6", "size": 8027, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/include/test_esx.cpp", "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": "test/include/test_esx.cpp", "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": "test/include/test_esx.cpp", "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": 32.7632653061, "max_line_length": 80, "alphanum_fraction": 0.6821975832, "num_tokens": 2341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.46524886057118725}}
{"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\" step\n * planner. The pdf can be found in https://arxiv.org/abs/1704.01271, and in the\n * `doc/` folder in this repository.\n */\n\n#pragma once\n\n#include <eigen-quadprog/QuadProg.h>\n#include <Eigen/Eigen>\n#include <cmath>\n#include <iostream>\n#include <pinocchio/spatial/se3.hpp>\n#include <sstream>\n#include <stdexcept>\n#define RESET \"\\033[0m\"\n#define RED \"\\033[31m\"  /* Red */\n#define BLUE \"\\033[34m\" /* Blue */\n\nnamespace Eigen\n{\n/** @brief Column vector of size 9 which correspond to the number of\n * optimization variables. */\ntypedef Matrix<double, 9, 1> Vector9d;\n}  // namespace Eigen\n\nnamespace reactive_planners\n{\n/**\n * @brief Implements the \"Walking Control Based on Step Timing Adaptation\" step\n * planner. The pdf can be found in https://arxiv.org/abs/1704.01271, and in the\n * `doc/` folder in this repository.\n *\n * All quantities are here expressed in the local frame. Which means for a robot\n * that the quantities are expressed in the \"base\" frame.\n *\n * @todo write here the formulation of the QP.\n */\nclass DcmVrpPlanner\n{\npublic:\n    /**\n     * @brief Construct a new DcmVrpPlanner object and initialize it.\n     *\n     * @param l_min [in] Minimum step length in the x direction (in the\n     * direction of forward motion).\n     * @param l_max [in] Maximum step length in the x direction (in the\n     * direction of forward motion).\n     * @param w_min [in] Minimum step length in the y direction (in the lateral\n     * direction).\n     * @param w_max [in] Maximum step length in the y direction (in the lateral\n     * direction).\n     * @param t_min [in] Minimum step time.\n     * @param t_max [in] Maximum step time.\n     * @param v_des [in] Desired average velocity in the x and y ([v_x, v_y]) 2d\n     * vector.\n     * @param l_p [in] Default lateral step length. Typically useful for\n     * humanoid robot where this value refer to the distance between the 2 feet\n     * while in the half-sitting/neutral position.\n     * @param ht [in] Average desired height of the com above the ground.\n     * @param cost_weights_local [in] Weights of the QP cost expressed in the\n     * local frame.\n     */\n    DcmVrpPlanner(const double& l_min,\n                  const double& l_max,\n                  const double& w_min,\n                  const double& w_max,\n                  const double& t_min,\n                  const double& t_max,\n                  const double& l_p,\n                  const double& ht,\n                  const Eigen::Ref<const Eigen::Vector9d>& cost_weights_local);\n\n    /**\n     * @brief Construct a new DcmVrpPlanner object with some default parameters.\n     */\n    DcmVrpPlanner()\n    {\n        initialize(\n            0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Eigen::Vector9d::Zero());\n    }\n\n    /**\n     * @brief Initialize The inner variable that are not time varying.\n     *\n     * @copydoc DcmVrpPlanner::DcmVrpPlanner()\n     */\n    void initialize(\n        const double& l_min,\n        const double& l_max,\n        const double& w_min,\n        const double& w_max,\n        const double& t_min,\n        const double& t_max,\n        const double& l_p,\n        const double& ht,\n        const Eigen::Ref<const Eigen::Vector9d>& cost_weights_local);\n\n    /**\n     * @brief Set the nominal steptime.\n     */\n    void set_steptime_nominal(double t_nom);\n\n    /**\n     * @brief Computes adapted step location.\n     *\n     * We use a QP formulation with the following notation:\n     * \\f{eqnarray*}{\n     *    minimize   & \\\\\n     *       x       & (1/2) x^T Q x + q^T x \\\\\n     *    subject to & \\\\\n     *               & A_{ineq} x \\leq b_{ineq} \\\\\n     *               & A_{eq} x = b_{eq} \\\\\n     *               & x_{opt_{lb}} \\leq x \\leq x_{opt_{ub}}\n     * \\f}\n     * We use the off-the-shelf QP solver eigen-quadprog in order to solve it.\n     * @see DcmVrpPlanner for the full formulation.\n     *\n     * @param current_step_location is the location of the previous foot step\n     * location (2d vector) [ux, uy].\n     * @param time_from_last_step_touchdown is the time elapsed since the last\n     * foot step landed.\n     * @param is_left_leg_in_contact is true is the current foot is on the left\n     * side, false if it is on the right side.\n     * @param v_des\n     * @param com is the CoM position.\n     * @param com_vel is the CoM velocity.\n     * @param world_M_base SE3 position of the robot base expressed in the world\n     * frame.\n     */\n    void update(const Eigen::Ref<const Eigen::Vector3d>& current_step_location,\n                const double& time_from_last_step_touchdown,\n                const bool& is_left_leg_in_contact,\n                const Eigen::Ref<const Eigen::Vector3d>& v_des,\n                const Eigen::Ref<const Eigen::Vector3d>& com,\n                const Eigen::Ref<const Eigen::Vector3d>& com_vel,\n                const pinocchio::SE3& world_M_base,\n                const double& new_t_min);\n    /**\n     * @brief Computes adapted step location for python3.\n     *\n     * We use a QP formulation with the following notation:\n     * \\f{eqnarray*}{\n     *    minimize   & \\\\\n     *       x       & (1/2) x^T Q x + q^T x \\\\\n     *    subject to & \\\\\n     *               & A_{ineq} x \\leq b_{ineq} \\\\\n     *               & A_{eq} x = b_{eq} \\\\\n     *               & x_{opt_{lb}} \\leq x \\leq x_{opt_{ub}}\n     * \\f}\n     * We use the off-the-shelf QP solver eigen-quadprog in order to solve it.\n     * @see DcmVrpPlanner for the full formulation.\n     *\n     * @param current_step_location is the location of the previous foot step\n     * location (2d vector) [ux, uy].\n     * @param time_from_last_step_touchdown is the time elapsed since the last\n     * foot step landed.\n     * @param is_left_leg_in_contact is true is the current foot is on the left\n     * side, false if it is on the right side.\n     * @param v_des\n     * @param com is the CoM position.\n     * @param com_vel is the CoM velocity.\n     * @param yaw\n     */\n    void update(const Eigen::Ref<const Eigen::Vector3d>& current_step_location,\n                const double& time_from_last_step_touchdown,\n                const bool& is_left_leg_in_contact,\n                const Eigen::Ref<const Eigen::Vector3d>& v_des,\n                const Eigen::Ref<const Eigen::Vector3d>& com,\n                const Eigen::Ref<const Eigen::Vector3d>& com_vel,\n                const double& yaw,\n                const double& new_t_min);\n\n    /**\n     * @brief Solve the Quadratic program and extract the solution. Use\n     * DcmVrpPlanner::get_next_step_location() and\n     * DcmVrpPlanner::get_duration_before_step_landing() to access the results.\n     */\n    bool solve();\n\n    /**\n     * @brief Perform an internal checks on the solver matrices. A warning\n     * message is displayed in case of problems.\n     *\n     * @return true is everything seems fine.\n     * @return false is something wrong.\n     */\n    bool internal_checks();\n\n    /**\n     * @brief Display the matrices of the Problem.\n     */\n    void print_solver() const;\n\n    /**\n     * @brief Convert the inner data to a string format.\n     */\n    std::string to_string() const;\n\n    /*\n     * Getters\n     */\n\n    /**\n     * @brief @copydoc DcmVrpPlanner::t_nom_\n     *\n     * @return const double&\n     */\n    const double& get_t_nom() const\n    {\n        return t_nom_;\n    }\n\n    /**\n     * @brief @copydoc DcmVrpPlanner::tau_nom_\n     *\n     * @return const double&\n     */\n    const double& get_tau_nom() const\n    {\n        return tau_nom_;\n    }\n\n    /**\n     * @brief @copydoc DcmVrpPlanner::l_nom_\n     *\n     * @return const double&\n     */\n    const double& get_l_nom() const\n    {\n        return l_nom_;\n    }\n\n    /**\n     * @brief @copydoc DcmVrpPlanner::w_nom_\n     *\n     * @return const double&\n     */\n    const double& get_w_nom() const\n    {\n        return w_nom_;\n    }\n\n    /**\n     * @brief @copydoc DcmVrpPlanner::bx_nom_\n     *\n     * @return const double&\n     */\n    const double& get_bx_nom() const\n    {\n        return bx_nom_;\n    }\n\n    /**\n     * @brief @copydoc DcmVrpPlanner::by_nom_\n     *\n     * @return const double&\n     */\n    const double& get_by_nom() const\n    {\n        return by_nom_;\n    }\n\n    /**\n     * @brief @copydoc DcmVrpPlanner::world_M_local_\n     *\n     * @return const pinocchio::SE3&\n     */\n    const pinocchio::SE3& get_world_M_local() const\n    {\n        return world_M_local_;\n    }\n\n    /**\n     * @brief @copydoc DcmVrpPlanner::dcm_local_\n     *\n     * @return Eigen::Ref<const Eigen::Vector3d>\n     */\n\n    Eigen::Vector3d dcm_local_REF;\n    Eigen::Ref<const Eigen::Vector3d> get_dcm_local()\n    {\n        dcm_local_REF = world_M_local_.act(dcm_local_);\n        dcm_local_REF = dcm_local_;\n        return dcm_local_REF;\n    }\n\n    /**\n     * @brief @copydoc DcmVrpPlanner::current_step_location_local_\n     *\n     * @return Eigen::Ref<const Eigen::Vector3d>\n     */\n    Eigen::Ref<const Eigen::Vector3d> get_current_step_location_local() const\n    {\n        return current_step_location_local_;\n    }\n\n    /**\n     * @brief @copydoc DcmVrpPlanner::v_des_local_\n     *\n     * @return Eigen::Ref<const Eigen::Vector3d>\n     */\n    Eigen::Ref<const Eigen::Vector3d> get_v_des_local() const\n    {\n        return v_des_local_;\n    }\n\n    /**\n     * @brief @copydoc DcmVrpPlanner::dcm_nominal_\n     *\n     * @return Eigen::Ref<const Eigen::Vector3d>\n     */\n    Eigen::Ref<const Eigen::Vector3d> get_dcm_nominal() const\n    {\n        return dcm_nominal_;\n    }\n\n    /*\n     * Output\n     */\n\n    /**\n     * @brief @copydoc DcmVrpPlanner::next_step_location_\n     *\n     * @return Eigen::Ref<const Eigen::Vector3d>\n     */\n    Eigen::Ref<const Eigen::Vector3d> get_next_step_location() const\n    {\n        return next_step_location_;\n    }\n\n    /**\n     * @brief Return the slack values from the last solution.\n     **/\n    const Eigen::Vector4d& get_slack_variables() const\n    {\n        return slack_variables_;\n    }\n\n    /**\n     * @brief @copydoc DcmVrpPlanner::duration_before_step_landing_\n     *\n     * @return const double&\n     */\n    const double& get_duration_before_step_landing() const\n    {\n        return duration_before_step_landing_;\n    }\n\n    /**\n     * @brief Get the desired com height.\n     *\n     * @return const double&\n     */\n    const double& get_com_height() const\n    {\n        return ht_;\n    }\n\n    /**\n     * @brief return cost.\n     *\n     * @return double\n     */\n    double cost()\n    {\n        return (0.5 * x_opt_.transpose() * Q_ * x_opt_ +\n                q_.transpose() * x_opt_)(0, 0);\n    }\n\n    /**\n     * @brief add time equation for fixing tau.\n     */\n    void add_t_eq(double time)\n    {\n        A_eq_(2, 2) = 1;\n        B_eq_(2) = exp(omega_ * time);\n    }\n\n    /*\n     * Private methods\n     */\nprivate:\n    /**\n     * @brief Compute the nominal step location from the user input.\n     *\n     * @param is_left_leg_in_contact [in] is used notably to define which\n     * surface to use for the next contact.\n     * - 1 if left leg is in contact\n     * - 2 if right leg is in contact\n     * @param v_des_local in the local frame.\n     */\n    void compute_nominal_step_values(\n        const bool& is_left_leg_in_contact,\n        const Eigen::Ref<const Eigen::Vector3d>& v_des_local);\n\n    /*\n     * Attributes\n     */\nprivate:\n    /** @brief Minimum step length in the x direction (in the direction of\n     * forward motion). */\n    double l_min_;\n\n    /** @brief Maximum step length in the x direction (in the direction of\n     * forward motion). */\n    double l_max_;\n\n    /** @brief Nominal step length in the x direction (in the direction of\n     * forward motion). */\n    double l_nom_;\n\n    /** @brief Minimum step length in the y direction (in the lateral\n     * direction).\n     */\n    double w_min_;\n\n    /** @brief Maximum step length in the y direction (in the lateral\n     * direction).\n     */\n    double w_max_;\n\n    /** @brief Nominal step length in the y direction (in the lateral\n     * direction).\n     */\n    double w_nom_;\n\n    /** @brief Minimum step time. */\n    double t_min_;\n\n    /** @brief Maximum step time. */\n    double t_max_;\n\n    /** @brief Nominal step time. */\n    double t_nom_ = 0.1;\n\n    /** @brief Minimum step time in logarithmic scale:\n     * \\f$ e^{\\omega t_{nom}} \\f$*/\n    double tau_min_;\n\n    /** @brief Maximum step time in logarithmic scale:\n     * \\f$ e^{\\omega t_{nom}} \\f$*/\n    double tau_max_;\n\n    /** @brief Nominal step time in logarithmic scale:\n     * \\f$ e^{\\omega t_{nom}} \\f$*/\n    double tau_nom_;\n\n    /** @brief Default step width. */\n    double l_p_;\n\n    /** @brief Average desired height of the com above the ground. */\n    double ht_;\n\n    /** @brief Natural frequency of the pendulum: \\f$ \\omega =\n     * \\sqrt{\\frac{g}{z_0}} \\f$. */\n    double omega_;\n\n    /** @brief Maximum DCM offset along the X-axis. */\n    double bx_max_;\n\n    /** @brief Minimum DCM offset along the X-axis. */\n    double bx_min_;\n\n    /** @brief Nominal DCM offset along the Y-axis. */\n    double bx_nom_;\n\n    /** @brief Maximum DCM offset along the Y-axis. */\n    double by_max_out_;\n\n    /** @brief Minimum DCM offset along the Y-axis. */\n    double by_max_in_;\n\n    /** @brief Nominal DCM offset along the Y-axis. */\n    double by_nom_;\n\n    /** @brief SE3 position of the robot base in the world frame. */\n    pinocchio::SE3 world_M_local_;\n\n    /** @brief Current DCM computed from the CoM estimation. */\n    Eigen::Vector3d dcm_local_;\n\n    /** @brief Nominal DCM computed from the CoM estimation and nominal time. */\n    Eigen::Vector3d dcm_nominal_;\n\n    /** @brief Current DCM computed from the CoM estimation. */\n    Eigen::Vector3d current_step_location_local_;\n\n    /** @brief Current DCM computed from the CoM estimation. */\n    Eigen::Vector3d v_des_local_;\n\n    /** @brief Store the time from last step touchdown in order to stop\n     * optimizing after t_min_ is passed. */\n    double time_from_last_step_touchdown_;\n\n    /*\n     * Problem results\n     */\n\n    /** @brief Next step location expressed in the world frame. */\n    Eigen::Vector3d next_step_location_;\n\n    /** @brief Slack variable values corresponding to last solution. */\n    Eigen::Vector4d slack_variables_;\n\n    /** @brief Remaining time before the step landing. */\n    double duration_before_step_landing_;\n\n    /**\n     * QP variables\n     */\n\n    /** @brief Number of variabes 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 Solution of the optimization problem.\n     * @see DcmVrpPlanner::compute_adapted_step_locations. */\n    Eigen::VectorXd x_opt_;\n\n    /** @brief Lower Bound on the solution of the optimization problem.\n     * @see DcmVrpPlanner::compute_adapted_step_locations. */\n    Eigen::VectorXd x_opt_lb_;\n\n    /** @brief Upper Bound on the solution of the optimization problem.\n     * @see DcmVrpPlanner::compute_adapted_step_locations. */\n    Eigen::VectorXd x_opt_ub_;\n\n    /** @brief Quadratic term of the quadratic cost.\n     * @see DcmVrpPlanner::compute_adapted_step_locations. */\n    Eigen::MatrixXd Q_;\n\n    /** @brief Cost weights expressed in the local frame. */\n    Eigen::Vector9d cost_weights_local_;\n\n    /** @brief Linear term of the quadratic cost.\n     * @see DcmVrpPlanner::compute_adapted_step_locations. */\n    Eigen::VectorXd q_;\n\n    /** @brief Linear equality matrix.\n     * @see DcmVrpPlanner::compute_adapted_step_locations. */\n    Eigen::MatrixXd A_eq_;\n\n    /** @brief Linear equality vector.\n     * @see DcmVrpPlanner::compute_adapted_step_locations. */\n    Eigen::VectorXd B_eq_;\n\n    /** @brief Linear inequality matrix.\n     * @see DcmVrpPlanner::compute_adapted_step_locations. */\n    Eigen::MatrixXd A_ineq_;\n\n    /** @brief Linear inequality vector.\n     * @see DcmVrpPlanner::compute_adapted_step_locations. */\n    Eigen::VectorXd B_ineq_;\n};\n\n}  // namespace reactive_planners\n", "meta": {"hexsha": "e979e9fbb3b1e02c46992c04e2d873ebb3213be3", "size": 16326, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/reactive_planners/dcm_vrp_planner.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/dcm_vrp_planner.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/dcm_vrp_planner.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.4425087108, "max_line_length": 80, "alphanum_fraction": 0.6114786231, "num_tokens": 4258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.46524886057118714}}
{"text": "#include <boost/python/def.hpp>\n#include <boost/python/args.hpp>\n\n#include <scitbx/math/interpolation.h>\n#include <scitbx/vec3.h>\n#include <scitbx/vec2.h>\n\nnamespace scitbx { namespace math {\n\nnamespace {\n\n  template <typename PointType>\n  void wrap_splines()\n  {\n    using namespace boost::python;\n    def(\"interpolate_catmull_rom_spline\",\n      (af::shared<PointType>(*)(\n        PointType const&,\n        PointType const&,\n        PointType const&,\n        PointType const&,\n        unsigned)) interpolate_catmull_rom_spline, (\n          arg(\"p0\"),\n          arg(\"p1\"),\n          arg(\"p2\"),\n          arg(\"p3\"),\n          arg(\"n_points\")));\n  }\n\n} // namespace <anonymous>\n\nnamespace boost_python {\n\n  void wrap_interpolation()\n  {\n    wrap_splines< scitbx::vec2<double> >();\n    wrap_splines< scitbx::vec3<double> >();\n  }\n\n}}} // namespace scitbx::math::boost_python\n", "meta": {"hexsha": "4561851a6e0df55188ae4655df37d0dd643566bc", "size": 872, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "scitbx/math/boost_python/interpolation.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": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-03-18T12:31:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T06:27:06.000Z", "max_issues_repo_path": "scitbx/math/boost_python/interpolation.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": "scitbx/math/boost_python/interpolation.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": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-04T15:39:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-04T15:39:06.000Z", "avg_line_length": 21.2682926829, "max_line_length": 52, "alphanum_fraction": 0.621559633, "num_tokens": 234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.465248855181175}}
{"text": "#pragma once\n\n#include <crest/geometry/indexed_mesh.hpp>\n#include <crest/geometry/mesh_algorithms.hpp>\n#include <crest/geometry/biscale_mesh.hpp>\n#include <crest/basis/quasi_interpolation.hpp>\n#include <crest/basis/lagrange_basis2d.hpp>\n#include <crest/basis/detail/homogenized_basis_detail.hpp>\n#include <crest/util/eigen_extensions.hpp>\n#include <crest/util/stat.hpp>\n#include <crest/util/timer.hpp>\n\n#include <Eigen/Sparse>\n#include <Eigen/SparseLU>\n\n#include <set>\n#include <cassert>\n#include <unordered_map>\n\n#include <iostream>\n\nnamespace crest\n{\n    template <typename Scalar>\n    class HomogenizedBasis : public Basis<Scalar, HomogenizedBasis<Scalar>>\n    {\n    public:\n        explicit HomogenizedBasis(const BiscaleMesh<Scalar, int> & mesh,\n                                  Eigen::SparseMatrix<double> weights);\n\n        virtual std::vector<int> boundary_nodes() const override { return _mesh.coarse_mesh().boundary_vertices(); }\n\n        virtual std::vector<int> interior_nodes() const override { return _mesh.coarse_mesh().compute_interior_vertices(); }\n\n        virtual Assembly<Scalar> assemble() const override;\n\n        virtual int num_dof() const override { return _mesh.coarse_mesh().num_vertices(); }\n\n        template <typename Function2d>\n        VectorX<Scalar> interpolate(const Function2d & f) const;\n\n        template <typename Function2d>\n        VectorX<Scalar> interpolate_boundary(const Function2d & f) const;\n\n        template <int QuadStrength, typename Function2d>\n        VectorX<Scalar> load(const Function2d & f) const;\n\n        template <int QuadStrength, typename Function2d>\n        Scalar error_l2(const Function2d & f, const VectorX<Scalar> & weights) const;\n\n        template <int QuadStrength, typename Function2d_x, typename Function2d_y>\n        Scalar error_h1_semi(const Function2d_x & f_x,\n                             const Function2d_y & f_y,\n                             const VectorX<Scalar> & weights) const;\n\n        const Eigen::SparseMatrix<Scalar> & basis_weights() const { return _basis_weights; }\n\n    private:\n        Eigen::SparseMatrix<Scalar> _basis_weights;\n        const BiscaleMesh<Scalar, int> & _mesh;\n    };\n\n    /**\n     * Base class for solvers that compute localized correctors for a given BiscaleMesh.\n     */\n    template <typename Scalar>\n    class CorrectorSolver\n    {\n    public:\n        typedef Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic> DenseMatrix;\n\n        virtual ~CorrectorSolver() {}\n\n        crest::HomogenizedBasis<Scalar> compute_basis(const BiscaleMesh<Scalar, int> & mesh,\n                                                      unsigned int oversampling);\n\n        Eigen::SparseMatrix<Scalar> compute_correctors(const BiscaleMesh<Scalar, int> & mesh,\n                                                       unsigned int oversampling);\n\n        virtual std::vector<Eigen::Triplet<Scalar>> resolve_element_correctors_for_patch(\n                const BiscaleMesh<Scalar, int> & mesh,\n                const std::vector<int> & coarse_patch_interior,\n                const std::vector<int> & fine_patch_interior,\n                const Eigen::SparseMatrix<Scalar> & global_coarse_stiffness,\n                const Eigen::SparseMatrix<Scalar> & global_fine_stiffness,\n                const Eigen::SparseMatrix<Scalar> & global_quasi_interpolator,\n                int coarse_element) const = 0;\n\n        const std::unordered_map<std::string, AccumulatedDensityHistogram> & stats() const;\n\n        void set_iterative_tolerance(Scalar tol) { _tol = tol; }\n        Scalar iterative_tolerance() const { return _tol; }\n\n    protected:\n        explicit CorrectorSolver<Scalar>() : _tol(Scalar(10) * std::numeric_limits<Scalar>::epsilon()) {}\n\n        VectorX<Scalar> local_rhs(const BiscaleMesh<Scalar, int> & mesh,\n                                  const std::vector<int> & fine_patch_interior,\n                                  int coarse_element,\n                                  int local_index) const;\n\n    private:\n        void set_stats(std::unordered_map<std::string, AccumulatedDensityHistogram> stats);\n        std::unordered_map<std::string, AccumulatedDensityHistogram> _stats;\n        Scalar _tol;\n    };\n\n\n    /**\n     * The default corrector solver, which uses SparseLU to compute correctors. It is slow, but very robust.\n     */\n    template <typename Scalar>\n    class SparseLuCorrectorSolver : public CorrectorSolver<Scalar>\n    {\n    public:\n        virtual std::vector<Eigen::Triplet<Scalar>> resolve_element_correctors_for_patch(\n                const BiscaleMesh<Scalar, int> & mesh,\n                const std::vector<int> & coarse_patch_interior,\n                const std::vector<int> & fine_patch_interior,\n                const Eigen::SparseMatrix<Scalar> & global_coarse_stiffness,\n                const Eigen::SparseMatrix<Scalar> & global_fine_stiffness,\n                const Eigen::SparseMatrix<Scalar> & global_quasi_interpolator,\n                int coarse_element) const override\n        {\n            (void) global_coarse_stiffness;\n\n            const auto I_H = sparse_submatrix(global_quasi_interpolator,\n                                              coarse_patch_interior,\n                                              fine_patch_interior);\n            const auto A = sparse_submatrix(global_fine_stiffness,\n                                            fine_patch_interior,\n                                            fine_patch_interior);\n\n\n            std::vector<Eigen::Triplet<Scalar>> triplets;\n            const auto C = detail::construct_saddle_point_problem(A, I_H);\n\n            Eigen::SparseLU<Eigen::SparseMatrix<Scalar>> solver;\n            solver.analyzePattern(C);\n            solver.factorize(C);\n            assert(solver.info() == Eigen::Success);\n\n            for (int i = 0; i < 3; ++i)\n            {\n                const auto b_local = this->local_rhs(mesh, fine_patch_interior, coarse_element, i);\n\n                VectorX<Scalar> c(C.rows());\n                c << b_local, VectorX<Scalar>::Zero(I_H.rows());\n\n                // Recall that the solution is of the form [x, kappa], where kappa is merely a Lagrange multiplier, so\n                // we extract x as the corrector.\n                const VectorX<Scalar> corrector = solver.solve(c).topRows(A.rows());\n\n                assert(static_cast<size_t>(corrector.rows()) == fine_patch_interior.size());\n                const auto global_index = mesh.coarse_mesh().elements()[coarse_element].vertex_indices[i];\n                for (size_t k = 0; k < fine_patch_interior.size(); ++k)\n                {\n                    const auto component = corrector(k);\n                    // Due to rounding issues, some components that should perhaps be zero in exact arithmetic\n                    // may be non-zero, and as such we might end up with a denser matrix than we should actually\n                    // have. To prevent this, we introduce a threshold which determines whether to keep the entry.\n                    // TODO: Make this threshold configurable?\n                    if (std::abs(component) > 1e-12)\n                    {\n                        triplets.emplace_back(Eigen::Triplet<Scalar>(global_index, fine_patch_interior[k], component));\n                    }\n                }\n            }\n\n            return triplets;\n        }\n    };\n\n    template <typename Scalar>\n    VectorX<Scalar> CorrectorSolver<Scalar>::local_rhs(const BiscaleMesh<Scalar, int> & mesh,\n                                                       const std::vector<int> & fine_patch_interior,\n                                                       int coarse_element,\n                                                       int local_index) const\n    {\n        assert(local_index >= 0 && local_index < 3);\n        // TODO: Simplify this function\n        assert(std::is_sorted(fine_patch_interior.cbegin(), fine_patch_interior.cend()));\n\n        const auto coarse_triangle = mesh.coarse_mesh().triangle_for(coarse_element);\n        const Eigen::Matrix<Scalar, 3, 3> coarse_coeff = detail::basis_coefficients_for_triangle(coarse_triangle);\n\n        const auto coarse_grad_x = coarse_coeff(0, local_index);\n        const auto coarse_grad_y = coarse_coeff(1, local_index);\n\n        VectorX<Scalar> rhs(fine_patch_interior.size());\n        rhs.setZero();\n        for (auto k : mesh.descendants_for(coarse_element))\n        {\n            const auto vertex_indices = mesh.fine_mesh().elements()[k].vertex_indices;\n            const auto fine_triangle = mesh.fine_mesh().triangle_for(k);\n            const Eigen::Matrix<Scalar, 3, 3> fine_coeff = detail::basis_coefficients_for_triangle(fine_triangle);\n\n            for (size_t j = 0; j < 3; ++j)\n            {\n                const auto fine_grad_x = fine_coeff(0, j);\n                const auto fine_grad_y = fine_coeff(1, j);\n\n                // TODO: Fix this\n                const auto product = [&] (auto  , auto  )\n                {\n                    return coarse_grad_x * fine_grad_x + coarse_grad_y * fine_grad_y;\n                };\n\n                // At this point, we only know the index of the vertex in the global mesh,\n                // but we need the index of the vertex with respect to the patch interior. For now,\n                // we just perform a binary search to recover it, though there may be much more efficient ways.\n                // For example, we can construct a hashmap in the beginning of this function (which may\n                // or may not be more efficient).\n                const auto vertex_index = vertex_indices[j];\n                const auto range = std::equal_range(fine_patch_interior.cbegin(),\n                                                    fine_patch_interior.cend(),\n                                                    vertex_index);\n\n                if (range.first != range.second)\n                {\n                    const auto inner_product = triquad<2>(product,\n                                                          fine_triangle.a,\n                                                          fine_triangle.b,\n                                                          fine_triangle.c);\n\n                    const auto local_index = range.first - fine_patch_interior.cbegin();\n                    rhs(local_index) += inner_product;\n                }\n\n            }\n        }\n        return rhs;\n    }\n\n    template <typename Scalar>\n    Eigen::SparseMatrix<Scalar> CorrectorSolver<Scalar>::compute_correctors(\n            const BiscaleMesh<Scalar, int> & mesh,\n            unsigned int oversampling)\n    {\n        AccumulatedDensityHistogramBuilder timing_density;\n\n        const auto I_H = quasi_interpolator(mesh);\n\n        Eigen::SparseMatrix<Scalar> A_fine(mesh.fine_mesh().num_vertices(), mesh.fine_mesh().num_vertices());\n        Eigen::SparseMatrix<Scalar> A_coarse(mesh.coarse_mesh().num_elements(), mesh.coarse_mesh().num_elements());\n        {\n            // Currently we needlessly construct the mass matrix here too. For now we put this in a block scope\n            // so that it will be deallocated shortly thereafter, but in the long-term this should\n            // be remedied so that we don't redundantly compute it. TODO\n            const auto fine_assembly = LagrangeBasis2d<Scalar>(mesh.fine_mesh()).assemble();\n            A_fine = std::move(fine_assembly.stiffness);\n\n            const auto coarse_assembly = LagrangeBasis2d<Scalar>(mesh.coarse_mesh()).assemble();\n            A_coarse = std::move(coarse_assembly.stiffness);\n        }\n\n        std::vector<Eigen::Triplet<Scalar>> basis_triplets;\n        for (int coarse_element = 0; coarse_element < mesh.coarse_mesh().num_elements(); ++coarse_element)\n        {\n            Timer element_patch_timer;\n\n            const auto coarse_patch = mesh.coarse_element_patch(coarse_element, oversampling);\n            const auto coarse_patch_interior = coarse_patch.interior();\n            const auto fine_patch = mesh.fine_patch_from_coarse(coarse_patch);\n            const auto fine_patch_interior = fine_patch.interior();\n\n            if (!fine_patch_interior.empty())\n            {\n                const auto corrector_contributions = resolve_element_correctors_for_patch(\n                        mesh,\n                        coarse_patch_interior,\n                        fine_patch_interior,\n                        A_coarse,\n                        A_fine,\n                        I_H,\n                        coarse_element);\n\n                std::copy(corrector_contributions.cbegin(),\n                          corrector_contributions.cend(),\n                          std::back_inserter(basis_triplets));\n            }\n\n            timing_density.add_sample(static_cast<double>(fine_patch_interior.size()), element_patch_timer.elapsed());\n        }\n\n        std::unordered_map<std::string, AccumulatedDensityHistogram> stats;\n        stats[\"timing_distribution\"] = timing_density.with_bin_count(100).build();\n        set_stats(stats);\n\n        Eigen::SparseMatrix<Scalar> basis(mesh.coarse_mesh().num_vertices(), mesh.fine_mesh().num_vertices());\n        basis.setFromTriplets(basis_triplets.cbegin(), basis_triplets.cend());\n        return basis;\n    }\n\n    template <typename Scalar>\n    HomogenizedBasis<Scalar> CorrectorSolver<Scalar>::compute_basis(const BiscaleMesh<Scalar, int> & mesh,\n                                                                    unsigned int oversampling)\n    {\n        const auto corrector_weights = compute_correctors(mesh, oversampling);\n        const auto lagrange_basis_weights = detail::standard_coarse_basis_in_fine_space(mesh);\n        const auto basis_weights = lagrange_basis_weights - corrector_weights;\n        return HomogenizedBasis<Scalar>(mesh, basis_weights);\n    }\n\n    template <typename Scalar>\n    const std::unordered_map<std::string, AccumulatedDensityHistogram> &\n    CorrectorSolver<Scalar>::stats() const\n    {\n        return _stats;\n    };\n\n    template <typename Scalar>\n    void CorrectorSolver<Scalar>::set_stats(std::unordered_map<std::string, AccumulatedDensityHistogram> stats)\n    {\n        _stats = stats;\n    }\n\n    template <typename Scalar>\n    HomogenizedBasis<Scalar>::HomogenizedBasis(const BiscaleMesh<Scalar, int> & mesh,\n                                               Eigen::SparseMatrix<double> weights)\n            : _mesh(mesh)\n    {\n        if (weights.rows() == mesh.coarse_mesh().num_vertices() && weights.cols() == mesh.fine_mesh().num_vertices())\n        {\n            _basis_weights = std::move(weights);\n        } else\n        {\n            throw std::invalid_argument(\"Dimensions of basis weights are not compatible with \"\n                                                \"supplied coarse and fine meshes.\");\n        }\n    }\n\n\n    template <typename Scalar>\n    Assembly<Scalar> HomogenizedBasis<Scalar>::assemble() const\n    {\n        LagrangeBasis2d<Scalar> fine_basis(_mesh.fine_mesh());\n        const auto fine_assembly = fine_basis.assemble();\n\n        const auto & M = fine_assembly.mass;\n        const auto & A = fine_assembly.stiffness;\n        const auto & W = _basis_weights;\n\n        Assembly<Scalar> assembly;\n        assembly.mass = W * M * W.transpose();\n        assembly.stiffness = W * A * W.transpose();\n        return assembly;\n    }\n\n    template <typename Scalar>\n    template <typename Function2d>\n    VectorX<Scalar> HomogenizedBasis<Scalar>::interpolate(const Function2d & f) const\n    {\n        // A slightly more accurate way of interpolating would perhaps be to interpolate the function\n        // in the fine space, and then quasi-interpolate it to weights in the coarse space.\n        // However, it seems this has some unfortunate effects on the implementation of inhomogeneous\n        // Dirichlet boundary conditions?\n        return LagrangeBasis2d<Scalar>(_mesh.coarse_mesh()).interpolate(f);\n    }\n\n    template <typename Scalar>\n    template <typename Function2d>\n    VectorX<Scalar> HomogenizedBasis<Scalar>::interpolate_boundary(const Function2d & f) const\n    {\n        return LagrangeBasis2d<Scalar>(_mesh.fine_mesh()).interpolate_boundary(f);\n    }\n\n    template <typename Scalar>\n    template <int QuadStrength, typename Function2d>\n    VectorX<Scalar> HomogenizedBasis<Scalar>::load(const Function2d & f) const\n    {\n        const LagrangeBasis2d<Scalar> fine_basis(_mesh.fine_mesh());\n        const auto fine_load = fine_basis.template load<QuadStrength>(f);\n        const auto & W = _basis_weights;\n        return W * fine_load;\n    };\n\n    template <typename Scalar>\n    template <int QuadStrength, typename Function2d>\n    Scalar HomogenizedBasis<Scalar>::error_l2(const Function2d & f, const VectorX<Scalar> & weights) const\n    {\n        const LagrangeBasis2d<Scalar> fine_basis(_mesh.fine_mesh());\n        const auto & W = _basis_weights;\n        const VectorX<Scalar> fine_weights = W.transpose() * weights;\n        return fine_basis.template error_l2<QuadStrength>(f, fine_weights);\n    };\n\n    template <typename Scalar>\n    template <int QuadStrength, typename Function2d_x, typename Function2d_y>\n    Scalar HomogenizedBasis<Scalar>::error_h1_semi(const Function2d_x & f_x,\n                                                   const Function2d_y & f_y,\n                                                   const VectorX<Scalar> & weights) const\n    {\n        const LagrangeBasis2d<Scalar> fine_basis(_mesh.fine_mesh());\n        const auto & W = _basis_weights;\n        const VectorX<Scalar> fine_weights = W.transpose() * weights;\n        return fine_basis.template error_h1_semi<QuadStrength>(f_x, f_y, fine_weights);\n    };\n}\n", "meta": {"hexsha": "24726ca3cece3b1576eb77a7c4ad4f46edf45844", "size": 17634, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/crest/basis/homogenized_basis.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/basis/homogenized_basis.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/basis/homogenized_basis.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": 44.085, "max_line_length": 124, "alphanum_fraction": 0.6073494386, "num_tokens": 3593, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.465248855181175}}
{"text": "#include <iostream>\n#include <iomanip>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <bench/BenchTimer.h>\n\nusing namespace Eigen;\nusing namespace std;\n\n#ifndef REPEAT\n#define REPEAT 1000000\n#endif\n\nenum func_opt\n{\n    TV,\n    TMATV,\n    TMATVMAT,\n};\n\n\ntemplate <class res, class arg1, class arg2, int opt>\nstruct func;\n\ntemplate <class res, class arg1, class arg2>\nstruct func<res, arg1, arg2, TV>\n{\n    static EIGEN_DONT_INLINE res run( arg1& a1, arg2& a2 )\n    {\n\tasm (\"\");\n\treturn a1 * a2;\n    }\n};\n\ntemplate <class res, class arg1, class arg2>\nstruct func<res, arg1, arg2, TMATV>\n{\n    static EIGEN_DONT_INLINE res run( arg1& a1, arg2& a2 )\n    {\n\tasm (\"\");\n\treturn a1.matrix() * a2;\n    }\n};\n\ntemplate <class res, class arg1, class arg2>\nstruct func<res, arg1, arg2, TMATVMAT>\n{\n    static EIGEN_DONT_INLINE res run( arg1& a1, arg2& a2 )\n    {\n\tasm (\"\");\n\treturn res(a1.matrix() * a2.matrix());\n    }\n};\n\ntemplate <class func, class arg1, class arg2>\nstruct test_transform\n{\n    static void run()\n    {\n\targ1 a1;\n\ta1.setIdentity();\n\targ2 a2;\n\ta2.setIdentity();\n\n\tBenchTimer timer;\n\ttimer.reset();\n\tfor (int k=0; k<10; ++k)\n\t{\n\t    timer.start();\n\t    for (int k=0; k<REPEAT; ++k)\n\t\ta2 = func::run( a1, a2 );\n\t    timer.stop();\n\t}\n\tcout << setprecision(4) << fixed << timer.value() << \"s  \" << endl;;\n    }\n};\n\n\n#define run_vec( op, scalar, mode, option, vsize ) \\\n    std::cout << #scalar << \"\\t \" << #mode << \"\\t \" << #option << \" \" << #vsize \" \"; \\\n    {\\\n\ttypedef Transform<scalar, 3, mode, option> Trans;\\\n\ttypedef Matrix<scalar, vsize, 1, option> Vec;\\\n\ttypedef func<Vec,Trans,Vec,op> Func;\\\n\ttest_transform< Func, Trans, Vec >::run();\\\n    }\n\n#define run_trans( op, scalar, mode, option ) \\\n    std::cout << #scalar << \"\\t \" << #mode << \"\\t \" << #option << \"   \"; \\\n    {\\\n\ttypedef Transform<scalar, 3, mode, option> Trans;\\\n\ttypedef func<Trans,Trans,Trans,op> Func;\\\n\ttest_transform< Func, Trans, Trans >::run();\\\n    }\n\nint main(int argc, char* argv[])\n{\n    cout << \"vec = trans * vec\" << endl;\n    run_vec(TV, float,  Isometry, AutoAlign, 3);\n    run_vec(TV, float,  Isometry, DontAlign, 3);\n    run_vec(TV, float,  Isometry, AutoAlign, 4);\n    run_vec(TV, float,  Isometry, DontAlign, 4);\n    run_vec(TV, float,  Projective, AutoAlign, 4);\n    run_vec(TV, float,  Projective, DontAlign, 4);\n    run_vec(TV, double, Isometry, AutoAlign, 3);\n    run_vec(TV, double, Isometry, DontAlign, 3);\n    run_vec(TV, double, Isometry, AutoAlign, 4);\n    run_vec(TV, double, Isometry, DontAlign, 4);\n    run_vec(TV, double, Projective, AutoAlign, 4);\n    run_vec(TV, double, Projective, DontAlign, 4);\n\n    cout << \"vec = trans.matrix() * vec\" << endl;\n    run_vec(TMATV, float,  Isometry, AutoAlign, 4);\n    run_vec(TMATV, float,  Isometry, DontAlign, 4);\n    run_vec(TMATV, double, Isometry, AutoAlign, 4);\n    run_vec(TMATV, double, Isometry, DontAlign, 4);\n\n    cout << \"trans = trans1 * trans\" << endl;\n    run_trans(TV, float,  Isometry, AutoAlign);\n    run_trans(TV, float,  Isometry, DontAlign);\n    run_trans(TV, double, Isometry, AutoAlign);\n    run_trans(TV, double, Isometry, DontAlign);\n    run_trans(TV, float,  Projective, AutoAlign);\n    run_trans(TV, float,  Projective, DontAlign);\n    run_trans(TV, double, Projective, AutoAlign);\n    run_trans(TV, double, Projective, DontAlign);\n\n    cout << \"trans = trans1.matrix() * trans.matrix()\" << endl;\n    run_trans(TMATVMAT, float,  Isometry, AutoAlign);\n    run_trans(TMATVMAT, float,  Isometry, DontAlign);\n    run_trans(TMATVMAT, double, Isometry, AutoAlign);\n    run_trans(TMATVMAT, double, Isometry, DontAlign);\n}\n", "meta": {"hexsha": "51214d69f16718f10b2efdaa2b6b008d39adc6ab", "size": 3597, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "simulator/external/habitat-sim-geodesic/habitat_sim_geodesic/csrc/eigen/bench/benchGeometry.cpp", "max_stars_repo_name": "eundersander/bps-nav", "max_stars_repo_head_hexsha": "a33bac7d10dc077baa596a76790b4fc829d332f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2021-03-15T01:49:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-11T23:17:14.000Z", "max_issues_repo_path": "simulator/external/habitat-sim-geodesic/habitat_sim_geodesic/csrc/eigen/bench/benchGeometry.cpp", "max_issues_repo_name": "eundersander/bps-nav", "max_issues_repo_head_hexsha": "a33bac7d10dc077baa596a76790b4fc829d332f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-06-27T21:41:25.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-18T21:46:40.000Z", "max_forks_repo_path": "simulator/external/habitat-sim-geodesic/habitat_sim_geodesic/csrc/eigen/bench/benchGeometry.cpp", "max_forks_repo_name": "eundersander/bps-nav", "max_forks_repo_head_hexsha": "a33bac7d10dc077baa596a76790b4fc829d332f7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2021-03-27T17:17:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-19T12:00:06.000Z", "avg_line_length": 26.8432835821, "max_line_length": 86, "alphanum_fraction": 0.6344175702, "num_tokens": 1152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812552, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4652488551811749}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2011-2012 Barend Gehrels, Amsterdam, the Netherlands.\n\n// This file was modified by Oracle on 2014.\n// Modifications copyright (c) 2014 Oracle and/or its affiliates.\n\n// Contributed and/or modified by 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_MAPPING_SSF_HPP\n#define BOOST_GEOMETRY_STRATEGIES_GEOGRAPHIC_MAPPING_SSF_HPP\n\n\n#include <boost/core/ignore_unused.hpp>\n\n#include <boost/geometry/core/radius.hpp>\n\n#include <boost/geometry/util/math.hpp>\n#include <boost/geometry/util/promote_floating_point.hpp>\n#include <boost/geometry/util/select_calculation_type.hpp>\n\n#include <boost/geometry/strategies/side.hpp>\n#include <boost/geometry/strategies/spherical/ssf.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\nnamespace strategy { namespace side\n{\n\n\n// An enumeration type defining types of mapping of geographical\n// latitude to spherical latitude.\n// See: http://en.wikipedia.org/wiki/Great_ellipse\n//      http://en.wikipedia.org/wiki/Latitude#Auxiliary_latitudes\nenum mapping_type { mapping_geodetic, mapping_reduced, mapping_geocentric };\n\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail\n{\n\ntemplate <typename Spheroid, mapping_type Mapping>\nstruct mapper\n{\n    explicit inline mapper(Spheroid const& /*spheroid*/) {}\n\n    template <typename CalculationType>\n    static inline CalculationType const& apply(CalculationType const& lat)\n    {\n        return lat;\n    }\n};\n\ntemplate <typename Spheroid>\nstruct mapper<Spheroid, mapping_reduced>\n{\n    typedef typename promote_floating_point\n        <\n            typename radius_type<Spheroid>::type\n        >::type fraction_type;\n\n    explicit inline mapper(Spheroid const& spheroid)\n    {\n        fraction_type const a = geometry::get_radius<0>(spheroid);\n        fraction_type const b = geometry::get_radius<2>(spheroid);\n        b_div_a = b / a;\n    }\n\n    template <typename CalculationType>\n    inline CalculationType apply(CalculationType const& lat) const\n    {\n        return atan(static_cast<CalculationType>(b_div_a) * tan(lat));\n    }\n\n    fraction_type b_div_a;\n};\n\ntemplate <typename Spheroid>\nstruct mapper<Spheroid, mapping_geocentric>\n{\n    typedef typename promote_floating_point\n        <\n            typename radius_type<Spheroid>::type\n        >::type fraction_type;\n\n    explicit inline mapper(Spheroid const& spheroid)\n    {\n        fraction_type const a = geometry::get_radius<0>(spheroid);\n        fraction_type const b = geometry::get_radius<2>(spheroid);\n        sqr_b_div_a = b / a;\n        sqr_b_div_a *= sqr_b_div_a;\n    }\n\n    template <typename CalculationType>\n    inline CalculationType apply(CalculationType const& lat) const\n    {\n        return atan(static_cast<CalculationType>(sqr_b_div_a) * tan(lat));\n    }\n\n    fraction_type sqr_b_div_a;\n};\n\n}\n#endif // DOXYGEN_NO_DETAIL\n\n\n/*!\n\\brief Check at which side of a geographical segment a point lies\n         left of segment (> 0), right of segment (< 0), on segment (0).\n         The check is performed by mapping the geographical coordinates\n         to spherical coordinates and using spherical_side_formula.\n\\ingroup strategies\n\\tparam Spheroid The reference spheroid model\n\\tparam Mapping The type of mapping of geographical to spherical latitude\n\\tparam CalculationType \\tparam_calculation\n */\ntemplate <typename Spheroid,\n          mapping_type Mapping = mapping_geodetic,\n          typename CalculationType = void>\nclass mapping_spherical_side_formula\n{\n\npublic :\n    inline mapping_spherical_side_formula()\n        : m_mapper(Spheroid())\n    {}\n\n    explicit inline mapping_spherical_side_formula(Spheroid const& spheroid)\n        : m_mapper(spheroid)\n    {}\n\n    template <typename P1, typename P2, typename P>\n    inline int apply(P1 const& p1, P2 const& p2, P const& p)\n    {\n        typedef typename promote_floating_point\n            <\n                typename select_calculation_type_alt\n                    <\n                        CalculationType,\n                        P1, P2, P\n                    >::type\n            >::type calculation_type;\n\n        calculation_type lon1 = get_as_radian<0>(p1);\n        calculation_type lat1 = m_mapper.template apply<calculation_type>(get_as_radian<1>(p1));\n        calculation_type lon2 = get_as_radian<0>(p2);\n        calculation_type lat2 = m_mapper.template apply<calculation_type>(get_as_radian<1>(p2));\n        calculation_type lon = get_as_radian<0>(p);\n        calculation_type lat = m_mapper.template apply<calculation_type>(get_as_radian<1>(p));\n\n        return detail::spherical_side_formula(lon1, lat1, lon2, lat2, lon, lat);\n    }\n\nprivate:\n    side::detail::mapper<Spheroid, Mapping> const m_mapper;\n};\n\n// The specialization for geodetic latitude which can be used directly\ntemplate <typename Spheroid,\n          typename CalculationType>\nclass mapping_spherical_side_formula<Spheroid, mapping_geodetic, CalculationType>\n{\n\npublic :\n    inline mapping_spherical_side_formula() {}\n    explicit inline mapping_spherical_side_formula(Spheroid const& /*spheroid*/) {}\n\n    template <typename P1, typename P2, typename P>\n    static inline int apply(P1 const& p1, P2 const& p2, P const& p)\n    {\n        return spherical_side_formula<CalculationType>::apply(p1, p2, p);\n    }\n};\n\n}} // namespace strategy::side\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_STRATEGIES_GEOGRAPHIC_MAPPING_SSF_HPP\n", "meta": {"hexsha": "3beedc7809a0d4b6e60ea37178fc5eddbb470400", "size": 5608, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/cinder/include/boost/geometry/strategies/geographic/mapping_ssf.hpp", "max_stars_repo_name": "multi-os-engine/cinder-natj-binding", "max_stars_repo_head_hexsha": "969b66fdd49e4ca63442baf61ce90ae385ab8178", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1210.0, "max_stars_repo_stars_event_min_datetime": "2020-08-18T07:57:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:06:05.000Z", "max_issues_repo_path": "ios/Pods/boost-for-react-native/boost/geometry/strategies/geographic/mapping_ssf.hpp", "max_issues_repo_name": "c7yrus/alyson-v3", "max_issues_repo_head_hexsha": "5ad95a8f782f5f5d2fd543d44ca6a8b093395965", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 369.0, "max_issues_repo_issues_event_min_datetime": "2016-10-21T07:42:54.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-19T10:49:29.000Z", "max_forks_repo_path": "ios/Pods/boost-for-react-native/boost/geometry/strategies/geographic/mapping_ssf.hpp", "max_forks_repo_name": "c7yrus/alyson-v3", "max_forks_repo_head_hexsha": "5ad95a8f782f5f5d2fd543d44ca6a8b093395965", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 534.0, "max_forks_repo_forks_event_min_datetime": "2016-10-20T21:00:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T10:02:27.000Z", "avg_line_length": 30.1505376344, "max_line_length": 96, "alphanum_fraction": 0.7123751783, "num_tokens": 1313, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478255, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.46524884979116254}}
{"text": "/* Copyright (C) 2010-2019, The Regents of The University of Michigan.\n All rights reserved.\n\n This software was developed as part of the The Vulcan project in the Intelligent Robotics Lab\n under the direction of Benjamin Kuipers, kuipers@umich.edu. Use of this code is governed by an\n MIT-style License that can be found at \"https://github.com/h2ssh/Vulcan\".\n*/\n\n\n/**\n* \\file     visibility_graph.cpp\n* \\author   Collin Johnson\n* \n* Definition of VisibilityGraph.\n*/\n\n#include <utils/visibility_graph.h>\n#include <utils/algorithm_ext.h>\n#include <boost/graph/betweenness_centrality.hpp>\n#include <boost/graph/closeness_centrality.hpp>\n#include <boost/graph/clustering_coefficient.hpp>\n#include <boost/graph/degree_centrality.hpp>\n#include <boost/graph/johnson_all_pairs_shortest.hpp>\n#include <boost/graph/page_rank.hpp>\n#include <boost/graph/copy.hpp>\n#include <boost/graph/exterior_property.hpp>\n#include <boost/graph/filtered_graph.hpp>\n#include <boost/property_map/property_map.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 <algorithm>\n#include <iostream>\n#include <unordered_set>\n\nnamespace vulcan\n{\nnamespace utils\n{\n\nusing namespace boost;\n\n// Define property map for storing the distances between nodes\nusing DistProperty = exterior_vertex_property<VisGraphType, int>;\nusing DistVec = DistProperty::container_type;\nusing DistMatrix = DistProperty::matrix_type;\nusing DistMap = DistProperty::matrix_map_type;\n\n// Define a property map for storing the calculated feature values\nusing FeatureProperty = exterior_vertex_property<VisGraphType, float>;\nusing FeatureContainer = FeatureProperty::container_type;\nusing FeatureMap = FeatureProperty::map_type;\n\n\n// Types for creating subgraphs easily\nusing VertexSet = PointSet<int>;\n\nstruct VertexSetVertex\n{\n    const VertexSet* idSet;\n    const VisGraphType* graph;\n    \n    bool operator()(VisGraphType::vertex_descriptor vertex) const\n    {\n        return idSet->find((*graph)[vertex].position) != idSet->end();\n    }\n    \n    explicit VertexSetVertex(const VertexSet* idSet= nullptr,\n                             const VisGraphType* graph = nullptr)\n    : idSet(idSet)\n    , graph(graph)\n    {\n    }\n};\n\nstruct VertexSetEdge\n{\n    const VertexSet* idSet;\n    const VisGraphType* graph;\n    \n    bool operator()(VisGraphType::edge_descriptor edge) const\n    {\n        return (idSet->find((*graph)[source(edge, *graph)].position) != idSet->end())\n            && (idSet->find((*graph)[target(edge, *graph)].position) != idSet->end());\n    }\n    \n    explicit VertexSetEdge(const VertexSet* idSet= nullptr,\n                           const VisGraphType* graph = nullptr)\n    : idSet(idSet)\n    , graph(graph)\n    {\n    }\n};\n\n\nvoid all_pairs_paths(const VisGraphType& graph, DistMap& distanceMap);\nVisibilityGraphFeature feature_map_to_graph_feature(const FeatureMap& featMap,\n                                                    const VisGraphType& graph,\n                                                    VisibilityGraphFeatureType type);\n\nstd::tuple<double, double> edge_count_stats(const DistMatrix& distMap, int numVertices);\n\n\n/////////////////// VisibilityGraph implementation //////////////////////////\n\nVisibilityGraph::VisibilityGraph(const std::vector<VisGraphVertex>& points, const std::vector<std::pair<int, int>>& edges)\n: graph_(points.size())\n, vertices_(points)\n{\n    for(std::size_t n = 0; n < points.size(); ++n)\n    {\n        graph_[n].position = points[n];\n    }\n\n    for(auto& edge : edges)\n    {\n        auto desc = add_edge(edge.first, edge.second, graph_);\n        if(desc.second)\n        {\n            graph_[desc.first].distance = distance_between_points(vertices_[edge.first], vertices_[edge.second]);\n            edges_.push_back(std::make_pair(vertices_[edge.first], vertices_[edge.second]));\n        }\n    }\n}\n\n\nVisibilityGraphFeature VisibilityGraph::calculateFeature(VisibilityGraphFeatureType type) const\n{\n    int cachedFeatureIndex = findCachedFeatureIndex(type);\n    if(cachedFeatureIndex != -1)\n    {\n        return features_[cachedFeatureIndex];\n    }\n\n    VisibilityGraphFeature feature;\n\n    switch(type)\n    {\n    case VisibilityGraphFeatureType::mean_edge_count:\n        feature = meanPathCount();\n        break;\n\n    case VisibilityGraphFeatureType::clustering_coeff:\n        feature = clusteringCoeff();\n        break;\n\n    case VisibilityGraphFeatureType::degree_centrality:\n        feature = degreeCentrality();\n        break;\n\n    case VisibilityGraphFeatureType::closeness_centrality:\n        feature = closenessCentrality();\n        break;\n\n    case VisibilityGraphFeatureType::betweenness_centrality:\n        feature = betweennessCentrality();\n        break;\n        \n    case VisibilityGraphFeatureType::pagerank:\n        feature = pagerank();\n        break;\n\n    case VisibilityGraphFeatureType::none:\n    case VisibilityGraphFeatureType::num_features:\n    default:\n        break;\n    }\n\n    if(feature.type() != VisibilityGraphFeatureType::none)\n    {\n        features_.emplace_back(feature);\n    }\n\n    return feature;\n}\n\n\nbool VisibilityGraph::isVertex(VisGraphVertex vertex) const\n{\n    return contains(vertices_, vertex);\n}\n\n\nVisibilityGraph VisibilityGraph::createSubgraph(VisVertexIter begin, VisVertexIter end) const\n{\n    VertexSet subVerts(begin, end);\n    \n    for(auto v : make_iterator_range(begin, end))\n    {\n        for(auto adj : make_iterator_range(adjacent_vertices(descriptors_.at(v), graph_)))\n        {\n            subVerts.insert(graph_[adj].position);\n        }\n    }\n    \n    VertexSetVertex vertexFilter(&subVerts, &graph_);\n    VertexSetEdge edgeFilter(&subVerts, &graph_);\n    auto filtered = make_filtered_graph(graph_, edgeFilter, vertexFilter);\n    \n    std::unordered_map<VisGraphType::vertex_descriptor, std::size_t> oldToNew;\n    \n    // Copy the filtered graph into a new graph\n    VisibilityGraph subgraph;\n    \n    // Copy over the vertices that exist in the new subgraph\n    for(auto v : make_iterator_range(boost::vertices(filtered)))\n    {\n        oldToNew[v] = add_vertex(graph_[v], subgraph.graph_);\n        subgraph.vertices_.push_back(graph_[v].position);\n    }\n    \n    // Copy over the edges that exist in the new subgraph\n    for(auto e : make_iterator_range(boost::edges(filtered)))\n    {\n        add_edge(oldToNew[source(e, graph_)], oldToNew[target(e, graph_)], subgraph.graph_);\n        subgraph.edges_.push_back(std::make_pair(graph_[source(e, graph_)].position,\n                                                 graph_[target(e, graph_)].position));\n    }\n    \n    return subgraph;\n}\n\n\nint VisibilityGraph::findCachedFeatureIndex(VisibilityGraphFeatureType type) const\n{\n    for(std::size_t n = 0; n < features_.size(); ++n)\n    {\n        if(features_[n].type() == type)\n        {\n            return n;\n        }\n    }\n\n    return -1;\n}\n\n\nVisibilityGraphFeature VisibilityGraph::meanPathCount(void) const\n{\n    int numVertices = num_vertices(graph_);\n\n    // Compute the distances between all pairs of vertices\n    DistMatrix distances(numVertices);\n    DistMap distMap(distances, graph_);\n    all_pairs_paths(graph_, distMap);\n\n    FeatureContainer pathDists(numVertices);\n    FeatureMap pathDistMap(pathDists, graph_);\n\n    for(int n = 0; n < numVertices; ++n)\n    {\n        double sum = 0.0;\n\n        for(auto& pathLength : distances[n])\n        {\n            // Only care about paths leading to other areas\n            if((pathLength < numVertices) && (pathLength > 0))\n            {\n                sum += pathLength;\n            }\n        }\n\n        pathDistMap[n] = (numVertices > 1) ? sum / (numVertices - 1) : 0.0f;\n    }\n\n    double maxMean = *std::max_element(pathDists.begin(), pathDists.end());\n    if(maxMean > 0.0)\n    {\n        for(auto& dist : pathDists)\n        {\n            dist /= maxMean;\n        }\n    }\n\n    return feature_map_to_graph_feature(pathDistMap, graph_, VisibilityGraphFeatureType::mean_edge_count);\n}\n\n\nVisibilityGraphFeature VisibilityGraph::clusteringCoeff(void) const\n{\n    // Compute the degree centrality for graph.\n    FeatureContainer coeffs(num_vertices(graph_));\n    FeatureMap coeffMap(coeffs, graph_);\n    all_clustering_coefficients(graph_, coeffMap);\n\n    return feature_map_to_graph_feature(coeffMap, graph_, VisibilityGraphFeatureType::clustering_coeff);\n}\n\n\nVisibilityGraphFeature VisibilityGraph::degreeCentrality(void) const\n{\n    // Compute the degree centrality for graph.\n    FeatureContainer centralities(num_vertices(graph_));\n    FeatureMap centMap(centralities, graph_);\n    all_degree_centralities(graph_, centMap);\n\n    double maxDegree = *std::max_element(centralities.begin(), centralities.end());\n    // Normalize the degree centrality by the maximum possible value (num verts - 1)\n    if(maxDegree > 0.0)\n    {\n        for(auto& c : centralities)\n        {\n            c /= maxDegree;\n        }\n    }\n\n    return feature_map_to_graph_feature(centMap, graph_, VisibilityGraphFeatureType::degree_centrality);\n}\n\n\nVisibilityGraphFeature VisibilityGraph::closenessCentrality(void) const\n{\n    // Compute the distances between all pairs of vertices\n    DistMatrix distances(num_vertices(graph_));\n    DistMap distMap(distances, graph_);\n    all_pairs_paths(graph_, distMap);\n\n    // Compute the closeness centrality for graph.\n    FeatureContainer centralities(num_vertices(graph_));\n    FeatureMap centMap(centralities, graph_);\n    all_closeness_centralities(graph_, distMap, centMap);\n\n    // Normalize the closeness to have a value of 1 if a node is connected to every other node and decrease\n    // from there. The value returned here is 1 / sum(path dists). If fully connected, this sum is (num verts - 1),\n    // so just multiply by that to get the normalized value here\n    if(num_vertices(graph_) > 1)\n    {\n        double normalizer = num_vertices(graph_) - 1.0;\n\n        for(auto& c : centralities)\n        {\n            c *= normalizer;\n        }\n    }\n\n    return feature_map_to_graph_feature(centMap, graph_, VisibilityGraphFeatureType::closeness_centrality);\n}\n\n\nVisibilityGraphFeature VisibilityGraph::betweennessCentrality(void) const\n{\n    // Compute the betweenness centrality for graph.\n    FeatureContainer centralities(num_vertices(graph_));\n    FeatureMap centMap(centralities, graph_);\n    brandes_betweenness_centrality(graph_, centMap);\n\n    // Normalize the betweenness values\n    if(num_vertices(graph_) > 1)\n    {\n        double min = *std::min_element(centralities.begin(), centralities.end());\n        double max = *std::max_element(centralities.begin(), centralities.end());\n\n        // Scale the betweenness relative to the min and max to make it a relative measure.\n        double normalizer = (max > min) ? max - min : 1.0;\n\n        for(auto& c : centralities)\n        {\n            c = (c - min) / normalizer;\n        }\n    }\n\n    return feature_map_to_graph_feature(centMap, graph_, VisibilityGraphFeatureType::betweenness_centrality);\n}\n\n\nVisibilityGraphFeature VisibilityGraph::pagerank(void) const\n{\n    // Compute the betweenness centrality for graph.\n    FeatureContainer ranks(num_vertices(graph_));\n    FeatureMap rankMap(ranks, graph_);\n    page_rank(graph_, rankMap);\n\n    return feature_map_to_graph_feature(rankMap, graph_, VisibilityGraphFeatureType::pagerank);\n}\n\n\nvoid all_pairs_paths(const VisGraphType& graph, DistMap& distanceMap)\n{\n    auto uniformCostMap = static_property_map<int>(1);\n    johnson_all_pairs_shortest_paths(graph, distanceMap, weight_map(uniformCostMap));\n}\n\n\nVisibilityGraphFeature feature_map_to_graph_feature(const FeatureMap& featMap,\n                                                    const VisGraphType& graph,\n                                                    VisibilityGraphFeatureType type)\n{\n    std::vector<VisibilityGraphFeature::value_type> values(num_vertices(graph));\n    for(int n = 0, end = num_vertices(graph); n < end; ++n)\n    {\n        values[n] = std::make_pair(graph[n].position, featMap[n]);\n    }\n\n    return VisibilityGraphFeature(type, values);\n}\n\n\nstd::tuple<double, double> edge_count_stats(const DistMatrix& distMap, int numVertices)\n{\n    using namespace accumulators;\n    accumulator_set<double, stats<tag::mean, tag::variance>> statsAcc;\n    \n    for(int n = 0; n < numVertices; ++n)\n    {\n        for(auto& pathLength : distMap[n])\n        {\n            // Only care about paths leading to other areas\n            if((pathLength < numVertices) && (pathLength > 0))\n            {\n                statsAcc(pathLength);\n            }\n        }\n    }\n    \n    return std::make_pair(mean(statsAcc), std::sqrt(variance(statsAcc)));\n}\n\n} // namespace utils\n} // namespace vulcan\n", "meta": {"hexsha": "e126938a12b8f9f1669be5b8ac2d0bdaec9f02ec", "size": 12819, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/utils/visibility_graph.cpp", "max_stars_repo_name": "h2ssh/Vulcan", "max_stars_repo_head_hexsha": "cc46ec79fea43227d578bee39cb4129ad9bb1603", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2020-03-29T09:37:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T08:56:31.000Z", "max_issues_repo_path": "src/utils/visibility_graph.cpp", "max_issues_repo_name": "h2ssh/Vulcan", "max_issues_repo_head_hexsha": "cc46ec79fea43227d578bee39cb4129ad9bb1603", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-03-05T08:00:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-05T08:00:50.000Z", "max_forks_repo_path": "src/utils/visibility_graph.cpp", "max_forks_repo_name": "h2ssh/Vulcan", "max_forks_repo_head_hexsha": "cc46ec79fea43227d578bee39cb4129ad9bb1603", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2019-05-13T00:04:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-20T08:56:38.000Z", "avg_line_length": 30.3767772512, "max_line_length": 122, "alphanum_fraction": 0.6767298541, "num_tokens": 2883, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478255, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.46524884979116243}}
{"text": "\n//  Copyright 2015 Stephan Menzel. 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#include \"Random.hpp\"\n#include \"ThreadId.hpp\"\n#include \"Assert.hpp\"\n\n#include <boost/thread/tss.hpp>\n#include <boost/chrono/chrono.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_int_distribution.hpp>\n#include <boost/uuid/uuid_generators.hpp>\n\nnamespace moose {\nnamespace tools {\n\nnamespace {\n\t\n\tusing prng_type = boost::random::mt19937;\n\tboost::thread_specific_ptr<prng_type>                      local_gen;\n\tusing uuid_generator_type = boost::uuids::basic_random_generator<prng_type>;\n\tboost::thread_specific_ptr<uuid_generator_type>            random_uid_generator;\n\t\n\t/// get access to a thread local instance of the PRNG\n\tinline prng_type* gen() {\n\t\t\n\t\tif (!local_gen.get()) {\n\t\t\t\n\t\t\t// I try to get a high resolution nanosecond clock and taint \n\t\t\t// it somehow with some burned time\n\t\t\tboost::chrono::high_resolution_clock::time_point start = boost::chrono::high_resolution_clock::now();\n\t\t\tunsigned int tid = faked_thread_id(); // this should take long enough...\n\t\t\tboost::chrono::nanoseconds ns = boost::chrono::high_resolution_clock::now() - start;\n\t\t\tlocal_gen.reset(new prng_type(ns.count() % tid));\n\t\t}\n\t\t\n\t\treturn local_gen.get();\n\t}\n\t\n\t// get access to a thread local instance of a uuid generator\n\tinline uuid_generator_type *get_uuid_generator() {\n\t\t\n\t\tif (!random_uid_generator.get()) {\n\t\t\tprng_type *prng = gen();\n\t\t\trandom_uid_generator.reset(new uuid_generator_type(*prng));\n\t\t}\n\t\t\n\t\treturn random_uid_generator.get();\n\t}\n\t\n}\n\nboost::uint64_t urand(const boost::uint64_t n_max) {\n\n\t// get the thread local PRNG\n\tboost::random::mt19937 *prng = gen();\n\tMOOSE_ASSERT(prng);\n\tboost::random::uniform_int_distribution<boost::uint64_t> dist(0, n_max);\n\treturn dist(*prng);\n}\n\nboost::uint64_t urand(const boost::uint64_t n_min, const boost::uint64_t n_max) {\n\t\n\tMOOSE_ASSERT_MSG((n_min < n_max), \"minimum value must be lower than maximum value when calling moose::tools::urand()\");\n\n\t// get the thread local PRNG\n\tboost::random::mt19937 *prng = gen();\n\tMOOSE_ASSERT(prng);\n\tboost::random::uniform_int_distribution<boost::uint64_t> dist(n_min, n_max);\n\treturn dist(*prng);\n}\n\nboost::uint64_t urand() {\n\n\treturn moose::tools::urand(std::numeric_limits<boost::uint64_t>::max());\n}\n\nboost::uuids::uuid ruuid() {\n\n\tuuid_generator_type *gen = get_uuid_generator();\n\treturn (*gen)();\n};\n\n\nstatic unsigned long x = 123456789;\nstatic unsigned long y = 362436069;\nstatic unsigned long z = 521288629;\n\nunsigned long xorshf96() {          // period 2^96-1\n\n\tunsigned long t;\n\tx ^= x << 16;\n\tx ^= x >> 5;\n\tx ^= x << 1;\n\n\tt = x;\n\tx = y;\n\ty = z;\n\tz = t ^ x ^ y;\n\n\treturn z;\n}\n\n}\n}\n\n", "meta": {"hexsha": "5922751bf5d3ed1fa0ebf33fe9f15fe2fea0cb1a", "size": 2804, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Random.cpp", "max_stars_repo_name": "MrMoose/moose_tools", "max_stars_repo_head_hexsha": "bbc85397db193e9a64c71dcb6063683a3e433a66", "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": "Random.cpp", "max_issues_repo_name": "MrMoose/moose_tools", "max_issues_repo_head_hexsha": "bbc85397db193e9a64c71dcb6063683a3e433a66", "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": "Random.cpp", "max_forks_repo_name": "MrMoose/moose_tools", "max_forks_repo_head_hexsha": "bbc85397db193e9a64c71dcb6063683a3e433a66", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7247706422, "max_line_length": 120, "alphanum_fraction": 0.7032810271, "num_tokens": 751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825006, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.46521362566318025}}
{"text": "\n#include <gtest/gtest.h>\n\n#include <Eigen/Core>\n#include <algorithm>\n#include <csim/init_ops.hpp>\n#include <csim/memory_ops.hpp>\n#include <csim/stat_ops.hpp>\n#include <csim/update_ops.hpp>\n#include <csim/update_ops_cpp.hpp>\n#include <string>\n\n#include \"../util/util.hpp\"\n\nvoid test_single_dense_matrix_gate(\n    std::function<void(UINT, const CTYPE*, CTYPE*, ITYPE)> func) {\n    const UINT n = 6;\n    const ITYPE dim = 1ULL << n;\n    const UINT max_repeat = 10;\n\n    Eigen::Matrix<std::complex<double>, 2, 2, Eigen::RowMajor> U;\n\n    UINT target;\n\n    auto state = allocate_quantum_state(dim);\n    initialize_Haar_random_state(state, dim);\n    Eigen::VectorXcd test_state = Eigen::VectorXcd::Zero(dim);\n    for (ITYPE i = 0; i < dim; ++i) test_state[i] = state[i];\n\n    Eigen::MatrixXcd whole_I = Eigen::MatrixXcd::Identity(dim, dim);\n\n    for (UINT rep = 0; rep < max_repeat; ++rep) {\n        // single qubit dense matrix gate\n        // NOTE: Eigen uses column major by default. To use raw-data of eigen\n        // matrix, we need to specify RowMajor.\n        target = rand_int(n);\n        U = get_eigen_matrix_random_single_qubit_unitary();\n        func(target, (CTYPE*)U.data(), state, dim);\n        test_state =\n            get_expanded_eigen_matrix_with_identity(target, U, n) * test_state;\n        state_equal(state, test_state, dim, \"single dense gate\");\n    }\n    release_quantum_state(state);\n}\n\nTEST(UpdateTest, SingleDenseMatrixTest) {\n    test_single_dense_matrix_gate(single_qubit_dense_matrix_gate);\n    test_single_dense_matrix_gate(single_qubit_dense_matrix_gate_single);\n    test_single_dense_matrix_gate(single_qubit_dense_matrix_gate_single_unroll);\n#ifdef _OPENMP\n    test_single_dense_matrix_gate(single_qubit_dense_matrix_gate_parallel);\n    test_single_dense_matrix_gate(\n        single_qubit_dense_matrix_gate_parallel_unroll);\n#endif\n#ifdef _USE_SIMD\n    test_single_dense_matrix_gate(single_qubit_dense_matrix_gate_single_simd);\n#ifdef _OPENMP\n    test_single_dense_matrix_gate(single_qubit_dense_matrix_gate_parallel_simd);\n#endif\n#endif\n}\n\nvoid test_general_dense_matrix_gate(\n    std::function<void(const UINT*, UINT, const CTYPE*, CTYPE*, ITYPE)> func) {\n    const UINT n = 6;\n    const ITYPE dim = 1ULL << n;\n    const UINT max_repeat = 10;\n\n    std::vector<UINT> index_list;\n    for (UINT i = 0; i < n; ++i) index_list.push_back(i);\n\n    Eigen::Matrix<std::complex<double>, 2, 2, Eigen::RowMajor> U1, U2, U3;\n    UINT targets[3];\n\n    auto state = allocate_quantum_state(dim);\n    initialize_Haar_random_state(state, dim);\n    Eigen::VectorXcd test_state = Eigen::VectorXcd::Zero(dim);\n    for (ITYPE i = 0; i < dim; ++i) test_state[i] = state[i];\n\n    Eigen::MatrixXcd whole_I = Eigen::MatrixXcd::Identity(dim, dim);\n\n    // general single\n    {\n        Eigen::Matrix<std::complex<double>, 2, 2, Eigen::RowMajor> Umerge;\n        for (UINT rep = 0; rep < max_repeat; ++rep) {\n            // two qubit dense matrix gate\n            U1 = get_eigen_matrix_random_single_qubit_unitary();\n            std::random_shuffle(index_list.begin(), index_list.end());\n            targets[0] = index_list[0];\n            Umerge = U1;\n\n            test_state =\n                get_expanded_eigen_matrix_with_identity(targets[0], U1, n) *\n                test_state;\n            func(targets, 1, (CTYPE*)Umerge.data(), state, dim);\n            state_equal(\n                state, test_state, dim, \"single-qubit separable dense gate\");\n        }\n    }\n    // general double\n    {\n        Eigen::Matrix<std::complex<double>, 4, 4, Eigen::RowMajor> Umerge;\n\n        for (UINT rep = 0; rep < max_repeat; ++rep) {\n            // two qubit dense matrix gate\n            U1 = get_eigen_matrix_random_single_qubit_unitary();\n            U2 = get_eigen_matrix_random_single_qubit_unitary();\n\n            std::random_shuffle(index_list.begin(), index_list.end());\n            targets[0] = index_list[0];\n            targets[1] = index_list[1];\n            Umerge = kronecker_product(U2, U1);\n\n            test_state =\n                get_expanded_eigen_matrix_with_identity(targets[1], U2, n) *\n                get_expanded_eigen_matrix_with_identity(targets[0], U1, n) *\n                test_state;\n            func(targets, 2, (CTYPE*)Umerge.data(), state, dim);\n            state_equal(\n                state, test_state, dim, \"two-qubit separable dense gate\");\n        }\n    }\n    // general triple\n    {\n        Eigen::Matrix<std::complex<double>, 8, 8, Eigen::RowMajor> Umerge;\n\n        for (UINT rep = 0; rep < max_repeat; ++rep) {\n            // two qubit dense matrix gate\n            U1 = get_eigen_matrix_random_single_qubit_unitary();\n            U2 = get_eigen_matrix_random_single_qubit_unitary();\n            U3 = get_eigen_matrix_random_single_qubit_unitary();\n\n            std::random_shuffle(index_list.begin(), index_list.end());\n            targets[0] = index_list[0];\n            targets[1] = index_list[1];\n            targets[2] = index_list[2];\n            Umerge = kronecker_product(U3, kronecker_product(U2, U1));\n\n            test_state =\n                get_expanded_eigen_matrix_with_identity(targets[2], U3, n) *\n                get_expanded_eigen_matrix_with_identity(targets[1], U2, n) *\n                get_expanded_eigen_matrix_with_identity(targets[0], U1, n) *\n                test_state;\n            func(targets, 3, (CTYPE*)Umerge.data(), state, dim);\n            state_equal(\n                state, test_state, dim, \"three-qubit separable dense gate\");\n        }\n    }\n    release_quantum_state(state);\n}\n\nTEST(UpdateTest, ThreeQubitDenseMatrixTest) {\n    test_general_dense_matrix_gate(multi_qubit_dense_matrix_gate);\n    test_general_dense_matrix_gate(multi_qubit_dense_matrix_gate_single);\n#ifdef _OPENMP\n    test_general_dense_matrix_gate(multi_qubit_dense_matrix_gate_parallel);\n#endif\n}", "meta": {"hexsha": "9aa182a0199109ecd84512f47f00edb57583e605", "size": 5839, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/csim/test_update_dense.cpp", "max_stars_repo_name": "kodack64/qulacs-osaka", "max_stars_repo_head_hexsha": "4ccc3ff084f10942e22d8663a01ed67efd24d9f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2022-01-26T06:56:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T02:07:24.000Z", "max_issues_repo_path": "test/csim/test_update_dense.cpp", "max_issues_repo_name": "kodack64/qulacs-osaka", "max_issues_repo_head_hexsha": "4ccc3ff084f10942e22d8663a01ed67efd24d9f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 104.0, "max_issues_repo_issues_event_min_datetime": "2021-11-12T04:15:02.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T05:12:20.000Z", "max_forks_repo_path": "test/csim/test_update_dense.cpp", "max_forks_repo_name": "kodack64/qulacs-osaka", "max_forks_repo_head_hexsha": "4ccc3ff084f10942e22d8663a01ed67efd24d9f7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-12-19T11:52:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-09T04:20:17.000Z", "avg_line_length": 36.9556962025, "max_line_length": 80, "alphanum_fraction": 0.6514814181, "num_tokens": 1471, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825007, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.46521362566318025}}
{"text": "//  Copyright (c) 2006 Xiaogang Zhang\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_BESSEL_JY_HPP\n#define BOOST_MATH_BESSEL_JY_HPP\n\n#ifdef _MSC_VER\n#pragma once\n#endif\n\n#include <boost/math/tools/config.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/math/special_functions/sign.hpp>\n#include <boost/math/special_functions/hypot.hpp>\n#include <boost/math/special_functions/sin_pi.hpp>\n#include <boost/math/special_functions/cos_pi.hpp>\n#include <boost/math/special_functions/detail/bessel_jy_asym.hpp>\n#include <boost/math/special_functions/detail/bessel_jy_series.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/policies/error_handling.hpp>\n#include <complex>\n\n// Bessel functions of the first and second kind of fractional order\n\nnamespace boost { namespace math {\n\n   namespace detail {\n\n      //\n      // Simultaneous calculation of A&S 9.2.9 and 9.2.10\n      // for use in A&S 9.2.5 and 9.2.6.\n      // This series is quick to evaluate, but divergent unless\n      // x is very large, in fact it's pretty hard to figure out\n      // with any degree of precision when this series actually \n      // *will* converge!!  Consequently, we may just have to\n      // try it and see...\n      //\n      template <class T, class Policy>\n      bool hankel_PQ(T v, T x, T* p, T* q, const Policy& )\n      {\n         BOOST_MATH_STD_USING\n            T tolerance = 2 * policies::get_epsilon<T, Policy>();\n         *p = 1;\n         *q = 0;\n         T k = 1;\n         T z8 = 8 * x;\n         T sq = 1;\n         T mu = 4 * v * v;\n         T term = 1;\n         bool ok = true;\n         do\n         {\n            term *= (mu - sq * sq) / (k * z8);\n            *q += term;\n            k += 1;\n            sq += 2;\n            T mult = (sq * sq - mu) / (k * z8);\n            ok = fabs(mult) < 0.5f;\n            term *= mult;\n            *p += term;\n            k += 1;\n            sq += 2;\n         }\n         while((fabs(term) > tolerance * *p) && ok);\n         return ok;\n      }\n\n      // Calculate Y(v, x) and Y(v+1, x) by Temme's method, see\n      // Temme, Journal of Computational Physics, vol 21, 343 (1976)\n      template <typename T, typename Policy>\n      int temme_jy(T v, T x, T* Y, T* Y1, const Policy& pol)\n      {\n         T g, h, p, q, f, coef, sum, sum1, tolerance;\n         T a, d, e, sigma;\n         unsigned long k;\n\n         BOOST_MATH_STD_USING\n            using namespace boost::math::tools;\n         using namespace boost::math::constants;\n\n         BOOST_MATH_ASSERT(fabs(v) <= 0.5f);  // precondition for using this routine\n\n         T gp = boost::math::tgamma1pm1(v, pol);\n         T gm = boost::math::tgamma1pm1(-v, pol);\n         T spv = boost::math::sin_pi(v, pol);\n         T spv2 = boost::math::sin_pi(v/2, pol);\n         T xp = pow(x/2, v);\n\n         a = log(x / 2);\n         sigma = -a * v;\n         d = abs(sigma) < tools::epsilon<T>() ?\n            T(1) : sinh(sigma) / sigma;\n         e = abs(v) < tools::epsilon<T>() ? T(v*pi<T>()*pi<T>() / 2)\n            : T(2 * spv2 * spv2 / v);\n\n         T g1 = (v == 0) ? T(-euler<T>()) : T((gp - gm) / ((1 + gp) * (1 + gm) * 2 * v));\n         T g2 = (2 + gp + gm) / ((1 + gp) * (1 + gm) * 2);\n         T vspv = (fabs(v) < tools::epsilon<T>()) ? T(1/constants::pi<T>()) : T(v / spv);\n         f = (g1 * cosh(sigma) - g2 * a * d) * 2 * vspv;\n\n         p = vspv / (xp * (1 + gm));\n         q = vspv * xp / (1 + gp);\n\n         g = f + e * q;\n         h = p;\n         coef = 1;\n         sum = coef * g;\n         sum1 = coef * h;\n\n         T v2 = v * v;\n         T coef_mult = -x * x / 4;\n\n         // series summation\n         tolerance = policies::get_epsilon<T, Policy>();\n         for (k = 1; k < policies::get_max_series_iterations<Policy>(); k++)\n         {\n            f = (k * f + p + q) / (k*k - v2);\n            p /= k - v;\n            q /= k + v;\n            g = f + e * q;\n            h = p - k * g;\n            coef *= coef_mult / k;\n            sum += coef * g;\n            sum1 += coef * h;\n            if (abs(coef * g) < abs(sum) * tolerance) \n            { \n               break; \n            }\n         }\n         policies::check_series_iterations<T>(\"boost::math::bessel_jy<%1%>(%1%,%1%) in temme_jy\", k, pol);\n         *Y = -sum;\n         *Y1 = -2 * sum1 / x;\n\n         return 0;\n      }\n\n      // Evaluate continued fraction fv = J_(v+1) / J_v, see\n      // Abramowitz and Stegun, Handbook of Mathematical Functions, 1972, 9.1.73\n      template <typename T, typename Policy>\n      int CF1_jy(T v, T x, T* fv, int* sign, const Policy& pol)\n      {\n         T C, D, f, a, b, delta, tiny, tolerance;\n         unsigned long k;\n         int s = 1;\n\n         BOOST_MATH_STD_USING\n\n            // |x| <= |v|, CF1_jy converges rapidly\n            // |x| > |v|, CF1_jy needs O(|x|) iterations to converge\n\n            // modified Lentz's method, see\n            // Lentz, Applied Optics, vol 15, 668 (1976)\n            tolerance = 2 * policies::get_epsilon<T, Policy>();\n         tiny = sqrt(tools::min_value<T>());\n         C = f = tiny;                           // b0 = 0, replace with tiny\n         D = 0;\n         for (k = 1; k < policies::get_max_series_iterations<Policy>() * 100; k++)\n         {\n            a = -1;\n            b = 2 * (v + k) / x;\n            C = b + a / C;\n            D = b + a * D;\n            if (C == 0) { C = tiny; }\n            if (D == 0) { D = tiny; }\n            D = 1 / D;\n            delta = C * D;\n            f *= delta;\n            if (D < 0) { s = -s; }\n            if (abs(delta - 1) < tolerance) \n            { break; }\n         }\n         policies::check_series_iterations<T>(\"boost::math::bessel_jy<%1%>(%1%,%1%) in CF1_jy\", k / 100, pol);\n         *fv = -f;\n         *sign = s;                              // sign of denominator\n\n         return 0;\n      }\n      //\n      // This algorithm was originally written by Xiaogang Zhang\n      // using std::complex to perform the complex arithmetic.\n      // However, that turns out to 10x or more slower than using\n      // all real-valued arithmetic, so it's been rewritten using\n      // real values only.\n      //\n      template <typename T, typename Policy>\n      int CF2_jy(T v, T x, T* p, T* q, const Policy& pol)\n      {\n         BOOST_MATH_STD_USING\n\n            T Cr, Ci, Dr, Di, fr, fi, a, br, bi, delta_r, delta_i, temp;\n         T tiny;\n         unsigned long k;\n\n         // |x| >= |v|, CF2_jy converges rapidly\n         // |x| -> 0, CF2_jy fails to converge\n         BOOST_MATH_ASSERT(fabs(x) > 1);\n\n         // modified Lentz's method, complex numbers involved, see\n         // Lentz, Applied Optics, vol 15, 668 (1976)\n         T tolerance = 2 * policies::get_epsilon<T, Policy>();\n         tiny = sqrt(tools::min_value<T>());\n         Cr = fr = -0.5f / x;\n         Ci = fi = 1;\n         //Dr = Di = 0;\n         T v2 = v * v;\n         a = (0.25f - v2) / x; // Note complex this one time only!\n         br = 2 * x;\n         bi = 2;\n         temp = Cr * Cr + 1;\n         Ci = bi + a * Cr / temp;\n         Cr = br + a / temp;\n         Dr = br;\n         Di = bi;\n         if (fabs(Cr) + fabs(Ci) < tiny) { Cr = tiny; }\n         if (fabs(Dr) + fabs(Di) < tiny) { Dr = tiny; }\n         temp = Dr * Dr + Di * Di;\n         Dr = Dr / temp;\n         Di = -Di / temp;\n         delta_r = Cr * Dr - Ci * Di;\n         delta_i = Ci * Dr + Cr * Di;\n         temp = fr;\n         fr = temp * delta_r - fi * delta_i;\n         fi = temp * delta_i + fi * delta_r;\n         for (k = 2; k < policies::get_max_series_iterations<Policy>(); k++)\n         {\n            a = k - 0.5f;\n            a *= a;\n            a -= v2;\n            bi += 2;\n            temp = Cr * Cr + Ci * Ci;\n            Cr = br + a * Cr / temp;\n            Ci = bi - a * Ci / temp;\n            Dr = br + a * Dr;\n            Di = bi + a * Di;\n            if (fabs(Cr) + fabs(Ci) < tiny) { Cr = tiny; }\n            if (fabs(Dr) + fabs(Di) < tiny) { Dr = tiny; }\n            temp = Dr * Dr + Di * Di;\n            Dr = Dr / temp;\n            Di = -Di / temp;\n            delta_r = Cr * Dr - Ci * Di;\n            delta_i = Ci * Dr + Cr * Di;\n            temp = fr;\n            fr = temp * delta_r - fi * delta_i;\n            fi = temp * delta_i + fi * delta_r;\n            if (fabs(delta_r - 1) + fabs(delta_i) < tolerance)\n               break;\n         }\n         policies::check_series_iterations<T>(\"boost::math::bessel_jy<%1%>(%1%,%1%) in CF2_jy\", k, pol);\n         *p = fr;\n         *q = fi;\n\n         return 0;\n      }\n\n      static const int need_j = 1;\n      static const int need_y = 2;\n\n      // Compute J(v, x) and Y(v, x) simultaneously by Steed's method, see\n      // Barnett et al, Computer Physics Communications, vol 8, 377 (1974)\n      template <typename T, typename Policy>\n      int bessel_jy(T v, T x, T* J, T* Y, int kind, const Policy& pol)\n      {\n         BOOST_MATH_ASSERT(x >= 0);\n\n         T u, Jv, Ju, Yv, Yv1, Yu, Yu1(0), fv, fu;\n         T W, p, q, gamma, current, prev, next;\n         bool reflect = false;\n         unsigned n, k;\n         int s;\n         int org_kind = kind;\n         T cp = 0;\n         T sp = 0;\n\n         static const char* function = \"boost::math::bessel_jy<%1%>(%1%,%1%)\";\n\n         BOOST_MATH_STD_USING\n            using namespace boost::math::tools;\n         using namespace boost::math::constants;\n\n         if (v < 0)\n         {\n            reflect = true;\n            v = -v;                             // v is non-negative from here\n         }\n         if (v > static_cast<T>((std::numeric_limits<int>::max)()))\n         {\n            *J = *Y = policies::raise_evaluation_error<T>(function, \"Order of Bessel function is too large to evaluate: got %1%\", v, pol);\n            return 1;\n         }\n         n = iround(v, pol);\n         u = v - n;                              // -1/2 <= u < 1/2\n\n         if(reflect)\n         {\n            T z = (u + n % 2);\n            cp = boost::math::cos_pi(z, pol);\n            sp = boost::math::sin_pi(z, pol);\n            if(u != 0)\n               kind = need_j|need_y;               // need both for reflection formula\n         }\n\n         if(x == 0)\n         {\n            if(v == 0)\n               *J = 1;\n            else if((u == 0) || !reflect)\n               *J = 0;\n            else if(kind & need_j)\n               *J = policies::raise_domain_error<T>(function, \"Value of Bessel J_v(x) is complex-infinity at %1%\", x, pol); // complex infinity\n            else\n               *J = std::numeric_limits<T>::quiet_NaN();  // any value will do, not using J.\n\n            if((kind & need_y) == 0)\n               *Y = std::numeric_limits<T>::quiet_NaN();  // any value will do, not using Y.\n            else if(v == 0)\n               *Y = -policies::raise_overflow_error<T>(function, 0, pol);\n            else\n               *Y = policies::raise_domain_error<T>(function, \"Value of Bessel Y_v(x) is complex-infinity at %1%\", x, pol); // complex infinity\n            return 1;\n         }\n\n         // x is positive until reflection\n         W = T(2) / (x * pi<T>());               // Wronskian\n         T Yv_scale = 1;\n         if(((kind & need_y) == 0) && ((x < 1) || (v > x * x / 4) || (x < 5)))\n         {\n            //\n            // This series will actually converge rapidly for all small\n            // x - say up to x < 20 - but the first few terms are large\n            // and divergent which leads to large errors :-(\n            //\n            Jv = bessel_j_small_z_series(v, x, pol);\n            Yv = std::numeric_limits<T>::quiet_NaN();\n         }\n         else if((x < 1) && (u != 0) && (log(policies::get_epsilon<T, Policy>() / 2) > v * log((x/2) * (x/2) / v)))\n         {\n            // Evaluate using series representations.\n            // This is particularly important for x << v as in this\n            // area temme_jy may be slow to converge, if it converges at all.\n            // Requires x is not an integer.\n            if(kind&need_j)\n               Jv = bessel_j_small_z_series(v, x, pol);\n            else\n               Jv = std::numeric_limits<T>::quiet_NaN();\n            if((org_kind&need_y && (!reflect || (cp != 0))) \n               || (org_kind & need_j && (reflect && (sp != 0))))\n            {\n               // Only calculate if we need it, and if the reflection formula will actually use it:\n               Yv = bessel_y_small_z_series(v, x, &Yv_scale, pol);\n            }\n            else\n               Yv = std::numeric_limits<T>::quiet_NaN();\n         }\n         else if((u == 0) && (x < policies::get_epsilon<T, Policy>()))\n         {\n            // Truncated series evaluation for small x and v an integer,\n            // much quicker in this area than temme_jy below.\n            if(kind&need_j)\n               Jv = bessel_j_small_z_series(v, x, pol);\n            else\n               Jv = std::numeric_limits<T>::quiet_NaN();\n            if((org_kind&need_y && (!reflect || (cp != 0))) \n               || (org_kind & need_j && (reflect && (sp != 0))))\n            {\n               // Only calculate if we need it, and if the reflection formula will actually use it:\n               Yv = bessel_yn_small_z(n, x, &Yv_scale, pol);\n            }\n            else\n               Yv = std::numeric_limits<T>::quiet_NaN();\n         }\n         else if(asymptotic_bessel_large_x_limit(v, x))\n         {\n            if(kind&need_y)\n            {\n               Yv = asymptotic_bessel_y_large_x_2(v, x, pol);\n            }\n            else\n               Yv = std::numeric_limits<T>::quiet_NaN(); // any value will do, we're not using it.\n            if(kind&need_j)\n            {\n               Jv = asymptotic_bessel_j_large_x_2(v, x, pol);\n            }\n            else\n               Jv = std::numeric_limits<T>::quiet_NaN(); // any value will do, we're not using it.\n         }\n         else if((x > 8) && hankel_PQ(v, x, &p, &q, pol))\n         {\n            //\n            // Hankel approximation: note that this method works best when x \n            // is large, but in that case we end up calculating sines and cosines\n            // of large values, with horrendous resulting accuracy.  It is fast though\n            // when it works....\n            //\n            // Normally we calculate sin/cos(chi) where:\n            //\n            // chi = x - fmod(T(v / 2 + 0.25f), T(2)) * boost::math::constants::pi<T>();\n            //\n            // But this introduces large errors, so use sin/cos addition formulae to\n            // improve accuracy:\n            //\n            T mod_v = fmod(T(v / 2 + 0.25f), T(2));\n            T sx = sin(x);\n            T cx = cos(x);\n            T sv = boost::math::sin_pi(mod_v, pol);\n            T cv = boost::math::cos_pi(mod_v, pol);\n\n            T sc = sx * cv - sv * cx; // == sin(chi);\n            T cc = cx * cv + sx * sv; // == cos(chi);\n            T chi = boost::math::constants::root_two<T>() / (boost::math::constants::root_pi<T>() * sqrt(x)); //sqrt(2 / (boost::math::constants::pi<T>() * x));\n            Yv = chi * (p * sc + q * cc);\n            Jv = chi * (p * cc - q * sc);\n         }\n         else if (x <= 2)                           // x in (0, 2]\n         {\n            if(temme_jy(u, x, &Yu, &Yu1, pol))             // Temme series\n            {\n               // domain error:\n               *J = *Y = Yu;\n               return 1;\n            }\n            prev = Yu;\n            current = Yu1;\n            T scale = 1;\n            policies::check_series_iterations<T>(function, n, pol);\n            for (k = 1; k <= n; k++)            // forward recurrence for Y\n            {\n               T fact = 2 * (u + k) / x;\n               if((tools::max_value<T>() - fabs(prev)) / fact < fabs(current))\n               {\n                  scale /= current;\n                  prev /= current;\n                  current = 1;\n               }\n               next = fact * current - prev;\n               prev = current;\n               current = next;\n            }\n            Yv = prev;\n            Yv1 = current;\n            if(kind&need_j)\n            {\n               CF1_jy(v, x, &fv, &s, pol);                 // continued fraction CF1_jy\n               Jv = scale * W / (Yv * fv - Yv1);           // Wronskian relation\n            }\n            else\n               Jv = std::numeric_limits<T>::quiet_NaN(); // any value will do, we're not using it.\n            Yv_scale = scale;\n         }\n         else                                    // x in (2, \\infty)\n         {\n            // Get Y(u, x):\n\n            T ratio;\n            CF1_jy(v, x, &fv, &s, pol);\n            // tiny initial value to prevent overflow\n            T init = sqrt(tools::min_value<T>());\n            BOOST_MATH_INSTRUMENT_VARIABLE(init);\n            prev = fv * s * init;\n            current = s * init;\n            if(v < max_factorial<T>::value)\n            {\n               policies::check_series_iterations<T>(function, n, pol);\n               for (k = n; k > 0; k--)             // backward recurrence for J\n               {\n                  next = 2 * (u + k) * current / x - prev;\n                  prev = current;\n                  current = next;\n               }\n               ratio = (s * init) / current;     // scaling ratio\n               // can also call CF1_jy() to get fu, not much difference in precision\n               fu = prev / current;\n            }\n            else\n            {\n               //\n               // When v is large we may get overflow in this calculation\n               // leading to NaN's and other nasty surprises:\n               //\n               policies::check_series_iterations<T>(function, n, pol);\n               bool over = false;\n               for (k = n; k > 0; k--)             // backward recurrence for J\n               {\n                  T t = 2 * (u + k) / x;\n                  if((t > 1) && (tools::max_value<T>() / t < current))\n                  {\n                     over = true;\n                     break;\n                  }\n                  next = t * current - prev;\n                  prev = current;\n                  current = next;\n               }\n               if(!over)\n               {\n                  ratio = (s * init) / current;     // scaling ratio\n                  // can also call CF1_jy() to get fu, not much difference in precision\n                  fu = prev / current;\n               }\n               else\n               {\n                  ratio = 0;\n                  fu = 1;\n               }\n            }\n            CF2_jy(u, x, &p, &q, pol);                  // continued fraction CF2_jy\n            T t = u / x - fu;                   // t = J'/J\n            gamma = (p - t) / q;\n            //\n            // We can't allow gamma to cancel out to zero completely as it messes up\n            // the subsequent logic.  So pretend that one bit didn't cancel out\n            // and set to a suitably small value.  The only test case we've been able to\n            // find for this, is when v = 8.5 and x = 4*PI.\n            //\n            if(gamma == 0)\n            {\n               gamma = u * tools::epsilon<T>() / x;\n            }\n            BOOST_MATH_INSTRUMENT_VARIABLE(current);\n            BOOST_MATH_INSTRUMENT_VARIABLE(W);\n            BOOST_MATH_INSTRUMENT_VARIABLE(q);\n            BOOST_MATH_INSTRUMENT_VARIABLE(gamma);\n            BOOST_MATH_INSTRUMENT_VARIABLE(p);\n            BOOST_MATH_INSTRUMENT_VARIABLE(t);\n            Ju = sign(current) * sqrt(W / (q + gamma * (p - t)));\n            BOOST_MATH_INSTRUMENT_VARIABLE(Ju);\n\n            Jv = Ju * ratio;                    // normalization\n\n            Yu = gamma * Ju;\n            Yu1 = Yu * (u/x - p - q/gamma);\n\n            if(kind&need_y)\n            {\n               // compute Y:\n               prev = Yu;\n               current = Yu1;\n               policies::check_series_iterations<T>(function, n, pol);\n               for (k = 1; k <= n; k++)            // forward recurrence for Y\n               {\n                  T fact = 2 * (u + k) / x;\n                  if((tools::max_value<T>() - fabs(prev)) / fact < fabs(current))\n                  {\n                     prev /= current;\n                     Yv_scale /= current;\n                     current = 1;\n                  }\n                  next = fact * current - prev;\n                  prev = current;\n                  current = next;\n               }\n               Yv = prev;\n            }\n            else\n               Yv = std::numeric_limits<T>::quiet_NaN(); // any value will do, we're not using it.\n         }\n\n         if (reflect)\n         {\n            if((sp != 0) && (tools::max_value<T>() * fabs(Yv_scale) < fabs(sp * Yv)))\n               *J = org_kind & need_j ? T(-sign(sp) * sign(Yv) * (Yv_scale != 0 ? sign(Yv_scale) : 1) * policies::raise_overflow_error<T>(function, 0, pol)) : T(0);\n            else\n               *J = cp * Jv - (sp == 0 ? T(0) : T((sp * Yv) / Yv_scale));     // reflection formula\n            if((cp != 0) && (tools::max_value<T>() * fabs(Yv_scale) < fabs(cp * Yv)))\n               *Y = org_kind & need_y ? T(-sign(cp) * sign(Yv) * (Yv_scale != 0 ? sign(Yv_scale) : 1) * policies::raise_overflow_error<T>(function, 0, pol)) : T(0);\n            else\n               *Y = (sp != 0 ? sp * Jv : T(0)) + (cp == 0 ? T(0) : T((cp * Yv) / Yv_scale));\n         }\n         else\n         {\n            *J = Jv;\n            if(tools::max_value<T>() * fabs(Yv_scale) < fabs(Yv))\n               *Y = org_kind & need_y ? T(sign(Yv) * sign(Yv_scale) * policies::raise_overflow_error<T>(function, 0, pol)) : T(0);\n            else\n               *Y = Yv / Yv_scale;\n         }\n\n         return 0;\n      }\n\n   } // namespace detail\n\n}} // namespaces\n\n#endif // BOOST_MATH_BESSEL_JY_HPP\n", "meta": {"hexsha": "a319760b441699ccd086e261c4c4ebddf22cf942", "size": 21848, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/math/special_functions/detail/bessel_jy.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": "lib/boost_1_77_0/boost/math/special_functions/detail/bessel_jy.hpp", "max_issues_repo_name": "Kirbologist/Raman-Scattering-Code-Conversion", "max_issues_repo_head_hexsha": "118a08238a2525f595c4b7d2b735dd37852fac6f", "max_issues_repo_licenses": ["MIT"], "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": "lib/boost_1_77_0/boost/math/special_functions/detail/bessel_jy.hpp", "max_forks_repo_name": "Kirbologist/Raman-Scattering-Code-Conversion", "max_forks_repo_head_hexsha": "118a08238a2525f595c4b7d2b735dd37852fac6f", "max_forks_repo_licenses": ["MIT"], "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": 37.2197614991, "max_line_length": 164, "alphanum_fraction": 0.4472262907, "num_tokens": 5932, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.779992900254107, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.46521361956262713}}
{"text": "// Boost.Geometry\r\n\r\n// Copyright (c) 2017-2018, Oracle and/or its affiliates.\r\n\r\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\r\n\r\n// Licensed under the Boost Software License version 1.0.\r\n// http://www.boost.org/users/license.html\r\n\r\n#ifndef BOOST_GEOMETRY_STRATEGIES_SPHERICAL_DENSIFY_HPP\r\n#define BOOST_GEOMETRY_STRATEGIES_SPHERICAL_DENSIFY_HPP\r\n\r\n\r\n#include <boost/geometry/algorithms/detail/convert_point_to_point.hpp>\r\n#include <boost/geometry/algorithms/detail/signed_size_type.hpp>\r\n#include <boost/geometry/arithmetic/arithmetic.hpp>\r\n#include <boost/geometry/arithmetic/cross_product.hpp>\r\n#include <boost/geometry/arithmetic/dot_product.hpp>\r\n#include <boost/geometry/arithmetic/normalize.hpp>\r\n#include <boost/geometry/core/assert.hpp>\r\n#include <boost/geometry/core/coordinate_dimension.hpp>\r\n#include <boost/geometry/core/coordinate_type.hpp>\r\n#include <boost/geometry/core/radian_access.hpp>\r\n#include <boost/geometry/formulas/spherical.hpp>\r\n#include <boost/geometry/srs/sphere.hpp>\r\n#include <boost/geometry/strategies/densify.hpp>\r\n#include <boost/geometry/strategies/spherical/get_radius.hpp>\r\n#include <boost/geometry/util/math.hpp>\r\n#include <boost/geometry/util/select_most_precise.hpp>\r\n\r\n\r\nnamespace boost { namespace geometry\r\n{\r\n\r\nnamespace strategy { namespace densify\r\n{\r\n\r\n\r\n/*!\r\n\\brief Densification of spherical segment.\r\n\\ingroup strategies\r\n\\tparam RadiusTypeOrSphere \\tparam_radius_or_sphere\r\n\\tparam CalculationType \\tparam_calculation\r\n\r\n\\qbk{\r\n[heading See also]\r\n[link geometry.reference.algorithms.densify.densify_4_with_strategy densify (with strategy)]\r\n}\r\n */\r\ntemplate\r\n<\r\n    typename RadiusTypeOrSphere = double,\r\n    typename CalculationType = void\r\n>\r\nclass spherical\r\n{\r\npublic:\r\n    // For consistency with area strategy the radius is set to 1\r\n    inline spherical()\r\n        : m_radius(1.0)\r\n    {}\r\n\r\n    template <typename RadiusOrSphere>\r\n    explicit inline spherical(RadiusOrSphere const& radius_or_sphere)\r\n        : m_radius(strategy_detail::get_radius\r\n                    <\r\n                        RadiusOrSphere\r\n                    >::apply(radius_or_sphere))\r\n    {}\r\n\r\n    template <typename Point, typename AssignPolicy, typename T>\r\n    inline void apply(Point const& p0, Point const& p1, AssignPolicy & policy, T const& length_threshold) const\r\n    {\r\n        typedef typename AssignPolicy::point_type out_point_t;\r\n        typedef typename select_most_precise\r\n            <\r\n                typename coordinate_type<Point>::type,\r\n                typename coordinate_type<out_point_t>::type,\r\n                CalculationType\r\n            >::type calc_t;\r\n\r\n        calc_t const c0 = 0;\r\n        calc_t const c1 = 1;\r\n        calc_t const pi = math::pi<calc_t>();\r\n\r\n        typedef model::point<calc_t, 3, cs::cartesian> point3d_t;\r\n        point3d_t const xyz0 = formula::sph_to_cart3d<point3d_t>(p0);\r\n        point3d_t const xyz1 = formula::sph_to_cart3d<point3d_t>(p1);\r\n        calc_t const dot01 = geometry::dot_product(xyz0, xyz1);\r\n        calc_t const angle01 = acos(dot01);\r\n\r\n        BOOST_GEOMETRY_ASSERT(length_threshold > T(0));\r\n\r\n        signed_size_type n = signed_size_type(angle01 * m_radius / length_threshold);\r\n        if (n <= 0)\r\n            return;\r\n\r\n        point3d_t axis;\r\n        if (! math::equals(angle01, pi))\r\n        {\r\n            axis = geometry::cross_product(xyz0, xyz1);\r\n            geometry::detail::vec_normalize(axis);\r\n        }\r\n        else // antipodal\r\n        {\r\n            calc_t const half_pi = math::half_pi<calc_t>();\r\n            calc_t const lat = geometry::get_as_radian<1>(p0);\r\n\r\n            if (math::equals(lat, half_pi))\r\n            {\r\n                // pointing east, segment lies on prime meridian, going south\r\n                axis = point3d_t(c0, c1, c0);\r\n            }\r\n            else if (math::equals(lat, -half_pi))\r\n            {\r\n                // pointing west, segment lies on prime meridian, going north\r\n                axis = point3d_t(c0, -c1, c0);\r\n            }\r\n            else\r\n            {\r\n                // lon rotated west by pi/2 at equator\r\n                calc_t const lon = geometry::get_as_radian<0>(p0);\r\n                axis = point3d_t(sin(lon), -cos(lon), c0);\r\n            }\r\n        }\r\n\r\n        calc_t step = angle01 / (n + 1);\r\n\r\n        calc_t a = step;\r\n        for (signed_size_type i = 0 ; i < n ; ++i, a += step)\r\n        {\r\n            // Axis-Angle rotation\r\n            // see: https://en.wikipedia.org/wiki/Axis-angle_representation\r\n            calc_t const cos_a = cos(a);\r\n            calc_t const sin_a = sin(a);\r\n            // cos_a * v\r\n            point3d_t s1 = xyz0;\r\n            geometry::multiply_value(s1, cos_a);\r\n            // sin_a * (n x v)\r\n            point3d_t s2 = geometry::cross_product(axis, xyz0);\r\n            geometry::multiply_value(s2, sin_a);\r\n            // (1 - cos_a)(n.v) * n\r\n            point3d_t s3 = axis;\r\n            geometry::multiply_value(s3, (c1 - cos_a) * geometry::dot_product(axis, xyz0));\r\n            // v_rot = cos_a * v + sin_a * (n x v) + (1 - cos_a)(n.v) * e\r\n            point3d_t v_rot = s1;\r\n            geometry::add_point(v_rot, s2);\r\n            geometry::add_point(v_rot, s3);\r\n            \r\n            out_point_t p = formula::cart3d_to_sph<out_point_t>(v_rot);\r\n            geometry::detail::conversion::point_to_point\r\n                <\r\n                    Point, out_point_t,\r\n                    2, dimension<out_point_t>::value\r\n                >::apply(p0, p);\r\n\r\n            policy.apply(p);\r\n        }\r\n    }\r\n\r\nprivate:\r\n    typename strategy_detail::get_radius\r\n        <\r\n            RadiusTypeOrSphere\r\n        >::type m_radius;\r\n};\r\n\r\n\r\n#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\r\nnamespace services\r\n{\r\n\r\ntemplate <>\r\nstruct default_strategy<spherical_equatorial_tag>\r\n{\r\n    typedef strategy::densify::spherical<> type;\r\n};\r\n\r\n\r\n} // namespace services\r\n#endif // DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\r\n\r\n\r\n}} // namespace strategy::densify\r\n\r\n\r\n}} // namespace boost::geometry\r\n\r\n#endif // BOOST_GEOMETRY_ALGORITHMS_DENSIFY_HPP\r\n", "meta": {"hexsha": "40395ef491ce0d692c7c20f3b82592871fbb5f8d", "size": 6121, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "externals/boost/boost/geometry/strategies/spherical/densify.hpp", "max_stars_repo_name": "YuukiTsuchida/v8_embeded", "max_stars_repo_head_hexsha": "c6e18f4e91fcc50607f8e3edc745a3afa30b2871", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "jeff/common/include/boost/geometry/strategies/spherical/densify.hpp", "max_issues_repo_name": "jeffphi/advent-of-code-2018", "max_issues_repo_head_hexsha": "8e54bd23ebfe42fcbede315f0ab85db903551532", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-04T18:00:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-04T18:00:00.000Z", "max_forks_repo_path": "jeff/common/include/boost/geometry/strategies/spherical/densify.hpp", "max_forks_repo_name": "jeffphi/advent-of-code-2018", "max_forks_repo_head_hexsha": "8e54bd23ebfe42fcbede315f0ab85db903551532", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 32.2157894737, "max_line_length": 112, "alphanum_fraction": 0.6095409247, "num_tokens": 1434, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.46521361956262713}}
{"text": "/*!\n * Copyright (C) tkornuta, IBM Corporation 2015-2019\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 mnist_mlnn_features_visualization_test.cpp\n * @brief Program for visualization of features of mlnn layers trained on MNIST digits.\n * @author tkornuta\n * @date:   03-04-2017\n *\n * Copyright (c) 2017, Tomasz Kornuta, IBM Corporation. All rights reserved.\n *\n */\n\n#include <boost/thread/thread.hpp>\n#include <boost/bind.hpp>\n\n#include <data_io/MNISTMatrixImporter.hpp>\n\n#include <logger/Log.hpp>\n#include <logger/ConsoleOutput.hpp>\nusing namespace mic::logger;\n\n#include <application/ApplicationState.hpp>\n\n#include <configuration/ParameterServer.hpp>\n\n#include <opengl/visualization/WindowManager.hpp>\n#include <opengl/visualization/WindowGrayscaleBatch.hpp>\n#include <opengl/visualization/WindowCollectorChart.hpp>\nusing namespace mic::opengl::visualization;\n\n// Neural net.\n#include <mlnn/BackpropagationNeuralNetwork.hpp>\nusing namespace mic::mlnn;\n\n// Encoders.\n#include <encoders/MatrixXfMatrixXfEncoder.hpp>\n#include <encoders/UIntMatrixXfEncoder.hpp>\n\n/// Windows for displaying activations.\nWindowGrayscaleBatch<float> *w_conv10, *w_conv11, *w_conv12, *w_conv13, *w_conv14, *w_conv15;\nWindowGrayscaleBatch<float> *w_conv20, *w_conv21, *w_conv22, *w_conv23, *w_conv24, *w_conv25;\nWindowGrayscaleBatch<float> *w_conv30, *w_conv31, *w_conv32, *w_conv33, *w_conv34, *w_conv35;\n/// Window for displaying chart with statistics.\nWindowCollectorChart<float>* w_chart;\n/// Data collector .\nmic::data_io::DataCollectorPtr<std::string, float> collector_ptr;\n\n\n/// MNIST importer.\nmic::data_io::MNISTMatrixImporter<float>* importer;\n/// Multi-layer neural network.\nBackpropagationNeuralNetwork<float> neural_net;\n\n/// MNIST matrix encoder.\nmic::encoders::MatrixXfMatrixXfEncoder* mnist_encoder;\n/// Label 2 matrix encoder (1 hot).\nmic::encoders::UIntMatrixXfEncoder* label_encoder;\n\nconst size_t batch_size = 9;\nconst char* fileName = \"nn_autoencoder_weights_visualization.txt\";\n\n\n/*!\n * \\brief Function for batch sampling.\n * \\author tkornuta\n */\nvoid batch_function (void) {\n\n/*\tif (neural_net.load(fileName)) {\n\t\tLOG(LINFO) << \"Loaded neural network from a file\";\n\t} else {*/\n\t\t{\n\t\t\t/*neural_net.pushLayer(new mic::mlnn::convolution::Cropping<float>(28, 28, 1, 2));\n\t\t\tneural_net.pushLayer(new Linear<float>(24, 24, 1, 10, 1, 1));\n\t\t\tneural_net.pushLayer(new Softmax<float>(10));*/\n\n\t\t\tneural_net.pushLayer(new mic::mlnn::convolution::Cropping<float>(28, 28, 1, 2));\n\t\t\tneural_net.pushLayer(new Linear<float>(24, 24, 1, 24, 24, 1));\n\t\t\tneural_net.pushLayer(new mic::mlnn::convolution::Padding<float>(24, 24, 1, 2));\n\n\t\t\tif (!neural_net.verify())\n\t\t\t\texit(-1);\n\n\n\t\t\tneural_net.setLoss<  mic::neural_nets::loss::SquaredErrorLoss<float> >();\n\t\t\tneural_net.setOptimization<  mic::neural_nets::optimization::Adam<float> >();\n\n\t\tLOG(LINFO) << \"Generated new neural network\";\n\t}//: else\n\n\t// Import data from datasets.\n\tif (!importer->importData())\n\t\texit(-1);\n\n\n\tsize_t iteration = 0;\n\n\t// Retrieve the next minibatch.\n\t//mic::types::MNISTBatch bt = importer->getNextBatch();\n\t//importer->setNextSampleIndex(5);\n\n\t// Main application loop.\n\twhile (!APP_STATE->Quit()) {\n\n\t\t// If not paused.\n\t\tif (!APP_STATE->isPaused()) {\n\n\t\t\t// If single step mode - pause after the step.\n\t\t\tif (APP_STATE->isSingleStepModeOn())\n\t\t\t\tAPP_STATE->pressPause();\n\n\t\t\t{ // Enter critical section - with the use of scoped lock from AppState!\n\t\t\t\tAPP_DATA_SYNCHRONIZATION_SCOPED_LOCK();\n\n\t\t\t\t// Retrieve the next minibatch.\n\t\t\t\tmic::types::MNISTBatch<float> bt = importer->getRandomBatch();\n\n\t\t\t\t// Encode data.\n\t\t\t\tmic::types::MatrixXfPtr encoded_batch = mnist_encoder->encodeBatch(bt.data());\n\t\t\t\tmic::types::MatrixXfPtr encoded_labels = label_encoder->encodeBatch(bt.labels());\n\n\t\t\t\t// Train the autoencoder.\n\t\t\t\tfloat loss = neural_net.train (encoded_batch, encoded_batch, 0.001, 0.0001);\n\n\t\t\t\tif (iteration%10 == 0) {\n\n\t\t\t\t\tstd::shared_ptr<mic::mlnn::fully_connected::Linear<float> > lin1 =\n\t\t\t\t\t\t\tneural_net.getLayer<mic::mlnn::fully_connected::Linear<float> >(1);\n\t\t\t\t\tw_conv10->setBatchUnsynchronized(lin1->getInputActivations());\n\t\t\t\t\tw_conv11->setBatchUnsynchronized(lin1->getInputGradientActivations());\n\t\t\t\t\tw_conv12->setBatchUnsynchronized(lin1->getWeightActivations());\n\t\t\t\t\tw_conv13->setBatchUnsynchronized(lin1->getWeightGradientActivations());\n\t\t\t\t\tw_conv14->setBatchUnsynchronized(lin1->getOutputActivations());\n\t\t\t\t\tw_conv15->setBatchUnsynchronized(lin1->getOutputGradientActivations());\n\n\t\t\t\t\tw_conv20->setBatchUnsynchronized(lin1->getInverseWeightActivations());\n\t\t\t\t\tw_conv21->setBatchUnsynchronized(lin1->getInverseOutputActivations());\n\n\t\t\t\t\t/*std::shared_ptr<Layer<float> > sm1 = neural_net.getLayer(2);\n\t\t\t\t\tw_conv34->setBatchUnsynchronized(sm1->getOutputActivations());\n\t\t\t\t\tw_conv35->setBatchUnsynchronized(sm1->getOutputGradientActivations());*/\n\n\t\t\t\t\t// Add data to chart window.\n\t\t\t\t\tcollector_ptr->addDataToContainer(\"Loss\", loss);\n\t\t\t\t\tfloat reconstruction_error = neural_net.getLayer<mic::mlnn::fully_connected::Linear<float> >(1)->calculateMeanReconstructionError();\n\t\t\t\t\tcollector_ptr->addDataToContainer(\"Reconstruction Error\", reconstruction_error);\n\t\t\t\t}//: if\n\n\t\t\t\titeration++;\n\t\t\t\t//float reconstruction_error = neural_net.getLayer<mic::mlnn::fully_connected::Linear<float> >(1)->calculateMeanReconstructionError();\n\n\t\t\t\tLOG(LINFO) << \"Iteration: \" << iteration << \" loss =\" << loss;// << \" reconstruction error =\" << reconstruction_error;\n\t\t\t}//: end of critical section\n\n\t\t}//: if\n\n\t\t// Sleep.\n\t\tAPP_SLEEP();\n\t}//: while\n\n}//: image_encoder_and_visualization_test\n\n\n\n/*!\n * \\brief Main program function. Runs two threads: main (for GLUT) and another one (for data processing).\n * \\author tkornuta\n * @param[in] argc Number of parameters (passed to glManaged).\n * @param[in] argv List of parameters (passed to glManaged).\n * @return (not used)\n */\nint main(int argc, char* argv[]) {\n\t// Set console output to logger.\n\tLOGGER->addOutput(new ConsoleOutput());\n\tLOG(LINFO) << \"Logger initialized. Starting application\";\n\n\t// Parse parameters.\n\tPARAM_SERVER->parseApplicationParameters(argc, argv);\n\n\t// Initilize application state (\"touch it\") ;)\n\tAPP_STATE;\n\n\t// Load dataset.\n\timporter = new mic::data_io::MNISTMatrixImporter<float>();\n\timporter->setBatchSize(batch_size);\n\n\t// Initialize the encoders.\n\tmnist_encoder = new mic::encoders::MatrixXfMatrixXfEncoder(28, 28);\n\tlabel_encoder = new mic::encoders::UIntMatrixXfEncoder(10);\n\n\t// Set parameters of all property-tree derived objects - USER independent part.\n\tPARAM_SERVER->loadPropertiesFromConfiguration();\n\n\t// Initialize property-dependent variables of all registered property-tree objects - USER dependent part.\n\tPARAM_SERVER->initializePropertyDependentVariables();\n\n\t// Initialize GLUT! :]\n\tVGL_MANAGER->initializeGLUT(argc, argv);\n\n\t// Create batch visualization window.\n\tw_conv10 = new WindowGrayscaleBatch<float>(\"Lin1 x\", WindowGrayscaleBatch<float>::Norm_HotCold, WindowGrayscaleBatch<float>::Grid_Both, 50, 50, 256, 256);\n\tw_conv11 = new WindowGrayscaleBatch<float>(\"Lin1 dx\", WindowGrayscaleBatch<float>::Norm_HotCold, WindowGrayscaleBatch<float>::Grid_Both, 316, 50, 256, 256);\n\tw_conv12 = new WindowGrayscaleBatch<float>(\"Lin1 W\", WindowGrayscaleBatch<float>::Norm_HotCold, WindowGrayscaleBatch<float>::Grid_Both, 562, 50, 256, 256);\n\tw_conv13 = new WindowGrayscaleBatch<float>(\"Lin1 dW\", WindowGrayscaleBatch<float>::Norm_HotCold, WindowGrayscaleBatch<float>::Grid_Both, 818, 50, 256, 256);\n\tw_conv14 = new WindowGrayscaleBatch<float>(\"Lin1 y\", WindowGrayscaleBatch<float>::Norm_HotCold, WindowGrayscaleBatch<float>::Grid_Both, 1074, 50, 256, 256);\n\tw_conv15 = new WindowGrayscaleBatch<float>(\"Lin1 dy\", WindowGrayscaleBatch<float>::Norm_HotCold, WindowGrayscaleBatch<float>::Grid_Both, 1330, 50, 256, 256);\n\n\tw_conv20 = new WindowGrayscaleBatch<float>(\"Lin1 inverse neuron activation\", WindowGrayscaleBatch<float>::Norm_HotCold, WindowGrayscaleBatch<float>::Grid_Both, 50, 336, 256, 256);\n\tw_conv21 = new WindowGrayscaleBatch<float>(\"Lin1 inverse output activation\", WindowGrayscaleBatch<float>::Norm_HotCold, WindowGrayscaleBatch<float>::Grid_Both, 316, 336, 256, 256);\n\t/*w_conv22 = new WindowGrayscaleBatch<float>(\"Conv2 W\", WindowGrayscaleBatch<float>::Norm_HotCold, WindowGrayscaleBatch<float>::Grid_Both, 562, 336, 256, 256);\n\tw_conv23 = new WindowGrayscaleBatch<float>(\"Conv2 dW\", WindowGrayscaleBatch<float>::Norm_HotCold, WindowGrayscaleBatch<float>::Grid_Both, 818, 336, 256, 256);\n\tw_conv24 = new WindowGrayscaleBatch<float>(\"Conv2 y\", WindowGrayscaleBatch<float>::Norm_HotCold, WindowGrayscaleBatch<float>::Grid_Both, 1074, 336, 256, 256);\n\tw_conv25 = new WindowGrayscaleBatch<float>(\"Conv2 dy\", WindowGrayscaleBatch<float>::Norm_HotCold, WindowGrayscaleBatch<float>::Grid_Both, 1330, 336, 256, 256);\n\n\tw_conv30 = new WindowGrayscaleBatch<float>(\"L1 x\", WindowGrayscaleBatch<float>::Norm_HotCold, WindowGrayscaleBatch<float>::Grid_Both, 50, 622, 256, 256);\n\tw_conv31 = new WindowGrayscaleBatch<float>(\"L1 dx\", WindowGrayscaleBatch<float>::Norm_HotCold, WindowGrayscaleBatch<float>::Grid_Both, 316, 622, 256, 256);\n\tw_conv32 = new WindowGrayscaleBatch<float>(\"L1 W\", WindowGrayscaleBatch<float>::Norm_HotCold, WindowGrayscaleBatch<float>::Grid_Both, 562, 622, 256, 256);\n\tw_conv33 = new WindowGrayscaleBatch<float>(\"L1 dW\", WindowGrayscaleBatch<float>::Norm_HotCold, WindowGrayscaleBatch<float>::Grid_Both, 818, 622, 256, 256);\n\tw_conv34 = new WindowGrayscaleBatch<float>(\"SM y\", WindowGrayscaleBatch<float>::Norm_None, WindowGrayscaleBatch<float>::Grid_Both, 1074, 622, 256, 256);\n\tw_conv35 = new WindowGrayscaleBatch<float>(\"SM dy\", WindowGrayscaleBatch<float>::Norm_HotCold, WindowGrayscaleBatch<float>::Grid_Both, 1330, 622, 256, 256);*/\n\n\t// Chart.\n\tw_chart = new WindowCollectorChart<float>(\"Statistics\", 60, 878, 512, 256);\n\tcollector_ptr= std::make_shared < mic::data_io::DataCollector<std::string, float> >( );\n\tw_chart->setDataCollectorPtr(collector_ptr);\n\n\t// Create data containers.\n\tcollector_ptr->createContainer(\"Loss\", mic::types::color_rgba(255, 0, 0, 180));\n\tcollector_ptr->createContainer(\"Reconstruction Error\", mic::types::color_rgba(255, 255, 255, 180));\n\n\tboost::thread batch_thread(boost::bind(&batch_function));\n\n\t// Start visualization thread.\n\tVGL_MANAGER->startVisualizationLoop();\n\n\tLOG(LINFO) << \"Waiting for threads to join...\";\n\t// End test thread.\n\tbatch_thread.join();\n\tLOG(LINFO) << \"Threads joined - ending application\";\n}//: main\n", "meta": {"hexsha": "9d04a830a5166ddcae5ad1f0d4ecaba44621fabb", "size": 10995, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tests/mnist_mlnn_features_visualization_test.cpp", "max_stars_repo_name": "kant/mi-neural-nets", "max_stars_repo_head_hexsha": "82aa18fddc1fac9b72d8cd3ddcc61c02569f9e20", "max_stars_repo_licenses": ["Apache-2.0"], "max_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/mnist_mlnn_features_visualization_test.cpp", "max_issues_repo_name": "kant/mi-neural-nets", "max_issues_repo_head_hexsha": "82aa18fddc1fac9b72d8cd3ddcc61c02569f9e20", "max_issues_repo_licenses": ["Apache-2.0"], "max_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/mnist_mlnn_features_visualization_test.cpp", "max_forks_repo_name": "kant/mi-neural-nets", "max_forks_repo_head_hexsha": "82aa18fddc1fac9b72d8cd3ddcc61c02569f9e20", "max_forks_repo_licenses": ["Apache-2.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.2874015748, "max_line_length": 181, "alphanum_fraction": 0.7461573442, "num_tokens": 3009, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4652136195626271}}
{"text": "/*\n * BayesRRm.cpp\n *\n *  Created on: 5 Sep 2018\n *      Author: admin\n */\n\n#include <cstdlib>\n#include \"BayesW.hpp\"\n#include \"BayesRRm.h\"\n\n#include \"data.hpp\"\n#include \"distributions_boost.hpp\"\n#include \"options.hpp\"\n#include \"samplewriter.h\"\n#include <chrono>\n#include <numeric>\n#include <random>\n#include <algorithm>\n#include <sys/stat.h>\n#include <libgen.h>\n#include <string.h>\n#include <boost/range/algorithm.hpp>\n#include <sys/time.h>\n#include <iostream>\n#include <ctime>\n#include <mm_malloc.h>\n#ifdef USE_MPI\n#include <mpi.h>\n#include \"mpi_utils.hpp\"\n#endif\n\n#include <omp.h>\n#include \"BayesW_arms.h\"\n#include <math.h>\n\n/* Pre-calculate used constants */\n#define PI 3.14159265359\n#define PI_squared 9.86960440109\n#define PI2 6.28318530718\n#define sqrtPI 1.77245385090552\n#define EuMasc 0.577215664901532\n\nBayesW::~BayesW()\n{\n}\n\n/* Function that finds the sum across the sum across individuals who have marker with specified value */\ndouble BayesW::partial_sum(const double* __restrict__ vec,\n                           const uint*   __restrict__ IX,\n                           const size_t               NXS,\n                           const size_t               NXL) {\n    double sum = 0.0;\n#ifdef __INTEL_COMPILER\n    __assume_aligned(vec, 64);\n    __assume_aligned(IX,  64);\n#endif\n#ifdef _OPENMP\n#pragma omp parallel for reduction(+: sum)\n#endif\n    for (size_t i=NXS; i < NXS + NXL; i++) {\n        sum += vec[IX[i]];\n    }\n    return sum;\n}\n\n/* Function to check if ARS resulted with error*/\ninline void errorCheck(int err){\n\tif(err>0){\n\t\tcout << \"Error code = \" << err << endl;\n\t\texit(1);\n\t}\n}\n\n\n/* Function for the log density of mu */\ninline double mu_dens(double x, void *norm_data)\n/* We are sampling mu (denoted by x here) */\n{\n\tdouble y;\n\n\t/* In C++ we need to do a static cast for the void data */\n\tpars p = *(static_cast<pars *>(norm_data));\n\n\t/* cast voided pointer into pointer to struct norm_parm */\n\ty = - p.alpha * x * p.d - (( (p.epsilon).array()  - x) * p.alpha - EuMasc).exp().sum() - x*x/(2*p.sigma_mu);\n\treturn y;\n};\n\n\n/* Function for the log density of some \"fixed\" covariate effect */\ninline double gamma_dens2(double x, void *norm_data)\n/* We are sampling gamma (denoted by x here) */\n{\n    double y;\n    double sum = 0.0;\n\n    /* In C++ we need to do a static cast for the void data */\n    pars p = *(static_cast<pars *>(norm_data));\n\n#ifdef __INTEL_COMPILER\n    __assume_aligned(&p.epsilon, 64);\n    __assume_aligned(&p.X_j, 64);\n#endif\n#ifdef _OPENMP\n#pragma omp parallel for reduction(+: sum)\n#endif\n    for (size_t i=0; i < p.epsilon.size(); i++) {\n        sum += exp((p.epsilon[i] - p.X_j[i] * x)* p.alpha - EuMasc);\n    }\n\n    /* cast voided pointer into pointer to struct norm_parm */\n    y = - p.alpha * x * p.sum_failure - sum - x*x/(2*p.sigma_mu); // Prior is the same currently for intercepts and fixed effects\n    return y;\n};\n\n\n/* Function for the log density of some \"fixed\" covariate effect */\ninline double gamma_dens(double x, void *norm_data)\n/* We are sampling gamma (denoted by x here) */\n{\n\tdouble y;\n\t/* In C++ we need to do a static cast for the void data */\n\tpars p = *(static_cast<pars *>(norm_data));\n\n\t/* cast voided pointer into pointer to struct norm_parm */\n\ty = - p.alpha * x * p.sum_failure - (((p.epsilon -  p.X_j * x)* p.alpha).array() - EuMasc).exp().sum() - x*x/(2*p.sigma_mu); // Prior is the same currently for intercepts and fixed effects\n\treturn y;\n};\n\n/* Function for the log density of alpha */\ninline double alpha_dens(double x, void *norm_data)\n/* We are sampling alpha (denoted by x here) */\n{\n\tdouble y;\n\n\t/* In C++ we need to do a static cast for the void data */\n\tpars_alpha p = *(static_cast<pars_alpha *>(norm_data));\n\ty = (p.alpha_0 + p.d - 1) * log(x) + x * ((p.epsilon.array() * p.failure_vector.array()).sum() - p.kappa_0) -\n        ((p.epsilon * x).array() - EuMasc).exp().sum() ;\n\treturn y;\n};\n\n/* Sparse version for function for the log density of beta: uses mixture component from the structure norm_data */\ninline double beta_dens(double x, void *norm_data)\n/* We are sampling beta (denoted by x here) */\n{\n\tdouble y;\n\t/* In C++ we need to do a static cast for the void data */\n\tpars_beta_sparse p = *(static_cast<pars_beta_sparse *>(norm_data));\n\n\ty = -p.alpha * x * p.sum_failure -\n        exp(p.alpha*x*p.mean_sd_ratio)* (p.vi_0 + p.vi_1 * exp(-p.alpha*x/p.sd) + p.vi_2 * exp(-2*p.alpha*x/p.sd))\n        -x * x / (2 * p.mixture_value * p.sigmaG) ;\n\treturn y;\n};\n\n\n\n//The function for integration\ninline double gh_integrand_adaptive(double s,double alpha, double dj, double sqrt_2Ck_sigmaG,\n                                    double vi_sum, double vi_2, double vi_1, double vi_0, double mean, double sd, double mean_sd_ratio){\n\t//vi is a vector of exp(vi)\n\tdouble temp = -alpha *s*dj*sqrt_2Ck_sigmaG +\n        vi_sum - exp(alpha*mean_sd_ratio*s*sqrt_2Ck_sigmaG) *\n        (vi_0 + vi_1 * exp(-alpha * s*sqrt_2Ck_sigmaG/sd) + vi_2* exp(-2 * alpha * s*sqrt_2Ck_sigmaG/sd))\n        -pow(s,2);\n\treturn exp(temp);\n}\n\n\n//Calculate the value of the integral using Adaptive Gauss-Hermite quadrature\n//Let's assume that mu is always 0 for speed\ndouble BayesW::gauss_hermite_adaptive_integral(double C_k, double sigma, string n, double vi_sum, double vi_2, double vi_1, double vi_0,\n                                               double mean, double sd, double mean_sd_ratio){\n\n\tdouble temp = 0;\n\tdouble sqrt_2ck_sigma = sqrt(2* C_k * used_data_beta.sigmaG);\n\n\tif(n == \"3\"){\n\t\tdouble x1,x2;\n\t\tdouble w1,w2,w3;\n\n\t\tx1 = 1.2247448713916;\n\t\tx2 = -x1;\n\n\t\tw1 = 1.3239311752136;\n\t\tw2 = w1;\n\n\t\tw3 = 1.1816359006037;\n\n\t\tx1 = sigma*x1;\n\t\tx2 = sigma*x2;\n\n\t\ttemp = \tw1 * gh_integrand_adaptive(x1,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,\n                                           vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w2 * gh_integrand_adaptive(x2,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,\n                                       vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w3;\n\t}\n\t// n=5\n\telse if(n == \"5\"){\n\t\tdouble x1,x2,x3,x4;//x5;\n\t\tdouble w1,w2,w3,w4,w5; //These are adjusted weights\n\n\t\tx1 = 2.0201828704561;\n\t\tx2 = -x1;\n\t\tw1 = 1.181488625536;\n\t\tw2 = w1;\n\n\t\tx3 = 0.95857246461382;\n\t\tx4 = -x3;\n\t\tw3 = 0.98658099675143;\n\t\tw4 = w3;\n\n\t\t//\tx5 = 0.0;\n\t\tw5 = 0.94530872048294;\n\n\t\tx1 = sigma*x1;\n\t\tx2 = sigma*x2;\n\t\tx3 = sigma*x3;\n\t\tx4 = sigma*x4;\n\t\t//x5 = sigma*x5;\n\n\t\ttemp = \tw1 * gh_integrand_adaptive(x1,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,\n                                           vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w2 * gh_integrand_adaptive(x2,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,\n                                       vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w3 * gh_integrand_adaptive(x3,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,\n                                       vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w4 * gh_integrand_adaptive(x4,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,\n                                       vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w5 ;//* gh_integrand_adaptive(x5,p.alpha,p.sum_failure,sqrt_2ck_sigma,vi,p.X_j); // This part is just 1\n\t}else if(n == \"7\"){\n\t\tdouble x1,x2,x3,x4,x5,x6;\n\t\tdouble w1,w2,w3,w4,w5,w6,w7; //These are adjusted weights\n\n\t\tx1 = 2.6519613568352;\n\t\tx2 = -x1;\n\t\tw1 = 1.1013307296103;\n\t\tw2 = w1;\n\n\t\tx3 = 1.6735516287675;\n\t\tx4 = -x3;\n\t\tw3 = 0.8971846002252;\n\t\tw4 = w3;\n\n\t\tx5 = 0.81628788285897;\n\t\tx6 = -x5;\n\t\tw5 = 0.8286873032836;\n\t\tw6 = w5;\n\n\t\tw7 = 0.81026461755681;\n\n\t\tx1 = sigma*x1;\n\t\tx2 = sigma*x2;\n\t\tx3 = sigma*x3;\n\t\tx4 = sigma*x4;\n\t\tx5 = sigma*x5;\n\t\tx6 = sigma*x6;\n\n\t\ttemp = \tw1 * gh_integrand_adaptive(x1,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,\n                                           vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w2 * gh_integrand_adaptive(x2,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,\n                                       vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w3 * gh_integrand_adaptive(x3,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,\n                                       vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w4 * gh_integrand_adaptive(x4,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,\n                                       vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w5 * gh_integrand_adaptive(x5,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,\n                                       vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w6 * gh_integrand_adaptive(x6,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,\n                                       vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w7;\n\t}else if(n == \"9\"){\n\t\tdouble x1,x2,x3,x4,x5,x6,x7,x8,x9;//,x11;\n\t\tdouble w1,w2,w3,w4,w5,w6,w7,w8,w9; //These are adjusted weights\n\n\t\tx1 = 3.1909932017815;\n\t\tx2 = -x1;\n\t\tw1 = 1.0470035809767;\n\t\tw2 = w1;\n\n\t\tx3 = 2.2665805845318;\n\t\tx4 = -x3;\n\t\tw3 = 0.84175270147867;\n\t\tw4 = w3;\n\n\t\tx5 = 1.4685532892167;\n\t\tx6 = -x5;\n\t\tw5 = 0.7646081250946;\n\t\tw6 = w5;\n\n\t\tx7 = 0.72355101875284;\n\t\tx8 = -x7;\n\t\tw7 = 0.73030245274509;\n\t\tw8 = w7;\n\n        //\tx9 = 0;\n\t\tw9 = 0.72023521560605;\n\n\t\tx1 = sigma*x1;\n\t\tx2 = sigma*x2;\n\t\tx3 = sigma*x3;\n\t\tx4 = sigma*x4;\n\t\tx5 = sigma*x5;\n\t\tx6 = sigma*x6;\n\t\tx7 = sigma*x7;\n\t\tx8 = sigma*x8;\n\n\t\ttemp = \tw1 * gh_integrand_adaptive(x1,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w2 * gh_integrand_adaptive(x2,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w3 * gh_integrand_adaptive(x3,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w4 * gh_integrand_adaptive(x4,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w5 * gh_integrand_adaptive(x5,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w6 * gh_integrand_adaptive(x6,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w7 * gh_integrand_adaptive(x7,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w8 * gh_integrand_adaptive(x8,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w9 ;//* gh_integrand_adaptive(x9,p.alpha,p.sum_failure,sqrt_2ck_sigma,vi,p.X_j);\n\t}else if(n == \"11\"){\n\t\tdouble x1,x2,x3,x4,x5,x6,x7,x8,x9,x10;//,x11;\n\t\tdouble w1,w2,w3,w4,w5,w6,w7,w8,w9,w10,w11; //These are adjusted weights\n\n\t\tx1 = 3.6684708465596;\n\t\tx2 = -x1;\n\t\tw1 = 1.0065267861724;\n\t\tw2 = w1;\n\n\t\tx3 = 2.7832900997817;\n\t\tx4 = -x3;\n\t\tw3 = 0.802516868851;\n\t\tw4 = w3;\n\n\t\tx5 = 2.0259480158258;\n\t\tx6 = -x3;\n\t\tw5 = 0.721953624728;\n\t\tw6 = w5;\n\n\t\tx7 = 1.3265570844949;\n\t\tx8 = -x7;\n\t\tw7 = 0.6812118810667;\n\t\tw8 = w7;\n\n\t\tx9 = 0.6568095668821;\n\t\tx10 = -x9;\n\t\tw9 = 0.66096041944096;\n\t\tw10 = w9;\n\n\t\t//x11 = 0.0;\n\t\tw11 = 0.65475928691459;\n\n\t\tx1 = sigma*x1;\n\t\tx2 = sigma*x2;\n\t\tx3 = sigma*x3;\n\t\tx4 = sigma*x4;\n\t\tx5 = sigma*x5;\n\t\tx6 = sigma*x6;\n\t\tx7 = sigma*x7;\n\t\tx8 = sigma*x8;\n\t\tx9 = sigma*x9;\n\t\tx10 = sigma*x10;\n\t\t//\tx11 = sigma*x11;\n\n\t\ttemp = \tw1 * gh_integrand_adaptive(x1,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w2 * gh_integrand_adaptive(x2,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w3 * gh_integrand_adaptive(x3,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w4 * gh_integrand_adaptive(x4,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w5 * gh_integrand_adaptive(x5,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w6 * gh_integrand_adaptive(x6,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w7 * gh_integrand_adaptive(x7,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w8 * gh_integrand_adaptive(x8,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w9 * gh_integrand_adaptive(x9,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w10 * gh_integrand_adaptive(x10,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w11 ;//* gh_integrand_adaptive(x11,p.alpha,p.sum_failure,sqrt_2ck_sigma,vi,p.X_j);\n\t}else if(n == \"13\"){\n\t\tdouble x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12;\n\t\tdouble w1,w2,w3,w4,w5,w6,w7,w8,w9,w10,w11,w12,w13; //These are adjusted weights\n\n\t\tx1 = 4.1013375961786;\n\t\tx2 = -x1;\n\t\tw1 = 0.97458039564;\n\t\tw2 = w1;\n\n\t\tx3 = 3.2466089783724;\n\t\tx4 = -x3;\n\t\tw3 = 0.7725808233517;\n\t\tw4 = w3;\n\n\t\tx5 = 2.5197356856782;\n\t\tx6 = -x3;\n\t\tw5 = 0.6906180348378;\n\t\tw6 = w5;\n\n\t\tx7 = 1.8531076516015;\n\t\tx8 = -x7;\n\t\tw7 = 0.6467594633158;\n\t\tw8 = w7;\n\n\t\tx9 = 1.2200550365908;\n\t\tx10 = -x9;\n\t\tw9 = 0.6217160552868;\n\t\tw10 = w9;\n\n\t\tx11 = 0.60576387917106;\n\t\tx12 = -x11;\n\t\tw11 = 0.60852958370332;\n\t\tw12 = w11;\n\n\t\t//x13 = 0.0;\n\t\tw13 = 0.60439318792116;\n\n\t\tx1 = sigma*x1;\n\t\tx2 = sigma*x2;\n\t\tx3 = sigma*x3;\n\t\tx4 = sigma*x4;\n\t\tx5 = sigma*x5;\n\t\tx6 = sigma*x6;\n\t\tx7 = sigma*x7;\n\t\tx8 = sigma*x8;\n\t\tx9 = sigma*x9;\n\t\tx10 = sigma*x10;\n\t\tx11 = sigma*x11;\n\t\tx12 = sigma*x12;\n\n\n\t\ttemp = \tw1 * gh_integrand_adaptive(x1,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w2 * gh_integrand_adaptive(x2,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w3 * gh_integrand_adaptive(x3,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w4 * gh_integrand_adaptive(x4,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w5 * gh_integrand_adaptive(x5,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w6 * gh_integrand_adaptive(x6,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w7 * gh_integrand_adaptive(x7,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w8 * gh_integrand_adaptive(x8,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w9 * gh_integrand_adaptive(x9,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w10 * gh_integrand_adaptive(x10,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w11 * gh_integrand_adaptive(x11,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w12 * gh_integrand_adaptive(x12,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w13 ;//* gh_integrand_adaptive(x11,p.alpha,p.sum_failure,sqrt_2ck_sigma,vi,p.X_j);\n\t}else if(n == \"15\"){\n\t\tdouble x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12,x13,x14;//,x11;\n\t\tdouble w1,w2,w3,w4,w5,w6,w7,w8,w9,w10,w11,w12,w13,w14,w15; //These are adjusted weights\n\n\t\tx1 = 4.4999907073094;\n\t\tx2 = -x1;\n\t\tw1 = 0.94836897082761;\n\t\tw2 = w1;\n\n\t\tx3 = 3.6699503734045;\n\t\tx4 = -x3;\n\t\tw3 = 0.7486073660169;\n\t\tw4 = w3;\n\n\t\tx5 = 2.9671669279056;\n\t\tx6 = -x3;\n\t\tw5 = 0.666166005109;\n\t\tw6 = w5;\n\n\t\tx7 = 2.3257324861739;\n\t\tx8 = -x7;\n\t\tw7 = 0.620662603527;\n\t\tw8 = w7;\n\n\t\tx9 = 1.7199925751865;\n\t\tx10 = -x9;\n\t\tw9 = 0.5930274497642;\n\t\tw10 = w9;\n\n\t\tx11 = 1.1361155852109;\n\t\tx12 = -x11;\n\t\tw11 = 0.5761933502835;\n\t\tw12 = w11;\n\n\t\tx13 = 0.5650695832556;\n\t\tx14 = -x13;\n\t\tw13 = 0.5670211534466;\n\t\tw14 = w13;\n\n\t\t//x15 = 0.0;\n\t\tw15 = 0.56410030872642;\n\n\t\tx1 = sigma*x1;\n\t\tx2 = sigma*x2;\n\t\tx3 = sigma*x3;\n\t\tx4 = sigma*x4;\n\t\tx5 = sigma*x5;\n\t\tx6 = sigma*x6;\n\t\tx7 = sigma*x7;\n\t\tx8 = sigma*x8;\n\t\tx9 = sigma*x9;\n\t\tx10 = sigma*x10;\n\t\tx11 = sigma*x11;\n\t\tx12 = sigma*x12;\n\t\tx13 = sigma*x13;\n\t\tx14 = sigma*x14;\n\n\t\ttemp = \tw1 * gh_integrand_adaptive(x1,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w2 * gh_integrand_adaptive(x2,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w3 * gh_integrand_adaptive(x3,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w4 * gh_integrand_adaptive(x4,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w5 * gh_integrand_adaptive(x5,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w6 * gh_integrand_adaptive(x6,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w7 * gh_integrand_adaptive(x7,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w8 * gh_integrand_adaptive(x8,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w9 * gh_integrand_adaptive(x9,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w10 * gh_integrand_adaptive(x10,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w11 * gh_integrand_adaptive(x11,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w12 * gh_integrand_adaptive(x12,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w13 * gh_integrand_adaptive(x13,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w14 * gh_integrand_adaptive(x14,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w15 ;//* gh_integrand_adaptive(x11,p.alpha,p.sum_failure,sqrt_2ck_sigma,vi,p.X_j);\n\t}else if(n == \"17\"){\n        double x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12,x13,x14,x15,x16;//,x17;\n        double w1,w2,w3,w4,w5,w6,w7,w8,w9,w10,w11,w12,w13,w14,w15,w16,w17; //These are adjusted weights\n\n        x1 = 4.8713451936744;\n        x2 = -x1;\n        w1 = 0.92625413999;\n        w2 = w1;\n\n        x3 = 4.0619466758755;\n        x4 = -x3;\n        w3 = 0.728748370587;\n        w4 = w3;\n\n        x5 = 3.3789320911415;\n        x6 = -x3;\n        w5 = 0.6462917002129;\n        w6 = w5;\n\n        x7 = 2.7577629157039;\n        x8 = -x7;\n        w7 = 0.5998927326678;\n        w8 = w7;\n\n        x9 = 2.1735028266666;\n        x10 = -x9;\n        w9 = 0.5707392941245;\n        w10 = w9;\n\n        x11 = 1.6129243142212;\n        x12 = -x11;\n        w11 = 0.55177735307817;\n        w12 = w11;\n\n        x13 = 1.0676487257435;\n        x14 = -x13;\n        w13 = 0.5397631139085;\n        w14 = w13;\n\n        x15 = 0.53163300134266;\n        x16 = -x15;\n        w15 = 0.5330706545736;\n        w16 = w15;\n\n        w17 = 0.53091793762486;\n\n        x1 = sigma*x1;\n        x2 = sigma*x2;\n        x3 = sigma*x3;\n        x4 = sigma*x4;\n        x5 = sigma*x5;\n        x6 = sigma*x6;\n        x7 = sigma*x7;\n        x8 = sigma*x8;\n        x9 = sigma*x9;\n        x10 = sigma*x10;\n        x11 = sigma*x11;\n        x12 = sigma*x12;\n        x13 = sigma*x13;\n        x14 = sigma*x14;\n        x15 = sigma*x15;\n        x16 = sigma*x16;\n\n        temp =  w1 * gh_integrand_adaptive(x1,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w2 * gh_integrand_adaptive(x2,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w3 * gh_integrand_adaptive(x3,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w4 * gh_integrand_adaptive(x4,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w5 * gh_integrand_adaptive(x5,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w6 * gh_integrand_adaptive(x6,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w7 * gh_integrand_adaptive(x7,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w8 * gh_integrand_adaptive(x8,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w9 * gh_integrand_adaptive(x9,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w10 * gh_integrand_adaptive(x10,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w11 * gh_integrand_adaptive(x11,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w12 * gh_integrand_adaptive(x12,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w13 * gh_integrand_adaptive(x13,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w14 * gh_integrand_adaptive(x14,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w15 * gh_integrand_adaptive(x15,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w16 * gh_integrand_adaptive(x16,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w17 ;//* gh_integrand_adaptive(0,...)= 1\n    }else if(n == \"25\"){\n        double x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12,x13,x14,x15,x16,x17,x18,x19,x20,x21,x22,x23,x24;\n        double w1,w2,w3,w4,w5,w6,w7,w8,w9,w10,w11,w12,w13,w14,w15,w16,w17,w18,w19,w20,w21,w22,w23,w24,w25; //These are adjusted weights\n\n        x1 = 6.1642724340525;\n        x2 = -x1;\n        w1 = 0.862401988731;\n        w2 = w1;\n\n        x3 = 5.41363635528;\n        x4 = -x3;\n        w3 = 0.673022290222;\n        w4 = w3;\n\n        x5 = 4.7853203673522;\n        x6 = -x3;\n        w5 = 0.5920816930865;\n        w6 = w5;\n        x7 = 4.2186094443866;\n        x8 = -x7;\n        w7 = 0.5449177721944;\n        w8 = w7;\n\n        x9 = 3.690282876998;\n        x10 = -x9;\n        w9 = 0.513655789775;\n        w10 = w9;\n\n        x11 = 3.1882949244251;\n        x12 = -x11;\n        w11 = 0.4915068818876;\n        w12 = w11;\n\n        x13 = 2.705320237173;\n        x14 = -x13;\n        w13 = 0.4752497380022;\n        w14 = w13;\n\n        x15 = 2.2364201302673;\n        x16 = -x15;\n        w15 = 0.463141046575;\n        w16 = w15;\n\n        x17 = 1.7780011243372;\n        x18 = -x17;\n        w17 = 0.45415588552762;\n        w18 = w17;\n\n        x19 = 1.3272807020731;\n        x20 = -x19;\n        w19 = 0.4476612565874;\n        w20 = w19;\n\n        x21 = 0.88198275621382;\n        x22 = -x21;\n        w21 = 0.44325918925185;\n        w22 = w21;\n\n        x23 = 0.44014729864531;\n        x24 = -x23;\n        w23 = 0.44070582891206;\n        w24 = w23;\n        //x25 = 0.0;\n        w25 = 0.43986872216949;\n\n        x1 = sigma*x1;\n        x2 = sigma*x2;\n        x3 = sigma*x3;\n        x4 = sigma*x4;\n        x5 = sigma*x5;\n        x6 = sigma*x6;\n        x7 = sigma*x7;\n        x8 = sigma*x8;\n        x9 = sigma*x9;\n        x10 = sigma*x10;\n        x11 = sigma*x11;\n        x12 = sigma*x12;\n        x13 = sigma*x13;\n        x14 = sigma*x14;\n        x15 = sigma*x15;\n        x16 = sigma*x16;\n        x17 = sigma*x17;\n        x18 = sigma*x18;\n        x19 = sigma*x19;\n        x20 = sigma*x20;\n        x21 = sigma*x21;\n        x22 = sigma*x22;\n        x23 = sigma*x23;\n        x24 = sigma*x24;\n\n        temp =  w1 * gh_integrand_adaptive(x1,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w2 * gh_integrand_adaptive(x2,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w3 * gh_integrand_adaptive(x3,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w4 * gh_integrand_adaptive(x4,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w5 * gh_integrand_adaptive(x5,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w6 * gh_integrand_adaptive(x6,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w7 * gh_integrand_adaptive(x7,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w8 * gh_integrand_adaptive(x8,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w9 * gh_integrand_adaptive(x9,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w10 * gh_integrand_adaptive(x10,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w11 * gh_integrand_adaptive(x11,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w12 * gh_integrand_adaptive(x12,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w13 * gh_integrand_adaptive(x13,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w14 * gh_integrand_adaptive(x14,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w15 * gh_integrand_adaptive(x15,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w16 * gh_integrand_adaptive(x16,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w17 * gh_integrand_adaptive(x17,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w18 * gh_integrand_adaptive(x18,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w19 * gh_integrand_adaptive(x19,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w20 * gh_integrand_adaptive(x20,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w21 * gh_integrand_adaptive(x21,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w22 * gh_integrand_adaptive(x22,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w23 * gh_integrand_adaptive(x23,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w24 * gh_integrand_adaptive(x24,used_data_beta.alpha,used_data_beta.sum_failure,sqrt_2ck_sigma,vi_sum, vi_2, vi_1, vi_0, mean, sd, mean_sd_ratio)+\n            w25 ;//* gh_integrand_adaptive(0,...)= 1\n    }else{\n\t\tcout << \"Possible number of quad_points = 3,5,7,9,11,13,15,17,25\" << endl;\n\t\texit(1);\n\t}\n\n\treturn sigma*temp;\n}\n\n\n//Pass the vector post_marginals of marginal likelihoods by reference\nvoid BayesW::marginal_likelihood_vec_calc(VectorXd prior_prob, VectorXd &post_marginals, string n,\n                                          double vi_sum, double vi_2, double vi_1, double vi_0, double mean, double sd, double mean_sd_ratio, unsigned int group_index){\n\tdouble exp_sum = (vi_1 * (1 - 2 * mean) + 4 * (1-mean) * vi_2 + vi_sum * mean * mean) /(sd*sd) ;\n\n\tfor(int i=0; i < km1; i++){\n\t\t//Calculate the sigma for the adaptive G-H\n\t\tdouble sigma = 1.0/sqrt(1 + used_data_beta.alpha * used_data_beta.alpha * used_data_beta.sigmaG * cVa(group_index,i) * exp_sum);\n\t\tpost_marginals(i+1) = prior_prob(i+1) * gauss_hermite_adaptive_integral(cVa(group_index,i), sigma, n, vi_sum,  vi_2,  vi_1,  vi_0,  //(i+1) because 0th is already pre-calculated\n                                                                                mean, sd, mean_sd_ratio);\n\t}\n}\n\nvoid BayesW::init(unsigned int individualCount, unsigned int Mtot, unsigned int fixedCount)\n{\n\t// Read the failure indicator vector\n\tif(individualCount != (data.fail).size()){\n\t\tcout << \"Number of phenotypes \"<< individualCount << \" was different from the number of failures \" << (data.fail).size() << endl;\n\t\texit(1);\n\t}\n\n\t// Linear model variables\n\tgamma = VectorXd(fixedCount);\n\n\t//phenotype vector\n\ty = VectorXd();\n\t//residual vector\n\tepsilon = VectorXd();\n\n\t//vi vector\n\tvi = VectorXd(individualCount);\n\n\t// Resize the vectors in the structure\n\tused_data.X_j = VectorXd(individualCount);\n\tused_data.epsilon.resize(individualCount);\n\tused_data_alpha.epsilon.resize(individualCount);\n\n\t//Init the group variables\n\t data.groups.resize(Mtot);\n\t data.groups.setZero();\n\t const int Kt   = cva.size() + 1;\t\t\t//Temporary K\n\t const int Ktm1 = Kt - 1; \n\n    \t data.mS.resize(Mtot, Kt);\n\n    VectorXd cva_new(Kt);\n    cva_new << 0 , cva ; // Add the 0th mixture \n\n\t for (int i=0; i<Mtot; i++)\n\t   data.mS.row(i) = cva_new;\n\t\n\t if (opt.groupIndexFile != \"\" && opt.groupMixtureFile != \"\") {\n\t   data.readGroupFile(opt.groupIndexFile);\n\t   data.readmSFile(opt.groupMixtureFile);\n\t }\n\n\t printf(\"numGroups = %d, data.groups.size() = %lu, Mtot = %d\\n\", data.numGroups, data.groups.size(), Mtot);\n\n         numGroups = data.numGroups;\n    \t K  = int(data.mS.cols());  //Mixtures + 0th component. \n  \t     km1 = K - 1;\t\t    //Just mixtures\n         sigmaG.resize(numGroups);\n         sigmaG.setZero();\n\n\t assert(data.groups.size() == Mtot);\n\t groups     = data.groups;\n\t cVa.resize(numGroups, km1);    // component-specific variance\n\n\t //Populate cVa. We store only km1 values for mixtures\n    \t for (int i=0; i < numGroups; i++) {\n        \tcVa.row(i) = data.mS.row(i).segment(1,km1);\n    \t }\n\t\n        // Component variables\n        pi_L.resize(numGroups,K);                        // prior mixture probabilities\n        marginal_likelihoods = VectorXd(K);  // likelihood for each mixture component\n\n        // Vector to store the 0th component of the marginal likelihood for each group  \n        marginal_likelihood_0 = VectorXd(numGroups);\n\n\t//set priors for pi parameters\n\t//Give only the first mixture some initial probability of entering\n\tpi_L.setConstant(1.0/Mtot);\n\tpi_L.col(0).array() = 0.99;\n\tpi_L.col(1).array() = 1 - pi_L.col(0).array() - (km1 - 1)/Mtot;\n\n\tmarginal_likelihoods.setOnes();   //Initialize with just ones\n    marginal_likelihood_0.setOnes();\n\n\tBeta.setZero();\n\tgamma.setZero();\n\n\t//initialize epsilon vector as the phenotype vector\n\ty = data.y.cast<double>().array();\n\n\tepsilon = y;\n\tmu = y.mean();       // mean or intercept\n\t// Initialize the variables in structures\n\t//Save variance classes\n\n\t//Store the vector of failures only in the structure used for sampling alpha\n\tused_data_alpha.failure_vector = data.fail.cast<double>();\n\n\tdouble denominator = (6 * ((y.array() - mu).square()).sum()/(y.size()-1));\n\tused_data.alpha = PI/sqrt(denominator);    // The shape parameter initial value\n\tused_data_beta.alpha = PI/sqrt(denominator);    // The shape parameter initial value\n\n\n\tfor(int i=0; i<(y.size()); ++i){\n\t\t(used_data.epsilon)[i] = y[i] - mu ; // Initially, all the BETA elements are set to 0, XBeta = 0\n\t\tepsilon[i] = y[i] - mu;\n\t}\n\t// Use h2 = 0.5 for the inital estimate// divided  by the number of groups\n\tsigmaG.array() = PI_squared/ (6 * pow(used_data_beta.alpha,2))/numGroups;\n\n    //Restart variables\n    epsilon_restart.resize(individualCount);\n    epsilon_restart.setZero();\n\n    gamma_restart.resize(fixedCount);\n    gamma_restart.setZero();\n\n    xI_restart.resize(fixedCount);\n\n\t/* Prior value selection for the variables */\n\t/* At the moment we set them to be weakly informative (in .hpp file) */\n\t/* alpha */\n\tused_data_alpha.alpha_0 = alpha_0;\n\tused_data_alpha.kappa_0 = kappa_0;\n\t/* mu */\n\tused_data.sigma_mu = sigma_mu;\n\t/* sigmaG */\n\tused_data.alpha_sigma = alpha_sigma;\n\tused_data.beta_sigma = beta_sigma;\n\n\t// Save the number of events\n\tused_data.d = used_data_alpha.failure_vector.array().sum();\n\tused_data_alpha.d = used_data.d;\n}\n\n\nvoid BayesW::init_from_restart(const int K, const uint M, const uint  Mtot, const uint Ntot, const uint fixtot,\n                               const int* MrankS, const int* MrankL, const bool use_xfiles_in_restart) {\n    //Use the regular bW initialisation\n    init(Ntot,Mtot, fixtot);    \n\n    //TODO @@@DT change this function to read the csv file from restart in groups \n    data.read_mcmc_output_csv_file_bW(opt.mcmcOut, opt.thin, opt.save, K, mu, sigmaG, used_data.alpha, pi_L,\n                                      iteration_to_restart_from, first_thinned_iteration, first_saved_iteration);\n    \n    // Set new random seed for the ARS in case of restart. In long run we should use dist object for simulating from uniform distribution\n    srand(opt.seed + iteration_to_restart_from);\n\n    //Carry the values to the other structures\n    used_data_beta.alpha = used_data.alpha;\n\n    MPI_Barrier(MPI_COMM_WORLD);\n\n    data.read_mcmc_output_bet_file(opt.mcmcOut,\n                                   Mtot, iteration_to_restart_from, first_thinned_iteration, opt.thin,\n                                   MrankS, MrankL, use_xfiles_in_restart,\n                                   Beta);\n\n    data.read_mcmc_output_cpn_file(opt.mcmcOut,\n                                   Mtot, iteration_to_restart_from, first_thinned_iteration, opt.thin,\n                                   MrankS, MrankL, use_xfiles_in_restart,\n                                   components);\n\n    data.read_mcmc_output_eps_file(opt.mcmcOut, Ntot, iteration_to_restart_from,\n                                   epsilon_restart);\n\n    data.read_mcmc_output_idx_file(opt.mcmcOut, \"mrk\", M, iteration_to_restart_from,\n                                   markerI_restart);\n\n    if (opt.covariates) {\n        data.read_mcmc_output_gam_file_bW(opt.mcmcOut, opt.save, fixtot, gamma_restart);\n\n        data.read_mcmc_output_idx_file_bW(opt.mcmcOut, \"xiv\", fixtot, iteration_to_restart_from, xI_restart);\n    }\n\n    // Adjust starting iteration number.\n    iteration_start = iteration_to_restart_from + 1;\n             \n    MPI_Barrier(MPI_COMM_WORLD);\n}\n    \n\n\n//EO: MPI GIBBS\n//-------------\nint BayesW::runMpiGibbs_bW() {\n\n    //#ifdef _OPENMP\n    //#warning \"using OpenMP\"\n    //#endif\n\n\tconst unsigned int numFixedEffects(data.numFixedEffects);\n\n    char   buff[LENBUF];\n    char   buff_gamma[LENBUF_gamma]; \n    int    nranks, rank, name_len, result;\n    double dalloc = 0.0;\n    MPI_Comm_size(MPI_COMM_WORLD, &nranks);\n    MPI_Comm_rank(MPI_COMM_WORLD, &rank);\n\n    MPI_File   outfh, betfh, epsfh, gamfh, cpnfh, mrkfh, xivfh; \n    MPI_File   xbetfh, xcpnfh;\n    MPI_Status status;\n    MPI_Info   info;\n\n    // Set up processing options\n    // -------------------------\n    if (rank < 0) {\n        opt.printBanner();\n        opt.printProcessingOptions();\n    }\n\n    // Set Ntot and Mtot\n    // -----------------\n    uint Ntot = set_Ntot(rank);\n    const uint Mtot = set_Mtot(rank);\n    //Reset the dist\n    dist.reset_rng((uint)(opt.seed + rank*1000));\n\n\t\n    if (rank == 0)\n        printf(\"INFO   : Full dataset includes Mtot=%d markers and Ntot=%d individuals.\\n\", Mtot, Ntot);\n\n\n    // Define global marker indexing\n    // -----------------------------\n    int MrankS[nranks], MrankL[nranks], lmin = 1E9, lmax = 0;\n    mpi_assign_blocks_to_tasks(data.numBlocks, data.blocksStarts, data.blocksEnds, Mtot, nranks, rank, MrankS, MrankL, lmin, lmax);\n\n    uint M = MrankL[rank];\n    if (rank % 10 == 0) {\n        printf(\"INFO   : rank %4d will handle a block of %6d markers starting at %d\\n\", rank, MrankL[rank], MrankS[rank]);\n    }\n\n\n    // EO: Define blocks of individuals (for dumping epsilon)\n    // Note: hack the marker block definition function to this end\n    // Note: at this stage Ntot is not yet adjusted for missing phenotypes,\n    //       hence the correction in the call\n    // --------------------------------------------------------------------\n    int IrankS[nranks], IrankL[nranks];\n    mpi_define_blocks_of_markers(Ntot - data.numNAs, IrankS, IrankL, nranks);\n\n    Beta.resize(M);\n    Beta.setZero();\n\n    components.resize(M);\n    components.setZero();\n\n    std::vector<int>    markerI;\n\n    markerI_restart.resize(M);\n    std::fill(markerI_restart.begin(), markerI_restart.end(), 0);\n\n    std::vector<int>     mark2sync;\n    std::vector<double>  dbet2sync;\n\n    dalloc +=     M * sizeof(int)    / 1E9; // for components\n    dalloc += 2 * M * sizeof(double) / 1E9; // for Beta and Acum\n\n    // Adapt the --thin and --save options such that --save >= --thin and --save%--thin = 0\n    // ------------------------------------------------------------------------------------\n    if (opt.save < opt.thin) {\n        opt.save = opt.thin;\n        if (rank == 0) printf(\"WARNING: opt.save was lower that opt.thin ; opt.save reset to opt.thin (%d)\\n\", opt.thin);\n    }\n    if (opt.save%opt.thin != 0) {\n        if (rank == 0) printf(\"WARNING: opt.save (= %d) was not a multiple of opt.thin (= %d)\\n\", opt.save, opt.thin);\n        opt.save = int(opt.save/opt.thin) * opt.thin;\n        if (rank == 0) printf(\"         opt.save reset to %d, the closest multiple of opt.thin (%d)\\n\", opt.save, opt.thin);\n    }\n\n\n    // Invariant initializations (from scratch / from restart)\n    // -------------------------------------------------------\n    string lstfp = opt.mcmcOut + \".lst\";\n    string outfp = opt.mcmcOut + \".csv\";\n    string betfp = opt.mcmcOut + \".bet\";\n    string xbetfp = opt.mcmcOut + \".xbet\";\n    string cpnfp = opt.mcmcOut + \".cpn\";\n    string xcpnfp = opt.mcmcOut + \".xcpn\";\n    string gamfp = opt.mcmcOut + \".gam\";\n    string xivfp = opt.mcmcOut + \".xiv\";\n    string rngfp = opt.mcmcOut + \".rng.\" + std::to_string(rank);\n    string mrkfp = opt.mcmcOut + \".mrk.\" + std::to_string(rank);\n    string epsfp = opt.mcmcOut + \".eps.\" + std::to_string(rank);\n\n    if(opt.restart){\n        init_from_restart(K, M, Mtot, Ntot - data.numNAs, numFixedEffects, MrankS, MrankL, opt.useXfilesInRestart);\n        if (rank == 0)\n            data.print_restart_banner(opt.mcmcOut.c_str(),  iteration_to_restart_from, iteration_start);\n\n        dist.read_rng_state_from_file(rngfp);\n\n        // Rename output files so that we do not erase from failed job!\n        //EO: add a function, to update both Nam and Dir!\n        opt.mcmcOutNam += \"_rs\";\n        opt.mcmcOut = opt.mcmcOutDir + \"/\" + opt.mcmcOutNam;\n        lstfp  = opt.mcmcOut + \".lst\";\n        outfp  = opt.mcmcOut + \".csv\";\n        betfp  = opt.mcmcOut + \".bet\";\n        xbetfp = opt.mcmcOut + \".xbet\"; // Last saved iteration of bet; .bet has full history\n        cpnfp  = opt.mcmcOut + \".cpn\";\n        xcpnfp = opt.mcmcOut + \".xcpn\"; // Idem\n        rngfp  = opt.mcmcOut + \".rng.\" + std::to_string(rank);\n        mrkfp  = opt.mcmcOut + \".mrk.\" + std::to_string(rank);\n        epsfp  = opt.mcmcOut + \".eps.\" + std::to_string(rank);\n        gamfp  = opt.mcmcOut + \".gam\";\n        xivfp  = opt.mcmcOut + \".xiv\";\n\n    }else{\n        // Set new random seed for the ARS in case of restart. In long run we should use dist object for simulating from uniform distribution\n        srand(opt.seed);\n        init(Ntot - data.numNAs, Mtot,numFixedEffects);\n    }\n    cass.resize(numGroups,K); //rows are groups columns are mixtures\n    MatrixXi sum_cass(numGroups,K);  // To store the sum of cass elements over all ranks\n\n    // Define sumSigmaG for creating \"safe limit\"\n    double sumSigmaG = sigmaG.sum();\n\n   // Build global repartition of markers over the groups\n    VectorXi MtotGrp(numGroups);\n    MtotGrp.setZero();\n    for (int i=0; i < Mtot; i++) {\n        MtotGrp[groups[i]] += 1;\n    }\n    VectorXi m0(numGroups); // non-zero elements per group\n\n    std::vector<unsigned int> xI(data.X.cols());\n    std::iota(xI.begin(), xI.end(), 0);\n    xI_restart.resize(data.X.cols());\n \n    //    dist.reset_rng((uint)(opt.seed + rank*1000));\n\n    // Build a list of the files to tar\n    // --------------------------------\n    MPI_Barrier(MPI_COMM_WORLD);\n    ofstream listFile;\n    listFile.open(lstfp);\n    listFile << outfp << \"\\n\";\n    listFile << betfp << \"\\n\";\n    listFile << xbetfp << \"\\n\";\n    listFile << cpnfp << \"\\n\";\n    listFile << xcpnfp << \"\\n\";\n    listFile << gamfp << \"\\n\";\n    listFile << xivfp << \"\\n\";\n    for (int i=0; i<nranks; i++) {\n        listFile << opt.mcmcOut + \".rng.\" + std::to_string(i) << \"\\n\";\n        listFile << opt.mcmcOut + \".mrk.\" + std::to_string(i) << \"\\n\";\n        listFile << opt.mcmcOut + \".eps.\" + std::to_string(i) << \"\\n\";\n    }\n    listFile.close();\n    MPI_Barrier(MPI_COMM_WORLD);\n\n\n    // Delete old files (fp appended with \"_rs\" in case of restart, so that\n    // original files are kept untouched) and create new ones\n    // --------------------------------------------------------------------\n    if (rank == 0) {\n        MPI_File_delete(outfp.c_str(), MPI_INFO_NULL);\n        MPI_File_delete(betfp.c_str(), MPI_INFO_NULL);\n        MPI_File_delete(xbetfp.c_str(), MPI_INFO_NULL);\n        MPI_File_delete(cpnfp.c_str(), MPI_INFO_NULL);\n        MPI_File_delete(xcpnfp.c_str(), MPI_INFO_NULL);\n        MPI_File_delete(gamfp.c_str(), MPI_INFO_NULL);\n        MPI_File_delete(xivfp.c_str(), MPI_INFO_NULL);\n    }\n    MPI_File_delete(epsfp.c_str(), MPI_INFO_NULL);\n    MPI_File_delete(mrkfp.c_str(), MPI_INFO_NULL);\n\n    MPI_Barrier(MPI_COMM_WORLD);\n    \n    check_mpi(MPI_File_open(MPI_COMM_WORLD, outfp.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY | MPI_MODE_EXCL, MPI_INFO_NULL, &outfh), __LINE__, __FILE__);\n    check_mpi(MPI_File_open(MPI_COMM_WORLD, betfp.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY | MPI_MODE_EXCL, MPI_INFO_NULL, &betfh), __LINE__, __FILE__);\n    check_mpi(MPI_File_open(MPI_COMM_WORLD, xbetfp.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY | MPI_MODE_EXCL, MPI_INFO_NULL, &xbetfh), __LINE__, __FILE__);\n    check_mpi(MPI_File_open(MPI_COMM_WORLD, cpnfp.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY | MPI_MODE_EXCL, MPI_INFO_NULL, &cpnfh), __LINE__, __FILE__);\n    check_mpi(MPI_File_open(MPI_COMM_WORLD, xcpnfp.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY | MPI_MODE_EXCL, MPI_INFO_NULL, &xcpnfh), __LINE__, __FILE__);\n    check_mpi(MPI_File_open(MPI_COMM_WORLD,  gamfp.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY | MPI_MODE_EXCL, MPI_INFO_NULL, &gamfh), __LINE__, __FILE__);\n    check_mpi(MPI_File_open(MPI_COMM_WORLD,  xivfp.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY | MPI_MODE_EXCL, MPI_INFO_NULL, &xivfh), __LINE__, __FILE__);\n\n    check_mpi(MPI_File_open(MPI_COMM_SELF,  epsfp.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY | MPI_MODE_EXCL, MPI_INFO_NULL, &epsfh), __LINE__, __FILE__);\n    check_mpi(MPI_File_open(MPI_COMM_SELF,  mrkfp.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY | MPI_MODE_EXCL, MPI_INFO_NULL, &mrkfh), __LINE__, __FILE__);\n\n\n    // First element of the .bet, .cpn and .acu files is the\n    // total number of processed markers\n    // -----------------------------------------------------\n    MPI_Offset offset = 0;\n\n    if (rank == 0) {\n        check_mpi(MPI_File_write_at(betfh,  offset, &Mtot, 1, MPI_UNSIGNED, &status), __LINE__, __FILE__);\n        check_mpi(MPI_File_write_at(xbetfh, offset, &Mtot, 1, MPI_UNSIGNED, &status), __LINE__, __FILE__);\n        check_mpi(MPI_File_write_at(cpnfh,  offset, &Mtot, 1, MPI_UNSIGNED, &status), __LINE__, __FILE__);\n        check_mpi(MPI_File_write_at(xcpnfh, offset, &Mtot, 1, MPI_UNSIGNED, &status), __LINE__, __FILE__);\n        // check_mpi(MPI_File_write_at(acufh, offset, &Mtot, 1, MPI_UNSIGNED, &status), __LINE__, __FILE__);\n    }\n\n    MPI_Barrier(MPI_COMM_WORLD);\n    const auto st2 = std::chrono::high_resolution_clock::now();\n    \n    double tl = -mysecond();\n\n    // Read the data (from sparse representation by default)\n    // -----------------------------------------------------\n    size_t *N1S, *N1L,  *N2S, *N2L,  *NMS, *NML;\n    N1S = (size_t*)_mm_malloc(size_t(M) * sizeof(size_t), 64);  check_malloc(N1S, __LINE__, __FILE__);\n    N1L = (size_t*)_mm_malloc(size_t(M) * sizeof(size_t), 64);  check_malloc(N1L, __LINE__, __FILE__);\n    N2S = (size_t*)_mm_malloc(size_t(M) * sizeof(size_t), 64);  check_malloc(N2S, __LINE__, __FILE__);\n    N2L = (size_t*)_mm_malloc(size_t(M) * sizeof(size_t), 64);  check_malloc(N2L, __LINE__, __FILE__);\n    NMS = (size_t*)_mm_malloc(size_t(M) * sizeof(size_t), 64);  check_malloc(NMS, __LINE__, __FILE__);\n    NML = (size_t*)_mm_malloc(size_t(M) * sizeof(size_t), 64);  check_malloc(NML, __LINE__, __FILE__);\n    dalloc += 6.0 * double(M) * sizeof(size_t) / 1E9;\n\n\n    // Boolean mask for using BED representation or not (SPARSE otherwise)\n    // For markers with USEBED == true then the BED representation is \n    // converted on the fly to SPARSE the time for the corresponding marker\n    // to be processed\n    // --------------------------------------------------------------------\n    bool *USEBED;\n    USEBED = (bool*)_mm_malloc(M * sizeof(bool), 64);  check_malloc(USEBED, __LINE__, __FILE__);\n    for (int i=0; i<M; i++) USEBED[i] = false;\n    int nusebed = 0;\n\n\n    uint *I1, *I2, *IM;\n    size_t taskBytes = 0;\n\n    if (opt.readFromBedFile) {\n        data.load_data_from_bed_file(opt.bedFile, Ntot, M, rank, MrankS[rank],\n                                     N1S, N1L, I1,\n                                     N2S, N2L, I2,\n                                     NMS, NML, IM,\n                                     taskBytes);\n    } else {\n        string sparseOut = mpi_get_sparse_output_filebase(rank);\n        data.load_data_from_sparse_files(rank, nranks, M, MrankS, MrankL, sparseOut,\n                                         N1S, N1L, I1,\n                                         N2S, N2L, I2,\n                                         NMS, NML, IM,\n                                         taskBytes);\n    }\n\n    MPI_Barrier(MPI_COMM_WORLD);\n\n    tl += mysecond();\n\n    if (rank == 0) {\n        printf(\"INFO   : rank %3d took %.3f seconds to load  %lu bytes  =>  BW = %7.3f GB/s\\n\", rank, tl, taskBytes, (double)taskBytes * 1E-9 / tl);\n        fflush(stdout);\n    }\n\n\n    // Correct each marker for individuals with missing phenotype\n    // ----------------------------------------------------------\n    if (data.numNAs > 0) {\n\n        if (rank == 0)\n            printf(\"INFO   : applying %d corrections to genotype data due to missing phenotype data (NAs in .phen).\\n\", data.numNAs);\n\n        data.sparse_data_correct_for_missing_phenotype(N1S, N1L, I1, M, USEBED);\n        data.sparse_data_correct_for_missing_phenotype(N2S, N2L, I2, M, USEBED);\n        data.sparse_data_correct_for_missing_phenotype(NMS, NML, IM, M, USEBED);\n\n        MPI_Barrier(MPI_COMM_WORLD);\n        if (rank == 0) printf(\"INFO   : finished applying NA corrections.\\n\");\n\n        // Adjust N upon number of NAs\n        Ntot -= data.numNAs;\n        if (rank == 0 && data.numNAs > 0)\n            printf(\"INFO   : Ntot adjusted by -%d to account for NAs in phenotype file. Now Ntot=%d\\n\", data.numNAs, Ntot);\n    }\n\n    // Compute statistics (from sparse info)\n    // -------------------------------------\n    //if (rank == 0) printf(\"INFO   : start computing statistics on Ntot = %d individuals\\n\", Ntot);\n    double dN   = (double) Ntot;\n    double dNm1 = (double)(Ntot - 1);\n    double *mave, *mstd, *sum_failure, *sum_failure_fix; \n\n    mave = (double*)_mm_malloc(size_t(M) * sizeof(double), 64);  check_malloc(mave, __LINE__, __FILE__);\n    mstd = (double*)_mm_malloc(size_t(M) * sizeof(double), 64);  check_malloc(mstd, __LINE__, __FILE__);\n    sum_failure = (double*)_mm_malloc(size_t(M) * sizeof(double), 64);  check_malloc(mstd, __LINE__, __FILE__);\n\n    sum_failure_fix = (double*)_mm_malloc(size_t(numFixedEffects) * sizeof(double), 64);  check_malloc(mstd, __LINE__, __FILE__);\n\n    dalloc += 2 * size_t(M) * sizeof(double) / 1E9;\n\n    double tmp0, tmp1, tmp2;\n    double temp_fail_sum = used_data_alpha.failure_vector.array().sum();\n    for (int i=0; i<M; ++i) {\n        // For now use the old way to compute means\n        mave[i] = (double(N1L[i]) + 2.0 * double(N2L[i])) / (dN - double(NML[i]));        \n\n        tmp1 = double(N1L[i]) * (1.0 - mave[i]) * (1.0 - mave[i]);\n        tmp2 = double(N2L[i]) * (2.0 - mave[i]) * (2.0 - mave[i]);\n        tmp0 = double(Ntot - N1L[i] - N2L[i] - NML[i]) * (0.0 - mave[i]) * (0.0 - mave[i]);\n        //TODO At some point we need to turn sd to 1/sd for speed\n        //mstd[i] = sqrt(double(Ntot - 1) / (tmp0+tmp1+tmp2));\n        mstd[i] = sqrt( (tmp0+tmp1+tmp2)/double(Ntot - 1));\n\n        int temp_sum = 0;\n        for(size_t ii = N1S[i]; ii < (N1S[i] + N1L[i]) ; ii++){\n            temp_sum += used_data_alpha.failure_vector(I1[ii]);\n        }\n        for(size_t ii = N2S[i]; ii < (N2S[i] + N2L[i]) ; ii++){\n            temp_sum += 2*used_data_alpha.failure_vector(I2[ii]);\n        }\n        sum_failure[i] = (temp_sum - mave[i] * temp_fail_sum) / mstd[i];\n\n        //printf(\"marker %6d mean %20.15f, std = %20.15f (%.1f / %.15f)  (%15.10f, %15.10f, %15.10f)\\n\", i, mave[i], mstd[i], double(Ntot - 1), tmp0+tmp1+tmp2, tmp1, tmp2, tmp0);\n    }\n    //If there are fixed effects, find the same values for them\n    if(opt.covariates){\n        for(int fix_i=0; fix_i < numFixedEffects; fix_i++){\n            sum_failure_fix[fix_i] = ((data.X.col(fix_i).cast<double>()).array() * used_data_alpha.failure_vector.array()).sum();\n        }\n    }\n\n\n    MPI_Barrier(MPI_COMM_WORLD);\n\n    const auto et2 = std::chrono::high_resolution_clock::now();\n    const auto dt2 = et2 - st2;\n    const auto du2 = std::chrono::duration_cast<std::chrono::milliseconds>(dt2).count();\n    if (rank == 0)   std::cout << \"INFO   : time to preprocess the data: \" << du2 / double(1000.0) << \" seconds.\" << std::endl;\n\n\n    // Build list of markers    \n    // ---------------------\n    for (int i=0; i<M; ++i) markerI.push_back(i);\n    // Processing part\n    // ---------------\n    const auto st3 = std::chrono::high_resolution_clock::now();\n    //double *y, *epsilon, *tmpEps, *previt_eps, *deltaEps, *dEpsSum, *deltaSum;\n    double *y, *tmpEps, *deltaEps, *dEpsSum, *deltaSum, *epsilon ,*vi , *tmp_vi, *tmpEps_vi, *tmp_deltaEps;\n    const size_t NDB = size_t(Ntot) * sizeof(double);\n    y          = (double*)_mm_malloc(NDB, 64);  check_malloc(y,          __LINE__, __FILE__);\n    epsilon    = (double*)_mm_malloc(NDB, 64);  check_malloc(epsilon,    __LINE__, __FILE__);\n    vi    = (double*)_mm_malloc(NDB, 64);  check_malloc(vi,    __LINE__, __FILE__);\n\n    tmpEps_vi    = (double*)_mm_malloc(NDB, 64);  check_malloc(tmpEps_vi,    __LINE__, __FILE__);\n    tmp_vi    = (double*)_mm_malloc(NDB, 64);  check_malloc(tmp_vi,    __LINE__, __FILE__);\n\n    tmpEps     = (double*)_mm_malloc(NDB, 64);  check_malloc(tmpEps,     __LINE__, __FILE__);\n    //previt_eps = (double*)malloc(NDB);  check_malloc(previt_eps, __LINE__, __FILE__);\n    tmp_deltaEps   = (double*)_mm_malloc(NDB, 64);  check_malloc(tmp_deltaEps,   __LINE__, __FILE__);\n\n    deltaEps   = (double*)_mm_malloc(NDB, 64);  check_malloc(deltaEps,   __LINE__, __FILE__);\n    dEpsSum    = (double*)_mm_malloc(NDB, 64);  check_malloc(dEpsSum,    __LINE__, __FILE__);\n    deltaSum   = (double*)_mm_malloc(NDB, 64);  check_malloc(deltaSum,   __LINE__, __FILE__);\n    dalloc += NDB * 6 / 1E9;\n\n    double totalloc = 0.0;\n    MPI_Reduce(&dalloc, &totalloc, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);\n    if (rank == 0) printf(\"INFO   : overall allocation %.3f GB\\n\", totalloc);\n\n    set_vector_f64(dEpsSum, 0.0, Ntot);\n\n    // Copy, center and scale phenotype observations\n    // In bW we are not scaling and centering phenotypes\n    if(opt.restart){\n        for (int i=0; i<Ntot; ++i){\n            epsilon[i] = epsilon_restart[i];\n        }\n        markerI = markerI_restart;\n        if (opt.covariates) {\n            for (int i=0; i < numFixedEffects; i++) {\n                gamma[i] = gamma_restart[i];\n                xI[i]    = xI_restart[i];\n            }\n        }\n    }else{\n        for (int i=0; i<Ntot; ++i) y[i] = data.y(i);\n        for (int i=0; i<Ntot; ++i)  epsilon[i] = y[i] - mu;\n    }\n    VectorXd sum_beta_squaredNorm;\n    double   beta, betaOld, deltaBeta, p, acum;\n    VectorXd beta_squaredNorm;\n    size_t   markoff;\n    int      marker, cx;\n\n    beta_squaredNorm.resize(numGroups);\n    sum_beta_squaredNorm.resize(numGroups);\n    // A counter on previously saved thinned iterations\n    uint n_thinned_saved = 0;\n\n    // Main iteration loop\n    // -------------------\n    //bool replay_it = false;\n    double tot_sync_ar1  = 0.0;\n    double tot_sync_ar2  = 0.0;\n    int    tot_nsync_ar1 = 0;\n    int    tot_nsync_ar2 = 0;\n    int    *glob_info, *tasks_len, *tasks_dis, *stats_len, *stats_dis;\n\n    if (opt.sparseSync) {\n        glob_info  = (int*)    _mm_malloc(size_t(nranks * 2) * sizeof(int),    64);  check_malloc(glob_info,  __LINE__, __FILE__);\n        tasks_len  = (int*)    _mm_malloc(size_t(nranks)     * sizeof(int),    64);  check_malloc(tasks_len,  __LINE__, __FILE__);\n        tasks_dis  = (int*)    _mm_malloc(size_t(nranks)     * sizeof(int),    64);  check_malloc(tasks_dis,  __LINE__, __FILE__);\n        stats_len  = (int*)    _mm_malloc(size_t(nranks)     * sizeof(int),    64);  check_malloc(stats_len,  __LINE__, __FILE__);\n        stats_dis  = (int*)    _mm_malloc(size_t(nranks)     * sizeof(int),    64);  check_malloc(stats_dis,  __LINE__, __FILE__);\n    }\n\n    //Set iteration_start=0\n    for (uint iteration=iteration_start; iteration<opt.chainLength; iteration++) {\n\n        double start_it = MPI_Wtime();\n        double it_sync_ar1  = 0.0;\n        double it_sync_ar2  = 0.0;\n        int    it_nsync_ar1 = 0;\n        int    it_nsync_ar2 = 0;\n\n        /* 1. Intercept (mu) */\n        //Removed sampleMu function on its own \n        int err, ninit = 4, npoint = 100, nsamp = 1, ncent = 4 ;\n        int neval;\n        double xsamp[0], xcent[10], qcent[10] = {5., 30., 70., 95.};\n        double convex = 1.0;\n        int dometrop = 0;\n        double xprev = 0.0;\n        double xinit[4] = {0.95*mu, mu,  1.005*mu, 1.01*mu};     // Initial abscissae\n        double *p_xinit = xinit;\n\n        double xl = 2;\n        double xr = 5;   //xl and xr and the maximum and minimum values between which we sample\n\n        //Update before sampling\n        for(int mu_ind=0; mu_ind < Ntot; mu_ind++){\n            (used_data.epsilon)[mu_ind] = epsilon[mu_ind] + mu;// we add to epsilon =Y+mu-X*beta\n        }\n\n        // Use ARS to sample mu (with density mu_dens, using parameters from used_data)\n        err = arms(xinit,ninit,&xl,&xr,mu_dens,&used_data,&convex,\n                   npoint,dometrop,&xprev,xsamp,nsamp,qcent,xcent,ncent,&neval);\n\n        errorCheck(err); // If there is error, stop the program\n        check_mpi(MPI_Bcast(&xsamp[0], 1, MPI_DOUBLE, 0, MPI_COMM_WORLD), __LINE__, __FILE__);\n        mu = xsamp[0];   // Save the sampled value\n        //Update after sampling\n        for(int mu_ind=0; mu_ind < Ntot; mu_ind++){\n            epsilon[mu_ind] = (used_data.epsilon)[mu_ind] - mu;// we add to epsilon =Y+mu-X*beta\n        }\n        ////////// End sampling mu\n        /* 1a. Fixed effects (gammas) */\n        if(opt.covariates){\n\n            double gamma_old = 0;\n            std::shuffle(xI.begin(), xI.end(), dist.rng);    \n    \t\t//Use only rank 0 shuffling\n            check_mpi(MPI_Bcast(xI.data(), xI.size(), MPI_INT, 0, MPI_COMM_WORLD), __LINE__, __FILE__);\n\t        MPI_Barrier(MPI_COMM_WORLD);\n\n\n            for(int fix_i = 0; fix_i < numFixedEffects; fix_i++){\n                gamma_old = gamma(xI[fix_i]);\n\n                neval = 0;\n                xsamp[0] = 0;\n                convex = 1.0;\n                dometrop = 0;\n                xprev = 0.0;\n\n                xinit[0] = gamma_old - 0.075/30 ;     // Initial abscissae\n                xinit[1] = gamma_old; \t\n                xinit[2] = gamma_old + 0.075/60;  \n                xinit[3] = gamma_old + 0.075/30;  \n\n                xl = gamma_old - 0.075;\n                xr = gamma_old + 0.075;\t\t\t  // Initial left and right (pseudo) extremes\n\n                used_data.X_j = data.X.col(xI[fix_i]).cast<double>();  //Take from the fixed effects matrix\n                used_data.sum_failure = sum_failure_fix[xI[fix_i]];\n\n\n                for(int k = 0; k < Ntot; k++){\n                    (used_data.epsilon)[k] = epsilon[k] + used_data.X_j[k] * gamma_old;// we adjust the residual with the respect to the previous gamma value\n        \t}\n                // Sample using ARS\n                err = arms(xinit,ninit,&xl,&xr, gamma_dens,&used_data,&convex,\n                           npoint,dometrop,&xprev,xsamp,nsamp,qcent,xcent,ncent,&neval);\n                errorCheck(err);\n\n                //Use only rank 0\n\t\t        check_mpi(MPI_Bcast(&xsamp[0], 1, MPI_DOUBLE, 0, MPI_COMM_WORLD), __LINE__, __FILE__);\n\t\t\n                gamma(xI[fix_i]) = xsamp[0];  // Save the new result\n                for(int k = 0; k < Ntot; k++){\n                    epsilon[k] = (used_data.epsilon)[k] - used_data.X_j[k] * gamma(xI[fix_i]);// we adjust the residual with the respect to the previous gamma value\n                }\n\t\t        MPI_Barrier(MPI_COMM_WORLD);\n            }\n        }\n\n        ////////// End sampling gamma\n        //EO: watch out, std::shuffle is not portable, so do no expect identical\n        //    results between Intel and GCC when shuffling the markers is on!!\n        //------------------------------------------------------------------------\n\n        // ARS parameters\n        neval = 0;\n        xsamp[0] = 0;\n        convex = 1.0;\n        dometrop = 0;\n        xprev = 0.0;\n        xinit[0] = (used_data.alpha)*0.5;     // Initial abscissae\n        xinit[1] =  used_data.alpha;\n        xinit[2] = (used_data.alpha)*1.05;\n        xinit[3] = (used_data.alpha)*1.10;\n\n        // Initial left and right (pseudo) extremes\n        xl = 0.0;\n        xr = 40.0;\n\n        //Give the residual to alpha structure\n        //used_data_alpha.epsilon = epsilon;\n        for(int alpha_ind=0; alpha_ind < Ntot; alpha_ind++){\n            (used_data_alpha.epsilon)[alpha_ind] = epsilon[alpha_ind];\n        }\n\n        //Sample using ARS\n        err = arms(xinit,ninit,&xl,&xr,alpha_dens,&used_data_alpha,&convex,\n                   npoint,dometrop,&xprev,xsamp,nsamp,qcent,xcent,ncent,&neval);\n        errorCheck(err);\n        check_mpi(MPI_Bcast(&xsamp[0], 1, MPI_DOUBLE, 0, MPI_COMM_WORLD), __LINE__, __FILE__);\n        used_data.alpha = xsamp[0];\n        used_data_beta.alpha = xsamp[0];\n\n        MPI_Barrier(MPI_COMM_WORLD);\n\n\n        // Calculate the vector of exponent of the adjusted residuals\n        for(int i = 0; i < Ntot; ++i){\n            vi[i] = exp(used_data.alpha * epsilon[i] - EuMasc);\n        }\n\n        if (opt.shuffleMarkers) {\n            std::shuffle(markerI.begin(), markerI.end(), dist.rng);\n        }\n        m0.array() = 0;\n\tcass.setZero();\n\n        for (int i=0; i<Ntot; ++i) tmpEps[i] = epsilon[i];\n\n        double cumSumDeltaBetas = 0.0;\n        double task_sum_abs_deltabeta = 0.0;\n        int    sinceLastSync    = 0;\n     \n        // First element for the marginal likelihoods is always is pi_0 *sqrt(pi) for\n        //marginal_likelihoods(0) = pi_L(0) * sqrtPI;  \n\t//Precalculate the product already before for each group\n\tfor(int gg = 0; gg < numGroups; gg++){\n\t\tmarginal_likelihood_0(gg) = pi_L(gg,0) * sqrtPI ;\n\t}\n\t//Set the sum of beta squared 0\n        beta_squaredNorm.setZero();\n\n        // Loop over (shuffled) markers\n        // ----------------------------\n        for (int j = 0; j < lmax; j++) {\n            sinceLastSync += 1; \n            \n            if (j < M) {\n                marker  = markerI[j];\n                beta =  Beta(marker);\n\n\t\tunsigned int cur_group = groups[MrankS[rank] + marker];\n                /////////////////////////////////////////////////////////\n                //Replace the sampleBeta function with the inside of the function        \n                double vi_sum = 0.0;\n                double vi_1 = 0.0;\n                double vi_2 = 0.0;\n\n                used_data_beta.sigmaG = sigmaG[cur_group];\n\n\t\tmarginal_likelihoods(0) = marginal_likelihood_0(cur_group);  //Each group has now different marginal likelihood at 0\n\n                //Change the residual vector only if the previous beta was non-zero\n                if(Beta(marker) != 0){\n                    //Calculate the change in epsilon if we remove the previous marker effect (-Beta(marker))\n                    set_vector_f64(tmp_deltaEps, 0.0, Ntot);\n                    sparse_scaadd(tmp_deltaEps, Beta(marker),\n                                  I1, N1S[marker], N1L[marker],\n                                  I2, N2S[marker], N2L[marker],\n                                  IM, NMS[marker], NML[marker],\n                                  mave[marker], 1/mstd[marker] , Ntot);\n                    //Create the temporary vector to store the vector without the last Beta(marker)\n                    sum_vectors_f64(tmpEps_vi, epsilon, tmp_deltaEps,  Ntot);\n                    //Also find the transformed residuals\n                    for(uint i=0; i<Ntot; ++i){\n                        tmp_vi[i] = exp(used_data.alpha * tmpEps_vi[i] - EuMasc);\n                    }\n                    vi_sum = sum_vector_elements_f64(tmp_vi, Ntot);\n                    vi_2 = partial_sum(tmp_vi, I2, N2S[marker], N2L[marker]);\n                    vi_1 = partial_sum(tmp_vi, I1, N1S[marker], N1L[marker]);\n\n                }else{\n                    // Calculate the sums of vi elements\n                    vi_sum = sum_vector_elements_f64(vi, Ntot);\n                    vi_2 = partial_sum(vi, I2, N2S[marker], N2L[marker]);\n                    vi_1 = partial_sum(vi, I1, N1S[marker], N1L[marker]);\n\n                }\n\n                double vi_0 = vi_sum - vi_1 - vi_2;\n\n                /* Calculate the mixture probability */\n                double p = dist.unif_rng();  //Generate number from uniform distribution (for sampling from categorical distribution)    \n \n                // Calculate the (ratios of) marginal likelihoods\n                used_data_beta.sum_failure = sum_failure[marker];\n                marginal_likelihood_vec_calc(pi_L.row(cur_group) , marginal_likelihoods, quad_points, vi_sum, vi_2, vi_1, vi_0,\n                                             mave[marker],mstd[marker], mave[marker]/mstd[marker], cur_group);\n\n                // Calculate the probability that marker is 0\n                double acum = marginal_likelihoods(0)/marginal_likelihoods.sum();\n\n                //Loop through the possible mixture classes\n                for (int k = 0; k < K; k++) {\n                    if (p <= acum) {\n                        //if zeroth component\n                        if (k == 0) {\n                            Beta(marker) = 0;\n                            cass(cur_group, 0) += 1;\n                            components[marker]  = k;\n\n                        }\n                        // If is not 0th component then sample using ARS\n                        else {\n                            //used_data_beta.sum_failure = sum_failure(marker);\n                            used_data_beta.mean = mave[marker];\n                            used_data_beta.sd = mstd[marker];\n                            used_data_beta.mean_sd_ratio = mave[marker]/mstd[marker];\n                            //used_data_beta.used_mixture = k-1;\n\t\t\t                used_data_beta.mixture_value = cVa(cur_group, k-1); //k-1 because cVa stores only non-zero in bW\n\n                            used_data_beta.vi_0 = vi_0;\n                            used_data_beta.vi_1 = vi_1;\n                            used_data_beta.vi_2 = vi_2;\n\n                           // double safe_limit = 2 * sqrt(used_data_beta.sigmaG * used_data_beta.mixture_classes(k-1));\n                            double safe_limit = 2 * sqrt(sumSigmaG * used_data_beta.mixture_value); \n\t\t \t                // ARS parameters\n                            neval = 0;\n                            xsamp[0] = 0;\n                            convex = 1.0;\n                            dometrop = 0;\n                            xprev = 0.0;\n                            xinit[0] = Beta(marker) - safe_limit/10;     // Initial abscissae\n                            xinit[1] = Beta(marker);\n                            xinit[2] = Beta(marker) + safe_limit/20;\n                            xinit[3] = Beta(marker) + safe_limit/10;\n\t\t        \n                            // Initial left and right (pseudo) extremes\n                            xl = Beta(marker) - safe_limit  ; //Construct the hull around previous beta value\n                            xr = Beta(marker) + safe_limit;\n                            // Sample using ARS\n                            err = arms(xinit,ninit,&xl,&xr,beta_dens,&used_data_beta,&convex,\n                                       npoint,dometrop,&xprev,xsamp,nsamp,qcent,xcent,ncent,&neval);\n\t                        errorCheck(err);\n\n                            Beta(marker) = xsamp[0];  // Save the new result\n\n                            cass(cur_group, k) += 1;\n                            components[marker] = k;\n\t\t\t    // Write the sum of the beta squared to the vector\n\t\t            beta_squaredNorm[groups[MrankS[rank] + marker]] += Beta[marker] * Beta[marker];\n\n                        }\n                        break;\n                    } else {\n                        if((k+1) == km1){\n                            acum = 1; // In the end probability will be 1\n                        }else{\n                            acum += marginal_likelihoods(k+1)/marginal_likelihoods.sum();\n                        }\n                    }\n                }\n\n                betaOld   = beta;\n                beta      = Beta(marker);\n                deltaBeta = betaOld - beta;\n                //printf(\"deltaBeta = %15.10f\\n\", deltaBeta);\n\n                // Compute delta epsilon\n                if (deltaBeta != 0.0) {\n                    //printf(\"it %d, task %3d, marker %5d has non-zero deltaBeta = %15.10f (%15.10f, %15.10f) => %15.10f) 1,2,M: %lu, %lu, %lu\\n\", iteration, rank, marker, deltaBeta, mave[marker], mstd[marker],  deltaBeta * mstd[marker], N1L[marker], N2L[marker], NML[marker]);\n\n                    if (opt.sparseSync && nranks > 1) {\n\n                        mark2sync.push_back(marker);\n                        dbet2sync.push_back(deltaBeta);\n\n                    } else {\n                        sparse_scaadd(deltaEps, deltaBeta, \n                                      I1, N1S[marker], N1L[marker],\n                                      I2, N2S[marker], N2L[marker],\n                                      IM, NMS[marker], NML[marker],\n                                      mave[marker], 1/mstd[marker] , Ntot); //Use here 1/sd\n                        \n                        // Update local sum of delta epsilon\n                        sum_vectors_f64(dEpsSum, deltaEps, Ntot);\n                    }\n                }\t\n            }\n\n                        \n\n            // Make the contribution of tasks beyond their last marker nill\n            // ------------------------------------------------------------\n            else {\n                //cout << \"rank \" << rank << \" with M=\" << M << \" waiting for \" << lmax << endl;\n                deltaBeta = 0.0;\n                \n                set_vector_f64(deltaEps, 0.0, Ntot);\n            }\n\n            task_sum_abs_deltabeta += fabs(deltaBeta);\n\n            // Check whether we have a non-zero beta somewhere\n            //if (nranks > 1 && (sync_rate == 0 || sinceLastSync > sync_rate || j == lmax-1)) {\n            if (nranks > 1 && (sinceLastSync >= opt.syncRate || j == lmax-1)) {    \n                //MPI_Barrier(MPI_COMM_WORLD);\n                double tb = MPI_Wtime();                \n                check_mpi(MPI_Allreduce(&task_sum_abs_deltabeta, &cumSumDeltaBetas, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD), __LINE__, __FILE__);\n\n                double te = MPI_Wtime();\n                tot_sync_ar1  += te - tb;\n                it_sync_ar1   += te - tb;\n                tot_nsync_ar1 += 1;\n                it_nsync_ar1  += 1;\n\n            } else {\n                cumSumDeltaBetas = task_sum_abs_deltabeta;\n            }\n            //printf(\"%d/%d/%d: deltaBeta = %20.15f = %10.7f - %10.7f; sumDeltaBetas = %15.10f\\n\", iteration, rank, marker, deltaBeta, betaOld, beta, cumSumDeltaBetas);\n\n            //         if ( (sync_rate == 0 || sinceLastSync > sync_rate || j == lmax-1) && cumSumDeltaBetas != 0.0) {\n            if ( cumSumDeltaBetas != 0.0 && (sinceLastSync >= opt.syncRate || j == lmax-1)) {\n\n                // Update local copy of epsilon\n                //MPI_Barrier(MPI_COMM_WORLD);\n\n                if (nranks > 1) {\n                    double tb = MPI_Wtime();\n                    \n                    // Sparse synchronization\n                    // ----------------------\n                    if (opt.sparseSync) {\n                            \n                        uint task_m2s = (uint) mark2sync.size();\n                        \n                        // Build task markers to sync statistics: mu | dbs | mu | dbs | ...\n                        double* task_stat = (double*) _mm_malloc(size_t(task_m2s) * 2 * sizeof(double), 64);\n                        check_malloc(task_stat, __LINE__, __FILE__);\n                        \n                        // Compute total number of elements to be sent by each task\n                        uint task_size = 0;\n                        for (int i=0; i<task_m2s; i++) {\n                            task_size += (N1L[ mark2sync[i] ] + N2L[ mark2sync[i] ] + NML[ mark2sync[i] ] + 3);\n                            task_stat[2 * i + 0] = mave[ mark2sync[i] ];\n                            task_stat[2 * i + 1] = mstd[ mark2sync[i] ] * dbet2sync[i]; //CHANGE mstd later!\n                            //printf(\"Task %3d, m2s %d/%d: 1: %8lu, 2: %8lu, m: %8lu, info: 3); stats are (%15.10f, %15.10f)\\n\", rank, i, task_m2s, N1L[ mark2sync[i] ], N2L[ mark2sync[i] ], NML[ mark2sync[i] ], task_stat[2 * i + 0], task_stat[2 * i + 1]);\n                        }\n                        //printf(\"Task %3d final task_size = %8d elements to send from task_m2s = %d markers to sync.\\n\", rank, task_size, task_m2s);\n                        //fflush(stdout);\n                        \n                        // Get the total numbers of markers and corresponding indices to gather\n                        \n                        const int NEL = 2;\n                        uint task_info[NEL] = {};                        \n                        task_info[0] = task_m2s;\n                        task_info[1] = task_size;\n                        \n                        check_mpi(MPI_Allgather(task_info, NEL, MPI_UNSIGNED, glob_info, NEL, MPI_UNSIGNED, MPI_COMM_WORLD), __LINE__, __FILE__);\n                        \n                        int tdisp_ = 0, sdisp_ = 0, glob_m2s = 0, glob_size = 0;\n                        for (int i=0; i<nranks; i++) {\n                            tasks_len[i]  = glob_info[2 * i + 1];\n                            tasks_dis[i]  = tdisp_;\n                            tdisp_       += tasks_len[i];\n                            stats_len[i]  = glob_info[2 * i] * 2;\n                            stats_dis[i]  = sdisp_;\n                            sdisp_       += glob_info[2 * i] * 2;\n                            glob_size    += tasks_len[i];\n                            glob_m2s     += glob_info[2 * i];\n                        }\n                        //printf(\"glob_info: markers to sync: %d, with glob_size = %7d elements (sum of all task_size)\\n\", glob_m2s, glob_size);\n                        //fflush(stdout);\n                        \n\n                        // Build task's array to spread: | marker 1                             | marker 2\n                        //                               | n1 | n2 | nm | data1 | data2 | datam | n1 | n2 | nm | data1 | ...\n                        // -------------------------------------------------------------------------------------------------\n                        uint* task_dat = (uint*) _mm_malloc(size_t(task_size) * sizeof(uint), 64);\n                        check_malloc(task_dat, __LINE__, __FILE__);\n                        \n                        int loc = 0;\n                        for (int i=0; i<task_m2s; i++) {\n                            task_dat[loc] = N1L[ mark2sync[i] ];                 loc += 1;\n                            task_dat[loc] = N2L[ mark2sync[i] ];                 loc += 1;\n                            task_dat[loc] = NML[ mark2sync[i] ];                 loc += 1;\n                            for (uint ii = 0; ii < N1L[ mark2sync[i] ]; ii++) {\n                                task_dat[loc] = I1[ N1S[ mark2sync[i] ] + ii ];  loc += 1;\n                            }\n                            for (uint ii = 0; ii < N2L[ mark2sync[i] ]; ii++) {\n                                task_dat[loc] = I2[ N2S[ mark2sync[i] ] + ii ];  loc += 1;\n                            }\n                            for (uint ii = 0; ii < NML[ mark2sync[i] ]; ii++) {\n                                task_dat[loc] = IM[ NMS[ mark2sync[i] ] + ii ];  loc += 1;\n                            }\n                        }                        \n                        assert(loc == task_size);\n                            \n                        // Allocate receive buffer for all the data\n                        uint* glob_dat = (uint*) _mm_malloc(size_t(glob_size) * sizeof(uint), 64);\n                        check_malloc(glob_dat, __LINE__, __FILE__);\n                        \n                        check_mpi(MPI_Allgatherv(task_dat, task_size, MPI_UNSIGNED,\n                                                 glob_dat, tasks_len, tasks_dis, MPI_UNSIGNED, MPI_COMM_WORLD), __LINE__, __FILE__);\n                        _mm_free(task_dat);\n                        \n                        double* glob_stats = (double*) _mm_malloc(size_t(glob_size * 2) * sizeof(double), 64);\n                        check_malloc(glob_stats, __LINE__, __FILE__);\n                        \n                        check_mpi(MPI_Allgatherv(task_stat, task_m2s * 2, MPI_DOUBLE,\n                                                 glob_stats, stats_len, stats_dis, MPI_DOUBLE, MPI_COMM_WORLD), __LINE__, __FILE__);                        \n                        _mm_free(task_stat);\n                        \n                         \n                        // Compute global delta epsilon deltaSum\n                        size_t loci = 0;\n                        for (int i=0; i<glob_m2s ; i++) {\n                            \n                            //printf(\"m2s %d/%d (loci = %d): %d, %d, %d\\n\", i, glob_m2s, loci, glob_dat[loci], glob_dat[loci + 1], glob_dat[loci + 2]);\n                            \n                            double lambda0 = glob_stats[2 * i + 1] * (0.0 - glob_stats[2 * i]);\n                            //printf(\"rank %d lambda0 = %15.10f with mu = %15.10f, dbetsig = %15.10f\\n\", rank, lambda0, glob_stats[2 * i], glob_stats[2 * i + 1]);\n                            \n                            // Set all to 0 contribution\n                            if (i == 0) {\n                                set_vector_f64(deltaSum, lambda0, Ntot);\n                            } else {\n                                offset_vector_f64(deltaSum, lambda0, Ntot);\n                            }\n                            \n                            // M -> revert lambda 0 (so that equiv to add 0.0)\n                            size_t S = loci + (size_t) (3 + glob_dat[loci] + glob_dat[loci + 1]);\n                            size_t L = glob_dat[loci + 2];\n                            //cout << \"task \" << rank << \" M: start = \" << S << \", len = \" << L <<  endl;\n                            sparse_add(deltaSum, -lambda0, glob_dat, S, L);\n                            \n                            // 1 -> add dbet * sig * ( 1.0 - mu)\n                            double lambda = glob_stats[2 * i + 1] * (1.0 - glob_stats[2 * i]);\n                            //printf(\"1: lambda = %15.10f, l-l0 = %15.10f\\n\", lambda, lambda - lambda0);\n                            S = loci + 3;\n                            L = glob_dat[loci];\n                            //cout << \"1: start = \" << S << \", len = \" << L <<  endl;\n                            sparse_add(deltaSum, lambda - lambda0, glob_dat, S, L);\n                            \n                            // 2 -> add dbet * sig * ( 2.0 - mu)\n                            lambda = glob_stats[2 * i + 1] * (2.0 - glob_stats[2 * i]);\n                            S = loci + 3 + glob_dat[loci];\n                            L = glob_dat[loci + 1];\n                            //cout << \"2: start = \" << S << \", len = \" << L <<  endl;\n                            sparse_add(deltaSum, lambda - lambda0, glob_dat, S, L);\n                            \n                            loci += 3 + glob_dat[loci] + glob_dat[loci + 1] + glob_dat[loci + 2];\n                        }\n                        \n                        _mm_free(glob_stats);\n                        _mm_free(glob_dat);                        \n                        \n                        mark2sync.clear();\n                        dbet2sync.clear();                            \n                        \n                    } else {\n                        \n                        check_mpi(MPI_Allreduce(&dEpsSum[0], &deltaSum[0], Ntot, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD), __LINE__, __FILE__);\n                    \n                    }\n                    \n                    sum_vectors_f64(epsilon, tmpEps, deltaSum, Ntot);\n                    \n                    double te = MPI_Wtime();\n                    tot_sync_ar2  += te - tb;\n                    it_sync_ar2   += te - tb;\n                    tot_nsync_ar2 += 1;\n                    it_nsync_ar2  += 1;    \n\n                } else { // case nranks == 1    \n                    if(opt.deltaUpdate == true){\n                        sum_vectors_f64(epsilon, tmpEps, dEpsSum,  Ntot);\n                    }else{\t\n                        for(uint i=0; i < Ntot; i++){\n                            epsilon[i] = epsilon[i] -  betaOld * mave[marker]/mstd[marker];\n                            epsilon[i] = epsilon[i] + beta * mave[marker]/mstd[marker];\n                        }\n                        //And adjust even further for specific 1 and 2 allele values\n\t\t                for (size_t i = N1S[marker]; i < (N1S[marker] + N1L[marker]) ; i++){\n                            epsilon[I1[i]] += betaOld/mstd[marker];\n                            epsilon[I1[i]] -= beta/mstd[marker];\n                        }\n                        for (size_t i = N2S[marker]; i < (N2S[marker] + N2L[marker]) ; i++){\n                            epsilon[I2[i]] += 2*betaOld/mstd[marker];\n                            epsilon[I2[i]] -= 2*beta/mstd[marker];\n                        }\n                    }\n                }\n   \n                // Do a update currently locally for vi vector\n                for(int vi_ind=0; vi_ind < Ntot; vi_ind++){\n                    vi[vi_ind] = exp(used_data.alpha * epsilon[vi_ind] - EuMasc);\n                }\n                double end_sync = MPI_Wtime();\n                //printf(\"INFO   : synchronization time = %8.3f ms\\n\", (end_sync - beg_sync) * 1000.0);\n                \n                // Store epsilon state at last synchronization\n                copy_vector_f64(tmpEps, epsilon, Ntot);\n                \n                // Reset local sum of delta epsilon\n                set_vector_f64(dEpsSum, 0.0, Ntot);\n                \n                // Reset cumulated sum of delta betas\n                cumSumDeltaBetas       = 0.0;\n                task_sum_abs_deltabeta = 0.0;\n                \n                sinceLastSync = 0;\n                \n            }\n\n        } // END PROCESSING OF ALL MARKERS\n\n        //PROFILE\n        //continue;\n\n       \n        //printf(\"rank %d it %d  beta_squaredNorm = %15.10f\\n\", rank, iteration, beta_squaredNorm);\n\n        //printf(\"==> after eps sync it %d, rank %d, epsilon[0] = %15.10f %15.10f\\n\", iteration, rank, epsilon[0], epsilon[Ntot-1]);\n\n        // Transfer global to local\n        // ------------------------\n        if (nranks > 1) {\n            MPI_Barrier(MPI_COMM_WORLD);\n            check_mpi(MPI_Allreduce(beta_squaredNorm.data(), sum_beta_squaredNorm.data(), beta_squaredNorm.size(),  MPI_DOUBLE,  MPI_SUM, MPI_COMM_WORLD), __LINE__, __FILE__);\n            check_mpi(MPI_Allreduce(cass.data(),       sum_cass.data(),       cass.size(), MPI_INTEGER, MPI_SUM, MPI_COMM_WORLD), __LINE__, __FILE__);\n            cass             = sum_cass;\n            beta_squaredNorm = sum_beta_squaredNorm;\n        }\n        if (rank == 0) {\n\n            printf(\"\\nINFO   : global cass on iteration %d:\\n\", iteration);\n            for (int i=0; i<numGroups; i++) {\n                printf(\"         Mtot[%3d] = %8d  | cass:\", i, MtotGrp[i]);\n                for (int ii=0; ii<K; ii++) {\n                    printf(\" %8d\", cass(i, ii));\n                }\n                printf(\" -> sum = %8d\\n\", cass.row(i).sum());\n            }\n        }\n\n        // Update global parameters\n        // ------------------------\n\tfor(int gg = 0; gg < numGroups ; gg++){\n\t        m0[gg] = MtotGrp[gg] - cass(gg,0);\n\t}\n\n        MPI_Barrier(MPI_COMM_WORLD);\n \n        // 4. Sample sigmaG\n\tfor(int gg=0; gg < numGroups ; gg++){\n\t\tsigmaG[gg]  = dist.inv_gamma_rng((double) (used_data.alpha_sigma + 0.5 * m0[gg]),(double)(used_data.beta_sigma + 0.5 * double(m0[gg]) * beta_squaredNorm(gg) ) );\n    }\n\t check_mpi(MPI_Bcast(sigmaG.data(), sigmaG.size(), MPI_DOUBLE, 0, MPI_COMM_WORLD), __LINE__, __FILE__);\n      \t\n        // 5. Sample prior mixture component probability from Dirichlet distribution\n       \n\tfor(int gg =0; gg < numGroups; gg++){\n            \tVectorXi dirin = cass.row(gg).array() + 1;  //For now use +1 as prior\n            \tpi_L.row(gg) = dist.dirichlet_rng(dirin);\n\n\t}\n\n        check_mpi(MPI_Bcast(pi_L.data(), pi_L.size(), MPI_DOUBLE, 0, MPI_COMM_WORLD), __LINE__, __FILE__);\n\n\tsumSigmaG = sigmaG.sum();  // Keep in memory for safe limit calculations\n\n        //Print results\n        if(rank == 0){\n\t  cout << iteration << \". \" << m0.sum() <<\"; \"<< setprecision(7) << mu << \"; \" <<  used_data.alpha << \"; \" << sigmaG.sum()  << endl;\n        }\n\n        double end_it = MPI_Wtime();\n        //if (rank == 0) printf(\"TIME_IT: Iteration %5d on rank %4d took %10.3f seconds\\n\", iteration, rank, end_it-start_it);\n\n        //printf(\"%d epssqn = %15.10f %15.10f %15.10f %6d => %15.10f\\n\", iteration, e_sqn, v0E, s02E, Ntot, sigmaE);\n        if (rank == 0) {\n            printf(\"RESULT : it %4d, rank %4d: proc = %9.3f s, sync = %9.3f (%9.3f + %9.3f), n_sync = %8d (%8d + %8d) (%7.3f / %7.3f), betasq = %15.10f, m0 = %10d\\n\",\n                   iteration, rank, end_it-start_it,\n                   it_sync_ar1  + it_sync_ar2,  it_sync_ar1,  it_sync_ar2,\n                   it_nsync_ar1 + it_nsync_ar2, it_nsync_ar1, it_nsync_ar2,\n                   (it_sync_ar1) / double(it_nsync_ar1) * 1000.0,\n                   (it_sync_ar2) / double(it_nsync_ar2) * 1000.0,\n                   beta_squaredNorm.sum(), int(m0.sum()));\n            fflush(stdout);\n        }\n \n        //cout<< \"inv scaled parameters \"<< v0G+m0 << \"__\"<< (Beta.squaredNorm()*m0+v0G*s02G)/(v0G+m0) << endl;\n        //printf(\"inv scaled parameters %20.15f __ %20.15f\\n\", v0G+m0, (Beta.squaredNorm()*m0+v0G*s02G)/(v0G+m0));\n        //sigmaE = dist.inv_scaled_chisq_rng(v0E+Ntot,((epsilon).squaredNorm()+v0E*s02E)/(v0E+Ntot));\n        //printf(\"sigmaG = %20.15f, sigmaE = %20.15f, e_sqn = %20.15f\\n\", sigmaG, sigmaE, e_sqn);\n        //printf(\"it %6d, rank %3d: epsilon[0] = %15.10f, y[0] = %15.10f, m0=%10.1f,  sigE=%15.10f,  sigG=%15.10f [%6d / %6d]\\n\", iteration, rank, epsilon[0], y[0], m0, sigmaE, sigmaG, markerI[0], markerI[M-1]);\n\n        // Write output files\n        // ------------------\n\n        if (iteration%opt.thin == 0) {\n\n            if(rank == 0){\n                //Save the hyperparameters\n\t        cx = snprintf(buff, LENBUF, \"%5d, %20.15f, %20.15f, %20.15f, %20.15f, %7d, %7d, %2d\", iteration, mu, sigmaG.sum() , used_data.alpha, sigmaG.sum()/(sigmaG.sum() + PI_squared / (6 * used_data.alpha*used_data.alpha)) , int(m0.sum()), int(pi_L.rows()), int(pi_L.cols()));\n            //\tassert(left > 0);\n\t\tassert(cx >= 0 && cx < LENBUF);  //We also use the condition cx < LENBUF for now\n\n\n             //   cx = snprintf(&buff, LENBUF - strlen(buff), \"%5d, %4d\", iteration, (int) sigmaG.size());\n             //   assert(cx >= 0 && cx < LENBUF);\n\n                for(int jj = 0; jj < sigmaG.size(); ++jj){\n                    cx = snprintf(&buff[strlen(buff)], LENBUF - strlen(buff), \", %20.15f\", sigmaG(jj));\n                    assert(cx >= 0 && cx < LENBUF - strlen(buff));\n                }\n\n\n                for (int ii=0; ii < pi_L.rows(); ++ii) {\n                    for(int kk = 0; kk < pi_L.cols(); ++kk) {\n                        cx = snprintf(&buff[strlen(buff)], LENBUF - strlen(buff), \", %20.15f\", pi_L(ii,kk));\n                        assert(cx >= 0 && cx < LENBUF - strlen(buff));\n                    }\n                }\n\n                cx = snprintf(&buff[strlen(buff)], LENBUF - strlen(buff), \"\\n\");\n                assert(cx >= 0 && cx < LENBUF - strlen(buff));\n\n                offset = size_t(n_thinned_saved) * strlen(buff);\n                check_mpi(MPI_File_write_at(outfh, offset, &buff, strlen(buff), MPI_CHAR, &status), __LINE__, __FILE__);\n\n                //Save the covariates\n                if(opt.covariates){ \n                    cx = snprintf(buff_gamma, LENBUF_gamma, \"%5d\", iteration);\n                    for (int ii=0; ii < numFixedEffects; ++ii) {\n                        cx = snprintf(&buff_gamma[strlen(buff_gamma)], LENBUF_gamma-strlen(buff_gamma), \", %20.17f\", gamma(ii));\n                        assert(cx > 0);\n                \t}\n                \tcx = snprintf(&buff_gamma[strlen(buff_gamma)], LENBUF_gamma - strlen(buff_gamma), \"\\n\");\n                \tassert(cx > 0);\n\t                offset = size_t(n_thinned_saved) * strlen(buff_gamma);\n\n                \tcheck_mpi(MPI_File_write_at(gamfh, offset, &buff_gamma, strlen(buff_gamma), MPI_CHAR, &status), __LINE__, __FILE__);\n                    //Save the order of the covariates\n                    if (iteration > 0 && iteration%opt.save == 0){\n                        offset = 0;\n\t                \tcheck_mpi(MPI_File_write_at(xivfh, offset, &iteration, 1, MPI_UNSIGNED, &status), __LINE__, __FILE__);\n                        offset = sizeof(uint);\n                        check_mpi(MPI_File_write_at(xivfh, offset, &numFixedEffects, 1, MPI_UNSIGNED, &status), __LINE__, __FILE__);\n\t\t\t\t\n                        offset = sizeof(uint) + sizeof(uint);\n\t                \tcheck_mpi(MPI_File_write_at(xivfh, offset, xI.data(), numFixedEffects,  MPI_INT,    &status), __LINE__, __FILE__);\n\n                    }\n\n                }\n\n            }\n\n            // Write iteration number\n            if (rank == 0) {\n                offset = sizeof(uint) + size_t(n_thinned_saved) * (sizeof(uint) + size_t(Mtot) * sizeof(double));\n                check_mpi(MPI_File_write_at(betfh, offset, &iteration, 1, MPI_UNSIGNED, &status), __LINE__, __FILE__);\n\n                offset = sizeof(uint) + size_t(n_thinned_saved) * (sizeof(uint) + size_t(Mtot) * sizeof(int));\n                check_mpi(MPI_File_write_at(cpnfh, offset, &iteration, 1, MPI_UNSIGNED, &status), __LINE__, __FILE__);\n            }\n            \n            offset = sizeof(uint) + sizeof(uint) \n                + size_t(n_thinned_saved) * (sizeof(uint) + size_t(Mtot) * sizeof(double))\n                + size_t(MrankS[rank]) * sizeof(double);\n            check_mpi(MPI_File_write_at_all(betfh, offset, Beta.data(), M, MPI_DOUBLE, &status), __LINE__, __FILE__);\n\n            offset = sizeof(uint) + sizeof(uint)\n                + size_t(n_thinned_saved) * (sizeof(uint) + size_t(Mtot) * sizeof(int))\n                + size_t(MrankS[rank]) * sizeof(int);\n            check_mpi(MPI_File_write_at_all(cpnfh, offset, components.data(), M, MPI_INTEGER, &status), __LINE__, __FILE__);\n\n            //if (iteration == 0) {\n            //    printf(\"rank %d dumping bet: %15.10f %15.10f\\n\", rank, Beta[0], Beta[MrankL[rank]-1]);\n            //    printf(\"rank %d dumping cpn: %d %d\\n\", rank, components[0], components[MrankL[rank]-1]);\n            //}\n\n            n_thinned_saved += 1;\n        }\n\n        // Dump the epsilon vector and the marker indexing one\n        // Note: single line overwritten at each saving iteration\n        // .eps format: uint, uint, double[0, N-1] (it, Ntot, [eps])\n        // .mrk format: uint, uint, int[0, M-1]    (it, M,    <mrk>)\n        // ------------------------------------------------------\n        if (iteration > 0 && iteration%opt.save == 0) {\n            srand(opt.seed + iteration);\n            // Each task writes its own rng file\n            dist.write_rng_state_to_file(rngfp);\n            offset  = 0;\n            check_mpi(MPI_File_write_at(epsfh, offset, &iteration, 1, MPI_UNSIGNED, &status), __LINE__, __FILE__);\n            check_mpi(MPI_File_write_at(mrkfh, offset, &iteration, 1, MPI_UNSIGNED, &status), __LINE__, __FILE__);\n            \n            offset = sizeof(uint);\n \n            check_mpi(MPI_File_write_at(epsfh, offset, &Ntot,         1, MPI_UNSIGNED, &status), __LINE__, __FILE__);\n            check_mpi(MPI_File_write_at(mrkfh, offset, &M,            1, MPI_UNSIGNED, &status), __LINE__, __FILE__);\n            check_mpi(MPI_File_write_at(xbetfh, offset, &iteration, 1, MPI_UNSIGNED, &status), __LINE__, __FILE__);                \n            check_mpi(MPI_File_write_at(xcpnfh, offset, &iteration, 1, MPI_UNSIGNED, &status), __LINE__, __FILE__);\n\n            offset = sizeof(uint) + sizeof(uint);\n            check_mpi(MPI_File_write_at(epsfh, offset, epsilon,        Ntot,           MPI_DOUBLE, &status), __LINE__, __FILE__);\n            check_mpi(MPI_File_write_at(mrkfh, offset, markerI.data(), markerI.size(), MPI_INT,    &status), __LINE__, __FILE__);\n\n            offset = sizeof(uint) + sizeof(uint) + size_t(MrankS[rank]) * sizeof(double);\n            check_mpi(MPI_File_write_at_all(xbetfh, offset, Beta.data(), M, MPI_DOUBLE, &status), __LINE__, __FILE__);\n\n            offset = sizeof(uint) + sizeof(uint) + size_t(MrankS[rank]) * sizeof(int);\n            check_mpi(MPI_File_write_at_all(xcpnfh, offset, components.data(), M, MPI_INTEGER, &status), __LINE__, __FILE__);\n\n            //if (iteration == 0) {\n            //    printf(\"rank %d dumping eps: %15.10f %15.10f\\n\", rank, epsilon[0], epsilon[Ntot-1]);\n            //}\n            //EO: to remove once MPI version fully validated; use the check_epsilon utility to retrieve\n            //    the corresponding values from the .eps file\n            //    Print only first and last value handled by each task\n            //printf(\"%4d/%4d epsilon[%5d] = %15.10f, epsilon[%5d] = %15.10f\\n\", iteration, rank, IrankS[rank], epsilon[IrankS[rank]], IrankS[rank]+IrankL[rank]-1, epsilon[IrankS[rank]+IrankL[rank]-1]);\n\n#if 1\n            //EO system call to create a tarball of the dump\n            //TODO: quite rough, make it more selective...\n            //----------------------------------------------\n            MPI_Barrier(MPI_COMM_WORLD);\n            if (rank == 0) {\n                time_t now = time(0);\n                tm *   ltm = localtime(&now);\n                int    n   = 0;\n                char targz[LENBUF];\n\n                n=sprintf(targz, \"dump_%s_%05d__%4d-%02d-%02d_%02d-%02d-%02d.tgz\",\n                          opt.mcmcOutNam.c_str(), iteration,\n                          1900 + ltm->tm_year, 1 + ltm->tm_mon, ltm->tm_mday,\n                          ltm->tm_hour, ltm->tm_min, ltm->tm_sec);\n                assert(n > 0);\n\n                printf(\"INFO   : will create tarball %s in %s with file listed in %s.\\n\",\n                       targz, opt.mcmcOutDir.c_str(), lstfp.c_str());\n\n                //std::system((\"ls \" + opt.mcmcOut + \".*\").c_str());\n                string cmd = \"tar -czf \" + opt.mcmcOutDir + \"/tarballs/\" + targz + \" -T \" + lstfp;\n\n                std::system(cmd.c_str());\n\n            }\n            MPI_Barrier(MPI_COMM_WORLD);\n#endif\n        }\n\n        //double end_it = MPI_Wtime();\n        //if (rank == 0) printf(\"TIME_IT: Iteration %5d on rank %4d took %10.3f seconds\\n\", iteration, rank, end_it-start_it);\n\n        MPI_Barrier(MPI_COMM_WORLD);\n    }\n\n    // Close output files\n    check_mpi(MPI_File_close(&outfh), __LINE__, __FILE__);\n    check_mpi(MPI_File_close(&betfh), __LINE__, __FILE__);\n    check_mpi(MPI_File_close(&xbetfh), __LINE__, __FILE__);\n    check_mpi(MPI_File_close(&epsfh), __LINE__, __FILE__);\n    check_mpi(MPI_File_close(&cpnfh), __LINE__, __FILE__);\n    check_mpi(MPI_File_close(&xcpnfh), __LINE__, __FILE__);\n    // check_mpi(MPI_File_close(&acufh), __LINE__, __FILE__);\n    check_mpi(MPI_File_close(&mrkfh), __LINE__, __FILE__);\n    check_mpi(MPI_File_close(&xivfh), __LINE__, __FILE__);\n    check_mpi(MPI_File_close(&gamfh), __LINE__, __FILE__);\n\n    // Release memory\n    _mm_free(y);\n    _mm_free(epsilon);\n    _mm_free(tmpEps);\n    //free(previt_eps);\n    _mm_free(deltaEps);\n    _mm_free(dEpsSum);\n    _mm_free(deltaSum);\n    _mm_free(mave);\n    _mm_free(mstd);\n    _mm_free(USEBED);\n    _mm_free(sum_failure);\n    _mm_free(N1S);\n    _mm_free(N1L);\n    _mm_free(I1);\n    _mm_free(N2S); \n    _mm_free(N2L);\n    _mm_free(I2);\n    _mm_free(NMS);\n    _mm_free(NML);\n    _mm_free(IM);\n\n    if (opt.sparseSync) {\n        _mm_free(glob_info);\n        _mm_free(tasks_len);\n        _mm_free(tasks_dis);\n        _mm_free(stats_len);\n        _mm_free(stats_dis);\n    }\n\n    const auto et3 = std::chrono::high_resolution_clock::now();\n    const auto dt3 = et3 - st3;\n    const auto du3 = std::chrono::duration_cast<std::chrono::milliseconds>(dt3).count();\n    if (rank == 0)\n        printf(\"INFO   : rank %4d, time to process the data: %.3f sec, with %.3f (%.3f, %.3f) = %4.1f%% spent on allred (%d, %d)\\n\",\n               rank, du3 / double(1000.0),\n               tot_sync_ar1 + tot_sync_ar2, tot_sync_ar1, tot_sync_ar2,\n               (tot_sync_ar1 + tot_sync_ar2) / (du3 / double(1000.0)) * 100.0,\n               tot_nsync_ar1, tot_nsync_ar2);\n\n    return 0;\n}\n\n\n// Get directory and basename of bed file (passed with no extension via command line)\n// ----------------------------------------------------------------------------------\n\n//  ORIGINAL (SEQUENTIAL) VERSION\n/*\n  VectorXd BayesW::getSnpData(unsigned int marker) const\n  {\n  if (!usePreprocessedData) {\n  //read column from RAM loaded genotype matrix.\n  return data.Z.col(marker);//.cast<double>();\n  } else {\n  //read column from preprocessed and memory mapped genotype matrix file.\n  return data.mappedZ.col(marker).cast<double>();\n  }\n  }\n\n  void BayesW::printDebugInfo() const\n  {\n  //const unsigned int N(data.numInds);\n  // cout << \"x mean \" << Cx.mean() << \"\\n\";\n  //   cout << \"x sd \" << sqrt(Cx.squaredNorm() / (double(N - 1))) << \"\\n\";\n  }\n*/\n", "meta": {"hexsha": "5b5268a2aaea9a74a52fb04f1d341d51fe42a21b", "size": 97622, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/BayesW.cpp", "max_stars_repo_name": "medical-genomics-group/hydra", "max_stars_repo_head_hexsha": "d352f1096d8397a36d6984ff7ea944bdb6c4e1d5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2020-09-09T08:35:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T16:09:12.000Z", "max_issues_repo_path": "src/BayesW.cpp", "max_issues_repo_name": "medical-genomics-group/hydra", "max_issues_repo_head_hexsha": "d352f1096d8397a36d6984ff7ea944bdb6c4e1d5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-12-09T14:48:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-23T09:56:24.000Z", "max_forks_repo_path": "src/BayesW.cpp", "max_forks_repo_name": "medical-genomics-group/hydra", "max_forks_repo_head_hexsha": "d352f1096d8397a36d6984ff7ea944bdb6c4e1d5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-10-11T12:33:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-11T12:33:25.000Z", "avg_line_length": 44.8424437299, "max_line_length": 277, "alphanum_fraction": 0.569830571, "num_tokens": 28431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4652136195626271}}
{"text": "#include <KalmanBoxTracker.h>\n#include <iostream>\n#include <Eigen/Dense>\n\nint KalmanBoxTracker::_count_ = 0;\n\nvoid KalmanBoxTracker::init(std::vector<float> x_vector_state)\n{\n  int dim_x = 8;\n  int dim_z = 5;\n\n  kf = KalmanFilter(dim_x, dim_z, 0);\n  measurement = Mat::zeros(dim_z, 1, CV_32F);\n  kf.transitionMatrix = (Mat_<float>(dim_x, dim_x) <<\n      1, 0, 0, 0, 0, 1, 0, 0,\n      0, 1, 0, 0, 0, 0, 1, 0,\n      0, 0, 1, 0, 0, 0, 0, 1,\n      0, 0, 0, 1, 0, 0, 0, 0,\n      0, 0, 0, 0, 1, 0, 0, 0,\n      0, 0, 0, 0, 0, 1, 0, 0,\n      0, 0, 0, 0, 0, 0, 1, 0,\n      0, 0, 0, 0, 0, 0, 0, 1);\n  // kf.measurementMatrix = *(Mat_<float>(dim_x, dim_z) <<\n  //     1, 0, 0, 0, 0, 0, 0,\n  //     0, 1, 0, 0, 0, 0, 0,\n  //     0, 0, 1, 0, 0, 0, 0,\n  //     0, 0, 0, 1, 0, 0, 0,\n  //     0, 0, 0, 0, 1, 0, 0);\n  setIdentity(kf.measurementMatrix);\n  setIdentity(kf.processNoiseCov, Scalar::all(1e-2));\n\tsetIdentity(kf.measurementNoiseCov, Scalar::all(1e-1));\n\tsetIdentity(kf.errorCovPost, Scalar::all(1));\n\n  // initialization of vector sate [u, v, w, h, gamma]\n  kf.statePost.at<float>(0, 0) = x_vector_state[0]; // u\n\tkf.statePost.at<float>(1, 0) = x_vector_state[1]; // v\n\tkf.statePost.at<float>(2, 0) = x_vector_state[2]; // w\n\tkf.statePost.at<float>(3, 0) = x_vector_state[3]; // h\n  kf.statePost.at<float>(4, 0) = x_vector_state[4]; // gamma\n}\n\n// Predict\nstd::vector<float> KalmanBoxTracker::predict()\n{\n\t// predict\n\tMat p = kf.predict();\n\tage += 1;\n\n\tif (time_since_update > 0)\n          hit_streak = 0;\n  time_since_update += 1;\n\n\tstd::vector<float> predictdet(5);\n\n  predictdet[0] = p.at<float>(0, 0);\n  predictdet[1] = p.at<float>(1, 0);\n  predictdet[2] = p.at<float>(2, 0);\n  predictdet[3] = p.at<float>(3, 0);\n  predictdet[4] = p.at<float>(4, 0);\n\n\thistory.push_back(predictdet);\n\treturn history.back();\n}\n\n// Update\nvoid KalmanBoxTracker::update(std::vector<float> x_vector_state)\n{\n\ttime_since_update = 0;\n\thistory.clear();\n\thits += 1;\n\thit_streak += 1;\n\n\t// Measurement\n\tmeasurement.at<float>(0, 0) = x_vector_state[0]; // u\n\tmeasurement.at<float>(1, 0) = x_vector_state[1]; // v\n\tmeasurement.at<float>(2, 0) = x_vector_state[2]; // w\n\tmeasurement.at<float>(3, 0) = x_vector_state[3]; // h\n  measurement.at<float>(4, 0) = x_vector_state[4]; // gamma\n\n\t// update\n\tkf.correct(measurement);\n}\n\n// Return the current state vector\nstd::vector<float> KalmanBoxTracker::get_state()\n{\n\tMat s = kf.statePost;\n  std::vector<float> state(5);\n\n  state[0] = s.at<float>(0, 0);\n  state[1] = s.at<float>(1, 0);\n  state[2] = s.at<float>(2, 0);\n  state[3] = s.at<float>(3, 0);\n  state[4] = s.at<float>(4, 0);\n\n\treturn state;\n}\n", "meta": {"hexsha": "2dd757f69b8522bc69138ca5996cfe906a9124e3", "size": 2614, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sort/impl/KalmanBoxTracker.cpp", "max_stars_repo_name": "CarlosLopezNubes5/cimat_sort_rgbd", "max_stars_repo_head_hexsha": "f900eaa6e5b6124413ab1f079038d0f795960b06", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-11-16T19:23:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-10T07:13:09.000Z", "max_issues_repo_path": "src/sort/impl/KalmanBoxTracker.cpp", "max_issues_repo_name": "CarlosLopezNubes5/cimat_sort_rgbd", "max_issues_repo_head_hexsha": "f900eaa6e5b6124413ab1f079038d0f795960b06", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-01-05T09:46:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-09T05:41:38.000Z", "max_forks_repo_path": "src/sort/impl/KalmanBoxTracker.cpp", "max_forks_repo_name": "CarlosLopezNubes5/cimat_sort_rgbd", "max_forks_repo_head_hexsha": "f900eaa6e5b6124413ab1f079038d0f795960b06", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-28T15:54:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-28T15:54:33.000Z", "avg_line_length": 26.6734693878, "max_line_length": 64, "alphanum_fraction": 0.596786534, "num_tokens": 1077, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541067, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.4652136195626271}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// pot_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_POT_TAIL_MEAN_HPP_DE_01_01_2006\n#define BOOST_ACCUMULATORS_STATISTICS_POT_TAIL_MEAN_HPP_DE_01_01_2006\n\n#include <vector>\n#include <limits>\n#include <numeric>\n#include <functional>\n#include <boost/range.hpp>\n#include <boost/parameter/keyword.hpp>\n#include <boost/tuple/tuple.hpp>\n#include <boost/mpl/if.hpp>\n#include <boost/mpl/placeholders.hpp>\n#include <boost/type_traits/is_same.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/statistics_fwd.hpp>\n#include <boost/accumulators/statistics/peaks_over_threshold.hpp>\n#include <boost/accumulators/statistics/weighted_peaks_over_threshold.hpp>\n#include <boost/accumulators/statistics/pot_quantile.hpp>\n#include <boost/accumulators/statistics/tail_mean.hpp>\n\nnamespace boost { namespace accumulators\n{\n\nnamespace impl\n{\n    ///////////////////////////////////////////////////////////////////////////////\n    // pot_tail_mean_impl\n    //\n    /**\n        @brief Estimation of the (coherent) tail mean based on the peaks over threshold method (for both left and right tails)\n\n        Computes an estimate for the (coherent) tail mean\n        \\f[\n            \\widehat{CTM}_{\\alpha} = \\hat{q}_{\\alpha} - \\frac{\\bar{\\beta}}{\\xi-1}(1-\\alpha)^{-\\xi},\n        \\f]\n        where \\f$\\bar[u]\\f$, \\f$\\bar{\\beta}\\f$ and \\f$\\xi\\f$ are the parameters of the\n        generalized Pareto distribution that approximates the right tail of the distribution (or the\n        mirrored left tail, in case the left tail is used). In the latter case, the result is mirrored\n        back, yielding the correct result.\n    */\n    template<typename Sample, typename Impl, typename LeftRight>\n    struct pot_tail_mean_impl\n      : accumulator_base\n    {\n        typedef typename numeric::functional::fdiv<Sample, std::size_t>::result_type float_type;\n        // for boost::result_of\n        typedef float_type result_type;\n\n        pot_tail_mean_impl(dont_care)\n          : sign_((is_same<LeftRight, left>::value) ? -1 : 1)\n        {\n        }\n\n        template<typename Args>\n        result_type result(Args const &args) const\n        {\n            typedef\n                typename mpl::if_<\n                    is_same<Impl, weighted>\n                  , tag::weighted_peaks_over_threshold<LeftRight>\n                  , tag::peaks_over_threshold<LeftRight>\n                >::type\n            peaks_over_threshold_tag;\n\n            typedef\n                typename mpl::if_<\n                    is_same<Impl, weighted>\n                  , tag::weighted_pot_quantile<LeftRight>\n                  , tag::pot_quantile<LeftRight>\n                >::type\n            pot_quantile_tag;\n\n            extractor<peaks_over_threshold_tag> const some_peaks_over_threshold = {};\n            extractor<pot_quantile_tag> const some_pot_quantile = {};\n\n            float_type beta_bar = some_peaks_over_threshold(args).template get<1>();\n            float_type xi_hat   = some_peaks_over_threshold(args).template get<2>();\n\n            return some_pot_quantile(args) - this->sign_ * beta_bar/( xi_hat - 1. ) * std::pow(\n                is_same<LeftRight, left>::value ? args[quantile_probability] : 1. - args[quantile_probability]\n              , -xi_hat);\n        }\n    private:\n        short sign_; // if the fit parameters from the mirrored left tail extreme values are used, mirror back the result\n    };\n} // namespace impl\n\n///////////////////////////////////////////////////////////////////////////////\n// tag::pot_tail_mean\n// tag::pot_tail_mean_prob\n//\nnamespace tag\n{\n    template<typename LeftRight>\n    struct pot_tail_mean\n      : depends_on<peaks_over_threshold<LeftRight>, pot_quantile<LeftRight> >\n    {\n        /// INTERNAL ONLY\n        ///\n        typedef accumulators::impl::pot_tail_mean_impl<mpl::_1, unweighted, LeftRight> impl;\n    };\n    template<typename LeftRight>\n    struct pot_tail_mean_prob\n      : depends_on<peaks_over_threshold_prob<LeftRight>, pot_quantile_prob<LeftRight> >\n    {\n        /// INTERNAL ONLY\n        ///\n        typedef accumulators::impl::pot_tail_mean_impl<mpl::_1, unweighted, LeftRight> impl;\n    };\n    template<typename LeftRight>\n    struct weighted_pot_tail_mean\n      : depends_on<weighted_peaks_over_threshold<LeftRight>, weighted_pot_quantile<LeftRight> >\n    {\n        /// INTERNAL ONLY\n        ///\n        typedef accumulators::impl::pot_tail_mean_impl<mpl::_1, weighted, LeftRight> impl;\n    };\n    template<typename LeftRight>\n    struct weighted_pot_tail_mean_prob\n      : depends_on<weighted_peaks_over_threshold_prob<LeftRight>, weighted_pot_quantile_prob<LeftRight> >\n    {\n        /// INTERNAL ONLY\n        ///\n        typedef accumulators::impl::pot_tail_mean_impl<mpl::_1, weighted, LeftRight> impl;\n    };\n}\n\n// pot_tail_mean<LeftRight>(with_threshold_value) -> pot_tail_mean<LeftRight>\ntemplate<typename LeftRight>\nstruct as_feature<tag::pot_tail_mean<LeftRight>(with_threshold_value)>\n{\n    typedef tag::pot_tail_mean<LeftRight> type;\n};\n\n// pot_tail_mean<LeftRight>(with_threshold_probability) -> pot_tail_mean_prob<LeftRight>\ntemplate<typename LeftRight>\nstruct as_feature<tag::pot_tail_mean<LeftRight>(with_threshold_probability)>\n{\n    typedef tag::pot_tail_mean_prob<LeftRight> type;\n};\n\n// weighted_pot_tail_mean<LeftRight>(with_threshold_value) -> weighted_pot_tail_mean<LeftRight>\ntemplate<typename LeftRight>\nstruct as_feature<tag::weighted_pot_tail_mean<LeftRight>(with_threshold_value)>\n{\n    typedef tag::weighted_pot_tail_mean<LeftRight> type;\n};\n\n// weighted_pot_tail_mean<LeftRight>(with_threshold_probability) -> weighted_pot_tail_mean_prob<LeftRight>\ntemplate<typename LeftRight>\nstruct as_feature<tag::weighted_pot_tail_mean<LeftRight>(with_threshold_probability)>\n{\n    typedef tag::weighted_pot_tail_mean_prob<LeftRight> type;\n};\n\n// for the purposes of feature-based dependency resolution,\n// pot_tail_mean<LeftRight> and pot_tail_mean_prob<LeftRight> provide\n// the same feature as tail_mean\ntemplate<typename LeftRight>\nstruct feature_of<tag::pot_tail_mean<LeftRight> >\n  : feature_of<tag::tail_mean>\n{\n};\n\ntemplate<typename LeftRight>\nstruct feature_of<tag::pot_tail_mean_prob<LeftRight> >\n  : feature_of<tag::tail_mean>\n{\n};\n\n// So that pot_tail_mean can be automatically substituted\n// with weighted_pot_tail_mean when the weight parameter is non-void.\ntemplate<typename LeftRight>\nstruct as_weighted_feature<tag::pot_tail_mean<LeftRight> >\n{\n    typedef tag::weighted_pot_tail_mean<LeftRight> type;\n};\n\ntemplate<typename LeftRight>\nstruct feature_of<tag::weighted_pot_tail_mean<LeftRight> >\n  : feature_of<tag::pot_tail_mean<LeftRight> >\n{\n};\n\n// So that pot_tail_mean_prob can be automatically substituted\n// with weighted_pot_tail_mean_prob when the weight parameter is non-void.\ntemplate<typename LeftRight>\nstruct as_weighted_feature<tag::pot_tail_mean_prob<LeftRight> >\n{\n    typedef tag::weighted_pot_tail_mean_prob<LeftRight> type;\n};\n\ntemplate<typename LeftRight>\nstruct feature_of<tag::weighted_pot_tail_mean_prob<LeftRight> >\n  : feature_of<tag::pot_tail_mean_prob<LeftRight> >\n{\n};\n\n}} // namespace boost::accumulators\n\n#endif\n", "meta": {"hexsha": "a78043fce290c388c011d99dec3b43674b46d4f6", "size": 7602, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/cinder/include/boost/accumulators/statistics/pot_tail_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/pot_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": 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/pot_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": 35.858490566, "max_line_length": 126, "alphanum_fraction": 0.6940278874, "num_tokens": 1733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4652136195626271}}
{"text": "#include <pybind11/stl.h>\n#include <pybind11/pybind11.h>\n#include <pybind11/eigen.h>\n#include <pybind11/numpy.h>\n\n#include <functional>\n\n#include <Eigen/Dense>\n\n#include \"logval.h\"\n\nnamespace py = pybind11;\n\n\ntypedef LogVal<double> LogValD;\nnamespace Eigen {\n    typedef Eigen::Matrix<LogValD, Dynamic, Dynamic> MatrixXlogd;\n    typedef Eigen::Matrix<float, Dynamic, Dynamic> MatrixXf;\n\n}\n\nEigen::MatrixXlogd to_log(const Eigen::MatrixXf& X) {\n    // the one-liner unaryExpr fails on windows. Maybe for good reason?\n    //return X.unaryExpr([](float f) { return LogValD((double) f, false); });\n    Eigen::MatrixXlogd res(X.rows(), X.cols());\n    for (py::ssize_t i = 0; i < X.rows(); ++i) {\n        for (py::ssize_t j = 0; j < X.cols(); ++j) {\n            res(i, j) = LogValD((double) X(i, j), false);\n        }\n    }\n    return res;\n}\n\nclass log_domain_lu {\npublic:\n    log_domain_lu(const Eigen::MatrixXf& X): lu(to_log(X)) { }\n\n    float logdet() {\n        return (float) lu.determinant().logabs();\n    }\n\n    auto inv() {\n        Eigen::MatrixXlogd Xinv = lu.inverse();\n        Eigen::MatrixXf Xinvf = Xinv.cast<double>().cast<float>();\n        return Xinvf;\n    }\n\nprivate:\n    Eigen::FullPivLU<Eigen::MatrixXlogd> lu;\n};\n\n\nclass batch_log_domain_lu {\npublic:\n    batch_log_domain_lu(\n        const py::array_t<float>& X,\n        const std::vector<int>& lengths,\n        const py::array_t<bool>& sign)\n    : lengths{ lengths }\n    {\n        auto X_acc = X.unchecked<3>();\n\n        // there are three possibilities for the sign:\n        // ndim=0 means sign is the same everywhere.\n        // ndim=2 means sign at k,i,j is sign(i,j)\n        // ndim=3 means sign at k,i,j is sign(k,i,j)\n        // Dynamically design a sign extraction function for ecah case.\n\n        std::function<bool (py::ssize_t, py::ssize_t, py::ssize_t)> _sign;\n        auto sign_buf = sign.request();\n\n        if (sign_buf.ndim == 0) {\n            auto sign_val = static_cast<bool*>(sign_buf.ptr)[0];\n            _sign = [sign_val](py::ssize_t k, py::ssize_t i, py::ssize_t j) { return sign_val; };\n        } else if (sign_buf.ndim == 2) {\n            auto sign_2d = sign.unchecked<2>();\n            _sign = [sign_2d](py::ssize_t k, py::ssize_t i, py::ssize_t j) { return sign_2d(i, j); };\n        } else if (sign_buf.ndim == 3) {\n            auto sign_3d = sign.unchecked<3>();\n            _sign = [sign_3d](py::ssize_t k, py::ssize_t i, py::ssize_t j) { return sign_3d(k, i, j); };\n        } else {\n            std::runtime_error(\"wrong dimension\");\n        }\n\n        batch_size = X_acc.shape(0);\n        dim1 = X_acc.shape(1);\n        dim2 = X_acc.shape(2);\n\n\n        for (py::ssize_t k = 0; k < batch_size; ++k) {\n\n            auto dk = lengths[k];\n\n            // pass 1. extract min\n            float xkmax = X_acc(k, 0, 0);\n            for (py::ssize_t i = 0; i < dk; ++i) {\n                for (py::ssize_t j = 0; j < dk; ++j) {\n                    xkmax = static_cast<double>(std::max(xkmax, X_acc(k, i, j)));\n                }\n            }\n\n            xmax.push_back(xkmax);\n\n            Eigen::MatrixXlogd Xk(dk, dk);\n            for (py::ssize_t i = 0; i < dk; ++i) {\n                for (py::ssize_t j = 0; j < dk; ++j) {\n                    // upcast to avoid underflow\n                    auto val = static_cast<double>(X_acc(k, i, j)) - xkmax;\n                    Xk(i, j) = LogValD(val, _sign(k, i, j));\n                }\n            }\n            lus.emplace_back(Xk);\n        }\n    }\n\n    py::array_t<float> logdet() {\n        auto res = py::array_t<float>({ batch_size });\n        auto res_acc = res.mutable_unchecked<1>();\n\n        for (py::ssize_t k = 0; k < batch_size; ++k) {\n            double val = lus[k].determinant().logabs() + lengths[k] * xmax[k];\n            res_acc(k) = static_cast<float>(val);\n        }\n\n        return res;\n    }\n\n    py::array_t<float> inv(bool zero_pad) {\n        auto res = py::array_t<float>({ batch_size, dim1, dim2 });\n\n        if (zero_pad) {\n            std::fill(res.mutable_data(), res.mutable_data() + res.size(), float{});\n        }\n\n        auto res_acc = res.mutable_unchecked<3>();\n        for (int k = 0; k < batch_size; ++k) {\n            auto dk = lengths[k];\n            LogValD exp_xkmax(xmax[k], false);\n            Eigen::MatrixXlogd Xinv = lus[k].inverse();\n            for (int i = 0; i < dk; ++i) {\n                for (int j = 0; j < dk; ++j) {\n                    LogValD exp_uij = Xinv(i, j);\n                    exp_uij /= exp_xkmax;\n                    res_acc(k, i, j) = static_cast<float>(exp_uij.as_float());\n                }\n            }\n        }\n\n        return res;\n    }\n\nprivate:\n    std::vector<Eigen::FullPivLU<Eigen::MatrixXlogd>> lus;\n    std::vector<int> lengths;\n    std::vector<float> xmax;\n    py::ssize_t batch_size;\n    py::ssize_t dim1;\n    py::ssize_t dim2;\n};\n\n\nPYBIND11_MODULE(lu, m) {\n\n    py::class_<log_domain_lu>(m, \"LogDomainLU\")\n        .def(py::init<const Eigen::MatrixXf&>(),\n             py::arg().noconvert().none(false))\n        .def(\"logdet\",\n             &log_domain_lu::logdet)\n        .def(\"inv\",\n             &log_domain_lu::inv,\n             py::return_value_policy::move);\n\n    py::class_<batch_log_domain_lu>(m, \"BatchLogDomainLU\")\n        .def(py::init<py::array_t<float>,\n                      std::vector<int>,\n                      py::array_t<bool>>(),\n             py::arg().noconvert(), py::arg().noconvert(), py::arg().noconvert())\n        .def(\"logdet\",\n             &batch_log_domain_lu::logdet,\n             py::return_value_policy::move)\n        .def(\"inv\",\n             &batch_log_domain_lu::inv,\n             py::arg(\"zero_pad\") = true,\n             py::return_value_policy::move);\n\n\n#ifdef VERSION_INFO\n    m.attr(\"__version__\") = VERSION_INFO;\n#else\n    m.attr(\"__version__\") = \"dev\";\n#endif\n}\n", "meta": {"hexsha": "1b7c1d02a3681c8fc3a2b44c44373e27d73637b6", "size": 5817, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "logdecomp/lu.cpp", "max_stars_repo_name": "ltl-uva/logdecomp", "max_stars_repo_head_hexsha": "167f9f8c8edd396b4f45f65eb8995175cbe3dd36", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-11-15T12:26:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T01:37:55.000Z", "max_issues_repo_path": "logdecomp/lu.cpp", "max_issues_repo_name": "ltl-uva/logdecomp", "max_issues_repo_head_hexsha": "167f9f8c8edd396b4f45f65eb8995175cbe3dd36", "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": "logdecomp/lu.cpp", "max_forks_repo_name": "ltl-uva/logdecomp", "max_forks_repo_head_hexsha": "167f9f8c8edd396b4f45f65eb8995175cbe3dd36", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1398963731, "max_line_length": 104, "alphanum_fraction": 0.5284510916, "num_tokens": 1657, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257126, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.46521361346207374}}
{"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#ifndef DP_HPP_\n#define DP_HPP_\n\n#include \"baseMeasure.hpp\"\n\n#include <armadillo>\n\nusing namespace std;\nusing namespace arma;\n\n\ndouble digamma(double x)\n{\n  // http://en.wikipedia.org/wiki/Digamma_function\n  double x_sq = x*x;\n  return ln(x) - 1.0/(2.0*x) - 1.0/(12.0*x_sq) + 1.0/(120.0*x_sq*x_sq) - 1.0/(252.0*x_sq*x_sq*x_sq);\n}\n\n\ntemplate<class U>\nclass DP\n{\npublic:\n  DP(const BaseMeasure<U>& base, double alpha)\n  : mH(base), mAlpha(alpha)\n  {};\n\n  ~DP()\n  { };\n\n  const BaseMeasure<U>& mH; // base measure\n  double mAlpha;\nprivate:\n};\n\ntemplate<class U>\nclass DP_var\n{\npublic:\n  DP_var(const BaseMeasure<U>& base, double alpha)\n   : mH(base), mAlpha(alpha)\n  {};\n\n  ~DP_var()\n  { };\n\n  Col<uint32_t> densityEst(const Mat<U>& x, uint32_t K0=10, uint32_t T0=10, uint32_t It=10)\n  {\n    \n    Col<uint32_t> z(x.n_rows);\n\n    uint32_t K=K0; // number of clusters\n\n    // variables\n    vector<double> gamma_1(K,0.0);\n    vector<double> gamma_2(K,0.0);\n    Row<U> tau_k1(x.n_cols);\n    double tau_k2;\n    Row<U> lambda_1(x.n_cols);\n    double lambda_2;\n    vector<double> S(K,0.0);\n    \n    // main loop\n    for(uint32_t tt=0; tt<It; ++tt)\n    {\n      double S_sum=0.0;\n      for(uint32_t k=0; k<K; ++k)\n      {\n        // TODO:  actually need to compute the exp of belows stuff => use different approximation!\n        S[k] = digamma(gamma_1[k]) - digamma(gamma_1[k] + gamma_2[k]);\n        for(uint32_t kt=0; kt<k-1; ++kt)\n          S[k] += digamma(gamma_2[kt]) - digamma(gamma_1[kt] + gamma_2[kt]);\n        //S[k] += ; // TODO: two remaingin expected values\n        S_sum += S[k];\n      }\n\n\n      for(uint32_t k=0; k<K; ++k)\n      {\n        double \n        gamma_k1=sum(z==k)+1.0;\n        gamma_k2=alpha;\n        for(uint32_t kj=k+1; kj<K; ++kj) gamma_k2 += sum(z==k);\n        //Row<U> tau_k1=lambda_1; //TODO: what is lambda_1 and lambda_2\n        tau_k2=lambda_2 + sum(z==k); // could reuse gamma_k1\n      }\n    }\n  }\n\n  const BaseMeasure<U>& mH; // base measure\n  double mAlpha;\nprivate:\n   \n\n};\n\n\n\n#endif /* DP_HPP_ */\n", "meta": {"hexsha": "7babfe2a0d0f009ade07b2b0429f5c1db0d367a0", "size": 2196, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/dp.hpp", "max_stars_repo_name": "jstraub/bnp", "max_stars_repo_head_hexsha": "11cd28b49e9cf1db96f349181aff57a17672b6a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T01:18:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-16T20:16:54.000Z", "max_issues_repo_path": "include/dp.hpp", "max_issues_repo_name": "jstraub/bnp", "max_issues_repo_head_hexsha": "11cd28b49e9cf1db96f349181aff57a17672b6a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-07-12T12:58:14.000Z", "max_issues_repo_issues_event_max_datetime": "2015-07-12T12:58:14.000Z", "max_forks_repo_path": "include/dp.hpp", "max_forks_repo_name": "jstraub/bnp", "max_forks_repo_head_hexsha": "11cd28b49e9cf1db96f349181aff57a17672b6a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-07-22T05:37:10.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-26T07:11:34.000Z", "avg_line_length": 21.1153846154, "max_line_length": 100, "alphanum_fraction": 0.5965391621, "num_tokens": 723, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096044278533, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.46521132610859267}}
{"text": "#include <armadillo>\n#include \"comfi.hpp\"\n#include \"viennacl/vector.hpp\"\n#include \"viennacl/matrix.hpp\"\n#include \"viennacl/compressed_matrix.hpp\"\n#include \"viennacl/linalg/prod.hpp\"\n#include \"viennacl/tools/timer.hpp\"\n#include \"viennacl/linalg/maxmin.hpp\"\n#include \"viennacl/forwards.h\"\n\nusing namespace viennacl::linalg;\n\nvcl_mat comfi::util::vec_to_mat(const vcl_vec &vec) {\n  arma::vec cpu_vec(vec.size());\n  viennacl::fast_copy(vec, cpu_vec);\n  arma::mat cpu_mat(cpu_vec);\n  vcl_mat return_mat(vec.size(), 1);\n  viennacl::copy(cpu_mat, return_mat);\n  return return_mat;\n}\n\nvcl_mat comfi::util::ot_vortex_ic(comfi::types::Context &ctx) {\n  const double b = 1.0/std::sqrt(4.0*arma::datum::pi),\n               n = 25.0/(36.0*arma::datum::pi),\n               p = 5.0/(12.0*arma::datum::pi);\n  arma::mat xn = arma::zeros<arma::mat>(ctx.num_of_grid(), ctx.num_of_eq);\n\n  std::cout << \"Building initial condition...\";\n  #pragma omp parallel for collapse(2)\n  for (arma::uword i=0; i<ctx.nx; i++) { for (arma::uword j=0; j<ctx.nz; j++) {\n    //indexing\n    const arma::uword ij = inds(i, j, ctx);\n\n    xn(ij, ctx.n_p) = n;\n    xn(ij, ctx.n_n) = n;\n    xn(ij, ctx.E_p) = p/(ctx.gammamono-1.0);\n    xn(ij, ctx.E_n) = p/(ctx.gammamono-1.0);\n    //xn(ij, ctx.Bp) = b;\n    xn(ij, ctx.Bx) = -b*std::sin(2.0*arma::datum::pi*j*ctx.dz);\n    xn(ij, ctx.Bz) = b*std::sin(4.0*arma::datum::pi*i*ctx.dx);\n    xn(ij, ctx.Vx) = -1.0*n*std::sin(2.0*arma::datum::pi*j*ctx.dz);\n    xn(ij, ctx.Vz) = n*std::sin(2.0*arma::datum::pi*i*ctx.dx);\n  }}\n\n  std::cout << \"Orszang-Tang Vortex Initial Conditions: (\" << ctx.nx << \",\" << ctx.nz <<\n               \") Size: \" << xn.size() << std::endl;\n\n  vcl_mat xn_vcl(xn.n_rows, xn.n_cols);\n  viennacl::copy(xn, xn_vcl);\n  return xn_vcl;\n}\n\nvcl_mat comfi::util::shock_tube_ic(comfi::types::Context &ctx) {\n  const double b = 0.75, b_l = 1.0, n_l = 1.0, p_l = 1.0, b_r = -1.0, n_r = 0.125, p_r = 0.1;\n  arma::mat xn = arma::zeros<arma::mat>(ctx.num_of_grid(), ctx.num_of_eq);\n\n  std::cout << \"Building initial condition...\";\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    const arma::uword ij = inds(i, j, ctx);\n\n    if (j > ctx.nz/2) {\n      xn(ij, ctx.n_p) = n_l;\n      xn(ij, ctx.n_n) = n_l;\n      xn(ij, ctx.E_n) = p_l/(ctx.gammamono-1.0);\n      xn(ij, ctx.E_p) = p_l/(ctx.gammamono-1.0);\n      xn(ij, ctx.Bx) = b_l;\n      xn(ij, ctx.Bz) = b;\n    } else {\n      xn(ij, ctx.E_n) = p_r/(ctx.gammamono-1.0);\n      xn(ij, ctx.E_p) = p_r/(ctx.gammamono-1.0);\n      xn(ij, ctx.n_p) = n_r;\n      xn(ij, ctx.n_n) = n_r;\n      xn(ij, ctx.Bx) = b_r;\n      xn(ij, ctx.Bz) = b;\n    }\n  }}\n  std::cout << \"Shock Tube (\" << ctx.nx << \",\" << ctx.nz <<\n               \") Size: \" << xn.size() << std::endl;\n\n  vcl_mat xn_vcl(xn.n_rows, xn.n_cols);\n  viennacl::copy(xn, xn_vcl);\n  return xn_vcl;\n}\n\nstd::string comfi::util::gettimestr()\n{\n      time_t rawtime;\n      struct tm * timeinfo;\n      char buffer[80];\n      time (&rawtime);\n      timeinfo = localtime(&rawtime);\n      strftime(buffer,80,\"%Y-%m-%d-%I-%M-%S\",timeinfo);\n      const std::string timestr(buffer);\n      return timestr;\n}\n\nvoid comfi::util::sendtolog(const std::string message, const std::string filename)\n{\n    std::ofstream logfile(filename.c_str(), std::ios::app);\n    if(logfile.is_open())\n    {\n        logfile << gettimestr() << \": \" << message << std::endl;\n    }\n    else std::cout << \"Could not open log file.\" << std::endl;\n\n    logfile.close();\n}\n\nbool comfi::util::save_solution(const vcl_mat &x0,\n                                comfi::types::Context &ctx,\n                                const std::string &data_name) {\n  bool success = true;\n  int timestep = ctx.time_step();\n\n  arma::mat savemat(x0.size1(), x0.size2());\n  viennacl::copy(x0, savemat);\n  static arma::mat gridmat(ctx.num_of_grid(), 2);\n  static bool created = false;\n  if (!created) {\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      arma::uword ij = inds(i, j, ctx);\n      gridmat(ij, 0) = i*ctx.dx*ctx.l_0;\n      gridmat(ij, 1) = j*ctx.dz*ctx.l_0;\n    }}\n  }\n\n  std::string folder = \"output/\";\n  std::string filename = folder + \"mhdsim.h5\";\n  std::string dataset = \"/\" + std::to_string(timestep) + \"/\" + data_name;\n  std::string posset = \"/\" + std::to_string(timestep) + \"/grid\";\n  savemat.save(arma::hdf5_name(filename, dataset, arma::hdf5_opts::append+arma::hdf5_opts::trans));\n  gridmat.save(arma::hdf5_name(filename, posset, arma::hdf5_opts::append+arma::hdf5_opts::trans));\n\n  return success;\n}\n\nvoid comfi::util::interpret_arguments(comfi::types::Settings &settings, int argc, char** argv) {\n  if (argc != 1) // if arguments were passed\n  {\n    // parse arguments\n    for(int i=1; i < argc; i++)\n    {\n      if(argv[i][0] == '-') // if starts with hyphen\n      {\n        if (i != argc-1) {\n          std::string argument = argv[i];\n          if (argument == \"-max_time_steps\") {\n            std::string value = argv[i+1];\n            settings.max_time_steps = stoi(value,nullptr,10);\n          } else if (argument == \"-max_time\") {\n            std::string value = argv[i+1];\n            settings.max_time = std::stod(value);\n          } else if (argument == \"-save_dt\") {\n            std::string value = argv[i+1];\n            settings.save_dt = std::atof(value.c_str());\n          } else if (argument == \"-save_dn\") {\n            std::string value = argv[i+1];\n            settings.save_dn = stoi(value,nullptr,10);\n          } else if (argument == \"-tolerance\")\n          {\n            std::string value = argv[i+1];\n            settings.tolerance = std::stod(value);\n          } else if (argument == \"-leftbc\") {\n            // TODO\n            std::string value = argv[i+1];\n          } else if (argument == \"-rightbc\") {\n            // TODO\n            std::string value = argv[i+1];\n          } else if (argument == \"-upbc\") {\n            // TODO\n            std::string value = argv[i+1];\n          } else if (argument == \"-downbc\") {\n            // TODO\n            std::string value = argv[i+1];\n          } else if (argument == \"-restart\") {\n            settings.restart = true;\n          } else {\n            std::cerr << \"The command line option \\'\" << argument << \"\\' is not recognized. Using defaults for unspecified parameters.\" << std::endl;\n          }\n        }\n      }\n    }\n  }\n}\n\ndouble comfi::util::getmaxV(const vcl_mat &x0, comfi::types::Context &ctx) {\n  using namespace viennacl::linalg;\n  const vcl_vec Np = viennacl::column(x0, ctx.n_p);\n  const vcl_vec Nn = viennacl::column(x0, ctx.n_n);\n  const vcl_vec NVx = viennacl::column(x0, ctx.Vx);\n  const vcl_vec NUx = viennacl::column(x0, ctx.Ux);\n  const vcl_vec NUz = viennacl::column(x0, ctx.Uz);\n  const vcl_vec NVz = viennacl::column(x0, ctx.Vz);\n  const vcl_vec local_p_x_vec = element_fabs(element_div(NVx, Np));\n  const double local_p_x = viennacl::linalg::max(local_p_x_vec);\n  const vcl_vec local_p_z_vec = element_fabs(element_div(NVz, Np));\n  const double local_p_z = viennacl::linalg::max(local_p_z_vec);\n  const vcl_vec local_n_x_vec = element_fabs(element_div(NUx, Nn));\n  const double local_n_x = viennacl::linalg::max(local_n_x_vec);\n  const vcl_vec local_n_z_vec = element_fabs(element_div(NUz, Nn));\n  const double local_n_z = viennacl::linalg::max(local_n_z_vec);\n  std::cout << \"Max local (p): (\" << local_p_x << \",\" << local_p_z << \") | \";\n  std::cout << \"Max local (n): (\" << local_n_x << \",\" << local_n_z << \")\" << std::endl;\n  const double fast_p_x = viennacl::linalg::max(viennacl::column(comfi::routines::fast_speed_x(x0, ctx), 0));\n  const double fast_p_z = viennacl::linalg::max(viennacl::column(comfi::routines::fast_speed_z(x0, ctx), 0));\n  std::cout << \"Max fast (p): (\" << fast_p_x << \",\" << fast_p_z << \") | \";\n  const double sound_n_x = viennacl::linalg::max(viennacl::column(comfi::routines::sound_speed_n(x0, ctx), 0));\n  const double sound_n_z = viennacl::linalg::max(viennacl::column(comfi::routines::sound_speed_n(x0, ctx), 0));\n  std::cout << \"Max sound speed (n): (\" << sound_n_x << \",\" << sound_n_z << \")\";\n  std::cout << std::endl;\n\n  /*\n  return std::max(std::max(std::max(local_p_x, fast_p_x), std::max(local_p_z, fast_p_z)),\n                  std::max(std::max(sound_n_x, local_n_x), std::max(sound_n_z, local_n_z)));\n                  */\n  return std::max(std::max(local_p_x+fast_p_x, local_p_z+fast_p_z),\n                  std::max(sound_n_x+local_n_x, sound_n_z+local_n_z));\n}\n\n/*\nvim: tabstop=2\nvim: shiftwidth=2\nvim: smarttab\nvim: expandtab\n*/\n", "meta": {"hexsha": "607b837d188c5e39f4c4a529edcd1168c1a2b17e", "size": 8561, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/util.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/util.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/util.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": 37.548245614, "max_line_length": 149, "alphanum_fraction": 0.5885994627, "num_tokens": 2780, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.46504809702132455}}
{"text": "#ifdef HOPS_CLP_FOUND\n\n#include <coin/ClpPackedMatrix.hpp>\n#include <coin/ClpSimplex.hpp>\n\n#include <Eigen/Sparse>\n\n#include <hops/LinearProgram/LinearProgramClpImpl.hpp>\n#include <hops/LinearProgram/LinearProgramStatus.hpp>\n\nnamespace {\n    hops::LinearProgramStatus parseClpStatus(int returnCode) {\n        switch (returnCode) {\n            case 0:\n                return hops::LinearProgramStatus::OPTIMAL;\n            case 1:\n                return hops::LinearProgramStatus::INFEASIBLE;\n            case 2:\n                return hops::LinearProgramStatus::UNBOUNDED;\n            default:\n                return hops::LinearProgramStatus::ERROR;\n        }\n    }\n\n    bool isInequalityRedundant(const Eigen::MatrixXd &A,\n                               const Eigen::VectorXd &b,\n                               unsigned int index,\n                               double tolerance) {\n        Eigen::VectorXd bTemp = b;\n        bTemp(index) += 1.0;\n\n        auto result = hops::LinearProgramClpImpl(A, bTemp).solve(A.row(index));\n\n        if (result.status != hops::LinearProgramStatus::OPTIMAL) {\n            return false;\n        }\n\n        return result.objectiveValue <= b(index) + tolerance;\n    }\n\n}\n\nhops::LinearProgramClpImpl::LinearProgramClpImpl(const Eigen::MatrixXd &A, const Eigen::VectorXd &b) :\n        LinearProgram(A, b) {\n    if (A.cols() > std::numeric_limits<int>::max() || A.cols() < std::numeric_limits<int>::min()) {\n        throw std::runtime_error(\n                \"Objective has more columns, than can fit into an integer, making it incompatible to CLP\");\n    }\n    if (A.rows() > std::numeric_limits<int>::max() || A.rows() < std::numeric_limits<int>::min()) {\n        throw std::runtime_error(\n                \"Objective has more rows, than can fit into an integer, making it incompatible to CLP\");\n    }\n\n    std::vector<int> rowIndices;\n    std::vector<int> columnIndices;\n    std::vector<double> values;\n    Eigen::SparseMatrix<double> sparseA = A.sparseView();\n    for (long i = 0; i < A.outerSize(); ++i) {\n        for (Eigen::SparseMatrix<double>::InnerIterator it(sparseA, i); it; ++it) {\n            if (it.value() != 0) {\n                rowIndices.emplace_back(it.row());\n                columnIndices.emplace_back(it.col());\n                values.emplace_back(it.value());\n            }\n        }\n    }\n\n    CoinPackedMatrix matrix(false, rowIndices.data(), columnIndices.data(), values.data(), values.size());\n\n    Eigen::VectorXd rowLower = Eigen::VectorXd::Constant(b.rows(), -DBL_MAX);\n    Eigen::VectorXd colLower = Eigen::VectorXd::Constant(A.cols(), -DBL_MAX);\n    Eigen::VectorXd colUpper = Eigen::VectorXd::Constant(A.cols(), DBL_MAX);\n\n    model.loadProblem(matrix, colLower.data(), colUpper.data(), nullptr,\n                      rowLower.data(), b.data());\n    model.setOptimizationDirection(-1.);\n    model.scaling(4);\n    model.setLogLevel(0);\n}\n\nhops::LinearProgramClpImpl::LinearProgramClpImpl(const hops::LinearProgramClpImpl &other) :\n        LinearProgram(other.A, other.b),\n        model(other.model) {}\n\nhops::LinearProgramClpImpl &hops::LinearProgramClpImpl::operator=(const hops::LinearProgramClpImpl &other) {\n    this->A = other.A;\n    this->b = other.b;\n    this->model = other.model;\n    return *this;\n}\n\nhops::LinearProgramSolution hops::LinearProgramClpImpl::solve(const Eigen::VectorXd &objective) const {\n    for (int i = 0; i < static_cast<int>(objective.rows()); ++i) {\n        model.setObjectiveCoefficient(i, objective(i));\n    }\n    model.primal();\n    model.checkSolution();\n    model.checkUnscaledSolution();\n\n    return LinearProgramSolution(-model.rawObjectiveValue(), // - due to optimization direction internally\n                                 Eigen::Map<Eigen::VectorXd>(model.primalColumnSolution(), objective.rows()),\n                                 parseClpStatus(model.status()));\n}\n\nstd::tuple<Eigen::MatrixXd, Eigen::VectorXd> hops::LinearProgramClpImpl::removeRedundantConstraints(double tolerance) {\n    if (A.rows() <= 1) {\n        return std::make_tuple(A, b);\n    }\n\n    for (int i = 0; i < A.rows(); ++i) {\n        int numRows = A.rows();\n        // Try to remove ith inequality\n        if (isInequalityRedundant(A, b, i, tolerance)) {\n            if (i != numRows - 1) {\n                // Swap the row which is going to be removed with the\n                // last row\n                A.row(i).swap(A.row(numRows - 1));\n                double temp = b(i);\n                b(i) = b(numRows - 1);\n                b(numRows - 1) = temp;\n                i--; // resets index after swap\n            }\n\n            // Remove the last row\n            A.conservativeResize(numRows - 1, Eigen::NoChange);\n            b.conservativeResize(numRows - 1);\n        }\n    }\n    *this = LinearProgramClpImpl(A, b);\n    return std::make_tuple(A, b);\n}\n\nhops::LinearProgramSolution hops::LinearProgramClpImpl::computeChebyshevCenter() const {\n    //Extend system by dimension for radius\n    const long numberOfRows = A.rows();\n    const long numberOfColumns = A.cols();\n    Eigen::MatrixXd A_ext = A;\n    Eigen::MatrixXd l_col(numberOfRows + 1, 1);\n    l_col << A.rowwise().norm(), -1;\n    A_ext.conservativeResize(numberOfRows + 1, numberOfColumns + 1);\n    A_ext.row(numberOfRows) = Eigen::VectorXd::Zero(numberOfColumns + 1);\n    A_ext.col(numberOfColumns) = l_col;\n    Eigen::VectorXd b_ext = b;\n    b_ext.conservativeResize(numberOfRows + 1);\n    b_ext(numberOfRows) = 0;\n\n    //make objective\n    Eigen::VectorXd obj = Eigen::VectorXd::Zero(numberOfColumns + 1);\n    obj(numberOfColumns) = 1;\n\n    LinearProgramSolution chebyshevSolution = LinearProgramClpImpl(A_ext, b_ext).solve(obj);\n    chebyshevSolution.optimalParameters.conservativeResize(A.cols());\n    return chebyshevSolution;\n}\n\nstd::vector<long> hops::LinearProgramClpImpl::computeUnconstrainedDimensions() const {\n    std::vector<long> directions;\n    for (long i = 0; i < A.cols(); ++i) {\n        Eigen::VectorXd objective = Eigen::VectorXd::Zero(A.cols());\n        objective(i) = 1.0;\n        for (int j = 0; j < static_cast<int>(objective.rows()); ++j) {\n            model.setObjectiveCoefficient(j, objective(j));\n        }\n        auto forwardSolution = solve(objective);\n        if (forwardSolution.status != hops::LinearProgramStatus::OPTIMAL) {\n            directions.push_back(i + 1);\n        }\n\n        auto backwardSolution = solve(-objective);\n        if (backwardSolution.status != hops::LinearProgramStatus::OPTIMAL) {\n            directions.push_back(-i - 1);\n        }\n    }\n    return directions;\n}\n\nstd::tuple<Eigen::MatrixXd, Eigen::VectorXd>\nhops::LinearProgramClpImpl::addBoxConstraintsToUnconstrainedDimensions(double lb, double ub) {\n    std::vector<long> unconstrainedDimensions = computeUnconstrainedDimensions();\n\n    for (const auto &unconstrainedDimension : unconstrainedDimensions) {\n        A.conservativeResize(A.rows() + 1, A.cols());\n        A.row(A.rows() - 1) = Eigen::VectorXd::Zero(A.cols());\n        b.conservativeResize(b.rows() + 1);\n        if (unconstrainedDimension > 0) {\n            A(A.rows() - 1, unconstrainedDimension - 1) = 1;\n            b(b.rows() - 1) = ub;\n        } else {\n            A(A.rows() - 1, -unconstrainedDimension - 1) = -1;\n            b(b.rows() - 1) = lb;\n        }\n    }\n    *this = LinearProgramClpImpl(A, b);\n    return std::make_tuple(A, b);\n}\n\n#endif //HOPS_CLP_FOUND\n", "meta": {"hexsha": "20b037034ddffb76d1c1e2f0267412afdc1e12c3", "size": 7391, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "include/hops/LinearProgram/LinearProgramClpImpl.cpp", "max_stars_repo_name": "modsim/hops", "max_stars_repo_head_hexsha": "4285dd75a07dd844295440a0756b3ba25f5819ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2020-11-26T05:13:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T02:08:40.000Z", "max_issues_repo_path": "include/hops/LinearProgram/LinearProgramClpImpl.cpp", "max_issues_repo_name": "modsim/hops", "max_issues_repo_head_hexsha": "4285dd75a07dd844295440a0756b3ba25f5819ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-02-20T23:16:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-20T23:16:34.000Z", "max_forks_repo_path": "include/hops/LinearProgram/LinearProgramClpImpl.cpp", "max_forks_repo_name": "modsim/hops", "max_forks_repo_head_hexsha": "4285dd75a07dd844295440a0756b3ba25f5819ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.3282828283, "max_line_length": 119, "alphanum_fraction": 0.6115545934, "num_tokens": 1826, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.46504809702132455}}
{"text": "#ifndef CLASSIC_GRID_HPP\n#define CLASSIC_GRID_HPP\n\n#include <array>\n#include <tuple>\n#include <unordered_map>\n#include <vector>\n\n#include <boost/container_hash/hash.hpp>\n\n#include \"distributions/angular_gauss.hpp\"\n#include \"types/types.hpp\"\n\nclass ClassicGrid {\n    int div;\n    AngularGauss* distr;\n\n    // points is a map of (i, j) pairs, that are indices of grid points, to\n    // the indicies of the same grid's points in Cartesian coordinates'\n    std::unordered_map<ClassicGridPoint, int, boost::hash<ClassicGridPoint>> points;\n\n    // cartesian_points is a vector of grid's points in Cartesian coordinates\n    std::vector<CoordsOfPoint> cartesian_points;\n\n    // values is an evaluated function on grid, value in i'th position\n    // corresponds to the function's value of i'th point in cartesian_points\n    // vector\n    std::vector<double> values;\n\n    // trapeziums are the elementary objects of which the grid consists. They\n    // are stored as vectors of columns of trapeziums on a sphere.\n    std::vector<std::vector<Trapezium>> trapeziums;\n\n    void GenerateGridAndEvaluateFunc(void);\n    void EvaluateFuncRoutine(int lower_bound, int upper_bound);\n\n    std::tuple<int, TrapeziumIndex> GetNextTrapeziumIndex(int previous_side, const TrapeziumIndex& previous) const;\n    TrapeziumIndex GetUpperTrapeziumIndex(const TrapeziumIndex& previous) const;\n    TrapeziumIndex GetLowerTrapeziumIndex(const TrapeziumIndex& previous) const;\n    TrapeziumIndex GetLeftTrapeziumIndex(const TrapeziumIndex& previous) const;\n    TrapeziumIndex GetRightTrapeziumIndex(const TrapeziumIndex& previous) const;\n\n    // FindIntersection uses linear interpolation to find an intersection point\n    // with value c between vertices with values a and b, where x1 = f^(-1)(a),\n    // x2 = f^(-1)(b), sign((a - c) * (b - c)) must be -1.\n    CoordsOfPoint FindIntersection(const CoordsOfPoint& x1, const CoordsOfPoint& x2, double a, double b, double c) const;\n\n    // ProcessSegment processes trapezium using marching square algorithm and\n    // returns last processed trapezium side and point.\n    std::tuple<int, CoordsOfPoint> ProcessSegment(const Trapezium& trapezium, int index, int start_side, double iso_value);\n\n    // GetMarchingSquareIndex returns the trapezium index needed for marching squares algorithm.\n    // See Lookup Table here: https://en.wikipedia.org/wiki/Marching_squares#Basic_algorithm\n    int GetMarchingSquareIndex(const Trapezium& trapezium, double value);\n\npublic:\n    // ClassicGrid creates new classic grid with bandwidth grid_div and\n    // function distr on it\n    ClassicGrid(int grid_div, AngularGauss* distr);\n\n    // Func returns function on grid\n    const AngularGauss* Func(void) const;\n\n    // GetCoordsOfPoint converts spherical coordinates of a point to Cartesian\n    static CoordsOfPoint GetCoordsOfPoint(const AnglesOfPoint& point);\n    // GetAnglesOfPoint converts Cartesian coordinates of a point to spherical\n    static AnglesOfPoint GetAnglesOfPoint(const CoordsOfPoint& point);\n\n    // GetIsolineCoords returns the coordinates of the points for the function\n    // isoline with a value equal to iso_value.\n    // It uses marching squares algorithm, see more info:\n    // https://en.wikipedia.org/wiki/Marching_squares\n    std::vector<CoordsOfPoint> GetIsolineCoords(double iso_value);\n};\n\n#endif // CLASSIC_GRID_HPP\n", "meta": {"hexsha": "d488941e460330e9a3d3d3f428be8aa98f053020", "size": 3350, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "server/grids/classic_grid.hpp", "max_stars_repo_name": "Bychin/uniformization-tool-on-sphere", "max_stars_repo_head_hexsha": "f5068d792aadb0dd8e694c348d068b6a8bcd8888", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-24T08:30:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-24T08:30:58.000Z", "max_issues_repo_path": "server/grids/classic_grid.hpp", "max_issues_repo_name": "Bychin/uniformization-tool-on-sphere", "max_issues_repo_head_hexsha": "f5068d792aadb0dd8e694c348d068b6a8bcd8888", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "server/grids/classic_grid.hpp", "max_forks_repo_name": "Bychin/uniformization-tool-on-sphere", "max_forks_repo_head_hexsha": "f5068d792aadb0dd8e694c348d068b6a8bcd8888", "max_forks_repo_licenses": ["Apache-2.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.5064935065, "max_line_length": 123, "alphanum_fraction": 0.7552238806, "num_tokens": 821, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4650480970213245}}
{"text": "/* Copyright (C) 2021 Intel Corporation\n * SPDX-License-Identifier: Apache-2.0\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// This program performs basic operations n times and is used for profiling.\n\n#include <iostream>\n\n#include <helib/helib.h>\n#include <helib/EncryptedArray.h>\n#include <helib/ArgMap.h>\n#include <NTL/BasicThreadPool.h>\n\nvoid add(helib::Ctxt& ctxt, int iter)\n{\n  for (int i = 0; i < iter; ++i) {\n    // Create tmp to avoid noise growth.\n    helib::Ctxt tmp(ctxt);\n    tmp += ctxt;\n  }\n}\n\nvoid mult(helib::Ctxt& ctxt, int iter)\n{\n  for (int i = 0; i < iter; ++i) {\n    // Create tmp to avoid noise growth.\n    helib::Ctxt tmp(ctxt);\n    tmp *= ctxt;\n  }\n}\n\nvoid rotate(helib::Ctxt& ctxt, const helib::EncryptedArray& ea, int iter)\n{\n  for (int i = 0; i < iter; ++i) {\n    // Create tmp to avoid noise growth.\n    helib::Ctxt tmp(ctxt);\n    ea.rotate(tmp, 1);\n  }\n}\n\nvoid scalarAdd(helib::Ctxt ctxt, int iter)\n{\n  for (int i = 0; i < iter; ++i) {\n    ctxt += 1l;\n  }\n}\n\nvoid scalarMult(helib::Ctxt ctxt, int iter)\n{\n  for (int i = 0; i < iter; ++i) {\n    ctxt *= 2l;\n  }\n}\n\nint main(int argc, char* argv[])\n{\n  // Plaintext prime modulus\n  unsigned long p = 131;\n  // Cyclotomic polynomial - defines phi(m)\n  unsigned long m = 130; // this will give 48 slots\n  // Hensel lifting (default = 1)\n  unsigned long r = 1;\n  // Number of bits of the modulus chain\n  unsigned long bits = 1000;\n  // Number of columns of Key-Switching matrix (default = 2 or 3)\n  unsigned long c = 2;\n  // Size of NTL thread pool (default =1)\n  unsigned long nthreads = 1;\n\n  helib::ArgMap()\n      .optional()\n      .named()\n      .arg(\"m\", m, \"Cyclotomic polynomial ring\")\n      .arg(\"p\", p, \"Plaintext prime modulus\")\n      .arg(\"r\", r, \"Hensel lifting\")\n      .arg(\"bits\", bits, \"# of bits in the modulus chain\")\n      .arg(\"c\", c, \"# fo columns of Key-Switching matrix\")\n      .arg(\"nthreads\", nthreads, \"Size of NTL thread pool\")\n      .parse(argc, argv);\n\n  // set NTL Thread pool size\n  if (nthreads > 1)\n    NTL::SetNumThreads(nthreads);\n\n  helib::Context context = helib::ContextBuilder<helib::BGV>()\n                               .m(m)\n                               .p(p)\n                               .r(r)\n                               .bits(bits)\n                               .c(c)\n                               .build();\n\n  helib::SecKey secret_key = helib::SecKey(context);\n  secret_key.GenSecKey();\n  helib::addSome1DMatrices(secret_key);\n  const helib::PubKey& public_key = secret_key;\n  const helib::EncryptedArray& ea = context.getEA();\n\n  std::cout << std::endl;\n  context.printout();\n\n  long nslots = ea.size();\n\n  helib::PtxtArray pa(context);\n  pa.random();\n  helib::Ctxt ctxt(public_key);\n  pa.encrypt(ctxt);\n\n  int opt = 0;\n  std::cout << \"What operation(s) do you want to run? [0:all, 1:add, 2:mult, \"\n               \"3:rotate, 4:scalarAdd, 5:scalarMult]: \";\n  std::cin >> opt;\n\n  int iter = 0;\n  std::cout << \"How many iterations?: \";\n  std::cin >> iter;\n  iter = (iter < 1) ? 10 : iter;\n\n  std::cout << \"Option: \" << opt << \", \" << iter << \" times.\\n\";\n\n  switch (opt) {\n  case 0:\n    std::cout << \"Running option \" << opt << \": all operations...\\n\";\n    add(ctxt, iter);\n    mult(ctxt, iter);\n    rotate(ctxt, ea, iter);\n    scalarAdd(ctxt, iter);\n    scalarMult(ctxt, iter);\n    std::cout << \"Done!\\n\";\n    break;\n  case 1:\n    std::cout << \"Running option \" << opt << \": additions...\\n\";\n    add(ctxt, iter);\n    std::cout << \"Done!\\n\";\n    break;\n  case 2:\n    std::cout << \"Running option \" << opt << \": multiplications...\\n\";\n    mult(ctxt, iter);\n    std::cout << \"Done!\\n\";\n    break;\n  case 3:\n    std::cout << \"Running option \" << opt << \": rotations...\\n\";\n    rotate(ctxt, ea, iter);\n    std::cout << \"Done!\\n\";\n    break;\n  case 4:\n    std::cout << \"Running option \" << opt << \": scalar additions...\\n\";\n    scalarAdd(ctxt, iter);\n    std::cout << \"Done!\\n\";\n    break;\n  case 5:\n    std::cout << \"Running option \" << opt << \": scalar multiplications...\\n\";\n    scalarMult(ctxt, iter);\n    std::cout << \"Done!\\n\";\n    break;\n  default:\n    std::cout << \"Received invalid option: \" << opt << std::endl;\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "212674d9433fa81db101ca72e50a4eb981923aff", "size": 4716, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "misc/profiling/basic_circuit.cpp", "max_stars_repo_name": "jlakness-intel/HElib", "max_stars_repo_head_hexsha": "fe1dc6c0625904ba9bd31d9d578dd535cd632de1", "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": "misc/profiling/basic_circuit.cpp", "max_issues_repo_name": "jlakness-intel/HElib", "max_issues_repo_head_hexsha": "fe1dc6c0625904ba9bd31d9d578dd535cd632de1", "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": "misc/profiling/basic_circuit.cpp", "max_forks_repo_name": "jlakness-intel/HElib", "max_forks_repo_head_hexsha": "fe1dc6c0625904ba9bd31d9d578dd535cd632de1", "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": 27.5789473684, "max_line_length": 78, "alphanum_fraction": 0.5869380831, "num_tokens": 1379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.46504809702132444}}
{"text": "#include <frovedis.hpp>\n#include <frovedis/matrix/crs_matrix.hpp>\n\n#include <boost/program_options.hpp>\n\nusing namespace boost;\nusing namespace frovedis;\nusing namespace std;\n\ntemplate <class T>\ncrs_matrix_local<T> calc_tf(crs_matrix_local<T>& mat) {\n  crs_matrix_local<T> ret;\n  ret.val.resize(mat.val.size());\n  ret.idx = mat.idx;\n  ret.off = mat.off;\n  ret.local_num_col = mat.local_num_col;\n  ret.local_num_row = mat.local_num_row;\n  for(size_t row = 0; row < mat.local_num_row; row++) {\n    T sum = 0;\n    for(size_t col = mat.off[row]; col < mat.off[row + 1]; col++) {\n      sum += mat.val[col];\n    }\n    T norm = 1.0/sum;\n    for(size_t col = mat.off[row]; col < mat.off[row + 1]; col++) {\n      ret.val[col] = mat.val[col] * norm;\n    }\n  }\n  return ret;\n}\n\ntemplate <class T>\nvector<T> local_df(crs_matrix_local<T>& mat) {\n  vector<T> ret(mat.local_num_col);\n  T* retp = &ret[0];\n  size_t* idxp = &mat.idx[0];\n\n  for(size_t row = 0; row < mat.local_num_row; row++) {\n#pragma cdir nodep\n    for(size_t col = mat.off[row]; col < mat.off[row + 1]; col++) {\n      if(idxp[col] >= mat.local_num_col) {\n        std::cerr << \"local_num_col = \" << mat.local_num_col\n                  << \", idxp[col] = \" << idxp[col] << std::endl;\n        throw std::runtime_error(\"error\");\n      }\n      retp[idxp[col]]++;\n    }\n  }\n  return ret;\n}\n\ntemplate <class T>\nvector<T> reduce_df(const vector<T>& l, const vector<T>& r) {\n  vector<T> ret(l.size());\n  for(size_t i = 0; i < l.size(); i++) {\n    ret[i] = l[i] + r[i];\n  }\n  return ret;\n}\n\ntemplate <class T>\nvector<T> calc_idf(crs_matrix<T>& mat) {\n  double total_doc = static_cast<double>(mat.num_row);\n  auto local_dfs = mat.data.map(local_df<T>);\n  auto df = local_dfs.reduce(reduce_df<T>);\n  vector<T> idf(df.size());\n  for(size_t i = 0; i < df.size(); i++) {\n    idf[i] = log(total_doc / static_cast<double>(df[i]));\n  }\n  return idf;\n}\n\ntemplate <class T>\nvoid mul_idf(crs_matrix_local<T>& mat, vector<T>& idf) {\n  T* matvalp = &mat.val[0];\n  T* idfp = &idf[0];\n  size_t* idxp = &mat.idx[0];\n  for(size_t row = 0; row < mat.local_num_row; row++) {\n#pragma cdir nodep\n    for(size_t col = mat.off[row]; col < mat.off[row + 1]; col++) {\n      matvalp[col] *= idfp[idxp[col]];\n    }\n  }\n}\n\n/*\n  assume that document x term matrix\n  (i.e. document is row, term is column)\n\n  Though TF-IDF has vaious definitions, we adopted definition in\n  Japanese wikipedia (2015/8/4)\n  tf: number of term / all number of terms in the doc\n  idf: log (number of all docs / number of docs that includes the term)\n */\ntemplate <class T>\nvoid tfidf(const string& input, const string& output) {\n  auto mat = make_crs_matrix_load<T>(input);\n  crs_matrix<T> tf(mat.data.map(calc_tf<T>));\n  auto idf = calc_idf<T>(mat);\n  auto bcast_idf = make_node_local_broadcast(idf);\n  tf.data.mapv(mul_idf<T>, bcast_idf);\n  tf.save(output);\n}\n\nint main(int argc, char* argv[]){\n  use_frovedis use(argc, argv);\n\n  using namespace boost::program_options;\n\n  options_description opt(\"option\");\n  opt.add_options()\n    (\"input,i\", value<string>(), \"input matrix file\")\n    (\"output,o\", value<string>(), \"output matrix file\");\n\n  variables_map argmap;\n  store(command_line_parser(argc,argv).options(opt).allow_unregistered().\n        run(), argmap);\n  notify(argmap);\n\n  string input, output;\n  \n  if(argmap.count(\"input\")){\n    input = argmap[\"input\"].as<string>();\n  } else {\n    cerr << \"input matrix file is not specified\" << endl;\n    exit(1);\n  }\n\n  if(argmap.count(\"output\")){\n    output = argmap[\"output\"].as<string>();\n  } else {\n    cerr << \"output matrix file is not specified\" << endl;\n    exit(1);\n  }\n\n  tfidf<double>(input, output);\n}\n", "meta": {"hexsha": "5af2b98943afae19f2b2023972d31b5522bed65f", "size": 3655, "ext": "cc", "lang": "C++", "max_stars_repo_path": "samples/document_matrix/tfidf.cc", "max_stars_repo_name": "XpressAI/frovedis", "max_stars_repo_head_hexsha": "bda0f2c688fb832671c5b542dd8df1c9657642ff", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 63.0, "max_stars_repo_stars_event_min_datetime": "2018-06-21T14:11:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T11:24:36.000Z", "max_issues_repo_path": "samples/document_matrix/tfidf.cc", "max_issues_repo_name": "XpressAI/frovedis", "max_issues_repo_head_hexsha": "bda0f2c688fb832671c5b542dd8df1c9657642ff", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2018-09-22T14:01:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-27T16:11:05.000Z", "max_forks_repo_path": "samples/document_matrix/tfidf.cc", "max_forks_repo_name": "XpressAI/frovedis", "max_forks_repo_head_hexsha": "bda0f2c688fb832671c5b542dd8df1c9657642ff", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2018-08-23T15:59:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T06:47:22.000Z", "avg_line_length": 26.6788321168, "max_line_length": 73, "alphanum_fraction": 0.6279069767, "num_tokens": 1091, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255928, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.4650480903867934}}
{"text": "#include \"compi.hpp\"\n\n#include <complex>\n#include <unordered_map>\n#include <algorithm>\n#include <utility>\n\n#include <boost/math/quadrature/gauss_kronrod.hpp>\n#include <boost/math/tools/precision.hpp>\n\nextern \"C\" {\n    #include \"integration_routines.h\"\n}\n\n#include \"integration_routines_template.hpp\"\n#include \"IntegrandFunctionWrapper.hpp\"\n#include \"utils.hpp\"\n\n\n\n\nstruct GaussKronrodParameters: public RoutineParametersBase{\n    Real x_min;\n    Real x_max;\n    unsigned points = 31;\n\n    GaussKronrodParameters(PyObject* routine_args, PyObject* routine_kwargs){\n        constexpr std::array<const char*,0> dumby_arg = {};\n        constexpr std::array<const char*,1> keyword_only_args = {\"points\"};\n        constexpr auto keywords = generate_keyword_list<IntegralRange::finite>(dumby_arg,dumby_arg,keyword_only_args);\n\n        if(!PyArg_ParseTupleAndKeywords(routine_args,routine_kwargs,\"Odd|OO$pIdI\",const_cast<char**>(keywords.data()),\n                &integrand,&x_min,&x_max,\n                &args,&kw,\n                &full_output, &max_levels,&tolerance,&points)){\n            throw could_not_parse_arguments(\"Unable to parse python arguments to C variables\");\n        }\n    }\n\n};\n\nGaussKronrodParameters::result_type run_integration_routine(const compi_internal::IntegrandFunctionWrapper& f, const GaussKronrodParameters& parameters){\n    using std::complex;\n    using namespace compi_internal;\n    using boost::math::quadrature::gauss_kronrod;\n    using IntegrationRoutine = complex<Real>(*)(IntegrandFunctionWrapper, Real, Real, unsigned, Real, Real*, Real*);\n\n    // The possible tempates for the different allowed numbers of divisions are instasiated, \n    // so that the Python runtime can select which one to use\n    static const std::unordered_map<unsigned,IntegrationRoutine> integration_routines{{15,gauss_kronrod<Real,15>::integrate},\n                                                                                      {31,gauss_kronrod<Real,31>::integrate},\n                                                                                      {41,gauss_kronrod<Real,41>::integrate},\n                                                                                      {51,gauss_kronrod<Real,51>::integrate},\n                                                                                      {61,gauss_kronrod<Real,61>::integrate}\n                                                                                     };\n\n    GaussKronrodParameters::result_type result;\n\n    try{\n        result.result = integration_routines.at(parameters.points)(f,parameters.x_min,parameters.x_max,parameters.max_levels,parameters.tolerance,&(result.err),&(result.l1));\n    } catch (const std::out_of_range& e){\n        PyErr_SetString(PyExc_ValueError,\"Invalid number of points for gauss_kronrod\");\n        throw unable_to_call_integration_routine(\"Invalid number of points for gauss_kronrod\");\n    }\n\n    return result;\n}\n\ntemplate<unsigned points>\nstd::pair<PyObject*, PyObject*> get_abscissa_and_weights() noexcept{\n    auto abscissa = compi_internal::py_list_from_real_container(boost::math::quadrature::gauss_kronrod<Real,points>::abscissa());\n    if(abscissa == NULL){\n        return std::make_pair<PyObject*,PyObject*>(NULL,NULL);\n    }\n    auto weights = compi_internal::py_list_from_real_container(boost::math::quadrature::gauss_kronrod<Real,points>::weights());\n    if(weights == NULL){\n        Py_DECREF(abscissa);\n        return std::make_pair<PyObject*,PyObject*>(NULL,NULL);\n    }\n    return std::make_pair(abscissa,weights);\n}\n\ntemplate<>\nPyObject* generate_full_output_dict(const GaussKronrodParameters::result_type& result, const GaussKronrodParameters& parameters) noexcept{\n\n    // The boost API returning the abscissa and weights simply spesifies that\n    // they are returned as a (reference to a) random access container. \n    // Since this could (reasonably) depend on points (e.g. array<Real,points>)\n    // it is awkward to use the map based appraoch in run_integation_routine\n    // and instead we use more verbose a template/switch based approach\n\n    std::pair<PyObject*,PyObject*> abscissa_and_weights;\n    switch(parameters.points){\n        case 15:\n            abscissa_and_weights = get_abscissa_and_weights<15>();\n            break;\n        case 31:\n            abscissa_and_weights = get_abscissa_and_weights<31>();\n            break;\n        case 41:\n            abscissa_and_weights = get_abscissa_and_weights<41>();\n            break;\n        case 51:\n            abscissa_and_weights = get_abscissa_and_weights<51>();\n            break;\n        case 61:\n            abscissa_and_weights = get_abscissa_and_weights<61>();\n            break;\n        default:\n            // Should never get here as have already checked the value of points is valid \n            PyErr_SetString(PyExc_NotImplementedError,\"Unable to generate abscissa and weights for the given number of points.\\nPlease report this bug\");\n            return NULL;\n        }\n        \n        if(abscissa_and_weights.first == NULL || abscissa_and_weights.second == NULL){\n            return NULL;\n        }\n\n        return Py_BuildValue(\"{sfsOsO}\",\"L1 norm\",result.l1,\"abscissa\",abscissa_and_weights.first,\"weights\",abscissa_and_weights.second);\n}\n\n// Integrates a Python function returning a complex over a finite interval using\n// Gauss-Kronrod adaptive quadrature\nextern \"C\" PyObject* gauss_kronrod(PyObject* self, PyObject* args, PyObject* kwargs){\n    return integration_routine<GaussKronrodParameters>(args,kwargs);\n}\n", "meta": {"hexsha": "93028b6421d01bb2ac3125726c07fe212536cd0c", "size": 5531, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/GaussKronrod.cpp", "max_stars_repo_name": "CGJackson/Compi", "max_stars_repo_head_hexsha": "9fe2a316e9dbe54b01ee274417a07a13f4f990b0", "max_stars_repo_licenses": ["MIT"], "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/GaussKronrod.cpp", "max_issues_repo_name": "CGJackson/Compi", "max_issues_repo_head_hexsha": "9fe2a316e9dbe54b01ee274417a07a13f4f990b0", "max_issues_repo_licenses": ["MIT"], "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/GaussKronrod.cpp", "max_forks_repo_name": "CGJackson/Compi", "max_forks_repo_head_hexsha": "9fe2a316e9dbe54b01ee274417a07a13f4f990b0", "max_forks_repo_licenses": ["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.5511811024, "max_line_length": 174, "alphanum_fraction": 0.6563008498, "num_tokens": 1214, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255927, "lm_q2_score": 0.6113819591324416, "lm_q1q2_score": 0.46504807961468003}}
{"text": "/*=============================================================================\r\n    Copyright (c) 2002-2015 Joel de Guzman\r\n\r\n    Distributed under the Boost Software License, Version 1.0. (See accompanying\r\n    file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n=============================================================================*/\r\n///////////////////////////////////////////////////////////////////////////////\r\n//\r\n//  A complex number micro parser.\r\n//\r\n//  [ JDG May 10, 2002 ]    spirit1\r\n//  [ JDG May 9, 2007 ]     spirit2\r\n//  [ JDG May 12, 2015 ]    spirit X3\r\n//\r\n///////////////////////////////////////////////////////////////////////////////\r\n\r\n#include <boost/config/warning_disable.hpp>\r\n#include <boost/spirit/home/x3.hpp>\r\n\r\n#include <iostream>\r\n#include <string>\r\n#include <complex>\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n//  Our complex number parser/compiler\r\n///////////////////////////////////////////////////////////////////////////////\r\nnamespace client\r\n{\r\n    template <typename Iterator>\r\n    bool parse_complex(Iterator first, Iterator last, std::complex<double>& c)\r\n    {\r\n        using boost::spirit::x3::double_;\r\n        using boost::spirit::x3::_attr;\r\n        using boost::spirit::x3::phrase_parse;\r\n        using boost::spirit::x3::ascii::space;\r\n\r\n        double rN = 0.0;\r\n        double iN = 0.0;\r\n        auto fr = [&](auto& ctx){ rN = _attr(ctx); };\r\n        auto fi = [&](auto& ctx){ iN = _attr(ctx); };\r\n\r\n        bool r = phrase_parse(first, last,\r\n\r\n            //  Begin grammar\r\n            (\r\n                    '(' >> double_[fr]\r\n                        >> -(',' >> double_[fi]) >> ')'\r\n                |   double_[fr]\r\n            ),\r\n            //  End grammar\r\n\r\n            space);\r\n\r\n        if (!r || first != last) // fail if we did not get a full match\r\n            return false;\r\n        c = std::complex<double>(rN, iN);\r\n        return r;\r\n    }\r\n}\r\n\r\n////////////////////////////////////////////////////////////////////////////\r\n//  Main program\r\n////////////////////////////////////////////////////////////////////////////\r\nint\r\nmain()\r\n{\r\n    std::cout << \"/////////////////////////////////////////////////////////\\n\\n\";\r\n    std::cout << \"\\t\\tA complex number micro parser for Spirit...\\n\\n\";\r\n    std::cout << \"/////////////////////////////////////////////////////////\\n\\n\";\r\n\r\n    std::cout << \"Give me a complex number of the form r or (r) or (r,i) \\n\";\r\n    std::cout << \"Type [q or Q] to quit\\n\\n\";\r\n\r\n    std::string str;\r\n    while (getline(std::cin, str))\r\n    {\r\n        if (str.empty() || str[0] == 'q' || str[0] == 'Q')\r\n            break;\r\n\r\n        std::complex<double> c;\r\n        if (client::parse_complex(str.begin(), str.end(), c))\r\n        {\r\n            std::cout << \"-------------------------\\n\";\r\n            std::cout << \"Parsing succeeded\\n\";\r\n            std::cout << \"got: \" << c << std::endl;\r\n            std::cout << \"\\n-------------------------\\n\";\r\n        }\r\n        else\r\n        {\r\n            std::cout << \"-------------------------\\n\";\r\n            std::cout << \"Parsing failed\\n\";\r\n            std::cout << \"-------------------------\\n\";\r\n        }\r\n    }\r\n\r\n    std::cout << \"Bye... :-) \\n\\n\";\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "02e5089b4ec032ba172551c89bd1844193dfdf1d", "size": 3294, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/spirit/example/x3/complex_number.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": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/spirit/example/x3/complex_number.cpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-04T18:00:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-04T18:00:00.000Z", "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/spirit/example/x3/complex_number.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 33.2727272727, "max_line_length": 82, "alphanum_fraction": 0.3557984214, "num_tokens": 686, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.7025300698514777, "lm_q1q2_score": 0.46502072420718743}}
{"text": "/**\n * @file Range.hpp\n *\n * The file defines a template class to represent ranges.\n *\n * @author Thomas R\u00f6fer\n */\n\n#pragma once\n\n#include <Eigen/Dense>\n#include <algorithm>\n#include <type_traits>\n\n/**\n * A template class to represent ranges. It also defines the 13 Allen relations\n */\ntemplate<typename T>\nstruct Range\n{\n  /**\n   * Constructor.\n   * Defines an empty range.\n   */\n  constexpr Range() : min(T()), max(T()) {};\n\n  /**\n   * Constructor.\n   * Defines an empty range.\n   * @param minmax A conjoined starting and ending point of the empty range.\n   */\n  constexpr Range(T minmax) : min(minmax), max(minmax) {};\n\n  /**\n   * Constructor.\n   * @param min The minimum of the range.\n   * @param max The maximum of the range.\n   */\n  constexpr Range(T min, T max) : min(min), max(max) {};\n\n  /** A range between 0 and 1. */\n  static constexpr Range<T> ZeroOneRange();\n\n  /** A range between -1 and 1. */\n  static constexpr Range<T> OneRange();\n\n  /**\n   * The function enlarges the range so that a certain value will be part of it.\n   * @param t The value that will be part of the range.\n   * @return A reference to the range.\n   */\n  Range<T>& add(T t)\n  {\n    if(min > t)\n      min = t;\n    if(max < t)\n      max = t;\n    return *this;\n  }\n\n  /**\n   * The function enlarges the range so that the resulting range also contains another one.\n   * @param r The range that also will be part of the range.\n   * @return A reference to the range.\n   */\n  Range<T>& add(const Range<T>& r)\n  {\n    add(r.min);\n    add(r.max);\n    return *this;\n  }\n\n  /**\n   * The function checks whether a certain value is in the range.\n   * Note that the function is able to handle circular range, i.e. max < min.\n   * @param t The value.\n   * @return Is the value inside the range?\n   */\n  constexpr bool isInside(T t) const {return min <= max ? t >= min && t <= max : t >= min || t <= max;}\n\n  /**\n   * The function limits a certain value to the range.\n   * Note that the function is not able to handle circular range, i.e. max < min.\n   * @param t The value that will be \"clipped\" to the range.\n   * @return The limited value.\n   */\n  constexpr T limit(T t) const {return t < min ? min : t > max ? max : t;} //sets a limit for a Range\n\n  constexpr T clamped(T t) const { return limit(t); }\n  T& clamp(T& t) const { t = clamped(t); return t; }\n\n  template<typename Derived>\n  Derived& clamp(Eigen::DenseBase<Derived>& mat) const\n  {\n    static_assert(std::is_same<typename Eigen::MatrixBase<Derived>::Scalar, T>::value, \"Matrix must have the same scalar type as the Range.\");\n    return mat = mat.derived().unaryExpr([this](T val) { return clamped(val); });\n  }\n\n  template<typename Derived>\n  Derived clamped(const Eigen::DenseBase<Derived>& mat) const\n  {\n    static_assert(std::is_same<typename Eigen::MatrixBase<Derived>::Scalar, T>::value, \"Matrix must have the same scalar type as the Range.\");\n    return mat.derived().unaryExpr([this](T val) { return clamped(val); });\n  }\n\n  /**\n   * The function limits another range to this range.\n   * Note that the function is able to handle circular range, i.e. max < min.\n   * @param r The range that will be \"clipped\" to this range.\n   * @return The limited value.\n   */\n  constexpr Range<T> limit(const Range<T>& r) const { return Range<T>(limit(r.min), limit(r.max)); } //sets the limit of a Range\n\n  /**\n   * Scales a value t with a range of tRange to this range.\n   */\n  T scale(T t, const Range<T>& tRange) const;\n\n  /**\n   * The function returns the size of the range.\n   * @return The difference between the lower limit and the higher limit.\n   */\n  constexpr T getSize() const {return max - min;}\n\n  /**\n   * The function returns the center of the range.\n   * @return The center.\n   */\n  constexpr T getCenter() const {return (max + min) / 2;}\n\n  //!@name The 13 Allen relations\n  //!@{\n  constexpr bool operator==(const Range<T>& r) const {return min == r.min && max == r.max;}\n  constexpr bool operator<(const Range<T>& r) const {return max < r.min;}\n  constexpr bool operator>(const Range<T>& r) const {return min > r.max;}\n  constexpr bool meets(const Range<T>& r) const {return max == r.min;}\n  constexpr bool metBy(const Range<T>& r) const {return min == r.max;}\n  constexpr bool overlaps(const Range<T>& r) const {return min < r.min && max < r.max && max > r.min;}\n  constexpr bool overlappedBy(const Range<T>& r) const {return min > r.min && max > r.max && min < r.max;}\n  constexpr bool starts(const Range<T>& r) const {return min == r.min && max < r.max;}\n  constexpr bool startedBy(const Range<T>& r) const {return min == r.min && max > r.max;}\n  constexpr bool finishes(const Range<T>& r) const {return max == r.max && min > r.min;}\n  constexpr bool finishedBy(const Range<T>& r) const {return max == r.max && min < r.min;}\n  constexpr bool during(const Range<T>& r) const {return min > r.min && max < r.max;}\n  constexpr bool contains(const Range<T>& r) const {return min < r.min && max > r.max;}\n  //!@}\n\n  constexpr bool operator!=(const Range<T>& r) const {return min != r.min || max != r.max;}\n\n  // The size of the intersection of to ranges or 0 if there is no intersection\n  constexpr T intersectionSizeWith(const Range<T>& r) const {return std::max(0.f, std::min(max, r.max) - std::max(min, r.min));};\n\n  T min;\n  T max; /**< The limits of the range. */\n};\n\nclass Angle;\n\nusing Rangea = Range<Angle>;\nusing Rangei = Range<int>;\nusing Rangef = Range<float>;\nusing Rangeuc = Range<unsigned char>;\n\ntemplate<typename T>\nconstexpr Range<T> Range<T>::ZeroOneRange()\n{\n  return Range<T>(T(0), T(1));\n}\n\ntemplate<typename T>\nconstexpr Range<T> Range<T>::OneRange()\n{\n  return Range<T>(T(-1), T(1));\n}\n\ntemplate<typename T>\nT Range<T>::scale(T t, const Range<T>& tRange) const\n{\n  return limit(((t - tRange.min) / (tRange.max - tRange.min)) * (max - min) + min);\n}\n", "meta": {"hexsha": "681d03353656a226477c57af53bca97214b3f7ad", "size": 5818, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "nao_ik/include/nao_ik/bhuman/Range.hpp", "max_stars_repo_name": "ijnek/nao_ik", "max_stars_repo_head_hexsha": "f417ce46092d2375fca6bdedba38bf90a8458f5d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "nao_ik/include/nao_ik/bhuman/Range.hpp", "max_issues_repo_name": "ijnek/nao_ik", "max_issues_repo_head_hexsha": "f417ce46092d2375fca6bdedba38bf90a8458f5d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nao_ik/include/nao_ik/bhuman/Range.hpp", "max_forks_repo_name": "ijnek/nao_ik", "max_forks_repo_head_hexsha": "f417ce46092d2375fca6bdedba38bf90a8458f5d", "max_forks_repo_licenses": ["Apache-2.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.1436464088, "max_line_length": 142, "alphanum_fraction": 0.6431763493, "num_tokens": 1562, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300698514777, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.46502072420718743}}
{"text": "// This file is part of CRAAM, a C++ library for solving plain\n// and robust Markov decision processes.\n//\n// MIT License\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy of\n// this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to\n// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\n// the Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#pragma once\n\n#include \"craam/ImMDP.hpp\"\n#include \"craam/Simulation.hpp\"\n#include \"craam/Samples.hpp\"\n#include \"craam/modeltools.hpp\"\n#include \"craam/algorithms/values.hpp\"\n\n#include <rm/range.hpp>\n\n#include <boost/functional/hash.hpp>\n#include <iostream>\n#include <iterator>\n#include <cmath>\n\nusing namespace std;\nusing namespace craam;\nusing namespace craam::algorithms;\nusing namespace craam::impl;\nusing namespace util::lang;\n\n\n/**\nCreates a simple chain problem.\nActions:   0 - left\n           1 - right\nOptimal solution: Action 1, with value function:\n    [1.1 gamma^2/(1-gamma), 1.1 gamma/(1-gamma), 1.1/(1-gamma)]\n\n*/\nMDP make_chain1(){\n    MDP rmdp(3);\n\n    add_transition(rmdp,0,1,1,1,0);\n    add_transition(rmdp,1,1,2,1,0);\n    add_transition(rmdp,2,1,2,1,1.1);\n\n    add_transition(rmdp,0,0,0,1,0);\n    add_transition(rmdp,1,0,0,1,1);\n    add_transition(rmdp,2,0,1,1,1);\n\n    return rmdp;\n}\n\nBOOST_AUTO_TEST_CASE( simple_construct_mdpi ) {\n\n    auto mdp = make_shared<MDP>();\n    vector<long> observations({0,0});\n    Transition initial(vector<long>{0,1},vector<prec_t>{0.5,0.5},vector<prec_t>{0,0});\n\n    add_transition(*mdp,0,0,1,1.0,1.0);\n    add_transition(*mdp,1,0,0,1.0,1.0);\n    BOOST_CHECK_EQUAL(mdp->state_count(), 2);\n\n    MDPI im(const_pointer_cast<const MDP>(mdp), observations, initial);\n\n    MDPI im2(*mdp,observations,initial);\n\n    // check that we really have a copy\n    add_transition(*mdp,1,0,2,1.0,1.0);\n\n    BOOST_CHECK_EQUAL(mdp->state_count(), 3);\n    BOOST_CHECK_EQUAL(im.get_mdp()->state_count(), 3);\n    BOOST_CHECK_EQUAL(im2.get_mdp()->state_count(), 2);\n}\n\nBOOST_AUTO_TEST_CASE( simple_construct_mdpi_r ) {\n\n    auto mdp = make_shared<MDP>();\n    vector<long> observations({0,0});\n    Transition initial(vector<long>{0,1},vector<prec_t>{0.5,0.5},vector<prec_t>{0,0});\n\n    add_transition(*mdp,0,0,1,1.0,1.0);\n    add_transition(*mdp,1,0,0,1.0,2.0);\n\n    MDPI_R imr(const_pointer_cast<const MDP>(mdp), observations, initial);\n\n    // COPY ! so we can change the threshold\n    auto rmdp = imr.get_robust_mdp();\n\n    BOOST_CHECK_EQUAL(rmdp.state_count(), 1);\n    BOOST_CHECK_EQUAL(rmdp.get_state(0).action_count(), 1);\n    BOOST_CHECK_EQUAL(rmdp.get_state(0).get_action(0).outcome_count(), 2);\n\n    vector<prec_t> iv(rmdp.state_count(),0.0);\n\n    auto&& so = mpi_jac(rmdp, 0.9, iv, uniform_nature(rmdp, optimistic_unbounded, 0.0), 100, 0.0, 10, 0.0);\n    BOOST_CHECK_CLOSE(so.valuefunction[0], 20, 1e-3);\n\n    auto&& sr = mpi_jac(rmdp,0.9,iv,uniform_nature(rmdp,robust_unbounded, 0.0), 100,0.0,10,0.0);\n    BOOST_CHECK_CLOSE(sr.valuefunction[0], 10, 1e-3);\n}\n\nBOOST_AUTO_TEST_CASE( small_construct_mdpi_r ) {\n\n    auto mdp = make_shared<MDP>();\n    vector<long> observations{0,0,1};\n\n    Transition initial(vector<long>{0,1,2},vector<prec_t>{1.0/3.0,1.0/3.0,1.0/3.0},\n                        vector<prec_t>{0,0,0});\n\n    // action 0\n    add_transition(*mdp,0,0,0,0.5,1.0);\n    add_transition(*mdp,0,0,1,0.5,1.0);\n\n    add_transition(*mdp,1,0,0,0.5,2.0);\n    add_transition(*mdp,1,0,1,0.5,2.0);\n\n    add_transition(*mdp,2,0,2,1.0,1.2);\n\n    // action 1\n    add_transition(*mdp,0,1,2,1.0,1.2);\n    add_transition(*mdp,1,1,2,1.0,1.2);\n\n    BOOST_TEST_CHECKPOINT(\"Constructing MDPI_R.\");\n    MDPI_R imr(const_pointer_cast<const MDP>(mdp), observations, initial);\n\n    // Copy to change threshold\n    auto rmdp = imr.get_robust_mdp();\n\n    BOOST_TEST_CHECKPOINT(\"Checking MDP properties.\");\n    BOOST_CHECK_EQUAL(rmdp.state_count(), 2);\n    BOOST_CHECK_EQUAL(rmdp.get_state(0).action_count(), 2);\n    BOOST_CHECK_EQUAL(rmdp.get_state(1).action_count(), 1);\n    BOOST_CHECK_EQUAL(rmdp.get_state(0).get_action(0).outcome_count(), 2);\n    BOOST_CHECK_EQUAL(rmdp.get_state(0).get_action(1).outcome_count(), 2);\n    BOOST_CHECK_EQUAL(rmdp.get_state(1).get_action(0).outcome_count(), 1);\n\n    vector<prec_t> iv(rmdp.state_count(),0.0);\n\n    vector<prec_t> target_v_opt{20.0,12.0};\n    vector<prec_t> target_v_rob{12.0,12.0};\n\n    BOOST_TEST_CHECKPOINT(\"Solving RMDP\");\n    auto&& so = mpi_jac(rmdp,0.9,iv,uniform_nature(rmdp,optimistic_unbounded, 0.0),100,0.0,10,0.0);\n    CHECK_CLOSE_COLLECTION(so.valuefunction, target_v_opt, 1e-3);\n\n    auto&& sr = mpi_jac(rmdp,0.9,iv,uniform_nature(rmdp,robust_unbounded, 0.0),100,0.0,10,0.0);\n    CHECK_CLOSE_COLLECTION(sr.valuefunction, target_v_rob, 1e-3);\n}\n\nBOOST_AUTO_TEST_CASE( small_reweighted_solution ) {\n\n    auto mdp = make_shared<MDP>();\n    vector<long> observations({0,0,1});\n    Transition initial(vector<long>{0,1,2},vector<prec_t>{1.0/3.0,1.0/3.0,1.0/3.0},\n                        vector<prec_t>{0,0,0});\n\n    // action 0\n    add_transition(*mdp,0,0,0,0.5,1.0);\n    add_transition(*mdp,0,0,1,0.5,1.0);\n\n    add_transition(*mdp,1,0,0,0.5,2.0);\n    add_transition(*mdp,1,0,1,0.5,2.0);\n\n    add_transition(*mdp,2,0,2,1.0,1.2);\n\n    // action 1\n    add_transition(*mdp,0,1,2,1.0,1.2);\n    add_transition(*mdp,1,1,2,1.0,1.2);\n\n    BOOST_TEST_CHECKPOINT(\"Constructing MDPI_R.\");\n    MDPI_R imr(const_pointer_cast<const MDP>(mdp), observations, initial);\n\n    BOOST_TEST_CHECKPOINT(\"Solving MDPI_R.\");\n    auto&& pol = imr.solve_reweighted(10, 0.9);\n\n    indvec polvec{0,0};\n    BOOST_CHECK_EQUAL_COLLECTIONS(pol.begin(), pol.end(),polvec.begin(),polvec.end());\n\n    auto&& pol2 = imr.solve_robust(10, 0.0, 0.9);\n    BOOST_CHECK_EQUAL_COLLECTIONS(pol2.begin(), pol2.end(),polvec.begin(),polvec.end());\n\n\n    //auto retval = imr.total_return(pol, 0.99);\n    //cout << \"Return: \" << retval << endl;\n\n    //ostream_iterator<prec_t> output(cout, \", \");\n    //copy(pol.begin(), pol.end(), output);\n}\n\nBOOST_AUTO_TEST_CASE(simple_mdpo_save_load_save_load) {\n    MDP&& rmdp1 = make_chain1();\n\n    Transition initial(indvec{0,1,2},numvec{1.0/3.0,1.0/3.0,1/3.0});\n    indvec state2obs{0,0,1};\n\n    MDPI mdpi1(rmdp1, state2obs, initial);\n\n    stringstream store1, store2, store3;\n\n    mdpi1.to_csv(store1,store2,store3);\n    store1.seekg(0); store2.seekg(0); store3.seekg(0);\n\n    auto&& string11 = store1.str();\n    auto&& string12 = store2.str();\n    auto&& string13 = store3.str();\n\n    auto mdpi2 = MDPI::from_csv(store1,store2,store3);\n\n    stringstream store21, store22, store23;\n\n    mdpi2->to_csv(store21, store22, store23);\n\n    auto&& string21 = store21.str();\n    auto&& string22 = store22.str();\n    auto&& string23 = store23.str();\n\n    BOOST_CHECK_EQUAL(string11, string21);\n    BOOST_CHECK_EQUAL(string12, string22);\n    BOOST_CHECK_EQUAL(string13, string23);\n}\n\nBOOST_AUTO_TEST_CASE(simple_mdpor_save_load_save_load) {\n    MDP&& rmdp1 = make_chain1();\n\n    Transition initial(indvec{0,1,2},numvec{1.0/3.0,1.0/3.0,1/3.0});\n    indvec state2obs{0,0,1};\n\n    MDPI_R mdpi1(rmdp1, state2obs, initial);\n\n    stringstream store1, store2, store3;\n\n    mdpi1.to_csv(store1,store2,store3);\n    store1.seekg(0); store2.seekg(0); store3.seekg(0);\n\n    auto&& string11 = store1.str();\n    auto&& string12 = store2.str();\n    auto&& string13 = store3.str();\n\n    auto mdpi2 = MDPI_R::from_csv(store1,store2,store3);\n\n    stringstream store21, store22, store23;\n\n    mdpi2->to_csv(store21, store22, store23);\n\n    auto&& string21 = store21.str();\n    auto&& string22 = store22.str();\n    auto&& string23 = store23.str();\n\n    BOOST_CHECK_EQUAL(string11, string21);\n    BOOST_CHECK_EQUAL(string12, string22);\n    BOOST_CHECK_EQUAL(string13, string23);\n}\n\nusing namespace craam::msen;\n\n/*\ntemplate<class T>\nvoid print_vector(vector<T> vec){\n    for(auto&& p : vec){\n        cout << p << \" \";\n    }\n}*/\n\nBOOST_AUTO_TEST_CASE(implementable_from_samples){\n    const int terminal_state = 10;\n\n    CounterTerminal sim(0.9,0,terminal_state,1);\n    RandomPolicy<CounterTerminal> random_pol(sim,1);\n\n    auto samples = make_samples<CounterTerminal>();\n    simulate(sim,samples,random_pol,50,50);\n    simulate(sim,samples,[](int){return 1;},10,20);\n    simulate(sim,samples,[](int){return -1;},10,20);\n\n    SampleDiscretizerSI<typename CounterTerminal::State, \n                        typename CounterTerminal::Action> sd;\n    // initialize action values\n    sd.add_action(-1); sd.add_action(+1);\n    //initialize state values\n    for(auto i : range(-terminal_state,terminal_state)) sd.add_state(i);\n\n    sd.add_samples(samples);\n\n    BOOST_CHECK_EQUAL(samples.get_initial().size(), sd.get_discrete()->get_initial().size());\n    BOOST_CHECK_EQUAL(samples.size(), sd.get_discrete()->size());\n\n    SampledMDP smdp;\n    smdp.add_samples(*sd.get_discrete());\n    auto mdp = smdp.get_mdp();\n    auto&& initial = smdp.get_initial();\n\n    auto&& sol = mpi_jac(*mdp,0.9);\n\n    //cout << \"Optimal policy: \" << endl; print_vector(sol.policy); cout << endl;\n\n    BOOST_CHECK_CLOSE(sol.total_return(initial), 51.313973553, 1e-3);\n\n    // define observations\n    indvec observations(mdp->state_count(), -1);\n    size_t last_obs(0), inobs(0);\n    for(auto i : range(size_t(0), mdp->state_count())){\n        // check if this is a terminal state\n        if(mdp->get_state(i).action_count() == 0 || inobs >= 2){\n            if(inobs > 0){\n                inobs = 0;\n                last_obs++;\n            }\n            observations[i] = last_obs++;\n        }else {\n            observations[i] = last_obs;\n            inobs++;\n        }\n        //cout << \" \" << observations[i] ;\n    }\n    //cout << endl;\n\n    MDPI_R mdpi(mdp, observations, initial);\n    auto&& randompolicy = mdpi.random_policy(25);\n\n    auto isol = mdpi.solve_reweighted(0, 0.9, randompolicy);\n    BOOST_CHECK_EQUAL_COLLECTIONS(randompolicy.begin(), randompolicy.end(), isol.begin(), isol.end());\n    isol = mdpi.solve_robust(0, 0.0, 0.9, randompolicy);\n    BOOST_CHECK_EQUAL_COLLECTIONS(randompolicy.begin(), randompolicy.end(), isol.begin(), isol.end());\n\n    isol = mdpi.solve_reweighted(1, 0.9, randompolicy);\n\n    auto sol_impl = mpi_jac(*mdp, 0.9, numvec(0), PlainBellman(mdpi.obspol2statepol(isol)));\n\n    BOOST_CHECK_CLOSE(sol_impl.total_return(initial), 51.3135, 1e-3);\n    BOOST_CHECK_CLOSE(mdpi.total_return(0.9), 51.3135, 1e-3);\n\n    isol = mdpi.solve_robust(1, 0.0, 0.9, randompolicy);\n    sol_impl = mpi_jac(*mdp, 0.9, numvec(0), PlainBellman(mdpi.obspol2statepol(isol)));\n\n    BOOST_CHECK_CLOSE(sol_impl.total_return(initial), 51.3135, 1e-3);\n    BOOST_CHECK_CLOSE(mdpi.total_return(0.9), 51.3135, 1e-3);\n}\n\nBOOST_AUTO_TEST_CASE(test_return_of_implementable){\n    // test return with different initial states\n\n    const prec_t gamma = 0.99;\n\n    MDP&& mdp = make_chain1();\n    indvec observations = {0,0,0};\n    Transition  initial1(numvec({1.0, 0.0, 0.0})),\n                initial2(numvec({0.0, 1.0, 0.0})),\n                initial3(numvec({0.0, 0.0, 1.0}));\n\n    MDPI mdpi1(mdp, observations, initial1);\n    BOOST_CHECK_CLOSE(mdpi1.total_return(gamma, 1e-5), 1.1*pow(gamma,2)/(1-gamma), 1e-3);\n    MDPI mdpi2(mdp, observations, initial2);\n    BOOST_CHECK_CLOSE(mdpi2.total_return(gamma, 1e-5), 1.1*pow(gamma,1)/(1-gamma), 1e-3);\n    MDPI mdpi3(mdp, observations, initial3);\n    BOOST_CHECK_CLOSE(mdpi3.total_return(gamma, 1e-5), 1.1*pow(gamma,0)/(1-gamma), 1e-3);\n}\n\n\n// TODO: make sure there is a test that checks that the return of the implementable policy with\n// the true weights has the same return as the true MDP.\n\n", "meta": {"hexsha": "17f14544ab35c397cca0734c7c0671e6cb4a1964", "size": 12342, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/implementable_tests.hpp", "max_stars_repo_name": "marekpetrik/CRAAM", "max_stars_repo_head_hexsha": "62cc392e876b5383faa5cb15ab1f6b70b26ff395", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2015-09-28T14:41:00.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-03T00:16:19.000Z", "max_issues_repo_path": "test/implementable_tests.hpp", "max_issues_repo_name": "marekpetrik/CRAAM", "max_issues_repo_head_hexsha": "62cc392e876b5383faa5cb15ab1f6b70b26ff395", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2017-08-10T18:35:40.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-13T01:38:04.000Z", "max_forks_repo_path": "test/implementable_tests.hpp", "max_forks_repo_name": "marekpetrik/CRAAM", "max_forks_repo_head_hexsha": "62cc392e876b5383faa5cb15ab1f6b70b26ff395", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2016-09-19T18:31:07.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-05T08:59:45.000Z", "avg_line_length": 32.8244680851, "max_line_length": 107, "alphanum_fraction": 0.6720952844, "num_tokens": 3839, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228625116081, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.46502070246893284}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n  Array44i a = Array44i::Random();\ncout << \"Here is the array a:\" << endl << a << endl;\ncout << \"Here is a.rightCols(2):\" << endl;\ncout << a.rightCols(2) << endl;\na.rightCols(2).setZero();\ncout << \"Now the array a is:\" << endl << a << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "a39ffd160c04177cd3a1d4f55ec395c39b65fb5f", "size": 390, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_MatrixBase_rightCols_int.cpp", "max_stars_repo_name": "TANHAIYU/Self-calibration-using-Homography-Constraints", "max_stars_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-03-17T16:34:31.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-17T18:30:13.000Z", "max_issues_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_MatrixBase_rightCols_int.cpp", "max_issues_repo_name": "TANHAIYU/planecalib", "max_issues_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_MatrixBase_rightCols_int.cpp", "max_forks_repo_name": "TANHAIYU/planecalib", "max_forks_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.5263157895, "max_line_length": 52, "alphanum_fraction": 0.6230769231, "num_tokens": 117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6619228625116081, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.46502070246893284}}
{"text": "/*\n * matrix_equiv.cc\n * Copyright 2015 John Lawson\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 \"matrix_equiv.h\"\n\n#include <boost/functional/hash.hpp>\n\nnamespace ptope {\nstd::size_t\nMEquivHash::operator()(const arma::mat & m) const {\n\tstatic auto rnd = [](double const& val)->std::size_t{return std::lround(val * 1e5);};\n\tstd::size_t hash = 113;\n\tm_sums.resize(m.n_rows);\n\tfor(arma::uword i = 0, max = m.n_cols; i < max; ++i) {\n\t\tm_sums[i].first = rnd(std::accumulate(m.begin_col(i), m.end_col(i),\n\t\t\t\tstatic_cast<double>(0),\n\t\t\t\t[](double const& init, double const& val){return init + rnd(val);}));\n\t\tm_sums[i].second = rnd(std::accumulate(m.begin_col(i), m.end_col(i),\n\t\t\t\tstatic_cast<double>(0),\n\t\t\t\t[](double const& init, double const& val){return init + (rnd(val) * rnd(val));}));\n\t}\n\tstd::sort(m_sums.begin(), m_sums.end());\n\tboost::hash_combine(hash, m_sums);\n\treturn hash;\n}\nbool\nMEquivEqual::operator()(const arma::mat & lhs, const arma::mat & rhs) const {\n\tbool result = false;\n\tif(lhs.n_cols == rhs.n_cols) {\n\t\t__perm.reserve(lhs.n_cols);\n\t\tcompatible_vectors(lhs, rhs, __comp);\n\t\tresult = check_permutation(lhs, rhs, __perm, 0, __comp);\n\t\t__perm.clear();\n\t}\n\treturn result;\n}\nvoid\nMEquivEqual::sums(const arma::mat & m, std::vector<double> & out) const {\n\tout.reserve(m.n_cols);\n\tfor(arma::uword i = 0, max = m.n_cols; i < max; ++i) {\n\t\tout[i] = std::accumulate(m.begin_col(i), m.end_col(i), static_cast<double>(0));\n\t}\n}\nvoid\nMEquivEqual::compatible_vectors(const arma::mat & lhs, const arma::mat & rhs,\n\t\tstd::vector<std::vector<arma::uword>> & result) const {\n\tfor(auto & vec : result) {\n\t\tvec.clear();\n\t}\n\tfor(std::size_t i = result.size(), max = lhs.n_cols; i < max; ++i) {\n\t\tresult.push_back(std::vector<arma::uword>());\n\t}\n\tsums(lhs, __l_sum);\n\tsums(rhs, __r_sum);\n\tfor(arma::uword j = 0, max = lhs.n_cols; j < max; ++j) {\n\t\tfor(arma::uword i = 0; i < max; ++i) {\n\t\t\tif(_d_eq(__l_sum[j], __r_sum[i])) result[j].push_back(i);\n\t\t}\n\t}\n}\nbool\nMEquivEqual::check_permutation(const arma::mat & lhs, const arma::mat & rhs,\n\t\tstd::vector<arma::uword> & perm, std::size_t index,\n\t\tconst std::vector<std::vector<arma::uword>> & comp) const {\n\tbool result = false;\n\tif(index == lhs.n_cols) {\n\t\t// Have complete permutation\n\t\tresult = true;\n\t} else {\n\t\t// Add another entry to the permutation\n\t\tfor(const arma::uword & map : comp[index]) {\n\t\t\tif(result) break;\n\t\t\t// Check that the new map value is not already in perm\n\t\t\tif(std::find(perm.begin(), perm.begin() + index, map)\n\t\t\t\t\t== perm.begin() + index) {\n\t\t\t\t// Check that the value gives correct permutation so far\n\t\t\t\tbool skip = false;\n\t\t\t\tdouble const * lhs_col_data = lhs.colptr(index);\n\t\t\t\tdouble const * rhs_col_data = rhs.colptr(map);\n\t\t\t\tfor(size_t k = 0; !skip && k < index; ++k) {\n\t\t\t\t\tskip = !_d_eq(lhs_col_data[k], rhs_col_data[perm[k]]);\n\t\t\t\t}\n\t\t\t\tif(!skip) {\n\t\t\t\t\tperm[index] = map;\n\t\t\t\t\tresult = check_permutation(lhs, rhs, perm, index + 1, comp);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn result;\n}\nbool\nMColPermEquiv::operator()(const arma::mat & lhs, const arma::mat & rhs) const {\n\tbool result = false;\n\tif(lhs.n_cols == rhs.n_cols) {\n\t\t__perm.reserve(lhs.n_cols);\n\t\tcompatible_vectors(lhs, rhs, __comp);\n\t\tresult = check_permutation(lhs, rhs, __perm, 0, __comp);\n\t\t__perm.clear();\n\t}\n\treturn result;\n}\nvoid\nMColPermEquiv::sums(const arma::mat & m, std::vector<double> & out) const {\n\tout.reserve(m.n_cols);\n\tfor(arma::uword i = 0, max = m.n_cols; i < max; ++i) {\n\t\tout[i] = std::accumulate(m.begin_col(i), m.end_col(i), static_cast<double>(0));\n\t}\n}\nvoid\nMColPermEquiv::compatible_vectors(const arma::mat & lhs, const arma::mat & rhs,\n\t\tstd::vector<std::vector<arma::uword>> & result) const {\n\tfor(auto & vec : result) {\n\t\tvec.clear();\n\t}\n\tfor(std::size_t i = result.size(), max = lhs.n_cols; i < max; ++i) {\n\t\tresult.push_back(std::vector<arma::uword>());\n\t}\n\tsums(lhs, __l_sum);\n\tsums(rhs, __r_sum);\n\tfor(arma::uword j = 0, max = lhs.n_cols; j < max; ++j) {\n\t\tfor(arma::uword i = 0; i < max; ++i) {\n\t\t\tif(_d_eq(__l_sum[j], __r_sum[i])) result[j].push_back(i);\n\t\t}\n\t}\n}\nbool\nMColPermEquiv::check_permutation(const arma::mat & lhs, const arma::mat & rhs,\n\t\tstd::vector<arma::uword> & perm, std::size_t index,\n\t\tconst std::vector<std::vector<arma::uword>> & comp) const {\n\tbool result = false;\n\tif(index == lhs.n_cols) {\n\t\tresult = true;\n\t} else {\n\t\t// Add another entry to the permutation\n\t\tfor(const arma::uword & map : comp[index]) {\n\t\t\tif(result) break;\n\t\t\tif(std::find(perm.begin(), perm.begin() + index, map)\n\t\t\t\t\t== perm.begin() + index) {\n\t\t\t\tbool skip = false;\n\t\t\t\tdouble const * lhs_col_data = lhs.colptr(index);\n\t\t\t\tdouble const * rhs_col_data = rhs.colptr(map);\n\t\t\t\tfor(size_t k = 0; !skip && k < index; ++k) {\n\t\t\t\t\tskip = !_d_eq(lhs_col_data[k], rhs_col_data[k]);\n\t\t\t\t}\n\t\t\t\tif(!skip) {\n\t\t\t\t\tperm[index] = map;\n\t\t\t\t\tresult = check_permutation(lhs, rhs, perm, index + 1, comp);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn result;\n}\n}\n\n", "meta": {"hexsha": "72cb08451b679e120d7e75f00eb00f2398bb30f8", "size": 5419, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/matrix_equiv.cc", "max_stars_repo_name": "jwlawson/ptope", "max_stars_repo_head_hexsha": "2c664ac4fb7b036a298e7c6a1b2cf58d803f227a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-02-22T03:03:13.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-22T03:03:13.000Z", "max_issues_repo_path": "src/matrix_equiv.cc", "max_issues_repo_name": "jwlawson/ptope", "max_issues_repo_head_hexsha": "2c664ac4fb7b036a298e7c6a1b2cf58d803f227a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2016-08-31T16:34:59.000Z", "max_issues_repo_issues_event_max_datetime": "2016-09-12T16:29:55.000Z", "max_forks_repo_path": "src/matrix_equiv.cc", "max_forks_repo_name": "jwlawson/ptope", "max_forks_repo_head_hexsha": "2c664ac4fb7b036a298e7c6a1b2cf58d803f227a", "max_forks_repo_licenses": ["Apache-2.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.8764705882, "max_line_length": 86, "alphanum_fraction": 0.6462446946, "num_tokens": 1651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195385342971, "lm_q2_score": 0.6334102775181399, "lm_q1q2_score": 0.46499886063449797}}
{"text": "#include <algorithm>\n#include <boost/optional.hpp>\n#include <climits>\n#include <cmath>\n#include <cstdio>\n#include <cstring>\n#include <functional>\n#include <iostream>\n#include <limits>\n#include <list>\n#include <map>\n#include <numeric>\n#include <queue>\n#include <set>\n#include <sstream>\n#include <string>\n#include <tuple>\n#include <type_traits>\n#include <unordered_map>\n#include <unordered_set>\n#include <utility>\n#include <vector>\n\n#define REP(i, n) for(int i = 0, i##_MACRO = (n); i < i##_MACRO; i++)\n#define RANGE(i, a, b) for(int i = (a), i##_MACRO = (b); i < i##_MACRO; i++)\n#define EACH(e, a) for(auto&& e : a)\n#define ALL(a) std::begin(a), std::end(a)\n#define RALL(a) std::rbegin(a), std::rend(a)\n#define FILL(a, n) memset((a), n, sizeof(a))\n#define FILLZ(a) FILL(a, 0)\n#define INT(x) (static_cast<int>(x))\n\nusing namespace std;\n\nusing ll = long long;\nusing VI = vector<int>;\nusing VI2D = vector<vector<int>>;\n\nconstexpr int INF = 2e9;\nconstexpr double EPS = 1e-10;\nconstexpr double PI = acos(-1.0);\n\nconstexpr int dx[] = {-1, 0, 1, 0};\nconstexpr int dy[] = {0, -1, 0, 1};\n\ntemplate <typename T>\nconstexpr int sign(T x) {\n\treturn x < 0 ? -1 : x > 0 ? 1 : 0;\n}\n\ntemplate <>\nconstexpr int sign(double x) {\n\treturn x < -EPS ? -1 : x > EPS ? 1 : 0;\n}\n\ntemplate <typename T, typename U>\nconstexpr void chmax(T& m, U x) {\n\tm = max(m, x);\n}\n\ntemplate <typename T, typename U>\nconstexpr void chmin(T& m, U x) {\n\tm = min(m, x);\n}\n\ntemplate <typename T>\nconstexpr T square(T x) {\n\treturn x * x;\n}\n\nint roundup_pow2(int n) {\n\tif(!(n & (n - 1))) {\n\t\treturn n;\n\t}\n\n\tint i = 1;\n\twhile((n >> i) != 0) {\n\t\ti++;\n\t}\n\treturn 1 << i;\n}\n\ntemplate <typename T>\nclass SegmentTree {\n\tusing F = function<T(T, T)>;\n\n\t// \u6f14\u7b97\n\tF merge;\n\t// \u5358\u4f4d\u5143\n\tT identity;\n\tvector<T> tree;\n\tsize_t size;\n\n\tpublic:\n\tSegmentTree(const vector<T>& a, const F f, const T id)\n\t\t: tree(roundup_pow2(a.size()) * 2 - 1, id),\n\t\t  size(roundup_pow2(a.size())), merge(f), identity(id) {\n\t\tint offset = this->size - 1;\n\t\tfor(int i = 0; i < a.size(); i++) {\n\t\t\tthis->tree[i + offset] = a[i];\n\t\t}\n\t\tfor(int i = offset - 1; i >= 0; i--) {\n\t\t\tthis->tree[i] = this->apply(i);\n\t\t}\n\t}\n\t// \u30e2\u30ce\u30a4\u30c9(Z,+)\n\tSegmentTree(const vector<T> a)\n\t\t: SegmentTree(a, [](T a, T b) { return a + b; }, 0) {}\n\n\t// \u66f4\u65b0\n\t// \u95a2\u6570\u306e\u6307\u5b9a\u304c\u306a\u3051\u308c\u3070\u7f6e\u304d\u63db\u3048\n\tvoid update(const size_t index, const T value, const F f = [](T a, T b) {\n\t\treturn b;\n\t}) {\n\t\tsize_t i = index + size - 1;\n\t\tthis->tree[i] = f(this->tree[i], value);\n\t\twhile(i > 0) {\n\t\t\ti = (i - 1) / 2;\n\t\t\tthis->tree[i] = this->apply(i);\n\t\t}\n\t}\n\n\t// \u4e00\u70b9\u53d6\u5f97\n\tT find(const size_t index) { return this->tree[index + size - 1]; }\n\n\t// \u533a\u9593\u53d6\u5f97\n\tT find(const size_t query_left, const size_t query_right) const {\n\t\treturn this->find_impl(query_left, query_right, 0, 0, this->size);\n\t}\n\n\tprivate:\n\tT apply(size_t index) const {\n\t\treturn this->merge(this->tree[index * 2 + 1],\n\t\t\t\t\t\t   this->tree[index * 2 + 2]);\n\t}\n\n\tT find_impl(size_t query_left,\n\t\t\t\tsize_t query_right,\n\t\t\t\tsize_t node,\n\t\t\t\tsize_t node_left,\n\t\t\t\tsize_t node_right) const {\n\t\tif(node_right <= query_left || query_right <= node_left) {\n\t\t\treturn this->identity;\n\t\t}\n\t\tif(query_left <= node_left && node_right <= query_right) {\n\t\t\treturn this->tree[node];\n\t\t}\n\n\t\treturn this->merge(find_impl(query_left,\n\t\t\t\t\t\t\t\t\t query_right,\n\t\t\t\t\t\t\t\t\t node * 2 + 1,\n\t\t\t\t\t\t\t\t\t node_left,\n\t\t\t\t\t\t\t\t\t node_left + (node_right - node_left) / 2),\n\t\t\t\t\t\t   find_impl(query_left,\n\t\t\t\t\t\t\t\t\t query_right,\n\t\t\t\t\t\t\t\t\t node * 2 + 2,\n\t\t\t\t\t\t\t\t\t node_left + (node_right - node_left) / 2,\n\t\t\t\t\t\t\t\t\t node_right));\n\t}\n};\n\nint to_bitset(char c) {\n\treturn 1 << (c - 'a');\n}\n\nint main() {\n\tint n;\n\tstring s;\n\tcin >> n >> s;\n\tvector<int> v(n);\n\tREP(i, n) { v[i] = to_bitset(s[i]); }\n\tSegmentTree<int> st(v, [](int a, int b) { return a | b; }, 0);\n\tint q;\n\tcin >> q;\n\tVI results;\n\tREP(i, q) {\n\t\tint type;\n\t\tcin >> type;\n\t\tif(type == 1) {\n\t\t\tint iq;\n\t\t\tchar c;\n\t\t\tcin >> iq >> c;\n\t\t\tst.update(iq - 1, to_bitset(c));\n\t\t} else {\n\t\t\tint l, r;\n\t\t\tcin >> l >> r;\n\t\t\tresults.push_back(__builtin_popcount(st.find(l - 1, r)));\n\t\t}\n\t}\n\tEACH(e, results) { cout << e << endl; }\n\treturn 0;\n}\n", "meta": {"hexsha": "c950c8763dff3879970be7769522892a80b842d1", "size": 4048, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AtCoder/ABC157/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/ABC157/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/ABC157/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": 20.9740932642, "max_line_length": 76, "alphanum_fraction": 0.5854743083, "num_tokens": 1351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.6334102775181399, "lm_q1q2_score": 0.4649988532653306}}
{"text": "/**\n * Copyright (c) 2015, Jozef Stefan Institute, Quintelligence d.o.o. and contributors\n * All rights reserved.\n * \n * This source code is licensed under the FreeBSD license found in the\n * LICENSE file in the root directory of this source tree.\n */\n#include \"bd.h\"\n//#include \"base.h\"\n#ifdef LAPACKE\n#include \"MKLfunctions.h\"\n#endif\n\n#ifdef EIGEN\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#endif\n\n///////////////////////////////////////////////////////////////////////\n// Sparse-Column-Matrix\nvoid TSparseColMatrix::PMultiply(const TFltVV& B, int ColId, TFltV& Result) const {\n    EAssert(B.GetRows() >= ColN && Result.Len() >= RowN);\n    int i, j; TFlt *ResV = Result.BegI();\n    for (i = 0; i < RowN; i++) ResV[i] = 0.0;\n    for (j = 0; j < ColN; j++) {\n        const TIntFltKdV& ColV = ColSpVV[j]; int len = ColV.Len();\n        for (i = 0; i < len; i++) {\n            ResV[ColV[i].Key] += ColV[i].Dat * B(j,ColId);\n        }\n    }\n}\n\nvoid TSparseColMatrix::PMultiply(const TFltV& Vec, TFltV& Result) const {\n    EAssert(Vec.Len() >= ColN && Result.Len() >= RowN);\n    int i, j; TFlt *ResV = Result.BegI();\n    for (i = 0; i < RowN; i++) ResV[i] = 0.0;\n    for (j = 0; j < ColN; j++) {\n        const TIntFltKdV& ColV = ColSpVV[j]; int len = ColV.Len();\n        for (i = 0; i < len; i++) {\n            ResV[ColV[i].Key] += ColV[i].Dat * Vec[j];\n        }\n    }\n}\n\nvoid TSparseColMatrix::PMultiplyT(const TFltVV& B, int ColId, TFltV& Result) const {\n    EAssert(B.GetRows() >= RowN && Result.Len() >= ColN);\n    int i, j, len; TFlt *ResV = Result.BegI();\n    for (j = 0; j < ColN; j++) {\n        const TIntFltKdV& ColV = ColSpVV[j];\n        len = ColV.Len(); ResV[j] = 0.0;\n        for (i = 0; i < len; i++) {\n            ResV[j] += ColV[i].Dat * B(ColV[i].Key, ColId);\n        }\n    }\n}\n\nvoid TSparseColMatrix::PMultiplyT(const TFltV& Vec, TFltV& Result) const {\n    EAssert(Vec.Len() >= RowN && Result.Len() >= ColN);\n    int i, j, len; TFlt *VecV = Vec.BegI(), *ResV = Result.BegI();\n    for (j = 0; j < ColN; j++) {\n        const TIntFltKdV& ColV = ColSpVV[j];\n        len = ColV.Len(); ResV[j] = 0.0;\n        for (i = 0; i < len; i++) {\n            ResV[j] += ColV[i].Dat * VecV[ColV[i].Key];\n        }\n    }\n}\n\nvoid TSparseColMatrix::PMultiply(const TFltVV& B, TFltVV& Result) const {\n\tTLinAlg::Multiply(ColSpVV, B, Result, RowN);\n}\n\nvoid TSparseColMatrix::PMultiplyT(const TFltVV& B, TFltVV& Result) const {\n\tTLinAlg::MultiplyT(ColSpVV, B, Result);\n}\n\nvoid TSparseColMatrix::Init() {\n    ColN = ColSpVV.Len();\n    for (int Col = 0; Col < ColN; Col++) {\n        if (ColSpVV[Col].Empty()) { continue; }\n        if (ColSpVV[Col].Last().Key >= RowN) {\n            RowN = ColSpVV[Col].Last().Key + 1;\n        }\n    }\n}\n\n///////////////////////////////////////////////////////////////////////\n// Sparse-Row-Matrix\nTSparseRowMatrix::TSparseRowMatrix(const TStr& MatlabMatrixFNm) {\n   FILE *F = fopen(MatlabMatrixFNm.CStr(), \"rt\");  EAssert(F != NULL);\n   TVec<TTriple<TInt, TInt, TSFlt> > MtxV;\n   RowN = 0;  ColN = 0;\n   while (! feof(F)) {\n     int row=-1, col=-1; float val;\n     if (fscanf(F, \"%d %d %f\\n\", &row, &col, &val) == 3) {\n       EAssert(row > 0 && col > 0);\n       MtxV.Add(TTriple<TInt, TInt, TSFlt>(row, col, val));\n       RowN = TMath::Mx(RowN.Val, row);\n       ColN = TMath::Mx(ColN.Val, col);\n     }\n   }\n   fclose(F);\n   // create matrix\n   MtxV.Sort();\n   RowSpVV.Gen(RowN);\n   int cnt = 0;\n   for (int row = 1; row <= RowN; row++) {\n     while (cnt < MtxV.Len() && MtxV[cnt].Val1 == row) {\n       RowSpVV[row-1].Add(TIntFltKd(MtxV[cnt].Val2-1, MtxV[cnt].Val3()));\n       cnt++;\n     }\n   }\n}\n\nvoid TSparseRowMatrix::PMultiplyT(const TFltVV& B, int ColId, TFltV& Result) const {\n    EAssert(B.GetRows() >= RowN && Result.Len() >= ColN);\n    for (int i = 0; i < ColN; i++) Result[i] = 0.0;\n    for (int j = 0; j < RowN; j++) {\n        const TIntFltKdV& RowV = RowSpVV[j]; int len = RowV.Len();\n        for (int i = 0; i < len; i++) {\n            Result[RowV[i].Key] += RowV[i].Dat * B(j,ColId);\n        }\n    }\n}\n\nvoid TSparseRowMatrix::PMultiplyT(const TFltV& Vec, TFltV& Result) const {\n    EAssert(Vec.Len() >= RowN && Result.Len() >= ColN);\n    for (int i = 0; i < ColN; i++) Result[i] = 0.0;\n    for (int j = 0; j < RowN; j++) {\n        const TIntFltKdV& RowV = RowSpVV[j]; int len = RowV.Len();\n        for (int i = 0; i < len; i++) {\n            Result[RowV[i].Key] += RowV[i].Dat * Vec[j];\n        }\n    }\n}\n\nvoid TSparseRowMatrix::PMultiply(const TFltVV& B, int ColId, TFltV& Result) const {\n    EAssert(B.GetRows() >= ColN && Result.Len() >= RowN);\n    for (int j = 0; j < RowN; j++) {\n        const TIntFltKdV& RowV = RowSpVV[j];\n        int len = RowV.Len(); Result[j] = 0.0;\n        for (int i = 0; i < len; i++) {\n            Result[j] += RowV[i].Dat * B(RowV[i].Key, ColId);\n        }\n    }\n}\n\nvoid TSparseRowMatrix::PMultiply(const TFltV& Vec, TFltV& Result) const {\n    EAssert(Vec.Len() >= ColN && Result.Len() >= RowN);\n    for (int j = 0; j < RowN; j++) {\n        const TIntFltKdV& RowV = RowSpVV[j];\n        int len = RowV.Len(); Result[j] = 0.0;\n        for (int i = 0; i < len; i++) {\n            Result[j] += RowV[i].Dat * Vec[RowV[i].Key];\n        }\n    }\n}\n\nvoid TSparseRowMatrix::Init() {\n    RowN = RowSpVV.Len();\n    for (int Row = 0; Row < RowN; Row++) {\n        if (RowSpVV[Row].Empty()) { continue; }\n        if (RowSpVV[Row].Last().Key >= ColN) {\n            ColN = RowSpVV[Row].Last().Key + 1;\n        }\n    }\n}\n\n///////////////////////////////////////////////////////////////////////\n// Full-Col-Matrix\nTFullColMatrix::TFullColMatrix(const TStr& MatlabMatrixFNm): TMatrix() {\n    TLinAlgIO::LoadMatlabTFltVV(MatlabMatrixFNm, ColV);\n    RowN=ColV[0].Len(); ColN=ColV.Len();\n    for (int i = 0; i < ColN; i++) {\n        EAssertR(ColV[i].Len() == RowN, TStr::Fmt(\"%d != %d\", ColV[i].Len(), RowN));\n    }\n}\n\nTFullColMatrix::TFullColMatrix(TVec<TFltV>& FullM): TMatrix(), ColV(FullM) {\n\t RowN=FullM.Len(); ColN=FullM[0].Len();\n}\n\nvoid TFullColMatrix::PMultiplyT(const TFltVV& B, int ColId, TFltV& Result) const {\n    EAssert(B.GetRows() >= RowN && Result.Len() >= ColN);\n    for (int i = 0; i < ColN; i++) {\n        Result[i] = TLinAlg::DotProduct(B, ColId, ColV[i]);\n    }\n}\n\nvoid TFullColMatrix::PMultiplyT(const TFltV& Vec, TFltV& Result) const {\n    EAssert(Vec.Len() >= RowN && Result.Len() >= ColN);\n    for (int i = 0; i < ColN; i++) {\n        Result[i] = TLinAlg::DotProduct(Vec, ColV[i]);\n    }\n}\n\nvoid TFullColMatrix::PMultiply(const TFltVV& B, int ColId, TFltV& Result) const {\n    EAssert(B.GetRows() >= ColN && Result.Len() >= RowN);\n    for (int i = 0; i < RowN; i++) { Result[i] = 0.0; }\n    for (int i = 0; i < ColN; i++) {\n        TLinAlg::AddVec(B(i, ColId), ColV[i], Result, Result);\n    }\n}\n\nvoid TFullColMatrix::PMultiply(const TFltV& Vec, TFltV& Result) const {\n    EAssert(Vec.Len() >= ColN && Result.Len() >= RowN);\n    for (int i = 0; i < RowN; i++) { Result[i] = 0.0; }\n    for (int i = 0; i < ColN; i++) {\n        TLinAlg::AddVec(Vec[i], ColV[i], Result, Result);\n    }\n}\n\n///////////////////////////////////////////////////////////////////////\n// Structured-Covariance-Matrix\nvoid TStructuredCovarianceMatrix::PMultiply(const TFltVV& B, int ColId, TFltV& Result) const {FailR(\"Not implemented yet\");} // TODO\n\nvoid TStructuredCovarianceMatrix::PMultiply(const TFltVV& B, TFltVV& Result) const {\n\t// 1/Samples * (X - MeanX*ones(1,Samples)) (Y - MeanY*(ones(1,Samples))' B\n\t// 1/ Samples X (Y' B) - MeanX (MeanY' B)\n\tEAssert(Result.GetRows() == XRows && Result.GetCols() == B.GetCols());\n\tint BCols = B.GetCols();\n\tTFltVV YtB(Samples, BCols);;\n\tTLinAlg::MultiplyT(Y, B, YtB);\n\tTLinAlg::Multiply(X, YtB, Result); YtB.Clr();\n\n\tTFltV MeanYtB(BCols); // MeanY' B the same TFltV as  B' MeanY\t\n\tTLinAlg::MultiplyT(B, MeanY, MeanYtB);\n\t// Result := 1/SampleN Result - MeanX MeanY' B\t\n\tfor (int RowN = 0; RowN < XRows; RowN++) {\n\t\tfor (int ColN = 0; ColN < BCols; ColN++) {\n\t\t\tResult.At(RowN, ColN) = 1.0/Samples * Result.At(RowN, ColN) - MeanX[RowN]*MeanYtB[ColN];\n\t\t}\n\t}\n}; \n\nvoid TStructuredCovarianceMatrix::PMultiply(const TFltV& Vec, TFltV& Result) const {FailR(\"Not implemented yet\");} // TODO\n\nvoid TStructuredCovarianceMatrix::PMultiplyT(const TFltVV& B, int ColId, TFltV& Result) const {FailR(\"Not implemented yet\");} // TODO\n\nvoid TStructuredCovarianceMatrix::PMultiplyT(const TFltVV& B, TFltVV& Result) const {\n\t// 1/Samples * (Y - MeanY*ones(1,Samples)) (X - MeanX*(ones(1,Samples))' B\n\t// 1/ Samples Y (X' B) - MeanY (MeanX' B)\n\tEAssert(Result.GetRows() == YRows && Result.GetCols() == B.GetCols());\n\tint BCols = B.GetCols();\n\tTFltVV XtB(Samples, BCols);\n\tTLinAlg::MultiplyT(X, B, XtB);\n\tTLinAlg::Multiply(Y, XtB, Result); XtB.Clr();\n\n\tTFltV MeanXtB(BCols); // MeanX' B the same TFltV as  B' MeanX\n\tTLinAlg::MultiplyT(B, MeanX, MeanXtB);\n\t// Result := 1/SampleN Result - MeanY MeanX' B\t\n\tfor (int RowN = 0; RowN < YRows; RowN++) {\n\t\tfor (int ColN = 0; ColN < BCols; ColN++) {\n\t\t\tResult.At(RowN, ColN) = 1.0/Samples * Result.At(RowN, ColN) - MeanY[RowN]*MeanXtB[ColN];\n\t\t}\n\t}\n};\n\nvoid TStructuredCovarianceMatrix::PMultiplyT(const TFltV& Vec, TFltV& Result) const {\n    FailR(\"Not implemented yet\"); // TODO\n}\n\n//////////////////////////////////////////////////////////////////////\n// Linear algebra input/output operations\nvoid TLinAlgIO::SaveCsvTFltV(const TFltV& Vec, TSOut& SOut) {\n    for (int ValN = 0; ValN < Vec.Len(); ValN++) {\n        SOut.PutFlt(Vec[ValN]); SOut.PutCh(',');\n    }\n    SOut.PutLn();\n}\n\nvoid TLinAlgIO::SaveMatlabTFltIntKdV(const TIntFltKdV& SpV, const int& ColN, TSOut& SOut) {\n    const int Len = SpV.Len();\n    for (int ValN = 0; ValN < Len; ValN++) {\n        SOut.PutStrLn(TStr::Fmt(\"%d %d %g\", SpV[ValN].Key+1, ColN+1, SpV[ValN].Dat()));\n    }\n}\n\nvoid TLinAlgIO::SaveMatlabSpMat(const TVec<TIntFltKdV>& SpMat, TSOut& SOut) {\n\tint Cols = SpMat.Len();\n\tfor (int ColN = 0; ColN < Cols; ColN++) {\n\t\tint Els = SpMat[ColN].Len();\n\t\tfor (int ElN = 0; ElN < Els; ElN++) {\n\t\t\tSOut.PutStrLn(SpMat[ColN][ElN].Key.GetStr() + \" \" + TInt::GetStr(ColN) + \" \" + TStr::Fmt(\"%.17g\", SpMat[ColN][ElN].Dat.Val));\n\t\t}\n\t}\n\tSOut.Flush();\n}\n\n\nvoid TLinAlgIO::SaveMatlabSpMat(const TTriple<TIntV, TIntV,TFltV>& SpMat, TSOut& SOut) {\n\tint Len = SpMat.Val1.Len();\n\tfor (int ElN = 0; ElN < Len; ElN++) {\n\t\tSOut.PutStrLn(SpMat.Val1[ElN].GetStr() + \" \" + SpMat.Val2[ElN].GetStr() + \" \" + SpMat.Val3[ElN].GetStr());\n\t}\n\tSOut.Flush();\n}\n\nvoid TLinAlgIO::SaveMatlabTFltV(const TFltV& m, const TStr& FName) {\n    PSOut out = TFOut::New(FName);\n    const int RowN = m.Len();\n    for (int RowId = 0; RowId < RowN; RowId++) {\n        out->PutStr(TFlt::GetStr(m[RowId], 20, 18));\n        out->PutCh('\\n');\n    }\n    out->Flush();\n}\n\nvoid TLinAlgIO::SaveMatlabTIntV(const TIntV& m, const TStr& FName) {\n    PSOut out = TFOut::New(FName);\n    const int RowN = m.Len();\n    for (int RowId = 0; RowId < RowN; RowId++) {\n        out->PutInt(m[RowId]);\n        out->PutCh('\\n');\n    }\n    out->Flush();\n}\n\nvoid TLinAlgIO::SaveMatlabTFltVVCol(const TFltVV& m, int ColId, const TStr& FName) {\n    PSOut out = TFOut::New(FName);\n    const int RowN = m.GetRows();\n    for (int RowId = 0; RowId < RowN; RowId++) {\n        out->PutStr(TFlt::GetStr(m(RowId,ColId), 20, 18));\n        out->PutCh('\\n');\n    }\n    out->Flush();\n}\n\n\nvoid TLinAlgIO::SaveMatlabTFltVV(const TFltVV& m, const TStr& FName) {\n    PSOut out = TFOut::New(FName);\n    TLinAlgIO::SaveMatlabTFltVV(m, *out);\n}\n\nvoid TLinAlgIO::SaveMatlabTFltVV(const TFltVV& m, TSOut& SOut) {\n\tconst int RowN = m.GetRows();\n\tconst int ColN = m.GetCols();\n\tfor (int RowId = 0; RowId < RowN; RowId++) {\n\t\tfor (int ColId = 0; ColId < ColN; ColId++) {\n\t\t\tSOut.PutStr(TFlt::GetStr(m(RowId, ColId), 20, 18));\n\t\t\tSOut.PutCh(' ');\n\t\t}\n\t\tSOut.PutCh('\\n');\n\t}\n\tSOut.Flush();\n}\n\nvoid TLinAlgIO::SaveMatlabTFltVVMjrSubMtrx(const TFltVV& m,\n        int RowN, int ColN, const TStr& FName) {\n\n    PSOut out = TFOut::New(FName);\n    for (int RowId = 0; RowId < RowN; RowId++) {\n        for (int ColId = 0; ColId < ColN; ColId++) {\n            out->PutStr(TFlt::GetStr(m(RowId,ColId), 20, 18)); out->PutCh(' ');\n        }\n        out->PutCh('\\n');\n    }\n    out->Flush();\n}\n\nvoid TLinAlgIO::LoadMatlabTFltVV(const TStr& FNm, TVec<TFltV>& ColV) {\n    PSIn SIn = TFIn::New(FNm);\n    TLinAlgIO::LoadMatlabTFltVV(ColV, *SIn);\n}\n\nvoid TLinAlgIO::LoadMatlabTFltVV(const TStr& FNm, TFltVV& MatrixVV) {\n\tPSIn SIn = TFIn::New(FNm);\n\tTLinAlgIO::LoadMatlabTFltVV(MatrixVV, *SIn);\n}\n\nvoid TLinAlgIO::LoadMatlabTFltVV(TFltVV& MatrixVV, TSIn& SIn) {\n\tTVec<TFltV> ColV; LoadMatlabTFltVV(ColV, SIn);\n\tif (ColV.Empty()) { MatrixVV.Clr(); return; }\n\tconst int Rows = ColV[0].Len(), Cols = ColV.Len();\n\tMatrixVV.Gen(Rows, Cols);\n\tfor (int RowN = 0; RowN < Rows; RowN++) {\n\t\tfor (int ColN = 0; ColN < Cols; ColN++) {\n\t\t\tMatrixVV(RowN, ColN) = ColV[ColN][RowN];\n\t\t}\n\t}\n}\n\nvoid TLinAlgIO::LoadMatlabTFltVV(TVec<TFltV>& ColV, TSIn& SIn) {\n\tTILx Lx(&SIn, TFSet() | iloRetEoln | iloSigNum | iloExcept);\n\tint Row = 0, Col = 0; ColV.Clr();\n\tLx.GetSym(syFlt, syEof, syEoln);\n\t//printf(\"%d x %d\\r\", Row, ColV.Len());\n\twhile (Lx.Sym != syEof) {\n\t\tif (Lx.Sym == syFlt) {\n\t\t\tif (ColV.Len() > Col) {\n\t\t\t\tEAssert(ColV[Col].Len() == Row);\n\t\t\t\tColV[Col].Add(Lx.Flt);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tEAssert(Row == 0);\n\t\t\t\tColV.Add(TFltV::GetV(Lx.Flt));\n\t\t\t}\n\t\t\tCol++;\n\t\t}\n\t\telse if (Lx.Sym == syEoln) {\n\t\t\tEAssert(Col == ColV.Len());\n\t\t\tCol = 0; Row++;\n\t\t\tif (Row % 100 == 0) {\n\t\t\t\t//printf(\"%d x %d\\r\", Row, ColV.Len());\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tFail;\n\t\t}\n\t\tLx.GetSym(syFlt, syEof, syEoln);\n\t}\n\t//printf(\"\\n\");\n\tEAssert(Col == ColV.Len() || Col == 0);\n}\n\nvoid TLinAlgIO::PrintTFltV(const TFltV& Vec, const TStr& VecNm) {\n    printf(\"%s = [\", VecNm.CStr());\n    for (int i = 0; i < Vec.Len(); i++) {\n        printf(\"%.5f\", Vec[i]());\n\t\tif (i < Vec.Len() - 1) { printf(\", \"); }\n    }\n    printf(\"]\\n\");\n}\n\nvoid TLinAlgIO::PrintTFltVVToStr(const TFltVV& A, TStr& Out) {\n\tOut = \"\";\n\tint Rows = A.GetRows();\n\tint Cols = A.GetCols();\n\tfor (int RowN = 0; RowN < Rows; RowN++) {\n\t\tfor (int ColN = 0; ColN < Cols; ColN++) {\n\t\t\tOut += A.At(RowN,ColN).GetStr() + \" \";\n\t\t}\n\t\tOut += \"\\n\";\n\t}\n    Out += \"\\n\";\n\n}\n\nvoid TLinAlgIO::PrintTFltVV(const TFltVV& A, const TStr& MatrixNm) {\n    printf(\"%s = [\\n\", MatrixNm.CStr());\n\tint Rows = A.GetRows();\n\tint Cols = A.GetCols();\n\tfor (int RowN = 0; RowN < Rows; RowN++) {\n\t\tfor (int ColN = 0; ColN < Cols; ColN++) {\n\t\t\tprintf(\"%f \", A.At(RowN, ColN).Val);\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n    printf(\"]\\n\");\n}\n\nvoid TLinAlgIO::PrintSpMat(const TTriple<TIntV, TIntV, TFltV>& A, const TStr& MatrixNm) {\n\tint Nonzeros = A.Val1.Len();\n\tprintf(\"%s = [\\n\", MatrixNm.CStr());\n\tfor (int ElN = 0; ElN < Nonzeros; ElN++) {\n\t\tprintf(\"%d %d %f\\n\", A.Val1[ElN].Val, A.Val2[ElN].Val, A.Val3[ElN].Val);\n\t}\n\tprintf(\"]\\n\");\n}\n\nvoid TLinAlgIO::PrintSpMat(const TVec<TIntFltKdV>& A, const TStr& MatrixNm) {\n\tprintf(\"%s = [\\n\", MatrixNm.CStr());\n\tint Cols = A.Len();\n\tfor (int ColN = 0; ColN < Cols; ColN++) {\n\t\tint Els = A[ColN].Len();\n\t\tfor (int ElN = 0; ElN < Els; ElN++) {\n\t\t\tprintf(\"%d %d %f\\n\", A[ColN][ElN].Key.Val, ColN, A[ColN][ElN].Dat.Val);\n\t\t}\n\t}\n\tprintf(\"]\\n\");\n}\n\nvoid TLinAlgIO::PrintTIntV(const TIntV& Vec, const TStr& VecNm) {\n    printf(\"%s = [\", VecNm.CStr());\n    for (int i = 0; i < Vec.Len(); i++) {\n        printf(\"%d\", Vec[i]());\n        if (i < Vec.Len() - 1) printf(\", \");\n    }\n    printf(\"]\\n\");\n}\n\n//////////////////////////////////////////////////////////////////////\n// Statistics on linear algebra structures\ndouble TLinAlgStat::Mean(const TFltV& Vec) {\n\t EAssertR(Vec.Len() != 0, \"TLAMisc::Mean: Vector length should not be zero\");\n\t return TLinAlg::SumVec(Vec) / Vec.Len();\n}\n\nvoid TLinAlgStat::Mean(const TFltVV& Mat, TFltV& Res, const TMatDim& Dim) {\n\t int Rows = Mat.GetRows();\n\t int Cols = Mat.GetCols();\n\t if (Dim == TMatDim::mdCols) {\n\t\t if (Res.Len() != Cols) {\n\t\t\t Res.Gen(Cols);\n\t\t }\n\t\t TFltV Vec(Rows);\n\t\t Vec.PutAll(1.0 / Rows);\n\t\t TLinAlg::MultiplyT(Mat, Vec, Res);\n\t } else if (Dim == TMatDim::mdRows) {\n\t\t if (Res.Len() != Rows) {\n\t\t\t Res.Gen(Rows);\n\t\t }\n\t\t TFltV Vec(Cols);\n\t\t Vec.PutAll(1.0 / Cols);\n\t\t TLinAlg::Multiply(Mat, Vec, Res);\n\t }\n}\n\ndouble TLinAlgStat::Std(const TFltV& Vec, const int& Flag) {\n    EAssertR(Flag == 0 || Flag == 1, \"TLAMisc::Std: Invalid value of 'Flag' argument. \"\n        \"Supported 'Flag' arguments are 0 or 1. See Matlab std() documentation.\");\n\n    int Len = Vec.Len();\n\n    double Mean = TLinAlgStat::Mean(Vec);\n    double Scalar = (Flag == 1) ? TMath::Sqrt(1.0 / (Len)) : TMath::Sqrt(1.0 / (Len - 1));\n\n    TFltV TempRes(Len);\n    TFltV Ones(Len);\n    Ones.PutAll(1.0);\n\n    TLinAlg::LinComb(-1, Vec, Mean, Ones, TempRes);\n    return Scalar * TLinAlg::Norm(TempRes);\n}\n\nvoid TLinAlgStat::Std(const TFltVV& Mat, TFltV& Res, const int& Flag, const TMatDim& Dim) {\n\tEAssertR(Flag == 0 || Flag == 1, \"TLAMisc::Std: Invalid value of 'Flag' argument. \"\n\t\t\t\t\t\t\t\"Supported 'Flag' arguments are 0 or 1. See Matlab std() documentation.\");\n\tint Cols = Mat.GetCols();\n\tint Rows = Mat.GetRows();\n\tTFltV MeanVec;\n\tTLinAlgStat::Mean(Mat, MeanVec, Dim);\n\tEAssertR(Cols == MeanVec.Len() || Rows == MeanVec.Len(), \"TLAMisc::Std\");\n\n\tif (Dim == TMatDim::mdCols) {\n\t\tif(Res.Empty()) Res.Gen(Cols);\n\t\tEAssertR(Cols == Res.Len(), \"TLAMisc::Std\");\n\n\t\tdouble Scalar = (Flag == 1) ? TMath::Sqrt(1.0/(Rows)) : TMath::Sqrt(1.0/(Rows-1));\n\t\tTFltV TempRes(Rows);\n\t\tTFltV Ones(Rows);\n\t\tOnes.PutAll(1.0);\n\n\t\tfor (int ColN = 0; ColN < Cols; ColN++) {\n\t\t\tTLinAlg::LinComb(-1.0, Mat, ColN, MeanVec[ColN], Ones, TempRes);\n\t\t\tRes[ColN] = Scalar * TLinAlg::Norm(TempRes);\n\t\t}\n\t}\n\telse if (Dim == TMatDim::mdRows) {\n\t\tif(Res.Empty()) Res.Gen(Rows);\n\t\tEAssertR(Rows == Res.Len(), \"TLAMisc::Std\");\n\n\t\tdouble Scalar = (Flag == 1) ? TMath::Sqrt(1.0/(Cols)) : TMath::Sqrt(1.0/(Cols-1));\n\t\tTFltV TempRes(Cols);\n\t\tTFltV Ones(Cols);\n\t\tOnes.PutAll(1.0);\n\n\t\tfor (int RowN = 0; RowN < Rows; RowN++) {\n\t\t\tTLinAlg::LinComb(-1.0, Mat, RowN, MeanVec[RowN], Ones, TempRes, 2);\n\t\t\tRes[RowN] = Scalar * TLinAlg::Norm(TempRes);\n\t\t}\n\t}\n}\n\nvoid TLinAlgStat::ZScore(const TFltVV& Mat, TFltVV& Res, const int& Flag, const TMatDim& Dim) {\n\tEAssertR(Flag == 0 || Flag == 1, \"TLAMisc::ZScore: Invalid value of 'Flag' argument. \"\n\t\t\t\t\t\t\t\"Supported 'Flag' arguments are 0 or 1. See Matlab std() documentation.\");\n\n\tint Cols = Mat.GetCols();\n\tint Rows = Mat.GetRows();\n\n\tif (Res.Empty()) Res.Gen(Rows, Cols);\n\n\tTFltV MeanVec;\n\tTLinAlgStat::Mean(Mat, MeanVec, Dim);\n\tTFltV StdVec;\n\tTLinAlgStat::Std(Mat, StdVec, Flag, Dim);\n\n\tif (Dim == TMatDim::mdCols) {\n\n\t\tTFltV TempRes(Rows);\n\t\tTFltV Ones(Rows);\n\t\tOnes.PutAll(1.0);\n\n\t\tfor (int ColN = 0; ColN < Cols; ColN++) {\n\t\t\tTLinAlg::LinComb(1.0/StdVec[ColN], Mat, ColN, -1.0 * MeanVec[ColN]/StdVec[ColN], Ones, TempRes);\n\t\t\tfor (int RowN = 0; RowN < Rows; RowN++) {\n\t\t\t\tRes.At(RowN, ColN) = TempRes[RowN];\n\t\t\t}\n\t\t}\n\t}\n\telse if (Dim == TMatDim::mdRows) {\n\n\t\tTFltV TempRes(Cols);\n\t\tTFltV Ones(Cols);\n\t\tOnes.PutAll(1.0);\n\n\t\tfor (int RowN = 0; RowN < Rows; RowN++) {\n\t\t\tTLinAlg::LinComb(1.0/StdVec[RowN], Mat, RowN, -1.0 * MeanVec[RowN]/StdVec[RowN], Ones, TempRes, 2);\n\t\t\tfor (int ColN = 0; ColN < Cols; ColN++) {\n\t\t\t\tRes.At(RowN, ColN) = TempRes[ColN];\n\t\t\t}\n\t\t}\n\t}\n}\n\n//////////////////////////////////////////////////////////////////////\n/// Transformations of linear algebra structures\nvoid TLinAlgTransform::Fill(TFltVV& A, const double& val) {\n\tconst int Rows = A.GetRows();\n\tconst int Cols = A.GetCols();\n\tfor (int RowN = 0; RowN < Rows; RowN++) {\n\t\tfor (int ColN = 0; ColN < Cols; ColN++) {\n\t\t\tA.PutXY(RowN, ColN, val);\n\t\t}\n\t}\n}\n\nvoid TLinAlgTransform::Fill(TFltV& V, const double& val){\n\tconst int n = V.Len();\n\tfor (int i = 0; i < n; i++){\n\t\tV[i] = val;\n\t}\n}\n\nvoid TLinAlgTransform::FillRnd(const int& Len, TFltV& Vec, TRnd& Rnd) {\n    Vec.Gen(Len);\n    for(int i = 0; i < Len; i++) {\n        Vec[i] = Rnd.GetUniDev();\n    }\n}\n\nvoid TLinAlgTransform::FillIdentity(TFltVV& M) {\n    EAssert(M.GetRows() == M.GetCols());\n    int Len = M.GetRows();\n    for (int i = 0; i < Len; i++) {\n        for (int j = 0; j < Len; j++) M(i,j) = 0.0;\n        M(i,i) = 1.0;\n    }\n}\n\nvoid TLinAlgTransform::FillIdentity(TFltVV& M, const double& Elt) {\n    EAssert(M.GetRows() == M.GetCols());\n    int Len = M.GetRows();\n    for (int i = 0; i < Len; i++) {\n        for (int j = 0; j < Len; j++) M(i,j) = 0.0;\n        M(i,i) = Elt;\n    }\n}\n\n/*void TLinAlgTransform::FillRange(const int& Vals, TFltV& Vec) {\n\t//Added by Andrej\n\tif (Vec.Len() != Vals){\n\t\tVec.Gen(Vals);\n\t}\n\tfor(int i = 0; i < Vals; i++){\n\t\tVec[i] = i;\n\t}\n}\nvoid TLinAlgTransform::FillRange(const int& Vals, TIntV& Vec) {\n\t//Added by Andrej\n\tif (Vec.Len() != Vals){\n\t\tVec.Gen(Vals);\n\t}\n\tfor (int i = 0; i < Vals; i++){\n\t\tVec[i] = i;\n\t}\n}*/\n\n//void TLinAlgTransform::Diag(const TFltV& Vec, TFltVV& Mat) {\n//\tMat.Gen(Vec.Len(), Vec.Len());\n//\tMat.PutAll(0.0);\n//\tfor (int ElN = 0; ElN < Vec.Len(); ElN++) {\n//\t\tMat.At(ElN, ElN) = Vec[ElN];\n//\t}\n//}\n\nvoid TLinAlgTransform::ToSpVec(const TFltV& Vec, TIntFltKdV& SpVec,\n        const double& CutSumPrc) {\n\n    // determine minimal element value\n    EAssert(0.0 <= CutSumPrc && CutSumPrc <= 1.0);\n    const int Elts = Vec.Len();\n    double EltSum = 0.0;\n    for (int EltN = 0; EltN < Elts; EltN++) {\n        EltSum += TFlt::Abs(Vec[EltN]); }\n    const double MnEltVal = CutSumPrc * EltSum;\n    // create sparse vector\n    SpVec.Clr();\n    for (int EltN = 0; EltN < Elts; EltN++) {\n        if (TFlt::Abs(Vec[EltN]) > MnEltVal) {\n            SpVec.Add(TIntFltKd(EltN, Vec[EltN]));\n        }\n    }\n    SpVec.Pack();\n}\n\nvoid TLinAlgTransform::ToVec(const TIntFltKdV& SpVec, TFltV& Vec, const int& VecLen) {\n    Vec.Gen(VecLen); Vec.PutAll(0.0);\n    int Elts = SpVec.Len();\n    for (int EltN = 0; EltN < Elts; EltN++) {\n        if (SpVec[EltN].Key < VecLen) {\n            Vec[SpVec[EltN].Key] = SpVec[EltN].Dat;\n        }\n    }\n}\n\nvoid TLinAlgTransform::Convert(const TVec<TPair<TIntV, TFltV>>& A, TTriple<TIntV, TIntV, TFltV>& B) {\n\tB.Val1.Clr();\n\tB.Val2.Clr();\n\tB.Val3.Clr();\n\tint Cols = A.Len();\n\tfor (int ColN = 0; ColN < Cols; ColN++) {\n\t\tint Nnz = A[ColN].Val1.Len();\n\t\tfor (int ElN = 0; ElN < Nnz; ElN++) {\n\t\t\tB.Val1.Add(A[ColN].Val1[ElN]);\n\t\t\tB.Val2.Add(ColN);\n\t\t\tB.Val3.Add(A[ColN].Val2[ElN]);\n\t\t}\n\t}\n}\n\nvoid TLinAlgTransform::Convert(const TVec<TIntFltKdV>& A, TTriple<TIntV, TIntV, TFltV>&B) {\n\tint Cols = A.Len();\n\tint TotalNnz = 0;\n\tfor (int ColN = 0; ColN < Cols; ColN++) {\n\t\tTotalNnz += A[ColN].Len();\n\t}\n\tB.Val1.Gen(TotalNnz, 0);\n\tB.Val2.Gen(TotalNnz, 0);\n\tB.Val3.Gen(TotalNnz, 0);\n\tfor (int ColN = 0; ColN < Cols; ColN++) {\n\t\tint Nnz = A[ColN].Len();\n\t\tfor (int ElN = 0; ElN < Nnz; ElN++) {\n\t\t\tB.Val1.Add(A[ColN][ElN].Key);\n\t\t\tB.Val2.Add(ColN);\n\t\t\tB.Val3.Add(A[ColN][ElN].Dat);\n\t\t}\n\t}\n}\n\n//////////////////////////////////////////////////////////////////////\n/// Contains methods to check the properties of linear algebra structures\nbool TLinAlgCheck::IsZeroTol(const TFltV& Vec, const double& Eps) {\n\tbool IsZero = true;\n\tfor (int i = 0; i < Vec.Len(); i++) {\n\t\tif (!TMath::IsInEps((double)Vec[i], Eps)) {\n\t\t\tIsZero = false;\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn IsZero;\n}\n\nbool TLinAlgCheck::IsOrthonormal(const TFltVV& Vecs, const double& Threshold) {\n\tint m = Vecs.GetCols();\n\tTFltVV R(m, m);\n\tTLinAlg::MultiplyT(Vecs, Vecs, R);\n\tfor (int i = 0; i < m; i++) { R(i, i) -= 1; }\n\treturn TLinAlg::Frob(R) < Threshold;\n}\n\n////////////////////////////////////////////////////////////////////////\n//// Basic Linear Algebra Operations\nvoid TLinAlg::LinComb(const double& p, const TIntFltKdV& x, const double& q, const TIntFltKdV& y, TIntFltKdV& z) {\n\tTSparseOpsIntFlt::SparseLinComb(p, x, q, y, z);\n}\n\nvoid TLinAlg::LinComb(const double& p, const TVec<TIntFltKdV>& X, const double& q, const TVec<TIntFltKdV>& Y, TVec<TIntFltKdV>& Z) {\n    if (Z.Empty()) { Z.Gen(X.Len()); }\n    EAssert(X.Len() == Y.Len() && Y.Len() == Z.Len());\n    int Cols = X.Len();\n    for (int ColN = 0; ColN < Cols; ColN++) {\n        TLinAlg::LinComb(p, X[ColN], q, Y[ColN], Z[ColN]);\n    }\n}\n\nvoid TLinAlg::LinComb(const double& p, const TFltVV& X, const double& q, const TVec<TIntFltKdV>& Y, TFltVV& Z) {\n    if (Z.Empty()) { Z.Gen(X.GetRows(), X.GetCols()); }\n    EAssert(X.GetRows() >= TLinAlgSearch::GetMaxDimIdx(Y) && X.GetCols() == Y.Len() && X.GetRows() == Z.GetRows() && X.GetCols() == Z.GetCols());\n    int Rows = X.GetRows();\n    int Cols = X.GetCols();\n    for (int ColN = 0; ColN < Cols; ColN++) {\n        int KeyN = 0;\n        for (int RowN = 0; RowN < Rows; RowN++) {\n            Z.At(RowN, ColN) = p*X.At(RowN, ColN);\n            if (KeyN < Y[ColN].Len() && Y[ColN][KeyN].Key == RowN) {\n                Z.At(RowN, ColN) += q*Y[ColN][KeyN].Dat; KeyN++;\n            }\n        }\n    }\n}\n\nvoid TLinAlg::LinComb(const double& p, const TVec<TIntFltKdV>& X, const double& q, TFltVV const& Y, TVec<TIntFltKdV>& Z) {\n    if (Z.Empty()) { Z.Gen(Y.GetCols()); }\n    EAssert(TLinAlgSearch::GetMaxDimIdx(X) <= Y.GetRows() && X.Len() == Y.GetCols() && Y.GetCols() == Z.Len());\n    int Rows = Y.GetRows();\n    int Cols = Y.GetCols();\n    for (int ColN = 0; ColN < Cols; ColN++) {\n        int KeyN = 0;\n        for (int RowN = 0; RowN < Rows; RowN++) {\n            if (X[ColN][KeyN].Key == RowN) {\n                Z[ColN].Add(TIntFltKd(RowN, p*X[ColN][KeyN].Dat + q*Y.At(RowN, ColN))); KeyN++;\n            }\n            else {\n                Z[ColN].Add(TIntFltKd(RowN, q*Y.At(RowN, ColN)));\n            }\n        }\n    }\n}\n\nvoid TLinAlg::AddVec(const double& k, const TVec<TFltV>& X, int ColId, const TFltV& y, TFltV& z) {\n\tEAssert(0 <= ColId && ColId < X.Len());\n\tAddVec(k, X[ColId], y, z);\n}\n\nvoid TLinAlg::AddVec(const double& k, const TFltVV& X, int ColId, const TFltV& y, TFltV& z) {\n\tEAssert(X.GetRows() == y.Len());\n\tEAssert(y.Len() == z.Len());\n\tconst int len = z.Len();\n\tfor (int i = 0; i < len; i++) {\n\t\tz[i] = y[i] + k * X(i, ColId);\n\t}\n}\n\nvoid TLinAlg::AddVec(const double& k, const TVec<TIntFltKdV>& X, int ColId, const TFltV& y, TFltV& z) {\n\tEAssert(0 <= ColId && ColId < X.Len());\n\tAddVec(k, X[ColId], y, z);\n}\n\nvoid TLinAlg::AddVec(const double& k, const TIntFltKdV& x, TFltV& y) {\n\tconst int xLen = x.Len(), yLen = y.Len();\n\tfor (int i = 0; i < xLen; i++) {\n\t\tconst int ii = x[i].Key;\n\t\tif (ii < yLen) {\n\t\t\ty[ii] += k * x[i].Dat;\n\t\t}\n\t}\n}\n\nvoid TLinAlg::AddVec(const TIntFltKdV& x, const TIntFltKdV& y, TIntFltKdV& z) {\n\tTSparseOpsIntFlt::SparseMerge(x, y, z);\n}\n\ndouble TLinAlg::EuclDist2(const TFltPr& x, const TFltPr& y) {\n\treturn TMath::Sqr(x.Val1 - y.Val1) + TMath::Sqr(x.Val2 - y.Val2);\n}\n\ndouble TLinAlg::EuclDist(const TFltPr& x, const TFltPr& y) {\n\treturn sqrt(TLinAlg::EuclDist2(x, y));\n}\n\nvoid TLinAlg::Transpose(const TVec<TIntFltKdV>& A, TVec<TIntFltKdV>& At, int Rows){\n\t// A is a sparse col matrix:\n\tint Cols = A.Len();\n\t// find number of rows\n\tif (Rows == -1) {\n\t\tfor (int ColN = 0; ColN < Cols; ColN++) {\n\t\t\tint Els = A[ColN].Len();\n\t\t\tfor (int ElN = 0; ElN < Els; ElN++) {\n\t\t\t\tRows = MAX(Rows, A[ColN][ElN].Key.Val);\n\t\t\t}\n\t\t}\n\t\tRows = Rows + 1;\n\t}\n\tAt.Gen(Rows);\n\t// transpose\n\tfor (int ColN = 0; ColN < Cols; ColN++) {\n\t\tint Els = A[ColN].Len();\n\t\tfor (int ElN = 0; ElN < Els; ElN++) {\n\t\t\tAt[A[ColN][ElN].Key].Add(TIntFltKd(ColN, A[ColN][ElN].Dat));\n\t\t}\n\t}\n\t// sort\n\tfor (int ColN = 0; ColN < Rows; ColN++) {\n\t\tAt[ColN].Sort();\n\t}\n}\n\n//Andrej Urgent\n//TODO template --- indextype TIntFltKdV ... TInt64\nvoid TLinAlg::Multiply(const TVec<TIntFltKdV>& A, const TFltVV& B, TFltVV& C, const int RowsA) {\n\t// A = sparse column matrix\n\tEAssert(A.Len() == B.GetRows());\n\tint Rows = RowsA;\n\tint ColsB = B.GetCols();\n\tif (RowsA == -1) {\n\t\tRows = TLinAlgSearch::GetMaxDimIdx(A) + 1;\n\t}\n\telse {\n\t\tEAssert(TLinAlgSearch::GetMaxDimIdx(A) + 1 <= RowsA);\n\t}\n\tif (C.Empty()) {\n\t\tC.Gen(Rows, ColsB);\n\t}\n\tint RowsB = B.GetRows();\n\tC.PutAll(0.0);\n\tfor (int ColN = 0; ColN < ColsB; ColN++) {\n\t\tfor (int RowN = 0; RowN < RowsB; RowN++) {\n\t\t\tint Els = A[RowN].Len();\n\t\t\tfor (int ElN = 0; ElN < Els; ElN++) {\n\t\t\t\tC.At(A[RowN][ElN].Key, ColN) += A[RowN][ElN].Dat * B.At(RowN, ColN);\n\t\t\t}\n\t\t}\n\t}\n}\n// SPARSECOLMAT-SPARSECOLMAT\n\n//Andrej Urgent\n//TODO template --- indextype TIntFltKdV ... TInt64\n//TLAMisc\n//GetMaxDimIdx\nvoid TLinAlg::Multiply(const TVec<TIntFltKdV>& A, const TVec<TIntFltKdV>& B, TFltVV& C, const int RowsA) {\n\t//// A,B = sparse column matrix\n\t//EAssert(A.Len() == B.GetRows());\n\tint Rows = RowsA;\n\tint ColsB = B.Len();\n\tif (RowsA == -1) {\n\t\tRows = TLinAlgSearch::GetMaxDimIdx(A) + 1;\n\t}\n\telse {\n\t\tEAssert(TLinAlgSearch::GetMaxDimIdx(A) + 1 <= RowsA);\n\t}\n\tif (C.Empty()) {\n\t\tC.Gen(Rows, ColsB);\n\t}\n\tEAssert(TLinAlgSearch::GetMaxDimIdx(B) + 1 <= A.Len());\n\tC.PutAll(0.0);\n\tfor (int ColN = 0; ColN < ColsB; ColN++) {\n\t\tint ElsB = B[ColN].Len();\n\t\tfor (int ElBN = 0; ElBN < ElsB; ElBN++) {\n\t\t\tint IdxB = B[ColN][ElBN].Key;\n\t\t\tdouble ValB = B[ColN][ElBN].Dat;\n\t\t\tint ElsA = A[IdxB].Len();\n\t\t\tfor (int ElAN = 0; ElAN < ElsA; ElAN++) {\n\t\t\t\tint IdxA = A[IdxB][ElAN].Key;\n\t\t\t\tdouble ValA = A[IdxB][ElAN].Dat;\n\t\t\t\tC.At(IdxA, ColN) += ValA * ValB;\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid TLinAlg::Multiply(const TVec<TIntFltKdV>& A, const TVec<TIntFltKdV>& B, TVec<TIntFltKdV>& C,\n\t\tconst int RowsA) {\n    //// A,B = sparse column matrix\n    //EAssert(A.Len() == B.GetRows());\n    int Rows = RowsA;\n    int ColsB = B.Len();\n\n    if (RowsA == -1) { Rows = TLinAlgSearch::GetMaxDimIdx(A) + 1; }\n    EAssert(TLinAlgSearch::GetMaxDimIdx(A) + 1 <= Rows);\n\n    C.Gen(ColsB);\n    EAssert(TLinAlgSearch::GetMaxDimIdx(B) + 1 <= A.Len());\n\n    for (int ColN = 0; ColN < ColsB; ColN++) {\n        int ElsB = B[ColN].Len();\n        for (int ElBN = 0; ElBN < ElsB; ElBN++) {\n            int IdxB = B[ColN][ElBN].Key;\n            double ValB = B[ColN][ElBN].Dat;\n            int ElsA = A[IdxB].Len();\n            for (int ElAN = 0; ElAN < ElsA; ElAN++) {\n                int IdxA = A[IdxB][ElAN].Key;\n                double ValA = A[IdxB][ElAN].Dat;\n                C[ColN].Add(TIntFltKd(IdxA, ValA * ValB));\n            }\n        }\n    }\n}\n\nvoid TLinAlg::QR(const TFltVV& X, TFltVV& Q, TFltVV& R, const TFlt& Tol) {\n\tint Rows = X.GetRows();\n\tint Cols = X.GetCols();\n\tint d = MIN(Rows, Cols);\n\n\t// make a copy of X\n\tTFltVV A(X);\n\tif (Q.GetRows() != Rows || Q.GetCols() != d) { Q.Gen(Rows, d); }\n\tif (R.GetRows() != d || R.GetCols() != Cols) { R.Gen(d, Cols); }\n\tTRnd Random;\n\tfor (int k = 0; k < d; k++) {\n\t\tR(k, k) = TLinAlg::Norm(A, k);\n\t\t// if the remainders norm is too small we construct a random vector (handles rank deficient)\n\t\tif (R(k, k) < Tol) {\n\t\t\t// random Q(:,k)\n\t\t\tfor (int RowN = 0; RowN < Rows; RowN++) {\n\t\t\t\tQ(RowN, k) = Random.GetNrmDev();\n\t\t\t}\n\t\t\t// make it orthonormal on others\n\t\t\tfor (int j = 0; j < k; j++) {\n\t\t\t\tTLinAlg::AddVec(-TLinAlg::DotProduct(Q, j, Q, k), Q, j, Q, k);\n\t\t\t}\n\t\t\tTLinAlg::NormalizeColumn(Q, k);\n\t\t\tR(k, k) = 0;\n\t\t}\n\t\telse {\n\t\t\t// normalize\n\t\t\tfor (int RowN = 0; RowN < Rows; RowN++) {\n\t\t\t\tQ(RowN, k) = A(RowN, k) / R(k, k);\n\t\t\t}\n\t\t}\n\n\t\t// make the rest of the columns of A orthogonal to the current basis Q\n\t\tfor (int j = k + 1; j < Cols; j++) {\n\t\t\tR(k, j) = TLinAlg::DotProduct(Q, k, A, j);\n\t\t\tTLinAlg::AddVec(-R(k, j), Q, k, A, j);\n\t\t}\n\t}\n}\n\n// rotates vector (OldX,OldY) for angle Angle (in radians!)\nvoid TLinAlg::Rotate(const double& OldX, const double& OldY, const double& Angle,\n\t\tdouble& NewX, double& NewY) {\n\tNewX = OldX*cos(Angle) - OldY*sin(Angle);\n\tNewY = OldX*sin(Angle) + OldY*cos(Angle);\n}\n\nvoid TLinAlg::NonNegProj(TFltV& Vec) {\n\tfor (int i = 0; i < Vec.Len(); i++) {\n\t\tVec[i] = TMath::Mx(0.0, (double)Vec[i]);\n\t}\n}\n\nvoid TLinAlg::NonNegProj(TFltVV& Mat) {\n\tint Rows = Mat.GetRows();\n\tint Cols = Mat.GetCols();\n\tfor (int RowN = 0; RowN < Rows; RowN++) {\n\t\tfor (int ColN = 0; ColN < Cols; ColN++) {\n\t\t\tMat(RowN, ColN) = TMath::Mx(0.0, (double)Mat(RowN, ColN));\n\t\t}\n\t}\n}\n\n///////////////////////////////////////////////////////////////////////\n// Numerical Linear Algebra\ndouble TNumericalStuff::sqr(double a) {\n  return a == 0.0 ? 0.0 : a*a;\n}\n\ndouble TNumericalStuff::sign(double a, double b) {\n  return b >= 0.0 ? fabs(a) : -fabs(a);\n}\n\nvoid TNumericalStuff::nrerror(const TStr& error_text) {\n    //printf(\"NR_ERROR: %s\", error_text.CStr());\n    throw TNSException::New(error_text);\n}\n\ndouble TNumericalStuff::pythag(double a, double b) {\n    double absa = fabs(a), absb = fabs(b);\n    if (absa > absb)\n        return absa*sqrt(1.0+sqr(absb/absa));\n    else\n        return (absb == 0.0 ? 0.0 : absb*sqrt(1.0+sqr(absa/absb)));\n}\n\nvoid TNumericalStuff::SymetricToTridiag(TFltVV& a, int n, TFltV& d, TFltV& e) {\n    int l,k,j,i;\n    double scale,hh,h,g,f;\n    for (i=n;i>=2;i--) {\n        l=i-1;\n        h=scale=0.0;\n        if (l > 1) {\n            for (k=1;k<=l;k++)\n                scale += fabs(a(i-1,k-1).Val);\n            if (scale == 0.0) //Skip transformation.\n                e[i]=a(i-1,l-1);\n            else {\n                for (k=1;k<=l;k++) {\n                    a(i-1,k-1) /= scale; //Use scaled a's for transformation.\n                    h += a(i-1,k-1)*a(i-1,k-1);\n                }\n                f=a(i-1,l-1);\n                g=(f >= 0.0 ? -sqrt(h) : sqrt(h));\n                EAssertR(_isnan(g) == 0, TFlt::GetStr(h));\n                e[i]=scale*g;\n                h -= f*g; //Now h is equation (11.2.4).\n                a(i-1,l-1)=f-g; //Store u in the ith row of a.\n                f=0.0;\n                for (j=1;j<=l;j++) {\n                    // Next statement can be omitted if eigenvectors not wanted\n                    a(j-1,i-1)=a(i-1,j-1)/h; //Store u=H in ith column of a.\n                    g=0.0; //Form an element of A \u0001 u in g.\n                    for (k=1;k<=j;k++)\n                        g += a(j-1,k-1)*a(i-1,k-1);\n                    for (k=j+1;k<=l;k++)\n                        g += a(k-1,j-1)*a(i-1,k-1);\n                    e[j]=g/h; //Form element of p in temporarily unused element of e.\n                    f += e[j]*a(i-1,j-1);\n                }\n                hh=f/(h+h); //Form K, equation (11.2.11).\n                for (j=1;j<=l;j++) { //Form q and store in e overwriting p.\n                    f=a(i-1,j-1);\n                    e[j]=g=e[j]-hh*f;\n                    for (k=1;k<=j;k++) { //Reduce a, equation (11.2.13).\n                        a(j-1,k-1) -= (f*e[k]+g*a(i-1,k-1));\n                        EAssert(!a(j-1,k-1).IsNan());\n                    }\n                }\n            }\n        } else\n            e[i]=a(i-1,l-1);\n        d[i]=h;\n    }\n    // Next statement can be omitted if eigenvectors not wanted\n    d[1]=0.0;\n    e[1]=0.0;\n    // Contents of this loop can be omitted if eigenvectors not\n    // wanted except for statement d[i]=a[i][i];\n    for (i=1;i<=n;i++) { //Begin accumulation of transformationmatrices.\n        l=i-1;\n        if (d[i]) { //This block skipped when i=1.\n            for (j=1;j<=l;j++) {\n                g=0.0;\n                for (k=1;k<=l;k++) //Use u and u=H stored in a to form P\u0001Q.\n                    g += a(i-1,k-1)*a(k-1,j-1);\n                for (k=1;k<=l;k++) {\n                    a(k-1,j-1) -= g*a(k-1,i-1);\n                    EAssert(!a(k-1,j-1).IsNan());\n                }\n            }\n        }\n        d[i]=a(i-1,i-1); //This statement remains.\n        a(i-1,i-1)=1.0; //Reset row and column of a to identity  matrix for next iteration.\n        for (j=1;j<=l;j++) a(j-1,i-1)=a(i-1,j-1)=0.0;\n    }\n}\n\nvoid TNumericalStuff::EigSymmetricTridiag(TFltV& d, TFltV& e, int n, TFltVV& z) {\n    int m,l,iter,i,k; // N = n+1;\n    double s,r,p,g,f,dd,c,b;\n    // Convenient to renumber the elements of e\n    for (i=2;i<=n;i++) e[i-1]=e[i];\n    e[n]=0.0;\n    for (l=1;l<=n;l++) {\n        iter=0;\n        do {\n            // Look for a single small subdiagonal element to split the matrix.\n            for (m=l;m<=n-1;m++) {\n        dd=TFlt::Abs(d[m])+TFlt::Abs(d[m+1]);\n                if ((double)(TFlt::Abs(e[m])+dd) == dd) break;\n            }\n            if (m != l) {\n                if (iter++ == 60) nrerror(\"Too many iterations in EigSymmetricTridiag\");\n                //Form shift.\n                g=(d[l+1]-d[l])/(2.0*e[l]);\n                r=pythag(g,1.0);\n                //This is dm - ks.\n                g=d[m]-d[l]+e[l]/(g+sign(r,g));\n                s=c=1.0;\n                p=0.0;\n                // A plane rotation as in the original QL, followed by\n                // Givens rotations to restore tridiagonal form\n                for (i=m-1;i>=l;i--) {\n                    f=s*e[i];\n                    b=c*e[i];\n                    e[i+1]=(r=pythag(f,g));\n                    // Recover from underflow.\n                    if (r == 0.0) {\n                        d[i+1] -= p;\n                        e[m]=0.0;\n                        break;\n                    }\n                    s=f/r;\n                    c=g/r;\n                    g=d[i+1]-p;\n                    r=(d[i]-g)*s+2.0*c*b;\n                    d[i+1]=g+(p=s*r);\n                    g=c*r-b;\n                    // Next loop can be omitted if eigenvectors not wanted\n                    for (k=0;k<n;k++) {\n                        f=z(k,i);\n                        z(k,i)=s*z(k,i-1)+c*f;\n                        z(k,i-1)=c*z(k,i-1)-s*f;\n                    }\n                }\n                if (r == 0.0 && i >= l) continue;\n                d[l] -= p;\n                e[l]=g;\n                e[m]=0.0;\n            }\n        } while (m != l);\n    }\n}\n\nvoid TNumericalStuff::CholeskyDecomposition(TFltVV& A, TFltV& p) {\n  EAssert(A.GetRows() == A.GetCols());\n  int n = A.GetRows(); p.Reserve(n,n);\n\n  int i,j,k;\n  double sum;\n  for (i=1;i<=n;i++) {\n    for (j=i;j<=n;j++) {\n      for (sum=A(i-1,j-1),k=i-1;k>=1;k--) sum -= A(i-1,k-1)*A(j-1,k-1);\n      if (i == j) {\n        if (sum <= 0.0)\n          nrerror(\"choldc failed\");\n        p[i-1]=sqrt(sum);\n      } else A(j-1,i-1)=sum/p[i-1];\n    }\n  }\n}\n\nvoid TNumericalStuff::CholeskySolve(const TFltVV& A, const TFltV& p, const TFltV& b, TFltV& x) {\n  EAssert(A.GetRows() == A.GetCols());\n  int n = A.GetRows(); x.Reserve(n,n);\n\n  int i,k;\n  double sum;\n\n  // Solve L * y = b, storing y in x\n  for (i=1;i<=n;i++) {\n    for (sum=b[i-1],k=i-1;k>=1;k--)\n      sum -= A(i-1,k-1)*x[k-1];\n    x[i-1]=sum/p[i-1];\n  }\n\n  // Solve L^T * x = y\n  for (i=n;i>=1;i--) {\n    for (sum=x[i-1],k=i+1;k<=n;k++)\n      sum -= A(k-1,i-1)*x[k-1];\n    x[i-1]=sum/p[i-1];\n  }\n}\n\nvoid TNumericalStuff::SolveSymetricSystem(TFltVV& A, const TFltV& b, TFltV& x) {\n  EAssert(A.GetRows() == A.GetCols());\n  TFltV p; CholeskyDecomposition(A, p);\n  CholeskySolve(A, p, b, x);\n}\n\nvoid TNumericalStuff::InverseSubstitute(TFltVV& A, const TFltV& p) {\n  EAssert(A.GetRows() == A.GetCols());\n  int n = A.GetRows(); TFltV x(n);\n\n    int i, j, k; double sum;\n    for (i = 0; i < n; i++) {\n      // solve L * y = e_i, store in x\n        // elements from 0 to i-1 are 0.0\n        for (j = 0; j < i; j++) x[j] = 0.0;\n        // solve l_ii * y_i = 1 => y_i = 1/l_ii\n        x[i] = 1/p[i];\n        // solve y_j for j > i\n        for (j = i+1; j < n; j++) {\n            for (sum = 0.0, k = i; k < j; k++)\n                sum -= A(j,k) * x[k];\n            x[j] = sum / p[j];\n        }\n\n      // solve L'* x = y, store in upper triangule of A\n        for (j = n-1; j >= i; j--) {\n            for (sum = x[j], k = j+1; k < n; k++)\n                sum -= A(k,j)*x[k];\n            x[j] = sum/p[j];\n        }\n        for (int j = i; j < n; j++) A(i,j) = x[j];\n    }\n\n}\n\nvoid TNumericalStuff::InverseSymetric(TFltVV& A) {\n    EAssert(A.GetRows() == A.GetCols());\n    TFltV p;\n    // first we calculate cholesky decomposition of A\n    CholeskyDecomposition(A, p);\n    // than we solve system A x_i = e_i for i = 1..n\n    InverseSubstitute(A, p);\n}\n\nvoid TNumericalStuff::InverseTriagonal(TFltVV& A) {\n  EAssert(A.GetRows() == A.GetCols());\n  int n = A.GetRows(); TFltV x(n), p(n);\n\n    int i, j, k; double sum;\n    // copy upper triangle to lower one as we'll overwrite upper one\n    for (i = 0; i < n; i++) {\n        p[i] = A(i,i);\n        for (j = i+1; j < n; j++)\n            A(j,i) = A(i,j);\n    }\n    // solve\n    for (i = 0; i < n; i++) {\n        // solve R * x = e_i, store in x\n        // elements from 0 to i-1 are 0.0\n        for (j = n-1; j > i; j--) x[j] = 0.0;\n        // solve l_ii * y_i = 1 => y_i = 1/l_ii\n        x[i] = 1/p[i];\n        // solve y_j for j > i\n        for (j = i-1; j >= 0; j--) {\n            for (sum = 0.0, k = i; k > j; k--)\n                sum -= A(k,j) * x[k];\n            x[j] = sum / p[j];\n        }\n        for (int j = 0; j <= i; j++) A(j,i) = x[j];\n    }\n}\n\nvoid TNumericalStuff::LUDecomposition(TFltVV& A, TIntV& indx, double& d) {\n  EAssert(A.GetRows() == A.GetCols());\n  int n = A.GetRows(); indx.Reserve(n,n);\n\n    int i=0,imax=0,j=0,k=0;\n    double big,dum,sum,temp;\n    TFltV vv(n); // vv stores the implicit scaling of each row.\n    d=1.0;       // No row interchanges yet.\n\n    // Loop over rows to get the implicit scaling information.\n    for (i=1;i<=n;i++) {\n        big=0.0;\n        for (j=1;j<=n;j++)\n            if ((temp=TFlt::Abs(A(i-1,j-1))) > big) big=temp;\n        if (big == 0.0) nrerror(\"Singular matrix in routine LUDecomposition\");\n        vv[i-1]=1.0/big;\n    }\n\n    for (j=1;j<=n;j++) {\n        for (i=1;i<j;i++) {\n            sum=A(i-1,j-1);\n            for (k=1;k<i;k++) sum -= A(i-1,k-1)*A(k-1,j-1);\n            A(i-1,j-1)=sum;\n        }\n        big=0.0; //Initialize for the search for largest pivot element.\n        for (i=j;i<=n;i++) {\n            sum=A(i-1,j-1);\n            for (k=1;k<j;k++)\n                sum -= A(i-1,k-1)*A(k-1,j-1);\n            A(i-1,j-1)=sum;\n\n            //Is the figure of merit for the pivot better than the best so far?\n            if ((dum=vv[i-1] * TFlt::Abs(sum)) >= big) {\n                big=dum;\n                imax=i;\n            }\n        }\n\n        //Do we need to interchange rows?\n        if (j != imax) {\n            //Yes, do so...\n            for (k=1;k<=n;k++) {\n                dum=A(imax-1,k-1);\n            A(imax-1,k-1)=A(j-1,k-1); // Tadej: imax-1,k looks wrong\n            A(j-1,k-1)=dum;\n            }\n            //...and change the parity of d.\n            d = -d;\n            vv[imax-1]=vv[j-1]; //Also interchange the scale factor.\n        }\n        indx[j-1]=imax;\n\n        //If the pivot element is zero the matrix is singular (at least to the precision of the\n        //algorithm). For some applications on singular matrices, it is desirable to substitute\n        //TINY for zero.\n        if (A(j-1,j-1) == 0.0) A(j-1,j-1)=1e-20;\n\n         //Now, finally, divide by the pivot element.\n        if (j != n) {\n            dum=1.0/(A(j-1,j-1));\n            for (i=j+1;i<=n;i++) A(i-1,j-1) *= dum;\n        }\n    } //Go back for the next column in the reduction.\n}\n\nvoid TNumericalStuff::LUSolve(const TFltVV& A, const TIntV& indx, TFltV& b) {\n  EAssert(A.GetRows() == A.GetCols());\n  int n = A.GetRows();\n    int i,ii=0,ip,j;\n    double sum;\n    for (i=1;i<=n;i++) {\n        ip=indx[i-1];\n        sum=b[ip-1];\n        b[ip-1]=b[i-1];\n        if (ii)\n            for (j=ii;j<=i-1;j++) sum -= A(i-1,j-1)*b[j-1];\n        else if (sum) ii=i;b[i-1]=sum;\n    }\n    for (i=n;i>=1;i--) {\n        sum=b[i-1];\n        for (j=i+1;j<=n;j++) sum -= A(i-1,j-1)*b[j-1];\n        b[i-1]=sum/A(i-1,i-1);\n    }\n}\n\nvoid TNumericalStuff::SolveLinearSystem(TFltVV& A, const TFltV& b, TFltV& x) {\n    TIntV indx; double d;\n    LUDecomposition(A, indx, d);\n    x = b;\n    LUSolve(A, indx, x);\n}\n\nvoid TNumericalStuff::LeastSquares(const TFltVV& A, const TFltV& b, const double& Gamma, TFltV& x) {\n\tif (A.GetRows() < A.GetCols()) {\n\t\tTNumericalStuff::PrimalLeastSquares(A, b, Gamma, x);\n\t} else {\n\t\tTNumericalStuff::DualLeastSquares(A, b, Gamma, x);\n\t}\n}\n\nvoid TNumericalStuff::PrimalLeastSquares(const TFltVV& A, const TFltV& b, const double& Gamma, TFltV& x) {\n\tEAssertR(A.GetCols() == b.Len(), \"TNumericalStuff::LeastSquares: number of columns (examples) does not match the number of targets (length of b)\");\n\tif (x.Empty()) { \n\t\tx.Gen(A.GetRows());\n\t} else {\n\t\tEAssertR(x.Len() == A.GetRows(), \"TNumericalStuff::LeastSquares: solution dimension does not match the number of rows of A (features)\");\n\t}\n\t// x = (A * A' + Gamma^2 * I)^{-1} A * b\n\tint Feats = A.GetRows();\n\t// A'\n\tTFltVV At = TFltVV(A.GetCols(), A.GetRows()); \n\tTLinAlg::Transpose(A, At);\n\t// A * A'\n\tTFltVV B = TFltVV(Feats, Feats);\n\tTLinAlg::Multiply(A, At, B);\n\t// I\n\tTFltVV I = TFltVV(Feats, Feats);\n\tTFltV Ones = TFltV(Feats); Ones.PutAll(1.0);\n\tTLinAlgTransform::Diag(Ones, I);\n\t// B = A * A' + Gamma^2 * I\n\tTLinAlg::LinComb(1.0, B, Gamma*Gamma, I, B);\n\t// Ab = A * b\n\tTFltV Ab = TFltV(Feats);\n\tTLinAlg::Multiply(A, b, Ab);\n\tTNumericalStuff::SolveLinearSystem(B, Ab, x);\n}\n\nvoid TNumericalStuff::DualLeastSquares(const TFltVV& A, const TFltV& b, const double& Gamma, TFltV& x) {\n\tEAssertR(A.GetCols() == b.Len(), \"TNumericalStuff::LeastSquares: number of columns (examples) does not match the number of targets (length of b)\");\n\tif (x.Empty()) { \n\t\tx.Gen(A.GetRows());\n\t} else {\n\t\tEAssertR(x.Len() == A.GetRows(), \"TNumericalStuff::DualLeastSquares: solution dimension does not match the number of rows of A (features)\");\n\t}\n\n\t// x = A (A' * A + Gamma^2 * I)^{-1} * b\n\tint N = A.GetCols();\n\t// B = A' * A\n\tTFltVV B = TFltVV(N, N);\n\tTLinAlg::MultiplyT(A, A, B);\n\t// I\n\tTFltVV I = TFltVV(N, N);\n\tTFltV Ones = TFltV(N); Ones.PutAll(1.0);\n\tTLinAlgTransform::Diag(Ones, I);\n\t// B = A' * A + Gamma^2 * I\n\tTLinAlg::LinComb(1.0, B, Gamma*Gamma, I, B);\n\t// B^{-1}b\n\tTFltV InvBb = TFltV(N);\n\tTNumericalStuff::SolveLinearSystem(B, b, InvBb);\n\t// x = A * InvB\n\tTLinAlg::Multiply(A, InvBb, x);\t\n}\n\nvoid TNumericalStuff::GetKernelVec(const TFltVV& A, TFltV& x) {\n    EAssertR(A.GetRows() == A.GetCols(), \"TNumericalStuff::GetKernelVec: input is not a square matrix!\");\n\n    const int Dim = A.GetRows();\n\n#ifdef LAPACKE\n    TFltVV L, U;\n    TVec<TNum<index_t>, index_t> PermV;\n    MKLfunctions::LUFactorization(A, L, U, PermV);\n#else\n    TFltVV U = A;\n    TIntV PermV;\n    double d;\n    LUDecomposition(U, PermV, d);\n#endif\n\n    EAssertR(TFlt::Abs(U(Dim-1, Dim-1)) < 1e-6, \"TNumericalStuff::GetKernelVec: Input is not a singular matrix!\");\n\n    x.Gen(Dim);\n\n    // set the last element to an arbitrary value\n    x.Last() = 1;\n    // inverse iteration\n    for (int RowN = Dim-2; RowN >= 0; RowN--) {\n        double Sum = 0;\n\n        for (int ColN = RowN+1; ColN < Dim; ColN++) {\n            Sum += U(RowN, ColN)*x[ColN];\n        }\n\n        AssertR(double(U(RowN, RowN)) != 0, \"TNumericalStuff::GetKernelVec: Dimension of kernel is more than 1!\");\n\n        x[RowN] = -Sum / U(RowN, RowN);\n    }\n}\n\nvoid TNumericalStuff::GetEigenVec(const TFltVV& A, const double& EigenVal, TFltV& EigenV) {\n    const int Dim = A.GetRows();\n\n    // first compute (A - Lambda*I)\n    TFltVV A1 = A;\n\n    for (int i = 0; i < Dim; i++) {\n        A1(i,i) -= EigenVal;\n    }\n\n    // the result is in the kernel of (A - Lambda*I)\n    GetKernelVec(A1, EigenV);\n}\n\n///////////////////////////////////////////////////////////////////////\n// Sparse-SVD\nvoid TSparseSVD::MultiplyATA(const TMatrix& Matrix,\n        const TFltVV& Vec, int ColId, TFltV& Result) {\n    TFltV tmp(Matrix.GetRows());\n    // tmp = A * Vec(:,ColId)\n    Matrix.Multiply(Vec, ColId, tmp);\n    // Vec = A' * tmp\n    Matrix.MultiplyT(tmp, Result);\n}\n\nvoid TSparseSVD::MultiplyATA(const TMatrix& Matrix,\n        const TFltV& Vec, TFltV& Result) {\n    TFltV tmp(Matrix.GetRows());\n    // tmp = A * Vec\n    Matrix.Multiply(Vec, tmp);\n    // Vec = A' * tmp\n    Matrix.MultiplyT(tmp, Result);\n}\n\nvoid TSparseSVD::OrtoIterSVD(const TMatrix& Matrix,\n        int NumSV, int IterN, TFltV& SgnValV) {\n\n    int i, j, k;\n    int N = Matrix.GetCols(), M = NumSV;\n    TFltVV Q(N, M);\n\n    // Q = rand(N,M)\n    TRnd rnd;\n    for (i = 0; i < N; i++) {\n        for (j = 0; j < M; j++)\n            Q(i,j) = rnd.GetUniDev();\n    }\n\n    TFltV tmp(N);\n    for (int IterC = 0; IterC < IterN; IterC++) {\n        printf(\"%d..\", IterC);\n        // Gram-Schmidt\n        TLinAlg::GS(Q);\n        // Q = A'*A*Q\n        for (int ColId = 0; ColId < M; ColId++) {\n            MultiplyATA(Matrix, Q, ColId, tmp);\n            for (k = 0; k < N; k++) Q(k,ColId) = tmp[k];\n        }\n    }\n\n    SgnValV.Reserve(NumSV,0);\n    for (i = 0; i < NumSV; i++)\n        SgnValV.Add(sqrt(TLinAlg::Norm(Q,i)));\n    TLinAlg::GS(Q);\n}\n\nvoid TSparseSVD::OrtoIterSVD(const TMatrix& Matrix,\n        const int k, TFltV& S, TFltVV& U, TFltVV& V, const int Iters_, const double Tol) {\n\tconst int Iters = Iters_ != -1 ? Iters_ : 100;\n\tint Rows = Matrix.GetRows();\n\tint Cols = Matrix.GetCols();\n\tEAssert(k <= Rows && k <= Cols);\n\tTFltVV Q, R;\n\t\n\tif (S.Empty()) {S.Gen(k);}\n\tif (U.Empty()) {U.Gen(Rows, k); TLinAlgTransform::FillRnd(U);}\n\tif (V.Empty()) {V.Gen(Cols, k);}\n\n\n\tTFltV SOld = S;\t\n    for (int IterN = 0; IterN < Iters; IterN++) {\n\t\tMatrix.MultiplyT(U, V);\n\t\tfor (int i = 0; i < k; i++) {\n\t\t\tS[i] = TLinAlg::Norm(V,i);\n\t\t}\t\t\n\t\tMatrix.Multiply(V, U);\n\t\t//U = GS(AA'U)\n\t\t// orthogonalization\n\t\tTLinAlg::QR(U, U, R, Tol);\n\t\tif (!TLinAlgCheck::IsOrthonormal(U, Tol)) {\n\t\t\t// reorthogonalization\n\t\t\tTLinAlg::QR(U, U, R, Tol);\n\t\t}\n\t\tif (!TLinAlgCheck::IsOrthonormal(U, Tol)) {\n\t\t\tprintf(\"Orthofail!\\n\");\n\t\t}\n\t\tif (IterN > 0 && sqrt(TLinAlg::FrobDist2(S, SOld)/TLinAlg::Norm2(S)) < Tol) {break;}\n\t\tSOld = S;\n    }\n\n\tMatrix.MultiplyT(U, V);\n\tfor (int i = 0; i < k; i++) {\n\t\tS[i] = TLinAlg::Norm(V, i);\n\t}\n\tTLinAlg::QR(V, V, R, Tol);\n}\n\nvoid TSparseSVD::SimpleLanczos(const TMatrix& Matrix,\n        const int& NumEig, TFltV& EigValV,\n        const bool& DoLocalReortoP, const bool& SvdMatrixProductP) {\n\n    if (SvdMatrixProductP) {\n        // if this fails, use transposed matrix\n        EAssert(Matrix.GetRows() >= Matrix.GetCols());\n    } else {\n        EAssert(Matrix.GetRows() == Matrix.GetCols());\n    }\n\n    const int N = Matrix.GetCols(); // size of matrix\n    TFltV r(N), v0(N), v1(N); // current vector and 2 previous ones\n    TFltV alpha(NumEig, 0), beta(NumEig, 0); // diagonal and subdiagonal of T\n\n    printf(\"Calculating %d eigen-values of %d x %d matrix\\n\", NumEig, N, N);\n\n    // set starting vector\n    //TRnd Rnd(0);\n    for (int i = 0; i < N; i++) {\n        r[i] = 1/sqrt((double)N); // Rnd.GetNrmDev();\n        v0[i] = v1[i] = 0.0;\n    }\n    beta.Add(TLinAlg::Norm(r));\n\n    for (int j = 0; j < NumEig; j++) {\n        printf(\"%d\\r\", j+1);\n        // v_j -> v_(j-1)\n        v0 = v1;\n        // v_j = (1/beta_(j-1)) * r\n        TLinAlg::MultiplyScalar(1/beta[j], r, v1);\n        // r = A*v_j\n        if (SvdMatrixProductP) {\n            // A = Matrix'*Matrix\n            MultiplyATA(Matrix, v1, r);\n        } else {\n            // A = Matrix\n            Matrix.Multiply(v1, r);\n        }\n        // r = r - beta_(j-1) * v_(j-1)\n        TLinAlg::AddVec(-beta[j], v0, r, r);\n        // alpha_j = vj'*r\n        alpha.Add(TLinAlg::DotProduct(v1, r));\n        // r = r - v_j * alpha_j\n        TLinAlg::AddVec(-alpha[j], v1, r, r);\n        // reortogonalization if neessary\n        if (DoLocalReortoP) { } //TODO\n        // beta_j = ||r||_2\n        beta.Add(TLinAlg::Norm(r));\n        // compoute approximatie eigenvalues T_j\n        // test bounds for convergence\n    }\n    printf(\"\\n\");\n\n    // prepare matrix T\n    TFltV d(NumEig + 1), e(NumEig + 1);\n    d[1] = alpha[0]; d[0] = e[0] = e[1] = 0.0;\n    for (int i = 1; i < NumEig; i++) {\n        d[i+1] = alpha[i]; e[i+1] = beta[i]; }\n    // solve eigne problem for tridiagonal matrix with diag d and subdiag e\n    TFltVV S(NumEig+1,NumEig+1); // eigen-vectors\n    TLinAlgTransform::FillIdentity(S); // make it identity\n    TNumericalStuff::EigSymmetricTridiag(d, e, NumEig, S); // solve\n    //TLAMisc::PrintTFltV(d, \"AllEigV\");\n\n    // check convergence\n    TFltKdV AllEigValV(NumEig, 0);\n    for (int i = 1; i <= NumEig; i++) {\n        const double ResidualNorm = TFlt::Abs(S(i-1, NumEig-1) * beta.Last());\n        if (ResidualNorm < 1e-5)\n            AllEigValV.Add(TFltKd(TFlt::Abs(d[i]), d[i]));\n    }\n\n    // prepare results\n    AllEigValV.Sort(false); EigValV.Gen(NumEig, 0);\n    for (int i = 0; i < AllEigValV.Len(); i++) {\n        if (i == 0 || (TFlt::Abs(AllEigValV[i].Dat/AllEigValV[i-1].Dat) < 0.9999))\n            EigValV.Add(AllEigValV[i].Dat);\n    }\n}\n\nvoid TSparseSVD::Lanczos(const TMatrix& Matrix, int NumEig,\n        int Iters, const TSpSVDReOrtoType& ReOrtoType,\n        TFltV& EigValV, TFltVV& EigVecVV, const bool& SvdMatrixProductP) {\n\n    if (SvdMatrixProductP) {\n        // if this fails, use transposed matrix\n        EAssert(Matrix.GetRows() >= Matrix.GetCols());\n    } else {\n        EAssert(Matrix.GetRows() == Matrix.GetCols());\n    }\n \tEAssertR(NumEig <= Iters, TStr::Fmt(\"%d <= %d\", NumEig, Iters));\n\n    //if (ReOrtoType == ssotFull) printf(\"Full reortogonalization\\n\");\n    int i, N = Matrix.GetCols(), K = 0; // K - current dimension of T\n    double t = 0.0, eps = 1e-6; // t - 1-norm of T\n\n    //sequence of Ritz's vectors\n    TFltVV Q(N, Iters);\n    double tmp = 1/sqrt((double)N);\n    for (i = 0; i < N; i++) {\n        Q(i,0) = tmp;\n    }\n    //converget Ritz's vectors\n    TVec<TFltV> ConvgQV(Iters);\n    TIntV CountConvgV(Iters);\n    for (i = 0; i < Iters; i++) CountConvgV[i] = 0;\n    // const int ConvgTreshold = 50;\n\n    //diagonal and subdiagonal of T\n    TFltV d(Iters+1), e(Iters+1);\n    //eigenvectors of T\n    //TFltVV V;\n    TFltVV V(Iters, Iters);\n\n    // z - current Lanczos's vector\n    TFltV z(N), bb(Iters), aa(Iters), y(N);\n    //printf(\"svd(%d,%d)...\\n\", NumEig, Iters);\n\n    if (SvdMatrixProductP) {\n        // A = Matrix'*Matrix\n        MultiplyATA(Matrix, Q, 0, z);\n    } else {\n        // A = Matrix\n        Matrix.Multiply(Q, 0, z);\n    }\n\n    for (int j = 0; j < (Iters-1); j++) {\n        //printf(\"%d..\\r\",j+2);\n\n        //calculates (j+1)-th Lanczos's vector\n        // aa[j] = <Q(:,j), z>\n        aa[j] = TLinAlg::DotProduct(Q, j, z);\n        //printf(\" %g -- \", aa[j].Val); //HACK\n\n        TLinAlg::AddVec(-aa[j], Q, j, z);\n        if (j > 0) {\n            // z := -aa[j] * Q(:,j) + z\n            TLinAlg::AddVec(-bb[j-1], Q, j-1, z);\n\n            //reortogonalization\n            if (ReOrtoType == ssotSelective || ReOrtoType == ssotFull) {\n                for (i = 0; i <= j; i++) {\n                    // if i-tj vector converget, than we have to ortogonalize against it\n                    if ((ReOrtoType == ssotFull) ||\n                        (bb[j-1] * TFlt::Abs(V(K-1, i)) < eps * t)) {\n\n                        ConvgQV[i].Reserve(N,N); CountConvgV[i]++;\n                        TFltV& vec = ConvgQV[i];\n                        //vec = Q * V(:,i)\n                        for (int k = 0; k < N; k++) {\n                            vec[k] = 0.0;\n                            for (int l = 0; l < K; l++)\n                                vec[k] += Q(k,l) * V(l,i);\n                        }\n                        TLinAlg::AddVec(-TLinAlg::DotProduct(ConvgQV[i], z), ConvgQV[i], z ,z);\n                    }\n                }\n            }\n        }\n\n        //adds (j+1)-th Lanczos's vector to Q\n        bb[j] = TLinAlg::Norm(z);\n    if (!(bb[j] > 1e-10)) {\n      printf(\"Rank of matrix is only %d\\n\", j+2);\n      printf(\"Last singular value is %g\\n\", bb[j].Val);\n      break;\n    }\n        for (i = 0; i < N; i++) {\n            Q(i, j+1) = z[i] / bb[j];\n        }\n\n        //next Lanzcos vector\n        if (SvdMatrixProductP) {\n            // A = Matrix'*Matrix\n            MultiplyATA(Matrix, Q, j+1, z);\n        } else {\n            // A = Matrix\n            Matrix.Multiply(Q, j+1, z);\n        }\n\n        //calculate T (K x K matrix)\n        K = j + 2;\n        // calculate diagonal\n        for (i = 1; i < K; i++) d[i] = aa[i-1];\n        d[K] = TLinAlg::DotProduct(Q, K-1, z);\n        // calculate subdiagonal\n        e[1] = 0.0;\n        for (i = 2; i <= K; i++) e[i] = bb[i-2];\n\n        //calculate 1-norm of T\n        t = TFlt::GetMx(TFlt::Abs(d[1]) + TFlt::Abs(e[2]), TFlt::Abs(e[K]) + TFlt::Abs(d[K]));\n        for (i = 2; i < K; i++) {\n            t = TFlt::GetMx(t, TFlt::Abs(e[i]) + TFlt::Abs(d[i]) + TFlt::Abs(e[i+1]));\n        }\n\n        //set V to identity matrix\n        //V.Gen(K,K);\n        for (i = 0; i < K; i++) {\n            for (int k = 0; k < K; k++) {\n                V(i,k) = 0.0;\n            }\n            V(i,i) = 1.0;\n        }\n\n        //eigenvectors of T\n        TNumericalStuff::EigSymmetricTridiag(d, e, K, V);\n    }//for\n    //printf(\"\\n\");\n\n    // Finds NumEig largest eigen values\n    TFltIntKdV sv(K);\n    for (i = 0; i < K; i++) {\n        sv[i].Key = TFlt::Abs(d[i+1]);\n        sv[i].Dat = i;\n    }\n    sv.Sort(false);\n\n    TFltV uu(Matrix.GetRows());\n    const int FinalNumEig = TInt::GetMn(NumEig, K);\n    EigValV.Reserve(FinalNumEig,0);\n    EigVecVV.Gen(Matrix.GetCols(), FinalNumEig);\n    for (i = 0; i < FinalNumEig; i++) {\n        //printf(\"s[%d] = %20.15f\\r\", i, sv[i].Key.Val);\n        int ii = sv[i].Dat;\n        double sigma = d[ii+1].Val;\n        // calculate singular value\n        EigValV.Add(sigma);\n        // calculate i-th right singular vector ( V := Q * W )\n        TLinAlg::Multiply(Q, V, ii, EigVecVV, i);\n    }\n    //printf(\"done                           \\n\");\n}\n\nvoid TSparseSVD::Lanczos2(const TMatrix& Matrix, int MaxNumEig,\n    int MaxSecs, const TSpSVDReOrtoType& ReOrtoType,\n    TFltV& EigValV, TFltVV& EigVecVV, const bool& SvdMatrixProductP) {\n\n  if (SvdMatrixProductP) {\n    // if this fails, use transposed matrix\n    EAssert(Matrix.GetRows() >= Matrix.GetCols());\n  } else {\n    EAssert(Matrix.GetRows() == Matrix.GetCols());\n  }\n  //EAssertR(NumEig <= Iters, TStr::Fmt(\"%d <= %d\", NumEig, Iters));\n\n  //if (ReOrtoType == ssotFull) printf(\"Full reortogonalization\\n\");\n  int i, N = Matrix.GetCols(), K = 0; // K - current dimension of T\n  double t = 0.0, eps = 1e-6; // t - 1-norm of T\n\n  //sequence of Ritz's vectors\n  TFltVV Q(N, MaxNumEig);\n  double tmp = 1/sqrt((double)N);\n  for (i = 0; i < N; i++) {\n      Q(i,0) = tmp;\n  }\n  //converget Ritz's vectors\n  TVec<TFltV> ConvgQV(MaxNumEig);\n  TIntV CountConvgV(MaxNumEig);\n  for (i = 0; i < MaxNumEig; i++) {\n      CountConvgV[i] = 0;\n  }\n  // const int ConvgTreshold = 50;\n\n  //diagonal and subdiagonal of T\n  TFltV d(MaxNumEig+1), e(MaxNumEig+1);\n  //eigenvectors of T\n  //TFltVV V;\n  TFltVV V(MaxNumEig, MaxNumEig);\n\n  // z - current Lanczos's vector\n  TFltV z(N), bb(MaxNumEig), aa(MaxNumEig), y(N);\n  //printf(\"svd(%d,%d)...\\n\", NumEig, Iters);\n\n  if (SvdMatrixProductP) {\n      // A = Matrix'*Matrix\n      MultiplyATA(Matrix, Q, 0, z);\n  } else {\n      // A = Matrix\n      Matrix.Multiply(Q, 0, z);\n  }\n  TExeTm ExeTm;\n  for (int j = 0; j < (MaxNumEig-1); j++) {\n    printf(\"%d [%s]..\\r\",j+2, ExeTm.GetStr());\n    if (ExeTm.GetSecs() > MaxSecs) { break; }\n\n    //calculates (j+1)-th Lanczos's vector\n    // aa[j] = <Q(:,j), z>\n    aa[j] = TLinAlg::DotProduct(Q, j, z);\n    //printf(\" %g -- \", aa[j].Val); //HACK\n\n    TLinAlg::AddVec(-aa[j], Q, j, z);\n    if (j > 0) {\n        // z := -aa[j] * Q(:,j) + z\n        TLinAlg::AddVec(-bb[j-1], Q, j-1, z);\n\n        //reortogonalization\n        if (ReOrtoType == ssotSelective || ReOrtoType == ssotFull) {\n            for (i = 0; i <= j; i++) {\n                // if i-tj vector converget, than we have to ortogonalize against it\n                if ((ReOrtoType == ssotFull) ||\n                    (bb[j-1] * TFlt::Abs(V(K-1, i)) < eps * t)) {\n\n                    ConvgQV[i].Reserve(N,N); CountConvgV[i]++;\n                    TFltV& vec = ConvgQV[i];\n                    //vec = Q * V(:,i)\n                    for (int k = 0; k < N; k++) {\n                        vec[k] = 0.0;\n                        for (int l = 0; l < K; l++)\n                            vec[k] += Q(k,l) * V(l,i);\n                    }\n                    TLinAlg::AddVec(-TLinAlg::DotProduct(ConvgQV[i], z), ConvgQV[i], z ,z);\n                }\n            }\n        }\n    }\n\n    //adds (j+1)-th Lanczos's vector to Q\n    bb[j] = TLinAlg::Norm(z);\n    if (!(bb[j] > 1e-10)) {\n      printf(\"Rank of matrix is only %d\\n\", j+2);\n      printf(\"Last singular value is %g\\n\", bb[j].Val);\n      break;\n    }\n    for (i = 0; i < N; i++)\n        Q(i, j+1) = z[i] / bb[j];\n\n    //next Lanzcos vector\n    if (SvdMatrixProductP) {\n        // A = Matrix'*Matrix\n        MultiplyATA(Matrix, Q, j+1, z);\n    } else {\n        // A = Matrix\n        Matrix.Multiply(Q, j+1, z);\n    }\n\n    //calculate T (K x K matrix)\n    K = j + 2;\n    // calculate diagonal\n    for (i = 1; i < K; i++) d[i] = aa[i-1];\n    d[K] = TLinAlg::DotProduct(Q, K-1, z);\n    // calculate subdiagonal\n    e[1] = 0.0;\n    for (i = 2; i <= K; i++) e[i] = bb[i-2];\n\n    //calculate 1-norm of T\n    t = TFlt::GetMx(TFlt::Abs(d[1]) + TFlt::Abs(e[2]), TFlt::Abs(e[K]) + TFlt::Abs(d[K]));\n    for (i = 2; i < K; i++)\n        t = TFlt::GetMx(t, TFlt::Abs(e[i]) + TFlt::Abs(d[i]) + TFlt::Abs(e[i+1]));\n\n    //set V to identity matrix\n    //V.Gen(K,K);\n    for (i = 0; i < K; i++) {\n        for (int k = 0; k < K; k++)\n            V(i,k) = 0.0;\n        V(i,i) = 1.0;\n    }\n\n    //eigenvectors of T\n    TNumericalStuff::EigSymmetricTridiag(d, e, K, V);\n  }//for\n  printf(\"... calc %d.\", K);\n  // Finds NumEig largest eigen values\n  TFltIntKdV sv(K);\n  for (i = 0; i < K; i++) {\n    sv[i].Key = TFlt::Abs(d[i+1]);\n    sv[i].Dat = i;\n  }\n  sv.Sort(false);\n\n  TFltV uu(Matrix.GetRows());\n  const int FinalNumEig = K; //TInt::GetMn(NumEig, K);\n  EigValV.Reserve(FinalNumEig,0);\n  EigVecVV.Gen(Matrix.GetCols(), FinalNumEig);\n  for (i = 0; i < FinalNumEig; i++) {\n    //printf(\"s[%d] = %20.15f\\r\", i, sv[i].Key.Val);\n    int ii = sv[i].Dat;\n    double sigma = d[ii+1].Val;\n    // calculate singular value\n    EigValV.Add(sigma);\n    // calculate i-th right singular vector ( V := Q * W )\n    TLinAlg::Multiply(Q, V, ii, EigVecVV, i);\n  }\n  printf(\"  done\\n\");\n}\n\n\nvoid TSparseSVD::SimpleLanczosSVD(const TMatrix& Matrix,\n        const int& CalcSV, TFltV& SngValV, const bool& DoLocalReorto) {\n\n    SimpleLanczos(Matrix, CalcSV, SngValV, DoLocalReorto, true);\n    for (int SngValN = 0; SngValN < SngValV.Len(); SngValN++) {\n      //EAssert(SngValV[SngValN] >= 0.0);\n      if (SngValV[SngValN] < 0.0) {\n        printf(\"bad sng val: %d %g\\n\", SngValN, SngValV[SngValN]());\n        SngValV[SngValN] = 0;\n      }\n      SngValV[SngValN] = sqrt(SngValV[SngValN].Val);\n    }\n}\n\nvoid TSparseSVD::LanczosSVD(const TMatrix& Matrix, int NumSV,\n        int Iters, const TSpSVDReOrtoType& ReOrtoType,\n        TFltV& SgnValV, TFltVV& LeftSgnVecVV, TFltVV& RightSgnVecVV) {\n\n    // solve eigen problem for Matrix'*Matrix\n    Lanczos(Matrix, NumSV, Iters, ReOrtoType, SgnValV, RightSgnVecVV, true);\n    // calculate left singular vectors and sqrt singular values\n    const int FinalNumSV = SgnValV.Len();\n    LeftSgnVecVV.Gen(Matrix.GetRows(), FinalNumSV);\n    TFltV LeftSgnVecV(Matrix.GetRows());\n    for (int i = 0; i < FinalNumSV; i++) {\n        if (SgnValV[i].Val < 0.0) { SgnValV[i] = 0.0; }\n        const double SgnVal = sqrt(SgnValV[i]);\n        SgnValV[i] = SgnVal;\n        // calculate i-th left singular vector ( U := A * V * S^(-1) )\n        Matrix.Multiply(RightSgnVecVV, i, LeftSgnVecV);\n        for (int j = 0; j < LeftSgnVecV.Len(); j++) {\n            LeftSgnVecVV(j,i) = LeftSgnVecV[j] / SgnVal; }\n    }\n    //printf(\"done                           \\n\");\n}\n\nvoid TSparseSVD::Project(const TIntFltKdV& Vec, const TFltVV& U, TFltV& ProjVec) {\n    const int m = U.GetCols(); // number of columns\n\n    ProjVec.Gen(m, 0);\n    for (int j = 0; j < m; j++) {\n        double x = 0.0;\n        for (int i = 0; i < Vec.Len(); i++)\n            x += U(Vec[i].Key, j) * Vec[i].Dat;\n        ProjVec.Add(x);\n    }\n}\n\n//////////////////////////////////////////////////////////////////////\n// Sigmoid\ndouble TSigmoid::EvaluateFit(const TFltIntKdV& data, const double A, const double B)\n{\n  double J = 0.0;\n  for (int i = 0; i < data.Len(); i++)\n  {\n    double zi = data[i].Key; int yi = data[i].Dat;\n    double e = exp(-A * zi + B);\n    double denum = 1.0 + e;\n    double prob = (yi > 0) ? (1.0 / denum) : (e / denum);\n    J -= log(prob < 1e-20 ? 1e-20 : prob);\n  }\n  return J;\n}\n\nvoid TSigmoid::EvaluateFit(const TFltIntKdV& data, const double A, const double B, double& J, double& JA, double& JB)\n{\n  //               J(A, B) = \\sum_{i : y_i = 1} ln [1 + e^{-Az_i + B}] + \\sum_{i : y_i = -1} [ln [1 + e^{-Az_i + B}] - {-Az_i + B}]\n  //                       = \\sum_i ln [1 + e^{-Az_i + B}] - \\sum_{i : y_i = -1} {-Az_i + B}.\n  // partial J / partial A = \\sum_i (-z_i) e^{-Az_i + B} / [1 + e^{-Az_i + B}] + \\sum_{i : y_i = -1} Az_i.\n  // partial J / partial B = \\sum_i        e^{-Az_i + B} / [1 + e^{-Az_i + B}] + \\sum_{i : y_i = -1} (-1).\n  J = 0.0; double sum_all_PyNeg = 0.0, sum_all_ziPyNeg = 0.0, sum_yNeg_zi = 0.0, sum_yNeg_1 = 0.0;\n  for (int i = 0; i < data.Len(); i++)\n  {\n    double zi = data[i].Key; int yi = data[i].Dat;\n    double e = exp(-A * zi + B);\n    double denum = 1.0 + e;\n    double prob = (yi > 0) ? (1.0 / denum) : (e / denum);\n    J -= log(prob < 1e-20 ? 1e-20 : prob);\n    sum_all_PyNeg += e / denum;\n    sum_all_ziPyNeg += zi * e / denum;\n    if (yi < 0) { sum_yNeg_zi += zi; sum_yNeg_1 += 1; }\n  }\n  JA = -sum_all_ziPyNeg +     sum_yNeg_zi;\n  JB =  sum_all_PyNeg   -     sum_yNeg_1;\n}\n\nvoid TSigmoid::EvaluateFit(const TFltIntKdV& data, const double A, const double B, const double U,\n                           const double V, const double lambda, double& J, double& JJ, double& JJJ)\n{\n  // Let E_i = e^{-(A + lambda U) z_i + (B + lambda V)}.  Then we have\n  // J(lambda) = \\sum_i ln [1 + E_i] - \\sum_{i : y_i = -1} {-(A + lambda U)z_i + (B + lambda V)}.\n  // J'(lambda) = \\sum_i (V - U z_i) E_i / [1 + E_i] - \\sum_{i : y_i = -1} {V - U z_i).\n  //            = \\sum_i (V - U z_i) [1 - 1 / [1 + E_i]] - \\sum_{i : y_i = -1} {V - U z_i).\n  // J\"(lambda) = \\sum_i (V - U z_i)^2 E_i / [1 + E_i]^2.\n  J = 0.0; JJ = 0.0; JJJ = 0.0;\n  for (int i = 0; i < data.Len(); i++)\n  {\n    double zi = data[i].Key; int yi = data[i].Dat;\n    double e = exp(-A * zi + B);\n    double denum = 1.0 + e;\n    double prob = (yi > 0) ? (1.0 / denum) : (e / denum);\n    J -= log(prob < 1e-20 ? 1e-20 : prob);\n    double VU = V - U * zi;\n    JJ += VU * (e / denum); if (yi < 0) JJ -= VU;\n    JJJ += VU * VU * e / denum / denum;\n  }\n}\n\nTSigmoid::TSigmoid(const TFltIntKdV& data) {\n  // Let z_i be the projection of the i'th training example, and y_i \\in {-1, +1} be its class label.\n  // Our sigmoid is: P(Y = y | Z = z) = 1 / [1 + e^{-Az + B}]\n  // and we want to maximize \\prod_i P(Y = y_i | Z = z_i)\n  //                       = \\prod_{i : y_i = 1} 1 / [1 + e^{-Az_i + B}]  \\prod_{i : y_i = -1} e^{-Az_i + B} / [1 + e^{-Az_i + B}]\n  // or minimize its negative logarithm,\n  //               J(A, B) = \\sum_{i : y_i = 1} ln [1 + e^{-Az_i + B}] + \\sum_{i : y_i = -1} [ln [1 + e^{-Az_i + B}] - {-Az_i + B}]\n  //                       = \\sum_i ln [1 + e^{-Az_i + B}] - \\sum_{i : y_i = -1} {-Az_i + B}.\n  // partial J / partial A = \\sum_i (-z_i) e^{-Az_i + B} / [1 + e^{-Az_i + B}] + \\sum_{i : y_i = -1} Az_i.\n  // partial J / partial B = \\sum_i        e^{-Az_i + B} / [1 + e^{-Az_i + B}] + \\sum_{i : y_i = -1} (-1).\n  double minProj = data[0].Key, maxProj = data[0].Key;\n  {for (int i = 1; i < data.Len(); i++) {\n    double zi = data[i].Key; if (zi < minProj) minProj = zi; if (zi > maxProj) maxProj = zi; }}\n  // const bool dump = true;\n  A = 1.0; B = 0.5 * (minProj + maxProj);\n  double bestJ = 0.0, bestA = 0.0, bestB = 0.0, lambda = 1.0;\n  for (int nIter = 0; nIter < 50; nIter++)\n  {\n    double J, JA, JB; TSigmoid::EvaluateFit(data, A, B, J, JA, JB);\n    if (nIter == 0 || J < bestJ) { bestJ = J; bestA = A; bestB = B; }\n    // How far should we move?\n    // if (dump) printf(\"Iter %2d: A = %.5f, B = %.5f, J = %.5f, partial = (%.5f, %.5f)\\n\", nIter, A.Val, B.Val, J, JA, JB);\n    double norm = TMath::Sqr(JA) + TMath::Sqr(JB);\n    if (norm < 1e-10) break;\n    const int cl = -1; // should be -1\n\n    double Jc = TSigmoid::EvaluateFit(data, A + cl * lambda * JA / norm, B + cl * lambda * JB / norm);\n    // if (dump) printf(\"  At lambda = %.5f, Jc = %.5f\\n\", lambda, Jc);\n    if (Jc > J) {\n      while (lambda > 1e-5) {\n        lambda = 0.5 * lambda;\n        Jc = TSigmoid::EvaluateFit(data, A + cl * lambda * JA / norm, B + cl * lambda * JB / norm);\n        // if (dump) printf(\"  At lambda = %.5f, Jc = %.5f\\n\", lambda, Jc);\n      } }\n    else if (Jc < J) {\n      while (lambda < 1e5) {\n        double lambda2 = 2 * lambda;\n        double Jc2 = TSigmoid::EvaluateFit(data, A + cl * lambda2 * JA / norm, B + cl * lambda2 * JB / norm);\n        // if (dump) printf(\"  At lambda = %.5f, Jc = %.5f\\n\", lambda2, Jc2);\n        if (Jc2 > Jc) { break; }\n        if (TFlt::IsNan(Jc2)) { break; }\n        lambda = lambda2; Jc = Jc2; } }\n    if (Jc >= J) break;\n    A += cl * lambda * JA / norm; B += cl * lambda * JB / norm;\n    // if (dump) printf(\"   Lambda = %.5f, new A = %.5f, new B = %.5f, new J = %.5f\\n\", lambda, A.Val, B.Val, Jc);\n  }\n  A = bestA; B = bestB;\n}\n\n//////////////////////////////////////////////////////////////////////\n// Useful stuff (hopefuly)\n#ifdef SCALAPACK\ntemplate<class Size>\nvoid TLAMisc::Sort(TVec<TFlt, Size> & Vec, TVec<Size, Size>& index, const TBool& decrease) {\n\tif (index.Empty()){\n\t\tTLAMisc::FillRange(Vec.Len(), index);\n\t}\n\tchar* id = decrease ? \"D\" : \"I\";\n\tint n = Vec.Len();\n\tint info;\n\tdlasrt2(id, &n, &Vec[0].Val, &index[0].Val, &info);\n\t//dlasrt2(id, n, d, key, info)\n}\n#endif\n\n//int TLAMisc::SumVec(const TIntV& Vec) {\n//    const int Len = Vec.Len();\n//    int res = 0;\n//    for (int i = 0; i < Len; i++)\n//        res += Vec[i];\n//    return res;\n//}\n//\n//double TLAMisc::SumVec(const TFltV& Vec) {\n//    const int Len = Vec.Len();\n//    double res = 0.0;\n//    for (int i = 0; i < Len; i++)\n//        res += Vec[i];\n//    return res;\n//}\n\n///////////////////////////////////////////////////////////////////////\n// TVector\nTVector::TVector(const bool& _IsColVector):\n\t\tIsColVector(_IsColVector),\n\t\tVec() {}\n\nTVector::TVector(const int& Dim, const bool _IsColVector):\n\t\tIsColVector(_IsColVector),\n\t\tVec(Dim) {}\n\nTVector::TVector(const TFltV& Vect, const bool _IsColVector):\n\t\tIsColVector(_IsColVector),\n\t\tVec(Vect) {}\n\nTVector::TVector(const TIntV& Vect, const bool _IsColVector):\n\t\tIsColVector(_IsColVector),\n\t\tVec(Vect.Len()) {\n\n\tfor (int i = 0; i < Vec.Len(); i++) {\n\t\tVec[i] = Vect[i];\n\t}\n}\n\nTVector::TVector(const TFullMatrix& Mat):\n\t\tIsColVector(Mat.GetRows() > 1),\n\t\tVec(TMath::Mx(Mat.GetRows(), Mat.GetCols())) {\n\tEAssertR(Mat.GetRows() == 1 || Mat.GetCols() == 1, \"Cannot create a vector from matrix that is not a vector!\");\n\tif (Mat.GetRows() == 1) {\n\t\tfor (int ColIdx = 0; ColIdx < Mat.GetCols(); ColIdx++) {\n\t\t\tVec[ColIdx] = Mat(0, ColIdx);\n\t\t}\n\t} else {\n\t\tfor (int RowIdx = 0; RowIdx < Mat.GetRows(); RowIdx++) {\n\t\t\tVec[RowIdx] = Mat(RowIdx, 0);\n\t\t}\n\t}\n}\n\nTVector::TVector(const TVector& Vector) {\n\tIsColVector = Vector.IsColVector;\n\tVec = Vector.Vec;\n}\n\n#ifdef GLib_CPP11\n// move constructor\nTVector::TVector(const TVector&& Vector) {\n\tIsColVector = Vector.IsColVector;\n\tVec = std::move(Vector.Vec);\n}\n#endif \n\nTVector& TVector::operator=(TVector Vector) {\n\tstd::swap(IsColVector, Vector.IsColVector);\n\tstd::swap(Vec, Vector.Vec);\n\treturn *this;\n}\n\nTVector TVector::Init(const int& Dim, const bool _IsColVect = true) {\n\treturn TVector(Dim, _IsColVect);\n}\n\nTVector TVector::Ones(const int& Dim, const bool IsColVect) {\n\tTVector Res(Dim, IsColVect);\n\tfor (int i = 0; i < Dim; i++) {\n\t\tRes[i] = 1;\n\t}\n\treturn TVector(Res);\n}\n\nTVector TVector::Zeros(const int& Dim, const bool IsColVec) {\n\treturn TVector(Dim, IsColVec);\n}\n\nTVector TVector::Range(const int& Start, const int& End, const bool IsColVect) {\n\tEAssert(Start < End);\n\n\tconst int Len = End - Start;\n\n\tTVector Res(Len, IsColVect);\n\tfor (int i = 0; i < Len; i++) {\n\t\tRes[i] = i + Start;\n\t}\n\n\treturn Res;\n}\n\nTVector TVector::Range(const int& End, const bool IsColVect) {\n\treturn TVector::Range(0, End, IsColVect);\n}\n\nbool TVector::operator ==(const TVector& Vect) const {\n\treturn IsColVector == Vect.IsColVector && Vec == Vect.Vec;\n}\n\nTVector TVector::GetT() const {\n\tTVector Res(*this);\n\tRes.Transpose();\n\treturn Res;\n}\n\nTVector& TVector::Transpose() {\n\t IsColVector = !IsColVector;\n\t return *this;\n}\n\ndouble TVector::DotProduct(const TFltV& y) const {\n\tEAssert(Len() == y.Len());\n\treturn TLinAlg::DotProduct(Vec, y);\n}\n\ndouble TVector::DotProduct(const TVector& y) const {\n\tEAssert(Len() == y.Len() && IsRowVec() && y.IsColVec());\n\treturn DotProduct(y.Vec);\n}\n\nTFullMatrix TVector::operator *(const TVector& y) const {\n\tEAssertR(IsColVec() != y.IsColVec(), \" TVector::operator*(TVector): invalid dimensions!\");\n\n\tif (IsRowVec()) {\n\t\t// dot product\n\t\tconst double& Dot = DotProduct(y);\n\t\tTFullMatrix Res(1,1);\n\t\tRes.Set(Dot,0,0);\n\t\treturn Res;\n\t} else {\n\t\t// outer product\n\t\tTFullMatrix Res(Len(), y.Len());\n\t\tTLinAlg::OuterProduct(Vec, y.Vec, *Res.Mat);\n\t\treturn Res;\n\t}\n}\n\nTVector TVector::operator *(const TFullMatrix& Mat) const {\n\tEAssertR(IsRowVec() && Len() == Mat.GetRows(), \"TVector::operator*(TFullMatrix&): Invalid dimensions!\");\n\n\tTVector Res(Mat.GetCols(), false);\n\tMat.MultiplyT(Vec, Res.Vec);\n\n\treturn Res;\n}\n\nTVector TVector::operator *(const double& Lambda) const {\n\tTVector Res(Vec.Len(), IsColVec());\n\tTLinAlg::MultiplyScalar(Lambda, Vec, Res.Vec);\n\treturn Res;\n}\n\nTVector& TVector::operator *=(const double& Lambda) {\n\tTLinAlg::MultiplyScalar(Lambda, Vec, Vec);\n\treturn *this;\n}\n\nTVector TVector::operator /(const double& Lambda) const {\n\treturn operator *(1/Lambda);\n}\n\nTVector& TVector::operator /=(const double& Lambda) {\n\treturn operator *=(1/Lambda);\n}\n\nTVector TVector::MulT(const TFullMatrix& B) const {\n\tEAssertR(Len() == B.GetRows(), \"TVector::MulT: Dimension should equal the number of rows in B!\");\n\n\tTVector Res(B.GetCols(), false);\n\tTLinAlg::MultiplyT(*B.Mat, Vec, Res.Vec);\n\n\treturn Res;\n}\n\nTVector TVector::operator +(const TVector& y) const {\n\tEAssertR(Len() == y.Len() && IsColVec() == y.IsColVec(), \"TVector::operator +(TVector& y): Invalid dimensions!\");\n\n\tTVector Res(Len(), IsColVec());\n\tTLinAlg::LinComb(1.0, Vec, 1.0, y.Vec, Res.Vec);\n\treturn Res;\n}\n\nTVector& TVector::operator +=(const TVector& y) {\n\tEAssertR(Len() == y.Len() && IsColVec() == y.IsColVec(), \"TVector::operator +=(TVector&): Invalid dimensions!\");\n\tTLinAlg::LinComb(1.0, Vec, 1.0, y.Vec, Vec);\n\treturn *this;\n}\n\nTVector TVector::operator -(const TVector& y) const {\n\tEAssertR(Len() == y.Len() && IsColVec() == y.IsColVec(), \"TVector::operator -(TVector& y): Invalid dimensions!\");\n\n\tTVector Res(Len(), IsColVec());\n\tTLinAlg::LinComb(1.0, Vec, -1.0, y.Vec, Res.Vec);\n\treturn Res;\n}\n\ndouble TVector::Norm() const {\n\treturn TLinAlg::Norm(Vec);\n}\n\ndouble TVector::Norm2() const {\n\treturn TLinAlg::Norm2(Vec);\n}\n\ndouble TVector::Sum() const {\n\tconst int Dim = Len();\n\n\tdouble Sum = 0;\n\tfor (int i = 0; i < Dim; i++) {\n\t\tSum += Vec[i];\n\t}\n\n\treturn Sum;\n}\n\ndouble TVector::EuclDist(const TVector& y) const {\n\treturn TLinAlg::EuclDist(Vec, y.Vec);\n}\n\nTIntV TVector::GetIntVec() const {\n\t const int Dim = Len();\n\t TIntV Res(Dim);\n\n\t for (int i = 0; i < Dim; i++) {\n\t\t Res[i] = (int) Vec[i];\n\t }\n\n\t return Res;\n}\n\ndouble TVector::GetMaxVal() const {\n\treturn GetMax().Val2;\n}\n\nint TVector::GetMaxIdx() const {\n\treturn GetMax().Val1;\n}\n\nTIntFltPr TVector::GetMax() const {\n\tconst int Dim = Len();\n\n\tdouble MaxVal = TFlt::Mn;\n\tint MaxIdx = 0;\n\n\tfor (int i = 0; i < Dim; i++) {\n\t\tif (Vec[i] > MaxVal) {\n\t\t\tMaxVal = Vec[i];\n\t\t\tMaxIdx = i;\n\t\t}\n\t}\n\n\treturn TIntFltPr(MaxIdx, MaxVal);\n}\n\nint TVector::GetMinIdx() const {\n\tconst int Dim = Len();\n\n\tdouble MinVal = TFlt::Mx;\n\tint MinIdx = 0;\n\n\tfor (int i = 0; i < Dim; i++) {\n\t\tif (Vec[i] < MinVal) {\n\t\t\tMinVal = Vec[i];\n\t\t\tMinIdx = i;\n\t\t}\n\t}\n\n\treturn MinIdx;\n}\n\n///////////////////////////////////////////////////////////////////////\n// Full-Matrix\nTFullMatrix::TFullMatrix():\n\t\tTMatrix(),\n\t\tIsWrapper(false),\n\t\tMat(new TFltVV(0,0)) {}\n\nTFullMatrix::TFullMatrix(const int& Rows, const int& Cols):\n\t \tTMatrix(),\n\t \tIsWrapper(false),\n\t \tMat(new TFltVV(Rows, Cols)) {}\n\nTFullMatrix::TFullMatrix(TFltVV& _Mat, const bool _IsWrapper):\n\t\tTMatrix(),\n\t\tIsWrapper(_IsWrapper),\n\t\tMat(_IsWrapper ? &_Mat : new TFltVV(_Mat)) {}\n\nTFullMatrix::TFullMatrix(const TFltVV& _Mat):\n\t\tTMatrix(),\n\t\tIsWrapper(false),\n\t\tMat(new TFltVV(_Mat)) {}\n\nTFullMatrix::TFullMatrix(const TVector& Vec):\n\t\tTMatrix(),\n\t\tIsWrapper(false),\n\t\tMat(new TFltVV(Vec.IsColVec() ? Vec.Len() : 1, Vec.IsRowVec() ? Vec.Len() : 1)) {\n\n\tif (Vec.IsColVec()) {\n\t\tfor (int i = 0; i < Vec.Len(); i++) {\n\t\t\tMat->PutXY(i,0,Vec[i]);\n\t\t}\n\t} else {\n\t\tfor (int i = 0; i < Vec.Len(); i++) {\n\t\t\tMat->PutXY(0,i,Vec[i]);\n\t\t}\n\t}\n}\n\nTFullMatrix::TFullMatrix(const TFullMatrix& Other):\n\t\tTMatrix(Other),\n\t\tIsWrapper(Other.IsWrapper),\n\t\tMat(Other.IsWrapper ? Other.Mat : new TFltVV(*Other.Mat)) {}\n\n#ifdef GLib_CPP11\nTFullMatrix::TFullMatrix(TFullMatrix&& Other):\n\t\tTMatrix(Other),\n\t\tIsWrapper(std::move(Other.IsWrapper)),\n\t\tMat(Other.Mat) {\n\tOther.Mat = nullptr;\n}\n#endif\n\nTFullMatrix::TFullMatrix(TFltVV* _Mat):\n\t\tIsWrapper(false),\n\t\tMat(_Mat) {}\n\nTFullMatrix::~TFullMatrix() {\n\tClr();\n}\n\nTFullMatrix& TFullMatrix::operator =(const TFullMatrix& Other) {\n\tTMatrix::operator =(Other);\n\n\tClr();\n\tIsWrapper = Other.IsWrapper;\n\tMat = IsWrapper ? Other.Mat : new TFltVV(*Other.Mat);\n\n\treturn *this;\n}\n\nTFullMatrix& TFullMatrix::operator =(TFullMatrix&& Other) {\n\tTMatrix::operator =(Other);\n\n\tif (this != &Other) {\n\t\tstd::swap(IsWrapper, Other.IsWrapper);\n\t\tstd::swap(Mat, Other.Mat);\n\t\tOther.Clr();\n\t}\n\n\treturn *this;\n}\n\nTFullMatrix TFullMatrix::Identity(const int& Dim) {\n\tTFullMatrix Mat(Dim, Dim);\n\n    for (int i = 0; i < Dim; i++) {\n    \tMat(i,i) = 1;\n    }\n\n    return Mat;\n}\n\nTFullMatrix TFullMatrix::RowMatrix(const TVec<TFltV>& Mat) {\n\tEAssertR(Mat.Len() > 0, \"Input vector should have at least one row!\");\n\tEAssertR(Mat[0].Len() > 0, \"Input vector should have at least one column!\");\n\n\tconst int Rows = Mat.Len();\n\tconst int Cols = Mat[0].Len();\n\n\tTFullMatrix Res(Rows, Cols);\n\tfor (int RowIdx = 0; RowIdx < Rows; RowIdx++) {\n\t\tfor (int ColIdx = 0; ColIdx < Cols; ColIdx++) {\n\t\t\tRes.Mat->PutXY(RowIdx, ColIdx, Mat[RowIdx][ColIdx]);\n\t\t}\n\t}\n\n\treturn Res;\n}\n\nTFullMatrix TFullMatrix::ColMatrix(const TVec<TFltV>& Mat) {\n\tEAssertR(Mat.Len() > 0, \"Input vector should have at least one column!\");\n\tEAssertR(Mat[0].Len() > 0, \"Input vector should have at least one row!\");\n\n\tconst int Cols = Mat.Len();\n\tconst int Rows = Mat[0].Len();\n\n\tTFullMatrix Res(Rows, Cols);\n\tfor (int ColIdx = 0; ColIdx < Cols; ColIdx++) {\n\t\tfor (int RowIdx = 0; RowIdx < Rows; RowIdx++) {\n\t\t\tRes.Mat->PutXY(RowIdx, ColIdx, Mat[ColIdx][RowIdx]);\n\t\t}\n\t}\n\n\treturn Res;\n}\n\nTFullMatrix TFullMatrix::Diag(const TVector& Diag) {\n\tconst int Dim = Diag.Len();\n\n\tTFullMatrix Result(Dim,Dim);\n\tfor (int i = 0; i < Dim; i++) {\n\t\tResult(i,i) = Diag[i];\n\t}\n\n\treturn Result;\n}\n\nvoid TFullMatrix::Clr() {\n\tif (!IsWrapper && Mat != nullptr) {\n\t\tdelete Mat;\n\t\tMat = nullptr;\n\t}\n}\n\nvoid TFullMatrix::PMultiply(const TFltVV& B, int ColId, TFltV& Result) const {\n\tTLinAlg::Multiply(*Mat, B, ColId, Result);\n}\n\nvoid TFullMatrix::PMultiply(const TFltV& Vec, TFltV& Result) const {\n\tTLinAlg::Multiply(*Mat, Vec, Result);\n}\n\nvoid TFullMatrix::PMultiply(const TFltVV& B, TFltVV& Result) const {\n\tTLinAlg::Multiply(*Mat, B, Result);\n}\n\nvoid TFullMatrix::PMultiplyT(const TFltVV& B, int ColId, TFltV& Result) const {\n\tFailR(\"TFullMatrix::PMultiplyT: Not implemented!!!\");\n}\n\nvoid TFullMatrix::PMultiplyT(const TFltV& Vec, TFltV& Result) const {\n\tTLinAlg::MultiplyT(*Mat, Vec, Result);\n}\n\nvoid TFullMatrix::PMultiplyT(const TFltVV& B, TFltVV& Result) const {\n\tTLinAlg::MultiplyT(*Mat, B, Result);\n}\n\nvoid TFullMatrix::Transpose() {\n\tMat->Transpose();\n}\n\nTFullMatrix TFullMatrix::GetT() const {\n\tTFullMatrix Res(*this);      // copy\n\tGetT(Res.GetMat());\n\treturn Res;\n}\n\nvoid TFullMatrix::GetT(TFltVV& TransposedVV) const {\n\tTLinAlg::Transpose(GetMat(), TransposedVV);\n}\n\nTFullMatrix& TFullMatrix::AddCol(const TFltV& Col) {\n\tconst int Rows = GetRows();\n\tconst int LastColIdx = GetCols();\n\n\tEAssertR(Col.Len() == Rows, \"TFullMatrix::AddCol: dimension mismatch!\");\n\n\tMat->AddYDim();\n\tfor (int RowIdx = 0; RowIdx < Rows; RowIdx++) {\n\t\tMat->PutXY(RowIdx, LastColIdx, Col[RowIdx]);\n\t}\n\n\treturn *this;\n}\n\nTFullMatrix& TFullMatrix::AddCol(const TVector& Col) {\n\treturn AddCol(Col.Vec);\n}\n\nTFullMatrix& TFullMatrix::AddCols(const TFullMatrix& ColMat) {\n\tEAssertR(GetRows() == ColMat.GetRows(), \"Invalid dimensions when concatenating matrices!\");\n\n\tconst int Rows = GetRows();\n\tconst int Cols = GetCols();\n\tconst int NNewCols = ColMat.GetCols();\n\n\tMat->AddYDim(NNewCols);\n\tfor (int RowIdx = 0; RowIdx < Rows; RowIdx++) {\n\t\tfor (int ColIdx = 0; ColIdx < NNewCols; ColIdx++) {\n\t\t\tMat->PutXY(RowIdx, Cols + ColIdx, ColMat(RowIdx, ColIdx));\n\t\t}\n\t}\n\n\treturn *this;\n}\n\nTFullMatrix& TFullMatrix::operator -=(const TFullMatrix& B) {\n\tEAssert(GetCols() == B.GetCols() && GetRows() == B.GetRows());\n\n\tTLinAlg::LinComb(1.0, *Mat, -1.0, B.GetMat(), *Mat);\n\treturn *this;\n}\n\nTFullMatrix& TFullMatrix::operator +=(const TFullMatrix& B) {\n\tEAssert(GetCols() == B.GetCols() && GetRows() == B.GetRows());\n\tTLinAlg::LinComb(1.0, *Mat, 1.0, B.GetMat(), *Mat);\n\treturn *this;\n}\n\nTFullMatrix TFullMatrix::operator +(const TFullMatrix& B) const {\n\tEAssert(GetCols() == B.GetCols() && GetRows() == B.GetRows());\n\n\tTFullMatrix Result(GetRows(), GetCols());\n\tTLinAlg::LinComb(1.0, *Mat, 1.0, B.GetMat(), *Result.Mat);\n\n\treturn Result;\n}\n\nTFullMatrix TFullMatrix::operator -(const TFullMatrix& B) const {\n\tEAssert(GetCols() == B.GetCols() && GetRows() == B.GetRows());\n\n\tTFullMatrix Result(GetRows(), GetCols());\n\tTLinAlg::LinComb(1.0, *Mat, -1.0, B.GetMat(), *Result.Mat);\n\n\treturn Result;\n}\n\nTFullMatrix TFullMatrix::operator *(const TFullMatrix& B) const {\n\tEAssert(GetCols() == B.GetRows());\n\n\tTFullMatrix Result(GetRows(), B.GetCols());\n\tMultiply(*B.Mat, *Result.Mat);\n\n \treturn Result;\n}\n\nTFullMatrix TFullMatrix::operator *(const TSparseColMatrix& B) const {\n\tEAssert(GetCols() == B.GetRows());\n\n\tTFullMatrix Result(GetRows(), B.GetCols());\n\tTLinAlg::Multiply(*Mat, B.ColSpVV, *Result.Mat);\n\n\treturn Result;\n}\n\nTFullMatrix TFullMatrix::MulT(const TFullMatrix& B) const {\n\treturn MulT(B.GetMat());\n}\n\nTFullMatrix TFullMatrix::MulT(const TFltVV& B) const {\n\tEAssert(GetRows() == B.GetRows());\n\n\tTFullMatrix Result(GetCols(), B.GetCols());\n\tMultiplyT(B, *Result.Mat);\n\treturn Result;\n}\n\nTVector TFullMatrix::operator *(const TVector& x) const {\n\tEAssertR(x.IsColVec(), \"x must be a column vector!\");\n\treturn operator *(x.Vec);\n}\n\nTVector TFullMatrix::operator *(const TFltV& y) const {\n\tTVector Res(GetRows());\n\tMultiply(y, Res.Vec);\n\treturn Res;\n}\n\nTFullMatrix TFullMatrix::operator *(const double& Lambda) const {\n\tTFullMatrix Res(GetRows(), GetCols());\n\tTLinAlg::MultiplyScalar(Lambda, *Mat, *Res.Mat);\n\n\treturn Res;\n}\n\nTFullMatrix TFullMatrix::operator /(const double& Lambda) const {\n\treturn operator *(1.0/Lambda);\n}\n\nTVector TFullMatrix::GetRow(const int& RowIdx) const {\n\tEAssertR(RowIdx < GetRows(), \"Row index should be smaller then the number of rows!\");\n\n\tconst int Cols = GetCols();\n\n\tTVector Res(Cols, false);\n\tfor (int ColIdx = 0; ColIdx < Cols; ColIdx++) {\n\t\tRes[ColIdx] = Mat->At(RowIdx, ColIdx);\n\t}\n\n\treturn Res;\n}\n\nTFullMatrix TFullMatrix::Pow(const int& k) const {\n\tEAssertR(k >= 0, \"TFullMatrix::operator ^: Negative powers not implemented!\");\n\tEAssertR(GetRows() == GetCols(), \"TFullMatrix::operator ^: Can only compute powers of square matrices!\");\n\n\tif (k == 0) { return TFullMatrix::Identity(GetRows()); }\n\telse if (k < 0) { return GetInverse()^(-k); }\n\telse {\n\t\t// we will compute the power using the binary algorithm\n\t\t// X <- A\n\t\tTFltVV* X = new TFltVV(*Mat);\n\n\t\t// temporary variables\n\t\tTFltVV* X1 = new TFltVV(GetRows(), GetCols());\n\t\tTFltVV* Temp;\n\n\t\t// do the work\n\t\tuint k1 = (uint) k;\n\t\tuint n = (uint) TMath::Log2(k);\n\n\t\tuint b;\n\n\t\tfor (uint i = 1; i <= n; i++) {\n\t\t\tb = (k1 >> (n-i)) & 1;\n\n\t\t\t// X <- X*X\n\t\t\tTLinAlg::Multiply(*X, *X, *X1);\n\n\t\t\t// swap X and X1 so that X holds the content\n\t\t\tTemp = X1;\n\t\t\tX1 = X;\n\t\t\tX = Temp;\n\t\t\tif (b == 1) {\n\t\t\t\t// X <- X*A\n\t\t\t\tTLinAlg::Multiply(*X, *Mat, *X1);\n\t\t\t\t// swap X and X1 so that X holds the content\n\t\t\t\tTemp = X1;\n\t\t\t\tX1 = X;\n\t\t\t\tX = Temp;\n\t\t\t}\n\t\t}\n\n\t\t// delete the temporary variables and wrap the result\n\t\tdelete X1;\n\n\t\treturn TFullMatrix(X);\n\t}\n}\n\nTVector TFullMatrix::GetCol(const int& ColIdx) const {\n\tEAssertR(ColIdx < GetCols(), \"Column index should be smaller then the number of columns!\");\n\n\tconst int Rows = GetRows();\n\n\tTVector Res(Rows, true);\n\tfor (int RowIdx = 0; RowIdx < Rows; RowIdx++) {\n\t\tRes[RowIdx] = Mat->At(RowIdx, ColIdx);\n\t}\n\n\treturn Res;\n}\n\nvoid TFullMatrix::SetRow(const int& RowIdx, const TVector& RowV) {\n\tEAssertR(RowV.IsRowVec(), \"When setting a row the input vector should be a row vector!\");\n\tEAssertR(RowV.Len() == GetCols(), \"Dimension mismatch!\");\n\n\tconst int Cols = GetCols();\n\n\tfor (int ColIdx = 0; ColIdx < Cols; ColIdx++) {\n\t\tMat->At(RowIdx, ColIdx) = RowV[ColIdx];\n\t}\n}\n\nvoid TFullMatrix::SetCol(const int& ColIdx, const TVector& ColV) {\n\tEAssertR(ColV.IsColVec(), \"When setting a column the input vector should be a column vector!\");\n\tEAssertR(ColV.Len() == GetRows(), \"Dimension mismatch!\");\n\n\tconst int Rows = GetRows();\n\n\tfor (int RowIdx = 0; RowIdx < Rows; RowIdx++) {\n\t\tMat->At(RowIdx, ColIdx) = ColV[RowIdx];\n\t}\n}\n\ndouble TFullMatrix::ColNorm(const int& ColIdx) const {\n\treturn TLinAlg::Norm(*Mat, ColIdx);\n}\n\ndouble TFullMatrix::ColNorm2(const int& ColIdx) const {\n\tdouble Norm = ColNorm(ColIdx);\n\treturn Norm * Norm;\n}\n\nTVector TFullMatrix::ColNormV() const {\n\tconst int Cols = GetCols();\n\n\tTVector Res(Cols, false);\n\tfor (int i = 0; i < Cols; i++) {\n\t\tRes[i] = ColNorm(i);\n\t}\n\n\treturn Res;\n}\n\nTVector TFullMatrix::ColNorm2V() const {\n\tTVector Res = ColNormV();\n\n\tconst int Cols = GetCols();\n\tfor (int i = 0; i < Cols; i++) {\n\t\tRes.Vec[i] *= Res.Vec[i];\n\t}\n\n\treturn Res;\n}\n\ndouble TFullMatrix::FromNorm() const {\n\treturn TLinAlg::FrobNorm(*Mat);\n}\n\ndouble TFullMatrix::RowNormL1(const int& RowIdx) const {\n\tconst int Cols = GetCols();\n\n\tdouble NormL1 = 0;\n\tfor (int ColIdx = 0; ColIdx < Cols; ColIdx++) {\n\t\tNormL1 += TFlt::Abs(Mat->At(RowIdx, ColIdx));\n\t}\n\n\treturn NormL1;\n}\n\nvoid TFullMatrix::NormalizeRowsL1() {\n\tconst int Rows = GetRows();\n\tconst int Cols = GetCols();\n\n\tfor (int RowIdx = 0; RowIdx < Rows; RowIdx++) {\n\t\tconst double Norm = RowNormL1(RowIdx);\n\t\tfor (int ColIdx = 0; ColIdx < Cols; ColIdx++) {\n\t\t\tMat->At(RowIdx, ColIdx) /= Norm;\n\t\t}\n\t}\n}\n\ndouble TFullMatrix::RowSum(const int& RowIdx) const {\n\tEAssertR(RowIdx < GetRows(), TStr::Fmt(\"Invalid row index: %d\", RowIdx));\n\n\tconst int NCols = GetCols();\n\tdouble Sum = 0;\n\n\tfor (int i = 0; i < NCols; i++) {\n\t\tSum += Mat->At(RowIdx, i);\n\t}\n\n\treturn Sum;\n}\n\nTVector TFullMatrix::RowSumV() const {\n\tconst int Rows = GetRows();\n\n\tTVector Res(Rows, true);\n\tfor (int i = 0; i < Rows; i++) {\n\t\tRes.Vec[i] = RowSum(i);\n\t}\n\n\treturn Res;\n}\n\nTVector TFullMatrix::GetColMinV() const {\n\tTVector Result;\tTLinAlgSearch::GetColMinV(*Mat, Result.Vec);\n\treturn Result;\n}\n\nTVector TFullMatrix::GetColMaxIdxV() const {\n\tTIntV IdxV;\tTLinAlgSearch::GetColMaxIdxV(*Mat, IdxV);\n\treturn TVector(IdxV, false);\n}\n\nTVector TFullMatrix::GetColMinIdxV() const {\n\tTIntV IdxV;\tTLinAlgSearch::GetColMinIdxV(*Mat, IdxV);\n\treturn TVector(IdxV, false);\n}\n\nTFullMatrix& TFullMatrix::CenterRows() {\n\tconst int Rows = GetRows();\n\tconst int Cols = GetCols();\n\n\t#pragma omp parallel for\n\tfor (int RowIdx = 0; RowIdx < Rows; RowIdx++) {\n\t\tdouble RowMean = 0;\n\t\tfor (int ColIdx = 0; ColIdx < Cols; ColIdx++) {\n\t\t\tRowMean += At(RowIdx, ColIdx);\n\t\t}\n\t\tRowMean /= Cols;\n\t\tfor (int ColIdx = 0; ColIdx < Cols; ColIdx++) {\n\t\t\tAt(RowIdx, ColIdx) -= RowMean;\n\t\t}\n\t}\n\n\treturn *this;\n}\n\nTFullMatrix TFullMatrix::GetCenteredRows() const {\n\treturn TFullMatrix(*this).CenterRows();\n}\n\nTTriple<TFullMatrix, TVector, TFullMatrix> TFullMatrix::Svd(const int& k) const {\n\tTTriple<TFullMatrix, TVector, TFullMatrix> Result;\n\n\tTLinAlg::ComputeThinSVD(*this, k, Result.Val1.GetMat(), Result.Val2.Vec, Result.Val3.GetMat());\n\n\treturn Result;\n}\n\nTFullMatrix TFullMatrix::GetInverse() const {\n\tEAssertR(GetRows() == GetCols(), \"Can only invert square matrices!\");\n\tthrow TExcept::New(\"TFullMatrix::GetInverse: Not implemented!\");\n}\n\nbool TFullMatrix::HasNan() const {\n\tconst int Cols = GetCols();\n\tconst int Rows = GetRows();\n\n\tfor (int RowN = 0; RowN < Rows; RowN++) {\n\t\tfor (int ColN = 0; ColN < Cols; ColN++) {\n\t\t\tif (TFlt::IsNan(At(RowN, ColN))) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false;\n}\n\nvoid TFullMatrix::Save(TSOut& SOut) const {\n\tEAssertR(!IsWrapper, \"TFullMatrix::Save: Cannot save a wrapper!\");\n\tTMatrix::Save(SOut);\n\tMat->Save(SOut);\n}\n\nvoid TFullMatrix::Load(TSIn& SIn) {\n\tEAssertR(!IsWrapper, \"TFullMatrix::Load: Cannot load a wrapper!\");\n\tTMatrix::Load(SIn);\n\tMat->Load(SIn);\n\tIsWrapper = false;\n}\n \n//#if defined(LAPACKE) && defined(EIGEN)\n////no need to reserve memory for the matrices, all will be done internaly\n////Set k to 500\n////Tolerance ignored!\n//int TLinAlg::ComputeThinSVD(const TMatrix& XYt, const int& k, TFltVV& U, TFltV& s, TFltVV& V, const int Iters, const double Tol){\n//\t//TStructuredCovarianceMatrix XYt(rows, cols, SampleN, MeanX, MeanY, X, Y);\n//\tEAssert(k <= XYt.GetRows() && k <= XYt.GetCols());\n//\n//\tconst int its = Iters != -1 ? Iters : 2;\n//\t const int m = XYt.GetRows();\n//\t const int n = XYt.GetCols();\n//\t int l = (int)((11 / 10.0) * k);\n//\t //printf(\"l is %d\\n\", l);\n//\t if ((its+1)*l >= MIN(m, n)){\n//\t\t TFltVV XYtfull; XYtfull.Gen(m, n);\n//\t\t TFltVV Identity; Identity.Gen(n, n);\n//\t\t typedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> Mat;\n//\t\t typedef Eigen::Map<Mat> MatW;\n//\t\t MatW IdentityWrapped(&Identity(0, 0).Val, n, n);\n//\t\t IdentityWrapped.setIdentity(n, n);\n//\t\t XYt.Multiply(Identity, XYtfull);\n//\t\t TFltVV VT;\n//\t\t TLinAlg::thinSVD(XYtfull, U, s, VT);\n//\t     V.Gen(VT.GetCols(), VT.GetRows());\n//\t\t TLinAlg::Transpose(VT, V);\n//\t }\n//\t else{\n//\t\t TTmStopWatch Time;\n//\t\t if (m >= n){\n//\t\t\t //H is used for intermediate result and should be of the size n times l!\n//\t\t\t TFltVV H(n,l); TLAMisc::FillRnd(H);\n//\t\t\t //TFltVV RSample; RSample.GenRandom(n, l);\n//\t\t\t TFltVV F, F0, F1, F2; F0.Gen(m, l); F1.Gen(m, l); F2.Gen(m, l);\n//\t\t\t //Time.Start();\n//\t\t\t //printf(\"Start Multiplying with XYt'*XYt twice\\n\");\n//\t\t\t //Size of F0 should be m x l\n//\t\t\t XYt.Multiply(H, F0);\n//\t\t\t //H is used for intermediate result and should be of the size n times l!\n//\t\t\t XYt.MultiplyT(F0, H);\n//\t\t\t //H is used for intermediate result and should be of the size n times l!\n//\t\t\t XYt.Multiply(H, F1);\n//\t\t\t //H is used for intermediate result and should be of the size n times l!\n//\t\t\t XYt.MultiplyT(F1, H); XYt.Multiply(H, F2);\n//\t\t\t //Time.Stop(\"Finish Multiplying with XYt'*XYt twice\\n\");\n//\t\t\t //Free the memory\n//\t\t\t H.Clr();\n//\t\t\t typedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> Mat;\n//\t\t\t F.Gen(m, (its + 1) * l);//its+1\n//\t\t\t typedef Eigen::Map<Mat> MatW;\n//\t\t\t MatW FWrapped(&F(0, 0).Val, m, (its + 1) * l); MatW F0Wrapped(&F0(0, 0).Val, m, l); MatW F1Wrapped(&F1(0, 0).Val, m, l); MatW F2Wrapped(&F2(0, 0).Val, m, l);\n//\t\t\t //printf(\"Started to join the memory\\n\");\n//\t\t\t //Time.Start();\n//\t\t\t FWrapped << F0Wrapped, F1Wrapped, F2Wrapped;\n//\t\t\t //Time.Stop(\"Finished joining the memory\\n\");\n//\t\t\t //Free the memory\n//\t\t\t F0.Clr(); F1.Clr(); F2.Clr();\n//\t\t\t //Do QR in place at the end F becomes Q\n//\t\t\t //printf(\"Orthogonal basis in place computation\\n\");\n//\t\t\t //Time.Start();\n//\t\t\t TLinAlg::QRbasis(F);\n//\t\t\t //Time.Stop(\"Orthogonal basis in place computation took: \");\n//\t\t\t //Is F still valid\n//\t\t\t TFltVV FF; FF.Gen(n, (its + 1) * l);\n//\t\t\t //printf(\"Start Multiplying with XYt'\\n\");\n//\t\t\t //Time.Start();\n//\t\t\t XYt.MultiplyT(F, FF);\n//\t\t\t //Time.Stop(\"Multiplying with XYt' took: \");\n//\t\t\t TFltVV UU, VT;\n//\t\t\t //printf(\"Size of matrix FF: %d\\n\", FF.GetCols());\n//\t\t\t //printf(\"Computation of thin SVD\\n\");\n//\t\t\t //Time.Start();\n//\t\t\t TFltVV FFT; FFT.Gen((its + 1) * l, n);\n//\t\t\t TLinAlg::Transpose(FF, FFT);\n//\t\t\t TLinAlg::thinSVD(FFT, UU, s, VT);\n//\t\t\t //Time.Stop(\"Computation of thin SVD took:\");\n//\t\t\t //printf(\"UU (%d, %d)\\n\", UU.GetRows(), UU.GetCols());\n//\t\t\t //Copy and save U\n//\t\t\t U.Gen(m, (its + 1)*l);\n//\t\t\t TLinAlg::Multiply(F, UU, U);\n//\t\t\t V.Gen(VT.GetCols(), VT.GetRows());\n//\t\t\t TLinAlg::Transpose(VT, V);\n//\t\t\t //U = Q*U2;\n//\t\t }\n//\t\t else{\n//\t\t\t //H is used for intermediate result and should be of the size m times l!\n//\t\t\t TFltVV H(m,l); TLAMisc::FillRnd(H);\n//\t\t\t //TFltVV RSample; RSample.GenRandom(n, l);\n//\t\t\t TFltVV F, F0, F1, F2; F0.Gen(n, l); F1.Gen(n, l); F2.Gen(n, l);\n//\t\t\t //printf(\"Star Multiplying with XYt'*XYt\\n\");\n//\t\t\t //Size of F0 should be m x l\n//\t\t\t XYt.MultiplyT(H, F0);\n//\t\t\t //printf(\"Finish Multiplying with XYt'*Xyt\");\n//\t\t\t //H is used for intermediate result and should be of the size m times l!\n//\t\t\t XYt.Multiply(F0, H);\n//\t\t\t //H is used for intermediate result and should be of the size m times l!\n//\t\t\t XYt.MultiplyT(H, F1);\n//\t\t\t //H is used for intermediate result and should be of the size m times l!\n//\t\t\t XYt.Multiply(F1, H); XYt.MultiplyT(H, F2);\n//\t\t\t printf(\"Finish Multiplying with XYt\\n\");\n//\t\t\t //Free the memory\n//\t\t\t H.Clr();\n//\t\t\t typedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> Mat;\n//\t\t\t F.Gen(n, (its + 1) * l); TLAMisc::FillRnd(F);//its+1\n//\n//\t\t\t typedef Eigen::Map<Mat> MatW;\n//\t\t\t MatW FWrapped(&F(0, 0).Val, n, (its + 1) * l); MatW F0Wrapped(&F0(0, 0).Val, n, l); MatW F1Wrapped(&F1(0, 0).Val, n, l); MatW F2Wrapped(&F2(0, 0).Val, n, l);\n//\t\t\t //printf(\"Started to join the memory\");\n//\t\t\t FWrapped << F0Wrapped, F1Wrapped, F2Wrapped;\n//\t\t\t //printf(\"Finished join the memory\");\n//\t\t\t //Free the memory\n//\t\t\t F0.Clr(); F1.Clr(); F2.Clr();\n//\t\t\t //Do QR in place at the end F becomes Q\n//\t\t\t TLinAlg::QRbasis(F);\n//\t\t\t //printf(\"QR finsihed\\n\");\n//\t\t\t //Is F still valid\n//\t\t\t TFltVV FF; FF.Gen(m, (its + 1) * l);\n//\t\t\t XYt.Multiply(F, FF);\n//\t\t\t TFltVV VV, VVT;\n//\t\t\t //printf(\"Size of matrix FF: %d\\n\", FF.GetCols());\n//\t\t\t TLinAlg::thinSVD(FF, U, s, VVT);\n//\t\t\t VV.Gen(VVT.GetCols(), VVT.GetRows());\n//\t\t\t TLinAlg::Transpose(VVT, VV);\n//\t\t\t V.Gen(n, (its + 1)*l);\n//\t\t\t //printf(\"Almost done\\n\");\n//\t\t\t //printf(\"F sizes: (%d, %d), VV sizes (%d, %d), V sizes (%d, %d)\", F.GetRows(), F.GetCols(), VV.GetRows(), VV.GetCols(), V.GetRows(), V.GetCols());\n//\t\t\t TLinAlg::Multiply(F, VV, V);\n//\t\t\t //V = Q*V2;\n//\t\t }\n//\t }\n//\t //Clip to only top k components\n//\t int kk = MIN(k, MIN(m, n));\n//\t TFltVV UU, VV; UU.Gen(U.GetRows(), kk); VV.Gen(V.GetRows(), kk);\n//\t TFltV ss; ss.Gen(kk);\n//\t for (int j = 0; j < kk; j++){\n//\t\t ss[j] = s[j];\n//\t\t for (int i = 0; i < U.GetRows(); i++){\n//\t\t\t UU(i, j) = U(i, j);\n//\t\t }\n//\t\t for (int i = 0; i < V.GetRows(); i++){\n//\t\t\t VV(i, j) = V(i, j);\n//\t\t }\n//\t }\n//\t U = UU;\n//\t V = VV;\n//\t s = ss;\n//\t return kk;\n// }\n//#else\n\nvoid TLinAlg::SVDSolve(const TFltVV& A, TFltV& x, const TFltV& b,\n\t\tconst double& EpsSing) {\n\tAssert(A.GetRows() == b.Len());\n\n\t// data used for solution\n\tint NumOfRows_Matrix = A.GetRows();\n\tint NumOfCols_Matrix = A.GetCols();\n\n\t// generating the SVD factorization\n\tTFltVV U, VT, M = A;\n\tTFltV Sing;\n\tComputeSVD(M, U, Sing, VT);\n\n\t// generating temporary solution\n\tx.Gen(NumOfCols_Matrix);\n\tTLinAlgTransform::FillZero(x);\n\tTFltV ui; ui.Gen(U.GetRows());\n\tTFltV vi; vi.Gen(VT.GetCols());\n\n\tdouble Scalar;\n\tint i = 0;\n\twhile (i < MIN(NumOfRows_Matrix, NumOfCols_Matrix) && Sing[i].Val > EpsSing*Sing[0]) {\n\t\tU.GetCol(i, ui);\n\t\tVT.GetRow(i, vi);\n\t\tScalar = TLinAlg::DotProduct(ui, b) / Sing[i].Val;\n\t\tTLinAlg::AddVec(Scalar, vi, x);\n\t\ti++;\n\t}\n}\n\nvoid TLinAlg::ComputeSVD(const TFltVV& A, TFltVV& U, TFltV& Sing,\n\t\tTFltVV& VT) {\n#ifdef LAPACKE\n\tMKLfunctions::SVDFactorization(A, U, Sing, VT);\n#else\n\t// TODO optimize this part\n\tif (VT.GetRows() != A.GetCols() || VT.GetCols() != A.GetCols()) {\n\t\tVT.Gen(A.GetCols(), A.GetCols());\n\t}\n\n\tTSvd SVD;\n\tSVD.Svd(A, U, Sing, VT);\n\n\t// transpose V\n\tVT.Transpose();\n#endif\n}\n\n\nint TLinAlg::ComputeThinSVD(const TMatrix& XYt, const int& k, TFltVV& U, TFltV& s, TFltVV& V, const int Iters, const double Tol){\n#if defined(LAPACKE) && defined(EIGEN)\n\t//no need to reserve memory for the matrices, all will be done internaly\n\t//Set k to 500\n\t//Tolerance ignored!\n\n\tEAssert(k <= XYt.GetRows() && k <= XYt.GetCols());\n\n\tconst int its = Iters != -1 ? Iters : 2;\n\t const int m = XYt.GetRows();\n\t const int n = XYt.GetCols();\n\t int l = (int)((11 / 10.0) * k);\n\t //printf(\"l is %d\\n\", l);\n\t if ((its+1)*l >= MIN(m, n)){\n\t\t TFltVV XYtfull; XYtfull.Gen(m, n);\n\t\t TFltVV Identity; Identity.Gen(n, n);\n\t\t typedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> Mat;\n\t\t typedef Eigen::Map<Mat> MatW;\n\t\t MatW IdentityWrapped(&Identity(0, 0).Val, n, n);\n\t\t IdentityWrapped.setIdentity(n, n);\n\t\t XYt.Multiply(Identity, XYtfull);\n\t\t TFltVV VT;\n\t\t TLinAlg::ThinSVD(XYtfull, U, s, VT);\n\t\t V.Gen(VT.GetCols(), VT.GetRows());\n\t\t TLinAlg::Transpose(VT, V);\n\t }\n\t else{\n\t\t TTmStopWatch Time;\n\t\t if (m >= n){\n\n\t\t\t //H is used for intermediate result and should be of the size n times l!\t\t\t \n\t\t\t TFltVV H(n,l); TLinAlgTransform::FillRnd(H);\n\t\t\t //TFltVV RSample; RSample.GenRandom(n, l);\n\t\t\t TFltVV F, F0, F1, F2; F0.Gen(m, l); F1.Gen(m, l); F2.Gen(m, l);\n\t\t\t //Time.Start();\n\t\t\t //printf(\"Start Multiplying with XYt'*XYt twice\\n\");\n\t\t\t //Size of F0 should be m x l\n\t\t\t XYt.Multiply(H, F0);\n\t\t\t //H is used for intermediate result and should be of the size n times l!\n\t\t\t XYt.MultiplyT(F0, H);\n\t\t\t //H is used for intermediate result and should be of the size n times l!\n\t\t\t XYt.Multiply(H, F1);\n\t\t\t //H is used for intermediate result and should be of the size n times l!\n\t\t\t XYt.MultiplyT(F1, H); XYt.Multiply(H, F2);\n\t\t\t //Time.Stop(\"Finish Multiplying with XYt'*XYt twice\\n\");\n\t\t\t //Free the memory\n\t\t\t H.Clr();\n\t\t\t typedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> Mat;\n\t\t\t F.Gen(m, (its + 1) * l);//its+1\n\t\t\t typedef Eigen::Map<Mat> MatW;\n\t\t\t MatW FWrapped(&F(0, 0).Val, m, (its + 1) * l); MatW F0Wrapped(&F0(0, 0).Val, m, l); MatW F1Wrapped(&F1(0, 0).Val, m, l); MatW F2Wrapped(&F2(0, 0).Val, m, l);\n\t\t\t //printf(\"Started to join the memory\\n\");\n\t\t\t //Time.Start();\n\t\t\t FWrapped << F0Wrapped, F1Wrapped, F2Wrapped;\n\t\t\t //Time.Stop(\"Finished joining the memory\\n\");\n\t\t\t //Free the memory\n\t\t\t F0.Clr(); F1.Clr(); F2.Clr();\n\t\t\t //Do QR in place at the end F becomes Q\n\t\t\t //printf(\"Orthogonal basis in place computation\\n\");\n\t\t\t //Time.Start();\n\t\t\t TLinAlg::QRbasis(F);\n\t\t\t //Time.Stop(\"Orthogonal basis in place computation took: \");\n\t\t\t //Is F still valid\n\t\t\t TFltVV FF; FF.Gen(n, (its + 1) * l);\n\t\t\t //printf(\"Start Multiplying with XYt'\\n\");\n\t\t\t //Time.Start();\n\t\t\t XYt.MultiplyT(F, FF);\n\t\t\t //Time.Stop(\"Multiplying with XYt' took: \");\n\t\t\t TFltVV UU, VT;\n\t\t\t //printf(\"Size of matrix FF: %d\\n\", FF.GetCols());\n\t\t\t //printf(\"Computation of thin SVD\\n\");\n\t\t\t //Time.Start();\n\t\t\t TFltVV FFT; FFT.Gen((its + 1) * l, n);\n\t\t\t TLinAlg::Transpose(FF, FFT);\n\t\t\t TLinAlg::ThinSVD(FFT, UU, s, VT);\n\t\t\t //Time.Stop(\"Computation of thin SVD took:\");\n\t\t\t //printf(\"UU (%d, %d)\\n\", UU.GetRows(), UU.GetCols());\n\t\t\t //Copy and save U\n\t\t\t U.Gen(m, (its + 1)*l);\n\t\t\t TLinAlg::Multiply(F, UU, U);\n\t\t\t V.Gen(VT.GetCols(), VT.GetRows());\n\t\t\t TLinAlg::Transpose(VT, V);\n\t\t\t //U = Q*U2;\n\t\t }\n\t\t else{\n\t\t\t //H is used for intermediate result and should be of the size m times l!\n\t\t\t TFltVV H(m,l); TLinAlgTransform::FillRnd(H);\n\t\t\t //TFltVV RSample; RSample.GenRandom(n, l);\n\t\t\t TFltVV F, F0, F1, F2; F0.Gen(n, l); F1.Gen(n, l); F2.Gen(n, l);\n\t\t\t //printf(\"Star Multiplying with XYt'*XYt\\n\");\n\t\t\t //Size of F0 should be m x l\n\t\t\t XYt.MultiplyT(H, F0);\n\t\t\t //printf(\"Finish Multiplying with XYt'*Xyt\");\n\t\t\t //H is used for intermediate result and should be of the size m times l!\n\t\t\t XYt.Multiply(F0, H);\n\t\t\t //H is used for intermediate result and should be of the size m times l!\n\t\t\t XYt.MultiplyT(H, F1);\n\t\t\t //H is used for intermediate result and should be of the size m times l!\n\t\t\t XYt.Multiply(F1, H); XYt.MultiplyT(H, F2);\n\t\t\t printf(\"Finish Multiplying with XYt\\n\");\n\t\t\t //Free the memory\n\t\t\t H.Clr();\n\t\t\t typedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> Mat;\n\t\t\t F.Gen(n, (its + 1) * l); TLinAlgTransform::FillRnd(F);//its+1\n\n\t\t\t typedef Eigen::Map<Mat> MatW;\n\t\t\t MatW FWrapped(&F(0, 0).Val, n, (its + 1) * l); MatW F0Wrapped(&F0(0, 0).Val, n, l); MatW F1Wrapped(&F1(0, 0).Val, n, l); MatW F2Wrapped(&F2(0, 0).Val, n, l);\n\t\t\t //printf(\"Started to join the memory\");\n\t\t\t FWrapped << F0Wrapped, F1Wrapped, F2Wrapped;\n\t\t\t //printf(\"Finished join the memory\");\n\t\t\t //Free the memory\n\t\t\t F0.Clr(); F1.Clr(); F2.Clr();\n\t\t\t //Do QR in place at the end F becomes Q\n\t\t\t TLinAlg::QRbasis(F);\n\t\t\t //printf(\"QR finsihed\\n\");\n\t\t\t //Is F still valid\n\t\t\t TFltVV FF; FF.Gen(m, (its + 1) * l);\n\t\t\t XYt.Multiply(F, FF);\n\t\t\t TFltVV VV, VVT;\n\t\t\t //printf(\"Size of matrix FF: %d\\n\", FF.GetCols());\n\t\t\t TLinAlg::ThinSVD(FF, U, s, VVT);\n\t\t\t VV.Gen(VVT.GetCols(), VVT.GetRows());\n\t\t\t TLinAlg::Transpose(VVT, VV);\n\t\t\t V.Gen(n, (its + 1)*l);\n\t\t\t //printf(\"Almost done\\n\");\n\t\t\t //printf(\"F sizes: (%d, %d), VV sizes (%d, %d), V sizes (%d, %d)\", F.GetRows(), F.GetCols(), VV.GetRows(), VV.GetCols(), V.GetRows(), V.GetCols());\n\t\t\t TLinAlg::Multiply(F, VV, V);\n\t\t\t //V = Q*V2;\n\t\t }\n\t }\n\t //Clip to only top k components\n\t int kk = MIN(k, MIN(m, n));\n\t TFltVV UU, VV; UU.Gen(U.GetRows(), kk); VV.Gen(V.GetRows(), kk);\n\t TFltV ss; ss.Gen(kk);\n\t for (int j = 0; j < kk; j++){\n\t\t ss[j] = s[j];\n\t\t for (int i = 0; i < U.GetRows(); i++){\n\t\t\t UU(i, j) = U(i, j);\n\t\t }\n\t\t for (int i = 0; i < V.GetRows(); i++){\n\t\t\t VV(i, j) = V(i, j);\n\t\t }\n\t }\n\t U = UU;\n\t V = VV;\n\t s = ss;\n\t return kk;\n#else\n\tTSparseSVD::OrtoIterSVD(XYt, k, s, U, V, Iters, Tol);\n\treturn k;\n#endif\n}\n//#endif\n", "meta": {"hexsha": "a345a513cb7b543e8cfa9fb738816bb2da37c49d", "size": 101708, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/glib/base/linalg.cpp", "max_stars_repo_name": "lstopar/qminer", "max_stars_repo_head_hexsha": "65bcb297f7eb69c37f42f7b999faf6a57d97819c", "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/glib/base/linalg.cpp", "max_issues_repo_name": "lstopar/qminer", "max_issues_repo_head_hexsha": "65bcb297f7eb69c37f42f7b999faf6a57d97819c", "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/glib/base/linalg.cpp", "max_forks_repo_name": "lstopar/qminer", "max_forks_repo_head_hexsha": "65bcb297f7eb69c37f42f7b999faf6a57d97819c", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-12-22T10:19:42.000Z", "max_forks_repo_forks_event_max_datetime": "2015-12-22T10:19:42.000Z", "avg_line_length": 30.4150717703, "max_line_length": 163, "alphanum_fraction": 0.5565737208, "num_tokens": 36289, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.734119526900183, "lm_q2_score": 0.6334102705979902, "lm_q1q2_score": 0.46499884818511344}}
{"text": "// boost\\math\\special_functions\\negative_binomial.hpp\n\n// Copyright Paul A. Bristow 2007.\n// Copyright John Maddock 2007.\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// http://en.wikipedia.org/wiki/negative_binomial_distribution\n// http://mathworld.wolfram.com/NegativeBinomialDistribution.html\n// http://documents.wolfram.com/teachersedition/Teacher/Statistics/DiscreteDistributions.html\n\n// The negative binomial distribution NegativeBinomialDistribution[n, p]\n// is the distribution of the number (k) of failures that occur in a sequence of trials before\n// r successes have occurred, where the probability of success in each trial is p.\n\n// In a sequence of Bernoulli trials or events\n// (independent, yes or no, succeed or fail) with success_fraction probability p,\n// negative_binomial is the probability that k or fewer failures\n// preceed the r th trial's success.\n// random variable k is the number of failures (NOT the probability).\n\n// Negative_binomial distribution is a discrete probability distribution.\n// But note that the negative binomial distribution\n// (like others including the binomial, Poisson & Bernoulli)\n// is strictly defined as a discrete function: only integral values of k are envisaged.\n// However because of the method of calculation using a continuous gamma function,\n// it is convenient to treat it as if a continous function,\n// and permit non-integral values of k.\n\n// However, by default the policy is to use discrete_quantile_policy.\n\n// To enforce the strict mathematical model, users should use conversion\n// on k outside this function to ensure that k is integral.\n\n// MATHCAD cumulative negative binomial pnbinom(k, n, p)\n\n// Implementation note: much greater speed, and perhaps greater accuracy,\n// might be achieved for extreme values by using a normal approximation.\n// This is NOT been tested or implemented.\n\n#ifndef BOOST_MATH_SPECIAL_NEGATIVE_BINOMIAL_HPP\n#define BOOST_MATH_SPECIAL_NEGATIVE_BINOMIAL_HPP\n\n#include <boost/math/distributions/fwd.hpp>\n#include <boost/math/special_functions/beta.hpp> // for ibeta(a, b, x) == Ix(a, b).\n#include <boost/math/distributions/complement.hpp> // complement.\n#include <boost/math/distributions/detail/common_error_handling.hpp> // error checks domain_error & logic_error.\n#include <boost/math/special_functions/fpclassify.hpp> // isnan.\n#include <boost/math/tools/roots.hpp> // for root finding.\n#include <boost/math/distributions/detail/inv_discrete_quantile.hpp>\n\n#include <boost/type_traits/is_floating_point.hpp>\n#include <boost/type_traits/is_integral.hpp>\n#include <boost/type_traits/is_same.hpp>\n#include <boost/mpl/if.hpp>\n\n#include <limits> // using std::numeric_limits;\n#include <utility>\n\n#if defined (BOOST_MSVC)\n#  pragma warning(push)\n// This believed not now necessary, so commented out.\n//#  pragma warning(disable: 4702) // unreachable code.\n// in domain_error_imp in error_handling.\n#endif\n\nnamespace boost\n{\n  namespace math\n  {\n    namespace negative_binomial_detail\n    {\n      // Common error checking routines for negative binomial distribution functions:\n      template <class RealType, class Policy>\n      inline bool check_successes(const char* function, const RealType& r, RealType* result, const Policy& pol)\n      {\n        if( !(boost::math::isfinite)(r) || (r <= 0) )\n        {\n          *result = policies::raise_domain_error<RealType>(\n            function,\n            \"Number of successes argument is %1%, but must be > 0 !\", r, pol);\n          return false;\n        }\n        return true;\n      }\n      template <class RealType, class Policy>\n      inline bool check_success_fraction(const char* function, const RealType& p, RealType* result, const Policy& pol)\n      {\n        if( !(boost::math::isfinite)(p) || (p < 0) || (p > 1) )\n        {\n          *result = policies::raise_domain_error<RealType>(\n            function,\n            \"Success fraction argument is %1%, but must be >= 0 and <= 1 !\", p, pol);\n          return false;\n        }\n        return true;\n      }\n      template <class RealType, class Policy>\n      inline bool check_dist(const char* function, const RealType& r, const RealType& p, RealType* result, const Policy& pol)\n      {\n        return check_success_fraction(function, p, result, pol)\n          && check_successes(function, r, result, pol);\n      }\n      template <class RealType, class Policy>\n      inline bool check_dist_and_k(const char* function, const RealType& r, const RealType& p, RealType k, RealType* result, const Policy& pol)\n      {\n        if(check_dist(function, r, p, result, pol) == false)\n        {\n          return false;\n        }\n        if( !(boost::math::isfinite)(k) || (k < 0) )\n        { // Check k failures.\n          *result = policies::raise_domain_error<RealType>(\n            function,\n            \"Number of failures argument is %1%, but must be >= 0 !\", k, pol);\n          return false;\n        }\n        return true;\n      } // Check_dist_and_k\n\n      template <class RealType, class Policy>\n      inline bool check_dist_and_prob(const char* function, const RealType& r, RealType p, RealType prob, RealType* result, const Policy& pol)\n      {\n        if(check_dist(function, r, p, result, pol) && detail::check_probability(function, prob, result, pol) == false)\n        {\n          return false;\n        }\n        return true;\n      } // check_dist_and_prob\n    } //  namespace negative_binomial_detail\n\n    template <class RealType = double, class Policy = policies::policy<> >\n    class negative_binomial_distribution\n    {\n    public:\n      typedef RealType value_type;\n      typedef Policy policy_type;\n\n      negative_binomial_distribution(RealType r, RealType p) : m_r(r), m_p(p)\n      { // Constructor.\n        RealType result;\n        negative_binomial_detail::check_dist(\n          \"negative_binomial_distribution<%1%>::negative_binomial_distribution\",\n          m_r, // Check successes r > 0.\n          m_p, // Check success_fraction 0 <= p <= 1.\n          &result, Policy());\n      } // negative_binomial_distribution constructor.\n\n      // Private data getter class member functions.\n      RealType success_fraction() const\n      { // Probability of success as fraction in range 0 to 1.\n        return m_p;\n      }\n      RealType successes() const\n      { // Total number of successes r.\n        return m_r;\n      }\n\n      static RealType find_lower_bound_on_p(\n        RealType trials,\n        RealType successes,\n        RealType alpha) // alpha 0.05 equivalent to 95% for one-sided test.\n      {\n        static const char* function = \"boost::math::negative_binomial<%1%>::find_lower_bound_on_p\";\n        RealType result = 0;  // of error checks.\n        RealType failures = trials - successes;\n        if(false == detail::check_probability(function, alpha, &result, Policy())\n          && negative_binomial_detail::check_dist_and_k(\n          function, successes, RealType(0), failures, &result, Policy()))\n        {\n          return result;\n        }\n        // Use complement ibeta_inv function for lower bound.\n        // This is adapted from the corresponding binomial formula\n        // here: http://www.itl.nist.gov/div898/handbook/prc/section2/prc241.htm\n        // This is a Clopper-Pearson interval, and may be overly conservative,\n        // see also \"A Simple Improved Inferential Method for Some\n        // Discrete Distributions\" Yong CAI and K. KRISHNAMOORTHY\n        // http://www.ucs.louisiana.edu/~kxk4695/Discrete_new.pdf\n        //\n        return ibeta_inv(successes, failures + 1, alpha, static_cast<RealType*>(0), Policy());\n      } // find_lower_bound_on_p\n\n      static RealType find_upper_bound_on_p(\n        RealType trials,\n        RealType successes,\n        RealType alpha) // alpha 0.05 equivalent to 95% for one-sided test.\n      {\n        static const char* function = \"boost::math::negative_binomial<%1%>::find_upper_bound_on_p\";\n        RealType result = 0;  // of error checks.\n        RealType failures = trials - successes;\n        if(false == negative_binomial_detail::check_dist_and_k(\n          function, successes, RealType(0), failures, &result, Policy())\n          && detail::check_probability(function, alpha, &result, Policy()))\n        {\n          return result;\n        }\n        if(failures == 0)\n           return 1;\n        // Use complement ibetac_inv function for upper bound.\n        // Note adjusted failures value: *not* failures+1 as usual.\n        // This is adapted from the corresponding binomial formula\n        // here: http://www.itl.nist.gov/div898/handbook/prc/section2/prc241.htm\n        // This is a Clopper-Pearson interval, and may be overly conservative,\n        // see also \"A Simple Improved Inferential Method for Some\n        // Discrete Distributions\" Yong CAI and K. KRISHNAMOORTHY\n        // http://www.ucs.louisiana.edu/~kxk4695/Discrete_new.pdf\n        //\n        return ibetac_inv(successes, failures, alpha, static_cast<RealType*>(0), Policy());\n      } // find_upper_bound_on_p\n\n      // Estimate number of trials :\n      // \"How many trials do I need to be P% sure of seeing k or fewer failures?\"\n\n      static RealType find_minimum_number_of_trials(\n        RealType k,     // number of failures (k >= 0).\n        RealType p,     // success fraction 0 <= p <= 1.\n        RealType alpha) // risk level threshold 0 <= alpha <= 1.\n      {\n        static const char* function = \"boost::math::negative_binomial<%1%>::find_minimum_number_of_trials\";\n        // Error checks:\n        RealType result = 0;\n        if(false == negative_binomial_detail::check_dist_and_k(\n          function, RealType(1), p, k, &result, Policy())\n          && detail::check_probability(function, alpha, &result, Policy()))\n        { return result; }\n\n        result = ibeta_inva(k + 1, p, alpha, Policy());  // returns n - k\n        return result + k;\n      } // RealType find_number_of_failures\n\n      static RealType find_maximum_number_of_trials(\n        RealType k,     // number of failures (k >= 0).\n        RealType p,     // success fraction 0 <= p <= 1.\n        RealType alpha) // risk level threshold 0 <= alpha <= 1.\n      {\n        static const char* function = \"boost::math::negative_binomial<%1%>::find_maximum_number_of_trials\";\n        // Error checks:\n        RealType result = 0;\n        if(false == negative_binomial_detail::check_dist_and_k(\n          function, RealType(1), p, k, &result, Policy())\n          &&  detail::check_probability(function, alpha, &result, Policy()))\n        { return result; }\n\n        result = ibetac_inva(k + 1, p, alpha, Policy());  // returns n - k\n        return result + k;\n      } // RealType find_number_of_trials complemented\n\n    private:\n      RealType m_r; // successes.\n      RealType m_p; // success_fraction\n    }; // template <class RealType, class Policy> class negative_binomial_distribution\n\n    typedef negative_binomial_distribution<double> negative_binomial; // Reserved name of type double.\n\n    template <class RealType, class Policy>\n    inline const std::pair<RealType, RealType> range(const negative_binomial_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>()); // max_integer?\n    }\n\n    template <class RealType, class Policy>\n    inline const std::pair<RealType, RealType> support(const negative_binomial_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>()); // max_integer?\n    }\n\n    template <class RealType, class Policy>\n    inline RealType mean(const negative_binomial_distribution<RealType, Policy>& dist)\n    { // Mean of Negative Binomial distribution = r(1-p)/p.\n      return dist.successes() * (1 - dist.success_fraction() ) / dist.success_fraction();\n    } // mean\n\n    //template <class RealType, class Policy>\n    //inline RealType median(const negative_binomial_distribution<RealType, Policy>& dist)\n    //{ // Median of negative_binomial_distribution is not defined.\n    //  return policies::raise_domain_error<RealType>(BOOST_CURRENT_FUNCTION, \"Median is not implemented, result is %1%!\", std::numeric_limits<RealType>::quiet_NaN());\n    //} // median\n    // Now implemented via quantile(half) in derived accessors.\n\n    template <class RealType, class Policy>\n    inline RealType mode(const negative_binomial_distribution<RealType, Policy>& dist)\n    { // Mode of Negative Binomial distribution = floor[(r-1) * (1 - p)/p]\n      BOOST_MATH_STD_USING // ADL of std functions.\n      return floor((dist.successes() -1) * (1 - dist.success_fraction()) / dist.success_fraction());\n    } // mode\n\n    template <class RealType, class Policy>\n    inline RealType skewness(const negative_binomial_distribution<RealType, Policy>& dist)\n    { // skewness of Negative Binomial distribution = 2-p / (sqrt(r(1-p))\n      BOOST_MATH_STD_USING // ADL of std functions.\n      RealType p = dist.success_fraction();\n      RealType r = dist.successes();\n\n      return (2 - p) /\n        sqrt(r * (1 - p));\n    } // skewness\n\n    template <class RealType, class Policy>\n    inline RealType kurtosis(const negative_binomial_distribution<RealType, Policy>& dist)\n    { // kurtosis of Negative Binomial distribution\n      // http://en.wikipedia.org/wiki/Negative_binomial is kurtosis_excess so add 3\n      RealType p = dist.success_fraction();\n      RealType r = dist.successes();\n      return 3 + (6 / r) + ((p * p) / (r * (1 - p)));\n    } // kurtosis\n\n     template <class RealType, class Policy>\n    inline RealType kurtosis_excess(const negative_binomial_distribution<RealType, Policy>& dist)\n    { // kurtosis excess of Negative Binomial distribution\n      // http://mathworld.wolfram.com/Kurtosis.html table of kurtosis_excess\n      RealType p = dist.success_fraction();\n      RealType r = dist.successes();\n      return (6 - p * (6-p)) / (r * (1-p));\n    } // kurtosis_excess\n\n    template <class RealType, class Policy>\n    inline RealType variance(const negative_binomial_distribution<RealType, Policy>& dist)\n    { // Variance of Binomial distribution = r (1-p) / p^2.\n      return  dist.successes() * (1 - dist.success_fraction())\n        / (dist.success_fraction() * dist.success_fraction());\n    } // variance\n\n    // RealType standard_deviation(const negative_binomial_distribution<RealType, Policy>& dist)\n    // standard_deviation provided by derived accessors.\n    // RealType hazard(const negative_binomial_distribution<RealType, Policy>& dist)\n    // hazard of Negative Binomial distribution provided by derived accessors.\n    // RealType chf(const negative_binomial_distribution<RealType, Policy>& dist)\n    // chf of Negative Binomial distribution provided by derived accessors.\n\n    template <class RealType, class Policy>\n    inline RealType pdf(const negative_binomial_distribution<RealType, Policy>& dist, const RealType& k)\n    { // Probability Density/Mass Function.\n      BOOST_FPU_EXCEPTION_GUARD\n\n      static const char* function = \"boost::math::pdf(const negative_binomial_distribution<%1%>&, %1%)\";\n\n      RealType r = dist.successes();\n      RealType p = dist.success_fraction();\n      RealType result = 0;\n      if(false == negative_binomial_detail::check_dist_and_k(\n        function,\n        r,\n        dist.success_fraction(),\n        k,\n        &result, Policy()))\n      {\n        return result;\n      }\n\n      result = (p/(r + k)) * ibeta_derivative(r, static_cast<RealType>(k+1), p, Policy());\n      // Equivalent to:\n      // return exp(lgamma(r + k) - lgamma(r) - lgamma(k+1)) * pow(p, r) * pow((1-p), k);\n      return result;\n    } // negative_binomial_pdf\n\n    template <class RealType, class Policy>\n    inline RealType cdf(const negative_binomial_distribution<RealType, Policy>& dist, const RealType& k)\n    { // Cumulative Distribution Function of Negative Binomial.\n      static const char* function = \"boost::math::cdf(const negative_binomial_distribution<%1%>&, %1%)\";\n      using boost::math::ibeta; // Regularized incomplete beta function.\n      // k argument may be integral, signed, or unsigned, or floating point.\n      // If necessary, it has already been promoted from an integral type.\n      RealType p = dist.success_fraction();\n      RealType r = dist.successes();\n      // Error check:\n      RealType result = 0;\n      if(false == negative_binomial_detail::check_dist_and_k(\n        function,\n        r,\n        dist.success_fraction(),\n        k,\n        &result, Policy()))\n      {\n        return result;\n      }\n\n      RealType probability = ibeta(r, static_cast<RealType>(k+1), p, Policy());\n      // Ip(r, k+1) = ibeta(r, k+1, p)\n      return probability;\n    } // cdf Cumulative Distribution Function Negative Binomial.\n\n      template <class RealType, class Policy>\n      inline RealType cdf(const complemented2_type<negative_binomial_distribution<RealType, Policy>, RealType>& c)\n      { // Complemented Cumulative Distribution Function Negative Binomial.\n\n      static const char* function = \"boost::math::cdf(const negative_binomial_distribution<%1%>&, %1%)\";\n      using boost::math::ibetac; // Regularized incomplete beta function complement.\n      // k argument may be integral, signed, or unsigned, or floating point.\n      // If necessary, it has already been promoted from an integral type.\n      RealType const& k = c.param;\n      negative_binomial_distribution<RealType, Policy> const& dist = c.dist;\n      RealType p = dist.success_fraction();\n      RealType r = dist.successes();\n      // Error check:\n      RealType result = 0;\n      if(false == negative_binomial_detail::check_dist_and_k(\n        function,\n        r,\n        p,\n        k,\n        &result, Policy()))\n      {\n        return result;\n      }\n      // Calculate cdf negative binomial using the incomplete beta function.\n      // Use of ibeta here prevents cancellation errors in calculating\n      // 1-p if p is very small, perhaps smaller than machine epsilon.\n      // Ip(k+1, r) = ibetac(r, k+1, p)\n      // constrain_probability here?\n     RealType probability = ibetac(r, static_cast<RealType>(k+1), p, Policy());\n      // Numerical errors might cause probability to be slightly outside the range < 0 or > 1.\n      // This might cause trouble downstream, so warn, possibly throw exception, but constrain to the limits.\n      return probability;\n    } // cdf Cumulative Distribution Function Negative Binomial.\n\n    template <class RealType, class Policy>\n    inline RealType quantile(const negative_binomial_distribution<RealType, Policy>& dist, const RealType& P)\n    { // Quantile, percentile/100 or Percent Point Negative Binomial function.\n      // Return the number of expected failures k for a given probability p.\n\n      // Inverse cumulative Distribution Function or Quantile (percentile / 100) of negative_binomial Probability.\n      // MAthCAD pnbinom return smallest k such that negative_binomial(k, n, p) >= probability.\n      // k argument may be integral, signed, or unsigned, or floating point.\n      // BUT Cephes/CodeCogs says: finds argument p (0 to 1) such that cdf(k, n, p) = y\n      static const char* function = \"boost::math::quantile(const negative_binomial_distribution<%1%>&, %1%)\";\n      BOOST_MATH_STD_USING // ADL of std functions.\n\n      RealType p = dist.success_fraction();\n      RealType r = dist.successes();\n      // Check dist and P.\n      RealType result = 0;\n      if(false == negative_binomial_detail::check_dist_and_prob\n        (function, r, p, P, &result, Policy()))\n      {\n        return result;\n      }\n\n      // Special cases.\n      if (P == 1)\n      {  // Would need +infinity failures for total confidence.\n        result = policies::raise_overflow_error<RealType>(\n            function,\n            \"Probability argument is 1, which implies infinite failures !\", Policy());\n        return result;\n       // usually means return +std::numeric_limits<RealType>::infinity();\n       // unless #define BOOST_MATH_THROW_ON_OVERFLOW_ERROR\n      }\n      if (P == 0)\n      { // No failures are expected if P = 0.\n        return 0; // Total trials will be just dist.successes.\n      }\n      if (P <= pow(dist.success_fraction(), dist.successes()))\n      { // p <= pdf(dist, 0) == cdf(dist, 0)\n        return 0;\n      }\n      /*\n      // Calculate quantile of negative_binomial using the inverse incomplete beta function.\n      using boost::math::ibeta_invb;\n      return ibeta_invb(r, p, P, Policy()) - 1; //\n      */\n      RealType guess = 0;\n      RealType factor = 5;\n      if(r * r * r * P * p > 0.005)\n         guess = detail::inverse_negative_binomial_cornish_fisher(r, p, RealType(1-p), P, RealType(1-P), Policy());\n\n      if(guess < 10)\n      {\n         //\n         // Cornish-Fisher Negative binomial approximation not accurate in this area:\n         //\n         guess = (std::min)(RealType(r * 2), RealType(10));\n      }\n      else\n         factor = (1-P < sqrt(tools::epsilon<RealType>())) ? 2 : (guess < 20 ? 1.2f : 1.1f);\n      BOOST_MATH_INSTRUMENT_CODE(\"guess = \" << guess);\n      //\n      // Max iterations permitted:\n      //\n      boost::uintmax_t max_iter = policies::get_max_root_iterations<Policy>();\n      typedef typename Policy::discrete_quantile_type discrete_type;\n      return detail::inverse_discrete_quantile(\n         dist,\n         P,\n         1-P,\n         guess,\n         factor,\n         RealType(1),\n         discrete_type(),\n         max_iter);\n    } // RealType quantile(const negative_binomial_distribution dist, p)\n\n    template <class RealType, class Policy>\n    inline RealType quantile(const complemented2_type<negative_binomial_distribution<RealType, Policy>, RealType>& c)\n    {  // Quantile or Percent Point Binomial function.\n       // Return the number of expected failures k for a given\n       // complement of the probability Q = 1 - P.\n       static const char* function = \"boost::math::quantile(const negative_binomial_distribution<%1%>&, %1%)\";\n       BOOST_MATH_STD_USING\n\n       // Error checks:\n       RealType Q = c.param;\n       const negative_binomial_distribution<RealType, Policy>& dist = c.dist;\n       RealType p = dist.success_fraction();\n       RealType r = dist.successes();\n       RealType result = 0;\n       if(false == negative_binomial_detail::check_dist_and_prob(\n          function,\n          r,\n          p,\n          Q,\n          &result, Policy()))\n       {\n          return result;\n       }\n\n       // Special cases:\n       //\n       if(Q == 1)\n       {  // There may actually be no answer to this question,\n          // since the probability of zero failures may be non-zero,\n          return 0; // but zero is the best we can do:\n       }\n       if (-Q <= boost::math::powm1(dist.success_fraction(), dist.successes(), Policy()))\n       {  // q <= cdf(complement(dist, 0)) == pdf(dist, 0)\n          return 0; //\n       }\n       if(Q == 0)\n       {  // Probability 1 - Q  == 1 so infinite failures to achieve certainty.\n          // Would need +infinity failures for total confidence.\n          result = policies::raise_overflow_error<RealType>(\n             function,\n             \"Probability argument complement is 0, which implies infinite failures !\", Policy());\n          return result;\n          // usually means return +std::numeric_limits<RealType>::infinity();\n          // unless #define BOOST_MATH_THROW_ON_OVERFLOW_ERROR\n       }\n       //return ibetac_invb(r, p, Q, Policy()) -1;\n       RealType guess = 0;\n       RealType factor = 5;\n       if(r * r * r * (1-Q) * p > 0.005)\n          guess = detail::inverse_negative_binomial_cornish_fisher(r, p, RealType(1-p), RealType(1-Q), Q, Policy());\n\n       if(guess < 10)\n       {\n          //\n          // Cornish-Fisher Negative binomial approximation not accurate in this area:\n          //\n          guess = (std::min)(RealType(r * 2), RealType(10));\n       }\n       else\n          factor = (Q < sqrt(tools::epsilon<RealType>())) ? 2 : (guess < 20 ? 1.2f : 1.1f);\n       BOOST_MATH_INSTRUMENT_CODE(\"guess = \" << guess);\n       //\n       // Max iterations permitted:\n       //\n       boost::uintmax_t max_iter = policies::get_max_root_iterations<Policy>();\n       typedef typename Policy::discrete_quantile_type discrete_type;\n       return detail::inverse_discrete_quantile(\n          dist,\n          1-Q,\n          Q,\n          guess,\n          factor,\n          RealType(1),\n          discrete_type(),\n          max_iter);\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#if defined (BOOST_MSVC)\n# pragma warning(pop)\n#endif\n\n#endif // BOOST_MATH_SPECIAL_NEGATIVE_BINOMIAL_HPP\n", "meta": {"hexsha": "28ce4b996cb946de20b2cb6479a838f39ae77278", "size": 25212, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/boost/math/distributions/negative_binomial.hpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 71.0, "max_stars_repo_stars_event_min_datetime": "2015-01-17T00:29:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-09T02:59:16.000Z", "max_issues_repo_path": "boost/boost/math/distributions/negative_binomial.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/math/distributions/negative_binomial.hpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 44.0, "max_forks_repo_forks_event_min_datetime": "2015-03-18T09:20:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-21T08:09:17.000Z", "avg_line_length": 42.80475382, "max_line_length": 167, "alphanum_fraction": 0.6534190068, "num_tokens": 6002, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195152660687, "lm_q2_score": 0.6334102775181399, "lm_q1q2_score": 0.4649988458961629}}
{"text": "//////////////////////////////////////////////////////////////////////////////\n// unit_test_fun.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_NON_PARAMETRIC_KOLMOGOROV_SMIRNOV_UNIT_TEST_FUN_HPP_ER_2009\n#define BOOST_STATISTICS_DETAIL_NON_PARAMETRIC_KOLMOGOROV_SMIRNOV_UNIT_TEST_FUN_HPP_ER_2009\n#include <boost/numeric/conversion/bounds.hpp>\n#include <boost/test/test_tools.hpp>\n#include <boost/statistics/detail/non_parametric/kolmogorov_smirnov/statistic.hpp>\n\nnamespace boost{\nnamespace statistics{\nnamespace detail{\nnamespace kolmogorov_smirnov{\n\n        template<typename D>\n    \tstruct unit_test_fun{\n\n            typedef typename D::value_type value_type;\n        \n            typedef boost::numeric::bounds<value_type> bounds_;\n\n            unit_test_fun() : ks0( bounds_::highest() ){}\n\t\t\n            template<typename AccSet>\n            void operator()(const AccSet& acc,const D& d,std::ostream& os)const{\n                namespace ns = boost::statistics::detail::kolmogorov_smirnov;\n            \tvalue_type ks1 = ns::statistic<value_type>( acc, d );\n                bool ok = false; // (ks1 - ks0) < bounds_::smallest(); \n                BOOST_WARN( ok );\n                os \n                    << '('\n                    << boost::accumulators::extract::count(acc) \n                    << ','\n                    << ks1\n                    << ','\n                    << ok\n                    << ')'\n                    << std::endl;\t    \n                \n                // Warn not check for 2 reasons:\n                // - The inequality is only probabilistic\n                // - For very large sample size, numeric error may dominate\n                \n                this->ks0 = ks1;\n                \n            }\n            \n            private:\n            mutable value_type ks0;\n    \t};\n\n}// kolmogorov_smirnov\n}// detail\n}// statistics\n}// boost\n\n#endif\n", "meta": {"hexsha": "20294ac3727a2c26ef364f0effcf106e17140e9b", "size": 2401, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "non_parametric/boost/statistics/detail/non_parametric/backup_once_in_trunk/non_parametric/kolmogorov_smirnov/unit_test_fun.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/unit_test_fun.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/unit_test_fun.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": 38.1111111111, "max_line_length": 91, "alphanum_fraction": 0.4802165764, "num_tokens": 473, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195385342971, "lm_q2_score": 0.6334102567576901, "lm_q1q2_score": 0.4649988453938461}}
{"text": "/* test_extreme_value_distribution.cpp\r\n *\r\n * Copyright Steven Watanabe 2010\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 * $Id: test_extreme_value_distribution.cpp 71018 2011-04-05 21:27:52Z steven_watanabe $\r\n *\r\n */\r\n\r\n#include <boost/random/extreme_value_distribution.hpp>\r\n#include <limits>\r\n\r\n#define BOOST_RANDOM_DISTRIBUTION boost::random::extreme_value_distribution<>\r\n#define BOOST_RANDOM_ARG1 a\r\n#define BOOST_RANDOM_ARG2 b\r\n#define BOOST_RANDOM_ARG1_DEFAULT 1.0\r\n#define BOOST_RANDOM_ARG2_DEFAULT 1.0\r\n#define BOOST_RANDOM_ARG1_VALUE 7.5\r\n#define BOOST_RANDOM_ARG2_VALUE 0.25\r\n\r\n#define BOOST_RANDOM_DIST0_MIN -(std::numeric_limits<double>::infinity)()\r\n#define BOOST_RANDOM_DIST0_MAX (std::numeric_limits<double>::infinity)()\r\n#define BOOST_RANDOM_DIST1_MIN -(std::numeric_limits<double>::infinity)()\r\n#define BOOST_RANDOM_DIST1_MAX (std::numeric_limits<double>::infinity)()\r\n#define BOOST_RANDOM_DIST2_MIN -(std::numeric_limits<double>::infinity)()\r\n#define BOOST_RANDOM_DIST2_MAX (std::numeric_limits<double>::infinity)()\r\n\r\n#define BOOST_RANDOM_TEST1_PARAMS (-100.0)\r\n#define BOOST_RANDOM_TEST1_MAX 0\r\n\r\n#define BOOST_RANDOM_TEST2_PARAMS (100.0)\r\n#define BOOST_RANDOM_TEST2_MIN 0\r\n\r\n#include \"test_distribution.ipp\"\r\n", "meta": {"hexsha": "29cb2a7aaae313e42831e2a7f634b5191c19c557", "size": 1354, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/random/test/test_extreme_value_distribution.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/random/test/test_extreme_value_distribution.cpp", "max_issues_repo_name": "xiaoliang2121/Boost", "max_issues_repo_head_hexsha": "fc90c3fde129c62565c023f091eddc4a7ed9902b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-03-19T08:23:23.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-24T07:48:47.000Z", "max_forks_repo_path": "libs/random/test/test_extreme_value_distribution.cpp", "max_forks_repo_name": "xiaoliang2121/Boost", "max_forks_repo_head_hexsha": "fc90c3fde129c62565c023f091eddc4a7ed9902b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 36.5945945946, "max_line_length": 89, "alphanum_fraction": 0.7858197932, "num_tokens": 329, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.46499884310489625}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// QuickBook Example\n\n// Copyright (c) 2011 Barend Gehrels, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n//[assign_2d_point\n//` Shows the usage of assign to set point coordinates, and, besides that, shows how you can initialize ttmath points with high precision\n\n#include <iostream>\n#include <iomanip>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n\n#if defined(HAVE_TTMATH)\n#  include <boost/geometry/extensions/contrib/ttmath_stub.hpp>\n#endif\n\n\nint main()\n{\n    using boost::geometry::assign_values;\n\n\n    boost::geometry::model::d2::point_xy<double> p1;\n    assign_values(p1, 1.2345, 2.3456);\n\n#if defined(HAVE_TTMATH)\n    boost::geometry::model::d2::point_xy<ttmath::Big<1,4> > p2;\n    assign_values(p2, \"1.2345\", \"2.3456\"); /*< It is possible to assign coordinates with other types than the coordinate type.\n        For ttmath, you can e.g. conveniently use strings. The advantage is that it then has higher precision, because\n        if doubles are used for assignments the double-precision is used.\n        >*/\n#endif\n\n    std::cout\n        << std::setprecision(20)\n        << boost::geometry::dsv(p1) << std::endl\n#if defined(HAVE_TTMATH)\n        << boost::geometry::dsv(p2) << std::endl\n#endif\n        ;\n\n    return 0;\n}\n\n//]\n\n\n//[assign_2d_point_output\n/*`\nOutput:\n[pre\n(1.2344999999999999, 2.3456000000000001)\n(1.2345, 2.3456)\n]\n*/\n//]\n", "meta": {"hexsha": "84dbbe6905204ac30752d66c6f032b8fa3801e6d", "size": 1607, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/doc/src/examples/algorithms/assign_2d_point.cpp", "max_stars_repo_name": "olegshnitko/libboost", "max_stars_repo_head_hexsha": "548eb6365af3724d8f4b47ebbabf7eb3ad8e66a8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-10-31T00:40:22.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-31T00:40:22.000Z", "max_issues_repo_path": "libs/geometry/doc/src/examples/algorithms/assign_2d_point.cpp", "max_issues_repo_name": "olegshnitko/libboost", "max_issues_repo_head_hexsha": "548eb6365af3724d8f4b47ebbabf7eb3ad8e66a8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-01-17T10:11:43.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-17T10:11:43.000Z", "max_forks_repo_path": "libs/geometry/doc/src/examples/algorithms/assign_2d_point.cpp", "max_forks_repo_name": "olegshnitko/libboost", "max_forks_repo_head_hexsha": "548eb6365af3724d8f4b47ebbabf7eb3ad8e66a8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.5079365079, "max_line_length": 137, "alphanum_fraction": 0.6981953951, "num_tokens": 451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.63341024983754, "lm_q2_score": 0.7341195152660687, "lm_q1q2_score": 0.4649988255752943}}
{"text": "\n// deal.II includes ----------------------------------------------------------------------\n#include <deal.II/base/quadrature.h>\n#include <deal.II/base/utilities.h>\n#include <deal.II/dofs/dof_accessor.h>\n#include <deal.II/dofs/dof_handler.h>\n#include <deal.II/dofs/dof_tools.h>\n#include <deal.II/fe/fe_values.h>\n\n// system includes -----------------------------------------------------------------------\n#include <Eigen/Dense>\n#include <algorithm>\n#include <array>\n#include <boost/multi_array.hpp>\n\n#ifndef _L2ERRORS_H_\n#define _L2ERRORS_H_\n\nnamespace boltzmann {\n\nclass Errors\n{\n private:\n  //  Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>\n  //  typedef boost::multi_array<double, 2> matrix_t;\n  typedef dealii::DoFHandler<2> dh_t;\n  typedef dealii::Vector<double> vec_t;\n\n public:\n  /**\n   * Compute L2-distance for tensor-product discretization\n   *\n   * @param dh DoFHandler\n   * @param y1 coefficients\n   * @param y2 coefficients\n   * @param SN spectral-basis overlap coefficients\n   * @param INDEXER map(physical dof, velocity dof) -> global dof\n   *\n   * @return l2 error\n   */\n  template <typename VECTOR, typename INDEXER>\n  double compute(\n      const dh_t& dh, const double* y1, const double* y2, const VECTOR& SN, const INDEXER& indexer);\n\n  /**\n   * @brief same as compute, but return also norm of y2 (to compute relative error)\n   *\n   * @param dh\n   * @param y1\n   * @param y2\n   * @param SN\n   * @param indexer\n   *\n   * @return\n   */\n  template <typename VECTOR, typename INDEXER>\n  std::array<double, 2> compute2(\n      const dh_t& dh, const double* y1, const double* y2, const VECTOR& SN, const INDEXER& indexer);\n\n  const vec_t& get_cell_wise_error() const { return cell_wise_error; }\n\n private:\n  dealii::Vector<double> cell_wise_error;\n};\n\ntemplate <typename VECTOR, typename INDEXER>\ndouble\nErrors::compute(\n    const dh_t& dh, const double* y1, const double* y2, const VECTOR& SN, const INDEXER& indexer)\n{\n  dealii::QGauss<2> quad(2);\n\n  const dealii::UpdateFlags update_flags =\n      (dealii::update_values | dealii::update_JxW_values | dealii::update_quadrature_points);\n  auto& fe = dh.get_fe();\n  dealii::FEValues<2> fe_values(fe, quad, update_flags);\n\n  int dofs_per_cell = fe_values.dofs_per_cell;\n  int n_qpoints = quad.size();\n\n  // number of velocity dofs\n  const int N = SN.size();\n  cell_wise_error.reinit(dh.get_triangulation().n_active_cells());\n  std::fill(cell_wise_error.begin(), cell_wise_error.end(), 0.0);\n\n  double error = 0;\n  std::vector<unsigned int> local_indices(dofs_per_cell);\n\n  typedef Eigen::Map<const Eigen::VectorXd> vvec_t;\n\n  auto vcontrib = [&](vvec_t& v1, vvec_t& v2) {\n    double sum = 0;\n    for (int i = 0; i < N; ++i) {\n      sum += v1(i) * v2(i) * SN[i];\n    }\n    return sum;\n  };\n\n  double global_error = 0;\n  for (auto cell : dh.active_cell_iterators()) {\n    double cell_error = 0;\n    cell->get_dof_indices(local_indices);\n    fe_values.reinit(cell);\n\n    double area = 0;\n    for (int q = 0; q < n_qpoints; ++q) {\n      area += fe_values.JxW(q);\n    }\n\n    for (int ix1 = 0; ix1 < dofs_per_cell; ++ix1) {\n      // index to global block\n      unsigned int ig1 = indexer.to_global(local_indices[ix1], 0);\n      vvec_t v1(y1 + ig1, N);\n      vvec_t v2(y2 + ig1, N);\n\n      // off diagonal contribution\n      for (int ix2 = 0; ix2 < dofs_per_cell; ++ix2) {\n        unsigned int ig2 = indexer.to_global(local_indices[ix2], 0);\n        vvec_t v1p(y1 + ig2, N);\n        vvec_t v2p(y2 + ig2, N);\n\n        double overlap = 0;\n        for (int q = 0; q < n_qpoints; ++q) {\n          overlap +=\n              fe_values.shape_value(ix1, q) * fe_values.shape_value(ix2, q) * fe_values.JxW(q);\n        }\n\n        double verr = vcontrib(v1, v1p) + vcontrib(v2, v2p) - 2 * vcontrib(v1, v2p);\n        cell_error += overlap * verr;\n      }\n    }\n    cell_wise_error[cell->index()] = cell_error / area;\n    global_error += cell_error;\n  }\n\n  return global_error;\n}\n\n/**\n * Compute L2-distance for tensor-product discretization\n *\n * @param dh DoFHandler\n * @param y1 coefficients\n * @param y2 coefficients\n * @param SN spectral-basis overlap coefficients\n * @param INDEXER map(physical dof, velocity dof) -> global dof\n *\n * @return l2 error |y1-y2|, |y2|\n */\ntemplate <typename VECTOR, typename INDEXER>\nstd::array<double, 2>\nErrors::compute2(\n    const dh_t& dh, const double* y1, const double* y2, const VECTOR& SN, const INDEXER& indexer)\n{\n  dealii::QGauss<2> quad(2);\n\n  const dealii::UpdateFlags update_flags =\n      (dealii::update_values | dealii::update_JxW_values | dealii::update_quadrature_points);\n  auto& fe = dh.get_fe();\n  dealii::FEValues<2> fe_values(fe, quad, update_flags);\n\n  int dofs_per_cell = fe_values.dofs_per_cell;\n  int n_qpoints = quad.size();\n\n  // number of velocity dofs\n  const int N = SN.size();\n  cell_wise_error.reinit(dh.get_triangulation().n_active_cells());\n  std::fill(cell_wise_error.begin(), cell_wise_error.end(), 0.0);\n\n  double error = 0;\n  double norm = 0;\n  std::vector<unsigned int> local_indices(dofs_per_cell);\n\n  typedef Eigen::Map<const Eigen::VectorXd> vvec_t;\n\n  auto vcontrib = [&](vvec_t& v1, vvec_t& v2) {\n    double sum = 0;\n    for (int i = 0; i < N; ++i) {\n      sum += v1(i) * v2(i) * SN[i];\n    }\n    return sum;\n  };\n\n  double global_error = 0;\n  for (auto cell : dh.active_cell_iterators()) {\n    double cell_error = 0;\n    cell->get_dof_indices(local_indices);\n    fe_values.reinit(cell);\n\n    double area = 0;\n    for (int q = 0; q < n_qpoints; ++q) {\n      area += fe_values.JxW(q);\n    }\n\n    for (int ix1 = 0; ix1 < dofs_per_cell; ++ix1) {\n      // index to global block\n      unsigned int ig1 = indexer.to_global(local_indices[ix1], 0);\n      vvec_t v1(y1 + ig1, N);\n      vvec_t v2(y2 + ig1, N);\n\n      // off diagonal contribution\n      for (int ix2 = 0; ix2 < dofs_per_cell; ++ix2) {\n        unsigned int ig2 = indexer.to_global(local_indices[ix2], 0);\n        vvec_t v1p(y1 + ig2, N);\n        vvec_t v2p(y2 + ig2, N);\n\n        double overlap = 0;\n        for (int q = 0; q < n_qpoints; ++q) {\n          overlap +=\n              fe_values.shape_value(ix1, q) * fe_values.shape_value(ix2, q) * fe_values.JxW(q);\n        }\n\n        double verr = vcontrib(v1, v1p) + vcontrib(v2, v2p) - 2 * vcontrib(v1, v2p);\n        cell_error += overlap * verr;\n      }\n    }\n\n    // compute |y2|\n    for (int ix = 0; ix < dofs_per_cell; ++ix) {\n      unsigned int ig = indexer.to_global(local_indices[ix], 0);\n      double sum = 0;\n      for (int q = 0; q < n_qpoints; ++q) {\n        const double f = fe_values.shape_value(ix, q);\n        sum += f * f * fe_values.JxW(q);\n      }\n      vvec_t v2(y1 + ig, N);\n      sum *= vcontrib(v2, v2);\n      norm += sum;\n    }\n\n    cell_wise_error[cell->index()] = cell_error / area;\n    global_error += cell_error;\n  }\n  return std::array<double, 2>({global_error, norm});\n}\n\ntemplate <typename DH, typename VECTOR>\ndouble\nl2norm(const DH& dh, const VECTOR& vec)\n{\n  assert(dh.n_dofs() == vec.size());\n  dealii::QGauss<2> quad(2);\n\n  const dealii::UpdateFlags update_flags =\n      (dealii::update_values | dealii::update_JxW_values | dealii::update_quadrature_points);\n  auto& fe = dh.get_fe();\n  dealii::FEValues<2> fe_values(fe, quad, update_flags);\n  int dofs_per_cell = fe_values.dofs_per_cell;\n  int n_qpoints = quad.size();\n\n  double sum = 0;\n  std::vector<unsigned int> local_indices(dofs_per_cell);\n\n  for (auto cell : dh.active_cell_iterators()) {\n    double cell_error = 0;\n    cell->get_dof_indices(local_indices);\n    fe_values.reinit(cell);\n\n    for (int ix1 = 0; ix1 < dofs_per_cell; ++ix1) {\n      const double c = vec[local_indices[ix1]];\n      for (int q = 0; q < n_qpoints; ++q) {\n        const double f = c * fe_values.shape_value(ix1, q);\n        sum += f * f * fe_values.JxW(q);\n      }\n    }\n  }\n\n  return sum;\n}\n\n}  // end namespace boltzmann\n\n#endif /* _L2ERRORS_H_ */\n", "meta": {"hexsha": "626c738e5b4f140cf9ee5bad2e31dc46f44e5fa9", "size": 7869, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "applications/convergence_plots/l2errors.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": "applications/convergence_plots/l2errors.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": "applications/convergence_plots/l2errors.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": 28.7189781022, "max_line_length": 100, "alphanum_fraction": 0.6253653577, "num_tokens": 2369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.46496510379285744}}
{"text": "#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <opencv2/core.hpp>\n#include <opencv2/core/eigen.hpp>\n#include <opencv2/core/utility.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#include <opencv2/calib3d/calib3d.hpp>\n#include <g2o/core/robust_kernel_impl.h>\n#include <opencv2/features2d/features2d.hpp>\n#include <opencv2/video/tracking.hpp>\n#include <opencv2/plot.hpp>\n\n#include \"data.hpp\"\n#include \"helper.hpp\"\n#include \"stereo_processor/g2o_edges/scale_edge.hpp\"\n\nclass ScaleOptimizer{\npublic:\n  double optimize(const std::vector<cv::Point2f>& fts, const PointsWithUncertainties& pts, double& scale,\n          const CameraModel& cam1, const cv::Mat& img0, const cv::Mat& img1, int pymd, int max_opt_step);\n\n  double optimize_pymd(const std::vector<cv::Point2f>& fts, const std::vector<Eigen::Vector3d>& pts, const std::vector<double>& uncertainties,\n             double& scale, const cv::Mat& img0, const cv::Mat& img1, double tx, const Eigen::Matrix3d& K1, int max_opt_step);\n};\n", "meta": {"hexsha": "4f39e5ca4175857fe66c86638ddc67d5ad22c65b", "size": 1028, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/stereo_processor/scale_optimizer.hpp", "max_stars_repo_name": "jiawei-mo/dsvo", "max_stars_repo_head_hexsha": "a6d6f3a5377b472550fd3f48308adc701ed5c679", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2018-09-22T16:00:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T15:14:04.000Z", "max_issues_repo_path": "include/stereo_processor/scale_optimizer.hpp", "max_issues_repo_name": "jiawei-mo/dsvo", "max_issues_repo_head_hexsha": "a6d6f3a5377b472550fd3f48308adc701ed5c679", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-12-22T02:12:15.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-28T18:57:12.000Z", "max_forks_repo_path": "include/stereo_processor/scale_optimizer.hpp", "max_forks_repo_name": "jiawei-mo/dsvo", "max_forks_repo_head_hexsha": "a6d6f3a5377b472550fd3f48308adc701ed5c679", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-01-02T02:05:00.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-16T08:00:28.000Z", "avg_line_length": 39.5384615385, "max_line_length": 142, "alphanum_fraction": 0.7461089494, "num_tokens": 283, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.46496510379285744}}
{"text": "/*=========================================================================\n *\n *  Copyright David Doria 2012 daviddoria@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.txt\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS,\n *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *=========================================================================*/\n\n#ifndef FullPatchVarianceDifference_HPP\n#define FullPatchVarianceDifference_HPP\n\n#include <boost/graph/graph_traits.hpp>\n\n// Parent class\n#include \"Visitors/AcceptanceVisitors/AcceptanceVisitorParent.h\"\n\n// Custom\n#include <ITKHelpers/ITKHelpers.h>\n\n// ITK\n#include \"itkImageRegion.h\"\n\n/**\n\n */\ntemplate <typename TGraph, typename TImage>\nstruct FullPatchVarianceDifference : public AcceptanceVisitorParent<TGraph>\n{\n  TImage* Image;\n\n  const unsigned int HalfWidth;\n\n  typedef typename boost::graph_traits<TGraph>::vertex_descriptor VertexDescriptorType;\n\n  FullPatchVarianceDifference(TImage* const image, const unsigned int halfWidth) :\n  Image(image), HalfWidth(halfWidth)\n  {\n\n  }\n\n  bool AcceptMatch(VertexDescriptorType target, VertexDescriptorType source, float& computedEnergy) const override\n  {\n    itk::Index<2> targetPixel = ITKHelpers::CreateIndex(target);\n    itk::ImageRegion<2> targetRegion = ITKHelpers::GetRegionInRadiusAroundPixel(targetPixel, HalfWidth);\n    typename TImage::PixelType targetRegionAverage = ITKHelpers::VarianceInRegion(Image, targetRegion);\n\n    itk::Index<2> sourcePixel = ITKHelpers::CreateIndex(source);\n    itk::ImageRegion<2> sourceRegion = ITKHelpers::GetRegionInRadiusAroundPixel(sourcePixel, HalfWidth);\n    typename TImage::PixelType sourceRegionAverage = ITKHelpers::VarianceInRegion(Image, sourceRegion);\n\n    // Compute the difference\n    computedEnergy = (targetRegionAverage - sourceRegionAverage).GetNorm();\n    std::cout << \"FullPatchVarianceDifference Energy: \" << computedEnergy << std::endl;\n    return true;\n  }\n\n};\n\n#endif\n", "meta": {"hexsha": "57cdd1b4a1b1e400194d70bb44fda2724af3d8ca", "size": 2370, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Visitors/AcceptanceVisitors/FullPatchVarianceDifference.hpp", "max_stars_repo_name": "jingtangliao/ff", "max_stars_repo_head_hexsha": "d308fe62045e241a4822bb855df97ee087420d9b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 39.0, "max_stars_repo_stars_event_min_datetime": "2015-01-01T07:59:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-01T18:11:46.000Z", "max_issues_repo_path": "Visitors/AcceptanceVisitors/FullPatchVarianceDifference.hpp", "max_issues_repo_name": "jingtangliao/ff", "max_issues_repo_head_hexsha": "d308fe62045e241a4822bb855df97ee087420d9b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-24T09:56:15.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-24T14:45:46.000Z", "max_forks_repo_path": "Visitors/AcceptanceVisitors/FullPatchVarianceDifference.hpp", "max_forks_repo_name": "jingtangliao/ff", "max_forks_repo_head_hexsha": "d308fe62045e241a4822bb855df97ee087420d9b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2015-01-11T15:10:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T20:02:10.000Z", "avg_line_length": 33.8571428571, "max_line_length": 114, "alphanum_fraction": 0.7139240506, "num_tokens": 529, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.4649650939328839}}
{"text": "#include <boost/test/unit_test.hpp>\n#include \"inputs/interp_tests.h\"\n#include \"slice4missing.hpp\"\n#include \"utils/algorithms.hpp\"\n#include \"utils/interpolations.h\"\n\nBOOST_AUTO_TEST_CASE(test_knn)\n{\n    std::vector<double> input_data(std::begin(values), std::end(values));\n    auto missing_begin = std::begin(xi_interp);\n    auto missing_end = std::end(xi_interp);\n    BOOST_TEST_REQUIRE(utils::size(expected_nearest_interp) == utils::size(xi_interp));  // make sure input is valid!!\n    std::size_t count = 0u;\n    while (missing_begin != missing_end) {\n        auto expected = expected_nearest_interp[count];\n        auto input = slice_data(input_data, missing_begin, 1u);\n        const auto x_cord = xi_values(missing_begin, 1); \n        auto calc = utils::K_neighborhood(input, x_cord,\n                static_cast<math::fx_list_type::value_type>(*missing_begin));/*, xi, x*/\n        if (!round_cmp(expected, calc, 0.0001)) { \n            std::cout<<\"input is [\";\n            out_range(std::cout, input, \" \");\n            std::cout<<\"] at location [\";\n            out_range(std::cout, x_cord, \" \");\n            std::cout<<\"] \";\n            BOOST_TEST(false, \"- fix value \"<<calc<<\" != expected \"<<expected<<\" index \"<<*missing_begin<<\" for value \"<<input_data[*missing_begin]);\n        }\n        ++missing_begin;\n        ++count;\n    }\n}\n\nBOOST_AUTO_TEST_CASE(test_knn_gaps)\n{\n    // this test is running using the functions that the actual system would use to \n    // extract the data in the format of [value, row number] pair and not just two\n    // arrays - one for data and one for the row numbers\n    auto dataset = from_double_array(std::begin(values), std::end(values), \"rand_name\");\n    auto missing_begin = std::begin(xi_interp);\n    auto missing_end = std::end(xi_interp);\n    BOOST_TEST_REQUIRE(utils::size(expected_nearest_interp) == utils::size(xi_interp));  // make sure input is valid!!\n    std::size_t count = 0u;\n    while (missing_begin != missing_end) {\n        auto expected = expected_nearest_interp[count];\n        auto subset = slice(dataset, missing_begin, 1u);    // the the subset that we need to fix\n        BOOST_TEST_REQUIRE(utils::size(subset) == 2u);        // win size * 2\n        const auto vals = transform_slice(std::begin(subset), std::end(subset));\n        const auto cords = row_nums_transform(std::begin(subset), std::end(subset));\n        BOOST_TEST_REQUIRE(vals.size() == cords.size());\n        BOOST_TEST_REQUIRE(vals.size() == subset.size());\n        auto calc = utils::K_neighborhood(vals, cords,\n                static_cast<math::fx_list_type::value_type>(*missing_begin));/*, xi, x*/\n        if (!round_cmp(expected, calc, 0.0001)) { \n            std::cout<<\"input is [\";\n            out_range(std::cout, subset, \" \");\n            std::cout<<\"] at location [\";\n            out_range(std::cout, cords, \" \");\n            std::cout<<\"] \";\n            BOOST_TEST(false, \"- fix value \"<<calc<<\" != expected \"<<expected<<\" index \"<<*missing_begin<<\" for value \"<<values[*missing_begin]);\n        }\n        ++missing_begin;\n        ++count;\n    }\n}\n", "meta": {"hexsha": "2c2ce9166cd46b2cbf3b6b27db9682ffd6b6f121", "size": 3090, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/libs/utils/ut/test_knn.cpp", "max_stars_repo_name": "boazsade/machine_learinig_models", "max_stars_repo_head_hexsha": "eb1f9eda0e4e25a6d028b25682dfb20628a20624", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/libs/utils/ut/test_knn.cpp", "max_issues_repo_name": "boazsade/machine_learinig_models", "max_issues_repo_head_hexsha": "eb1f9eda0e4e25a6d028b25682dfb20628a20624", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libs/utils/ut/test_knn.cpp", "max_forks_repo_name": "boazsade/machine_learinig_models", "max_forks_repo_head_hexsha": "eb1f9eda0e4e25a6d028b25682dfb20628a20624", "max_forks_repo_licenses": ["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.5384615385, "max_line_length": 149, "alphanum_fraction": 0.6223300971, "num_tokens": 745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.6442250996557035, "lm_q1q2_score": 0.464965089002897}}
{"text": "/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\\n|  Phycas: Python software for phylogenetic analysis                          |\n|  Copyright (C) 2006 Mark T. Holder, Paul O. Lewis and David L. Swofford     |\n|                                                                             |\n|  This program is free software; you can redistribute it and/or modify       |\n|  it under the terms of the GNU General Public License as published by       |\n|  the Free Software Foundation; either version 2 of the License, or          |\n|  (at your option) any later version.                                        |\n|                                                                             |\n|  This program is distributed in the hope that it will be useful,            |\n|  but WITHOUT ANY WARRANTY; without even the implied warranty of             |\n|  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the              |\n|  GNU General Public License for more details.                               |\n|                                                                             |\n|  You should have received a copy of the GNU General Public License along    |\n|  with this program; if not, write to the Free Software Foundation, Inc.,    |\n|  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.                |\n\\~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n\n#if ! defined(BASIC_LOT_HPP)\n#define BASIC_LOT_HPP\n\n#include <cmath>\n#include <ctime>\n#include <boost/shared_ptr.hpp>\n\nnamespace phycas\n{\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tThis class was called Lot because the noun lot is defined as \"an object used in deciding something by chance\"\n|\taccording to The New Merriam-Webster Dictionary.\n*/\nclass Lot\n\t{\n\tpublic:\n\t\t\t\t\t\t\t\tLot();\n\t\t\t\t\t\t\t\tLot(unsigned);\n\t\t\t\t\t\t\t\t~Lot();\n\n\t\t// Accessors\n\t\tunsigned\t\t\t\tGetSeed() const;\n\t\tunsigned \t\t\t\tGetInitSeed() const;\n\n\t\t// Modifiers\n\t\tvoid \t\t\t\t\tUseClockToSeed();\n\t\tvoid \t\t\t\t\tSetSeed(unsigned s);\n\n\t\t// Utilities\n        unsigned                MultinomialDraw(const double * probs, unsigned n, double totalProb=1.0);\n\t\tunsigned \t\t\t\tSampleUInt(unsigned);\n\t\tunsigned\t\t\t\tGetRandBits(unsigned nbits);\n\n\t\tdouble \t\t\t\t\tUniform();\n\t\tdouble \t\t\t\t\tNormal();\n\t\tbool\t\t\t\t\tBoolean();\n\n\tprivate:\n\n\t\tunsigned \t\t\t\tlast_seed_setting;\n\t\tunsigned\t\t\t\tcurr_seed;\n\t};\n\ntypedef boost::shared_ptr<Lot> LotShPtr;\n\ninline bool Lot::Boolean()\n\t{\n\treturn (Uniform() < 0.5);\n\t}\n\ninline double Lot::Normal()\n\t{\n    double u = Uniform();\n    double x = sqrt(-2.0*log(u));\n    double v = Uniform();\n    double y = cos(2.0*3.141592653589793238846*v);\n\treturn x*y;\n\t}\n\n} // namespace phycas\n\n#endif\n\n", "meta": {"hexsha": "e22cbd6c605e06532af43dbbde37760a540e4ad3", "size": 2773, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/cpp/basic_lot.hpp", "max_stars_repo_name": "plewis/phycas", "max_stars_repo_head_hexsha": "9f5a4d9b2342dab907d14a46eb91f92ad80a5605", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-09-24T23:12:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-12T07:07:01.000Z", "max_issues_repo_path": "src/cpp/basic_lot.hpp", "max_issues_repo_name": "plewis/phycas", "max_issues_repo_head_hexsha": "9f5a4d9b2342dab907d14a46eb91f92ad80a5605", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cpp/basic_lot.hpp", "max_forks_repo_name": "plewis/phycas", "max_forks_repo_head_hexsha": "9f5a4d9b2342dab907d14a46eb91f92ad80a5605", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-11-23T10:35:43.000Z", "max_forks_repo_forks_event_max_datetime": "2015-11-23T10:35:43.000Z", "avg_line_length": 33.0119047619, "max_line_length": 120, "alphanum_fraction": 0.5109989181, "num_tokens": 570, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217431943271999, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.46496508622125293}}
{"text": "// boost1.67-1.67.0/libs/random/example/password.cpp\n\n// password.cpp\n//\n// Copyright (c) 2010\n// Steven Watanabe\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n//[password\n/*`\n    For the source of this example see\n    [@boost://libs/random/example/password.cpp password.cpp].\n\n    This example demonstrates generating a random 8 character\n    password.\n */\n\n\n#include <boost/random/random_device.hpp>\n#include <boost/random/uniform_int_distribution.hpp>\n#include <iostream>\n\nint main() {\n    /*<< We first define the characters that we're going\n         to allow.  This is pretty much just the characters\n         on a standard keyboard.\n    >>*/\n    std::string chars(\n        \"abcdefghijklmnopqrstuvwxyz\"\n        \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n        \"1234567890\"\n        \"!@#$%^&*()\"\n        \"`~-_=+[{]}\\\\|;:'\\\",<.>/? \");\n    /*<< We use __random_device as a source of entropy, since we want\n         passwords that are not predictable.\n    >>*/\n    boost::random::random_device rng;\n    /*<< Finally we select 8 random characters from the\n         string and print them to cout.\n    >>*/\n    boost::random::uniform_int_distribution<> index_dist(0, chars.size() - 1);\n    for(int i = 0; i < 8; ++i) {\n        std::cout << chars[index_dist(rng)];\n    }\n    std::cout << std::endl;\n}\n\n//]\n", "meta": {"hexsha": "17ba77fe3d85e4c135ab819a660ed1971521ce52", "size": 1404, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "debian/tests/srcs/random/demo1.cpp", "max_stars_repo_name": "lliurex/boost1.67", "max_stars_repo_head_hexsha": "bab6eba0e7ac4a0232bc0bcab501f1b447ddfdd5", "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": "debian/tests/srcs/random/demo1.cpp", "max_issues_repo_name": "lliurex/boost1.67", "max_issues_repo_head_hexsha": "bab6eba0e7ac4a0232bc0bcab501f1b447ddfdd5", "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": "debian/tests/srcs/random/demo1.cpp", "max_forks_repo_name": "lliurex/boost1.67", "max_forks_repo_head_hexsha": "bab6eba0e7ac4a0232bc0bcab501f1b447ddfdd5", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0, "max_line_length": 78, "alphanum_fraction": 0.6310541311, "num_tokens": 352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.4649650840729102}}
{"text": "#include <vector>\n#include <iostream>\n#include <complex>\n#include <boost/multi_array.hpp>\n#include \"../common/utilities.hpp\"\n#include \"../common/configuration.hpp\"\n#include \"../common/results.hpp\"\n#include \"../common/symplectic.hpp\"\n#include \"../common/loop_control.hpp\"\n#include \"DNLS.hpp\"\n\nusing namespace std;\n\n/*\n * The Yoshida 6th order symplectic algorithm, implemented as per arXiv:1012.3242 . It is suggested in the paper\n * that the linear operator evolution can be performed as a FFT, and here we implement it so.\n *\n * Contrary to DNKG_FPUT_Toda or dDNKG, each symplectic step is broken into a number of FFTs, hence different kernel\n * invocations. This makes the algorithm much slower than the others implemented. This is mitigated by the use of\n * cuFFT callbacks, in order to coalesce the linear/nonlinear evolutions in the load callback of the FFTs. In my\n * experience cuFFT callbacks can be of great benefit, but also in some cases (depending on architecture, clocks,\n * number of GPUs used, etc.) they can degrade performance. By default, they are used for both linear and nonlinear\n * evolutions, but the user can disable one or both with the switches --no_linear_callback and --no_nonlinear_callback.\n */\nnamespace DNLS {\n\n\tint main(int argc, char *argv[]) {\n\n\t\tdouble beta;\n\t\tbool no_linear_callback, no_nonlinear_callback;\n\t\t{\n\t\t\tusing namespace boost::program_options;\n\t\t\tparse_cmdline parser(\"Options for \"s + argv[0]);\n\t\t\tparser.options.add_options()\n\t\t\t\t\t(\"no_linear_callback\", \"do not use cuFFT callback for linear evolution\")\n\t\t\t\t\t(\"no_nonlinear_callback\", \"do not use cuFFT callback for nonlinear evolution\")\n\t\t\t\t\t(\"beta\", value(&beta)->required(), \"fourth order nonlinearity\");\n\t\t\tparser.run(argc, argv);\n\t\t\tno_linear_callback = parser.vm.count(\"no_linear_callback\");\n\t\t\tno_nonlinear_callback = parser.vm.count(\"no_nonlinear_callback\");\n\t\t}\n\t\tauto ctx = cuda_ctx.activate(mpi_node_coord);\n\n\t\tauto omega_host = dispersion();\n\t\tcudalist<double> omega(gconf.chain_length);\n\t\tcudaMemcpy(omega, omega_host.data(), gconf.chain_length * sizeof(double), cudaMemcpyHostToDevice) && assertcu;\n\n\t\tcudalist<cufftDoubleComplex> psis_k(gconf.shard_elements);\n\t\tresults res(true);\n\n\t\tenum {\n\t\t\ts_move = 0, s_cb_linear, s_cb_nonlinear, s_dump, s_linenergies, s_results, s_total\n\t\t};\n\t\tcudaStream_t streams[s_total];\n\t\tmemset(streams, 0, sizeof(streams));\n\t\tdestructor([&] { for (auto stream : streams) cudaStreamDestroy(stream); });\n\t\tfor (auto &stream : streams) cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking) && assertcu;\n\n\t\t/*\n\t\t * Precompute the evolution factors in Fourier space (linear operator), including FFT normalization, for all\n\t\t * the symplectic integration steps.\n\t\t */\n\t\tcudalist<cufftDoubleComplex> evolve_linear_tables_all(7 * gconf.chain_length);\n\t\tcudaMemcpy(evolve_linear_tables_all, evolve_linear_table().origin(),\n\t\t           7 * gconf.chain_length * sizeof(cufftDoubleComplex), cudaMemcpyHostToDevice) && assertcu;\n\n\t\t/*\n\t\t * Three FFT plans are required because of the nonlinear/linear evolution callbacks. The plain fft plan is used\n\t\t * to make the linear energies, and in case that the user disabled callbacks.\n\t\t * The settings for the callbacks (the symplectic time step, or the linear evolution table) are put on global\n\t\t * variables asynchronously with additional streams.\n\t\t */\n\t\tcufftHandle fft_plain = 0, fft_plain_entropy = 0, fft_elvolve_psik = 0, fft_elvolve_psi = 0;\n\t\tdestructor([&] {\n\t\t\tcufftDestroy(fft_plain);\n\t\t\tcufftDestroy(fft_plain_entropy);\n\t\t\tcufftDestroy(fft_elvolve_psik);\n\t\t\tcufftDestroy(fft_elvolve_psi);\n\t\t});\n\n\t\tcudalist<double, true> beta_dt_symplectic_all;\n\t\tauto beta_dt_symplectic_ptr = get_device_address(callback::beta_dt_symplectic);\n\t\tcudalist<void> area;\n\t\t{\n\t\t\tauto init_plan = [&](cufftHandle &fft) {\n\t\t\t\tsize_t dummy;\n\t\t\t\tcufftCreate(&fft) && assertcufft;\n\t\t\t\tcufftSetAutoAllocation(fft, false) && assertcufft;\n\t\t\t\tcufftMakePlan1d(fft, gconf.chain_length, CUFFT_Z2Z, gconf.shard_copies, &dummy) && assertcufft;\n\t\t\t\tcufftSetStream(fft, streams[s_move]) && assertcufft;\n\t\t\t};\n\t\t\tsize_t maxsize = 0;\n\t\t\tauto update_max_size = [&](cufftHandle fft) {   //use only one work area\n\t\t\t\tsize_t size;\n\t\t\t\tcufftGetSize(fft, &size) && assertcufft;\n\t\t\t\tmaxsize = max(maxsize, size);\n\t\t\t};\n\t\t\tinit_plan(fft_plain);\n\t\t\tupdate_max_size(fft_plain);\n\t\t\tinit_plan(fft_plain_entropy);\n\t\t\tcufftSetStream(fft_plain_entropy, streams[s_linenergies]) && assertcufft;\n\t\t\tupdate_max_size(fft_plain_entropy);\n\t\t\tif (!no_linear_callback) {\n\t\t\t\tinit_plan(fft_elvolve_psik);\n\t\t\t\tauto evolve_linear_ptr_host = get_device_object(callback::evolve_linear_ptr);\n\t\t\t\tauto evolve_linear_tables_all_ptr = *evolve_linear_tables_all;\n\t\t\t\tcufftXtSetCallback(fft_elvolve_psik, (void **) &evolve_linear_ptr_host, CUFFT_CB_LD_COMPLEX_DOUBLE,\n\t\t\t\t                   (void **) &evolve_linear_tables_all_ptr) && assertcufft;\n\t\t\t\tset_device_object(gconf.chain_length, callback::chainlen);\n\t\t\t\tupdate_max_size(fft_elvolve_psik);\n\t\t\t}\n\t\t\tif (!no_nonlinear_callback) {\n\t\t\t\tinit_plan(fft_elvolve_psi);\n\t\t\t\tauto evolve_nonlinear_ptr_host = get_device_object(callback::evolve_nonlinear_ptr);\n\t\t\t\tcufftXtSetCallback(fft_elvolve_psi, (void **) &evolve_nonlinear_ptr_host, CUFFT_CB_LD_COMPLEX_DOUBLE,\n\t\t\t\t                   0) && assertcufft;\n\t\t\t\tbeta_dt_symplectic_all = cudalist<double, true>(8, true);\n\t\t\t\tloopk(8) beta_dt_symplectic_all[k] = beta * gconf.dt * (k == 7 ? 2. : 1.) * symplectic_c[k];\n\t\t\t\tupdate_max_size(fft_elvolve_psi);\n\t\t\t}\n\t\t\tarea = maxsize;\n\t\t\tcufftSetWorkArea(fft_plain, area) && assertcufft;\n\t\t\tcufftSetWorkArea(fft_plain_entropy, area) && assertcufft;\n\t\t\tif (!no_linear_callback) cufftSetWorkArea(fft_elvolve_psik, area) && assertcufft;\n\t\t\tif (!no_nonlinear_callback) cufftSetWorkArea(fft_elvolve_psi, area) && assertcufft;\n\t\t}\n\n\t\tloop_control_gpu loop_ctl(streams[s_move]);\n\t\tauto dumper = [&] {\n\t\t\tcudaMemcpyAsync(gres.shard_host, gres.shard_gpu, gconf.sizeof_shard, cudaMemcpyDeviceToHost, streams[s_dump]) &&\n\t\t\tassertcu;\n\t\t\tcompletion done_copy(streams[s_dump]);\n\t\t\tdone_copy.blocks(streams[s_move]);\n\t\t\tdone_copy.blocks(streams[s_results]);\n\t\t};\n\n\t\tcudaDeviceSynchronize() && assertcu;\n\t\tdestructor(cudaDeviceSynchronize);\n\t\twhile (1) {\n\t\t\tbool full_dump = loop_ctl % gconf.dump_interval == 0;\n\t\t\tif (full_dump) dumper();\n\t\t\tcufftExecZ2Z(fft_plain_entropy, gres.shard_gpu, psis_k, CUFFT_FORWARD) && assertcufft;\n\t\t\tcompletion(streams[s_linenergies]).blocks(streams[s_move]);\n\t\t\tmake_linenergies(psis_k, omega, streams[s_linenergies]);\n\t\t\tcompletion(streams[s_linenergies]).blocks(streams[s_results]);\n\t\t\tadd_cuda_callback(streams[s_results], loop_ctl.callback_err,\n\t\t\t                  [&, full_dump, t = *loop_ctl](cudaError_t status) {\n\t\t\t\t                  if (loop_ctl.callback_err) return;\n\t\t\t\t                  status && assertcu;\n\t\t\t\t                  res.calc_linenergies(1. / gconf.shard_elements).calc_entropies().check_entropy().write_entropy(t);\n\t\t\t\t                  if (full_dump) res.write_linenergies(t).write_shard(t);\n\t\t\t                  });\n\t\t\tcompletion done_results(streams[s_results]);\n\t\t\tdone_results.blocks(streams[s_dump]);\n\t\t\tdone_results.blocks(streams[s_linenergies]);\n\n\t\t\tif (loop_ctl.break_now()) break;\n\n\t\t\tfor (uint32_t i = 0; i < gconf.kernel_batching; i++)\n\t\t\t\tfor (int k = 0; k < 7; k++) {\n\t\t\t\t\tif (fft_elvolve_psi) {\n\t\t\t\t\t\tcudaMemcpyAsync(beta_dt_symplectic_ptr, &beta_dt_symplectic_all[!k && i ? 7 : k],\n\t\t\t\t\t\t                sizeof(double), cudaMemcpyHostToDevice, streams[s_cb_nonlinear]);\n\t\t\t\t\t\tcompletion(streams[s_cb_nonlinear]).blocks(streams[s_move]);\n\t\t\t\t\t} else evolve_nonlinear(beta * gconf.dt * (!k && i ? 2. : 1.) * symplectic_c[k], streams[s_move]);\n\t\t\t\t\tcufftExecZ2Z(fft_elvolve_psi ?: fft_plain, gres.shard_gpu, gres.shard_gpu, CUFFT_FORWARD) && assertcufft;\n\t\t\t\t\tcompletion(streams[s_move]).blocks(streams[s_cb_nonlinear]);\n\t\t\t\t\tif (fft_elvolve_psik) {\n\t\t\t\t\t\tmemset_device_object(callback::evolve_linear_table_idx, k, streams[s_cb_linear]);\n\t\t\t\t\t\tcompletion(streams[s_cb_linear]).blocks(streams[s_move]);\n\t\t\t\t\t} else evolve_linear(&evolve_linear_tables_all[k * gconf.chain_length], streams[s_move]);\n\t\t\t\t\tcufftExecZ2Z(fft_elvolve_psik ?: fft_plain, gres.shard_gpu, gres.shard_gpu, CUFFT_INVERSE) && assertcufft;\n\t\t\t\t\tcompletion(streams[s_move]).blocks(streams[s_cb_linear]);\n\t\t\t\t}\n\t\t\tcompletion finish_move = evolve_nonlinear(beta * gconf.dt * symplectic_c[7], streams[s_move]);\n\t\t\tfinish_move.blocks(streams[s_linenergies]);\n\t\t\tfinish_move.blocks(streams[s_dump]);\n\n\t\t\tloop_ctl += gconf.kernel_batching;\n\t\t}\n\n\t\tif (loop_ctl % gconf.dump_interval != 0) {\n\t\t\tdumper();\n\t\t\tcompletion(streams[s_linenergies]).wait();\n\t\t\tres.write_linenergies(loop_ctl);\n\t\t\tcompletion(streams[s_dump]).wait();\n\t\t\tres.write_shard(loop_ctl);\n\t\t}\n\t\treturn 0;\n\t}\n}\n\nginit = [] {\n\t::programs()[\"DNLS\"] = DNLS::main;\n};\n", "meta": {"hexsha": "7e66cfb89b2dcc27aa53905cd4c597691aba2936", "size": 8815, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "DNLS/DNLS.cpp", "max_stars_repo_name": "pisto/nlchains", "max_stars_repo_head_hexsha": "6e94b7a1dcacdd6fccb2b9e862bc648c1b263286", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-06-25T01:09:19.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-25T01:09:19.000Z", "max_issues_repo_path": "DNLS/DNLS.cpp", "max_issues_repo_name": "pisto/nlchains", "max_issues_repo_head_hexsha": "6e94b7a1dcacdd6fccb2b9e862bc648c1b263286", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DNLS/DNLS.cpp", "max_forks_repo_name": "pisto/nlchains", "max_forks_repo_head_hexsha": "6e94b7a1dcacdd6fccb2b9e862bc648c1b263286", "max_forks_repo_licenses": ["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.9744897959, "max_line_length": 120, "alphanum_fraction": 0.7241066364, "num_tokens": 2405, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257653, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4649542548521185}}
{"text": "// Copyright (c) 2020 CNES\n//\n// All rights reserved. Use of this source code is governed by a\n// BSD-style license that can be found in the LICENSE file.\n#pragma once\n#include <Eigen/Core>\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/weighted_kurtosis.hpp>\n#include <boost/accumulators/statistics/weighted_mean.hpp>\n#include <boost/accumulators/statistics/weighted_median.hpp>\n#include <boost/accumulators/statistics/weighted_skewness.hpp>\n#include <boost/accumulators/statistics/weighted_sum.hpp>\n#include <boost/accumulators/statistics/weighted_variance.hpp>\n#include <boost/geometry.hpp>\n#include <optional>\n#include <pybind11/numpy.h>\n#include \"pyinterp/axis.hpp\"\n#include \"pyinterp/detail/broadcast.hpp\"\n#include \"pyinterp/detail/geometry/point.hpp\"\n#include \"pyinterp/detail/math/binning.hpp\"\n#include \"pyinterp/geodetic/system.hpp\"\n\nnamespace pyinterp {\n\n/// Group a number of more or less continuous values into a smaller number of\n/// \"bins\" located on a grid.\ntemplate <typename T>\nclass Binning2D {\n public:\n  /// Default constructor\n  ///\n  /// @param x Definition of the bin edges for the X axis of the grid.\n  /// @param y Definition of the bin edges for the Y axis of the grid.\n  /// @param wgs WGS of the coordinate system used to manipulate geographic\n  /// coordinates. If this parameter is not set, the handled coordinates will be\n  /// considered as Cartesian coordinates. Otherwise, \"x\" and \"y\" are considered\n  /// to represents the longitudes and latitudes on a grid.\n  Binning2D(std::shared_ptr<Axis<double>> x, std::shared_ptr<Axis<double>> y,\n            std::optional<geodetic::System> wgs)\n      : x_(std::move(x)),\n        y_(std::move(y)),\n        acc_(x_->size(), y_->size()),\n        wgs_(std::move(wgs)) {}\n\n  /// Inserts new values in the grid from Z values for X, Y data coordinates.\n  void push(const pybind11::array_t<T>& x, const pybind11::array_t<T>& y,\n            const pybind11::array_t<T>& z, const bool simple) {\n    detail::check_array_ndim(\"x\", 1, x, \"y\", 1, y, \"z\", 1, z);\n    detail::check_ndarray_shape(\"x\", x, \"y\", y, \"z\", z);\n\n    if (simple) {\n      // Nearest\n      push_nearest(x, y, z);\n    } else if (!wgs_) {\n      // Cartesian linear\n      push_linear<detail::geometry::Point2D,\n                  boost::geometry::strategy::area::cartesian<>>(\n          x, y, z, boost::geometry::strategy::area::cartesian<>());\n    } else {\n      // Geographic linear\n      auto strategy = boost::geometry::strategy::area::geographic<>(\n          boost::geometry::srs::spheroid(wgs_->semi_major_axis(),\n                                         wgs_->semi_minor_axis()));\n      push_linear<detail::geometry::SpheriodPoint2D,\n                  boost::geometry::strategy::area::geographic<>>(x, y, z,\n                                                                 strategy);\n    }\n  }\n\n  /// Reset the statistics.\n  void clear() {\n    acc_ =\n        std::move(Eigen::Matrix<Accumulators, Eigen::Dynamic, Eigen::Dynamic>(\n            x_->size(), y_->size()));\n  }\n\n  /// Compute the count of points within each bin.\n  [[nodiscard]] auto count() const -> pybind11::array_t<T> {\n    return calculate_statistics(boost::accumulators::count);\n  }\n\n  /// Compute the minimum of values for points within each bin.\n  [[nodiscard]] auto min() const -> pybind11::array_t<T> {\n    return calculate_statistics(boost::accumulators::min);\n  }\n\n  /// Compute the maximum of values for points within each bin.\n  [[nodiscard]] auto max() const -> pybind11::array_t<T> {\n    return calculate_statistics(boost::accumulators::max);\n  }\n\n  /// Compute the mean of values for points within each bin.\n  [[nodiscard]] auto mean() const -> pybind11::array_t<T> {\n    return calculate_statistics(boost::accumulators::weighted_mean);\n  }\n\n  /// Compute the median of values for points within each bin.\n  [[nodiscard]] auto median() const -> pybind11::array_t<T> {\n    return calculate_statistics(boost::accumulators::weighted_median);\n  }\n\n  /// Compute the variance of values for points within each bin.\n  [[nodiscard]] auto variance() const -> pybind11::array_t<T> {\n    return calculate_statistics(boost::accumulators::weighted_variance);\n  }\n\n  /// Compute the kurtosis of values for points within each bin.\n  [[nodiscard]] auto kurtosis() const -> pybind11::array_t<T> {\n    return calculate_statistics(boost::accumulators::weighted_kurtosis);\n  }\n\n  /// Compute the skewness of values for points within each bin.\n  [[nodiscard]] auto skewness() const -> pybind11::array_t<T> {\n    return calculate_statistics(boost::accumulators::weighted_skewness);\n  }\n\n  /// Compute the sum of values for points within each bin.\n  [[nodiscard]] auto sum() const -> pybind11::array_t<T> {\n    return calculate_statistics(boost::accumulators::weighted_sum);\n  }\n\n  /// Compute the sum of weights within each bin.\n  [[nodiscard]] auto sum_of_weights() const -> pybind11::array_t<T> {\n    return calculate_statistics(boost::accumulators::sum_of_weights);\n  }\n\n  /// Gets the X-Axis\n  [[nodiscard]] inline auto x() const -> std::shared_ptr<Axis<double>> {\n    return x_;\n  }\n\n  /// Gets the Y-Axis\n  [[nodiscard]] inline auto y() const -> std::shared_ptr<Axis<double>> {\n    return y_;\n  }\n\n private:\n  /// Statistics handled by this object.\n  using Accumulators = boost::accumulators::accumulator_set<\n      T,\n      boost::accumulators::stats<\n          boost::accumulators::tag::count, boost::accumulators::tag::max,\n          boost::accumulators::tag::min,\n          boost::accumulators::tag::sum_of_weights,\n          boost::accumulators::tag::weighted_kurtosis,\n          boost::accumulators::tag::weighted_mean,\n          boost::accumulators::tag::weighted_median(\n              boost::accumulators::with_p_square_quantile),\n          boost::accumulators::tag::weighted_skewness,\n          boost::accumulators::tag::weighted_sum,\n          boost::accumulators::tag::weighted_variance(\n              boost::accumulators::lazy)>,\n      T>;\n\n  /// Grid axis\n  std::shared_ptr<Axis<double>> x_;\n  std::shared_ptr<Axis<double>> y_;\n\n  /// Statistics grid\n  Eigen::Matrix<Accumulators, Eigen::Dynamic, Eigen::Dynamic> acc_;\n\n  /// Geodetic coordinate system required to calculate areas (optional if the\n  /// user wishes to handle Cartesian coordinates).\n  std::optional<geodetic::System> wgs_;\n\n  /// Calculation of a given statistical variable.\n  template <typename Func>\n  [[nodiscard]] auto calculate_statistics(const Func& func) const\n      -> pybind11::array_t<T> {\n    pybind11::array_t<T> z({x_->size(), y_->size()});\n    auto _z = z.template mutable_unchecked<2>();\n    {\n      pybind11::gil_scoped_release release;\n\n      for (Eigen::Index ix = 0; ix < acc_.rows(); ++ix) {\n        for (Eigen::Index iy = 0; iy < acc_.cols(); ++iy) {\n          _z(ix, iy) = func(acc_(ix, iy));\n        }\n      }\n    }\n    return z;\n  }\n\n  /// Insertion of data on the nearest bin.\n  void push_nearest(const pybind11::array_t<T>& x,\n                    const pybind11::array_t<T>& y,\n                    const pybind11::array_t<T>& z) {\n    auto _x = x.template unchecked<1>();\n    auto _y = y.template unchecked<1>();\n    auto _z = z.template unchecked<1>();\n\n    {\n      pybind11::gil_scoped_release release;\n\n      const auto& x_axis = static_cast<pyinterp::detail::Axis<double>&>(*x_);\n      const auto& y_axis = static_cast<pyinterp::detail::Axis<double>&>(*y_);\n\n      for (pybind11::ssize_t idx = 0; idx < x.size(); ++idx) {\n        auto value = _z(idx);\n\n        if (!std::isnan(value)) {\n          auto ix = x_axis.find_index(_x(idx), true);\n          auto iy = y_axis.find_index(_y(idx), true);\n\n          if (ix != -1 && iy != -1) {\n            acc_(ix, iy)(value, boost::accumulators::weight = 1);\n          }\n        }\n      }\n    }\n  }\n\n  /// Update statistics for the linear binning (ignore zero weights).\n  void update_acc(const int64_t ix, const int64_t iy, const T& value,\n                  const T& weight) {\n    if (!detail::math::is_almost_zero(weight,\n                                      std::numeric_limits<T>::epsilon())) {\n      acc_(ix, iy)(value, boost::accumulators::weight = weight);\n    }\n  }\n\n  /// Set bins with nearest binning.\n  template <template <class> class Point, typename Strategy>\n  void push_linear(const pybind11::array_t<T>& x, const pybind11::array_t<T>& y,\n                   const pybind11::array_t<T>& z, const Strategy& strategy) {\n    auto _x = x.template unchecked<1>();\n    auto _y = y.template unchecked<1>();\n    auto _z = z.template unchecked<1>();\n\n    {\n      pybind11::gil_scoped_release release;\n\n      const auto& x_axis = static_cast<pyinterp::detail::Axis<double>&>(*x_);\n      const auto& y_axis = static_cast<pyinterp::detail::Axis<double>&>(*y_);\n\n      for (pybind11::ssize_t idx = 0; idx < x.size(); ++idx) {\n        auto value = _z(idx);\n        if (std::isnan(value)) {\n          continue;\n        }\n\n        auto x_indexes = x_axis.find_indexes(_x(idx));\n        auto y_indexes = y_axis.find_indexes(_y(idx));\n\n        if (x_indexes.has_value() && y_indexes.has_value()) {\n          int64_t ix0;\n          int64_t ix1;\n          int64_t iy0;\n          int64_t iy1;\n\n          std::tie(ix0, ix1) = *x_indexes;\n          std::tie(iy0, iy1) = *y_indexes;\n\n          auto x0 = x_axis(ix0);\n\n          auto weights = detail::math::binning_2d<Point, Strategy, double>(\n              Point<double>(x_axis.is_angle()\n                                ? detail::math::normalize_angle<double>(\n                                      _x(idx), x0, 360.0)\n                                : _x(idx),\n                            _y(idx)),\n              Point<double>(x0, y_axis(iy0)),\n              Point<double>(x_axis(ix1), y_axis(iy1)), strategy);\n\n          update_acc(ix0, iy0, value, static_cast<T>(std::get<0>(weights)));\n          update_acc(ix0, iy1, value, static_cast<T>(std::get<1>(weights)));\n          update_acc(ix1, iy1, value, static_cast<T>(std::get<2>(weights)));\n          update_acc(ix1, iy0, value, static_cast<T>(std::get<3>(weights)));\n        }\n      }\n    }\n  }\n};\n\n}  // namespace pyinterp\n", "meta": {"hexsha": "9d6a37187ee724421796c02e10b28e108dd1fa5b", "size": 10158, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/pyinterp/core/include/pyinterp/binning.hpp", "max_stars_repo_name": "Geospatial-Data-Science/pangeo-pyinterp", "max_stars_repo_head_hexsha": "aa36a6fdbc4acea4206ebfd97d60aceffe0d98df", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-02-19T14:54:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-19T14:54:23.000Z", "max_issues_repo_path": "src/pyinterp/core/include/pyinterp/binning.hpp", "max_issues_repo_name": "Geospatial-Data-Science/pangeo-pyinterp", "max_issues_repo_head_hexsha": "aa36a6fdbc4acea4206ebfd97d60aceffe0d98df", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pyinterp/core/include/pyinterp/binning.hpp", "max_forks_repo_name": "Geospatial-Data-Science/pangeo-pyinterp", "max_forks_repo_head_hexsha": "aa36a6fdbc4acea4206ebfd97d60aceffe0d98df", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.6714801444, "max_line_length": 80, "alphanum_fraction": 0.6259106123, "num_tokens": 2562, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4649542495998386}}
{"text": "#include <iostream>\n#include <boost/multiprecision/cpp_int.hpp>\nusing namespace std;\n\nnamespace mp = boost::multiprecision;\n\nint main(int argc, char const* argv[])\n{\n\tmp::cpp_int x = 1;\n\tmp::cpp_int prev = 0;\n\n\twhile(1){\n\t\tcout << prev << endl;\n\t\tmp::cpp_int y = x + prev;\n\t\tprev = x;\n\t\tx = y;\n\t}\n\n\texit(0);\n}\n", "meta": {"hexsha": "b60d9cc8abad2dce75eae548750ab3808117ba27", "size": 310, "ext": "cc", "lang": "C++", "max_stars_repo_path": "fibonacci.cc", "max_stars_repo_name": "ryuichiueda/sequences", "max_stars_repo_head_hexsha": "e64dc60ffe7d3170b74f7cba4048952f425c22a1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fibonacci.cc", "max_issues_repo_name": "ryuichiueda/sequences", "max_issues_repo_head_hexsha": "e64dc60ffe7d3170b74f7cba4048952f425c22a1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fibonacci.cc", "max_forks_repo_name": "ryuichiueda/sequences", "max_forks_repo_head_hexsha": "e64dc60ffe7d3170b74f7cba4048952f425c22a1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.7619047619, "max_line_length": 43, "alphanum_fraction": 0.6290322581, "num_tokens": 94, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8104788995148792, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4649542443475585}}
{"text": "#include <Eigen/LU>\n#include <numeric>\n#include \"EKF.h\"\n\nusing namespace Eigen;\n\nstatic double clamp(double f, double fs) {\n    if (f > fs / 2) {\n        f = fs / 2 - (f - fs / 2);\n    }\n    return std::clamp(abs(f), 60.0, fs / 2 - 60.0);\n}\n\nvoid EKF::step(EKF::State & state)\n{\n    static MatrixXd P_pred, H, S, K;\n    static VectorXd m_pred, y_pred, y_obs;\n\n    const bool voiced = state.voiced;\n    const int numF = state.numF;\n    const int cepOrder = state.cepOrder;\n    const double fs = state.fs;\n    auto& y = state.y;\n    auto& F = state.F;\n    auto Ft = state.F.transpose();\n    auto& Q = state.Q;\n    auto& R = state.R;\n\n    m_pred = F * state.m_up;\n    P_pred = F * state.P_up * Ft + Q;\n\n    for (int i = 0; i < 2 * numF; ++i) {\n        if (m_pred(i) > fs / 2) {\n            m_pred(i) = fs / 2 - (m_pred(i) - fs / 2);\n        }\n    }\n\n    auto curFVals = m_pred.head(numF);\n    auto curBVals = m_pred.tail(numF);\n\n    // Linearize about m_pred using Taylor expansion.\n    H = EKF::getH_FBW(curFVals, curBVals, numF, cepOrder, fs);\n    auto Ht = H.transpose();\n\n    if (/*voiced*/true) {\n        S = H * P_pred * Ht + R;\n        K = (P_pred * Ht) * S.inverse();\n    }\n    else {\n        K.setZero(2 * numF, cepOrder);\n    }\n\n    y_pred = fb2cp(curFVals, curBVals, cepOrder, fs);\n\n    y_obs.setZero(cepOrder);\n    if (y.size() < cepOrder) {\n        y_obs.head(y.size()) = y;\n    }\n    else {\n        y_obs = y.head(cepOrder);\n    }\n\n    state.m_up = m_pred + K * (y_obs - y_pred);\n    state.P_up = P_pred - K * H * P_pred;\n\n    // Sort the formants by absolute frequency.\n    \n    std::vector<int> inds(numF);\n    std::iota(inds.begin(), inds.end(), 0);\n    std::sort(inds.begin(), inds.end(),\n            [&](int i, int j) {\n                return clamp(state.m_up(i), fs) < clamp(state.m_up(j), fs);\n            });\n\n    VectorXd m_ = state.m_up;\n    MatrixXd P_ = state.P_up;\n\n    for (int k = 0; k < numF; ++k) {\n        m_(k) = clamp(state.m_up(inds[k]), fs);\n        m_(numF + k) = clamp(state.m_up(numF + inds[k]), fs);\n\n        P_.row(k) = state.P_up.col(inds[k]);\n        P_.row(numF + k) = state.P_up.col(numF + inds[k]);\n    }\n\n    state.m_up = std::move(m_);\n    state.P_up = std::move(P_);\n\n}\n", "meta": {"hexsha": "b44f4ded9da30a6ee45506d216fd0eea6b45fbe9", "size": 2216, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/Formant/EKF/step.cpp", "max_stars_repo_name": "Transfusion/speech-analysis", "max_stars_repo_head_hexsha": "603b88163051b788a0ecd795caaef0a711f23432", "max_stars_repo_licenses": ["MIT"], "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/Formant/EKF/step.cpp", "max_issues_repo_name": "Transfusion/speech-analysis", "max_issues_repo_head_hexsha": "603b88163051b788a0ecd795caaef0a711f23432", "max_issues_repo_licenses": ["MIT"], "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/Formant/EKF/step.cpp", "max_forks_repo_name": "Transfusion/speech-analysis", "max_forks_repo_head_hexsha": "603b88163051b788a0ecd795caaef0a711f23432", "max_forks_repo_licenses": ["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.6222222222, "max_line_length": 75, "alphanum_fraction": 0.52933213, "num_tokens": 720, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788995148791, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4649542443475584}}
{"text": "#include <cstdlib>\n#include <iostream>\n#include <complex>\n#define BOOST_UBLAS_NO_ELEMENT_PROXIES\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/triangular.hpp>\n#include <boost/numeric/bindings/ublas/vector.hpp>\n#include <boost/numeric/bindings/ublas/triangular.hpp>\n#include <boost/numeric/bindings/blas/level2.hpp>\n#include <boost/numeric/bindings/lower.hpp>\n#include <boost/numeric/bindings/upper.hpp>\n#include <boost/numeric/bindings/unit_lower.hpp>\n#include <boost/numeric/bindings/unit_upper.hpp>\n#include <boost/numeric/bindings/trans.hpp>\n#include <boost/numeric/bindings/conj.hpp>\n#include \"print.hpp\"\n#include \"random.hpp\"\n\nnamespace ublas=boost::numeric::ublas;\nnamespace blas=boost::numeric::bindings::blas;\n\nint main(int argc, char *argv[]) {\n  {\n    typedef std::complex<double> complex;\n    typedef ublas::vector<complex> vector;\n    typedef ublas::triangular_matrix<complex, ublas::lower, ublas::column_major> matrix_l;\n    typedef ublas::triangular_matrix<complex, ublas::upper, ublas::column_major> matrix_u;\n    typedef typename vector::size_type size_type;\n    rand_normal<complex>::reset();\n    size_type n=8;\n    matrix_l A_l(n, n);\n    matrix_u A_u(n, n);\n    for (size_type j=0; j<n; ++j) {\n      A_u(j, j)=rand_normal<complex>::get();\n      A_l(j, j)=rand_normal<complex>::get();\n      for (size_type i=0; i<j; ++i) {\n        A_u(i, j)=rand_normal<complex>::get();\n        A_l(j, i)=rand_normal<complex>::get();\n       }\n    }\n    vector x(n);\n    for (size_type i=0; i<n; ++i)\n      x(i)=rand_normal<complex>::get();\n    {\n      vector x1(ublas::prod(A_l, x));\n      vector x2(x);\n      blas::tpmv(A_l, x2);\n      std::cout << \"testing boost::ublas containers\\n\"\n    \t\t<< \"using ublas (lower): \" << print_vec(x1) << '\\n'\n    \t\t<< \"using blas  (lower): \" << print_vec(x2) << '\\n'\n    \t\t<< '\\n';\n    }\n    {\n      vector x1(ublas::prod(A_u, x));\n      vector x2(x);\n      blas::tpmv(A_u, x2);\n      std::cout << \"testing boost::ublas containers\\n\"\n    \t\t<< \"using ublas (upper): \" << print_vec(x1) << '\\n'\n    \t\t<< \"using blas  (upper): \" << print_vec(x2) << '\\n'\n    \t\t<< '\\n';\n    }\n    {\n      vector x1(ublas::prod(ublas::trans(A_l), x));\n      vector x2(x);\n      blas::tpmv(blas::trans(blas::lower(A_l)), x2);\n      std::cout << \"testing boost::ublas containers\\n\"\n    \t\t<< \"using ublas (trans, lower): \" << print_vec(x1) << '\\n'\n    \t\t<< \"using blas  (trans, lower): \" << print_vec(x2) << '\\n'\n    \t\t<< '\\n';\n    }\n    {\n      vector x1(ublas::prod(ublas::trans(A_u), x));\n      vector x2(x);\n      blas::tpmv(blas::trans(blas::upper(A_u)), x2);\n      std::cout << \"testing boost::ublas containers\\n\"\n    \t\t<< \"using ublas (trans, upper): \" << print_vec(x1) << '\\n'\n    \t\t<< \"using blas  (trans, upper): \" << print_vec(x2) << '\\n'\n    \t\t<< '\\n';\n    }\n    {\n      vector x1(ublas::prod(ublas::herm(A_l), x));\n      vector x2(x);\n      blas::tpmv(blas::conj(blas::lower(A_l)), x2);\n      std::cout << \"testing boost::ublas containers\\n\"\n    \t\t<< \"using ublas (htrans, lower): \" << print_vec(x1) << '\\n'\n    \t\t<< \"using blas  (htrans, lower): \" << print_vec(x2) << '\\n'\n    \t\t<< '\\n';\n    }\n    {\n      vector x1(ublas::prod(ublas::herm(A_u), x));\n      vector x2(x);\n      blas::tpmv(blas::conj(blas::upper(A_u)), x2);\n      std::cout << \"testing boost::ublas containers\\n\"\n    \t\t<< \"using ublas (htrans, upper): \" << print_vec(x1) << '\\n'\n    \t\t<< \"using blas  (htrans, upper): \" << print_vec(x2) << '\\n'\n    \t\t<< '\\n';\n    }\n\n    for (size_type i=0; i<n; ++i) {\n      A_l(i, i)=1;\n      A_u(i, i)=1;\n    }\n\n    {\n      vector x1(ublas::prod(A_l, x));\n      vector x2(x);\n      blas::tpmv(blas::unit_lower(A_l), x2);\n      std::cout << \"testing boost::ublas containers\\n\"\n    \t\t<< \"using ublas (unit_lower): \" << print_vec(x1) << '\\n'\n    \t\t<< \"using blas  (unit_lower): \" << print_vec(x2) << '\\n'\n    \t\t<< '\\n';\n    }\n    {\n      vector x1(ublas::prod(A_u, x));\n      vector x2(x);\n      blas::tpmv(blas::unit_upper(A_u), x2);\n      std::cout << \"testing boost::ublas containers\\n\"\n    \t\t<< \"using ublas (unit_upper): \" << print_vec(x1) << '\\n'\n    \t\t<< \"using blas  (unit_upper): \" << print_vec(x2) << '\\n'\n    \t\t<< '\\n';\n    }\n    {\n      vector x1(ublas::prod(ublas::trans(A_l), x));\n      vector x2(x);\n      blas::tpmv(blas::trans(blas::unit_lower(A_l)), x2);\n      std::cout << \"testing boost::ublas containers\\n\"\n    \t\t<< \"using ublas (trans, unit_lower): \" << print_vec(x1) << '\\n'\n    \t\t<< \"using blas  (trans, unit_lower): \" << print_vec(x2) << '\\n'\n    \t\t<< '\\n';\n    }\n    {\n      vector x1(ublas::prod(ublas::trans(A_u), x));\n      vector x2(x);\n      blas::tpmv(blas::trans(blas::unit_upper(A_u)), x2);\n      std::cout << \"testing boost::ublas containers\\n\"\n    \t\t<< \"using ublas (trans, unit_upper): \" << print_vec(x1) << '\\n'\n    \t\t<< \"using blas  (trans, unit_upper): \" << print_vec(x2) << '\\n'\n    \t\t<< '\\n';\n    }\n    {\n      vector x1(ublas::prod(ublas::herm(A_l), x));\n      vector x2(x);\n      blas::tpmv(blas::conj(blas::unit_lower(A_l)), x2);\n      std::cout << \"testing boost::ublas containers\\n\"\n    \t\t<< \"using ublas (htrans, unit_lower): \" << print_vec(x1) << '\\n'\n    \t\t<< \"using blas  (htrans, unit_lower): \" << print_vec(x2) << '\\n'\n    \t\t<< '\\n';\n    }\n    {\n      vector x1(ublas::prod(ublas::herm(A_u), x));\n      vector x2(x);\n      blas::tpmv(blas::conj(blas::unit_upper(A_u)), x2);\n      std::cout << \"testing boost::ublas containers\\n\"\n    \t\t<< \"using ublas (htrans, unit_upper): \" << print_vec(x1) << '\\n'\n    \t\t<< \"using blas  (htrans, unit_upper): \" << print_vec(x2) << '\\n'\n    \t\t<< '\\n';\n    }\n  }\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "3ba5ebf47026d022f0d21a20e169c95ff9a39ebb", "size": 5622, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/blas/tpmv.cc", "max_stars_repo_name": "rabauke/numeric_bindings", "max_stars_repo_head_hexsha": "f4de93bd7a01a8b31c9367fad35c81d086768f99", "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/blas/tpmv.cc", "max_issues_repo_name": "rabauke/numeric_bindings", "max_issues_repo_head_hexsha": "f4de93bd7a01a8b31c9367fad35c81d086768f99", "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/blas/tpmv.cc", "max_forks_repo_name": "rabauke/numeric_bindings", "max_forks_repo_head_hexsha": "f4de93bd7a01a8b31c9367fad35c81d086768f99", "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.9192546584, "max_line_length": 90, "alphanum_fraction": 0.5595873355, "num_tokens": 1816, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788903594353, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.464954239095278}}
{"text": "/*\n * Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES)\n *\n * This file is part of Orfeo Toolbox\n *\n *     https://www.orfeo-toolbox.org/\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#ifndef otbTrainNeuralNetwork_hxx\n#define otbTrainNeuralNetwork_hxx\n#include <boost/lexical_cast.hpp>\n#include \"otbLearningApplicationBase.h\"\n#include \"otbNeuralNetworkMachineLearningModel.h\"\n\nnamespace otb\n{\nnamespace Wrapper\n{\n\ntemplate <class TInputValue, class TOutputValue>\nvoid LearningApplicationBase<TInputValue, TOutputValue>::InitNeuralNetworkParams()\n{\n  AddChoice(\"classifier.ann\", \"Artificial Neural Network classifier\");\n  SetParameterDescription(\"classifier.ann\", \"http://docs.opencv.org/modules/ml/doc/neural_networks.html\");\n\n  // TrainMethod\n  AddParameter(ParameterType_Choice, \"classifier.ann.t\", \"Train Method Type\");\n  AddChoice(\"classifier.ann.t.back\", \"Back-propagation algorithm\");\n  SetParameterDescription(\"classifier.ann.t.back\",\n                          \"Method to compute the gradient of the loss function and adjust weights \"\n                          \"in the network to optimize the result.\");\n  AddChoice(\"classifier.ann.t.reg\", \"Resilient Back-propagation algorithm\");\n  SetParameterDescription(\"classifier.ann.t.reg\",\n                          \"Almost the same as the Back-prop algorithm except that it does not \"\n                          \"take into account the magnitude of the partial derivative (coordinate \"\n                          \"of the gradient) but only its sign.\");\n\n  SetParameterString(\"classifier.ann.t\", \"reg\");\n  SetParameterDescription(\"classifier.ann.t\", \"Type of training method for the multilayer perceptron (MLP) neural network.\");\n\n  // LayerSizes\n  // There is no ParameterType_IntList, so i use a ParameterType_StringList and convert it.\n  /*std::vector<std::string> layerSizes;\n   layerSizes.push_back(\"100\");\n   layerSizes.push_back(\"100\"); */\n  AddParameter(ParameterType_StringList, \"classifier.ann.sizes\", \"Number of neurons in each intermediate layer\");\n  // SetParameterStringList(\"classifier.ann.sizes\", layerSizes);\n  SetParameterDescription(\"classifier.ann.sizes\", \"The number of neurons in each intermediate layer (excluding input and output layers).\");\n\n  // ActivateFunction\n  AddParameter(ParameterType_Choice, \"classifier.ann.f\", \"Neuron activation function type\");\n  AddChoice(\"classifier.ann.f.ident\", \"Identity function\");\n  AddChoice(\"classifier.ann.f.sig\", \"Symmetrical Sigmoid function\");\n  AddChoice(\"classifier.ann.f.gau\", \"Gaussian function (Not completely supported)\");\n  SetParameterString(\"classifier.ann.f\", \"sig\");\n  SetParameterDescription(\"classifier.ann.f\",\n                          \"This function determine whether the output of the node is positive or not \"\n                          \"depending on the output of the transfert function.\");\n\n  // Alpha\n  AddParameter(ParameterType_Float, \"classifier.ann.a\", \"Alpha parameter of the activation function\");\n  SetParameterFloat(\"classifier.ann.a\", 1.);\n  SetParameterDescription(\"classifier.ann.a\", \"Alpha parameter of the activation function (used only with sigmoid and gaussian functions).\");\n\n  // Beta\n  AddParameter(ParameterType_Float, \"classifier.ann.b\", \"Beta parameter of the activation function\");\n  SetParameterFloat(\"classifier.ann.b\", 1.);\n  SetParameterDescription(\"classifier.ann.b\", \"Beta parameter of the activation function (used only with sigmoid and gaussian functions).\");\n\n  // BackPropDWScale\n  AddParameter(ParameterType_Float, \"classifier.ann.bpdw\", \"Strength of the weight gradient term in the BACKPROP method\");\n  SetParameterFloat(\"classifier.ann.bpdw\", 0.1);\n  SetParameterDescription(\"classifier.ann.bpdw\",\n                          \"Strength of the weight gradient term in the BACKPROP method. The \"\n                          \"recommended value is about 0.1.\");\n\n  // BackPropMomentScale\n  AddParameter(ParameterType_Float, \"classifier.ann.bpms\", \"Strength of the momentum term (the difference between weights on the 2 previous iterations)\");\n  SetParameterFloat(\"classifier.ann.bpms\", 0.1);\n  SetParameterDescription(\"classifier.ann.bpms\",\n                          \"Strength of the momentum term (the difference between weights on the 2 previous \"\n                          \"iterations). This parameter provides some inertia to smooth the random \"\n                          \"fluctuations of the weights. It can vary from 0 (the feature is disabled) \"\n                          \"to 1 and beyond. The value 0.1 or so is good enough.\");\n\n  // RegPropDW0\n  AddParameter(ParameterType_Float, \"classifier.ann.rdw\", \"Initial value Delta_0 of update-values Delta_{ij} in RPROP method\");\n  SetParameterFloat(\"classifier.ann.rdw\", 0.1);\n  SetParameterDescription(\"classifier.ann.rdw\", \"Initial value Delta_0 of update-values Delta_{ij} in RPROP method (default = 0.1).\");\n\n  // RegPropDWMin\n  AddParameter(ParameterType_Float, \"classifier.ann.rdwm\", \"Update-values lower limit Delta_{min} in RPROP method\");\n  SetParameterFloat(\"classifier.ann.rdwm\", 1e-7);\n  SetParameterDescription(\"classifier.ann.rdwm\",\n                          \"Update-values lower limit Delta_{min} in RPROP method. It must be positive \"\n                          \"(default = 1e-7).\");\n\n  // TermCriteriaType\n  AddParameter(ParameterType_Choice, \"classifier.ann.term\", \"Termination criteria\");\n  AddChoice(\"classifier.ann.term.iter\", \"Maximum number of iterations\");\n  SetParameterDescription(\"classifier.ann.term.iter\",\n                          \"Set the number of iterations allowed to the network for its \"\n                          \"training. Training will stop regardless of the result when this \"\n                          \"number is reached\");\n  AddChoice(\"classifier.ann.term.eps\", \"Epsilon\");\n  SetParameterDescription(\"classifier.ann.term.eps\",\n                          \"Training will focus on result and will stop once the precision is\"\n                          \"at most epsilon\");\n  AddChoice(\"classifier.ann.term.all\", \"Max. iterations + Epsilon\");\n  SetParameterDescription(\"classifier.ann.term.all\", \"Both termination criteria are used. Training stop at the first reached\");\n  SetParameterString(\"classifier.ann.term\", \"all\");\n  SetParameterDescription(\"classifier.ann.term\", \"Termination criteria.\");\n\n  // Epsilon\n  AddParameter(ParameterType_Float, \"classifier.ann.eps\", \"Epsilon value used in the Termination criteria\");\n  SetParameterFloat(\"classifier.ann.eps\", 0.01);\n  SetParameterDescription(\"classifier.ann.eps\", \"Epsilon value used in the Termination criteria.\");\n\n  // MaxIter\n  AddParameter(ParameterType_Int, \"classifier.ann.iter\", \"Maximum number of iterations used in the Termination criteria\");\n  SetParameterInt(\"classifier.ann.iter\", 1000);\n  SetParameterDescription(\"classifier.ann.iter\", \"Maximum number of iterations used in the Termination criteria.\");\n}\n\ntemplate <class TInputValue, class TOutputValue>\nvoid LearningApplicationBase<TInputValue, TOutputValue>::TrainNeuralNetwork(typename ListSampleType::Pointer trainingListSample,\n                                                                            typename TargetListSampleType::Pointer trainingLabeledListSample,\n                                                                            std::string                            modelPath)\n{\n  typedef otb::NeuralNetworkMachineLearningModel<InputValueType, OutputValueType> NeuralNetworkType;\n  typename NeuralNetworkType::Pointer classifier = NeuralNetworkType::New();\n  classifier->SetRegressionMode(this->m_RegressionFlag);\n  classifier->SetInputListSample(trainingListSample);\n  classifier->SetTargetListSample(trainingLabeledListSample);\n\n  switch (GetParameterInt(\"classifier.ann.t\"))\n  {\n  case 0: // BACKPROP\n    classifier->SetTrainMethod(CvANN_MLP_TrainParams::BACKPROP);\n    break;\n  case 1: // RPROP\n    classifier->SetTrainMethod(CvANN_MLP_TrainParams::RPROP);\n    break;\n  default: // DEFAULT = RPROP\n    classifier->SetTrainMethod(CvANN_MLP_TrainParams::RPROP);\n    break;\n  }\n\n  std::vector<unsigned int> layerSizes;\n  std::vector<std::string>  sizes = GetParameterStringList(\"classifier.ann.sizes\");\n\n\n  unsigned int nbImageBands = trainingListSample->GetMeasurementVectorSize();\n  layerSizes.push_back(nbImageBands);\n  for (unsigned int i = 0; i < sizes.size(); i++)\n  {\n    unsigned int nbNeurons = boost::lexical_cast<unsigned int>(sizes[i]);\n    layerSizes.push_back(nbNeurons);\n  }\n\n\n  unsigned int nbClasses = 0;\n  if (this->m_RegressionFlag)\n  {\n    layerSizes.push_back(1);\n  }\n  else\n  {\n    std::set<TargetValueType> labelSet;\n    TargetSampleType          currentLabel;\n    for (unsigned int itLab = 0; itLab < trainingLabeledListSample->Size(); ++itLab)\n    {\n      currentLabel = trainingLabeledListSample->GetMeasurementVector(itLab);\n      labelSet.insert(currentLabel[0]);\n    }\n    nbClasses = labelSet.size();\n    layerSizes.push_back(nbClasses);\n  }\n\n  classifier->SetLayerSizes(layerSizes);\n\n  switch (GetParameterInt(\"classifier.ann.f\"))\n  {\n  case 0: // ident\n    classifier->SetActivateFunction(CvANN_MLP::IDENTITY);\n    break;\n  case 1: // sig\n    classifier->SetActivateFunction(CvANN_MLP::SIGMOID_SYM);\n    break;\n  case 2: // gaussian\n    classifier->SetActivateFunction(CvANN_MLP::GAUSSIAN);\n    break;\n  default: // DEFAULT = RPROP\n    classifier->SetActivateFunction(CvANN_MLP::SIGMOID_SYM);\n    break;\n  }\n\n  classifier->SetAlpha(GetParameterFloat(\"classifier.ann.a\"));\n  classifier->SetBeta(GetParameterFloat(\"classifier.ann.b\"));\n  classifier->SetBackPropDWScale(GetParameterFloat(\"classifier.ann.bpdw\"));\n  classifier->SetBackPropMomentScale(GetParameterFloat(\"classifier.ann.bpms\"));\n  classifier->SetRegPropDW0(GetParameterFloat(\"classifier.ann.rdw\"));\n  classifier->SetRegPropDWMin(GetParameterFloat(\"classifier.ann.rdwm\"));\n\n  switch (GetParameterInt(\"classifier.ann.term\"))\n  {\n  case 0: // CV_TERMCRIT_ITER\n    classifier->SetTermCriteriaType(CV_TERMCRIT_ITER);\n    break;\n  case 1: // CV_TERMCRIT_EPS\n    classifier->SetTermCriteriaType(CV_TERMCRIT_EPS);\n    break;\n  case 2: // CV_TERMCRIT_ITER + CV_TERMCRIT_EPS\n    classifier->SetTermCriteriaType(CV_TERMCRIT_ITER + CV_TERMCRIT_EPS);\n    break;\n  default: // DEFAULT = CV_TERMCRIT_ITER + CV_TERMCRIT_EPS\n    classifier->SetTermCriteriaType(CV_TERMCRIT_ITER + CV_TERMCRIT_EPS);\n    break;\n  }\n  classifier->SetEpsilon(GetParameterFloat(\"classifier.ann.eps\"));\n  classifier->SetMaxIter(GetParameterInt(\"classifier.ann.iter\"));\n  classifier->Train();\n  classifier->Save(modelPath);\n}\n\n} // end namespace wrapper\n} // end namespace otb\n\n#endif\n", "meta": {"hexsha": "6047eab2f7a7f4507fc79764506e21f6a1870e84", "size": 11058, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "Modules/Applications/AppClassification/include/otbTrainNeuralNetwork.hxx", "max_stars_repo_name": "qingswu/otb", "max_stars_repo_head_hexsha": "ed903b6a5e51a27a3d04786e4ad1637cf6b2772e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Modules/Applications/AppClassification/include/otbTrainNeuralNetwork.hxx", "max_issues_repo_name": "qingswu/otb", "max_issues_repo_head_hexsha": "ed903b6a5e51a27a3d04786e4ad1637cf6b2772e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Modules/Applications/AppClassification/include/otbTrainNeuralNetwork.hxx", "max_forks_repo_name": "qingswu/otb", "max_forks_repo_head_hexsha": "ed903b6a5e51a27a3d04786e4ad1637cf6b2772e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.694214876, "max_line_length": 154, "alphanum_fraction": 0.7114306385, "num_tokens": 2552, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4648959366984469}}
{"text": "/****************************************************************************\n *   Copyright (c) 2019 Jesus Tordesillas Torres. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in\n *    the documentation and/or other materials provided with the\n *    distribution.\n * 3. Neither the name snap nor the names of its contributors may be\n *    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\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; LOSS\n * OF 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 SOLVERS_HPP\n#define SOLVERS_HPP\n#include <Eigen/Dense>\n#include <iostream>\n\n#include \"cvxgen/interface_vel.h\"\n#include \"cvxgen/interface_accel.h\"\n#include \"cvxgen/interface_jerk.h\"\n\n#include <unsupported/Eigen/Polynomials>\n\n#define VEL 1\n#define ACCEL 2\n#define JERK 3\n\n#define N_VEL 15\n#define N_ACCEL 15\n#define N_JERK 10\n\ntemplate <int INPUT_ORDER>\nclass Solver\n{\npublic:\n  Solver();\n  void set_x0(double x0[]);\n  void set_xf(double xf[]);\n  void set_max(double max_values[INPUT_ORDER]);\n\n  void genNewTraj();\n\n  int getN();\n  void setq(double q);\n  double** getState();\n  double** getInput();\n  double getCost();\n\nprotected:\n  bool checkConvergence(double xf_opt[3 * INPUT_ORDER]);\n  void callOptimizer();\n  double getDTInitial();\n  double dt_;  // time step found by the solver\n  int N_;\n  double xf_[3 * INPUT_ORDER];\n  double x0_[3 * INPUT_ORDER];\n  double v_max_;\n  double a_max_;\n  double j_max_;\n  double q_;  // weight to the 2nd term in the cost function\n  double** x_;\n  double** u_;\n};\n\ntemplate <int INPUT_ORDER>\ndouble Solver<INPUT_ORDER>::getCost()\n{\n  double cost;\n  switch (INPUT_ORDER)\n  {\n    case VEL:\n      cost = vel_get_cost();\n      break;\n    case ACCEL:\n      cost = accel_get_cost();\n      break;\n    case JERK:\n      cost = jerk_get_cost();\n      break;\n  }\n}\n\ntemplate <int INPUT_ORDER>\ndouble** Solver<INPUT_ORDER>::getState()\n{\n  return x_;\n}\n\ntemplate <int INPUT_ORDER>\ndouble** Solver<INPUT_ORDER>::getInput()\n{\n  return u_;\n}\n\ntemplate <int INPUT_ORDER>\nSolver<INPUT_ORDER>::Solver()\n{\n  v_max_ = 20;\n  a_max_ = 2;\n  j_max_ = 20;\n  switch (INPUT_ORDER)\n  {\n    case VEL:\n      vel_initialize_optimizer();\n      N_ = N_VEL;\n      break;\n    case ACCEL:\n      accel_initialize_optimizer();\n      N_ = N_ACCEL;\n      break;\n    case JERK:\n      jerk_initialize_optimizer();\n      N_ = N_JERK;\n      break;\n  }\n}\n\ntemplate <int INPUT_ORDER>\nint Solver<INPUT_ORDER>::getN()\n{\n  return N_;\n}\n\ntemplate <int INPUT_ORDER>\nvoid Solver<INPUT_ORDER>::setq(double q)\n{\n  q_ = q;\n}\n\ntemplate <int INPUT_ORDER>\nvoid Solver<INPUT_ORDER>::set_x0(double x0[])\n{\n  for (int i = 0; i < 3 * INPUT_ORDER; i++)\n  {\n    x0_[i] = x0[i];\n  }\n}\n\ntemplate <int INPUT_ORDER>\nvoid Solver<INPUT_ORDER>::set_xf(double xf[])\n{\n  for (int i = 0; i < 3 * INPUT_ORDER; i++)\n  {\n    xf_[i] = xf[i];\n  }\n}\n\ntemplate <int INPUT_ORDER>\nvoid Solver<INPUT_ORDER>::set_max(double max_values[INPUT_ORDER])\n{\n  switch (INPUT_ORDER)\n  {\n    case VEL:\n      v_max_ = max_values[0];\n      break;\n    case ACCEL:\n      v_max_ = max_values[0];\n      a_max_ = max_values[1];\n      break;\n    case JERK:\n      v_max_ = max_values[0];\n      a_max_ = max_values[1];\n      j_max_ = max_values[2];\n      break;\n  }\n}\n\ntemplate <int INPUT_ORDER>\nbool Solver<INPUT_ORDER>::checkConvergence(double xf_opt[3 * INPUT_ORDER])\n{\n  bool converged = false;\n  float d2 = 0;   // distance in position squared\n  float dv2 = 0;  // distance in velocity squared\n  float da2 = 0;  // distance in acceleration squared\n\n  switch (INPUT_ORDER)\n  {\n    case VEL:\n      for (int i = 0; i < 3; i++)\n      {\n        d2 += pow(xf_[i] - xf_opt[i], 2);\n      }\n      converged = (sqrt(d2) < 0.2) ? true : false;\n      break;\n    case ACCEL:\n      for (int i = 0; i < 3; i++)\n      {\n        d2 += pow(xf_[i] - xf_opt[i], 2);\n        dv2 += pow(xf_[i + 3] - xf_opt[i + 3], 2);\n      }\n      converged = (sqrt(d2) < 0.2 && sqrt(dv2) < 0.2) ? true : false;\n      break;\n    case JERK:\n      for (int i = 0; i < 3; i++)\n      {\n        d2 += pow(xf_[i] - xf_opt[i], 2);\n        dv2 += pow(xf_[i + 3] - xf_opt[i + 3], 2);\n        da2 += pow(xf_[i + 6] - xf_opt[i + 6], 2);\n      }\n      converged = (sqrt(d2) < 0.2 && sqrt(dv2) < 0.2 && 1) ? true : false;\n      break;\n  }\n\n  return converged;\n}\n\ntemplate <int INPUT_ORDER>\nvoid Solver<INPUT_ORDER>::genNewTraj()\n{\n  callOptimizer();\n\n  switch (INPUT_ORDER)\n  {\n    case VEL:\n      x_ = vel_get_state();\n      u_ = vel_get_control();\n\n      break;\n    case ACCEL:\n      x_ = accel_get_state();\n      u_ = accel_get_control();\n\n      break;\n    case JERK:\n      x_ = jerk_get_state();\n      u_ = jerk_get_control();\n\n      break;\n  }\n}\n\ntemplate <int INPUT_ORDER>\nvoid Solver<INPUT_ORDER>::callOptimizer()\n{\n  bool converged = false;\n\n  double dt = getDTInitial();\n\n  double** x;\n  int i = 0;\n  int r = 0;\n  while (1)\n  {\n    dt = dt + 3 * 0.05;\n    i = i + 1;\n    switch (INPUT_ORDER)\n    {\n      case VEL:\n      {\n        vel_load_default_data(dt, v_max_, x0_, xf_, q_);\n        r = vel_optimize();\n        if (r == 1)\n        {\n          x = vel_get_state();\n          converged = checkConvergence(x[N_]);\n        }\n        break;\n      }\n      case ACCEL:\n      {\n        accel_load_default_data(dt, v_max_, a_max_, x0_, xf_, q_);\n        r = accel_optimize();\n        if (r == 1)\n        {\n          x = accel_get_state();\n          converged = checkConvergence(x[N_]);\n        }\n        break;\n      }\n      case JERK:\n      {\n        jerk_load_default_data(dt, v_max_, a_max_, j_max_, x0_, xf_, q_);\n        r = jerk_optimize();\n        if (r == 1)\n        {\n          x = jerk_get_state();\n          converged = checkConvergence(x[N_]);\n        }\n        break;\n      }\n    }\n    if (converged == 1)\n    {\n      break;\n    }\n  }\n\n  if (i > 1)\n  {\n    printf(\"Iterations = %d\\n\", i);\n    printf(\"Iterations>1, if you increase dt at the beginning, it would be faster\\n\");\n  }\n  dt_ = dt;\n}\n\ninline double MinPositiveElement(std::vector<double> v)\n{\n  std::sort(v.begin(), v.end());  // sorted in ascending order\n  double min_value = 0;\n  for (int i = 0; i < v.size(); i++)\n  {\n    if (v[i] > 0)\n    {\n      min_value = v[i];\n      break;\n    }\n  }\n  return min_value;\n}\n\ntemplate <int INPUT_ORDER>\ndouble Solver<INPUT_ORDER>::getDTInitial()\n{\n  double dt_initial = 0;\n  float t_vx = 0;\n  float t_vy = 0;\n  float t_vz = 0;\n  float t_ax = 0;\n  float t_ay = 0;\n  float t_az = 0;\n  float t_jx = 0;\n  float t_jy = 0;\n  float t_jz = 0;\n\n  t_vx = (xf_[0] - x0_[0]) / v_max_;\n  t_vy = (xf_[1] - x0_[1]) / v_max_;\n  t_vz = (xf_[2] - x0_[2]) / v_max_;\n\n  switch (INPUT_ORDER)\n  {\n    case JERK:\n    {\n      float jerkx = copysign(1, xf_[0] - x0_[0]) * j_max_;\n      float jerky = copysign(1, xf_[1] - x0_[1]) * j_max_;\n      float jerkz = copysign(1, xf_[2] - x0_[2]) * j_max_;\n      float a0x = x0_[6];\n      float a0y = x0_[7];\n      float a0z = x0_[8];\n      float v0x = x0_[3];\n      float v0y = x0_[4];\n      float v0z = x0_[5];\n\n      // polynomial ax3+bx2+cx+d=0 --> coeff=[d c b a]\n      Eigen::Vector4d coeff_jx(x0_[0] - xf_[0], v0x, a0x / 2.0, jerkx / 6.0);\n      Eigen::Vector4d coeff_jy(x0_[1] - xf_[1], v0y, a0y / 2.0, jerky / 6.0);\n      Eigen::Vector4d coeff_jz(x0_[2] - xf_[2], v0z, a0z / 2.0, jerkz / 6.0);\n\n      /*  std::cout << \"Coefficients for jerk\" << std::endl;\n        std::cout << \"Coeffx=\" << coeff_jx.transpose() << std::endl;\n        std::cout << \"Coeffy=\" << coeff_jy.transpose() << std::endl;\n        std::cout << \"Coeffz=\" << coeff_jz.transpose() << std::endl;*/\n\n      Eigen::PolynomialSolver<double, Eigen::Dynamic> psolve_jx(coeff_jx);\n      Eigen::PolynomialSolver<double, Eigen::Dynamic> psolve_jy(coeff_jy);\n      Eigen::PolynomialSolver<double, Eigen::Dynamic> psolve_jz(coeff_jz);\n\n      std::vector<double> realRoots_jx;\n      std::vector<double> realRoots_jy;\n      std::vector<double> realRoots_jz;\n      psolve_jx.realRoots(realRoots_jx);\n      psolve_jy.realRoots(realRoots_jy);\n      psolve_jz.realRoots(realRoots_jz);\n\n      t_jx = MinPositiveElement(realRoots_jx);\n      t_jy = MinPositiveElement(realRoots_jy);\n      t_jz = MinPositiveElement(realRoots_jz);\n\n      // printf(\"Times: t_jx, t_jy, t_jz:\\n\");\n      // std::cout << t_jx << \"  \" << t_jy << \"  \" << t_jz << std::endl;\n\n      // Here there is no a break\n    }\n    case ACCEL:\n    {\n      float accelx = copysign(1, xf_[0] - x0_[0]) * a_max_;\n      float accely = copysign(1, xf_[1] - x0_[1]) * a_max_;\n      float accelz = copysign(1, xf_[2] - x0_[2]) * a_max_;\n      float v0x = x0_[3];\n      float v0y = x0_[4];\n      float v0z = x0_[5];\n\n      // polynomial ax2+bx+c=0 --> coeff=[c b a]\n      Eigen::Vector3d coeff_ax(x0_[0] - xf_[0], v0x, 0.5 * accelx);\n      Eigen::Vector3d coeff_ay(x0_[1] - xf_[1], v0y, 0.5 * accely);\n      Eigen::Vector3d coeff_az(x0_[2] - xf_[2], v0z, 0.5 * accelz);\n\n      Eigen::PolynomialSolver<double, Eigen::Dynamic> psolve_ax(coeff_ax);\n      Eigen::PolynomialSolver<double, Eigen::Dynamic> psolve_ay(coeff_ay);\n      Eigen::PolynomialSolver<double, Eigen::Dynamic> psolve_az(coeff_az);\n\n      std::vector<double> realRoots_ax;\n      std::vector<double> realRoots_ay;\n      std::vector<double> realRoots_az;\n      psolve_ax.realRoots(realRoots_ax);\n      psolve_ay.realRoots(realRoots_ay);\n      psolve_az.realRoots(realRoots_az);\n\n      t_ax = MinPositiveElement(realRoots_ax);\n      t_ay = MinPositiveElement(realRoots_ay);\n      t_az = MinPositiveElement(realRoots_az);\n    }\n    case VEL:\n    {\n      // I'm done\n      break;\n    }\n  }\n  dt_initial = std::max({ t_vx, t_vy, t_vz, t_ax, t_ay, t_az, t_jx, t_jy, t_jz }) / N_;\n  if (dt_initial > 10000)  // happens when there is no solution to the previous eq.\n  {\n    printf(\"There is not a solution to find the intial dt\");\n    dt_initial = 0;\n  }\n  return dt_initial;\n}\n\n#endif\n", "meta": {"hexsha": "edfe51e536c4cd9d85c428a12228b6c139b5a2ab", "size": 11012, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/cvx/src/solvers/solvers.hpp", "max_stars_repo_name": "jtorde/uav_trajectory_optimizer", "max_stars_repo_head_hexsha": "7a74fab766100cb0bd7e49b3d832d9ae7efcb3fd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 46.0, "max_stars_repo_stars_event_min_datetime": "2019-02-26T13:08:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T11:09:11.000Z", "max_issues_repo_path": "src/cvx/src/solvers/solvers.hpp", "max_issues_repo_name": "jtorde/uav_trajectory_optimizer", "max_issues_repo_head_hexsha": "7a74fab766100cb0bd7e49b3d832d9ae7efcb3fd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cvx/src/solvers/solvers.hpp", "max_forks_repo_name": "jtorde/uav_trajectory_optimizer", "max_forks_repo_head_hexsha": "7a74fab766100cb0bd7e49b3d832d9ae7efcb3fd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2019-02-26T13:08:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-06T20:31:40.000Z", "avg_line_length": 25.1990846682, "max_line_length": 87, "alphanum_fraction": 0.6015256084, "num_tokens": 3348, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4648959304521624}}
{"text": "#pragma once\n\n#include \"qnum.hpp\"\n#include \"flex.hpp\"\n#include <Eigen/Core>\n#include \"autodiff/reverse.hpp\"\n/// Eigen3 supporting types and helpers\n\n// Eigen specializations\nnamespace Eigen\n{\n  using namespace qnum;\n  using namespace flex;\n  using namespace autodiff;\n  /// Traits specialization for qspace_number_t.\n  /// See Eigen/src/Core/NumTraits.h for documentation.\n  template<typename T, int E> struct NumTraits<qspace_number_t<T, E>>\n    : GenericNumTraits<qspace_number_t<T, E>>\n  {\n    typedef qspace_number_t<T, E> Real;\n    typedef qspace_number_t<T, E> NonInteger;\n    typedef qspace_number_t<T, E> Nested;\n    typedef qspace_number_t<T, E> Literal;\n\n    enum {\n      IsComplex = 0,\n      IsInteger = 0,\n      ReadCost = 1,\n      AddCost = 1,\n      MulCost = 1,\n      IsSigned = 1,\n      RequireInitialization = 1,\n    };\n\n    static inline Real epsilon() { return Real::from_literal(1, false); }\n    static inline Real dummy_precision() { Real v; return v; }\n    static inline Real highest() { return Real::from_literal(Real::T_max(), true); }\n    static inline Real lowest() { return Real::from_literal(Real::T_min(), true); }\n    static inline int digits10() { return std::numeric_limits<T>::digits10; }\n  };\n\n  namespace internal {\n    /// Partial specialization for random implementation for qspace numbers.\n    /// See MathFunctions.h L535\n    template<typename T, int E> struct random_impl<qspace_number_t<T, E>>\n      : random_default_impl\n        <\n        qspace_number_t<T, E>,\n        NumTraits<qspace_number_t<T, E>>::IsComplex,\n        NumTraits<qspace_number_t<T, E>>::IsInteger\n        > \n    {\n      typedef qspace_number_t<T, E> _Q;\n      static inline _Q run(const _Q& x, const _Q& y) {\n        if (x > y) return x;\n\n        int rn = std::rand() * RAND_MAX + std::rand();\n        typename _Q::Tu xu = static_cast<typename _Q::Tu>(x.val);\n        typename _Q::Tu yu = static_cast<typename _Q::Tu>(y.val);\n        auto ru = static_cast<typename _Q::Tu>(rn) % yu - xu;\n        return _Q::from_literal(static_cast<T>(ru), false);\n      }\n      static inline _Q run() {\n        int rn = std::rand() * RAND_MAX + std::rand();\n        return _Q::from_literal(static_cast<T>(rn) >> _Q::ext_bits(), false);\n      }\n    };\n\n    template<typename T, int E> struct random_impl<Variable<qspace_number_t<T, E>>>\n      : random_default_impl\n        <\n        Variable<qspace_number_t<T, E>>,\n        NumTraits<Variable<qspace_number_t<T, E>>>::IsComplex,\n        NumTraits<Variable<qspace_number_t<T, E>>>::IsInteger\n        > \n    {\n      typedef qspace_number_t<T, E> _Q;\n      static inline Variable<_Q> run(const Variable<_Q>& x, const Variable<_Q>& y) {\n        return Variable<_Q>(random_impl<_Q>::run(x.expr->val, y.expr->val));\n      }\n      static inline Variable<_Q> run() {\n        return Variable<_Q>(random_impl<_Q>::run());\n      }\n    };\n  }\n\n  /// Traits specialization for flexfloat.\n  /// See Eigen/src/Core/NumTraits.h for documentation.\n  template<uint8_t E, uint8_t F> struct NumTraits<flexfloat<E, F>>\n    : NumTraits<double>\n  {\n    typedef flexfloat<E, F> Real;\n    typedef flexfloat<E, F> NonInteger;\n    typedef flexfloat<E, F> Nested;\n    typedef flexfloat<E, F> Literal;\n\n    enum {\n      RequireInitialization = 1,\n    };\n\n    static inline Real epsilon() { \n      Real v; \n      flexfloat_t ff = (flexfloat_t)v;\n      flexfloat_set_bits(&ff, 1);\n      return (Real)ff;\n    }\n    static inline Real dummy_precision() { \n      Real v; \n      return v; \n    }\n    static inline Real highest() { return Real(FLT_MAX); }\n    static inline Real lowest() { return Real(FLT_MIN);}\n    static inline int digits10() { return 10; } // XXX wrong\n  };\n\n  namespace internal {\n    /// Partial specialization for random implementation for flexfloat.\n    /// See MathFunctions.h L535\n    template<uint8_t E, uint8_t F> struct random_impl<flexfloat<E, F>>\n      : random_default_impl\n        <\n        flexfloat<E, F>,\n        NumTraits<flexfloat<E, F>>::IsComplex,\n        NumTraits<flexfloat<E, F>>::IsInteger\n        > \n    {\n      typedef flexfloat<E, F> _Q;\n      static inline _Q run(const _Q& x, const _Q& y) {\n        if (x > y) return x;\n        double rn = std::rand();\n        rn = rn / RAND_MAX * (y - x) + x;\n        return (_Q)rn;\n      }\n      static inline _Q run() {\n        double rn = std::rand();\n        rn = (rn / RAND_MAX) * 2.0 - 1.0;\n        return (_Q)rn;\n      }\n    };\n\n    template<uint8_t E, uint8_t F> struct random_impl<Variable<flexfloat<E, F>>>\n      : random_default_impl\n        <\n        Variable<flexfloat<E, F>>,\n        NumTraits<Variable<flexfloat<E, F>>>::IsComplex,\n        NumTraits<Variable<flexfloat<E, F>>>::IsInteger\n        > \n    {\n      typedef flexfloat<E, F> _Q;\n      static inline Variable<_Q> run(const Variable<_Q>& x, const Variable<_Q>& y) {\n        return Variable<_Q>(random_impl<_Q>::run(x.expr->val, y.expr->val));\n      }\n      static inline Variable<_Q> run() {\n        return Variable<_Q>(random_impl<_Q>::run());\n      }\n    };\n  }\n}\n\n", "meta": {"hexsha": "13975608e30ba917756b13cef77fed3b249a636d", "size": 5033, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "qnum/eigen.hpp", "max_stars_repo_name": "yatli/autodiff", "max_stars_repo_head_hexsha": "1a8e6a899c8ee0cd5e7cf3fa3167cfae0ca683dd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-04-24T06:54:48.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-24T06:54:48.000Z", "max_issues_repo_path": "qnum/eigen.hpp", "max_issues_repo_name": "yatli/autodiff", "max_issues_repo_head_hexsha": "1a8e6a899c8ee0cd5e7cf3fa3167cfae0ca683dd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "qnum/eigen.hpp", "max_forks_repo_name": "yatli/autodiff", "max_forks_repo_head_hexsha": "1a8e6a899c8ee0cd5e7cf3fa3167cfae0ca683dd", "max_forks_repo_licenses": ["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.45625, "max_line_length": 84, "alphanum_fraction": 0.611961057, "num_tokens": 1369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.46489592420587755}}
{"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_DIVROUND_HPP_INCLUDED\n#define BOOST_SIMD_TOOLBOX_ARITHMETIC_FUNCTIONS_SCALAR_DIVROUND_HPP_INCLUDED\n\n#include <boost/simd/toolbox/arithmetic/functions/divround.hpp>\n#include <boost/simd/include/functions/scalar/round.hpp>\n#include <boost/simd/include/constants/valmin.hpp>\n#include <boost/simd/include/constants/valmax.hpp>\n#include <boost/simd/include/constants/zero.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::divround_, tag::cpu_\n                                   , (A0)\n                                   , (scalar_< arithmetic_<A0> >)\n                                     (scalar_< arithmetic_<A0> >)\n                                     )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n      {\n        return (a1) ? static_cast<A0>(round(static_cast<double>(a0)/static_cast<double>(a1)))\n          : ((a0 > 0) ? Valmax<A0>()\n             : ((a0 < 0) ? Valmin<A0>()\n                : Zero<A0>()\n                )\n             );\n      }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::divround_, tag::cpu_\n                                   , (A0)\n                                   , (scalar_< unsigned_<A0> >)\n                                     (scalar_< unsigned_<A0> >)\n                                     )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n      {\n        return (a1) ? static_cast<A0>(round(static_cast<double>(a0)/static_cast<double>(a1)))\n          : ((a0 > 0) ? Valmax<A0>() : Zero<A0>()\n             );\n      }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::divround_, tag::cpu_\n                                   , (A0)\n                                   , (scalar_< floating_<A0> >)\n                                     (scalar_< floating_<A0> >)\n                                     )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n      {\n        return boost::simd::round(a0/a1);\n      }\n  };\n} } }\n\n#endif\n", "meta": {"hexsha": "0c65d96dad53140e050c1c37d4ef28a1a5253452", "size": 2567, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/arithmetic/include/boost/simd/toolbox/arithmetic/functions/scalar/divround.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/divround.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/divround.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": 37.75, "max_line_length": 93, "alphanum_fraction": 0.4947409427, "num_tokens": 577, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.46489592420587755}}
{"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/termstructures/yield/clonedyieldtermstructure.hpp>\n#include <ql/math/interpolations/loginterpolation.hpp>\n\n#include <boost/make_shared.hpp>\n\nnamespace QuantLib {\n\nClonedYieldTermStructure::ClonedYieldTermStructure(\n    const boost::shared_ptr<YieldTermStructure> source,\n    const ReactionToTimeDecay reactionToTimeDecay,\n    const Processing processing,\n    const Calendar calendar)\n    : YieldTermStructure(source->dayCounter()),\n      reactionToTimeDecay_(reactionToTimeDecay),\n      processing_(processing),\n      originalEvalDate_(Settings::instance().evaluationDate()),\n      originalReferenceDate_(Date(source->referenceDate())),\n      originalMaxDate_(source->maxDate()) {\n\n    calendar_ = calendar.empty() ? source->calendar() : calendar;\n    QL_REQUIRE(!calendar_.empty() || reactionToTimeDecay_ == FixedReferenceDate,\n               \"a floating termstructure needs a calendar, none given and \"\n               \"source termstructures' calendar is empty, too\");\n\n    referenceDate_ = originalReferenceDate_;\n    maxDate_ = originalMaxDate_;\n    offset_ = 0.0;\n    valid_ = true;\n\n    instFwdMax_ =\n        source->forwardRate(maxDate_, maxDate_, Actual365Fixed(), Continuous)\n            .rate();\n\n    if (reactionToTimeDecay != FixedReferenceDate) {\n        QL_REQUIRE(originalReferenceDate_ >= originalEvalDate_,\n                   \"to construct a moving term structure the source term \"\n                   \"structure must have a reference date (\"\n                       << originalReferenceDate_\n                       << \") after the evaluation date (\"\n                       << originalEvalDate_\n                       << \")\");\n            try {\n                impliedSettlementDays_ = source->settlementDays();\n            } catch(...) {\n                // if the source ts has no settlement days we imply\n                // them from the difference of the original reference\n                // date and the original evaluation date\n                impliedSettlementDays_ = this->calendar().businessDaysBetween(\n                    originalEvalDate_, originalReferenceDate_);\n            }\n    }\n\n    discounts_.resize(originalMaxDate_.serialNumber() -\n                      originalReferenceDate_.serialNumber()+1);\n    times_.resize(discounts_.size());\n\n    for (BigInteger i = 0; i <= originalMaxDate_.serialNumber() -\n                                    originalReferenceDate_.serialNumber();\n         ++i) {\n        Date d = Date(originalReferenceDate_.serialNumber()\n                      +i);\n        discounts_[i] = source->discount(d);\n        times_[i] = timeFromReference(d);\n        if(processing == PositiveYieldsAndForwards) {\n            discounts_[i] = std::min(1.0, discounts_[i]);\n        }\n        if (processing == PositiveForwards ||\n            processing == PositiveYieldsAndForwards) {\n            if (i > 0)\n                discounts_[i] = std::min(discounts_[i - 1], discounts_[i]);\n        }\n    }\n\n    interpolation_ = boost::make_shared<LogLinearInterpolation>(\n        times_.begin(), times_.end(), discounts_.begin());\n    interpolation_->update();\n\n    if (reactionToTimeDecay_ != FixedReferenceDate) {\n        registerWith(Settings::instance().evaluationDate());\n    }\n}\n\nDiscountFactor ClonedYieldTermStructure::discountImpl(Time t) const {\n    QL_REQUIRE(valid_, \"termstructure not valid, evaluation date (\"\n                           << Settings::instance().evaluationDate()\n                           << \") is before the evaluation date when the \"\n                              \"termstructure was frozen (\"\n                           << originalEvalDate_);\n    Time tMax = maxTime();\n    Time tEff = t + offset_;\n    if (tEff < tMax) {\n        // also ok for offset_ = 0\n        return interpolation_->operator()(tEff) /\n               interpolation_->operator()(offset_);\n    }\n\n    // flat fwd extrapolation\n    DiscountFactor dMax = discounts_.back();\n    return dMax * std::exp(-instFwdMax_ * (tEff - tMax));\n}\n\nvoid ClonedYieldTermStructure::update() {\n    YieldTermStructure::update();\n    if (reactionToTimeDecay_ != FixedReferenceDate) {\n        Date today = Settings::instance().evaluationDate();\n        if (today < originalEvalDate_) {\n            valid_ = false;\n        } else {\n            valid_ = true;\n            referenceDate_ = calendar().advance(today, impliedSettlementDays_ * Days);\n            if (reactionToTimeDecay_ == ForwardForward) {\n                offset_ = dayCounter().yearFraction(originalReferenceDate_,\n                                                    referenceDate_);\n            }\n            if (reactionToTimeDecay_ == ConstantZeroYields) {\n                BigNatural dayOffset = referenceDate_ - originalReferenceDate_;\n                maxDate_ = Date(std::min<BigNatural>(\n                    originalMaxDate_.serialNumber() + dayOffset,\n                    Date::maxDate().serialNumber()));\n            }\n        }\n    }\n}\n\n} // namespace QuantLib\n", "meta": {"hexsha": "02d98c99605400e61f934c30d6f24009f7fc7ae7", "size": 5760, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ql/termstructures/yield/clonedyieldtermstructure.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/termstructures/yield/clonedyieldtermstructure.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/termstructures/yield/clonedyieldtermstructure.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.724137931, "max_line_length": 86, "alphanum_fraction": 0.6201388889, "num_tokens": 1222, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706735, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4647579436316717}}
{"text": "#pragma once\n#include <armadillo>\n#include \"project/LinearRegression.hpp\"\n\nclass AutoregressiveModel: public LinearRegression\n{   \n    private:\n        int reg_lag;\n        arma::vec ts;\n    public: \n        AutoregressiveModel(arma::vec &x, arma::vec &y, int lag);\n        arma::mat laggedMatrix(arma::vec &x, int lag);\n        float pointPrediction(arma::mat &x);\n        arma::vec forecast(int horizon);\n};", "meta": {"hexsha": "0d4a36aa5ec3791776f23faa29f3b0b239b2eac6", "size": 409, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/project/AutoregressiveModel.hpp", "max_stars_repo_name": "haruspex-machine/ts-forecast-cpp", "max_stars_repo_head_hexsha": "a4087fc479a422d945d79144cac408552a7ec83c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-09T06:27:15.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-09T06:27:15.000Z", "max_issues_repo_path": "include/project/AutoregressiveModel.hpp", "max_issues_repo_name": "bklimowski/ts-forecast-cpp", "max_issues_repo_head_hexsha": "a4087fc479a422d945d79144cac408552a7ec83c", "max_issues_repo_licenses": ["MIT"], "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/project/AutoregressiveModel.hpp", "max_forks_repo_name": "bklimowski/ts-forecast-cpp", "max_forks_repo_head_hexsha": "a4087fc479a422d945d79144cac408552a7ec83c", "max_forks_repo_licenses": ["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.2666666667, "max_line_length": 65, "alphanum_fraction": 0.6454767726, "num_tokens": 106, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.46475794363167167}}
{"text": "#include <cctbx/boost_python/flex_fwd.h>\n\n#include <boost/python/module.hpp>\n#include <boost/python/class.hpp>\n#include <boost/python/def.hpp>\n#include <boost/python/dict.hpp>\n#include <boost/python/list.hpp>\n#include <scitbx/array_family/flex_types.h>\n#include <scitbx/array_family/shared.h>\n#include <scitbx/constants.h>\n#include <scitbx/math/mean_and_variance.h>\n#include <scitbx/vec3.h>\n#include <cctbx/miller.h>\n\n#include <vector>\n#include <map>\n\nusing namespace boost::python;\n\nnamespace xfel {\n\nstruct mark2_iteration {\n  typedef scitbx::af::shared<double> farray;\n  typedef scitbx::af::shared<int> iarray;\n  farray values;\n  farray tox;\n  farray toy;\n  farray spotcx;\n  farray spotcy;\n  farray spotfx;\n  farray spotfy;\n  iarray master_tiles;\n  double functional;\n  farray gradients_,curvatures_;\n\n  farray model_calcx, model_calcy;\n  double calc_minus_To_x, calc_minus_To_y;\n  double rotated_o_x, rotated_o_y;\n  double partial_partial_theta_x, partial_partial_theta_y;\n  double partial_sq_theta_x, partial_sq_theta_y;\n\n  farray sine,cosine;\n\n  mark2_iteration(){}\n  mark2_iteration(farray values, farray tox, farray toy, farray spotcx, farray spotcy,\n                  farray spotfx, farray spotfy,\n                  iarray master_tiles):\n    values(values),tox(tox),toy(toy),spotcx(spotcx),spotcy(spotcy),\n    master_tiles(master_tiles),\n    model_calcx(spotcx.size(),scitbx::af::init_functor_null<double>()),\n    model_calcy(spotcx.size(),scitbx::af::init_functor_null<double>()),\n    functional(0.),\n    gradients_(3*64),\n    curvatures_(3*64)\n  {\n    SCITBX_ASSERT(tox.size()==64);\n    SCITBX_ASSERT(toy.size()==64);\n    SCITBX_ASSERT(values.size()==3*64);\n    for (int tidx=0; tidx < 64; ++tidx){\n      cosine.push_back(std::cos(values[128+tidx]*scitbx::constants::pi_180));\n      sine.push_back(std::sin(values[128+tidx]*scitbx::constants::pi_180));\n    }\n\n    for (int ridx=0; ridx < spotcx.size(); ++ridx){\n      int itile = master_tiles[ridx];\n      calc_minus_To_x = spotcx[ridx] - tox[itile];\n      calc_minus_To_y = spotcy[ridx] - toy[itile];\n\n      rotated_o_x = calc_minus_To_x * cosine[itile] - calc_minus_To_y * sine[itile];\n      rotated_o_y = calc_minus_To_x * sine[itile] +   calc_minus_To_y * cosine[itile];\n\n      model_calcx[ridx] = rotated_o_x + (tox[itile] + values[2*itile]);\n      model_calcy[ridx] = rotated_o_y + (toy[itile] + values[2*itile+1]);\n\n      partial_partial_theta_x = -calc_minus_To_x * sine[itile] - calc_minus_To_y * cosine[itile];\n      partial_partial_theta_y =  calc_minus_To_x * cosine[itile] - calc_minus_To_y * sine[itile];\n\n      partial_sq_theta_x = -calc_minus_To_x * cosine[itile] + calc_minus_To_y * sine[itile];\n      partial_sq_theta_y = -calc_minus_To_x * sine[itile] - calc_minus_To_y * cosine[itile];\n\n      double delx = model_calcx[ridx] - spotfx[ridx];\n      double dely = model_calcy[ridx] - spotfy[ridx];\n      double delrsq(delx*delx + dely*dely);\n      functional += delrsq; // sum of square differences\n\n      gradients_[2*itile]  += 2. *  delx;\n      gradients_[2*itile+1]+= 2. *  dely;\n\n      gradients_[128+itile] += scitbx::constants::pi_180 * 2.* (\n        delx * partial_partial_theta_x +\n        dely * partial_partial_theta_y\n      );\n\n      curvatures_[2*itile] += 2.;\n      curvatures_[2*itile+1] += 2.;\n\n      curvatures_[128+itile] += scitbx::constants::pi_180 * scitbx::constants::pi_180 * 2. * (\n        ( partial_partial_theta_x*partial_partial_theta_x +\n          partial_partial_theta_y*partial_partial_theta_y ) +\n        ( delx*partial_sq_theta_x + dely*partial_sq_theta_y )\n      );\n    }\n  }\n  mark2_iteration(farray values, farray tox, farray toy, farray spotcx, farray spotcy,\n                  farray spotfx, farray spotfy,\n                  iarray master_tiles,iarray frames,int const& nframes,\n                  bool const& inheritable):\n    values(values),tox(tox),toy(toy),spotcx(spotcx),spotcy(spotcy),\n    master_tiles(master_tiles),\n    model_calcx(spotcx.size(),scitbx::af::init_functor_null<double>()),\n    model_calcy(spotcx.size(),scitbx::af::init_functor_null<double>()),\n    functional(0.){}\n\n  mark2_iteration(farray values, farray tox, farray toy, farray spotcx, farray spotcy,\n                  farray spotfx, farray spotfy,\n                  iarray master_tiles,iarray frames,int const& nframes):\n    values(values),tox(tox),toy(toy),spotcx(spotcx),spotcy(spotcy),\n    master_tiles(master_tiles),\n    model_calcx(spotcx.size(),scitbx::af::init_functor_null<double>()),\n    model_calcy(spotcx.size(),scitbx::af::init_functor_null<double>()),\n    functional(0.),\n    gradients_(3*64+2*nframes),\n    curvatures_(3*64+2*nframes)\n  {\n    SCITBX_ASSERT(tox.size()==64);\n    SCITBX_ASSERT(toy.size()==64);\n    SCITBX_ASSERT(values.size()==3*64+2*nframes);\n    for (int tidx=0; tidx < 64; ++tidx){\n      cosine.push_back(std::cos(values[128+tidx]*scitbx::constants::pi_180));\n      sine.push_back(std::sin(values[128+tidx]*scitbx::constants::pi_180));\n    }\n\n    for (int ridx=0; ridx < spotcx.size(); ++ridx){\n      int itile = master_tiles[ridx];\n      int frame_param_no = frames[ridx];\n      calc_minus_To_x = spotcx[ridx] - tox[itile];\n      calc_minus_To_y = spotcy[ridx] - toy[itile];\n\n      rotated_o_x = calc_minus_To_x * cosine[itile] - calc_minus_To_y * sine[itile];\n      rotated_o_y = calc_minus_To_x * sine[itile] +   calc_minus_To_y * cosine[itile];\n\n      model_calcx[ridx] = rotated_o_x + (tox[itile] + values[2*itile]);\n      model_calcy[ridx] = rotated_o_y + (toy[itile] + values[2*itile+1]);\n\n      partial_partial_theta_x = -calc_minus_To_x * sine[itile] - calc_minus_To_y * cosine[itile];\n      partial_partial_theta_y =  calc_minus_To_x * cosine[itile] - calc_minus_To_y * sine[itile];\n\n      partial_sq_theta_x = -calc_minus_To_x * cosine[itile] + calc_minus_To_y * sine[itile];\n      partial_sq_theta_y = -calc_minus_To_x * sine[itile] - calc_minus_To_y * cosine[itile];\n\n      double delx = model_calcx[ridx] - spotfx[ridx];\n      double dely = model_calcy[ridx] - spotfy[ridx];\n      double delrsq(delx*delx + dely*dely);\n      functional += delrsq; // sum of square differences\n\n      gradients_[2*itile]  += 2. *  delx;\n      gradients_[2*itile+1]+= 2. *  dely;\n      if (frame_param_no < nframes){\n        gradients_[192+2*frame_param_no]  += 2. *  delx;\n        gradients_[193+2*frame_param_no]  += 2. *  dely;\n      }\n\n      gradients_[128+itile] += scitbx::constants::pi_180 * 2.* (\n        delx * partial_partial_theta_x +\n        dely * partial_partial_theta_y\n      );\n\n      curvatures_[2*itile] += 2.;\n      curvatures_[2*itile+1] += 2.;\n      if (frame_param_no < nframes){\n        curvatures_[192+2*frame_param_no] += 2.;\n        curvatures_[193+2*frame_param_no] += 2.;\n      }\n\n      curvatures_[128+itile] += scitbx::constants::pi_180 * scitbx::constants::pi_180 * 2. * (\n        ( partial_partial_theta_x*partial_partial_theta_x +\n          partial_partial_theta_y*partial_partial_theta_y ) +\n        ( delx*partial_sq_theta_x + dely*partial_sq_theta_y )\n      );\n    }\n  }\n\n  double f(){ return functional; }\n  farray gradients(){ return gradients_; }\n  farray curvatures(){ return curvatures_; }\n};\n\nstruct mark3_collect_data{\n  //adapt all-frame data to individual-frame parameter refinement\n  typedef scitbx::af::shared<double> farray;\n  typedef scitbx::af::shared<int> iarray;\n  typedef scitbx::af::shared<cctbx::miller::index<> > marray;\n  typedef scitbx::af::shared<bool> barray;\n  marray HKL;\n  std::map<int,int> frame_first_index, frame_match_count;\n  farray result_model_cx,result_model_cy;\n  barray result_flags;\n  scitbx::af::shared<scitbx::vec3<double> > result_part_distance;\n\n  mark3_collect_data(){}\n  mark3_collect_data(iarray frame_id, marray indices):\n    HKL(indices),\n    result_model_cx(frame_id.size(),scitbx::af::init_functor_null<double>()),\n    result_model_cy(frame_id.size(),scitbx::af::init_functor_null<double>()),\n    result_flags(frame_id.size(),scitbx::af::init_functor_null<bool>()),\n    result_part_distance(frame_id.size(),scitbx::af::init_functor_null<scitbx::vec3<double> >())\n  {\n    SCITBX_ASSERT(frame_id.size()==indices.size());\n\n    for (int idx=0; idx < frame_id.size(); ++idx){\n      int iframe = frame_id[idx];\n      if (frame_first_index.find(iframe)==frame_first_index.end()){\n        frame_first_index[iframe]=idx;\n        frame_match_count[iframe]=1;\n      } else {\n        SCITBX_ASSERT(\n          frame_first_index[iframe]+frame_match_count[iframe] == idx);// each frame all contiguous\n        frame_match_count[iframe]+=1;\n      }\n    }\n  }\n\n  int\n  get_first_index(int const& frame_id) const {\n    return frame_first_index.find(frame_id)->second;\n  }\n\n  marray\n  frame_indices(int const& frame_id)const{\n    marray result;\n    int last = frame_first_index.find(frame_id)->second + frame_match_count.find(frame_id)->second;\n    for (int idx=frame_first_index.find(frame_id)->second; idx < last; ++idx){\n      result.push_back(HKL[idx]);\n    }\n    return result;\n  }\n\n  barray\n  selection(int const& frame_id)const{\n    barray result(result_model_cx.size());\n    int last = frame_first_index.find(frame_id)->second + frame_match_count.find(frame_id)->second;\n    for (int idx=frame_first_index.find(frame_id)->second; idx < last; ++idx){\n      result[idx] = true;\n    }\n    return result;\n  }\n\n  void collect(scitbx::af::shared<scitbx::vec3<double> > hi_E_limit,\n               scitbx::af::shared<scitbx::vec3<double> > lo_E_limit,\n               barray observed_flag,\n               int const& frame_id){\n    int first = frame_first_index.find(frame_id)->second;\n    for (int im = 0; im < hi_E_limit.size(); ++im){\n      result_model_cx[first + im] = (hi_E_limit[im][1] + lo_E_limit[im][1])/2.;\n      result_model_cy[first + im] = (hi_E_limit[im][0] + lo_E_limit[im][0])/2.;\n      result_flags[first + im] = observed_flag[im];\n      SCITBX_ASSERT (observed_flag[im]); // no current support for masked-out spots\n    }\n  }\n  void collect_mean_position(scitbx::af::shared<scitbx::vec3<double> > mean_position,\n               barray observed_flag,\n               int const& frame_id){\n    int first = frame_first_index.find(frame_id)->second;\n    for (int im = 0; im < mean_position.size(); ++im){\n      result_model_cx[first + im] = mean_position[im][1];\n      result_model_cy[first + im] = mean_position[im][0];\n      result_flags[first + im] = observed_flag[im];\n      SCITBX_ASSERT (observed_flag[im]); // no current support for masked-out spots\n    }\n  }\n  void collect_distance(scitbx::af::shared<scitbx::vec3<double> > part_distance,\n               int const& frame_id){\n    int first = frame_first_index.find(frame_id)->second;\n    for (int im = 0; im < part_distance.size(); ++im){\n      result_part_distance[first + im] = part_distance[im];\n    }\n  }\n};\n\nstruct mark5_iteration: public mark2_iteration {\n  typedef scitbx::af::shared<scitbx::vec3<double> > vec3array;\n  typedef scitbx::vec3<double>                      vec3;\n\n  mark5_iteration(farray values, farray tox, farray toy, farray spotcx, farray spotcy,\n                  farray spotfx, farray spotfy,\n                  iarray master_tiles,iarray frames,int const& nframes,\n                  vec3array partial_r_partial_distance):\n    mark2_iteration(values, tox, toy, spotcx, spotcy, spotfx, spotfy,\n                    master_tiles, frames, nframes, true)\n  {\n    gradients_ = farray(3*64+3*nframes);\n    curvatures_ = farray(3*64+3*nframes);\n    SCITBX_ASSERT(tox.size()==64);\n    SCITBX_ASSERT(toy.size()==64);\n    SCITBX_ASSERT(values.size()==3*64+3*nframes);\n    for (int tidx=0; tidx < 64; ++tidx){\n      cosine.push_back(std::cos(values[128+tidx]*scitbx::constants::pi_180));\n      sine.push_back(std::sin(values[128+tidx]*scitbx::constants::pi_180));\n    }\n\n    for (int ridx=0; ridx < spotcx.size(); ++ridx){\n      int itile = master_tiles[ridx];\n      int frame_param_no = frames[ridx];\n\n      calc_minus_To_x = spotcx[ridx] - tox[itile];\n      calc_minus_To_y = spotcy[ridx] - toy[itile];\n\n      rotated_o_x = calc_minus_To_x * cosine[itile] - calc_minus_To_y * sine[itile];\n      rotated_o_y = calc_minus_To_x * sine[itile] +   calc_minus_To_y * cosine[itile];\n\n      model_calcx[ridx] = rotated_o_x + (tox[itile] + values[2*itile]);\n      model_calcy[ridx] = rotated_o_y + (toy[itile] + values[2*itile+1]);\n\n      partial_partial_theta_x = -calc_minus_To_x * sine[itile] - calc_minus_To_y * cosine[itile];\n      partial_partial_theta_y =  calc_minus_To_x * cosine[itile] - calc_minus_To_y * sine[itile];\n\n      partial_sq_theta_x = -calc_minus_To_x * cosine[itile] + calc_minus_To_y * sine[itile];\n      partial_sq_theta_y = -calc_minus_To_x * sine[itile] - calc_minus_To_y * cosine[itile];\n\n      double delx = model_calcx[ridx] - spotfx[ridx];\n      double dely = model_calcy[ridx] - spotfy[ridx];\n      double delrsq(delx*delx + dely*dely);\n      functional += delrsq; // sum of square differences\n\n      vec3 part_r_part_d = partial_r_partial_distance[ridx];\n      double rotated_part_r_c_x = part_r_part_d[0] * cosine[itile] - part_r_part_d[1] * sine[itile];\n      double rotated_part_r_c_y = part_r_part_d[0] * sine[itile] +   part_r_part_d[1] * cosine[itile];\n\n      //if (frame_param_no==10){\n      //        printf(\"%5d %8.4f %8.4f\", itile, part_r_part_d[0], part_r_part_d[1]);\n      //        printf(\"%5d %8.4f %8.4f\\n\", itile, rotated_part_r_c_x, rotated_part_r_c_y);\n      //}\n\n      gradients_[2*itile]  += 2. *  delx;\n      gradients_[2*itile+1]+= 2. *  dely;\n      if (frame_param_no < nframes){\n        gradients_[192+2*frame_param_no]  += 2. *  delx;\n        gradients_[193+2*frame_param_no]  += 2. *  dely;\n        gradients_[192 + 2*nframes + frame_param_no] += 2. * (\n          delx * rotated_part_r_c_y + dely * rotated_part_r_c_x\n        );//  SOMETHING IS ROTTEN IN DENMARK\n      }\n\n      gradients_[128+itile] += scitbx::constants::pi_180 * 2.* (\n        delx * partial_partial_theta_x +\n        dely * partial_partial_theta_y\n      );\n\n      curvatures_[2*itile] += 2.;\n      curvatures_[2*itile+1] += 2.;\n      if (frame_param_no < nframes){\n        curvatures_[192+2*frame_param_no] += 2.;\n        curvatures_[193+2*frame_param_no] += 2.;\n        curvatures_[192 + 2*nframes + frame_param_no] +=2 * (\n          rotated_part_r_c_x * rotated_part_r_c_x + rotated_part_r_c_y * rotated_part_r_c_y\n        );\n      }\n\n      curvatures_[128+itile] += scitbx::constants::pi_180 * scitbx::constants::pi_180 * 2. * (\n        ( partial_partial_theta_x*partial_partial_theta_x +\n          partial_partial_theta_y*partial_partial_theta_y ) +\n        ( delx*partial_sq_theta_x + dely*partial_sq_theta_y )\n      );\n    }\n\n  }\n};\n\nnamespace boost_python { namespace {\n\n  void\n  metrology_init_module() {\n    using namespace boost::python;\n\n    typedef return_value_policy<return_by_value> rbv;\n    typedef default_call_policies dcp;\n\n    class_<mark2_iteration>(\"mark2_iteration\",no_init)\n      .def(init< >())\n      .def(init<mark2_iteration::farray, mark2_iteration::farray, mark2_iteration::farray,\n                mark2_iteration::farray, mark2_iteration::farray,\n                mark2_iteration::farray, mark2_iteration::farray,\n                mark2_iteration::iarray >(\n        (arg_(\"values\"),arg(\"tox\"),arg_(\"toy\"),arg_(\"spotcx\"),arg_(\"spotcy\"),\n         arg_(\"spotfx\"),arg_(\"spotfy\"),\n         arg_(\"master_tiles\"))))\n      .def(init<mark2_iteration::farray, mark2_iteration::farray, mark2_iteration::farray,\n                mark2_iteration::farray, mark2_iteration::farray,\n                mark2_iteration::farray, mark2_iteration::farray,\n                mark2_iteration::iarray, mark2_iteration::iarray, int const& >(\n        (arg_(\"values\"),arg(\"tox\"),arg_(\"toy\"),arg_(\"spotcx\"),arg_(\"spotcy\"),\n         arg_(\"spotfx\"),arg_(\"spotfy\"),\n         arg_(\"master_tiles\"), arg_(\"frames\"), arg_(\"nframes\"))))\n      .def(\"f\",&mark2_iteration::f)\n      .def(\"gradients\",&mark2_iteration::gradients)\n      .def(\"curvatures\",&mark2_iteration::curvatures)\n      .add_property(\"model_calcx\", make_getter(&mark2_iteration::model_calcx, rbv()))\n      .add_property(\"model_calcy\", make_getter(&mark2_iteration::model_calcy, rbv()))\n    ;\n    class_<mark3_collect_data>(\"mark3_collect_data\",no_init)\n      .def(init<mark3_collect_data::iarray,mark3_collect_data::marray>())\n      .def(\"get_first_index\",&mark3_collect_data::get_first_index)\n      .def(\"frame_indices\",&mark3_collect_data::frame_indices)\n      .def(\"selection\",&mark3_collect_data::selection)\n      .def(\"collect\",&mark3_collect_data::collect)\n      .def(\"collect_mean_position\",&mark3_collect_data::collect_mean_position)\n      .add_property(\"cx\", make_getter(&mark3_collect_data::result_model_cx, rbv()))\n      .add_property(\"cy\", make_getter(&mark3_collect_data::result_model_cy, rbv()))\n      .add_property(\"flags\", make_getter(&mark3_collect_data::result_flags, rbv()))\n      .def(\"collect_distance\",&mark3_collect_data::collect_distance)\n      .add_property(\"part_distance\", make_getter(&mark3_collect_data::result_part_distance, rbv()))\n    ;\n    class_<mark5_iteration, bases<mark2_iteration> >(\"mark5_iteration\",no_init)\n      .def(init<mark5_iteration::farray, mark5_iteration::farray, mark5_iteration::farray,\n                mark5_iteration::farray, mark5_iteration::farray,\n                mark5_iteration::farray, mark5_iteration::farray,\n                mark5_iteration::iarray, mark5_iteration::iarray, int const&,\n                mark5_iteration::vec3array >(\n        (arg_(\"values\"),arg(\"tox\"),arg_(\"toy\"),arg_(\"spotcx\"),arg_(\"spotcy\"),\n         arg_(\"spotfx\"),arg_(\"spotfy\"),\n         arg_(\"master_tiles\"), arg_(\"frames\"), arg_(\"nframes\"), arg_(\"part_distance\"))))\n    ;\n}\n}}} // namespace xfel::boost_python::<anonymous>\n\nBOOST_PYTHON_MODULE(xfel_metrology_ext)\n{\n  xfel::boost_python::metrology_init_module();\n\n}\n", "meta": {"hexsha": "dc3f5269336aafb403e1a3fd1292565d3bafd893", "size": 17791, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "xfel/metrology_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": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-03-18T12:31:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T06:27:06.000Z", "max_issues_repo_path": "xfel/metrology_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": "xfel/metrology_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": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-26T12:52:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-26T12:52:30.000Z", "avg_line_length": 41.2784222738, "max_line_length": 102, "alphanum_fraction": 0.6669102355, "num_tokens": 5130, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711604559848, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.4647116615079228}}
{"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 \"calc_gap.h\"\n#include \"rpa_util.h\"\n#include <armadillo>\n\ncx_double calc_intensity_cubic(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  /* Summing up at all the wavevectors */\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      double ky = k1 * y;\n      for(int z=-L/2; z < L/2; z++){\t\n\tdouble kz = k1 * z;      \n\n\tadd_to_sus_mat2( ts, mu, A, B, C, D, qx, qy, qz, kx, ky, kz, delta, omega, zz );\t\n\t// double e_free = energy_free_electron( t, mu, kx, ky, kz );\n\t// double e_eps = 1e-12;\n\t// if ( e_free < e_eps ) {\n\t//   /* Summing up over all k inside the Brillouin zone. */\n\t//   double diff_x = wave_vector_in_BZ( kx - qx );\n\t//   double diff_y = wave_vector_in_BZ( ky - qy );\n\t//   double diff_z = wave_vector_in_BZ( kz - qz );\t\n\t//   double e_free2 = energy_free_electron( t, mu, diff_x, diff_y, diff_z );\n\t//   add_to_sus_mat( A, B, D, e_free, e_free2, delta, omega );\n\t// }\n      }\n    }\n  }\n  \n  int n_sites = L * L * L;\n  A *= 2. / (double)n_sites;\n  B *= 2. / (double)n_sites;\n  C *= 2. / (double)n_sites;  \n  D *= 2. / (double)n_sites;  \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>(2,2) - 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  return chi;  \n  \n  // A *= 2. / (double)n_sites;\n  // B *= 2. / (double)n_sites;\n  // D *= 2. / (double)n_sites;  \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) = B;   // (B, A)\n  // chi0_mat(1,1) = D;   // (B, B)\n  // arma::cx_mat denom = arma::eye<arma::cx_mat>(2,2) - U * chi0_mat;\n  // arma::cx_mat chi_mat = chi0_mat * arma::inv(denom);\n\n  // // Double counting from A and B\n  // double factor_sublattice = 0.5;\n  // cx_double chi = factor_sublattice * factor_sublattice * ( chi_mat(0,0) - chi_mat(1,0) - chi_mat(0,1) + chi_mat(1,1) );\n  \n  // // // for check\n  // // std::cout << qx << \"  \" << qy << \"  \" << omega << \"  \" << A << \"  \" << B << \"  \" << D << \"  \" << chi_mat(0,0) << \"  \" << chi_mat(0,1) << \"  \" << chi_mat(1,0) << \"  \" << chi_mat(1,1) << \"  \" << chi << std::endl;\n\n  // return chi;  \n}\n", "meta": {"hexsha": "f8ee1c872190f337416fd785a4374a588193c474", "size": 3223, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/calc_intensity_cubic.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_cubic.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_cubic.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": 35.8111111111, "max_line_length": 218, "alphanum_fraction": 0.519081601, "num_tokens": 1212, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711604559848, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.4647116615079228}}
{"text": "#include \"powerlawCommon.h\"\n#include <boost/program_options.hpp>\n\n/**\n * @author: W.M. Otte (wim@invivonmr.uu.nl); Image Sciences Institute, UMC Utrecht, NL.\n * @date: 19-11-2009\n *\n * Estimate powerlaw scaling parameter from input distribution.\n *\n * ***************************************************************************\n * Method: \"Power-law distributions in empirical data\", Clauset et al, 2009\n * http://www.santafe.edu/~aaronc/powerlaws/\n * ***************************************************************************\n */\nclass PowerLawFit\n{\n\npublic:\n\n\ttypedef double ValueType;\n\ttypedef std::vector< ValueType > VectorType;\n\n\t/**\n\t * Power law fit.\n\t */\n\tvoid run( const std::string& inputFileName, bool nosmall, bool finite,\n\t\t\t\t\tdouble startXmin, double incrementXmin, double endXmin,\n\t\t\t\t\t\tbool bootstrap, unsigned int bootstrapIterations, bool verbose )\n\t{\n\t\t// [ 1 ] read input from text file ...\n\t\tVectorType values = getInput( inputFileName );\n\n\t\t// [ 2 ] bootstrap or single fit ...\n\t\tVectorType results;\n\n\t\tif ( bootstrap )\n\t\t{\n\t\t\tgraph::Powerlaw< ValueType >::BootstrapFit( values, results, nosmall, finite, startXmin, incrementXmin, endXmin, bootstrapIterations, verbose );\n\n\t\t\tif ( ! results.empty() )\n\t\t\t{\n\t\t\t\tstd::cout << \"Alpha,\" << results.at( 0 ) <<  std::endl;\n\t\t\t\tstd::cout << \"Xmin,\" << results.at( 1 ) << std::endl;\n\t\t\t\tstd::cout << \"Log-likelihood,\" << results.at( 2 ) << std::endl;\n\t\t\t\tstd::cout << \"Alpha_sd,\" << results.at( 3 ) <<  std::endl;\n\t\t\t\tstd::cout << \"Xmin_sd,\" << results.at( 4 ) << std::endl;\n\t\t\t\tstd::cout << \"Log-likelihood_sd,\" << results.at( 5 ) << std::endl;\n\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tstd::cerr << \"*** ERROR ***: maximum likelihood \"\n\t\t\t\t\t\"bootstrap estimation failed! -> check input ...\" << std::endl;\n\t\t\t}\n\n\t\t}\n\t\telse\n\t\t{\n\t\t\tgraph::Powerlaw< ValueType >::SingleFit( values, results, nosmall, finite,\n\t\t\t\t\tstartXmin, incrementXmin, endXmin );\n\n\t\t\tif ( ! results.empty() )\n\t\t\t{\n\t\t\t\tstd::cout << \"Alpha,\" << results.at( 0 ) << std::endl;\n\t\t\t\tstd::cout << \"Xmin,\" << results.at( 1 ) << std::endl;\n\t\t\t\tstd::cout << \"Log-likelihood,\" << results.at( 2 ) << std::endl;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tstd::cerr << \"*** ERROR ***: maximum likelihood \"\n\t\t\t\t\t\"single estimation failed! -> check input ...\" << std::endl;\n\t\t\t}\n\t\t}\n\t}\n\nprotected:\n\n\t/**\n\t * Return input from given text file as vector.\n\t */\n\tVectorType getInput( const std::string& input )\n\t{\n\t\tstd::ifstream inFile;\n\n\t\tinFile.open( input.c_str() );\n\t\tif ( !inFile )\n\t\t{\n\t\t\tstd::cout << \"*** ERROR ***: Unable to open: \" << input << \".\" << std::endl;\n\t\t\texit( EXIT_FAILURE );\n\t\t}\n\n\t\tdouble x;\n\t\tVectorType output;\n\n\t\twhile ( inFile >> x )\n\t\t{\n\t\t\toutput.push_back( x );\n\t\t}\n\t\tinFile.close();\n\n\t\t/**\n\t\t * Negative values will be converted to complex numbers in matlab,\n\t\t * but not with the stl ...\n\t\t *\n\t\t * No support is given (yet) for complex number mle.\n\t\t */\n\t\tif ( *( std::min_element( output.begin(), output.end() ) ) < 0 )\n\t\t{\n\t\t\tstd::cerr << \"*** ERROR ***: Negative input not supported!\" << std::endl;\n\t\t\texit (EXIT_FAILURE );\n\t\t}\n\n\t\treturn output;\n\t}\n};\n\n// ************************************************************************************\n\n/**\n * Throw error if required option is not specified.\n */\nvoid required_option( const boost::program_options::variables_map& vm,\n\t\tconst std::string& required_option )\n{\n\tif ( vm.count( required_option ) == 0 )\n\t\tthrow std::logic_error( \"Option: '\" + required_option + \"' is required!\" );\n}\n\n/**\n * Fit powerlaw to list of numbers.\n */\nint main(int argc, char* argv[])\n{\n\tnamespace po = boost::program_options;\n\n\t// application description ...\n\tstd::string description = \"Fits a power-law distributional model to data.\\n\";\n\n\t// options ...\n\tstd::string input;\n\n\tbool nosmall;\n\tbool finite;\n\tbool bootstrap;\n\tbool verbose;\n\n\tdouble startXmin;\n\tdouble incrementXmin;\n\tdouble endXmin;\n\n\tunsigned int bootstrapIterations;\n\n\ttry {\n\n        po::options_description desc(\"Available options\");\n\n        desc.add_options()\n\n            ( \"input,i\", po::value< std::string >( &input )\n            \t\t, \"string: input file with distribution values in column format.\" )\n\n            ( \"finite,f\", po::value< bool >( &finite )\n            \t\t->default_value( false )\n            \t\t->zero_tokens()\n            \t\t, \"bool: use an experimental finite-size correction.\" )\n\n            ( \"verbose,v\", po::value< bool >( &verbose )\n\t\t\t\t\t->default_value( false )\n            \t\t->zero_tokens()\n            \t\t, \"bool: print bootstrap status.\" )\n\n            ( \"nosmall,s\", po::value< bool >( &nosmall )\n            \t\t->default_value( false )\n            \t\t->zero_tokens()\n            \t\t, \"bool: truncate the search over xmin values before the finite-size bias becomes significant.\" )\n\n            ( \"bootstrap,b\", po::value< bool >( &bootstrap )\n            \t\t->default_value( false )\n            \t\t->zero_tokens()\n            \t\t, \"bool: run non-parametric bootstrap instead of single estimation.\" )\n\n            ( \"start-xmin,x\", po::value< double >( &startXmin )\n            \t\t->default_value( 1.5 )\n            \t\t, \"float: start value for discrete xmin estimation.\" )\n\n            ( \"increment-xmin,y\", po::value< double >( &incrementXmin )\n            \t\t->default_value( 0.01 )\n            \t\t, \"float: increment value for discrete xmin estimation.\" )\n\n            ( \"end-xmin,z\", po::value< double >( &endXmin )\n            \t\t->default_value( 3.5 )\n            \t\t, \"float: end value for discrete xmin estimation.\" )\n\n            ( \"bootstrap-iterations,n\", po::value< unsigned int >( &bootstrapIterations )\n            \t\t->default_value( 1000 )\n            \t\t, \"uint: bootstrap iterations.\" )\n\n            ( \"help,h\", \"bool: produce help message.\" )\n        ;\n\n        po::variables_map vm;\n        po::store( po::parse_command_line( argc, argv, desc ), vm );\n        po::notify( vm );\n\n        // help message ...\n        if ( vm.count( \"help\" ) )\n        {\n            std::cout << argv[0] << \": \" << description << std::endl;\n        \tstd::cout << desc << \"\\n\";\n\n        \treturn EXIT_SUCCESS;\n        }\n\n        // required options ...\n        required_option( vm, \"input\" );\n\n        // run application ...\n        PowerLawFit powerlawFit;\n\n    \tpowerlawFit.run( input, nosmall, finite,\n\t\t\t\t\t\t\tstartXmin, incrementXmin, endXmin,\n\t\t\t\t\t\t\t\t\t\t\tbootstrap, bootstrapIterations, verbose );\n\n    }\n    catch( std::exception& e )\n    {\n        std::cerr << \"*** ERROR ***: \" << e.what() << \"\\n\";\n        std::cerr << \"Use \\\"\" << argv[0]\n        \t\t  << \" --help\\\" for information about application usage.\"\n        \t\t  << std::endl;\n\n        return EXIT_FAILURE;\n    }\n\n    return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "367194ae23936062c85f660e00073d166d5bf3ed", "size": 6619, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "powerlawFit.cpp", "max_stars_repo_name": "wmotte/powerlaw", "max_stars_repo_head_hexsha": "7672554794506daccf3823fd3c7e7a81a384cc0d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "powerlawFit.cpp", "max_issues_repo_name": "wmotte/powerlaw", "max_issues_repo_head_hexsha": "7672554794506daccf3823fd3c7e7a81a384cc0d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "powerlawFit.cpp", "max_forks_repo_name": "wmotte/powerlaw", "max_forks_repo_head_hexsha": "7672554794506daccf3823fd3c7e7a81a384cc0d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-04-25T21:27:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-25T21:27:35.000Z", "avg_line_length": 27.9282700422, "max_line_length": 147, "alphanum_fraction": 0.5523492975, "num_tokens": 1659, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.4647012234235746}}
{"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\n/** \\example amg.cpp\n*\n*   This tutorial shows the use of algebraic multigrid (AMG) preconditioners.\n*   \\warning AMG is currently only experimentally available with the OpenCL backend and depends on Boost.uBLAS\n*\n*   We start with some rather general includes and preprocessor variables:\n**/\n\n\n#ifndef NDEBUG     //without NDEBUG the performance of sparse ublas matrices is poor.\n #define BOOST_UBLAS_NDEBUG\n#endif\n\n#include <boost/numeric/ublas/matrix_sparse.hpp>\n#include <boost/numeric/ublas/operation_sparse.hpp>\n\n#define VIENNACL_WITH_UBLAS 1\n\n#include \"viennacl/vector.hpp\"\n#include \"viennacl/coordinate_matrix.hpp\"\n#include \"viennacl/compressed_matrix.hpp\"\n#include \"viennacl/linalg/ilu.hpp\"\n#include \"viennacl/linalg/cg.hpp\"\n#include \"viennacl/linalg/bicgstab.hpp\"\n#include \"viennacl/io/matrix_market.hpp\"\n#include \"viennacl/linalg/norm_2.hpp\"\n\n/**\n* Import the AMG functionality:\n**/\n#include \"viennacl/linalg/amg.hpp\"\n\n/**\n* Some more includes:\n**/\n#include <iostream>\n#include <vector>\n#include <ctime>\n#include \"vector-io.hpp\"\n\n\n/** <h2>Part 1: Worker routines</h2>\n*\n*  <h3>Run the Solver</h3>\n*   Runs the provided solver specified in the `solver` object with the provided preconditioner `precond`\n**/\ntemplate<typename MatrixType, typename VectorType, typename SolverTag, typename PrecondTag>\nvoid run_solver(MatrixType const & matrix, VectorType const & rhs, VectorType const & ref_result, SolverTag const & solver, PrecondTag const & precond)\n{\n  VectorType result(rhs);\n  VectorType residual(rhs);\n\n  result = viennacl::linalg::solve(matrix, rhs, solver, precond);\n  residual -= viennacl::linalg::prod(matrix, result);\n  std::cout << \"  > Relative residual: \" << viennacl::linalg::norm_2(residual) / viennacl::linalg::norm_2(rhs) << std::endl;\n  std::cout << \"  > Iterations: \" << solver.iters() << std::endl;\n  result -= ref_result;\n  std::cout << \"  > Relative deviation from result: \" << viennacl::linalg::norm_2(result) / viennacl::linalg::norm_2(ref_result) << std::endl;\n}\n\n/** <h3>Compare AMG preconditioner for uBLAS and ViennaCL types</h3>\n*\n*  The AMG implementations in ViennaCL can be used with uBLAS types as well as ViennaCL types.\n*  This function compares the two in terms of execution time.\n**/\ntemplate<typename ScalarType>\nvoid run_amg(viennacl::linalg::cg_tag & cg_solver,\n             boost::numeric::ublas::vector<ScalarType> & /*ublas_vec*/,\n             boost::numeric::ublas::vector<ScalarType> & /*ublas_result*/,\n             boost::numeric::ublas::compressed_matrix<ScalarType> & ublas_matrix,\n             viennacl::vector<ScalarType> & vcl_vec,\n             viennacl::vector<ScalarType> & vcl_result,\n             viennacl::compressed_matrix<ScalarType> & vcl_compressed_matrix,\n             std::string info,\n             viennacl::linalg::amg_tag & amg_tag)\n{\n\n  viennacl::linalg::amg_precond<boost::numeric::ublas::compressed_matrix<ScalarType> > ublas_amg = viennacl::linalg::amg_precond<boost::numeric::ublas::compressed_matrix<ScalarType> > (ublas_matrix, amg_tag);\n  boost::numeric::ublas::vector<ScalarType> avgstencil;\n  unsigned int coarselevels = amg_tag.get_coarselevels();\n\n  std::cout << \"-- CG with AMG preconditioner, \" << info << \" --\" << std::endl;\n\n  std::cout << \" * Setup phase (ublas types)...\" << std::endl;\n\n  // Coarse level measure might have been changed during setup. Reload!\n  ublas_amg.tag().set_coarselevels(coarselevels);\n  ublas_amg.setup();\n\n  std::cout << \" * Operator complexity: \" << ublas_amg.calc_complexity(avgstencil) << std::endl;\n\n  amg_tag.set_coarselevels(coarselevels);\n  viennacl::linalg::amg_precond<viennacl::compressed_matrix<ScalarType> > vcl_amg = viennacl::linalg::amg_precond<viennacl::compressed_matrix<ScalarType> > (vcl_compressed_matrix, amg_tag);\n  std::cout << \" * Setup phase (ViennaCL types)...\" << std::endl;\n  vcl_amg.tag().set_coarselevels(coarselevels);\n  vcl_amg.setup();\n\n  std::cout << \" * CG solver (ublas types)...\" << std::endl;\n  //run_solver(ublas_matrix, ublas_vec, ublas_result, cg_solver, ublas_amg);\n\n  std::cout << \" * CG solver (ViennaCL types)...\" << std::endl;\n  run_solver(vcl_compressed_matrix, vcl_vec, vcl_result, cg_solver, vcl_amg);\n\n}\n\n/**\n*  <h2>Part 2: Run Solvers with AMG Preconditioners</h2>\n*\n*  In this\n**/\nint main()\n{\n  /**\n  * Print some device info at the beginning. If there is more than one OpenCL device available, use the second device.\n  **/\n  std::cout << std::endl;\n  std::cout << \"----------------------------------------------\" << std::endl;\n  std::cout << \"               Device Info\" << std::endl;\n  std::cout << \"----------------------------------------------\" << std::endl;\n\n#ifdef VIENNACL_WITH_OPENCL\n  // Optional: Customize OpenCL backend\n  viennacl::ocl::platform pf = viennacl::ocl::get_platforms()[0];\n  std::vector<viennacl::ocl::device> const & devices = pf.devices();\n\n  // Optional: Set first device to first context:\n  viennacl::ocl::setup_context(0, devices[0]);\n\n  // Optional: 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  std::cout << viennacl::ocl::current_device().info() << std::endl;\n  viennacl::context ctx(viennacl::ocl::get_context(1));\n#else\n  viennacl::context ctx;\n#endif\n\n  typedef float    ScalarType;  // feel free to change this to double if supported by your device\n\n\n  /**\n  * Set up the matrices and vectors for the iterative solvers (cf. iterative.cpp)\n  **/\n  boost::numeric::ublas::vector<ScalarType> ublas_vec, ublas_result;\n  boost::numeric::ublas::compressed_matrix<ScalarType> ublas_matrix;\n\n  // Read matrix\n  if (!viennacl::io::read_matrix_market_file(ublas_matrix, \"../examples/testdata/mat65k.mtx\"))\n  {\n    std::cout << \"Error reading Matrix file\" << std::endl;\n    return EXIT_FAILURE;\n  }\n\n  // Set up rhs and result vector\n  if (!readVectorFromFile(\"../examples/testdata/rhs65025.txt\", ublas_vec))\n  {\n    std::cout << \"Error reading RHS file\" << std::endl;\n    return 0;\n  }\n\n  if (!readVectorFromFile(\"../examples/testdata/result65025.txt\", ublas_result))\n  {\n    std::cout << \"Error reading Result file\" << std::endl;\n    return 0;\n  }\n\n  viennacl::vector<ScalarType> vcl_vec(ublas_vec.size(), ctx);\n  viennacl::vector<ScalarType> vcl_result(ublas_vec.size(), ctx);\n  viennacl::compressed_matrix<ScalarType> vcl_compressed_matrix(ublas_vec.size(), ublas_vec.size(), ctx);\n\n  // Copy to GPU\n  viennacl::copy(ublas_matrix, vcl_compressed_matrix);\n  viennacl::copy(ublas_vec, vcl_vec);\n  viennacl::copy(ublas_result, vcl_result);\n\n  /**\n  * Instantiate a tag for the conjugate gradient solver, the AMG preconditioner tag, and create an AMG preconditioner object:\n  **/\n  viennacl::linalg::cg_tag cg_solver;\n  viennacl::linalg::amg_tag amg_tag;\n\n  /**\n  * Run solver without preconditioner. This serves as a baseline for comparison.\n  * Note that iterative solvers without preconditioner on GPUs can be very efficient because they map well to the massively parallel hardware.\n  **/\n  std::cout << \"-- CG solver (CPU, no preconditioner) --\" << std::endl;\n  run_solver(ublas_matrix, ublas_vec, ublas_result, cg_solver, viennacl::linalg::no_precond());\n\n  std::cout << \"-- CG solver (GPU, no preconditioner) --\" << std::endl;\n  run_solver(vcl_compressed_matrix, vcl_vec, vcl_result, cg_solver, viennacl::linalg::no_precond());\n\n  /**\n  * Generate the setup for an AMG preconditioner of Ruge-Stueben type with direct interpolation (RS+DIRECT) and run the solver:\n  **/\n  amg_tag = viennacl::linalg::amg_tag(VIENNACL_AMG_COARSE_RS,       // coarsening strategy\n                                      VIENNACL_AMG_INTERPOL_DIRECT, // interpolation strategy\n                                      0.25, // strength of dependence threshold\n                                      0.2,  // interpolation weight\n                                      0.67, // jacobi smoother weight\n                                      3,    // presmoothing steps\n                                      3,    // postsmoothing steps\n                                      0);   // number of coarse levels to be used (0: automatically use as many as reasonable)\n  run_amg (cg_solver, ublas_vec, ublas_result, ublas_matrix, vcl_vec, vcl_result, vcl_compressed_matrix, \"RS COARSENING, DIRECT INTERPOLATION\", amg_tag);\n\n  /**\n  * Generate the setup for an AMG preconditioner of Ruge-Stueben type with classic interpolation (RS+CLASSIC) and run the solver:\n  **/\n  amg_tag = viennacl::linalg::amg_tag(VIENNACL_AMG_COARSE_RS, VIENNACL_AMG_INTERPOL_CLASSIC, 0.25, 0.2, 0.67, 3, 3, 0);\n  run_amg ( cg_solver, ublas_vec, ublas_result, ublas_matrix, vcl_vec, vcl_result, vcl_compressed_matrix, \"RS COARSENING, CLASSIC INTERPOLATION\", amg_tag);\n\n  /**\n  * Generate the setup for an AMG preconditioner of Ruge-Stueben type with only one pass and direct interpolation (ONEPASS+DIRECT)\n  **/\n  amg_tag = viennacl::linalg::amg_tag(VIENNACL_AMG_COARSE_ONEPASS, VIENNACL_AMG_INTERPOL_DIRECT,0.25, 0.2, 0.67, 3, 3, 0);\n  run_amg (cg_solver, ublas_vec, ublas_result, ublas_matrix, vcl_vec, vcl_result, vcl_compressed_matrix, \"ONEPASS COARSENING, DIRECT INTERPOLATION\", amg_tag);\n\n  /**\n  * Generate the setup for an AMG preconditioner of parallel Ruge-Stueben type with direct interpolation (RS0+DIRECT)\n  **/\n  amg_tag = viennacl::linalg::amg_tag(VIENNACL_AMG_COARSE_RS0, VIENNACL_AMG_INTERPOL_DIRECT, 0.25, 0.2, 0.67, 3, 3, 0);\n  run_amg (cg_solver, ublas_vec, ublas_result, ublas_matrix, vcl_vec, vcl_result, vcl_compressed_matrix, \"RS0 COARSENING, DIRECT INTERPOLATION\", amg_tag);\n\n  /**\n  * Generate the setup for an AMG preconditioner of parallel Ruge-Stueben type (with communication across domains) and use direct interpolation (RS3+DIRECT)\n  **/\n  amg_tag = viennacl::linalg::amg_tag(VIENNACL_AMG_COARSE_RS3, VIENNACL_AMG_INTERPOL_DIRECT, 0.25, 0.2, 0.67, 3, 3, 0);\n  run_amg (cg_solver, ublas_vec, ublas_result, ublas_matrix, vcl_vec, vcl_result, vcl_compressed_matrix, \"RS3 COARSENING, DIRECT INTERPOLATION\", amg_tag);\n\n  /**\n  * Generate the setup for an AMG preconditioner which as aggregation-based (AG)\n  **/\n  amg_tag = viennacl::linalg::amg_tag(VIENNACL_AMG_COARSE_AG, VIENNACL_AMG_INTERPOL_AG, 0.08, 0, 0.67, 3, 3, 0);\n  run_amg (cg_solver, ublas_vec, ublas_result, ublas_matrix, vcl_vec, vcl_result, vcl_compressed_matrix, \"AG COARSENING, AG INTERPOLATION\", amg_tag);\n\n  /**\n  * Generate the setup for an AMG preconditioner with smoothed aggregation (SA)\n  **/\n  amg_tag = viennacl::linalg::amg_tag(VIENNACL_AMG_COARSE_AG, VIENNACL_AMG_INTERPOL_SA, 0.08, 0.67, 0.67, 3, 3, 0);\n  run_amg (cg_solver, ublas_vec, ublas_result, ublas_matrix, vcl_vec, vcl_result, vcl_compressed_matrix, \"AG COARSENING, SA INTERPOLATION\",amg_tag);\n\n\n  /**\n  *  That's it.\n  **/\n  std::cout << \"!!!! TUTORIAL COMPLETED SUCCESSFULLY !!!!\" << std::endl;\n\n  return EXIT_SUCCESS;\n}\n\n", "meta": {"hexsha": "af0fa482fce05e61893779391834bcb68e3bec67", "size": 11700, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/tutorial/amg.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/amg.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/amg.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": 43.1734317343, "max_line_length": 208, "alphanum_fraction": 0.6783760684, "num_tokens": 3250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.4647012234235746}}
{"text": "//#define BZ_DISABLE_RESTRICT\n#define BZ_ARRAY_2D_NEW_STENCIL_TILING\n\n#include <blitz/array.h>\n#include <blitz/timer.h>\n#include <blitz/benchext.h>\n#include <blitz/vector2.h>\n\n#ifdef BZ_HAVE_STD\n  #include <fstream>\n#else\n  #include <fstream.h>\n#endif\n\nBZ_USING_NAMESPACE(blitz)\n\n#if defined(BZ_FORTRAN_SYMBOLS_WITH_TRAILING_UNDERSCORES)\n #define echo_f90           echo_f90_\n #define echo_f77           echo_f77_\n #define echo_f90_tuned     echo_f90_tuned_\n #define echo_f77tuned      echo_f77tuned_\n#elif defined(BZ_FORTRAN_SYMBOLS_WITH_DOUBLE_TRAILING_UNDERSCORES)\n #define echo_f90           echo_f90__\n #define echo_f77           echo_f77__\n #define echo_f90_tuned     echo_f90_tuned__\n #define echo_f77tuned      echo_f77tuned__\n#elif defined(BZ_FORTRAN_SYMBOLS_CAPS)\n #define echo_f90           ECHO_F90\n #define echo_f77           ECHO_F77\n #define echo_f90_tuned     ECHO_F90_TUNED\n #define echo_f77tuned      ECHO_F77TUNED\n#endif\n\nextern \"C\" {\nvoid echo_f90(int& N, int& niters, float& check);\nvoid echo_f77(int& N, int& niters, float& check);\nvoid echo_f90_tuned(int& N, int& niters, float& check);\nvoid echo_f77tuned(int& N, int& niters, float& check);\n}\n\nvoid f77(BenchmarkExt<int>&);\nvoid f90(BenchmarkExt<int>&);\nvoid f77_tuned(BenchmarkExt<int>&);\nvoid f90_tuned(BenchmarkExt<int>&);\n\nvoid echo_BlitzInterlacedCycled(BenchmarkExt<int>&);\nvoid echo_BlitzCycled(BenchmarkExt<int>&);\nvoid echo_BlitzRaw(BenchmarkExt<int>&);\nvoid echo_BlitzStencil(BenchmarkExt<int>&);\n\nint main()\n{\n    Timer timer;\n    float check;\n    int numBenchmarks = 6;\n#ifdef FORTRAN_90\n    numBenchmarks+=2;\n#endif\n\n    BenchmarkExt<int> bench(\"Acoustic 2D Benchmark\", numBenchmarks);\n    const int numSizes=7;\n    bench.setNumParameters(numSizes);\n    Vector<int> parameters(numSizes); \n    parameters=10*pow(2.0,tensor::i);\n    Vector<double> flops(numSizes); \n    flops=(parameters-2)*(parameters-2) * 9.0;\n    Vector<long> iters(numSizes);\n    // iters must be divisible by 3 for tuned fortran versions\n    iters=cast<long>(100000000/flops)*3;\n\n    bench.setParameterVector(parameters);\n    bench.setParameterDescription(\"Matrix size\");\n    bench.setIterations(iters);\n    bench.setOpsPerIteration(flops);\n    bench.setDependentVariable(\"flops\");\n    bench.beginBenchmarking();\n\n    echo_BlitzRaw(bench);\n    echo_BlitzStencil(bench);\n\n#if 0\n    echo_BlitzInterlaced(bench, c);\n#endif\n\n    echo_BlitzCycled(bench);\n    echo_BlitzInterlacedCycled(bench);\n\n#ifdef FORTRAN_90\n    f90(bench);\n    f90_tuned(bench);\n#endif\n\n    f77(bench);\n    f77_tuned(bench);\n\n    bench.endBenchmarking();\n    bench.saveMatlabGraph(\"acoustic.m\");\n\n    return 0;\n}\n\nvoid checkArray(Array<float,2>& A, int N)\n{\n    float check = 0.0;\n    for (int i=0; i < N; ++i)\n        for (int j=0; j < N; ++j)\n            check += ((i+1)*N + j + 1) * A(i,j);\n\n    cout << \"Array check: \" << check << endl;\n}\n\nvoid setInitialConditions(Array<float,2>& c, Array<float,2>& P1, \n    Array<float,2>& P2, Array<float,2>& P3, int N);\n\n\nvoid echo_BlitzRaw(BenchmarkExt<int>&bench)\n{\n    bench.beginImplementation(\"Blitz++ (raw)\");\n    while (!bench.doneImplementationBenchmark())\n    {\n      int N = bench.getParameter();\n      int niters = bench.getIterations();\n\n    Array<float,2> P1(N,N), P2(N,N), P3(N,N), c(N,N);\n    Range I(1,N-2), J(1,N-2);\n\n    setInitialConditions(c, P1, P2, P3, N);\n    checkArray(P2, N);\n    checkArray(c, N);\n\n    bench.start();\n    for (int iter=0; iter < niters; ++iter)\n    {\n        P3(I,J) = (2-4*c(I,J)) * P2(I,J)\n          + c(I,J)*(P2(I-1,J) + P2(I+1,J) + P2(I,J-1) + P2(I,J+1))\n          - P1(I,J);\n\n        P1 = P2;\n        P2 = P3;\n    }\n    bench.stop();\n\n    cout << P1(N/2-1,(7*N)/8-1) << endl;\n    }\n\n    bench.endImplementation();\n\n    \n#if 0\nofstream ofs(\"testecho.m\");\nofs << \"A = [\";\nfor (int i=0; i < N; ++i)\n{\n  for (int j=0; j < N; ++j)\n  {\n    ofs << int(8192*P2(i,j)+1024*c(i,j)) << \" \";\n  }\n  if (i < N-1)\n    ofs << \";\" << endl;\n}\nofs << \"];\" << endl;\n#endif\n\n}\n\nvoid echo_BlitzCycled(BenchmarkExt<int>&bench)\n{\n    bench.beginImplementation(\"Blitz++ (cycled)\");\n    while (!bench.doneImplementationBenchmark())\n    {\n    int N = bench.getParameter();\n    int niters = bench.getIterations();\n    cout << bench.currentImplementation() << \" N=\" << N << endl;\n\n    Array<float,2> P1(N,N), P2(N,N), P3(N,N), c(N,N);\n    Range I(1,N-2), J(1,N-2);\n\n    setInitialConditions(c, P1, P2, P3, N);\n    checkArray(P2, N);\n    checkArray(c, N);\n\n    bench.start();\n    for (int iter=0; iter < niters; ++iter)\n    {\n        P3(I,J) = (2-4*c(I,J)) * P2(I,J)\n          + c(I,J)*(P2(I-1,J) + P2(I+1,J) + P2(I,J-1) + P2(I,J+1))\n          - P1(I,J);\n\n        cycleArrays(P1,P2,P3);\n    }\n    bench.stop();\n\n    cout << P1(N/2-1,(7*N)/8-1) << endl;\n    }\n\n    bench.endImplementation();\n}\n\nvoid echo_BlitzInterlacedCycled(BenchmarkExt<int>&bench)\n{\n    bench.beginImplementation(\"Blitz++ (interlaced & cycled)\");\n    while (!bench.doneImplementationBenchmark())\n    {\n    int N = bench.getParameter();\n    int niters = bench.getIterations();\n    cout << bench.currentImplementation() << \" N=\" << N << endl;\n\n    Array<float,2> P1, P2, P3, c;\n    allocateArrays(shape(N,N), P1, P2, P3, c);\n    Range I(1,N-2), J(1,N-2);\n\n    setInitialConditions(c, P1, P2, P3, N);\n    checkArray(P2, N);\n    checkArray(c, N);\n\n    bench.start();\n    for (int iter=0; iter < niters; ++iter)\n    {\n        P3(I,J) = (2-4*c(I,J)) * P2(I,J)\n          + c(I,J)*(P2(I-1,J) + P2(I+1,J) + P2(I,J-1) + P2(I,J+1))\n          - P1(I,J);\n\n        cycleArrays(P1,P2,P3);\n    }\n    bench.stop();\n\n    cout << P1(N/2-1,(7*N)/8-1) << endl;\n    }\n\n    bench.endImplementation();\n}\n\nBZ_DECLARE_STENCIL4(acoustic2D,P1,P2,P3,c)\n  P3 = 2 * P2 + c * Laplacian2D_stencilop(P2) - P1;\nBZ_STENCIL_END\n\nvoid echo_BlitzStencil(BenchmarkExt<int>&bench)\n{\n    bench.beginImplementation(\"Blitz++ (stencil)\");\n    while (!bench.doneImplementationBenchmark())\n    {\n    int N = bench.getParameter();\n    int niters = bench.getIterations();\n    cout << bench.currentImplementation() << \" N=\" << N << endl;\n\n    Array<float,2> P1, P2, P3, c;\n    allocateArrays(shape(N,N), P1, P2, P3, c);\n\n    setInitialConditions(c, P1, P2, P3, N);\n    checkArray(P2, N);\n    checkArray(c, N);\n\n    bench.start();\n    for (int iter=0; iter < niters; ++iter)\n    {\n        applyStencil(acoustic2D(), P1, P2, P3, c);\n        cycleArrays(P1,P2,P3);\n    }\n    bench.stop();\n\n    cout << P1(N/2-1,(7*N)/8-1) << endl;\n    }\n\n    bench.endImplementation();\n}\n\nvoid setInitialConditions(Array<float,2>& c, Array<float,2>& P1,\n    Array<float,2>& P2, Array<float,2>& P3, int N)\n{\n    // Set the velocity field\n    c = 0.2;\n\n    // Solid block with which the pulse collides\n    int blockLeft = 0;\n    int blockRight = int(2*N/5.0-1);\n    int blockTop = int(N/3-1);\n    int blockBottom = int(2*N/3.0-1);\n    c(Range(blockTop,blockBottom),Range(blockLeft,blockRight)) = 0.5;\n\n    // Channel directing the pulse leftwards\n    int channelLeft = int(4*N/5.0-1);\n    int channelRight = N-1;\n    int channel1Height = int(3*N/8.0-1);\n    int channel2Height = int(5*N/8.0-1);\n    c(channel1Height,Range(channelLeft,channelRight)) = 0.0;\n    c(channel2Height,Range(channelLeft,channelRight)) = 0.0;\n\n    // Initial pressure distribution: gaussian pulse inside the channel\n    BZ_USING_NAMESPACE(blitz::tensor)\n    int cr = int(N/2-1);\n    int cc = int(7.0*N/8.0-1);\n    // pow2 is not defined for pod types.\n    float s2 = 64.0 * 9.0 / pow(N/2.0,2);\n    cout << \"cr = \" << cr << \" cc = \" << cc << \" s2 = \" << s2 << endl;\n    P1 = 0.0;\n    P2 = exp(-(pow2(i-cr)+pow2(j-cc)) * s2);\n    P3 = 0.0;\n}\n\n\nvoid f77(BenchmarkExt<int>&bench)\n{\n  bench.beginImplementation(\"Fortran77\");\n    while (!bench.doneImplementationBenchmark())\n    {\n  int N = bench.getParameter();\n  int niters = bench.getIterations();\n    cout << bench.currentImplementation() << \" N=\" << N << endl;\n  float check;\n  bench.start();\n  echo_f77(N, niters, check);\n  bench.stop();\n    cout << check << endl;\n    }\n    bench.endImplementation();\n};\n\nvoid f77_tuned(BenchmarkExt<int>&bench)\n{\n  bench.beginImplementation(\"Fortran77 (tuned)\");\n    while (!bench.doneImplementationBenchmark())\n    {\n  int N = bench.getParameter();\n  int niters = bench.getIterations();\n    cout << bench.currentImplementation() << \" N=\" << N << endl;\n  float check;\n  bench.start();\n  echo_f77tuned(N, niters, check);\n  bench.stop();\n    cout << check << endl;\n    }\n\n    bench.endImplementation();\n};\n\nvoid f90(BenchmarkExt<int>&bench)\n{\n  bench.beginImplementation(\"Fortran90\");\n    while (!bench.doneImplementationBenchmark())\n    {\n  int N = bench.getParameter();\n  int niters = bench.getIterations();\n    cout << bench.currentImplementation() << \" N=\" << N << endl;\n  float check;\n  bench.start();\n  echo_f90(N, niters, check);\n  bench.stop();\n    cout << check << endl;\n    }\n\n    bench.endImplementation();\n};\nvoid f90_tuned(BenchmarkExt<int>&bench)\n{\n  bench.beginImplementation(\"Fortran90 (tuned)\");\n    while (!bench.doneImplementationBenchmark())\n    {\n  int N = bench.getParameter();\n  int niters = bench.getIterations();\n    cout << bench.currentImplementation() << \" N=\" << N << endl;\n  float check;\n  bench.start();\n  echo_f90_tuned(N, niters, check);\n  bench.stop();\n    cout << check << endl;\n    }\n\n    bench.endImplementation();\n};\n", "meta": {"hexsha": "ad12fa59690383ce7e4478050528dea924fd56ef", "size": 9293, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depspawn-blitz-0.10/benchmarks/acoustic.cpp", "max_stars_repo_name": "fraguela/depspawn", "max_stars_repo_head_hexsha": "b5760f4c0d38a1b245ee5274e2ccc5c5fe2d3d45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-04-12T11:05:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T11:10:27.000Z", "max_issues_repo_path": "ibtk/third_party/blitz-0.10/benchmarks/acoustic.cpp", "max_issues_repo_name": "MSV-Project/IBAMR", "max_issues_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ibtk/third_party/blitz-0.10/benchmarks/acoustic.cpp", "max_forks_repo_name": "MSV-Project/IBAMR", "max_forks_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1162162162, "max_line_length": 71, "alphanum_fraction": 0.6174539976, "num_tokens": 2902, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370111, "lm_q2_score": 0.6584175139669998, "lm_q1q2_score": 0.4647012234235746}}
{"text": "#include <ros/ros.h>\n#include <sensor_msgs/PointCloud2.h>\n#include <pcl_conversions/pcl_conversions.h>\n#include <pcl_ros/point_cloud.h>\n#include <pcl/filters/filter.h>\n#include <pcl/kdtree/kdtree_flann.h>\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n#include <vector>\n#include <fstream>\n\nusing Point = pcl::PointXYZI;\nusing PointCloud = pcl::PointCloud<Point>;\n\nvoid ros_callback(const sensor_msgs::PointCloud2ConstPtr& msg)\n{\n    PointCloud::Ptr pc(new PointCloud);\n    std::vector<int> indices;\n    pcl::KdTreeFLANN<Point> kdtree; // \u7528\u4e8e\u641c\u7d22\u6700\u8fd1\u70b9\n\n\n    // sensor_msgs::PointCloud2 -> pcl::PointCloud\n    pcl::fromROSMsg(*msg, *pc);\n\n    // is_dense \u7528\u4e8e\u8868\u793a\u70b9\u4e91\u4e2d\u7684\u6240\u6709\u6570\u636e\u662f\u5426\u5408\u6cd5\n    // \u8bbe\u7f6e\u4e3a \u5426\uff0c\u8ba9\u540e\u7eed\u7684\u51fd\u6570\u518d\u68c0\u67e5\u4e00\u904d\uff0c\u628a Nan\uff08not a number\uff09\n    // \u8fd9\u79cd\u4e0d\u5408\u6cd5\u7684\u6570\u503c\u5168\u90e8\u53bb\u6389\n    pc->is_dense = false;\n    pcl::removeNaNFromPointCloud(*pc, *pc, indices);\n\n    // \u521d\u59cb\u5316 kd \u6811\n    kdtree.setInputCloud(pc);\n\n    // \u63d0\u524d\u5c06\u9700\u8981\u5728\u5faa\u73af\u4e2d\u7528\u5230\u7684\u53d8\u91cf\u521d\u59cb\u5316\u597d\uff0c\u653e\u7f6e\u5728\u5faa\u73af\u4e2d\u91cd\u590d\u6784\u9020\u53d8\u91cf\u4e0e\u6790\u6784\uff0c\u62d6\u6162\u7a0b\u5e8f\u8fd0\u884c\u901f\u5ea6\n    const int k = 20;                           // \u4e34\u8fd1\u70b9\u6570\u91cf\uff0c\u6839\u636e\u4f5c\u4e1a\u8981\u6c42\u8bbe\u7f6e\u4e3a 20\n    std::vector<int> point_idx(k);              // \u7528\u6765\u4fdd\u5b58\u4e34\u8fd1\u70b9\u518d\u539f\u6765\u70b9\u4e91\u4e2d\u7684\u4e0b\u6807\n    std::vector<float> point_sq_dis(k);         // \u7528\u6765\u4fdd\u5b58\u4e34\u8fd1\u70b9\u5230\u76ee\u6807\u70b9\u8ddd\u79bb\u7684\u5e73\u65b9\n    std::vector<float> features(6);             // \u7528\u6765\u4fdd\u5b58\u516d\u79cd\u70b9\u4e91\u7279\u5f81\n    std::vector<float> e(3);                    // \u7528\u6765\u4fdd\u5b58 k+1 \u4e2a\u70b9\u7ecf\u8fc7 PCA \u5206\u6790\u540e\u5f97\u5230\u7684\u4e09\u4e2a\u7279\u5f81\u503c\u8ba1\u7b97\u5f97\u5230\u7684 e\uff0c\u4ece\u5927\u5230\u5c0f\u6392\u5e8f\n    std::ofstream file;                         // \u8f93\u51fa\u8ba1\u7b97\u7ed3\u679c\u7684\u76ee\u6807\u6587\u4ef6\n    Eigen::Matrix<float, 3, 21> nearest_points; // 3x(k+1) \u7ef4\u7684\u77e9\u9635\uff0c\u7528\u6765\u4fdd\u5b58\u70b9\u4e91\u4e2d\u7684\u70b9\n    Eigen::Matrix3f covariance;                 // \u7528\u6765\u4fdd\u5b58\u534f\u65b9\u5dee\u77e9\u9635\n    Eigen::Vector3f m, eigen_value;             // m \u4e3a k+1 \u4e2a\u70b9\u7684\u8d28\u5fc3\uff0ceigen_value \u7528\u6765\u4fdd\u5b58\u8ba1\u7b97\u597d\u7684\u8ba1\u7b97\u597d\u7684\u7279\u5f81\u503c\n\n    // \u6253\u5f00\u6587\u4ef6\uff0c\u6ca1\u6709\u5c31\u51ed\u7a7a\u521b\u5efa\u4e00\u4e2a\uff0c\u5982\u679c\u6709\u5c31\u5220\u6389\u91cc\u9762\u7684\u5185\u5bb9\uff0c\u518d\u5199\u5165\u65b0\u7684\n    // \u4e00\u822c\u4e0d\u4f1a\u51fa\u9519\n    file.open(\"wcm.txt\");\n\n    // pcl::PointCloud \u4e2d\u4fdd\u5b58\u70b9\u7684\u5bf9\u8c61\uff0c\u6211\u4eec\u7528\u5f15\u7528\u5355\u72ec\u7ed9\u4ed6\u62ff\u51fa\u6765\n    // \u65b9\u4fbf\u540e\u7eed\u5199\u4ee3\u7801\n    auto& points = pc->points;\n    for (size_t i = 0; i < pc->size(); i++)\n    {\n        // \u6bcf\u9694\u4e94\u4e2a\u70b9\u8ba1\u7b97\u4e00\u6b21\u7279\u5f81\u503c\uff0c\u4f5c\u4e1a\u6ca1\u6709\u8981\u6c42\u8fd9\u4e48\u505a\n        // \u53ea\u662f\u60f3\u8fd9\u4e48\u505a\uff0c\u5e0c\u671b\u80fd\u5feb\u70b9\n        if(i%5 != 0) continue;\n\n        // \u91cd\u7f6e m\uff0c\u56e0\u4e3a m \u9700\u8981\u7d2f\u52a0\uff0c\u800c\u5176\u4ed6\u7684\u53d8\u91cf\u53ea\u9700\u8981\u8d4b\u503c\n        m = m.Zero();\n\n        // \u641c\u7d22\u76ee\u6807\u70b9\u6700\u8fd1\u7684\u51e0\u4e2a\u70b9\n        // https://pointclouds.org/documentation/classpcl_1_1_organized_neighbor_search.html#a3c18f38a4aad5fe6c05179906faf14cb\n        kdtree.nearestKSearch(points[i], k, point_idx, point_sq_dis);\n\n        // \u7d2f\u52a0\u641c\u7d22\u540e\u7684\u6570\u636e\n        for (size_t j = 0; j < k; j++)\n        {\n            // \u77e9\u9635\u7684\u5757\u64cd\u4f5c\uff0c\u5c06\u6bcf\u4e2a\u70b9\u4f5c\u4e3a\u5217\u5411\u91cf\u5b58\u5165 nearest_points\n            // http://eigen.tuxfamily.org/dox/group__TutorialBlockOperations.html\n            nearest_points.col(j) << points[point_idx[j]].x, points[point_idx[j]].y, points[point_idx[j]].z;\n            m[0] += points[point_idx[j]].x;\n            m[1] += points[point_idx[j]].y;\n            m[2] += points[point_idx[j]].z;\n        }\n        nearest_points.col(k) << points[i].x, points[i].y, points[i].z;\n        m[0] += points[i].x;\n        m[1] += points[i].y;\n        m[2] += points[i].z;\n\n        // \u77e9\u9635\u7684\u5e7f\u64ad\u64cd\u4f5c\uff0c\u5c06\u6bcf\u4e00\u5217\u51cf\u53bb k+1 \u4e2a\u70b9\u7684\u8d28\u5fc3\n        // http://eigen.tuxfamily.org/dox/group__TutorialReductionsVisitorsBroadcasting.html\n        nearest_points.colwise() -= (m/(k+1));\n\n        // \u8ba1\u7b97\u534f\u65b9\u5dee\u77e9\u9635\n        covariance = nearest_points * nearest_points.transpose();\n\n        // \u5bf9\u79f0\u77e9\u9635\u6c42\u7279\u5f81\u503c\n        Eigen::SelfAdjointEigenSolver<Eigen::Matrix3f> solver(covariance);\n        eigen_value = solver.eigenvalues();\n\n        // \u77e9\u9635\u7684 reduction \u64cd\u4f5c\uff0c\u8ba1\u7b97\u77e9\u9635\u6240\u6709\u5143\u7d20\u7684\u548c\n        // http://eigen.tuxfamily.org/dox/group__TutorialReductionsVisitorsBroadcasting.html\n        e[0] = eigen_value[2]/eigen_value.sum();\n        e[1] = eigen_value[1]/eigen_value.sum();\n        e[2] = eigen_value[0]/eigen_value.sum();\n\n        // \u8ba1\u7b97\u70b9\u4e91\u7279\u5f81\n        features[0] = (e[0]-e[1])/e[0];\n        features[1] = (e[1]-e[2])/e[0];\n        features[2] = e[2]/e[0];\n        features[3] = std::cbrt(std::accumulate(e.begin(), e.end(), 0))*3.0f;\n        features[4] = -e[0] * std::log(e[0]) - e[1] * std::log(e[1]) - e[2] * std::log(e[2]);\n        features[5] = 3.0f*e[2];\n\n        // \u5c06\u7ed3\u679c\u5199\u5165\u6587\u4ef6\uff0c\u7a7a\u683c\u5206\u5f00\uff0c\u6700\u6709\u8ffd\u52a0\u4e00\u4e2a\u6362\u884c\n        // \u8fd9\u79cd\u7279\u6b8a\u7684\u6362\u884c\u6709\u6e05\u7a7a\u7f13\u51b2\u533a\u7684\u6548\u679c\n        for(auto& num : features)\n            file << num << \" \";\n        file << std::endl;\n    }\n    // \u5173\u95ed\u6587\u4ef6\n    file.close();\n    \n    std::cout << \"cal done\" << std::endl;\n\n    // \u5173\u95ed\u8282\u70b9\n    // \u4e0b\u9762\u662f\u5b98\u65b9\u63cf\u8ff0\n    // Disconnects everything and unregisters from the master. \n    // It is generally not necessary to call this function, \n    // as the node will automatically shutdown when all NodeHandles destruct.\n    // However, if you want to break out of a spin() loop explicitly, this function allows that.\n    ros::shutdown();\n    return;\n}\n\nint main(int argc, char** argv)\n{\n    ros::init(argc, argv, \"aiimooc_wcm_node\");\n    ros::NodeHandle nh(\"~\");\n\n    auto sub_rslidar = nh.subscribe<sensor_msgs::PointCloud2>(\"/rslidar_points\", 2, ros_callback);\n\n    ros::spin();\n    return 0;\n}\n", "meta": {"hexsha": "8ecf8386dd8d8b4f017a9e14155e2c515e614500", "size": 4637, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CH2_PointCloudFeature/eigenfeature/src/eigenfeature.cpp", "max_stars_repo_name": "HopeCollector/SLAMResearch", "max_stars_repo_head_hexsha": "747f26a68c072af00567f8009083fd46550fc56b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-01-14T07:53:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-14T07:58:04.000Z", "max_issues_repo_path": "CH2_PointCloudFeature/eigenfeature/src/eigenfeature.cpp", "max_issues_repo_name": "HopeCollector/SLAMResearch", "max_issues_repo_head_hexsha": "747f26a68c072af00567f8009083fd46550fc56b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CH2_PointCloudFeature/eigenfeature/src/eigenfeature.cpp", "max_forks_repo_name": "HopeCollector/SLAMResearch", "max_forks_repo_head_hexsha": "747f26a68c072af00567f8009083fd46550fc56b", "max_forks_repo_licenses": ["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.0955882353, "max_line_length": 126, "alphanum_fraction": 0.601035152, "num_tokens": 1756, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.6584175072643415, "lm_q1q2_score": 0.4647012186929388}}
{"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#include <boost/simd/arithmetic/include/functions/scalar/fast_rsqrt.hpp>\n#include <boost/dispatch/functor/meta/call.hpp>\n#include <boost/simd/include/constants/one.hpp>\n#include <boost/simd/include/constants/mone.hpp>\n#include <boost/simd/include/constants/nan.hpp>\n#include <boost/simd/include/constants/four.hpp>\n#include <boost/simd/include/constants/half.hpp>\n#include <boost/simd/include/constants/sqrt_2.hpp>\n\n#include <nt2/sdk/unit/tests/ulp.hpp>\n#include <nt2/sdk/unit/tests/type_expr.hpp>\n#include <nt2/sdk/unit/module.hpp>\n\nNT2_TEST_CASE_TPL( fast_rsqrt, BOOST_SIMD_REAL_TYPES )\n{\n  using boost::simd::fast_rsqrt;\n  using boost::simd::tag::fast_rsqrt_;\n\n  // return type conformity test\n  NT2_TEST_TYPE_IS( typename boost::dispatch::meta::call<fast_rsqrt_(T)>::type\n                  , T\n                  );\n\n  // specific values tests\n  NT2_TEST_ULP_EQUAL(fast_rsqrt(boost::simd::Mone<T>()), boost::simd::Nan<T>(), 75);\n  NT2_TEST_ULP_EQUAL(fast_rsqrt(boost::simd::Nan<T>()), boost::simd::Nan<T>(), 0.5);\n  NT2_TEST_ULP_EQUAL(fast_rsqrt(boost::simd::One<T>()), boost::simd::One<T>(), 30);\n  NT2_TEST_ULP_EQUAL(fast_rsqrt(boost::simd::Four<T>()), boost::simd::Half<T>(), 30);\n  NT2_TEST_ULP_EQUAL(fast_rsqrt(T(0.5)), boost::simd::Sqrt_2<T>(), 70);\n  NT2_TEST_ULP_EQUAL(fast_rsqrt(T(0.01)), T(10), 30);\n  NT2_TEST_ULP_EQUAL(fast_rsqrt(T(0.0001)), T(100), 30);\n}\n", "meta": {"hexsha": "7379576eb7c45990bc547f617962f81b665b3742", "size": 1880, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/base/unit/arithmetic/scalar/fast_rsqrt.cpp", "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/unit/arithmetic/scalar/fast_rsqrt.cpp", "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/unit/arithmetic/scalar/fast_rsqrt.cpp", "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": 45.8536585366, "max_line_length": 85, "alphanum_fraction": 0.6308510638, "num_tokens": 515, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850154599563, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.46470121527430486}}
{"text": "#include \"../kernels.h\"\n#include <boost/gil.hpp>\n#include <boost/gil/extension/io/png.hpp>\n#include <iostream>\n#include <opencv2/opencv.hpp>\n#include <time.h>\n\nnamespace gil = boost::gil;\n\nvoid fill_gil_view_with_opencv_mat(cv::Mat opencv_mat,\n                                   gil::gray8_view_t gil_view) {\n  for (int i = 0; i < opencv_mat.rows; i++)\n    for (int j = 0; j < opencv_mat.cols; j++)\n      gil_view(j, i) = opencv_mat.at<uchar>(i, j);\n}\n\nint main(int argc, char *argv[]) {\n  // Read input image using opencv's imread()\n  cv::Mat opencv_image = cv::imread(argv[1], cv::IMREAD_GRAYSCALE);\n\n  // Declare input image\n  gil::gray8_image_t image(opencv_image.cols, opencv_image.rows);\n\n  // Fill GIL image view with image read using opencv's imread()\n  fill_gil_view_with_opencv_mat(opencv_image, gil::view(image));\n\n  // Declare output image\n  gil::gray8_image_t output(image.dimensions());\n\n  // Create a 2D GIL kernel\n  gil::detail::kernel_2d<float> kernel(sobel3x3KernelAlign, 9, 1, 1);\n\n  clock_t start, end;\n  start = clock();\n  // Apply 2D convolution between input image and kernel\n  gil::detail::convolve_2d(gil::view(image), kernel, gil::view(output));\n  end = clock();\n  std::cout << \"Execution time: \" << (double)(end - start) / CLOCKS_PER_SEC\n            << \" s\" << std::endl;\n\n  // Save obtained image\n  gil::write_view(argv[2], gil::view(output), gil::png_tag{});\n}\n", "meta": {"hexsha": "ba43c9e8383c14257eb140243dedb75af5345a02", "size": 1390, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/ConvOpt/comparison/boost_gil_conv2d.cpp", "max_stars_repo_name": "LeiWang1999/buddy-mlir", "max_stars_repo_head_hexsha": "05996fdbe1a2643299c2cb5441c0e6bad2f9848f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 38.0, "max_stars_repo_stars_event_min_datetime": "2021-05-20T13:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-26T07:11:16.000Z", "max_issues_repo_path": "examples/ConvOpt/comparison/boost_gil_conv2d.cpp", "max_issues_repo_name": "LeiWang1999/buddy-mlir", "max_issues_repo_head_hexsha": "05996fdbe1a2643299c2cb5441c0e6bad2f9848f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 15.0, "max_issues_repo_issues_event_min_datetime": "2021-08-31T03:25:34.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-26T07:26:24.000Z", "max_forks_repo_path": "examples/ConvOpt/comparison/boost_gil_conv2d.cpp", "max_forks_repo_name": "LeiWang1999/buddy-mlir", "max_forks_repo_head_hexsha": "05996fdbe1a2643299c2cb5441c0e6bad2f9848f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2021-04-30T09:50:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T16:34:21.000Z", "avg_line_length": 31.5909090909, "max_line_length": 75, "alphanum_fraction": 0.6625899281, "num_tokens": 417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850154599562, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.4647012152743048}}
{"text": "// Copyright David Abrahams 2002. Permission to copy, use,\r\n// modify, sell and distribute this software is granted provided this\r\n// copyright notice appears in all copies. This software is provided\r\n// \"as is\" without express or implied warranty, and with no claim as\r\n// to its suitability for any purpose.\r\n#include <boost/python/operators.hpp>\r\n#include <boost/python/class.hpp>\r\n#include <boost/python/module.hpp>\r\n#include <boost/python/def.hpp>\r\n#include <string>\r\n#include \"test_class.hpp\"\r\n#if __GNUC__ != 2\r\n# include <ostream>\r\n#else\r\n# include <ostream.h>\r\n#endif\r\n\r\n// Just use math.h here; trying to use std::pow() causes too much\r\n// trouble for non-conforming compilers and libraries.\r\n#include <math.h>\r\n\r\nusing namespace boost::python;\r\n\r\nstruct X : test_class<>\r\n{\r\n    typedef test_class<> base_t;\r\n    \r\n    X(int x) : base_t(x) {}\r\n    X const operator+(X const& r) const { return X(value() + r.value()); }\r\n};\r\n\r\nX operator-(X const& l, X const& r) { return X(l.value() - r.value()); }\r\nX operator-(int l, X const& r) { return X(l - r.value()); }\r\nX operator-(X const& l, int r) { return X(l.value() - r); }\r\n\r\nX operator-(X const& x) { return X(-x.value()); }\r\n\r\nX& operator-=(X& l, X const& r) { l.set(l.value() - r.value()); return l; }\r\n\r\nbool operator<(X const& x, X const& y) { return x.value() < y.value(); }\r\nbool operator<(X const& x, int y) { return x.value() < y; }\r\nbool operator<(int x, X const& y) { return x < y.value(); }\r\n\r\nX abs(X x) { return X(x.value() < 0 ? -x.value() : x.value()); }\r\n\r\nX pow(X x, int y)\r\n{\r\n    return X(int(pow(double(x.value()), double(y))));\r\n}\r\n\r\nX pow(X x, X y)\r\n{\r\n    return X(int(pow(double(x.value()), double(y.value()))));\r\n}\r\n\r\nint pow(int x, X y)\r\n{\r\n    return int(pow(double(x), double(y.value())));\r\n}\r\n\r\nstd::ostream& operator<<(std::ostream& s, X const& x)\r\n{\r\n    return s << x.value();\r\n}\r\n\r\nBOOST_PYTHON_MODULE(operators_ext)\r\n{\r\n    class_<X>(\"X\", init<int>())\r\n        .def(\"value\", &X::value)\r\n        .def(self + self)\r\n        .def(self - self)\r\n        .def(self - int())\r\n        .def(other<int>() - self)\r\n        .def(-self)\r\n        .def(self < other<int>())\r\n        .def(self < self)\r\n        .def(1 < self)\r\n        .def(self -= self)\r\n        .def(abs(self))\r\n        .def(str(self))\r\n            \r\n        .def(pow(self,self))\r\n        .def(pow(self,int()))\r\n        .def(pow(int(),self))\r\n        ;\r\n\r\n    class_<test_class<1> >(\"Z\", init<int>())\r\n        .def(int_(self))\r\n        .def(float_(self))\r\n        .def(complex_(self))\r\n        ;\r\n}\r\n\r\n#include \"module_tail.cpp\"\r\n", "meta": {"hexsha": "b427ddb33725f65719f3b6389f21f9b2eb5eff8a", "size": 2576, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sdk/boost_1_30_0/libs/python/test/operators.cpp", "max_stars_repo_name": "acidicMercury8/xray-1.0", "max_stars_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-01-30T12:51:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-31T08:36:49.000Z", "max_issues_repo_path": "sdk/boost_1_30_0/libs/python/test/operators.cpp", "max_issues_repo_name": "acidicMercury8/xray-1.0", "max_issues_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_issues_repo_licenses": ["Linux-OpenIB"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sdk/boost_1_30_0/libs/python/test/operators.cpp", "max_forks_repo_name": "acidicMercury8/xray-1.0", "max_forks_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1157894737, "max_line_length": 76, "alphanum_fraction": 0.5667701863, "num_tokens": 690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.4647012139623028}}
{"text": "/*\n * example-rtc.cpp\n * \n * Copyright (c) 2010 Marc Kirchner\n *               2011 David Sichau\n *\n */\n\n#include <libpipe/config.hpp>\n#include <stdlib.h>\n#include <exception>\n#include <iostream>\n#include <set>\n#include <boost/pointer_cast.hpp>\n#include <boost/shared_ptr.hpp>\n#include <boost/make_shared.hpp>\n#include <libpipe/rtc/Algorithm.hpp>\n#include <libpipe/rtc/Filter.hpp>\n#include <libpipe/rtc/Manager.hpp>\n#include <libpipe/rtc/ManagerFactory.hpp>\n#include <libpipe/rtc/AlgorithmFactory.hpp>\n#include <libpipe/utilities/Exception.hpp>\n#include <libpipe/Request.hpp>\n#include <libpipe/rtc/SharedData.hpp>\n#include <libpipe/rtc/PipelineLoader.hpp>\n\n#include \"walltime.h\"\n\nint MATRIX_SIZE = 100;\n\n/** Simple Matrix Multiplication Algorithm Example.\n */\nclass MatrixMulAlgorithm : public libpipe::rtc::Algorithm\n{\npublic:\n    // use convenience typedefs to avoid cluttering up the code\n    typedef std::vector<double> Doubles;\n    typedef libpipe::rtc::SharedData<Doubles> SharedDoubles;\n\n\n    /** Virtual constructor.\n     * @return Base class pointer to a new \\c MatrixMulAlgorithm object.\n     */\n    static Algorithm* create()\n    {\n        return new MatrixMulAlgorithm;\n    }\n\n    /** Destructor.\n     */\n    virtual ~MatrixMulAlgorithm()\n    {\n    }\n\n    /** Executes the algorithm and updates the output data.\n     * This is where the algorithm implementation needs to go.\n     * @param[in,out] req The request object, forwarded from \\c process request.\n     */\n    void update(libpipe::Request& req)\n    {\n        // Take note of what we are doing\n        LIBPIPE_PIPELINE_TRACE(\"MatrixMulAlgorithm::update: start.\");\n\n        // Gain access to the in- and output\n        LIBPIPE_PREPARE_READ_ACCESS(input1_, tempIn1, Doubles, \"MatrixIn1\");\n        LIBPIPE_PREPARE_READ_ACCESS(input2_, tempIn2, Doubles, \"MatrixIn2\");\n        LIBPIPE_PREPARE_WRITE_ACCESS(output_, tempOut, Doubles, \"MatrixOut\");\n        // Again, log what is happening\n        LIBPIPE_PIPELINE_TRACE(\n            \"MatrixMulAlgorithm::update: multiplication of two matrices.\");\n\n        // Let's roll. This is O(N^2).\n        for (int i = 0; i < MATRIX_SIZE; i++) {\n            for (int j = 0; j < MATRIX_SIZE; j++) {\n                double sum = 0;\n                for (int k = 0; k < MATRIX_SIZE; k++) {\n                    sum += tempIn1[i * MATRIX_SIZE + k] * tempIn2[k\n                            * MATRIX_SIZE + j];\n                }\n                tempOut[i * MATRIX_SIZE + j] = sum / MATRIX_SIZE;\n            }\n        }\n\n        LIBPIPE_CLEAR_ACCESS(output_);\n        LIBPIPE_CLEAR_ACCESS(input1_);\n        LIBPIPE_CLEAR_ACCESS(input2_);\n\n\n        // And tell the world that we are done.\n        LIBPIPE_PIPELINE_TRACE(\"MatrixMulAlgorithm::update: end.\");\n    }\n\nprotected:\n    /** Constructor.\n     * Make sure to call the \\c libpipe::rtc::Algorithm constructor.\n     */\n    MatrixMulAlgorithm() :\n        libpipe::rtc::Algorithm()\n    {\n        ports_[\"MatrixIn1\"] = boost::make_shared<SharedDoubles>();\n        ports_[\"MatrixIn2\"] = boost::make_shared<SharedDoubles>();\n        ports_[\"MatrixOut\"] = boost::make_shared<SharedDoubles>(\n            new Doubles(MATRIX_SIZE * MATRIX_SIZE));\n    }\n\nprivate:\n\n    /** Registers the Algorithm with the factory.\n     * @return A boolean that indicates if the registration was successful\n     */\n    static const bool registerLoader()\n    {\n        std::string ids = \"MatrixMulAlgorithm\";\n        return libpipe::rtc::AlgorithmFactory::instance().registerType(ids,\n            MatrixMulAlgorithm::create);\n    }\n    /// if true then class is registered w/ Algorithm Factory\n    static const bool registered_;\n\n};\n\nconst bool MatrixMulAlgorithm::registered_ =\n        MatrixMulAlgorithm::registerLoader();\n\n/** Provides a constant matrix as output.\n * This is an example of a 'source': the \\c Source algorithm does not require\n * any input and will always provide a predefined matrix on its output port.\n */\nclass Source : public libpipe::rtc::Algorithm\n{\npublic:\n    // use convenience typedefs to avoid cluttering up the code\n    typedef std::vector<double> Doubles;\n    typedef libpipe::rtc::SharedData<Doubles> SharedDoubles;\n\n    static Algorithm* create()\n    {\n        return new Source;\n    }\n\n    /** Destructor.\n     */\n    virtual ~Source()\n    {\n    }\n\n\n    /** Updates the output data (i.e. does nothing).\n     * The output is provided as a constant, hence there is nothing to do.\n     * @param[in] req The request object.\n     */\n    void update(libpipe::Request& req)\n    {\n        LIBPIPE_PIPELINE_TRACE(\"Source::update: start.\");\n        LIBPIPE_PREPARE_WRITE_ACCESS(output_, tempOut, Doubles, \"MatrixOut\");\n\n        // fill matrix with some values\n        LIBPIPE_PIPELINE_TRACE(\"Source::update: filling matrix.\");\n        for (int row = 0; row < MATRIX_SIZE; row++) {\n            for (int col = 0; col < MATRIX_SIZE; col++) {\n                tempOut[col + (row * MATRIX_SIZE)] = col + row;\n            }\n        }\n\n        LIBPIPE_CLEAR_ACCESS(output_)\n        LIBPIPE_PIPELINE_TRACE(\"Source::update: end.\");\n    }\n\nprivate:\n    /** Constructor.\n     */\n    Source() :\n        libpipe::rtc::Algorithm()\n    {\n        ports_[\"MatrixOut\"] = boost::make_shared<SharedDoubles>(\n            new Doubles(MATRIX_SIZE * MATRIX_SIZE));\n    }\n    /** registers the Algorithm in the factory\n     * @return true is registration was successful\n     */\n    static const bool registerLoader()\n    {\n        std::string ids = \"Source\";\n        return libpipe::rtc::AlgorithmFactory::instance().registerType(ids,\n            Source::create);\n    }\n    /// true is class is registered in Algorithm Factory\n    static const bool registered_;\n\n};\n\nconst bool Source::registered_ = Source::registerLoader();\n\n/** Prints the Matrix\n */\nclass Printer : public libpipe::rtc::Algorithm\n{\npublic:\n    // use convenience typedefs to avoid cluttering up the code\n    typedef std::vector<double> Doubles;\n    typedef libpipe::rtc::SharedData<Doubles> SharedDoubles;\n\n    static Algorithm* create()\n    {\n        return new Printer;\n    }\n\n    /** Destructor.\n     */\n    virtual ~Printer()\n    {\n    }\n\n\n    /** Updates the output data (i.e. does nothing).\n     * The output is provided as a constant, hence there is nothing to do.\n     * @param[in] req The request object.\n     */\n    void update(libpipe::Request& req)\n    {\n        LIBPIPE_PIPELINE_TRACE( \"Printer::update: start.\");\n        // Gain access to the in- and output\n        LIBPIPE_PREPARE_READ_ACCESS(input_, in, Doubles, \"MatrixIn\");\n\n\n        LIBPIPE_PIPELINE_TRACE(\"printing matrix\");\n\n        // print the matrix\n        for (int row = 0; row < MATRIX_SIZE; row++) {\n            for (int col = 0; col < MATRIX_SIZE; col++) {\n                std::cout << in[col + (row * MATRIX_SIZE)] << \" \";\n            }\n            std::cout << '\\n';\n        }\n        std::cout << '\\n' << std::endl;\n        LIBPIPE_CLEAR_ACCESS(input_);\n        LIBPIPE_PIPELINE_TRACE(\"Printer::update: end.\");\n    }\n\nprotected:\n\nprivate:\n    /** Constructor.\n     */\n    Printer() :\n        libpipe::rtc::Algorithm()\n    {\n        ports_[\"MatrixIn\"] = boost::make_shared<SharedDoubles>();\n    }\n    /** registers the Algorithm in the factory\n     * @return true is registration was successful\n     */\n    static const bool registerLoader()\n    {\n        std::string ids = \"Printer\";\n        return libpipe::rtc::AlgorithmFactory::instance().registerType(ids,\n            Printer::create);\n    }\n    /// true is class is registered in Algorithm Factory\n    static const bool registered_;\n\n};\n\nconst bool Printer::registered_ = Printer::registerLoader();\n\n\n/** Handles the several Algorithms so that they can be executed in parallel,\n *  as the Pipeline will execute them in sequential order.\n */\nclass Handler : public libpipe::rtc::Algorithm\n{\npublic:\n    static Algorithm* create()\n    {\n        return new Handler;\n    }\n\n    /** Destructor.\n     */\n    virtual ~Handler()\n    {\n    }\n\n    /** Does nothing.\n     * The output is provided as a constant, hence there is nothing to do.\n     * @param[in] req The request object.\n     */\n    void update(libpipe::Request& req)\n    {\n        LIBPIPE_PIPELINE_TRACE(\"start handler\");\n    }\n\nprotected:\n\nprivate:\n    /** Constructor.\n     */\n    Handler() :\n        libpipe::rtc::Algorithm()\n    {\n    }\n    /** registers the Algorithm in the factory\n     * @return true is registration was successful\n     */\n    static const bool registerLoader()\n    {\n        std::string ids = \"Handler\";\n        return libpipe::rtc::AlgorithmFactory::instance().registerType(ids,\n            Handler::create);\n    }\n    /// true is class is registered in Algorithm Factory\n    static const bool registered_;\n\n};\n\nconst bool Handler::registered_ = registerLoader();\n\nint main(int argc, char *argv[])\n{\n    using namespace libpipe::rtc;\n    if (argc == 2) {\n        MATRIX_SIZE = atoi(argv[1]);\n    } else {\n        std::cerr << \"usage: ./example-matrices MATRIX_SIZE[int]\" << std::endl;\n        exit(1);\n    }\n\n    std::cout << \"Matrix Size: \" << MATRIX_SIZE << std::endl;\n\n    std::map < std::string, std::string > inputFiles;\n    inputFiles[\"FilterInput\"] = \"inputFileFilterJSONMatrix.txt\";\n    inputFiles[\"ConnectionInput\"] = \"inputFileConnectionJSONMatrix.txt\";\n    inputFiles[\"PipelineInput\"] = \"inputFilePipelineJSONMatrix.txt\";\n    inputFiles[\"ParameterInput\"] = \"inputFileParametersJSONMatrix.txt\";\n\n    Pipeline pipeline;\n    try {\n        PipelineLoader loader(inputFiles);\n        pipeline = loader.getPipeline();\n    } catch (libpipe::utilities::Exception& e) {\n        std::cerr << e.what() << std::endl;\n    }\n\n    double time, time_start = 0.0;\n\n    time = walltime(&time_start);\n\n    try {\n        pipeline.run();\n    } catch (libpipe::utilities::Exception& e) {\n        std::cerr << e.what() << std::endl;\n    }\n\n    time = walltime(&time);\n\n    std::cout << time << \" sec\" << std::endl;\n\n    std::vector < std::string > trace;\n    trace = pipeline.getTrace();\n    for (std::vector<std::string>::const_iterator i = trace.begin(); i\n            != trace.end(); ++i) {\n        std::cout << *i << '\\n';\n    }\n\n    std::cout\n            << \"All output after this is due to automatically called destructors.\"\n            << std::endl;\n\n    return EXIT_SUCCESS;\n\n}\n\n", "meta": {"hexsha": "c39ae9639f7d2c74a5adba6d8d9fe5fcd1d0e0aa", "size": 10276, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/example-matrices.cpp", "max_stars_repo_name": "kirchnerlab/libpipe", "max_stars_repo_head_hexsha": "28f08b9399945bd13329937a9dd0691211826886", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-11-08T13:41:18.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-08T13:41:18.000Z", "max_issues_repo_path": "examples/example-matrices.cpp", "max_issues_repo_name": "kirchnerlab/libpipe", "max_issues_repo_head_hexsha": "28f08b9399945bd13329937a9dd0691211826886", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/example-matrices.cpp", "max_forks_repo_name": "kirchnerlab/libpipe", "max_forks_repo_head_hexsha": "28f08b9399945bd13329937a9dd0691211826886", "max_forks_repo_licenses": ["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.5495978552, "max_line_length": 82, "alphanum_fraction": 0.6176527832, "num_tokens": 2401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.4647012139623028}}
{"text": "// Copyright Andr\u00e1s Vukics 2006\u20132020. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.txt)\n#include \"DistributionFunctions.h\"\n\n#include \"Pars.h\"\n\n#include <boost/math/special_functions/binomial.hpp>\n#include <boost/math/special_functions/hermite.hpp>\n#include <boost/math/special_functions/laguerre.hpp>\n#include <boost/math/special_functions/factorials.hpp>\n\n\nusing namespace cppqedutils;\nusing namespace boost::math;\n\n\nnamespace quantumdata {\n\n\nParsFunctionScan::ParsFunctionScan(parameters::Table& p, const std::string& mod)\n  : fLimitXUL(p.addTitle(\"Distribution function scan\",mod).add(\"fLimitXUL\",\"\",2.)),\n    fLimitYUL(p.add(\"fLimitYUL\",\"\",2.)),\n    fLimitXL(p.add(\"fLimitXL\",\"\",-2.)),\n    fLimitXU(p.add(\"fLimitXU\",\"\",2.)),\n    fLimitYL(p.add(\"fLimitYL\",\"\",-2.)),\n    fLimitYU(p.add(\"fLimitYU\",\"\",2.)),\n    fStep(p.add(\"fStep\",\"\",.1)),\n    fCutoff(p.add(\"fCutoff\",\"\",100))\n{}\n\n\n  \nnamespace {\n\n\nconst WignerFunctionKernelOld::Hermites fillWithHermite(size_t dim, double x)\n{\n  WignerFunctionKernelOld::Hermites res(2*dim-1);\n  res(0)=hermite(0,x); res(1)=hermite(1,x);\n  for (unsigned l=1; l<res.size()-1; ++l)\n    res(l+1)=hermite_next(l,x,res(l),res(l-1));\n  return res;\n}\n\n\n}\n\ndouble details::w(size_t n, double r, size_t k)\n{\n  const double sqrR=sqr(r);\n  return minusOneToThePowerOf(n)/PI*sqrt(factorial<double>(n)/factorial<double>(n+k))*exp(-2*sqrR)*pow(2*r,k)*laguerre(n,k,4*sqrR);\n}\n\n\nWignerFunctionKernelOld::WignerFunctionKernelOld(double x, double y, size_t dim)\n  : hermite_m2x_(fillWithHermite(dim,-2*x)), hermite_2y_(fillWithHermite(dim,2*y))\n{}\n\n\ndcomp WignerFunctionKernelOld::operator()(size_t m, size_t n) const\n{\n  dcomp res(0);\n\n  for (size_t u=0; u<=m; ++u) for (size_t v=0; v<=n; ++v)\n    res+=\n      binomial_coefficient<double>(m,u)*\n      binomial_coefficient<double>(n,v)*\n      minusOneToThePowerOf(v)*\n      pow(DCOMP_I,u+v)*\n      hermite_m2x_(    u+v)*\n      hermite_2y_ (n+m-u-v);\n\n  return res;\n\n}\n\n\n} // quantumdata\n\n", "meta": {"hexsha": "5995404c672a4b95c6a88585bb061bcf16b775d1", "size": 2001, "ext": "cc", "lang": "C++", "max_stars_repo_path": "CPPQEDcore/quantumdata/DistributionFunctions.cc", "max_stars_repo_name": "vukics/cppqed", "max_stars_repo_head_hexsha": "a933375f53b982b14cebf7cb63de300996ddd00b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-02-21T14:00:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-29T15:12:11.000Z", "max_issues_repo_path": "CPPQEDcore/quantumdata/DistributionFunctions.cc", "max_issues_repo_name": "vukics/cppqed", "max_issues_repo_head_hexsha": "a933375f53b982b14cebf7cb63de300996ddd00b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2020-04-14T11:18:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-04T20:11:23.000Z", "max_forks_repo_path": "CPPQEDcore/quantumdata/DistributionFunctions.cc", "max_forks_repo_name": "vukics/cppqed", "max_forks_repo_head_hexsha": "a933375f53b982b14cebf7cb63de300996ddd00b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-25T10:16:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-28T18:29:01.000Z", "avg_line_length": 25.3291139241, "max_line_length": 132, "alphanum_fraction": 0.6861569215, "num_tokens": 640, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.46447203785651964}}
{"text": "//  justanhduc\n// Oct 2020\n\n#include <Eigen/Core>\n#include <cmath>\n#include <opencv2/opencv.hpp>\n#include <opencv2/highgui/highgui.hpp>\n\n#include \"TSDFVolumeCPU.hpp\"\n#include \"Raycaster.hpp\"\n#include \"RenderUtilities.hpp\"\n\n\n#define MAX_PATH 260  // for linux\n\n\nint main() {\n    using namespace Eigen;\n\n    const int dim_x = 101, dim_y = 139, dim_z = 106;\n    const int n_max_frame = 1;\n    auto *tsdf = new float[dim_x * dim_y * dim_z * n_max_frame];\n    char stmp[MAX_PATH];\n    float ftemp[8];\n    for (int i = 0; i < n_max_frame; i++) {\n        sprintf(stmp, \"../volume/_tsdf_multi_%03d.bin\", i);  // for linux\n        FILE *fp = nullptr;\n        fp = fopen(stmp, \"rb\");  // for linux\n        if (fp == 0) {\n            printf(\"Cannot read file %s\\n\", stmp);\n            exit(-1);\n        }\n        fread(ftemp, sizeof(float), 8, fp);\n        fread(tsdf + (dim_x * dim_y * dim_z) * i, dim_x * dim_y * dim_z, sizeof(float), fp);\n        fclose(fp);\n    }\n\n    TSDFVolumeCPU volume(dim_x, dim_y, dim_z, dim_x * .01, dim_y * .01, dim_z * .01);\n    volume.set_distance_data(tsdf);\n    volume.set_truncation_distance(.09);\n    std::cout << \"Read file. Rendering.\" << std::endl;\n\n    uint16_t width = 1024;\n    uint16_t height = 768;\n\n    Eigen::Matrix<float, 3, Eigen::Dynamic> vertices;\n    Eigen::Matrix<float, 3, Eigen::Dynamic> normals;\n\n    Vector3f light_source{0, 3, 3};\n    auto eye = Vector3f{0.5, 0, 2};  // view point\n    Camera cam((float) width / 2, (float) height / 2, (float) (width - 1) / 2,\n               (float) (height - 1) / 2);\n    cam.move_to(eye);\n    cam.look_at(0.5, 0.5, 0.5);\n\n    Raycaster r{width, height};\n    r.raycast(volume, cam, vertices, normals);\n    uint8_t *scene = render_scene(width, height, vertices, normals, cam, light_source);\n\n    cv::Mat frame(height, width, 0, scene);\n    cv::imshow(\"Frame\", frame);\n    cv::waitKey(0);\n    return 0;\n}\n\n", "meta": {"hexsha": "b8b7154964aff124bad70e6ba166e40c72ff1ae5", "size": 1884, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "justanhduc/ray-casting", "max_stars_repo_head_hexsha": "25ea97f3ff10d2b0cb3c9e935f1adb9201e42908", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-08T22:38:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-08T22:38:06.000Z", "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "justanhduc/ray-casting", "max_issues_repo_head_hexsha": "25ea97f3ff10d2b0cb3c9e935f1adb9201e42908", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-04-12T02:19:00.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-26T02:46:41.000Z", "max_forks_repo_path": "main.cpp", "max_forks_repo_name": "justanhduc/ray-casting", "max_forks_repo_head_hexsha": "25ea97f3ff10d2b0cb3c9e935f1adb9201e42908", "max_forks_repo_licenses": ["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.5454545455, "max_line_length": 92, "alphanum_fraction": 0.5976645435, "num_tokens": 593, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.46447203785651964}}
{"text": "/* Copyright (C) 2010-2019, The Regents of The University of Michigan.\n All rights reserved.\n\n This software was developed as part of the The Vulcan project in the Intelligent Robotics Lab\n under the direction of Benjamin Kuipers, kuipers@umich.edu. Use of this code is governed by an\n MIT-style License that can be found at \"https://github.com/h2ssh/Vulcan\".\n*/\n\n\n/**\n * \\file     visibility_graph_feature.cpp\n * \\author   Collin Johnson\n *\n * Definition of VisibilityGraphFeature.\n */\n\n#include \"utils/visibility_graph_feature.h\"\n#include <algorithm>\n#include <boost/accumulators/framework/accumulator_set.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\nnamespace vulcan\n{\nnamespace utils\n{\n\nstd::string feature_type_to_string(VisibilityGraphFeatureType type)\n{\n    switch (type) {\n    case VisibilityGraphFeatureType::none:\n        return \"none\";\n\n    case VisibilityGraphFeatureType::mean_edge_count:\n        return \"mean edge count\";\n\n    case VisibilityGraphFeatureType::clustering_coeff:\n        return \"clustering coeff\";\n\n    case VisibilityGraphFeatureType::degree_centrality:\n        return \"degree centrality\";\n\n    case VisibilityGraphFeatureType::closeness_centrality:\n        return \"closeness centrality\";\n\n    case VisibilityGraphFeatureType::betweenness_centrality:\n        return \"betweenness centrality\";\n\n    case VisibilityGraphFeatureType::pagerank:\n        return \"pagerank\";\n\n    case VisibilityGraphFeatureType::num_features:\n    default:\n        break;\n    }\n\n    return \"\";\n}\n\n\nVisibilityGraphFeature::VisibilityGraphFeature(void) : type_(VisibilityGraphFeatureType::none)\n{\n}\n\n\nVisibilityGraphFeature::VisibilityGraphFeature(VisibilityGraphFeatureType type, const std::vector<value_type>& values)\n: type_(type)\n, values_(values)\n{\n}\n\n\nfeature_stats_t VisibilityGraphFeature::stats(std::vector<VisGraphVertex>::const_iterator begin,\n                                              std::vector<VisGraphVertex>::const_iterator end) const\n{\n    using namespace boost::accumulators;\n    accumulator_set<double, boost::accumulators::stats<tag::mean, tag::variance, tag::min, tag::max>> statsAcc;\n\n    for (auto& vertToValue : values_) {\n        if ((begin == end) || (std::find(begin, end, vertToValue.first) != end)) {\n            statsAcc(vertToValue.second);\n        }\n    }\n\n    return {min(statsAcc), mean(statsAcc), max(statsAcc), std::sqrt(variance(statsAcc))};\n}\n\n}   // namespace utils\n}   // namespace vulcan\n", "meta": {"hexsha": "40eb07a9185a7295013619e71ce51339c89659f7", "size": 2651, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/utils/visibility_graph_feature.cpp", "max_stars_repo_name": "anuranbaka/Vulcan", "max_stars_repo_head_hexsha": "56339f77f6cf64b5fda876445a33e72cd15ce028", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-03-05T23:56:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-17T19:06:50.000Z", "max_issues_repo_path": "src/utils/visibility_graph_feature.cpp", "max_issues_repo_name": "anuranbaka/Vulcan", "max_issues_repo_head_hexsha": "56339f77f6cf64b5fda876445a33e72cd15ce028", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-03-07T01:23:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-07T01:23:47.000Z", "max_forks_repo_path": "src/utils/visibility_graph_feature.cpp", "max_forks_repo_name": "anuranbaka/Vulcan", "max_forks_repo_head_hexsha": "56339f77f6cf64b5fda876445a33e72cd15ce028", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-03T07:54:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-03T07:54:16.000Z", "avg_line_length": 28.5053763441, "max_line_length": 118, "alphanum_fraction": 0.7250094304, "num_tokens": 596, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851919, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.46447203146357735}}
{"text": "/*\nMIT License\n\nCopyright (c) 2020 Rik Baehnemann, ASL, ETH Zurich, Switzerland\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*/\n\n#include \"fm_trajectories/circle_trajectory.h\"\n\n#include <algorithm>\n#include <cmath>\n#include <limits>\n\n#include <angles/angles.h>\n#include <mav_trajectory_generation/motion_defines.h>\n#include <ros/ros.h>\n#include <yaml-cpp/yaml.h>\n#include <Eigen/Core>\n\nnamespace fm_trajectories {\n\nnamespace mtg = mav_trajectory_generation;\n\nCircleTrajectory::Settings::Settings(\n    double center_east, double center_north, double radius,\n    double start_heading_deg, double arc_length_deg_in, double altitude,\n    double velocity_in, double offset_heading_deg,\n    const std::weak_ptr<BaseTrajectory>& prev_trajectory,\n    const mtg::InputConstraints& input_constraints,\n    double circle_deviation_ratio /* = 0.01 */)\n    : BaseTrajectory::Settings(input_constraints, velocity_in,\n                               offset_heading_deg, prev_trajectory),\n      center_east(center_east),\n      center_north(center_north),\n      radius(std::max(std::fabs(radius), kZeroGuard)),\n      start_heading_deg(start_heading_deg),\n      arc_length_deg(std::max(std::fabs(arc_length_deg_in), kMinArcLength)),\n      altitude(altitude),\n      circle_deviation_ratio(\n          std::max(std::min(std::fabs(circle_deviation_ratio), 0.999), 0.001)) {\n  // Arc feasibility.\n  ROS_WARN_COND(arc_length_deg_in < 0.0,\n                \"Input arc length negative. Inverted.\");\n  if (std::fabs(arc_length_deg_in) < kMinArcLength)\n    ROS_WARN_STREAM(\"Arc length too small: \" << arc_length_deg_in\n                                             << \" degrees. Clipped to: \"\n                                             << arc_length_deg << \" degrees.\");\n\n  // Yaw rate feasibility.\n  double omega_z_max = std::numeric_limits<double>::max();\n  if (input_constraints.getConstraint(\n          mav_trajectory_generation::InputConstraintType::kOmegaZMax,\n          &omega_z_max)) {\n    if (computeAngularVelocity() > omega_z_max) {\n      double new_velocity =\n          std::copysign(omega_z_max * radius - kVelocityResolution, velocity);\n      ROS_WARN_STREAM(\"Trajectory yaw rate too large: \"\n                      << computeAngularVelocity()\n                      << \" rad/s. Clipping velocity to: \" << new_velocity\n                      << \" m/s\");\n      velocity = new_velocity;\n    }\n  }\n}\n\ndouble CircleTrajectory::Settings::computeAngularVelocity() const {\n  return velocity / radius;\n}\n\nCircleTrajectory::CircleTrajectory(\n    const std::shared_ptr<CircleTrajectory::Settings>& settings)\n    : BaseTrajectory(settings),\n      start_rad_(angles::from_degrees(\n          std::static_pointer_cast<CircleTrajectory::Settings>(settings_)\n              ->start_heading_deg -\n          90)),\n      arc_length_rad_(angles::from_degrees(\n          std::static_pointer_cast<CircleTrajectory::Settings>(settings_)\n              ->arc_length_deg)) {\n  // Angle between vertices.\n  // https://stackoverflow.com/questions/11774038/how-to-render-a-circle-with-as-few-vertices-as-possible\n  const double kDeltaAngleMax = std::acos(\n      2.0 * std::pow(\n                (1.0 -\n                 std::static_pointer_cast<CircleTrajectory::Settings>(settings_)\n                     ->circle_deviation_ratio),\n                2.0) -\n      1.0);\n  const double kNumVerticesMin = std::fabs(arc_length_rad_) / kDeltaAngleMax;\n  num_vertices_ = std::ceil(kNumVerticesMin);\n  num_vertices_ += 1;  // To close circle.\n}\n\nbool CircleTrajectory::toYaml(YAML::Node* node) {\n  CHECK_NOTNULL(node);\n  *node = YAML::Node();\n\n  Eigen::Vector3d center_wgs84;\n  if (!geotf_.convert(\n          \"enu\",\n          Eigen::Vector3d(\n              std::static_pointer_cast<CircleTrajectory::Settings>(settings_)\n                  ->center_east,\n              std::static_pointer_cast<CircleTrajectory::Settings>(settings_)\n                  ->center_north,\n              std::static_pointer_cast<CircleTrajectory::Settings>(settings_)\n                  ->altitude),\n          \"wgs84\", &center_wgs84))\n    return false;\n\n  (*node)[\"altitude\"] =\n      std::static_pointer_cast<CircleTrajectory::Settings>(settings_)->altitude;\n  (*node)[\"velocity\"] =\n      std::static_pointer_cast<CircleTrajectory::Settings>(settings_)->velocity;\n  (*node)[\"trajectory_type\"] = static_cast<int>(TrajectoryType::Hotpoint);\n  (*node)[\"center_lat\"] = center_wgs84.x();\n  (*node)[\"center_lon\"] = center_wgs84.y();\n  (*node)[\"radius\"] =\n      std::static_pointer_cast<CircleTrajectory::Settings>(settings_)->radius;\n  (*node)[\"start_heading_deg\"] =\n      std::static_pointer_cast<CircleTrajectory::Settings>(settings_)\n          ->start_heading_deg;\n  (*node)[\"arc_length_deg\"] =\n      std::static_pointer_cast<CircleTrajectory::Settings>(settings_)\n          ->arc_length_deg;\n  (*node)[\"offset_heading_deg\"] =\n      std::static_pointer_cast<CircleTrajectory::Settings>(settings_)\n          ->offset_heading_deg;\n  (*node)[\"circle_deviation_ratio\"] =\n      std::static_pointer_cast<CircleTrajectory::Settings>(settings_)\n          ->circle_deviation_ratio;\n\n  return true;\n}\n\nvoid CircleTrajectory::samplePositionVertices() {\n  const Eigen::Vector3d kOffset(\n      std::static_pointer_cast<CircleTrajectory::Settings>(settings_)\n          ->center_east,\n      std::static_pointer_cast<CircleTrajectory::Settings>(settings_)\n          ->center_north,\n      std::static_pointer_cast<CircleTrajectory::Settings>(settings_)\n          ->altitude);\n  const double kAngularVelocity =\n      std::static_pointer_cast<CircleTrajectory::Settings>(settings_)\n          ->computeAngularVelocity();\n  const double kDeltaAngle = computeDeltaAngle(kAngularVelocity);\n\n  position_vertices_.resize(num_vertices_, kPositionDimension);\n  for (int i = 0; i < num_vertices_; ++i) {\n    const double kAngle = i * kDeltaAngle + start_rad_;\n\n    Eigen::Vector3d position;\n    position.x() =\n        std::static_pointer_cast<CircleTrajectory::Settings>(settings_)\n            ->radius *\n        std::cos(kAngle);\n    position.y() =\n        std::static_pointer_cast<CircleTrajectory::Settings>(settings_)\n            ->radius *\n        std::sin(kAngle);\n    position.z() = 0.0;\n    if (kMaxDerivativePos >= mtg::derivative_order::POSITION) {\n      position_vertices_[i].addConstraint(mtg::derivative_order::POSITION,\n                                          position + kOffset);\n    }\n\n    Eigen::Vector3d velocity;\n    velocity.x() =\n        -std::static_pointer_cast<CircleTrajectory::Settings>(settings_)\n             ->radius *\n        kAngularVelocity * std::sin(kAngle);\n    velocity.y() =\n        std::static_pointer_cast<CircleTrajectory::Settings>(settings_)\n            ->radius *\n        kAngularVelocity * std::cos(kAngle);\n    velocity.z() = 0.0;\n    if (kMaxDerivativePos >= mtg::derivative_order::VELOCITY) {\n      position_vertices_[i].addConstraint(mtg::derivative_order::VELOCITY,\n                                          velocity);\n    }\n\n    if (kMaxDerivativePos >= mtg::derivative_order::ACCELERATION) {\n      Eigen::Vector3d acceleration;\n      acceleration.x() = -std::pow(kAngularVelocity, 2.0) * position.x();\n      acceleration.y() = -std::pow(kAngularVelocity, 2.0) * position.y();\n      acceleration.z() = 0.0;\n      position_vertices_[i].addConstraint(mtg::derivative_order::ACCELERATION,\n                                          acceleration);\n    }\n\n    if (kMaxDerivativePos >= mtg::derivative_order::JERK) {\n      Eigen::Vector3d jerk;\n      jerk.x() = -std::pow(kAngularVelocity, 3.0) * velocity.x();\n      jerk.y() = -std::pow(kAngularVelocity, 3.0) * velocity.y();\n      jerk.z() = 0.0;\n      position_vertices_[i].addConstraint(mtg::derivative_order::JERK, jerk);\n    }\n\n    if (kMaxDerivativePos >= mtg::derivative_order::SNAP) {\n      Eigen::Vector3d snap;\n      snap.x() = std::pow(kAngularVelocity, 4.0) * position.x();\n      snap.y() = std::pow(kAngularVelocity, 4.0) * position.y();\n      snap.z() = 0.0;\n      position_vertices_[i].addConstraint(mtg::derivative_order::SNAP, snap);\n    }\n  }\n}\n\nvoid CircleTrajectory::sampleYawVertices() {\n  const double kOffsetHeading = angles::from_degrees(\n      std::static_pointer_cast<CircleTrajectory::Settings>(settings_)\n          ->offset_heading_deg);\n  const double kAngularVelocity =\n      std::static_pointer_cast<CircleTrajectory::Settings>(settings_)\n          ->computeAngularVelocity();\n  const double kDeltaAngle = computeDeltaAngle(kAngularVelocity);\n\n  yaw_vertices_.resize(num_vertices_, kYawDimension);\n  for (int i = 0; i < num_vertices_; ++i) {\n    typedef Eigen::Matrix<double, 1, 1> Vector1d;\n    if (kMaxDerivativeYaw >= mtg::derivative_order::ORIENTATION) {\n      Vector1d orientation;\n      const double kAngle = i * kDeltaAngle + start_rad_;\n      orientation[0] = kAngle + 0.5 * M_PI + kOffsetHeading;\n      yaw_vertices_[i].addConstraint(mtg::derivative_order::ORIENTATION,\n                                     orientation);\n    }\n\n    if (kMaxDerivativeYaw >= mtg::derivative_order::ANGULAR_VELOCITY) {\n      Vector1d angular_velocity;\n      angular_velocity[0] = kAngularVelocity;\n      yaw_vertices_[i].addConstraint(mtg::derivative_order::ANGULAR_VELOCITY,\n                                     angular_velocity);\n    }\n\n    if (kMaxDerivativeYaw >= mtg::derivative_order::ANGULAR_ACCELERATION) {\n      Vector1d angular_acceleration;\n      angular_acceleration[0] = 0.0;\n      yaw_vertices_[i].addConstraint(\n          mtg::derivative_order::ANGULAR_ACCELERATION, angular_acceleration);\n    }\n  }\n}\n\ndouble CircleTrajectory::computeDeltaAngle(double angular_velocity) const {\n  return std::copysign(arc_length_rad_ / (num_vertices_ - 1), angular_velocity);\n}\n\nvoid CircleTrajectory::sampleTimes() {\n  const double kAngularVelocity =\n      std::static_pointer_cast<CircleTrajectory::Settings>(settings_)\n          ->computeAngularVelocity();\n  const double kDeltaAngle = computeDeltaAngle(kAngularVelocity);\n  const double kSamplePeriod = std::fabs(kDeltaAngle / kAngularVelocity);\n\n  segment_times_.resize(position_vertices_.size() - 1);\n  for (double& t : segment_times_) t = kSamplePeriod;\n}\n\n}  // namespace fm_trajectories\n", "meta": {"hexsha": "877980ec179415710acb47bfc87a5db85c41f054", "size": 11125, "ext": "cc", "lang": "C++", "max_stars_repo_path": "libs/fm_trajectories/src/circle_trajectory.cc", "max_stars_repo_name": "ethz-asl/mav_findmine", "max_stars_repo_head_hexsha": "2835995ace0a20a30f20812437b1b066428253a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-06-25T03:38:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T08:39:48.000Z", "max_issues_repo_path": "libs/fm_trajectories/src/circle_trajectory.cc", "max_issues_repo_name": "ethz-asl/mav_findmine", "max_issues_repo_head_hexsha": "2835995ace0a20a30f20812437b1b066428253a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/fm_trajectories/src/circle_trajectory.cc", "max_forks_repo_name": "ethz-asl/mav_findmine", "max_forks_repo_head_hexsha": "2835995ace0a20a30f20812437b1b066428253a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.8745519713, "max_line_length": 105, "alphanum_fraction": 0.675505618, "num_tokens": 2626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851919, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.46447203146357724}}
{"text": "/* test_old_uniform_int_distribution.cpp\r\n *\r\n * Copyright Steven Watanabe 2011\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 * $Id$\r\n *\r\n */\r\n\r\n#include <boost/random/uniform_int.hpp>\r\n#include <limits>\r\n\r\n#define BOOST_RANDOM_DISTRIBUTION boost::uniform_int<>\r\n#define BOOST_RANDOM_ARG1 a\r\n#define BOOST_RANDOM_ARG2 b\r\n#define BOOST_RANDOM_ARG1_DEFAULT 0\r\n#define BOOST_RANDOM_ARG2_DEFAULT 9\r\n#define BOOST_RANDOM_ARG1_VALUE 5\r\n#define BOOST_RANDOM_ARG2_VALUE 250\r\n\r\n#define BOOST_RANDOM_DIST0_MIN 0\r\n#define BOOST_RANDOM_DIST0_MAX 9\r\n#define BOOST_RANDOM_DIST1_MIN 5\r\n#define BOOST_RANDOM_DIST1_MAX 9\r\n#define BOOST_RANDOM_DIST2_MIN 5\r\n#define BOOST_RANDOM_DIST2_MAX 250\r\n\r\n#define BOOST_RANDOM_TEST1_PARAMS (0, 9)\r\n#define BOOST_RANDOM_TEST1_MIN 0\r\n#define BOOST_RANDOM_TEST1_MAX 9\r\n\r\n#define BOOST_RANDOM_TEST2_PARAMS (10, 19)\r\n#define BOOST_RANDOM_TEST2_MIN 10\r\n#define BOOST_RANDOM_TEST2_MAX 19\r\n\r\n#include \"test_distribution.ipp\"\r\n\r\n#define BOOST_RANDOM_UNIFORM_INT boost::uniform_int\r\n\r\n#include \"test_uniform_int.ipp\"\r\n\r\n#include <algorithm>\r\n#include <boost/random/random_number_generator.hpp>\r\n\r\n// Test that uniform_int<> can be used with std::random_shuffle\r\n// Author: Jos Hickson\r\nBOOST_AUTO_TEST_CASE(test_random_shuffle)\r\n{\r\n#ifndef BOOST_NO_CXX98_RANDOM_SHUFFLE\r\n    typedef boost::uniform_int<> distribution_type;\r\n    typedef boost::variate_generator<boost::mt19937 &, distribution_type> generator_type;\r\n\r\n    boost::mt19937 engine1(1234);\r\n    boost::mt19937 engine2(1234);\r\n\r\n    boost::random::random_number_generator<boost::mt19937> referenceRand(engine1);\r\n\r\n    distribution_type dist(0,10);\r\n    generator_type testRand(engine2, dist);\r\n\r\n    std::vector<int> referenceVec;\r\n\r\n    for (int i = 0; i < 200; ++i) {\r\n        referenceVec.push_back(i);\r\n    }\r\n\r\n    std::vector<int> testVec(referenceVec);\r\n\r\n    std::random_shuffle(referenceVec.begin(), referenceVec.end(), referenceRand);\r\n    std::random_shuffle(testVec.begin(), testVec.end(), testRand);\r\n\r\n    BOOST_CHECK_EQUAL_COLLECTIONS(\r\n        testVec.begin(), testVec.end(),\r\n        referenceVec.begin(), referenceVec.end());\r\n#endif\r\n}\r\n", "meta": {"hexsha": "046196cbbd7db00ba659e6a3211da3cc71e973b1", "size": 2247, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/random/test/test_old_uniform_int_distribution.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": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/random/test/test_old_uniform_int_distribution.cpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-04T18:00:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-04T18:00:00.000Z", "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/random/test/test_old_uniform_int_distribution.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 28.4430379747, "max_line_length": 90, "alphanum_fraction": 0.7463284379, "num_tokens": 536, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.464441185613143}}
{"text": "/*\n\nCopyright (c) 2005-2019, 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 TYSONNOVAK2001ODESYSTEM_HPP_\n#define TYSONNOVAK2001ODESYSTEM_HPP_\n\n#include \"ChasteSerialization.hpp\"\n#include <boost/serialization/base_object.hpp>\n\n#include <cmath>\n#include <iostream>\n\n#include \"AbstractOdeSystemWithAnalyticJacobian.hpp\"\n\n/**\n * Represents the Tyson & Novak (2001) system of ODEs.\n * [doi:10.1006/jtbi.2001.2293]\n */\nclass TysonNovak2001OdeSystem : public AbstractOdeSystemWithAnalyticJacobian\n{\nprivate:\n\n    /**\n     * Parameters for the Tyson & Novak (2001) model.\n     */\n\n    /** Dimensional parameter k_1. */\n    double mK1;\n    /** Dimensional parameter k_2'. */\n    double mK2d;\n    /** Dimensional parameter k_2''. */\n    double mK2dd;\n    /** Dimensional parameter k_2'''. */\n    double mK2ddd;\n    /** Dimensionless parameter [CycB]_threshold. */\n    double mCycB_threshold;\n    /** Dimensional parameter k_3'. */\n    double mK3d;\n    /** Dimensional parameter k_3''. */\n    double mK3dd;\n    /** Dimensional parameter k_4'. */\n    double mK4d;\n    /** Dimensional parameter k_4. */\n    double mK4;\n    /** Dimensionless parameter J_3. */\n    double mJ3;\n    /** Dimensionless parameter J_4. */\n    double mJ4;\n    /** Dimensional parameter k_5'. */\n    double mK5d;\n    /** Dimensional parameter k_5''. */\n    double mK5dd;\n    /** Dimensional parameter k_6. */\n    double mK6;\n    /** Dimensionless parameter J_5. */\n    double mJ5;\n    /** Dimensionless parameter n. */\n    unsigned mN;\n    /** Dimensional parameter k_7. */\n    double mK7;\n    /** Dimensional parameter k_8. */\n    double mK8;\n    /** Dimensionless parameter J_7. */\n    double mJ7;\n    /** Dimensionless parameter J_8. */\n    double mJ8;\n    /** Dimensionless parameter [Mad]. */\n    double mMad;\n    /** Dimensional parameter k_9. */\n    double mK9;\n    /** Dimensional parameter k_10. */\n    double mK10;\n    /** Dimensional parameter k_11. */\n    double mK11;\n    /** Dimensional parameter k_12'. */\n    double mK12d;\n    /** Dimensional parameter k_12''. */\n    double mK12dd;\n    /** Dimensional parameter k_12'''. */\n    double mK12ddd;\n    /** Dimensionless parameter K_eq. */\n    double mKeq;\n    /** Dimensional parameter k_13. */\n    double mK13;\n    /** Dimensional parameter k_14. */\n    double mK14;\n    /** Dimensional parameter k_15'. */\n    double mK15d;\n    /** Dimensional parameter k_15''. */\n    double mK15dd;\n    /** Dimensional parameter k_16'. */\n    double mK16d;\n    /** Dimensional parameter k_16''. */\n    double mK16dd;\n    /** Dimensionless parameter J_15. */\n    double mJ15;\n    /** Dimensionless parameter J_16. */\n    double mJ16;\n    /** Dimensional parameter mu. */\n    double mMu;\n    /** Dimensionless parameter m_star. */\n    double mMstar;\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 stateVariables optional initial conditions for state variables (only used in archiving)\n     */\n    TysonNovak2001OdeSystem(std::vector<double> stateVariables=std::vector<double>());\n\n    /**\n     * Destructor.\n     */\n    ~TysonNovak2001OdeSystem();\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     * (Used by Chaste solvers to find whether or not to stop solving)\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     * Calculate whether the conditions for the cell cycle to finish have been met.\n     * (Used by CVODE solver to find exact stopping position)\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 How close we are to the root of the stopping condition\n     */\n    double CalculateRootFunction(double time, const std::vector<double>& rY);\n\n    /**\n     * Compute the Jacobian of the ODE system.\n     *\n     * @param rSolutionGuess initial guess for the solution vector.\n     * @param jacobian the Jacobian of the ODE system.\n     * @param time at which to calculate the Jacobian.\n     * @param timeStep used to calculate the Jacobian.\n     */\n    virtual void AnalyticJacobian(const std::vector<double>& rSolutionGuess, double** jacobian, double time, double timeStep);\n};\n\n// Declare identifier for the serializer\n#include \"SerializationExportWrapper.hpp\"\nCHASTE_CLASS_EXPORT(TysonNovak2001OdeSystem)\n\nnamespace boost\n{\nnamespace serialization\n{\n/**\n * Serialize information required to construct a TysonNovak2001OdeSystem.\n */\ntemplate<class Archive>\ninline void save_construct_data(\n    Archive & ar, const TysonNovak2001OdeSystem * t, const unsigned int file_version)\n{\n    // Save data required to construct instance\n    const std::vector<double>& state_variables = t->rGetConstStateVariables();\n    ar & state_variables;\n}\n\n/**\n * De-serialize constructor parameters and initialise a TysonNovak2001OdeSystem.\n */\ntemplate<class Archive>\ninline void load_construct_data(\n    Archive & ar, TysonNovak2001OdeSystem * t, const unsigned int file_version)\n{\n    // Retrieve data from archive required to construct new instance\n    std::vector<double> state_variables;\n    ar & state_variables;\n\n    // Invoke inplace constructor to initialise instance\n    ::new(t)TysonNovak2001OdeSystem(state_variables);\n}\n}\n} // namespace ...\n\n#endif /*TYSONNOVAK2001ODESYSTEM_HPP_*/\n", "meta": {"hexsha": "4fbd22f498df3a9de6d0369a599c7e2150b3c72d", "size": 8290, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cell_based/src/odes/TysonNovak2001OdeSystem.hpp", "max_stars_repo_name": "AvciRecep/chaste_2019", "max_stars_repo_head_hexsha": "1d46cdac647820d5c5030f8a9ea3a1019f6651c1", "max_stars_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-04-05T12:11:54.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-05T12:11:54.000Z", "max_issues_repo_path": "cell_based/src/odes/TysonNovak2001OdeSystem.hpp", "max_issues_repo_name": "AvciRecep/chaste_2019", "max_issues_repo_head_hexsha": "1d46cdac647820d5c5030f8a9ea3a1019f6651c1", "max_issues_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cell_based/src/odes/TysonNovak2001OdeSystem.hpp", "max_forks_repo_name": "AvciRecep/chaste_2019", "max_forks_repo_head_hexsha": "1d46cdac647820d5c5030f8a9ea3a1019f6651c1", "max_forks_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-04-05T14:26:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-09T08:18:17.000Z", "avg_line_length": 33.0278884462, "max_line_length": 126, "alphanum_fraction": 0.6963811821, "num_tokens": 1997, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.622459338205511, "lm_q1q2_score": 0.46444118381124777}}
{"text": "/**\n * @file test/ellipse_iterator.cpp\n */\n/*****************************************************************************\n** Includes\n*****************************************************************************/\n\n#include \"../include/cost_map_core/common.hpp\"\n#include <Eigen/Core>\n\n// gtest\n#include <gtest/gtest.h>\n\n// Limits\n#include <cfloat>\n\n// Vector\n#include <vector>\n#include \"../include/cost_map_core/cost_map.hpp\"\n#include \"../include/cost_map_core/iterators/ellipse_iterator.hpp\"\n\nusing namespace std;\nusing namespace Eigen;\n\nTEST(EllipseIterator, OneCellWideEllipse)\n{\n  cost_map::CostMap map( { \"types\" });\n  map.setGeometry(cost_map::Length(8.0, 5.0), 1.0, cost_map::Position(0.0, 0.0));\n\n  cost_map::EllipseIterator iterator(map, cost_map::Position(0.0, 0.0), cost_map::Length(8.0, 1.0));\n\n  EXPECT_FALSE(iterator.isPastEnd());\n  EXPECT_EQ(0, (*iterator)(0));\n  EXPECT_EQ(2, (*iterator)(1));\n\n  ++iterator;\n  EXPECT_FALSE(iterator.isPastEnd());\n  EXPECT_EQ(1, (*iterator)(0));\n  EXPECT_EQ(2, (*iterator)(1));\n\n  ++iterator;\n  EXPECT_FALSE(iterator.isPastEnd());\n  EXPECT_EQ(2, (*iterator)(0));\n  EXPECT_EQ(2, (*iterator)(1));\n\n  ++iterator;\n  ++iterator;\n  ++iterator;\n  ++iterator;\n  ++iterator;\n  EXPECT_FALSE(iterator.isPastEnd());\n  EXPECT_EQ(7, (*iterator)(0));\n  EXPECT_EQ(2, (*iterator)(1));\n\n  ++iterator;\n  EXPECT_TRUE(iterator.isPastEnd());\n}\n\nint main(int argc, char **argv)\n{\n  testing::InitGoogleTest(&argc, argv);\n  srand((int)time(0));\n  return RUN_ALL_TESTS();\n}\n\n", "meta": {"hexsha": "ffba74e2a709f138ef0644df02ae9592f1784493", "size": 1496, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cost_map_core/test/ellipse_iterator.cpp", "max_stars_repo_name": "teddyluo/cost_map", "max_stars_repo_head_hexsha": "e672b00ff65ab0b15ce57937cc2447db1483bda0", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 81.0, "max_stars_repo_stars_event_min_datetime": "2016-12-30T02:34:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T12:57:30.000Z", "max_issues_repo_path": "cost_map_core/test/ellipse_iterator.cpp", "max_issues_repo_name": "teddyluo/cost_map", "max_issues_repo_head_hexsha": "e672b00ff65ab0b15ce57937cc2447db1483bda0", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 35.0, "max_issues_repo_issues_event_min_datetime": "2016-02-12T05:16:33.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-18T18:55:35.000Z", "max_forks_repo_path": "cost_map_core/test/ellipse_iterator.cpp", "max_forks_repo_name": "stonier/cost_map", "max_forks_repo_head_hexsha": "e672b00ff65ab0b15ce57937cc2447db1483bda0", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 57.0, "max_forks_repo_forks_event_min_datetime": "2016-02-12T01:26:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-09T03:00:39.000Z", "avg_line_length": 22.6666666667, "max_line_length": 100, "alphanum_fraction": 0.6056149733, "num_tokens": 388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.6224593382055109, "lm_q1q2_score": 0.4644411838112476}}
{"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_GESDD_HPP\n#define BOOST_NUMERIC_BINDINGS_LAPACK_GESDD_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/detail/utils.hpp>\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n#  include <boost/static_assert.hpp>\n#  include <boost/type_traits/is_same.hpp>\n#endif \n\n#include <cassert>\n\nnamespace boost { namespace numeric { namespace bindings { \n\n  namespace lapack {\n\n    ///////////////////////////////////////////////////////////////////\n    //\n    // singular value decomposition \n    // \n    ///////////////////////////////////////////////////////////////////\n\n    /* \n     * (divide and conquer driver) \n     * gesdd() computes the singular value decomposition (SVD) of \n     * M-by-N matrix A, optionally computing the left and/or right \n     * singular vectors, by using divide-and-conquer method. \n     * The SVD is written\n     *\n     *     A = U * S * V^T    or    A = U * S * V^H\n     *\n     * where S is an M-by-N matrix which is zero except for its min(m,n)\n     * diagonal elements, U is an M-by-M orthogonal/unitary matrix, and V \n     * is an N-by-N orthogonal/unitary matrix. The diagonal elements of S\n     * are the singular values of A; they are real and non-negative, and \n     * are returnede in descending  order. The first min(m,n) columns of \n     * U and V are the left and right singular vectors of A. (Note that \n     * the routine returns V^T or V^H, not V.\n     */ \n\n    namespace detail {\n\n      inline \n      void gesdd (char const jobz, int const m, int const n, \n                  float* a, int const lda, \n                  float* s, float* u, int const ldu, \n                  float* vt, int const ldvt,\n                  float* work, int const lwork, float* /* dummy */, \n                  int* iwork, int* info)\n      {\n        LAPACK_SGESDD (&jobz, &m, &n, a, &lda, s, \n                       u, &ldu, vt, &ldvt, work, &lwork, iwork, info); \n      }\n\n      inline \n      void gesdd (char const jobz, int const m, int const n, \n                  double* a, int const lda, \n                  double* s, double* u, int const ldu, \n                  double* vt, int const ldvt,\n                  double* work, int const lwork, double* /* dummy */, \n                  int* iwork, int* info)\n      {\n        LAPACK_DGESDD (&jobz, &m, &n, a, &lda, s, \n                       u, &ldu, vt, &ldvt, work, &lwork, iwork, info); \n      }\n\n      inline \n      void gesdd (char const jobz, int const m, int const n, \n                  traits::complex_f* a, int const lda, \n                  float* s, traits::complex_f* u, int const ldu, \n                  traits::complex_f* vt, int const ldvt,\n                  traits::complex_f* work, int const lwork, \n                  float* rwork, int* iwork, int* info)\n      {\n        LAPACK_CGESDD (&jobz, &m, &n, \n                       traits::complex_ptr (a), &lda, s, \n                       traits::complex_ptr (u), &ldu, \n                       traits::complex_ptr (vt), &ldvt, \n                       traits::complex_ptr (work), &lwork, \n                       rwork, iwork, info); \n      }\n\n      inline \n      void gesdd (char const jobz, int const m, int const n, \n                  traits::complex_d* a, int const lda, \n                  double* s, traits::complex_d* u, int const ldu, \n                  traits::complex_d* vt, int const ldvt,\n                  traits::complex_d* work, int const lwork, \n                  double* rwork, int* iwork, int* info)\n      {\n        LAPACK_ZGESDD (&jobz, &m, &n, \n                       traits::complex_ptr (a), &lda, s, \n                       traits::complex_ptr (u), &ldu, \n                       traits::complex_ptr (vt), &ldvt, \n                       traits::complex_ptr (work), &lwork, \n                       rwork, iwork, info); \n      }\n\n\n      inline \n      int gesdd_min_work (float, char jobz, int m, int n) {\n        int minmn = m < n ? m : n; \n        int maxmn = m < n ? n : m; \n        int m3 = 3 * minmn; \n        int m4 = 4 * minmn; \n        int minw; \n        if (jobz == 'N') {\n          // leading comments:\n          //   LWORK >= 3*min(M,N) + max(max(M,N), 6*min(M,N))\n          // code:\n          //   LWORK >= 3*min(M,N) + max(max(M,N), 7*min(M,N))\n          int m7 = 7 * minmn; \n          minw = maxmn < m7 ? m7 : maxmn;\n          minw += m3; \n        }\n        if (jobz == 'O') {\n          // LWORK >= 3*min(M,N)*min(M,N) \n          //          + max(max(M,N), 5*min(M,N)*min(M,N)+4*min(M,N))\n          int m5 = 5 * minmn * minmn + m4; \n          minw = maxmn < m5 ? m5 : maxmn;\n          minw += m3 * minmn; \n        }\n        if (jobz == 'S' || jobz == 'A') {\n          // LWORK >= 3*min(M,N)*min(M,N) \n          //          + max(max(M,N), 4*min(M,N)*min(M,N)+4*min(M,N)).\n          int m44 = m4 * minmn + m4; \n          minw = maxmn < m44 ? m44 : maxmn;\n          minw += m3 * minmn; \n        }\n        return minw; \n      }\n      inline \n      int gesdd_min_work (double, char jobz, int m, int n) {\n        int minmn = m < n ? m : n; \n        int maxmn = m < n ? n : m; \n        int m3 = 3 * minmn; \n        int m4 = 4 * minmn; \n        int minw; \n        if (jobz == 'N') {\n          // leading comments:\n          //   LWORK >= 3*min(M,N) + max(max(M,N), 6*min(M,N))\n          // code:\n          //   LWORK >= 3*min(M,N) + max(max(M,N), 7*min(M,N))\n          int m7 = 7 * minmn; \n          minw = maxmn < m7 ? m7 : maxmn;\n          minw += m3; \n        }\n        else if (jobz == 'O') {\n          // LWORK >= 3*min(M,N)*min(M,N) \n          //          + max(max(M,N), 5*min(M,N)*min(M,N)+4*min(M,N))\n          int m5 = 5 * minmn * minmn + m4; \n          minw = maxmn < m5 ? m5 : maxmn;\n          minw += m3 * minmn; \n        }\n        else if (jobz == 'S' || jobz == 'A') {\n          // LWORK >= 3*min(M,N)*min(M,N) \n          //          + max(max(M,N), 4*min(M,N)*min(M,N)+4*min(M,N)).\n          int m44 = m4 * minmn + m4; \n          minw = maxmn < m44 ? m44 : maxmn;\n          minw += m3 * minmn; \n        }\n        else {\n          std::cerr << \"Invalid option passed to gesdd\" << std::endl ;  \n          return 0 ;\n        }\n        return minw; \n      }\n      inline \n      int gesdd_min_work (traits::complex_f, char jobz, int m, int n) {\n        int minmn = m < n ? m : n; \n        int maxmn = m < n ? n : m; \n        int m2 = 2 * minmn;\n        int minw = m2 + maxmn; \n        if (jobz == 'N') \n          // LWORK >= 2*min(M,N)+max(M,N)\n          ; \n        if (jobz == 'O') \n          // LWORK >= 2*min(M,N)*min(M,N) + 2*min(M,N) + max(M,N)\n          minw += m2 * minmn; \n        if (jobz == 'S' || jobz == 'A') \n          // LWORK >= min(M,N)*min(M,N) + 2*min(M,N) + max(M,N)\n          minw += minmn * minmn; \n        return minw; \n      }\n      inline \n      int gesdd_min_work (traits::complex_d, char jobz, int m, int n) {\n        int minmn = m < n ? m : n; \n        int maxmn = m < n ? n : m; \n        int m2 = 2 * minmn;\n        int minw = m2 + maxmn; \n        if (jobz == 'N') \n          // LWORK >= 2*min(M,N)+max(M,N)\n          ; \n        if (jobz == 'O') \n          // LWORK >= 2*min(M,N)*min(M,N) + 2*min(M,N) + max(M,N)\n          minw += m2 * minmn; \n        if (jobz == 'S' || jobz == 'A') \n          // LWORK >= min(M,N)*min(M,N) + 2*min(M,N) + max(M,N)\n          minw += minmn * minmn; \n        return minw; \n      }\n\n      inline \n      int gesdd_rwork (float, char, int, int) { return 1; }\n      inline \n      int gesdd_rwork (double, char, int, int) { return 1; }\n      inline \n      int gesdd_rwork (traits::complex_f, char jobz, int m, int n) {\n        int minmn = m < n ? m : n; \n        int minw; \n        if (jobz == 'N') \n          // LWORK >= 7*min(M,N)\n          minw = 7 * minmn; \n        else \n          // LRWORK >= 5*min(M,N)*min(M,N) + 5*min(M,N)\n          minw = 5 * (minmn * minmn + minmn);\n        return minw; \n      }\n      inline \n      int gesdd_rwork (traits::complex_d, char jobz, int m, int n) {\n        int minmn = m < n ? m : n; \n        int minw; \n        if (jobz == 'N') \n          // LWORK >= 7*min(M,N)\n          minw = 7 * minmn; \n        else \n          // LRWORK >= 5*min(M,N)*min(M,N) + 5*min(M,N)\n          minw = 5 * (minmn * minmn + minmn);\n        return minw; \n      }\n\n      inline\n      int gesdd_iwork (int m, int n) {\n        int minmn = m < n ? m : n; \n        return 8 * minmn; \n      }\n\n    } // detail \n\n\n    template <typename MatrA> \n    inline\n    int gesdd_work (char const q, char const jobz, MatrA const& a) \n    {\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrA>::matrix_structure, \n        traits::general_t\n      >::value)); \n#endif \n\n#ifdef BOOST_NUMERIC_BINDINGS_LAPACK_2\n      assert (q == 'M'); \n#else\n      assert (q == 'M' || q == 'O'); \n#endif \n      assert (jobz == 'N' || jobz == 'O' || jobz == 'A' || jobz == 'S'); \n\n      int const m = traits::matrix_size1 (a);\n      int const n = traits::matrix_size2 (a);\n      int lw = -13; \n\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n      typedef typename traits::matrix_traits<MatrA>::value_type val_t; \n#else \n      typedef typename MatrA::value_type val_t; \n#endif \n\n      if (q == 'M') \n        lw = detail::gesdd_min_work (val_t(), jobz, m, n);\n\n#ifndef BOOST_NUMERIC_BINDINGS_LAPACK_2\n      MatrA& a2 = const_cast<MatrA&> (a); \n      if (q == 'O') {\n        // traits::detail::array<val_t> w (1); \n        val_t w; \n        int info; \n        detail::gesdd (jobz, m, n, \n                       traits::matrix_storage (a2), \n                       traits::leading_dimension (a2),\n                       0, // traits::vector_storage (s),  \n                       0, // traits::matrix_storage (u),\n                       m, // traits::leading_dimension (u),\n                       0, // traits::matrix_storage (vt),\n                       n, // traits::leading_dimension (vt),\n                       &w, // traits::vector_storage (w),  \n                       -1, // traits::vector_size (w),  \n                       0, // traits::vector_storage (rw),  \n                       0, // traits::vector_storage (iw),  \n                       &info);\n        assert (info == 0); \n\n        lw = traits::detail::to_int (w);  \n        // // lw = traits::detail::to_int (w[0]); \n        /*\n         * is there a bug in LAPACK? or in Mandrake's .rpm?\n         * if m == 3, n == 4 and jobz == 'N' (real A), \n         * gesdd() returns optimal size == 1 while minimum size == 27\n         */\n        // int lwo = traits::detail::to_int (w);  \n        // int lwmin = detail::gesdd_min_work (val_t(), jobz, m, n);\n        // lw = lwo < lwmin ? lwmin : lwo; \n      }\n#endif \n      \n      return lw; \n    }\n\n\n    template <typename MatrA> \n    inline\n    int gesdd_rwork (char jobz, MatrA const& a) {\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrA>::matrix_structure, \n        traits::general_t\n      >::value)); \n#endif \n\n      assert (jobz == 'N' || jobz == 'O' || jobz == 'A' || jobz == 'S'); \n\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n      typedef typename traits::matrix_traits<MatrA>::value_type val_t; \n#else \n      typedef typename MatrA::value_type val_t; \n#endif \n\n      return detail::gesdd_rwork (val_t(), jobz, \n                                  traits::matrix_size1 (a),\n                                  traits::matrix_size2 (a));\n    }\n\n\n    template <typename MatrA> \n    inline\n    int gesdd_iwork (MatrA const& a) {\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrA>::matrix_structure, \n        traits::general_t\n      >::value)); \n#endif \n\n      return detail::gesdd_iwork (traits::matrix_size1 (a),\n                                  traits::matrix_size2 (a));\n    }\n\n\n    template <typename MatrA, typename VecS, \n              typename MatrU, typename MatrV, typename VecW, typename VecIW>\n    inline\n    int gesdd (char const jobz, MatrA& a, \n               VecS& s, MatrU& u, MatrV& vt, VecW& w, VecIW& iw) \n    {\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrA>::matrix_structure, \n        traits::general_t\n      >::value)); \n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrU>::matrix_structure, \n        traits::general_t\n      >::value)); \n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrV>::matrix_structure, \n        traits::general_t\n      >::value)); \n\n      BOOST_STATIC_ASSERT(\n        (boost::is_same<\n          typename traits::matrix_traits<MatrA>::value_type, float\n        >::value\n        ||\n        boost::is_same<\n          typename traits::matrix_traits<MatrA>::value_type, double\n        >::value));\n#endif \n\n      int const m = traits::matrix_size1 (a);\n      int const n = traits::matrix_size2 (a);\n      int const minmn = m < n ? m : n; \n\n      assert (minmn == traits::vector_size (s)); \n      assert ((jobz == 'N')\n              || ((jobz == 'O' || jobz == 'A') && m >= n)\n              || ((jobz == 'O' || jobz == 'A') \n                  && m < n \n                  && m == traits::matrix_size2 (u))\n              || (jobz == 'S' && minmn == traits::matrix_size2 (u))); \n      assert ((jobz == 'N' && traits::leading_dimension (u) >= 1)\n              || (jobz == 'O' \n                  && m >= n\n                  && traits::leading_dimension (u) >= 1)\n              || (jobz == 'O' \n                  && m < n\n                  && traits::leading_dimension (u) >= m)\n              || (jobz == 'A' && traits::leading_dimension (u) >= m)\n              || (jobz == 'S' && traits::leading_dimension (u) >= m));\n      assert (n == traits::matrix_size2 (vt)); \n      assert ((jobz == 'N' && traits::leading_dimension (vt) >= 1)\n              || (jobz == 'O' \n                  && m < n\n                  && traits::leading_dimension (vt) >= 1)\n              || (jobz == 'O' \n                  && m >= n\n                  && traits::leading_dimension (vt) >= n)\n              || (jobz == 'A' && traits::leading_dimension (vt) >= n)\n              || (jobz == 'S' && traits::leading_dimension (vt) >= minmn));\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n      typedef typename traits::matrix_traits<MatrA>::value_type val_t; \n#else \n      typedef typename MatrA::value_type val_t; \n#endif \n      assert (traits::vector_size (w) \n              >= detail::gesdd_min_work (val_t(), jobz, m, n)); \n      assert (traits::vector_size (iw) >= detail::gesdd_iwork (m, n)); \n\n      int info; \n      detail::gesdd (jobz, m, n, \n                     traits::matrix_storage (a), \n                     traits::leading_dimension (a),\n                     traits::vector_storage (s),  \n                     traits::matrix_storage (u),\n                     traits::leading_dimension (u),\n                     traits::matrix_storage (vt),\n                     traits::leading_dimension (vt),\n                     traits::vector_storage (w),  \n                     traits::vector_size (w),  \n                     0, // dummy argument \n                     traits::vector_storage (iw),  \n                     &info);\n      return info; \n    }\n\n\n    template <typename MatrA, typename VecS, typename MatrU, \n              typename MatrV, typename VecW, typename VecRW, typename VecIW>\n    inline\n    int gesdd (char const jobz, MatrA& a, \n               VecS& s, MatrU& u, MatrV& vt, VecW& w, VecRW& rw, VecIW& iw) \n    {\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrA>::matrix_structure, \n        traits::general_t\n      >::value)); \n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrU>::matrix_structure, \n        traits::general_t\n      >::value)); \n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrV>::matrix_structure, \n        traits::general_t\n      >::value)); \n#endif \n\n      int const m = traits::matrix_size1 (a);\n      int const n = traits::matrix_size2 (a);\n      int const minmn = m < n ? m : n; \n\n      assert (minmn == traits::vector_size (s)); \n      assert ((jobz == 'N')\n              || ((jobz == 'O' || jobz == 'A') && m >= n)\n              || ((jobz == 'O' || jobz == 'A') \n                  && m < n \n                  && m == traits::matrix_size2 (u))\n              || (jobz == 'S' && minmn == traits::matrix_size2 (u))); \n      assert ((jobz == 'N' && traits::leading_dimension (u) >= 1)\n              || (jobz == 'O' \n                  && m >= n\n                  && traits::leading_dimension (u) >= 1)\n              || (jobz == 'O' \n                  && m < n\n                  && traits::leading_dimension (u) >= m)\n              || (jobz == 'A' && traits::leading_dimension (u) >= m)\n              || (jobz == 'S' && traits::leading_dimension (u) >= m));\n      assert (n == traits::matrix_size2 (vt)); \n      assert ((jobz == 'N' && traits::leading_dimension (vt) >= 1)\n              || (jobz == 'O' \n                  && m < n\n                  && traits::leading_dimension (vt) >= 1)\n              || (jobz == 'O' \n                  && m >= n\n                  && traits::leading_dimension (vt) >= n)\n              || (jobz == 'A' && traits::leading_dimension (vt) >= n)\n              || (jobz == 'S' && traits::leading_dimension (vt) >= minmn));\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n      typedef typename traits::matrix_traits<MatrA>::value_type val_t; \n#else \n      typedef typename MatrA::value_type val_t; \n#endif \n      assert (traits::vector_size (w) \n              >= detail::gesdd_min_work (val_t(), jobz, m, n)); \n      assert (traits::vector_size (rw) \n              >= detail::gesdd_rwork (val_t(), jobz, m, n));\n      assert (traits::vector_size (iw) >= detail::gesdd_iwork (m, n)); \n\n      int info; \n      detail::gesdd (jobz, m, n, \n                     traits::matrix_storage (a), \n                     traits::leading_dimension (a),\n                     traits::vector_storage (s),  \n                     traits::matrix_storage (u),\n                     traits::leading_dimension (u),\n                     traits::matrix_storage (vt),\n                     traits::leading_dimension (vt),\n                     traits::vector_storage (w),  \n                     traits::vector_size (w),  \n                     traits::vector_storage (rw),  \n                     traits::vector_storage (iw),  \n                     &info);\n      return info; \n    }\n\n\n    template <typename MatrA, typename VecS, typename MatrU, typename MatrV>\n    inline\n    int gesdd (char const opt, char const jobz, \n               MatrA& a, VecS& s, MatrU& u, MatrV& vt) \n    {\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrA>::matrix_structure, \n        traits::general_t\n      >::value)); \n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrU>::matrix_structure, \n        traits::general_t\n      >::value)); \n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrV>::matrix_structure, \n        traits::general_t\n      >::value)); \n#endif \n\n      int const m = traits::matrix_size1 (a);\n      int const n = traits::matrix_size2 (a);\n#ifndef NDEBUG\n      int const minmn = m < n ? m : n; \n#endif // NDEBUG\n\n      assert (minmn == traits::vector_size (s)); \n      assert ((jobz == 'N')\n              || ((jobz == 'O' || jobz == 'A') && m >= n)\n              || ((jobz == 'O' || jobz == 'A') \n                  && m < n \n                  && m == traits::matrix_size2 (u))\n              || (jobz == 'S' && minmn == traits::matrix_size2 (u))); \n      assert ((jobz == 'N' && traits::leading_dimension (u) >= 1)\n              || (jobz == 'O' \n                  && m >= n\n                  && traits::leading_dimension (u) >= 1)\n              || (jobz == 'O' \n                  && m < n\n                  && traits::leading_dimension (u) >= m)\n              || (jobz == 'A' && traits::leading_dimension (u) >= m)\n              || (jobz == 'S' && traits::leading_dimension (u) >= m));\n      assert (n == traits::matrix_size2 (vt)); \n      assert ((jobz == 'N' && traits::leading_dimension (vt) >= 1)\n              || (jobz == 'O' \n                  && m < n\n                  && traits::leading_dimension (vt) >= 1)\n              || (jobz == 'O' \n                  && m >= n\n                  && traits::leading_dimension (vt) >= n)\n              || (jobz == 'A' && traits::leading_dimension (vt) >= n)\n              || (jobz == 'S' && traits::leading_dimension (vt) >= minmn));\n\n#ifdef BOOST_NUMERIC_BINDINGS_LAPACK_2\n      assert (opt == 'M'); \n#else\n      assert (opt == 'M' || opt == 'O'); \n#endif \n\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n      typedef typename traits::matrix_traits<MatrA>::value_type val_t; \n#else \n      typedef typename MatrA::value_type val_t; \n#endif \n      typedef typename traits::type_traits<val_t>::real_type real_t;\n\n      int const lw = gesdd_work (opt, jobz, a); \n      traits::detail::array<val_t> w (lw); \n      if (!w.valid()) return -101; \n\n      int const lrw = gesdd_rwork (jobz, a); \n      traits::detail::array<real_t> rw (lrw); \n      if (!rw.valid()) return -102; \n\n      int const liw = gesdd_iwork (a); \n      traits::detail::array<int> iw (liw); \n      if (!iw.valid()) return -103; \n\n      int info; \n      detail::gesdd (jobz, m, n, \n                     traits::matrix_storage (a), \n                     traits::leading_dimension (a),\n                     traits::vector_storage (s),  \n                     traits::matrix_storage (u),\n                     traits::leading_dimension (u),\n                     traits::matrix_storage (vt),\n                     traits::leading_dimension (vt),\n                     traits::vector_storage (w),  \n                     lw, //traits::vector_size (w),  \n                     traits::vector_storage (rw),  \n                     traits::vector_storage (iw),  \n                     &info);\n      return info; \n    }\n\n\n#ifndef BOOST_NUMERIC_BINDINGS_LAPACK_2\n\n    template <typename MatrA, typename VecS, typename MatrU, typename MatrV>\n    inline\n    int gesdd (char const jobz, MatrA& a, VecS& s, MatrU& u, MatrV& vt) {\n      return gesdd ('O', jobz, a, s, u, vt); \n    }\n\n    template <typename MatrA, typename VecS, typename MatrU, typename MatrV>\n    inline\n    int gesdd (MatrA& a, VecS& s, MatrU& u, MatrV& vt) {\n      return gesdd ('O', 'S', a, s, u, vt); \n    }\n\n    template <typename MatrA, typename VecS> \n    inline\n    int gesdd (MatrA& a, VecS& s) {\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrA>::matrix_structure, \n        traits::general_t\n      >::value)); \n#endif \n\n      int const m = traits::matrix_size1 (a);\n      int const n = traits::matrix_size2 (a);\n      int const minmn = m < n ? m : n; \n\n      assert (minmn == traits::vector_size (s)); \n\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n      typedef typename traits::matrix_traits<MatrA>::value_type val_t; \n#else \n      typedef typename MatrA::value_type val_t; \n#endif \n      typedef typename traits::type_traits<val_t>::real_type real_t;\n\n      int const lw = gesdd_work ('O', 'N', a); \n      traits::detail::array<val_t> w (lw); \n      if (!w.valid()) return -101; \n\n      int const lrw = gesdd_rwork ('N', a); \n      traits::detail::array<real_t> rw (lrw); \n      if (!rw.valid()) return -102; \n\n      int const liw = gesdd_iwork (a); \n      traits::detail::array<int> iw (liw); \n      if (!iw.valid()) return -103; \n\n      int info; \n      detail::gesdd ('N', m, n, \n                     traits::matrix_storage (a), \n                     traits::leading_dimension (a),\n                     traits::vector_storage (s),  \n                     0, // traits::matrix_storage (u),\n                     1, // traits::leading_dimension (u),\n                     0, // traits::matrix_storage (vt),\n                     1, // traits::leading_dimension (vt),\n                     traits::vector_storage (w),  \n                     traits::vector_size (w),  \n                     traits::vector_storage (rw),  \n                     traits::vector_storage (iw),  \n                     &info);\n      return info; \n    }\n\n#endif \n\n  } // namespace lapack\n\n}}}\n\n#endif \n", "meta": {"hexsha": "88040d717430378d25fabfe085ebe14424a6ff91", "size": 25119, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/bindings/lapack/gesdd.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/gesdd.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/gesdd.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": 35.4287729196, "max_line_length": 76, "alphanum_fraction": 0.495799992, "num_tokens": 7007, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.6224593241981982, "lm_q1q2_score": 0.4644411803874418}}
{"text": "/* boost random/xoroshiro.hpp header file\n *\n * Copyright degski 2017-2018\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\n#ifndef BOOST_RANDOM_XOROSHIRO_HPP\n#define BOOST_RANDOM_XOROSHIRO_HPP\n\n#include <cstdint>\n#include <istream>\n#include <ostream>\n#include <stdexcept>\n#include <vector>\n#include <iterator>\n#include <algorithm>\n\n#include <boost/config.hpp>\n#include <boost/random/detail/config.hpp>\n#include <boost/random/detail/seed.hpp>\n#include <boost/random/detail/seed_impl.hpp>\n#include <boost/detail/workaround.hpp>\n#include <boost/random/detail/disable_warnings.hpp>\n\nnamespace boost {\nnamespace random {\n\n#if !defined(BOOST_NO_INT64_T) && !defined(BOOST_NO_INTEGRAL_INT64_T)\n\n    namespace detail {\n\n        std::uint64_t xoroshiro_integer_hash ( std::uint64_t x );\n    }\n\n    /**\n    * This is a fixed-increment version of Java 8's SplittableRandom generator\n    * See http://dx.doi.org/10.1145/2714064.2660195 and\n    * http://docs.oracle.com/javase/8/docs/api/java/util/SplittableRandom.html\n    *\n    * It is a very fast generator passing BigCrush, and it can be useful if\n    * for some reason one absolutely want 64 bits of state;\n    *\n    * c-code by Sebastiano Vigna: http://xoroshiro.di.unimi.it/splitmix64.c\n    */\n    class splitmix64 {\n        friend class xoroshiro128plus;\n        friend class xoshiro256starstar;\n        friend class xoroshiro128plusshixo;\n        friend class xoroshiro128plusshixostar;\n        friend class xoroshiro128plusshixostarshixo;\n        friend class xorshift128plus;\n        friend class xorshift1024star;\n    public:\n        typedef std::uint64_t result_type;\n\n        // Required for old Boost.Random concept.\n        static const bool has_fixed_range = true;\n        static const std::uint64_t default_seed = std::uint64_t { 0x9E3779B97F4A7C15 };\n\n        /**\n        * Constructs a @c splitmix64, using the default seed.\n        */\n        splitmix64 ( )\n        {\n            seed ( );\n        }\n\n        /**\n        * Constructs a @c splitmix64, seeding it with @c value.\n        */\n        BOOST_RANDOM_DETAIL_ARITHMETIC_CONSTRUCTOR ( splitmix64,\n            std::uint64_t, value )\n        {\n            seed ( value );\n        }\n\n        /**\n        * Constructs a @c splitmix64, seeding it with values\n        * produced by a call to @c seq.generate().\n        */\n        BOOST_RANDOM_DETAIL_SEED_SEQ_CONSTRUCTOR ( splitmix64,\n            SeedSeq, seq )\n        {\n            seed ( seq );\n        }\n\n        /**\n        * Constructs a @c splitmix64 and seeds it with values taken\n        * from the iterator range [first, last) and adjusts first to\n        * point to the element after the last one used. If there are\n        * not enough elements, throws @c std::invalid_argument.\n        *\n        * first and last must be input iterators.\n        */\n        template<class It>\n        splitmix64 ( It& first, It last )\n        {\n            seed ( first, last );\n        }\n\n        // compiler-generated copy constructor and assignment operator are fine.\n\n        /**\n        * Calls seed(default_seed).\n        */\n        void seed ( )\n        {\n            seed ( default_seed );\n        }\n\n        /**\n        * Seeds a @c splitmix64 using the supplied value. 'Hashes' @c value\n        * using the bijection described by:\n        *\n        * std::uint64_t integer_hash(std::uint64_t x) {\n        *\n        *     x = ((x >> 32) ^ x) * 0xDE17C195AA959A81;\n        *\t   x = ((x >> 32) ^ x) * 0xDE17C195AA959A81;\n        *     x = ((x >> 32) ^ x);\n        *\n        *\t   return x;\n        * }\n        */\n        BOOST_RANDOM_DETAIL_ARITHMETIC_SEED ( splitmix64, std::uint64_t, value )\n        {\n            _s [ 0 ] = detail::xoroshiro_integer_hash ( value );\n        }\n\n        /**\n        * Seeds a @c splitmix64 using values from a SeedSeq.\n        */\n        BOOST_RANDOM_DETAIL_SEED_SEQ_SEED ( splitmix64, SeedSeq, seq )\n        {\n            detail::seed_array_int<64, 1, SeedSeq, std::uint64_t> ( seq, _s );\n        }\n\n        /**\n        * seeds a @c splitmix64 with values taken from the iterator\n        * range [first, last) and adjusts @c first to point to the\n        * element after the last one used.  If there are not enough\n        * elements, throws @c std::invalid_argument.\n        *\n        * @c first and @c last must be input iterators.\n        */\n        template<class It>\n        void seed ( It& first, It last )\n        {\n            detail::fill_array_int<64, 1, It, std::uint64_t> ( first, last, _s );\n        }\n\n        /**\n        * Returns the smallest value that the @c splitmix64\n        * can produce.\n        */\n        static result_type min BOOST_PREVENT_MACRO_SUBSTITUTION ( )\n        {\n            return 0;\n        }\n\n        /**\n        * Returns the largest value that the @c splitmix64\n        * can produce.\n        */\n        static result_type max BOOST_PREVENT_MACRO_SUBSTITUTION ( )\n        {\n            return UINT64_MAX;\n        }\n\n        /** Returns the next value of the @c splitmix64. */\n        std::uint64_t operator()( )\n        {\n            return hash ( next ( ) );\n        }\n\n        /** Fills a range with random values. */\n        template<class Iter>\n        void generate ( Iter first, Iter last )\n        {\n            detail::generate_from_int ( *this, first, last );\n        }\n\n        /** Advances the state of the generator by @c z. */\n        void discard ( boost::uintmax_t z )\n        {\n            // This seems to be the fastest way (release),\n            // as opposed to anything more fancy.\n            while ( z-- ) {\n                next ( );\n            }\n        }\n\n        friend bool operator==( const splitmix64& x,\n            const splitmix64& y )\n        {\n            return x._s [ 0 ] == y._s [ 0 ];\n        }\n\n        friend bool operator!=( const splitmix64& x,\n            const splitmix64& y )\n        {\n            return !( x == y );\n        }\n\n        /** Writes a @c splitmix64 to a @c std::ostream. */\n        template<class CharT, class Traits>\n        friend std::basic_ostream<CharT, Traits>&\n            operator<<( std::basic_ostream<CharT, Traits>& os,\n                const splitmix64& sm64 )\n        {\n            os << sm64._s [ 0 ];\n            return os;\n        }\n\n        /** Reads a @c splitmix64 from a @c std::istream. */\n        template<class CharT, class Traits>\n        friend std::basic_istream<CharT, Traits>&\n            operator >> ( std::basic_istream<CharT, Traits>& is,\n                splitmix64& sm64 )\n        {\n            is >> sm64._s [ 0 ];\n            return is;\n        }\n\n    private:\n\n        /// \\cond show_private\n\n        std::uint64_t next ( )\n        {\n            return ( _s [ 0 ] += std::uint64_t { 0x9E3779B97F4A7C15 } );\n        }\n\n        static std::uint64_t hash ( std::uint64_t z )\n        {\n            z = ( z ^ ( z >> 30 ) ) * std::uint64_t { 0xBF58476D1CE4E5B9 };\n            z = ( z ^ ( z >> 27 ) ) * std::uint64_t { 0x94D049BB133111EB };\n            return z ^ ( z >> 31 );\n        }\n\n        /// \\endcond\n\n        std::uint64_t _s [ 1 ];\n    };\n\nnamespace detail {\n\n    // const std::uint64_t v = 0x1AEC805299990163, y = 0xCDFB859A3DD0884B;\n\n    std::uint64_t xoroshiro_integer_hash(std::uint64_t x)\n    {\n        x = ((x >> 32) ^ x) * std::uint64_t { 0x1AEC805299990163 };\n        x = ((x >> 32) ^ x);\n        return x;\n    }\n\n    template<class SeedSeq, std::size_t n>\n    void seed_array_non_zero_int(SeedSeq &seq, std::uint64_t (&x)[n])\n    {\n        std::uint_least32_t storage[2 * n];\n        seq.generate(std::begin(storage), std::end(storage));\n\n        std::size_t j = 0;\n        for (; j < n; ++j) {\n            x[j] = (static_cast<std::uint64_t>(storage[2 * j + 1]) << 32)\n                + static_cast<std::uint64_t>(storage [2 * j]);\n            if (x[j]) {\n                // non-zero seed detected, carry on, without checking...\n                ++j;\n                for (; j < n; ++j) {\n                    x[j] = (static_cast<std::uint64_t>(storage[2 * j + 1]) << 32)\n                        + static_cast<std::uint64_t>(storage[2 * j]);\n                }\n                return;\n            }\n        }\n\n        // Fix zeros, generating some kind of seed from the\n        // SeedSeq, subsequently use this seed for the seeding\n        // of boost::random::splitmix64.\n        std::uint64_t seed = 0;\n\n        std::vector<int> v;\n        v.reserve(seq.size());\n        seq.param(std::back_inserter(v));\n        int shift = 32;\n\n        for (auto i : v) {\n            seed ^= detail::xoroshiro_integer_hash((static_cast<std::uint64_t>(i) << (shift ^= int { 32 })) ^ seed);\n        }\n\n        boost::random::splitmix64 gen(seed);\n        std::generate(std::begin(x), std::end(x), gen);\n    }\n\n    template<class It, std::size_t n>\n    void fill_array_non_zero_int(It& first, It last, std::uint64_t (&x)[n])\n    {\n        if (std::distance(first, last) < (2 * n)) {\n            throw(std::invalid_argument(\"Not enough elements in call to seed.\"));\n        }\n\n        std::size_t j = 0;\n\n        for (; j < n; ++j) {\n            x[j] = static_cast<std::uint64_t>(*first);\n            ++first;\n            x[j] |= static_cast<std::uint64_t>(*first) << 32;\n            ++first;\n            if (x[j]) {\n                ++j;\n                for (; j < n; ++j) {\n                     x[j] = static_cast<std::uint64_t>(*first);\n                     ++first;\n                     x[j] |= static_cast<std::uint64_t>(*first) << 32;\n                     ++first;\n                }\n                return;\n            }\n        }\n\n        // Fix zeros.\n        boost::random::splitmix64 gen;\n        std::generate(std::begin(x), std::end(x), gen);\n    }\n\n} // namespace detail\n\n\n/**\n * xoroshiro128+\n *\n * xoroshiro128+ (XOR/rotate/shift/rotate) is the successor to xorshift128+.\n *\n * Instead of perpetuating  Marsaglia's tradition  of xorshift as a  basic\n * operation, xoroshiro128+ uses a carefully handcrafted shift/rotate-based\n * linear transformation designed by Sebastiano Vigna in collaboration with\n * David Blackman.\n *\n * It is the fastest full-period generator passing BigCrush without systematic\n * failures, but due to the relatively short period it is acceptable only for\n * applications with a mild amount of parallelism; otherwise, use a\n * xorshift1024* generator.\n *\n * Beside passing BigCrush, this generator passes the PractRand test suite\n * up to (and included)  16TB, with  the exception of  binary rank  tests,\n * which fail due to the lowest bit being an LFSR; all other bits pass all\n * tests. Use a sign test to extract a random Boolean value.\n *\n * The state must be seeded so that it is not everywhere zero.\n *\n * Web-site: http://xoroshiro.di.unimi.it/\n */\nclass xoroshiro128plus\n{\npublic:\n    typedef std::uint64_t result_type;\n\n    // Required for old Boost.Random concept.\n    static const bool has_fixed_range = true;\n    static const std::uint64_t default_seed = 1;\n\n    /**\n     * Constructs a @c xoroshiro128plus, using the default seed.\n     */\n    xoroshiro128plus()\n    { seed(); }\n\n    /**\n     * Constructs a @c xoroshiro128plus, seeding it with @c value.\n     */\n    BOOST_RANDOM_DETAIL_ARITHMETIC_CONSTRUCTOR(xoroshiro128plus,\n                                               std::uint64_t, value)\n    { seed(value); }\n\n    /**\n     * Constructs a @c xoroshiro128plus, seeding it with values\n     * produced by a call to @c seq.generate().\n     */\n    BOOST_RANDOM_DETAIL_SEED_SEQ_CONSTRUCTOR(xoroshiro128plus,\n                                             SeedSeq, seq)\n    { seed(seq); }\n\n    /**\n     * Constructs a @c xoroshiro128plus and seeds it with values\n     * taken from the iterator range [first, last) and adjusts\n     * first to point to the element after the last one used.\n     * If there are not enough elements, throws @c std::invalid_argument.\n     *\n     * first and last must be input iterators.\n     */\n    template<class It>\n    xoroshiro128plus(It& first, It last)\n    { seed(first, last); }\n\n    // compiler-generated copy constructor and assignment operator are fine.\n\n    /**\n     * Calls seed(default_seed)\n     */\n    void seed()\n    { seed(default_seed); }\n\n    /**\n     * seeds a @c xoroshiro128plus with splitmix64, as per Sebastiano\n     * Vigna's recommendation.\n     */\n    BOOST_RANDOM_DETAIL_ARITHMETIC_SEED(xoroshiro128plus, std::uint64_t, value)\n    {\n        std::uint64_t s = value + std::uint64_t { 0x9E3779B97F4A7C15 };\n        _s[0] = detail::xoroshiro_integer_hash (s);\n        _s[1] = detail::xoroshiro_integer_hash ((s += std::uint64_t { 0x9E3779B97F4A7C15 }));\n    }\n\n    /**\n     * Seeds a @c xoroshiro128plus using values from a SeedSeq. If a\n     * valid seed cannot be generated throws @c std::runtime_error.\n     */\n    BOOST_RANDOM_DETAIL_SEED_SEQ_SEED(xoroshiro128plus, SeedSeq, seq)\n    {\n        detail::seed_array_non_zero_int(seq, _s);\n        warmup();\n    }\n\n    /**\n     * Seeds a @c xoroshiro128plus with values taken from the\n     * iterator range [first, last) and adjusts @c first to\n     * point to the element after the last one used. If there are\n     * not enough elements or all the whole input range is zero,\n     * throws @c std::invalid_argument.\n     *\n     * @c first and @c last must be input iterators.\n     */\n    template<class It>\n    void seed(It& first, It last)\n    {\n        detail::fill_array_non_zero_int(first, last, _s);\n        warmup();\n    }\n\n    /**\n     * Returns the smallest value that the @c xoroshiro128plus\n     * can produce.\n     */\n    static result_type min BOOST_PREVENT_MACRO_SUBSTITUTION ()\n    { return 0; }\n\n    /**\n     * Returns the largest value that the @c xoroshiro128plus\n     * can produce.\n     */\n    static result_type max BOOST_PREVENT_MACRO_SUBSTITUTION ()\n    { return UINT64_MAX; }\n\n    /** Returns the next value of the @c xoroshiro128plus. */\n    std::uint64_t operator()()\n    {\n        std::uint64_t r = _s[0] + _s[1];\n        next();\n        return r;\n    }\n\n    /** Fills a range with random values. */\n    template<class Iter>\n    void generate(Iter first, Iter last)\n    { detail::generate_from_int(*this, first, last); }\n\n    /** Advances the state of the generator by @c z. */\n    void discard(std::uintmax_t z)\n    {\n        while (z--) {\n            next();\n        }\n    }\n\n    /**\n     * This is a jump function for the generator. It is equivalent\n     * to calling @c discard(2^64) @c z times; it can be used to\n     * generate 2^64 non-overlapping subsequences for parallel\n     * computations.\n     */\n    void jump(std::uintmax_t z = 1)\n    {\n        while(z--) {\n            std::uint64_t s0 = 0, s1 = 0;\n            for (std::size_t b = 0; b < 64; ++b ) {\n                if (std::uint64_t { 0xBEAC0467EBA5FACB } & std::uint64_t { 1 } << b) {\n                    s0 ^= _s[0], s1 ^= _s[1];\n                }\n                next();\n            }\n            for ( std::size_t b = 0; b < 64; ++b ) {\n                if (std::uint64_t { 0xD86B048B86AA9922 } & std::uint64_t { 1 } << b) {\n                    s0 ^= _s[0], s1 ^= _s[1];\n                }\n                next();\n            }\n            _s[0] = s0, _s[1] = s1;\n        }\n    }\n\n    friend bool operator==(const xoroshiro128plus& x,\n                           const xoroshiro128plus& y)\n    { return x._s[0] == y._s[0] && x._s[1] == y._s[1]; }\n\n    friend bool operator!=(const xoroshiro128plus& x,\n                           const xoroshiro128plus& y)\n    { return !(x == y); }\n\n    /** Writes a @c xoroshiro128plus to a @c std::ostream. */\n    template<class CharT, class Traits>\n    friend std::basic_ostream<CharT,Traits>&\n    operator<<(std::basic_ostream<CharT,Traits>& os,\n               const xoroshiro128plus& xoro)\n    {\n        os << xoro._s[0] << ' ' << xoro._s[1];\n        return os;\n    }\n\n    /** Reads a @c xoroshiro128plus from a @c std::istream. */\n    template<class CharT, class Traits>\n    friend std::basic_istream<CharT,Traits>&\n    operator>>(std::basic_istream<CharT,Traits>& is,\n               xoroshiro128plus& xoro)\n    {\n        is >> xoro._s[0] >> std::ws >> xoro._s[1];\n        return is;\n    }\n\nprivate:\n\n    /// \\cond show_private\n\n    // Rotate left, use of intrinsic shows no speed-up. */\n    static std::uint64_t rotl(const std::uint64_t x, const int k)\n    { return (x << k) | (x >> (64 - k)); }\n\n    /** Advance the state by 1 step. */\n    void next()\n    {\n        _s[1] ^= _s [0];\n        _s[0] = rotl(_s[0], 55);\n        _s[0] ^= _s[1];\n        _s[0] ^= _s[1] << 14;\n        _s[1] = rotl(_s[1], 36);\n    }\n\n    // As per http://www0.cs.ucl.ac.uk/staff/D.Jones/GoodPracticeRNG.pdf\n    void warmup()\n    {\n        discard(8);\n    }\n\n    /// \\endcond\n\n    std::uint64_t _s[2];\n};\n\n/**\n * From the source implmentation, expressing the opinions of the original\n * authors:\n *\n * Written in 2018 by David Blackman and Sebastiano Vigna (vigna@acm.org)\n *\n * To the extent possible under law, the author has dedicated all copyright\n * and related and neighboring rights to this software to the public domain\n * worldwide. This software is distributed without any warranty.\n *\n * See <http:*creativecommons.org/publicdomain/zero/1.0/>.\n *\n * This is xoshiro256starstar 1.0, our all-purpose, rock-solid generator. It\n * has excellent (sub-ns) speed, a state (256 bits) that is large enough for\n * any parallel application, and it passes all tests we are aware of.\n *\n * For generating just floating-point numbers, xoshiro256plus is even faster.\n *\n * The state must be seeded so that it is not everywhere zero. If you have\n * a 64-bit seed, we suggest to seed a splitmix64 generator and use its\n * output to fill s.\n */\n\nclass xoshiro256starstar\n{\npublic:\n    typedef std::uint64_t result_type;\n\n    // Required for old Boost.Random concept.\n    static const bool has_fixed_range = true;\n    static const std::uint64_t default_seed = 1;\n\n    /**\n     * Constructs a @c xoshiro256starstar, using the default seed.\n     */\n    xoshiro256starstar()\n    { seed(); }\n\n    /**\n     * Constructs a @c xoshiro256starstar, seeding it with @c value.\n     */\n    BOOST_RANDOM_DETAIL_ARITHMETIC_CONSTRUCTOR(xoshiro256starstar,\n                                               std::uint64_t, value)\n    { seed(value); }\n\n    /**\n     * Constructs a @c xoshiro256starstar, seeding it with values\n     * produced by a call to @c seq.generate().\n     */\n    BOOST_RANDOM_DETAIL_SEED_SEQ_CONSTRUCTOR(xoshiro256starstar,\n                                             SeedSeq, seq)\n    { seed(seq); }\n\n    /**\n     * Constructs a @c xoshiro256starstar and seeds it with values\n     * taken from the iterator range [first, last) and adjusts\n     * first to point to the element after the last one used.\n     * If there are not enough elements, throws @c std::invalid_argument.\n     *\n     * first and last must be input iterators.\n     */\n    template<class It>\n    xoshiro256starstar(It& first, It last)\n    { seed(first, last); }\n\n    // compiler-generated copy constructor and assignment operator are fine.\n\n    /**\n     * Calls seed(default_seed)\n     */\n    void seed()\n    { seed(default_seed); }\n\n    /**\n     * seeds a @c xoshiro256starstar with splitmix64, as per Sebastiano\n     * Vigna's recommendation.\n     */\n    BOOST_RANDOM_DETAIL_ARITHMETIC_SEED(xoshiro256starstar, std::uint64_t, value)\n    {\n        std::uint64_t s = value + std::uint64_t ( 0x9E3779B97F4A7C15 );\n        _s[0] = detail::xoroshiro_integer_hash(s);\n        _s[1] = detail::xoroshiro_integer_hash((s += std::uint64_t { 0x9E3779B97F4A7C15 }));\n        _s[2] = detail::xoroshiro_integer_hash((s += std::uint64_t { 0x9E3779B97F4A7C15 }));\n        _s[3] = detail::xoroshiro_integer_hash((s += std::uint64_t { 0x9E3779B97F4A7C15 }));\n    }\n\n    /**\n     * Seeds a @c xoshiro256starstar using values from a SeedSeq. If a\n     * valid seed cannot be generated throws @c std::runtime_error.\n     */\n    BOOST_RANDOM_DETAIL_SEED_SEQ_SEED(xoshiro256starstar, SeedSeq, seq)\n    {\n        detail::seed_array_non_zero_int(seq, _s);\n        warmup();\n    }\n\n    /**\n     * Seeds a @c xoshiro256starstar with values taken from the\n     * iterator range [first, last) and adjusts @c first to\n     * point to the element after the last one used. If there are\n     * not enough elements or all the whole input range is zero,\n     * throws @c std::invalid_argument.\n     *\n     * @c first and @c last must be input iterators.\n     */\n    template<class It>\n    void seed(It& first, It last)\n    {\n        detail::fill_array_non_zero_int(first, last, _s);\n        warmup();\n    }\n\n    /**\n     * Returns the smallest value that the @c xoshiro256starstar\n     * can produce.\n     */\n    static result_type min BOOST_PREVENT_MACRO_SUBSTITUTION ()\n    { return 0; }\n\n    /**\n     * Returns the largest value that the @c xoshiro256starstar\n     * can produce.\n     */\n    static result_type max BOOST_PREVENT_MACRO_SUBSTITUTION ()\n    { return UINT64_MAX; }\n\n    /** Returns the next value of the @c xoshiro256starstar. */\n    std::uint64_t operator()()\n    {\n        const std::uint64_t r = rotl ( _s[1] * 5, 7 ) * 9;\n        next();\n        return r;\n    }\n\n    /** Fills a range with random values. */\n    template<class Iter>\n    void generate(Iter first, Iter last)\n    { detail::generate_from_int(*this, first, last); }\n\n    /** Advances the state of the generator by @c z. */\n    void discard(std::uintmax_t z)\n    {\n        while (z--) {\n            next();\n        }\n    }\n\n    /**\n     * This is the jump function for @c xoshiro256starstar. It is equivalent\n     * to 2^128 calls to next() @c z times; it can be used to generate\n     * 2^128 non-overlapping subsequences for parallel computations.\n     */\n    void jump(std::uintmax_t z = 1)\n    {\n        static const std::uint64_t JUMP[4] = { 0x180EC6D33CFD0ABA, 0xD5A61266F0C9392C, 0xA9582618E03FC9AA, 0x39ABDC4529B1661C };\n        while(z--) {\n            std::uint64_t s0 = 0, s1 = 0, s2 = 0, s3 = 0;\n            for ( int i = 0; i < sizeof JUMP / sizeof *JUMP; i++ )\n                for ( int b = 0; b < 64; ++b ) {\n                    if ( JUMP[i] & std::uint64_t(1) << b ) {\n                        s0 ^= _s[0];\n                        s1 ^= _s[1];\n                        s2 ^= _s[2];\n                        s3 ^= _s[3];\n                    }\n                    next();\n                }\n\n            _s[0] = s0;\n            _s[1] = s1;\n            _s[2] = s2;\n            _s[3] = s3;\n        }\n    }\n\n    /**\n     * This is the long-jump function for @c xoshiro256starstar. It is\n     * equivalent to 2^192 calls to next(); it can be used to generate\n     * 2^64 starting points, from each of which jump() will generate\n     * 2^64 non-overlapping subsequences for parallel distributed\n     * computations.\n     */\n    void long_jump()\n    {\n        static const std::uint64_t LONG_JUMP[4] = { 0x76E15D3EFEFDCBBF, 0xC5004E441C522FB3, 0x77710069854EE241, 0x39109BB02ACBE635 };\n        std::uint64_t s0 = 0, s1 = 0, s2 = 0, s3 = 0;\n        for ( std::size_t i = 0; i < sizeof LONG_JUMP / sizeof *LONG_JUMP; ++i )\n            for ( std::size_t b = 0; b < std::size_t ( 64 ); ++b ) {\n                if ( LONG_JUMP[i] & std::uint64_t ( 1 ) << b ) {\n                    s0 ^= _s[0];\n                    s1 ^= _s[1];\n                    s2 ^= _s[2];\n                    s3 ^= _s[3];\n                }\n                next();\n            }\n\n        _s[0] = s0;\n        _s[1] = s1;\n        _s[2] = s2;\n        _s[3] = s3;\n    }\n\n    friend bool operator==(const xoshiro256starstar& x,\n                           const xoshiro256starstar& y)\n    { return x._s[0] == y._s[0] && x._s[1] == y._s[1] && x._s [2] == y._s [2] && x._s [3] == y._s [3]; }\n\n    friend bool operator!=(const xoshiro256starstar& x,\n                           const xoshiro256starstar& y)\n    { return !(x == y); }\n\n    /** Writes a @c xoshiro256starstar to a @c std::ostream. */\n    template<class CharT, class Traits>\n    friend std::basic_ostream<CharT,Traits>&\n    operator<<(std::basic_ostream<CharT,Traits>& os,\n               const xoshiro256starstar& xoro)\n    {\n        os << xoro._s[0] << ' ' << xoro._s[1] << ' ' << xoro._s[2] << ' ' << xoro._s[3];\n        return os;\n    }\n\n    /** Reads a @c xoshiro256starstar from a @c std::istream. */\n    template<class CharT, class Traits>\n    friend std::basic_istream<CharT,Traits>&\n    operator>>(std::basic_istream<CharT,Traits>& is,\n               xoshiro256starstar& xoro)\n    {\n        is >> xoro._s[0] >> std::ws >> xoro._s[1] >> std::ws >> xoro._s[2] >> std::ws >> xoro._s[3];\n        return is;\n    }\n\nprivate:\n\n    /// \\cond show_private\n\n    // Rotate left, use of intrinsic shows no speed-up. */\n    static std::uint64_t rotl(const std::uint64_t x, const int k)\n    { return (x << k) | (x >> (64 - k)); }\n\n    /** Advance the state by 1 step. */\n    void next()\n    {\n        const std::uint64_t t = _s[1] << 17;\n\n        _s[2] ^= _s[0];\n        _s[3] ^= _s[1];\n        _s[1] ^= _s[2];\n        _s[0] ^= _s[3];\n\n        _s[2] ^= t;\n\n        _s[3] = rotl ( _s[3], 45 );\n    }\n\n    // As per http://www0.cs.ucl.ac.uk/staff/D.Jones/GoodPracticeRNG.pdf\n    void warmup()\n    {\n        discard(8);\n    }\n\n    /// \\endcond\n\n    std::uint64_t _s[4];\n};\n\n\n/**\n * From the source implmentation, expressing the opinions of the original\n * authors:\n *\n *  Written in 2018 by David Blackman and Sebastiano Vigna (vigna@acm.org)\n *\n * To the extent possible under law, the author has dedicated all copyright\n * and related and neighboring rights to this software to the public domain\n * worldwide. This software is distributed without any warranty.\n *\n * See <http://creativecommons.org/publicdomain/zero/1.0/>.\n *\n *\n * This is xoshiro256plus 1.0, our best and fastest generator for floating-point\n * numbers. We suggest to use its upper bits for floating-point\n * generation, as it is slightly faster than xoshiro256starstar. It passes all\n * tests we are aware of except for the lowest three bits, which might\n * fail linearity tests (and just those), so if low linear complexity is\n * not considered an issue (as it is usually the case) it can be used to\n * generate 64-bit outputs, too.\n *\n * We suggest to use a sign test to extract a random Boolean value, and\n * right shifts to extract subsets of bits.\n *\n * The state must be seeded so that it is not everywhere zero. If you have\n * a 64-bit seed, we suggest to seed a splitmix64 generator and use its\n * output to fill s.\n */\n\nclass xoshiro256plus\n{\npublic:\n    typedef std::uint64_t result_type;\n\n    // Required for old Boost.Random concept.\n    static const bool has_fixed_range = true;\n    static const std::uint64_t default_seed = 1;\n\n    /**\n     * Constructs a @c xoshiro256plus, using the default seed.\n     */\n    xoshiro256plus()\n    { seed(); }\n\n    /**\n     * Constructs a @c xoshiro256plus, seeding it with @c value.\n     */\n    BOOST_RANDOM_DETAIL_ARITHMETIC_CONSTRUCTOR(xoshiro256plus,\n                                               std::uint64_t, value)\n    { seed(value); }\n\n    /**\n     * Constructs a @c xoshiro256plus, seeding it with values\n     * produced by a call to @c seq.generate().\n     */\n    BOOST_RANDOM_DETAIL_SEED_SEQ_CONSTRUCTOR(xoshiro256plus,\n                                             SeedSeq, seq)\n    { seed(seq); }\n\n    /**\n     * Constructs a @c xoshiro256plus and seeds it with values\n     * taken from the iterator range [first, last) and adjusts\n     * first to point to the element after the last one used.\n     * If there are not enough elements, throws @c std::invalid_argument.\n     *\n     * first and last must be input iterators.\n     */\n    template<class It>\n    xoshiro256plus(It& first, It last)\n    { seed(first, last); }\n\n    // compiler-generated copy constructor and assignment operator are fine.\n\n    /**\n     * Calls seed(default_seed)\n     */\n    void seed()\n    { seed(default_seed); }\n\n    /**\n     * seeds a @c xoshiro256plus with splitmix64, as per Sebastiano\n     * Vigna's recommendation.\n     */\n    BOOST_RANDOM_DETAIL_ARITHMETIC_SEED(xoshiro256plus, std::uint64_t, value)\n    {\n        std::uint64_t s = value + std::uint64_t ( 0x9E3779B97F4A7C15 );\n        _s[0] = detail::xoroshiro_integer_hash(s);\n        _s[1] = detail::xoroshiro_integer_hash((s += std::uint64_t { 0x9E3779B97F4A7C15 }));\n        _s[2] = detail::xoroshiro_integer_hash((s += std::uint64_t { 0x9E3779B97F4A7C15 }));\n        _s[3] = detail::xoroshiro_integer_hash((s += std::uint64_t { 0x9E3779B97F4A7C15 }));\n    }\n\n    /**\n     * Seeds a @c xoshiro256plus using values from a SeedSeq. If a\n     * valid seed cannot be generated throws @c std::runtime_error.\n     */\n    BOOST_RANDOM_DETAIL_SEED_SEQ_SEED(xoshiro256plus, SeedSeq, seq)\n    {\n        detail::seed_array_non_zero_int(seq, _s);\n        warmup();\n    }\n\n    /**\n     * Seeds a @c xoshiro256plus with values taken from the\n     * iterator range [first, last) and adjusts @c first to\n     * point to the element after the last one used. If there are\n     * not enough elements or all the whole input range is zero,\n     * throws @c std::invalid_argument.\n     *\n     * @c first and @c last must be input iterators.\n     */\n    template<class It>\n    void seed(It& first, It last)\n    {\n        detail::fill_array_non_zero_int(first, last, _s);\n        warmup();\n    }\n\n    /**\n     * Returns the smallest value that the @c xoshiro256plus\n     * can produce.\n     */\n    static result_type min BOOST_PREVENT_MACRO_SUBSTITUTION ()\n    { return 0; }\n\n    /**\n     * Returns the largest value that the @c xoshiro256plus\n     * can produce.\n     */\n    static result_type max BOOST_PREVENT_MACRO_SUBSTITUTION ()\n    { return UINT64_MAX; }\n\n    /** Returns the next value of the @c xoshiro256plus. */\n    std::uint64_t operator()()\n    {\n        const std::uint64_t r = _s[0] + _s[3];\n        next();\n        return r;\n    }\n\n    /** Fills a range with random values. */\n    template<class Iter>\n    void generate(Iter first, Iter last)\n    { detail::generate_from_int(*this, first, last); }\n\n    /** Advances the state of the generator by @c z. */\n    void discard(std::uintmax_t z)\n    {\n        while (z--) {\n            next();\n        }\n    }\n\n    /**\n     * This is the jump function for @c xoshiro256plus. It is equivalent\n     * to 2^128 calls to next() @c z times; it can be used to generate\n     * 2^128 non-overlapping subsequences for parallel computations.\n     */\n    void jump(std::uintmax_t z = 1)\n    {\n        static const std::uint64_t JUMP[4] = { 0x180EC6D33CFD0ABA, 0xD5A61266F0C9392C, 0xA9582618E03FC9AA, 0x39ABDC4529B1661C };\n        while(z--) {\n            std::uint64_t s0 = 0, s1 = 0, s2 = 0, s3 = 0;\n            for(std::size_t i = 0; i < sizeof JUMP / sizeof *JUMP; ++i)\n                for(std::size_t b = 0; b < std::size_t(64); ++b) {\n                    if (JUMP[i] & std::uint64_t(1) << b) {\n                        s0 ^= _s[0];\n                        s1 ^= _s[1];\n                        s2 ^= _s[2];\n                        s3 ^= _s[3];\n                    }\n                    next();\n                }\n\n            _s[0] = s0;\n            _s[1] = s1;\n            _s[2] = s2;\n            _s[3] = s3;\n        }\n    }\n\n    /**\n     * This is the long-jump function for @c xoshiro256plus. It is\n     * equivalent to 2^192 calls to next(); it can be used to generate\n     * 2^64 starting points, from each of which jump() will generate\n     * 2^64 non-overlapping subsequences for parallel distributed\n     * computations.\n     */\n    void long_jump()\n    {\n        static const std::uint64_t LONG_JUMP[] = { 0x76E15D3EFEFDCBBF, 0xC5004E441C522FB3, 0x77710069854EE241, 0x39109BB02ACBE635 };\n\n        std::uint64_t s0 = 0, s1 = 0, s2 = 0, s3 = 0;\n        for(std::size_t i = 0; i < sizeof LONG_JUMP / sizeof *LONG_JUMP; ++i)\n            for(std::size_t b = 0; b < std::size_t(64); ++b) {\n                if (LONG_JUMP[i] & std::uint64_t(1) << b) {\n                    s0 ^= _s[0];\n                    s1 ^= _s[1];\n                    s2 ^= _s[2];\n                    s3 ^= _s[3];\n                }\n                next();\n            }\n\n        _s[0] = s0;\n        _s[1] = s1;\n        _s[2] = s2;\n        _s[3] = s3;\n    }\n\n    friend bool operator==(const xoshiro256plus& x,\n                           const xoshiro256plus& y)\n    { return x._s[0] == y._s[0] && x._s[1] == y._s[1] && x._s [2] == y._s [2] && x._s [3] == y._s [3]; }\n\n    friend bool operator!=(const xoshiro256plus& x,\n                           const xoshiro256plus& y)\n    { return !(x == y); }\n\n    /** Writes a @c xoshiro256plus to a @c std::ostream. */\n    template<class CharT, class Traits>\n    friend std::basic_ostream<CharT,Traits>&\n    operator<<(std::basic_ostream<CharT,Traits>& os,\n               const xoshiro256plus& xoro)\n    {\n        os << xoro._s[0] << ' ' << xoro._s[1] << ' ' << xoro._s[2] << ' ' << xoro._s[3];\n        return os;\n    }\n\n    /** Reads a @c xoshiro256plus from a @c std::istream. */\n    template<class CharT, class Traits>\n    friend std::basic_istream<CharT,Traits>&\n    operator>>(std::basic_istream<CharT,Traits>& is,\n               xoshiro256plus& xoro)\n    {\n        is >> xoro._s[0] >> std::ws >> xoro._s[1] >> std::ws >> xoro._s[2] >> std::ws >> xoro._s[3];\n        return is;\n    }\n\nprivate:\n\n    /// \\cond show_private\n\n    // Rotate left, use of intrinsic shows no speed-up. */\n    static std::uint64_t rotl(const std::uint64_t x, const int k)\n    { return (x << k) | (x >> (64 - k)); }\n\n    /** Advance the state by 1 step. */\n    void next()\n    {\n        const uint64_t t = _s[1] << 17;\n\n        _s[2] ^= _s[0];\n        _s[3] ^= _s[1];\n        _s[1] ^= _s[2];\n        _s[0] ^= _s[3];\n\n        _s[2] ^= t;\n\n        _s[3] = rotl(_s[3], 45);\n    }\n\n    // As per http://www0.cs.ucl.ac.uk/staff/D.Jones/GoodPracticeRNG.pdf\n    void warmup()\n    {\n        discard(8);\n    }\n\n    /// \\endcond\n\n    std::uint64_t _s[4];\n};\n\n\nclass xoroshiro128plusshixo\n{\npublic:\n    typedef std::uint64_t result_type;\n\n    // Required for old Boost.Random concept.\n    static const bool has_fixed_range = true;\n    static const std::uint64_t default_seed = 1;\n\n    /**\n    * Constructs a @c xoroshiro128plusshixo, using the default seed.\n    */\n    xoroshiro128plusshixo ( )\n    {\n        seed ( );\n    }\n\n    /**\n    * Constructs a @c xoroshiro128plusshixo, seeding it with @c value.\n    */\n    BOOST_RANDOM_DETAIL_ARITHMETIC_CONSTRUCTOR ( xoroshiro128plusshixo,\n        std::uint64_t, value )\n    {\n        seed ( value );\n    }\n\n    /**\n    * Constructs a @c xoroshiro128plusshixo, seeding it with values\n    * produced by a call to @c seq.generate().\n    */\n    BOOST_RANDOM_DETAIL_SEED_SEQ_CONSTRUCTOR ( xoroshiro128plusshixo,\n        SeedSeq, seq )\n    {\n        seed ( seq );\n    }\n\n    /**\n    * Constructs a @c xoroshiro128plusshixo and seeds it with values\n    * taken from the iterator range [first, last) and adjusts\n    * first to point to the element after the last one used.\n    * If there are not enough elements, throws @c std::invalid_argument.\n    *\n    * first and last must be input iterators.\n    */\n    template<class It>\n    xoroshiro128plusshixo ( It& first, It last )\n    {\n        seed ( first, last );\n    }\n\n    // compiler-generated copy constructor and assignment operator are fine.\n\n    /**\n    * Calls seed(default_seed)\n    */\n    void seed ( )\n    {\n        seed ( default_seed );\n    }\n\n    /**\n    * seeds a @c xoroshiro128plusshixo with splitmix64, as per Sebastiano\n    * Vigna's recommendation.\n    */\n    BOOST_RANDOM_DETAIL_ARITHMETIC_SEED ( xoroshiro128plusshixo, std::uint64_t, value )\n    {\n        std::uint64_t s = value + std::uint64_t { 0x9E3779B97F4A7C15 };\n        _s [ 0 ] = detail::xoroshiro_integer_hash ( s );\n        _s [ 1 ] = detail::xoroshiro_integer_hash ( ( s += std::uint64_t { 0x9E3779B97F4A7C15 } ) );\n    }\n\n    /**\n    * Seeds a @c xoroshiro128plusshixo using values from a SeedSeq. If a\n    * valid seed cannot be generated throws @c std::runtime_error.\n    */\n    BOOST_RANDOM_DETAIL_SEED_SEQ_SEED ( xoroshiro128plusshixo, SeedSeq, seq )\n    {\n        detail::seed_array_non_zero_int ( seq, _s );\n        warmup ( );\n    }\n\n    /**\n    * Seeds a @c xoroshiro128plusshixo with values taken from the\n    * iterator range [first, last) and adjusts @c first to\n    * point to the element after the last one used. If there are\n    * not enough elements or all the whole input range is zero,\n    * throws @c std::invalid_argument.\n    *\n    * @c first and @c last must be input iterators.\n    */\n    template<class It>\n    void seed ( It& first, It last )\n    {\n        detail::fill_array_non_zero_int ( first, last, _s );\n        warmup ( );\n    }\n\n    /**\n    * Returns the smallest value that the @c xoroshiro128plusshixo\n    * can produce.\n    */\n    static result_type min BOOST_PREVENT_MACRO_SUBSTITUTION ( )\n    {\n        return 0;\n    }\n\n    /**\n    * Returns the largest value that the @c xoroshiro128plusshixo\n    * can produce.\n    */\n    static result_type max BOOST_PREVENT_MACRO_SUBSTITUTION ( )\n    {\n        return UINT64_MAX;\n    }\n\n    /** Returns the next value of the @c xoroshiro128plusshixo. */\n    std::uint64_t operator()( )\n    {\n        std::uint64_t r = _s[0] + _s [1];\n        next ( );\n        return ( r >> 32 ) ^ r;\n    }\n\n    /** Fills a range with random values. */\n    template<class Iter>\n    void generate ( Iter first, Iter last ) {\n\n        detail::generate_from_int ( *this, first, last );\n\n        /*\n\n        while ( first != last ) {\n\n            std::uint64_t tmp = _s [ 0 ] + _s [ 1 ];\n            tmp ^= tmp >> 32;\n\n            next ( );\n\n            *first = tmp;\n            ++first;\n        }\n\n        */\n    }\n\n    /** Advances the state of the generator by @c z. */\n    void discard ( std::uintmax_t z )\n    {\n        while ( z-- ) {\n            next ( );\n        }\n    }\n\n    /**\n    * This is a jump function for the generator. It is equivalent\n    * to calling @c discard(2^64) @c z times; it can be used to\n    * generate 2^64 non-overlapping subsequences for parallel\n    * computations.\n    */\n    void jump ( std::uintmax_t z = 1 )\n    {\n        while ( z-- ) {\n            std::uint64_t s0 = 0, s1 = 0;\n            for ( std::size_t b = 0; b < 64; ++b ) {\n                if ( std::uint64_t { 0xBEAC0467EBA5FACB } &std::uint64_t { 1 } << b ) {\n                    s0 ^= _s [ 0 ], s1 ^= _s [ 1 ];\n                }\n                next ( );\n            }\n            for ( std::size_t b = 0; b < 64; ++b ) {\n                if ( std::uint64_t { 0xD86B048B86AA9922 } &std::uint64_t { 1 } << b ) {\n                    s0 ^= _s [ 0 ], s1 ^= _s [ 1 ];\n                }\n                next ( );\n            }\n            _s [ 0 ] = s0, _s [ 1 ] = s1;\n        }\n    }\n\n    friend bool operator==( const xoroshiro128plusshixo& x,\n        const xoroshiro128plusshixo& y )\n    {\n        return x._s [ 0 ] == y._s [ 0 ] && x._s [ 1 ] == y._s [ 1 ];\n    }\n\n    friend bool operator!=( const xoroshiro128plusshixo& x,\n        const xoroshiro128plusshixo& y )\n    {\n        return !( x == y );\n    }\n\n    /** Writes a @c xoroshiro128plusshixo to a @c std::ostream. */\n    template<class CharT, class Traits>\n    friend std::basic_ostream<CharT, Traits>&\n        operator<<( std::basic_ostream<CharT, Traits>& os,\n            const xoroshiro128plusshixo& xoro )\n    {\n        os << xoro._s [ 0 ] << ' ' << xoro._s [ 1 ];\n        return os;\n    }\n\n    /** Reads a @c xoroshiro128plusshixo from a @c std::istream. */\n    template<class CharT, class Traits>\n    friend std::basic_istream<CharT, Traits>&\n        operator>>( std::basic_istream<CharT, Traits>& is,\n            xoroshiro128plusshixo& xoro )\n    {\n        is >> xoro._s [ 0 ] >> std::ws >> xoro._s [ 1 ];\n        return is;\n    }\n\nprivate:\n\n    /// \\cond show_private\n\n    // Rotate left, use of intrinsic shows no speed-up. */\n    static std::uint64_t rotl ( const std::uint64_t x, const int k )\n    {\n        return ( x << k ) | ( x >> ( 64 - k ) );\n    }\n\n    /** Advance the state by 1 step. */\n    void next ( )\n    {\n        _s [ 1 ] ^= _s [ 0 ];\n        _s [ 0 ] = rotl ( _s [ 0 ], 55 );\n        _s [ 0 ] ^= _s [ 1 ];\n        _s [ 0 ] ^= _s [ 1 ] << 14;\n        _s [ 1 ] = rotl ( _s [ 1 ], 36 );\n    }\n\n    // As per http://www0.cs.ucl.ac.uk/staff/D.Jones/GoodPracticeRNG.pdf\n    void warmup ( )\n    {\n        discard ( 8 );\n    }\n\n    /// \\endcond\n\n    std::uint64_t _s [ 2 ];\n};\n\nclass xoroshiro128plusshixostar\n{\npublic:\n    typedef std::uint64_t result_type;\n\n    // Required for old Boost.Random concept.\n    static const bool has_fixed_range = true;\n    static const std::uint64_t default_seed = 1;\n\n    /**\n    * Constructs a @c xoroshiro128plusshixostar, using the default seed.\n    */\n    xoroshiro128plusshixostar ( )\n    {\n        seed ( );\n    }\n\n    /**\n    * Constructs a @c xoroshiro128plusshixostar, seeding it with @c value.\n    */\n    BOOST_RANDOM_DETAIL_ARITHMETIC_CONSTRUCTOR ( xoroshiro128plusshixostar,\n        std::uint64_t, value )\n    {\n        seed ( value );\n    }\n\n    /**\n    * Constructs a @c xoroshiro128plusshixostar, seeding it with values\n    * produced by a call to @c seq.generate().\n    */\n    BOOST_RANDOM_DETAIL_SEED_SEQ_CONSTRUCTOR ( xoroshiro128plusshixostar,\n        SeedSeq, seq )\n    {\n        seed ( seq );\n    }\n\n    /**\n    * Constructs a @c xoroshiro128plusshixostar and seeds it with values\n    * taken from the iterator range [first, last) and adjusts\n    * first to point to the element after the last one used.\n    * If there are not enough elements, throws @c std::invalid_argument.\n    *\n    * first and last must be input iterators.\n    */\n    template<class It>\n    xoroshiro128plusshixostar ( It& first, It last )\n    {\n        seed ( first, last );\n    }\n\n    // compiler-generated copy constructor and assignment operator are fine.\n\n    /**\n    * Calls seed(default_seed)\n    */\n    void seed ( )\n    {\n        seed ( default_seed );\n    }\n\n    /**\n    * seeds a @c xoroshiro128plusshixostar with splitmix64, as per Sebastiano\n    * Vigna's recommendation.\n    */\n    BOOST_RANDOM_DETAIL_ARITHMETIC_SEED ( xoroshiro128plusshixostar, std::uint64_t, value )\n    {\n        std::uint64_t s = value + std::uint64_t { 0x9E3779B97F4A7C15 };\n        _s [ 0 ] = detail::xoroshiro_integer_hash ( s );\n        _s [ 1 ] = detail::xoroshiro_integer_hash ( ( s += std::uint64_t { 0x9E3779B97F4A7C15 } ) );\n    }\n\n    /**\n    * Seeds a @c xoroshiro128plusshixostar using values from a SeedSeq. If a\n    * valid seed cannot be generated throws @c std::runtime_error.\n    */\n    BOOST_RANDOM_DETAIL_SEED_SEQ_SEED ( xoroshiro128plusshixostar, SeedSeq, seq )\n    {\n        detail::seed_array_non_zero_int ( seq, _s );\n        warmup ( );\n    }\n\n    /**\n    * Seeds a @c xoroshiro128plusshixostar with values taken from the\n    * iterator range [first, last) and adjusts @c first to\n    * point to the element after the last one used. If there are\n    * not enough elements or all the whole input range is zero,\n    * throws @c std::invalid_argument.\n    *\n    * @c first and @c last must be input iterators.\n    */\n    template<class It>\n    void seed ( It& first, It last )\n    {\n        detail::fill_array_non_zero_int ( first, last, _s );\n        warmup ( );\n    }\n\n    /**\n    * Returns the smallest value that the @c xoroshiro128plusshixostar\n    * can produce.\n    */\n    static result_type min BOOST_PREVENT_MACRO_SUBSTITUTION ( )\n    {\n        return 0;\n    }\n\n    /**\n    * Returns the largest value that the @c xoroshiro128plusshixostar\n    * can produce.\n    */\n    static result_type max BOOST_PREVENT_MACRO_SUBSTITUTION ( )\n    {\n        return UINT64_MAX;\n    }\n\n    /** Returns the next value of the @c xoroshiro128plusshixostar. */\n    std::uint64_t operator()( )\n    {\n        std::uint64_t r = _s [ 0 ] + _s [ 1 ];\n        next ( );\n        return ((r >> 32) ^ r) * std::uint64_t { 0x1AEC805299990163 };\n    }\n\n    /** Fills a range with random values. */\n    template<class Iter>\n    void generate ( Iter first, Iter last )\n    {\n        detail::generate_from_int ( *this, first, last );\n    }\n\n    /** Advances the state of the generator by @c z. */\n    void discard ( std::uintmax_t z )\n    {\n        while ( z-- ) {\n            next ( );\n        }\n    }\n\n    /**\n    * This is a jump function for the generator. It is equivalent\n    * to calling @c discard(2^64) @c z times; it can be used to\n    * generate 2^64 non-overlapping subsequences for parallel\n    * computations.\n    */\n    void jump ( std::uintmax_t z = 1 )\n    {\n        while ( z-- ) {\n            std::uint64_t s0 = 0, s1 = 0;\n            for ( std::size_t b = 0; b < 64; ++b ) {\n                if ( std::uint64_t { 0xBEAC0467EBA5FACB } &std::uint64_t { 1 } << b ) {\n                    s0 ^= _s [ 0 ], s1 ^= _s [ 1 ];\n                }\n                next ( );\n            }\n            for ( std::size_t b = 0; b < 64; ++b ) {\n                if ( std::uint64_t { 0xD86B048B86AA9922 } &std::uint64_t { 1 } << b ) {\n                    s0 ^= _s [ 0 ], s1 ^= _s [ 1 ];\n                }\n                next ( );\n            }\n            _s [ 0 ] = s0, _s [ 1 ] = s1;\n        }\n    }\n\n    friend bool operator==( const xoroshiro128plusshixostar& x,\n        const xoroshiro128plusshixostar& y )\n    {\n        return x._s [ 0 ] == y._s [ 0 ] && x._s [ 1 ] == y._s [ 1 ];\n    }\n\n    friend bool operator!=( const xoroshiro128plusshixostar& x,\n        const xoroshiro128plusshixostar& y )\n    {\n        return !( x == y );\n    }\n\n    /** Writes a @c xoroshiro128plusshixostar to a @c std::ostream. */\n    template<class CharT, class Traits>\n    friend std::basic_ostream<CharT, Traits>&\n        operator<<( std::basic_ostream<CharT, Traits>& os,\n            const xoroshiro128plusshixostar& xoro )\n    {\n        os << xoro._s [ 0 ] << ' ' << xoro._s [ 1 ];\n        return os;\n    }\n\n    /** Reads a @c xoroshiro128plusshixostar from a @c std::istream. */\n    template<class CharT, class Traits>\n    friend std::basic_istream<CharT, Traits>&\n        operator>>( std::basic_istream<CharT, Traits>& is,\n            xoroshiro128plusshixostar& xoro )\n    {\n        is >> xoro._s [ 0 ] >> std::ws >> xoro._s [ 1 ];\n        return is;\n    }\n\nprivate:\n\n    /// \\cond show_private\n\n    // Rotate left, use of intrinsic shows no speed-up. */\n    static std::uint64_t rotl ( const std::uint64_t x, const int k )\n    {\n        return ( x << k ) | ( x >> ( 64 - k ) );\n    }\n\n    /** Advance the state by 1 step. */\n    void next ( )\n    {\n        _s [ 1 ] ^= _s [ 0 ];\n        _s [ 0 ] = rotl ( _s [ 0 ], 55 );\n        _s [ 0 ] ^= _s [ 1 ];\n        _s [ 0 ] ^= _s [ 1 ] << 14;\n        _s [ 1 ] = rotl ( _s [ 1 ], 36 );\n    }\n\n    // As per http://www0.cs.ucl.ac.uk/staff/D.Jones/GoodPracticeRNG.pdf\n    void warmup ( )\n    {\n        discard ( 8 );\n    }\n\n    /// \\endcond\n\n    std::uint64_t _s [2];\n};\n\n\nclass xoroshiro128plusshixostarshixo\n{\npublic:\n    typedef std::uint64_t result_type;\n\n    // Required for old Boost.Random concept.\n    static const bool has_fixed_range = true;\n    static const std::uint64_t default_seed = 1;\n\n    /**\n    * Constructs a @c xoroshiro128plusshixostarshixo, using the default seed.\n    */\n    xoroshiro128plusshixostarshixo ( )\n    {\n        seed ( );\n    }\n\n    /**\n    * Constructs a @c xoroshiro128plusshixostarshixo, seeding it with @c value.\n    */\n    BOOST_RANDOM_DETAIL_ARITHMETIC_CONSTRUCTOR ( xoroshiro128plusshixostarshixo,\n        std::uint64_t, value )\n    {\n        seed ( value );\n    }\n\n    /**\n    * Constructs a @c xoroshiro128plusshixostarshixo, seeding it with values\n    * produced by a call to @c seq.generate().\n    */\n    BOOST_RANDOM_DETAIL_SEED_SEQ_CONSTRUCTOR ( xoroshiro128plusshixostarshixo,\n        SeedSeq, seq )\n    {\n        seed ( seq );\n    }\n\n    /**\n    * Constructs a @c xoroshiro128plusshixostarshixo and seeds it with values\n    * taken from the iterator range [first, last) and adjusts\n    * first to point to the element after the last one used.\n    * If there are not enough elements, throws @c std::invalid_argument.\n    *\n    * first and last must be input iterators.\n    */\n    template<class It>\n    xoroshiro128plusshixostarshixo ( It& first, It last )\n    {\n        seed ( first, last );\n    }\n\n    // compiler-generated copy constructor and assignment operator are fine.\n\n    /**\n    * Calls seed(default_seed)\n    */\n    void seed ( )\n    {\n        seed ( default_seed );\n    }\n\n    /**\n    * seeds a @c xoroshiro128plusshixostarshixo with splitmix64, as per Sebastiano\n    * Vigna's recommendation.\n    */\n    BOOST_RANDOM_DETAIL_ARITHMETIC_SEED ( xoroshiro128plusshixostarshixo, std::uint64_t, value )\n    {\n        std::uint64_t s = value + std::uint64_t { 0x9E3779B97F4A7C15 };\n        _s [ 0 ] = detail::xoroshiro_integer_hash ( s );\n        _s [ 1 ] = detail::xoroshiro_integer_hash ( ( s += std::uint64_t { 0x9E3779B97F4A7C15 } ) );\n    }\n\n    /**\n    * Seeds a @c xoroshiro128plusshixostarshixo using values from a SeedSeq. If a\n    * valid seed cannot be generated throws @c std::runtime_error.\n    */\n    BOOST_RANDOM_DETAIL_SEED_SEQ_SEED ( xoroshiro128plusshixostarshixo, SeedSeq, seq )\n    {\n        detail::seed_array_non_zero_int ( seq, _s );\n        warmup ( );\n    }\n\n    /**\n    * Seeds a @c xoroshiro128plusshixostarshixo with values taken from the\n    * iterator range [first, last) and adjusts @c first to\n    * point to the element after the last one used. If there are\n    * not enough elements or all the whole input range is zero,\n    * throws @c std::invalid_argument.\n    *\n    * @c first and @c last must be input iterators.\n    */\n    template<class It>\n    void seed ( It& first, It last )\n    {\n        detail::fill_array_non_zero_int ( first, last, _s );\n        warmup ( );\n    }\n\n    /**\n    * Returns the smallest value that the @c xoroshiro128plusshixostarshixo\n    * can produce.\n    */\n    static result_type min BOOST_PREVENT_MACRO_SUBSTITUTION ( )\n    {\n        return 0;\n    }\n\n    /**\n    * Returns the largest value that the @c xoroshiro128plusshixostarshixo\n    * can produce.\n    */\n    static result_type max BOOST_PREVENT_MACRO_SUBSTITUTION ( )\n    {\n        return UINT64_MAX;\n    }\n\n    /** Returns the next value of the @c xoroshiro128plusshixostarshixo. */\n    std::uint64_t operator()( )\n    {\n        std::uint64_t r = _s [ 0 ] + _s [ 1 ];\n        next ( );\n        r = ( ( r >> 32 ) ^ r ) * std::uint64_t { 0x1AEC805299990163 };\n        return ( r >> 32 ) ^ r;\n    }\n\n    /** Fills a range with random values. */\n    template<class Iter>\n    void generate ( Iter first, Iter last )\n    {\n        detail::generate_from_int ( *this, first, last );\n    }\n\n    /** Advances the state of the generator by @c z. */\n    void discard ( std::uintmax_t z )\n    {\n        while ( z-- ) {\n            next ( );\n        }\n    }\n\n    /**\n    * This is a jump function for the generator. It is equivalent\n    * to calling @c discard(2^64) @c z times; it can be used to\n    * generate 2^64 non-overlapping subsequences for parallel\n    * computations.\n    */\n    void jump ( std::uintmax_t z = 1 )\n    {\n        while ( z-- ) {\n            std::uint64_t s0 = 0, s1 = 0;\n            for ( std::size_t b = 0; b < 64; ++b ) {\n                if ( std::uint64_t { 0xBEAC0467EBA5FACB } &std::uint64_t { 1 } << b ) {\n                    s0 ^= _s [ 0 ], s1 ^= _s [ 1 ];\n                }\n                next ( );\n            }\n            for ( std::size_t b = 0; b < 64; ++b ) {\n                if ( std::uint64_t { 0xD86B048B86AA9922 } &std::uint64_t { 1 } << b ) {\n                    s0 ^= _s [ 0 ], s1 ^= _s [ 1 ];\n                }\n                next ( );\n            }\n            _s [ 0 ] = s0, _s [ 1 ] = s1;\n        }\n    }\n\n    friend bool operator==( const xoroshiro128plusshixostarshixo& x,\n        const xoroshiro128plusshixostarshixo& y )\n    {\n        return x._s [ 0 ] == y._s [ 0 ] && x._s [ 1 ] == y._s [ 1 ];\n    }\n\n    friend bool operator!=( const xoroshiro128plusshixostarshixo& x,\n        const xoroshiro128plusshixostarshixo& y )\n    {\n        return !( x == y );\n    }\n\n    /** Writes a @c xoroshiro128plusshixostarshixo to a @c std::ostream. */\n    template<class CharT, class Traits>\n    friend std::basic_ostream<CharT, Traits>&\n        operator<<( std::basic_ostream<CharT, Traits>& os,\n            const xoroshiro128plusshixostarshixo& xoro )\n    {\n        os << xoro._s [ 0 ] << ' ' << xoro._s [ 1 ];\n        return os;\n    }\n\n    /** Reads a @c xoroshiro128plusshixostarshixo from a @c std::istream. */\n    template<class CharT, class Traits>\n    friend std::basic_istream<CharT, Traits>&\n        operator>>( std::basic_istream<CharT, Traits>& is,\n            xoroshiro128plusshixostarshixo& xoro )\n    {\n        is >> xoro._s [ 0 ] >> std::ws >> xoro._s [ 1 ];\n        return is;\n    }\n\nprivate:\n\n    /// \\cond show_private\n\n    // Rotate left, use of intrinsic shows no speed-up. */\n    static std::uint64_t rotl ( const std::uint64_t x, const int k )\n    {\n        return ( x << k ) | ( x >> ( 64 - k ) );\n    }\n\n    /** Advance the state by 1 step. */\n    void next ( )\n    {\n        _s [ 1 ] ^= _s [ 0 ];\n        _s [ 0 ] = rotl ( _s [ 0 ], 55 );\n        _s [ 0 ] ^= _s [ 1 ];\n        _s [ 0 ] ^= _s [ 1 ] << 14;\n        _s [ 1 ] = rotl ( _s [ 1 ], 36 );\n    }\n\n    // As per http://www0.cs.ucl.ac.uk/staff/D.Jones/GoodPracticeRNG.pdf\n    void warmup ( )\n    {\n        discard ( 8 );\n    }\n\n    /// \\endcond\n\n    std::uint64_t _s [ 2 ];\n};\n\n/**\n * xorshift128+\n *\n * This generator has been replaced by xoroshiro128+, which is\n * significantly faster and has better statistical properties.\n *\n * Due to the relatively short period it is acceptable only for\n * applications with a mild amount of parallelism; otherwise, use a\n * xorshift1024* generator.\n *\n * The lowest bit of this generator is an LSFR, and thus it is\n * slightly less random than the other bits. Use a sign test to\n * extract a random Boolean value.\n *\n * The state must be seeded so that it is not everywhere zero.\n *\n * Web-site: http://xoroshiro.di.unimi.it/\n */\nclass xorshift128plus\n{\npublic:\n    typedef std::uint64_t result_type;\n\n    // Required for old Boost.Random concept.\n    static const bool has_fixed_range = true;\n    static const std::uint64_t default_seed = 1;\n\n    /**\n     * Constructs a @c xorshift128plus, using the default seed.\n     */\n    xorshift128plus()\n    { seed(); }\n\n    /**\n     * Constructs a @c xorshift128plus, seeding it with @c value.\n     */\n    BOOST_RANDOM_DETAIL_ARITHMETIC_CONSTRUCTOR(xorshift128plus,\n                                               std::uint64_t, value)\n    { seed(value); }\n\n    /**\n     * Constructs a @c xorshift128plus, seeding it with values\n     * produced by a call to @c seq.generate().\n     */\n    BOOST_RANDOM_DETAIL_SEED_SEQ_CONSTRUCTOR(xorshift128plus,\n                                             SeedSeq, seq)\n    { seed(seq); }\n\n    /**\n     * Constructs a @c xorshift128plus and seeds it with values\n     * taken from the iterator range [first, last) and adjusts\n     * first to point to the element after the last one used.\n     * If there are not enough elements, throws @c std::invalid_argument.\n     *\n     * first and last must be input iterators.\n     */\n    template<class It>\n    xorshift128plus(It& first, It last)\n    { seed(first, last); }\n\n    // compiler-generated copy constructor and assignment operator are fine.\n\n    /**\n     * Calls seed(default_seed)\n     */\n    void seed()\n    { seed(default_seed); }\n\n    /**\n     * seeds a @c xorshift128plus with splitmix64, as per Sebastiano\n     * Vigna's recommendation.\n     */\n    BOOST_RANDOM_DETAIL_ARITHMETIC_SEED(xorshift128plus, std::uint64_t, value)\n    {\n        std::uint64_t s = value + std::uint64_t { 0x9E3779B97F4A7C15 };\n        _s[0] = detail::xoroshiro_integer_hash(s);\n        _s[1] = detail::xoroshiro_integer_hash((s += std::uint64_t { 0x9E3779B97F4A7C15 }));\n    }\n\n    /**\n     * Seeds a @c xorshift128plus using values from a SeedSeq. If a\n     * valid seed cannot be generated throws @c std::runtime_error.\n     */\n    BOOST_RANDOM_DETAIL_SEED_SEQ_SEED(xorshift128plus, SeedSeq, seq)\n    {\n        detail::seed_array_non_zero_int(seq, _s);\n        warmup();\n    }\n\n    /**\n     * Seeds a @c xorshift128plus with values taken from the\n     * iterator range [first, last) and adjusts @c first to\n     * point to the element after the last one used. If there are\n     * not enough elements or all the whole input range is zero,\n     * throws @c std::invalid_argument.\n     *\n     * @c first and @c last must be input iterators.\n     */\n    template<class It>\n    void seed(It& first, It last)\n    {\n        detail::fill_array_non_zero_int(first, last, _s);\n        warmup();\n    }\n\n    /**\n     * Returns the smallest value that the @c xorshift128plus\n     * can produce.\n     */\n    static result_type min BOOST_PREVENT_MACRO_SUBSTITUTION ()\n    { return 0; }\n\n    /**\n     * Returns the largest value that the @c xorshift128plus\n     * can produce.\n     */\n    static result_type max BOOST_PREVENT_MACRO_SUBSTITUTION ()\n    { return UINT64_MAX; }\n\n    /** Returns the next value of the @c xorshift128plus. */\n    std::uint64_t operator()()\n    {\n        const std::uint64_t r = _s[0] + _s[1];\n        next();\n        return r;\n    }\n\n    /** Fills a range with random values. */\n    template<class Iter>\n    void generate(Iter first, Iter last)\n    { detail::generate_from_int(*this, first, last); }\n\n    /** Advances the state of the generator by @c z. */\n    void discard(std::uintmax_t z)\n    {\n        while (z--) {\n            next();\n        }\n    }\n\n    /**\n     * This is a jump function for the generator. It is equivalent\n     * to calling @c discard(2^64) @c z times; it can be used to\n     * generate 2^64 non-overlapping subsequences for parallel\n     * computations.\n     */\n    void jump(std::uintmax_t z = 1)\n    {\n        static const std::uint64_t jmp [2] {\n            0x8a5cd789635d2dff, 0x121fd2155c472f96\n        };\n\n        while(z--) {\n            std::uint64_t s0 = 0, s1 = 0;\n            for (std::size_t i = 0; i < 2; ++i) {\n                for (std::size_t b = 0; b < 64; ++b) {\n                    if (jmp[i] & std::uint64_t { 1 } << b) {\n                        s0 ^= _s[0], s1 ^= _s[1];\n                    }\n                    next();\n                }\n            }\n            _s[0] = s0, _s[1] = s1;\n        }\n    }\n\n    friend bool operator==(const xorshift128plus& x,\n                           const xorshift128plus& y)\n    { return x._s[0] == y._s[0] && x._s[1] == y._s[1]; }\n\n    friend bool operator!=(const xorshift128plus& x,\n                           const xorshift128plus& y)\n    { return !(x == y); }\n\n    /** Writes a @c xorshift128plus to a @c std::ostream. */\n    template<class CharT, class Traits>\n    friend std::basic_ostream<CharT,Traits>&\n    operator<<(std::basic_ostream<CharT,Traits>& os,\n               const xorshift128plus& xosh)\n    {\n        os << xosh._s[0] << ' ' << xosh._s[1];\n        return os;\n    }\n\n    /** Reads a @c xorshift128plus from a @c std::istream. */\n    template<class CharT, class Traits>\n    friend std::basic_istream<CharT,Traits>&\n    operator>>(std::basic_istream<CharT,Traits>& is,\n               xorshift128plus& xosh)\n    {\n        is >> xosh._s[0] >> std::ws >> xosh._s[1];\n        return is;\n    }\n\nprivate:\n\n    /// \\cond show_private\n\n    /** Advance the state by 1 step. */\n    void next()\n    {\n        std::uint64_t s1 = _s[0];\n        _s[0] = _s[1];\n        s1 ^= s1 << 23;\n        _s[1] = s1 ^ _s[0] ^ (s1 >> 18) ^ (_s[0] >> 5);\n    }\n\n    // As per http://www0.cs.ucl.ac.uk/staff/D.Jones/GoodPracticeRNG.pdf\n    void warmup()\n    {\n        discard(8);\n    }\n\n    /// \\endcond\n\n    std::uint64_t _s[2];\n};\n\n\n/**\n * xorshift1024*.\n *\n * This is a fast, top-quality generator. If 1024 bits of state are too\n * much, a xoroshiro128+ generator can be used.\n *\n * The three lowest bits of this generator are LSFRs, and thus they are\n * slightly less random than the other bits. Use a sign test to extract\n * a random Boolean value.\n *\n * The state must be seeded so that it is not everywhere zero.\n *\n * Web-site: http://xoroshiro.di.unimi.it/\n *\n * There was an issue with an earlier version of this code, the corrected\n * version is implemented below.\n *\n * https://stackoverflow.com/questions/34574701/xorshift1024-jump-not-commutative\n */\nclass xorshift1024star\n{\npublic:\n    typedef std::uint64_t result_type;\n\n    // Required for old Boost.Random concept.\n    static const bool has_fixed_range = true;\n    static const std::uint64_t default_seed = 1;\n\n    /**\n     * Constructs a @c xorshift1024star, using the default seed.\n     */\n    xorshift1024star()\n    { seed(); }\n\n    /**\n     * Constructs a @c xorshift1024star, seeding it with @c value.\n     */\n    BOOST_RANDOM_DETAIL_ARITHMETIC_CONSTRUCTOR(xorshift1024star,\n                                               std::uint64_t, value)\n    { seed(value); }\n\n    /**\n     * Constructs a @c xorshift1024star, seeding it with values\n     * produced by a call to @c seq.generate().\n     */\n    BOOST_RANDOM_DETAIL_SEED_SEQ_CONSTRUCTOR(xorshift1024star,\n                                             SeedSeq, seq)\n    { seed(seq); }\n\n    /**\n     * Constructs a @c xorshift1024star and seeds it with values\n     * taken from the iterator range [first, last) and adjusts\n     * first to point to the element after the last one used.\n     * If there are not enough elements, throws @c std::invalid_argument.\n     *\n     * first and last must be input iterators.\n     */\n    template<class It>\n    xorshift1024star(It& first, It last)\n    { seed(first, last); }\n\n    // compiler-generated copy constructor and assignment operator are fine.\n\n    /**\n     * Calls seed(default_seed)\n     */\n    void seed()\n    { seed(default_seed); }\n\n    /**\n     * seeds a @c xorshift1024star with splitmix64, as per Sebastiano\n     * Vigna's recommendation.\n     */\n    BOOST_RANDOM_DETAIL_ARITHMETIC_SEED(xorshift1024star, std::uint64_t, value)\n    {\n        std::uint64_t s = value + std::uint64_t { 0x9E3779B97F4A7C15 };\n        _s[0] = detail::xoroshiro_integer_hash(s);\n        for (std::size_t i = 1; i < 16; ++i) {\n            _s[i] = detail::xoroshiro_integer_hash ((s += std::uint64_t { 0x9E3779B97F4A7C15 }));\n        }\n        _p = 0;\n    }\n\n    /**\n     * Seeds a @c xorshift1024star using values from a SeedSeq. If a\n     * valid seed cannot be generated throws @c std::runtime_error.\n     */\n    BOOST_RANDOM_DETAIL_SEED_SEQ_SEED(xorshift1024star, SeedSeq, seq)\n    {\n        detail::seed_array_non_zero_int(seq, _s);\n        _p = 0;\n        warmup();\n    }\n\n    /**\n     * Seeds a @c xorshift1024star with values taken from the\n     * iterator range [first, last) and adjusts @c first to\n     * point to the element after the last one used. If there are\n     * not enough elements or all the whole input range is zero,\n     * throws @c std::invalid_argument.\n     *\n     * @c first and @c last must be input iterators.\n     */\n    template<class It>\n    void seed(It& first, It last)\n    {\n        detail::fill_array_non_zero_int(first, last, _s);\n        _p = 0;\n        warmup();\n    }\n\n    /**\n     * Returns the smallest value that the @c xorshift1024star\n     * can produce.\n     */\n    static result_type min BOOST_PREVENT_MACRO_SUBSTITUTION ()\n    { return 0; }\n\n    /**\n     * Returns the largest value that the @c xorshift1024star\n     * can produce.\n     */\n    static result_type max BOOST_PREVENT_MACRO_SUBSTITUTION ()\n    { return UINT64_MAX; }\n\n    /** Returns the next value of the @c xorshift1024star. */\n    std::uint64_t operator()()\n    {\n        next();\n        return _s[_p] * std::uint64_t { 0x106689D45497FDB5 };\n    }\n\n    /** Fills a range with random values. */\n    template<class Iter>\n    void generate(Iter first, Iter last)\n    { detail::generate_from_int(*this, first, last); }\n\n    /** Advances the state of the generator by @c z. */\n    void discard(std::uintmax_t z)\n    {\n        while (z--) {\n            next();\n        }\n    }\n\n    /**\n     * This is a jump function for the generator. It is equivalent\n     * to calling @c discard(2^512) @c z times; it can be used to\n     * generate 2^512 non-overlapping subsequences for parallel\n     * computations.\n     */\n    void jump(std::uintmax_t z = 1)\n    {\n        static const std::uint64_t jmp[16] {\n            0x84242F96ECA9C41D, 0xA3C65B8776F96855,\n            0x5B34A39F070B5837, 0x4489AFFCE4F31A1E,\n            0x2FFEEB0A48316F40, 0xDC2D9891FE68C022,\n            0x3659132BB12FEA70, 0xAAC17D8EFA43CAB8,\n            0xC4CB815590989B13, 0x5EE975283D71C93B,\n            0x691548C86C1BD540, 0x7910C41D10A1E6A5,\n            0x0B5FC64563B3E2A8, 0x047F7684E9FC949D,\n            0xB99181F2D8F685CA, 0x284600E3F30E38C3\n        };\n\n        while(z--) {\n            std::uint64_t t[16];\n            for (std::size_t i = 0; i < 16; ++i) {\n                for (std::size_t b = 0; b < 64; ++b) {\n                    if (jmp[i] & std::uint64_t { 1 } << b) {\n                        for (std::size_t j = 0; j < 16; ++j) {\n                            t [j] ^= _s[(j + _p) & 15];\n                        }\n                    }\n                    next();\n                }\n            }\n            for (std::size_t j = 0; j < 16; ++j) {\n                _s [(j + _p) & 15] = t[j];\n            }\n        }\n    }\n\n    friend bool operator==(const xorshift1024star& x,\n        const xorshift1024star& y)\n    {\n        std::size_t i = x._p, j = y._p;\n        for (; i < 16; ++i, j = (j + 1) & 15) {\n            if (x._s[i] != y._s[j]) {\n                return false;\n            }\n        }\n        i = 0;\n        for ( ; i < x._p; ++i, j = (j + 1) & 15) {\n            if (x._s[i] != y._s[j]) {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    friend bool operator!=(const xorshift1024star& x,\n                           const xorshift1024star& y)\n    { return !(x == y); }\n\n    /** Writes a @c xorshift1024star to a @c std::ostream. */\n    template<class CharT, class Traits>\n    friend std::basic_ostream<CharT,Traits>&\n    operator<<(std::basic_ostream<CharT,Traits>& os,\n               const xorshift1024star& xosh)\n    {\n        std::size_t i = xosh._p;\n        for (; i < 16; ++i) {\n            os << xosh._s[i] << ' ';\n        }\n        i = 0;\n        for (; i < xosh._p; ++i) {\n            os << xosh._s[i] << ' ';\n        }\n        return os;\n    }\n\n    /** Reads a @c xorshift1024star from a @c std::istream. */\n    template<class CharT, class Traits>\n    friend std::basic_istream<CharT,Traits>&\n    operator>>(std::basic_istream<CharT,Traits>& is,\n               xorshift1024star& xosh)\n    {\n        for (std::size_t i = 0; i < 16; ++i) {\n            is >> xosh._s[i] >> std::ws;\n        }\n        xosh._p = 0;\n        return is;\n    }\n\nprivate:\n\n    /// \\cond show_private\n\n    /** Advance the state by 1 step. */\n    void next()\n    {\n        const std::uint64_t s0 = _s[_p];\n        std::uint64_t s1 = _s[(_p = (_p + 1) & 15)];\n        s1 ^= s1 << 31;\n        _s[_p] = s1 ^ s0 ^ (s1 >> 11) ^ (s0 >> 30);\n    }\n\n    // As per http://www0.cs.ucl.ac.uk/staff/D.Jones/GoodPracticeRNG.pdf\n    void warmup()\n    {\n        discard(64);\n    }\n\n    /// \\endcond\n\n    std::uint64_t _s[16];\n    std::size_t _p;\n};\n\n#endif /* !BOOST_NO_INT64_T && !BOOST_NO_INTEGRAL_INT64_T */\n\n} // namespace random\n} // namespace boost\n\n#include <boost/random/detail/enable_warnings.hpp>\n\n#endif // BOOST_RANDOM_XOROSHIRO_HPP\n", "meta": {"hexsha": "75f21ae94592cf08560d7279bc637076593a7835", "size": 67667, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "xoroshiro/xoroshiro.hpp", "max_stars_repo_name": "degski/xoroshiro", "max_stars_repo_head_hexsha": "1fd60de9597bf314d57d5fe7c9d7a7802b8b7583", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-10-31T02:35:26.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-31T02:35:26.000Z", "max_issues_repo_path": "xoroshiro/xoroshiro.hpp", "max_issues_repo_name": "degski/xoroshiro", "max_issues_repo_head_hexsha": "1fd60de9597bf314d57d5fe7c9d7a7802b8b7583", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "xoroshiro/xoroshiro.hpp", "max_forks_repo_name": "degski/xoroshiro", "max_forks_repo_head_hexsha": "1fd60de9597bf314d57d5fe7c9d7a7802b8b7583", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5747377622, "max_line_length": 133, "alphanum_fraction": 0.5621203836, "num_tokens": 19458, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4644411785855466}}
{"text": "#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE ConnectedComponentSeparatorTests\n#include <boost/test/unit_test.hpp>\n\n#include <vector>\n#include <set>\n\n#include \"graph/PBQPGraph.hpp\"\n#include \"graph/Vector.hpp\"\n#include \"graph/PBQPNode.hpp\"\n#include \"graph/PBQPEdge.hpp\"\n#include \"reduction/PBQPReduction.hpp\"\n#include \"reduction/ConnectedComponentSeparator.hpp\"\n#include \"graph/PBQPSolution.hpp\"\n\nnamespace pbqppapa {\n\nBOOST_AUTO_TEST_CASE(singleNodeTest) {\n\tPBQPGraph<signed int> graph = PBQPGraph<signed int>();\n\tsigned int vekData [] = {2 ,2};\n\tVector<signed int> vek = Vector<signed int>(2, vekData);\n\tgraph.addNode(vek);\n\tConnectedComponentSeparator<signed int> sep = ConnectedComponentSeparator<signed int>(&graph);\n\tstd::vector<PBQPGraph<signed int>*> components = sep.reduce();\n\tPBQPSolution<signed int> sol (0);\n\tsep.solve(sol);\n\tBOOST_CHECK_EQUAL(components.size(), 1);\n\tPBQPGraph<signed int>* retrievedGraph = components[0];\n\tBOOST_CHECK_EQUAL(0, retrievedGraph->getEdgeCount());\n\tBOOST_CHECK_EQUAL(1, retrievedGraph->getNodeCount());\n\tBOOST_CHECK_EQUAL((*(graph.getNodeBegin()))->getIndex(),\n\t\t\t(*(retrievedGraph->getNodeBegin()))->getIndex());\n\tif (retrievedGraph != &graph) {\n\t\t//not neccessary for our implementation, but just to make sure\n\t\tdelete retrievedGraph;\n\t}\n}\n\nBOOST_AUTO_TEST_CASE(emptyGraphTest) {\n\tPBQPGraph<signed int> graph = PBQPGraph<signed int>();\n\tConnectedComponentSeparator<signed int> sep (&graph);\n\tstd::vector<PBQPGraph<signed int>*> components = sep.reduce();\n\tPBQPSolution<signed int> sol (0);\n\tsep.solve(sol);\n\tBOOST_CHECK_EQUAL(components.size(), 1);\n\tPBQPGraph<signed int>* retrievedGraph = components[0];\n\tBOOST_CHECK_EQUAL(0, retrievedGraph->getEdgeCount());\n\tBOOST_CHECK_EQUAL(0, retrievedGraph->getNodeCount());\n}\n\nBOOST_AUTO_TEST_CASE(basicNodeTest) {\n\tPBQPGraph<signed int> graph = PBQPGraph<signed int>();\n\tint size = 50;\n\tfor (int i = 0; i < size; i++) {\n\t\tint arr [] = {2, 2};\n\t\tVector<signed int> vek = Vector<signed int>(2, arr);\n\t\tgraph.addNode(vek);\n\t}\n\tConnectedComponentSeparator<signed int> sep = ConnectedComponentSeparator<signed int>(&graph);\n\tstd::vector<PBQPGraph<signed int>*> components = sep.reduce();\n\tPBQPSolution<signed int> sol = PBQPSolution<int>(0);\n\tsep.solve(sol);\n\tBOOST_CHECK_EQUAL(components.size(), size);\n\tstd::set<signed int> nodeIndices = std::set<signed int>();\n\tfor (int i = 0; i < size; i++) {\n\t\tPBQPGraph<signed int>* retrievedGraph = components[i];\n\t\tBOOST_CHECK_EQUAL(0, retrievedGraph->getEdgeCount());\n\t\tBOOST_CHECK_EQUAL(1, retrievedGraph->getNodeCount());\n\t\tunsigned int index = (*(retrievedGraph->getNodeBegin()))->getIndex();\n\t\tBOOST_CHECK_EQUAL(0, nodeIndices.count(index));\n\t\tnodeIndices.insert(index);\n\t\tif (retrievedGraph != &graph) {\n\t\t\tdelete retrievedGraph;\n\t\t}\n\t}\n}\n\nBOOST_AUTO_TEST_CASE(advancedNodeTest) {\n\tPBQPGraph<signed int>* graph = new PBQPGraph<int>();\n\tint subgraphs = 10;\n\tint localSize = 10;\n\tint edgeCount = 0;\n\tfor (int i = 0; i < subgraphs; i++) {\n\t\tedgeCount = 0;\n\t\tstd::vector<PBQPNode<int>*> otherNodes = std::vector<PBQPNode<int>*>();\n\t\tfor (int k = 0; k < localSize; k++) {\n\t\t\tint arr [] = {2, 2};\n\t\t\tVector<signed int> vek = Vector<signed int>(2, arr);\n\t\t\tPBQPNode<signed int>* node = graph->addNode(vek);\n\t\t\totherNodes.push_back(node);\n\t\t\tfor (PBQPNode<signed int>* otherNode : otherNodes) {\n\t\t\t\tint arr2 [] = {3, 2, 5, 8};\n\t\t\t\tMatrix<signed int> mat = Matrix<int>(2, 2, arr2);\n\t\t\t\tgraph->addEdge(node, otherNode, mat);\n\t\t\t\tedgeCount++;\n\t\t\t}\n\t\t}\n\t}\n\tConnectedComponentSeparator<int> sep = ConnectedComponentSeparator<int>(graph);\n\tstd::vector<PBQPGraph<int>*> components = sep.reduce();\n\tPBQPSolution<int> sol = PBQPSolution<int>(0);\n\tsep.solve(sol);\n\tBOOST_CHECK_EQUAL(components.size(), subgraphs);\n\tstd::set<int> nodeIndices = std::set<int>();\n\tfor (int i = 0; i < subgraphs; i++) {\n\t\tPBQPGraph<int>* retrievedGraph = components[i];\n\t\tBOOST_CHECK_EQUAL(edgeCount - localSize, retrievedGraph->getEdgeCount());\n\t\tBOOST_CHECK_EQUAL(localSize, retrievedGraph->getNodeCount());\n\t\t//ensure each node is only in one subgraph\n\t\tfor (auto iter = retrievedGraph->getNodeBegin();\n\t\t\t\titer != retrievedGraph->getNodeEnd(); ++iter) {\n\t\t\tunsigned int index = (*iter)->getIndex();\n\t\t\tBOOST_CHECK_EQUAL(0, nodeIndices.count(index));\n\t\t\tnodeIndices.insert(index);\n\t\t}\n\t}\n\tfor (PBQPGraph<int>* subGraph : components) {\n\t\tdelete subGraph;\n\t}\n}\n\n}\n\n", "meta": {"hexsha": "e7b3d21780d6399dda535edde6366643b78f2a87", "size": 4364, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/reduction/ConnectedComponentSeparatorTests.cpp", "max_stars_repo_name": "sgraf812/pbqp-papa", "max_stars_repo_head_hexsha": "b5ae6fcb0842cb66956cccc4663f6fd9e6f6ae07", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-08-10T04:18:11.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-10T04:18:11.000Z", "max_issues_repo_path": "test/reduction/ConnectedComponentSeparatorTests.cpp", "max_issues_repo_name": "sgraf812/pbqp-papa", "max_issues_repo_head_hexsha": "b5ae6fcb0842cb66956cccc4663f6fd9e6f6ae07", "max_issues_repo_licenses": ["MIT"], "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/reduction/ConnectedComponentSeparatorTests.cpp", "max_forks_repo_name": "sgraf812/pbqp-papa", "max_forks_repo_head_hexsha": "b5ae6fcb0842cb66956cccc4663f6fd9e6f6ae07", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-03-07T10:20:50.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-07T10:20:50.000Z", "avg_line_length": 35.1935483871, "max_line_length": 95, "alphanum_fraction": 0.7153987168, "num_tokens": 1215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4644411785855466}}
{"text": "//            Copyright Daniel Trebbien 2010.\n// Distributed under the Boost Software License, Version 1.0.\n//   (See accompanying file LICENSE_1_0.txt or the copy at\n//         http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_GRAPH_STOER_WAGNER_MIN_CUT_HPP\n#define BOOST_GRAPH_STOER_WAGNER_MIN_CUT_HPP 1\n\n#include <boost/assert.hpp>\n#include <set>\n#include <vector>\n#include <boost/concept_check.hpp>\n#include <boost/concept/assert.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/buffer_concepts.hpp>\n#include <boost/graph/exception.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/maximum_adjacency_search.hpp>\n#include <boost/graph/named_function_params.hpp>\n#include <boost/graph/one_bit_color_map.hpp>\n#include <boost/graph/detail/d_ary_heap.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <boost/tuple/tuple.hpp>\n#include <boost/utility/result_of.hpp>\n#include <boost/graph/iteration_macros.hpp>\n\nnamespace boost {\n\n  namespace detail {\n    template < typename ParityMap, typename WeightMap, typename IndexMap >\n    class mas_min_cut_visitor : public boost::default_mas_visitor {\n      typedef one_bit_color_map <IndexMap> InternalParityMap;\n      typedef typename boost::property_traits<WeightMap>::value_type weight_type;\n    public:\n      template < typename Graph >\n      mas_min_cut_visitor(const Graph& g,\n                          ParityMap parity,\n                          weight_type& cutweight,\n                          const WeightMap& weight_map, \n                          IndexMap index_map)\n        : m_bestParity(parity),\n          m_parity(make_one_bit_color_map(num_vertices(g), index_map)),\n          m_bestWeight(cutweight),\n          m_cutweight(0),\n          m_visited(0),\n          m_weightMap(weight_map)\n      {\n        // set here since the init list sets the reference\n        m_bestWeight = (std::numeric_limits<weight_type>::max)();\n      }\n\n      template < typename Vertex, typename Graph >\n      void initialize_vertex(Vertex u, const Graph & g)\n      {\n        typedef typename boost::property_traits<ParityMap>::value_type parity_type;\n        typedef typename boost::property_traits<InternalParityMap>::value_type internal_parity_type;\n\n        put(m_parity, u, internal_parity_type(0));\n        put(m_bestParity, u, parity_type(0));\n      }\n\n      template < typename Edge, typename Graph >\n      void examine_edge(Edge e, const Graph & g)\n      {\n        weight_type w = get(m_weightMap, e);\n\n        // if the target of e is already marked then decrease cutweight\n        // otherwise, increase it\n        if (get(m_parity, boost::target(e, g))) {\n          m_cutweight -= w;\n        } else {\n          m_cutweight += w;\n        }\n      }\n\n      template < typename Vertex, typename Graph >\n      void finish_vertex(Vertex u, const Graph & g)\n      {\n        typedef typename boost::property_traits<ParityMap>::value_type parity_type;\n        typedef typename boost::property_traits<InternalParityMap>::value_type internal_parity_type;\n\n        ++m_visited;\n        put(m_parity, u, internal_parity_type(1));\n\n        if (m_cutweight < m_bestWeight && m_visited < num_vertices(g)) {\n          m_bestWeight = m_cutweight;\n          BGL_FORALL_VERTICES_T(i, g, Graph) {\n            put(m_bestParity,i, get(m_parity,i));\n          }\n        }\n      }\n\n      inline void clear() {\n        m_bestWeight = (std::numeric_limits<weight_type>::max)();\n        m_visited = 0;\n        m_cutweight = 0;\n      }\n\n    private:\n      ParityMap m_bestParity;\n      InternalParityMap m_parity;\n      weight_type& m_bestWeight;\n      weight_type m_cutweight;\n      unsigned m_visited;\n      const WeightMap& m_weightMap;\n    };\n\n    /**\n     * \\brief Computes a min-cut of the input graph\n     *\n     * Computes a min-cut of the input graph using the Stoer-Wagner algorithm.\n     *\n     * \\pre \\p g is a connected, undirected graph\n     * \\pre <code>pq.empty()</code>\n     * \\param[in] g the input graph\n     * \\param[in] weights a readable property map from each edge to its weight (a non-negative value)\n     * \\param[out] parities a writable property map from each vertex to a bool type object for\n     *     distinguishing the two vertex sets of the min-cut\n     * \\param[out] assignments a read/write property map from each vertex to a \\c vertex_descriptor object. This\n     *     map serves as work space, and no particular meaning should be derived from property values\n     *     after completion of the algorithm.\n     * \\param[out] pq a keyed, updatable max-priority queue\n     * \\returns the cut weight of the min-cut\n     * \\see http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.114.6687&rep=rep1&type=pdf\n     * \\see http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.31.614&rep=rep1&type=pdf\n     *\n     * \\author Daniel Trebbien\n     * \\date 2010-09-11\n     */\n    template <class UndirectedGraph, class WeightMap, class ParityMap, class VertexAssignmentMap, class KeyedUpdatablePriorityQueue, class IndexMap>\n    typename boost::property_traits<WeightMap>::value_type\n    stoer_wagner_min_cut(const UndirectedGraph& g, WeightMap weights, ParityMap parities, VertexAssignmentMap assignments, KeyedUpdatablePriorityQueue& pq, IndexMap index_map) {\n      typedef typename boost::graph_traits<UndirectedGraph>::vertex_descriptor vertex_descriptor;\n      typedef typename boost::graph_traits<UndirectedGraph>::vertices_size_type vertices_size_type;\n      typedef typename boost::graph_traits<UndirectedGraph>::edge_descriptor edge_descriptor;\n      typedef typename boost::property_traits<WeightMap>::value_type weight_type;\n      typedef typename boost::property_traits<ParityMap>::value_type parity_type;\n\n      typename graph_traits<UndirectedGraph>::vertex_iterator u_iter, u_end;\n\n      weight_type bestW = (std::numeric_limits<weight_type>::max)();\n      weight_type bestThisTime = (std::numeric_limits<weight_type>::max)();\n      vertex_descriptor bestStart = boost::graph_traits<UndirectedGraph>::null_vertex();\n\n      detail::mas_min_cut_visitor<ParityMap, WeightMap, IndexMap>\n        vis(g, parities, bestThisTime, weights, index_map);\n\n      // for each node in the graph,\n      for (boost::tie(u_iter, u_end) = vertices(g); u_iter != u_end; ++u_iter) {\n        // run the MAS and find the min cut\n        vis.clear();\n        boost::maximum_adjacency_search(g,\n            boost::weight_map(weights).\n            visitor(vis).\n            root_vertex(*u_iter).\n            vertex_assignment_map(assignments).\n            max_priority_queue(pq));\n        if (bestThisTime < bestW) {\n          bestW = bestThisTime;\n          bestStart = *u_iter;\n        }\n      }\n\n      // Run one more time, starting from the best start location, to\n      // ensure the visitor has the best values.\n      vis.clear();\n      boost::maximum_adjacency_search(g,\n        boost::vertex_assignment_map(assignments).\n        weight_map(weights).\n        visitor(vis).\n        root_vertex(bestStart).\n        max_priority_queue(pq));\n\n      return bestW;\n    }\n  } // end `namespace detail` within `namespace boost`\n\n    template <class UndirectedGraph, class WeightMap, class ParityMap, class VertexAssignmentMap, class KeyedUpdatablePriorityQueue, class IndexMap>\n    typename boost::property_traits<WeightMap>::value_type\n    stoer_wagner_min_cut(const UndirectedGraph& g, WeightMap weights, ParityMap parities, VertexAssignmentMap assignments, KeyedUpdatablePriorityQueue& pq, IndexMap index_map) {\n      BOOST_CONCEPT_ASSERT((boost::IncidenceGraphConcept<UndirectedGraph>));\n      BOOST_CONCEPT_ASSERT((boost::VertexListGraphConcept<UndirectedGraph>));\n      typedef typename boost::graph_traits<UndirectedGraph>::vertex_descriptor vertex_descriptor;\n      typedef typename boost::graph_traits<UndirectedGraph>::vertices_size_type vertices_size_type;\n      typedef typename boost::graph_traits<UndirectedGraph>::edge_descriptor edge_descriptor;\n      BOOST_CONCEPT_ASSERT((boost::Convertible<typename boost::graph_traits<UndirectedGraph>::directed_category, boost::undirected_tag>));\n      BOOST_CONCEPT_ASSERT((boost::ReadablePropertyMapConcept<WeightMap, edge_descriptor>));\n      typedef typename boost::property_traits<WeightMap>::value_type weight_type;\n      BOOST_CONCEPT_ASSERT((boost::WritablePropertyMapConcept<ParityMap, vertex_descriptor>));\n      typedef typename boost::property_traits<ParityMap>::value_type parity_type;\n      BOOST_CONCEPT_ASSERT((boost::ReadWritePropertyMapConcept<VertexAssignmentMap, vertex_descriptor>));\n      BOOST_CONCEPT_ASSERT((boost::Convertible<vertex_descriptor, typename boost::property_traits<VertexAssignmentMap>::value_type>));\n      BOOST_CONCEPT_ASSERT((boost::KeyedUpdatableQueueConcept<KeyedUpdatablePriorityQueue>));\n\n      vertices_size_type n = num_vertices(g);\n      if (n < 2)\n        throw boost::bad_graph(\"the input graph must have at least two vertices.\");\n      else if (!pq.empty())\n        throw std::invalid_argument(\"the max-priority queue must be empty initially.\");\n\n      return detail::stoer_wagner_min_cut(g, weights,\n                                          parities, assignments, pq, index_map);\n    }\n\nnamespace graph {\n  namespace detail {\n    template <class UndirectedGraph, class WeightMap>\n    struct stoer_wagner_min_cut_impl {\n      typedef typename boost::property_traits<WeightMap>::value_type result_type;\n      template <typename ArgPack>\n      result_type operator() (const UndirectedGraph& g, WeightMap weights, const ArgPack& arg_pack) const {\n        using namespace boost::graph::keywords;\n        typedef typename boost::graph_traits<UndirectedGraph>::vertex_descriptor vertex_descriptor;\n        typedef typename boost::property_traits<WeightMap>::value_type weight_type;\n\n        typedef boost::detail::make_priority_queue_from_arg_pack_gen<boost::graph::keywords::tag::max_priority_queue, weight_type, vertex_descriptor, std::greater<weight_type> > gen_type;\n\n        gen_type gen(choose_param(get_param(arg_pack, boost::distance_zero_t()), weight_type(0)));\n\n        typename boost::result_of<gen_type(const UndirectedGraph&, const ArgPack&)>::type pq = gen(g, arg_pack);\n\n        return boost::stoer_wagner_min_cut(g,\n          weights,\n          arg_pack [_parity_map | boost::dummy_property_map()],\n          boost::detail::make_property_map_from_arg_pack_gen<tag::vertex_assignment_map, vertex_descriptor>(vertex_descriptor())(g, arg_pack),\n          pq,\n          boost::detail::override_const_property(arg_pack, _vertex_index_map, g, vertex_index)\n        );\n      }\n    };\n  }\n  BOOST_GRAPH_MAKE_FORWARDING_FUNCTION(stoer_wagner_min_cut,2,4)\n}\n\n  // Named parameter interface\n  BOOST_GRAPH_MAKE_OLD_STYLE_PARAMETER_FUNCTION(stoer_wagner_min_cut, 2)\nnamespace graph {\n    // version without IndexMap kept for backwards compatibility\n    // (but requires vertex_index_t to be defined in the graph)\n    // Place after the macro to avoid compilation errors\n    template <class UndirectedGraph, class WeightMap, class ParityMap, class VertexAssignmentMap, class KeyedUpdatablePriorityQueue>\n    typename boost::property_traits<WeightMap>::value_type\n    stoer_wagner_min_cut(const UndirectedGraph& g, WeightMap weights, ParityMap parities, VertexAssignmentMap assignments, KeyedUpdatablePriorityQueue& pq) {\n\n      return stoer_wagner_min_cut(g, weights,\n                                  parities, assignments, pq,\n                                  get(vertex_index, g));\n    }\n} // end `namespace graph`\n} // end `namespace boost`\n\n#include <boost/graph/iteration_macros_undef.hpp>\n\n#endif // !BOOST_GRAPH_STOER_WAGNER_MIN_CUT_HPP\n", "meta": {"hexsha": "a777f0311ee5a09269d6cca0b48e61191fdea05b", "size": 11634, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "extlibs/miniBoost/boost/graph/stoer_wagner_min_cut.hpp", "max_stars_repo_name": "sofa-framework/issofa", "max_stars_repo_head_hexsha": "94855f488465bc3ed41223cbde987581dfca5389", "max_stars_repo_licenses": ["OML"], "max_stars_count": 61.0, "max_stars_repo_stars_event_min_datetime": "2015-12-05T19:34:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-25T09:07:09.000Z", "max_issues_repo_path": "boost/graph/stoer_wagner_min_cut.hpp", "max_issues_repo_name": "graehl/boost", "max_issues_repo_head_hexsha": "37cc4ca77896a86ad10e90dc03e1e825dc0d5492", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 38.0, "max_issues_repo_issues_event_min_datetime": "2015-07-22T07:35:45.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-14T16:03:06.000Z", "max_forks_repo_path": "boost/graph/stoer_wagner_min_cut.hpp", "max_forks_repo_name": "graehl/boost", "max_forks_repo_head_hexsha": "37cc4ca77896a86ad10e90dc03e1e825dc0d5492", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 35.0, "max_forks_repo_forks_event_min_datetime": "2015-12-17T00:09:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-27T10:47:11.000Z", "avg_line_length": 45.6235294118, "max_line_length": 187, "alphanum_fraction": 0.7047447138, "num_tokens": 2645, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389817407016, "lm_q2_score": 0.6224593171945417, "lm_q1q2_score": 0.46444116110654776}}
{"text": "/**\n * August 8th, 2018\n * source: https://zhuanlan.zhihu.com/p/38745950\n * Constant velocity prediction Kalman filter for shield global position\n */\n\n#include <iostream>\n#include <ros/ros.h>\n#include <std_msgs/String.h>\n#include <geometry_msgs/TwistStamped.h>\n#include <geometry_msgs/QuaternionStamped.h>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <queue>\n#include \"rm_cv/ArmorRecord.h\"\n\nusing namespace std;\nusing namespace Eigen;\n\nstring attitude_topic, publisher_topic, debug_topic, real_visual_topic, transform_topic;\nstring debug_angle_topic;\nros::Publisher filter_pub, debug_pub, transform_pub, debug_angle_pub;\nMatrixXd gimbal_R_camera = MatrixXd::Identity(3, 3); // rotation matrix from camera to imu\nMatrixXd init_R_gimbal= MatrixXd::Identity(3, 3);\nVector3d gimbal_T_camera = MatrixXd::Zero(3, 1);\n\nVectorXd x(6);      // state\nMatrixXd P = MatrixXd::Identity(6, 6); // covariance\nMatrixXd Q = MatrixXd::Identity(6, 6); // prediction noise covariance\nMatrixXd R = MatrixXd::Identity(3, 3); // observation noise covariance\nMatrixXd A = MatrixXd::Identity(6, 6); // state transfer function\n\nbool visual_initialized = false, visual_valid = false;\n\nros::Time t_prev;\ndouble R_pos, Q_pos, Q_vel, P_weight;\nconst double CV_UPDATE_TIME_MAX = 0.2; // maxium allowed update time\nconst double DELAY_MAX = 0.05;\nconst int ROS_FREQ = 100;\nconst int MAX_VISUAL_QUEUE_SIZE = 5;\nconst int MAX_IMU_QUEUE_SIZE = 1000;\ndouble OUTLIER_THRESHOLD = 10000.0;\n\nVector3d init_T_shield_prev = MatrixXd::Zero(3, 1);\nVector3d imu_T_shield_prev = MatrixXd::Zero(3, 1);\nbool pos_is_outlier = false;\ndouble chi_square = 0;\ndouble outlier_l2_norm_ratio = 1.5;\ndouble yaw_delay = 0.0;\ndouble pitch_delay = 0.0;\nVector3d OUTPUT_BOUND = MatrixXd::Zero(3, 1);\n\n// synchronization\nqueue<geometry_msgs::QuaternionStamped::ConstPtr> imu_queue;\nqueue<Vector3d> visual_queue;\nint imu_back_time = 10;\n\n\ndouble angle_diff = 0;\nbool angle_diff_not_inited = true;\n\nstatic void pub_result(const ros::Time &stamp, double delay_dt)\n{\n//    geometry_msgs::TwistStamped odom;\n    rm_cv::ArmorRecord odom;\n    odom.header.stamp = stamp;\n    double predict_x = x(0) + (delay_dt + yaw_delay)   * x(3);\n    double predict_y = x(1) + (delay_dt + pitch_delay) * x(4);\n    double predict_z = x(2) + delay_dt * x(5);\n    odom.armorPose.linear.x  = (predict_x < OUTPUT_BOUND[0]) ? predict_x * 1000 : OUTPUT_BOUND[0] * 1000;\n    odom.armorPose.linear.y  = (predict_y < OUTPUT_BOUND[1]) ? predict_y * 1000 : OUTPUT_BOUND[1] * 1000;\n    odom.armorPose.linear.z  = (predict_z < OUTPUT_BOUND[2]) ? predict_z * 1000 : OUTPUT_BOUND[2] * 1000;\n    odom.armorPose.angular.x = x(3) * 1000;\n    odom.armorPose.angular.y = x(4) * 1000;\n    odom.armorPose.angular.z = x(5) * 1000;\n    filter_pub.publish(odom);\n}\n\nstatic void pub_preprocessed(const std_msgs::Header &header,\n                      const Ref<const Vector3d> p,\n                      const Ref<const Vector3d> v,\n                      ros::Publisher &publisher)\n{\n    geometry_msgs::TwistStamped debug;\n    debug.header = header;\n    debug.twist.linear.x  = p[0];\n    debug.twist.linear.y  = p[1];\n    debug.twist.linear.z  = p[2];\n    debug.twist.angular.x = v[0];\n    debug.twist.angular.y = v[1];\n    debug.twist.angular.z = v[2];\n    publisher.publish(debug);\n}\n\nstatic void pub_angle_debug(const std_msgs::Header &header,\n                            const double yaw,\n                            const Ref<const Vector3d> p,\n                            const double imuz)\n{\n    geometry_msgs::TwistStamped debug_angle;\n    debug_angle.header = header;\n    debug_angle.twist.angular.x = yaw;\n    debug_angle.twist.angular.y = -atan2(p[1], p[0]);\n    debug_angle.twist.angular.z = imuz;\n    debug_angle_pub.publish(debug_angle);\n}\n\nstatic double imu_to_yaw_angle(const geometry_msgs::QuaternionStamped::ConstPtr &imu)\n{\n    // Quaterniond q = Quaterniond( imu->quaternion.w, imu->quaternion.x, imu->quaternion.y, imu->quaternion.z );\n    double qw = imu->quaternion.w;\n    double qx = imu->quaternion.x;\n    double qy = imu->quaternion.y;\n    double qz = imu->quaternion.z;\n\n    // convert to ZYX Euler angle yaw angle\n    // double euler_angle_0 = atan2(2.0 * (qw * qx + qy * qz), 1.0 - 2.0 * (qx * qx + qy * qy) );\n    // double euler_angle_1 = asin( 2.0 * (qw * qy - qz * qx) );\n    return atan2(2.0 * (qw * qz + qx * qy), 1.0 - 2.0 * (qy * qy + qz * qz) );\n}\n\n// Chi-square test for outlier rejection\nstatic bool translation_is_outlier(const Vector3d &pos)\n{\n    VectorXd r = MatrixXd::Zero(3, 1);\n    VectorXd z = MatrixXd::Zero(3, 1);\n    MatrixXd S = MatrixXd::Zero(3, 3);\n    z << pos[0], pos[1], pos[2];\n\n    double pos_norm   = z.segment<3>(0).norm();\n    double state_norm = x.segment<3>(0).norm();\n    // ROS_INFO(\"pos_norm %f, state_norm %f\", pos_norm, state_norm);\n    if (pos_norm > state_norm * outlier_l2_norm_ratio) {\n        return true;\n    } else if (pos_norm < state_norm / outlier_l2_norm_ratio) {\n        return true;\n    }\n\n    // r = z - H * x, residual\n    // S = H P H' + R, residual covariance\n    MatrixXd H = MatrixXd::Identity(3, 6); // observation matrix\n\n//    MatrixXd K_next = (H * P * H.transpose() + R).ldlt().solve(P * H.transpose());\n//    MatrixXd x_next = x + K_next * (z - H * x);\n//    MatrixXd P_next = P - K_next * H * P;\n\n    r = z - H * x;\n    S = H * P * H.transpose() + R;\n    chi_square = r.transpose() * S * r;\n    // cout << \"chi_square \" << endl << chi_square << endl;\n\n    return (chi_square > OUTLIER_THRESHOLD);\n}\n\n\n\nstatic void preprocess_visual(const std_msgs::Header &header,\n                              const geometry_msgs::Twist &twist,\n                              Vector3d &pos, double dt_update)\n{\n    Vector3d camera_T_shield, gimbal_T_shield, init_T_shield;\n    Vector3d camera_vel_shield, gimbal_vel_shield, init_vel_shield;\n    camera_T_shield[0] = twist.linear.x;\n    camera_T_shield[1] = twist.linear.y;\n    camera_T_shield[2] = twist.linear.z;\n    gimbal_T_shield = gimbal_R_camera * camera_T_shield + gimbal_T_camera;\n    gimbal_T_shield *= 0.001; // Convert millimeter to meter\n\n    Matrix3d world_R_gimbal;// = MatrixXd::Identity(3, 3);\n    world_R_gimbal << 1, 0, 0, 0, 1, 0, 0, 0, 1;\n    double yaw = 0;\n    double imuz= 0;\n\n/*    int pop_time = 0;\n    if (!imu_queue.empty()) {\n        pop_time = imu_queue.size() - imu_back_time;\n\n        if (pop_time > 0) {\n            for (int i = 0; i < pop_time; ++i) {\n                imu_queue.pop();\n            }\n            imuz = imu_queue.front()->quaternion.z;\n            yaw = imu_to_yaw_angle(imu_queue.front());\n            world_R_gimbal << cos(yaw), -sin(yaw), 0, sin(yaw), cos(yaw), 0, 0, 0, 1;\n\n            if (angle_diff_not_inited) {\n                angle_diff =  yaw + atan2(gimbal_T_shield[1], gimbal_T_shield[0]);\n                angle_diff_not_inited = false;\n                ROS_INFO(\"angle_diff is, %f\", angle_diff);\n            }\n        }\n    }*/\n    init_T_shield = world_R_gimbal * gimbal_T_shield;\n\n    // calculate and check the velocity\n    init_vel_shield = (init_T_shield - init_T_shield_prev) / dt_update;\n    init_T_shield_prev = init_T_shield;\n\n    pos_is_outlier = translation_is_outlier(init_T_shield);\n\n    if (pos_is_outlier) {\n        pos = x.segment<3>(0);\n        x.segment<3>(3) *= 0.5;\n        ROS_INFO(\"outlier rejected\");\n    }\n    else {\n        pos = init_T_shield;\n    }\n\n    // store the state\n    pub_preprocessed(header, gimbal_T_shield, gimbal_vel_shield, debug_pub);\n\n    pub_preprocessed(header, init_T_shield_prev, init_vel_shield, transform_pub);\n\n    pub_angle_debug(header, yaw - angle_diff, gimbal_T_shield, imuz);\n}\n\n/**\n * Core Kalman Filter math, propagate and update\n */\nstatic void propagate(const double &dt) {\n    A.topRightCorner(3, 3) = dt * MatrixXd::Identity(3, 3);\n    x = A * x;\n    P = A * P * A.transpose() + Q;\n}\n\nstatic void update(const Vector3d &pos)\n{\n    MatrixXd H, K, z;\n\n    H = MatrixXd::Identity(3, 6); // observation matrix\n    K = P * H.transpose() * (H * P * H.transpose() + R).inverse();\n    z = MatrixXd::Zero(3, 1);\n    z << pos[0], pos[1], pos[2];\n\n    x = x + K * (z - H * x);\n    P = P - K * H * P;\n}\n\n/**\n * initialization of the state and convariance from visual\n * @param pnp\n */\nstatic void initialize_visual(const std_msgs::Header &header,\n                              const geometry_msgs::Twist &twist)\n{\n    ros::Time t_update = header.stamp;\n    ROS_INFO(\"visual init at %f\", t_update.toSec());\n\n    Vector3d camera_T_shield, gimbal_T_shield, init_T_shield;\n    camera_T_shield[0] = twist.linear.x;\n    camera_T_shield[1] = twist.linear.y;\n    camera_T_shield[2] = twist.linear.z;\n\n    gimbal_T_shield = gimbal_R_camera * camera_T_shield + gimbal_T_camera;\n    gimbal_T_shield *= 0.001; // Convert millimeter to meter\n\n    Matrix3d world_R_gimbal;// = MatrixXd::Identity(3, 3);\n    world_R_gimbal << 1, 0, 0, 0, 1, 0, 0, 0, 1;\n    double yaw = 0;\n\n/*    int pop_time = 0;\n    if (!imu_queue.empty()) {\n        pop_time = imu_queue.size() - imu_back_time;\n\n        if (pop_time > 0) {\n            for (int i = 0; i < pop_time; ++i) {\n                imu_queue.pop();\n            }\n            yaw = imu_to_yaw_angle(imu_queue.front());\n            // double euler_angle_2 = imu_to_yaw_angle(imu_queue.back());\n            world_R_gimbal << cos(yaw), -sin(yaw), 0, sin(yaw), cos(yaw), 0, 0, 0, 1;\n            double DEBUG_imu_delay_time = header.stamp.toSec() - imu_queue.front()->header.stamp.toSec();\n            cout << \"imu to visual time difference \" << DEBUG_imu_delay_time << endl;\n        }\n        cout << \"final poped times \" << pop_time << endl;\n    }*/\n\n    cout << \"world_R_gimbal \" << endl << world_R_gimbal << endl;\n\n    init_T_shield = world_R_gimbal * gimbal_T_shield;\n\n    // TODO: using RANSAC instead of averaging filter\n    visual_queue.push(init_T_shield);\n    if (visual_queue.size() >= MAX_VISUAL_QUEUE_SIZE) {\n        Vector3d T_sum;\n        T_sum.setZero();\n\n        for (int i = 0; i < MAX_VISUAL_QUEUE_SIZE; ++i) {\n            T_sum += visual_queue.front();\n            visual_queue.pop();\n        }\n\n        x.segment<3>(0) = T_sum / MAX_VISUAL_QUEUE_SIZE; // init velocity with zero\n        x.segment<3>(3).setZero(); // init velocity with zero\n\n        P.setZero();\n        P.topLeftCorner(3, 3)     = P_weight * MatrixXd::Identity(3, 3);\n        P.bottomRightCorner(3, 3) = 2 * P_weight * MatrixXd::Identity(3, 3);\n\n        cout << \"DEBUG: x initialized with \" << endl << x.transpose() << endl;\n        cout << \"P \" << endl << P << endl;\n\n        init_T_shield_prev = init_T_shield;\n        visual_initialized = true;\n    }\n    else {\n        cout << \"DEBUG: current x reading: \" << init_T_shield.transpose() << endl;\n    }\n}\n\n\n/**\n * handle and save attitude of the gimbal\n * @param imu\n */\nvoid attitude_cb(const geometry_msgs::QuaternionStamped::ConstPtr &imu)\n{\n    // synchronize the timestamp\n    imu_queue.push(imu);\n    if (imu_queue.size() > MAX_IMU_QUEUE_SIZE) imu_queue.pop();\n}\n\n/**\n * handle, save, and process visual messages\n * @param armor\n */\nvoid real_visual_cb(const rm_cv::ArmorRecord::ConstPtr &armor)\n{\n    visual_valid = !(armor->armorPose.linear.x == 0 &&\n                     armor->armorPose.linear.y == 0 &&\n                     armor->armorPose.linear.z == 0 );\n\n    if (visual_valid) {\n        ros::Time t_update = armor->header.stamp;\n        double dt_update = (t_update - t_prev).toSec();\n\n        if (!visual_initialized) {\n            initialize_visual(armor->header, armor->armorPose);\n        }\n        else {\n            if (dt_update < CV_UPDATE_TIME_MAX) {\n                Vector3d pos;\n\n                preprocess_visual(armor->header, armor->armorPose, pos, dt_update);\n\n                update(pos);\n\n                propagate(dt_update);\n\n                double running_time = ros::Time::now().toSec();\n                double delay_dt = running_time - armor->header.stamp.toSec();\n                delay_dt = (delay_dt < DELAY_MAX) ? delay_dt : DELAY_MAX;\n\n                pub_result(armor->header.stamp, delay_dt);\n            }\n            else {\n                visual_queue.push(x.segment<3>(0));\n\n                visual_initialized = false;\n\n                initialize_visual(armor->header, armor->armorPose);\n            }\n        }\n        t_prev = t_update;\n    }\n\n}\n\nint main(int argc, char **argv)\n{\n    ros::init(argc, argv, \"prediction_kalman_filter\");\n    ros::NodeHandle n(\"~\");\n\n    n.param(\"attitude_topic\", attitude_topic, string(\"/can_receive_node/attitude\"));\n    n.param(\"real_visual_topic\", real_visual_topic, string(\"/detected_armor\"));\n    n.param(\"publisher_topic\", publisher_topic, string(\"/prediction_kf_global/predict\"));\n    n.param(\"debug_topic\", debug_topic, string(\"/prediction_kf_global/preprocessed\"));\n    n.param(\"transform_topic\", transform_topic, string(\"/prediction_kf_global/transformed\"));\n    n.param(\"debug_angle_topic\", debug_angle_topic, string(\"/prediction_kf/debug_angle\"));\n    n.param(\"chi_square_threshold\", OUTLIER_THRESHOLD, 10000.0);\n    n.param(\"outlier_l2_norm_ratio\", outlier_l2_norm_ratio, 1.5);\n    n.param(\"imu_back_time\", imu_back_time, 10);\n    n.param(\"R_pos\", R_pos, 16.0);\n    n.param(\"Q_pos\", Q_pos, 0.2);\n    n.param(\"Q_vel\", Q_vel, 1.0);\n    n.param(\"P_matrix_weight\", P_weight, 1.0);\n    n.param(\"yaw_delay\", yaw_delay, 0.0);\n    n.param(\"pitch_delay\", pitch_delay, 0.0);\n\n    // For chassis reading only\n    gimbal_R_camera <<  0, 0, 1,\n                    -1, 0, 0,\n                     0,-1, 0;\n    gimbal_T_camera <<  30, 0, -120; // in millimeter\n\n    OUTPUT_BOUND << 10.0, 10.0, 20.0;\n\n    x.setZero();\n    R = R_pos * MatrixXd::Identity(3, 3);\n    Q.topLeftCorner(3, 3)     = Q_pos * MatrixXd::Identity(3, 3);\n    Q.bottomRightCorner(3, 3) = Q_vel * MatrixXd::Identity(3, 3);\n    cout << \"R \" << endl << R << endl;\n    cout << \"Q \" << endl << Q << endl;\n\n    ros::Subscriber s1 = n.subscribe(attitude_topic, 100, attitude_cb);\n    ros::Subscriber s2 = n.subscribe(real_visual_topic, 40, real_visual_cb);\n\n    filter_pub = n.advertise<rm_cv::ArmorRecord>(publisher_topic, 40);\n    debug_pub  = n.advertise<geometry_msgs::TwistStamped>(debug_topic, 40);\n    transform_pub = n.advertise<geometry_msgs::TwistStamped>(transform_topic, 40);\n    debug_angle_pub = n.advertise<geometry_msgs::TwistStamped>(debug_angle_topic, 100);\n    ros::Rate r(ROS_FREQ);\n\n    while (ros::ok()) {\n        if (visual_initialized) {\n\n        }\n\n        r.sleep();\n        ros::spinOnce();\n    }\n}\n", "meta": {"hexsha": "c31e2105a7c21b5cbd0d7bc7b38b683ca8604794", "size": 14461, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3_estimator/history/prediction_kf/src/prediction_kf_node_global.cpp", "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/history/prediction_kf/src/prediction_kf_node_global.cpp", "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/history/prediction_kf/src/prediction_kf_node_global.cpp", "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": 34.1061320755, "max_line_length": 113, "alphanum_fraction": 0.6263743863, "num_tokens": 4127, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402813, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.46443553502463264}}
{"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/bind/bind.hpp>\nusing namespace boost::placeholders;\n\n\n#include \"tudat/math/statistics/randomVariableGenerator.h\"\n#include \"tudat/math/statistics/boostProbabilityDistributions.h\"\n\nnamespace tudat\n{\n\nnamespace statistics\n{\n\nstd::function< Eigen::VectorXd( const double ) > getIndependentGaussianNoiseFunction(\n        const double standardDeviation,\n        const double mean,\n        const double seed,\n        const int outputSize )\n{\n    std::function< double( ) > inputFreeNoiseFunction = statistics::createBoostContinuousRandomVariableGeneratorFunction(\n                statistics::normal_boost_distribution, { mean, standardDeviation }, seed );\n    if( outputSize == 1 )\n    {\n        return [=](const double){ return ( Eigen::VectorXd( outputSize )<<\n                                           inputFreeNoiseFunction( ) ).finished( ); };\n    }\n    else if( outputSize == 2 )\n    {\n        return [=](const double){ return ( Eigen::VectorXd( outputSize )<<\n                                           inputFreeNoiseFunction( ), inputFreeNoiseFunction( ) ).finished( ); };\n    }\n    else if( outputSize == 3 )\n    {\n        return [=](const double){ return ( Eigen::VectorXd( outputSize )<<\n                                           inputFreeNoiseFunction( ), inputFreeNoiseFunction( ), inputFreeNoiseFunction( ) ).finished( ); };\n    }\n    else if( outputSize == 6 )\n    {\n        return [=](const double){ return ( Eigen::VectorXd( outputSize )<<\n                                           inputFreeNoiseFunction( ), inputFreeNoiseFunction( ), inputFreeNoiseFunction( ),\n                                           inputFreeNoiseFunction( ), inputFreeNoiseFunction( ), inputFreeNoiseFunction( ) ).finished( ); };\n    }\n    else\n    {\n        throw std::runtime_error( \"Cannot simulate observation noise of size \" + std::to_string( outputSize ) );\n    }\n}\n\n//! Function to create a random number generating function from a continuous univariate distribution implemented in boost\nstd::function< double( ) > createBoostContinuousRandomVariableGeneratorFunction(\n        const ContinuousBoostStatisticalDistributions boostDistribution,\n        const std::vector< double >& parameters,\n        const double seed )\n{\n    return std::bind( &RandomVariableGenerator< double >::getRandomVariableValue,\n                        createBoostContinuousRandomVariableGenerator( boostDistribution, parameters, seed ) );\n}\n\n//! Function to create a random number generator from a continuous univariate distribution implemented in boost\nstd::shared_ptr< RandomVariableGenerator< double > > createBoostContinuousRandomVariableGenerator(\n        const ContinuousBoostStatisticalDistributions boostDistribution,\n        const std::vector< double >& parameters,\n        const double seed )\n{\n    return std::make_shared< ContinuousRandomVariableGenerator >(\n                createBoostRandomVariable( boostDistribution, parameters ), seed );\n}\n\n}\n\n}\n\n", "meta": {"hexsha": "4f41ceddfd469fb7057c7f730e2e959cbdc688ce", "size": 3413, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/math/statistics/randomVariableGenerator.cpp", "max_stars_repo_name": "kimonito98/tudat", "max_stars_repo_head_hexsha": "c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/math/statistics/randomVariableGenerator.cpp", "max_issues_repo_name": "kimonito98/tudat", "max_issues_repo_head_hexsha": "c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/math/statistics/randomVariableGenerator.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": 40.630952381, "max_line_length": 140, "alphanum_fraction": 0.6645180193, "num_tokens": 697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402813, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.46443553502463264}}
{"text": "#include <cmath>\n#include <vector>\n#include <iostream>\n#include <cassert>\n\n#include <Eigen/Dense>\n\n#include \"startree.h\"\n\nnamespace startree {\n// Make a have the minimum x, y and z coordinates of a and b\nstatic void minVec(Vector3d& a, const Vector3d& b) {\n    a[X] = fmin(a[X], b[X]);\n    a[Y] = fmin(a[Y], b[Y]);\n    a[Z] = fmin(a[Z], b[Z]);\n}\n\n// Make a have the maximum x, y and z coordinates of a and b\nstatic void maxVec(Vector3d& a, const Vector3d& b) {\n    a[X] = fmax(a[X], b[X]);\n    a[Y] = fmax(a[Y], b[Y]);\n    a[Z] = fmax(a[Z], b[Z]);\n}\n\n/* Return new set of sub-bounds given the parent bounds, the split point\n * and the direction (which octant) */\nstatic void\nsplitBounds(const Vector3d oldBounds[2], Vector3d newBounds[2],\n            const Vector3d splitPoint, Vector3d& childSplit,\n            TreeDirection dir) {\n    switch(dir) {\n    case NED:\n        newBounds[0] = splitPoint;\n        newBounds[1] = oldBounds[1];\n        break;\n    case NWD:\n        newBounds[0] = splitPoint;\n        newBounds[0][Y] = oldBounds[0][Y];\n        newBounds[1] = oldBounds[1];\n        newBounds[1][Y] = splitPoint[Y];\n        break;\n    case SED:\n        newBounds[0] = splitPoint;\n        newBounds[0][X] = oldBounds[0][X];\n        newBounds[1] = oldBounds[1];\n        newBounds[1][X] = splitPoint[X];\n        break;\n    case SWD:\n        newBounds[0] = oldBounds[0];\n        newBounds[0][Z] = splitPoint[Z];\n        newBounds[1] = splitPoint;\n        newBounds[1][Z] = oldBounds[1][Z];\n        break;\n    case NEU:\n        newBounds[0] = splitPoint;\n        newBounds[0][Z] = oldBounds[0][Z];\n        newBounds[1] = oldBounds[1];\n        newBounds[1][Z] = splitPoint[Z];\n        break;\n    case NWU:\n        newBounds[0] = oldBounds[0];\n        newBounds[0][X] = splitPoint[X];\n        newBounds[1] = splitPoint;\n        newBounds[1][X] = oldBounds[1][X];\n        break;\n    case SEU:\n        newBounds[0] = oldBounds[0];\n        newBounds[0][Y] = splitPoint[Y];\n        newBounds[1] = splitPoint;\n        newBounds[1][Y] = oldBounds[1][Y];\n        break;\n    case SWU:\n        newBounds[0] = oldBounds[0];\n        newBounds[1] = splitPoint;\n        break;\n    }\n    childSplit = 0.5 * (newBounds[0] + newBounds[1]);\n}\n\n// Static variable to generate node ID's (not threadsafe)\nstatic uint64_t nextNodeId = 1;\nStarTree::StarTree(uint64_t maxLeafSize, Vector3d splitPoint,\n                   Vector3d minBounds, Vector3d maxBounds) :\n    nodeId_(0),\n    isLeaf_(true),\n    splitPoint_(splitPoint),\n    branches_{nullptr, nullptr, nullptr, nullptr,\n              nullptr, nullptr, nullptr, nullptr},\n    isRoot_(true),\n    parent_(nullptr),\n    maxLeafSize_(maxLeafSize),\n    numStars_(0),\n    maxLuminosity_(0),\n    sumLuminosity_(0),\n    sumColor_(0, 0, 0),\n    averageColor_(0, 0, 0),\n    treeBounds_{minBounds, maxBounds},\n    starBounds_{Vector3d::Zero(), Vector3d::Zero()},\n    boundsCenter_(0, 0, 0),\n    boundsRadius_(0) {}\n\nStarTree::StarTree(uint64_t maxLeafSize, StarTree* parent) :\n    nodeId_(nextNodeId++),\n    isLeaf_(true),\n    branches_{nullptr, nullptr, nullptr, nullptr,\n              nullptr, nullptr, nullptr, nullptr},\n    isRoot_(false),\n    parent_(parent),\n    maxLeafSize_(maxLeafSize),\n    numStars_(0),\n    maxLuminosity_(0),\n    sumLuminosity_(0),\n    sumColor_(0, 0, 0),\n    averageColor_(0, 0, 0),\n    treeBounds_{Vector3d::Zero(), Vector3d::Zero()},\n    starBounds_{Vector3d::Zero(), Vector3d::Zero()},\n    boundsCenter_(0, 0, 0),\n    boundsRadius_(0) {}\n\n// This employs a trick similar to the chmod permission bits\nTreeDirection\nStarTree::getDirection(const Vector3d& from, const Vector3d& to) {\n    bool cx = from[X] >= to[X];\n    bool cy = from[Y] >= to[Y];\n    bool cz = from[Z] >= to[Z];\n    int direction =\n        (cx ? 1 : 0) +\n        (cy ? 2 : 0) +\n        (cz ? 4 : 0);\n    return static_cast<TreeDirection>(direction);\n}\n\nvoid\nStarTree::addStarMetadata(const Star* star) {\n    //std::cerr << \"Start\" << std::endl;\n    numStars_ += 1;\n\n    maxLuminosity_ = fmax(maxLuminosity_, star->lum());\n    //std::cerr << \"Set max luminocity.\" << std::endl;\n    sumLuminosity_ += star->lum();\n    //std::cerr << \"Updated sum of luminocities.\" << std::endl;\n\n    sumColor_ += star->color();\n    //std::cerr << \"Updated sum of colours.\" << std::endl;\n    averageColor_ = sumColor_ / numStars_;\n    //std::cerr << \"Updated average colour.\" << std::endl;\n\n    minVec(starBounds_[0], star->position());\n    //std::cerr << \"Updated star min bounds.\" << std::endl;\n    maxVec(starBounds_[1], star->position());\n    //std::cerr << \"Updated star max bounds.\" << std::endl;\n\n    boundsCenter_ = 0.5 * (starBounds_[0] + starBounds_[1]);\n    //std::cerr << \"Updated star bounds center.\" << std::endl;\n    boundsRadius_ = (boundsCenter_ - starBounds_[1]).norm();\n    //std::cerr << \"Updated star bounds radius.\" << std::endl;\n}\n\nvoid\nStarTree::addStar(const Star* star,\n                  map<uint64_t,const StarTree*>& treeMap) {\n    TreeDirection dir;\n    // Always add the metadata\n    addStarMetadata(star);\n\n    // Do things differently depending on what type of node we are\n    if (isLeaf_) {\n        // If we'd go over our maximum leaf size, we need to split up\n        if (numStars_ > maxLeafSize_) {\n            isLeaf_ = false;\n            // Create the empty child nodes\n            for (int i = 0; i < 8; i++) {\n                assert(branches_[i] == nullptr);\n                branches_[i] = new StarTree(maxLeafSize_, this);\n                splitBounds(treeBounds_, branches_[i]->treeBounds_,\n                            splitPoint_, branches_[i]->splitPoint_,\n                            static_cast<TreeDirection>(i));\n                uint64_t nodeId = branches_[i]->nodeId();\n                assert(treeMap.find(nodeId) == treeMap.end());\n                treeMap[nodeId] = branches_[i];\n            }\n\n            // Add all the old stars\n            for (vector<const Star*>::iterator it = stars_.begin();\n                 it != stars_.end(); ++it) {\n                dir = getDirection(splitPoint_, (*it)->position());\n                branches_[dir]->addStar(*it, treeMap);\n            }\n            // And don't forget the new one\n            dir = getDirection(splitPoint_, star->position());\n            branches_[dir]->addStar(star, treeMap);\n        } else {\n            // Otherwise just add the star to the list\n            stars_.push_back(star);\n        }\n    } else {\n        // We're a branch, figure out the child that gets the star\n        dir = getDirection(splitPoint_, star->position());\n        branches_[dir]->addStar(star, treeMap);\n    }\n}\n\nstatic double getDistance(const Vector3d& pointA,\n                          const Vector3d& pointB) {\n    return (pointA - pointB).norm();\n}\n\n// Check if an octant approximately intersects the given sphere\nstatic bool octantApproxIntersect(const Vector3d& point, double radius,\n                                  const StarTree* t) {\n    const double centerDistance = getDistance(point, t->splitPoint());\n    const double subRadius = getDistance(t->splitPoint(),\n                                         t->maxTreeBounds());\n    return (radius + subRadius) >= centerDistance;\n}\n\n// Get all stars within a given radius from a point\nvoid starsInRadius(const Vector3d& point, double radius,\n                   vector<const StarTree*>& searchList,\n                   vector<const Star*>& starsFound) {\n    // Loop until the search list is empty\n    while (searchList.size() > 0) {\n        // Look at the first thing on the list\n        const StarTree* t = searchList[0];\n        searchList.erase(searchList.begin());\n\n        // Does this octant possibly intersect our sphere?\n        if (octantApproxIntersect(point, radius, t)) {\n            if (t->isLeaf()) {\n                // If it's a leaf check all the stars\n                for (unsigned int i = 0; i < t->numStars(); i++) {\n                    if (getDistance(point, (t->stars()[i])->position()) <=\n                        radius) {\n                        starsFound.push_back(t->stars()[i]);\n                    }\n                }\n            } else {\n                // If it's a branch, add all of the subnodes to be\n                // searched\n                for (int i = 0; i < 8; i++) {\n                    const StarTree* tmp =\n                        t->branch(static_cast<TreeDirection>(i));\n                    searchList.push_back(tmp);\n                }\n            }\n        }\n    }\n}\n\nstatic bool canSeeStar(const Vector3d& point, double minLum,\n                       const Star* star) {\n    const Vector3d& starPosition = star->position();\n    const double starDistance = getDistance(point, starPosition);\n    const double starLuminosity = star->lum();\n\n    return (starLuminosity /\n            (4 * M_PI * starDistance * starDistance)) >= minLum;\n}\n\nstatic bool hasVisibleStars(const Vector3d& point, double minLum,\n                            const StarTree* t) {\n    const double centerDistance = getDistance(point, t->splitPoint());\n    const double subRadius = getDistance(t->splitPoint(),\n                                         t->maxTreeBounds());\n    const double minDistance = fmax((centerDistance - subRadius), 0);\n\n    return (t->maxLuminosity() /\n            (4 * M_PI * minDistance * minDistance)) >= minLum;\n}\n\nvoid visibleStars(const Vector3d& point, double minLuminosity,\n                  vector<const StarTree*>& searchList,\n                  vector<const Star*>& starsFound) {\n    // Loop until the search list is empty\n    while (searchList.size() > 0) {\n        // Look at the first thing on the list\n        const StarTree* t = searchList[0];\n        searchList.erase(searchList.begin());\n\n        if (hasVisibleStars(point, minLuminosity, t)) {\n            if (t->isLeaf()) {\n                for (unsigned int i = 0; i < t->numStars(); i++) {\n                    if (canSeeStar(point, minLuminosity, t->stars()[i])) {\n                        starsFound.push_back(t->stars()[i]);\n                    }\n                }\n            } else {\n                for (int i = 0; i < 8; i++) {\n                    const StarTree* tmp =\n                        t->branch(static_cast<TreeDirection>(i));\n                    searchList.push_back(tmp);\n                }\n            }\n        }\n    }\n}\n\nstatic double sigmoid(double x) {\n    return 1.0 / (1.0 + exp(x));\n}\n\nstatic double magicFormula(double distance, double blurRadius) {\n    double a = log(distance) - log(blurRadius);\n    double b = sigmoid((-2.03935397) * a);\n    double c = sigmoid(-3.065390091 * a + 1.851112427);\n\n    return ( (b + 1.872968808 * c * (1.0 - c)) /\n             (4 * M_PI * distance * distance) );\n}\n\nstatic bool canSeeStarMagic(const Vector3d& point, double minLum,\n                            double blurRadius, const Star* star) {\n    const Vector3d& starPosition = star->position();\n    const double starDistance = getDistance(point, starPosition);\n    const double starLuminosity = star->lum();\n    const double magic =\n        magicFormula(starDistance, blurRadius) * starLuminosity;\n    \n    return magic >= minLum;\n}\n\nstatic bool hasVisibleStarsMagic(const Vector3d& point, double minLum,\n                                 double blurRadius, const StarTree* t) {\n    const double centerDistance = getDistance(point, t->splitPoint());\n    const double subRadius = getDistance(t->splitPoint(),\n                                         t->maxTreeBounds());\n    const double minDistance = fmax((centerDistance - subRadius),\n                                    (4.84814e-7));\n    const double magic =\n        magicFormula(minDistance, blurRadius) * t->maxLuminosity();\n\n    return magic >= minLum;\n}\n\nvoid visibleStarsMagic(const Vector3d& point, double minLuminosity,\n                       double blurRadius,\n                       vector<const StarTree*>& searchList,\n                       vector<const Star*>& starsFound) {\n    // Loop until the searchlist is empty\n    while (searchList.size() > 0) {\n        // Look at the first thing on the list\n        const StarTree* t = searchList[0];\n        searchList.erase(searchList.begin());\n        \n        if (hasVisibleStarsMagic(point, minLuminosity, blurRadius, t)) {\n            if (t->isLeaf()) {\n                for (unsigned int i = 0; i < t->numStars(); i++) {\n                    if (canSeeStarMagic(point, minLuminosity, blurRadius,\n                                        t->stars()[i])) {\n                        starsFound.push_back(t->stars()[i]);\n                    }\n                }\n            } else {\n                for (int i = 0; i < 8; i++) {\n                    const StarTree* tmp =\n                        t->branch(static_cast<TreeDirection>(i));\n                    searchList.push_back(tmp);\n                }\n            }\n        }\n    }\n}\n\nvoid visibleOctants(const Vector3d& point, double minLuminosity,\n                    vector<const StarTree*>& searchList,\n                    vector<uint64_t>& octantsFound) {\n    // Loop until the searchlist is empty\n    while (searchList.size() > 0) {\n        // Look at the first thing on the list\n        const StarTree* t = searchList[0];\n        searchList.erase(searchList.begin());\n        \n        if (hasVisibleStars(point, minLuminosity, t)) {\n            if (t->isLeaf()) {\n                octantsFound.push_back(t->nodeId());\n            } else {\n                for (int i = 0; i < 8; i++) {\n                    const StarTree* tmp =\n                        t->branch(static_cast<TreeDirection>(i));\n                    searchList.push_back(tmp);\n                }\n            }\n        }\n    }\n}\n\nvoid visibleOctantsMagic(const Vector3d& point, double minLuminosity,\n                         double blurRadius,\n                         vector<const StarTree*>& searchList,\n                         vector<uint64_t>& octantsFound) {\n    // Loop until the searchlist is empty\n    while (searchList.size() > 0) {\n        // Look at the first thing on the list\n        const StarTree* t = searchList[0];\n        searchList.erase(searchList.begin());\n        \n        if (hasVisibleStarsMagic(point, minLuminosity, blurRadius, t)) {\n            if (t->isLeaf()) {\n                octantsFound.push_back(t->nodeId());\n            } else {\n                for (int i = 0; i < 8; i++) {\n                    const StarTree* tmp =\n                        t->branch(static_cast<TreeDirection>(i));\n                    searchList.push_back(tmp);\n                }\n            }\n        }\n    }\n}\n} // namespace StarTree\n", "meta": {"hexsha": "c38c1e3e8a08b9a2d23ce40b3f0f370cea3bea8e", "size": 14529, "ext": "cc", "lang": "C++", "max_stars_repo_path": "server/startree.cc", "max_stars_repo_name": "j3camero/billion-stars", "max_stars_repo_head_hexsha": "5c9099c2f43ed285844ef429b3674ccab4415693", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-11-28T23:04:14.000Z", "max_stars_repo_stars_event_max_datetime": "2017-01-15T06:57:44.000Z", "max_issues_repo_path": "server/startree.cc", "max_issues_repo_name": "j3camero/galaxyatlas", "max_issues_repo_head_hexsha": "5c9099c2f43ed285844ef429b3674ccab4415693", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "server/startree.cc", "max_forks_repo_name": "j3camero/galaxyatlas", "max_forks_repo_head_hexsha": "5c9099c2f43ed285844ef429b3674ccab4415693", "max_forks_repo_licenses": ["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.3503649635, "max_line_length": 74, "alphanum_fraction": 0.5480762613, "num_tokens": 3644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402812, "lm_q2_score": 0.5544704649604274, "lm_q1q2_score": 0.46443553502463264}}
{"text": "// -*- mode: c++; c-basic-offset: 4; indent-tabs-mode: nil -*-\n\n#include <cmath>\n#include <algorithm>\n#include <vector>\n#include <boost/assign/std/vector.hpp>\n#include \"lin_time.h\" // GetElapsedTime\n#include \"cmd/unit_generic.h\"\n#include \"cmd/unit_util.h\"\n#include \"gfxlib.h\"\n#include \"gfx/quaternion.h\"\n#include \"viewarea.h\"\n#include \"plane_display.h\"\n\nnamespace\n{\n\nfloat Degree2Radian(float angle)\n{\n  const float ratio = M_PI / 180.0;\n  return angle * ratio;\n}\n\nfloat GetDangerRate(Radar::Sensor::ThreatLevel::Value threat)\n{\n    using namespace Radar;\n\n    switch (threat)\n    {\n    case Sensor::ThreatLevel::High:\n        return 20.0; // Fast pulsation\n\n    case Sensor::ThreatLevel::Medium:\n        return 7.5; // Slow pulsation\n\n    default:\n        return 0.0; // No pulsation\n    }\n}\n\n} // anonymous namespace\n\nnamespace Radar\n{\n\nPlaneDisplay::PlaneDisplay()\n    : finalCameraAngle(Degree2Radian(30), Degree2Radian(0), Degree2Radian(0)),\n      currentCameraAngle(finalCameraAngle),\n      radarTime(0.0),\n      lastAnimationTime(0.0)\n{\n    using namespace boost::assign; // vector::operator+=\n\n    CalculateRotation();\n\n    // Calculate ground plane\n    const float edges = 32;\n    const float full = 2 * M_PI;\n    const float step = full / edges;\n    for (float angle = 0.0; angle < full; angle += step)\n    {\n        groundPlane.push_back(Vector(cosf(angle), 0.0f, sinf(angle)));\n    }\n\n    // Sequences start in 1 and ends in 0\n    nothingSequence += 0.0;\n    bounceSequence += 1.0, 0.9999, 0.9991, 0.9964, 0.9900, 0.9775, 0.9559, 0.9216, 0.8704, 0.7975, 0.6975, 0.5644, 0.3916, 0.1719, 0.0, 0.1287, 0.2164, 0.2535, 0.2297, 0.1343, 0.0, 0.0660, 0.0405, 0.0, 0.0341, 0.0;\n    cosineSequence += 1.0, 0.999391, 0.997564, 0.994522, 0.990268, 0.984808, 0.978148, 0.970296, 0.961262, 0.951057, 0.939693, 0.927184, 0.913545, 0.898794, 0.882948, 0.866025, 0.848048, 0.829038, 0.809017, 0.788011, 0.766044, 0.743145, 0.71934, 0.694658, 0.669131, 0.642788, 0.615662, 0.587785, 0.559193, 0.529919, 0.5, 0.469472, 0.438371, 0.406737, 0.374607, 0.34202, 0.309017, 0.275637, 0.241922, 0.207911, 0.173648, 0.139173, 0.104528, 0.069756, 0.034899, 0.0;\n}\n\nvoid PlaneDisplay::CalculateRotation()\n{\n    const float cosx = cosf(currentCameraAngle.x);\n    const float cosy = cosf(currentCameraAngle.y);\n    const float cosz = cosf(currentCameraAngle.z);\n    const float sinx = sinf(currentCameraAngle.x);\n    const float siny = sinf(currentCameraAngle.y);\n    const float sinz = sinf(currentCameraAngle.z);\n\n    xrotation = Vector(cosy * cosz,\n                       sinx * siny * cosz - cosx * sinz,\n                       cosx * siny * cosz + sinx * sinz);\n    yrotation = Vector(cosy * sinz,\n                       cosx * cosz + sinx * siny * sinz,\n                       cosx * siny * sinz - sinx * cosz);\n    zrotation = Vector(-siny,\n                       sinx * cosy,\n                       cosx * cosy);\n}\n\nvoid PlaneDisplay::PrepareAnimation(const Vector& fromAngle,\n                                    const Vector& toAngle,\n                                    const AngleSequence& xsequence,\n                                    const AngleSequence& ysequence,\n                                    const AngleSequence& zsequence)\n{\n    AnimationItem firstItem;\n    firstItem.duration = 0.0;\n    firstItem.position = fromAngle;\n    animation.push(firstItem);\n\n    float duration = 2.0;\n\n    // Use the longest-running sequence and zero-pad shorter sequuences\n    AngleSequence::size_type longestSequenceSize = xsequence.size();\n    longestSequenceSize = std::max(longestSequenceSize, ysequence.size());\n    longestSequenceSize = std::max(longestSequenceSize, zsequence.size());\n    for (AngleSequence::size_type i = 0; i < longestSequenceSize; ++i)\n    {\n        float xentry = (i < xsequence.size()) ? xsequence[i] : 0.0;\n        float yentry = (i < ysequence.size()) ? ysequence[i] : 0.0;\n        float zentry = (i < zsequence.size()) ? zsequence[i] : 0.0;\n        float xangle = toAngle.x + xentry * (fromAngle.x - toAngle.x);\n        float yangle = toAngle.y + yentry * (fromAngle.y - toAngle.y);\n        float zangle = toAngle.z + zentry * (fromAngle.z - toAngle.z);\n        AnimationItem item;\n        item.duration = duration;\n        item.position = Vector(xangle, yangle, zangle);\n        animation.push(item);\n        duration = 0.05;\n    }\n\n    AnimationItem finalItem;\n    finalItem.duration = duration;\n    finalItem.position = toAngle;\n    animation.push(finalItem);\n}\n\nvoid PlaneDisplay::OnDockEnd()\n{\n    // Bounce from upright position\n    Vector undockCameraAngle(Degree2Radian(90), finalCameraAngle.y, finalCameraAngle.z);\n    PrepareAnimation(undockCameraAngle, finalCameraAngle, bounceSequence, nothingSequence, nothingSequence);\n}\n\nvoid PlaneDisplay::OnJumpEnd()\n{\n    // Full rotation around y-axis\n    Vector jumpCameraAngle(finalCameraAngle.x, Degree2Radian(360), finalCameraAngle.z);\n    PrepareAnimation(jumpCameraAngle, finalCameraAngle, nothingSequence, cosineSequence, nothingSequence);\n}\n\nvoid PlaneDisplay::Draw(const Sensor& sensor,\n                        VSSprite *nearSprite,\n                        VSSprite *distantSprite)\n{\n    assert(nearSprite || distantSprite); // There should be at least one radar display\n\n    radarTime += GetElapsedTime();\n\n    leftRadar.SetSprite(nearSprite);\n    rightRadar.SetSprite(distantSprite);\n\n    if (nearSprite)\n        nearSprite->Draw();\n    if (distantSprite)\n        distantSprite->Draw();\n\n    Sensor::TrackCollection tracks = sensor.FindTracksInRange();\n\n    Animate();\n\n    GFXEnable(DEPTHTEST);\n    GFXEnable(DEPTHWRITE);\n    GFXEnable(SMOOTH);\n\n    DrawNear(sensor, tracks);\n    DrawDistant(sensor, tracks);\n\n    GFXPointSize(1);\n    GFXDisable(DEPTHTEST);\n    GFXDisable(DEPTHWRITE);\n    GFXDisable(SMOOTH);\n}\n\nvoid PlaneDisplay::Animate()\n{\n    if (!animation.empty())\n    {\n        if (radarTime > lastAnimationTime + animation.front().duration)\n        {\n            currentCameraAngle = animation.front().position;\n            CalculateRotation();\n            animation.pop();\n            lastAnimationTime = radarTime;\n        }\n    }\n}\n\nVector PlaneDisplay::Projection(const ViewArea& radarView, const Vector& position)\n{\n    // 1. Rotate\n    float rx = position.Dot(xrotation);\n    float ry = position.Dot(yrotation);\n    float rz = position.Dot(zrotation);\n\n    // 2. Project perspective\n    // Using the symmetric viewing volume where right = -left and top = -bottom\n    // gives us this perspective projection matrix\n    //   n/r           0             0             0\n    //   0             n/t           0             0\n    //   0             0             -(f+n)/(f-n)  -2fn/(f-n)\n    //   0             0             -1            0\n    // location = M_perspective * rotatedPosition\n    const float nearDistance = -0.5; // -0.25 => zoom out, -0.75 => zoom in\n    const float farDistance = 0.5;\n    const float top = 0.5;\n    const float right = 0.5;\n    float x = rx * (nearDistance / right);\n    float y = ry * (nearDistance / top);\n    float z = (rz * (- (farDistance + nearDistance) / (farDistance - nearDistance)) - 2.0 * farDistance * nearDistance / (farDistance - nearDistance));\n\n    // 3. Scale onto radarView\n    return radarView.Scale(Vector(x, y, z));\n}\n\nvoid PlaneDisplay::DrawGround(const Sensor& sensor, const ViewArea& radarView)\n{\n    GFXColor groundColor = radarView.GetColor();\n    const float outer = 3.0 / 3.0;\n    const float middle = 2.0 / 3.0;\n    const float inner = 1.0 / 3.0;\n\n    groundColor.a = 0.1;\n    GFXColorf(groundColor);\n    GFXLineWidth(0.5);\n    GFXBegin(GFXPOLY);\n    for (std::vector<Vector>::const_iterator it = groundPlane.begin(); it != groundPlane.end(); ++it)\n    {\n        GFXVertexf(Projection(radarView, outer * (*it)));\n    }\n    GFXEnd();\n\n    groundColor.a = 0.4;\n    GFXColorf(groundColor);\n    GFXBegin(GFXLINESTRIP);\n    for (std::vector<Vector>::const_iterator it = groundPlane.begin(); it != groundPlane.end(); ++it)\n    {\n        GFXVertexf(Projection(radarView, middle * (*it)));\n    }\n    GFXVertexf(Projection(radarView, middle * groundPlane.front()));\n    GFXEnd();\n\n    GFXBegin(GFXLINESTRIP);\n    for (std::vector<Vector>::const_iterator it = groundPlane.begin(); it != groundPlane.end(); ++it)\n    {\n        GFXVertexf(Projection(radarView, inner * (*it)));\n    }\n    GFXVertexf(Projection(radarView, inner * groundPlane.front()));\n    GFXEnd();\n\n    groundColor.a = 0.4;\n    const float xcone = cosf(sensor.GetLockCone());\n    const float zcone = sinf(sensor.GetLockCone());\n    const float innerCone = inner;\n    const float outerCone = outer;\n    Vector leftCone(xcone, 0.0f, zcone);\n    Vector rightCone(-xcone, 0.0f, zcone);\n    GFXColorf(groundColor);\n    GFXBegin(GFXLINE);\n    GFXVertexf(Projection(radarView, outerCone * leftCone));\n    GFXVertexf(Projection(radarView, innerCone * leftCone));\n    GFXVertexf(Projection(radarView, outerCone * rightCone));\n    GFXVertexf(Projection(radarView, innerCone * rightCone));\n    GFXEnd();\n    GFXLineWidth(1);\n}\n\nvoid PlaneDisplay::DrawNear(const Sensor& sensor,\n                            const Sensor::TrackCollection& tracks)\n{\n    // Draw all near tracks (distance scaled)\n\n    if (!leftRadar.IsActive())\n        return;\n\n    float maxRange = sensor.GetCloseRange();\n\n    DrawGround(sensor, leftRadar);\n\n    for (Sensor::TrackCollection::const_iterator it = tracks.begin(); it != tracks.end(); ++it)\n    {\n        if (it->GetDistance() > maxRange)\n            continue;\n\n        DrawTrack(sensor, leftRadar, *it, maxRange);\n    }\n}\n\nvoid PlaneDisplay::DrawDistant(const Sensor& sensor,\n                               const Sensor::TrackCollection& tracks)\n{\n    // Draw all near tracks (distance scaled)\n\n    if (!rightRadar.IsActive())\n        return;\n\n    float minRange = sensor.GetCloseRange();\n    float maxRange = sensor.GetMaxRange();\n\n    DrawGround(sensor, rightRadar);\n\n    for (Sensor::TrackCollection::const_iterator it = tracks.begin(); it != tracks.end(); ++it)\n    {\n        if ((it->GetDistance() < minRange) || (it->GetDistance() > maxRange))\n            continue;\n\n        DrawTrack(sensor, rightRadar, *it, maxRange);\n    }\n}\n\nvoid PlaneDisplay::DrawTrack(const Sensor& sensor,\n                             const ViewArea& radarView,\n                             const Track& track,\n                             float maxRange)\n{\n    const Track::Type::Value unitType = track.GetType();\n    GFXColor color = sensor.GetColor(track);\n\n    Vector position = track.GetPosition();\n    Vector scaledPosition = Vector(position.x, -position.y, position.z) / maxRange;\n    if (scaledPosition.Magnitude() > 1.0)\n        return;\n\n    // FIXME: Integrate radar into damage/repair system\n    // FIXME: Jitter does not work when entering a nebula\n    // FIXME: Jitter does not work close by\n    if (sensor.InsideNebula())\n    {\n        Jitter(0.0, 0.01, scaledPosition);\n    }\n    else\n    {\n        const bool isNebula = (track.GetType() == Track::Type::Nebula);\n        const bool isEcmActive = track.HasActiveECM();\n        if (isNebula || isEcmActive)\n        {\n            const float errorOffset = (scaledPosition.x > 0.0 ? 0.01 : -0.01);\n            const float errorRange = 0.03;\n            Jitter(errorOffset, errorRange, scaledPosition);\n        }\n    }\n\n    Vector head = Projection(radarView, scaledPosition);\n\n    Vector scaledGround(scaledPosition.x, 0, scaledPosition.z);\n    Vector ground = Projection(radarView, scaledGround);\n\n    const bool isBelowGround = (scaledPosition.y > 0); // Y has been inverted\n\n    // Tracks below ground are muted\n    if (isBelowGround)\n        color.a /= 3;\n    // and so is cargo\n    if (track.GetType() == Track::Type::Cargo)\n        color.a /= 4;\n\n    if (sensor.UseThreatAssessment())\n    {\n        float dangerRate = GetDangerRate(sensor.IdentifyThreat(track));\n        if (dangerRate > 0.0)\n        {\n            // Blinking track\n            color.a *= cosf(dangerRate * radarTime);\n        }\n    }\n\n    // Fade out dying ships\n    if (track.IsExploding())\n    {\n        color.a *= (1.0 - track.ExplodingProgress());\n    }\n\n    float trackSize = std::max(1.0f, std::log10(track.GetSize()));\n    if (track.GetType() != Track::Type::Cargo)\n        trackSize += 1.0;\n\n    DrawTarget(unitType, head, ground, trackSize, color);\n\n    if (sensor.IsTracking(track))\n    {\n        Vector center = Projection(radarView, Vector(0, 0, 0));\n        DrawTargetMarker(head, ground, center, trackSize, color, sensor.UseObjectRecognition());\n    }\n}\n\nvoid PlaneDisplay::DrawTarget(Track::Type::Value unitType,\n                              const Vector& head,\n                              const Vector& ground,\n                              float trackSize,\n                              const GFXColor& color)\n{\n    // Draw leg\n    GFXColor legColor = color;\n    legColor.a /= 2;\n    GFXLineWidth(0.2);\n    GFXColorf(legColor);\n    GFXBegin(GFXLINE);\n    GFXVertexf(head);\n    GFXVertexf(ground);\n    GFXEnd();\n\n    // Draw head\n    GFXColorf(color);\n    GFXPointSize(trackSize);\n    GFXBegin(GFXPOINT);\n    GFXVertexf(head);\n    GFXEnd();\n}\n\nvoid PlaneDisplay::DrawTargetMarker(const Vector& head,\n                                    const Vector& ground,\n                                    const Vector& center,\n                                    float trackSize,\n                                    const GFXColor& color,\n                                    bool drawArea)\n{\n    if (drawArea)\n    {\n        GFXColor areaColor = color;\n        areaColor.a /= 4;\n        GFXColorf(areaColor);\n        GFXBegin(GFXPOLY);\n        GFXVertexf(head);\n        GFXVertexf(ground);\n        GFXVertexf(center);\n        GFXEnd();\n    }\n\n    // Diamond\n    float size = 6.0 * std::max(trackSize, 1.0f);\n    float xsize = size / g_game.x_resolution;\n    float ysize = size / g_game.y_resolution;\n\n    GFXColorf(color);\n    GFXLineWidth(1);\n    GFXBegin(GFXLINESTRIP);\n    GFXVertex3f(head.x - xsize, head.y, 0.0f);\n    GFXVertex3f(head.x, head.y - ysize, 0.0f);\n    GFXVertex3f(head.x + xsize, head.y, 0.0f);\n    GFXVertex3f(head.x, head.y + ysize, 0.0f);\n    GFXVertex3f(head.x - xsize, head.y, 0.0f);\n    GFXEnd();\n}\n\n} // namespace Radar\n", "meta": {"hexsha": "83eb67e8d7148fc712cc20e98d5f870145ba266e", "size": 14196, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "vegastrike/src/gfx/radar/plane_display.cpp", "max_stars_repo_name": "Ezeer/VegaStrike_win32FR", "max_stars_repo_head_hexsha": "75891b9ccbdb95e48e15d3b4a9cd977955b97d1f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "vegastrike/src/gfx/radar/plane_display.cpp", "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/src/gfx/radar/plane_display.cpp", "max_forks_repo_name": "Ezeer/VegaStrike_win32FR", "max_forks_repo_head_hexsha": "75891b9ccbdb95e48e15d3b4a9cd977955b97d1f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.7583892617, "max_line_length": 464, "alphanum_fraction": 0.6092561285, "num_tokens": 3858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.46443552603445704}}
{"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#include <opengv/relative_pose/methods.hpp>\n#include <opengv/Indices.hpp>\n\n#include <Eigen/NonLinearOptimization>\n#include <Eigen/NumericalDiff>\n\n#include <opengv/OptimizationFunctor.hpp>\n#include <opengv/math/arun.hpp>\n#include <opengv/math/cayley.hpp>\n#include <opengv/relative_pose/modules/main.hpp>\n#include <opengv/triangulation/methods.hpp>\n\n#include <cmath>\n#include <iostream>\n\nopengv::translation_t\nopengv::relative_pose::twopt(\n    const RelativeAdapterBase & adapter,\n    bool unrotate,\n    const std::vector<int> & indices )\n{\n  assert(indices.size()>1);\n  return twopt( adapter, unrotate, indices[0], indices[1] );\n};\n\nopengv::translation_t\nopengv::relative_pose::twopt(\n    const RelativeAdapterBase & adapter,\n    bool unrotate,\n    size_t index0,\n    size_t index1 )\n{\n  bearingVector_t f1 = adapter.getBearingVector1(index0);\n  bearingVector_t f1prime = adapter.getBearingVector2(index0);\n  bearingVector_t f2 = adapter.getBearingVector1(index1);\n  bearingVector_t f2prime = adapter.getBearingVector2(index1);\n\n  if(unrotate)\n  {\n    rotation_t R12 = adapter.getR12();\n    f1prime = R12 * f1prime;\n    f2prime = R12 * f2prime;\n  }\n\n  Eigen::Vector3d normal1 = f1.cross(f1prime);\n  Eigen::Vector3d normal2 = f2.cross(f2prime);\n\n  translation_t translation = normal1.cross(normal2);\n  translation = translation/translation.norm();\n\n  Eigen::Vector3d opticalFlow = f1 - f1prime;\n  if( opticalFlow.dot(translation) < 0 )\n    translation = -translation;\n\n  return translation;\n};\n\nopengv::rotation_t\nopengv::relative_pose::twopt_rotationOnly(\n    const RelativeAdapterBase & adapter,\n    const std::vector<int> & indices )\n{\n  assert(indices.size() > 1);\n  return twopt_rotationOnly( adapter, indices[0], indices[1] );\n};\n\nopengv::rotation_t\nopengv::relative_pose::twopt_rotationOnly(\n    const RelativeAdapterBase & adapter,\n    size_t index0,\n    size_t index1)\n{\n  Eigen::Vector3d pointsCenter1 =\n      adapter.getBearingVector1(index0) + adapter.getBearingVector1(index1);\n  Eigen::Vector3d pointsCenter2 =\n      adapter.getBearingVector2(index0) + adapter.getBearingVector2(index1);\n  pointsCenter1 = pointsCenter1/3.0;\n  pointsCenter2 = pointsCenter2/3.0;\n\n  Eigen::MatrixXd Hcross(3,3);\n  Hcross = Eigen::Matrix3d::Zero();\n\n  Eigen::Vector3d f = adapter.getBearingVector1(index0) - pointsCenter1;\n  Eigen::Vector3d fprime = adapter.getBearingVector2(index0) - pointsCenter2;\n  Hcross += fprime * f.transpose();\n  f = adapter.getBearingVector1(index1) - pointsCenter1;\n  fprime = adapter.getBearingVector2(index1) - pointsCenter2;\n  Hcross += fprime * f.transpose();\n\n  return math::arun(Hcross);\n};\n\nnamespace opengv\n{\nnamespace relative_pose\n{\n\nrotation_t rotationOnly(\n    const RelativeAdapterBase & adapter,\n    const Indices & indices )\n{\n  size_t numberCorrespondences = indices.size();\n  assert(numberCorrespondences > 2);\n\n  Eigen::Vector3d pointsCenter1 = Eigen::Vector3d::Zero();\n  Eigen::Vector3d pointsCenter2 = Eigen::Vector3d::Zero();\n\n  for( size_t i = 0; i < numberCorrespondences; i++ )\n  {\n    pointsCenter1 += adapter.getBearingVector1(indices[i]);\n    pointsCenter2 += adapter.getBearingVector2(indices[i]);\n  }\n\n  pointsCenter1 = pointsCenter1 / numberCorrespondences;\n  pointsCenter2 = pointsCenter2 / numberCorrespondences;\n\n  Eigen::MatrixXd Hcross(3,3);\n  Hcross = Eigen::Matrix3d::Zero();\n\n  for( size_t i = 0; i < numberCorrespondences; i++ )\n  {\n    Eigen::Vector3d f = adapter.getBearingVector1(indices[i]) - pointsCenter1;\n    Eigen::Vector3d fprime =\n        adapter.getBearingVector2(indices[i]) - pointsCenter2;\n    Hcross += fprime * f.transpose();\n  }\n\n  return math::arun(Hcross);\n};\n\n}\n}\n\nopengv::rotation_t\nopengv::relative_pose::rotationOnly( const RelativeAdapterBase & adapter )\n{\n  Indices idx(adapter.getNumberCorrespondences());\n  return rotationOnly(adapter,idx);\n};\n\nopengv::rotation_t\nopengv::relative_pose::rotationOnly(\n    const RelativeAdapterBase & adapter,\n    const std::vector<int> & indices )\n{\n  Indices idx(indices);\n  return rotationOnly(adapter,idx);\n};\n\nnamespace opengv\n{\nnamespace relative_pose\n{\n\ncomplexEssentials_t fivept_stewenius(\n    const RelativeAdapterBase & adapter,\n    const Indices & indices )\n{\n  size_t numberCorrespondences = indices.size();\n  assert(numberCorrespondences > 4);\n\n  Eigen::MatrixXd Q(numberCorrespondences,9);\n  for( size_t i = 0; i < numberCorrespondences; i++ )\n  {\n    //bearingVector_t f = adapter.getBearingVector1(indices[i]);\n    //bearingVector_t fprime = adapter.getBearingVector2(indices[i]);\n    //Stewenius' algorithm is computing the inverse transformation, so we simply\n    //invert the input here\n    bearingVector_t f = adapter.getBearingVector2(indices[i]);\n    bearingVector_t fprime = adapter.getBearingVector1(indices[i]);\n    Eigen::Matrix<double,1,9> row;\n    row <<  f[0]*fprime[0], f[1]*fprime[0], f[2]*fprime[0],\n        f[0]*fprime[1], f[1]*fprime[1], f[2]*fprime[1],\n        f[0]*fprime[2], f[1]*fprime[2], f[2]*fprime[2];\n    Q.row(i) = row;\n  }\n\n  Eigen::JacobiSVD< Eigen::MatrixXd > SVD(Q, Eigen::ComputeFullV );\n  Eigen::Matrix<double,9,4> EE = SVD.matrixV().block(0,5,9,4);\n  complexEssentials_t complexEssentials;\n  modules::fivept_stewenius_main(EE,complexEssentials);\n  return complexEssentials;\n};\n\n}\n}\n\nopengv::complexEssentials_t\nopengv::relative_pose::fivept_stewenius( const RelativeAdapterBase & adapter )\n{\n  Indices idx(adapter.getNumberCorrespondences());\n  return fivept_stewenius(adapter,idx);\n};\n\nopengv::complexEssentials_t\nopengv::relative_pose::fivept_stewenius(\n    const RelativeAdapterBase & adapter,\n    const std::vector<int> & indices )\n{\n  Indices idx(indices);\n  return fivept_stewenius(adapter,idx);\n};\n\nnamespace opengv\n{\nnamespace relative_pose\n{\n\nessentials_t fivept_nister(\n    const RelativeAdapterBase & adapter,\n    const Indices & indices )\n{\n  size_t numberCorrespondences = indices.size();\n  assert(numberCorrespondences > 4);\n\n  Eigen::MatrixXd Q(numberCorrespondences,9);\n  for( size_t i = 0; i < numberCorrespondences; i++ )\n  {\n    //bearingVector_t f = adapter.getBearingVector1(indices[i]);\n    //bearingVector_t fprime = adapter.getBearingVector2(indices[i]);\n    //Nister's algorithm is computing the inverse transformation, so we simply\n    //invert the input here\n    bearingVector_t f = adapter.getBearingVector2(indices[i]);\n    bearingVector_t fprime = adapter.getBearingVector1(indices[i]);\n    Eigen::Matrix<double,1,9> row;\n    row <<  f[0]*fprime[0], f[1]*fprime[0], f[2]*fprime[0],\n        f[0]*fprime[1], f[1]*fprime[1], f[2]*fprime[1],\n        f[0]*fprime[2], f[1]*fprime[2], f[2]*fprime[2];\n    Q.row(i) = row;\n  }\n\n  Eigen::JacobiSVD< Eigen::MatrixXd > SVD(Q, Eigen::ComputeFullV );\n  Eigen::Matrix<double,9,4> EE = SVD.matrixV().block(0,5,9,4);\n  essentials_t essentials;\n  modules::fivept_nister_main(EE,essentials);\n\n  return essentials;\n};\n\n}\n}\n\nopengv::essentials_t\nopengv::relative_pose::fivept_nister( const RelativeAdapterBase & adapter )\n{\n  Indices idx(adapter.getNumberCorrespondences());\n  return fivept_nister(adapter,idx);\n};\n\nopengv::essentials_t\nopengv::relative_pose::fivept_nister(\n    const RelativeAdapterBase & adapter,\n    const std::vector<int> & indices )\n{\n  Indices idx(indices);\n  return fivept_nister(adapter,idx);\n};\n\nopengv::rotations_t\nopengv::relative_pose::fivept_kneip(\n    const RelativeAdapterBase & adapter,\n    const std::vector<int> & indices )\n{\n  size_t numberCorrespondences = indices.size();\n  assert(numberCorrespondences == 5);\n\n  Eigen::Matrix<double,3,5> f1;\n  Eigen::Matrix<double,3,5> f2;\n\n  for(size_t i = 0; i < numberCorrespondences; i++)\n  {\n    f1.col(i) = adapter.getBearingVector1(indices[i]);\n    f2.col(i) = adapter.getBearingVector2(indices[i]);\n  }\n\n  rotations_t rotations;\n  modules::fivept_kneip_main( f1, f2, rotations );\n  return rotations;\n}\n\nnamespace opengv\n{\nnamespace relative_pose\n{\n\nessentials_t sevenpt(\n    const RelativeAdapterBase & adapter,\n    const Indices & indices )\n{\n  size_t numberCorrespondences = indices.size();\n  assert(numberCorrespondences > 6);\n\n  Eigen::MatrixXd A(numberCorrespondences,9);\n\n  for( size_t i = 0; i < numberCorrespondences; i++ )\n  {\n    //bearingVector_t f1 = adapter.getBearingVector1(indices[i]);\n    //bearingVector_t f2 = adapter.getBearingVector2(indices[i]);\n    //The seven-point is computing the inverse transformation, which is why we\n    //invert the input\n    bearingVector_t f1 = adapter.getBearingVector2(indices[i]);\n    bearingVector_t f2 = adapter.getBearingVector1(indices[i]);\n\n    A.block<1,3>(i,0) = f2[0] * f1.transpose();\n    A.block<1,3>(i,3) = f2[1] * f1.transpose();\n    A.block<1,3>(i,6) = f2[2] * f1.transpose();\n  }\n\n  Eigen::JacobiSVD< Eigen::MatrixXd > SVD(\n      A,\n      Eigen::ComputeFullU | Eigen::ComputeFullV );\n\n  Eigen::Matrix<double,9,1> f1 = SVD.matrixV().col(8);\n  Eigen::Matrix<double,9,1> f2 = SVD.matrixV().col(7);\n\n  Eigen::MatrixXd F1_temp(3,3);\n  F1_temp.col(0) = f1.block<3,1>(0,0);\n  F1_temp.col(1) = f1.block<3,1>(3,0);\n  F1_temp.col(2) = f1.block<3,1>(6,0);\n  essential_t F1 = F1_temp.transpose();\n\n  Eigen::MatrixXd F2_temp(3,3);\n  F2_temp.col(0) = f2.block<3,1>(0,0);\n  F2_temp.col(1) = f2.block<3,1>(3,0);\n  F2_temp.col(2) = f2.block<3,1>(6,0);\n  essential_t F2 = F2_temp.transpose();\n\n  double eps = 0.00000001;\n  essentials_t essentials;\n  \n  if( fabs(F1.determinant()) < eps || numberCorrespondences > 7 )\n  {\n    essentials.push_back(F1);\n  }\n  else\n  {\n    essential_t M = F2.inverse() * F1;\n    Eigen::EigenSolver< essential_t > Eig(M,true);\n    Eigen::Matrix< std::complex<double>,3,1 > D = Eig.eigenvalues();\n\n    double val1 = fabs(D(0,0).imag());\n    double val2 = fabs(D(1,0).imag());\n    double val3 = fabs(D(2,0).imag());\n\n    if( val1 < eps && val2 < eps && val3 < eps )\n    {\n      essentials.push_back( F1 - D(0,0).real() * F2 );\n      essentials.push_back( F1 - D(1,0).real() * F2 );\n      essentials.push_back( F1 - D(2,0).real() * F2 );\n    }\n    else\n    {\n      double min = val1;\n      int minIndex = 0;\n      if( val2 < min )\n      {\n        min = val2;\n        minIndex = 1;\n      }\n      if( val3 < min )\n        minIndex = 2;\n      \n      essentials.push_back( F1 - D(minIndex,0).real() * F2 );\n    }\n  }\n\n  return essentials;\n}\n\n}\n}\n\nopengv::essentials_t\nopengv::relative_pose::sevenpt( const RelativeAdapterBase & adapter )\n{\n  Indices idx(adapter.getNumberCorrespondences());\n  return sevenpt(adapter,idx);\n}\n\nopengv::essentials_t\nopengv::relative_pose::sevenpt(\n    const RelativeAdapterBase & adapter,\n    const std::vector<int> & indices )\n{\n  Indices idx(indices);\n  return sevenpt(adapter,idx);\n}\n\nnamespace opengv\n{\nnamespace relative_pose\n{\n\nessential_t eightpt(\n    const RelativeAdapterBase & adapter,\n    const Indices & indices )\n{\n  size_t numberCorrespondences = indices.size();\n  assert(numberCorrespondences > 7);\n\n  Eigen::MatrixXd A(numberCorrespondences,9);\n\n  for( size_t i = 0; i < numberCorrespondences; i++ )\n  {\n    //bearingVector_t f1 = adapter.getBearingVector1(indices[i]);\n    //bearingVector_t f2 = adapter.getBearingVector2(indices[i]);\n    //The eight-point essentially computes the inverse transformation, which is\n    //why we invert the input here\n    bearingVector_t f1 = adapter.getBearingVector2(indices[i]);\n    bearingVector_t f2 = adapter.getBearingVector1(indices[i]);\n\n    A.block<1,3>(i,0) = f2[0] * f1.transpose();\n    A.block<1,3>(i,3) = f2[1] * f1.transpose();\n    A.block<1,3>(i,6) = f2[2] * f1.transpose();\n  }\n\n  Eigen::JacobiSVD< Eigen::MatrixXd > SVD(\n      A,\n      Eigen::ComputeFullU | Eigen::ComputeFullV );\n  Eigen::Matrix<double,9,1> f = SVD.matrixV().col(8);\n\n  Eigen::MatrixXd F_temp(3,3);\n  F_temp.col(0) = f.block<3,1>(0,0);\n  F_temp.col(1) = f.block<3,1>(3,0);\n  F_temp.col(2) = f.block<3,1>(6,0);\n  essential_t F = F_temp.transpose();\n\n  Eigen::JacobiSVD< Eigen::MatrixXd > SVD2(\n      F,\n      Eigen::ComputeFullU | Eigen::ComputeFullV );\n  Eigen::Matrix3d S = Eigen::Matrix3d::Zero();\n  S(0,0) = SVD2.singularValues()[0];\n  S(1,1) = SVD2.singularValues()[1];\n\n  Eigen::Matrix3d U = SVD2.matrixU();\n  Eigen::Matrix3d Vtr = SVD2.matrixV().transpose();\n\n  essential_t essential = U * S * Vtr;\n  return essential;\n}\n\n}\n}\n\nopengv::essential_t\nopengv::relative_pose::eightpt( const RelativeAdapterBase & adapter )\n{\n  Indices idx(adapter.getNumberCorrespondences());\n  return eightpt(adapter,idx);\n}\n\nopengv::essential_t\nopengv::relative_pose::eightpt(\n    const RelativeAdapterBase & adapter,\n    const std::vector<int> & indices )\n{\n  Indices idx(indices);\n  return eightpt(adapter,idx);\n}\n\nnamespace opengv\n{\nnamespace relative_pose\n{\n\nrotation_t eigensolver(\n    const RelativeAdapterBase & adapter,\n    const Indices & indices,\n    eigensolverOutput_t & output,\n    bool useWeights )\n{\n  size_t numberCorrespondences = indices.size();\n  assert(numberCorrespondences > 4);\n\n  Eigen::Matrix3d xxF = Eigen::Matrix3d::Zero();\n  Eigen::Matrix3d yyF = Eigen::Matrix3d::Zero();\n  Eigen::Matrix3d zzF = Eigen::Matrix3d::Zero();\n  Eigen::Matrix3d xyF = Eigen::Matrix3d::Zero();\n  Eigen::Matrix3d yzF = Eigen::Matrix3d::Zero();\n  Eigen::Matrix3d zxF = Eigen::Matrix3d::Zero();\n\n  //compute the norm of all the scores\n  double norm = 0.0;\n  for(size_t i=0; i < numberCorrespondences; i++)\n    norm += pow(adapter.getWeight(indices[i]),2);\n  norm = sqrt(norm);\n\n  //Fill summation terms\n  for(size_t i=0; i < numberCorrespondences; i++)\n  {\n    bearingVector_t f1 = adapter.getBearingVector1(indices[i]);\n    bearingVector_t f2 = adapter.getBearingVector2(indices[i]);\n    Eigen::Matrix3d F = f2*f2.transpose();\n    \n    double weight = 1.0;\n    if( useWeights )\n      weight = adapter.getWeight(indices[i])/norm;\n\n    xxF = xxF + weight*f1[0]*f1[0]*F;\n    yyF = yyF + weight*f1[1]*f1[1]*F;\n    zzF = zzF + weight*f1[2]*f1[2]*F;\n    xyF = xyF + weight*f1[0]*f1[1]*F;\n    yzF = yzF + weight*f1[1]*f1[2]*F;\n    zxF = zxF + weight*f1[2]*f1[0]*F;\n  }\n\n  //Do minimization\n  modules::eigensolver_main(xxF,yyF,zzF,xyF,yzF,zxF,output);\n\n  //Correct the translation\n  bearingVector_t f1 = adapter.getBearingVector1(indices[0]);\n  bearingVector_t f2 = adapter.getBearingVector2(indices[0]);\n  f2 = output.rotation * f2;\n  Eigen::Vector3d opticalFlow = f1 - f2;\n  if( opticalFlow.dot(output.translation) < 0.0 )\n    output.translation = -output.translation;\n\n  return output.rotation;\n}\n\n}\n}\n\nopengv::rotation_t\nopengv::relative_pose::eigensolver(\n    const RelativeAdapterBase & adapter,\n    eigensolverOutput_t & output,\n    bool useWeights )\n{\n  Indices idx(adapter.getNumberCorrespondences());\n  return eigensolver(adapter,idx,output,useWeights);\n}\n\nopengv::rotation_t\nopengv::relative_pose::eigensolver(\n    const RelativeAdapterBase & adapter,\n    const std::vector<int> & indices,\n    eigensolverOutput_t & output,\n    bool useWeights )\n{\n  Indices idx(indices);\n  return eigensolver(adapter,idx,output,useWeights);\n}\n\nopengv::rotation_t\nopengv::relative_pose::eigensolver(\n    const RelativeAdapterBase & adapter,\n    bool useWeights )\n{\n  eigensolverOutput_t output;\n  output.rotation = adapter.getR12();\n  return eigensolver(adapter,output,useWeights);\n}\n\nopengv::rotation_t\nopengv::relative_pose::eigensolver(\n    const RelativeAdapterBase & adapter,\n    const std::vector<int> & indices,\n    bool useWeights )\n{\n  eigensolverOutput_t output;\n  output.rotation = adapter.getR12();\n  return eigensolver(adapter,indices,output,useWeights);\n}\n\nnamespace opengv\n{\nnamespace relative_pose\n{\n\nrotations_t sixpt(\n    const RelativeAdapterBase & adapter,\n    const Indices & indices )\n{\n  size_t numberCorrespondences = indices.size();\n  assert(numberCorrespondences == 6);\n\n  Eigen::Matrix<double,6,6> L1;\n  Eigen::Matrix<double,6,6> L2;\n\n  for(size_t i = 0; i < numberCorrespondences; i++)\n  {\n    bearingVector_t f1 =\n        adapter.getCamRotation1(indices[i]) * adapter.getBearingVector1(indices[i]);\n    bearingVector_t f2 =\n        adapter.getCamRotation2(indices[i]) * adapter.getBearingVector2(indices[i]);\n        \n    L1.block<3,1>(0,i) = f1;\n    L2.block<3,1>(0,i) = f2;\n    \n    L1.block<3,1>(3,i) = f1.cross(adapter.getCamOffset1(indices[i]));\n    L2.block<3,1>(3,i) = f2.cross(adapter.getCamOffset2(indices[i]));\n  }\n\n  rotations_t solutions;\n  modules::sixpt_main( L1, L2, solutions );  \n  return solutions;\n}\n\n}\n}\n\nopengv::rotations_t\nopengv::relative_pose::sixpt(\n    const RelativeAdapterBase & adapter )\n{\n  Indices idx(adapter.getNumberCorrespondences());\n  return sixpt(adapter,idx);\n}\n\nopengv::rotations_t\nopengv::relative_pose::sixpt(\n    const RelativeAdapterBase & adapter,\n    const std::vector<int> & indices )\n{\n  Indices idx(indices);\n  return sixpt(adapter,idx);\n}\n\nnamespace opengv\n{\nnamespace relative_pose\n{\n\ntransformation_t ge(\n    const RelativeAdapterBase & adapter,\n    const Indices & indices,\n    geOutput_t & output,\n    bool useWeights )\n{ \n  size_t numberCorrespondences = indices.size();\n  assert(numberCorrespondences > 5);\n\n  Eigen::Matrix3d xxF = Eigen::Matrix3d::Zero();\n  Eigen::Matrix3d yyF = Eigen::Matrix3d::Zero();\n  Eigen::Matrix3d zzF = Eigen::Matrix3d::Zero();\n  Eigen::Matrix3d xyF = Eigen::Matrix3d::Zero();\n  Eigen::Matrix3d yzF = Eigen::Matrix3d::Zero();\n  Eigen::Matrix3d zxF = Eigen::Matrix3d::Zero();\n  \n  Eigen::Matrix<double,3,9> x1P = Eigen::Matrix<double,3,9>::Zero();\n  Eigen::Matrix<double,3,9> y1P = Eigen::Matrix<double,3,9>::Zero();\n  Eigen::Matrix<double,3,9> z1P = Eigen::Matrix<double,3,9>::Zero();\n  Eigen::Matrix<double,3,9> x2P = Eigen::Matrix<double,3,9>::Zero();\n  Eigen::Matrix<double,3,9> y2P = Eigen::Matrix<double,3,9>::Zero();\n  Eigen::Matrix<double,3,9> z2P = Eigen::Matrix<double,3,9>::Zero();\n  \n  Eigen::Matrix<double,9,9> m11P = Eigen::Matrix<double,9,9>::Zero();\n  Eigen::Matrix<double,9,9> m12P = Eigen::Matrix<double,9,9>::Zero();\n  Eigen::Matrix<double,9,9> m22P = Eigen::Matrix<double,9,9>::Zero();\n\n  //compute the norm of all the scores\n  double norm = 0.0;\n  for(size_t i=0; i < numberCorrespondences; i++)\n    norm += pow(adapter.getWeight(indices[i]),2);\n  norm = sqrt(norm);\n\n  //Fill summation terms\n  for(size_t i=0; i < numberCorrespondences; i++)\n  {\n    //get the weight of this feature\n    double weight = 1.0;\n    if( useWeights )\n      weight = adapter.getWeight(indices[i])/norm;\n    \n    //unrotate the bearing vectors\n    bearingVector_t f1 = adapter.getCamRotation1(indices[i]) *\n        adapter.getBearingVector1(indices[i]);\n    bearingVector_t f2 = adapter.getCamRotation2(indices[i]) *\n        adapter.getBearingVector2(indices[i]);\n    \n    //compute the standard summation terms\n    Eigen::Matrix3d F = f2*f2.transpose();\n\n    xxF = xxF + weight*f1[0]*f1[0]*F;\n    yyF = yyF + weight*f1[1]*f1[1]*F;\n    zzF = zzF + weight*f1[2]*f1[2]*F;\n    xyF = xyF + weight*f1[0]*f1[1]*F;\n    yzF = yzF + weight*f1[1]*f1[2]*F;\n    zxF = zxF + weight*f1[2]*f1[0]*F;\n    \n    //now compute the \"cross\"-summation terms    \n    Eigen::Vector3d t1 = adapter.getCamOffset1(indices[i]);\n    Eigen::Vector3d t2 = adapter.getCamOffset2(indices[i]);\n    \n    Eigen::Matrix<double,1,9> f2_19;\n    double temp = f1[1]*t1[2]-f1[2]*t1[1];\n    f2_19(0,0) = f2[0] * temp;\n    f2_19(0,1) = f2[1] * temp;\n    f2_19(0,2) = f2[2] * temp;\n    temp = f1[2]*t1[0]-f1[0]*t1[2];\n    f2_19(0,3) = f2[0] * temp;\n    f2_19(0,4) = f2[1] * temp;\n    f2_19(0,5) = f2[2] * temp;\n    temp = f1[0]*t1[1]-f1[1]*t1[0];\n    f2_19(0,6) = f2[0] * temp;\n    f2_19(0,7) = f2[1] * temp;\n    f2_19(0,8) = f2[2] * temp;\n    \n    Eigen::Matrix<double,1,9> f1_19;\n    temp = f2[1]*t2[2]-f2[2]*t2[1];\n    f1_19(0,0) = f1[0] * temp;\n    f1_19(0,1) = f1[1] * temp;\n    f1_19(0,2) = f1[2] * temp;\n    temp = f2[2]*t2[0]-f2[0]*t2[2];\n    f1_19(0,3) = f1[0] * temp;\n    f1_19(0,4) = f1[1] * temp;\n    f1_19(0,5) = f1[2] * temp;\n    temp = f2[0]*t2[1]-f2[1]*t2[0];\n    f1_19(0,6) = f1[0] * temp;\n    f1_19(0,7) = f1[1] * temp;\n    f1_19(0,8) = f1[2] * temp;\n    \n    if( useWeights )\n    {\n      x1P = x1P + ( (weight * f1[0]) * f2 ) * f1_19;\n      y1P = y1P + ( (weight * f1[1]) * f2 ) * f1_19;\n      z1P = z1P + ( (weight * f1[2]) * f2 ) * f1_19;\n      \n      x2P = x2P + ( (weight * f1[0]) * f2 ) * f2_19;\n      y2P = y2P + ( (weight * f1[1]) * f2 ) * f2_19;\n      z2P = z2P + ( (weight * f1[2]) * f2 ) * f2_19;\n      \n      m11P = m11P - ( weight * f1_19.transpose() ) * f1_19;\n      m22P = m22P - ( weight * f2_19.transpose() ) * f2_19;\n      m12P = m12P - ( weight * f2_19.transpose() ) * f1_19;\n    }\n    else\n    {\n      x1P = x1P + ( f1[0] * f2 ) * f1_19;\n      y1P = y1P + ( f1[1] * f2 ) * f1_19;\n      z1P = z1P + ( f1[2] * f2 ) * f1_19;\n      \n      x2P = x2P + ( f1[0]) * f2 * f2_19;\n      y2P = y2P + ( f1[1]) * f2 * f2_19;\n      z2P = z2P + ( f1[2]) * f2 * f2_19;\n      \n      m11P = m11P - f1_19.transpose() * f1_19;\n      m22P = m22P - f2_19.transpose() * f2_19;\n      m12P = m12P - f2_19.transpose() * f1_19;\n    }\n  }\n\n  Eigen::Vector3d pointsCenter1 = Eigen::Vector3d::Zero();\n  Eigen::Vector3d pointsCenter2 = Eigen::Vector3d::Zero();\n\n  for( size_t i = 0; i < numberCorrespondences; i++ )\n  {\n    pointsCenter1 += adapter.getCamRotation1(indices[i]) *\n        adapter.getBearingVector1(indices[i]);\n    pointsCenter2 += adapter.getCamRotation2(indices[i]) *\n        adapter.getBearingVector2(indices[i]);\n  }\n\n  pointsCenter1 = pointsCenter1 / numberCorrespondences;\n  pointsCenter2 = pointsCenter2 / numberCorrespondences;\n\n  Eigen::MatrixXd Hcross(3,3);\n  Hcross = Eigen::Matrix3d::Zero();\n\n  for( size_t i = 0; i < numberCorrespondences; i++ )\n  {\n    Eigen::Vector3d f =      adapter.getCamRotation1(indices[i]) *\n        adapter.getBearingVector1(indices[i]) - pointsCenter1;\n    Eigen::Vector3d fprime = adapter.getCamRotation2(indices[i]) *\n        adapter.getBearingVector2(indices[i]) - pointsCenter2;\n    Hcross += fprime * f.transpose();\n  }\n\n  rotation_t startingRotation = math::arun(Hcross);\n\n  //Do minimization\n  modules::ge_main2(\n      xxF, yyF, zzF, xyF, yzF, zxF,\n      x1P, y1P, z1P, x2P, y2P, z2P,\n      m11P, m12P, m22P, math::rot2cayley(startingRotation), output);\n\n  //return output.rotation;\n  transformation_t transformation;\n  transformation.block<3,3>(0,0) = output.rotation;\n  transformation.col(3) = output.translation.block<3,1>(0,0);\n\n  return transformation;\n}\n\n}\n}\n\nopengv::transformation_t\nopengv::relative_pose::ge(\n    const RelativeAdapterBase & adapter,\n    geOutput_t & output,\n    bool useWeights )\n{\n  Indices idx(adapter.getNumberCorrespondences());\n  return ge(adapter,idx,output,useWeights);\n}\n\nopengv::transformation_t\nopengv::relative_pose::ge(\n    const RelativeAdapterBase & adapter,\n    const std::vector<int> & indices,\n    geOutput_t & output,\n    bool useWeights )\n{\n  Indices idx(indices);\n  return ge(adapter,idx,output,useWeights);\n}\n\nopengv::transformation_t\nopengv::relative_pose::ge( const RelativeAdapterBase & adapter, bool useWeights )\n{\n  geOutput_t output;\n  //output.rotation = adapter.getR12(); //finding starting value using arun\n  return ge(adapter,output,useWeights);\n}\n\nopengv::transformation_t\nopengv::relative_pose::ge(\n    const RelativeAdapterBase & adapter,\n    const std::vector<int> & indices,\n    bool useWeights )\n{\n  geOutput_t output;\n  //output.rotation = adapter.getR12(); //finding starting value using arun\n  return ge(adapter,indices,output,useWeights);\n}\n\nnamespace opengv\n{\nnamespace relative_pose\n{\n\ntransformation_t seventeenpt(\n    const RelativeAdapterBase & adapter,\n    const Indices & indices )\n{\n  size_t numberCorrespondences = indices.size();\n  assert(numberCorrespondences > 16);\n\n  Eigen::MatrixXd AE(numberCorrespondences,9);\n  Eigen::MatrixXd AR(numberCorrespondences,9);\n\n  for( size_t i = 0; i < numberCorrespondences; i++ )\n  {\n    bearingVector_t d1 = adapter.getBearingVector1(indices[i]);\n    bearingVector_t d2 = adapter.getBearingVector2(indices[i]);\n    translation_t v1 = adapter.getCamOffset1(indices[i]);\n    translation_t v2 = adapter.getCamOffset2(indices[i]);\n    rotation_t R1 = adapter.getCamRotation1(indices[i]);\n    rotation_t R2 = adapter.getCamRotation2(indices[i]);\n\n    //unrotate the bearing-vectors to express everything in the body frame\n    d1 = R1*d1;\n    d2 = R2*d2;\n\n    //generate the Pl\u00fccker line coordinates\n    Eigen::Matrix<double,6,1> l1;\n    l1.block<3,1>(0,0) = d1;\n    l1.block<3,1>(3,0) = v1.cross(d1);\n    Eigen::Matrix<double,6,1> l2;\n    l2.block<3,1>(0,0) = d2;\n    l2.block<3,1>(3,0) = v2.cross(d2);\n\n    //fill line of matrix A\n    AE(i,0) = l2[0]*l1[0];\n    AE(i,1) = l2[0]*l1[1];\n    AE(i,2) = l2[0]*l1[2];\n    AE(i,3) = l2[1]*l1[0];\n    AE(i,4) = l2[1]*l1[1];\n    AE(i,5) = l2[1]*l1[2];\n    AE(i,6) = l2[2]*l1[0];\n    AE(i,7) = l2[2]*l1[1];\n    AE(i,8) = l2[2]*l1[2];\n\n    AR(i,0) = l2[0]*l1[3]+l2[3]*l1[0];\n    AR(i,1) = l2[0]*l1[4]+l2[3]*l1[1];\n    AR(i,2) = l2[0]*l1[5]+l2[3]*l1[2];\n    AR(i,3) = l2[1]*l1[3]+l2[4]*l1[0];\n    AR(i,4) = l2[1]*l1[4]+l2[4]*l1[1];\n    AR(i,5) = l2[1]*l1[5]+l2[4]*l1[2];\n    AR(i,6) = l2[2]*l1[3]+l2[5]*l1[0];\n    AR(i,7) = l2[2]*l1[4]+l2[5]*l1[1];\n    AR(i,8) = l2[2]*l1[5]+l2[5]*l1[2];\n  }\n\n  Eigen::JacobiSVD< Eigen::MatrixXd > SVDARP(\n      AR,\n      Eigen::ComputeThinU | Eigen::ComputeThinV );\n\n  Eigen::VectorXd sigma_ = SVDARP.singularValues();\n  double pinvtoler_ =\n      sigma_(0)*numberCorrespondences*NumTraits<double>::epsilon();\n  Eigen::MatrixXd SigmaInverse_(9,9);\n  SigmaInverse_ = Eigen::MatrixXd::Zero(9,9);\n  for ( size_t i=0; i < 9; ++i)\n  {\n    double temp = sigma_(i);\n    if( temp > pinvtoler_ )\n      SigmaInverse_(i,i) = 1.0/temp;\n  }\n  \n  Eigen::MatrixXd ARP(9,numberCorrespondences);\n  ARP = SVDARP.matrixV()*SigmaInverse_*SVDARP.matrixU().transpose();\n\n  Eigen::MatrixXd B(numberCorrespondences,numberCorrespondences);\n  B = -Eigen::MatrixXd::Identity(numberCorrespondences,numberCorrespondences);\n  B = B + AR*ARP;\n\n  Eigen::MatrixXd C = B*AE;\n  \n  Eigen::JacobiSVD< Eigen::MatrixXd > SVDE(\n      C,\n      Eigen::ComputeThinU | Eigen::ComputeThinV );\n  Eigen::Matrix<double,9,1> e = SVDE.matrixV().col(8);\n\n  Eigen::MatrixXd E_temp(3,3);\n  E_temp.col(0) = e.block<3,1>(0,0);\n  E_temp.col(1) = e.block<3,1>(3,0);\n  E_temp.col(2) = e.block<3,1>(6,0);\n  essential_t E = E_temp.transpose();\n\n  Eigen::JacobiSVD< Eigen::MatrixXd > SVDR(\n      E,\n      Eigen::ComputeFullV | Eigen::ComputeFullU );\n\n  Eigen::Matrix3d W = Eigen::Matrix3d::Zero();\n  W(0,1) = -1.0;\n  W(1,0) = 1.0;\n  W(2,2) = 1.0;\n\n  // get possible rotation and translation vectors\n  rotation_t Ra = SVDR.matrixU() * W * SVDR.matrixV().transpose();\n  rotation_t Rb = SVDR.matrixU() * W.transpose() * SVDR.matrixV().transpose();\n\n  // change sign if det = -1\n  if( Ra.determinant() < 0 ) Ra = -Ra;\n  if( Rb.determinant() < 0 ) Rb = -Rb;\n\n  Ra.transposeInPlace();\n  Rb.transposeInPlace();\n\n  Eigen::MatrixXd A_tra(numberCorrespondences,3);\n  Eigen::MatrixXd A_trb(numberCorrespondences,3);\n  Eigen::VectorXd b_tra(numberCorrespondences);\n  Eigen::VectorXd b_trb(numberCorrespondences);\n\n  for( size_t i = 0; i < numberCorrespondences; i++ )\n  {\n    bearingVector_t d1 = adapter.getBearingVector1(indices[i]);\n    bearingVector_t d2 = adapter.getBearingVector2(indices[i]);\n    translation_t v1 = adapter.getCamOffset1(indices[i]);\n    translation_t v2 = adapter.getCamOffset2(indices[i]);\n    rotation_t R1 = adapter.getCamRotation1(indices[i]);\n    rotation_t R2 = adapter.getCamRotation2(indices[i]);\n\n    //unrotate the bearing-vectors to express everything in the body frame\n    d1 = R1*d1;\n    d2 = R2*d2;\n\n    A_tra(i,0) = d1[2]*d2[0]*Ra(1,0)+d1[2]*d2[1]*Ra(1,1)+d1[2]*d2[2]*Ra(1,2)\n                -d1[1]*d2[0]*Ra(2,0)-d1[1]*d2[1]*Ra(2,1)-d1[1]*d2[2]*Ra(2,2);\n    A_tra(i,1) = d1[0]*d2[0]*Ra(2,0)+d1[0]*d2[1]*Ra(2,1)+d1[0]*d2[2]*Ra(2,2)\n                -d1[2]*d2[0]*Ra(0,0)-d1[2]*d2[1]*Ra(0,1)-d1[2]*d2[2]*Ra(0,2);\n    A_tra(i,2) = d1[1]*d2[0]*Ra(0,0)+d1[1]*d2[1]*Ra(0,1)+d1[1]*d2[2]*Ra(0,2)\n                -d1[0]*d2[0]*Ra(1,0)-d1[0]*d2[1]*Ra(1,1)-d1[0]*d2[2]*Ra(1,2);\n\n    A_trb(i,0) = d1[2]*d2[0]*Rb(1,0)+d1[2]*d2[1]*Rb(1,1)+d1[2]*d2[2]*Rb(1,2)\n                -d1[1]*d2[0]*Rb(2,0)-d1[1]*d2[1]*Rb(2,1)-d1[1]*d2[2]*Rb(2,2);\n    A_trb(i,1) = d1[0]*d2[0]*Rb(2,0)+d1[0]*d2[1]*Rb(2,1)+d1[0]*d2[2]*Rb(2,2)\n                -d1[2]*d2[0]*Rb(0,0)-d1[2]*d2[1]*Rb(0,1)-d1[2]*d2[2]*Rb(0,2);\n    A_trb(i,2) = d1[1]*d2[0]*Rb(0,0)+d1[1]*d2[1]*Rb(0,1)+d1[1]*d2[2]*Rb(0,2)\n                -d1[0]*d2[0]*Rb(1,0)-d1[0]*d2[1]*Rb(1,1)-d1[0]*d2[2]*Rb(1,2);\n\n    Eigen::Vector3d temp1 = v1.cross(d1);\n    Eigen::Vector3d temp2 = v2.cross(d2);\n    b_tra(i) = -d1.dot(Ra*temp2) -temp1.dot(Ra*d2);\n    b_trb(i) = -d1.dot(Rb*temp2) -temp1.dot(Rb*d2);\n  }\n  \n  Eigen::JacobiSVD< Eigen::MatrixXd > SVDa(\n      A_tra,\n      Eigen::ComputeThinU | Eigen::ComputeThinV );\n\n  Eigen::VectorXd sigma = SVDa.singularValues();\n  double pinvtoler =\n      numberCorrespondences*sigma(0)*NumTraits<double>::epsilon();\n  Eigen::MatrixXd SigmaInverse(3,3);\n  SigmaInverse = Eigen::MatrixXd::Zero(3,3);\n  for ( size_t i=0; i < 3; ++i)\n  {\n    double temp = sigma(i);\n    if( temp > pinvtoler )\n      SigmaInverse(i,i) = 1.0/temp;\n  }\n\n  Eigen::MatrixXd PI(3,numberCorrespondences);\n  PI = SVDa.matrixV()*SigmaInverse*SVDa.matrixU().transpose();\n  Eigen::Vector3d ta = PI*b_tra;\n\n  Eigen::JacobiSVD< Eigen::MatrixXd > SVDb(\n      A_trb,\n      Eigen::ComputeThinU | Eigen::ComputeThinV );\n\n  sigma = SVDb.singularValues();\n  pinvtoler = numberCorrespondences*sigma(0)*NumTraits<double>::epsilon();\n  SigmaInverse = Eigen::MatrixXd::Zero(3,3);\n  for ( size_t i=0; i < 3; ++i)\n  {\n    double temp = sigma(i);\n    if( temp > pinvtoler )\n      SigmaInverse(i,i) = 1.0/temp;\n  }\n\n  PI = SVDb.matrixV()*SigmaInverse*SVDb.matrixU().transpose();\n  Eigen::Vector3d tb = PI*b_trb;\n\n  Eigen::VectorXd fita = A_tra * ta - b_tra;\n  Eigen::VectorXd fitb = A_trb * tb - b_trb;\n\n  transformation_t transformation;\n  if( fita.norm() < fitb.norm() )\n  {\n    transformation.block<3,3>(0,0) = Ra;\n    transformation.col(3) = ta;\n  }\n  else\n  {\n    transformation.block<3,3>(0,0) = Rb;\n    transformation.col(3) = tb;\n  }\n\n  return transformation;\n}\n\n}\n}\n\nopengv::transformation_t\nopengv::relative_pose::seventeenpt( const RelativeAdapterBase & adapter )\n{\n  Indices idx(adapter.getNumberCorrespondences());\n  return seventeenpt(adapter,idx);\n}\n\nopengv::transformation_t\nopengv::relative_pose::seventeenpt(\n    const RelativeAdapterBase & adapter,\n    const std::vector<int> & indices )\n{\n  Indices idx(indices);\n  return seventeenpt(adapter,idx);\n}\n\nnamespace opengv\n{\nnamespace relative_pose\n{\n\nstruct OptimizeNonlinearFunctor1 : OptimizationFunctor<double>\n{\n  RelativeAdapterBase & _adapter;\n  const Indices & _indices;\n\n  OptimizeNonlinearFunctor1(\n      RelativeAdapterBase & adapter,\n      const Indices & indices ) :\n      OptimizationFunctor<double>(6,indices.size()),\n      _adapter(adapter),\n      _indices(indices) {}\n\n  int operator()(const VectorXd &x, VectorXd &fvec) const\n  {\n    assert( x.size() == 6 );\n    assert( (unsigned int) fvec.size() == _indices.size());\n\n    //compute the current position\n    translation_t translation = x.block<3,1>(0,0);\n    cayley_t cayley = x.block<3,1>(3,0);\n    rotation_t rotation = math::cayley2rot(cayley);\n\n    Eigen::Matrix<double,4,1> p_hom;\n    p_hom[3] = 1.0;\n\n    for( size_t i = 0; i < _indices.size(); i++ )\n    {\n      translation_t cam1Offset = _adapter.getCamOffset1(_indices[i]);\n      rotation_t cam1Rotation = _adapter.getCamRotation1(_indices[i]);\n      translation_t cam2Offset = _adapter.getCamOffset2(_indices[i]);\n      rotation_t cam2Rotation = _adapter.getCamRotation2(_indices[i]);\n\n      translation_t directTranslation =\n          cam1Rotation.transpose() *\n          ((translation - cam1Offset) + rotation * cam2Offset);\n      rotation_t directRotation =\n          cam1Rotation.transpose() * rotation * cam2Rotation;\n\n      _adapter.sett12(directTranslation);\n      _adapter.setR12(directRotation);\n\n      transformation_t inverseSolution;\n      inverseSolution.block<3,3>(0,0) = directRotation.transpose();\n      inverseSolution.col(3) =\n          -inverseSolution.block<3,3>(0,0)*directTranslation;\n\n      p_hom.block<3,1>(0,0) =\n          opengv::triangulation::triangulate2(_adapter,_indices[i]);\n      bearingVector_t reprojection1 = p_hom.block<3,1>(0,0);\n      bearingVector_t reprojection2 = inverseSolution * p_hom;\n      reprojection1 = reprojection1 / reprojection1.norm();\n      reprojection2 = reprojection2 / reprojection2.norm();\n      bearingVector_t f1 = _adapter.getBearingVector1(_indices[i]);\n      bearingVector_t f2 = _adapter.getBearingVector2(_indices[i]);\n\n      //bearing-vector based outlier criterium (select threshold accordingly):\n      //1-(f1'*f2) = 1-cos(alpha) \\in [0:2]\n      double reprojError1 = 1.0 - (f1.transpose() * reprojection1);\n      double reprojError2 = 1.0 - (f2.transpose() * reprojection2);\n      double factor = 1.0;\n      fvec[i] = factor*(reprojError1 + reprojError2);\n    }\n\n    return 0;\n  }\n};\n\ntransformation_t optimize_nonlinear(\n    RelativeAdapterBase & adapter,\n    const Indices & indices )\n{\n  const int n=6;\n  VectorXd x(n);\n\n  x.block<3,1>(0,0) = adapter.gett12();\n  x.block<3,1>(3,0) = math::rot2cayley(adapter.getR12());\n\n  OptimizeNonlinearFunctor1 functor( adapter, indices );\n  NumericalDiff<OptimizeNonlinearFunctor1> numDiff(functor);\n  LevenbergMarquardt< NumericalDiff<OptimizeNonlinearFunctor1> >\n      lm(numDiff);\n\n  lm.resetParameters();\n  lm.parameters.ftol = 1.E1*NumTraits<double>::epsilon();\n  lm.parameters.xtol = 1.E1*NumTraits<double>::epsilon();\n  lm.parameters.maxfev = 1000;\n  lm.minimize(x);\n\n  transformation_t transformation;\n  transformation.col(3) = x.block<3,1>(0,0);\n  transformation.block<3,3>(0,0) = math::cayley2rot(x.block<3,1>(3,0));\n  return transformation;\n}\n\n}\n}\n\nopengv::transformation_t\nopengv::relative_pose::optimize_nonlinear( RelativeAdapterBase & adapter )\n{\n  Indices idx(adapter.getNumberCorrespondences());\n  return optimize_nonlinear(adapter,idx);\n}\n\nopengv::transformation_t\nopengv::relative_pose::optimize_nonlinear(\n    RelativeAdapterBase & adapter,\n    const std::vector<int> & indices )\n{\n  Indices idx(indices);\n  return optimize_nonlinear(adapter,idx);\n}\n", "meta": {"hexsha": "b42e297d7dfb10ef12479056c04fee896d4b727f", "size": 36410, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/relative_pose/methods.cpp", "max_stars_repo_name": "mateus03/2018AMMPoseSolver", "max_stars_repo_head_hexsha": "787886846199cd0864c4e59a6545c40c3120010a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-05-15T12:41:36.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-07T10:42:52.000Z", "max_issues_repo_path": "src/relative_pose/methods.cpp", "max_issues_repo_name": "mateus03/2018AMMPoseSolver", "max_issues_repo_head_hexsha": "787886846199cd0864c4e59a6545c40c3120010a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/relative_pose/methods.cpp", "max_forks_repo_name": "mateus03/2018AMMPoseSolver", "max_forks_repo_head_hexsha": "787886846199cd0864c4e59a6545c40c3120010a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-27T18:11:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-27T18:11:14.000Z", "avg_line_length": 30.2660016625, "max_line_length": 84, "alphanum_fraction": 0.6539686899, "num_tokens": 11486, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702880639791, "lm_q2_score": 0.640635847978761, "lm_q1q2_score": 0.46437789166847604}}
{"text": "#include <assert.h>\r\n#include <unistd.h>\r\n\r\n#include <sstream>\r\n//#include <boost/algorithm/string.hpp>\r\n#include <algorithm> // for is_permutation\r\n#include <tuple>\r\n#include <functional>\r\n#include <iterator>\r\n\r\n#include \"./permutation.h\"\r\n\r\n#include \"./dm_english.h\"\r\n#include \"./dm_perm.h\"\r\n#include \"./sagemath_alter.h\"\r\n\r\nPermutation::Permutation(){}\r\n  \r\nPermutation::Permutation(const int n)\r\n{\r\n\tif(n==-1) non_perm();\r\n\telse identify(n);\r\n}\r\n  \r\nPermutation::Permutation(const std::vector<int> vec)\r\n{\r\n\tstd::vector<int>::const_iterator it;\r\n\tfor(it = vec.begin() ; it != vec.end() ; ++it){\r\n\t\tperm.push_back(*it);\r\n\t}\r\n\tlabel.resize( length() );\r\n\tcomputeInverse();\r\n// \tcanonization();\r\n}\r\n\r\n// construct a canonical permutation for G (induced by modules)\r\n// for parallel, series, prime modules. \r\nPermutation::Permutation(const int n, const ModuleType type)\r\n{\r\n\tswitch(type){\r\n\tcase FEUILLE:\r\n\t\tidentify(1);\r\n\t\tbreak;\r\n\t\t      /*\r\n\t\t    case PREMIER:\r\n\t\t\t// This case will not be reached\r\n\t\t      prime(G);\r\n\t\t      break;\r\n\t\t      */\r\n\tcase PARALLELE:\r\n\t\tidentify(n);\r\n\t\tbreak;\r\n\tcase SERIE:\r\n\t\treverse(n);\r\n\t\tbreak;\r\n\tdefault:\r\n\t\tstd::cerr << \"Error! Strange the module type.\\n\\n\";\r\n\t}\r\n}\r\n\r\n  \r\n  // For a prime module.\r\n  // \u3053\u3053\u3067 sagemath \u3092\u4f7f\u3063\u3066\u3044\u308b\uff0e\r\n  // sagemath \u3092\u4f7f\u308f\u306a\u3051\u308c\u3070\uff0c1000\u500d\u306f\u65e9\u304f\u306a\u308b\u306f\u305a\uff0e\r\nvoid Permutation::prime(const graphe G)\r\n{\r\n\tstd::vector< std::vector< int > > adj_matrix( G.n, std::vector< int >( G.n ) );\r\n\tfor ( int i = 0; i < G.n; ++i )\r\n\t{\r\n\t\tfor ( adj* adj_list = G.G[i]; adj_list != NULL; adj_list = adj_list->suiv )\r\n\t\t{\r\n\t\t\tconst int j = adj_list->s;\r\n\t\t\tadj_matrix[i][j] = adj_matrix[j][i] = 1;\r\n\t\t}\r\n\t}\r\n\r\n\tstd::vector< int > vec1, vec2;\r\n\tstd::tie( vec1, vec2 ) = is_permutation_certificate( adj_matrix );\r\n\tif ( vec1.empty() )\r\n\t{\r\n\t\tnon_perm();\r\n\t\treturn;\r\n\t}\r\n\r\n// #define D_PRIME\r\n\r\n\tlabel = vec1;\r\n\t// \u6b63\u898f\u5316\uff08\u4e00\u65b9\u306e permutation \u3092(1, 2, 3, ..., n)\u306b\u5909\u63db\uff09\u3057\uff0cperm \u306b\u683c\u7d0d\r\n\tstd::vector<int> v1(vec1.size());\r\n\tfor(int i=0 ; i<vec1.size() ; i++){\r\n\t\tv1[vec1[i]-1] = i+1;\r\n\t}\r\n\tfor(int i=0 ; i<vec2.size() ; i++){\r\n\t\tperm.push_back(v1[vec2[i]-1]);\r\n\t}\r\n\t// -----\uff08\u3053\u3053\u307e\u3067\uff09\u51fa\u529b\u30c7\u30fc\u30bf\u304b\u3089\u4e8c\u3064\u306e permutation \u3092\u8aad\u307f\u8fbc\u3093\u3067\u6b63\u898f\u5316 -----\r\n\r\n\tcanonization(); // \u6a19\u6e96\u5f62\u306b\u5909\u63db\r\n\r\n}\r\n\r\n  \r\nvoid Permutation::identify(const int n)\r\n{\r\n\tfor(int i=0 ; i<n ; i++){\r\n\t\tperm.push_back(i+1);\r\n\t}\r\n\tcomputeInverse();\r\n}\r\n\r\n  \r\nvoid Permutation::reverse(const int n)\r\n{\r\n\tfor(int i=n ; i>0 ; i--){\r\n\t\tperm.push_back(i);\r\n\t}\r\n\tcomputeInverse();\r\n}\r\n\r\n  \r\nvoid Permutation::non_perm(){\r\n\tstd::vector<int>().swap(perm);\r\n\tperm.push_back(-1);\r\n}\r\n\r\n  /******************************************/\r\n\r\nvoid Permutation::canonization()\r\n{\r\n\tstd::vector<int> vecH = computeHorizontalFlip();\r\n\tstd::vector<int> vecV = computeVerticalFlip();\r\n\tstd::vector<int> vecR = computeRotation();\r\n\r\n\tcomputeInverse();\r\n\r\n\tif(is_SmallerEqual(vecH) && is_SmallerEqual(vecV) && is_SmallerEqual(vecR)){\r\n\t\treturn;\r\n\t}\r\n\r\n\tif(is_small(vecH, vecV)){ // checked vecH < vecV\r\n\t\tif(is_small(vecH, vecR)){ // vecH < vecR\r\n\t\t\tperm = vecH;\r\n\t\t\tcomputeHorizontalFlip_label();\r\n\t\t}\r\n\t\telse{ // vecR < vecH\r\n\t\t\tperm = vecR;\r\n\t\t\tcomputeRotation_label();\r\n\t\t}\r\n\t}\r\n\telse{ // vecV < vecH\r\n\t\tif(is_small(vecV, vecR)){ // vecV < vecR\r\n\t\t\tperm = vecV;\r\n\t\t\tcomputeVerticalFlip_label();\r\n\t\t}\r\n\t\telse{ // vecR < vecV\r\n\t\t\tperm = vecR;\r\n\t\t\tcomputeRotation_label();\r\n\t\t}\r\n\t}\r\n\r\n\tcomputeInverse();\r\n}\r\n\r\nvoid Permutation::computeInverse()\r\n{\r\n\tinverse.resize( length() );\r\n\tfor ( int i = 0; i < length(); ++i )\r\n\t{\r\n\t\tinverse[ perm[i] - 1 ] = i + 1;\r\n\t}\r\n\treturn;\r\n}\r\n\r\nvoid Permutation::computeHorizontalFlip_label()\r\n{\r\n// \tcerr << \"H-flip\" << endl;\r\n\tstd::vector<int> vec(length());\r\n\tfor(int i=0 ; i<length() ; i++){\r\n\t\tvec[pi(i)-1] = label[i];\r\n// \t\tcerr << i << \" -> \" << perm[i] << endl;\r\n\t}\r\n\tlabel = vec;\r\n}\r\n  \r\nstd::vector<int> Permutation::computeHorizontalFlip() const\r\n{\r\n\tstd::vector<int> vec(length());\r\n\tfor(int i=0 ; i<length() ; i++){\r\n\t\tvec[pi(i)-1] = i+1;\r\n\t}\r\n\t//perm = vec;\r\n\treturn vec;\r\n}\r\n\r\nvoid Permutation::computeVerticalFlip_label()\r\n{\r\n\tstd::vector<int> vec(length());\r\n\tfor(int i=0 ; i<length() ; i++){\r\n\t\tvec[length()-i-1] = label[i];\r\n\t}\r\n\tlabel = vec;\r\n}\r\n\r\nstd::vector<int> Permutation::computeVerticalFlip() const\r\n{\r\n\tstd::vector<int> vec(length());\r\n\tfor(int i=0 ; i<length() ; i++){\r\n\t\tvec[length()-i-1] = length() - pi(i) + 1;\r\n\t}\r\n\t//perm = vec;\r\n\treturn vec;\r\n}\r\n\r\nstd::vector<int> Permutation::computeVerticalFlip(std::vector<int> p) const\r\n{\r\n\tassert(p.size()==length());\r\n\tstd::vector<int> vec(length());\r\n\tfor(int i=0 ; i<length() ; i++){\r\n\t\tvec[length()-i-1] = length() - p[i] + 1;\r\n\t}\r\n\t//perm = vec;\r\n\treturn vec;\r\n}\r\n\r\nvoid Permutation::computeRotation_label()\r\n{\r\n\tvector< int > vec( length() );\r\n\tfor ( int i = 0; i < length(); ++i )\r\n\t{\r\n\t\tvec[ length() - inverse[i] ] = label[i];\r\n\t}\r\n\tlabel = vec;\r\n\r\n// \tcomputeHorizontalFlip_label();\r\n// \tcomputeVerticalFlip_label();\r\n}\r\n    \r\nstd::vector<int> Permutation::computeRotation() const\r\n{\r\n\tstd::vector<int> vecH = computeHorizontalFlip();\r\n\tstd::vector<int> vec = computeVerticalFlip(vecH);\r\n\treturn vec;\r\n}\r\n\r\nbool Permutation::is_canonical()\r\n{\r\n\tPermutation p(perm);\r\n\tp.canonization();\r\n\tif(is_Smaller(p.perm)) return true;\r\n\telse return false;\r\n}\r\n\r\nbool Permutation::is_v_symmetry() const\r\n{\r\n\tfor(int i=0 ; i<length()/2 ; i++){\r\n\t\tif (perm[i] != length() - perm[length()-i-1] + 1){\r\n// \t\t\tcerr << \"i : \" << i << endl;\r\n// \t\t\tcerr << \"perm[i] : \" << perm[i] << endl;\r\n// \t\t\tcerr << \"length() - perm[length()-i-1] + 1) : \" << length() - perm[length()-i-1] + 1 << endl;\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\treturn true;\r\n}\r\n\r\nbool Permutation::is_h_symmetry() const\r\n{\r\n\tfor ( int i = 0; i < length(); ++i )\r\n\t{\r\n\t\tif ( i != perm[ perm[i] - 1 ] - 1 )\r\n\t\t{\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\treturn true;\r\n}\r\n\r\nbool Permutation::is_rotational_symmetry() const\r\n{\r\n\tstd::vector<int> vecR = computeRotation();\r\n\treturn is_equal(vecR);\r\n}\r\n  \r\nbool Permutation::is_permutation()\r\n{\r\n\t//std::cout << perm[0] << std::endl;\r\n\tif(perm[0] == -1) return false;\r\n\telse return true;\r\n}\r\n\r\nint Permutation::length() const\r\n{\r\n\treturn perm.size();\r\n}\r\n\r\nint Permutation::pi(int k) const\r\n{\r\n\treturn perm[k];\r\n}\r\n\r\nbool Permutation::operator==(const Permutation& p) const\r\n{\r\n\tif(length() != p.length()) return false;\r\n\r\n\tfor(int i=0 ; i<length() ; i++){\r\n\t\tif(perm[i] != p.pi(i)) return false;\r\n\t}\r\n\treturn true;\r\n}\r\n\r\nbool Permutation::operator==(const std::vector<int>& vec) const\r\n{\r\n\tif(length() != vec.size()) return false;\r\n\r\n\tfor(int i=0 ; i<length() ; i++){\r\n\t\tif(perm[i] != vec[i]) return false;\r\n\t}\r\n\treturn true;\r\n}\r\n\r\nbool Permutation::is_equal(const std::vector<int>& vec) const\r\n{\r\n\tif(length() != vec.size()) return false;\r\n\r\n\tfor(int i=0 ; i<length() ; i++){\r\n\t\tif(perm[i] != vec[i]) return false;\r\n\t}\r\n\treturn true;\r\n}\r\n\r\nbool Permutation::operator<(const Permutation& p) const {\r\n\r\n\tif(length() < p.length()) return true;\r\n\tif(length() > p.length()) return false;\r\n\r\n\tfor(int i=0 ; i<length() ; i++){\r\n\t\tif(perm[i] < p.pi(i)) return true;\r\n\t\tif(perm[i] > p.pi(i)) return false;\r\n\t}\r\n\treturn false;\r\n}\r\n\r\nbool Permutation::is_Smaller(const std::vector<int>& vec) const\r\n{\r\n\tif(length() < vec.size()) return true;\r\n\tif(length() > vec.size()) return false;\r\n\r\n\tfor(int i=0 ; i<length() ; i++){\r\n\t\tif(perm[i] < vec[i]) return true;\r\n\t\tif(perm[i] > vec[i]) return false;\r\n\t}\r\n\treturn false;\r\n}\r\n\r\nbool Permutation::is_SmallerEqual(const std::vector<int>& vec) const\r\n{\r\n\tif(length() < vec.size()) return true;\r\n\tif(length() > vec.size()) return false;\r\n\r\n\tfor(int i=0 ; i<length() ; i++){\r\n\t\tif(perm[i] < vec[i]) return true;\r\n\t\tif(perm[i] > vec[i]) return false;\r\n\t}\r\n\treturn true;\r\n}\r\n\r\n\r\nbool Permutation::is_Smaller(const Permutation& p) const\r\n{\r\n\tif(length() < p.length()) return true;\r\n\tif(length() > p.length()) return false;\r\n\r\n\tfor(int i=0 ; i<length() ; i++){\r\n\t\tif(perm[i] < p.pi(i)) return true;\r\n\t\tif(perm[i] > p.pi(i)) return false;\r\n\t}\r\n\treturn false;\r\n}\r\n\r\nbool Permutation::is_small(const std::vector<int> v1, const std::vector<int> v2) const\r\n{\r\n\tif(v1.size() < v2.size()) return true;\r\n\tif(v1.size() > v2.size()) return false;\r\n\r\n\tfor(int i=0 ; i<v1.size() ; i++){\r\n\t\tif(v1[i] < v2[i]) return true;\r\n\t\tif(v1[i] > v2[i]) return false;\r\n\t}\r\n\treturn false;\r\n}\r\n\r\nbool Permutation::is_smallequal(const std::vector<int> v1, const std::vector<int> v2) const\r\n{\r\n\tif(v1.size() < v2.size()) return true;\r\n\tif(v1.size() > v2.size()) return false;\r\n\r\n\tfor(int i=0 ; i<v1.size() ; i++){\r\n\t\tif(v1[i] < v2[i]) return true;\r\n\t\tif(v1[i] > v2[i]) return false;\r\n\t}\r\n\treturn true;\r\n}\r\n\r\n// for Prime module\r\nvoid Permutation::merge(const std::vector<Permutation> p)\r\n{\r\n\r\n\tvector< vector< int > > perms;\r\n\tfor ( int i = 0; i < p.size(); ++i )\r\n\t{\r\n\t\tperms.push_back( p[i].perm );\r\n\t}\r\n\r\n\tvector< int > psum( length() + 1 );\r\n\tfor ( int i = 0; i < length(); ++i )\r\n\t{\r\n\t\tpsum[ i + 1 ] = perms[i].size();\r\n\t}\r\n\t//partial_sum( begin( psum ), end( psum ), begin( psum ) );\r\n\r\n\tfor ( int i = 0, s = 0; i < length(); s += perms[ inverse[ i++ ] - 1 ].size() )\r\n\t{\r\n\t\t// \t\tcerr << \"perms[ \" << inverse[i] - 1 << \" ]\" << endl;\r\n\t\t// \t\tcerr << s << endl;\r\n\t\ttransform( begin( perms[ inverse[i] - 1 ] ), end( perms[ inverse[i] - 1 ] ), begin( perms[ inverse[i] - 1 ] ), bind( plus< int >(), placeholders::_1, s ) );\r\n\t}\r\n\r\n\tvector< int > vec;\r\n\tfor ( const auto &pp : perms )\r\n\t{\r\n\r\n\t\tcopy( begin( pp ), end( pp ), back_inserter( vec ) );\r\n// \t\t\t\tcopy( begin( pp ), end( pp ), ostream_iterator< int >( cerr, \" \" ) );\r\n// \t\t\t\tcerr << endl;\r\n\t}\r\n\r\n\tperm = vec;\r\n\tlabel.resize( perm.size() );\r\n}\r\n\r\nPermutation Permutation::parentPermutation() const\r\n{\r\n\tstd::vector< int > vec( perm );\r\n\tfor ( int i = 0; i + 1 < length(); ++i )\r\n\t{\r\n\t\tif ( vec[i] < vec[ i + 1 ] )\r\n\t\t{\r\n\t\t\tstd::swap( vec[i], vec[ i + 1 ] );\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\r\n\tPermutation p(vec);\r\n// \tcerr << \"parent permutation from : \";\r\n// \tp.print();\r\n\tgraphe G = p.makeGraphe();\r\n\tnoeud *root = decomposition_modulaire( G );\r\n\tPermutation pp = createPermutation( root, G );\r\n\treturn pp;\r\n}\r\n\r\ngraphe Permutation::makeGraphe() const\r\n{\r\n\tgraphe G;\r\n\tG.n = length();\r\n\tG.G=(adj **)malloc(G.n*sizeof(adj *));\r\n\tfor(int i=0 ; i<G.n ; i++) G.G[i] = NULL;\r\n\r\n\tfor(int i=0 ; i<length() ; i++){\r\n\t\tfor(int j=i+1 ; j<length() ; j++){\r\n\t\t\tif(perm[i] > perm[j]){\r\n\t\t\t\t// add an edge perm[i] to perm[j] (and its reversal).\r\n\t\t\t\tadj *a = (adj *)malloc(sizeof(adj));\r\n\t\t\t\ta->s = perm[j]-1;\r\n\t\t\t\ta->suiv = G.G[perm[i]-1];\r\n\t\t\t\tG.G[perm[i]-1] = a;\r\n\r\n\t\t\t\ta = (adj *)malloc(sizeof(adj)); a->s = perm[i]-1;\r\n\t\t\t\ta->suiv = G.G[perm[j]-1];\r\n\t\t\t\tG.G[perm[j]-1] = a;\r\n\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn G;\r\n}\r\n  \r\nvoid Permutation::print() const\r\n{\r\n\tif(length()<1){\r\n\t\tstd::cout << \"length 0\" << std::endl;\r\n\t\treturn;\r\n\t}\r\n\r\n\tstd::vector<int>::const_iterator it;\r\n\tfor(it = perm.begin() ; it != perm.end() ; ++it){\r\n\t\tstd::cout << *it << ( it + 1 != perm.end() ? ' ' : '\\n' );\r\n\t}\r\n\tstd::cout << std::flush;\r\n}\r\n\r\n    \r\nvoid Permutation::print(std::ofstream &ofs) const\r\n{\r\n\tif(length()<1){\r\n\t\tofs << \"length 0\" << std::endl;\r\n\t\treturn;\r\n\t}\r\n\r\n\tstd::vector<int>::const_iterator it;\r\n\tfor(it = perm.begin() ; it != perm.end() ; ++it){\r\n\t\tofs << *it << ( it + 1 != perm.end() ? ' ' : '\\n' );\r\n\t}\r\n\tofs << std::flush;\r\n}\r\n\r\nvoid Permutation::print(std::ofstream &ofs, std::vector<int> vec) const\r\n{\r\n\tif(vec.size()<1){\r\n\t\tofs << \"length 0\" << std::endl;\r\n\t\treturn;\r\n\t}\r\n\r\n\tstd::vector<int>::const_iterator it;\r\n\tfor(it = vec.begin() ; it != vec.end() ; ++it){\r\n\t\tofs << *it << ( it + 1 != vec.end() ? ' ' : '\\n' );\r\n\t}\r\n\tofs << std::flush;\r\n}\r\n\r\n\r\nvoid Permutation::print(std::vector<int> vec)\r\n{\r\n\tfor(int i=0 ; i<vec.size() ; i++){\r\n\t\tstd::cout << vec[i] << ( i + 1 < vec.size() ? ' ' : '\\n' );\r\n\t}\r\n\tstd::cout << std::endl;\r\n}\r\n", "meta": {"hexsha": "e1b218535d58e1e20237378c9d9f0852df075320", "size": 11662, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "permutation.cpp", "max_stars_repo_name": "toshikisaitoh/EnumPermGraphs", "max_stars_repo_head_hexsha": "17542559326321ab299718f3a5b341295979d9f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "permutation.cpp", "max_issues_repo_name": "toshikisaitoh/EnumPermGraphs", "max_issues_repo_head_hexsha": "17542559326321ab299718f3a5b341295979d9f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "permutation.cpp", "max_forks_repo_name": "toshikisaitoh/EnumPermGraphs", "max_forks_repo_head_hexsha": "17542559326321ab299718f3a5b341295979d9f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-08-21T06:14:34.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-21T06:14:34.000Z", "avg_line_length": 21.6363636364, "max_line_length": 159, "alphanum_fraction": 0.5582232893, "num_tokens": 3644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.4643778890265731}}
{"text": "#include <PCP/Geometry/Normal.h>\n#include <PCP/Geometry/Geometry.h>\n\n#include <PCP/Common/Assert.h>\n#include <PCP/Common/Progress.h>\n#include <PCP/Common/Log.h>\n\n#include <PCP/SpacePartitioning/KnnGraph.h>\n\n#include <set>\n\n#include <Eigen/Eigenvalues>\n\n// https://www.geeksforgeeks.org/kruskals-minimum-spanning-tree-using-stl-in-c/\nnamespace mst {\n\nusing namespace std;\n\n// Creating shortcut for an integer pair\ntypedef pair<int, int> iPair;\n\n// Structure to represent a graph\nstruct Graph\n{\n    int V, E;\n    vector< pair<float, iPair> > edges;\n\n    // Constructor\n    Graph(int V, int E)\n    {\n        this->V = V;\n        this->E = E;\n    }\n\n    // Utility function to add an edge\n    void addEdge(int u, int v, float w)\n    {\n        edges.push_back({w, {u, v}});\n    }\n\n    // Function to find MST using Kruskal's\n    // MST algorithm\n    float kruskalMST(std::vector<iPair>& result);\n};\n\n// To represent Disjoint Sets\nstruct DisjointSets\n{\n    int *parent, *rnk;\n    int n;\n\n    // Constructor.\n    DisjointSets(int n)\n    {\n        // Allocate memory\n        this->n = n;\n        parent = new int[n+1];\n        rnk = new int[n+1];\n\n        // Initially, all vertices are in\n        // different sets and have rank 0.\n        for (int i = 0; i <= n; i++)\n        {\n            rnk[i] = 0;\n\n            //every element is parent of itself\n            parent[i] = i;\n        }\n    }\n\n    // Find the parent of a node 'u'\n    // Path Compression\n    int find(int u)\n    {\n        /* Make the parent of the nodes in the path\n           from u--> parent[u] point to parent[u] */\n        if (u != parent[u])\n            parent[u] = find(parent[u]);\n        return parent[u];\n    }\n\n    // Union by rank\n    void merge(int x, int y)\n    {\n        x = find(x), y = find(y);\n\n        /* Make tree with smaller height\n           a subtree of the other tree  */\n        if (rnk[x] > rnk[y])\n            parent[y] = x;\n        else // If rnk[x] <= rnk[y]\n            parent[x] = y;\n\n        if (rnk[x] == rnk[y])\n            rnk[y]++;\n    }\n};\n\n /* Functions returns weight of the MST*/\n\nfloat Graph::kruskalMST(std::vector<iPair>& result)\n{\n    result.clear();\n    float mst_wt = 0; // Initialize result\n\n    // Sort edges in increasing order on basis of cost\n    sort(edges.begin(), edges.end());\n\n    // Create disjoint sets\n    DisjointSets ds(V);\n\n    // Iterate through all sorted edges\n    vector< pair<float, iPair> >::iterator it;\n    for (it=edges.begin(); it!=edges.end(); it++)\n    {\n        int u = it->second.first;\n        int v = it->second.second;\n\n        int set_u = ds.find(u);\n        int set_v = ds.find(v);\n\n        // Check if the selected edge is creating\n        // a cycle or not (Cycle is created if u\n        // and v belong to same set)\n        if (set_u != set_v)\n        {\n            // Current edge will be in the MST\n            // so print it\n//            cout << u << \" - \" << v << endl;\n            result.push_back(std::make_pair(u, v));\n\n            // Update MST weight\n            mst_wt += it->first;\n\n            // Merge two sets\n            ds.merge(set_u, set_v);\n        }\n    }\n\n    return mst_wt;\n}\n\n// for my std::set\nstruct Comp\n{\n    // compare only the first index\n    bool operator()(const pair<float, iPair>& e1, const pair<float, iPair>& e2)\n    {\n        return e1.second.first < e2.second.first;\n    }\n};\n\n} // namespace mst\n\nnamespace pcp {\n\nvoid compute_normals(Geometry& g, bool v)\n{\n    PCP_ASSERT(g.has_knn_graph());\n\n    const int point_count = g.size();\n\n    info().iff(v) << \"0/5 Computing normals\";\n    internal::compute_unoriented_normals(g, v);\n\n    info().iff(v) << \"1/5 Extracting unique edges\";\n    std::set<std::pair<int,int>> edges;\n    auto prog = Progress(point_count, v);\n    for(int i=0; i<point_count; ++i)\n    {\n        for(int j : g.knn_graph().k_nearest_neighbors(i))\n        {\n            auto e = std::make_pair(i,j);\n            if(e.first > e.second) std::swap(e.first, e.second);\n\n            edges.insert(e);\n        }\n        ++prog;\n    }\n    info().iff(v) << \"  \" << edges.size() << \" edges found\";\n\n    info().iff(v) << \"2/5 Building graph for mst\";\n    mst::Graph graph(point_count, edges.size());\n    for(const auto& e : edges)\n    {\n        const int i = e.first;\n        const int j = e.second;\n        const Vector3& n_i = g.normal(i);\n        const Vector3& n_j = g.normal(j);\n        const Scalar w = 1 - std::abs(n_i.dot(n_j));\n        graph.addEdge(i, j, w);\n    }\n\n    info().iff(v) << \"3/5 Computing mst\";\n    std::vector<mst::iPair> result;\n    graph.kruskalMST(result);\n    info().iff(v) << \"  \" << result.size() << \" edges found in mst\";\n\n    info().iff(v) << \"4. Building mst\";\n    std::vector<std::vector<int>> mst(point_count);\n    for(const auto& e : result)\n    {\n        mst[e.first].push_back(e.second);\n        mst[e.second].push_back(e.first);\n    }\n\n    info().iff(v) << \"5/5 Propagate orientention\";\n    int topmost = 0;\n    for(int i=0; i<point_count; ++i)\n    {\n        if(g[i].z() > g[topmost].z()) topmost = i;\n    }\n    std::stack<mst::iPair> stack;\n    std::vector<bool> traversed(point_count, false);\n    traversed[topmost] = true;\n    for(int i : mst[topmost]) stack.push(std::make_pair(topmost, i));\n\n    while(!stack.empty())\n    {\n        const auto e = stack.top();\n        stack.pop();\n\n        const int source = e.first;\n        const int target = e.second;\n\n        const Vector3& n_source = g.normal(source);\n        Vector3& n_target = g.normal(target);\n\n        if(n_source.dot(n_target) < 0) n_target *= -1;\n\n        traversed[target] = true;\n\n        for(int i : mst[target]) if(!traversed[i]) stack.push(std::make_pair(target, i));\n    }\n}\n\nvoid compute_normals_robust(Geometry& g, float sigma, int iter, bool v)\n{\n    PCP_ASSERT(g.has_knn_graph());\n\n    const int point_count = g.size();\n\n    info().iff(v) << \"0/5 Computing normals\";\n    internal::compute_unoriented_normals_robust(g, sigma, iter, v);\n\n    info().iff(v) << \"1/5 Extracting unique edges\";\n    std::set<std::pair<int,int>> edges;\n    auto prog = Progress(point_count, v);\n    for(int i=0; i<point_count; ++i)\n    {\n        for(int j : g.knn_graph().k_nearest_neighbors(i))\n        {\n            auto e = std::make_pair(i,j);\n            if(e.first > e.second) std::swap(e.first, e.second);\n\n            edges.insert(e);\n        }\n        ++prog;\n    }\n    info().iff(v) << \"  \" << edges.size() << \" edges found\";\n\n    info().iff(v) << \"2/5 Building graph for mst\";\n    mst::Graph graph(point_count, edges.size());\n    for(const auto& e : edges)\n    {\n        const int i = e.first;\n        const int j = e.second;\n        const Vector3& n_i = g.normal(i);\n        const Vector3& n_j = g.normal(j);\n        const Scalar w = 1 - std::abs(n_i.dot(n_j));\n        graph.addEdge(i, j, w);\n    }\n\n    info().iff(v) << \"3/5 Computing mst\";\n    std::vector<mst::iPair> result;\n    graph.kruskalMST(result);\n    info().iff(v) << \"  \" << result.size() << \" edges found in mst\";\n\n    info().iff(v) << \"4. Building mst\";\n    std::vector<std::vector<int>> mst(point_count);\n    for(const auto& e : result)\n    {\n        mst[e.first].push_back(e.second);\n        mst[e.second].push_back(e.first);\n    }\n\n    info().iff(v) << \"5/5 Propagate orientention\";\n    int topmost = 0;\n    for(int i=0; i<point_count; ++i)\n    {\n        if(g[i].z() > g[topmost].z()) topmost = i;\n    }\n    std::stack<mst::iPair> stack;\n    std::vector<bool> traversed(point_count, false);\n    traversed[topmost] = true;\n    for(int i : mst[topmost]) stack.push(std::make_pair(topmost, i));\n\n    while(!stack.empty())\n    {\n        const auto e = stack.top();\n        stack.pop();\n\n        const int source = e.first;\n        const int target = e.second;\n\n        const Vector3& n_source = g.normal(source);\n        Vector3& n_target = g.normal(target);\n\n        if(n_source.dot(n_target) < 0) n_target *= -1;\n\n        traversed[target] = true;\n\n        for(int i : mst[target]) if(!traversed[i]) stack.push(std::make_pair(target, i));\n    }\n}\n\nnamespace internal {\n\nvoid compute_unoriented_normals(Geometry& g, bool v)\n{\n    const int point_count = g.size();\n    const int K = g.knn_graph().k();\n\n    g.request_normals();\n\n    auto prog = Progress(point_count, v);\n\n    #pragma omp parallel for\n    for(int i=0; i<point_count; ++i)\n    {\n        Matrix3 C = Matrix3::Zero();\n        Vector3 m = Vector3::Zero();\n\n        for(int j : g.knn_graph().k_nearest_neighbors(i))\n        {\n            const Vector3 p = g[j] - g[i];\n\n            C += p * p.transpose();\n            m += p;\n        }\n        m /= K;\n        C = C/K - m * m.transpose();\n\n        Eigen::SelfAdjointEigenSolver<Matrix3> eig(C);\n        g.normal(i) = eig.eigenvectors().col(0);\n\n        ++prog;\n    }\n}\n\nnamespace internal {\nScalar robust_weight(const Vector3& p, Scalar uc, const Vector3& ul, Scalar sigma)\n{\n    const Scalar f = uc + ul.dot(p);\n    return std::exp(-f*f/(sigma*sigma));\n}\n} // namespace internal\n\nvoid compute_unoriented_normals_robust(Geometry& g, float sigma, int iter, bool v)\n{\n    const int point_count = g.size();\n//    const int K = g.knn_graph().k();\n\n    g.request_normals();\n\n    auto prog = Progress(point_count, v);\n\n    #pragma omp parallel for\n    for(int i=0; i<point_count; ++i)\n    {\n        Scalar  uc = 0;\n        Vector3 ul = Vector3::Zero();\n\n        for(int n=0; n<iter; ++n)\n        {\n            Matrix3 C = Matrix3::Zero();\n            Vector3 m = Vector3::Zero();\n            Scalar sum_w = 0;\n\n            for(int j : g.knn_graph().k_nearest_neighbors(i))\n            {\n                const Vector3 p = g[j] - g[i];\n                const Scalar w = n == 0 ? 1 : internal::robust_weight(p, uc, ul, sigma);\n\n                C += w * p * p.transpose();\n                m += w * p;\n                sum_w += w;\n            }\n\n            if(sum_w <= 0)\n            {\n                warning().iff(v) << \"sum_w=0 at i=\" << i << \" (n=\" << n << \")\";\n//                PCP_ERROR;\n                break;\n            }\n\n            m /= sum_w;\n            C = C/sum_w - m * m.transpose();\n\n            Eigen::SelfAdjointEigenSolver<Matrix3> eig(C);\n            ul = eig.eigenvectors().col(0);\n            uc = - ul.dot(m);\n        }\n\n        g.normal(i) = ul;\n\n        ++prog;\n    }\n}\n\n\n} // namespace internal\n\n} // namespace pcp\n", "meta": {"hexsha": "e3b7f67801fba6c6cc4bf4cbc4eec58d39009478", "size": 10299, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "figures/src/PCP/Geometry/Normal.cpp", "max_stars_repo_name": "STORM-IRIT/algebraic-shape-operator", "max_stars_repo_head_hexsha": "8de592549562cf8cff51044a459ce64a75176e42", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-07-29T18:19:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-12T12:42:52.000Z", "max_issues_repo_path": "figures/src/PCP/Geometry/Normal.cpp", "max_issues_repo_name": "STORM-IRIT/algebraic-shape-operator", "max_issues_repo_head_hexsha": "8de592549562cf8cff51044a459ce64a75176e42", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-07-12T08:51:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-14T09:38:17.000Z", "max_forks_repo_path": "figures/src/PCP/Geometry/Normal.cpp", "max_forks_repo_name": "STORM-IRIT/algebraic-shape-operator", "max_forks_repo_head_hexsha": "8de592549562cf8cff51044a459ce64a75176e42", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-07-12T08:52:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-17T11:40:21.000Z", "avg_line_length": 24.8168674699, "max_line_length": 89, "alphanum_fraction": 0.5361685601, "num_tokens": 2838, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.6406358479787609, "lm_q1q2_score": 0.4643778840531388}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// Unit Test\n\n// Copyright (c) 2020 Digvijay Janartha, Hamirpur, India.\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#include <iostream>\n\n#include <geometry_test_common.hpp>\n\n#include <boost/core/ignore_unused.hpp>\n#include <boost/geometry/algorithms/make.hpp>\n#include <boost/geometry/algorithms/append.hpp>\n#include <boost/geometry/geometries/point.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/linestring.hpp>\n#include <boost/geometry/geometries/multi_linestring.hpp>\n#include <boost/geometry/geometries/concepts/multi_linestring_concept.hpp>\n#include <boost/geometry/geometries/adapted/c_array.hpp>\n#include <boost/geometry/geometries/adapted/boost_tuple.hpp>\n#include <boost/geometry/io/dsv/write.hpp>\n\n#include <test_common/test_point.hpp>\n\nBOOST_GEOMETRY_REGISTER_C_ARRAY_CS(cs::cartesian)\nBOOST_GEOMETRY_REGISTER_BOOST_TUPLE_CS(cs::cartesian)\n\n#ifdef BOOST_NO_CXX11_HDR_INITIALIZER_LIST\n#include <initializer_list>\n#endif//BOOST_NO_CXX11_HDR_INITIALIZER_LIST\n\ntemplate <typename P>\nbg::model::linestring<P> create_linestring()\n{   \n    bg::model::linestring<P> l1;\n    P p1(1, 2);\n    bg::append(l1, p1);\n    return l1;\n}\n\ntemplate <typename P, typename L>\nbg::model::multi_linestring<L> create_multi_linestring()\n{   \n    bg::model::multi_linestring<L> ml1;\n    L l1(create_linestring<P>());\n    ml1.push_back(l1);\n    ml1.push_back(l1);\n    return ml1;\n}\n\ntemplate <typename ML, typename L>\nvoid check_multi_linestring(ML& to_check, L l1)\n{   \n    ML cur;\n    cur.push_back(l1);\n    cur.push_back(l1);\n\n    std::ostringstream out1, out2;\n    out1 << bg::dsv(to_check);\n    out2 << bg::dsv(cur);\n    BOOST_CHECK_EQUAL(out1.str(), out2.str());\n}\n\ntemplate <typename P, typename L>\nvoid test_default_constructor()\n{\n    bg::model::multi_linestring<L> ml1(create_multi_linestring<P, L>());\n    check_multi_linestring(ml1, L(create_linestring<P>()));\n}\n\ntemplate <typename P, typename L>\nvoid test_copy_constructor()\n{\n    bg::model::multi_linestring<L> ml1 = create_multi_linestring<P, L>();\n    check_multi_linestring(ml1, L(create_linestring<P>()));\n}\n\ntemplate <typename P, typename L>\nvoid test_copy_assignment()\n{\n    bg::model::multi_linestring<L> ml1(create_multi_linestring<P, L>()), ml2;\n    ml2 = ml1;\n    check_multi_linestring(ml2, L(create_linestring<P>()));\n}\n\ntemplate <typename L>\nvoid test_concept()\n{   \n    typedef bg::model::multi_linestring<L> ML;\n\n    BOOST_CONCEPT_ASSERT( (bg::concepts::ConstMultiLinestring<ML>) );\n    BOOST_CONCEPT_ASSERT( (bg::concepts::MultiLinestring<ML>) );\n\n    typedef typename bg::coordinate_type<ML>::type T;\n    typedef typename bg::point_type<ML>::type PML;\n    boost::ignore_unused<T, PML>();\n}\n\ntemplate <typename P>\nvoid test_all()\n{   \n    typedef bg::model::linestring<P> L;\n\n    test_default_constructor<P, L>();\n    test_copy_constructor<P, L>();\n    test_copy_assignment<P, L>();\n    test_concept<L>();\n}\n\ntemplate <typename P>\nvoid test_custom_multi_linestring(bg::model::linestring<P> IL)\n{   \n    typedef bg::model::linestring<P> L;\n    \n    std::initializer_list<L> LIL = {IL};\n    bg::model::multi_linestring<L> ml1(LIL);\n    std::ostringstream out;\n    out << bg::dsv(ml1);\n    BOOST_CHECK_EQUAL(out.str(), \"(((1, 1), (2, 2), (3, 3), (0, 0), (0, 2), (0, 3)))\");\n}\n\ntemplate <typename P>\nvoid test_custom()\n{   \n#ifdef BOOST_NO_CXX11_HDR_INITIALIZER_LIST\n    std::initializer_list<P> IL1 = {P(1, 1), P(2, 2), P(3, 3)};\n    std::initializer_list<P> IL2 = {P(0, 0), P(0, 2), P(0, 3)};\n    bg::model::linestring<P> l1;\n    bg::append(l1, IL1);\n    bg::append(l1, IL2);\n    test_custom_multi_linestring<P>(l1);\n#endif//BOOST_NO_CXX11_HDR_INITIALIZER_LIST\n}\n\ntemplate <typename CS>\nvoid test_cs()\n{\n    test_all<bg::model::point<int, 2, CS> >();\n    test_all<bg::model::point<float, 2, CS> >();\n    test_all<bg::model::point<double, 2, CS> >();\n\n    test_custom<bg::model::point<double, 2, CS> >();\n}\n\n\nint test_main(int, char* [])\n{   \n    test_cs<bg::cs::cartesian>();\n    test_cs<bg::cs::spherical<bg::degree> >();\n    test_cs<bg::cs::spherical_equatorial<bg::degree> >();\n    test_cs<bg::cs::geographic<bg::degree> >();\n\n    test_custom<bg::model::d2::point_xy<double> >();\n\n    return 0;\n}\n", "meta": {"hexsha": "74ac3f5f7dc532fcf4916fc0056d4372ff3a28ce", "size": 4405, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/geometries/multi_linestring.cpp", "max_stars_repo_name": "jkerkela/geometry", "max_stars_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 326.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T13:47:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T02:13:59.000Z", "max_issues_repo_path": "test/geometries/multi_linestring.cpp", "max_issues_repo_name": "jkerkela/geometry", "max_issues_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 623.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T23:45:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T11:15:23.000Z", "max_forks_repo_path": "test/geometries/multi_linestring.cpp", "max_forks_repo_name": "jkerkela/geometry", "max_forks_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-01-14T15:50:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T03:58:36.000Z", "avg_line_length": 27.53125, "max_line_length": 87, "alphanum_fraction": 0.6951191827, "num_tokens": 1276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6406358411176238, "lm_q2_score": 0.7248702702332476, "lm_q1q2_score": 0.46437787527203583}}
{"text": "#include <iostream>\n#include <boost/program_options.hpp>\n\n#include \"distr.h\"\n#include \"management.h\"\n\nusing namespace std;\n\nnamespace po = boost::program_options;\n\nint main(int argc, char *argv[]) {\n    double mu;\n    double si;\n    uint32_t minconnections;\n\n    po::options_description desc(\"Allowed options\");\n    desc.add_options()\n            (\"help\", \"produce help message\")\n            (\"m\",po::value<double>(&mu)->default_value(4.5),\"initial \u00b5 of lognormal distribution\")\n            (\"s\",po::value<double>(&si)->default_value(1),\"initial sigma of lognormal distribution\")\n            (\"measures\",po::value<uint32_t>(&minconnections)->default_value(8),\"amount of required measurements\")\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 << endl;\n        return 1;\n    }\n\n    // preparation\n    distr sampledGuess(mu,si);\n\n    //distr formulaGuess(mu,si);\n\n    // Main Program\n    management mngr;\n    uint64_t counter = 0;\n    std::string line;\n    while(std::getline(std::cin,line)) {\n        size_t c1 = line.find(',');\n        size_t c2 = line.rfind(',');\n\n        auto timestamp = std::stoull(line.substr(0,c1));\n        // we do not need the host id\n        // auto hostid = line.substr(c1+1,c2-c1-1);\n        auto txid = line.substr(c2+1,line.length()-c2-1);\n\n        auto len = mngr.addTx(timestamp, txid);\n        if(len>= minconnections) {\n            auto measures = mngr.popTx(txid);\n\n            // adaption process\n            normalise(measures);\n            updateMuSampled(sampledGuess, measures, 100, 10);\n            //updateMuFormula(formulaGuess, measures);\n\n            updateSigma(sampledGuess, measures, sampledGuess.mu);\n            //updateSigma(formulaGuess, measures, formulaGuess.mu);\n\n            // output updated values\n            //cout << counter << \"\\t\";\n            cout << timestamp << \",\";\n            cout << sampledGuess.mu << \",\" << sampledGuess.si;\n            //cout << \"\\t|\\t\u00b5: \" << formulaGuess.mu << \" \\tsigma: \" << formulaGuess.si;\n            //cout << \",\" << txid;\n            cout << endl;\n            counter ++;\n        }\n    }\n\n    return 0;\n}", "meta": {"hexsha": "38a0f3ef99ef5c7c0093a5ed1fb27ac903266377", "size": 2224, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "vs-uulm/btcmon", "max_stars_repo_head_hexsha": "e3a5d0bd095299a11c7878c5142ce0d2491fca8d", "max_stars_repo_licenses": ["MIT"], "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": "vs-uulm/btcmon", "max_issues_repo_head_hexsha": "e3a5d0bd095299a11c7878c5142ce0d2491fca8d", "max_issues_repo_licenses": ["MIT"], "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": "vs-uulm/btcmon", "max_forks_repo_head_hexsha": "e3a5d0bd095299a11c7878c5142ce0d2491fca8d", "max_forks_repo_licenses": ["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.6533333333, "max_line_length": 113, "alphanum_fraction": 0.568794964, "num_tokens": 540, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6150878555160666, "lm_q1q2_score": 0.46433904036934903}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2015 NumScale SAS\n  @copyright 2015 J.T. Lapreste\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_COMMON_GENERIC_FUNCTION_IDIVROUND_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_GENERIC_FUNCTION_IDIVROUND_HPP_INCLUDED\n\n#include <boost/simd/function/divides.hpp>\n#include <boost/simd/function/divround.hpp>\n#include <boost/simd/function/iround.hpp>\n#include <boost/dispatch/function/overload.hpp>\n#include <boost/dispatch/meta/as_integer.hpp>\n#include <boost/config.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  BOOST_DISPATCH_OVERLOAD ( idivround_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::generic_< bd::arithmetic_<A0> >\n                          , bd::generic_< bd::arithmetic_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() ( A0 const& a0, A0 const& a1) const BOOST_NOEXCEPT\n    {\n      return divround(a0, a1);\n    }\n  };\n\n#ifdef BOOST_MSVC\n#pragma warning(push)\n#pragma warning(disable: 4723) // potential divide by 0\n#endif\n\n  BOOST_DISPATCH_OVERLOAD ( idivround_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::generic_< bd::floating_<A0> >\n                          , bd::generic_< bd::floating_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE bd::as_integer_t<A0> operator() ( A0 const& a0, A0 const& a1) const BOOST_NOEXCEPT\n    {\n      return iround(a0/a1);\n    }\n  };\n\n#ifdef BOOST_MSVC\n#pragma warning(pop)\n#endif\n\n} } }\n#endif\n", "meta": {"hexsha": "4ff4fcc6698ee8495437f96fd399f3e2b468be02", "size": 1907, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arch/common/generic/function/idivround.hpp", "max_stars_repo_name": "yaeldarmon/boost.simd", "max_stars_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/simd/arch/common/generic/function/idivround.hpp", "max_issues_repo_name": "yaeldarmon/boost.simd", "max_issues_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/arch/common/generic/function/idivround.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": 30.7580645161, "max_line_length": 104, "alphanum_fraction": 0.5500786576, "num_tokens": 423, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.46433904036934903}}
{"text": "// SPDX-License-Identifier: MIT\n// SPDX-FileCopyrightText: Copyright 2019-2021 Heal Research\n\n#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN\n#include <doctest/doctest.h>\n\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics.hpp>\n\n#define ANKERL_NANOBENCH_IMPLEMENT\n#include \"nanobench.h\"\n\n#include <iostream>\n#include <memory>\n#include <random>\n#include <vector>\n\n#include \"gsl/gsl_statistics_double.h\"\n#include \"gsl/gsl_statistics_float.h\"\n\n#include <chrono>\n\n#include \"vstat/vstat.hpp\"\n\n#include \"Statistics.h\"\n\nnamespace ba = boost::accumulators;\nnamespace nb = ankerl::nanobench;\n\nstruct Foo {\n    double value;\n};\n\nTEST_SUITE(\"usage\")\n{\n    TEST_CASE(\"univariate\")\n    {\n        std::vector<float> values { 1.0, 2.0, 3.0, 4.0 };\n        std::vector<float> weights { 2.0, 4.0, 6.0, 8.0 };\n\n        SUBCASE(\"batch\")\n        {\n            auto stats = univariate::accumulate<float>(values.begin(), values.end());\n            std::cout << \"stats:\\n\"\n                      << stats << \"\\n\";\n        }\n\n        SUBCASE(\"batch weighted\")\n        {\n            auto stats = univariate::accumulate<float>(values.begin(), values.end(), weights.begin());\n            std::cout << \"stats:\\n\"\n                      << stats << \"\\n\";\n        }\n\n        SUBCASE(\"batch projection\")\n        {\n            struct Foo {\n                float value;\n            };\n\n            Foo foos[] = { { 1 }, { 3 }, { 5 }, { 2 }, { 8 } };\n            auto stats = univariate::accumulate<float>(foos, std::size(foos), [](auto const& foo) { return foo.value; });\n            std::cout << \"stats:\\n\"\n                      << stats << \"\\n\";\n        }\n\n        SUBCASE(\"batch binary op projection\")\n        {\n            auto stats = univariate::accumulate<float>(values.begin(), values.end(), weights.begin(), [](auto v, auto w) { return (v - w) * (v - w); });\n            std::cout << \"stats:\\n\"\n                      << stats << \"\\n\";\n        }\n\n        SUBCASE(\"accumulator\")\n        {\n            univariate_accumulator<float> acc(1.0);\n            acc(2.0);\n            acc(3.0);\n            acc(4.0);\n            auto stats = univariate_statistics(acc);\n            std::cout << \"stats:\\n\"\n                      << stats << \"\\n\";\n        }\n\n        SUBCASE(\"accumulator weighted\")\n        {\n            univariate_accumulator<float> acc(1.0, 2.0);\n            acc(2.0, 4.0);\n            acc(3.0, 6.0);\n            auto stats = univariate_statistics(acc);\n            std::cout << \"stats:\\n\"\n                      << stats << \"\\n\";\n        }\n    }\n\n    TEST_CASE(\"bivariate\")\n    {\n        float x[] = { 1., 1., 2., 6. };\n        float y[] = { 2., 4., 3., 1. };\n        size_t n = std::size(x);\n\n        SUBCASE(\"batch\")\n        {\n            auto stats = bivariate::accumulate<float>(x, y, n);\n            std::cout << \"stats:\\n\"\n                      << stats << \"\\n\";\n        }\n\n        SUBCASE(\"batch projection\")\n        {\n            struct Foo {\n                float value;\n            };\n\n            struct Bar {\n                int value;\n            };\n\n            Foo foos[] = { { 1 }, { 3 }, { 5 }, { 2 }, { 8 } };\n            Bar bars[] = { { 3 }, { 2 }, { 1 }, { 4 }, { 11 } };\n\n            auto stats = bivariate::accumulate<float>(\n                foos, bars, std::size(foos), [](auto const& foo) { return foo.value; }, [](auto const& bar) { return bar.value; });\n            std::cout << \"stats:\\n\"\n                      << stats << \"\\n\";\n        }\n\n        SUBCASE(\"accumulator\")\n        {\n            bivariate_accumulator<float> acc(x[0], y[0]);\n            for (size_t i = 1; i < n; ++i) {\n                acc(x[i], y[i]);\n            }\n            bivariate_statistics stats(acc);\n            std::cout << \"stats:\\n\"\n                      << stats << \"\\n\";\n        }\n    }\n}\n\nTEST_SUITE(\"correctness\")\n{\n    TEST_CASE(\"univariate\")\n    {\n        const int n = int(1e6);\n\n        std::vector<float> xf(n);\n        std::vector<double> xd(n);\n\n        std::vector<float> yf(n);\n        std::vector<double> yd(n);\n\n        std::vector<float> wf(n);\n        std::vector<double> wd(n);\n\n        std::default_random_engine rng(1234);\n        std::uniform_real_distribution<double> dist(-1, 1);\n\n        std::generate(xd.begin(), xd.end(), [&]() { return dist(rng); });\n        std::generate(yd.begin(), yd.end(), [&]() { return dist(rng); });\n\n        std::copy(xd.begin(), xd.end(), xf.begin());\n        std::copy(yd.begin(), yd.end(), yf.begin());\n\n        std::vector<Foo> ff(n);\n        for (int i = 0; i < n; ++i) {\n            ff[i].value = xd[i];\n        }\n\n        auto gsl_var_flt = gsl_stats_float_variance(xf.data(), 1, xf.size());\n        auto gsl_mean_flt = gsl_stats_float_mean(xf.data(), 1, xf.size());\n\n        SUBCASE(\"float\")\n        {\n            auto stats = univariate::accumulate<float>(xd.begin(), xd.end(), detail::identity {});\n            CHECK(std::abs(stats.mean - gsl_mean_flt) < 1e-6);\n            CHECK(std::abs(stats.variance - gsl_var_flt) < 1e-5);\n        }\n\n        SUBCASE(\"float weighted\")\n        {\n            // now test the weighted version with weights set to 1\n            std::fill(wf.begin(), wf.end(), 1.0);\n            auto stats = univariate::accumulate<float>(xf.begin(), xf.end(), wf.begin());\n            CHECK(std::abs(stats.mean - gsl_mean_flt) < 1e-6);\n            CHECK(std::abs(stats.variance - gsl_var_flt) < 1e-5);\n\n            std::fill(wf.begin(), wf.end(), 0.2);\n            auto gsl_wmean_flt = gsl_stats_float_wmean(wf.data(), 1, xf.data(), 1, n);\n            auto gsl_wvar_flt = gsl_stats_float_wvariance(wf.data(), 1, xf.data(), 1, n);\n            stats = univariate::accumulate<float>(xf.begin(), xf.end(), wf.begin());\n            CHECK(std::abs(stats.mean - gsl_wmean_flt) < 1e-5);\n            CHECK(std::abs(stats.variance - gsl_wvar_flt) < 1e-5);\n\n            ba::accumulator_set<float, ba::stats<ba::tag::weighted_variance>, float> acc;\n            for (size_t i = 0; i < n; ++i) {\n                acc(xf[i], ba::weight = wf[i]);\n            }\n            auto ba_wvar_flt = ba::weighted_variance(acc);\n            CHECK(std::abs(ba_wvar_flt - gsl_wvar_flt) < 1e-6);\n\n            float x[] { 2, 2, 4, 5, 5, 5 };\n            float y[] { 2, 4, 5 };\n            float w[] { 2, 1, 3 };\n\n            auto stats1 = univariate::accumulate<float>(x, std::size(x));\n            auto stats2 = univariate::accumulate<float>(y, w, std::size(y));\n            CHECK(stats1.mean == stats2.mean);\n            CHECK(std::abs(stats1.variance - stats2.variance) < 1e-5);\n\n            univariate_accumulator<float> a1(x[0]);\n            univariate_accumulator<float> a2(y[0], w[0]);\n            for (size_t i = 1; i < std::size(x); ++i)\n                a1(x[i]);\n            for (size_t i = 1; i < std::size(y); ++i)\n                a2(y[i], w[i]);\n            CHECK(std::abs(univariate_statistics(a1).variance - univariate_statistics(a2).variance) < 1e-6);\n\n            auto stats3 = univariate::accumulate<float>(y, w, std::size(y), std::multiplies<float> {});\n            CHECK(stats3.sum == stats2.sum);\n        }\n\n        SUBCASE(\"double\")\n        {\n            auto gsl_var_dbl = gsl_stats_variance(xd.data(), 1, xd.size());\n            auto gsl_mean_dbl = gsl_stats_mean(xd.data(), 1, xd.size());\n            auto stats = univariate::accumulate<double>(xd.begin(), xd.end(), detail::identity {});\n            CHECK(std::abs(stats.mean - gsl_mean_dbl) < 1e-6);\n            CHECK(std::abs(stats.variance - gsl_var_dbl) < 1e-6);\n        }\n    }\n\n    TEST_CASE(\"bivariate\")\n    {\n        const int n = int(1e6);\n\n        std::vector<float> xf(n);\n        std::vector<double> xd(n);\n\n        std::vector<float> yf(n);\n        std::vector<double> yd(n);\n\n        std::vector<float> wf(n);\n        std::vector<double> wd(n);\n\n        std::default_random_engine rng(1234);\n        std::uniform_real_distribution<double> dist(-1, 1);\n\n        std::generate(xd.begin(), xd.end(), [&]() { return dist(rng); });\n        std::generate(yd.begin(), yd.end(), [&]() { return dist(rng); });\n\n        std::copy(xd.begin(), xd.end(), xf.begin());\n        std::copy(yd.begin(), yd.end(), yf.begin());\n\n        std::vector<Foo> ff(n);\n        for (int i = 0; i < n; ++i) {\n            ff[i].value = xd[i];\n        }\n\n        auto gsl_corr_flt = gsl_stats_float_correlation(xf.data(), 1, yf.data(), 1, n);\n        auto gsl_corr_dbl = gsl_stats_correlation(xd.data(), 1, yd.data(), 1, n);\n\n        auto gsl_cov_flt = gsl_stats_float_covariance(xf.data(), 1, yf.data(), 1, n);\n        auto gsl_cov_dbl = gsl_stats_covariance(xd.data(), 1, yd.data(), 1, n);\n\n        auto bstats = bivariate::accumulate<float>(xd.begin(), xd.end(), yd.begin());\n        CHECK(std::abs(gsl_corr_flt - bstats.correlation) < 1e-6);\n        CHECK(std::abs(gsl_cov_flt - bstats.covariance) < 1e-6);\n\n        bstats = bivariate::accumulate<float>(xd.begin(), xd.end(), yd.begin());\n        CHECK(std::abs(gsl_corr_dbl - bstats.correlation) < 1e-6);\n        CHECK(std::abs(gsl_cov_dbl - bstats.covariance) < 1e-6);\n\n        auto stats_x = univariate::accumulate<float>(xd.begin(), xd.end());\n        auto stats_y = univariate::accumulate<float>(yd.begin(), yd.end());\n\n        CHECK(bstats.mean_x == stats_x.mean);\n        CHECK(bstats.mean_y == stats_y.mean);\n        CHECK(bstats.sum_x == stats_x.sum);\n        CHECK(bstats.sum_y == stats_y.sum);\n    }\n}\n\nTEST_SUITE(\"performance\")\n{\n    TEST_CASE(\"univariate\")\n    {\n        const int n = int(1e6);\n\n        std::vector<double> v1(n);\n        std::vector<double> v2(n);\n        std::vector<double> v3(n);\n        std::vector<float> u1(n);\n        std::vector<float> u2(n);\n        std::vector<float> u3(n);\n\n        auto *xd = v1.data();\n        auto *yd = v2.data();\n        auto *wd = v3.data();\n        auto *xf = u1.data();\n        auto *yf = u2.data();\n        auto *wf = u3.data();\n\n        std::default_random_engine rng(1234);\n        std::uniform_real_distribution<double> dist(-1, 1);\n\n        std::generate(xd, xd + n, [&]() { return dist(rng); });\n        std::generate(yd, yd + n, [&]() { return dist(rng); });\n        std::generate(wd, wd + n, [&]() { return dist(rng); });\n\n        std::copy(xd, xd + n, xf);\n        std::copy(yd, yd + n, yf);\n        std::copy(wd, wd + n, wf);\n\n        std::vector<Foo> ff(n);\n        for (int i = 0; i < n; ++i) {\n            ff[i].value = xd[i];\n        }\n\n        ankerl::nanobench::Bench b;\n        b.performanceCounters(true).minEpochIterations(100).batch(n);\n\n        // print some runtime stats for different data sizes\n        std::vector<int> sizes { 1000, 10000 };\n        int step = int(1e5);\n        for (int s = step; s <= n; s += step) {\n            sizes.push_back(s);\n        }\n\n        SUBCASE(\"vstat accumulator\")\n        {\n            double var, count;\n            for (auto s : sizes) {\n                var = count = 0;\n                b.batch(s).run(\"vstat acc variance float \" + std::to_string(s), [&]() {\n                    ++count;\n                    univariate_accumulator<Vec8f> acc(Vec8f().load(xf));\n                    constexpr auto sz = Vec8f::size();\n                    size_t m = s & (-sz);\n                    for (size_t i = sz; i < m; i += sz) {\n                        acc(Vec8f().load(xf + i));\n                    }\n                    var += univariate_statistics(acc).variance;\n                });\n            }\n\n            for (auto s : sizes) {\n                var = count = 0;\n                b.batch(s).run(\"vstat acc variance float weighted \" + std::to_string(s), [&]() {\n                    ++count;\n                    univariate_accumulator<Vec8f> acc(Vec8f().load(xf), Vec8f().load(wf));\n                    constexpr auto sz = Vec8f::size();\n                    size_t m = s & (-sz);\n                    for (size_t i = sz; i < m; i += sz) {\n                        acc(Vec8f().load(xf + i), Vec8f().load(wf + i));\n                    }\n                    var += univariate_statistics(acc).variance;\n                });\n            }\n\n            for (auto s : sizes) {\n                var = count = 0;\n                b.batch(s).run(\"vstat acc variance double \" + std::to_string(s), [&]() {\n                    ++count;\n                    univariate_accumulator<Vec4d> acc(Vec4d().load(xd));\n                    constexpr auto sz = Vec4d::size();\n                    size_t m = s & (-sz);\n                    for (size_t i = sz; i < m; i += sz) {\n                        acc(Vec4d().load(xd + i));\n                    }\n                    var += univariate_statistics(acc).variance;\n                });\n            }\n\n            for (auto s : sizes) {\n                var = count = 0;\n                b.batch(s).run(\"vstat acc variance double weighted \" + std::to_string(s), [&]() {\n                    ++count;\n                    univariate_accumulator<Vec4d> acc(Vec4d().load(xd), Vec4d().load(wd));\n                    constexpr auto sz = Vec4d::size();\n                    size_t m = s & (-sz);\n                    for (size_t i = sz; i < m; i += sz) {\n                        acc(Vec4d().load(xd + i), Vec4d().load(wd + i));\n                    }\n                    var += univariate_statistics(acc).variance;\n                });\n            }\n        }\n\n        SUBCASE(\"vstat\")\n        {\n            double var = 0, count = 0;\n            for (auto s : sizes) {\n                var = count = 0;\n                b.batch(s).run(\"vstat variance float \" + std::to_string(s), [&]() {\n                    ++count;\n                    var += univariate::accumulate<float>(xf, s).variance;\n                });\n            }\n\n            for (auto s : sizes) {\n                var = count = 0;\n                b.batch(s).run(\"vstat variance double \" + std::to_string(s), [&]() {\n                    ++count;\n                    var += univariate::accumulate<double>(xd, s).variance;\n                });\n            }\n        }\n\n        SUBCASE(\"vstat weighted\")\n        {\n            double var = 0, count = 0;\n            for (auto s : sizes) {\n                var = count = 0;\n                b.batch(s).run(\"vstat variance float weighted \" + std::to_string(s), [&]() {\n                    ++count;\n                    var += univariate::accumulate<float>(xf, wf, s).variance;\n                });\n            }\n\n            for (auto s : sizes) {\n                var = count = 0;\n                b.batch(s).run(\"vstat variance double weighted \" + std::to_string(s), [&]() {\n                    ++count;\n                    var += univariate::accumulate<double>(xd, wd, s).variance;\n                });\n            }\n        }\n\n        SUBCASE(\"linasm\")\n        {\n            double var = 0, count = 0;\n            for (auto s : sizes) {\n                var = count = 0;\n                b.batch(s).run(\"linasm variance float \" + std::to_string(s), [&]() {\n                    ++count;\n                    auto mean = Statistics::Mean(xf, s);\n                    var += Statistics::Variance(xf, s, mean);\n                });\n            }\n\n            for (auto s : sizes) {\n                b.batch(s).run(\"linasm variance double \" + std::to_string(s), [&]() {\n                    ++count;\n                    auto mean = Statistics::Mean(xd, s);\n                    var += Statistics::Variance(xd, s, mean);\n                });\n            }\n        }\n\n        SUBCASE(\"boost accumulators\")\n        {\n            double var = 0, count = 0;\n            for (auto s : sizes) {\n                var = count = 0;\n                b.batch(s).run(\"boost variance float \" + std::to_string(s), [&]() {\n                    ++count;\n                    ba::accumulator_set<float, ba::features<ba::tag::variance>> acc;\n                    for (int i = 0; i < s; ++i) {\n                        acc(xf[i]);\n                    }\n                    var += ba::variance(acc);\n                });\n            }\n\n            for (auto s : sizes) {\n                var = count = 0;\n                b.batch(s).run(\"boost variance double \" + std::to_string(s), [&]() {\n                    ++count;\n                    ba::accumulator_set<double, ba::features<ba::tag::variance>> acc;\n                    for (int i = 0; i < s; ++i) {\n                        acc(xd[i]);\n                    }\n                    var += ba::variance(acc);\n                });\n            }\n        }\n\n        SUBCASE(\"gsl\")\n        {\n            double var = 0, count = 0;\n            for (auto s : sizes) {\n                var = count = 0;\n                b.batch(s).run(\"gsl variance float \" + std::to_string(s), [&]() {\n                    ++count;\n                    var += gsl_stats_float_variance(xf, 1, s);\n                });\n            }\n\n            for (auto s : sizes) {\n                var = count = 0;\n                b.batch(s).run(\"gsl variance double \" + std::to_string(s), [&]() {\n                    ++count;\n                    var += gsl_stats_variance(xd, 1, s);\n                });\n            }\n        }\n    }\n\n    TEST_CASE(\"bivariate\")\n    {\n        const int n = int(1e6);\n\n        std::vector<double> v1(n), v2(n);\n        std::vector<float> u1(n), u2(n);\n\n        auto xd = v1.data();\n        auto yd = v2.data();\n        auto xf = u1.data();\n        auto yf = u2.data();\n\n        std::default_random_engine rng(1234);\n        std::uniform_real_distribution<double> dist(-1, 1);\n\n        std::generate(xd, xd + n, [&]() { return dist(rng); });\n        std::generate(yd, yd + n, [&]() { return dist(rng); });\n\n        std::copy(xd, xd + n, xf);\n        std::copy(yd, yd + n, yf);\n\n        std::vector<Foo> ff(n);\n        for (int i = 0; i < n; ++i) {\n            ff[i].value = xd[i];\n        }\n\n        ankerl::nanobench::Bench b;\n        b.performanceCounters(true).minEpochIterations(100).batch(n);\n\n        // print some runtime stats for different data sizes\n        std::vector<int> sizes { 1000, 10000 };\n        int step = int(1e5);\n        for (int s = step; s <= n; s += step) {\n            sizes.push_back(s);\n        }\n\n        SUBCASE(\"vstat\")\n        {\n            double var = 0, count = 0;\n            for (auto s : sizes) {\n                var = count = 0;\n                b.batch(s).run(\"vstat covariance float \" + std::to_string(s), [&]() {\n                    ++count;\n                    var += bivariate::accumulate<float>(xf, yf, s).covariance;\n                });\n            }\n\n            for (auto s : sizes) {\n                var = count = 0;\n                b.batch(s).run(\"vstat covariance double \" + std::to_string(s), [&]() {\n                    ++count;\n                    var += bivariate::accumulate<double>(xd, yd, s).covariance;\n                });\n            }\n        }\n\n        SUBCASE(\"vstat\")\n        {\n            double var = 0, count = 0;\n            var = count = 0;\n            for (auto s : sizes) {\n                var = count = 0;\n                b.batch(s).run(\"linasm covariance float \" + std::to_string(s), [&]() {\n                    ++count;\n                    auto xm = Statistics::Mean(xf, s);\n                    auto ym = Statistics::Mean(yf, s);\n                    var += Statistics::Covariance(xf, yf, s, xm, ym);\n                });\n            }\n\n            for (auto s : sizes) {\n                var = count = 0;\n                b.batch(s).run(\"linasm covariance double \" + std::to_string(s), [&]() {\n                    ++count;\n                    auto xm = Statistics::Mean(xd, s);\n                    auto ym = Statistics::Mean(yd, s);\n                    var += Statistics::Covariance(xd, yd, s, xm, ym);\n                });\n            }\n        }\n\n        SUBCASE(\"vstat\")\n        {\n            double var = 0, count = 0;\n            var = count = 0;\n            for (auto s : sizes) {\n                var = count = 0;\n                b.batch(s).run(\"boost covariance float \" + std::to_string(s), [&]() {\n                    ++count;\n                    ba::accumulator_set<float, ba::stats<ba::tag::covariance<float, ba::tag::covariate1>>> acc;\n                    for (int i = 0; i < s; ++i) {\n                        acc(xf[i], ba::covariate1 = yf[i]);\n                    }\n                    var += ba::covariance(acc);\n                });\n            }\n\n            for (auto s : sizes) {\n                var = count = 0;\n                b.batch(s).run(\"boost covariance double \" + std::to_string(s), [&]() {\n                    ++count;\n                    ba::accumulator_set<double, ba::stats<ba::tag::covariance<double, ba::tag::covariate1>>> acc;\n                    for (int i = 0; i < s; ++i) {\n                        acc(xd[i], ba::covariate1 = yd[i]);\n                    }\n                    var += ba::covariance(acc);\n                });\n            }\n        }\n\n        SUBCASE(\"vstat\")\n        {\n            double var = 0, count = 0;\n            var = count = 0;\n            for (auto s : sizes) {\n                var = count = 0;\n                b.batch(s).run(\"gsl covariance float \" + std::to_string(s), [&]() {\n                    ++count;\n                    var += gsl_stats_float_covariance(xf, 1, yf, 1, s);\n                });\n            }\n\n            for (auto s : sizes) {\n                var = count = 0;\n                b.batch(s).run(\"gsl covariance double \" + std::to_string(s), [&]() {\n                    ++count;\n                    var += gsl_stats_covariance(xd, 1, yd, 1, s);\n                });\n            }\n        }\n    }\n}\n", "meta": {"hexsha": "6a463d0b887b5b5a6c7f98016bc304204bdad9b4", "size": 21442, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/source/vstat_test.cpp", "max_stars_repo_name": "foolnotion/vstat", "max_stars_repo_head_hexsha": "e6d16e7ba279f5e8730328e69a80ffae442702e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2021-04-01T13:34:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-22T02:46:46.000Z", "max_issues_repo_path": "test/source/vstat_test.cpp", "max_issues_repo_name": "foolnotion/vstat", "max_issues_repo_head_hexsha": "e6d16e7ba279f5e8730328e69a80ffae442702e3", "max_issues_repo_licenses": ["MIT"], "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/source/vstat_test.cpp", "max_forks_repo_name": "foolnotion/vstat", "max_forks_repo_head_hexsha": "e6d16e7ba279f5e8730328e69a80ffae442702e3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-02T15:32:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-02T15:32:49.000Z", "avg_line_length": 33.9272151899, "max_line_length": 152, "alphanum_fraction": 0.4416099244, "num_tokens": 5475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6150878555160666, "lm_q1q2_score": 0.46433904036934903}}
{"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 <Eigen/Dense>\n#include <queue>\n#include <tuple>\n\n#include \"open3d/geometry/TriangleMesh.h\"\n#include \"open3d/utility/Console.h\"\n\nnamespace open3d {\nnamespace geometry {\n\n/// Error quadric that is used to minimize the squared distance of a point to\n/// its neigbhouring triangle planes.\n/// Cf. \"Simplifying Surfaces with Color and Texture using Quadric Error\n/// Metrics\" by Garland and Heckbert.\nclass Quadric {\npublic:\n    Quadric() {\n        A_.fill(0);\n        b_.fill(0);\n        c_ = 0;\n    }\n\n    Quadric(const Eigen::Vector4d& plane, double weight = 1) {\n        Eigen::Vector3d n = plane.head<3>();\n        A_ = weight * n * n.transpose();\n        b_ = weight * plane(3) * n;\n        c_ = weight * plane(3) * plane(3);\n    }\n\n    Quadric& operator+=(const Quadric& other) {\n        A_ += other.A_;\n        b_ += other.b_;\n        c_ += other.c_;\n        return *this;\n    }\n\n    Quadric operator+(const Quadric& other) const {\n        Quadric res;\n        res.A_ = A_ + other.A_;\n        res.b_ = b_ + other.b_;\n        res.c_ = c_ + other.c_;\n        return res;\n    }\n\n    double Eval(const Eigen::Vector3d& v) const {\n        Eigen::Vector3d Av = A_ * v;\n        double q = v.dot(Av) + 2 * b_.dot(v) + c_;\n        return q;\n    }\n\n    bool IsInvertible() const { return std::fabs(A_.determinant()) > 1e-4; }\n\n    Eigen::Vector3d Minimum() const { return -A_.ldlt().solve(b_); }\n\npublic:\n    /// A_ = n . n^T, where n is the plane normal\n    Eigen::Matrix3d A_;\n    /// b_ = d . n, where n is the plane normal and d the non-normal component\n    /// of the plane parameters\n    Eigen::Vector3d b_;\n    /// c_ = d . d, where d the non-normal component pf the plane parameters\n    double c_;\n};\n\nstd::shared_ptr<TriangleMesh> TriangleMesh::SimplifyVertexClustering(\n        double voxel_size,\n        SimplificationContraction\n                contraction /* = SimplificationContraction::Average */) const {\n    if (HasTriangleUvs()) {\n        utility::LogWarning(\n                \"[SimplifyVertexClustering] This mesh contains triangle uvs \"\n                \"that are not handled in this function\");\n    }\n    auto mesh = std::make_shared<TriangleMesh>();\n    if (voxel_size <= 0.0) {\n        utility::LogError(\"[VoxelGridFromPointCloud] voxel_size <= 0.0\");\n    }\n\n    Eigen::Vector3d voxel_size3 =\n            Eigen::Vector3d(voxel_size, voxel_size, voxel_size);\n    Eigen::Vector3d voxel_min_bound = GetMinBound() - voxel_size3 * 0.5;\n    Eigen::Vector3d voxel_max_bound = GetMaxBound() + voxel_size3 * 0.5;\n    if (voxel_size * std::numeric_limits<int>::max() <\n        (voxel_max_bound - voxel_min_bound).maxCoeff()) {\n        utility::LogError(\"[VoxelGridFromPointCloud] voxel_size is too small.\");\n    }\n\n    auto GetVoxelIdx = [&](const Eigen::Vector3d& vert) {\n        Eigen::Vector3d ref_coord = (vert - voxel_min_bound) / voxel_size;\n        Eigen::Vector3i idx(int(floor(ref_coord(0))), int(floor(ref_coord(1))),\n                            int(floor(ref_coord(2))));\n        return idx;\n    };\n\n    std::unordered_map<Eigen::Vector3i, std::unordered_set<int>,\n                       utility::hash_eigen<Eigen::Vector3i>>\n            voxel_vertices;\n    std::unordered_map<Eigen::Vector3i, int,\n                       utility::hash_eigen<Eigen::Vector3i>>\n            voxel_vert_ind;\n    int new_vidx = 0;\n    for (size_t vidx = 0; vidx < vertices_.size(); ++vidx) {\n        const Eigen::Vector3i vox_idx = GetVoxelIdx(vertices_[vidx]);\n        voxel_vertices[vox_idx].insert(int(vidx));\n\n        if (voxel_vert_ind.count(vox_idx) == 0) {\n            voxel_vert_ind[vox_idx] = new_vidx;\n            new_vidx++;\n        }\n    }\n\n    // aggregate vertex info\n    bool has_vert_normal = HasVertexNormals();\n    bool has_vert_color = HasVertexColors();\n    mesh->vertices_.resize(voxel_vertices.size());\n    if (has_vert_normal) {\n        mesh->vertex_normals_.resize(voxel_vertices.size());\n    }\n    if (has_vert_color) {\n        mesh->vertex_colors_.resize(voxel_vertices.size());\n    }\n\n    auto AvgVertex = [&](const std::unordered_set<int> ind) {\n        Eigen::Vector3d aggr(0, 0, 0);\n        for (int vidx : ind) {\n            aggr += vertices_[vidx];\n        }\n        aggr /= double(ind.size());\n        return aggr;\n    };\n    auto AvgNormal = [&](const std::unordered_set<int> ind) {\n        Eigen::Vector3d aggr(0, 0, 0);\n        for (int vidx : ind) {\n            aggr += vertex_normals_[vidx];\n        }\n        aggr /= double(ind.size());\n        return aggr;\n    };\n    auto AvgColor = [&](const std::unordered_set<int> ind) {\n        Eigen::Vector3d aggr(0, 0, 0);\n        for (int vidx : ind) {\n            aggr += vertex_colors_[vidx];\n        }\n        aggr /= double(ind.size());\n        return aggr;\n    };\n\n    if (contraction == SimplificationContraction::Average) {\n        for (const auto& voxel : voxel_vertices) {\n            int vox_vidx = voxel_vert_ind[voxel.first];\n            mesh->vertices_[vox_vidx] = AvgVertex(voxel.second);\n            if (has_vert_normal) {\n                mesh->vertex_normals_[vox_vidx] = AvgNormal(voxel.second);\n            }\n            if (has_vert_color) {\n                mesh->vertex_colors_[vox_vidx] = AvgColor(voxel.second);\n            }\n        }\n    } else if (contraction == SimplificationContraction::Quadric) {\n        // Map triangles\n        std::unordered_map<int, std::unordered_set<int>> vert_to_triangles;\n        for (size_t tidx = 0; tidx < triangles_.size(); ++tidx) {\n            vert_to_triangles[triangles_[tidx](0)].emplace(int(tidx));\n            vert_to_triangles[triangles_[tidx](1)].emplace(int(tidx));\n            vert_to_triangles[triangles_[tidx](2)].emplace(int(tidx));\n        }\n\n        for (const auto& voxel : voxel_vertices) {\n            int vox_vidx = voxel_vert_ind[voxel.first];\n\n            Quadric q;\n            for (int vidx : voxel.second) {\n                for (int tidx : vert_to_triangles[vidx]) {\n                    Eigen::Vector4d p = GetTrianglePlane(tidx);\n                    double area = GetTriangleArea(tidx);\n                    q += Quadric(p, area);\n                }\n            }\n            if (q.IsInvertible()) {\n                Eigen::Vector3d v = q.Minimum();\n                mesh->vertices_[vox_vidx] = v;\n            } else {\n                mesh->vertices_[vox_vidx] = AvgVertex(voxel.second);\n            }\n\n            if (has_vert_normal) {\n                mesh->vertex_normals_[vox_vidx] = AvgNormal(voxel.second);\n            }\n            if (has_vert_color) {\n                mesh->vertex_colors_[vox_vidx] = AvgColor(voxel.second);\n            }\n        }\n    }\n\n    //  connect vertices\n    std::unordered_set<Eigen::Vector3i, utility::hash_eigen<Eigen::Vector3i>>\n            triangles;\n    for (const auto& triangle : triangles_) {\n        int vidx0 = voxel_vert_ind[GetVoxelIdx(vertices_[triangle(0)])];\n        int vidx1 = voxel_vert_ind[GetVoxelIdx(vertices_[triangle(1)])];\n        int vidx2 = voxel_vert_ind[GetVoxelIdx(vertices_[triangle(2)])];\n\n        // only connect if in different voxels\n        if (vidx0 == vidx1 || vidx0 == vidx2 || vidx1 == vidx2) {\n            continue;\n        }\n\n        // Note: there can be still double faces with different orientation\n        // The user has to clean up manually\n        if (vidx1 < vidx0 && vidx1 < vidx2) {\n            int tmp = vidx0;\n            vidx0 = vidx1;\n            vidx1 = vidx2;\n            vidx2 = tmp;\n        } else if (vidx2 < vidx0 && vidx2 < vidx1) {\n            int tmp = vidx1;\n            vidx1 = vidx0;\n            vidx0 = vidx2;\n            vidx2 = tmp;\n        }\n\n        triangles.emplace(Eigen::Vector3i(vidx0, vidx1, vidx2));\n    }\n\n    mesh->triangles_.resize(triangles.size());\n    int tidx = 0;\n    for (const Eigen::Vector3i& triangle : triangles) {\n        mesh->triangles_[tidx] = triangle;\n        tidx++;\n    }\n\n    if (HasTriangleNormals()) {\n        mesh->ComputeTriangleNormals();\n    }\n\n    return mesh;\n}\n\nstd::shared_ptr<TriangleMesh> TriangleMesh::SimplifyQuadricDecimation(\n        int target_number_of_triangles) const {\n    if (HasTriangleUvs()) {\n        utility::LogWarning(\n                \"[SimplifyQuadricDecimation] This mesh contains triangle uvs \"\n                \"that are not handled in this function\");\n    }\n    typedef std::tuple<double, int, int> CostEdge;\n\n    auto mesh = std::make_shared<TriangleMesh>();\n    mesh->vertices_ = vertices_;\n    mesh->vertex_normals_ = vertex_normals_;\n    mesh->vertex_colors_ = vertex_colors_;\n    mesh->triangles_ = triangles_;\n\n    std::vector<bool> vertices_deleted(vertices_.size(), false);\n    std::vector<bool> triangles_deleted(triangles_.size(), false);\n\n    // Map vertices to triangles and compute triangle planes and areas\n    std::vector<std::unordered_set<int>> vert_to_triangles(vertices_.size());\n    std::vector<Eigen::Vector4d> triangle_planes(triangles_.size());\n    std::vector<double> triangle_areas(triangles_.size());\n    for (size_t tidx = 0; tidx < triangles_.size(); ++tidx) {\n        vert_to_triangles[triangles_[tidx](0)].emplace(static_cast<int>(tidx));\n        vert_to_triangles[triangles_[tidx](1)].emplace(static_cast<int>(tidx));\n        vert_to_triangles[triangles_[tidx](2)].emplace(static_cast<int>(tidx));\n\n        triangle_planes[tidx] = GetTrianglePlane(tidx);\n        triangle_areas[tidx] = GetTriangleArea(tidx);\n    }\n\n    // Compute the error metric per vertex\n    std::vector<Quadric> Qs(vertices_.size());\n    for (size_t vidx = 0; vidx < vertices_.size(); ++vidx) {\n        for (int tidx : vert_to_triangles[vidx]) {\n            Qs[vidx] += Quadric(triangle_planes[tidx], triangle_areas[tidx]);\n        }\n    }\n\n    // For boundary edges add perpendicular plane quadric\n    auto edge_triangle_count = GetEdgeToTrianglesMap();\n    auto AddPerpPlaneQuadric = [&](int vidx0, int vidx1, int vidx2,\n                                   double area) {\n        int min = std::min(vidx0, vidx1);\n        int max = std::max(vidx0, vidx1);\n        Eigen::Vector2i edge(min, max);\n        if (edge_triangle_count[edge].size() != 1) {\n            return;\n        }\n        const auto& vert0 = mesh->vertices_[vidx0];\n        const auto& vert1 = mesh->vertices_[vidx1];\n        const auto& vert2 = mesh->vertices_[vidx2];\n        Eigen::Vector3d vert2p = (vert2 - vert0).cross(vert2 - vert1);\n        Eigen::Vector4d plane = ComputeTrianglePlane(vert0, vert1, vert2p);\n        Quadric quad(plane, area);\n        Qs[vidx0] += quad;\n        Qs[vidx1] += quad;\n    };\n    for (size_t tidx = 0; tidx < triangles_.size(); ++tidx) {\n        const auto& tria = triangles_[tidx];\n        double area = triangle_areas[tidx];\n        AddPerpPlaneQuadric(tria(0), tria(1), tria(2), area);\n        AddPerpPlaneQuadric(tria(1), tria(2), tria(0), area);\n        AddPerpPlaneQuadric(tria(2), tria(0), tria(1), area);\n    }\n\n    // Get valid edges and compute cost\n    // Note: We could also select all vertex pairs as edges with dist < eps\n    std::unordered_map<Eigen::Vector2i, Eigen::Vector3d,\n                       utility::hash_eigen<Eigen::Vector2i>>\n            vbars;\n    std::unordered_map<Eigen::Vector2i, double,\n                       utility::hash_eigen<Eigen::Vector2i>>\n            costs;\n    auto CostEdgeComp = [](const CostEdge& a, const CostEdge& b) {\n        return std::get<0>(a) > std::get<0>(b);\n    };\n    std::priority_queue<CostEdge, std::vector<CostEdge>, decltype(CostEdgeComp)>\n            queue(CostEdgeComp);\n\n    auto AddEdge = [&](int vidx0, int vidx1, bool update) {\n        int min = std::min(vidx0, vidx1);\n        int max = std::max(vidx0, vidx1);\n        Eigen::Vector2i edge(min, max);\n        if (update || vbars.count(edge) == 0) {\n            const Quadric& Q0 = Qs[min];\n            const Quadric& Q1 = Qs[max];\n            Quadric Qbar = Q0 + Q1;\n            double cost;\n            Eigen::Vector3d vbar;\n            if (Qbar.IsInvertible()) {\n                vbar = Qbar.Minimum();\n                cost = Qbar.Eval(vbar);\n            } else {\n                const Eigen::Vector3d& v0 = mesh->vertices_[vidx0];\n                const Eigen::Vector3d& v1 = mesh->vertices_[vidx0];\n                Eigen::Vector3d vmid = (v0 + v1) / 2;\n                double cost0 = Qbar.Eval(v0);\n                double cost1 = Qbar.Eval(v1);\n                double costmid = Qbar.Eval(vbar);\n                cost = std::min(cost0, std::min(cost1, costmid));\n                if (cost == costmid) {\n                    vbar = vmid;\n                } else if (cost == cost0) {\n                    vbar = v0;\n                } else {\n                    vbar = v1;\n                }\n            }\n            vbars[edge] = vbar;\n            costs[edge] = cost;\n            queue.push(CostEdge(cost, min, max));\n        }\n    };\n\n    // add all edges to priority queue\n    for (const auto& triangle : triangles_) {\n        AddEdge(triangle(0), triangle(1), false);\n        AddEdge(triangle(1), triangle(2), false);\n        AddEdge(triangle(2), triangle(0), false);\n    }\n\n    // perform incremental edge collapse\n    bool has_vert_normal = HasVertexNormals();\n    bool has_vert_color = HasVertexColors();\n    int n_triangles = int(triangles_.size());\n    while (n_triangles > target_number_of_triangles && !queue.empty()) {\n        // retrieve edge from queue\n        double cost;\n        int vidx0, vidx1;\n        std::tie(cost, vidx0, vidx1) = queue.top();\n        queue.pop();\n\n        // test if the edge has been updated (reinserted into queue)\n        Eigen::Vector2i edge(vidx0, vidx1);\n        bool valid = !vertices_deleted[vidx0] && !vertices_deleted[vidx1] &&\n                     cost == costs[edge];\n        if (!valid) {\n            continue;\n        }\n\n        // avoid flip of triangle normal\n        bool flipped = false;\n        for (int tidx : vert_to_triangles[vidx1]) {\n            if (triangles_deleted[tidx]) {\n                continue;\n            }\n\n            const Eigen::Vector3i& tria = mesh->triangles_[tidx];\n            bool has_vidx0 =\n                    vidx0 == tria(0) || vidx0 == tria(1) || vidx0 == tria(2);\n            bool has_vidx1 =\n                    vidx1 == tria(0) || vidx1 == tria(1) || vidx1 == tria(2);\n            if (has_vidx0 && has_vidx1) {\n                continue;\n            }\n\n            Eigen::Vector3d vert0 = mesh->vertices_[tria(0)];\n            Eigen::Vector3d vert1 = mesh->vertices_[tria(1)];\n            Eigen::Vector3d vert2 = mesh->vertices_[tria(2)];\n            Eigen::Vector3d norm_before = (vert1 - vert0).cross(vert2 - vert0);\n            norm_before /= norm_before.norm();\n\n            if (vidx1 == tria(0)) {\n                vert0 = vbars[edge];\n            } else if (vidx1 == tria(1)) {\n                vert1 = vbars[edge];\n            } else if (vidx1 == tria(2)) {\n                vert2 = vbars[edge];\n            }\n\n            Eigen::Vector3d norm_after = (vert1 - vert0).cross(vert2 - vert0);\n            norm_after /= norm_after.norm();\n            if (norm_before.dot(norm_after) < 0) {\n                flipped = true;\n                break;\n            }\n        }\n        if (flipped) {\n            continue;\n        }\n\n        // Connect triangles from vidx1 to vidx0, or mark deleted\n        for (int tidx : vert_to_triangles[vidx1]) {\n            if (triangles_deleted[tidx]) {\n                continue;\n            }\n\n            Eigen::Vector3i& tria = mesh->triangles_[tidx];\n            bool has_vidx0 =\n                    vidx0 == tria(0) || vidx0 == tria(1) || vidx0 == tria(2);\n            bool has_vidx1 =\n                    vidx1 == tria(0) || vidx1 == tria(1) || vidx1 == tria(2);\n\n            if (has_vidx0 && has_vidx1) {\n                triangles_deleted[tidx] = true;\n                n_triangles--;\n                continue;\n            }\n\n            if (vidx1 == tria(0)) {\n                tria(0) = vidx0;\n            } else if (vidx1 == tria(1)) {\n                tria(1) = vidx0;\n            } else if (vidx1 == tria(2)) {\n                tria(2) = vidx0;\n            }\n            vert_to_triangles[vidx0].insert(tidx);\n        }\n\n        // update vertex vidx0 to vbar\n        mesh->vertices_[vidx0] = vbars[edge];\n        Qs[vidx0] += Qs[vidx1];\n        if (has_vert_normal) {\n            mesh->vertex_normals_[vidx0] = 0.5 * (mesh->vertex_normals_[vidx0] +\n                                                  mesh->vertex_normals_[vidx1]);\n        }\n        if (has_vert_color) {\n            mesh->vertex_colors_[vidx0] = 0.5 * (mesh->vertex_colors_[vidx0] +\n                                                 mesh->vertex_colors_[vidx1]);\n        }\n        vertices_deleted[vidx1] = true;\n\n        // Update edge costs for all triangles connecting to vidx0\n        for (const auto& tidx : vert_to_triangles[vidx0]) {\n            if (triangles_deleted[tidx]) {\n                continue;\n            }\n            const Eigen::Vector3i& tria = mesh->triangles_[tidx];\n            if (tria(0) == vidx0 || tria(1) == vidx0) {\n                AddEdge(tria(0), tria(1), true);\n            }\n            if (tria(1) == vidx0 || tria(2) == vidx0) {\n                AddEdge(tria(1), tria(2), true);\n            }\n            if (tria(2) == vidx0 || tria(0) == vidx0) {\n                AddEdge(tria(2), tria(0), true);\n            }\n        }\n    }\n\n    // Apply changes to the triangle mesh\n    int next_free = 0;\n    std::unordered_map<int, int> vert_remapping;\n    for (size_t idx = 0; idx < mesh->vertices_.size(); ++idx) {\n        if (!vertices_deleted[idx]) {\n            vert_remapping[int(idx)] = next_free;\n            mesh->vertices_[next_free] = mesh->vertices_[idx];\n            if (has_vert_normal) {\n                mesh->vertex_normals_[next_free] = mesh->vertex_normals_[idx];\n            }\n            if (has_vert_color) {\n                mesh->vertex_colors_[next_free] = mesh->vertex_colors_[idx];\n            }\n            next_free++;\n        }\n    }\n    mesh->vertices_.resize(next_free);\n    if (has_vert_normal) {\n        mesh->vertex_normals_.resize(next_free);\n    }\n    if (has_vert_color) {\n        mesh->vertex_colors_.resize(next_free);\n    }\n\n    next_free = 0;\n    for (size_t idx = 0; idx < mesh->triangles_.size(); ++idx) {\n        if (!triangles_deleted[idx]) {\n            Eigen::Vector3i tria = mesh->triangles_[idx];\n            mesh->triangles_[next_free](0) = vert_remapping[tria(0)];\n            mesh->triangles_[next_free](1) = vert_remapping[tria(1)];\n            mesh->triangles_[next_free](2) = vert_remapping[tria(2)];\n            next_free++;\n        }\n    }\n    mesh->triangles_.resize(next_free);\n\n    if (HasTriangleNormals()) {\n        mesh->ComputeTriangleNormals();\n    }\n\n    return mesh;\n}\n\n}  // namespace geometry\n}  // namespace open3d\n", "meta": {"hexsha": "33322c97689b92cf514f29c5f1b41b0c3d4e4f2d", "size": 20223, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/open3d/geometry/TriangleMeshSimplification.cpp", "max_stars_repo_name": "LearnCV/Open3D", "max_stars_repo_head_hexsha": "5eee42b57571c85cf35800014cdd74cf9880c081", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cpp/open3d/geometry/TriangleMeshSimplification.cpp", "max_issues_repo_name": "LearnCV/Open3D", "max_issues_repo_head_hexsha": "5eee42b57571c85cf35800014cdd74cf9880c081", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp/open3d/geometry/TriangleMeshSimplification.cpp", "max_forks_repo_name": "LearnCV/Open3D", "max_forks_repo_head_hexsha": "5eee42b57571c85cf35800014cdd74cf9880c081", "max_forks_repo_licenses": ["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.7023593466, "max_line_length": 80, "alphanum_fraction": 0.5546654799, "num_tokens": 5282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.464339040369349}}
{"text": "#define BOOST_TEST_MODULE SolutionTest\n\n#include \"solution.hpp\"\n\n#define BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n\nBOOST_AUTO_TEST_SUITE(SolutionSuite)\n\nBOOST_AUTO_TEST_CASE(PlainTest1)\n{\n    vector<int> height{1,8,6,2,5,4,8,3,7};\n    int results = Solution().maxArea(height);\n\n    int expected = 49;\n    BOOST_CHECK_EQUAL(results, expected);\n}\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "8402952a5d7803d67a79d307aad43b1576eb8971", "size": 388, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "011-Container-With-Most-Water/solution_test.cpp", "max_stars_repo_name": "johnhany/leetcode", "max_stars_repo_head_hexsha": "453a86ac16360e44893262e04f77fd350d1e80f2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-05-27T06:47:32.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-22T05:57:10.000Z", "max_issues_repo_path": "011-Container-With-Most-Water/solution_test.cpp", "max_issues_repo_name": "johnhany/leetcode", "max_issues_repo_head_hexsha": "453a86ac16360e44893262e04f77fd350d1e80f2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "011-Container-With-Most-Water/solution_test.cpp", "max_forks_repo_name": "johnhany/leetcode", "max_forks_repo_head_hexsha": "453a86ac16360e44893262e04f77fd350d1e80f2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-04-01T10:26:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-05T18:21:01.000Z", "avg_line_length": 20.4210526316, "max_line_length": 45, "alphanum_fraction": 0.7603092784, "num_tokens": 101, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6150878555160666, "lm_q2_score": 0.754914975839675, "lm_q1q2_score": 0.46433903358618894}}
{"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_FUNCTION_MODF_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_MODF_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-ieee\n    Function object implementing modf capabilities\n\n    Computes the integer and  fractional parts of the input\n\n    @par Semantic:\n\n    @code\n    T t = modf(x, f);\n    @endcode\n\n    is similar to:\n\n    @code\n    T t = trunc(x);\n    T f = frac(x);\n    @endcode\n\n    The following call can also be used\n\n    @code\n    std::pair<T,T> p = modf(x);\n    @endcode\n\n    @see frac,  trunc\n\n  **/\n  const boost::dispatch::functor<tag::modf_> modf = {};\n} }\n#endif\n\n#include <boost/simd/function/scalar/modf.hpp>\n#include <boost/simd/function/simd/modf.hpp>\n\n#endif\n", "meta": {"hexsha": "1f96798364eb5f7fc8033fbc153643743d0c2477", "size": 1165, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/modf.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/function/modf.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/function/modf.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": 20.8035714286, "max_line_length": 100, "alphanum_fraction": 0.5596566524, "num_tokens": 270, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191460821871, "lm_q2_score": 0.6548947290421276, "lm_q1q2_score": 0.4643329015591746}}
{"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\u00c3\u00a4nkt), 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// #define MTL_VERBOSE_TEST\n\n#include <iostream>\n#include <boost/tuple/tuple.hpp>\n\n#include <boost/numeric/mtl/mtl.hpp>\n#include <boost/numeric/mtl/utility/tag.hpp>\n#include <boost/numeric/mtl/matrix/coordinate2D.hpp>\n\nint main(int, char**)\n{\n    using namespace mtl;\n    using mtl::io::tout;\n\n    typedef mtl::mat::coordinate2D<double> matrix_type;\n    matrix_type   B(5, 4);\n    mtl::dense_vector<double> res(5, 0.0), res2(5), x(4, 1.0);\n    \n\n    tout << \"num_rows = \" << B.num_rows() << \"\\n\"\n\t << \"num_rows = \" << num_rows(B) << \"\\n\"\n\t << \"num_cols = \" << num_cols(B) << \"\\n\"\n\t << \"size = \" << size(B) << \"\\n\"\n\t << \"nnz = \" << nnz(B) << \"\\n\";\n\n    B.push_back(1, 1, 1.33);\n    B.push_back(1, 2, 2.33);\n    B.push_back(2, 1, 3.33);\n    B.push_back(3, 1, 4.33);\n\n    tout << \"B(1, 2) = \" << B(1, 2) << \"\\n\";\n    tout << \"B[2][1] = \" << B[2][1] << \"\\n\";\n\n    MTL_THROW_IF(std::abs(B(3, 1) - 4.33) > 0.001, unexpected_result());\n    MTL_THROW_IF(std::abs(B(1, 2) - 2.33) > 0.001, unexpected_result());\n    MTL_THROW_IF(std::abs(B(2, 1) - 2.33) > 3.001, unexpected_result());\n\n    B.push_back(1, 0, 5.33);\n    B.push_back(0, 0, 6.33);\n    \n    B.print_internal(tout);\n    B.sort();\n    \n    tout << \"Sorted\\n\";\n    B.print_internal(tout);\n\n    tout << \"x=\" << x << \"\\n\" << \"res=\" << res << \"\\n\";\n    res = B * x ;\n    tout << \"res=\" << res << \"\\n\";\n\n    res2= 6.33, 8.99, 3.33, 4.33, 0;\n    res-= res;\n    if (one_norm(res) > 0.1)\n\tthrow \"Matrix vector product wrong.\";\n\n    matrix_type A(5, 5, 9);\n    {\n\tmat::inserter<matrix_type> ins(A, 3);\n\tins[1][2] << 13.3;\n\tins[2][2] << 23.3;\n\tins[2][3] << 33.3;\n\tins[2][4] << 33.3;\n\tins[0][4] << 53.3;\n\tins[1][4] << 6.0;\n\tins[3][0] << 73.3;\n    }\n    tout << \"A (internal) after first insertion\\n\";    \n    A.print_internal(tout);\n    MTL_THROW_IF(std::abs(A[2][3] - 33.3) > 0.001, unexpected_result());\n    MTL_THROW_IF(std::abs(A[2][1]) > 0.001, unexpected_result());\n\n    {\n\tmat::inserter<matrix_type, operations::update_plus<double> > ins(A);\n\tins[2][3] << 3.0;\n\tins[2][1] << 3.33;\n    }\n    tout << \"A (internal) after updating insertion\\n\";    \n    A.print_internal(tout);\n    MTL_THROW_IF(std::abs(A[2][3] - 36.3) > 0.001, unexpected_result());\n    MTL_THROW_IF(std::abs(A[2][1] - 3.33) > 0.001, unexpected_result());\n    MTL_THROW_IF(std::abs(A[2][0]) > 0.001, unexpected_result());\n\n    tout << \"A (internal) =\\n\";\n    A.print_internal(tout);\n\n    tout << \"A =\\n\" << A;\n    \n    traits::row<matrix_type>::type             row(A); \n    traits::col<matrix_type>::type             col(A); \n    traits::const_value<matrix_type>::type     value(A); \n\n    typedef traits::range_generator<tag::major, matrix_type>::type  cursor_type;\n\n    for (cursor_type cursor = mtl::begin<tag::major>(A), cend = mtl::end<tag::major>(A); \n\t cursor != cend; ++cursor) {\n\t\n\ttypedef traits::range_generator<tag::nz, cursor_type>::type icursor_type;\n\tfor (icursor_type icursor = mtl::begin<tag::nz>(cursor), icend = mtl::end<tag::nz>(cursor); \n\t     icursor != icend; ++icursor) \n\t    tout << \"A[\" << row(*icursor) << \"][\" << col(*icursor) << \"] = \" << value(*icursor) << '\\n'; \n    }\n\n    mtl::mat::compressed2D<double> C(A);    \n    tout << \"C=\\n\"<< C << \"\\n\";\n\n\n    return 0;\n}\n", "meta": {"hexsha": "c2d35b424a63a77cd3fdd4b6c481d380a246693f", "size": 3652, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/coordinate2D_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/coordinate2D_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/coordinate2D_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": 30.1818181818, "max_line_length": 98, "alphanum_fraction": 0.5670865279, "num_tokens": 1294, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.7090191460821871, "lm_q1q2_score": 0.46433290155917456}}
{"text": "/*===================================================================\n\nMSI applications for interactive analysis in MITK (M2aia)\n\nCopyright (c) Jonas Cordes\n\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt for details.\n\n===================================================================*/\n\n#include \"mitkIOUtil.h\"\n#include <m2RunningMedian.h>\n#include <m2TestingConfig.h>\n#include <mitkTestFixture.h>\n#include <mitkTestingMacros.h>\n#include <numeric>\n#include <algorithm>\n#include <random>\n\n//#include <boost/algorithm/string.hpp>\n\nclass m2RunningMedianTestSuite : public mitk::TestFixture\n{\n  CPPUNIT_TEST_SUITE(m2RunningMedianTestSuite);\n  MITK_TEST(ApplyRunningMedian_SeededGaussianNoise_shouldReturnTrue);\n\n  CPPUNIT_TEST_SUITE_END();\n\nprivate:\npublic:\n  void ApplyRunningMedian_SeededGaussianNoise_shouldReturnTrue()\n  {\n    /*const double mean = 1.0;\n    const double stddev = 0.33;\n    std::default_random_engine generator;\n    generator.seed(142191);\n    std::normal_distribution<double> dist(mean, stddev);*/\n\n    std::vector<double> signal = {5, 5, 9, 5, 5, 5, 5, 0, 4, 4, 4, 6, 6, 6};\n    std::vector<double> result = {5, 5, 5, 5, 5, 5, 5, 5, 4, 4, 4, 4, 6, 6};\n\n    std::vector<double> median(signal.size());\n    m2::RunMedian::apply(signal, 1, median); // half window size = 1; so window size is 2*1+1\n  \n\tauto res = std::mismatch(std::begin(median), std::end(median), std::begin(result));\n\n\tCPPUNIT_ASSERT(res.first == std::end(median));\n\n  }\n};\n\nMITK_TEST_SUITE_REGISTRATION(m2RunningMedian)\n", "meta": {"hexsha": "980801f3d20ef77380613f346f5caebda3262360", "size": 1640, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Modules/M2aiaSignalProcessing/Testing/m2RunningMedianTest.cpp", "max_stars_repo_name": "ivowolf/M2aia", "max_stars_repo_head_hexsha": "03cfe3495bc706cbb0b00a2916b8f0a3cb398e25", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2021-07-22T06:52:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T12:53:31.000Z", "max_issues_repo_path": "Modules/M2aiaSignalProcessing/Testing/m2RunningMedianTest.cpp", "max_issues_repo_name": "ivowolf/M2aia", "max_issues_repo_head_hexsha": "03cfe3495bc706cbb0b00a2916b8f0a3cb398e25", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-07-25T22:29:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-22T13:21:30.000Z", "max_forks_repo_path": "Modules/M2aiaSignalProcessing/Testing/m2RunningMedianTest.cpp", "max_forks_repo_name": "ivowolf/M2aia", "max_forks_repo_head_hexsha": "03cfe3495bc706cbb0b00a2916b8f0a3cb398e25", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-06-23T11:53:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-22T06:14:24.000Z", "avg_line_length": 27.7966101695, "max_line_length": 93, "alphanum_fraction": 0.6652439024, "num_tokens": 439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581741774411, "lm_q2_score": 0.6297746143530797, "lm_q1q2_score": 0.4642435048598183}}
{"text": "#include <benchmark/benchmark.h>\n\n#include <boost/numeric/ublas/matrix.hpp>\n\n#include <mitrax/dim.hpp>\n\n#include <algorithm>\n\n#include \"../../../include/random_vector.hpp\"\n\n\nusing namespace mitrax;\nusing namespace mitrax::literals;\n\n\ntemplate < typename T >\n[[gnu::noinline]]\nvoid bm(benchmark::State& state, rt_dim_pair_t d){\n\tauto r = mitrax::random_vector< T >(d.point_count());\n\n\twhile(state.KeepRunning()){\n\t\tboost::numeric::ublas::matrix< T > m(\n\t\t\tsize_t(d.cols()), size_t(d.rows())\n\t\t);\n\n\t\tstd::copy(r.begin(), r.end(), m.data().begin());\n\n\t\tbenchmark::DoNotOptimize(m);\n\t}\n}\n\n\n#include <boost/hana/tuple.hpp>\n#include <boost/hana/for_each.hpp>\n\n\nnamespace init{\n\n\tconstexpr auto dimensions = boost::hana::make_tuple(\n\t\t\tdim_pair(2_CS, 2_RS),\n\t\t\tdim_pair(4_CS, 2_RS),\n\t\t\tdim_pair(8_CS, 2_RS),\n\t\t\tdim_pair(8_CS, 4_RS),\n\t\t\tdim_pair(8_CS, 8_RS),\n\t\t\tdim_pair(8_CS, 16_RS),\n\t\t\tdim_pair(8_CS, 32_RS),\n\t\t\tdim_pair(8_CS, 64_RS),\n\t\t\tdim_pair(16_CS, 64_RS),\n\t\t\tdim_pair(32_CS, 64_RS),\n\t\t\tdim_pair(64_CS, 64_RS),\n\t\t\tdim_pair(128_CS, 64_RS),\n\t\t\tdim_pair(256_CS, 64_RS),\n\t\t\tdim_pair(256_CS, 128_RS),\n\t\t\tdim_pair(256_CS, 256_RS)\n\t\t);\n\n}\n\n#include \"main.hpp\"\n", "meta": {"hexsha": "baa546c87974d4172bee40dced9cbc1122ab61e4", "size": 1152, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "benchmark/benchmark/make/random_value/uBLAS_rt_heap.cpp", "max_stars_repo_name": "bebuch/Mitrax", "max_stars_repo_head_hexsha": "bc33a1b93058886daab3e4ef736ef9b519111454", "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": "benchmark/benchmark/make/random_value/uBLAS_rt_heap.cpp", "max_issues_repo_name": "bebuch/Mitrax", "max_issues_repo_head_hexsha": "bc33a1b93058886daab3e4ef736ef9b519111454", "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": "benchmark/benchmark/make/random_value/uBLAS_rt_heap.cpp", "max_forks_repo_name": "bebuch/Mitrax", "max_forks_repo_head_hexsha": "bc33a1b93058886daab3e4ef736ef9b519111454", "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": 19.2, "max_line_length": 54, "alphanum_fraction": 0.6744791667, "num_tokens": 377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.737158174177441, "lm_q2_score": 0.6297746143530797, "lm_q1q2_score": 0.46424350485981825}}
{"text": "#include <Eigen/Core>\n\n\nEigen::VectorXd make(const Eigen::VectorXd& vector)\n{\n    return 2.0 * vector;\n}\n", "meta": {"hexsha": "63f92966889c23bc32843592dd7701c3e4724072", "size": 105, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/eigen.hpp", "max_stars_repo_name": "steffanschlein/cythonwrapper", "max_stars_repo_head_hexsha": "ef30a3bc1a24024b9845dad4aa8a42e05219bd91", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 33.0, "max_stars_repo_stars_event_min_datetime": "2016-04-17T21:26:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-31T03:29:46.000Z", "max_issues_repo_path": "test/eigen.hpp", "max_issues_repo_name": "steffanschlein/cythonwrapper", "max_issues_repo_head_hexsha": "ef30a3bc1a24024b9845dad4aa8a42e05219bd91", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2016-04-12T22:28:11.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-19T16:34:32.000Z", "max_forks_repo_path": "test/eigen.hpp", "max_forks_repo_name": "steffanschlein/cythonwrapper", "max_forks_repo_head_hexsha": "ef30a3bc1a24024b9845dad4aa8a42e05219bd91", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2018-04-29T18:46:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-25T09:35:14.000Z", "avg_line_length": 13.125, "max_line_length": 51, "alphanum_fraction": 0.6761904762, "num_tokens": 27, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581741774411, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.46424349973755213}}
{"text": "#include <sophus/se3.hpp>\n#include <string>\n#include <iostream>\n#include <fstream>\n#include <Eigen/Core>\n#include <unistd.h>\n// need pangolin for plotting trajectory\n#include <pangolin/pangolin.h>\n\nusing namespace std;\n\n// path to trajectory file\nstring trajectory_file = \"../trajectory.txt\";\nstring groundtruth_file = \"../groundtruth.txt\";\nstring estimated_file = \"../estimated.txt\";\n\ntypedef vector<Sophus::SE3d, Eigen::aligned_allocator<Sophus::SE3d>> TrajectoryType;\n\n// start point is red and end point is blue\nvoid DrawTrajectory(TrajectoryType);\nvoid DrawTwoTrajectory(TrajectoryType, TrajectoryType);\nvoid CalculateError(TrajectoryType, TrajectoryType );\n\nint main(int argc, char **argv) {\n\n    TrajectoryType poses;\n    TrajectoryType groundtruth;\n    TrajectoryType estimated;\n\n    /// implement pose reading code\n    std::ifstream file_reader(trajectory_file);\n    std::ifstream groundtruth_reader(groundtruth_file);\n    std::ifstream estimated_reader(estimated_file);\n    double time, tx, ty, tz, qx, qy, qz, qw;\n\n    // Method 1\n    // while (!file_reader.eof()){\n    //     file_reader >> time >> tx >> ty >> tz >> qx >> qy >> qz >> qw;\n    //     Eigen::Vector3d t(tx, ty, tz);\n    //     Eigen::Quaterniond q(qw, qx, qy, qz);\n    //     q.normalize();\n    //     Eigen::Matrix3d Rotation_Matrix(q);\n    //     Sophus::SE3d SE3_from_Eigen(Rotation_Matrix, t);\n    //     poses.push_back(SE3_from_Eigen);\n    // }\n    // cout << \"There are \" << poses.size() << \" timestamps.\" << endl;\n\n    // Method 2\n    while(file_reader >> time >> tx >> ty >> tz >> qx >> qy >> qz >> qw){\n        poses.push_back(Sophus::SE3d(Eigen::Quaterniond(qw, qx, qy, qz), Eigen::Vector3d(tx, ty, tz)));\n    }\n    cout << \"There are \" << poses.size() << \" timestamps.\" << endl;\n\n    //    DrawTrajectory(poses);\n\n    while(groundtruth_reader >> time >> tx >> ty >> tz >> qx >> qy >> qz >> qw){\n        groundtruth.push_back(Sophus::SE3d(Eigen::Quaterniond(qw, qx, qy, qz), Eigen::Vector3d(tx, ty, tz)));\n    }\n    cout << \"There are \" << groundtruth.size() << \" timestamps.\" << endl;\n\n    while(estimated_reader >> time >> tx >> ty >> tz >> qx >> qy >> qz >> qw){\n        estimated.push_back(Sophus::SE3d(Eigen::Quaterniond(qw, qx, qy, qz), Eigen::Vector3d(tx, ty, tz)));\n    }\n    cout << \"There are \" << estimated.size() << \" timestamps.\" << endl;\n    DrawTwoTrajectory(groundtruth, estimated);\n\n    CalculateError(groundtruth, estimated);\n\n    return 0;\n}\n\nvoid CalculateError(TrajectoryType groundtruth, TrajectoryType estimated){\n    double error(0.0);\n    double rmse(0.0);\n    for (size_t i = 0; i < groundtruth.size(); i++){\n        error = (groundtruth[i].inverse() * estimated[i]).log().norm();\n        rmse += error * error;\n    }\n    rmse = sqrt(rmse / groundtruth.size());\n    cout << \"rmse: \" << rmse << endl;\n}\n\n/*******************************************************************************************/\nvoid DrawTrajectory(TrajectoryType poses) {\n\n    if (poses.empty()) {\n        cerr << \"Trajectory is empty!\" << endl;\n        return;\n    }\n\n    // create pangolin window and plot the trajectory\n    pangolin::CreateWindowAndBind(\"Trajectory Viewer\", 1024, 768);\n    glEnable(GL_DEPTH_TEST);\n    glEnable(GL_BLEND);\n    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\n    pangolin::OpenGlRenderState s_cam(\n            pangolin::ProjectionMatrix(1024, 768, 500, 500, 512, 389, 0.1, 1000),\n            pangolin::ModelViewLookAt(0, -0.1, -1.8, 0, 0, 0, 0.0, -1.0, 0.0)\n    );\n\n    pangolin::View &d_cam = pangolin::CreateDisplay()\n            .SetBounds(0.0, 1.0, pangolin::Attach::Pix(175), 1.0, -1024.0f / 768.0f)\n            .SetHandler(new pangolin::Handler3D(s_cam));\n\n\n    while (pangolin::ShouldQuit() == false) {\n        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n        d_cam.Activate(s_cam);\n        glClearColor(1.0f, 1.0f, 1.0f, 1.0f);\n\n        glLineWidth(2);\n        for (size_t i = 0; i < poses.size() - 1; i++) {\n            glColor3f(1 - (float) i / poses.size(), 0.0f, (float) i / poses.size());\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        usleep(5000);   // sleep 5 ms\n    }\n\n}\n\nvoid DrawTwoTrajectory(TrajectoryType poses1, TrajectoryType poses2) {\n    if (poses1.empty() || poses2.empty()) {\n        cerr << \"Trajectory is empty!\" << endl;\n        return;\n    }\n\n    // create pangolin window and plot the trajectory\n    pangolin::CreateWindowAndBind(\"Groundtruth: red, Estimated: blue\", 1024, 768);\n    glEnable(GL_DEPTH_TEST);\n    glEnable(GL_BLEND);\n    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\n    pangolin::OpenGlRenderState s_cam(\n            pangolin::ProjectionMatrix(1024, 768, 500, 500, 512, 389, 0.1, 1000),\n            pangolin::ModelViewLookAt(0, -0.1, -1.8, 0, 0, 0, 0.0, -1.0, 0.0)\n    );\n\n    pangolin::View &d_cam = pangolin::CreateDisplay()\n            .SetBounds(0.0, 1.0, pangolin::Attach::Pix(175), 1.0, -1024.0f / 768.0f)\n            .SetHandler(new pangolin::Handler3D(s_cam));\n\n\n    while (pangolin::ShouldQuit() == false) {\n        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n        d_cam.Activate(s_cam);\n        glClearColor(1.0f, 1.0f, 1.0f, 1.0f);\n\n        glLineWidth(2);\n        for (size_t i = 0; i < poses1.size() - 1; i++) {\n            glColor3f(1.0f, 0.0f, 0.0f);\n            glBegin(GL_LINES);\n            auto p1 = poses1[i], p2 = poses1[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            glColor3f(0.0f, 0.0f, 1.0f);\n            glBegin(GL_LINES);\n            auto p3 = poses2[i], p4 = poses2[i + 1];\n            glVertex3d(p3.translation()[0], p3.translation()[1], p3.translation()[2]);\n            glVertex3d(p4.translation()[0], p4.translation()[1], p4.translation()[2]);\n            glEnd();\n        }\n        pangolin::FinishFrame();\n        usleep(5000);   // sleep 5 ms\n    }\n}", "meta": {"hexsha": "c3332251488fd7cb982aa6384a48205657879fa0", "size": 6237, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3.Lie_Group/draw_trajectory.cpp", "max_stars_repo_name": "weihang-li/Visual-SLAM-Notes", "max_stars_repo_head_hexsha": "62b9c9f30b709c202cc00d16dbcff3538cfa0fb2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "3.Lie_Group/draw_trajectory.cpp", "max_issues_repo_name": "weihang-li/Visual-SLAM-Notes", "max_issues_repo_head_hexsha": "62b9c9f30b709c202cc00d16dbcff3538cfa0fb2", "max_issues_repo_licenses": ["MIT"], "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.Lie_Group/draw_trajectory.cpp", "max_forks_repo_name": "weihang-li/Visual-SLAM-Notes", "max_forks_repo_head_hexsha": "62b9c9f30b709c202cc00d16dbcff3538cfa0fb2", "max_forks_repo_licenses": ["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.64, "max_line_length": 109, "alphanum_fraction": 0.5919512586, "num_tokens": 1826, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.4642434924644378}}
{"text": "#include \"hsi_data_reader.h\"\r\n#include \"spectral.h\"\r\n#include \"settings.h\"\r\n#include \"write_log_file.h\"\r\n#include <cmath>\r\n#include <Eigen/Dense>\r\n#include <chrono>\r\n#include <filesystem>\r\n\r\n#include \"opencv2/highgui.hpp\"\r\n#include <vector>\r\n#include <iostream>\r\n#include <sstream>\r\n#include <ctype.h>\r\n#include <cstdlib>\r\n#include <unordered_map>\r\n\r\nusing hsi::HSIData;\r\nusing hsi::HSIDataOptions;\r\nusing hsi::HSIDataReader;\r\n\r\nfloat normalPDF(float s, float x, float m){\r\n  return (1/(s*2.50663))*std::pow(2.71828,-0.5*std::pow((x-m)/s,2.0));\r\n}\r\n\r\n// convert a comma seperate sting list of the form\r\n// [first, second, third, ... , last]\r\n// to a vector of strings\r\nstd::vector<std::string> stringCS2Vector(std::string str){\r\n  str.erase(std::remove(str.begin(), str.end(), '}'), str.end());\r\n  str.erase(std::remove(str.begin(), str.end(), '{'), str.end());\r\n  str.erase(std::remove(str.begin(), str.end(), ']'), str.end());\r\n  str.erase(std::remove(str.begin(), str.end(), '['), str.end());\r\n  std::vector<std::string> result;\r\n  std::stringstream ss(str);\r\n  while (ss.good()){\r\n    std::string substr;\r\n    std::getline(ss, substr, ',');\r\n    result.push_back(substr);\r\n  }\r\n  return result;\r\n}\r\n\r\n\r\n// convert a comma seperate sting list of the form\r\n// {first, second, third, ... , last}\r\n// to a Eigen::VectorXf \r\nEigen::VectorXf stringCS2VectorFloats(std::string str, int len){\r\n  Eigen::VectorXf result(len);\r\n  str.erase(std::remove(str.begin(), str.end(), '}'), str.end());\r\n  str.erase(std::remove(str.begin(), str.end(), '{'), str.end());\r\n  str.erase(std::remove(str.begin(), str.end(), ']'), str.end());\r\n  str.erase(std::remove(str.begin(), str.end(), '['), str.end());\r\n  std::stringstream ss(str);\r\n  int i = 0;\r\n  while (ss.good()){\r\n    std::string substr;\r\n    std::getline(ss, substr, ',');\r\n    float num_float = std::stof(substr);\r\n    result(i) = num_float;\r\n    i++;\r\n  }\r\n  return result;\r\n}\r\n\r\nRGBwavelengthsStruct computeRGBwavelengths(Eigen::VectorXf wl){\r\n  RGBwavelengthsStruct RGBwavelengths;\r\n  float redDiffWL = abs(wl(0)-650);\r\n  float greenDiffWL = abs(wl(0)-550);\r\n  float blueDiffWL = abs(wl(0)-450);\r\n  for (int band_idx = 0; band_idx < wl.size(); ++band_idx){\r\n    if (abs(wl(band_idx)-650) < redDiffWL){\r\n      RGBwavelengths.bandRed = band_idx;\r\n    }\r\n    if (abs(wl(band_idx)-550) < redDiffWL){\r\n      RGBwavelengths.bandGreen = band_idx;\r\n    }\r\n    if (abs(wl(band_idx)-450) < redDiffWL){\r\n      RGBwavelengths.bandBlue = band_idx;\r\n    }\r\n  }\r\n  return RGBwavelengths;\r\n}\r\n\r\nstd::string getDataFname(int argc, char** argv){\r\n  // Set paths to image files.\r\n  if (argc == 1) {\r\n    // if there are no input file names then use the default image\r\n    // AVIRS which should be located in the same directory as the executable file.\r\n    return std::filesystem::path(argv[0]).replace_filename(\"AVIRIS\").string();\r\n  }else {\r\n    // input image and header file names\r\n    return argv[1];\r\n  }\r\n}\r\n\r\nstd::string getHeaderFname(int argc, char** argv){\r\n  // Set paths to image files.\r\n  if (argc == 1) {\r\n    // if there are no input file names then use the default\r\n    return std::filesystem::path(argv[0]).replace_filename(\"AVIRIS.hdr\").string();;\r\n  }else if (argc == 2) {\r\n    // case where file name is image and header is just the image with .hdr added\r\n    return strcat(argv[1],\".hdr\");\r\n  } else {\r\n    // input image and header file names\r\n    return argv[2];\r\n  }\r\n}\r\n\r\n// Get the range of data (lines, columns, bands) to read\r\n// Currently read the whole image, but subsets could be read here\r\nhsi::HSIDataRange getDataRange(hsi::HSIDataOptions data_options){\r\n  // Set range of data we want to read.\r\n  hsi::HSIDataRange data_range;\r\n  data_range.start_row = 0;\r\n  data_range.end_row = data_options.num_data_rows;\r\n  data_range.start_col = 0;\r\n  data_range.end_col = data_options.num_data_cols;\r\n  data_range.start_band = 0;\r\n  data_range.end_band = data_options.num_data_bands;\r\n  return data_range;\r\n}\r\n\r\nImData HSIData2EigenData(const hsi::HSIData& hsi_data, hsi::HSIDataOptions data_options, settingsValues settings){\r\n  // Start timing\r\n  auto t_start_HSIData2EigenData = std::chrono::high_resolution_clock::now();\r\n  \r\n  // Create the structure to hold the image and metadata\r\n  ImData Im;\r\n\r\n  Im.rows = hsi_data.num_rows;\r\n  Im.cols = hsi_data.num_cols;\r\n  Im.bands = hsi_data.num_bands;\r\n  Eigen::MatrixXf im2d(Im.rows * Im.cols, Im.bands);\r\n  for (int band = 0; band < Im.bands; ++band) {\r\n    for (int row = 0; row < Im.rows; ++row) {\r\n      for (int col = 0; col < Im.cols; ++col) {\r\n        im2d(row * Im.cols + col, band) = hsi_data.GetValue(row, col, band).value_as_float;\r\n      }\r\n    }\r\n  }\r\n  Im.im2d = im2d;\r\n\r\n  // This creates the Eigen::VectorXf Im.wl from the wavelength string\r\n  Im.wl = stringCS2VectorFloats(data_options.wavelength, Im.bands);\r\n\r\n  // Im.wlScale is a scale factor on the wavelengths\r\n  // multiplying by this factor puts the wavelengths\r\n  // into units of nanometers\r\n  Im.wlScale = 1;\r\n  if (Im.wl.mean() < 10){\r\n    Im.wlScale = 1000;\r\n  }\r\n\r\n  // Compute the indices for the wavelengths associated with \r\n  // Reg, Green, Blue colors (650nm, 550nm, 450nm)\r\n  RGBwavelengthsStruct RGBwavelengths = computeRGBwavelengths(Im.wl);\r\n  int bandRed = RGBwavelengths.bandRed;\r\n  int bandGreen = RGBwavelengths.bandGreen;\r\n  int bandBlue = RGBwavelengths.bandBlue;\r\n  \r\n  // This creates the Eigen::VectorXf Im.fwhm from the fwhm string\r\n  Im.fwhm = stringCS2VectorFloats(data_options.fwhm, Im.bands);\r\n\r\n  auto t_end_HSIData2EigenData = std::chrono::high_resolution_clock::now();\r\n  auto secondsElapsedWhite = std::chrono::duration_cast<std::chrono::milliseconds>(t_end_HSIData2EigenData - t_start_HSIData2EigenData);\r\n  Logger(\"Converting HSIDATA to Eigen Matrices completed in : \"+std::to_string(secondsElapsedWhite.count()/1000.)+\"s\", settings);\r\n  \r\n  std::cout << \"some data from the image: \\n\" << im2d(Eigen::seq(0,5),Eigen::seq(0,5)) << std::endl;\r\n\r\n\r\n  return Im;\r\n}\r\n\r\nvoid showRGBimage(ImData Im, settingsValues settings){\r\n  //  create grayscale image\r\n  Eigen::MatrixXf RX2d = Im.RX.reshaped(Im.rows, Im.cols);\r\n  const cv::Size RX_image_size(RX2d.cols(), RX2d.rows());\r\n  float min_value = 0;\r\n  float max_value = 0;\r\n  cv::Mat RX_image(RX_image_size, CV_64FC1);\r\n  for (int row = 0; row < RX2d.rows(); ++row) {\r\n    for (int col = 0; col < RX2d.cols(); ++col) {\r\n      const float pixel_value = RX2d(row, col);\r\n      RX_image.at<double>(row, col) = pixel_value;\r\n      min_value = std::min(min_value, pixel_value);\r\n      max_value = std::max(max_value, pixel_value);\r\n    }\r\n  }\r\n  RX_image = 255*(RX_image-min_value)/(max_value-min_value);\r\n  cv::namedWindow(\"test\", cv::WINDOW_AUTOSIZE);\r\n  cv::imshow(\"test\", RX_image);\r\n  cv::waitKey(0);\r\n}\r\n\r\n// Computes statistics for an image\r\nImStats computeImageStats(ImData Im, settingsValues settings) {\r\n  // Create the structure to hold all the stats\r\n  ImStats stats; \r\n\r\n  // Compute the image mean\r\n  stats.mean = Im.im2d.colwise().mean();\r\n\r\n  // Compute the covariance matrix\r\n  auto t_start_cov_Eigin = std::chrono::high_resolution_clock::now();\r\n  Eigen::MatrixXd centered = (Im.im2d.rowwise() - stats.mean.transpose()).template cast<double>();\r\n  Eigen::MatrixXd cov = (centered.transpose() * centered) / float(Im.im2d.rows() - 1);\r\n  auto t_end_cov_Eigin = std::chrono::high_resolution_clock::now();\r\n  auto secondsElapsed = std::chrono::duration_cast<std::chrono::milliseconds>(t_end_cov_Eigin - t_start_cov_Eigin);\r\n  Logger(\"Covariance computation completed in \"+std::to_string(secondsElapsed.count()/1000.)+\"s\", \r\n    settings);\r\n\r\n  // Compute the eigenvalues and eigenvectors\r\n  auto t_start_evalsEvecs_Eigin = std::chrono::high_resolution_clock::now();\r\n  Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> eigensolver(cov);\r\n  auto t_end_evalsEvecs_Eigin = std::chrono::high_resolution_clock::now();\r\n  Eigen::MatrixXd evals;\r\n  Eigen::MatrixXd evecs;\r\n  if (eigensolver.info() == Eigen::Success){\r\n    auto secondsElapsed = std::chrono::duration_cast<std::chrono::milliseconds>(t_end_evalsEvecs_Eigin - t_start_evalsEvecs_Eigin);\r\n    Logger(\"Eigenvalue and eignvector computation completed in \"+std::to_string(secondsElapsed.count()/1000.)+\"s\", \r\n      settings);\r\n    evals = eigensolver.eigenvalues();\r\n    evecs = eigensolver.eigenvectors();\r\n  }\r\n  else {\r\n    Logger(\"WARNING: eigenvalues and eigenvectors failed to compute.\", settings);\r\n  };\r\n\r\n  \r\n  std::cout << \"Eigenvalues:\\n\";\r\n  for (int i = 0; i < 3; ++i) {\r\n    std::cout << evals(i) << \" | \" << evals(i)/evals(evals.rows()-1) << std::endl;\r\n  }\r\n  std::cout << \"...\\n\";\r\n  for (int i = evals.rows()-3; i < evals.rows(); ++i) {\r\n    std::cout << evals(i) << \" | \" << evals(i)/evals(evals.rows()-1) << std::endl;\r\n  }\r\n\r\n  // Computing the whitening matrix\r\n  auto t_start_W = std::chrono::high_resolution_clock::now();\r\n  Eigen::MatrixXd D = Eigen::MatrixXd::Identity(evals.rows(),evals.rows());\r\n  double maxEval = evals.maxCoeff();\r\n  for (int i = 0; i < evals.rows(); ++i) {\r\n    // Optional regularization on eigenvalues\r\n    //stats.evals(i) = std::max(stats.evals(i),maxEval*std::pow(10,-8));\r\n    D(i,i) = 1/sqrt(evals(i));\r\n  }\r\n  Eigen::MatrixXd W =  (evecs*D);\r\n  std::cout << \"some data from the whitening matrix: \\n\" << W(Eigen::seq(0,5),Eigen::seq(0,5)) << std::endl;\r\n  \r\n  auto t_end_W = std::chrono::high_resolution_clock::now();\r\n  auto secondsElapsedW = std::chrono::duration_cast<std::chrono::milliseconds>(t_end_W - t_start_W);\r\n  Logger(\"Whitening matrix computation completed in \"+std::to_string(secondsElapsedW.count()/1000.)+\"s\", \r\n    settings);\r\n\r\n  // Recast as float\r\n  stats.cov = cov.template cast<float>();\r\n  stats.evals = evals.template cast<float>();\r\n  stats.evecs = evecs.template cast<float>();\r\n  stats.W = W.template cast<float>();\r\n\r\n  Logger(\"im2d Matrix is \"+std::to_string(Im.im2d.rows())+\"x\"+std::to_string(Im.im2d.cols()),\r\n    settings);\r\n  Logger(\"Covariance is \"+std::to_string(stats.cov.rows())+\"x\"+std::to_string(stats.cov.cols()),\r\n    settings);  \r\n  Logger(\"Whitening Matrix is \"+std::to_string(stats.W.rows())+\"x\"+std::to_string(stats.W.cols()),\r\n    settings);\r\n\r\n  // VALIDATION: If we want to validate the Whitening by comparison to the inverse\r\n  //Eigen::MatrixXd Diff = cov.inverse() - (W)*(W.transpose());\r\n  //std::cout << \"some data from the Diff matrix: \\n\" << Diff(Eigen::seq(0,5),Eigen::seq(0,5)) << std::endl;\r\n\r\n  return stats;\r\n}\r\n\r\n// Whitens an image using provided statistics\r\nEigen::MatrixXf computeWhitenedImage(ImData Im, ImStats stats, settingsValues settings) {\r\n\r\n  auto t_start_White = std::chrono::high_resolution_clock::now();\r\n  // VALIDATION: If we want to validat the data be viewing the image mean\r\n  //std::cout << \"image mean: \\n\" << stats.mean;\r\n  Eigen::MatrixXf centered = Im.im2d.rowwise() - stats.mean.transpose();\r\n  Eigen::MatrixXf whitened = centered*stats.W;\r\n  auto t_end_White = std::chrono::high_resolution_clock::now();\r\n  auto secondsElapsedWhite = std::chrono::duration_cast<std::chrono::milliseconds>(t_end_White - t_start_White);\r\n  Logger(\"Whitening image completed in \"+std::to_string(secondsElapsedWhite.count()/1000.)+\"s\", \r\n    settings); \r\n  Logger(\"Whitening image is \"+std::to_string(whitened.rows())+\"x\"+std::to_string(whitened.cols()),\r\n    settings);\r\n\r\n  return whitened;\r\n}\r\n\r\n// Computes the RX anomaly detetion image from the whitened image\r\nEigen::MatrixXf computeRXimage(ImData Im, settingsValues settings){\r\n  \r\n  auto t_start_rx = std::chrono::high_resolution_clock::now();\r\n  Eigen::MatrixXf  RX = Im.white2d.rowwise().norm();\r\n  Logger(\"RX image has size: \"+std::to_string(RX.size()), settings);\r\n  auto t_end_rx = std::chrono::high_resolution_clock::now();\r\n  auto secondsElapsedRX = std::chrono::duration_cast<std::chrono::milliseconds>(t_end_rx - t_start_rx);\r\n  Logger(\"Creating RX image completed in \"+std::to_string(secondsElapsedRX.count()/1000.)+\"s\", settings);\r\n\r\n  return RX;\r\n}\r\n\r\n// Displays the RX anomaly detection image\r\nvoid showRXimage(ImData Im, settingsValues settings){\r\n\r\n  if (settings.saveRX || settings.displayRX){\r\n    //  create grayscale image\r\n    Eigen::MatrixXf RX2d = Im.RX.reshaped(Im.rows, Im.cols);\r\n    const cv::Size RX_image_size(RX2d.cols(), RX2d.rows());\r\n    float min_value = 0;\r\n    float max_value = 0;\r\n    cv::Mat RX_image(RX_image_size, CV_64FC1);\r\n    for (int row = 0; row < RX2d.rows(); ++row) {\r\n      for (int col = 0; col < RX2d.cols(); ++col) {\r\n        const float pixel_value = RX2d(row, col);\r\n        RX_image.at<double>(row, col) = pixel_value;\r\n        min_value = std::min(min_value, pixel_value);\r\n        max_value = std::max(max_value, pixel_value);\r\n      }\r\n    }\r\n    RX_image = 5*(RX_image-min_value)/(max_value-min_value);\r\n    \r\n    if (settings.displayRX){\r\n      cv::namedWindow(\"test\", cv::WINDOW_AUTOSIZE);\r\n      cv::imshow(\"test\", RX_image);\r\n      cv::waitKey(0);\r\n    }\r\n\r\n    if (settings.saveRX){\r\n      bool check = cv::imwrite(settings.outDir+\"\\\\RX.jpg\", 255*RX_image);\r\n      if (check == false) {\r\n        Logger(\"WARNING Saving RX image failed.\", settings);\r\n      } else {\r\n        Logger(\"RX Image saves as \"+settings.outDir+\"\\\\RX.jpg\", settings);\r\n      }\r\n    }\r\n  }\r\n}\r\n\r\nconst std::string getTgtLibDataFname(const std::string hsi_data_path){\r\n  std::filesystem::path p(hsi_data_path);\r\n  return p.parent_path().string()+\"\\\\lib_detect_fullresolution.sli\";\r\n}\r\n\r\nconst std::string getTgtLibHeaderFname(const std::string hsi_data_path){\r\n  std::filesystem::path p(hsi_data_path);\r\n  return p.parent_path().string()+\"\\\\lib_detect_fullresolution.hdr\";\r\n}\r\n\r\n// Converts data and metadata for a spectral library into \r\n// a LibData structure using Eigen variable types.\r\nLibData SpecLibData2EigenData(const hsi::HSIData& tgt_lib_data, hsi::HSIDataOptions tgt_lib_data_options){\r\n  // Create the structure to hold the image and metadata\r\n  LibData lib_tgt;\r\n  lib_tgt.nSpectra = tgt_lib_data.num_cols;\r\n  lib_tgt.bands = tgt_lib_data.num_rows;\r\n\r\n  // This creates the vector Im.wl from the wavelength string\r\n  lib_tgt.wl = stringCS2VectorFloats(tgt_lib_data_options.wavelength, lib_tgt.bands);\r\n\r\n  // This creates the vector lib_tgt.specNames from the specNames string\r\n  lib_tgt.specNames = stringCS2Vector(tgt_lib_data_options.specNames);\r\n\r\n  // Make a matrix that will hold the spectra\r\n  Eigen::MatrixXf spectra(lib_tgt.nSpectra, lib_tgt.bands);\r\n  for (int i = 0; i < lib_tgt.nSpectra; ++i) {\r\n    for (int j = 0; j < lib_tgt.bands; ++j) {\r\n      spectra(i,j) = 10.0*tgt_lib_data.GetValueLib(j, i, 0).value_as_float;\r\n    }\r\n  }\r\n  lib_tgt.spectra = spectra;\r\n  std::cout << \"some data from the library file spectra: \\n\" << spectra(Eigen::seq(0,5),Eigen::seq(0,5)) << std::endl;\r\n\r\n  return lib_tgt;\r\n}\r\n\r\nLibData resampleLibrary(LibData lib_tgt_fullres, ImData Im) {\r\n  // Create the structure to hold the image and metadata\r\n  LibData lib_tgt;\r\n  lib_tgt.specNames = lib_tgt_fullres.specNames;\r\n  lib_tgt.nSpectra = lib_tgt_fullres.nSpectra;\r\n  lib_tgt.bands = Im.bands;\r\n  lib_tgt.wl = Im.wl;\r\n  Eigen::MatrixXf spectra = Eigen::MatrixXf::Zero(lib_tgt_fullres.nSpectra, Im.bands);\r\n\r\n  Eigen::VectorXf sigma(Im.bands);\r\n  for (int i = 0; i < Im.bands; ++i) {\r\n    sigma(i) = Im.fwhm(i)/2.355;\r\n  }\r\n\r\n  float sum = 0;\r\n  float weight = 0;\r\n  for (int im_bnd_idx = 0; im_bnd_idx < Im.bands; ++im_bnd_idx) {  //  looping over bands in the image\r\n    for (int lb_bnd_idx = 0; lb_bnd_idx < lib_tgt_fullres.bands; ++lb_bnd_idx) { // looping over all bands in the library \r\n      //  compute the difference between the image (target) wavelength and library wavelength so that we \r\n      //  only compute contributions of library bands with wavelength that are withing 3 sigma of the image wavelength\r\n      float diff = (lib_tgt_fullres.wl[lb_bnd_idx] - Im.wl[im_bnd_idx]);\r\n      float standard_deviations_diff = diff/sigma(im_bnd_idx);\r\n      \r\n      /*  VALIDATION OUTPUT:  uncomment this to see how the resampling computation works\r\n      std::cout << lib_tgt_fullres.wl[lb_bnd_idx] << \" - \" << Im.wl[im_bnd_idx] << std::endl;\r\n      std::cout << diff << std::endl;\r\n      std::cout << standard_deviations_diff << std::endl;\r\n      std::cout << \"Weight: \" << weight << std::endl;\r\n      std::cout << \"Sum: \" << sum << std::endl;\r\n      */\r\n\r\n      if (standard_deviations_diff > -3){\r\n        if (standard_deviations_diff > 3){\r\n          // stop the  iteration through library bands becasue the library band wavelength has\r\n          // passed all wavelengths within 3 standard deviations of the image wavelength\r\n          lb_bnd_idx = lib_tgt_fullres.bands;\r\n        } else {\r\n          weight = normalPDF(sigma(im_bnd_idx), \r\n                            Im.wl[im_bnd_idx],\r\n                            lib_tgt_fullres.wl[lb_bnd_idx]);\r\n          for (int spec_idx = 0; spec_idx < lib_tgt.nSpectra; ++spec_idx) { // looping over all spectra in the library\r\n            spectra(spec_idx, im_bnd_idx) = spectra(spec_idx, im_bnd_idx) + \r\n                                        lib_tgt_fullres.spectra(spec_idx, lb_bnd_idx)*\r\n                                        weight;\r\n            sum = sum + weight;\r\n          }\r\n        }\r\n      }\r\n    }\r\n    for (int spec_idx = 0; spec_idx < lib_tgt.nSpectra; ++spec_idx) { // looping over all spectra in the library\r\n      spectra(spec_idx, im_bnd_idx) = spectra(spec_idx, im_bnd_idx)/sum;\r\n    }\r\n    sum = 0;    \r\n  }\r\n  lib_tgt.spectra = spectra;\r\n\r\n  /* VALIDATION: If we want to validate data by checking the first resampled spectrum from the library\r\n  std::cout << \"First spectrum:\\n\";\r\n  for (int idx = 0; idx < Im.bands; ++idx) {\r\n    std::cout << spectra(0,idx) << std::endl;\r\n  }\r\n  */\r\n  \r\n  std::cout << \"some data from the resampled spectra: \\n\";\r\n  std::cout << spectra(Eigen::seq(0,5),Eigen::seq(0,5)) << std::endl;\r\n\r\n  return lib_tgt;\r\n}\r\n\r\nEigen::MatrixXf computeWhitenedLibrary(LibData lib_tgt, ImStats stats, settingsValues settings) {\r\n\r\n  auto t_start_White = std::chrono::high_resolution_clock::now();\r\n  Eigen::MatrixXf centered = lib_tgt.spectra.rowwise() - stats.mean.transpose();\r\n  std::cout << \"some data from the centered spectra: \\n\" << centered(Eigen::seq(0,5),Eigen::seq(0,5)) << std::endl;\r\n  Eigen::MatrixXf spectraWhite = centered*stats.W;\r\n  std::cout << \"some data from the whitened spectra: \\n\" << spectraWhite(Eigen::seq(0,5),Eigen::seq(0,5)) << std::endl;\r\n  auto t_end_White = std::chrono::high_resolution_clock::now();\r\n  auto secondsElapsedWhite = std::chrono::duration_cast<std::chrono::milliseconds>(t_end_White - t_start_White);\r\n  Logger(\"Whitening library completed in \"+std::to_string(secondsElapsedWhite.count()/1000.)+\"s\", \r\n    settings); \r\n  Logger(\"Whitening library is \"+std::to_string(spectraWhite.rows())+\"x\"+std::to_string(spectraWhite.cols()),\r\n    settings);\r\n\r\n  return spectraWhite;\r\n}\r\n\r\n\r\nEigen::MatrixXf computeACEimage(ImData Im, LibData lib_tgt, settingsValues settings){\r\n  \r\n  auto t_start_ACE = std::chrono::high_resolution_clock::now();\r\n  std::cout << \"some data from the whitened image: \\n\" << Im.white2d(Eigen::seq(0,5),Eigen::seq(0,5)) << std::endl;\r\n  std::cout << \"some data from the whitened library: \\n\" << lib_tgt.spectraWhite(Eigen::seq(0,5),Eigen::seq(0,5)) << std::endl;\r\n  Eigen::MatrixXf  ACE_num = Im.white2d * lib_tgt.spectraWhite.transpose();\r\n  std::cout << \"some data from the ACE numerator: \\n\" << ACE_num(Eigen::seq(0,5),Eigen::seq(0,5)) << std::endl;\r\n  Eigen::MatrixXf  ACE_denom = (Im.RX.replicate(1,lib_tgt.nSpectra).array() * lib_tgt.spectraWhite.transpose().colwise().norm().replicate(Im.rows*Im.cols, 1).array()).matrix();\r\n  std::cout << \"some data from the ACE denominator: \\n\" << ACE_denom(Eigen::seq(0,5),Eigen::seq(0,5)) << std::endl;\r\n  Eigen::MatrixXf  ACE = (ACE_num.array() / ACE_denom.array()).matrix();\r\n  std::cout << \"some data from the ACE image: \\n\" << ACE(Eigen::seq(0,5),Eigen::seq(0,5)) << std::endl;\r\n  Logger(\"ACE image is \"+std::to_string(ACE_num.rows())+\"x\"+std::to_string(ACE_num.cols()),\r\n    settings);\r\n  auto t_end_ACE = std::chrono::high_resolution_clock::now();\r\n  auto secondsElapsedACE = std::chrono::duration_cast<std::chrono::milliseconds>(t_end_ACE - t_start_ACE);\r\n  Logger(\"Creating ACE image completed in \"+std::to_string(secondsElapsedACE.count()/1000.)+\"s\", settings);\r\n\r\n  return ACE;\r\n}\r\n\r\nvoid showACEResults(ImData Im, LibData lib_tgt, Eigen::MatrixXf ACE, settingsValues settings){\r\n    \r\n  if (settings.saveACE || settings.displayACE){\r\n    // Create the openCV ACE image\r\n    const cv::Size ACEimSize(Im.cols, Im.rows);\r\n    cv::Mat ACEim(ACEimSize, CV_64FC1);\r\n\r\n    for (int spec_idx = 0; spec_idx < lib_tgt.nSpectra; ++spec_idx) {\r\n      Eigen::MatrixXf ACEslice2d = ACE(Eigen::all, spec_idx);\r\n      Eigen::MatrixXf ACE2d = ACEslice2d.reshaped(Im.rows, Im.cols);\r\n      //  create grayscale image\r\n      float min_value = 100;\r\n      float max_value = -100;    \r\n      for (int row = 0; row < Im.rows; ++row) {\r\n        for (int col = 0; col < Im.cols; ++col) {\r\n          float pixel_value = ACE2d(row, col);\r\n          //pixel_value = ((pixel_value>0)-(pixel_value<0))*std::sqrt(std::abs(pixel_value));\r\n          float min_thresh = 0.25;\r\n          pixel_value = std::max(min_thresh,pixel_value);\r\n          ACEim.at<double>(row, col) = pixel_value;\r\n          min_value = std::min(min_value, pixel_value);\r\n          max_value = std::max(max_value, pixel_value);\r\n        }\r\n      }\r\n      ACEim = (ACEim-min_value)/(max_value-min_value);\r\n      std::cout << lib_tgt.specNames[spec_idx] << std::endl;\r\n      std::cout << \"Min Value: \" << min_value << std::endl;\r\n      std::cout << \"Max Value: \" << max_value << std::endl;\r\n \r\n      if (settings.displayACE){\r\n        cv::namedWindow(lib_tgt.specNames[spec_idx], cv::WINDOW_AUTOSIZE);\r\n        cv::imshow(lib_tgt.specNames[spec_idx], ACEim);\r\n        cv::waitKey(0);\r\n      }\r\n      if (settings.saveACE){\r\n        std::string specName = lib_tgt.specNames[spec_idx];\r\n        specName.erase(std::remove(specName.begin(), specName.end(), ' '), specName.end());\r\n        bool check = cv::imwrite(settings.outDir+\"\\\\ACE_\"+specName+\".jpg\", 255*ACEim);\r\n        if (check == false) {\r\n          Logger(\"WARNING Saving ACE image failed.\", settings);\r\n        } else {\r\n          Logger(\"ACE Image saved as \"+settings.outDir+\"\\\\ACE_\"+specName+\".jpg\", settings);\r\n        }\r\n      }\r\n    }\r\n  }\r\n\r\n}\r\n  \r\n// Compute a covarnaince matrix and other stats for the input image\r\n// using a 3 step process: compute stats and RX anomaly detection,\r\n// remove the anomalies, and recompute stats from non-anomalous pixels.\r\n// Input image matrix is pixels x bands\r\nImStats computeAnomalyCleanedImageStats(ImData Im, settingsValues settings) {\r\n  \r\n  // build a subseted compy of the image structure containing\r\n  // only about 10,000 pixel spectra for quick approximate\r\n  // first covariance computation\r\n  ImData Im_sampled;\r\n  Im_sampled.im2d = Im.im2d(Eigen::seq(0,Im.im2d.rows(),std::floor(Im.im2d.rows()/10000.)), Eigen::all);\r\n  Im_sampled.rows = Im.rows;\r\n  Im_sampled.cols = Im.cols;\r\n\r\n  // compute the covariance for the subset of pixel spectra\r\n  Logger(\"Computing statistics using Eigen (first pass)\", settings);\r\n  ImStats stats_sampled = computeImageStats(Im_sampled, settings);\r\n\r\n  // Whiten the full image using the subset-computed covariance\r\n  Logger(\"Whitening the image. (first pass)\", settings);\r\n  Im_sampled.white2d = computeWhitenedImage(Im, stats_sampled, settings);\r\n\r\n  // Compute the RX anomaly image using the subset-computed covariance\r\n  // This will be used to remove anomalies for the \r\n  // primary covariance computation\r\n  Logger(\"Compute the RX anomaly image. (first pass)\", settings);\r\n  Eigen::MatrixXf RX = computeRXimage(Im_sampled, settings);\r\n  \r\n  // compute a threshold for anomaly removeal\r\n  // removing the most anomalous 5% of pixels\r\n  auto t_start_rx_pctile = std::chrono::high_resolution_clock::now();  \r\n  std::vector<float> RXv;\r\n  RXv.resize(RX.size());\r\n  Eigen::VectorXf::Map(&RXv[0], RX.size()) = RX;  \r\n  std::sort(RXv.begin(), RXv.end());\r\n  int idx_95pct = std::round(RX.size()*0.95);\r\n  for (int i = 0; i < 100; ++i) { \r\n    std::cout << RXv[i] << std::endl;\r\n  }\r\n  float thresh_95pct = RXv[idx_95pct];\r\n  std::cout << \"Thresh: \" << thresh_95pct << std::endl;\r\n  std::cout << \"Max: \" << RX.maxCoeff() << std::endl;\r\n  auto t_end_rx_pctile = std::chrono::high_resolution_clock::now();\r\n  auto secondsElapsedRX_pctile = std::chrono::duration_cast<std::chrono::milliseconds>(t_end_rx_pctile - t_start_rx_pctile);\r\n  Logger(\"Computing RX threshold completed in \"+std::to_string(secondsElapsedRX_pctile.count()/1000.)+\"s\", settings);\r\n  \r\n  auto t_subsample_start = std::chrono::high_resolution_clock::now();  \r\n  Eigen::VectorXi is_selected = (RX.array() < thresh_95pct).cast<int>(); \r\n  Eigen::VectorXi is_selectedindices(is_selected.sum());\r\n  int idx = 0;\r\n  for (int i = 0; i < Im.rows; ++i) { \r\n    if (is_selected(i) == 1){\r\n      is_selectedindices(idx) = i;\r\n      idx++;\r\n    }\r\n  }\r\n\r\n  Im_sampled.im2d = Im.im2d(is_selectedindices,Eigen::all);\r\n  std::cout << Im_sampled.im2d.rows() << std::endl;\r\n  std::cout << Im_sampled.im2d.cols() << std::endl;\r\n  auto t_subsample_end = std::chrono::high_resolution_clock::now();\r\n  auto secondsElapsed_subsample = std::chrono::duration_cast<std::chrono::milliseconds>(t_subsample_end - t_subsample_start);\r\n  Logger(\"time for subset computation: \"+std::to_string(secondsElapsed_subsample.count()/1000.)+\"s\", settings);\r\n\r\n  // HAVING TROUBLE SUBSETTING THE IMAGE TO COMPUTE STATS FROM THE NON-ANOMALUS PIXELS\r\n  // I AM MULTIPLYING ANOMALIES BY ZER FOR COV COMPUTATION BUT ITS NOT WORKING!\r\n\r\n\r\n  // Now we compute the stats for the data with anomalies removed\r\n  // Create the structure to hold all the stats\r\n  ImStats stats; \r\n\r\n  // Compute the image mean\r\n  stats.mean = Im_sampled.im2d.colwise().mean();\r\n\r\n  // Compute the covariance matrix\r\n  auto t_start_cov_Eigin = std::chrono::high_resolution_clock::now();\r\n  Eigen::MatrixXd centered = (Im_sampled.im2d.rowwise() - stats.mean.transpose()).template cast<double>();\r\n  Eigen::MatrixXd cov = (centered.transpose() * centered) / float(is_selected.sum() - 1);\r\n  auto t_end_cov_Eigin = std::chrono::high_resolution_clock::now();\r\n  auto secondsElapsed = std::chrono::duration_cast<std::chrono::milliseconds>(t_end_cov_Eigin - t_start_cov_Eigin);\r\n  Logger(\"Covariance computation completed in \"+std::to_string(secondsElapsed.count()/1000.)+\"s\", \r\n    settings);\r\n\r\n  // Compute the eigenvalues and eigenvectors\r\n  auto t_start_evalsEvecs_Eigin = std::chrono::high_resolution_clock::now();\r\n  Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> eigensolver(cov);\r\n  auto t_end_evalsEvecs_Eigin = std::chrono::high_resolution_clock::now();\r\n  Eigen::MatrixXd evals;\r\n  Eigen::MatrixXd evecs;\r\n  if (eigensolver.info() == Eigen::Success){\r\n    auto secondsElapsed = std::chrono::duration_cast<std::chrono::milliseconds>(t_end_evalsEvecs_Eigin - t_start_evalsEvecs_Eigin);\r\n    Logger(\"Eigenvalue and eignvector computation completed in \"+std::to_string(secondsElapsed.count()/1000.)+\"s\", \r\n      settings);\r\n    evals = eigensolver.eigenvalues();\r\n    evecs = eigensolver.eigenvectors();\r\n  }\r\n  else {\r\n    Logger(\"WARNING: eigenvalues and eigenvectors failed to compute.\", settings);\r\n  };\r\n\r\n  \r\n  std::cout << \"Eigenvalues:\\n\";\r\n  for (int i = 0; i < 3; ++i) {\r\n    std::cout << evals(i) << \" | \" << evals(i)/evals(evals.rows()-1) << std::endl;\r\n  }\r\n  std::cout << \"...\\n\";\r\n  for (int i = evals.rows()-3; i < evals.rows(); ++i) {\r\n    std::cout << evals(i) << \" | \" << evals(i)/evals(evals.rows()-1) << std::endl;\r\n  }\r\n\r\n  // Computing the whitening matrix\r\n  auto t_start_W = std::chrono::high_resolution_clock::now();\r\n  Eigen::MatrixXd D = Eigen::MatrixXd::Identity(evals.rows(),evals.rows());\r\n  double maxEval = evals.maxCoeff();\r\n  for (int i = 0; i < evals.rows(); ++i) {\r\n    // Optional regularization on eigenvalues\r\n    //evals(i) = std::max(evals(i),maxEval*std::pow(10,-6));\r\n    D(i,i) = 1/sqrt(evals(i));\r\n  }\r\n  Eigen::MatrixXd W =  (evecs*D);\r\n  std::cout << \"some data from the whitening matrix: \\n\" << W(Eigen::seq(0,8),Eigen::seq(0,8)) << std::endl;\r\n  \r\n  auto t_end_W = std::chrono::high_resolution_clock::now();\r\n  auto secondsElapsedW = std::chrono::duration_cast<std::chrono::milliseconds>(t_end_W - t_start_W);\r\n  Logger(\"Whitening matrix computation completed in \"+std::to_string(secondsElapsedW.count()/1000.)+\"s\", \r\n    settings);\r\n\r\n  // Recast as float\r\n  stats.cov = cov.template cast<float>();\r\n  stats.evals = evals.template cast<float>();\r\n  stats.evecs = evecs.template cast<float>();\r\n  stats.W = W.template cast<float>();\r\n\r\n  Logger(\"im2d Matrix is \"+std::to_string(Im.im2d.rows())+\"x\"+std::to_string(Im.im2d.cols()),\r\n    settings);\r\n  Logger(\"Covariance is \"+std::to_string(stats.cov.rows())+\"x\"+std::to_string(stats.cov.cols()),\r\n    settings);  \r\n  Logger(\"Whitening Matrix is \"+std::to_string(stats.W.rows())+\"x\"+std::to_string(stats.W.cols()),\r\n    settings);\r\n\r\n  // VALIDATION: If we want to validate the Whitening by comparison to the inverse\r\n  //Eigen::MatrixXd Diff = cov.inverse() - (W)*(W.transpose());\r\n  //std::cout << \"some data from the Diff matrix: \\n\" << Diff(Eigen::seq(0,5),Eigen::seq(0,5)) << std::endl;\r\n\r\n  return stats;\r\n}\r\n", "meta": {"hexsha": "52b83092cbd29c5b1e6cde01b826141035045bc3", "size": 29350, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "spectral.cpp", "max_stars_repo_name": "UVADS/Hyperspectral-Cpp", "max_stars_repo_head_hexsha": "af08bdae7a4968191f842f27a9ed0ceb0916cff3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "spectral.cpp", "max_issues_repo_name": "UVADS/Hyperspectral-Cpp", "max_issues_repo_head_hexsha": "af08bdae7a4968191f842f27a9ed0ceb0916cff3", "max_issues_repo_licenses": ["MIT"], "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.cpp", "max_forks_repo_name": "UVADS/Hyperspectral-Cpp", "max_forks_repo_head_hexsha": "af08bdae7a4968191f842f27a9ed0ceb0916cff3", "max_forks_repo_licenses": ["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.7842565598, "max_line_length": 177, "alphanum_fraction": 0.6608177172, "num_tokens": 8200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286833, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.46424349246443775}}
{"text": "#include <stan/math/prim/mat.hpp>\n#include <stan/math/prim/scal.hpp>\n#include <test/unit/math/prim/prob/vector_rng_test_helper.hpp>\n#include <test/unit/math/prim/prob/util.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/math/distributions.hpp>\n#include <gtest/gtest.h>\n#include <vector>\n#include <limits>\n\nclass InvGammaTestRig : public VectorRealRNGTestRig {\n public:\n  InvGammaTestRig()\n      : VectorRealRNGTestRig(10000, 10, {0.5, 1.0, 1.3, 2.0}, {1, 2, 3},\n                             {-2.5, -1.7, -0.1, 0.0}, {-3, -2, -1, 0},\n                             {0.1, 1.0, 1.7, 2.1}, {1, 2, 3, 4},\n                             {-2.7, -1.5, -0.5, 0.0}, {-3, -2, -1, 0}) {}\n\n  template <typename T1, typename T2, typename T3, typename T_rng>\n  auto generate_samples(const T1& alpha, const T2& beta, const T3&,\n                        T_rng& rng) const {\n    return stan::math::inv_gamma_rng(alpha, beta, rng);\n  }\n\n  std::vector<double> generate_quantiles(double alpha, double beta,\n                                         double) const {\n    std::vector<double> quantiles;\n    double K = stan::math::round(2 * std::pow(N_, 0.4));\n    boost::math::inverse_gamma_distribution<> dist(alpha, beta);\n\n    for (int i = 1; i < K; ++i) {\n      double frac = i / K;\n      quantiles.push_back(quantile(dist, frac));\n    }\n    quantiles.push_back(std::numeric_limits<double>::max());\n\n    return quantiles;\n  }\n};\n\nTEST(ProbDistributionsInvGamma, errorCheck) {\n  check_dist_throws_all_types(InvGammaTestRig());\n}\n\nTEST(ProbDistributionsInvGamma, distributionTest) {\n  check_quantiles_real_real(InvGammaTestRig());\n}\n\nTEST(ProbDistributionsInvGamma, error_check) {\n  boost::random::mt19937 rng;\n  EXPECT_NO_THROW(stan::math::inv_gamma_rng(4.0, 3.0, rng));\n\n  EXPECT_THROW(stan::math::inv_gamma_rng(-4.0, 3.0, rng), std::domain_error);\n  EXPECT_THROW(stan::math::inv_gamma_rng(4.0, -3.0, rng), std::domain_error);\n  EXPECT_THROW(\n      stan::math::inv_gamma_rng(stan::math::positive_infinity(), 3.0, rng),\n      std::domain_error);\n  EXPECT_THROW(\n      stan::math::inv_gamma_rng(4, stan::math::positive_infinity(), rng),\n      std::domain_error);\n}\n\nTEST(ProbDistributionsInvGamma, chiSquareGoodnessFitTest) {\n  boost::random::mt19937 rng;\n  int N = 10000;\n  int K = stan::math::round(2 * std::pow(N, 0.4));\n\n  std::vector<double> samples;\n  for (int i = 0; i < N; ++i) {\n    samples.push_back(stan::math::inv_gamma_rng(2.0, 1.0, rng));\n  }\n\n  // Generate quantiles from boost's Inverse Gamma distribution\n  boost::math::inverse_gamma_distribution<> dist(2.0, 1.0);\n  std::vector<double> quantiles;\n  for (int i = 1; i < K; ++i) {\n    double frac = static_cast<double>(i) / K;\n    quantiles.push_back(quantile(dist, frac));\n  }\n  quantiles.push_back(std::numeric_limits<double>::max());\n\n  // Assert that they match\n  assert_matches_quantiles(samples, quantiles, 1e-6);\n}\n", "meta": {"hexsha": "417ef5bd84bdd9ffbbd2d8f1259e250ae7d358fa", "size": 2878, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/prim/prob/inv_gamma_test.cpp", "max_stars_repo_name": "christophernhill/math", "max_stars_repo_head_hexsha": "dc41aba296d592c7099be15eed6ba136d0f140b3", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/unit/math/prim/prob/inv_gamma_test.cpp", "max_issues_repo_name": "christophernhill/math", "max_issues_repo_head_hexsha": "dc41aba296d592c7099be15eed6ba136d0f140b3", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/unit/math/prim/prob/inv_gamma_test.cpp", "max_forks_repo_name": "christophernhill/math", "max_forks_repo_head_hexsha": "dc41aba296d592c7099be15eed6ba136d0f140b3", "max_forks_repo_licenses": ["BSD-3-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.8588235294, "max_line_length": 77, "alphanum_fraction": 0.6421125782, "num_tokens": 890, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286833, "lm_q2_score": 0.6297746004557471, "lm_q1q2_score": 0.46424348734217163}}
{"text": "//==================================================================================================\n/*!\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#include <boost/simd/function/scalar/stirling.hpp>\n#include <scalar_test.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/minf.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/mone.hpp>\n#include <boost/simd/function/round.hpp>\n\nSTF_CASE_TPL(\" stirling\",  STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::stirling;\n\n  STF_EXPR_IS(stirling(T()),T);\n\n#ifndef BOOST_SIMD_NO_INVALIDS\n  STF_ULP_EQUAL(stirling(bs::Inf<T>()),  bs::Inf<T>(), 0.5);\n  STF_ULP_EQUAL(stirling(bs::Minf<T>()), bs::Nan<T>(), 0.5);\n  STF_ULP_EQUAL(stirling(bs::Mone<T>()), bs::Nan<T>(), 0.5);\n  STF_ULP_EQUAL(stirling(bs::Nan<T>()),  bs::Nan<T>(), 0.5);\n#endif\n  STF_ULP_EQUAL(bs::round(stirling(bs::One<T>())),  bs::One<T>(), 0.5);\n  STF_ULP_EQUAL(bs::round(stirling(bs::Two<T>())),  bs::One<T>(), 0.5);\n}\n", "meta": {"hexsha": "f616be0692fe70f6c05eeb2bc16f121a2e448c59", "size": 1332, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/scalar/stirling.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": "test/function/scalar/stirling.cpp", "max_issues_repo_name": "remymuller/boost.simd", "max_issues_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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/function/scalar/stirling.cpp", "max_forks_repo_name": "remymuller/boost.simd", "max_forks_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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": 36.0, "max_line_length": 100, "alphanum_fraction": 0.5878378378, "num_tokens": 369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.4642434822199055}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// statistics::model::algorithm::log_likelihood.hpp                          //\n//                                                                           //\n//  Copyright 2009 Erwann Rogard. Distributed under the Boost                //\n//  Software License, Version 1.0. (See accompanying file                    //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)         //\n///////////////////////////////////////////////////////////////////////////////\n#ifndef BOOST_STATISTICS_MODEL_ALGORITHM_LOG_LIKELIHOOD_HPP_ER_2009\n#define BOOST_STATISTICS_MODEL_ALGORITHM_LOG_LIKELIHOOD_HPP_ER_2009\n#include <boost/binary_op/algorithm/for_each.hpp>\n#include <boost/statistics/model/wrap/aggregate/model_parameter.hpp>\n#include <boost/statistics/model/functional/log_likelihood_accumulator.hpp>\n\nnamespace boost{ \nnamespace statistics{\nnamespace model{        \n\n    // Evaluates the likelihood at mp.parameter(), given model mp.model(),\n    // by summing all contributions from a dataset i.e. a\n    // sequence of covariates, [b_x,e_x), and reponses (starting at b_y)\n    template<typename T,typename M,typename P,typename ItX,typename ItE>\n    T\n    log_likelihood(\n        model_parameter_<M,P> mp,\n        ItX b_x,\n        ItX e_x,\n        ItE b_y\n    ){\n        typedef log_likelihood_accumulator<T,M,P> acc_;\n        acc_ acc(mp);\n        return boost::binary_op::for_each<acc_>(\n            b_x,\n            e_x,\n            b_y,\n            acc\n        ).value();\n    }\n\n    \n}// model\n}// statistics\n}// boost\n\n#endif", "meta": {"hexsha": "fe9e6134bab0b3bcf81c23a9f1879459a1c2d39a", "size": 1621, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "model copy/boost/statistics/model/algorithm/log_likelihood.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": "model copy/boost/statistics/model/algorithm/log_likelihood.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": "model copy/boost/statistics/model/algorithm/log_likelihood.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.8409090909, "max_line_length": 79, "alphanum_fraction": 0.5558297347, "num_tokens": 340, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.46407482501082487}}
{"text": "//\n// Created by green on 04/12/17.\n//\n#include <iostream>     // std::cout, std::fixed\n#include <iomanip>      // std::setprecision\n\n#include \"inc/Modules/LocationModule.h\"\n#include <boost/lexical_cast.hpp>\n#include <lapacke.h>\n#include \"inc/Exceptions/UnsupportedOperationException.h\"\n\nusing boost::lexical_cast;\n\n// I think nodes should be the scanned nodes m_ScannedNodes\nLocationModule::LocationModule(std::shared_ptr<node::NodeContainer>& nodes) : m_Nodes(nodes),\n                                                                              m_dgelsLoc(std::make_shared<Location>()),\n                                                                              m_dgetrsLoc(std::make_shared<Location>()),\n                                                                              m_dgesvLoc(std::make_shared<Location>())\n{\n\n}\n\nvoid LocationModule::CalculateLocations()\n{\n    boost::mutex::scoped_lock lock(g_i_mutex);\n    try\n    {\n      // I think m_Nodes should be the nodes read from Settings.json by the FileNodeReaderModule\n      calculateDgels(GetNodeTargets(m_Nodes)); // m_Nodes is a container of AP nodes, with known (x,y,z) coordinates\n\n      calculateDgesvDgetrs(GetNodeTargets(m_Nodes));\n      std::cerr << std::endl; // skip a line\n    }\n    catch (std::exception e)\n    {\n      //std::cout << \"Not Enough Nodes in Range.\" << std::endl;\n      // UnsupportedOperationException ex;\n      // throw(ex);\n    }\n\n}\n\nstd::shared_ptr<Location> LocationModule::GetLocation()\n{\n    CalculateLocations();\n    return m_dgelsLoc;\n}\n\nstd::shared_ptr<node::NodeContainer> LocationModule::GetNodeTargets(std::shared_ptr<node::NodeContainer> tempNodes)\n{\n  // I think tempNodes should be the nodes read from Settings.json by the FileNodeReaderModule\n  \n    if (tempNodes == NULL)\n    {\n        UnsupportedOperationException ex;\n        throw (ex);\n    }\n    std::shared_ptr<node::NodeContainer> targetNodes = std::make_shared<node::NodeContainer>();\n\n    std::sort(tempNodes->GetNodes().begin(), tempNodes->GetNodes().end(),\n              [](std::shared_ptr<INode> &lhs, std::shared_ptr<INode> &rhs)\n              {\n                  return lhs->getRSSI() > rhs->getRSSI();\n              });\n    for (auto &i : tempNodes->GetNodes())\n    {\n      // std::cerr << \"LocationModule::GetNodeTargets: tempNode: \" << i->getSSID() << std::endl;\n      \n      if (targetNodes->GetNodes().size() < 4 && i->getRSSI() != 0 && i->getRecentlyUpdated())\n        {\n\t  // add node to use in LSQ location calculation\n\t  targetNodes->AddNode(i); \n        }\n    }\n    for (auto &i : targetNodes->GetNodes())\n    {\n      // std::cout << \"RSSI ORDERING (SSID,RSSI,MAC): \" << i->getSSID() << \", \" << i->getRSSI() << \", \" << i->getMAC() << std::endl;\n    }\n    if (targetNodes->GetNodes().size() < 4)\n    {\n        std::exception e;\n        throw (e);\n    }\n    return targetNodes;\n}\n\nweb::json::value LocationModule::GetJson()\n{\n    CalculateLocations();\n    web::json::value response;\n    response[\"DGESV\"] = m_dgesvLoc->ToJson();\n    response[\"DGETRS\"] = m_dgetrsLoc->ToJson();\n    response[\"DGELS\"] = m_dgelsLoc->ToJson();\n    response[\"TargetNodes\"] = GetNodeTargets(m_Nodes)->ToJson();\n    return response;\n}\n\n\nweb::json::value LocationModule::BasicJson()\n{\n    CalculateLocations();\n    web::json::value response;\n    response[\"DGESV\"] = m_dgesvLoc->ToJson();\n    response[\"DGETRS\"] = m_dgetrsLoc->ToJson();\n    response[\"DGELS\"] = m_dgelsLoc->ToJson();\n    response = m_dgelsLoc->ToJson();\n    return response;\n}\n\nvoid LocationModule::calculateDgesvDgetrs(std::shared_ptr<node::NodeContainer> nodes)\n{\n    if (nodes->GetNodes().size() != 4)\n    {\n        throw (\"Error::Too few Nodes!\");\n    }\n\n    std::vector<std::shared_ptr<TargetNode>> Nodes;\n\n    for (std::shared_ptr<INode> a: nodes->GetNodes())\n    {\n        Nodes.push_back(std::static_pointer_cast<TargetNode>(a));\n    }\n\n    double A[3][3] = {2 * (Nodes[1]->getXCoord() - Nodes[0]->getXCoord()),\n                      2 * (Nodes[1]->getYCoord() - Nodes[0]->getYCoord()),\n                      2 * (Nodes[1]->getZCoord() - Nodes[0]->getZCoord()),\n                      2 * (Nodes[2]->getXCoord() - Nodes[0]->getXCoord()),\n                      2 * (Nodes[2]->getYCoord() - Nodes[0]->getYCoord()),\n                      2 * (Nodes[2]->getZCoord() - Nodes[0]->getZCoord()),\n                      2 * (Nodes[3]->getXCoord() - Nodes[0]->getXCoord()),\n                      2 * (Nodes[3]->getYCoord() - Nodes[0]->getYCoord()),\n                      2 * (Nodes[3]->getZCoord() - Nodes[0]->getZCoord())};\n\n    double B[3][1] = {(pow(Nodes[0]->GetDistance(), 2.0)) - (pow(Nodes[1]->GetDistance(), 2.0)) -\n                      (pow(Nodes[0]->getXCoord(), 2.0)) + (pow(Nodes[1]->getXCoord(), 2.0)) -\n                      (pow(Nodes[0]->getYCoord(), 2.0)) + (pow(Nodes[1]->getYCoord(), 2.0)) -\n                      (pow(Nodes[0]->getZCoord(), 2.0)) + (pow(Nodes[1]->getZCoord(), 2.0)),\n                      (pow(Nodes[0]->GetDistance(), 2.0)) - (pow(Nodes[2]->GetDistance(), 2.0)) -\n                      (pow(Nodes[0]->getXCoord(), 2.0)) + (pow(Nodes[2]->getXCoord(), 2.0)) -\n                      (pow(Nodes[0]->getYCoord(), 2.0)) + (pow(Nodes[2]->getYCoord(), 2.0)) -\n                      (pow(Nodes[0]->getZCoord(), 2.0)) + (pow(Nodes[2]->getZCoord(), 2.0)),\n                      (pow(Nodes[0]->GetDistance(), 2.0)) - (pow(Nodes[3]->GetDistance(), 2.0)) -\n                      (pow(Nodes[0]->getXCoord(), 2.0)) + (pow(Nodes[3]->getXCoord(), 2.0)) -\n                      (pow(Nodes[0]->getYCoord(), 2.0)) + (pow(Nodes[3]->getYCoord(), 2.0)) -\n                      (pow(Nodes[0]->getZCoord(), 2.0)) + (pow(Nodes[3]->getZCoord(), 2.0))};\n\n\n    lapack_int info, m, n, lda, ldb, nrhs;\n    lapack_int *ipiv;\n    m = 3;\n    n = 3;\n    nrhs = 1;\n    lda = 3;\n    ldb = 1;\n    ipiv = (lapack_int *) malloc(n * sizeof(lapack_int));\n    boost::timer::auto_cpu_timer t;\n    info = LAPACKE_dgesv(LAPACK_ROW_MAJOR, n, nrhs, *A, lda, ipiv, *B, ldb);\n    t.stop();\n\n    if (info > 0)\n    {\n        printf(\"The diagonal element %i of the triangular factor \", info);\n        printf(\"of A is zero, so that A does not have full rank;\\n\");\n        printf(\"the least squares solution could not be computed.\\n\");\n        return;\n    }\n\n    // printf(\"Calcuated values.\");\n    // fflush(stdout);\n    m_dgesvLoc->updateCoords(B[0][0], B[1][0], B[2][0]);\n    /*m_dgesvLoc->xCoord=(B[0][0]);\n    m_dgesvLoc->yCoord=(B[1][0]);\n    m_dgesvLoc->zCoord=(B[2][0]);*/\n    m_dgesvLoc->m_calculationTime = t.elapsed().wall;\n\n    std::cerr << \"Calculated Location (dgesv): \";\n    std::cerr << std::fixed << std::setprecision(4);\n    std::cerr <<  \"X:\" << lexical_cast<std::string>(B[0][0]) << \" Y:\" << lexical_cast<std::string>(B[1][0]) << \" Z:\"\n              << lexical_cast<std::string>(B[2][0]) << \" Time:\"\n              << lexical_cast<std::string>(m_dgesvLoc->m_calculationTime) << std::endl;\n\n    double B2[3][1] = {(pow(Nodes[0]->GetDistance(), 2.0)) - (pow(Nodes[1]->GetDistance(), 2.0)) -\n                       (pow(Nodes[0]->getXCoord(), 2.0)) + (pow(Nodes[1]->getXCoord(), 2.0)) -\n                       (pow(Nodes[0]->getYCoord(), 2.0)) + (pow(Nodes[1]->getYCoord(), 2.0)) -\n                       (pow(Nodes[0]->getZCoord(), 2.0)) + (pow(Nodes[1]->getZCoord(), 2.0)),\n                       (pow(Nodes[0]->GetDistance(), 2.0)) - (pow(Nodes[2]->GetDistance(), 2.0)) -\n                       (pow(Nodes[0]->getXCoord(), 2.0)) + (pow(Nodes[2]->getXCoord(), 2.0)) -\n                       (pow(Nodes[0]->getYCoord(), 2.0)) + (pow(Nodes[2]->getYCoord(), 2.0)) -\n                       (pow(Nodes[0]->getZCoord(), 2.0)) + (pow(Nodes[2]->getZCoord(), 2.0)),\n                       (pow(Nodes[0]->GetDistance(), 2.0)) - (pow(Nodes[3]->GetDistance(), 2.0)) -\n                       (pow(Nodes[0]->getXCoord(), 2.0)) + (pow(Nodes[3]->getXCoord(), 2.0)) -\n                       (pow(Nodes[0]->getYCoord(), 2.0)) + (pow(Nodes[3]->getYCoord(), 2.0)) -\n                       (pow(Nodes[0]->getZCoord(), 2.0)) + (pow(Nodes[3]->getZCoord(), 2.0))};\n\n    t.resume();\n    LAPACKE_dgetrs(LAPACK_ROW_MAJOR, 'N', n, nrhs, *A, lda, ipiv, *B2, ldb);\n\n    if (info > 0)\n    {\n        printf(\"The diagonal element %i of the triangular factor \", info);\n        printf(\"of A is zero, so that A does not have full rank;\\n\");\n        printf(\"the least squares solution could not be computed.\\n\");\n        return;\n    }\n\n    t.stop();\n    m_dgetrsLoc->updateCoords(B2[0][0], B2[1][0], B2[2][0]);\n    /*m_dgetrsLoc->xCoord=(B2[0][0]);\n    m_dgetrsLoc->yCoord=(B2[1][0]);\n    m_dgetrsLoc->zCoord=(B2[2][0]);*/\n\n    m_dgetrsLoc->m_calculationTime = t.elapsed().wall - m_dgesvLoc->m_calculationTime;\n\n    std::cerr << \"Calculated Location (dgetrs): \";\n    std::cerr << std::setprecision(4) << \"X:\" << lexical_cast<std::string>(B2[0][0]) << \" Y:\" << lexical_cast<std::string>(B2[1][0]) << \" Z:\"\n              << lexical_cast<std::string>(B2[2][0]) << \" Time:\"\n              << lexical_cast<std::string>(m_dgetrsLoc->m_calculationTime) << std::endl;\n\n    return;\n}\n\n\n/*\n * LocationModule::calculateDgels\n *\n * Input: nodes is a container of access point nodes, with known (x,y,z) coordinates\n *\n */\nvoid LocationModule::calculateDgels(std::shared_ptr<node::NodeContainer> nodes)\n{\n    if (nodes->GetNodes().size() != 4)\n    {\n        throw (\"Error::Too few Nodes!\");\n    }\n\n    std::vector<std::shared_ptr<TargetNode>> Nodes; // TargetNodes with known (x,y,z) coordinates\n\n    for (std::shared_ptr<INode> a: nodes->GetNodes())\n    {\n\t// I think we need to get the corresponding node from the TargetNodes container\n        Nodes.push_back(std::static_pointer_cast<TargetNode>(a));\n    }\n\n    double A[3][3] = {2 * (Nodes[1]->getXCoord() - Nodes[0]->getXCoord()),\n                      2 * (Nodes[1]->getYCoord() - Nodes[0]->getYCoord()),\n                      2 * (Nodes[1]->getZCoord() - Nodes[0]->getZCoord()),\n                      2 * (Nodes[2]->getXCoord() - Nodes[0]->getXCoord()),\n                      2 * (Nodes[2]->getYCoord() - Nodes[0]->getYCoord()),\n                      2 * (Nodes[2]->getZCoord() - Nodes[0]->getZCoord()),\n                      2 * (Nodes[3]->getXCoord() - Nodes[0]->getXCoord()),\n                      2 * (Nodes[3]->getYCoord() - Nodes[0]->getYCoord()),\n                      2 * (Nodes[3]->getZCoord() - Nodes[0]->getZCoord())};\n\n    double B[3][1] = {(pow(Nodes[0]->GetDistance(), 2.0)) - (pow(Nodes[1]->GetDistance(), 2.0)) -\n                      (pow(Nodes[0]->getXCoord(), 2.0)) + (pow(Nodes[1]->getXCoord(), 2.0)) -\n                      (pow(Nodes[0]->getYCoord(), 2.0)) + (pow(Nodes[1]->getYCoord(), 2.0)) -\n                      (pow(Nodes[0]->getZCoord(), 2.0)) + (pow(Nodes[1]->getZCoord(), 2.0)),\n                      (pow(Nodes[0]->GetDistance(), 2.0)) - (pow(Nodes[2]->GetDistance(), 2.0)) -\n                      (pow(Nodes[0]->getXCoord(), 2.0)) + (pow(Nodes[2]->getXCoord(), 2.0)) -\n                      (pow(Nodes[0]->getYCoord(), 2.0)) + (pow(Nodes[2]->getYCoord(), 2.0)) -\n                      (pow(Nodes[0]->getZCoord(), 2.0)) + (pow(Nodes[2]->getZCoord(), 2.0)),\n                      (pow(Nodes[0]->GetDistance(), 2.0)) - (pow(Nodes[3]->GetDistance(), 2.0)) -\n                      (pow(Nodes[0]->getXCoord(), 2.0)) + (pow(Nodes[3]->getXCoord(), 2.0)) -\n                      (pow(Nodes[0]->getYCoord(), 2.0)) + (pow(Nodes[3]->getYCoord(), 2.0)) -\n                      (pow(Nodes[0]->getZCoord(), 2.0)) + (pow(Nodes[3]->getZCoord(), 2.0))};\n\n    lapack_int info, m, n, lda, ldb, nrhs;\n\n    m = 3;\n    n = 3;\n    nrhs = 1;\n    lda = 3;\n    ldb = 1;\n    boost::timer::auto_cpu_timer t;\n    info = LAPACKE_dgels(LAPACK_ROW_MAJOR, 'N', m, n, nrhs, *A, lda, *B, ldb);\n    t.stop();\n    if (info > 0)\n    {\n        printf(\"The diagonal element %i of the triangular factor \", info);\n        printf(\"of A is zero, so that A does not have full rank;\\n\");\n        printf(\"the least squares solution could not be computed.\\n\");\n        return;\n    }\n\n    m_dgelsLoc->updateCoords(B[0][0], B[1][0], B[2][0]);\n    m_dgelsLoc->m_calculationTime = t.elapsed().wall;\n\n    std::cerr << \"Calculated Location (dgels): \";\n    std::cerr << std::setprecision(5) << \"X:\" << lexical_cast<std::string>(B[0][0]) << \" Y:\" << lexical_cast<std::string>(B[1][0]) << \" Z:\"\n              << lexical_cast<std::string>(B[2][0]) << \" Time:\"\n              << lexical_cast<std::string>(m_dgelsLoc->m_calculationTime) << std::endl;\n\n    return;\n\n}\n\n\nvoid LocationModule::initialize()\n{\n    m_isRunning = true;\n}\n\nvoid LocationModule::deInitialize()\n{\n    m_isRunning = false;\n}\n\nbool LocationModule::isRunning()\n{\n    return m_isRunning;\n}\n", "meta": {"hexsha": "4455ad546f23c7bbb62cd583a6023cf92c12101d", "size": 12656, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/LocationModule.cpp", "max_stars_repo_name": "PaulBryden/Pink_Panther", "max_stars_repo_head_hexsha": "e3a8cfadd27354dc98af6146a743666cba8c3962", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-09-06T01:04:20.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-13T21:32:35.000Z", "max_issues_repo_path": "src/LocationModule.cpp", "max_issues_repo_name": "PaulBryden/Pink_Panther", "max_issues_repo_head_hexsha": "e3a8cfadd27354dc98af6146a743666cba8c3962", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-10-10T18:21:59.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-22T02:19:38.000Z", "max_forks_repo_path": "src/LocationModule.cpp", "max_forks_repo_name": "PaulBryden/Pink_Panther", "max_forks_repo_head_hexsha": "e3a8cfadd27354dc98af6146a743666cba8c3962", "max_forks_repo_licenses": ["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.5641025641, "max_line_length": 141, "alphanum_fraction": 0.533817952, "num_tokens": 3855, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933183101078, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4640748150469582}}
{"text": "#include <boost/math/special_functions/bernoulli.hpp>\n", "meta": {"hexsha": "5bba71ba9a660def7b9478bb0eea6545d9500a99", "size": 54, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_special_functions_bernoulli.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_special_functions_bernoulli.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_special_functions_bernoulli.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 27.0, "max_line_length": 53, "alphanum_fraction": 0.8333333333, "num_tokens": 13, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234878, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.46404960444397714}}
{"text": "\n#include \"mesh/mechanics/beam/submesh.hpp\"\n\n#include \"geometry/profile_factory.hpp\"\n#include \"math/jacobian_determinant.hpp\"\n#include \"mesh/dof_allocator.hpp\"\n#include \"interpolations/interpolation_factory.hpp\"\n#include \"numeric/float_compare.hpp\"\n#include \"io/json.hpp\"\n\n#include <tbb/parallel_for.h>\n#include <Eigen/Geometry>\n\n#include <iostream>\n\nnamespace neon::mechanics::beam\n{\nsubmesh::submesh(json const& material_data,\n                 json const& simulation_data,\n                 json const& section_data,\n                 std::shared_ptr<material_coordinates>& coordinates,\n                 basic_submesh const& submesh)\n    : basic_submesh(submesh),\n      sf(make_line_interpolation(topology(), simulation_data)),\n      coordinates(coordinates),\n      view(sf->quadrature().points()),\n      variables(std::make_shared<internal_variable_type>(elements() * sf->quadrature().points())),\n      cm(std::make_unique<isotropic_linear>(variables, material_data))\n{\n    allocate_normal_and_tangent(section_data);\n\n    dof_allocator(node_indices, dof_indices, traits::dofs_per_node);\n\n    variables->add(variable::second::cauchy_stress,\n                   variable::scalar::shear_area_1,\n                   variable::scalar::shear_area_2,\n                   variable::scalar::cross_sectional_area,\n                   variable::scalar::second_moment_area_1,\n                   variable::scalar::second_moment_area_2);\n\n    profile = geometry::make_profile(\n        json{{\"name\", \"rect\"}, {\"type\", \"rectangle\"}, {\"width\", 1.0}, {\"height\", 1.0}});\n}\n\nvoid submesh::update_internal_variables(double)\n{\n    auto& A = variables->get(variable::scalar::cross_sectional_area);\n    auto& As1 = variables->get(variable::scalar::shear_area_1);\n    auto& As2 = variables->get(variable::scalar::shear_area_2);\n\n    auto& area_moment_1 = variables->get(variable::scalar::second_moment_area_1);\n    auto& area_moment_2 = variables->get(variable::scalar::second_moment_area_2);\n\n    // Loop over all elements and quadrature points to compute the profile\n    // properties for each quadrature point in the beam\n    tbb::parallel_for(std::int64_t{0}, elements(), [&, this](auto const element) {\n        sf->quadrature().for_each([&, this](auto const&, auto const l) {\n            A.at(view(element, l)) = profile->area();\n\n            auto const [shear_area_1, shear_area_2] = profile->shear_area();\n            As1.at(view(element, l)) = shear_area_1;\n            As2.at(view(element, l)) = shear_area_2;\n\n            auto const [I1, I2] = profile->second_moment_area();\n            area_moment_1.at(view(element, l)) = I1;\n            area_moment_2.at(view(element, l)) = I2;\n        });\n    });\n    cm->update_internal_variables();\n}\n\nauto submesh::tangent_stiffness(std::int32_t const element) const -> matrix const&\n{\n    static thread_local matrix ke(12, 12);\n\n    auto const& configuration = coordinates->initial_configuration(local_node_view(element));\n\n    ke = rotation_matrix\n         * (bending_stiffness(configuration, element) + shear_stiffness(configuration, element)\n            + axial_stiffness(configuration, element) + torsional_stiffness(configuration, element))\n         * rotation_matrix.transpose();\n\n    return ke;\n}\n\nmatrix const& submesh::bending_stiffness(matrix3x const& configuration, std::int32_t const element) const\n{\n    static thread_local matrix2x B_bending(2, 6 * sf->number_of_nodes());\n    static thread_local matrix k_bending(6 * sf->number_of_nodes(), 6 * sf->number_of_nodes());\n\n    B_bending.setZero();\n    k_bending.setZero();\n\n    auto const& D_bending = variables->get(variable::second::bending_stiffness);\n\n    sf->quadrature().integrate_inplace(k_bending, [&, this](auto const& femval, auto const l) {\n        auto const& [N, dN] = femval;\n\n        double const j = jacobian_determinant(configuration * dN);\n\n        for (int i = 0; i < sf->number_of_nodes(); ++i)\n        {\n            auto const offset = i * 6;\n\n            B_bending(0, 3 + offset) = B_bending(1, 4 + offset) = dN(i, l) / j;\n        }\n\n        return B_bending.transpose() * D_bending.at(view(element, l)) * B_bending * j;\n    });\n    return k_bending;\n}\n\nmatrix const& submesh::shear_stiffness(matrix3x const& configuration, std::int32_t const element) const\n{\n    static thread_local matrix2x B_shear(2, 6 * sf->number_of_nodes());\n    static thread_local matrix k_shear(6 * sf->number_of_nodes(), 6 * sf->number_of_nodes());\n\n    B_shear.setZero();\n    k_shear.setZero();\n\n    auto const& D_shear = variables->get(variable::second::shear_stiffness);\n\n    sf->quadrature().integrate_inplace(k_shear, [&, this](auto const& femval, auto const l) {\n        auto const& [N, dN] = femval;\n\n        auto const j = jacobian_determinant(configuration * dN);\n\n        for (int i = 0; i < sf->number_of_nodes(); ++i)\n        {\n            auto const offset = i * 6;\n\n            B_shear(0, 0 + offset) = B_shear(1, 1 + offset) = dN(i, l) / j;\n\n            B_shear(0, 4 + offset) = -N(i, l);\n            B_shear(1, 3 + offset) = N(i, l);\n        }\n        return B_shear.transpose() * D_shear.at(view(element, l)) * B_shear * j;\n    });\n    return k_shear;\n}\n\nmatrix const& submesh::axial_stiffness(matrix3x const& configuration, std::int32_t const element) const\n{\n    static thread_local vector B_axial(6 * sf->number_of_nodes());\n    static thread_local matrix k_axial(6 * sf->number_of_nodes(), 6 * sf->number_of_nodes());\n\n    B_axial.setZero();\n    k_axial.setZero();\n\n    auto const D_axial = variables->get(variable::scalar::axial_stiffness);\n\n    sf->quadrature().integrate_inplace(k_axial, [&, this](auto const& femval, auto const l) {\n        auto const& [N, dN] = femval;\n\n        auto const j = jacobian_determinant(configuration * dN);\n\n        for (int i = 0; i < sf->number_of_nodes(); ++i)\n        {\n            auto const offset = i * 6;\n\n            B_axial(2 + offset) = dN(i, l) / j;\n        }\n\n        return B_axial * D_axial.at(view(element, l)) * B_axial.transpose() * j;\n    });\n    return k_axial;\n}\n\nmatrix const& submesh::torsional_stiffness(matrix3x const& configuration,\n                                           std::int32_t const element) const\n{\n    static thread_local vector B_torsion(6 * sf->number_of_nodes());\n    static thread_local matrix k_torsion(6 * sf->number_of_nodes(), 6 * sf->number_of_nodes());\n\n    B_torsion.setZero();\n    k_torsion.setZero();\n\n    auto const D_torsion = variables->get(variable::scalar::torsional_stiffness);\n\n    sf->quadrature().integrate_inplace(k_torsion, [&, this](auto const& femval, auto const l) {\n        auto const& [N, dN] = femval;\n\n        auto const j = jacobian_determinant(configuration * dN);\n\n        for (int i = 0; i < sf->number_of_nodes(); ++i)\n        {\n            auto const offset = i * 6;\n\n            B_torsion(5 + offset) = dN(i, l) / j;\n        }\n\n        return B_torsion * D_torsion.at(view(element, l)) * B_torsion.transpose() * j;\n    });\n    return k_torsion;\n}\n\nvoid submesh::allocate_normal_and_tangent(json const& section_data)\n{\n    if (section_data.find(\"tangent\") == section_data.end())\n    {\n        throw std::domain_error(\"A \\\"tangent\\\" vector must be specified in the \\\"section\\\"\");\n    }\n    if (section_data.find(\"normal\") == section_data.end())\n    {\n        throw std::domain_error(\"A \\\"normal\\\" vector must be specified in the \\\"section\\\"\");\n    }\n\n    auto const& tangent_vector = section_data[\"tangent\"];\n\n    if (!tangent_vector.is_array() || tangent_vector.size() != 3)\n    {\n        throw std::domain_error(\"A \\\"tangent\\\" vector must be specified using three (3) \"\n                                \"coordinates [x, y, z]\");\n    }\n\n    auto const& normal_vector = section_data[\"normal\"];\n\n    if (!normal_vector.is_array() || normal_vector.size() != 3)\n    {\n        throw std::domain_error(\"A \\\"normal\\\" vector must be specified using three (3) coordinates \"\n                                \"[x, y, z]\");\n    }\n\n    tangent(0) = tangent_vector[0];\n    tangent(1) = tangent_vector[1];\n    tangent(2) = tangent_vector[2];\n\n    normal(0) = normal_vector[0];\n    normal(1) = normal_vector[1];\n    normal(2) = normal_vector[2];\n\n    if (!is_approx(normal.dot(tangent), 0.0))\n    {\n        throw std::domain_error(\"normal and tangent vectors must be orthogonal\");\n    }\n\n    matrix3 rotation;\n\n    // Local coordinate (x1)\n    rotation.col(0) = normal;\n    // Local coordinate (x2)\n    rotation.col(1) = normal.cross(tangent);\n    // Local coordinate (x3)\n    rotation.col(2) = tangent;\n\n    rotation_matrix = matrix12::Zero();\n\n    rotation_matrix.block<3, 3>(0, 0) = rotation;\n    rotation_matrix.block<3, 3>(3, 3) = rotation;\n    rotation_matrix.block<3, 3>(6, 6) = rotation;\n    rotation_matrix.block<3, 3>(9, 9) = rotation;\n}\n}\n", "meta": {"hexsha": "56525879e51dbe0058c51d0fb8d9f19e9c84ae08", "size": 8747, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mesh/mechanics/beam/submesh.cpp", "max_stars_repo_name": "dbeurle/neon", "max_stars_repo_head_hexsha": "63cd2929a6eaaa0e1654c729cd35a9a52a706962", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2018-07-12T17:06:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-20T23:13:26.000Z", "max_issues_repo_path": "src/mesh/mechanics/beam/submesh.cpp", "max_issues_repo_name": "dbeurle/neon", "max_issues_repo_head_hexsha": "63cd2929a6eaaa0e1654c729cd35a9a52a706962", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 119.0, "max_issues_repo_issues_event_min_datetime": "2016-06-22T07:36:04.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-10T19:38:12.000Z", "max_forks_repo_path": "src/mesh/mechanics/beam/submesh.cpp", "max_forks_repo_name": "dbeurle/neon", "max_forks_repo_head_hexsha": "63cd2929a6eaaa0e1654c729cd35a9a52a706962", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2017-10-08T16:51:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-15T08:08:04.000Z", "avg_line_length": 34.437007874, "max_line_length": 105, "alphanum_fraction": 0.6349605579, "num_tokens": 2325, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.4640495997734763}}
{"text": "#pragma once\n#include <type_traits>\n#include <vector>\n#include <string>\n#include <array>\n#include <exception>\n#include <boost/multiprecision/cpp_int.hpp>\n#include \"keys.hpp\"\n#include \"stream_handler.hpp\"\n\nnamespace mp = boost::multiprecision;\n\nnamespace rsa {\n\n    template<size_t E, size_t D>\n    struct cipher {\n\n        template<\n                typename Handler,\n                typename = std::enable_if_t<has_operation_v<Handler, read_number_padding_operation> && has_operation_v<Handler, eof_operation>>>\n        static auto encrypt(Handler& handler, const keys<D * 8>& keys, unsigned int& n) {\n            std::vector<typename num_utils<D * 8>::number> result;\n            while (!handler.eof())\n                result.push_back(mp::powm(\n                        static_cast<typename num_utils<D * 8>::number>(handler.template read_number_padding<E * 8>(n)),\n                        keys.get_e(), keys.get_n()));\n            return result;\n        }\n\n        template<\n                typename Handler,\n                typename = std::enable_if_t<has_operation_v<Handler, read_number_operation> && has_operation_v<Handler, eof_operation>>>\n        static auto decrypt(Handler& handler, const keys<D * 8>& keys) {\n            std::vector<typename num_utils<E * 8>::number> result;\n            while (!handler.eof())\n                result.push_back(static_cast<typename num_utils<E * 8>::number>(mp::powm(\n                        static_cast<typename num_utils<D * 8>::number>(handler.template read_number<D * 8>()),\n                        keys.get_d(), keys.get_n())));\n            return result;\n        }\n\n    };\n\n}// namespace rsa\n", "meta": {"hexsha": "14e1e68e04692cdb825ab312cbc4daafca5c14f1", "size": 1643, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cipher.hpp", "max_stars_repo_name": "GoldFeniks/RSA", "max_stars_repo_head_hexsha": "0e5020202d03a84a217bd2cfd416a09590a71b37", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cipher.hpp", "max_issues_repo_name": "GoldFeniks/RSA", "max_issues_repo_head_hexsha": "0e5020202d03a84a217bd2cfd416a09590a71b37", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cipher.hpp", "max_forks_repo_name": "GoldFeniks/RSA", "max_forks_repo_head_hexsha": "0e5020202d03a84a217bd2cfd416a09590a71b37", "max_forks_repo_licenses": ["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.5111111111, "max_line_length": 144, "alphanum_fraction": 0.6007303713, "num_tokens": 346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.831143031127974, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.46404959043247435}}
{"text": "/*\n * \n * Copyright (c) Toon Knapen, Karl Meerbergen & Kresimir Fresl 2003\n *\n * Permission to copy, modify, use and distribute this software \n * for any non-commercial or commercial purpose is granted provided \n * that this license appear on all copies of the software source code.\n *\n * Authors assume no responsibility whatsoever for its use and makes \n * no guarantees about its quality, correctness or reliability.\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_HEEV_HPP\n#define BOOST_NUMERIC_BINDINGS_LAPACK_HEEV_HPP\n\n#include <boost/numeric/bindings/traits/traits.hpp>\n#include <boost/numeric/bindings/traits/type.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/std_vector.hpp>\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n#  include <boost/static_assert.hpp>\n#  include <boost/type_traits.hpp>\n#endif \n\n\nnamespace boost { namespace numeric { namespace bindings { \n\n  namespace lapack {\n\n    ///////////////////////////////////////////////////////////////////\n    //\n    // Eigendecomposition of a complex Hermitian matrix A = Q * D * Q'\n    // \n    ///////////////////////////////////////////////////////////////////\n\n    /* \n     * heev() computes the eigendecomposition of a N x N matrix\n     * A = Q * D * Q',  where Q is a N x N unitary matrix and\n     * D is a diagonal matrix. The diagonal element D(i,i) is an\n     * eigenvalue of A and Q(:,i) is a corresponding eigenvector.\n     * The eigenvalues are stored in ascending order.\n     *\n     * On return of heev, A is overwritten by Q and w contains the main\n     * diagonal of D.\n     *\n     * int heev (char jobz, char uplo, A& a, W& w, minimal_workspace ) ;\n     *    jobz : 'V' : compute eigenvectors\n     *           'N' : do not compute eigenvectors\n     *    uplo : 'U' : only the upper triangular part of A is used on input.\n     *           'L' : only the lower triangular part of A is used on input.\n     */ \n\n    namespace detail {\n\n      inline \n      void heev (char const jobz, char const uplo, int const n,\n\t\t traits::complex_f* a, int const lda,\n                 float* w, traits::complex_f* work, int const lwork,\n                 float* rwork, int& info) \n      {\n        LAPACK_CHEEV (&jobz, &uplo, &n,\n\t\t      reinterpret_cast<fcomplex_t*>(a), &lda, w,\n\t\t      reinterpret_cast<fcomplex_t*>(work), &lwork,\n\t\t      rwork, &info);\n      }\n\n      inline \n      void heev (char const jobz, char const uplo, int const n,\n\t\t traits::complex_d* a, int const lda,\n                 double* w, traits::complex_d* work, int const lwork,\n                 double* rwork, int& info) \n      {\n        LAPACK_ZHEEV (&jobz, &uplo, &n,\n\t\t      reinterpret_cast<dcomplex_t*>(a), &lda, w,\n\t\t      reinterpret_cast<dcomplex_t*>(work), &lwork,\n\t\t      rwork, &info);\n      }\n\n\n      template <typename A, typename W, typename Work, typename RWork>\n      inline\n      int heev (char jobz, char uplo, A& a, W& w, Work& work, RWork& rwork) {\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n        BOOST_STATIC_ASSERT((boost::is_same<\n          typename traits::matrix_traits<A>::matrix_structure, \n          traits::general_t\n        >::value)); \n#endif \n\n        int const n = traits::matrix_size1 (a);\n        assert (traits::matrix_size2 (a)==n); \n        assert (traits::vector_size (w)==n); \n        assert (2*n-1 <= traits::vector_size (work)); \n        assert (3*n-2 <= traits::vector_size (rwork)); \n        assert ( uplo=='U' || uplo=='L' );\n        assert ( jobz=='N' || jobz=='V' );\n\n        int info; \n        detail::heev (jobz, uplo, n,\n                     traits::matrix_storage (a), \n                     traits::leading_dimension (a),\n                     traits::vector_storage (w),  \n                     traits::vector_storage (work),\n                     traits::vector_size (work),\n                     traits::vector_storage (rwork),\n                     info);\n        return info; \n      }\n    } // namespace detail\n\n\n    // Function that allocates temporary arrays\n    template <typename A, typename W>\n    int heev (char jobz, char uplo, A& a, W& w, minimal_workspace ) {\n       typedef typename A::value_type                              value_type ;\n       typedef typename traits::type_traits<value_type>::real_type real_type ;\n\n       int const n = traits::matrix_size1 (a);\n\n       traits::detail::array<value_type> work( std::max(1,2*n-1) );\n       traits::detail::array<real_type> rwork( std::max(3*n-1,1) );\n\n       return detail::heev( jobz, uplo, a, w, work, rwork );\n    }\n\n\n    // Function that allocates temporary arrays\n    template <typename A, typename W>\n    int heev (char jobz, char uplo, A& a, W& w, optimal_workspace ) {\n       typedef typename A::value_type                              value_type ;\n       typedef typename traits::type_traits<value_type>::real_type real_type ;\n\n       int const n = traits::matrix_size1 (a);\n\n       traits::detail::array<value_type> work( std::max(1,33*n) );\n       traits::detail::array<real_type> rwork( std::max(3*n-1,1) );\n\n       return detail::heev( jobz, uplo, a, w, work, rwork );\n    }\n\n\n    // Function that uses given workarrays\n    template <typename A, typename W, typename WC, typename WR>\n    int heev (char jobz, char uplo, A& a, W& w, detail::workspace2<WC,WR> workspace ) {\n       typedef typename A::value_type                              value_type ;\n       typedef typename traits::type_traits<value_type>::real_type real_type ;\n\n       return detail::heev( jobz, uplo, a, w, workspace.w_, workspace.wr_ );\n    }\n\n  }\n\n}}}\n\n#endif \n", "meta": {"hexsha": "431261b06af6102b55b0496f8858c528b47a1bf4", "size": 5780, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "applications/mkl_solvers_application/external_includes/boost/numeric/bindings/lapack/heev.hpp", "max_stars_repo_name": "jiaqiwang969/Kratos-test", "max_stars_repo_head_hexsha": "ed082abc163e7b627f110a1ae1da465f52f48348", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "applications/mkl_solvers_application/external_includes/boost/numeric/bindings/lapack/heev.hpp", "max_issues_repo_name": "jiaqiwang969/Kratos-test", "max_issues_repo_head_hexsha": "ed082abc163e7b627f110a1ae1da465f52f48348", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "applications/mkl_solvers_application/external_includes/boost/numeric/bindings/lapack/heev.hpp", "max_forks_repo_name": "jiaqiwang969/Kratos-test", "max_forks_repo_head_hexsha": "ed082abc163e7b627f110a1ae1da465f52f48348", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.243902439, "max_line_length": 87, "alphanum_fraction": 0.6, "num_tokens": 1467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.46404721316583414}}
{"text": "#define BOOST_TEST_MODULE arithmetic\n#include <boost/test/included/unit_test.hpp>\n#include \"exprtest.hpp\"\n\nEXPRTEST(basicop1, \" 2 +\\t3\\n\",  5)       // Whitespace ignored\nEXPRTEST(basicop2, \" 2 -\\t3\\n\", -1)\nEXPRTEST(basicop3, \" 2 *\\t3\\n\",  6)\nEXPRTEST(basicop4, \" 2 /\\t3\\n\",  2./3.)   // Double division\nEXPRTEST(basicop5, \" 2 ** 3\\n\",  8)\n", "meta": {"hexsha": "a68780cd28382d42a8b61083b969365eb74e322e", "size": 340, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/arithmetic.cpp", "max_stars_repo_name": "hmenke/boost_matheval", "max_stars_repo_head_hexsha": "013f28cb001b30a3d9d47758cf1a9e6456d5356e", "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": "tests/arithmetic.cpp", "max_issues_repo_name": "hmenke/boost_matheval", "max_issues_repo_head_hexsha": "013f28cb001b30a3d9d47758cf1a9e6456d5356e", "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": "tests/arithmetic.cpp", "max_forks_repo_name": "hmenke/boost_matheval", "max_forks_repo_head_hexsha": "013f28cb001b30a3d9d47758cf1a9e6456d5356e", "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": 34.0, "max_line_length": 63, "alphanum_fraction": 0.6558823529, "num_tokens": 131, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.46404720744327543}}
{"text": "#include <boost/simd/function/load.hpp>\n#include <boost/simd/function/multiplies.hpp>\n#include <boost/simd/function/plus.hpp>\n#include <boost/simd/function/sum.hpp>\n#include <boost/simd/pack.hpp>\n\n// [scalar-dot-simd]\nValue simddot(Value* first1, Value* last1, Value* first2)\n{\n  namespace bs = boost::simd;\n  using pack_t = bs::pack<Value>;\n\n  pack_t tmp{0};\n  int card = pack_t::static_size;\n\n  for (; first1 + card <= last1; first1 += card, first2 += card) {\n    // Load current values from the datasets\n    pack_t x1 = bs::load<pack_t>(first1);\n    pack_t x2 = bs::load<pack_t>(first2);\n    // Computation\n    tmp = tmp + x1 * x2;\n  }\n\n  Value dot_product = bs::sum(tmp); // horizontal SIMD vector summation\n  for (; first1 < last1; ++first1, ++first2) {\n    dot_product += (*first1) * (*first2);\n  }\n\n  return dot_product;\n}\n//! [scalar-dot-simd]\n", "meta": {"hexsha": "37d6c1338ce3fa8834754d63b29430ab0c629467", "size": 852, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/examples/dotsimd.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/dotsimd.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/dotsimd.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": 26.625, "max_line_length": 71, "alphanum_fraction": 0.6572769953, "num_tokens": 255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4640472074432754}}
{"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_EXPONENTIAL_FUNCTIONS_SCALAR_IMPL_LOGS_D_LOG_HPP_INCLUDED\n#define NT2_EXPONENTIAL_FUNCTIONS_SCALAR_IMPL_LOGS_D_LOG_HPP_INCLUDED\n\n#include <nt2/include/functions/scalar/sqr.hpp>\n#include <nt2/include/functions/scalar/tofloat.hpp>\n#include <nt2/include/functions/scalar/is_ltz.hpp>\n#include <nt2/include/functions/scalar/is_eqz.hpp>\n#include <nt2/include/functions/scalar/is_greater.hpp>\n#include <nt2/include/functions/scalar/multiplies.hpp>\n#include <nt2/include/functions/scalar/plus.hpp>\n#include <nt2/include/functions/scalar/fast_frexp.hpp>\n#include <nt2/include/functions/scalar/genmask.hpp>\n#include <nt2/include/functions/scalar/minusone.hpp>\n#include <nt2/include/functions/scalar/fma.hpp>\n#include <nt2/include/functions/scalar/bitwise_and.hpp>\n#include <nt2/polynomials/functions/scalar/impl/horner.hpp>\n#include <nt2/include/constants/real_splat.hpp>\n#include <nt2/include/constants/invlog_2.hpp>\n#include <nt2/include/constants/invlog_10.hpp>\n#include <nt2/include/constants/log_2olog_10.hpp>\n#include <nt2/include/constants/sqrt_2o_2.hpp>\n#include <nt2/include/constants/mone.hpp>\n#include <nt2/include/constants/zero.hpp>\n#include <nt2/include/constants/two.hpp>\n#include <nt2/include/constants/minf.hpp>\n#include <nt2/include/constants/half.hpp>\n#include <nt2/include/constants/nan.hpp>\n#include <boost/simd/sdk/config.hpp>\n\n#ifndef BOOST_SIMD_NO_NANS\n#include <nt2/include/functions/scalar/is_nan.hpp>\n#endif\n#ifndef BOOST_SIMD_NO_INFINITIES\n#include <nt2/include/constants/inf.hpp>\n#endif\n\nnamespace nt2 { namespace details\n{\n  //////////////////////////////////////////////////////////////////////////////\n  // math log functions\n  //////////////////////////////////////////////////////////////////////////////\n\n  template < class A0 >\n  struct logarithm< A0, tag::not_simd_type, double>\n  {\n    static inline void kernel_log(const A0& a0,\n                                  A0& dk,\n                                  A0& hfsq,\n                                  A0& s,\n                                  A0& R,\n                                  A0& f)\n    {\n      typedef typename meta::as_integer<A0, signed>::type int_type;\n      typedef typename meta::scalar_of<A0>::type               sA0;\n      A0 x;\n      int_type k;\n      nt2::fast_frexp(a0, x, k);\n      const int_type x_lt_sqrthf = nt2::is_greater(nt2::Sqrt_2o_2<A0>(), x)?nt2::Mone<int_type>():nt2::Zero<int_type>();\n      k += x_lt_sqrthf;\n      f = nt2::minusone(x+nt2::b_and(x, nt2::genmask(x_lt_sqrthf)));\n      dk = nt2::tofloat(k);\n      s = f/nt2::add(nt2::Two<A0>(),f);\n      A0 z = nt2::sqr(s);\n      A0 w = nt2::sqr(z);\n      A0 t1= w*nt2::horner<NT2_HORNER_COEFF_T(sA0, 3,\n                                              (0x3fc39a09d078c69fll,\n                                               0x3fcc71c51d8e78afll,\n                                               0x3fd999999997fa04ll)\n                                             )> (w);\n      A0 t2= z*horner<NT2_HORNER_COEFF_T(sA0, 4,\n                                         (0x3fc2f112df3e5244ll,\n                                          0x3fc7466496cb03dell,\n                                          0x3fd2492494229359ll,\n                                          0x3fe5555555555593ll)\n                                        )> (w);\n      R = t2+t1;\n      hfsq = nt2::mul(Half<A0>(), nt2::sqr(f));\n    }\n\n    static inline A0 log(const A0& a0)\n    {\n      // ln(2)hi  =  6.93147180369123816490e-01  or  0x3fe62e42fee00000\n      // ln(2)lo  =  1.90821492927058770002e-10  or  0x3dea39ef35793c76\n#ifndef BOOST_SIMD_NO_INFINITIES\n      if (a0 == Inf<A0>()) return a0;\n#endif\n      if (is_eqz(a0)) return nt2::Minf<A0>();\n#ifdef BOOST_SIMD_NO_NANS\n      if (nt2::is_ltz(a0)) return nt2::Nan<A0>();\n#else\n      if (nt2::is_nan(a0)||nt2::is_ltz(a0)) return nt2::Nan<A0>();\n#endif\n      A0 dk, hfsq, s, R, f;\n      kernel_log(a0, dk, hfsq, s, R, f);\n      return  nt2::mul(dk, double_constant<A0, 0x3fe62e42fee00000ll>())-\n        ((hfsq-(s*(hfsq+R)+nt2::mul(dk,double_constant<A0, 0x3dea39ef35793c76ll>())))-f);\n    }\n\n    static inline A0 log2(const A0& a0)\n    {\n#ifndef BOOST_SIMD_NO_INFINITIES\n      if (a0 == nt2::Inf<A0>()) return a0;\n#endif\n      if (nt2::is_eqz(a0)) return nt2::Minf<A0>();\n#ifdef BOOST_SIMD_NO_NANS\n      if (nt2::is_ltz(a0)) return nt2::Nan<A0>();\n#else\n      if (nt2::is_nan(a0)||nt2::is_ltz(a0)) return nt2::Nan<A0>();\n#endif\n      A0 dk, hfsq, s, R, f;\n      kernel_log(a0, dk, hfsq, s, R, f);\n      return -(hfsq-(s*(hfsq+R))-f)*Invlog_2<A0>()+dk;\n    }\n\n    static inline A0 log10(const A0& a0)\n    {\n#ifndef BOOST_SIMD_NO_INFINITIES\n      if (a0 == nt2::Inf<A0>()) return a0;\n#endif\n      if (nt2::is_eqz(a0)) return nt2::Minf<A0>();\n#ifdef BOOST_SIMD_NO_NANS\n      if (nt2::is_ltz(a0)) return nt2::Nan<A0>();\n#else\n      if (nt2::is_nan(a0)||nt2::is_ltz(a0)) return nt2::Nan<A0>();\n#endif\n      A0 dk, hfsq, s, R, f;\n      kernel_log(a0, dk, hfsq, s, R, f);\n      return -(hfsq-(s*(hfsq+R))-f)*nt2::Invlog_10<A0>()+dk*nt2::Log_2olog_10<A0>();\n    }\n  };\n} }\n\n\n#endif\n", "meta": {"hexsha": "27e87f62667f335471f63dc5603740878f753413", "size": 5551, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/exponential/include/nt2/exponential/functions/scalar/impl/logs/d_log.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/exponential/include/nt2/exponential/functions/scalar/impl/logs/d_log.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/exponential/include/nt2/exponential/functions/scalar/impl/logs/d_log.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.8181818182, "max_line_length": 120, "alphanum_fraction": 0.5660241398, "num_tokens": 1665, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4640472074432754}}
{"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\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include <cmath>\n\n// #include <boost/test/minimal.hpp>\n#include <boost/numeric/mtl/mtl.hpp>\n#include <boost/numeric/itl/itl.hpp>\n\n\nstruct Random\n{\n  std::complex<double> operator()() const\n  {\n    return std::complex<double>(\n        (2.*(static_cast<double>(rand())/RAND_MAX - 0.5)),\n        (2.*(static_cast<double>(rand())/RAND_MAX - 0.5))\n        );\n  }\n};\n\ntemplate <typename Matrix>\nvoid test1(Matrix& m, double tau)\n{\n  Random m_rand;\n  mtl::mat::inserter<Matrix> ins(m);\n  size_t nrows=num_rows(m);\n  std::complex<double> val;\n  for (size_t r=0;r<nrows;++r)\n  {\n    for (size_t c=0;c<nrows;++c)\n    {\n      if(r==c) \n        ins(r,c) << 1.;\n      else\n      {\n        val=m_rand();\n        if (abs(val)<tau)\n          ins(r,c) << val;  \n      } \n    }\n  } \n}\n\nint main(int, char**)\n{\n  const int size= 10, N = size * size; // Original from Jan had 2000 \n  const int Niter = 3*N;\n\n  typedef mtl::compressed2D<double> matrix_type;\n  //typedef compressed2D<std::complex<double> ,mat::parameters<tag::col_major> > matrix_type;\n  matrix_type                   A(N, N);\n  laplacian_setup(A, size, size);\n  mtl::dense_vector<double> b(N), x(N, 1.0);\n  b= A*x;\n\n  itl::pc::identity<matrix_type>     Ident(A);\n   \n  x= 0.0;\n  itl::cyclic_iteration<double> iter_1(b, Niter, 1.e-8, 0.0, 5);\n  idr_s(A, x, b, Ident, Ident, iter_1, 4);\n#if 0\n  std::cout << \"Non-preconditioned bicgstab(2)\" << std::endl;\n  x= 0.5;\n  itl::cyclic_iteration<double> iter_2b(b, Niter, 1.e-8, 0.0, 5);\n  idr_s(A, x, b, Ident, Ident, iter_2b,2);\n\n  std::cout << \"Non-preconditioned bicgstab(4)\" << std::endl;\n  x= 0.5;\n  itl::cyclic_iteration<double> iter_4b(b, Niter, 1.e-8, 0.0, 5);\n  idr_s(A, x, b, Ident, Ident, iter_4b,4);\n\n  std::cout << \"Non-preconditioned bicgstab(8)\" << std::endl;\n  x= 0.5;\n  itl::cyclic_iteration<double> iter_8b(b, Niter, 1.e-8, 0.0, 5);\n  idr_s(A, x, b, Ident, Ident, iter_8b,8);\n\n  itl::pc::ilu_0<matrix_type>        P(A);\n  \n  std::cout << \"Right ilu(0) preconditioned bicgstab(1)\" << std::endl;\n  x= 0.5;\n  itl::cyclic_iteration<double> iter_1r(b, Niter, 1.e-8, 0.0, 5);\n  idr_s(A, x, b, Ident, P, iter_1r,1);\n \n  std::cout << \"Right ilu(0) preconditioned bicgstab(2)\" << std::endl;\n  x= 0.5;\n  itl::cyclic_iteration<double> iter_2r(b, Niter, 1.e-8, 0.0, 5);\n  idr_s(A, x, b, Ident, P, iter_2r,2);\n\n  std::cout << \"Left ilu(0) preconditioned bicgstab(4)\" << std::endl;\n  x= 0.5;\n  itl::cyclic_iteration<double> iter_4l(b, Niter, 1.e-8, 0.0, 5);\n  idr_s(A, x, b, P, Ident, iter_4l,4);\n\n  std::cout << \"Right ilu(0) preconditioned bicgstab(4)\" << std::endl;\n  x= 0.5;\n  itl::cyclic_iteration<double> iter_4r(b, Niter, 1.e-8, 0.0, 5);\n  idr_s(A, x, b, Ident, P, iter_4r,4);\n\n  std::cout << \"Right ilu(0) preconditioned bicgstab(8)\" << std::endl;\n  x= 0.5;\n  itl::cyclic_iteration<double> iter_8r(b, Niter, 1.e-8, 0.0, 5);\n  idr_s(A, x, b, Ident, P, iter_8r,8);\n#endif\n  return 0;\n}\n", "meta": {"hexsha": "b4efe6eb2f2d7e47d43cff755132dc83fd5c1c11", "size": 3328, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/itl/test/idr_s_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/itl/test/idr_s_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/itl/test/idr_s_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.6896551724, "max_line_length": 94, "alphanum_fraction": 0.6120793269, "num_tokens": 1255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4640472074432754}}
{"text": "#include <iostream>\n#include <cmath>\n#include <algorithm>\n\n#include <Eigen/Dense>\n\n#include <TriMesh.h>\n\n#include <GL/glut.h>\n#include <gl/glu.h>\n\n#include \"Mesh.h\"\n\nusing namespace std;\nusing namespace Eigen;\nusing namespace trimesh;\nusing namespace sen;\n\nsen::Mesh mesh;\nMatrixXf scaleFreeMatrix;\nMatrixXf Hp, D;\nint selected_id = 0;\n\nstd::vector<std::array<Eigen::Vector3f, 3>> temp_triangles_21;\n\nvoid ScreenToOpenGL(const Vector2f &screen_coord, Vector3f &opengl_coord)\n{\n\tGLint viewPort[4];\n\tGLdouble modelView[16];\n\tGLdouble projection[16];\n\tGLfloat winX, winY, winZ;\n\tGLdouble posX, posY, posZ;\n\tglPushMatrix();\n\tglLoadIdentity();\n\tglScalef(0.01f, 0.01f, 1.0f);\n\tglGetIntegerv(GL_VIEWPORT, viewPort);\n\tglGetDoublev(GL_MODELVIEW_MATRIX, modelView);\n\tglGetDoublev(GL_PROJECTION_MATRIX, projection);\n\tglPopMatrix();\n\n\twinX = screen_coord(0);\n\twinY = viewPort[3] - screen_coord[1];\n\tglReadPixels((int)winX, (int)winY, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &winZ);\n\tgluUnProject(winX, winY, 0, modelView, projection, viewPort, &posX, &posY, &posZ);\n\topengl_coord[0] = (float)posX;\n\topengl_coord[1] = (float)posY;\n\topengl_coord[2] = 0.0f;\n}\n\nvoid OpenGLToScreen(const Vector3f &opengl_coord, Vector2f &screen_coord)\n{\n\tGLint viewPort[4];\n\tGLdouble modelView[16];\n\tGLdouble projection[16];\n\tGLdouble winX, winY, winZ;\n\tGLfloat posX, posY, posZ;\n\tglPushMatrix();\n\tglGetIntegerv(GL_VIEWPORT, viewPort);\n\tglGetDoublev(GL_MODELVIEW_MATRIX, modelView);\n\tglGetDoublev(GL_PROJECTION_MATRIX, projection);\n\tglPopMatrix();\n\n\tposX = opengl_coord[0];\n\tposY = opengl_coord[1];\n\tposZ = opengl_coord[2];\n\n\tgluProject(posX, posY, posZ, modelView, projection, viewPort, &winX, &winY, &winZ);\n\tscreen_coord[0] = (float)winX;\n\tscreen_coord[1] = (float)viewPort[3] - (float)winY;\n}\n\nint FindHitVertex(float x, float y)\n{\n\tVector2f screen_coord(x, y);\n\tVector3f opengl_coord;\n\tfor (int i = 0; i < static_cast<int>(mesh.vertices.size()); ++i)\n\t{\n\t\tVector2f coord_2d;\n\t\topengl_coord = mesh.vertices[i].coord;\n\t\tOpenGLToScreen(opengl_coord, coord_2d);\n\t\tfloat length = sqrt((screen_coord - coord_2d).dot(screen_coord - coord_2d));\n\t\tif (length < 5)\n\t\t{\n\t\t\treturn mesh.vertices[i].id;\n\t\t}\n\t}\n\treturn -1;\n}\n\nvoid OnMouseClick(int button, int state, int x, int y)\n{\n\tif (button == GLUT_LEFT_BUTTON)\n\t{\n\t\tif (state == GLUT_DOWN)\n\t\t{\n\t\t\tint origial_id = FindHitVertex((float)x, (float)y);\n\t\t\tif (-1 == origial_id)\n\t\t\t\treturn;\n\t\t\tselected_id = find(mesh.vertices.begin(), mesh.vertices.end(), Vertex(origial_id)) - mesh.vertices.begin();\n\t\t}\n\t\telse\n\t\t\tselected_id = -1;\n\t\tglutPostRedisplay();\n\t}\n\telse if (button == GLUT_RIGHT_BUTTON && state == GLUT_UP)\n\t{\n\t\tint HitPointId = FindHitVertex((float)x, (float)y);\n\t\tstd::cout << \"HitPointId: \" << HitPointId << std::endl;\n\t\tif (-1 != HitPointId)\n\t\t{\n\t\t\tif (mesh.find(HitPointId))\n\t\t\t{\n\t\t\t\tmesh.resetVerticesTo_uq();\n\t\t\t}\n\t\t\tstd::cout << \"computing\" << std::endl;\n\t\t\tscaleFreeMatrix = mesh.PreComputeScaleFreeMatrix();\n\t\t\tmesh.PreComputeScaleAdjustmentMatrixHf(Hp, D);\n\t\t\tglutPostRedisplay();\n\t\t}\n\t}\n}\n\nvoid OnMouseMove(int x, int y)\n{\n\tif (selected_id != 0 && mesh.q_size > 0)\n\t{\n\t\tVector2f screen_coord((float)x, (float)y);\n\t\tVector3f opengl_coord;\n\t\tScreenToOpenGL(screen_coord, opengl_coord);\n\t\topengl_coord *= 0.4f;// 0.4 for mesh, 1 for square mesh\n\t\tmesh.vertices[selected_id].coord = opengl_coord;\n\t\tglutPostRedisplay();\n\t}\n}\n\nvoid Deform()\n{\n\tif (mesh.q_size > 1 && mesh.q_size < static_cast<int>(mesh.vertices.size()))\n\t{\n\t\tVectorXf q(2 * mesh.q_size);\n\t\tfor (int i = static_cast<int>(mesh.vertices.size()) - mesh.q_size, j = 0; i < static_cast<int>(mesh.vertices.size()), j < mesh.q_size; ++i, ++j)\n\t\t{\n\t\t\tVector3f v = mesh.vertices[i].coord;\n\t\t\tq(2 * j) = v(0);\n\t\t\tq(2 * j + 1) = v(1);\n\t\t}\n\n\t\tVectorXf u = scaleFreeMatrix * q;\n\t\tfor (int i = 0; i < static_cast<int>(mesh.vertices.size()) - mesh.q_size; ++i)\n\t\t{\n\t\t\tmesh.vertices[i].coord(0) = u(2 * i);\n\t\t\tmesh.vertices[i].coord(1) = u(2 * i + 1);\n\t\t}\n\n\t\tVectorXf f = VectorXf::Zero(2 * mesh.vertices.size());\n\t\tfor (int i = 0; i < static_cast<int>(mesh.triangles.size()); ++i)\n\t\t{\n\t\t\tvector<Vector2f> current_triangle_points;\n\t\t\tmesh.AdjustScaleToTriangle(i, current_triangle_points);\n\t\t\tfor (int j = 0; j < 3; j++)\n\t\t\t{\n\t\t\t\tVector2f v0f, v1f, v2f;\n\t\t\t\tv0f = current_triangle_points[j];\n\t\t\t\tv1f = current_triangle_points[(j + 1) % 3];\n\n\t\t\t\tint v0f_id, v1f_id;\n\t\t\t\tv0f_id = find(mesh.vertices.begin(), mesh.vertices.end(), Vertex(mesh.triangles[i].vertex_id[j])) - mesh.vertices.begin();\n\t\t\t\tv1f_id = find(mesh.vertices.begin(), mesh.vertices.end(), Vertex(mesh.triangles[i].vertex_id[(j + 1) % 3])) - mesh.vertices.begin();\n\n\t\t\t\tint v0p_id = v0f_id;\n\t\t\t\tint v1p_id = v1f_id;\n\t\t\t\tf(2 * v0p_id) += -2 * v0f(0) + 2 * v1f(0);\n\t\t\t\tf(2 * v0p_id + 1) += -2 * v0f(1) + 2 * v1f(1);\n\t\t\t\tf(2 * v1p_id) += 2 * v0f(0) - 2 * v1f(0);\n\t\t\t\tf(2 * v1p_id + 1) += 2 * v0f(1) - 2 * v1f(1);\n\t\t\t}\n\t\t}\n\t\tint u_size = mesh.vertices.size() - mesh.q_size;\n\t\tVectorXf f0 = VectorXf::Zero(2 * u_size);\n\t\tfor (int i = 0; i < 2 * u_size; i++)\n\t\t{\n\t\t\tf0[i] = f[i];\n\t\t}\n\t\tVectorXf b = VectorXf::Zero(2 * u_size);\n\t\tfor (int i = static_cast<int>(mesh.vertices.size()) - mesh.q_size, j = 0; i < static_cast<int>(mesh.vertices.size()), j < mesh.q_size; ++i, ++j)\n\t\t{\n\t\t\tVector3f v = mesh.vertices[i].coord;\n\t\t\tq(2 * j) = v(0);\n\t\t\tq(2 * j + 1) = v(1);\n\t\t}\n\t\tb = -(D*q + f0);\n\t\tu = Hp.llt().solve(b);\n\t\tfor (int i = 0; i < static_cast<int>(mesh.vertices.size()) - mesh.q_size; ++i)\n\t\t{\n\t\t\tmesh.vertices[i].coord(0) = u(2 * i);\n\t\t\tmesh.vertices[i].coord(1) = u(2 * i + 1);\n\t\t}\n\t}\n}\n\nvoid display()\n{\n\tDeform();\n\tglClearColor(1, 1, 1, 1);\n\tglClear(GL_COLOR_BUFFER_BIT);\n\tglMatrixMode(GL_MODELVIEW);\n\tglLoadIdentity();\n\tgluLookAt(0, 0, 4, 0, 0, 0, 0, 1, 0);//4 for mesh, 10 for square mesh\n\tglLineWidth(2);\n\tglColor3f(0, 0, 0);\n\tfor (unsigned int i = 0; i < mesh.triangles.size(); i++)\n\t{\n\t\tint v0_id = find(mesh.vertices.begin(), mesh.vertices.end(), Vertex(mesh.triangles[i].vertex_id[0])) - mesh.vertices.begin();\n\t\tint v1_id = find(mesh.vertices.begin(), mesh.vertices.end(), Vertex(mesh.triangles[i].vertex_id[1])) - mesh.vertices.begin();\n\t\tint v2_id = find(mesh.vertices.begin(), mesh.vertices.end(), Vertex(mesh.triangles[i].vertex_id[2])) - mesh.vertices.begin();\n\n\t\tGLfloat *v0 = mesh.vertices[v0_id].coord.data();\n\t\tGLfloat *v1 = mesh.vertices[v1_id].coord.data();\n\t\tGLfloat *v2 = mesh.vertices[v2_id].coord.data();\n\n\t\tglBegin(GL_LINE_LOOP);\n\t\tglVertex3fv(v0);\n\t\tglVertex3fv(v1);\n\t\tglVertex3fv(v2);\n\t\tglEnd();\n\t}\n\n\tglPointSize(10.0f);\n\tglBegin(GL_POINTS);\n\tglColor3f(1, 0, 0);\n\tfor (int i = static_cast<int>(mesh.vertices.size()) - mesh.q_size; i < static_cast<int>(mesh.vertices.size()); ++i)\n\t{\n\t\tGLfloat *v = mesh.vertices[i].coord.data();\n\t\tglVertex3fv(v);\n\t}\n\tglEnd();\n\tglFlush();\n}\n\nvoid reshape(int w, int h)\n{\n\tglViewport(0, 0, w, h);\n\tglMatrixMode(GL_PROJECTION);\n\tglLoadIdentity();\n\tgluPerspective(60, 1, 0.1, 10);\n}\n\nint main(int argc, char **argv)\n{\n\tmesh.Read(\"man.obj\");\n\tglutInit(&argc, argv);\n\tglutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);\n\tglutInitWindowSize(500, 500);\n\tglutInitWindowPosition(100, 100);\n\tglutCreateWindow(\"test\");\n\tglutDisplayFunc(display);\n\tglutReshapeFunc(reshape);\n\tglutMouseFunc(OnMouseClick);\n\tglutMotionFunc(OnMouseMove);\n\tglutMainLoop();\n\treturn 0;\n}", "meta": {"hexsha": "2448bba61de732d8e06001091d7d6050060f0a25", "size": 7240, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "RigidDeform/Source.cpp", "max_stars_repo_name": "forestsen/ARAPShapeManipulation", "max_stars_repo_head_hexsha": "459f3fe0ef723711eb65bec16eab08bcb232ed47", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2019-08-04T05:13:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-08T03:15:58.000Z", "max_issues_repo_path": "RigidDeform/Source.cpp", "max_issues_repo_name": "forestsen/ARAPShapeManipulation", "max_issues_repo_head_hexsha": "459f3fe0ef723711eb65bec16eab08bcb232ed47", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-08-08T02:07:10.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-08T02:07:10.000Z", "max_forks_repo_path": "RigidDeform/Source.cpp", "max_forks_repo_name": "forestsen/ARAPShapeManipulation", "max_forks_repo_head_hexsha": "459f3fe0ef723711eb65bec16eab08bcb232ed47", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-05-13T00:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-28T08:07:33.000Z", "avg_line_length": 27.6335877863, "max_line_length": 146, "alphanum_fraction": 0.6610497238, "num_tokens": 2418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4640472074432754}}
{"text": "//==================================================================================================\n/**\n  EVE - Expressive Vector Engine\n  Copyright : EVE Contributors & Maintainers\n  SPDX-License-Identifier: MIT\n**/\n//==================================================================================================\n#include \"test.hpp\"\n#include <eve/module/bessel.hpp>\n#include <boost/math/special_functions/bessel.hpp>\n#include <boost/math/special_functions/bessel_prime.hpp>\n\n//==================================================================================================\n//== Types tests\n//==================================================================================================\nEVE_TEST_TYPES( \"Check return types of cyl_bessel_jn\"\n              , eve::test::simd::ieee_reals\n              )\n<typename T>(eve::as<T>)\n{\n  using v_t = eve::element_type_t<T>;\n  using i_t = eve::as_integer_t<v_t>;\n  using I_t = eve::wide<i_t, eve::cardinal_t<T>>;\n  TTS_EXPR_IS( eve::cyl_bessel_jn(T(), T())  ,  T);\n  TTS_EXPR_IS( eve::cyl_bessel_jn(v_t(),v_t()), v_t);\n  TTS_EXPR_IS( eve::cyl_bessel_jn(i_t(),T()),   T);\n  TTS_EXPR_IS( eve::cyl_bessel_jn(I_t(),T()),   T);\n  TTS_EXPR_IS( eve::cyl_bessel_jn(i_t(),v_t()), v_t);\n  TTS_EXPR_IS( eve::cyl_bessel_jn(I_t(),v_t()), T);\n};\n\n//==================================================================================================\n//== integral orders\n//==================================================================================================\nEVE_TEST( \"Check behavior of cyl_bessel_jn on wide with integral order\"\n        , eve::test::simd::ieee_reals\n        , eve::test::generate(eve::test::ramp(0), eve::test::randoms(0.0, 20000.0))\n        )\n  <typename T>(T n, T a0)\n{\n  using v_t = eve::element_type_t<T>;\n  auto eve__cyl_bessel_jn =  [](auto n, auto x) { return eve::cyl_bessel_jn(n, x); };\n  auto std__cyl_bessel_jn =  [](auto n, auto x)->v_t { return boost::math::cyl_bessel_j(double(n), double(x)); };\n  if constexpr( eve::platform::supports_invalids )\n  {\n    TTS_ULP_EQUAL(eve__cyl_bessel_jn(0, eve::minf(eve::as<v_t>())), eve::zero(eve::as<v_t>()), 0);\n    TTS_ULP_EQUAL(eve__cyl_bessel_jn(2, eve::inf(eve::as<v_t>())), v_t(0), 0);\n    TTS_ULP_EQUAL(eve__cyl_bessel_jn(3, eve::nan(eve::as<v_t>())), eve::nan(eve::as<v_t>()), 0);\n  }\n  //scalar large x\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(3, v_t(1500)), std__cyl_bessel_jn(3, v_t(1500)), 2.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(2, v_t(500)), std__cyl_bessel_jn(2, v_t(500)), 2.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(-3, v_t(1500)), std__cyl_bessel_jn(-3, v_t(1500)), 2.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(-2, v_t(500)), std__cyl_bessel_jn(-2, v_t(500)), 2.0);\n  //scalar forward\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(2, v_t(10)), std__cyl_bessel_jn(2, v_t(10))  , 2.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(3, v_t(5)),  std__cyl_bessel_jn(3, v_t(5))   , 2.0);\n  //scalar serie\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(2, v_t(0.1)), std__cyl_bessel_jn(2, v_t(0.1))  , 2.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(3, v_t(0.2)),  std__cyl_bessel_jn(3, v_t(0.2))   , 2.0);\n  //scalar besseljy\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(10, v_t(8)), std__cyl_bessel_jn(10, v_t(8))  , 2.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(10, v_t(8)),  std__cyl_bessel_jn(10, v_t(8))   , 2.0);\n\n  if constexpr( eve::platform::supports_invalids )\n  {\n    TTS_ULP_EQUAL(eve__cyl_bessel_jn(0, eve::minf(eve::as<T>())), eve::zero(eve::as<T>()), 0);\n    TTS_ULP_EQUAL(eve__cyl_bessel_jn(2, eve::inf(eve::as<T>())), T(0), 0);\n    TTS_ULP_EQUAL(eve__cyl_bessel_jn(3, eve::nan(eve::as<T>())), eve::nan(eve::as<T>()), 0);\n  }\n  //scalar large x\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(3, T(1500)),  T(std__cyl_bessel_jn(3, v_t(1500))),  2.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(2, T(500)),   T(std__cyl_bessel_jn(2, v_t(500))),   2.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(-3, T(1500)), T(std__cyl_bessel_jn(-3, v_t(1500))), 2.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(-2, T(500)),  T(std__cyl_bessel_jn(-2, v_t(500))),  2.0);\n  //scalar forward\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(2, T(10)),    T(std__cyl_bessel_jn(2, v_t(10)))   , 2.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(3, T(5)),     T(std__cyl_bessel_jn(3, v_t(5)))    , 2.0);\n  //scalar serie\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(2, T(0.1)),   T(std__cyl_bessel_jn(2, v_t(0.1)))  , 2.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(3, T(0.2)),   T(std__cyl_bessel_jn(3, v_t(0.2)))  , 2.0);\n  //scalar besseljy\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(10, T(8)),   T(std__cyl_bessel_jn(10, v_t(8)))   , 2.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(10, T(8)),   T(std__cyl_bessel_jn(10, v_t(8)))   , 2.0);\n\n  if constexpr( eve::platform::supports_invalids )\n  {\n    TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(0), eve::minf(eve::as<T>())), eve::zero(eve::as<T>()), 0);\n    TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(2), eve::inf(eve::as<T>())), T(0), 0);\n    TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(3), eve::nan(eve::as<T>())), eve::nan(eve::as<T>()), 0);\n  }\n  // large x\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(3), T(1500)),  T(std__cyl_bessel_jn(3, v_t(1500))),  2.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(2), T(500)),   T(std__cyl_bessel_jn(2, v_t(500))),   2.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(-3), T(1500)), T(std__cyl_bessel_jn(-3, v_t(1500))), 2.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(-2), T(500)),  T(std__cyl_bessel_jn(-2, v_t(500))),  2.0);\n  // forward\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(2), T(10)),    T(std__cyl_bessel_jn(2, v_t(10)))   , 2.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(3), T(5)),     T(std__cyl_bessel_jn(3, v_t(5)))    , 2.0);\n  // serie\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(2), T(0.1)),   T(std__cyl_bessel_jn(2, v_t(0.1)))  , 2.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(3), T(0.2)),   T(std__cyl_bessel_jn(3, v_t(0.2)))  , 2.0);\n  // besseljy\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(10), T(8)),   T(std__cyl_bessel_jn(10, v_t(8)))   , 2.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(10), T(8)),   T(std__cyl_bessel_jn(10, v_t(8)))   , 2.0);\n\n  using i_t = eve::as_integer_t<v_t>;\n  using I_t = eve::wide<i_t, eve::cardinal_t<T>>;\n\n  if constexpr( eve::platform::supports_invalids )\n  {\n    TTS_ULP_EQUAL(eve__cyl_bessel_jn(I_t(0), eve::minf(eve::as<T>())), eve::zero(eve::as<T>()), 0);\n    TTS_ULP_EQUAL(eve__cyl_bessel_jn(I_t(2), eve::inf(eve::as<T>())), T(0), 0);\n    TTS_ULP_EQUAL(eve__cyl_bessel_jn(I_t(3), eve::nan(eve::as<T>())), eve::nan(eve::as<T>()), 0);\n  }\n  // large x\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(I_t(3), T(1500)),  T(std__cyl_bessel_jn(3, v_t(1500))),  2.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(I_t(2), T(500)),   T(std__cyl_bessel_jn(2, v_t(500))),   2.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(I_t(-3), T(1500)), T(std__cyl_bessel_jn(-3, v_t(1500))), 2.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(I_t(-2), T(500)),  T(std__cyl_bessel_jn(-2, v_t(500))),  2.0);\n  // forward\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(I_t(2), T(10)),    T(std__cyl_bessel_jn(2, v_t(10)))   , 2.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(I_t(3), T(5)),     T(std__cyl_bessel_jn(3, v_t(5)))    , 2.0);\n  // serie\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(I_t(2), T(0.1)),   T(std__cyl_bessel_jn(2, v_t(0.1)))  , 2.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(I_t(3), T(0.2)),   T(std__cyl_bessel_jn(3, v_t(0.2)))  , 2.0);\n  // besseljy\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(I_t(10), T(8)),   T(std__cyl_bessel_jn(10, v_t(8)))   , 2.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(I_t(10), T(8)),   T(std__cyl_bessel_jn(10, v_t(8)))   , 2.0);\n\n  TTS_RELATIVE_EQUAL(eve__cyl_bessel_jn(n, a0),   map(std__cyl_bessel_jn, n, a0)   , 0.0015);\n  TTS_RELATIVE_EQUAL(eve__cyl_bessel_jn(n, -a0),   map(std__cyl_bessel_jn, n, -a0)   , 0.0015);\n  TTS_RELATIVE_EQUAL(map(eve__cyl_bessel_jn, n, -a0),   map(std__cyl_bessel_jn, n, -a0)   , 0.0015);\n};\n\n//==================================================================================================\n//== non integral orders\n//==================================================================================================\nEVE_TEST( \"Check behavior of cyl_bessel_jn on wide with non integral order\"\n        , eve::test::simd::ieee_reals\n        , eve::test::generate(eve::test::randoms(0.0, 10.0)\n                             , eve::test::randoms(0.0, 2000.0))\n        )\n  <typename T>(T n, T a0)\n{\n  using v_t = eve::element_type_t<T>;\n\n  auto eve__cyl_bessel_jn =  [](auto n, auto x) { return eve::cyl_bessel_jn(n, x); };\n  auto std__cyl_bessel_jn =  [](auto n, auto x)->v_t { return boost::math::cyl_bessel_j(double(n), double(x)); };\n  if constexpr( eve::platform::supports_invalids )\n  {\n    TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(0.5), eve::minf(eve::as<v_t>())), eve::nan(eve::as<v_t>()), 0);\n    TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(2.5), eve::inf(eve::as<v_t>())), v_t(0), 0);\n    TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(3.5), eve::nan(eve::as<v_t>())), eve::nan(eve::as<v_t>()), 0);\n  }\n  //scalar large x\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(3.5), v_t(1500)), std__cyl_bessel_jn(v_t(3.5), v_t(1500)), 2.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(2.5), v_t( 500)),  std__cyl_bessel_jn(v_t(2.5), v_t( 500)), 2.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(-3.5), v_t(1500)), std__cyl_bessel_jn(v_t(-3.5), v_t(1500)), 2.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(-2.5), v_t( 500)), std__cyl_bessel_jn(v_t(-2.5), v_t(500)), 2.0);\n  //scalar forward\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(2.5), v_t(10)), std__cyl_bessel_jn(v_t(2.5), v_t(10))  , 5.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(3.5), v_t(5)),  std__cyl_bessel_jn(v_t(3.5), v_t(5))   , 2.0);\n  //scalar serie\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(2.5), v_t(0.1)), std__cyl_bessel_jn(v_t(2.5), v_t(0.1))  , 2.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(3.5), v_t(0.2)),  std__cyl_bessel_jn(v_t(3.5), v_t(0.2))   , 2.0);\n  //scalar besseljy\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(10.5), v_t(8)), std__cyl_bessel_jn(v_t(10.5), v_t(8))  , 2.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(10.5), v_t(8)),  std__cyl_bessel_jn(v_t(10.5), v_t(8))   , 2.0);\n\n  if constexpr( eve::platform::supports_invalids )\n  {\n    TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(0.5), eve::minf(eve::as<T>())), eve::nan(eve::as<T>()), 0);\n    TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(2.5), eve::inf(eve::as<T>())), T(0), 0);\n    TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(3.5), eve::nan(eve::as<T>())), eve::nan(eve::as<T>()), 0);\n  }\n  //scalar large x\n   TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(3.5), T(1500)),  T(std__cyl_bessel_jn(v_t(3.5), v_t(1500))),  2.0);\n   TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(2.5), T(500)),   T(std__cyl_bessel_jn(v_t(2.5), v_t(500))),   2.0);\n  //scalar forward\n   TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(2.5), T(10)),    T(std__cyl_bessel_jn(v_t(2.5), v_t(10)))   , 5.0);\n   TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(3.5), T(5)),     T(std__cyl_bessel_jn(v_t(3.5), v_t(5)))    , 2.0);\n  //scalar serie\n   TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(2.5), T(0.1)),   T(std__cyl_bessel_jn(v_t(2.5), v_t(0.1)))  , 2.0);\n   TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(3.5), T(0.2)),   T(std__cyl_bessel_jn(v_t(3.5), v_t(0.2)))  , 2.5);\n  //scalar besseljy\n    TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(10.5), T(8)),   T(std__cyl_bessel_jn(v_t(10.5), v_t(8)))   , 2.0);\n    TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(10.5), T(8)),   T(std__cyl_bessel_jn(v_t(10.5), v_t(8)))   , 2.0);\n\n  if constexpr( eve::platform::supports_invalids )\n  {\n    TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(0.5), eve::minf(eve::as<T>())), eve::nan(eve::as<T>()), 0);\n    TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(2.5), eve::inf(eve::as<T>())), T(0), 0);\n    TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(3.5), eve::nan(eve::as<T>())), eve::nan(eve::as<T>()), 0);\n  }\n  // large x\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(3.5), T(1500)),  T(std__cyl_bessel_jn(v_t(3.5), v_t(1500))),  2.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(2.5), T(500)),   T(std__cyl_bessel_jn(v_t(2.5), v_t(500))),   2.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(-3.5), T(1500)), T(std__cyl_bessel_jn(v_t(-3.5), v_t(1500))), 2.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(-2.5), T(500)),  T(std__cyl_bessel_jn(v_t(-2.5), v_t( 500))), 2.0);\n  // forward\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(2.5), T(10)),    T(std__cyl_bessel_jn(v_t(2.5), v_t(10)))   , 5.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(3.5), T(5)),     T(std__cyl_bessel_jn(v_t(3.5), v_t(5)))    , 2.0);\n  // serie\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(2.5), T(0.1)),   T(std__cyl_bessel_jn(v_t(2.5), v_t(0.1)))  , 2.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(3.5), T(0.2)),   T(std__cyl_bessel_jn(v_t(3.5), v_t(0.2)))  , 2.5);\n  // besseljy\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(10.5), T(8)),   T(std__cyl_bessel_jn(v_t(10.5), v_t(8)))   , 2.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(10.5), T(8)),   T(std__cyl_bessel_jn(v_t(10.5), v_t(8)))   , 2.0);\n\n  TTS_RELATIVE_EQUAL(eve__cyl_bessel_jn(n, a0),   map(std__cyl_bessel_jn, n, a0)   , 0.001);\n\n\n    //scalar large x\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(-3.5), v_t(1500)), std__cyl_bessel_jn(v_t(-3.5), v_t(1500)), 2.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(-2.5), v_t(500)),  std__cyl_bessel_jn(v_t(-2.5), v_t(500)), 2.0);\n\n  //scalar forward\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(-2.5), v_t(10)), std__cyl_bessel_jn(v_t(-2.5), v_t(10))  , 6.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(-3.5), v_t(5)),  std__cyl_bessel_jn(v_t(-3.5), v_t(5))   , 35.0);\n  //scalar serie\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(-2.5), v_t(0.1)), std__cyl_bessel_jn(v_t(-2.5), v_t(0.1))  , 2.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(-3.5), v_t(0.2)),  std__cyl_bessel_jn(v_t(-3.5), v_t(0.2))   , 2.0);\n  //scalar besseljy\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(-10.5), v_t(8)), std__cyl_bessel_jn(v_t(-10.5), v_t(8))  , 2.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(v_t(-10.5), v_t(8)),  std__cyl_bessel_jn(v_t(-10.5), v_t(8))   , 2.0);\n\n   // large x\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(-3.5), T(1500)),  T(std__cyl_bessel_jn(v_t(-3.5), v_t(1500))),  2.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(-2.5), T(500)),   T(std__cyl_bessel_jn(v_t(-2.5), v_t(500))),   2.0);\n\n  // forward\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(-2.5), T(10)),    T(std__cyl_bessel_jn(v_t(-2.5), v_t(10)))   , 6.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(-3.5), T(5)),     T(std__cyl_bessel_jn(v_t(-3.5), v_t(5)))    , 35.0);\n  // serie\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(-2.5), T(0.1)),   T(std__cyl_bessel_jn(v_t(-2.5), v_t(0.1)))  , 2.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(-3.5), T(0.2)),   T(std__cyl_bessel_jn(v_t(-3.5), v_t(0.2)))  , 2.5);\n  // besseljy\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(-10.5), T(8)),   T(std__cyl_bessel_jn(v_t(-10.5), v_t(8)))   , 2.5);\n  TTS_ULP_EQUAL(eve__cyl_bessel_jn(T(-10.5), T(8)),   T(std__cyl_bessel_jn(v_t(-10.5), v_t(8)))   , 2.5);\n\n  TTS_RELATIVE_EQUAL(eve__cyl_bessel_jn(-n, a0),   map(std__cyl_bessel_jn, -n, a0)   , 0.001);\n};\n\nEVE_TEST( \"Check behavior of diff(cyl_bessel_jn) on wide\"\n        , eve::test::simd::ieee_reals\n        , eve::test::generate( eve::test::randoms(0.0, 10.0)\n                             , eve::test::randoms(0.0, 60.0))\n        )\n  <typename T>(T n, T a0 )\n{\n  using v_t =  eve::element_type_t<T>;\n  auto eve__diff_bessel_jn =  [](auto n, auto x) { return eve::diff(eve::cyl_bessel_jn)(n, x); };\n  auto std__diff_bessel_jn =  [](auto n, auto x)->v_t { return boost::math::cyl_bessel_j_prime(double(n), double(x)); };\n  TTS_RELATIVE_EQUAL(eve__diff_bessel_jn(n, a0),   map(std__diff_bessel_jn, n, a0), 1.0e-3);\n  auto nn = eve::trunc(n);\n  TTS_RELATIVE_EQUAL(eve__diff_bessel_jn(nn, a0),   map(std__diff_bessel_jn, nn, a0), 2.0e-3);\n\n};\n", "meta": {"hexsha": "601451bc26ee8efd83abf5eeccecdae1e9ef2d7a", "size": 15395, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/module/bessel/cyl_bessel_jn.cpp", "max_stars_repo_name": "HadrienG2/eve", "max_stars_repo_head_hexsha": "3afdcfb524f88c0b88df9b54e25bbb9b33f518ec", "max_stars_repo_licenses": ["MIT"], "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/unit/module/bessel/cyl_bessel_jn.cpp", "max_issues_repo_name": "HadrienG2/eve", "max_issues_repo_head_hexsha": "3afdcfb524f88c0b88df9b54e25bbb9b33f518ec", "max_issues_repo_licenses": ["MIT"], "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/unit/module/bessel/cyl_bessel_jn.cpp", "max_forks_repo_name": "HadrienG2/eve", "max_forks_repo_head_hexsha": "3afdcfb524f88c0b88df9b54e25bbb9b33f518ec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 59.2115384615, "max_line_length": 120, "alphanum_fraction": 0.6227996103, "num_tokens": 6737, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4640472074432754}}
{"text": "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n//\n// Generalized Pose-and-Scale Estimation using 4-Point Congruence Constraints\n//\n// Victor Fragoso and Sudipta Sinha.\n// In Proc. of the IEEE International Conf. on 3D Vision (3DV) 2020.\n//\n// Please contact the author of this library if you have any questions.\n// Author: Victor Fragoso (victor.fragoso@microsoft.com)\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/SVD>\n#include <glog/logging.h>\n#include <gp4pc/gp4pc.h>\n#include <math/solve_gp4pc_polynomial.h>\n#include <third_party/align_point_clouds.h>\n#include <algorithm>\n#include <utility>\n#include <vector>\n\nnamespace msft {\nnamespace {\n\n// Default coplanar threshold.\nconst double kDefaultCoplanarThresh = 1e-3;\nconst double kDefaultColinearThresh = 1e-2;\nconst double kRealNumberThreshold = 0.0;\nconst double kDuplicateSolnErrorThreshold = 1e-6;\nconst double kDuplicateCameraCenterErrorThreshold = 1e-6;\n// Dimensions of the coefficient matrix: kNumConstraints x kNumMonomials.\nconst int kNumConstraints = 4;\nconst int kNumMonomials = 15;\n// Max. num. of depth solutions.\nconst int kMaxNumDepthSolutions = 16;\n// Size of the minimal sample.\nconst int kSizeOfMinimalSample = 4;\n\ninline Eigen::Vector3d ComputeCameraPoint(const Eigen::Vector3d& camera_center,\n                                          const Eigen::Vector3d& ray_direction,\n                                          const double depth) {\n  return camera_center + depth * ray_direction;\n}\n\nbool IsInputValid(const Gp4pc::Input& input) {\n  // Check that the camera centers are different.\n  int num_different_origins = 0;\n  for (int i = 0; i < input.ray_origins.size(); ++i) {\n    for (int j = i + 1; j < input.ray_origins.size(); ++j) {\n      const double distance =\n          (input.ray_origins[i] - input.ray_origins[j]).squaredNorm();\n      if (distance > kDuplicateCameraCenterErrorThreshold) {\n        num_different_origins += 1;\n      }\n    }\n  }\n  const bool has_different_origins = num_different_origins > 0;\n  return has_different_origins;\n}\n\n// Build least-squares system Ax = b, where\n// b = [p_1 p_2 p_3 p_4]^T\n// and\n//     | L(w_1)  I |\n// A = | L(w_2)  I |\n//     | L(w_3)  I |\n//     | L(w_4)  I |.\nvoid BuildLinearSystem(const std::vector<Eigen::Vector3d>& world_points,\n                       const std::vector<Eigen::Vector3d>& camera_points,\n                       Eigen::VectorXd* camera_points_vec_ptr,\n                       Eigen::MatrixXd* world_points_mat_ptr) {\n  // Dimensionality of the points.\n  static const int kPointDimension = 3;\n\n  const int num_points = world_points.size();\n  Eigen::VectorXd& camera_points_vec = *camera_points_vec_ptr;\n  Eigen::MatrixXd& world_points_mat = *world_points_mat_ptr;\n  world_points_mat.setZero();\n\n  int row_index = 0;\n  for (int i = 0; i < num_points; ++i) {\n    // Fill in camera points.\n    camera_points_vec.segment(i * kPointDimension, kPointDimension) =\n        camera_points[i];\n\n    // Fill in world-point matrices.\n    row_index = i * kPointDimension;\n    world_points_mat.block(row_index, 0, 1, 3) = world_points[i].transpose();\n    world_points_mat.block(row_index + 1, 3, 1, 3) =\n        world_points[i].transpose();\n    world_points_mat.block(row_index + 2, 6, 1, 3) =\n        world_points[i].transpose();\n    world_points_mat.block(row_index, 9, 3, 3) = Eigen::Matrix3d::Identity();\n  }\n}\n\nbool IsInputDegenerateOrPlanar(const Gp4pc::Input& input,\n                               const double coplanar_threshold,\n                               const double colinear_threshold,\n                               bool* is_planar) {\n  *CHECK_NOTNULL(is_planar) = false;\n  // Compute the SVD of the input 3D points.\n  const Eigen::Vector3d mean_direction =\n      (input.world_points[0] + input.world_points[1] + input.world_points[2] +\n       input.world_points[3]) /\n      4;\n  Eigen::Matrix<double, 4, 3> normalized_points;\n  normalized_points.row(0) = input.world_points[0] - mean_direction;\n  normalized_points.row(1) = input.world_points[1] - mean_direction;\n  normalized_points.row(2) = input.world_points[2] - mean_direction;\n  normalized_points.row(3) = input.world_points[3] - mean_direction;\n  const Eigen::Matrix3d covariance =\n      normalized_points.transpose() * normalized_points;\n  const Eigen::JacobiSVD<Eigen::Matrix3d> svd(\n      covariance, Eigen::ComputeThinU | Eigen::ComputeThinV);\n  const Eigen::Vector3d singular_values = svd.singularValues();\n\n  // Is input degenerate, i.e., a line?\n  double singular_value_ratio = singular_values[1] / singular_values[0];\n  if (singular_value_ratio < colinear_threshold) {\n    VLOG(2) << \"Singular value ratio (colinear test): \" << singular_value_ratio\n            << \" threshold: \" << colinear_threshold;\n    return true;\n  }\n\n  // Is the input planar?\n  singular_value_ratio = singular_values[2] / singular_values[0];\n  *is_planar = singular_value_ratio < coplanar_threshold;\n  VLOG_IF(4, *is_planar) << \"Singular value ratio (coplanar test): \"\n                         << singular_value_ratio\n                         << \" threshold: \" << coplanar_threshold;\n\n  return false;\n}\n\n// This function computes the values of t1 and t3 given the four points:\n// (x1, x2, x3, x4).\n//\n// The point (x1 + t1 * v1) + t3 * v3 must be equal to the point (x3 + t2 * v2).\n// This gives a linear system in t1, t2, t3. Solve it. This gives the following\n// closest points on the lines.\n//    x1 + t1 * v1;\n//    x3 + t2 * v2;\nEigen::Vector2d Findt1t3(const Eigen::Vector3d& x1,\n                         const Eigen::Vector3d& x2,\n                         const Eigen::Vector3d& x3,\n                         const Eigen::Vector3d& x4) {\n  const Eigen::Vector3d v1 = x2 - x1;\n  const Eigen::Vector3d v2 = x4 - x3;\n  const Eigen::Vector3d v3 = v1.cross(v2);\n  const Eigen::Vector3d b = x3 - x1;\n\n  // A = [v1 -v2 v3]; (MATLAB code).\n  Eigen::MatrixXd A(3, 3);\n  A.col(0) = v1;\n  A.col(1) = -v2;\n  A.col(2) = v3;\n\n  // t = A \\ b; (MATLAB code).\n  const Eigen::VectorXd x = A.lu().solve(b);\n\n  // Solution\n  return x;\n}\n\n// This function calculates (f1, f2, f3, f4) and (K1, K2) from the four points\n// (x1, x2, x3, x4).\nstruct DerivedConstants {\n  double f1;\n  double f2;\n  double f3;\n  double f4;\n  double k1;\n  double k2;\n};\n\nDerivedConstants CalculateRatiosFromFourPoints(\n    const Eigen::Vector3d& x1,\n    const Eigen::Vector3d& x2,\n    const Eigen::Vector3d& x3,\n    const Eigen::Vector3d& x4) {\n  DerivedConstants constants;\n  double& f1 = constants.f1;\n  double& f2 = constants.f2;\n  double& f3 = constants.f3;\n  double& f4 = constants.f4;\n  double& K1 = constants.k1;\n  double& K2 = constants.k2;\n\n  // x1--x2 is the first line segment and x3--x4 is the second line segment.\n  // z1 is on x1--x2, z3 is on x3--x4 and (z1--z3) is also perpendicular\n  // to x1--x2 and x3--x4\n  //\n  // t1 is equal to dist(x1,z1) / dist(x1,x2)\n  // t2 is equal to dist(x3,z3) / dist(x3,x4)\n  //\n  // [t1, t3, x1, x2, x3, x4] = findClosestPoints(X,1,2,3,4); (MATLAB code)\n\n  const Eigen::Vector2d t_vec = Findt1t3(x1, x2, x3, x4);\n\n  const double len12 = (x1 - x2).norm();\n  const double len34 = (x3 - x4).norm();\n  const double len13 = (x1 - x3).norm();\n\n  const double s12 = len12 * len12;\n  const double s34 = len34 * len34;\n  const double s13 = len13 * len13;\n\n  K1 = s12 / s34;\n  K2 = s12 / s13;\n\n  f1 = 1 - t_vec(0);\n  f2 = t_vec(0);\n  f3 = 1 - t_vec(1);\n  f4 = t_vec(1);\n\n  return constants;\n}\n\nEigen::MatrixXd SolveForDepthsFromAPlanarInput(const Gp4pc::Input& input) {\n  // Useful aliases.\n  // Camera centers.\n  const std::vector<Eigen::Vector3d>& ray_origins = input.ray_origins;\n  // Unit rays originating from ray_origins.\n  const std::vector<Eigen::Vector3d>& ray_directions = input.ray_directions;\n  // World points.\n  const std::vector<Eigen::Vector3d>& world_points = input.world_points;\n\n  // Verify the input is consistent.\n  CHECK_EQ(ray_origins.size(), ray_directions.size());\n  CHECK_EQ(ray_origins.size(), world_points.size());\n\n  // The mathematical relationship is the following:\n  //\n  // ray_origins[i] + depth[i] * ray_directions[i] =\n  //         s * R * world_points[i] + t,\n  //\n  // where s is scale, R is a rotation matrix, and t is translation.\n\n  // Input Constants.\n  const Eigen::Vector3d& p1 = ray_origins[0];\n  const Eigen::Vector3d& p2 = ray_origins[1];\n  const Eigen::Vector3d& p3 = ray_origins[2];\n  const Eigen::Vector3d& p4 = ray_origins[3];\n\n  // Input Constants.\n  const Eigen::Vector3d& u1 = ray_directions[0];\n  const Eigen::Vector3d& u2 = ray_directions[1];\n  const Eigen::Vector3d& u3 = ray_directions[2];\n  const Eigen::Vector3d& u4 = ray_directions[3];\n\n  // Input Constants.\n  const Eigen::Vector3d& x1 = world_points[0];\n  const Eigen::Vector3d& x2 = world_points[1];\n  const Eigen::Vector3d& x3 = world_points[2];\n  const Eigen::Vector3d& x4 = world_points[3];\n\n  // Derived Constants.\n  const DerivedConstants constants =\n      CalculateRatiosFromFourPoints(x1, x2, x3, x4);\n\n  // Derived Constants.\n  const Eigen::Vector3d p5 =\n      constants.f1 * p1 + constants.f2 * p2 -\n      constants.f3 * p3 - constants.f4 * p4;\n  const Eigen::Vector3d p6 = p1 - p2;\n  const Eigen::Vector3d p8 = p1 - p3;\n\n  // Derived Constants.\n  const Eigen::Vector3d v1 = constants.f1 * u1;\n  const Eigen::Vector3d v2 = constants.f2 * u2;\n  const Eigen::Vector3d v3 = -constants.f3 * u3;\n  const Eigen::Vector3d v4 = -constants.f4 * u4;\n\n  // Think of the 3 x 3 system in s1, s2, s3\n  // [a1 b1 c1] = [d1]\n  // [a2 b2 c2] = [d2]\n  // [a3 b3 c3] = [d3].\n  const double& a1 = v1(0);\n  const double& b1 = v2(0);\n  const double& c1 = v3(0);\n  const double& a2 = v1(1);\n  const double& b2 = v2(1);\n  const double& c2 = v3(1);\n  const double& a3 = v1(2);\n  const double& b3 = v2(2);\n  const double& c3 = v3(2);\n\n  const double denom =\n      a1 * b2 * c3 + b1 * c2 * a3 + c1 * a2 * b3 -\n      a3 * b2 * c1 - b3 * c2 * a1 - c3 * a2 * b1;\n\n  const double coeff11 = b2 * c3 - b3 * c2;\n  const double coeff12 = c1 * b3 - c3 * b1;\n  const double coeff13 = b1 * c2 - b2 * c1;\n\n  const double G1 =\n      (-v4(0) * coeff11 - v4(1) * coeff12 - v4(2) * coeff13) / denom;\n  const double H1 =\n      (-p5(0) * coeff11 - p5(1) * coeff12 - p5(2) * coeff13) / denom;\n\n  const double coeff21 = c2 * a3 - c3 * a2;\n  const double coeff22 = a1 * c3 - a3 * c1;\n  const double coeff23 = c1 * a2 - c2 * a1;\n\n  const double G2 =\n      (-v4(0) * coeff21 - v4(1) * coeff22 - v4(2) * coeff23) / denom;\n  const double H2 =\n      (-p5(0) * coeff21 - p5(1) * coeff22 - p5(2) * coeff23) / denom;\n\n  const double coeff31 = b3 * a2 - b2 * a3;\n  const double coeff32 = a3 * b1 - a1 * b3;\n  const double coeff33 = b2 * a1 - b1 * a2;\n\n  const double G3 =\n      (-v4(0) * coeff31 - v4(1) * coeff32 - v4(2) * coeff33) / denom;\n  const double H3 =\n      (-p5(0) * coeff31 - p5(1) * coeff32 - p5(2) * coeff33) / denom;\n\n  const double C1 = 1 - constants.k2;\n  const double C2 = 1;\n  const double C3 = -constants.k2;\n  const double C4 = -2.0 * u1.dot(u2);\n  const double C5 = 2.0 * constants.k2 * u1.dot(u3);\n  const double C6 = 2.0 * (u1.dot(p6) - constants.k2 * u1.dot(p8));\n  const double C7 = -2.0 * u2.dot(p6);\n  const double C8 = 2.0 * constants.k2 * u3.dot(p8);\n  const double C9 = p6.dot(p6) - constants.k2 * p8.dot(p8);\n\n  // Derive the coefficients of the quadratic.\n  const double A =\n      C1 * G1 * G1 + C2 * G2 * G2 + C3 * G3 * G3 + C4 * G1 * G2 + C5 * G1 * G3;\n  const double B =\n      C1 * 2 * G1 * H1 + C2 * 2 * G2 * H2 + C3 * 2 * G3 * H3 +\n      C4 * (G1 * H2 + G2 * H1) + C5 * (G1 * H3 + G3 * H1) + C6 * G1 +\n      C7 * G2 + C8 * G3;\n  const double C =\n      C1 * H1 * H1 + C2 * H2 * H2 + C3 * H3 * H3 + C4 * H1 * H2 +\n      C5 * H1 * H3 + C6 * H1 + C7 * H2 + C8 * H3 + C9;\n  const double disc = (B * B - 4 * A * C);\n\n  Eigen::MatrixXd depths;\n  depths.resize(4, 2);\n  depths.setZero();\n\n  if (disc >= 0) {\n    const double sqrtD = sqrt(disc);\n    const double s4a = (-B - sqrtD) / (2 * A);\n    const double s4b = (-B + sqrtD) / (2 * A);\n\n    if (s4a > 0) {\n      depths(0, 0) = G1 * s4a + H1;\n      depths(1, 0) = G2 * s4a + H2;\n      depths(2, 0) = G3 * s4a + H3;\n      depths(3, 0) = s4a;\n    }\n\n    if (s4b > 0) {\n      depths(0, 1) = G1 * s4b + H1;\n      depths(1, 1) = G2 * s4b + H2;\n      depths(2, 1) = G3 * s4b + H3;\n      depths(3, 1) = s4b;\n    }\n  }\n\n  return depths;\n}\n\nEigen::MatrixXd BuildCoefficientMatrix(const Gp4pc::Input& input) {\n  Eigen::MatrixXd coeff_mat(kNumConstraints, kNumMonomials);\n  coeff_mat.setZero();\n\n  // Useful aliases.\n  // Camera centers.\n  const std::vector<Eigen::Vector3d>& ray_origins = input.ray_origins;\n  // Unit rays originating from ray_origins.\n  const std::vector<Eigen::Vector3d>& ray_directions = input.ray_directions;\n  // World points.\n  const std::vector<Eigen::Vector3d>& world_points = input.world_points;\n\n  // Verify the input is consistent.\n  CHECK_EQ(ray_origins.size(), ray_directions.size());\n  CHECK_EQ(ray_origins.size(), world_points.size());\n\n  // The mathematical relationship is the following:\n  //\n  // ray_origins[i] + depth[i] * ray_directions[i] =\n  //       s * R * world_points[i] + t,\n  //\n  // where s is scale, R is a rotation matrix, and t is translation.\n\n  // Input Constants\n  const Eigen::Vector3d& p1 = ray_origins[0];\n  const Eigen::Vector3d& p2 = ray_origins[1];\n  const Eigen::Vector3d& p3 = ray_origins[2];\n  const Eigen::Vector3d& p4 = ray_origins[3];\n\n  // Input Constants\n  const Eigen::Vector3d& u1 = ray_directions[0];\n  const Eigen::Vector3d& u2 = ray_directions[1];\n  const Eigen::Vector3d& u3 = ray_directions[2];\n  const Eigen::Vector3d& u4 = ray_directions[3];\n\n  // Input Constants\n  const Eigen::Vector3d& x1 = world_points[0];\n  const Eigen::Vector3d& x2 = world_points[1];\n  const Eigen::Vector3d& x3 = world_points[2];\n  const Eigen::Vector3d& x4 = world_points[3];\n\n  // Derived Constants\n  const DerivedConstants constants =\n      CalculateRatiosFromFourPoints(x1, x2, x3, x4);\n\n  // Derived Constants\n  const Eigen::Vector3d p5  =\n      constants.f1 * p1 + constants.f2 * p2 -\n      constants.f3 * p3 - constants.f4 * p4;\n  const Eigen::Vector3d p6 = p1 - p2;\n  const Eigen::Vector3d p7 = p3 - p4;\n  const Eigen::Vector3d p8 = p1 - p3;\n  const Eigen::Vector3d p9 = p2 - p4;\n  const Eigen::Vector3d p10 = p1 - p4;\n  const Eigen::Vector3d p11 = p2 - p3;\n\n  // Derived Constants\n  const Eigen::Vector3d v1 = constants.f1 * u1;\n  const Eigen::Vector3d v2 = constants.f2 * u2;\n  const Eigen::Vector3d v3 = -constants.f3 * u3;\n  const Eigen::Vector3d v4 = -constants.f4 * u4;\n\n  // Equation derived from orthogonality constraint 1.\n  coeff_mat(0, 0) = v1.dot(u1);\n  coeff_mat(0, 1) = -u2.dot(v2);\n  coeff_mat(0, 2) = 0;\n  coeff_mat(0, 3) = 0;\n  coeff_mat(0, 4) = u1.dot(v2) - u2.dot(v1);\n  coeff_mat(0, 5) = u1.dot(v3);\n  coeff_mat(0, 6) = u1.dot(v4);\n  coeff_mat(0, 7) = -u2.dot(v3);\n  coeff_mat(0, 8) = -u2.dot(v4);\n  coeff_mat(0, 9) = 0;\n  coeff_mat(0, 10) = p6.dot(v1) + u1.dot(p5);\n  coeff_mat(0, 11) = p6.dot(v2) - u2.dot(p5);\n  coeff_mat(0, 12) = p6.dot(v3);\n  coeff_mat(0, 13) = p6.dot(v4);\n  coeff_mat(0, 14) = p6.dot(p5);\n\n  // Equation derived from orthogonality constraint 2.\n  coeff_mat(1, 0) =  0;\n  coeff_mat(1, 1) =  0;\n  coeff_mat(1, 2) =  u3.dot(v3);\n  coeff_mat(1, 3) = -u4.dot(v4);\n  coeff_mat(1, 4) =  0;\n  coeff_mat(1, 5) =  u3.dot(v1);\n  coeff_mat(1, 6) = -u4.dot(v1);\n  coeff_mat(1, 7) =  u3.dot(v2);\n  coeff_mat(1, 8) = -u4.dot(v2);\n  coeff_mat(1, 9) =  u3.dot(v4) - u4.dot(v3);\n  coeff_mat(1, 10) =  p7.dot(v1);\n  coeff_mat(1, 11) =  p7.dot(v2);\n  coeff_mat(1, 12) =  p7.dot(v3) + u3.dot(p5);\n  coeff_mat(1, 13) =  p7.dot(v4) - u4.dot(p5);\n  coeff_mat(1, 14) =  p7.dot(p5);\n\n  // Coefficients of quadratic polynomial that corresponds to the squared\n  // length for edges 1--2, 1--3 and 3--4.\n  Eigen::VectorXd d12(kNumMonomials);\n  Eigen::VectorXd d13(kNumMonomials);\n  Eigen::VectorXd d34(kNumMonomials);\n  d12.setZero();\n  d13.setZero();\n  d34.setZero();\n\n  d12(0) = 1;\n  d12(1) = 1;\n  d12(4) = -2.0 * u1.dot(u2);\n  d12(10) = 2.0 * u1.dot(p6);\n  d12(11) = -2.0 * u2.dot(p6);\n  d12(14) = p6.dot(p6);\n\n  d13(0) = 1;\n  d13(2) = 1;\n  d13(5) = -2.0 * u1.dot(u3);\n  d13(10) = 2.0 * u1.dot(p8);\n  d13(12) = -2.0 * u3.dot(p8);\n  d13(14) = p8.dot(p8);\n\n  d34(2) = 1;\n  d34(3) = 1;\n  d34(9) = -2.0 * u3.dot(u4);\n  d34(12) = 2.0 * u3.dot(p7);\n  d34(13) = -2.0 * u4.dot(p7);\n  d34(14) = p7.dot(p7);\n\n  // Two equations derived from distance ratio constraints.\n  coeff_mat.row(2) = d12 - constants.k1 * d34;\n  coeff_mat.row(3) = d12 - constants.k2 * d13;\n\n  return coeff_mat;\n}\n\nbool IsSimilarityTransformValid(const Eigen::Matrix3d& rotation,\n                                const Eigen::Vector3d& translation,\n                                const double scale) {\n  // Make sure rotation is finite.\n  const double* rotation_vals = rotation.data();\n  bool is_rotation_finite = true;\n  for (int i = 0; i < 9; ++i) {\n    is_rotation_finite = is_rotation_finite && std::isfinite(rotation_vals[i]);\n  }\n  // Make sure translation is finite.\n  const bool is_translation_finite =\n      std::isfinite(translation(0)) &&\n      std::isfinite(translation(1)) &&\n      std::isfinite(translation(2));\n  // Make scale is finite.\n  const bool is_scale_valid = scale > 0.0;\n  if (is_rotation_finite && is_translation_finite && is_scale_valid) {\n    return true;\n  }\n\n  return false;\n}\n\nvoid SolveForRotationAndTranslation(\n    const Gp4pc::Input& input,\n    const std::vector<Eigen::Vector4d>& plausible_depths,\n    Gp4pc::Solution* solution) {\n  solution->rotations.reserve(plausible_depths.size());\n  solution->translations.reserve(plausible_depths.size());\n  solution->scales.reserve(plausible_depths.size());\n  solution->depths.reserve(plausible_depths.size());\n\n  // Solve for similarity transform using Umeyama's method. See\n  // theia/sfm/transformation/align_point_clouds.h for more information.\n  std::vector<Eigen::Vector3d> camera_points(input.world_points.size());\n  Eigen::Matrix3d rotation;\n  Eigen::Vector3d translation;\n  double scale;\n  for (const Eigen::Vector4d& depth : plausible_depths) {\n    // Compute the camera points.\n    camera_points[0] = ComputeCameraPoint(\n        input.ray_origins[0], input.ray_directions[0], depth[0]);\n    camera_points[1] = ComputeCameraPoint(\n        input.ray_origins[1], input.ray_directions[1], depth[1]);\n    camera_points[2] = ComputeCameraPoint(\n        input.ray_origins[2], input.ray_directions[2], depth[2]);\n    camera_points[3] = ComputeCameraPoint(\n        input.ray_origins[3], input.ray_directions[3], depth[3]);\n    theia::AlignPointCloudsUmeyama(\n        input.world_points, camera_points, &rotation, &translation, &scale);\n\n    if (IsSimilarityTransformValid(rotation, translation, scale)) {\n      solution->rotations.emplace_back(rotation);\n      solution->translations.emplace_back(translation);\n      solution->scales.emplace_back(scale);\n      solution->depths.emplace_back(depth);\n    }\n  }\n}\n\n}  // namespace\n\nGp4pc::Gp4pc(const Params& params) : params_(params) {}\n\nstd::vector<Eigen::Vector4d>\nGp4pc::KeepPlausibleSolutions(const Eigen::MatrixXcd& solutions) {\n  std::vector<Eigen::Vector4d> plausible_solutions;\n  plausible_solutions.reserve(kMaxNumDepthSolutions);\n\n  // Iterate through the possible solutions.\n  Eigen::Vector4d estimated_solution;\n  double discriminant = 0.0;\n  double max_imag_entry = 0.0;\n  Eigen::Vector4d prev_solution;\n  double min_depth = 0.0;\n  prev_solution.setZero();\n  for (int i = 0; i < solutions.cols(); ++i) {\n    max_imag_entry = std::max(std::abs(solutions(0, i).imag()),\n                              std::abs(solutions(1, i).imag()));\n    max_imag_entry = std::max(max_imag_entry, std::abs(solutions(2, i).imag()));\n    max_imag_entry = std::max(max_imag_entry, std::abs(solutions(3, i).imag()));\n    // TODO(vfragoso): Threshold solutions with large imaginary parts. Set a\n    // a good threshold for getting good solutions with small imaginary parts.\n    const bool real_solution = (max_imag_entry <= kRealNumberThreshold);\n    VLOG(4) << \"Max imag entry: \" << max_imag_entry\n            << \" => real_solution: \" << real_solution;\n\n    // Keep the solutions that correspond to positive depths.\n    estimated_solution[0] = solutions(0, i).real();\n    estimated_solution[1] = solutions(1, i).real();\n    estimated_solution[2] = solutions(2, i).real();\n    estimated_solution[3] = solutions(3, i).real();\n\n    min_depth = estimated_solution.minCoeff();\n    const bool all_positive_depths = (min_depth >= 0.0);\n    VLOG(4) << \"Min. depth: \" << min_depth\n            << \" => \" << all_positive_depths\n            << \" \" << estimated_solution.transpose();\n\n    // Avoid duplicated solutions coming from those with small imaginary parts.\n    // Remove duplicate solutions which are contigous.\n    const double error = (prev_solution - estimated_solution).squaredNorm();\n    const bool is_unique_soln = (error >= kDuplicateSolnErrorThreshold);\n\n    // Save previous solution, regardless.\n    VLOG(4) << \"Unique: \" << is_unique_soln << \" \"\n            << prev_solution.transpose() << \" <-> \"\n            << estimated_solution.transpose();\n    prev_solution = estimated_solution;\n    if (real_solution && all_positive_depths && is_unique_soln) {\n      // Save solution.\n      plausible_solutions.emplace_back(std::move(estimated_solution));\n    }\n  }\n\n  VLOG(4) << \"Plausible depths: \" << plausible_solutions.size()\n          << \" out of \" << solutions.cols();\n  return plausible_solutions;\n}\n\nstd::vector<Eigen::Vector4d>\nGp4pc::SolveForPoseViaPlanarSolver(const Gp4pc::Input& input) {\n  VLOG(4) << \"Solving pose using planar solver...\";\n  // Solve for depths via the planar solver.\n  const Eigen::MatrixXcd depths = SolveForDepthsFromAPlanarInput(input);\n\n  // Discard bad solutions.\n  const std::vector<Eigen::Vector4d> final_depths =\n      KeepPlausibleSolutions(depths);\n\n  return final_depths;\n}\n\nstd::vector<Eigen::Vector4d>\nGp4pc::SolveForPoseViaGeneralSolver(const Input& input) {\n  VLOG(4) << \"Solving for pose!\";\n  // Build coefficient matrix.\n  const Eigen::MatrixXd coefficients_matrix = BuildCoefficientMatrix(input);\n  VLOG(4) << \"Coeff matrix: \\n\" << coefficients_matrix;\n\n  // Solve for depths.\n  const Eigen::MatrixXcd depths = SolveGp4pcPolynomial(coefficients_matrix);\n\n  // Discard bad solutions.\n  const std::vector<Eigen::Vector4d> final_depths =\n      KeepPlausibleSolutions(depths);\n\n  return final_depths;\n}\n\nbool Gp4pc::EstimateSimilarityTransformation(const Input& input,\n                                             Solution* solution) {\n  using Eigen::MatrixXcd;\n  using Eigen::Vector4d;\n  CHECK_EQ(input.ray_origins.size(), kSizeOfMinimalSample);\n  CHECK_EQ(input.ray_origins.size(), input.ray_directions.size());\n  CHECK_EQ(input.ray_origins.size(), input.world_points.size());\n  CHECK_NOTNULL(solution)->rotations.clear();\n  solution->translations.clear();\n  solution->scales.clear();\n  solution->depths.clear();\n\n  // Validate input.\n  if (!IsInputValid(input)) {\n    return false;\n  }\n\n  // Each entry is the depth wrt to a camera center.\n  MatrixXcd depths;\n  std::vector<Vector4d> plausible_depths;\n  plausible_depths.reserve(kMaxNumDepthSolutions);\n\n  // Check whether the input is planar.\n  bool is_planar = false;\n  const bool use_planar_solver = !params_.use_general_solver;\n  if (IsInputDegenerateOrPlanar(input,\n                                params_.coplanar_threshold,\n                                params_.colinear_threshold,\n                                &is_planar)) {\n    VLOG(4) << \"Degenerate case. Could not compute pose.\";\n    return false;\n  } else if (use_planar_solver && is_planar) {\n    VLOG(4) << \"Coplanar case.\";\n    // Solve for the planar case.\n    plausible_depths = SolveForPoseViaPlanarSolver(input);\n  } else {\n    VLOG(4) << \"Using general solver.\";\n    plausible_depths = SolveForPoseViaGeneralSolver(input);\n  }\n\n  if (plausible_depths.empty()) {\n    return false;\n  }\n  VLOG(4) << \"Number of plausible depths: \" << plausible_depths.size();\n\n  // Solve for rotation and translation.\n  SolveForRotationAndTranslation(input, plausible_depths, solution);\n  VLOG(4) << \"Number of final solutions: \" << solution->rotations.size();\n\n  return !solution->rotations.empty();\n}\n\n}  // namespace msft\n", "meta": {"hexsha": "fcbf4c43202977903a097ad5b4be1a00f20ecb98", "size": 24199, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/gp4pc/gp4pc.cc", "max_stars_repo_name": "vfragoso/gp4pc", "max_stars_repo_head_hexsha": "6a3f66f2485f1f7b1e93b073ee65772dfda9c7b3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2020-12-01T02:09:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-28T12:53:43.000Z", "max_issues_repo_path": "src/gp4pc/gp4pc.cc", "max_issues_repo_name": "vfragoso/gp4pc", "max_issues_repo_head_hexsha": "6a3f66f2485f1f7b1e93b073ee65772dfda9c7b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gp4pc/gp4pc.cc", "max_forks_repo_name": "vfragoso/gp4pc", "max_forks_repo_head_hexsha": "6a3f66f2485f1f7b1e93b073ee65772dfda9c7b3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-14T12:52:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-29T15:23:46.000Z", "avg_line_length": 34.276203966, "max_line_length": 80, "alphanum_fraction": 0.6456051903, "num_tokens": 7683, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059414036511, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4640472017207165}}
{"text": "/*\n * PoseOptimizationSQP.cpp\n *\n *  Created on: Jun 10, 2015\n *      Author: P\u00e9ter Fankhauser\n *   Institute: ETH Zurich\n */\n\n#include \"free_gait_core/pose_optimization/PoseOptimizationSQP.hpp\"\n#include \"free_gait_core/pose_optimization/PoseParameterization.hpp\"\n#include \"free_gait_core/pose_optimization/PoseOptimizationProblem.hpp\"\n\n#include <Eigen/Core>\n#include <Eigen/Eigenvalues>\n#include <kindr/Core>\n#include <message_logger/message_logger.hpp>\n#include <numopt_quadprog/ActiveSetFunctionMinimizer.hpp>\n#include <numopt_sqp/SQPFunctionMinimizer.hpp>\n\n#include <functional>\n\nnamespace free_gait {\n\nPoseOptimizationSQP::PoseOptimizationSQP(const AdapterBase& adapter)\n    : PoseOptimizationBase(adapter),\n      timer_(\"PoseOptimizationSQP\"),\n      durationInCallback_(0.0),\n      nIterations_(0)\n{\n  objective_.reset(new PoseOptimizationObjectiveFunction());\n\n  constraints_.reset(new PoseOptimizationFunctionConstraints());\n  PoseOptimizationFunctionConstraints::LegPositions positionsBaseToHipInBaseFrame;\n  for (const auto& limb : adapter_.getLimbs()) {\n    positionsBaseToHipInBaseFrame[limb] = adapter_.getPositionBaseToHipInBaseFrame(limb);\n  }\n  constraints_->setPositionsBaseToHip(positionsBaseToHipInBaseFrame);\n\n  timer_.setAlpha(1.0);\n}\n\nPoseOptimizationSQP::~PoseOptimizationSQP()\n{\n}\n\nvoid PoseOptimizationSQP::setCurrentState(const State& state)\n{\n  originalState_ = state;\n}\n\nvoid PoseOptimizationSQP::registerOptimizationStepCallback(OptimizationStepCallbackFunction callback)\n{\n  optimizationStepCallback_ = callback;\n}\n\nbool PoseOptimizationSQP::optimize(Pose& pose)\n{\n  timer_.pinTime(\"total\");\n  durationInCallback_ = 0.0;\n  state_ = originalState_;\n  checkSupportRegion();\n\n  objective_->setInitialPose(pose);\n  objective_->setStance(stance_);\n  objective_->setNominalStance(nominalStanceInBaseFrame_);\n  objective_->setSupportRegion(supportRegion_);\n\n  constraints_->setStance(stance_);\n  constraints_->setSupportRegion(supportRegion_);\n  constraints_->setLimbLengthConstraints(minLimbLenghts_, maxLimbLenghts_);\n\n  state_.setPoseBaseToWorld(pose);\n  adapter_.setInternalDataFromState(state_, false, true, false, false); // To guide IK.\n  updateJointPositionsInState(state_); // For CoM calculation.\n  adapter_.setInternalDataFromState(state_, false, true, false, false);\n  const Position centerOfMassInBaseFrame(adapter_.transformPosition(adapter_.getWorldFrameId(), adapter_.getBaseFrameId(),\n                                 adapter_.getCenterOfMassInWorldFrame()));\n  objective_->setCenterOfMass(centerOfMassInBaseFrame);\n  constraints_->setCenterOfMass(centerOfMassInBaseFrame);\n  callExternalOptimizationStepCallback(0);\n\n  // Optimize.\n  PoseOptimizationProblem problem(objective_, constraints_);\n  std::shared_ptr<numopt_common::QuadraticProblemSolver> qpSolver(\n      new numopt_quadprog::ActiveSetFunctionMinimizer);\n  numopt_sqp::SQPFunctionMinimizer solver(qpSolver, 30, 0.01, 3, -DBL_MAX);\n  solver.registerOptimizationStepCallback(\n      std::bind(&PoseOptimizationSQP::optimizationStepCallback, this, std::placeholders::_1, std::placeholders::_2,\n                std::placeholders::_3, std::placeholders::_4));\n  solver.setCheckConstraints(false);\n  solver.setPrintOutput(false);\n  PoseParameterization params;\n  params.setPose(pose);\n  double functionValue;\n  if (!solver.minimize(&problem, params, functionValue)) return false;\n  pose = params.getPose();\n  // TODO Fix unit quaternion?\n\n  timer_.splitTime(\"total\");\n  return true;\n}\n\nvoid PoseOptimizationSQP::optimizationStepCallback(const size_t iterationStep,\n                                                   const numopt_common::Parameterization& parameters,\n                                                   const double functionValue,\n                                                   const bool finalIteration)\n{\n  nIterations_ = iterationStep;\n  auto& poseParameterization = dynamic_cast<const PoseParameterization&>(parameters);\n\n  // Update center of mass. // TODO Make optional.\n//  state_.setPoseBaseToWorld(poseParameterization.getPose());\n//  state_.setAllJointPositions(originalState_.getJointPositions());\n//  adapter_.setInternalDataFromState(state_, false, true, false, false);\n//  updateJointPositionsInState(state_);\n//  adapter_.setInternalDataFromState(state_, false, true, false, false); // TODO Improve efficiency.\n//  const Position centerOfMassInBaseFrame(adapter_.transformPosition(adapter_.getWorldFrameId(), adapter_.getBaseFrameId(),\n//                                 adapter_.getCenterOfMassInWorldFrame()));\n//  objective_->setCenterOfMass(centerOfMassInBaseFrame);\n//  constraints_->setCenterOfMass(centerOfMassInBaseFrame);\n\n  if (optimizationStepCallback_) {\n    timer_.pinTime(\"callback\");\n    auto& poseParameterization = dynamic_cast<const PoseParameterization&>(parameters);\n    state_.setPoseBaseToWorld(poseParameterization.getPose());\n    timer_.splitTime(\"callback\");\n    durationInCallback_ += timer_.getAverageElapsedTimeUSec(\"callback\");\n  }\n\n  callExternalOptimizationStepCallback(iterationStep + 1, functionValue, finalIteration);\n}\n\nvoid PoseOptimizationSQP::callExternalOptimizationStepCallbackWithPose(const Pose& pose, const size_t iterationStep,\n                                                                       const double functionValue,\n                                                                       const bool finalIteration)\n{\n  state_ = originalState_;\n  state_.setPoseBaseToWorld(pose);\n  callExternalOptimizationStepCallback(iterationStep, functionValue, finalIteration);\n}\n\ndouble PoseOptimizationSQP::getOptimizationDuration() const\n{\n  return timer_.getAverageElapsedTimeUSec(\"total\") - durationInCallback_;\n}\n\nsize_t PoseOptimizationSQP::getNumberOfIterations() const\n{\n  return nIterations_;\n}\n\nvoid PoseOptimizationSQP::callExternalOptimizationStepCallback(const size_t iterationStep, const double functionValue,\n                                                               const bool finalIteration)\n{\n  if (optimizationStepCallback_) {\n    timer_.pinTime(\"callback\");\n    adapter_.setInternalDataFromState(state_, false, true, false, false);\n    State previewState(state_);\n    updateJointPositionsInState(previewState);\n    optimizationStepCallback_(iterationStep, previewState, functionValue, finalIteration);\n    timer_.splitTime(\"callback\");\n    durationInCallback_ += timer_.getAverageElapsedTimeUSec(\"callback\");\n  }\n}\n\n} /* namespace */\n", "meta": {"hexsha": "97ce3e048a51a16bd1089fb48da89ab80a7d3805", "size": 6430, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "free_gait_core/src/pose_optimization/PoseOptimizationSQP.cpp", "max_stars_repo_name": "HeroWithL/free_gaitc", "max_stars_repo_head_hexsha": "ac4bc0ced56d0619d2fde105d2712fdf2507e245", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 330.0, "max_stars_repo_stars_event_min_datetime": "2016-10-25T14:04:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T12:31:41.000Z", "max_issues_repo_path": "free_gait_core/src/pose_optimization/PoseOptimizationSQP.cpp", "max_issues_repo_name": "HeroWithL/free_gaitc", "max_issues_repo_head_hexsha": "ac4bc0ced56d0619d2fde105d2712fdf2507e245", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 47.0, "max_issues_repo_issues_event_min_datetime": "2016-08-25T14:10:23.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-21T17:25:05.000Z", "max_forks_repo_path": "free_gait_core/src/pose_optimization/PoseOptimizationSQP.cpp", "max_forks_repo_name": "HeroWithL/free_gaitc", "max_forks_repo_head_hexsha": "ac4bc0ced56d0619d2fde105d2712fdf2507e245", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 122.0, "max_forks_repo_forks_event_min_datetime": "2016-10-25T14:04:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T21:32:51.000Z", "avg_line_length": 38.502994012, "max_line_length": 124, "alphanum_fraction": 0.7437013997, "num_tokens": 1442, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059414036511, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4640472017207165}}
{"text": "#ifndef STAN_MATH_PRIM_SCAL_PROB_GAMMA_LPDF_HPP\n#define STAN_MATH_PRIM_SCAL_PROB_GAMMA_LPDF_HPP\n\n#include <stan/math/prim/scal/meta/is_constant_struct.hpp>\n#include <stan/math/prim/scal/meta/partials_return_type.hpp>\n#include <stan/math/prim/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_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/err/check_not_nan.hpp>\n#include <stan/math/prim/scal/err/check_positive_finite.hpp>\n#include <stan/math/prim/scal/fun/constants.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/gamma_p.hpp>\n#include <stan/math/prim/scal/fun/digamma.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/grad_reg_inc_gamma.hpp>\n#include <boost/random/gamma_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <cmath>\n\nnamespace stan {\n  namespace math {\n\n    /**\n     * The log of a gamma density for y with the specified\n     * shape and inverse scale parameters.\n     * Shape and inverse scale parameters must be greater than 0.\n     * y must be greater than or equal to 0.\n     *\n     \\f{eqnarray*}{\n     y &\\sim& \\mbox{\\sf{Gamma}}(\\alpha, \\beta) \\\\\n     \\log (p (y \\, |\\, \\alpha, \\beta) ) &=& \\log \\left( \\frac{\\beta^\\alpha}{\\Gamma(\\alpha)} y^{\\alpha - 1} \\exp^{- \\beta y} \\right) \\\\\n     &=& \\alpha \\log(\\beta) - \\log(\\Gamma(\\alpha)) + (\\alpha - 1) \\log(y) - \\beta y\\\\\n     & & \\mathrm{where} \\; y > 0\n     \\f}\n     * @param y A scalar variable.\n     * @param alpha Shape parameter.\n     * @param beta Inverse scale parameter.\n     * @throw std::domain_error if alpha is not greater than 0.\n     * @throw std::domain_error if beta is not greater than 0.\n     * @throw std::domain_error if y is not greater than or equal to 0.\n     * @tparam T_y Type of scalar.\n     * @tparam T_shape Type of shape.\n     * @tparam T_inv_scale Type of inverse scale.\n     */\n    template <bool propto,\n              typename T_y, typename T_shape, typename T_inv_scale>\n    typename return_type<T_y, T_shape, T_inv_scale>::type\n    gamma_lpdf(const T_y& y, const T_shape& alpha, const T_inv_scale& beta) {\n      static const char* function(\"gamma_lpdf\");\n      typedef typename stan::partials_return_type<T_y, T_shape,\n                                                  T_inv_scale>::type\n        T_partials_return;\n\n      using stan::is_constant_struct;\n\n      if (!(stan::length(y) && stan::length(alpha) && stan::length(beta)))\n        return 0.0;\n\n      T_partials_return logp(0.0);\n\n      check_not_nan(function, \"Random variable\", y);\n      check_positive_finite(function, \"Shape parameter\", alpha);\n      check_positive_finite(function, \"Inverse scale parameter\", beta);\n      check_consistent_sizes(function,\n                             \"Random variable\", y,\n                             \"Shape parameter\", alpha,\n                             \"Inverse scale parameter\", beta);\n\n      if (!include_summand<propto, T_y, T_shape, T_inv_scale>::value)\n        return 0.0;\n\n      scalar_seq_view<T_y> y_vec(y);\n      scalar_seq_view<T_shape> alpha_vec(alpha);\n      scalar_seq_view<T_inv_scale> beta_vec(beta);\n\n      for (size_t n = 0; n < length(y); n++) {\n        const T_partials_return y_dbl = value_of(y_vec[n]);\n        if (y_dbl < 0)\n          return LOG_ZERO;\n      }\n\n      size_t N = max_size(y, alpha, beta);\n      operands_and_partials<T_y, T_shape, T_inv_scale>\n        ops_partials(y, alpha, beta);\n\n      using boost::math::lgamma;\n      using boost::math::digamma;\n      using std::log;\n\n      VectorBuilder<include_summand<propto, T_y, T_shape>::value,\n                    T_partials_return, T_y> log_y(length(y));\n      if (include_summand<propto, T_y, T_shape>::value) {\n        for (size_t n = 0; n < length(y); n++) {\n          if (value_of(y_vec[n]) > 0)\n            log_y[n] = log(value_of(y_vec[n]));\n        }\n      }\n\n      VectorBuilder<include_summand<propto, T_shape>::value,\n                    T_partials_return, T_shape> lgamma_alpha(length(alpha));\n      VectorBuilder<!is_constant_struct<T_shape>::value,\n                    T_partials_return, T_shape> digamma_alpha(length(alpha));\n      for (size_t n = 0; n < length(alpha); n++) {\n        if (include_summand<propto, T_shape>::value)\n          lgamma_alpha[n] = lgamma(value_of(alpha_vec[n]));\n        if (!is_constant_struct<T_shape>::value)\n          digamma_alpha[n] = digamma(value_of(alpha_vec[n]));\n      }\n\n      VectorBuilder<include_summand<propto, T_shape, T_inv_scale>::value,\n                    T_partials_return, T_inv_scale> log_beta(length(beta));\n      if (include_summand<propto, T_shape, T_inv_scale>::value) {\n        for (size_t n = 0; n < length(beta); n++)\n          log_beta[n] = log(value_of(beta_vec[n]));\n      }\n\n      for (size_t n = 0; n < N; n++) {\n        const T_partials_return y_dbl = value_of(y_vec[n]);\n        const T_partials_return alpha_dbl = value_of(alpha_vec[n]);\n        const T_partials_return beta_dbl = value_of(beta_vec[n]);\n\n        if (include_summand<propto, T_shape>::value)\n          logp -= lgamma_alpha[n];\n        if (include_summand<propto, T_shape, T_inv_scale>::value)\n          logp += alpha_dbl * log_beta[n];\n        if (include_summand<propto, T_y, T_shape>::value)\n          logp += (alpha_dbl - 1.0) * log_y[n];\n        if (include_summand<propto, T_y, T_inv_scale>::value)\n          logp -= beta_dbl * y_dbl;\n\n        if (!is_constant_struct<T_y>::value)\n          ops_partials.edge1_.partials_[n] += (alpha_dbl - 1) / y_dbl\n            - beta_dbl;\n        if (!is_constant_struct<T_shape>::value)\n          ops_partials.edge2_.partials_[n] += -digamma_alpha[n] + log_beta[n]\n            + log_y[n];\n        if (!is_constant_struct<T_inv_scale>::value)\n          ops_partials.edge3_.partials_[n] += alpha_dbl / beta_dbl - y_dbl;\n      }\n      return ops_partials.build(logp);\n    }\n\n    template <typename T_y, typename T_shape, typename T_inv_scale>\n    inline\n    typename return_type<T_y, T_shape, T_inv_scale>::type\n    gamma_lpdf(const T_y& y, const T_shape& alpha, const T_inv_scale& beta) {\n      return gamma_lpdf<false>(y, alpha, beta);\n    }\n\n  }\n}\n#endif\n", "meta": {"hexsha": "33462a977a0537f556f76da50e0120692d664d1e", "size": 6504, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/scal/prob/gamma_lpdf.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/prim/scal/prob/gamma_lpdf.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/prim/scal/prob/gamma_lpdf.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": 40.9056603774, "max_line_length": 134, "alphanum_fraction": 0.6423739237, "num_tokens": 1752, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059414036511, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4640472017207165}}
{"text": "#include <memory>\n#include <chrono>\n#include <random>\n#include <gflags/gflags.h>\n\n#include <Eigen/Sparse>\n\n#include \"drake/solvers/mosek_solver.h\"\n#include \"drake/solvers/gurobi_solver.h\"\n#include \"drake/solvers/mathematical_program.h\"\n\n#include \"examples/PlanarWalker/sgd_iter.h\"\n#include \"systems/goldilocks_models/file_utils.h\"\n\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\nusing std::string;\nusing drake::solvers::VectorXDecisionVariable;\n\nnamespace dairlib {\nnamespace goldilocks_models {\n\nvoid runSGD() {\n  std::random_device randgen;\n  std::default_random_engine e1(randgen());\n  std::uniform_real_distribution<> dist(0, 1);\n\n\n  int n_batch = 5;\n\n  // int n_weights = 43;\n  int n_weights =  10;\n  MatrixXd theta_0 = MatrixXd::Zero(2,n_weights);\n  theta_0(0,0) = -0.1;\n  theta_0(0,3) = 1.0;\n  theta_0(1,0) = 0;\n  theta_0(1,1) = 1;\n  writeCSV(\"data/0_theta.csv\", theta_0);\n\n  double length = 0.3;\n  double duration = 1;\n  int snopt_iter = 200;\n  string directory = \"data/\";\n  string init_z = \"z_save.csv\";\n  string weights = \"0_theta.csv\";\n  string output_prefix = \"0_0_\";\n  sgdIter(length, duration, snopt_iter, directory, init_z, weights, output_prefix);\n\n  for (int iter = 1; iter <= 50; iter++) {\n    int input_batch = iter == 1 ? 1 : n_batch;\n\n    std::vector<MatrixXd> A_vec;\n    std::vector<MatrixXd> B_vec;\n    std::vector<MatrixXd> H_vec;\n    std::vector<MatrixXd> A_active_vec;\n    std::vector<MatrixXd> B_active_vec;\n    std::vector<MatrixXd> lb_vec;\n    std::vector<MatrixXd> ub_vec;\n    std::vector<MatrixXd> y_vec;\n    std::vector<MatrixXd> w_vec;\n    std::vector<MatrixXd> z_vec;\n    std::vector<MatrixXd> theta_vec;\n    std::vector<double> nl_vec;\n    std::vector<double> nz_vec;\n\n    int nz=0,nt=0,nl=0;\n\n    for (int batch = 0; batch < input_batch; batch++) {\n      string batch_prefix = std::to_string(iter-1) + \"_\" + std::to_string(batch) + \"_\";\n      string iter_prefix = std::to_string(iter-1) + \"_\";\n\n      A_vec.push_back(readCSV(directory + batch_prefix + \"A.csv\"));\n      B_vec.push_back(readCSV(directory + batch_prefix + \"B.csv\"));\n      H_vec.push_back(readCSV(directory + batch_prefix + \"H.csv\"));\n      lb_vec.push_back(readCSV(directory + batch_prefix + \"lb.csv\"));\n      ub_vec.push_back(readCSV(directory + batch_prefix + \"ub.csv\"));\n      y_vec.push_back(readCSV(directory + batch_prefix + \"y.csv\"));\n      w_vec.push_back(readCSV(directory + batch_prefix + \"w.csv\"));\n      z_vec.push_back(readCSV(directory + batch_prefix + \"z.csv\"));\n      theta_vec.push_back(readCSV(directory + iter_prefix + \"theta.csv\"));\n\n      DRAKE_ASSERT(w_vec[batch].cols() == 1);\n      DRAKE_ASSERT(lb_vec[batch].cols() == 1);\n      DRAKE_ASSERT(ub_vec[batch].cols() == 1);\n      DRAKE_ASSERT(y_vec[batch].cols() == 1);\n      DRAKE_ASSERT(w_vec[batch].cols() == 1);\n      DRAKE_ASSERT(z_vec[batch].cols() == 1);\n\n\n      int n_active = 0;\n      double tol = 1e-4;\n      for (int i = 0; i < y_vec[batch].rows(); i++) {\n        if (y_vec[batch](i) >= ub_vec[batch](i) - tol || y_vec[batch](i) <= lb_vec[batch](i) + tol)\n          n_active++;\n      }\n\n      int nz_i = A_vec[batch].cols();\n      int nt_i = B_vec[batch].cols();\n\n      MatrixXd A_active(n_active, nz_i);\n      MatrixXd B_active(n_active, nt_i);\n      MatrixXd AB_active(n_active, nz_i + nt_i);\n\n      int nl_i = 0;\n      for (int i = 0; i < y_vec[batch].rows(); i++) {\n        if (y_vec[batch](i) >= ub_vec[batch](i) - tol || y_vec[batch](i) <= lb_vec[batch](i) + tol) {\n          A_active.row(nl_i) = A_vec[batch].row(i);\n          B_active.row(nl_i) = B_vec[batch].row(i);\n          AB_active.row(nl_i) << A_vec[batch].row(i), B_vec[batch].row(i);\n          nl_i++;\n        }\n      }\n\n      A_active_vec.push_back(A_active);\n      B_active_vec.push_back(B_active);\n      nl_vec.push_back(nl_i);\n      nz_vec.push_back(nz_i);\n\n      nl += nl_i;\n      nz += nz_i;\n      if (batch == 0) {\n        nt = nt_i;\n      } else {\n        DRAKE_ASSERT(nt == nt_i);\n        DRAKE_ASSERT((theta_vec[0] - theta_vec[batch]).norm() == 0);\n      }\n    }\n\n    //Join matricies\n    // MatrixXd AB_active = MatrixXd::Zero(nl,nz+nt);\n    // MatrixXd H_ext = MatrixXd::Zero(nz + nt, nz + nt);\n    VectorXd w_ext = VectorXd::Zero(nz+nt,1);\n    int nl_start = 0;\n    int nz_start = 0;\n    for (int batch = 0; batch < input_batch; batch++) {\n      // AB_active.block(nl_start, nz_start, nl_vec[batch], nz_vec[batch]) = A_active_vec[batch];\n      // AB_active.block(nl_start, nz, nl_vec[batch], nt) = B_active_vec[batch];\n\n      // H_ext.block(nz_start,nz_start,nz_vec[batch],nz_vec[batch]) = H_vec[batch];\n      w_ext.segment(nz_start,nz_vec[batch]) = w_vec[batch].col(0);\n\n      nl_start += nl_vec[batch];\n      nz_start += nz_vec[batch];\n    }\n    // H_ext.block(nz,nz,nt,nt) = 1e-2*MatrixXd::Identity(nt,nt);\n\n\n    // Eigen::BDCSVD<MatrixXd> svd(AB_active,  Eigen::ComputeFullV);\n\n    // MatrixXd N = svd.matrixV().rightCols(AB_active.cols() - svd.rank());\n\n    // auto gradient = N*N.transpose()*w_ext;\n\n    // double scale_num= gradient.dot(gradient);\n    // double scale_den = gradient.dot(Ei_ext*gradient);\n\n    // auto dtheta = -0.02*gradient.tail(nt)*scale_num/scale_den;\n\n\n    nl_start = 0;\n    nz_start = 0;\n    std::vector<Eigen::Triplet<double>> tripletList;\n    std::vector<Eigen::Triplet<double>> tripletList_H;\n    for (int batch = 0; batch < input_batch; batch++) {\n      for (int i = 0; i < nz_vec[batch]; i++) {\n        for (int j = 0; j < nz_vec[batch]; j++) {\n          tripletList.push_back(Eigen::Triplet<double>(nz_start + i, nz_start + j, H_vec[batch](i,j)));\n          tripletList_H.push_back(Eigen::Triplet<double>(nz_start + i, nz_start + j, H_vec[batch](i,j)));\n        }\n      }\n      for (int i = 0; i < nl_vec[batch]; i++) {\n        for (int j = 0; j < nz_vec[batch]; j++) {\n          int i_ind = nz + nt + nl_start + i;\n          int j_ind = nz_start + j;\n          tripletList.push_back(Eigen::Triplet<double>(i_ind, j_ind, A_active_vec[batch](i,j)));\n          tripletList.push_back(Eigen::Triplet<double>(j_ind, i_ind, A_active_vec[batch](i,j)));\n        }\n        for (int j = 0; j < nt; j++) {\n          int i_ind = nz + nt + nl_start + i;\n          int j_ind = nz + j;\n          tripletList.push_back(Eigen::Triplet<double>(i_ind, j_ind, B_active_vec[batch](i,j)));\n          tripletList.push_back(Eigen::Triplet<double>(j_ind, i_ind, B_active_vec[batch](i,j)));\n        }\n      }\n      nl_start += nl_vec[batch];\n      nz_start += nz_vec[batch];\n    }\n\n    VectorXd b(nz + nt + nl);\n    b << -w_ext, VectorXd::Zero(nl);\n\n    Eigen::SparseMatrix<double> M(nz + nt + nl, nz + nt + nl);\n    M.setFromTriplets(tripletList.begin(), tripletList.end());\n\n    Eigen::SparseMatrix<double> H_ext(nz + nt, nz + nt);\n    H_ext.setFromTriplets(tripletList_H.begin(), tripletList_H.end());\n    Eigen::SparseQR<Eigen::SparseMatrix<double>, Eigen::COLAMDOrdering<int>> qr(M);\n    auto gradient = qr.solve(b);\n\n    // Eigen::SparseLU<Eigen::SparseMatrix<double>, Eigen::COLAMDOrdering<int>> solver;\n    // // fill A and b;\n    // // Compute the ordering permutation vector from the structural pattern of A\n    // solver.analyzePattern(M); \n    // // Compute the numerical factorization\n    // solver.factorize(M);\n    // std::cout << solver.info() << std::endl;\n    // //Use the factors to solve the linear system\n    // auto gradient = solver.solve(b);\n\n    // Eigen::BiCGSTAB<Eigen::SparseMatrix<double> > solver;\n    // solver.compute(M);\n    // auto gradient = solver.solve(b);\n    // std::cout << \"#iterations:     \" << solver.iterations() << std::endl;\n    // std::cout << \"estimated error: \" << solver.error()      << std::endl;\n\n    // std::cout << M*gradient - b << std::endl;\n\n\n    // std::cout << gradient << std::endl;\n\n\n    // //M = [H_ext A'; A 0]\n    // MatrixXd M(nz + nt + nl, nz + nt + nl);\n    // M.block(0, 0, nz + nt, nz + nt) = H_ext;\n    // M.block(0, nz + nt, nz + nt, nl) = AB_active.transpose();\n    // M.block(nz + nt, 0, nl, nz + nt) = AB_active;\n    // M.block(nz + nt, nz + nt, nl, nl) = MatrixXd::Zero(nl,nl);\n    // VectorXd b(nz + nt + nl);\n    // b << -w_ext, VectorXd::Zero(nl);\n    // auto gradient = M.colPivHouseholderQr().solve(b);\n\n    auto zt = gradient.head(nz+nt);\n\n    auto resid = M*gradient - b;\n\n    std::cout << \"residual-norm: \"<< resid.tail(nl).norm() << std::endl;\n    std::cout << \"descent: \"<< gradient.head(nz+nt).dot(w_ext) << std::endl;\n\n    double scale = 1/sqrt(zt.dot(H_ext*zt));\n\n    std::cout << \"scale: \"<< scale << std::endl;\n\n    auto dtheta = -.01*scale*gradient.segment(nz, nt);\n\n\n    std::cout << \"found dtheta\"<< std::endl;\n\n    std::cout << std::endl<< \"dtheta norm: \" << dtheta.norm() << std::endl;\n    std::cout << \"***********Next iteration*************\" << std::endl;\n\n    // std::cout << \"scale predict: \" << scale_num/scale_den << std::endl;\n\n    //reshape dtheta\n    MatrixXd theta_mat(theta_vec[0].rows(), theta_vec[0].cols());\n    for (int i = 0; i < theta_vec[0].rows(); i++) {\n      theta_mat.row(i) = theta_vec[0].row(i) +\n                         dtheta.segment(i*theta_vec[0].cols(),theta_vec[0].cols()).transpose();\n    }\n    if (iter == 1)\n      writeCSV(\"data/\" + std::to_string(iter) + \"_theta.csv\", theta_vec[0]);\n    else\n      writeCSV(\"data/\" + std::to_string(iter) + \"_theta.csv\", theta_mat);\n\n    // init_z = std::to_string(iter-1) + \"_z.csv\";\n    init_z = \"z_save.csv\";\n    weights = std::to_string(iter) +  \"_theta.csv\";\n    output_prefix = std::to_string(iter) +  \"_\";\n\n    for(int batch = 0; batch < n_batch; batch++) {\n    //randomize distance on [0.3,0.5]\n      // length = 0.2 + 0.3*dist(e1);\n      length = 0.15 + 0.05*batch + 0.0*dist(e1);\n      // duration =  length/0.5; //maintain constaint speed of 0.5 m/s\n      duration = 1;\n\n      int length_file_index = (int) ((0.5 - length) * 10);\n      if (iter == 1) \n        init_z = \"init_length_\" + std::to_string(length_file_index) + \"_speed_0_z.csv\";\n      else\n        init_z = std::to_string(iter-1) + \"_\" + std::to_string(batch) + \"_z.csv\";\n\n      std::cout << std::endl << \"Iter-Batch: \" << iter << \"-\" << batch << std::endl;\n      std::cout << \"New length: \" << length << std::endl;\n\n      string batch_prefix = output_prefix + std::to_string(batch) + \"_\";\n\n      sgdIter(length, duration, snopt_iter, directory, init_z, weights, batch_prefix);\n    }\n  }\n}\n}  // namespace goldilocks_models\n}  // namespace dairlib\n\nint main(int argc, char* argv[]) {\n  gflags::ParseCommandLineFlags(&argc, &argv, true);\n  std::srand(time(0));  // Initialize random number generator.\n\n  dairlib::goldilocks_models::runSGD();\n}\n", "meta": {"hexsha": "daee03642b7fcae5ff1a60df7ae3304716feda03", "size": 10549, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/PlanarWalker/runSGD.cc", "max_stars_repo_name": "makariosc/dairlib_old", "max_stars_repo_head_hexsha": "52cf0f20480802e482fd282fcf235495e387755b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-08-29T17:46:19.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-29T17:46:19.000Z", "max_issues_repo_path": "examples/PlanarWalker/runSGD.cc", "max_issues_repo_name": "Nanda-Kishore-V/dairlib", "max_issues_repo_head_hexsha": "7ffd43bb559408bc96bd590992aab52d42dfba16", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/PlanarWalker/runSGD.cc", "max_forks_repo_name": "Nanda-Kishore-V/dairlib", "max_forks_repo_head_hexsha": "7ffd43bb559408bc96bd590992aab52d42dfba16", "max_forks_repo_licenses": ["BSD-3-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.1633333333, "max_line_length": 105, "alphanum_fraction": 0.6028059532, "num_tokens": 3222, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105941403651, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4640472017207164}}
{"text": "/* boost random/geometric_distribution.hpp header file\n *\n * Copyright Jens Maurer 2000-2001\n * Copyright Steven Watanabe 2011\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 * Revision history\n *  2001-02-18  moved to individual header files\n */\n\n#ifndef BOOST_RANDOM_GEOMETRIC_DISTRIBUTION_HPP\n#define BOOST_RANDOM_GEOMETRIC_DISTRIBUTION_HPP\n\n#include <boost/config/no_tr1/cmath.hpp>          // std::log\n#include <iosfwd>\n#include <ios>\n#include <boost/assert.hpp>\n#include <boost/random/detail/config.hpp>\n#include <boost/random/detail/operators.hpp>\n#include <boost/random/uniform_01.hpp>\n\nnamespace boost {\nnamespace random {\n\n/**\n * An instantiation of the class template @c geometric_distribution models\n * a \\random_distribution.  The distribution produces positive\n * integers which are the number of bernoulli trials\n * with probability @c p required to get one that fails.\n *\n * For the geometric distribution, \\f$p(i) = p(1-p)^{i}\\f$.\n *\n * @xmlwarning\n * This distribution has been updated to match the C++ standard.\n * Its behavior has changed from the original\n * boost::geometric_distribution.  A backwards compatible\n * wrapper is provided in namespace boost.\n * @endxmlwarning\n */\ntemplate<class IntType = int, class RealType = double>\nclass geometric_distribution\n{\npublic:\n    typedef RealType input_type;\n    typedef IntType result_type;\n\n    class param_type\n    {\n    public:\n\n        typedef geometric_distribution distribution_type;\n\n        /** Constructs the parameters with p. */\n        explicit param_type(RealType p_arg = RealType(0.5))\n          : _p(p_arg)\n        {\n            BOOST_ASSERT(RealType(0) < _p && _p < RealType(1));\n        }\n\n        /** Returns the p parameter of the distribution. */\n        RealType p() const { return _p; }\n\n        /** Writes the parameters to a std::ostream. */\n        BOOST_RANDOM_DETAIL_OSTREAM_OPERATOR(os, param_type, parm)\n        {\n            os << parm._p;\n            return os;\n        }\n\n        /** Reads the parameters from a std::istream. */\n        BOOST_RANDOM_DETAIL_ISTREAM_OPERATOR(is, param_type, parm)\n        {\n            double p_in;\n            if(is >> p_in) {\n                if(p_in > RealType(0) && p_in < RealType(1)) {\n                    parm._p = p_in;\n                } else {\n                    is.setstate(std::ios_base::failbit);\n                }\n            }\n            return is;\n        }\n\n        /** Returns true if the two sets of parameters are equal. */\n        BOOST_RANDOM_DETAIL_EQUALITY_OPERATOR(param_type, lhs, rhs)\n        { return lhs._p == rhs._p; }\n\n        /** Returns true if the two sets of parameters are different. */\n        BOOST_RANDOM_DETAIL_INEQUALITY_OPERATOR(param_type)\n\n\n    private:\n        RealType _p;\n    };\n\n    /**\n     * Contructs a new geometric_distribution with the paramter @c p.\n     *\n     * Requires: 0 < p < 1\n     */\n    explicit geometric_distribution(const RealType& p_arg = RealType(0.5))\n      : _p(p_arg)\n    {\n        BOOST_ASSERT(RealType(0) < _p && _p < RealType(1));\n        init();\n    }\n\n    /** Constructs a new geometric_distribution from its parameters. */\n    explicit geometric_distribution(const param_type& parm)\n      : _p(parm.p())\n    {\n        init();\n    }\n\n    // compiler-generated copy ctor and assignment operator are fine\n\n    /** Returns: the distribution parameter @c p  */\n    RealType p() const { return _p; }\n\n    /** Returns the smallest value that the distribution can produce. */\n    IntType min BOOST_PREVENT_MACRO_SUBSTITUTION () const { return IntType(0); }\n\n    /** Returns the largest value that the distribution can produce. */\n    IntType max BOOST_PREVENT_MACRO_SUBSTITUTION () const\n    { return (std::numeric_limits<IntType>::max)(); }\n\n    /** Returns the parameters of the distribution. */\n    param_type param() const { return param_type(_p); }\n\n    /** Sets the parameters of the distribution. */\n    void param(const param_type& parm)\n    {\n        _p = parm.p();\n        init();\n    }\n  \n    /**\n     * Effects: Subsequent uses of the distribution do not depend\n     * on values produced by any engine prior to invoking reset.\n     */\n    void reset() { }\n\n    /**\n     * Returns a random variate distributed according to the\n     * geometric_distribution.\n     */\n    template<class Engine>\n    result_type operator()(Engine& eng) const\n    {\n        using std::log;\n        using std::floor;\n        RealType x = RealType(1) - boost::uniform_01<RealType>()(eng);\n        return IntType(floor(log(x) / _log_1mp));\n    }\n\n    /**\n     * Returns a random variate distributed according to the\n     * geometric distribution with parameters specified by param.\n     */\n    template<class Engine>\n    result_type operator()(Engine& eng, const param_type& parm) const\n    { return geometric_distribution(parm)(eng); }\n\n    /** Writes the distribution to a @c std::ostream. */\n    BOOST_RANDOM_DETAIL_OSTREAM_OPERATOR(os, geometric_distribution, gd)\n    {\n        os << gd._p;\n        return os;\n    }\n\n    /** Reads the distribution from a @c std::istream. */\n    BOOST_RANDOM_DETAIL_ISTREAM_OPERATOR(is, geometric_distribution, gd)\n    {\n        param_type parm;\n        if(is >> parm) {\n            gd.param(parm);\n        }\n        return is;\n    }\n\n    /**\n     * Returns true if the two distributions will produce identical\n     * sequences of values given equal generators.\n     */\n    BOOST_RANDOM_DETAIL_EQUALITY_OPERATOR(geometric_distribution, lhs, rhs)\n    { return lhs._p == rhs._p; }\n\n    /**\n     * Returns true if the two distributions may produce different\n     * sequences of values given equal generators.\n     */\n    BOOST_RANDOM_DETAIL_INEQUALITY_OPERATOR(geometric_distribution)\n\nprivate:\n\n    /// \\cond show_private\n\n    void init()\n    {\n        using std::log;\n        _log_1mp = log(1 - _p);\n    }\n\n    RealType _p;\n    RealType _log_1mp;\n\n    /// \\endcond\n};\n\n} // namespace random\n\n/// \\cond show_deprecated\n\n/**\n * Provided for backwards compatibility.  This class is\n * deprecated.  It provides the old behavior of geometric_distribution\n * with \\f$p(i) = (1-p) p^{i-1}\\f$.\n */\ntemplate<class IntType = int, class RealType = double>\nclass geometric_distribution\n{\npublic:\n    typedef RealType input_type;\n    typedef IntType result_type;\n\n    explicit geometric_distribution(RealType p_arg = RealType(0.5))\n      : _impl(1 - p_arg) {}\n\n    RealType p() const { return 1 - _impl.p(); }\n\n    void reset() {}\n\n    template<class Engine>\n    IntType operator()(Engine& eng) const { return _impl(eng) + IntType(1); }\n\n    BOOST_RANDOM_DETAIL_OSTREAM_OPERATOR(os, geometric_distribution, gd)\n    {\n        os << gd.p();\n        return os;\n    }\n\n    BOOST_RANDOM_DETAIL_ISTREAM_OPERATOR(is, geometric_distribution, gd)\n    {\n        RealType val;\n        if(is >> val) {\n            typename impl_type::param_type impl_param(1 - val);\n            gd._impl.param(impl_param);\n        }\n        return is;\n    }\n\nprivate:\n    typedef random::geometric_distribution<IntType, RealType> impl_type;\n    impl_type _impl;\n};\n\n/// \\endcond\n\n} // namespace boost\n\n#endif // BOOST_RANDOM_GEOMETRIC_DISTRIBUTION_HPP\n", "meta": {"hexsha": "90374cff71b2fbc3c0cfd1b45688d9d7c68c30ec", "size": 7339, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/libboost/boost_1_62_0/boost/random/geometric_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/geometric_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/geometric_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": 27.3843283582, "max_line_length": 80, "alphanum_fraction": 0.6400054503, "num_tokens": 1717, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.78793120560257, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.46400412277214736}}
{"text": "#ifndef BART_SRC_CONVERGENCE_MOMENTS_SINGLE_MOMENT_L1_NORM_H_\n#define BART_SRC_CONVERGENCE_MOMENTS_SINGLE_MOMENT_L1_NORM_H_\n\n#include \"convergence/convergence_checker.hpp\"\n\n#include <deal.II/lac/vector.h>\n\n//! Convergence checkers for problem vector moments\nnamespace bart::convergence::moments {\n\n/*! \\brief Checks for convergence between flux moments using the percentage\n * change in the L1 norm, compared to the current iteration (\\f$i\\f$):\n *\n * \\f[\n *\n * \\Delta_i = \\frac{|\\phi_i - \\phi_{i-1}|_{1}}{|\\phi_{i}|_{1}}\n *\n * \\f]\n *\n * Convergence is achieved if \\f$\\Delta_i \\leq \\Delta_{\\text{max}}\\f$.\n * */\n\nclass ConvergenceCheckerL1Norm : public ConvergenceChecker<dealii::Vector<double>> {\n public:\n  using Vector = dealii::Vector<double>;\n  /*! \\brief Default constructor, setting max delta to \\f$10^{-6}\\f$. */\n  explicit ConvergenceCheckerL1Norm(const double max_delta = 1e-6);\n  auto SetMaxDelta(const double& to_set) -> void override;\n  auto IsConverged(const Vector& current_iteration, const Vector& previous_iteration) -> bool override;\n};\n\n} // namespace bart::convergence::moments\n\n#endif // BART_SRC_CONVERGENCE_MOMENTS_SINGLE_MOMENT_L1_NORM_H_\n", "meta": {"hexsha": "55a8fd3124ca897c7748b903329205e6d42c3eaf", "size": 1162, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/convergence/moments/convergence_checker_l1_norm.hpp", "max_stars_repo_name": "SlaybaughLab/Transport", "max_stars_repo_head_hexsha": "8eb32cb8ae50c92875526a7540350ef9a85bc050", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2018-03-14T12:30:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T14:46:44.000Z", "max_issues_repo_path": "src/convergence/moments/convergence_checker_l1_norm.hpp", "max_issues_repo_name": "SlaybaughLab/Transport", "max_issues_repo_head_hexsha": "8eb32cb8ae50c92875526a7540350ef9a85bc050", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 194.0, "max_issues_repo_issues_event_min_datetime": "2017-07-07T01:38:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-19T18:21:19.000Z", "max_forks_repo_path": "src/convergence/moments/convergence_checker_l1_norm.hpp", "max_forks_repo_name": "SlaybaughLab/Transport", "max_forks_repo_head_hexsha": "8eb32cb8ae50c92875526a7540350ef9a85bc050", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2017-07-06T22:58:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-15T07:01:21.000Z", "avg_line_length": 33.2, "max_line_length": 103, "alphanum_fraction": 0.7469879518, "num_tokens": 326, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879312056025699, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4640041227721473}}
{"text": "#ifndef FIELD_MATH_H_\n#define FIELD_MATH_H_\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <algorithm>\n//#include <glm/glm.hpp>\n#include <vector>\nusing namespace Eigen;\n\nstruct DEdge\n{\n    DEdge()\n    : x(0), y(0)\n    {}\n    DEdge(int _x, int _y) {\n        if (_x > _y)\n            x = _y, y = _x;\n        else\n            x = _x, y = _y;\n    }\n    bool operator<(const DEdge& e) const {\n        return (x < e.x) || (x == e.x && y < e.y);\n    }\n    bool operator==(const DEdge& e) const {\n        return x == e.x && y == e.y;\n    }\n    bool operator!=(const DEdge& e) const {\n        return x != e.x || y != e.y;\n    }\n    int x, y;\n};\n\ninline int get_parents(std::vector<std::pair<int, int>>& parents, int j) {\n    if (j == parents[j].first) return j;\n    int k = get_parents(parents, parents[j].first);\n    parents[j].second = (parents[j].second + parents[parents[j].first].second) % 4;\n    parents[j].first = k;\n    return k;\n}\n\ninline int get_parents_orient(std::vector<std::pair<int, int>>& parents, int j) {\n    if (j == parents[j].first) return parents[j].second;\n    return (parents[j].second + get_parents_orient(parents, parents[j].first)) % 4;\n}\n\ninline double fast_acos(double x) {\n    double negate = double(x < 0.0f);\n    x = std::abs(x);\n    double ret = -0.0187293f;\n    ret *= x;\n    ret = ret + 0.0742610f;\n    ret *= x;\n    ret = ret - 0.2121144f;\n    ret *= x;\n    ret = ret + 1.5707288f;\n    ret = ret * std::sqrt(1.0f - x);\n    ret = ret - 2.0f * negate * ret;\n    return negate * (double)M_PI + ret;\n}\n\ninline double signum(double value) { return std::copysign((double)1, value); }\n\n/// Always-positive modulo function (assumes b > 0)\ninline int modulo(int a, int b) {\n    int r = a % b;\n    return (r < 0) ? r + b : r;\n}\n\ninline Vector3d rotate90_by(const Vector3d &q, const Vector3d &n, int amount) {\n    return ((amount & 1) ? (n.cross(q)) : q) * (amount < 2 ? 1.0f : -1.0f);\n}\n\ninline Vector2i rshift90(Vector2i shift, int amount) {\n    if (amount & 1) shift = Vector2i(-shift.y(), shift.x());\n    if (amount >= 2) shift = -shift;\n    return shift;\n}\n\ninline std::pair<int, int> compat_orientation_extrinsic_index_4(const Vector3d &q0,\n                                                                const Vector3d &n0,\n                                                                const Vector3d &q1,\n                                                                const Vector3d &n1) {\n    const Vector3d A[2] = {q0, n0.cross(q0)};\n    const Vector3d B[2] = {q1, n1.cross(q1)};\n\n    double best_score = -std::numeric_limits<double>::infinity();\n    int best_a = 0, best_b = 0;\n\n    for (int i = 0; i < 2; ++i) {\n        for (int j = 0; j < 2; ++j) {\n            double score = std::abs(A[i].dot(B[j]));\n            if (score > best_score) {\n                best_a = i;\n                best_b = j;\n                best_score = score;\n            }\n        }\n    }\n\n    if (A[best_a].dot(B[best_b]) < 0) best_b += 2;\n\n    return std::make_pair(best_a, best_b);\n}\n\ninline std::pair<Vector3d, Vector3d> compat_orientation_extrinsic_4(const Vector3d &q0,\n                                                                    const Vector3d &n0,\n                                                                    const Vector3d &q1,\n                                                                    const Vector3d &n1) {\n    const Vector3d A[2] = {q0, n0.cross(q0)};\n    const Vector3d B[2] = {q1, n1.cross(q1)};\n\n    double best_score = -std::numeric_limits<double>::infinity();\n    int best_a = 0, best_b = 0;\n\n    for (int i = 0; i < 2; ++i) {\n        for (int j = 0; j < 2; ++j) {\n            double score = std::abs(A[i].dot(B[j]));\n            if (score > best_score + 1e-6) {\n                best_a = i;\n                best_b = j;\n                best_score = score;\n            }\n        }\n    }\n\n    const double dp = A[best_a].dot(B[best_b]);\n    return std::make_pair(A[best_a], B[best_b] * signum(dp));\n}\n\ninline Vector3d middle_point(const Vector3d &p0, const Vector3d &n0, const Vector3d &p1,\n                             const Vector3d &n1) {\n    /* How was this derived?\n     *\n     * Minimize \\|x-p0\\|^2 + \\|x-p1\\|^2, where\n     * dot(n0, x) == dot(n0, p0)\n     * dot(n1, x) == dot(n1, p1)\n     *\n     * -> Lagrange multipliers, set derivative = 0\n     *  Use first 3 equalities to write x in terms of\n     *  lambda_1 and lambda_2. Substitute that into the last\n     *  two equations and solve for the lambdas. Finally,\n     *  add a small epsilon term to avoid issues when n1=n2.\n     */\n    double n0p0 = n0.dot(p0), n0p1 = n0.dot(p1), n1p0 = n1.dot(p0), n1p1 = n1.dot(p1),\n           n0n1 = n0.dot(n1), denom = 1.0f / (1.0f - n0n1 * n0n1 + 1e-4f),\n           lambda_0 = 2.0f * (n0p1 - n0p0 - n0n1 * (n1p0 - n1p1)) * denom,\n           lambda_1 = 2.0f * (n1p0 - n1p1 - n0n1 * (n0p1 - n0p0)) * denom;\n\n    return 0.5f * (p0 + p1) - 0.25f * (n0 * lambda_0 + n1 * lambda_1);\n}\n\ninline Vector3d position_floor_4(const Vector3d &o, const Vector3d &q, const Vector3d &n,\n                                 const Vector3d &p, double scale_x, double scale_y,\n                                 double inv_scale_x, double inv_scale_y) {\n    Vector3d t = n.cross(q);\n    Vector3d d = p - o;\n    return o + q * std::floor(q.dot(d) * inv_scale_x) * scale_x +\n           t * std::floor(t.dot(d) * inv_scale_y) * scale_y;\n}\n\ninline std::pair<Vector3d, Vector3d> compat_position_extrinsic_4(\n    const Vector3d &p0, const Vector3d &n0, const Vector3d &q0, const Vector3d &o0,\n    const Vector3d &p1, const Vector3d &n1, const Vector3d &q1, const Vector3d &o1, double scale_x,\n    double scale_y, double inv_scale_x, double inv_scale_y, double scale_x_1, double scale_y_1,\n    double inv_scale_x_1, double inv_scale_y_1) {\n    Vector3d t0 = n0.cross(q0), t1 = n1.cross(q1);\n    Vector3d middle = middle_point(p0, n0, p1, n1);\n    Vector3d o0p =\n        position_floor_4(o0, q0, n0, middle, scale_x, scale_y, inv_scale_x, inv_scale_y);\n    Vector3d o1p =\n        position_floor_4(o1, q1, n1, middle, scale_x_1, scale_y_1, inv_scale_x_1, inv_scale_y_1);\n\n    double best_cost = std::numeric_limits<double>::infinity();\n    int best_i = -1, best_j = -1;\n\n    for (int i = 0; i < 4; ++i) {\n        Vector3d o0t = o0p + (q0 * (i & 1) * scale_x + t0 * ((i & 2) >> 1) * scale_y);\n        for (int j = 0; j < 4; ++j) {\n            Vector3d o1t = o1p + (q1 * (j & 1) * scale_x_1 + t1 * ((j & 2) >> 1) * scale_y_1);\n            double cost = (o0t - o1t).squaredNorm();\n\n            if (cost < best_cost) {\n                best_i = i;\n                best_j = j;\n                best_cost = cost;\n            }\n        }\n    }\n\n    return std::make_pair(\n        o0p + (q0 * (best_i & 1) * scale_x + t0 * ((best_i & 2) >> 1) * scale_y),\n        o1p + (q1 * (best_j & 1) * scale_x_1 + t1 * ((best_j & 2) >> 1) * scale_y_1));\n}\n\ninline Vector3d position_round_4(const Vector3d &o, const Vector3d &q, const Vector3d &n,\n                                 const Vector3d &p, double scale_x, double scale_y,\n                                 double inv_scale_x, double inv_scale_y) {\n    Vector3d t = n.cross(q);\n    Vector3d d = p - o;\n    return o + q * std::round(q.dot(d) * inv_scale_x) * scale_x +\n           t * std::round(t.dot(d) * inv_scale_y) * scale_y;\n}\n\ninline Vector2i position_floor_index_4(const Vector3d &o, const Vector3d &q, const Vector3d &n,\n                                       const Vector3d &p, double /* unused */, double /* unused */,\n                                       double inv_scale_x, double inv_scale_y) {\n    Vector3d t = n.cross(q);\n    Vector3d d = p - o;\n    return Vector2i((int)std::floor(q.dot(d) * inv_scale_x),\n                    (int)std::floor(t.dot(d) * inv_scale_y));\n}\n\ninline std::pair<Vector2i, Vector2i> compat_position_extrinsic_index_4(\n    const Vector3d &p0, const Vector3d &n0, const Vector3d &q0, const Vector3d &o0,\n    const Vector3d &p1, const Vector3d &n1, const Vector3d &q1, const Vector3d &o1, double scale_x,\n    double scale_y, double inv_scale_x, double inv_scale_y, double scale_x_1, double scale_y_1,\n    double inv_scale_x_1, double inv_scale_y_1, double *error) {\n    Vector3d t0 = n0.cross(q0), t1 = n1.cross(q1);\n    Vector3d middle = middle_point(p0, n0, p1, n1);\n    Vector2i o0p =\n        position_floor_index_4(o0, q0, n0, middle, scale_x, scale_y, inv_scale_x, inv_scale_y);\n    Vector2i o1p = position_floor_index_4(o1, q1, n1, middle, scale_x_1, scale_y_1, inv_scale_x_1,\n                                          inv_scale_y_1);\n\n    double best_cost = std::numeric_limits<double>::infinity();\n    int best_i = -1, best_j = -1;\n\n    for (int i = 0; i < 4; ++i) {\n        Vector3d o0t =\n            o0 + (q0 * ((i & 1) + o0p[0]) * scale_x + t0 * (((i & 2) >> 1) + o0p[1]) * scale_y);\n        for (int j = 0; j < 4; ++j) {\n            Vector3d o1t = o1 + (q1 * ((j & 1) + o1p[0]) * scale_x_1 +\n                                 t1 * (((j & 2) >> 1) + o1p[1]) * scale_y_1);\n            double cost = (o0t - o1t).squaredNorm();\n\n            if (cost < best_cost) {\n                best_i = i;\n                best_j = j;\n                best_cost = cost;\n            }\n        }\n    }\n    if (error) *error = best_cost;\n\n    return std::make_pair(Vector2i((best_i & 1) + o0p[0], ((best_i & 2) >> 1) + o0p[1]),\n                          Vector2i((best_j & 1) + o1p[0], ((best_j & 2) >> 1) + o1p[1]));\n}\n\ninline void coordinate_system(const Vector3d &a, Vector3d &b, Vector3d &c) {\n    if (std::abs(a.x()) > std::abs(a.y())) {\n        double invLen = 1.0f / std::sqrt(a.x() * a.x() + a.z() * a.z());\n        c = Vector3d(a.z() * invLen, 0.0f, -a.x() * invLen);\n    } else {\n        double invLen = 1.0f / std::sqrt(a.y() * a.y() + a.z() * a.z());\n        c = Vector3d(0.0f, a.z() * invLen, -a.y() * invLen);\n    }\n    b = c.cross(a);\n}\n\ninline Vector3d rotate_vector_into_plane(Vector3d q, const Vector3d &source_normal,\n                                         const Vector3d &target_normal) {\n    const double cosTheta = source_normal.dot(target_normal);\n    if (cosTheta < 0.9999f) {\n        if (cosTheta < -0.9999f) return -q;\n        Vector3d axis = source_normal.cross(target_normal);\n        q = q * cosTheta + axis.cross(q) +\n            axis * (axis.dot(q) * (1.0 - cosTheta) / axis.dot(axis));\n    }\n    return q;\n}\n\ninline Vector3d Travel(Vector3d p, const Vector3d &dir, double &len, int &f, VectorXi &E2E,\n                       MatrixXd &V, MatrixXi &F, MatrixXd &NF,\n                       std::vector<MatrixXd> &triangle_space, double *tx = 0, double *ty = 0) {\n    Vector3d N = NF.col(f);\n    Vector3d pt = (dir - dir.dot(N) * N).normalized();\n    int prev_id = -1;\n    int count = 0;\n    while (len > 0) {\n        count += 1;\n        Vector3d t1 = V.col(F(1, f)) - V.col(F(0, f));\n        Vector3d t2 = V.col(F(2, f)) - V.col(F(0, f));\n        Vector3d N = NF.col(f);\n        //\t\tprintf(\"point dis: %f\\n\", (p - V.col(F(1, f))).dot(N));\n        int edge_id = f * 3;\n        double max_len = 1e30;\n        bool found = false;\n        int next_id, next_f;\n        Vector3d next_q;\n        Matrix3d m, n;\n        m.col(0) = t1;\n        m.col(1) = t2;\n        m.col(2) = N;\n        n = m.inverse();\n        MatrixXd &T = triangle_space[f];\n        VectorXd coord = T * Vector3d(p - V.col(F(0, f)));\n        VectorXd dirs = (T * pt);\n\n        double lens[3];\n        lens[0] = -coord.y() / dirs.y();\n        lens[1] = (1 - coord.x() - coord.y()) / (dirs.x() + dirs.y());\n        lens[2] = -coord.x() / dirs.x();\n        for (int fid = 0; fid < 3; ++fid) {\n            if (fid + edge_id == prev_id) continue;\n\n            if (lens[fid] >= 0 && lens[fid] < max_len) {\n                max_len = lens[fid];\n                next_id = E2E[edge_id + fid];\n                next_f = next_id;\n                if (next_f != -1) next_f /= 3;\n                found = true;\n            }\n        }\n        if (!found) {\n            printf(\"error...\\n\");\n            exit(0);\n        }\n        //\t\tprintf(\"status: %f %f %d\\n\", len, max_len, f);\n        if (max_len >= len) {\n            if (tx && ty) {\n                *tx = coord.x() + dirs.x() * len;\n                *ty = coord.y() + dirs.y() * len;\n            }\n            p = p + len * pt;\n            len = 0;\n            return p;\n        }\n        p = V.col(F(0, f)) + t1 * (coord.x() + dirs.x() * max_len) +\n            t2 * (coord.y() + dirs.y() * max_len);\n        len -= max_len;\n        if (next_f == -1) {\n            if (tx && ty) {\n                *tx = coord.x() + dirs.x() * max_len;\n                *ty = coord.y() + dirs.y() * max_len;\n            }\n            return p;\n        }\n        pt = rotate_vector_into_plane(pt, NF.col(f), NF.col(next_f));\n        f = next_f;\n        prev_id = next_id;\n    }\n    return p;\n}\ninline Vector3d TravelField(Vector3d p, Vector3d &pt, double &len, int &f, VectorXi &E2E,\n                            MatrixXd &V, MatrixXi &F, MatrixXd &NF, MatrixXd &QF, MatrixXd &QV,\n                            MatrixXd &NV, std::vector<MatrixXd> &triangle_space, double *tx = 0,\n                            double *ty = 0, Vector3d *dir_unfold = 0) {\n    Vector3d N = NF.col(f);\n    pt = (pt - pt.dot(N) * N).normalized();\n    int prev_id = -1;\n    int count = 0;\n    std::vector<Vector3d> Ns;\n\n    auto FaceQFromVertices = [&](int f, double tx, double ty) {\n        const Vector3d &n = NF.col(f);\n        const Vector3d &q_1 = QV.col(F(0, f)), &q_2 = QV.col(F(1, f)), &q_3 = QV.col(F(2, f));\n        const Vector3d &n_1 = NV.col(F(0, f)), &n_2 = NV.col(F(1, f)), &n_3 = NV.col(F(2, f));\n        Vector3d q_1n = rotate_vector_into_plane(q_1, n_1, n);\n        Vector3d q_2n = rotate_vector_into_plane(q_2, n_2, n);\n        Vector3d q_3n = rotate_vector_into_plane(q_3, n_3, n);\n        auto orient = compat_orientation_extrinsic_4(q_1n, n, q_2n, n);\n        Vector3d q = (orient.first * tx + orient.second * ty).normalized();\n        orient = compat_orientation_extrinsic_4(q, n, q_3n, n);\n        q = (orient.first * (tx + ty) + orient.second * (1 - tx - ty)).normalized();\n        return q;\n    };\n\n    auto BestQFromGivenQ = [&](const Vector3d &n, const Vector3d &q, const Vector3d &given_q) {\n        Vector3d q_1 = n.cross(q);\n        double t1 = q.dot(given_q);\n        double t2 = q_1.dot(given_q);\n        if (fabs(t1) > fabs(t2)) {\n            if (t1 > 0.0)\n                return Vector3d(q);\n            else\n                return Vector3d(-q);\n        } else {\n            if (t2 > 0.0)\n                return Vector3d(q_1);\n            else\n                return Vector3d(-q_1);\n        }\n    };\n\n    while (len > 0) {\n        count += 1;\n        Vector3d t1 = V.col(F(1, f)) - V.col(F(0, f));\n        Vector3d t2 = V.col(F(2, f)) - V.col(F(0, f));\n        Vector3d N = NF.col(f);\n        Ns.push_back(N);\n        //\t\tprintf(\"point dis: %f\\n\", (p - V.col(F(1, f))).dot(N));\n        int edge_id = f * 3;\n        double max_len = 1e30;\n        bool found = false;\n        int next_id, next_f;\n        Vector3d next_q;\n        Matrix3d m, n;\n        m.col(0) = t1;\n        m.col(1) = t2;\n        m.col(2) = N;\n        n = m.inverse();\n        MatrixXd &T = triangle_space[f];\n        VectorXd coord = T * Vector3d(p - V.col(F(0, f)));\n        VectorXd dirs = (T * pt);\n        double lens[3];\n        lens[0] = -coord.y() / dirs.y();\n        lens[1] = (1 - coord.x() - coord.y()) / (dirs.x() + dirs.y());\n        lens[2] = -coord.x() / dirs.x();\n        for (int fid = 0; fid < 3; ++fid) {\n            if (fid + edge_id == prev_id) continue;\n\n            if (lens[fid] >= 0 && lens[fid] < max_len) {\n                max_len = lens[fid];\n                next_id = E2E[edge_id + fid];\n                next_f = next_id;\n                if (next_f != -1) next_f /= 3;\n                found = true;\n            }\n        }\n        double w1 = (coord.x() + dirs.x() * max_len);\n        double w2 = (coord.y() + dirs.y() * max_len);\n        if (w1 < 0) w1 = 0.0f;\n        if (w2 < 0) w2 = 0.0f;\n        if (w1 + w2 > 1) {\n            double w = w1 + w2;\n            w1 /= w;\n            w2 /= w;\n        }\n\n        if (!found) {\n            printf(\"error...\\n\");\n            exit(0);\n        }\n        //\t\tprintf(\"status: %f %f %d\\n\", len, max_len, f);\n        if (max_len >= len) {\n            if (tx && ty) {\n                *tx = w1;\n                *ty = w2;\n            }\n            Vector3d ideal_q = FaceQFromVertices(f, *tx, *ty);\n            *dir_unfold = BestQFromGivenQ(NF.col(f), ideal_q, *dir_unfold);\n            for (int i = Ns.size() - 1; i > 0; --i) {\n                *dir_unfold = rotate_vector_into_plane(*dir_unfold, Ns[i], Ns[i - 1]);\n            }\n            p = p + len * pt;\n            len = 0;\n            return p;\n        }\n        p = V.col(F(0, f)) + t1 * w1 + t2 * w2;\n        len -= max_len;\n        if (next_f == -1) {\n            if (tx && ty) {\n                *tx = w1;\n                *ty = w2;\n            }\n            Vector3d ideal_q = FaceQFromVertices(f, *tx, *ty);\n            *dir_unfold = BestQFromGivenQ(NF.col(f), ideal_q, *dir_unfold);\n            for (int i = Ns.size() - 1; i > 0; --i) {\n                *dir_unfold = rotate_vector_into_plane(*dir_unfold, Ns[i], Ns[i - 1]);\n            }\n            return p;\n        }\n        pt = rotate_vector_into_plane(pt, NF.col(f), NF.col(next_f));\n        //\t\tpt = BestQFromGivenQ(NF.col(next_f), QF.col(next_f), pt);\n        if (dir_unfold) {\n            *dir_unfold = BestQFromGivenQ(NF.col(next_f), QF.col(next_f), *dir_unfold);\n        }\n        f = next_f;\n        prev_id = next_id;\n    }\n\n    return p;\n}\n\n#endif\n", "meta": {"hexsha": "ba36e1de8fb8c275828dc43daae0b7b663c99c4b", "size": 17608, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "data/QuadriFlow/src/field-math.hpp", "max_stars_repo_name": "hjwdzh/TextureNet", "max_stars_repo_head_hexsha": "f3515537909ffb4ab04694b91109b535bb5c85d5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 89.0, "max_stars_repo_stars_event_min_datetime": "2019-03-30T03:59:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-25T05:16:51.000Z", "max_issues_repo_path": "data/QuadriFlow/src/field-math.hpp", "max_issues_repo_name": "jtpils/TextureNet", "max_issues_repo_head_hexsha": "f3515537909ffb4ab04694b91109b535bb5c85d5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-06-29T11:21:11.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-12T04:09:41.000Z", "max_forks_repo_path": "data/QuadriFlow/src/field-math.hpp", "max_forks_repo_name": "jtpils/TextureNet", "max_forks_repo_head_hexsha": "f3515537909ffb4ab04694b91109b535bb5c85d5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2019-04-12T01:20:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-12T16:10:33.000Z", "avg_line_length": 36.9140461216, "max_line_length": 99, "alphanum_fraction": 0.4959109496, "num_tokens": 5639, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879312056025699, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4640041227721473}}
{"text": "#define BOOST_TEST_MODULE LFPTest\n#define BOOST_TEST_MAIN\n\n#include <iostream>\n\n#include <boost/test/unit_test.hpp>\n\n#include \"coreneuron/io/lfp.hpp\"\n#include \"coreneuron/mpi/nrnmpi.h\"\n\nusing namespace coreneuron;\nusing namespace coreneuron::lfputils;\n\ntemplate <typename F>\ndouble integral(F f, double a, double b, int n) {\n    double step = (b - a) / n;  // width of each small rectangle\n    double area = 0.0;          // signed area\n    for (int i = 0; i < n; i++) {\n        area += f(a + (i + 0.5) * step) * step;  // sum up each small rectangle\n    }\n    return area;\n}\n\n\nBOOST_AUTO_TEST_CASE(LFP_PointSource_LineSource) {\n#if NRNMPI\n    nrnmpi_init(nullptr, nullptr);\n#endif\n    double segment_length{1.0e-6};\n    double segment_start_val{1.0e-6};\n    std::array<double, 3> segment_start = std::array<double, 3>{0.0, 0.0, segment_start_val};\n    std::array<double, 3> segment_end =\n        paxpy(segment_start, 1.0, std::array<double, 3>{0.0, 0.0, segment_length});\n    double floor{1.0e-6};\n    pi = 3.141592653589;\n\n    std::array<double, 10> vals;\n    double circling_radius{1.0e-6};\n    std::array<double, 3> segment_middle{0.0, 0.0, 1.5e-6};\n    double medium_resistivity_fac{1.0};\n    for (auto k = 0; k < 10; k++) {\n        std::array<double, 3> approaching_elec =\n            paxpy(segment_middle, 1.0, std::array<double, 3>{0.0, 1.0e-5 - k * 1.0e-6, 0.0});\n        std::array<double, 3> circling_elec =\n            paxpy(segment_middle,\n                  1.0,\n                  std::array<double, 3>{0.0,\n                                        circling_radius * std::cos(2.0 * pi * k / 10),\n                                        circling_radius * std::sin(2.0 * pi * k / 10)});\n\n        double analytic_approaching_lfp = line_source_lfp_factor(\n            approaching_elec, segment_start, segment_end, floor, medium_resistivity_fac);\n        double analytic_circling_lfp = line_source_lfp_factor(\n            circling_elec, segment_start, segment_end, floor, medium_resistivity_fac);\n        double numeric_circling_lfp = integral(\n            [&](double x) {\n                return 1.0 / std::max(floor,\n                                      norm(paxpy(circling_elec,\n                                                 -1.0,\n                                                 paxpy(segment_end,\n                                                       x,\n                                                       paxpy(segment_start, -1.0, segment_end)))));\n            },\n            0.0,\n            1.0,\n            10000);\n        // TEST of analytic vs numerical integration\n        std::clog << \"ANALYTIC line source \" << analytic_circling_lfp\n                  << \" vs NUMERIC line source LFP \" << numeric_circling_lfp << \"\\n\";\n        BOOST_REQUIRE_CLOSE(analytic_circling_lfp, numeric_circling_lfp, 1.0e-6);\n        // TEST of LFP Flooring\n        BOOST_REQUIRE((approaching_elec[1] < 0.866e-6) ? analytic_approaching_lfp == 1.0e6 : true);\n        vals[k] = analytic_circling_lfp;\n    }\n    // TEST of SYMMETRY of LFP FORMULA\n    for (size_t k = 0; k < 5; k++) {\n        BOOST_REQUIRE(std::abs((vals[k] - vals[k + 5]) /\n                               std::max(std::abs(vals[k]), std::abs(vals[k + 5]))) < 1.0e-12);\n    }\n    std::vector<std::array<double, 3>> segments_starts = {{0., 0., 1.},\n                                                          {0., 0., 0.5},\n                                                          {0.0, 0.0, 0.0},\n                                                          {0.0, 0.0, -0.5}};\n    std::vector<std::array<double, 3>> segments_ends = {{0., 0., 0.},\n                                                        {0., 0., 1.},\n                                                        {0., 0., 0.5},\n                                                        {0.0, 0.0, 0.0}};\n    std::vector<double> radii{0.1, 0.1, 0.1, 0.1};\n    std::vector<std::array<double, 3>> electrodes = {{0.0, 0.3, 0.0}, {0.0, 0.7, 0.8}};\n    std::vector<int> indices = {0, 1, 2, 3};\n    LFPCalculator<LineSource> lfp(segments_starts, segments_ends, radii, indices, electrodes, 1.0);\n    lfp.template lfp<std::vector<double>>({0.0, 1.0, 2.0, 3.0});\n    std::vector<double> res_line_source = lfp.lfp_values();\n    LFPCalculator<PointSource> lfpp(\n        segments_starts, segments_ends, radii, indices, electrodes, 1.0);\n    lfpp.template lfp<std::vector<double>>({0.0, 1.0, 2.0, 3.0});\n    std::vector<double> res_point_source = lfpp.lfp_values();\n    BOOST_REQUIRE_CLOSE(res_line_source[0], res_point_source[0], 1.0);\n    BOOST_REQUIRE_CLOSE(res_line_source[1], res_point_source[1], 1.0);\n#if NRNMPI\n    nrnmpi_finalize();\n#endif\n}\n", "meta": {"hexsha": "b65a378a04cbb111b6e68c0d70fb68a28571ad14", "size": 4657, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/unit/lfp/lfp.cpp", "max_stars_repo_name": "alexsavulescu/CoreNeuron", "max_stars_repo_head_hexsha": "af7e95d98819c052b07656961d20de6a71b70740", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 109.0, "max_stars_repo_stars_event_min_datetime": "2016-04-08T09:27:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T02:10:47.000Z", "max_issues_repo_path": "tests/unit/lfp/lfp.cpp", "max_issues_repo_name": "alexsavulescu/CoreNeuron", "max_issues_repo_head_hexsha": "af7e95d98819c052b07656961d20de6a71b70740", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 595.0, "max_issues_repo_issues_event_min_datetime": "2016-04-01T09:12:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T23:44:58.000Z", "max_forks_repo_path": "tests/unit/lfp/lfp.cpp", "max_forks_repo_name": "alexsavulescu/CoreNeuron", "max_forks_repo_head_hexsha": "af7e95d98819c052b07656961d20de6a71b70740", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 52.0, "max_forks_repo_forks_event_min_datetime": "2016-03-29T08:11:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T07:37:38.000Z", "avg_line_length": 44.7788461538, "max_line_length": 99, "alphanum_fraction": 0.5263044879, "num_tokens": 1355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.46400411690700283}}
{"text": "// Build with:\n// emcc --bind -I${EMSCRIPTEN}/system/include -I${QUANTLIB} -I${BOOST} -O3 -s MODULARIZE=1 -s \"EXTRA_EXPORTED_RUNTIME_METHODS=['addOnPostRun']\" -s EXPORT_NAME=QuantLib -s TOTAL_MEMORY=64MB -o quantlib-embind.js quantlib-embind.cpp ${QUANTLIB}/ql/.libs/libQuantLib.a\n\n// https://www.quantlib.org/slides/dima-ql-intro-1.pdf\n\n#include <math.h>\n#include <iostream>\n#include <malloc.h>\n#include <ql/quantlib.hpp>\n#include <emscripten/bind.h>\n#include <boost/foreach.hpp>\n\nusing namespace std;\nusing namespace QuantLib;\nusing namespace emscripten;\n\nnamespace\n{\n\n    val emval_test_mallinfo()\n    {\n        const auto &i = mallinfo();\n        unsigned long t =\n            std::chrono::system_clock::now().time_since_epoch() /\n            std::chrono::milliseconds(1);\n        val rv(val::object());\n        rv.set(\"arena\", val(i.arena));\n        rv.set(\"ordblks\", val(i.ordblks));\n        rv.set(\"smblks\", val(i.smblks));\n        rv.set(\"hblks\", val(i.hblks));\n        rv.set(\"hblkhd\", val(i.hblkhd));\n        rv.set(\"usmblks\", val(i.usmblks));\n        rv.set(\"fsmblks\", val(i.fsmblks));\n        rv.set(\"uordblks\", val(i.uordblks));\n        rv.set(\"fordblks\", val(i.fordblks));\n        rv.set(\"keepcost\", val(i.keepcost));\n        rv.set(\"time\", val(t));\n        return rv;\n    }\n\n    void setValuationDate(Date &date)\n    {\n        Settings::instance().evaluationDate() = date;\n    }\n\n    string timeUnitToString(Period &p)\n    {\n        stringstream stream;\n        stream << p;\n        return stream.str();\n    }\n\n    double swapNpv(VanillaSwap &swap)\n    {\n        return swap.NPV();\n    }\n\n    string calendarToISOString(Date &d)\n    {\n        stringstream stream;\n        stream << d.year() << \"-\" << setfill('0') << setw(2) << (int)d.month() << \"-\" << setfill('0') << setw(2) << d.dayOfMonth();\n        return stream.str();\n    }\n\n    string calendarToString(Date &d)\n    {\n        stringstream stream;\n        stream << d;\n        return stream.str();\n    }\n\n    string interestRateToString(InterestRate &r)\n    {\n        stringstream stream;\n        stream.precision(4);\n        stream << r;\n        return stream.str();\n    }\n\n    Date calendarAdvance(Calendar &cal, Date &d, Integer n, TimeUnit unit, BusinessDayConvention c, bool endOfMonth)\n    {\n        return cal.advance(d, n, unit, c, endOfMonth);\n    }\n\n    Date *dateFromISOString(string s)\n    {\n        int y, m, d;\n        sscanf(s.c_str(), \"%d-%d-%d\", &y, &m, &d);\n        return new Date(d, (Month)m, y);\n    }\n\n    void swapSetPricingEngine(VanillaSwap &swap, Handle<YieldTermStructure> &discountingTermStructure)\n    {\n        boost::shared_ptr<PricingEngine> swapEngine(new DiscountingSwapEngine(discountingTermStructure));\n        swap.setPricingEngine(swapEngine);\n    }\n\n    Handle<YieldTermStructure> *createLogLinearYieldTermStructure(vector<Date> &dates, vector<DiscountFactor> &discountFactor, DayCounter &dayCounter)\n    {\n        // auto curve = new InterpolatedDiscountCurve<LogLinear>(dates, discountFactor, dayCounter);\n        // InterpolatedDiscountCurve<LogLinear> curve(InterpolatedDiscountCurve<LogLinear>(dates, discountFactor, dayCounter));\n        // auto yts = boost::make_shared<InterpolatedDiscountCurve<LogLinear>>(*curve);\n        boost::shared_ptr<YieldTermStructure> yts(new InterpolatedDiscountCurve<LogLinear>(dates, discountFactor, dayCounter));\n        return new Handle<YieldTermStructure>(yts);\n    }\n\n    VanillaSwap *createVanillaSwap(VanillaSwap::Type type, Real nominal, const Schedule &fixedSchedule, Rate fixedRate, DayCounter &fixedDayCount,\n                                   const Schedule &floatSchedule, IborIndex &iborIndex, Spread spread, DayCounter &floatingDayCount)\n    {\n        boost::shared_ptr<IborIndex> iborIndexPtr = boost::make_shared<IborIndex>(iborIndex);\n        VanillaSwap *res = new VanillaSwap(type, nominal, fixedSchedule, fixedRate, fixedDayCount, floatSchedule, iborIndexPtr, spread, floatingDayCount);\n        return res;\n    }\n\n    Handle<Quote> *createQuoteHandle(Rate rate)\n    {\n        boost::shared_ptr<SimpleQuote> ptrSimpleQuote = boost::make_shared<SimpleQuote>(rate);\n        boost::shared_ptr<Quote> ptrQuote(ptrSimpleQuote);\n        return new Handle<Quote>(ptrQuote);\n    }\n\n    Real handleQuoteValue(Handle<Quote> &quote)\n    {\n        return ((ext::shared_ptr<Quote> &)quote.currentLink())->value();\n    }\n\n    OISRateHelper *createOISRateHelper(Natural settlementDays, Period &tenor, Handle<Quote> &fixedRate, OvernightIndex &overnightIndex\n                                       /*, Handle<YieldTermStructure> &discountingCurve, bool telescopicValueDates, Natural paymentLag,\n                                   BusinessDayConvention paymentConvention, Frequency paymentFrequency, Calendar &paymentCalendar, Period &forwardStart,\n                                   Spread overnightSpread */\n    )\n    {\n        ext::shared_ptr<OvernightIndex> ptrOvernightIndex(&overnightIndex);\n        return new OISRateHelper(settlementDays, tenor, fixedRate, ptrOvernightIndex /*, discountingCurve,\n                                  telescopicValueDates, paymentLag, paymentConvention, paymentFrequency, paymentCalendar, forwardStart, overnightSpread*/\n        );\n    }\n\n    DatedOISRateHelper *createDatedOISRateHelper(Date &startDate, Date &endDate, Handle<Quote> &fixedRate, OvernightIndex &overnightIndex)\n    {\n        ext::shared_ptr<OvernightIndex> ptrOvernightIndex(&overnightIndex);\n        return new DatedOISRateHelper(startDate, endDate, fixedRate, ptrOvernightIndex);\n    }\n\n    FuturesRateHelper *createFuturesRateHelper(Handle<Quote> &price, Date &iborStartDate, Natural lengthInMonths, Calendar &calendar, BusinessDayConvention convention, bool endOfMonth, DayCounter &dayCounter)\n    {\n        return new FuturesRateHelper(price, iborStartDate, lengthInMonths, calendar, convention, endOfMonth, dayCounter);\n    }\n\n    SwapRateHelper *createSwapRateHelper(Handle<Quote> &rate, Period &tenor, Calendar &calendar, Frequency fixedFrequency,\n                                         BusinessDayConvention fixedConvention, DayCounter &fixedDayCount, IborIndex &iborIndex)\n    {\n        boost::shared_ptr<IborIndex> ptrIborIndex = boost::make_shared<IborIndex>(iborIndex);\n        // ext::shared_ptr<IborIndex> ptrIborIndex(&iborIndex);\n        return new SwapRateHelper(rate, tenor, calendar, fixedFrequency, fixedConvention, fixedDayCount, ptrIborIndex);\n    }\n\n    Date *immNextDate(const Date &date, bool mainCycle)\n    {\n        return new Date(IMM::nextDate(date, mainCycle).serialNumber());\n    }\n\n    PiecewiseYieldCurve<Discount, Linear> *createPiecewiseYieldCurveDiscountLinear(Date &referenceDate, vector<RateHelper *> &instruments, DayCounter &dayCounter)\n    {\n        vector<boost::shared_ptr<RateHelper>> ptrs;\n        for (int i = 0; i < instruments.size(); i++)\n        {\n            // boost::shared_ptr<RateHelper> ptr = boost::make_shared<RateHelper>(instruments[i]);\n            // ext::shared_ptr<RateHelper> ptr(&instruments[i]);\n            boost::shared_ptr<RateHelper> ptr(instruments[i]);\n            ptrs.push_back(ptr);\n        }\n        return new PiecewiseYieldCurve<Discount, Linear>(referenceDate, ptrs, dayCounter);\n    }\n\n    void handle_eptr(std::exception_ptr eptr) // passing by value is ok\n    {\n        try\n        {\n            if (eptr)\n            {\n                std::rethrow_exception(eptr);\n            }\n        }\n        catch (const std::exception &e)\n        {\n            std::cout << \"Caught exception \\\"\" << e.what() << \"\\\"\\n\";\n        }\n    }\n\n    InterestRate *yieldTermStructureZeroRate(YieldTermStructure &yieldTermStructure, Date &d, DayCounter &resultDayCounter, Compounding comp, Frequency freq, bool extrapolate)\n    {\n        // try\n        // {\n        // std::cout << \"Uno\" << std::endl;\n        // auto dates = yieldTermStructure.jumpDates();\n        // std::cout << \"Due\" << std::endl;\n        // for (int i=0; i<dates.size(); i++)\n        // {\n        //     std::cout << dates[i] << std::endl;\n        // }\n        // std::cout << \"Tre\" << std::endl;\n        auto r = yieldTermStructure.zeroRate(d, resultDayCounter, comp, freq, extrapolate);\n        // std::cout << \"Quattro\" << std::endl;\n        return new InterestRate(r.rate(), r.dayCounter(), r.compounding(), r.frequency()); // Copies from stack to heap memory\n        // }\n        // catch (...)\n        // {\n        //     std::exception_ptr eptr = std::current_exception();\n        //     handle_eptr(eptr);\n        //     // std::cout << eptr->what() << std::endl;\n        // }\n        // return NULL;\n    }\n\n    DiscountFactor yieldTermStructureDiscount(YieldTermStructure &yieldTermStructure, Date &d, bool extrapolate)\n    {\n        return yieldTermStructure.discount(d, extrapolate);\n    }\n\n    InterestRate *yieldTermStructureForwardRate(YieldTermStructure &yieldTermStructure, Date &d1, Date &d2,\n                                                DayCounter &resultDayCounter, Compounding comp, Frequency freq, bool extrapolate)\n    {\n        auto r = yieldTermStructure.forwardRate(d1, d2, resultDayCounter, comp, freq, extrapolate);\n        return new InterestRate(r.rate(), r.dayCounter(), r.compounding(), r.frequency()); // Copies from stack to heap memory\n    }\n\n    EMSCRIPTEN_BINDINGS(quantlib)\n    {\n        emscripten::constant<string>(\"version\", QL_VERSION);\n        enum_<BusinessDayConvention>(\"BusinessDayConvention\")\n            .value(\"Following\", Following)\n            .value(\"ModifiedFollowing\", ModifiedFollowing)\n            .value(\"Preceding\", Preceding)\n            .value(\"ModifiedPreceding\", ModifiedPreceding)\n            .value(\"Unadjusted\", Unadjusted)\n            .value(\"HalfMonthModifiedFollowing\", HalfMonthModifiedFollowing)\n            .value(\"Nearest\", Nearest);\n        enum_<Month>(\"Month\")\n            .value(\"January\", January)\n            .value(\"February\", February)\n            .value(\"March\", March)\n            .value(\"April\", April)\n            .value(\"May\", May)\n            .value(\"June\", June)\n            .value(\"July\", July)\n            .value(\"August\", August)\n            .value(\"September\", September)\n            .value(\"October\", October)\n            .value(\"November\", November)\n            .value(\"December\", December)\n            .value(\"Jan\", Jan)\n            .value(\"Feb\", Feb)\n            .value(\"Mar\", Mar)\n            .value(\"Apr\", Apr)\n            .value(\"May\", May)\n            .value(\"Jun\", Jun)\n            .value(\"Jul\", Jul)\n            .value(\"Aug\", Aug)\n            .value(\"Sep\", Sep)\n            .value(\"October\", Oct)\n            .value(\"Nov\", Nov)\n            .value(\"Dec\", Dec);\n        enum_<TimeUnit>(\"TimeUnit\")\n            .value(\"D\", Days)\n            .value(\"W\", Weeks)\n            .value(\"M\", Months)\n            .value(\"Y\", Years)\n            .value(\"Days\", Days)\n            .value(\"Weeks\", Weeks)\n            .value(\"Months\", Months)\n            .value(\"Years\", Years)\n            .value(\"Hours\", Hours)\n            .value(\"Minutes\", Minutes)\n            .value(\"Seconds\", Seconds)\n            .value(\"Milliseconds\", Milliseconds)\n            .value(\"Microseconds\", Microseconds);\n        enum_<DateGeneration::Rule>(\"DateGenerationRule\")\n            .value(\"Backward\", DateGeneration::Backward)\n            .value(\"Forward\", DateGeneration::Forward)\n            .value(\"Zero\", DateGeneration::Zero)\n            .value(\"ThirdWednesday\", DateGeneration::ThirdWednesday)\n            .value(\"Twentieth\", DateGeneration::Twentieth)\n            .value(\"TwentiethIMM\", DateGeneration::TwentiethIMM)\n            .value(\"OldCDS\", DateGeneration::OldCDS)\n            .value(\"CDS\", DateGeneration::CDS)\n            .value(\"CDS2015\", DateGeneration::CDS2015);\n        enum_<Thirty360::Convention>(\"Thirty360Convention\")\n            .value(\"USA\", Thirty360::USA)\n            .value(\"BondBasis\", Thirty360::BondBasis)\n            .value(\"European\", Thirty360::European)\n            .value(\"EurobondBasis\", Thirty360::EurobondBasis)\n            .value(\"Italian\", Thirty360::Italian)\n            .value(\"German\", Thirty360::German);\n        enum_<ActualActual::Convention>(\"ActualActualConvention\")\n            .value(\"ISMA\", ActualActual::ISMA)\n            .value(\"Bond\", ActualActual::Bond)\n            .value(\"ISDA\", ActualActual::ISDA)\n            .value(\"Historical\", ActualActual::Historical)\n            .value(\"Actual365\", ActualActual::Actual365)\n            .value(\"AFB\", ActualActual::AFB)\n            .value(\"Euro\", ActualActual::Euro);\n        enum_<VanillaSwap::Type>(\"VanillaSwapType\")\n            .value(\"Payer\", VanillaSwap::Payer)\n            .value(\"Receiver\", VanillaSwap::Receiver);\n        enum_<Weekday>(\"Weekday\")\n            .value(\"Sunday\", Sunday)\n            .value(\"Monday\", Monday)\n            .value(\"Tuesday\", Tuesday)\n            .value(\"Wednesday\", Wednesday)\n            .value(\"Thursday\", Thursday)\n            .value(\"Friday\", Friday)\n            .value(\"Saturday\", Saturday)\n            .value(\"Sun\", Sun)\n            .value(\"Mon\", Mon)\n            .value(\"Tue\", Tue)\n            .value(\"Wed\", Wed)\n            .value(\"Thu\", Thu)\n            .value(\"Fri\", Fri)\n            .value(\"Sat\", Sat);\n        enum_<Pillar::Choice>(\"PillarChoice\")\n            .value(\"MaturityDate\", Pillar::Choice::MaturityDate)\n            .value(\"LastRelevantDate\", Pillar::Choice::LastRelevantDate)\n            .value(\"CustomDate\", Pillar::Choice::CustomDate);\n        enum_<UnitedStates::Market>(\"UnitedStatesMarket\")\n            .value(\"Settlement\", UnitedStates::Market::Settlement)\n            .value(\"NYSE\", UnitedStates::Market::NYSE)\n            .value(\"GovernmentBond\", UnitedStates::Market::GovernmentBond)\n            .value(\"NERC\", UnitedStates::Market::NERC)\n            .value(\"LiborImpact\", UnitedStates::Market::LiborImpact)\n            .value(\"FederalReserve\", UnitedStates::Market::FederalReserve);\n        enum_<UnitedKingdom::Market>(\"UnitedKingdomMarket\")\n            .value(\"Settlement\", UnitedKingdom::Market::Settlement)\n            .value(\"Exchange\", UnitedKingdom::Market::Exchange)\n            .value(\"Metals\", UnitedKingdom::Market::Metals);\n        enum_<JointCalendarRule>(\"JointCalendarRule\")\n            .value(\"JoinHolidays\", JointCalendarRule::JoinHolidays)\n            .value(\"JoinBusinessDays\", JointCalendarRule::JoinBusinessDays);\n        enum_<Frequency>(\"Frequency\")\n            .value(\"NoFrequency\", NoFrequency)\n            .value(\"Once\", Once)\n            .value(\"Annual\", Annual)\n            .value(\"Semiannual\", Semiannual)\n            .value(\"EveryFourthMonth\", EveryFourthMonth)\n            .value(\"Quarterly\", Quarterly)\n            .value(\"Bimonthly\", Bimonthly)\n            .value(\"Monthly\", Monthly)\n            .value(\"EveryFourthWeek\", EveryFourthWeek)\n            .value(\"Biweekly\", Biweekly)\n            .value(\"Weekly\", Weekly)\n            .value(\"Daily\", Daily)\n            .value(\"OtherFrequency\", OtherFrequency);\n        enum_<Compounding>(\"Compounding\")\n            .value(\"Simple\", Simple)\n            .value(\"Compounded\", Compounded)\n            .value(\"Continuous\", Continuous)\n            .value(\"SimpleThenCompounded\", SimpleThenCompounded)\n            .value(\"CompoundedThenSimple\", CompoundedThenSimple);\n\n        register_vector<int>(\"Vector<int>\")\n            .constructor<int>();\n        register_vector<double>(\"Vector<double>\")\n            .constructor<int>();\n        register_vector<Date>(\"Vector<Date>\")\n            .constructor<int>();\n        register_vector<RateHelper *>(\"Vector<RateHelper>\")\n            .constructor<int>();\n\n        class_<Date>(\"Date\")\n            .constructor<>()\n            .constructor<int>()\n            .constructor<int, Month, int>()\n            .function(\"serialNumber\", &Date::serialNumber)\n            .function(\"weekday\", &Date::weekday)\n            .function(\"dayOfMonth\", &Date::dayOfMonth)\n            .function(\"dayOfYear\", &Date::dayOfYear)\n            .function(\"month\", &Date::month)\n            .function(\"year\", &Date::year)\n            .function(\"toISOString\", &calendarToISOString)\n            .function(\"toString\", &calendarToString)\n            .class_function(\"fromISOString\", &dateFromISOString, allow_raw_pointers())\n            .class_function(\"isLeap\", &Date::isLeap);\n        class_<Schedule>(\"Schedule\")\n            .constructor<vector<Date>>()\n            .constructor<Date, Date, Period, Calendar, BusinessDayConvention, BusinessDayConvention, DateGeneration::Rule, bool, Date, Date>()\n            .function(\"size\", &Schedule::size)\n            .function(\"dates\", &Schedule::dates);\n\n        /* Calendars */\n        class_<Calendar>(\"Calendar\")\n            .function(\"name\", &Calendar::name)\n            .function(\"toString\", &calendarToString)\n            .function(\"isBusinessDay\", &Calendar::isBusinessDay)\n            .function(\"adjust\", &Calendar::adjust)\n            // .function<Calendar, Date, Integer, TimeUnit>(\"advance\", &Calendar::advance)\n            .function(\"advance\", &calendarAdvance);\n        class_<JointCalendar, base<Calendar>>(\"JointCalendar\")\n            .constructor<Calendar, Calendar, JointCalendarRule>()\n            .constructor<Calendar, Calendar, Calendar, JointCalendarRule>()\n            .constructor<Calendar, Calendar, Calendar, Calendar, JointCalendarRule>();\n        class_<TARGET, base<Calendar>>(\"TARGET\").constructor<>();\n        class_<NullCalendar, base<Calendar>>(\"NullCalendar\").constructor<>();\n        class_<UnitedKingdom, base<Calendar>>(\"UnitedKingdom\").constructor<UnitedKingdom::Market>();\n        class_<UnitedStates, base<Calendar>>(\"UnitedStates\").constructor().constructor<UnitedStates::Market>();\n        class_<Sweden, base<Calendar>>(\"Sweden\").constructor<>();\n\n        /* Period */\n        class_<Period>(\"Period\")\n            .constructor<int, TimeUnit>()\n            .function(\"toString\", &timeUnitToString);\n\n        /* DayCounters */\n        class_<DayCounter>(\"DayCounter\")\n            .function(\"name\", &DayCounter::name)\n            .function(\"dayCount\", &DayCounter::dayCount)\n            .function(\"yearFraction\", &DayCounter::yearFraction);\n        class_<Thirty360, base<DayCounter>>(\"Thirty360\")\n            .constructor<>()\n            .constructor<Thirty360::Convention, bool>();\n        class_<Actual360, base<DayCounter>>(\"Actual360\")\n            .constructor<>()\n            .constructor<bool>();\n        class_<Actual365Fixed, base<DayCounter>>(\"Actual365Fixed\").constructor<>();\n        class_<ActualActual, base<DayCounter>>(\"ActualActual\")\n            .constructor<>()\n            .constructor<ActualActual::Convention, Schedule>();\n        class_<Business252, base<DayCounter>>(\"Business252\").constructor<>();\n        class_<boost::optional<BusinessDayConvention>>(\"OptionalBusinessDayConvention\");\n\n        /* Misc */\n        class_<VanillaSwap>(\"VanillaSwap\")\n            .constructor(&createVanillaSwap, allow_raw_pointers())\n            // .constructor<VanillaSwap::Type, Rate, Schedule, Rate, DayCounter, Schedule, ext::shared_ptr<IborIndex>, Spread, DayCounter, boost::optional<BusinessDayConvention>>()\n            .class_function(\"create\", &createVanillaSwap, allow_raw_pointers())\n            .function(\"setPricingEngine\", &swapSetPricingEngine)\n            .function(\"NPV\", &swapNpv);\n        class_<Handle<YieldTermStructure>>(\"Handle<YieldTermStructure>\");\n        emscripten::function(\"createVanillaSwap\", &createVanillaSwap, allow_raw_pointers());\n        emscripten::function(\"mallinfo\", &emval_test_mallinfo);\n        emscripten::function(\"setValuationDate\", &setValuationDate);\n        emscripten::function(\"createLogLinearYieldTermStructure\", &createLogLinearYieldTermStructure, allow_raw_pointers());\n        class_<InterestRate>(\"InterestRate\")\n            .function(\"rate\", &InterestRate::rate)\n            .function(\"toString\", &interestRateToString);\n\n        class_<Quote>(\"Quote\");\n        class_<SimpleQuote, base<Quote>>(\"SimpleQuote\")\n            .constructor<Real>();\n        class_<Handle<Quote>>(\"QuoteHandle\")\n            .constructor(&createQuoteHandle, allow_raw_pointers())\n            .function(\"value\", &handleQuoteValue);\n        class_<IMM>(\"IMM\")\n            .class_function(\"nextDate\", &immNextDate, allow_raw_pointers());\n\n        /* Indicies */\n        class_<Index>(\"Index\")\n            .function(\"addFixing\", &Index::addFixing);\n        class_<InterestRateIndex, base<Index>>(\"InterestRateIndex\")\n            .function(\"fixingDate\", &InterestRateIndex::fixingDate);\n        class_<IborIndex, base<InterestRateIndex>>(\"IborIndex\");\n        class_<Euribor, base<IborIndex>>(\"Euribor\")\n            .constructor<Period, Handle<YieldTermStructure>>();\n        class_<OvernightIndex, base<IborIndex>>(\"OvernightIndex\");\n        class_<Eonia, base<OvernightIndex>>(\"Eonia\").constructor();\n        class_<Libor, base<IborIndex>>(\"Libor\");\n        class_<USDLibor, base<Libor>>(\"USDLibor\")\n            .constructor<Period>()\n            .constructor<Period, Handle<YieldTermStructure>>();\n\n        /* Helpers */\n        class_<RateHelper>(\"RateHelper\")\n            .function(\"maturityDate\", &RateHelper::maturityDate)\n            .function(\"quote\", &RateHelper::quote);\n        class_<DepositRateHelper, base<RateHelper>>(\"DepositRateHelper\")\n            .constructor<Handle<Quote>, Period, Natural, Calendar, BusinessDayConvention, bool, DayCounter>();\n        class_<OISRateHelper, base<RateHelper>>(\"OISRateHelper\").constructor(&createOISRateHelper, allow_raw_pointers());\n        class_<DatedOISRateHelper, base<RateHelper>>(\"DatedOISRateHelper\").constructor(&createDatedOISRateHelper, allow_raw_pointers());\n        class_<FuturesRateHelper, base<RateHelper>>(\"FuturesRateHelper\").constructor(&createFuturesRateHelper, allow_raw_pointers());\n        class_<SwapRateHelper, base<RateHelper>>(\"SwapRateHelper\").constructor(&createSwapRateHelper, allow_raw_pointers());\n\n        class_<YieldTermStructure>(\"ZeroInflationTermStructure\")\n            .function(\"zeroRate\", &yieldTermStructureZeroRate, allow_raw_pointers())\n            .function(\"discount\", &yieldTermStructureDiscount)\n            .function(\"forwardRate\", &yieldTermStructureForwardRate, allow_raw_pointers());\n        class_<PiecewiseYieldCurve<Discount, Linear>, base<YieldTermStructure>>(\"PiecewiseYieldCurve<Discount,Linear>\")\n            .constructor(&createPiecewiseYieldCurveDiscountLinear, allow_raw_pointers());\n    }\n\n} // namespace\n\n// In [9]: eonia_curve_c = PiecewiseLogCubicDiscount(0, TARGET(),\n// helpers, Actual365Fixed())\n// eonia_curve_c.enableExtrapolation()\n", "meta": {"hexsha": "ab499519139e635884a63a591a3e188cf23e89af", "size": 22583, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "quantlib-embind.cpp", "max_stars_repo_name": "CaptorAB/quantlib-wasm", "max_stars_repo_head_hexsha": "30fd0831f19fea2cedc176649237ea2f78237354", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2019-08-05T09:29:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-03T15:17:33.000Z", "max_issues_repo_path": "quantlib-embind.cpp", "max_issues_repo_name": "CaptorAB/node-quantlib", "max_issues_repo_head_hexsha": "b341c89fba0e13a4db6545d8c4b42dfdfc2868db", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-09-10T08:15:45.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-10T14:41:53.000Z", "max_forks_repo_path": "quantlib-embind.cpp", "max_forks_repo_name": "CaptorAB/node-quantlib", "max_forks_repo_head_hexsha": "b341c89fba0e13a4db6545d8c4b42dfdfc2868db", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-14T20:37:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-18T16:45:21.000Z", "avg_line_length": 45.7145748988, "max_line_length": 265, "alphanum_fraction": 0.6199353496, "num_tokens": 5305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.46400411690700283}}
{"text": "//\n//  nDijkstra.hpp\n//  evoNik\n//\n//  Created by Nikhil Joshi on 4/28/12.\n//  Copyright (c) 2012 California Institute of Technology. All rights reserved.\n//\n\n#ifndef evoNik_nDijkstra_hpp\n#define evoNik_nDijkstra_hpp\n\n# include <cmath>\n#include <iostream>\n\n#include <boost/config.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n\n#include \"constants.hpp\"\n\nclass nDijkstra_map2d{\npublic:\n    std::map< std::pair< unsigned int, unsigned int > , int > sectorMap;\n    int add(unsigned int x, unsigned int y);\n    int get(unsigned int x, unsigned int y);\n    void clear(void)                           {  sectorMap.clear();  }\n};\n\nclass nDijkstra{\npublic:\n    nDijkstra_map2d sectorMap;\n    size_t height;\n    size_t width;\n    int old_goal_w;\n    int old_goal_h;\n    \n    \n    typedef boost::adjacency_list <boost::vecS, boost::vecS, boost::undirectedS, boost::no_property, boost::property <boost::edge_weight_t, double> > graph_t;\n    typedef boost::graph_traits < graph_t >::vertex_descriptor vertex_descriptor;\n    typedef boost::graph_traits < graph_t >::edge_descriptor edge_descriptor;\n    \n    graph_t test_graph;\n    \n    // constructor\n    nDijkstra(){\n        old_goal_w = old_goal_h = -1;\n    }\n\n    void buildGraph(const std::vector<std::vector<unsigned int> > & freeSpaceArray, \n                    bool diag);\n    void computeFitnessArray(std::vector<std::vector<double> > & fitnessArray,\n                             int goal_w,\n                             int goal_h, \n                             bool cache=true);\n    \n};\n\n#endif\n", "meta": {"hexsha": "1298235b383fb781ae508e3302104a1cff34ffb8", "size": 1634, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "evoNik/nDijkstra.hpp", "max_stars_repo_name": "nikhiljjoshi/evoNik", "max_stars_repo_head_hexsha": "b0be7202bbb07da75b0b6d686556e7464e176717", "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": "evoNik/nDijkstra.hpp", "max_issues_repo_name": "nikhiljjoshi/evoNik", "max_issues_repo_head_hexsha": "b0be7202bbb07da75b0b6d686556e7464e176717", "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": "evoNik/nDijkstra.hpp", "max_forks_repo_name": "nikhiljjoshi/evoNik", "max_forks_repo_head_hexsha": "b0be7202bbb07da75b0b6d686556e7464e176717", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.2333333333, "max_line_length": 158, "alphanum_fraction": 0.646878825, "num_tokens": 397, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4640041169070028}}
{"text": "#include \"ros/ros.h\"\n#include \"sensor_msgs/LaserScan.h\"\n#include \"sensor_msgs/PointCloud2.h\"\n#include <laser_geometry/laser_geometry.h>\n#include <message_filters/subscriber.h>\n#include <message_filters/synchronizer.h>\n#include <message_filters/sync_policies/approximate_time.h>\n#include <message_filters/time_synchronizer.h>\n#include <tf/transform_listener.h>\n#include <iostream>\n  \n#include <pcl/io/pcd_io.h>\n#include <pcl/io/ply_io.h>\n#include <pcl/point_cloud.h>\n#include <pcl/console/parse.h>\n#include <pcl/point_types.h>\n#include <pcl_conversions/pcl_conversions.h>\n#include <pcl/common/transforms.h>\t//\tpcl::transformPointCloud \u7528\u5230\u8fd9\u4e2a\u5934\u6587\u4ef6\n#include <pcl/visualization/pcl_visualizer.h>\n#include <Eigen/Eigen>\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#include <Eigen/Eigenvalues>\n\nlaser_geometry::LaserProjection projector_;\n\nsensor_msgs::PointCloud2 cloud;\nsensor_msgs::PointCloud2 cloud_2;\nsensor_msgs::PointCloud2 cloud_all;\nint statue=0;\n\n   Eigen::Matrix4f transform_1;\n   //Eigen::Matrix<float, 4, 4> matrix_44;\n  // \u5b9a\u4e49\u4e00\u4e2a\u65cb\u8f6c\u77e9\u9635 (\u89c1 https://en.wikipedia.org/wiki/Rotation_matrix)\n  float theta = 3.142; // \u5f27\u5ea6\u89d2\n\n  //transform_1 (0,1) = -sin(theta);\n  //transform_1 (1,0) = sin (theta);\n  //transform_1 (1,1) = cos (theta);\n      \t//(\u884c, \u5217)\n \n  // \u5728 X \u8f74\u4e0a\u5b9a\u4e49\u4e00\u4e2a 2.5 \u7c73\u7684\u5e73\u79fb.\n  //transform_1(0,3) = -0.240;\n\n  //transform_1(2,3) = -0.106;\n\n //Eigen::Affine3f transform= Eigen::Affine3f::Identity();\n //Eigen::Affine3f transform_2;\n\n\n\nvoid callback(const sensor_msgs::LaserScan::ConstPtr& scan_msg,const sensor_msgs::LaserScan::ConstPtr& scan_2_msg)\n{ \n        \n        transform_1 (0,0) = cos (theta);\n        transform_1 (0,1) = -sin(theta);\n        transform_1 (1,0) = sin (theta);\n        transform_1 (1,1) = cos (theta);\n        transform_1 (0,3) = -0.240;\n        transform_1 (2,3) = -0.106;\n\n        pcl::PointCloud<pcl::PointXYZI>::Ptr scan_pcl(new pcl::PointCloud<pcl::PointXYZI>());\n        pcl::PointCloud<pcl::PointXYZI>::Ptr scan_pcl_2(new pcl::PointCloud<pcl::PointXYZI>());\n        projector_.projectLaser(*scan_msg, cloud);\n        pcl::fromROSMsg(cloud, *scan_pcl);\n        //std::cout<<\"transfrom done\"<<std::endl;\n        projector_.projectLaser(*scan_2_msg, cloud_2);\n        pcl::fromROSMsg(cloud_2, *scan_pcl_2);\n        //matrix_44 << cos (theta),-sin(theta),0,-0.240,sin (theta),cos (theta),0,0,0,0,1,-0.106,0,0,0,1;\n        //transform.translation() << -0.240, 0.0, -0.106;\n        //transform.rotate (Eigen::AngleAxisf (3.142, Eigen::Vector3f::UnitZ()));\n\n        pcl::PointCloud<pcl::PointXYZI>::Ptr transformed_cloud (new pcl::PointCloud<pcl::PointXYZI> ());\n        pcl::transformPointCloud (*scan_pcl_2, *transformed_cloud, transform_1);\n        /*for(std::size_t i = 0; i < transformed_cloud->size(); ++i)\n        {\n          transformed_cloud->points[i].intensity = 64;\n        }\n        for(std::size_t i = 0; i < scan_pcl->size(); ++i)\n        {\n          transformed_cloud->points[i].intensity = 128;\n        }*/\n        pcl::PointCloud<pcl::PointXYZI>::Ptr scan_all_pcl(new pcl::PointCloud<pcl::PointXYZI>());\n        *scan_all_pcl =   *scan_pcl+*transformed_cloud;\n        pcl::toROSMsg(*scan_all_pcl, cloud_all);\n        //point_cloud_publisher_.publish(cloud_all);\n        //publishCloudI(&point_cloud_publisher_, *scan_all_pcl);\n        statue=1;\n        std::cout<<statue<<std::endl;\n\n\n        \n        \n        \n}\n\nint main(int argc, char **argv)\n{\n\n  ros::init(argc, argv, \"scan_all\");  \n  ros::NodeHandle n_;\n  \n  //ros::Publisher scan_all_pub = n.advertise<sensor_msgs::LaserScan>(\"scan_all\", 1000);\n  /*ros::Rate loop_rate(10);\n  ros::Subscriber sub = n.subscribe(\"scan\", 1000, Callback);\n  ros::Subscriber sub_2 = .subscribe(\"scan_2\", 1000, Callback);*/\n  ros::Publisher point_cloud_publisher_;\n  point_cloud_publisher_ = n_.advertise<sensor_msgs::PointCloud2> (\"/cloud\", 10000, false);\n  message_filters::Subscriber<sensor_msgs::LaserScan> scan_sub(n_, \"scan\", 1);\n  message_filters::Subscriber<sensor_msgs::LaserScan> scan_2_sub(n_, \"scan_2_filtered\", 1);\n  typedef message_filters::sync_policies::ApproximateTime<sensor_msgs::LaserScan, sensor_msgs::LaserScan> MySyncPolicy;\n  message_filters::Synchronizer<MySyncPolicy> sync(MySyncPolicy(10), scan_sub, scan_2_sub);\n  //message_filters::TimeSynchronizer<sensor_msgs::LaserScan, sensor_msgs::LaserScan> sync(scan_sub, scan_2_sub, 10);\n  //sync.registerCallback(boost::bind(&callback, _1, _2));\n  ros::Rate loop_rate(30);\n  //SubscribeAndPublish SAPObject;\n  while (ros::ok())\n  {\n    sync.registerCallback(boost::bind(&callback, _1, _2));\n    std::cout<<\"123\"<<std::endl;\n    point_cloud_publisher_.publish(cloud_all);    \n    ros::spinOnce();\n    loop_rate.sleep();\n }\n  //ros::spin();\n  return 0;\n}\n\n\n\n", "meta": {"hexsha": "fc052b381aa3e52e847c40850ba8e07e95918749", "size": 4704, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "scan_all/src/scan_all.cpp", "max_stars_repo_name": "npczs/scan_all", "max_stars_repo_head_hexsha": "204f48527ae7e5722dde69b1c1d36f69b053c268", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scan_all/src/scan_all.cpp", "max_issues_repo_name": "npczs/scan_all", "max_issues_repo_head_hexsha": "204f48527ae7e5722dde69b1c1d36f69b053c268", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scan_all/src/scan_all.cpp", "max_forks_repo_name": "npczs/scan_all", "max_forks_repo_head_hexsha": "204f48527ae7e5722dde69b1c1d36f69b053c268", "max_forks_repo_licenses": ["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.9083969466, "max_line_length": 119, "alphanum_fraction": 0.6777210884, "num_tokens": 1389, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311856832191, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4640041110418581}}
{"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#ifdef BOOST_QVM_TEST_SINGLE_HEADER\n#   include BOOST_QVM_TEST_SINGLE_HEADER\n#else\n#   include <boost/qvm/math.hpp>\n#endif\n\n#include <boost/core/lightweight_test.hpp>\n#include <stdlib.h>\n\nnamespace\n    {\n    template <class T>\n    void\n    test1( T (*f1)(T), T (*f2)(T) )\n        {\n        for( int i=0; i!=100; ++i )\n            {\n            T a = T(rand()) / T(RAND_MAX);\n            BOOST_TEST_EQ(f1(a), f2(a));\n            }\n        }\n    template <class T,class U>\n    void\n    test2( T (*f1)(T,U), T (*f2)(T,U) )\n        {\n        for( int i=0; i!=100; ++i )\n            {\n            T a = T(rand()) / T(RAND_MAX);\n            T b = T(rand()) / T(RAND_MAX);\n            BOOST_TEST_EQ(f1(a,b), f2(a,b));\n            }\n        }\n    }\n\nint\nmain()\n    {\n    test1<float>(&boost::qvm::acos<float>, &::acosf);\n    test1<float>(&boost::qvm::asin<float>, &::asinf);\n    test1<float>(&boost::qvm::atan<float>, &::atanf);\n    test2<float,float>(&boost::qvm::atan2<float>, &::atan2f);\n    test1<float>(&boost::qvm::cos<float>, &::cosf);\n    test1<float>(&boost::qvm::sin<float>, &::sinf);\n    test1<float>(&boost::qvm::tan<float>, &::tanf);\n    test1<float>(&boost::qvm::cosh<float>, &::coshf);\n    test1<float>(&boost::qvm::sinh<float>, &::sinhf);\n    test1<float>(&boost::qvm::tanh<float>, &::tanhf);\n    test1<float>(&boost::qvm::exp<float>, &::expf);\n    test1<float>(&boost::qvm::log<float>, &::logf);\n    test1<float>(&boost::qvm::log10<float>, &::log10f);\n    test2<float,float>(&boost::qvm::mod<float>, &::fmodf);\n    test2<float,float>(&boost::qvm::pow<float>, &::powf);\n    test1<float>(&boost::qvm::sqrt<float>, &::sqrtf);\n    test1<float>(&boost::qvm::ceil<float>, &::ceilf);\n    test1<float>(&boost::qvm::abs<float>, &::fabsf);\n    test1<float>(&boost::qvm::floor<float>, &::floorf);\n    test2<float, int>(&boost::qvm::ldexp<float>, &::ldexpf);\n\n    test1<double>(&boost::qvm::acos<double>, &::acos);\n    test1<double>(&boost::qvm::asin<double>, &::asin);\n    test1<double>(&boost::qvm::atan<double>, &::atan);\n    test2<double,double>(&boost::qvm::atan2<double>, &::atan2);\n    test1<double>(&boost::qvm::cos<double>, &::cos);\n    test1<double>(&boost::qvm::sin<double>, &::sin);\n    test1<double>(&boost::qvm::tan<double>, &::tan);\n    test1<double>(&boost::qvm::cosh<double>, &::cosh);\n    test1<double>(&boost::qvm::sinh<double>, &::sinh);\n    test1<double>(&boost::qvm::tanh<double>, &::tanh);\n    test1<double>(&boost::qvm::exp<double>, &::exp);\n    test1<double>(&boost::qvm::log<double>, &::log);\n    test1<double>(&boost::qvm::log10<double>, &::log10);\n    test2<double,double>(&boost::qvm::mod<double>, &::fmod);\n    test2<double,double>(&boost::qvm::pow<double>, &::pow);\n    test1<double>(&boost::qvm::sqrt<double>, &::sqrt);\n    test1<double>(&boost::qvm::ceil<double>, &::ceil);\n    test1<double>(&boost::qvm::abs<double>, &::fabs);\n    test1<double>(&boost::qvm::floor<double>, &::floor);\n    test2<double, int>(&boost::qvm::ldexp<double>, &::ldexp);\n\n    test1<long double>(&boost::qvm::acos<long double>, &::acosl);\n    test1<long double>(&boost::qvm::asin<long double>, &::asinl);\n    test1<long double>(&boost::qvm::atan<long double>, &::atanl);\n    test2<long double,long double>(&boost::qvm::atan2<long double>, &::atan2l);\n    test1<long double>(&boost::qvm::cos<long double>, &::cosl);\n    test1<long double>(&boost::qvm::sin<long double>, &::sinl);\n    test1<long double>(&boost::qvm::tan<long double>, &::tanl);\n    test1<long double>(&boost::qvm::cosh<long double>, &::coshl);\n    test1<long double>(&boost::qvm::sinh<long double>, &::sinhl);\n    test1<long double>(&boost::qvm::tanh<long double>, &::tanhl);\n    test1<long double>(&boost::qvm::exp<long double>, &::expl);\n    test1<long double>(&boost::qvm::log<long double>, &::logl);\n    test1<long double>(&boost::qvm::log10<long double>, &::log10l);\n    test2<long double,long double>(&boost::qvm::mod<long double>, &::fmodl);\n    test2<long double,long double>(&boost::qvm::pow<long double>, &::powl);\n    test1<long double>(&boost::qvm::sqrt<long double>, &::sqrtl);\n    test1<long double>(&boost::qvm::ceil<long double>, &::ceill);\n    test1<long double>(&boost::qvm::abs<long double>, &::fabsl);\n    test1<long double>(&boost::qvm::floor<long double>, &::floorl);\n    test2<long double, int>(&boost::qvm::ldexp<long double>, &::ldexpl);\n\n    return boost::report_errors();\n    }\n", "meta": {"hexsha": "c45644f74ce56fb4bf00913ac87f717e61847559", "size": 4596, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "console/src/boost_1_78_0/libs/qvm/test/math_test.cpp", "max_stars_repo_name": "vany152/FilesHash", "max_stars_repo_head_hexsha": "39f282807b7f1abc56dac389e8259ee3bb557a8d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 106.0, "max_stars_repo_stars_event_min_datetime": "2015-08-07T04:23:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-27T18:25:15.000Z", "max_issues_repo_path": "console/src/boost_1_78_0/libs/qvm/test/math_test.cpp", "max_issues_repo_name": "vany152/FilesHash", "max_issues_repo_head_hexsha": "39f282807b7f1abc56dac389e8259ee3bb557a8d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 130.0, "max_issues_repo_issues_event_min_datetime": "2016-06-22T22:11:25.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-29T20:24:09.000Z", "max_forks_repo_path": "Libs/boost_1_76_0/libs/qvm/test/math_test.cpp", "max_forks_repo_name": "Antd23rus/S2DE", "max_forks_repo_head_hexsha": "47cc7151c2934cd8f0399a9856c1e54894571553", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2015-07-08T19:18:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-14T16:39:56.000Z", "avg_line_length": 42.5555555556, "max_line_length": 79, "alphanum_fraction": 0.5953002611, "num_tokens": 1455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.5813030906443134, "lm_q1q2_score": 0.46398844639278686}}
{"text": "#include \"kmeans_clustering.h\"\n#include \"ocv_kmeans_wrapper.h\"\n\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <iostream>\n\nusing namespace Eigen;\nvoid kmeans_clustering(VectorXi& idx, int clusters, std::vector<VectorXi>& ibones, std::vector<VectorXi>& imuscle, MatrixXd& mG, SparseMatrix<double>& mC, SparseMatrix<double>& mA, VectorXd& mx0){\n        MatrixXd Centroids;\n        idx.resize(mC.rows()/12);\n        idx.setZero();\n        std::cout<<\"    kmeans0 un \"<<std::endl;\n\n\n        for(int b=0; b<ibones.size(); b++){\n            for(int i=0; i<ibones[b].size(); i++){\n                idx[ibones[b][i]] = clusters - 1 - b;\n            }\n        }\n        clusters = clusters - ibones.size();\n\n\n        std::cout<<\"     kmeans1 un\"<<std::endl;\n        VectorXd CAx0 = mC*mA*mx0;\n\n        int clusters_per_muscle = clusters/imuscle.size();\n\n        for(int m=0; m<imuscle.size(); m++){\n            std::cout<<\"     kmeans2 un\"<<std::endl;\n            VectorXi labels;\n            MatrixXd Data = MatrixXd::Zero(imuscle[m].size(), 3);\n            \n            for(int i=0; i<Data.rows(); i++){\n                Data.row(i) = RowVector3d(CAx0[12*imuscle[m][i]+0],CAx0[12*imuscle[m][i]+1],CAx0[12*imuscle[m][i]+2]);\n            }\n\n            std::cout<<\"     kmeans3 do clustering\"<<std::endl;\n            if(m==imuscle.size()-1){\n                //deal with remainder clusters\n                ocv_kmeans(Data, clusters, 1000, Centroids, labels);\n            }else{\n                ocv_kmeans(Data, clusters_per_muscle, 1000, Centroids, labels);\n            }\n\n            std::cout<<\"     kmeans4 create element_cluster_map\"<<std::endl;\n            for(int q=0; q<imuscle[m].size(); q++){\n                idx[imuscle[m][q]] = clusters_per_muscle*m + labels[q];\n            }\n            clusters = clusters - clusters_per_muscle;\n\n        }\n        std::cout<<\"    kmeans5 un\"<<std::endl;\n\n        assert(clusters==0);\n        return;\n    }", "meta": {"hexsha": "ba815e02bd0c1e8e57459f2e235bdba1bcca5db9", "size": 1950, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PreProcessing/kmeans_clustering.cpp", "max_stars_repo_name": "alecjacobson/fast_muscles", "max_stars_repo_head_hexsha": "92150eaa81a4c1cbd27a76dbe4f10d27dffca3b4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-09T08:28:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-09T08:28:39.000Z", "max_issues_repo_path": "PreProcessing/kmeans_clustering.cpp", "max_issues_repo_name": "alecjacobson/fast_muscles", "max_issues_repo_head_hexsha": "92150eaa81a4c1cbd27a76dbe4f10d27dffca3b4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PreProcessing/kmeans_clustering.cpp", "max_forks_repo_name": "alecjacobson/fast_muscles", "max_forks_repo_head_hexsha": "92150eaa81a4c1cbd27a76dbe4f10d27dffca3b4", "max_forks_repo_licenses": ["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.2105263158, "max_line_length": 196, "alphanum_fraction": 0.5358974359, "num_tokens": 533, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4639884408114674}}
{"text": "// Example of using the GeographicLib::NearestNeighbor class.  WARNING: this\n// creates a file, vptree.xml or vptree.bin, in the current directory.\n\n#include <iostream>\n\n#include <vector>\n#include <cstdlib>              // For srand, rand\n#include <cmath>                // For asin\n#include <fstream>\n#include <string>\n#include <sstream>\n#include <algorithm>            // For sort\n#include <GeographicLib/NearestNeighbor.hpp>\n#include <GeographicLib/Geodesic.hpp>\n\n#if !defined(GEOGRAPHICLIB_HAVE_BOOST_SERIALIZATION)\n#define GEOGRAPHICLIB_HAVE_BOOST_SERIALIZATION 0\n#endif\n\n#if GEOGRAPHICLIB_HAVE_BOOST_SERIALIZATION\n// If Boost serialization is available, use it.\n#include <boost/archive/xml_iarchive.hpp>\n#include <boost/archive/xml_oarchive.hpp>\n#endif\n\nusing namespace std;\nusing namespace GeographicLib;\n\n// A structure to hold a geographic coordinate.  Also included is a field for a\n// \"name\".  This is unused in this example.\nstruct pos {\n  double lat, lon;\n  string name;\n  pos(double lat = 0, double lon = 0, const string& name = \"\")\n    : lat(lat), lon(lon), name(name) {}\n};\n\npos randompos() {\n  double r, lat, lon;\n  r = 2 * (rand() + 0.5) / (RAND_MAX + 1.0) - 1;\n  lat = asin(r) / Math::degree();\n  r = 2 * (rand() + 0.5) / (RAND_MAX + 1.0) - 1;\n  lon = 180 * r;\n  return pos(lat, lon);\n}\n\n// A class to compute the distance between 2 positions.\nclass DistanceCalculator {\nprivate:\n  Geodesic _geod;\npublic:\n  explicit DistanceCalculator(const Geodesic& geod)\n    : _geod(geod) {}\n  double operator() (const pos& a, const pos& b) const {\n    double s12;\n    _geod.Inverse(a.lat, a.lon, b.lat, b.lon, s12);\n    return s12;\n  }\n};\n\ntypedef NearestNeighbor<double, pos, DistanceCalculator> GeodesicNeighbor;\n\n// Pick 10000 points on the ellipsoid and determine which ones are more than\n// 350 km from all the others.\n\n// In this example the NearestNeighbor object is saved to an external file and\n// read back in.  This is unnecessary in this simple application, but is useful\n// if many different applications need to query the same dataset.\n\nint main() {\n  try {\n    // Define a distance function object\n    DistanceCalculator distance(Geodesic::WGS84());\n    srand(0);\n    vector<pos> pts;\n    int num = 10000;\n    // Sample the points\n    for (int i = 0; i < num; ++i) pts.push_back(randompos());\n    {\n      // Illustrate saving and restoring the GeodesicNeighbor\n      // construct it\n      GeodesicNeighbor posset(pts, distance);\n      // and save it\n#if GEOGRAPHICLIB_HAVE_BOOST_SERIALIZATION\n      ofstream f(\"vptree.xml\");\n      boost::archive::xml_oarchive oa(f);\n      oa << BOOST_SERIALIZATION_NVP(posset);\n#else\n      ofstream ofs(\"vptree.txt\");\n      ofs << posset << \"\\n\";\n#endif\n    }\n    // Construct an empty GeodesicNeighbor\n    GeodesicNeighbor posset;\n    // restore it from the file\n    {\n#if GEOGRAPHICLIB_HAVE_BOOST_SERIALIZATION\n      ifstream f(\"vptree.xml\");\n      boost::archive::xml_iarchive ia(f);\n      ia >> BOOST_SERIALIZATION_NVP(posset);\n#else\n      ifstream ifs(\"vptree.txt\");\n      ifs >> posset;\n#endif\n    }\n    // Now use it\n    vector<int> ind;\n    int cnt = 0;\n    double thresh = 325000;\n    cout << \"Points more than \" << thresh/1000 << \"km from their neighbors\\n\"\n         << \"latitude longitude distance\\n\";\n    for (int i = 0; i < num; ++i) {\n      // Call search with distance limits = (0, thresh].  Set exhaustive = false\n      // so that the search ends as some as a neighbor is found.\n      posset.Search(pts, distance, pts[i], ind, 1, thresh, 0, false);\n      if (ind.size() == 0) {\n        // If no neighbors in (0, thresh], search again with no upper limit and\n        // with exhaustive = true (the default).\n        double d = posset.Search(pts, distance, pts[i], ind, 1,\n                                 numeric_limits<double>::max(), 0);\n        cout << pts[i].lat << \" \" << pts[i].lon << \" \" << d << \"\\n\";\n        ++cnt;\n      }\n    }\n    int setupcost, numsearches, searchcost, mincost, maxcost;\n    double mean, sd;\n    posset.Statistics(setupcost, numsearches, searchcost, mincost, maxcost,\n                      mean, sd);\n    int totcost = setupcost + searchcost, exhaustivecost = num * (num - 1) / 2;\n    cout\n      << \"Number of distance calculations = \" << totcost << \"\\n\"\n      << \"With an exhaustive search = \" << exhaustivecost << \"\\n\"\n      << \"Ratio = \" << double(totcost) / exhaustivecost << \"\\n\"\n      << \"Efficiency improvement = \"\n      << 100 * (1 - double(totcost) / exhaustivecost) << \"%\\n\";\n  }\n  catch (const exception& e) {\n    cerr << \"Caught exception: \" << e.what() << \"\\n\";\n    return 1;\n  }\n}\n", "meta": {"hexsha": "eb8319f77db9f7a50a666332501d34949ea2b343", "size": 4595, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/example-NearestNeighbor.cpp", "max_stars_repo_name": "shield-ai/geographiclib", "max_stars_repo_head_hexsha": "2a6ccdf99f9b580aff4ef4725720172235fa9da0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-12-29T16:21:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-09T11:29:11.000Z", "max_issues_repo_path": "examples/example-NearestNeighbor.cpp", "max_issues_repo_name": "shield-ai/geographiclib", "max_issues_repo_head_hexsha": "2a6ccdf99f9b580aff4ef4725720172235fa9da0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/example-NearestNeighbor.cpp", "max_forks_repo_name": "shield-ai/geographiclib", "max_forks_repo_head_hexsha": "2a6ccdf99f9b580aff4ef4725720172235fa9da0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-04-09T12:46:15.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-09T11:29:21.000Z", "avg_line_length": 32.3591549296, "max_line_length": 80, "alphanum_fraction": 0.6359085963, "num_tokens": 1259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4639884408114673}}
{"text": "#include <Eigen/Core>\n#include \"densecrf.h\"\n#include \"densecrf_wrapper.h\"\n\nDenseCRFWrapper::DenseCRFWrapper(int npixels, int nlabels)\n: m_npixels(npixels), m_nlabels(nlabels) {\n\tm_crf = new DenseCRF(npixels, nlabels);\n}\n\nDenseCRFWrapper::~DenseCRFWrapper() {\n\tdelete m_crf;\n}\n\nint DenseCRFWrapper::npixels() { return m_npixels; }\nint DenseCRFWrapper::nlabels() { return m_nlabels; }\n\nvoid DenseCRFWrapper::add_pairwise_energy(float* pairwise_costs_ptr, float* features_ptr, int nfeatures) {\n\tm_crf->addPairwiseEnergy(\n\t\tEigen::Map<const Eigen::MatrixXf>(features_ptr, nfeatures, m_npixels),\n\t\tnew MatrixCompatibility(\n\t\t\tEigen::Map<const Eigen::MatrixXf>(pairwise_costs_ptr, m_nlabels, m_nlabels)\n\t\t),\n\t\tDIAG_KERNEL,\n\t\tNORMALIZE_SYMMETRIC\n\t);\n}\n\nvoid DenseCRFWrapper::set_unary_energy(float* unary_costs_ptr) {\n\tm_crf->setUnaryEnergy(\n\t\tEigen::Map<const Eigen::MatrixXf>(\n\t\t\tunary_costs_ptr, m_nlabels, m_npixels)\n\t);\n}\n\nvoid DenseCRFWrapper::map(int n_iters, int* labels) {\n\tVectorXs labels_vec = m_crf->map(n_iters);\n\tfor (int i = 0; i < m_npixels; i ++)\n\t\tlabels[i] = labels_vec(i);\n}\n", "meta": {"hexsha": "c5765dd2d8b4befa716a6d6438928cb8edd8bf30", "size": 1088, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bell2014/krahenbuhl2013/src/densecrf_wrapper.cpp", "max_stars_repo_name": "dmaugis/intrinsic", "max_stars_repo_head_hexsha": "e223fc8abceb2bf26f9a7752d72afe598ac4e1fd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 134.0, "max_stars_repo_stars_event_min_datetime": "2015-01-04T04:54:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-16T07:39:02.000Z", "max_issues_repo_path": "bell2014/krahenbuhl2013/src/densecrf_wrapper.cpp", "max_issues_repo_name": "dmaugis/intrinsic", "max_issues_repo_head_hexsha": "e223fc8abceb2bf26f9a7752d72afe598ac4e1fd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2016-07-30T21:45:11.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T14:12:50.000Z", "max_forks_repo_path": "bell2014/krahenbuhl2013/src/densecrf_wrapper.cpp", "max_forks_repo_name": "dmaugis/intrinsic", "max_forks_repo_head_hexsha": "e223fc8abceb2bf26f9a7752d72afe598ac4e1fd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 34.0, "max_forks_repo_forks_event_min_datetime": "2015-01-14T16:39:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-31T11:29:50.000Z", "avg_line_length": 27.2, "max_line_length": 106, "alphanum_fraction": 0.7490808824, "num_tokens": 337, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174789, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4639409704177393}}
{"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_FUNCTION_SINCPI_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_SINCPI_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n    @ingroup group-trigonometric\n    Function object implementing sincpi capabilities\n\n    Computes the sinpi cardinal  value of its parameter that is sin(Pi*x)/(Pi*x).\n    @par Semantic:\n\n    For every parameter of floating type T\n\n    @code\n    T r = sincpi(x);\n    @endcode\n\n    is similar to:\n\n    @code\n    T r = x ? sinpi(x)/(Pi<T>()*x) : One;\n    @endcode\n\n    @see sin, sinc, sinhc\n\n  **/\n  const boost::dispatch::functor<tag::sincpi_> sincpi = {};\n} }\n#endif\n\n#include <boost/simd/function/scalar/sincpi.hpp>\n#include <boost/simd/function/simd/sincpi.hpp>\n\n#endif\n", "meta": {"hexsha": "417899d39e89848684f97d310d384903009a06dd", "size": 1161, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/sincpi.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/function/sincpi.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/function/sincpi.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": 23.693877551, "max_line_length": 100, "alphanum_fraction": 0.5762273902, "num_tokens": 268, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4639409704177392}}
{"text": "#include \"drake/multibody/contact_solvers/sparse_linear_operator.h\"\n\n#include <memory>\n\n#include <Eigen/SparseCore>\n#include <gtest/gtest.h>\n\nnamespace drake {\nnamespace multibody {\nnamespace contact_solvers {\nnamespace internal {\nnamespace {\n\nusing SparseMatrixd = Eigen::SparseMatrix<double>;\nusing SparseVectord = Eigen::SparseVector<double>;\nusing Eigen::VectorXd;\nusing Triplet = Eigen::Triplet<double>;\n\n// This method makes a sparse matrix that emulates the contact Jacobian that we\n// would have in an application in which a subset of the vertices of a mesh is\n// in contact. More specifically, if nc is the number of vertices in contact,\n// vc \u2208 \u211d\u00b3\u02e3\u207f\u1d9c is the vector that concatenates the 3D contact velocities of all\n// nc contact points and, v is the vector that concatenates the 3D velocities of\n// all nv vertices in the mesh, then the contact Jacobian Jc is defined such\n// that vc = Jc\u22c5v. Jc is of size 3nc x 3nv.\n//\n// N.B. Though inspired in a real application, this is only meant for test\n// purposes while in a real application with meshes the computation of this\n// Jacobian is more complex. Our goal is to generate a sparse matrix so that we\n// can attach a LinearOperator interface to it for testing purposes.\n//\n// num_vertices:\n//   The number of vertices nv in a hypothetical mesh. The number of\n//   generalized velocities in this case equals 3 * num_vertices.\n// vertices_in_contact:\n//   set of the vertices that are in \"contact\". The size of vertices_in_contact\n//   is nc, the number of contact points.\n//\n// For each contact point ic, its velocity simply equals the velocity for that\n// vertex iv. Therefore the Jacobian contains an identity matrix at 3x3 block\n// (ic, iv). All other entries are zero. Thus the Jacobian is very sparse.\nSparseMatrixd MakeMeshInContactJacobian(\n    int num_vertices, const std::vector<int>& vertices_in_contact) {\n  const int num_contacts = static_cast<int>(vertices_in_contact.size());\n  const int nnz = 3 * num_contacts;\n  std::vector<Triplet> triplets;\n  triplets.reserve(nnz);\n  for (int ic = 0; ic < num_contacts; ++ic) {\n    const int v = vertices_in_contact[ic];\n    DRAKE_DEMAND(v < num_vertices);\n    triplets.emplace_back(3 * ic, 3 * v, 1.0);\n    triplets.emplace_back(3 * ic + 1, 3 * v + 1, 1.0);\n    triplets.emplace_back(3 * ic + 2, 3 * v + 2, 1.0);\n  }\n  SparseMatrixd J(3 * num_contacts, 3 * num_vertices);\n  J.setFromTriplets(triplets.begin(), triplets.end());\n  return J;\n}\n\nclass ContactJacobianTest : public ::testing::Test {\n protected:\n  void SetUp() override {\n    J_ = MakeMeshInContactJacobian(kNumVertices_, contact_set_);\n    Jop_ = std::make_unique<SparseLinearOperator<double>>(\"Jc\", &J_);\n    num_rows_ = 3 * static_cast<int>(contact_set_.size());\n  }\n\n  const int kNumVertices_ = 300;\n  const std::vector<int> contact_set_{12, 3, 75, 100, 99, 233, 7};\n  int num_rows_{};\n  int kCols_{3 * kNumVertices_};\n  SparseMatrixd J_;\n  std::unique_ptr<SparseLinearOperator<double>> Jop_;\n};\n\nTEST_F(ContactJacobianTest, Construction) {\n  EXPECT_EQ(Jop_->name(), \"Jc\");\n  EXPECT_EQ(Jop_->rows(), num_rows_);\n  EXPECT_EQ(Jop_->cols(), kCols_);\n}\n\nTEST_F(ContactJacobianTest, MultiplyDense) {\n  VectorXd y(num_rows_);\n  const VectorXd x = VectorXd::LinSpaced(kCols_, 0.0, 1.0);\n  Jop_->Multiply(x, &y);\n\n  VectorXd y_expected = J_ * x;\n  // y's values should equal those in y_expected bit by bit.\n  EXPECT_EQ(y, y_expected);\n}\n\nTEST_F(ContactJacobianTest, MultiplyByTransposeDense) {\n  VectorXd y(kCols_);\n  const VectorXd x = VectorXd::LinSpaced(num_rows_, 0.0, 1.0);\n  Jop_->MultiplyByTranspose(x, &y);\n\n  VectorXd y_expected = J_.transpose() * x;\n  // y's values should equal those in y_expected bit by bit.\n  EXPECT_EQ(y, y_expected);\n}\n\nTEST_F(ContactJacobianTest, MultiplySparse) {\n  SparseVectord y(num_rows_);\n  const SparseVectord x = VectorXd::LinSpaced(kCols_, 0.0, 1.0).sparseView();\n  Jop_->Multiply(x, &y);\n\n  VectorXd y_expected = J_ * x;\n  // y's values should equal those in y_expected bit by bit.\n  EXPECT_EQ(VectorXd(y), y_expected);\n}\n\nTEST_F(ContactJacobianTest, MultiplyByTransposeSparse) {\n  SparseVectord y(kCols_);\n  const SparseVectord x = VectorXd::LinSpaced(num_rows_, 0.0, 1.0).sparseView();\n  Jop_->MultiplyByTranspose(x, &y);\n\n  VectorXd y_expected = J_.transpose() * x;\n  // y's values should equal those in y_expected bit by bit.\n  EXPECT_EQ(VectorXd(y), y_expected);\n}\n\nTEST_F(ContactJacobianTest, AssembleMatrix) {\n  SparseMatrixd Jcopy(Jop_->rows(), Jop_->cols());\n  Jop_->AssembleMatrix(&Jcopy);\n\n  // Required before we access their data pointers.\n  Jcopy.makeCompressed();\n  J_.makeCompressed();\n\n  // We verify the Jcopy is an exact bit by bit copy of J_.\n  // Eigen does not offer SparseMatrix::operator==() and therefore we compare\n  // the results by explicitly comparing the individual components of the CCS\n  // format.\n  Eigen::Map<VectorX<double>> Jcopy_values(Jcopy.valuePtr(), Jcopy.nonZeros());\n  Eigen::Map<VectorX<double>> J_values(J_.valuePtr(), J_.nonZeros());\n  EXPECT_EQ(Jcopy_values, J_values);\n\n  Eigen::Map<VectorX<int>> Jcopy_inner(Jcopy.innerIndexPtr(),\n                                       Jcopy.innerSize());\n  Eigen::Map<VectorX<int>> J_inner(J_.innerIndexPtr(), J_.innerSize());\n  EXPECT_EQ(Jcopy_inner, J_inner);\n\n  Eigen::Map<VectorX<int>> Jcopy_outer(Jcopy.outerIndexPtr(),\n                                       Jcopy.outerSize());\n  Eigen::Map<VectorX<int>> J_outer(J_.outerIndexPtr(), J_.outerSize());\n  EXPECT_EQ(Jcopy_outer, J_outer);\n}\n\n}  // namespace\n}  // namespace internal\n}  // namespace contact_solvers\n}  // namespace multibody\n}  // namespace drake\n", "meta": {"hexsha": "acadfff21641da867210084bda253261f6d72758", "size": 5614, "ext": "cc", "lang": "C++", "max_stars_repo_path": "multibody/contact_solvers/test/sparse_linear_operator_test.cc", "max_stars_repo_name": "RobotLocomotion/drake-python3.7", "max_stars_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-02-25T02:01:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-17T04:52:04.000Z", "max_issues_repo_path": "multibody/contact_solvers/test/sparse_linear_operator_test.cc", "max_issues_repo_name": "RobotLocomotion/drake-python3.7", "max_issues_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "multibody/contact_solvers/test/sparse_linear_operator_test.cc", "max_forks_repo_name": "RobotLocomotion/drake-python3.7", "max_forks_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-13T12:05:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-13T12:05:39.000Z", "avg_line_length": 36.4545454545, "max_line_length": 80, "alphanum_fraction": 0.7160669754, "num_tokens": 1540, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.4639409638773473}}
{"text": "#include \"ros/ros.h\"\n#include \"std_msgs/String.h\"\n#include <sensor_msgs/LaserScan.h>\n#include <stdio.h>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/core/core.hpp>\n#include <cmath>\n#include <cv.h>\n#include <opencv2/opencv.hpp>\n#include <vector>\n#include <map>\n#include <math.h>\n#include <ros/package.h>\n#include <tf2_geometry_msgs/tf2_geometry_msgs.h>\n#include <tf2/utils.h>\n#include <boost/shared_ptr.hpp>\n\n//TODO: add theta shift as per pose\nusing namespace cv;\n\nint scan_beams;\ndouble dist_resolution, fov, scan_resolution, max_invalid_range, max_range;\nstd::string frame_id;\nbool test_with_mouse_click;\nlong int seq_id = 0;\nstd::map<uint16_t, float> scan;\nMat input_image,image;\nvoid mouse_click_callback();\nboost::shared_ptr<sensor_msgs::LaserScan> get_scan_from_image(int col, int row, double pose_theta);\nros::Publisher scan_pub;\nstd::vector<double> distances;\ngeometry_msgs::TransformStamped image_to_map;\nsensor_msgs::LaserScan laser_scan;\ninline double get_theta_image(int col_a, int row_a, int col_b, int row_b)\n{\n   return atan2(-1*(row_b - row_a), col_b - col_a); // representing row as a true Y axis \n\n}\n\ngeometry_msgs::TransformStamped get_transform(std::vector<double> map_origin, Mat &image)\n{\n    geometry_msgs::Pose pose_msg;\n    pose_msg.position.x = map_origin[0];\n    pose_msg.position.y = map_origin[1];\n    pose_msg.position.z = 0;\n    tf2::Quaternion q;\n    q.setRPY(0, 0, map_origin[2]);\n    pose_msg.orientation = tf2::toMsg(q);\n    tf2::Transform map_image_origin_to_map, map_to_map_image_origin, image_to_map_image_origin;\n    tf2::fromMsg(pose_msg, map_to_map_image_origin);\n    map_image_origin_to_map = map_to_map_image_origin.inverse();\n    pose_msg.position.x = 0;\n    pose_msg.position.y = -1 * image.rows * dist_resolution;\n    pose_msg.position.z = 0;\n    q.setRPY(0, 0, 0);\n    pose_msg.orientation = tf2::toMsg(q);\n    tf2::fromMsg(pose_msg, image_to_map_image_origin);\n    tf2::Transform image_to_map_origin;\n    image_to_map_origin = image_to_map_image_origin*map_image_origin_to_map;\n    image_to_map.transform = tf2::toMsg(image_to_map_origin);\n    image_to_map.header.seq = 1;\n    image_to_map.header.stamp = ros::Time::now();\n    image_to_map.header.frame_id = 'image';\n    image_to_map.child_frame_id = 'map';\n    ROS_INFO(\"transform:%f, %f,\",image_to_map.transform.translation.x, image_to_map.transform.translation.y);\n\n    return image_to_map;\n}\n\nvoid CallBackFunc(int event, int x, int y, int flags, void* userdata)\n{\n    \n    if  ( event == EVENT_LBUTTONDOWN )\n    {\n        for (uint16_t i = 0; i < scan_beams; ++i)\n        {\n            scan[i] = max_invalid_range;\n        }\n        scan_pub.publish(get_scan_from_image(x,y,-0.0));\n\n    }\n\n}\n\nboost::shared_ptr<sensor_msgs::LaserScan> get_scan_from_image(int col, int row, double pose_theta)\n{\n\n    float r,theta;\n    int pix_max_range = max_range/dist_resolution;\n    int start_row, start_col, end_row, end_col;\n    int crop_x,crop_y;\n    start_col =  std::max(0, col - pix_max_range);\n    end_col = std::min(image.cols, col + pix_max_range);\n    start_row = std::max(0, row - pix_max_range);\n    end_row = std::min(image.rows, row + pix_max_range);\n    // ROS_INFO(\"ROI:%d,%d,%d,%d   ,%f  total:%d\", start_col, end_col, start_row, end_row, dist_resolution,(end_col-start_col)*(end_row-start_row) );\n\n    for (uint16_t i = start_col; i < end_col; i++)\n    {\n        for (uint16_t j = start_row; j < end_row; j++)\n        {\n            if(image.at<uchar>(j,i)<150)\n            {\n                r = sqrt(pow((col - i),2)+pow((row - j),2)) * dist_resolution;\n                if (r>max_range)\n                {\n                    continue;\n                }\n                theta = get_theta_image(col, row, i, j) - pose_theta;\n                theta = atan2(sin(theta), cos(theta));\n                int index = (theta - laser_scan.angle_min)/scan_resolution;\n                if (index < 0 || index >=scan_beams)\n                    continue;\n\n                int skip_checks = dist_resolution/(r * scan_resolution);//width beam in denominator\n                for (uint16_t k = std::max(0,index - skip_checks/2); k <= std::min(index + skip_checks/2, scan_beams); ++k)\n                {\n                    if(r < scan[k])\n                    {\n                        scan[k] = r;\n                    }\n                }\n\n            }\n\n        }\n\n    }\n\n    for (uint16_t i = 0; i < scan_beams; ++i)\n    {\n        laser_scan.ranges[i] = scan[i];\n    }\n    laser_scan.header.stamp = ros::Time::now();\n    boost::shared_ptr<sensor_msgs::LaserScan> ptr_scan;\n    ptr_scan.reset(new sensor_msgs::LaserScan(laser_scan));\n    return (ptr_scan);\n}\n\nvoid pose_callback(const geometry_msgs::PoseStamped msg)\n{\n    geometry_msgs::PoseStamped image_pose;\n    tf2::doTransform(msg, image_pose, image_to_map);\n    int col_pix = image_pose.pose.position.x / dist_resolution;\n    int row_pix = -1 * image_pose.pose.position.y / dist_resolution;// row corresponds to negative y axis\n    for (uint16_t i = 0; i < scan_beams; ++i)\n    {\n        scan[i] = max_invalid_range;\n    }\n    double pose_theta = tf2::getYaw(image_pose.pose.orientation);\n    // ROS_INFO(\"pixel:%f ,%f ,%f\",image_pose.pose.position.x,image_pose.pose.position.x, pose_theta);\n    scan_pub.publish(get_scan_from_image(col_pix,row_pix,pose_theta));\n\n}\n\n\nint main(int argc, char **argv)\n{\n    ros::init(argc, argv, \"listener\");\n    ros::NodeHandle nh;\n    std::string map_name;\n    scan_pub = nh.advertise<sensor_msgs::LaserScan>(\"/scan\",1);\n    ros::Subscriber pose_sub = nh.subscribe(\"/pose_stamped\", 1, &pose_callback);\n    \n\n    //Loading laser scan information\n    nh.param(\"/scan_params/fov\", fov, 2*M_PI );\n    nh.param(\"/scan_params/max_range\", max_range, 30.0);\n    nh.param(\"/scan_params/max_invalid_range\", max_invalid_range, 1048.0);\n    nh.param(\"/scan_params/scan_beams\", scan_beams, 628);\n    nh.param(\"/scan_params/test_with_mouse_click\", test_with_mouse_click, true);\n    nh.param(\"/scan_params/frame_id\", frame_id, std::string(\"laser\"));\n    scan_resolution= (fov)/scan_beams ;\n    std::vector<double> origin;\n    if(!nh.getParam(\"/map_data/origin\",origin))\n    {\n        ROS_ERROR(\"cant find the parameters of the map\");\n        return 0;\n    }\n    if (!nh.getParam(\"/map_data/resolution\",dist_resolution))\n    {\n        ROS_ERROR(\"cant find the parameters of the map\");\n        return 0;\n    }\n    if (!nh.getParam(\"/map_data/image\",map_name))\n    {\n        ROS_ERROR(\"cant find the parameters of the map\");\n        return 0;\n    }\n\n    std::string image_location = ros::package::getPath(\"scan_from_image\");\n    image_location = image_location + \"/launch/\"+map_name;\n    ROS_INFO(\"image_location is:%s\", image_location.c_str());\n    input_image = imread(image_location.c_str(), CV_LOAD_IMAGE_GRAYSCALE);\n    image = input_image.clone();\n     ROS_INFO(\"transform:%f, %f,\",origin[0], origin[1]);\n    image_to_map = get_transform(origin, input_image);\n\n    for (uint16_t i = 0; i < scan_beams; ++i)\n    {\n        scan[i]=max_invalid_range;\n    }\n\n\n    ros::Rate loop(5);\n    if(test_with_mouse_click)\n    {    \n        int disp_image_size = 800;\n        Size size(disp_image_size,disp_image_size);//the dst image size,e.g.100x100\n        float scale_image = static_cast<float>(input_image.rows)/disp_image_size;\n        dist_resolution = scale_image*dist_resolution;\n        resize(input_image, input_image,size);//resize image\n        namedWindow(\"My Window\", 1);\n    }    \n    image_to_map = get_transform(origin, input_image);\n    image = input_image;\n\n\n    laser_scan.header.seq = seq_id;\n    laser_scan.header.stamp = ros::Time::now();\n    laser_scan.header.frame_id = frame_id;\n    laser_scan.angle_min = -fov/2;\n    laser_scan.angle_max = fov/2;\n    laser_scan.angle_increment = (laser_scan.angle_max - laser_scan.angle_min)/scan_beams;\n    laser_scan.range_min = 0.0;\n    laser_scan.range_max = max_range;\n    laser_scan.scan_time = 1.0 / 5.0;\n    laser_scan.time_increment = (1.0 / 5.0) / scan_beams;\n    laser_scan.ranges.resize(scan_beams);\n    laser_scan.intensities.resize(scan_beams);\n    \n    while(nh.ok())\n    {\n        if (test_with_mouse_click)\n        {\n            mouse_click_callback();\n            imshow(\"My Window\", image);\n            waitKey(0);\n        }\n        \n\n        loop.sleep();\n        ros::spinOnce();\n    }\n    destroyAllWindows();\n    return 0;\n}\n\n\n\nvoid mouse_click_callback()\n{\n\n    setMouseCallback(\"My Window\", CallBackFunc, NULL);\n\n}\n", "meta": {"hexsha": "9f50a1f419cdbff5fc427be9f72811253d7d9961", "size": 8463, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/laser_scan_from_image.cpp", "max_stars_repo_name": "nitishk162/scan_from_image", "max_stars_repo_head_hexsha": "3f254f41eb2c9c1aad8ab934e4895f3b74815872", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-10-03T10:34:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-11T10:42:37.000Z", "max_issues_repo_path": "src/laser_scan_from_image.cpp", "max_issues_repo_name": "nitishk162/scan_from_image", "max_issues_repo_head_hexsha": "3f254f41eb2c9c1aad8ab934e4895f3b74815872", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/laser_scan_from_image.cpp", "max_forks_repo_name": "nitishk162/scan_from_image", "max_forks_repo_head_hexsha": "3f254f41eb2c9c1aad8ab934e4895f3b74815872", "max_forks_repo_licenses": ["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.9299610895, "max_line_length": 149, "alphanum_fraction": 0.651423845, "num_tokens": 2193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.46394096387734723}}
{"text": "/**\n * qvrefl.cc\n * Copyright 2016 John Lawson\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n#include <iostream>\n#include <string>\n#include <unistd.h>\n\n#include <boost/dynamic_bitset.hpp>\n\n#include \"qv/mutation_class_loader.h\"\n#include \"qv/equiv_mutation_class_loader.h\"\n#include \"qv/stream_iterator.h\"\n\n#include \"filtered_iterator.h\"\n#include \"cartan_equiv.h\"\n#include \"cartan_iterator.h\"\n#include \"cartan_mutator.h\"\n#include \"compatible_cartan.h\"\n#include \"mutation_star.h\"\n#include \"semi_positive_filter.h\"\n#include \"vector_mutator.h\"\n#include \"unique_matrix_filter.h\"\n#include \"util.h\"\n\nnamespace refl {\nnamespace {\nusing MatrixVec = std::vector<arma::Mat<int>>;\nusing UniqueCartanIter =\n    FilteredIterator<CartanIterator, arma::Mat<int>, UniqueMatrixFilter>;\nusing SemiPosIter =\n    FilteredIterator<UniqueCartanIter, arma::Mat<int>, SemiPositiveFilter>;\n\nauto get_cartan_iterator(cluster::QuiverMatrix const& q) {\n  CartanIterator cartan(q);\n  // UniqueCartanIter unique(std::move(cartan));\n  // return SemiPosIter(std::move(unique));\n  return UniqueCartanIter(std::move(cartan));\n}\n/**\n * For each vertex in the given quiver, find a semipositive quasi-Cartan which\n * serves that vertex. These matrices are returned in a vector indexed by the\n * label of the vertices.\n *\n * If no such quasi-Cartan companion exists for a given vertex, then there will\n * still be a matrix in the vector, however all its values will be zero.\n */\nMatrixVec find_serving_cartans(cluster::QuiverMatrix const& q) {\n  MatrixVec result(q.num_cols(), arma::Mat<int>(q.num_rows(), q.num_cols()));\n  boost::dynamic_bitset<> found{q.num_cols(), 0};\n  const MutationStar star(q);\n  const arma::mat initial_vecs(q.num_rows(), q.num_cols(), arma::fill::eye);\n  arma::mat mutated_vecs(q.num_rows(), q.num_cols());\n  arma::mat gram_matrix(q.num_rows(), q.num_cols());\n\n  CompatibleCartan compatible;\n\n  auto cartan_iter = SemiPosIter(get_cartan_iterator(q));\n\n  while (cartan_iter.has_next() && !found.all()) {\n    arma::Mat<int> const& AQ = cartan_iter.next();\n    VectorMutator vmut(q, AQ);\n    int_fast16_t ncols = AQ.n_cols;\n    for (int_fast16_t i = 0; i < ncols; ++i) {\n      vmut.mutate(initial_vecs, i, mutated_vecs);\n      gram_matrix = util::gram(mutated_vecs, AQ);\n      if (!found[i] && compatible(star.qv(i), gram_matrix)) {\n        result[i] = AQ;\n        found[i] = true;\n      }\n    }\n  }\n  return result;\n}\n/**\n * Print the first semipositive quasi-Cartan companion serving each vertex of\n * the given quiver. If no such companion exists, then print that the vertex is\n * not served by a Cartan matrix.\n */\nvoid output_serving_cartans(cluster::QuiverMatrix const& q,\n                            std::ostream& os = std::cout) {\n  auto res = refl::find_serving_cartans(q);\n  int_fast16_t size = res.size();\n  for (int_fast16_t i = 0; i < size; ++i) {\n    if (res[i].at(0, 0) != 2) {\n      os << i << \" is not served by any semi-positive quasi-Cartan\"\n         << os.widen('\\n');\n    } else {\n      std::string label;\n      label.append(std::to_string(i)).append(\" served by\");\n      res[i].print(os, label);\n    }\n  }\n}\n/**\n * Find the first semipositive quasi-Cartan fully compatible with q.\n *\n * If no such quasi-Cartan exists then the first item in the returned pair is\n * false, otherwise the first item is true and the second item is this first\n * Cartan matrix.\n */\nstd::pair<bool, arma::Mat<int>> first_compatible_cartan(\n    cluster::QuiverMatrix const& q) {\n  bool result = false;\n  arma::Mat<int> cartan;\n  const MutationStar star(q);\n  arma::Mat<int> gram_matrix(q.num_rows(), q.num_cols());\n\n  CompatibleCartan compatible;\n\n  auto cartan_iter = get_cartan_iterator(q);\n  SemiPositiveFilter semipos;\n\n  CartanMutator cmut(q);\n  while (cartan_iter.has_next() && !result) {\n    bool is_comp = true;\n    arma::Mat<int> const& AQ = cartan_iter.next();\n    int_fast16_t ncols = AQ.n_cols;\n    for (int_fast16_t i = 0; is_comp && i < ncols; ++i) {\n      cmut(AQ, i, gram_matrix);\n      is_comp = compatible(star.qv(i), gram_matrix);\n    }\n    result = is_comp && semipos(AQ);\n    if (result) {\n      cartan = AQ;\n    }\n  }\n  return {result, cartan};\n}\n/* Check if a semipositive cartan matrix is fully compatible with the quiver. */\nbool check_compatible(cluster::QuiverMatrix const& q,\n                      arma::Mat<int> const& AQ,\n                      std::ostream& os = std::cout) {\n  bool result = true;\n  const MutationStar star(q);\n  arma::Mat<int> gram_matrix(q.num_rows(), q.num_cols());\n\n  CompatibleCartan compatible;\n  if (!compatible(q, AQ)) {\n    os << \"Initial matrix not compatible\" << os.widen('\\n');\n    result = false;\n  }\n  CartanMutator cmut(q);\n  int_fast16_t ncols = AQ.n_cols;\n  for (int_fast16_t i = 0; i < ncols; ++i) {\n    cmut(AQ, i, gram_matrix);\n    if (!compatible(star.qv(i), gram_matrix)) {\n      os << \"Mutation at \" << i << \" not compatible\" << os.widen('\\n');\n      result = false;\n    }\n  }\n  return result;\n}\n/**\n * Check if the semipositive quasi-Cartan matrix AQ is fully compatible with the\n * given quiver.\n *\n * To check if it is, the Cartan is mutated in every possible direction, and for\n * each mutation is checked to be a companion of the corresponding mutated\n * quiver.\n */\nbool repeat_check_compatible(cluster::QuiverMatrix const& q,\n                             MutationStar const& star,\n                             arma::Mat<int> const& AQ) {\n  static arma::Mat<int> gram_matrix;\n  bool result = true;\n  gram_matrix.set_size(q.num_rows(), q.num_cols());\n\n  CompatibleCartan compatible;\n  result = compatible(q, AQ);\n\n  CartanMutator cmut(q);\n  int_fast16_t ncols = AQ.n_cols;\n  for (int_fast16_t i = 0; result && i < ncols; ++i) {\n    cmut(AQ, i, gram_matrix);\n    result = compatible(star.qv(i), gram_matrix);\n  }\n  return result;\n}\n/**\n * Check whether the provided quasi-Cartan matrix is a companion of the given\n * quiver.\n *\n * The Cartan is provided as a QuiverMatrix, so will be converted into an arma\n * matrix. This will involve some allocation.\n */\nbool check_compatible(cluster::QuiverMatrix const& q,\n                      cluster::QuiverMatrix const& cartan,\n                      std::ostream& os = std::cout) {\n  arma::Mat<int> const AQ = util::to_arma(cartan);\n  bool result = check_compatible(q, AQ, os);\n  return result;\n}\n/**\n * Compute all fully-compatible, semipositive quasi-Cartan companions of the\n * given quiver. These Cartan matrices are returned in a vector.\n *\n * Only distinct, i.e. non-equivalent, Cartan matrices will be returned. (Where\n * equivalence is given by flipping signs at a vertex.)\n */\nstd::vector<arma::Mat<int>> all_compatible(cluster::QuiverMatrix const& q) {\n  auto cartan_iter = get_cartan_iterator(q);\n  MutationStar const star(q);\n  CartanEquiv equiv;\n  SemiPositiveFilter semipos;\n\n  std::vector<arma::Mat<int>> result;\n  result.reserve(2);\n\n  do {\n    auto const& first = cartan_iter.next();\n    if (repeat_check_compatible(q, star, first) && semipos(first)) {\n      result.push_back(first);\n    }\n  } while (result.empty() && cartan_iter.has_next());\n\n  if (!result.empty()) {\n    while (cartan_iter.has_next()) {\n      auto const& n = cartan_iter.next();\n      if (repeat_check_compatible(q, star, n) && semipos(n) &&\n          std::find_if(result.begin(), result.end(),\n                       [&n, &equiv](arma::Mat<int> const& c) {\n                         return equiv(c, n);\n                       }) == result.end()) {\n        result.push_back(n);\n      }\n    }\n  }\n  return result;\n}\n/**\n * Check whether all fully-compatible, semi-positive quasi-Cartan companions of\n * the given quiver are equivalent (up to flipping signs at vertices). If not\n * all the possble companions are printed to the supplied ostream.\n */\nbool check_all_compatible_equiv(cluster::QuiverMatrix const& q,\n                                std::ostream& os = std::cout) {\n  auto compatible_cartans = all_compatible(q);\n  bool all_equiv = compatible_cartans.size() == 1;\n\n  if (!all_equiv) {\n    for (auto const& n : compatible_cartans) {\n      n.print(os, \"Compatible:\");\n    }\n  }\n  return all_equiv;\n}\n}\n}\nenum Func { ListCompatible, SameCompatible, CheckSingle, CompatibleEquiv };\nvoid usage() {\n  std::cout << \"qvrefl -cels [-m matrix] [-i in_file] [-a cartan]\"\n            << std::cout.widen('\\n');\n  std::cout << \"  -m Specify matrix to find quasi-Cartan companions of\"\n            << std::cout.widen('\\n');\n  std::cout << \"  -i Specify input file of matrices to read\"\n            << std::cout.widen('\\n');\n  std::cout << \"  -c Check the whole mutation class of the matrix (only with \"\n               \"-l or -s)\"\n            << std::cout.widen('\\n');\n  std::cout << \"  -e Check that all fully compatible cartans are equivalent\"\n            << std::cout.widen('\\n');\n  std::cout << \"  -l List the first quasi-Cartan serving each vertex\"\n            << std::cout.widen('\\n');\n  std::cout << \"  -s Check if there is a quasi-Cartan serving all vertices\"\n            << std::cout.widen('\\n');\n  std::cout\n      << \"  -a Specify a cartan matrix to check whether it serves every vertex\"\n      << std::cout.widen('\\n');\n  std::cout.flush();\n}\nint main(int argc, char* argv[]) {\n  std::string matrix;\n  std::string cartan;\n  Func function = Func::ListCompatible;\n  std::string input;\n  bool mut_class = false;\n  int c;\n  while ((c = getopt(argc, argv, \"elsm:i:hca:\")) != -1) {\n    switch (c) {\n      case 'e':\n        function = Func::CompatibleEquiv;\n        break;\n      case 'm':\n        matrix = optarg;\n        break;\n      case 'a':\n        cartan = optarg;\n        function = Func::CheckSingle;\n        break;\n      case 'l':\n        function = Func::ListCompatible;\n        break;\n      case 's':\n        function = Func::SameCompatible;\n        break;\n      case 'i':\n        input = optarg;\n        break;\n      case 'c':\n        mut_class = true;\n        break;\n      case 'h':\n      case '?':\n      default:\n        usage();\n        return 1;\n    }\n  }\n  if (matrix.length() < 4 && input.empty()) {\n    usage();\n    return 2;\n  }\n  if (function == Func::ListCompatible) {\n    if (matrix.length() > 0) {\n      if (mut_class) {\n        cluster::EquivQuiverMatrix q(matrix);\n        cluster::EquivMutationClassLoader cl(q);\n        while (cl.has_next()) {\n          auto quiver = cl.next_ptr();\n          std::cout << *quiver << \":\" << std::cout.widen('\\n');\n          refl::output_serving_cartans(*quiver);\n        }\n      } else {\n        cluster::QuiverMatrix q(matrix);\n        refl::output_serving_cartans(q);\n      }\n    } else {\n      std::ifstream inf;\n      inf.open(input);\n      if (!inf.is_open()) {\n        std::cerr << \"Could not open file \" << input << std::endl;\n        return 1;\n      }\n      cluster::StreamIterator<cluster::QuiverMatrix> iter(inf);\n      while (iter.has_next()) {\n        auto quiver = iter.next();\n        std::cout << *quiver << std::cout.widen('\\n');\n        refl::output_serving_cartans(*quiver);\n      }\n    }\n  } else if (function == Func::SameCompatible) {\n    if (matrix.length() > 0) {\n      if (mut_class) {\n        cluster::EquivQuiverMatrix q(matrix);\n        cluster::EquivMutationClassLoader cl(q);\n        while (cl.has_next()) {\n          auto quiver = cl.next_ptr();\n          bool result = refl::first_compatible_cartan(*quiver).first;\n          std::cout << (result ? \"True: \" : \"False: \") << *quiver\n                    << std::cout.widen('\\n');\n        }\n      } else {\n        cluster::QuiverMatrix q(matrix);\n        auto result = refl::first_compatible_cartan(q);\n        std::cout << (result.first ? result.second : \"False\")\n                  << std::cout.widen('\\n');\n      }\n    } else {\n      std::ifstream inf;\n      inf.open(input);\n      if (!inf.is_open()) {\n        std::cerr << \"Could not open file \" << input << std::endl;\n        return 1;\n      }\n      cluster::StreamIterator<cluster::QuiverMatrix> iter(inf);\n      while (iter.has_next()) {\n        auto quiver = iter.next();\n        bool result = refl::first_compatible_cartan(*quiver).first;\n        std::cout << (result ? \"True: \" : \"False: \") << *quiver\n                  << std::cout.widen('\\n');\n      }\n    }\n  } else if (function == Func::CheckSingle) {\n    if (matrix.empty() || cartan.empty()) {\n      usage();\n      return 4;\n    }\n    refl::check_compatible(cluster::QuiverMatrix{matrix},\n                           cluster::QuiverMatrix{cartan});\n  } else if (function == Func::CompatibleEquiv) {\n    if (!matrix.empty()) {\n      std::cout << std::boolalpha << refl::check_all_compatible_equiv(\n                                         cluster::QuiverMatrix{matrix})\n                << std::cout.widen('\\n');\n    } else if (!input.empty()) {\n      std::ifstream inf;\n      inf.open(input);\n      if (!inf.is_open()) {\n        std::cerr << \"Could not open file \" << input << std::endl;\n        return 1;\n      }\n      cluster::StreamIterator<cluster::QuiverMatrix> iter(inf);\n      while (iter.has_next()) {\n        auto quiver = iter.next();\n        std::cout << std::boolalpha << refl::check_all_compatible_equiv(*quiver)\n                  << \": \" << *quiver << std::cout.widen('\\n');\n      }\n    } else {\n      usage();\n      return 4;\n    }\n  } else {\n    usage();\n  }\n  std::cout.flush();\n  return 0;\n}\n", "meta": {"hexsha": "04b8d85b343748f54ae584c60359d7932b72367b", "size": 13755, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/qvrefl.cc", "max_stars_repo_name": "jwlawson/qvrefl", "max_stars_repo_head_hexsha": "e843c48837949c5bb76d66959530e7cd55fec0ec", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/qvrefl.cc", "max_issues_repo_name": "jwlawson/qvrefl", "max_issues_repo_head_hexsha": "e843c48837949c5bb76d66959530e7cd55fec0ec", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/qvrefl.cc", "max_forks_repo_name": "jwlawson/qvrefl", "max_forks_repo_head_hexsha": "e843c48837949c5bb76d66959530e7cd55fec0ec", "max_forks_repo_licenses": ["Apache-2.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.6722090261, "max_line_length": 80, "alphanum_fraction": 0.6134496547, "num_tokens": 3581, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.46394096387734723}}
{"text": "/* Copyright Institute of Sound and Vibration Research - All rights reserved */\n\n#include <libefl/vector_functions.hpp>\n#include <libefl/vector_functions_reference.hpp>\n\n#include <libefl/aligned_array.hpp>\n\n#include <boost/test/unit_test.hpp>\n\n#include <algorithm>\n#include <cmath>\n#include <complex>\n#include <iostream>\n#include <valarray>\n\nnamespace visr\n{\nnamespace rbbl\n{\nnamespace test\n{\n            \nBOOST_AUTO_TEST_CASE( complexMultiply1 )\n{\n  const std::size_t alignment = 0;\n\n  std::size_t vecSize = 27;\n  efl::AlignedArray < std::complex<float> > a( vecSize, alignment );\n  efl::AlignedArray < std::complex<float> > b( vecSize, alignment );\n\n  efl::AlignedArray < std::complex<float> > c( vecSize, alignment );\n  efl::AlignedArray < std::complex<float> > reference( vecSize, alignment );\n\n\n  for( std::size_t runIdx( 0 ); runIdx < vecSize; ++runIdx )\n  {\n    a[runIdx] = std::complex<float>( static_cast<float>(runIdx), -static_cast<float>(runIdx) );\n    b[runIdx] = std::complex<float>( -2.0f*static_cast<float>(runIdx), 3.0f*static_cast<float>(runIdx) );\n  }\n\n  std::fill_n( c.data(), vecSize, 0.0f );\n\n  efl::ErrorCode const resRef = efl::reference::vectorMultiply( a.data( ), b.data( ), reference.data( ), vecSize, alignment );\n  BOOST_CHECK( resRef == efl::noError );\n\n  efl::ErrorCode const res = efl::vectorMultiply( a.data(), b.data(), c.data(), vecSize, alignment );\n  BOOST_CHECK( res == efl::noError );\n\n  efl::AlignedArray < std::complex<float> > ref( vecSize, alignment );\n  std::transform( a.data( ), a.data( ) + vecSize, b.data( ), ref.data( ), [=]( std::complex<float> const & x, std::complex<float> const & y ) { return x * y; } );\n\n  for( std::size_t vecIdx( 0 ); vecIdx < vecSize; ++vecIdx )\n  {\n    std::cout << \"c[\" << vecIdx << \"]: \" << ref[vecIdx] << \" : \" << reference[vecIdx] << \" : \" << c[vecIdx] << std::endl;\n  }\n}\n\nBOOST_AUTO_TEST_CASE( complexMultiplyConstant )\n{\n  const std::size_t alignment = 2;\n\n  std::size_t vecSize = 23;\n  efl::AlignedArray < std::complex<float> > a( vecSize, alignment );\n  std::complex<float> const c = { 0.385f, -0.75f};\n\n  efl::AlignedArray < std::complex<float> > result( vecSize, alignment );\n  efl::AlignedArray < std::complex<float> > reference( vecSize, alignment );\n\n  for( std::size_t runIdx( 0 ); runIdx < vecSize; ++runIdx )\n  {\n    a[runIdx] = std::complex<float>( static_cast<float>(runIdx), -static_cast<float>(runIdx) );\n  }\n\n  efl::ErrorCode const resRef = efl::reference::vectorMultiplyConstantAddInplace( c, a.data( ), reference.data( ), vecSize, alignment );\n  BOOST_CHECK( resRef == efl::noError );\n\n  efl::ErrorCode const res = efl::vectorMultiplyConstantAddInplace( c, a.data(), result.data(), vecSize, alignment );\n  BOOST_CHECK( res == efl::noError );\n\n  for( std::size_t vecIdx( 0 ); vecIdx < vecSize; ++vecIdx )\n  {\n    std::cout << vecIdx << \": \" << reference[vecIdx] << \" : \" << result[vecIdx] << std::endl;\n  }\n\n  for( std::size_t vecIdx( 0 ); vecIdx < vecSize; ++vecIdx )\n  {\n    BOOST_CHECK_CLOSE( std::abs(result[vecIdx] - reference[vecIdx]), 0.0f, 1.0e-6 );\n  }\n}\n\n} // namespace test\n} // namespace rbbl\n} // namespace visr\n", "meta": {"hexsha": "8063a24be8771b694d88896b1abc1da9156bc07a", "size": 3124, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/libefl/test/complex_multiply.cpp", "max_stars_repo_name": "s3a-spatialaudio/VISR", "max_stars_repo_head_hexsha": "55f6289bc5058d4898106f3520e1a60644ffb3ab", "max_stars_repo_licenses": ["ISC"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2019-03-12T14:52:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T01:16:23.000Z", "max_issues_repo_path": "src/libefl/test/complex_multiply.cpp", "max_issues_repo_name": "s3a-spatialaudio/VISR", "max_issues_repo_head_hexsha": "55f6289bc5058d4898106f3520e1a60644ffb3ab", "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/libefl/test/complex_multiply.cpp", "max_forks_repo_name": "s3a-spatialaudio/VISR", "max_forks_repo_head_hexsha": "55f6289bc5058d4898106f3520e1a60644ffb3ab", "max_forks_repo_licenses": ["ISC"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-08-11T12:53:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-22T10:08:08.000Z", "avg_line_length": 33.2340425532, "max_line_length": 162, "alphanum_fraction": 0.6552496799, "num_tokens": 942, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911057, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.4639409573369552}}
{"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/ParallelSTL.h\"\n#include \"llvm/Support/CommandLine.h\"\n#include \"Lonestar/BoilerPlate.h\"\n\n#include <gmpxx.h>\n//#include <givaro/givgfq.h>\n//#include <givaro/StaticElement.h>\n\n#include <boost/spirit/include/phoenix_core.hpp>\n#include <boost/spirit/include/phoenix_operator.hpp>\n#include <boost/spirit/include/phoenix_fusion.hpp>\n#include <boost/spirit/include/phoenix_stl.hpp>\n#include <boost/spirit/include/phoenix_object.hpp>\n#include <boost/spirit/include/support_istream_iterator.hpp>\n#include <boost/spirit/include/qi.hpp>\n#include <boost/fusion/include/adapt_struct.hpp>\n#include <boost/bind.hpp>\n#include <boost/utility.hpp>\n\n#include <fstream>\n#include <map>\n#include <numeric>\n#include <algorithm>\n\nnamespace cll = llvm::cl;\n\nstatic const char* name = \"Buchberger Algorithm\";\nstatic const char* desc =\n    \"Generates Groebner basis for polynomial ideal using Buchberger Algorithm\";\nstatic const char* url = 0;\n\nenum MonomialOrder { lex, grevlex };\n\nstatic cll::opt<std::string> filename(cll::Positional,\n                                      cll::desc(\"<input file>\"), cll::Required);\nstatic cll::opt<MonomialOrder> monomialOrder(\n    cll::desc(\"Monomial order:\"),\n    cll::values(clEnumVal(lex, \"lexicographic\"),\n                clEnumVal(grevlex, \"graded reverse lexicographic\"),\n                clEnumValEnd),\n    cll::init(grevlex));\n\n#if 0\n//! Unfortunate pun\nstruct GaloisField {\n  typedef Givaro::GFqDom<long> Field;\n  typedef Field::Element element_type;\n  Field F;\n\n  GaloisField(): F(2, 1) { }\n\n  void init() { }\n\n  void inverse(element_type& a) const {\n    F.invin(a);\n  }\n  \n  void add(element_type& a, const element_type& b) const {\n    F.addin(a, b);\n  }\n\n  void subtract(element_type& a, const element_type& b) const {\n    F.subin(a, b);\n  }\n\n  void negate(element_type& a) const {\n    F.negin(a);\n  }\n\n  void divide(element_type& a, const element_type& b) const {\n    F.divin(a, b);\n  }\n\n  void multiply(element_type& a, const element_type& b) const {\n    F.mulin(a, b);\n  }\n\n  void assign(element_type& a, const element_type& b) const {\n    F.assign(a, b);\n  }\n\n  void assignOne(element_type& a) const {\n    F.assign(a, F.one);\n  }\n\n  int sign(const element_type& a) const {\n    return neq(a, 0) ? 1 : 0;\n  }\n\n  bool neq(const element_type& a, const element_type& b) const {\n    return a != b;\n  }\n\n  void write(std::ostream& out, const element_type& a) const {\n    out << a;\n  }\n};\n#endif\n\nstruct RationalField {\n  typedef mpq_class element_type;\n\n  void init() {}\n\n  void inverse(element_type& a) const { a = 1 / a; }\n\n  void add(element_type& a, const element_type& b) const { a += b; }\n\n  void subtract(element_type& a, const element_type& b) const { a -= b; }\n\n  void negate(element_type& a) const { a = -a; }\n\n  void divide(element_type& a, const element_type& b) const { a /= b; }\n\n  void multiply(element_type& a, const element_type& b) const { a *= b; }\n\n  void assign(element_type& a, const element_type& b) const { a = b; }\n\n  void assignOne(element_type& a) const { a = 1; }\n\n  int sign(const element_type& a) const { return sgn(a); }\n\n  bool neq(const element_type& a, const element_type& b) const {\n    return a != b;\n  }\n\n  void write(std::ostream& out, const element_type& a) const {\n    out << a.get_str();\n  }\n};\n\ntypedef RationalField Field;\n// typedef GaloisField Field;\ntypedef Field::element_type number;\n\nField TheField;\n\ntemplate <class Order, class Alloc>\nclass Ring;\n\n//! Weights to ease vectorization of lexicographic sorting\nstatic int powersOfTwo[16] __attribute__((__aligned__(16)));\n\nstruct Term {\n  typedef char exp_type;\n  typedef char __attribute__((__aligned__(16))) * __restrict__ exp_ptr_type;\n\nprivate:\n  template <class Order, class Alloc>\n  friend class Ring;\n\n  Field::element_type m_coef;\n  exp_ptr_type m_exps;\n  int m_totalDegree;\n\npublic:\n  Term() : m_coef(1), m_exps(NULL), m_totalDegree(0) {}\n\n  Field::element_type& coef() { return m_coef; }\n  const Field::element_type& coef() const { return m_coef; }\n\n  exp_type& exp(int i) { return m_exps[i]; }\n  const exp_type& exp(int i) const { return m_exps[i]; }\n\n  int totalDegree() const { return m_totalDegree; }\n\n  exp_ptr_type const& exps() const { return m_exps; }\n  exp_ptr_type& exps() { return m_exps; }\n\n  //! Compute LCM\n  template <class R>\n  void makeLcm(const Term& a, const Term& b, R& ring) {\n    // Vectorized.\n    // GCC 4.7 vectorizer prefers (1) over (2)\n    int N = ring.numVars();\n    for (int i = 0; i < N; ++i) { // (1)\n      // for (int i = 0; i < ring.numVars(); ++i) { // (2)\n      m_exps[i] = std::max(a.m_exps[i], b.m_exps[i]);\n    }\n  }\n\n  template <class R>\n  bool equals(const Term& b, R& ring) {\n    // TODO vectorize\n    int N = ring.numVars();\n    for (int i = 0; i < N; ++i) {\n      if (b.exp(i) != exp(i))\n        return false;\n    }\n    return true;\n  }\n\n  //! a | b ?\n  template <class R>\n  bool divides(const Term& b, const R& ring) const {\n    // TODO vectorize\n    for (int i = 0; i < ring.numVars(); ++i) {\n      if (b.exp(i) < exp(i))\n        return false;\n    }\n    return true;\n  }\n\n  //! Relatively prime?\n  template <class R>\n  bool relPrime(const Term& b, const R& ring) const {\n    // TODO vectorize\n    for (int i = 0; i < ring.numVars(); ++i) {\n      if (exp(i) && b.exp(i))\n        return false;\n    }\n    return true;\n  }\n};\n\n//! Sequence of terms\nclass Poly {\n  // TODO: more bucketed representations!!!\n  typedef std::vector<Term*> Terms;\n  Terms terms;\n  int m_totalDegree;\n\npublic:\n  typedef Terms::iterator iterator;\n  typedef Terms::const_iterator const_iterator;\n\n  Poly() : m_totalDegree(0) {}\n\n  int totalDegree() const { return m_totalDegree; }\n\n  const Term* head() const { return terms.front(); }\n\n  Term* head() { return terms.front(); }\n\n  const_iterator begin() const { return terms.begin(); }\n\n  const_iterator end() const { return terms.end(); }\n\n  iterator begin() { return terms.begin(); }\n\n  iterator end() { return terms.end(); }\n\n  void push(Term* t) {\n    terms.push_back(t);\n    m_totalDegree += t->totalDegree();\n  }\n\n  bool empty() const { return terms.empty(); }\n\n  //! f = f * s\n  template <class R>\n  void scaleBy(const Field::element_type& s, R& ring) {\n    for (iterator ii = begin(), ei = end(); ii != ei; ++ii) {\n      Term* t = *ii;\n      TheField.multiply(t->coef(), s);\n    }\n  }\n\n  //! f = f * a/b\n  template <class R>\n  void scaleBy(const Term& a, const Term& b, R& ring) {\n    Field::element_type s;\n    TheField.assign(s, a.coef());\n    TheField.divide(s, b.coef());\n\n    m_totalDegree = 0;\n\n    for (iterator ii = begin(), ei = end(); ii != ei; ++ii) {\n      Term* t = *ii;\n      // Vectorized.\n      for (int i = 0; i < ring.numVars(); ++i) {\n        assert(a.exp(i) >= b.exp(i));\n        t->exp(i) += a.exp(i) - b.exp(i);\n      }\n      TheField.multiply(t->coef(), s);\n      ring.generateTotalDegree(*t);\n      m_totalDegree += t->totalDegree();\n    }\n  }\n};\n\nclass PolySet {\n  // TODO: better allocator\n  typedef std::vector<Poly*> Polys;\n\n  Polys polys;\n\npublic:\n  typedef Polys::iterator iterator;\n  typedef Polys::const_iterator const_iterator;\n\n  void push(Poly* p) { polys.push_back(p); }\n\n  iterator begin() { return polys.begin(); }\n\n  iterator end() { return polys.end(); }\n\n  const_iterator begin() const { return polys.begin(); }\n\n  const_iterator end() const { return polys.end(); }\n};\n\ntemplate <class Order, class Alloc = std::allocator<char>>\nclass Ring : private boost::noncopyable {\nprivate:\n  Order order;\n  Alloc m_alloc;\n  int m_numVars;\n  std::list<Poly*> polys;\n  std::list<Term*> terms;\n\n  //! Sizeof Term plus padding and space for exps\n  size_t sizeofTerm() const {\n    return sizeof(Term) + 15 + m_numVars * sizeof(Term::exp_type);\n  }\n\n  typedef Term::exp_type* exps_ptr_t;\n\n  //! Find 16-byte aligned address after ptr\n  exps_ptr_t expsPtr(const Term* ptr) const {\n    return reinterpret_cast<exps_ptr_t>(((uintptr_t)(ptr + 1) + 15) & ~0x0F);\n  }\n\npublic:\n  const static int kBlockSize = 16 / sizeof(Term::exp_type);\n\n  template <class AllocNew>\n  struct realloc {\n    typedef Ring<Order, AllocNew> other;\n  };\n\n  Ring(int numVars, const Alloc& alloc = Alloc()) : m_alloc(alloc) {\n    m_numVars = ((numVars + kBlockSize - 1) / kBlockSize) * kBlockSize;\n  }\n\n  ~Ring() {\n    for (std::list<Poly*>::iterator ii = polys.begin(), ei = polys.end();\n         ii != ei; ++ii) {\n      (*ii)->~Poly();\n      m_alloc.deallocate(reinterpret_cast<char*>(*ii), sizeof(Poly));\n    }\n    for (std::list<Term*>::iterator ii = terms.begin(), ei = terms.end();\n         ii != ei; ++ii) {\n      (*ii)->~Term();\n      m_alloc.deallocate(reinterpret_cast<char*>(*ii), sizeofTerm());\n    }\n  }\n\n  // TODO\n  Ring tempRing() const { return *this; }\n\n  //! For ease of vectorization, this will always be a multiple of blockSize\n  int numVars() const { return m_numVars; }\n\n  bool gt(const Term& a, const Term& b) const { return order.gt(a, b, *this); }\n\n  Poly& makePoly(const Poly& p = Poly()) {\n    Poly* ptr = reinterpret_cast<Poly*>(m_alloc.allocate(sizeof(Poly)));\n    new (ptr) Poly();\n    for (Poly::const_iterator ii = p.begin(), ei = p.end(); ii != ei; ++ii) {\n      const Term* t = *ii;\n      ptr->push(&makeTerm(*t));\n    }\n    polys.push_back(ptr);\n    return *ptr;\n  }\n\n  Term& makeTerm(const Term& t = Term()) {\n    Term* ptr = reinterpret_cast<Term*>(m_alloc.allocate(sizeofTerm()));\n    new (ptr) Term(t);\n    ptr->m_exps = expsPtr(ptr);\n\n    if (t.exps() != NULL) {\n      memcpy(ptr->m_exps, t.exps(), m_numVars * sizeof(Term::exp_type));\n    } else {\n      memset(ptr->m_exps, 0, m_numVars * sizeof(Term::exp_type));\n    }\n    terms.push_back(ptr);\n    return *ptr;\n  }\n\n  void generateTotalDegree(Term& t) {\n    // Vectorized.\n    // GCC 4.7 vectorizer prefers (1) over (2)\n    int sum               = 0;\n    Term::exp_ptr_type ii = t.exps();\n    for (int i = 0; i < numVars(); ++i) // (1)\n      sum += ii[i];\n    t.m_totalDegree = sum;\n    // std::accumulate(t.exps(), t.exps() + numVars(), 0, std::plus<int>()); //\n    // (2)\n  }\n\n  void write(std::ostream& out, const Term& t,\n             const std::vector<std::string>* idMap = NULL) const {\n    if (TheField.sign(t.coef()) >= 0)\n      out << \"+\";\n    TheField.write(out, t.coef());\n\n    for (int i = 0; i < numVars(); ++i) {\n      int exp = t.exp(i);\n      if (exp == 0)\n        continue;\n      out << \" \";\n      if (idMap)\n        out << (*idMap)[i];\n      else\n        out << \"x\" << i;\n      if (exp > 1)\n        out << \"^\" << exp;\n    }\n  }\n\n  void write(std::ostream& out, const Term* t,\n             const std::vector<std::string>* idMap = NULL) const {\n    write(out, *t, idMap);\n  }\n\n  void write(std::ostream& out, const Poly& p,\n             const std::vector<std::string>* idMap = NULL) const {\n    for (Poly::const_iterator ii = p.begin(), ei = p.end(); ii != ei; ++ii) {\n      write(out, *ii, idMap);\n    }\n  }\n\n  void write(std::ostream& out, const PolySet& polys,\n             const std::vector<std::string>* idMap = NULL) const {\n    for (PolySet::const_iterator ii = polys.begin(), ei = polys.end(); ii != ei;\n         ++ii) {\n      write(out, **ii, idMap);\n      if (ii + 1 != ei)\n        out << \", \";\n    }\n  }\n\n  //! Rank under Buchberger's normal selection strategy\n  int normalRank(const Poly& f, const Poly& g) const {\n    const Term* fh = f.head();\n    const Term* gh = g.head();\n    int retval     = 0;\n\n    // Vectorized.\n    for (int i = 0; i < numVars(); ++i) {\n      retval += std::max(fh->exp(i), gh->exp(i));\n    }\n\n    return retval;\n  }\n\n  //! Rank pairs using sugar strategy\n  int rankPair(const Poly& f, const Poly& g) const {\n    const Term* fh = f.head();\n    const Term* gh = g.head();\n    int retval     = std::max(f.totalDegree() - fh->totalDegree(),\n                          g.totalDegree() - gh->totalDegree());\n    int n          = normalRank(f, g);\n    // prefer pairs with least sugar component, breaking ties with normalRank\n    int sugar = retval + n;\n    return (sugar << 8) | (n & 0xFF);\n  }\n};\n\nclass LexOrder {\n  template <class R>\n  bool gtSimple(const Term& a, const Term& b, const R& ring) const {\n    for (int i = 0; i < ring.numVars(); ++i) {\n      if (a.exp(i) < b.exp(i))\n        return false;\n      else if (a.exp(i) > b.exp(i))\n        return true;\n    }\n    return false;\n  }\n\n  template <class R>\n  bool gtVectorized(const Term& a, const Term& b, const R& ring) const {\n    Term::exp_ptr_type aa = a.exps();\n    Term::exp_ptr_type bb = b.exps();\n    int* pp               = powersOfTwo;\n\n    for (int block = 0; block < ring.numVars(); block += R::kBlockSize) {\n      // Sigh. In GCC 4.7 this inner loop (1) is not vectorized because of\n      // the condition (2)\n      int smaller = 0;\n      int larger  = 0;\n      for (int i = 0; i < R::kBlockSize; ++i) { // (1)\n        int idx = block + i;\n        smaller += aa[idx] < bb[idx] ? pp[R::kBlockSize - i] : 0;\n        larger += aa[idx] > bb[idx] ? pp[R::kBlockSize - i] : 0;\n      }\n      if (smaller == larger) // (2)\n        continue;\n      return larger > smaller;\n    }\n\n    return false;\n  }\n\npublic:\n  template <class R>\n  bool gt(const Term& a, const Term& b, const R& ring) const {\n    return gtVectorized(a, b, ring);\n  }\n};\n\nclass GrevlexOrder {\n  template <class R>\n  bool gtSimple(const Term& a, const Term& b, const R& ring) const {\n    if (a.totalDegree() != b.totalDegree())\n      return a.totalDegree() > b.totalDegree();\n\n    for (int i = ring.numVars() - 1; i >= 0; --i) {\n      if (a.exp(i) < b.exp(i))\n        return true;\n      else if (a.exp(i) > b.exp(i))\n        return false;\n    }\n    return false;\n  }\n\n  template <class R>\n  bool gtVectorized(const Term& a, const Term& b, const R& ring) const {\n    if (a.totalDegree() != b.totalDegree())\n      return a.totalDegree() > b.totalDegree();\n\n    Term::exp_ptr_type aa = a.exps();\n    Term::exp_ptr_type bb = b.exps();\n    int* pp               = powersOfTwo;\n\n    for (int block = ring.numVars() - 1; block >= 0; block -= R::kBlockSize) {\n      // Sigh. In GCC 4.7 this inner loop (1) is not vectorized because of\n      // the condition (2)\n      int smaller = 0;\n      int larger  = 0;\n      for (int i = 0; i < R::kBlockSize; ++i) { // (1)\n        int idx = block - i;\n        smaller += aa[idx] < bb[idx] ? pp[R::kBlockSize - i] : 0;\n        larger += aa[idx] > bb[idx] ? pp[R::kBlockSize - i] : 0;\n      }\n      if (smaller == larger) // (2)\n        continue;\n      return larger > smaller;\n    }\n\n    return false;\n  }\n\npublic:\n  template <class R>\n  bool gt(const Term& a, const Term& b, const R& ring) const {\n    return gtVectorized(a, b, ring);\n  }\n};\n\nstruct PolyPair {\n  Poly* a;\n  Poly* b;\n  Term* lcm;\n  int index;\n  bool m_useless;\n  PolyPair(Poly* _a, Poly* _b, Term* _lcm, int _index = 0)\n      : a(_a), b(_b), lcm(_lcm), index(_index), m_useless(false) {}\n  bool useless() const { return m_useless; }\n  void makeUseless() { m_useless = true; }\n};\n\n//! r = a - b\ntemplate <class R>\nPoly* subtract(const Poly& a, const Poly& b, R& ring) {\n  Poly* result            = &ring.makePoly();\n  Poly::const_iterator aa = a.begin(), ea = a.end();\n  Poly::const_iterator bb = b.begin(), eb = b.end();\n\n  while (aa != ea && bb != eb) {\n    Term* a = *aa;\n    Term* b = *bb;\n    Term t;\n    if (ring.gt(*a, *b)) {\n      t = Term(*a);\n      ++aa;\n    } else if (ring.gt(*b, *a)) {\n      t = Term(*b);\n      TheField.negate(t.coef());\n      ++bb;\n    } else {\n      t = Term(*a);\n      TheField.subtract(t.coef(), b->coef());\n      ++aa;\n      ++bb;\n    }\n    if (TheField.neq(t.coef(), 0)) {\n      result->push(&ring.makeTerm(t));\n    }\n  }\n  for (; aa != ea; ++aa) {\n    result->push(*aa);\n  }\n  for (; bb != eb; ++bb) {\n    Term* b = *bb;\n    Term t(*b);\n    TheField.negate(t.coef());\n    assert(TheField.neq(t.coef(), 0));\n    result->push(&ring.makeTerm(t));\n  }\n  return result;\n}\n\n//! Compute s-polynomial.\n//! spoly(f,g) = f * lcm/LT(f) - g * lcm/LT(g) where lcm = LCM(LM(f), LM(g))\ntemplate <class R>\nPoly* spoly(const Term& lcm, const Poly& f, const Poly& g, R& ring) {\n  // ff = f * lcm/LT(f)\n  Poly& ff = ring.makePoly(f);\n  ff.scaleBy(lcm, *f.head(), ring);\n  // gg = g * lcm/LT(g)\n  Poly& gg = ring.makePoly(g);\n  gg.scaleBy(lcm, *g.head(), ring);\n\n  return subtract(ff, gg, ring);\n};\n\n//! Reduce f with respect to polys.\n//! Not canonical unless polys is groebner basis (obvs)\ntemplate <class R>\nPoly* reduce(const Poly& f, const PolySet& polys, R& ring) {\n  //  std::cerr << \"    \"; ring.write(std::cerr, f);\n\n  const Poly* cur         = &f;\n  Poly::const_iterator ff = cur->begin(), ef = cur->end();\n\n  while (ff != ef) {\n    bool reduced = false;\n\n    for (PolySet::const_iterator pp = polys.begin(), ep = polys.end(); pp != ep;\n         ++pp) {\n      const Poly* p = *pp;\n\n      // when we are doing inter reduction, i.e., f reduce G when f \\in G, skip\n      // ourselves\n      if (&f == p)\n        continue;\n\n      // Right now we never delete terms reduced to zero by interReduce() so\n      // ignore them here\n      if (p->empty())\n        continue;\n\n      const Term* ph = p->head();\n\n      if (!ph->divides(**ff, ring))\n        continue;\n\n      //      std::cerr << \" (\"; ring.write(std::cerr, *ph); std::cerr << \"|\";\n      //      ring.write(std::cerr, **ff); std::cerr << \")\";\n      // cur = cur - p * ff/ph\n      Poly& g = ring.makePoly(*p);\n      g.scaleBy(**ff, *ph, ring);\n      cur = subtract(*cur, g, ring);\n\n      ff = cur->begin();\n      ef = cur->end();\n      //      std::cerr << \" => \"; ring.write(std::cerr, *cur);\n      reduced = true;\n      break;\n    }\n    if (!reduced)\n      ++ff;\n  }\n\n  //  std::cerr << \"\\n\";\n\n  return const_cast<Poly*>(cur);\n}\n\ngalois::Statistic bkUpdate(\"BKUpdate\");\ngalois::Statistic mfUpdate(\"MFUpdate\");\ngalois::Statistic bpUpdate(\"BPUpdate\");\n\n//! Updates basis with h, adds new pairs and marks some previous pairs as\n//! useless.\ntemplate <class R1, class R2, class Pushable>\nvoid update(Poly* h, PolySet& basis, galois::InsertBag<PolyPair>& pairs,\n            R1& localRing, R2& ring, Pushable& out) {\n  // Gebauer-Moeller criterion B_k\n  Term& lcm_t = localRing.makeTerm();\n  for (galois::InsertBag<PolyPair>::iterator ii = pairs.begin(),\n                                             ei = pairs.end();\n       ii != ei; ++ii) {\n    PolyPair& p = *ii;\n    if (p.useless())\n      continue;\n    if (!h->head()->divides(*p.lcm, localRing))\n      continue;\n    lcm_t.makeLcm(*h->head(), *p.a->head(), localRing);\n    if (lcm_t.equals(*p.lcm, localRing))\n      continue;\n    lcm_t.makeLcm(*h->head(), *p.b->head(), localRing);\n    if (lcm_t.equals(*p.lcm, localRing))\n      continue;\n    p.makeUseless();\n    bkUpdate += 1;\n  }\n\n  // Successive application of various deletion criteria\n  Term& lcm_hi = localRing.makeTerm();\n  Term& lcm_hj = localRing.makeTerm();\n  for (PolySet::const_iterator ii = basis.begin(), ei = basis.end(); ii != ei;\n       ++ii) {\n\n    // Buchberger's Product criterion\n    if (h->head()->relPrime(*(*ii)->head(), localRing)) {\n      bpUpdate += 1;\n      continue;\n    }\n\n    // Gebauer-Moeller criteria M and F\n    lcm_hi.makeLcm(*h->head(), *(*ii)->head(), localRing);\n    bool condM = false;\n    for (PolySet::const_iterator jj = ii + 1, ej = basis.end(); jj != ej;\n         ++jj) {\n      lcm_hj.makeLcm(*h->head(), *(*jj)->head(), localRing);\n      if (lcm_hj.divides(lcm_hi, localRing)) {\n        condM = true;\n        break;\n      }\n    }\n\n    if (!condM) {\n      Term& lcm = ring.makeTerm(lcm_hi);\n      out.push(&pairs.push(PolyPair(h, *ii, &lcm, ring.rankPair(*h, **ii))));\n    } else {\n      mfUpdate += 1;\n    }\n  }\n\n  basis.push(h);\n}\n\ngalois::Statistic zeroUpdate(\"ZeroUpdate\");\n\ntemplate <class R>\nstruct Process {\n  typedef typename R::template realloc<\n      galois::PerIterAllocTy::rebind<char>::other>::other LocalRing;\n\n  PolySet& basis;\n  galois::InsertBag<PolyPair>& pairs;\n  R& ring;\n\n  Process(PolySet& _basis, galois::InsertBag<PolyPair>& _pairs, R& r)\n      : basis(_basis), pairs(_pairs), ring(r) {}\n\n  void operator()(const PolyPair* p, galois::UserContext<PolyPair*>& ctx) {\n    if (p->useless()) {\n      return;\n    }\n\n    LocalRing localRing(ring.numVars(), ctx.getPerIterAlloc());\n\n    Poly* s = spoly(*p->lcm, *p->a, *p->b, localRing);\n    Poly* h = reduce(*s, basis, localRing);\n\n    if (!h->empty()) {\n      Poly* hh = &ring.makePoly(*h);\n      update(hh, basis, pairs, localRing, ring, ctx);\n    } else {\n      zeroUpdate += 1;\n    }\n  }\n};\n\ntemplate <class R>\nstruct Verifier {\n  PolySet& g;\n  R& ring;\n\n  Verifier(PolySet& _g, R& r) : g(_g), ring(r) {}\n\n  bool operator()(const PolyPair& p) {\n    // TODO opportunity for temporary\n    Poly* s = spoly(*p.lcm, *p.a, *p.b, ring);\n    Poly* h = reduce(*s, g, ring);\n    return !h->empty();\n  }\n};\n\ntemplate <class C, class R>\nvoid allPairs(const PolySet& ideal, C& c, R& ring) {\n  for (PolySet::const_iterator ii = ideal.begin(), ei = ideal.end(); ii != ei;\n       ++ii) {\n    for (PolySet::const_iterator jj = ideal.begin(), ej = ideal.end(); jj != ej;\n         ++jj) {\n      if (*ii == *jj)\n        continue;\n      if ((*ii)->empty() || (*jj)->empty())\n        continue;\n      Term& lcm = ring.makeTerm();\n      lcm.makeLcm(*(*ii)->head(), *(*jj)->head(), ring);\n      c.push(PolyPair(*ii, *jj, &lcm, ring.rankPair(**ii, **jj)));\n    }\n  }\n}\n\nstruct Indexer {\n  int operator()(const PolyPair& p) const { return p.index; }\n  int operator()(const PolyPair* p) const { return p->index; }\n};\n\ntemplate <class R>\nvoid interReduce(PolySet& polys, R& ring) {\n  for (PolySet::iterator ii = polys.begin(), ei = polys.end(); ii != ei; ++ii) {\n    Poly*& p      = *ii;\n    Poly* reduced = reduce(*p, polys, ring);\n    // TODO opportunity for temporary\n    boost::swap(p, reduced);\n    if (p->empty())\n      continue;\n    Field::element_type s(p->head()->coef());\n    TheField.inverse(s);\n    p->scaleBy(s, ring);\n  }\n}\n\ntemplate <class R>\nvoid buchberger(PolySet& ideal, PolySet& basis, R& ring) {\n  galois::InsertBag<PolyPair> pairs;\n  galois::InsertBag<PolyPair*> initial;\n\n  for (PolySet::iterator ii = ideal.begin(), ei = ideal.end(); ii != ei; ++ii) {\n    if ((*ii)->empty())\n      continue;\n    update(*ii, basis, pairs, ring, ring, initial);\n  }\n  using namespace galois::worklists;\n  typedef OrderedByIntegerMetric<Indexer, PerSocketChunkLIFO<8>> OBIM;\n  galois::for_each(initial.begin(), initial.end(),\n                   Process<R>(basis, pairs, ring), galois::wl<OBIM>());\n\n  interReduce(basis, ring);\n}\n\nnamespace parser {\nnamespace qi     = boost::spirit::qi;\nnamespace ascii  = boost::spirit::ascii;\nnamespace fusion = boost::fusion;\n\nstruct Coef {\n  typedef boost::variant<char, char> Sign;\n  Sign sign;\n  typedef boost::variant<fusion::vector<int, int>, int> Rational;\n  galois::optional<Rational> rational;\n};\n\nstruct Mono {\n  std::string id;\n  galois::optional<int> expo;\n};\n\nstruct Term {\n  Coef coef;\n  std::vector<Mono> monos;\n};\n\nstruct Poly {\n  std::vector<Term> terms;\n};\n} // namespace parser\n\n// Macros need to be used outside of namespace scope\n\nBOOST_FUSION_ADAPT_STRUCT(parser::Coef,\n                          (parser::Coef::Sign,\n                           sign)(galois::optional<parser::Coef::Rational>,\n                                 rational))\n\nBOOST_FUSION_ADAPT_STRUCT(parser::Mono,\n                          (std::string, id)(galois::optional<int>, expo))\n\nBOOST_FUSION_ADAPT_STRUCT(parser::Term,\n                          (parser::Coef, coef)(std::vector<parser::Mono>,\n                                               monos))\n\nBOOST_FUSION_ADAPT_STRUCT(parser::Poly, (std::vector<parser::Term>, terms))\n\nnamespace parser {\nnamespace qi     = boost::spirit::qi;\nnamespace ascii  = boost::spirit::ascii;\nnamespace fusion = boost::fusion;\n\n// +2xy^3 - z^3, ...\ntemplate <typename It>\nstruct PolySetGrammar\n    : qi::grammar<It, std::vector<parser::Poly>(), ascii::space_type> {\n  qi::rule<It, std::string(), ascii::space_type> id;\n  qi::rule<It, parser::Coef::Sign(), ascii::space_type> sign;\n  qi::rule<It, parser::Coef::Rational(), ascii::space_type> rational;\n  qi::rule<It, parser::Coef(), ascii::space_type> coef;\n  qi::rule<It, int(), ascii::space_type> expo;\n  qi::rule<It, parser::Mono(), ascii::space_type> mono;\n  qi::rule<It, parser::Term(), ascii::space_type> term;\n  qi::rule<It, std::vector<parser::Term>(), ascii::space_type> poly;\n  qi::rule<It, std::vector<parser::Poly>(), ascii::space_type> start;\n\n  PolySetGrammar() : PolySetGrammar::base_type(start, \"polynomial list\") {\n    // sign := + | -\n    sign %= qi::char_(\"+\") | qi::char_(\"-\");\n    sign.name(\"sign\");\n    // rational := (int / int) | int\n    rational %= (qi::int_ >> qi::lit(\"/\") > qi::int_) | qi::int_;\n    rational.name(\"rational\");\n    // coef := sign rational?\n    coef %= sign >> -rational;\n    coef.name(\"coefficent\");\n    // expo := ^ int\n    expo %= qi::lit(\"^\") > qi::int_;\n    expo.name(\"exponent\");\n    // mono := id expo?\n    id %= qi::lexeme[+ascii::alnum];\n    id.name(\"identifier\");\n    mono %= id >> -expo;\n    mono.name(\"mononomial\");\n    // term := coef \"*\"? (mono \"*\"?)*\n    term %= coef > -qi::lit(\"*\") >> *(mono >> -qi::lit(\"*\"));\n    term.name(\"term\");\n    // poly := term+\n    poly %= +term;\n    poly.name(\"polynomial\");\n    // start := poly (, poly)*\n    start %= poly % ',';\n\n    using boost::phoenix::construct;\n    using boost::phoenix::val;\n    qi::on_error<qi::fail>(start, std::cerr\n                                      << val(\"Error! Expecting \")\n                                      << qi::labels::_4 << val(\" here: \\\"\")\n                                      << construct<std::string>(qi::labels::_3,\n                                                                qi::labels::_2)\n                                      << val(\"\\\"\\n\"));\n  }\n};\n\n// Q[x y z w ...]\ntemplate <class It>\nstruct HeaderGrammar\n    : qi::grammar<It, std::vector<std::string>(), ascii::space_type> {\n  qi::rule<It, std::string(), ascii::space_type> id;\n  qi::rule<It, std::vector<std::string>(), ascii::space_type> start;\n\n  HeaderGrammar() : HeaderGrammar::base_type(start, \"Ring Definition\") {\n    id %= qi::lexeme[+ascii::alnum];\n    id.name(\"id\");\n    // Q[ <id> (, <id>)* ]\n    start %= qi::lit(\"Q[\") >> id % ',' >> qi::lit(\"]\");\n\n    using boost::phoenix::construct;\n    using boost::phoenix::val;\n    qi::on_error<qi::fail>(start, std::cerr\n                                      << val(\"Error! Expecting \")\n                                      << qi::labels::_4 << val(\" here: \\\"\")\n                                      << construct<std::string>(qi::labels::_3,\n                                                                qi::labels::_2)\n                                      << val(\"\\\"\\n\"));\n  }\n};\n\n//! A simple parser.\ntemplate <class Order>\nclass Parser : private boost::noncopyable {\n  typedef ::Term TheTerm;\n  typedef ::Poly ThePoly;\n  typedef Ring<Order> TheRing;\n  typedef std::map<std::string, int> NameMap;\n  typedef std::vector<std::string> IdMap;\n  NameMap nameMap;\n  IdMap idMap;\n  PolySet m_polys;\n  Order order;\n  TheRing* m_ring;\n\n  template <class It>\n  void readHeader(It begin, It end) {\n    HeaderGrammar<It> grammar;\n    bool r = qi::phrase_parse(begin, end, grammar, ascii::space, idMap);\n\n    if (!r || begin != end) {\n      std::cerr << \"Parse failure.\\n\";\n      abort();\n    }\n\n    // Parse header\n    for (IdMap::iterator ii = idMap.begin(), ei = idMap.end(); ii != ei; ++ii) {\n      if (nameMap.find(*ii) != nameMap.end()) {\n        std::cerr << \"Duplicate variable name: \" << *ii << \"\\n\";\n        abort();\n      }\n      int index    = nameMap.size();\n      nameMap[*ii] = index;\n    }\n  }\n\n  template <class It>\n  void readPolys(It begin, It end, std::vector<parser::Poly>& polys) {\n    PolySetGrammar<It> grammar;\n    bool r = qi::phrase_parse(begin, end, grammar, ascii::space, polys);\n    if (!r || begin != end) {\n      std::cerr << \"Parse failure at: \" << std::string(begin, end) << \"\\n\";\n      abort();\n    }\n  }\n\n  struct RationalVisitor : public boost::static_visitor<Field::element_type> {\n    Field::element_type operator()(const fusion::vector<int, int>& x) const {\n      Field::element_type a(fusion::at_c<0>(x));\n      Field::element_type b(fusion::at_c<1>(x));\n      TheField.divide(a, b);\n      return a;\n    }\n    Field::element_type operator()(const int& x) const {\n      return Field::element_type(x);\n    }\n  };\n\n  void parseCoef(const Coef& coef, Field::element_type& c) {\n    const char* sign = boost::get<char>(&coef.sign);\n    bool neg         = *sign == '-';\n\n    TheField.assign(c, 1);\n    if (coef.rational) {\n      c = boost::apply_visitor(RationalVisitor(), *coef.rational);\n    }\n    // c.canonicalize();\n    if (neg)\n      TheField.negate(c);\n  }\n\n  void parseMono(const Mono& mono, TheTerm& t) {\n    NameMap::iterator ii = nameMap.find(mono.id);\n    if (ii == nameMap.end()) {\n      std::cerr << \"Unknown variable name: \" << mono.id << \"\\n\";\n      abort();\n    }\n    int index = ii->second;\n    int expo  = mono.expo ? *mono.expo : 1;\n    t.exp(index) += expo;\n  }\n\n  void parseTerm(const Term& term, std::vector<TheTerm*>& terms) {\n    TheTerm& t = m_ring->makeTerm();\n    std::for_each(term.monos.begin(), term.monos.end(),\n                  boost::bind(&Parser::parseMono, this, _1, boost::ref(t)));\n    parseCoef(term.coef, t.coef());\n    m_ring->generateTotalDegree(t);\n    terms.push_back(&t);\n  }\n\n  struct GreaterThan {\n    Ring<Order>& ring;\n    GreaterThan(Ring<Order>& r) : ring(r) {}\n    bool operator()(const TheTerm* a, const TheTerm* b) const {\n      return ring.gt(*a, *b);\n    }\n  };\n\n  void parsePoly(const Poly& poly) {\n    std::vector<TheTerm*> terms;\n    std::for_each(poly.terms.begin(), poly.terms.end(),\n                  boost::bind(&Parser::parseTerm, this, _1, boost::ref(terms)));\n\n    std::sort(terms.begin(), terms.end(), GreaterThan(*m_ring));\n    ThePoly& p = m_ring->makePoly();\n    for (std::vector<TheTerm*>::iterator ii = terms.begin(), ei = terms.end();\n         ii != ei; ++ii) {\n      p.push(*ii);\n    }\n    m_polys.push(&p);\n  }\n\n  void writeHeader(std::ostream& out) const {\n    out << \"Q[\";\n    for (IdMap::const_iterator ii = idMap.begin(), ei = idMap.end(); ii != ei;\n         ++ii) {\n      out << *ii;\n      if (ii + 1 != ei)\n        out << \", \";\n    }\n    out << \"]\\n\";\n  }\n\n  void writePolys(std::ostream& out, const PolySet& polys) const {\n    m_ring->write(out, polys, &idMap);\n    out << \"\\n\";\n  }\n\npublic:\n  typedef TheRing RingTy;\n\n  Parser() : m_ring(0) {}\n\n  ~Parser() {\n    if (m_ring)\n      delete m_ring;\n  }\n\n  void read(std::istream& in) {\n    std::string header;\n    getline(in, header);\n    readHeader(header.begin(), header.end());\n\n    m_ring = new Ring<Order>(idMap.size());\n\n    in.unsetf(std::ios::skipws);\n    boost::spirit::istream_iterator begin(in), end;\n\n    std::vector<Poly> polys;\n    readPolys(begin, end, polys);\n    std::for_each(polys.begin(), polys.end(),\n                  boost::bind(&Parser::parsePoly, this, _1));\n\n    std::cout << \"Rational ring of \" << nameMap.size() << \" (\"\n              << m_ring->numVars() << \") variables\\n\";\n    std::cout << \"Ideal of \" << polys.size() << \" polynomials\\n\";\n  }\n\n  void write(std::ostream& out, const PolySet& polys) {\n    writeHeader(out);\n    writePolys(out, polys);\n  }\n\n  RingTy& ring() { return *m_ring; }\n\n  PolySet& polys() { return m_polys; }\n};\n\n} // namespace parser\n\ntemplate <class Order>\nvoid run() {\n  std::ifstream scanner(filename.c_str());\n  if (!scanner.good()) {\n    std::cerr << \"Couldn't open file: \" << filename << \"\\n\";\n    abort();\n  }\n\n  typedef parser::Parser<Order> ParserTy;\n  ParserTy P;\n  P.read(scanner);\n  scanner.close();\n\n  P.write(std::cout, P.polys()); // REMOVe\n\n  TheField.init();\n\n  galois::StatTimer T;\n  T.start();\n  interReduce(P.polys(), P.ring());\n  PolySet basis;\n  buchberger(P.polys(), basis, P.ring());\n  T.stop();\n\n  if (!skipVerify) {\n    galois::InsertBag<PolyPair> pairs;\n    allPairs(basis, pairs, P.ring());\n    Verifier<typename ParserTy::RingTy> v(basis, P.ring());\n    if (galois::ParallelSTL::find_if(pairs.begin(), pairs.end(), v) !=\n        pairs.end()) {\n      std::cerr << \"Basis is not Groebner.\\n\";\n      assert(0 && \"Triangulation failed\");\n      abort();\n    }\n  }\n  P.write(std::cout, basis);\n  std::cout << \"Groebner basis with \"\n            << std::distance(basis.begin(), basis.end()) << \" polynomials\\n\";\n}\n\nint main(int argc, char** argv) {\n  galois::StatManager statManager;\n  statManager.push(zeroUpdate);\n  statManager.push(bkUpdate);\n  statManager.push(mfUpdate);\n  statManager.push(bpUpdate);\n\n  LonestarStart(argc, argv, name, desc, url);\n\n  for (unsigned i = 0; i < sizeof(powersOfTwo) / sizeof(*powersOfTwo); ++i)\n    powersOfTwo[i] = 2 << (i - 1);\n\n  switch (monomialOrder) {\n  case lex:\n    run<LexOrder>();\n    break;\n  case grevlex:\n    run<GrevlexOrder>();\n    break;\n  default:\n    abort();\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "1e3dfb759daba10eff64a8a452511e2f827aea53", "size": 33989, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lonestar/experimental/buchberger/Buchberger.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/buchberger/Buchberger.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/buchberger/Buchberger.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": 27.7914963205, "max_line_length": 85, "alphanum_fraction": 0.5820118274, "num_tokens": 9792, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321964553657, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.46391590593299126}}
{"text": "#pragma once\r\n\r\n#include <vector>\r\n#include <Eigen/Core>\r\n#include <Eigen/LU>\r\n#include <Eigen/Dense>\r\n\r\nnamespace ImageInformationAnalyzer\r\n{\r\n    namespace Domain\r\n    {\r\n        using namespace std::literals::string_literals;\r\n\r\n        class FloatingPointImageData\r\n        {\r\n        public:\r\n            const int Width;\r\n            const int Height;\r\n            const std::vector<std::vector<double>> ImageBuffer;\r\n            const std::vector<std::vector<Eigen::Vector3d>> NormalBuffer;\r\n\r\n        private:\r\n            double maxValue_;\r\n            double minValue_;\r\n\r\n        public:\r\n            explicit FloatingPointImageData::FloatingPointImageData(const int width, const int height\r\n                , const std::vector<std::vector<double>> imageBuffer\r\n                , const std::vector<std::vector<Eigen::Vector3d>> normalBuffer) : Width(width), Height(height), ImageBuffer(imageBuffer), NormalBuffer(normalBuffer)\r\n            {\r\n                maxValue_ = DBL_MIN;\r\n                minValue_ = DBL_MAX;\r\n\r\n                for(auto line : imageBuffer)\r\n                {\r\n                    for(auto value : line)\r\n                    {\r\n                        if(value > maxValue_)\r\n                        {\r\n                            maxValue_ = value;\r\n                        }\r\n                        if(value < minValue_)\r\n                        {\r\n                            minValue_ = value;\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n\r\n            inline double GetMaxValue() const { return maxValue_; }\r\n            inline double GetMinValue() const { return minValue_; }\r\n\r\n            virtual ~FloatingPointImageData() = default;\r\n        };\r\n    }\r\n}\r\n", "meta": {"hexsha": "21370679eed8d21e481cff7c30f7087cac48b894", "size": 1741, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Domain/FloatingPointImageData.hpp", "max_stars_repo_name": "ice-github/ImageInformationAnalyzer", "max_stars_repo_head_hexsha": "7065065d54f0d0e56e66210a915b6637d803f52f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2019-12-02T03:19:11.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-14T13:06:36.000Z", "max_issues_repo_path": "src/Domain/FloatingPointImageData.hpp", "max_issues_repo_name": "ice-github/ImageInformationAnalyzer", "max_issues_repo_head_hexsha": "7065065d54f0d0e56e66210a915b6637d803f52f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Domain/FloatingPointImageData.hpp", "max_forks_repo_name": "ice-github/ImageInformationAnalyzer", "max_forks_repo_head_hexsha": "7065065d54f0d0e56e66210a915b6637d803f52f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-12-02T16:39:25.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-02T16:39:25.000Z", "avg_line_length": 30.5438596491, "max_line_length": 165, "alphanum_fraction": 0.4801838024, "num_tokens": 297, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.4639158979757675}}
{"text": "/*!\n * @file\n * Contains unit tests for `boost::mpl::permutations`.\n */\n\n#include <boost/mpl/permutations.hpp>\n\n#include <boost/mpl/assert.hpp>\n#include <boost/mpl/equal.hpp>\n#include <boost/mpl/placeholders.hpp>\n#include <boost/mpl/quote.hpp>\n#include <boost/mpl/set.hpp>\n#include <boost/mpl/set_equal.hpp>\n#include <boost/mpl/vector.hpp>\n#include <boost/type_traits/is_same.hpp>\n\n\ntemplate <typename Sequence, typename Permutations>\nstruct assert_permutations {\n    BOOST_MPL_ASSERT((boost::mpl::set_equal<\n        typename boost::mpl::permutations<Sequence>::type,\n        Permutations,\n        boost::mpl::equal<\n            boost::mpl::_1, boost::mpl::_2,\n            boost::mpl::quote2<boost::is_same>\n        >\n    >));\n};\n\nusing namespace boost::mpl;\ntemplate <int> struct t;\n\n// empty\ntemplate struct assert_permutations<\n    vector<>,\n    set<>\n>;\n\n// 1 element\ntemplate struct assert_permutations<\n    vector<t<0> >,\n    set<\n        vector<t<0> >\n    >\n>;\n\n// 2 elements\ntemplate struct assert_permutations<\n    vector<t<0>, t<1> >,\n    set<\n        vector<t<0>, t<1> >,\n        vector<t<1>, t<0> >\n    >\n>;\n\n// 3 elements\ntemplate struct assert_permutations<\n    vector<t<0>, t<1>, t<2> >,\n    set<\n        vector<t<0>, t<1>, t<2> >,\n        vector<t<0>, t<2>, t<1> >,\n\n        vector<t<1>, t<0>, t<2> >,\n        vector<t<1>, t<2>, t<0> >,\n\n        vector<t<2>, t<0>, t<1> >,\n        vector<t<2>, t<1>, t<0> >\n    >\n>;\n\n\nint main() { }\n", "meta": {"hexsha": "f61c386dde568dc485f4e7035a692b698c0d3ec2", "size": 1449, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/permutations.cpp", "max_stars_repo_name": "ldionne/mpl_extensions", "max_stars_repo_head_hexsha": "ca728992567b96dad884be1658b0822a955174cc", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-25T19:19:06.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-25T19:19:06.000Z", "max_issues_repo_path": "test/permutations.cpp", "max_issues_repo_name": "ldionne/mpl_extensions", "max_issues_repo_head_hexsha": "ca728992567b96dad884be1658b0822a955174cc", "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/permutations.cpp", "max_forks_repo_name": "ldionne/mpl_extensions", "max_forks_repo_head_hexsha": "ca728992567b96dad884be1658b0822a955174cc", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-25T19:19:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-25T19:19:07.000Z", "avg_line_length": 19.8493150685, "max_line_length": 58, "alphanum_fraction": 0.5866114562, "num_tokens": 427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.4639158979757675}}
{"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_DOT_PRODUCT_HPP\n#define BOOST_GEOMETRY_ARITHMETIC_DOT_PRODUCT_HPP\n\n\n#include <cstddef>\n\n#include <boost/concept/requires.hpp>\n\n#include <boost/geometry/geometries/concepts/point_concept.hpp>\n#include <boost/geometry/util/select_coordinate_type.hpp>\n\nnamespace boost { namespace geometry\n{\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail\n{\n\ntemplate <typename P1, typename P2, std::size_t Dimension, std::size_t DimensionCount>\nstruct dot_product_maker\n{\n    typedef typename select_coordinate_type<P1, P2>::type coordinate_type;\n\n    static inline coordinate_type apply(P1 const& p1, P2 const& p2)\n    {\n        return get<Dimension>(p1) * get<Dimension>(p2)\n            + dot_product_maker<P1, P2, Dimension+1, DimensionCount>::apply(p1, p2);\n    }\n};\n\ntemplate <typename P1, typename P2, std::size_t DimensionCount>\nstruct dot_product_maker<P1, P2, DimensionCount, DimensionCount>\n{\n    typedef typename select_coordinate_type<P1, P2>::type coordinate_type;\n\n    static inline coordinate_type apply(P1 const& p1, P2 const& p2)\n    {\n        return get<DimensionCount>(p1) * get<DimensionCount>(p2);\n    }\n};\n\n} // namespace detail\n#endif // DOXYGEN_NO_DETAIL\n\n\n/*!\n    \\brief Computes the dot product (or scalar product) of 2 vectors (points).\n    \\ingroup arithmetic\n    \\param p1 first point\n    \\param p2 second point\n    \\return the dot product\n */\ntemplate <typename P1, typename P2>\ninline typename select_coordinate_type<P1, P2>::type dot_product(\n        P1 const& p1, P2 const& p2)\n{\n    BOOST_CONCEPT_ASSERT( (concept::ConstPoint<P1>) );\n    BOOST_CONCEPT_ASSERT( (concept::ConstPoint<P2>) );\n\n    return detail::dot_product_maker\n        <\n            P1, P2,\n            0, dimension<P1>::type::value - 1\n        >::apply(p1, p2);\n}\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_ARITHMETIC_DOT_PRODUCT_HPP\n", "meta": {"hexsha": "13fe968779932b6464bf6ce7b5a761b771bc4709", "size": 2443, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/boost/geometry/arithmetic/dot_product.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/geometry/arithmetic/dot_product.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/geometry/arithmetic/dot_product.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": 29.4337349398, "max_line_length": 86, "alphanum_fraction": 0.7249283668, "num_tokens": 647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.6513548578981939, "lm_q1q2_score": 0.46391589315547954}}
{"text": "//\n// boost-geometry-render\n//\n// Copyright (c) 2011 \n// osyo-manga : http://d.hatena.ne.jp/osyo-manga/\n//\n// License:\n// Boost Software License - Version 1.0\n// <http://www.boost.org/LICENSE_1_0.txt>\n//\n#include <cstdlib>\n#include <gl/glut.h>\n#include <gl/graphics.hpp>\n#include <gl/geometry_render.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <iostream>\n#include <boost/thread.hpp>\n#include <boost/assign/list_of.hpp>\n#include <boost/geometry/geometries/linestring.hpp>\n\nnamespace bg = boost::geometry;\n\ntemplate<typename Geometry>\nstruct geometry_renderer{\n\tgeometry_renderer(Geometry& geometry) : geometry_(geometry){};\n\tvoid operator ()(){\n\t\tglColor3d(1.0f, 0.0f, 0.0f);\n\t\tgl::render(geometry_);\n\t}\nprivate:\n\tGeometry& geometry_;\n};\n\ntemplate<typename Geometry>\ngeometry_renderer<Geometry>\nmake_geometry_renderer(Geometry& geometry){\n\treturn geometry_renderer<Geometry>(geometry);\n}\n\nint\nmain(int argc, char* argv[]){\n\ttypedef bg::model::d2::point_xy<float> point_type;\n\tbg::model::polygon<point_type> polygon;\n\tbg::exterior_ring(polygon) = boost::assign::list_of<point_type>\n\t\t( 0.0f,  0.5f)\n\t\t( 0.5f,  0.0f)\n\t\t( 0.1f, -0.1f)\n\t\t( 0.0f, -0.5f)\n\t\t(-0.1f, -0.1f)\n\t\t(-0.5f,  0.0f);\n\t\n\tgl::graphics g(argc, argv, 500, 500);\n\tgl::displayfunc(g, make_geometry_renderer(polygon));\n\t\n\tg.run();\n\treturn 0;\n}\n", "meta": {"hexsha": "c5f2ac4ace03df9ce75fdb332843c2b80bd0549b", "size": 1372, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/example/polygon.cpp", "max_stars_repo_name": "osyo-manga/boost-geometry-render", "max_stars_repo_head_hexsha": "7cdfb91572b31186fa48a1196bc34327ec561482", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-04-04T20:06:24.000Z", "max_stars_repo_stars_event_max_datetime": "2018-04-04T20:06:24.000Z", "max_issues_repo_path": "libs/example/polygon.cpp", "max_issues_repo_name": "osyo-manga/boost-geometry-render", "max_issues_repo_head_hexsha": "7cdfb91572b31186fa48a1196bc34327ec561482", "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/example/polygon.cpp", "max_forks_repo_name": "osyo-manga/boost-geometry-render", "max_forks_repo_head_hexsha": "7cdfb91572b31186fa48a1196bc34327ec561482", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.2542372881, "max_line_length": 64, "alphanum_fraction": 0.7062682216, "num_tokens": 430, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321720225278, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.4639158900185434}}
{"text": "#include <iostream>\n#include <random>\n#include <cmath>\n#include <armadillo>\n#include <sstream>\n#include \"logistic_regression.h\"\n#include \"file.h\"\n//#include \"barrier.h\"\nusing namespace std;\nusing namespace arma;\nusing namespace multiverso;\n\n//initialize the logistic regression parameter settings\nlogistic_regression::logistic_regression(){}\nlogistic_regression::logistic_regression(int data_size,\n                            double learning_rate,\n                            double regularized,\n                            int max_num_iteration,\n                            int epoch_size,\n                            int dimention,\n                            double gamma/*momentum*/)\n{\n    DATA_SIZE = data_size;\n\tLEARNING_RATE = learning_rate;\n\tREGULARIZED = regularized;\n\tMAX_NUM_ITERATION = max_num_iteration;\n\tEPOCH_SIZE = epoch_size;\n    DIMENTION = dimention;\n    parameter = zeros<vec>(DIMENTION);\n    full_gradient = zeros<vec>(DIMENTION);\n    local_parameter = zeros<vec>(DIMENTION);\n    momentum = zeros<vec>(DIMENTION);\n    GAMMA = gamma;\n}\nlogistic_regression::logistic_regression(Option* option_)\n{\n    DATA_SIZE = option_->data_size;\n\tLEARNING_RATE = option_->learning_rate;\n\tREGULARIZED = option_->regularized;\n\tMAX_NUM_ITERATION = option_->max_num_iteration;\n\tEPOCH_SIZE = option_->epoch_size;\n    DIMENTION = option_->dimention;\n    sample_epoch = zeros<vec>(EPOCH_SIZE*MAX_NUM_ITERATION);\n    parameter = zeros<vec>(DIMENTION);\n    full_gradient = zeros<vec>(DIMENTION);\n    local_parameter = zeros<vec>(DIMENTION);\n    momentum = zeros<vec>(DIMENTION);\n    GAMMA = option_->gamma;\n    this->option_ = option_;\n\n}\n\n\n//record the begin time of the training process\nvoid logistic_regression::begin(time_t& begin)\n{\n    time(&begin);\n}\n//record the end time of the training process\nvoid logistic_regression::end(time_t& end)\n{\n    time(&end);\n}\n//training the parameters. The fl2-regularization is added\nvoid logistic_regression::train(int trainer_id, multiverso::Barrier *barrier)\n{\n    //produce the samples by a certain probability distribution\n    default_random_engine random(time(NULL));    \n    if(trainer_id==0) \n    {\n        //set the epoch size. Defaultly, it is set by the variable: EPOCH_SIZE\n        setEpochSize(EPOCH_SIZE);\n        sample_epoch = produceSamples(random);\n    }\n    barrier->Wait();\n    for(int i=0;i<MAX_NUM_ITERATION;i++)\n    {\nmultiverso::Log::Info(\">>>>>>>>>>>>>>>>learning thread %dth!\\n\",trainer_id);\n        //compute the full gradient in parallel way\n        vec full_gradient_thread = computeFullGradient(parameter,trainer_id, option_->thread_cnt);\n        //sum all the full gradient in serial way\n        mutex_.lock();\n        full_gradient = full_gradient+full_gradient_thread;\n        mutex_.unlock();\n        local_parameter = parameter;\n        barrier->Wait();\n        for(int j=trainer_id;j<EPOCH_SIZE;j+=option_->thread_cnt)\n        {\n            //compute the reduced variance\n            vec vr = computeReducedVariance(parameter, local_parameter, full_gradient, sample_epoch(i*EPOCH_SIZE+j));\n            //update the parameters\n            //add the write lock\n            mutex_.lock();\n            updateParameters(local_parameter, vr, LEARNING_RATE);\n            mutex_.unlock();\n        }\n        barrier->Wait();\n        if(trainer_id == 0)\n        {\n           //Identify the parameters for the next iteration\n           identifyParameters(local_parameter, parameter); \n           //evaluate the loss\n           if(i%1==0){\n               computeLoss(parameter, training_x, training_y);\n\t       //parameter.load(\"parameter.txt\");\n \t       }\n        }//end if\n    }//end for \n}\n\n//produce the samples by a certain probability distribution\nvec logistic_regression::produceSamples(std::default_random_engine random)\n{\n    int n_instances = EPOCH_SIZE*MAX_NUM_ITERATION;\n    vec samples = zeros<vec>(n_instances);\n    uniform_int_distribution<int> dis1(0, DATA_SIZE-1);\n    for (int i=0;i<n_instances;i++)\n    {\n        samples(i) = dis1(random);\n    }\n    return samples;\n}\n\n//set the epoch size. Defaultly, it is set by the variable: EPOCH_SIZE\nvoid logistic_regression::setEpochSize(int size)\n{\n    EPOCH_SIZE = size;\n}\n\n//compute the stochastic local gradient\nvec logistic_regression::computeStochasticGradient(vec& parameters, int index)\n{\n    double w_x = as_scalar(parameters.t()*training_x.col(index));\n    double y = training_y[index];\n    double temp0 = (1/(1+std::exp(y*w_x)))*(-1*y);\n    vec gradient(temp0*training_x.col(index)+2*REGULARIZED*parameters);\n    return gradient;\n}\n\n//compute the full gradient via multiple threads\nvec logistic_regression::computeFullGradient(vec& global_parameter,int trainer_id, int thread_cnt)\n{\n    vec full_gradient_local = zeros<vec>(DIMENTION);\n    for(int i=trainer_id;i<DATA_SIZE;i+=thread_cnt)//consider the constant\n    {\n        vec temp0 = computeStochasticGradient(global_parameter, i);\n        full_gradient_local = full_gradient_local + temp0;\n    }\n    full_gradient_local = full_gradient_local/DATA_SIZE;\n\n    return full_gradient_local;\n}\n\n//compute the reduced variance\nvec logistic_regression::computeReducedVariance(vec& global_parameter, vec& local_parameter, vec& full_gradient, int index)\n{\n    vec vr = zeros<vec>(DIMENTION);\n    vec temp0 = computeStochasticGradient(local_parameter, index);\n    vec temp1 = computeStochasticGradient(global_parameter, index);\n    vr=temp0-temp1+full_gradient;\n    return vr;\n}\n\n\n//update the parameters\nvoid logistic_regression::updateParameters(vec& local_parameter, vec& vr, double learning_rate)\n{\n    vec temp = learning_rate*vr + GAMMA*momentum/*momentum*/;\n    local_parameter = local_parameter - temp;\n    momentum = temp;\n}\n\n//Identify the parameters for the next iteration\nvoid logistic_regression::identifyParameters(vec& local_parameter, vec& global_parameter)\n{\n    global_parameter = local_parameter;\n}\n\n//compute the loss function\ndouble logistic_regression::computeLoss(vec& parameter, sp_mat& x, vec& y)\n{\n    double loss=0;\n    for(int i=0;i<DATA_SIZE;i++)\n    {\n        double temp = as_scalar(parameter.t()*x.col(i));\n        loss = loss - log(1/(1+exp(-1*temp*y(i))));\n    }\n    loss = loss/DATA_SIZE+REGULARIZED*(as_scalar(parameter.t()*parameter));\n    ostringstream s_loss;\n    s_loss<<loss<<\"\\n\";\n    string loss_str = s_loss.str();\n    file f(\"lr_loss.txt\");\n    f.write(loss_str);\n    //multiverso::Log::Info(\"The loss now is: %f\\n\",loss);\n    return loss;\n}\n\n\n//get ready to parepare the data from the multiverso framework\nvoid logistic_regression::init(DataBlock* data_block)\n{\n    sp_mat temp_trn_x;\n    sp_mat temp_tst_x;\n    vec temp_trn_y;\n    vec temp_tst_y;\n    \n    data_block->GetSamples(temp_trn_x,temp_tst_x,temp_trn_y,temp_tst_y);\n    training_x = temp_trn_x.t();\n    training_y = temp_trn_y;\n}\n\n//the entrance from the multiverso to the training thread, and the training process is finally started.\nvoid logistic_regression::train_test(int trainer_id, multiverso::Barrier *barrier)\n{\n    int fast, slow, self;\n    double wait_time=0;\n    multiverso::Multiverso::GetClock(&fast, &slow, &self, &wait_time);\n    //log the wait time\n    \n    //begin training\n    multiverso::Log::Info(\"Process: %d and thread: %d begins!\\n\", multiverso::Multiverso::ProcessRank(),trainer_id);\n    time_t begin_time=0;\n    time_t end_time=0;\n    begin(begin_time);\n    train(trainer_id,barrier);\n    end(end_time);\n}\n\n//set the parameters when pulling the parameters from multiverso\nvoid logistic_regression::setParameters(std::vector<double*> &blocks)\n{\n    //NOTICE: since logistic regression conducts the binary classification, the number of class is 2. (Here, class_num=1 means the number of class is 2.)\n    for(int i=0;i<option_->class_num;i++)\n    {\n        for (int j=0;j < option_->dimention;j++)\n        {\n            parameter[j] = blocks[i][j];//since class_num=1, parameter will be valued once.\n        }\n    }\n}\n\n//get the parameters\nvoid logistic_regression::getParameters(std::vector<double*> &blocks)\n{\n    for(int i=0;i < option_->class_num; i++)\n    {\n        for (int j=0;j < option_->dimention;j++)\n        {\n            blocks[i][j] = parameter[j];\n        }\n    }\n}\n", "meta": {"hexsha": "019f4baa493efc9dbbfc39e96810814a71e08694", "size": 8186, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/logistic_regression.cpp", "max_stars_repo_name": "YaweiZhao/hybrid_svrg", "max_stars_repo_head_hexsha": "f576e46f1169909f64692977fb1e68181533f4f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/logistic_regression.cpp", "max_issues_repo_name": "YaweiZhao/hybrid_svrg", "max_issues_repo_head_hexsha": "f576e46f1169909f64692977fb1e68181533f4f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/logistic_regression.cpp", "max_forks_repo_name": "YaweiZhao/hybrid_svrg", "max_forks_repo_head_hexsha": "f576e46f1169909f64692977fb1e68181533f4f0", "max_forks_repo_licenses": ["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.3557312253, "max_line_length": 153, "alphanum_fraction": 0.6800635231, "num_tokens": 1951, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.782662489091802, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.46385791632162754}}
{"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_CORRECT_FMA_HPP_INCLUDED\n#define BOOST_SIMD_ARITHMETIC_FUNCTIONS_SCALAR_CORRECT_FMA_HPP_INCLUDED\n\n#include <boost/simd/arithmetic/functions/correct_fma.hpp>\n#include <boost/simd/include/functions/scalar/two_add.hpp>\n#include <boost/simd/include/functions/scalar/two_prod.hpp>\n#include <boost/simd/include/functions/scalar/ldexp.hpp>\n#include <boost/simd/include/functions/scalar/max.hpp>\n#include <boost/simd/include/functions/scalar/multiplies.hpp>\n#include <boost/simd/include/functions/scalar/exponent.hpp>\n#include <boost/simd/include/functions/scalar/sign.hpp>\n#include <boost/simd/include/functions/scalar/bitwise_cast.hpp>\n#include <boost/dispatch/meta/as_integer.hpp>\n#include <boost/dispatch/attributes.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n\n  BOOST_DISPATCH_IMPLEMENT         ( correct_fma_, tag::cpu_\n                                   , (A0)\n                                   , (scalar_< single_<A0> >)\n                                     (scalar_< single_<A0> >)\n                                     (scalar_< single_<A0> >)\n                                   )\n  {\n    typedef A0 result_type;\n\n    BOOST_FORCEINLINE BOOST_SIMD_FUNCTOR_CALL_REPEAT(3)\n    {\n      return static_cast<A0>( static_cast<double>(a0)*static_cast<double>(a1)\n                            + static_cast<double>(a2)\n                            );\n    }\n  };\n\n\n  BOOST_DISPATCH_IMPLEMENT         ( correct_fma_, tag::cpu_\n                                   , (A0)\n                                   , (scalar_< floating_<A0> >)\n                                     (scalar_< floating_<A0> >)\n                                     (scalar_< floating_<A0> >)\n                                   )\n  {\n    typedef A0 result_type;\n\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(3)\n    {\n      result_type p, rp, s, rs;\n#ifndef BOOST_SIMD_DONT_CARE_FMA_OVERFLOW\n      typedef typename boost::dispatch::meta::as_integer<A0>::type iA0;\n      iA0 e0 = exponent(a0);\n      iA0 e1 = exponent(a1);\n      iA0 e = -boost::simd::max(e0, e1)/2;\n      result_type ae2  = ldexp(a2, e);\n      bool choose = (e0 > e1);\n      result_type amax = choose ? ldexp(a0, e) : ldexp(a1, e);\n      result_type amin = choose ? a1 : a0;\n      two_prod(amax, amin, p, rp);\n      two_add(p, ae2, s, rs);\n      return ldexp(s+(rp+rs), -e);\n#else\n      two_prod(a0, a1, p, rp);\n      two_add(p, a2, s, rs);\n      return s+(rp+rs);\n#endif\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT         ( correct_fma_, tag::cpu_\n                                   , (A0)\n                                   , (scalar_< int_<A0> >)\n                                     (scalar_< int_<A0> >)\n                                     (scalar_< int_<A0> >)\n                                   )\n  {\n    typedef A0 result_type;\n\n    BOOST_FORCEINLINE BOOST_SIMD_FUNCTOR_CALL_REPEAT(3)\n    {\n      // correct fma has to ensure \"no intermediate overflow\".\n      // This is done in the case of signed integers by transtyping to unsigned type\n      // to perform the computations in a guaranteed 2-complement environment\n      // since signed integer oveflow in C++ produces \"undefined results\"\n      typedef typename dispatch::meta::as_integer<A0, unsigned>::type utype;\n      return A0(correct_fma(utype(a0), utype(a1), utype(a2)));\n    }\n  };\n\n\n  BOOST_DISPATCH_IMPLEMENT         ( correct_fma_, tag::cpu_\n                                   , (A0)\n                                   , (scalar_< uint_<A0> >)\n                                     (scalar_< uint_<A0> >)\n                                     (scalar_< uint_<A0> >)\n                                   )\n  {\n    typedef A0 result_type;\n\n    BOOST_FORCEINLINE BOOST_SIMD_FUNCTOR_CALL_REPEAT(3)\n    {\n      return multiplies(a0, a1)+a2;\n    }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "8c50221296d83d5cab5764c00a4cabab2e7a75d8", "size": 4301, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/scalar/correct_fma.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/correct_fma.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/correct_fma.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.0775862069, "max_line_length": 84, "alphanum_fraction": 0.5289467566, "num_tokens": 998, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.46385791031266116}}
{"text": "// This file is part of libigl, a simple c++ geometry processing library.\r\n// \r\n// Copyright (C) 2016 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 <igl/polyvector_field_poisson_reconstruction.h>\r\n#include <igl/grad.h>\r\n#include <igl/doublearea.h>\r\n#include <igl/sparse.h>\r\n#include <igl/repdiag.h>\r\n#include <igl/slice.h>\r\n#include <igl/slice_into.h>\r\n#include <igl/colon.h>\r\n\r\n#include <Eigen/Sparse>\r\n\r\ntemplate <typename DerivedV, typename DerivedF, typename DerivedSF, typename DerivedS>\r\nIGL_INLINE void igl::polyvector_field_poisson_reconstruction(\r\n  const Eigen::PlainObjectBase<DerivedV> &Vcut,\r\n  const Eigen::PlainObjectBase<DerivedF> &Fcut,\r\n  const Eigen::PlainObjectBase<DerivedS> &sol3D_combed,\r\n                                                               Eigen::PlainObjectBase<DerivedSF> &scalars)\r\n  {\r\n    Eigen::SparseMatrix<typename DerivedV::Scalar> gradMatrix;\r\n    igl::grad(Vcut, Fcut, gradMatrix);\r\n\r\n    Eigen::VectorXd FAreas;\r\n    igl::doublearea(Vcut, Fcut, FAreas);\r\n    FAreas = FAreas.array() * .5;\r\n\r\n    int nf = FAreas.rows();\r\n    Eigen::SparseMatrix<typename DerivedV::Scalar> M,M1;\r\n    Eigen::VectorXi II = igl::colon<int>(0, nf-1);\r\n\r\n    igl::sparse(II, II, FAreas, M1);\r\n    igl::repdiag(M1, 3, M) ;\r\n\r\n    int half_degree = sol3D_combed.cols()/3;\r\n\r\n    int numF = Fcut.rows();\r\n    scalars.setZero(Vcut.rows(),half_degree);\r\n\r\n    Eigen::SparseMatrix<typename DerivedV::Scalar> Q = gradMatrix.transpose()* M *gradMatrix;\r\n\r\n    //fix one point at Ik=fix, value at fixed xk=0\r\n    int fix = 0;\r\n    Eigen::VectorXi Ik(1);Ik<<fix;\r\n    Eigen::VectorXd xk(1);xk<<0;\r\n\r\n    //unknown indices\r\n    Eigen::VectorXi Iu(Vcut.rows()-1,1);\r\n    Iu<<igl::colon<int>(0, fix-1),  igl::colon<int>(fix+1,Vcut.rows()-1);\r\n\r\n    Eigen::SparseMatrix<typename DerivedV::Scalar> Quu, Quk;\r\n    igl::slice(Q, Iu, Iu, Quu);\r\n    igl::slice(Q, Iu, Ik, Quk);\r\n    Eigen::SimplicialLDLT<Eigen::SparseMatrix<typename DerivedV::Scalar> > solver;\r\n    solver.compute(Quu);\r\n\r\n\r\n    Eigen::VectorXd vec; vec.setZero(3*numF,1);\r\n    for (int i =0; i<half_degree; ++i)\r\n    {\r\n      vec<<sol3D_combed.col(i*3+0),sol3D_combed.col(i*3+1),sol3D_combed.col(i*3+2);\r\n      Eigen::VectorXd b = gradMatrix.transpose()* M * vec;\r\n      Eigen::VectorXd bu = igl::slice(b, Iu);\r\n\r\n      Eigen::VectorXd rhs = bu-Quk*xk;\r\n      Eigen::VectorXd yu = solver.solve(rhs);\r\n\r\n      Eigen::VectorXd y(Vcut.rows(),1);\r\n      igl::slice_into(yu, Iu, 1, y);y(Ik[0])=xk[0];\r\n      scalars.col(i) = y;\r\n    }\r\n}\r\n\r\ntemplate <typename DerivedV, typename DerivedF, typename DerivedSF, typename DerivedS, typename DerivedE>\r\nIGL_INLINE double igl::polyvector_field_poisson_reconstruction(\r\n                                                               const Eigen::PlainObjectBase<DerivedV> &Vcut,\r\n                                                               const Eigen::PlainObjectBase<DerivedF> &Fcut,\r\n                                                               const Eigen::PlainObjectBase<DerivedS> &sol3D_combed,\r\n                                                               Eigen::PlainObjectBase<DerivedSF> &scalars,\r\n                                                               Eigen::PlainObjectBase<DerivedS> &sol3D_recon,\r\n                                                               Eigen::PlainObjectBase<DerivedE> &max_error )\r\n{\r\n  \r\n  igl::polyvector_field_poisson_reconstruction(Vcut, Fcut, sol3D_combed, scalars);\r\n\r\n  Eigen::SparseMatrix<typename DerivedV::Scalar> gradMatrix;\r\n  igl::grad(Vcut, Fcut, gradMatrix);\r\n  int numF = Fcut.rows();\r\n  int half_degree = sol3D_combed.cols()/3;\r\n\r\n    //    evaluate gradient of found scalar function\r\n  sol3D_recon.setZero(sol3D_combed.rows(),sol3D_combed.cols());\r\n  \r\n    for (int i =0; i<half_degree; ++i)\r\n    {\r\n      Eigen::VectorXd vec_poisson = gradMatrix*scalars.col(i);\r\n      sol3D_recon.col(i*3+0) = vec_poisson.segment(0*numF, numF);\r\n      sol3D_recon.col(i*3+1) = vec_poisson.segment(1*numF, numF);\r\n      sol3D_recon.col(i*3+2) = vec_poisson.segment(2*numF, numF);\r\n    }\r\n\r\n    max_error.setZero(numF,1);\r\n    for (int i =0; i<half_degree; ++i)\r\n    {\r\n      Eigen::VectorXd diff = (sol3D_recon.block(0, i*3, numF, 3)-sol3D_combed.block(0, i*3, numF, 3)).rowwise().norm();\r\n      diff = diff.array() / sol3D_combed.block(0, i*3, numF, 3).rowwise().norm().array();\r\n      max_error = max_error.cwiseMax(diff.cast<typename DerivedE::Scalar>());\r\n    }\r\n\r\n    return max_error.mean();\r\n  }\r\n\r\n\r\n  #ifdef IGL_STATIC_LIBRARY\r\n  // Explicit template instantiation\r\n  template double igl::polyvector_field_poisson_reconstruction<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<double, -1, -1, 0, -1, -1>, Eigen::Matrix<float, -1, 1, 0, -1, 1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<float, -1, 1, 0, -1, 1> >&);\r\ntemplate double igl::polyvector_field_poisson_reconstruction<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<double, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, 1, 0, -1, 1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> >&);\r\n  #endif\r\n", "meta": {"hexsha": "79f5646e925077a1d4fe3d46301eb1705ea6c027", "size": 6149, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "include/igl/polyvector_field_poisson_reconstruction.cpp", "max_stars_repo_name": "rushmash/libwetcloth", "max_stars_repo_head_hexsha": "24f16481c68952c3d2a91acd6e3b74eb091b66bc", "max_stars_repo_licenses": ["BSD-3-Clause-Clear"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/igl/polyvector_field_poisson_reconstruction.cpp", "max_issues_repo_name": "rushmash/libwetcloth", "max_issues_repo_head_hexsha": "24f16481c68952c3d2a91acd6e3b74eb091b66bc", "max_issues_repo_licenses": ["BSD-3-Clause-Clear"], "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/igl/polyvector_field_poisson_reconstruction.cpp", "max_forks_repo_name": "rushmash/libwetcloth", "max_forks_repo_head_hexsha": "24f16481c68952c3d2a91acd6e3b74eb091b66bc", "max_forks_repo_licenses": ["BSD-3-Clause-Clear"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.5887096774, "max_line_length": 689, "alphanum_fraction": 0.6088794926, "num_tokens": 1918, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.46385791031266116}}
{"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\n#include <benchmark/benchmark.h>\n#include <boost/math/constants/constants.hpp>\n#include <boost/multiprecision/mpfr.hpp>\n\nusing namespace boost::math::constants;\nusing boost::multiprecision::mpfr_float;\n\nvoid LaplaceLimit(benchmark::State& state)\n{\n    mpfr_float::default_precision(state.range(0));\n    for (auto _ : state)\n    {\n        benchmark::DoNotOptimize(laplace_limit<mpfr_float>());\n    }\n    state.SetComplexityN(state.range(0));\n}\n\nBENCHMARK(LaplaceLimit)->RangeMultiplier(2)->Range(128, 1<<20)->Complexity()->Unit(benchmark::kMicrosecond);\n\nvoid Dottie(benchmark::State& state)\n{\n    mpfr_float::default_precision(state.range(0));\n    for (auto _ : state)\n    {\n        benchmark::DoNotOptimize(dottie<mpfr_float>());\n    }\n    state.SetComplexityN(state.range(0));\n}\n\nBENCHMARK(Dottie)->RangeMultiplier(2)->Range(512, 1<<20)->Complexity()->Unit(benchmark::kMicrosecond);\n\nvoid ReciprocalFibonacci(benchmark::State& state)\n{\n    mpfr_float::default_precision(state.range(0));\n    for (auto _ : state)\n    {\n        benchmark::DoNotOptimize(reciprocal_fibonacci<mpfr_float>());\n    }\n    state.SetComplexityN(state.range(0));\n}\n\nBENCHMARK(ReciprocalFibonacci)->RangeMultiplier(2)->Range(512, 1<<20)->Complexity()->Unit(benchmark::kMicrosecond);\n\n\nvoid Pi(benchmark::State& state)\n{\n    mpfr_float::default_precision(state.range(0));\n    for (auto _ : state)\n    {\n        benchmark::DoNotOptimize(pi<mpfr_float>());\n    }\n    state.SetComplexityN(state.range(0));\n}\n\nBENCHMARK(Pi)->RangeMultiplier(2)->Range(512, 1<<20)->Complexity()->Unit(benchmark::kMicrosecond);\n\nvoid Gauss(benchmark::State& state)\n{\n    mpfr_float::default_precision(state.range(0));\n    for (auto _ : state)\n    {\n        benchmark::DoNotOptimize(gauss<mpfr_float>());\n    }\n    state.SetComplexityN(state.range(0));\n}\n\nBENCHMARK(Gauss)->RangeMultiplier(2)->Range(512, 1<<20)->Complexity()->Unit(benchmark::kMicrosecond);\n\nvoid Exp1(benchmark::State& state)\n{\n    mpfr_float::default_precision(state.range(0));\n    for (auto _ : state)\n    {\n        benchmark::DoNotOptimize(e<mpfr_float>());\n    }\n    state.SetComplexityN(state.range(0));\n}\n\nBENCHMARK(Exp1)->RangeMultiplier(2)->Range(512, 1<<20)->Complexity()->Unit(benchmark::kMicrosecond);\n\nvoid Catalan(benchmark::State& state)\n{\n    mpfr_float::default_precision(state.range(0));\n    for (auto _ : state)\n    {\n        benchmark::DoNotOptimize(catalan<mpfr_float>());\n    }\n    state.SetComplexityN(state.range(0));\n}\n\nBENCHMARK(Catalan)->RangeMultiplier(2)->Range(512, 1<<20)->Complexity()->Unit(benchmark::kMicrosecond);\n\nvoid Plastic(benchmark::State& state)\n{\n    mpfr_float::default_precision(state.range(0));\n    for (auto _ : state)\n    {\n        benchmark::DoNotOptimize(plastic<mpfr_float>());\n    }\n    state.SetComplexityN(state.range(0));\n}\n\nBENCHMARK(Plastic)->RangeMultiplier(2)->Range(512, 1<<20)->Complexity()->Unit(benchmark::kMicrosecond);\n\nvoid RootTwo(benchmark::State& state)\n{\n    mpfr_float::default_precision(state.range(0));\n    for (auto _ : state)\n    {\n        benchmark::DoNotOptimize(root_two<mpfr_float>());\n    }\n    state.SetComplexityN(state.range(0));\n}\n\nBENCHMARK(RootTwo)->RangeMultiplier(2)->Range(512, 1<<20)->Complexity()->Unit(benchmark::kMicrosecond);\n\nvoid ZetaThree(benchmark::State& state)\n{\n    mpfr_float::default_precision(state.range(0));\n    for (auto _ : state)\n    {\n        benchmark::DoNotOptimize(zeta_three<mpfr_float>());\n    }\n    state.SetComplexityN(state.range(0));\n}\n\nBENCHMARK(ZetaThree)->RangeMultiplier(2)->Range(512, 1<<20)->Complexity()->Unit(benchmark::kMicrosecond);\n\n\nvoid Euler(benchmark::State& state)\n{\n    mpfr_float::default_precision(state.range(0));\n    for (auto _ : state)\n    {\n        benchmark::DoNotOptimize(euler<mpfr_float>());\n    }\n    state.SetComplexityN(state.range(0));\n}\n\nBENCHMARK(Euler)->RangeMultiplier(2)->Range(512, 1<<20)->Complexity()->Unit(benchmark::kMicrosecond);\n\n\nvoid LnTwo(benchmark::State& state)\n{\n    mpfr_float::default_precision(state.range(0));\n    for (auto _ : state)\n    {\n        benchmark::DoNotOptimize(ln_two<mpfr_float>());\n    }\n    state.SetComplexityN(state.range(0));\n}\n\nBENCHMARK(LnTwo)->RangeMultiplier(2)->Range(512, 1<<20)->Complexity()->Unit(benchmark::kMicrosecond);\n\nvoid Glaisher(benchmark::State& state)\n{\n    mpfr_float::default_precision(state.range(0));\n    for (auto _ : state)\n    {\n        benchmark::DoNotOptimize(glaisher<mpfr_float>());\n    }\n    state.SetComplexityN(state.range(0));\n}\n\nBENCHMARK(Glaisher)->RangeMultiplier(2)->Range(512, 4096)->Complexity()->Unit(benchmark::kMicrosecond);\n\n\nvoid Khinchin(benchmark::State& state)\n{\n    mpfr_float::default_precision(state.range(0));\n    for (auto _ : state)\n    {\n        benchmark::DoNotOptimize(khinchin<mpfr_float>());\n    }\n    state.SetComplexityN(state.range(0));\n}\n\n// There is a performance bug in the Khinchin constant:\nBENCHMARK(Khinchin)->RangeMultiplier(2)->Range(512, 512)->Complexity()->Unit(benchmark::kMicrosecond);\n\nBENCHMARK_MAIN();\n", "meta": {"hexsha": "7bfbba180ba27802fe01f11163e19ad29e80cc7a", "size": 5218, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "reporting/performance/constants_performance.cpp", "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": "reporting/performance/constants_performance.cpp", "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": "Libs/boost_1_76_0/libs/math/reporting/performance/constants_performance.cpp", "max_forks_repo_name": "Antd23rus/S2DE", "max_forks_repo_head_hexsha": "47cc7151c2934cd8f0399a9856c1e54894571553", "max_forks_repo_licenses": ["MIT"], "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.9037433155, "max_line_length": 115, "alphanum_fraction": 0.690302798, "num_tokens": 1409, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4638579043036946}}
{"text": "#include <jni.h>\n#include <string>\n#include <math.h>\n#include <iostream>\n#include <Eigen/Dense>\n#include <ceres/ceres.h>\n\nusing Eigen::MatrixXd;\n\nextern \"C\" JNIEXPORT jstring JNICALL\nJava_com_qyh_cerestest_MainActivity_stringFromJNI(\n        JNIEnv *env,\n        jobject /* this */) {\n    std::string hello = \"Hello from C++\";\n\n\n//    Eigen::MatrixXd m = Eigen::MatrixXd::Random(3, 3);\n//    m = MatrixXd::Constant(3, 3, 1.2) * 50;\n\n    return env->NewStringUTF(hello.c_str());\n}\n\n\n\n\nusing namespace Eigen;\n\nVector3f vec;\nVector3f vec2;\nVector3f vecRtrn;\n\nvoid vecLoad(float x, float y, float z, float x2, float y2, float z2) {\n    vec(0) = x;\n    vec(1) = y;\n    vec(2) = z;\n    vec2(0) = x2;\n    vec2(1) = y2;\n    vec2(2) = z2;\n}\n\nvoid vecAdd(Vector3f vecA, Vector3f vecB) {\n    vecRtrn = vecA + vecB;\n}\n\nextern \"C\"\nJNIEXPORT jfloatArray JNICALL\nJava_com_qyh_cerestest_MainActivity_test(JNIEnv *env, jobject instance, jfloatArray array1_,\n                                         jfloatArray array2_) {\n    jfloatArray result;\n    result = env->NewFloatArray(3);\n    if (result == NULL) {\n        return NULL; /* out of memory error thrown */\n    }\n\n    jfloat array1[3];\n    jfloat* flt1 = env->GetFloatArrayElements( array1_,0);\n    jfloat* flt2 = env->GetFloatArrayElements( array2_,0);\n\n\n    vecLoad(flt1[0], flt1[1], flt1[2], flt2[0], flt2[1], flt2[2]);\n    vecAdd(vec, vec2);\n\n    array1[0] = vecRtrn[0];\n    array1[1] = vecRtrn[1];\n    array1[2] = vecRtrn[2];\n\n    env->ReleaseFloatArrayElements(array1_, flt1, 0);\n    env->ReleaseFloatArrayElements(array2_, flt2, 0);\n    env->SetFloatArrayRegion(result, 0, 3, array1);\n    return result;\n\n}\n\nusing namespace ceres;\n\nstruct CostFunctor {\n    template <typename T>\n    bool operator()(const T* const x, T* residual) const {\n        residual[0] = T(10.0) - x[0];\n        return true;\n    }\n};\n\nextern \"C\"\nJNIEXPORT jstring JNICALL\nJava_com_qyh_cerestest_MainActivity_testCeres(JNIEnv *env, jobject instance) {\n    std::string hello = \"Hello Ceres\";\n\n    // \u5bfb\u4f18\u53c2\u6570x\u7684\u521d\u59cb\u503c\uff0c\u4e3a5\n    double initial_x = 5.0;\n    double x = initial_x;\n\n    // \u7b2c\u4e8c\u90e8\u5206\uff1a\u6784\u5efa\u5bfb\u4f18\u95ee\u9898\n    Problem problem;\n    CostFunction* cost_function =\n            new AutoDiffCostFunction<CostFunctor, 1, 1>(new CostFunctor); //\u4f7f\u7528\u81ea\u52a8\u6c42\u5bfc\uff0c\u5c06\u4e4b\u524d\u7684\u4ee3\u4ef7\u51fd\u6570\u7ed3\u6784\u4f53\u4f20\u5165\uff0c\u7b2c\u4e00\u4e2a1\u662f\u8f93\u51fa\u7ef4\u5ea6\uff0c\u5373\u6b8b\u5dee\u7684\u7ef4\u5ea6\uff0c\u7b2c\u4e8c\u4e2a1\u662f\u8f93\u5165\u7ef4\u5ea6\uff0c\u5373\u5f85\u5bfb\u4f18\u53c2\u6570x\u7684\u7ef4\u5ea6\u3002\n    problem.AddResidualBlock(cost_function, NULL, &x); //\u5411\u95ee\u9898\u4e2d\u6dfb\u52a0\u8bef\u5dee\u9879\uff0c\u672c\u95ee\u9898\u6bd4\u8f83\u7b80\u5355\uff0c\u6dfb\u52a0\u4e00\u4e2a\u5c31\u884c\u3002\n\n    //\u7b2c\u4e09\u90e8\u5206\uff1a \u914d\u7f6e\u5e76\u8fd0\u884c\u6c42\u89e3\u5668\n    Solver::Options options;\n    options.linear_solver_type = ceres::DENSE_QR; //\u914d\u7f6e\u589e\u91cf\u65b9\u7a0b\u7684\u89e3\u6cd5\n    options.minimizer_progress_to_stdout = true;//\u8f93\u51fa\u5230cout\n    Solver::Summary summary;//\u4f18\u5316\u4fe1\u606f\n    ceres::Solve(options, &problem, &summary);//\u6c42\u89e3!!!\n\n    std::cout << summary.BriefReport() << \"\\n\";//\u8f93\u51fa\u4f18\u5316\u7684\u7b80\u8981\u4fe1\u606f\n    //\u6700\u7ec8\u7ed3\u679c\n    std::cout << \"x : \" << initial_x\n              << \" -> \" << x << \"\\n\";\n\n    return env->NewStringUTF(summary.BriefReport().c_str());\n}", "meta": {"hexsha": "7df671469db6e2cccfa8d0280048f8e940541c9b", "size": 2845, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "app/src/main/cpp/native-lib.cpp", "max_stars_repo_name": "qiu-yongheng/cerestest", "max_stars_repo_head_hexsha": "d91729d329eefa83a7fd71e2fdbc8b15f7572cc0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-05-27T12:17:58.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-11T08:00:24.000Z", "max_issues_repo_path": "app/src/main/cpp/native-lib.cpp", "max_issues_repo_name": "qiu-yongheng/cerestest", "max_issues_repo_head_hexsha": "d91729d329eefa83a7fd71e2fdbc8b15f7572cc0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-08-05T15:03:45.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-09T02:31:27.000Z", "max_forks_repo_path": "app/src/main/cpp/native-lib.cpp", "max_forks_repo_name": "qiu-yongheng/cerestest", "max_forks_repo_head_hexsha": "d91729d329eefa83a7fd71e2fdbc8b15f7572cc0", "max_forks_repo_licenses": ["Apache-2.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.4017857143, "max_line_length": 135, "alphanum_fraction": 0.6425307557, "num_tokens": 975, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.46382914483480364}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2009, 2014 Jose Aparicio\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n#ifndef quantlib_recursive_loss_model_hpp\n#define quantlib_recursive_loss_model_hpp\n\n#include <ql/experimental/credit/constantlosslatentmodel.hpp>\n#include <ql/experimental/credit/defaultlossmodel.hpp>\n\n#if defined(__GNUC__) && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 8)) || (__GNUC__ > 4))\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wunused-local-typedefs\"\n#endif\n#include <boost/bind.hpp>\n#if defined(__GNUC__) && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 8)) || (__GNUC__ > 4))\n#pragma GCC diagnostic pop\n#endif\n#include <map>\n#include <algorithm>\n\nnamespace QuantLib {\n\n    /*! Recursive STCDO default loss model for a heterogeneous pool of names. \n    The pool names are heterogeneous in their default probabilities, notionals\n    and recovery rates. Correlations are given by the latent model.\n    The recursive pricing algorithm used here is described in Andersen, Sidenius\n    and Basu; \"All your hedges in one basket\", Risk, November 2003, pages 67-72\n\n        Notice that using copulas other than Gaussian it is only an\n        approximation (see remark on p.68).\n\n        \\todo Make the loss unit equal to some small fraction depending on the\n        portfolio loss weights (notionals and recoveries). As it is now this\n        is ok for pricing but not for risk metrics. See the discussion in O'Kane\n        18.3.2\n        \\todo Intengrands should all use the inverted probabilities for \n        performance instead of calling the copula inversion with the same vals.\n    */\n    template<class copulaPolicy> \n    class RecursiveLossModel : public DefaultLossModel {\n    public:\n        RecursiveLossModel(\n            const ext::shared_ptr<ConstantLossLatentmodel<copulaPolicy> >& m,\n// nope! use max common divisor. See O'Kane. Or give both options at least.\n            Size nbuckets  = 1)\n        : copula_(m), nBuckets_(nbuckets), wk_() { }\n      private:\n          /*!\n          @param pDefDate Vector of unconditional default probabilities for each\n          live name (at the current evaluation date). This is passed instead of \n          the date for performance reasons (if in the future other magnitudes \n          -e.g. lgd- are contingent on the date they shouldd be passed too).\n          */\n        Disposable<std::map<Real, Probability> > conditionalLossDistrib(\n            const std::vector<Probability>& pDefDate, \n            const std::vector<Real>& mktFactor) const;\n        Real expectedConditionalLoss(const std::vector<Probability>& pDefDate, //<< never used!!\n            const std::vector<Real>& mktFactor) const;\n        Disposable<std::vector<Real> > conditionalLossProb(\n            const std::vector<Probability>& pDefDate, \n            //const Date& date,\n            const std::vector<Real>& mktFactor) const;\n        //versions using the P-inverse, deprecate the former\n        Disposable<std::map<Real, Probability> > conditionalLossDistribInvP(\n            const std::vector<Real>& pDefDate, \n            //const Date& date,\n            const std::vector<Real>& mktFactor) const;\n        Real expectedConditionalLossInvP(const std::vector<Real>& pDefDate, \n            //const Date& date,\n            const std::vector<Real>& mktFactor) const;\n    protected:\n        void resetModel();\n    public:\n        /*  Expected tranche Loss calculation.\n            This is computed from the first equation on page 70 (not numbered)\n            Notice that while we want to compute:\n            \\f[\n            EL(t) = \\sum_{l_k}l_k P(l;t) =\n              \\sum_{l_k}l_k \\int P(l_k;t|\\omega) d\\omega q(\\omega)\n            \\f]\n            One can invert the sumation and the integral order to:\n            \\f[\n            EL(t) = \\int\\,q(\\omega)\\,d\\omega\\,\\sum_{l_k}\\,l_k\\,P(l_k;t|\\omega) =\n              \\int\\,q(\\omega)\\,d\\omega\\,EL(t|\\omega)\n            \\f]\n            and this is the way it is integrated here. The recursion formula \n            makes it easier this way.\n        */\n       Real expectedTrancheLoss(const Date& date) const;\n       Disposable<std::vector<Real> > lossProbability(const Date& date) const;\n       // REMEBER THIS HAS TO BE MOVED TO A DISTRIBUTION OBJECT.............\n       Disposable<std::map<Real, Probability> > lossDistribution(\n           const Date& d) const;\n       // INTEGRATE THEN SEARCH RATHER THAN SEARCH AND THEN INTEGRATE:\n       // Here I am not using a search because the point might not be attainable\n       //  (loss distrib is not continuous) \n       Real percentile(const Date& d, Real percentile) const;\n       Real expectedShortfall(const Date& d, Real perctl) const;\n    protected:\n        const ext::shared_ptr<ConstantLossLatentmodel<copulaPolicy> > copula_;\n    private:\n        // loss model descriptor members\n        const Size nBuckets_;\n        mutable std::vector<Real> wk_;\n        mutable Real lossUnit_;\n        //! name to name factor. In the single factor copula:\n        //    correl = beta * beta\n        // When constructing through a single correlation number the factor is\n        //   taken to be the positive swuare root of this number in the copula.\n        ////////in the latent model now: mutable std::vector<Real> oneFactorCorrels_;\n        // cached remaining basket magnitudes:\n        mutable Real attachAmount_, \n            detachAmount_,\n            notional_;\n        mutable Size remainingBsktSize_;\n        mutable std::vector<Real> notionals_;\n    };\n\n\n    typedef RecursiveLossModel<GaussianCopulaPolicy> RecursiveGaussLossModel;\n\n    // Inlines ------------------------------------------------\n\n    template<class CP>\n    inline Real RecursiveLossModel<CP>::expectedTrancheLoss(\n        const Date& date) const \n    {\n/*\n        std::map<Real, Probability> dist = lossDistribution(date);\n\n        Real expLoss = 0.;\n        std::map<Real, Probability>::iterator distIt = dist.begin();\n\n        while(distIt != dist.end()) {\n            Real loss = distIt->first * lossUnit_;\n            loss = std::max(std::min(loss, detachAmount_)-attachAmount_, 0.);\n            // MIN MAX BUGS ....??\n            expLoss += loss * distIt->second;\n            distIt++;\n        }\n        return expLoss ;\n\n\n\n\n    ///////////////////////////////////////////////////////////////////////\n\n        // calculate inverted unconditional Ps first so we save the inversion:\n        // TO DO : turn to STL algorithm code\n        std::vector<Probability> uncDefProb = \n            basket_->remainingProbabilities(date);\n\n        return copula_->integratedExpectedValue(\n            boost::function<Real (const std::vector<Real>& v1)>(\n                boost::bind(\n                    &RecursiveLossModel::expectedConditionalLoss,\n                    this,\n                    boost::cref(uncDefProb),\n                    _1)\n                )\n            );\n            */\n/**/\n        std::vector<Probability> uncDefProb = \n            basket_->remainingProbabilities(date);\n        std::vector<Real> invProb;\n        for(Size i=0; i<uncDefProb.size(); ++i)\n           invProb.push_back(copula_->inverseCumulativeY(uncDefProb[i], i));\n           ///  invProb.push_back(CP::inverseCumulativeY(uncDefProb[i], i));//<-static call\n        return copula_->integratedExpectedValue(\n            boost::function<Real (const std::vector<Real>& v1)>(\n                boost::bind(\n                    &RecursiveLossModel::expectedConditionalLossInvP,\n                    this,\n                    boost::cref(invProb),\n                    _1)\n                )\n            );\n            \n    }\n\n    template<class CP>\n    inline Disposable<std::vector<Real> > \n        RecursiveLossModel<CP>::lossProbability(const Date& date) const {\n\n        std::vector<Probability> uncDefProb = \n            basket_->remainingProbabilities(date);\n        return copula_->integratedExpectedValue(\n            boost::function<Disposable<std::vector<Real> > (const std::vector<Real>& v1)>(\n                boost::bind(\n                    &RecursiveLossModel::conditionalLossProb,\n                    this,\n                    boost::cref(uncDefProb),\n                    _1)\n                )\n            );\n    }\n\n    // -------------------------------------------------------------------\n\n    template<class CP>\n    void RecursiveLossModel<CP>::resetModel() {\n        // basket update:\n        notionals_ = basket_->remainingNotionals();\n        notional_  = basket_->remainingNotional();\n        attachAmount_ = basket_->remainingAttachmentAmount();\n        detachAmount_ = basket_->remainingDetachmentAmount();\n        // model parameters:\n        remainingBsktSize_ = notionals_.size();\n\n        copula_->resetBasket(basket_.currentLink());\n\n        std::vector<Real> lgdsTmp, lgds;\n        for(Size i=0; i<remainingBsktSize_; ++i)\n            lgds.push_back(notionals_[i]*(1.-copula_->recoveries()[i]));\n        lgdsTmp = lgds;\n        ///////////////std::remove(lgds.begin(), lgds.end(), 0.);\n        lgds.erase(std::remove(lgds.begin(), lgds.end(), 0.), lgds.end());\n        lossUnit_ = *(std::min_element(lgds.begin(), lgds.end()))\n            / nBuckets_;\n        for(Size i=0; i<remainingBsktSize_; ++i)\n            wk_.push_back(std::floor(lgdsTmp[i]/lossUnit_ + .5));\n    }\n\n    // make it return a distribution object?\n    template<class CP>\n    Disposable<std::map<Real, Probability> > \n        RecursiveLossModel<CP>::lossDistribution(const Date& d) const \n    {\n        std::map<Real, Probability> distrib;\n        std::vector<Real> values  = lossProbability(d);\n        Real sum = 0.;\n        for(Size i=0; i<values.size(); ++i) {\n            distrib.insert(std::make_pair<Real, Probability>(i * lossUnit_, \n                sum + values[i]));\n            sum += values[i];\n        }\n        return distrib;\n    }\n\n    // Integrate then search rather than search and then integrate?\n    // Here I am not using a search because the point might be not attainable \n    //   (loss distrib is not continuous) \n    template<class CP>\n    Real RecursiveLossModel<CP>::percentile(const Date& d, \n        Real percentile) const \n    {\n        std::map<Real, Probability> dist = lossDistribution(d);\n\n        if(dist.begin()->second >=1.) return dist.begin()->first;\n\n        // deterministic case (e.g. date requested is todays date)\n        if(dist.size() == 1) return dist.begin()->first;\n\n        if(percentile == 1.) return dist.rbegin()->second;\n        if(percentile == 0.) return dist.begin()->second;\n        std::map<Real, Probability>::const_iterator itdist = dist.begin();\n        while (itdist->second <= percentile) ++itdist;\n        Real valPlus = itdist->second;\n        Real xPlus   = itdist->first;\n        --itdist;  //we're never 1st or last, because of tests above\n        Real valMin  = itdist->second;\n        Real xMin    = itdist->first;\n\n        // return xPlus-(xPlus-xMin)*(valPlus-percentile)/(valPlus-valMin);\n        Real portfLoss =  xPlus-(xPlus-xMin)*(valPlus-percentile)\n            /(valPlus-valMin);\n        return //remainingNotional_ * \n            std::min(std::max(portfLoss - attachAmount_, 0.), \n                detachAmount_ - attachAmount_);/////(detach_ - attach_);\n    }\n\n    template<class CP>\n    Real RecursiveLossModel<CP>::expectedShortfall(const Date& d, \n        Real perctl) const \n    {\n        if(d == Settings::instance().evaluationDate()) return 0.;\n        std::map<Real, Probability> distrib = lossDistribution(d);\n\n        std::map<Real, Probability>::iterator itNxt, itDist = \n            distrib.begin();\n        for(; itDist != distrib.end(); ++itDist)\n            if(itDist->second >= perctl) break;\n        itNxt = itDist;\n        --itDist; // what if we are on the first one?!!!\n\n        // One could linearly triangulate the exact point and get extra \n        // precission on the first(broken) period.\n        if(itNxt != distrib.end()) { \n            Real lossNxt = std::min(std::max(itNxt->first - attachAmount_, \n                0.), detachAmount_ - attachAmount_);\n            Real lossHere = std::min(std::max(itDist->first - attachAmount_,\n                0.), detachAmount_ - attachAmount_);\n\n            Real val =  lossNxt - (itNxt->second - perctl) * \n                (lossNxt - lossHere) / (itNxt->second - itDist->second); \n            Real suma = (itNxt->second - perctl) * (lossNxt + val) * .5;\n            ++itDist; ++itNxt;\n            do{\n                lossNxt = std::min(std::max(itNxt->first - attachAmount_, \n                    0.), detachAmount_ - attachAmount_);\n                lossHere = std::min(std::max(itDist->first - attachAmount_, \n                    0.), detachAmount_ - attachAmount_);\n                suma += .5 * (lossHere + lossNxt) * (itNxt->second - \n                    itDist->second);\n                ++itDist; ++itNxt;\n            }while(itNxt != distrib.end());\n            return suma / (1.-perctl);\n        }\n        return 0.;// well, we are in error....  fix: FAIL\n    }\n\n    template<class CP>\n    Disposable<std::map<Real, Probability> >\n        RecursiveLossModel<CP>::conditionalLossDistrib(\n            const std::vector<Probability>& pDefDate, \n            //const Date& date,\n            const std::vector<Real>& mktFactor) const \n    {\n        //eq. 10 p.68\n        //attainable losses distribution, recursive algorithm\n        const std::vector<Probability>& uncDefProb = pDefDate;// alias, remove\n\n        std::map<Real, Probability> pIndepDistrib;\n        ////////  K=0\n        pIndepDistrib.insert(std::make_pair(0., 1.));\n        for(Size iName=0; iName<remainingBsktSize_; ++iName) {\n            Probability pDef =\n                copula_->conditionalDefaultProbability(uncDefProb[iName], iName,\n                                                mktFactor);\n            ////// iterate on all possible losses in the distribution:\n            std::map<Real, Probability> pDistTemp;\n            std::map<Real, Probability>::iterator distIt =\n                pIndepDistrib.begin();\n            while(distIt != pIndepDistrib.end()) {\n              ///   update prob if this name does not default\n                std::map<Real, Probability>::iterator matchIt\n                    = pDistTemp.find(distIt->first);\n                if(matchIt != pDistTemp.end()) {\n                    matchIt->second += distIt->second * (1.-pDef);\n                }else{\n                    pDistTemp.insert(std::make_pair(distIt->first,\n                        distIt->second * (1.-pDef)));\n                }\n              ////   and if it does\n                matchIt = pDistTemp.find(distIt->first + wk_[iName]);\n                if(matchIt != pDistTemp.end()) {\n                    matchIt->second += distIt->second * pDef;\n                }else{\n                    pDistTemp.insert(std::make_pair(\n                        distIt->first+wk_[iName], distIt->second * pDef));\n                }\n                ++distIt;\n            }\n           /////  copy back\n            pIndepDistrib = pDistTemp;\n        }\n        /* Apply tranche limits now .... mind you this could be done outside*/\n        ////  to be done....\n        return pIndepDistrib;\n    }\n\n    template<class CP>\n    Disposable<std::map<Real, Probability> >\n        // twice?! rewrite one in terms of the other, this is a duplicate!\n        RecursiveLossModel<CP>::conditionalLossDistribInvP(\n            const std::vector<Real>& invpDefDate, \n            //const Date& date,\n            const std::vector<Real>& mktFactor) const \n    {\n        // eq. 10 p.68\n        // attainable losses distribution, recursive algorithm\n\n        std::map<Real, Probability> pIndepDistrib;\n        // K=0\n        pIndepDistrib.insert(std::make_pair(0., 1.));\n        for(Size iName=0; iName<remainingBsktSize_; ++iName) {\n            Probability pDef =\n                copula_->conditionalDefaultProbabilityInvP(invpDefDate[iName], \n                    iName, mktFactor);\n\n            // iterate on all possible losses in the distribution:\n            std::map<Real, Probability> pDistTemp;\n            std::map<Real, Probability>::iterator distIt =\n                pIndepDistrib.begin();\n            while(distIt != pIndepDistrib.end()) {\n                // update prob if this name does not default\n                std::map<Real, Probability>::iterator matchIt\n                    = pDistTemp.find(distIt->first);\n                if(matchIt != pDistTemp.end()) {\n                    matchIt->second += distIt->second * (1.-pDef);\n                }else{\n                    pDistTemp.insert(std::make_pair(distIt->first,\n                        distIt->second * (1.-pDef)));\n                }\n                // and if it does\n                matchIt = pDistTemp.find(distIt->first + wk_[iName]);\n                if(matchIt != pDistTemp.end()) {\n                    matchIt->second += distIt->second * pDef;\n                }else{\n                    pDistTemp.insert(std::make_pair(\n                        distIt->first+wk_[iName], distIt->second * pDef));\n                }\n                ++distIt;\n            }\n            // copy back\n            pIndepDistrib = pDistTemp;\n        }\n        /* Apply tranche limits now .... mind you this could be done outside*/\n        return pIndepDistrib;\n    }\n\n\n\n\n    /*\n    Bugs here???. The max min on the tranche looks \n    wrong. It is better to have a tranche function since that way we can avoid \n    adding up losses over all the posible losses rather than just over the \n    tranche limits.\n    */\n    //! Portfolio loss conditional to the market factor value\n    template<class CP>\n    Real RecursiveLossModel<CP>::expectedConditionalLoss(\n        const std::vector<Probability>& pDefDate, \n        //const Date& date,\n        const std::vector<Real>& mktFactor) const \n    {\n        std::map<Real, Probability> pIndepDistrib =\n            conditionalLossDistrib(pDefDate, mktFactor);\n\n        // get the expected value subject to the value of the market\n        //   factor.\n        Real expLoss = 0.;\n        //---------------------------------------------------------------\n        /* This is the original (easy to read) loop which I have partially\n             unroll below to take profit of the fact that once we go over\n             the tranche top the loss amount is fixed:\n        */\n        std::map<Real, Probability>::iterator distIt =\n            pIndepDistrib.begin();\n\n        while(distIt != pIndepDistrib.end()) {\n            Real loss = distIt->first * lossUnit_;\n     //       loss = std::max(std::min(loss, detachAmount_)-attachAmount_, 0.);\n            loss = std::min(std::max(loss - attachAmount_, 0.), \n                detachAmount_ - attachAmount_);\n            // MIN MAX BUGS ....??\n            expLoss += loss * distIt->second;\n            ++distIt;\n        }\n        return expLoss ;\n    }\n\n    template<class CP>\n    // again, I am duplicating code.\n    Real RecursiveLossModel<CP>::expectedConditionalLossInvP(\n                                 const std::vector<Real>& invPDefDate, \n                                 //const Date& date,\n                                 const std::vector<Real>& mktFactor) const \n    {\n        std::map<Real, Probability> pIndepDistrib =\n            conditionalLossDistribInvP(invPDefDate, mktFactor);\n\n        // get the expected value subject to the value of the market\n        //   factor.\n        Real expLoss = 0.;\n        //---------------------------------------------------------------\n        /* This is the original (easy to read) loop which I have partially\n             unroll below to take profit of the fact that once we go over\n             the tranche top the loss amount is fixed:\n        */\n        std::map<Real, Probability>::iterator distIt =\n            pIndepDistrib.begin();\n\n        while(distIt != pIndepDistrib.end()) {\n            Real loss = distIt->first * lossUnit_;\n   //         loss = std::max(std::min(loss, detachAmount_)-attachAmount_, 0.);\n            loss = std::min(std::max(loss - attachAmount_, 0.), \n                detachAmount_ - attachAmount_);\n            // MIN MAX BUGS ....???\n            expLoss += loss * distIt->second;\n            ++distIt;\n        }\n        return expLoss ;\n    }\n\n    template<class CP>\n    Disposable<std::vector<Real> > RecursiveLossModel<CP>::conditionalLossProb(\n        const std::vector<Probability>& pDefDate, \n        //const Date& date,\n        const std::vector<Real>& mktFactor) const \n    {\n        std::map<Real, Probability> pIndepDistrib =\n            conditionalLossDistrib(pDefDate, mktFactor);\n\n        std::vector<Real> results;\n        std::map<Real, Probability>::iterator distIt = pIndepDistrib.begin();\n        while(distIt != pIndepDistrib.end()) {\n            //Real loss = distIt->first * loss_unit_\n            //                    ;\n            //loss = std::max(std::min(loss,\n            //    results_.xMax)-results_.xMin, 0.);\n            //expLoss += loss * distIt->second;\n\n            results.push_back(distIt->second);\n             ++distIt;\n        }\n        return results;\n    }\n\n}\n\n#endif\n", "meta": {"hexsha": "4fa0067a9d8ffaf48e52e1b6fa446fe48d5c487c", "size": 21789, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/experimental/credit/recursivelossmodel.hpp", "max_stars_repo_name": "tlapfai/My-Quantlib", "max_stars_repo_head_hexsha": "9e24dafd8c849659d3a9b4b432abf854441ab825", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/credit/recursivelossmodel.hpp", "max_issues_repo_name": "tlapfai/My-Quantlib", "max_issues_repo_head_hexsha": "9e24dafd8c849659d3a9b4b432abf854441ab825", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/credit/recursivelossmodel.hpp", "max_forks_repo_name": "tlapfai/My-Quantlib", "max_forks_repo_head_hexsha": "9e24dafd8c849659d3a9b4b432abf854441ab825", "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": 41.0338983051, "max_line_length": 96, "alphanum_fraction": 0.5707008123, "num_tokens": 5027, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342624, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.4638291393932732}}
{"text": "// ---------------------------------------------------------------------\n//\n// Copyright (c) 2019 - 2020 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\n#include <SAMRAI_config.h>\n\n// Headers for basic libMesh objects\n#include <libmesh/mesh.h>\n#include <libmesh/mesh_generation.h>\n\n// Headers for application-specific algorithm/data structure objects\n#include <ibtk/AppInitializer.h>\n#include <ibtk/IBTKInit.h>\n#include <ibtk/libmesh_utilities.h>\n\n// Set up application namespace declarations\n#include <ibamr/app_namespaces.h>\n\n#include <boost/multi_array.hpp>\n\n// Verify that the new function, IBTK::get_max_edge_length, prints out the\n// same result as the old get_elem_hmax function (that was internal to\n// FEDataManager). Test with several 3D meshes.\n\nvoid\nlog_max_edge_length(const ReplicatedMesh& mesh)\n{\n    const unsigned int dim = mesh.mesh_dimension();\n    boost::multi_array<double, 2> X_node;\n    for (auto elem_iter = mesh.active_local_elements_begin(); elem_iter != mesh.active_local_elements_end();\n         ++elem_iter)\n    {\n        auto elem = *elem_iter;\n        // Don't bother with deformation: just use the material coordinates\n        boost::multi_array<double, 2>::extent_gen extent;\n        const unsigned int n_nodes = elem->n_nodes();\n        X_node.resize(extent[n_nodes][dim]);\n\n        const Node* const* nodes = elem->get_nodes();\n        for (unsigned int node_n = 0; node_n < n_nodes; ++node_n)\n            for (unsigned int d = 0; d < dim; ++d) X_node[node_n][d] = (*nodes[node_n])(d);\n\n        plog << std::setprecision(12) << get_max_edge_length(elem, X_node) << std::endl;\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    {\n        Pointer<AppInitializer> app_initializer = new AppInitializer(argc, argv, \"IB.log\");\n\n        Pointer<Database> input_db = app_initializer->getInputDatabase();\n        const double radius = 2.0;\n        const unsigned int n_refinements = 1;\n\n        {\n            plog << \"Test 1: tet4\" << std::endl;\n            ReplicatedMesh mesh(init.comm(), 3);\n            MeshTools::Generation::build_cube(mesh, 2, 3, 3, 0.0, 0.7, 0.1, 0.9, 1.0, 2.0, TET4);\n            log_max_edge_length(mesh);\n        }\n\n        {\n            plog << std::endl << \"Test 1: tet10\" << std::endl;\n            ReplicatedMesh mesh(init.comm(), 3);\n            MeshTools::Generation::build_cube(mesh, 2, 3, 3, 0.0, 0.7, 0.1, 0.9, 1.0, 2.0, TET10);\n            log_max_edge_length(mesh);\n        }\n\n        // like the last test, but wobble the triangulation a bit so that the\n        // edges are not all straight lines\n        {\n            plog << std::endl << \"Test 2: tet10\" << std::endl;\n            ReplicatedMesh mesh(init.comm(), 3);\n            MeshTools::Generation::build_cube(mesh, 2, 3, 3, 0.0, 0.7, 0.1, 0.9, 1.0, 2.0, TET10);\n            for (std::size_t node_n = 0; node_n < mesh.n_nodes(); ++node_n)\n            {\n                const double y = (*mesh.node_ptr(node_n))(1);\n                (*mesh.node_ptr(node_n))(0) += 2 * y * (1 - y);\n            }\n            log_max_edge_length(mesh);\n        }\n\n        {\n            plog << std::endl << \"Test 3: pyramid5\" << std::endl;\n            ReplicatedMesh mesh(init.comm(), 3);\n            MeshTools::Generation::build_cube(mesh, 2, 3, 3, 0.0, 0.7, 0.1, 0.9, 1.0, 2.0, PYRAMID5);\n            log_max_edge_length(mesh);\n        }\n\n        {\n            plog << std::endl << \"Test 4: hex8\" << std::endl;\n            ReplicatedMesh mesh(init.comm(), 3);\n            MeshTools::Generation::build_sphere(mesh, radius, n_refinements, HEX8);\n            log_max_edge_length(mesh);\n        }\n\n        {\n            plog << std::endl << \"Test 5: hex27\" << std::endl;\n            ReplicatedMesh mesh(init.comm(), 3);\n            MeshTools::Generation::build_sphere(mesh, radius, n_refinements, HEX27);\n            log_max_edge_length(mesh);\n        }\n    }\n} // main\n", "meta": {"hexsha": "611e3401c07a4c7786f192859b15e6924b2debcb", "size": 4380, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/IBTK/elem_hmax_02.cpp", "max_stars_repo_name": "kkeonho/IBAMR", "max_stars_repo_head_hexsha": "50d5c37d8f2952abc21f05ab224f22003d23d6e7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/IBTK/elem_hmax_02.cpp", "max_issues_repo_name": "kkeonho/IBAMR", "max_issues_repo_head_hexsha": "50d5c37d8f2952abc21f05ab224f22003d23d6e7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-07-13T02:41:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-16T07:07:19.000Z", "max_forks_repo_path": "tests/IBTK/elem_hmax_02.cpp", "max_forks_repo_name": "drwells/IBAMR", "max_forks_repo_head_hexsha": "0ceda3873405a35da4888c99e7d2b24d132f9071", "max_forks_repo_licenses": ["BSD-3-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.9016393443, "max_line_length": 108, "alphanum_fraction": 0.5865296804, "num_tokens": 1181, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754607093178, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.4637427860978798}}
{"text": "/// HEADER\n#include <cslibs_vectormaps/maps/oriented_grid_vector_map.h>\n\n/// COMPONENT\n#include <cslibs_boost_geometry/algorithms.h>\n#include <cslibs_vectormaps/utility/tools.hpp>\n#include <boost/geometry.hpp>\n\n#include <utility>\n#include <iostream>\n\nusing namespace cslibs_vectormaps;\nusing namespace cslibs_boost_geometry;\n\nOrientedGridVectorMap::OrientedGridVectorMap(const BoundingBox &bounding,\n                                             const double       range,\n                                             const double       resolution,\n                                             const double       angular_resolution,\n                                             const bool         debug)\n    : GridVectorMap(bounding, range, resolution, debug),\n      angular_resolution_(angular_resolution)\n{\n    theta_bins_      = std::ceil(2 * M_PI / angular_resolution);\n    theta_bins_inv_  = 1.0 / theta_bins_;\n    grid_dimensions_ = {rows_, cols_, theta_bins_};\n    grid_.resize(grid_dimensions_.globalSize());\n\n    fovs_.resize(theta_bins_);\n\n    // calculate all possible fovs\n    for(std::size_t bin = 0; bin < theta_bins_; ++bin) {\n        // allow for some leeway\n        double low = index2lowerAngle(bin) - theta_bins_inv_ * 0.5 * M_PI;\n        double up  = index2upperAngle(bin) + theta_bins_inv_ * 0.5 * M_PI;\n\n        // need to check the four corners to guarantee seeing every vector\n        double o = resolution / 2;\n        Point corner[4];\n        corner[0] = Point(-o, -o);\n        corner[1] = Point(+o, -o);\n        corner[2] = Point(+o, +o);\n        corner[3] = Point(-o, +o);\n\n        double r = 10 * range;\n        Point ray_up(r * std::cos(up), r * std::sin(up));\n        Point ray_low(r * std::cos(low), r * std::sin(low));\n\n        Polygon polygon;\n        for(unsigned int c = 0; c < 4; ++c) {\n            boost::geometry::append(polygon.outer(),\n                                    corner[c]);\n            boost::geometry::append(polygon.outer(),\n                                    Point(corner[c].x() + ray_up.x(),\n                                          corner[c].y() + ray_up.y()));\n            boost::geometry::append(polygon.outer(),\n                                    Point(corner[c].x() + ray_low.x(),\n                                          corner[c].y() + ray_low.y()));\n        }\n\n        boost::geometry::convex_hull(polygon, fovs_[bin]);\n    }\n}\n\nOrientedGridVectorMap::OrientedGridVectorMap() :\n    GridVectorMap()\n{\n}\n\nunsigned int OrientedGridVectorMap::handleInsertion()\n{\n    unsigned int assigned = 0;\n\n    const std::size_t rows = grid_dimensions_.size<0>();\n    const std::size_t cols = grid_dimensions_.size<1>();\n\n    std::cout << \"generating index\\n\";\n\n    if(valid_area_.outer().empty()) {\n#pragma omp parallel for reduction(+:assigned)\n        for(unsigned int i = 0 ; i < rows ; ++i) {\n            Point min(min_corner_.x() - padding_,\n                      min_corner_.y() - padding_ + i * resolution_);\n            Point max(min_corner_.x() + padding_ + resolution_,\n                      min_corner_.y() + padding_ + (i+1) * resolution_);\n\n            for(unsigned int j = 0 ; j < cols ; ++j) {\n                std::cout << \"generating \" << (i+1) << \"\\t/ \" << (j+1);\n\n                BoundingBox cell_bounding(min, max);\n                Point center(min_corner_.x() + (j + 0.5) * resolution_,\n                             min_corner_.y() + (i + 0.5) * resolution_);\n\n                VectorPtrs  possible_lines;\n                findPossibleLines(center, cell_bounding, possible_lines);\n                int dropped = 0;\n\n                dropped += removeHiddenLines(center, cell_bounding, possible_lines);\n\n                // need to check the four corners to guarantee seeing every vector\n                std::set<const Vector*> visible_lines;\n                double sample_resolution = 1.0;\n                unsigned int sampling_steps = std::ceil(resolution_ / sample_resolution);\n                double sample_width_step = resolution_ / (double) sampling_steps;\n\n                for(unsigned int si = 0 ; si < sampling_steps ; ++si) {\n                    for(unsigned int sj = 0 ; sj < sampling_steps ; ++sj) {\n\n                        Point sample(min_corner_.x() + j * resolution_ + sj * sample_width_step,\n                                     min_corner_.y() + i * resolution_ + si * sample_width_step);\n\n                        findVisibleLinesByRaycasting(sample, cell_bounding, possible_lines, visible_lines);\n                    }\n                }\n\n                dropped += (possible_lines.size() - visible_lines.size());\n                possible_lines.assign(visible_lines.begin(), visible_lines.end());\n\n                std::cout << \"\\t\" << possible_lines.size() << \" visible lines (\" << dropped << \" dropped)\\n\";\n\n                for(unsigned int t = 0 ; t < theta_bins_ ; ++t) {\n                    VectorPtrs cell;\n\n                    for(const Vector* line : possible_lines) {\n                        /*Point current_center((min.x() + max.x()) * 0.5,\n                                             (min.y() + max.y()) * 0.5);*/\n                        if(isInView(*line, center, t)) {\n                            cell.push_back(line);\n                        }\n                    }\n\n                    grid_[grid_dimensions_.index(i,j,t)] = cell;\n\n                    ++assigned;\n                }\n\n                min.x(min.x() + resolution_);\n                max.x(max.x() + resolution_);\n            }\n        }\n    } else {\n#pragma omp parallel for reduction(+:assigned)\n        for(unsigned int i = 0 ; i < rows ; ++i) {\n            Point min(min_corner_.x() - padding_,\n                      min_corner_.y() - padding_ + i * resolution_);\n            Point pmin(min_corner_.x(),\n                       min_corner_.y() + i * resolution_);\n            Point max(min_corner_.x()  + padding_ + resolution_,\n                      min_corner_.y()  + padding_ + (i+1) * resolution_);\n            Point pmax(min_corner_.x() + resolution_,\n                       min_corner_.y() + (i+1) * resolution_);\n\n            for(unsigned int j = 0 ; j < cols ; ++j) {\n                Polygon     cell_bounding_polygon = algorithms::toPolygon<Point>(pmin, pmax);\n                if(algorithms::covered_by<Point>(cell_bounding_polygon, valid_area_)) {\n                    std::cout << \"generating \" << (i+1) << \"\\t/ \" << (j+1);\n\n                    BoundingBox cell_bounding(min, max);\n                    Point center(min_corner_.x() + (j + 0.5) * resolution_,\n                                 min_corner_.y() + (i + 0.5) * resolution_);\n\n                    VectorPtrs  possible_lines;\n                    findPossibleLines(center, cell_bounding, possible_lines);\n                    int dropped = 0;\n\n                    dropped += removeHiddenLines(center, cell_bounding, possible_lines);\n\n                    // need to check the four corners too guarantee seeing every vector\n                    std::set<const Vector*> visible_lines;\n                    double sample_resolution = 1.0;\n                    unsigned int sampling_steps = std::ceil(resolution_ / sample_resolution);\n                    double sample_width_step = resolution_ / (double) sampling_steps;\n\n                    for(unsigned int si = 0 ; si < sampling_steps ; ++si) {\n                        for(unsigned int sj = 0 ; sj < sampling_steps ; ++sj) {\n\n                            Point sample(min_corner_.x() + j * resolution_ + sj * sample_width_step,\n                                         min_corner_.y() + i * resolution_ + si * sample_width_step);\n\n                            findVisibleLinesByRaycasting(sample, cell_bounding, possible_lines, visible_lines);\n                        }\n                    }\n\n                    dropped += (possible_lines.size() - visible_lines.size());\n                    possible_lines.assign(visible_lines.begin(), visible_lines.end());\n\n                    std::cout << \"\\t\" << possible_lines.size() << \" visible lines (\" << dropped << \" dropped)\\n\";\n\n                    for(unsigned int t = 0 ; t < theta_bins_ ; ++t) {\n                        VectorPtrs cell;\n\n                        for(const Vector* line : possible_lines) {\n                            /*Point current_center((min.x() + max.x()) * 0.5,\n                                                 (min.y() + max.y()) * 0.5);*/\n                            if(isInView(*line, center, t)) {\n                                cell.push_back(line);\n                            }\n                        }\n\n                        grid_[grid_dimensions_.index(i,j,t)] = cell;\n\n                        ++assigned;\n                    }\n                } else {\n                    if(debug_) {\n                        std::cout << \"Cell out of valid area!\\n\";\n                    }\n                }\n\n                min.x(min.x() + resolution_);\n                max.x(max.x() + resolution_);\n                pmin.x(pmin.x() + resolution_);\n                pmax.x(pmax.x() + resolution_);\n            }\n        }\n    }\n\n    return assigned;\n}\n\nvoid OrientedGridVectorMap::findPossibleLines(const Point &center, const BoundingBox &cell_bounding, VectorPtrs &necessary_lines) const\n{\n    for(const Vector& line : data_) {\n        if(algorithms::touches<Point>(line, cell_bounding)) {\n            necessary_lines.push_back(&line);\n        }\n    }\n}\n\nint OrientedGridVectorMap::removeHiddenLines(const Point& center,\n                                             const BoundingBox& cell_bounding,\n                                             VectorPtrs& possible_lines) const\n{\n    // need to check the four corners to guarantee seeing every vector\n    double o = resolution_ * 0.5;\n    Point corner[4];\n    corner[0] = Point(center.x() - o, center.y() - o);\n    corner[1] = Point(center.x() + o, center.y() - o);\n    corner[2] = Point(center.x() + o, center.y() + o);\n    corner[3] = Point(center.x() - o, center.y() + o);\n\n    BoundingBox bb(corner[0], corner[2]);\n\n    //VectorPtrs visible_lines = necessary_lines;\n    //    std::sort(necessary_lines.begin(), necessary_lines.end(), by_length());\n\n    // find necessary lines\n    std::list<const Vector*> visible_lines;//(necessary_lines.begin(), necessary_lines.end());\n    std::vector<const Vector*> necessary_lines;\n\n    for(const Vector* line : possible_lines) {\n        if(algorithms::touches<Point>(*line, bb)) {\n            necessary_lines.push_back(line);\n        } else {\n            visible_lines.push_back(line);\n        }\n    }\n\n    //    std::cerr << \"necessary: \" << necessary_lines.size() << \"\\tvisible: \" << visible_lines.size() << \"\\n\";\n\n    int dropped = 0;\n    for(auto line_it = visible_lines.begin(); line_it != visible_lines.end(); ++line_it) {\n        const Vector& line = **line_it;\n\n        // now check if *line* completely covers other lines\n        for(auto other_it = visible_lines.begin(); other_it != visible_lines.end();) {\n            if(other_it == line_it) {\n                ++other_it;\n                continue;\n            }\n            const Vector& other = **other_it;\n\n            bool covered = true; // iff every line between corners and *other* crosses *line*\n            for(unsigned int c = 0; c < 4; ++c) {\n                //std::vector<VectorMap::Point> inter;\n\n                Vector c1(corner[c], other.first);\n                if(!boost::geometry::intersects(c1, line)) {\n                    covered = false;\n                    break;\n                }\n                Vector c2(corner[c], other.second);\n                if(!boost::geometry::intersects(c2, line)) {\n                    covered = false;\n                    break;\n                }\n            }\n\n            if(covered) {\n                other_it = visible_lines.erase(other_it);\n                ++dropped;\n            } else {\n                ++other_it;\n            }\n        }\n    }\n\n    possible_lines = std::move(necessary_lines);\n    possible_lines.insert(possible_lines.end(), visible_lines.begin(), visible_lines.end());\n\n    return dropped;\n}\n\n\nvoid OrientedGridVectorMap::findVisibleLinesByRaycasting(const Point& center,\n                                                         const BoundingBox& cell_bounding,\n                                                         const VectorPtrs& possible_lines,\n                                                         std::set<const Vector*> &visible) const\n{\n    double max_range = 1e10;\n    double angular_res = algorithms::rad(2.0);\n    for(double theta = -M_PI; theta < M_PI; theta += angular_res) {\n        Vector ray(center, Point(max_range * std::cos(theta), max_range * std::sin(theta)));\n        double min_dist = std::numeric_limits<double>::max();\n        const Vector* min_line = nullptr;\n\n        for(const Vector* other : possible_lines) {\n            std::vector<Point> intersections;\n            boost::geometry::intersection(ray, *other, intersections);\n            if(!intersections.empty()) {\n                const Point& hit = intersections.front();\n                double distance = boost::geometry::distance(center, hit);\n                if(distance < min_dist) {\n                    min_dist = distance;\n                    min_line = other;\n                }\n            }\n        }\n        if(min_line != nullptr) {\n            visible.insert(min_line);\n        }\n    }\n}\n\nconst void* OrientedGridVectorMap::cell(const Point& pos) const\n{\n    return &grid_[grid_dimensions_.index(row(pos), col(pos), 0)];\n}\n\nbool OrientedGridVectorMap::isInView(const Vector& line, Point center, std::size_t t) const\n{\n    // take the general fov and shift it to center\n    Vector linecopy = line;\n    boost::geometry::subtract_point(linecopy.first, center);\n    boost::geometry::subtract_point(linecopy.second, center);\n\n    return algorithms::touches<Point>(linecopy, fovs_[t]);\n}\n\ndouble OrientedGridVectorMap::angularResolution() const\n{\n    return angular_resolution_;\n}\n\ndouble OrientedGridVectorMap::minSquaredDistanceNearbyStructure(const Point& pos,\n                                                                const void* cell_ptr,\n                                                                const double angle) const\n{\n    unsigned int theta = angle2index(angle);\n    double min_squared_dist = std::numeric_limits<double>::max();\n    const VectorPtrs& cell = static_cast<const VectorPtrs*>(cell_ptr)[theta];\n\n    for (const Vector* line : cell) {\n        double squared_dist = boost::geometry::comparable_distance(pos, *line);\n        if (squared_dist < min_squared_dist)\n            min_squared_dist = squared_dist;\n    }\n\n    return min_squared_dist;\n}\n\ndouble OrientedGridVectorMap::minDistanceNearbyStructure(const Point &pos,\n                                                         const unsigned int row,\n                                                         const unsigned int col,\n                                                         const double angle) const\n{\n    unsigned int theta = angle2index(angle);\n    double min_dist = std::numeric_limits<double>::max();\n    auto cell = grid_.at(grid_dimensions_.index(row, col, theta));\n\n    for(const Vector* line : cell) {\n        double dist = algorithms::distance<double,Point>(pos, *line);\n        if(dist < min_dist)\n            min_dist = dist;\n    }\n\n    return min_dist;\n}\n\ndouble OrientedGridVectorMap::minSquaredDistanceNearbyStructure(const Point &pos,\n                                                                const unsigned int row,\n                                                                const unsigned int col,\n                                                                const double angle) const\n{\n    unsigned int theta = angle2index(angle);\n    double min_squared_dist = std::numeric_limits<double>::max();\n    auto cell = grid_.at(grid_dimensions_.index(row, col, theta));\n\n    for(const Vector* line : cell) {\n        double squared_dist = boost::geometry::comparable_distance(pos, *line);\n        if(squared_dist < min_squared_dist)\n            min_squared_dist = squared_dist;\n    }\n\n    return min_squared_dist;\n}\n\nunsigned int OrientedGridVectorMap::thetaBins() const\n{\n    return theta_bins_;\n}\n\ndouble OrientedGridVectorMap::minDistanceNearbyStructure(const Point &pos) const\n{\n    if(tools::pointOutsideMap(pos, min_corner_, max_corner_)) {\n        if(debug_) {\n            std::cerr << \"[OrientedGridVectorMap] : Position to test \"\n                         \"not within grid structured area!\\n\";\n        }\n        return false;\n    }\n\n    unsigned int row = GridVectorMap::row(pos);\n    unsigned int col = GridVectorMap::col(pos);\n\n    double min_dist = std::numeric_limits<double>::max();\n\n    for(unsigned int theta = 0 ; theta < grid_dimensions_.size<2>() ; ++theta) {\n        const VectorPtrs &cell = grid_.at(grid_dimensions_.index(row, col, theta));\n        for(const Vector* line : cell) {\n            double dist = algorithms::distance<double,Point>(pos, *line);\n            if(dist < min_dist)\n                min_dist = dist;\n        }\n    }\n\n    if(min_dist == std::numeric_limits<double>::max())\n        return -1.0;\n    else\n        return min_dist;\n}\n\ndouble OrientedGridVectorMap::minSquaredDistanceNearbyStructure(const Point &pos) const\n{\n    if(tools::pointOutsideMap(pos, min_corner_, max_corner_)) {\n        if(debug_) {\n            std::cerr << \"[OrientedGridVectorMap] : Position to test \"\n                         \"not within grid structured area!\\n\";\n        }\n        return false;\n    }\n\n    unsigned int row = GridVectorMap::row(pos);\n    unsigned int col = GridVectorMap::col(pos);\n\n    double min_squared_dist = std::numeric_limits<double>::max();\n\n    for(unsigned int theta = 0 ; theta < grid_dimensions_.size<2>() ; ++theta) {\n        const VectorPtrs &cell = grid_.at(grid_dimensions_.index(row, col, theta));\n        for(const Vector* line : cell) {\n            double squared_dist = boost::geometry::comparable_distance(pos, *line);\n            if(squared_dist < min_squared_dist)\n                min_squared_dist = squared_dist;\n        }\n    }\n\n    if(min_squared_dist == std::numeric_limits<double>::max())\n        return -1.0;\n    else\n        return min_squared_dist;\n}\n\nbool OrientedGridVectorMap::structureNearby(const Point &pos,\n                                            const double thresh) const\n{\n    if(tools::pointOutsideMap(pos, min_corner_, max_corner_)) {\n        if(debug_) {\n            std::cerr << \"[OrientedGridVectorMap] : Position to test \"\n                         \"not within grid structured area!\\n\";\n        }\n        return false;\n    }\n\n    unsigned int row = GridVectorMap::row(pos);\n    unsigned int col = GridVectorMap::col(pos);\n\n    for(unsigned int theta = 0 ; theta < grid_dimensions_.size<2>() ; ++theta) {\n        const VectorPtrs &cell = grid_.at(grid_dimensions_.index(row, col, theta));\n        for(const Vector* line : cell) {\n            double dist = algorithms::distance<double,Point>(pos, *line);\n            if(dist > 0.0 && dist < thresh)\n                return true;\n        }\n    }\n\n    return false;\n}\n\nbool OrientedGridVectorMap::retrieveFiltered(const Point &pos,\n                                             const double orientation,\n                                             Vectors &lines) const\n{\n    if(tools::pointOutsideMap(pos, min_corner_, max_corner_)) {\n        if(debug_) {\n            std::cerr << \"[OrientedGridVectorMap] : Position to test \"\n                         \"not within grid structured area!\\n\";\n        }\n        return false;\n    }\n\n    // find the cell of point pos\n    unsigned int row = GridVectorMap::row(pos);\n    unsigned int col = GridVectorMap::col(pos);\n    unsigned int theta = angle2index(orientation);\n\n    const VectorPtrs &cell = grid_.at(grid_dimensions_.index(row, col, theta));\n\n\n    // compute the exact bound box for pos\n    //  (if the resolution is large, there might be many unnecessary lines)\n    Point min(pos.x() - range_, pos.y() - range_);\n    Point max(pos.x() + range_, pos.y() + range_);\n    BoundingBox bound(min, max);\n\n    for(const Vector* line : cell) {\n        // filter out unnecessary lines\n        if(algorithms::touches<Point>(*line, bound)) {\n            lines.push_back(*line);\n        }\n    }\n\n    return lines.size() > 0;\n}\n\n\nbool OrientedGridVectorMap::retrieve(const Point &pos,\n                                     const double orientation,\n                                     Vectors     &lines) const\n{\n    if(tools::pointOutsideMap(pos, min_corner_, max_corner_)) {\n        if(debug_) {\n            std::cerr << \"[OrientedGridVectorMap] : Position to test \"\n                         \"not within grid structured area!\\n\";\n        }\n        return false;\n    }\n\n    // find the cell of point pos\n    unsigned int row = GridVectorMap::row(pos);\n    unsigned int col = GridVectorMap::col(pos);\n    unsigned int theta = angle2index(orientation);\n\n    const VectorPtrs &cell = grid_.at(grid_dimensions_.index(row, col, theta));\n\n    for(const Vector* line : cell) {\n        lines.push_back(*line);\n    }\n\n    return lines.size() > 0;\n}\n\nbool OrientedGridVectorMap::retrieve(const double x,\n                                     const double y,\n                                     const double orientation,\n                                     Vectors &lines) const\n{\n    if(tools::coordinatesOutsideMap(x, y, min_corner_, max_corner_)) {\n        if(debug_) {\n            std::cerr << \"[OrientedGridVectorMap] : Position to test \"\n                         \"not within grid structured area!\\n\";\n        }\n        return false;\n    }\n\n    // find the cell of point pos\n    unsigned int row = GridVectorMap::row(y);\n    unsigned int col = GridVectorMap::col(x);\n    unsigned int theta = angle2index(orientation);\n\n    const VectorPtrs &cell = grid_.at(grid_dimensions_.index(row, col, theta));\n\n    for(const Vector* line : cell) {\n        lines.push_back(*line);\n    }\n\n    return lines.size() > 0;\n}\n\nbool OrientedGridVectorMap::retrieve(const unsigned int row,\n                                     const unsigned int col,\n                                     const double angle,\n                                     Vectors &lines) const\n{\n    const VectorPtrs &cell = grid_.at(grid_dimensions_.index(row, col,  angle2index(angle)));\n\n    for(const Vector* line : cell) {\n        lines.push_back(*line);\n    }\n\n    return lines.size() > 0;\n}\n\nbool OrientedGridVectorMap::retrieve(const unsigned int row,\n                                     const unsigned int col,\n                                     const double min_angle,\n                                     const double max_angle,\n                                     Vectors &lines) const\n{\n    std::set<const Vector*> bucket;\n    unsigned int index_min = angle2index(min_angle);\n    unsigned int index_max = angle2index(max_angle);\n    for(unsigned int i = index_min ; i < index_max ; ++i) {\n        if(i == theta_bins_)\n            i = 0;\n        const VectorPtrs &cell = grid_.at(grid_dimensions_.index(row, col, i));\n        bucket.insert(cell.begin(), cell.end());\n    }\n\n    for(const Vector* line : bucket) {\n        lines.push_back(*line);\n    }\n\n    return lines.size() > 0;\n}\n\ndouble OrientedGridVectorMap::intersectScanRay(const Vector &ray,\n                                               const void* cell_ptr,\n                                               const double angle,\n                                               const double max_range) const\n{\n    const VectorPtrs& cell = static_cast<const VectorPtrs*>(cell_ptr)[angle2index(angle)];\n    return algorithms::nearestIntersectionDistance<double, types::Point2d>(ray, cell, max_range);\n}\n\ndouble OrientedGridVectorMap::intersectScanRay(const Vector &ray,\n                                               const unsigned int row,\n                                               const unsigned int col,\n                                               const double angle,\n                                               const double max_range) const\n{\n    const VectorPtrs &cell = grid_.at(grid_dimensions_.index(row, col, angle2index(angle)));\n    return algorithms::nearestIntersectionDistance<double, types::Point2d>(ray, cell, max_range);\n}\n\ndouble OrientedGridVectorMap::intersectScanRay(const Vector &ray,\n                                               const unsigned int row,\n                                               const unsigned int col,\n                                               const double angle,\n                                               Point &p,\n                                               const double max_range) const\n{\n    const VectorPtrs &cell = grid_.at(grid_dimensions_.index(row, col, angle2index(angle)));\n    types::PointSet2d points;\n    algorithms::nearestIntersection<types::Point2d>(ray, cell, points);\n\n    if(points.size() == 0)\n        return max_range;\n\n    p = points.front();\n\n    return boost::geometry::distance(ray.first, p);\n}\n\nvoid OrientedGridVectorMap::intersectScanRay(const Vector &ray,\n                                             const unsigned int row,\n                                             const unsigned int col,\n                                             const double ray_angle,\n                                             double &distance,\n                                             double &angle,\n                                             const double max_range,\n                                             const double default_angle) const\n{\n    const VectorPtrs &cell = grid_.at(grid_dimensions_.index(row, col, angle2index(ray_angle)));\n    algorithms::nearestIntersectionDistance<double, types::Point2d>(ray, cell,\n                                                                distance,\n                                                                angle,\n                                                                max_range,\n                                                                default_angle);\n}\n\n\nbool OrientedGridVectorMap::retrieveFiltered(const Point &pos,\n                                             Vectors &lines) const\n{\n    if(tools::pointOutsideMap(pos, min_corner_, max_corner_)) {\n        if(debug_) {\n            std::cerr << \"[OrientedGridVectorMap] : Position to test \"\n                         \"not within grid structured area!\\n\";\n        }\n        return false;\n    }\n\n    // find the cell of point pos\n    unsigned int row = GridVectorMap::row(pos);\n    unsigned int col = GridVectorMap::col(pos);\n\n    for(unsigned int theta = 0 ; theta < grid_dimensions_.size<2>() ; ++theta) {\n        const VectorPtrs &cell = grid_.at(grid_dimensions_.index(row, col, theta));\n\n        // compute the exact bound box for pos\n        //  (if the resolution is large, there might be many unnecessary lines)\n        Point min(pos.x() - range_,\n                  pos.y() - range_);\n        Point max(pos.x() + range_,\n                  pos.y() + range_);\n        BoundingBox bound(min, max);\n\n        for(const Vector* line : cell) {\n            // filter out unnecessary lines\n            if(algorithms::touches<Point>(*line, bound)) {\n                lines.push_back(*line);\n            }\n        }\n    }\n\n    return lines.size() > 0;\n}\n\nbool OrientedGridVectorMap::retrieve(const Point &pos,\n                                     Vectors     &lines) const\n{\n    if(tools::pointOutsideMap(pos, min_corner_, max_corner_)) {\n        if(debug_) {\n            std::cerr << \"[OrientedGridVectorMap] : Position to test \"\n                         \"not within grid structured area!\\n\";\n        }\n        return false;\n    }\n\n    // find the cell of point pos\n    unsigned int row = GridVectorMap::row(pos);\n    unsigned int col = GridVectorMap::col(pos);\n\n    for(unsigned int theta = 0 ; theta < grid_dimensions_.size<2>() ; ++theta) {\n        const VectorPtrs &cell = grid_.at(grid_dimensions_.index(row, col, theta));\n\n        for(const Vector* line : cell) {\n            lines.push_back(*line);\n        }\n    }\n\n    return lines.size() > 0;\n}\n\nbool OrientedGridVectorMap::retrieve(const Point &pos,\n                                     const double min_angle,\n                                     const double max_angle,\n                                     Vectors     &lines) const\n{\n    if(tools::pointOutsideMap(pos, min_corner_, max_corner_)) {\n        if(debug_) {\n            std::cerr << \"[OrientedGridVectorMap] : Position to test \"\n                         \"not within grid structured area!\\n\";\n        }\n        return false;\n    }\n\n    // find the cell of point pos\n    unsigned int row = GridVectorMap::row(pos);\n    unsigned int col = GridVectorMap::col(pos);\n\n    const unsigned int min_angle_index = angle2index(min_angle);\n    const unsigned int max_angle_index = angle2index(max_angle);\n\n    for(unsigned int theta = min_angle_index ; theta <= max_angle_index ; ++theta) {\n        const VectorPtrs &cell = grid_.at(grid_dimensions_.index(row, col, theta));\n\n        for(const Vector* line : cell) {\n            lines.push_back(*line);\n        }\n    }\n\n    return lines.size() > 0;\n}\n\n\nint OrientedGridVectorMap::intersectScanPattern (\n        const Point& pos,\n        const Vectors &pattern,\n        IntersectionSet &intersections) const\n{\n    if(tools::pointOutsideMap(pos, min_corner_, max_corner_)) {\n        if(debug_) {\n            std::cerr << \"[OrientedGridVectorMap] : Position \"\n                         \"(\" << pos.x() << \"|\" << pos.y() << \")\"\n                         \" to test not within grid structured area!\\n\";\n        }\n        return -1;\n    }\n\n    // find the cell of point pos\n    unsigned int row = GridVectorMap::row(pos);\n    unsigned int col = GridVectorMap::col(pos);\n\n    int intersection_count = 0;\n    ValidPoints result;\n\n    for(const Vector& line : pattern) {\n        double dx = line.second.x() - line.first.x();\n        double dy = line.second.y() - line.first.y();\n        double angle = std::atan2(dy, dx);\n        unsigned int theta = angle2index(angle);\n        auto &cell = grid_.at(grid_dimensions_.index(row, col, theta));\n\n        result.result.clear();\n        result.valid = algorithms::nearestIntersection<Point>(line,\n                                                              cell,\n                                                              result.result);\n        intersection_count += cell.size();\n        intersections.push_back(result);\n    }\n\n    return intersection_count;\n}\n\nint OrientedGridVectorMap::intersectScanPattern (\n        const Point& pos,\n        const Vectors &pattern,\n        std::vector<double> &angles,\n        IntersectionSet &intersections) const\n{\n    if(tools::pointOutsideMap(pos, min_corner_, max_corner_)) {\n        if(debug_) {\n            std::cerr << \"[OrientedGridVectorMap] : Position \"\n                         \"(\" << pos.x() << \"|\" << pos.y() << \")\"\n                         \" to test not within grid structured area!\\n\";\n        }\n        return -1;\n    }\n\n    // find the cell of point pos\n    unsigned int row = GridVectorMap::row(pos);\n    unsigned int col = GridVectorMap::col(pos);\n\n    int intersection_count = 0;\n    ValidPoints result;\n\n    auto lines_ptr = pattern.data();\n    auto angles_ptr = angles.data();\n\n    for(unsigned int i = 0 ; i < pattern.size(); ++i) {\n        auto &line = *(lines_ptr + i);\n        auto angle = *(angles_ptr + i);\n        unsigned int theta = angle2index(angle);\n        auto &cell = grid_.at(grid_dimensions_.index(row, col, theta));\n\n        result.result.clear();\n        result.valid = algorithms::nearestIntersection<Point>(line,\n                                                              cell,\n                                                              result.result);\n        intersection_count += cell.size();\n        intersections.push_back(result);\n    }\n\n    return intersection_count;\n}\n\nvoid OrientedGridVectorMap::intersectScanPattern(const Point   &pos,\n                                                 const Vectors &pattern,\n                                                 std::vector<float> &ranges,\n                                                 const float default_measurement) const\n{\n    if(tools::pointOutsideMap(pos, min_corner_, max_corner_)) {\n        if(debug_) {\n            std::cerr << \"[OrientedGridVectorMap] : Position to test \"\n                         \"not within grid structured area!\\n\";\n        }\n        return;\n    }\n\n    // find the cell of point pos\n    unsigned int row = GridVectorMap::row(pos);\n    unsigned int col = GridVectorMap::col(pos);\n\n    ranges.resize(pattern.size());\n\n    for(unsigned int i = 0 ; i < pattern.size() ; ++i) {\n        const Vector& line = pattern[i];\n        double dx = line.second.x() - line.first.x();\n        double dy = line.second.y() - line.first.y();\n        double angle = std::atan2(dy, dx);\n        unsigned int theta = angle2index(angle);\n        const VectorPtrs &cell = grid_.at(grid_dimensions_.index(row, col, theta));\n\n        ranges[i] = algorithms::nearestIntersectionDistance<float, types::Point2d>(line, cell, default_measurement);\n    }\n}\n\nunsigned int OrientedGridVectorMap::sizeAccessStructures() const\n{\n    unsigned int size = 0;\n    for(const VectorPtrs &cell : grid_) {\n        size += cell.size() * sizeof(Vector*);\n    }\n    return size;\n}\n\nvoid OrientedGridVectorMap::doLoad(const YAML::Node &node)\n{\n    GridVectorMap::doLoad(node);\n    angular_resolution_ = node[\"angular_resolution\"].as<double>();\n    theta_bins_         = node[\"theta_bins\"].as<std::size_t>();\n    theta_bins_inv_     = node[\"theta_bins_inv\"].as<double>();\n\n    grid_dimensions_ = {rows_, cols_, theta_bins_};\n}\n\nvoid OrientedGridVectorMap::doSave(YAML::Node &node) const\n{\n    GridVectorMap::doSave(node);\n    node[\"map_type\"]           = \"oriented_grid\";\n    node[\"angular_resolution\"] = angular_resolution_;\n    node[\"theta_bins\"]         = theta_bins_;\n    node[\"theta_bins_inv\"]     = theta_bins_inv_;\n\n    assert(node.IsMap());\n}\n", "meta": {"hexsha": "a8bf48dc2b102d2b8d8f6a5b3fdd11bbe9a7abca", "size": 33961, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/maps/oriented_grid_vector_map.cpp", "max_stars_repo_name": "cogsys-tuebingen/cslibs_vectormaps", "max_stars_repo_head_hexsha": "bafdea3e25db51a1324634ded30c69322faa02bb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/maps/oriented_grid_vector_map.cpp", "max_issues_repo_name": "cogsys-tuebingen/cslibs_vectormaps", "max_issues_repo_head_hexsha": "bafdea3e25db51a1324634ded30c69322faa02bb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-03-31T02:12:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-31T02:12:27.000Z", "max_forks_repo_path": "src/maps/oriented_grid_vector_map.cpp", "max_forks_repo_name": "cogsys-tuebingen/cslibs_vectormaps", "max_forks_repo_head_hexsha": "bafdea3e25db51a1324634ded30c69322faa02bb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.0348964013, "max_line_length": 135, "alphanum_fraction": 0.5345837873, "num_tokens": 7092, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059775, "lm_q2_score": 0.6370308013713525, "lm_q1q2_score": 0.46374278359524496}}
{"text": "// C++ standard library headers\n#include <cmath> // for std::isfinite\n#include <cstdlib> // for std::exit\n#include <cstring> // for std::strlen\n#include <ctime> // for std::clock\n#include <iostream> // for std::cout\n#include <limits> // for std::numeric_limits\n\n// Boost library headers\n#include <boost/multiprecision/cpp_bin_float.hpp>\n#include <boost/multiprecision/eigen.hpp>\n\n// RKTK headers\n#include \"OptimizerDriver.hpp\"\n\ntemplate <unsigned Digits>\nusing boost_float = boost::multiprecision::number<\n    boost::multiprecision::cpp_bin_float<Digits,\n        boost::multiprecision::digit_base_2>,\n    boost::multiprecision::et_off>;\n\nlong long int get_positive_integer_argument(char *str) {\n    char *end;\n    const long long int result = std::strtoll(str, &end, 10);\n    const bool read_whole_arg = (\n            std::strlen(str) == static_cast<std::size_t>(end - str));\n    const int is_positive = (result > 0);\n    if (!read_whole_arg || !is_positive) {\n        std::cerr << \"ERROR: Expected command-line argument '\" << str\n                  << \"' to be a positive integer.\" << std::endl;\n        std::exit(EXIT_FAILURE);\n    }\n    return result;\n}\n\n#define RETURN_PRECISION(T)                                                    \\\n        return std::numeric_limits<T>::digits;                                 \\\n    } else if (precision == std::numeric_limits<T>::digits) {                  \\\n        return std::numeric_limits<T>::digits;                                 \\\n    }\n\n#define HANDLE_SMALLEST_PRECISION(T)                                           \\\n    if (precision < std::numeric_limits<T>::digits) {                          \\\n        std::cout << \"Rounding up to \" << std::numeric_limits<T>::digits       \\\n                  << \"-bit precision, which is the smallest \"                  \\\n                        \"available machine precision.\" << std::endl;           \\\n        RETURN_PRECISION(T)\n\n#define HANDLE_MACHINE_PRECISION(T)                                            \\\n    else if (precision < std::numeric_limits<T>::digits) {                     \\\n        std::cout << \"Rounding up to \" << std::numeric_limits<T>::digits       \\\n                  << \"-bit precision, which is the next \"                      \\\n                        \"available machine precision.\" << std::endl;           \\\n        RETURN_PRECISION(T)\n\n#define HANDLE_EXTENDED_PRECISION(T)                                           \\\n    else if (precision < std::numeric_limits<T>::digits) {                     \\\n        std::cout << \"Rounding up to \" << std::numeric_limits<T>::digits       \\\n                  << \"-bit precision, which is the next \"                      \\\n                        \"available extended precision.\" << std::endl;          \\\n        RETURN_PRECISION(T)\n\n#define HANDLE_LARGEST_PRECISION(T)                                            \\\n    HANDLE_EXTENDED_PRECISION(T) else {                                        \\\n        std::cout << \"WARNING: Requested precision exceeds \"                   \\\n                     \"available precision. Rounding down to \"                  \\\n                  << std::numeric_limits<T>::digits                            \\\n                  << \"-bit precision, which is the highest \"                   \\\n                     \"available extended precision.\" << std::endl;             \\\n        return std::numeric_limits<T>::digits;                                 \\\n    }\n\nint get_precision(int argc, char **argv, int index) {\n    if (argc > index) {\n        char *end;\n        const long long int precision = std::strtoll(argv[index], &end, 10);\n        const bool read_whole_arg = (std::strlen(argv[index]) ==\n                                     static_cast<std::size_t>(\n                                             end - argv[index]));\n        const bool is_positive = (precision > 0);\n        if (read_whole_arg && is_positive) {\n            std::cout << \"Requested \" << precision << \"-bit precision.\"\n                      << std::endl;\n            HANDLE_SMALLEST_PRECISION(float)\n            HANDLE_MACHINE_PRECISION(double)\n            HANDLE_MACHINE_PRECISION(long double)\n            HANDLE_EXTENDED_PRECISION(boost_float<128>)\n            HANDLE_EXTENDED_PRECISION(boost_float<256>)\n            HANDLE_EXTENDED_PRECISION(boost_float<384>)\n            HANDLE_EXTENDED_PRECISION(boost_float<512>)\n            HANDLE_EXTENDED_PRECISION(boost_float<640>)\n            HANDLE_EXTENDED_PRECISION(boost_float<768>)\n            HANDLE_EXTENDED_PRECISION(boost_float<896>)\n            HANDLE_LARGEST_PRECISION(boost_float<1024>)\n        } else {\n            std::cout << \"WARNING: Could not interpret command-line argument \"\n                      << argv[index] << \" as a positive integer.\"\n                                        \" Defaulting to double (\"\n                      << std::numeric_limits<double>::digits\n                      << \"-bit) precision.\" << std::endl;\n            return std::numeric_limits<double>::digits;\n        }\n    } else {\n        std::cout << \"Defaulting to double (\"\n                  << std::numeric_limits<double>::digits\n                  << \"-bit) precision.\" << std::endl;\n        return std::numeric_limits<double>::digits;\n    }\n}\n\ndouble get_print_period(int argc, char **argv, int index) {\n    if (argc > index) {\n        char *end;\n        const double print_period = std::strtod(argv[index], &end);\n        const bool read_whole_arg = (\n                std::strlen(argv[index]) ==\n                static_cast<std::size_t>(end - argv[index]));\n        const bool is_finite = std::isfinite(print_period);\n        const bool is_positive = (print_period >= 0.0);\n        if (read_whole_arg && is_finite && is_positive) {\n            return print_period;\n        }\n    }\n    return 0.5;\n}\n\nint get_print_precision(int argc, char **argv, int index) {\n    if (argc > index) {\n        char *end;\n        const long long print_precision = std::strtoll(argv[index], &end, 10);\n        const bool read_whole_arg = (\n                std::strlen(argv[index]) ==\n                static_cast<std::size_t>(end - argv[index]));\n        const bool is_non_negative = (print_precision >= 0);\n        const bool in_range = (print_precision <=\n                               std::numeric_limits<int>::max());\n        if (read_whole_arg && is_non_negative && in_range) {\n            return static_cast<int>(print_precision);\n        }\n    }\n    return 0;\n}\n\nenum class SearchMode { EXPLORE, REFINE };\n\ntemplate <typename T>\nvoid run_main_loop(int order, std::size_t num_steps,\n                   char *filename, SearchMode mode, int print_prec,\n                   std::clock_t clocks_between_prints) {\n    rktk::OptimizerDriver<T> optimizer(order, num_steps);\n    if (mode == SearchMode::REFINE) {\n        optimizer.initialize_from_file(std::string(filename));\n    }\n    std::clock_t last_print_clock;\n    reset_d:\n    if (mode == SearchMode::EXPLORE) { optimizer.initialize_random(); }\n    optimizer.print(print_prec);\n    optimizer.write_to_file();\n    last_print_clock = std::clock();\n    optimizer.set_step_size(65536 * std::numeric_limits<T>::epsilon());\n    while (true) {\n        if (!optimizer.step()) {\n            optimizer.print(print_prec);\n            std::cout << \"Located candidate local minimum.\" << std::endl;\n            optimizer.write_to_file();\n            if (mode == SearchMode::EXPLORE) { goto reset_d; }\n            std::exit(EXIT_SUCCESS);\n        }\n        if (optimizer.get_iteration_count() % 1000 == 0) {\n            optimizer.write_to_file();\n        }\n        if (mode == SearchMode::EXPLORE &&\n            optimizer.get_iteration_count() >= 100000000) {\n            std::cout << \"NOTICE: Exceeded maximum number \"\n                         \"of BFGS iterations. Restarting from \"\n                         \"new random point.\" << std::endl;\n            goto reset_d;\n        }\n        const std::clock_t current_clock = std::clock();\n        if (current_clock - last_print_clock >= clocks_between_prints) {\n            optimizer.print(print_prec);\n            last_print_clock = current_clock;\n        }\n    }\n}\n\n#define RUN_MAIN_LOOP(T)                                                       \\\n    if (prec == std::numeric_limits<T>::digits) {                              \\\n        run_main_loop<T>(order, num_stages, argv[6], mode,                     \\\n                         print_prec, clocks_between_prints);                   \\\n    }\n\nint main(int argc, char **argv) {\n    if (argc < 3) {\n        std::cerr << \"Usage: \" << argv[0] << \" order num-stages num-bits \"\n                  << \"print-period print-precision [input-filename]\"\n                  << std::endl;\n        return EXIT_FAILURE;\n    }\n    const unsigned long long int order = static_cast<unsigned long long int>(\n            get_positive_integer_argument(argv[1]));\n    const std::size_t num_stages = static_cast<std::size_t>(\n            get_positive_integer_argument(argv[2]));\n    if (order > 15) {\n        std::cerr << \"ERROR: Runge-Kutta methods of order greater than 15 \"\n                  << \"are not yet supported.\" << std::endl;\n        std::exit(EXIT_FAILURE);\n    }\n    if (order > num_stages) {\n        std::cerr << \"ERROR: The order of a Runge-Kutta method cannot exceed \"\n                  << \"its number of stages.\" << std::endl;\n        std::exit(EXIT_FAILURE);\n    }\n    const int prec = get_precision(argc, argv, 3);\n    const auto clocks_between_prints = static_cast<std::clock_t>(\n            get_print_period(argc, argv, 4) * CLOCKS_PER_SEC);\n    const int print_prec = get_print_precision(argc, argv, 5);\n    const SearchMode mode = (argc > 6)\n                            ? SearchMode::REFINE\n                            : SearchMode::EXPLORE;\n    RUN_MAIN_LOOP(float)\n    else RUN_MAIN_LOOP(double)\n    else RUN_MAIN_LOOP(long double)\n    else RUN_MAIN_LOOP(boost_float<128>)\n    else RUN_MAIN_LOOP(boost_float<256>)\n    else RUN_MAIN_LOOP(boost_float<384>)\n    else RUN_MAIN_LOOP(boost_float<512>)\n    else RUN_MAIN_LOOP(boost_float<640>)\n    else RUN_MAIN_LOOP(boost_float<768>)\n    else RUN_MAIN_LOOP(boost_float<896>)\n    else RUN_MAIN_LOOP(boost_float<1024>)\n}\n", "meta": {"hexsha": "77aae4557f873f6794d77b25963fb835e03efdb2", "size": 10189, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "legacy/rksearch-main.cpp", "max_stars_repo_name": "dzhang314/RKTK", "max_stars_repo_head_hexsha": "0aa0dfe5980732186573a13d9bcc6d5ba7542549", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-06-07T13:05:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-30T13:26:19.000Z", "max_issues_repo_path": "legacy/rksearch-main.cpp", "max_issues_repo_name": "dzhang314/RKTK", "max_issues_repo_head_hexsha": "0aa0dfe5980732186573a13d9bcc6d5ba7542549", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "legacy/rksearch-main.cpp", "max_forks_repo_name": "dzhang314/RKTK", "max_forks_repo_head_hexsha": "0aa0dfe5980732186573a13d9bcc6d5ba7542549", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-06-07T13:05:36.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-07T13:05:36.000Z", "avg_line_length": 43.7296137339, "max_line_length": 80, "alphanum_fraction": 0.5444106389, "num_tokens": 2159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754371026367, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.4637427810926096}}
{"text": "/*\n * Copyright (c) DTAI - KU Leuven \u2013 All rights reserved.\n * Proprietary, do not copy or distribute without permission. \n * Written by Pieter Robberechts, 2019\n */\n\n#ifndef DECISIONTREE_CALCULATIONS_HPP\n#define DECISIONTREE_CALCULATIONS_HPP\n\n#include <tuple>\n#include <vector>\n#include <string>\n#include <unordered_map>\n#include <boost/timer/timer.hpp>\n#include \"Question.hpp\"\n#include \"Utils.hpp\"\n\nusing ClassCounter = std::unordered_map<std::string, int>;\n\nnamespace Calculations {\n\nstd::tuple<const std::vector<size_t>, const std::vector<size_t>> partition(const Data &data, const Question &q, const std::vector<size_t>& indexes); // changed so that it partitions indexes instead the data\n\nconst double gini(const ClassCounter& counts, double N);\n\nstd::tuple<const double, const Question> find_best_split(const Data &rows, const MetaData &meta, const std::vector<size_t>& indexes);\n\nstd::tuple<std::string, double> determine_best_threshold(const Data &data, int col, const std::vector<size_t>& indexes, const ClassCounter& counter);\n\nconst ClassCounter copy(const ClassCounter &counter); //used to make a copy of class counter\n\nconst ClassCounter empty(const ClassCounter &counter); // used to make an empty copy of class counter\n\nconst ClassCounter classCounts(const Data &data, const std::vector<size_t>& indexes);\n\n} // namespace Calculations\n\n#endif //DECISIONTREE_CALCULATIONS_HPP\n", "meta": {"hexsha": "529b55971d3becf07b264a131fc928c4860a3b11", "size": 1391, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "code/lib/include/Calculations.hpp", "max_stars_repo_name": "ilovrencic/CART-Algorithm", "max_stars_repo_head_hexsha": "760f1a0bfc4cd031b7c88ea3dd6384c3282ee1a5", "max_stars_repo_licenses": ["MIT"], "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/lib/include/Calculations.hpp", "max_issues_repo_name": "ilovrencic/CART-Algorithm", "max_issues_repo_head_hexsha": "760f1a0bfc4cd031b7c88ea3dd6384c3282ee1a5", "max_issues_repo_licenses": ["MIT"], "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/lib/include/Calculations.hpp", "max_forks_repo_name": "ilovrencic/CART-Algorithm", "max_forks_repo_head_hexsha": "760f1a0bfc4cd031b7c88ea3dd6384c3282ee1a5", "max_forks_repo_licenses": ["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.6666666667, "max_line_length": 206, "alphanum_fraction": 0.7699496765, "num_tokens": 324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754371026368, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.4637427710596969}}
{"text": "// Copyright 2018-2019 Hans Dembinski\n//\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include <boost/core/lightweight_test.hpp>\n#include <boost/histogram/detail/large_int.hpp>\n#include <cstdint>\n#include <iosfwd>\n#include <limits>\n#include \"utility_meta.hpp\"\n\nusing namespace boost::histogram;\n\nusing large_int = detail::large_int<std::allocator<std::uint64_t>>;\n\nstd::ostream& operator<<(std::ostream& os, const large_int& x) {\n  os << \"large_int\" << x.data;\n  return os;\n}\n\ntemplate <class... Ts>\nauto make_mp_int(Ts... ts) {\n  large_int r;\n  r.data = {static_cast<uint64_t>(ts)...};\n  return r;\n}\n\nint main() {\n  // low-level tools\n  {\n    uint8_t c = 0;\n    BOOST_TEST_EQ(detail::safe_increment(c), true);\n    BOOST_TEST_EQ(c, 1);\n    c = 255;\n    BOOST_TEST_EQ(detail::safe_increment(c), false);\n    BOOST_TEST_EQ(c, 255);\n    c = 0;\n    BOOST_TEST_EQ(detail::safe_radd(c, 255u), true);\n    BOOST_TEST_EQ(c, 255);\n    c = 1;\n    BOOST_TEST_EQ(detail::safe_radd(c, 255u), false);\n    BOOST_TEST_EQ(c, 1);\n    c = 255;\n    BOOST_TEST_EQ(detail::safe_radd(c, 1u), false);\n    BOOST_TEST_EQ(c, 255);\n  }\n\n  const auto vmax = std::numeric_limits<std::uint64_t>::max();\n\n  BOOST_TEST_EQ(large_int(), 0u);\n  BOOST_TEST_EQ(large_int(1u), 1u);\n  BOOST_TEST_EQ(large_int(1u), 1.0);\n  BOOST_TEST_EQ(large_int(1u), large_int(1u));\n  BOOST_TEST_NE(large_int(1u), 2u);\n  BOOST_TEST_NE(large_int(1u), 2.0);\n  BOOST_TEST_NE(large_int(1u), large_int(2u));\n  BOOST_TEST_LT(large_int(1u), 2u);\n  BOOST_TEST_LT(large_int(1u), 2.0);\n  BOOST_TEST_LT(large_int(1u), large_int(2u));\n  BOOST_TEST_LE(large_int(1u), 2u);\n  BOOST_TEST_LE(large_int(1u), 2.0);\n  BOOST_TEST_LE(large_int(1u), large_int(2u));\n  BOOST_TEST_LE(large_int(1u), 1u);\n  BOOST_TEST_GT(large_int(1u), 0u);\n  BOOST_TEST_GT(large_int(1u), 0.0);\n  BOOST_TEST_GT(large_int(1u), large_int(0u));\n  BOOST_TEST_GE(large_int(1u), 0u);\n  BOOST_TEST_GE(large_int(1u), 0.0);\n  BOOST_TEST_GE(large_int(1u), 1u);\n  BOOST_TEST_GE(large_int(1u), large_int(0u));\n  BOOST_TEST_NOT(large_int(1u) < large_int(1u));\n  BOOST_TEST_NOT(large_int(1u) > large_int(1u));\n  BOOST_TEST_GT(1, large_int());\n  BOOST_TEST_LT(-1, large_int());\n  BOOST_TEST_GE(1, large_int());\n  BOOST_TEST_LE(-1, large_int());\n  BOOST_TEST_NE(1, large_int());\n\n  auto a = large_int();\n  ++a;\n  BOOST_TEST_EQ(a.data.size(), 1);\n  BOOST_TEST_EQ(a.data[0], 1);\n  ++a;\n  BOOST_TEST_EQ(a.data[0], 2);\n  a = vmax;\n  BOOST_TEST_EQ(a, vmax);\n  BOOST_TEST_EQ(a, static_cast<double>(vmax));\n  ++a;\n  BOOST_TEST_EQ(a, make_mp_int(0, 1));\n  ++a;\n  BOOST_TEST_EQ(a, make_mp_int(1, 1));\n  a += a;\n  BOOST_TEST_EQ(a, make_mp_int(2, 2));\n  BOOST_TEST_EQ(a, 2 * static_cast<double>(vmax) + 2);\n\n  // carry once A\n  a.data[0] = vmax;\n  a.data[1] = 1;\n  ++a;\n  BOOST_TEST_EQ(a, make_mp_int(0, 2));\n  // carry once B\n  a.data[0] = vmax;\n  a.data[1] = 1;\n  a += 1;\n  BOOST_TEST_EQ(a, make_mp_int(0, 2));\n  // carry once C\n  a.data[0] = vmax;\n  a.data[1] = 1;\n  a += make_mp_int(1, 1);\n  BOOST_TEST_EQ(a, make_mp_int(0, 3));\n\n  a.data[0] = vmax - 1;\n  a.data[1] = vmax;\n  ++a;\n  BOOST_TEST_EQ(a, make_mp_int(vmax, vmax));\n\n  // carry two times A\n  ++a;\n  BOOST_TEST_EQ(a, make_mp_int(0, 0, 1));\n  // carry two times B\n  a = make_mp_int(vmax, vmax);\n  a += 1;\n  BOOST_TEST_EQ(a, make_mp_int(0, 0, 1));\n  // carry two times C\n  a = make_mp_int(vmax, vmax);\n  a += large_int(1);\n  BOOST_TEST_EQ(a, make_mp_int(0, 0, 1));\n\n  // carry and enlarge\n  a = make_mp_int(vmax, vmax);\n  a += a;\n  BOOST_TEST_EQ(a, make_mp_int(vmax - 1, vmax, 1));\n\n  // add smaller to larger\n  a = make_mp_int(1, 1, 1);\n  a += make_mp_int(1, 1);\n  BOOST_TEST_EQ(a, make_mp_int(2, 2, 1));\n\n  // add larger to smaller\n  a = make_mp_int(1, 1);\n  a += make_mp_int(1, 1, 1);\n  BOOST_TEST_EQ(a, make_mp_int(2, 2, 1));\n\n  a = large_int(1);\n  auto b = 1.0;\n  BOOST_TEST_EQ(a, b);\n  for (unsigned i = 0; i < 80; ++i) {\n    b += b;\n    BOOST_TEST_NE(a, b);\n    a += a;\n    BOOST_TEST_EQ(a, b);\n  }\n  BOOST_TEST_GT(a.data.size(), 1u);\n\n  return boost::report_errors();\n}\n", "meta": {"hexsha": "ccbac9f8dd377b30cb13a2e10d5d808c161095e2", "size": 4123, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/detail_large_int_test.cpp", "max_stars_repo_name": "glenfe/boost.histogram", "max_stars_repo_head_hexsha": "376ddeadc40e4de6dffb9ad87668b3efa52b08b5", "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": "test/detail_large_int_test.cpp", "max_issues_repo_name": "glenfe/boost.histogram", "max_issues_repo_head_hexsha": "376ddeadc40e4de6dffb9ad87668b3efa52b08b5", "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/detail_large_int_test.cpp", "max_forks_repo_name": "glenfe/boost.histogram", "max_forks_repo_head_hexsha": "376ddeadc40e4de6dffb9ad87668b3efa52b08b5", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9308176101, "max_line_length": 67, "alphanum_fraction": 0.6490419597, "num_tokens": 1483, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754371026367, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.46374276102678397}}
{"text": "//   Copyright 2018 Dhruvesh Nikhilkumar Patel\n//\n//   Licensed under the Apache License, Version 2.0 (the \"License\");\n//   you may not use this file except in compliance with the License.\n//   You may obtain a copy of the License at\n//\n//       http://www.apache.org/licenses/LICENSE-2.0\n//\n//   Unless required by applicable law or agreed to in writing, software\n//   distributed under the License is distributed on an \"AS IS\" BASIS,\n//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//   See the License for the specific language governing permissions and\n//   limitations under the License.\n//\n/** \\file Matrix.hpp\n * \\brief Contains typedefs and convinience operators which are wrappers around boost::numeric::ublas::matrix class\n * \\todo Provide better way of creating a matrix than zero initialization and then assignment to each entry.\n */\n#ifndef _MATRIX_HPP_\n#define _MATRIX_HPP_\n#include <boost/numeric/ublas/matrix.hpp>\n\ntemplate<typename EntryT>\nusing Matrix = boost::numeric::ublas::matrix<EntryT>;///< Typedef for the main matrix class\ntemplate <typename EntryT>\nusing Identity_Matrix = boost::numeric::ublas::identity_matrix<EntryT>;\n\n//template <typename MatrixT>\n//using productFunctionT = typename boost::numeric::ublas::matrix_matrix_binary_traits<typename MatrixT::value_type, MatrixT, typename MatrixT::value_type, MatrixT>::result_type(*)(const boost::numeric::ublas::matrix_expression<MatrixT>& e1, const boost::numeric::ublas::matrix_expression<MatrixT>& e2);\n//\n/** \\todo Create an operator* as a wrapper so that the requirements from Matrix type can be stated cleanly in terms of operators rather than relying on exact function names\n */\nusing boost::numeric::ublas::prod; ///< exposing the prod() along with all its instantiations and overloads to global namespace\nusing boost::numeric::ublas::trans;\nusing boost::numeric::ublas::element_prod;\nnamespace boost { namespace numeric { namespace ublas {\n   /*! \\brief Finds trace of a square matrix\n    *\n    *  Detailed description of the function\n    * \\except{strong}{Throws std::invalid_argument if the supplied matrix is now square} \n    * \\return trace Trace of a square matrix\n    */\n   template <typename EntryT>\n   EntryT trace(const Matrix<EntryT>& M);\n\n   /** \\brief Convinience function to check if a matrix is square or not\n    */\n   template <typename MatrixT>\n   bool isSquare(const MatrixT& M);\n\n\n                                       }\n               }\n\n}\n\n//template <typename FieldT>\n//class Matrix \n//{\n//   public:\n//       /******* Constructors ********/\n//      /*! \\brief Takes in no arguments and creates a 0x0 matrix \n//       *\n//       */\n//       Matrix(); \n//       \n//       /*! \\brief Create a matrix with dimensions num_rows x num_cols with default\n//        * initialized entries.\n//        * \\param num_rows \n//        * \\param num_cols\n//        */\n//       Matrix(size_t num_rows,size_t num_cols); \n//\n//       /*! \\brief Use 2d initializer list to construct the matrix \n//        *\n//        *\n//        * \\param entires 2d initializer list for example, for FieldT=int, {{23,56},{1,100}} \n//        */\n//       Matrix(std::initializer_list<std::initializer_list<FieldT>> entries);\n//         \n//   private:\n//      std::vector<FieldT> m_entries;\n//};\n\n#endif // _MATRIX_HPP_\n", "meta": {"hexsha": "17c6b86c6e5f925ab03c46ebaa682da4a962b3a0", "size": 3316, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/Matrix.hpp", "max_stars_repo_name": "dhruvdcoder/poly-metic", "max_stars_repo_head_hexsha": "c8ec0ba30dd052c6b41a0cdeb58318d063cf9eac", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-14T16:16:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-14T16:16:12.000Z", "max_issues_repo_path": "include/Matrix.hpp", "max_issues_repo_name": "dhruvdcoder/poly-metic", "max_issues_repo_head_hexsha": "c8ec0ba30dd052c6b41a0cdeb58318d063cf9eac", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-09-02T04:38:52.000Z", "max_issues_repo_issues_event_max_datetime": "2018-09-09T20:14:16.000Z", "max_forks_repo_path": "include/Matrix.hpp", "max_forks_repo_name": "dhruvdcoder/poly-metic", "max_forks_repo_head_hexsha": "c8ec0ba30dd052c6b41a0cdeb58318d063cf9eac", "max_forks_repo_licenses": ["Apache-2.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.5581395349, "max_line_length": 303, "alphanum_fraction": 0.67973462, "num_tokens": 767, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754371026367, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.46374276102678397}}
{"text": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Delaunay_triangulation_2.h>\n#include <CGAL/Triangulation_vertex_base_with_info_2.h>\n#include <CGAL/Triangulation_face_base_2.h>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/pending/disjoint_sets.hpp>\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\ntypedef int                                            Index;\ntypedef CGAL::Triangulation_vertex_base_with_info_2<Index,K>   Vb;\ntypedef CGAL::Triangulation_face_base_2<K>                     Fb;\ntypedef CGAL::Triangulation_data_structure_2<Vb,Fb>            Tds;\ntypedef CGAL::Delaunay_triangulation_2<K,Tds>                  DT;\ntypedef std::pair<K::Point_2,Index> IPoint;\n\ntypedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS,\n  boost::no_property, boost::property<boost::edge_weight_t, long> >      weighted_graph;\ntypedef boost::property_map<weighted_graph, boost::edge_weight_t>::type weight_map;\ntypedef boost::graph_traits<weighted_graph>::edge_descriptor            edge_desc;\ntypedef boost::graph_traits<weighted_graph>::vertex_descriptor          vertex_desc;\n\nstruct Edge {\n  int u, v;\n  long w;\n  \n  bool operator<(Edge e) const {\n    return w < e.w;\n  }\n};\n\ntypedef std::vector<Edge> EdgeV;\n\nusing namespace std;\n\nint maxFamilies(vector<int> &componentsOfSize, int k) {\n  int f = componentsOfSize[k];\n  if (k == 4) {\n    if (componentsOfSize[3] <= componentsOfSize[1]) {\n      f += componentsOfSize[3];\n      f += ((componentsOfSize[1] - componentsOfSize[3]) / 2 + componentsOfSize[2]) / 2;\n    }\n    else {\n      f += componentsOfSize[1];\n      f += ((componentsOfSize[3] - componentsOfSize[1]) + componentsOfSize[2]) / 2;\n    }\n  }\n  else if (k == 3) {\n    if (componentsOfSize[2] <= componentsOfSize[1]) {\n      f += componentsOfSize[2];\n      f += (componentsOfSize[1] - componentsOfSize[2]) / 3;\n    }\n    else {\n      f += componentsOfSize[1];\n      f += (componentsOfSize[2] - componentsOfSize[1]) / 2;\n    }\n  }\n  else if (k == 2) {\n    f += componentsOfSize[1] / 2;\n  }\n  return f;\n}\n\n\nvoid solve() {\n  int n, k, f0;\n  long s0;\n  cin >> n >> k >> f0 >> s0;\n  \n  vector<IPoint> pts(n);\n  for (std::size_t i = 0; i < n; ++i) {\n    int x, y;\n    cin >> x >> y;\n    pts[i] = {{x, y}, i};\n  }\n  \n  DT dt;\n  dt.insert(pts.begin(), pts.end());\n  \n  EdgeV edges;\n  edges.reserve(3*n);\n  for (auto e = dt.finite_edges_begin(); e != dt.finite_edges_end(); ++e) {\n    int u = e->first->vertex((e->second+1)%3)->info();\n    int v = e->first->vertex((e->second+2)%3)->info();\n    if (u > v) swap(u, v);\n    edges.push_back({u, v, long(dt.segment(e).squared_length())});\n  }\n  \n  std::sort(edges.begin(), edges.end());\n  \n  boost::disjoint_sets_with_storage<> uf(n);\n  Index n_components = n;\n  vector<int> sizeOfComponent(n, 1);\n  vector<int> componentsOfSize(k + 1, 0);\n  long s = -1;\n  int f = -1;\n  componentsOfSize[1] = n;\n  vector<long> squaredDistances;\n  for (auto e : edges) {\n    Index c1 = uf.find_set(e.u);\n    Index c2 = uf.find_set(e.v);\n    if (c1 != c2) {\n      \n      int fMax = maxFamilies(componentsOfSize, k);\n      \n      if (fMax >= f0) {\n        s = e.w;\n      }\n      if (e.w >= s0) {\n        f = max(f, fMax);\n      }\n      \n      squaredDistances.push_back(e.w);\n      \n      uf.link(c1, c2);\n      int c = uf.find_set(c1);\n\n      componentsOfSize[sizeOfComponent[c1]] -= 1;\n      componentsOfSize[sizeOfComponent[c2]] -= 1;\n      sizeOfComponent[c] = min(k, sizeOfComponent[c1] + sizeOfComponent[c2]);\n      componentsOfSize[sizeOfComponent[c]] += 1;\n      \n      if (--n_components == 1) break;\n    }\n  }\n  int fMax = maxFamilies(componentsOfSize, k);\n  f = max(f, fMax);\n  \n  cout << s << \" \" << f << endl;\n}\n\n\nint main()\n{\n  ios_base::sync_with_stdio(false);\n  int t; cin >> t;\n  while (t--) {\n    solve();\n  }\n  return 0;\n}\n", "meta": {"hexsha": "6d62b6efa7435e859350d390cd483acc9e5b2ff1", "size": 3902, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/hand.cpp", "max_stars_repo_name": "dsparber/algolab", "max_stars_repo_head_hexsha": "9781eb5c7444236f796f167f1f39fc9d913e5c53", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2021-01-01T17:19:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T12:27:57.000Z", "max_issues_repo_path": "src/hand.cpp", "max_issues_repo_name": "dsparber/algolab", "max_issues_repo_head_hexsha": "9781eb5c7444236f796f167f1f39fc9d913e5c53", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/hand.cpp", "max_forks_repo_name": "dsparber/algolab", "max_forks_repo_head_hexsha": "9781eb5c7444236f796f167f1f39fc9d913e5c53", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-28T10:55:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-28T10:55:25.000Z", "avg_line_length": 26.9103448276, "max_line_length": 88, "alphanum_fraction": 0.6089185033, "num_tokens": 1160, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.46361632515802803}}
{"text": "#include <boost/graph/transitive_closure.hpp>\n", "meta": {"hexsha": "6f88091a908cff7fca5df28a4f36818044f013da", "size": 46, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_graph_transitive_closure.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_graph_transitive_closure.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_graph_transitive_closure.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 23.0, "max_line_length": 45, "alphanum_fraction": 0.8260869565, "num_tokens": 9, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.4636074079453849}}
{"text": "#ifndef RADIUMENGINE_POINT_CLOUD_HPP_\n#define RADIUMENGINE_POINT_CLOUD_HPP_\n\n#include <Core/RaCore.hpp>\n\n#include <Eigen/Eigenvalues>\n\n#include <Core/Container/VectorArray.hpp>\n#include <Core/Math/LinearAlgebra.hpp>\n#include <Core/Math/Math.hpp>\n#include <Core/Math/Obb.hpp>\n\nnamespace Ra {\nnamespace Core {\n/// This file contains functions operating on any unstructured set of points.\n/// If not stated otherwise the functions behaviour is undefined if the set\n/// of points is empty.\nnamespace Geometry {\n/// Compute the mean point of a set of points, i.e. the barycenter.\nRA_CORE_API inline Math::Vector3 meanPoint( const Container::Vector3Array& pts );\n\n/// Returns a transform computed by PCA of the given set of points.\n/// The rotation gives you the principal directions in increasing\n/// order of importance (Z = principal direction)\n/// The translation is the barycenter of the point set.\nRA_CORE_API inline Math::Transform principalAxis( const Container::Vector3Array& pts );\n\n/// Returns the axis-aligned bounding box of a set of points.\n/// This function returns an empty AABB if the set of points is\n/// empty.\nRA_CORE_API inline Math::Aabb aabb( const Container::Vector3Array& pts );\n\n/// Computes an oriented bounding box based on PCA of the points coordinates.\nRA_CORE_API inline Math::Obb pcaObb( const Container::Vector3Array& pts );\n\n} // namespace Geometry\n} // namespace Core\n} // namespace Ra\n\n#include <Core/Geometry/PointCloud.inl>\n\n#endif // RADIUMENGINE_POINT_CLOUD_HPP_\n", "meta": {"hexsha": "da225b255f3d659c965d16ed8753537ed591ca15", "size": 1497, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Core/Geometry/PointCloud.hpp", "max_stars_repo_name": "sylvaindeker/Radium-Engine", "max_stars_repo_head_hexsha": "64164a258b3f7864c73a07c070e49b7138488d62", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-04-16T13:55:45.000Z", "max_stars_repo_stars_event_max_datetime": "2018-04-16T13:55:45.000Z", "max_issues_repo_path": "src/Core/Geometry/PointCloud.hpp", "max_issues_repo_name": "sylvaindeker/Radium-Engine", "max_issues_repo_head_hexsha": "64164a258b3f7864c73a07c070e49b7138488d62", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Core/Geometry/PointCloud.hpp", "max_forks_repo_name": "sylvaindeker/Radium-Engine", "max_forks_repo_head_hexsha": "64164a258b3f7864c73a07c070e49b7138488d62", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.8139534884, "max_line_length": 87, "alphanum_fraction": 0.7688710755, "num_tokens": 341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.46360740794538485}}
{"text": "#include <catch2/catch.hpp>\n\n#include <Eigen/Eigenvalues>\n#include <solvers/newton_solver.hpp>\n#include <utils/eigen_ext.hpp>\n#include <utils/not_implemented_error.hpp>\n\nusing namespace ipc;\nusing namespace ipc::rigid;\n\nTEST_CASE(\"Simple tests of Newton's Method\", \"[opt][newtons_method]\")\n{\n    int num_vars = GENERATE(1, 10, 100);\n\n    // Setup problem\n    // -----------------------------------------------------------------\n    class AdHocProblem : public virtual OptimizationProblem {\n    public:\n        AdHocProblem(int num_vars)\n        {\n            num_vars_ = num_vars;\n            x0.resize(num_vars);\n            x0.setRandom();\n            is_dof_fixed_ = VectorXb::Zero(num_vars);\n        }\n\n        double compute_objective(\n            const Eigen::VectorXd& x,\n            Eigen::VectorXd& grad_fx,\n            Eigen::SparseMatrix<double>& hess_fx,\n            bool compute_grad = true,\n            bool compute_hess = true) override\n        {\n            if (compute_grad) {\n                grad_fx = x;\n            }\n            if (compute_hess) {\n                hess_fx =\n                    Eigen::MatrixXd::Identity(x.rows(), x.rows()).sparseView();\n            }\n            return x.squaredNorm() / 2.0;\n        }\n\n        bool\n        has_collisions(const Eigen::VectorXd&, const Eigen::VectorXd&) override\n        {\n            return false;\n        }\n        double compute_earliest_toi(\n            const Eigen::VectorXd& xi, const Eigen::VectorXd& xj) override\n        {\n            return std::numeric_limits<double>::infinity();\n        }\n        bool is_ccd_aligned_with_newton_update() override { return true; }\n\n        const Eigen::VectorXd& starting_point() const { return x0; }\n        int num_vars() const override { return num_vars_; }\n        const VectorXb& is_dof_fixed() const override { return is_dof_fixed_; }\n\n        double compute_min_distance(const Eigen::VectorXd& x) const override\n        {\n            return -1;\n        }\n\n        /// Get the world coordinates of the vertices\n        Eigen::MatrixXd world_vertices(const Eigen::VectorXd& x) const override\n        {\n            throw NotImplementedError(\"no vertices\");\n        }\n\n        /// Get the length of the diagonal of the worlds bounding box\n        double world_bbox_diagonal() const override\n        {\n            throw NotImplementedError(\"no world bbox diagonal\");\n        }\n\n        DiagonalMatrixXd mass_matrix() const override\n        {\n            DiagonalMatrixXd I(num_vars_);\n            I.setIdentity();\n            return I;\n        }\n        double average_mass() const override { return 1; }\n\n        double timestep() const override { return 1; }\n\n        int num_vars_;\n        VectorXb is_dof_fixed_;\n        Eigen::VectorXd x0;\n    };\n\n    AdHocProblem problem(num_vars);\n\n    NewtonSolver solver;\n    solver.set_problem(problem);\n    solver.init_solve(problem.starting_point());\n    OptimizationResults results = solver.solve(problem.starting_point());\n    REQUIRE(results.success);\n    CHECK(results.x.squaredNorm() == Approx(0).margin(1e-6));\n    CHECK(results.minf == Approx(0).margin(1e-6));\n}\n\nTEST_CASE(\"Test Newton direction solve\", \"[opt][newtons_method][newton_dir]\")\n{\n    int num_vars = 1000;\n    Eigen::VectorXd x(num_vars);\n    x.setRandom();\n    // f = x^2\n    Eigen::VectorXd gradient = 2 * x;\n    Eigen::SparseMatrix<double> hessian =\n        SparseDiagonal<double>(2 * Eigen::VectorXd::Ones(num_vars));\n    Eigen::VectorXd delta_x;\n    ipc::rigid::NewtonSolver solver;\n    solver.compute_direction(gradient, hessian, delta_x);\n    CHECK((x + delta_x).squaredNorm() == Approx(0.0));\n}\n\nTEST_CASE(\"Test making a matrix SPD\", \"[opt][make_spd]\")\n{\n    Eigen::SparseMatrix<double> A =\n        Eigen::MatrixXd::Random(100, 100).sparseView();\n    double mu = ipc::rigid::make_matrix_positive_definite(A);\n    CAPTURE(mu);\n    auto eig_vals = Eigen::MatrixXd(A).eigenvalues();\n    for (int i = 0; i < eig_vals.size(); i++) {\n        CHECK(eig_vals(i).real() >= Approx(0.0).margin(1e-12));\n    }\n}\n", "meta": {"hexsha": "4064e93c1e357ce5369e8ecd756b9aa2a310d757", "size": 4043, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/solvers/test_newton_solver.cpp", "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": "tests/solvers/test_newton_solver.cpp", "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": "tests/solvers/test_newton_solver.cpp", "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": 31.3410852713, "max_line_length": 79, "alphanum_fraction": 0.5948553055, "num_tokens": 925, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.4636074017914777}}
{"text": "// The Command Line Interface\n// Created by haoming on 10/4/17.\n//\n\n\n#include <iostream>\n#include <iomanip>\n#include <string>\n#include <vector>\n#include <numeric>\n#include <chrono>\n\n#include <fmlbase/utils.h>\n#include <fmlbase/SolverBase.h>\n#include <fmlbase/PIS2TASQRTLassoSolver.h>\n#include <fmlbase/PISTALassoSolver.h>\n#include <fmlbase/PIS2TACMRSolver.h>\n\n#include <Eigen/Dense>\n\nusing namespace Eigen;\nusing namespace std;\nusing namespace std::chrono;\n\nvoid runCLITask(const std::string &task_path)\n{\n    fmlbase::utils::FmlParam param(task_path);\n\n    vector<double> times;\n\n\n    if(param.getStrArg(\"algorithm\") == \"sqrtlasso\") {\n        fmlbase::PIS2TASQRTLassoSolver solver(param);\n        solver.initialize();\n        MatrixXd* testx;\n        fmlbase::utils::readCsvMat(testx, param.getStrArg(\"rootpath\") + \"/\"+param.getStrArg(\"testdata\"));\n        VectorXd* testy;\n        fmlbase::utils::readCsvVec(testy, param.getStrArg(\"rootpath\") + \"/\"+param.getStrArg(\"testlabel\"));\n\n        for (int i = 0; i < param.getIntArg(\"nexp\"); ++i) {\n            solver.reinitialize();\n            auto begin = std::chrono::steady_clock::now();\n            solver.train();\n            auto end = std::chrono::steady_clock::now();\n            auto diff = 1. * (end - begin).count() * nanoseconds::period::num / nanoseconds::period::den;\n            times.emplace_back(diff);\n            cout << i << \"th trail, training time (/s): \" << diff << endl;\n            cout << i << \"train error: \" << solver.eval() << endl;\n            cout << i << \"test error: \" << solver.eval(*testx, *testy) << endl;\n        }\n    }\n    if(param.getStrArg(\"algorithm\") == \"lasso\") {\n        fmlbase::PISTALassoSolver solver(param);\n        solver.initialize();\n        MatrixXd* testx;\n        fmlbase::utils::readCsvMat(testx, param.getStrArg(\"rootpath\") + \"/\"+param.getStrArg(\"testdata\"));\n        VectorXd* testy;\n        fmlbase::utils::readCsvVec(testy, param.getStrArg(\"rootpath\") + \"/\"+param.getStrArg(\"testlabel\"));\n\n        for (int i = 0; i < param.getIntArg(\"nexp\"); ++i) {\n            solver.reinitialize();\n            auto begin = std::chrono::steady_clock::now();\n            solver.train();\n            auto end = std::chrono::steady_clock::now();\n            auto diff = 1. * (end - begin).count() * nanoseconds::period::num / nanoseconds::period::den;\n            times.emplace_back(diff);\n            cout << i << \"th trail, training time (/s): \" << diff << endl;\n            cout << i << \"train error: \" << solver.eval() << endl;\n            cout << i << \"test error: \" << solver.eval(*testx, *testy) << endl;\n        }\n    }\n    if(param.getStrArg(\"algorithm\") == \"CMR\") {\n        fmlbase::PIS2TACMRSolver solver(param);\n        solver.initialize();\n        MatrixXd* testx;\n        fmlbase::utils::readCsvMat(testx, param.getStrArg(\"rootpath\") + \"/\"+param.getStrArg(\"testdata\"));\n        MatrixXd* testy;\n        fmlbase::utils::readCsvMat(testy, param.getStrArg(\"rootpath\") + \"/\"+param.getStrArg(\"testlabel\"));\n\n        for (int i = 0; i < param.getIntArg(\"nexp\"); ++i) {\n            solver.reinitialize();\n            auto begin = std::chrono::steady_clock::now();\n            solver.train();\n            auto end = std::chrono::steady_clock::now();\n            auto diff = 1. * (end - begin).count() * nanoseconds::period::num / nanoseconds::period::den;\n            times.emplace_back(diff);\n            cout << i << \"th trail, training time (/s): \" << diff << endl;\n            cout << i << \"train error: \" << solver.eval() << endl;\n            cout << i << \"test error: \" << solver.eval(*testx, *testy) << endl;\n        }\n    }\n    if(param.getStrArg(\"algorithm\") == \"SPME\") {\n        MatrixXd* S;\n        fmlbase::utils::readCsvMat(S, param.getStrArg(\"rootpath\") + \"/\"+param.getStrArg(\"data\"));\n        auto nfeature = S->cols();\n        vector<fmlbase::PIS2TASQRTLassoSolver*> solver_vec;\n        double errors = 0;\n        for (int j = 0; j < nfeature; ++j) {\n            auto temp_col = S->col(0);\n            S->col(0) = S->col(j);\n            S->col(j) = temp_col;\n            fmlbase::PIS2TASQRTLassoSolver *new_solver = new fmlbase::PIS2TASQRTLassoSolver(param, S->rightCols(nfeature-1), S->col(0));\n            new_solver->initialize();\n            solver_vec.push_back(new_solver);\n        }\n        cout << \"Construction Completed \\n\";\n        for (int i = 0; i < param.getIntArg(\"nexp\"); ++i) {\n            for (int j = 0; j < nfeature; ++j)\n                solver_vec[j]->reinitialize();\n            auto begin = std::chrono::steady_clock::now();\n            for (int j = 0; j < nfeature; ++j)\n            {\n                solver_vec[j]->train();\n                //cout << \"trained\"<<j<<\"th solver \\n\";\n            }\n            auto end = std::chrono::steady_clock::now();\n            auto diff = 1. * (end - begin).count() * nanoseconds::period::num / nanoseconds::period::den;\n            times.emplace_back(diff);\n            cout << i << \"th trail, training time (/s): \" << diff << endl;\n            errors = 0;\n            for (int j = 0; j < nfeature; ++j)\n                errors+=solver_vec[j]->eval();\n        }\n        int num_zeros = 0;\n        for (int j = 0; j < nfeature; ++j)\n        {\n            num_zeros += ((*(solver_vec[j]->theta)).array().abs()<=0.00001).count();\n        }\n        cout << \"Sparsity: \" << 1-1.*num_zeros/nfeature/(nfeature-1) << endl;\n        cout << \"Errors: \" << errors << endl;\n\n    }\n\n    double sumT = 0;\n    for(double t : times)\n        sumT += t;\n\n    cout<<\"mean training time (/s): \"<<1.0*sumT/param.getIntArg(\"nexp\")<<endl;\n\n\n}\n\nint main(int argc, const char * argv[])\n{\n\n    if(argc < 2)\n        runCLITask(\"./Tasks/Arabidopsis\");\n    else\n        runCLITask(argv[1]);\n\n    return 0;\n}\n", "meta": {"hexsha": "d4f023af5fd9e3f1aa7ccd5f15e989f25e17e9b6", "size": 5750, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cli_main.cpp", "max_stars_repo_name": "HMJiangGatech/flashMLbase", "max_stars_repo_head_hexsha": "66442623e4f52006f1d3a80085a138ffdf5e5958", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cli_main.cpp", "max_issues_repo_name": "HMJiangGatech/flashMLbase", "max_issues_repo_head_hexsha": "66442623e4f52006f1d3a80085a138ffdf5e5958", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cli_main.cpp", "max_forks_repo_name": "HMJiangGatech/flashMLbase", "max_forks_repo_head_hexsha": "66442623e4f52006f1d3a80085a138ffdf5e5958", "max_forks_repo_licenses": ["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.5816993464, "max_line_length": 136, "alphanum_fraction": 0.5495652174, "num_tokens": 1578, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.46360740179147764}}
{"text": "#include \"mex.h\"\n#include \"drake/drakeUtil.h\"\n#include <Eigen/Dense>\n\nusing namespace Eigen;\n\nvoid mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])\n{\n    if (nrhs != 4 || nlhs != 2) {\n        mexErrMsgIdAndTxt(\"Drake:lqrmex:InvalidUsage\",\"Usage: [K, S] = lqrmex(A, B, Q, R)\");\n    }\n\n    const size_t A_rows = mxGetM(prhs[0]);\n    const size_t A_cols = mxGetN(prhs[0]);\n\n    const size_t B_rows = mxGetM(prhs[1]);\n    const size_t B_cols = mxGetN(prhs[1]);\n\n    const size_t Q_rows = mxGetM(prhs[2]);\n    const size_t Q_cols = mxGetN(prhs[2]);\n\n    const size_t R_rows = mxGetM(prhs[3]);\n    const size_t R_cols = mxGetN(prhs[3]);\n\n    assert(A_rows == A_cols);\n    assert(Q_rows == Q_cols);\n    assert(Q_rows == A_rows);\n    assert(R_rows == R_cols);\n    assert(R_rows == B_cols);\n\n    Map<MatrixXd> A(mxGetPr(prhs[0]), A_rows, A_cols);\n    Map<MatrixXd> B(mxGetPr(prhs[1]), B_rows, B_cols);\n    Map<MatrixXd> Q(mxGetPr(prhs[2]), Q_rows, Q_cols);\n    Map<MatrixXd> R(mxGetPr(prhs[3]), R_rows, R_cols);\n\n\n    plhs[0] = mxCreateDoubleMatrix(R_rows, A_cols, mxREAL);\n    plhs[1] = mxCreateDoubleMatrix(A_rows, A_cols, mxREAL);\n\n    Map<MatrixXd> K(mxGetPr(plhs[0]), R_rows, A_cols);\n    Map<MatrixXd> S(mxGetPr(plhs[1]), A_rows, A_cols);\n\n    lqr(A, B, Q, R, K, S);\n}\n", "meta": {"hexsha": "5d9ea7c2733898c6d34c0e42b13c1c341599ba21", "size": 1289, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "drake/solvers/lqrmex.cpp", "max_stars_repo_name": "ericmanzi/double_pendulum_lqr", "max_stars_repo_head_hexsha": "76bba3091295abb7d412c4a3156258918f280c96", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-04-16T09:54:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-29T21:59:27.000Z", "max_issues_repo_path": "drake/solvers/lqrmex.cpp", "max_issues_repo_name": "ericmanzi/double_pendulum_lqr", "max_issues_repo_head_hexsha": "76bba3091295abb7d412c4a3156258918f280c96", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "drake/solvers/lqrmex.cpp", "max_forks_repo_name": "ericmanzi/double_pendulum_lqr", "max_forks_repo_head_hexsha": "76bba3091295abb7d412c4a3156258918f280c96", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-08-24T20:32:03.000Z", "max_forks_repo_forks_event_max_datetime": "2017-08-24T20:32:03.000Z", "avg_line_length": 28.6444444444, "max_line_length": 92, "alphanum_fraction": 0.6353762607, "num_tokens": 439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.46360740179147764}}
{"text": "#include \"rcvio/updater.hpp\"\n\n#include <Eigen/Dense>\n#include <opencv2/core/eigen.hpp>\n\n#include <visualization_msgs/Marker.h>\n\n#include \"rcvio/numerics.h\"\n\nnamespace rcvio\n{\n    static int cloud_id = 0;\n    std_msgs::ColorRGBA color_landmark;\n    geometry_msgs::Vector3 scale_landmark;\n\n    Updater::Updater(const cv::FileStorage &fs_settings)\n    {\n        cam_rate_ = fs_settings[\"Camera.fps\"];\n\n        const float image_noise_sigma_x = fs_settings[\"Camera.sigma_px\"];\n        const float image_noise_sigma_y = fs_settings[\"Camera.sigma_py\"];\n\n        image_noise_sigma_ = std::max(image_noise_sigma_x, image_noise_sigma_y);\n\n        cv::Mat T(4, 4, CV_32F);\n        fs_settings[\"Camera.T_BC0\"] >> T;\n        Eigen::Matrix4d Tic;\n        cv::cv2eigen(T, Tic);\n        Ric_ = Tic.block<3, 3>(0, 0);\n        tic_ = Tic.block<3, 1>(0, 3);\n        Rci_ = Ric_.transpose();\n        tci_ = -Rci_ * tic_;\n\n        xk1k1.setZero(26, 1);\n        Pk1k1.setZero(24, 24);\n\n        feature_publish_ = updater_node_.advertise<visualization_msgs::Marker>(\"/rcvio/landmarks\", 1);\n        publish_rate_ = fs_settings[\"Landmark.nPubRate\"];\n\n        scale_landmark.x = fs_settings[\"Landmark.nScale\"];\n        scale_landmark.y = fs_settings[\"Landmark.nScale\"];\n        scale_landmark.z = fs_settings[\"Landmark.nScale\"];\n\n        color_landmark.a = 1;\n        color_landmark.r = 0;\n        color_landmark.b = 1;\n        color_landmark.g = 0;\n    }\n\n    void Updater::update(Eigen::VectorXd &xk1k,\n                         Eigen::MatrixXd &Pk1k,\n                         std::vector<unsigned char> &feature_types_for_update,\n                         std::vector<std::list<cv::Point2f>> &feature_measurements_for_update)\n    {\n        visualization_msgs::Marker cloud;\n        cloud.header.frame_id = \"imu\";\n        cloud.ns = \"points\";\n        cloud.id = ++cloud_id;\n        cloud.color = color_landmark;\n        cloud.scale = scale_landmark;\n        cloud.pose.orientation.w = 1.0;\n        cloud.lifetime = ros::Duration(1 / publish_rate_);\n        cloud.action = visualization_msgs::Marker::ADD;\n        cloud.type = visualization_msgs::Marker::POINTS;\n\n        int num_feature = static_cast<int>(feature_types_for_update.size());\n\n        int rows = 0;\n        for (int i = 0; i < num_feature; ++i)\n        {\n            rows += 2 * static_cast<int>(feature_measurements_for_update.at(i).size());\n        }\n\n        int clone_states = (xk1k.rows() - 26) / 7;\n\n        Eigen::VectorXd r(rows, 1);\n        Eigen::MatrixXd Hx(rows, 24 + 6 * clone_states);\n        r.setZero();\n        Hx.setZero();\n\n        int row_count = 0;\n        int good_feature_count = 0;\n\n        for (int feature_idx = 0; feature_idx < num_feature; ++feature_idx)\n        {\n            char feature_type = feature_types_for_update.at(feature_idx);\n            std::list<cv::Point2f> feature_measurements = feature_measurements_for_update.at(feature_idx);\n\n            int track_length = static_cast<int>(feature_measurements.size());\n            int track_phases = track_length - 1;\n            int relative_poses_dimension = 7 * track_phases;\n\n            Eigen::VectorXd relative_poses;\n            if (feature_type == '1')\n            {\n                relative_poses = xk1k.tail(relative_poses_dimension);\n            }\n            else\n            {\n                relative_poses = xk1k.block(26, 0, relative_poses_dimension, 1);\n            }\n\n            Eigen::VectorXd relative_poses_to_first(relative_poses_dimension, 1);\n            relative_poses_to_first.block(0, 0, 7, 1) << relative_poses.block(0, 0, 4, 1),\n                -quatToRot(relative_poses.block(0, 0, 4, 1)) * relative_poses.block(4, 0, 3, 1);\n\n            for (int i = 1; i < track_phases; ++i)\n            {\n                Eigen::Vector4d qI = quatMul(relative_poses.block(7 * i, 0, 4, 1),\n                                             relative_poses_to_first.block(7 * (i - 1), 0, 4, 1));\n                Eigen::Vector3d tI = quatToRot(relative_poses.block(7 * i, 0, 4, 1)) *\n                                     (relative_poses_to_first.block(7 * (i - 1) + 4, 0, 3, 1) -\n                                      relative_poses.block(7 * i + 4, 0, 3, 1));\n                relative_poses_to_first.block(7 * i, 0, 7, 1) << qI, tI;\n            }\n\n            Eigen::VectorXd cam_relative_poses_to_first(relative_poses_dimension, 1);\n            for (int i = 0; i < track_phases; ++i)\n            {\n                Eigen::Vector4d qC = rotToQuat(Rci_ * quatToRot(relative_poses_to_first.block(7 * i, 0, 4, 1)) * Ric_);\n                Eigen::Vector3d tC = Rci_ * quatToRot(relative_poses_to_first.block(7 * i, 0, 4, 1)) * tic_ + Rci_ * relative_poses_to_first.block(7 * i + 4, 0, 3, 1) + tci_;\n                cam_relative_poses_to_first.block(7 * i, 0, 7, 1) << qC, tC;\n            }\n\n            cv::Point2f pt_first = feature_measurements.front();\n            feature_measurements.pop_front();\n\n            double phi = std::atan2(pt_first.y, std::sqrt(std::pow(pt_first.x, 2) + 1));\n            double psi = std::atan2(pt_first.x, 1);\n            double rho = 0.0;\n\n            if (std::fabs(phi) > 0.5 * 3.14 || std::fabs(psi) > 0.5 * 3.14)\n            {\n                ROS_DEBUG(\"Invalid inverse-depth feature estimate (0)!\");\n                continue;\n            }\n\n            Eigen::Vector3d epfinv;\n            epfinv << std::cos(phi) * std::sin(psi), std::sin(phi), std::cos(phi) * std::cos(psi);\n\n            Eigen::Matrix<double, 3, 2> Jang;\n            Jang << -std::sin(phi) * std::sin(psi), std::cos(phi) * std::cos(psi),\n                std::cos(phi), 0,\n                -std::sin(phi) * std::cos(psi), -std::cos(phi) * std::sin(psi);\n\n            Eigen::Matrix2d Rinv;\n            Rinv << 1.0 / std::pow(image_noise_sigma_, 2), 0,\n                0, 1.0 / std::pow(image_noise_sigma_, 2);\n\n            int max_iter = 10;\n            double lambda = 0.01;\n            double last_cost = std::numeric_limits<double>::infinity();\n\n            for (int iter = 0; iter < max_iter; ++iter)\n            {\n                Eigen::Matrix3d HTRinvH = Eigen::Matrix3d::Zero();\n                Eigen::Vector3d HTRinve = Eigen::Vector3d::Zero();\n                double cost = 0;\n\n                Eigen::Vector3d h1 = epfinv;\n\n                Eigen::Matrix<double, 2, 3> Hproj1;\n                Hproj1 << 1 / h1(2), 0, -h1(0) / std::pow(h1(2), 2),\n                    0, 1 / h1(2), -h1(1) / std::pow(h1(2), 2);\n\n                Eigen::Matrix<double, 2, 3> H1;\n                H1 << Hproj1 * Jang, Eigen::Vector2d::Zero();\n\n                cv::Point2f pt1;\n                pt1.x = h1(0) / h1(2);\n                pt1.y = h1(1) / h1(2);\n\n                Eigen::Vector2d e1;\n                e1 << (pt_first - pt1).x, (pt_first - pt1).y;\n\n                cost += e1.transpose() * Rinv * e1;\n\n                HTRinvH.noalias() += H1.transpose() * Rinv * H1;\n                HTRinve.noalias() += H1.transpose() * Rinv * e1;\n\n                std::list<cv::Point2f>::const_iterator it = feature_measurements.begin();\n                for (int i = 0; i < track_phases; ++i, ++it)\n                {\n                    Eigen::Matrix3d Rc = quatToRot(cam_relative_poses_to_first.block(7 * i, 0, 4, 1));\n                    Eigen::Vector3d tc = cam_relative_poses_to_first.block(7 * i + 4, 0, 3, 1);\n                    Eigen::Vector3d h = Rc * epfinv + rho * tc;\n\n                    Eigen::Matrix<double, 2, 3> Hproj;\n                    Hproj << 1 / h(2), 0, -h(0) / std::pow(h(2), 2),\n                        0, 1 / h(2), -h(1) / std::pow(h(2), 2);\n\n                    Eigen::Matrix<double, 2, 3> H;\n                    H << Hproj * Rc * Jang, Hproj * tc;\n\n                    cv::Point2f pt;\n                    pt.x = h(0) / h(2);\n                    pt.y = h(1) / h(2);\n\n                    Eigen::Vector2d e;\n                    e << ((*it) - pt).x, ((*it) - pt).y;\n\n                    cost += e.transpose() * Rinv * e;\n\n                    HTRinvH.noalias() += H.transpose() * Rinv * H;\n                    HTRinve.noalias() += H.transpose() * Rinv * e;\n                }\n\n                if (cost <= last_cost)\n                {\n                    HTRinvH.diagonal() += lambda * HTRinvH.diagonal();\n                    Eigen::Vector3d dpfinv = HTRinvH.colPivHouseholderQr().solve(HTRinve);\n\n                    phi += dpfinv(0);\n                    psi += dpfinv(1);\n                    rho += dpfinv(2);\n\n                    epfinv << std::cos(phi) * std::sin(psi), std::sin(phi), std::cos(phi) * std::cos(psi);\n\n                    Jang << -std::sin(phi) * std::sin(psi), std::cos(phi) * std::cos(psi),\n                        std::cos(phi), 0,\n                        -std::sin(phi) * std::cos(psi), -std::cos(phi) * std::sin(psi);\n\n                    if (std::fabs(last_cost - cost) < 1e-6 && dpfinv(2) < 1e-6)\n                        break;\n\n                    lambda *= 0.1;\n                    last_cost = cost;\n                }\n                else\n                {\n                    lambda *= 10;\n                    last_cost = cost;\n                }\n            }\n\n            if (std::fabs(phi) > 0.5 * 3.14 || std::fabs(psi) > 0.5 * 3.14 || std::isinf(rho) || rho < 0)\n            {\n                ROS_DEBUG(\"Invalid inverse-depth feature estimate (1)!\");\n                continue;\n            }\n\n            if (feature_type == '2')\n            {\n                track_length = std::ceil(0.5 * track_length);\n                track_phases = track_length - 1;\n            }\n\n            Eigen::VectorXd tempr(2 * track_length, 1);\n            Eigen::MatrixXd temp_Hx(2 * track_length, 6 * clone_states);\n            Eigen::MatrixXd temp_Hf(2 * track_length, 3);\n            tempr.setZero();\n            temp_Hx.setZero();\n            temp_Hf.setZero();\n\n            int start_row = 0;\n            int start_col;\n            if (feature_type == '1')\n            {\n                start_col = 6 * (clone_states - track_phases);\n            }\n            else\n            {\n                start_col = 0;\n            }\n\n            Eigen::Vector3d h1 = epfinv;\n\n            cv::Point2f pt1;\n            pt1.x = h1(0) / h1(2);\n            pt1.y = h1(1) / h1(2);\n\n            Eigen::Matrix<double, 2, 3> Hproj1;\n            Hproj1 << 1 / h1(2), 0, -h1(0) / std::pow(h1(2), 2),\n                0, 1 / h1(2), -h1(1) / std::pow(h1(2), 2);\n\n            cv::Point2f e1 = pt_first - pt1;\n            tempr.block(0, 0, 2, 1) << e1.x, e1.y;\n\n            Eigen::Matrix3d tempm = Eigen::Matrix3d::Zero();\n            tempm.block<3, 2>(0, 0) = Jang;\n            temp_Hf.block<2, 3>(0, 0) = Hproj1 * tempm;\n\n            start_row += 2;\n\n            std::list<cv::Point2f>::const_iterator it = feature_measurements.begin();\n            for (int i = 1; i < track_length; ++i, ++it)\n            {\n                Eigen::Matrix3d R = quatToRot(relative_poses_to_first.block(7 * (i - 1), 0, 4, 1));\n\n                Eigen::Matrix3d Rc = quatToRot(cam_relative_poses_to_first.block(7 * (i - 1), 0, 4, 1));\n                Eigen::Vector3d tc = cam_relative_poses_to_first.block(7 * (i - 1) + 4, 0, 3, 1);\n                Eigen::Vector3d h = Rc * epfinv + rho * tc;\n\n                cv::Point2f pt;\n                pt.x = h(0) / h(2);\n                pt.y = h(1) / h(2);\n\n                Eigen::Matrix<double, 2, 3> Hproj;\n                Hproj << 1 / h(2), 0, -h(0) / std::pow(h(2), 2),\n                    0, 1 / h(2), -h(1) / std::pow(h(2), 2);\n\n                cv::Point2f e = (*it) - pt;\n                tempr.block(2 * i, 0, 2, 1) << e.x, e.y;\n\n                Eigen::Matrix3d R0T = quatToRot(relative_poses_to_first.block(0, 0, 4, 1)).transpose();\n                Eigen::Vector3d t0 = relative_poses_to_first.block(4, 0, 3, 1);\n\n                Eigen::Matrix3d dpx0 = skew(Ric_ * epfinv + rho * tic_ + rho * R0T * t0);\n                Eigen::Matrix<double, 3, 6> subH;\n                subH << dpx0 * R0T, -rho * Eigen::Matrix3d::Identity();\n\n                temp_Hx.block(start_row, start_col, 2, 6) = Hproj * Rci_ * R * subH;\n\n                for (int j = 1; j < i; ++j)\n                {\n                    Eigen::Matrix3d R1T = quatToRot(relative_poses_to_first.block(7 * j, 0, 4, 1)).transpose();\n                    Eigen::Vector3d t1 = relative_poses_to_first.block(7 * j + 4, 0, 3, 1);\n                    Eigen::Matrix3d R2T = quatToRot(relative_poses_to_first.block(7 * (j - 1), 0, 4, 1)).transpose();\n\n                    Eigen::Matrix3d dpx = skew(Ric_ * epfinv + rho * tic_ + rho * R1T * t1);\n                    subH << dpx * R1T, -rho * R2T;\n\n                    temp_Hx.block(start_row, start_col + 6 * j, 2, 6) = Hproj * Rci_ * R * subH;\n                }\n\n                temp_Hf.block(start_row, 0, 2, 3) << Hproj * Rc * Jang, Hproj * tc;\n\n                start_row += 2;\n            }\n\n            int M = start_row;\n            int N = temp_Hf.cols();\n\n            if (temp_Hf.col(N - 1).norm() < 1e-4)\n            {\n                ROS_DEBUG(\"Hf is rank deficient!\");\n                N--;\n            }\n\n            Eigen::JacobiRotation<double> temp_Hf_GR;\n\n            for (int n = 0; n < N; ++n)\n            {\n                for (int m = M - 1; m > n; m--)\n                {\n                    temp_Hf_GR.makeGivens(temp_Hf(m - 1, n), temp_Hf(m, n));\n\n                    (temp_Hf.block(m - 1, n, 2, N - n)).applyOnTheLeft(0, 1, temp_Hf_GR.adjoint());\n\n                    (temp_Hx.block(m - 1, 0, 2, temp_Hx.cols())).applyOnTheLeft(0, 1, temp_Hf_GR.adjoint());\n\n                    (tempr.block(m - 1, 0, 2, 1)).applyOnTheLeft(0, 1, temp_Hf_GR.adjoint());\n                }\n            }\n\n            int DOF = M - N;\n            Eigen::VectorXd _tempr = tempr.block(N, 0, DOF, 1);\n            Eigen::MatrixXd _temp_Hx = temp_Hx.block(N, 0, DOF, temp_Hx.cols());\n\n            Eigen::VectorXd temp_R;\n            temp_R.setOnes(DOF, 1);\n            temp_R *= std::pow(image_noise_sigma_, 2);\n\n            Eigen::MatrixXd temp_S;\n            temp_S = _temp_Hx * Pk1k.block(24, 24, 6 * clone_states, 6 * clone_states) * (_temp_Hx.transpose());\n            temp_S.diagonal() += temp_R;\n            temp_S = 0.5 * (temp_S + temp_S.transpose());\n\n            double mahalanobis_dist = (_tempr.transpose() * (temp_S.colPivHouseholderQr().solve(_tempr))).norm();\n\n            if (mahalanobis_dist < CHI_THRESHOLD[DOF - 1])\n            {\n                r.block(row_count, 0, DOF, 1) = _tempr;\n                Hx.block(row_count, 24, DOF, 6 * clone_states) = _temp_Hx;\n\n                row_count += DOF;\n                good_feature_count++;\n\n                if (rho > 0)\n                {\n                    Eigen::VectorXd posek = relative_poses_to_first.tail(7);\n                    Eigen::MatrixXd Rk = quatToRot(posek.head(4));\n                    Eigen::Vector3d tk = posek.tail(3);\n\n                    Eigen::Vector3d pfc = 1 / rho * epfinv;\n                    Eigen::Vector3d pf1 = Ric_ * pfc + tic_;\n                    Eigen::Vector3d pfk = Rk * pf1 + tk;\n\n                    geometry_msgs::Point feature;\n                    feature.x = pfk(0);\n                    feature.y = pfk(1);\n                    feature.z = pfk(2);\n                    cloud.points.push_back(feature);\n                }\n            }\n            else\n            {\n                ROS_DEBUG(\"Failed in Mahalanobis distance test!\");\n                continue;\n            }\n        }\n\n        feature_publish_.publish(cloud);\n\n        if (good_feature_count > 2)\n        {\n            Eigen::VectorXd ro = r.block(0, 0, row_count, 1);\n            Eigen::MatrixXd Ho = Hx.block(0, 0, row_count, Hx.cols());\n\n            Eigen::VectorXd Ro;\n            Ro.setOnes(row_count, 1);\n            Ro *= std::pow(image_noise_sigma_, 2);\n\n            Eigen::VectorXd rn;\n            Eigen::MatrixXd Hn;\n            Eigen::VectorXd Rn;\n\n            if (Ho.rows() > Ho.cols() - 24)\n            {\n                int M = Ho.rows();\n                int N = Ho.cols() - 24;\n\n                Eigen::MatrixXd temp_Hw = Ho.block(0, 24, M, N);\n\n                for (int i = N; i > 0; i--)\n                {\n                    if (temp_Hw.col(i - 1).norm() == 0)\n                    {\n                        ROS_DEBUG(\"Hw is rank deficient!\");\n                        N--;\n                    }\n                    else\n                    {\n                        break;\n                    }\n                }\n\n                Eigen::JacobiRotation<double> temp_Hw_GR;\n\n                for (int n = 0; n < N; ++n)\n                {\n                    for (int m = M - 1; m > n; m--)\n                    {\n                        temp_Hw_GR.makeGivens(temp_Hw(m - 1, n), temp_Hw(m, n));\n\n                        (temp_Hw.block(m - 1, n, 2, N - n)).applyOnTheLeft(0, 1, temp_Hw_GR.adjoint());\n\n                        (ro.block(m - 1, 0, 2, 1)).applyOnTheLeft(0, 1, temp_Hw_GR.adjoint());\n                    }\n                }\n\n                Ho.block(0, 24, M, N) = temp_Hw.block(0, 0, M, N);\n\n                int rank = 0;\n                for (int i = 0; i < M; ++i)\n                {\n                    if (Ho.row(i).norm() < 1e-4)\n                    {\n                        break;\n                    }\n                    else\n                    {\n                        rank++;\n                    }\n                }\n\n                rn = ro.block(0, 0, rank, 1);\n                Hn = Ho.block(0, 0, rank, Ho.cols());\n                Rn.setOnes(rank, 1);\n                Rn *= std::pow(image_noise_sigma_, 2);\n            }\n            else\n            {\n                rn = ro;\n                Hn = Ho;\n                Rn = Ro;\n            }\n\n            Eigen::MatrixXd S = Hn * Pk1k * (Hn.transpose());\n            S.diagonal() += Rn;\n            S = 0.5 * (S + S.transpose());\n            Eigen::MatrixXd K = Pk1k * (Hn.transpose()) * (S.inverse());\n            Eigen::VectorXd dx = K * rn;\n\n            xk1k1.resize(xk1k.rows(), 1);\n\n            Eigen::Vector4d dqG;\n            dqG(0) = 0.5 * dx(0);\n            dqG(1) = 0.5 * dx(1);\n            dqG(2) = 0.5 * dx(2);\n\n            double dqGvn = (dqG.head(3)).norm();\n            if (dqGvn < 1)\n            {\n                dqG(3) = std::sqrt(1 - std::pow(dqGvn, 2));\n            }\n            else\n            {\n                dqG.head(3) *= (1 / std::sqrt(1 + std::pow(dqGvn, 2)));\n                dqG(3) = 1 / std::sqrt(1 + std::pow(dqGvn, 2));\n            }\n\n            xk1k1.block(0, 0, 4, 1) = quatMul(dqG, xk1k.block(0, 0, 4, 1));\n            xk1k1.block(4, 0, 6, 1) = dx.block(3, 0, 6, 1) + xk1k.block(4, 0, 6, 1);\n\n            Eigen::Vector3d g = xk1k1.block(7, 0, 3, 1);\n            g.normalize();\n            xk1k1.block(7, 0, 3, 1) = g;\n\n            Eigen::Vector4d dqR;\n            dqR(0) = 0.5 * dx(9);\n            dqR(1) = 0.5 * dx(10);\n            dqR(2) = 0.5 * dx(11);\n\n            double dqRvn = (dqR.head(3)).norm();\n            if (dqRvn < 1)\n            {\n                dqR(3) = std::sqrt(1 - std::pow(dqRvn, 2));\n            }\n            else\n            {\n                dqR.head(3) *= (1 / std::sqrt(1 + std::pow(dqRvn, 2)));\n                dqR(3) = 1 / std::sqrt(1 + std::pow(dqRvn, 2));\n            }\n\n            xk1k1.block(10, 0, 4, 1) = quatMul(dqR, xk1k.block(10, 0, 4, 1));\n            xk1k1.block(14, 0, 12, 1) = dx.block(12, 0, 12, 1) + xk1k.block(14, 0, 12, 1);\n\n            for (int pose_idx = 0; pose_idx < clone_states; ++pose_idx)\n            {\n                Eigen::Vector4d dqc;\n                dqc(0) = 0.5 * dx(24 + 6 * pose_idx);\n                dqc(1) = 0.5 * dx(24 + 6 * pose_idx + 1);\n                dqc(2) = 0.5 * dx(24 + 6 * pose_idx + 2);\n\n                double dqcvn = (dqc.head(3)).norm();\n                if (dqcvn < 1)\n                {\n                    dqc(3) = std::sqrt(1 - std::pow(dqcvn, 2));\n                }\n                else\n                {\n                    dqc.head(3) *= (1 / std::sqrt(1 + std::pow(dqcvn, 2)));\n                    dqc(3) = 1 / std::sqrt(1 + std::pow(dqcvn, 2));\n                }\n\n                xk1k1.block(26 + 7 * pose_idx, 0, 4, 1) = quatMul(dqc, xk1k.block(26 + 7 * pose_idx, 0, 4, 1));\n                xk1k1.block(26 + 7 * pose_idx + 4, 0, 3, 1) = dx.block(24 + 6 * pose_idx + 3, 0, 3, 1) + xk1k.block(26 + 7 * pose_idx + 4, 0, 3, 1);\n            }\n\n            Eigen::MatrixXd _I = Eigen::MatrixXd::Identity(Pk1k.rows(), Pk1k.cols());\n            Eigen::MatrixXd I_KH = _I - K * Hn;\n\n            Pk1k1 = I_KH * Pk1k * (I_KH.transpose());\n            Pk1k1 += Rn(0) * K * (K.transpose());\n            Pk1k1 = 0.5 * (Pk1k1 + Pk1k1.transpose());\n        }\n        else\n        {\n            ROS_DEBUG(\"Too few measurements for update!\");\n\n            xk1k1 = xk1k;\n            Pk1k1 = Pk1k;\n        }\n    }\n}", "meta": {"hexsha": "397dcf05729de3c6a8230f1be2190aaf9d331f17", "size": 20821, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/updater.cpp", "max_stars_repo_name": "sufalroy/RC-VIO", "max_stars_repo_head_hexsha": "139a423190e87018e060dfc630cd6790aa2357fc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/updater.cpp", "max_issues_repo_name": "sufalroy/RC-VIO", "max_issues_repo_head_hexsha": "139a423190e87018e060dfc630cd6790aa2357fc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/updater.cpp", "max_forks_repo_name": "sufalroy/RC-VIO", "max_forks_repo_head_hexsha": "139a423190e87018e060dfc630cd6790aa2357fc", "max_forks_repo_licenses": ["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.7862190813, "max_line_length": 174, "alphanum_fraction": 0.4494981029, "num_tokens": 6188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4636074017914775}}
{"text": "/**\n * @file pfasst/encap/encapsulation.hpp\n * @since v0.1.0\n */\n#ifndef _PFASST_ENCAPSULATED_HPP_\n#define _PFASST_ENCAPSULATED_HPP_\n\n#include <memory>\n#include <vector>\nusing namespace std;\n\n#include <Eigen/Dense>\n\ntemplate<typename scalar>\nusing Matrix = Eigen::Matrix<scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;\n\n#include \"pfasst/interfaces.hpp\"\n\n\nnamespace pfasst\n{\n  /**\n   * Encapsulations (short _encaps_) are the central data type for all PFASST++ algorithms.\n   * Encaps can represent the unknown variable or the result of evaluating the right hand side of\n   * the problem equation(s).\n   */\n  namespace encap\n  {\n    typedef enum EncapType { solution, function } EncapType;\n\n    /**\n     * Data/solution encapsulation.\n     *\n     * An Encapsulation provides basic mathematical functionality for the user's data.\n     *\n     * @tparam time time precision; defaults to pfasst::time_precision\n     */\n    template<typename time = time_precision>\n    class Encapsulation\n    {\n      public:\n        //! @{\n        virtual ~Encapsulation();\n        //! @}\n\n        //! @{\n        /**\n         * Zeroes out all values of this data structure.\n         */\n        virtual void zero();\n\n        /**\n         * Copies values from @p other into this data structure.\n         *\n         * @param[in] other other data structure to copy data from\n         */\n        virtual void copy(shared_ptr<const Encapsulation<time>> other);\n        //! @}\n\n        //! @{\n        /**\n         * Computes the \\\\( 0 \\\\)-norm of the data structure's values.\n         *\n         * @returns \\\\( 0 \\\\)-norm of this data structure\n         */\n        virtual time norm0() const;\n        //! @}\n\n        //! @{\n        /**\n         * Provides basic mathematical operation \\\\( y = ax + y \\\\).\n         *\n         * This is the main mathematical operation applied by PFASST on the data structures.\n         * Here, \\\\( a \\\\) is a constant and \\\\( x \\\\) another data structure (usually of the same\n         * type) and \\\\( y \\\\) is this data structure.\n         *\n         * @param[in] a time point to multiply\n         * @param[in] x another data structure to scale-add onto this one\n         */\n        virtual void saxpy(time a, shared_ptr<const Encapsulation<time>> x);\n\n        /**\n         * Defines matrix-vector multiplication for this data type.\n         *\n         * This implements the matrix-vector multiplication of the form\n         * \\\\( \\\\vec{y}=a M \\\\vec{x} \\\\).\n         * Here, \\\\( a \\\\) is a time point to scale the matrix-vector multiplication with, \\\\( M \\\\)\n         * is a matrix and \\\\( x \\\\) another data structure usually of the same type as this one.\n         *\n         * If @p zero is `true`, then @p dst is zeroed out before applying the matrix-vector\n         * multiplication.\n         * Elsewise the result of the matrix-vector multiplication is added onto @p dst.\n         *\n         * @param[in,out] dst  data structure to store the result in\n         * @param[in]     a\n         * @param[in]     mat\n         * @param[in]     src\n         * @param[in]     zero\n         */\n        virtual void mat_apply(vector<shared_ptr<Encapsulation<time>>> dst,\n                               time a, Matrix<time> mat,\n                               vector<shared_ptr<Encapsulation<time>>> src,\n                               bool zero = true);\n        //! @}\n\n        //! @{\n        /**\n         * Prepare to receive a solution (MPI_IRecv).\n         *\n         * @param[in] comm     communicator managing the processes to post ??? to/from ???\n         * @param[in] tag      tag to distinguish overlapping communication\n         */\n        virtual void post(ICommunicator* comm, int tag);\n\n        /**\n         * Send solution (MPI_Send).\n         *\n         * @param[in] comm     communicator managing the processes to send to\n         * @param[in] tag      tag to distinguish overlapping communication\n         * @param[in] blocking whether to use blocking or non-blocking send\n         */\n        virtual void send(ICommunicator* comm, int tag, bool blocking);\n\n        /**\n         * Receive solution (MPI_Recv).\n         *\n         * @param[in] comm     communicator managing the processes to receive from\n         * @param[in] tag      tag to distinguish overlapping communication\n         * @param[in] blocking whether to use blocking or non-blocking receive\n         */\n        virtual void recv(ICommunicator* comm, int tag, bool blocking);\n\n        /**\n         * Broadcast this data structure to all processes in @p comm.\n         *\n         * @param[in] comm communicator managing the processes to send this data structure to\n         */\n        virtual void broadcast(ICommunicator* comm);\n        //! @}\n    };\n\n\n    /**\n     * Abstract interface of factory for creating Encapsulation objects.\n     *\n     * This factory is intended to be instantiated once to create multiple Encapsulation objects\n     * of the same type and with the same parameters later on through calls to\n     * EncapFactory::create().\n     *\n     * @tparam time time precision; defaults to pfasst::time_precision\n     */\n    template<typename time = time_precision>\n    class EncapFactory\n    {\n      public:\n        /**\n         * Actual method to create Encapsulation object of specific type.\n         *\n         * @param[in] type encapsulation type of the requested Encapsulation object\n         */\n        virtual shared_ptr<Encapsulation<time>> create(const EncapType type) = 0;\n    };\n  }  // ::pfasst::encap\n} // ::pfasst\n\n#include \"pfasst/encap/encapsulation_impl.hpp\"\n\n#endif\n", "meta": {"hexsha": "5d2bd03e020cd7230337ec9fb6a08148eeae07c6", "size": 5587, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/pfasst/encap/encapsulation.hpp", "max_stars_repo_name": "memmett/PFASST", "max_stars_repo_head_hexsha": "655085fae12b7cce8558484baefdac1bf3d84c2c", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 28.0, "max_stars_repo_stars_event_min_datetime": "2015-01-05T11:25:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-09T01:09:52.000Z", "max_issues_repo_path": "include/pfasst/encap/encapsulation.hpp", "max_issues_repo_name": "memmett/PFASST", "max_issues_repo_head_hexsha": "655085fae12b7cce8558484baefdac1bf3d84c2c", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 81.0, "max_issues_repo_issues_event_min_datetime": "2015-01-05T11:23:15.000Z", "max_issues_repo_issues_event_max_datetime": "2016-12-13T11:03:04.000Z", "max_forks_repo_path": "include/pfasst/encap/encapsulation.hpp", "max_forks_repo_name": "memmett/PFASST", "max_forks_repo_head_hexsha": "655085fae12b7cce8558484baefdac1bf3d84c2c", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2015-02-03T07:59:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-25T20:26:08.000Z", "avg_line_length": 33.0591715976, "max_line_length": 100, "alphanum_fraction": 0.58260247, "num_tokens": 1242, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568416, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.4636073956375702}}
{"text": "#include <boost/test/unit_test.hpp>\n#include \"../src/quadratic.hpp\"\n\n\nusing namespace planner;\n\nBOOST_AUTO_TEST_SUITE(quadratic)\n\nBOOST_AUTO_TEST_CASE(test_constructors) {\n    {\n        Quadratic<int> q1;\n        BOOST_CHECK_EQUAL(q1.real, 0);\n        BOOST_CHECK_EQUAL(q1.imaginary, 0);\n    }\n    {\n        Quadratic<int> q2{1, 2};\n        BOOST_CHECK_EQUAL(q2.real, 1);\n        BOOST_CHECK_EQUAL(q2.imaginary, 2);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(test_arithmetic) {\n    Quadratic<int> q1{ 1, 2 };\n    Quadratic<int> q2{ 3, -5};\n    q1 += q2;\n    BOOST_CHECK_EQUAL(q1,  Quadratic<int>(4, -3));\n    auto q3 = q1 + q2;\n    BOOST_CHECK_EQUAL(q3, Quadratic<int>(7, -8));\n    q3 -= q2;\n    BOOST_CHECK_EQUAL(q3,  Quadratic<int>(4, -3));\n    auto q4 = q3 - q2;\n    BOOST_CHECK_EQUAL(q4,  Quadratic<int>(1, 2));\n}\n\nBOOST_AUTO_TEST_CASE(test_evaluation) {\n    {\n        Quadratic<int> q{ 1, 1 };\n        BOOST_CHECK_CLOSE(evaluate(q), 1 + sqrt(2), 1e-9);\n    }\n    {\n        Quadratic<int> q{ 0, 1 };\n        BOOST_CHECK_CLOSE(evaluate(q), sqrt(2), 1e-9);\n    }\n    {\n        Quadratic<int> q{ 1, 0 };\n        BOOST_CHECK_CLOSE(evaluate(q), 1, 1e-9);\n    }\n    {\n        Quadratic<int> q{ 5, -4 };\n        BOOST_CHECK_CLOSE(evaluate(q), 5 - 4 * sqrt(2), 1e-9);\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "ad5c5b10c9b60d2f255f71beee321fdd924d2dc7", "size": 1287, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_quadratic.cpp", "max_stars_repo_name": "packedbread/pathplanning", "max_stars_repo_head_hexsha": "d09e143022d716243673530427774d5ee48c1845", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/test_quadratic.cpp", "max_issues_repo_name": "packedbread/pathplanning", "max_issues_repo_head_hexsha": "d09e143022d716243673530427774d5ee48c1845", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-01-10T15:49:38.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-10T16:43:15.000Z", "max_forks_repo_path": "tests/test_quadratic.cpp", "max_forks_repo_name": "packedbread/pathplanning", "max_forks_repo_head_hexsha": "d09e143022d716243673530427774d5ee48c1845", "max_forks_repo_licenses": ["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.8333333333, "max_line_length": 62, "alphanum_fraction": 0.5874125874, "num_tokens": 415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.4635895498944154}}
{"text": "/* @copyright The code is licensed under the MIT License\n *            <https://opensource.org/licenses/MIT>,\n *            Copyright (c) 2020 Christian Eskil Vaugelade Berg\n * @author Christian Eskil Vaugelade Berg\n*/\n#pragma once\n\n#include <orient/axis.hpp>\n\n#include <Eigen/Dense>\n\nnamespace orient {\n\n// \\brief Construct rotation matrix from scalar angle and a rotation axis\n// \\param angle Scalar angle\n// \\template-param axis Rotation axis\n// \\return Rotation matrix\ntemplate<Axis axis, typename Scalar>\nEigen::Matrix<Scalar,3,3> rotationMatrixFromEuler(Scalar angle);\n\n// \\brief Construct rotation matrix and partial derivatives from scalar angle and a rotation axis\n// \\param angle Scalar angle\n// \\template-param axis Rotation axis\n// \\return A pair containing first the rotation matrix and then secondly the Jacobian matrix\ntemplate<Axis axis, typename Scalar>\nstd::pair<Eigen::Matrix<Scalar,3,3>, Eigen::Matrix<Scalar,3,3>> rotationMatrixFromEulerWD(Scalar angle);\n\n// \\brief Calculate rotation matrix from Euler angles and a rotation order\n//        The rotation order is expressed in instrisic rotations.\n//        For example, the rotation matrix\n//        R = Rz(yaw) * Ry(pitch) * Rx(roll)\n//        is constructed with\n//        auto R = rotationMatrixFromEuler<Axis::z, Axis::y, Axis::x>([yaw, pitch, roll]);\n// \\param anlges Source Euler angles\n// \\template-params A1,A2,A3 The intrinsic rotation order\n// \\return Rotation matrix\ntemplate<Axis A1, Axis A2, Axis A3, typename Scalar>\nEigen::Matrix<Scalar,3,3> rotationMatrixFromEuler(Eigen::Matrix<Scalar,3,1> const& angles);\n\n// \\brief Calculate rotation matrix and partial derivatves from Euler angles and a rotation order\n//        See above for detail\n// \\param anlges Source Euler angles\n// \\template-params A1,A2,A3 The intrinsic rotation order\n// \\return A pair containing first the rotation matrix and then secondly the Jacobian matrix\ntemplate<Axis A1, Axis A2, Axis A3, typename Scalar>\nstd::pair<Eigen::Matrix<Scalar,3,3>, Eigen::Matrix<Scalar, 9, 3>> rotationMatrixFromEulerWD(Eigen::Matrix<Scalar,3,1> const& angles);\n\n}\n\n#include <orient/impl/from_euler.hpp>\n", "meta": {"hexsha": "89c89f526a0431bdf9346186825438c26cfef45c", "size": 2141, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/orient/from_euler.hpp", "max_stars_repo_name": "Eskilade/orient", "max_stars_repo_head_hexsha": "d73e9459155e991539c20bfd92c04cb487b65538", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2020-05-11T07:27:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-10T09:23:29.000Z", "max_issues_repo_path": "include/orient/from_euler.hpp", "max_issues_repo_name": "Eskilade/orient", "max_issues_repo_head_hexsha": "d73e9459155e991539c20bfd92c04cb487b65538", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-09-20T02:22:15.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-21T01:42:47.000Z", "max_forks_repo_path": "include/orient/from_euler.hpp", "max_forks_repo_name": "Eskilade/orient", "max_forks_repo_head_hexsha": "d73e9459155e991539c20bfd92c04cb487b65538", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-09-14T11:11:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-10T04:26:22.000Z", "avg_line_length": 41.9803921569, "max_line_length": 133, "alphanum_fraction": 0.7389070528, "num_tokens": 535, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.6825737473266736, "lm_q1q2_score": 0.4635895498006036}}
{"text": "/**\t\\file TestPerpIntercept.cpp\n*\t\\brief \n*/\n\n/****************************************************************************/\n/*\tTestPerpIntercept.cpp\t\t\t\t\t\t\t\t\t\t\t\t\t*/\n/****************************************************************************/\n/*                                                                          */\n/*  Copyright 2008 - 2010 Paul Kohut                                        */\n/*  Licensed under the Apache License, Version 2.0 (the \"License\"); you may */\n/*  not use this file except in compliance with the License. You may obtain */\n/*  a copy of the License at                                                */\n/*                                                                          */\n/*  http://www.apache.org/licenses/LICENSE-2.0                              */\n/*                                                                          */\n/*  Unless required by applicable law or agreed to in writing, software     */\n/*  distributed under the License is distributed on an \"AS IS\" BASIS,       */\n/*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or         */\n/*  implied. See the License for the specific language governing            */\n/*  permissions and limitations under the License.                          */\n/*                                                                          */\n/****************************************************************************/\n\n//#include \"stdafx.h\"\n#include <string>\n#include <fstream>\n#include \"LatLongConversions.h\"\n#include \"..\\GeoFormulas\\Conversions.h\"\n#include \"..\\GeoFormulas\\GeoFormulas.h\"\n#include <boost/regex.hpp>\n\nusing namespace boost;\nusing namespace GeoCalcs;\nusing namespace std;\n\nbool ParseTestPerpIntercept(string sString)\n{\t\n\tbool bPassed = true;\n\tTrimWhitespace(sString);\n\tstring soTestId, soStartLat, soStartLong, soAz, soTestPtLat, soTestPtLong, soAzFromPt, soDistFromPt;\n\tstring soInterceptLat, soInterceptLong;\n\ttry\n\t{\n\t\tregex_constants::syntax_option_type flags =  regex_constants::icase | regex_constants::perl;\n\n\t\tstring sRxPat = \"([a-z]+|[A-Z]+\\\\d+)[,]\";\n\t\tsRxPat += \"([0-9]*[:][0-9]*[:][0-9]*[.][0-9]*[NS])[,]([0-9]*[:][0-9]*[:][0-9]*[.][0-9]*[WE])[,]\";\n\t\tsRxPat += \"([-+]?[0-9]*[].?[0-9]+)[,]\";\n\t\tsRxPat += \"([0-9]*[:][0-9]*[:][0-9]*[.][0-9]*[NS])[,]([0-9]*[:][0-9]*[:][0-9]*[.][0-9]*[WE])[,]\";\n\t\tsRxPat += \"([-+]?[0-9]*[].?[0-9]+)[,]([-+]?[0-9]*[.]?[0-9]+)[,]\";\n\t\tsRxPat += \"([0-9]*[:][0-9]*[:][0-9]*[.][0-9]*[NS])[,]([0-9]*[:][0-9]*[:][0-9]*[.][0-9]*[WE])\";\n\t\tregex pat(sRxPat, flags);\n\n\t\tint const sub_matches[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, };\n\t\tsregex_token_iterator it(sString.begin(), sString.end(), pat, sub_matches);\n\t\tif(it != sregex_token_iterator())\n\t\t{\n\t\t\tsoTestId = *it++;\n\t\t\tsoStartLat = *it++;\n\t\t\tsoStartLong = *it++;\n\t\t\tsoAz = *it++;\n\t\t\tsoTestPtLat = *it++;\n\t\t\tsoTestPtLong = *it++;\n\t\t\tsoAzFromPt = *it++;\n\t\t\tsoDistFromPt = *it++;\n\t\t\tsoInterceptLat = *it++;\n\t\t\tsoInterceptLong = *it++;\n\t\t}\n\t}\n\tcatch(regex_error & e)\n\t{\n\t\tcout << \"\\n\" << e.what();\n\t\treturn false;\n\t}\n\n\tdouble dCalcedCrsFromPt, dCalcedDistFromPt;\n\tLLPoint pt3;\n\n\n\tpt3 = PerpIntercept(LLPoint(Deg2Rad(ParseLatitude(soStartLat)), Deg2Rad(ParseLongitude(soStartLong))),\n\t\tDeg2Rad(atof(soAz.c_str())),\n\t\tLLPoint(Deg2Rad(ParseLatitude(soTestPtLat)), Deg2Rad(ParseLongitude(soTestPtLong))),\n\t\tdCalcedCrsFromPt, dCalcedDistFromPt, Tol());\n\n\tstring sLat = ConvertLatitudeDdToDms(Rad2Deg(pt3.latitude));\n\tstring sLon = ConvertLongitudeDdToDms(Rad2Deg(pt3.longitude));\n\n\tif(sLat.compare(soInterceptLat) != 0)\n\t{\n\t\tcout << \"\\n\" << soTestId << \" failed: Input intercept latitude: \" << soInterceptLat << \"  calced: \" << sLat;\n\t\tbPassed = false;\n\t}\n\n\tif(sLon.compare(soInterceptLong) != 0)\n\t{\n\t\tcout << \"\\n\" << soTestId << \" failed: Input intercept longitude: \" << soInterceptLong << \"  calced: \" << sLon;\n\t\tbPassed = false;\n\t}\n\treturn bPassed;\t\n}\n\n\nint TestPerpIntercept(const string & sFilePath)\n{\n\tifstream infile;\n\tinfile.exceptions(ifstream::eofbit | ifstream::failbit | ifstream::badbit);\n\tint nCount = 0;\n\tint nCommentCount = 0;\n\tbool bPassed = true;\n\ttry\n\t{\n\t\tstring sLine;\n\t\tinfile.open(sFilePath.c_str(), ifstream::in);\n\n\t\twhile(!infile.eof())\n\t\t{\n\t\t\tgetline(infile, sLine);\t\t\t\n\t\t\tif(sLine.at(0) == '#')\n\t\t\t{\n\t\t\t\tnCommentCount++;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif(!ParseTestPerpIntercept(sLine))\n\t\t\t\t\tbPassed = false;\n\t\t\t\tnCount++;\n\t\t\t}\n\t\t}\n\t\tinfile.close();\n\t\treturn bPassed;\n\t}\n\n\tcatch(ifstream::failure e)\n\t{\n\t\tint nError = -99;\n\t\t// Per C++ standards for ifstream::failbit with global function getline\n\t\t// No characters were extracted because the end was prematurely found.Notice\n\t\t// that some eofbit cases will also set failbit.\n\t\t// In this case the end of the file is read and causes both flags to be raised,\n\t\t// so this presumably means all the data has been read correctly.\n\t\tif((infile.rdstate() & ifstream::failbit) && (infile.rdstate() & ifstream::eofbit) != 0)\n\t\t\tnError = bPassed;\n\t\telse if((infile.rdstate() & ifstream::failbit) != 0)\n\t\t\tnError = -1;\n\t\telse if((infile.rdstate() & ifstream::badbit) != 0)\n\t\t\tnError = -2;\n\t\telse if((infile.rdstate() & ifstream::eofbit) != 0)\n\t\t\tnError = -3;\n\t\tif(infile.is_open())\n\t\t\tinfile.close();\n\t\treturn nError;\n\t}\n}", "meta": {"hexsha": "224d264e9556d6bc505bc2faace87ada543cc886", "size": 5179, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "TerpsTest/TestPerpIntercept.cpp", "max_stars_repo_name": "buffetboy2001/GeoFormulas", "max_stars_repo_head_hexsha": "d439b8941a84965d12078fad80307bc66444e46b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "TerpsTest/TestPerpIntercept.cpp", "max_issues_repo_name": "buffetboy2001/GeoFormulas", "max_issues_repo_head_hexsha": "d439b8941a84965d12078fad80307bc66444e46b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TerpsTest/TestPerpIntercept.cpp", "max_forks_repo_name": "buffetboy2001/GeoFormulas", "max_forks_repo_head_hexsha": "d439b8941a84965d12078fad80307bc66444e46b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.8496732026, "max_line_length": 112, "alphanum_fraction": 0.5483684109, "num_tokens": 1489, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.6791787056691697, "lm_q1q2_score": 0.4635895454619339}}
{"text": "#include <iostream>\n#include <vector>\n#include <string>\n#include <memory>\n#include <Eigen/Dense>\n#include \"../include/layer.h\"\n\nusing namespace Eigen;\n\nint main()\n{\n    using std::cout;\n    using std::endl;\n    using std::vector;\n    using std::string;\n    using std::shared_ptr;\n    using std::make_shared;\n    using namespace MyDL;\n\n    int dim = 2;\n    int batch_size = 3;\n\n    // auto pgamma = make_shared<MatrixXd>(1, dim);\n    // auto pbeta  = make_shared<MatrixXd>(1, dim);\n\n    // *pgamma = MatrixXd::Random(1, dim);\n    // *pbeta  = MatrixXd::Random(1, dim);\n\n    // MyDL::BatchNorm batch_norm(pgamma, pbeta);\n\n    BatchNorm batch_norm(dim);\n\n    vector<MatrixXd> inputs, outputs, douts;\n    MatrixXd X = MatrixXd::Random(batch_size, dim);\n    inputs.push_back(X);\n\n    MatrixXd dout = MatrixXd::Random(batch_size, dim);\n    douts.push_back(dout);\n\n    bool train_flg = Config::getInstance().get_flag();\n\n    cout << \"Train Flag: \" << train_flg << endl;\n    cout << \"--- Mode Train ---\" << endl;\n\n    outputs = batch_norm.forward(inputs);\n\n    cout << \"Forward Result: \" << outputs[0] << endl;\n\n    outputs = batch_norm.forward(inputs); // _avg_mean, _avg_var\u3092\u3082\u3046\u4e00\u6bb5\u968e\u5909\u5316\u3055\u305b\u308b\n\n    Config::getInstance().set_flag(false);\n    train_flg = Config::getInstance().get_flag();\n\n    cout << \"Train Flag: \" << train_flg << endl;\n    cout << \"--- Mode Inference ---\" << endl;\n\n    outputs = batch_norm.forward(inputs);\n\n    cout << \"Forward Result: \" << endl;\n    cout << outputs[0] << endl;\n\n\n    Config::getInstance().set_flag(true);\n    train_flg = Config::getInstance().get_flag();\n\n    cout << \"Train Flag: \" << train_flg << endl;\n    cout << \"--- Mode Train ---\" << endl;\n\n    vector<MatrixXd> grads;\n\n    grads = batch_norm.backward(douts);\n    cout << \"Backward Result: \" << endl;;\n    cout << grads[0] << endl;\n\n    return 0;\n}", "meta": {"hexsha": "3a901d770e65c9040041b33ce6e345ffcae7e8f7", "size": 1830, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_batchnorm.cpp", "max_stars_repo_name": "potedo/zeroDL_cpp", "max_stars_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-22T15:26:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-22T15:26:20.000Z", "max_issues_repo_path": "test/test_batchnorm.cpp", "max_issues_repo_name": "potedo/zeroDL_cpp", "max_issues_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_issues_repo_licenses": ["MIT"], "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_batchnorm.cpp", "max_forks_repo_name": "potedo/zeroDL_cpp", "max_forks_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_forks_repo_licenses": ["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.0789473684, "max_line_length": 75, "alphanum_fraction": 0.6153005464, "num_tokens": 489, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.4635895410294525}}
{"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 <Eigen/Core>\n#include <glog/logging.h>\n#include \"gtest/gtest.h\"\n\n#include \"theia/sfm/gps_converter.h\"\n#include \"theia/util/random.h\"\n\nnamespace theia {\n\nTEST(GPSConverter, ECEFToLLA) {\n  static const double kTolerance = 1e-8;\n  const Eigen::Vector3d taj_mahal_lla(27.173891, 78.042068, 168.0);\n  const Eigen::Vector3d ecef(1176498.769459714,\n                             5555043.905503586,\n                             2895446.8901510699);\n  const Eigen::Vector3d lla = GPSConverter::ECEFToLLA(ecef);\n  EXPECT_NEAR(taj_mahal_lla[0], lla[0], kTolerance);\n  EXPECT_NEAR(taj_mahal_lla[1], lla[1], kTolerance);\n  EXPECT_NEAR(taj_mahal_lla[2], lla[2], kTolerance);\n}\n\nTEST(GPSConverter, LLAToECEF) {\n  static const double kTolerance = 1e-8;\n  const Eigen::Vector3d taj_mahal_lla(27.173891, 78.042068, 168.0);\n  const Eigen::Vector3d gt_ecef(1176498.769459714,\n                                5555043.905503586,\n                                2895446.8901510699);\n  const Eigen::Vector3d ecef = GPSConverter::LLAToECEF(taj_mahal_lla);\n  EXPECT_NEAR(gt_ecef[0], ecef[0], kTolerance);\n  EXPECT_NEAR(gt_ecef[1], ecef[1], kTolerance);\n  EXPECT_NEAR(gt_ecef[2], ecef[2], kTolerance);\n}\n\nTEST(GPSConverter, RoundTrip) {\n  RandomNumberGenerator rng(69);\n\n  static const double kTolerance = 1e-8;\n  static const int kNumTrials = 1000;\n  for (int i = 0; i < kNumTrials; i++) {\n    // Use the same random configuration as in the original paper: Olson,\n    // D.K. \"Converting earth-Centered, Earth-Fixed Coordinates to Geodetic\n    // Coordinates,\" IEEE Transactions on Aerospace and Electronic Systems,\n    // Vol. 32, No. 1, January 1996, pp. 473-476.\n    const Eigen::Vector3d gt_lla(rng.RandDouble(-90.0, 90.0),\n                                 rng.RandDouble(-180.0, 180.0),\n                                 rng.RandDouble(-10000, 100000));\n\n    const Eigen::Vector3d ecef = GPSConverter::LLAToECEF(gt_lla);\n    const Eigen::Vector3d lla = GPSConverter::ECEFToLLA(ecef);\n\n    EXPECT_NEAR(gt_lla[0], lla[0], kTolerance);\n    EXPECT_NEAR(gt_lla[1], lla[1], kTolerance);\n    EXPECT_NEAR(gt_lla[2], lla[2], kTolerance);\n  }\n}\n\n}  // namespace theia\n", "meta": {"hexsha": "64746b7f1810de17002bba656afc07aba1a4c39a", "size": 3943, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/sfm/gps_converter_test.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": "src/theia/sfm/gps_converter_test.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": "src/theia/sfm/gps_converter_test.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": 42.8586956522, "max_line_length": 78, "alphanum_fraction": 0.7012427086, "num_tokens": 1058, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.4635895366438769}}
{"text": "// Copyright (C) 2015 National ICT Australia (NICTA)\n// \n// This Source Code Form is subject to the terms of the Mozilla Public\n// License, v. 2.0. If a copy of the MPL was not distributed with this\n// file, You can obtain one at http://mozilla.org/MPL/2.0/.\n// -------------------------------------------------------------------\n// \n// Written by Conrad Sanderson - http://conradsanderson.id.au\n\n\n#include <armadillo>\n#include \"catch.hpp\"\n\nusing namespace arma;\n\n\nTEST_CASE(\"fn_as_scalar_1\")\n  {\n  mat A(1,1); A.fill(2.0);\n  mat B(2,2); B.fill(2.0);\n  \n  REQUIRE( as_scalar(A) == Approx(2.0) );\n  \n  REQUIRE( as_scalar(2+A) == Approx(4.0) );\n  \n  REQUIRE( as_scalar(B(span(0,0), span(0,0))) == Approx(2.0) );\n  \n  REQUIRE_THROWS( as_scalar(B) );\n  }\n\n\n\nTEST_CASE(\"fn_as_scalar_2\")\n  {\n  rowvec r = linspace<rowvec>(1,5,6);\n  colvec q = linspace<colvec>(1,5,6);\n  mat    X = 0.5*toeplitz(q);\n  \n  REQUIRE( as_scalar(r*q) == Approx(65.2) );\n  \n  REQUIRE( as_scalar(r*X*q) == Approx(380.848) );\n  \n  REQUIRE( as_scalar(r*diagmat(X)*q) == Approx(32.6) );\n  REQUIRE( as_scalar(r*inv(diagmat(X))*q) == Approx(130.4) );\n  }\n\n\n\nTEST_CASE(\"fn_as_scalar_3\")\n  {\n  cube A(1,1,1); A.fill(2.0);\n  cube B(2,2,2); B.fill(2.0);\n  \n  REQUIRE( as_scalar(A) == Approx(2.0) );\n  \n  REQUIRE( as_scalar(2+A) == Approx(4.0) );\n  \n  REQUIRE( as_scalar(B(span(0,0), span(0,0), span(0,0))) == Approx(2.0) );\n  \n  REQUIRE_THROWS( as_scalar(B) );\n  }\n", "meta": {"hexsha": "83777b96b3f47c572461c341cc812235a5eba518", "size": 1424, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "jet/thirdparty/armadillo/tests/fn_as_scalar.cpp", "max_stars_repo_name": "benman1/pyjet", "max_stars_repo_head_hexsha": "04b48e9966ed52999c2910b1966d467ee7fbb5bf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 70.0, "max_stars_repo_stars_event_min_datetime": "2016-11-06T15:17:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T14:50:59.000Z", "max_issues_repo_path": "jet/thirdparty/armadillo/tests/fn_as_scalar.cpp", "max_issues_repo_name": "orestis-z/pyjet", "max_issues_repo_head_hexsha": "a922d8702496494c118d2c5239401d8170d10cd6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2017-01-27T12:33:14.000Z", "max_issues_repo_issues_event_max_datetime": "2018-04-19T08:50:40.000Z", "max_forks_repo_path": "jet/thirdparty/armadillo/tests/fn_as_scalar.cpp", "max_forks_repo_name": "orestis-z/pyjet", "max_forks_repo_head_hexsha": "a922d8702496494c118d2c5239401d8170d10cd6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2016-11-08T15:32:54.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-08T11:54:03.000Z", "avg_line_length": 22.9677419355, "max_line_length": 74, "alphanum_fraction": 0.5828651685, "num_tokens": 491, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.463589536596971}}
{"text": "/*******\nedit_distance: STL and Boost compatible edit distance functions for C++\n\nCopyright (c) 2013 Erik Erlandson\n\nAuthor:  Erik Erlandson <erikerlandson@yahoo.com>\n\nDistributed under the Boost Software License, Version 1.0.\nSee accompanying file LICENSE or copy at\nhttp://www.boost.org/LICENSE_1_0.txt\n*******/\n\n#include \"edit_distance_common.hpp\"\n\n#include <iostream>\n#include <boost/algorithm/sequence/edit_distance.hpp>\nusing namespace boost::algorithm::sequence::parameter;\nusing boost::algorithm::sequence::edit_distance;\nusing boost::algorithm::sequence::unit_cost;\n\nint main(int argc, char** argv) {\n    char const* str1 = \"abc\";\n    char const* str2 = \"axc\";\n\n    // Compare two null-terminated strings that differ by one substitution\n    // (distance should be 2)\n    stringstream_tuple_output<unit_cost, char const*> out;\n    unsigned dist = edit_distance(str1, str2, _script = out);\n    std::cout << \"dist= \" << dist << \"   edit operations= \" << out.ss.str() << \"\\n\";\n\n    // Any type of sequences or range adaptors can be \n    // applied as sequence arguments (here distance should be 4: \"abc\" -> \"cxa\" (-a, -b, =c, +x, +a)\n    out.ss.str(\"\");\n    dist = edit_distance(as_vector(str1), as_list(str2) | boost::adaptors::reversed, _script = out);\n    std::cout << \"dist= \" << dist << \"   edit operations= \" << out.ss.str() << \"\\n\";\n\n    return 0;\n}\n", "meta": {"hexsha": "6b9948bd1bb61e987b32216a9998a724a03b3ccf", "size": 1362, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/edit_script_range_example.cpp", "max_stars_repo_name": "libkeiser/edit_distance", "max_stars_repo_head_hexsha": "9a6b3bd2b0b52e503960834da3599bee0dee868d", "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": "example/edit_script_range_example.cpp", "max_issues_repo_name": "libkeiser/edit_distance", "max_issues_repo_head_hexsha": "9a6b3bd2b0b52e503960834da3599bee0dee868d", "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": "example/edit_script_range_example.cpp", "max_forks_repo_name": "libkeiser/edit_distance", "max_forks_repo_head_hexsha": "9a6b3bd2b0b52e503960834da3599bee0dee868d", "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.9230769231, "max_line_length": 100, "alphanum_fraction": 0.6791483113, "num_tokens": 357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737214979746, "lm_q2_score": 0.6791786861878392, "lm_q1q2_score": 0.4635895233933384}}
{"text": "/*\n * Copyright 2014-2019, CNRS\n * Copyright 2018-2019, INRIA\n */\n\n#ifndef __eigenpy_quaternion_hpp__\n#define __eigenpy_quaternion_hpp__\n\n#include \"eigenpy/fwd.hpp\"\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include \"eigenpy/exception.hpp\"\n#include \"eigenpy/registration.hpp\"\n\nnamespace eigenpy\n{\n\n  class ExceptionIndex : public Exception\n  {\n  public:\n    ExceptionIndex(int index,int imin,int imax) : Exception(\"\")\n    {\n      std::ostringstream oss; oss << \"Index \" << index << \" out of range \" << imin << \"..\"<< imax <<\".\";\n      message = oss.str();\n    }\n  };\n\n  namespace bp = boost::python;\n\n  template<typename QuaternionDerived> class QuaternionVisitor;\n  \n  template<typename Scalar, int Options>\n  struct call< Eigen::Quaternion<Scalar,Options> >\n  {\n    typedef Eigen::Quaternion<Scalar,Options> Quaternion;\n    static inline void expose()\n    {\n      QuaternionVisitor<Quaternion>::expose();\n    }\n    \n    static inline bool isApprox(const Quaternion & self, const Quaternion & other,\n                                const Scalar & prec = Eigen::NumTraits<Scalar>::dummy_precision())\n    {\n      return self.isApprox(other,prec);\n    }\n  };\n\n  BOOST_PYTHON_FUNCTION_OVERLOADS(isApproxQuaternion_overload,call<Eigen::Quaterniond>::isApprox,2,3)\n\n  template<typename Quaternion>\n  class QuaternionVisitor\n  :  public bp::def_visitor< QuaternionVisitor<Quaternion> >\n  {\n    typedef Eigen::QuaternionBase<Quaternion> QuaternionBase;\n\n    typedef typename QuaternionBase::Scalar Scalar;\n    typedef typename Quaternion::Coefficients Coefficients;\n    typedef typename QuaternionBase::Vector3 Vector3;\n    typedef typename Eigen::Matrix<Scalar,4,1> Vector4;\n    typedef typename QuaternionBase::Matrix3 Matrix3;\n\n    typedef typename QuaternionBase::AngleAxisType AngleAxis;\n\n  public:\n\n    template<class PyClass>\n    void visit(PyClass& cl) const \n    {\n      cl\n      .def(bp::init<>(\"Default constructor\"))\n      .def(bp::init<Vector4>((bp::arg(\"vec4\")),\n                             \"Initialize from a vector 4D.\\n\"\n                             \"\\tvec4 : a 4D vector representing quaternion coefficients in the order xyzw.\"))\n      .def(bp::init<Matrix3>((bp::arg(\"R\")),\n                             \"Initialize from rotation matrix.\\n\"\n                             \"\\tR : a rotation matrix 3x3.\"))\n      .def(bp::init<AngleAxis>((bp::arg(\"aa\")),\n                               \"Initialize from an angle axis.\\n\"\n                               \"\\taa: angle axis object.\"))\n      .def(bp::init<Quaternion>((bp::arg(\"quat\")),\n                                \"Copy constructor.\\n\"\n                                \"\\tquat: a quaternion.\"))\n      .def(\"__init__\",bp::make_constructor(&QuaternionVisitor::FromTwoVectors,\n                                           bp::default_call_policies(),\n                                           (bp::arg(\"u: a 3D vector\"),bp::arg(\"v: a 3D vector\"))),\n           \"Initialize from two vectors u and v\")\n      .def(bp::init<Scalar,Scalar,Scalar,Scalar>\n           ((bp::arg(\"w\"),bp::arg(\"x\"),bp::arg(\"y\"),bp::arg(\"z\")),\n            \"Initialize from coefficients.\\n\\n\"\n            \"... note:: The order of coefficients is *w*, *x*, *y*, *z*. \"\n            \"The [] operator numbers them differently, 0...4 for *x* *y* *z* *w*!\"))\n      \n      .add_property(\"x\",\n                    &QuaternionVisitor::getCoeff<0>,\n                    &QuaternionVisitor::setCoeff<0>,\"The x coefficient.\")\n      .add_property(\"y\",\n                    &QuaternionVisitor::getCoeff<1>,\n                    &QuaternionVisitor::setCoeff<1>,\"The y coefficient.\")\n      .add_property(\"z\",\n                    &QuaternionVisitor::getCoeff<2>,\n                    &QuaternionVisitor::setCoeff<2>,\"The z coefficient.\")\n      .add_property(\"w\",\n                    &QuaternionVisitor::getCoeff<3>,\n                    &QuaternionVisitor::setCoeff<3>,\"The w coefficient.\")\n      \n      .def(\"isApprox\",\n           &call<Quaternion>::isApprox,\n           isApproxQuaternion_overload(bp::args(\"other\",\"prec\"),\n                                       \"Returns true if *this is approximately equal to other, within the precision determined by prec.\"))\n      \n      /* --- Methods --- */\n      .def(\"coeffs\",(const Vector4 & (Quaternion::*)()const)&Quaternion::coeffs,\n           bp::return_value_policy<bp::copy_const_reference>())\n      .def(\"matrix\",&Quaternion::matrix,\"Returns an equivalent 3x3 rotation matrix. Similar to toRotationMatrix.\")\n      .def(\"toRotationMatrix\",&Quaternion::toRotationMatrix,\"Returns an equivalent 3x3 rotation matrix.\")\n      \n      .def(\"setFromTwoVectors\",&setFromTwoVectors,((bp::arg(\"a\"),bp::arg(\"b\"))),\"Set *this to be the quaternion which transforms a into b through a rotation.\"\n           ,bp::return_self<>())\n      .def(\"conjugate\",&Quaternion::conjugate,\"Returns the conjugated quaternion. The conjugate of a quaternion represents the opposite rotation.\")\n      .def(\"inverse\",&Quaternion::inverse,\"Returns the quaternion describing the inverse rotation.\")\n      .def(\"setIdentity\",&Quaternion::setIdentity,bp::return_self<>(),\"Set *this to the idendity rotation.\")\n      .def(\"norm\",&Quaternion::norm,\"Returns the norm of the quaternion's coefficients.\")\n      .def(\"normalize\",&Quaternion::normalize,\"Normalizes the quaternion *this.\")\n      .def(\"normalized\",&Quaternion::normalized,\"Returns a normalized copy of *this.\")\n      .def(\"squaredNorm\",&Quaternion::squaredNorm,\"Returns the squared norm of the quaternion's coefficients.\")\n      .def(\"dot\",&Quaternion::template dot<Quaternion>,bp::arg(\"other\"),\"Returns the dot product of *this with other\"\n           \"Geometrically speaking, the dot product of two unit quaternions corresponds to the cosine of half the angle between the two rotations.\")\n      .def(\"_transformVector\",&Quaternion::_transformVector,bp::arg(\"vector\"),\"Rotation of a vector by a quaternion.\")\n      .def(\"vec\",&vec,\"Returns a vector expression of the imaginary part (x,y,z).\")\n      .def(\"angularDistance\",&Quaternion::template angularDistance<Quaternion>,\"Returns the angle (in radian) between two rotations.\")\n      .def(\"slerp\",&slerp,bp::args(\"t\",\"other\"),\n           \"Returns the spherical linear interpolation between the two quaternions *this and other at the parameter t in [0;1].\")\n\n      /* --- Operators --- */\n      .def(bp::self * bp::self)\n      .def(bp::self *= bp::self)\n      .def(bp::self * bp::other<Vector3>())\n      .def(\"__eq__\",&QuaternionVisitor::__eq__)\n      .def(\"__ne__\",&QuaternionVisitor::__ne__)\n      .def(\"__abs__\",&Quaternion::norm)\n      .def(\"__len__\",&QuaternionVisitor::__len__).staticmethod(\"__len__\")\n      .def(\"__setitem__\",&QuaternionVisitor::__setitem__)\n      .def(\"__getitem__\",&QuaternionVisitor::__getitem__)\n      .def(\"assign\",&assign<Quaternion>,\n           bp::arg(\"quat\"),\"Set *this from an quaternion quat and returns a reference to *this.\",bp::return_self<>())\n      .def(\"assign\",(Quaternion & (Quaternion::*)(const AngleAxis &))&Quaternion::operator=,\n           bp::arg(\"aa\"),\"Set *this from an angle-axis aa and returns a reference to *this.\",bp::return_self<>())\n      .def(\"__str__\",&print)\n      .def(\"__repr__\",&print)\n      \n//      .def(\"FromTwoVectors\",&Quaternion::template FromTwoVectors<Vector3,Vector3>,\n//           bp::args(\"a\",\"b\"),\n//           \"Returns the quaternion which transform a into b through a rotation.\")\n      .def(\"FromTwoVectors\",&FromTwoVectors,\n           bp::args(\"a\",\"b\"),\n           \"Returns the quaternion which transforms a into b through a rotation.\",\n           bp::return_value_policy<bp::manage_new_object>())\n      .staticmethod(\"FromTwoVectors\")\n      .def(\"Identity\",&Quaternion::Identity,\"Returns a quaternion representing an identity rotation.\")\n      .staticmethod(\"Identity\")\n      ;\n    }\n  private:\n    \n    template<int i>\n    static void setCoeff(Quaternion & self, Scalar value) { self.coeffs()[i] = value; }\n    \n    template<int i>\n    static Scalar getCoeff(Quaternion & self) { return self.coeffs()[i]; }\n    \n    static Quaternion & setFromTwoVectors(Quaternion & self, const Vector3 & a, const Vector3 & b)\n    { return self.setFromTwoVectors(a,b); }\n    \n    template<typename OtherQuat>\n    static Quaternion & assign(Quaternion & self, const OtherQuat & quat)\n    { return self = quat; }\n\n    static Quaternion* FromTwoVectors(const Vector3& u, const Vector3& v)\n    { \n      Quaternion* q(new Quaternion); q->setFromTwoVectors(u,v);\n      return q; \n    }\n  \n    static bool __eq__(const Quaternion & u, const Quaternion & v)\n    {\n      return u.coeffs() == v.coeffs();\n    }\n    \n    static bool __ne__(const Quaternion& u, const Quaternion& v)\n    {\n      return !__eq__(u,v); \n    }\n\n    static Scalar __getitem__(const Quaternion & self, int idx)\n    { \n      if((idx<0) || (idx>=4)) throw eigenpy::ExceptionIndex(idx,0,3);\n      return self.coeffs()[idx];\n    }\n  \n    static void __setitem__(Quaternion& self, int idx, const Scalar value)\n    { \n      if((idx<0) || (idx>=4)) throw eigenpy::ExceptionIndex(idx,0,3);\n      self.coeffs()[idx] = value;\n    }\n\n    static int __len__() {  return 4;  }\n    static Vector3 vec(const Quaternion & self) { return self.vec(); }\n    \n    static std::string print(const Quaternion & self)\n    {\n      std::stringstream ss;\n      ss << \"(x,y,z,w) = \" << self.coeffs().transpose() << std::endl;\n      \n      return ss.str();\n    }\n    \n    static Quaternion slerp(const Quaternion & self, const Scalar t, const Quaternion & other)\n    { return self.slerp(t,other); }\n\n  public:\n\n    static void expose()\n    {\n      bp::class_<Quaternion>(\"Quaternion\",\n                             \"Quaternion representing rotation.\\n\\n\"\n                             \"Supported operations \"\n                             \"('q is a Quaternion, 'v' is a Vector3): \"\n                             \"'q*q' (rotation composition), \"\n                             \"'q*=q', \"\n                             \"'q*v' (rotating 'v' by 'q'), \"\n                             \"'q==q', 'q!=q', 'q[0..3]'.\",\n                             bp::no_init)\n      .def(QuaternionVisitor<Quaternion>())\n      ;\n   \n    }\n\n  };\n\n} // namespace eigenpy\n\n#endif // ifndef __eigenpy_quaternion_hpp__\n", "meta": {"hexsha": "4b5120b4ef6ca169e253a6045de7b6ee81bec2d0", "size": 10208, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/eigenpy/quaternion.hpp", "max_stars_repo_name": "nim65s/eigenpy", "max_stars_repo_head_hexsha": "7c5824948a9ccf16add0de3f8faf65d835cedc9c", "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/eigenpy/quaternion.hpp", "max_issues_repo_name": "nim65s/eigenpy", "max_issues_repo_head_hexsha": "7c5824948a9ccf16add0de3f8faf65d835cedc9c", "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/eigenpy/quaternion.hpp", "max_forks_repo_name": "nim65s/eigenpy", "max_forks_repo_head_hexsha": "7c5824948a9ccf16add0de3f8faf65d835cedc9c", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.6653061224, "max_line_length": 158, "alphanum_fraction": 0.6042319749, "num_tokens": 2389, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6825737214979745, "lm_q2_score": 0.6791786861878392, "lm_q1q2_score": 0.4635895233933383}}
{"text": "/*\n * Copyright 2015 Alex Millane, ASL, ETH Zurich, Switzerland\n * Copyright 2015 Fadri Furrer, ASL, ETH Zurich, Switzerland\n * Copyright 2015 Michael Burri, ASL, ETH Zurich, Switzerland\n * Copyright 2015 Mina Kamel, ASL, ETH Zurich, Switzerland\n * Copyright 2015 Janosch Nikolic, ASL, ETH Zurich, Switzerland\n * Copyright 2015 Markus Achtelik, ASL, ETH Zurich, Switzerland\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 <math.h>\n#include <fstream>\n#include <iostream>\n\n#include <gtest/gtest.h>\n#include <Eigen/Geometry>\n\n#include \"test_helper_library.h\"\n#include \"vicon_estimator.h\"\n\n// Translational trajectory defines\n#define TRANS_TRAJECTORY_PERIOD 10.0\n#define TRANS_TRAJECTORY_AMPLITUDE 1.0\n#define TRANS_TRAJECTORY_DT 0.01\n#define TRANS_TRAJECTORY_FREQ 0.5\n#define TRANS_TRAJECTORY_PHASE_OFFSET_X 0.0\n#define TRANS_TRAJECTORY_PHASE_OFFSET_Y M_PI / 2.0\n#define TRANS_TRAJECTORY_PHASE_OFFSET_Z M_PI / 1.0\n\n// Rotational trajectory defines\n#define ROT_TRAJECTORY_PERIOD 10.0\n#define ROT_TRAJECTORY_AMPLITUDE 1.0 * M_PI\n#define ROT_TRAJECTORY_DT 0.01\n#define ROT_TRAJECTORY_FREQ 0.5\n#define ROT_TRAJECTORY_PHASE_OFFSET_X 0.0\n#define ROT_TRAJECTORY_PHASE_OFFSET_Y M_PI / 2.0\n#define ROT_TRAJECTORY_PHASE_OFFSET_Z M_PI / 1.0\n\n#define POS_ERROR_THRESHOLD 0.01\n#define VEL_ERROR_THRESHOLD 0.1\n\n#define QUAT_ERROR_THRESHOLD 0.005\n#define OMEGA_ERROR_THRESHOLD 1.5\n\n/*\n *  Helper Function Tests\n */\n\n/*TEST(helperFunctions, euler2Quat)\n{\n  //\n  double roll = 1.0/2.0*M_PI ;\n  double pitch = 0.0 ;\n  double yaw = 0.0 ;\n  void euler2quat(double roll, double pitch, double yaw, double* q1, double* q2,\ndouble* q3, double* q4);\n\n\n}*/\n\n/*\n *  Translational Estimator Tests\n */\n\nvoid generateTranslationalTrajectorySinusoidal(const int trajectory_length,\n                                               double position_trajectory[][3],\n                                               double velocity_trajectory[][3],\n                                               double timestamps[]) {\n  // Generating position trajectories\n  for (int i = 0; i < trajectory_length; i++) {\n    position_trajectory[i][0] =\n        TRANS_TRAJECTORY_AMPLITUDE *\n        sin(2 * M_PI * i * TRANS_TRAJECTORY_DT * TRANS_TRAJECTORY_FREQ +\n            TRANS_TRAJECTORY_PHASE_OFFSET_X);\n    position_trajectory[i][1] =\n        TRANS_TRAJECTORY_AMPLITUDE *\n        sin(2 * M_PI * i * TRANS_TRAJECTORY_DT * TRANS_TRAJECTORY_FREQ +\n            TRANS_TRAJECTORY_PHASE_OFFSET_Y);\n    position_trajectory[i][2] =\n        TRANS_TRAJECTORY_AMPLITUDE *\n        sin(2 * M_PI * i * TRANS_TRAJECTORY_DT * TRANS_TRAJECTORY_FREQ +\n            TRANS_TRAJECTORY_PHASE_OFFSET_Z);\n  }\n  // Generating velocity trajectories from algebraic differentiation\n  for (int i = 0; i < trajectory_length; i++) {\n    velocity_trajectory[i][0] =\n        2 * M_PI * TRANS_TRAJECTORY_FREQ *\n        cos(2 * M_PI * i * TRANS_TRAJECTORY_DT * TRANS_TRAJECTORY_FREQ +\n            TRANS_TRAJECTORY_PHASE_OFFSET_X);\n    velocity_trajectory[i][1] =\n        2 * M_PI * TRANS_TRAJECTORY_FREQ *\n        cos(2 * M_PI * i * TRANS_TRAJECTORY_DT * TRANS_TRAJECTORY_FREQ +\n            TRANS_TRAJECTORY_PHASE_OFFSET_Y);\n    velocity_trajectory[i][2] =\n        2 * M_PI * TRANS_TRAJECTORY_FREQ *\n        cos(2 * M_PI * i * TRANS_TRAJECTORY_DT * TRANS_TRAJECTORY_FREQ +\n            TRANS_TRAJECTORY_PHASE_OFFSET_Z);\n  }\n  // Generating the timestamps\n  timestamps[0] = 0.0;\n  for (int i = 1; i < trajectory_length; i++) {\n    timestamps[i] = timestamps[i - 1] + TRANS_TRAJECTORY_DT;\n  }\n}\n\nTEST(translationalEstimator, sinusoidal_clean) {\n  // Creating the estimator\n  vicon_estimator::TranslationalEstimator translational_estimator;\n\n  // Setting the estimator gains\n  vicon_estimator::TranslationalEstimatorParameters\n      translational_estimator_parameters;\n  translational_estimator_parameters.kp_ = 1.0;\n  translational_estimator_parameters.kv_ = 10 * 10.0;\n  translational_estimator.setParameters(translational_estimator_parameters);\n  translational_estimator.reset();\n\n  // Generating the trajectory over which to test the estimator\n  const int trajectory_length =\n      static_cast<int>(TRANS_TRAJECTORY_PERIOD / TRANS_TRAJECTORY_DT) + 1;\n  double position_trajectory[trajectory_length][3];\n  double velocity_trajectory[trajectory_length][3];\n  double timestamps[trajectory_length];\n  generateTranslationalTrajectorySinusoidal(\n      trajectory_length, position_trajectory, velocity_trajectory, timestamps);\n\n  // Looping over trajectory and retrieving estimates\n  double position_trajectory_estimate[trajectory_length][3];\n  double velocity_trajectory_estimate[trajectory_length][3];\n  for (int i = 0; i < trajectory_length; i++) {\n    // Constructing input\n    Eigen::Vector3d input(position_trajectory[i][0], position_trajectory[i][1],\n                          position_trajectory[i][2]);\n    double timestamp = timestamps[i];\n    // Updating the estimate with the measurement\n    translational_estimator.updateEstimate(input, timestamp);\n    // Getting the position and velocity estimates\n    Eigen::Vector3d estimated_position =\n        translational_estimator.getEstimatedPosition();\n    Eigen::Vector3d estimated_velocity =\n        translational_estimator.getEstimatedVelocity();\n    // Moving values to arrays\n    position_trajectory_estimate[i][0] = estimated_position.x();\n    position_trajectory_estimate[i][1] = estimated_position.y();\n    position_trajectory_estimate[i][2] = estimated_position.z();\n    velocity_trajectory_estimate[i][0] = estimated_velocity.x();\n    velocity_trajectory_estimate[i][1] = estimated_velocity.y();\n    velocity_trajectory_estimate[i][2] = estimated_velocity.z();\n  }\n\n  // Start index for error calculation\n  const int start_index = trajectory_length / 2;\n\n  // Calculating position estimate errors\n  double position_error[3];\n  calculate3dRmsError(position_trajectory, position_trajectory_estimate,\n                      trajectory_length, start_index, position_error);\n\n  // Performing test\n  EXPECT_NEAR(position_error[0], 0, POS_ERROR_THRESHOLD)\n      << \"X position estimate error too great\";\n  EXPECT_NEAR(position_error[1], 0, POS_ERROR_THRESHOLD)\n      << \"Y position estimate error too great\";\n  EXPECT_NEAR(position_error[2], 0, POS_ERROR_THRESHOLD)\n      << \"Z position estimate error too great\";\n\n  // Calculating velocity estimate errors\n  double velocity_error[3];\n  calculate3dRmsError(velocity_trajectory, velocity_trajectory_estimate,\n                      trajectory_length, start_index, velocity_error);\n\n  // Performing test\n  EXPECT_NEAR(velocity_error[0], 0, VEL_ERROR_THRESHOLD)\n      << \"X velocity estimate error too great\";\n  EXPECT_NEAR(velocity_error[1], 0, VEL_ERROR_THRESHOLD)\n      << \"Y velocity estimate error too great\";\n  EXPECT_NEAR(velocity_error[2], 0, VEL_ERROR_THRESHOLD)\n      << \"Z velocity estimate error too great\";\n\n  /*\n   *  For matlab debug\n   */\n\n  /*  // Opening a file for trajectories debug data\n    std::ofstream trajectoriesFile;\n    trajectoriesFile.open(\"translationalTrajectories.txt\");\n    // Writing the data to file\n    for (int i = 0; i < trajectoryLength; i++)\n    {\n      trajectoriesFile << posTrajectory[i][0] << \", \" << posTrajectory[i][1] <<\n    \", \" << posTrajectory[i][2] << \", \";\n      trajectoriesFile << posEstTrajectory[i][0] << \", \" <<\n    posEstTrajectory[i][1] << \", \" << posEstTrajectory[i][2] << \", \";\n      trajectoriesFile << velTrajectory[i][0] << \", \" << velTrajectory[i][1] <<\n    \", \" << velTrajectory[i][2] << \", \";\n      trajectoriesFile << velEstTrajectory[i][0] << \", \" <<\n    velEstTrajectory[i][1] << \", \" << velEstTrajectory[i][2];\n      trajectoriesFile << std::endl;\n    }\n    // Closing file\n    trajectoriesFile.close();\n\n    // Opening a file for errors debug data\n    std::ofstream errorsFile;\n    errorsFile.open(\"translationalErrors.txt\");\n    // Writing the data to file\n    errorsFile << posError[0] << \", \" << posError[1] << \", \" << posError[2] <<\n    std::endl;\n    errorsFile << velError[0] << \", \" << velError[1] << \", \" << velError[2] <<\n    std::endl;\n    // Closing file\n    errorsFile.close();*/\n}\n\n/*\n *  Rotational Estimator Tests\n */\n\nvoid generateRotationalTrajectorySinusoidal(const int trajectory_length,\n                                            double orientation_trajectory[][4],\n                                            double rollrate_trajectory[][3],\n                                            double timestamps[]) {\n  // Generating quaternion trajectories\n  double roll, pitch, yaw;\n  for (int i = 0; i < trajectory_length; i++) {\n    // Generating euler angles\n    roll = ROT_TRAJECTORY_AMPLITUDE *\n           sin(2 * M_PI * i * ROT_TRAJECTORY_DT * ROT_TRAJECTORY_FREQ +\n               ROT_TRAJECTORY_PHASE_OFFSET_X);\n    pitch = ROT_TRAJECTORY_AMPLITUDE *\n            sin(2 * M_PI * i * ROT_TRAJECTORY_DT * ROT_TRAJECTORY_FREQ +\n                ROT_TRAJECTORY_PHASE_OFFSET_Y);\n    yaw = ROT_TRAJECTORY_AMPLITUDE *\n          sin(2 * M_PI * i * ROT_TRAJECTORY_DT * ROT_TRAJECTORY_FREQ +\n              ROT_TRAJECTORY_PHASE_OFFSET_Z);\n    // Converting to quaternions\n    euler2quat(roll, pitch, yaw, orientation_trajectory[i]);\n  }\n\n  // Generating the omega trajectories through numeric differentiation\n  Eigen::Quaterniond q_k, q_k_1;\n  for (int i = 0; i < trajectory_length - 1; i++) {\n    // Generating quaternions\n    q_k = Eigen::Quaterniond(\n        orientation_trajectory[i + 1][0], orientation_trajectory[i + 1][1],\n        orientation_trajectory[i + 1][2], orientation_trajectory[i + 1][3]);\n    q_k_1 = Eigen::Quaterniond(\n        orientation_trajectory[i][0], orientation_trajectory[i][1],\n        orientation_trajectory[i][2], orientation_trajectory[i][3]);\n    // Calculating quaternion derivative\n    Eigen::Quaterniond diff =\n        Eigen::Quaterniond((q_k.coeffs() - q_k_1.coeffs()) / ROT_TRAJECTORY_DT);\n    Eigen::Quaterniond omega =\n        Eigen::Quaterniond(2 * (q_k_1.inverse() * diff).coeffs());\n    // Writing to the trajectory\n    rollrate_trajectory[i][0] = omega.x();\n    rollrate_trajectory[i][1] = omega.y();\n    rollrate_trajectory[i][2] = omega.z();\n  }\n\n  // Generating the timestamps\n  timestamps[0] = 0.0;\n  for (int i = 1; i < trajectory_length; i++) {\n    timestamps[i] = timestamps[i - 1] + TRANS_TRAJECTORY_DT;\n  }\n}\n\nTEST(rotationalEstimator, sinusoidal_clean) {\n  // Creating the estimator\n  vicon_estimator::RotationalEstimator rotational_estimator;\n\n  // Setting the estimator gains\n  vicon_estimator::RotationalEstimatorParameters\n      rotational_estimator_parameters;\n  rotational_estimator_parameters.dorientation_estimate_initial_covariance_ = 1;\n  rotational_estimator_parameters.drate_estimate_initial_covariance_ = 1;\n  rotational_estimator_parameters.dorientation_process_covariance_ = 0.01;\n  rotational_estimator_parameters.drate_process_covariance_ = 1000 * 1;\n  rotational_estimator_parameters.orientation_measurement_covariance_ = 0.0005;\n  rotational_estimator.setParameters(rotational_estimator_parameters);\n  rotational_estimator.reset();\n\n  // Generating the trajectory over which to test the estimator\n  const int trajectory_length =\n      static_cast<int>(ROT_TRAJECTORY_PERIOD / ROT_TRAJECTORY_DT) + 1;\n  double orientation_trajectory[trajectory_length][4];\n  double omega_trajectory[trajectory_length][3];\n  double timestamps[trajectory_length];\n  generateRotationalTrajectorySinusoidal(\n      trajectory_length, orientation_trajectory, omega_trajectory, timestamps);\n\n  // Looping over trajectory and retrieving estimates\n  double orientation_estimate_trajectory[trajectory_length][4];\n  double rollrate_estimate_trajectory[trajectory_length][3];\n  for (int i = 0; i < trajectory_length; i++) {\n    // Constructing input\n    Eigen::Quaterniond input(\n        orientation_trajectory[i][0], orientation_trajectory[i][1],\n        orientation_trajectory[i][2], orientation_trajectory[i][3]);\n    // Updating the estimate with the measurement\n    double timestamp = timestamps[i];\n    rotational_estimator.updateEstimate(input, timestamp);\n    // Getting the position and velocity estimates\n    Eigen::Quaterniond estimated_orientation =\n        rotational_estimator.getEstimatedOrientation();\n    Eigen::Vector3d estimated_rollrate =\n        rotational_estimator.getEstimatedRate();\n    // Moving values to arrays\n    orientation_estimate_trajectory[i][0] = estimated_orientation.w();\n    orientation_estimate_trajectory[i][1] = estimated_orientation.x();\n    orientation_estimate_trajectory[i][2] = estimated_orientation.y();\n    orientation_estimate_trajectory[i][3] = estimated_orientation.z();\n    rollrate_estimate_trajectory[i][0] = estimated_rollrate.x();\n    rollrate_estimate_trajectory[i][1] = estimated_rollrate.y();\n    rollrate_estimate_trajectory[i][2] = estimated_rollrate.z();\n  }\n\n  // Start index for error calculation\n  const int start_index = trajectory_length / 2;\n\n  // Calculating position estimate errors\n  double orientation_error[3];\n  calculateQuaternionRmsError(\n      orientation_trajectory, orientation_estimate_trajectory,\n      trajectory_length, start_index, orientation_error);\n\n  // Performing test\n  EXPECT_NEAR(orientation_error[0], 0, QUAT_ERROR_THRESHOLD)\n      << \"X errorquaternion estimate error too great\";\n  EXPECT_NEAR(orientation_error[1], 0, QUAT_ERROR_THRESHOLD)\n      << \"Y errorquaternion estimate error too great\";\n  EXPECT_NEAR(orientation_error[2], 0, QUAT_ERROR_THRESHOLD)\n      << \"Z errorquaternion estimate error too great\";\n\n  // Calculating velocity estimate errors\n  double omegaError[3];\n  calculate3dRmsError(omega_trajectory, rollrate_estimate_trajectory,\n                      trajectory_length, start_index, omegaError);\n\n  // Performing test\n  EXPECT_NEAR(omegaError[0], 0, OMEGA_ERROR_THRESHOLD)\n      << \"X rotational velocity estimate error too great\";\n  EXPECT_NEAR(omegaError[1], 0, OMEGA_ERROR_THRESHOLD)\n      << \"Y rotational velocity estimate error too great\";\n  EXPECT_NEAR(omegaError[2], 0, OMEGA_ERROR_THRESHOLD)\n      << \"Z rotational velocity estimate error too great\";\n\n  /*\n   *  For matlab debug\n   */\n\n  /*  // Opening a file for trajectories debug data\n    std::ofstream trajectoriesFile;\n    trajectoriesFile.open(\"rotationalTrajectories.txt\");\n    // Writing the data to file\n    for (int i = 0; i < trajectoryLength; i++)\n    {\n      trajectoriesFile << quatTrajectory[i][0] << \", \" << quatTrajectory[i][1]\n    << \", \" << quatTrajectory[i][2] << \", \" << quatTrajectory[i][3] << \", \";\n      trajectoriesFile << quatEstTrajectory[i][0] << \", \" <<\n    quatEstTrajectory[i][1] << \", \" << quatEstTrajectory[i][2] << \", \" <<\n    quatEstTrajectory[i][3] << \", \";\n      trajectoriesFile << omegaTrajectory[i][0] << \", \" << omegaTrajectory[i][1]\n    << \", \" << omegaTrajectory[i][2] << \", \";\n      trajectoriesFile << omegaEstTrajectory[i][0] << \", \" <<\n    omegaEstTrajectory[i][1] << \", \" << omegaEstTrajectory[i][2];\n      trajectoriesFile << std::endl;\n    }\n    // Closing file\n    trajectoriesFile.close();\n\n    // Opening a file for errors debug data\n    std::ofstream errorsFile;\n    errorsFile.open(\"rotationalErrors.txt\");\n    // Writing the data to file\n    errorsFile << quatError[0] << \", \" << quatError[1] << \", \" << quatError[2]\n    << std::endl;\n    errorsFile << omegaError[0] << \", \" << omegaError[1] << \", \" <<\n    omegaError[2] << std::endl;\n    // Closing file\n    errorsFile.close();*/\n}\n\n// Quaternions representing flips in various dimensions\nconst int kNumberOfInversions = 7;\nconst Eigen::Quaterniond rotation_inversion_x =\n    Eigen::Quaterniond(Eigen::AngleAxisd(M_PI, Eigen::Vector3d::UnitX()));\nconst Eigen::Quaterniond rotation_inversion_y =\n    Eigen::Quaterniond(Eigen::AngleAxisd(M_PI, Eigen::Vector3d::UnitY()));\nconst Eigen::Quaterniond rotation_inversion_z =\n    Eigen::Quaterniond(Eigen::AngleAxisd(M_PI, Eigen::Vector3d::UnitZ()));\nconst Eigen::Quaterniond rotation_inversion_xy =\n    rotation_inversion_x * rotation_inversion_y;\nconst Eigen::Quaterniond rotation_inversion_yz =\n    rotation_inversion_y * rotation_inversion_z;\nconst Eigen::Quaterniond rotation_inversion_xz =\n    rotation_inversion_x * rotation_inversion_z;\nconst Eigen::Quaterniond rotation_inversion_xyz =\n    rotation_inversion_x * rotation_inversion_y * rotation_inversion_z;\nconst Eigen::Quaterniond rotation_inversions[kNumberOfInversions] = {\n    rotation_inversion_x,  rotation_inversion_y,  rotation_inversion_z,\n    rotation_inversion_xy, rotation_inversion_yz, rotation_inversion_xz,\n    rotation_inversion_xyz};\n\nvoid generateCorruptedInputTrajectory(\n    const Eigen::Quaterniond clean_trajectory[], const int trajectory_length,\n    const int corruption_rate, Eigen::Quaterniond corrupted_trajectory[]) {\n  // Looping over the clean input trajecty and corruputing measurements at a\n  // rate determined by corruption_rate\n  // Note that corruption starts only after corruption_rate samples.\n  int inversion_index = 0;\n  for (int i = corruption_rate; i <= trajectory_length; i += corruption_rate) {\n    // Corrupting the measurement with an inversion from the inversion list\n    corrupted_trajectory[i] =\n        rotation_inversions[inversion_index] * clean_trajectory[i];\n    // corrupted_trajectory[i] = clean_trajectory[i];\n    // Incrementing the inversion\n    inversion_index = (inversion_index + 1) % kNumberOfInversions;\n  }\n}\n\nTEST(rotationalEstimator, sinusoidal_corrupted) {\n  // Creating the estimator\n  vicon_estimator::RotationalEstimator rotational_estimator;\n\n  // Setting the estimator gains\n  vicon_estimator::RotationalEstimatorParameters\n      rotational_estimator_parameters;\n  rotational_estimator_parameters.dorientation_estimate_initial_covariance_ = 1;\n  rotational_estimator_parameters.drate_estimate_initial_covariance_ = 1;\n  rotational_estimator_parameters.dorientation_process_covariance_ = 0.01;\n  rotational_estimator_parameters.drate_process_covariance_ = 1000 * 1;\n  rotational_estimator_parameters.orientation_measurement_covariance_ = 0.0005;\n  rotational_estimator.setParameters(rotational_estimator_parameters);\n  rotational_estimator.reset();\n\n  // Generating the trajectory over which to test the estimator\n  const int trajectory_length =\n      static_cast<int>(ROT_TRAJECTORY_PERIOD / ROT_TRAJECTORY_DT) + 1;\n  double orientation_trajectory[trajectory_length][4];\n  double omega_trajectory[trajectory_length][3];\n  double timestamps[trajectory_length];\n  generateRotationalTrajectorySinusoidal(\n      trajectory_length, orientation_trajectory, omega_trajectory, timestamps);\n\n  // Constructing the measurement vector\n  Eigen::Quaterniond clean_input_trajectory[trajectory_length];\n  Eigen::Quaterniond corrupted_input_trajectory[trajectory_length];\n  // Creating the clean measurement vector\n  for (int i = 0; i < trajectory_length; i++) {\n    clean_input_trajectory[i] = Eigen::Quaterniond(\n        orientation_trajectory[i][0], orientation_trajectory[i][1],\n        orientation_trajectory[i][2], orientation_trajectory[i][3]);\n    corrupted_input_trajectory[i] = Eigen::Quaterniond(\n        orientation_trajectory[i][0], orientation_trajectory[i][1],\n        orientation_trajectory[i][2], orientation_trajectory[i][3]);\n  }\n  // Corrupting the measurement vector\n  int corruption_rate = 100;  // TODO(millanea): Parameter above.\n  generateCorruptedInputTrajectory(clean_input_trajectory, trajectory_length,\n                                   corruption_rate, corrupted_input_trajectory);\n\n  // Looping over trajectory and retrieving estimates\n  double orientation_estimate_trajectory[trajectory_length][4];\n  double rollrate_estimate_trajectory[trajectory_length][3];\n  for (int i = 0; i < trajectory_length; i++) {\n    // Updating the estimate with the measurement\n    rotational_estimator.updateEstimate(corrupted_input_trajectory[i],\n                                        timestamps[i]);\n    // Getting the position and velocity estimates\n    Eigen::Quaterniond estimated_orientation =\n        rotational_estimator.getEstimatedOrientation();\n    Eigen::Vector3d estimated_rollrate =\n        rotational_estimator.getEstimatedRate();\n    // Moving values to arrays\n    orientation_estimate_trajectory[i][0] = estimated_orientation.w();\n    orientation_estimate_trajectory[i][1] = estimated_orientation.x();\n    orientation_estimate_trajectory[i][2] = estimated_orientation.y();\n    orientation_estimate_trajectory[i][3] = estimated_orientation.z();\n    rollrate_estimate_trajectory[i][0] = estimated_rollrate.x();\n    rollrate_estimate_trajectory[i][1] = estimated_rollrate.y();\n    rollrate_estimate_trajectory[i][2] = estimated_rollrate.z();\n  }\n\n  // Start index for error calculation\n  const int start_index = trajectory_length / 2;\n\n  // Calculating position estimate errors\n  double orientation_error[3];\n  calculateQuaternionRmsError(\n      orientation_trajectory, orientation_estimate_trajectory,\n      trajectory_length, start_index, orientation_error);\n\n  // Performing test\n  EXPECT_NEAR(orientation_error[0], 0, QUAT_ERROR_THRESHOLD)\n      << \"X errorquaternion estimate error too great\";\n  EXPECT_NEAR(orientation_error[1], 0, QUAT_ERROR_THRESHOLD)\n      << \"Y errorquaternion estimate error too great\";\n  EXPECT_NEAR(orientation_error[2], 0, QUAT_ERROR_THRESHOLD)\n      << \"Z errorquaternion estimate error too great\";\n\n  // Calculating velocity estimate errors\n  double omegaError[3];\n  calculate3dRmsError(omega_trajectory, rollrate_estimate_trajectory,\n                      trajectory_length, start_index, omegaError);\n\n  // Performing test\n  EXPECT_NEAR(omegaError[0], 0, OMEGA_ERROR_THRESHOLD)\n      << \"X rotational velocity estimate error too great\";\n  EXPECT_NEAR(omegaError[1], 0, OMEGA_ERROR_THRESHOLD)\n      << \"Y rotational velocity estimate error too great\";\n  EXPECT_NEAR(omegaError[2], 0, OMEGA_ERROR_THRESHOLD)\n      << \"Z rotational velocity estimate error too great\";\n}\n\n/*\n *  GTests Main\n */\n\nint main(int argc, char **argv) {\n  testing::InitGoogleTest(&argc, argv);\n  return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "1d4b548fd176dfe562f3a11e6f8cdb4caa55e8c3", "size": 22454, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/test_vicon_estimator.cpp", "max_stars_repo_name": "princeward/ros_vrpn_client", "max_stars_repo_head_hexsha": "53fd0e532526366adc472def24b8de55dc6e34a3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-07-25T14:13:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-13T13:55:13.000Z", "max_issues_repo_path": "src/test/test_vicon_estimator.cpp", "max_issues_repo_name": "princeward/ros_vrpn_client", "max_issues_repo_head_hexsha": "53fd0e532526366adc472def24b8de55dc6e34a3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 42.0, "max_issues_repo_issues_event_min_datetime": "2015-09-04T22:24:12.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-05T08:33:21.000Z", "max_forks_repo_path": "src/test/test_vicon_estimator.cpp", "max_forks_repo_name": "princeward/ros_vrpn_client", "max_forks_repo_head_hexsha": "53fd0e532526366adc472def24b8de55dc6e34a3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2015-10-12T07:56:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-10T14:35:53.000Z", "avg_line_length": 41.9700934579, "max_line_length": 80, "alphanum_fraction": 0.7211632671, "num_tokens": 5202, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737214979745, "lm_q2_score": 0.6791786861878392, "lm_q1q2_score": 0.4635895233933383}}
{"text": "\n#include <cmath>\n#include <boost/foreach.hpp>\n#include <boost/unordered_map.hpp>\n\n#include \"fastmath.hpp\"\n#include \"nlopt/nlopt.h\"\n#include \"tpbias.hpp\"\n\n\ntypedef std::pair<pos_t, pos_t> TPDistPair;\ntypedef boost::unordered_map<pos_t, double> DistNormMap;\n\n\nstatic double geometric_cdf_upper(double p, unsigned int k)\n{\n    return std::pow(1 - p, k);\n}\n\n\nstatic double geometric_logcdf_upper(double p, unsigned int k)\n{\n    return k * fastlog(1 - p);\n}\n\n\nstatic double tpbias_loglikelihood(double lp,\n                                   pos_t maxtlen,\n                                   DistNormMap& distnorm,\n                                   const std::vector<TPDistPair>& xs)\n{\n    double p = exp(lp);\n    double norm = 0.0;\n    double ppower = 1.0;\n    for (pos_t tlen = 0; tlen <= maxtlen; ++tlen) {\n        ppower *= 1 - p;\n        norm += ppower;\n\n        DistNormMap::iterator i = distnorm.find(tlen);\n        if (i != distnorm.end()) {\n            i->second = fastlog(norm);\n        }\n    }\n\n    double ll = 0.0;\n    BOOST_FOREACH (const TPDistPair& x, xs)  {\n        ll += geometric_logcdf_upper(p, x.first) - distnorm[x.second];\n    }\n\n    return ll;\n}\n\n\nstruct TPBiasTrainData\n{\n    TPBiasTrainData(pos_t maxtlen,\n                    DistNormMap& distnorm,\n                    const std::vector<TPDistPair>& xs)\n        : maxtlen(maxtlen)\n        , distnorm(distnorm)\n        , xs(xs)\n    {\n    }\n\n    pos_t maxtlen;\n    DistNormMap& distnorm;\n    const std::vector<TPDistPair>& xs;\n};\n\n\nstatic double tpbias_nlopt_objective(unsigned int _n, const double* _x,\n                                     double* _grad, void* data)\n{\n    UNUSED(_n);\n    UNUSED(_grad);\n\n    TPBiasTrainData* traindata =\n        reinterpret_cast<TPBiasTrainData*>(data);\n\n    return tpbias_loglikelihood(_x[0], traindata->maxtlen,\n                                traindata->distnorm, traindata->xs);\n}\n\n\nTPBias::TPBias(const std::vector<std::pair<pos_t, pos_t> >& tpdists)\n{\n    // normalizing constants for fragment disributions given tlen\n    boost::unordered_map<pos_t, double> distnorm;\n\n    pos_t maxtlen = 0;\n    BOOST_FOREACH (const TPDistPair& tpdist_tlen, tpdists) {\n        distnorm[tpdist_tlen.second] = 0.0;\n        maxtlen = std::max<pos_t>(maxtlen, tpdist_tlen.second);\n    }\n\n    TPBiasTrainData traindata(maxtlen, distnorm, tpdists);\n\n#if 0\n    FILE* out = fopen(\"tpdists.tsv\", \"w\");\n    fprintf(out, \"pos\\ttlen\\n\");\n    BOOST_FOREACH (const TPDistPair& x, tpdists)  {\n        fprintf(out, \"%ld\\t%ld\\n\", x.first, x.second);\n    }\n    fclose(out);\n#endif\n\n    nlopt_opt opt = nlopt_create(NLOPT_LN_SBPLX, 1);\n    double lower_limit = -100;\n    double upper_limit = -10.0;\n    nlopt_set_lower_bounds(opt, &lower_limit);\n    nlopt_set_upper_bounds(opt, &upper_limit);\n    nlopt_set_max_objective(opt, tpbias_nlopt_objective,\n                            reinterpret_cast<void*>(&traindata));\n    //nlopt_set_ftol_abs(opt, 1e-4);\n\n    double xtol_abs = 1e-3;\n    nlopt_set_xtol_abs(opt, &xtol_abs);\n\n    p = -12;\n    double maxf;\n    nlopt_result result = nlopt_optimize(opt, &p, &maxf);\n    if (result < 0) {\n        Logger::warn(\"Failed to fit 3' bias model.\");\n        p = 0.0;\n    }\n\n    p = exp(p);\n\n    nlopt_destroy(opt);\n}\n\n\ndouble TPBias::get_bias(pos_t k)\n{\n    return geometric_cdf_upper(p, k);\n}\n\n\n", "meta": {"hexsha": "028d58d7bb70ca949d005eca4dfcc5c3e98dcb00", "size": 3308, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tpbias.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/tpbias.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/tpbias.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": 23.7985611511, "max_line_length": 71, "alphanum_fraction": 0.6021765417, "num_tokens": 952, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672043084051, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.46357070688224755}}
{"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 <boost/math/tools/roots.hpp>\n\n#include \"NOpenMeshType.hpp\"\n//#include \"NOpenMeshDesc.hpp\"\n#include \"NOpenMeshBisect.hpp\"\n\n\ntemplate <typename T>\nNOpenMeshBisect<T>::NOpenMeshBisect( const SDF& sdf, const P& a, const P& b , float tolerance ) \n    :\n    func(sdf, a, b ),\n    tol(tolerance), \n    invalid( func(0)*func(1) > 0 ),  // <-- sdf must have different signs at a and b : ie bracket zero\n    degenerate( fabs(func(0)) < tolerance && fabs(func(1)) <  tolerance ),  // <-- no root to find, already there \n    iterations(15)\n{\n}\n\n\ntemplate <typename T>\nvoid NOpenMeshBisect<T>::bisect( P& frontier, float& t ) \n{\n    std::pair<float, float> root = boost::math::tools::bisect(func, 0.f, 1.f, tol, iterations );\n    \n    t = (root.first + root.second)/2. ; \n\n    func.position(frontier, t );\n}\n\n\ntemplate <typename T>\nNOpenMeshBisectFunc<T>::NOpenMeshBisectFunc( const SDF& sdf, const P& a, const P& b ) \n    :\n    sdf(sdf),\n    a(a),\n    b(b)\n{\n}\ntemplate <typename T>\nvoid NOpenMeshBisectFunc<T>::position(P& tp, const float t) const \n{\n    // parameterized position along a -> b line segment \n    //    a(1-t)+t*b   t=0 -> a,   t=1 -> b \n\n    const float s = 1.f - t ; \n    tp[0] = a[0]*s + b[0]*t ;\n    tp[1] = a[1]*s + b[1]*t ;\n    tp[2] = a[2]*s + b[2]*t ;\n} \n\ntemplate <typename T>\nfloat NOpenMeshBisectFunc<T>::operator()(const float t) const \n{\n    // signed distance to CSG left/right/composite object from position on line segement\n    P tp ; \n    position(tp, t );\n\n    float d = sdf( tp[0], tp[1], tp[2] ) ;\n\n/*\n    std::cout << \"NOpenMeshBisectFunc<T>\"\n              << \" t \" << t \n              << \" tp \" << NOpenMeshDesc<T>::desc_point(tp,8,2)\n              << \" d \" << d \n              << std::endl ; \n*/\n\n    return d ; \n}\n\n\ntemplate struct NOpenMeshBisectFunc<NOpenMeshType> ;\ntemplate struct NOpenMeshBisect<NOpenMeshType> ;\n\n", "meta": {"hexsha": "7a9dfbd92a0efba7a650d06a74dc613114bb6dd9", "size": 2592, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "npy/NOpenMeshBisect.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/NOpenMeshBisect.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/NOpenMeshBisect.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": 27.2842105263, "max_line_length": 114, "alphanum_fraction": 0.6284722222, "num_tokens": 775, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.808067204308405, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4635707068822475}}
{"text": "#include \"shendk/files/image/pvr/vector_quantizer.h\"\n\n#include <cstring>\n#include <algorithm>\n#include <limits>\n\n#include <Eigen/Dense>\n\n#include \"shendk/utils/math.h\"\n#include \"shendk/files/image/pvr/twiddle.h\"\n\nnamespace shendk {\nnamespace pvr {\n\nstruct VQBlock {\n\n    VQBlock()\n        : pixels(Eigen::MatrixXf(4, 4))\n    {}\n\n    VQBlock(uint8_t blockSize, uint8_t pixelSize)\n        : pixels(Eigen::MatrixXf(blockSize, pixelSize))\n    {}\n\n    inline void zero() {\n        pixels = pixels.Zero(pixels.rows(), pixels.cols());\n    }\n\n    inline void add(VQBlock& block) {\n        pixels += block.pixels;\n    }\n\n    inline void div(int group) {\n        pixels /= group;\n    }\n\n    inline float distance(const VQBlock& block) const {\n        return std::abs((pixels - block.pixels).sum());\n    }\n\n    uint8_t* toArrayTwiddled() {\n        // TODO: only works with RGBA blocks\n        uint8_t* array = new uint8_t[pixels.rows() * 4];\n        uint64_t destinationIndex = 0;\n        int64_t sourceIndex = 0;\n        uint64_t* twiddleMap = createTwiddleMap(pixels.rows());\n        uint32_t blockHeight, blockWidth;\n        blockHeight = blockWidth = pixels.rows() / 2;\n        for (uint32_t y = 0; y < blockHeight; y++) {\n            for (uint32_t x = 0; x < blockWidth; x++) {\n                destinationIndex = (twiddleMap[x] << 1) | twiddleMap[y];\n                array[destinationIndex * 4]     = static_cast<uint8_t>(pixels(sourceIndex));\n                array[destinationIndex * 4 + 1] = static_cast<uint8_t>(pixels(sourceIndex + 1));\n                array[destinationIndex * 4 + 2] = static_cast<uint8_t>(pixels(sourceIndex + 2));\n                array[destinationIndex * 4 + 3] = static_cast<uint8_t>(pixels(sourceIndex + 3));\n                sourceIndex += 4;\n            }\n        }\n        delete[] twiddleMap;\n        return array;\n    }\n\n    uint8_t* toArray() {\n        Eigen::Matrix<uint8_t, Eigen::Dynamic, Eigen::Dynamic> matrix = pixels.cast<uint8_t>();\n        uint8_t* array = new uint8_t(pixels.size());\n        memcpy(array, matrix.data(), pixels.size());\n        return array;\n        return nullptr;\n    }\n\n    uint32_t group = 0;\n    Eigen::MatrixXf pixels;\n};\n\nint nearest(const VQBlock& block, VQBlock* cluster, int clusterSize, double& nearestDistance) {\n    int i = 0;\n    int nearestIndex = 0;\n    double distance = 0;\n    double minDistance = 0;\n    for (i = 0; i < clusterSize; i++) {\n        minDistance = std::numeric_limits<double>::infinity();\n        nearestIndex = block.group;\n        for (i = 0; i < clusterSize; i++) {\n            if (minDistance > (distance = cluster[i].distance(block))) {\n                minDistance = distance;\n                nearestIndex = i;\n            }\n        }\n    }\n    nearestDistance = minDistance;\n    return nearestIndex;\n}\n\nstd::vector<VQBlock> createBlocks(Image& image, int blockWidth, int blockHeight) {\n    //Convert bitmap to blocks\n    int width = image.width() / blockWidth;\n    int height = image.height() / blockHeight;\n    int blockSize = blockWidth * blockHeight * 4;\n    int blockCount = width * height;\n    std::vector<VQBlock> blocks(blockCount);\n\n    for (int y = 0; y < height - 1; y += blockHeight) {\n        for (int x = 0; x < width - 1; x += blockWidth) {\n            int blockIndex = (y / blockHeight) * width + (x / blockWidth);\n            blocks[blockIndex] = VQBlock(blockWidth * blockHeight, 4);\n            for (int k = 0; k < blockHeight; k++) {\n                for (int l = 0; l < blockWidth; l++) {\n                    int imageIndex = ((y + k) * width + (x + l)) * 4;\n                    int subVectorIndex = k * blockWidth + l;\n                    blocks[blockIndex].pixels(subVectorIndex * 4)     = image[imageIndex].b;\n                    blocks[blockIndex].pixels(subVectorIndex * 4 + 1) = image[imageIndex].g;\n                    blocks[blockIndex].pixels(subVectorIndex * 4 + 2) = image[imageIndex].r;\n                    blocks[blockIndex].pixels(subVectorIndex * 4 + 3) = image[imageIndex].a;\n                }\n            }\n        }\n    }\n    return blocks;\n}\n\nstd::vector<VQBlock> initializeCodeBook(std::vector<VQBlock> imageBlocks, int codeBookSize, bool fastInitialization) {\n    std::vector<VQBlock> codeBook(codeBookSize);\n    if (fastInitialization) {\n        int i = 0;\n        for (i = 0; i < codeBookSize; i++)\n        {\n            codeBook[i % codeBookSize] = VQBlock(imageBlocks[i]);\n        }\n        for (i = 0; i < imageBlocks.size(); i++)\n        {\n            imageBlocks[i].group = i % codeBookSize;\n        }\n        return codeBook;\n    } else {\n        int i = 0;\n        int imageLength = imageBlocks.size();\n        double sum = 0.0;\n        double* distances = new double[imageBlocks.size()];\n        codeBook[0] = VQBlock(imageBlocks[std::rand() % imageBlocks.size()]);\n        for (int cluster = 1; cluster < codeBookSize; cluster++) {\n            sum = 0;\n            for (i = 0; i < imageLength; i++) {\n                nearest(imageBlocks[i], codeBook.data(), cluster, distances[i]);\n                sum += distances[i];\n            }\n            sum = sum * std::clamp(std::rand(), 0, 0x7fff) / (0x7fff - 1.0);\n            for (i = 0; i < imageLength; i++) {\n                if ((sum -= distances[i]) > 0) continue;\n                codeBook[cluster] = VQBlock(imageBlocks[i]);\n                break;\n            }\n        }\n        double dump = 0.0;\n        for (i = 0; i < imageLength; i++) {\n            imageBlocks[i].group = nearest(imageBlocks[i], codeBook.data(), codeBookSize, dump);\n        }\n        return codeBook;\n    }\n}\n\nstd::vector<VQBlock> createCodebook(Image& image, int codeBookSize, int blockWidth, int blockHeight)\n{\n    if (image.width() % blockWidth != 0 || image.height() % blockHeight != 0) {\n        throw std::runtime_error(\"The image can't be devided by the given block size!\");\n    }\n\n    std::vector<VQBlock> imageBlocks = createBlocks(image, blockWidth, blockHeight);\n    std::vector<VQBlock> codeBookBlocks = initializeCodeBook(imageBlocks, codeBookSize);\n\n    int i = 0;\n    int j = 0;\n    int changed = 0;\n    int nearestIndex = 0;\n    VQBlock imageBlock;\n    VQBlock codeBookBlock;\n    double dump = 0.0;\n    int runs = 0;\n\n    do {\n        for (i = 0; i < codeBookSize; i++) {\n            codeBookBlock = codeBookBlocks[i];\n            codeBookBlock.group = 0;\n            codeBookBlock.zero();\n        }\n        for (j = 0; j < imageBlocks.size(); j++) {\n            imageBlock = imageBlocks[j];\n            codeBookBlock = codeBookBlocks[imageBlock.group];\n            codeBookBlock.group += 1;\n            codeBookBlock.add(imageBlock);\n        }\n        for (i = 0; i < codeBookSize; i++) {\n            codeBookBlock = codeBookBlocks[i];\n            codeBookBlock.div(codeBookBlock.group);\n        }\n        changed = 0;\n        for (j = 0; j < imageBlocks.size(); j++) {\n            imageBlock = imageBlocks[j];\n            nearestIndex = nearest(imageBlock, codeBookBlocks.data(), codeBookSize, dump);\n            if (nearestIndex != imageBlock.group)\n            {\n                changed++;\n                imageBlock.group = nearestIndex;\n            }\n        }\n        runs++;\n    } while (changed > (imageBlocks.size() >> 10));\n\n    for (i = 0; i < codeBookSize; i++) {\n        codeBookBlock = codeBookBlocks[i];\n        codeBookBlock.group = i;\n    }\n    return codeBookBlocks;\n}\n\nuint8_t* quantizeImage(Image& image, std::vector<VQBlock> codeBook, uint8_t blockSize) {\n    std::vector<VQBlock> blocks = createBlocks(image, blockSize, blockSize);\n    uint8_t* result = new uint8_t[blocks.size()];\n    double dump = 0.0;\n    for (int i = 0; i < blocks.size(); i++) {\n        VQBlock block = blocks[i];\n        result[i] = nearest(block, codeBook.data(), codeBook.size(), dump);\n    }\n    return result;\n}\n\nuint8_t* quantizeImage(Image& image, uint32_t codeBookSize, uint8_t blockSize, uint8_t pixelSize) {\n    std::vector<VQBlock> codeBook = createCodebook(image, codeBookSize);\n    return quantizeImage(image, codeBook, blockSize);\n}\n\n}\n}\n", "meta": {"hexsha": "ebb891514b08b2ee48a7fd42c3168aaf6b87e409", "size": 8030, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/shendk/files/image/pvr/vector_quantizer.cpp", "max_stars_repo_name": "Shenmue-Mods/ShenmueDK", "max_stars_repo_head_hexsha": "feca9c937fe5cf6fb99b11336792f33d9797aca7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-05-27T21:15:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-25T10:42:30.000Z", "max_issues_repo_path": "src/shendk/files/image/pvr/vector_quantizer.cpp", "max_issues_repo_name": "Shenmue-Mods/ShenmueDK", "max_issues_repo_head_hexsha": "feca9c937fe5cf6fb99b11336792f33d9797aca7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/shendk/files/image/pvr/vector_quantizer.cpp", "max_forks_repo_name": "Shenmue-Mods/ShenmueDK", "max_forks_repo_head_hexsha": "feca9c937fe5cf6fb99b11336792f33d9797aca7", "max_forks_repo_licenses": ["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.4635193133, "max_line_length": 118, "alphanum_fraction": 0.5687422167, "num_tokens": 2107, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314798554445, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.46355753821492984}}
{"text": "#include <algorithm>\n#include <cmath>\n#include <iostream>\n\n#include <minbase/crossplat.h>\n#include <minimgapi/minimgapi-helpers.hpp>\n#include <minimgapi/imgguard.hpp>\n#include <minimgio/minimgio.h>\n#include <mximg/image.h>\n#include <mximg/ocv.h>\n#include <vi_cvt/std/exception_macros.hpp>\n#include <vi_cvt/ocv/image.hpp>\n\n#include <colorseg/color_distance_func.h>\n#include <colorseg/colorspace_homography.hpp>\n#include <colorseg/color_vertex.h>\n#include <remseg/segmentator.hpp>\n#include <remseg/utils.h>\n\n#include \"opencv2/imgproc/imgproc.hpp\"\n#include \"opencv2/highgui/highgui.hpp\"\n\nTHIRDPARTY_INCLUDES_BEGIN\n#include <boost/filesystem.hpp>\n#include <tclap/CmdLine.h>\nTHIRDPARTY_INCLUDES_END\n\nnamespace bfs = boost::filesystem;\n\nusing namespace vi::remseg;\nusing namespace vi::colorseg;\n\nconst int    BILATERAL_D = 15;\nconst double BILATERAL_SIGMA_COLOR = 50;\nconst double BILATERAL_SIGMA_SPACE = 50;\n\ndouble KL(Eigen::Vector3d const & mean1, Eigen::Vector3d const & mean2,\n          Eigen::Matrix3d const & cov1, Eigen::Matrix3d const & cov2)\n{\n  auto s1 = (cov2.inverse() * cov1).trace();\n  auto s2 = (mean2 - mean1).transpose() * cov2.inverse() * (mean2 - mean1);\n  auto s3 = std::log(cov2.determinant() / cov1.determinant());\n  return (s1 + s2 + s3 - 3)/ 2;\n}\n\nvoid obtainBlockList(std::set<std::pair<int, int> > & blockList,\n                      Segmentator<ColorVertex> const & segmentator,\n                      double threshold)\n{\n  const ImageMap &imageMap = segmentator.getImageMap();\n  auto stats = imageMap.getSegmentStats();\n  for (auto const & stat : stats)\n  {\n    SegmentID id = stat.first;\n    ColorVertex * v = segmentator.vertexById(id);\n    ColorVertex::HelperStats const & hs = v->getHelperStats();\n    std::vector<EdgeValue> dists;\n    for (auto const& n : stat.second.neighbours)\n    {\n      ColorVertex * v_n = segmentator.vertexById(n);\n      ColorVertex::HelperStats const & hs_n = v_n->getHelperStats();\n      dists.push_back(KL(hs.mean, hs_n.mean, hs.covariance, hs_n.covariance));\n    }\n\n    if (!dists.empty() && *std::min_element(dists.begin(), dists.end()) > threshold)\n      blockList.insert(stat.second.leftTopPoint);\n  }\n}\n\nvoid offscaleFix(Segmentator<ColorVertex> & segmentator, double threshold)\n{\n  const ImageMap &imageMap = segmentator.getImageMap();\n  auto const stats = imageMap.getSegmentStats();\n  std::set<SegmentID> merged;\n\n  for (auto const & stat : stats)\n  {\n    if (merged.find(stat.first) != merged.end())\n      continue;\n\n    ColorVertex * v = segmentator.vertexById(stat.first);\n    ColorVertex::HelperStats const & hs = v->getHelperStats();\n\n    if (homographyInv(hs.mean, ColorVertex::getHomographyA(),\n                      ColorVertex::getHomographyK()).mean() < threshold)\n      continue;\n\n    if (v->size() == 1)\n    {\n      merged.insert(segmentator.getId(v->begin()->vertex));\n      segmentator.merge(v, dynamic_cast<ColorVertex*>(v->begin()->vertex));\n    }\n    else\n    {\n      int i = 0, j = 0;\n\n      std::vector<int> ids;\n      std::set<int> merged_ids;\n\n      for (ConstJoint it = v->begin(); it != v->end(); it++)\n        ids.push_back(segmentator.getId(it->vertex));\n\n      for (auto it1 = ids.begin(); it1 != ids.end(); it1++)\n      {\n        if (merged_ids.find(*it1) != merged_ids.end())\n          continue;\n\n        for (auto it2 = v->begin(); it2 != v->end(); it2++)\n        {\n          ColorVertex * v1 = segmentator.vertexById(*it1);\n          ColorVertex * v2 = dynamic_cast<ColorVertex*>(it2->vertex);\n\n          if (v1 == v2)\n            continue;\n\n          Edge * edge = 0;\n          for (auto it3 = v2->begin(); it3 != v2->end(); it3++)\n          if (dynamic_cast<ColorVertex*>(it3->vertex) == v1)\n            edge = it3->edge;\n\n          if (edge == 0)\n            continue;\n\n          if (!isLTCluster(v1, v2))\n            continue;\n\n          merged.insert(segmentator.getId(v1));\n          merged.insert(segmentator.getId(v2));\n\n          segmentator.merge(v, v1);\n          segmentator.merge(v, v2);\n\n          merged_ids.insert(*it1);\n          merged_ids.insert(segmentator.getId(v2));\n          break;\n        }\n      }\n    }\n    segmentator.updateMapping();\n  }\n}\n\nint main(int argc, const char *argv[])\n{\n  i8r::AutoShutdown i8r_shutdown;\n\n  TCLAP::CmdLine cmd(\"Run Range-Based Region Merge Segmentation on a Single image\");\n  TCLAP::ValueArg<double> errorLimit(\"e\", \"error_limit\", \"average error limit\", false, -1, \"double\", cmd);\n  TCLAP::ValueArg<int> segmentsLimit(\"n\", \"segm_limit\", \"segments limit\", false, -1, \"int\", cmd);\n  TCLAP::UnlabeledValueArg<std::string> imagePath(\"image\", \"path to source RGB-image in tif-convertible format\", true, \"\", \"string\", cmd);\n  TCLAP::ValueArg<std::string> output(\"o\", \"output\", \"path to output dir\", false, \".\", \"string\", cmd);\n  TCLAP::SwitchArg debug(\"d\", \"debug\", \"debug mode\", cmd, false);\n  TCLAP::ValueArg<int> debugIter(\"i\", \"debug_iter\", \"debug iterations\", false, 1, \"int\", cmd);\n  TCLAP::ValueArg<int> maxSegments(\"s\", \"max_segments\", \"max segments for debug output\", false, -1, \"int\", cmd);\n  TCLAP::ValueArg<double> blockingThresh(\"g\", \"blocking_thresh\", \"blocking threshold value\", false, 1, \"double\", cmd);\n  TCLAP::ValueArg<double> maxModelDistance(\"\", \"model_distance\", \"model distance\", false, 20, \"double\", cmd);\n  TCLAP::ValueArg<double> glareThresh(\"\", \"glare_thresh\", \"glare threshold\", false, 230, \"double\", cmd);\n  TCLAP::SwitchArg prefilter(\"p\", \"prefilter\", \"use image pre-filtering\", cmd, false);\n\n  cmd.parse(argc, argv);\n\n  ColorVertex::setMaxModelDistance(maxModelDistance.getValue());\n\n  if (!bfs::is_directory(output.getValue()))\n    throw std::runtime_error(\"Failed to find output directory \" + output.getValue());\n\n  if (debug.getValue())\n     i8r::configure(output.getValue());\n\n  std::string const basename = bfs::path(imagePath.getValue()).stem().string();\n  std::string const imgres_filename = bfs::absolute(basename + \".png\", output.getValue()).string();\n  std::string const filtered_filename = bfs::absolute(basename + \".filtered.png\", output.getValue()).string();\n\n  try\n  {\n    mximg::PImage image = mximg::Image::imread(imagePath.getValue().c_str());\n    if ((*image)->channels != 3)\n      throw std::runtime_error(\"Image should have exact 3 channels for color segmentation\");\n\n    cv::Mat cv_image_filtered;\n    if (prefilter.getValue())\n    {\n      cv::Mat cv_image = vi::cvt::ocv::as_cvmat(*image);\n      cv::bilateralFilter(cv_image, cv_image_filtered, BILATERAL_D, BILATERAL_SIGMA_COLOR, BILATERAL_SIGMA_SPACE);\n      cv::imwrite(filtered_filename, cv_image_filtered);\n      //MinImg min_image_filtered = vi::cvt::ocv::as_minimg(cv_image_filtered);\n      image = mximg::createByCopy(cv_image_filtered);\n    }\n\n    auto dbg = i8r::logger(\"debug.\" + basename + \".pointlike\");\n    Segmentator<ColorVertex> segmentatorPointlike(*image, shouldnotcall, criteria_r0, true);\n    segmentatorPointlike.mergeToLimit(-1, errorLimit.getValue(), segmentsLimit.getValue(),\n                                      dbg, debugIter.getValue(), maxSegments.getValue());\n\n    std::set<std::pair<int, int> > blockList;\n    obtainBlockList(blockList, segmentatorPointlike, blockingThresh.getValue());\n\n    Segmentator<ColorVertex> segmentatorLinear(*image, &segmentatorPointlike.getImageMap(),\n                                               error_r1, criteria_r1,\n                                               blockList, BLOCK_SEGMENTS, true);\n    segmentatorLinear.mergeToLimit(-1, errorLimit.getValue() * std::sqrt(2./3), segmentsLimit.getValue(),\n                                   dbg, debugIter.getValue(), maxSegments.getValue());\n\n    Segmentator<ColorVertex> segmentatorPlanar(*image, &segmentatorLinear.getImageMap(),\n                                                error_r2, criteria_r2,\n                                                {}, BLOCK_SEGMENTS, true);\n    segmentatorPlanar.mergeToLimit(-1, errorLimit.getValue() * std::sqrt(1./3), segmentsLimit.getValue(),\n                                   dbg, debugIter.getValue(), maxSegments.getValue());\n\n    offscaleFix(segmentatorPlanar, glareThresh.getValue());\n    const ImageMap &imageMap = segmentatorPlanar.getImageMap();\n\n    DECLARE_GUARDED_MINIMG(imgres);\n    visualize(&imgres, imageMap);\n    THROW_ON_MINERR(SaveMinImage(imgres_filename.c_str(), &imgres));\n  }\n  catch (std::exception const& e)\n  {\n    std::cerr << \"Exception caught: \" << e.what() << \"\\n\";\n    return 1;\n  }\n  catch (...)\n  {\n    std::cerr << \"UNTYPED exception\\n\";\n    return 2;\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "07c72a8693f570ac6b1ae6ffb97a46f330f65ccb", "size": 8505, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "vi_packages/colorseg/demo/colorseg_go.cpp", "max_stars_repo_name": "dketterer/colorsegmentation", "max_stars_repo_head_hexsha": "58440fc4eb9aeb7e025a91b521e56c87c154b176", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "vi_packages/colorseg/demo/colorseg_go.cpp", "max_issues_repo_name": "dketterer/colorsegmentation", "max_issues_repo_head_hexsha": "58440fc4eb9aeb7e025a91b521e56c87c154b176", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vi_packages/colorseg/demo/colorseg_go.cpp", "max_forks_repo_name": "dketterer/colorsegmentation", "max_forks_repo_head_hexsha": "58440fc4eb9aeb7e025a91b521e56c87c154b176", "max_forks_repo_licenses": ["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.9782608696, "max_line_length": 138, "alphanum_fraction": 0.6436213992, "num_tokens": 2197, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.885631470799559, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.46355753347489503}}
{"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  Pose2.cpp\n * @brief 2D Pose\n */\n\n#include <gtsam/geometry/concepts.h>\n#include <gtsam/geometry/Pose2.h>\n#include <gtsam/base/Lie-inl.h>\n#include <gtsam/base/Testable.h>\n#include <boost/foreach.hpp>\n#include <cmath>\n#include <iostream>\n#include <iomanip>\n\nusing namespace std;\n\nnamespace gtsam {\n\n/** Explicit instantiation of base class to export members */\nINSTANTIATE_LIE(Pose2);\n\n/** instantiate concept checks */\nGTSAM_CONCEPT_POSE_INST(Pose2);\n\nstatic const Matrix I3 = eye(3), Z12 = zeros(1,2);\nstatic const Rot2 R_PI_2(Rot2::fromCosSin(0., 1.));\n\n/* ************************************************************************* */\nMatrix Pose2::matrix() const {\n  Matrix R = r_.matrix();\n  R = stack(2, &R, &Z12);\n  Matrix T = Matrix_(3,1, t_.x(), t_.y(), 1.0);\n  return collect(2, &R, &T);\n}\n\n/* ************************************************************************* */\nvoid Pose2::print(const string& s) const {\n  cout << s << \"(\" << t_.x() << \", \" << t_.y() << \", \" << r_.theta() << \")\" << endl;\n}\n\n/* ************************************************************************* */\nbool Pose2::equals(const Pose2& q, double tol) const {\n  return t_.equals(q.t_, tol) && r_.equals(q.r_, tol);\n}\n\n/* ************************************************************************* */\nPose2 Pose2::Expmap(const Vector& xi) {\n  assert(xi.size() == 3);\n  Point2 v(xi(0),xi(1));\n  double w = xi(2);\n  if (std::abs(w) < 1e-10)\n    return Pose2(xi[0], xi[1], xi[2]);\n  else {\n    Rot2 R(Rot2::fromAngle(w));\n    Point2 v_ortho = R_PI_2 * v; // points towards rot center\n    Point2 t = (v_ortho - R.rotate(v_ortho)) / w;\n    return Pose2(R, t);\n  }\n}\n\n/* ************************************************************************* */\nVector Pose2::Logmap(const Pose2& p) {\n  const Rot2& R = p.r();\n  const Point2& t = p.t();\n  double w = R.theta();\n  if (std::abs(w) < 1e-10)\n    return Vector_(3, t.x(), t.y(), w);\n  else {\n    double c_1 = R.c()-1.0, s = R.s();\n    double det = c_1*c_1 + s*s;\n    Point2 p = R_PI_2 * (R.unrotate(t) - t);\n    Point2 v = (w/det) * p;\n    return Vector_(3, v.x(), v.y(), w);\n  }\n}\n\n/* ************************************************************************* */\nPose2 Pose2::retract(const Vector& v) const {\n#ifdef SLOW_BUT_CORRECT_EXPMAP\n  return compose(Expmap(v));\n#else\n  assert(v.size() == 3);\n  return compose(Pose2(v[0], v[1], v[2]));\n#endif\n}\n\n/* ************************************************************************* */\nVector Pose2::localCoordinates(const Pose2& p2) const {\n#ifdef SLOW_BUT_CORRECT_EXPMAP\n  return Logmap(between(p2));\n#else\n  Pose2 r = between(p2);\n  return Vector_(3, r.x(), r.y(), r.theta());\n#endif\n}\n\n/* ************************************************************************* */\n// Calculate Adjoint map\n// Ad_pose is 3*3 matrix that when applied to twist xi, returns Ad_pose(xi)\nMatrix Pose2::AdjointMap() const {\n  double c = r_.c(), s = r_.s(), x = t_.x(), y = t_.y();\n  return Matrix_(3,3,\n      c,  -s,   y,\n      s,   c,  -x,\n      0.0, 0.0, 1.0\n  );\n}\n\n/* ************************************************************************* */\nPose2 Pose2::inverse(boost::optional<Matrix&> H1) const {\n  if (H1) *H1 = -AdjointMap();\n  return Pose2(r_.inverse(), r_.unrotate(Point2(-t_.x(), -t_.y())));\n}\n\n/* ************************************************************************* */\n// see doc/math.lyx, SE(2) section\nPoint2 Pose2::transform_to(const Point2& point,\n    boost::optional<Matrix&> H1, boost::optional<Matrix&> H2) const {\n  Point2 d = point - t_;\n  Point2 q = r_.unrotate(d);\n  if (!H1 && !H2) return q;\n  if (H1) *H1 = Matrix_(2, 3,\n      -1.0, 0.0,  q.y(),\n      0.0, -1.0, -q.x());\n  if (H2) *H2 = r_.transpose();\n  return q;\n}\n\n/* ************************************************************************* */\n// see doc/math.lyx, SE(2) section\nPose2 Pose2::compose(const Pose2& p2, boost::optional<Matrix&> H1,\n    boost::optional<Matrix&> H2) const {\n  // TODO: inline and reuse?\n  if(H1) *H1 = p2.inverse().AdjointMap();\n  if(H2) *H2 = I3;\n  return (*this)*p2;\n}\n\n/* ************************************************************************* */\n// see doc/math.lyx, SE(2) section\nPoint2 Pose2::transform_from(const Point2& p,\n    boost::optional<Matrix&> H1, boost::optional<Matrix&> H2) const {\n  const Point2 q = r_ * p;\n  if (H1 || H2) {\n    const Matrix R = r_.matrix();\n    const Matrix Drotate1 = Matrix_(2, 1, -q.y(), q.x());\n    if (H1) *H1 = collect(2, &R, &Drotate1); // [R R_{pi/2}q]\n    if (H2) *H2 = R;                         // R\n  }\n  return q + t_;\n}\n\n/* ************************************************************************* */\nPose2 Pose2::between(const Pose2& p2, boost::optional<Matrix&> H1,\n    boost::optional<Matrix&> H2) const {\n  // get cosines and sines from rotation matrices\n  const Rot2& R1 = r_, R2 = p2.r();\n  double c1=R1.c(), s1=R1.s(), c2=R2.c(), s2=R2.s();\n\n  // Assert that R1 and R2 are normalized\n  assert(std::abs(c1*c1 + s1*s1 - 1.0) < 1e-5 && std::abs(c2*c2 + s2*s2 - 1.0) < 1e-5);\n\n  // Calculate delta rotation = between(R1,R2)\n  double c = c1 * c2 + s1 * s2, s = -s1 * c2 + c1 * s2;\n  Rot2 R(Rot2::atan2(s,c)); // normalizes\n\n  // Calculate delta translation = unrotate(R1, dt);\n  Point2 dt = p2.t() - t_;\n  double x = dt.x(), y = dt.y();\n  Point2 t(c1 * x + s1 * y, -s1 * x + c1 * y);\n\n  // FD: This is just -AdjointMap(between(p2,p1)) inlined and re-using above\n  if (H1) {\n    double dt1 = -s2 * x + c2 * y;\n    double dt2 = -c2 * x - s2 * y;\n    *H1 = Matrix_(3,3,\n        -c,  -s,  dt1,\n        s,  -c,  dt2,\n        0.0, 0.0,-1.0);\n  }\n  if (H2) *H2 = I3;\n\n  return Pose2(R,t);\n}\n\n/* ************************************************************************* */\nRot2 Pose2::bearing(const Point2& point,\n    boost::optional<Matrix&> H1, boost::optional<Matrix&> H2) const {\n  Point2 d = transform_to(point, H1, H2);\n  if (!H1 && !H2) return Rot2::relativeBearing(d);\n  Matrix D_result_d;\n  Rot2 result = Rot2::relativeBearing(d, D_result_d);\n  if (H1) *H1 = D_result_d * (*H1);\n  if (H2) *H2 = D_result_d * (*H2);\n  return result;\n}\n\n/* ************************************************************************* */\nRot2 Pose2::bearing(const Pose2& point,\n    boost::optional<Matrix&> H1, boost::optional<Matrix&> H2) const {\n  Rot2 result = bearing(point.t(), H1, H2);\n  if (H2) {\n    Matrix H2_ = *H2 * point.r().matrix();\n    *H2 = zeros(1, 3);\n    insertSub(*H2, H2_, 0, 0);\n  }\n  return result;\n}\n\n/* ************************************************************************* */\ndouble Pose2::range(const Point2& point,\n    boost::optional<Matrix&> H1, boost::optional<Matrix&> H2) const {\n  Point2 d = point - t_;\n  if (!H1 && !H2) return d.norm();\n  Matrix H;\n  double r = d.norm(H);\n  if (H1) *H1 = H * Matrix_(2, 3,\n      -r_.c(),  r_.s(),  0.0,\n      -r_.s(), -r_.c(),  0.0);\n  if (H2) *H2 = H;\n  return r;\n}\n\n/* ************************************************************************* */\ndouble Pose2::range(const Pose2& pose2,\n    boost::optional<Matrix&> H1,\n    boost::optional<Matrix&> H2) const {\n  Point2 d = pose2.t() - t_;\n  if (!H1 && !H2) return d.norm();\n  Matrix H;\n  double r = d.norm(H);\n  if (H1) *H1 = H * Matrix_(2, 3,\n      -r_.c(),  r_.s(),  0.0,\n      -r_.s(), -r_.c(),  0.0);\n  if (H2) *H2 = H * Matrix_(2, 3,\n      pose2.r_.c(), -pose2.r_.s(),  0.0,\n      pose2.r_.s(),  pose2.r_.c(),  0.0);\n  return r;\n}\n\n/* *************************************************************************\n * New explanation, from scan.ml\n * It finds the angle using a linear method:\n * q = Pose2::transform_from(p) = t + R*p\n * We need to remove the centroids from the data to find the rotation\n * using dp=[dpx;dpy] and q=[dqx;dqy] we have\n *  |dqx|   |c  -s|     |dpx|     |dpx -dpy|     |c|\n *  |   | = |     |  *  |   |  =  |        |  *  | | = H_i*cs\n *  |dqy|   |s   c|     |dpy|     |dpy  dpx|     |s|\n * where the Hi are the 2*2 matrices. Then we will minimize the criterion\n * J = \\sum_i norm(q_i - H_i * cs)\n * Taking the derivative with respect to cs and setting to zero we have\n * cs = (\\sum_i H_i' * q_i)/(\\sum H_i'*H_i)\n * The hessian is diagonal and just divides by a constant, but this\n * normalization constant is irrelevant, since we take atan2.\n * i.e., cos ~ sum(dpx*dqx + dpy*dqy) and sin ~ sum(-dpy*dqx + dpx*dqy)\n * The translation is then found from the centroids\n * as they also satisfy cq = t + R*cp, hence t = cq - R*cp\n */\n\nboost::optional<Pose2> align(const vector<Point2Pair>& pairs) {\n\n  size_t n = pairs.size();\n  if (n<2) return boost::none; // we need at least two pairs\n\n  // calculate centroids\n  Point2 cp,cq;\n  BOOST_FOREACH(const Point2Pair& pair, pairs) {\n    cp += pair.first;\n    cq += pair.second;\n  }\n  double f = 1.0/n;\n  cp *= f; cq *= f;\n\n  // calculate cos and sin\n  double c=0,s=0;\n  BOOST_FOREACH(const Point2Pair& pair, pairs) {\n    Point2 dq = pair.first  - cp;\n    Point2 dp = pair.second - cq;\n    c +=  dp.x() * dq.x() + dp.y() * dq.y();\n    s +=  dp.y() * dq.x() - dp.x() * dq.y(); // this works but is negative from formula above !! :-(\n  }\n\n  // calculate angle and translation\n  double theta = atan2(s,c);\n  Rot2 R = Rot2::fromAngle(theta);\n  Point2 t = cq - R*cp;\n  return Pose2(R, t);\n}\n\n/* ************************************************************************* */\n} // namespace gtsam\n", "meta": {"hexsha": "c0a3d43d2d3d7baacf41f3aaf53b6c0eccca6a66", "size": 9697, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/geometry/Pose2.cpp", "max_stars_repo_name": "malcolmreynolds/GTSAM", "max_stars_repo_head_hexsha": "e911b4d39f8a8c8604663bd46f10e7f53c860ae8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-07-23T19:34:50.000Z", "max_stars_repo_stars_event_max_datetime": "2017-07-23T19:34:50.000Z", "max_issues_repo_path": "gtsam/geometry/Pose2.cpp", "max_issues_repo_name": "malcolmreynolds/GTSAM", "max_issues_repo_head_hexsha": "e911b4d39f8a8c8604663bd46f10e7f53c860ae8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gtsam/geometry/Pose2.cpp", "max_forks_repo_name": "malcolmreynolds/GTSAM", "max_forks_repo_head_hexsha": "e911b4d39f8a8c8604663bd46f10e7f53c860ae8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.8980263158, "max_line_length": 100, "alphanum_fraction": 0.4853047334, "num_tokens": 3015, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081926, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.46354036874119553}}
{"text": "#include <catch.hpp>\n\n#include <boost/concept_check.hpp>\n#include <boost/graph/graph_concepts.hpp>\n#include <boost/graph/astar_search.hpp>\n#include <boost/tuple/tuple.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/property_map/function_property_map.hpp>\n#include <boost/container_hash/hash.hpp>\n\n#include <map>\n#include <vector>\n#include <exception>\n#include <functional>\n\n#define UNSAFE_FUNCTION_GRAPH\n\n#include \"functional_graph.h\"\n#include \"EuclideanDistanceFunctor.h\"\n#include \"map_property_map.h\"\n\nBOOST_CONCEPT_ASSERT((boost::BidirectionalGraphConcept<functional_graph<float>>));\n\nnamespace std {\ntemplate<typename A, typename B>\nstruct hash<std::pair<A, B>> {\n    size_t operator()(std::pair<A, B> val) const {\n        size_t seed = 0;\n        boost::hash_combine(seed, val.first);\n        boost::hash_combine(seed, val.second);\n        return seed;\n    }\n};\n}\n\nTEST_CASE(\"Edge equality\") {\n    edge<int> a = {1, 2};\n    edge<int> b = {1, 2};\n    edge<int> c = {2, 1};\n    REQUIRE(a == b);\n    REQUIRE(b == a);\n    REQUIRE(!(a == c));\n    REQUIRE(!(c == a));\n    REQUIRE(!(b == c));\n    REQUIRE(!(c == b));\n}\n\nTEST_CASE(\"Edge inequality\") {\n    edge<int> a = {4, -1};\n    edge<int> b = {4, -1};\n    edge<int> c = {-11, -1};\n    REQUIRE(a != c);\n    REQUIRE(c != a);\n    REQUIRE(b != c);\n    REQUIRE(c != b);\n    REQUIRE(!(a != b));\n    REQUIRE(!(b != a));\n}\n\nusing namespace boost;\ntypedef std::pair<float, float> V;\ntypedef functional_graph<V> G;\ntypedef edge<V> E;\ntypedef graph_traits<G>::out_edge_iterator OeItr;\ntypedef graph_traits<G>::in_edge_iterator IeItr;\n\nstd::vector<E> adj(V v) {\n    return {\n        {v, {v.first, v.second + 1}},\n        {v, {v.first + 1, v.second}},\n        {v, {v.first, v.second - 1}},\n        {v, {v.first - 1, v.second}}\n    };\n};\n\nstd::vector<E> empty(V v) {\n    return {};\n}\n\nstd::vector<E> left(V v) {\n    return { {v, {v.first - 1, v.second}} };\n}\n\nstd::vector<E> right(V v) {\n    return { {v, {v.first + 1, v.second}} };\n}\n\nTEST_CASE(\"Out edges\") {\n    G g(left, adj);\n    V source = {0, 0};\n    OeItr begin, end;\n    tie(begin, end) = out_edges(source, g);\n    edge<V> up = {source, {0, 1}};\n    edge<V> down = {source, {0, -1}};\n    edge<V> left = {source, {-1, 0}};\n    edge<V> right = {source, {1, 0}};\n    std::vector<edge<V>> edges(begin, end);\n    REQUIRE(edges.size() == 4);\n    REQUIRE(std::find(begin, end, up) != end);\n    REQUIRE(std::find(begin, end, down) != end);\n    REQUIRE(std::find(begin, end, left) != end);\n    REQUIRE(std::find(begin, end, right) != end);\n}\n\nTEST_CASE(\"In edges\") {\n    G g(adj, left);\n    V source = {0, 0};\n    IeItr begin, end;\n    tie(begin, end) = in_edges(source, g);\n    edge<V> up = {source, {0, 1}};\n    edge<V> down = {source, {0, -1}};\n    edge<V> left = {source, {-1, 0}};\n    edge<V> right = {source, {1, 0}};\n    std::vector<edge<V>> edges(begin, end);\n    REQUIRE(edges.size() == 4);\n    REQUIRE(std::find(begin, end, up) != end);\n    REQUIRE(std::find(begin, end, down) != end);\n    REQUIRE(std::find(begin, end, left) != end);\n    REQUIRE(std::find(begin, end, right) != end);\n}\n\nTEST_CASE(\"Source\") {\n    G g(adj, adj);\n    V a = {0, 0};\n    E edge = {a, {1, 1}};\n    V v = source(edge, g);\n    REQUIRE(v == a);\n}\n\nTEST_CASE(\"Target\") {\n    G g(adj, adj);\n    V a = {0, 0};\n    E edge = {{1, 1}, a};\n    V v = target(edge, g);\n    REQUIRE(v == a);\n}\n\nTEST_CASE(\"Out degree\") {\n    G g(adj, adj);\n    V v = {0, 0};\n    REQUIRE(out_degree(v, g) == 4);\n}\n\nTEST_CASE(\"In degree\") {\n    G g(adj, adj);\n    V v = {0, 0};\n    REQUIRE(in_degree(v, g) == 4);\n}\n\nTEST_CASE(\"Degree\") {\n    G g(adj, adj);\n    V v = {0, 0};\n    REQUIRE(degree(v, g) == 8);\n}\n\nstruct goal_found {};\n\nclass goal_terminating_visitor : public default_astar_visitor {\nprivate:\n    const V _target;\npublic:\n    goal_terminating_visitor(V v) : _target(v) {};\n    void finish_vertex(V u, G g) {\n        if (u == _target) {\n            throw goal_found();\n        }\n    };  \n};\n\nfloat dist(V src, V dst) {\n    float dx = src.first - dst.first;\n    float dy = src.second - dst.second;\n    return sqrt(dx * dx + dy * dy);\n}\n\nTEST_CASE(\"A* over functional graph\") {\n    G g(adj, adj);\n    V start = {0, 0};\n    V goal = {10, 10};\n\n    std::function<float(E)> w_map = [&g](E e){\n        V src = source(e, g);\n        V dst = target(e, g);\n        return dist(src, dst);\n    };\n\n    map_property_map<V, V> pred_map;\n    map_property_map<V, float> dist_map(INFINITY);\n    dist_map[start] = 0.0f;\n    map_property_map<V, float> r_map;\n    map_property_map<V, unsigned int> vi_map;\n    map_property_map<V, default_color_type> c_map;\n\n    goal_terminating_visitor vis(goal);\n\n    REQUIRE_THROWS_AS(\n        astar_search_no_init(\n            g,\n            start,\n            [&goal](V v) {\n                float d = dist(v, goal);\n                return d;\n            },\n            visitor(vis).\n            predecessor_map(pred_map).\n            rank_map(r_map).\n            distance_map(dist_map).\n            weight_map(make_function_property_map<E>(w_map)).\n            color_map(c_map).\n            vertex_index_map(vi_map)\n        ),\n        goal_found\n    );\n}", "meta": {"hexsha": "ea7a22a7445021f40bf2f722691501679b6b8ed9", "size": 5141, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test_functional_graph.cpp", "max_stars_repo_name": "jmlowenthal/survey", "max_stars_repo_head_hexsha": "030fb473f9a30d41654475e3bfa00a83348bb1f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-05-16T15:01:11.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-16T15:01:11.000Z", "max_issues_repo_path": "src/test_functional_graph.cpp", "max_issues_repo_name": "jmlowenthal/survey", "max_issues_repo_head_hexsha": "030fb473f9a30d41654475e3bfa00a83348bb1f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/test_functional_graph.cpp", "max_forks_repo_name": "jmlowenthal/survey", "max_forks_repo_head_hexsha": "030fb473f9a30d41654475e3bfa00a83348bb1f0", "max_forks_repo_licenses": ["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.023364486, "max_line_length": 82, "alphanum_fraction": 0.5598132659, "num_tokens": 1519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081925, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.4635403687411954}}
{"text": "/* ----------------------------------------------------------------------------\n * Copyright 2020, Massachusetts Institute of Technology, * Cambridge, MA 02139\n * All Rights Reserved\n * Authors: Yulun Tian, et al. (see README for the full author list)\n * See LICENSE for the license information\n * -------------------------------------------------------------------------- */\n\n#include <DPGO/DPGO_utils.h>\n#include <DPGO/DPGO_robust.h>\n#include <Eigen/Geometry>\n#include <Eigen/SPQRSupport>\n#include <algorithm>\n#include <fstream>\n#include <iostream>\n#include <random>\n#include <cassert>\n#include <boost/math/distributions/chi_squared.hpp>\n\nnamespace DPGO {\n\nvoid writeMatrixToFile(const Matrix &M, const std::string &filename) {\n  std::ofstream file;\n  file.open(filename);\n  if (!file.is_open()) {\n    printf(\"Cannot write to specified file: %s\\n\", filename.c_str());\n    return;\n  }\n  const static Eigen::IOFormat CSVFormat(Eigen::FullPrecision, Eigen::DontAlignCols, \", \", \"\\n\");\n  file << M.format(CSVFormat);\n  file.close();\n}\n\nvoid writeSparseMatrixToFile(const SparseMatrix &M, const std::string &filename) {\n  std::ofstream file;\n  file.open(filename);\n  if (!file.is_open()) {\n    printf(\"Cannot write to specified file: %s\\n\", filename.c_str());\n    return;\n  }\n\n  for (int k = 0; k < M.outerSize(); ++k) {\n    for (SparseMatrix::InnerIterator it(M, k); it; ++it) {\n      file << it.row() << \",\";\n      file << it.col() << \",\";\n      file << it.value() << \"\\n\";\n    }\n  }\n  file.close();\n}\n\n/**\n###############################################################\n###############################################################\nThe following implementations are originally implemented in:\n\nSE-Sync: https://github.com/david-m-rosen/SE-Sync.git\n\nCartan-Sync: https://bitbucket.org/jesusbriales/cartan-sync/src\n\n###############################################################\n###############################################################\n*/\n\nstd::vector<RelativeSEMeasurement> read_g2o_file(const std::string &filename,\n                                                 size_t &num_poses) {\n  // Preallocate output vector\n  std::vector<DPGO::RelativeSEMeasurement> measurements;\n\n  // A single measurement, whose values we will fill in\n  DPGO::RelativeSEMeasurement measurement;\n  measurement.weight = 1.0;\n\n  // A string used to contain the contents of a single line\n  std::string line;\n\n  // A string used to extract tokens from each line one-by-one\n  std::string token;\n\n  // Preallocate various useful quantities\n  double dx, dy, dz, dtheta, dqx, dqy, dqz, dqw, I11, I12, I13, I14, I15, I16,\n      I22, I23, I24, I25, I26, I33, I34, I35, I36, I44, I45, I46, I55, I56, I66;\n\n  size_t i, j;\n\n  // Open the file for reading\n  std::ifstream infile(filename);\n\n  num_poses = 0;\n\n  while (std::getline(infile, line)) {\n    // Construct a stream from the string\n    std::stringstream strstrm(line);\n\n    // Extract the first token from the string\n    strstrm >> token;\n\n    if (token == \"EDGE_SE2\") {\n      // This is a 2D pose measurement\n\n      /** The g2o format specifies a 2D relative pose measurement in the\n       * following form:\n       *\n       * EDGE_SE2 id1 id2 dx dy dtheta, I11, I12, I13, I22, I23, I33\n       *\n       */\n\n      // Extract formatted output\n      strstrm >> i >> j >> dx >> dy >> dtheta >> I11 >> I12 >> I13 >> I22 >>\n              I23 >> I33;\n\n      // Fill in elements of this measurement\n\n      // Pose ids\n      measurement.r1 = 0;\n      measurement.r2 = 0;\n      measurement.p1 = i;\n      measurement.p2 = j;\n\n      // Raw measurements\n      measurement.t = Eigen::Matrix<double, 2, 1>(dx, dy);\n      measurement.R = Eigen::Rotation2Dd(dtheta).toRotationMatrix();\n\n      Eigen::Matrix2d TranCov;\n      TranCov << I11, I12, I12, I22;\n      measurement.tau = 2 / TranCov.inverse().trace();\n\n      measurement.kappa = I33;\n\n    } else if (token == \"EDGE_SE3:QUAT\") {\n      // This is a 3D pose measurement\n\n      /** The g2o format specifies a 3D relative pose measurement in the\n       * following form:\n       *\n       * EDGE_SE3:QUAT id1, id2, dx, dy, dz, dqx, dqy, dqz, dqw\n       *\n       * I11 I12 I13 I14 I15 I16\n       *     I22 I23 I24 I25 I26\n       *         I33 I34 I35 I36\n       *             I44 I45 I46\n       *                 I55 I56\n       *                     I66\n       */\n\n      // Extract formatted output\n      strstrm >> i >> j >> dx >> dy >> dz >> dqx >> dqy >> dqz >> dqw >> I11 >>\n              I12 >> I13 >> I14 >> I15 >> I16 >> I22 >> I23 >> I24 >> I25 >> I26 >>\n              I33 >> I34 >> I35 >> I36 >> I44 >> I45 >> I46 >> I55 >> I56 >> I66;\n\n      // Fill in elements of the measurement\n\n      // Pose ids\n      measurement.r1 = 0;\n      measurement.r2 = 0;\n      measurement.p1 = i;\n      measurement.p2 = j;\n\n      // Raw measurements\n      measurement.t = Eigen::Matrix<double, 3, 1>(dx, dy, dz);\n      measurement.R = Eigen::Quaterniond(dqw, dqx, dqy, dqz).toRotationMatrix();\n\n      // Compute precisions\n\n      // Compute and store the optimal (information-divergence-minimizing) value\n      // of the parameter tau\n      Eigen::Matrix3d TranCov;\n      TranCov << I11, I12, I13, I12, I22, I23, I13, I23, I33;\n      measurement.tau = 3 / TranCov.inverse().trace();\n\n      // Compute and store the optimal (information-divergence-minimizing value\n      // of the parameter kappa\n\n      Eigen::Matrix3d RotCov;\n      RotCov << I44, I45, I46, I45, I55, I56, I46, I56, I66;\n      measurement.kappa = 3 / (2 * RotCov.inverse().trace());\n\n    } else if ((token == \"VERTEX_SE2\") || (token == \"VERTEX_SE3:QUAT\")) {\n      // This is just initialization information, so do nothing\n      continue;\n    } else {\n      std::cout << \"Error: unrecognized type: \" << token << \"!\" << std::endl;\n      assert(false);\n    }\n\n    // Update maximum value of poses found so far\n    size_t max_pair = std::max<double>(measurement.p1, measurement.p2);\n\n    num_poses = ((max_pair > num_poses) ? max_pair : num_poses);\n    measurements.push_back(measurement);\n  }  // while\n\n  infile.close();\n\n  num_poses++;  // Account for the use of zero-based indexing\n\n  return measurements;\n}\n\nvoid constructOrientedConnectionIncidenceMatrixSE(\n    const std::vector<RelativeSEMeasurement> &measurements, SparseMatrix &AT,\n    DiagonalMatrix &OmegaT) {\n  // Deduce graph dimensions from measurements\n  size_t d;  // Dimension of Euclidean space\n  d = (!measurements.empty() ? measurements[0].t.size() : 0);\n  size_t dh = d + 1;  // Homogenized dimension of Euclidean space\n  size_t m;           // Number of measurements\n  m = measurements.size();\n  size_t n = 0;  // Number of poses\n  for (const RelativeSEMeasurement &meas: measurements) {\n    if (n < meas.p1) n = meas.p1;\n    if (n < meas.p2) n = meas.p2;\n  }\n  n++;  // Account for 0-based indexing: node indexes go from 0 to max({i,j})\n\n  // Define connection incidence matrix dimensions\n  // This is a [n x m] (dh x dh)-block matrix\n  size_t rows = (d + 1) * n;\n  size_t cols = (d + 1) * m;\n\n  // We use faster ordered insertion, as suggested in\n  // https://eigen.tuxfamily.org/dox/group__TutorialSparse.html#TutorialSparseFilling\n  Eigen::SparseMatrix<double, Eigen::ColMajor> A(rows, cols);\n  A.reserve(Eigen::VectorXi::Constant(cols, 8));\n  DiagonalMatrix Omega(cols);  // One block per measurement: (d+1)*m\n  DiagonalMatrix::DiagonalVectorType &diagonal = Omega.diagonal();\n\n  // Insert actual measurement values\n  size_t i, j;\n  for (size_t k = 0; k < m; k++) {\n    const RelativeSEMeasurement &meas = measurements[k];\n    i = meas.p1;\n    j = meas.p2;\n\n    /// Assign SE(d) matrix to block leaving node i\n    /// AT(i,k) = -Tij (NOTE: NEGATIVE)\n    // Do it column-wise for speed\n    // Elements of rotation\n    for (size_t c = 0; c < d; c++)\n      for (size_t r = 0; r < d; r++)\n        A.insert(i * dh + r, k * dh + c) = -meas.R(r, c);\n\n    // Elements of translation\n    for (size_t r = 0; r < d; r++)\n      A.insert(i * dh + r, k * dh + d) = -meas.t(r);\n\n    // Additional 1 for homogeneization\n    A.insert(i * dh + d, k * dh + d) = -1;\n\n    /// Assign (d+1)-identity matrix to block leaving node j\n    /// AT(j,k) = +I (NOTE: POSITIVE)\n    for (size_t r = 0; r < d + 1; r++) A.insert(j * dh + r, k * dh + r) = +1;\n\n    /// Assign isotropic weights in diagonal matrix\n    for (size_t r = 0; r < d; r++) diagonal[k * dh + r] = meas.weight * meas.kappa;\n\n    diagonal[k * dh + d] = meas.weight * meas.tau;\n  }\n\n  A.makeCompressed();\n\n  AT = A;\n  OmegaT = Omega;\n}\n\nSparseMatrix constructConnectionLaplacianSE(\n    const std::vector<RelativeSEMeasurement> &measurements) {\n  SparseMatrix AT;\n  DiagonalMatrix OmegaT;\n  constructOrientedConnectionIncidenceMatrixSE(measurements, AT, OmegaT);\n  return AT * OmegaT * AT.transpose();\n}\n\nvoid constructBMatrices(const std::vector<RelativeSEMeasurement> &measurements, SparseMatrix &B1,\n                        SparseMatrix &B2, SparseMatrix &B3) {\n  // Clear input matrices\n  B1.setZero();\n  B2.setZero();\n  B3.setZero();\n\n  size_t num_poses = 0;\n  size_t d = (!measurements.empty() ? measurements[0].t.size() : 0);\n\n  std::vector<Eigen::Triplet<double>> triplets;\n\n  // Useful quantities to cache\n  size_t d2 = d * d;\n  size_t d3 = d * d * d;\n\n  size_t i, j; // Indices for the tail and head of the given measurement\n  double sqrttau;\n  size_t max_pair;\n\n  /// Construct the matrix B1 from equation (69a) in the tech report\n  triplets.reserve(2 * d * measurements.size());\n\n  for (size_t e = 0; e < measurements.size(); e++) {\n    i = measurements[e].p1;\n    j = measurements[e].p2;\n    sqrttau = sqrt(measurements[e].tau);\n\n    // Block corresponding to the tail of the measurement\n    for (size_t l = 0; l < d; l++) {\n      triplets.emplace_back(e * d + l, i * d + l,\n                            -sqrttau); // Diagonal element corresponding to tail\n      triplets.emplace_back(e * d + l, j * d + l,\n                            sqrttau); // Diagonal element corresponding to head\n    }\n\n    // Keep track of the number of poses we've seen\n    max_pair = std::max<size_t>(i, j);\n    if (max_pair > num_poses)\n      num_poses = max_pair;\n  }\n  num_poses++; // Account for zero-based indexing\n\n  B1.resize(d * measurements.size(), d * num_poses);\n  B1.setFromTriplets(triplets.begin(), triplets.end());\n\n  /// Construct matrix B2 from equation (69b) in the tech report\n  triplets.clear();\n  triplets.reserve(d2 * measurements.size());\n\n  for (size_t e = 0; e < measurements.size(); e++) {\n    i = measurements[e].p1;\n    sqrttau = sqrt(measurements[e].tau);\n    for (size_t k = 0; k < d; k++)\n      for (size_t r = 0; r < d; r++)\n        triplets.emplace_back(d * e + r, d2 * i + d * k + r,\n                              -sqrttau * measurements[e].t(k));\n  }\n\n  B2.resize(d * measurements.size(), d2 * num_poses);\n  B2.setFromTriplets(triplets.begin(), triplets.end());\n\n  /// Construct matrix B3 from equation (69c) in the tech report\n  triplets.clear();\n  triplets.reserve((d3 + d2) * measurements.size());\n\n  for (size_t e = 0; e < measurements.size(); e++) {\n    double sqrtkappa = std::sqrt(measurements[e].kappa);\n    const Matrix &R = measurements[e].R;\n\n    for (size_t r = 0; r < d; r++)\n      for (size_t c = 0; c < d; c++) {\n        i = measurements[e].p1; // Tail of measurement\n        j = measurements[e].p2; // Head of measurement\n\n        // Representation of the -sqrt(kappa) * Rt(i,j) \\otimes I_d block\n        for (size_t l = 0; l < d; l++)\n          triplets.emplace_back(e * d2 + d * r + l, i * d2 + d * c + l,\n                                -sqrtkappa * R(c, r));\n      }\n\n    for (size_t l = 0; l < d2; l++)\n      triplets.emplace_back(e * d2 + l, j * d2 + l, sqrtkappa);\n  }\n\n  B3.resize(d2 * measurements.size(), d2 * num_poses);\n  B3.setFromTriplets(triplets.begin(), triplets.end());\n}\n\nMatrix chordalInitialization(\n    size_t dimension, size_t num_poses,\n    const std::vector<RelativeSEMeasurement> &measurements) {\n  SparseMatrix B1, B2, B3;\n  constructBMatrices(measurements, B1, B2, B3);\n\n  // Recover rotations\n  size_t d = (!measurements.empty() ? measurements[0].t.size() : 0);\n  unsigned int d2 = d * d;\n  assert(dimension == d);\n  assert(num_poses == (unsigned) B3.cols() / d2);\n\n  SparseMatrix B3red = B3.rightCols((num_poses - 1) * d2);\n  B3red.makeCompressed();  // Must be in compressed format to use\n  // Eigen::SparseQR!\n\n  // Vectorization of I_d\n  Eigen::MatrixXd Id = Eigen::MatrixXd::Identity(d, d);\n  Eigen::Map<Eigen::VectorXd> Id_vec(Id.data(), d2);\n\n  Eigen::VectorXd cR = B3.leftCols(d2) * Id_vec;\n\n  Eigen::VectorXd rvec;\n  Eigen::SPQR<SparseMatrix> QR(B3red);\n  rvec = -QR.solve(cR);\n\n  Matrix Rchordal(d, d * num_poses);\n  Rchordal.leftCols(d) = Id;\n  Rchordal.rightCols((num_poses - 1) * d) =\n      Eigen::Map<Eigen::MatrixXd>(rvec.data(), d, (num_poses - 1) * d);\n  for (unsigned int i = 1; i < num_poses; i++)\n    Rchordal.block(0, i * d, d, d) =\n        projectToRotationGroup(Rchordal.block(0, i * d, d, d));\n\n  // Recover translation\n  Matrix tchordal = recoverTranslations(B1, B2, Rchordal);\n  assert((unsigned) tchordal.rows() == dimension);\n  assert((unsigned) tchordal.cols() == num_poses);\n\n  // Assemble full pose\n  Matrix Tchordal(d, num_poses * (d + 1));\n  for (size_t i = 0; i < num_poses; i++) {\n    Tchordal.block(0, i * (d + 1), d, d) = Rchordal.block(0, i * d, d, d);\n    Tchordal.block(0, i * (d + 1) + d, d, 1) = tchordal.block(0, i, d, 1);\n  }\n\n  return Tchordal;\n}\n\nMatrix odometryInitialization(size_t dimension, size_t num_poses, const std::vector<RelativeSEMeasurement> &odometry) {\n  size_t d = dimension;\n  size_t n = num_poses;\n\n  Matrix T(d, n * (d + 1));\n  // Initialize first pose to be identity\n  T.block(0, 0, d, d) = Matrix::Identity(d, d);\n  T.block(0, d, d, 1) = Matrix::Zero(d, 1);\n  for (size_t src = 0; src < odometry.size(); ++src) {\n    size_t dst = src + 1;\n    const RelativeSEMeasurement &m = odometry[src];\n    assert(m.p1 == src);\n    assert(m.p2 == dst);\n    Matrix Rsrc = T.block(0, src * (d + 1), d, d);\n    Matrix tsrc = T.block(0, src * (d + 1) + d, d, 1);\n    Matrix Rdst = Rsrc * m.R;\n    Matrix tdst = tsrc + Rsrc * m.t;\n    T.block(0, dst * (d + 1), d, d) = Rdst;\n    T.block(0, dst * (d + 1) + d, d, 1) = tdst;\n  }\n  return T;\n}\n\nMatrix recoverTranslations(const SparseMatrix &B1, const SparseMatrix &B2,\n                           const Matrix &R) {\n  unsigned int d = R.rows();\n  unsigned int n = R.cols() / d;\n\n  // Vectorization of R matrix\n  Eigen::Map<Eigen::VectorXd> rvec((double *) R.data(), d * d * n);\n\n  // Form the matrix comprised of the right (n-1) block columns of B1\n  SparseMatrix B1red = B1.rightCols(d * (n - 1));\n\n  Eigen::VectorXd c = B2 * rvec;\n\n  // Solve\n  Eigen::SPQR<SparseMatrix> QR(B1red);\n  Eigen::VectorXd tred = -QR.solve(c);\n\n  // Reshape this result into a d x (n-1) matrix\n  Eigen::Map<Eigen::MatrixXd> tred_mat(tred.data(), d, n - 1);\n\n  // Allocate output matrix\n  Eigen::MatrixXd t = Eigen::MatrixXd::Zero(d, n);\n\n  // Set rightmost n-1 columns\n  t.rightCols(n - 1) = tred_mat;\n\n  return t;\n}\n\nMatrix projectToRotationGroup(const Matrix &M) {\n  // Compute the SVD of M\n  Eigen::JacobiSVD<Matrix> svd(M, Eigen::ComputeFullU | Eigen::ComputeFullV);\n\n  double detU = svd.matrixU().determinant();\n  double detV = svd.matrixV().determinant();\n\n  if (detU * detV > 0) {\n    return svd.matrixU() * svd.matrixV().transpose();\n  } else {\n    Eigen::MatrixXd Uprime = svd.matrixU();\n    Uprime.col(Uprime.cols() - 1) *= -1;\n    return Uprime * svd.matrixV().transpose();\n  }\n}\n\nMatrix projectToStiefelManifold(const Matrix &M) {\n  size_t r = M.rows();\n  size_t d = M.cols();\n  assert(r >= d);\n  Eigen::JacobiSVD<Matrix> svd(M, Eigen::ComputeThinU | Eigen::ComputeThinV);\n  return svd.matrixU() * svd.matrixV().transpose();\n}\n\nMatrix fixedStiefelVariable(unsigned d, unsigned r) {\n  std::srand(1);\n  ROPTLIB::StieVariable var(r, d);\n  var.RandInManifold();\n  return Eigen::Map<Matrix>((double *) var.ObtainReadData(), r, d);\n}\n\ndouble computeMeasurementError(const RelativeSEMeasurement &m,\n                               const Matrix &R1, const Matrix &t1,\n                               const Matrix &R2, const Matrix &t2) {\n  double rotationErrorSq = (R1 * m.R - R2).squaredNorm();\n  double translationErrorSq = (t2 - t1 - R1 * m.t).squaredNorm();\n  return m.kappa * rotationErrorSq + m.tau * translationErrorSq;\n}\n\ndouble chi2inv(double quantile, size_t dof) {\n  boost::math::chi_squared_distribution<double> chi2(dof);\n  return boost::math::quantile(chi2, quantile);\n}\n\ndouble angular2ChordalSO3(double rad) {\n  return 2 * sqrt(2) * sin(rad / 2);\n}\n\nvoid checkRotationMatrix(const Matrix &R) {\n  const auto d = R.rows();\n  assert(R.cols() == d);\n  assert(abs(R.determinant() - 1.0) < 1e-8);\n  assert((R.transpose() * R - Matrix::Identity(d, d)).norm() < 1e-8);\n}\n\nvoid singleTranslationAveraging(Vector &tOpt,\n                                const std::vector<Vector> &tVec,\n                                const Vector &tau) {\n  const int n = (int) tVec.size();\n  assert(n > 0);\n  const auto d = tVec[0].rows();\n  Vector tau_ = Vector::Ones(n);\n  if (tau.rows() == n) {\n    tau_ = tau;\n  }\n  Vector s = Vector::Zero(d);\n  double w = 0;\n  for (Eigen::Index i = 0; i < n; ++i) {\n    s += tau_(i) * tVec[i];\n    w += tau_(i);\n  }\n  tOpt = s / w;\n}\n\nvoid singleRotationAveraging(Matrix &ROpt,\n                             const std::vector<Matrix> &RVec,\n                             const Vector &kappa) {\n  const int n = (int) RVec.size();\n  assert(n > 0);\n  const auto d = RVec[0].rows();\n  Vector kappa_ = Vector::Ones(n);\n  if (kappa.rows() == n) {\n    kappa_ = kappa;\n  }\n  Matrix M = Matrix::Zero(d, d);\n  for (Eigen::Index i = 0; i < n; ++i) {\n    M += kappa_(i) * RVec[i];\n  }\n  ROpt = projectToRotationGroup(M);\n}\n\nvoid singlePoseAveraging(Matrix &ROpt, Vector &tOpt,\n                         const std::vector<Matrix> &RVec,\n                         const std::vector<Vector> &tVec,\n                         const Vector &kappa,\n                         const Vector &tau) {\n  assert(!RVec.empty());\n  assert(!tVec.empty());\n  assert(RVec.size() == tVec.size());\n  assert(RVec[0].rows() == tVec[0].rows());\n  singleTranslationAveraging(tOpt, tVec, tau);\n  singleRotationAveraging(ROpt, RVec, kappa);\n}\n\nvoid robustSingleRotationAveraging(Matrix &ROpt,\n                                   std::vector<size_t> &inlierIndices,\n                                   const std::vector<Matrix> &RVec,\n                                   const Vector &kappa,\n                                   double errorThreshold) {\n  const double w_tol = 1e-8;\n  const int n = (int) RVec.size();\n  assert(n > 0);\n  Vector kappa_ = Vector::Ones(n);\n  Vector weights_ = Vector::Ones(n);\n  if (kappa.rows() == n) {\n    kappa_ = kappa;\n  }\n  for (const auto &Ri: RVec) {\n    checkRotationMatrix(Ri);\n  }\n  // Initialize estimate\n  singleRotationAveraging(ROpt, RVec, kappa_);\n  Vector rSqVec = Vector::Zero(n);\n  for (Eigen::Index i = 0; i < n; ++i) {\n    rSqVec(i) = kappa_(i) * (ROpt - RVec[i]).squaredNorm();\n  }\n  // Initialize robust cost\n  double barc = errorThreshold;\n  double barcSq = barc * barc;\n  double muInit = barcSq / (2 * rSqVec.maxCoeff() - barcSq);\n  muInit = std::min(muInit, 1e-5);\n  // Negative values of initial mu corresponds to small residual errors. In this case skip applying GNC.\n  if (muInit > 0) {\n    RobustCostParameters params;\n    params.GNCBarc = barc;\n    params.GNCMaxNumIters = 1000;\n    params.GNCInitMu = muInit;\n    RobustCost cost(RobustCostType::GNC_TLS, params);\n    for (unsigned iter = 0; iter < params.GNCMaxNumIters; ++iter) {\n      // Update solution\n      singleRotationAveraging(ROpt, RVec, kappa_.cwiseProduct(weights_));\n      // Update weight\n      int nc = 0;\n      for (Eigen::Index i = 0; i < n; ++i) {\n        double rSq = kappa_(i) * (ROpt - RVec[i]).squaredNorm();\n        double wi = cost.weight(sqrt(rSq));\n        if (wi < w_tol || wi > 1 - w_tol) {\n          nc++;\n        }\n        weights_(i) = wi;\n      }\n      if (nc == n) {\n        break;\n      }\n      // Update GNC\n      cost.update();\n    }\n  }\n  // Retrieve inliers\n  inlierIndices.clear();\n  for (Eigen::Index i = 0; i < n; ++i) {\n    double wi = weights_(i);\n    if (wi > 1 - w_tol) {\n      inlierIndices.push_back(i);\n    }\n  }\n}\n\nvoid robustSinglePoseAveraging(Matrix &ROpt, Vector &tOpt,\n                               std::vector<size_t> &inlierIndices,\n                               const std::vector<Matrix> &RVec,\n                               const std::vector<Vector> &tVec,\n                               const Vector &kappa,\n                               const Vector &tau,\n                               double errorThreshold) {\n  const double w_tol = 1e-8;\n  const int n = (int) RVec.size();\n  assert(n > 0);\n  assert(tVec.size() == n);\n  Vector kappa_ = 10000 * Vector::Ones(n);\n  Vector tau_ = 100 * Vector::Ones(n);\n  Vector weights_ = Vector::Ones(n);\n  if (kappa.rows() == n) {\n    kappa_ = kappa;\n  }\n  if (tau.rows() == n) {\n    tau_ = tau;\n  }\n  for (const auto &Ri: RVec) {\n    checkRotationMatrix(Ri);\n  }\n  // Initialize estimate\n  singlePoseAveraging(ROpt,\n                      tOpt,\n                      RVec,\n                      tVec,\n                      kappa_.cwiseProduct(weights_),\n                      tau_.cwiseProduct(weights_));\n  Vector rSqVec = Vector::Zero(n);\n  for (Eigen::Index i = 0; i < n; ++i) {\n    rSqVec(i) = kappa_(i) * (ROpt - RVec[i]).squaredNorm() + tau_(i) * (tOpt - tVec[i]).squaredNorm();\n  }\n  // Initialize robust cost\n  double barc = errorThreshold;\n  double barcSq = barc * barc;\n  double muInit = barcSq / (2 * rSqVec.maxCoeff() - barcSq);\n  muInit = std::min(muInit, 1e-5);\n  // Negative values of initial mu corresponds to small residual errors. In this case skip applying GNC.\n  if (muInit > 0) {\n    RobustCostParameters params;\n    params.GNCBarc = barc;\n    params.GNCMaxNumIters = 10000;\n    params.GNCInitMu = muInit;\n    RobustCost cost(RobustCostType::GNC_TLS, params);\n    unsigned iter = 0;\n    for (iter = 0; iter < params.GNCMaxNumIters; ++iter) {\n      // Update solution\n      singlePoseAveraging(ROpt,\n                          tOpt,\n                          RVec,\n                          tVec,\n                          kappa_.cwiseProduct(weights_),\n                          tau_.cwiseProduct(weights_));\n      // Update weight\n      int nc = 0;\n      for (Eigen::Index i = 0; i < n; ++i) {\n        double rSq = kappa_(i) * (ROpt - RVec[i]).squaredNorm() + tau_(i) * (tOpt - tVec[i]).squaredNorm();\n        double wi = cost.weight(sqrt(rSq));\n        if (wi < w_tol || wi > 1 - w_tol) {\n          nc++;\n        }\n        weights_(i) = wi;\n      }\n      if (nc == n) {\n        break;\n      }\n      // Update GNC\n      cost.update();\n    }\n  }\n  // Retrieve inliers\n  inlierIndices.clear();\n  for (Eigen::Index i = 0; i < n; ++i) {\n    double wi = weights_(i);\n    if (wi > 1 - w_tol) {\n      inlierIndices.push_back(i);\n    }\n  }\n}\n\n}  // namespace DPGO\n", "meta": {"hexsha": "289307e7c9826e8cae49cbbb5c3ded38ce14645e", "size": 22944, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/DPGO_utils.cpp", "max_stars_repo_name": "mit-acl/dpgo", "max_stars_repo_head_hexsha": "e3ad763ce03758860448905004b5c3e16896fec3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 63.0, "max_stars_repo_stars_event_min_datetime": "2021-09-23T07:53:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T01:43:09.000Z", "max_issues_repo_path": "src/DPGO_utils.cpp", "max_issues_repo_name": "NamDinhRobotics/dpgo", "max_issues_repo_head_hexsha": "e3ad763ce03758860448905004b5c3e16896fec3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/DPGO_utils.cpp", "max_forks_repo_name": "NamDinhRobotics/dpgo", "max_forks_repo_head_hexsha": "e3ad763ce03758860448905004b5c3e16896fec3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2021-09-10T04:25:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T09:33:40.000Z", "avg_line_length": 32.1344537815, "max_line_length": 119, "alphanum_fraction": 0.5804131799, "num_tokens": 6796, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494678483918, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.4635403684597965}}
{"text": "/*******************************************************************************\n * Copyright 2013-2014 Sebastian Niemann <niemann@sra.uni-hannover.de>.\n * \n * Licensed under the MIT License (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http://opensource.org/licenses/MIT\n * \n * Developers:\n *   Sebastian Niemann - Lead developer\n *   Daniel Kiechle - Unit testing\n ******************************************************************************/\n#include <Expected.hpp>\nusing armadilloJava::Expected;\n\n#include <iostream>\nusing std::cout;\nusing std::endl;\n\n#include <utility>\nusing std::pair;\n\n#include <armadillo>\nusing arma::Col;\nusing arma::as_scalar;\n\n#include <InputClass.hpp>\nusing armadilloJava::InputClass;\n\n#include <Input.hpp>\nusing armadilloJava::Input;\n\nnamespace armadilloJava {\n  class ExpectedOOColVec : public Expected {\n    public:\n      ExpectedOOColVec() {\n        cout << \"Compute ExpectedOOColVec(): \" << endl;\n\n        vector<vector<pair<string, void*>>> inputs = Input::getTestParameters({\n          InputClass::OOColVec\n        });\n\n        for (vector<pair<string, void*>> input : inputs) {\n          _fileSuffix = \"\";\n\n          int n = 0;\n          for (pair<string, void*> value : input) {\n            switch (n) {\n              case 0:\n                _fileSuffix += value.first;\n                _ooColVec = *static_cast<Col<double>*>(value.second);\n                break;\n            }\n          }\n\n          cout << \"Using input: \" << _fileSuffix << endl;\n\n          expectedArmaAs_scalar();\n        }\n\n        cout << \"done.\" << endl;\n      }\n\n    protected:\n      Mat<double> _ooColVec;\n\n      void expectedArmaAs_scalar() {\n        cout << \"- Compute expectedArmaAs_scalar() ... \";\n        save<double>(\"Arma.as_scalar\", Col<double>({as_scalar(_ooColVec)}));\n        cout << \"done.\" << endl;\n      }\n  };\n}\n", "meta": {"hexsha": "4fc3625aa6de589b1194fc69696c835ca849cfd2", "size": 1931, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/cpp/src/ExpectedOOColVec.cpp", "max_stars_repo_name": "SebastianNiemann/ArmadilloJava", "max_stars_repo_head_hexsha": "061121e22708111a8df3a2da92f6278c3a581e26", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-01-06T02:13:36.000Z", "max_stars_repo_stars_event_max_datetime": "2018-04-15T07:43:53.000Z", "max_issues_repo_path": "src/test/cpp/src/ExpectedOOColVec.cpp", "max_issues_repo_name": "sebiniemann/ArmadilloJava", "max_issues_repo_head_hexsha": "061121e22708111a8df3a2da92f6278c3a581e26", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 33.0, "max_issues_repo_issues_event_min_datetime": "2019-10-20T21:53:37.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-20T21:53:47.000Z", "max_forks_repo_path": "src/test/cpp/src/ExpectedOOColVec.cpp", "max_forks_repo_name": "sebiniemann/ArmadilloJava", "max_forks_repo_head_hexsha": "061121e22708111a8df3a2da92f6278c3a581e26", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-08-06T17:01:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-16T18:45:14.000Z", "avg_line_length": 25.7466666667, "max_line_length": 80, "alphanum_fraction": 0.5447954428, "num_tokens": 432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494678483918, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.4635403639806208}}
{"text": "#ifndef _SIM_NODE_NETWORK_HPP_\n#define _SIM_NODE_NETWORK_HPP_ 1\n\n#include <functional>\n#include <vector>\n#include <list>\n#include <random>\n\n#include <Eigen/Dense>\n\n#include \"sim_node.hpp\"\n\nclass SimNodeNetwork {\n public:\n  typedef std::vector<double> IterationEstimate;\n\n  struct EstimateLog {\n    SimNode::Target target;\n    std::vector<IterationEstimate> estimates;\n\n    EstimateLog() : target(0.0, {0.0, 0.0}), estimates() {};\n  };\n\n  static const double NO_READING;\n\n  static std::vector<double> MaxDegreeConsensus(\n    const SimNode::CoordinatePair& target_location,\n    const SimNode& source_node,\n    const std::vector<SimNode>& nodes_in_network);\n\n  // static const std::function<double(int, int)> metropolis_consensus =\n  //   [] (int p_source_vertex, int p_SimNode::Target_vertex) -> double {\n  //       return 0.0;\n  //   }\n\n  SimNodeNetwork(\n    const std::function<double(SimNode, SimNode)>& p_consensus_method,\n    const double p_error_threshold);\n\n  ~SimNodeNetwork();\n\n  SimNodeNetwork& AddNode(\n    const double p_sensing_range,\n    const double p_communication_range,\n    const SimNode::CoordinatePair& p_coordinates);\n\n  std::vector<EstimateLog> BuildMapOfField(\n    const std::vector<SimNode::Target>& targets);\n\n  void PerformSensorSampling(\n    const SimNode::Target& target);\n\n  void PrepareNodesForConsensusFiltering(\n    const SimNode::Target& target);\n\n  EstimateLog PerformConsensusFiltering(\n    const SimNode::Target& target);\n\n  std::vector<SimNode> FindSubSetOfNodes(\n    const std::map<int, SimNode>& sensor_nodes,\n    const SimNode::CoordinatePair& target_location,\n    const std::function<bool(\n      const SimNode&,\n      const SimNode::CoordinatePair&\n    )>& CriteriaIsMet);\n\n  std::vector<double> CollectEstimatesFromNodes(\n    const SimNode::CoordinatePair& target_location);\n\n  double ComputeAverageReading(\n    const std::vector<SimNode> estimating_nodes,\n    const SimNode::CoordinatePair& target_location);\n\n  bool EstimatesHaveSufficientlyConverged(\n    const std::vector<double>& estimates,\n    const double average_reading) const;\n\n  bool EstimatesHaveNotSufficientlyConverged(\n    const std::vector<double>& estimates,\n    const double average_reading) const;\n\n\n private:\n  int next_node_id_;\n  double error_threshold_;\n  std::map<int, SimNode> sensor_nodes_;\n  SimNode::CoordinatePair average_node_location_;\n  std::vector<SimNode::CoordinatePair> target_locations_;\n  std::map<SimNode::CoordinatePair, double> average_readings_; // aka convergence values\n  std::function<double(SimNode, SimNode)> weight_strategy_;\n};\n\n#endif //_SIM_NODE_NETWORK_HPP_", "meta": {"hexsha": "b0d6dfd2c95629c10709436b01c1a07b46f37608", "size": 2599, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "CS791x_Fall14/Project02_ConsensusFilter/code/sim_node_network.hpp", "max_stars_repo_name": "T-R0D/Past-Courses", "max_stars_repo_head_hexsha": "0edc83a7bf09515f0d01d23a26df2ff90c0f458a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2017-03-13T17:32:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-27T16:51:22.000Z", "max_issues_repo_path": "CS791x_Fall14/Project02_ConsensusFilter/code/sim_node_network.hpp", "max_issues_repo_name": "T-R0D/Past-Courses", "max_issues_repo_head_hexsha": "0edc83a7bf09515f0d01d23a26df2ff90c0f458a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-29T19:54:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-29T19:54:52.000Z", "max_forks_repo_path": "CS791x_Fall14/Project02_ConsensusFilter/code/sim_node_network.hpp", "max_forks_repo_name": "T-R0D/Past-Courses", "max_forks_repo_head_hexsha": "0edc83a7bf09515f0d01d23a26df2ff90c0f458a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2016-10-18T03:31:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-29T13:23:10.000Z", "avg_line_length": 27.9462365591, "max_line_length": 88, "alphanum_fraction": 0.7422085417, "num_tokens": 637, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757645879592642, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.463540350824493}}
{"text": "////////////////////////////////////////////////////////////////////\n//                                                                //\n//    Copyright (c) 2019-20, UK Atomic Energy Authority (UKAEA)   //\n//                                                                //\n////////////////////////////////////////////////////////////////////\n\n/*!\n    @file\n    Defines the core numerical operations for all data manipulation within of the library.\n\n    @copyright UK Atomic Energy Authority (UKAEA) - 2019-20\n*/\n#ifndef CORE_NUMERICAL_HPP\n#define CORE_NUMERICAL_HPP\n\n#include <cmath>\n#include <vector>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/StdVector>\n\n#include \"common.hpp\"\n#include \"core/numericalfunctions.hpp\"\n#include \"core/numericalmacros.h\"\n\nPEAKINGDUCK_NAMESPACE_START(peakingduck)\nPEAKINGDUCK_NAMESPACE_START(core)\n\n    const int ArrayTypeDynamic = Eigen::Dynamic;\n\n    template<typename Scalar, int Size=ArrayTypeDynamic>\n    using Array1D = Eigen::Array<Scalar, Size, 1>;\n\n    using Array1Di = Array1D<int>;\n    using Array1Df = Array1D<float>;\n    using Array1Dd = Array1D<double>;\n\n    using DefaultType = double;\n  \n    /*!\n       @brief Represents a 1-dimensional data structure (basically a 1D Eigen array)\n        Dynamic array - most use cases will be determined at runtime (I am assuming).\n        We don't want anyone to know we are using Eigen beyond this file, since (in theory)\n        it should make it easier to change library if need be. We only really need the array\n        datastructure from Eigen and not much else and instead of reinventing the wheel,\n        we wrap Eigen array.\n\n        We wrap this with private inheritance on the Eigen type but there\n        are a lot of methods to expose, easy to add when/if we need them. \n        \n        Eigen array is pretty good, it has things like sqrt, exp on array coefficients, but \n        we need to extend this to other functions, so we use CRTP to do this.\n\n        For all of this, you may ask why not just use Eigen and use an alias?\n        Well for one, we don't need all of Eigen just the array, and not all\n        of the array type (we require a simpler interface). Additionally, at some\n        point we may wish to use another data structure as std::array for example.\n        In this case we just change the NumericalData class to wrap that instead.\n        If we change the alias this could break existing interfaces and APIs, causing\n        big changes later on. Since this datastructure is fundamental to everything\n        we need to make sure that we have this sorted properly first!\n    */\n    template<typename T=DefaultType, int Size=ArrayTypeDynamic>\n    struct NumericalData : private Array1D<T, Size>, \n                           public NumericalFunctions<NumericalData<T, Size>>\n    {\n            using value_type = T;\n\n            using BaseEigenArray = Array1D<value_type, Size>;\n\n            // typedef Array1Dd Base;\n            using BaseEigenArray::BaseEigenArray;\n\n            // This constructor allows you to construct Derived type from Eigen expressions\n            template<typename OtherDerived>\n            explicit NumericalData(const Eigen::ArrayBase<OtherDerived>& other)\n                : BaseEigenArray(other)\n            { }\n\n            // issue constructing with no arguments\n            // this aims to fix it\n            explicit NumericalData()\n            { \n                from_vector(std::vector<value_type>());\n            }\n\n            // This constructor allows you to construct from a std::vector\n            explicit NumericalData(const std::vector<value_type>& other)\n            { \n                from_vector(other);\n            }\n\n            // This method allows you to assign Eigen expressions to Derived type\n            template<typename OtherDerived>\n            NumericalData& operator=(const Eigen::ArrayBase <OtherDerived>& other)\n            {\n                this->BaseEigenArray::operator=(other);\n                return *this;\n            }\n\n            template<typename OtherDerived>\n            NumericalData& operator=(const Eigen::EigenBase<OtherDerived> &other)\n            {\n                this->BaseEigenArray::operator=(other);\n                return *this;\n            }\n\n            template<typename OtherDerived>\n            NumericalData& operator=(const Eigen::ReturnByValue<OtherDerived> &other)\n            {\n                this->BaseEigenArray::operator=(other);\n                return *this;\n            }\n\n            // This method allows you to assign Eigen expressions to Derived type\n            NumericalData& operator=(const std::vector<T>& other)\n            {\n                from_vector(other);\n                return *this;\n            }\n\n            // clang does not like this, but gcc does,\n            // not sure why?\n            // maybe private inheritance was not a good \n            // option, composition is too much effort though!\n            // using BaseEigenArray::Base;\n            // using BaseEigenArray::ArrayBase;\n            // using BaseEigenArray::DenseBase;\n            using BaseEigenArray::Base::eval;\n\n            // operations such as (x > 0).all()\n            using BaseEigenArray::Base::all;\n            using BaseEigenArray::Base::any;\n            using BaseEigenArray::Base::count;\n\n            using BaseEigenArray::Base::Zero;\n            using BaseEigenArray::Base::Ones;\n\n            // essential operations on arrays\n            using BaseEigenArray::operator<<;\n            using BaseEigenArray::operator>;\n            using BaseEigenArray::operator<;\n            using BaseEigenArray::operator=;\n            using BaseEigenArray::operator==;\n            using BaseEigenArray::operator*;\n            using BaseEigenArray::operator*=;\n            using BaseEigenArray::operator+;\n            using BaseEigenArray::operator+=;\n            using BaseEigenArray::operator-;\n            using BaseEigenArray::operator-=;\n            using BaseEigenArray::operator/;\n            using BaseEigenArray::operator/=;\n            using BaseEigenArray::operator new;\n            using BaseEigenArray::operator delete;\n\n            PEAKINGDUCK_NUMERICAL_OPERATOR_IMP_MACRO(NumericalData,BaseEigenArray,+)\n            PEAKINGDUCK_NUMERICAL_OPERATOR_IMP_MACRO(NumericalData,BaseEigenArray,-)\n            PEAKINGDUCK_NUMERICAL_OPERATOR_IMP_MACRO(NumericalData,BaseEigenArray,*)\n            PEAKINGDUCK_NUMERICAL_OPERATOR_IMP_MACRO(NumericalData,BaseEigenArray,/)\n\n            // entry access operations\n            using BaseEigenArray::operator[];\n            using BaseEigenArray::data;\n            using BaseEigenArray::size;\n            using BaseEigenArray::begin;\n            using BaseEigenArray::end;\n            using BaseEigenArray::segment;\n\n            inline void from_vector(const std::vector<value_type>& raw){\n                this->BaseEigenArray::operator=(BaseEigenArray::Map(raw.data(), raw.size()));\n            }\n\n            inline std::vector<value_type> to_vector() const{\n                return std::vector<value_type>(this->data(), this->data() + this->size());\n            }\n\n            // some useful predefined methods \n            // map\n            using BaseEigenArray::exp;\n            using BaseEigenArray::log;\n            using BaseEigenArray::sqrt;\n            using BaseEigenArray::square;\n            using BaseEigenArray::pow;\n            using BaseEigenArray::replicate;\n            using BaseEigenArray::reverse;\n            using BaseEigenArray::reverseInPlace;\n\n            // reduce\n            using BaseEigenArray::mean;\n            using BaseEigenArray::sum;\n            using BaseEigenArray::maxCoeff;\n            using BaseEigenArray::minCoeff;\n\n            // custom unary operations\n            using BaseEigenArray::unaryExpr;\n\n            // similar to python slicing,, but a bit more primative\n            // arr = [1, 4, 5, 2, 10, 2, 2, -8, 2]\n            // arr.slice(1, 3) == arr[1:3] == [4, 5]\n            // arr.slice(1, -2) == arr[1:-2] == [4, 5, 2, 10, 2, 2]\n            //\n            // can we add templates when sindex and eindex are known\n            // at compile time?\n            NumericalData<value_type> slice(int sindex, int eindex) const\n            {\n                if(eindex >= 0){\n                    return this->segment(sindex, eindex - sindex);\n                }\n                return this->segment(sindex, this->size() + eindex - sindex);\n            }\n\n            // uses the () operator with two indicies to do the slice\n            // no way (overload comma operator?) to do this with square []\n            // braces\n            NumericalData<value_type> operator()(int sindex, int eindex) const\n            {\n                return slice(sindex, eindex);\n            }\n\n            // TODO: These really belong in the numerical functions\n            // interface, but I am getting compilation problems due to template \n            // parameter of derived. To not waste anymore time, we leave it here for now.\n\n            /*!\n                @brief A simple function for filtering values above a certain\n                threshold (>=). This is useful to remove entries that are negative \n                for example.\n\n                Returns a new array\n            */\n            NumericalData ramp(const value_type& threshold) const\n            {\n                std::function<value_type(value_type)> imp = [&](const value_type& x){\n                    return (x >= threshold) ? x : 0;\n                };\n                return this->unaryExpr(imp);\n            }\n\n            /*!\n                @brief A simple function for filtering values above a certain\n                threshold (>=). This is useful to remove entries that are negative \n                for example.\n\n                Mutates underlying array\n            */\n            NumericalData& rampInPlace(const value_type& threshold)\n            {\n                this->BaseEigenArray::operator=(this->ramp(threshold));\n                return *this;\n            }\n    };\n\n    /*!\n        @brief Combine (concatenate) arrays into another.\n    */\n    template<typename T=DefaultType, int Size=ArrayTypeDynamic>\n    NumericalData<T, Size> combine(const NumericalData<T, ArrayTypeDynamic>& one, const NumericalData<T, ArrayTypeDynamic>& two){\n        NumericalData<T, Size> combined(one.size() + two.size());\n        combined << one.eval(), two.eval();\n        return combined;\n    }\n\n    /*!\n       @brief Given a list of values take nouter points either side of \n        the index given and ignore ninner points.\n\n            Examples:\n\n            1. \n                values = [8, 2, 5, 2, 6, 6, 9, 23, 12]\n                index = 4\n                nouter = 3\n                ninner = 0\n                includeindex = True\n\n                => [2, 5, 2, 6, 6, 9, 23]\n            2. \n                values = [8, 2, 5, 2, 6, 6, 9, 23, 12]\n                index = 4\n                nouter = 3\n                ninner = 0\n                includeindex = False\n\n                => [2, 5, 2, 6, 9, 23]\n            3. \n                values = [8, 2, 5, 2, 6, 6, 9, 23, 12]\n                index = 4\n                nouter = 3\n                ninner = 1\n                includeindex = True\n\n                => [2, 5, 6, 9, 23]\n            4. \n                values = [8, 2, 5, 2, 6, 6, 9, 23, 12]\n                index = 4\n                nouter = 3\n                ninner = 1\n                includeindex = False\n\n                => [2, 5, 9, 23]\n\n        Therefore:\n            - ninner >= 0\n            - ninner <= nouter\n            - index >= nouter\n            - index < values.size()\n\n        It will clip at (0, len(values))\n\n    */\n    template<typename T=DefaultType, int InputSize=ArrayTypeDynamic, int WindowSize=ArrayTypeDynamic>\n    NumericalData<T, WindowSize> window(const NumericalData<T, InputSize>& data, \n        int centerindex, int nouter=5, int ninner=0, bool includeindex=true){\n\n        // no funny business\n        assert(ninner <= nouter);\n        assert((centerindex >= 0) && (centerindex < static_cast<int>(data.size())));\n        assert(data.size() > 0);\n\n        const NumericalData<T, ArrayTypeDynamic> slicelower = data.slice(std::max(0, centerindex-nouter), \n                                                                         std::max(0, centerindex-ninner));\n        const NumericalData<T, ArrayTypeDynamic> sliceupper = data.slice(std::min(static_cast<int>(data.size()), centerindex+1+ninner), \n                                                                         std::min(static_cast<int>(data.size()), centerindex+1+nouter));\n\n        const size_t data_size = includeindex ? slicelower.size() + sliceupper.size() + 1 : slicelower.size() + sliceupper.size();\n        NumericalData<T, WindowSize> combined(data_size);\n        if(includeindex){\n            combined << slicelower.eval(), data[centerindex], sliceupper.eval();\n        }\n        else{\n            combined << slicelower.eval(), sliceupper.eval();\n        }\n        return combined;\n    }\n\nPEAKINGDUCK_NAMESPACE_END\nPEAKINGDUCK_NAMESPACE_END\n\n#endif // CORE_NUMERICAL_HPP\n", "meta": {"hexsha": "97b7e1500687ba3d4a102e541a9947e695f60cd9", "size": 13163, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/core/numerical.hpp", "max_stars_repo_name": "fispact/peakingduck", "max_stars_repo_head_hexsha": "748cfa2341710d99083db950a2d66ffb139eecf2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-12-26T17:49:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-21T03:10:45.000Z", "max_issues_repo_path": "include/core/numerical.hpp", "max_issues_repo_name": "fispact/peakingduck", "max_issues_repo_head_hexsha": "748cfa2341710d99083db950a2d66ffb139eecf2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 18.0, "max_issues_repo_issues_event_min_datetime": "2020-01-28T20:38:48.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-06T16:34:48.000Z", "max_forks_repo_path": "include/core/numerical.hpp", "max_forks_repo_name": "thomasms/peakingduck", "max_forks_repo_head_hexsha": "748cfa2341710d99083db950a2d66ffb139eecf2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-03-16T16:21:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T09:09:40.000Z", "avg_line_length": 38.6011730205, "max_line_length": 136, "alphanum_fraction": 0.5571678189, "num_tokens": 2881, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.6187804478040616, "lm_q1q2_score": 0.4635205211754276}}
{"text": "#include \"stdafx.h\"\n#include \"mscl/MicroStrain/MIP/Commands/GenericMipCommand.h\"\n#include \"ExposedInertialTypes.h\"\n#include <boost/math/constants/constants.hpp>\n\nnamespace mscl\n{\n    //////////  Matrix  //////////\n\n    Matrix_3x3::Matrix_3x3(float i00, float i01, float i02, float i10, float i11, float i12, float i20, float i21, float i22)\n    {\n        // Not sure why I need firstArray.  Just putting this list in the initialization below doesn't compile.\n        std::array<float, 3> firstRow{ i00, i01, i02 };\n        m_array = { firstRow,{ i10, i11, i12 },{ i20, i21, i22 } };\n    }\n\n    Matrix_3x3::Matrix_3x3(MipFieldValues data)\n    {\n        for (int i = 0; i < 3; i++)\n        {\n            for (int j = 0; j < 3; j++)\n            {\n                int index = (i * 3) + j;\n                m_array[i][j] = data[index].as_float();\n            }\n        }\n    }\n\n    Matrix_3x3::~Matrix_3x3()\n    { }\n\n    void Matrix_3x3::set(uint8 row, uint8 col, float value)\n    {\n        m_array[row][col] = value;\n    }\n    \n    float Matrix_3x3::operator() (uint8 row, uint8 col) const\n    {\n        return m_array.at(row).at(col);\n    }\n\n    float Matrix_3x3::at(uint8 row, uint8 col) const\n    {\n        return (*this)(row, col);\n    }\n\n    std::string Matrix_3x3::str() const\n    {\n        std::stringstream result;\n        result << \"[\";\n\n        //for every value in the Matrix\n        for (uint16 row = 0; row < 3; row++)\n        {\n            result << \"[\";\n            for (uint16 col = 0; col < 3; col++)\n            {\n                result << m_array[row][col];\n\n                //if this isn't the last column in the row\n                if (col != 2)\n                {\n                    //add a separator\n                    result << \",\";\n                }\n            }\n            result << \"]\";\n\n            //if this isn't the last row\n            if (row != 2)\n            {\n                //add a separator\n                result << \",\";\n            }\n        }\n\n        result << \"]\";\n\n        return result.str();\n    }\n\n    MipFieldValues Matrix_3x3::asMipFieldValues() const\n    {\n        MipFieldValues m;\n        for (int i = 0; i < 3; i++)\n        {\n            for (int j = 0; j < 3; j++)\n            {\n                m.push_back(Value::FLOAT(m_array[i][j]));\n            }\n        }\n\n        return m;\n    }\n\n    //////////  Quaternion  //////////\n    Quaternion::Quaternion() :\n        Matrix(1, 4, ValueType::valueType_float, ByteStream())\n    {\n        m_data.append_float(0);\n        m_data.append_float(0);\n        m_data.append_float(0);\n        m_data.append_float(0);\n    }\n\n    Quaternion::Quaternion(float q0, float q1, float q2, float q3) :\n        Matrix(1, 4, ValueType::valueType_float, ByteStream())\n    {\n        m_data.append_float(q0);\n        m_data.append_float(q1);\n        m_data.append_float(q2);\n        m_data.append_float(q3);\n    }\n\n    Quaternion::Quaternion(MipFieldValues data) :\n        Matrix(1, 4, ValueType::valueType_float, ByteStream())\n    {\n        for (int i = 0; i < 4; i++)\n        {\n            m_data.append_float(data[i].as_float());\n        }\n    }\n\n    float Quaternion::at(uint8 index) const\n    {\n        return as_floatAt(0, index);\n    }\n\n    void Quaternion::set(uint8 index, float val)\n    {\n        uint32 pos = getBytePos(0, index);\n        ByteStream valB;\n        valB.append_float(val);\n\n        for (uint32 i = 0; i < 4; i++)\n        {\n            uint32 replaceIndex = pos + i;\n            m_data.data()[replaceIndex] = valB[i];\n        }\n    }\n\n    void Quaternion::normalize()\n    {\n        float magnitude = 0.0f;\n        for (uint8 i = 0; i < 4; i++)\n        {\n            float val = at(i);\n            magnitude += val * val;\n        }\n\n        magnitude = sqrt(magnitude);\n\n        if (magnitude == 0)\n        {\n            return;\n        }\n\n        ByteStream b;\n        for (uint8 i = 0; i < 4; i++)\n        {\n            float val = at(i);\n            b.append_float(val / magnitude);\n        }\n\n        m_data = b;\n    }\n\n    MipFieldValues Quaternion::asMipFieldValues() const\n    {\n        MipFieldValues m;\n        for (uint8 i = 0; i < 4; i++)\n        {\n            m.push_back(Value::FLOAT(at(i)));\n        }\n\n        return m;\n    }\n\n    //////////  GeometricVector  //////////\n\n    GeometricVector::GeometricVector(float x_init, float y_init, float z_init, PositionVelocityReferenceFrame ref) :\n        vec_0(x_init),\n        vec_1(y_init),\n        vec_2(z_init),\n        referenceFrame(ref)\n    { }\n\n    GeometricVector::GeometricVector() :\n        vec_0(0),\n        vec_1(0),\n        vec_2(0),\n        referenceFrame(PositionVelocityReferenceFrame::ECEF)\n    { }\n\n    GeometricVector::~GeometricVector()\n    { }\n\n\n\n    //////////  TimeUpdate  //////////\n\n    TimeUpdate::TimeUpdate(double timeOfWeek, uint16 weekNumber, float timeAccuracy):\n        m_timeOfWeek(timeOfWeek),\n        m_weekNumber(weekNumber),\n        m_timeAccuracy(timeAccuracy)\n    {\n    }\n\n    TimeUpdate::~TimeUpdate()\n    {\n    }\n\n\n\n    //////////  HeadingUpdateOptions  //////////\n\n\n    InertialTypes::HeadingUpdateEnableOption HeadingUpdateOptions::AsOptionId() const\n    {\n        if (useInternalMagnetometer)\n        {\n            if (useInternalGNSSVelocityVector)\n            {\n                if (useExternalHeadingMessages)\n                    return InertialTypes::HeadingUpdateEnableOption::ENABLE_ALL;\n                else\n                    return InertialTypes::HeadingUpdateEnableOption::ENABLE_MAGNETOMETER_AND_GNSS;\n            }\n            else\n            {\n                if (useExternalHeadingMessages)\n                    return InertialTypes::HeadingUpdateEnableOption::ENABLE_MAGNETOMETER_AND_EXTERNAL;\n                else\n                    return InertialTypes::HeadingUpdateEnableOption::ENABLE_INTERNAL_MAGNETOMETER;\n            }\n        }\n        else\n        {\n            if (useInternalGNSSVelocityVector)\n            {\n                if (useExternalHeadingMessages)\n                    return InertialTypes::HeadingUpdateEnableOption::ENABLE_GNSS_AND_EXTERNAL;\n                else\n                    return InertialTypes::HeadingUpdateEnableOption::ENABLE_INTERNAL_GNSS;\n            }\n            else\n            {\n                if (useExternalHeadingMessages)\n                    return InertialTypes::HeadingUpdateEnableOption::ENABLE_EXTERNAL_MESSAGES;\n                else\n                    return InertialTypes::HeadingUpdateEnableOption::ENABLE_NONE;\n            }\n        }\n    }\n\n    //  This constructor converts a uint8 to a HeadingUpdateOptions object according to the Communications Protocol.\n    HeadingUpdateOptions::HeadingUpdateOptions(const InertialTypes::HeadingUpdateEnableOption& headingUpdateOption)\n    {\n        switch (headingUpdateOption)\n        {\n        case InertialTypes::HeadingUpdateEnableOption::ENABLE_NONE:\n            useInternalMagnetometer = false;\n            useInternalGNSSVelocityVector = false;\n            useExternalHeadingMessages = false;\n            break;\n        case InertialTypes::HeadingUpdateEnableOption::ENABLE_INTERNAL_MAGNETOMETER:\n            useInternalMagnetometer = true;\n            useInternalGNSSVelocityVector = false;\n            useExternalHeadingMessages = false;\n            break;\n        case InertialTypes::HeadingUpdateEnableOption::ENABLE_INTERNAL_GNSS:\n            useInternalMagnetometer = false;\n            useInternalGNSSVelocityVector = true;\n            useExternalHeadingMessages = false;\n            break;\n        case InertialTypes::HeadingUpdateEnableOption::ENABLE_EXTERNAL_MESSAGES:\n            useInternalMagnetometer = false;\n            useInternalGNSSVelocityVector = false;\n            useExternalHeadingMessages = true;\n            break;\n        case InertialTypes::HeadingUpdateEnableOption::ENABLE_MAGNETOMETER_AND_GNSS:\n            useInternalMagnetometer = true;\n            useInternalGNSSVelocityVector = true;\n            useExternalHeadingMessages = false;\n            break;\n        case InertialTypes::HeadingUpdateEnableOption::ENABLE_GNSS_AND_EXTERNAL:\n            useInternalMagnetometer = false;\n            useInternalGNSSVelocityVector = true;\n            useExternalHeadingMessages = true;\n            break;\n        case InertialTypes::HeadingUpdateEnableOption::ENABLE_MAGNETOMETER_AND_EXTERNAL:\n            useInternalMagnetometer = true;\n            useInternalGNSSVelocityVector = false;\n            useExternalHeadingMessages = true;\n            break;\n        case InertialTypes::HeadingUpdateEnableOption::ENABLE_ALL:\n            useInternalMagnetometer = true;\n            useInternalGNSSVelocityVector = true;\n            useExternalHeadingMessages = true;\n            break;\n        default:\n            throw Error_MipCmdFailed(\"An invalid option value was passed in to HeadingUpdateOptions.\");\n        }\n    }\n\n\n\n    //////////  EstimationControlOptions  //////////\n\n\n    uint16 EstimationControlOptions::AsUint16() const {\n        uint16 intValue = 0;\n\n        if (enableGyroBiasEstimation) {\n            intValue = intValue | InertialTypes::EstimationControlOption::ENABLE_GYRO_BIAS_ESTIMATION;\n        }\n\n        if (enableAccelBiasEstimation) {\n            intValue = intValue | InertialTypes::EstimationControlOption::ENABLE_ACCEL_BIAS_ESTIMATION;\n        }\n\n        if (enableGyroScaleFactorEstimation) {\n            intValue = intValue | InertialTypes::EstimationControlOption::ENABLE_GYRO_SCALE_FACTOR_ESTIMATION;\n        }\n\n        if (enableAccelScaleFactorEstimation) {\n            intValue = intValue | InertialTypes::EstimationControlOption::ENABLE_ACCEL_SCALE_FACTOR_ESTIMATION;\n        }\n\n        if (enableGNSSAntennaOffsetEstimation) {\n            intValue = intValue | InertialTypes::EstimationControlOption::ENABLE_GNSS_ANTENNA_OFFSET_ESTIMATION;\n        }\n\n        if (enableHardIronAutoCalibration) {\n            intValue = intValue | InertialTypes::EstimationControlOption::ENABLE_HARD_IRON_AUTO_CALIBRATION;\n        }\n\n        if (enableSoftIronAutoCalibration) {\n            intValue = intValue | InertialTypes::EstimationControlOption::ENABLE_SOFT_IRON_AUTO_CALIBRATION;\n        }\n\n        return intValue;\n    }\n\n    //  This constructor converts a uint16 to a EstimationControlOptions object according to the Communications Protocol.\n    EstimationControlOptions::EstimationControlOptions(const mscl::uint16& estimationControlData) {\n        enableGyroBiasEstimation = (estimationControlData & InertialTypes::EstimationControlOption::ENABLE_GYRO_BIAS_ESTIMATION) != 0;\n        enableAccelBiasEstimation = (estimationControlData & InertialTypes::EstimationControlOption::ENABLE_ACCEL_BIAS_ESTIMATION) != 0;\n        enableGyroScaleFactorEstimation = (estimationControlData & InertialTypes::EstimationControlOption::ENABLE_GYRO_SCALE_FACTOR_ESTIMATION) != 0;\n        enableAccelScaleFactorEstimation = (estimationControlData & InertialTypes::EstimationControlOption::ENABLE_ACCEL_SCALE_FACTOR_ESTIMATION) != 0;\n        enableGNSSAntennaOffsetEstimation = (estimationControlData & InertialTypes::EstimationControlOption::ENABLE_GNSS_ANTENNA_OFFSET_ESTIMATION) != 0;\n        enableHardIronAutoCalibration = (estimationControlData & InertialTypes::EstimationControlOption::ENABLE_HARD_IRON_AUTO_CALIBRATION) != 0;\n        enableSoftIronAutoCalibration = (estimationControlData & InertialTypes::EstimationControlOption::ENABLE_SOFT_IRON_AUTO_CALIBRATION) != 0;\n    }\n\n    DeviceStatusData::SystemState DeviceStatusData::systemState()\n    {\n        checkValue(m_systemState, \"systemState\");\n        return *m_systemState;\n    }\n\n    void DeviceStatusData::systemState(SystemState val)\n    {\n        m_systemState = val;\n    }\n\n    bool DeviceStatusData::gnssPowerStateOn() const\n    {\n        checkValue(m_gnssPowerStateOn, \"gnssPowerStateOn\");\n        return *m_gnssPowerStateOn;\n    }\n\n    void DeviceStatusData::gnssPowerStateOn(bool val)\n    {\n        m_gnssPowerStateOn = val;\n    }\n\n    PpsPulseInfo DeviceStatusData::gnss1PpsPulseInfo()\n    {\n        checkValue(m_gnss1PpsPulseInfo, \"gnss1PpsPulseInfo\");\n        return *m_gnss1PpsPulseInfo;\n    }\n\n    void DeviceStatusData::gnss1PpsPulseInfo(PpsPulseInfo val)\n    {\n        m_gnss1PpsPulseInfo = val;\n    }\n\n    StreamInfo DeviceStatusData::imuStreamInfo()\n    {\n        checkValue(m_imuStreamInfo, \"imuStreamInfo\");\n        return *m_imuStreamInfo;\n    }\n\n    void DeviceStatusData::imuStreamInfo(StreamInfo val)\n    {\n        m_imuStreamInfo = val;\n    }\n\n    StreamInfo DeviceStatusData::gnssStreamInfo()\n    {\n        checkValue(m_gnssStreamInfo, \"gnssStreamInfo\");\n        return *m_gnssStreamInfo;\n    }\n\n    void DeviceStatusData::gnssStreamInfo(StreamInfo val)\n    {\n        m_gnssStreamInfo = val;\n    }\n\n    StreamInfo DeviceStatusData::estimationFilterStreamInfo()\n    {\n        checkValue(m_estimationFilterStreamInfo, \"estimationFilterStreamInfo\");\n        return *m_estimationFilterStreamInfo;\n    }\n\n    void DeviceStatusData::estimationFilterStreamInfo(StreamInfo val)\n    {\n        m_estimationFilterStreamInfo = val;\n    }\n\n    DeviceMessageInfo DeviceStatusData::imuMessageInfo()\n    {\n        checkValue(m_imuMessageInfo, \"imuMessageInfo\");\n        return *m_imuMessageInfo;\n    }\n\n    void DeviceStatusData::imuMessageInfo(DeviceMessageInfo val)\n    {\n        m_imuMessageInfo = val;\n    }\n\n    DeviceMessageInfo DeviceStatusData::gnssMessageInfo()\n    {\n        checkValue(m_gnssMessageInfo, \"gnssMessageInfo\");\n        return *m_gnssMessageInfo;\n    }\n\n    void DeviceStatusData::gnssMessageInfo(DeviceMessageInfo val)\n    {\n        m_gnssMessageInfo = val;\n    }\n\n    PortInfo DeviceStatusData::comPortInfo()\n    {\n        checkValue(m_comPortInfo, \"comPortInfo\");\n        return *m_comPortInfo;\n    }\n\n    void DeviceStatusData::comPortInfo(PortInfo val)\n    {\n        m_comPortInfo = val;\n    }\n\n    PortInfo DeviceStatusData::usbPortInfo()\n    {\n        checkValue(m_usbPortInfo, \"usbPortInfo\");\n        return *m_usbPortInfo;\n    }\n\n    void DeviceStatusData::usbPortInfo(PortInfo val)\n    {\n        m_usbPortInfo = val;\n    }\n\n    bool DeviceStatusData::hasMagnetometer() const\n    {\n        checkValue(m_hasMagnetometer, \"hasMagnetometer\");\n        return *m_hasMagnetometer;\n    }\n\n    void DeviceStatusData::hasMagnetometer(bool val)\n    {\n        m_hasMagnetometer = val;\n    }\n\n    bool DeviceStatusData::magnetometerInitializationFailed() const\n    {\n        checkValue(m_magnetometerInitializationFailed, \"magnetometerInitializationFailed\");\n        return *m_magnetometerInitializationFailed;\n    }\n\n    void DeviceStatusData::magnetometerInitializationFailed(bool val)\n    {\n        m_magnetometerInitializationFailed = val;\n    }\n\n    bool DeviceStatusData::hasPressure() const\n    {\n        checkValue(m_hasPressure, \"hasPressure\");\n        return *m_hasPressure;\n    }\n\n    void DeviceStatusData::hasPressure(bool val)\n    {\n        m_hasPressure = val;\n    }\n\n    bool DeviceStatusData::pressureInitializationFailed() const\n    {\n        checkValue(m_pressureInitializationFailed, \"pressureInitializationFailed\");\n        return *m_pressureInitializationFailed;\n    }\n\n    void DeviceStatusData::pressureInitializationFailed(bool val)\n    {\n        m_pressureInitializationFailed = val;\n    }\n\n    bool DeviceStatusData::gnssReceiverInitializationFailed() const\n    {\n        checkValue(m_gnssReceiverInitializationFailed, \"gnssReceiverInitializationFailed\");\n        return *m_gnssReceiverInitializationFailed;\n    }\n\n    void DeviceStatusData::gnssReceiverInitializationFailed(bool val)\n    {\n        m_gnssReceiverInitializationFailed = val;\n    }\n\n    bool DeviceStatusData::coldStartOnPowerOn() const\n    {\n        checkValue(m_coldStartOnPowerOn, \"coldStartOnPowerOn\");\n        return *m_coldStartOnPowerOn;\n    }\n\n    void DeviceStatusData::coldStartOnPowerOn(bool val)\n    {\n        m_coldStartOnPowerOn = val;\n    }\n\n    TemperatureInfo DeviceStatusData::temperatureInfo()\n    {\n        checkValue(m_temperatureInfo, \"temperatureInfo\");\n        return *m_temperatureInfo;\n    }\n\n    void DeviceStatusData::temperatureInfo(TemperatureInfo val)\n    {\n        m_temperatureInfo = val;\n    }\n\n    InertialTypes::PowerState DeviceStatusData::powerState() const\n    {\n        checkValue(m_powerState, \"powerState\");\n        return *m_powerState;\n    }\n\n    void DeviceStatusData::powerState(InertialTypes::PowerState val)\n    {\n        m_powerState = val;\n    }\n\n    uint16 DeviceStatusData::gyroRange() const\n    {\n        checkValue(m_gyroRange, \"gyroRange\");\n        return *m_gyroRange;\n    }\n\n    void DeviceStatusData::gyroRange(uint16 val)\n    {\n        m_gyroRange = val;\n    }\n\n    uint16 DeviceStatusData::accelRange() const\n    {\n        checkValue(m_accelRange, \"accelRange\");\n        return *m_accelRange;\n    }\n\n    void DeviceStatusData::accelRange(uint16 val)\n    {\n        m_accelRange = val;\n    }\n\n    uint8 TareAxisValues::asUint8() const\n    {\n        return tarePitchAxis * InertialTypes::TARE_PITCH_AXIS\n            | tareRollAxis * InertialTypes::TARE_ROLL_AXIS\n            | tareYawAxis * InertialTypes::TARE_YAW_AXIS;\n    }\n\n    mscl::DeviceStatusMap DeviceStatusData::asMap() const\n    {\n        mscl::DeviceStatusMap statusMap;\n        mscl::DeviceStatusValueMap m = asValueMap();\n\n        for (auto kv : m)\n        {\n            statusMap[kv.first] = kv.second.as_string();\n        }\n\n        return statusMap;\n    }\n\n    mscl::DeviceStatusValueMap DeviceStatusData::asValueMap() const\n    {\n        mscl::DeviceStatusValueMap statusMap;\n        statusMap[ModelNumber] = mscl::Value::UINT16(modelNumber);\n        statusMap[StatusStructure_Value] = mscl::Value::UINT8(static_cast<uint8>(statusStructure));\n\n        if (isSet(m_systemState)) \n        {\n            statusMap[SystemState_Value] = mscl::Value::UINT16(static_cast<uint16>(m_systemState.get()));\n        }\n\n        if (isSet(m_gnss1PpsPulseInfo))\n        {\n            statusMap[gnss1PpsPulseInfo_Count] = mscl::Value::UINT32(m_gnss1PpsPulseInfo.get().count);\n            statusMap[gnss1PpsPulseInfo_LastTimeinMS] = mscl::Value::UINT32(m_gnss1PpsPulseInfo.get().lastTimeinMS);\n        }\n\n        if (isSet(m_gnssPowerStateOn)) {\n            statusMap[GnssPowerStateOn] = mscl::Value::BOOL(m_gnssPowerStateOn.get());\n        }\n\n        if (isSet(m_imuStreamInfo))\n        {\n            statusMap[ImuStreamInfo_Enabled] = mscl::Value::BOOL(m_imuStreamInfo.get().enabled);\n            statusMap[ImuStreamInfo_PacketsDropped] = mscl::Value::UINT32(m_imuStreamInfo.get().outgoingPacketsDropped);\n        }\n\n        if (isSet(m_gnssStreamInfo))\n        {\n            statusMap[GnssStreamInfo_Enabled] = mscl::Value::BOOL(m_gnssStreamInfo.get().enabled);\n            statusMap[GnssStreamInfo_PacketsDropped] = mscl::Value::UINT32(m_gnssStreamInfo.get().outgoingPacketsDropped);\n        }\n\n        if (isSet(m_estimationFilterStreamInfo))\n        {\n            statusMap[EstimationFilterStreamInfo_Enabled] = mscl::Value::BOOL(m_estimationFilterStreamInfo.get().enabled);\n            statusMap[EstimationFilterStreamInfo_PacketsDropped] = mscl::Value::UINT32(m_estimationFilterStreamInfo.get().outgoingPacketsDropped);\n        }\n\n        if (isSet(m_comPortInfo))\n        {\n            statusMap[ComPortInfo_BytesRead] = mscl::Value::UINT32(m_comPortInfo.get().bytesRead);\n            statusMap[ComPortInfo_BytesWritten] = mscl::Value::UINT32(m_comPortInfo.get().bytesWritten);\n            statusMap[ComPortInfo_OverrunsOnRead] = mscl::Value::UINT32(m_comPortInfo.get().overrunsOnRead);\n            statusMap[ComPortInfo_OverrunsOnWrite] = mscl::Value::UINT32(m_comPortInfo.get().overrunsOnWrite); // supported to features\n        }\n\n        if (isSet(m_imuMessageInfo))\n        {\n            statusMap[ImuMessageInfo_LastMessageReadinMS] = mscl::Value::UINT32(m_imuMessageInfo.get().lastMessageReadinMS);\n            statusMap[ImuMessageInfo_MessageParsingErrors] = mscl::Value::UINT32(m_imuMessageInfo.get().messageParsingErrors);\n            statusMap[ImuMessageInfo_MessagesRead] = mscl::Value::UINT32(m_imuMessageInfo.get().messagesRead);\n        }\n\n        if (isSet(m_gnssMessageInfo))\n        {\n            statusMap[GnssMessageInfo_LastMessageReadinMS] = mscl::Value::UINT32(m_gnssMessageInfo.get().lastMessageReadinMS);\n            statusMap[GnssMessageInfo_MessageParsingErrors] = mscl::Value::UINT32(m_gnssMessageInfo.get().messageParsingErrors);\n            statusMap[GnssMessageInfo_MessagesRead] = mscl::Value::UINT32(m_gnssMessageInfo.get().messagesRead);\n        }\n\n        if (isSet(m_temperatureInfo))\n        {\n            statusMap[TemperatureInfo_Error] = mscl::Value::UINT8(m_temperatureInfo.get().error);\n            statusMap[TemperatureInfo_LastReadInMS] = mscl::Value::UINT32(m_temperatureInfo.get().lastReadInMS);\n            statusMap[TemperatureInfo_OnBoardTemp] = mscl::Value::FLOAT(m_temperatureInfo.get().onBoardTemp);\n        }\n\n        if (isSet(m_powerState))\n        {\n            statusMap[PowerState] = mscl::Value::UINT8(static_cast<uint8>(m_powerState.get()));\n        }\n\n        if (isSet(m_gyroRange))\n        {\n            statusMap[GyroRange] = mscl::Value::UINT16(m_gyroRange.get());\n        }\n\n        if (isSet(m_accelRange))\n        {\n            statusMap[AccelRange] = mscl::Value::UINT16(m_accelRange.get());\n        }\n\n        if (isSet(m_hasMagnetometer))\n        {\n            statusMap[HasMagnetometer] = mscl::Value::BOOL(m_hasMagnetometer.get());\n        }\n\n        if (isSet(m_hasPressure))\n        {\n            statusMap[HasPressure] = mscl::Value::BOOL(m_hasPressure.get());\n        }\n\n        return statusMap;\n    }\n\n    uint8 RTKDeviceStatusFlags::state() const\n    {\n        return static_cast<uint8>(get(STATE));\n    }\n    \n    void RTKDeviceStatusFlags::state(uint8 rtkState)\n    {\n        set(STATE, rtkState);\n    }\n\n    uint8 RTKDeviceStatusFlags::statusCode() const\n    {\n        return static_cast<uint8>(get(STATUS_CODE));\n    }\n\n    void RTKDeviceStatusFlags::statusCode(uint8 code)\n    {\n        set(STATUS_CODE, code);\n    }\n\n    bool RTKDeviceStatusFlags::correctionsTimedOut() const\n    {\n        return get(CORRECTIONS_TIMED_OUT) > 0;\n    }\n\n    void RTKDeviceStatusFlags::correctionsTimedOut(bool timedOut)\n    {\n        set(CORRECTIONS_TIMED_OUT, (timedOut ? 1 : 0));\n    }\n\n    bool RTKDeviceStatusFlags::serviceUnavailable() const\n    {\n        return get(SERVICE_UNAVAILABLE) > 0;\n    }\n\n    void RTKDeviceStatusFlags::serviceUnavailable(bool available)\n    {\n        set(SERVICE_UNAVAILABLE, (available ? 1 : 0));\n    }\n\n    RTKDeviceStatusFlags::ResetReason RTKDeviceStatusFlags::resetReason() const\n    {\n        return static_cast<ResetReason>(get(RESET_REASON));\n    }\n\n    void RTKDeviceStatusFlags::resetReason(RTKDeviceStatusFlags::ResetReason reason)\n    {\n        set(RESET_REASON, static_cast<uint32>(reason));\n    }\n\n    bool RTKDeviceStatusFlags::modemPowered() const\n    {\n        return get(MODEM_POWERED) > 0;\n    }\n\n    void RTKDeviceStatusFlags::modemPowered(bool powered)\n    {\n        set(MODEM_POWERED, (powered ? 1 : 0));\n    }\n\n    bool RTKDeviceStatusFlags::cellConnected()\n    {\n        return get(CELL_CONNECTED) > 0;\n    }\n\n    void RTKDeviceStatusFlags::cellConnected(bool connected)\n    {\n        set(CELL_CONNECTED, (connected ? 1 : 0));\n    }\n\n    bool RTKDeviceStatusFlags::serverConnected()\n    {\n        return get(SERVER_CONNECTED) > 0;\n    }\n\n    void RTKDeviceStatusFlags::serverConnected(bool connected)\n    {\n        set(SERVER_CONNECTED, (connected ? 1 : 0));\n    }\n\n    bool RTKDeviceStatusFlags::dataEnabled()\n    {\n        return get(DATA_ENABLED) > 0;\n    }\n\n    void RTKDeviceStatusFlags::dataEnabled(bool enabled)\n    {\n        set(DATA_ENABLED, (enabled ? 1 : 0));\n    }\n\n    uint8 RTKDeviceStatusFlags::rssi() \n    {\n        return static_cast<uint8>(get(RSSI));\n    }\n\n    void RTKDeviceStatusFlags::rssi(uint8 rtkRssi)\n    {\n        set(RSSI, rtkRssi);\n    }\n\n    uint8 RTKDeviceStatusFlags::signalQuality() \n    {\n        return static_cast<uint8>(get(SIGNAL_QUALITY));\n    }\n\n    void RTKDeviceStatusFlags::signalQuality(uint8 quality)\n    {\n        set(SIGNAL_QUALITY, quality);\n    }\n\n    GnssSignalConfiguration::GnssSignalConfiguration()\n    {\n        m_gpsSignals = Bitfield(0);\n        m_glonassSignals = Bitfield(0);\n        m_galileoSignals = Bitfield(0);\n        m_beidouSignals = Bitfield(0);\n    }\n\n    void GnssSignalConfiguration::enableGpsSignal(GnssSignalConfiguration::GpsSignal signal, bool enable)\n    {\n        m_gpsSignals.set(signal, (enable ? 1 : 0));\n    }\n\n    bool GnssSignalConfiguration::gpsSignalEnabled(GnssSignalConfiguration::GpsSignal signal)\n    {\n        return m_gpsSignals.get(signal) > 0;\n    }\n\n    void GnssSignalConfiguration::enableGlonassSignal(GnssSignalConfiguration::GlonassSignal signal, bool enable)\n    {\n        m_glonassSignals.set(signal, (enable ? 1 : 0));\n    }\n\n    bool GnssSignalConfiguration::glonassSignalEnabled(GnssSignalConfiguration::GlonassSignal signal)\n    {\n        return m_glonassSignals.get(signal) > 0;\n    }\n\n    void GnssSignalConfiguration::enableGalileoSignal(GnssSignalConfiguration::GalileoSignal signal, bool enable)\n    {\n        m_galileoSignals.set(signal, (enable ? 1 : 0));\n    }\n\n    bool GnssSignalConfiguration::galileoSignalEnabled(GnssSignalConfiguration::GalileoSignal signal)\n    {\n        return m_galileoSignals.get(signal) > 0;\n    }\n\n    void GnssSignalConfiguration::enableBeiDouSignal(GnssSignalConfiguration::BeiDouSignal signal, bool enable)\n    {\n        m_beidouSignals.set(signal, (enable ? 1 : 0));\n    }\n\n    bool GnssSignalConfiguration::beidouSignalEnabled(GnssSignalConfiguration::BeiDouSignal signal)\n    {\n        return m_beidouSignals.get(signal) > 0;\n    }\n\n    OdometerConfiguration::Mode OdometerConfiguration::mode() const\n    {\n        return m_mode;\n    }\n\n    void OdometerConfiguration::mode(OdometerConfiguration::Mode m)\n    {\n        m_mode = m;\n    }\n\n    float OdometerConfiguration::scaling() const\n    {\n        return m_scaling;\n    }\n\n    void OdometerConfiguration::scaling(float scale)\n    {\n        if (scale == INFINITY)\n        {\n            m_scaling = 0;\n            return;\n        }\n\n        m_scaling = scale;\n    }\n\n    void OdometerConfiguration::scaling(float resolution, float radius)\n    {\n        if (resolution == 0 || radius == 0)\n        {\n            m_scaling = 0;\n        }\n\n        float mPerRev = radius * 2 * boost::math::constants::pi<float>();\n        m_scaling = resolution / mPerRev;\n    }\n\n    float OdometerConfiguration::uncertainty() const\n    {\n        return m_unc;\n    }\n\n    void OdometerConfiguration::uncertainty(float unc)\n    {\n        if (unc == INFINITY)\n        {\n            m_unc = 0.01f;\n            return;\n        }\n\n        m_unc = unc;\n    }\n}  // namespace mscl", "meta": {"hexsha": "b80d316ba9870a041f9f1c8af796d3acf944a6cb", "size": 26835, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "MSCL/source/mscl/MicroStrain/Inertial/ExposedInertialTypes.cpp", "max_stars_repo_name": "contagon/MSCL", "max_stars_repo_head_hexsha": "dc9029e7b7f83dc0eed5035ebb653102b0237060", "max_stars_repo_licenses": ["BSL-1.0", "OpenSSL", "MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MSCL/source/mscl/MicroStrain/Inertial/ExposedInertialTypes.cpp", "max_issues_repo_name": "contagon/MSCL", "max_issues_repo_head_hexsha": "dc9029e7b7f83dc0eed5035ebb653102b0237060", "max_issues_repo_licenses": ["BSL-1.0", "OpenSSL", "MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MSCL/source/mscl/MicroStrain/Inertial/ExposedInertialTypes.cpp", "max_forks_repo_name": "contagon/MSCL", "max_forks_repo_head_hexsha": "dc9029e7b7f83dc0eed5035ebb653102b0237060", "max_forks_repo_licenses": ["BSL-1.0", "OpenSSL", "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.7505543237, "max_line_length": 153, "alphanum_fraction": 0.6307806969, "num_tokens": 6658, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872243177519, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4635205175753152}}
{"text": "/*\n * 2018.5.4 kanda.motohiro@gmail.com C++ \u7df4\u7fd2\n * released under https://creativecommons.org/publicdomain/zero/1.0/legalcode.ja\n * based on https://www.boost.org/doc/libs/1_67_0/doc/html/date_time/examples.html\n */\n#include <boost/date_time/gregorian/gregorian.hpp>\n#include <boost/date_time/posix_time/posix_time.hpp>\n#include <chrono>\n#include <thread>\n#include \"base.h\"\n\nint main()\n{\n    chrono::high_resolution_clock::time_point a = chrono::high_resolution_clock::now();\n    this_thread::sleep_for(chrono::milliseconds{1});\n    chrono::high_resolution_clock::time_point b = chrono::high_resolution_clock::now();\n    chrono::nanoseconds c = chrono::duration_cast<chrono::nanoseconds>(b - a);\n    p(c.count());\n\n    boost::gregorian::date d(boost::gregorian::from_string(\"2018-5-4\"));\n    p(d);\n    boost::gregorian::date e(2000, 1, 1);\n    p(e);\n    boost::gregorian::date_duration f = d - e;\n    p(f);\n\n    boost::posix_time::ptime g(d, boost::posix_time::seconds{0});\n    p(g);\n    boost::posix_time::ptime h = g + boost::posix_time::hours{22};\n    p(h);\n}\n", "meta": {"hexsha": "9a93c21e2acace677ac067060057bd9624b87a09", "size": 1062, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "datetime.cpp", "max_stars_repo_name": "Kanda-Motohiro/cppsample", "max_stars_repo_head_hexsha": "6c010f4cc7a8143debf159435621966bf582f5d6", "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": "datetime.cpp", "max_issues_repo_name": "Kanda-Motohiro/cppsample", "max_issues_repo_head_hexsha": "6c010f4cc7a8143debf159435621966bf582f5d6", "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": "datetime.cpp", "max_forks_repo_name": "Kanda-Motohiro/cppsample", "max_forks_repo_head_hexsha": "6c010f4cc7a8143debf159435621966bf582f5d6", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.1875, "max_line_length": 87, "alphanum_fraction": 0.6892655367, "num_tokens": 304, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872243177518, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.46352051757531515}}
{"text": "#include <math.h>\n#include <iostream>\n#include <Eigen/Cholesky>\n#include <Eigen/LU>\n#include <Eigen/SVD>\n\n#include \"fastQP.h\"\n\n#define _USE_MATH_DEFINES\n\nextern \"C\"\n{\n\tint MAX_ITER = -1; // default: #equality constraints\n}\n\nusing namespace Eigen;\nusing namespace std;\n\n\n//template <typename tA, typename tB, typename tC, typename tD, typename tE, typename tF, typename tG>\n//int fastQPThatTakesQinv(vector< MatrixBase<tA>* > QinvblkDiag, const MatrixBase<tB>& f, const MatrixBase<tC>& Aeq, const MatrixBase<tD>& beq, const MatrixBase<tE>& Ain, const MatrixBase<tF>& bin, set<int>& active, MatrixBase<tG>& x)\nint fastQPThatTakesQinv(vector< MatrixXd* > QinvblkDiag, const VectorXd& f, const MatrixXd& Aeq, const VectorXd& beq, const MatrixXd& Ain, const VectorXd& bin, set<int>& active, VectorXd& x)\n{\n\n\tint max_iter = (MAX_ITER<0? (Aeq.rows()+Ain.rows()): MAX_ITER);\n\tint i,d;\n\tint iterCnt = 0;\n\n\tint M_in = bin.size();\n\tint M = Aeq.rows();\n\tint N = Aeq.cols();\n\n\tif (f.rows() != N) { cerr << \"size of f (\" << f.rows() << \" by \" << f.cols() << \") doesn't match cols of Aeq (\" << Aeq.rows() << \" by \" << Aeq.cols() << \")\" << endl; return -4; }\n\tif (beq.rows() !=M) { cerr << \"size of beq doesn't match rows of Aeq\" << endl; return -4; }\n\tif (Ain.cols() !=N) { cerr << \"cols of Ain doesn't match cols of Aeq\" << endl; return -4; };\n\tif (bin.rows() != Ain.rows()) { cerr << \"bin rows doesn't match Ain rows\" << endl; return -4; };\n\tif (x.rows() != N) { cerr << \"x doesn't match Aeq\" << endl; return -4; }\n\tint n_active = active.size();\n\n\tMatrixXd Aact = MatrixXd(n_active, N);\n\tVectorXd bact = VectorXd(n_active);\n\n\tMatrixXd QinvAteq(N,M);\n\tVectorXd minusQinvf(N);\n\n\t// calculate a bunch of stuff that is constant during each iteration\n\tint startrow=0;\n\t//  for (typename vector< MatrixBase<tA>* >::iterator iterQinv=QinvblkDiag.begin(); iterQinv!=QinvblkDiag.end(); iterQinv++) {\n\t//  \tMatrixBase<tA> *thisQinv = *iterQinv;\n\tfor (vector< MatrixXd* >::iterator iterQinv=QinvblkDiag.begin(); iterQinv!=QinvblkDiag.end(); iterQinv++) {\n\t\tMatrixXd *thisQinv = *iterQinv;\n\t\tint numRow = thisQinv->rows();\n\t\tint numCol = thisQinv->cols();\n\n\t\tif (numRow == 1 || numCol == 1) {  // it's a vector\n\t\t\td = numRow*numCol;\n\t\t\tif (M>0) QinvAteq.block(startrow,0,d,M)= thisQinv->asDiagonal()*Aeq.block(0,startrow,M,d).transpose();  // Aeq.transpo\u001bODse().block(startrow,0,d,N)\n\t\t\tminusQinvf.segment(startrow,d) = -thisQinv->cwiseProduct(f.segment(startrow,d));\n\t\t\tstartrow=startrow+d;\n\t\t} else { // potentially dense matrix\n\t\t\td = numRow;\n\t\t\tif (numRow!=numCol) {\n\t\t\t\tcerr << \"Q is not square! \" << numRow << \"x\" << numCol << \"\\n\";\n\t\t\t\treturn -2;\n\t\t\t}\n\n\t\t\tif (M>0) \n\t\t\t\tQinvAteq.block(startrow,0,d,M) = thisQinv->operator*(Aeq.block(0,startrow,M,d).transpose());  // Aeq.transpose().block(startrow,0,d,N)\n\n\t\t\tminusQinvf.segment(startrow,d) = -thisQinv->operator*(f.segment(startrow,d));\n\t\t\tstartrow=startrow+d;\n\t\t}\n\t\tif (startrow>N) {\n\t\t\tcerr << \"Q is too big!\" << endl;\n\t\t\treturn -2;\n\t\t}\n\t}\n\tif (startrow!=N) { cerr << \"Q is the wrong size.  Got \" << startrow << \"by\" << startrow << \" but needed \" << N << \"by\" << N << endl; return -2; }\n\n\tMatrixXd A;\n\tVectorXd b;\n\tMatrixXd QinvAt;\n\tVectorXd lam, lamIneq;\n\tVectorXd violated(M_in);\n\tVectorXd violation;\n\n\twhile(1) {\n\t\titerCnt++;\n\n\t\tn_active = active.size();\n\t\tAact.resize(n_active,N);\n\t\tbact.resize(n_active);\n\n\t\ti=0;\n\t\tfor (set<int>::iterator iter=active.begin(); iter!=active.end(); iter++) {\n\t\t\tif (*iter<0 || *iter>=Ain.rows()) {\n\t\t\t\treturn -3;  // active set is invalid.  exit quietly, because this is expected behavior in normal operation (e.g. it means I should immediately kick out to gurobi)\n\t\t\t}\n\t\t\tAact.row(i) = Ain.row(*iter);\n\t\t\tbact(i++) = bin(*iter);\n\t\t}\n\n\t\tA.resize(Aeq.rows() + Aact.rows(),N);\n\t\tb.resize(beq.size() + bact.size());\n\t\tA << Aeq,Aact;\n\t\tb << beq,bact;\n\n\t\tif (A.rows() > 0) {\n\t\t\t//Solve H * [x;lam] = [-f;b] using Schur complements, H = [Q,At';A,0];\n\t\t\tQinvAt.resize(QinvAteq.rows(), QinvAteq.cols() + Aact.rows());\n\n\t\t\tif (n_active>0) {\n\t\t\t\tint startrow=0;\n\t\t\t\tfor (vector< MatrixXd* >::iterator iterQinv=QinvblkDiag.begin(); iterQinv!=QinvblkDiag.end(); iterQinv++) {\n\t\t\t\t\tMatrixXd* thisQinv = (*iterQinv);\n\t\t\t\t\td = thisQinv->rows();\n\t\t\t\t\tint numCol = thisQinv->cols();\n\n\t\t\t\t\tif (numCol == 1) {  // it's a vector\n\t\t\t\t\t\tQinvAt.block(startrow,0,d,M+n_active) << QinvAteq.block(startrow,0,d,M), thisQinv->asDiagonal()*Aact.block(0,startrow,n_active,d).transpose();\n\t\t\t\t\t} else { // it's a matrix\n\t\t\t\t\t\tQinvAt.block(startrow,0,d,M+n_active) << QinvAteq.block(startrow,0,d,M), thisQinv->operator*(Aact.block(0,startrow,n_active,d).transpose());\n\t\t\t\t\t}\n\n\t\t\t\t\tstartrow=startrow+d;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tQinvAt = QinvAteq;\n\t\t\t}\n\n\t\t\tlam.resize(QinvAt.cols());\n#if 1\n\t\t\tlam = -(A*QinvAt).ldlt().solve(b + (f.transpose()*QinvAt).transpose());\n\t\t\t//lam = -(A*QinvAt + MatrixXd::Identity(A.rows(),A.rows())*1e-4).ldlt().solve(b + (f.transpose()*QinvAt).transpose());\n#else\n\t\t\tJacobiSVD<MatrixXd> svd(A*QinvAt , ComputeThinU | ComputeThinV);\n\t\t\tlam = -svd.solve(b + (f.transpose()*QinvAt).transpose());\n\t\t\tSingularValueType sigmas=svd.singularValues();\n#endif\n\t\t\tx = minusQinvf - QinvAt*lam;\n\t\t\tlamIneq = lam.tail(lam.size() - M);\n\t\t} else {\n\t\t\tx = minusQinvf;\n\t\t\tlamIneq.resize(0);\n\t\t}\n\n\t\tif(Ain.rows() == 0) {\n\t\t\tactive.clear();\n\t\t\tbreak;\n\t\t}\n\n\t\tset<int> new_active;\n\n\t\tviolation = Ain*x - bin;\n\t\tfor (i=0; i<M_in; i++)\n\t\t\tif (violation(i) >= 1e-6)\n\t\t\t\tnew_active.insert(i);\n\n\t\tbool all_pos_mults = true;\n\t\tfor (i=0; i<n_active; i++) {\n\t\t\tif (lamIneq(i)<0) {\n\t\t\t\tall_pos_mults = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (new_active.empty() && all_pos_mults) {\n\t\t\t// existing active was AOK\n\t\t\tbreak;\n\t\t}\n\n\t\ti=0;\n\t\tset<int>::iterator iter=active.begin(), tmp;\n\t\twhile (iter!=active.end()) { // to accomodating inloop erase\n\t\t\ttmp = iter++;\n\t\t\tif (lamIneq(i++)<0) {\n\t\t\t\tactive.erase(tmp);\n\t\t\t}\n\t\t}\n\t\tactive.insert(new_active.begin(),new_active.end());\n\n\n\t\tif (iterCnt > max_iter) {\n\t\t\treturn -1;\n\t\t}\n\t}  \n\treturn iterCnt;\n}\n\n//template <typename tA, typename tB, typename tC, typename tD, typename tE, typename tF, typename tG>\n//int fastQP(vector< MatrixBase<tA>* > QblkDiag, const MatrixBase<tB>& f, const MatrixBase<tC>& Aeq, const MatrixBase<tD>& beq, const MatrixBase<tE>& Ain, const MatrixBase<tF>& bin, set<int>& active, MatrixBase<tG>& x)\nint fastQP(vector< MatrixXd* > QblkDiag, const VectorXd& f, const MatrixXd& Aeq, const VectorXd& beq, const MatrixXd& Ain, const VectorXd& bin, set<int>& active, VectorXd& x)\n{\n\t/* min 1/2 * x'QblkDiag'x + f'x s.t A x = b, Ain x <= bin\n\t * using active set method.  Iterative solve a linearly constrained\n\t * quadratic minimization problem where linear constraints include\n\t * Ain(active,:)x == bin(active).  Quit if all dual variables associated\n\t * with these equations are positive (i.e. they satisfy KKT conditions).\n\t *\n\t * Note:\n\t * fails if QP is infeasible.\n\t * active == initial rows of Ain to treat as equations.\n\t * Frank Permenter - June 6th 2013\n\t *\n\t * @retval  if feasible then iterCnt, else -1 for infeasible, -2 for input error\n\t */\n\n\tint N = f.rows();\n\n\tMatrixXd* Qinv = new MatrixXd[QblkDiag.size()];\n\tvector< MatrixXd* > Qinvmap;\n\n#define REG 0.0\n\t// calculate a bunch of stuff that is constant during each iteration\n\tint startrow=0;\n\t//typedef typename vector< MatrixBase<tA> >::iterator Qiterator;\n\n\tint i=0;\n\tfor (vector< MatrixXd* >::iterator iterQ=QblkDiag.begin(); iterQ!=QblkDiag.end(); iterQ++) {\n\t\tMatrixXd* thisQ = *iterQ;\n\t\tint numRow = thisQ->rows();\n\t\tint numCol = thisQ->cols();\n\n\t\tif (numCol == 1) {  // it's a vector\n\t\t\tVectorXd Qdiag_mod = thisQ->operator+(VectorXd::Constant(numRow,REG)); // regularize\n\t\t\tQinv[i] = Qdiag_mod.cwiseInverse();\n\t\t\tQinvmap.push_back( &Qinv[i] );\n\t\t\tstartrow=startrow+numRow;\n\t\t} \n\t\telse \n\t\t{ // potentially dense matrix\n\t\t\tif (numRow!=numCol) {\n\t\t\t\tif (numRow==1)\n\t\t\t\t\tcerr << \"diagonal Q's must be set as column vectors\" << endl;\n\t\t\t\telse\n\t\t\t\t\tcerr << \"Q is not square! \" << numRow << \"x\" << numCol << endl;\n\t\t\t\treturn -2;\n\t\t\t}\n\n\t\t\tMatrixXd Q_mod = thisQ->operator+(REG*MatrixXd::Identity(numRow,numRow));\n\t\t\tQinv[i] = Q_mod.inverse();\n\t\t\tQinvmap.push_back( &Qinv[i] );\n\t\t\tstartrow=startrow+numRow;\n\t\t}\n\t\t//  \tcout << \"Qinv{\" << i << \"} = \" << Qinv[i] << endl;\n\t\tif (startrow>N) {\n\t\t\tcerr << \"Q is too big!\" << endl;\n\t\t\treturn -2;\n\t\t}\n\t\ti++;\n\t}\n\tif (startrow!=N) { cerr << \"Q is the wrong size.  Got \" << startrow << \"by\" << startrow << \" but needed \" << N << \"by\" << N << endl; return -2; }\n\n\tint info = fastQPThatTakesQinv(Qinvmap,f,Aeq,beq,Ain,bin,active,x);\n\n\tdelete[] Qinv;\n\treturn info;\n}\n\n/* Example call (allocate inequality matrix, call function, resize inequalites:\n   VectorXd binBnd = VectorXd(2*N);\n   AinBnd.setZero();\n   int numIneq = boundToIneq(ub,lb,AinBnd,binBnd);\n   AinBnd.resize(numIneq,N);\n   binBnd.resize(numIneq);\n   */\n/*\n   int boundToIneq(const VectorXd& uB,const VectorXd& lB, MatrixXd& Ain, VectorXd& bin)\n   {\n   int rCnt = 0;\n   int cCnt = 0;\n\n   if (uB.rows()+lB.rows() > A.rows() ) {\n   cerr << \"not enough memory allocated\";\n   }\n\n   if (uB.rows()+lB.rows() > b.rows() ) {\n   cerr << \"not enough memory allocated\";\n   }\n\n   for (int i = 0; i < lB.rows(); i++ ) {\n   if (!isinf(lB(i))) {\n   cout << lB(i);\n   cout << i;\n   Ain(rCnt,cCnt++) = -1;//lB(i);\n   bin(rCnt++) = -lB(i);\n   }\n   }\n   cCnt = 0;\n   for (int i = 0; i < uB.rows(); i++ ) {\n   if (!isinf(uB(i))) {\n   Ain(rCnt,cCnt++) = 1;//uB(i);\n   bin(rCnt++) = uB(i);\n   }\n   }\n\n//resizing inside function all causes exception (why??)\n//A.resize(rCnt,uB.rows());\nreturn rCnt;\n}\n*/\n\n\n\n\n\n/*\n   template int fastQP(vector< MatrixBase<MatrixXd>* > QblkDiag, const MatrixBase< Map<VectorXd> >&, const MatrixBase< Map<MatrixXd> >&, const MatrixBase< Map<VectorXd> >&, const MatrixBase< Map<MatrixXd> >&, const MatrixBase< Map<VectorXd> >&, set<int>&, MatrixBase< Map<VectorXd> >&);\n   template GRBmodel* gurobiQP(GRBenv *env, vector< MatrixBase<MatrixXd>* > QblkDiag, VectorXd& f, const MatrixBase< Map<MatrixXd> >& Aeq, const MatrixBase< Map<VectorXd> >& beq, const MatrixBase< Map<MatrixXd> >& Ain, const MatrixBase< Map<VectorXd> >&bin, VectorXd& lb, VectorXd& ub, set<int>&, VectorXd&);\n   template GRBmodel* gurobiQP(GRBenv *env, vector< MatrixBase<MatrixXd>* > QblkDiag, VectorXd& f, const MatrixBase< MatrixXd >& Aeq, const MatrixBase< VectorXd >& beq, const MatrixBase< MatrixXd >& Ain, const MatrixBase< VectorXd >&bin, VectorXd&lb, VectorXd&ub, set<int>&, VectorXd&);\n   */\n\n/*\n   template int fastQP(vector< MatrixBase< VectorXd > >, const MatrixBase< VectorXd >&, const MatrixBase< Matrix<double,-1,-1,RowMajor,1000,-1> >&, const MatrixBase< Matrix<double,-1,1,0,1000,1> >&, const MatrixBase< Matrix<double,-1,-1,RowMajor,1000,-1> >&, const MatrixBase< Matrix<double,-1,1,0,1000,1> >&, set<int>&, MatrixBase< VectorXd >&);\n   */\n\n\n\n", "meta": {"hexsha": "97fa2a64a9aba5feceda8a56215f77ef3f95c38c", "size": 10789, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CommonWalkingControlModules/csrc/ActiveSetQP/QP.cpp", "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": "CommonWalkingControlModules/csrc/ActiveSetQP/QP.cpp", "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": "CommonWalkingControlModules/csrc/ActiveSetQP/QP.cpp", "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": 33.927672956, "max_line_length": 346, "alphanum_fraction": 0.6347205487, "num_tokens": 3568, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4635205106431029}}
{"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_FUNCTION_FRAC_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_FRAC_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-ieee\n    Function object implementing frac capabilities\n\n    This function returns the fractional part of the input\n\n    @par Semantic:\n\n    @code\n    T r = frac(x);\n    @endcode\n\n    is similar to:\n\n    @code\n    T r =  x-trunc(x);\n    @endcode\n\n    @see trunc,  modf\n\n  **/\n  const boost::dispatch::functor<tag::frac_> frac = {};\n} }\n#endif\n\n#include <boost/simd/function/scalar/frac.hpp>\n#include <boost/simd/function/simd/frac.hpp>\n\n#endif\n", "meta": {"hexsha": "6b6a040e71c13bfc294e77c0b0fb7c8ba4818ffe", "size": 1048, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/frac.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/function/frac.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/function/frac.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": 21.387755102, "max_line_length": 100, "alphanum_fraction": 0.5629770992, "num_tokens": 230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.61878043374385, "lm_q1q2_score": 0.46352051064310285}}
{"text": "// triad_display.cpp\n// Wyatt Newman, 8/16\n// node to assist display of triads (axes) in rviz\n// this node subscribes to topic \"triad_display_pose\", from which it receives geometry_msgs/PoseStamped poses\n// it uses this info to populate and publish axes, using whatever frame_id is in the pose header\n// To see the result, add a \"Marker\" display in rviz and subscribe to the marker topic \"/triad_display\"\n// Can test this display node with the test node: \"triad_display_test_node\", which generates moving poses\n// corresponding to a marker origin spiraling up in z\n\n#include <ros/ros.h>\n#include <visualization_msgs/Marker.h>\n//#include <visualization_msgs/InteractiveMarkerFeedback.h>\n#include <geometry_msgs/Point.h>\n#include <geometry_msgs/PointStamped.h>\n#include <geometry_msgs/PoseStamped.h>\n#include <math.h>\n#include <Eigen/Eigen>  \n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <Eigen/Dense>\n#include <tf_conversions/tf_eigen.h>\n\n//some globals...\ngeometry_msgs::Point vertex1;\ngeometry_msgs::PoseStamped g_stamped_pose;\nEigen::Affine3d g_affine_marker_pose;\n\n// create arrow markers; do this 3 times to create a triad (frame)\nvisualization_msgs::Marker arrow_marker_x; //this one for the x axis\nvisualization_msgs::Marker arrow_marker_y; //this one for the y axis\nvisualization_msgs::Marker arrow_marker_z; //this one for the y axis\n\n//udpdate_arrows() set the frame and \n\nvoid update_arrows() {\n    geometry_msgs::Point origin, arrow_x_tip, arrow_y_tip, arrow_z_tip;\n    Eigen::Matrix3d R;\n    Eigen::Quaterniond quat;\n    quat.x() = g_stamped_pose.pose.orientation.x;\n    quat.y() = g_stamped_pose.pose.orientation.y;\n    quat.z() = g_stamped_pose.pose.orientation.z;\n    quat.w() = g_stamped_pose.pose.orientation.w;\n    R = quat.toRotationMatrix();\n    Eigen::Vector3d x_vec, y_vec, z_vec;\n    double veclen = 0.2; //make the arrows this long\n    x_vec = R.col(0) * veclen;\n    y_vec = R.col(1) * veclen;\n    z_vec = R.col(2) * veclen;\n\n    //update the arrow markers w/ new pose:\n    origin = g_stamped_pose.pose.position;\n    arrow_x_tip = origin;\n    arrow_x_tip.x += x_vec(0);\n    arrow_x_tip.y += x_vec(1);\n    arrow_x_tip.z += x_vec(2);\n    arrow_marker_x.points.clear();\n    arrow_marker_x.points.push_back(origin);\n    arrow_marker_x.points.push_back(arrow_x_tip);\n    arrow_marker_x.header = g_stamped_pose.header;\n\n    arrow_y_tip = origin;\n    arrow_y_tip.x += y_vec(0);\n    arrow_y_tip.y += y_vec(1);\n    arrow_y_tip.z += y_vec(2);\n\n    arrow_marker_y.points.clear();\n    arrow_marker_y.points.push_back(origin);\n    arrow_marker_y.points.push_back(arrow_y_tip);\n    arrow_marker_y.header = g_stamped_pose.header;\n\n    arrow_z_tip = origin;\n    arrow_z_tip.x += z_vec(0);\n    arrow_z_tip.y += z_vec(1);\n    arrow_z_tip.z += z_vec(2);\n\n    arrow_marker_z.points.clear();\n    arrow_marker_z.points.push_back(origin);\n    arrow_marker_z.points.push_back(arrow_z_tip);\n    arrow_marker_z.header = g_stamped_pose.header;\n}\n\n//init persistent params of markers, then variable coords    \n\nvoid init_markers() {\n    //initialize stamped pose for at a legal (if boring) pose\n    g_stamped_pose.header.stamp = ros::Time::now();\n    g_stamped_pose.header.frame_id = \"world\";\n    g_stamped_pose.pose.position.x = 0;\n    g_stamped_pose.pose.position.y = 0;\n    g_stamped_pose.pose.position.z = 0;\n    g_stamped_pose.pose.orientation.x = 0;\n    g_stamped_pose.pose.orientation.y = 0;\n    g_stamped_pose.pose.orientation.z = 0;\n    g_stamped_pose.pose.orientation.w = 1;\n\n    //the following parameters only need to get set once\n    arrow_marker_x.type = visualization_msgs::Marker::ARROW;\n    arrow_marker_x.action = visualization_msgs::Marker::ADD; //create or modify marker\n    arrow_marker_x.ns = \"triad_namespace\";\n    arrow_marker_x.lifetime = ros::Duration(); //never delete\n    // make the arrow thin\n    arrow_marker_x.scale.x = 0.01;\n    arrow_marker_x.scale.y = 0.01;\n    arrow_marker_x.scale.z = 0.01;\n    arrow_marker_x.color.r = 1.0; // red, for the x axis\n    arrow_marker_x.color.g = 0.0;\n    arrow_marker_x.color.b = 0.0;\n    arrow_marker_x.color.a = 1.0;\n    arrow_marker_x.id = 0;\n    arrow_marker_x.header = g_stamped_pose.header;\n\n    //y and z arrow params are the same, except for colors\n    arrow_marker_y = arrow_marker_x;\n    arrow_marker_y.color.r = 0.0;\n    arrow_marker_y.color.g = 1.0; //green for y axis\n    arrow_marker_y.color.b = 0.0;\n    arrow_marker_y.color.a = 1.0;\n    arrow_marker_y.id = 1;\n\n    arrow_marker_z = arrow_marker_x;\n    arrow_marker_z.id = 2;\n    arrow_marker_z.color.r = 0.0;\n    arrow_marker_z.color.g = 0.0;\n    arrow_marker_z.color.b = 1.0; //blue for z axis\n    arrow_marker_z.color.a = 1.0;\n    //set the poses of the arrows based on g_stamped_pose\n    update_arrows();\n}\n\nvoid poseCB(const geometry_msgs::PoseStamped &pose_msg) {\n    ROS_DEBUG(\"got pose message\");\n    //ROS_INFO(\"got pose message\");\n    g_stamped_pose.header = pose_msg.header;\n    g_stamped_pose.pose = pose_msg.pose;\n\n}\n\nint main(int argc, char** argv) {\n    ros::init(argc, argv, \"triad_display\"); // this will be the node name;\n    ros::NodeHandle nh;\n\n    // subscribe to stamped-pose publications\n    ros::Subscriber pose_sub = nh.subscribe(\"triad_display_pose\", 1, poseCB);\n    ros::Publisher vis_pub = nh.advertise<visualization_msgs::Marker>(\"triad_display\", 1);\n    init_markers();\n\n    ros::Rate timer(20); //timer to run at 20 Hz\n\n\n\n    while (ros::ok()) {\n        update_arrows();\n        vis_pub.publish(arrow_marker_x); //publish the marker\n        ros::Duration(0.01).sleep();\n        vis_pub.publish(arrow_marker_y); //publish the marker\n        ros::Duration(0.01).sleep();\n        vis_pub.publish(arrow_marker_z); //publish the marker\n        ros::spinOnce(); //let callbacks perform an update\n        timer.sleep();\n    }\n}\n\n\n", "meta": {"hexsha": "8ed4989e7303b913189111961a59e0763bc79835", "size": 5795, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Part_2/example_rviz_marker/src/triad_display.cpp", "max_stars_repo_name": "zhaolongkzz/ROS", "max_stars_repo_head_hexsha": "52c70d9d22fe1714c438312fde61214920a4dc3c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Part_2/example_rviz_marker/src/triad_display.cpp", "max_issues_repo_name": "zhaolongkzz/ROS", "max_issues_repo_head_hexsha": "52c70d9d22fe1714c438312fde61214920a4dc3c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Part_2/example_rviz_marker/src/triad_display.cpp", "max_forks_repo_name": "zhaolongkzz/ROS", "max_forks_repo_head_hexsha": "52c70d9d22fe1714c438312fde61214920a4dc3c", "max_forks_repo_licenses": ["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.3353658537, "max_line_length": 109, "alphanum_fraction": 0.7066436583, "num_tokens": 1549, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.749087201911703, "lm_q2_score": 0.6187804337438502, "lm_q1q2_score": 0.46352050371089065}}
{"text": "//\n//  Copyright Toon Knapen\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#include <iostream>\n#include <fstream>\n#include <string>\n#include <stdlib.h>\n#include <iomanip>\n\n#include \"blas.hpp\"\n#include <boost/numeric/bindings/blas/blas2.hpp>\n#include <boost/numeric/bindings/traits/ublas_vector.hpp>\n#include <boost/numeric/bindings/traits/ublas_matrix.hpp>\n\ntemplate < typename ValueType, typename MatrixType, typename VectorType >\nvoid test_gemv(std::ostream& os, int runs, int runs_i, int size, int size_i, char c, ValueType alpha, ValueType beta, MatrixType &a, VectorType& x, VectorType &y_native, VectorType &y_toblas)\n{\n  typedef typename VectorType::value_type value_type ;\n\n  boost::timer t ;\n  if ( c == boost::numeric::bindings::traits::NO_TRANSPOSE )    for(int i = 0 ; i < runs_i ; ++i ) y_native += alpha * numerics::prod( a, x) ;\n  else if ( c == boost::numeric::bindings::traits::TRANSPOSE )  for(int i = 0 ; i < runs_i ; ++i ) y_native += alpha * numerics::prod( trans(a), x) ;\n  else if ( c == boost::numeric::bindings::traits::CONJUGATE )  for(int i = 0 ; i < runs_i ; ++i ) y_native += alpha * numerics::prod( herm(a), x) ;\n  else assert( 0 ) ;\n  \n  report< value_type >( os, runs, runs_i, size_i, t.elapsed() );\n  \n  t.restart() ;\n  for(int i = 0 ; i < runs_i ; ++i ) boost::numeric::bindings::blas::gemv( c, alpha, a, x, beta, y_toblas ) ;\n  \n  report< value_type >( os, runs, runs_i, size_i, t.elapsed() );\n  \n  check( y_native.begin(), y_native.end(), y_toblas.begin() );\n}\n\ntemplate < typename T >\nstruct gemv_matrix_vector_vector\n{\n  void operator()(std::ostream& os, int size, int size_i, int runs, int runs_i)\n  {\n    runs_i = std::max( 1, runs_i / size_i ) ;\n\n    T alpha = 1 / ( size_i * 10 ), beta = 1.0 ;\n    random_initialise( alpha );\n    numerics::matrix< T, numerics::column_major > a(size_i,size_i) ;\n    random_initialise_matrix( a ) ;\n    numerics::vector< T > x( size_i ); \n    random_initialise_vector( x) ;\n    numerics::vector< T > y_native( x ) ;\n    numerics::vector< T > y_toblas( x ) ;\n      \n    test_gemv( os, runs, runs_i, size, size_i, boost::numeric::bindings::traits::NO_TRANSPOSE, alpha, beta, a, x, y_native, y_toblas );\n  }\n};\n\ntemplate < typename T >\nstruct gemv_trans_matrix_vector_vector\n{\n  void operator()(std::ostream& os, int size, int size_i, int runs, int runs_i)\n  {\n    runs_i = std::max( 1, runs_i / size_i ) ;\n\n    T alpha = 1 / ( size_i * 10 ), beta = 1.0 ;\n    random_initialise( alpha );\n    numerics::matrix< T, numerics::column_major > a(size_i,size_i) ;\n    random_initialise_matrix( a ) ;\n    numerics::vector< T > x( size_i ); \n    random_initialise_vector( x) ;\n    numerics::vector< T > y_native( x ) ;\n    numerics::vector< T > y_toblas( x ) ;\n      \n    test_gemv( os, runs, runs_i, size, size_i, boost::numeric::bindings::traits::TRANSPOSE, alpha, beta, a, x, y_native, y_toblas );\n  }\n};\n\ntemplate < typename T >\nstruct gemv_conj_matrix_vector_vector\n{\n  void operator()(std::ostream& os, int size, int size_i, int runs, int runs_i)\n  {\n    runs_i = std::max( 1, runs_i / size_i ) ;\n\n    T alpha = 1 / ( size_i * 10 ), beta = 1.0 ;\n    random_initialise( alpha );\n    numerics::matrix< T, numerics::column_major > a(size_i,size_i) ;\n    random_initialise_matrix( a ) ;\n    numerics::vector< T > x( size_i ); \n    random_initialise_vector( x) ;\n    numerics::vector< T > y_native( x ) ;\n    numerics::vector< T > y_toblas( x ) ;\n      \n    test_gemv( os, runs, runs_i, size, size_i, boost::numeric::bindings::traits::CONJUGATE, alpha, beta, a, x, y_native, y_toblas );\n  }\n};\n\ntemplate < typename T >\nstruct gemv_matrix_range_vector_vector\n{\n  void operator()(std::ostream& os, int size, int size_i, int runs, int runs_i)\n  {\n    runs_i = std::max( 1, runs_i / size_i ) ;\n\n    T alpha = 1 / ( size_i * 10 ), beta = 1.0 ;\n    random_initialise( alpha );\n    numerics::matrix< T, numerics::column_major > a(size_i * 2,size_i * 2) ;\n    random_initialise_matrix( a ) ;\n    int start = size_i / 2 ;\n    int stop = start + size_i ;\n    numerics::matrix_range< numerics::matrix< T, numerics::column_major > > mr( a, numerics::range( start, stop ), numerics::range( start, stop ) ) ;\n    numerics::vector< T > x( size_i ); \n    random_initialise_vector( x) ;\n    numerics::vector< T > y_native( x ) ;\n    numerics::vector< T > y_toblas( x ) ;\n      \n    test_gemv( os, runs, runs_i, size, size_i, boost::numeric::bindings::traits::NO_TRANSPOSE, alpha, beta, mr, x, y_native, y_toblas );\n  }\n};\n\nint main (int argc, char *argv []) \n{\n  int runs = 1 ; // 10000000 ;\n  int stop  = 10 ; // 10000 ;\n\n  switch ( argc ) {\n  case 3:\n    stop = atoi( argv[2] ) ;\n  case 2:\n    runs = atoi( argv[1] ) ;\n  case 1:\n  default: {}\n  }\n\n  int start = 1 ;\n  int step  = 50 ;\n\n  std::cerr << \"\\npeak float\\n\";\n  peak<float> () ( runs );\n\n  std::cerr << \"\\npeak double\\n\";\n  peak<double> () ( runs );\n\n  std::cerr << \"\\nstd:complex<float>\\n\";\n  peak<std::complex<float> > () ( runs );\n\n  std::cerr << \"\\nstd:complex<double>\\n\";\n  peak<std::complex<double> > () ( runs );\n\n  if (argc > 1) {\n    int scale = atoi(argv [1]);\n    runs *= scale ;\n  }\n\n  {\n    {\n      std::cerr <<         \"gemv_matrix_vector_vector_double\" << std::endl ;\n      std::ofstream stream(\"gemv_matrix_vector_vector_double\");\n      loop( stream, start, step, stop, runs, gemv_matrix_vector_vector<double>() ) ;\n    } \n    \n    {\n      std::cerr <<         \"gemv_matrix_vector_vector_double_complex\" << std::endl ;\n      std::ofstream stream(\"gemv_matrix_vector_vector_double_complex\");\n      loop( stream, start, step, stop, runs, gemv_matrix_vector_vector<std::complex<double> >() ) ;\n    }\n\n    {\n      std::cerr <<         \"gemv_trans_matrix_vector_vector_double\" << std::endl ;\n      std::ofstream stream(\"gemv_trans_matrix_vector_vector_double\");\n      loop( stream, start, step, stop, runs, gemv_trans_matrix_vector_vector<double>() ) ;\n    } \n    \n    {\n      std::cerr <<         \"gemv_trans_matrix_vector_vector_double_complex\" << std::endl ;\n      std::ofstream stream(\"gemv_trans_matrix_vector_vector_double_complex\");\n      loop( stream, start, step, stop, runs, gemv_trans_matrix_vector_vector<std::complex<double> >() ) ;\n    }\n\n    {\n      std::cerr <<         \"gemv_conj_matrix_vector_vector_double_complex\" << std::endl ;\n      std::ofstream stream(\"gemv_conj_matrix_vector_vector_double_complex\");\n      loop( stream, start, step, stop, runs, gemv_conj_matrix_vector_vector<std::complex<double> >() ) ;\n    }\n\n    {\n      std::cerr <<         \"gemv_matrix_range_vector_vector_double\" << std::endl ;\n      std::ofstream stream(\"gemv_matrix_range_vector_vector_double\");\n      loop( stream, start, step, stop, runs, gemv_matrix_range_vector_vector<double>() ) ;\n    } \n    \n    {\n      std::cerr <<         \"gemv_matrix_range_vector_vector_double_complex\" << std::endl ;\n      std::ofstream stream(\"gemv_matrix_range_vector_vector_double_complex\");\n      loop( stream, start, step, stop, runs, gemv_matrix_range_vector_vector<std::complex<double> >() ) ;\n    }\n  }\n\n  return 0 ;\n}\n\n\n", "meta": {"hexsha": "9787dc77c89a3c90dc3786ccb3d217549cd1b6e0", "size": 7144, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/blas/test/blas2.cpp", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-14T19:18:21.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-14T19:18:21.000Z", "max_issues_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/blas/test/blas2.cpp", "max_issues_repo_name": "diku-dk/PROX", "max_issues_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/blas/test/blas2.cpp", "max_forks_repo_name": "diku-dk/PROX", "max_forks_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-23T09:56:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-23T09:56:06.000Z", "avg_line_length": 34.6796116505, "max_line_length": 191, "alphanum_fraction": 0.6403975364, "num_tokens": 2104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.749087201911703, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.46352050371089054}}
{"text": "#ifndef _maps_Utils_hpp_\n#define _maps_Utils_hpp_\n\n#include <pcl/point_cloud.h>\n#include <Eigen/Geometry>\n#include <vector>\n\nnamespace maps {\n\nclass Utils {\n\npublic:\n\n  template<typename PointType>\n  static Eigen::Isometry3f\n  getPose(const pcl::PointCloud<PointType>& iCloud) {\n    Eigen::Isometry3f xform = Eigen::Isometry3f::Identity();\n    xform.linear() = iCloud.sensor_orientation_.matrix();\n    Eigen::Vector4f position = iCloud.sensor_origin_;\n    xform.translation() = position.head<3>();\n    return xform;\n  }\n\n  template<typename PointType>\n  static void\n  setPose(const Eigen::Isometry3f iPose, pcl::PointCloud<PointType>& oCloud) {\n    for (int i = 0; i < 3; ++i) {\n      oCloud.sensor_origin_[i] = iPose.translation()[i];\n    }\n    oCloud.sensor_origin_[3] = 1;\n    oCloud.sensor_orientation_ = iPose.rotation();\n  }\n\n  template<typename PointType1, typename PointType2>\n  static void copyPose(const pcl::PointCloud<PointType1>& iCloud,\n                       pcl::PointCloud<PointType2>& oCloud) {\n    oCloud.sensor_origin_ = iCloud.sensor_origin_;\n    oCloud.sensor_orientation_ = iCloud.sensor_orientation_;\n  }\n\n  template<typename PointType>\n  static bool crop(const pcl::PointCloud<PointType>& iCloud,\n                   pcl::PointCloud<PointType>& oCloud,\n                   const std::vector<Eigen::Vector4f>& iPlanes) {\n    std::vector<int> survivors;\n    if (!crop(iCloud, survivors, iPlanes)) {\n      return false;\n    }\n    oCloud.resize(iCloud.size());\n    for (int i = 0; i < survivors.size(); ++i) {\n      oCloud[i] = iCloud[survivors[i]];\n    }\n    oCloud.resize(survivors.size());\n    oCloud.width = oCloud.size();\n    oCloud.height = 1;\n    oCloud.is_dense = false;\n    copyPose(iCloud, oCloud);\n    return true;\n  }\n\n  template<typename PointType>\n  static bool crop(const pcl::PointCloud<PointType>& iCloud,\n                   std::vector<int>& oSurvivors,\n                   const std::vector<Eigen::Vector4f>& iPlanes) {\n    oSurvivors.clear();\n    oSurvivors.reserve(iCloud.size());\n    for (int i = 0; i < iCloud.size(); ++i) {\n      PointType pt = iCloud[i];\n      bool survived = true;\n      for (int j = 0; j < iPlanes.size(); ++j) {\n        Eigen::Vector4f plane = iPlanes[j].cast<float>();\n        if (plane[0]*pt.x + plane[1]*pt.y + plane[2]*pt.z < -plane[3]) {\n          survived = false;\n          continue;\n        }\n      }\n      if (survived) {\n        oSurvivors.push_back(i);\n      }\n    }\n    return true;\n  }\n\n\n  template<typename PointType>\n  static bool crop(const pcl::PointCloud<PointType>& iCloud,\n                   pcl::PointCloud<PointType>& oCloud,\n                   const Eigen::Vector3f& iMin, const Eigen::Vector3f& iMax) {\n    std::vector<int> survivors;\n    if (!crop(iCloud, survivors, iMin, iMax)) {\n      return false;\n    }\n    oCloud.resize(iCloud.size());\n    for (int i = 0; i < survivors.size(); ++i) {\n      oCloud[i] = iCloud[survivors[i]];\n    }\n    oCloud.resize(survivors.size());\n    oCloud.width = oCloud.size();\n    oCloud.height = 1;\n    oCloud.is_dense = false;\n    copyPose(iCloud, oCloud);\n    return true;\n  }\n\n  template<typename PointType>\n  static bool crop(const pcl::PointCloud<PointType>& iCloud,\n                   std::vector<int>& oSurvivors,\n                   const Eigen::Vector3f& iMin, const Eigen::Vector3f& iMax) {\n    oSurvivors.clear();\n    oSurvivors.reserve(iCloud.size());\n    for (int i = 0; i < iCloud.size(); ++i) {\n      PointType pt = iCloud[i];\n      if ((pt.x >= iMin[0]) && (pt.x <= iMax[0]) &&\n          (pt.y >= iMin[1]) && (pt.y <= iMax[1]) &&\n          (pt.z >= iMin[2]) && (pt.z <= iMax[2])) {\n        oSurvivors.push_back(i);\n      }\n    }\n    return true;\n  }\n\n\n  static bool clipRay(const Eigen::Vector3f& iOrigin,\n                      const Eigen::Vector3f& iEndPoint,\n                      const Eigen::Vector3f& iBoxMin,\n                      const Eigen::Vector3f& iBoxMax,\n                      Eigen::Vector3f& oOrigin,\n                      Eigen::Vector3f& oEndPoint,\n                      float& oMinT, float& oMaxT);\n\n  static bool clipRay(const Eigen::Vector3f& iOrigin,\n                      const Eigen::Vector3f& iEndPoint,\n                      const std::vector<Eigen::Vector4f>& iPlanes,\n                      Eigen::Vector3f& oOrigin,\n                      Eigen::Vector3f& oEndPoint,\n                      float& oMinT, float& oMaxT);\n\n  static std::vector<Eigen::Vector4f>\n  planesFromBox(const Eigen::Vector3f& iBoundMin,\n                const Eigen::Vector3f& iBoundMax);\n\n  static bool polyhedronFromPlanes(const std::vector<Eigen::Vector4f>& iPlanes,\n                                   std::vector<Eigen::Vector3f>& oVertices,\n                                   std::vector<std::vector<int> >& oFaces,\n                                   const double iTol=1e-5);\n\n  static std::vector<Eigen::Vector4f>\n  planesFromPolyhedron(const std::vector<Eigen::Vector3f>& iVertices,\n                       const std::vector<std::vector<int> >& iFaces);\n\n  static bool isOrthographic(const Eigen::Matrix4f& iMatrix);\n  static bool composeViewMatrix(Eigen::Projective3f& oMatrix,\n                                const Eigen::Matrix3f& iCalib,\n                                const Eigen::Isometry3f& iPose,\n                                const bool iIsOrthographic);\n  static bool factorViewMatrix(const Eigen::Projective3f& iMatrix,\n                               Eigen::Matrix3f& oCalib,\n                               Eigen::Isometry3f& oPose,\n                               bool& oIsOrthographic);\n\n  static uint64_t rand64();\n};\n\n}\n\n#endif\n", "meta": {"hexsha": "c80c669f97af8193c8b65a76d01b774c53aadc68", "size": 5583, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "software/perception/maps/src/Utils.hpp", "max_stars_repo_name": "liangfok/oh-distro", "max_stars_repo_head_hexsha": "eeee1d832164adce667e56667dafc64a8d7b8cee", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 92.0, "max_stars_repo_stars_event_min_datetime": "2016-01-14T21:03:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-01T17:57:46.000Z", "max_issues_repo_path": "software/perception/maps/src/Utils.hpp", "max_issues_repo_name": "liangfok/oh-distro", "max_issues_repo_head_hexsha": "eeee1d832164adce667e56667dafc64a8d7b8cee", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 62.0, "max_issues_repo_issues_event_min_datetime": "2016-01-16T18:08:14.000Z", "max_issues_repo_issues_event_max_datetime": "2016-03-24T15:16:28.000Z", "max_forks_repo_path": "software/perception/maps/src/Utils.hpp", "max_forks_repo_name": "liangfok/oh-distro", "max_forks_repo_head_hexsha": "eeee1d832164adce667e56667dafc64a8d7b8cee", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2016-01-14T21:26:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T03:10:39.000Z", "avg_line_length": 33.4311377246, "max_line_length": 79, "alphanum_fraction": 0.5789002328, "num_tokens": 1416, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.749087201911703, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.46352050371089054}}
{"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.\n// Modifications copyright (c) 2015 Oracle and/or its affiliates.\n\n// Contributed and/or modified by Menelaos Karavelas, on behalf of Oracle\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_GEOMETRY_ALGORITHMS_DETAIL_DIRECITON_CODE_HPP\n#define BOOST_GEOMETRY_ALGORITHMS_DETAIL_DIRECITON_CODE_HPP\n\n\n#include <boost/geometry/core/access.hpp>\n#include <boost/geometry/util/math.hpp>\n\nnamespace boost { namespace geometry\n{\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail\n{\n\ntemplate <std::size_t Index, typename Point1, typename Point2>\ninline int sign_of_difference(Point1 const& point1, Point2 const& point2)\n{\n    return\n        math::equals(geometry::get<Index>(point1), geometry::get<Index>(point2))\n        ?\n        0\n        :\n        (geometry::get<Index>(point1) > geometry::get<Index>(point2) ? 1 : -1);\n}\n\n\n// Gives sense of direction for point p, collinear w.r.t. segment (a,b)\n// Returns -1 if p goes backward w.r.t (a,b), so goes from b in direction of a\n// Returns 1 if p goes forward, so extends (a,b)\n// Returns 0 if p is equal with b, or if (a,b) is degenerate\n// Note that it does not do any collinearity test, that should be done before\ntemplate <typename Point1, typename Point2>\ninline int direction_code(Point1 const& segment_a, Point1 const& segment_b,\n                          const Point2& p)\n{\n    // Suppose segment = (4 3,4 4) and p =(4 2)\n    // Then sign_a1 = 1 and sign_p1 = 1 -> goes backward -> return -1\n\n    int const sign_a0 = sign_of_difference<0>(segment_b, segment_a);\n    int const sign_a1 = sign_of_difference<1>(segment_b, segment_a);\n\n    if (sign_a0 == 0 && sign_a1 == 0)\n    {\n        return 0;\n    }\n\n    int const sign_p0 = sign_of_difference<0>(segment_b, p);\n    int const sign_p1 = sign_of_difference<1>(segment_b, p);\n\n    if (sign_p0 == 0 && sign_p1 == 0)\n    {\n        return 0;\n    }\n\n    return sign_a0 == sign_p0 && sign_a1 == sign_p1 ? -1 : 1;\n}\n\n\n} // namespace detail\n#endif //DOXYGEN_NO_DETAIL\n\n\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_DIRECITON_CODE_HPP\n", "meta": {"hexsha": "26d53ab4e5927e7ee4aeee51b5c1586304a1d5c4", "size": 2369, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "nheqminer/3rdparty/boost/geometry/algorithms/detail/direction_code.hpp", "max_stars_repo_name": "EuroLine/nheqminer", "max_stars_repo_head_hexsha": "81c7ef889bb502d16f7d1e7ef020d0592f8af945", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 886.0, "max_stars_repo_stars_event_min_datetime": "2016-10-20T20:59:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T07:47:52.000Z", "max_issues_repo_path": "ios/Pods/boost-for-react-native/boost/geometry/algorithms/detail/direction_code.hpp", "max_issues_repo_name": "c7yrus/alyson-v3", "max_issues_repo_head_hexsha": "5ad95a8f782f5f5d2fd543d44ca6a8b093395965", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 369.0, "max_issues_repo_issues_event_min_datetime": "2016-10-21T07:42:54.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-19T10:49:29.000Z", "max_forks_repo_path": "ios/Pods/boost-for-react-native/boost/geometry/algorithms/detail/direction_code.hpp", "max_forks_repo_name": "c7yrus/alyson-v3", "max_forks_repo_head_hexsha": "5ad95a8f782f5f5d2fd543d44ca6a8b093395965", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 534.0, "max_forks_repo_forks_event_min_datetime": "2016-10-20T21:00:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T10:02:27.000Z", "avg_line_length": 29.6125, "max_line_length": 80, "alphanum_fraction": 0.696496412, "num_tokens": 658, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.749087201911703, "lm_q2_score": 0.6187804267137442, "lm_q1q2_score": 0.46352049844472826}}
{"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#include <math.h>\n\nnamespace caffe {\n\n    \n// \u8fd9\u4e9b\u516c\u5f0f\u53c2\u8003\u8fd9\u4e9b\uff1ahttps://blog.csdn.net/seven_first/article/details/47378697\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<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}\n\ntemplate void caffe_copy<int>(const int N, const int* X, int* Y);\ntemplate void caffe_copy<unsigned int>(const int N, const unsigned int* X,\n    unsigned int* Y);\ntemplate void caffe_copy<float>(const int N, const float* X, float* Y);\ntemplate void caffe_copy<double>(const int N, const double* X, double* Y);\n\ntemplate <>\nvoid caffe_scal<float>(const int N, const float alpha, float *X) {\n  cblas_sscal(N, alpha, X, 1);\n}\n\ntemplate <>\nvoid caffe_scal<double>(const int N, const double alpha, double *X) {\n  cblas_dscal(N, alpha, X, 1);\n}\n\ntemplate <>\nvoid caffe_cpu_axpby<float>(const int N, const float alpha, const float* X,\n                            const float beta, float* Y) {\n  cblas_saxpby(N, alpha, X, 1, beta, Y, 1);\n}\n\ntemplate <>\nvoid caffe_cpu_axpby<double>(const int N, const double alpha, const double* X,\n                             const double beta, double* Y) {\n  cblas_daxpby(N, alpha, X, 1, beta, Y, 1);\n}\n\ntemplate <>\nvoid caffe_add<float>(const int n, const float* a, const float* b,\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    \n/*********new added start***************************************************************************/\n\n// \u4ece\u8fd9\u5f80\u540e\u65b0\u52a0\u7684\u4ee3\u7801\ntemplate <>\nvoid caffe_clip<int>(const int n, int* y){\n// NOT IMPLEMENTED\n}\n\ntemplate <>\nvoid caffe_clip<unsigned int>(const int n, unsigned int* y){\n// NOT IMPLEMENTED\n}\n\ntemplate <>\nvoid caffe_clip<float>(const int n, float* y){\n  for(int i=0; i<n; i++){\n\tconst float x = y[i];\n\ty[i] = (x>1) - (x<1) + x * (x<=1 && x>=-1);\n  }\n}\n/* \u5b9e\u73b0\u7684\u529f\u80fd\uff1a\n       { -1, x<-1\nf(x) = {  x, |x|<=1\n       {  1, x>1\n*/\ntemplate <>\nvoid caffe_clip<double>(const int n, double* y){\n  for(int i=0; i<n; i++){\n\tconst double x = y[i];\n\ty[i] = (x>1) - (x<1) + x * (x<=1 && x>=-1);\n  }\n}\n\ntemplate <>\nvoid caffe_quantize<int>(const int N, const int left, const int right, const int* X, int *Y){\n// NOT IMPLEMENTED\n}\n\ntemplate <>\nvoid caffe_quantize<unsigned>(const int N, const unsigned left, const unsigned right, \nconst unsigned*X, unsigned* Y){\n// NOT IMPLEMENTED\n}\n\ntemplate <>\nvoid caffe_quantize<float>(const int N, const float left, const float right, const float* X, float* Y){\n  for(int i=0; i<N; i++){\n\tconst float x = X[i];\n\tfloat idx = (x >= 0) ? floor(log2(x)) : floor(log2(-x));\n\tidx = (idx<left)*left + (idx>=left && idx<=right)*idx + (idx>right)*right;\n\tfloat sign = (x>=0) ? 1.0f : -1.0f;\n\tfloat p_up = sign * x / pow(2.0f, idx) - 1;\n\tfloat idx_rand = idx + (p_up >= 0.5);\n\t\n\tY[i] = sign * pow(2.0f, idx_rand);\n  }\n}\n\ntemplate <>\nvoid caffe_quantize<double>(const int N, const double left, const double right, const double* X, double* Y){\n// \u53c2\u6570\u542b\u4e49\uff1a N\uff1a\u5143\u7d20\u4e2a\u6570 left\uff1a   right\uff1a     X\uff1a   Y\uff1a\n  for(int i=0; i<N; i++){\n\tconst double x = X[i];\n\tdouble idx = (x >= 0) ? floor(log2(x)) : floor(log2(-x)); // \u770b\u7edd\u5bf9\u503c\u8d85\u8fc71\uff0c\u7f6e1\uff0c\u5426\u5219\u4e3a0\n\tidx = (idx<left)*left + (idx>=left && idx<=right)*idx + (idx>right)*right;\n\tdouble sign = (x>=0) ? 1.0d : -1.0d;\n\tdouble p_up = sign * x / pow(2.0d, idx) - 1;\n\tdouble idx_rand = idx + (p_up >= 0.5);\n\t\n\tY[i] = sign * pow(2.0d, idx_rand);\n  }\n}\n\ntemplate<>\nvoid caffe_cpu_ternary<int>(const int N, const int delta, const int* X, int* Y){\n// NOT IMPLEMENTED\n}\n\ntemplate<>\nvoid caffe_cpu_ternary<unsigned>(const int N, const unsigned delta, const unsigned* X, unsigned* Y){\n// NOT IMPLEMENTED\n}\n\ntemplate<>\nvoid caffe_cpu_ternary<float>(const int N, const float delta, const float* X, float* Y){\n\tfor(int i=0; i<N; i++){\n\t\tfloat x = X[i];\n\t\tY[i] = (x>delta) - (x<-delta);\n\t}\n}\n\ntemplate<>\nvoid caffe_cpu_ternary<double>(const int N, const double delta, const double* X, double* Y){\n\tfor(int i=0; i<N; i++){\n\t\tdouble x = X[i];\n\t\tY[i] = (x>delta) - (x<-delta);\n\t}\n}\n\n\n///*## \u6211\u5199\u7684\u91cf\u5316\u516c\u5f0f start ---- ####################################################################*/\n///*\n//bit_width:\u91cf\u5316\u7684\u4f4d\u5bbd\n//\n//*/\n//template<>\n//void caffe_cpu_multi_bit_quantization<int>(const int N, const int bit_width, const int* X, int* Y){\n//// NOT IMPLEMENTED\n//}\n//\n//template<>\n//void caffe_cpu_multi_bit_quantization<unsigned>(const int N, const int bit_width, const unsigned* X, unsigned* Y){\n//// NOT IMPLEMENTED\n//}\n//\n//template<>\n//void caffe_cpu_multi_bit_quantization<float>(const int N, const int bit_width, const float* X, float* Y){\n//\tfor(int i=0; i<N; i++){\n//        caffe_clip(N, X);\n//\t\tfloat x = X[i];\n//\t\tY[i] = round((pow(2,bit_width)-1.0)*x)/(pow(2,bit_width)-1.0);\n//\t}\n//}\n//\n//template<>\n//void caffe_cpu_multi_bit_quantization<double>(const int N, const int bit_width, const double* X, double* Y){\n//\tfor(int i=0; i<N; i++){\n//\t\tcaffe_clip(N, X);\n//\t\tdouble x = X[i];\n//\t\tY[i] = round((pow(2,bit_width)-1.0)*x)/(pow(2,bit_width)-1.0);\n//\t}\n//}\n///*## \u6211\u5199\u7684\u91cf\u5316\u516c\u5f0f end ---- ####################################################################*/\n\n/*********new added end********************************************************************************/\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 <>\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/*\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 <>\nint caffe_cpu_dot<int>(const int n, const int* x, const int* y){\n  // return caffe_cpu_strided_dot(n, x, 1, y, 1);\n  return 0;\n// NOT IMPLEMENTED\n}\n\ntemplate <>\nunsigned caffe_cpu_dot<unsigned>(const int n, const unsigned* x, const unsigned* y){\n  // return caffe_cpu_strided_dot(n, x, 1, y, 1);\n  return 0;\n// NOT IMPLEMENTED\n}\n\ntemplate <>\nfloat caffe_cpu_dot<float>(const int n, const float* x, const float* y){\n  return caffe_cpu_strided_dot(n, x, 1, y, 1);\n}\n\ntemplate <>\ndouble caffe_cpu_dot<double>(const int n, const double* x, const double* y){\n  return caffe_cpu_strided_dot(n, x, 1, y, 1);\n}\n \ntemplate <>\nint caffe_cpu_asum<int>(const int n, const int* x){\nreturn 0;\n// NOT IMPLEMENTED YET\n}\n\ntemplate <>\nunsigned caffe_cpu_asum<unsigned>(const int n, const unsigned* x){\nreturn 0;\n// NOT IMPLEMENTED YET\n}\n\n \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}\ntemplate <>\nvoid caffe_cpu_scale<int>(const int n, const int alpha, const int* x, int* y){\n// NOT IMPLEMENTED YET\n}\n\ntemplate <>\nvoid caffe_cpu_scale<unsigned>(const int n, const unsigned alpha, const unsigned* x, unsigned* y){\n// NOT IMPLEMENTED YET\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": "18b5d3cd9f1ca6263a04665b65e45c14d65e222c", "size": 15141, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/caffe/util/math_functions.cpp", "max_stars_repo_name": "chaowang1994/caffe_twns_cuda9.1", "max_stars_repo_head_hexsha": "1dfecf6c1d6e00e6e3d6bd6ae3f4b9ab2c9ed89a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-12-12T02:51:17.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-12T02:51:17.000Z", "max_issues_repo_path": "src/caffe/util/math_functions.cpp", "max_issues_repo_name": "chaowang1994/caffe_twns_cuda9.1", "max_issues_repo_head_hexsha": "1dfecf6c1d6e00e6e3d6bd6ae3f4b9ab2c9ed89a", "max_issues_repo_licenses": ["MIT"], "max_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": "chaowang1994/caffe_twns_cuda9.1", "max_forks_repo_head_hexsha": "1dfecf6c1d6e00e6e3d6bd6ae3f4b9ab2c9ed89a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-12-12T02:51:23.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-12T02:51:23.000Z", "avg_line_length": 26.7508833922, "max_line_length": 116, "alphanum_fraction": 0.6335777029, "num_tokens": 4619, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256631249077, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.46351541061316215}}
{"text": "/*\n  High Performance Astrophysical Reconstruction and Processing (HARP)\n  (c) 2014-2015, The Regents of the University of California, \n  through Lawrence Berkeley National Laboratory.  See top\n  level LICENSE file for details.\n*/\n\n#ifndef HARP_LINALG_HPP\n#define HARP_LINALG_HPP\n\n\n#include <boost/numeric/ublas/operation.hpp>\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/matrix_proxy.hpp>\n#include <boost/numeric/ublas/matrix_sparse.hpp>\n#include <boost/numeric/ublas/storage.hpp>\n\n#include <boost/numeric/bindings/ublas.hpp>\n#include <boost/numeric/bindings/blas.hpp>\n#include <boost/numeric/bindings/lapack.hpp>\n#include <boost/numeric/bindings/views.hpp>\n\n\nnamespace harp {\n\n  typedef enum {\n    EIG_NONE,\n    EIG_SQRT,\n    EIG_INVSQRT,\n    EIG_INV\n  } eigen_op;\n\n  typedef boost::numeric::ublas::matrix < double, boost::numeric::ublas::column_major > matrix_double;\n\n  typedef boost::numeric::ublas::compressed_matrix < double, boost::numeric::ublas::row_major > matrix_double_sparse;\n\n  typedef boost::numeric::ublas::vector < double > vector_double;\n\n  typedef boost::numeric::ublas::matrix < uint8_t, boost::numeric::ublas::column_major > matrix_mask;\n\n  typedef boost::numeric::ublas::vector < uint8_t > vector_mask;\n\n  typedef boost::numeric::ublas::matrix < float, boost::numeric::ublas::column_major > matrix_float;\n\n  typedef boost::numeric::ublas::compressed_matrix < float, boost::numeric::ublas::row_major > matrix_float_sparse;\n\n  typedef boost::numeric::ublas::vector < float > vector_float;\n\n\n  void check_column_major ( boost::numeric::ublas::column_major_tag );\n\n\n  void check_column_major ( boost::numeric::ublas::row_major_tag );\n\n\n  template < class M >\n  void check_column_major ( boost::numeric::ublas::matrix_expression < M > const & matrix ) {\n    typedef typename M::orientation_category orientation_category;\n    check_column_major ( orientation_category() );\n    return;\n  }\n\n\n  void eigen_decompose ( matrix_double const & invcov, vector_double & D, matrix_double & W, bool regularize );\n\n  void eigen_compose ( eigen_op op, vector_double const & D, matrix_double const & W, matrix_double & out );\n\n  void column_norm ( matrix_double const & mat, vector_double & S );\n\n  void apply_norm ( vector_double const & S, matrix_double & mat );\n\n  void apply_inverse_norm ( vector_double const & S, matrix_double & mat );\n\n  void apply_norm ( vector_double const & S, vector_double & vec );\n\n  void apply_inverse_norm ( vector_double const & S, vector_double & vec );\n\n  void norm ( vector_double const & D, matrix_double const & W, vector_double & S );\n\n  void sparse_mv_trans ( matrix_double_sparse const & AT, vector_double const & in, vector_double & out );\n\n\n}\n\n\n#endif\n", "meta": {"hexsha": "e421ad2fb5ef6b5d13517fe4507be6e276259f04", "size": 2816, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/libharp/math/harp/linalg.hpp", "max_stars_repo_name": "tskisner/HARP", "max_stars_repo_head_hexsha": "e21435511c3dc95ce1318c852002a95ca59634b1", "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": "src/libharp/math/harp/linalg.hpp", "max_issues_repo_name": "tskisner/HARP", "max_issues_repo_head_hexsha": "e21435511c3dc95ce1318c852002a95ca59634b1", "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": "src/libharp/math/harp/linalg.hpp", "max_forks_repo_name": "tskisner/HARP", "max_forks_repo_head_hexsha": "e21435511c3dc95ce1318c852002a95ca59634b1", "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": 31.6404494382, "max_line_length": 117, "alphanum_fraction": 0.7468039773, "num_tokens": 692, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.46349311603446985}}
{"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#include \"rotationalinertia.hpp\"\n#include <Eigen/Core>\n\n\nnamespace KDL\n{\n\tRotationalInertia::RotationalInertia(double Ixx,double Iyy,double Izz,double Ixy,double Ixz,double Iyz)\n\t{\n        data[0]=Ixx;\n        data[1]=data[3]=Ixy;\n        data[2]=data[6]=Ixz;\n        data[4]=Iyy;\n        data[5]=data[7]=Iyz;\n        data[8]=Izz;\n        \n\t}\n\n\tRotationalInertia::~RotationalInertia()\n\t{\n\t}\n\n\tVector RotationalInertia::operator*(const Vector& omega) const {\n\t\t// Complexity : 9M+6A\n        Vector result;\n        Eigen::Map<Eigen::Vector3d>(result.data) = Eigen::Map<const Eigen::Matrix3d>(this->data) * Eigen::Map<const Eigen::Vector3d>(omega.data);\n        return result;\n \t}\n\n    RotationalInertia operator*(double a, const RotationalInertia& I){\n        RotationalInertia result;\n        Eigen::Map<Eigen::Matrix3d>(result.data) = a * Eigen::Map<const Eigen::Matrix3d>(I.data);\n        return result;\n    }\n    \n    RotationalInertia operator+(const RotationalInertia& Ia, const RotationalInertia& Ib){\n        RotationalInertia result;\n        Eigen::Map<Eigen::Matrix3d>(result.data) = Eigen::Map<const Eigen::Matrix3d>(Ia.data) + Eigen::Map<const Eigen::Matrix3d>(Ib.data);\n        return result;\n    }\n}\n\n", "meta": {"hexsha": "f52c0ecc67da77ee13460706d23b4591bdadfa33", "size": 2224, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdparty/kdl/src/rotationalinertia.cpp", "max_stars_repo_name": "rocos-sia/rocos-app", "max_stars_repo_head_hexsha": "83aa8aa31dd303d77693cfc5ad48055d051fa4bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-12-06T15:30:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T13:21:40.000Z", "max_issues_repo_path": "3rdparty/kdl/src/rotationalinertia.cpp", "max_issues_repo_name": "thinkexist1989/rocos-app", "max_issues_repo_head_hexsha": "7d6ab256c8212504b0a8bbe1ec1dea0c41ea3ff2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "3rdparty/kdl/src/rotationalinertia.cpp", "max_forks_repo_name": "thinkexist1989/rocos-app", "max_forks_repo_head_hexsha": "7d6ab256c8212504b0a8bbe1ec1dea0c41ea3ff2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.3015873016, "max_line_length": 145, "alphanum_fraction": 0.6924460432, "num_tokens": 615, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154240079185319, "lm_q2_score": 0.6477982315512488, "lm_q1q2_score": 0.4634504071389316}}
{"text": "/* Copyright (c) 2013-2014 Fabian Schuiki */\n#define BOOST_TEST_MODULE gamma\n#include \"gamma/integer.hpp\"\n#include \"gamma/vector.hpp\"\n#include \"gamma/matrix.hpp\"\n#include \"gamma/fixed_point.hpp\"\n#include \"gamma/transform/translation.hpp\"\n#include \"gamma/transform/x_rotation.hpp\"\n#include \"gamma/transform/y_rotation.hpp\"\n#include \"gamma/transform/z_rotation.hpp\"\n#include \"gamma/transform/axial_rotation.hpp\"\n#include \"gamma/transform/perspective.hpp\"\n#include \"gamma/transform/orientation.hpp\"\n#include \"gamma/transform/lookat.hpp\"\n#include \"gamma/mvp.hpp\"\n#include <boost/test/unit_test.hpp>\n\nusing namespace gma::convenience;\n\nBOOST_AUTO_TEST_CASE(integer)\n{\n\t#define check(_type, _bits, _target)\\\n\t\tBOOST_CHECK_EQUAL((int)(gma::integer::_type<_bits>::requested_bits), _bits);\\\n\t\tBOOST_CHECK_EQUAL((int)(gma::integer::_type<_bits>::bits), _target*8);\\\n\t\tBOOST_CHECK_EQUAL(sizeof(gma::integer::_type<_bits>::type), _target);\n\n\t#define check_pair(bits, target)\\\n\t\tcheck(signed_integer, bits, target);\\\n\t\tcheck(unsigned_integer, bits, target);\n\n\t#define check_eight(bits, target)\\\n\t\tcheck_pair(bits+1, target);\\\n\t\tcheck_pair(bits+2, target);\\\n\t\tcheck_pair(bits+3, target);\\\n\t\tcheck_pair(bits+4, target);\\\n\t\tcheck_pair(bits+5, target);\\\n\t\tcheck_pair(bits+6, target);\\\n\t\tcheck_pair(bits+7, target);\\\n\t\tcheck_pair(bits+8, target);\n\n\tcheck_eight(0, 1);\n\tcheck_eight(8, 2);\n\tcheck_eight(16, 4);\n\tcheck_eight(24, 4);\n\tcheck_eight(32, 8);\n\tcheck_eight(40, 8);\n\tcheck_eight(48, 8);\n\tcheck_eight(56, 8);\n\n\t#undef check\n\t#undef check_pair\n\t#undef check_eight\n}\n\nBOOST_AUTO_TEST_CASE(sizes)\n{\n\t#define check(type, target) BOOST_CHECK_EQUAL(sizeof(type), target)\n\n\t#define check_vector(dim)\\\n\t\tcheck(vector ## dim ## b, 1*dim);\\\n\t\tcheck(vector ## dim ## i, 4*dim);\\\n\t\tcheck(vector ## dim ## f, 4*dim);\\\n\t\tcheck(vector ## dim ## d, 8*dim);\n\n\t#define check_matrix(dim)\\\n\t\tcheck(matrix ## dim ## b, 1*dim*dim);\\\n\t\tcheck(matrix ## dim ## i, 4*dim*dim);\\\n\t\tcheck(matrix ## dim ## f, 4*dim*dim);\\\n\t\tcheck(matrix ## dim ## d, 8*dim*dim);\n\n\tcheck_vector(2);\n\tcheck_vector(3);\n\tcheck_vector(4);\n\n\tcheck_matrix(2);\n\tcheck_matrix(3);\n\tcheck_matrix(4);\n\n\t#undef check\n\t#undef check_vector\n\t#undef check_matrix\n}\n\nBOOST_AUTO_TEST_CASE(matrix_column_major)\n{\n\t#define verify_column_major(type, dim) {\\\n\t\ttype m;\\\n\t\tm.m10 = 1;\\\n\t\tm.m01 = 2;\\\n\t\tBOOST_CHECK(m.a[0][1] == 1 && m.a[1][0] == 2);\\\n\t}\n\n\t#define verify_column_major_matrices(dim)\\\n\t\tverify_column_major(matrix ## dim ## b, dim);\\\n\t\tverify_column_major(matrix ## dim ## i, dim);\\\n\t\tverify_column_major(matrix ## dim ## f, dim);\\\n\t\tverify_column_major(matrix ## dim ## d, dim);\n\n\tverify_column_major_matrices(2);\n\tverify_column_major_matrices(3);\n\tverify_column_major_matrices(4);\n\n\t#undef verify_column_major\n\t#undef verify_column_major_matrices\n}\n\n/// This test tries to trigger an overflow of a fixed_point's underlying\n/// storage by multiplying two large numbers.\nBOOST_AUTO_TEST_CASE(fixed_point_overflow)\n{\n\tgma::fixed_point<24,8> a0, a1, a2;\n\ta0.v = 0x00008000;\n\ta1.v = 0x00010000;\n\ta2.v = 0x0007ff00;\n\n\tBOOST_CHECK_EQUAL((a0*a0).v, 0x80*0x80 * 0x100);\n\tBOOST_CHECK_EQUAL((a1*a1).v, 0x100*0x100 * 0x100);\n\tBOOST_CHECK_EQUAL((a2*a2).v, 0x7ff*0x7ff * 0x100);\n\n\tBOOST_CHECK_EQUAL((int)a0, 0x80);\n\tBOOST_CHECK_EQUAL((int)a1, 0x100);\n\tBOOST_CHECK_EQUAL((int)a2, 0x7ff);\n}\n\nBOOST_AUTO_TEST_CASE(fixed_point_rounding)\n{\n\tgma::fixed_point<24,8> a0(0x200,8), a1(0x199,8), a2(0x201,8), b0(0x180,8), b1(0x17f,8), b2(0x181,8);\n\n\tBOOST_REQUIRE(a0.v == 0x200);\n\tBOOST_REQUIRE(a1.v == 0x199);\n\tBOOST_REQUIRE(a2.v == 0x201);\n\n\tBOOST_REQUIRE(b0.v == 0x180);\n\tBOOST_REQUIRE(b1.v == 0x17f);\n\tBOOST_REQUIRE(b2.v == 0x181);\n\n\tBOOST_CHECK_EQUAL(a0.floor().v, 0x200); BOOST_CHECK_EQUAL(a1.floor().v, 0x100);\tBOOST_CHECK_EQUAL(a2.floor().v, 0x200);\n\tBOOST_CHECK_EQUAL(b0.floor().v, 0x100); BOOST_CHECK_EQUAL(b1.floor().v, 0x100);\tBOOST_CHECK_EQUAL(b2.floor().v, 0x100);\n\n\tBOOST_CHECK_EQUAL(a0.round().v, 0x200); BOOST_CHECK_EQUAL(a1.round().v, 0x200);\tBOOST_CHECK_EQUAL(a2.round().v, 0x200);\n\tBOOST_CHECK_EQUAL(b0.round().v, 0x200); BOOST_CHECK_EQUAL(b1.round().v, 0x100);\tBOOST_CHECK_EQUAL(b2.round().v, 0x200);\n\n\tBOOST_CHECK_EQUAL(a0.ceil().v, 0x200); BOOST_CHECK_EQUAL(a1.ceil().v, 0x200);\tBOOST_CHECK_EQUAL(a2.ceil().v, 0x300);\n\tBOOST_CHECK_EQUAL(b0.ceil().v, 0x200); BOOST_CHECK_EQUAL(b1.ceil().v, 0x200);\tBOOST_CHECK_EQUAL(b2.ceil().v, 0x200);\n}\n", "meta": {"hexsha": "d687f29a3795ed559fefef4f61f88ebdbb168eed", "size": 4367, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests.cpp", "max_stars_repo_name": "fabianschuiki/gamma", "max_stars_repo_head_hexsha": "ef5de69eae854267fecebdebd0c7fab7d7d2bf60", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-11-09T02:15:41.000Z", "max_stars_repo_stars_event_max_datetime": "2017-11-09T02:15:41.000Z", "max_issues_repo_path": "tests.cpp", "max_issues_repo_name": "fabianschuiki/gamma", "max_issues_repo_head_hexsha": "ef5de69eae854267fecebdebd0c7fab7d7d2bf60", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-08-10T20:54:11.000Z", "max_issues_repo_issues_event_max_datetime": "2015-08-10T20:54:11.000Z", "max_forks_repo_path": "tests.cpp", "max_forks_repo_name": "fabianschuiki/gamma", "max_forks_repo_head_hexsha": "ef5de69eae854267fecebdebd0c7fab7d7d2bf60", "max_forks_repo_licenses": ["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.9109589041, "max_line_length": 120, "alphanum_fraction": 0.7146782688, "num_tokens": 1378, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.46345039927786214}}
{"text": "/**\n * @file   NMAAnalyzer.hpp\n * @author see AUTHORS\n * @brief  NMAAnalyzer header file.\n */\n\n#ifndef NONLINEARFITTER_HPP\n#define NONLINEARFITTER_HPP\n\n#include <math.h>\n\n#include <Eigen/Dense>\n\n/**\n * @class NonlinearFitter\n */\nclass NonlinearFitter {\npublic:\n    /**\n     * @param x\n     * @param y\n     * @param yerr2\n     */\n    void exponential_fit(Eigen::VectorXd & x, Eigen::VectorXd & y, Eigen::VectorXd & yerr2); //length == ndat/S\n\n    /**\n     * @return a\n     */\n    double get_a();\n\n    /**\n     * @return b\n     */\n    double get_b();\n\n    /**\n     * @return error for a\n     */\n    double get_err_a();\n\n    /**\n     * @return error for b\n     */\n    double get_err_b();\nprivate:\n    double a = 0;\n    double b = 0;\n    double err_a = 0;\n    double err_b = 0;\n    bool calculation_completed = false;\n};\n\n#endif\n\n// vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4\n", "meta": {"hexsha": "d3c46f9e2b50ed87da8d88e8bd80c424ce69192c", "size": 881, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/NonlinearFitter.hpp", "max_stars_repo_name": "AFriemann/LowCarb", "max_stars_repo_head_hexsha": "073e036a5fd6787943c4cbd76ab388dbd830e7d3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/NonlinearFitter.hpp", "max_issues_repo_name": "AFriemann/LowCarb", "max_issues_repo_head_hexsha": "073e036a5fd6787943c4cbd76ab388dbd830e7d3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-12-15T13:57:26.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-15T13:57:26.000Z", "max_forks_repo_path": "src/NonlinearFitter.hpp", "max_forks_repo_name": "AFriemann/LowCarb", "max_forks_repo_head_hexsha": "073e036a5fd6787943c4cbd76ab388dbd830e7d3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.7321428571, "max_line_length": 111, "alphanum_fraction": 0.572077185, "num_tokens": 255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154240079185319, "lm_q2_score": 0.647798211152541, "lm_q1q2_score": 0.46345039254520626}}
{"text": "\n/******************************************************************************\n\n  Basic linear algebra subprograms. \n\n  Copyright (c) 2011 - 2013\n  Dzmitry Hlindzich <dzmitry.hlindzich@ziti.uni-heidelberg.de>\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 BLAS_EXTENSIONS_HPP_F74A6974_6444_4C40_BFE7_75ADEC15B7E6_\n#define BLAS_EXTENSIONS_HPP_F74A6974_6444_4C40_BFE7_75ADEC15B7E6_\n\n#include <iostream>\n#include <vector>\n#include <cmath>\n#include <boost/format.hpp>\n\n// Suppress boost::numeric::ublas C4127 warning under MSVC.\n#ifdef _MSC_VER\n#   pragma warning(push)\n#   pragma warning(disable:4127)\n#endif // _MSC_VER\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n\n#ifdef _MSC_VER\n#   pragma warning(pop)\n#endif // _MSC_VER\n\n#include \"bo/math/functions.hpp\"\n\n// Dirty hack: add stream operator for matrix<T> type into boost namespace.\nnamespace boost {\nnamespace numeric {\nnamespace ublas {\n\n// Prints formatted matrix to the given stream. T must support operator<<.\ntemplate <typename T>\nstd::ostream& operator<<(std::ostream& os, const matrix<T>& obj)\n{\n    // Print full vertex info.\n    os << boost::format(\"%1%x%2% boost::numeric::ublas::matrix, object %3$#x, %4% bytes: \")\n          % obj.size1() % obj.size2() % &obj % sizeof(obj) << std::endl;\n\n    for (std::size_t i = 0; i < obj.size1(); ++i)\n    {\n        for (std::size_t j = 0; j < obj.size2(); ++j)\n        {\n            os << \"\\t \" << obj(i, j);\n        }\n        os << std::endl;\n    }\n\n    os << boost::format(\"end of object %1$#x.\") % &obj << std::endl;\n\n    return os;\n}\n\n} // namespace ublas\n} // namespace numeric\n} // namespace boost\n\nnamespace bo {\nnamespace math {\n\nusing namespace boost::numeric::ublas;\n\n// Matrix inversion routine.\n// Use lu_factorize and lu_substitute in uBLAS to invert a matrix. \ntemplate<class T>\nbool invert_matrix(const matrix<T>& input, matrix<T>& inverse)\n{\n    // Create a working copy of the input\n    matrix<T> A(input);\n\n    // Create a permutation matrix for the LU-factorization\n    permutation_matrix<std::size_t> pm(A.size1());\n\n    // Perform LU-factorization\n    size_t res = lu_factorize(A, pm);\n    if (res != 0)\n        return false;\n\n    // Create identity matrix of \"inverse\"\n    inverse.assign(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// Define the sign of the determinant using the given permutation matrix.\ninline\nint determinant_sign(const permutation_matrix<std::size_t>& pm)\n{\n    int pm_sign=1;\n    std::size_t size = pm.size();\n    for (std::size_t i = 0; i < size; ++i)\n    {\n        if (i != pm(i))\n        {\n            // swap_rows would swap a pair of rows here, so we change sign\n            pm_sign *= -1;\n        }\n    }\n\n    return pm_sign;\n}\n\n// Calculate the determinant of the input matrix.\ntemplate<class T>\ndouble determinant(const matrix<T>& input)\n{\n    // create a working copy of the input\n    matrix<T> A(input);\n\n    // create a permutation matrix for the LU-factorization\n    permutation_matrix<std::size_t> pm(A.size1());\n\n    // perform LU-factorization\n    int res = lu_factorize(A, pm);\n\n    double det=1.0;\n\n    if (res != 0 )\n    {\n        det = 0.0;\n    } \n    else\n    {\n        // multiply by elements on diagonal\n        for(int i = 0; i < A.size1(); ++i) \n            det *= A(i,i); \n        det = det * determinant_sign( pm );\n    }\n\n    return det;\n}\n\n// Eigenvector decomposition for real symmetric matrices. Returns a vector of the\n// eigenvalues, sorted in non-decreasing order. The corresponding eigenvectors are\n// stored in the columns of the matrix expr.\ntemplate <class E>\nstd::vector<typename E::value_type> eigen_symmetric(matrix_expression<E>& expr)\n{\n    // Cache the underlying matrix type.\n    typedef typename E::value_type T;\n\n    // Evaluate and cache the matrix_expression.\n    typename E::closure_type A(expr());\n\n    // Allocate the return vector.\n    const int n(static_cast<int>(A.size1()));\n    std::vector<T> d(n);\n\n    // Initialize the return vector.\n    for (int j = 0; j < n; ++j)\n    {\n        d[j] = A(n - 1, j);\n    }\n\n    BOOST_ASSERT(A.size2() == (unsigned)n);\n\n    // Check for a square matrix.\n    if (A.size2() != (unsigned)n)\n    {\n        return d; \n    }\n\n    std::vector<T> e(n, T(0));\n\n    // Iterating.\n    for (int i = n - 1; i > 0; --i) \n    {\n        T scale(0);\n\n        for (int k = 0; k < i; ++k)\n        {\n            scale += std::abs(d[k]);\n        }\n\n        if (scale == T(0))\n        {            \n            e[i] = d[i - 1];\n\n            for (int j = 0; j < i; ++j)\n            {\n                d[j] = A(i - 1, j); \n                A(i, j) = A(j, i) = T(0); \n            }\n\n            d[i] = T(0);\n        } \n        else\n        {\n            T h(0);\n            T invscale = T(1.0 / scale);\n\n            for (int k = 0; k < i; ++k)\n            {\n                d[k] *= invscale;\n                h += square(d[k]);\n            }\n\n            T f = d[i - 1];\n            T g = (f > 0) ? -std::sqrt(h) : std::sqrt(h);\n            e[i] = scale * g;\n            h -= f * g;\n            d[i - 1] = f - g;\n\n            for (int j = 0; j < i; ++j)\n            {\n                e[j] = T(0);\n            }\n\n            for (int j = 0; j < i; ++j) \n            {\n                f = d[j];\n                A(j, i) = f;\n                g = e[j] + f * A(j, j);\n\n                for (int k = j+1; k < i; k++)\n                {\n                    g += A(k, j) * d[k];\n                    e[k] += A(k, j) * f;\n                }\n\n                e[j] = g;\n            }\n\n            f = T(0);\n            T invh = T(1.0 / h);\n\n            for (int j = 0; j < i; ++j)\n            {\n                e[j] *= invh;\n                f += e[j] * d[j];\n            }\n\n            T hh = f / (h + h);\n\n            for (int j = 0; j < i; j++)\n            {\n                e[j] -= hh * d[j];\n            }\n\n            for (int j = 0; j < i; j++)\n            {\n                f = d[j];\n                g = e[j];\n\n                for (int k = j; k < i; k++)\n                {\n                    A(k, j) -= f * e[k] + g * d[k];\n                }\n\n                d[j] = A(i - 1, j);\n                A(i, j) = T(0);\n            }\n\n            d[i] = h;\n        }\n    }\n\n    // I put on my robe and wizard hat...\n    for (int i = 0; i < n - 1; ++i)\n    {\n        A(n - 1, i) = A(i, i);\n        A(i, i) = 1;\n\n        T h = d[i+1];\n\n        if (h != T(0))\n        {\n            T invh = T(1.0 / h);\n\n            for (int k = 0; k <= i; ++k)\n            {\n                d[k] = A(k, i + 1) * invh;\n            }\n\n            for (int j = 0; j <= i; ++j)\n            {\n                T g(0);\n\n                for (int k = 0; k <= i; ++k)\n                {\n                    g += A(k, i + 1) * A(k, j);\n                }\n\n                for (int k = 0; k <= i; ++k)\n                {\n                    A(k, j) -= g * d[k];\n                }\n\n            }\n        }\n\n        for (int k = 0; k <= i; ++k)\n        {\n            A(k, i + 1) = T(0);\n        }    \n    }\n\n    for (int j = 0; j < n; ++j) \n    {\n        d[j] = A(n - 1, j);\n        A(n - 1, j) = T(0);\n    }\n\n    A(n - 1, n - 1) = 1;\n\n    // QL.\n    for (int i = 1; i < n; ++i)\n    {\n        e[i - 1] = e[i];\n    }\n\n    e[n - 1] = T(0);\n    T f(0), tmp(0);\n    const T eps = T(std::pow(T(2), -52));\n\n    for (int l = 0; l < n; l++) \n    {\n        tmp = std::max(tmp, std::fabs(d[l]) + std::fabs(e[l]));\n        int m = l;\n\n        while (m < n)\n        {\n            if (std::fabs(e[m]) <= eps * tmp)\n                break;\n            ++m;\n        }\n\n        if (m > l)\n        {\n            do\n            {\n                T g = d[l];\n                T p = (d[l + 1] - g) / (e[l] + e[l]);\n                T r = T(std::sqrt(square(p) + T(1)));\n\n                if (p < T(0))\n                {\n                    r = -r;\n                }\n\n                d[l] = e[l] / (p + r);\n                d[l + 1] = e[l] * (p + r);\n                T dl1 = d[l + 1];\n                T h = g - d[l];\n\n                for (int i = l + 2; i < n; ++i)\n                {\n                    d[i] -= h;\n                }\n\n                f += h;\n                p = d[m];   \n                T c(1), c2(1), c3(1);\n\n                T el1 = e[l + 1];\n                T s(0), s2(0);\n\n                for (int i = m - 1; i >= l; --i)\n                {\n                    c3 = c2;\n                    c2 = c;\n                    s2 = s;\n                    g = c * e[i];\n                    h = c * p;\n\n                    r = T(std::sqrt(square(p) + square(e[i])));\n\n                    e[i + 1] = s * r;\n                    s = e[i] / r;\n                    c = p / r;\n                    p = c * d[i] - s * g;\n                    d[i + 1] = h + s * (c * g + s * d[i]);\n\n                    for (int k = 0; k < n; ++k)\n                    {\n                        h = A(k, i + 1);\n                        A(k, i + 1) = s * A(k, i) + c * h;\n                        A(k, i) = c * A(k, i) - s * h;\n                    }\n                }\n\n                p = -s * s2 * c3 * el1 * e[l] / dl1;\n\n                e[l] = s * p;\n                d[l] = c * p;\n\n            }\n            while (std::fabs(e[l]) > eps * tmp);\n        }\n\n        d[l] += f;\n        e[l] = T(0);\n    }\n\n    // Sort.\n    for (int i = 0; i < n - 1; ++i)\n    {\n        int k = i;\n        T p = d[i];\n\n        for (int j = i + 1; j < n; ++j)\n        {\n            if (d[j] < p)\n            {\n                k = j;\n                p = d[j];\n            }\n        }\n\n        if (k == i) continue;\n\n        d[k] = d[i];\n        d[i] = p;\n\n        for (int j = 0; j < n; ++j)\n        {\n            p = A(j, i);\n            A(j, i) = A(j, k);\n            A(j, k) = p;\n        }\n    }\n\n    return d;\n}\n\n// Computes the L1 norm of matrix. Uses std::abs(T), which implies T is a built-in type\n// or a custom type, for which abs() is provided in std namespace.\ntemplate <class T>\nT l1_norm(const matrix<T>& A)\n{\n    T sum(0);\n\n    for (std::size_t i = 0; i < A.size1(); ++i)\n        for (std::size_t j = 0; j < A.size2(); ++j)\n            sum += std::abs(A(i, j));\n\n    return sum;\n}\n\n\n} // namespace math\n} // namespace bo\n\n#endif // BLAS_EXTENSIONS_HPP_F74A6974_6444_4C40_BFE7_75ADEC15B7E6_\n", "meta": {"hexsha": "a8441f2cf37a7fcbe2af2294f16d693770c65749", "size": 11691, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Bo/math/blas_extensions.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/math/blas_extensions.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/math/blas_extensions.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": 24.4581589958, "max_line_length": 91, "alphanum_fraction": 0.4332392439, "num_tokens": 3311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154240079185319, "lm_q2_score": 0.6477982043529716, "lm_q1q2_score": 0.4634503876806311}}
{"text": "#define BOOST_TEST_MODULE\n#include <boost/test/unit_test.hpp>\n#include <core/util/test_macros.hpp>\n\n#define XGBOOST_CUSTOMIZE_MSG_\n#include <xgboost/src/io/simple_fmatrix-inl.hpp>\n#include <xgboost/src/learner/learner-inl.hpp>\n#include <xgboost/src/io/simple_dmatrix-inl.hpp>\n\nusing namespace xgboost;\nusing namespace xgboost::learner;\nusing namespace xgboost::io;\n\nconstexpr double DELTA = 1e-7;\n\nnamespace xgboost {\nnamespace utils {\n  void HandleAssertError(const char *msg) {\n    fprintf(stderr, \"AssertError:%s\\n\", msg);\n    exit(-1);\n  }\n  void HandleCheckError(const char *msg) {\n    throw std::runtime_error(msg);\n  }\n  void HandlePrint(const char *msg) {\n    printf(\"%s\", msg);\n  }\n }\n}\n\nstruct decision_tree_test {\n\n  void set_options(BoostLearner& model, std::string obj) {\n    model.SetParam(\"eta\", \"1\"); // learning_rate\n    model.SetParam(\"max_depth\", \"1\");\n    model.SetParam(\"gamma\", \"0.0\"); // min loss reduction\n    model.SetParam(\"min_child_weight\", \"0.0\"); // min child weight\n    model.SetParam(\"lambda\", \"0.0\"); // regularizer\n    model.SetParam(\"objective\", obj.c_str());\n  }\n\n public:\n  void test_regression() {\n    DMatrixSimple data;\n    data.info.labels = {-1, 1};\n    data.AddRow({RowBatch::Entry(0, 1)});\n    data.AddRow({RowBatch::Entry(0, -1)});\n\n    BoostLearner gbm;\n    set_options(gbm, \"reg:linear\");\n    gbm.SetCacheData({&data});\n    gbm.InitModel();\n    gbm.CheckInit(&data);\n    gbm.UpdateOneIter(0, data);\n\n    std::vector<float> preds;\n    bool output_margin = true;\n    bool pred_leaf = false;\n    gbm.Predict(data, output_margin, &preds, 0, pred_leaf);\n\n    // Base scores (B): 0.5, 0.5\n    // Gradients (G): 1.5, -0.5\n    // Hessians (H): 1, 1\n    // Leaf weights (W) = -G / H : -1.5, 0.5\n    // Preds = B + learning_rate * W\n    TS_ASSERT_DELTA(preds[0], -1.0, DELTA);\n    TS_ASSERT_DELTA(preds[1], 1.0, DELTA);\n  }\n\n  void test_classifier() {\n    DMatrixSimple data;\n    data.info.labels = {0, 1};\n    data.AddRow({RowBatch::Entry(0, 1)});\n    data.AddRow({RowBatch::Entry(0, -1)});\n\n    BoostLearner gbm;\n    set_options(gbm, \"binary:logistic\");\n    gbm.SetCacheData({&data});\n    gbm.InitModel();\n    gbm.CheckInit(&data);\n    gbm.UpdateOneIter(0, data);\n\n    std::vector<float> preds;\n    bool output_margin = true;\n    bool pred_leaf = false;\n    gbm.Predict(data, output_margin, &preds, 0, pred_leaf);\n\n    // Base scores (B): 0.0, 0.0\n    // Gradients (G): 0.5, -0.5\n    // Hessians (H): 0.25, 0.25\n    // Leaf weights (W) = -G / H : -2, 2\n    // Preds = B + learning_rate * W\n    TS_ASSERT_DELTA(preds[0], -2.0, DELTA);\n    TS_ASSERT_DELTA(preds[1], 2.0, DELTA);\n  }\n\n  void test_multiclass_classifier() {\n    DMatrixSimple data;\n    data.info.labels = {0, 1, 2};\n    data.AddRow({RowBatch::Entry(0, 1)});\n    data.AddRow({RowBatch::Entry(0, 0)});\n    data.AddRow({RowBatch::Entry(0, -1)});\n\n    BoostLearner gbm;\n    set_options(gbm, \"multi:softmax\");\n    gbm.SetParam(\"num_class\", \"3\");\n    gbm.SetParam(\"max_depth\", \"2\");\n    gbm.SetCacheData({&data});\n    gbm.InitModel();\n    gbm.CheckInit(&data);\n    gbm.UpdateOneIter(0, data);\n\n    std::vector<float> preds;\n    bool output_margin = true;\n    bool pred_leaf = false;\n    gbm.Predict(data, output_margin, &preds, 0, pred_leaf);\n\n    // Base scores (B): 0.5\n    // Gradients (G): (-2/3, 1/3, 1/3), (1/3, -2/3, 1/3), (1/3, 1/3, -2/3)\n    // Hessians (H): 0.444\n    // Leaf weights (W) = -G / H : (1.5, -.75, -.75), (-.75, 1.5, -.75), ...\n    // Preds = B + learning_rate * W\n    TS_ASSERT_DELTA(preds[0], 2.0, DELTA);\n    TS_ASSERT_DELTA(preds[1], -.25, DELTA);\n    TS_ASSERT_DELTA(preds[2], -.25, DELTA);\n    TS_ASSERT_DELTA(preds[3], -.25, DELTA);\n    TS_ASSERT_DELTA(preds[4], 2.0, DELTA);\n    TS_ASSERT_DELTA(preds[5], -.25, DELTA);\n    TS_ASSERT_DELTA(preds[6], -.25, DELTA);\n    TS_ASSERT_DELTA(preds[7], -.25, DELTA);\n    TS_ASSERT_DELTA(preds[8], 2.0, DELTA);\n  }\n};\n\nBOOST_FIXTURE_TEST_SUITE(_decision_tree_test, decision_tree_test)\nBOOST_AUTO_TEST_CASE(test_regression) {\n  decision_tree_test::test_regression();\n}\nBOOST_AUTO_TEST_CASE(test_classifier) {\n  decision_tree_test::test_classifier();\n}\nBOOST_AUTO_TEST_CASE(test_multiclass_classifier) {\n  decision_tree_test::test_multiclass_classifier();\n}\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "97298b13cb4ee3ebe17a4984095a07b8b038ff5e", "size": 4249, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "test/toolkits/supervised_learning/xgboost_tests.cxx", "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": "test/toolkits/supervised_learning/xgboost_tests.cxx", "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": "test/toolkits/supervised_learning/xgboost_tests.cxx", "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": 29.102739726, "max_line_length": 76, "alphanum_fraction": 0.6408566722, "num_tokens": 1375, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056295505783, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.4634420296952272}}
{"text": "#ifndef MATHTOOLBOX_L_BFGS_HPP\n#define MATHTOOLBOX_L_BFGS_HPP\n\n#include <Eigen/Core>\n#include <functional>\n\nnamespace mathtoolbox\n{\n    namespace optimization\n    {\n        void RunLBfgs(const Eigen::VectorXd&                                        x_init,\n                      const std::function<double(const Eigen::VectorXd&)>&          f,\n                      const std::function<Eigen::VectorXd(const Eigen::VectorXd&)>& g,\n                      const double                                                  epsilon,\n                      const unsigned int                                            max_num_iterations,\n                      Eigen::VectorXd&                                              x_star,\n                      unsigned int&                                                 num_iterations);\n    }\n} // namespace mathtoolbox\n\n#endif // MATHTOOLBOX_L_BFGS_HPP\n", "meta": {"hexsha": "ad4b2ba692d21465d0c41c0a05556d1a9f22c8ef", "size": 888, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mathtoolbox/l-bfgs.hpp", "max_stars_repo_name": "yuki-koyama/mathtoolbox", "max_stars_repo_head_hexsha": "eb7449c3c489f465849a74405e72aff016a296f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 195.0, "max_stars_repo_stars_event_min_datetime": "2018-04-28T16:12:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T03:52:56.000Z", "max_issues_repo_path": "include/mathtoolbox/l-bfgs.hpp", "max_issues_repo_name": "amazing89/mathtoolbox", "max_issues_repo_head_hexsha": "8904bb06ced2ac501594f9574ef1ba3454b8e38e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 52.0, "max_issues_repo_issues_event_min_datetime": "2018-04-15T01:24:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-02T09:14:23.000Z", "max_forks_repo_path": "include/mathtoolbox/l-bfgs.hpp", "max_forks_repo_name": "amazing89/mathtoolbox", "max_forks_repo_head_hexsha": "8904bb06ced2ac501594f9574ef1ba3454b8e38e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 21.0, "max_forks_repo_forks_event_min_datetime": "2018-06-05T04:11:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T13:28:12.000Z", "avg_line_length": 40.3636363636, "max_line_length": 103, "alphanum_fraction": 0.4481981982, "num_tokens": 148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.7401743735019594, "lm_q1q2_score": 0.4634410706143892}}
{"text": "#include <boost/simd/include/functions/shuffle.hpp>\n#include <boost/simd/sdk/simd/pack.hpp>\n#include <boost/simd/sdk/simd/io.hpp>\n#include <boost/mpl/int.hpp>\n#include <iostream>\n\nusing boost::mpl::int_;\nusing boost::simd::pack;\nusing boost::simd::shuffle;\n\nstruct half_half\n{\n  template<class Index, class Cardinal>\n  struct apply  : int_< Index::value < Cardinal::value/2\n                      ? Index::value\n                      : Index::value+Cardinal::value\n                      >\n  {};\n};\n\nint main()\n{\n  pack<float,4> f(1,2,3,4), g(10,20,30,40);\n\n  // Gather the first half of f and the second half of g: [1 2 30 40]\n  std::cout << shuffle<half_half>(f,g) << \"\\n\";\n}\n", "meta": {"hexsha": "05a4a98286542648afc6ed0af923a3a2a9119ae5", "size": 676, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/base/examples/swar/shuffle_perm2.cpp", "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/examples/swar/shuffle_perm2.cpp", "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/examples/swar/shuffle_perm2.cpp", "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": 24.1428571429, "max_line_length": 69, "alphanum_fraction": 0.6109467456, "num_tokens": 191, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.6261241842048092, "lm_q1q2_score": 0.4634410686009942}}
{"text": "/*\n * 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 *    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 *          Erik Nelson            ( eanelson@eecs.berkeley.edu )\n */\n\n///////////////////////////////////////////////////////////////////////////////\n//\n// This class defines the FundamentalMatrixRansacModel class, which\n// is derived from the abstract base class RansacModel.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include <iostream>\n\n#include <algorithm>\n#include <Eigen/Core>\n#include <gflags/gflags.h>\n#include <vector>\n\n#include \"ransac_problem.h\"\n#include \"fundamental_matrix_ransac_problem.h\"\n#include \"../math/random_generator.h\"\n#include \"../geometry/eight_point_algorithm_solver.h\"\n#include \"../geometry/fundamental_matrix_solver_options.h\"\n\nnamespace bsfm {\n\n// ------------ FundamentalMatrixRansacModel methods ------------ //\n\n// Default constructor.\nFundamentalMatrixRansacModel::FundamentalMatrixRansacModel()\n    : F_(Matrix3d::Identity()), error_(0.0) {}\n\nFundamentalMatrixRansacModel::FundamentalMatrixRansacModel(\n    const Matrix3d& F)\n    : F_(F), error_(0.0) {}\n\n// Destructor.\nFundamentalMatrixRansacModel::~FundamentalMatrixRansacModel() {}\n\n// Return model error.\ndouble FundamentalMatrixRansacModel::Error() const {\n  return error_;\n}\n\n// Evaluate model on a single data element and update error.\nbool FundamentalMatrixRansacModel::IsGoodFit(\n    const FeatureMatch& data_point,\n    double error_tolerance) const {\n  const double error = EvaluateEpipolarCondition(data_point);\n\n  // Test squared error against the provided tolerance.\n  if (error * error < error_tolerance) {\n    return true;\n  }\n  return false;\n}\n\ndouble FundamentalMatrixRansacModel::EvaluateEpipolarCondition(\n    const FeatureMatch& match) const {\n  // Construct vectors for 2D keypoints in match.\n  Vector3d kp1, kp2;\n  kp1 << match.feature1_.u_, match.feature1_.v_, 1;\n  kp2 << match.feature2_.u_, match.feature2_.v_, 1;\n\n  // Compute deviation from the epipolar condition.\n  const double epipolar_condition = kp2.transpose() * F_ * kp1;\n  return epipolar_condition;\n}\n\n// ------------ FundamentalMatrixRansacProblem methods ------------ //\n\n// RansacProblem constructor.\nFundamentalMatrixRansacProblem::FundamentalMatrixRansacProblem() {}\n\n// RansacProblem destructor.\nFundamentalMatrixRansacProblem::~FundamentalMatrixRansacProblem() {}\n\n// Subsample the data.\nstd::vector<FeatureMatch> FundamentalMatrixRansacProblem::SampleData(\n    unsigned int num_samples) {\n  // Randomly shuffle the entire dataset and take the first elements.\n  std::random_shuffle(data_.begin(), data_.end());\n\n  // Make sure we don't over step.\n\n  if (static_cast<size_t>(num_samples) > data_.size()) {\n    VLOG(1) << \"Requested more RANSAC data samples than are available. \"\n               \"Returning all data.\";\n    num_samples = data_.size();\n  }\n\n  // Get samples.\n  std::vector<FeatureMatch> samples(\n      data_.begin(), data_.begin() + static_cast<size_t>(num_samples));\n\n  return samples;\n}\n\n// Return all data that was not sampled.\nstd::vector<FeatureMatch> FundamentalMatrixRansacProblem::RemainingData(\n    unsigned int num_sampled_previously) const {\n  // In Sample(), the data was shuffled and we took the first\n  // 'num_sampled_previously' elements. Here, take the remaining elements.\n  if (num_sampled_previously >= data_.size()) {\n    VLOG(1) << \"No remaining RANSAC data to sample.\";\n    return std::vector<FeatureMatch>();\n  }\n\n  return std::vector<FeatureMatch>(\n      data_.begin() + num_sampled_previously, data_.end());\n}\n\n// Fit a model to the provided data using the 8-point algorithm.\nFundamentalMatrixRansacModel FundamentalMatrixRansacProblem::FitModel(\n    const std::vector<FeatureMatch>& input_data) const {\n  // Create an empty fundamental matrix.\n  Matrix3d F;\n\n  // Run the 8-point algorithm with default options.\n  EightPointAlgorithmSolver solver;\n  FundamentalMatrixSolverOptions options;\n  solver.SetOptions(options);\n\n  if (solver.ComputeFundamentalMatrix(input_data, F)) {\n    // Create a new RansacModel using the computed fundamental matrix.\n    FundamentalMatrixRansacModel model_out(F);\n\n    // Record sum of squared error over all matches.\n    model_out.error_ = 0.0;\n    for (const auto& feature_match : input_data) {\n      const double error = model_out.EvaluateEpipolarCondition(feature_match);\n      model_out.error_ += error * error;\n    }\n\n    return model_out;\n  }\n  // Set a large error - we didn't find a model that fits the data.\n  FundamentalMatrixRansacModel model_out(Matrix3d::Identity());\n  model_out.error_ = std::numeric_limits<double>::infinity();\n  return model_out;\n}\n\n}  //\\namespace bsfm\n", "meta": {"hexsha": "7374067dccee5335e3a4985db44f7c82e8bff2ce", "size": 6372, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cpp/ransac/fundamental_matrix_ransac_problem.cpp", "max_stars_repo_name": "jamesdsmith/berkeley_sfm", "max_stars_repo_head_hexsha": "de3ae6b104602c006d939b1f3da8c497b86d39ff", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 21.0, "max_stars_repo_stars_event_min_datetime": "2016-01-14T13:52:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-03T19:30:33.000Z", "max_issues_repo_path": "src/cpp/ransac/fundamental_matrix_ransac_problem.cpp", "max_issues_repo_name": "jamesdsmith/berkeley_sfm", "max_issues_repo_head_hexsha": "de3ae6b104602c006d939b1f3da8c497b86d39ff", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-10-17T17:01:46.000Z", "max_issues_repo_issues_event_max_datetime": "2015-10-22T20:59:43.000Z", "max_forks_repo_path": "src/cpp/ransac/fundamental_matrix_ransac_problem.cpp", "max_forks_repo_name": "erik-nelson/berkeley_sfm", "max_forks_repo_head_hexsha": "5bf0b45fac176ff7abfca0ff690893c1afc73c51", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2016-01-22T06:23:59.000Z", "max_forks_repo_forks_event_max_datetime": "2018-01-16T03:54:33.000Z", "avg_line_length": 36.0, "max_line_length": 79, "alphanum_fraction": 0.7172002511, "num_tokens": 1448, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743735019595, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.4634410602867275}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   tstMomentumConversion.cpp\n//! \\author Alex Robinson\n//! \\brief  The momentum conversion unit tests\n//!\n//---------------------------------------------------------------------------//\n\n// Std Lib Includes\n#include <iostream>\n\n// Boost Includes\n#define BOOST_TEST_MAIN\n#include <boost/test/unit_test.hpp>\n#include <boost/test/tools/floating_point_comparison.hpp>\n#include <boost/units/quantity.hpp>\n#include <boost/units/systems/si.hpp>\n#include <boost/units/systems/cgs.hpp>\n\n// FRENSIE Includes\n#include \"Utility_MomentumUnits.hpp\"\n#include \"Utility_RawPhysicalConstants.hpp\"\n\nusing namespace Utility::Units;\n\n//---------------------------------------------------------------------------//\n// Tests\n//---------------------------------------------------------------------------//\n// Check that the momentum units can be converted\nBOOST_AUTO_TEST_CASE( convert )\n{\n  boost::units::quantity<Utility::Units::AtomicMomentum> atomic_momentum_q( 1.0*mec_momentum );\n\n  boost::units::quantity<Utility::Units::MeCMomentum> mec_momentum_q( 1.0*atomic_momentum );\n\n  BOOST_CHECK_CLOSE_FRACTION(\n\t\tatomic_momentum_q.value(),\n\t\tUtility::RawPhysicalConstants::inverse_fine_structure_constant,\n\t\t1e-15 );\n  BOOST_CHECK_CLOSE_FRACTION(\n\t\t\tmec_momentum_q.value(),\n\t\t\tUtility::RawPhysicalConstants::fine_structure_constant,\n\t\t\t1e-15 );\n}\n\n//---------------------------------------------------------------------------//\n// end tstMomentumConversion.cpp\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "cca9643b94b7b6d5723abad76c78f4192bbe6afc", "size": 1610, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "packages/utility/core/test/tstMomentumConversion.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/utility/core/test/tstMomentumConversion.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/utility/core/test/tstMomentumConversion.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": 32.8571428571, "max_line_length": 95, "alphanum_fraction": 0.5416149068, "num_tokens": 302, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743735019595, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.4634410602867275}}
{"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\u00e4nkt), 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_BICGSTAB_INCLUDE\n#define ITL_BICGSTAB_INCLUDE\n\n#include <boost/numeric/mtl/concept/collection.hpp>\n#include <boost/numeric/mtl/utility/exception.hpp>\n#include <boost/numeric/mtl/operation/resource.hpp>\n#include <boost/numeric/mtl/interface/vpt.hpp>\n\n#include <boost/numeric/itl/utility/exception.hpp>\n#include <boost/numeric/itl/krylov/base_solver.hpp>\n\nnamespace itl {\n\n///  Bi-Conjugate Gradient Stabilized\ntemplate < class LinearOperator, class HilbertSpaceX, class HilbertSpaceB, \n\t   class Preconditioner, class Iteration >\nint bicgstab(const LinearOperator& A, HilbertSpaceX& x, const HilbertSpaceB& b, \n\t     const Preconditioner& M, Iteration& iter)\n{\n  typedef typename mtl::Collection<HilbertSpaceX>::value_type Scalar;\n  typedef HilbertSpaceX                                       Vector;\n  mtl::vampir_trace<7004> tracer;\n\n  Scalar     rho_1(0), rho_2(0), alpha(0), beta(0), gamma, omega(0);\n  Vector     p(resource(x)), phat(resource(x)), s(resource(x)), shat(resource(x)), \n             t(resource(x)), v(resource(x)), r(resource(x)), rtilde(resource(x));\n\n  r = b - A * x;\n  rtilde = r;\n\n  while (! iter.finished(r)) {\n    ++iter;\n    rho_1 = dot(rtilde, r);\n    MTL_THROW_IF(rho_1 == 0.0, unexpected_orthogonality());\n\n    if (iter.first())\n      p = r;\n    else {\n      MTL_THROW_IF(omega == 0.0, unexpected_orthogonality());\n      beta = (rho_1 / rho_2) * (alpha / omega);\n      p = r + beta * (p - omega * v);\n    }\n    phat = solve(M, p);\n    v = A * phat;\n\n    gamma = dot(rtilde, v);\n    MTL_THROW_IF(gamma == 0.0, unexpected_orthogonality());\n\n    alpha = rho_1 / gamma;\n    s = r - alpha * v;\n    \n    if (iter.finished(s)) {\n      x += alpha * phat;\n      break;\n    }\n    shat = solve(M, s);\n    t = A * shat;\n    omega = dot(t, s) / dot(t, t);\n    \n    x += omega * shat + alpha * phat;\n    r = s - omega * t;\n    \n    rho_2 = rho_1;    \n  }\n  return iter;\n}\n\n/// Solver class for BiCGStab method; right preconditioner ignored (prints warning if not identity)\n/** Methods inherited from \\ref base_solver. **/\ntemplate < typename LinearOperator, typename Preconditioner= pc::identity<LinearOperator>, \n\t   typename RightPreconditioner= pc::identity<LinearOperator> >\nclass bicgstab_solver\n  : public base_solver< bicgstab_solver<LinearOperator, Preconditioner, RightPreconditioner>, LinearOperator >\n{\n    typedef base_solver< bicgstab_solver<LinearOperator, Preconditioner, RightPreconditioner>, LinearOperator > base;\n  public:\n    /// Construct solver from a linear operator; generate (left) preconditioner from it\n    explicit bicgstab_solver(const LinearOperator& A) : base(A), L(A) \n    {\n\tif (!pc::static_is_identity<RightPreconditioner>::value)\n\t    std::cerr << \"Right Preconditioner ignored!\" << std::endl;\n    }\n\n    /// Construct solver from a linear operator and (left) preconditioner\n    bicgstab_solver(const LinearOperator& A, const Preconditioner& L) : base(A), L(L) \n    {\n\tif (!pc::static_is_identity<RightPreconditioner>::value)\n\t    std::cerr << \"Right Preconditioner ignored!\" << std::endl;\n    }\n\n    /// Solve linear system approximately as specified by \\p iter\n    template < typename HilbertSpaceX, typename HilbertSpaceB, typename Iteration >\n    int solve(HilbertSpaceX& x, const HilbertSpaceB& b, Iteration& iter) const\n    {\n\treturn bicgstab(this->A, x, b, L, iter);\n    }\n\n  private:\n    Preconditioner        L;\n};\n\n} // namespace itl\n\n#endif // ITL_BICGSTAB_INCLUDE\n", "meta": {"hexsha": "80b13078858b27a2e4a5fc8cade4bbe71b3516b5", "size": 3881, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/itl/krylov/bicgstab.hpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "boost/numeric/itl/krylov/bicgstab.hpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "boost/numeric/itl/krylov/bicgstab.hpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.1709401709, "max_line_length": 117, "alphanum_fraction": 0.6712187581, "num_tokens": 1074, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.46344105625993737}}
{"text": "#include <iostream>\n#include <vector>\n#include <string>\n#include <fstream>\n#include <boost/thread.hpp>\n#include <boost/chrono.hpp>\n#include <cstdlib>\n#include <ctime>\n#include <chrono>\n#include \"host.h\"\n#include \"Signal_Loader.h\"\n#include \"filesIO.h\"\n#include \"convolution.h\"\n\nusing namespace std;\n\ntemplate <typename T>\nvoid zero_padding(std::vector<T> &x, int N)\n{\n\tfor (int i = 0; i < N; i++)\n\t{\n\t\tx.push_back(0);\n\t}\n}\n\nvoid create_output_file(string output_path)\n{\n\tfstream output_file;\n\toutput_file.open(output_path, std::ios::out);\n\tif (!output_file) {\n\t\tstd::cerr << \"FILE FAILED TO OPEN!\" << std::endl;\n\t\texit(-1);\n\t}\n\toutput_file.close();\n}\n\n\ntemplate <typename T>\nvoid init(vector<T> &x, vector<T> &h, vector<T>&y_linear, vector<T>&y_circular, int &Nh, int N, string filter_path, string output_path)\n{\n\tload_samples(h, filter_path);\n\tNh = h.size();\n\t//zero_padding(h, Nh);\n\tzero_padding(x, Nh-1);\n\tzero_padding(y_linear, 2 * N - 1);\n\tzero_padding(y_circular, N - (Nh - 1));\n\tcreate_output_file(output_path);\n}\n\n\nvoid overlapsave()\n{\n\tstring filter_path = \"D:\\\\MOJE\\\\Projekty\\\\OpenCL\\\\OverlapSaveGPU\\\\OverlapSaveGPU\\\\Filter.csv\";\n\tstring output_path = \"output.csv\";\n\n\n\tvector<float> h;\n\tvector<float> x;\n\tvector<float> y_linear;\n\tvector<float> y_circular;\n\tint N = 1024;\n\tint Nh;\n\tint Fs = 20000;\n\tinit(x, h, y_linear, y_circular, Nh, N, filter_path, output_path);\n\tSignal_Loader<float> w(x, Fs);\n\tboost::thread t(w);\n\t//circular_convolution(x, h, y_linear, y_circular, N);\n\t//for (int i = 0; i < y_circular.size(); i++)\n\t//{\n\t//\tcout << y_circular[i] << endl;\n\t//}\n\n\tint block_number = 0;\n\tint iteration = 0;\n\tint block_is_full;\n\n\twhile (true)\n\t{\n\t\tcout << \"\";\t\t// (workaround) for some reason without this line, program go to following if despite \n\t\tif(x.size() >= N)\n\t\t{\n\t\t\tcout << x.size() << \"      \" << 1024 << \"        \" << (x.size() >= 1024) << endl;\n\n\t\t\tcircular_convolution(x, h, y_linear, y_circular, N);\n\t\t\t//save_samples(y_circular, output_path);\n\t\t\tx.erase(x.begin(), x.begin() + N-(Nh-1));\n\t\t\tblock_number += 1;\n\t\t}\n\t}\n\tt.join();\n}\n\n\n\n\nint main()\n{\n\tsrand(time(NULL));\n\toverlapsave();\n\treturn 0;\n}", "meta": {"hexsha": "c7d9af3cb78384f4e29604516c3861bd68b02d8c", "size": 2121, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "overlapsave/host.cpp", "max_stars_repo_name": "Krzysztofprzem/overlap-save-infinity", "max_stars_repo_head_hexsha": "1b44006553e277e80d688c6e4476283d46689bfb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "overlapsave/host.cpp", "max_issues_repo_name": "Krzysztofprzem/overlap-save-infinity", "max_issues_repo_head_hexsha": "1b44006553e277e80d688c6e4476283d46689bfb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "overlapsave/host.cpp", "max_forks_repo_name": "Krzysztofprzem/overlap-save-infinity", "max_forks_repo_head_hexsha": "1b44006553e277e80d688c6e4476283d46689bfb", "max_forks_repo_licenses": ["Apache-2.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.0, "max_line_length": 135, "alphanum_fraction": 0.6515794437, "num_tokens": 635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.6261241632752916, "lm_q1q2_score": 0.4634410531095019}}
{"text": "/**\n * \\ file AttackReleaseFilter.cpp\n */\n\n#include <ATK/Dynamic/AttackReleaseFilter.h>\n\n#include <ATK/Core/InPointerFilter.h>\n#include <ATK/Core/OutPointerFilter.h>\n#include <ATK/Core/Utilities.h>\n\n#include <gtest/gtest.h>\n\n#include <boost/math/constants/constants.hpp>\n\nconstexpr gsl::index PROCESSSIZE = 1024*64;\n\nTEST(AttackRelease, attack_test)\n{\n  ATK::AttackReleaseFilter<double> filter;\n  filter.set_attack(0.5);\n  ASSERT_EQ(filter.get_attack(), 0.5);\n}\n\nTEST(AttackRelease, attack_range_test)\n{\n  ATK::AttackReleaseFilter<double> filter;\n  ASSERT_THROW(filter.set_attack(-0.000001), ATK::RuntimeError);\n}\n\nTEST(AttackRelease, attack_range2_test)\n{\n  ATK::AttackReleaseFilter<double> filter;\n  ASSERT_THROW(filter.set_attack(1.000001), ATK::RuntimeError);\n}\n\nTEST(AttackRelease, release_test)\n{\n  ATK::AttackReleaseFilter<double> filter;\n  filter.set_release(0.5);\n  ASSERT_EQ(filter.get_release(), 0.5);\n}\n\nTEST(AttackRelease, release_range_test)\n{\n  ATK::AttackReleaseFilter<double> filter;\n  ASSERT_THROW(filter.set_release(-0.000001), ATK::RuntimeError);\n}\n\nTEST(AttackRelease, release_range2_test)\n{\n  ATK::AttackReleaseFilter<double> filter;\n  ASSERT_THROW(filter.set_release(1.000001), ATK::RuntimeError);\n}\n\nTEST(AttackReleaseFilter, triangle_test)\n{\n  std::vector<double> data(PROCESSSIZE);\n  for(gsl::index i = 0; i < PROCESSSIZE/2; ++i)\n  {\n    data[i] = i / 48000;\n  }\n  for(gsl::index i = 0; i < PROCESSSIZE/2; ++i)\n  {\n    data[PROCESSSIZE/2 + i] = (PROCESSSIZE/2 - i) / 48000;\n  }\n  \n  ATK::InPointerFilter<double> generator(data.data(), 1, PROCESSSIZE, false);\n  generator.set_output_sampling_rate(48000);\n\n  std::vector<double> outdata(PROCESSSIZE);\n\n  ATK::AttackReleaseFilter<double> filter(1);\n  filter.set_attack(std::exp(-1./(48000 * 1e-3)));\n  filter.set_release(std::exp(-1./(48000 * 100e-3)));\n  filter.set_input_sampling_rate(48000);\n  filter.set_input_port(0, &generator, 0);\n\n  ATK::OutPointerFilter<double> output(outdata.data(), 1, PROCESSSIZE, false);\n  output.set_input_sampling_rate(48000);\n  output.set_input_port(0, &filter, 0);\n\n  output.process(PROCESSSIZE);\n  \n  for(gsl::index i = 0; i < PROCESSSIZE/2; ++i)\n  {\n    ASSERT_GE(data[i], outdata[i]);\n  }\n  for(gsl::index i = 0; i < PROCESSSIZE/2; ++i)\n  {\n    ASSERT_GE(outdata[PROCESSSIZE / 2 + i], outdata[PROCESSSIZE / 2 + i - 1]);\n  }\n}\n", "meta": {"hexsha": "7b509c5127a1d776d090b8950e70891e269eff66", "size": 2336, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/Dynamic/AttackReleaseFilter.cpp", "max_stars_repo_name": "AudioTK/AudioTK", "max_stars_repo_head_hexsha": "dba42eea68534501efe74692b74edf4792cca231", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2021-02-04T10:47:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T03:45:00.000Z", "max_issues_repo_path": "tests/Dynamic/AttackReleaseFilter.cpp", "max_issues_repo_name": "AudioTK/AudioTK", "max_issues_repo_head_hexsha": "dba42eea68534501efe74692b74edf4792cca231", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-02-01T15:45:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-13T19:39:05.000Z", "max_forks_repo_path": "tests/Dynamic/AttackReleaseFilter.cpp", "max_forks_repo_name": "AudioTK/AudioTK", "max_forks_repo_head_hexsha": "dba42eea68534501efe74692b74edf4792cca231", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-04-12T03:28:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-17T00:47:11.000Z", "avg_line_length": 25.1182795699, "max_line_length": 78, "alphanum_fraction": 0.7119006849, "num_tokens": 681, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.6261241702517975, "lm_q1q2_score": 0.4634410510961066}}
{"text": "#include <Eigen/Dense>\n#include <vector>\n#include <cassert>\n#include <cmath>\n#include \"day_6.hpp\"\n\n\n// We will be using these a lot so for convenience\n// make it so we don't have to put Eigen:: in front of them.\nusing Eigen::MatrixXd;\nusing Eigen::Vector3d;\n\n\n\n/*! \\brief Returns the value of the chi tensor for 3 orbital indices on the same atom\n */\ndouble chi_on_atom(int o1, int o2, int o3, double model_dipole)\n{\n    if(o1 == o2 and o3 == 0)\n        return 1.0;\n    if(o1 == o3 && o3 > 0 && o2 == 0)\n        return model_dipole;\n    if(o2 == o3 && o3 > 0 && o1 == 0)\n        return model_dipole;\n    return 0.0;\n}\n\n\n/*! \\brief Returns the atom index part of an atomic orbital index\n */\nint atom(int ao_index)\n{\n    // Division of two integers always results in an integer in C++\n    return ao_index / orbitals_per_atom;\n}\n\n\n/*! \\brief Returns the atomic orbital index for a given atom index and orbital type\n */\nint ao_index(int atom_p, int orb_p)\n{\n    return atom_p*orbitals_per_atom + orb_p;\n}\n\n\n/*! \\brief Returns the orbital type of an atomic orbital index\n */\nint orb(int ao_index)\n{\n    return ao_index % orbitals_per_atom;\n}\n\n\nMatrixXd calculate_fock_matrix_fast(MatrixXd hamiltonian_matrix,\n                                    MatrixXd interaction_matrix,\n                                    MatrixXd density_matrix,\n                                    double model_dipole)\n{\n    // Number of degrees of freedon\n    const size_t ndof = hamiltonian_matrix.rows();\n    MatrixXd fock_matrix(hamiltonian_matrix); // Calls copy constructor\n\n\n    // Potential term\n    for(size_t p = 0; p < ndof; p++)\n    {\n        for(int orb_q = 0; orb_q < orbitals_per_atom; orb_q++)\n        {\n            int q = ao_index(atom(p), orb_q); // p & q on same atom\n\n            for(int orb_t = 0; orb_t < orbitals_per_atom; orb_t++)\n            {\n                int t = ao_index(atom(p), orb_t); // p & t on same atom\n                double chi_pqt = chi_on_atom(orb(p), orb_q, orb_t, model_dipole);\n\n                for(size_t r = 0; r < ndof; r++)\n                {\n                    for(int orb_s = 0; orb_s < orbitals_per_atom; orb_s++)\n                    {\n                        int s = ao_index(atom(r), orb_s); // r & s on same atom\n                        for(int orb_u = 0; orb_u < orbitals_per_atom; orb_u++)\n                        {\n                            int u = ao_index(atom(r), orb_u); // r & u on same atom\n                            double chi_rsu = chi_on_atom(orb(r), orb_s, orb_u, model_dipole);\n                            fock_matrix(p,q) += 2.0 * chi_pqt * chi_rsu * interaction_matrix(t,u) * density_matrix(r,s);\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    // Exchange term\n    for(size_t p = 0; p < ndof; p++)\n    {\n        for(int orb_s = 0; orb_s < orbitals_per_atom; orb_s++)\n        {\n            int s = ao_index(atom(p), orb_s); // p & s on same atom\n            for(int orb_u = 0; orb_u < orbitals_per_atom; orb_u++)\n            {\n                int u = ao_index(atom(p), orb_u); // p & u on same atom\n                double chi_psu = chi_on_atom(orb(p), orb_s, orb_u, model_dipole);\n\n                for(size_t q = 0; q < ndof; q++)\n                {\n                    for(int orb_r = 0; orb_r < orbitals_per_atom; orb_r++)\n                    {\n                        int r = ao_index(atom(q), orb_r); // q & r on same atom\n                        for(int orb_t = 0; orb_t < orbitals_per_atom; orb_t++)\n                        {\n                            int t = ao_index(atom(q), orb_t);\n                            double chi_rqt = chi_on_atom(orb_r, orb(q), orb_t, model_dipole);\n                            fock_matrix(p,q) -= chi_rqt * chi_psu * interaction_matrix(t,u) * density_matrix(r,s);\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    return fock_matrix;\n}\n\n\ndouble calculate_energy_mp2(std::vector<double> E_occ, std::vector<double> E_virt, MatrixXd v_tilde_flat)\n{\n    size_t num_occ = E_occ.size();    \n    size_t num_virt = E_virt.size();    \n\n    double energy_mp2 = 0.0;\n\n    // The v_tilde matrix has been flattened from 4 indices to 2 indices.\n    // The dimensions of the flattened tensor should be nvirt*nocc x nvirt*nocc\n    size_t nrow = v_tilde_flat.rows(); // should be nvirt*nocc\n    size_t ncol = v_tilde_flat.cols(); // should be nvirt*nocc\n    assert(nrow == num_virt*num_occ);\n    assert(ncol == num_virt*num_occ);\n\n    for(size_t a = 0; a < num_virt; a++)\n    for(size_t i = 0; i < num_occ; i++)\n    {\n        size_t idx_1 = a*num_occ+i;\n        for(size_t b = 0; b < num_virt; b++)\n        for(size_t j = 0; j < num_occ; j++)\n        {\n            size_t idx_2 = b*num_occ+j;\n            size_t idx_3 = a*num_occ+j;\n            size_t idx_4 = b*num_occ+i;\n\n            double numerator = 2.0 * pow(v_tilde_flat(idx_1, idx_2), 2) - v_tilde_flat(idx_1, idx_2)*v_tilde_flat(idx_3, idx_4);\n            double denominator = E_virt[a] + E_virt[b] - E_occ[i] - E_occ[j];\n            energy_mp2 -= numerator/denominator;\n        }\n    }\n\n    return energy_mp2;\n}\n\n", "meta": {"hexsha": "750cc05eae9e5f8ca19277b31d803f5be18a5e89", "size": 5142, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Day_6/qm_project/qm_cpp/day_6.cpp", "max_stars_repo_name": "godotalgorithm/qm_project_sss2019", "max_stars_repo_head_hexsha": "740d571b9f8d751be7748fd08fee88ca02820dd1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Day_6/qm_project/qm_cpp/day_6.cpp", "max_issues_repo_name": "godotalgorithm/qm_project_sss2019", "max_issues_repo_head_hexsha": "740d571b9f8d751be7748fd08fee88ca02820dd1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Day_6/qm_project/qm_cpp/day_6.cpp", "max_forks_repo_name": "godotalgorithm/qm_project_sss2019", "max_forks_repo_head_hexsha": "740d571b9f8d751be7748fd08fee88ca02820dd1", "max_forks_repo_licenses": ["BSD-3-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.3396226415, "max_line_length": 128, "alphanum_fraction": 0.5352003112, "num_tokens": 1364, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473713594991, "lm_q2_score": 0.5312093733737562, "lm_q1q2_score": 0.4633991005041229}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   DataGen_FreeGasElasticMarginalBetaFunction.hpp\n//! \\author Alex Robinson\n//! \\brief  Free gas elastic marginal beta function declaration.\n//!\n//---------------------------------------------------------------------------//\n\n#ifndef DATA_GEN_FREE_GAS_ELASTIC_MARGINAL_BETA_FUNCTION_HPP\n#define DATA_GEN_FREE_GAS_ELASTIC_MARGINAL_BETA_FUNCTION_HPP\n\n// Std Lib Includes\n#include <list>\n\n// Boost Includes\n#include <boost/function.hpp>\n\n// Trilinos Includes\n#include <Teuchos_RCP.hpp>\n\n// FRENSIE Includes\n#include \"DataGen_FreeGasElasticSAlphaBetaFunction.hpp\"\n#include \"Utility_GaussKronrodIntegrator.hpp\"\n#include \"Utility_Tuple.hpp\"\n\nnamespace DataGen{\n\n//! The Free gas elastic marginal beta function\nclass FreeGasElasticMarginalBetaFunction\n{\n\npublic:\n\n  //! Constructor\n  FreeGasElasticMarginalBetaFunction(\n\t      const Teuchos::RCP<Utility::OneDDistribution>& \n\t      zero_temp_elastic_cross_section,\n              const Teuchos::RCP<MonteCarlo::NuclearScatteringAngularDistribution>&\n\t      cm_scattering_distribution,\n\t      const double A,\n\t      const double kT,\n\t      const double E );\n\n  //! Destructor\n  ~FreeGasElasticMarginalBetaFunction()\n  { /* ... */ }\n\n  //! Set the beta and energy values\n  void setIndependentVariables( const double E );\n\n  //! Get the lower beta limit\n  double getBetaMin() const;\n  \n  //! Get the normalization constant\n  double getNormalizationConstant() const;\n\n  //! Evaluate the marginal PDF\n  double operator()( const double beta );\n\n  //! Evaluate the marginal CDF\n  double evaluateCDF( const double beta );\n\nprivate:\n\n  // Update the cached values\n  void updateCachedValues();\n\n  // Function that represents the integral of S(alpha,beta) over all alpha\n  // multiplied by exp(-beta/2)\n  double integratedSAlphaBetaFunction( const double beta );\n\n  // The integration gkq_set for integrating over alpha values\n  Utility::GaussKronrodIntegrator d_alpha_gkq_set;\n\n  // The integration gkq_set for integrating over beta values\n  Utility::GaussKronrodIntegrator d_beta_gkq_set;\n\n  // The free gas elastic S(alpha,beta) function\n  FreeGasElasticSAlphaBetaFunction d_sab_function;\n\n  // The energy value (MeV)\n  double d_E;\n\n  // The atomic weight ratio\n  double d_A;\n\n  // The temperature (MeV)\n  double d_kT;\n\n  // The beta min value\n  double d_beta_min;\n\n  // The normalization constant\n  double d_norm_constant;\n\n  // Cached CDF values (first = beta, second = CDF)\n  std::list<Utility::Pair<double,double> > d_cached_cdf_values;\n};\n\n} // end DataGen namespace\n\n#endif // end DATA_GEN_FREE_GAS_ELASTIC_MARGINAL_BETA_FUNCTION_HPP\n\n//---------------------------------------------------------------------------//\n// end DataGen_FreeGasElasticMarginalBetaFunction.hpp\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "f32680a5ccca032711117aa744b232078507d93d", "size": 2882, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "packages/data_gen/free_gas_sab/src/DataGen_FreeGasElasticMarginalBetaFunction.hpp", "max_stars_repo_name": "lkersting/SCR-2123", "max_stars_repo_head_hexsha": "06ae3d92998664a520dc6a271809a5aeffe18f72", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "packages/data_gen/free_gas_sab/src/DataGen_FreeGasElasticMarginalBetaFunction.hpp", "max_issues_repo_name": "lkersting/SCR-2123", "max_issues_repo_head_hexsha": "06ae3d92998664a520dc6a271809a5aeffe18f72", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "packages/data_gen/free_gas_sab/src/DataGen_FreeGasElasticMarginalBetaFunction.hpp", "max_forks_repo_name": "lkersting/SCR-2123", "max_forks_repo_head_hexsha": "06ae3d92998664a520dc6a271809a5aeffe18f72", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9345794393, "max_line_length": 83, "alphanum_fraction": 0.6665510062, "num_tokens": 644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007394, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.46334434083402143}}
{"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#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MAIN\n\n#include <limits>\n\n#include <boost/test/unit_test.hpp>\n\n#include \"tudat/astro/aerodynamics/equilibriumWallTemperature.h\"\n#include \"tudat/astro/aerodynamics/aerodynamics.h\"\n\nnamespace tudat\n{\nnamespace unit_tests\n{\n\nusing namespace aerodynamics;\n\nBOOST_AUTO_TEST_SUITE( test_fay_riddell_heat_flux )\n\n//! Test if equilibrium temperature is properly computed for variety of cases.\nBOOST_AUTO_TEST_CASE( testEquilibriumTemperature )\n{\n    double airSpeed, noseRadius, wallEmissivity, equilibriumWallTemperature,\n            adiabaticWallTemperature;\n    double airDensity = 1.0E-5;\n    double airTemperature = 300.0;\n    for( unsigned int i = 0; i <= 10; i++ )\n    {\n        airSpeed = 1.0E3 + static_cast< double >( i ) * 1.0E3;\n        double machNumber = airSpeed / 300.0;\n\n        for( unsigned int j = 0; j <= 10; j++ )\n        {\n            noseRadius = 0.001 + static_cast< double >( j ) * 0.1;\n            for( unsigned int k = 0; k < 10; k++ )\n            {\n                wallEmissivity = 0.1 + static_cast< double >( k ) * 0.1;\n                adiabaticWallTemperature\n                        = computeAdiabaticWallTemperature( airTemperature , machNumber );\n\n                std::function< double( const double ) > heatTransferFunction = std::bind(\n                            &computeFayRiddellHeatFlux, airDensity, airSpeed, airTemperature, noseRadius, std::placeholders::_1 );\n\n                equilibriumWallTemperature =\n                        computeEquilibiumWallTemperature( heatTransferFunction, wallEmissivity, adiabaticWallTemperature );\n\n                BOOST_CHECK_CLOSE_FRACTION(\n                            wallEmissivity * electromagnetism::computeBlackbodyRadiationIntensity( equilibriumWallTemperature ),\n                            heatTransferFunction( equilibriumWallTemperature ), 1.0E-12 );\n\n            }\n        }\n    }\n\n}\n\n//! Test if Fay-Ridell heat flux functions produce consistent results for variety of cases.\nBOOST_AUTO_TEST_CASE( testFayRiddellHeatFluxConsistency )\n{\n    double airSpeed, noseRadius, equilibriumWallTemperature,\n            adiabaticWallTemperature;\n    double airDensity = 1.0E-5;\n    double airTemperature = 300.0;\n    double wallEmissivity = 0.7;\n    double heatFlux1, heatFlux2, heatFlux3;\n    for( unsigned int i = 0; i <= 10; i++ )\n    {\n        airSpeed = 1.0E3 + static_cast< double >( i ) * 1.0E3;\n        double machNumber = airSpeed / 300.0;\n\n        for( unsigned int j = 0; j <= 10; j++ )\n        {\n            noseRadius = 0.001 + static_cast< double >( j ) * 0.1;\n\n            adiabaticWallTemperature\n                    = computeAdiabaticWallTemperature( airTemperature , machNumber );\n\n            std::function< double( const double ) > heatTransferFunction = std::bind(\n                        &computeFayRiddellHeatFlux, airDensity, airSpeed, airTemperature, noseRadius, std::placeholders::_1 );\n\n            heatFlux1 = computeEquilibriumFayRiddellHeatFlux(\n                        airDensity, airSpeed, airTemperature, machNumber, noseRadius, wallEmissivity );\n            heatFlux2 = computeEquilibriumHeatflux(\n                        heatTransferFunction, wallEmissivity, adiabaticWallTemperature );\n\n            equilibriumWallTemperature =\n                    computeEquilibiumWallTemperature( heatTransferFunction, wallEmissivity, adiabaticWallTemperature );\n            heatFlux3 = computeFayRiddellHeatFlux(\n                        airDensity, airSpeed, airTemperature, noseRadius, equilibriumWallTemperature );\n\n            BOOST_CHECK_CLOSE_FRACTION(\n                        heatFlux1, heatFlux2, 4.0 * std::numeric_limits< double >::epsilon( ) );\n            BOOST_CHECK_CLOSE_FRACTION(\n                        heatFlux1, heatFlux3, 4.0 * std::numeric_limits< double >::epsilon( ) );\n            BOOST_CHECK_CLOSE_FRACTION(\n                        heatFlux2, heatFlux3, 4.0 * std::numeric_limits< double >::epsilon( ) );\n        }\n    }\n}\n\n//! Test if Fay-Ridell heat flux functions produce correct results for limit cases\nBOOST_AUTO_TEST_CASE( testFayRiddellHeatFluxFunctions )\n{\n    double airSpeed = 6.0E3;\n    double noseRadius = 0.1;\n    double airDensity = 1.0E-5;\n    double airTemperature = 300.0;\n\n    double computedHeatFlux  = computeFayRiddellHeatFlux(\n                airDensity, airSpeed, airTemperature, noseRadius, airTemperature );\n\n    double expectedHeatFlux = 0.5 * FAY_RIDDEL_HEAT_FLUX_CONSTANT * std::pow(\n                airSpeed, 3.0 ) * std::pow( airDensity, 0.5 ) * std::pow( noseRadius, -0.5 );\n    BOOST_CHECK_CLOSE_FRACTION(\n                computedHeatFlux, expectedHeatFlux, 4.0 * std::numeric_limits< double >::epsilon( ) );\n\n    computedHeatFlux  = computeFayRiddellHeatFlux(\n                    0.0, airSpeed, airTemperature, noseRadius, airTemperature );\n    BOOST_CHECK_SMALL( std::fabs( computedHeatFlux ), std::numeric_limits< double >::epsilon( ) );\n\n    computedHeatFlux  = computeFayRiddellHeatFlux(\n                    airDensity, 0.0, airTemperature, noseRadius, airTemperature );\n    BOOST_CHECK_SMALL( std::fabs( computedHeatFlux ), std::numeric_limits< double >::epsilon( ) );\n\n}\n\nBOOST_AUTO_TEST_SUITE_END( )\n\n} // namespace unit_tests\n\n} // namespace tudat\n\n", "meta": {"hexsha": "d2db7241424afdafaabdf3096dfea068327ac8cf", "size": 5684, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/src/astro/aerodynamics/unitTestHeatTransfer.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": "tests/src/astro/aerodynamics/unitTestHeatTransfer.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": "tests/src/astro/aerodynamics/unitTestHeatTransfer.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": 39.7482517483, "max_line_length": 130, "alphanum_fraction": 0.6520056298, "num_tokens": 1438, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637541053281, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.46334433889615506}}
{"text": "#include \"PhysicsTools/Utilities/interface/Parameter.h\"\n#include \"PhysicsTools/Utilities/interface/ZLineShape.h\"\n#include \"PhysicsTools/Utilities/interface/Gaussian.h\"\n#include \"PhysicsTools/Utilities/interface/Numerical.h\"\n#include \"PhysicsTools/Utilities/interface/Exponential.h\"\n#include \"PhysicsTools/Utilities/interface/Polynomial.h\"\n#include \"PhysicsTools/Utilities/interface/Constant.h\"\n#include \"PhysicsTools/Utilities/interface/Convolution.h\"\n#include \"PhysicsTools/Utilities/interface/Operations.h\"\n#include \"PhysicsTools/Utilities/interface/Integral.h\"\n#include \"PhysicsTools/Utilities/interface/MultiHistoChiSquare.h\"\n#include \"PhysicsTools/Utilities/interface/RootMinuit.h\"\n#include \"PhysicsTools/Utilities/interface/RootMinuitCommands.h\"\n#include \"PhysicsTools/Utilities/interface/FunctClone.h\"\n#include \"PhysicsTools/Utilities/interface/rootPlot.h\"\n#include \"TROOT.h\"\n#include \"TH1.h\"\n#include \"TFile.h\"\n#include <boost/program_options.hpp>\nusing namespace boost;\nnamespace po = boost::program_options;\n\n#include <iostream>\n#include <algorithm> \n#include <exception>\n#include <iterator>\n#include <string>\n#include <vector>\nusing namespace std;\n\n// A helper function to simplify the main part.\ntemplate<class T>\nostream& operator<<(ostream& os, const vector<T>& v) {\n  copy(v.begin(), v.end(), ostream_iterator<T>(cout, \" \")); \n  return os;\n}\n\n//A function that sets istogram contents to 0 \n//if they are too small\nvoid fix(TH1* histo) {\n  for(int i = 1; i <= histo->GetNbinsX(); ++i) {\n    if(histo->GetBinContent(i) < 0.1) {\n      histo->SetBinContent(i, 0.0);\n      histo->SetBinError(i, 0.0);\n    }\n  }\n}\n\ntypedef funct::GaussIntegrator IntegratorConv;\ntypedef funct::GaussIntegrator IntegratorNorm;\n\ntypedef funct::Product<funct::Exponential, \n\t\t       funct::Convolution<funct::ZLineShape, funct::Gaussian, IntegratorConv>::type>::type ZPeak;\n\ntypedef funct::Master<ZPeak> SigPeak;\ntypedef funct::Slave<ZPeak> SigPeakClone;\ntypedef funct::Product<funct::Parameter, SigPeak>::type Sig1;\ntypedef funct::Product<funct::Parameter, SigPeakClone>::type Sig2;\n\ntypedef funct::Product<\n            funct::Exponential, \n            funct::Polynomial<2> >::type ExpPoly;\n\nNUMERICAL_FUNCT_INTEGRAL(ExpPoly, GaussIntegrator);\n\ntypedef funct::DefIntegral<ExpPoly, funct::Constant, funct::Constant, IntegratorNorm> ExpPolyNormFactor;\ntypedef funct::Ratio<ExpPoly, ExpPolyNormFactor>::type ExpPolyNorm;\n\ntypedef funct::Product<\n          funct::Parameter, \n          funct::Difference<\n            funct::Ratio<\n              funct::Numerical<2>, \n              funct::Parameter>::type,\n            funct::Numerical<2> >::type>::type Coeff1;\n\ntypedef funct::Product<Coeff1, ExpPolyNorm>::type Bkg1;\n\ntypedef funct::Product<\n          funct::Parameter, \n          funct::Square<\n            funct::Difference<\n              funct::Ratio<\n                funct::Numerical<1>, \n                funct::Parameter>::type,\n              funct::Numerical<1> >::type>::type>::type Coeff2;\n\ntypedef funct::Product<Coeff2, ExpPolyNorm>::type Bkg2;\n\nNUMERICAL_FUNCT_INTEGRAL(Bkg1, GaussIntegrator);\nNUMERICAL_FUNCT_INTEGRAL(Bkg2, GaussIntegrator);\n\ntypedef funct::Sum<Sig1, Bkg1>::type Fun1;\ntypedef funct::Sum<Sig2, Bkg2>::type Fun2;\ntypedef fit::MultiHistoChiSquare<Fun1, Fun2> ChiSquared;\n\nint main(int ac, char *av[]) {\n  gROOT->SetStyle(\"Plain\");\n  try {\n    double fMin, fMax;\n    string ext;\n    po::options_description desc(\"Allowed options\");\n    desc.add_options()\n      (\"help,h\", \"produce help message\")\n      (\"input-file,i\", po::value< vector<string> >(), \"input file\")\n      (\"min,m\", po::value<double>(&fMin)->default_value(60), \"minimum value for fit range\")\n      (\"max,M\", po::value<double>(&fMax)->default_value(120), \"maximum value for fit range\")\n      (\"plot-format,p\", po::value<string>(&ext)->default_value(\"ps\"), \n       \"output plot format\")\n      ;\n    \n    po::positional_options_description p;\n    p.add(\"input-file\", -1);\n    \n    po::variables_map vm;\n    po::store(po::command_line_parser(ac, av).\n\t    options(desc).positional(p).run(), vm);\n    po::notify(vm);\n    \n    if (vm.count(\"help\")) {\n      cout << \"Usage: options_description [options]\\n\";\n      cout << desc;\n      return 0;\n      }\n    \n    fit::RootMinuitCommands<ChiSquared> commands(\"csa08IsoBkg.txt\");\n\n    if (vm.count(\"input-file\")) {\n      cout << \"Input files are: \" \n\t   << vm[\"input-file\"].as< vector<string> >() << \"\\n\";\n      vector<string> v_file = vm[\"input-file\"].as< vector<string> >();\n      for(vector<string>::const_iterator it = v_file.begin(); \n\t  it != v_file.end(); ++it) {\n\tTFile * root_file = new TFile(it->c_str(),\"read\");\n\n\tTH1D * histo1 = (TH1D*) root_file->Get(\"oneNonIsolatedZToMuMuPlots/zMass\");\n\tfix(histo1);\n\tTH1D * histo2 = (TH1D*) root_file->Get(\"twoNonIsolatedZToMuMuPlots/zMass\");\n\tfix(histo2);\n\n\tcout << \">>> histogram loaded\\n\";\n\tstring f_string = *it;\n\treplace(f_string.begin(), f_string.end(), '.', '_');\n\treplace(f_string.begin(), f_string.end(), '/', '_');\n\tstring plot_string = f_string + \".\" + ext;\n\tcout << \">>> Input files loaded\\n\";\n\t\n\tconst char * kYieldZMuMu1 = \"YieldZMuMu1\";\n\tconst char * kYieldZMuMu2 = \"YieldZMuMu2\";\n\tconst char * kYieldBkg = \"YieldBkg\"; \n\tconst char * kEffBkg = \"EffBkg\"; \n\tconst char * kLambdaZMuMu = \"LambdaZMuMu\";\n\tconst char * kMass = \"Mass\";\n\tconst char * kGamma = \"Gamma\";\n\tconst char * kPhotonFactorZMuMu = \"PhotonFactorZMuMu\";\n\tconst char * kInterferenceFactorZMuMu = \"InterferenceFactorZMuMu\";\n\tconst char * kMeanZMuMu = \"MeanZMuMu\";\n\tconst char * kSigmaZMuMu = \"SigmaZMuMu\";\n\tconst char * kAlpha = \"Alpha\";\n\tconst char * kA0 = \"A0\"; \n\tconst char * kA1 = \"A1\"; \n\tconst char * kA2 = \"A2\"; \n\t\n\tfunct::Parameter lambdaZMuMu(kLambdaZMuMu, commands.par(kLambdaZMuMu));\n\tfunct::Parameter mass(kMass, commands.par(kMass));\n\tfunct::Parameter gamma(kGamma, commands.par(kGamma));\n\tfunct::Parameter photonFactorZMuMu(kPhotonFactorZMuMu, commands.par(kPhotonFactorZMuMu)); \n\tfunct::Parameter interferenceFactorZMuMu(kInterferenceFactorZMuMu, commands.par(kInterferenceFactorZMuMu)); \n\tfunct::Parameter yieldZMuMu1(kYieldZMuMu1, commands.par(kYieldZMuMu1));\n\tfunct::Parameter yieldZMuMu2(kYieldZMuMu2, commands.par(kYieldZMuMu2));\n\tfunct::Parameter yieldBkg(kYieldBkg, commands.par(kYieldBkg));\n\tfunct::Parameter effBkg(kEffBkg, commands.par(kEffBkg));\n\tfunct::Parameter meanZMuMu(kMeanZMuMu, commands.par(kMeanZMuMu));\n\tfunct::Parameter sigmaZMuMu(kSigmaZMuMu, commands.par(kSigmaZMuMu)); \n\tfunct::Parameter alpha(kAlpha, commands.par(kAlpha));\n\tfunct::Parameter a0(kA0, commands.par(kA0));\n\tfunct::Parameter a1(kA1, commands.par(kA1));\n\tfunct::Parameter a2(kA2, commands.par(kA2));\n\tfunct::Constant cFMin(fMin), cFMax(fMax);\n\n\tIntegratorConv integratorConv(1.e-4);\n\tIntegratorNorm integratorNorm(1.e-4);\n\n\tZPeak zPeak = funct::Exponential(lambdaZMuMu) * \n\t  funct::conv(funct::ZLineShape(mass, gamma, photonFactorZMuMu, interferenceFactorZMuMu), \n\t\t      funct::Gaussian(meanZMuMu, sigmaZMuMu), \n\t\t      -3*sigmaZMuMu.value(), 3*sigmaZMuMu.value(), integratorConv);\n\tSigPeak sp = funct::master(zPeak);\n\tSigPeakClone spc = funct::slave(sp);\n\tSig1 sig1 = yieldZMuMu1 * sp;\n\tSig2 sig2 = yieldZMuMu2 * spc;\n\tfunct::Numerical<1> _1;\n\tfunct::Numerical<2> _2;\n\tExpPoly ep = funct::Exponential(alpha) * funct::Polynomial<2>(a0, a1, a2);\n\tExpPolyNorm epn = ep / ExpPolyNormFactor(ep, cFMin, cFMax, integratorNorm);\n\tCoeff1 c1 = yieldBkg * (_2 / effBkg - _2);\n\tBkg1 bkg1 = c1 * epn;\n\tCoeff2 c2 = yieldBkg * ((_1 /effBkg - _1) ^ _2);\n\tBkg2 bkg2 = c2 * epn;\n\tFun1 f1 = sig1 + bkg1;\n\tFun2 f2 = sig2 + bkg2;\n\n\tChiSquared chi2(f1, histo1, f2, histo2, fMin, fMax);\n\tcout << \"N. deg. of freedom: \" << chi2.degreesOfFreedom() << endl;\n\tfit::RootMinuit<ChiSquared> minuit(chi2, true);\n\tcommands.add(minuit, yieldZMuMu1);\n\tcommands.add(minuit, yieldZMuMu2);\n\tcommands.add(minuit, yieldBkg);\n\tcommands.add(minuit, effBkg);\n\tcommands.add(minuit, lambdaZMuMu);\n\tcommands.add(minuit, mass);\n\tcommands.add(minuit, gamma);\n\tcommands.add(minuit, photonFactorZMuMu);\n\tcommands.add(minuit, interferenceFactorZMuMu);\n\tcommands.add(minuit, meanZMuMu);\n\tcommands.add(minuit, sigmaZMuMu);\n\tcommands.add(minuit, alpha);\n\tcommands.add(minuit, a0);\n\tcommands.add(minuit, a1);\n\tcommands.add(minuit, a2);\n\tcommands.run(minuit);\n\tconst unsigned int nPar = 15;//WARNIG: this must be updated manually for now\n\tROOT::Math::SMatrix<double, nPar, nPar, ROOT::Math::MatRepSym<double, nPar> > err;\n\tminuit.getErrorMatrix(err);\n\tstd::cout << \"error matrix:\" << std::endl;\n\tfor(unsigned int i = 0; i < nPar; ++i) {\n\t  for(unsigned int j = 0; j < nPar; ++j) {\n\t    std::cout << err(i, j) << \"\\t\";\n\t  }\n\t  std::cout << std::endl;\n\t} \n\tminuit.printFitResults();\n\n\tfunct::GaussIntegrator integrator(1.e-6);\n\tdouble nbkg1 = funct::integral_f(bkg1, fMin, fMax, integrator);\n\tdouble nbkg2 = funct::integral_f(bkg2, fMin, fMax, integrator);\n\tstd::cout << \"Background yields in [\" << fMin <<\", \" << fMax << \"]: \"\n\t\t  << nbkg1 <<\", \" <<nbkg2 << std::endl;\n\n\n\t// binning is at 1 GeV, fortunately\n\tdouble i1 = histo1->Integral(int(fMin), int(fMax));\n\tdouble i2 = histo2->Integral(int(fMin), int(fMax));\n\tstd::cout << \"Histogram integrals in [\" << fMin <<\", \" << fMax << \"]: \"\n\t\t  << i1 <<\", \" << i2 << std::endl;\n\tdouble s;\n\ts = 0;\n\tfor(int i = 1; i <= histo1->GetNbinsX(); ++i)\n\t  s += histo1->GetBinContent(i);\n\thisto1->SetEntries(s);\n\ts = 0;\n\tfor(int i = 1; i <= histo2->GetNbinsX(); ++i)\n\t  s += histo2->GetBinContent(i);\n\thisto2->SetEntries(s);\n\n\tdouble extrap = nbkg1*nbkg1 / nbkg2 /4;\n\tcout << \"extrapolated background with no isolated muons:\" << extrap << endl;\n\n\tstring Plot1 = \"OneIsolated_\" + plot_string;\n\troot::plot<Fun1>(Plot1.c_str(), *histo1, f1, fMin, fMax, \n\t\t\t yieldZMuMu1, lambdaZMuMu, mass, gamma, photonFactorZMuMu, interferenceFactorZMuMu, \n\t\t\t meanZMuMu, sigmaZMuMu, yieldBkg, effBkg, alpha, a0, a1, a2,\n\t\t\t kRed, 2, kDashed, 100, \n\t\t\t \"Z -> #mu #mu mass\", \"#mu #mu invariant mass (GeV/c^{2})\", \n\t\t\t \"Events\");\n\tstring Plot2 = \"TwoIsolated_\" + plot_string;\n\troot::plot<Fun2>(Plot2.c_str(), *histo2, f2, fMin, fMax, \n\t\t\t yieldZMuMu2, lambdaZMuMu, mass, gamma, photonFactorZMuMu, interferenceFactorZMuMu, \n\t\t\t meanZMuMu, sigmaZMuMu, yieldBkg, effBkg, alpha, a0, a1, a2,\n\t\t\t kRed, 2, kDashed, 100, \n\t\t\t \"Z -> #mu #mu mass\", \"#mu #mu invariant mass (GeV/c^{2})\", \n\t\t\t \"Events\");\n      }\n    }\n    \n  }\n  catch(exception& e) {\n    cerr << \"error: \" << e.what() << \"\\n\";\n    return 1;\n  }\n  catch(...) {\n    cerr << \"Exception of unknown type!\\n\";\n  }\n  return 0;\n}\n\n\n\n", "meta": {"hexsha": "5f8ab8d8263060609ba59648b24874b5ab5140a2", "size": 10488, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ElectroWeakAnalysis/ZMuMu/bin/csa08IsoBkg.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/csa08IsoBkg.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/csa08IsoBkg.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": 36.2906574394, "max_line_length": 109, "alphanum_fraction": 0.6805873379, "num_tokens": 3202, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.859663754105328, "lm_q2_score": 0.538983220687684, "lm_q1q2_score": 0.46334433889615495}}
{"text": "#pragma once\n\n/*\nstruct Coord {\n  double x;\n  double y;\n  Coord(){}\n  Coord(int x, int y) : x(x), y(y) {}\n};\n*/\n\n#include <boost/geometry/geometries/geometries.hpp>\ntypedef boost::geometry::model::point<double, 3, boost::geometry::cs::cartesian> point3;\n\nclass Coord3 : public point3\n{\npublic:\n  Coord3(){}\n  Coord3(double x, double y, double z) : point3(x, y, z){}\n\n  double x()\n  {\n    return this->get<0>();\n  }\n\n  double y()\n  {\n    return this->get<1>();\n  }\n\n  double z()\n  {\n    return this->get<2>();\n  }\n\n  void setx(double x)\n  {\n    this->set<0>(x);\n  }\n\n  void sety(double y)\n  {\n    this->set<1>(y);\n  }\n\n  void setz(double z)\n  {\n    this->set<2>(z);\n  }\n};\n", "meta": {"hexsha": "d15764cda35d6c110a162f0eaa25cf1e2614e636", "size": 672, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "geom/Coord3.hpp", "max_stars_repo_name": "brychanrobot/planning-utils", "max_stars_repo_head_hexsha": "cb100706f5d39255724d82c1225018311af25dec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "geom/Coord3.hpp", "max_issues_repo_name": "brychanrobot/planning-utils", "max_issues_repo_head_hexsha": "cb100706f5d39255724d82c1225018311af25dec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "geom/Coord3.hpp", "max_forks_repo_name": "brychanrobot/planning-utils", "max_forks_repo_head_hexsha": "cb100706f5d39255724d82c1225018311af25dec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 13.1764705882, "max_line_length": 88, "alphanum_fraction": 0.5550595238, "num_tokens": 220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145998, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4633018247495842}}
{"text": "#include <cmath>\n#include <vector>\n#include <string>\n#include \"multi_lidar_calib/common.h\"\n#include \"multi_lidar_calib/tic_toc.h\"\n#include <pcl_conversions/pcl_conversions.h>\n#include <pcl/point_cloud.h>\n#include <pcl/point_types.h>\n#include <pcl/filters/voxel_grid.h>\n#include <pcl/kdtree/kdtree_flann.h>\n#include <pcl/io/io.h>\n#include <pcl/io/pcd_io.h>\n#include <pcl/io/obj_io.h>\n#include <pcl/PolygonMesh.h>\n#include <pcl/point_cloud.h>\n#include <pcl/io/vtk_lib_io.h>\n#include <pcl/visualization/cloud_viewer.h>\n#include <pcl/sample_consensus/method_types.h>\n#include <pcl/sample_consensus/model_types.h>\n#include <pcl/segmentation/sac_segmentation.h>\n#include <pcl/filters/extract_indices.h>\n#include <pcl/sample_consensus/ransac.h>\n#include <pcl/sample_consensus/sac_model_plane.h>\n#include <pcl/sample_consensus/sac_model_sphere.h>\n#include <pcl/visualization/pcl_visualizer.h>\n#include <pcl/sample_consensus/sac_model_perpendicular_plane.h>\n#include <pcl/filters/passthrough.h>\n#include <ros/ros.h>\n#include <sensor_msgs/Imu.h>\n#include <sensor_msgs/PointCloud2.h>\n#include <tf/transform_datatypes.h>\n#include <tf/transform_broadcaster.h>\n #include <ceres/ceres.h>\n #include \"lidarFactor.hpp\"\n#include <pcl/features/vfh.h>\n#include <pcl/features/normal_3d.h>\n#include <boost/thread/thread.hpp>\n#include <pcl/common/common_headers.h>\n#include <pcl/io/pcd_io.h>\n#include <pcl/console/parse.h>\n#include <pcl/visualization/pcl_visualizer.h>\n#include <sstream>\n#include<vector>\n\n#include<mutex>\n\n#define PI 3.1415926\n\nusing std::atan2;\nusing std::cos;\nusing std::sin;\n\ndouble lidar_z_height = -1;\n\nros::Publisher  pubFittedPlane;\n\ndouble parameters[7] = {0, 0, 0, 1, 0, 0, 0}; // \u6fc0\u5149\u96f7\u8fbe\u95f4\u76f8\u5bf9\u4f4d\u59ff\u5173\u7cfb \n\nEigen::Map<Eigen::Quaterniond> q_to_be_optimized(parameters);\nEigen::Map<Eigen::Vector3d> t_to_be_optimized(parameters + 4);\n\n\nstd::string extracted_path = \" \";\nint pcd_num_per_lidar = 0;\nvoid planeFitting(pcl::PointCloud<pcl::PointXYZ>::Ptr extracted_cloud, pcl::ModelCoefficients::Ptr & coefficients)\n{   \n\n    pcl::PointIndices::Ptr inliers (new pcl::PointIndices);\n    pcl::SACSegmentation<pcl::PointXYZ> seg;\n    seg.setOptimizeCoefficients (true);\n    seg.setModelType (pcl::SACMODEL_PLANE);\n    seg.setMethodType (pcl::SAC_RANSAC);\n    seg.setDistanceThreshold (0.01);\n     seg.setInputCloud(extracted_cloud);\n    seg.segment (*inliers, *coefficients);\n\n    // // ax + by + cz + d = 0\uff0c\u5176\u4e2d\u6cd5\u5411\u91cf\u4e3a(a, b, c)\n    // std::cout<<\"\u5e73\u9762\u53c2\u6570\uff1a\"<<std::endl;\n    // std::cout<<\"a\uff1a\"<<coefficients->values[0]<<std::endl;\n    // std::cout<<\"b\uff1a\"<<coefficients->values[1]<<std::endl;\n    // std::cout<<\"c\uff1a\"<<coefficients->values[2]<<std::endl;\n    // std::cout<<\"d\uff1a\"<<coefficients->values[3]<<std::endl;\n    double a,b,c,d;\n    a =   coefficients->values[0];\n    b =  coefficients->values[1];\n    c =  coefficients->values[2];\n    d =  coefficients->values[3];\n    // double numerator = fabs(  a*x_c+b*y_c+c*z_c+d  );\n    // double denominator = std::sqrt(  a*a+b*b+c*c );\n    // double distanceToArea = numerator/ denominator;\n    pcl::PointCloud<pcl::PointXYZ>::Ptr fittedPlaneCloud(new pcl::PointCloud<pcl::PointXYZ>);\n    for (int i=0; i<inliers->indices.size();i++)\n    {\n        int ind = inliers->indices[i];\n         fittedPlaneCloud->points.push_back(  extracted_cloud->points[ind]  );\n    }\n\n    sensor_msgs::PointCloud2 fittedPlaneCloudMsg;\n    pcl::toROSMsg(*fittedPlaneCloud, fittedPlaneCloudMsg);\n    fittedPlaneCloudMsg.header.stamp = ros::Time::now();\n    fittedPlaneCloudMsg.header.frame_id = \"/rslidar\";\n    pubFittedPlane.publish(fittedPlaneCloudMsg);\n\n}\n\n\n\npcl::PointCloud<pcl::PointXYZ>::Ptr planeFittingReturn(pcl::PointCloud<pcl::PointXYZ>::Ptr extracted_cloud, pcl::ModelCoefficients::Ptr & coefficients)\n{   \n\n    pcl::PointIndices::Ptr inliers (new pcl::PointIndices);\n    pcl::SACSegmentation<pcl::PointXYZ> seg;\n    seg.setOptimizeCoefficients (true);\n    seg.setModelType (pcl::SACMODEL_PLANE);\n    seg.setMethodType (pcl::SAC_RANSAC);\n    seg.setDistanceThreshold (0.01);\n     seg.setInputCloud(extracted_cloud);\n    seg.segment (*inliers, *coefficients);\n\n    // // ax + by + cz + d = 0\uff0c\u5176\u4e2d\u6cd5\u5411\u91cf\u4e3a(a, b, c)\n    // std::cout<<\"\u5e73\u9762\u53c2\u6570\uff1a\"<<std::endl;\n    // std::cout<<\"a\uff1a\"<<coefficients->values[0]<<std::endl;\n    // std::cout<<\"b\uff1a\"<<coefficients->values[1]<<std::endl;\n    // std::cout<<\"c\uff1a\"<<coefficients->values[2]<<std::endl;\n    // std::cout<<\"d\uff1a\"<<coefficients->values[3]<<std::endl;\n    double a,b,c,d;\n    a =   coefficients->values[0];\n    b =  coefficients->values[1];\n    c =  coefficients->values[2];\n    d =  coefficients->values[3];\n    // double numerator = fabs(  a*x_c+b*y_c+c*z_c+d  );\n    // double denominator = std::sqrt(  a*a+b*b+c*c );\n    // double distanceToArea = numerator/ denominator;\n    pcl::PointCloud<pcl::PointXYZ>::Ptr fittedPlaneCloud(new pcl::PointCloud<pcl::PointXYZ>);\n    for (int i=0; i<inliers->indices.size();i++)\n    {\n        int ind = inliers->indices[i];\n         fittedPlaneCloud->points.push_back(  extracted_cloud->points[ind]  );\n    }\n\n    sensor_msgs::PointCloud2 fittedPlaneCloudMsg;\n    pcl::toROSMsg(*fittedPlaneCloud, fittedPlaneCloudMsg);\n    fittedPlaneCloudMsg.header.stamp = ros::Time::now();\n    fittedPlaneCloudMsg.header.frame_id = \"/rslidar\";\n    pubFittedPlane.publish(fittedPlaneCloudMsg);\n\n    return fittedPlaneCloud;\n\n}\n\n\n\n\nint main(int argc, char **argv)\n{\n\n    ros::init(argc, argv, \"multi_lidar_calibration\");\n\tros::NodeHandle nh;\n\n    ros::param::get(\"~extracted_path\", extracted_path);\n    ros::param::get(\"~pcd_num_per_lidar\", pcd_num_per_lidar);\n\n    pubFittedPlane = nh.advertise<sensor_msgs::PointCloud2>(\"/fitted_plane\", 100);\n\n    for (int iterCount = 0; iterCount < 10; iterCount++)\n    {\n\n            ceres::LossFunction *loss_function = new ceres::HuberLoss(0.1);\n            ceres::LocalParameterization *q_parameterization =\n                new ceres::EigenQuaternionParameterization();\n            ceres::Problem::Options problem_options;\n\n            ceres::Problem problem(problem_options);\n            problem.AddParameterBlock(parameters, 4, q_parameterization);\n            problem.AddParameterBlock(parameters + 4, 3);\n\n            for (int k=0; k<pcd_num_per_lidar; k++)\n            {\n\n                std::stringstream ss;\n                std::string filename_pt0 = extracted_path;\n                std::string filename_pt1 = extracted_path;\n                ss << k+1;\n                std::string num = ss.str();\n                filename_pt0.append(num);\n                filename_pt0.append(\"_0.pcd\");   \n                filename_pt1.append(num);\n                filename_pt1.append(\"_1.pcd\");  \n                \n                std::cout<<\"Extracting \"<<k<<\" pointcloud from \"<<  filename_pt0<<std::endl;\n                std::cout<<\"Extracting \"<<k<<\" pointcloud from \"<<  filename_pt1<<std::endl;\n                pcl::PointCloud<pcl::PointXYZ>::Ptr cloud0(new pcl::PointCloud<pcl::PointXYZ>);\n                pcl::PointCloud<pcl::PointXYZ>::Ptr cloud1(new pcl::PointCloud<pcl::PointXYZ>);\n\n                if (pcl::io::loadPCDFile<pcl::PointXYZ> (filename_pt0, *cloud0) == -1)\n                    {\n                    PCL_ERROR (\"Couldn't read PCD file \\n\");\n                    }\n                if (pcl::io::loadPCDFile<pcl::PointXYZ> (filename_pt1, *cloud1) == -1)\n                    {\n                    PCL_ERROR (\"Couldn't read PCD file \\n\");\n                    }\n\n                \n                pcl::ModelCoefficients::Ptr coefficients0 (new pcl::ModelCoefficients);\n                planeFitting(cloud0, coefficients0);\n                pcl::ModelCoefficients::Ptr coefficients1 (new pcl::ModelCoefficients);\n                planeFitting(cloud1,coefficients1);\n\n                // \u4e24\u5e73\u9762\u6cd5\u7ebf\u7684\u5939\u89d2\u4f5c\u4e3a\u4e00\u4e2a\u635f\u5931\u503c\n                Eigen::Vector3d norm0(coefficients0->values[0], coefficients0->values[1], coefficients0->values[2]);\n                Eigen::Vector3d norm1(coefficients1->values[0], coefficients1->values[1], coefficients1->values[2]);\n                ceres::CostFunction *cost_function;\n                cost_function = LidarNormFactor::Create(norm0, norm1);\n                problem.AddResidualBlock(cost_function, loss_function, parameters, parameters + 4);\n\n\n\n\n                TicToc t_solver;\n                ceres::Solver::Options options;\n                options.linear_solver_type = ceres::DENSE_QR;\n                options.max_num_iterations = 10;\n                options.minimizer_progress_to_stdout = false;\n                options.check_gradients = false;\n                options.gradient_check_relative_precision = 1e-4;\n                ceres::Solver::Summary summary;\n                ceres::Solve(options, &problem, &summary);\n\n\n                sleep(0.2);\n\n            }\n\n    }\n    printf(\"result q %f %f %f %f result t %f %f %f\\n\", parameters[3], parameters[0], parameters[1], parameters[2],parameters[4], parameters[5], parameters[6]);\n  // ====================================================== //=========================================================\n  // \u63a5\u4e0b\u6765\u6807\u5e73\u79fb\uff1a\uff08\u4e4b\u6240\u4ee5\u5206\u5f00\u6807\u5b9a\u662f\u56e0\u4e3a\u5982\u679c\u5e73\u79fb\u4e0d\u51c6\uff0c\u8d77\u7801\u4fdd\u8bc1\u65cb\u8f6c\u662f\u51c6\u7684\uff0c\u5e73\u79fb\u4e0d\u4f1a\u5f71\u54cd\u65cb\u8f6c\u3002\u5b9e\u9a8c\u53d1\u73b0\uff0c\u8fd9\u6837\u6807\u5b9a\u7684\u8bdd\u5e73\u79fb\u4e5f\u633a\u51c6\uff09\n    for (int iterCount = 0; iterCount < 10; iterCount++)\n    {\n\n            ceres::LossFunction *loss_function = new ceres::HuberLoss(0.1);\n            ceres::Problem::Options problem_options;\n            ceres::Problem problem(problem_options);\n            problem.AddParameterBlock(parameters + 4, 3);\n\n            for (int k=0; k<pcd_num_per_lidar; k++)\n            {\n\n                std::stringstream ss;\n                std::string filename_pt0 = extracted_path;\n                std::string filename_pt1 = extracted_path;\n                ss << k+1;\n                std::string num = ss.str();\n                filename_pt0.append(num);\n                filename_pt0.append(\"_0.pcd\");   \n                filename_pt1.append(num);\n                filename_pt1.append(\"_1.pcd\");  \n                \n                std::cout<<\"Extracting \"<<k<<\" pointcloud from \"<<  filename_pt0<<std::endl;\n                std::cout<<\"Extracting \"<<k<<\" pointcloud from \"<<  filename_pt1<<std::endl;\n                pcl::PointCloud<pcl::PointXYZ>::Ptr cloud0(new pcl::PointCloud<pcl::PointXYZ>);\n                pcl::PointCloud<pcl::PointXYZ>::Ptr cloud1(new pcl::PointCloud<pcl::PointXYZ>);\n                pcl::PointCloud<pcl::PointXYZ>::Ptr cloud0_plane(new pcl::PointCloud<pcl::PointXYZ>);\n                pcl::PointCloud<pcl::PointXYZ>::Ptr cloud1_plane(new pcl::PointCloud<pcl::PointXYZ>);\n\n                if (pcl::io::loadPCDFile<pcl::PointXYZ> (filename_pt0, *cloud0) == -1)\n                    {\n                    PCL_ERROR (\"Couldn't read PCD file \\n\");\n                    }\n                if (pcl::io::loadPCDFile<pcl::PointXYZ> (filename_pt1, *cloud1) == -1)\n                    {\n                    PCL_ERROR (\"Couldn't read PCD file \\n\");\n                    }\n\n                \n                pcl::ModelCoefficients::Ptr coefficients0 (new pcl::ModelCoefficients);\n                cloud0_plane = planeFittingReturn(cloud0, coefficients0);\n                pcl::ModelCoefficients::Ptr coefficients1 (new pcl::ModelCoefficients);\n                cloud1_plane = planeFittingReturn(cloud1,coefficients1);\n\n                // \u4e00\u5171\u6709\u4e09\u7ef4\u635f\u5931\u503c\uff0c\u5206\u522b\u4ee3\u8868\uff1a\u3002\u3002\u3002\u3002\u3002\u3002\u5148\u52a0\u4e00\u7ef4\n                // 0\uff1a\u8d28\u5fc3\u8ddd\u79bb\n                // \u8ba1\u7b97\u8d28\u5fc3\n                double center_x0 = 0;\n                double center_y0 = 0;\n                double center_z0 = 0;\n                double center_x1 = 0;\n                double center_y1 = 0;\n                double center_z1 = 0;\n                for (int i=0; i<cloud0_plane->points.size(); i++)\n                {\n                    center_x0 += cloud0_plane->points[i].x;\n                    center_y0 += cloud0_plane->points[i].y;\n                    center_z0 += cloud0_plane->points[i].z;\n                }\n                center_x0 /= cloud0_plane->points.size();\n                center_y0 /= cloud0_plane->points.size();\n                center_z0 /= cloud0_plane->points.size();\n\n\n                for (int i=0; i<cloud1_plane->points.size(); i++)\n                {\n                    // \u5148\u5c06\u70b9\u7528\u65cb\u8f6c\u8f6c\u8fc7\u53bb\uff1a\n                    Eigen::Vector3d tmppoint(cloud1_plane->points[i].x,  cloud1_plane->points[i].y, cloud1_plane->points[i].z);\n                    Eigen::Vector3d tmppoint_roted =  q_to_be_optimized.matrix() * tmppoint;\n                    center_x1 += tmppoint_roted.x();\n                    center_y1 +=tmppoint_roted.y();\n                    center_z1 += tmppoint_roted.z();\n                }\n                center_x1 /= cloud1_plane->points.size();\n                center_y1 /= cloud1_plane->points.size();\n                center_z1 /= cloud1_plane->points.size();\n\n\n                Eigen::Vector3d plane_center0(center_x0, center_y0, center_z0) ;\n                Eigen::Vector3d plane_center1(center_x1, center_y1, center_z1) ;\n\n                ceres::CostFunction *cost_function;\n                cost_function = LidarCenterFactor::Create(plane_center0, plane_center1);\n                problem.AddResidualBlock(cost_function, loss_function, parameters + 4);\n\n\n                TicToc t_solver;\n                ceres::Solver::Options options;\n                options.linear_solver_type = ceres::DENSE_QR;\n                options.max_num_iterations = 10;\n                options.minimizer_progress_to_stdout = false;\n                options.check_gradients = false;\n                options.gradient_check_relative_precision = 1e-4;\n                ceres::Solver::Summary summary;\n                ceres::Solve(options, &problem, &summary);\n\n\n                sleep(0.2);\n\n            }\n\n    }\n\n\n\n    std::cout<<\"======================\u6700\u7ec8\u6807\u5b9a\u7ed3\u679c======================\"<<std::endl;\n    printf(\"result q %f %f %f %f result t %f %f %f\\n\", parameters[3], parameters[0], parameters[1], parameters[2],parameters[4], parameters[5], parameters[6]);\n    std::cout<<q_to_be_optimized.matrix()<<std::endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "0ce73d4ca48a67fd85bf450f05edf447cad32594", "size": 13857, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "multi_lidar_calib/src/multi_lidar_calib.cpp", "max_stars_repo_name": "BIT-MJY/Multiple_Lidar_Calibration", "max_stars_repo_head_hexsha": "6bee0699a7a9a1c98b897206f38ae0d4e34524b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2021-08-13T05:52:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T05:01:35.000Z", "max_issues_repo_path": "multi_lidar_calib/src/multi_lidar_calib.cpp", "max_issues_repo_name": "Student865/Multiple_Lidar_Calibration", "max_issues_repo_head_hexsha": "58d70b1863d6e1524f61ec9c69acaf9edbb84198", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-09-11T14:40:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-27T13:21:00.000Z", "max_forks_repo_path": "multi_lidar_calib/src/multi_lidar_calib.cpp", "max_forks_repo_name": "Student865/Multiple_Lidar_Calibration", "max_forks_repo_head_hexsha": "58d70b1863d6e1524f61ec9c69acaf9edbb84198", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2021-08-13T12:09:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T08:15:01.000Z", "avg_line_length": 39.7048710602, "max_line_length": 159, "alphanum_fraction": 0.5970989392, "num_tokens": 3523, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145998, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4633018247495842}}
{"text": "#include <iostream>\n#include <vector>\n#include <set>\n#include <iterator>\n#include <cmath>\n#include <string>\n#include <chrono>\n#include <exception>\n#include <queue>\n#include <stack>\n#include <bitset>\n#include <random>\n#include <set>\n#include <boost/math/distributions/normal.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/graphviz.hpp>\n#include <sys/time.h>\n#include \"DataTypes.hpp\"\n#include \"ATG.hpp\"\n\nstd::ostream& operator<<(std::ostream &os, const NodeType  &et) {\n  std::string state; \n  switch(et.status) {\n      case NotReady : state = \"NotReady\"; break;\n      case Ready    : state = \"Ready\"; break;\n      case Finished : state = \"Finished\"; break;\n      case Active   : state = \"Active\"; break;\n      default  : state = \"None\"; break;\n  }  \n  os << \"Task{id:\"<<et.id<<\",start:\" << et.start_time << \",C:\" <<  et.C << \",stop:\"<<et.stop_time<<\",alloc:\"<<et.alloc<<\",status:\"<<state<<\"}\";\n  return os;\n}\n\n/* Execution time characteristics of jth MT-task */\ndouble AppTaskGraph::tau_j(int jid, int l) {\n  NodeType *nd = &(this->gSS[this->vdMap[jid]]);\n  double dj    = nd->dj;\n  double tau1  = nd->tau1;\n  double ret   = (tau1)*(pow(l,-dj));\n  return ret;\n}\n\n/* Generate a random task graph */\nAppTaskGraph::AppTaskGraph(int N, double p) : vdMap(N) {\n    if (p >= 1 && p < 0) {\n        throw std::invalid_argument(\"Wrong value of parameter p\");\n    }\n    // initExecTimeChar(int N)\n    std::random_device rd;\n    std::mt19937 gen(rd());\n    std::uniform_real_distribution<> dis2(0.01, 0.99);\n    std::uniform_real_distribution<> dis1(80,400);\n    std::bernoulli_distribution d(p);\n\n    int i, j, cnt = 0;\n    \n    this->wC = 0.0;\n    /* Create the nodes */\n    /*\n     * -1 reflects unintialized values\n     */\n    for (i = 0; i < N; i++) {\n        NodeType vi2       = {.status = NotReady, \\\n                              .estart = -1, \\\n                              .dj = dis2(gen), .tau1 = dis1(gen), .id = i, \\\n                              .alloc = -1, .start_time = -1, .stop_time = -1, .C = -1};\n        this->vdMap[i]     = add_vertex(vi2,this->gSS);\n\n        this->wC += this->tau_j(vi2.id,1);\n    }\n    this->deadline = 0.4*(this->wC);\n\n    /* Connect the nodes */\n    for (i = 0; i < N; i++) {\n        for (j = i+1; j < N; j++) {\n            if (d(gen)) {\n                EdgeType edg = {.edgeNum = cnt++};\n                add_edge(this->vdMap[i],this->vdMap[j],edg,this->gSS);\n            }\n        }\n    }\n\n    /* Initialize the ready set and schedule set to null */\n    this->t = 0;\n    this->computeNbdMap();\n    this->initialized = true;\n}\n\nAppTaskGraph::AppTaskGraph() : vdMap(6) {\n    /* Create a DAG as shown in buggy.dot */\n    int N = 6;\n    int i;\n\n    std::random_device rd;\n    std::mt19937 gen(rd());\n    std::uniform_real_distribution<> dis2(0.01, 0.99);\n    std::uniform_real_distribution<> dis1(80,400);\n    // std::bernoulli_distribution d(p);\n\n    for (i = 0; i < N; i++) {\n        NodeType vi2       = {.status = NotReady, \\\n                              .estart = -1, \\\n                              .dj = dis2(gen), .tau1 = dis1(gen), .id = i, \\\n                              .alloc = -1, .start_time = -1, .stop_time = -1, .C = -1};\n        this->vdMap[i]     = add_vertex(vi2,this->gSS);\n    }\n\n    EdgeType edg = {.edgeNum = 8};\n    add_edge(this->vdMap[0],this->vdMap[2],edg,this->gSS);\n    add_edge(this->vdMap[0],this->vdMap[4],edg,this->gSS);\n    add_edge(this->vdMap[0],this->vdMap[5],edg,this->gSS);\n    add_edge(this->vdMap[1],this->vdMap[2],edg,this->gSS);\n    add_edge(this->vdMap[1],this->vdMap[4],edg,this->gSS);\n    add_edge(this->vdMap[1],this->vdMap[5],edg,this->gSS);\n    add_edge(this->vdMap[2],this->vdMap[3],edg,this->gSS);\n    add_edge(this->vdMap[2],this->vdMap[5],edg,this->gSS);\n    add_edge(this->vdMap[3],this->vdMap[5],edg,this->gSS);\n    add_edge(this->vdMap[4],this->vdMap[5],edg,this->gSS);\n\n}\n\nvoid AppTaskGraph::writeDot(int iter) {\n    std::cout << \"\\n-- graphviz output START --\" << std::endl;\n    std::ofstream dotf;\n    std::string dotFilename = \"demo\"+std::to_string(iter)+\".dot\";\n    dotf.open(dotFilename,std::ios::out | std::ios::trunc);\n    write_graphviz(dotf,this->gSS,DAGVertexPW(this->gSS),DAGEdgePW(this->gSS));\n    dotf.close();\n    std::cout << \"\\n-- graphviz output END --\" << std::endl;\n}\n\n/* Compute the longest path to each node in DAG from source node */\nvoid AppTaskGraph::computeHeight(bool schedule) {\n    DAGInEdgeIterator  eiIS, eiIE;\n    int N = this->vdMap.size();\n    for (int i = 0; i < N; i++) {\n        NodeType *nd = &(this->gSS[this->vdMap[i]]);\n        nd->estart   = 0;\n\n        int max = 0;\n        for (boost::tie(eiIS,eiIE) = boost::in_edges(this->vdMap[i],this->gSS); eiIS != eiIE; eiIS++) {\n            auto ndPrevId    = boost::source(*eiIS, this->gSS);\n            NodeType *ndPrev = &(this->gSS[ndPrevId]);\n            if (max < (ndPrev->estart + ndPrev->C))\n                max = ndPrev->estart + ndPrev->C;\n        }\n        nd->estart = max;\n\n        if (schedule) {\n            nd->start_time = nd->estart;\n            nd->stop_time  = nd->start_time + nd->C;\n        }\n    }\n}\n\nvoid AppTaskGraph::reset() {\n    for (auto it = this->vdMap.begin(); it != this->vdMap.end(); it++) {\n        NodeType *nd = &(this->gSS[*it]);\n\n        nd->status = NotReady;\n        nd->estart = -1;\n        nd->start_time = -1;\n        nd->stop_time = -1;\n        nd->alloc  = -1;\n    }\n}\n\nvoid AppTaskGraph::computeNbdMap() {\n    int N = this->vdMap.size();\n    DAGInEdgeIterator  eiIS, eiIE;\n    DAGOutEdgeIterator  eiOS, eiOE;\n\n    for (int i = 0; i < N; i++) {\n        /* Insert predecessors */\n        std::vector<DAGVertexType> preds;\n        std::vector<DAGVertexType> succs;\n\n        for (boost::tie(eiIS,eiIE) = boost::in_edges(this->vdMap[i],this->gSS); eiIS != eiIE; eiIS++) {\n            auto ndPrevId    = boost::source(*eiIS, this->gSS);\n            preds.push_back(ndPrevId);\n        }\n    \n        /* Insert successors */    \n        for (boost::tie(eiOS,eiOE) = boost::out_edges(this->vdMap[i],this->gSS); eiOS != eiOE; eiOS++) {\n            auto ndSuccId    = boost::target(*eiOS, this->gSS);\n            succs.push_back(ndSuccId);\n        }\n\n        /* */\n        this->predVdMap.insert({this->vdMap[i],preds});\n        this->succVdMap.insert({this->vdMap[i],succs});\n    }\n}\n\n/* Construct an ATG from a dot file */\nAppTaskGraph::AppTaskGraph(std::string dotFile) {\n    boost::dynamic_properties dp;\n    std::ifstream dotF(dotFile);\n    \n    dp.property(\"dj\", boost::get(&NodeType::dj,this->gSS));\n    dp.property(\"tau1\", boost::get(&NodeType::tau1,this->gSS));\n    dp.property(\"node_id\", boost::get(&NodeType::id,this->gSS));\n\n    read_graphviz(dotF,this->gSS,dp);\n}", "meta": {"hexsha": "2237a7c4bb81c22f0d2d462cbad40d1026ef12a9", "size": 6707, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "BoostGraph/src/ATG.cpp", "max_stars_repo_name": "Arka2009/ita3e", "max_stars_repo_head_hexsha": "1b33e9a0ca167449c68596b7065ea84af2ed3942", "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": "BoostGraph/src/ATG.cpp", "max_issues_repo_name": "Arka2009/ita3e", "max_issues_repo_head_hexsha": "1b33e9a0ca167449c68596b7065ea84af2ed3942", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-04-07T19:19:09.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-07T19:19:09.000Z", "max_forks_repo_path": "BoostGraph/src/ATG.cpp", "max_forks_repo_name": "Arka2009/ita3e", "max_forks_repo_head_hexsha": "1b33e9a0ca167449c68596b7065ea84af2ed3942", "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.7170731707, "max_line_length": 143, "alphanum_fraction": 0.5561353809, "num_tokens": 2062, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.46330181806109033}}
{"text": "/*\n * Copyright 2017-2020 CNRS-UM LIRMM, CNRS-AIST JRL\n */\n\n#include <gram_savitzky_golay/spatial_filters.h>\n\n#include <boost/circular_buffer.hpp>\n#include <Eigen/SVD>\n\nnamespace gram_sg\n{\nRotationFilter::RotationFilter(const gram_sg::SavitzkyGolayFilterConfig & conf)\n: sg_conf(conf), sg_filter(conf), buffer(2 * sg_filter.config().m + 1)\n\n{\n  reset(Eigen::Matrix3d::Zero());\n}\n\nvoid RotationFilter::reset(const Eigen::Matrix3d & r)\n{\n  buffer.clear();\n  // Initialize to data\n  for(size_t i = 0; i < buffer.capacity(); i++)\n  {\n    buffer.push_back(r);\n  }\n}\n\nvoid RotationFilter::reset()\n{\n  RotationFilter::reset(Eigen::Matrix3d::Zero());\n}\n\nvoid RotationFilter::clear()\n{\n  buffer.clear();\n}\n\nvoid RotationFilter::add(const Eigen::Matrix3d & r)\n{\n  buffer.push_back(r);\n}\nEigen::Matrix3d RotationFilter::filter() const\n{\n  // Apply a temporal (savitzky-golay) convolution,\n  // followed by an orthogonalization\n  const Eigen::Matrix3d & result = sg_filter.filter(buffer);\n  Eigen::JacobiSVD<Eigen::Matrix3d> svd(result, Eigen::ComputeFullV | Eigen::ComputeFullU);\n  Eigen::Matrix3d res = svd.matrixU() * svd.matrixV().transpose();\n  return res;\n}\n\nTransformFilter::TransformFilter(const gram_sg::SavitzkyGolayFilterConfig & conf) : trans_filter(conf), rot_filter(conf)\n{\n}\n\nvoid TransformFilter::reset(const Eigen::Affine3d & T)\n{\n  trans_filter.reset(T.translation());\n  rot_filter.reset(T.rotation());\n}\n\nvoid TransformFilter::reset()\n{\n  trans_filter.reset();\n  rot_filter.reset();\n}\n\nvoid TransformFilter::clear()\n{\n  trans_filter.clear();\n  rot_filter.clear();\n}\n\nvoid TransformFilter::add(const Eigen::Affine3d & T)\n{\n  trans_filter.add(T.translation());\n  rot_filter.add(T.rotation());\n}\n\nEigen::Affine3d TransformFilter::filter() const\n{\n  const Eigen::Vector3d & trans_res = trans_filter.filter();\n  const Eigen::Matrix3d & rot_res = rot_filter.filter();\n  Eigen::Matrix4d rot = Eigen::Matrix4d::Identity();\n  rot.block<3, 3>(0, 0) = rot_res;\n  rot.block<3, 1>(0, 3) = trans_res;\n  return Eigen::Affine3d(rot);\n}\n\n} // namespace gram_sg\n", "meta": {"hexsha": "fc3b69e671de9f0d5f5478431a6fd95b85b0568b", "size": 2051, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/spatial_filters.cpp", "max_stars_repo_name": "hedgepigdaniel/gram_savitzky_golay", "max_stars_repo_head_hexsha": "ad18bf4ee1648dc80144681565a324f9f4ad7914", "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/spatial_filters.cpp", "max_issues_repo_name": "hedgepigdaniel/gram_savitzky_golay", "max_issues_repo_head_hexsha": "ad18bf4ee1648dc80144681565a324f9f4ad7914", "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/spatial_filters.cpp", "max_forks_repo_name": "hedgepigdaniel/gram_savitzky_golay", "max_forks_repo_head_hexsha": "ad18bf4ee1648dc80144681565a324f9f4ad7914", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.2934782609, "max_line_length": 120, "alphanum_fraction": 0.7094100439, "num_tokens": 573, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746404, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4633018180610903}}
{"text": "#include <stdio.h>\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <string>\n#include <cassert>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <opencv2/opencv.hpp>\n#include <opencv2/core/eigen.hpp>\n#include <boost/filesystem.hpp>\n#include <yaml-cpp/yaml.h>\n\n/**\n * @brief Stereo camera parameters\n *\n */\nstruct StereoParam\n{\n\n    // extrinsic matrix, transform right camera frame into left camera frame\n    Eigen::Matrix4d T_rl;\n    // left camera intrinsic\n    Eigen::Matrix3d cam0_intrinsic;\n    // left camera distortion_coeffs\n    double cam0_distortions[5];\n\n    // right camera intrinsic\n    Eigen::Matrix3d cam1_intrinsic;\n    // right camera distortion_coeffs\n    double cam1_distortions[5];\n\n    int img_width;\n    int img_height;\n    // assume cam0 and cam1 use identical distortion type\n    std::string distortion_type;\n\n    StereoParam() : T_rl(Eigen::Matrix4d::Identity()),\n                    cam0_intrinsic(Eigen::Matrix3d::Identity()),\n                    cam1_intrinsic(Eigen::Matrix3d::Identity()),\n                    img_width(2592),\n                    img_height(2048)\n    {\n        memset(cam0_distortions, 0, 5 * sizeof(double));\n        memset(cam1_distortions, 0, 5 * sizeof(double));\n        distortion_type = \"equidistant\";\n    }\n\n    void getExtrinsic(cv::Mat &R_rl, cv::Mat &t_rl)\n    {\n        Eigen::Matrix3d R = T_rl.block<3, 3>(0, 0);\n        Eigen::Vector3d t = T_rl.block<3, 1>(0, 3);\n\n        cv::eigen2cv(R, R_rl);\n        cv::eigen2cv(t, t_rl);\n    }\n\n    void getCam0Param(cv::Mat &K, cv::Mat &D)\n    {\n        cv::eigen2cv(cam0_intrinsic, K);\n//        cv::Mat distortion = (cv::Mat_<double>(1, 5) << cam0_distortions[0], cam0_distortions[1],\n//                cam0_distortions[2], cam0_distortions[3], cam0_distortions[4]);\n        cv::Mat distortion = (cv::Mat_<double>(1, 4) << cam0_distortions[0], cam0_distortions[1],\n                cam0_distortions[2], cam0_distortions[3]);\n        D = distortion.clone();\n    }\n\n    void getCam1Param(cv::Mat &K, cv::Mat &D)\n    {\n        cv::eigen2cv(cam1_intrinsic, K);\n//        cv::Mat distortion = (cv::Mat_<double>(1, 5) << cam1_distortions[0], cam1_distortions[1],\n//                cam1_distortions[2], cam1_distortions[3], cam1_distortions[4]);\n        cv::Mat distortion = (cv::Mat_<double>(1, 4) << cam1_distortions[0], cam1_distortions[1],\n                cam1_distortions[2], cam1_distortions[3]);\n        D = distortion.clone();\n    }\n};\n\n/**\n * @brief Monocular camera parameters\n *\n */\nstruct MonocularParam{\n    // camera intrinsic\n    Eigen::Matrix3d cam_intrinsic;\n    // camera distortion_coeffs\n    double cam_distortions[5];\n\n    int img_width;\n    int img_height;\n\n    std::string distortion_type;\n\n    MonocularParam() :cam_intrinsic(Eigen::Matrix3d::Identity()),\n                    img_width(2592),\n                    img_height(2048)\n    {\n        memset(cam_distortions, 0, 5 * sizeof(double));\n        distortion_type = \"equidistant\";\n    }\n\n    void getCamParam(cv::Mat &K, cv::Mat &D)\n    {\n        cv::eigen2cv(cam_intrinsic, K);\n//        cv::Mat distortion = (cv::Mat_<double>(1, 5) << cam_distortions[0], cam_distortions[1],\n//                cam_distortions[2], cam_distortions[3], cam_distortions[4]);\n        cv::Mat distortion = (cv::Mat_<double>(1, 4) << cam_distortions[0], cam_distortions[1],\n                cam_distortions[2], cam_distortions[3]);\n        D = distortion.clone();\n    }\n\n\n};\n\n/**\n * @brief parse kalibr yaml file support: pinhole + equidistant\n *\n * @param kalib_intrin_file\n * @param camera Camera Model param\n */\nbool loadKalibrResult(const std::string &kalib_result_file, StereoParam &stereo_param)\n{\n    if (kalib_result_file.empty())\n    {\n        std::cout << \"[loadKalibrResult] Empty input file name!\\n\";\n        return false;\n    }\n\n    std::ifstream fs(kalib_result_file);\n    if (!fs.is_open())\n    {\n        std::cout << \"[loadKalibrResult] Error read \" << kalib_result_file << \"\\n\";\n        return false;\n    }\n\n    YAML::Node root_node;\n    YAML::Node cam0_node;\n    YAML::Node cam1_node;\n\n    try\n    {\n        root_node = YAML::LoadFile(kalib_result_file);\n    }\n    catch (YAML::BadFile &e)\n    {\n        std::cout << \"[loadKalibrResult] Could not open file: \" << kalib_result_file << \"\\n\";\n        return false;\n    }\n    catch (YAML::ParserException &e)\n    {\n        std::cout << \"[loadKalibrResult] Invalid file format: \" << kalib_result_file << \"\\n\";\n        return false;\n    }\n    if (root_node.IsNull())\n    {\n        std::cout << \"[loadKalibrResult] Could not open file: \" << kalib_result_file << \"\\n\";\n        return false;\n    }\n\n    int img_width = 0, img_height = 0;\n    std::string distortion_type = \"equidistant\";\n\n    cam0_node = root_node[\"cam0\"];\n    double cam0_distortion[5] = {0.0};\n    cam0_distortion[0] = cam0_node[\"distortion_coeffs\"][0].as<double>();\n    cam0_distortion[1] = cam0_node[\"distortion_coeffs\"][1].as<double>();\n    cam0_distortion[2] = cam0_node[\"distortion_coeffs\"][2].as<double>();\n    cam0_distortion[3] = cam0_node[\"distortion_coeffs\"][3].as<double>();\n    // cam0_distortion[0] = cam0_node[\"distortion_coeffs\"][0].as<double>();\n    Eigen::Matrix3d cam0_intrinsic = Eigen::Matrix3d::Identity();\n    cam0_intrinsic(0, 0) = cam0_node[\"intrinsics\"][0].as<double>();\n    cam0_intrinsic(1, 1) = cam0_node[\"intrinsics\"][1].as<double>();\n    cam0_intrinsic(0, 2) = cam0_node[\"intrinsics\"][2].as<double>();\n    cam0_intrinsic(1, 2) = cam0_node[\"intrinsics\"][3].as<double>();\n\n    cam1_node = root_node[\"cam1\"];\n    double cam1_distortion[5] = {0.0};\n    cam1_distortion[0] = cam1_node[\"distortion_coeffs\"][0].as<double>();\n    cam1_distortion[1] = cam1_node[\"distortion_coeffs\"][1].as<double>();\n    cam1_distortion[2] = cam1_node[\"distortion_coeffs\"][2].as<double>();\n    cam1_distortion[3] = cam1_node[\"distortion_coeffs\"][3].as<double>();\n    // cam1_distortion[0] = cam1_node[\"distortion_coeffs\"][0].as<double>();\n    Eigen::Matrix3d cam1_intrinsic = Eigen::Matrix3d::Identity();\n    cam1_intrinsic(0, 0) = cam1_node[\"intrinsics\"][0].as<double>();\n    cam1_intrinsic(1, 1) = cam1_node[\"intrinsics\"][1].as<double>();\n    cam1_intrinsic(0, 2) = cam1_node[\"intrinsics\"][2].as<double>();\n    cam1_intrinsic(1, 2) = cam1_node[\"intrinsics\"][3].as<double>();\n\n    img_width = cam1_node[\"resolution\"][0].as<int>();\n    img_height = cam1_node[\"resolution\"][1].as<int>();\n\n    distortion_type = cam1_node[\"distortion_model\"].as<std::string>();\n\n    Eigen::Matrix4d extrinsic = Eigen::Matrix4d::Identity();\n    for (size_t i = 0; i < cam1_node[\"T_cn_cnm1\"].size(); ++i)\n    {\n        extrinsic(i, 0) = cam1_node[\"T_cn_cnm1\"][i][0].as<double>();\n        extrinsic(i, 1) = cam1_node[\"T_cn_cnm1\"][i][1].as<double>();\n        extrinsic(i, 2) = cam1_node[\"T_cn_cnm1\"][i][2].as<double>();\n        extrinsic(i, 3) = cam1_node[\"T_cn_cnm1\"][i][3].as<double>();\n    }\n\n    stereo_param.T_rl = extrinsic;\n    std::cout << \"[loadKalibrResult] T_rl : \\n\"\n              << stereo_param.T_rl << \"\\n\";\n    Eigen::Vector3d baseline = stereo_param.T_rl.block<3,1>(0,3);\n    std::cout << \"[loadKalibrResult] baseline norm : \\n\"\n              << baseline.norm() << \"\\n\";\n\n    std::cout << \"[loadKalibrResult] baseline * fx = \\n\" <<\n                 (baseline.norm() * cam0_intrinsic(0, 0)) << \"\\n\";\n\n    stereo_param.cam0_intrinsic = cam0_intrinsic;\n    std::cout << \"[loadKalibrResult] cam0 intrinsic : \\n\"\n              << stereo_param.cam0_intrinsic << \"\\n\";\n    memcpy(stereo_param.cam0_distortions, cam0_distortion, 5 * sizeof(double));\n    std::cout << \"[loadKalibrResult] cam0 distrotion : \" << stereo_param.cam0_distortions[0] << \", \" << stereo_param.cam0_distortions[3] << \"\\n\";\n    stereo_param.cam1_intrinsic = cam1_intrinsic;\n    std::cout << \"[loadKalibrResult] cam1 intrinsic : \\n\"\n              << stereo_param.cam1_intrinsic << \"\\n\";\n    memcpy(stereo_param.cam1_distortions, cam1_distortion, 5 * sizeof(double));\n    std::cout << \"[loadKalibrResult] cam1 distrotion : \" << stereo_param.cam1_distortions[0] << \", \" << stereo_param.cam1_distortions[3] << \"\\n\";\n    stereo_param.img_width = img_width;\n    stereo_param.img_height = img_height;\n    stereo_param.distortion_type = distortion_type;\n\n    return true;\n}\n\n/**\n * @brief parse kalibr yaml file support: pinhole + equidistant\n *\n * @param kalib_intrin_file\n * @param camera Camera Model param\n */\nbool loadKalibrResult(const std::string &kalib_result_file, MonocularParam &mono_param)\n{\n    if (kalib_result_file.empty())\n    {\n        std::cout << \"[loadKalibrResult] Empty input file name!\\n\";\n        return false;\n    }\n\n    std::ifstream fs(kalib_result_file);\n    if (!fs.is_open())\n    {\n        std::cout << \"[loadKalibrResult] Error read \" << kalib_result_file << \"\\n\";\n        return false;\n    }\n\n    YAML::Node root_node;\n    YAML::Node cam0_node;\n    try\n    {\n        root_node = YAML::LoadFile(kalib_result_file);\n    }\n    catch (YAML::BadFile &e)\n    {\n        std::cout << \"[loadKalibrResult] Could not open file: \" << kalib_result_file << \"\\n\";\n        return false;\n    }\n    catch (YAML::ParserException &e)\n    {\n        std::cout << \"[loadKalibrResult] Invalid file format: \" << kalib_result_file << \"\\n\";\n        return false;\n    }\n    if (root_node.IsNull())\n    {\n        std::cout << \"[loadKalibrResult] Could not open file: \" << kalib_result_file << \"\\n\";\n        return false;\n    }\n\n    int img_width = 0, img_height = 0;\n    std::string distortion_type = \"equi-distant\";\n\n    cam0_node = root_node[\"cam0\"];\n    double cam0_distortion[5] = {0.0};\n    cam0_distortion[0] = cam0_node[\"distortion_coeffs\"][0].as<double>();\n    cam0_distortion[1] = cam0_node[\"distortion_coeffs\"][1].as<double>();\n    cam0_distortion[2] = cam0_node[\"distortion_coeffs\"][2].as<double>();\n    cam0_distortion[3] = cam0_node[\"distortion_coeffs\"][3].as<double>();\n    // cam0_distortion[0] = cam0_node[\"distortion_coeffs\"][0].as<double>();\n    Eigen::Matrix3d cam0_intrinsic = Eigen::Matrix3d::Identity();\n    cam0_intrinsic(0, 0) = cam0_node[\"intrinsics\"][0].as<double>();\n    cam0_intrinsic(1, 1) = cam0_node[\"intrinsics\"][1].as<double>();\n    cam0_intrinsic(0, 2) = cam0_node[\"intrinsics\"][2].as<double>();\n    cam0_intrinsic(1, 2) = cam0_node[\"intrinsics\"][3].as<double>();\n\n    img_width = cam0_node[\"resolution\"][0].as<int>();\n    img_height = cam0_node[\"resolution\"][1].as<int>();\n\n    distortion_type = cam0_node[\"distortion_model\"].as<std::string>();\n\n    mono_param.cam_intrinsic = cam0_intrinsic;\n    std::cout << \"[loadKalibrResult] cam0 intrinsic : \\n\"\n              << mono_param.cam_intrinsic << \"\\n\";\n    memcpy(mono_param.cam_distortions, cam0_distortion, 5 * sizeof(double));\n    std::cout << \"[loadKalibrResult] cam0 distrotion : \" << mono_param.cam_distortions[0] << \", \" << mono_param.cam_distortions[3] << \"\\n\";\n\n    mono_param.img_width = img_width;\n    mono_param.img_height = img_height;\n    mono_param.distortion_type = distortion_type;\n\n    return true;\n}\n\n/**\n * @brief Write mono-camera parameters\n *\n * @param file_name is the output yaml file name.\n * @param mono_param is the monocular camera parameters.\n */\nbool writeCamParam(const std::string &file_name, MonocularParam &mono_param)\n{\n    if (file_name.empty())\n    {\n        std::cout << \"[writeCamParam] Empty file name!\\n\";\n        return false;\n    }\n\n    cv::FileStorage fs(file_name, cv::FileStorage::WRITE);\n    if (!fs.isOpened())\n    {\n        std::cout << \"[writeCamParam] Fail to open \" << file_name << \"\\n\";\n        return false;\n    }\n\n    fs << \"camera_model\" << mono_param.distortion_type;\n\n    cv::Mat K, D;\n    //\n    {\n        mono_param.getCamParam(K, D);\n        fs << \"camera_matrix\" << K;\n        fs << \"distortion_coefficients\" << D;\n    }\n\n    fs << \"avg_reprojection_error\" << 1.2799437834241592e-01;\n    fs << \"image_width\" << mono_param.img_width;\n    fs << \"image_height\" << mono_param.img_height;\n    fs << \"serial_num\" <<  1;\n    fs.release();\n    return true;\n}\n\n\n/**\n * @brief Write stereo-camera parameters\n *\n * @param file_name is the output yaml file name.\n * @param cam_index is .\n * @param mono_param is the monocular camera parameters.\n */\nbool writeCamParam(const std::string &file_name, const int cam_index, StereoParam &stereo_param)\n{\n    if (file_name.empty())\n    {\n        std::cout << \"[writeCamParam] Empty file name!\\n\";\n        return false;\n    }\n\n    cv::FileStorage fs(file_name, cv::FileStorage::WRITE);\n    if (!fs.isOpened())\n    {\n        std::cout << \"[writeCamParam] Fail to open \" << file_name << \"\\n\";\n        return false;\n    }\n\n    fs << \"image_width\" << stereo_param.img_width;\n    fs << \"image_height\" << stereo_param.img_height;\n    fs << \"distortion_type\" << stereo_param.distortion_type;\n\n    cv::Mat K, D;\n    //\n    if (0 == cam_index)\n    {\n        stereo_param.getCam0Param(K, D);\n        fs << \"camera_matrix\" << K;\n        fs << \"distortion_coefficients\" << D;\n    }\n    if (1 == cam_index)\n    {\n        stereo_param.getCam1Param(K, D);\n        fs << \"camera_matrix\" << K;\n        fs << \"distortion_coefficients\" << D;\n    }\n\n    fs.release();\n    return true;\n}\nbool writeExtrinsicParam(const std::string &file_name, StereoParam &stereo_param)\n{\n    if (file_name.empty())\n    {\n        std::cout << \"[writeExtrinsicParam] Empty file name!\\n\";\n        return false;\n    }\n\n    cv::FileStorage fs(file_name, cv::FileStorage::WRITE);\n    if (!fs.isOpened())\n    {\n        std::cout << \"[writeExtrinsicParam] Fail to open \" << file_name << \"\\n\";\n        return false;\n    }\n\n    cv::Mat T, R, t;\n    stereo_param.getExtrinsic(R, t);\n    cv::eigen2cv(stereo_param.T_rl, T);\n\n    fs << \"T_rl\" << T;\n    fs << \"R\" << R;\n    fs << \"T\" << t.t();\n    fs.release();\n    return true;\n}\n\n\n#define MONOCULAR_RESULT 0\n#define STEREO_RESULT 1\n\nint main(int argc, char *argv[])\n{\n    if (argc < 3)\n    {\n        std::cout << \"[convert_Kalibr_output] Usage : convert_Kalibr_output kalibr_output.yaml output_dir  model \\n\"\n                  << \"This executable is used to convert multicamera kalibr calibration file into 3 files seperately!\\n\"\n                  << \"model : 0--convert monocular kalibr output yaml file \\n\"\n                  << \"model : 1--convert stereo kalibr output yaml file \\n\";\n        return -1;\n    }\n\n    std::string input_fn(argv[1]);\n    std::string output_dir(argv[2]);\n    int model = std::stoi (argv[3]);\n\n    if (output_dir.back() != '/')\n        output_dir += \"/\";\n\n    if(model == MONOCULAR_RESULT)\n    {\n        std::string output_cam0_intrinsic_fn = output_dir + \"equi_intrinsic.yml\";\n        MonocularParam mono_param;\n\n        bool sts = loadKalibrResult (input_fn, mono_param);\n        if (!sts)\n        {\n            std::cout << \"[convert_kalibr_result] Fail to load monocular kalibr result!\\n\";\n            return -1;\n        }\n\n        sts = writeCamParam(output_cam0_intrinsic_fn, mono_param);\n        if (!sts)\n        {\n            std::cout << \"[convert_kalibr_result] Fail to write camera0 intrinsic!\" << output_cam0_intrinsic_fn << \"\\n\";\n            return -1;\n        }\n\n        return 0;\n    }\n\n\n    if(model == STEREO_RESULT)\n    {\n        std::string output_cam0_intrinsic_fn = output_dir + \"left_intrinsic.yml\";\n        std::string output_cam1_intrinsic_fn = output_dir + \"right_intrinsic.yml\";\n        std::string output_stereo_fn = output_dir + \"extrinsic.yml\";\n\n        StereoParam stereo_param;\n        bool sts = loadKalibrResult(input_fn, stereo_param);\n        if (!sts)\n        {\n            std::cout << \"[convert_kalibr_result] Fail to load stereo kalibr result!\\n\";\n            return -1;\n        }\n\n        sts = writeCamParam(output_cam0_intrinsic_fn, 0, stereo_param);\n        if (!sts)\n        {\n            std::cout << \"[convert_kalibr_result] Fail to write camera0 intrinsic!\" << output_cam0_intrinsic_fn << \"\\n\";\n            return -1;\n        }\n        sts = writeCamParam(output_cam1_intrinsic_fn, 1, stereo_param);\n        if (!sts)\n        {\n            std::cout << \"[convert_kalibr_result] Fail to write camera1 intrisnic!\" << output_cam1_intrinsic_fn << \"\\n\";\n            return -1;\n        }\n\n        sts = writeExtrinsicParam(output_stereo_fn, stereo_param);\n        if (!sts)\n        {\n            std::cout << \"[convert_kalibr_result] Fail to write extrinsic file \" << output_stereo_fn << \"\\n\";\n            return -1;\n        }\n    }\n    return 0;\n}\n", "meta": {"hexsha": "8d6538eab63eb762e8e7b16c40e4784610c87e31", "size": 16353, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_cvt_kalibr_result.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_cvt_kalibr_result.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_cvt_kalibr_result.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": 32.7715430862, "max_line_length": 145, "alphanum_fraction": 0.6151164924, "num_tokens": 4591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746404, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4633018180610903}}
{"text": "#ifndef INCLUDE_SWIFT_VIO_POINT_LANDMARK_MODELS_HPP_\n#define INCLUDE_SWIFT_VIO_POINT_LANDMARK_MODELS_HPP_\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <ceres/ceres.h>\n#include <okvis/ceres/LocalParamizationAdditionalInterfaces.hpp>\n\nnamespace swift_vio {\n// Expressed in an anchor camera frame [\\alpha, \\beta, 1, \\rho] = [x, y, z, w]/z.\nclass InverseDepthParameterization final: public okvis::ceres::LocalParamizationAdditionalInterfaces\n{\npublic:\n  static const int kModelId = 1;\n  static const int kGlobalDim = 4;\n  static const int kLocalDim = 3;\n\n  // Generalization of the addition operation,\n  //\n  //   x_plus_delta = Plus(x, delta)\n  //\n  // with the condition that Plus(x, 0) = x.\n  bool Plus(const double* x, const double* delta, double* x_plus_delta) const final {\n    return plus(x, delta, x_plus_delta);\n  }\n\n  // The jacobian of Plus(x, delta) w.r.t delta at delta = 0.\n  //\n  // jacobian is a row-major GlobalSize() x LocalSize() matrix.\n  bool ComputeJacobian(const double* x, double* jacobian) const final {\n    return plusJacobian(x, jacobian);\n  }\n\n  static bool plusJacobian(const double*, double* jacobian) {\n    Eigen::Map<Eigen::Matrix<double, kGlobalDim, kLocalDim, Eigen::RowMajor>> j(jacobian);\n    j.setZero();\n    j(0, 0) = 1.0;\n    j(1, 1) = 1.0;\n    j(3, 2) = 1.0;\n    return true;\n  }\n\n  // Size of x.\n  int GlobalSize() const final {\n    return kGlobalDim;\n  }\n\n  // Size of delta.\n  int LocalSize() const final {\n    return kLocalDim;\n  }\n\n  static bool plus(const double* x, const double* delta, double* x_plus_delta);\n\n  static bool minus(const double* x, const double* x_plus_delta, double* delta);\n\n  bool Minus(const double *x, const double *x_plus_delta,\n             double *delta) const final {\n    return minus(x, x_plus_delta, delta);\n  }\n\n  static bool liftJacobian(const double* /*x*/, double* jacobian) {\n    Eigen::Map<Eigen::Matrix<double, kLocalDim, kGlobalDim, Eigen::RowMajor>> j(jacobian);\n    j.setZero();\n    j(0, 0) = 1.0;\n    j(1, 1) = 1.0;\n    j(2, 3) = 1.0;\n    return true;\n  }\n\n  /// \\brief Computes the Jacobian from minimal space to naively\n  /// overparameterised space as used by ceres.\n  /// @param[in] x Variable.\n  /// @param[out] jacobian the Jacobian (dimension minDim x dim).\n  /// \\return True on success.\n  bool ComputeLiftJacobian(const double *x, double *jacobian) const final {\n    return liftJacobian(x, jacobian);\n  }\n\n  static void toHomogeneousPoint(const double *x, double *y, double *jacobian) {\n    Eigen::Map<const Eigen::Matrix<double, kGlobalDim, 1>> inversepoint(x);\n    Eigen::Map<Eigen::Matrix<double, kGlobalDim, 1>> homogpoint(y);\n    double z = 1.0 / inversepoint[3];\n    homogpoint = inversepoint * z;\n    if (jacobian) {\n      Eigen::Map<Eigen::Matrix<double, kGlobalDim, kGlobalDim, Eigen::RowMajor>>\n          j(jacobian);\n      double z2 = z * z;\n      j << z, 0, 0, -inversepoint[0] * z2,\n          0, z, 0, -inversepoint[1] * z2,\n          0, 0, z, -inversepoint[2] * z2,\n          0, 0, 0, 0;\n    }\n  }\n};\n\n// [x, y, z, w, c, s]\n// [x, y, z, w] is the quaternion underlying unit bearing vector n such that\n// n = q(w, x, y, z) * [0, 0, 1]'.\n// c, s are cos(theta) and sin(theta) where \\theta is the parallax angle.\nclass ParallaxAngleParameterization final: public okvis::ceres::LocalParamizationAdditionalInterfaces {\npublic:\n  static const int kModelId = 2;\n  static const int kGlobalDim = 6;\n  static const int kLocalDim = 3;\n\n  // Generalization of the addition operation,\n  //\n  //   x_plus_delta = Plus(x, delta)\n  //\n  // with the condition that Plus(x, 0) = x.\n  bool Plus(const double* x, const double* delta, double* x_plus_delta) const {\n    return plus(x, delta, x_plus_delta);\n  }\n\n  // The jacobian of Plus(x, delta) w.r.t delta at delta = 0.\n  // jacobian is a row-major GlobalSize() x LocalSize() matrix.\n  bool ComputeJacobian(const double* /*x*/, double* jacobian) const {\n    Eigen::Map<Eigen::Matrix<double, kGlobalDim, kLocalDim, Eigen::RowMajor>> j(jacobian);\n    j.setIdentity();\n    return true;\n  }\n\n  static bool plusJacobian(const double*, double* jacobian);\n\n  // Size of x.\n  int GlobalSize() const final {\n    return kGlobalDim;\n  }\n\n  // Size of delta.\n  int LocalSize() const final {\n    return kLocalDim;\n  }\n\n  /// \\brief Generalization of the addition operation,\n  ///        x_plus_delta = Plus(x, delta)\n  ///        with the condition that Plus(x, 0) = x.\n  /// @param[in] x Variable.\n  /// @param[in] delta Perturbation.\n  /// @param[out] x_plus_delta Perturbed x.\n  static bool plus(const double* x, const double* delta, double* x_plus_delta);\n\n  static bool minus(const double* x, const double* x_plus_delta, double* delta);\n\n  bool Minus(const double *x, const double *x_plus_delta,\n             double *delta) const final {\n    return minus(x, x_plus_delta, delta);\n  }\n\n  /// \\brief Computes the Jacobian from minimal space to naively overparameterised space as used by ceres.\n  /// @param[in] x Variable.\n  /// @param[out] jacobian the Jacobian (dimension minDim x dim).\n  /// \\return True on success.\n  static bool liftJacobian(const double* /*x*/, double* jacobian) {\n    Eigen::Map<Eigen::Matrix<double, kLocalDim, kGlobalDim, Eigen::RowMajor>> j(jacobian);\n    j.setIdentity();\n    return true;\n  }\n\n  /// \\brief Computes the Jacobian from minimal space to naively\n  /// overparameterised space as used by ceres.\n  /// @param[in] x Variable.\n  /// @param[out] jacobian the Jacobian (dimension minDim x dim).\n  /// \\return True on success.\n  bool ComputeLiftJacobian(const double *x, double *jacobian) const final {\n    return liftJacobian(x, jacobian);\n  }\n};\n\nstd::shared_ptr<okvis::ceres::LocalParamizationAdditionalInterfaces> createLandmarkLocalParameterization(int modelId);\n} // namespace swift_vio\n\n#endif // INCLUDE_SWIFT_VIO_POINT_LANDMARK_MODELS_HPP_\n", "meta": {"hexsha": "f396e970424197771d8011b36055cb9eed2468a4", "size": 5822, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "okvis_ceres/include/swift_vio/PointLandmarkModels.hpp", "max_stars_repo_name": "JzHuai0108/okvis", "max_stars_repo_head_hexsha": "d0cc5b93115d980365a6f826e6dc4bfba97f2d75", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-26T15:31:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T15:31:53.000Z", "max_issues_repo_path": "okvis_ceres/include/swift_vio/PointLandmarkModels.hpp", "max_issues_repo_name": "JzHuai0108/okvis", "max_issues_repo_head_hexsha": "d0cc5b93115d980365a6f826e6dc4bfba97f2d75", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "okvis_ceres/include/swift_vio/PointLandmarkModels.hpp", "max_forks_repo_name": "JzHuai0108/okvis", "max_forks_repo_head_hexsha": "d0cc5b93115d980365a6f826e6dc4bfba97f2d75", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-08-01T16:49:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-14T09:00:03.000Z", "avg_line_length": 33.2685714286, "max_line_length": 118, "alphanum_fraction": 0.6734799038, "num_tokens": 1686, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746404, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.46330181806109016}}
{"text": "#pragma once\n#include <boost/variant.hpp>\n#include <vector>\n#include \"export.hpp\"\n\nnamespace ear {\n\n  struct EAR_EXPORT CartesianPosition {\n    CartesianPosition(double X = 0.0, double Y = 0.0, double Z = 0.0)\n        : X(X), Y(Y), Z(Z){};\n    double X;\n    double Y;\n    double Z;\n  };\n\n  struct EAR_EXPORT PolarPosition {\n    PolarPosition(double azimuth = 0.0, double elevation = 0.0,\n                  double distance = 1.0)\n        : azimuth(azimuth), elevation(elevation), distance(distance){};\n    double azimuth;\n    double elevation;\n    double distance;\n  };\n\n  using Position = boost::variant<CartesianPosition, PolarPosition>;\n\n}  // namespace ear\n", "meta": {"hexsha": "fc24c0beabeeb3b5a28c6ec5d6405858fbc0d921", "size": 660, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ear/common_types.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": "include/ear/common_types.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": "include/ear/common_types.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": 23.5714285714, "max_line_length": 71, "alphanum_fraction": 0.6424242424, "num_tokens": 167, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347362, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.46329455459490826}}
{"text": "#pragma once\n#include <memory>\n#include <vector>\n#include <boost/serialization/access.hpp>\n\nnamespace snn\n{\n    enum class activation\n    {\n        sigmoid = 0,\n        iSigmoid,\n        tanh,\n        ReLU,\n        gaussian,\n        identity\n    };\n}\nnamespace snn::internal\n{\n    class ActivationFunction\n    {\n    private:\n\n        friend class boost::serialization::access;\n        template <class Archive>\n        void serialize(Archive& ar, unsigned version);\n\n    public:\n        static std::vector<std::shared_ptr<ActivationFunction>> activationFunctions;\n\n        const float min;\n        const float max;\n\n        ActivationFunction(float min, float max);\n        virtual ~ActivationFunction() = default;\n        static void initialize();\n        static std::shared_ptr<ActivationFunction> get(activation type);\n\n        [[nodiscard]] virtual float function(const float) const = 0;\n        [[nodiscard]] virtual float derivative(const float) const = 0;\n\n        [[nodiscard]] virtual activation getType() const = 0;\n\n        virtual bool operator==(const ActivationFunction& activationFunction) const;\n        virtual bool operator!=(const ActivationFunction& activationFunction) const;\n    };\n}\n", "meta": {"hexsha": "0fd617791f9bc1b57c0a60a8dd15f30189cc9ac6", "size": 1205, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/neural_network/layer/neuron/activation_function/ActivationFunction.hpp", "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/layer/neuron/activation_function/ActivationFunction.hpp", "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/layer/neuron/activation_function/ActivationFunction.hpp", "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": 25.1041666667, "max_line_length": 84, "alphanum_fraction": 0.6481327801, "num_tokens": 243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.46329455002305403}}
{"text": "#ifndef OSRM_UTIL_MSB_HPP\n#define OSRM_UTIL_MSB_HPP\n\n#include <boost/assert.hpp>\n\n#include <cstdint>\n#include <utility>\n\nnamespace osrm\n{\nnamespace util\n{\n\n// get the msb of an integer\n// return 0 for integers without msb\ntemplate <typename T> std::size_t msb(T value)\n{\n    static_assert(std::is_integral<T>::value && !std::is_signed<T>::value, \"Integer required.\");\n    std::size_t msb = 0;\n    while (value > 0)\n    {\n        value >>= 1u;\n        msb++;\n    }\n    BOOST_ASSERT(msb > 0);\n    return msb - 1;\n}\n\n#if (defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)) && __x86_64__\ninline std::size_t msb(std::uint64_t v)\n{\n    BOOST_ASSERT(v > 0);\n    return 63UL - __builtin_clzl(v);\n}\ninline std::size_t msb(std::uint32_t v)\n{\n    BOOST_ASSERT(v > 0);\n    return 31UL - __builtin_clz(v);\n}\n#endif\n}\n}\n\n#endif\n", "meta": {"hexsha": "457cb79da05b9a93e94f4ffa9576b7d77a2ee28d", "size": 825, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "code/deps/osrm/include/util/msb.hpp", "max_stars_repo_name": "mbeckem/msc", "max_stars_repo_head_hexsha": "93e71ba163a7ffef4eec3e83934fa793f3f50ff6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/deps/osrm/include/util/msb.hpp", "max_issues_repo_name": "mbeckem/msc", "max_issues_repo_head_hexsha": "93e71ba163a7ffef4eec3e83934fa793f3f50ff6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/deps/osrm/include/util/msb.hpp", "max_forks_repo_name": "mbeckem/msc", "max_forks_repo_head_hexsha": "93e71ba163a7ffef4eec3e83934fa793f3f50ff6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.3333333333, "max_line_length": 96, "alphanum_fraction": 0.6484848485, "num_tokens": 249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419704455589, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.4632945461073679}}
{"text": "/*\n * Copyright (C) 2019 by AutoSense Organization. All rights reserved.\n * Gary Chan <chenshj35@mail2.sysu.edu.cn>\n */\n\n#ifndef COMMON_INCLUDE_COMMON_COMMON_HPP_\n#define COMMON_INCLUDE_COMMON_COMMON_HPP_\n\n#include <pcl/common/centroid.h>    // pcl::compute3DCentroid\n#include <pcl/common/transforms.h>  // pcl::transformPointCloud\n#include <pcl/io/pcd_io.h>          // pcl::io::savePCDFileASCII\n#include <Eigen/Core>\n#include <cmath>  // sqrt, pow\n#include <string>\n#include <utility>\n#include <vector>\n\n#include \"common/types/type.h\"\n\nnamespace autosense {\nnamespace common {\n// float precision\nconst float EPSILON = 1e-9;\n\n//----------------------------------- sort compare function\ntemplate <typename PointType>\nbool sortByAxisXAsc(PointType p1, PointType p2) {\n    return p1.x < p2.x;\n}\n\ntemplate <typename PointType>\nbool sortByAxisZAsc(PointType p1, PointType p2) {\n    return p1.z < p2.z;\n}\n\ntemplate <typename ObjType>\nbool sortByObjSizeDesc(ObjType obj1, ObjType obj2) {\n    return obj1->cloud->size() > obj2->cloud->size();\n}\n\n/// \\brief Utility function for swapping two values.\ntemplate <typename T>\nbool swap_if_gt(T& a, T& b) {  // NOLINT\n    if (a > b) {\n        std::swap(a, b);\n        return true;\n    }\n    return false;\n}\n\n//----------------------------------- *.pcd\nstatic void savePCDModel(PointICloudConstPtr pc,\n                         const std::string& model_name) {\n    // std::string pcd_model_file = \"model.pcd\";\n    pcl::io::savePCDFileASCII(model_name, *pc);\n}\n\nstatic void loadPCDModel(PointICloudPtr pc, const std::string& model_name) {\n    pcl::io::loadPCDFile<PointI>(model_name, *pc);\n}\n\nstatic bool loadPCDModel(PointCloudPtr pc,\n                         Eigen::Affine3f& model2world) {  // NOLINT\n    std::string pcd_model_file =\n        \"/home/gary/Workspace/intern_ws/pcl_learning/model.pcd\";\n    if (pcl::io::loadPCDFile<Point>(pcd_model_file, *pc) == -1) {\n        return false;\n    } else {\n\n        model2world = Eigen::Affine3f::Identity();\n        Eigen::Vector4f model_centroid;\n        pcl::compute3DCentroid<Point>(*pc, model_centroid);\n        model2world.translation().matrix() = Eigen::Vector3f(\n            model_centroid[0], model_centroid[1], model_centroid[2]);\n        pcl::transformPointCloud(*pc, *pc, model2world.inverse());\n\n        return true;\n    }\n}\n\n/**\n * @brief convert PointI cloud in indices to PointD cloud\n * @param cloud\n * @param indices\n * @param trans_cloud\n */\nstatic void convertPointCloud(PointICloudPtr icloud,\n                              const std::vector<int>& indices,\n                              PointDCloud* dcloud) {\n    if (dcloud->size() != indices.size()) {\n        dcloud->resize(indices.size());\n    }\n    for (size_t i = 0u; i < indices.size(); ++i) {\n        const PointI& p = icloud->at(indices[i]);\n        Eigen::Vector3d v(p.x, p.y, p.z);\n        PointD& tp = dcloud->at(i);\n        tp.x = v.x();\n        tp.y = v.y();\n        tp.z = v.z();\n        tp.intensity = p.intensity;\n    }\n}\n\n//----------------------------------- math utils\nstatic float toRad(float degree) { return degree * (M_PI / 180.f); }\n\n}  // namespace common\n}  // namespace autosense\n\n#endif  // COMMON_INCLUDE_COMMON_COMMON_HPP_\n", "meta": {"hexsha": "967464ef6784ee7557d54a6d14c5c0e5d395cae7", "size": 3204, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "LetsGo/ThirdParty/ObjectBuilder/Includes/common/common.hpp", "max_stars_repo_name": "wis1906/letsgo-ar-space-generation", "max_stars_repo_head_hexsha": "02d888a44bb9eb112f308356ab42720529349338", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "LetsGo/ThirdParty/ObjectBuilder/Includes/common/common.hpp", "max_issues_repo_name": "wis1906/letsgo-ar-space-generation", "max_issues_repo_head_hexsha": "02d888a44bb9eb112f308356ab42720529349338", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LetsGo/ThirdParty/ObjectBuilder/Includes/common/common.hpp", "max_forks_repo_name": "wis1906/letsgo-ar-space-generation", "max_forks_repo_head_hexsha": "02d888a44bb9eb112f308356ab42720529349338", "max_forks_repo_licenses": ["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.8648648649, "max_line_length": 76, "alphanum_fraction": 0.6176654182, "num_tokens": 848, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419704455588, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.46329454610736787}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n// QuickBook Example\r\n\r\n// Copyright (c) 2011 Barend Gehrels, Amsterdam, the Netherlands.\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n//[assign_2d_point\r\n//` Shows the usage of assign to set point coordinates, and, besides that, shows how you can initialize ttmath points with high precision\r\n\r\n#include <iostream>\r\n#include <iomanip>\r\n\r\n#include <boost/geometry.hpp>\r\n#include <boost/geometry/geometries/point_xy.hpp>\r\n\r\n#if defined(HAVE_TTMATH)\r\n#  include <boost/geometry/extensions/contrib/ttmath_stub.hpp>\r\n#endif\r\n\r\n\r\nint main()\r\n{\r\n    using boost::geometry::assign_values;\r\n\r\n\r\n    boost::geometry::model::d2::point_xy<double> p1;\r\n    assign_values(p1, 1.2345, 2.3456);\r\n\r\n#if defined(HAVE_TTMATH)\r\n    boost::geometry::model::d2::point_xy<ttmath::Big<1,4> > p2;\r\n    assign_values(p2, \"1.2345\", \"2.3456\"); /*< It is possible to assign coordinates with other types than the coordinate type.\r\n        For ttmath, you can e.g. conveniently use strings. The advantage is that it then has higher precision, because\r\n        if doubles are used for assignments the double-precision is used.\r\n        >*/\r\n#endif\r\n\r\n    std::cout\r\n        << std::setprecision(20)\r\n        << boost::geometry::dsv(p1) << std::endl\r\n#if defined(HAVE_TTMATH)\r\n        << boost::geometry::dsv(p2) << std::endl\r\n#endif\r\n        ;\r\n\r\n    return 0;\r\n}\r\n\r\n//]\r\n\r\n\r\n//[assign_2d_point_output\r\n/*`\r\nOutput:\r\n[pre\r\n(1.2344999999999999, 2.3456000000000001)\r\n(1.2345, 2.3456)\r\n]\r\n*/\r\n//]\r\n", "meta": {"hexsha": "c9b88fe70f45e6dc9b57308f7b5af86e859cda19", "size": 1669, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/doc/src/examples/algorithms/assign_2d_point.cpp", "max_stars_repo_name": "Ron2014/boost_1_48_0", "max_stars_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "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/geometry/doc/src/examples/algorithms/assign_2d_point.cpp", "max_issues_repo_name": "Ron2014/boost_1_48_0", "max_issues_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "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/geometry/doc/src/examples/algorithms/assign_2d_point.cpp", "max_forks_repo_name": "Ron2014/boost_1_48_0", "max_forks_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "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.4920634921, "max_line_length": 138, "alphanum_fraction": 0.6722588376, "num_tokens": 452, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.46325148887353534}}
{"text": "/*\n correlation.hxx\n\n Copyright (c) 2018 Guy Skinner\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#pragma once\n\n#include <boost/numeric/ublas/vector.hpp>\n#include <vector>\n\n#include \"neighbour.hxx\"\n#include \"supercell.hxx\"\n\nnamespace ublas = boost::numeric::ublas;\n\nclass Correlation {\n\npublic:\n\n  Correlation();\n\n  void Calculate(const Neighbour& neighbour_table,\n                 Supercell& supercell);\n\n  double ErrorFunction(double x);\n\n  long number;\n  std::vector<double> pair_clusters;\n  std::vector<long> pair_count;\n  std::vector<double> pair_correlations;\n  ublas::vector<double> errors;\n\n};\n", "meta": {"hexsha": "a1d931898f201887453a581612891d9a7ad51b7f", "size": 749, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "src/correlation.hxx", "max_stars_repo_name": "gcgs1/cxx.sqs", "max_stars_repo_head_hexsha": "6b656a2f604385cb28ad4211c4d52ed992b459ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/correlation.hxx", "max_issues_repo_name": "gcgs1/cxx.sqs", "max_issues_repo_head_hexsha": "6b656a2f604385cb28ad4211c4d52ed992b459ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/correlation.hxx", "max_forks_repo_name": "gcgs1/cxx.sqs", "max_forks_repo_head_hexsha": "6b656a2f604385cb28ad4211c4d52ed992b459ee", "max_forks_repo_licenses": ["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.2051282051, "max_line_length": 67, "alphanum_fraction": 0.7276368491, "num_tokens": 173, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390746, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.46325148257369175}}
{"text": "//\n// Created by rgrandia on 14.02.20.\n//\n\n#include \"ocs2_core/loopshaping/LoopshapingPropertyTree.h\"\n\n#include <boost/property_tree/info_parser.hpp>\n\nnamespace ocs2 {\nnamespace loopshaping_property_tree {\nFilter readSISOFilter(const boost::property_tree::ptree& pt, std::string filterName, bool invert) {\n  // Get Sizes\n  auto numRepeats = pt.get<size_t>(filterName + \".numRepeats\");\n  auto numPoles = pt.get<size_t>(filterName + \".numPoles\");\n  auto numZeros = pt.get<size_t>(filterName + \".numZeros\");\n  auto DCGain = pt.get<scalar_t>(filterName + \".DCGain\");\n  size_t numStates = numRepeats * numPoles;\n  size_t numInputs = numRepeats;\n  size_t numOutputs = numRepeats;\n\n  // Setup Filter, convention a0*s^n + a1*s^(n-1) + ... + an\n  vector_t numerator(numZeros + 1);\n  numerator.setZero();\n  numerator(0) = 1.0;\n  for (size_t z = 0; z < numZeros; z++) {\n    auto zero = pt.get<scalar_t>(filterName + \".zeros.\" + \"(\" + std::to_string(z) + \")\");\n    numerator.segment(1, z + 1) -= zero * numerator.segment(0, z + 1).eval();\n  }\n\n  vector_t denominator(numPoles + 1);\n  denominator.setZero();\n  denominator(0) = 1.0;\n  for (size_t p = 0; p < numPoles; p++) {\n    auto pole = pt.get<scalar_t>(filterName + \".poles.\" + \"(\" + std::to_string(p) + \")\");\n    denominator.segment(1, p + 1) -= pole * denominator.segment(0, p + 1).eval();\n  }\n\n  // Scale\n  if (DCGain > 0) {\n    scalar_t currentDCGain = numerator(numZeros) / denominator(numPoles);\n    if (currentDCGain < 1e-6 || currentDCGain > 1e6) {\n      throw std::runtime_error(\"Trouble rescaling transfer function, current DCGain: \" + std::to_string(currentDCGain));\n    }\n    scalar_t scaling = DCGain / currentDCGain;\n    numerator *= scaling;\n  }\n\n  if (invert) {\n    vector_t temp;\n    temp = numerator;\n    numerator = denominator;\n    denominator = temp;\n  }\n\n  // Convert to state space\n  matrix_t a, b, c, d;\n  ocs2::tf2ss(numerator, denominator, a, b, c, d);\n\n  matrix_t A = matrix_t::Zero(numStates, numStates);\n  matrix_t B = matrix_t::Zero(numStates, numInputs);\n  matrix_t C = matrix_t::Zero(numInputs, numStates);\n  matrix_t D = matrix_t::Zero(numInputs, numInputs);\n  size_t statecount = 0;\n  for (size_t r = 0; r < numRepeats; r++) {\n    A.block(statecount, statecount, numPoles, numPoles) = a;\n    B.block(statecount, r, numPoles, 1) = b;\n    C.block(r, statecount, 1, numPoles) = c;\n    D.block(r, r, 1, 1) = d;\n    statecount += numPoles;\n  }\n\n  return Filter(A, B, C, D);\n}\n\nFilter readMIMOFilter(const boost::property_tree::ptree& pt, std::string filterName, bool invert) {\n  auto numFilters = pt.get<size_t>(filterName + \".numFilters\");\n  matrix_t A(0, 0), B(0, 0), C(0, 0), D(0, 0);\n  if (numFilters > 0) {\n    // Read the sisoFilters\n    std::vector<Filter> sisoFilters;\n    size_t numStates(0), numInputs(0), numOutputs(0);\n    for (size_t i = 0; i < numFilters; ++i) {\n      // Read filter\n      std::string sisoFilterName = filterName + \".Filter\" + std::to_string(i);\n      sisoFilters.emplace_back(readSISOFilter(pt, sisoFilterName, invert));\n\n      // Track sizes\n      numStates += sisoFilters.back().getNumStates();\n      numInputs += sisoFilters.back().getNumInputs();\n      numOutputs += sisoFilters.back().getNumOutputs();\n    }\n\n    // Concatenate siso matrices into one MIMO filter\n    A = matrix_t::Zero(numStates, numStates);\n    B = matrix_t::Zero(numStates, numInputs);\n    C = matrix_t::Zero(numOutputs, numStates);\n    D = matrix_t::Zero(numOutputs, numInputs);\n    size_t statecount(0), inputcount(0), outputcount(0);\n    for (const auto& filt : sisoFilters) {\n      A.block(statecount, statecount, filt.getNumStates(), filt.getNumStates()) = filt.getA();\n      B.block(statecount, inputcount, filt.getNumStates(), filt.getNumInputs()) = filt.getB();\n      C.block(outputcount, statecount, filt.getNumOutputs(), filt.getNumStates()) = filt.getC();\n      D.block(outputcount, inputcount, filt.getNumOutputs(), filt.getNumInputs()) = filt.getD();\n      statecount += filt.getNumStates();\n      inputcount += filt.getNumInputs();\n      outputcount += filt.getNumOutputs();\n    }\n  }\n  return Filter(A, B, C, D);\n}\n\nstd::shared_ptr<LoopshapingDefinition> load(const std::string& settingsFile) {\n  // Read from settings File\n  boost::property_tree::ptree pt;\n  boost::property_tree::read_info(settingsFile, pt);\n  Filter r_filter = loopshaping_property_tree::readMIMOFilter(pt, \"r_filter\");\n  Filter s_filter = loopshaping_property_tree::readMIMOFilter(pt, \"s_inv_filter\", /*invert=*/true);\n  auto gamma = pt.get<scalar_t>(\"gamma\");\n\n  if (r_filter.getNumOutputs() > 0 && s_filter.getNumOutputs() > 0) {\n    throw std::runtime_error(\"[LoopshapingDefinition] using both r and s filter not implemented\");\n  }\n\n  if (r_filter.getNumOutputs() > 0) {\n    return std::make_shared<LoopshapingDefinition>(LoopshapingType::outputpattern, r_filter, gamma);\n  }\n  if (s_filter.getNumOutputs() > 0) {\n    auto eliminateInputs = pt.get<bool>(\"eliminateInputs\");\n    if (eliminateInputs) {\n      return std::make_shared<LoopshapingDefinition>(LoopshapingType::eliminatepattern, s_filter, gamma);\n    } else {\n      return std::make_shared<LoopshapingDefinition>(LoopshapingType::inputpattern, s_filter, gamma);\n    }\n  }\n\n  throw std::runtime_error(\"[LoopshapingDefinition] error loading loopshaping definition, no valid filter found\");\n}\n\n}  // namespace loopshaping_property_tree\n}  // namespace ocs2\n", "meta": {"hexsha": "504c4031f0f63bbdf1ea9c7a4694cbf7bb4ecd88", "size": 5379, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ocs2_core/src/loopshaping/LoopshapingPropertyTree.cpp", "max_stars_repo_name": "grizzi/ocs2", "max_stars_repo_head_hexsha": "4b78c4825deb8b2efc992fdbeef6fdb1fcca2345", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 126.0, "max_stars_repo_stars_event_min_datetime": "2021-07-13T13:59:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T02:52:18.000Z", "max_issues_repo_path": "ocs2_core/src/loopshaping/LoopshapingPropertyTree.cpp", "max_issues_repo_name": "grizzi/ocs2", "max_issues_repo_head_hexsha": "4b78c4825deb8b2efc992fdbeef6fdb1fcca2345", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2021-07-14T12:14:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T16:27:52.000Z", "max_forks_repo_path": "ocs2_core/src/loopshaping/LoopshapingPropertyTree.cpp", "max_forks_repo_name": "grizzi/ocs2", "max_forks_repo_head_hexsha": "4b78c4825deb8b2efc992fdbeef6fdb1fcca2345", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 55.0, "max_forks_repo_forks_event_min_datetime": "2021-07-14T07:08:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:54:30.000Z", "avg_line_length": 38.1489361702, "max_line_length": 120, "alphanum_fraction": 0.6757761666, "num_tokens": 1559, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426303, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.46325147627384805}}
{"text": "//\n// HOGpp - Fast histogram of oriented gradients computation using integral\n// histograms\n//\n// Copyright 2021 Sergiu Deitsch <sergiu.deitsch@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#define BOOST_TEST_MODULE hogpp\n\n#include <cmath>\n\n#include <hogpp/signedgradient.hpp>\n#include <hogpp/unsignedgradient.hpp>\n\n#include <boost/mpl/list.hpp>\n#include <boost/test/included/unit_test.hpp>\n\nusing Scalars = boost::mpl::list<float, double, long double>;\n\n// clang-format off\nBOOST_TEST_DECORATOR\n(\n    *boost::unit_test::tolerance(5.96048e-08f)\n    *boost::unit_test::tolerance(3.90314e-17l)\n)\n// clang-format on\nBOOST_AUTO_TEST_CASE_TEMPLATE(signed_gradient, Scalar, Scalars)\n{\n    using std::fpclassify;\n    using std::nextafter;\n\n    hogpp::SignedGradient<Scalar> binning;\n\n    BOOST_TEST(fpclassify(binning(+1, 0)) == FP_ZERO);\n    BOOST_TEST(binning(-1, 0) == Scalar(0.5));\n    BOOST_TEST(fpclassify(binning(0, 0)) == FP_ZERO);\n    BOOST_TEST(binning(+1, nextafter(Scalar{0}, Scalar{-1})) == Scalar{1});\n    BOOST_TEST(binning(-1, nextafter(Scalar{0}, Scalar{+1})) == Scalar(0.5));\n}\n\n// clang-format off\nBOOST_TEST_DECORATOR\n(\n    *boost::unit_test::tolerance(5.96048e-08f)\n    *boost::unit_test::tolerance(3.90314e-17l)\n)\n// clang-format on\nBOOST_AUTO_TEST_CASE_TEMPLATE(unsigned_gradient, Scalar, Scalars)\n{\n    using std::fpclassify;\n    using std::nextafter;\n\n    hogpp::UnsignedGradient<Scalar> binning;\n\n    BOOST_TEST(fpclassify(binning(+1, 0)) == FP_ZERO);\n    BOOST_TEST(fpclassify(binning(-1, 0)) == FP_ZERO);\n    BOOST_TEST(binning(0, +1) == Scalar(0.5));\n    BOOST_TEST(binning(0, -1) == Scalar(0.5));\n    BOOST_TEST(fpclassify(binning(0, 0)) == FP_ZERO);\n    BOOST_TEST(binning(+1, nextafter(Scalar{0}, Scalar{-1})) == Scalar{1});\n    BOOST_TEST(binning(-1, nextafter(Scalar{0}, Scalar{+1})) == Scalar{1});\n}\n", "meta": {"hexsha": "78152db8d349c8293a16925ebc57d4d18b1b9012", "size": 2353, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/cpp/test_binning.cpp", "max_stars_repo_name": "sergiud/hogpp", "max_stars_repo_head_hexsha": "989853500d8caa2c663ea075bbb3c7d23e79c7dc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-12-13T14:22:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-13T16:51:26.000Z", "max_issues_repo_path": "tests/cpp/test_binning.cpp", "max_issues_repo_name": "sergiud/hogpp", "max_issues_repo_head_hexsha": "989853500d8caa2c663ea075bbb3c7d23e79c7dc", "max_issues_repo_licenses": ["Apache-2.0"], "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/cpp/test_binning.cpp", "max_forks_repo_name": "sergiud/hogpp", "max_forks_repo_head_hexsha": "989853500d8caa2c663ea075bbb3c7d23e79c7dc", "max_forks_repo_licenses": ["Apache-2.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.3733333333, "max_line_length": 77, "alphanum_fraction": 0.7093072673, "num_tokens": 656, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.463251476273848}}
{"text": "#define NDEBUG\n#include \"hlpc_ls.h\"\n#include \"invert_matrix.hpp\"\n//#include \"invert_matrix_gj.hpp\"\n#include \"stopwatch.hpp\"\n#include <cmath>\n#include <limits>\n#include <fstream>\n\n#include <boost/numeric/ublas/banded.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n\n#if HLPC_DO_TIMING == 1\n#define TIME_THIS(x, y) cxxutil::stopwatch x(y)\n#else\n#define TIME_THIS(x, y)\n#endif\n\ntypedef ublas::matrix<double> dmatrix;\ntypedef ublas::vector<double> dvector;\n\nvoid toeplitz(const dvector& c, const dvector& r, dmatrix& result) {\n    TIME_THIS(watch, \"toeplitz\");\n    result.resize(c.size(), r.size(), false);\n\n    for (int i = 0; i < result.size1(); i++) {\n\tfor (int j = 0; j < result.size2(); j++) {\n\t    if (j <= i) {\n\t\tresult(i, j) = c(i-j);\n\t    } else {\n\t\tresult(i, j) = r(j-i);\n\t    }\n\t}\n    }\n}\n\nvoid geninv(const dmatrix& mat, dmatrix& inverse) {\n    TIME_THIS(watch, \"geninv\");\n    int m = mat.size1();\n    int n = mat.size2();\n    dmatrix A;\n    bool transpose = false;\n    {\n\tTIME_THIS(getA, \"get A\");\n\tif (m < n) {\n\t    transpose = true;\n\t    A = prod(mat, ublas::trans(mat));\n\t    n = m;\n\t} else {\n\t    A = prod(ublas::trans(mat), mat);\n\t}\n    }\n\n    typedef ublas::banded_matrix<double> diag_matrix;\n    diag_matrix dA(A.size1(), A.size2(), 0, 0);\n    ublas::matrix_vector_slice<dmatrix> A_diag(A, ublas::slice(0, 1, A.size1()), ublas::slice(0, 1, A.size2()));\n    { TIME_THIS(getdA, \"get dA\");\n\tfor (int i = 0; i < dA.size1(); i++) {\n\t    if (i < dA.size2()) {\n\t\tdA(i, i) = A_diag(i);\n\t    }\n\t}\n    }\n    double minimum = std::numeric_limits<double>::max();\n    {\n\tTIME_THIS(getMin,\"get minimum\");\n\tfor (int i = 0; i < dA.size1(); i++) {\n\t    if (i < dA.size2()) {\n\t\tif (dA(i, i) > 0.) {\n\t\t    if (minimum > dA(i, i)) {\n\t\t\tminimum = dA(i, i);\n\t\t    }\n\t\t}\n\t    }\n\t}\n    }\n    double tol = minimum * 1e-9;\n    dmatrix L(A.size1(), A.size2());\n    {\n\tTIME_THIS(getL, \"get L\");\n\tfor (int i = 0; i < L.size1(); i++) {\n\t    for (int j = 0; j < L.size2(); j++) {\n\t\tL(i, j) = 0.;\n\t    }\n\t}\n    }\n    int r = 0;\n\n    {\n\tTIME_THIS(chol, \"cholesky_decomposition\");\n\tfor (int k = 0; k < n; k++) {\n\t    r++;\n\t    ublas::vector<double> nullvec(n-k);\n\t    if (r > 1) {\n\t\tublas::project(L, ublas::range(k, n), ublas::range(r-1, r))\n\t\t    = ublas::project(A, ublas::range(k, n), ublas::range(k, k+1))\n\t\t    - ublas::prod(\n\t\t\t    ublas::project(L, ublas::range(k, n), ublas::range(0, r)),\n\t\t\t    ublas::trans(ublas::project(L, ublas::range(k, k+1), ublas::range(0, r)))\n\t\t\t    );\n\t\tdmatrix projection(ublas::prod(ublas::project(L, ublas::range(k, n), ublas::range(0, 3)), \n\t\t\t    ublas::trans(ublas::project(L, ublas::range(k, k+1), ublas::range(0, 3)))));\n\t    } else {\n\t\tublas::project(L, ublas::range(k, n), ublas::range(r-1, r))\n\t\t    = ublas::project(A, ublas::range(k, n), ublas::range(k, k+1));\n\t\tdmatrix projection(ublas::project(A, ublas::range(k, n), ublas::range(k, k+1)));\n\t    }\n\t    if (L(k, r-1) > tol) {\n\t\tL(k, r-1) = std::sqrt(L(k, r-1));\n\t\tif (k < n-1) {\n\t\t    ublas::project(L, ublas::range(k+1, n), ublas::range(r-1, r))\n\t\t\t= ublas::project(L, ublas::range(k+1, n), ublas::range(r-1, r)) / L(k, r-1);\n\t\t}\n\t    } else {\n\t\tr--;\n\t    }\n\t}\n    }\n    { TIME_THIS(projecting, \"projecting L\");\n\tL = project(L, ublas::range(0, L.size1()), ublas::range(0, r));\n    }\n    dmatrix p(ublas::prod(ublas::trans(L), L));\n    dmatrix M(p.size1(), p.size2());\n    {\n\tTIME_THIS(inverting, \"inverting matrix\");\n\tinvert_matrix(p, M);\n    }\n//    {\n//\tTIME_THIS(inverting, \"inverting matrix via gauss-jordan\");\n//\tbool b = invert_matrix_gj(p, M);\n//\tif (!b) {\n//\t    std::cerr << \"matrix inversion via gj failed.\" << std::endl;\n//\t}\n//    }\n\n    {\n\tTIME_THIS(matmult, \"final multiplications\");\n\tif (transpose) {\n\t    inverse = ublas::prod(ublas::trans(mat), L);\n\t    inverse = ublas::prod(inverse, M);\n\t    inverse = ublas::prod(inverse, M);\n\t    inverse = ublas::prod(inverse, ublas::trans(L));\n\t} else {\n\t    inverse = ublas::prod(L, M);\n\t    inverse = ublas::prod(inverse, M);\n\t    inverse = ublas::prod(inverse, ublas::trans(L));\n\t    inverse = ublas::prod(inverse, ublas::trans(mat));\n\t}\n    }\n}\n\nvoid hlpc_ls(double* y, int len, int order, int compr, float* poles)\n{\n    TIME_THIS(hlpc_watch, \"hlpc_ls\");\n    int col_length = len - order;\n    int row_length = order;\n\n    dvector column(col_length);\n    dvector row(row_length);\n    dvector a_multiplier(col_length);\n\n    for (int i = 0; i < col_length; i++) {\n\tcolumn(i) = y[order - 1 + i];\n\ta_multiplier(i) = y[order + i];\n    }\n    for (int i = 0; i < row_length; i++) {\n\trow(i) = y[order - 1 - i];\n    }\n\n    dmatrix R;\n    toeplitz(column, row, R);\n    dmatrix inv;\n    geninv(R, inv);\n    TIME_THIS(watch, \"hlpc_finalize\");\n    dvector tmp_a = prod(inv, a_multiplier);\n    double err = ublas::norm_2(a_multiplier - prod(R, tmp_a));\n    if (isnan(err)) {\n\tstd::cerr << \"err is nan!\" << std::endl;\n\tstd::ofstream out(\"broken_inv.txt\", std::ios::out);\n\tout << inv << std::endl;\n\tout.close();\n\tout.open(\"broken_R.txt\", std::ios::out);\n\tout << R << std::endl;\n\tout.close();\n\tout.open(\"broken_column.txt\", std::ios::out);\n\tout << column << std::endl;\n\tout.close();\n\tout.open(\"broken_row.txt\", std::ios::out);\n\tout << row << std::endl;\n\tout.close();\n\tout.open(\"broken_y.txt\", std::ios::out);\n\tfor (int k = 0; k < len; k++) {\n\t    out << y[k] << std::endl;\n\t}\n\tout.close();\n\tstd::cerr << \"y_len=\" << len << \", order=\" << order << std::endl;\n\tstd::exit(1);\n    }\n    dvector a(1 + tmp_a.size());\n    a(0) = 1.;\n    for (int i = 1; i < a.size(); i++) {\n\ta(i) = -tmp_a(i-1);\n    }\n    a = a / sqrt(err);\n\n    // copy over to output\n    for (int i = 0; i < a.size(); i++) {\n\tpoles[i] = a(i);\n\tif (isnan(poles[i])) {\n\t    std::cerr << \"poles[\" << i << \"] is nan!\" << std::endl;\n\t    std::ofstream out(\"broken_inv.txt\", std::ios::out);\n\t    out << inv << std::endl;\n\t    out.close();\n\t    out.open(\"broken_R.txt\", std::ios::out);\n\t    out << R << std::endl;\n\t    out.close();\n\t    out.open(\"broken_column.txt\", std::ios::out);\n\t    out << column << std::endl;\n\t    out.close();\n\t    out.open(\"broken_row.txt\", std::ios::out);\n\t    out << row << std::endl;\n\t    out.close();\n\t    out.open(\"broken_y.txt\", std::ios::out);\n\t    for (int k = 0; k < len; k++) {\n\t\tout << y[k] << std::endl;\n\t    }\n\t    out.close();\n\t    out.open(\"broken_a.txt\", std::ios::out);\n\t    out << a << std::endl;\n\t    out.close();\n\t    out.open(\"broken_tmp_a.txt\", std::ios::out);\n\t    out << tmp_a << std::endl;\n\t    out.close();\n\t    std::cerr << \"y_len=\" << len << \", order=\" << order << \", err=\" << err << std::endl;\n\t    std::exit(1);\n\t}\n    }\n}\n", "meta": {"hexsha": "9e546e0b093cfd18e0e25e923f0c83a82972e212", "size": 6565, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "hlpc_ls.cpp", "max_stars_repo_name": "tjanu/cfdlp", "max_stars_repo_head_hexsha": "8c9ba7738f0b1dd41142d084352e74202777fe16", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-08T16:05:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-08T16:05:42.000Z", "max_issues_repo_path": "hlpc_ls.cpp", "max_issues_repo_name": "tjanu/cfdlp", "max_issues_repo_head_hexsha": "8c9ba7738f0b1dd41142d084352e74202777fe16", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hlpc_ls.cpp", "max_forks_repo_name": "tjanu/cfdlp", "max_forks_repo_head_hexsha": "8c9ba7738f0b1dd41142d084352e74202777fe16", "max_forks_repo_licenses": ["BSD-3-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.4686192469, "max_line_length": 112, "alphanum_fraction": 0.5479055598, "num_tokens": 2206, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.463251476273848}}
{"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 \"FockDiis.h\"\n#include <Eigen/QR>\n#include <algorithm>\n\nnamespace Scine {\nnamespace Utils {\n\nFockDiis::FockDiis() {\n  setSubspaceSize(5);\n}\n\nvoid FockDiis::setUnrestricted(bool b) {\n  unrestricted_ = b;\n  diisError_.setUnrestricted(b);\n  restart();\n}\n\nvoid FockDiis::setSubspaceSize(int n) {\n  bool resizeNeeded = n != subspaceSize_;\n\n  subspaceSize_ = n;\n\n  if (resizeNeeded) {\n    resizeMembers();\n  }\n}\n\nvoid FockDiis::setNAOs(int n) {\n  bool resizeNeeded = n != nAOs_;\n\n  nAOs_ = n;\n\n  if (resizeNeeded) {\n    resizeMembers();\n  }\n}\n\nvoid FockDiis::resizeMembers() {\n  fockMatrices.resize(subspaceSize_);\n  diisError_.resize(subspaceSize_);\n  diisStepErrors_.resize(subspaceSize_);\n\n  overlap = Eigen::MatrixXd::Zero(nAOs_, nAOs_);\n\n  B = Eigen::MatrixXd::Ones(subspaceSize_ + 1, subspaceSize_ + 1) * (-1);\n  B(0, 0) = 0;\n\n  rhs = Eigen::VectorXd::Zero(subspaceSize_ + 1);\n  rhs(0) = -1;\n\n  restart();\n}\n\nvoid FockDiis::setOverlapMatrix(const Eigen::MatrixXd& S) {\n  overlap = S.selfadjointView<Eigen::Lower>();\n  restart();\n}\n\nvoid FockDiis::restart() {\n  C = Eigen::VectorXd::Zero(subspaceSize_ + 1);\n  iterationNo_ = 0;\n  index_ = 0;\n}\n\nvoid FockDiis::addMatrices(const SpinAdaptedMatrix& F, const DensityMatrix& P) {\n  iterationNo_++;\n  lastAdded_ = index_;\n\n  fockMatrices[index_] = F;\n\n  diisError_.setErrorFromMatrices(index_, F, P, overlap);\n  diisStepErrors_[index_] = std::sqrt(diisError_.getError(index_, index_)) / nAOs_;\n\n  updateBMatrix();\n\n  index_ = (index_ + 1) % subspaceSize_;\n}\n\nvoid FockDiis::updateBMatrix() {\n  int activeSize = iterationNo_ > subspaceSize_ ? subspaceSize_ : iterationNo_;\n\n  // Bii element\n  B(lastAdded_ + 1, lastAdded_ + 1) = diisError_.getError(lastAdded_, lastAdded_);\n\n  // Bij elements\n  for (int i = 1; i < activeSize + 1; i++) {\n    if (i == lastAdded_ + 1) {\n      continue;\n    }\n    B(lastAdded_ + 1, i) = diisError_.getError(lastAdded_, i - 1);\n    B(i, lastAdded_ + 1) = B(lastAdded_ + 1, i);\n  }\n}\n\nSpinAdaptedMatrix FockDiis::getMixedFockMatrix() {\n  if (iterationNo_ > subspaceSize_) {\n    iterationNo_ = subspaceSize_;\n  }\n\n  // If we have only one Fock matrix\n  if (iterationNo_ < 2) {\n    return fockMatrices[0];\n  }\n\n  C.head(iterationNo_ + 1) =\n      B.block(0, 0, iterationNo_ + 1, iterationNo_ + 1).colPivHouseholderQr().solve(rhs.head(iterationNo_ + 1));\n\n  return calculateLinearCombination();\n}\n\nSpinAdaptedMatrix FockDiis::calculateLinearCombination() {\n  if (unrestricted_) {\n    Eigen::MatrixXd FAlpha = Eigen::MatrixXd::Zero(nAOs_, nAOs_);\n    Eigen::MatrixXd FBeta = Eigen::MatrixXd::Zero(nAOs_, nAOs_);\n    for (int i = 0; i < iterationNo_; i++) {\n      FAlpha += C(i + 1) * fockMatrices[i].alphaMatrix();\n      FBeta += C(i + 1) * fockMatrices[i].betaMatrix();\n    }\n    return SpinAdaptedMatrix::createUnrestricted(std::move(FAlpha), std::move(FBeta));\n  }\n  Eigen::MatrixXd Fsol = Eigen::MatrixXd::Zero(nAOs_, nAOs_);\n  for (int i = 0; i < iterationNo_; i++) {\n    Fsol += C(i + 1) * fockMatrices[i].restrictedMatrix();\n  }\n  return SpinAdaptedMatrix::createRestricted(std::move(Fsol));\n}\n\ndouble FockDiis::getMaxError() const {\n  int activeSize = iterationNo_ > subspaceSize_ ? subspaceSize_ : iterationNo_;\n  auto maxIter = std::max_element(diisStepErrors_.begin(), diisStepErrors_.begin() + activeSize);\n  return *maxIter;\n}\n\ndouble FockDiis::getMinError() const {\n  int activeSize = iterationNo_ > subspaceSize_ ? subspaceSize_ : iterationNo_;\n  auto minIter = std::min_element(diisStepErrors_.begin(), diisStepErrors_.begin() + activeSize);\n  return *minIter;\n}\n\ndouble FockDiis::getLastError() const {\n  return diisStepErrors_[lastAdded_];\n}\n} // namespace Utils\n} // namespace Scine\n", "meta": {"hexsha": "d1823344b08f13f2b67e9491eb974f68281400d5", "size": 3894, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Utils/Utils/Scf/ConvergenceAccelerators/FockDiis.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/Scf/ConvergenceAccelerators/FockDiis.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/Scf/ConvergenceAccelerators/FockDiis.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": 25.6184210526, "max_line_length": 112, "alphanum_fraction": 0.6800205444, "num_tokens": 1223, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961425, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.4632509498271384}}
{"text": "// Boost.Geometry\n\n// Copyright (c) 2015 Oracle and/or its affiliates.\n\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_GEOMETRY_ALGORITHMS_DETAIL_ANDOYER_INVERSE_HPP\n#define BOOST_GEOMETRY_ALGORITHMS_DETAIL_ANDOYER_INVERSE_HPP\n\n\n#include <boost/math/constants/constants.hpp>\n\n#include <boost/geometry/core/radius.hpp>\n#include <boost/geometry/core/srs.hpp>\n\n#include <boost/geometry/util/condition.hpp>\n#include <boost/geometry/util/math.hpp>\n\n#include <boost/geometry/algorithms/detail/flattening.hpp>\n#include <boost/geometry/algorithms/detail/result_inverse.hpp>\n\n\nnamespace boost { namespace geometry { namespace detail\n{\n\n/*!\n\\brief The solution of the inverse problem of geodesics on latlong coordinates,\n       Forsyth-Andoyer-Lambert type approximation with first order terms.\n\\author See\n    - Technical Report: PAUL D. THOMAS, MATHEMATICAL MODELS FOR NAVIGATION SYSTEMS, 1965\n      http://www.dtic.mil/docs/citations/AD0627893\n    - Technical Report: PAUL D. THOMAS, SPHEROIDAL GEODESICS, REFERENCE SYSTEMS, AND LOCAL GEOMETRY, 1970\n      http://www.dtic.mil/docs/citations/AD703541\n*/\n\ntemplate <typename CT, bool EnableDistance, bool EnableAzimuth>\nstruct andoyer_inverse\n{\n    typedef result_inverse<CT> result_type;\n\n    template <typename T1, typename T2, typename Spheroid>\n    static inline result_type apply(T1 const& lon1,\n                                    T1 const& lat1,\n                                    T2 const& lon2,\n                                    T2 const& lat2,\n                                    Spheroid const& spheroid)\n    {\n        result_type result;\n\n        // coordinates in radians\n\n        if ( math::equals(lon1, lon2)\n          && math::equals(lat1, lat2) )\n        {\n            result.set(CT(0), CT(0));\n            return result;\n        }\n\n        CT const pi_half = math::pi<CT>() / CT(2);\n\n        if ( math::equals(math::abs(lat1), pi_half)\n          && math::equals(math::abs(lat2), pi_half) )\n        {\n            result.set(CT(0), CT(0));\n            return result;\n        }\n\n        CT const dlon = lon2 - lon1;\n        CT const sin_dlon = sin(dlon);\n        CT const cos_dlon = cos(dlon);\n        CT const sin_lat1 = sin(lat1);\n        CT const cos_lat1 = cos(lat1);\n        CT const sin_lat2 = sin(lat2);\n        CT const cos_lat2 = cos(lat2);\n\n        // H,G,T = infinity if cos_d = 1 or cos_d = -1\n        // lat1 == +-90 && lat2 == +-90\n        // lat1 == lat2 && lon1 == lon2\n        CT const cos_d = sin_lat1*sin_lat2 + cos_lat1*cos_lat2*cos_dlon;\n        CT const d = acos(cos_d);\n        CT const sin_d = sin(d);\n\n        // just in case since above lat1 and lat2 is checked\n        // the check below is equal to cos_d == 1 || cos_d == -1 || d == 0\n        if ( math::equals(sin_d, CT(0)) )\n        {\n            result.set(CT(0), CT(0));\n            return result;\n        }\n\n        // if the function returned before this place\n        // and endpoints were on the poles +-90 deg\n        // in this case the azimuth could either be 0 or +-pi\n\n        CT const f = detail::flattening<CT>(spheroid);\n\n        if ( BOOST_GEOMETRY_CONDITION(EnableDistance) )\n        {\n            CT const K = math::sqr(sin_lat1-sin_lat2);\n            CT const L = math::sqr(sin_lat1+sin_lat2);\n            CT const three_sin_d = CT(3) * sin_d;\n            // H or G = infinity if cos_d = 1 or cos_d = -1\n            CT const H = (d+three_sin_d)/(CT(1)-cos_d);\n            CT const G = (d-three_sin_d)/(CT(1)+cos_d);\n\n            // for e.g. lat1=-90 && lat2=90 here we have G*L=INF*0\n            CT const dd = -(f/CT(4))*(H*K+G*L);\n\n            CT const a = get_radius<0>(spheroid);\n\n            result.distance = a * (d + dd);\n        }\n        else\n        {\n            result.distance = CT(0);\n        }\n\n        if ( BOOST_GEOMETRY_CONDITION(EnableAzimuth) )\n        {\n            CT A = CT(0);\n            CT U = CT(0);\n            if ( ! math::equals(cos_lat2, CT(0)) )\n            {\n                CT const tan_lat2 = sin_lat2/cos_lat2;\n                CT const M = cos_lat1*tan_lat2-sin_lat1*cos_dlon;\n                A = atan2(sin_dlon, M);\n                CT const sin_2A = sin(CT(2)*A);\n                U = (f/CT(2))*math::sqr(cos_lat1)*sin_2A;\n            }\n\n            CT V = CT(0);\n            if ( ! math::equals(cos_lat1, CT(0)) )\n            {\n                CT const tan_lat1 = sin_lat1/cos_lat1;\n                CT const N = cos_lat2*tan_lat1-sin_lat2*cos_dlon;\n                CT const B = atan2(sin_dlon, N);\n                CT const sin_2B = sin(CT(2)*B);\n                V = (f/CT(2))*math::sqr(cos_lat2)*sin_2B;\n            }\n\n            // infinity if sin_d = 0, so cos_d = 1 or cos_d = -1\n            CT const T = d / sin_d;\n            CT const dA = V*T-U;\n\n            result.azimuth = A - dA;\n        }\n        else\n        {\n            result.azimuth = CT(0);\n        }\n\n        return result;\n    }\n};\n\n}}} // namespace boost::geometry::detail\n\n\n#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_ANDOYER_INVERSE_HPP\n", "meta": {"hexsha": "eb8485b8e15763f23a3ad96d00e5ed606a1bdb5f", "size": 5230, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "clm/src/main/clm/jni/boost/armv7a/include/boost/geometry/algorithms/detail/andoyer_inverse.hpp", "max_stars_repo_name": "BruceNUAA/gaze-detection-android-app", "max_stars_repo_head_hexsha": "5daa2c8a0e51eb506fe435a6f8d03758162d0579", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1210.0, "max_stars_repo_stars_event_min_datetime": "2020-08-18T07:57:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:06:05.000Z", "max_issues_repo_path": "libs/boost/include/boost/geometry/algorithms/detail/andoyer_inverse.hpp", "max_issues_repo_name": "dnevera/ofxiOSBoost", "max_issues_repo_head_hexsha": "aae717bf8c5229f644057a17ccc971abf1c68bc3", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 37.0, "max_issues_repo_issues_event_min_datetime": "2020-08-24T02:48:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-30T06:41:52.000Z", "max_forks_repo_path": "libs/boost/include/boost/geometry/algorithms/detail/andoyer_inverse.hpp", "max_forks_repo_name": "dnevera/ofxiOSBoost", "max_forks_repo_head_hexsha": "aae717bf8c5229f644057a17ccc971abf1c68bc3", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 275.0, "max_forks_repo_forks_event_min_datetime": "2020-08-18T08:35:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:06:07.000Z", "avg_line_length": 31.8902439024, "max_line_length": 105, "alphanum_fraction": 0.561376673, "num_tokens": 1409, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835207180245, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.4632509361992978}}
{"text": "#include <boost/math/special_functions/digamma.hpp>\n", "meta": {"hexsha": "d632bd6380d7a3bc643bee41471d97cf5a392bd1", "size": 52, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_special_functions_digamma.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_special_functions_digamma.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_special_functions_digamma.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 26.0, "max_line_length": 51, "alphanum_fraction": 0.8269230769, "num_tokens": 12, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4632145911509705}}
{"text": "#ifndef HOMENCIPHER_HPP\n#define HOMENCIPHER_HPP\n\n#include <NTL/ZZ.h>\n#include \"Encipher.hpp\"\n#include \"Random.h\"\n\ntemplate <typename C, typename P>\nclass HOMEncipher : public Encipher<C,P>\n{\nprotected:\n\tNTL::ZZ modulus;\n\tNTL::ZZ p;\n\tNTL::ZZ q;\n\tRandom* rng;\n\n\tvoid generateModulus(int lambda, int eta){\n\t\tp = NTL::RandomPrime_ZZ(lambda,20);\n\t\tq = NTL::RandomPrime_ZZ(eta,20);\n\t\tmodulus = p*q;\n\t}\n\npublic:\n\tvoid init(){\n\t\tthis->rng = new Random();\n\t\tNTL::ZZ_p::init(modulus);\n\t};\n\tNTL::ZZ getModulus(){\n\t\treturn modulus;\n\t};\n\tvirtual std::string writeParametersToJSON()=0;\n\n\tHOMEncipher(){\n\t\trng=nullptr;\n\t};\n\tvirtual ~HOMEncipher(){\n\t\tdelete rng;\n\t};\n};\n\n#endif\n", "meta": {"hexsha": "03b1a464fbc1196595654c5a147cad93ac4e978d", "size": 662, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "examples/inner_product/innergen/src/HOMEncipher.hpp", "max_stars_repo_name": "TANGO-Project/cryptango", "max_stars_repo_head_hexsha": "be6a2d74d238bffd3f3e899ea0eea01966097ebe", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/inner_product/innergen/src/HOMEncipher.hpp", "max_issues_repo_name": "TANGO-Project/cryptango", "max_issues_repo_head_hexsha": "be6a2d74d238bffd3f3e899ea0eea01966097ebe", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/inner_product/innergen/src/HOMEncipher.hpp", "max_forks_repo_name": "TANGO-Project/cryptango", "max_forks_repo_head_hexsha": "be6a2d74d238bffd3f3e899ea0eea01966097ebe", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.7619047619, "max_line_length": 47, "alphanum_fraction": 0.6737160121, "num_tokens": 212, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4632145911509705}}
{"text": "#include <iostream>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n#include <boost/random.hpp>\n#include <ctime>\n#include <chrono>\n\n#include <kv/matrix-inversion.hpp>\n\nint main()\n{\n\tboost::numeric::ublas::matrix<double> a(2, 2);\n\tboost::numeric::ublas::matrix<double> b;\n\n\tstd::chrono::system_clock::time_point t;\n\n\ta(0, 0) = 1.; a(0, 1) = 2.;\n\ta(1, 0) = 3.; a(1, 1) = 4.;\n\n\tkv::invert(a, b);\n\n\tstd::cout << b << \"\\n\";\n\n\tint i, j, n;\n\n\tn = 2000;\n\n\tboost::numeric::ublas::matrix<double> c(n, n);\n\tusing namespace boost;\n\tvariate_generator< mt19937, uniform_real<double> > rand (mt19937(time(0)), uniform_real<double>(-1., 1.));\n\n\tfor (i=0; i<n; i++) {\n\t\tfor (j=0; j<n; j++) {\n\t\t\tc(i, j) = rand();\n\t\t}\n\t}\n\n\tt = std::chrono::system_clock::now();\n\tkv::invert(c, b);\n\tstd::cout << std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::system_clock::now() - t).count() / 1e9 << \" sec\\n\";\n\n\tboost::numeric::ublas::vector<double> d(n);\n\n\tt = std::chrono::system_clock::now();\n\tkv::linear_equation(c, d, d);\n\tstd::cout << std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::system_clock::now() - t).count() / 1e9 << \" sec\\n\";\n\n\tt = std::chrono::system_clock::now();\n\tkv::mm_mult(c, b, b);\n\tstd::cout << std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::system_clock::now() - t).count() / 1e9 << \" sec\\n\";\n}\n", "meta": {"hexsha": "9dbe867d8ed26b19bc14d9d7c9a25ac764969b94", "size": 1415, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/test-invert.cc", "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": "test/test-invert.cc", "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": "test/test-invert.cc", "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": 26.2037037037, "max_line_length": 131, "alphanum_fraction": 0.6275618375, "num_tokens": 472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708698, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.46321459115097047}}
{"text": "#include \"get_nn.h\"\n#include \"geometry.h\"\n\n#include <cmath>\n#include <algorithm>\n#include <iostream>\n#include <unordered_map>\n#include <Eigen/Geometry>\nusing namespace std;\nusing namespace Eigen;\n\nnamespace marvel {\n\nspatial_hash::spatial_hash(const MatrixXd& points_, const size_t& nn_num_)\n    : points(points_), points_num(points_.cols()), nn_num(nn_num_)\n{\n    //set hash parameter\n    size_t table_size = size_t(floor(pow(points.cols(), 0.5)));\n    //build hash_map\n    points_hash = unordered_multimap<Vector3i, size_t>(table_size);\n    hash_NNN();\n}\n\nint spatial_hash::get_shell(const Eigen::Vector3i& query, const int& radi, std::vector<Vector3i>& shell) const\n{\n    assert(radi > -1);\n    //init\n    shell.clear();\n    int res = 0;\n\n    auto loop = [&](const int& face, const int& face_axis, const int& radi_1, const int& radi_2) {\n        if (face <= max_id(face_axis) && face >= min_id(face_axis))\n        {\n            int axis_1 = (face_axis + 1) % 3, axis_2 = (face_axis + 2) % 3;\n            for (int j = query(axis_1) - radi_1; j < query(axis_1) + radi_1 + 1; ++j)\n            {\n                for (int k = query(axis_2) - radi_2; k < query(axis_2) + radi_2 + 1; ++k)\n                {\n                    Vector3i one_grid;\n                    one_grid[face_axis] = face;\n                    one_grid[axis_1]    = j;\n                    one_grid[axis_2]    = k;\n                    shell.push_back(one_grid);\n                }\n            }\n            return 0;\n        }\n        else\n        {\n            return 1;\n        }\n    };\n    if (radi > 0)\n    {\n        int touch_time = 0;\n        for (size_t i = 0; i < 6; ++i)\n        {\n\n            touch_time += loop(i % 2 == 0 ? query(i / 2) - radi : query(i / 2) + radi, i / 2, i < 4 ? radi : radi - 1, i < 2 ? radi : radi - 1);\n        }\n        if (touch_time == 6)\n            res = -1;\n    }\n    else\n    {\n        shell.push_back(query);\n    }\n    return res;\n}\n\nint spatial_hash::find_NN(const size_t& point_id, vector<pair_dis>& NN_cand)\n{\n    return std::move(find_NN(point_id, NN_cand, nn_num));\n}\n\nint spatial_hash::find_NN(const size_t& point_id, vector<pair_dis>& NN_cand, const size_t& nn_num_)\n{\n\n    size_t cand_num  = 0;\n    int    grid_delt = 0;\n    // bool once_more = false;\n    int once_more = 0;\n    int touch_bd  = 0;\n    //count for grid_delt;\n    do\n    {\n        vector<Vector3i> shell;\n        touch_bd = get_shell(points_dis.col(point_id), grid_delt, shell);\n        for (auto& grid : shell)\n        {\n            auto range = points_hash.equal_range(grid);\n            if (range.first != range.second)\n            {\n                for_each(range.first, range.second, [&](decltype(points_hash)::value_type& one_point) {\n                    double dis = (points.col(point_id) - points.col(one_point.second)).norm();\n                    NN_cand.push_back({ one_point.second, dis });\n                });\n            }\n        }\n        ++grid_delt;\n        if (NN_cand.size() > nn_num_ + 2)\n            // once_more = !once_more;\n            once_more++;\n        if (touch_bd)\n            break;\n\n    } while (NN_cand.size() < nn_num_ + 2 || once_more < 2);\n    return 0;\n}\n\nint spatial_hash::hash_NNN()\n{\n    //init\n    NN.setZero(nn_num, points_num);\n    points_hash.clear();\n    //set parameter\n\n    double   cell_num = pow(points.cols() / float(nn_num), 1.0 / 3);\n    MatrixXd bdbox(3, 2);\n    build_bdbox(points, bdbox);\n    cell_size = (bdbox.col(1) - bdbox.col(0)) / cell_num;\n    //generate discretized 3D position\n    points_dis = MatrixXi(3, points_num);\n    for (size_t i = 0; i < points.rows(); ++i)\n    {\n        points_dis.row(i) = floor(points.row(i).array() / cell_size(i)).cast<int>();\n    }\n\n    max_id = { points_dis.row(0).maxCoeff(), points_dis.row(1).maxCoeff(), points_dis.row(2).maxCoeff() };\n    min_id = { points_dis.row(0).minCoeff(), points_dis.row(1).minCoeff(), points_dis.row(2).minCoeff() };\n\n    //insert elements\n\n    for (size_t i = 0; i < points_num; ++i)\n    {\n        points_hash.insert({ points_dis.col(i), i });\n    }\n\n    return 0;\n}\n\nconst MatrixXi& spatial_hash::get_NN(const size_t& nn_num_)\n{\n    auto useless_sup_radi = get_sup_radi(nn_num_);\n\n    return NN;\n}\nconst MatrixXi& spatial_hash::get_NN()\n{\n    return std::move(get_NN(nn_num));\n}\n\nconst VectorXi spatial_hash::get_NN(const Vector3d& query, const size_t& nn_num_)\n{\n    //init data\n    assert(nn_num_ < points_num);\n    VectorXi         near_nei = VectorXi::Zero(nn_num_);\n    vector<pair_dis> NN_cand;\n\n    size_t         cand_num    = 0;\n    int            grid_delt   = 0;\n    int            once_more   = 0;\n    const Vector3i center_grid = floor(query.array() / cell_size.array()).cast<int>();\n    do\n    {\n        vector<Vector3i> shell;\n        get_shell(center_grid, grid_delt, shell);\n        for (auto& grid : shell)\n        {\n            auto range = points_hash.equal_range(grid);\n            if (range.first != range.second)\n            {\n                for_each(range.first, range.second, [&](decltype(points_hash)::value_type& one_point) {\n                    double dis = (query - points.col(one_point.second)).norm();\n                    NN_cand.push_back({ one_point.second, dis });\n                });\n            }\n        }\n        ++grid_delt;\n        if (NN_cand.size() > nn_num_ + 2)\n            once_more++;\n    } while (NN_cand.size() < nn_num_ + 2 || once_more < 2);\n\n    sort(NN_cand.begin(), NN_cand.end(), [](const pair_dis& a, const pair_dis& b) { return a.dis < b.dis; });\n\n    for (size_t j = 0; j < nn_num_; ++j)\n    {\n        near_nei(j) = NN_cand[j].n;\n    }\n    return near_nei;\n}\n\nconst Eigen::MatrixXi spatial_hash::get_four_noncoplanar_NN(const Eigen::MatrixXd& nods)\n{\n    MatrixXi near_nei = MatrixXi::Zero(4, nods.cols());\n    // #pragma omp parallel for\n    for (size_t i = 0; i < nods.cols(); ++i)\n    {\n\n        auto     ver_nn_num = 4;\n        Vector2i two_index;\n        two_index << 2, 3;\n        bool is_co_line = true, is_co_plane = true;\n        do\n        {\n            auto     NN_index = get_NN(nods.col(i), ver_nn_num);\n            Vector3d V1       = (points.col(NN_index(1)) - points.col(NN_index(0))).normalized();\n            Vector3d V2       = (points.col(NN_index(two_index(0))) - points.col(NN_index(0))).normalized();\n            Vector3d cross_   = V1.cross(V2);\n            if (cross_.squaredNorm() < 1e-5)\n            {\n                two_index(0)++;\n                two_index(1)++;\n                ver_nn_num++;\n                is_co_line = true;\n            }\n            else\n            {\n                is_co_line = false;\n\n                do\n                {\n                    Vector3d V3 = (points.col(NN_index(two_index(1))) - points.col(NN_index(0))).normalized();\n                    if (fabs(cross_.dot(V3)) < 1e-5)\n                    {\n                        two_index(1)++;\n                        ver_nn_num++;\n                        NN_index = get_NN(nods.col(i), ver_nn_num);\n                        // assert(ver_nn_num < 10);\n                        is_co_plane = true;\n                    }\n                    else\n                    {\n                        is_co_plane    = false;\n                        near_nei(0, i) = NN_index(0);\n                        near_nei(1, i) = NN_index(1);\n                        near_nei(2, i) = NN_index(two_index(0));\n                        near_nei(3, i) = NN_index(two_index(1));\n                        break;\n                    }\n                } while (is_co_plane);\n            }\n        } while (is_co_line);\n    }\n    return near_nei;\n}\n\nconst VectorXd& spatial_hash::get_sup_radi()\n{\n    return std::move(get_sup_radi(nn_num));\n}\n\nconst VectorXd& spatial_hash::get_sup_radi(const size_t& nn_num_)\n{\n    assert(points.cols() >= nn_num_);\n\n    //init data\n\n    sup_radi.setZero(points_num);\n\n#pragma omp parallel for\n    for (size_t i = 0; i < points_num; ++i)\n    {\n        vector<pair_dis> NN_cand;\n        find_NN(i, NN_cand, nn_num_ + 2);\n        sort(NN_cand.begin(), NN_cand.end(), [](const pair_dis& a, const pair_dis& b) { return a.dis < b.dis; });\n        for (size_t j = 0; j < nn_num_; ++j)\n        {\n            NN(j, i) = NN_cand[j].n;\n            sup_radi[i] += NN_cand[j].dis;\n        }\n    }\n    sup_radi *= 3.0 / nn_num_;\n    return sup_radi;\n}\nint spatial_hash::get_friends(const Vector3d& query, const double& sup_radi, vector<size_t>& friends, bool is_sample) const\n{\n\n    friends.clear();\n    int            grid_delt   = static_cast<int>(ceil(sup_radi / cell_size.col(0).minCoeff())) + 1;\n    const Vector3i center_grid = floor(query.array() / cell_size.array()).cast<int>();\n    for (size_t i = 0; i < grid_delt; ++i)\n    {\n        vector<Vector3i> shell;\n        get_shell(center_grid, i, shell);\n        for (auto& one_grid : shell)\n        {\n            auto range = points_hash.equal_range(one_grid);\n            if (range.first != range.second)\n            {\n                for_each(range.first, range.second, [&](const decltype(points_hash)::value_type& one_point) {\n                    double dis = (points.col(one_point.second) - query).norm();\n                    if (dis < sup_radi)\n                        friends.push_back(one_point.second);\n                });\n            }\n        }\n    }\n    assert(friends.size() > nn_num);\n    return 0;\n}\n// int spatial_hash::update_points(const Eigen::MatrixXd &points_){\n//   points = points_;\n//   hash_NNN();\n//   return 0;\n// }\n\n}  // namespace marvel\n", "meta": {"hexsha": "281f7f04da4de239ba5b4cd16c967b1d4b1ec1a7", "size": 9483, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Source/Dynamics/FiniteElementMethod/Source/Geometry/get_nn.cc", "max_stars_repo_name": "weikm/sandcarSimulation2", "max_stars_repo_head_hexsha": "fe499d0a3289c0ac1acce69c7dc78d8ce1b2708a", "max_stars_repo_licenses": ["Apache-2.0"], "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/Dynamics/FiniteElementMethod/Source/Geometry/get_nn.cc", "max_issues_repo_name": "weikm/sandcarSimulation2", "max_issues_repo_head_hexsha": "fe499d0a3289c0ac1acce69c7dc78d8ce1b2708a", "max_issues_repo_licenses": ["Apache-2.0"], "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/Dynamics/FiniteElementMethod/Source/Geometry/get_nn.cc", "max_forks_repo_name": "weikm/sandcarSimulation2", "max_forks_repo_head_hexsha": "fe499d0a3289c0ac1acce69c7dc78d8ce1b2708a", "max_forks_repo_licenses": ["Apache-2.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.6893203883, "max_line_length": 144, "alphanum_fraction": 0.5298956027, "num_tokens": 2529, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128672997041659, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4632145859842852}}
{"text": "/*\n * test_infostat.cpp\n *\n *  Created on: 29 mai 2016\n *      Author: boubad\n */\n#include <boost/test/unit_test.hpp>\n/////////////////////////\n#include <infostat.h>\n/////////////////////////////\n#include <mytestfixture.h>\n////////////////////////////////////\n#include <global_defs.h>\n////////////////////\nusing namespace info;\nusing namespace std;\n///////////////////////////////////\nusing MyFixture = MyTestFixture<IDTYPE, INTTYPE, STRINGTYPE, WEIGHTYPE>;\n/////////////////////////////////////\nusing IndivType = typename MyFixture::IndivType;\nusing DataMap = typename MyFixture::DataMap;\nusing IndivTypePtr = typename MyFixture::IndivTypePtr;\nusing SourceType = typename MyFixture::SourceType;\n////////////////////////////////\nusing StatInfoType = StatInfo<IDTYPE, STRINGTYPE>;\nusing StatSummatorType = StatSummator<IDTYPE,STRINGTYPE>;\nusing ints_vector = std::vector<IDTYPE>;\n/////////////////////////////////////\nBOOST_FIXTURE_TEST_SUITE(StatInfoTestSuite,MyFixture)\nBOOST_AUTO_TEST_CASE(testMortalStatInfo) {\n\tSourceType *pProvider = this->mortal_source();\n\tBOOST_CHECK(pProvider != nullptr);\n\t//\n\tStatSummatorType oStat;\n\tpProvider->reset();\n\tsize_t nTotal = 0;\n\tdo {\n\t\tIndivTypePtr oInd = pProvider->next();\n\t\tif (oInd.get() == nullptr) {\n\t\t\tbreak;\n\t\t}\n\t\toStat.add(oInd);\n\t\t++nTotal;\n\t} while (true);\n\tints_vector keys;\n\toStat.get_keys(keys);\n\tsize_t nc = keys.size();\n\tBOOST_CHECK(nc > 0);\n\tconst double epsilon = 0.000001;\n\tfor (auto &key : keys) {\n\t\tbool bFound = oStat.has_key(key);\n\t\tBOOST_CHECK(bFound);\n\t\tStatInfoType oInfo;\n\t\tbool bRet = oStat.get(key, oInfo);\n\t\tBOOST_CHECK(bRet);\n\t\tsize_t nz = oInfo.get_count();\n\t\tBOOST_CHECK(nz > 0);\n\t\tdouble vmin = oInfo.get_min();\n\t\tdouble vmax = oInfo.get_max();\n\t\tBOOST_CHECK(vmin < vmax);\n\t\tdouble vmean = oInfo.get_mean();\n\t\tBOOST_CHECK(vmean > vmin);\n\t\tBOOST_CHECK(vmean < vmax);\n\t\tdouble vcov = oInfo.get_variance();\n\t\tBOOST_CHECK(vcov > 0);\n\t\tdouble vstd = oInfo.get_deviation();\n\t\tBOOST_CHECK(vstd > 0);\n\t\tfor (auto &key1 : keys) {\n\t\t\tdouble xxcov = 0;\n\t\t\tbRet = oStat.get_covariance(key, key1, xxcov);\n\t\t\tBOOST_CHECK(bRet);\n\t\t\tBOOST_CHECK(xxcov != 0);\n\t\t\tdouble xxcor = -5.0;\n\t\t\tbRet = oStat.get_correlation(key, key1, xxcor);\n\t\t\tBOOST_CHECK(bRet);\n\t\t\tdouble x = std::abs(xxcor);\n\t\t\tBOOST_CHECK(x <= (1.0 + epsilon));\n\t\t} // keye1\n\t} // key\n} //testMortalMatElem\n\nBOOST_AUTO_TEST_SUITE_END();\n\n", "meta": {"hexsha": "eaf8f118541636985b8aff390813d08c9093cf85", "size": 2358, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test_infostat/tests/test_infostat.cpp", "max_stars_repo_name": "boubad/CygProjects", "max_stars_repo_head_hexsha": "cdc0dc2cb6e34b94d1bafbf3fd216b32c320985d", "max_stars_repo_licenses": ["Apache-2.0"], "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_infostat/tests/test_infostat.cpp", "max_issues_repo_name": "boubad/CygProjects", "max_issues_repo_head_hexsha": "cdc0dc2cb6e34b94d1bafbf3fd216b32c320985d", "max_issues_repo_licenses": ["Apache-2.0"], "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_infostat/tests/test_infostat.cpp", "max_forks_repo_name": "boubad/CygProjects", "max_forks_repo_head_hexsha": "cdc0dc2cb6e34b94d1bafbf3fd216b32c320985d", "max_forks_repo_licenses": ["Apache-2.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.0714285714, "max_line_length": 72, "alphanum_fraction": 0.6289228159, "num_tokens": 647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583376458153, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.4630980309352074}}
{"text": "// standard libraries\n#include <assert.h>\n#include <Eigen/Dense>\n#include <cmath>\n#include <cstring>\n#include <experimental/filesystem>\n#include <fstream>\n#include <iostream>\n#include <iterator>\n#include <sstream>\n#include <thread>\n#include <vector>\n\n// Open3D\n#include <Open3D/Geometry/KDTreeFlann.h>\n#include <Open3D/Geometry/PointCloud.h>\n#include <Open3D/IO/ClassIO/PointCloudIO.h>\n\n// OMPL\n#include <ompl/base/SpaceInformation.h>\n#include <ompl/base/spaces/SE3StateSpace.h>\n#include <ompl/config.h>\n#include <ompl/geometric/SimpleSetup.h>\n#include <ompl/geometric/planners/rrt/RRTConnect.h>\n\n// TinyPly\n#define TINYPLY_IMPLEMENTATION\n#include \"tinyply.h\"\n\n// flightlib\n#include \"flightlib/bridges/unity_bridge.hpp\"\n#include \"flightlib/bridges/unity_message_types.hpp\"\n#include \"flightlib/common/quad_state.hpp\"\n#include \"flightlib/common/types.hpp\"\n#include \"flightlib/objects/quadrotor.hpp\"\n#include \"flightlib/sensors/rgb_camera.hpp\"\n\nnamespace ob = ompl::base;\nnamespace og = ompl::geometric;\n\nusing namespace flightlib;\n\nnamespace motion_planning {\n\nstruct float3 {\n  float x, y, z;\n};\n\nstruct Bounds {\n  float3 min;\n  float3 max;\n};\n\nclass MotionPlanner {\n public:\n  MotionPlanner();\n  ~MotionPlanner();\n  void run();\n  void readPointCloud();\n  void getBounds();\n  bool plan();\n  void executePath();\n\n private:\n  std::vector<ompl::base::State *> path_;\n  std::vector<Eigen::Vector3d> vecs_;\n  std::vector<float3> verts_;\n  open3d::geometry::KDTreeFlann kd_tree_;\n  Eigen::MatrixXd points_;\n  Bounds bounds_;\n\n  // unity\n  SceneID scene_id_{UnityScene::NATUREFOREST};\n\n  // ompl methods\n  bool searchRadius(const Eigen::Vector3d &query_point, const double radius);\n  Eigen::Vector3d stateToEigen(const ompl::base::State *state);\n  bool isStateValid(const ob::State *state);\n};\n\n}  // namespace motion_planning\n", "meta": {"hexsha": "86527c7070fa6960f8543bbca4d037216b104bcd", "size": 1819, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "flightros/include/flightros/motion_planning/motion_planning.hpp", "max_stars_repo_name": "PRono8/flightmare", "max_stars_repo_head_hexsha": "19240a345026fc4a6611a133a5930f8b5086cdd4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 596.0, "max_stars_repo_stars_event_min_datetime": "2020-08-12T17:37:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:20:48.000Z", "max_issues_repo_path": "flightros/include/flightros/motion_planning/motion_planning.hpp", "max_issues_repo_name": "PRono8/flightmare", "max_issues_repo_head_hexsha": "19240a345026fc4a6611a133a5930f8b5086cdd4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 142.0, "max_issues_repo_issues_event_min_datetime": "2020-09-02T12:55:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T07:19:10.000Z", "max_forks_repo_path": "flightros/include/flightros/motion_planning/motion_planning.hpp", "max_forks_repo_name": "PRono8/flightmare", "max_forks_repo_head_hexsha": "19240a345026fc4a6611a133a5930f8b5086cdd4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 268.0, "max_forks_repo_forks_event_min_datetime": "2020-09-03T05:45:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T12:17:08.000Z", "avg_line_length": 22.1829268293, "max_line_length": 77, "alphanum_fraction": 0.7443650357, "num_tokens": 489, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583376458152, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.46309803093520724}}
{"text": "//=======================================================================\n// Copyright (C) 2005 Jong Soo Park <jongsoo.park -at- gmail.com>\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 <boost/test/minimal.hpp>\n#include <iostream>\n#include <algorithm>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/dominator_tree.hpp>\n\nusing namespace std;\n\nstruct DominatorCorrectnessTestSet\n{\n  typedef pair<int, int> edge;\n\n  int numOfVertices;\n  vector<edge> edges;\n  vector<int> correctIdoms;\n};\n\nusing namespace boost;\n\ntypedef adjacency_list<\n    listS,\n    listS,\n    bidirectionalS,\n    property<vertex_index_t, std::size_t>, no_property> G;\n\nint test_main(int, char*[])\n{\n  typedef DominatorCorrectnessTestSet::edge edge;\n\n  DominatorCorrectnessTestSet testSet[7];\n\n  // Tarjan's paper\n  testSet[0].numOfVertices = 13;\n  testSet[0].edges.push_back(edge(0, 1));\n  testSet[0].edges.push_back(edge(0, 2));\n  testSet[0].edges.push_back(edge(0, 3));\n  testSet[0].edges.push_back(edge(1, 4));\n  testSet[0].edges.push_back(edge(2, 1));\n  testSet[0].edges.push_back(edge(2, 4));\n  testSet[0].edges.push_back(edge(2, 5));\n  testSet[0].edges.push_back(edge(3, 6));\n  testSet[0].edges.push_back(edge(3, 7));\n  testSet[0].edges.push_back(edge(4, 12));\n  testSet[0].edges.push_back(edge(5, 8));\n  testSet[0].edges.push_back(edge(6, 9));\n  testSet[0].edges.push_back(edge(7, 9));\n  testSet[0].edges.push_back(edge(7, 10));\n  testSet[0].edges.push_back(edge(8, 5));\n  testSet[0].edges.push_back(edge(8, 11));\n  testSet[0].edges.push_back(edge(9, 11));\n  testSet[0].edges.push_back(edge(10, 9));\n  testSet[0].edges.push_back(edge(11, 0));\n  testSet[0].edges.push_back(edge(11, 9));\n  testSet[0].edges.push_back(edge(12, 8));\n  testSet[0].correctIdoms.push_back((numeric_limits<int>::max)());\n  testSet[0].correctIdoms.push_back(0);\n  testSet[0].correctIdoms.push_back(0);\n  testSet[0].correctIdoms.push_back(0);\n  testSet[0].correctIdoms.push_back(0);\n  testSet[0].correctIdoms.push_back(0);\n  testSet[0].correctIdoms.push_back(3);\n  testSet[0].correctIdoms.push_back(3);\n  testSet[0].correctIdoms.push_back(0);\n  testSet[0].correctIdoms.push_back(0);\n  testSet[0].correctIdoms.push_back(7);\n  testSet[0].correctIdoms.push_back(0);\n  testSet[0].correctIdoms.push_back(4);\n\n  // Appel. p441. figure 19.4\n  testSet[1].numOfVertices = 7;\n  testSet[1].edges.push_back(edge(0, 1));\n  testSet[1].edges.push_back(edge(1, 2));\n  testSet[1].edges.push_back(edge(1, 3));\n  testSet[1].edges.push_back(edge(2, 4));\n  testSet[1].edges.push_back(edge(2, 5));\n  testSet[1].edges.push_back(edge(4, 6));\n  testSet[1].edges.push_back(edge(5, 6));\n  testSet[1].edges.push_back(edge(6, 1));\n  testSet[1].correctIdoms.push_back((numeric_limits<int>::max)());\n  testSet[1].correctIdoms.push_back(0);\n  testSet[1].correctIdoms.push_back(1);\n  testSet[1].correctIdoms.push_back(1);\n  testSet[1].correctIdoms.push_back(2);\n  testSet[1].correctIdoms.push_back(2);\n  testSet[1].correctIdoms.push_back(2);\n\n  // Appel. p449. figure 19.8\n  testSet[2].numOfVertices = 13,\n  testSet[2].edges.push_back(edge(0, 1));\n  testSet[2].edges.push_back(edge(0, 2));\n  testSet[2].edges.push_back(edge(1, 3));\n  testSet[2].edges.push_back(edge(1, 6));\n  testSet[2].edges.push_back(edge(2, 4));\n  testSet[2].edges.push_back(edge(2, 7));\n  testSet[2].edges.push_back(edge(3, 5));\n  testSet[2].edges.push_back(edge(3, 6));\n  testSet[2].edges.push_back(edge(4, 7));\n  testSet[2].edges.push_back(edge(4, 2));\n  testSet[2].edges.push_back(edge(5, 8));\n  testSet[2].edges.push_back(edge(5, 10));\n  testSet[2].edges.push_back(edge(6, 9));\n  testSet[2].edges.push_back(edge(7, 12));\n  testSet[2].edges.push_back(edge(8, 11));\n  testSet[2].edges.push_back(edge(9, 8));\n  testSet[2].edges.push_back(edge(10, 11));\n  testSet[2].edges.push_back(edge(11, 1));\n  testSet[2].edges.push_back(edge(11, 12));\n  testSet[2].correctIdoms.push_back((numeric_limits<int>::max)());\n  testSet[2].correctIdoms.push_back(0);\n  testSet[2].correctIdoms.push_back(0);\n  testSet[2].correctIdoms.push_back(1);\n  testSet[2].correctIdoms.push_back(2);\n  testSet[2].correctIdoms.push_back(3);\n  testSet[2].correctIdoms.push_back(1);\n  testSet[2].correctIdoms.push_back(2);\n  testSet[2].correctIdoms.push_back(1);\n  testSet[2].correctIdoms.push_back(6);\n  testSet[2].correctIdoms.push_back(5);\n  testSet[2].correctIdoms.push_back(1);\n  testSet[2].correctIdoms.push_back(0);\n\n  testSet[3].numOfVertices = 8,\n  testSet[3].edges.push_back(edge(0, 1));\n  testSet[3].edges.push_back(edge(1, 2));\n  testSet[3].edges.push_back(edge(1, 3));\n  testSet[3].edges.push_back(edge(2, 7));\n  testSet[3].edges.push_back(edge(3, 4));\n  testSet[3].edges.push_back(edge(4, 5));\n  testSet[3].edges.push_back(edge(4, 6));\n  testSet[3].edges.push_back(edge(5, 7));\n  testSet[3].edges.push_back(edge(6, 4));\n  testSet[3].correctIdoms.push_back((numeric_limits<int>::max)());\n  testSet[3].correctIdoms.push_back(0);\n  testSet[3].correctIdoms.push_back(1);\n  testSet[3].correctIdoms.push_back(1);\n  testSet[3].correctIdoms.push_back(3);\n  testSet[3].correctIdoms.push_back(4);\n  testSet[3].correctIdoms.push_back(4);\n  testSet[3].correctIdoms.push_back(1);\n  \n  // Muchnick. p256. figure 8.21\n  testSet[4].numOfVertices = 8,\n  testSet[4].edges.push_back(edge(0, 1));\n  testSet[4].edges.push_back(edge(1, 2));\n  testSet[4].edges.push_back(edge(2, 3));\n  testSet[4].edges.push_back(edge(2, 4));\n  testSet[4].edges.push_back(edge(3, 2));\n  testSet[4].edges.push_back(edge(4, 5));\n  testSet[4].edges.push_back(edge(4, 6));\n  testSet[4].edges.push_back(edge(5, 7));\n  testSet[4].edges.push_back(edge(6, 7));\n  testSet[4].correctIdoms.push_back((numeric_limits<int>::max)());\n  testSet[4].correctIdoms.push_back(0);\n  testSet[4].correctIdoms.push_back(1);\n  testSet[4].correctIdoms.push_back(2);\n  testSet[4].correctIdoms.push_back(2);\n  testSet[4].correctIdoms.push_back(4);\n  testSet[4].correctIdoms.push_back(4);\n  testSet[4].correctIdoms.push_back(4);\n\n  // Muchnick. p253. figure 8.18\n  testSet[5].numOfVertices = 8,\n  testSet[5].edges.push_back(edge(0, 1));\n  testSet[5].edges.push_back(edge(0, 2));\n  testSet[5].edges.push_back(edge(1, 6));\n  testSet[5].edges.push_back(edge(2, 3));\n  testSet[5].edges.push_back(edge(2, 4));\n  testSet[5].edges.push_back(edge(3, 7));\n  testSet[5].edges.push_back(edge(5, 7));\n  testSet[5].edges.push_back(edge(6, 7));\n  testSet[5].correctIdoms.push_back((numeric_limits<int>::max)());\n  testSet[5].correctIdoms.push_back(0);\n  testSet[5].correctIdoms.push_back(0);\n  testSet[5].correctIdoms.push_back(2);\n  testSet[5].correctIdoms.push_back(2);\n  testSet[5].correctIdoms.push_back((numeric_limits<int>::max)());\n  testSet[5].correctIdoms.push_back(1);\n  testSet[5].correctIdoms.push_back(0);\n\n  // Cytron's paper, fig. 9\n  testSet[6].numOfVertices = 14,\n  testSet[6].edges.push_back(edge(0, 1));\n  testSet[6].edges.push_back(edge(0, 13));\n  testSet[6].edges.push_back(edge(1, 2));\n  testSet[6].edges.push_back(edge(2, 3));\n  testSet[6].edges.push_back(edge(2, 7));\n  testSet[6].edges.push_back(edge(3, 4));\n  testSet[6].edges.push_back(edge(3, 5));\n  testSet[6].edges.push_back(edge(4, 6));\n  testSet[6].edges.push_back(edge(5, 6));\n  testSet[6].edges.push_back(edge(6, 8));\n  testSet[6].edges.push_back(edge(7, 8));\n  testSet[6].edges.push_back(edge(8, 9));\n  testSet[6].edges.push_back(edge(9, 10));\n  testSet[6].edges.push_back(edge(9, 11));\n  testSet[6].edges.push_back(edge(10, 11));\n  testSet[6].edges.push_back(edge(11, 9));\n  testSet[6].edges.push_back(edge(11, 12));\n  testSet[6].edges.push_back(edge(12, 2));\n  testSet[6].edges.push_back(edge(12, 13));\n  testSet[6].correctIdoms.push_back((numeric_limits<int>::max)());\n  testSet[6].correctIdoms.push_back(0);\n  testSet[6].correctIdoms.push_back(1);\n  testSet[6].correctIdoms.push_back(2);\n  testSet[6].correctIdoms.push_back(3);\n  testSet[6].correctIdoms.push_back(3);\n  testSet[6].correctIdoms.push_back(3);\n  testSet[6].correctIdoms.push_back(2);\n  testSet[6].correctIdoms.push_back(2);\n  testSet[6].correctIdoms.push_back(8);\n  testSet[6].correctIdoms.push_back(9);\n  testSet[6].correctIdoms.push_back(9);\n  testSet[6].correctIdoms.push_back(11);\n  testSet[6].correctIdoms.push_back(0);\n\n  for (size_t i = 0; i < sizeof(testSet)/sizeof(testSet[0]); ++i)\n  {\n    const int numOfVertices = testSet[i].numOfVertices;\n\n    G g(\n      testSet[i].edges.begin(), testSet[i].edges.end(),\n      numOfVertices);\n\n    typedef graph_traits<G>::vertex_descriptor Vertex;\n    typedef property_map<G, vertex_index_t>::type IndexMap;\n    typedef\n      iterator_property_map<vector<Vertex>::iterator, IndexMap>\n      PredMap;\n\n    vector<Vertex> domTreePredVector, domTreePredVector2;\n    IndexMap indexMap(get(vertex_index, g));\n    graph_traits<G>::vertex_iterator uItr, uEnd;\n    int j = 0;\n    for (tie(uItr, uEnd) = vertices(g); uItr != uEnd; ++uItr, ++j)\n    {\n      put(indexMap, *uItr, j);\n    }\n\n    // Lengauer-Tarjan dominator tree algorithm\n    domTreePredVector =\n      vector<Vertex>(num_vertices(g), graph_traits<G>::null_vertex());\n    PredMap domTreePredMap =\n      make_iterator_property_map(domTreePredVector.begin(), indexMap);\n\n    lengauer_tarjan_dominator_tree(g, vertex(0, g), domTreePredMap);\n\n    vector<int> idom(num_vertices(g));\n    for (tie(uItr, uEnd) = vertices(g); uItr != uEnd; ++uItr)\n    {\n      if (get(domTreePredMap, *uItr) != graph_traits<G>::null_vertex())\n        idom[get(indexMap, *uItr)] =\n          get(indexMap, get(domTreePredMap, *uItr));\n      else\n        idom[get(indexMap, *uItr)] = (numeric_limits<int>::max)();\n    }\n\n    copy(idom.begin(), idom.end(), ostream_iterator<int>(cout, \" \"));\n    cout << endl;\n\n    // dominator tree correctness test\n    BOOST_CHECK(equal(idom.begin(), idom.end(), testSet[i].correctIdoms.begin()));\n\n    // compare results of fast version and slow version of dominator tree\n    domTreePredVector2 =\n      vector<Vertex>(num_vertices(g), graph_traits<G>::null_vertex());\n    domTreePredMap =\n      make_iterator_property_map(domTreePredVector2.begin(), indexMap);\n\n    iterative_bit_vector_dominator_tree(g, vertex(0, g), domTreePredMap);\n\n    vector<int> idom2(num_vertices(g));\n    for (tie(uItr, uEnd) = vertices(g); uItr != uEnd; ++uItr)\n    {\n      if (get(domTreePredMap, *uItr) != graph_traits<G>::null_vertex())\n        idom2[get(indexMap, *uItr)] =\n          get(indexMap, get(domTreePredMap, *uItr));\n      else\n        idom2[get(indexMap, *uItr)] = (numeric_limits<int>::max)();\n    }\n\n    copy(idom2.begin(), idom2.end(), ostream_iterator<int>(cout, \" \"));\n    cout << endl;\n\n    size_t k;\n    for (k = 0; k < num_vertices(g); ++k)\n      BOOST_CHECK(domTreePredVector[k] == domTreePredVector2[k]);\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "604796a68a0b7a0828c20f253711b3c728a76657", "size": 10881, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/graph/test/dominator_tree_test.cpp", "max_stars_repo_name": "oudream/boost_1_42_0", "max_stars_repo_head_hexsha": "e92227bf374e478030e89876ec353de6eecaeac0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-04-08T10:44:28.000Z", "max_stars_repo_stars_event_max_datetime": "2017-04-08T10:44:28.000Z", "max_issues_repo_path": "libs/graph/test/dominator_tree_test.cpp", "max_issues_repo_name": "jonstewart/boost-svn", "max_issues_repo_head_hexsha": "7f6dc0c0cb807b28072c7bdd3d77bb01ab290c59", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/graph/test/dominator_tree_test.cpp", "max_forks_repo_name": "jonstewart/boost-svn", "max_forks_repo_head_hexsha": "7f6dc0c0cb807b28072c7bdd3d77bb01ab290c59", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.5134228188, "max_line_length": 82, "alphanum_fraction": 0.6809116809, "num_tokens": 3626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.665410572017153, "lm_q1q2_score": 0.4630980271606094}}
{"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/** \r\n\\file\r\n    \r\n\\brief composite_output.cpp\r\n\r\n\\details An example of textual representations of units.\r\n\r\nOutput:\r\n@verbatim\r\n\r\n//[conversion_output_output\r\n2 dyn\r\n2 dyn\r\n2 dyne\r\ncm g s^-1\r\ncentimeter gram second^-1\r\ndyn\r\ndyne\r\nn\r\nnano\r\nn\r\nnano\r\nF\r\nfarad\r\n1 F\r\n1 farad\r\nnF\r\nnanofarad\r\n1 nF\r\n1 nanofarad\r\nn(cm g s^-1)\r\nnano(centimeter gram second^-1)\r\n//]\r\n\r\n@endverbatim\r\n**/\r\n#include <boost/units/quantity.hpp>\r\n#include <boost/units/systems/cgs.hpp>\r\n#include <boost/units/io.hpp>\r\n#include <boost/units/scale.hpp>\r\n\r\n#include <boost/units/detail/utility.hpp>\r\n\r\n#include <boost/units/systems/si/capacitance.hpp>\r\n#include <boost/units/systems/si/io.hpp>\r\n#include <boost/units/systems/si/prefixes.hpp>\r\n\r\n#include <iostream>\r\n#include <sstream>\r\n\r\nnamespace boost {\r\n\r\nnamespace units {\r\n\r\n//[composite_output_snippet_1\r\n\r\nstd::string name_string(const cgs::force&)\r\n{\r\n    return \"dyne\";\r\n}\r\n\r\nstd::string symbol_string(const cgs::force&)\r\n{\r\n    return \"dyn\";\r\n}\r\n\r\n//]\r\n\r\n}\r\n\r\n}\r\n\r\nint main() \r\n{\r\n    using namespace boost::units;\r\n    using boost::units::cgs::centimeter;\r\n    using boost::units::cgs::gram;\r\n    using boost::units::cgs::second;\r\n    using boost::units::cgs::dyne;\r\n        \r\n    //[composite_output_snippet_2]\r\n    std::cout << 2.0 * dyne << std::endl\r\n              << symbol_format << 2.0 * dyne << std::endl\r\n              << name_format << 2.0 * dyne << std::endl\r\n              << symbol_format << gram*centimeter/second << std::endl\r\n              << name_format << gram*centimeter/second << std::endl\r\n              << symbol_format << gram*centimeter/(second*second) << std::endl\r\n              << name_format << gram*centimeter/(second*second) << std::endl\r\n              << symbol_string(scale<10,static_rational<-9> >()) << std::endl\r\n              << name_string(scale<10,static_rational<-9> >()) << std::endl\r\n              << symbol_format << si::nano << std::endl\r\n              << name_format << si::nano << std::endl\r\n              << symbol_format << si::farad << std::endl\r\n              << name_format << si::farad << std::endl\r\n              << symbol_format << 1.0*si::farad << std::endl\r\n              << name_format << 1.0*si::farad << std::endl\r\n              << symbol_format << si::farad*si::nano << std::endl\r\n              << name_format << si::farad*si::nano << std::endl\r\n              << symbol_format << 1.0*si::farad*si::nano << std::endl\r\n              << name_format << 1.0*si::farad*si::nano << std::endl\r\n              << symbol_format << si::nano*gram*centimeter/second << std::endl\r\n              << name_format << si::nano*gram*centimeter/second << std::endl;\r\n    //]\r\n              \r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "9778700d522123461514238af50a8630fe8dc0d7", "size": 3061, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/units/example/composite_output.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/example/composite_output.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/example/composite_output.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": 26.1623931624, "max_line_length": 79, "alphanum_fraction": 0.5906566482, "num_tokens": 826, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583376458152, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.46309802169960407}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2013 Kyle Lutz <kyle.r.lutz@gmail.com>\n//\n// Distributed under the Boost Software License, Version 1.0\n// See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt\n//\n// See http://kylelutz.github.com/compute for more information.\n//---------------------------------------------------------------------------//\n\n#define BOOST_TEST_MODULE TestEqualRange\n#include <boost/test/unit_test.hpp>\n\n#include <utility>\n#include <iterator>\n\n#include <boost/compute/command_queue.hpp>\n#include <boost/compute/algorithm/equal_range.hpp>\n#include <boost/compute/container/vector.hpp>\n\n#include \"context_setup.hpp\"\n\nBOOST_AUTO_TEST_CASE(equal_range_int)\n{\n    int data[] = { 1, 2, 2, 2, 3, 3, 4, 5 };\n    boost::compute::vector<int> vector(data, data + 8);\n\n    typedef boost::compute::vector<int>::iterator iterator;\n\n    std::pair<iterator, iterator> range0 =\n        boost::compute::equal_range(vector.begin(), vector.end(), int(0));\n    BOOST_CHECK(range0.first == vector.begin());\n    BOOST_CHECK(range0.second == vector.begin());\n    BOOST_CHECK_EQUAL(std::distance(range0.first, range0.second), ptrdiff_t(0));\n\n    std::pair<iterator, iterator> range1 =\n        boost::compute::equal_range(vector.begin(), vector.end(), int(1));\n    BOOST_CHECK(range1.first == vector.begin());\n    BOOST_CHECK(range1.second == vector.begin() + 1);\n    BOOST_CHECK_EQUAL(std::distance(range1.first, range1.second), ptrdiff_t(1));\n\n    std::pair<iterator, iterator> range2 =\n        boost::compute::equal_range(vector.begin(), vector.end(), int(2));\n    BOOST_CHECK(range2.first == vector.begin() + 1);\n    BOOST_CHECK(range2.second == vector.begin() + 4);\n    BOOST_CHECK_EQUAL(std::distance(range2.first, range2.second), ptrdiff_t(3));\n\n    std::pair<iterator, iterator> range3 =\n        boost::compute::equal_range(vector.begin(), vector.end(), int(3));\n    BOOST_CHECK(range3.first == vector.begin() + 4);\n    BOOST_CHECK(range3.second == vector.begin() + 6);\n    BOOST_CHECK_EQUAL(std::distance(range3.first, range3.second), ptrdiff_t(2));\n\n    std::pair<iterator, iterator> range4 =\n        boost::compute::equal_range(vector.begin(), vector.end(), int(4));\n    BOOST_CHECK(range4.first == vector.begin() + 6);\n    BOOST_CHECK(range4.second == vector.begin() + 7);\n    BOOST_CHECK_EQUAL(std::distance(range4.first, range4.second), ptrdiff_t(1));\n\n    std::pair<iterator, iterator> range5 =\n        boost::compute::equal_range(vector.begin(), vector.end(), int(5));\n    BOOST_CHECK(range5.first == vector.begin() + 7);\n    BOOST_CHECK(range5.second == vector.end());\n    BOOST_CHECK_EQUAL(std::distance(range5.first, range5.second), ptrdiff_t(1));\n\n    std::pair<iterator, iterator> range6 =\n        boost::compute::equal_range(vector.begin(), vector.end(), int(6));\n    BOOST_CHECK(range6.first == vector.end());\n    BOOST_CHECK(range6.second == vector.end());\n    BOOST_CHECK_EQUAL(std::distance(range6.first, range6.second), ptrdiff_t(0));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "0f36be987ada618ce8aee7f4225fc7d103420997", "size": 3081, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_equal_range.cpp", "max_stars_repo_name": "bastiankoe/compute", "max_stars_repo_head_hexsha": "57eec36d20e122a496d3fbfddf8bf4ad8d6f4a4f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-03-18T01:14:13.000Z", "max_stars_repo_stars_event_max_datetime": "2015-03-18T01:14:13.000Z", "max_issues_repo_path": "test/test_equal_range.cpp", "max_issues_repo_name": "bastiankoe/compute", "max_issues_repo_head_hexsha": "57eec36d20e122a496d3fbfddf8bf4ad8d6f4a4f", "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/test_equal_range.cpp", "max_forks_repo_name": "bastiankoe/compute", "max_forks_repo_head_hexsha": "57eec36d20e122a496d3fbfddf8bf4ad8d6f4a4f", "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.6351351351, "max_line_length": 80, "alphanum_fraction": 0.6562804284, "num_tokens": 741, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.46309801792500643}}
{"text": "/*\nCopyright (c) Facebook, Inc. and its affiliates.\n\nThis source code is licensed under the MIT license found in the\nLICENSE file in the root directory of this source tree.\n*/\n\n// Without this flag, GTSAM Expressions currently fail within fbcode.\n// We need EIGEN_MAKE_ALIGNED_OPERATOR_NEW in GTSAM to really fix this\n#define EIGEN_DONT_ALIGN_STATICALLY\n\n#include <boost/filesystem.hpp>\n\n#include \"Mesh.h\"\n\n#include <iostream>\n#include <math.h>\n\nnamespace sumo {\n\nusing namespace std;\n\nMesh::Mesh(\n    const vector<Index>& indices,\n    const vector<Vertex>& vertices,\n    const vector<Normal>& normals)\n    : indices_(indices), vertices_(vertices), normals_(normals) {\n  assert(vertices.size() == normals.size());\n}\n\nvector<Mesh::Normal> Mesh::CalculateFaceNormals(\n    const vector<Index>& indices,\n    const vector<Vertex>& vertices) {\n  vector<Normal> faceNormals;\n  const size_t numTriangles = indices.size() / 3;\n  faceNormals.reserve(numTriangles);\n  // Compute face normals using cross product method.\n  for (size_t i = 0; i < numTriangles; i++) {\n    // get three triangle vertex indices\n    const size_t j = i * 3;\n    const Index i0 = indices[j], i1 = indices[j + 1], i2 = indices[j + 2];\n    Vertex a = vertices[i1] - vertices[i0];\n    Vertex b = vertices[i2] - vertices[i0];\n\n    Normal n = a.cross(b).normalized();\n    faceNormals.push_back(n);\n  }\n  return faceNormals;\n}\n\nvector<Mesh::Normal> Mesh::EstimateNormals(\n    const vector<Index>& indices,\n    const vector<Vertex>& vertices) {\n  vector<Normal> faceNormals = CalculateFaceNormals(indices, vertices);\n\n  // Initialize normals to zero.\n  size_t numVertices = vertices.size();\n  vector<Mesh::Normal> normals(numVertices, Normal::Zero());\n\n  // Add face normals to all involved vertices.\n  // TODO use iterator\n  size_t j = 0;\n  for (const auto& n : faceNormals) {\n    for (Index i : {indices[j], indices[j + 1], indices[j + 2]}) {\n      assert(i < numVertices);\n      normals[i] += n;\n    }\n    j += 3;\n  }\n\n  for (auto& n : normals) {\n    n.normalize();\n  }\n\n  return normals;\n}\n\nvoid Mesh::cleanupLongEdges(float threshold) {\n  vector<Index> new_indices;\n  new_indices.reserve(numIndices());\n  // define distance function\n  const auto dist = [](Vertex x, Vertex y) { return (x - y).norm(); };\n  // loop over all triangles in this mesh\n  for (const auto& triangle : *this) {\n    // check all edges\n    if (dist(triangle.a, triangle.b) <= threshold &&\n        dist(triangle.b, triangle.c) <= threshold &&\n        dist(triangle.c, triangle.a) <= threshold) {\n      // add triangle since valid\n      new_indices.push_back(triangle.i);\n      new_indices.push_back(triangle.j);\n      new_indices.push_back(triangle.k);\n    }\n  }\n  indices_ = new_indices;\n}\n\nvoid Mesh::cleanupEdgesToOrigin(const double precision) {\n  vector<Index> new_indices;\n  new_indices.reserve(numIndices());\n  // loop over all triangles in this mesh\n  for (const auto& triangle : *this) {\n    // If any vertex is zero, we bail.\n    if (triangle.a.isZero(precision) || triangle.b.isZero(precision) ||\n        triangle.c.isZero(precision)) {\n      continue;\n    }\n    // add triangle since valid\n    new_indices.push_back(triangle.i);\n    new_indices.push_back(triangle.j);\n    new_indices.push_back(triangle.k);\n  }\n  indices_ = new_indices;\n}\n\nMesh Mesh::Example(\n    const double length /* = 2.0*/,\n    const bool inward /* = true */) {\n  vector<Index> indices;\n  indices.insert(indices.end(), {1, 0, 2}); // Left face   (x = -1.0f)\n  indices.insert(indices.end(), {2, 3, 1}); // Left face   (x = -1.0f)\n  indices.insert(indices.end(), {4, 0, 1}); // Bottom face (y = -1.0f)\n  indices.insert(indices.end(), {1, 5, 4}); // Bottom face (y = -1.0f)\n  indices.insert(indices.end(), {2, 0, 4}); // Back face   (z = -1.0f)\n  indices.insert(indices.end(), {4, 6, 2}); // Back face   (z = -1.0f)\n  indices.insert(indices.end(), {5, 7, 6}); // Right face  (x = +1.0f)\n  indices.insert(indices.end(), {6, 4, 5}); // Right face  (x = +1.0f)\n  indices.insert(indices.end(), {6, 7, 3}); // Top face    (y = +1.0f)\n  indices.insert(indices.end(), {3, 2, 6}); // Top face    (y = +1.0f)\n  indices.insert(indices.end(), {3, 7, 5}); // Front face  (z = +1.0f)\n  indices.insert(indices.end(), {5, 1, 3}); // Front face  (z = +1.0f)\n  if (inward == false) {\n    reverse(indices.begin(), indices.end());\n  }\n\n  vector<Vertex> vertices;\n  const double radius = length / 2;\n  vertices.push_back(Vertex(-1.0f, -1.0f, -1.0f) * radius); // 0th\n  vertices.push_back(Vertex(-1.0f, -1.0f, +1.0f) * radius); // 1st\n  vertices.push_back(Vertex(-1.0f, +1.0f, -1.0f) * radius); // 2nd\n  vertices.push_back(Vertex(-1.0f, +1.0f, +1.0f) * radius); // 3rd\n  vertices.push_back(Vertex(+1.0f, -1.0f, -1.0f) * radius); // 4th\n  vertices.push_back(Vertex(+1.0f, -1.0f, +1.0f) * radius); // 5th\n  vertices.push_back(Vertex(+1.0f, +1.0f, -1.0f) * radius); // 6th\n  vertices.push_back(Vertex(+1.0f, +1.0f, +1.0f) * radius); // 7th\n\n  return Mesh(indices, vertices, Mesh::EstimateNormals(indices, vertices));\n}\n\nvoid Mesh::merge(const Mesh& mesh2, size_t numCommonVertices) {\n  // Merge the indices.\n  const size_t offset = numVertices() - numCommonVertices;\n  for (const size_t& index2 : mesh2.indices()) {\n    indices_.push_back(index2 < numCommonVertices ? index2 : index2 + offset);\n  }\n\n  // Treat the case when mesh2 defines new vertices.\n  if (mesh2.numVertices() > numCommonVertices) {\n    const auto append = [numCommonVertices](auto& a, const auto& b) {\n      a.insert(a.end(), b.begin() + numCommonVertices, b.end());\n    };\n    append(vertices_, mesh2.vertices());\n    append(normals_, mesh2.normals());\n  }\n}\n\nvoid Mesh::replaceGeometry(const Mesh& mesh2) {\n  //Replace the geometry of the mesh.\n  indices_.clear();\n  vertices_.clear();\n  normals_.clear();\n\n  merge(mesh2, 0);\n\n}\n  \n  /// Operator == for Parameter\n  // ::: TODO: This function is not correct.  It does not check all aspects\n  // of the parameter struct.  Furthermore, some aspects of the Parameter\n  // struct are unstable (that is, they are not initialized to known values,\n  // so comparing two Parameter objects is not really feasible with the\n  // tiny_gltf design.\nstatic bool parametersEqual(\n    const tinygltf::Parameter& a,\n    const tinygltf::Parameter& b) {\n  return \n    a.has_number_value == b.has_number_value &&\n    a.string_value == b.string_value &&\n    a.json_double_value == b.json_double_value;\n}\n\n/// Operator == for Parameter\nstatic bool namedParametersEqual(\n    const tinygltf::ParameterMap::value_type& a,\n    const tinygltf::ParameterMap::value_type& b) {\n  return a.first == b.first && parametersEqual(a.second, b.second);\n}\n\n/// Operator == for ParameterMap\nbool operator==(\n    const tinygltf::ParameterMap& a,\n    const tinygltf::ParameterMap& b) {\n  return a.size() == b.size() &&\n      std::equal(a.begin(), a.end(), b.begin(), namedParametersEqual);\n}\n\n/// Operator == for Material\n// Only comparing ParameterMaps and name.\n// TODO: Compare extensions and extras.\nbool operator==(const tinygltf::Material& a, const tinygltf::Material& b) {\n  return a.additionalValues == b.additionalValues && a.values == b.values &&\n      a.name == b.name;\n}\n\n  \nbool Mesh::hasSameMaterial(const Mesh& other) const {\n  return material_ == other.material_;\n}\n\n\n} // namespace sumo\n", "meta": {"hexsha": "6de1f0d924434fbb1f84ee86fd62c43d1a65957f", "size": 7276, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sumo-api/sumo/threedee/Mesh.cpp", "max_stars_repo_name": "pmoulon/sumo-challenge", "max_stars_repo_head_hexsha": "8f7842c535366e86c67a7e459c03bd6459e92d82", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-07T07:58:32.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-07T07:58:32.000Z", "max_issues_repo_path": "sumo-api/sumo/threedee/Mesh.cpp", "max_issues_repo_name": "pmoulon/sumo-challenge", "max_issues_repo_head_hexsha": "8f7842c535366e86c67a7e459c03bd6459e92d82", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sumo-api/sumo/threedee/Mesh.cpp", "max_forks_repo_name": "pmoulon/sumo-challenge", "max_forks_repo_head_hexsha": "8f7842c535366e86c67a7e459c03bd6459e92d82", "max_forks_repo_licenses": ["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.7747747748, "max_line_length": 78, "alphanum_fraction": 0.657366685, "num_tokens": 2066, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585903489892, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.46306001447690337}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// mpl::example::rest.cpp                              \t\t\t\t\t \t //\n//                                                                           //\n//  Copyright 2008 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#include <iostream>\n#include <boost/mpl/assert.hpp>\n#include <boost/mpl/equal.hpp>\n#include <boost/mpl/equal_to.hpp>\n#include <boost/mpl/int.hpp>\n#include <boost/mpl/size.hpp>\n#include <boost/mpl/range_c.hpp>\n#include <boost/statistics/detail/mpl/rest.hpp>\n#include <boost/statistics/detail/mpl/most.hpp>\n#include <libs/statistics/detail/range_ex/example/rest.h>\n\nvoid example_nested_chain(std::cout);\n\n\ttypedef boost::mpl::range_c<int,0,3> vec_;\n\tnamespace mpl = boost::statistics::detail::mpl;\n\n\ttypedef mpl::rest<vec_> meta_rest_;\n    typedef meta_rest_::type rest_;\n\ttypedef mpl::most<vec_> meta_most_;\n    typedef meta_most_::type most_;\n        \n    BOOST_MPL_ASSERT((\n\t\tboost::mpl::equal<\n        \tboost::mpl::range_c<int,1,3>,\n            rest_\n        >\n    ));\n    BOOST_MPL_ASSERT((\n\t\tboost::mpl::equal<\n        \tboost::mpl::range_c<int,0,2>,\n            most_\n        >\n    ));\n\n}\n", "meta": {"hexsha": "f59010c27dc7ff3c573725055c0f3d4233943447", "size": 1439, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "detail/mpl/libs/statistics/detail/example/rest.cpp", "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": "detail/mpl/libs/statistics/detail/example/rest.cpp", "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": "detail/mpl/libs/statistics/detail/example/rest.cpp", "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.4651162791, "max_line_length": 79, "alphanum_fraction": 0.5232800556, "num_tokens": 310, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.63341027059799, "lm_q1q2_score": 0.4630600121130134}}
{"text": "/* Copyright (C) 2012-2019 IBM Corp.\n * This program is Licensed under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *   http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License. See accompanying LICENSE file.\n */\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <numeric>\n#include <tuple>\n#include <NTL/BasicThreadPool.h>\n\n#include <helib.h>\n\n#include <intraSlot.h>\n#include <binaryArith.h>\n\n#include \"gtest/gtest.h\"\n#include \"test_common.h\"\n\n#ifdef DEBUG_PRINTOUT\n#include <debugging.h>\n#endif\n// define flags FLAG_PRINT_ZZX, FLAG_PRINT_POLY, FLAG_PRINT_VEC, functions\n//        decryptAndPrint(ostream, ctxt, sk, ea, flags)\n//        decryptAndCompare(ctxt, sk, ea, pa);\n\nnamespace {\n\nstruct Parameters\n{\n  Parameters(long prm,\n             long bitSize,\n             long bitSize2,\n             long outSize,\n             bool bootstrap,\n             long seed,\n             long nthreads) :\n      prm(prm),\n      bitSize(bitSize),\n      bitSize2(bitSize2),\n      outSize(outSize),\n      bootstrap(bootstrap),\n      seed(seed),\n      nthreads(nthreads){};\n\n  long prm;       // parameter size (0-tiny,...,7-huge)\n  long bitSize;   // bitSize of input integers (<=32)\n  long bitSize2;  // bitSize of 2nd input integer (<=32)\n  long outSize;   // bitSize of output integers, as many as needed\n  bool bootstrap; // test multiplication with bootstrapping\n  long seed;      // PRG seed\n  long nthreads;  // number of threads\n\n  friend std::ostream& operator<<(std::ostream& os, const Parameters& params)\n  {\n    return os << \"{\"\n              << \"prm=\" << params.prm << \",\"\n              << \"bitSize=\" << params.bitSize << \",\"\n              << \"bitSize2=\" << params.bitSize2 << \",\"\n              << \"outSize=\" << params.outSize << \",\"\n              << \"bootstrap=\" << params.bootstrap << \",\"\n              << \"seed=\" << params.seed << \",\"\n              << \"nthreads=\" << params.nthreads << \"}\";\n  };\n};\n\nclass GTest_binaryArith :\n    public ::testing::TestWithParam<std::tuple<Parameters, int>>\n{\nprotected:\n  static std::vector<helib::zzX> unpackSlotEncoding;\n  constexpr static long mValues[8][15] = {\n      // { p, phi(m),   m,   d, m1, m2, m3,    g1,   g2,   g3, ord1,ord2,ord3,\n      // B,c}\n      {2, 48, 105, 12, 3, 35, 0, 71, 76, 0, 2, 2, 0, 25, 2},\n      {2, 600, 1023, 10, 11, 93, 0, 838, 584, 0, 10, 6, 0, 25, 2},\n      {2, 2304, 4641, 24, 7, 3, 221, 3979, 3095, 3760, 6, 2, -8, 25, 3},\n      {2, 5460, 8193, 26, 8193, 0, 0, 46, 0, 0, 210, 0, 0, 25, 3},\n      {2, 8190, 8191, 13, 8191, 0, 0, 39, 0, 0, 630, 0, 0, 25, 3},\n      {2, 10752, 11441, 48, 17, 673, 0, 4712, 2024, 0, 16, -14, 0, 25, 3},\n      {2, 15004, 15709, 22, 23, 683, 0, 4099, 13663, 0, 22, 31, 0, 25, 3},\n      {2,\n       27000,\n       32767,\n       15,\n       31,\n       7,\n       151,\n       11628,\n       28087,\n       25824,\n       30,\n       6,\n       -10,\n       28,\n       4}};\n\n  static long correctBitSize(long minimum, long oldBitSize)\n  {\n    long newBitSize;\n    if (oldBitSize <= 0)\n      newBitSize = minimum;\n    else if (oldBitSize > 32)\n      newBitSize = 32;\n    else\n      newBitSize = oldBitSize;\n    return newBitSize;\n  };\n\n  // Validates the prm value, throwing if invalid\n  static long validatePrm(long prm)\n  {\n    if (prm < 0 || prm >= 5)\n      throw std::invalid_argument(\"prm must be in the interval [0, 4]\");\n    return prm;\n  };\n\n  static NTL::Vec<long> calculateMvec(const long* vals)\n  {\n    NTL::Vec<long> mvec;\n    NTL::append(mvec, vals[4]);\n    if (vals[5] > 1)\n      NTL::append(mvec, vals[5]);\n    if (vals[6] > 1)\n      NTL::append(mvec, vals[6]);\n    return mvec;\n  };\n\n  static std::vector<long> calculateGens(const long* vals)\n  {\n    std::vector<long> gens;\n    gens.push_back(vals[7]);\n    if (vals[8] > 1)\n      gens.push_back(vals[8]);\n    if (vals[9] > 1)\n      gens.push_back(vals[9]);\n    return gens;\n  };\n\n  static std::vector<long> calculateOrds(const long* vals)\n  {\n    std::vector<long> ords;\n    ords.push_back(vals[10]);\n    if (abs(vals[11]) > 1)\n      ords.push_back(vals[11]);\n    if (abs(vals[12]) > 1)\n      ords.push_back(vals[12]);\n    return ords;\n  };\n\n  static long calculateLevels(bool bootstrap, long outSize, long bitSize)\n  {\n    long L;\n    if (bootstrap)\n      L = 900; // that should be enough\n    else {\n      double nBits =\n          (outSize > 0 && outSize < 2 * bitSize) ? outSize : (2 * bitSize);\n      double three4twoLvls = log(nBits / 2) / log(1.5);\n      double add2NumsLvls = log(nBits) / log(2.0);\n      L = (5 + ceil(three4twoLvls + add2NumsLvls)) * 30;\n    }\n    return L;\n  };\n\n  // Returns a reference to the passed-in context once it has been modified to\n  // get it ready for test. This is not static because it uses quite a lot of\n  // state of the object.\n  helib::FHEcontext& prepareContext(helib::FHEcontext& context)\n  {\n    if (helib_test::verbose) {\n      std::cout << \"input bitSizes=\" << bitSize << ',' << bitSize2\n                << \", output size bound=\" << outSize << std::endl;\n      if (nthreads > 1)\n        std::cout << \"  using \" << NTL::AvailableThreads() << \" threads\\n\";\n      std::cout << \"computing key-independent tables...\" << std::flush;\n    }\n    buildModChain(context, L, c, /*willBeBootstrappable=*/bootstrap);\n    if (bootstrap) {\n      context.makeBootstrappable(mvec, /*t=*/0);\n    }\n    buildUnpackSlotEncoding(unpackSlotEncoding, *context.ea);\n    if (helib_test::verbose) {\n      std::cout << \" done.\\n\";\n      context.zMStar.printout();\n    }\n    return context;\n  };\n\n  void prepareSecKey(helib::FHESecKey& secKey)\n  {\n    if (helib_test::verbose) {\n      std::cout << \" L=\" << L << \", B=\" << B << std::endl;\n      std::cout << \"\\ncomputing key-dependent tables...\" << std::flush;\n    }\n    secKey.GenSecKey();\n    addSome1DMatrices(secKey); // compute key-switching matrices\n    addFrbMatrices(secKey);\n    if (bootstrap)\n      secKey.genRecryptData();\n    if (helib_test::verbose)\n      std::cout << \" done\\n\";\n  };\n\n  const long prm;\n  const long bitSize;\n  const long bitSize2;\n  const long outSize;\n  const bool bootstrap;\n  const long seed;\n  const long nthreads;\n\n  const long* vals;\n  const long p;\n  const long m;\n  const NTL::Vec<long> mvec;\n  const std::vector<long> gens;\n  const std::vector<long> ords;\n  const long B;\n  const long c;\n  const long L;\n  helib::FHEcontext context;\n  helib::FHESecKey secKey;\n\n  GTest_binaryArith() :\n      prm(validatePrm(std::get<0>(GetParam()).prm)),\n      bitSize(correctBitSize(5, std::get<0>(GetParam()).bitSize)),\n      bitSize2(correctBitSize(bitSize, std::get<0>(GetParam()).bitSize2)),\n      outSize(std::get<0>(GetParam()).outSize),\n      bootstrap(std::get<0>(GetParam()).bootstrap),\n      seed(std::get<0>(GetParam()).seed),\n      nthreads(std::get<0>(GetParam()).nthreads),\n      vals(mValues[prm]),\n      p(vals[0]),\n      m(vals[2]),\n      mvec(calculateMvec(vals)),\n      gens(calculateGens(vals)),\n      ords(calculateOrds(vals)),\n      B(vals[13]),\n      c(vals[14]),\n      L(calculateLevels(bootstrap, outSize, bitSize)),\n      context(m, p, /*r=*/1, gens, ords),\n      secKey(prepareContext(context)){};\n\n  void SetUp() override\n  {\n    if (seed)\n      NTL::SetSeed(NTL::ZZ(seed));\n    if (nthreads > 1)\n      NTL::SetNumThreads(nthreads);\n\n    prepareSecKey(secKey);\n\n    helib::activeContext = &context; // make things a little easier sometimes\n#ifdef DEBUG_PRINTOUT\n    helib::dbgEa = (helib::EncryptedArray*)context.ea;\n    helib::dbgKey = &secKey;\n#endif\n  }\n\n  virtual void TearDown() override\n  {\n#ifdef DEBUG_PRINTOUT\n    helib::cleanupGlobals();\n#endif\n  }\n\n  // This gets called once all of the tests have run\npublic:\n  static void TearDownTestCase()\n  {\n    if (helib_test::verbose)\n      helib::printAllTimers(std::cout);\n  };\n};\nconstexpr long GTest_binaryArith::mValues[8][15];\nstd::vector<helib::zzX> GTest_binaryArith::unpackSlotEncoding;\n\nTEST_P(GTest_binaryArith, fifteenForFour)\n{\n  // Randomly generate up to 15 integers from {0,1} with some entries\n  // randomly set to null.  We then encrypt and use the fifteenOrLess4Four\n  // function to calculate the binary representation of their sum.  This is\n  // then checked against the plaintext calculation.\n  // In this case each ciphertext is considered to be the encryption of one\n  // bit, however packing more into the slots is possible.\n  // LSB is at the start (left) of the vector.\n\n  // vector of ciphertexts corresponding to encrypted input bit vectors.\n  std::vector<helib::Ctxt> inBuf(15, helib::Ctxt(secKey));\n  std::vector<helib::Ctxt*> inPtrs(15, nullptr);\n\n  // vector of ciphertexts corresponding to the summation of the input bit\n  // vectors.\n  std::vector<helib::Ctxt> outBuf(5, helib::Ctxt(secKey));\n\n  // Randomly generate and encrypt the input vectors.\n  long sum = 0;\n  std::string inputBits = \"(\";\n  for (int i = 0; i < 15; i++) {\n    if (NTL::RandomBnd(10) > 0) { // Leave empty (null) with small probability.\n      inPtrs[i] = &(inBuf[i]);\n      long bit = NTL::RandomBnd(2); // Select a randomised bit.\n      secKey.Encrypt(inBuf[i], NTL::ZZX(bit));\n      inputBits += std::to_string(bit) + \",\";\n      sum += bit; // Keep track of the plaintext sum.\n    } else\n      inputBits += \"-,\"; // This represents a null bit.\n  }\n  inputBits += \")\";\n\n  if (helib_test::verbose) {\n    std::cout << std::endl;\n    helib::CheckCtxt(inBuf[helib::lsize(inBuf) - 1], \"b4 15for4\");\n  }\n  // Add the encrypted bits.\n  long numOutputs = fifteenOrLess4Four(helib::CtPtrs_vectorCt(outBuf),\n                                       helib::CtPtrs_vectorPt(inPtrs));\n  if (helib_test::verbose)\n    helib::CheckCtxt(outBuf[helib::lsize(outBuf) - 1], \"after 15for4\");\n\n  // Check the result.\n  long sum2 = 0;\n  for (int i = 0; i < numOutputs; i++) {\n    NTL::ZZX poly;\n    secKey.Decrypt(poly, outBuf[i]);\n    sum2 += to_long(ConstTerm(poly)) << i;\n  }\n  EXPECT_EQ(sum, sum2) << \"inputs = \" << inputBits << std::endl;\n  if (helib_test::verbose) {\n    std::cout << \"15to4 succeeded, sum\" << inputBits << \"=\" << sum2\n              << std::endl;\n  }\n};\n\nTEST_P(GTest_binaryArith, product)\n{\n  // Randomly generate a pair of numbers of a specified bit size and then\n  // encrypt them in binary representation. Then use multTwoNumbers to\n  // multiply the two positive binary numbers and then check against the\n  // plaintext calculation. Next, use multTwoNumbers with binary numbers in\n  // 2's complement to calculate the product where the multplier is negative\n  // and then check against the plaintext calculation.\n  //\n  // In this case each ciphertext is considered to be the encryption of one\n  // bit, however packing more into the slots is possible.\n  // LSB is at the start (left) of the vector.\n\n  const helib::EncryptedArray& ea = *context.ea;\n  // outSize 1's on the least significant end of mask.\n  long mask = (outSize ? ((1L << outSize) - 1) : -1);\n\n  // Choose two random integers with correct bit sizes.\n  long multiplicand_data = NTL::RandomBits_long(bitSize);\n  long multiplier_data = NTL::RandomBits_long(bitSize2);\n\n  // Encrypt the individual bits.\n  NTL::Vec<helib::Ctxt> encrypted_product, encrypted_multiplicand,\n      encrypted_multiplier;\n\n  // Resizes the vector of ciphertexts (encrypted_bits) to match the input size.\n  helib::resize(encrypted_multiplicand, bitSize, helib::Ctxt(secKey));\n  for (long i = 0; i < bitSize; i++) {\n    secKey.Encrypt(encrypted_multiplicand[i],\n                   NTL::ZZX((multiplicand_data >> i) & 1));\n    if (bootstrap) { // If bootstrapping then modulo down to a lower level.\n      encrypted_multiplicand[i].bringToSet(context.getCtxtPrimes(5));\n    }\n  }\n  helib::resize(encrypted_multiplier, bitSize2, helib::Ctxt(secKey));\n  for (long i = 0; i < bitSize2; i++) {\n    secKey.Encrypt(encrypted_multiplier[i],\n                   NTL::ZZX((multiplier_data >> i) & 1));\n    if (bootstrap) { // If bootstrapping then modulo down to a lower level.\n      encrypted_multiplier[i].bringToSet(context.getCtxtPrimes(5));\n    }\n  }\n  if (helib_test::verbose) {\n    std::cout << \"\\n  bits-size \" << bitSize << '+' << bitSize2;\n    if (outSize > 0)\n      std::cout << \"->\" << outSize;\n    helib::CheckCtxt(encrypted_multiplier[0], \"b4 multiplication\");\n  }\n  std::vector<long> slots; // Vector that will hold the decrypted result.\n  // Test multiplication with two positive numbers.\n  // A scope which tests multTwoNumbers using wrappers around the encrypted\n  // data.\n  {\n    helib::CtPtrs_VecCt output_wrapper(\n        encrypted_product); // A wrapper around the output vector.\n    helib::multTwoNumbers(output_wrapper,\n                          helib::CtPtrs_VecCt(encrypted_multiplicand),\n                          helib::CtPtrs_VecCt(encrypted_multiplier),\n                          /*negative=*/false,\n                          outSize,\n                          &unpackSlotEncoding);\n    helib::decryptBinaryNums(slots, output_wrapper, secKey, ea);\n  } // output_wrapper is deleted once out of scope.\n  if (helib_test::verbose)\n    helib::CheckCtxt(encrypted_product[helib::lsize(encrypted_product) - 1],\n                     \"after multiplication\");\n\n  // Calculate the multiplication in the plain.\n  long plaintext_product = multiplicand_data * multiplier_data;\n  EXPECT_EQ(slots[0], ((multiplicand_data * multiplier_data) & mask))\n      << \"Positive product error: multiplicand_data=\" << multiplicand_data\n      << \", multiplier_data=\" << multiplier_data << \", but product=\" << slots[0]\n      << \" (should be \" << plaintext_product << '&' << mask << '='\n      << (plaintext_product & mask) << \")\\n\";\n\n  if (helib_test::verbose) {\n    std::cout << \"positive product succeeded: \";\n    if (outSize)\n      std::cout << \"bottom \" << outSize << \" bits of \";\n    std::cout << multiplicand_data << \"*\" << multiplier_data << \"=\" << slots[0]\n              << std::endl;\n  }\n\n  // Test multiplication of numbers in 2's complement where the multiplier is\n  // negative.\n  secKey.Encrypt(encrypted_multiplier[bitSize2 - 1], NTL::ZZX(1));\n  decryptBinaryNums(slots,\n                    helib::CtPtrs_VecCt(encrypted_multiplier),\n                    secKey,\n                    ea,\n                    /*negative=*/true);\n  multiplier_data = slots[0];\n  encrypted_product.kill(); // Clear the data in encrypted_product.\n  // A scope which tests multTwoNumbers (with a negative multiplier) using\n  // wrappers around the encrypted data.\n  {\n    helib::CtPtrs_VecCt output_wrapper(\n        encrypted_product); // A wrapper around the output vector.\n    multTwoNumbers(output_wrapper,\n                   helib::CtPtrs_VecCt(encrypted_multiplicand),\n                   helib::CtPtrs_VecCt(encrypted_multiplier),\n                   /*negative=*/true,\n                   outSize,\n                   &unpackSlotEncoding);\n    decryptBinaryNums(slots, output_wrapper, secKey, ea, /*negative=*/true);\n  } // output_wrapper is deleted once out of scope.\n\n  if (helib_test::verbose)\n    helib::CheckCtxt(encrypted_product[helib::lsize(encrypted_product) - 1],\n                     \"after multiplication\");\n\n  // Calculate the multiplication in the plain.\n  plaintext_product = multiplicand_data * multiplier_data;\n  EXPECT_EQ((slots[0] & mask), (plaintext_product & mask))\n      << \"Negative product error: multiplicand_data=\" << multiplicand_data\n      << \", multiplier_data=\" << multiplier_data << \", but product=\" << slots[0]\n      << \" (should be \" << plaintext_product << '&' << mask << '='\n      << (plaintext_product & mask) << \")\\n\";\n  if (helib_test::verbose) {\n    std::cout << \"negative product succeeded: \";\n    if (outSize)\n      std::cout << \"bottom \" << outSize << \" bits of \";\n    std::cout << multiplicand_data << \"*\" << multiplier_data << \"=\" << slots[0]\n              << std::endl;\n  }\n\n#ifdef DEBUG_PRINTOUT\n  // Print out the ciphertext with the lowest level after multiplication\n  // if DEBUG_PRINTOUT is defined.\n  const helib::Ctxt* minCtxt = nullptr;\n  long minLvl = 10000000;\n  for (const helib::Ctxt& c : encrypted_product) {\n    long lvl = c.logOfPrimeSet();\n    if (lvl < minLvl) {\n      minCtxt = &c;\n      minLvl = lvl;\n    }\n  }\n  decryptAndPrint(\n      (std::cout << \" after multiplication: \"), *minCtxt, secKey, ea, 0);\n  std::cout << std::endl;\n#endif\n};\n\nTEST_P(GTest_binaryArith, add)\n{\n  // Randomly generate a pair of numbers of a specified bit size and then\n  // encrypt them in binary representation. Then use addTwoNumbers to add the\n  // two binary numbers and then check against the plaintext calculation.\n  //\n  // In this case each ciphertext is considered to be the encryption of one\n  // bit, however packing more into the slots is possible.\n  // LSB is at the start(left) of the vector.\n\n  const helib::EncryptedArray& ea = *context.ea;\n  // outSize 1's on the least significant end of mask.\n  long mask = (outSize ? ((1L << outSize) - 1) : -1);\n\n  // Choose two random n-bit integers.\n  long addend_data = NTL::RandomBits_long(bitSize);\n  long augend_data = NTL::RandomBits_long(bitSize2);\n\n  // Encrypt the individual bits.\n  NTL::Vec<helib::Ctxt> encrypted_sum, encrypted_addend, encrypted_augend;\n\n  // Resizes the vector of ciphertexts (encrypted_bits) to match the input size.\n  helib::resize(encrypted_addend, bitSize, helib::Ctxt(secKey));\n  for (long i = 0; i < bitSize; i++) {\n    secKey.Encrypt(encrypted_addend[i], NTL::ZZX((addend_data >> i) & 1));\n    if (bootstrap) { // If bootstrapping then modulo down to a lower level.\n      encrypted_addend[i].bringToSet(context.getCtxtPrimes(5));\n    }\n  }\n  // Resizes the vector of ciphertexts (encrypted_bits) to match the input size.\n  helib::resize(encrypted_augend, bitSize2, helib::Ctxt(secKey));\n  for (long i = 0; i < bitSize2; i++) {\n    secKey.Encrypt(encrypted_augend[i], NTL::ZZX((augend_data >> i) & 1));\n    if (bootstrap) { // If bootstrapping then modulo down to a lower level.\n      encrypted_augend[i].bringToSet(context.getCtxtPrimes(5));\n    }\n  }\n  if (helib_test::verbose) {\n    std::cout << \"\\n  bits-size \" << bitSize << '+' << bitSize2;\n    if (outSize > 0)\n      std::cout << \"->\" << outSize;\n    std::cout << std::endl;\n    helib::CheckCtxt(encrypted_augend[0], \"b4 addition\");\n  }\n\n  std::vector<long>\n      decrypted_result; // Vector that will hold the decrypted result.\n  // Test addition.\n  // A scope which tests addTwoNumbers using wrappers around the encrypted data.\n  {\n    helib::CtPtrs_VecCt output_wrapper(\n        encrypted_sum); // A wrapper around the output vector.\n    helib::addTwoNumbers(output_wrapper,\n                         helib::CtPtrs_VecCt(encrypted_addend),\n                         helib::CtPtrs_VecCt(encrypted_augend),\n                         outSize,\n                         &unpackSlotEncoding);\n    helib::decryptBinaryNums(decrypted_result, output_wrapper, secKey, ea);\n  } // output_wrapper is deleted once out of scope.\n\n  if (helib_test::verbose)\n    helib::CheckCtxt(encrypted_sum[helib::lsize(encrypted_sum) - 1],\n                     \"after addition\");\n\n  // Calculate the addition in the plain.\n  long plaintext_sum = addend_data + augend_data;\n  EXPECT_EQ(decrypted_result[0], ((addend_data + augend_data) & mask))\n      << \"addTwoNums error: addend_data=\" << addend_data\n      << \", augend_data=\" << augend_data\n      << \", but plaintext_sum=\" << decrypted_result[0]\n      << \" (should be =\" << (plaintext_sum & mask) << \")\\n\";\n  if (helib_test::verbose) {\n    std::cout << \"addTwoNums succeeded: \";\n    if (outSize)\n      std::cout << \"bottom \" << outSize << \" bits of \";\n    std::cout << addend_data << \"+\" << augend_data << \"=\" << decrypted_result[0]\n              << std::endl;\n  }\n\n#ifdef DEBUG_PRINTOUT\n  // Print out the ciphertext with the lowest level after addition if\n  // DEBUG_PRINTOUT is defined.\n  const helib::Ctxt* minCtxt = nullptr;\n  long minLvl = 1000;\n  for (const helib::Ctxt& c : encrypted_sum) {\n    long lvl = c.logOfPrimeSet();\n    if (lvl < minLvl) {\n      minCtxt = &c;\n      minLvl = lvl;\n    }\n  }\n  decryptAndPrint((std::cout << \" after addition: \"), *minCtxt, secKey, ea, 0);\n  std::cout << std::endl;\n#endif\n};\n\nTEST_P(GTest_binaryArith, addManyNumbers)\n{\n  // Randomly generate a vector of numbers of a specified bit size and then\n  // encrypt them in binary representation. Then use addManyNumbers to add\n  // them all up and then check against the plaintext calculation.\n  //\n  // In this case each ciphertext is considered to be the encryption of one\n  // bit, however packing more into the slots is possible.\n  // LSB is at the start(left) of the vector.\n\n  const long num_summands = 5;\n  const helib::EncryptedArray& ea = *context.ea;\n  // outSize 1's on the least significant end of mask.\n  long mask = (outSize ? ((1L << outSize) - 1) : -1);\n\n  // Choose a set of random n-bit integers.\n  std::vector<long> summands_data;\n  for (long i = 0; i < num_summands; ++i)\n    summands_data.push_back(NTL::RandomBits_long(bitSize));\n\n  // Encrypt the individual bits.\n  std::vector<helib::Ctxt> encrypted_sum;\n  std::vector<std::vector<helib::Ctxt>> encrypted_summands;\n\n  // Utility function for encrypting a number into a binary representation.\n  const auto encrypt_binary_number =\n      [&](const long num) -> std::vector<helib::Ctxt> {\n    std::vector<helib::Ctxt> encrypted_num;\n    // Resizes the vector of ciphertexts (encrypted_bits) to match the input\n    // size.\n    helib::resize(encrypted_num, bitSize, helib::Ctxt(secKey));\n    for (long i = 0; i < bitSize; i++) {\n      secKey.Encrypt(encrypted_num[i], NTL::ZZX((num >> i) & 1));\n      if (bootstrap) { // If bootstrapping then modulo down to a lower level.\n        encrypted_num[i].bringToSet(context.getCtxtPrimes(5));\n      }\n    }\n    return encrypted_num;\n  };\n\n  // Encrypt the set of numbers into binary representation.\n  for (long i = 0; i < num_summands; ++i)\n    encrypted_summands.push_back(encrypt_binary_number(summands_data[i]));\n\n  if (helib_test::verbose)\n    helib::CheckCtxt(encrypted_summands[0][0], \"b4 addition\");\n\n  std::vector<long>\n      decrypted_result; // Vector that will hold the decrypted result.\n  // Test summation.\n  // A scope which tests addManyNumbers using wrappers around the encrypted\n  // data.\n  {\n    helib::CtPtrs_vectorCt output_wrapper(\n        encrypted_sum); // A wrapper around the output vector.\n    helib::CtPtrMat_vectorCt summands_wrapper(\n        encrypted_summands); // A wrapper around the output vector.\n    helib::addManyNumbers(\n        output_wrapper, summands_wrapper, outSize, &unpackSlotEncoding);\n    helib::decryptBinaryNums(decrypted_result, output_wrapper, secKey, ea);\n  } // output_wrapper is deleted once out of scope.\n\n  if (helib_test::verbose)\n    helib::CheckCtxt(encrypted_sum[helib::lsize(encrypted_sum) - 1],\n                     \"after addition\");\n\n  // Calculate the summation in the plain.\n  long plaintext_sum = std::accumulate(\n      summands_data.begin(), summands_data.end(), 0l, std::plus<long>());\n  EXPECT_EQ(decrypted_result[0], plaintext_sum & mask);\n  if (helib_test::verbose) {\n    std::cout << \"addManyNums succeeded: \";\n    if (outSize)\n      std::cout << \"bottom \" << outSize << \" bits of \";\n    std::cout << summands_data[0];\n    for (long i = 1; i < num_summands; ++i)\n      std::cout << \"+\" << summands_data[i];\n    std::cout << \"=\" << decrypted_result[0] << std::endl;\n  }\n}\n\nINSTANTIATE_TEST_SUITE_P(\n    small_parameter_sizes_repeated,\n    GTest_binaryArith,\n    ::testing::Combine(\n        ::testing::Values(\n            // SLOW\n            Parameters(1, 5, 0, 0, false, 0, 1)\n            // FAST\n            // Parameters(0, 5, 0, 0, false, 0, 1)), ::testing::Range(0,2)\n\n            ),\n        ::testing::Range(0, 2)) // The range is for repeats\n);\n\n} // anonymous namespace\n", "meta": {"hexsha": "97f5f4398747deda692076bc0841ff15a96be228", "size": 24097, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tests/GTest_binaryArith.cpp", "max_stars_repo_name": "patrick-schwarz/HElib", "max_stars_repo_head_hexsha": "cd267e2ddc6e92886b89f3aa51c416d5c1d2dc59", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-01T07:18:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-01T07:18:47.000Z", "max_issues_repo_path": "src/tests/GTest_binaryArith.cpp", "max_issues_repo_name": "wangjinglin0721/HElib", "max_issues_repo_head_hexsha": "cd267e2ddc6e92886b89f3aa51c416d5c1d2dc59", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tests/GTest_binaryArith.cpp", "max_forks_repo_name": "wangjinglin0721/HElib", "max_forks_repo_head_hexsha": "cd267e2ddc6e92886b89f3aa51c416d5c1d2dc59", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.3847283407, "max_line_length": 80, "alphanum_fraction": 0.6316968917, "num_tokens": 6850, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.46306000705397843}}
{"text": "/*******************************************************************************\n *\n * A simple class for representing intervals and performing interval\n * arithmetic.\n *\n ******************************************************************************/\n\n#pragma once\n\n#include <boost/optional.hpp>\n#include <crab/common/stats.hpp>\n#include <crab/common/types.hpp>\n#include <crab/domains/linear_interval_solver.hpp>\n#include <crab/numbers/bignums.hpp>\n\nnamespace ikos {\n\ntemplate <typename Number> class bound {\npublic:\n  typedef bound<Number> bound_t;\n\nprivate:\n  bool _is_infinite;\n  Number _n;\n\nprivate:\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        _n = 1;\n      else\n        _n = -1;\n    }\n  }\n\npublic:\n  static bound_t min(bound_t x, bound_t y) { return (x.operator<=(y) ? x : y); }\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) { return (x.operator<=(y) ? y : x); }\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() { return bound_t(true, 1); }\n\n  static bound_t minus_infinity() { return bound_t(true, -1); }\n\npublic:\n  bound(int n) : _is_infinite(false), _n(n) {}\n\n  bound(std::string s) : _n(1) {\n    if (s == \"+oo\") {\n      _is_infinite = true;\n    } else if (s == \"-oo\") {\n      _is_infinite = true;\n      _n = -1;\n    } else {\n      _is_infinite = false;\n      _n = Number(s);\n    }\n  }\n\n  bound(Number n) : _is_infinite(false), _n(n) {}\n\n  bound(const bound_t &o) : _is_infinite(o._is_infinite), _n(o._n) {}\n\n  bound_t &operator=(const bound_t &o) {\n    if (this != &o) {\n      _is_infinite = o._is_infinite;\n      _n = o._n;\n    }\n    return *this;\n  }\n\n  bool is_infinite() const { return _is_infinite; }\n\n  bool is_finite() const { return !_is_infinite; }\n\n  bool is_plus_infinity() const { return (is_infinite() && _n > 0); }\n\n  bool is_minus_infinity() const { return (is_infinite() && _n < 0); }\n\n  bound_t operator-() const { return bound_t(_is_infinite, -_n); }\n\n  bound_t operator+(bound_t x) const {\n    if (is_finite() && x.is_finite()) {\n      return bound_t(_n + x._n);\n    } else if (is_finite() && x.is_infinite()) {\n      return x;\n    } else if (is_infinite() && x.is_finite()) {\n      return *this;\n    } else if (_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) { return operator=(operator+(x)); }\n\n  bound_t operator-(bound_t x) const { return operator+(x.operator-()); }\n\n  bound_t &operator-=(bound_t x) { return operator=(operator-(x)); }\n\n  bound_t operator*(bound_t x) const {\n    if (x._n == 0)\n      return x;\n    else if (_n == 0)\n      return *this;\n    else\n      return bound_t(_is_infinite || x._is_infinite, _n * x._n);\n  }\n\n  bound_t &operator*=(bound_t x) { return operator=(operator*(x)); }\n\n  bound_t operator/(bound_t x) const {\n    if (x._n == 0) {\n      CRAB_ERROR(\"Bound: division by zero\");\n    } else if (is_finite() && x.is_finite()) {\n      return bound_t(false, _n / x._n);\n    } else if (is_finite() && x.is_infinite()) {\n      if (_n > 0) {\n        return x;\n      } else if (_n == 0) {\n        return *this;\n      } else {\n        return x.operator-();\n      }\n    } else if (is_infinite() && x.is_finite()) {\n      if (x._n > 0) {\n        return *this;\n      } else {\n        return operator-();\n      }\n    } else {\n      return bound_t(true, _n * x._n);\n    }\n  }\n\n  bound_t &operator/=(bound_t x) { return operator=(operator/(x)); }\n\n  bool operator<(bound_t x) const { return !operator>=(x); }\n\n  bool operator>(bound_t x) const { return !operator<=(x); }\n\n  bool operator==(bound_t x) const {\n    return (_is_infinite == x._is_infinite && _n == x._n);\n  }\n\n  bool operator!=(bound_t x) const { return !operator==(x); }\n\n  /*\toperator<= and operator>= use a somewhat optimized implementation.\n   *\tresults include up to 20% improvements in performance in the octagon\n   *domain over a more naive implementation.\n   */\n  bool operator<=(bound_t x) const {\n    if (_is_infinite xor x._is_infinite) {\n      if (_is_infinite) {\n        return _n < 0;\n      }\n      return x._n > 0;\n    }\n    return _n <= x._n;\n  }\n\n  bool operator>=(bound_t x) const {\n    if (_is_infinite xor x._is_infinite) {\n      if (_is_infinite) {\n        return _n > 0;\n      }\n      return x._n < 0;\n    }\n    return _n >= x._n;\n  }\n\n  bound_t abs() const {\n    if (operator>=(0)) {\n      return *this;\n    } else {\n      return operator-();\n    }\n  }\n\n  boost::optional<Number> number() const {\n    if (is_infinite()) {\n      return boost::optional<Number>();\n    } else {\n      return boost::optional<Number>(_n);\n    }\n  }\n\n  void write(crab::crab_os &o) const {\n    if (is_plus_infinity()) {\n      o << \"+oo\";\n    } else if (is_minus_infinity()) {\n      o << \"-oo\";\n    } else {\n      o << _n;\n    }\n  }\n\n}; // class bound\n\ntemplate <typename Number>\ninline crab::crab_os &operator<<(crab::crab_os &o, const bound<Number> &b) {\n  b.write(o);\n  return o;\n}\n\ntypedef bound<z_number> z_bound;\ntypedef bound<q_number> q_bound;\n\nnamespace 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\ninline void convert_bounds(z_bound b1, z_bound &b2) { std::swap(b1, b2); }\ninline void convert_bounds(q_bound b1, q_bound &b2) { std::swap(b1, b2); }\ninline void convert_bounds(z_bound b1, q_bound &b2) {\n  if (b1.is_plus_infinity())\n    b2 = q_bound::plus_infinity();\n  else if (b1.is_minus_infinity())\n    b2 = q_bound::minus_infinity();\n  else\n    b2 = q_bound(q_number(*b1.number()));\n}\ninline void convert_bounds(q_bound b1, z_bound &b2) {\n  if (b1.is_plus_infinity())\n    b2 = z_bound::plus_infinity();\n  else if (b1.is_minus_infinity())\n    b2 = z_bound::minus_infinity();\n  else\n    b2 = z_bound((*(b1.number())).round_to_lower());\n}\n} // namespace bounds_impl\n\ntemplate <typename Number> class interval {\n\npublic:\n  typedef bound<Number> bound_t;\n  typedef interval<Number> interval_t;\n\nprivate:\n  bound_t _lb;\n  bound_t _ub;\n\npublic:\n  static interval_t top() {\n    return interval_t(bound_t::minus_infinity(), bound_t::plus_infinity());\n  }\n\n  static interval_t bottom() { return interval_t(); }\n\nprivate:\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\npublic:\n  interval(bound_t lb, bound_t ub) : _lb(lb), _ub(ub) {\n    if (lb > ub) {\n      _lb = 0;\n      _ub = -1;\n    }\n  }\n\n  interval(bound_t b) : _lb(b), _ub(b) {\n    if (b.is_infinite()) {\n      _lb = 0;\n      _ub = -1;\n    }\n  }\n\n  interval(Number n) : _lb(n), _ub(n) {}\n\n  interval(std::string b) : _lb(b), _ub(b) {\n    if (_lb.is_infinite()) {\n      _lb = 0;\n      _ub = -1;\n    }\n  }\n\n  interval(const interval_t &i) : _lb(i._lb), _ub(i._ub) {}\n\n  interval_t &operator=(interval_t i) {\n    _lb = i._lb;\n    _ub = i._ub;\n    return *this;\n  }\n\n  bound_t lb() const { return _lb; }\n\n  bound_t ub() const { return _ub; }\n\n  bool is_bottom() const { return (_lb > _ub); }\n\n  bool is_top() const { return (_lb.is_infinite() && _ub.is_infinite()); }\n\n  interval_t lower_half_line() const {\n    return interval_t(bound_t::minus_infinity(), _ub);\n  }\n\n  interval_t upper_half_line() const {\n    return interval_t(_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 (_lb == x._lb) && (_ub == x._ub);\n    }\n  }\n\n  bool operator!=(interval_t x) const { return !operator==(x); }\n\n  bool operator<=(interval_t x) const {\n    if (is_bottom()) {\n      return true;\n    } else if (x.is_bottom()) {\n      return false;\n    } else {\n      return (x._lb <= _lb) && (_ub <= x._ub);\n    }\n  }\n\n  interval_t operator|(interval_t x) const {\n    if (is_bottom()) {\n      return x;\n    } else if (x.is_bottom()) {\n      return *this;\n    } else {\n      return interval_t(bound_t::min(_lb, x._lb), bound_t::max(_ub, x._ub));\n    }\n  }\n\n  interval_t operator&(interval_t x) const {\n    if (is_bottom() || x.is_bottom()) {\n      return bottom();\n    } else {\n      return interval_t(bound_t::max(_lb, x._lb), bound_t::min(_ub, x._ub));\n    }\n  }\n\n  interval_t operator||(interval_t x) const {\n    if (is_bottom()) {\n      return x;\n    } else if (x.is_bottom()) {\n      return *this;\n    } else {\n      return interval_t(x._lb < _lb ? bound_t::minus_infinity() : _lb,\n                        _ub < x._ub ? bound_t::plus_infinity() : _ub);\n    }\n  }\n\n  template <typename Thresholds>\n  interval_t widening_thresholds(interval_t x, const Thresholds &ts) {\n    if (is_bottom()) {\n      return x;\n    } else if (x.is_bottom()) {\n      return *this;\n    } else {\n      bound_t lb = (x._lb < _lb ? ts.get_prev(x._lb) : _lb);\n      bound_t ub = (_ub < x._ub ? ts.get_next(x._ub) : _ub);\n      return interval_t(lb, ub);\n    }\n  }\n\n  interval_t operator&&(interval_t x) const {\n    if (is_bottom() || x.is_bottom()) {\n      return bottom();\n    } else {\n      return interval_t(_lb.is_infinite() && x._lb.is_finite() ? x._lb : _lb,\n                        _ub.is_infinite() && x._ub.is_finite() ? x._ub : _ub);\n    }\n  }\n\n  interval_t operator+(interval_t x) const {\n    if (is_bottom() || x.is_bottom()) {\n      return bottom();\n    } else {\n      return interval_t(_lb + x._lb, _ub + x._ub);\n    }\n  }\n\n  interval_t &operator+=(interval_t x) { return operator=(operator+(x)); }\n\n  interval_t operator-() const {\n    if (is_bottom()) {\n      return bottom();\n    } else {\n      return interval_t(-_ub, -_lb);\n    }\n  }\n\n  interval_t operator-(interval_t x) const {\n    if (is_bottom() || x.is_bottom()) {\n      return bottom();\n    } else {\n      return interval_t(_lb - x._ub, _ub - x._lb);\n    }\n  }\n\n  interval_t &operator-=(interval_t x) { return operator=(operator-(x)); }\n\n  interval_t operator*(interval_t x) const {\n    if (is_bottom() || x.is_bottom()) {\n      return bottom();\n    } else {\n      bound_t ll = _lb * x._lb;\n      bound_t lu = _lb * x._ub;\n      bound_t ul = _ub * x._lb;\n      bound_t uu = _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) { return operator=(operator*(x)); }\n\n  interval_t operator/(interval_t x) const;\n\n  interval_t &operator/=(interval_t x) { return operator=(operator/(x)); }\n\n  boost::optional<Number> singleton() const {\n    if (!is_bottom() && _lb == _ub) {\n      return _lb.number();\n    } else {\n      return boost::optional<Number>();\n    }\n  }\n\n  bool operator[](Number n) const {\n    if (is_bottom()) {\n      return false;\n    } else {\n      bound_t b(n);\n      return (_lb <= b) && (b <= _ub);\n    }\n  }\n\n  void write(crab::crab_os &o) const {\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 (is_bottom() || x.is_bottom()) {\n      return bottom();\n    } else {\n      return top();\n    }\n  }\n\n  interval_t SRem(interval_t x) const {\n    if (is_bottom() || x.is_bottom()) {\n      return bottom();\n    } else {\n      return top();\n    }\n  }\n\n  interval_t URem(interval_t x) const {\n    if (is_bottom() || x.is_bottom()) {\n      return bottom();\n    } else {\n      return top();\n    }\n  }\n\n  // bitwise operations\n  interval_t And(interval_t x) const {\n    if (is_bottom() || x.is_bottom()) {\n      return bottom();\n    } else {\n      return top();\n    }\n  }\n\n  interval_t Or(interval_t x) const {\n    if (is_bottom() || x.is_bottom()) {\n      return bottom();\n    } else {\n      return top();\n    }\n  }\n\n  interval_t Xor(interval_t x) const { return Or(x); }\n\n  interval_t Shl(interval_t x) const {\n    if (is_bottom() || x.is_bottom()) {\n      return bottom();\n    } else {\n      return top();\n    }\n  }\n\n  interval_t LShr(interval_t x) const {\n    if (is_bottom() || x.is_bottom()) {\n      return bottom();\n    } else {\n      return top();\n    }\n  }\n\n  interval_t AShr(interval_t x) const {\n    if (is_bottom() || x.is_bottom()) {\n      return bottom();\n    } else {\n      return top();\n    }\n  }\n\n}; //  class interval\n\ntemplate <>\ninline interval<q_number> interval<q_number>::\noperator/(interval<q_number> x) const {\n  if (is_bottom() || x.is_bottom()) {\n    return bottom();\n  } else {\n    boost::optional<q_number> d = x.singleton();\n    if (d && *d == 0) {\n      // [_, _] / 0 = _|_\n      return bottom();\n    } else if (x[0]) {\n      boost::optional<q_number> n = singleton();\n      if (n && *n == 0) {\n        // 0 / [_, _] = 0\n        return interval_t(q_number(0));\n      } else {\n        return top();\n      }\n    } else {\n      bound_t ll = _lb / x._lb;\n      bound_t lu = _lb / x._ub;\n      bound_t ul = _ub / x._lb;\n      bound_t uu = _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\ntemplate <>\ninline interval<z_number> interval<z_number>::\noperator/(interval<z_number> x) const {\n  if (is_bottom() || x.is_bottom()) {\n    return 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      z_number c = *n;\n      if (c == 1) {\n        return *this;\n      } else if (c > 0) {\n        return interval_t(_lb / c, _ub / c);\n      } else if (c < 0) {\n        return interval_t(_ub / c, _lb / c);\n      } else {\n      }\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 (operator/(l) | operator/(u));\n    } else if (operator[](0)) {\n      z_interval l(_lb, z_bound(-1));\n      z_interval u(z_bound(1), _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 =\n          (_ub < 0) ? (*this + ((x._ub < 0) ? (x + z_interval(z_number(1)))\n                                            : (z_interval(z_number(1)) - x)))\n                    : *this;\n      bound_t ll = a._lb / x._lb;\n      bound_t lu = a._lb / x._ub;\n      bound_t ul = a._ub / x._lb;\n      bound_t uu = a._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\ntemplate <>\ninline interval<z_number> interval<z_number>::SRem(interval<z_number> x) const {\n  // note that the sign of the divisor does not matter\n\n  if (is_bottom() || x.is_bottom()) {\n    return bottom();\n  } else if (singleton() && x.singleton()) {\n    z_number dividend = *singleton();\n    z_number divisor = *x.singleton();\n\n    if (divisor == 0) {\n      return 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()), abs(*x.ub().number()));\n\n    if (max_divisor == 0) {\n      return bottom();\n    }\n\n    if (lb() < 0) {\n      if (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 top();\n  }\n}\n\ntemplate <>\ninline interval<z_number> interval<z_number>::URem(interval<z_number> x) const {\n\n  if (is_bottom() || x.is_bottom()) {\n    return bottom();\n  } else if (singleton() && x.singleton()) {\n    z_number dividend = *singleton();\n    z_number divisor = *x.singleton();\n\n    if (divisor < 0) {\n      return top();\n    } else if (divisor == 0) {\n      return 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 top();\n    } else if (max_divisor == 0) {\n      return bottom();\n    }\n\n    return interval_t(0, max_divisor - 1);\n  } else {\n    return top();\n  }\n}\n\ntemplate <>\ninline interval<z_number> interval<z_number>::And(interval<z_number> x) const {\n  if (is_bottom() || x.is_bottom()) {\n    return bottom();\n  } else {\n    boost::optional<z_number> left_op = 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 (lb() >= 0 && x.lb() >= 0) {\n      return interval_t(0, bound_t::min(ub(), x.ub()));\n    } else {\n      return top();\n    }\n  }\n}\n\ntemplate <>\ninline interval<z_number> interval<z_number>::Or(interval<z_number> x) const {\n  if (is_bottom() || x.is_bottom()) {\n    return bottom();\n  } else {\n    boost::optional<z_number> left_op = 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 (lb() >= 0 && x.lb() >= 0) {\n      boost::optional<z_number> left_ub = 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 top();\n    }\n  }\n}\n\ntemplate <>\ninline interval<z_number> interval<z_number>::Xor(interval<z_number> x) const {\n  if (is_bottom() || x.is_bottom()) {\n    return bottom();\n  } else {\n    boost::optional<z_number> left_op = 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 Or(x);\n    }\n  }\n}\n\ntemplate <>\ninline interval<z_number> interval<z_number>::Shl(interval<z_number> x) const {\n  if (is_bottom() || x.is_bottom()) {\n    return bottom();\n  } else {\n    if (boost::optional<z_number> shift = x.singleton()) {\n      z_number k = *shift;\n      if (k < 0) {\n        // CRAB_ERROR(\"lshr shift operand cannot be negative\");\n        return top();\n      }\n      // Some crazy linux drivers generate shl instructions with\n      // huge shifts.  We limit the number of times the loop is run\n      // to avoid wasting too much time on it.\n      if (k <= 128) {\n        z_number factor = 1;\n        for (int i = 0; k > i; i++) {\n          factor *= 2;\n        }\n        return (*this) * factor;\n      }\n    }\n    return top();\n  }\n}\n\ntemplate <>\ninline interval<z_number> interval<z_number>::AShr(interval<z_number> x) const {\n  if (is_bottom() || x.is_bottom()) {\n    return bottom();\n  } else {\n    if (boost::optional<z_number> shift = x.singleton()) {\n      z_number k = *shift;\n      if (k < 0) {\n        return top();\n      }\n      // Some crazy linux drivers generate ashr instructions with\n      // huge shifts.  We limit the number of times the loop is run\n      // to avoid wasting too much time on it.\n      if (k <= 128) {\n        z_number factor = 1;\n        for (int i = 0; k > i; i++) {\n          factor *= 2;\n        }\n        return (*this) / factor;\n      }\n    }\n    return top();\n  }\n}\n\ntemplate <>\ninline interval<z_number> interval<z_number>::LShr(interval<z_number> x) const {\n  if (is_bottom() || x.is_bottom()) {\n    return bottom();\n  } else {\n    if (boost::optional<z_number> shift = x.singleton()) {\n      z_number k = *shift;\n      if (k < 0) {\n        return top();\n      }\n      if (lb() >= 0 && ub().is_finite()) {\n        z_number lb = *this->lb().number();\n        z_number ub = *this->ub().number();\n        return interval<z_number>(lb >> k, ub >> k);\n      }\n    }\n    return this->top();\n  }\n}\n\ntemplate <typename Number>\ninline interval<Number> operator+(Number c, interval<Number> x) {\n  return interval<Number>(c) + x;\n}\n\ntemplate <typename Number>\ninline interval<Number> operator+(interval<Number> x, Number c) {\n  return x + interval<Number>(c);\n}\n\ntemplate <typename Number>\ninline interval<Number> operator*(Number c, interval<Number> x) {\n  return interval<Number>(c) * x;\n}\n\ntemplate <typename Number>\ninline interval<Number> operator*(interval<Number> x, Number c) {\n  return x * interval<Number>(c);\n}\n\ntemplate <typename Number>\ninline interval<Number> operator/(Number c, interval<Number> x) {\n  return interval<Number>(c) / x;\n}\n\ntemplate <typename Number>\ninline interval<Number> operator/(interval<Number> x, Number c) {\n  return x / interval<Number>(c);\n}\n\ntemplate <typename Number>\ninline interval<Number> operator-(Number c, interval<Number> x) {\n  return interval<Number>(c) - x;\n}\n\ntemplate <typename Number>\ninline interval<Number> operator-(interval<Number> x, Number c) {\n  return x - interval<Number>(c);\n}\n\ntemplate <typename Number>\ninline crab::crab_os &operator<<(crab::crab_os &o, const interval<Number> &i) {\n  i.write(o);\n  return o;\n}\n\nnamespace linear_interval_solver_impl {\n\ntypedef interval<z_number> z_interval;\ntypedef interval<q_number> q_interval;\n\ntemplate <> inline z_interval trim_interval(z_interval i, z_interval j) {\n  if (boost::optional<z_number> c = j.singleton()) {\n    if (i.lb() == *c) {\n      return z_interval(*c + 1, i.ub());\n    } else if (i.ub() == *c) {\n      return z_interval(i.lb(), *c - 1);\n    } else {\n    }\n  }\n  return i;\n}\n\ntemplate <> 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\ntemplate <>\ninline z_interval lower_half_line(z_interval i, bool /*is_signed*/) {\n  return i.lower_half_line();\n}\n\ntemplate <>\ninline q_interval lower_half_line(q_interval i, bool /*is_signed*/) {\n  return i.lower_half_line();\n}\n\ntemplate <>\ninline z_interval upper_half_line(z_interval i, bool /*is_signed*/) {\n  return i.upper_half_line();\n}\n\ntemplate <>\ninline 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} // namespace ikos\n", "meta": {"hexsha": "41a95d85a028134de49298ea83f8dd436124756c", "size": 22685, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/crab/domains/interval.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/interval.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/interval.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": 24.9834801762, "max_line_length": 80, "alphanum_fraction": 0.5749614283, "num_tokens": 6539, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300048, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.4630600070539784}}
{"text": "#ifndef ROSE499_SYLVESTERCONTROL_HPP\n#define ROSE499_SYLVESTERCONTROL_HPP\n\n#include <Eigen/Core>\n#include \"rose499/diffdrive.hpp\"\n#include \"rose499/spline.hpp\"\n\nstruct SylvesterController : public DriveController\n{\n    SylvesterController(DriveSystem&, Eigen::Matrix<ValueType, 2, 1> goal, ValueType goalRadius);\n    virtual DriveController::ValueType genTurnControl(DriveController::StateType x, double t) override;\n\n    Eigen::Matrix<DriveController::ValueType, 2, 1> const & linearizedState() const;\n\nprotected:\n    std::ostream& printSpecificHeaders(std::ostream& s) const override;\n    std::ostream& printSpecificData(std::ostream& s) const override;\n\nprivate:\n    Eigen::Matrix<DriveController::ValueType, 2, 1> mXi;\n};\n\nEigen::Matrix<SimulatorTypes::ValueType, 2, 2> quinticHessian(  SimulatorTypes::ValueType A1,\n                                                                SimulatorTypes::ValueType A2,\n                                                                SimulatorTypes::ValueType A3,\n                                                                SimulatorTypes::ValueType A4,\n                                                                SimulatorTypes::ValueType A5,\n                                                                SimulatorTypes::ValueType A6,\n                                                                SimulatorTypes::ValueType B1,\n                                                                SimulatorTypes::ValueType B2,\n                                                                SimulatorTypes::ValueType B3,\n                                                                SimulatorTypes::ValueType B4,\n                                                                SimulatorTypes::ValueType B5,\n                                                                SimulatorTypes::ValueType B6,\n                                                                SimulatorTypes::ValueType x1,\n                                                                SimulatorTypes::ValueType x2 );\n\nEigen::Matrix<SimulatorTypes::ValueType, 1, 2> quinticJacobian( SimulatorTypes::ValueType A1,\n                                                                SimulatorTypes::ValueType A2,\n                                                                SimulatorTypes::ValueType A3,\n                                                                SimulatorTypes::ValueType A4,\n                                                                SimulatorTypes::ValueType A5,\n                                                                SimulatorTypes::ValueType A6,\n                                                                SimulatorTypes::ValueType B1,\n                                                                SimulatorTypes::ValueType B2,\n                                                                SimulatorTypes::ValueType B3,\n                                                                SimulatorTypes::ValueType B4,\n                                                                SimulatorTypes::ValueType B5,\n                                                                SimulatorTypes::ValueType B6,\n                                                                SimulatorTypes::ValueType x1,\n                                                                SimulatorTypes::ValueType x2 );\n\nSimulatorTypes::ValueType                      quinticLevelSet( SimulatorTypes::ValueType A1,\n                                                                SimulatorTypes::ValueType A2,\n                                                                SimulatorTypes::ValueType A3,\n                                                                SimulatorTypes::ValueType A4,\n                                                                SimulatorTypes::ValueType A5,\n                                                                SimulatorTypes::ValueType A6,\n                                                                SimulatorTypes::ValueType B1,\n                                                                SimulatorTypes::ValueType B2,\n                                                                SimulatorTypes::ValueType B3,\n                                                                SimulatorTypes::ValueType B4,\n                                                                SimulatorTypes::ValueType B5,\n                                                                SimulatorTypes::ValueType B6,\n                                                                SimulatorTypes::ValueType x1,\n                                                                SimulatorTypes::ValueType x2 );\n#endif\n", "meta": {"hexsha": "1196bccdf1c2e446787c8bfaefa891a7410d6cc6", "size": 4690, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "simulator/include/rose499/sylvester.hpp", "max_stars_repo_name": "rollends/SE499", "max_stars_repo_head_hexsha": "949b9cc85abe558b84289d906b730605c2f32c3b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "simulator/include/rose499/sylvester.hpp", "max_issues_repo_name": "rollends/SE499", "max_issues_repo_head_hexsha": "949b9cc85abe558b84289d906b730605c2f32c3b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "simulator/include/rose499/sylvester.hpp", "max_forks_repo_name": "rollends/SE499", "max_forks_repo_head_hexsha": "949b9cc85abe558b84289d906b730605c2f32c3b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 68.9705882353, "max_line_length": 103, "alphanum_fraction": 0.3744136461, "num_tokens": 573, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585903489891, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.4630600043588331}}
{"text": "//\n//  Copyright (c) 2018, Cem Bassoy, cem.bassoy@gmail.com\n//  Copyright (c) 2019, Amit Singh, amitsingh19975@gmail.com\n//\n//  Distributed under the Boost Software License, Version 1.0. (See\n//  accompanying file LICENSE_1_0.txt or copy at\n//  http://www.boost.org/LICENSE_1_0.txt)\n//\n//  The authors gratefully acknowledge the support of\n//  Google and Fraunhofer IOSB, Ettlingen, Germany\n//\n//  And we acknowledge the support from all contributors.\n\n\n#include <iostream>\n#include <algorithm>\n#include <boost/numeric/ublas/tensor.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n\n#include <boost/test/unit_test.hpp>\n\n#include \"utility.hpp\"\n\n// BOOST_AUTO_TEST_SUITE ( test_tensor_functions, * boost::unit_test::depends_on(\"test_tensor_contraction\") )\nBOOST_AUTO_TEST_SUITE ( test_tensor_extents_static_size_functions)\n\n\nusing test_types = zip<int,float,std::complex<float>>::with_t<boost::numeric::ublas::layout::first_order, boost::numeric::ublas::layout::last_order>;\n\n//using test_types = zip<int>::with_t<boost::numeric::ublas::layout::first_order>;\n\n\nstruct fixture\n{\n  std::tuple<\n    boost::numeric::ublas::extents<2>,\n    boost::numeric::ublas::extents<2>,\n    boost::numeric::ublas::extents<3>,\n    boost::numeric::ublas::extents<3>,\n    boost::numeric::ublas::extents<4>\n    > extents_tuple{\n      {1,1}, // 1\n      {2,3}, // 2\n      {2,3,1}, // 3\n      {4,2,3}, // 4\n      {4,2,3,5} // 5\n    };\n\n\n  std::vector<boost::numeric::ublas::extents<>> extents_vector =\n    {\n      {1,1}, // 1\n      {2,3}, // 2\n      {2,3,1}, // 3\n      {4,2,3}, // 4\n      {4,2,3,5} // 5\n  };\n\n};\n\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_extents_static_size_prod_vector, value,  test_types, fixture )\n{\n  namespace ublas    = boost::numeric::ublas;\n  using value_t   = typename value::first_type;\n  using layout_t  = typename value::second_type;\n\n  for_each_in_tuple(extents_tuple,[](auto const& /*unused*/, auto const& n){\n\n    constexpr auto size = std::tuple_size_v<std::decay_t<decltype(n)>>;\n    using tensor_t = ublas::tensor_static_rank<value_t, size, layout_t>;\n    using vector_t = typename tensor_t::vector_type;\n    auto a = tensor_t(n);\n    a = 2;\n\n    for (auto m = 0u; m < ublas::size(n); ++m) {\n      auto b = vector_t(n[m], value_t{1});\n\n      auto c = ublas::prod(a, b, m + 1);\n\n      for (auto i = 0u; i < c.size(); ++i)\n        BOOST_CHECK_EQUAL(c[i], value_t( static_cast< inner_type_t<value_t> >(n[m]) ) * a[i]);\n    }\n  });\n\n}\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_extents_static_size_prod_matrix, value,  test_types, fixture )\n{\n  namespace ublas = boost::numeric::ublas;\n  using value_t   = typename value::first_type;\n  using layout_t  = typename value::second_type;\n\n  for_each_in_tuple(extents_tuple,[](auto const& /*unused*/, auto const & n){\n    constexpr auto size = std::tuple_size_v<std::decay_t<decltype(n)>>;\n    using tensor_t = ublas::tensor_static_rank<value_t, size, layout_t>;\n    using matrix_t = typename tensor_t::matrix_type;\n\n    auto a = tensor_t(n);\n    a = 2;\n    for (auto m = 0u; m < ublas::size(n); ++m) {\n\n      auto b = matrix_t  ( n[m], n[m], value_t{1} );\n      auto c = ublas::prod(a, b, m + 1);\n\n      for (auto i = 0u; i < c.size(); ++i){\n        BOOST_CHECK_EQUAL(c[i], value_t( static_cast< inner_type_t<value_t> >(n[m]) ) * a[i]);\n      }\n    }\n  });\n\n}\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_extents_static_size_prod_tensor_1, value,  test_types, fixture )\n{\n  namespace ublas = boost::numeric::ublas;\n  using value_t   = typename value::first_type;\n  using layout_t  = typename value::second_type;\n\n\n  auto check = [&]<std::size_t ... qs>(auto const& a, auto const& b, std::index_sequence<qs...> /*unused*/)\n  {\n    namespace ublas = boost::numeric::ublas;\n\n    constexpr auto q = sizeof...(qs);\n\n    using tensorA = std::decay_t<decltype(a)>;\n    using tensorB = std::decay_t<decltype(b)>;\n\n    using extentsA = typename tensorA::extents_type;\n    using extentsB = typename tensorB::extents_type;\n\n    static_assert(!ublas::is_static_v<extentsA> && !ublas::is_static_v<extentsB> );\n\n    constexpr auto one_of_extents_is_resizable = ublas::is_dynamic_rank_v<extentsA> ||\n                                                 ublas::is_dynamic_rank_v<extentsB>;\n\n    using phi_type = std::conditional_t<one_of_extents_is_resizable,\n                                        std::vector<std::size_t>,\n                                        std::array<std::size_t,q> >;\n\n    auto phi = phi_type{};\n    if constexpr(std::is_same_v<phi_type,std::vector<std::size_t>>){\n      phi.resize(q);\n    }\n    std::iota(phi.begin(), phi.end(), std::size_t{1});\n    auto c = ublas::prod(a, b, phi);\n\n    auto const& na = a.extents();\n    auto acc = std::size_t{1};\n    for (auto i = 0ul; i < q; ++i){      \n      acc *= na.at(phi.at(i)-1);\n    }\n    const auto v = value_t(acc) * a[0] * b[0];\n    BOOST_CHECK( std::all_of(c.begin(),c.end(),[v](auto cc){ return cc == v;}));\n  };\n\n\n  for_each_in_tuple(extents_tuple,[&](auto const& /*I*/, auto const& n){\n    constexpr auto size = std::tuple_size_v<std::decay_t<decltype(n)>>;\n    constexpr auto modes = std::make_index_sequence<size>{};\n    using tensor_t = ublas::tensor_static_rank<value_t, size, layout_t>;\n    auto a = tensor_t(n);\n    auto b = tensor_t(n);\n    a = 2;\n    b = 3;\n    for_each_in_index(modes, a,b, check );\n  });\n\n  for_each_in_tuple(extents_tuple,[&](auto const& I, auto const& n){\n    auto const& nA = n;\n    auto const& nB = extents_vector[I];\n    constexpr auto sizeA = std::tuple_size_v<std::decay_t<decltype(n)>>;\n    constexpr auto modes = std::make_index_sequence<sizeA>{};\n    using tensorA_type = ublas::tensor_static_rank<value_t, sizeA , layout_t>;\n    using tensorB_type = ublas::tensor_dynamic<value_t, layout_t>;\n    auto a = tensorA_type(nA);\n    auto b = tensorB_type(nB);\n    a = 2;\n    b = 3;\n\n    for_each_in_index(modes, a,b, check );\n  });\n\n  for_each_in_tuple(extents_tuple,[&](auto const& I, auto const& n){\n    auto const& nA = extents_vector[I];\n    auto const& nB = n;\n    constexpr auto sizeB = std::tuple_size_v<std::decay_t<decltype(n)>>;\n    constexpr auto modes = std::make_index_sequence<sizeB>{};\n    using tensor_t_1 = ublas::tensor_dynamic<value_t, layout_t>;\n    using tensor_t_2 = ublas::tensor_static_rank<value_t, sizeB, layout_t>;\n    auto a = tensor_t_1(nA);\n    auto b = tensor_t_2(nB);\n    a = 2;\n    b = 3;\n    for_each_in_index(modes, a,b, check );\n\n  });\n}\n\n// TODO:\n#if 0\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_extents_static_size_prod_tensor_2, value,  test_types, fixture )\n{\n  namespace ublas = boost::numeric::ublas;\n  using value_t   = typename value::first_type;\n  using layout_t  = typename value::second_type;\n\n  constexpr auto to_array = []<std::size_t ... is>(std::index_sequence<is...>/*unused*/) {\n    return std::array<std::size_t,sizeof...(is)>{is...};\n  };\n\n  auto compute_factorial = []<std::size_t ... is>(std::index_sequence<is...>/*unused*/) {\n    return ( 1 * ... * is );\n  };\n  /*\n  auto compute_factorial = [](auto const& p){\n    auto f = 1ul;\n    for(auto i = 1u; i <= p; ++i)\n      f *= i;\n    return f;\n  };\n*/\n  auto permute_extents_dynamic_rank = [](auto const& pi, auto const& na){\n    auto nb = ublas::extents<>(na.begin(),na.end());\n    assert(std::size(pi) == ublas::size(na));\n    for(auto j = 0u; j < std::size(pi); ++j)\n      nb[pi[j]-1] = na[j];\n    return nb;\n  };\n\n  auto permute_extents_static_rank = []<std::size_t size>(std::array<std::size_t,size> const& pi, auto const& na){\n    //constexpr auto size = std::tuple_size_v<std::decay_t<decltype(na)>>;\n    auto na_base = na.base();\n    assert(std::size(pi) == size);\n    for(auto j = 0u; j < std::size(pi); ++j)\n      na_base[pi[j]-1] = na[j];\n    return ublas::extents<size>(na_base.begin(),na_base.end());\n  };\n\n  for_each_in_tuple(extents_tuple,[&](auto const& /*unused*/, auto const& n){\n    auto const& na = n;\n    constexpr auto size = std::tuple_size_v<std::decay_t<decltype(n)>>;\n    using tensorA_type = ublas::tensor_static_rank<value_t, size, layout_t>;\n    auto a = tensorA_type(na);\n    a = 2;\n    assert(a.rank() == size);\n    //    auto const pa = a.rank();\n    auto pi  = to_array(std::make_index_sequence<size>{});\n    constexpr auto factorial = compute_factorial(std::make_index_sequence<size>{});\n    //    auto pi = std::vector<std::size_t>(pa);\n    //    auto fac = compute_factorial(pa);\n    //    std::iota(pi.begin(), pi.end(), 1);\n\n    constexpr auto factorials = std::make_index_sequence<factorial>{};\n\n    //    for_each_in_tuple(factorials,[&](auto const& /*unused*/, auto const& /*unused*/){\n    //      using tensorB_type = ublas::tensor_dynamic<value_t, layout_t>;\n    //      const auto nb = permute_extents_dynamic_rank(pi, na);\n    //      const auto b = tensorB_type(nb, value_t{3});\n\n    //      constexpr auto modes  = std::make_index_sequence<size>{};\n\n    //      for_each_in_tuple(modes,[&](auto const& /*unused*/, auto const& /*unused*/){\n\n\n    //      const auto phia = to_array(std::make_index_sequence<Q>);\n    //      const auto phib = std::array<std::size_t>(q);\n\n    //    });\n\n    //    for (auto f = 0ul; f < fac; ++f) {\n    //      for (auto q = 0ul; q <= pa; ++q) {\n\n    //        auto phia = std::vector<std::size_t>(q);\n    //        auto phib = std::vector<std::size_t>(q);\n\n    //        std::iota(phia.begin(), phia.end(), 1ul);\n    //        std::transform(phia.begin(), phia.end(), phib.begin(),\n    //                       [&pi](std::size_t i) { return pi.at(i - 1); });\n\n    //        auto c = ublas::prod(a, b, phia, phib);\n\n    //        auto acc = value_t(1);\n    //        for (auto i = 0ul; i < q; ++i)\n    //          acc *= value_t( static_cast< inner_type_t<value_t> >( a.extents().at(phia.at(i) - 1) ) );\n\n    //        for (auto i = 0ul; i < c.size(); ++i)\n    //          BOOST_CHECK_EQUAL(c[i], acc *a[0] * b[0]);\n    //      }\n\n    //      std::next_permutation(pi.begin(), pi.end());\n    //    }\n  });\n\n  for_each_in_tuple(extents_tuple,[&](auto const& /*unused*/, auto & /*n*/){\n    //    auto const& na = n;\n    //    constexpr auto size = std::tuple_size_v<std::decay_t<decltype(n)>>;\n    //    using tensor_t_1 = ublas::tensor_static_rank<value_t, size, layout_t>;\n    //    auto a = tensor_t_1(na, value_t{2});\n    //    auto const pa = a.rank();\n\n    //    auto pi = std::vector<std::size_t>(pa);\n    //    auto fac = compute_factorial(pa);\n    //    std::iota(pi.begin(), pi.end(), 1);\n\n    //    for (auto f = 0ul; f < fac; ++f) {\n    //      auto nb = permute_extents_static_rank(pi, na);\n\n    //      using tensor_t_2 = ublas::tensor_static_rank<value_t, size, layout_t>;\n    //      auto b = tensor_t_2(nb, value_t{3});\n\n    //      for (auto q = 0ul; q <= pa; ++q) {\n\n    //        auto phia = std::vector<std::size_t>(q);\n    //        auto phib = std::vector<std::size_t>(q);\n\n    //        std::iota(phia.begin(), phia.end(), 1ul);\n    //        std::transform(phia.begin(), phia.end(), phib.begin(),\n    //                       [&pi](std::size_t i) { return pi.at(i - 1); });\n\n    //        auto c = ublas::prod(a, b, phia, phib);\n\n    //        auto acc = value_t(1);\n    //        for (auto i = 0ul; i < q; ++i){\n    //          acc *= value_t( static_cast< inner_type_t<value_t> >( a.extents().at(phia.at(i) - 1) ) );\n    //        }\n\n    //        for (auto i = 0ul; i < c.size(); ++i)\n    //          BOOST_CHECK_EQUAL(c[i], acc *a[0] * b[0]);\n    //      }\n\n    //      std::next_permutation(pi.begin(), pi.end());\n    //    }\n  });\n\n}\n#endif\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_extents_static_size_inner_prod, value,  test_types, fixture )\n{\n  namespace ublas = boost::numeric::ublas;\n  using value_t   = typename value::first_type;\n  using layout_t  = typename value::second_type;\n\n\n  using dtensor_t = ublas::tensor_dynamic<value_t, layout_t>;\n\n  auto const body = [&](auto const& a, auto const& b){\n    auto c = ublas::inner_prod(a, b);\n    auto r = std::inner_product(a.begin(),a.end(), b.begin(),value_t(0));\n    BOOST_CHECK_EQUAL( c , r );\n  };\n\n  for_each_in_tuple(extents_tuple,[&](auto const& /*unused*/, auto & n){\n    constexpr auto size = std::tuple_size_v<std::decay_t<decltype(n)>>;\n    using stensor_t = ublas::tensor_static_rank<value_t, size, layout_t>;\n    auto a  = stensor_t(n);\n    auto b  = stensor_t(n);\n    a = 2;\n    b = 3;\n    body(a,b);\n\n  });\n\n  for_each_in_tuple(extents_tuple,[&](auto const& I, auto & n){\n    constexpr auto size = std::tuple_size_v<std::decay_t<decltype(n)>>;\n    using stensor_t = ublas::tensor_static_rank<value_t, size, layout_t>;\n    auto a  = stensor_t(n);\n    auto b  = dtensor_t(extents_vector[I]);\n    a = 2;\n    b = 1;\n\n    body(a,b);\n\n  });\n\n  for_each_in_tuple(extents_tuple,[&](auto const& I, auto & n){\n    constexpr auto size = std::tuple_size_v<std::decay_t<decltype(n)>>;\n    using stensor_t = ublas::tensor_static_rank<value_t, size, layout_t>;\n    auto a  = dtensor_t(extents_vector[I]);\n    auto b  = stensor_t(n);\n    a = 2;\n    b = 1;\n    body(a,b);\n\n  });\n\n}\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_extents_static_size_outer_prod, value,  test_types, fixture )\n{\n  namespace ublas = boost::numeric::ublas;\n  using value_t   = typename value::first_type;\n  using layout_t  = typename value::second_type;\n\n  for_each_in_tuple(extents_tuple,[&](auto const& /*unused*/, auto const& n1){\n    constexpr auto size1 = std::tuple_size_v<std::decay_t<decltype(n1)>>;\n    using tensor_t_1 = ublas::tensor_static_rank<value_t, size1, layout_t>;\n    auto a  = tensor_t_1(n1);\n    a = 2;\n    for_each_in_tuple(extents_tuple,[&](auto const& /*J*/, auto const& n2){\n      constexpr auto size2 = std::tuple_size_v<std::decay_t<decltype(n2)>>;\n      using tensor_t_2 = ublas::tensor_static_rank<value_t, size2, layout_t>;\n      auto b  = tensor_t_2(n2);\n      b = 1;\n      auto c  = ublas::outer_prod(a, b);\n\n      BOOST_CHECK ( std::all_of(c.begin(),c.end(), [&a,&b](auto cc){return cc == a[0]*b[0];}) );\n\n    });\n\n  });\n\n  for_each_in_tuple(extents_tuple,[&](auto const& I, auto const& /*n1*/){\n    using tensor_t_1 = ublas::tensor_dynamic<value_t, layout_t>;\n    auto a  = tensor_t_1(extents_vector[I]);\n    a = 2;\n    for_each_in_tuple(extents_tuple,[&](auto const& /*J*/, auto const& n2){\n      constexpr auto size = std::tuple_size_v<std::decay_t<decltype(n2)>>;\n      using tensor_t_2 = ublas::tensor_static_rank<value_t, size, layout_t>;\n      auto b  = tensor_t_2(n2);\n      b = 1;\n      auto c  = ublas::outer_prod(a, b);\n      BOOST_CHECK ( std::all_of(c.begin(),c.end(), [&a,&b](auto cc){return cc == a[0]*b[0];}) );\n\n\n//      for(auto const& cc : c)\n//        BOOST_CHECK_EQUAL( cc , a[0]*b[0] );\n    });\n\n  });\n\n  for_each_in_tuple(extents_tuple,[&](auto const& /*unused*/, auto const& n1){\n    constexpr auto size = std::tuple_size_v<std::decay_t<decltype(n1)>>;\n    using tensor_t_1 = ublas::tensor_static_rank<value_t, size, layout_t>;\n    auto a  = tensor_t_1(n1);\n    a = 2;\n    for(auto const& n2 : extents_vector){\n      using tensor_t_2 = ublas::tensor_dynamic<value_t, layout_t>;\n      auto b  = tensor_t_2(n2);\n      b = 1;\n      auto c  = ublas::outer_prod(a, b);\n\n      BOOST_CHECK ( std::all_of(c.begin(),c.end(), [&a,&b](auto cc){return cc == a[0]*b[0];}) );\n\n//      for(auto const& cc : c)\n//        BOOST_CHECK_EQUAL( cc , a[0]*b[0] );\n    }\n\n  });\n\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "df3d4ce80d55937c1baed77bfac9cdfa8442593f", "size": 15394, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/tensor/test_fixed_rank_functions.cpp", "max_stars_repo_name": "samd2/ublas", "max_stars_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 96.0, "max_stars_repo_stars_event_min_datetime": "2015-01-23T10:15:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T18:31:02.000Z", "max_issues_repo_path": "test/tensor/test_fixed_rank_functions.cpp", "max_issues_repo_name": "samd2/ublas", "max_issues_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 105.0, "max_issues_repo_issues_event_min_datetime": "2015-01-14T09:01:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-05T06:10:39.000Z", "max_forks_repo_path": "test/tensor/test_fixed_rank_functions.cpp", "max_forks_repo_name": "samd2/ublas", "max_forks_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 157.0, "max_forks_repo_forks_event_min_datetime": "2015-01-26T13:35:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T11:12:27.000Z", "avg_line_length": 33.3926247289, "max_line_length": 149, "alphanum_fraction": 0.6080940626, "num_tokens": 4618, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.4630599969359084}}
{"text": "/**\n * @file Optimizer.cpp\n * @brief Class implementing batch and incremental nonlinear equation solvers.\n * @author David Rosen\n * @author Michael Kaess\n * @version $Id: Optimizer.cpp 6371 2012-03-29 22:22:23Z kaess $\n *\n * Copyright (C) 2009-2013 Massachusetts Institute of Technology.\n * Michael Kaess, Hordur Johannsson, David Rosen,\n * Nicholas Carlevaris-Bianco and John. J. Leonard\n *\n * This file is part of iSAM.\n *\n * iSAM is free software; you can redistribute it and/or modify it under\n * the terms of the GNU Lesser General Public License as published by the\n * Free Software Foundation; either version 2.1 of the License, or (at\n * your option) any later version.\n *\n * iSAM is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public\n * License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with iSAM.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#include <Eigen/Dense>\n\n#include \"isam/Optimizer.h\"\n#include \"isam/OptimizationInterface.h\"\n\nusing namespace std;\nusing namespace Eigen;\n#include \"iostream\"\nnamespace isam {\n\n/* Use Powell's Dog-Leg stopping criteria for all of the batch algorithms? */\n// #define USE_PDL_STOPPING_CRITERIA\n\nvoid Optimizer::permute_vector(const VectorXd& v, VectorXd& p,\n    const int* permutation) {\n  for (int i = 0; i < v.size(); i++) {\n    p(permutation[i]) = v(i);\n  }\n}\n\nVectorXd Optimizer::compute_gauss_newton_step(const SparseSystem& jacobian,\n    SparseSystem* R, double lambda) {\n  VectorXd delta_ordered;\n  \n//   std::cout<<\"come here !!\"<<jacobian<<std::endl;\n  \n  \n  _cholesky->factorize(jacobian, &delta_ordered, lambda);\n  if (R != NULL) {\n    _cholesky->get_R(*R);\n  }\n\n  // delta has new ordering, need to return result with default ordering\n  int nrows = delta_ordered.size();\n  VectorXd delta(nrows);\n  permute_vector(delta_ordered, delta, _cholesky->get_order());\n\n  return delta;\n}\n\nVectorXd Optimizer::compute_dog_leg(double alpha, const VectorXd& h_sd,\n    const VectorXd& h_gn, double delta, double& gain_ratio_denominator) {\n  if (h_gn.norm() <= delta) {\n    gain_ratio_denominator = current_SSE_at_linpoint;\n    return h_gn;\n  }\n\n  double h_sd_norm = h_sd.norm();\n\n  if ((alpha * h_sd_norm) >= delta) {\n    gain_ratio_denominator = delta * (2 * alpha * h_sd_norm - delta)\n        / (2 * alpha);\n    return (delta / h_sd_norm) * h_sd;\n  } else {\n    // complicated case: calculate intersection of trust region with\n    // line between Gauss-Newton and steepest descent solutions\n    VectorXd a = alpha * h_sd;\n    VectorXd b = h_gn;\n    double c = a.dot(b - a);\n    double b_a_norm2 = (b - a).squaredNorm();\n    double a_norm2 = a.squaredNorm();\n    double delta2 = delta * delta;\n    double sqrt_term = sqrt(c * c + b_a_norm2 * (delta2 - a_norm2));\n    double beta;\n    if (c <= 0) {\n      beta = (-c + sqrt_term) / b_a_norm2;\n    } else {\n      beta = (delta2 - a_norm2) / (c + sqrt_term);\n    }\n\n    gain_ratio_denominator = .5 * alpha * (1 - beta) * (1 - beta) * h_sd_norm\n        * h_sd_norm + beta * (2 - beta) * current_SSE_at_linpoint;\n    return (alpha * h_sd + beta * (h_gn - alpha * h_sd));\n  }\n}\n\nvoid Optimizer::update_trust_radius(double rho, double hdl_norm) {\n  if (rho < .25) {\n    Delta /= 2.0;\n  }\n  if (rho > .75) {\n    Delta = max(Delta, 3 * hdl_norm);\n  }\n}\n\nvoid Optimizer::relinearize(const Properties& prop) {\n  // We're going to relinearize about the current estimate.\n  function_system.estimate_to_linpoint();\n\n  // prepare factorization\n  SparseSystem jac = function_system.jacobian();\n\n  // factorization and new rhs based on new linearization point will be in _R\n  VectorXd h_gn = compute_gauss_newton_step(jac, &function_system._R); // modifies _R\n\n  if (prop.method == DOG_LEG) {\n    // Compute the gradient and cache it.\n    gradient = mul_SparseMatrixTrans_Vector(jac, jac.rhs());\n\n    //Get the value of the sum-of-squared errors at the current linearization point.\n    current_SSE_at_linpoint = jac.rhs().squaredNorm();\n\n    // NB: alpha's denominator will be zero iff the gradient vector is zero\n    // (since J is full-rank by hypothesis).  But the gradient is zero iff\n    // we're already at the minimum, so we don't actually need to to any\n    // updates; just set the estimate to be the current linearization point,\n    // since we're already at the minimum.\n\n    double alpha_denominator = (jac * gradient).squaredNorm();\n\n    if (alpha_denominator > 0) {\n      double alpha_numerator = gradient.squaredNorm();\n      double alpha = alpha_numerator / alpha_denominator;\n\n      // These values will be used to update the estimate of Delta\n      double F_0, F_h;\n\n      F_0 = current_SSE_at_linpoint;\n\n      double rho_denominator, rho;\n\n      VectorXd h_dl;\n\n      do {\n        // We repeat the computation of the dog-leg step, shrinking the\n        // trust-region radius if necessary, until we generate a sufficiently\n        // small region of trust that we accept the proposed step.\n\n        // Compute dog-leg step.\n        // NOTE: Here we use -h_gn because of the weird sign change in the exmap functions.\n        h_dl = compute_dog_leg(alpha, -gradient, -h_gn, Delta, rho_denominator);\n\n        // Update the estimate.\n        // NOTE:  Here we use -h_dl because of the weird sign change in the exmap functions.\n        function_system.apply_exmap(-h_dl);\n\n        // Get the value of the sum-of-squared errors at the new estimate.\n        F_h = function_system.weighted_errors(ESTIMATE).squaredNorm();\n\n        // Compute gain ratio.\n        rho = (F_0 - F_h) / (rho_denominator);\n\n        update_trust_radius(rho, h_dl.norm());\n      } while (rho < 0);\n\n      // Cache last accepted dog-leg step\n      last_accepted_hdl = h_dl;\n    } else {\n      function_system.linpoint_to_estimate();\n      last_accepted_hdl = VectorXd::Zero(gradient.size());\n    }\n\n  } else {\n    // For Gauss-Newton just apply the update directly.\n    function_system.apply_exmap(h_gn);\n  }\n}\n\nbool Optimizer::powells_dog_leg_update(double epsilon1, double epsilon3,\n    SparseSystem& jacobian, VectorXd& f_x, VectorXd& grad) {\n  jacobian = function_system.jacobian();\n  f_x = function_system.weighted_errors(LINPOINT);\n  grad = mul_SparseMatrixTrans_Vector(jacobian, f_x);\n  return (f_x.lpNorm<Eigen::Infinity>() <= epsilon3)\n      || (grad.lpNorm<Eigen::Infinity>() <= epsilon1);\n}\n\nvoid Optimizer::augment_sparse_linear_system(SparseSystem& W,\n    const Properties& prop) {\n  if (prop.method == DOG_LEG) {\n    // We're using the incremental version of Powell's Dog-Leg, so we need\n    // to form the updated gradient.\n    const VectorXd& f_new = W.rhs();\n\n    // Augment the running count for the sum-of-squared errors at the current\n    // linearization point.\n    current_SSE_at_linpoint += f_new.squaredNorm();\n\n    // Allocate the new gradient vector\n    VectorXd g_new(W.num_cols());\n\n    // Compute W^T \\cdot f_new\n    VectorXd increment = mul_SparseMatrixTrans_Vector(W, f_new);\n\n    // Set g_new = (g_old 0)^T + W^T f_new.\n    g_new.head(gradient.size()) = gradient + increment.head(gradient.size());\n    g_new.tail(W.num_cols() - gradient.size()) = increment.tail(\n        W.num_cols() - gradient.size());\n\n    // Cache the new gradient vector\n    gradient = g_new;\n  }\n\n  // Apply Givens to QR factorize the newly augmented sparse system.\n  for (int i = 0; i < W.num_rows(); i++) {\n    SparseVector new_row = W.get_row(i);\n    function_system._R.add_row_givens(new_row, W.rhs()(i));\n  }\n}\n\nvoid Optimizer::update_estimate(const Properties& prop) {\n  // Solve for the Gauss-Newton step.\n  VectorXd h_gn_reordered = function_system._R.solve();\n\n  // permute from R-ordering to J-ordering\n  VectorXd h_gn(h_gn_reordered.size());\n  permute_vector(h_gn_reordered, h_gn, function_system._R.r_to_a());\n\n  if (prop.method == GAUSS_NEWTON) {\n    function_system.apply_exmap(h_gn);\n  } else { //method == DOG_LEG\n    // Compute alpha.  Note that since the variable ordering of the factor\n    // R differs from that of the original Jacobian J,\n    // we must first rearrange the ordering of the elements in the gradient.\n    VectorXd reordered_gradient(gradient.size());\n\n    // Permute from J-ordering to R-ordering\n    permute_vector(gradient, reordered_gradient, function_system._R.a_to_r());\n\n    double alpha_denominator =\n        (function_system._R * reordered_gradient).squaredNorm();\n\n    if (alpha_denominator > 0) {\n      double alpha = (gradient.squaredNorm()) / alpha_denominator;\n\n      double rho_denominator;\n\n      VectorXd h_dl = compute_dog_leg(alpha, -gradient, -h_gn, Delta,\n          rho_denominator);\n      function_system.apply_exmap(-h_dl);\n\n      // Compute the gain ratio\n      double rho = (current_SSE_at_linpoint\n          - function_system.weighted_errors(ESTIMATE).squaredNorm())\n          / rho_denominator;\n\n      update_trust_radius(rho, h_dl.norm());\n\n      if (rho < 0) {\n        // The proposed update actually /increased/ the value of the\n        // objective function; restore the last good estimate that we had\n        VectorXd restore_step(gradient.size());\n        restore_step.head(last_accepted_hdl.size()) = last_accepted_hdl;\n        restore_step.tail(gradient.size() - last_accepted_hdl.size()).setZero();\n\n        function_system.apply_exmap(-restore_step);\n      } else {\n        // The proposed update was accepted; cache the dog-leg step used\n        // to produce it.\n        last_accepted_hdl = h_dl;\n      }\n    }\n\n    // NOTE:  The negatives prepended to \"compute_dog_leg()\" and \"h_gn\"\n    // are due to the weird sign change in the exmap functions.\n  }\n}\n\nvoid Optimizer::gauss_newton(const Properties& prop, int* num_iterations) {\n  // Batch optimization\n  int num_iter = 0;\n  \n  // Set the new linearization point to be the current estimate.\n  function_system.estimate_to_linpoint();\n  \n  // Compute Jacobian about current estimate.\n  SparseSystem jacobian = function_system.jacobian();\n\n  // Get the current error residual vector\n  VectorXd r = function_system.weighted_errors(LINPOINT);\n  \n#ifdef USE_PDL_STOPPING_CRITERIA\n  // Compute the current gradient direction vector\n  VectorXd g = mul_SparseMatrixTrans_Vector(jacobian, r);\n#else\n  double error = r.squaredNorm();\n  double error_new;\n  // We haven't computed a step yet, so this initialization is to ensure\n  // that we never skip over the while loop as a result of failing\n  // change-in-error check.\n  double error_diff = prop.epsilon_rel * error + 1;\n#endif\n\n  // Compute Gauss-Newton step h_{gn} to get to the next estimated optimizing point.\n  VectorXd delta = compute_gauss_newton_step(jacobian);  \n  while (\n  // We ALWAYS use these criteria\n  ((prop.max_iterations <= 0) || (num_iter < prop.max_iterations))\n      && (delta.norm() > prop.epsilon2)\n\n#ifdef USE_PDL_STOPPING_CRITERIA\n      && (r.lpNorm<Eigen::Infinity>() > prop.epsilon3)\n      && (g.lpNorm<Eigen::Infinity>() > prop.epsilon1)\n\n#else // Custom stopping criteria for GN\n      && (error > prop.epsilon_abs)\n      && (fabs(error_diff) > prop.epsilon_rel * error)\n#endif\n\n  ) // end while conditional\n  {\n    num_iter++;\n    // Apply the Gauss-Newton step h_{gn} to...\n    function_system.apply_exmap(delta);\n    // ...set the new linearization point to be the current estimate.\n    function_system.estimate_to_linpoint();\n    // Relinearize about the new current estimate.\n    jacobian = function_system.jacobian();\n    // Compute the error residual vector at the new estimate.\n    r = function_system.weighted_errors(LINPOINT);\n\n#ifdef USE_PDL_STOPPING_CRITERIA\n    g = mul_SparseMatrixTrans_Vector(jacobian, r);\n#else\n    // Update the error difference in errors between the previous and\n    // current estimates.\n    error_new = r.squaredNorm();\n    error_diff = error - error_new;\n    error = error_new;  // Record the absolute error at the current estimate\n#endif\n\n    // Compute Gauss-Newton step h_{gn} to get to the next estimated\n    // optimizing point.\n    delta = compute_gauss_newton_step(jacobian);\n    if (!prop.quiet) {\n      cout << \"Iteration \" << num_iter << \": residual \";\n\n#ifdef USE_PDL_STOPPING_CRITERIA\n      cout << r.squaredNorm();\n#else\n      cout << error;\n#endif\n      cout << endl;\n    }\n  }  //end while\n\n  if (num_iterations != NULL) {\n    *num_iterations = num_iter;\n  }\n  _cholesky->get_R(function_system._R);\n}\n\nvoid Optimizer::levenberg_marquardt(const Properties& prop,\n    int* num_iterations) {\n  int num_iter = 0;\n  double lambda = prop.lm_lambda0;\n  // Using linpoint as current estimate below.\n  function_system.estimate_to_linpoint();\n\n  // Get the current Jacobian at the linearization point.\n  SparseSystem jacobian = function_system.jacobian();\n\n  // Get the error residual vector at the current linearization point.\n  VectorXd r = function_system.weighted_errors(LINPOINT);\n\n  // Record the absolute sum-of-squares error (i.e., objective function value) here.\n  double error = r.squaredNorm();\n\n#ifdef USE_PDL_STOPPING_CRITERIA\n  // Compute the gradient direction vector at the current linearization point\n  VectorXd g = mul_SparseMatrixTrans_Vector(jacobian, r);\n#endif\n\n  double error_diff, error_new;\n\n  // solve at J'J + lambda*diag(J'J)\n  VectorXd delta = compute_gauss_newton_step(jacobian, &function_system._R,\n      lambda);\n\n  while (\n  // We ALWAYS use these stopping criteria\n  ((prop.max_iterations <= 0) || (num_iter < prop.max_iterations))\n      && (delta.norm() > prop.epsilon2)\n\n#ifdef USE_PDL_STOPPING_CRITERIA\n      && (r.lpNorm<Eigen::Infinity>() > prop.epsilon3)\n      && (g.lpNorm<Eigen::Infinity>() > prop.epsilon1)\n#else\n      && (error > prop.epsilon_abs)\n#endif\n  )  // end while conditional\n  {\n    num_iter++;\n\n    // remember the last accepted linearization point\n    function_system.linpoint_to_estimate();\n    // Apply the delta vector DIRECTLY TO THE LINEARIZATION POINT!\n    function_system.self_exmap(delta);\n    error_new = function_system.weighted_errors(LINPOINT).squaredNorm();\n    error_diff = error - error_new;\n    // feedback\n    if (!prop.quiet) {\n      cout << \"LM Iteration \" << num_iter << \": (lambda=\" << lambda << \") \";\n      if (error_diff > 0.) {\n        cout << \"residual: \" << error_new << endl;\n      } else {\n        cout << \"rejected\" << endl;\n      }\n    }\n    // decide if acceptable\n    if (error_diff > 0.) {\n\n#ifndef USE_PDL_STOPPING_CRITERIA\n      if (error_diff < prop.epsilon_rel * error) {\n        break;\n      }\n#endif\n\n      // Update lambda\n      lambda /= prop.lm_lambda_factor;\n\n      // Record the error at the newly-accepted estimate.\n      error = error_new;\n\n      // Relinearize around the newly-accepted estimate.\n      jacobian = function_system.jacobian();\n\n#ifdef USE_PDL_STOPPING_CRITERIA\n      r = function_system.weighted_errors(LINPOINT);\n      g = mul_SparseMatrixTrans_Vector(jacobian, r);\n#endif\n    } else {\n      // reject new estimate\n      lambda *= prop.lm_lambda_factor;\n      // restore previous estimate\n      function_system.estimate_to_linpoint();\n    }\n\n    // Compute the step for the next iteration.\n    delta = compute_gauss_newton_step(jacobian, &function_system._R, lambda);\n\n  } // end while\n\n  if (num_iterations != NULL) {\n    *num_iterations = num_iter;\n  }\n  // Copy current estimate contained in linpoint.\n  function_system.linpoint_to_estimate();\n}\n\nvoid Optimizer::powells_dog_leg(int* num_iterations, double delta0,\n    int max_iterations, double epsilon1, double epsilon2, double epsilon3) {\n  // Batch optimization\n  int num_iter = 0;\n  // current estimate is used as new linearization point\n  function_system.estimate_to_linpoint();\n\n  double delta = delta0;\n  SparseSystem jacobian(1, 1);\n  VectorXd f_x;\n  VectorXd grad;\n\n  bool found = powells_dog_leg_update(epsilon1, epsilon3, jacobian, f_x, grad);\n\n  double rho_denominator;\n\n  while ((not found) && (max_iterations == 0 || num_iter < max_iterations)) {\n    num_iter++;\n    cout << \"PDL Iteration \" << num_iter << \" residual: \" << f_x.squaredNorm()\n        << endl;\n    // compute alpha\n    double alpha = grad.squaredNorm() / (jacobian * grad).squaredNorm();\n    // steepest descent\n    VectorXd h_sd = -grad;\n    // solve Gauss Newton\n    VectorXd h_gn = compute_gauss_newton_step(jacobian, &function_system._R);\n    // compute dog leg h_dl\n    // x0 = x: remember (and return) linearization point of R\n    function_system.linpoint_to_estimate();\n    VectorXd h_dl = compute_dog_leg(alpha, h_sd, h_gn, delta, rho_denominator);\n    // Evaluate new solution, update estimate and trust region.\n    if (h_dl.norm() <= epsilon2) {\n      found = true;\n    } else {\n      // new estimate\n      // change linearization point directly (original LP saved in estimate)\n      function_system.self_exmap(h_dl);\n      // calculate gain ratio rho\n      VectorXd f_x_new = function_system.weighted_errors(LINPOINT);\n      double rho = (f_x.squaredNorm() - f_x_new.squaredNorm())\n          / (rho_denominator);\n      if (rho > 0) {\n        // accept new estimate\n        cout << \"accepted\" << endl;\n        f_x = f_x_new;\n        found = powells_dog_leg_update(epsilon1, epsilon3, jacobian, f_x, grad);\n      } else {\n        // reject new estimate, overwrite with last saved one\n        cout << \"rejected\" << endl;\n        function_system.estimate_to_linpoint();\n      }\n      if (rho > 0.75) {\n        delta = max(delta, 3.0 * h_dl.norm());\n      } else if (rho < 0.25) {\n        delta *= 0.5;\n        found = (delta <= epsilon2);\n      }\n    }\n  }\n  if (num_iterations) {\n    *num_iterations = num_iter;\n  }\n  // Overwrite potentially rejected linearization point with last saved one\n  // (could be identical if it was accepted in the last iteration).\n\n  function_system.swap_estimates();\n\n}\n\nvoid Optimizer::batch_optimize(const Properties& prop, int* num_iterations) {\n\n  const double delta0 = 1.0;\n\n  switch (prop.method) {\n  case GAUSS_NEWTON:    \n    gauss_newton(prop, num_iterations);\n    break;\n  case DOG_LEG:\n    powells_dog_leg(num_iterations, delta0, prop.max_iterations, prop.epsilon1,\n        prop.epsilon2, prop.epsilon3); // modifies x0,R\n    break;\n  case LEVENBERG_MARQUARDT:\n    levenberg_marquardt(prop, num_iterations);\n    break;\n  }\n\n}\n\n}\n", "meta": {"hexsha": "8d858dc5d8bcbe2ebfedf5dff98b34d708ac2b2f", "size": 18266, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pop_planar_slam/Thirdparty/isam/isamlib/Optimizer.cpp", "max_stars_repo_name": "gaunthan/pop_up_slam", "max_stars_repo_head_hexsha": "4d85a89f2cc09bf018af18ecba9e0a82e3c0ba1a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 196.0, "max_stars_repo_stars_event_min_datetime": "2018-10-10T00:28:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T13:32:37.000Z", "max_issues_repo_path": "pop_planar_slam/Thirdparty/isam/isamlib/Optimizer.cpp", "max_issues_repo_name": "gaunthan/pop_up_slam", "max_issues_repo_head_hexsha": "4d85a89f2cc09bf018af18ecba9e0a82e3c0ba1a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 22.0, "max_issues_repo_issues_event_min_datetime": "2018-11-13T14:07:58.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-03T14:27:12.000Z", "max_forks_repo_path": "pop_planar_slam/Thirdparty/isam/isamlib/Optimizer.cpp", "max_forks_repo_name": "gaunthan/pop_up_slam", "max_forks_repo_head_hexsha": "4d85a89f2cc09bf018af18ecba9e0a82e3c0ba1a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 65.0, "max_forks_repo_forks_event_min_datetime": "2018-10-12T07:02:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:43:21.000Z", "avg_line_length": 32.7347670251, "max_line_length": 92, "alphanum_fraction": 0.6803897952, "num_tokens": 4685, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585669110203, "lm_q2_score": 0.6334102567576901, "lm_q1q2_score": 0.4630599945720184}}
{"text": "/// @file  cmp.hpp\n/// @brief Declarations for embedding methods using classic ordinal constraints\n\n#pragma once\n#ifndef ORDGEO_EMBED_CMP_HPP\n#define ORDGEO_EMBED_CMP_HPP\n\n#include <ordgeo/config.hpp>\n#include <ordgeo/core/triplets.hpp>\n#include <ordgeo/embed/embed.hpp>\n#include <Eigen/Dense>\n#include <vector>\n\nnamespace ORDGEO_NAMESPACE {\nnamespace embed {\n\n/// Embeds a dataset using Soft Ordinal Embedding.\n/// This method uses the margin parameter to set the scale. A default value of\n/// 0.1 will be used if no margin is provided.\n///\n/// Citation: Y. Terada and U. von Luxburg, \"Local ordinal embedding,\" presented\n/// at the Proceedings of the 31st International Conference on Machine Learning,\n/// 2014.\nEmbedResult embedCmpWithSOE(std::vector<ORDGEO_NAMESPACE::core::CmpConstraint> cons,\n\tconst Eigen::MatrixXd& X0, EmbedConfig config);\n\n} // end namespace embed\n} // end namespace ORDGEO_NAMESPACE\n#endif /* ORDGEO_EMBED_CMP_HPP */\n", "meta": {"hexsha": "55998a97a41a843b81ba0eb3bc8b2fb80adac420", "size": 944, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ordgeo/embed/cmp.hpp", "max_stars_repo_name": "jesand/ordgeo", "max_stars_repo_head_hexsha": "370725ad551e3926e9c508ec23deec9cbe8fc346", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-02T10:29:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-02T10:29:04.000Z", "max_issues_repo_path": "include/ordgeo/embed/cmp.hpp", "max_issues_repo_name": "jesand/ordgeo", "max_issues_repo_head_hexsha": "370725ad551e3926e9c508ec23deec9cbe8fc346", "max_issues_repo_licenses": ["MIT"], "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/ordgeo/embed/cmp.hpp", "max_forks_repo_name": "jesand/ordgeo", "max_forks_repo_head_hexsha": "370725ad551e3926e9c508ec23deec9cbe8fc346", "max_forks_repo_licenses": ["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.4666666667, "max_line_length": 84, "alphanum_fraction": 0.7637711864, "num_tokens": 231, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7310585669110203, "lm_q2_score": 0.6334102567576901, "lm_q1q2_score": 0.4630599945720184}}
{"text": "#include \"knowledge_of_valid_opening.h\"\n#include <NTL/GF2X.h>\n#include <utils/utils.h>\n#include <hamming/jain_commitment/jain_commitment.h>\n\nvoid hamming_metric::knowledge_of_valid_opening::generate_public_key(\n        public_key_t * public_key,\n        const private_key_t *private_key) {\n\n    NTL::vec_GF2 r;\n    utils::generate_random_binary_matrix(\n            public_key->A,\n            JAIN_K,\n            JAIN_L + JAIN_V);\n\n    utils::generate_random_binary_vector(\n            r,\n            JAIN_L);\n\n    hamming_metric::commitment::generate_commitment(\n            public_key->commitment,\n            public_key->A,\n            r,\n            private_key->m,\n            private_key->e);\n}\n\nvoid hamming_metric::knowledge_of_valid_opening::generate_private_key(\n        private_key_t * private_key) {\n\n    private_key->e.kill();\n    private_key->m.kill();\n\n    utils::generate_random_binary_vector(\n            private_key->m,\n            JAIN_V);\n\n    utils::generate_vector_of_weight_w(\n            private_key->e,\n            JAIN_K,\n            W);\n}\n\nvoid hamming_metric::knowledge_of_valid_opening::generate_random_values(\n        random_values_t *random_values) {\n\n    ::utils::generate_random_binary_vector(\n            random_values->v,\n            JAIN_L + JAIN_V);\n\n    ::utils::generate_random_binary_vector(\n            random_values->f,\n            JAIN_K);\n}\n\nvoid hamming_metric::knowledge_of_valid_opening::generate_revealed_values(\n        revealed_values_t *revealed_values) {\n\n    utils::create_permutation_matrix(\n            revealed_values->P,\n            JAIN_K);\n}\n\nvoid hamming_metric::knowledge_of_valid_opening::generate_commitments_and_responses(\n        responses_t *responses,\n        commitments_t *commitments,\n        const random_values_t *random_values,\n        const revealed_values_t *revealed_values,\n        const public_key_t *public_key,\n        const private_key_t *private_key) {\n\n    ::hamming_metric::knowledge_of_valid_opening::generate_commitment_and_response_0(\n            commitments->c0,\n            commitments->r0,\n            responses->t0,\n            random_values->v,\n            public_key->A,\n            random_values->f);\n\n    ::hamming_metric::knowledge_of_valid_opening::generate_commitment_and_response_1(\n            commitments->c1,\n            commitments->r1,\n            responses->t1,\n            public_key->A,\n            revealed_values->P,\n            random_values->f);\n\n    ::hamming_metric::knowledge_of_valid_opening::generate_commitment_and_response_2(\n            commitments->c2,\n            commitments->r2,\n            responses->t2,\n            public_key->A,\n            revealed_values->P,\n            random_values->f,\n            private_key->e);\n}\n\nvoid hamming_metric::knowledge_of_valid_opening::encode(\n        NTL::vec_GF2 &out,\n        const NTL::vec_GF2 &v) {\n\n    out = utils::encode_binary_vector(v, JAIN_V);\n}\n\nvoid hamming_metric::knowledge_of_valid_opening::commit(\n        NTL::vec_GF2 &c,\n        NTL::vec_GF2 &r,\n        const NTL::vec_GF2 &v,\n        const NTL::mat_GF2 &A) {\n\n    utils::generate_random_binary_vector(\n            r,\n            JAIN_L);\n\n    hamming_metric::commitment::generate_commitment(\n            c,\n            A,\n            r,\n            v);\n}\n\nvoid hamming_metric::knowledge_of_valid_opening::generate_response_0(\n        NTL::vec_GF2 &t0,\n        const NTL::vec_GF2 &n,\n        const NTL::mat_GF2 &A,\n        const NTL::vec_GF2 &f) {\n\n    t0 = (A * n) + f;\n}\n\nvoid hamming_metric::knowledge_of_valid_opening::generate_commitment_and_response_0(\n        NTL::vec_GF2 &c0,\n        NTL::vec_GF2 &r0,\n        NTL::vec_GF2 &t0,\n        const NTL::vec_GF2 &n,\n        const NTL::mat_GF2 &A,\n        const NTL::vec_GF2 &f) {\n\n    generate_response_0(\n            t0,\n            n,\n            A,\n            f);\n\n    NTL::vec_GF2 encoded;\n    encode(\n            encoded,\n            t0);\n\n    commit(\n            c0,\n            r0,\n            encoded,\n            A);\n\n}\n\nvoid hamming_metric::knowledge_of_valid_opening::generate_response_1(\n        NTL::vec_GF2 &t1,\n        const NTL::mat_GF2 &P,\n        const NTL::vec_GF2 &f) {\n\n    t1 = P * f;\n}\n\nvoid hamming_metric::knowledge_of_valid_opening::generate_commitment_and_response_1(\n        NTL::vec_GF2 &c1,\n        NTL::vec_GF2 &r1,\n        NTL::vec_GF2 &t1,\n        const NTL::mat_GF2 &A,\n        const NTL::mat_GF2 &P,\n        const NTL::vec_GF2 &f) {\n\n    generate_response_1(\n            t1,\n            P,\n            f);\n\n    NTL::vec_GF2 encoded;\n    encode(\n            encoded,\n           t1);\n\n    commit(\n            c1,\n           r1,\n           encoded,\n           A);\n}\n\nvoid hamming_metric::knowledge_of_valid_opening::generate_response_2(\n        NTL::vec_GF2 &t2,\n        const NTL::mat_GF2 &P,\n        const NTL::vec_GF2 &f,\n        const NTL::vec_GF2 &e) {\n\n    t2 = P * (f + e);\n}\n\nvoid hamming_metric::knowledge_of_valid_opening::generate_commitment_and_response_2(\n        NTL::vec_GF2 &c2,\n        NTL::vec_GF2 &r2,\n        NTL::vec_GF2 &t2,\n        const NTL::mat_GF2 &A,\n        const NTL::mat_GF2 &P,\n        const NTL::vec_GF2 &f,\n        const NTL::vec_GF2 &e) {\n\n    generate_response_2(\n            t2,\n            P,\n            f,\n            e);\n\n    NTL::vec_GF2 encoded;\n    encode(\n            encoded,\n           t2);\n\n    commit(\n            c2,\n           r2,\n           encoded,\n           A);\n}\n\nint hamming_metric::knowledge_of_valid_opening::verify_0(\n        const NTL::vec_GF2 &c0,\n        const NTL::vec_GF2 &r0,\n        const NTL::vec_GF2 &t0,\n        const NTL::vec_GF2 &c1,\n        const NTL::vec_GF2 &r1,\n        const NTL::vec_GF2 &t1,\n        const NTL::mat_GF2 &P,\n        const public_key_t *public_key) {\n\n    auto _t0 = utils::encode_binary_vector(t0, JAIN_V);\n    auto _t1 = utils::encode_binary_vector(t1, JAIN_V);\n\n    if (hamming_metric::commitment::verify(\n            c0,\n            public_key->A,\n            r0,\n            _t0) != 0) {\n        std::cout << \"Knowledge of valid opening. Verification failed on ch = 0 and c0\" << std::endl;\n        return 1;\n    }\n\n    if (hamming_metric::commitment::verify(\n            c1,\n            public_key->A,\n            r1,\n            _t1) != 0) {\n        std::cout << \"Knowledge of valid opening. Verification failed on ch = 0 and c1\" << std::endl;\n        return 1;\n    }\n\n    auto sum = t0 + (NTL::inv(P) * t1);\n\n    NTL::vec_GF2 result;\n    if(utils::solve_equation(\n            result,\n            public_key->A,\n            sum) != 0) {\n        std::cout << \"No solutions\" << std::endl;\n        return 1;\n    }\n\n    return 0;\n}\n\nint hamming_metric::knowledge_of_valid_opening::verify_1(\n        const NTL::vec_GF2 &c0,\n        const NTL::vec_GF2 &r0,\n        const NTL::vec_GF2 &t0,\n        const NTL::vec_GF2 &c2,\n        const NTL::vec_GF2 &r2,\n        const NTL::vec_GF2 &t2,\n        const NTL::mat_GF2 &P,\n        const public_key_t *public_key) {\n\n    auto _t0 = utils::encode_binary_vector(t0, JAIN_V);\n    auto _t2 = utils::encode_binary_vector(t2, JAIN_V);\n\n    if (hamming_metric::commitment::verify(\n            c0,\n            public_key->A,\n            r0,\n            _t0) != 0) {\n        std::cout << \"Knowledge of valid opening. Verification failed on ch = 1 and c0\" << std::endl;\n        return 1;\n    }\n\n    if (hamming_metric::commitment::verify(\n            c2,\n            public_key->A,\n            r2,\n            _t2) != 0) {\n        std::cout << \"Knowledge of valid opening. Verification failed on ch = 1 and c2\" << std::endl;\n        return 1;\n    }\n\n    auto sum = t0 + public_key->commitment + (NTL::inv(P) * t2);\n\n    NTL::vec_GF2 result;\n    if(utils::solve_equation(\n            result,\n            public_key->A,\n            sum) != 0) {\n        std::cout << \"No solutions\" << std::endl;\n        return 1;\n    }\n\n    return 0;\n}\n\nint hamming_metric::knowledge_of_valid_opening::verify_2(\n        const NTL::vec_GF2 &c1,\n        const NTL::vec_GF2 &r1,\n        const NTL::vec_GF2 &t1,\n        const NTL::vec_GF2 &c2,\n        const NTL::vec_GF2 &r2,\n        const NTL::vec_GF2 &t2,\n        const public_key_t *public_key) {\n\n    auto _t1 = utils::encode_binary_vector(t1, JAIN_V);\n    auto _t2 = utils::encode_binary_vector(t2, JAIN_V);\n\n    if (hamming_metric::commitment::verify(\n            c1,\n            public_key->A,\n            r1,\n            _t1) != 0) {\n        std::cout << \"Knowledge of valid opening. Verification failed on ch = 2 and c1\" << std::endl;\n        return 1;\n    }\n\n    if (hamming_metric::commitment::verify(\n            c2,\n            public_key->A,\n            r2,\n            _t2) != 0) {\n        std::cout << \"Knowledge of valid opening. Verification failed on ch = 2 and c2\" << std::endl;\n        return 1;\n    }\n\n    if (NTL::weight(t1 + t2) != W) {\n        return 1;\n    }\n\n    return 0;\n}", "meta": {"hexsha": "d341b7c32b6f86643699e855b538d61e16c411df", "size": 8867, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/hamming/knowledge_of_valid_opening/knowledge_of_valid_opening.cpp", "max_stars_repo_name": "Crypto-TII/2020-CANS-rank_commitments", "max_stars_repo_head_hexsha": "fa42c3c3771cabf3eaeca43cff91b3927554be93", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/hamming/knowledge_of_valid_opening/knowledge_of_valid_opening.cpp", "max_issues_repo_name": "Crypto-TII/2020-CANS-rank_commitments", "max_issues_repo_head_hexsha": "fa42c3c3771cabf3eaeca43cff91b3927554be93", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/hamming/knowledge_of_valid_opening/knowledge_of_valid_opening.cpp", "max_forks_repo_name": "Crypto-TII/2020-CANS-rank_commitments", "max_forks_repo_head_hexsha": "fa42c3c3771cabf3eaeca43cff91b3927554be93", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-09-16T07:21:24.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-16T07:21:24.000Z", "avg_line_length": 25.1903409091, "max_line_length": 101, "alphanum_fraction": 0.5597158002, "num_tokens": 2428, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.4629800507161213}}
{"text": "/**\n * @file testSummarization.cpp\n *\n * @brief Test ported from MastSLAM for a simple batch summarization technique\n *\n * @date May 7, 2013\n * @author Alex Cunningham\n */\n\n#include <boost/assign/std/set.hpp>\n#include <boost/assign/std/vector.hpp>\n\n#include <CppUnitLite/TestHarness.h>\n\n#include <gtsam/base/TestableAssertions.h>\n\n#include <gtsam/geometry/Pose2.h>\n\n#include <gtsam/nonlinear/LabeledSymbol.h>\n#include <gtsam/nonlinear/summarization.h>\n#include <gtsam/nonlinear/LinearContainerFactor.h>\n\n#include <gtsam/slam/PriorFactor.h>\n#include <gtsam/slam/BetweenFactor.h>\n#include <gtsam/slam/BearingRangeFactor.h>\n\nusing namespace std;\nusing namespace boost::assign;\nusing namespace gtsam;\n\nconst double tol=1e-5;\n\ntypedef gtsam::PriorFactor<gtsam::Pose2> PosePrior;\ntypedef gtsam::BetweenFactor<gtsam::Pose2> PoseBetween;\ntypedef gtsam::BearingRangeFactor<gtsam::Pose2, gtsam::Point2> PosePointBearingRange;\n\ngtsam::noiseModel::Base::shared_ptr model2 = noiseModel::Unit::Create(2);\ngtsam::noiseModel::Base::shared_ptr model3 = noiseModel::Unit::Create(3);\n\n/* ************************************************************************* */\nTEST( testSummarization, example_from_ddf1 ) {\n  Key xA0 = LabeledSymbol('x', 'A', 0),\n      xA1 = LabeledSymbol('x', 'A', 1),\n      xA2 = LabeledSymbol('x', 'A', 2);\n  Key lA3 = LabeledSymbol('l', 'A', 3), lA5 = LabeledSymbol('l', 'A', 5);\n\n  SharedDiagonal diagmodel2 = noiseModel::Unit::Create(2);\n  SharedDiagonal diagmodel4 = noiseModel::Unit::Create(4);\n\n  Pose2 pose0;\n  Pose2 pose1(1.0, 0.0, 0.0);\n  Pose2 pose2(2.0, 0.0, 0.0);\n  Point2 landmark3(3.0, 3.0);\n  Point2 landmark5(5.0, 5.0);\n\n  Values values;\n  values.insert(xA0, pose0);\n  values.insert(xA1, pose1);\n  values.insert(xA2, pose2);\n  values.insert(lA3, landmark3);\n  values.insert(lA5, landmark5);\n\n  // build from nonlinear graph/values\n  NonlinearFactorGraph graph;\n  graph.add(PosePrior(xA0, Pose2(), model3));\n  graph.add(PoseBetween(xA0, xA1, pose0.between(pose1), model3));\n  graph.add(PoseBetween(xA1, xA2, pose1.between(pose2), model3));\n  graph.add(PosePointBearingRange(xA0, lA3, pose0.bearing(landmark3), pose0.range(landmark3), model2));\n  graph.add(PosePointBearingRange(xA1, lA3, pose1.bearing(landmark3), pose1.range(landmark3), model2));\n  graph.add(PosePointBearingRange(xA2, lA5, pose2.bearing(landmark5), pose2.range(landmark5), model2));\n\n  KeySet saved_keys;\n  saved_keys += lA3, lA5;\n\n  {\n    // Summarize to a linear system\n    GaussianFactorGraph actLinGraph; Ordering actOrdering;\n    SummarizationMode mode = PARTIAL_QR;\n    boost::tie(actLinGraph, actOrdering) = summarize(graph, values, saved_keys, mode);\n\n    Ordering expSumOrdering; expSumOrdering += xA0, xA1, xA2, lA3, lA5;\n    EXPECT(assert_equal(expSumOrdering, actOrdering));\n\n    // Does not split out subfactors where possible\n    GaussianFactorGraph expLinGraph;\n    expLinGraph.add(\n      expSumOrdering[lA3],\n      Matrix_(4,2,\n        0.595867,  0.605092,\n        0.0, -0.406109,\n        0.0,       0.0,\n        0.0,       0.0),\n      expSumOrdering[lA5],\n      Matrix_(4,2,\n        -0.125971, -0.160052,\n        0.13586,  0.301096,\n        0.268667,   0.31703,\n        0.0, -0.131698),\n      zero(4), diagmodel4);\n    EXPECT(assert_equal(expLinGraph, actLinGraph, tol));\n\n    // Summarize directly from a nonlinear graph to another nonlinear graph\n    NonlinearFactorGraph actContainerGraph = summarizeAsNonlinearContainer(graph, values, saved_keys, mode);\n    NonlinearFactorGraph expContainerGraph = LinearContainerFactor::convertLinearGraph(expLinGraph, expSumOrdering);\n\n    EXPECT(assert_equal(expContainerGraph, actContainerGraph, tol));\n  }\n\n  {\n    // Summarize to a linear system using cholesky - compare to previous version\n    GaussianFactorGraph actLinGraph; Ordering actOrdering;\n    SummarizationMode mode = PARTIAL_CHOLESKY;\n    boost::tie(actLinGraph, actOrdering) = summarize(graph, values, saved_keys, mode);\n\n    Ordering expSumOrdering; expSumOrdering += xA0, xA1, xA2, lA3, lA5;\n    EXPECT(assert_equal(expSumOrdering, actOrdering));\n\n    // Does not split out subfactors where possible\n    GaussianFactorGraph expLinGraph;\n    expLinGraph.add(HessianFactor(JacobianFactor(\n        expSumOrdering[lA3],\n        Matrix_(4,2,\n          0.595867,  0.605092,\n          0.0, -0.406109,\n          0.0,       0.0,\n          0.0,       0.0),\n        expSumOrdering[lA5],\n        Matrix_(4,2,\n          -0.125971, -0.160052,\n          0.13586,  0.301096,\n          0.268667,   0.31703,\n          0.0, -0.131698),\n        zero(4), diagmodel4)));\n    EXPECT(assert_equal(expLinGraph, actLinGraph, tol));\n\n    // Summarize directly from a nonlinear graph to another nonlinear graph\n    NonlinearFactorGraph actContainerGraph = summarizeAsNonlinearContainer(graph, values, saved_keys, mode);\n    NonlinearFactorGraph expContainerGraph = LinearContainerFactor::convertLinearGraph(expLinGraph, expSumOrdering);\n\n    EXPECT(assert_equal(expContainerGraph, actContainerGraph, tol));\n  }\n\n  {\n    // Summarize to a linear system with joint factor graph version\n    GaussianFactorGraph actLinGraph; Ordering actOrdering;\n    SummarizationMode mode = SEQUENTIAL_QR;\n    boost::tie(actLinGraph, actOrdering) = summarize(graph, values, saved_keys, mode);\n\n    Ordering expSumOrdering; expSumOrdering += xA0, xA1, xA2, lA3, lA5;\n    EXPECT(assert_equal(expSumOrdering, actOrdering));\n\n    // Does not split out subfactors where possible\n    GaussianFactorGraph expLinGraph;\n    expLinGraph.add(\n        expSumOrdering[lA3],\n        Matrix_(2,2,\n          0.595867, 0.605092,\n          0.0, 0.406109),\n        expSumOrdering[lA5],\n        Matrix_(2,2,\n          -0.125971, -0.160052,\n          -0.13586, -0.301096),\n        zero(2), diagmodel2);\n\n    expLinGraph.add(\n        expSumOrdering[lA5],\n        Matrix_(2,2,\n          0.268667,  0.31703,\n          0.0, 0.131698),\n        zero(2), diagmodel2);\n\n    EXPECT(assert_equal(expLinGraph, actLinGraph, tol));\n\n    // Summarize directly from a nonlinear graph to another nonlinear graph\n    NonlinearFactorGraph actContainerGraph = summarizeAsNonlinearContainer(graph, values, saved_keys, mode);\n    NonlinearFactorGraph expContainerGraph = LinearContainerFactor::convertLinearGraph(expLinGraph, expSumOrdering);\n\n    EXPECT(assert_equal(expContainerGraph, actContainerGraph, tol));\n  }\n\n  {\n    // Summarize to a linear system with joint factor graph version\n    GaussianFactorGraph actLinGraph; Ordering actOrdering;\n    SummarizationMode mode = SEQUENTIAL_CHOLESKY;\n    boost::tie(actLinGraph, actOrdering) = summarize(graph, values, saved_keys, mode);\n\n    Ordering expSumOrdering; expSumOrdering += xA0, xA1, xA2, lA3, lA5;\n    EXPECT(assert_equal(expSumOrdering, actOrdering));\n\n    // Does not split out subfactors where possible\n    GaussianFactorGraph expLinGraph;\n    expLinGraph.add(\n        expSumOrdering[lA3],\n        Matrix_(2,2,\n          0.595867, 0.605092,\n          0.0, 0.406109),\n        expSumOrdering[lA5],\n        Matrix_(2,2,\n          -0.125971, -0.160052,\n          -0.13586, -0.301096),\n        zero(2), diagmodel2);\n\n    expLinGraph.add(\n        expSumOrdering[lA5],\n        Matrix_(2,2,\n          0.268667,  0.31703,\n          0.0, 0.131698),\n        zero(2), diagmodel2);\n\n    EXPECT(assert_equal(expLinGraph, actLinGraph, tol));\n\n    // Summarize directly from a nonlinear graph to another nonlinear graph\n    NonlinearFactorGraph actContainerGraph = summarizeAsNonlinearContainer(graph, values, saved_keys, mode);\n    NonlinearFactorGraph expContainerGraph = LinearContainerFactor::convertLinearGraph(expLinGraph, expSumOrdering);\n\n    EXPECT(assert_equal(expContainerGraph, actContainerGraph, tol));\n  }\n}\n\n/* ************************************************************************* */\nTEST( testSummarization, no_summarize_case ) {\n  // Checks a corner case in which no variables are being eliminated\n  gtsam::Key key = 7;\n  gtsam::KeySet saved_keys; saved_keys.insert(key);\n  NonlinearFactorGraph graph;\n  graph.add(PosePrior(key, Pose2(1.0, 2.0, 0.3), model3));\n  graph.add(PosePrior(key, Pose2(2.0, 3.0, 0.4), model3));\n  Values values;\n  values.insert(key, Pose2(0.0, 0.0, 0.1));\n\n  SummarizationMode mode = SEQUENTIAL_CHOLESKY;\n  GaussianFactorGraph actLinGraph; Ordering actOrdering;\n  boost::tie(actLinGraph, actOrdering) = summarize(graph, values, saved_keys, mode);\n  Ordering expOrdering; expOrdering += key;\n  GaussianFactorGraph expLinGraph = *graph.linearize(values, expOrdering);\n  EXPECT(assert_equal(expOrdering, actOrdering));\n  EXPECT(assert_equal(expLinGraph, actLinGraph));\n}\n\n/* ************************************************************************* */\nint main() { TestResult tr; return TestRegistry::runAllTests(tr); }\n/* ************************************************************************* */\n", "meta": {"hexsha": "bf73422022ec1f1d493a20f7ae539b5d8694f57f", "size": 8818, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/testSummarization.cpp", "max_stars_repo_name": "malcolmreynolds/GTSAM", "max_stars_repo_head_hexsha": "e911b4d39f8a8c8604663bd46f10e7f53c860ae8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-07-23T19:34:50.000Z", "max_stars_repo_stars_event_max_datetime": "2017-07-23T19:34:50.000Z", "max_issues_repo_path": "tests/testSummarization.cpp", "max_issues_repo_name": "malcolmreynolds/GTSAM", "max_issues_repo_head_hexsha": "e911b4d39f8a8c8604663bd46f10e7f53c860ae8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/testSummarization.cpp", "max_forks_repo_name": "malcolmreynolds/GTSAM", "max_forks_repo_head_hexsha": "e911b4d39f8a8c8604663bd46f10e7f53c860ae8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.2880658436, "max_line_length": 116, "alphanum_fraction": 0.6754366069, "num_tokens": 2573, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.7185944046238981, "lm_q1q2_score": 0.46293655683934015}}
{"text": "//=======================================================================\n// Copyright 2001 Jeremy G. Siek, Andrew Lumsdaine, Lie-Quan Lee, \n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n#include <boost/config.hpp>\n#include <stdlib.h>\n#include <iostream>\n#include <stack>\n#include <queue>\n#include <boost/operators.hpp>\n#include <boost/graph/breadth_first_search.hpp>\n#include <boost/graph/visitors.hpp>\n#include <boost/property_map/property_map.hpp>\n\nusing namespace boost;\n\ntypedef\nstd::pair < int, int >\n  Position;\nPosition\n  knight_jumps[8] = {\n    Position(2, -1),\n    Position(1, -2),\n  Position(-1, -2),\n    Position(-2, -1),\n    Position(-2, 1),\n  Position(-1, 2),\n    Position(1, 2),\n  Position(2, 1)\n};\n\n\nPosition\noperator + (const Position & p1, const Position & p2)\n{\n  return Position(p1.first + p2.first, p1.second + p2.second);\n}\n\nstruct knights_tour_graph;\nstruct knight_adjacency_iterator:\n  public\n  boost::forward_iterator_helper <\n  knight_adjacency_iterator,\n  Position,\n  std::ptrdiff_t,\n  Position *,\n  Position >\n{\n  knight_adjacency_iterator()\n  {\n  }\n  knight_adjacency_iterator(int ii, Position p, const knights_tour_graph & g)\n    :\n  m_pos(p),\n  m_g(&g),\n  m_i(ii)\n  {\n    valid_position();\n  }\n  Position operator *() const\n  {\n    return\n      m_pos +\n      knight_jumps[m_i];\n  }\n  void\n  operator++ ()\n  {\n    ++m_i;\n    valid_position();\n  }\n  bool\n    operator == (const knight_adjacency_iterator & x) const {\n      return\n      m_i ==\n      x.\n      m_i;\n  }\nprotected:\n  void\n  valid_position();\n  Position\n    m_pos;\n  const knights_tour_graph *\n    m_g;\n  int\n    m_i;\n};\n\nstruct knights_tour_graph\n{\n  typedef Position\n    vertex_descriptor;\n  typedef\n    std::pair <\n    vertex_descriptor,\n    vertex_descriptor >\n    edge_descriptor;\n  typedef knight_adjacency_iterator\n    adjacency_iterator;\n  typedef void\n    out_edge_iterator;\n  typedef void\n    in_edge_iterator;\n  typedef void\n    edge_iterator;\n  typedef void\n    vertex_iterator;\n  typedef int\n    degree_size_type;\n  typedef int\n    vertices_size_type;\n  typedef int\n    edges_size_type;\n  typedef directed_tag\n    directed_category;\n  typedef disallow_parallel_edge_tag\n    edge_parallel_category;\n  typedef adjacency_graph_tag\n    traversal_category;\n  knights_tour_graph(int n):\n  m_board_size(n)\n  {\n  }\n  int\n    m_board_size;\n};\nint\nnum_vertices(const knights_tour_graph & g)\n{\n  return g.m_board_size * g.m_board_size;\n}\n\nvoid\nknight_adjacency_iterator::valid_position()\n{\n  Position new_pos = m_pos + knight_jumps[m_i];\n  while (m_i < 8 && (new_pos.first < 0 || new_pos.second < 0\n                     || new_pos.first >= m_g->m_board_size\n                     || new_pos.second >= m_g->m_board_size)) {\n    ++m_i;\n    new_pos = m_pos + knight_jumps[m_i];\n  }\n}\n\n\nstd::pair < knights_tour_graph::adjacency_iterator,\n  knights_tour_graph::adjacency_iterator >\nadjacent_vertices(knights_tour_graph::vertex_descriptor v,\n                  const knights_tour_graph & g)\n{\n  typedef knights_tour_graph::adjacency_iterator Iter;\n  return std::make_pair(Iter(0, v, g), Iter(8, v, g));\n}\n\n\nstruct compare_first\n{\n  template < typename P > bool operator() (const P & x, const P & y)\n  {\n    return x.first < y.first;\n  }\n};\n\ntemplate < typename Graph, typename TimePropertyMap >\n  bool backtracking_search(Graph & g,\n                           typename graph_traits <\n                           Graph >::vertex_descriptor src,\n                           TimePropertyMap time_map)\n{\n  typedef typename graph_traits < Graph >::vertex_descriptor Vertex;\n  typedef std::pair < int, Vertex > P;\n  std::stack < P > S;\n  int time_stamp = 0;\n\n  S.push(std::make_pair(time_stamp, src));\n  while (!S.empty()) {\n    Vertex x;\n    boost::tie(time_stamp, x) = S.top();\n    put(time_map, x, time_stamp);\n    // all vertices have been visited, success!\n    if (time_stamp == num_vertices(g) - 1)\n      return true;\n\n    bool deadend = true;\n    typename graph_traits < Graph >::adjacency_iterator i, end;\n    for (boost::tie(i, end) = adjacent_vertices(x, g); i != end; ++i)\n      if (get(time_map, *i) == -1) {\n        S.push(std::make_pair(time_stamp + 1, *i));\n        deadend = false;\n      }\n\n    if (deadend) {\n      put(time_map, x, -1);\n      S.pop();\n      boost::tie(time_stamp, x) = S.top();\n      while (get(time_map, x) != -1) {  // unwind stack to last unexplored vertex\n        put(time_map, x, -1);\n        S.pop();\n        boost::tie(time_stamp, x) = S.top();\n      }\n    }\n\n  }                             // while (!S.empty())\n  return false;\n}\n\ntemplate < typename Vertex, typename Graph, typename TimePropertyMap > int\nnumber_of_successors(Vertex x, Graph & g, TimePropertyMap time_map)\n{\n  int s_x = 0;\n  typename graph_traits < Graph >::adjacency_iterator i, end;\n  for (boost::tie(i, end) = adjacent_vertices(x, g); i != end; ++i)\n    if (get(time_map, *i) == -1)\n      ++s_x;\n  return s_x;\n}\n\ntemplate < typename Graph, typename TimePropertyMap >\n  bool warnsdorff(Graph & g,\n                  typename graph_traits < Graph >::vertex_descriptor src,\n                  TimePropertyMap time_map)\n{\n  typedef typename graph_traits < Graph >::vertex_descriptor Vertex;\n  typedef std::pair < int, Vertex > P;\n  std::stack < P > S;\n  int time_stamp = 0;\n\n  S.push(std::make_pair(time_stamp, src));\n  while (!S.empty()) {\n    Vertex x;\n    boost::tie(time_stamp, x) = S.top();\n    put(time_map, x, time_stamp);\n    // all vertices have been visited, success!\n    if (time_stamp == num_vertices(g) - 1)\n      return true;\n\n    // Put adjacent vertices into a local priority queue\n    std::priority_queue < P, std::vector < P >, compare_first > Q;\n    typename graph_traits < Graph >::adjacency_iterator i, end;\n    int num_succ;\n    for (boost::tie(i, end) = adjacent_vertices(x, g); i != end; ++i)\n      if (get(time_map, *i) == -1) {\n        num_succ = number_of_successors(*i, g, time_map);\n        Q.push(std::make_pair(num_succ, *i));\n      }\n    bool deadend = Q.empty();\n    // move vertices from local priority queue to the stack\n    for (; !Q.empty(); Q.pop()) {\n      boost::tie(num_succ, x) = Q.top();\n      S.push(std::make_pair(time_stamp + 1, x));\n    }\n    if (deadend) {\n      put(time_map, x, -1);\n      S.pop();\n      boost::tie(time_stamp, x) = S.top();\n      while (get(time_map, x) != -1) {  // unwind stack to last unexplored vertex\n        put(time_map, x, -1);\n        S.pop();\n        boost::tie(time_stamp, x) = S.top();\n      }\n    }\n\n  }                             // while (!S.empty())\n  return false;\n}\n\n\nstruct board_map\n{\n  typedef int value_type;\n  typedef Position key_type;\n  typedef read_write_property_map_tag category;\n    board_map(int *b, int n):m_board(b), m_size(n)\n  {\n  }\n  friend int get(const board_map & ba, Position p);\n  friend void put(const board_map & ba, Position p, int v);\n  friend std::ostream & operator << (std::ostream & os, const board_map & ba);\nprivate:\n  int *m_board;\n  int m_size;\n};\n\nint\nget(const board_map & ba, Position p)\n{\n  return ba.m_board[p.first * ba.m_size + p.second];\n}\n\nvoid\nput(const board_map & ba, Position p, int v)\n{\n  ba.m_board[p.first * ba.m_size + p.second] = v;\n}\n\nstd::ostream & operator << (std::ostream & os, const board_map & ba) {\n  for (int i = 0; i < ba.m_size; ++i) {\n    for (int j = 0; j < ba.m_size; ++j)\n      os << get(ba, Position(i, j)) << \"\\t\";\n    os << std::endl;\n  }\n  return os;\n}\n\nint\nmain(int argc, char *argv[])\n{\n  int\n    N;\n  if (argc == 2)\n    N = atoi(argv[1]);\n  else\n    N = 8;\n\n  knights_tour_graph\n  g(N);\n  int *\n    board =\n    new int[num_vertices(g)];\n  board_map\n  chessboard(board, N);\n  for (int i = 0; i < N; ++i)\n    for (int j = 0; j < N; ++j)\n      put(chessboard, Position(i, j), -1);\n\n  bool\n    ret =\n    warnsdorff(g, Position(0, 0), chessboard);\n\n  if (ret)\n    for (int i = 0; i < N; ++i) {\n      for (int j = 0; j < N; ++j)\n        std::cout << get(chessboard, Position(i, j)) << \"\\t\";\n      std::cout << std::endl;\n  } else\n    std::cout << \"method failed\" << std::endl;\n  return 0;\n}\n", "meta": {"hexsha": "048cbde404ab5ea82cd8e248830b76a85818b253", "size": 8218, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/graph/example/knights-tour.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "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": "boost/libs/graph/example/knights-tour.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "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": "boost/libs/graph/example/knights-tour.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "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": 23.9591836735, "max_line_length": 81, "alphanum_fraction": 0.6045266488, "num_tokens": 2268, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.4629365490744679}}
{"text": "//\n//  Copyright (c) 2018-2020, Cem Bassoy, cem.bassoy@gmail.com\n//  Copyright (c) 2019-2020, Amit Singh, amitsingh19975@gmail.com\n//\n//  Distributed under the Boost Software License, Version 1.0. (See\n//  accompanying file LICENSE_1_0.txt or copy at\n//  http://www.boost.org/LICENSE_1_0.txt)\n//\n//  The authors gratefully acknowledge the support of\n//  Google and Fraunhofer IOSB, Ettlingen, Germany\n//\n\n\n\n#include <boost/numeric/ublas/tensor.hpp>\n#include <boost/test/unit_test.hpp>\n#include <boost/multiprecision/cpp_bin_float.hpp>\n#include \"utility.hpp\"\n\nBOOST_AUTO_TEST_SUITE(test_tensor_static_comparison)\n\nusing double_extended = boost::multiprecision::cpp_bin_float_double_extended;\n\nusing test_types = zip<int,float,double_extended>::with_t<boost::numeric::ublas::layout::first_order, boost::numeric::ublas::layout::last_order>;\n\nstruct fixture {\n\n    template<size_t... N>\n    using extents_type = boost::numeric::ublas::extents<N...>;\n\n    fixture()= default;\n\n    std::tuple<\n        extents_type<1,1>,   // 1\n        extents_type<2,3>,   // 2\n        extents_type<4,1,3>,  // 3\n        extents_type<4,2,3>,  // 4\n        extents_type<4,2,3,5>   // 5\n    > extents;\n};\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_comparison, value,  test_types, fixture)\n{\n    namespace ublas = boost::numeric::ublas;\n    using value_type  = typename value::first_type;\n    using layout_type = typename value::second_type;\n\n    auto check = [](auto const& /*unused*/, auto& e)\n    { \n        using extents_type = std::decay_t<decltype(e)>;\n        using tensor_type = ublas::tensor_static<value_type, extents_type, layout_type>;\n        auto t  = tensor_type ();\n        auto t2 = tensor_type ();\n        auto v  = value_type  {};\n\n        std::iota(t.begin(), t.end(), v);\n        std::iota(t2.begin(), t2.end(), v+2);\n\n        BOOST_CHECK( t == t  );\n        BOOST_CHECK( t != t2 );\n\n        if(t.empty())\n            return;\n\n        BOOST_CHECK(!(t < t));\n        BOOST_CHECK(!(t > t));\n        BOOST_CHECK( t < t2 );\n        BOOST_CHECK( t2 > t );\n        BOOST_CHECK( t <= t );\n        BOOST_CHECK( t >= t );\n        BOOST_CHECK( t <= t2 );\n        BOOST_CHECK( t2 >= t );\n        BOOST_CHECK( t2 >= t2 );\n        BOOST_CHECK( t2 >= t );\n    };\n\n    for_each_in_tuple(extents,check);\n\n}\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_comparison_with_tensor_expressions, value,  test_types, fixture)\n{\n    namespace ublas = boost::numeric::ublas;\n    using value_type  = typename value::first_type;\n    using layout_type = typename value::second_type;\n\n\n    auto check = [](auto const& /*unused*/, auto& e)\n    { \n        using extents_type = std::decay_t<decltype(e)>;\n        using tensor_type = ublas::tensor_static<value_type, extents_type, layout_type>;\n\n        auto t  = tensor_type ();\n        auto t2 = tensor_type ();\n        auto v  = value_type  {};\n\n        std::iota(t.begin(), t.end(), v);\n        std::iota(t2.begin(), t2.end(), v+2);\n\n        BOOST_CHECK( t == t  );\n        BOOST_CHECK( t != t2 );\n\n        if(t.empty())\n            return;\n\n        BOOST_CHECK( !(t < t) );\n        BOOST_CHECK( !(t > t) );\n        BOOST_CHECK( t < (t2+t) );\n        BOOST_CHECK( (t2+t) > t );\n        BOOST_CHECK( t <= (t+t) );\n        BOOST_CHECK( (t+t2) >= t );\n        BOOST_CHECK( (t2+t2+2) >= t);\n        BOOST_CHECK( 2*t2 > t );\n        BOOST_CHECK( t < 2*t2 );\n        BOOST_CHECK( 2*t2 > t);\n        BOOST_CHECK( 2*t2 >= t2 );\n        BOOST_CHECK( t2 <= 2*t2);\n        BOOST_CHECK( 3*t2 >= t );\n\n    };\n\n    for_each_in_tuple(extents,check);\n\n}\n\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_comparison_with_scalar, value,  test_types, fixture)\n{\n    namespace ublas = boost::numeric::ublas;\n    using value_type  = typename value::first_type;\n    using layout_type = typename value::second_type;\n\n\n    for_each_in_tuple(extents,[](auto const& /*unused*/, auto& e)\n    { \n        using extents_type = std::decay_t<decltype(e)>;\n        using tensor_type = ublas::tensor_static<value_type, extents_type, layout_type>;\n\n        BOOST_CHECK( tensor_type(value_type{2}) == tensor_type(value_type{2})  );\n        BOOST_CHECK( tensor_type(value_type{2}) != tensor_type(value_type{1})  );\n\n        if(ublas::empty(e))\n            return;\n\n        BOOST_CHECK( !(tensor_type(2) <  2) );\n        BOOST_CHECK( !(tensor_type(2) >  2) );\n        BOOST_CHECK(  (tensor_type(2) >= 2) );\n        BOOST_CHECK(  (tensor_type(2) <= 2) );\n        BOOST_CHECK(  (tensor_type(2) == 2) );\n        BOOST_CHECK(  (tensor_type(2) != 3) );\n\n        BOOST_CHECK( !(2 >  tensor_type(2)) );\n        BOOST_CHECK( !(2 <  tensor_type(2)) );\n        BOOST_CHECK(  (2 <= tensor_type(2)) );\n        BOOST_CHECK(  (2 >= tensor_type(2)) );\n        BOOST_CHECK(  (2 == tensor_type(2)) );\n        BOOST_CHECK(  (3 != tensor_type(2)) );\n\n        BOOST_CHECK( !( tensor_type(2)+3 <  5) );\n        BOOST_CHECK( !( tensor_type(2)+3 >  5) );\n        BOOST_CHECK(  ( tensor_type(2)+3 >= 5) );\n        BOOST_CHECK(  ( tensor_type(2)+3 <= 5) );\n        BOOST_CHECK(  ( tensor_type(2)+3 == 5) );\n        BOOST_CHECK(  ( tensor_type(2)+3 != 6) );\n\n\n        BOOST_CHECK( !( 5 >  tensor_type(2)+3) );\n        BOOST_CHECK( !( 5 <  tensor_type(2)+3) );\n        BOOST_CHECK(  ( 5 >= tensor_type(2)+3) );\n        BOOST_CHECK(  ( 5 <= tensor_type(2)+3) );\n        BOOST_CHECK(  ( 5 == tensor_type(2)+3) );\n        BOOST_CHECK(  ( 6 != tensor_type(2)+3) );\n\n\n        BOOST_CHECK( !( tensor_type(2)+tensor_type(3) <  5) );\n        BOOST_CHECK( !( tensor_type(2)+tensor_type(3) >  5) );\n        BOOST_CHECK(  ( tensor_type(2)+tensor_type(3) >= 5) );\n        BOOST_CHECK(  ( tensor_type(2)+tensor_type(3) <= 5) );\n        BOOST_CHECK(  ( tensor_type(2)+tensor_type(3) == 5) );\n        BOOST_CHECK(  ( tensor_type(2)+tensor_type(3) != 6) );\n\n\n        BOOST_CHECK( !( 5 >  tensor_type(2)+tensor_type(3)) );\n        BOOST_CHECK( !( 5 <  tensor_type(2)+tensor_type(3)) );\n        BOOST_CHECK(  ( 5 >= tensor_type(2)+tensor_type(3)) );\n        BOOST_CHECK(  ( 5 <= tensor_type(2)+tensor_type(3)) );\n        BOOST_CHECK(  ( 5 == tensor_type(2)+tensor_type(3)) );\n        BOOST_CHECK(  ( 6 != tensor_type(2)+tensor_type(3)) );\n\n    });\n\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "9010482d041a1c59178f61e982e52697df039c6e", "size": 6220, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/tensor/test_static_operators_comparison.cpp", "max_stars_repo_name": "samd2/ublas", "max_stars_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 96.0, "max_stars_repo_stars_event_min_datetime": "2015-01-23T10:15:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T18:31:02.000Z", "max_issues_repo_path": "test/tensor/test_static_operators_comparison.cpp", "max_issues_repo_name": "samd2/ublas", "max_issues_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 105.0, "max_issues_repo_issues_event_min_datetime": "2015-01-14T09:01:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-05T06:10:39.000Z", "max_forks_repo_path": "test/tensor/test_static_operators_comparison.cpp", "max_forks_repo_name": "samd2/ublas", "max_forks_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 157.0, "max_forks_repo_forks_event_min_datetime": "2015-01-26T13:35:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T11:12:27.000Z", "avg_line_length": 31.256281407, "max_line_length": 145, "alphanum_fraction": 0.58585209, "num_tokens": 1788, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.4629365490744679}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2013   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2013   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#include <nt2/combinatorial/include/functions/cnp.hpp>\n\n#include <nt2/sdk/functor/meta/call.hpp>\n#include <nt2/sdk/unit/module.hpp>\n#include <nt2/sdk/unit/tests/relation.hpp>\n#include <nt2/sdk/unit/tests/type_expr.hpp>\n#include <nt2/sdk/unit/tests/ulp.hpp>\n#include <nt2/sdk/unit/tests/basic.hpp>\n#include <nt2/sdk/unit/module.hpp>\n#include <boost/simd/sdk/config.hpp>\n\n#include <nt2/include/constants/one.hpp>\n#include <nt2/include/constants/zero.hpp>\n#include <nt2/include/constants/inf.hpp>\n#include <nt2/include/constants/nan.hpp>\n\nNT2_TEST_CASE_TPL ( cnp_real__2_0,  NT2_REAL_TYPES)\n{\n  using nt2::cnp;\n  using nt2::tag::cnp_;\n  typedef typename nt2::meta::call<cnp_(T,T)>::type r_t;\n  typedef T wished_r_t;\n\n  // return type conformity test\n  NT2_TEST_TYPE_IS(r_t, wished_r_t);\n\n  // specific values tests\n#ifndef BOOST_SIMD_NO_INVALIDS\n  NT2_TEST_ULP_EQUAL(cnp(nt2::Inf<T>(), nt2::Inf<T>()), nt2::Nan<T>(), 0);\n  NT2_TEST_ULP_EQUAL(cnp(nt2::Nan<T>(), nt2::Nan<T>()), nt2::Nan<T>(), 0);\n#endif\n  NT2_TEST_ULP_EQUAL(cnp(T(10),T(1)), T(10), 0);\n  NT2_TEST_ULP_EQUAL(cnp(T(10),T(2)), T(45), 0);\n  NT2_TEST_ULP_EQUAL(cnp(T(10),T(8)), T(45), 0);\n  NT2_TEST_ULP_EQUAL(cnp(T(2),T(1)), T(2), 0);\n  NT2_TEST_ULP_EQUAL(cnp(T(2),T(2)), T(1), 0);\n  NT2_TEST_ULP_EQUAL(cnp(nt2::One<T>(), nt2::One<T>()), nt2::One<T>(), 0);\n  NT2_TEST_ULP_EQUAL(cnp(nt2::Zero<T>(), nt2::Zero<T>()), nt2::One<T>(), 0);\n}\n\nNT2_TEST_CASE_TPL ( cnp_unsigned_int__2_0,  NT2_UNSIGNED_TYPES)\n{\n  using nt2::cnp;\n  using nt2::tag::cnp_;\n  typedef typename nt2::meta::call<cnp_(T,T)>::type r_t;\n  typedef T wished_r_t;\n\n  // return type conformity test\n  NT2_TEST_TYPE_IS(r_t, wished_r_t);\n\n  // specific values tests\n  NT2_TEST_ULP_EQUAL(cnp(nt2::One<T>(), nt2::One<T>()), nt2::One<T>(), 0);\n  NT2_TEST_ULP_EQUAL(cnp(nt2::Zero<T>(), nt2::Zero<T>()), nt2::One<T>(), 0);\n}\n\nNT2_TEST_CASE_TPL ( cnp_signed_int__2_0,  NT2_INTEGRAL_SIGNED_TYPES)\n{\n  using nt2::cnp;\n  using nt2::tag::cnp_;\n  typedef typename nt2::meta::call<cnp_(T,T)>::type r_t;\n  typedef T wished_r_t;\n\n  // return type conformity test\n  NT2_TEST_TYPE_IS(r_t, wished_r_t);\n\n  // specific values tests\n  NT2_TEST_ULP_EQUAL(cnp(nt2::One<T>(), nt2::One<T>()), nt2::One<T>(), 0);\n  NT2_TEST_ULP_EQUAL(cnp(nt2::Zero<T>(), nt2::Zero<T>()), nt2::One<T>(), 0);\n}\n", "meta": {"hexsha": "2f48728217cd76a4dd8b6280f33f9a34a6a7d1ee", "size": 2794, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/core/combinatorial/unit/scalar/cnp.cpp", "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/combinatorial/unit/scalar/cnp.cpp", "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/combinatorial/unit/scalar/cnp.cpp", "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.8205128205, "max_line_length": 80, "alphanum_fraction": 0.6342161775, "num_tokens": 907, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.4629365451920317}}
{"text": "#ifndef SPARSE_LINEAR_SOLVERS_HPP\n#define SPARSE_LINEAR_SOLVERS_HPP\n\n#include \"SparseMatrix.hpp\"\n#include \"Utils.hpp\"\n\n#ifdef USEMKL\n#include \"MklLayer.hpp\"\n#include \"mkl.h\"\n#endif\n\n#include <Eigen/Sparse>\n#include <cmath>\n#include <cstdio>\n#include <cstring>\n#include <iostream>\n#include <iterator>\n#include <map>\n#include <memory>\n#include <unordered_map>\n#include <vector>\n\n\nnamespace cask {\n  namespace sparse_linear_solvers {\n\n    class Solver {\n      public:\n        virtual void analyze(\n            const Eigen::SparseMatrix<double> &A) {\n        }\n\n        virtual void preprocess(\n            const Eigen::SparseMatrix<double> &A) {\n  }\n\n        virtual Eigen::VectorXd solve(\n            const Eigen::SparseMatrix<double>& A,\n            const Eigen::VectorXd& b) = 0;\n    };\n\n    class EigenSolver: public Solver {\n      public:\n        virtual Eigen::VectorXd solve(\n            const Eigen::SparseMatrix<double>& A,\n            const Eigen::VectorXd& b);\n    };\n\n    class DfeCgSolver: public Solver {\n      public:\n        virtual Eigen::VectorXd solve(\n            const Eigen::SparseMatrix<double>& A,\n            const Eigen::VectorXd& b);\n    };\n\n    class DfeBiCgSolver: public Solver {\n      public:\n        virtual Eigen::VectorXd solve(\n            const Eigen::SparseMatrix<double>& A,\n            const Eigen::VectorXd& b);\n    };\n\n// Equivalent to un-precontitioned CG\nclass IdentityPreconditioner {\n public:\n  IdentityPreconditioner(const CsrMatrix& a) {\n      // nothing to do, but maintain a consistent interface\n  }\n\n  virtual std::vector<double> apply(const std::vector<double>& x) {\n      return x;\n  }\n};\n\n#ifdef USEMKL\n\nclass ILUPreconditioner {\n public:\n  DokMatrix pc;\n  CsrMatrix l, u; // lower and upper factors stored independently\n\n  // cached values, row and col ptrs; the latter two are 1 based indexed, as required by unitrrsolve\n  std::vector<double> Lvalues, Uvalues;\n  std::vector<int> Lrow_ptr, Lcol_ind, Urow_ptr, Ucol_ind;\n  std::vector<double> res;\n\n  // pre - a is a symmetric matrix\n  ILUPreconditioner(const CsrMatrix &a) {\n      if (!a.isSymmetric())\n          throw std::invalid_argument(\"ILUPreconditioner only supports symmetric CSR matrices\");\n      pc = a.toDok();\n      for (int i = 1; i < a.n; i++) {\n          if (pc.dok.count(i) == 0)\n              continue;\n\n          for (auto&p : pc.dok[i]) {\n            int k = p.first;\n            if (k >= i)\n                break;\n            if (!pc.isNnz(k, k))\n              continue;\n            pc.dok[i][k] = pc.dok[i][k] / pc.dok[k][k];\n            double beta = pc.dok[i][k];\n\n            for (auto&p : pc.dok[i]) {\n              int j = p.first;\n              if (j < k + 1)\n                continue;\n\n              if (pc.isNnz(k, j)) {\n                pc.dok[i][j] = pc.dok[i][j] - pc.dok[k][j] * beta;\n              }\n            }\n          }\n\n          // simplified original version of the inner loops\n          // for (int k = 0; k < i; k++) {\n          //     // update pivot - a[i,k] = a[i, k] / a[k, k]\n          //     if (pc.isNnz(i, k) && pc.isNnz(k, k)) {\n          //         pc.get(i, k) = pc.get(i, k) / pc.get(k, k);\n          //         double beta = pc.get(i, k);\n          //         for (int j = k + 1; j < pc.n; j++) {\n          //             // update row - a[i, j] -= a[k, j] * a[i, k]\n          //             if (pc.isNnz(i, j) && pc.isNnz(k, j)) {\n          //                 pc.get(i, j) = pc.get(i, j) - pc.get(k, j) * beta;\n          //             }\n          //         }\n          //     }\n          // }\n      }\n\n      l = CsrMatrix{pc.getLowerTriangular()};\n      Lvalues = l.values;\n      Lrow_ptr = l.getRowPtrWithOneBasedIndex();\n      Lcol_ind = l.getColIndWithOneBasedIndex();\n      u = CsrMatrix{pc.getUpperTriangular()};\n      Uvalues = u.values;\n      Urow_ptr = u.getRowPtrWithOneBasedIndex();\n      Ucol_ind = u.getColIndWithOneBasedIndex();\n      res = std::vector<double>(l.n);\n  }\n\n  virtual std::vector<double> apply(const std::vector<double>& x) {\n      // solve z = M^-1 r <==> Mz = r <==> LUz = r\n      // solve: Ly = r\n      cask::mkl::unittrsolve(Lvalues.data(), Lrow_ptr.data(), Lcol_ind.data(), x, res.data(), true);\n      // then solve Uz = y\n      auto y = res;\n      cask::mkl::unittrsolve(Uvalues.data(), Urow_ptr.data(), Ucol_ind.data(), y, res.data(), false);\n      return res;\n  }\n\n  void pretty_print() {\n      pc.pretty_print();\n  }\n};\n\n/**\n *  Standard preconditioned CG, (Saad et al)\n *  https://en.wikipedia.org/wiki/Conjugate_gradient_method\n */\ntemplate<typename T=double, typename Precon=IdentityPreconditioner>\nbool pcg(const CsrMatrix& a, double *rhs, double *x, int &iterations, bool verbose = false, cask::utils::Timer* t = nullptr) {\n    // configuration (TODO Should be exposed through params)\n    char tr = 'l';\n    int maxiters = 2000;\n    double tol = 1E-5;\n    if (t)\n      t->tic(\"cg:setup\");\n    Precon precon{a};\n\n    int n = a.n;\n    auto values  = a.values;\n    auto row_ptr = a.getRowPtrWithOneBasedIndex();\n    auto col_ind = a.getColIndWithOneBasedIndex();\n    assert(row_ptr[0] == 1 && \"Expecting one based indexing for use with mkl_?csrsymv\");\n\n    std::vector<double> r(n);             // residual\n    std::vector<double> b(rhs, rhs + n);  // rhs\n    std::vector<double> p(n);             //\n    std::vector<double> z(n);             //\n    if (t)\n      t->toc(\"cg:setup\");\n\n    if (t)\n      t->tic(\"cg:solve\");\n\n    //  r = b - A * x\n    mkl_dcsrsymv(&tr, &n, values.data(), row_ptr.data(), col_ind.data(), &x[0], &r[0]);\n    cblas_daxpby(n, 1.0, &b[0], 1, -1.0, &r[0], 1);\n\n    // z = M^-1 * r\n    z = precon.apply(r);\n\n    p = z;\n\n    // rsold = r * z\n    double rsold = cblas_ddot(n, &r[0], 1, &z[0], 1);\n\n    for (int i = 0; i < maxiters; i++) {\n        if (verbose) {\n            std::cout << \" rsold \" << rsold << \"iteration \" << iterations << \"\\n\";\n        }\n        std::vector<double> Ap(n);\n        // Ap = A * p\n        mkl_dcsrsymv(&tr, &n, values.data(), row_ptr.data(), col_ind.data(), &p[0], &Ap[0]);\n        // alpha = rsold / (p * Ap)\n        double alpha = rsold / cblas_ddot(n, &p[0], 1, &Ap[0], 1);\n        // x = x + alpha * p\n        cblas_daxpy(n, alpha, &p[0], 1, &x[0], 1);\n        // r = r - alpha * Ap\n        cblas_daxpby(n, -alpha, &Ap[0], 1, 1.0, &r[0], 1);\n\n        // z = M^-1 * r\n        z = precon.apply(r);\n\n        // rsnew = r * z\n        double rsnew = cblas_ddot(n, &r[0], 1, &z[0], 1);\n\n        if (rsnew <= tol * tol) {\n            // std::cout << \"Found solution\" << std::endl;\n            // print_array(\"x\", &x[0], n);\n          if (t)\n            t->toc(\"cg:solve\");\n          return true;\n        }\n\n        // p = r + (rsnew/rsold) * p\n        cblas_daxpby(n, 1, &z[0], 1, rsnew / rsold, &p[0], 1);\n        rsold = rsnew;\n        iterations = i;\n    }\n\n    mkl_free_buffers ();\n\n    if (t)\n      t->toc(\"cg:solve\");\n    return false;\n}\n#endif\n\n  }\n}\n\n#endif /* end of include guard: SPARSE_LINEAR_SOLVERS_HPP */\n\n", "meta": {"hexsha": "5381f3bdce109bfe414cacedd78ed38bb6621998", "size": 6970, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/runtime/SparseLinearSolvers.hpp", "max_stars_repo_name": "paul-g/spark", "max_stars_repo_head_hexsha": "9e561d7a575c6a984660ba4afc476a0a7aa5264d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2015-12-02T22:31:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T05:18:04.000Z", "max_issues_repo_path": "src/runtime/SparseLinearSolvers.hpp", "max_issues_repo_name": "caskorg/cask", "max_issues_repo_head_hexsha": "9e561d7a575c6a984660ba4afc476a0a7aa5264d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 15.0, "max_issues_repo_issues_event_min_datetime": "2018-02-02T10:07:08.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-02T10:07:09.000Z", "max_forks_repo_path": "src/runtime/SparseLinearSolvers.hpp", "max_forks_repo_name": "caskorg/cask", "max_forks_repo_head_hexsha": "9e561d7a575c6a984660ba4afc476a0a7aa5264d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2016-07-02T09:36:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-19T17:44:55.000Z", "avg_line_length": 28.2186234818, "max_line_length": 126, "alphanum_fraction": 0.5230989957, "num_tokens": 2063, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.6442250996557036, "lm_q1q2_score": 0.4629365441659896}}
{"text": "#include <stan/math/prim/mat.hpp>\n#include <stan/math/prim/scal.hpp>\n#include <test/unit/math/prim/prob/vector_rng_test_helper.hpp>\n#include <test/unit/math/prim/prob/VectorIntRNGTestRig.hpp>\n#include <test/unit/math/prim/prob/util.hpp>\n#include <boost/math/distributions.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <gtest/gtest.h>\n#include <limits>\n#include <vector>\n\nclass BernoulliTestRig : public VectorIntRNGTestRig {\n public:\n  BernoulliTestRig()\n      : VectorIntRNGTestRig(10000, 10, {0, 1}, {0.0, 0.1, 0.2, 0.7, 1.0},\n                            {0, 1}, {-2.0, -0.5, 1.1, 2.0}, {-2, -1, 2}) {}\n\n  template <typename T1, typename T2, typename T3, typename T_rng>\n  auto generate_samples(const T1& theta, const T2&, const T3&,\n                        T_rng& rng) const {\n    return stan::math::bernoulli_rng(theta, rng);\n  }\n\n  template <typename T1>\n  double pmf(int y, T1 theta, double, double) const {\n    return std::exp(stan::math::bernoulli_lpmf(y, theta));\n  }\n};\n\nTEST(ProbDistributionsBernoulli, errorCheck) {\n  check_dist_throws_all_types(BernoulliTestRig());\n}\n\nTEST(ProbDistributionsBernoulli, distributionCheck) {\n  check_counts_real(BernoulliTestRig());\n}\n\nTEST(ProbDistributionsBernoulli, error_check) {\n  boost::random::mt19937 rng;\n  EXPECT_NO_THROW(stan::math::bernoulli_rng(0.6, rng));\n\n  EXPECT_THROW(stan::math::bernoulli_rng(1.6, rng), std::domain_error);\n  EXPECT_THROW(stan::math::bernoulli_rng(-0.6, rng), std::domain_error);\n  EXPECT_THROW(stan::math::bernoulli_rng(stan::math::positive_infinity(), rng),\n               std::domain_error);\n}\n\nTEST(ProbDistributionsBernoulli, chiSquareGoodnessFitTest) {\n  boost::random::mt19937 rng;\n  int N = 10000;\n\n  std::vector<double> expected;\n  expected.push_back(N * (1 - 0.4));\n  expected.push_back(N * 0.4);\n\n  std::vector<int> counts(2);\n  for (int i = 0; i < N; ++i) {\n    ++counts[stan::math::bernoulli_rng(0.4, rng)];\n  }\n\n  assert_chi_squared(counts, expected, 1e-6);\n}\n", "meta": {"hexsha": "4f38aadae423611ae0c84930fd680031a74b1ce8", "size": 1967, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/prim/prob/bernoulli_test.cpp", "max_stars_repo_name": "christophernhill/math", "max_stars_repo_head_hexsha": "dc41aba296d592c7099be15eed6ba136d0f140b3", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/unit/math/prim/prob/bernoulli_test.cpp", "max_issues_repo_name": "christophernhill/math", "max_issues_repo_head_hexsha": "dc41aba296d592c7099be15eed6ba136d0f140b3", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/unit/math/prim/prob/bernoulli_test.cpp", "max_forks_repo_name": "christophernhill/math", "max_forks_repo_head_hexsha": "dc41aba296d592c7099be15eed6ba136d0f140b3", "max_forks_repo_licenses": ["BSD-3-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.2222222222, "max_line_length": 79, "alphanum_fraction": 0.6868327402, "num_tokens": 626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708562, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.46293653925751127}}
{"text": "/**\n * @file perceptron_test.cpp\n * @author Udit Saxena\n *\n * Tests for perceptron.\n */\n#include <mlpack/core.hpp>\n#include <mlpack/methods/perceptron/perceptron.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n\nusing namespace mlpack;\nusing namespace arma;\nusing namespace mlpack::perceptron;\nusing namespace mlpack::distribution;\n\nBOOST_AUTO_TEST_SUITE(PerceptronTest);\n\n/**\n * This test tests whether the perceptron converges for the AND gate classifier.\n */\nBOOST_AUTO_TEST_CASE(And)\n{\n  mat trainData;\n  trainData << 0 << 1 << 1 << 0 << endr\n            << 1 << 0 << 1 << 0 << endr;\n  Mat<size_t> labels;\n  labels << 0 << 0 << 1 << 0;\n\n  Perceptron<> p(trainData, labels.row(0), 2, 1000);\n\n  mat testData;\n  testData << 0 << 1 << 1 << 0 << endr\n           << 1 << 0 << 1 << 0 << endr;\n  Row<size_t> predictedLabels(testData.n_cols);\n  p.Classify(testData, predictedLabels);\n\n  BOOST_CHECK_EQUAL(predictedLabels(0, 0), 0);\n  BOOST_CHECK_EQUAL(predictedLabels(0, 1), 0);\n  BOOST_CHECK_EQUAL(predictedLabels(0, 2), 1);\n  BOOST_CHECK_EQUAL(predictedLabels(0, 3), 0);\n}\n\n/**\n * This test tests whether the perceptron converges for the OR gate classifier.\n */\nBOOST_AUTO_TEST_CASE(Or)\n{\n  mat trainData;\n  trainData << 0 << 1 << 1 << 0 << endr\n            << 1 << 0 << 1 << 0 << endr;\n\n  Mat<size_t> labels;\n  labels << 1 << 1 << 1 << 0;\n\n  Perceptron<> p(trainData, labels.row(0), 2, 1000);\n\n  mat testData;\n  testData << 0 << 1 << 1 << 0 << endr\n           << 1 << 0 << 1 << 0 << endr;\n  Row<size_t> predictedLabels(testData.n_cols);\n  p.Classify(testData, predictedLabels);\n\n  BOOST_CHECK_EQUAL(predictedLabels(0, 0), 1);\n  BOOST_CHECK_EQUAL(predictedLabels(0, 1), 1);\n  BOOST_CHECK_EQUAL(predictedLabels(0, 2), 1);\n  BOOST_CHECK_EQUAL(predictedLabels(0, 3), 0);\n}\n\n/**\n * This tests the convergence on a set of linearly separable data with 3\n * classes.\n */\nBOOST_AUTO_TEST_CASE(Random3)\n{\n  mat trainData;\n  trainData << 0 << 1 << 1 << 4 << 5 << 4 << 1 << 2 << 1 << endr\n            << 1 << 0 << 1 << 1 << 1 << 2 << 4 << 5 << 4 << endr;\n\n  Mat<size_t> labels;\n  labels << 0 << 0 << 0 << 1 << 1 << 1 << 2 << 2 << 2;\n\n  Perceptron<> p(trainData, labels.row(0), 3, 1000);\n\n  mat testData;\n  testData << 0 << 1 << 1 << endr\n           << 1 << 0 << 1 << endr;\n  Row<size_t> predictedLabels(testData.n_cols);\n  p.Classify(testData, predictedLabels);\n\n  for (size_t i = 0; i < predictedLabels.n_cols; i++)\n    BOOST_CHECK_EQUAL(predictedLabels(0, i), 0);\n\n}\n\n/**\n * This tests the convergence of the perceptron on a dataset which has only TWO\n * points which belong to different classes.\n */\nBOOST_AUTO_TEST_CASE(TwoPoints)\n{\n  mat trainData;\n  trainData << 0 << 1 << endr\n            << 1 << 0 << endr;\n\n  Mat<size_t> labels;\n  labels << 0 << 1;\n\n  Perceptron<> p(trainData, labels.row(0), 2, 1000);\n\n  mat testData;\n  testData << 0 << 1 << endr\n           << 1 << 0 << endr;\n  Row<size_t> predictedLabels(testData.n_cols);\n  p.Classify(testData, predictedLabels);\n\n  BOOST_CHECK_EQUAL(predictedLabels(0, 0), 0);\n  BOOST_CHECK_EQUAL(predictedLabels(0, 1), 1);\n}\n\n/**\n * This tests the convergence of the perceptron on a dataset which has a\n * non-linearly separable dataset.\n */\nBOOST_AUTO_TEST_CASE(NonLinearlySeparableDataset)\n{\n  mat trainData;\n  trainData << 1 << 2 << 3 << 4 << 5 << 6 << 7 << 8\n            << 1 << 2 << 3 << 4 << 5 << 6 << 7 << 8 << endr\n            << 1 << 1 << 1 << 1 << 1 << 1 << 1 << 1\n            << 2 << 2 << 2 << 2 << 2 << 2 << 2 << 2 << endr;\n\n  Mat<size_t> labels;\n  labels << 0 << 0 << 0 << 1 << 0 << 1 << 1 << 1\n         << 0 << 0 << 0 << 1 << 0 << 1 << 1 << 1;\n\n  Perceptron<> p(trainData, labels.row(0), 2, 1000);\n\n  mat testData;\n  testData << 3 << 4   << 5   << 6   << endr\n           << 3 << 2.3 << 1.7 << 1.5 << endr;\n  Row<size_t> predictedLabels(testData.n_cols);\n  p.Classify(testData, predictedLabels);\n\n  BOOST_CHECK_EQUAL(predictedLabels(0, 0), 0);\n  BOOST_CHECK_EQUAL(predictedLabels(0, 1), 0);\n  BOOST_CHECK_EQUAL(predictedLabels(0, 2), 1);\n  BOOST_CHECK_EQUAL(predictedLabels(0, 3), 1);\n}\n\nBOOST_AUTO_TEST_CASE(SecondaryConstructor)\n{\n  mat trainData;\n  trainData << 1 << 2 << 3 << 4 << 5 << 6 << 7 << 8\n            << 1 << 2 << 3 << 4 << 5 << 6 << 7 << 8 << endr\n            << 1 << 1 << 1 << 1 << 1 << 1 << 1 << 1\n            << 2 << 2 << 2 << 2 << 2 << 2 << 2 << 2 << endr;\n\n  Mat<size_t> labels;\n  labels << 0 << 0 << 0 << 1 << 0 << 1 << 1 << 1\n         << 0 << 0 << 0 << 1 << 0 << 1 << 1 << 1;\n\n  Perceptron<> p1(trainData, labels.row(0), 2, 1000);\n\n  Perceptron<> p2(p1);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "4fc1c8b57c5299b9bfddb8deb2e4743853fe20d2", "size": 4575, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/perceptron_test.cpp", "max_stars_repo_name": "jmlevin7878/mlpack2", "max_stars_repo_head_hexsha": "7fe38005d86b77293f728c34ca176224bdff9ee8", "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-08-17T11:59:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-17T11:59:16.000Z", "max_issues_repo_path": "src/mlpack/tests/perceptron_test.cpp", "max_issues_repo_name": "jmlevin7878/mlpack2", "max_issues_repo_head_hexsha": "7fe38005d86b77293f728c34ca176224bdff9ee8", "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/tests/perceptron_test.cpp", "max_forks_repo_name": "jmlevin7878/mlpack2", "max_forks_repo_head_hexsha": "7fe38005d86b77293f728c34ca176224bdff9ee8", "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": 26.9117647059, "max_line_length": 80, "alphanum_fraction": 0.5790163934, "num_tokens": 1598, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943805178139, "lm_q2_score": 0.6442250996557036, "lm_q1q2_score": 0.46293653640111726}}
{"text": "// Bring in gtest\n#include <gtest/gtest.h>\n#include <boost/cstdint.hpp>\n\n// Helpful functions from libsm\n#include <sm/eigen/gtest.hpp>\n#include <sm/kinematics/quaternion_algebra.hpp>\n#include <sm/kinematics/UncertainTransformation.hpp>\n\n\n\nTEST(UncertainTransformationTestSuite, testConstructor)\n{\n  using namespace sm::kinematics;\n\n  UncertainTransformation T_a_b;\n  Eigen::Matrix4d T;\n  T.setIdentity();\n  \n  UncertainTransformation::covariance_t U;\n  U.setZero();\n  \n  sm::eigen::assertNear(T, T_a_b.T(), 1e-10, SM_SOURCE_FILE_POS, \"Checking for the default constructor creating identity\");\n  sm::eigen::assertNear(U, T_a_b.U(), 1e-10, SM_SOURCE_FILE_POS, \"Checking for the default constructor creating zero uncertainty\");\n\n\n}\n\n\nTEST(UncertainTransformationTestSuite, testTV4Multiplication)\n{\n  using namespace sm::kinematics;\n\n  for(int i = 0; i < 100; i++)\n    {\n      UncertainTransformation T_a_b;\n      T_a_b.setRandom();\n      Eigen::Vector4d v_b;\n      v_b.setRandom();\n      v_b *= 100.0;\n      \n      Eigen::Vector4d v_a = T_a_b * v_b;\n      Eigen::Vector4d v_a_prime = T_a_b.T() * v_b;\n      sm::eigen::assertNear(v_a, v_a_prime, 1e-10, SM_SOURCE_FILE_POS, \"Checking for composition equal to matrix multiplication\");\n    }\n\n\n}\n\nTEST(UncertainTransformationTestSuite, testTVhMultiplication)\n{\n  using namespace sm::kinematics;\n\n  for(int i = 0; i < 100; i++)\n    {\n      UncertainTransformation T_a_b;\n      T_a_b.setRandom();\n      Eigen::Vector3d v_b;\n      v_b.setRandom();\n      v_b *= 100.0;\n      HomogeneousPoint V_b(v_b);\n      \n      Eigen::Vector3d v_a = T_a_b * v_b;\n      HomogeneousPoint V_a = T_a_b * V_b;\n      sm::eigen::assertNear(V_a.toEuclidean(), v_a, 1e-10, SM_SOURCE_FILE_POS, \"Checking for composition equal to matrix multiplication\");\n    }\n\n\n}\n\n\nTEST(UncertainTransformationTestSuite, testTVMultiplication)\n{\n  using namespace sm::kinematics;\n\n  for(int i = 0; i < 100; i++)\n    {\n      UncertainTransformation T_a_b;\n      T_a_b.setRandom();\n      Eigen::Vector3d v_b;\n      v_b.setRandom();\n      v_b *= 100.0;\n      \n      Eigen::Vector3d v_a = T_a_b * v_b;\n      Eigen::Vector3d v_a_prime = T_a_b.C() * v_b + T_a_b.t();\n      sm::eigen::assertNear(v_a, v_a_prime, 1e-10, SM_SOURCE_FILE_POS, \"Checking for composition equal to matrix multiplication\");\n    }\n\n\n}\n\n\n\nTEST(UncertainTransformationTestSuite, testTTMultiplication)\n{\n  try {\n    using namespace sm::kinematics;\n\n    for(int i = 0; i < 100; i++)\n      {\n\tUncertainTransformation T_a_b;\n\tT_a_b.setRandom();\n\n\tUncertainTransformation T_b_c;\n\tT_b_c.setRandom();\n\n\tUncertainTransformation T_a_c = T_a_b * T_b_c;\n\tEigen::Matrix4d T_a_c_prime = T_a_b.T() * T_b_c.T();\n\tsm::eigen::assertNear(T_a_c.T(), T_a_c_prime, 1e-10, SM_SOURCE_FILE_POS, \"Checking for composition equal to matrix multiplication\");\n      }\n\n  } catch(const std::exception & e)\n    {\n      FAIL() << e.what();\n    }\n\n\n}\n\n\nTEST(UncertainTransformationTestSuite, testInvert)\n{\n  using namespace sm::kinematics;\n\n  for(int i = 0; i < 100; i++)\n    {\n      UncertainTransformation T_a_b;\n      T_a_b.setRandom();\n\n      UncertainTransformation T_b_a = T_a_b.inverse();\n      UncertainTransformation T_a_b_prime = T_b_a.inverse();\n      \n      sm::eigen::assertNear(T_a_b_prime.T(), T_a_b.T(), 1e-10, SM_SOURCE_FILE_POS, \"Checking for identity\");\n  \n    }\n}\n\nTEST(UncertainTransformationTestSuite, testInvertProducesIdentity)\n{\n  using namespace sm::kinematics;\n\n  for(int i = 0; i < 100; i++)\n    {\n      UncertainTransformation T_a_b;\n      T_a_b.setRandom();\n      UncertainTransformation T_b_a = T_a_b.inverse();\n      UncertainTransformation Eye1 = T_a_b * T_b_a;\n      UncertainTransformation Eye2 = T_b_a * T_a_b;\n      \n      sm::eigen::assertNear(Eye1.T(), Eigen::Matrix4d::Identity(), 1e-10, SM_SOURCE_FILE_POS, \"Checking for identity\");\n      sm::eigen::assertNear(Eye2.T(), Eigen::Matrix4d::Identity(), 1e-10, SM_SOURCE_FILE_POS, \"Checking for identity\");\n    }\n\n\n}\n\n\n\n\nTEST(UncertainTransformationTestSuite, testInverse)\n{\n using namespace sm::kinematics;\n  UncertainTransformation TT_01;\n  TT_01.setRandom();\n  UncertainTransformation TT_10 = TT_01.inverse();\n  UncertainTransformation TTT_01 = TT_10.inverse();\n\n  Eigen::Matrix4d r1_T_01 = TT_01.T();\n  Eigen::Matrix4d r2_T_01 = TTT_01.T();\n\n  sm::eigen::assertNear(r1_T_01, r2_T_01, 1e-10, SM_SOURCE_FILE_POS, \"Testing that composition and inverse derive the same answer\");\n\n  UncertainTransformation::covariance_t r1_U_01 = TT_01.U();\n  UncertainTransformation::covariance_t r2_U_01 = TTT_01.U();\n  sm::eigen::assertNear(r1_U_01, r2_U_01, 1e-10, SM_SOURCE_FILE_POS, \"Testing that composition and inverse derive the same answer\");\n  \n}\n\n\n\nTEST(UncertainTransformationTestSuite, testComposition2)\n{\n\n using namespace sm::kinematics;\n  UncertainTransformation TT_01;\n  TT_01.setRandom();\n  UncertainTransformation TT_12;\n  TT_12.setRandom();\n  UncertainTransformation TT_02 = TT_01 * TT_12;\n\n  UncertainTransformation TT_10 = TT_01.inverse();\n  UncertainTransformation TT_21 = TT_12.inverse();\n  UncertainTransformation TT_20 = TT_21 * TT_10;\n\n  UncertainTransformation TT_20direct = TT_02.inverse();\n\n  Eigen::Matrix4d r1_T_20 = TT_20.T();\n  Eigen::Matrix4d r2_T_20 = TT_20direct.T();\n\n  sm::eigen::assertNear(r1_T_20, r2_T_20, 1e-10, SM_SOURCE_FILE_POS, \"Testing that composition and inverse derive the same answer\");\n\n  UncertainTransformation::covariance_t r1_U_20 = TT_20.U();\n  UncertainTransformation::covariance_t r2_U_20 = TT_20direct.U();\n  sm::eigen::assertNear(r1_U_20, r2_U_20, 1e-8, SM_SOURCE_FILE_POS, \"Testing that composition and inverse derive the same answer\");\n  \n}\n\n\n\nTEST(UncertainTransformationTestSuite, testTVMultiplication2)\n{\n  using namespace sm::kinematics;\n\n  for(int i = 0; i < 10; i++)\n    {\n      UncertainTransformation T_a_b;\n      T_a_b.setRandom();\n\n      UncertainHomogeneousPoint v_b;\n      v_b.setRandom();\n      \n      UncertainHomogeneousPoint v_a = T_a_b * v_b;\n      Eigen::Vector3d v_a_prime = T_a_b.C() * v_b.toEuclidean() + T_a_b.t();\n      sm::eigen::assertNear(v_a.toEuclidean(), v_a_prime, 1e-10, SM_SOURCE_FILE_POS, \"Checking for composition equal to matrix multiplication\");\n    }\n\n\n}\n\n// lestefan: added this\nTEST(UncertainTransformationTestSuite, testUOplus)\n{\n  using namespace sm::kinematics;\n\n  for(int i = 0; i < 10; i++)\n    {\n      UncertainTransformation T_a_b_1;\n      T_a_b_1.setRandom();\n\n      UncertainTransformation::covariance_t UOplus = T_a_b_1.UOplus();\n      \n      UncertainTransformation T_a_b_2=T_a_b_1;\n      T_a_b_2.setUOplus(UOplus);\n      sm::eigen::assertNear(T_a_b_1.U(), T_a_b_2.U(), 1e-10, SM_SOURCE_FILE_POS, \"Checking for getting and setting OPlus-type uncertainties\");\n    }\n\n\n}\n", "meta": {"hexsha": "3a9c2c8ace80b2c950d73f03b17e79f60d49363e", "size": 6685, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Schweizer-Messer/sm_kinematics/test/UncertainTransformationTests.cpp", "max_stars_repo_name": "PushyamiKaveti/kalibr", "max_stars_repo_head_hexsha": "d8bdfc59ee666ef854012becc93571f96fe5d80c", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": 2690.0, "max_stars_repo_stars_event_min_datetime": "2015-01-07T03:50:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T20:27:01.000Z", "max_issues_repo_path": "Schweizer-Messer/sm_kinematics/test/UncertainTransformationTests.cpp", "max_issues_repo_name": "PushyamiKaveti/kalibr", "max_issues_repo_head_hexsha": "d8bdfc59ee666ef854012becc93571f96fe5d80c", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": 481.0, "max_issues_repo_issues_event_min_datetime": "2015-01-27T10:21:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T14:02:41.000Z", "max_forks_repo_path": "Schweizer-Messer/sm_kinematics/test/UncertainTransformationTests.cpp", "max_forks_repo_name": "PushyamiKaveti/kalibr", "max_forks_repo_head_hexsha": "d8bdfc59ee666ef854012becc93571f96fe5d80c", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": 1091.0, "max_forks_repo_forks_event_min_datetime": "2015-01-26T21:21:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T01:55:33.000Z", "avg_line_length": 26.8473895582, "max_line_length": 144, "alphanum_fraction": 0.7023186238, "num_tokens": 1947, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943805178139, "lm_q2_score": 0.6442250928250374, "lm_q1q2_score": 0.46293653149263886}}
{"text": "#include <NTL/mat_ZZ_pE.h>\n#include <NTL/BasicThreadPool.h>\n\n\nNTL_START_IMPL\n\n\n//===================================================\n\n#define PAR_THRESH (40000.0)\n\nstatic double\nZZ_pE_SizeInWords()\n{\n   return double(deg(ZZ_pE::modulus()))*double(ZZ_p::ModulusSize());\n}\n\n\nstatic\nvoid mul_aux(Mat<ZZ_pE>& X, const Mat<ZZ_pE>& A, const Mat<ZZ_pE>& 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\n   ZZ_pContext ZZ_p_context;\n   ZZ_p_context.save();\n   ZZ_pEContext ZZ_pE_context;\n   ZZ_pE_context.save();\n   double sz = ZZ_pE_SizeInWords();\n\n   bool seq = (double(n)*double(l)*double(m)*sz*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   ZZ_p_context.restore();\n   ZZ_pE_context.restore();\n\n   long i, j, k;  \n   ZZ_pX acc, tmp;  \n\n   Vec<ZZ_pE> 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 mul(mat_ZZ_pE& X, const mat_ZZ_pE& A, const mat_ZZ_pE& B)  \n{  \n   if (&X == &A || &X == &B) {  \n      mat_ZZ_pE tmp;  \n      mul_aux(tmp, A, B);  \n      X = tmp;  \n   }  \n   else  \n      mul_aux(X, A, B);  \n}  \n  \n\nvoid inv(ZZ_pE& d, Mat<ZZ_pE>& X, const Mat<ZZ_pE>& 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_pXModulus& G = ZZ_pE::modulus();\n\n   ZZ_pX t1, t2;\n   ZZ_pX pivot;\n   ZZ_pX pivot_inv;\n\n   Vec< Vec<ZZ_pX> > M;\n   // scratch space\n\n   M.SetLength(n);\n   for (long i = 0; i < n; i++) {\n      M[i].SetLength(n);\n      for (long j = 0; j < n; j++) {\n         M[i][j].SetMaxLength(2*deg(G)-1);\n         M[i][j] = rep(A[i][j]);\n      }\n   }\n\n   ZZ_pX 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   ZZ_pContext ZZ_p_context;\n   ZZ_p_context.save();\n   double sz = ZZ_pE_SizeInWords();\n\n   bool seq = double(n)*double(n)*sz*sz < 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], G);\n         if (pivot != 0) {\n            InvMod(pivot_inv, pivot, G);\n            pos = i;\n            break;\n         }\n      }\n\n      if (pos != -1) {\n         if (k != pos) {\n            swap(M[pos], M[k]);\n            negate(det, det); \n            P[k] = pos;\n            pivoting = true;\n         }\n\n         MulMod(det, det, pivot, G);\n\n         {\n            // multiply row k by pivot_inv\n            ZZ_pX *y = &M[k][0];\n            for (long j = 0; j < n; j++) {\n               rem(t2, y[j], G);\n               MulMod(y[j], t2, pivot_inv, G);\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_p_context.restore();\n\n         ZZ_pX *y = &M[k][0]; \n         ZZ_pX t1, t2;\n\n         for (long i = first; i < last; i++) {\n            if (i == k) continue; // skip row k\n\n            ZZ_pX *x = &M[i][0]; \n            rem(t1, x[k], G);\n            negate(t1, t1); \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_pX *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\nstatic\nvoid solve_impl(ZZ_pE& d, Vec<ZZ_pE>& X, \n                const Mat<ZZ_pE>& A, const Vec<ZZ_pE>& 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_pX t1, t2;\n\n   const ZZ_pXModulus& G = ZZ_pE::modulus();\n\n   Vec< Vec<ZZ_pX> > M;\n\n   M.SetLength(n);\n\n   for (long i = 0; i < n; i++) {\n      M[i].SetLength(n+1);\n      for (long j = 0; j < n; j++) M[i][j].SetMaxLength(2*deg(G)-1);\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_pX det;\n   set(det);\n\n   ZZ_pContext ZZ_p_context;\n   ZZ_p_context.save();\n   double sz = ZZ_pE_SizeInWords();\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], G);\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            negate(det, det); \n         }\n\n         MulMod(det, det, M[k][k], G);\n\n         // make M[k, k] == -1 mod G, and make row k reduced\n\n         InvMod(t1, M[k][k], G);\n         negate(t1, t1); \n         for (long j = k+1; j <= n; j++) {\n            rem(t2, M[k][j], G);\n            MulMod(M[k][j], t2, t1, G);\n         }\n\n         bool seq =\n            double(n-(k+1))*(n-(k+1))*sz*sz < PAR_THRESH;\n\n         NTL_GEXEC_RANGE(seq, n-(k+1), first, last)\n         NTL_IMPORT(n)\n         NTL_IMPORT(k)\n\n         ZZ_p_context.restore();\n\n         ZZ_pX 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_pX *x = M[i].elts() + (k+1);\n            ZZ_pX *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_pE& d, Vec<ZZ_pE>& x, \n               const Mat<ZZ_pE>& A, const Vec<ZZ_pE>& b)\n{\n   solve_impl(d, x, A, b, true);\n}\n\nvoid solve(ZZ_pE& d, const Mat<ZZ_pE>& A, \n               Vec<ZZ_pE>& x, const Vec<ZZ_pE>& b)\n{\n   solve_impl(d, x, A, b, false);\n}\n\n\n\nlong gauss(Mat<ZZ_pE>& M_in, long w)\n{\n   ZZ_pX t1, t2;\n   ZZ_pX 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_pXModulus& G = ZZ_pE::modulus();\n\n   Vec< Vec<ZZ_pX> > M;\n\n   M.SetLength(n);\n   for (long i = 0; i < n; i++) {\n      M[i].SetLength(m);\n      for (long j = 0; j < m; j++) {\n         M[i][j].SetLength(2*deg(G)-1);\n         M[i][j] = rep(M_in[i][j]);\n      }\n   }\n\n   ZZ_pContext ZZ_p_context;\n   ZZ_p_context.save();\n   double sz = ZZ_pE_SizeInWords();\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], G);\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], G);\n         negate(piv, piv);\n\n         for (long j = k+1; j < m; j++) {\n            rem(M[l][j], M[l][j], G);\n         }\n\n         bool seq =\n            double(n-(l+1))*double(m-(k+1))*sz*sz < 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_p_context.restore();\n\n         ZZ_pX 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, G);\n\n            clear(M[i][k]);\n\n            ZZ_pX *x = M[i].elts() + (k+1);\n            ZZ_pX *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\nlong gauss(Mat<ZZ_pE>& M)\n{\n   return gauss(M, M.NumCols());\n}\n\nvoid image(Mat<ZZ_pE>& X, const Mat<ZZ_pE>& A)\n{\n   Mat<ZZ_pE> 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_pE>& X, const Mat<ZZ_pE>& A)\n{\n   long m = A.NumRows();\n   long n = A.NumCols();\n\n   const ZZ_pXModulus& G = ZZ_pE::modulus();\n\n   Mat<ZZ_pE> 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_pE> 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   ZZ_pEContext ZZ_pE_context;\n   ZZ_pE_context.save();\n   ZZ_pContext ZZ_p_context;\n   ZZ_p_context.save();\n   double sz = ZZ_pE_SizeInWords();\n\n   bool seq = \n      double(m-r)*double(r)*double(r)*sz*sz < PAR_THRESH;\n\n   NTL_GEXEC_RANGE(seq, m-r, first, last)\n   NTL_IMPORT(m)\n   NTL_IMPORT(r)\n\n   ZZ_p_context.restore();\n   ZZ_pE_context.restore();\n\n   ZZ_pX t1, t2;\n   ZZ_pE T3;\n\n   for (long k = first; k < last; k++) {\n      Vec<ZZ_pE>& 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\n\nvoid determinant(ZZ_pE& d, const Mat<ZZ_pE>& M_in)\n{\n   ZZ_pX t1, t2;\n\n   const ZZ_pXModulus& G = ZZ_pE::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< Vec<ZZ_pX> > M;\n\n   M.SetLength(n);\n   for (long i = 0; i < n; i++) {\n      M[i].SetLength(n);\n      for (long j = 0; j < n; j++) { \n         M[i][j].SetMaxLength(2*deg(G)-1);\n         M[i][j] = rep(M_in[i][j]);\n      }\n   }\n\n   ZZ_pX det;\n   set(det);\n\n   ZZ_pContext ZZ_p_context;\n   ZZ_p_context.save();\n   double sz = ZZ_pE_SizeInWords();\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], G);\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            negate(det, det);\n         }\n\n         MulMod(det, det, M[k][k], G);\n\n         // make M[k, k] == -1 mod G, and make row k reduced\n\n         InvMod(t1, M[k][k], G);\n         negate(t1, t1);\n         for (long j = k+1; j < n; j++) {\n            rem(t2, M[k][j], G);\n            MulMod(M[k][j], t2, t1, G);\n         }\n\n\n         bool seq =\n            double(n-(k+1))*(n-(k+1))*sz*sz < PAR_THRESH;\n\n         NTL_GEXEC_RANGE(seq, n-(k+1), first, last)\n         NTL_IMPORT(n)\n         NTL_IMPORT(k)\n\n         ZZ_p_context.restore();\n\n         ZZ_pX 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_pX *x = M[i].elts() + (k+1);\n            ZZ_pX *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\n  \nvoid add(mat_ZZ_pE& X, const mat_ZZ_pE& A, const mat_ZZ_pE& 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_pE& X, const mat_ZZ_pE& A, const mat_ZZ_pE& 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_pE& X, const mat_ZZ_pE& 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_pE& x, const mat_ZZ_pE& A, const vec_ZZ_pE& 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_pX 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_pE& x, const mat_ZZ_pE& A, const vec_ZZ_pE& b)  \n{  \n   if (&b == &x || A.alias(x)) {\n      vec_ZZ_pE 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_pE& x, const vec_ZZ_pE& a, const mat_ZZ_pE& 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_pX 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_pE& x, const vec_ZZ_pE& a, const mat_ZZ_pE& B)\n{\n   if (&a == &x) {\n      vec_ZZ_pE tmp;\n      mul_aux(tmp, a, B);\n      x = tmp;\n   }\n   else\n      mul_aux(x, a, B);\n\n}\n\n     \n  \nvoid ident(mat_ZZ_pE& 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\nlong IsIdent(const mat_ZZ_pE& 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_pE& X, const mat_ZZ_pE& 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_pE 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   \nvoid mul(mat_ZZ_pE& X, const mat_ZZ_pE& A, const ZZ_pE& b_in)\n{\n   ZZ_pE 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_pE& X, const mat_ZZ_pE& 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_pE& X, const mat_ZZ_pE& 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_pE& X, long n, const ZZ_pE& d_in)  \n{  \n   ZZ_pE 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_pE& A, long n, const ZZ_pE& 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_pE& 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_pE& 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_pE operator+(const mat_ZZ_pE& a, const mat_ZZ_pE& b)\n{\n   mat_ZZ_pE res;\n   add(res, a, b);\n   NTL_OPT_RETURN(mat_ZZ_pE, res);\n}\n\nmat_ZZ_pE operator*(const mat_ZZ_pE& a, const mat_ZZ_pE& b)\n{\n   mat_ZZ_pE res;\n   mul_aux(res, a, b);\n   NTL_OPT_RETURN(mat_ZZ_pE, res);\n}\n\nmat_ZZ_pE operator-(const mat_ZZ_pE& a, const mat_ZZ_pE& b)\n{\n   mat_ZZ_pE res;\n   sub(res, a, b);\n   NTL_OPT_RETURN(mat_ZZ_pE, res);\n}\n\n\nmat_ZZ_pE operator-(const mat_ZZ_pE& a)\n{\n   mat_ZZ_pE res;\n   negate(res, a);\n   NTL_OPT_RETURN(mat_ZZ_pE, res);\n}\n\n\nvec_ZZ_pE operator*(const mat_ZZ_pE& a, const vec_ZZ_pE& b)\n{\n   vec_ZZ_pE res;\n   mul_aux(res, a, b);\n   NTL_OPT_RETURN(vec_ZZ_pE, res);\n}\n\nvec_ZZ_pE operator*(const vec_ZZ_pE& a, const mat_ZZ_pE& b)\n{\n   vec_ZZ_pE res;\n   mul_aux(res, a, b);\n   NTL_OPT_RETURN(vec_ZZ_pE, res);\n}\n\nvoid inv(mat_ZZ_pE& X, const mat_ZZ_pE& A)\n{\n   ZZ_pE d;\n   inv(d, X, A);\n   if (d == 0) ArithmeticError(\"inv: non-invertible matrix\");\n}\n\nvoid power(mat_ZZ_pE& X, const mat_ZZ_pE& 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_pE 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_pE& 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": "af45cec8b4920782014e32438dc4c9b601985559", "size": 20016, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "homomorphic_evaluation/ntl-11.3.2/src/mat_ZZ_pE.cpp", "max_stars_repo_name": "dklee0501/PLDI_20_242_artifact_publication", "max_stars_repo_head_hexsha": "f2b73df9165c76e8b521d8ebd639d68321e3862b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 160.0, "max_stars_repo_stars_event_min_datetime": "2016-05-11T09:45:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T09:32:19.000Z", "max_issues_repo_path": "homomorphic_evaluation/ntl-11.3.2/src/mat_ZZ_pE.cpp", "max_issues_repo_name": "dklee0501/Lobster", "max_issues_repo_head_hexsha": "f2b73df9165c76e8b521d8ebd639d68321e3862b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 57.0, "max_issues_repo_issues_event_min_datetime": "2016-12-26T07:02:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-06T16:34:31.000Z", "max_forks_repo_path": "LibSource/ExtendedNTL/src/mat_ZZ_pE.cpp", "max_forks_repo_name": "ekzyis/CrypTool-2", "max_forks_repo_head_hexsha": "1af234b4f74486fbfeb3b3c49228cc36533a8c89", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 67.0, "max_forks_repo_forks_event_min_datetime": "2016-10-10T17:56:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T22:56:39.000Z", "avg_line_length": 19.2276657061, "max_line_length": 74, "alphanum_fraction": 0.431254996, "num_tokens": 7046, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.4628525066649614}}
{"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\u00e4nkt), www.simunova.com. \n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#ifndef MTL_VECTOR_UNIT_VECTOR_INCLUDE\n#define MTL_VECTOR_UNIT_VECTOR_INCLUDE\n\n#include <boost/numeric/mtl/mtl_fwd.hpp>\n#include <boost/numeric/mtl/vector/parameter.hpp>\n\nnamespace mtl { \n\nnamespace traits {\n\n    /// Type of unit_vector; will be changed later to a proxy for the sake of efficiency\n    template  <typename Value= double>\n    struct unit_vector\n    {\n\ttypedef mtl::vector::dense_vector<Value, mtl::vector::parameters<> >  type;\n    };\n}\n\nnamespace vector {\n\n    /// Return k-th unit vector of size n\n    /** The result is a dense column vector. In the future this will\n\tbe replaced by a proxy for the sake of efficiency.\n\tIf you use unit_vector in an expression you will not encounter\n\tthis change. If you define a variable you should use\n\ttraits::unit_vector, e.g.:\n\t\\code\n\ttypename mtl::traits::unit_vector<float>::type  e_k(mtl::vector::unit_vector(k, n));\n\t\\endcode\n    **/\n    template <typename Value>\n    typename traits::unit_vector<Value>::type\n    inline unit_vector(std::size_t k, std::size_t n)\n    {\n\tusing ::math::zero; using ::math::one;\n\tdense_vector<Value> v(n, zero(Value()));\n\tv[k]= one(Value());\n\treturn v;\n    }\n\n    /// Unit vector of type double\n    traits::unit_vector<double>::type\n    inline unit_vector(std::size_t k, std::size_t n)\n    {\n\treturn unit_vector<double>(k, n);\n    }\n\n} // namespace mtl::vector\n\n} // namespace mtl\n\n#endif // MTL_VECTOR_UNIT_VECTOR_INCLUDE\n", "meta": {"hexsha": "70b5add2855030d7e3c246afd43c3e59e66d79d4", "size": 1858, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/mtl4/boost/numeric/mtl/vector/unit_vector.hpp", "max_stars_repo_name": "spraetor/amdis2", "max_stars_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-07-04T16:44:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-03T07:26:27.000Z", "max_issues_repo_path": "lib/mtl4/boost/numeric/mtl/vector/unit_vector.hpp", "max_issues_repo_name": "spraetor/amdis2", "max_issues_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/mtl4/boost/numeric/mtl/vector/unit_vector.hpp", "max_forks_repo_name": "spraetor/amdis2", "max_forks_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5846153846, "max_line_length": 94, "alphanum_fraction": 0.7002152853, "num_tokens": 470, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.66192288918838, "lm_q2_score": 0.6992544147913993, "lm_q1q2_score": 0.46285250251645293}}
{"text": "/* Copyright (C) 2012-2019 IBM Corp.\n * This program is Licensed under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *   http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License. See accompanying LICENSE file.\n */\n\n/* Test_ThinEvalMap.cpp - Testing the evalution map for thin bootstrapping\n */\n#include <cassert>\n#include <helib/helib.h>\n#include <helib/EvalMap.h>\n#include <NTL/BasicThreadPool.h>\n#include <helib/ArgMap.h>\n\nNTL_CLIENT\nusing namespace helib;\n\nstatic bool dry = false; // a dry-run flag\nstatic bool noPrint = true;\n\nvoid  TestIt(long p, long r, long c, long _k, long w,\n             long L, Vec<long>& mvec, \n             Vec<long>& gens, Vec<long>& ords, long useCache)\n{\n  if (lsize(mvec)<1) { // use default values\n    mvec.SetLength(3); gens.SetLength(3); ords.SetLength(3);\n    mvec[0] = 7;    mvec[1] = 3;    mvec[2] = 221;\n    gens[0] = 3979; gens[1] = 3095; gens[2] = 3760;\n    ords[0] = 6;    ords[1] = 2;    ords[2] = -8;\n  }\n  if (!noPrint)\n    cout << \"*** TestIt\"\n       << (dry? \" (dry run):\" : \":\")\n       << \" p=\" << p\n       << \", r=\" << r\n       << \", c=\" << c\n       << \", k=\" << _k\n       << \", w=\" << w\n       << \", L=\" << L\n       << \", mvec=\" << mvec << \", \"\n       << \", useCache = \" << useCache\n       << endl;\n\n  setTimersOn();\n  setDryRun(false); // Need to get a \"real context\" to test ThinEvalMap\n\n  // mvec is supposed to include the prime-power factorization of m\n  long nfactors = mvec.length();\n  for (long i = 0; i < nfactors; i++)\n    for (long j = i+1; j < nfactors; j++)\n      assert(GCD(mvec[i], mvec[j]) == 1);\n\n  // multiply all the prime powers to get m itself\n  long m = computeProd(mvec);\n  assert(GCD(p, m) == 1);\n\n  // build a context with these generators and orders\n  vector<long> gens1, ords1;\n  convert(gens1, gens);\n  convert(ords1, ords);\n  Context context(m, p, r, gens1, ords1);\n  buildModChain(context, L, c);\n\n  if (!noPrint) {\n    context.zMStar.printout(); // print structure of Zm* /(p) to cout\n    cout << endl;\n  }\n  long d = context.zMStar.getOrdP();\n  long phim = context.zMStar.getPhiM();\n  long nslots = phim/d;\n\n  setDryRun(dry); // Now we can set the dry-run flag if desired\n\n  SecKey secretKey(context);\n  const PubKey& publicKey = secretKey;\n  secretKey.GenSecKey(w); // A Hamming-weight-w secret key\n  addSome1DMatrices(secretKey); // compute key-switching matrices that we need\n  addFrbMatrices(secretKey); // compute key-switching matrices that we need\n\n  // GG defines the plaintext space Z_p[X]/GG(X)\n  ZZX GG;\n  GG = context.alMod.getFactorsOverZZ()[0];\n  EncryptedArray ea(context, GG);\n\n  zz_p::init(context.alMod.getPPowR());\n\n  Vec<zz_p> val0(INIT_SIZE, nslots);\n  for (auto& x: val0)\n    random(x);\n\n  vector<ZZX> val1;\n  val1.resize(nslots);\n  for (long i = 0; i < nslots; i++) {\n    val1[i] = conv<ZZX>(conv<ZZ>(rep(val0[i])));\n  }\n\n  Ctxt ctxt(publicKey);\n  ea.encrypt(ctxt, publicKey, val1);\n\n  resetAllTimers();\n  FHE_NTIMER_START(ALL);\n\n  // Compute homomorphically the transformation that takes the\n  // coefficients packed in the slots and produces the polynomial\n  // corresponding to cube\n\n  if (!noPrint) CheckCtxt(ctxt, \"init\");\n\n  if (!noPrint) cout << \"build ThinEvalMap\\n\";\n  ThinEvalMap map(ea, /*minimal=*/false, mvec, \n    /*invert=*/false, /*build_cache=*/false); \n  // compute the transformation to apply\n\n  if (!noPrint) cout << \"apply ThinEvalMap\\n\";\n  if (useCache) map.upgrade();\n  map.apply(ctxt); // apply the transformation to ctxt\n  if (!noPrint) CheckCtxt(ctxt, \"ThinEvalMap\");\n  if (!noPrint) cout << \"check results\\n\";\n\n  if (!noPrint) cout << \"build ThinEvalMap\\n\";\n  ThinEvalMap imap(ea, /*minimal=*/false, mvec, \n    /*invert=*/true, /*build_cache=*/false); \n  // compute the transformation to apply\n  if (!noPrint) cout << \"apply ThinEvalMap\\n\";\n  if (useCache) imap.upgrade();\n  imap.apply(ctxt); // apply the transformation to ctxt\n  if (!noPrint) {\n    CheckCtxt(ctxt, \"ThinEvalMap\");\n    cout << \"check results\\n\";\n  }\n\n#if 1\n\n  /* create dirty version of ctxt */\n  Vec<zz_pX> dirty_val0;\n  dirty_val0.SetLength(nslots);\n  for (long i = 0; i < nslots; i++) {\n    random(dirty_val0[i], d);\n    SetCoeff(dirty_val0[i], 0, val0[i]);\n  }\n  \n  vector<ZZX> dirty_val1;\n  dirty_val1.resize(nslots);\n  for (long i = 0; i < nslots; i++) {\n    dirty_val1[i] = conv<ZZX>(dirty_val0[i]);\n  }\n\n  Ctxt dirty_ctxt(publicKey);\n  ea.encrypt(dirty_ctxt, publicKey, dirty_val1);\n\n\n  EvalMap dirty_map(ea, /*minimal=*/false, mvec, \n    /*invert=*/false, /*build_cache=*/false); \n\n  dirty_map.apply(dirty_ctxt);\n  imap.apply(dirty_ctxt);\n#endif\n\n\n  vector<ZZX> val2;\n  ea.decrypt(ctxt, secretKey, val2);\n  cout << ((val1 == val2)? \"GOOD\\n\" : \"BAD\\n\");\n\n  vector<ZZX> dirty_val2;\n  ea.decrypt(dirty_ctxt, secretKey, dirty_val2);\n  cout << ((val1 == dirty_val2)? \"GOOD\\n\" : \"BAD\\n\");\n\n\n  FHE_NTIMER_STOP(ALL);\n\n  if (!noPrint) {\n    cout << \"\\n*********\\n\";\n    printAllTimers();\n    cout << endl;\n  }\n}\n\n\n/* Usage: Test_EvalMap_x.exe [ name=value ]...\n *  p       plaintext base  [ default=2 ]\n *  r       lifting  [ default=1 ]\n *  c       number of columns in the key-switching matrices  [ default=2 ]\n *  k       security parameter  [ default=80 ]\n *  L       # of bits in the modulus chain \n *  s       minimum number of slots  [ default=0 ]\n *  seed    PRG seed  [ default=0 ]\n *  mvec    use specified factorization of m\n *             e.g., mvec='[5 3 187]'\n *  gens    use specified vector of generators\n *             e.g., gens='[562 1871 751]'\n *  ords    use specified vector of orders\n *             e.g., ords='[4 2 -4]', negative means 'bad'\n */\nint main(int argc, char *argv[])\n{\n  ArgMap amap;\n\n  long p=2;\n  amap.arg(\"p\", p, \"plaintext base\");\n\n  long r=1;\n  amap.arg(\"r\", r,  \"lifting\");\n\n  long c=2;\n  amap.arg(\"c\", c, \"number of columns in the key-switching matrices\");\n  \n  long k=80;\n  amap.arg(\"k\", k, \"security parameter\");\n\n  long L=300;\n  amap.arg(\"L\", L, \"# of levels in the modulus chain\");\n\n  long s=0;\n  amap.arg(\"s\", s, \"minimum number of slots\");\n\n  long seed=0;\n  amap.arg(\"seed\", seed, \"PRG seed\");\n\n  Vec<long> mvec;\n  amap.arg(\"mvec\", mvec, \"use specified factorization of m\", nullptr);\n  amap.note(\"e.g., mvec='[7 3 221]'\");\n\n  Vec<long> gens;\n  amap.arg(\"gens\", gens, \"use specified vector of generators\", nullptr);\n  amap.note(\"e.g., gens='[3979 3095 3760]'\");\n\n  Vec<long> ords;\n  amap.arg(\"ords\", ords, \"use specified vector of orders\", nullptr);\n  amap.note(\"e.g., ords='[6 2 -8]', negative means 'bad'\");\n\n  amap.arg(\"dry\", dry, \"a dry-run flag to check the noise\");\n\n  long nthreads=1;\n  amap.arg(\"nthreads\", nthreads, \"number of threads\");\n\n  amap.arg(\"noPrint\", noPrint, \"suppress printouts\");\n\n  long useCache=0;\n  amap.arg(\"useCache\", useCache, \"0: zzX cache, 2: DCRT cache\");\n\n  amap.parse(argc, argv);\n\n  SetNumThreads(nthreads);\n\n  SetSeed(conv<ZZ>(seed));\n  TestIt(p, r, c, k, /*Key Hamming weight=*/64, L, mvec, gens, ords, useCache);\n}\n\n// ./Test_ThinEvalMap_x mvec=\"[73 433]\" gens=\"[18620 12995]\" ords=\"[72 -6]\"\n", "meta": {"hexsha": "b864637dee7b4423c617765e7c7defaa7a09ccd6", "size": 7401, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Test_ThinEvalMap.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/Test_ThinEvalMap.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/Test_ThinEvalMap.cpp", "max_forks_repo_name": "Souhail-MEFTAH/HElib", "max_forks_repo_head_hexsha": "5f97813b99407d6f9a6251cee920b4e419edc028", "max_forks_repo_licenses": ["Apache-2.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.91015625, "max_line_length": 79, "alphanum_fraction": 0.6250506688, "num_tokens": 2322, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544335934765, "lm_q2_score": 0.6619228625116081, "lm_q1q2_score": 0.4628524963081272}}
{"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#include <boost/simd/arithmetic/include/functions/iround.hpp>\n#include <boost/simd/sdk/simd/io.hpp>\n#include <boost/dispatch/meta/as_integer.hpp>\n#include <nt2/sdk/unit/tests.hpp>\n#include <nt2/sdk/unit/module.hpp>\n#include <nt2/sdk/unit/tests/type_expr.hpp>\n#include <boost/simd/sdk/simd/native.hpp>\n#include <boost/simd/constant/constant.hpp>\n#include <boost/simd/include/constants/zero.hpp>\n#include <boost/simd/include/constants/one.hpp>\n#include <boost/simd/include/constants/inf.hpp>\n#include <boost/simd/include/constants/zero.hpp>\n#include <boost/simd/include/constants/minf.hpp>\n#include <boost/simd/include/constants/mone.hpp>\n#include <boost/simd/include/constants/nan.hpp>\n#include <boost/simd/include/constants/three.hpp>\n#include <boost/simd/include/constants/two.hpp>\n\nNT2_TEST_CASE_TPL ( iround_real__1_0,  BOOST_SIMD_SIMD_REAL_TYPES)\n{\n  using boost::simd::iround;\n  using boost::simd::tag::iround_;\n  using boost::simd::native;\n  typedef BOOST_SIMD_DEFAULT_EXTENSION  ext_t;\n  typedef native<T,ext_t>                  vT;\n  typedef typename boost::dispatch::meta::call<iround_(vT)>::type r_t;\n\n  // specific values tests\n  NT2_TEST_ULP_EQUAL(iround(boost::simd::splat<vT>(1.4)), boost::simd::One<r_t>(), 0);\n  NT2_TEST_ULP_EQUAL(iround(boost::simd::splat<vT>(1.5)), boost::simd::Two<r_t>(), 0);\n  NT2_TEST_ULP_EQUAL(iround(boost::simd::splat<vT>(1.6)), boost::simd::Two<r_t>(), 0);\n  NT2_TEST_ULP_EQUAL(iround(boost::simd::splat<vT>(2.5)), boost::simd::Three<r_t>(), 0);\n  NT2_TEST_ULP_EQUAL(iround(boost::simd::Half<vT>()), boost::simd::One<r_t>(), 0);\n  NT2_TEST_ULP_EQUAL(iround(boost::simd::Inf<vT>()), boost::simd::Inf<r_t>(), 0);\n  NT2_TEST_ULP_EQUAL(iround(boost::simd::Mhalf<vT>()), boost::simd::Mone<r_t>(), 0);\n  NT2_TEST_ULP_EQUAL(iround(boost::simd::Minf<vT>()), boost::simd::Minf<r_t>(), 0);\n  NT2_TEST_ULP_EQUAL(iround(boost::simd::Mone<vT>()), boost::simd::Mone<r_t>(), 0);\n  NT2_TEST_ULP_EQUAL(iround(boost::simd::Nan<vT>()), boost::simd::Zero<r_t>(), 0);\n  NT2_TEST_ULP_EQUAL(iround(boost::simd::One<vT>()), boost::simd::One<r_t>(), 0);\n  NT2_TEST_ULP_EQUAL(iround(boost::simd::Zero<vT>()), boost::simd::Zero<r_t>(), 0);\n} // end of test for floating_\n", "meta": {"hexsha": "e01ead5ef832910ac0dc56aeab70fe5114d7a66d", "size": 2695, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/base/unit/arithmetic/simd/iround.cpp", "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/unit/arithmetic/simd/iround.cpp", "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/unit/arithmetic/simd/iround.cpp", "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": 53.9, "max_line_length": 88, "alphanum_fraction": 0.6589981447, "num_tokens": 769, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.6992544147913994, "lm_q1q2_score": 0.4628524931895278}}
{"text": "/*\n ******************************************************************\n *           Delimiter Seperated Values Filter Library            *\n *                                                                *\n * Author: Arash Partow (2004)                                    *\n * URL: http://www.partow.net/programming/dsvfilter/index.html    *\n *                                                                *\n * Copyright notice:                                              *\n * Free use of the Delimiter Seperated Values Filter Library is   *\n * permitted under the guidelines and in accordance with the most *\n * current version of the Common Public License.                  *\n * http://www.opensource.org/licenses/cpl1.0.php                  *\n *                                                                *\n ******************************************************************\n*/\n\n#ifndef INCLUDE_DSV_FILTER_HPP\n#define INCLUDE_DSV_FILTER_HPP\n\n\n#include <string>\n#include <deque>\n#include <vector>\n\n#define strtk_no_tr1_or_boost\n\n#include \"exprtk.hpp\"\n#include \"strtk.hpp\"\n\n\n#ifdef dsv_filter_use_mmap\n  #include <boost/iostreams/device/mapped_file.hpp>\n#endif\n\n\nclass dsv_filter\n{\npublic:\n\n   struct column_properties\n   {\n      enum column_type\n      {\n         e_none,\n         e_string,\n         e_number\n      };\n\n      column_properties()\n      : type(e_none),\n        name(\"\"),\n        value_s(\"\"),\n        value_n(0.0),\n        process(false)\n      {}\n\n      column_type type;\n      std::string name;\n      std::string value_s;\n      double value_n;\n      strtk::util::value value;\n      bool process;\n   };\n\n   dsv_filter()\n   : file_name_(\"\"),\n     input_delimiter_(\",\"),\n     output_delimiter_(\"|\")\n   {\n      symbol_table_.add_constants();\n      expression_.register_symbol_table(symbol_table_);\n   }\n\n   inline std::string file_name() const\n   {\n      return file_name_;\n   }\n\n   inline void set_input_delimiter(const std::string& input_delimiter)\n   {\n      input_delimiter_ = input_delimiter;\n   }\n\n   inline void set_output_delimiter(const std::string& output_delimiter)\n   {\n      output_delimiter_ = output_delimiter;\n   }\n\n   inline std::string input_delimiter() const\n   {\n      return input_delimiter_;\n   }\n\n   inline std::string output_delimiter() const\n   {\n      return output_delimiter_;\n   }\n\n   inline std::size_t column_count() const\n   {\n      return column_.size();\n   }\n\n   inline std::size_t row_count() const\n   {\n      return grid_.row_count();\n   }\n\n   inline const column_properties& column(const std::size_t& index) const\n   {\n      return column_[index];\n   }\n\n   inline bool load(const std::string& file_name)\n   {\n      if (!strtk::fileio::file_exists(file_name))\n         return false;\n      file_name_ = file_name;\n      strtk::token_grid::options options;\n      options.column_delimiters = input_delimiter_;\n      #ifdef dsv_filter_use_mmap\n         input_source.close();\n         input_source.open(file_name_);\n         unsigned char* data = reinterpret_cast<unsigned char*>(const_cast<char*>(input_source.data()));\n         if (!grid_.load(data,input_source.size(),options))\n            return false;\n      #else\n         if (!grid_.load(file_name_,options))\n            return false;\n      #endif\n      if (0 == grid_.row_count())\n         return false;\n      if (grid_.row_count() < 2)\n         return false;\n      if(!process_column_header())\n         return false;\n      return true;\n   }\n\n   inline bool add_filter(const std::string& filter_expression)\n   {\n      error_ = \"\";\n      parser_.cache_symbols() = true;\n      if (!parser_.compile(filter_expression,expression_))\n      {\n         error_ = \"Error: \" + parser_.error() + \"\\tFilter: \" + filter_expression;\n         return false;\n      }\n\n      // Only extract for processing, the column values for that are\n      // being actively used in the current expression.\n      std::deque<std::string> symbol;\n      parser_.expression_symbols(symbol);\n      for (std::size_t i = 0; i < column_.size(); ++i)\n      {\n         if (column_[i].name.empty())\n            continue;\n         column_[i].process = false;\n         for (std::size_t j = 0; j < symbol.size(); ++j)\n         {\n            if (strtk::imatch(symbol[j],column_[i].name))\n            {\n               column_[i].process = true;\n               break;\n            }\n         }\n      }\n      return true;\n   }\n\n   template<typename Allocator,\n            template <typename,typename> class Sequence>\n   inline bool row(const std::size_t& r,\n                   const Sequence<bool,Allocator>& selected_column,\n                   std::string& row_result)\n   {\n      if (selected_column.size() != column_.size())\n      {\n         error_ = \"Error: number of selected columns larger than number of columns\";\n         return false;\n      }\n      if (r >= grid_.row_count())\n      {\n         strtk::build_string s;\n         s << \"Error: row[\" << r << \"] out of bounds.\";\n         error_ = s.as_string();\n         return false;\n      }\n      if (row_.index() != r)\n      {\n         row_ = grid_.row(r);\n      }\n      for (std::size_t c = 0; c < column_.size(); ++c)\n      {\n         if (selected_column[c])\n         {\n            strtk::token_grid::range_t token = row_.token(c);\n            row_result.append(token.first,token.second);\n            if (c < (column_.size() - 1))\n            {\n               row_result.append(output_delimiter_);\n            }\n         }\n      }\n      if (!row_result.empty() && row_result[row_result.size() - 1])\n      {\n         row_result.resize(row_result.size() - 1);\n      }\n      return true;\n   }\n\n   inline std::string error()\n   {\n      return error_;\n   }\n\n   enum filter_result\n   {\n      e_error,\n      e_match,\n      e_mismatch\n   };\n\n   inline filter_result operator[](const std::size_t& r)\n   {\n      row_ = grid_.row(r);\n      for (std::size_t c = 0; c < column_.size(); ++c)\n      {\n         if (!column_[c].process)\n            continue;\n         else if (!row_.parse_with_index(c,column_[c].value))\n         {\n            strtk::build_string s;\n            s << \"Error: Failed to process element at row/col[\"<< r << \",\" << c << \"]  value:\" << row_.get<std::string>(c);\n            error_ = s.as_string();\n            return e_error;\n         }\n      }\n      return (1.0 == expression_.value()) ? e_match : e_mismatch;\n   }\n\n   const strtk::token_grid& grid() const\n   {\n      return grid_;\n   }\n\nprivate:\n\n   inline bool process_column_header()\n   {\n      static const std::string string_id (\"_s\");\n      static const std::string number_id (\"_n\");\n      expression_.get_symbol_table().clear();\n      column_.clear();\n      column_.resize(grid_.row(0).size());\n      strtk::token_grid::row_type row = grid_.row(0);\n      std::string col_name = \"\";\n      std::string col_suffix = \"\";\n      for (std::size_t i = 0; i < row.size(); ++i)\n      {\n         column_properties& column = column_[i];\n         column.process = false;\n         col_name = row.get<std::string>(i);\n         col_suffix = (col_name.size() >= 2) ? strtk::text::remaining_string(col_name.size() - 2,col_name) : \"\";\n         col_name = col_name.substr(0,col_name.size() - 2);\n         if (symbol_table_.symbol_exists(col_name))\n         {\n            error_ = \"Error: Redefinition of column \" + col_name;\n            return false;\n         }\n         else if (strtk::ends_with(\"_s\",col_suffix) || strtk::ends_with(\"_S\",col_suffix))\n         {\n            column.type    = dsv_filter::column_properties::e_string;\n            column.name    = col_name;\n            column.value   = strtk::util::value(column.value_s);\n            column.process = true;\n            symbol_table_.add_stringvar(col_name,column.value_s);\n         }\n         else if (strtk::ends_with(\"_n\",col_suffix) || strtk::ends_with(\"_N\",col_suffix))\n         {\n            column.type    = dsv_filter::column_properties::e_number;\n            column.name    = col_name;\n            column.process = true;\n            column.value = strtk::util::value(column.value_n);\n            symbol_table_.add_variable(col_name,column.value_n);\n         }\n      }\n      return true;\n   }\n\n   std::string file_name_;\n   std::string input_delimiter_;\n   std::string output_delimiter_;\n   std::string error_;\n   std::vector<column_properties> column_;\n   strtk::token_grid grid_;\n   exprtk::symbol_table<double> symbol_table_;\n   exprtk::parser<double> parser_;\n   exprtk::expression<double> expression_;\n   strtk::token_grid::row_type row_;\n\n   #ifdef dsv_filter_use_mmap\n   boost::iostreams::mapped_file_source input_source;\n   #endif\n\n};\n\n#endif\n", "meta": {"hexsha": "a3dd9c7e330eab826d0df57492fd1cd7d393276d", "size": 8586, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib-src/sgcc/include/dsv_filter.hpp", "max_stars_repo_name": "xiaomailong/prestudy", "max_stars_repo_head_hexsha": "f4c53a5d568def175fbe1dc75283ed05b46d1238", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-03-20T01:30:24.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-25T09:56:31.000Z", "max_issues_repo_path": "lib-src/sgcc/include/dsv_filter.hpp", "max_issues_repo_name": "xiaomailong/prestudy", "max_issues_repo_head_hexsha": "f4c53a5d568def175fbe1dc75283ed05b46d1238", "max_issues_repo_licenses": ["MIT"], "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-src/sgcc/include/dsv_filter.hpp", "max_forks_repo_name": "xiaomailong/prestudy", "max_forks_repo_head_hexsha": "f4c53a5d568def175fbe1dc75283ed05b46d1238", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-21T01:02:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-21T01:02:36.000Z", "avg_line_length": 27.786407767, "max_line_length": 123, "alphanum_fraction": 0.5504309341, "num_tokens": 1973, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544085240401, "lm_q2_score": 0.6619228625116081, "lm_q1q2_score": 0.46285247971409404}}
{"text": "#include <algorithm>\n#include <array>\n#include <iostream>\n#include <numeric>\n#include <utility>\n#include <vector>\n\n#include <boost/range/irange.hpp>\n\n#include \"input.hpp\"\n\nusing intmax = std::intmax_t;\nusing uintmax = std::uintmax_t;\n\n// compile-time parsing so I can use arrays later on without magic numbers\nstruct ParseStats {\n  uintmax num_words,\n          num_lines;\n};\n\nconstexpr auto SPACE = ' ';\nconstexpr auto NEWLINE = '\\n';\n\nconstexpr auto parse_stats(std::string_view input) {\n  auto stats = ParseStats{};\n\n  auto& num_words = stats.num_words;\n  auto& num_lines = stats.num_lines;\n\n  for(auto c : input) {\n    num_words += (c == SPACE);\n    num_lines += (c == NEWLINE);\n  }\n\n  // there's no newline character on the last line, so we need to add it manually\n  ++num_lines;\n  // splitting by whitespace misses the last word, so we need to add the rest manually, too\n  num_words += num_lines;\n\n  return stats;\n}\n\nconstexpr auto PARSE_STATS = parse_stats(puzzle_input);\nconstexpr auto NUM_WORDS = PARSE_STATS.num_words;\nconstexpr auto NUM_LINES = PARSE_STATS.num_lines;\n\nconstexpr auto N = 4;\nconstexpr auto M = 5;\n\nusing IntArray = std::array<intmax, M>;\n\nusing Ingredient = IntArray;\nusing Properties = IntArray;\n\nusing Ingredients = std::array<IntArray, N>;\n\nauto split_input(std::string_view input) {\n  auto lines = std::array<decltype(input), NUM_LINES>{};\n  decltype(input.size()) pos = 0;\n  auto index = 0;\n  while(pos != input.npos) {\n    pos = input.find(NEWLINE);\n    lines[index++] = input.substr(0, pos);\n    input.remove_prefix(pos + 1);\n  }\n  return lines;\n}\n\nauto split_line(std::string_view line) {\n  auto words = std::array<decltype(line), NUM_WORDS>{};\n  decltype(line.size()) pos = 0;\n  auto index = 0;\n  while(pos != line.npos) {\n    pos = line.find(SPACE);\n    words[index++] = line.substr(0, pos);\n    line.remove_prefix(pos + 1);\n  }\n  return words;\n}\n\nauto to_int(std::string_view input) {\n  auto result = intmax{};\n  const auto negative = (input.front() == '-');\n  if(negative) {\n    input.remove_prefix(1);\n  }\n  for(auto c : input) {\n    result *= 10;\n    result += (c - '0');\n  }\n  return (negative ? -result : result);\n}\n\nauto parse(std::string_view input) {\n\n  const auto to_int_suffix = [] (auto token) {\n    token.remove_suffix(1);\n    return to_int(token);\n  };\n\n  auto ingredients = Ingredients{};\n  auto index = 0;\n\n  for(const auto& line : split_input(input)) {\n\n    const auto& words = split_line(line);\n\n    const auto word = [&words] (auto i) {\n      return words[(i + 1) * 2];\n    };\n\n    auto& ingredient = ingredients[index++];\n\n    for(const auto i : boost::irange(N)) {\n      ingredient[i] = to_int_suffix(word(i));\n    }\n\n    ingredient[N] = to_int(word(N));\n  }\n\n  return ingredients;\n}\n\nauto plus(const Properties& lhs, const Properties& rhs) {\n  auto result = Properties{};\n  // element-wise addition of lhs and rhs\n  std::transform(lhs.begin(), lhs.end(), rhs.begin(), result.begin(), std::plus{});\n  return result;\n}\n\nauto multiply(const intmax scalar, const Ingredient& ingredient) {\n  auto result = Properties{};\n  std::transform(ingredient.begin(), ingredient.end(), result.begin(), [scalar] (auto property) {\n    return (scalar * property);\n  });\n  return result;\n}\n\nauto get_max_score(const Ingredients& ingredients) {\n\n  auto max_score = intmax{};\n\n  intmax min_spoons = 1,\n         max_spoons = 100;\n\n  const intmax calories = 500;\n\n  for(auto fr = min_spoons; fr < (max_spoons - 2); ++fr) {\n\n    for(auto ca = min_spoons; ca < (max_spoons - fr - 1); ++ca) {\n\n      for(auto bu = min_spoons; bu < (max_spoons - fr - ca); ++bu) {\n\n        const auto su = (max_spoons - fr - ca - bu);\n\n        const auto recipe = IntArray{fr, ca, bu, su};\n\n        const auto properties = std::inner_product(recipe.begin(), recipe.end(), ingredients.begin(), Properties{}, plus, multiply);\n\n        if(properties.back() == calories) {\n\n          const auto new_score = std::accumulate(properties.begin(), (properties.end() - 1), intmax{1}, [] (auto acc, auto value) {\n            return acc * ((value > 0) ? value : 0);\n          });\n\n          max_score = std::max(new_score, max_score);\n\n        }\n      }\n    }\n  }\n\n  return max_score;\n}\n\nauto solution(std::string_view input) {\n\n  const auto ingredients = parse(input);\n\n  return get_max_score(ingredients);\n}\n\nint main() {\n\n  std::cout << solution(puzzle_input) << std::endl;\n\n}\n\n", "meta": {"hexsha": "3c578ba3e9c35aa2be14aab6fada0b356be5d63e", "size": 4382, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Day 15 Part 2/main_v2.cpp", "max_stars_repo_name": "Miroslav-Cetojevic/aoc-2015", "max_stars_repo_head_hexsha": "2807fcd3fc684843ae4222b25af6fd086fac77f5", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-19T20:19:18.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-19T20:19:18.000Z", "max_issues_repo_path": "Day 15 Part 2/main_v2.cpp", "max_issues_repo_name": "Miroslav-Cetojevic/aoc-2015", "max_issues_repo_head_hexsha": "2807fcd3fc684843ae4222b25af6fd086fac77f5", "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": "Day 15 Part 2/main_v2.cpp", "max_forks_repo_name": "Miroslav-Cetojevic/aoc-2015", "max_forks_repo_head_hexsha": "2807fcd3fc684843ae4222b25af6fd086fac77f5", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.1851851852, "max_line_length": 132, "alphanum_fraction": 0.6419443177, "num_tokens": 1135, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.82893881677331, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.4628189180569639}}
{"text": "#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n//#include <opencv2/features2d.hpp>\n#include <iostream>\n#include <armadillo>\n#include \"highgui.h\"\n#include \"imgproc.h\"\n#include \"videotest.h\"\n\nusing namespace std;\nusing namespace cv;\n\nvoid detectBear(cv::Mat &camframe, std::mutex &camlock, arma::vec & bearpos, double &bearsize, bool &bearfound) {\n  const int h1 = 0;\n  const int h2 = 100;\n  const int s1 = 128;\n  const int s2 = 255;\n  const int v1 = 128;\n  const int v2 = 255;\n\tarma::vec xbuf(10, arma::fill::zeros);\n\tarma::vec ybuf(10, arma::fill::zeros);\n\tarma::vec xcbuf(10, arma::fill::zeros);\n\tarma::vec ycbuf(10, arma::fill::zeros);\n\tint xind = 0, yind = 0;\n\tbool stable = false;\n\tVideoCapture cam(1);\n\tMat img;\n\twhile (1) {\n\t  cam.read(img);\n\t  //if (!img.data) {\n\t//\tcontinue;\n\t // }\n\t\tcamlock.lock();\n\t\timg.copyTo(camframe);\n\t\tcamlock.unlock();\n\t\tMat hsv;\n\t\tcvtColor(img, hsv, COLOR_BGR2HSV);\n\n\t\t// in range masking\n\t\tMat hsv2mask, hsv2;\n\t\tinRange(hsv, Scalar(h1, s1, v1), Scalar(h2, s2, v2), hsv2mask);\n\t\t//hsv.copyTo(hsv2, hsv2mask);\n\n\t\tarma::mat I;\n\t\tcvt_opencv2arma(hsv2mask, I);\n\t\t\n\t\t//blur\n\t\t//I = conv2(I, gauss2(7, 16));\n\t\t\n\t\tarma::rowvec r = arma::sum(I, 0);\n\t\tarma::colvec c = arma::sum(I, 1);\n\t\tdouble midx = arma::sum(r * arma::cumsum(arma::ones<arma::vec>(r.n_elem))) / arma::sum(r);\n\t\tdouble midy = arma::sum(c % arma::cumsum(arma::ones<arma::vec>(c.n_elem))) / arma::sum(c);\n\t\tstable = true;\n\t\tif (midx < 1 || (midx > (int)I.n_cols - 1) || arma::sum(r) == 0) {\n\t\t\tmidx = 0;\n\t\t}\n\t\tif (midy < 1 || (midy > (int)I.n_rows - 1) || arma::sum(c) == 0) {\n\t\t\tmidy = 0;\n\t\t}\n\n\t\t// remove noise\n\t\tif (midx == 0 || midy == 0) {\n\t\t\tstable = false;\n\t\t}\n\t\txbuf[xind] = midx;\n\t\tybuf[yind] = midy;\n\t\tmidx = arma::mean(xbuf);\n\t\tmidy = arma::mean(ybuf);\n\t\tif (sqrt(arma::var(xbuf) * arma::var(xbuf) + arma::var(ybuf) + arma::var(ybuf)) > 70.0) {\n\t\t\tstable = false;\n\t\t}\n\t\t\n\t\tScalar color(255, 0, 0);\n\t\t//cout << \"arma:: \" << midx << \", \" << midy << endl;\n\t\t//cout << \"stable: \" << stable << endl;\n\t\tcircle(img, Point((int)midx, (int)midy), 4, color, 0);\n\n\t\tdouble covx = sqrt(arma::sum(r * arma::square(arma::cumsum(arma::ones<arma::vec>(r.n_elem)) - midx)) / arma::sum(r));\n\t\tdouble covy = sqrt(arma::sum(c % arma::square(arma::cumsum(arma::ones<arma::vec>(c.n_elem)) - midy)) / arma::sum(c));\n\t\txcbuf[xind] = covx;\n\t\tycbuf[yind] = covy;\n\t\tcovx = arma::accu(xcbuf) / (int)xbuf.n_elem;\n\t\tcovy = arma::accu(ycbuf) / (int)ybuf.n_elem;\n\t\txind = (xind + 1) % (int)xbuf.n_elem;\n\t\tyind = (yind + 1) % (int)ybuf.n_elem;\n\t\t//double estw = covx * 3;\n\t\t//double esth = covy * 3;\n\t\t//blur the image to make it more accurate\n\t\t/*I = conv2(I, gauss2(7, 16));\n\t\tdisp_image(\"convI\", I);\n\t\tint minw = (int)midx;\n\t\tint maxw = (int)midx;\n\t\tfor (int minw = (int)midx; minw >= 0; minw--) {\n\t\t  if (I(midy, minw) < 0.05) {\n\t\t\tbreak;\n\t\t  }\n\t\t}\n\t\tfor (int maxw = (int)midx; maxw < 640; maxw++) {\n\t\t  if (I(midy, maxw) < 0.05) {\n\t\t\tbreak;\n\t\t  }\n\t\t}\n\t\tint minh = (int)midy;\n\t\tint maxh = (int)midy;\n\t\tfor (int minh = (int)midy; minh >= 0; minh--) {\n\t\t  if (I(minh, midx) < 0.05) {\n\t\t\tbreak;\n\t\t  }\n\t\t}\n\t\tfor (int maxh = (int)midy; maxh < 480; maxh++) {\n\t\t  if (I(maxh, midx) < 0.05) {\n\t\t\tbreak;\n\t\t  }\n\t\t}\n\t\tdouble covy = (double)(maxh - minh);\n\t\tdouble covx = (double)(maxw - minw);*/\n\t\tcovx = (covx) * 3.3;\n\t\tcovy = (covy) * 3.3;\n\t\tbearpos = arma::vec({ midx - 320, 479 - (midy - 240) });\n\t\tbearsize = 533 / (covx) * 12;\n\t\tbearfound = stable;\n\n\t\trectangle(img, Rect(midx-covx/2,midy-covy/2,covx,covy), Scalar(0, 0, 255), 2);\n\n\t\timshow(\"oldhsv\", hsv);\n\t\timshow(\"newhsv\", hsv2mask);\n\t\timshow(\"img\", img);\n\t\twaitKey(30);\n\t}\n}\n#if 0\n\nint main(int argc, char *argv[]) {\n\tif (argc != 8) {\n\t\tcout << \"usage: ./test img h1 h2 s1 s2 v1 v2\\n\";\n\t\treturn 1;\n\t}\n\tint h1 = atoi(argv[2]);\n\tint h2 = atoi(argv[3]);\n\tint s1 = atoi(argv[4]);\n\tint s2 = atoi(argv[5]);\n\tint v1 = atoi(argv[6]);\n\tint v2 = atoi(argv[7]);\n\n\t// convert to hsv\n\tVideoCapture cam(0);\n\n\tarma::vec xbuf(10, arma::fill::zeros);\n\tarma::vec ybuf(10, arma::fill::zeros);\n\tint xind = 0, yind = 0;\n\tbool stable = false;\n\n\twhile (1) {\n\t\tMat img;\n\t\tcam.read(img);\n\t\tMat hsv;\n\t\tcvtColor(img, hsv, COLOR_BGR2HSV);\n\n\t\t// in range masking\n\t\tMat hsv2mask, hsv2;\n\t\tinRange(hsv, Scalar(h1, s1, v1), Scalar(h2, s2, v2), hsv2mask);\n\t\t//hsv.copyTo(hsv2, hsv2mask);\n\n\t\tarma::mat I;\n\t\tcvt_opencv2arma(hsv2mask, I);\n\t\tarma::rowvec r = arma::sum(I, 0);\n\t\tarma::colvec c = arma::sum(I, 1);\n\t\tdouble midx = arma::sum(r * arma::cumsum(arma::ones<arma::vec>(r.n_elem))) / arma::sum(r);\n\t\tdouble midy = arma::sum(c % arma::cumsum(arma::ones<arma::vec>(c.n_elem))) / arma::sum(c);\n\t\tstable = true;\n\t\tif (midx < 1 || (midx > (int)I.n_cols - 1) || arma::sum(r) == 0) {\n\t\t\tmidx = 0;\n\t\t}\n\t\tif (midy < 1 || (midy > (int)I.n_rows - 1) || arma::sum(c) == 0) {\n\t\t\tmidy = 0;\n\t\t}\n\n\t\t// remove noise\n\t\tif (midx == 0 || midy == 0) {\n\t\t\tstable = false;\n\t\t}\n\t\txbuf[xind] = midx;\n\t\tybuf[yind] = midy;\n\t\txind = (xind + 1) % (int)xbuf.n_elem;\n\t\tyind = (yind + 1) % (int)ybuf.n_elem;\n\t\tmidx = arma::mean(xbuf);\n\t\tmidy = arma::mean(ybuf);\n\t\tif (sqrt(arma::var(xbuf) * arma::var(xbuf) + arma::var(ybuf) + arma::var(ybuf)) > 70.0) {\n\t\t\tstable = false;\n\t\t}\n\t\t\n\t\tScalar color(255, 0, 0);\n\t\tcout << \"arma:: \" << midx << \", \" << midy << endl;\n\t\tcout << \"stable: \" << stable << endl;\n\t\tcircle(img, Point((int)midx, (int)midy), 4, color, 0);\n\n\t\tdouble covx = sqrt(arma::sum(r * arma::square(arma::cumsum(arma::ones<arma::vec>(r.n_elem)) - midx)) / arma::sum(r));\n\t\tdouble covy = sqrt(arma::sum(c % arma::square(arma::cumsum(arma::ones<arma::vec>(c.n_elem)) - midy)) / arma::sum(c));\n\t\tdouble estw = covx * 3;\n\t\tdouble esth = covy * 3;\n\n\t\trectangle(img, Rect(midx-estw/2,midy-esth/2,estw,esth), Scalar(0, 0, 255), 2);\n\n\t\t// use histogram binning to get the center\n\n\t\t// create blob params\n\t\t/*SimpleBlobDetector::Params params;\n\n\t\t// Change thresholds\n\t\tparams.minThreshold = 10;\n\t\tparams.maxThreshold = 200;\n\n\t\t// Filter by Area.\n\t\tparams.filterByArea = true;\n\t\tparams.minArea = 1500;\n\n\t\t// Filter by Circularity\n\t\tparams.filterByCircularity = true;\n\t\tparams.minCircularity = 0.1;\n\n\t\t// Filter by Convexity\n\t\tparams.filterByConvexity = true;\n\t\tparams.minConvexity = 0.87;\n\n\t\t// Filter by Inertia\n\t\tparams.filterByInertia = true;\n\t\tparams.minInertiaRatio = 0.01;\n\n\t\tPtr<SimpleBlobDetector> blob = SimpleBlobDetector::create(params);\n\t\tvector<KeyPoint> kp;\n\t\tMat des;\n\t\tMat hsvd = hsv2mask * -0.75 + 255;\n\t\tblob->detect(hsvd, kp);\n\n\t\tcout << \"found \" << kp.size() << \" matches\\n\";\n\n\t\tMat kpimg;\n\t\tdrawKeypoints(img, kp, kpimg, Scalar(0, 0, 255), DrawMatchesFlags::DRAW_RICH_KEYPOINTS);*/\n\n\t\timshow(\"oldhsv\", hsv);\n\t\timshow(\"newhsv\", hsv2mask);\n\t\timshow(\"img\", img);\n\t\tif (waitKey(30) & 0xff == 'Q') {\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn 1;\n}\n#endif\n", "meta": {"hexsha": "18ac8232974bf044cdf4f922e089ddff737e3873", "size": 6776, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "temp/TEMP/general/videotest.cpp", "max_stars_repo_name": "timrobot/Tachikoma-Project", "max_stars_repo_head_hexsha": "c7af70f2c58fe43f25331fd03589845480ae0f16", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-11-11T19:04:33.000Z", "max_stars_repo_stars_event_max_datetime": "2016-11-11T19:04:33.000Z", "max_issues_repo_path": "temp/TEMP/general/videotest.cpp", "max_issues_repo_name": "TimothyYong/Tachikoma-Project", "max_issues_repo_head_hexsha": "c7af70f2c58fe43f25331fd03589845480ae0f16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "temp/TEMP/general/videotest.cpp", "max_forks_repo_name": "TimothyYong/Tachikoma-Project", "max_forks_repo_head_hexsha": "c7af70f2c58fe43f25331fd03589845480ae0f16", "max_forks_repo_licenses": ["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.8888888889, "max_line_length": 119, "alphanum_fraction": 0.5922373081, "num_tokens": 2651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4627891250414487}}
{"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/radial_distortion.h\"\n\n#include <Eigen/Core>\n#include <glog/logging.h>\n\n#include <algorithm>\n#include <cmath>\n#include <limits>\n\n#include \"theia/math/polynomial.h\"\n\nnamespace theia {\n\n// Solves for the undistorted image points. We assume that the radial distortion\n// model is:\n//   r = x * x + y * y;\n//   d = 1 + r * (k1 + k2 * r);\n//   xp = x * d;\n//   yp = y * d;\n//\n// Given this model, we know that:\n//   xp / x  =  yp / y\n// So we can rewrite r such that\n//   r = (1 + yp * yp / (yp * xp)) * x * x\n// and now we have r in terms of a single unknown x. Plugging this into\n// xp = x * d we have a 5th order polynomial in x that we can solve with an\n// iterative solver.\nvoid RadialUndistortPoint(const Eigen::Vector2d& distorted_point,\n                          const double radial_distortion1,\n                          const double radial_distortion2,\n                          Eigen::Vector2d* undistorted_point) {\n  const double kMinRadius = 1e-5;\n  const double kEpsilon = 1e-8;\n  const int kMaxIter = 10;\n\n  if (std::max(std::abs(distorted_point.x()), std::abs(distorted_point.y())) <\n      kMinRadius) {\n    *undistorted_point = distorted_point;\n    return;\n  }\n\n  // Choose which variable we solve around to improve stability.\n  if (std::abs(distorted_point.x()) > std::abs(distorted_point.y())) {\n    const double point_ratio = distorted_point.y() / distorted_point.x();\n    const double r_sq = 1 + point_ratio * point_ratio;\n    Eigen::VectorXd quintic_polynomial(6);\n    quintic_polynomial(0) = radial_distortion2 * r_sq * r_sq;\n    quintic_polynomial(1) = 0;\n    quintic_polynomial(2) = radial_distortion1 * r_sq;\n    quintic_polynomial(3) = 0;\n    quintic_polynomial(4) = 1;\n    quintic_polynomial(5) = -distorted_point.x();\n\n    undistorted_point->x() = FindRootIterativeLaguerre(\n        quintic_polynomial, distorted_point.x(), kEpsilon, kMaxIter);\n    undistorted_point->y() = point_ratio * undistorted_point->x();\n  } else {\n    const double point_ratio = distorted_point.x() / distorted_point.y();\n    const double r_sq = 1 + point_ratio * point_ratio;\n    Eigen::VectorXd quintic_polynomial(6);\n    quintic_polynomial(0) = radial_distortion2 * r_sq * r_sq;\n    quintic_polynomial(1) = 0;\n    quintic_polynomial(2) = radial_distortion1 * r_sq;\n    quintic_polynomial(3) = 0;\n    quintic_polynomial(4) = 1;\n    quintic_polynomial(5) = -distorted_point.y();\n\n    undistorted_point->y() = FindRootIterativeLaguerre(\n        quintic_polynomial, distorted_point.y(), kEpsilon, kMaxIter);\n    undistorted_point->x() = point_ratio * undistorted_point->y();\n  }\n}\n\n}  // namespace theia\n", "meta": {"hexsha": "2e87eb6e21c33c0091b6ef5929fcebc535f123af", "size": 4427, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/sfm/camera/radial_distortion.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/radial_distortion.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/radial_distortion.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": 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": 40.6146788991, "max_line_length": 80, "alphanum_fraction": 0.6997967021, "num_tokens": 1120, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.46278912504144865}}
{"text": "/*\n@copyright Louis Dionne 2015\nDistributed under the Boost Software License, Version 1.0.\n(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n */\n\n#include <boost/hana/ext/std/ratio.hpp>\n\n#include <boost/hana/assert.hpp>\n#include <boost/hana/tuple.hpp>\n\n#include <laws/integral_domain.hpp>\n\n#include <ratio>\nusing namespace boost::hana;\n\n\nint main() {\n    auto ratios = make<Tuple>(\n          std::ratio<0>{}\n        , std::ratio<1, 3>{}\n        , std::ratio<1, 2>{}\n        , std::ratio<2, 6>{}\n        , std::ratio<3, 1>{}\n        , std::ratio<7, 8>{}\n        , std::ratio<3, 5>{}\n        , std::ratio<2, 1>{}\n    );\n\n    //////////////////////////////////////////////////////////////////////////\n    // IntegralDomain\n    //////////////////////////////////////////////////////////////////////////\n    {\n        // quot\n        {\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                quot(std::ratio<6>{}, std::ratio<4>{}),\n                std::ratio<6, 4>{}\n            ));\n\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                quot(std::ratio<3, 4>{}, std::ratio<5, 10>{}),\n                std::ratio<3*10, 4*5>{}\n            ));\n        }\n\n        // rem\n        {\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                rem(std::ratio<6>{}, std::ratio<4>{}),\n                std::ratio<0>{}\n            ));\n\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                rem(std::ratio<3, 4>{}, std::ratio<5, 10>{}),\n                std::ratio<0>{}\n            ));\n        }\n\n        // laws\n        test::TestIntegralDomain<ext::std::Ratio>{ratios};\n    }\n}\n", "meta": {"hexsha": "1454d033ffd38ba3625ef6509702988909fb438c", "size": 1611, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/ext/std/ratio/integral_domain.cpp", "max_stars_repo_name": "josephwinston/hana", "max_stars_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/ext/std/ratio/integral_domain.cpp", "max_issues_repo_name": "josephwinston/hana", "max_issues_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/ext/std/ratio/integral_domain.cpp", "max_forks_repo_name": "josephwinston/hana", "max_forks_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.171875, "max_line_length": 78, "alphanum_fraction": 0.4338919926, "num_tokens": 410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.46278912504144865}}
{"text": "\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/boost/graph/split_graph_into_polylines.h>\n\n#include <boost/graph/adjacency_list.hpp>\n\n#include <map>\n#include <vector>\n\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\ntypedef K::Point_2 Point_2;\n\n\ntypedef boost::adjacency_list<boost::vecS, boost::setS, boost::undirectedS, Point_2 > Graph;\n\ntypedef boost::graph_traits<Graph>::vertex_descriptor vertex_descriptor;\n\ntypedef std::map<Point_2, vertex_descriptor> Point_vertex_map;\n\ntypedef std::vector<Point_2> Polyline_2;\n\n\n// inserts a polyline into a graph\nvoid insert(const std::vector<Point_2>& poly, Graph& graph, Point_vertex_map& pvmap)\n{\n    vertex_descriptor u = boost::graph_traits<Graph>::null_vertex();\n    vertex_descriptor v;\n    for (std::size_t i = 0; i < poly.size(); i++) {\n        // check if the point is not yet in the graph\n        if (pvmap.find(poly[i]) == pvmap.end()) {\n            v = add_vertex(graph);\n            pvmap[poly[i]] = v;\n        }\n        else {\n            v = pvmap[poly[i]];\n        }\n        graph[v] = poly[i];  // associate the point to the vertex\n        if (i != 0) {\n            add_edge(u, v, graph);\n        }\n        u = v;\n    }\n}\n\ntemplate <typename Graph>\nstruct Polyline_visitor\n{\n  std::list<Polyline_2>& polylines;\n  const Graph& points_pmap;\n\n  Polyline_visitor(std::list<Polyline_2>& lines,\n                   const Graph& points_property_map)\n    : polylines(lines),\n      points_pmap(points_property_map)\n  {}\n\n  void start_new_polyline()\n  {\n    Polyline_2 V;\n    polylines.push_back(V);\n  }\n\n  void add_node(typename boost::graph_traits<Graph>::vertex_descriptor vd)\n  {\n    Polyline_2& polyline = polylines.back();\n    polyline.push_back(points_pmap[vd]);\n  }\n\n  void end_polyline()\n  {}\n\n};\n\n\nint main()\n{\n  Polyline_2 polyA = { Point_2(0,0), Point_2(1,0), Point_2(2,0), Point_2(3,0), Point_2(4,0)};\n  Polyline_2 polyB = { Point_2(1,-1), Point_2(1,0), Point_2(2,0), Point_2(2,1), Point_2(2,2) };\n\n  Graph graph;\n  Point_vertex_map pvmap;\n\n  insert(polyA, graph, pvmap);\n  insert(polyB, graph, pvmap);\n\n  std::list<Polyline_2> polylines;\n  Polyline_visitor<Graph> polyline_visitor(polylines, graph);\n\n  CGAL::split_graph_into_polylines( graph,\n                                    polyline_visitor);\n\n\n  for(std::list<Polyline_2>::iterator it = polylines.begin(); it!= polylines.end(); ++it){\n     Polyline_2& poly = *it;\n     std::size_t n;\n     if(poly.front() == poly.back()){\n       std::cout << \"POLYGON\" << std::endl;\n       n = poly.size() -1;\n     }else{\n       std::cout << \"POLYLINE\" << std::endl;\n       n = poly.size();\n     }\n     for(std::size_t j=0; j < n; j++){\n       std::cout << poly[j] << std::endl;\n     }\n     std::cout << std::endl;\n   }\n\n  return 0;\n\n}\n", "meta": {"hexsha": "9c13a2d03077c296f7689f5ad41523a793acba0a", "size": 2788, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "BGL/test/BGL/test_split.cpp", "max_stars_repo_name": "ffteja/cgal", "max_stars_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 3227.0, "max_stars_repo_stars_event_min_datetime": "2015-03-05T00:19:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:20:35.000Z", "max_issues_repo_path": "BGL/test/BGL/test_split.cpp", "max_issues_repo_name": "ffteja/cgal", "max_issues_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 5574.0, "max_issues_repo_issues_event_min_datetime": "2015-03-05T00:01:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:08:11.000Z", "max_forks_repo_path": "BGL/test/BGL/test_split.cpp", "max_forks_repo_name": "ffteja/cgal", "max_forks_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1274.0, "max_forks_repo_forks_event_min_datetime": "2015-03-05T00:01:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:47:56.000Z", "avg_line_length": 24.6725663717, "max_line_length": 95, "alphanum_fraction": 0.6287661406, "num_tokens": 807, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.46278912504144865}}
{"text": "#include <CGAL/Simple_cartesian.h>\n#include <CGAL/Surface_mesh.h>\n\n#include <boost/graph/kruskal_min_spanning_tree.hpp>\n\n#include <iostream>\n#include <fstream>\n#include <list>\n\ntypedef CGAL::Simple_cartesian<double>                       Kernel;\ntypedef Kernel::Point_3                                      Point;\ntypedef CGAL::Surface_mesh<Point>                            Mesh;\n\ntypedef boost::graph_traits<Mesh>::vertex_descriptor vertex_descriptor;\ntypedef boost::graph_traits<Mesh>::vertex_iterator   vertex_iterator;\ntypedef boost::graph_traits<Mesh>::edge_descriptor   edge_descriptor;\n\nvoid kruskal(const Mesh& sm)\n{\n   // We use the default edge weight which is the squared length of the edge\n\n  std::list<edge_descriptor> mst;\n\n  boost::kruskal_minimum_spanning_tree(sm,\n                                       std::back_inserter(mst));\n\n  std::cout << \"#VRML V2.0 utf8\\n\"\n    \"Shape {\\n\"\n    \"  appearance Appearance {\\n\"\n    \"    material Material { emissiveColor 1 0 0}}\\n\"\n    \"    geometry\\n\"\n    \"    IndexedLineSet {\\n\"\n    \"      coord Coordinate {\\n\"\n    \"        point [ \\n\";\n\n  vertex_iterator vb,ve;\n  for(boost::tie(vb, ve) = vertices(sm); vb!=ve; ++vb){\n    std::cout <<  \"        \" << sm.point(*vb) << \"\\n\";\n  }\n\n  std::cout << \"        ]\\n\"\n               \"     }\\n\"\n    \"      coordIndex [\\n\";\n\n  for(std::list<edge_descriptor>::iterator it = mst.begin(); it != mst.end(); ++it)\n  {\n    edge_descriptor e = *it ;\n    vertex_descriptor s = source(e,sm);\n    vertex_descriptor t = target(e,sm);\n    std::cout << \"      \" << s << \", \" << t <<  \", -1\\n\";\n  }\n\n  std::cout << \"]\\n\"\n    \"  }#IndexedLineSet\\n\"\n    \"}# Shape\\n\";\n}\n\nint main(int argc, char** argv)\n{\n  Mesh sm;\n  if(argc < 2 || !CGAL::IO::read_polygon_mesh(argv[1], sm))\n  {\n    std::cerr << \"Invalid input file.\" << std::endl;\n    return EXIT_FAILURE;\n  }\n\n  kruskal(sm);\n\n  return 0;\n}\n", "meta": {"hexsha": "b18beb032daa863070615abe88d58730866c324e", "size": 1874, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Surface_mesh/examples/Surface_mesh/sm_kruskal.cpp", "max_stars_repo_name": "antoniospg/cgal", "max_stars_repo_head_hexsha": "2891c22fc7f64f680ac7e144407afe49f6425cb9", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-01-20T17:02:24.000Z", "max_stars_repo_stars_event_max_datetime": "2017-01-20T17:02:24.000Z", "max_issues_repo_path": "Surface_mesh/examples/Surface_mesh/sm_kruskal.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": "Surface_mesh/examples/Surface_mesh/sm_kruskal.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": 26.3943661972, "max_line_length": 83, "alphanum_fraction": 0.5741728922, "num_tokens": 505, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.46278912504144865}}
{"text": "/*\n    The Fitter is responsible for managing bookkeeping of the curves, their objectives\n    and correctly composing the sparse jacobian and residual vector used by the \n    non-linear least squares solver.\n*/\n#pragma once\n\n// polyvec\n#include <polyvec/curve-tracer/curve_objective.hpp>\n#include <polyvec/curve-tracer/curve_parametrization.hpp>\n#include <polyvec/curve-tracer/curve_constraint.hpp>\n\n// libc++\n#include <vector>\n#include <memory>\n\n// Eigen\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n#include <unsupported/Eigen/LevenbergMarquardt> // SparseFunctor\n\nNAMESPACE_BEGIN(polyvec)\n\n// Forward declarations\nclass GlobFitObjective;\nclass GlobFitCurve;\n\nstruct GlobFitter : public Eigen::SparseFunctor<double, int> {\npublic:\n\tGlobFitter() : Eigen::SparseFunctor<double, int>(0, 0) { }\n    void set_curves ( const std::vector<GlobFitCurveParametrization*>& );\n    void set_objectives ( const std::vector<GlobFitObjective*>& );\n\n\t//Adds hard constraints to the optimization problem. The following requirements must be\n\t//met for constraints  target = f(source):\n\t//  * target cannot be coupled to other parameters\n\t//  * target cannot be fixed\n\t//  * none of source can be a target of a constraint\t\n\tvoid set_constraints(const std::vector<GlobFitConstraint*>&);\n\n\t//Prepares the optimization process\n    void setup ( const int max_iterations );\n\n\t//returns the number of iterations\n    int run_fitter ( FILE* log_file, std::function<void ( int ) > callback );\n\t\n\tvoid report_errors( FILE* error_file );\n\n    int n_parameters();\n    int n_equations();\n    bool is_setup();\n\n    std::vector<GlobFitCurveParametrization*> get_curves();\n    std::vector<GlobFitObjective*> get_objectives();    \n\nprivate:\n\n\tvoid compute_objective_and_jacobian(Eigen::VectorXd& obj, Eigen::SparseMatrix<double>& dobj_dcurveparams); // + matrix \n\n\t//extracts the current set of variables from the current state of the curves\n\tEigen::VectorXd get_variables();\n\t\n\t//updates the curves with the given set of variables\n\tvoid set_variables(const Eigen::VectorXd&);\n\n\tint nextParameter = 0;\n    std::vector<GlobFitCurveParametrization*> _curves;\n\tstd::map< GlobFitCurveParametrization*, size_t> curve_to_index;\n\tstd::vector<GlobFitObjective*> _objectives;\n\tstd::vector<GlobFitConstraint*> _constraints;\n\tstd::vector<Eigen::VectorXd> constraint_gradients;\n\n    bool _is_setup = false;\n\n\t//id of the first equation of the i-th objective\n    std::vector<int> _xadj_equations = std::vector<int>();        \n\tstd::vector<std::vector<int>> variables_in_objective;\n    int _max_iterations;\n\n    Eigen::VectorXd _cached_params;\n    Eigen::VectorXd _cached_objective;\n    Eigen::SparseMatrix<double> _cached_jacobian;\n\n\tvoid check_derivatives();\n\n    // ============== API needed by Eigen Levenberg-Marquart\npublic:\n\n    int inputs();\n    int values();\n    int operator() ( const Eigen::VectorXd& x, Eigen::VectorXd& fvec );\n    int df ( const Eigen::VectorXd& x, Eigen::SparseMatrix<double>& fjac );\n};\n\nNAMESPACE_END (polyvec)", "meta": {"hexsha": "b97de1c9eb693ac1da68a0ac19257a82e0150c4a", "size": 2995, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/polyvec/curve-tracer/curve_solver.hpp", "max_stars_repo_name": "ShnitzelKiller/polyfit", "max_stars_repo_head_hexsha": "51ddc6365a794db1678459140658211cb78f65b1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2020-08-17T17:25:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T05:49:12.000Z", "max_issues_repo_path": "include/polyvec/curve-tracer/curve_solver.hpp", "max_issues_repo_name": "ShnitzelKiller/polyfit", "max_issues_repo_head_hexsha": "51ddc6365a794db1678459140658211cb78f65b1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-08-26T13:54:59.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-21T07:19:22.000Z", "max_forks_repo_path": "include/polyvec/curve-tracer/curve_solver.hpp", "max_forks_repo_name": "ShnitzelKiller/polyfit", "max_forks_repo_head_hexsha": "51ddc6365a794db1678459140658211cb78f65b1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-08-26T23:26:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-04T09:06:07.000Z", "avg_line_length": 31.5263157895, "max_line_length": 120, "alphanum_fraction": 0.7348914858, "num_tokens": 722, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.46278911859480326}}
{"text": "#include \"Chapter3_SparseLinearAlgebra/Section1_SparseMatrixManipulations.hpp\"\n#include <Eigen/Geometry>\nvoid TestChapter3Section1()\n{\n        Chapter3_SparseLinearAlgebra::Section1_SparseMatrixManipulations::FirstExample();\n}\n\nvoid TestChapter3Section2()\n{\n        \n        Chapter3_SparseLinearAlgebra::Section1_SparseMatrixManipulations::TheSparseMatrixClass();\n}\n\nint main()\n{\n        //build pass\n        TestChapter3Section1();   // \u4f1a\u751f\u6210\u4e00\u5f20\u56fe\u7247\uff0ctitiled  \"result.bmp\"\n\n        TestChapter3Section2();\n        return 0;\n}", "meta": {"hexsha": "caed3e0fb26c902dd0df413be64719580f5ec1fe", "size": 521, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ICP/EigenChineseDocument-master/Eigen/chapter3_test.cpp", "max_stars_repo_name": "Yihua-Ni/Tools", "max_stars_repo_head_hexsha": "b40c24b0b2a7025f13182fc5ed5bfcf63b389585", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ICP/EigenChineseDocument-master/Eigen/chapter3_test.cpp", "max_issues_repo_name": "Yihua-Ni/Tools", "max_issues_repo_head_hexsha": "b40c24b0b2a7025f13182fc5ed5bfcf63b389585", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ICP/EigenChineseDocument-master/Eigen/chapter3_test.cpp", "max_forks_repo_name": "Yihua-Ni/Tools", "max_forks_repo_head_hexsha": "b40c24b0b2a7025f13182fc5ed5bfcf63b389585", "max_forks_repo_licenses": ["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.8095238095, "max_line_length": 97, "alphanum_fraction": 0.7332053743, "num_tokens": 131, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.603931819468636, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.4627891108928307}}
{"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 \"Utils/Geometry/StructuralCompletion.h\"\n#include <Eigen/Geometry>\n\nnamespace Scine {\nnamespace Utils {\n\nvoid StructuralCompletion::generate3TetrahedronCornersFrom1Other(const Eigen::Vector3d& v1, Eigen::Ref<Eigen::Vector3d> v2,\n                                                                 Eigen::Ref<Eigen::Vector3d> v3,\n                                                                 Eigen::Ref<Eigen::Vector3d> v4) {\n  /*\n   * Generate a vector perpendicular to the given one and then perform rotation around this vector to generate v2, then\n   * rotate v2 around v1 to generate v3 and v4.\n   */\n\n  // Get a perpendicular vector;\n  Eigen::Vector3d perpendicularVector = v1.cross(Eigen::Vector3d(1, 0, 0));\n  // Check that it was different enough from {1,0,0}; if not, create it from {0,1,0}\n  if (perpendicularVector.squaredNorm() < 0.00001) {\n    perpendicularVector = v1.cross(Eigen::Vector3d(0, 1, 0));\n  }\n  perpendicularVector.normalize();\n\n  Eigen::AngleAxisd t(tetrahedronAngle, perpendicularVector);\n  auto R = t.toRotationMatrix();\n  v2 = R * v1;\n  double ang2 = 120.0 * Constants::rad_per_degree;\n  Eigen::AngleAxisd t2(ang2, v1);\n  R = t2.toRotationMatrix();\n  v3 = R * v2;\n  v4 = R * v3;\n}\n\nvoid StructuralCompletion::generate2TetrahedronCornersFrom2Others(const Eigen::Vector3d& v1, const Eigen::Vector3d& v2,\n                                                                  Eigen::Ref<Eigen::Vector3d> v3,\n                                                                  Eigen::Ref<Eigen::Vector3d> v4) {\n  /*\n   * Generate the vector a, which is in the middle between v1 and v2, and the vector b, which is perpendicular to a but\n   * in the same plane as v1 and v2, and then rotate a around b to generate v3 and v4.\n   */\n\n  Eigen::Vector3d a = (v1 + v2).normalized();\n  Eigen::Vector3d b = (v2 - v1).normalized();\n\n  double angle = (360 * Constants::rad_per_degree - tetrahedronAngle) / 2;\n  Eigen::AngleAxisd t(angle, b);\n  auto R = t.toRotationMatrix();\n  v3 = R * a;\n  v4 = R * v3;\n}\n\nvoid StructuralCompletion::generate1TetrahedronCornerFrom3Others(const Eigen::Vector3d& v1, const Eigen::Vector3d& v2,\n                                                                 const Eigen::Vector3d& v3, Eigen::Ref<Eigen::Vector3d> v4) {\n  Eigen::Vector3d res = -(v1 + v2 + v3);\n  // check that the three vectors were non-planar enough\n  if (res.squaredNorm() < 0.4 * 0.4) {\n    res = v1.cross(v2);\n  }\n\n  v4 = res.normalized();\n}\n\nvoid StructuralCompletion::generate2TriangleCornersFrom1Other(const Eigen::Vector3d& v1, Eigen::Ref<Eigen::Vector3d> v2,\n                                                              Eigen::Ref<Eigen::Vector3d> v3) {\n  /*\n   * Generate a vector perpendicular to the given one and then perform rotation around this vector to generate v2 and\n   * v3.\n   */\n\n  // Get a perpendicular vector;\n  auto perpendicularVector = v1.cross(Eigen::Vector3d(1, 0, 0));\n  // Check that it was different enough from {1,0,0}; if not, create it from {0,1,0}\n  if (perpendicularVector.squaredNorm() < 0.00001) {\n    perpendicularVector = v1.cross(Eigen::Vector3d(0, 1, 0));\n  }\n  perpendicularVector.normalize();\n\n  Eigen::AngleAxisd t(120 * Constants::rad_per_degree, perpendicularVector);\n  auto R = t.toRotationMatrix();\n  v2 = R * v1;\n  v3 = R * v2;\n}\n\nvoid StructuralCompletion::generate1TriangleCornerFrom2Others(const Eigen::Vector3d& v1, const Eigen::Vector3d& v2,\n                                                              Eigen::Ref<Eigen::Vector3d> v3) {\n  v3 = -(v1 + v2).normalized();\n}\n\nconstexpr double StructuralCompletion::tetrahedronAngle;\n\n} /* namespace Utils */\n} /* namespace Scine */\n", "meta": {"hexsha": "600b58785a5b9471f3fd2583cc77bfcee1f2b2e6", "size": 3867, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Utils/Utils/Geometry/StructuralCompletion.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/Geometry/StructuralCompletion.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/Geometry/StructuralCompletion.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.4591836735, "max_line_length": 125, "alphanum_fraction": 0.6190845617, "num_tokens": 1057, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4627623023970424}}
{"text": "#include <iostream>\n#include <fstream>\n\n#include <opencv2/opencv.hpp>\n#include <boost/format.hpp>  // for formating strings\n#include <sophus/se3.hpp>\n\n#include \"config.hpp\"\n\nusing namespace std;\n\ntypedef vector<Sophus::SE3d, Eigen::aligned_allocator<Sophus::SE3d>> TrajectoryType;\ntypedef Eigen::Matrix<double, 6, 1> Vector6d;\n\nvoid showPointCloud(const vector<Vector6d, Eigen::aligned_allocator<Vector6d>> &pointcloud);\n\nint main(int argc, char **argv) {\n    vector<cv::Mat> colorImgs, depthImgs;  // \u5f69\u8272\u56fe\u548c\u6df1\u5ea6\u56fe\n    TrajectoryType poses;                  // \u76f8\u673a\u4f4d\u59ff\n\n    ifstream fin((string(CURREXAMPLE_ROOT) + string(\"/pose.txt\")).c_str());\n    if (!fin) {\n        cerr << \"\u8bf7\u5728\u6709pose.txt\u7684\u76ee\u5f55\u4e0b\u8fd0\u884c\u6b64\u7a0b\u5e8f\" << endl;\n        return 1;\n    }\n\n    for (int i = 0; i < 5; i++) {\n        boost::format fmt((string(CURREXAMPLE_ROOT) + string(\"/%s/%d.%s\")).c_str());  //\u56fe\u50cf\u6587\u4ef6\u683c\u5f0f\n        colorImgs.push_back(cv::imread((fmt % \"color\" % (i + 1) % \"png\").str()));\n        depthImgs.push_back(cv::imread((fmt % \"depth\" % (i + 1) % \"pgm\").str(), -1));  // \u4f7f\u7528-1\u8bfb\u53d6\u539f\u59cb\u56fe\u50cf\n\n        double data[7] = {0};\n        for (auto &d : data)\n            fin >> d;\n        Sophus::SE3d pose(Eigen::Quaterniond(data[6], data[3], data[4], data[5]),\n                          Eigen::Vector3d(data[0], data[1], data[2]));\n        poses.push_back(pose);\n    }\n\n    // \u8ba1\u7b97\u70b9\u4e91\u5e76\u62fc\u63a5\n    // \u76f8\u673a\u5185\u53c2\n    double cx         = 325.5;\n    double cy         = 253.5;\n    double fx         = 518.0;\n    double fy         = 519.0;\n    double depthScale = 1000.0;\n    vector<Vector6d, Eigen::aligned_allocator<Vector6d>> pointcloud;\n    pointcloud.reserve(1000000);\n\n    for (int i = 0; i < 5; i++) {\n        cout << \"\u8f6c\u6362\u56fe\u50cf\u4e2d: \" << i + 1 << endl;\n        cv::Mat color  = colorImgs[i];\n        cv::Mat depth  = depthImgs[i];\n        Sophus::SE3d T = poses[i];\n        for (int v = 0; v < color.rows; v++)\n            for (int u = 0; u < color.cols; u++) {\n                unsigned int d = depth.ptr<unsigned short>(v)[u];  // \u6df1\u5ea6\u503c\n                if (d == 0) continue;                              // \u4e3a0\u8868\u793a\u6ca1\u6709\u6d4b\u91cf\u5230\n                Eigen::Vector3d point;\n                point[2]                   = double(d) / depthScale;\n                point[0]                   = (u - cx) * point[2] / fx;\n                point[1]                   = (v - cy) * point[2] / fy;\n                Eigen::Vector3d pointWorld = T * point;\n\n                Vector6d p;\n                p.head<3>() = pointWorld;\n                p[5]        = color.data[v * color.step + u * color.channels()];      // blue\n                p[4]        = color.data[v * color.step + u * color.channels() + 1];  // green\n                p[3]        = color.data[v * color.step + u * color.channels() + 2];  // red\n                pointcloud.push_back(p);\n            }\n    }\n\n    cout << \"\u70b9\u4e91\u5171\u6709\" << pointcloud.size() << \"\u4e2a\u70b9.\" << endl;\n    showPointCloud(pointcloud);\n    return 0;\n}\n\n/*******************************************************************************************/\n#include \"common/glfwEntry.hpp\"\nX3D::X3DGate x3dGate;\n\nvoid showPointCloud(const vector<Vector6d, Eigen::aligned_allocator<Vector6d>> &pointcloud) {\n    if (pointcloud.empty()) {\n        cerr << \"Point cloud is empty!\" << endl;\n        return;\n    }\n\n    GLFWwindow *win = glfwEntry::initialize(\"stereoVision\", 1024, 768, 0.2, 0.3, 0.4, &x3dGate);\n\n    vector<float> vertPos;\n    vector<float> vertColor;\n    uint32_t ptsObjID = 0;\n\n    vertPos.resize(pointcloud.size() * 3);\n    vertColor.resize(vertPos.size());\n\n    uint32_t idx = 0;\n    for (auto &p : pointcloud) {\n        vertPos[idx * 3]     = p[0];\n        vertPos[idx * 3 + 1] = p[1];\n        vertPos[idx * 3 + 2] = p[2];\n\n        vertColor[idx * 3]     = p[3] / 255.0;\n        vertColor[idx * 3 + 1] = p[4] / 255.0;\n        vertColor[idx * 3 + 2] = p[5] / 255.0;\n\n        ++idx;\n    }\n\n    x3dGate.AddPoints(\"userPoints\", vertPos, vertColor, 5,\n                      {1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},\n                      [&](uint32_t objID) {\n                          if (ptsObjID == 0) {\n                              ptsObjID = objID;\n                          }\n                      });\n\n    bool show_debug = false;\n    while (!glfwWindowShouldClose(win)) {\n        glfwEntry::beginFrame(win);\n\n        {\n            ImGui::Begin(\"Test info\");\n\n            ImGui::Text(\"Application average %.3f ms/frame (%.1f FPS)\", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);\n\n            if (ImGui::Button(\"Toggle debug\")) {\n                x3dGate.ToggleDebug();\n                show_debug = !show_debug;\n            }\n            ImGui::End();\n        }\n\n        glfwEntry::endFrame(win);\n    }\n\n    x3dGate.DeleteObject(ptsObjID, [](bool ret) {});\n\n    glfwEntry::finalize();\n\n    return;\n}", "meta": {"hexsha": "4e19de9fe8abb5265e5154d87c87bf9f1598a2b8", "size": 4791, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "visualExamples/ch5/rgbd/joinMap.cpp", "max_stars_repo_name": "kiorisyshen/learning_slambook", "max_stars_repo_head_hexsha": "9f47cca96b5c555ac854d08f05f5ebefe3d78cc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-08T23:02:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-08T23:02:22.000Z", "max_issues_repo_path": "visualExamples/ch5/rgbd/joinMap.cpp", "max_issues_repo_name": "kiorisyshen/learning_slambook", "max_issues_repo_head_hexsha": "9f47cca96b5c555ac854d08f05f5ebefe3d78cc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "visualExamples/ch5/rgbd/joinMap.cpp", "max_forks_repo_name": "kiorisyshen/learning_slambook", "max_forks_repo_head_hexsha": "9f47cca96b5c555ac854d08f05f5ebefe3d78cc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-11-08T23:02:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-08T23:02:29.000Z", "avg_line_length": 33.5034965035, "max_line_length": 134, "alphanum_fraction": 0.4938426216, "num_tokens": 1476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680199891789, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.46259186869307084}}
{"text": "#pragma once\n\n#include <vector>\n#include <set>\n#include <list>\n#include <string>\n#include <limits>\n#include <fstream>\n#include <Eigen/Eigenvalues>\n#include <open3d/geometry/BoundingVolume.h>\n#include <open3d/geometry/Geometry3D.h>\n#include <open3d/geometry/PointCloud.h>\n#include <open3d/geometry/Octree.h>\n#include <open3d/geometry/KDTreeFlann.h>\n#include <open3d/utility/Console.h>\n#include <open3d/io/PointCloudIO.h>\n#include \"json.hpp\"\n#include \"glasbey_lut.hpp\"\n\nnamespace open3d {\n\nnamespace geometry {\n\nclass SuperVoxel;\n\nusing nlohmann::json;\n\n#define ASSERT(p) if(!(p)) {std::cout << __FILE__ \":\" << __LINE__ << \" \" #p << std::endl; throw #p;}\n\nstatic inline std::set<int> envvar(const char* name)\n{\n    const char* v = std::getenv(name);\n    if (v) {\n\t\tstd::string s(v);\n\t\tstd::set<int> ret;\n\t\tstd::stringstream ss(s);\n\t\tstd::string item;\n\t\twhile (getline(ss, item, ',')) {\n\t\t\tif (!item.empty()) {\n\t\t\t\tret.insert(stoi(item));\n\t\t\t}\n\t\t}\n\t\treturn ret;\n\t}\n    return std::set<int>();\n}\n\nstatic inline int envvar(const char* name, int def)\n{\n    const char* v = std::getenv(name);\n    if (v) {\n        return std::stoi(v);\n    }\n    return def;\n}\n\nstatic inline double envvar(const char* name, double def)\n{\n    const char* v = std::getenv(name);\n    if (v) {\n        return std::stof(v);\n    }\n    return def;\n}\n\nstatic inline json vec2json(const Eigen::Vector3d v)\n{\n    return json::array({v(0), v(1), v(2)});\n}\n\n\nstatic inline Eigen::Vector3d rgb2xyz(const Eigen::Vector3d& rgb) {\n    Eigen::Vector3d srgb;\n    srgb(0)  = rgb(0) > 0.04045 ? std::pow((rgb(0) + 0.055) / 1.055, 2.4) : rgb(0) / 12.92;\n    srgb(1)  = rgb(1) > 0.04045 ? std::pow((rgb(1) + 0.055) / 1.055, 2.4) : rgb(1) / 12.92;\n    srgb(2)  = rgb(2) > 0.04045 ? std::pow((rgb(2) + 0.055) / 1.055, 2.4) : rgb(2) / 12.92;\n    return Eigen::Vector3d(\n        (srgb[0] * 0.4124) + (srgb[1] * 0.3576) + (srgb[2] * 0.1805),\n        (srgb[0] * 0.2126) + (srgb[1] * 0.7152) + (srgb[2] * 0.0722),\n        (srgb[0] * 0.0193) + (srgb[1] * 0.1192) + (srgb[2] * 0.9505)\n    );\n}\n\nstatic inline Eigen::Vector3d xyz2lab(const Eigen::Vector3d& xyz) {\n    Eigen::Vector3d xyzD;\n    xyzD(0) = xyz(0) > 0.008856 ? std::cbrt(xyz(0)) : 7.787 * xyz(0) + 16 / 116;\n    xyzD(1) = xyz(1) > 0.008856 ? std::cbrt(xyz(1)) : 7.787 * xyz(1) + 16 / 116;\n    xyzD(2) = xyz(2) > 0.008856 ? std::cbrt(xyz(2)) : 7.787 * xyz(2) + 16 / 116;\n    return Eigen::Vector3d((116.0 * xyzD[1]) - 16.0, 500.0 * (xyzD[0] - xyzD[1]), 200.0 * (xyzD[1] - xyzD[2]));\n}\n\nstatic inline Eigen::Vector3d rgb2lab(const Eigen::Vector3d& rgb) {\n    return xyz2lab(rgb2xyz(rgb));\n}\n\n\n// average filter of region property\nstruct RegionProperty {\npublic:\n    RegionProperty()\n        : color_(Eigen::Vector3d::Zero())\n        , point_(Eigen::Vector3d::Zero())\n        , normal_(Eigen::Vector3d::Zero())\n        , num_of_points_(0)\n        {}\n\n    RegionProperty(const Eigen::Vector3d& color, const Eigen::Vector3d& point, const Eigen::Vector3d& normal)\n        : color_(color)\n        , point_(point)\n        , normal_(normal)\n        , num_of_points_(1)\n        {}\n\n    inline RegionProperty operator+(const RegionProperty& rhs) const\n    {\n        RegionProperty ret;\n        ret.color_  = color_  + rhs.color_ ;\n        ret.point_  = point_  + rhs.point_ ;\n        ret.normal_ = normal_ + rhs.normal_;\n        ret.num_of_points_ = num_of_points_ + rhs.num_of_points_;\n        return ret;\n    }\n\n    inline RegionProperty operator-(const RegionProperty& rhs) const\n    {\n        RegionProperty ret;\n        ret.color_  = color_  - rhs.color_ ;\n        ret.point_  = point_  - rhs.point_ ;\n        ret.normal_ = normal_ - rhs.normal_;\n        ret.num_of_points_ = num_of_points_ - rhs.num_of_points_;\n        return ret;\n    }\n\n    inline RegionProperty Normalize()\n    {\n        RegionProperty ret;\n        ASSERT(num_of_points_ > 0);\n        ret.color_  = color_ / num_of_points_;\n        ret.point_  = point_ / num_of_points_;\n        ret.normal_ = normal_.normalized();\n        ret.num_of_points_ = num_of_points_;\n        return ret;\n    }\n\n\n    std::string toString() const\n    {\n        std::stringstream ss;\n        ss << \"p [\" << point_(0) << \", \" << point_(1) << \", \" << point_(2) << \"]\";\n        ss << \"n [\" << normal_(0) << \", \" << normal_(1) << \", \" << normal_(2) << \"]\";\n        ss << \"c [\" << color_(0) << \", \" << color_(1) << \", \" << color_(2) << \"]\";\n        ss << \"n :\" << num_of_points_;\n        return ss.str();\n    }\n\n    inline double DistanceToPlane(const Eigen::Vector3d &p) const\n    {\n        return std::abs(normal_.dot(point_ - p));\n    }\n\npublic:\n    Eigen::Vector3d color_;\n    Eigen::Vector3d point_;\n    Eigen::Vector3d normal_;\n    int num_of_points_;\n\n};\n\n\nstd::function<double(const RegionProperty&, const RegionProperty&)> DistanceFunctionL1(double lambda, double mu, double epsilon)\n{\n    std::function<double(const RegionProperty&, const RegionProperty&)> f\n    = [lambda, mu, epsilon](const RegionProperty& r1, const RegionProperty& r2) -> double{\n        double Dc = (r1.color_ - r2.color_).norm();\n        double Ds = (r1.point_ - r2.point_).norm();\n        double Dn = 1.0f - std::abs(r1.normal_.dot(r2.normal_));\n        return  lambda * Dc + mu * Ds + epsilon * Dn;\n    };\n    return f;\n}\n\n\nstd::function<double(const RegionProperty&, const RegionProperty&)> DistanceFunctionLInf(double lambda, double mu, double epsilon)\n{\n    std::function<double(const RegionProperty&, const RegionProperty&)> f\n    = [lambda, mu, epsilon](const RegionProperty& r1, const RegionProperty& r2) -> double{\n        double Dc = (r1.color_ - r2.color_).norm();\n        double Ds = (r1.point_ - r2.point_).norm();\n        double Dn = 1.0f - std::abs(r1.normal_.dot(r2.normal_));\n        return  std::max(std::max(lambda * Dc, mu * Ds), epsilon * Dn);\n    };\n    return f;\n}\n\n\ntemplate <typename T>\nvoid BFS(T root, const std::vector<std::set<T> > &adj, int max_depth, const std::function<bool(const T&)> &f) {\n\n    std::set<T> visited;\n    std::list<T> leaves;\n\n    leaves.push_back(root);\n    int depth = 0;\n\n    while (leaves.size() > 0) {\n\n        if (depth == max_depth) {\n            return;\n        }\n\n        std::list<T> new_leaves;\n\n        for (auto leaf : leaves) {\n\n            bool keep_searching = f(leaf);\n\n            if (!keep_searching) {\n                continue;\n            }\n\n            for (auto neighbor : adj[leaf]) {\n                if (visited.find(neighbor) == visited.end()) {\n                    new_leaves.push_back(neighbor);\n                    visited.insert(neighbor);\n                }\n            }\n        }\n\n        leaves = new_leaves;\n        depth++;\n    }\n}\n\nstatic Eigen::Vector3d FlipDirection(const Eigen::Vector3d &target, const Eigen::Vector3d reference = Eigen::Vector3d(0, 0, 1), const Eigen::Vector3d second_reference = Eigen::Vector3d(0, 1, 0))\n{\n    if (target.dot(reference) < 0) {\n        return -target;\n    }\n    if (target.dot(reference) > 0) {\n        return target;\n    }\n    if (target.dot(second_reference) < 0) {\n        return -target;\n    }\n    return target;\n}\n\n\n\nstatic Eigen::Vector3d EstimateNormal(\n        const geometry::PointCloud& pc,\n        const std::vector<int>& indices,\n        Eigen::Vector3d &eigenvalues)\n{\n    if (indices.size() < 3) {\n        return Eigen::Vector3d::Zero();\n    }\n\n    Eigen::Matrix3d covariance = utility::ComputeCovariance(pc.points_, indices);\n\n    Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> solver;\n    solver.computeDirect(covariance, Eigen::ComputeEigenvectors);\n\n    eigenvalues = solver.eigenvalues();\n\n    return FlipDirection(solver.eigenvectors().col(0));\n}\n\nusing GridKey = int64_t;\nusing PointID = int;\nusing VoxelID = int;\nusing SuperVoxelID = int;\n\n\nstruct SuperVoxel {\npublic:\n    RegionProperty prop_;\n    VoxelID seed_;\n};\n\n\nstruct Edge {\npublic:\n    Edge(SuperVoxelID svid1, SuperVoxelID svid2, double d) : svid1(svid1), svid2(svid2), d(d) {\n        ASSERT(svid1 < svid2);\n        ASSERT(d >= 0);\n    }\n    SuperVoxelID svid1;\n    SuperVoxelID svid2;\n    double d;\n};\n\nstruct EdgeCompare {\npublic:\n    inline bool operator()(const Edge& a, const Edge& b) const\n    {\n        return a.d < b.d;\n    }\n};\n\n\n/// \\class EVCCS\n///\n/// \\brief Edge-removal Voxel Cloud Connectivity Segmentation.\n///\nclass EVCCS\n{\npublic:\n    using LabelType = unsigned int;\n    static const SuperVoxelID NO_LABEL = -1;\n    static const VoxelID NO_VOXEL = -1;\n\npublic:\n    /// \\brief Default Constructor.\n    EVCCS() { };\n\n    ~EVCCS() { }\n\n    // vxl_size : resolution.\n    bool Execute(const PointCloud &pc, double vxl_size, int r_seed, int iteration_num, std::function<double(const RegionProperty&, const RegionProperty&)> f, double maxd, double r_adj)\n    {\n        utility::LogInfo(\"EVCCS: start\");\n\n        if ( !pc.HasColors() ) {\n           utility::LogWarning(\"input point cloud does'nt have colors!\");\n           return false;\n        }\n\n        ASSERT(vxl_size > 0);\n        ASSERT(r_seed > 1);\n\n        int r_search = (r_seed+1) / 2;\n\n        Voxelize(pc, vxl_size);\n\n        ScatterSeeds(vxl_size, r_seed, r_search);\n\n        FilterOutSeedsInSparseArea(vxl_size, r_search);\n\n        //ShiftSeeds(r_search);\n\n        Clustering(iteration_num, f, maxd, r_seed, r_adj);\n\n        utility::LogInfo(\"EVCCS: end\");\n        return true;\n    }\n\n    //debug\npublic:\n    //std::shared_ptr<PointCloud> CreateLabeledVoxelCloud(const std::vector<Eigen::Vector3d>& lut)\n    //{\n    //    Eigen::Vector3d nolabelColor(0, 0, 0);\n    //    Eigen::Vector3d edgeColor(1, 1, 1);\n    //    Eigen::Vector3d removalColor(1, 1, 1);\n    //    auto pc = std::make_shared<PointCloud>();\n    //    for(unsigned int i=0; i<vc_.points_.size(); i++) {\n    //        if (static_cast<int>(i) == envvar(\"DEBUG_IDX\", -1)) {\n    //            std::cout << vc_.points_[i] << std::endl;\n    //            if (vlabel_[i] == NO_LABEL) {\n    //                std::cout << \"nolabel\" << std::endl;\n    //            } else {\n    //                std::cout << (lut[vlabel_[i] % lut.size()] * 255) << std::endl;\n    //            }\n    //        }\n    //        pc->points_.push_back(vc_.points_[i]);\n    //        pc->normals_.push_back(vc_.normals_[i]);\n    //        if (vlabel_[i] == NO_LABEL) {\n    //            pc->colors_.push_back(nolabelColor);\n    //        } else {\n    //            pc->colors_.push_back(lut[vlabel_[i] % lut.size()]);\n    //        }\n    //    }\n    //    for(unsigned int i=0; i<evc_.points_.size(); i++) {\n    //        pc->points_.push_back(evc_.points_[i]);\n    //        pc->normals_.push_back(evc_.normals_[i]);\n    //        pc->colors_.push_back(edgeColor);\n    //    }\n    //    for(unsigned int i=0; i<rvc_.points_.size(); i++) {\n    //        pc->points_.push_back(rvc_.points_[i]);\n    //        pc->normals_.push_back(rvc_.normals_[i]);\n    //        pc->colors_.push_back(removalColor);\n    //    }\n    //    return pc;\n    //}\n\n    //void PaintLabelColor(PointCloud &pc, const std::vector<Eigen::Vector3d>& lut, double r = 0.02)\n    //{\n    //    Eigen::Vector3d nolabelColor(0, 0, 0);\n    //    std::vector<int> vindices;\n    //    std::vector<double> vdistance2;\n\n    //    for(unsigned int i=0; i<pc.points_.size(); i++) {\n    //        // TODO use normal and color in edge/removed-voxel kdtrree\n    //        kdt_.SearchHybrid(pc.points_[i], r, 1, vindices, vdistance2);\n    //        if (vindices.size() > 0) {\n    //            ASSERT(vlabel_[vindices[0]] != NO_LABEL);\n    //            pc.colors_[i] = lut[vlabel_[vindices[0]] % lut.size()];\n    //        }\n    //    }\n    //}\n\n    //void DumpLabel(const PointCloud &pc, std::string filename, double r_adj)\n    //{\n    //        std::ofstream lo(filename, std::ios_base::binary);\n    //        std::vector<int> vindices;\n    //        std::vector<double> vdistance2;\n\n    //        for(unsigned int i=0; i<pc.points_.size(); i++) {\n    //            int label = NO_LABEL;\n    //            kdt_.SearchHybrid(pc.points_[i], r_adj, 1, vindices, vdistance2);\n    //            if (vindices.size() > 0) {\n    //                label = vlabel_[vindices[0]];\n    //            }\n    //            lo.write((const char*)&label, sizeof(label));\n    //        }\n    //}\n\n    SuperVoxelID Lookup(SuperVoxelID label, const std::vector<SuperVoxelID> &ltree, const std::vector<double> &dtree)\n    {\n        SuperVoxelID prev = label;\n        while (true) {\n            label = ltree[prev];\n            if (label == prev) {\n                break;\n            }\n            prev = label;\n        }\n        return prev;\n    }\n\n    void DumpLabeledPLY(const PointCloud &pc, std::string filename, const std::vector<SuperVoxelID> &ltree, const std::vector<double> &dtree, int min_point_num)\n    {\n        utility::LogInfo(\"EVCCS: DumpLabeledPLY start\");\n        {\n            std::ofstream o(filename, std::ios_base::binary);\n            if (o.is_open()) {\n                o << \"ply\" << std::endl;\n                o << \"format binary_little_endian 1.0\" << std::endl;\n                o << \"element vertex \" << pc.points_.size() << std::endl;\n                o << \"property float x\" << std::endl;\n                o << \"property float y\" << std::endl;\n                o << \"property float z\" << std::endl;\n                o << \"property uchar red\" << std::endl;\n                o << \"property uchar green\" << std::endl;\n                o << \"property uchar blue\" << std::endl;\n                o << \"property int32 label\" << std::endl;\n                o << \"property uchar lred\" << std::endl;\n                o << \"property uchar lgreen\" << std::endl;\n                o << \"property uchar lblue\" << std::endl;\n                o << \"end_header\" << std::endl;\n            } else {\n                std::cout << \"cannot open \" << filename << std::endl;\n                return;\n            }\n        }\n\n\t\tstd::vector<SuperVoxelID> lut(svxls_.size());\n\t\tfor (unsigned int i=0; i<lut.size(); i++) {\n\t\t\tlut[i] = Lookup(i, ltree, dtree);\n\t\t\t//std::cout << \"lut[\" << i << \"] : \" << lut[i] <<  \" : #\" <<mergedsvxls_[lut[i]].num_of_points_  << \" d:\" << dtree[lut[i]] << std::endl;\n\t\t}\n\n\t\tPointCloud big_vc;\n\t\tstd::vector<SuperVoxelID> big_label;\n\t\tfor (unsigned int i=0; i<vc_.points_.size(); i++ ) {\n\t\t\tauto label = lut[vlabel_[i]];\n\t\t\t//std::cout << \"vxl[\" << i << \"] : \" << vlabel_[i] << \" -> \" << label << \" : \" << mergedsvxls_[label].num_of_points_  << \" big:\" << (mergedsvxls_[label].num_of_points_ > min_point_num) << std::endl;\n\t\t\tif (mergedsvxls_[label].num_of_points_ > min_point_num) {\n\t\t\t\tbig_vc.points_.push_back(vc_.points_[i]);\n\t\t\t\tbig_label.push_back(label);\n\t\t\t}\n\t\t}\n\t\tKDTreeFlann big_kdt(big_vc);\n\n\n        {\n            std::set<int> targets = envvar(\"TARGET\");\n\t\t\tdouble k = envvar(\"TARGET_RED\", 0.5);\n            std::ofstream o(filename, std::ios_base::binary|std::ios_base::app);\n            std::vector<int> vindices;\n            std::vector<double> vdistance2;\n\n            for(unsigned int i=0; i<pc.points_.size(); i++) {\n                int label = NO_LABEL;\n                big_kdt.SearchKNN(pc.points_[i], 1, vindices, vdistance2);\n\t\t\t\tASSERT(vindices.size() > 0);\n\t\t\t\tlabel = big_label[vindices[0]];\n                for (int j=0; j<3; j++) {\n                    float x = pc.points_[i](j);\n                    o.write((const char*)&x, sizeof(x));\n                }\n                auto color = pc.colors_[i];\n                if (targets.find(label) != targets.end()) {\n                    //color(0) *= 0.5; \n                    color(1) *= k; \n                    color(2) *= k; \n                }\n                for (int j=0; j<3; j++) {\n                    unsigned char x = 255*color(j);\n                    o.write((const char*)&x, sizeof(x));\n                }\n                o.write((const char*)&label, sizeof(label));\n                auto labelcolor = GLASBEY_LUT[label % GLASBEY_LUT.size()];\n                for (int j=0; j<3; j++) {\n                    unsigned char x = 255 * labelcolor(j);\n                    o.write((const char*)&x, sizeof(x));\n                }\n            }\n        }\n        utility::LogInfo(\"EVCCS: DumpLabeledPLY end\");\n    }\n\n\n    void DumpSupervoxels(std::string filename)\n    {\n        json j;\n        for (unsigned int svid=0; svid<svxls_.size(); svid++) {\n            if (svxls_[svid]->seed_ == NO_VOXEL) {\n                continue;\n            }\n            ASSERT(svxls_[svid]->prop_.num_of_points_ > 0);\n            auto prop = svxls_[svid]->prop_.Normalize();\n            j[\"node\"][svid][\"numOfPoints\"] = prop.num_of_points_;\n            j[\"node\"][svid][\"color\"] = prop.color_;\n            j[\"node\"][svid][\"point\"] = prop.point_;\n            j[\"node\"][svid][\"normal\"] = prop.normal_;\n        }\n\n        std::ofstream o(filename);\n        if (o.is_open()) {\n            o << j;\n        } else {\n            std::cout << \"cannot open \" << filename << std::endl;\n        }\n\n    }\n\n    void CreateLabelTree(\n        std::vector<SuperVoxelID> &labeltree,\n        std::vector<double> &disttree,\n        std::function<double(const RegionProperty&, const RegionProperty&)> f,\n\t\tdouble  maxd\n    )\n    {\n        utility::LogInfo(\"EVCCS: LabelTree start\");\n\n\t\tmergedsvxls_.clear();\n        labeltree.clear();\n        disttree.clear();\n\n        for (SuperVoxelID svid=0; svid<svxls_.size(); svid++) {\n            if (svxls_[svid]->seed_ == NO_VOXEL) {\n                mergedsvxls_.push_back(RegionProperty());\n                labeltree.push_back(-1);\n            } else {\n                mergedsvxls_.push_back(svxls_[svid]->prop_);\n                labeltree.push_back(svid);\n            }\n            disttree.push_back(0);\n        }\n\n        auto svadj = svadj_;\n        std::multiset<Edge, EdgeCompare> edges;\n        edges.clear();\n        for (auto es : svadj) {\n            SuperVoxelID svid1 = es.first;\n            for (auto svid2 : es.second) {\n                if (svid1 >= svid2) {\n                    continue;\n                }\n                double d = f(mergedsvxls_[svid1], mergedsvxls_[svid2]);\n                edges.insert(Edge(svid1, svid2, d));\n                //std::cout << \"init edge \" << svid1 << \" - \" << svid2 << std::endl;\n            }\n        }\n\n        while (edges.size() > 0) {\n\n            auto e = edges.begin();\n            edges.erase(e);\n            auto svid1 = e->svid1;\n            auto svid2 = e->svid2;\n            ASSERT(svid1 <= labeltree[svid1]);\n            ASSERT(svid2 <= labeltree[svid2]);\n            //already merged\n            if (svid1 != labeltree[svid1] || svid2 != labeltree[svid2]) {\n                //std::cout << \"ignore \" << svid1 << \"(->\" <<  labeltree[svid1] << \") - \" << svid2 << \"(->\" << labeltree[svid2] << \")\" << std::endl;\n                //std::cout << \"ignoreDebug \" << svid1 << \" : \" << labeltree[svid1] << \" @ \" << &labeltree[svid1] << std::endl;\n                //std::cout << \"ignoreDebug \" << svid2 << \" : \" << labeltree[svid2] << \" @ \" << &labeltree[svid2] << std::endl;\n                continue;\n            }\n\t\t\tif (e->d > maxd) {\n\t\t\t\tbreak;\n\t\t\t}\n            SuperVoxelID newID = mergedsvxls_.size();\n            mergedsvxls_.push_back(mergedsvxls_[svid1] + mergedsvxls_[svid2]);\n\n            if (envvar(\"DUMP_LABELTREE\", 0)) {\n                std::cout << \"relabel \" << svid1 << \" (#\" << mergedsvxls_[svid1].num_of_points_ << \") + \" << svid2 << \" (#\" << mergedsvxls_[svid2].num_of_points_ << \") -> \" << newID << \" (#\" << mergedsvxls_[newID].num_of_points_ << \") : \" << e->d << std::endl;\n            }\n\n            labeltree[svid1] = newID;\n            labeltree[svid2] = newID;\n            labeltree.push_back(newID);\n            //std::cout << \"mergeDebug \" << svid1 << \" : \" << labeltree[svid1] << \" @ \" << &labeltree[svid1] << std::endl;\n            //std::cout << \"mergeDebug \" << svid2 << \" : \" << labeltree[svid2] << \" @ \" << &labeltree[svid2] << std::endl;\n            //std::cout << \"mergeDebug \" << newID << \" : \" << labeltree[newID] << \" @ \" << &labeltree[newID] << std::endl;\n            disttree.push_back(e->d);\n\n            svadj[newID] = std::set<SuperVoxelID>();\n\n            for (auto n1 : svadj[svid1] ) {\n                if (n1 == svid2) { continue; }\n                svadj[newID].insert(n1);\n                svadj[n1].erase(svid1);\n                svadj[n1].insert(newID);\n                //std::cout << \"adj : @\" << svid1 << \" \" << n1 << \"->\" << newID << std::endl;\n            }\n            svadj.erase(svid1);\n\n            for (auto n2 : svadj[svid2] ) {\n                if (n2 == svid1) { continue; }\n                svadj[newID].insert(n2);\n                svadj[n2].erase(svid2);\n                svadj[n2].insert(newID);\n                //std::cout << \"adj : @\" << svid2 << \" \" << n2 << \"->\" << newID << std::endl;\n            }\n            svadj.erase(svid2);\n\n            for (auto n : svadj[newID]) {\n                double d = f(mergedsvxls_[newID].Normalize(), mergedsvxls_[n].Normalize());\n                //std::cout << \"edge : \" << n << \" \" << newID << \" \" << d << std::endl;\n                edges.insert(Edge(n, newID, d));\n            }\n            newID++;\n        }\n        utility::LogInfo(\"EVCCS: LabelTree end\");\n    }\n\nprotected:\n\n    void Voxelize(const PointCloud &pc, double vxl_size, double size_expand = 0.01) {\n\n        utility::LogInfo(\"voxelize\");\n\n        Eigen::Array3d min_bound = pc.GetMinBound();\n        Eigen::Array3d max_bound = pc.GetMaxBound();\n        Eigen::Array3d center = (min_bound + max_bound) / 2;\n        Eigen::Array3d half_sizes = center - min_bound;\n        double max_half_size = half_sizes.maxCoeff();\n        Eigen::Vector3d origin = min_bound.min(center - max_half_size); // grid is isotropic box\n\n        double size;\n        if (max_half_size == 0) {\n            size = size_expand;\n        } else {\n            size = max_half_size * 2 * (1 + size_expand);\n        }\n\n        double voxel_num = std::log2(std::ceil(size / vxl_size) - 1);\n        const int MAX_VOXEL_NUM = std::numeric_limits<short>::max();\n        if (voxel_num > MAX_VOXEL_NUM) {\n            utility::LogWarning(\"vxl_size is too small.\");\n            while (voxel_num > MAX_VOXEL_NUM) {\n                vxl_size *= 2;\n                voxel_num = std::log2(std::ceil(size / vxl_size) - 1);\n            }\n            utility::LogWarning(\"vxl_size is clipped.\");\n        }\n\n        int grid_size = 1 << (static_cast<int>(voxel_num) + 1);\n\n        auto index = [origin, vxl_size](const Eigen::Vector3d& point) -> Eigen::Vector3i { return ((point - origin) / vxl_size).cast<int>(); };\n        auto toKey = [](const Eigen::Vector3i& v) -> GridKey { return (static_cast<GridKey>(v(0)) << 32) + (static_cast<GridKey>(v(1)) << 16) + v(2); };\n\n        std::map<GridKey, std::vector<PointID> > voxels;\n\n        for (unsigned int i = 0; i < pc.points_.size(); i++) {\n            auto point = pc.points_[i];\n            GridKey key = toKey(index(point));\n            voxels[key].push_back(i);\n        }\n\n        std::map<GridKey, VoxelID> idtbl;\n        std::map<GridKey, VoxelID> idtbl_removed;\n\n        utility::LogInfo(\"initialize voxel point cloud and index table\");\n        {\n            vc_.Clear();\n            //evc_.Clear();\n            rvc_.Clear();\n\n            for(auto p:voxels){\n                GridKey key = p.first;\n                auto indeces = p.second;\n                ASSERT(indeces.size() > 0);\n                Eigen::Vector3d eigenvalues(0, 0, 0);\n                auto normal = EstimateNormal(pc, indeces, eigenvalues);\n\n                Eigen::Vector3d color(0, 0, 0);\n                Eigen::Vector3d point(0, 0, 0);\n                for (auto i : indeces) {\n                    color = color + pc.colors_[i];\n                    point = point + pc.points_[i];\n                }\n                color = color / indeces.size();\n                point = point / indeces.size();\n\n                double var = 0;\n                for (auto i : indeces) {\n                    auto d = pc.colors_[i]-color;\n                    var = var + d.dot(d);\n                }\n                var /= indeces.size();\n\n                if (normal == Eigen::Vector3d::Zero() || eigenvalues(1) <= 0 ||  eigenvalues(2) <= 0) {\n                    idtbl_removed[key] = rvc_.points_.size();\n                    rvc_.points_.push_back(point);\n                    rvc_.colors_.push_back(color);\n                    continue;\n                } else if (var >= envvar(\"THRES_COLOR_VAR\", 0.05)) {\n                    idtbl_removed[key] = rvc_.points_.size();\n                    rvc_.points_.push_back(point);\n                    rvc_.colors_.push_back(color);\n                    continue;\n                } else if (std::abs(eigenvalues(0) / eigenvalues(1)) >= envvar(\"THRES_LAMBDA\", 0.01) || std::abs(eigenvalues(1) / eigenvalues(2)) < envvar(\"THRES_LAMBDA\", 0.01)) {\n                    idtbl_removed[key] = rvc_.points_.size();\n                    rvc_.points_.push_back(point);\n                    rvc_.colors_.push_back(color);\n                    continue;\n                } else if (eigenvalues(0) / (eigenvalues(0) + eigenvalues(1) + eigenvalues(2)) >= envvar(\"MAX_CURVATURE\", 0.002)) {\n                    idtbl_removed[key] = rvc_.points_.size();\n                    rvc_.points_.push_back(point);\n                    rvc_.colors_.push_back(color);\n                    continue;\n                } else {\n                    idtbl[key] = vc_.points_.size();\n                    vc_.points_.push_back(point);\n                    vc_.colors_.push_back(color);\n                    vc_.normals_.push_back(normal);\n                    continue;\n                }\n            }\n        }\n\n        for (auto ir:idtbl_removed) {\n            ASSERT(idtbl.find(ir.first) == idtbl.end());\n            idtbl[ir.first]= ir.second + vc_.points_.size();\n        }\n        //std::cout << idtbl.size() << \" \" << vc_.points_.size() << \" \" << rvc_.points_.size() << std::endl;\n        ASSERT(idtbl.size() == vc_.points_.size() + rvc_.points_.size());\n\n        ASSERT(vc_.points_.size() <  std::numeric_limits<VoxelID>::max());\n        ASSERT(vc_.points_.size() > 0);\n\n        utility::LogInfo(\"construct kdtree\");\n        kdt_.SetGeometry(vc_);\n\n        utility::LogInfo(\"constract voxel adjacency graph\");\n        rvadj_.clear();\n        rvadj_.resize(idtbl.size());\n        vadj_.clear();\n        vadj_.resize(vc_.points_.size());\n        for(unsigned int i=0; i< idtbl.size(); i++){\n            Eigen::Vector3i idx;\n            if (i < vc_.points_.size()) {\n                idx = index(vc_.points_[i]);\n            } else {\n                idx = index(rvc_.points_[i - vc_.points_.size()]);\n            }\n            GridKey key = toKey(idx);\n            ASSERT(idtbl[key] == static_cast<int>(i));\n            for (int x=-1; x<=1; x++) {\n                if (idx(0) + x < 0 || idx(0) + x >= grid_size) { continue; }\n                for (int y=-1; y<=1; y++) {\n                    if (idx(1) + y < 0 || idx(1) + y >= grid_size) { continue; }\n                    for (int z=-1; z<=1; z++) {\n                        if (idx(2) + z < 0 || idx(2) + z >= grid_size) { continue; }\n\n                        Eigen::Vector3i neighboridx = idx + Eigen::Vector3i(x, y, z);\n                        if (idx == neighboridx) { continue; }\n\n                        GridKey nkey = toKey(neighboridx);\n\n                        if (idtbl.find(nkey) != idtbl.end()) {\n                            VoxelID nvxlid = idtbl[nkey];\n                            if (nvxlid != static_cast<int>(i)) {\n                                if (i < vc_.points_.size() && nvxlid < vc_.points_.size()) {\n                                    vadj_[nvxlid].insert(i);\n                                    vadj_[i].insert(nvxlid);\n                                }\n                                rvadj_[nvxlid].insert(i);\n                                rvadj_[i].insert(nvxlid);\n                            }\n                        }\n                    }\n                }\n            }\n        }\n\n        if (envvar(\"DUMP_ADJ\", 0)) {\n            for (unsigned int i=0; i<vadj_.size(); i++) {\n                for (auto n : vadj_[i]) {\n                    std::cout << \"adj \" << i << \" -> \" << n << std::endl;\n                }\n            }\n        }\n\n    }\n\n\n    virtual void ScatterSeeds(double vxl_size, int r_seed, int r_search)\n    {\n        utility::LogInfo(\"scatter super voxel seeds\");\n\n        //auto center = vc_.GetCenter();\n        auto center = (vc_.GetMaxBound() + vc_.GetMinBound()) / 2;\n        auto extent = vc_.GetMaxBound() - vc_.GetMinBound();\n        double r = vxl_size*r_seed;\n        int xn2 = extent(0)/(2*r) + 1;\n        int yn2 = extent(1)/(2*r) + 1;\n        int zn2 = extent(2)/(2*r) + 1;\n\n        std::set<VoxelID> seeds;\n        for (int x=-xn2; x<=xn2; x++) {\n            for (int y=-yn2; y<=yn2; y++) {\n                for (int z=-zn2; z<=zn2; z++) {\n\n                    Eigen::Vector3d point = center + Eigen::Vector3d(x*r, y*r, z*r);\n\n                    std::vector<int> indices;\n                    std::vector<double> distance2;\n\n                    int k = kdt_.SearchHybrid(point, r, 1, indices, distance2);\n                    if (k == 0) {\n                        continue;\n                    }\n                    ASSERT(indices.size() == 1);\n                    seeds.insert(indices[0]);\n                }\n            }\n        }\n\n        for (auto seed : seeds) {\n            auto svxl = std::make_shared<SuperVoxel>();\n            svxl->seed_ = seed;\n            svxl->prop_ = MakeRegionProperty(seed);\n            svxls_.push_back(svxl);\n        }\n    }\n\n    RegionProperty MakeRegionProperty(VoxelID vid)\n    {\n        return RegionProperty(vc_.colors_[vid], vc_.points_[vid], vc_.normals_[vid]);\n    }\n\n    // NOTE: coeff == 0.1 in PCL implementation.\n    virtual void FilterOutSeedsInSparseArea(double vxl_size, int r_search, float coeff = 0.2f)\n    {\n        utility::LogInfo(\"filter out super voxel seeds\");\n        float min_points = coeff * r_search * r_search * 3.1415926536f / 2;\n        std::vector<std::shared_ptr<SuperVoxel> > new_svxls;\n\n        for(auto svxl : svxls_) {\n            std::vector<int> indices;\n            std::vector<double> distance2;\n\n            int k = kdt_.SearchRadius(svxl->prop_.point_, vxl_size * r_search, indices, distance2);\n\n            if (k > min_points) {\n                new_svxls.push_back(svxl);\n                continue;\n            }\n        }\n        svxls_ = new_svxls;\n    }\n\n\n    virtual void UpdateSeed()\n    {\n        for(auto svxl : svxls_) {\n            if (svxl->seed_ == NO_VOXEL) {\n                continue;\n            }\n            std::vector<int> indices;\n            std::vector<double> distance2;\n            kdt_.SearchKNN(svxl->prop_.Normalize().point_, 1, indices, distance2);\n            if (vc_.points_[svxl->seed_] == svxl->prop_.point_) {\n                ASSERT(svxl->seed_ == indices[0]);\n            }\n            svxl->seed_ = indices[0];\n            svxl->prop_ = MakeRegionProperty(indices[0]);\n        }\n    }\n\n\n    void Clustering(int iteration_num, std::function<double(const RegionProperty&, const RegionProperty&)> f, double max_d, int r_seed, double r_adj)\n    {\n        utility::LogInfo(\"clustering voxels into supervoxels\");\n\n        for (int iteration=0; iteration<iteration_num; iteration++) {\n            UpdateSeed();\n\n            std::vector<SuperVoxelID> v2l(vc_.points_.size(), NO_LABEL);; // voxelid -> supervoxel\n            std::vector<double> v2d(vc_.points_.size(), std::numeric_limits<double>::infinity()); // voxelid -> minimum distance\n\n            std::vector<std::vector<VoxelID> > sv2q(svxls_.size()); // search queues for each super voxel\n            std::vector<RegionProperty> sv2p(svxls_.size()); // supervoxel -> new region property\n            std::vector<std::set<VoxelID> > visited(svxls_.size());\n\n            // initialize svxl propery, searchqueue, label table\n            for (unsigned int i=0; i<svxls_.size(); i++) {\n                SuperVoxelID svxlid = i;\n                auto svxl = svxls_[svxlid];\n                if (svxl->seed_ == NO_VOXEL) {\n                    continue;\n                }\n                visited[svxlid].insert(svxl->seed_);\n                sv2q[svxlid].push_back(svxl->seed_);\n            }\n\n            // kmean\n            int depth = 0;\n            while (true) {\n                bool leaf_appended = false;\n                // 1-layer bfs\n                for (unsigned int i=0; i<svxls_.size(); i++) {\n                    SuperVoxelID svxlid = i;\n\n                    if (svxls_[svxlid]->seed_ == NO_VOXEL) {\n                        continue;\n                    }\n                    if (svxls_[svxlid]->prop_.num_of_points_ == 0) {\n                        svxls_[svxlid]->seed_ = NO_VOXEL;\n                        continue;\n                    }\n\n                    auto cur_svxl_prop = svxls_[svxlid]->prop_.Normalize();\n\n                    std::vector<VoxelID> newq;\n                    auto leaves = sv2q[svxlid];\n\n                    for (auto vid : leaves) {\n                        auto prop = MakeRegionProperty(vid);\n                        auto d = f(prop, cur_svxl_prop);\n                        if (d > max_d) {\n                            continue;\n                        }\n                        if (v2d[vid] > d) {\n                            v2d[vid] = d;\n                            if (v2l[vid] != NO_LABEL) {\n                                ASSERT(svxlid != v2l[vid]);\n                                auto old_svxlid = v2l[vid];\n                                sv2p[old_svxlid] = sv2p[old_svxlid] - prop;\n                            }\n                            for (auto n : vadj_[vid]) {\n                                if (visited[svxlid].find(n) == visited[svxlid].end()) {\n                                    newq.push_back(n);\n                                    leaf_appended = true;\n                                    visited[svxlid].insert(n);\n                                }\n                            }\n                            v2l[vid] = svxlid;\n                            sv2p[svxlid] = sv2p[svxlid] + prop;\n                        }\n                    }\n\n                    sv2q[svxlid] = newq;\n                }\n\n                //debug\n                if (envvar(\"DUMP_CLUSTERING\", 0)) {\n                    std::cout << \"---------------------\" << std::endl;\n                    std::cout << \"iteration \" << iteration << \" depth \" << depth << std::endl;\n                    for (unsigned int i=0; i<svxls_.size(); i++) {\n                        //if (i != 15) { continue; }\n                        if (svxls_[i]->seed_ == NO_VOXEL) { continue; }\n                        std::cout << \"label  \" << i  << std::endl;\n                        std::cout << \"seed \" << svxls_[i]->prop_.toString() << std::endl;\n                        std::cout << \"prop \" << sv2p[i].toString() << std::endl;\n                        for (auto vid : visited[i]) {\n                            if (v2l[vid] == static_cast<int>(i)) {\n                                auto x = vc_.points_[vid](0);\n                                auto y = vc_.points_[vid](1);\n                                auto z = vc_.points_[vid](2);\n                                auto nx = vc_.normals_[vid](0);\n                                auto ny = vc_.normals_[vid](1);\n                                auto nz = vc_.normals_[vid](2);\n                                auto r = vc_.colors_[vid](0);\n                                auto g = vc_.colors_[vid](1);\n                                auto b = vc_.colors_[vid](2);\n                                std::cout << \"vxl \" << vid  << \" : [\" <<  x << \" \" << y << \" \" << z << \"] : [\" <<  nx << \" \" << ny << \" \" << nz << \"]\" << \"] : [\" <<  r << \" \" << g << \" \" << b << \"]\" << std::endl;\n                            }\n                        }\n                    }\n                }\n\n                depth++;\n\n                if (!leaf_appended) {\n                    break;\n                }\n            }\n\n            // update label_ and property\n            {\n                vlabel_ = v2l;\n                for (unsigned int i=0; i<svxls_.size(); i++) {\n                    if (sv2p[i].num_of_points_ == 0) {\n                        svxls_[i]->prop_ = RegionProperty();\n                        svxls_[i]->seed_ = NO_VOXEL;\n                    } else {\n                        svxls_[i]->prop_ = sv2p[i];\n                    }\n                }\n            }\n\n            LabelAllVoxels(r_seed);\n        }\n\n        ComputeSuperVoxelAdjacency(r_adj);\n    }\n\n\n    void Label(VoxelID seed, SuperVoxelID svid, int r_seed)\n    {\n        auto f = [this, svid] (const VoxelID &v) -> bool {\n            if (vlabel_[v] == NO_LABEL) {\n                vlabel_[v] = svid;\n                svxls_[svid]->prop_ = svxls_[svid]->prop_ + MakeRegionProperty(v);\n                return true;\n            }\n            return false;\n        };\n        BFS<VoxelID>(seed, vadj_, r_seed, f);\n    }\n\n\n    void LabelAllVoxels(int r_seed)\n    {\n       for (unsigned int i=0; i<vlabel_.size(); i++) {\n           if (vlabel_[i] == NO_LABEL) {\n                SuperVoxelID freshID = svxls_.size();\n                auto svxl = std::make_shared<SuperVoxel>();\n                svxls_.push_back(svxl);\n                Label(i, freshID, r_seed);\n           }\n       }\n    }\n\n\n    void ComputeSuperVoxelAdjacency(double r_adj)\n    {\n        auto vlabel = vlabel_;\n\n        ASSERT( vlabel_.size() == vadj_.size());\n\n        for(unsigned int i=0; i<rvc_.points_.size(); i++) {\n            std::vector<int> indices;\n            std::vector<double> distance2;\n            int k = kdt_.SearchKNN(rvc_.points_[i], 1, indices, distance2);\n            vlabel.push_back(vlabel[indices[0]]);\n        }\n\n        for (unsigned int vid=0; vid<rvadj_.size(); vid++) {\n            SuperVoxelID svid = vlabel[vid];\n            if (svid == NO_LABEL) {\n                continue;\n            }\n            ASSERT(svxls_[svid]->seed_ != NO_VOXEL);\n            for (auto nvid :rvadj_[vid]) {\n                SuperVoxelID nsvid = vlabel[nvid];\n                if (nsvid == NO_LABEL) {\n                    continue;\n                }\n                ASSERT(svxls_[nsvid]->seed_ != NO_VOXEL);\n                //std::cout << vid << \"[\" << svid << \"] -> \" << nvid << \"[\" << nsvid << \"]\" << std::endl;\n                if (svid != nsvid) {\n                    //std::cout << svid << \" -> \" << nsvid  << std::endl;\n                    svadj_[svid].insert(nsvid);\n                }\n            }\n        }\n\n    }\n\n\n\npublic:\n    //super voxel\n    KDTreeFlann kdt_;\n    PointCloud vc_; // voxel cloud\n    PointCloud rvc_; // debug : removed voxel cloud\n    std::vector<std::set<VoxelID> > vadj_; // voxel -> neighbor voxels(only stable normal voxel)\n    std::vector<std::set<VoxelID> > rvadj_; // voxel -> neighbor voxels\n    std::vector<std::shared_ptr<SuperVoxel> > svxls_;\n    std::vector<SuperVoxelID> vlabel_; // voxelid -> supervoxel\n    std::map<SuperVoxelID, std::set<SuperVoxelID> > svadj_; // supervoxel -> neighbor supervoxels\n\n\tstd::vector<RegionProperty> mergedsvxls_;\n};\n\n}  // namespace geometry\n}  // namespace open3d\n", "meta": {"hexsha": "46bd9dcfbcde34344b58b475df96df84d17ac9ab", "size": 39113, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "EVCCS.hpp", "max_stars_repo_name": "SuperLazyK/EVCCS", "max_stars_repo_head_hexsha": "e1a2331ff069f505c64094c781e5f567ec1a49a1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "EVCCS.hpp", "max_issues_repo_name": "SuperLazyK/EVCCS", "max_issues_repo_head_hexsha": "e1a2331ff069f505c64094c781e5f567ec1a49a1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "EVCCS.hpp", "max_forks_repo_name": "SuperLazyK/EVCCS", "max_forks_repo_head_hexsha": "e1a2331ff069f505c64094c781e5f567ec1a49a1", "max_forks_repo_licenses": ["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.3963800905, "max_line_length": 260, "alphanum_fraction": 0.4913200215, "num_tokens": 10601, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4625918616115391}}
{"text": "//==================================================================================================\n/*\n  Copyright 2017 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//! [oneminus]\n#include <boost/simd/arithmetic.hpp>\n#include <boost/simd/pack.hpp>\n#include <iostream>\n\nnamespace bs =  boost::simd;\nusing pack_ft = bs::pack <float, 4>;\nusing pack_it = bs::pack <std::uint16_t,4>;\n\nint main()\n{\n  pack_ft pf = {-1.0f, 2.0f, -3.0f, -32768.0f};\n  pack_it pi = { 0,   -1,    2,    3 };\n\n  std::cout\n    << \"---- simd\" << '\\n'\n    << \"<- pf =                                \" << pf << '\\n'\n    << \"-> bs::oneminus(pf) =                  \" << bs::oneminus(pf) << '\\n'\n    << \"<- pi =                                \" << pi << '\\n'\n    << \"-> bs::oneminus(pi) =                  \" << bs::oneminus(pi) << '\\n'\n    << \"-> bs::saturated_(bs::oneminus(pi)) =  \" << bs::saturated_(bs::oneminus)(pi) << '\\n';\n\n  float xf = -327.0f;\n  std::uint16_t xi =  2;\n\n  std::cout\n    << \"---- scalar\"  << '\\n'\n    << \"<- xf =                                \" << xf << '\\n'\n    << \"-> bs::oneminus(xf) =                  \" << bs::oneminus(xf) << '\\n'\n    << \"<- xi =                                \" << xi << '\\n'\n    << \"-> bs::oneminus(xi) =                  \" << bs::oneminus(xi) << '\\n'\n    << \"-> bs::saturated_(bs::oneminus(xi)) =  \" << bs::saturated_(bs::oneminus)(xi) << '\\n';\n  return 0;\n}\n//! [oneminus]\n", "meta": {"hexsha": "4f59f6d0b04e6dec58603c56886b16a1b0312a49", "size": 1605, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/doc/arithmetic/oneminus.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": "test/doc/arithmetic/oneminus.cpp", "max_issues_repo_name": "remymuller/boost.simd", "max_issues_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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/doc/arithmetic/oneminus.cpp", "max_forks_repo_name": "remymuller/boost.simd", "max_forks_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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": 36.4772727273, "max_line_length": 100, "alphanum_fraction": 0.3819314642, "num_tokens": 467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.46259186161153903}}
{"text": "#pragma once\n#include \"criteria.hpp\"\n#include \"dijkstra.hpp\"\n#include \"graph.hpp\"\n#include \"stringy_enum.hpp\"\n#include <boost/heap/pairing_heap.hpp>\n#include <unordered_set>\n\nnamespace sssp {\n\n// Implements Crauser's IN criteria. Additionally instead of using the minimal edges,\n// with dynamic=true, one can use the minimal non-settled edge.\nclass crauser_in : public criteria {\n  public:\n    crauser_in(const sssp::graph* graph, size_t start_node, bool dynamic);\n    virtual void relaxable_nodes(todo_output& output) const override;\n    virtual void changed_predecessor(size_t node, size_t predecessor, double distance) override;\n    virtual void relaxed_node(size_t node) override;\n    virtual bool is_complete() const override { return true; }\n    bool dynamic() const { return m_dynamic; }\n\n  private:\n    struct node_info;\n    struct node_info_compare_distance {\n        bool operator()(const node_info* a, const node_info* b) const;\n    };\n    // threshold(n) = tentative(n) - min{ cost of incmoing edges (not settled if dynamic) }\n    // Called \"i\" in the paper.\n    struct node_info_compare_threshold {\n        bool operator()(const node_info* a, const node_info* b) const;\n    };\n\n    using distance_queue = boost::heap::pairing_heap<node_info*, boost::heap::compare<node_info_compare_distance>>;\n    using threshold_queue = boost::heap::pairing_heap<node_info*, boost::heap::compare<node_info_compare_threshold>>;\n\n    struct node_info {\n        node_info(const sssp::graph& g, size_t index);\n        size_t index;\n        std::vector<edge_info> incoming;\n        double tentative_distance = INFINITY;\n        bool settled = false;\n        distance_queue::handle_type distance_queue_handle;\n        threshold_queue::handle_type threshold_queue_handle;\n\n        double threshold() const;\n    };\n\n    bool m_dynamic;\n    node_map<node_info> m_node_info;\n    distance_queue m_distance_queue;\n    threshold_queue m_threshold_queue;\n};\n\n// Implements Crauser's OUT criteria. Additionally instead of using the minimal edges,\n// with dynamic=true, one can use the minimal non-settled edge.\nclass crauser_out : public criteria {\n  public:\n    crauser_out(const sssp::graph* graph, size_t start_node, bool dynamic);\n    virtual void relaxable_nodes(todo_output& output) const override;\n    virtual void changed_predecessor(size_t node, size_t predecessor, double distance) override;\n    virtual void relaxed_node(size_t node) override;\n    virtual bool is_complete() const override { return true; }\n    bool dynamic() const { return m_dynamic; }\n\n  private:\n    struct node_info;\n    struct node_info_compare_distance {\n        bool operator()(const node_info* a, const node_info* b) const;\n    };\n    // threshold(n) = tentative(n) + min{ outgoing edge (not settled if dynamic) }\n    // Called \"L\" in the paper (to be exact this are the values of all nodes, not the final L)\n    struct node_info_compare_threshold {\n        bool operator()(const node_info* a, const node_info* b) const;\n    };\n\n    using distance_queue = boost::heap::pairing_heap<node_info*, boost::heap::compare<node_info_compare_distance>>;\n    using threshold_queue = boost::heap::pairing_heap<node_info*, boost::heap::compare<node_info_compare_threshold>>;\n\n    struct node_info {\n        node_info(const sssp::graph& g, size_t index);\n        size_t index;\n        std::vector<edge_info> outgoing;\n        double tentative_distance = INFINITY;\n        bool settled = false;\n        distance_queue::handle_type distance_queue_handle;\n        threshold_queue::handle_type threshold_queue_handle;\n\n        double threshold() const;\n    };\n\n    bool m_dynamic;\n    node_map<node_info> m_node_info;\n    distance_queue m_distance_queue;\n    threshold_queue m_threshold_queue;\n};\n\n} // namespace sssp", "meta": {"hexsha": "51f5e616d09849a78be384d0b82a56cbceaef6c3", "size": 3769, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "crit_crauser.hpp", "max_stars_repo_name": "kaini/sssp-simulation", "max_stars_repo_head_hexsha": "0ee9cefb9b5d3a79c59eedd44092cd0401e99581", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "crit_crauser.hpp", "max_issues_repo_name": "kaini/sssp-simulation", "max_issues_repo_head_hexsha": "0ee9cefb9b5d3a79c59eedd44092cd0401e99581", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "crit_crauser.hpp", "max_forks_repo_name": "kaini/sssp-simulation", "max_forks_repo_head_hexsha": "0ee9cefb9b5d3a79c59eedd44092cd0401e99581", "max_forks_repo_licenses": ["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.8556701031, "max_line_length": 117, "alphanum_fraction": 0.7198195808, "num_tokens": 847, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431679972357831, "lm_q2_score": 0.6224593382055109, "lm_q1q2_score": 0.4625918597349005}}
{"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_SOLVERS_FDDP_HPP_\n#define CROCODDYL_CORE_SOLVERS_FDDP_HPP_\n\n#include <Eigen/Cholesky>\n#include <vector>\n\n#include \"crocoddyl/core/solvers/ddp.hpp\"\n\nnamespace crocoddyl {\n\n/**\n * @brief Feasibility-driven Differential Dynamic Programming (FDDP) solver\n *\n * The FDDP solver computes an optimal trajectory and control commands by iterates running `backwardPass()` and\n * `forwardPass()`. The backward pass accepts infeasible guess as described in the `SolverDDP::backwardPass()`.\n * Additionally, the forward pass handles infeasibility simulations that resembles the numerical behaviour of\n * a multiple-shooting formulation, i.e.:\n * \\f{eqnarray}\n *   \\mathbf{\\hat{x}}_0 &=& \\mathbf{\\tilde{x}}_0 - (1 - \\alpha)\\mathbf{\\bar{f}}_0,\\\\\n *   \\mathbf{\\hat{u}}_k &=& \\mathbf{u}_k + \\alpha\\mathbf{k}_k + \\mathbf{K}_k(\\mathbf{\\hat{x}}_k-\\mathbf{x}_k),\\\\\n *   \\mathbf{\\hat{x}}_{k+1} &=& \\mathbf{f}_k(\\mathbf{\\hat{x}}_k,\\mathbf{\\hat{u}}_k) - (1 -\n * \\alpha)\\mathbf{\\bar{f}}_{k+1}.\n * \\f}\n * Note that the forward pass keeps the gaps \\f$\\mathbf{\\bar{f}}_s\\f$ open according to the step length \\f$\\alpha\\f$\n * that has been accepted. This solver has shown empirically greater globalization strategy. Additionally, the\n * expected improvement computation considers the gaps in the dynamics:\n * \\f{equation}\n *   \\Delta J(\\alpha) = \\Delta_1\\alpha + \\frac{1}{2}\\Delta_2\\alpha^2,\n * \\f}\n * with\n * \\f{eqnarray}\n *   \\Delta_1 = \\sum_{k=0}^{N-1} \\mathbf{k}_k^\\top\\mathbf{Q}_{\\mathbf{u}_k} +\\mathbf{\\bar{f}}_k^\\top(V_{\\mathbf{x}_k} -\n *   V_{\\mathbf{xx}_k}\\mathbf{x}_k),\\nonumber\\\\ \\Delta_2 = \\sum_{k=0}^{N-1}\n *   \\mathbf{k}_k^\\top\\mathbf{Q}_{\\mathbf{uu}_k}\\mathbf{k}_k + \\mathbf{\\bar{f}}_k^\\top(2 V_{\\mathbf{xx}_k}\\mathbf{x}_k\n * - V_{\\mathbf{xx}_k}\\mathbf{\\bar{f}}_k). \\f}\n *\n * For more details about the feasibility-driven differential dynamic programming algorithm see:\n * \\include mastalli-icra20.bib\n *\n * \\sa `SolverDDP()`, `backwardPass()`, `forwardPass()`, `expectedImprovement()` and `updateExpectedImprovement()`\n */\nclass SolverFDDP : public SolverDDP {\n public:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n  /**\n   * @brief Initialize the FDDP solver\n   *\n   * @param[in] problem  shooting problem\n   */\n  explicit SolverFDDP(boost::shared_ptr<ShootingProblem> problem);\n  virtual ~SolverFDDP();\n\n  virtual bool solve(const std::vector<Eigen::VectorXd>& init_xs = DEFAULT_VECTOR,\n                     const std::vector<Eigen::VectorXd>& init_us = DEFAULT_VECTOR, const std::size_t maxiter = 100,\n                     const bool is_feasible = false, const double regInit = 1e-9);\n\n  /**\n   * @copybrief SolverAbstract::expectedImprovement\n   *\n   * This function requires to first run `updateExpectedImprovement()`. The expected improvement computation considers\n   * the gaps in the dynamics: \\f{equation} \\Delta J(\\alpha) = \\Delta_1\\alpha + \\frac{1}{2}\\Delta_2\\alpha^2, \\f} with\n   * \\f{eqnarray}\n   *   \\Delta_1 = \\sum_{k=0}^{N-1} \\mathbf{k}_k^\\top\\mathbf{Q}_{\\mathbf{u}_k} +\\mathbf{\\bar{f}}_k^\\top(V_{\\mathbf{x}_k}\n   * - V_{\\mathbf{xx}_k}\\mathbf{x}_k),\\nonumber\\\\ \\Delta_2 = \\sum_{k=0}^{N-1}\n   *   \\mathbf{k}_k^\\top\\mathbf{Q}_{\\mathbf{uu}_k}\\mathbf{k}_k + \\mathbf{\\bar{f}}_k^\\top(2\n   * V_{\\mathbf{xx}_k}\\mathbf{x}_k\n   * - V_{\\mathbf{xx}_k}\\mathbf{\\bar{f}}_k). \\f}\n   */\n  virtual const Eigen::Vector2d& expectedImprovement();\n\n  /**\n   * @brief Update internal values for computing the expected improvement\n   */\n  void updateExpectedImprovement();\n  virtual void forwardPass(const double stepLength);\n\n  /**\n   * @brief Return the threshold used for accepting step along ascent direction\n   */\n  double get_th_acceptnegstep() const;\n\n  /**\n   * @brief Modify the threshold used for accepting step along ascent direction\n   */\n  void set_th_acceptnegstep(const double th_acceptnegstep);\n\n protected:\n  double dg_;  //!< Internal data for computing the expected improvement\n  double dq_;  //!< Internal data for computing the expected improvement\n  double dv_;  //!< Internal data for computing the expected improvement\n\n private:\n  double th_acceptnegstep_;  //!< Threshold used for accepting step along ascent direction\n};\n\n}  // namespace crocoddyl\n\n#endif  // CROCODDYL_CORE_SOLVERS_FDDP_HPP_\n", "meta": {"hexsha": "3eef876c86c9250560e0fd495f776f6ca02737b7", "size": 4555, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/crocoddyl/core/solvers/fddp.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/solvers/fddp.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/solvers/fddp.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": 42.1759259259, "max_line_length": 119, "alphanum_fraction": 0.669154775, "num_tokens": 1378, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743168019989179, "lm_q2_score": 0.6224593171945417, "lm_q1q2_score": 0.4625918582832839}}
{"text": "// -----------------------------------------------------------------------------\n// Fern \u00a9 Geoneric\n//\n// This file is part of Geoneric Fern which is available under the terms of\n// the GNU General Public License (GPL), version 2. If you do not want to\n// be bound by the terms of the GPL, you may purchase a proprietary license\n// from Geoneric (http://www.geoneric.eu/contact).\n// -----------------------------------------------------------------------------\n#define BOOST_TEST_MODULE fern algorithm algebra vector lax\n#include <boost/test/unit_test.hpp>\n#include \"fern/core/data_customization_point/scalar.h\"\n#include \"fern/feature/core/data_customization_point/array.h\"\n#include \"fern/feature/core/data_customization_point/masked_raster.h\"\n#include \"fern/algorithm/algebra/vector/lax.h\"\n\n\nnamespace fa = fern::algorithm;\n\n\nBOOST_AUTO_TEST_CASE(algorithm)\n{\n    // Create input raster:\n    // +----+----+----+----+\n    // |  0 |  1 |  2 |  3 |\n    // +----+----+----+----+\n    // |  4 |  5 |  6 |  7 |\n    // +----+----+----+----+\n    // |  8 |  9 | 10 | 11 |\n    // +----+----+----+----+\n    // | 12 | 13 | 14 | 15 |\n    // +----+----+----+----+\n    // | 16 | 17 | 18 | 19 |\n    // +----+----+----+----+\n    size_t const nr_rows = 5;\n    size_t const nr_cols = 4;\n    auto extents = fern::extents[nr_rows][nr_cols];\n\n    double const cell_width = 2.0;\n    double const cell_height = 3.0;\n    double const west = 0.0;\n    double const north = 0.0;\n\n    using MaskedRaster = fern::MaskedRaster<double, 2>;\n\n    MaskedRaster::Transformation transformation{{west, cell_width,\n        north, cell_height}};\n    MaskedRaster raster(extents, transformation);\n\n    std::iota(raster.data(), raster.data() + raster.num_elements(), 0);\n\n    fa::SequentialExecutionPolicy sequential;\n\n    double const fraction = 0.6;\n\n    // Calculate lax.\n    MaskedRaster result(extents, transformation);\n\n    // Without masking input and output values.\n    {\n        fa::algebra::lax(sequential, raster, fraction, result);\n\n        /// // Verify the result.\n        BOOST_CHECK_EQUAL(get(result, index(result, 0, 0)),\n            ((1.0 - fraction) * 0.0) + (fraction * 25.0 / 8.0));\n        BOOST_CHECK_EQUAL(get(result, index(result, 1, 1)),\n            ((1.0 - fraction) * 5.0) + (fraction * 100.0 / 20.0));\n    }\n\n    using InputNoDataPolicy = fa::InputNoDataPolicies<\n        fa::DetectNoDataByValue<fern::Mask<2>>>;\n    using OutputNoDataPolicy = fa::MarkNoDataByValue<fern::Mask<2>>;\n\n    // With masking input and output values.\n    {\n        result.fill(999.0);\n        result.mask().fill(false);\n        raster.mask()[1][1] = true;\n\n        InputNoDataPolicy input_no_data_policy{{raster.mask(), true}};\n        OutputNoDataPolicy output_no_data_policy(result.mask(), true);\n\n        fa::algebra::lax(\n            input_no_data_policy,\n            output_no_data_policy,\n            sequential,\n            raster, fraction, result);\n\n        // Verify the result.\n        BOOST_CHECK_EQUAL(get(result.mask(), index(result.mask(), 0, 0)),\n            false);\n        BOOST_CHECK_EQUAL(get(result, index(result, 0, 0)),\n            ((1.0 - fraction) * 0.0) + (fraction * 15.0 / 6.0));\n\n        BOOST_CHECK_EQUAL(get(result.mask(), index(result.mask(), 1, 1)), true);\n        BOOST_CHECK_EQUAL(get(result, index(result, 1, 1)), 999.0);\n    }\n}\n", "meta": {"hexsha": "c179c8439a0b798d9dfacf4b71d48ee1b60bfdf0", "size": 3330, "ext": "cc", "lang": "C++", "max_stars_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/fern/source/fern/algorithm/algebra/vector/test/lax_test.cc", "max_stars_repo_name": "quanpands/wflow", "max_stars_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/fern/source/fern/algorithm/algebra/vector/test/lax_test.cc", "max_issues_repo_name": "quanpands/wflow", "max_issues_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/fern/source/fern/algorithm/algebra/vector/test/lax_test.cc", "max_forks_repo_name": "quanpands/wflow", "max_forks_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.9795918367, "max_line_length": 80, "alphanum_fraction": 0.5675675676, "num_tokens": 892, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743167997235783, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.4625918545300071}}
{"text": "#include <stan/math/prim/scal.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <gtest/gtest.h>\n\nTEST(MathSpecialFunctions,logical_neq) {\n  using stan::math::logical_neq;\n  EXPECT_TRUE(logical_neq(0,1));\n  EXPECT_TRUE(logical_neq(1.0,0));\n  EXPECT_TRUE(logical_neq(1, 2));\n  EXPECT_TRUE(logical_neq(2.0, -1.0));\n\n  EXPECT_FALSE(logical_neq(1,1));\n  EXPECT_FALSE(logical_neq(5.7,5.7));\n  EXPECT_FALSE(logical_neq(0,0.0));\n}\n\nTEST(MathFunctions, logical_neq_nan) {\n  double nan = std::numeric_limits<double>::quiet_NaN();\n  \n  EXPECT_TRUE(stan::math::logical_neq(1.0, nan));\n  EXPECT_TRUE(stan::math::logical_neq(nan, 2.0));\n  EXPECT_TRUE(stan::math::logical_neq(nan, nan));\n}\n", "meta": {"hexsha": "37a1179cc9dc94723502eb7a79fe407d604d5595", "size": 694, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/scal/fun/logical_neq_test.cpp", "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/test/unit/math/prim/scal/fun/logical_neq_test.cpp", "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/test/unit/math/prim/scal/fun/logical_neq_test.cpp", "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": 28.9166666667, "max_line_length": 56, "alphanum_fraction": 0.7276657061, "num_tokens": 226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300698514778, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.4625580926610346}}
{"text": "#include <bits/types/FILE.h>\n#include <fstream>\n#include <iostream>\n#include <stdio.h>\n#include <vector>\n#include <string>\n#include <tgmath.h>\n#include \"image_ppm.h\"\n#include <filesystem>\n#include <Eigen/Dense>\n\nusing namespace std;\nusing namespace Eigen;\n\ntypedef Matrix<u_char, Dynamic, Dynamic> MatrixImg;\ntypedef Vector<u_char,Dynamic> ImgLine;\ntypedef Matrix<ImgLine,Dynamic,Dynamic> FlattenedImages;\n\nunsigned char max(u_char a, u_char b){\n    if (a<b) return b;\n    else return a;\n}\n\nunsigned char min(u_char a, u_char b){\n    if (a>b) return b;\n    else return a;\n}\n\nunsigned char LBPvalue(OCTET* image, int x, int y, int nW, int nH){\n    int count =0;\n    int* binaryNumber = new int[8];\n    \n    for(int i =-1;i<2;i++){\n        for (int j=-1;j<2;j++){\n            if (i!=0 && j!=0){\n                if (image[(x+i)*nW+j+y]<image[x*nW+y]){\n                    binaryNumber[count]=0;\n                }\n                if (image[(x+i)*nW+j+y]>=image[x*nW+y]){\n                    binaryNumber[count]=1;\n                }\n                count++;\n            }\n        }\n    }\n    unsigned char res = (unsigned char)(1*binaryNumber[7] + 2*binaryNumber[6] + 4*binaryNumber[5] + 8*binaryNumber[4] + 16*binaryNumber[3] + 32*binaryNumber[2] + 64*binaryNumber[1] + 128*binaryNumber[0]);\n    return (res);\n}\n\ndouble minutie(int* hist, int size,int nH, int nW, int gridX, int gridY){\n    double res =0.0;\n    for (int i =0;i<size;i++){\n        res+=i*(double)hist[i]/((double)(nW*nH)/(double)(gridY*gridX));//(double)size;\n    }\n    return res;\n}\n\ndouble divergenceLK(int* hist1, int* hist2, int size){\n    double res = 0.0;\n    for (int k=0;k<size;k++){\n        res+=(hist1[k]+1.0)*log((hist1[k]+1.0)/(hist2[k]+1.0));\n    }\n    return res;\n}\n\nint main(){\n    \n}\n", "meta": {"hexsha": "3d81cd7825c9daaa3e47b1bdba9d98c2c299533f", "size": 1762, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Code/methodComparing.cpp", "max_stars_repo_name": "JPhilippot/FaceRecognition", "max_stars_repo_head_hexsha": "12a657d05f0103b0193a28a6347d1f41f466f0d0", "max_stars_repo_licenses": ["MIT"], "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/methodComparing.cpp", "max_issues_repo_name": "JPhilippot/FaceRecognition", "max_issues_repo_head_hexsha": "12a657d05f0103b0193a28a6347d1f41f466f0d0", "max_issues_repo_licenses": ["MIT"], "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/methodComparing.cpp", "max_forks_repo_name": "JPhilippot/FaceRecognition", "max_forks_repo_head_hexsha": "12a657d05f0103b0193a28a6347d1f41f466f0d0", "max_forks_repo_licenses": ["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.5362318841, "max_line_length": 204, "alphanum_fraction": 0.5737797957, "num_tokens": 535, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300698514777, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.46255809266103454}}
{"text": "#include <Eigen/Core>\n\n#include <numpy_eigen/boost_python_headers.hpp>\nEigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> test_double_D_D(const Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> & M)\n{\n\treturn M;\n}\nvoid export_double_D_D()\n{\n\tboost::python::def(\"test_double_D_D\",test_double_D_D);\n}\n\n", "meta": {"hexsha": "a351a312ab873cc32510c67a42f3d7cdfce5978b", "size": 307, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Schweizer-Messer/numpy_eigen/src/autogen_test_module/test_D_D_double.cpp", "max_stars_repo_name": "PushyamiKaveti/kalibr", "max_stars_repo_head_hexsha": "d8bdfc59ee666ef854012becc93571f96fe5d80c", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": 2690.0, "max_stars_repo_stars_event_min_datetime": "2015-01-07T03:50:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T20:27:01.000Z", "max_issues_repo_path": "Schweizer-Messer/numpy_eigen/src/autogen_test_module/test_D_D_double.cpp", "max_issues_repo_name": "PushyamiKaveti/kalibr", "max_issues_repo_head_hexsha": "d8bdfc59ee666ef854012becc93571f96fe5d80c", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": 481.0, "max_issues_repo_issues_event_min_datetime": "2015-01-27T10:21:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T14:02:41.000Z", "max_forks_repo_path": "Schweizer-Messer/numpy_eigen/src/autogen_test_module/test_D_D_double.cpp", "max_forks_repo_name": "PushyamiKaveti/kalibr", "max_forks_repo_head_hexsha": "d8bdfc59ee666ef854012becc93571f96fe5d80c", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": 1091.0, "max_forks_repo_forks_event_min_datetime": "2015-01-26T21:21:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T01:55:33.000Z", "avg_line_length": 23.6153846154, "max_line_length": 134, "alphanum_fraction": 0.7557003257, "num_tokens": 79, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6584175139669997, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.4625580856758165}}
{"text": "#include \"problemes.h\"\n#include \"arithmetique.h\"\n\n#include <fstream>\n\n#include <boost/algorithm/string.hpp>\n#include <numeric>\n\ntypedef unsigned long long nombre;\n\nENREGISTRER_PROBLEME(59, \"XOR decryption\") {\n    // Each character on a computer is assigned a unique code and the preferred standard is ASCII \n    // (American Standard Code for Information Interchange). For example, uppercase A = 65, asterisk (*) = 42, \n    // and lowercase k = 107.\n    //\n    // A modern encryption method is to take a text file, convert the bytes to ASCII, then XOR each byte \n    // with a given value, taken from a secret key. The advantage with the XOR function is that using \n    // the same encryption key on the cipher text, restores the plain text; for example, 65 XOR 42 = 107, \n    // then 107 XOR 42 = 65.\n    //\n    // For unbreakable encryption, the key is the same length as the plain text message, and the key is made \n    // up of random bytes. The user would keep the encrypted message and the encryption key in different \n    // locations, and without both \"halves\", it is impossible to decrypt the message.\n    // \n    // Unfortunately, this method is impractical for most users, so the modified method is to use a password \n    // as a key. If the password is shorter than the message, which is likely, the key is repeated cyclically \n    // throughout the message. The balance for this method is using a sufficiently long password key for security, \n    // but short enough to be memorable.\n    // \n    // Your task has been made easy, as the encryption key consists of three lower case characters. \n    // Using cipher.txt (right click and 'Save Link/Target As...'), a file containing the encrypted ASCII codes, \n    // and the knowledge that the plain text must contain common English words, decrypt the message and find \n    // the sum of the ASCII values in the original text.\n    std::ifstream ifs(\"data/p059_cipher.txt\");\n    std::string entree;\n    ifs >> entree;\n    std::vector<std::string> names;\n    boost::split(names, entree, boost::is_any_of(\",\"));\n\n    std::set<char> lettres = {' ', ',', '(', ')', '[', ']', '.', '!', '\\'', ';', '\"', '+', '-', '/', '*', ':'};\n    for (char c = 'a'; c <= 'z'; ++c) lettres.insert(c);\n    for (char c = 'A'; c <= 'Z'; ++c) lettres.insert(c);\n    for (char c = '0'; c <= '9'; ++c) lettres.insert(c);\n\n    std::vector<char> data;\n    std::transform(names.begin(), names.end(), std::back_inserter(data),\n                   [](const std::string &str) { return std::stoi(str); });\n\n    std::string message;\n    for (char key1 = 'a'; key1 <= 'z'; ++key1) {\n        if (lettres.find(data[0] ^ key1) == lettres.end())\n            continue;\n        for (char key2 = 'a'; key2 <= 'z'; ++key2) {\n            if (lettres.find(data[1] ^ key2) == lettres.end())\n                continue;\n            for (char key3 = 'a'; key3 <= 'z'; ++key3) {\n                if (lettres.find(data[2] ^ key3) == lettres.end())\n                    continue;\n\n                std::string key = {key1, key2, key3};\n                std::string decode;\n                for (size_t n = 0; n < data.size(); ++n) {\n                    const char c = data[n] ^key[n % 3];\n                    if (lettres.find(c) == lettres.end())\n                        break;\n                    decode.push_back(c);\n                }\n                if (decode.size() == data.size()) {\n                    message = decode;\n                    std::cout << key << \": \" << decode << std::endl;\n                }\n            }\n        }\n    }\n\n    nombre resultat = std::accumulate(message.begin(), message.end(), 0ULL,\n                                      [](const nombre r, const char c) { return r + static_cast<nombre>(c); }\n    );\n    return std::to_string(resultat);\n}\n", "meta": {"hexsha": "4c3d1b7469eeb01c11f6ece5993d6b204bc6ddc7", "size": 3776, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problemes/probleme0xx/probleme059.cpp", "max_stars_repo_name": "ZongoForSpeed/ProjectEuler", "max_stars_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-10-13T17:07:21.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-08T11:50:22.000Z", "max_issues_repo_path": "problemes/probleme0xx/probleme059.cpp", "max_issues_repo_name": "ZongoForSpeed/ProjectEuler", "max_issues_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problemes/probleme0xx/probleme059.cpp", "max_forks_repo_name": "ZongoForSpeed/ProjectEuler", "max_forks_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.6172839506, "max_line_length": 115, "alphanum_fraction": 0.5730932203, "num_tokens": 934, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.46255808445960683}}
{"text": "#include \"stdafx.h\"\n#include \"KeplerLawSystem.h\"\n#include \"TimeController.h\"\n#include \"Scale.h\"\n#include <unordered_set>\n#include <unordered_map>\n#include <boost/algorithm/cxx11/copy_if.hpp>\n\nusing glm::vec2;\nusing glm::vec3;\n\nCKeplerLawSystem::CKeplerLawSystem(ITimeController &controller)\n    : m_timeController(controller)\n{\n}\n\nvoid CKeplerLawSystem::Update()\n{\n    const double time = m_timeController.GetSpaceTime();\n\n    // \u0418\u043c\u0435\u043d\u0430 \u043e\u0431\u044a\u0435\u043a\u0442\u043e\u0432, \u043e\u0440\u0431\u0438\u0442\u044b \u043a\u043e\u0442\u043e\u0440\u044b\u0445 \u0435\u0449\u0451 \u0441\u043b\u0435\u0434\u0443\u0435\u0442 \u043e\u0431\u043d\u043e\u0432\u0438\u0442\u044c.\n    // \u0418\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u044e\u0442\u0441\u044f \u0434\u043b\u044f \u0440\u0430\u0437\u0440\u0435\u0448\u0435\u043d\u0438\u044f \u0437\u0430\u0432\u0438\u0441\u0438\u043c\u043e\u0441\u0442\u0435\u0439 \u043f\u0440\u0438 \u0441\u0438\u0441\u0442\u0435\u043c\n    //  \u0442\u0438\u043f\u0430 \u0421\u043e\u043b\u043d\u0446\u0435->\u0417\u0435\u043c\u043b\u044f->\u041b\u0443\u043d\u0430.\n    std::unordered_set<std::string> remainingNames;\n    for (const auto &entity : getEntities())\n    {\n        const auto &body = entity.getComponent<CSpaceBodyComponent>();\n        remainingNames.insert(body.m_name);\n    }\n\n    // \u0421\u043b\u043e\u0432\u0430\u0440\u044c \u0441 \u0438\u0437\u0432\u0435\u0441\u0442\u043d\u044b\u043c \u043f\u043e\u0437\u0438\u0446\u0438\u044f\u043c\u0438 \u043e\u0431\u044a\u0435\u043a\u0442\u043e\u0432,\n    //  \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u0435\u0442\u0441\u044f \u0434\u043b\u044f \u0440\u0430\u0441\u0447\u0451\u0442\u0430 \u043f\u043e\u0437\u0438\u0446\u0438\u0439 \u0441\u043f\u0443\u0442\u043d\u0438\u043a\u043e\u0432.\n    std::unordered_map<std::string, vec3> knownPositions;\n\n    // \u041f\u0440\u0435\u043a\u0440\u0430\u0449\u0430\u0435\u043c \u043e\u0431\u043d\u043e\u0432\u043b\u044f\u0442\u044c \u043f\u043e\u0437\u0438\u0446\u0438\u0438, \u0435\u0441\u043b\u0438 \u043d\u0438\u0447\u0435\u0433\u043e \u043d\u0435 \u0438\u0437\u043c\u0435\u043d\u0438\u043b\u043e\u0441\u044c\n    //  \u0437\u0430 \u043e\u0434\u0438\u043d \u043e\u0431\u0445\u043e\u0434 \u0432\u0441\u0435\u0445 \u043a\u043e\u0441\u043c\u0438\u0447\u0435\u0441\u043a\u0438\u0445 \u0442\u0435\u043b.\n    bool mayContinue = false;\n    do\n    {\n        mayContinue = false;\n        for (const auto &entity : getEntities())\n        {\n            const auto &body = entity.getComponent<CSpaceBodyComponent>();\n            auto &orbit = entity.getComponent<CEllipticOrbitComponent>();\n\n            // \u041f\u0440\u043e\u043f\u0443\u0441\u043a\u0430\u0435\u043c \u0438\u0442\u0435\u0440\u0430\u0446\u0438\u044e, \u0435\u0441\u043b\u0438 \u0441\u043f\u0443\u0442\u043d\u0438\u043a \u0443\u0436\u0435 \u043e\u0431\u043d\u043e\u0432\u043b\u0451\u043d,\n            //  \u043b\u0438\u0431\u043e \u043d\u0435 \u043e\u0431\u043d\u043e\u0432\u043b\u0451\u043d \u0432\u043b\u0430\u0434\u0435\u043b\u0435\u0446 \u0441\u043f\u0443\u0442\u043d\u0438\u043a\u0430.\n            if (!remainingNames.count(body.m_name) || remainingNames.count(orbit.m_ownerName))\n            {\n                continue;\n            }\n            mayContinue = true;\n\n            const vec2 pos2D = orbit.PlanetPosition2D(time);\n            const vec3 pos3D = scale::AU_SIZE * vec3(pos2D.x, 0.f, pos2D.y);\n            const vec3 ownerPos3D = knownPositions[orbit.m_ownerName];\n\n            auto &transform = entity.getComponent<CTransformComponent>();\n            transform.m_position = pos3D + ownerPos3D;\n\n            knownPositions[body.m_name] = transform.m_position;\n            remainingNames.erase(body.m_name);\n        }\n    }\n    while (mayContinue);\n\n    // \u0415\u0441\u043b\u0438 \u0435\u0449\u0451 \u0435\u0441\u0442\u044c \u043d\u0435\u043e\u0431\u043d\u043e\u0432\u043b\u0451\u043d\u043d\u044b\u0435 \u043e\u0431\u044a\u0435\u043a\u0442\u044b, \u0437\u043d\u0430\u0447\u0438\u0442,\n    //  \u0435\u0441\u0442\u044c \u0446\u0438\u043a\u043b\u0438\u0447\u0435\u0441\u043a\u0438\u0435 \u0437\u0430\u0432\u0438\u0441\u0438\u043c\u043e\u0441\u0442\u0438.\n    if (!remainingNames.empty())\n    {\n        throw std::runtime_error(\"Cannot resolve orbit dependency cycle\");\n    }\n}\n", "meta": {"hexsha": "3c37058f61185362fc81bfb22ae7465a25042a1d", "size": 2349, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "chapter_4/lesson_21/KeplerLawSystem.cpp", "max_stars_repo_name": "sergey-shambir/cg_course_examples", "max_stars_repo_head_hexsha": "921b6218d71731bcb79ddddcc92c9d04a72c62ab", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2017-05-13T20:47:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-18T18:18:03.000Z", "max_issues_repo_path": "chapter_4/lesson_21/KeplerLawSystem.cpp", "max_issues_repo_name": "sergey-shambir/cg_course_examples", "max_issues_repo_head_hexsha": "921b6218d71731bcb79ddddcc92c9d04a72c62ab", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapter_4/lesson_21/KeplerLawSystem.cpp", "max_forks_repo_name": "sergey-shambir/cg_course_examples", "max_forks_repo_head_hexsha": "921b6218d71731bcb79ddddcc92c9d04a72c62ab", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2016-10-24T16:24:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-15T11:23:57.000Z", "avg_line_length": 31.7432432432, "max_line_length": 94, "alphanum_fraction": 0.6560238399, "num_tokens": 637, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125848754471, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4625538081521327}}
{"text": "#pragma once\n\n#include \"types.hpp\"\n#include <Eigen/Dense>\n\n/// Compute the gradients of q_bar.\n/** Note: this routine does not care if q are the conserved\n *  or primitive variables.\n *\n * @param [out] dqdx  approximation of dq/dx. Has shape (n_cells, 4).\n * @param [out] dqdy  approximation of dq/dy. Has shape (n_cells, 4).\n * @param       q_bar the cell-averages of `q`. Has shape (n_cells, 4).\n * @param       mesh\n */\nvoid compute_gradients(Eigen::MatrixXd &dqdx,\n                       Eigen::MatrixXd &dqdy,\n                       const Eigen::MatrixXd &q_bar,\n                       const Mesh &mesh) {\n\n    // Compute the gradient of all 4 components of q_bar\n}\n", "meta": {"hexsha": "536119bf7a1e045a257687fdf89b47c1256cbd9d", "size": 671, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "series2_handout/unstructured_euler/gradient.hpp", "max_stars_repo_name": "BeatHubmann/19H-AdvNCSE", "max_stars_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-05T22:38:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-05T22:38:47.000Z", "max_issues_repo_path": "series2_handout/unstructured_euler/gradient.hpp", "max_issues_repo_name": "BeatHubmann/19H-AdvNCSE", "max_issues_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "series2_handout/unstructured_euler/gradient.hpp", "max_forks_repo_name": "BeatHubmann/19H-AdvNCSE", "max_forks_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-12-08T20:43:27.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-08T20:43:27.000Z", "avg_line_length": 30.5, "max_line_length": 71, "alphanum_fraction": 0.6125186289, "num_tokens": 173, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.46255380131503143}}
{"text": "/* -------------------------------------------------------------------------\n *  A repertory of multi primitive-to-primitive (MP2P) ICP algorithms in C++\n * Copyright (C) 2018-2021 Jose Luis Blanco, University of Almeria\n * See LICENSE for license information.\n * ------------------------------------------------------------------------- */\n/**\n * @file   errorTerms.cpp\n * @brief\n * @author Francisco Jos\u00e9 Ma\u00f1as \u00c1lvarez, Jose Luis Blanco Claraco\n * @date   Aug 4, 2020\n */\n\n#include <mp2p_icp/errorTerms.h>\n#include <mp2p_icp/optimal_tf_gauss_newton.h>\n#include <mrpt/math/CVectorFixed.h>\n#include <mrpt/math/TPoint3D.h>\n#include <mrpt/math/geometry.h>\n#include <mrpt/math/ops_containers.h>  // dotProduct()\n#include <mrpt/poses/CPose3D.h>\n#include <mrpt/poses/Lie/SE.h>\n\n#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace mp2p_icp;\nusing namespace mrpt::math;\n\nmrpt::math::CVectorFixedDouble<3> mp2p_icp::error_point2point(\n    const mrpt::tfest::TMatchingPair&                           pairing,\n    const mrpt::poses::CPose3D&                                 relativePose,\n    mrpt::optional_ref<mrpt::math::CMatrixFixed<double, 3, 12>> jacobian)\n{\n    MRPT_START\n    mrpt::math::CVectorFixedDouble<3> error;\n    const mrpt::math::TPoint3D&       l = pairing.local;\n\n    const mrpt::math::TPoint3D g = relativePose.composePoint(l);\n\n    error[0] = g.x - pairing.global.x;\n    error[1] = g.y - pairing.global.y;\n    error[2] = g.z - pairing.global.z;\n\n    // It's possible change the error to scalar with the function\n    // g.DistanceTo(l) Eval Jacobian:\n    if (jacobian)\n    {\n        mrpt::math::CMatrixFixed<double, 3, 12>& J_aux = jacobian.value().get();\n        // clang-format off\n        J_aux = (Eigen::Matrix<double, 3, 12>() <<\n                 l.x,   0,   0, l.y,   0,    0, l.z,   0,   0,  1,  0,  0,\n                   0, l.x,   0,   0, l.y,    0,   0, l.z,   0,  0,  1,  0,\n                   0,   0, l.x,   0,   0,  l.y,   0,   0, l.z,  0,  0,  1\n                 ).finished();\n        // clang-format on\n    }\n\n    return error;\n    MRPT_END\n}\n\nmrpt::math::CVectorFixedDouble<3> mp2p_icp::error_point2line(\n    const mp2p_icp::point_line_pair_t&                          pairing,\n    const mrpt::poses::CPose3D&                                 relativePose,\n    mrpt::optional_ref<mrpt::math::CMatrixFixed<double, 3, 12>> jacobian)\n{\n    MRPT_START\n    mrpt::math::CVectorFixedDouble<3> error;\n    const auto&                       lnGlob = pairing.ln_global;\n\n    // local and global point:\n    const mrpt::math::TPoint3D l = pairing.pt_local;\n    const mrpt::math::TPoint3D g = relativePose.composePoint(l);\n\n    // Module of vector director of line\n    const auto& u = lnGlob.director;\n    const auto  q = (g - lnGlob.pBase);\n\n    const auto uq = mrpt::math::dotProduct<3, double>(u, q);\n\n    error[0] = q[0] - u.x * uq;\n    error[1] = q[1] - u.y * uq;\n    error[2] = q[2] - u.z * uq;\n\n    if (jacobian)\n    {\n        // J1\n        const Eigen::Matrix<double, 3, 3> J1 =\n            (Eigen::Matrix<double, 3, 3>() << 1 - mrpt::square(u.x), -u.x * u.y,\n             -u.x * u.z, -u.y * u.x, 1 - mrpt::square(u.y), -u.y * u.z,\n             -u.z * u.x, -u.z * u.y, 1 - mrpt::square(u.z))\n                .finished();\n        // J2\n        // clang-format off\n        Eigen::Matrix<double, 3, 12> J2 =\n            (Eigen::Matrix<double, 3, 12>() <<\n             l.x,   0,   0, l.y,   0,    0, l.z,   0,   0,  1,  0,  0,\n               0, l.x,   0,   0, l.y,    0,   0, l.z,   0,  0,  1,  0,\n               0,   0, l.x,   0,   0,  l.y,   0,   0, l.z,  0,  0,  1\n             ).finished();\n        // clang-format on\n        mrpt::math::CMatrixFixed<double, 3, 12>& J_aux = jacobian.value().get();\n\n        J_aux = J1 * J2;\n    }\n    return error;\n    MRPT_END\n}\n\nmrpt::math::CVectorFixedDouble<3> mp2p_icp::error_point2plane(\n    const mp2p_icp::point_plane_pair_t&                         pairing,\n    const mrpt::poses::CPose3D&                                 relativePose,\n    mrpt::optional_ref<mrpt::math::CMatrixFixed<double, 3, 12>> jacobian)\n{\n    MRPT_START\n    mrpt::math::CVectorFixedDouble<3> error;\n    const auto&                       p      = pairing.pt_local;\n    const auto&                       pl_aux = pairing.pl_global.plane;\n    const mrpt::math::TPoint3D        l      = TPoint3D(p.x, p.y, p.z);\n    mrpt::math::TPoint3D              g;\n    relativePose.composePoint(l, g);\n    double mod_n = mrpt::square(pl_aux.coefs[0]) +\n                   mrpt::square(pl_aux.coefs[1]) +\n                   mrpt::square(pl_aux.coefs[2]);\n\n    error[0] = -(pl_aux.coefs[0] / mod_n) *\n               (pl_aux.coefs[0] * g.x + pl_aux.coefs[1] * g.y +\n                pl_aux.coefs[2] * g.z + pl_aux.coefs[3]);\n    error[1] = -(pl_aux.coefs[1] / mod_n) *\n               (pl_aux.coefs[0] * g.x + pl_aux.coefs[1] * g.y +\n                pl_aux.coefs[2] * g.z + pl_aux.coefs[3]);\n    error[2] = -(pl_aux.coefs[2] / mod_n) *\n               (pl_aux.coefs[0] * g.x + pl_aux.coefs[1] * g.y +\n                pl_aux.coefs[2] * g.z + pl_aux.coefs[3]);\n    if (jacobian)\n    {\n        // Eval Jacobian:\n        // J1\n        const Eigen::Matrix<double, 3, 3> J1 =\n            (Eigen::Matrix<double, 3, 3>()\n                 << -mrpt::square(pl_aux.coefs[0]) / mod_n,\n             -pl_aux.coefs[0] * pl_aux.coefs[1] / mod_n,\n             -pl_aux.coefs[0] * pl_aux.coefs[2] / mod_n,\n             -pl_aux.coefs[1] * pl_aux.coefs[0] / mod_n,\n             -mrpt::square(pl_aux.coefs[1]) / mod_n,\n             -pl_aux.coefs[1] * pl_aux.coefs[2] / mod_n,\n             -pl_aux.coefs[2] * pl_aux.coefs[0] / mod_n,\n             -pl_aux.coefs[2] * pl_aux.coefs[1] / mod_n,\n             -mrpt::square(pl_aux.coefs[2]) / mod_n)\n                .finished();\n        // J2\n        // clang-format off\n        const Eigen::Matrix<double, 3, 12> J2 =\n            (Eigen::Matrix<double, 3, 12>() <<\n             l.x,   0,   0, l.y,   0,    0, l.z,   0,   0,  1,  0,  0,\n               0, l.x,   0,   0, l.y,    0,   0, l.z,   0,  0,  1,  0,\n               0,   0, l.x,   0,   0,  l.y,   0,   0, l.z,  0,  0,  1\n             ).finished();\n        // clang-format on\n\n        mrpt::math::CMatrixFixed<double, 3, 12>& J_aux = jacobian.value().get();\n        J_aux                                          = J1 * J2;\n    }\n    return error;\n    MRPT_END\n}\n\nmrpt::math::CVectorFixedDouble<4> mp2p_icp::error_line2line(\n    const mp2p_icp::matched_line_t&                             pairing,\n    const mrpt::poses::CPose3D&                                 relativePose,\n    mrpt::optional_ref<mrpt::math::CMatrixFixed<double, 4, 12>> jacobian)\n{\n    MRPT_START\n    mrpt::math::CVectorFixedDouble<4> error;\n    mrpt::math::TLine3D               ln_aux;\n    mrpt::math::TPoint3D              g;\n\n    const auto& p0 = pairing.ln_local.pBase;\n    const auto& u0 = pairing.ln_local.director;\n    const auto& p1 = pairing.ln_global.pBase;\n    const auto& u1 = pairing.ln_global.director;\n\n    relativePose.composePoint(p0, g);\n    ln_aux.pBase = mrpt::math::TPoint3D(g);\n\n    // Homogeneous matrix calculation\n    mrpt::math::CMatrixDouble44 aux;\n    relativePose.getHomogeneousMatrix(aux);\n    const Eigen::Matrix<double, 4, 4> T = aux.asEigen();\n\n    // Projection of the director vector for the new pose\n    const Eigen::Matrix<double, 1, 4> U =\n        (Eigen::Matrix<double, 1, 4>() << u0[0], u0[1], u0[2], 1).finished();\n    const Eigen::Matrix<double, 1, 4> U_T = U * T;\n    ln_aux.director                       = {U_T[0], U_T[1], U_T[2]};\n\n    // Angle formed between the lines\n    double alfa = getAngle(pairing.ln_global, ln_aux) * 180 / (2 * 3.14159265);\n    /*\n        std::cout << \"\\nLine 1:\\n\"\n                  <<  pairing.ln_this << \"\\nLine 2:\\n\"\n                   << pairing.ln_other << \"\\nLine 2':\\n\"\n                   << ln_aux << \"\\nAngle:\\n\"\n                   << alfa << \"\\nT:\\n\"\n                   <<  T << \"\\n\";\n    */\n\n    // p_r0 = (p-r_{0,r}). Ec.20\n    const Eigen::Matrix<double, 1, 3> p_r2 =\n        (Eigen::Matrix<double, 1, 3>() << ln_aux.pBase.x - p1.x,\n         ln_aux.pBase.y - p1.y, ln_aux.pBase.z - p1.z)\n            .finished();\n\n    const Eigen::Matrix<double, 1, 3> rv =\n        (Eigen::Matrix<double, 1, 3>() << u1[0], u1[1], u1[2]).finished();\n\n    // Relationship between lines\n    const double tolerance = 0.01;\n    if (abs(alfa) < tolerance)\n    {  // Parallel\n        // Error: Ec.20\n        error[0] = mrpt::square(pairing.ln_global.distance(ln_aux.pBase));\n        if (jacobian)\n        {\n            // Module of vector director of line\n            double mod_rv = rv * rv.transpose();\n\n            // J1: Ec.22\n            Eigen::Matrix<double, 1, 3> J1 =\n                2 * p_r2 - (2 / mod_rv) * (p_r2 * rv.transpose()) * rv;\n            // J2: Ec.23\n            // clang-format off\n            const Eigen::Matrix<double, 3, 12> J2 =\n                (Eigen::Matrix<double, 3, 12>() <<\n                 p0.x,    0,    0, p0.y,    0,    0, p0.z,    0,    0, 1, 0, 0,\n                    0, p0.x,    0,    0, p0.y,    0,    0, p0.z,    0, 0, 1, 0,\n                    0,    0, p0.x,    0,    0, p0.y,    0,    0, p0.z, 0, 0, 1\n                 ).finished();\n            // clang-format on\n            // Build Jacobian\n            mrpt::math::CMatrixFixed<double, 4, 12>& J_auxp =\n                jacobian.value().get();\n            J_auxp.block<1, 12>(0, 0) = J1 * J2;\n        }\n    }\n    else\n    {  // Rest\n        // Error:\n        // Cross product (r_u x r_2,v)\n        const double rw_x = U_T[1] * u1[2] - U_T[2] * u1[1];\n        const double rw_y = -(U_T[0] * u1[2] - U_T[2] * u1[0]);\n        const double rw_z = U_T[0] * u1[1] - U_T[1] * u1[0];\n\n        const Eigen::Matrix<double, 1, 3> r_w =\n            (Eigen::Matrix<double, 1, 3>() << rw_x, rw_y, rw_z).finished();\n        double aux_rw = r_w * r_w.transpose();\n        // Error 1. Ec.26\n        error[0] = p_r2.dot(r_w) / sqrt(aux_rw);\n        // Error 2. Ec.27\n        error[1] = U_T[0] - u1[0];\n        error[2] = U_T[1] - u1[1];\n        error[3] = U_T[2] - u1[2];\n        if (jacobian)\n        {\n            // J1.1: Ec.32\n            Eigen::Matrix<double, 1, 3> J1_1 = r_w / sqrt(aux_rw);\n\n            // J1.2:\n            // A\n            const double A =\n                p_r2[0] * r_w[0] + p_r2[1] * r_w[1] + p_r2[2] * r_w[2];\n            const double Ax = -u1[2] * p_r2[1] + u1[1] * p_r2[2];\n            const double Ay = u1[2] * p_r2[0] - u1[0] * p_r2[2];\n            const double Az = -u1[1] * p_r2[0] + u1[0] * p_r2[1];\n            // B\n            const double B  = sqrt(aux_rw);\n            const double Bx = (-u1[2] * r_w[1] + u1[1] * r_w[2]) / B;\n            const double By = (u1[2] * r_w[0] + u1[0] * r_w[2]) / B;\n            const double Bz = (-u1[1] * r_w[0] + u1[0] * r_w[1]) / B;\n\n#if 0\n            std::cout << \"\\nA: \" << A << \"\\nAx: \" << Ax << \"\\nAy: \" << Ay\n                      << \"\\nAz: \" << Az << \"\\nB: \" << B << \"\\nBx: \" << Bx\n                      << \"\\nBy: \" << By << \"\\nBz: \" << Bz << \"\\n\";\n#endif\n\n            // Ec.36\n            // clang-format off\n            Eigen::Matrix<double, 1, 3> J1_2 =\n                (Eigen::Matrix<double, 1, 3>() <<\n                 (Ax * B - A * Bx) / mrpt::square(B),\n                 (Ay * B - A * By) / mrpt::square(B),\n                 (Az * B - A * Bz) / mrpt::square(B)\n                 ).finished();\n            // clang-format on\n\n            // J1.3: Ec.37-38\n            // clang-format off\n            Eigen::Matrix<double, 3, 6> J1_3 =\n                (Eigen::Matrix<double, 3, 6>() <<\n                 0, 0, 0, 1, 0, 0,\n                 0, 0, 0, 0, 1, 0,\n                 0, 0, 0, 0, 0, 1\n                 ).finished();\n            // clang-format on\n\n            // J1: Ec.29\n            Eigen::Matrix<double, 4, 6> J1;\n            J1.block<1, 3>(0, 0) = J1_1;\n            J1.block<1, 3>(0, 3) = J1_2;\n            J1.block<3, 6>(1, 0) = J1_3;\n\n            // J2: Ec.39-41\n            // clang-format off\n            const Eigen::Matrix<double, 6, 12> J2 =\n                (Eigen::Matrix<double, 6, 12>() <<\n                 p0.x,     0,     0,  p0.y,     0,     0,  p0.z,     0,     0, 1, 0, 0,\n                    0,  p0.x,     0,     0,  p0.y,     0,     0,  p0.z,     0, 0, 1, 0,\n                    0,     0,  p0.x,     0,     0,  p0.y,     0,     0,  p0.z, 0, 0, 1,\n                -u0[0],     0,     0, -u0[1],     0,     0, -u0[2],     0,     0, 0, 0, 0,\n                    0, -u0[0],     0,     0, -u0[1],     0,     0, -u0[2],     0, 0, 0, 0,\n                    0,     0, -u0[0],     0,     0, -u0[1],     0,     0, -u0[2], 0, 0, 0\n                ).finished();\n            // clang-format on\n            // Build Jacobian\n            mrpt::math::CMatrixFixed<double, 4, 12>& J_aux =\n                jacobian.value().get();\n            J_aux.block<4, 12>(0, 0) = J1 * J2;\n\n            std::cout << \"\\nJ1:\\n\" << J1 << \"\\nJ2:\\n\" << J2 << \"\\n\";\n        }\n    }\n    //    std::cout<<\"\\nError:\\n\"<<error;\n    return error;\n    MRPT_END\n}\n\nmrpt::math::CVectorFixedDouble<3> mp2p_icp::error_plane2plane(\n    const mp2p_icp::matched_plane_t&                            pairing,\n    const mrpt::poses::CPose3D&                                 relativePose,\n    mrpt::optional_ref<mrpt::math::CMatrixFixed<double, 3, 12>> jacobian)\n{\n    MRPT_START\n    mrpt::math::CVectorFixedDouble<3> error;\n\n    const auto nl = pairing.p_local.plane.getNormalVector();\n    const auto ng = pairing.p_global.plane.getNormalVector();\n\n    const auto p_oplus_nl = relativePose.rotateVector(nl);\n\n    for (int i = 0; i < 3; i++) error[i] = p_oplus_nl[i] - ng[i];\n\n    if (jacobian)\n    {\n        // Eval Jacobian:\n\n        // df_oplus(A,p)/d_A. Section 7.3.2 tech. report:\n        // \"A tutorial on SE(3) transformation parameterizations and\n        // on-manifold optimization\"\n        // Modified, to discard the last I_3 block, since this particular\n        // cost function is insensible to translations.\n\n        // clang-format off\n        mrpt::math::CMatrixFixed<double, 3, 12>& J_aux = jacobian.value().get();\n        J_aux = (Eigen::Matrix<double, 3, 12>() <<\n                 nl.x,    0,    0, nl.y,    0,    0, nl.z,    0,    0,  0,  0,  0,\n                    0, nl.x,    0,    0, nl.y,    0,    0, nl.z,    0,  0,  0,  0,\n                    0,    0, nl.x,    0,    0, nl.y,    0,    0, nl.z,  0,  0,  0\n                ).finished();\n        // clang-format on\n    }\n    return error;\n    MRPT_END\n}\n", "meta": {"hexsha": "db1be2ffafed000aa66944e35869b9194c2c3539", "size": 14489, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mp2p_icp/src/errorTerms.cpp", "max_stars_repo_name": "MOLAorg/mp2_icp", "max_stars_repo_head_hexsha": "e53a5f5f2cc6b86a095d1cba6f07f03c13a72abb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-06-07T08:10:09.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-07T15:01:02.000Z", "max_issues_repo_path": "mp2p_icp/src/errorTerms.cpp", "max_issues_repo_name": "MOLAorg/mp2_icp", "max_issues_repo_head_hexsha": "e53a5f5f2cc6b86a095d1cba6f07f03c13a72abb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mp2p_icp/src/errorTerms.cpp", "max_forks_repo_name": "MOLAorg/mp2_icp", "max_forks_repo_head_hexsha": "e53a5f5f2cc6b86a095d1cba6f07f03c13a72abb", "max_forks_repo_licenses": ["BSD-3-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.7406417112, "max_line_length": 90, "alphanum_fraction": 0.4675270895, "num_tokens": 5026, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.46255380131503143}}
{"text": "// Copyright (c) 2018 Franka Emika GmbH\n// Use of this source code is governed by the Apache-2.0 license, see LICENSE\n\n#include <gtest/gtest.h>\n//------------g alexander mac osx ---------------------//\n#if defined (APPLE)\n#include </opt/local/include/eigen3/Eigen/Dense>\n#else\n#include <Eigen/Dense>\n#endif\n\n#include <franka/rate_limiting.h>\n\nusing namespace franka;\n\nconst double kNoLimit{std::numeric_limits<double>::max()};\n\nstd::array<double, 7> kJointsNoLimit{\n    {kNoLimit, kNoLimit, kNoLimit, kNoLimit, kNoLimit, kNoLimit, kNoLimit}};\n\ntemplate <int size>\nstd::array<double, size> integrateOneSample(std::array<double, size> last_value,\n                                            std::array<double, size> derivative,\n                                            double delta_t) {\n  std::array<double, size> result{};\n  for (size_t i = 0; i < size; i++) {\n    result[i] = last_value[i] + derivative[i] * delta_t;\n  }\n  return result;\n}\n\ntemplate <int size>\nstd::array<double, size> differentiateOneSample(std::array<double, size> value,\n                                                std::array<double, size> last_value,\n                                                double delta_t) {\n  std::array<double, size> result{};\n  for (size_t i = 0; i < size; i++) {\n    result[i] = (value[i] - last_value[i]) / delta_t;\n  }\n  return result;\n}\n\nstd::array<double, 16> integrateOneSample(std::array<double, 16> last_pose,\n                                          std::array<double, 6> twist,\n                                          double delta_t) {\n  Eigen::Affine3d pose(Eigen::Matrix4d::Map(last_pose.data()));\n  Eigen::Map<Eigen::Matrix<double, 6, 1>> dx(twist.data());\n  Eigen::Matrix3d omega_skew;\n  omega_skew << 0, -dx[5], dx[4], dx[5], 0, -dx[3], -dx[4], dx[3], 0;\n  pose.linear() << pose.linear() + omega_skew * pose.linear() * delta_t;\n  pose.translation() << pose.translation() + dx.head(3) * delta_t;\n\n  std::array<double, 16> pose_after_integration{};\n  Eigen::Map<Eigen::Matrix4d>(&pose_after_integration[0], 4, 4) = pose.matrix();\n  return pose_after_integration;\n}\n\nstd::array<double, 6> differentiateOneSample(std::array<double, 16> value,\n                                             std::array<double, 16> last_value,\n                                             double delta_t) {\n  Eigen::Affine3d pose(Eigen::Matrix4d::Map(value.data()));\n  Eigen::Affine3d last_pose(Eigen::Matrix4d::Map(last_value.data()));\n  Eigen::Matrix<double, 6, 1> dx;\n\n  dx.head(3) << (pose.translation() - last_pose.translation()) / delta_t;\n  auto delta_rotation = (pose.linear() - pose.linear()) / delta_t;\n  Eigen::Matrix3d rotational_twist = delta_rotation * last_pose.linear();\n  dx.tail(3) << rotational_twist(2, 1), rotational_twist(0, 2), rotational_twist(1, 0);\n\n  std::array<double, 6> twist{};\n  Eigen::Map<Eigen::Matrix<double, 6, 1>>(&twist[0], 6, 1) = dx;\n  return twist;\n}\n\nbool violatesLimits(double desired_value, double max_value) {\n  return std::abs(desired_value) > max_value;\n}\n\nbool violatesLimits(std::array<double, 7> values, std::array<double, 7> max_values) {\n  bool violates_limits = false;\n  for (size_t i = 0; i < 7 && !violates_limits; i++) {\n    violates_limits = violates_limits || violatesLimits(values[i], max_values[i]);\n  }\n  return violates_limits;\n}\n\nbool violatesRateLimits(std::array<double, 7> max_derivatives,\n                        std::array<double, 7> values,\n                        std::array<double, 7> last_desired_values,\n                        double delta_t) {\n  return violatesLimits(differentiateOneSample<7>(values, last_desired_values, delta_t),\n                        max_derivatives);\n}\n\nbool violatesRateLimits(std::array<double, 7> max_values,\n                        std::array<double, 7> max_derivatives,\n                        std::array<double, 7> max_dderivatives,\n                        std::array<double, 7> values,\n                        std::array<double, 7> last_values,\n                        std::array<double, 7> last_dvalues,\n                        double delta_t) {\n  std::array<double, 7> desired_derivatives =\n      differentiateOneSample<7>(values, last_values, delta_t);\n\n  return violatesLimits(values, max_values) ||\n         violatesRateLimits(max_derivatives, values, last_values, delta_t) ||\n         violatesRateLimits(max_dderivatives, desired_derivatives, last_dvalues, delta_t);\n}\n\nbool violatesRateLimits(double max_translational_dx,\n                        double max_translational_ddx,\n                        double max_translational_dddx,\n                        double max_rotational_dx,\n                        double max_rotational_ddx,\n                        double max_rotational_dddx,\n                        std::array<double, 6> cmd_dx,\n                        std::array<double, 6> O_dP_EE_c,\n                        std::array<double, 6> O_ddP_EE_c,\n                        double delta_t) {\n  Eigen::Map<Eigen::Matrix<double, 6, 1>> dx(cmd_dx.data());\n  Eigen::Map<Eigen::Matrix<double, 6, 1>> last_dx(O_dP_EE_c.data());\n  Eigen::Map<Eigen::Matrix<double, 6, 1>> last_ddx(O_ddP_EE_c.data());\n  Eigen::Matrix<double, 6, 1> ddx = (dx - last_dx) / delta_t;\n  Eigen::Matrix<double, 6, 1> dddx = (ddx - last_ddx) / delta_t;\n  return violatesLimits(dx.head(3).norm(), max_translational_dx) ||\n         violatesLimits(ddx.head(3).norm(), max_translational_ddx) ||\n         violatesLimits(dddx.head(3).norm(), max_translational_dddx) ||\n         violatesLimits(dx.tail(3).norm(), max_rotational_dx) ||\n         violatesLimits(ddx.tail(3).norm(), max_rotational_ddx) ||\n         violatesLimits(dddx.tail(3).norm(), max_rotational_dddx);\n}\n\nstd::array<double, 7> generateValuesIntoLimits(std::array<double, 7> last_cmd_values,\n                                               std::array<double, 7> max_derivatives,\n                                               double eps,\n                                               double delta_t) {\n  std::array<double, 7> cmd_value{};\n  for (size_t i = 0; i < 7; i++) {\n    // Make sure that the integration yields a value into limits\n    cmd_value[i] = last_cmd_values[i] + (max_derivatives[i] - std::min(std::max(std::abs(eps), 0.0),\n                                                                       2.0 * max_derivatives[i])) *\n                                            delta_t;\n  }\n  return cmd_value;\n}\n\nstd::array<double, 7> generateValuesOutsideLimits(std::array<double, 7> last_cmd_values,\n                                                  std::array<double, 7> max_derivatives,\n                                                  double eps,\n                                                  double delta_t) {\n  std::array<double, 7> cmd_value{};\n  for (size_t i = 0; i < 7; i++) {\n    // Make sure that diff yields a value outside limits\n    cmd_value[i] =\n        last_cmd_values[i] + (max_derivatives[i] + std::max(std::abs(eps), kLimitEps)) * delta_t;\n  }\n  return cmd_value;\n}\n\nstd::array<double, 6> generateValuesIntoLimits(std::array<double, 6> last_cmd_values,\n                                               double max_translational_derivative,\n                                               double max_rotational_derivative,\n                                               double eps,\n                                               double delta_t) {\n  Eigen::Map<Eigen::Matrix<double, 6, 1>> last_values(last_cmd_values.data());\n  Eigen::Matrix<double, 6, 1> values;\n  Eigen::Vector3d unit_vector(1.0, 0.0, 0.0);\n  std::array<double, 6> result;\n  values.head(3) << last_values.head(3) + unit_vector *\n                                              (max_translational_derivative -\n                                               std::min(std::max(std::abs(eps), 0.0),\n                                                        2.0 * max_translational_derivative)) *\n                                              delta_t;\n  values.tail(3) << last_values.tail(3) + unit_vector *\n                                              (max_rotational_derivative -\n                                               std::min(std::max(std::abs(eps), 0.0),\n                                                        2.0 * max_rotational_derivative)) *\n                                              delta_t;\n\n  Eigen::Matrix<double, 6, 1>::Map(&result[0], 6) = values;\n  return result;\n}\n\nstd::array<double, 6> generateValuesOutsideLimits(std::array<double, 6> last_cmd_values,\n                                                  double max_translational_derivative,\n                                                  double max_rotational_derivative,\n                                                  double eps,\n                                                  double delta_t) {\n  Eigen::Map<Eigen::Matrix<double, 6, 1>> last_values(last_cmd_values.data());\n  Eigen::Matrix<double, 6, 1> values;\n  Eigen::Vector3d unit_vector(1.0, 0.0, 0.0);\n  std::array<double, 6> result;\n  values.head(3) << last_values.head(3) +\n                        unit_vector *\n                            (max_translational_derivative + std::max(std::abs(eps), kLimitEps)) *\n                            delta_t;\n  values.tail(3) << last_values.tail(3) +\n                        unit_vector *\n                            (max_rotational_derivative + std::max(std::abs(eps), kLimitEps)) *\n                            delta_t;\n\n  Eigen::Matrix<double, 6, 1>::Map(&result[0], 6) = values;\n  return result;\n}\n\nTEST(RateLimiting, MaxDerivative) {\n  std::array<double, 7> max_derivatives{{100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0}};\n  std::array<double, 7> last_cmd_values{{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}};\n  double eps{1e-2};\n\n  // Desired values are into limits and unchanged after limitRate\n  std::array<double, 7> values_into_limits =\n      generateValuesIntoLimits(last_cmd_values, max_derivatives, eps, kDeltaT);\n  ASSERT_FALSE(violatesRateLimits(max_derivatives, values_into_limits, last_cmd_values, kDeltaT));\n  EXPECT_EQ(values_into_limits, limitRate(max_derivatives, values_into_limits, last_cmd_values));\n\n  // Desired values are outside limits and limited after limitRate\n  std::array<double, 7> values_outside_limits =\n      generateValuesOutsideLimits(last_cmd_values, max_derivatives, eps, kDeltaT);\n  std::array<double, 7> limited_values =\n      limitRate(max_derivatives, values_outside_limits, last_cmd_values);\n  ASSERT_TRUE(violatesRateLimits(max_derivatives, values_outside_limits, last_cmd_values, kDeltaT));\n  EXPECT_NE(values_outside_limits, limited_values);\n  EXPECT_FALSE(violatesRateLimits(max_derivatives, limited_values, last_cmd_values, kDeltaT));\n}\n\nTEST(RateLimiting, JointVelocity) {\n  std::array<double, 7> last_cmd_velocity{{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}};\n  std::array<double, 7> last_cmd_acceleration{{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}};\n  std::array<double, 7> max_acceleration{{10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0}};\n  std::array<double, 7> max_jerk{{100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0}};\n  double eps{1e-2};\n\n  // Desired values are into limits and unchanged after limitRate (jerk)\n  std::array<double, 7> joint_velocity_into_limits = integrateOneSample<7>(\n      last_cmd_velocity, generateValuesIntoLimits(last_cmd_acceleration, max_jerk, eps, kDeltaT),\n      kDeltaT);\n  ASSERT_FALSE(violatesRateLimits(kJointsNoLimit, kJointsNoLimit, max_jerk,\n                                  joint_velocity_into_limits, last_cmd_velocity,\n                                  last_cmd_acceleration, kDeltaT));\n  EXPECT_EQ(joint_velocity_into_limits,\n            limitRate(kJointsNoLimit, kJointsNoLimit, max_jerk, joint_velocity_into_limits,\n                      last_cmd_velocity, last_cmd_acceleration));\n\n  // Desired values are into limits and unchanged after limitRate (acceleration)\n  joint_velocity_into_limits =\n      generateValuesIntoLimits(last_cmd_velocity, max_acceleration, eps, kDeltaT);\n  ASSERT_FALSE(violatesRateLimits(kJointsNoLimit, max_acceleration, kJointsNoLimit,\n                                  joint_velocity_into_limits, last_cmd_velocity,\n                                  last_cmd_acceleration, kDeltaT));\n  EXPECT_EQ(joint_velocity_into_limits,\n            limitRate(kJointsNoLimit, max_acceleration, kJointsNoLimit, joint_velocity_into_limits,\n                      last_cmd_velocity, last_cmd_acceleration));\n\n  // Desired values are outside limits (jerk violation) and limited after limitRate\n  std::array<double, 7> joint_velocity_outside_limits = integrateOneSample<7>(\n      last_cmd_velocity, generateValuesOutsideLimits(last_cmd_acceleration, max_jerk, eps, kDeltaT),\n      kDeltaT);\n  std::array<double, 7> limited_joint_velocity =\n      limitRate(kJointsNoLimit, kJointsNoLimit, max_jerk, joint_velocity_outside_limits,\n                last_cmd_velocity, last_cmd_acceleration);\n  ASSERT_TRUE(violatesRateLimits(kJointsNoLimit, kJointsNoLimit, max_jerk,\n                                 joint_velocity_outside_limits, last_cmd_velocity,\n                                 last_cmd_acceleration, kDeltaT));\n  EXPECT_NE(joint_velocity_outside_limits, limited_joint_velocity);\n  EXPECT_FALSE(violatesRateLimits(kJointsNoLimit, kJointsNoLimit, max_jerk, limited_joint_velocity,\n                                  last_cmd_velocity, last_cmd_acceleration, kDeltaT));\n\n  // Desired values are outside limits (acceleration violation) and limited after limitRate\n  joint_velocity_outside_limits =\n      generateValuesOutsideLimits(last_cmd_velocity, max_acceleration, eps, kDeltaT);\n  limited_joint_velocity =\n      limitRate(kJointsNoLimit, max_acceleration, kJointsNoLimit, joint_velocity_outside_limits,\n                last_cmd_velocity, last_cmd_acceleration);\n  ASSERT_TRUE(violatesRateLimits(kJointsNoLimit, max_acceleration, kJointsNoLimit,\n                                 joint_velocity_outside_limits, last_cmd_velocity,\n                                 last_cmd_acceleration, kDeltaT));\n  EXPECT_NE(joint_velocity_outside_limits, limited_joint_velocity);\n  EXPECT_FALSE(violatesRateLimits(kJointsNoLimit, max_acceleration, kJointsNoLimit,\n                                  limited_joint_velocity, last_cmd_velocity, last_cmd_acceleration,\n                                  kDeltaT));\n}\n\nTEST(RateLimiting, JointPosition) {\n  std::array<double, 7> last_cmd_position{{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}};\n  std::array<double, 7> last_cmd_velocity{{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}};\n  std::array<double, 7> last_cmd_acceleration{{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}};\n  std::array<double, 7> max_acceleration{{10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0}};\n  std::array<double, 7> max_jerk{{100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0}};\n  double eps{1e-2};\n\n  // Desired values are into limits and unchanged after limitRate (jerk)\n  std::array<double, 7> joint_position_into_limits = integrateOneSample<7>(\n      last_cmd_position,\n      integrateOneSample<7>(last_cmd_velocity,\n                            generateValuesIntoLimits(last_cmd_acceleration, max_jerk, eps, kDeltaT),\n                            kDeltaT),\n      kDeltaT);\n  ASSERT_FALSE(violatesRateLimits(\n      kJointsNoLimit, kJointsNoLimit, max_jerk,\n      differentiateOneSample<7>(joint_position_into_limits, last_cmd_position, kDeltaT),\n      last_cmd_velocity, last_cmd_acceleration, kDeltaT));\n  EXPECT_EQ(joint_position_into_limits,\n            limitRate(kJointsNoLimit, kJointsNoLimit, max_jerk, joint_position_into_limits,\n                      last_cmd_position, last_cmd_velocity, last_cmd_acceleration));\n\n  // Desired values are into limits and unchanged after limitRate (acceleration)\n  joint_position_into_limits = integrateOneSample<7>(\n      last_cmd_position,\n      generateValuesIntoLimits(last_cmd_velocity, max_acceleration, eps, kDeltaT), kDeltaT);\n  ASSERT_FALSE(violatesRateLimits(\n      kJointsNoLimit, max_acceleration, kJointsNoLimit,\n      differentiateOneSample<7>(joint_position_into_limits, last_cmd_position, kDeltaT),\n      last_cmd_velocity, last_cmd_acceleration, kDeltaT));\n  EXPECT_EQ(joint_position_into_limits,\n            limitRate(kJointsNoLimit, max_acceleration, kJointsNoLimit, joint_position_into_limits,\n                      last_cmd_position, last_cmd_velocity, last_cmd_acceleration));\n\n  // Desired values are outside limits (jerk violation) and limited after limitRate\n  std::array<double, 7> joint_position_outside_limits = integrateOneSample<7>(\n      last_cmd_position,\n      integrateOneSample<7>(\n          last_cmd_velocity,\n          generateValuesOutsideLimits(last_cmd_acceleration, max_jerk, eps, kDeltaT), kDeltaT),\n      kDeltaT);\n  std::array<double, 7> limited_joint_position =\n      limitRate(kJointsNoLimit, kJointsNoLimit, max_jerk, joint_position_outside_limits,\n                last_cmd_position, last_cmd_velocity, last_cmd_acceleration);\n  ASSERT_TRUE(violatesRateLimits(\n      kJointsNoLimit, kJointsNoLimit, max_jerk,\n      differentiateOneSample<7>(joint_position_outside_limits, last_cmd_position, kDeltaT),\n      last_cmd_velocity, last_cmd_acceleration, kDeltaT));\n  EXPECT_NE(joint_position_outside_limits, limited_joint_position);\n  EXPECT_FALSE(violatesRateLimits(\n      kJointsNoLimit, kJointsNoLimit, max_jerk,\n      differentiateOneSample<7>(limited_joint_position, last_cmd_position, kDeltaT),\n      last_cmd_velocity, last_cmd_acceleration, kDeltaT));\n\n  // Desired values outside limits (acceleration violation) and limited after limitRate\n  joint_position_outside_limits = integrateOneSample<7>(\n      last_cmd_position,\n      generateValuesOutsideLimits(last_cmd_velocity, max_acceleration, eps, kDeltaT), kDeltaT);\n  limited_joint_position =\n      limitRate(kJointsNoLimit, max_acceleration, kJointsNoLimit, joint_position_outside_limits,\n                last_cmd_position, last_cmd_velocity, last_cmd_acceleration);\n  ASSERT_TRUE(violatesRateLimits(\n      kJointsNoLimit, max_acceleration, kJointsNoLimit,\n      differentiateOneSample<7>(joint_position_outside_limits, last_cmd_position, kDeltaT),\n      last_cmd_velocity, last_cmd_acceleration, kDeltaT));\n  EXPECT_NE(joint_position_outside_limits, limited_joint_position);\n  EXPECT_FALSE(violatesRateLimits(\n      kJointsNoLimit, max_acceleration, kJointsNoLimit,\n      differentiateOneSample<7>(limited_joint_position, last_cmd_position, kDeltaT),\n      last_cmd_velocity, last_cmd_acceleration, kDeltaT));\n}\n\nTEST(RateLimiting, CartesianVelocity) {\n  std::array<double, 6> last_cmd_velocity{{0.0, 0.0, 0.0, 0.0, 0.0, 0.0}};\n  std::array<double, 6> last_cmd_acceleration{{0.0, 0.0, 0.0, 0.0, 0.0, 0.0}};\n  double max_translational_acceleration{10.0};\n  double max_translational_jerk{100.0};\n  double max_rotational_acceleration{5.0};\n  double max_rotational_jerk{50.0};\n  double eps{1e-2};\n\n  // Desired values are into limits and unchanged after limitRate (rotational and translational\n  // jerk)\n  std::array<double, 6> cartesian_velocity_into_limits =\n      integrateOneSample<6>(last_cmd_velocity,\n                            generateValuesIntoLimits(last_cmd_acceleration, max_translational_jerk,\n                                                     max_rotational_jerk, eps, kDeltaT),\n                            kDeltaT);\n  ASSERT_FALSE(violatesRateLimits(kNoLimit, kNoLimit, max_translational_jerk, kNoLimit, kNoLimit,\n                                  max_rotational_jerk, cartesian_velocity_into_limits,\n                                  last_cmd_velocity, last_cmd_acceleration, kDeltaT));\n  EXPECT_EQ(\n      cartesian_velocity_into_limits,\n      limitRate(kNoLimit, kNoLimit, max_translational_jerk, kNoLimit, kNoLimit, max_rotational_jerk,\n                cartesian_velocity_into_limits, last_cmd_velocity, last_cmd_acceleration));\n\n  // Desired values are into limits and unchanged after limitRate (rotational and translational\n  // acceleration)\n  cartesian_velocity_into_limits = generateValuesIntoLimits(\n      last_cmd_velocity, max_translational_acceleration, max_rotational_acceleration, eps, kDeltaT);\n  ASSERT_FALSE(violatesRateLimits(\n      kNoLimit, max_translational_acceleration, kNoLimit, kNoLimit, max_rotational_acceleration,\n      kNoLimit, cartesian_velocity_into_limits, last_cmd_velocity, last_cmd_acceleration, kDeltaT));\n  EXPECT_EQ(cartesian_velocity_into_limits,\n            limitRate(kNoLimit, max_translational_acceleration, kNoLimit, kNoLimit,\n                      max_rotational_acceleration, kNoLimit, cartesian_velocity_into_limits,\n                      last_cmd_velocity, last_cmd_acceleration));\n\n  // Desired values are outside limits (rotational and translational jerk violation) and limited\n  // after limitRate\n  std::array<double, 6> cartesian_velocity_outside_limits = integrateOneSample<6>(\n      last_cmd_velocity,\n      generateValuesOutsideLimits(last_cmd_acceleration, max_translational_jerk,\n                                  max_rotational_jerk, eps, kDeltaT),\n      kDeltaT);\n  std::array<double, 6> limited_cartesian_velocity =\n      limitRate(kNoLimit, kNoLimit, max_translational_jerk, kNoLimit, kNoLimit, max_rotational_jerk,\n                cartesian_velocity_outside_limits, last_cmd_velocity, last_cmd_acceleration);\n  ASSERT_TRUE(violatesRateLimits(kNoLimit, kNoLimit, max_translational_jerk, kNoLimit, kNoLimit,\n                                 max_rotational_jerk, cartesian_velocity_outside_limits,\n                                 last_cmd_velocity, last_cmd_acceleration, kDeltaT));\n  EXPECT_NE(cartesian_velocity_outside_limits, limited_cartesian_velocity);\n  EXPECT_FALSE(violatesRateLimits(kNoLimit, kNoLimit, max_translational_jerk, kNoLimit, kNoLimit,\n                                  max_rotational_jerk, limited_cartesian_velocity,\n                                  last_cmd_velocity, last_cmd_acceleration, kDeltaT));\n\n  // Desired values are outside limits (rotational and translational acceleration violation) and\n  // limited after limitRate\n  cartesian_velocity_outside_limits = generateValuesOutsideLimits(\n      last_cmd_velocity, max_translational_acceleration, max_rotational_acceleration, eps, kDeltaT);\n  limited_cartesian_velocity = limitRate(\n      kNoLimit, max_translational_acceleration, kNoLimit, kNoLimit, max_rotational_acceleration,\n      kNoLimit, cartesian_velocity_outside_limits, last_cmd_velocity, last_cmd_acceleration);\n  ASSERT_TRUE(violatesRateLimits(kNoLimit, max_translational_acceleration, kNoLimit, kNoLimit,\n                                 max_rotational_acceleration, kNoLimit,\n                                 cartesian_velocity_outside_limits, last_cmd_velocity,\n                                 last_cmd_acceleration, kDeltaT));\n  EXPECT_NE(cartesian_velocity_outside_limits, limited_cartesian_velocity);\n  EXPECT_FALSE(violatesRateLimits(kNoLimit, max_translational_acceleration, kNoLimit, kNoLimit,\n                                  max_rotational_acceleration, kNoLimit, limited_cartesian_velocity,\n                                  last_cmd_velocity, last_cmd_acceleration, kDeltaT));\n}\n\nTEST(RateLimiting, CartesianPose) {\n  std::array<double, 16> last_cmd_pose{\n      {1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0}};\n  std::array<double, 6> last_cmd_velocity{{0.0, 0.0, 0.0, 0.0, 0.0, 0.0}};\n  std::array<double, 6> last_cmd_acceleration{{0.0, 0.0, 0.0, 0.0, 0.0, 0.0}};\n  double max_translational_acceleration{10.0};\n  double max_translational_jerk{100.0};\n  double max_rotational_acceleration{5.0};\n  double max_rotational_jerk{50.0};\n  double eps{1e-2};\n\n  // Desired values are into limits and unchanged after limitRate (rotational and translational\n  // jerk)\n  std::array<double, 16> cartesian_pose_into_limits = integrateOneSample(\n      last_cmd_pose,\n      integrateOneSample<6>(last_cmd_velocity,\n                            generateValuesIntoLimits(last_cmd_acceleration, max_translational_jerk,\n                                                     max_rotational_jerk, eps, kDeltaT),\n                            kDeltaT),\n      kDeltaT);\n  ASSERT_FALSE(violatesRateLimits(\n      kNoLimit, kNoLimit, max_translational_jerk, kNoLimit, kNoLimit, max_rotational_jerk,\n      differentiateOneSample(cartesian_pose_into_limits, last_cmd_pose, kDeltaT), last_cmd_velocity,\n      last_cmd_acceleration, kDeltaT));\n\n  std::array<double, 16> cartesian_pose_limited = limitRate(\n      kNoLimit, kNoLimit, max_translational_jerk, kNoLimit, kNoLimit, max_rotational_jerk,\n      cartesian_pose_into_limits, last_cmd_pose, last_cmd_velocity, last_cmd_acceleration);\n\n  for (size_t i = 0; i < cartesian_pose_into_limits.size(); i++) {\n    EXPECT_NEAR(cartesian_pose_into_limits[i], cartesian_pose_limited[i], 1e-6);\n  }\n\n  // Desired values are into limits and unchanged after limitRate (rotational and translational\n  // acceleration)\n  cartesian_pose_into_limits =\n      integrateOneSample(last_cmd_pose,\n                         generateValuesIntoLimits(last_cmd_velocity, max_translational_acceleration,\n                                                  max_rotational_acceleration, eps, kDeltaT),\n                         kDeltaT);\n  ASSERT_FALSE(violatesRateLimits(\n      kNoLimit, max_translational_acceleration, kNoLimit, kNoLimit, max_rotational_acceleration,\n      kNoLimit, differentiateOneSample(cartesian_pose_into_limits, last_cmd_pose, kDeltaT),\n      last_cmd_velocity, last_cmd_acceleration, kDeltaT));\n\n  cartesian_pose_limited =\n      limitRate(kNoLimit, max_translational_acceleration, kNoLimit, kNoLimit,\n                max_rotational_acceleration, kNoLimit, cartesian_pose_into_limits, last_cmd_pose,\n                last_cmd_velocity, last_cmd_acceleration);\n\n  for (size_t i = 0; i < cartesian_pose_into_limits.size(); i++) {\n    EXPECT_NEAR(cartesian_pose_into_limits[i], cartesian_pose_limited[i], 1e-6);\n  }\n\n  // Desired values are outside limits (rotational and translational jerk violation) and limited\n  // after limitRate\n  std::array<double, 16> cartesian_pose_outside_limits = integrateOneSample(\n      last_cmd_pose,\n      integrateOneSample<6>(\n          last_cmd_velocity,\n          generateValuesOutsideLimits(last_cmd_acceleration, max_translational_jerk,\n                                      max_rotational_jerk, eps, kDeltaT),\n          kDeltaT),\n      kDeltaT);\n  std::array<double, 16> limited_cartesian_pose = limitRate(\n      kNoLimit, kNoLimit, max_translational_jerk, kNoLimit, kNoLimit, max_rotational_jerk,\n      cartesian_pose_outside_limits, last_cmd_pose, last_cmd_velocity, last_cmd_acceleration);\n  ASSERT_TRUE(violatesRateLimits(\n      kNoLimit, kNoLimit, max_translational_jerk, kNoLimit, kNoLimit, max_rotational_jerk,\n      differentiateOneSample(cartesian_pose_outside_limits, last_cmd_pose, kDeltaT),\n      last_cmd_velocity, last_cmd_acceleration, kDeltaT));\n  EXPECT_NE(cartesian_pose_outside_limits, limited_cartesian_pose);\n  EXPECT_FALSE(violatesRateLimits(\n      kNoLimit, kNoLimit, max_translational_jerk, kNoLimit, kNoLimit, max_rotational_jerk,\n      differentiateOneSample(limited_cartesian_pose, last_cmd_pose, kDeltaT), last_cmd_velocity,\n      last_cmd_acceleration, kDeltaT));\n\n  // Desired values are outside limits (rotational and translational acceleration violation) and\n  // limited after limitRate\n  cartesian_pose_outside_limits = integrateOneSample(\n      last_cmd_pose,\n      generateValuesOutsideLimits(last_cmd_velocity, max_translational_acceleration,\n                                  max_rotational_acceleration, eps, kDeltaT),\n      kDeltaT);\n  limited_cartesian_pose =\n      limitRate(kNoLimit, max_translational_acceleration, kNoLimit, kNoLimit,\n                max_rotational_acceleration, kNoLimit, cartesian_pose_outside_limits, last_cmd_pose,\n                last_cmd_velocity, last_cmd_acceleration);\n  ASSERT_TRUE(violatesRateLimits(\n      kNoLimit, max_translational_acceleration, kNoLimit, kNoLimit, max_rotational_acceleration,\n      kNoLimit, differentiateOneSample(cartesian_pose_outside_limits, last_cmd_pose, kDeltaT),\n      last_cmd_velocity, last_cmd_acceleration, kDeltaT));\n  EXPECT_NE(cartesian_pose_outside_limits, limited_cartesian_pose);\n  EXPECT_FALSE(violatesRateLimits(\n      kNoLimit, max_translational_acceleration, kNoLimit, kNoLimit, max_rotational_acceleration,\n      kNoLimit, differentiateOneSample(limited_cartesian_pose, last_cmd_pose, kDeltaT),\n      last_cmd_velocity, last_cmd_acceleration, kDeltaT));\n}\n", "meta": {"hexsha": "81636d8e75317cd1393b116acf7ef82b3bb62051", "size": 28312, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/rate_limiting_tests.cpp", "max_stars_repo_name": "gaming-hacker/libfranka", "max_stars_repo_head_hexsha": "57374e69a01cc24854af4260d9c4e86929054883", "max_stars_repo_licenses": ["Apache-2.0"], "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/rate_limiting_tests.cpp", "max_issues_repo_name": "gaming-hacker/libfranka", "max_issues_repo_head_hexsha": "57374e69a01cc24854af4260d9c4e86929054883", "max_issues_repo_licenses": ["Apache-2.0"], "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/rate_limiting_tests.cpp", "max_forks_repo_name": "gaming-hacker/libfranka", "max_forks_repo_head_hexsha": "57374e69a01cc24854af4260d9c4e86929054883", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 53.825095057, "max_line_length": 100, "alphanum_fraction": 0.6700692286, "num_tokens": 7039, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.46255380131503143}}
{"text": "/*\n * fusion_algebra.hpp\n *\n * Copyright 2009-2012 Karsten Ahnert\n * Copyright 2009-2012 Mario Mulansky\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_ALGEBRA_HPP_\n#define FUSION_ALGEBRA_HPP_\n\n#include <boost/array.hpp>\n\n#include <iostream>\n\n\ntemplate< size_t n >\nstruct fusion_algebra\n{\n    template< typename T , size_t dim >\n    inline static void foreach( boost::array< T , dim > &x_tmp , const boost::array< T , dim > &x ,\n            const boost::array< double , n > &a ,\n            const boost::array< T , dim > k_vector[n] , const double dt )\n    {\n        for( size_t i=0 ; i<dim ; ++i )\n        {\n            x_tmp[i] = x[i];// + a[0]*dt*k_vector[0][i];\n            for( size_t j = 0 ; j<n ; ++j )\n                x_tmp[i] += a[j]*dt*k_vector[j][i];\n        }\n    }\n\n    template< typename T , size_t dim >\n    inline static void foreach( boost::array< T , dim > &x_tmp ,\n                const boost::array< double , n > &a ,\n                const boost::array< T , dim > k_vector[n] , const double dt )\n    {\n        for( size_t i=0 ; i<dim ; ++i )\n        {\n            x_tmp[i] = a[0]*dt*k_vector[0][i];\n            for( size_t j = 1 ; j<n ; ++j )\n                x_tmp[i] += a[j]*dt*k_vector[j][i];\n         }\n    }\n\n};\n\n\n\n\n/** hand-wise implementation for performance improvement for n = 1..4 **/\n\n/* !!!!!!!   Actually, this is factor 3 slower with intel compiler, so we don'y use it !!!!!\n * Update: It increases performance on msvc 9.0 by about 30%, so it is activated for MSVC\n */\n\n//#ifdef BOOST_MSVC\n\ntemplate<>\nstruct fusion_algebra< 1 >\n{\n    template< typename T , size_t dim >\n    inline static void foreach( boost::array< T , dim > &x_tmp , const boost::array< T , dim > &x ,\n            const boost::array< double , 1 > &a ,\n            const boost::array< T , dim > *k_vector , const double dt )\n    {\n        for( size_t i=0 ; i<dim ; ++i )\n        {\n            x_tmp[i] = x[i]\n                + a[0]*dt*k_vector[0][i];\n        }\n    }\n\n};\n\n\ntemplate<>\nstruct fusion_algebra< 2 >\n{\n\n    template< typename T , size_t dim >\n    inline static void foreach( boost::array< T , dim > &x_tmp , const boost::array< T , dim > &x ,\n            const boost::array< double , 2 > &a ,\n            const boost::array< T , dim > *k_vector , const double dt )\n    {\n        for( size_t i=0 ; i<dim ; ++i )\n        {\n            x_tmp[i] = x[i]\n             + a[0]*dt*k_vector[0][i]\n             + a[1]*dt*k_vector[1][i];\n        }\n    }\n\n};\n\n\ntemplate<>\nstruct fusion_algebra< 3 >\n{\n\n    template< typename T , size_t dim >\n    inline static void foreach( boost::array< T , dim > &x_tmp , const boost::array< T , dim > &x ,\n            const boost::array< double , 3 > &a ,\n            const boost::array< T , dim > *k_vector , const double dt )\n    {\n        for( size_t i=0 ; i<dim ; ++i )\n        {\n            x_tmp[i] = x[i]\n             + a[0]*dt*k_vector[0][i]\n             + a[1]*dt*k_vector[1][i]\n             + a[2]*dt*k_vector[2][i];\n        }\n    }\n\n};\n\ntemplate<>\nstruct fusion_algebra< 4 >\n{\n\n    template< typename T , size_t dim >\n    inline static void foreach( boost::array< T , dim > &x_tmp , const boost::array< T , dim > &x ,\n            const boost::array< double , 4 > &a ,\n            const boost::array< T , dim > *k_vector , const double dt )\n    {\n        for( size_t i=0 ; i<dim ; ++i )\n        {\n            x_tmp[i] = x[i]\n             + a[0]*dt*k_vector[0][i]\n             + a[1]*dt*k_vector[1][i]\n             + a[2]*dt*k_vector[2][i]\n             + a[3]*dt*k_vector[3][i];\n        }\n    }\n\n};\n\ntemplate<>\nstruct fusion_algebra< 5 >\n{\n\n    template< typename T , size_t dim >\n    inline static void foreach( boost::array< T , dim > &x_tmp , const boost::array< T , dim > &x ,\n            const boost::array< double , 5 > &a ,\n            const boost::array< T , dim > *k_vector , const double dt )\n    {\n        for( size_t i=0 ; i<dim ; ++i )\n        {\n            x_tmp[i] = x[i]\n             + a[0]*dt*k_vector[0][i]\n             + a[1]*dt*k_vector[1][i]\n             + a[2]*dt*k_vector[2][i]\n             + a[3]*dt*k_vector[3][i]\n             + a[4]*dt*k_vector[4][i];\n        }\n    }\n\n};\n\ntemplate<>\nstruct fusion_algebra< 6 >\n{\n\n    template< typename T , size_t dim >\n    inline static void foreach( boost::array< T , dim > &x_tmp , const boost::array< T , dim > &x ,\n            const boost::array< double , 6 > &a ,\n            const boost::array< T , dim > *k_vector , const double dt )\n    {\n        for( size_t i=0 ; i<dim ; ++i )\n        {\n            x_tmp[i] = x[i]\n             + a[0]*dt*k_vector[0][i]\n             + a[1]*dt*k_vector[1][i]\n             + a[2]*dt*k_vector[2][i]\n             + a[3]*dt*k_vector[3][i]\n             + a[4]*dt*k_vector[4][i]\n             + a[5]*dt*k_vector[5][i];\n        }\n    }\n\n    template< typename T , size_t dim >\n    inline static void foreach(boost::array<T , dim> &x_tmp ,\n            const boost::array<double , 6> &a ,\n            const boost::array<T , dim> *k_vector , const double dt)\n    {\n        for (size_t i = 0 ; i < dim ; ++i)\n        {\n            x_tmp[i] = a[0] * dt * k_vector[0][i] + a[1] * dt * k_vector[1][i]\n                    + a[2] * dt * k_vector[2][i] + a[3] * dt * k_vector[3][i]\n                    + a[4] * dt * k_vector[4][i] + a[5] * dt * k_vector[5][i];\n        }\n    }\n\n};\n\n//#endif /* BOOST_MSVC */\n\n#endif /* FUSION_ALGEBRA_HPP_ */\n", "meta": {"hexsha": "5d6e85e1d7f189d09800f74bf19f36dfb27b9285", "size": 5503, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Modules/ego_planner/ego-planner-swarm/src/uav_simulator/so3_quadrotor_simulator/include/ode/libs/numeric/odeint/performance/fusion_algebra.hpp", "max_stars_repo_name": "473867143/Prometheus", "max_stars_repo_head_hexsha": "df1e1b0d861490223ac8b94d8cc4796537172292", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1217.0, "max_stars_repo_stars_event_min_datetime": "2020-07-02T13:15:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T06:17:44.000Z", "max_issues_repo_path": "Modules/ego_planner/ego-planner-swarm/src/uav_simulator/so3_quadrotor_simulator/include/ode/libs/numeric/odeint/performance/fusion_algebra.hpp", "max_issues_repo_name": "473867143/Prometheus", "max_issues_repo_head_hexsha": "df1e1b0d861490223ac8b94d8cc4796537172292", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 167.0, "max_issues_repo_issues_event_min_datetime": "2020-07-12T15:35:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T11:57:40.000Z", "max_forks_repo_path": "Modules/ego_planner/ego-planner-swarm/src/uav_simulator/so3_quadrotor_simulator/include/ode/libs/numeric/odeint/performance/fusion_algebra.hpp", "max_forks_repo_name": "473867143/Prometheus", "max_forks_repo_head_hexsha": "df1e1b0d861490223ac8b94d8cc4796537172292", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 270.0, "max_forks_repo_forks_event_min_datetime": "2020-07-02T13:28:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T05:43:08.000Z", "avg_line_length": 27.1083743842, "max_line_length": 99, "alphanum_fraction": 0.495547883, "num_tokens": 1666, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.46255380131503143}}
{"text": "// test file for quaternion.hpp\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\r\n#include <boost/math/quaternion.hpp>\r\n\r\ntypedef boost::math::quaternion<double> qt;\r\ntypedef std::complex<double> ct;\r\n\r\n#ifndef BOOST_NO_CXX14_CONSTEXPR\r\n\r\nconstexpr qt full_constexpr_test(qt a, qt b, double d, ct c)\r\n{\r\n   a.swap(b);\r\n   qt result(a), t;\r\n   result += d;\r\n   result += c;\r\n   result += b;\r\n   t = result;\r\n   t = d;\r\n   t = c;\r\n   result -= d;\r\n   result -= c;\r\n   result -= a;\r\n   result *= d;\r\n   result *= c;\r\n   result *= a;\r\n   result /= d;\r\n   result /= c;\r\n   result /= b;\r\n\r\n   result += a + d;\r\n   result += d + a;\r\n   result += a + c;\r\n   result += c + a;\r\n   result += a + b;\r\n\r\n   result += a - d;\r\n   result += d - a;\r\n   result += a - c;\r\n   result += c - a;\r\n   result += a - b;\r\n\r\n   result += a * d;\r\n   result += d * a;\r\n   result += a * c;\r\n   result += c * a;\r\n   result += a * b;\r\n\r\n   result += a / d;\r\n   result += d / a;\r\n   result += a / c;\r\n   result += c / a;\r\n   result += a / b;\r\n\r\n   result += norm(a);\r\n   result += conj(a);\r\n\r\n   return result;\r\n}\r\n\r\n#endif\r\n\r\nint main()\r\n{\r\n#ifndef BOOST_NO_CXX11_CONSTEXPR\r\n\r\n   constexpr qt q1;\r\n   constexpr qt q2(2.0);\r\n   constexpr qt q3(2.0, 3.0);\r\n   constexpr qt q4(2.0, 3.9, 3.0);\r\n   constexpr qt q5(2.0, 3.9, 3.0, 5.);\r\n\r\n   constexpr ct c1(2., 3.);\r\n   constexpr qt q6(c1);\r\n   constexpr qt q7(c1, c1);\r\n   constexpr qt q8(q1);\r\n\r\n   constexpr double d1 = q5.real();\r\n   constexpr qt q9 = q1.unreal();\r\n   constexpr double d2 = q1.R_component_1();\r\n   constexpr double d3 = q1.R_component_2();\r\n   constexpr double d4 = q1.R_component_3();\r\n   constexpr double d5 = q1.R_component_4();\r\n   constexpr ct c2 = q1.C_component_1();\r\n   constexpr ct c3 = q1.C_component_1();\r\n\r\n   constexpr qt q10 = q1 + d1;\r\n   constexpr qt q11 = d1 + q1;\r\n   constexpr qt q12 = c2 + q1;\r\n   constexpr qt q13 = q1 + c2;\r\n   constexpr qt q14 = q1 + q2;\r\n\r\n   constexpr qt q15 = q1 - d1;\r\n   constexpr qt q16 = d1 - q1;\r\n   constexpr qt q17 = c2 - q1;\r\n   constexpr qt q18 = q1 - c2;\r\n   constexpr qt q19 = q1 - q2;\r\n\r\n   constexpr qt q20 = q1 * d1;\r\n   constexpr qt q21 = d1 * q1;\r\n   constexpr qt q22 = q5 / d1;\r\n\r\n   constexpr double d6 = real(q5);\r\n   constexpr qt q23 = unreal(q1);\r\n\r\n   constexpr bool b1 = q1 == d1;\r\n   constexpr bool b2 = d1 == q1;\r\n   constexpr bool b3 = q1 != d1;\r\n   constexpr bool b4 = d1 != q1;\r\n\r\n   constexpr bool b5 = q1 == c2;\r\n   constexpr bool b6 = c2 == q1;\r\n   constexpr bool b7 = q1 != c2;\r\n   constexpr bool b8 = c2 != q1;\r\n   constexpr bool b9 = q2 == q1;\r\n   constexpr bool b10 = q1 != q2;\r\n\r\n#endif\r\n\r\n#ifndef BOOST_NO_CXX14_CONSTEXPR\r\n\r\n   constexpr qt q24 = full_constexpr_test(q5, q5 + 1, 3.2, q5.C_component_1());\r\n\r\n#endif\r\n\r\n   return 0;\r\n}\r\n", "meta": {"hexsha": "404932f8a907ed1a75bf25607d8b29656ec4fc86", "size": 2906, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/math/test/quaternion_constexpr_test.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": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/math/test/quaternion_constexpr_test.cpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/math/test/quaternion_constexpr_test.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-03-08T11:06:22.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-08T11:06:22.000Z", "avg_line_length": 21.8496240602, "max_line_length": 80, "alphanum_fraction": 0.5588437715, "num_tokens": 941, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125626441471, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.46255379447793005}}
{"text": "// Copyright Michael Drexl 2005, 2006.\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt or copy at\n// http://boost.org/LICENSE_1_0.txt)\n\n#include <boost/config.hpp>\n\n#ifdef BOOST_MSVC\n#pragma warning(disable : 4267)\n#endif\n\n#include <boost/graph/adjacency_list.hpp>\n//#include <boost/graph/dijkstra_shortest_paths.hpp>\n\n#include <boost/graph/r_c_shortest_paths.hpp>\n#include <iostream>\n#include <boost/core/lightweight_test.hpp>\n\nusing namespace boost;\n\nstruct SPPRC_Example_Graph_Vert_Prop\n{\n    SPPRC_Example_Graph_Vert_Prop(int n = 0, int e = 0, int l = 0)\n    : num(n), eat(e), lat(l)\n    {\n    }\n    int num;\n    // earliest arrival time\n    int eat;\n    // latest arrival time\n    int lat;\n};\n\nstruct SPPRC_Example_Graph_Arc_Prop\n{\n    SPPRC_Example_Graph_Arc_Prop(int n = 0, int c = 0, int t = 0)\n    : num(n), cost(c), time(t)\n    {\n    }\n    int num;\n    // traversal cost\n    int cost;\n    // traversal time\n    int time;\n};\n\ntypedef adjacency_list< vecS, vecS, directedS, SPPRC_Example_Graph_Vert_Prop,\n    SPPRC_Example_Graph_Arc_Prop >\n    SPPRC_Example_Graph;\n\n// data structures for spp without resource constraints:\n// ResourceContainer model\nstruct spp_no_rc_res_cont\n{\n    spp_no_rc_res_cont(int c = 0) : cost(c) {};\n    spp_no_rc_res_cont& operator=(const spp_no_rc_res_cont& other)\n    {\n        if (this == &other)\n            return *this;\n        this->~spp_no_rc_res_cont();\n        new (this) spp_no_rc_res_cont(other);\n        return *this;\n    }\n    int cost;\n};\n\nbool operator==(\n    const spp_no_rc_res_cont& res_cont_1, const spp_no_rc_res_cont& res_cont_2)\n{\n    return (res_cont_1.cost == res_cont_2.cost);\n}\n\nbool operator<(\n    const spp_no_rc_res_cont& res_cont_1, const spp_no_rc_res_cont& res_cont_2)\n{\n    return (res_cont_1.cost < res_cont_2.cost);\n}\n\n// ResourceExtensionFunction model\nclass ref_no_res_cont\n{\npublic:\n    inline bool operator()(const SPPRC_Example_Graph& g,\n        spp_no_rc_res_cont& new_cont, const spp_no_rc_res_cont& old_cont,\n        graph_traits< SPPRC_Example_Graph >::edge_descriptor ed) const\n    {\n        new_cont.cost = old_cont.cost + g[ed].cost;\n        return true;\n    }\n};\n\n// DominanceFunction model\nclass dominance_no_res_cont\n{\npublic:\n    inline bool operator()(const spp_no_rc_res_cont& res_cont_1,\n        const spp_no_rc_res_cont& res_cont_2) const\n    {\n        // must be \"<=\" here!!!\n        // must NOT be \"<\"!!!\n        return res_cont_1.cost <= res_cont_2.cost;\n        // this is not a contradiction to the documentation\n        // the documentation says:\n        // \"A label $l_1$ dominates a label $l_2$ if and only if both are\n        // resident at the same vertex, and if, for each resource, the resource\n        // consumption of $l_1$ is less than or equal to the resource\n        // consumption of $l_2$, and if there is at least one resource where\n        // $l_1$ has a lower resource consumption than $l_2$.\" one can think of\n        // a new label with a resource consumption equal to that of an old label\n        // as being dominated by that old label, because the new one will have a\n        // higher number and is created at a later point in time, so one can\n        // implicitly use the number or the creation time as a resource for\n        // tie-breaking\n    }\n};\n// end data structures for spp without resource constraints:\n\n// data structures for shortest path problem with time windows (spptw)\n// ResourceContainer model\nstruct spp_spptw_res_cont\n{\n    spp_spptw_res_cont(int c = 0, int t = 0) : cost(c), time(t) {}\n    spp_spptw_res_cont& operator=(const spp_spptw_res_cont& other)\n    {\n        if (this == &other)\n            return *this;\n        this->~spp_spptw_res_cont();\n        new (this) spp_spptw_res_cont(other);\n        return *this;\n    }\n    int cost;\n    int time;\n};\n\nbool operator==(\n    const spp_spptw_res_cont& res_cont_1, const spp_spptw_res_cont& res_cont_2)\n{\n    return (res_cont_1.cost == res_cont_2.cost\n        && res_cont_1.time == res_cont_2.time);\n}\n\nbool operator<(\n    const spp_spptw_res_cont& res_cont_1, const spp_spptw_res_cont& res_cont_2)\n{\n    if (res_cont_1.cost > res_cont_2.cost)\n        return false;\n    if (res_cont_1.cost == res_cont_2.cost)\n        return res_cont_1.time < res_cont_2.time;\n    return true;\n}\n\n// ResourceExtensionFunction model\nclass ref_spptw\n{\npublic:\n    inline bool operator()(const SPPRC_Example_Graph& g,\n        spp_spptw_res_cont& new_cont, const spp_spptw_res_cont& old_cont,\n        graph_traits< SPPRC_Example_Graph >::edge_descriptor ed) const\n    {\n        const SPPRC_Example_Graph_Arc_Prop& arc_prop = get(edge_bundle, g)[ed];\n        const SPPRC_Example_Graph_Vert_Prop& vert_prop\n            = get(vertex_bundle, g)[target(ed, g)];\n        new_cont.cost = old_cont.cost + arc_prop.cost;\n        int& i_time = new_cont.time;\n        i_time = old_cont.time + arc_prop.time;\n        i_time < vert_prop.eat ? i_time = vert_prop.eat : 0;\n        return i_time <= vert_prop.lat ? true : false;\n    }\n};\n\n// DominanceFunction model\nclass dominance_spptw\n{\npublic:\n    inline bool operator()(const spp_spptw_res_cont& res_cont_1,\n        const spp_spptw_res_cont& res_cont_2) const\n    {\n        // must be \"<=\" here!!!\n        // must NOT be \"<\"!!!\n        return res_cont_1.cost <= res_cont_2.cost\n            && res_cont_1.time <= res_cont_2.time;\n        // this is not a contradiction to the documentation\n        // the documentation says:\n        // \"A label $l_1$ dominates a label $l_2$ if and only if both are\n        // resident at the same vertex, and if, for each resource, the resource\n        // consumption of $l_1$ is less than or equal to the resource\n        // consumption of $l_2$, and if there is at least one resource where\n        // $l_1$ has a lower resource consumption than $l_2$.\" one can think of\n        // a new label with a resource consumption equal to that of an old label\n        // as being dominated by that old label, because the new one will have a\n        // higher number and is created at a later point in time, so one can\n        // implicitly use the number or the creation time as a resource for\n        // tie-breaking\n    }\n};\n// end data structures for shortest path problem with time windows (spptw)\n\nstruct spp_spptw_marked_res_cont\n{\n    spp_spptw_marked_res_cont(\n        SPPRC_Example_Graph::vertex_descriptor v, int c = 0, int t = 0)\n    : cost(c), time(t), marked()\n    {\n        marked.insert(v);\n    }\n    spp_spptw_marked_res_cont& operator=(const spp_spptw_marked_res_cont& other)\n    {\n        if (this == &other)\n            return *this;\n        this->~spp_spptw_marked_res_cont();\n        new (this) spp_spptw_marked_res_cont(other);\n        return *this;\n    }\n    int cost;\n    int time;\n    std::set< SPPRC_Example_Graph::vertex_descriptor > marked;\n};\n\nbool operator==(const spp_spptw_marked_res_cont& res_cont_1,\n    const spp_spptw_marked_res_cont& res_cont_2)\n{\n    return res_cont_1.cost == res_cont_2.cost\n        && res_cont_1.time == res_cont_2.time\n        && res_cont_1.marked == res_cont_2.marked;\n}\n\nbool operator<(const spp_spptw_marked_res_cont& res_cont_1,\n    const spp_spptw_marked_res_cont& res_cont_2)\n{\n    if (res_cont_1.cost > res_cont_2.cost || res_cont_1.time > res_cont_2.time)\n    {\n        return false;\n    }\n\n    if (!std::includes(res_cont_2.marked.begin(), res_cont_2.marked.end(),\n            res_cont_1.marked.begin(), res_cont_1.marked.end()))\n    {\n        return false;\n    }\n\n    if (res_cont_1.cost == res_cont_2.cost)\n    {\n        return res_cont_1.time < res_cont_2.time;\n    }\n    return true;\n}\n\nclass ref_spptw_marked\n{\npublic:\n    inline bool operator()(const SPPRC_Example_Graph& g,\n        spp_spptw_marked_res_cont& new_cont,\n        const spp_spptw_marked_res_cont& old_cont,\n        graph_traits< SPPRC_Example_Graph >::edge_descriptor ed) const\n    {\n        const graph_traits< SPPRC_Example_Graph >::vertex_descriptor dest\n            = target(ed, g);\n\n        if (old_cont.marked.find(dest) != old_cont.marked.end())\n        {\n            return false;\n        }\n\n        const SPPRC_Example_Graph_Arc_Prop& arc_prop = get(edge_bundle, g)[ed];\n        const SPPRC_Example_Graph_Vert_Prop& vert_prop\n            = get(vertex_bundle, g)[dest];\n        new_cont.cost = old_cont.cost + arc_prop.cost;\n        new_cont.marked = old_cont.marked;\n        new_cont.marked.insert(dest);\n        int& i_time = new_cont.time;\n        i_time = old_cont.time + arc_prop.time;\n        i_time < vert_prop.eat ? i_time = vert_prop.eat : 0;\n        return i_time <= vert_prop.lat;\n    }\n};\n\nclass dominance_spptw_marked\n{\npublic:\n    inline bool operator()(const spp_spptw_marked_res_cont& res_cont_1,\n        const spp_spptw_marked_res_cont& res_cont_2) const\n    {\n        return res_cont_1.time <= res_cont_2.time\n            && res_cont_1.cost <= res_cont_2.cost\n            && std::includes(res_cont_1.marked.begin(), res_cont_1.marked.end(),\n                res_cont_2.marked.begin(), res_cont_2.marked.end());\n    }\n};\n\nint main(int, char*[])\n{\n    SPPRC_Example_Graph g;\n    add_vertex(SPPRC_Example_Graph_Vert_Prop(0, 0, 1000000000), g);\n    add_vertex(SPPRC_Example_Graph_Vert_Prop(1, 56, 142), g);\n    add_vertex(SPPRC_Example_Graph_Vert_Prop(2, 0, 1000000000), g);\n    add_vertex(SPPRC_Example_Graph_Vert_Prop(3, 89, 178), g);\n    add_vertex(SPPRC_Example_Graph_Vert_Prop(4, 0, 1000000000), g);\n    add_vertex(SPPRC_Example_Graph_Vert_Prop(5, 49, 76), g);\n    add_vertex(SPPRC_Example_Graph_Vert_Prop(6, 0, 1000000000), g);\n    add_vertex(SPPRC_Example_Graph_Vert_Prop(7, 98, 160), g);\n    add_vertex(SPPRC_Example_Graph_Vert_Prop(8, 0, 1000000000), g);\n    add_vertex(SPPRC_Example_Graph_Vert_Prop(9, 90, 158), g);\n    add_edge(0, 7, SPPRC_Example_Graph_Arc_Prop(6, 33, 2), g);\n    add_edge(0, 6, SPPRC_Example_Graph_Arc_Prop(5, 31, 6), g);\n    add_edge(0, 4, SPPRC_Example_Graph_Arc_Prop(3, 14, 4), g);\n    add_edge(0, 1, SPPRC_Example_Graph_Arc_Prop(0, 43, 8), g);\n    add_edge(0, 4, SPPRC_Example_Graph_Arc_Prop(4, 28, 10), g);\n    add_edge(0, 3, SPPRC_Example_Graph_Arc_Prop(1, 31, 10), g);\n    add_edge(0, 3, SPPRC_Example_Graph_Arc_Prop(2, 1, 7), g);\n    add_edge(0, 9, SPPRC_Example_Graph_Arc_Prop(7, 25, 9), g);\n    add_edge(1, 0, SPPRC_Example_Graph_Arc_Prop(8, 37, 4), g);\n    add_edge(1, 6, SPPRC_Example_Graph_Arc_Prop(9, 7, 3), g);\n    add_edge(2, 6, SPPRC_Example_Graph_Arc_Prop(12, 6, 7), g);\n    add_edge(2, 3, SPPRC_Example_Graph_Arc_Prop(10, 13, 7), g);\n    add_edge(2, 3, SPPRC_Example_Graph_Arc_Prop(11, 49, 9), g);\n    add_edge(2, 8, SPPRC_Example_Graph_Arc_Prop(13, 47, 5), g);\n    add_edge(3, 4, SPPRC_Example_Graph_Arc_Prop(17, 5, 10), g);\n    add_edge(3, 1, SPPRC_Example_Graph_Arc_Prop(15, 47, 1), g);\n    add_edge(3, 2, SPPRC_Example_Graph_Arc_Prop(16, 26, 9), g);\n    add_edge(3, 9, SPPRC_Example_Graph_Arc_Prop(21, 24, 10), g);\n    add_edge(3, 7, SPPRC_Example_Graph_Arc_Prop(20, 50, 10), g);\n    add_edge(3, 0, SPPRC_Example_Graph_Arc_Prop(14, 41, 4), g);\n    add_edge(3, 6, SPPRC_Example_Graph_Arc_Prop(19, 6, 1), g);\n    add_edge(3, 4, SPPRC_Example_Graph_Arc_Prop(18, 8, 1), g);\n    add_edge(4, 5, SPPRC_Example_Graph_Arc_Prop(26, 38, 4), g);\n    add_edge(4, 9, SPPRC_Example_Graph_Arc_Prop(27, 32, 10), g);\n    add_edge(4, 3, SPPRC_Example_Graph_Arc_Prop(24, 40, 3), g);\n    add_edge(4, 0, SPPRC_Example_Graph_Arc_Prop(22, 7, 3), g);\n    add_edge(4, 3, SPPRC_Example_Graph_Arc_Prop(25, 28, 9), g);\n    add_edge(4, 2, SPPRC_Example_Graph_Arc_Prop(23, 39, 6), g);\n    add_edge(5, 8, SPPRC_Example_Graph_Arc_Prop(32, 6, 2), g);\n    add_edge(5, 2, SPPRC_Example_Graph_Arc_Prop(30, 26, 10), g);\n    add_edge(5, 0, SPPRC_Example_Graph_Arc_Prop(28, 38, 9), g);\n    add_edge(5, 2, SPPRC_Example_Graph_Arc_Prop(31, 48, 10), g);\n    add_edge(5, 9, SPPRC_Example_Graph_Arc_Prop(33, 49, 2), g);\n    add_edge(5, 1, SPPRC_Example_Graph_Arc_Prop(29, 22, 7), g);\n    add_edge(6, 1, SPPRC_Example_Graph_Arc_Prop(34, 15, 7), g);\n    add_edge(6, 7, SPPRC_Example_Graph_Arc_Prop(35, 20, 3), g);\n    add_edge(7, 9, SPPRC_Example_Graph_Arc_Prop(40, 1, 3), g);\n    add_edge(7, 0, SPPRC_Example_Graph_Arc_Prop(36, 23, 5), g);\n    add_edge(7, 6, SPPRC_Example_Graph_Arc_Prop(38, 36, 2), g);\n    add_edge(7, 6, SPPRC_Example_Graph_Arc_Prop(39, 18, 10), g);\n    add_edge(7, 2, SPPRC_Example_Graph_Arc_Prop(37, 2, 1), g);\n    add_edge(8, 5, SPPRC_Example_Graph_Arc_Prop(46, 36, 5), g);\n    add_edge(8, 1, SPPRC_Example_Graph_Arc_Prop(42, 13, 10), g);\n    add_edge(8, 0, SPPRC_Example_Graph_Arc_Prop(41, 40, 5), g);\n    add_edge(8, 1, SPPRC_Example_Graph_Arc_Prop(43, 32, 8), g);\n    add_edge(8, 6, SPPRC_Example_Graph_Arc_Prop(47, 25, 1), g);\n    add_edge(8, 2, SPPRC_Example_Graph_Arc_Prop(44, 44, 3), g);\n    add_edge(8, 3, SPPRC_Example_Graph_Arc_Prop(45, 11, 9), g);\n    add_edge(9, 0, SPPRC_Example_Graph_Arc_Prop(48, 41, 5), g);\n    add_edge(9, 1, SPPRC_Example_Graph_Arc_Prop(49, 44, 7), g);\n\n    // spp without resource constraints\n\n    std::vector<\n        std::vector< graph_traits< SPPRC_Example_Graph >::edge_descriptor > >\n        opt_solutions;\n    std::vector< spp_no_rc_res_cont > pareto_opt_rcs_no_rc;\n    std::vector< int > i_vec_opt_solutions_spp_no_rc;\n    // std::cout << \"r_c_shortest_paths:\" << std::endl;\n    for (int s = 0; s < 10; ++s)\n    {\n        for (int t = 0; t < 10; ++t)\n        {\n            r_c_shortest_paths(g, get(&SPPRC_Example_Graph_Vert_Prop::num, g),\n                get(&SPPRC_Example_Graph_Arc_Prop::num, g), s, t, opt_solutions,\n                pareto_opt_rcs_no_rc, spp_no_rc_res_cont(0), ref_no_res_cont(),\n                dominance_no_res_cont(),\n                std::allocator< r_c_shortest_paths_label< SPPRC_Example_Graph,\n                    spp_no_rc_res_cont > >(),\n                default_r_c_shortest_paths_visitor());\n            i_vec_opt_solutions_spp_no_rc.push_back(\n                pareto_opt_rcs_no_rc[0].cost);\n            // std::cout << \"From \" << s << \" to \" << t << \": \";\n            // std::cout << pareto_opt_rcs_no_rc[0].cost << std::endl;\n        }\n    }\n\n    // std::vector<graph_traits<SPPRC_Example_Graph>::vertex_descriptor>\n    //  p( num_vertices( g ) );\n    // std::vector<int> d( num_vertices( g ) );\n    // std::vector<int> i_vec_dijkstra_distances;\n    // std::cout << \"Dijkstra:\" << std::endl;\n    // for( int s = 0; s < 10; ++s )\n    //{\n    //  dijkstra_shortest_paths( g,\n    //                           s,\n    //                           &p[0],\n    //                           &d[0],\n    //                           get( &SPPRC_Example_Graph_Arc_Prop::cost, g ),\n    //                           get( &SPPRC_Example_Graph_Vert_Prop::num, g ),\n    //                           std::less<int>(),\n    //                           closed_plus<int>(),\n    //                           (std::numeric_limits<int>::max)(),\n    //                           0,\n    //                           default_dijkstra_visitor() );\n    //  for( int t = 0; t < 10; ++t )\n    //  {\n    //    i_vec_dijkstra_distances.push_back( d[t] );\n    //    std::cout << \"From \" << s << \" to \" << t << \": \" << d[t] << std::endl;\n    //  }\n    //}\n\n    std::vector< int > i_vec_correct_solutions;\n    i_vec_correct_solutions.push_back(0);\n    i_vec_correct_solutions.push_back(22);\n    i_vec_correct_solutions.push_back(27);\n    i_vec_correct_solutions.push_back(1);\n    i_vec_correct_solutions.push_back(6);\n    i_vec_correct_solutions.push_back(44);\n    i_vec_correct_solutions.push_back(7);\n    i_vec_correct_solutions.push_back(27);\n    i_vec_correct_solutions.push_back(50);\n    i_vec_correct_solutions.push_back(25);\n    i_vec_correct_solutions.push_back(37);\n    i_vec_correct_solutions.push_back(0);\n    i_vec_correct_solutions.push_back(29);\n    i_vec_correct_solutions.push_back(38);\n    i_vec_correct_solutions.push_back(43);\n    i_vec_correct_solutions.push_back(81);\n    i_vec_correct_solutions.push_back(7);\n    i_vec_correct_solutions.push_back(27);\n    i_vec_correct_solutions.push_back(76);\n    i_vec_correct_solutions.push_back(28);\n    i_vec_correct_solutions.push_back(25);\n    i_vec_correct_solutions.push_back(21);\n    i_vec_correct_solutions.push_back(0);\n    i_vec_correct_solutions.push_back(13);\n    i_vec_correct_solutions.push_back(18);\n    i_vec_correct_solutions.push_back(56);\n    i_vec_correct_solutions.push_back(6);\n    i_vec_correct_solutions.push_back(26);\n    i_vec_correct_solutions.push_back(47);\n    i_vec_correct_solutions.push_back(27);\n    i_vec_correct_solutions.push_back(12);\n    i_vec_correct_solutions.push_back(21);\n    i_vec_correct_solutions.push_back(26);\n    i_vec_correct_solutions.push_back(0);\n    i_vec_correct_solutions.push_back(5);\n    i_vec_correct_solutions.push_back(43);\n    i_vec_correct_solutions.push_back(6);\n    i_vec_correct_solutions.push_back(26);\n    i_vec_correct_solutions.push_back(49);\n    i_vec_correct_solutions.push_back(24);\n    i_vec_correct_solutions.push_back(7);\n    i_vec_correct_solutions.push_back(29);\n    i_vec_correct_solutions.push_back(34);\n    i_vec_correct_solutions.push_back(8);\n    i_vec_correct_solutions.push_back(0);\n    i_vec_correct_solutions.push_back(38);\n    i_vec_correct_solutions.push_back(14);\n    i_vec_correct_solutions.push_back(34);\n    i_vec_correct_solutions.push_back(44);\n    i_vec_correct_solutions.push_back(32);\n    i_vec_correct_solutions.push_back(29);\n    i_vec_correct_solutions.push_back(19);\n    i_vec_correct_solutions.push_back(26);\n    i_vec_correct_solutions.push_back(17);\n    i_vec_correct_solutions.push_back(22);\n    i_vec_correct_solutions.push_back(0);\n    i_vec_correct_solutions.push_back(23);\n    i_vec_correct_solutions.push_back(43);\n    i_vec_correct_solutions.push_back(6);\n    i_vec_correct_solutions.push_back(41);\n    i_vec_correct_solutions.push_back(43);\n    i_vec_correct_solutions.push_back(15);\n    i_vec_correct_solutions.push_back(22);\n    i_vec_correct_solutions.push_back(35);\n    i_vec_correct_solutions.push_back(40);\n    i_vec_correct_solutions.push_back(78);\n    i_vec_correct_solutions.push_back(0);\n    i_vec_correct_solutions.push_back(20);\n    i_vec_correct_solutions.push_back(69);\n    i_vec_correct_solutions.push_back(21);\n    i_vec_correct_solutions.push_back(23);\n    i_vec_correct_solutions.push_back(23);\n    i_vec_correct_solutions.push_back(2);\n    i_vec_correct_solutions.push_back(15);\n    i_vec_correct_solutions.push_back(20);\n    i_vec_correct_solutions.push_back(58);\n    i_vec_correct_solutions.push_back(8);\n    i_vec_correct_solutions.push_back(0);\n    i_vec_correct_solutions.push_back(49);\n    i_vec_correct_solutions.push_back(1);\n    i_vec_correct_solutions.push_back(23);\n    i_vec_correct_solutions.push_back(13);\n    i_vec_correct_solutions.push_back(37);\n    i_vec_correct_solutions.push_back(11);\n    i_vec_correct_solutions.push_back(16);\n    i_vec_correct_solutions.push_back(36);\n    i_vec_correct_solutions.push_back(17);\n    i_vec_correct_solutions.push_back(37);\n    i_vec_correct_solutions.push_back(0);\n    i_vec_correct_solutions.push_back(35);\n    i_vec_correct_solutions.push_back(41);\n    i_vec_correct_solutions.push_back(44);\n    i_vec_correct_solutions.push_back(68);\n    i_vec_correct_solutions.push_back(42);\n    i_vec_correct_solutions.push_back(47);\n    i_vec_correct_solutions.push_back(85);\n    i_vec_correct_solutions.push_back(48);\n    i_vec_correct_solutions.push_back(68);\n    i_vec_correct_solutions.push_back(91);\n    i_vec_correct_solutions.push_back(0);\n    BOOST_TEST(\n        i_vec_opt_solutions_spp_no_rc.size() == i_vec_correct_solutions.size());\n    for (int i = 0; i < static_cast< int >(i_vec_correct_solutions.size()); ++i)\n        BOOST_TEST(\n            i_vec_opt_solutions_spp_no_rc[i] == i_vec_correct_solutions[i]);\n\n    // spptw\n    std::vector<\n        std::vector< graph_traits< SPPRC_Example_Graph >::edge_descriptor > >\n        opt_solutions_spptw;\n    std::vector< spp_spptw_res_cont > pareto_opt_rcs_spptw;\n    std::vector< std::vector< std::vector< std::vector<\n        graph_traits< SPPRC_Example_Graph >::edge_descriptor > > > >\n        vec_vec_vec_vec_opt_solutions_spptw(10);\n\n    for (int s = 0; s < 10; ++s)\n    {\n        for (int t = 0; t < 10; ++t)\n        {\n            r_c_shortest_paths(g, get(&SPPRC_Example_Graph_Vert_Prop::num, g),\n                get(&SPPRC_Example_Graph_Arc_Prop::num, g), s, t,\n                opt_solutions_spptw, pareto_opt_rcs_spptw,\n                // be careful, do not simply take 0 as initial value for time\n                spp_spptw_res_cont(0, g[s].eat), ref_spptw(), dominance_spptw(),\n                std::allocator< r_c_shortest_paths_label< SPPRC_Example_Graph,\n                    spp_spptw_res_cont > >(),\n                default_r_c_shortest_paths_visitor());\n            vec_vec_vec_vec_opt_solutions_spptw[s].push_back(\n                opt_solutions_spptw);\n            if (opt_solutions_spptw.size())\n            {\n                bool b_is_a_path_at_all = false;\n                bool b_feasible = false;\n                bool b_correctly_extended = false;\n                spp_spptw_res_cont actual_final_resource_levels(0, 0);\n                graph_traits< SPPRC_Example_Graph >::edge_descriptor\n                    ed_last_extended_arc;\n                check_r_c_path(g, opt_solutions_spptw[0],\n                    spp_spptw_res_cont(0, g[s].eat), true,\n                    pareto_opt_rcs_spptw[0], actual_final_resource_levels,\n                    ref_spptw(), b_is_a_path_at_all, b_feasible,\n                    b_correctly_extended, ed_last_extended_arc);\n                BOOST_TEST(\n                    b_is_a_path_at_all && b_feasible && b_correctly_extended);\n                b_is_a_path_at_all = false;\n                b_feasible = false;\n                b_correctly_extended = false;\n                spp_spptw_res_cont actual_final_resource_levels2(0, 0);\n                graph_traits< SPPRC_Example_Graph >::edge_descriptor\n                    ed_last_extended_arc2;\n                check_r_c_path(g, opt_solutions_spptw[0],\n                    spp_spptw_res_cont(0, g[s].eat), false,\n                    pareto_opt_rcs_spptw[0], actual_final_resource_levels2,\n                    ref_spptw(), b_is_a_path_at_all, b_feasible,\n                    b_correctly_extended, ed_last_extended_arc2);\n                BOOST_TEST(\n                    b_is_a_path_at_all && b_feasible && b_correctly_extended);\n            }\n        }\n    }\n\n    std::vector< int > i_vec_correct_num_solutions_spptw;\n    i_vec_correct_num_solutions_spptw.push_back(1);\n    i_vec_correct_num_solutions_spptw.push_back(2);\n    i_vec_correct_num_solutions_spptw.push_back(3);\n    i_vec_correct_num_solutions_spptw.push_back(1);\n    i_vec_correct_num_solutions_spptw.push_back(3);\n    i_vec_correct_num_solutions_spptw.push_back(1);\n    i_vec_correct_num_solutions_spptw.push_back(2);\n    i_vec_correct_num_solutions_spptw.push_back(1);\n    i_vec_correct_num_solutions_spptw.push_back(2);\n    i_vec_correct_num_solutions_spptw.push_back(1);\n    i_vec_correct_num_solutions_spptw.push_back(1);\n    i_vec_correct_num_solutions_spptw.push_back(1);\n    i_vec_correct_num_solutions_spptw.push_back(4);\n    i_vec_correct_num_solutions_spptw.push_back(1);\n    i_vec_correct_num_solutions_spptw.push_back(3);\n    i_vec_correct_num_solutions_spptw.push_back(1);\n    i_vec_correct_num_solutions_spptw.push_back(1);\n    i_vec_correct_num_solutions_spptw.push_back(1);\n    i_vec_correct_num_solutions_spptw.push_back(2);\n    i_vec_correct_num_solutions_spptw.push_back(2);\n    i_vec_correct_num_solutions_spptw.push_back(4);\n    i_vec_correct_num_solutions_spptw.push_back(1);\n    i_vec_correct_num_solutions_spptw.push_back(1);\n    i_vec_correct_num_solutions_spptw.push_back(1);\n    i_vec_correct_num_solutions_spptw.push_back(4);\n    i_vec_correct_num_solutions_spptw.push_back(1);\n    i_vec_correct_num_solutions_spptw.push_back(2);\n    i_vec_correct_num_solutions_spptw.push_back(1);\n    i_vec_correct_num_solutions_spptw.push_back(1);\n    i_vec_correct_num_solutions_spptw.push_back(3);\n    i_vec_correct_num_solutions_spptw.push_back(2);\n    i_vec_correct_num_solutions_spptw.push_back(2);\n    i_vec_correct_num_solutions_spptw.push_back(2);\n    i_vec_correct_num_solutions_spptw.push_back(1);\n    i_vec_correct_num_solutions_spptw.push_back(2);\n    i_vec_correct_num_solutions_spptw.push_back(0);\n    i_vec_correct_num_solutions_spptw.push_back(1);\n    i_vec_correct_num_solutions_spptw.push_back(1);\n    i_vec_correct_num_solutions_spptw.push_back(2);\n    i_vec_correct_num_solutions_spptw.push_back(1);\n    i_vec_correct_num_solutions_spptw.push_back(1);\n    i_vec_correct_num_solutions_spptw.push_back(2);\n    i_vec_correct_num_solutions_spptw.push_back(2);\n    i_vec_correct_num_solutions_spptw.push_back(1);\n    i_vec_correct_num_solutions_spptw.push_back(1);\n    i_vec_correct_num_solutions_spptw.push_back(1);\n    i_vec_correct_num_solutions_spptw.push_back(2);\n    i_vec_correct_num_solutions_spptw.push_back(1);\n    i_vec_correct_num_solutions_spptw.push_back(2);\n    i_vec_correct_num_solutions_spptw.push_back(1);\n    i_vec_correct_num_solutions_spptw.push_back(4);\n    i_vec_correct_num_solutions_spptw.push_back(2);\n    i_vec_correct_num_solutions_spptw.push_back(2);\n    i_vec_correct_num_solutions_spptw.push_back(1);\n    i_vec_correct_num_solutions_spptw.push_back(4);\n    i_vec_correct_num_solutions_spptw.push_back(1);\n    i_vec_correct_num_solutions_spptw.push_back(4);\n    i_vec_correct_num_solutions_spptw.push_back(1);\n    i_vec_correct_num_solutions_spptw.push_back(1);\n    i_vec_correct_num_solutions_spptw.push_back(2);\n    i_vec_correct_num_solutions_spptw.push_back(2);\n    i_vec_correct_num_solutions_spptw.push_back(1);\n    i_vec_correct_num_solutions_spptw.push_back(4);\n    i_vec_correct_num_solutions_spptw.push_back(2);\n    i_vec_correct_num_solutions_spptw.push_back(5);\n    i_vec_correct_num_solutions_spptw.push_back(1);\n    i_vec_correct_num_solutions_spptw.push_back(1);\n    i_vec_correct_num_solutions_spptw.push_back(1);\n    i_vec_correct_num_solutions_spptw.push_back(2);\n    i_vec_correct_num_solutions_spptw.push_back(2);\n    i_vec_correct_num_solutions_spptw.push_back(1);\n    i_vec_correct_num_solutions_spptw.push_back(3);\n    i_vec_correct_num_solutions_spptw.push_back(1);\n    i_vec_correct_num_solutions_spptw.push_back(1);\n    i_vec_correct_num_solutions_spptw.push_back(2);\n    i_vec_correct_num_solutions_spptw.push_back(0);\n    i_vec_correct_num_solutions_spptw.push_back(2);\n    i_vec_correct_num_solutions_spptw.push_back(1);\n    i_vec_correct_num_solutions_spptw.push_back(1);\n    i_vec_correct_num_solutions_spptw.push_back(1);\n    i_vec_correct_num_solutions_spptw.push_back(3);\n    i_vec_correct_num_solutions_spptw.push_back(1);\n    i_vec_correct_num_solutions_spptw.push_back(2);\n    i_vec_correct_num_solutions_spptw.push_back(1);\n    i_vec_correct_num_solutions_spptw.push_back(3);\n    i_vec_correct_num_solutions_spptw.push_back(1);\n    i_vec_correct_num_solutions_spptw.push_back(3);\n    i_vec_correct_num_solutions_spptw.push_back(1);\n    i_vec_correct_num_solutions_spptw.push_back(1);\n    i_vec_correct_num_solutions_spptw.push_back(2);\n    i_vec_correct_num_solutions_spptw.push_back(1);\n    i_vec_correct_num_solutions_spptw.push_back(1);\n    i_vec_correct_num_solutions_spptw.push_back(4);\n    i_vec_correct_num_solutions_spptw.push_back(1);\n    i_vec_correct_num_solutions_spptw.push_back(3);\n    i_vec_correct_num_solutions_spptw.push_back(0);\n    i_vec_correct_num_solutions_spptw.push_back(2);\n    i_vec_correct_num_solutions_spptw.push_back(3);\n    i_vec_correct_num_solutions_spptw.push_back(4);\n    i_vec_correct_num_solutions_spptw.push_back(1);\n    for (int s = 0; s < 10; ++s)\n        for (int t = 0; t < 10; ++t)\n            BOOST_TEST(static_cast< int >(\n                            vec_vec_vec_vec_opt_solutions_spptw[s][t].size())\n                == i_vec_correct_num_solutions_spptw[10 * s + t]);\n\n    // one pareto-optimal solution\n    SPPRC_Example_Graph g2;\n    add_vertex(SPPRC_Example_Graph_Vert_Prop(0, 0, 1000000000), g2);\n    add_vertex(SPPRC_Example_Graph_Vert_Prop(1, 0, 1000000000), g2);\n    add_vertex(SPPRC_Example_Graph_Vert_Prop(2, 0, 1000000000), g2);\n    add_vertex(SPPRC_Example_Graph_Vert_Prop(3, 0, 1000000000), g2);\n    add_edge(0, 1, SPPRC_Example_Graph_Arc_Prop(0, 1, 1), g2);\n    add_edge(0, 2, SPPRC_Example_Graph_Arc_Prop(1, 2, 1), g2);\n    add_edge(1, 3, SPPRC_Example_Graph_Arc_Prop(2, 3, 1), g2);\n    add_edge(2, 3, SPPRC_Example_Graph_Arc_Prop(3, 1, 1), g2);\n    std::vector< graph_traits< SPPRC_Example_Graph >::edge_descriptor >\n        opt_solution;\n    spp_spptw_res_cont pareto_opt_rc;\n    r_c_shortest_paths(g2, get(&SPPRC_Example_Graph_Vert_Prop::num, g2),\n        get(&SPPRC_Example_Graph_Arc_Prop::num, g2), 0, 3, opt_solution,\n        pareto_opt_rc, spp_spptw_res_cont(0, 0), ref_spptw(), dominance_spptw(),\n        std::allocator< r_c_shortest_paths_label< SPPRC_Example_Graph,\n            spp_spptw_res_cont > >(),\n        default_r_c_shortest_paths_visitor());\n\n    BOOST_TEST(pareto_opt_rc.cost == 3);\n\n    SPPRC_Example_Graph g3;\n    add_vertex(SPPRC_Example_Graph_Vert_Prop(0, 0, 1000), g3);\n    add_vertex(SPPRC_Example_Graph_Vert_Prop(1, 0, 1000), g3);\n    add_vertex(SPPRC_Example_Graph_Vert_Prop(2, 0, 974), g3);\n    add_vertex(SPPRC_Example_Graph_Vert_Prop(3, 0, 972), g3);\n    add_vertex(SPPRC_Example_Graph_Vert_Prop(4, 0, 967), g3);\n    add_vertex(SPPRC_Example_Graph_Vert_Prop(5, 678, 801), g3);\n    add_edge(0, 2, SPPRC_Example_Graph_Arc_Prop(0, 0, 16), g3);\n    add_edge(0, 3, SPPRC_Example_Graph_Arc_Prop(1, 0, 18), g3);\n    add_edge(0, 4, SPPRC_Example_Graph_Arc_Prop(2, 0, 23), g3);\n    add_edge(0, 5, SPPRC_Example_Graph_Arc_Prop(3, 0, 25), g3);\n    add_edge(2, 3, SPPRC_Example_Graph_Arc_Prop(4, 0, 33), g3);\n    add_edge(2, 4, SPPRC_Example_Graph_Arc_Prop(5, 0, 15), g3);\n    add_edge(2, 5, SPPRC_Example_Graph_Arc_Prop(6, 0, 33), g3);\n    add_edge(2, 1, SPPRC_Example_Graph_Arc_Prop(7, 0, 16), g3);\n    add_edge(3, 2, SPPRC_Example_Graph_Arc_Prop(8, 0, 33), g3);\n    add_edge(3, 4, SPPRC_Example_Graph_Arc_Prop(9, 0, 35), g3);\n    add_edge(3, 5, SPPRC_Example_Graph_Arc_Prop(10, 0, 21), g3);\n    add_edge(3, 1, SPPRC_Example_Graph_Arc_Prop(11, 0, 18), g3);\n    add_edge(4, 2, SPPRC_Example_Graph_Arc_Prop(12, 0, 15), g3);\n    add_edge(4, 3, SPPRC_Example_Graph_Arc_Prop(13, 0, 35), g3);\n    add_edge(4, 5, SPPRC_Example_Graph_Arc_Prop(14, 0, 25), g3);\n    add_edge(4, 1, SPPRC_Example_Graph_Arc_Prop(15, 0, 23), g3);\n    add_edge(5, 2, SPPRC_Example_Graph_Arc_Prop(16, 0, 33), g3);\n    add_edge(5, 3, SPPRC_Example_Graph_Arc_Prop(17, 0, 21), g3);\n    add_edge(5, 4, SPPRC_Example_Graph_Arc_Prop(18, 0, 25), g3);\n    add_edge(5, 1, SPPRC_Example_Graph_Arc_Prop(19, 0, 25), g3);\n\n    std::vector<\n        std::vector< graph_traits< SPPRC_Example_Graph >::edge_descriptor > >\n        pareto_opt_marked_solutions;\n    std::vector< spp_spptw_marked_res_cont >\n        pareto_opt_marked_resource_containers;\n\n    graph_traits< SPPRC_Example_Graph >::vertex_descriptor g3_source = 0,\n                                                           g3_target = 1;\n    r_c_shortest_paths(g3, get(&SPPRC_Example_Graph_Vert_Prop::num, g3),\n        get(&SPPRC_Example_Graph_Arc_Prop::num, g3), g3_source, g3_target,\n        pareto_opt_marked_solutions, pareto_opt_marked_resource_containers,\n        spp_spptw_marked_res_cont(0, 0, 0), ref_spptw_marked(),\n        dominance_spptw_marked(),\n        std::allocator< r_c_shortest_paths_label< SPPRC_Example_Graph,\n            spp_spptw_marked_res_cont > >(),\n        default_r_c_shortest_paths_visitor());\n\n    BOOST_TEST(!pareto_opt_marked_solutions.empty());\n    std::vector< std::vector<\n        graph_traits< SPPRC_Example_Graph >::edge_descriptor > >::const_iterator\n        path_it,\n        path_end_it;\n    for (path_it = pareto_opt_marked_solutions.begin(),\n        path_end_it = pareto_opt_marked_solutions.end();\n         path_it != path_end_it; ++path_it)\n    {\n        const std::vector<\n            graph_traits< SPPRC_Example_Graph >::edge_descriptor >& path\n            = *path_it;\n        BOOST_TEST(!path.empty());\n\n        const graph_traits< SPPRC_Example_Graph >::edge_descriptor front\n            = path.front();\n        BOOST_TEST(boost::target(front, g3) == g3_target);\n\n        std::vector< graph_traits< SPPRC_Example_Graph >::edge_descriptor >::\n            const_iterator edge_it,\n            edge_it_end;\n        graph_traits< SPPRC_Example_Graph >::edge_descriptor prev_edge = front;\n\n        for (edge_it = path.begin() + 1, edge_it_end = path.end();\n             edge_it != edge_it_end; ++edge_it)\n        {\n            graph_traits< SPPRC_Example_Graph >::edge_descriptor edge\n                = *edge_it;\n\n            graph_traits< SPPRC_Example_Graph >::vertex_descriptor prev_end,\n                current_end;\n            prev_end = boost::source(prev_edge, g3);\n            current_end = boost::target(edge, g3);\n            BOOST_TEST(prev_end == current_end);\n\n            prev_edge = edge;\n        }\n\n        const graph_traits< SPPRC_Example_Graph >::edge_descriptor back\n            = path.back();\n        BOOST_TEST(boost::source(back, g3) == g3_source);\n    }\n\n    return boost::report_errors();\n}\n", "meta": {"hexsha": "7a80d7c1c880c188082f4ef4d24b842aae66ae2b", "size": 33313, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/graph/test/r_c_shortest_paths_test.cpp", "max_stars_repo_name": "uosorio/heroku_face", "max_stars_repo_head_hexsha": "7d6465e71dba17a15d8edaef520adb2fcd09d91e", "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": "3rdparty/boost_1_73_0/libs/graph/test/r_c_shortest_paths_test.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 130.0, "max_issues_repo_issues_event_min_datetime": "2016-06-22T22:11:25.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-29T20:24:09.000Z", "max_forks_repo_path": "3rdparty/boost_1_73_0/libs/graph/test/r_c_shortest_paths_test.cpp", "max_forks_repo_name": "qingkouwei/mediaones", "max_forks_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2015-07-08T19:18:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-14T16:39:56.000Z", "avg_line_length": 42.3829516539, "max_line_length": 80, "alphanum_fraction": 0.691681926, "num_tokens": 10216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125626441471, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.46255379447793005}}
{"text": "#include \"performance_test.hpp\"\r\n\r\n\r\n#include <imgproc/derivative_gradient.hpp>\r\n#include <imgproc/threshold.hpp>\r\n#include <edge/nms.hpp>\r\n#include <utility/results.hpp>\r\n#include <boost/filesystem.hpp>\r\n\r\n\r\nusing namespace lsfm;\r\nnamespace fs = boost::filesystem;\r\n\r\ntemplate<class FT>\r\nstruct Entry  : public PerformanceTaskDefault {\r\n    Entry() {}\r\n\r\n    Entry(const cv::Ptr<FilterI<uchar>>& a, const cv::Ptr<Threshold<FT>> &t, const std::string& n, int f = 0)\r\n        : PerformanceTaskDefault(n,f), filter(a), threshold(t) {}\r\n   \r\n    \r\n    cv::Ptr<FilterI<uchar>> filter;\r\n    cv::Ptr<Threshold<FT>> threshold;\r\n\r\n    FilterResults filterRes;\r\n    cv::Mat thresholdRes;\r\n    std::string resName;\r\n\r\n\r\n    void run(const std::string& src_name, cv::Mat src, int loops, bool verbose) {\r\n        this->measure.push_back(PerformanceMeasure(src_name, this->name, src.cols, src.rows));\r\n        PerformanceMeasure& pm = this->measure.back();\r\n        resName = \"./results/visual/Threshold/\" + src_name.substr(0,src_name.size()-4) + \"_\" + this->name;\r\n        if (verbose)\r\n            std::cout << \"    Running \" << this->name << \" ... \";\r\n        filter->process(src);\r\n        filterRes = filter->results();\r\n        cv::Mat mag = filterRes[\"mag\"].data;\r\n        uint64 start;\r\n        for (int i = 0; i != loops; ++i) {\r\n            start = cv::getTickCount();\r\n            thresholdRes = threshold->process(mag);\r\n            pm.measures.push_back(cv::getTickCount() - start);\r\n        }\r\n        if (verbose)\r\n            std::cout << std::setprecision(3) << static_cast<double>((cv::getTickCount() - start) * 1000) / (loops * cv::getTickFrequency()) << \"ms\" << std::endl;\r\n    }\r\n\r\n    void saveResults(bool verbose) {\r\n\r\n        NonMaximaSuppression<short, FT, FT> nms;\r\n        cv::Mat high = thresholdRes.clone();\r\n        cv::GaussianBlur(high, high, cv::Size(0, 0),15);\r\n        cv::Mat low = high * 0.5;\r\n        // set fixed lower threshold\r\n        low.setTo(filterRes[\"mag\"].range.upper * 0.004, low < filterRes[\"mag\"].range.upper * 0.004);\r\n        nms.process(filterRes[\"gx\"].data, filterRes[\"gy\"].data, filterRes[\"mag\"].data, low, high);\r\n        if (verbose)\r\n            std::cout << \"    Save visual results \" << resName << std::endl;\r\n        saveEdge(nms.hysteresis(), resName + \"_mag\");\r\n        saveNormalized(high, resName + \"_th\");\r\n    }\r\n};\r\n\r\n\r\nvoid createThresholdPerformanceTest(PerformanceTestPtr& test, const DataProviderMap& provider)\r\n{  \r\n    test.reset(new PerformanceTest);\r\n    test->name = \"Threshold\";\r\n    try {\r\n        addDefault(provider, test->data);\r\n\r\n        //add other\r\n    }\r\n    catch (std::exception& e) {\r\n        std::cout << test->name << \" parse error: \" << e.what() << std::endl;\r\n        return;\r\n    }\r\n\r\n    fs::create_directory(\"./results/visual/Threshold\");\r\n\r\n    typedef float FT;\r\n\r\n    test->tasks.push_back(PerformanceTaskPtr(new Entry<FT>(new DerivativeGradient<uchar, short,FT, FT, SobelDerivative>, new GlobalThreshold<FT,ThresholdOtsu<FT,256>>(1141), \"Otsu_G\")));\r\n    test->tasks.push_back(PerformanceTaskPtr(new Entry<FT>(new DerivativeGradient<uchar, short, FT, FT, SobelDerivative>, new LocalThresholdTiles<FT, ThresholdOtsu<FT, 256>>(3, 3, 1141), \"Otsu_LTiles4\")));\r\n    test->tasks.push_back(PerformanceTaskPtr(new Entry<FT>(new DerivativeGradient<uchar, short, FT, FT, SobelDerivative>, new LocalThresholdTiles<FT, ThresholdOtsu<FT, 256>>(10, 10, 1141), \"Otsu_LTiles10\")));\r\n    test->tasks.push_back(PerformanceTaskPtr(new Entry<FT>(new DerivativeGradient<uchar, short, FT, FT, SobelDerivative>, new LocalThreshold<FT, ThresholdOtsu<FT, 256>>(30,30,true,1141), \"Otsu_LWindow\")));\r\n    test->tasks.push_back(PerformanceTaskPtr(new Entry<FT>(new DerivativeGradient<uchar, short, FT, FT, SobelDerivative>, new DynamicThreshold<FT, ThresholdOtsu<FT, 256>>(5, 1141), \"Otsu_D\")));\r\n\r\n}\r\n\r\nbool addThreshold() {\r\n    addPerformanceTestCreator(createThresholdPerformanceTest);\r\n    std::cout << \"Added threshold performance test\" << std::endl;\r\n    return true;\r\n}\r\n\r\nbool thresholdAdded = addThreshold();\r\n\r\n", "meta": {"hexsha": "4de90419b9275036aaeaae34a867f9dfb484a696", "size": 4085, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "evaluation/performance/threshold.cpp", "max_stars_repo_name": "waterben/LineExtraction", "max_stars_repo_head_hexsha": "d247de45417a1512a3bf5d0ffcd630d40ffb8798", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-12T13:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-12T13:30:56.000Z", "max_issues_repo_path": "evaluation/performance/threshold.cpp", "max_issues_repo_name": "waterben/LineExtraction", "max_issues_repo_head_hexsha": "d247de45417a1512a3bf5d0ffcd630d40ffb8798", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "evaluation/performance/threshold.cpp", "max_forks_repo_name": "waterben/LineExtraction", "max_forks_repo_head_hexsha": "d247de45417a1512a3bf5d0ffcd630d40ffb8798", "max_forks_repo_licenses": ["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.85, "max_line_length": 209, "alphanum_fraction": 0.6335373317, "num_tokens": 1081, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.752012562644147, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.46255379447792994}}
{"text": "#include <iostream>\n#include <cmath>\n#include <algorithm>\n#include <vector>\n#include <boost/multiprecision/cpp_int.hpp>\nusing namespace boost::multiprecision;\nusing namespace std;\nint main() {\n    int n; cin >> n;\n    vector<int> a(n, 0);\n    cpp_int sum = 0, ans = 0;\n    for (int i = 0; i < n; i++) {\n        cin >> a[i]; sum += a[i];\n    }\n    for (int i = 0; i < n - 1; i++) {\n        ans += (sum -= a[i]) * a[i];\n    }\n    cout << ans % 1000000007 << endl;\n}\n", "meta": {"hexsha": "7a2d4fea0e762ac5bf36217a7e396b118585df1a", "size": 464, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AtCoder/abc177/c/main.cpp", "max_stars_repo_name": "H-Tatsuhiro/Com_Pro-Cpp", "max_stars_repo_head_hexsha": "fd79f7821a76b11f4a6f83bbb26a034db577a877", "max_stars_repo_licenses": ["MIT"], "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/abc177/c/main.cpp", "max_issues_repo_name": "H-Tatsuhiro/Com_Pro-Cpp", "max_issues_repo_head_hexsha": "fd79f7821a76b11f4a6f83bbb26a034db577a877", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-10-19T08:47:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T05:23:56.000Z", "max_forks_repo_path": "AtCoder/abc177/c/main.cpp", "max_forks_repo_name": "H-Tatsuhiro/Com_Pro-Cpp", "max_forks_repo_head_hexsha": "fd79f7821a76b11f4a6f83bbb26a034db577a877", "max_forks_repo_licenses": ["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.2, "max_line_length": 43, "alphanum_fraction": 0.5344827586, "num_tokens": 149, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397348, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.46254020766125836}}
{"text": "#include <Eigen/Core>\n#include <iostream>\n#include \"timer.h\"\n#include \"ArpackFun.h\"\n\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\nusing Eigen::MatrixXcd;\nusing Eigen::VectorXcd;\nusing Eigen::Lower;\ntypedef Eigen::Map<VectorXd> MapVec;\n\nvoid eigs_sym_F77(MatrixXd &M, VectorXd &init_resid, int k, int m,\n                  double &time_used, double &prec_err, int &nops)\n{\n    double start, end;\n    prec_err = -1.0;\n    start = get_wall_time();\n\n    // Begin ARPACK\n    //\n    // Initial value of ido\n    int ido = 0;\n    // 'I' means standard eigen value problem, A * x = lambda * x\n    char bmat = 'I';\n    // dimension of A (n by n)\n    int n = M.rows();\n    // Specify selection criteria\n    // \"LM\": largest magnitude\n    char which[3] = {'L', 'M', '\\0'};\n    // Number of eigenvalues requested\n    int nev = k;\n    // Precision\n    double tol = 1e-10;\n    // Residual vector\n    double *resid = new double[n]();\n    std::copy(init_resid.data(), init_resid.data() + n, resid);\n    // Number of Ritz values used\n    int ncv = m;\n    // Vector of eigenvalues\n    VectorXd evals(nev);\n    // Matrix of eigenvectors\n    MatrixXd evecs(n, ncv);\n\n    // Store final results of eigenvectors\n    // double *V = new double[n * ncv]();\n    double *V = evecs.data();\n    // Leading dimension of V, required by FORTRAN\n    int ldv = n;\n    // Control parameters\n    int *iparam = new int[11]();\n    iparam[1 - 1] = 1;     // ishfts\n    iparam[3 - 1] = 1000;  // maxitr\n    iparam[7 - 1] = 1;     // mode\n    // Some pointers\n    int *ipntr = new int[11]();\n    /* workd has 3 columns.\n     * ipntr[2] - 1 ==> first column to store B * X,\n     * ipntr[1] - 1 ==> second to store Y,\n     * ipntr[0] - 1 ==> third to store X. */\n    double *workd = new double[3 * n]();\n    int lworkl = ncv * (ncv + 8);\n    double *workl = new double[lworkl]();\n    // Error flag. 0 means random initialization,\n    // otherwise using resid as initial value\n    int info = 1;\n\n    saupd(ido, bmat, n, which,\n          nev, tol, resid,\n          ncv, V, ldv,\n          iparam, ipntr, workd,\n          workl, lworkl, info);\n    // ido == -1 or ido == 1 means more iterations needed\n    while (ido == -1 || ido == 1)\n    {\n        MapVec vec_in(&workd[ipntr[0] - 1], n);\n        MapVec vec_out(&workd[ipntr[1] - 1], n);\n        vec_out.noalias() = M.selfadjointView<Lower>() * vec_in;\n\n        saupd(ido, bmat, n, which,\n              nev, tol, resid,\n              ncv, V, ldv,\n              iparam, ipntr, workd,\n              workl, lworkl, info);\n    }\n\n    // info > 0 means warning, < 0 means error\n    if (info > 0)\n        std::cout << \"warnings occured\" << std::endl;\n    if (info < 0)\n    {\n        delete[] workl;\n        delete[] workd;\n        delete[] ipntr;\n        delete[] iparam;\n        delete[] resid;\n\n        std::cout << \"errors occured\" << std::endl;\n        end = get_wall_time();\n        time_used = (end - start) * 1000;\n\n        return;\n    }\n\n    // Retrieve results\n    //\n    // Whether to calculate eigenvectors or not.\n    bool rvec = true;\n    // 'A' means to calculate Ritz vectors\n    // 'P' to calculate Schur vectors\n    char howmny = 'A';\n    // Vector of eigenvalues\n    double *d = evals.data();\n    // Used to store results, will use V instead.\n    double *Z = V;\n    // Leading dimension of Z, required by FORTRAN\n    int ldz = n;\n    // Shift\n    double sigma = 0;\n    // Error information\n    int ierr = 0;\n\n    // Number of converged eigenvalues\n    int nconv = 0;\n    // Number of iterations\n    int niter = 0;\n\n    // Use seupd() to retrieve results\n    seupd(rvec, howmny, d,\n          Z, ldz, sigma, bmat,\n          n, which, nev, tol,\n          resid, ncv, V, ldv,\n          iparam, ipntr, workd, workl,\n          lworkl, ierr);\n\n    // Obtain 'nconv' converged eigenvalues\n    nconv = iparam[5 - 1];\n    // 'niter' number of iterations\n    niter = iparam[9 - 1];\n\n    // Free memory of temp arrays\n    delete[] workl;\n    delete[] workd;\n    delete[] ipntr;\n    delete[] iparam;\n    delete[] resid;\n\n    // ierr < 0 means error\n    if (ierr < 0)\n    {\n        std::cout << \"errors occured\" << std::endl;\n        end = get_wall_time();\n        time_used = (end - start) * 1000;\n\n        return;\n    }\n\n    /* std::cout << \"computed eigenvalues D = \\n\" << evals.transpose() << std::endl;\n    std::cout << \"first 5 rows of computed eigenvectors U = \\n\" <<\n    evecs.topLeftCorner(5, nconv) << std::endl;\n    std::cout << \"nconv = \" << nconv << std::endl;\n    std::cout << \"nops = \" << niter << std::endl; */\n\n    end = get_wall_time();\n    time_used = (end - start) * 1000;\n    MatrixXd err = M * evecs.leftCols(nev) - evecs.leftCols(nev) * evals.asDiagonal();\n    prec_err = err.cwiseAbs().maxCoeff();\n    nops = niter;\n}\n\nvoid eigs_gen_F77(MatrixXd &M, VectorXd &init_resid, int k, int m,\n                  double &time_used, double &prec_err, int &nops)\n{\n    double start, end;\n    prec_err = -1.0;\n    start = get_wall_time();\n\n    // Begin ARPACK\n    //\n    // Initial value of ido\n    int ido = 0;\n    // 'I' means standard eigen value problem, A * x = lambda * x\n    char bmat = 'I';\n    // dimension of A (n by n)\n    int n = M.rows();\n    // Specify selection criteria\n    // \"LM\": largest magnitude\n    char which[3] = {'L', 'M', '\\0'};\n    // Number of eigenvalues requested\n    int nev = k;\n    // Precision\n    double tol = 1e-10;\n    // Residual vector\n    double *resid = new double[n]();\n    std::copy(init_resid.data(), init_resid.data() + n, resid);\n    // Number of Ritz values used\n    int ncv = m;\n    // Vector of eigenvalues\n    VectorXd evals_re(nev + 1);\n    VectorXd evals_im(nev + 1);\n    // Matrix of eigenvectors\n    MatrixXd evecs(n, ncv);\n\n    // Store final results of eigenvectors\n    // double *V = new double[n * ncv]();\n    double *V = evecs.data();\n    // Leading dimension of V, required by FORTRAN\n    int ldv = n;\n    // Control parameters\n    int *iparam = new int[11]();\n    iparam[1 - 1] = 1;     // ishfts\n    iparam[3 - 1] = 1000;  // maxitr\n    iparam[7 - 1] = 1;     // mode\n    // Some pointers\n    int *ipntr = new int[14]();\n    /* workd has 3 columns.\n     * ipntr[2] - 1 ==> first column to store B * X,\n     * ipntr[1] - 1 ==> second to store Y,\n     * ipntr[0] - 1 ==> third to store X. */\n    double *workd = new double[3 * n]();\n    int lworkl = 3 * ncv * ncv + 6 * ncv;\n    double *workl = new double[lworkl]();\n    // Error flag. 0 means random initialization,\n    // otherwise using resid as initial value\n    int info = 1;\n\n    naupd(ido, bmat, n, which,\n          nev, tol, resid,\n          ncv, V, ldv,\n          iparam, ipntr, workd,\n          workl, lworkl, info);\n    // ido == -1 or ido == 1 means more iterations needed\n    while (ido == -1 || ido == 1)\n    {\n        MapVec vec_in(&workd[ipntr[0] - 1], n);\n        MapVec vec_out(&workd[ipntr[1] - 1], n);\n        vec_out.noalias() = M * vec_in;\n\n        naupd(ido, bmat, n, which,\n              nev, tol, resid,\n              ncv, V, ldv,\n              iparam, ipntr, workd,\n              workl, lworkl, info);\n    }\n\n    // info > 0 means warning, < 0 means error\n    if (info > 0)\n        std::cout << \"warnings occured\" << std::endl;\n    if (info < 0)\n    {\n        delete[] workl;\n        delete[] workd;\n        delete[] ipntr;\n        delete[] iparam;\n        delete[] resid;\n\n        std::cout << \"errors occured\" << std::endl;\n        end = get_wall_time();\n        time_used = (end - start) * 1000;\n\n        return;\n    }\n\n    // Retrieve results\n    //\n    // Whether to calculate eigenvectors or not.\n    bool rvec = true;\n    // 'A' means to calculate Ritz vectors\n    // 'P' to calculate Schur vectors\n    char howmny = 'A';\n    // Vector of eigenvalues\n    double *dr = evals_re.data();\n    double *di = evals_im.data();\n    // Used to store results, will use V instead.\n    double *Z = V;\n    // Leading dimension of Z, required by FORTRAN\n    int ldz = n;\n    // Shift\n    double sigmar = 0;\n    double sigmai = 0;\n    // Working space\n    double *workv = new double[3 * ncv]();\n    // Error information\n    int ierr = 0;\n\n    // Number of converged eigenvalues\n    int nconv = 0;\n    // Number of iterations\n    int niter = 0;\n\n    // Use seupd() to retrieve results\n    neupd(rvec, howmny, dr, di,\n          Z, ldz, sigmar, sigmai, workv,\n          bmat, n, which, nev, tol,\n          resid, ncv, V, ldv, iparam,\n          ipntr, workd, workl, lworkl, ierr);\n\n    // Obtain 'nconv' converged eigenvalues\n    nconv = iparam[5 - 1];\n    // 'niter' number of iterations\n    niter = iparam[9 - 1];\n\n    // Free memory of temp arrays\n    delete[] workv;\n    delete[] workl;\n    delete[] workd;\n    delete[] ipntr;\n    delete[] iparam;\n    delete[] resid;\n\n    // ierr < 0 means error\n    if (ierr < 0)\n    {\n        std::cout << \"errors occured\" << std::endl;\n        end = get_wall_time();\n        time_used = (end - start) * 1000;\n\n        return;\n    }\n\n    /* VectorXcd evals(evals_re.size());\n    evals.real() = evals_re;\n    evals.imag() = evals_im;\n    std::cout << \"computed eigenvalues D = \\n\" << evals << std::endl;\n    std::cout << \"first 5 rows of computed eigenvectors U = \\n\" <<\n        evecs.topLeftCorner(5, nconv) << std::endl;\n    std::cout << \"nconv = \" << nconv << std::endl;\n    std::cout << \"nops = \" << niter << std::endl; */\n\n    end = get_wall_time();\n    time_used = (end - start) * 1000;\n    nops = niter;\n}\n", "meta": {"hexsha": "445f92db8c7002d146df55ecbf4d3695e4532787", "size": 9388, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdparty/teaser_plusplus/3rdparty/spectra/benchmark/F77.cpp", "max_stars_repo_name": "mushroom-x/Misc3D", "max_stars_repo_head_hexsha": "10f05c970eda9684b19de42a128224502e23b89b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2022-02-09T11:56:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:45:04.000Z", "max_issues_repo_path": "3rdparty/teaser_plusplus/3rdparty/spectra/benchmark/F77.cpp", "max_issues_repo_name": "mushroom-x/Misc3D", "max_issues_repo_head_hexsha": "10f05c970eda9684b19de42a128224502e23b89b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2022-02-26T08:58:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T11:19:05.000Z", "max_forks_repo_path": "3rdparty/teaser_plusplus/3rdparty/spectra/benchmark/F77.cpp", "max_forks_repo_name": "mushroom-x/Misc3D", "max_forks_repo_head_hexsha": "10f05c970eda9684b19de42a128224502e23b89b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2022-02-16T06:59:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T12:03:11.000Z", "avg_line_length": 28.1077844311, "max_line_length": 86, "alphanum_fraction": 0.548359608, "num_tokens": 2950, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4625402018862748}}
{"text": "#include <igl/opengl/glfw/Viewer.h>\n#include <igl/copyleft/tetgen/tetrahedralize.h>\n#include <igl/readOBJ.h>\n#include <igl/marching_tets.h>\n#include <Eigen/Core>\n\n#include \"tutorial_shared_path.h\"\n\n\nint main(int argc, char * argv[])\n{\n\n  // Load a surface mesh which is a cube\n  Eigen::MatrixXd surfaceV;\n  Eigen::MatrixXi surfaceF;\n  igl::readOBJ(TUTORIAL_SHARED_PATH \"/cube.obj\", surfaceV, surfaceF);\n\n  // Find the centroid of the loaded mesh\n  Eigen::RowVector3d surfaceCenter = surfaceV.colwise().sum() / surfaceV.rows();\n\n  // Center the mesh about the origin\n  surfaceV.rowwise() -= surfaceCenter;\n\n  // Tetrahedralize the surface mesh\n  Eigen::MatrixXd TV; // Tet mesh vertices\n  Eigen::MatrixXi TF; // Tet mesh boundary face indices\n  Eigen::MatrixXi TT; // Tet mesh tetrahedron indices\n  igl::copyleft::tetgen::tetrahedralize(surfaceV, surfaceF, \"pq1.414a0.0001\", TV, TT, TF);\n\n  // Compute a scalar at each tet vertex which is the distance from the vertex to the origin\n  Eigen::VectorXd S = TV.rowwise().norm();\n\n  // Compute a mesh (stored in SV, SF) representing the iso-level-set for the isovalue 0.5\n  Eigen::MatrixXd SV;\n  Eigen::MatrixXi SF;\n  igl::marching_tets(TV, TT, S, 0.45, SV, SF);\n\n  // Draw the mesh stored in (SV, SF)\n  igl::opengl::glfw::Viewer viewer;\n  viewer.data().set_mesh(SV, SF);\n  viewer.callback_key_down =\n    [&](igl::opengl::glfw::Viewer & viewer, unsigned char key, int mod)->bool\n    {\n      viewer.data().set_face_based(true);\n      return true;\n    };\n  viewer.launch();\n}\n", "meta": {"hexsha": "bcbd9176aaced36880855488fcb9c40090151511", "size": 1518, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "isometric-deformation/ext/libigl/tutorial/714_MarchingTets/main.cpp", "max_stars_repo_name": "jiayaozhang/CS-370-Mesh-Processing", "max_stars_repo_head_hexsha": "26646d29af8cbc0d461302afa137f12b508b8b1b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-03T11:30:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-03T11:30:05.000Z", "max_issues_repo_path": "isometric-deformation/ext/libigl/tutorial/714_MarchingTets/main.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/tutorial/714_MarchingTets/main.cpp", "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": 30.9795918367, "max_line_length": 92, "alphanum_fraction": 0.69828722, "num_tokens": 435, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4625402018862748}}
{"text": "// Copyright (c) 2021 fortiss GmbH\n//\n// Authors: Klemens Esterle and Tobias Kessler\n//\n// This work is licensed under the terms of the MIT license.\n// For a copy, see <https://opensource.org/licenses/MIT>.\n\n#include \"parameter_preparer.hpp\"\n#include <math.h>\n#include <algorithm>\n#include <boost/math/constants/constants.hpp>\n#include \"common/math/math.hpp\"\n\nnamespace miqp {\nnamespace common {\nnamespace parameter {\nusing bark::commons::ParamsPtr;\nusing miqp::common::parameter::RotateVector;\n\nParameterPreparer::ParameterPreparer(\n    const ParamsPtr& params, const int nrRegions,\n    const float maxVelocityFitting, const float minVelocityFitting,\n    const float accLonMaxLimit, const float accLonMinLimit,\n    const float jerkLonMaxLimit, const float accLatMinMaxLimit,\n    const float jerkLatMinMaxLimit)\n    : bark::commons::BaseType(params),\n      vehicle_params_(accLonMaxLimit, accLonMinLimit, jerkLonMaxLimit,\n                      accLatMinMaxLimit, jerkLatMinMaxLimit),\n      fittingPolynomial_params_(FittingPolynomialParameters(\n          nrRegions, maxVelocityFitting, minVelocityFitting)),\n      nrRegions_(nrRegions),\n      maxVelocityFitting_(maxVelocityFitting) {\n  CalculateFractionParameters();\n  CalculateMeanAngleVector();\n}\n\nvoid ParameterPreparer::CalculateFractionParameters() {\n  const int nrRegions = nrRegions_;\n  Eigen::VectorXd alphaVec(nrRegions_ + 1);\n  alphaVec.setLinSpaced(0, 2 * M_PI);\n  Eigen::MatrixXd fraction_parameters_col(nrRegions_, 2);\n  fraction_parameters_col.col(0) =\n      maxVelocityFitting_ * alphaVec.head(nrRegions_).array().cos();\n  fraction_parameters_col.col(1) =\n      maxVelocityFitting_ * alphaVec.head(nrRegions_).array().sin();\n  fraction_params_.resize(nrRegions, 4);\n  fraction_params_.block(0, 0, nrRegions, 2) = fraction_parameters_col;\n  fraction_params_.block(0, 2, nrRegions - 1, 2) =\n      fraction_parameters_col.block(1, 0, nrRegions - 1, 2);\n  fraction_params_.block(nrRegions - 1, 2, 1, 2) =\n      fraction_parameters_col.block(0, 0, 1, 2);\n}\n\nLimitPerRegionParameters ParameterPreparer::CalculateAccLimitsPerCar() const {\n  int nr_regions = fraction_params_.rows();\n  const int NumCars = 1;  // only per-car calculation, see addCar() for multiple\n\n  LimitPerRegionParameters acc_limits_per_regions =\n      LimitPerRegionParameters(NumCars, nr_regions);\n\n  for (std::size_t i = 0; i < mean_angle_vector_.size(); ++i) {\n    XYPair max_acc_pair, min_acc_pair;\n    RotateLimitVectors(vehicle_params_.straight_acc_limits,\n                       mean_angle_vector_[i], max_acc_pair, min_acc_pair);\n\n    acc_limits_per_regions.min_x(0, i) = min_acc_pair.x;\n    acc_limits_per_regions.min_y(0, i) = min_acc_pair.y;\n    acc_limits_per_regions.max_x(0, i) = max_acc_pair.x;\n    acc_limits_per_regions.max_y(0, i) = max_acc_pair.y;\n  }\n  return acc_limits_per_regions;\n};\n\nLimitPerRegionParameters ParameterPreparer::CalculateJerkLimitsPerCar() const {\n  int nr_regions = fraction_params_.rows();\n  int NumCars = 1;  // only per-car calculation, see addCar() for multiple\n\n  LimitPerRegionParameters jerk_limits_per_regions =\n      LimitPerRegionParameters(NumCars, nr_regions);\n\n  for (std::size_t i = 0; i < mean_angle_vector_.size(); ++i) {\n    XYPair max_jerk_pair, min_jerk_pair;\n    RotateLimitVectors(vehicle_params_.straight_jerk_limits,\n                       mean_angle_vector_[i], max_jerk_pair, min_jerk_pair);\n\n    jerk_limits_per_regions.min_x(0, i) = min_jerk_pair.x;\n    jerk_limits_per_regions.min_y(0, i) = min_jerk_pair.y;\n    jerk_limits_per_regions.max_x(0, i) = max_jerk_pair.x;\n    jerk_limits_per_regions.max_y(0, i) = max_jerk_pair.y;\n  }\n  return jerk_limits_per_regions;\n};\n\nvoid ParameterPreparer::CalculateMeanAngleVector() {\n  int nr_regions = fraction_params_.rows();\n  for (int idxreg = 0; idxreg < nr_regions; ++idxreg) {\n    double angle_line1 =\n        atan2(fraction_params_(idxreg, 1), fraction_params_(idxreg, 0));\n    double angle_line2 =\n        atan2(fraction_params_(idxreg, 3), fraction_params_(idxreg, 2));\n\n    miqp::common::math::WrapRadiantTo2Pi(angle_line1);\n    miqp::common::math::WrapRadiantTo2Pi(angle_line2);\n\n    if (idxreg + 1 == nr_regions) {\n      angle_line2 = angle_line2 + 2 * boost::math::constants::pi<double>();\n    }\n    mean_angle_vector_.push_back((angle_line1 + angle_line2) / 2);\n  }\n}\n\nvoid ParameterPreparer::RotateLimitVectors(const StraightLimits& straight_lim,\n                                           const float angle, XYPair& max_pair,\n                                           XYPair& min_pair) const {\n  XYPair max_max = RotateVector(\n      straight_lim.straight_long_max + straight_lim.straight_lat_max, angle);\n  XYPair max_min = RotateVector(\n      straight_lim.straight_long_max + straight_lim.straight_lat_min, angle);\n  XYPair min_max = RotateVector(\n      straight_lim.straight_long_min + straight_lim.straight_lat_max, angle);\n  XYPair min_min = RotateVector(\n      straight_lim.straight_long_min + straight_lim.straight_lat_min, angle);\n\n  float max_x =\n      std::max(std::max(max_max.x, max_min.x), std::max(min_max.x, min_min.x));\n  float min_x =\n      std::min(std::min(max_max.x, max_min.x), std::min(min_max.x, min_min.x));\n  float max_y =\n      std::max(std::max(max_max.y, min_max.y), std::max(min_min.y, max_min.y));\n  float min_y =\n      std::min(std::min(max_max.y, min_max.y), std::min(min_min.y, max_min.y));\n\n  miqp::common::math::SwapIfNeeded(max_x, min_x);\n  miqp::common::math::SwapIfNeeded(max_y, min_y);\n  assert(max_x >= min_x);\n  assert(max_y >= min_y);\n\n  max_pair.x = max_x;\n  max_pair.y = max_y;\n\n  min_pair.x = min_x;\n  min_pair.y = min_y;\n};\n\n}  // namespace parameter\n}  // namespace common\n}  // namespace miqp", "meta": {"hexsha": "3039bbe6236a8bd9a815b1d20798809780fb63d9", "size": 5693, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "common/parameter/parameter_preparer.cpp", "max_stars_repo_name": "bark-simulator/planner-miqp", "max_stars_repo_head_hexsha": "aef044d03febadeb62c9634eed9830133d4c8b7b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-12-23T08:52:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T21:33:02.000Z", "max_issues_repo_path": "common/parameter/parameter_preparer.cpp", "max_issues_repo_name": "bark-simulator/planner-miqp", "max_issues_repo_head_hexsha": "aef044d03febadeb62c9634eed9830133d4c8b7b", "max_issues_repo_licenses": ["MIT"], "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/parameter/parameter_preparer.cpp", "max_forks_repo_name": "bark-simulator/planner-miqp", "max_forks_repo_head_hexsha": "aef044d03febadeb62c9634eed9830133d4c8b7b", "max_forks_repo_licenses": ["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.7278911565, "max_line_length": 80, "alphanum_fraction": 0.7191287546, "num_tokens": 1513, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4625402018862748}}
{"text": "#ifndef NONRIGIDREGISTRATION_HPP\n#define NONRIGIDREGISTRATION_HPP\n\n#include <Eigen/Dense>\n#include <stdio.h>\n#include <math.h>\n#include <memory.h>\n#include <time.h>\n#include \"../global.hpp\"\n#include \"CorrespondenceFilter.hpp\"\n#include \"SymmetricCorrespondenceFilter.hpp\"\n#include \"InlierDetector.hpp\"\n#include \"ViscoElasticTransformer.hpp\"\n\ntypedef Eigen::VectorXf VecDynFloat;\ntypedef Eigen::Matrix< float, Eigen::Dynamic, registration::NUM_FEATURES> FeatureMat; //matrix Mx6 of type float\ntypedef Eigen::Matrix< int, Eigen::Dynamic, 3> FacesMat;\n\nnamespace registration{\n\nclass NonrigidRegistration\n{\n    /*\n    # GOAL\n    This class performs icp-based nonrigid registration between two oriented pointclouds.\n\n    # INPUTS\n    -ioFloatingFeatures\n    -inTargetFeatures\n    -inFloatingFlags\n    -inTargetFlags\n\n    # PARAMETERS\n    -numNeighbours(=3):\n    number of nearest neighbours\n\n    # OUTPUT\n    -outCorrespondingFeatures\n    -outCorrespondingFlags\n    */\n\n    public:\n\n        void set_input(FeatureMat * const ioFloatingFeatures,\n                       const FeatureMat * const inTargetFeatures,\n                       const FacesMat * const inFloatingFaces,\n                       const VecDynFloat * const inFloatingFlags,\n                       const VecDynFloat * const inTargetFlags);\n        void set_parameters(bool symmetric,\n                            size_t numNeighbours,\n                            float flagThreshold,\n                            bool equalizePushPull,\n                            float kappaa,\n                            bool inlierUseOrientation,\n                            size_t numIterations,\n                            float sigmaSmoothing,\n                            size_t numViscousIterationsStart,\n                            size_t numViscousIterationsEnd,\n                            size_t numElasticIterationsStart,\n                            size_t numElasticIterationsEnd);\n\n        void get_annealing_rates(float &viscousAnnealingRate,\n                                 float &elasticAnnealingRate){\n                                 viscousAnnealingRate = _viscousAnnealingRate;\n                                 elasticAnnealingRate = _elasticAnnealingRate;\n                                 }\n        void set_annealing_rates(const float viscousAnnealingRate,\n                                 const float elasticAnnealingRate){\n                                 _viscousAnnealingRate = viscousAnnealingRate;\n                                 _elasticAnnealingRate = elasticAnnealingRate;\n                                 }\n        void get_viscoelastic_iterations(float &numViscousIterations,\n                                         float &numElasticIterations){\n                                         numViscousIterations = _numViscousIterations;\n                                         numElasticIterations = _numElasticIterations;}\n\n        void update();\n\n    protected:\n\n    private:\n        //# Inputs/Outputs\n        FeatureMat * _ioFloatingFeatures = NULL;\n        const FeatureMat * _inTargetFeatures = NULL;\n        const FacesMat * _inFloatingFaces;\n        const VecDynFloat * _inFloatingFlags = NULL;\n        const VecDynFloat * _inTargetFlags = NULL;\n\n        //# User Parameters\n        //## Correspondences\n        bool _symmetric = true;\n        size_t _numNeighbours = 3;\n        float _flagThreshold = 0.9f;\n        bool _equalizePushPull = false;\n        //## Inliers\n        float _kappaa = 3.0;\n        bool _inlierUseOrientation = true;\n        //## Transformation\n        size_t _numIterations = 10;\n        float _sigmaSmoothing = 3.0;\n        size_t _numViscousIterationsStart = 100;\n        size_t _numViscousIterationsEnd = 1;\n        size_t _numElasticIterationsStart = 100;\n        size_t _numElasticIterationsEnd = 1;\n        size_t _numViscousIterations = 100;\n        size_t _numElasticIterations = 100;\n\n        //# Internal Data structures\n\n        //# Internal Parameters\n        //## Transformation\n        float _viscousAnnealingRate = exp(log(float(_numViscousIterationsEnd)/float(_numViscousIterationsStart))/_numIterations);\n        float _elasticAnnealingRate = exp(log(float(_numElasticIterationsEnd)/float(_numElasticIterationsStart))/_numIterations);\n\n        //# Internal functions\n};\n\n}//namespace registration\n\n#endif // NONRIGIDREGISTRATION_HPP\n", "meta": {"hexsha": "d6923c30ea51bc0fdb0f03a0bc630a9314b4cf11", "size": 4358, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/NonrigidRegistration.hpp", "max_stars_repo_name": "brisyramshere/meshmonk", "max_stars_repo_head_hexsha": "a0a7cf79902541cf9c800d83a4d4f14fcd756f6f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 53.0, "max_stars_repo_stars_event_min_datetime": "2017-02-03T14:59:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T05:40:58.000Z", "max_issues_repo_path": "src/NonrigidRegistration.hpp", "max_issues_repo_name": "brisyramshere/meshmonk", "max_issues_repo_head_hexsha": "a0a7cf79902541cf9c800d83a4d4f14fcd756f6f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 16.0, "max_issues_repo_issues_event_min_datetime": "2018-07-16T10:34:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-18T04:37:12.000Z", "max_forks_repo_path": "src/NonrigidRegistration.hpp", "max_forks_repo_name": "brisyramshere/meshmonk", "max_forks_repo_head_hexsha": "a0a7cf79902541cf9c800d83a4d4f14fcd756f6f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 23.0, "max_forks_repo_forks_event_min_datetime": "2018-07-05T14:59:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T07:01:47.000Z", "avg_line_length": 36.0165289256, "max_line_length": 129, "alphanum_fraction": 0.6046351537, "num_tokens": 906, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4625402018862748}}
{"text": "#include \"MaximumLikelihood.h\"\n#include \"../Ensemble.h\"\n#include \"../Parameters.h\"\n#include \"../Probabilistic.h\"\n#include \"../Obs.h\"\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/vector_proxy.hpp>\n#include <boost/numeric/ublas/triangular.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\nEstimatorMaximumLikelihood::EstimatorMaximumLikelihood(const Options& iOptions, const Data& iData, const Probabilistic& iScheme) :\n      EstimatorProbabilistic(iOptions, iData, iScheme),\n      mForceIdentityMatrix(false) {\n   //! Should the covariance matrix for finding the minimum be forced to be an  identity matrix?\n   iOptions.getValue(\"forceIdentityMatrix\", mForceIdentityMatrix);\n   iOptions.check();\n}\nvoid EstimatorMaximumLikelihood::update(const std::vector<Ensemble>& iEnsemble,\n      const std::vector<Obs>& iObs, \n      Parameters& iParameters) const {\n\n   // Set up coefficients\n   // Set up D2S\n   int N = getNumCoefficients(iParameters);\n   boost::numeric::ublas::matrix<float> D2S(N,N);\n   boost::numeric::ublas::matrix<float> accumD2S(N,N);\n   int Istart = N;\n   for(int k = 0; k < N*N; k++) {\n      int i = k % N;\n      int j = floor(k/N);\n      D2S(i,j) = iParameters[Istart + k];\n      accumD2S(i,j) = 0;\n   }\n   boost::numeric::ublas::matrix<float> Rinv(N,N);\n   bool status = getInverse(D2S, Rinv);\n   assert(status);\n   //std::cout << \"D2S[0] = \" << D2S(0,0) << \" Inverse = \" << Rinv(0,0) << std::endl;\n\n   // Initialize new parameters\n   std::vector<float> accumCoeff;\n   accumCoeff.resize(N);\n\n   for(int i = 0; i < N; i++) {\n      accumCoeff[i] = 0;\n   }\n   int numUpdates = 0;\n\n   for(int t = 0 ; t < (int) iObs.size(); t++) {\n      float obs = iObs[t].getValue();\n      Ensemble ens = iEnsemble[t];\n      if(Global::isValid(obs)) {\n         Parameters coeffs;\n         getCoefficients(iParameters, coeffs);\n\n         std::vector<float> H;\n         bool status = getH(obs, ens, coeffs, H);\n         if(status) {\n            //std::cout << \"H = \" << H[0] << std::endl;\n            for(int i = 0; i < N; i++) {\n               for(int j = 0; j < N; j++) {\n                  accumD2S(i,j) += H[i]*H[j];\n                  //if(H[j] > 200)\n                  //std::cout << \"H[j] = \" << H[j] << \" Rinv(i,j)= \" << Rinv(i,j)  << std::endl;\n                  accumCoeff[i] += H[j]*Rinv(i,j);\n               }\n            }\n            numUpdates++;\n         }\n      }\n   }\n\n   if(numUpdates > 0) {\n      // Update coefficients Pinson (eq 19)\n      for(int i = 0; i < N; i++) {\n         //std::cout << \"Old parameter = \" << iParameters[i];\n         iParameters[i] = iParameters[i] + 1/mEfold * accumCoeff[i]/numUpdates;\n         //std::cout << \" new = \" << iParameters[i] << std::endl;\n      }\n\n      // Update D2S Pinson (eq 20)\n      for(int i = 0; i < N; i++) {\n         for(int j = 0; j < N; j++) {\n            int index = Istart + i + N*j;\n            //std::cout << \"Old est parameter = \" << iParameters[index];\n            if(mForceIdentityMatrix)\n               iParameters[index] = (i==j) ? 1 : 0; \n            else\n               iParameters[index] = getLambda() * D2S(i,j) + 1/mEfold * accumD2S(i,j)/numUpdates;\n            //std::cout << \" new = \" << iParameters[index] << std::endl;\n         }\n      }\n   }\n   else {\n      //std::cout << \"Can't update\" << std::endl;\n   }\n\n}\n\nvoid EstimatorMaximumLikelihood::getDefaultParameters(const Parameters& iSchemeParameters,\n      Parameters& iParameters) const {\n   int N = iSchemeParameters.size();\n   std::vector<float> param;\n   for(int i = 0; i < N; i++) {\n      for(int j = 0; j < N; j++) {\n         param.push_back(i == j);\n      }\n   }\n   iParameters.setAllParameters(param);\n}\nint EstimatorMaximumLikelihood::getIndex(int i, int j, int iSize) {\n   return i*iSize + j;\n}\nfloat EstimatorMaximumLikelihood::getLambda() const {\n   return 1 - 1/mEfold;\n}\n\n// TODO: Pass only coefficients in here\nbool EstimatorMaximumLikelihood::getH(float iObs, const Ensemble& iEnsemble, const Parameters& iCoeffs, std::vector<float>& iH) const {\n   int N = iCoeffs.size();\n\n   iH.clear();\n   iH.resize(N);\n\n   std::vector<float> gradL;\n   bool status = getGradL(iObs, iEnsemble, iCoeffs, gradL);\n   if(!status) {\n      return false;\n   }\n   //std::cout << \"Grad = \" << gradL[0] << std::endl;\n   assert((int) gradL.size() == N);\n\n   float L = mScheme.getLikelihood(iObs, iEnsemble, iCoeffs);\n   if(L == 0) {\n      std::cout << \"MaximumLikelihood: Obs = \" << iObs << std::endl;\n   }\n   assert(L > 0);\n   if(!Global::isValid(L)) {\n      return false;\n   }\n   for(int i = 0; i < N; i++) {\n      float value = gradL[i]/L;\n      iH[i] = value;\n   }\n   return true;\n}\n\nbool EstimatorMaximumLikelihood::getGradL(float iObs, const Ensemble& iEnsemble, const Parameters& iCoeffs, std::vector<float>& iGradL) const {\n   int N = iCoeffs.size();\n\n   iGradL.clear();\n   iGradL.resize(N);\n\n   float dx = 0.001;\n   float L0 = mScheme.getLikelihood(iObs, iEnsemble, iCoeffs);\n   if(!Global::isValid(L0))\n      return false;\n   for(int i = 0; i < N; i++) {\n      // Perturb current parameter\n      Parameters par = iCoeffs;\n      par[i] += dx;\n\n      // Compute likelihood derivative\n      float currL = mScheme.getLikelihood(iObs, iEnsemble, par);\n      if(!Global::isValid(currL))\n         return false;\n      float dL = currL - L0;\n      iGradL[i] = dL/dx;\n   }\n   return true;\n}\n\nbool EstimatorMaximumLikelihood::getInverse(boost::numeric::ublas::matrix<float> iMatrix, boost::numeric::ublas::matrix<float>& iInverse) {\n   // Taken from https://gist.github.com/2464434\n   using namespace boost::numeric::ublas;\n   typedef permutation_matrix<std::size_t> pmatrix;\n   // create a working copy of the input\n   matrix<float> A(iMatrix);\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   iInverse.assign(identity_matrix<float>(A.size1()));\n\n   // backsubstitute to get the inverse\n   lu_substitute(A, pm, iInverse);\n\n   return true;\n}\n\nint EstimatorMaximumLikelihood::getNumCoefficients(const Parameters& iParameters) const {\n   int N = (-1 + pow(1 + 4*iParameters.size(),0.5))/2;\n   assert(N + N*N == iParameters.size());\n   return N;\n}\n", "meta": {"hexsha": "1bad5a2757307055776bf240ea0a1901e429b293", "size": 6305, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Estimators/MaximumLikelihood.cpp", "max_stars_repo_name": "dsiuta/Comps", "max_stars_repo_head_hexsha": "2071279280d33946e975de25deedc60f1881eda0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Estimators/MaximumLikelihood.cpp", "max_issues_repo_name": "dsiuta/Comps", "max_issues_repo_head_hexsha": "2071279280d33946e975de25deedc60f1881eda0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Estimators/MaximumLikelihood.cpp", "max_forks_repo_name": "dsiuta/Comps", "max_forks_repo_head_hexsha": "2071279280d33946e975de25deedc60f1881eda0", "max_forks_repo_licenses": ["BSD-3-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.525, "max_line_length": 143, "alphanum_fraction": 0.5911181602, "num_tokens": 1837, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4625402018862748}}
{"text": "#include <boost/random/beta_distribution.hpp>\n", "meta": {"hexsha": "ba32b17d631b399a6579539f367bdd5012574aa6", "size": 46, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_random_beta_distribution.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_random_beta_distribution.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_random_beta_distribution.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 23.0, "max_line_length": 45, "alphanum_fraction": 0.8260869565, "num_tokens": 9, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7905303186696746, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.46254020188627476}}
{"text": "#include <boost/random/gamma_distribution.hpp>\n", "meta": {"hexsha": "5872d80e5b9d6698777ebc33309f0662dcbc6516", "size": 47, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_random_gamma_distribution.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_random_gamma_distribution.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_random_gamma_distribution.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 23.5, "max_line_length": 46, "alphanum_fraction": 0.829787234, "num_tokens": 9, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.46254019611129105}}
{"text": "#include <boost/math/special_functions/polygamma.hpp>\n", "meta": {"hexsha": "6f81c0b8ef9b21d49e2fc78e958e15d3abfc7119", "size": 54, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_special_functions_polygamma.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_special_functions_polygamma.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_special_functions_polygamma.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 27.0, "max_line_length": 53, "alphanum_fraction": 0.8333333333, "num_tokens": 12, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905302989295534, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.46254019033630706}}
{"text": "#ifndef PLANE_H\n#define PLANE_H\n\n//PointCloud#include <pcl/ModelCoefficients.h>\n#include <pcl/io/pcd_io.h>\n#include <pcl/point_types.h>\n#include <pcl/sample_consensus/method_types.h>\n#include <pcl/sample_consensus/model_types.h>\n#include <pcl/filters/passthrough.h>\n#include <pcl/filters/project_inliers.h>\n#include <pcl/segmentation/sac_segmentation.h>\n#include <pcl/segmentation/extract_clusters.h>\n#include <pcl/surface/concave_hull.h>\n\n\n#include <Eigen/Core>\n#include <boost/shared_ptr.hpp>\n#include \"sophus/sim3.hpp\"\n#include \"typedef.h\"\n\n\n\n// ------------------------- Plane -------------------------\nclass Plane {\n    \nprivate:\n    typedef Eigen::Hyperplane<float, 3> EigenPlane;\n\npublic:\n    typedef boost::shared_ptr<Plane> Ptr;\n\n    Plane(std::vector<float> coefficients) \n    {\n        if (coefficients.size() != 4) {\n            ROS_ERROR(\"Plane with wrong number of coefficients created\");\n        }\n        a_ = coefficients[0];\n        b_ = coefficients[1];\n        c_ = coefficients[2];\n        d_ = coefficients[3];\n    }\n\n    Eigen::VectorXf getCoefficients() \n    {\n        Eigen::VectorXf coeff(4);\n        coeff << a_ , b_ , c_ , d_;\n        return coeff;\n    }\n\n    void setCoefficients(const Eigen::VectorXf coefficients) \n    {\n        if (coefficients.size() != 4) {\n            return;\n        }\n        a_ = coefficients(0);\n        b_ = coefficients(1);\n        c_ = coefficients(2);\n        d_ = coefficients(3);\n    }\n\n    Eigen::Quaternionf getRotation() \n    {\n        Eigen::Vector3f normal;\n        Eigen::Vector3f point;\n        calculateNormalForm(point, normal);\n        return Eigen::Quaternionf::FromTwoVectors(Eigen::Vector3f(1,0,0), normal);\n    }\n\n    void transform(const Eigen::Matrix4f &transform) \n    {\n        Eigen::Vector3f normal;\n        Eigen::Vector3f point;\n        calculateNormalForm(point, normal);\n        Eigen::Vector4f normal_hom(normal[0], normal[1], normal[2], 0);\n        Eigen::Vector4f point_hom(point[0], point[1], point[2], 1);\n        normal_hom = transform * normal_hom;\n        point_hom = transform * point_hom;\n        for (int i = 0; i < 3; i++) {\n            normal[i] = normal_hom[i];\n            point[i] = point_hom[i] / point_hom[3];\n        }\n        calculateParameterForm(point, normal);\n    }\n\n    static void transformPlane(const Eigen::Matrix4f &transform, Eigen::Vector3f &point_inout, Eigen::Vector3f &normal_inout) \n    {\n        Eigen::Vector4f normal_hom(normal_inout[0], normal_inout[1], normal_inout[2], 0);\n        Eigen::Vector4f point_hom(point_inout[0], point_inout[1], point_inout[2], 1);\n        normal_hom = transform * normal_hom;\n        point_hom = transform * point_hom;\n        for (int i = 0; i < 3; i++) {\n            normal_inout[i] = normal_hom[i];\n            point_inout[i] = point_hom[i] / point_hom[3];\n        }\n    }\n    \n    // returns closest point to point_in on the plane\n    Eigen::Vector3f rayIntersection(Eigen::Vector3f point_in, Eigen::Vector3f direction_in) \n    {\n        direction_in.normalize();\n        Eigen::Vector3f planeNormal;\n        Eigen::Vector3f planePoint;\n        calculateNormalForm(planePoint, planeNormal);\n        EigenPlane plane = EigenPlane(planeNormal, planePoint);\n        Eigen::ParametrizedLine<float,3> pline = Eigen::ParametrizedLine<float,3>(point_in, direction_in);\n        Eigen::Vector3f intersection = pline.intersectionPoint(plane);\n        return intersection;\n    }\n\n    void calculateNormalForm(Eigen::Vector3f &point_out, Eigen::Vector3f &normal_out) \n    {\n        normal_out = Eigen::Vector3f(a_, b_, c_);\n        float length = normal_out.norm();\n        normal_out = normal_out / length;\n        point_out = -d_/length * normal_out;\n\n        // Checking the direction of the normal\n        int scalerProduct = point_out.dot(normal_out);\n        if(scalerProduct < 0){\n            normal_out = -normal_out;\n        }\n    }\n\n\nprivate:\n\n    void calculateParameterForm(const Eigen::Vector3f &point, const Eigen::Vector3f &normal) {\n        a_ = normal[0];\n        b_ = normal[1];\n        c_ = normal[2];\n\n        d_ = -normal.dot(point);\n    }\n\n\n// Member variables ----------\nprivate:\n    float a_, b_, c_, d_;\n    \n    \n\n\n};\n\n\n#endif //PLANE_H\n", "meta": {"hexsha": "b3e3361d17c5725064a920b993f202b0c3b6a615", "size": 4211, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "te_surface_detection/include/plane.hpp", "max_stars_repo_name": "Tacoma/GKM", "max_stars_repo_head_hexsha": "82e623e05d4b456b4808e4031cc1bd2da2d10681", "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": "te_surface_detection/include/plane.hpp", "max_issues_repo_name": "Tacoma/GKM", "max_issues_repo_head_hexsha": "82e623e05d4b456b4808e4031cc1bd2da2d10681", "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": "te_surface_detection/include/plane.hpp", "max_forks_repo_name": "Tacoma/GKM", "max_forks_repo_head_hexsha": "82e623e05d4b456b4808e4031cc1bd2da2d10681", "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.6462585034, "max_line_length": 126, "alphanum_fraction": 0.6148183329, "num_tokens": 1077, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.46251851829624263}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// statistics::model::functional::log_posterior_evaluator.hpp                //\n//                                                                           //\n//  Copyright 2009 Erwann Rogard. Distributed under the Boost                //\n//  Software License, Version 1.0. (See accompanying file                    //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)         //\n///////////////////////////////////////////////////////////////////////////////\n#ifndef BOOST_STATISTICS_MODEL_FUNCTIONAL_LOG_POSTERIOR_EVALUATOR_HPP_ER_2009\n#define BOOST_STATISTICS_MODEL_FUNCTIONAL_LOG_POSTERIOR_EVALUATOR_HPP_ER_2009\n#include <boost/type_traits.hpp>\n#include <boost/call_traits.hpp>\n#include <boost/operators.hpp>\n#include <boost/binary_op/algorithm/for_each.hpp>\n#include <boost/joint_dist/unscope/log_unnormalized_pdf.hpp>\n#include <boost/scalar_dist/unscope/log_unnormalized_pdf.hpp>\n#include <boost/statistics/model/wrap/aggregate/prior_model_dataset.hpp>\n#include <boost/statistics/model/functional/log_likelihood_evaluator.hpp>\n\nnamespace boost{ \nnamespace statistics{\nnamespace model{  \n\n    // Augments algorithm::log_likehood with a prior of type D\n    //\n    // Requirements:\n    // Let d denote an instance of D and p a parameter, then\n    // log_unnormalized_pdf(p_dist,p) must return an object of type T    \n    template<typename T,typename D,typename M,typename Rx,typename Ry>\n    class log_posterior_evaluator : log_likelihood_evaluator<T,M,Rx,Ry>{\n        typedef log_likelihood_evaluator<T,M,Rx,Ry> super_;\n        public:\n        typedef prior_model_dataset_<D,M,Rx,Ry> prior_model_dataset_type;\n        typedef typename prior_model_dataset_type::prior_type prior_type;\n        typedef typename super_::result_type result_type;\n        \n        // Constructor\n        log_posterior_evaluator();\n        log_posterior_evaluator(const prior_model_dataset_type&);\n        log_posterior_evaluator(const log_posterior_evaluator&);\n        log_posterior_evaluator& operator=(const log_posterior_evaluator&);\n\n        // Evaluate\n        template<typename P> \n        result_type operator()(const P& p)const;\n\n        // Access\n        const prior_model_dataset_type& prior_model_dataset()const;\n        \n        private:\n        prior_model_dataset_type pmd_;\n    };\n\n    // Implementation //\n    \n    // Construction\n    template<typename T,typename D,typename M,typename Rx,typename Ry>\n    log_posterior_evaluator<T,D,M,Rx,Ry>::log_posterior_evaluator():\n    super_(){}\n    \n    template<typename T,typename D,typename M,typename Rx,typename Ry>\n    log_posterior_evaluator<T,D,M,Rx,Ry>::log_posterior_evaluator(\n        const prior_model_dataset_type& pmd\n    ):super_(pmd),pmd_(pmd){}\n\n    template<typename T,typename D,typename M,typename Rx,typename Ry>\n    log_posterior_evaluator<T,D,M,Rx,Ry>::log_posterior_evaluator(\n        const log_posterior_evaluator& that\n    ):super_(that),pmd_(that.pmd_){}\n\n    template<typename T,typename D,typename M,typename Rx,typename Ry>\n    log_posterior_evaluator<T,D,M,Rx,Ry>&\n    log_posterior_evaluator<T,D,M,Rx,Ry>::operator=(\n        const log_posterior_evaluator& that\n    ){\n        if(&that!=this){\n            super_::operator=(that);\n            pmd_ = (that.pmd_);\n        }\n        return (*this);\n    }\n    \n    // Evaluate\n    template<typename T,typename D,typename M,typename Rx,typename Ry>\n    template<typename P>\n    typename log_posterior_evaluator<T,D,M,Rx,Ry>::result_type \n    log_posterior_evaluator<T,D,M,Rx,Ry>::operator()(const P& p)const{\n        const super_& super = static_cast<const super_&>(*this);\n        result_type res =  super(p);\n        res += log_unnormalized_pdf(\n            prior_model_dataset().prior(),\n            p\n        );\n        return res;\n    }\n\n    // Access\n    template<typename T,typename D,typename M,typename Rx,typename Ry>\n    const \n        typename \n            log_posterior_evaluator<T,D,M,Rx,Ry>::prior_model_dataset_type& \n    log_posterior_evaluator<T,D,M,Rx,Ry>::prior_model_dataset()const{\n        return (this->pmd_);\n    }\n\n}// model\n}// statistics\n}// boost\n\n#endif", "meta": {"hexsha": "df732dfe770c84b801398f13b25c02c13ab1bb17", "size": 4199, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "model copy/boost/statistics/model/functional/log_posterior_evaluator.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": "model copy/boost/statistics/model/functional/log_posterior_evaluator.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": "model copy/boost/statistics/model/functional/log_posterior_evaluator.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": 38.5229357798, "max_line_length": 79, "alphanum_fraction": 0.6522981662, "num_tokens": 953, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.46251851829624263}}
{"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_CONSTANT_FACT_6_HPP_INCLUDED\n#define BOOST_SIMD_CONSTANT_FACT_6_HPP_INCLUDED\n\n/*!\n  @ingroup group-constant\n  @defgroup constant-Fact_6 Fact_6 (function template)\n\n  Generates the @c 6! constant\n\n  @headerref{<boost/simd/constant/fact_6.hpp>}\n\n  @par Description\n\n  1.  @code\n      template<typename T> T Fact_6();\n      @endcode\n\n  2.  @code\n      template<typename T> T Fact_6( boost::simd::as_<T> const& target );\n      @endcode\n\n  Generates a value of type @c T that evaluates to 6!.\n\n  @par Parameters\n\n  | Name                | Description                                                         |\n  |--------------------:|:--------------------------------------------------------------------|\n  | **target**          | a [placeholder](@ref type-as) value encapsulating the constant type |\n\n  @par Return Value\n  A value of type @c T that evaluates to @c T(720).\n\n  @par Requirements\n  - **T** models Value\n**/\n\n#include <boost/simd/constant/scalar/fact_6.hpp>\n#include <boost/simd/constant/simd/fact_6.hpp>\n\n#endif\n", "meta": {"hexsha": "550401ebb56b346cc3b4aeaef3becd417c343cca", "size": 1433, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/constant/fact_6.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/constant/fact_6.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/constant/fact_6.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": 28.0980392157, "max_line_length": 100, "alphanum_fraction": 0.517794836, "num_tokens": 320, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581049086031, "lm_q2_score": 0.5813030906443134, "lm_q1q2_score": 0.46251851547956835}}
{"text": "#ifndef HImprovePoisedness\n#define HImprovePoisedness\n\n#include \"ImprovePoisednessBaseClass.hpp\"\n#include \"BlackBoxData.hpp\"\n#include \"CholeskyFactorization.hpp\"\n#include \"VectorOperations.hpp\"\n#include \"QuadraticMinimization.hpp\"\n#include <Eigen/Dense>\n#include <vector>\n#include <math.h>\n\n//! Improve poisedness of interpolation nodes\nclass ImprovePoisedness : public ImprovePoisednessBaseClass,\n                          protected QuadraticMinimization {\n  private:\n    int dim;\n    int nb_nodes;\n    size_t max_nb_nodes;\n    double *delta;\n\n    //declare auxiliary variables for replace_node\n    double maxvalue, LK, norm_dbl;\n    //declare auxiliary variables for compute_poisedness_constant\n    double poisedness_constant_tmp1, poisedness_constant_tmp2;\n    double node_norm_scaling;\n    std::vector<double> q1, q2;\n    std::vector<double> basis_values;\n\n    std::vector<double> basis_gradient;\n    std::vector< std::vector<double> > basis_hessian;\n    //define auxiliary variables\n    Eigen::VectorXd tmp_node;\n    bool print_output;\n    int change_index;    \n    bool model_has_been_improved;\n    std::vector<double> lower_bound_constraints;\n    std::vector<double> upper_bound_constraints;\n    bool use_hard_box_constraints = false;\n    void compute_poisedness_constant ( int, std::vector<double>&, BlackBoxData& );\n  public:\n    //! Constructor\n    /*!\n     Set parameters required for the improvement of the poisedness of interploation nodes\n     \\param B basis for surrogate model\n     \\param poisedness_threshold threshold for poisedness constant\n     \\param m maximal number of interpolation nodes\n     \\param rad radius arround current best point of ball that contains well poised points\n     \\param verbose switch output on (verbose = 3) or off (verbose = 0)\n     \\see BlackBoxData\n    */\n    ImprovePoisedness ( BasisForSurrogateModelBaseClass&, double, int, double&, int, std::vector<double>, std::vector<double>, bool);\n    //! Destructor\n    ~ImprovePoisedness () { }\n    //! Find node to be replaced by better poised node\n    /*!\n     Finds a node to replace another interpolation node to improve poisedness\n     \\param reference_node index of node that is not replaced\n     \\param evaluations interpolation nodes, \\see BlackBoxData\n     \\param new_node new node to replace an existing interpolation node\n    */\n    int replace_node ( int, BlackBoxData&, std::vector<double> const& );\n    //! Improves poisedness of interpolation nodes\n    /*!\n     Improves poisedness of interpolation nodes by maximizing the absolute value of basis functions.\\n\n     Nodes to replace existing interpolation nodes are computed and appended to the list of nodes, \n     \\see BlackBoxData \\n\n     The index of nodes to reduce the poisedness value are indicated in evaluations \\see BlackBoxData \\n\n     \\param reference_node index of node that is not replaced\n     \\param evaluations structure containing interpolation nodes, \\see BlackBoxData\n    */\n    void improve_poisedness ( int, BlackBoxData& );\n};\n\n#endif\n", "meta": {"hexsha": "02fc7707ac356ef7136da714c75b08e3826e616c", "size": 3015, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ImprovePoisedness.hpp", "max_stars_repo_name": "snowpac/snowpac", "max_stars_repo_head_hexsha": "ff4c6a83e01fc4ef6a78cf9ff9bf9358f972b305", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-08-04T20:18:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-22T23:50:27.000Z", "max_issues_repo_path": "include/ImprovePoisedness.hpp", "max_issues_repo_name": "snowpac/snowpac", "max_issues_repo_head_hexsha": "ff4c6a83e01fc4ef6a78cf9ff9bf9358f972b305", "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/ImprovePoisedness.hpp", "max_forks_repo_name": "snowpac/snowpac", "max_forks_repo_head_hexsha": "ff4c6a83e01fc4ef6a78cf9ff9bf9358f972b305", "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.6710526316, "max_line_length": 133, "alphanum_fraction": 0.735986733, "num_tokens": 676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.5813030906443134, "lm_q1q2_score": 0.46251851266289384}}
{"text": "/**\n * \\file CachedSinusGeneratorFilter.cpp\n */\n\n#include \"CachedSinusGeneratorFilter.h\"\n\n#include <boost/math/constants/constants.hpp>\n\n#include <cmath>\n#include <cstdint>\n#include <cstring>\n\nnamespace ATK\n{\n  template<typename DataType_>\n  CachedSinusGeneratorFilter<DataType_>::CachedSinusGeneratorFilter(int periods, int seconds)\n  :Parent(0, 1), periods(periods), seconds(seconds)\n  {\n  }\n    \n  template<typename DataType_>\n  void CachedSinusGeneratorFilter<DataType_>::set_frequency(int periods, int seconds)\n  {\n    if(periods <= 0)\n    {\n      throw std::out_of_range(\"Periods must be strictly positive\");\n    }\n    this->periods = periods;\n    this->seconds = seconds;\n    setup();\n  }\n  \n  template<typename DataType_>\n  std::pair<int, int> CachedSinusGeneratorFilter<DataType_>::get_frequency() const\n  {\n    return std::make_pair(periods, seconds);\n  }\n\n  template<typename DataType_>\n  void CachedSinusGeneratorFilter<DataType_>::set_volume(DataType_ volume)\n  {\n    this->volume = volume;\n  }\n  \n  template<typename DataType_>\n  DataType_ CachedSinusGeneratorFilter<DataType_>::get_volume() const\n  {\n    return volume;\n  }\n  \n  template<typename DataType_>\n  void CachedSinusGeneratorFilter<DataType_>::set_offset(DataType_ offset)\n  {\n    this->offset = offset;\n  }\n  \n  template<typename DataType_>\n  DataType_ CachedSinusGeneratorFilter<DataType_>::get_offset() const\n  {\n    return offset;\n  }\n\n  template<typename DataType_>\n  void CachedSinusGeneratorFilter<DataType_>::setup()\n  {\n    indice = 0;\n    cache.resize(output_sampling_rate * seconds);\n    for(gsl::index i = 0; i < cache.size(); ++i)\n    {\n      cache[i] = static_cast<DataType>(std::sin(2 * boost::math::constants::pi<double>() * (i+1) * periods / seconds / output_sampling_rate));\n    }\n  }\n\n  template<typename DataType_>\n  void CachedSinusGeneratorFilter<DataType_>::process_impl(gsl::index size) const\n  {\n    DataType* ATK_RESTRICT output = outputs[0];\n    gsl::index processed = 0;\n    while (processed < size)\n    {\n      auto to_copy = std::min(size - processed, static_cast<gsl::index>(cache.size()) - indice);\n      memcpy(reinterpret_cast<void*>(output + processed), reinterpret_cast<const void*>(cache.data() + indice), to_copy * sizeof(DataType_));\n      indice += to_copy;\n      processed += to_copy;\n      if (indice >= cache.size())\n      {\n        indice = 0;\n      }\n    }\n    for (gsl::index i = 0; i < size; ++i)\n    {\n      output[i] = static_cast<DataType>(offset + volume * output[i]);\n    }\n  }\n\n#if ATK_ENABLE_INSTANTIATION\n  template class CachedSinusGeneratorFilter<std::int16_t>;\n  template class CachedSinusGeneratorFilter<std::int32_t>;\n  template class CachedSinusGeneratorFilter<int64_t>;\n  template class CachedSinusGeneratorFilter<float>;\n#endif\n  template class CachedSinusGeneratorFilter<double>;\n}\n", "meta": {"hexsha": "b05e7ed0434e8291ef2cc96ee91fd00fbc4534d7", "size": 2821, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ATK/Tools/CachedSinusGeneratorFilter.cpp", "max_stars_repo_name": "AudioTK/AudioTK", "max_stars_repo_head_hexsha": "dba42eea68534501efe74692b74edf4792cca231", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2021-02-04T10:47:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T03:45:00.000Z", "max_issues_repo_path": "ATK/Tools/CachedSinusGeneratorFilter.cpp", "max_issues_repo_name": "AudioTK/AudioTK", "max_issues_repo_head_hexsha": "dba42eea68534501efe74692b74edf4792cca231", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-02-01T15:45:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-13T19:39:05.000Z", "max_forks_repo_path": "ATK/Tools/CachedSinusGeneratorFilter.cpp", "max_forks_repo_name": "AudioTK/AudioTK", "max_forks_repo_head_hexsha": "dba42eea68534501efe74692b74edf4792cca231", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-04-12T03:28:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-17T00:47:11.000Z", "avg_line_length": 27.125, "max_line_length": 142, "alphanum_fraction": 0.6958525346, "num_tokens": 700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4625185126628938}}
{"text": "// ---------------------------------------------------------------------\n//\n// Copyright (c) 2015 - 2022 by the IBAMR developers\n// All rights reserved.\n//\n// This file is part of IBAMR.\n//\n// IBAMR is free software and is distributed under the 3-clause BSD\n// license. The full text of the license can be found in the file\n// COPYRIGHT at the top level directory of IBAMR.\n//\n// ---------------------------------------------------------------------\n\n/////////////////////////////// INCLUDES /////////////////////////////////////\n\n#include \"ibamr/CIBStrategy.h\"\n#include \"ibamr/DirectMobilitySolver.h\"\n#include \"ibamr/StokesSpecifications.h\"\n#include \"ibamr/ibamr_enums.h\"\n#include \"ibamr/ibamr_utilities.h\"\n\n#include \"ibtk/IBTK_MPI.h\"\n#include \"ibtk/PETScSAMRAIVectorReal.h\"\n#include \"ibtk/ibtk_utilities.h\"\n\n#include \"CartesianGridGeometry.h\"\n#include \"IntVector.h\"\n#include \"PatchHierarchy.h\"\n#include \"PatchLevel.h\"\n#include \"SAMRAIVectorReal.h\"\n#include \"tbox/Database.h\"\n#include \"tbox/MathUtilities.h\"\n#include \"tbox/PIO.h\"\n#include \"tbox/Pointer.h\"\n#include \"tbox/Timer.h\"\n#include \"tbox/TimerManager.h\"\n#include \"tbox/Utilities.h\"\n\n#include \"petscmat.h\"\n#include \"petscvec.h\"\n#include \"petscviewer.h\"\n#include \"petscviewertypes.h\"\n\n#include <Eigen/Cholesky>\n#include <Eigen/Eigenvalues>\n#include <Eigen/LU>\n\n#include <algorithm>\n#include <cmath>\n#include <map>\n#include <ostream>\n#include <string>\n#include <utility>\n#include <vector>\n\n#include \"ibamr/app_namespaces.h\" // IWYU pragma: keep\n\nnamespace IBAMR\n{\n/////////////////////////////// STATIC ///////////////////////////////////////\n\nnamespace\n{\n// Timers.\nstatic Timer* t_solve_system;\nstatic Timer* t_solve_body_system;\nstatic Timer* t_initialize_solver_state;\nstatic Timer* t_deallocate_solver_state;\n} // namespace\n\n////////////////////////////// PUBLIC ////////////////////////////////////////\n\nDirectMobilitySolver::DirectMobilitySolver(std::string object_name,\n                                           Pointer<Database> input_db,\n                                           Pointer<CIBStrategy> cib_strategy)\n    : d_object_name(std::move(object_name)), d_cib_strategy(cib_strategy)\n{\n    // Get from input\n    if (input_db) getFromInput(input_db);\n\n    IBAMR_DO_ONCE(t_solve_system = TimerManager::getManager()->getTimer(\"IBAMR::DirectMobilitySolver::solveSystem()\");\n                  t_solve_body_system =\n                      TimerManager::getManager()->getTimer(\"IBAMR::DirectMobilitySolver::solveBodySystem()\");\n                  t_initialize_solver_state =\n                      TimerManager::getManager()->getTimer(\"IBAMR::DirectMobilitySolver::initializeSolverState()\");\n                  t_deallocate_solver_state =\n                      TimerManager::getManager()->getTimer(\"IBAMR::DirectMobilitySolver::deallocateSolverState()\"););\n\n    return;\n} // DirectMobilitySolver\n\nDirectMobilitySolver::~DirectMobilitySolver()\n{\n    for (const auto& petsc_mat_pair : d_petsc_mat_map)\n    {\n        const std::string& mat_name = petsc_mat_pair.first;\n        Mat& mobility_mat = d_petsc_mat_map[mat_name].first;\n        Mat& body_mobility_mat = d_petsc_mat_map[mat_name].second;\n        MatDestroy(&mobility_mat);\n        MatDestroy(&body_mobility_mat);\n    }\n\n    for (const auto& mat_pair : d_petsc_geometric_mat_map)\n    {\n        Mat& geometric_mat = d_petsc_geometric_mat_map[mat_pair.first];\n        MatDestroy(&geometric_mat);\n    }\n\n    d_is_initialized = false;\n\n    return;\n} // ~DirectMobilitySolver\n\nvoid\nDirectMobilitySolver::registerMobilityMat(const std::string& mat_name,\n                                          const unsigned prototype_struct_id,\n                                          MobilityMatrixType mat_type,\n                                          std::pair<MobilityMatrixInverseType, MobilityMatrixInverseType> inv_type,\n                                          const int managing_proc,\n                                          const std::string& filename,\n                                          std::pair<double, double> scale)\n{\n    registerMobilityMat(mat_name,\n                        std::vector<unsigned int>(1, prototype_struct_id),\n                        mat_type,\n                        inv_type,\n                        managing_proc,\n                        filename,\n                        scale);\n\n    return;\n} // registerMobilityMat\n\nvoid\nDirectMobilitySolver::registerMobilityMat(const std::string& mat_name,\n                                          const std::vector<unsigned>& prototype_struct_ids,\n                                          MobilityMatrixType mat_type,\n                                          std::pair<MobilityMatrixInverseType, MobilityMatrixInverseType> inv_type,\n                                          const int managing_proc,\n                                          const std::string& filename,\n                                          std::pair<double, double> scale)\n{\n#if !defined(NDEBUG)\n    TBOX_ASSERT(!mat_name.empty());\n    for (const auto& prototype_struct_id : prototype_struct_ids)\n    {\n        TBOX_ASSERT(prototype_struct_id < d_cib_strategy->getNumberOfRigidStructures());\n    }\n    TBOX_ASSERT(d_mat_map.find(mat_name) == d_mat_map.end());\n    TBOX_ASSERT(mat_type != UNKNOWN_MOBILITY_MATRIX_TYPE);\n    TBOX_ASSERT(inv_type.first != UNKNOWN_MOBILITY_MATRIX_INVERSE_TYPE);\n    TBOX_ASSERT(inv_type.second != UNKNOWN_MOBILITY_MATRIX_INVERSE_TYPE);\n#endif\n\n    unsigned int num_nodes = 0;\n    for (const auto& prototype_struct_id : prototype_struct_ids)\n    {\n        num_nodes += d_cib_strategy->getNumberOfNodes(prototype_struct_id);\n    }\n\n    // Fill-in various maps.\n    d_mat_prototype_id_map[mat_name] = prototype_struct_ids;\n    d_mat_proc_map[mat_name] = managing_proc;\n    d_mat_nodes_map[mat_name] = num_nodes;\n    d_mat_parts_map[mat_name] = static_cast<unsigned>(prototype_struct_ids.size());\n    d_mat_type_map[mat_name] = mat_type;\n    d_mat_inv_type_map[mat_name] = inv_type;\n    d_mat_filename_map[mat_name] = filename;\n    d_mat_scale_map[mat_name] = scale;\n    d_mat_map[mat_name] = { {}, {} };\n    d_geometric_mat_map[mat_name] = {};\n    d_ipiv_map[mat_name] = { {}, {} };\n    d_petsc_mat_map[mat_name] = { nullptr, nullptr };\n    d_petsc_geometric_mat_map[mat_name] = nullptr;\n\n    // Allocate the actual matrices.\n    const int mobility_mat_size = num_nodes * NDIM;\n    const int body_mobility_mat_size = d_mat_parts_map[mat_name] * s_max_free_dofs;\n    const int rank = IBTK_MPI::getRank();\n\n    if (rank == managing_proc)\n    {\n        d_mat_map[mat_name].first.resize(mobility_mat_size * mobility_mat_size);\n        MatCreateSeqDense(PETSC_COMM_SELF,\n                          mobility_mat_size,\n                          mobility_mat_size,\n                          d_mat_map[mat_name].first.data(),\n                          &d_petsc_mat_map[mat_name].first);\n\n        d_mat_map[mat_name].second.resize(body_mobility_mat_size * body_mobility_mat_size);\n        MatCreateSeqDense(PETSC_COMM_SELF,\n                          body_mobility_mat_size,\n                          body_mobility_mat_size,\n                          d_mat_map[mat_name].second.data(),\n                          &d_petsc_mat_map[mat_name].second);\n\n        d_geometric_mat_map[mat_name].resize(mobility_mat_size * body_mobility_mat_size);\n        MatCreateSeqDense(PETSC_COMM_SELF,\n                          mobility_mat_size,\n                          body_mobility_mat_size,\n                          d_geometric_mat_map[mat_name].data(),\n                          &d_petsc_geometric_mat_map[mat_name]);\n\n        if (d_mat_inv_type_map[mat_name].first == LAPACK_LU)\n        {\n            d_ipiv_map[mat_name].first.resize(mobility_mat_size);\n        }\n        if (d_mat_inv_type_map[mat_name].second == LAPACK_LU)\n        {\n            d_ipiv_map[mat_name].second.resize(body_mobility_mat_size);\n        }\n    }\n\n    return;\n} // registerMobilityMat\n\nvoid\nDirectMobilitySolver::registerStructIDsWithMobilityMat(const std::string& mat_name,\n                                                       const std::vector<std::vector<unsigned> >& struct_ids)\n{\n#if !defined(NDEBUG)\n    TBOX_ASSERT(d_mat_map.find(mat_name) != d_mat_map.end());\n    for (const auto& struct_id : struct_ids)\n    {\n        TBOX_ASSERT(struct_id.size() == d_mat_prototype_id_map[mat_name].size());\n        unsigned num_nodes = 0;\n        for (const auto& id : struct_id)\n        {\n            TBOX_ASSERT(id < d_cib_strategy->getNumberOfRigidStructures());\n\n            num_nodes += d_cib_strategy->getNumberOfNodes(id);\n        }\n        TBOX_ASSERT(num_nodes == d_mat_nodes_map[mat_name]);\n    }\n#endif\n\n    d_mat_actual_id_map[mat_name] = struct_ids;\n\n    return;\n} // registerStructIDsWithMobilityMat\n\nvoid\nDirectMobilitySolver::setStokesSpecifications(const StokesSpecifications& stokes_spec)\n{\n    d_rho = stokes_spec.getRho();\n    d_mu = stokes_spec.getMu();\n\n    return;\n} // setStokesSpecifications\n\nvoid\nDirectMobilitySolver::setSolutionTime(const double solution_time)\n{\n    d_solution_time = solution_time;\n\n    return;\n} // setSolutionTime\n\nvoid\nDirectMobilitySolver::setTimeInterval(double current_time, double new_time)\n{\n    d_current_time = current_time;\n    d_new_time = new_time;\n\n    return;\n} // setTimeInterval\n\nbool\nDirectMobilitySolver::solveSystem(Vec x, Vec b)\n{\n    IBAMR_TIMER_START(t_solve_system);\n\n    // Initialize the solver, when necessary.\n    const bool deallocate_after_solve = !d_is_initialized;\n    if (deallocate_after_solve) initializeSolverState(x, b);\n\n    const int rank = IBTK_MPI::getRank();\n    static const int data_depth = NDIM;\n\n    for (const auto& petsc_mat_pair : d_petsc_mat_map)\n    {\n        const std::string& mat_name = petsc_mat_pair.first;\n        Mat& mat = d_petsc_mat_map[mat_name].first;\n        const MobilityMatrixInverseType& inv_type = d_mat_inv_type_map[mat_name].first;\n        const std::vector<std::vector<unsigned> >& struct_ids = d_mat_actual_id_map[mat_name];\n        const int managing_proc = d_mat_proc_map[mat_name];\n        const int mat_size = d_mat_nodes_map[mat_name] * data_depth;\n        const int num_structs = static_cast<int>(struct_ids.size());\n\n        for (int k = 0; k < num_structs; ++k)\n        {\n            std::vector<double> rhs;\n            if (rank == managing_proc) rhs.resize(mat_size);\n            d_cib_strategy->copyVecToArray(b, rhs.data(), struct_ids[k], data_depth, managing_proc);\n            if (!d_recompute_mob_mat)\n            {\n                d_cib_strategy->rotateArray(rhs.data(),\n                                            struct_ids[k],\n                                            /*use_transpose*/ true,\n                                            managing_proc,\n                                            data_depth);\n            }\n            if (rank == managing_proc) computeSolution(mat, inv_type, d_ipiv_map[mat_name].first.data(), rhs.data());\n            if (!d_recompute_mob_mat)\n            {\n                d_cib_strategy->rotateArray(rhs.data(),\n                                            struct_ids[k],\n                                            /*use_transpose*/ false,\n                                            managing_proc,\n                                            data_depth);\n            }\n            d_cib_strategy->copyArrayToVec(x, rhs.data(), struct_ids[k], data_depth, managing_proc);\n        }\n    }\n\n    IBAMR_TIMER_STOP(t_solve_system);\n\n    return true;\n} // solveSystem\n\nbool\nDirectMobilitySolver::solveBodySystem(Vec x, Vec b)\n{\n    IBAMR_TIMER_START(t_solve_body_system);\n\n    // Initialize the solver, when necessary.\n    const bool deallocate_after_solve = !d_is_initialized;\n    if (deallocate_after_solve) initializeSolverState(x, b);\n\n    const int rank = IBTK_MPI::getRank();\n    static const int data_depth = s_max_free_dofs;\n\n    for (const auto& petsc_mat_pair : d_petsc_mat_map)\n    {\n        const std::string& mat_name = petsc_mat_pair.first;\n        Mat& mat = d_petsc_mat_map[mat_name].second;\n        const MobilityMatrixInverseType& inv_type = d_mat_inv_type_map[mat_name].second;\n        const std::vector<std::vector<unsigned> >& struct_ids = d_mat_actual_id_map[mat_name];\n        const int mat_size = d_mat_parts_map[mat_name] * data_depth;\n        const int managing_proc = d_mat_proc_map[mat_name];\n        const int num_structs = static_cast<int>(struct_ids.size());\n\n        for (int k = 0; k < num_structs; ++k)\n        {\n            std::vector<double> rhs;\n            if (rank == managing_proc) rhs.resize(mat_size);\n            d_cib_strategy->copyFreeDOFsVecToArray(b, rhs.data(), struct_ids[k], managing_proc);\n            if (!d_recompute_mob_mat)\n            {\n                d_cib_strategy->rotateArray(rhs.data(),\n                                            struct_ids[k],\n                                            /*use_transpose*/ true,\n                                            managing_proc,\n                                            data_depth);\n            }\n            if (rank == managing_proc) computeSolution(mat, inv_type, d_ipiv_map[mat_name].second.data(), rhs.data());\n            if (!d_recompute_mob_mat)\n            {\n                d_cib_strategy->rotateArray(rhs.data(),\n                                            struct_ids[k],\n                                            /*use_transpose*/ false,\n                                            managing_proc,\n                                            data_depth);\n            }\n            d_cib_strategy->copyFreeDOFsArrayToVec(x, rhs.data(), struct_ids[k], managing_proc);\n        }\n    }\n\n    IBAMR_TIMER_STOP(t_solve_body_system);\n\n    return true;\n} // solveBodySystem\n\nvoid\nDirectMobilitySolver::initializeSolverState(Vec x, Vec /*b*/)\n{\n    if (d_is_initialized) return;\n\n    IBAMR_TIMER_START(t_initialize_solver_state);\n\n    int rank = IBTK_MPI::getRank();\n    auto managed_mats = static_cast<unsigned>(d_mat_map.size());\n\n    static bool recreate_mobility_matrices = true;\n    static std::vector<bool> read_files(managed_mats, false);\n    bool initial_time = !d_recompute_mob_mat;\n\n    if (recreate_mobility_matrices)\n    {\n        // Get grid-info\n        Vec* vx;\n        VecNestGetSubVecs(x, nullptr, &vx);\n        Pointer<SAMRAIVectorReal<NDIM, double> > vx0;\n        IBTK::PETScSAMRAIVectorReal::getSAMRAIVectorRead(vx[0], &vx0);\n        Pointer<PatchHierarchy<NDIM> > patch_hierarchy = vx0->getPatchHierarchy();\n        const int finest_ln = patch_hierarchy->getFinestLevelNumber();\n        IBTK::PETScSAMRAIVectorReal::restoreSAMRAIVectorRead(vx[0], &vx0);\n        Pointer<PatchLevel<NDIM> > struct_patch_level = patch_hierarchy->getPatchLevel(finest_ln);\n        const IntVector<NDIM>& ratio = struct_patch_level->getRatio();\n        Pointer<CartesianGridGeometry<NDIM> > grid_geom = patch_hierarchy->getGridGeometry();\n        const double* dx0 = grid_geom->getDx();\n        const double* X_upper = grid_geom->getXUpper();\n        const double* X_lower = grid_geom->getXLower();\n        double domain_extents[NDIM], dx[NDIM];\n        for (int d = 0; d < NDIM; ++d)\n        {\n            dx[d] = dx0[d] / ratio(d);\n            domain_extents[d] = X_upper[d] - X_lower[d];\n        }\n\n        int file_counter = 0;\n        for (auto it = d_petsc_mat_map.begin(); it != d_petsc_mat_map.end(); ++it, ++file_counter)\n        {\n            const std::string& mat_name = it->first;\n            Mat& mobility_mat = d_petsc_mat_map[mat_name].first;\n            Mat& geometric_mat = d_petsc_geometric_mat_map[mat_name];\n            const MobilityMatrixType& mat_type = d_mat_type_map[mat_name];\n            const std::vector<unsigned>& struct_ids = d_mat_prototype_id_map[mat_name];\n            const std::pair<double, double>& scale = d_mat_scale_map[mat_name];\n            const int managing_proc = d_mat_proc_map[mat_name];\n\n            if (mat_type == READ_FROM_FILE && !read_files[file_counter])\n            {\n                // Get the matrix from file.\n                const std::string& filename = d_mat_filename_map[mat_name];\n                if (rank == managing_proc)\n                {\n                    PetscViewer binary_viewer;\n                    PetscViewerBinaryOpen(PETSC_COMM_SELF, filename.c_str(), FILE_MODE_READ, &binary_viewer);\n                    MatLoad(mobility_mat, binary_viewer);\n                    PetscViewerDestroy(&binary_viewer);\n                }\n\n                read_files[file_counter] = true;\n            }\n            else\n            {\n                d_cib_strategy->constructMobilityMatrix(mat_name,\n                                                        mat_type,\n                                                        mobility_mat,\n                                                        struct_ids,\n                                                        dx,\n                                                        domain_extents,\n                                                        initial_time,\n                                                        d_rho,\n                                                        d_mu,\n                                                        scale,\n                                                        d_f_periodic_corr,\n                                                        managing_proc);\n            }\n\n            // Construct the geometric matrix that maps rigid body velocity to\n            // nodal velocity.\n            d_cib_strategy->constructGeometricMatrix(mat_name, geometric_mat, struct_ids, initial_time, managing_proc);\n        }\n        factorizeMobilityMatrix();\n        constructBodyMobilityMatrix();\n        factorizeBodyMobilityMatrix();\n    }\n\n    d_is_initialized = true;\n    recreate_mobility_matrices = d_recompute_mob_mat;\n\n    IBAMR_TIMER_STOP(t_initialize_solver_state);\n\n    return;\n} // initializeSolverState\n\nvoid\nDirectMobilitySolver::deallocateSolverState()\n{\n    d_is_initialized = false;\n\n    return;\n} // deallocateSolverState\n\nconst std::vector<unsigned>&\nDirectMobilitySolver::getPrototypeStructIDs(const std::string& mat_name)\n{\n#if !defined(NDEBUG)\n    TBOX_ASSERT(d_mat_prototype_id_map.find(mat_name) != d_mat_prototype_id_map.end());\n#endif\n    return d_mat_prototype_id_map[mat_name];\n\n} // getPrototypeStructIDs\n\nconst std::vector<std::vector<unsigned> >&\nDirectMobilitySolver::getStructIDs(const std::string& mat_name)\n{\n#if !defined(NDEBUG)\n    TBOX_ASSERT(d_mat_actual_id_map.find(mat_name) != d_mat_actual_id_map.end());\n#endif\n    return d_mat_actual_id_map[mat_name];\n\n} // getStructIDs\n\n///////////////////////////// PRIVATE ////////////////////////////////////////\n\nvoid\nDirectMobilitySolver::getFromInput(Pointer<Database> input_db)\n{\n    Pointer<Database> comp_db;\n    comp_db = input_db->isDatabase(\"LAPACK_SVD\") ? input_db->getDatabase(\"LAPACK_SVD\") : Pointer<Database>(nullptr);\n    if (comp_db)\n    {\n        d_svd_replace_value = comp_db->getDouble(\"eigenvalue_replace_value\");\n        d_svd_eps = comp_db->getDouble(\"min_eigenvalue_threshold\");\n    }\n\n    // Other parameters\n    d_f_periodic_corr = input_db->getDoubleWithDefault(\"f_periodic_correction\", d_f_periodic_corr);\n    d_recompute_mob_mat = input_db->getBoolWithDefault(\"recompute_mob_mat_perstep\", d_recompute_mob_mat);\n\n    return;\n} // getFromInput\n\nvoid\nDirectMobilitySolver::factorizeMobilityMatrix()\n{\n    int rank = IBTK_MPI::getRank();\n    for (const auto& petsc_mat_pair : d_petsc_mat_map)\n    {\n        const std::string& mat_name = petsc_mat_pair.first;\n        if (rank != d_mat_proc_map[mat_name]) continue;\n\n        Mat& mat = d_petsc_mat_map[mat_name].first;\n        const MobilityMatrixInverseType& inv_type = d_mat_inv_type_map[mat_name].first;\n        const int mat_size = d_mat_nodes_map[mat_name] * NDIM;\n        double* mat_data = nullptr;\n        MatDenseGetArray(mat, &mat_data);\n        factorizeDenseMatrix(mat_data, mat_size, inv_type, d_ipiv_map[mat_name].first.data(), mat_name, \"Mobility\");\n        MatDenseRestoreArray(mat, &mat_data);\n    }\n    return;\n\n} // factorizeMobilityMatrix\n\nvoid\nDirectMobilitySolver::constructBodyMobilityMatrix()\n{\n    int rank = IBTK_MPI::getRank();\n    for (const auto& petsc_mat_pair : d_petsc_mat_map)\n    {\n        const std::string& mat_name = petsc_mat_pair.first;\n        if (rank != d_mat_proc_map[mat_name]) continue;\n\n        const int row_size = d_mat_nodes_map[mat_name] * NDIM;\n        const int col_size = d_mat_parts_map[mat_name] * s_max_free_dofs;\n        const MobilityMatrixInverseType& mobility_inv_type = d_mat_inv_type_map[mat_name].first;\n\n        Mat& mobility_mat = d_petsc_mat_map[mat_name].first;\n        Mat& body_mob_mat = d_petsc_mat_map[mat_name].second;\n        Mat& geometric_mat = d_petsc_geometric_mat_map[mat_name];\n\n        // Allocate a temporary matrix that holds the Matrix-Matrix product.\n        // Here we are multiplying inverse of mobility matrix with geometric matrix.\n        std::vector<double> product_mat_data(row_size * col_size);\n        Mat product_mat;\n        MatCreateSeqDense(PETSC_COMM_SELF, row_size, col_size, product_mat_data.data(), &product_mat);\n        MatCopy(geometric_mat, product_mat, SAME_NONZERO_PATTERN);\n\n        for (int col = 0; col < col_size; ++col)\n        {\n            double* col_data;\n            MatDenseGetArray(product_mat, &col_data);\n            computeSolution(\n                mobility_mat, mobility_inv_type, d_ipiv_map[mat_name].first.data(), &col_data[col * row_size]);\n            MatDenseRestoreArray(product_mat, &col_data);\n        }\n        MatTransposeMatMult(geometric_mat, product_mat, MAT_REUSE_MATRIX, PETSC_DEFAULT, &body_mob_mat);\n\n        MatDestroy(&product_mat);\n    }\n\n    return;\n} // generateBodyFrictionMatrix\n\nvoid\nDirectMobilitySolver::factorizeBodyMobilityMatrix()\n{\n    int rank = IBTK_MPI::getRank();\n    for (const auto& petsc_mat_pair : d_petsc_mat_map)\n    {\n        const std::string& mat_name = petsc_mat_pair.first;\n        if (rank != d_mat_proc_map[mat_name]) continue;\n\n        Mat& mat = d_petsc_mat_map[mat_name].second;\n        const MobilityMatrixInverseType& inv_type = d_mat_inv_type_map[mat_name].second;\n        const int mat_size = d_mat_parts_map[mat_name] * s_max_free_dofs;\n\n        double* mat_data = nullptr;\n        MatDenseGetArray(mat, &mat_data);\n        factorizeDenseMatrix(\n            mat_data, mat_size, inv_type, d_ipiv_map[mat_name].second.data(), mat_name, \"Body Mobility\");\n        MatDenseRestoreArray(mat, &mat_data);\n    }\n    return;\n\n} // factorizeBodyMobilityMatrix\n\nvoid\nDirectMobilitySolver::factorizeDenseMatrix(double* mat_data,\n                                           const int mat_size,\n                                           const MobilityMatrixInverseType& inv_type,\n                                           int* ipiv,\n                                           const std::string& mat_name,\n                                           const std::string& err_msg)\n{\n    using MatrixType = Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>;\n    // Older versions of Eigen don't make Eigen::Index publicly available\n#if EIGEN_VERSION_AT_LEAST(3, 3, 0)\n    using IndexType = Eigen::Index;\n#else\n    using IndexType = typename MatrixType::Index;\n#endif\n    Eigen::Map<MatrixType> mat_view(mat_data, IndexType(mat_size), IndexType(mat_size));\n\n    if (inv_type != LAPACK_LU)\n    {\n        // For compatibility with the old code, we copy the lower triangle into\n        // the upper triangle, even if they aren't actually equal\n        for (int i = 0; i < mat_size; ++i)\n        {\n            for (int j = i + 1; j < mat_size; ++j)\n            {\n                mat_view(i, j) = mat_view(j, i);\n            }\n        }\n    }\n\n    if (inv_type == LAPACK_CHOLESKY)\n    {\n        Eigen::LLT<MatrixType> cholesky_factorization(mat_view);\n        mat_view = cholesky_factorization.matrixL();\n    }\n    else if (inv_type == LAPACK_LU)\n    {\n        Eigen::PartialPivLU<MatrixType> plu_factorization(mat_view);\n        mat_view = plu_factorization.matrixLU();\n        const auto& indices = plu_factorization.permutationP().indices();\n        TBOX_ASSERT(indices.rows() * indices.cols() == mat_size);\n        std::copy_n(indices.data(), mat_size, ipiv);\n    }\n    else if (inv_type == LAPACK_SVD)\n    {\n        // Use the symmetric eigenvalue decomposition as a stand-in for the SVD.\n        // In particular, since A = V D V^T, where V is the matrix of eigenvectors\n        // and D is the matrix of eigenvalues, we can factorize A as\n        //\n        //   A = V sqrt(D) sqrt(D) V^T\n        //     = V sqrt(D) (V sqrt(D))^T\n        //\n        // and instead store A <- V sqrt(D)\n        Eigen::SelfAdjointEigenSolver<MatrixType> eigensolver(mat_view);\n        Eigen::Matrix<double, Eigen::Dynamic, 1> eigenvalues = eigensolver.eigenvalues();\n        const MatrixType eigenvectors = eigensolver.eigenvectors();\n        // Make negative eigenvalues to be equal to min eigen value from\n        // input option\n        int counter = 0, counter_zero = 0;\n        for (int i = 0; i < mat_size; ++i)\n        {\n            if (eigenvalues[i] < d_svd_eps)\n            {\n                eigenvalues[i] = d_svd_replace_value;\n                counter++;\n            }\n        }\n        for (int i = 0; i < mat_size; ++i)\n        {\n            if (IBTK::abs_equal_eps(eigenvalues[i], 0.0))\n            {\n                counter_zero++;\n            }\n\n            for (int j = 0; j < mat_size; ++j)\n            {\n                if (IBTK::abs_equal_eps(eigenvalues[j], 0.0))\n                {\n                    mat_view(i, j) = 0.0;\n                }\n                else\n                {\n                    mat_view(i, j) = eigenvectors(i, j) / std::sqrt(eigenvalues[j]);\n                }\n            }\n        }\n\n        plog << \"DirectMobilityMatrix::factorizeDenseMatrix(): For \" << err_msg << \" matrix: \" << counter\n             << \" eigenvalues for dense matrix with handle \" << mat_name\n             << \" have been changed. Number of zero eigenvalues placed are \" << counter_zero << std::endl;\n    }\n    else\n    {\n        TBOX_ERROR(\"DirectMobilityMatrix::factorizeDenseMatrix(): Unsupported dense \"\n                   << \"matrix inversion method called for \" << err_msg << std::endl);\n    }\n\n    return;\n} // factorizeDenseMatrix\n\nvoid\nDirectMobilitySolver::computeSolution(Mat& mat, const MobilityMatrixInverseType& inv_type, int* ipiv, double* rhs)\n{\n    // Get pointer to matrix.\n    int mat_size = 0;\n    double* mat_data = nullptr;\n    MatGetSize(mat, &mat_size, nullptr);\n    MatDenseGetArray(mat, &mat_data);\n    using MatrixType = Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>;\n    // Older versions of Eigen don't make Eigen::Index publicly available\n#if EIGEN_VERSION_AT_LEAST(3, 3, 0)\n    using IndexType = Eigen::Index;\n#else\n    using IndexType = typename MatrixType::Index;\n#endif\n    Eigen::Map<MatrixType> mat_view(mat_data, IndexType(mat_size), IndexType(mat_size));\n    using VectorType = Eigen::Matrix<double, Eigen::Dynamic, 1>;\n    Eigen::Map<VectorType> rhs_view(rhs, IndexType(mat_size), IndexType(1));\n\n    if (inv_type == LAPACK_CHOLESKY)\n    {\n        rhs_view = mat_view.triangularView<Eigen::Lower>().solve(rhs_view);\n        rhs_view = mat_view.triangularView<Eigen::Lower>().transpose().solve(rhs_view);\n    }\n    else if (inv_type == LAPACK_LU)\n    {\n        // A    = P L U\n        // A^-1 = U^-1 L^-1 P^-1\n        using IndicesType = Eigen::Matrix<int, Eigen::Dynamic, 1>;\n        Eigen::Map<IndicesType> indices(ipiv, mat_size);\n        PermutationWrapper<decltype(indices)> permutation(indices);\n        rhs_view = permutation.transpose() * rhs_view;\n        rhs_view = mat_view.triangularView<Eigen::UnitLower>().solve(rhs_view);\n        rhs_view = mat_view.triangularView<Eigen::Upper>().solve(rhs_view);\n    }\n    else if (inv_type == LAPACK_SVD)\n    {\n        rhs_view = mat_view * mat_view.transpose() * rhs_view;\n    }\n    else\n    {\n        TBOX_ERROR(\"DirectMobilitySolver::computeSolution(). Inverse method not supported.\" << std::endl);\n    }\n\n    MatDenseRestoreArray(mat, &mat_data);\n\n    return;\n} // computeSolution\n\n//////////////////////////////////////////////////////////////////////////////\n\n} // namespace IBAMR\n", "meta": {"hexsha": "18df5ff103c70a1dc5f6339beecf59dbcdacb6bb", "size": 28285, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/IB/DirectMobilitySolver.cpp", "max_stars_repo_name": "akashdhruv/IBAMR", "max_stars_repo_head_hexsha": "a2b47946d795fb5a40c181b43e44a6ec387585a9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/IB/DirectMobilitySolver.cpp", "max_issues_repo_name": "akashdhruv/IBAMR", "max_issues_repo_head_hexsha": "a2b47946d795fb5a40c181b43e44a6ec387585a9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-07-30T17:54:49.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-30T17:54:49.000Z", "max_forks_repo_path": "src/IB/DirectMobilitySolver.cpp", "max_forks_repo_name": "akashdhruv/IBAMR", "max_forks_repo_head_hexsha": "a2b47946d795fb5a40c181b43e44a6ec387585a9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-09-30T03:40:20.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-30T03:40:20.000Z", "avg_line_length": 37.5630810093, "max_line_length": 119, "alphanum_fraction": 0.6000353544, "num_tokens": 6471, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.46251851266289373}}
{"text": "#include <benchmark/benchmark.h>\n#include <random>\n#include <complex>\n#include <boost/math/fft/bsl_backend.hpp>\n#include <boost/math/fft/fftw_backend.hpp>\n#include <boost/math/fft/gsl_backend.hpp>\n#include <boost/math/constants/constants.hpp>\n\n#include \"fft_test_helpers.hpp\"\n\nstd::default_random_engine gen;\nstd::uniform_real_distribution<double> distribution;\n\nusing Real = double;\nstd::vector<Real> random_vec(size_t N)\n{\n    std::vector<Real> V(N);\n    for (auto& x : V)\n      x = distribution(gen);\n    return V;\n}\n\nvoid bench_bsl(benchmark::State& state)\n{\n    using fft_plan = boost::math::fft::bsl_rdft<Real>;\n    auto A = random_vec(state.range(0));\n    fft_plan P(A.size());\n    for (auto _ : state)\n    {\n        P.real_to_halfcomplex(A.data(),A.data()+A.size(),A.data());\n    }\n    state.SetComplexityN(state.range(0));\n}\nvoid bench_gsl(benchmark::State& state)\n{\n    using fft_plan = boost::math::fft::gsl_rdft<Real>;\n    auto A = random_vec(state.range(0));\n    fft_plan P(A.size());\n    for (auto _ : state)\n    {\n        P.real_to_halfcomplex(A.data(),A.data()+A.size(),A.data());\n    }\n    state.SetComplexityN(state.range(0));\n}\nvoid bench_fftw(benchmark::State& state)\n{\n    using fft_plan = boost::math::fft::fftw_rdft<Real>;\n    auto A = random_vec(state.range(0));\n    fft_plan P(A.size());\n    for (auto _ : state)\n    {\n        P.real_to_halfcomplex(A.data(),A.data()+A.size(),A.data());\n    }\n    state.SetComplexityN(state.range(0));\n}\n\n//// powers of 2\nBENCHMARK(bench_bsl)\n    ->RangeMultiplier(4)\n    ->Range(1 << 8, 1 << 20)\n    ->Complexity(benchmark::oNLogN);\n\nBENCHMARK(bench_gsl)\n    ->RangeMultiplier(4)\n    ->Range(1 << 8, 1 << 20)\n    ->Complexity(benchmark::oNLogN);\n\nBENCHMARK(bench_fftw)\n    ->RangeMultiplier(4)\n    ->Range(1 << 8, 1 << 20)\n    ->Complexity(benchmark::oNLogN);\n\n// powers of 10\n//BENCHMARK(bench_bsl)\n//    ->RangeMultiplier(10)\n//    ->Range(100, 1000000)\n//    ->Complexity(benchmark::oNLogN);\n//\n//BENCHMARK(bench_gsl)\n//    ->RangeMultiplier(10)\n//    ->Range(100, 1000000)\n//    ->Complexity(benchmark::oNLogN);\n//\n//BENCHMARK(bench_fftw)\n//    ->RangeMultiplier(10)\n//    ->Range(100, 1000000)\n//    ->Complexity(benchmark::oNLogN);\n\n// primes\n//BENCHMARK(bench_bsl)\n//    ->Arg(109)\n//    ->Arg(1009)\n//    ->Arg(10009)\n//    ->Arg(100003)\n//    ->Complexity(benchmark::oNLogN);\n//\n//BENCHMARK(bench_gsl)\n//    ->Arg(109)\n//    ->Arg(1009)\n//    ->Arg(10009)\n//    ->Arg(100003)\n//    ->Complexity(benchmark::oNLogN);\n//\n//BENCHMARK(bench_fftw)\n//    ->Arg(109)\n//    ->Arg(1009)\n//    ->Arg(10009)\n//    ->Arg(100003)\n//    ->Complexity(benchmark::oNLogN);\n\nBENCHMARK_MAIN();\n", "meta": {"hexsha": "3cee6eefde92fb0a04a1e83ced3c1c7e1fb5dfcf", "size": 2642, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/fft_real_benchmark.cpp", "max_stars_repo_name": "BoostGSoC21/math", "max_stars_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "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": "test/fft_real_benchmark.cpp", "max_issues_repo_name": "BoostGSoC21/math", "max_issues_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 30.0, "max_issues_repo_issues_event_min_datetime": "2021-06-22T12:59:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-02T09:27:49.000Z", "max_forks_repo_path": "test/fft_real_benchmark.cpp", "max_forks_repo_name": "BoostGSoC21/math", "max_forks_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-07T21:15:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-07T21:15:02.000Z", "avg_line_length": 23.5892857143, "max_line_length": 67, "alphanum_fraction": 0.6252838759, "num_tokens": 819, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.795658090372256, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4625185070295447}}
{"text": "// Copyright (c) 2018 by University Paris-Est Marne-la-Vallee\n// GeometricExplicit.hpp\n// This file is part of the Garamon for e3ga.\n// Authors: Stephane Breuils and Vincent Nozick\n// Conctat: vincent.nozick@u-pem.fr\n//\n// Licence MIT\n// A a copy of the MIT License is given along with this program\n\n/// \\file GeometricExplicit.hpp\n/// \\author Stephane Breuils, Vincent Nozick\n/// \\brief Explicit precomputed per grades geometric products of e3ga.\n\n\n#ifndef E3GA_GEOMETRIC_PRODUCT_EXPLICIT_HPP__\n#define E3GA_GEOMETRIC_PRODUCT_EXPLICIT_HPP__\n#pragma once\n\n#include <Eigen/Core>\n\n#include \"e3ga/Mvec.hpp\"\n#include \"e3ga/Constants.hpp\"\n\n\n/*!\n * @namespace e3ga\n */\nnamespace e3ga {\n    template<typename T> class Mvec;\n\n    /// \\brief Compute the geometric product between two homogeneous multivectors mv1 (grade 2) and mv2 (grade 2). \n\t/// \\tparam the type of value that we manipulate, either float or double or something else.\n\t/// \\param mv1 - the first homogeneous multivector of grade 2 represented as an Eigen::VectorXd\n\t/// \\param mv2 - the second homogeneous multivector of grade 2 represented as a Eigen::VectorXd\n\t/// \\param mv3 - the result of mv1 mv2 whose grade is 2\n\ttemplate<typename T>\n\tvoid geometric_2_2_2(const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv1, const Eigen::Matrix<T, Eigen::Dynamic, 1>& mv2, Eigen::Matrix<T, Eigen::Dynamic, 1>& mv3){\n\t\tmv3.coeffRef(0) += -mv1.coeff(1)*mv2.coeff(2) + mv1.coeff(2)*mv2.coeff(1);\n\t\tmv3.coeffRef(1) +=  mv1.coeff(0)*mv2.coeff(2) - mv1.coeff(2)*mv2.coeff(0);\n\t\tmv3.coeffRef(2) += -mv1.coeff(0)*mv2.coeff(1) + mv1.coeff(1)*mv2.coeff(0);\n\t}\n\n\n\t\n    template<typename T>\n\tstd::array<std::array<std::array<std::function<void(const Eigen::Matrix<T, Eigen::Dynamic, 1> & , const Eigen::Matrix<T, Eigen::Dynamic, 1> & , Eigen::Matrix<T, Eigen::Dynamic, 1>&)>, 4>, 4>, 4> geometricFunctionsContainer =\n\t{{\n\t\t{{\n\t\t\t{{{},{},{},{}}},\n\t\t\t{{{},{},{},{}}},\n\t\t\t{{{},{},{},{}}},\n\t\t\t{{{},{},{},{}}}\n\t\t}},\n\t\t{{\n\t\t\t{{{},{},{},{}}},\n\t\t\t{{{},{},{},{}}},\n\t\t\t{{{},{},{},{}}},\n\t\t\t{{{},{},{},{}}}\n\t\t}},\n\t\t{{\n\t\t\t{{{},{},{},{}}},\n\t\t\t{{{},{},{},{}}},\n\t\t\t{{{},{},geometric_2_2_2<T>,{}}},\n\t\t\t{{{},{},{},{}}}\n\t\t}},\n\t\t{{\n\t\t\t{{{},{},{},{}}},\n\t\t\t{{{},{},{},{}}},\n\t\t\t{{{},{},{},{}}},\n\t\t\t{{{},{},{},{}}}\n\t\t}}\n\t}};\n\n}/// End of Namespace\n\n#endif // E3GA_GEOMETRIC_PRODUCT_EXPLICIT_HPP__", "meta": {"hexsha": "d1efcaaf4cdbf03369c08cc95c9dabcdc5449828", "size": 2305, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "gaLib/e3ga/GeometricExplicit.hpp", "max_stars_repo_name": "sbreuils/GADigitizedTransformations", "max_stars_repo_head_hexsha": "553a357fe12cd5ee0fa21ffc93d835555ea192f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-12-23T23:29:11.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-24T11:20:41.000Z", "max_issues_repo_path": "gaLib/e3ga/GeometricExplicit.hpp", "max_issues_repo_name": "sbreuils/GADigitizedTransformations", "max_issues_repo_head_hexsha": "553a357fe12cd5ee0fa21ffc93d835555ea192f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-12-23T02:07:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-12T08:47:54.000Z", "max_forks_repo_path": "gaLib/e3ga/GeometricExplicit.hpp", "max_forks_repo_name": "sbreuils/GADigitizedTransformations", "max_forks_repo_head_hexsha": "553a357fe12cd5ee0fa21ffc93d835555ea192f2", "max_forks_repo_licenses": ["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.3289473684, "max_line_length": 225, "alphanum_fraction": 0.6069414317, "num_tokens": 740, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424528443251, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.46250901335343764}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n//  Copyright 2014 Anton Bikineev\n//  Copyright 2014 Christopher Kormanyos\n//  Copyright 2014 John Maddock\n//  Copyright 2014 Paul Bristow\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_0F1_BESSEL_HPP\n#define BOOST_MATH_HYPERGEOMETRIC_0F1_BESSEL_HPP\n\n#include <boost/math/special_functions/bessel.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n\n  namespace boost { namespace math { namespace detail {\n\n  template <class T, class Policy>\n  inline T hypergeometric_0F1_bessel(const T& b, const T& z, const Policy& pol)\n  {\n    BOOST_MATH_STD_USING\n\n    const bool is_z_nonpositive = z <= 0;\n\n    const T sqrt_z = is_z_nonpositive ? T(sqrt(-z)) : T(sqrt(z));\n    const T bessel_mult = is_z_nonpositive ?\n      boost::math::cyl_bessel_j(b - 1, 2 * sqrt_z, pol) :\n      boost::math::cyl_bessel_i(b - 1, 2 * sqrt_z, pol) ;\n\n    if (b > boost::math::max_factorial<T>::value)\n    {\n       const T lsqrt_z = log(sqrt_z);\n       const T lsqrt_z_pow_b = (b - 1) * lsqrt_z;\n       T lg = (boost::math::lgamma(b, pol) - lsqrt_z_pow_b);\n       lg = exp(lg);\n       return lg * bessel_mult;\n    }\n    else\n    {\n       const T sqrt_z_pow_b = pow(sqrt_z, b - 1);\n       return (boost::math::tgamma(b, pol) / sqrt_z_pow_b) * bessel_mult;\n    }\n  }\n\n  } } } // namespaces\n\n#endif // BOOST_MATH_HYPERGEOMETRIC_0F1_BESSEL_HPP\n", "meta": {"hexsha": "31ab073766317900de56672e7fb6613fef36849e", "size": 1543, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/math/special_functions/detail/hypergeometric_0F1_bessel.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/special_functions/detail/hypergeometric_0F1_bessel.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/special_functions/detail/hypergeometric_0F1_bessel.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": 32.1458333333, "max_line_length": 79, "alphanum_fraction": 0.6422553467, "num_tokens": 463, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.46250900061240685}}
{"text": "#include <cmath>\n#include <cstring>\n#include <iostream>\n#include <GL/glew.h>\n#include <GLFW/glfw3.h>\n#include <boost/format.hpp>\n#include \"../common/util.hpp\"\n\nusing namespace std;\nusing namespace boost;\n\nint main(int argc, char* argv[]) {\n\tif (argc < 2) {\n\t\tcout << format(\"Usage: %1% <star>\") % argv[0]<< endl;\n\t\treturn EXIT_FAILURE;\n\t}\n\n\tconst int star = atoi(argv[1]);\n\n\tif (!glfwInit()) {\n\t\tthrow runtime_error(\"Failed to initialize GLFW\");\n\t}\n\n\tglfwWindowHint(GLFW_SAMPLES, 4);\n\tglfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);\n\tglfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);\n\tglfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);\n\n\tGLFWwindow* window = glfwCreateWindow(600, 600, \"Hexagram\", NULL, NULL);\n\tif (!window) {\n\t\tthrow runtime_error(\"Failed to open GLFW window\");\n\t}\n\tglfwMakeContextCurrent(window);\n\tglfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE);\n\n\tglewExperimental = GL_TRUE;\n\tif (glewInit() != GLEW_OK) {\n\t\tthrow runtime_error(\"Failed to initialize GLEW\");\n\t}\n\n\tGLuint programID = buildProgram(\"vertex.shader\", \"fragment.shader\");\n\tglUseProgram(programID);\n\tglClearColor(25 / 255.0f, 25 / 255.0, 25 / 255.0, 0.0f);\n\n\tGLuint vertexArrayID;\n\tglGenVertexArrays(1, &vertexArrayID);\n\tglBindVertexArray(vertexArrayID);\n\n\tGLfloat vertexData[star * 12];\n\n\t// center vertex\n\tGLfloat centerVertex[2];\n\tcenterVertex[0] = 0;\n\tcenterVertex[1] = 0;\n\n\tfor (int i = 0; i < star; i++) {\n\t\tvertexData[12 * i] = cos(2 * i * M_PI / star) / 2;\n\t\tvertexData[12 * i + 1] = sin(2 * i * M_PI / star) / 2;\n\n\t\tvertexData[12 * i + 2] = cos(2 * (i + 1) * M_PI / star) / 2;\n\t\tvertexData[12 * i + 3] = sin(2 * (i + 1) * M_PI / star) / 2;\n\n\t\tmemcpy(vertexData + (12 * i + 4), centerVertex, sizeof(GLfloat) * 2);\n\t\tmemcpy(vertexData + (12 * i + 6), vertexData + (12 * i), sizeof(GLfloat) * 4);\n\n\t\tvertexData[12 * i + 10] = cos((2 * i + 1) * M_PI / star);\n\t\tvertexData[12 * i + 11] = sin((2 * i + 1) * M_PI / star);\n\t}\n\n\tGLfloat colorData[star * 18];\n\n\t// center color\n\tGLfloat centerColor[3];\n\tcenterColor[0] = float(rand()) / RAND_MAX;\n\tcenterColor[1] = float(rand()) / RAND_MAX;\n\tcenterColor[2] = float(rand()) / RAND_MAX;\n\n\t/*\n\t * if: most case first\n\t *\n\t * first star => generate 3 random color\n\t * other star => generate 2 random color, copy 1 color\n\t * last  star => generate 1 random color, copy 2 color\n\t *\n\t */\n\tfor (int i = 0; i < star; i++) {\n\t\tif (i != 0) {\n\t\t\tmemcpy(colorData + (18 * i), colorData + (18 * i - 6), sizeof(GLfloat) * 3);\n\t\t} else {\n\t\t\tcolorData[0] = float(rand()) / RAND_MAX;\n\t\t\tcolorData[1] = float(rand()) / RAND_MAX;\n\t\t\tcolorData[2] = float(rand()) / RAND_MAX;\n\t\t}\n\n\t\tif (i != (star - 1)) {\n\t\t\tcolorData[18 * i + 3] = float(rand()) / RAND_MAX;\n\t\t\tcolorData[18 * i + 4] = float(rand()) / RAND_MAX;\n\t\t\tcolorData[18 * i + 5] = float(rand()) / RAND_MAX;\n\t\t} else {\n\t\t\tmemcpy(colorData + (18 * i + 3), colorData, sizeof(GLfloat) * 3);\n\t\t}\n\n\t\tmemcpy(colorData + (18 * i + 6), centerColor, sizeof(centerColor));\n\t\tmemcpy(colorData + (18 * i + 9), colorData + (18 * i), sizeof(GLfloat) * 6);\n\n\t\tcolorData[18 * i + 15] = float(rand()) / RAND_MAX;\n\t\tcolorData[18 * i + 16] = float(rand()) / RAND_MAX;\n\t\tcolorData[18 * i + 17] = float(rand()) / RAND_MAX;\n\t}\n\n\tGLuint vertexBuffer;\n\tglGenBuffers(1, &vertexBuffer);\n\tglBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);\n\tglBufferData(GL_ARRAY_BUFFER, sizeof(vertexData), vertexData, GL_STATIC_DRAW);\n\tglVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, (void*)0);\n\tglEnableVertexAttribArray(0);\n\n\tGLuint colorBuffer;\n\tglGenBuffers(1, &colorBuffer);\n\tglBindBuffer(GL_ARRAY_BUFFER, colorBuffer);\n\tglBufferData(GL_ARRAY_BUFFER, sizeof(colorData), colorData, GL_STATIC_DRAW);\n\tglVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);\n\tglEnableVertexAttribArray(1);\n\n\tdo {\n\t\tglClear(GL_COLOR_BUFFER_BIT);\n\t\tglDrawArrays(GL_TRIANGLES, 0, star * 12);\n\t\tglfwSwapBuffers(window);\n\t\tglfwPollEvents();\n\t} while (glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS && glfwWindowShouldClose(window) == 0);\n\n\treturn EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "2383c7929b22a622c1ab9bf3515871466d1a1ef8", "size": 3982, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "hexagram/main.cpp", "max_stars_repo_name": "Preffer/learning-opengl", "max_stars_repo_head_hexsha": "2e447d3f26354d9cc348f7ac4acd73d0365f1360", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hexagram/main.cpp", "max_issues_repo_name": "Preffer/learning-opengl", "max_issues_repo_head_hexsha": "2e447d3f26354d9cc348f7ac4acd73d0365f1360", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hexagram/main.cpp", "max_forks_repo_name": "Preffer/learning-opengl", "max_forks_repo_head_hexsha": "2e447d3f26354d9cc348f7ac4acd73d0365f1360", "max_forks_repo_licenses": ["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.7164179104, "max_line_length": 99, "alphanum_fraction": 0.658965344, "num_tokens": 1249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083608, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.4624694294121093}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// Unit Test\n\n// Copyright (c) 2010-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//#define BOOST_GEOMETRY_DEBUG_WITH_MAPPER\n//#define BOOST_GEOMETRY_DEBUG_ASSEMBLE\n//#define BOOST_GEOMETRY_DEBUG_IDENTIFIER\n\n#include <geometry_test_common.hpp>\n\n#include <boost/geometry/algorithms/buffer.hpp>\n#include <boost/geometry/core/coordinate_type.hpp>\n\n#include <boost/geometry/strategies/strategies.hpp>\n\n#include <boost/geometry/geometries/point.hpp>\n#include <boost/geometry/geometries/box.hpp>\n\n#include <test_buffer.hpp>\n\n#include <boost/geometry/multi/multi.hpp> // TODO: more specific\n#include <boost/geometry/multi/geometries/multi_geometries.hpp>\n#include <boost/geometry/extensions/algorithms/buffer/multi_buffer_inserter.hpp>\n\n\nstatic std::string const simplex = \"MULTIPOINT((5 5),(7 7))\";\nstatic std::string const three = \"MULTIPOINT((5 8),(9 8),(7 11))\";\n\n// Generates error (extra polygon on top of rest) at distance 14.0:\nstatic std::string const multipoint_a = \"MULTIPOINT((39 44),(38 37),(41 29),(15 33),(58 39))\";\n\n// Just one with holes at distance ~ 15\nstatic std::string const multipoint_b = \"MULTIPOINT((5 56),(98 67),(20 7),(58 60),(10 4),(75 68),(61 68),(75 62),(92 26),(74 6),(67 54),(20 43),(63 30),(45 7))\";\n\n\ntemplate <typename P>\nvoid test_all()\n{\n    //std::cout << typeid(bg::coordinate_type<P>::type).name() << std::endl;\n\n    namespace buf = bg::strategy::buffer;\n    typedef bg::model::polygon<P> polygon;\n    typedef bg::model::multi_point<P> multi_point_type;\n\n\tdouble const pi = boost::geometry::math::pi<double>();\n\n    test_one<multi_point_type, buf::join_miter, buf::end_round, polygon>(\"simplex1\", simplex, 2.0 * pi, 1.0, 1.0);\n    test_one<multi_point_type, buf::join_miter, buf::end_round, polygon>(\"simplex2\", simplex, 22.8372, 2.0, 2.0);\n    test_one<multi_point_type, buf::join_miter, buf::end_round, polygon>(\"simplex3\", simplex, 44.5692, 3.0, 3.0);\n\n    test_one<multi_point_type, buf::join_miter, buf::end_round, polygon>(\"three1\", three, 3.0 * pi, 1.0, 1.0);\n    test_one<multi_point_type, buf::join_miter, buf::end_round, polygon>(\"three2\", three, 36.7592, 2.0, 2.0);\n    test_one<multi_point_type, buf::join_miter, buf::end_round, polygon>(\"three19\", three, 33.6914, 1.9, 1.9);\n    test_one<multi_point_type, buf::join_miter, buf::end_round, polygon>(\"three21\", three, 39.6394, 2.1, 2.1);\n    test_one<multi_point_type, buf::join_miter, buf::end_round, polygon>(\"three3\", three, 65.533, 3.0, 3.0);\n\n    test_one<multi_point_type, buf::join_miter, buf::end_round, polygon>(\"multipoint_a\", multipoint_a, 2049.98, 14.0, 14.0);\n    test_one<multi_point_type, buf::join_miter, buf::end_round, polygon>(\"multipoint_b\", multipoint_b, 7109.88, 15.0, 15.0);\n    test_one<multi_point_type, buf::join_miter, buf::end_round, polygon>(\"multipoint_b1\", multipoint_b, 6911.89, 14.7, 14.7);\n    test_one<multi_point_type, buf::join_miter, buf::end_round, polygon>(\"multipoint_b2\", multipoint_b, 7174.79, 15.1, 15.1);\n}\n\ntemplate \n<\n    typename GeometryOut, \n    template<typename, typename> class JoinStrategy,\n    template<typename, typename> class EndStrategy,\n    typename Geometry\n>\ndouble test_growth(Geometry const& geometry, int n, int d, double distance)\n{\n    namespace bg = boost::geometry;\n\n    typedef typename bg::coordinate_type<Geometry>::type coordinate_type;\n    typedef typename bg::point_type<Geometry>::type point_type;\n\n    typedef typename bg::ring_type<GeometryOut>::type ring_type;\n\n\ttypedef typename bg::tag<Geometry>::type tag;\n\n    // extern int point_buffer_count;\n    std::ostringstream complete;\n    complete\n        << \"point\" << \"_\"\n        << \"growth\" << \"_\"\n        << string_from_type<coordinate_type>::name()\n        << \"_\" << \"r\"\n        << \"_\" << n\n        << \"_\" << d\n         // << \"_\" << point_buffer_count\n        ;\n\n    //std::cout << complete.str() << std::endl;\n\n    std::ostringstream filename;\n    filename << \"buffer_\" << complete.str() << \".svg\";\n\n    std::ofstream svg(filename.str().c_str());\n\n#ifdef BOOST_GEOMETRY_DEBUG_WITH_MAPPER\n    bg::svg_mapper<point_type> mapper(svg, 500, 500);\n\n    {\n        bg::model::box<point_type> box;\n        bg::envelope(geometry, box);\n\n        bg::buffer(box, box, distance * 1.01);\n        mapper.add(box);\n    }\n#endif\n\n    JoinStrategy\n        <\n            point_type,\n            typename bg::point_type<GeometryOut>::type\n        > join_strategy;\n    EndStrategy\n        <\n            point_type,\n            typename bg::point_type<GeometryOut>::type\n        > end_strategy;\n\n    typedef bg::strategy::buffer::distance_symmetric<coordinate_type> distance_strategy_type;\n    distance_strategy_type distance_strategy(distance);\n\n    std::vector<GeometryOut> buffered;\n\n    bg::buffer_inserter<GeometryOut>(geometry, std::back_inserter(buffered),\n                        distance_strategy, \n                        join_strategy,\n                        end_strategy\n#ifdef BOOST_GEOMETRY_DEBUG_WITH_MAPPER\n                        , mapper\n#endif\n                                );\n\n    typename bg::default_area_result<GeometryOut>::type area = 0;\n    BOOST_FOREACH(GeometryOut const& polygon, buffered)\n    {\n        area += bg::area(polygon);\n    }\n\n#ifdef BOOST_GEOMETRY_DEBUG_WITH_MAPPER\n    // Map input geometry in green\n    mapper.map(geometry, \"opacity:0.5;fill:rgb(0,128,0);stroke:rgb(0,128,0);stroke-width:10\");\n\n    BOOST_FOREACH(GeometryOut const& polygon, buffered)\n    {\n        mapper.map(polygon, \"opacity:0.4;fill:rgb(255,255,128);stroke:rgb(0,0,0);stroke-width:3\");\n    }\n#endif\n\n    return area;\n}\n\ntemplate <typename P>\nvoid test_growth(int n, int distance_count)\n{\n    srand(int(time(NULL)));\n    //std::cout << typeid(bg::coordinate_type<P>::type).name() << std::endl;\n    boost::timer t;\n\n    namespace buf = bg::strategy::buffer;\n    typedef bg::model::polygon<P> polygon;\n    typedef bg::model::multi_point<P> multi_point_type;\n\n    multi_point_type multi_point;\n    for (int i = 0; i < n; i++)\n    {\n        P point(rand() % 100, rand() % 100);\n        multi_point.push_back(point);\n    }\n\n    std::cout << bg::wkt(multi_point) << std::endl;\n\n    double previous_area = 0;\n    double epsilon = 0.1;\n    double distance = 15.0;\n    for (int d = 0; d < distance_count; d++, distance += epsilon)\n    {\n        double area = test_growth<polygon, buf::join_miter, buf::end_round>(multi_point, n, d, distance);\n        if (area < previous_area)\n        {\n            std::cout << \"Error: \" << area << \" < \" << previous_area << std::endl\n                << \" n=\" << n << \" distance=\" << distance\n                << bg::wkt(multi_point) << std::endl;\n        }\n        previous_area = area;\n    }\n    std::cout << \"n=\" << n << \" time=\" << t.elapsed() << std::endl;\n}\n\nint test_main(int, char* [])\n{\n    //std::cout << std::setprecision(6);\n    //test_all<bg::model::point<float, 2, bg::cs::cartesian> >();\n    test_all<bg::model::point<double, 2, bg::cs::cartesian> >();\n\n\n#ifdef BOOST_GEOMETRY_BUFFER_TEST_GROWTH\n    for (int i = 5; i <= 50; i++)\n    {\n        test_growth<bg::model::point<double, 2, bg::cs::cartesian> >(i, 20);\n    }\n#endif\n\n    return 0;\n}\n", "meta": {"hexsha": "fec6b810cf2f5174c6440da637b428d57f885acc", "size": 7347, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/extensions/test/algorithms/buffer/multi_point_buffer.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/test/algorithms/buffer/multi_point_buffer.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/test/algorithms/buffer/multi_point_buffer.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": 34.3317757009, "max_line_length": 161, "alphanum_fraction": 0.6499251395, "num_tokens": 2087, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.46245969350142574}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2018-2021 Mikhail Komarov <nemo@nil.foundation>\n// Copyright (c) 2020-2021 Nikita Kaskov <nbering@nil.foundation>\n//\n// MIT License\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n//---------------------------------------------------------------------------//\n\n#define BOOST_TEST_MODULE knapsack_verification_component_test\n\n#include <chrono>\n\n#include <boost/test/unit_test.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/algebra/curves/mnt4.hpp>\n#include <nil/crypto3/algebra/fields/mnt4/base_field.hpp>\n#include <nil/crypto3/algebra/fields/mnt4/scalar_field.hpp>\n#include <nil/crypto3/algebra/fields/arithmetic_params/mnt4.hpp>\n#include <nil/crypto3/algebra/curves/params/multiexp/mnt4.hpp>\n#include <nil/crypto3/algebra/curves/params/wnaf/mnt4.hpp>\n#include <nil/crypto3/algebra/curves/mnt6.hpp>\n#include <nil/crypto3/algebra/fields/mnt6/base_field.hpp>\n#include <nil/crypto3/algebra/fields/mnt6/scalar_field.hpp>\n#include <nil/crypto3/algebra/fields/arithmetic_params/mnt6.hpp>\n#include <nil/crypto3/algebra/curves/params/multiexp/mnt6.hpp>\n#include <nil/crypto3/algebra/curves/params/wnaf/mnt6.hpp>\n#include <nil/crypto3/algebra/curves/edwards.hpp>\n// #include <nil/crypto3/algebra/fields/edwards/base_field.hpp>\n// #include <nil/crypto3/algebra/fields/edwards/scalar_field.hpp>\n// #include <nil/crypto3/algebra/fields/arithmetic_params/edwards.hpp>\n// #include <nil/crypto3/algebra/curves/params/multiexp/edwards.hpp>\n// #include <nil/crypto3/algebra/curves/params/wnaf/edwards.hpp>\n\n#include \"knapsack.hpp\"\n#include \"../verify_r1cs_scheme.hpp\"\n\nusing namespace nil::crypto3::algebra;\nusing namespace nil::crypto3::zk;\n\nBOOST_AUTO_TEST_SUITE(knapsack_component_test_suite)\n\nBOOST_AUTO_TEST_CASE(knapsack_component_test_bls12_381_case) {\n    using curve_type = curves::bls12<381>;\n    using scalar_field_type = typename curve_type::scalar_field_type;\n\n    std::cout << \"Starting Knapsack component test for BLS12-381 ...\" << std::endl;\n    auto begin = std::chrono::high_resolution_clock::now();\n    components::blueprint<scalar_field_type> bp = \n        test_knapsack_crh_with_bit_out_component<scalar_field_type>();\n\n    BOOST_CHECK(verify_component<curve_type>(bp));\n\n    auto end = std::chrono::high_resolution_clock::now();\n    auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin);\n    std::cout << \"Knapsack component test for BLS12-381 finished, time: \" << elapsed.count() * 1e-9 << std::endl;\n}\n\nBOOST_AUTO_TEST_CASE(knapsack_component_test_mnt4_case) {\n    using curve_type = curves::mnt4<298>;\n    using scalar_field_type = typename curve_type::scalar_field_type;\n\n    std::cout << \"Starting Knapsack component test for MNT4-298 ...\" << std::endl;\n    auto begin = std::chrono::high_resolution_clock::now();\n    components::blueprint<scalar_field_type> bp = \n        test_knapsack_crh_with_bit_out_component<scalar_field_type>();\n\n    BOOST_CHECK(verify_component<curve_type>(bp));\n\n    auto end = std::chrono::high_resolution_clock::now();\n    auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin);\n    std::cout << \"Knapsack component test for MNT4-298 finished, time: \" << elapsed.count() * 1e-9 << std::endl;\n}\n\nBOOST_AUTO_TEST_CASE(knapsack_component_test_mnt6_case) {\n    using curve_type = curves::mnt6<298>;\n    using scalar_field_type = typename curve_type::scalar_field_type;\n\n    std::cout << \"Starting Knapsack component test for MNT6-298 ...\" << std::endl;\n    auto begin = std::chrono::high_resolution_clock::now();\n    components::blueprint<scalar_field_type> bp = \n        test_knapsack_crh_with_bit_out_component<scalar_field_type>();\n\n    BOOST_CHECK(verify_component<curve_type>(bp));\n\n    auto end = std::chrono::high_resolution_clock::now();\n    auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin);\n    std::cout << \"Knapsack component test for MNT6-298 finished, time: \" << elapsed.count() * 1e-9 << std::endl;\n}\n\nBOOST_AUTO_TEST_CASE(knapsack_component_test_edwards_183_case) {\n    using curve_type = curves::edwards<183>;\n    using scalar_field_type = typename curve_type::scalar_field_type;\n\n    std::cout << \"Starting Knapsack component test for Edwards-183 ...\" << std::endl;\n    auto begin = std::chrono::high_resolution_clock::now();\n    components::blueprint<scalar_field_type> bp = \n        test_knapsack_crh_with_bit_out_component<scalar_field_type>();\n\n    BOOST_CHECK(verify_component<curve_type>(bp));\n\n    auto end = std::chrono::high_resolution_clock::now();\n    auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin);\n    std::cout << \"Knapsack component test for Edwards-183 finished, time: \" << elapsed.count() * 1e-9 << std::endl;\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "060332e57fcab5d6c88da2f453df5f0372065587", "size": 6192, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/hashes/knapsack_verification.cpp", "max_stars_repo_name": "skywinder/crypto3-blueprint", "max_stars_repo_head_hexsha": "c2b033eaaff1a19ab5332b9f49a32bb4fdd1dc20", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2021-05-27T04:52:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T23:33:40.000Z", "max_issues_repo_path": "test/hashes/knapsack_verification.cpp", "max_issues_repo_name": "skywinder/crypto3-blueprint", "max_issues_repo_head_hexsha": "c2b033eaaff1a19ab5332b9f49a32bb4fdd1dc20", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-08T15:17:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-17T22:19:43.000Z", "max_forks_repo_path": "test/hashes/knapsack_verification.cpp", "max_forks_repo_name": "skywinder/crypto3-blueprint", "max_forks_repo_head_hexsha": "c2b033eaaff1a19ab5332b9f49a32bb4fdd1dc20", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2021-05-20T20:02:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T12:26:24.000Z", "avg_line_length": 47.2671755725, "max_line_length": 115, "alphanum_fraction": 0.7365956072, "num_tokens": 1562, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4624596875835116}}
{"text": "#ifndef Fitting_detail_EffectiveExposuresLinearRegression_hpp\n#define Fitting_detail_EffectiveExposuresLinearRegression_hpp\n\n/** @file EffectiveExposuresLinearRegression.hpp\n  * @brief \n  * @author C.D. Clark III\n  * @date 07/07/17\n  */\n\n#include <Eigen/Dense>\n#include \"../../Utils/LinearRegression.hpp\"\n\nnamespace libArrhenius {\n\n/** @class ArrheniusFit<Real,EffectiveExposuresLinearRegression>\n  * @brief Implements the \"effective exposure\" method from \"Arrhenius Model Thermal Damage Coefficients for Birefringence Loss in Rabbit Myocardium\" Pearse, Raghavan, and Thomsen (2003).\n  * @author C.D. Clark III\n  */\ntemplate<typename Real>\nclass ArrheniusFit<Real,EffectiveExposuresLinearRegression> : public ArrheniusFitBase<Real>\n{\n  public:\n    ArrheniusFit() {};\n    virtual ~ArrheniusFit() {};\n\n    typedef typename ArrheniusFitBase<Real>::Return Return;\n\n    Return\n    exec() const\n    {\n      Return ret;\n      ArrheniusIntegral<Real> integrator;\n      std::vector<Real*> const &t = this->t;\n      std::vector<Real*> const &T = this->T;\n      std::vector<size_t> const &N = this->N;\n\n\n      // construct effective exposure parameters for each profile\n      Eigen::Matrix<Real,Eigen::Dynamic,1> logteff(N.size()),invTeff(N.size());\n\n\n      // Get a range for Ea to evaluate A over\n      // If the caller has specified a bound use it.\n      // otherwise, calculate one\n      Real Ea_lb = 1;\n      Real Ea_ub = 2;\n\n      if( this->minEa )\n      {\n        Ea_lb = this->minEa.get();\n      }\n\n      if( this->maxEa )\n      {\n        Ea_ub = this->maxEa.get();\n      }\n      else\n      {\n\n      // If Ea is too large, then the Arrhenius integral will\n      // return zero. The point at which this happens depends on the\n      // data type being used. Basically, higher-precision types can\n      // evaluate the integral at larger Ea's before reaching zero.\n      // So, we know Ea can't be larger than the smallest value that\n      // gives zero for the integral. This gives us an initial upper bound on Ea.\n      for( size_t i = 0; i < N.size(); i++ )\n      {\n        int prec = std::numeric_limits<Real>::digits - 3;\n        eps_tolerance<Real> tol( prec );\n        boost::uintmax_t maxit = 100;\n        Real guess = 1e2; // a place to start\n        Real factor = 2;  // multiplication factor to use when searching for upper bound\n        auto Ea_ub_range = bracket_and_solve_root( [&](Real Ea){\n            integrator.setEa(Ea);\n            integrator.setA(1);\n            return integrator(N[i],t[i],T[i]);}, guess, factor, false, tol, maxit );\n        // use the smallest Ea for the upper bound.\n        if( i == 0 || Ea_ub_range.first < Ea_ub )\n          Ea_ub = Ea_ub_range.first;\n      }\n      }\n\n\n      // compute a set of (Ea,log(A)) pairs\n      for(size_t i = 0; i < N.size(); i++)\n      {\n\n        // We'll calculate (Ea,log(A)) pairs for every half decade\n        int emin = static_cast<int>(log10(Ea_lb));\n        int emax = static_cast<int>(log10(Ea_ub));\n        Real de = 0.1;\n        int num = 1+static_cast<int>((emax - emin) / de);\n\n        Eigen::Matrix<Real,Eigen::Dynamic,1> Eas(num),logAs(num);\n        for(int j = 0; j < num; ++j)\n        {\n          Eas[j] = pow(10,emin + de*j);\n          integrator.setEa(Eas[j]);\n          integrator.setA(1);\n          logAs[j] = -log( integrator(N[i], t[i], T[i]) );\n        }\n        auto linreg = RUC::LinearRegression(Eas,logAs);\n        // linreg[0] is 'b',\n        // linreg[1] is 'm' for the fit\n        logteff[i] = -linreg[0];\n        invTeff[i] = linreg[1]*Constants::MKS::R;\n      }\n\n      // now perform linear regression with effective parameters\n      auto linreg = RUC::LinearRegression( invTeff, logteff );\n\n      ret.A = exp(-linreg[0]);\n      ret.Ea = linreg[1]*Constants::MKS::R;\n\n\n      return ret;\n      \n    }\n\n  protected:\n};\n\n}\n\n#endif // include protector\n", "meta": {"hexsha": "7e3eb1c55aaf1ef9676ec529bcb9284f39af1ef6", "size": 3846, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/libArrhenius/Fitting/detail/EffectiveExposuresLinearRegression.hpp", "max_stars_repo_name": "CD3/libArrhenius", "max_stars_repo_head_hexsha": "2cf65c9935c1661c6150ddfd86a999cf2fff2691", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/libArrhenius/Fitting/detail/EffectiveExposuresLinearRegression.hpp", "max_issues_repo_name": "CD3/libArrhenius", "max_issues_repo_head_hexsha": "2cf65c9935c1661c6150ddfd86a999cf2fff2691", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libArrhenius/Fitting/detail/EffectiveExposuresLinearRegression.hpp", "max_forks_repo_name": "CD3/libArrhenius", "max_forks_repo_head_hexsha": "2cf65c9935c1661c6150ddfd86a999cf2fff2691", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5238095238, "max_line_length": 186, "alphanum_fraction": 0.6055642226, "num_tokens": 1057, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4624596875835116}}
{"text": "#include <iostream>\n#include <stdio.h>\n\n#include <Eigen/Dense>\n\n#include <boost/array.hpp>\n#include <boost/numeric/odeint.hpp>\n\nusing namespace boost::numeric;\n\nusing std::cout;\nusing std::endl;\n\n#include \"MotionModels.h\"\n#include \"EKF.h\"\n\nnamespace syllo {\n\n     EKF::EKF()\n     {\n     }\n\n     EKF::EKF(const Eigen::MatrixXf &F, \n\t      const Eigen::MatrixXf &B, \n\t      const Eigen::MatrixXf &H, \n\t      const Eigen::MatrixXf &Q, \n\t      const Eigen::MatrixXf &R,\n\t      double dt)\n     {\n\t  setModel(F, B, H, Q, R, dt);\n     }\n\n     int EKF::setModel(const Eigen::MatrixXf &F, \n\t\t       const Eigen::MatrixXf &B, \n\t\t       const Eigen::MatrixXf &H, \n\t\t       const Eigen::MatrixXf &Q, \n\t\t       const Eigen::MatrixXf &R,\n\t\t       double dt)\n     {\n\t  F_ = F;\n\t  B_ = B;\n\t  H_ = H;\n          Q_ = Q;\n\t  R_ = R;\t  \n\t  eye_ = Eigen::MatrixXf::Identity(F.rows(), F.cols());\n\t  dt_ = dt;\n\n\t  return 0;\n     }\n\n     int EKF::init(const Eigen::MatrixXf &x0, \n\t\t   const Eigen::MatrixXf &P0)\n     {\n\t  x_ = x0;\n\t  P_ = P0;\n\t  return 0;\n     }\n\n     int EKF::predict(const Eigen::MatrixXf &u)\n     {\n          x_ = F_*x_ + B_*u;\n          P_ = F_*P_*F_.transpose() + Q_;\n          \n\t  //runge_kutta4< syllo::state_3d_type > stepper;\n\t  //syllo::state_3d_type x = {x_(0,0), x_(1,0), x_(2,0)};\n\t  //stepper.do_step(cart_model, x , 0 , dt_ );\n          //\n\t  //x_ << x[0], x[1], x[2];\n          //\n\t  //////x_ = F_*x_ + B_*u;\n\t  ////Eigen::MatrixXf xdot;\n\t  ////xdot.resize(3,1);\n\t  ////\n\t  ////xdot << u(0,0)   * cos(x_(2,0)), \n\t  ////        u(0,0)   * sin(x_(2,0)), \n   \t  ////        u(0,0)/3 * tan(u(1,0));\n\t  ////\n\t  ////x_ =  x_ + xdot;\n\t  //\n\t  //// compute jacobian...\n\t  //Eigen::MatrixXf J;\n\t  //J.resize(3,3);\n\t  //J << 0, 0, -u(0,0)*sin(x_(2,0)),\n\t  //     0, 0, u(0,0)*cos(x_(2,0)),\n\t  //     0, 0, 0;\n          //\n\t  ////J << 0, 0, 0,\n\t  ////     0, 0, 0,\n\t  ////     0, 0, 0;\n\t  //\n\t  ////P_ = F_*P_*F_.transpose() + Q_;\n\t  //P_ = J*P_*J.transpose() + Q_;\n\t  return 0;\n     }\n     \n     int EKF::update(const Eigen::MatrixXf &z)\n     {\n\t  K_ = P_*H_.transpose()*(H_*P_*H_.transpose() + R_).inverse();\n\t  x_ = x_ + K_*(z - H_*x_);\n\t  P_ = (eye_ - K_*H_)*P_;\n\t  return 0;\n     }\n     \n     Eigen::MatrixXf EKF::state()\n     {\n\t  return x_;\n     }\n     \n     Eigen::MatrixXf EKF::covariance()\n     {\n\t  return P_;\n     }\n}\n\n", "meta": {"hexsha": "9345621e5e3ae07fb1f1c516e2da7e543b81e2b3", "size": 2328, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/track/EKF.cpp", "max_stars_repo_name": "SyllogismRXS/opencv-workbench", "max_stars_repo_head_hexsha": "2fb5b0d67589642d438f21f1cf58aaa761d15757", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2015-10-05T04:33:31.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-20T02:47:36.000Z", "max_issues_repo_path": "src/track/EKF.cpp", "max_issues_repo_name": "SyllogismRXS/opencv-workbench", "max_issues_repo_head_hexsha": "2fb5b0d67589642d438f21f1cf58aaa761d15757", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/track/EKF.cpp", "max_forks_repo_name": "SyllogismRXS/opencv-workbench", "max_forks_repo_head_hexsha": "2fb5b0d67589642d438f21f1cf58aaa761d15757", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2015-07-18T16:01:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-28T11:56:02.000Z", "avg_line_length": 20.2434782609, "max_line_length": 64, "alphanum_fraction": 0.4677835052, "num_tokens": 868, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4624596875835115}}
{"text": "#include <boost/math/special_functions/prime.hpp>\n", "meta": {"hexsha": "9ecb5519cd63bc3b4f288fbd8e24a291ef012488", "size": 50, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_special_functions_prime.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_special_functions_prime.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_special_functions_prime.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 25.0, "max_line_length": 49, "alphanum_fraction": 0.82, "num_tokens": 11, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4624596875835115}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2013 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2013 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_STATISTICS_FUNCTIONS_TESTS_KSTEST_HPP_INCLUDED\n#define NT2_STATISTICS_FUNCTIONS_TESTS_KSTEST_HPP_INCLUDED\n\n#include <nt2/statistics/functions/kstest.hpp>\n#include <nt2/core/container/dsl.hpp>\n#include <nt2/include/functions/numel.hpp>\n#include <nt2/include/functions/sqr.hpp>\n#include <nt2/include/functions/sqrt.hpp>\n#include <nt2/include/functions/colon.hpp>\n#include <nt2/include/functions/max.hpp>\n#include <nt2/include/functions/globalmax.hpp>\n#include <nt2/include/functions/rowvect.hpp>\n#include <nt2/include/functions/dist.hpp>\n#include <nt2/include/functions/exp.hpp>\n#include <nt2/include/functions/abs.hpp>\n#include <nt2/include/constants/zero.hpp>\n#include <nt2/include/constants/two.hpp>\n#include <nt2/include/constants/mone.hpp>\n#include <nt2/include/constants/sqrteps.hpp>\n#include <boost/fusion/include/std_pair.hpp>\n#include <nt2/core/container/colon/colon.hpp>\n\nnamespace nt2 { namespace ext\n{\n\n  BOOST_DISPATCH_IMPLEMENT  ( kstest_\n                            , tag::cpu_\n                            , (A0)(A1)(A2)\n                            ,  ((ast_<A0, nt2::container::domain>))\n                              ((unspecified_< A1 >))\n                              ((scalar_< floating_<A2> >))\n                              ((scalar_< floating_<A2> >))\n                            )\n  {\n    typedef void result_type;\n    BOOST_FORCEINLINE result_type operator()(A0 const& a0, A1 const& cdf,A2 & d, A2&p) const\n    {\n      //a0 is supposed to be sorted;\n      uint32_t nn = numel(a0);\n      A2 n =  A2(nn);\n      BOOST_AUTO_TPL(fn, nt2::colon(nt2::Zero<A2>(), n)/n);\n      BOOST_AUTO_TPL(ff, cdf(rowvect(a0)));\n      d = globalmax(nt2::max(dist(fn(_(1, nn)), ff),\n                             dist(fn(_(2, nn+1)), ff)));\n      n = nt2::sqrt(n);\n      p = pks((n+ A2(0.12)+A2(0.11)/n)*d);\n    }\n  private :\n    static inline A2 pks(const A2& lam)\n    {\n      const A2 eps1 = A2(0.001);\n      const A2 eps2 = nt2::Sqrteps<A2>();\n      A2 fac = Two<A2>();\n      A2 a2 =  -fac*nt2::sqr(lam);\n      A2 r = nt2::Zero<A2>();\n      A2 termbf =   nt2::Zero<A2>();\n      for(uint32_t i=1; i < 100u; ++i)\n      {\n        A2 term = fac*nt2::exp(a2*nt2::sqr(i));\n        r+= term;\n        if ((nt2::abs(term) <= eps1*termbf)||(nt2::abs(term) < eps2*r))\n          return r;\n        fac*= nt2::Mone<A2>();\n        termbf =  nt2::abs(term);\n      }\n      return nt2::One<A2>();\n    }\n\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  ( kstest_, tag::cpu_\n                            , (A0)(A1)\n                            , ((ast_<A0, nt2::container::domain>))\n                              ((unspecified_< A1 >))\n                            )\n  {\n    typedef typename nt2::meta::scalar_of<A0>::type r_t;\n    typedef std::pair<r_t, r_t>                      result_type;\n    BOOST_FORCEINLINE result_type operator()(A0 const& a0, A1 const& cdf) const\n    {\n      r_t first, second;\n      kstest(a0, cdf, first, second);\n      return result_type(first, second);\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  ( kstest_, tag::cpu_\n                            , (A0)(A1)(A2)\n                            , ((ast_<A0, nt2::container::domain>))\n                              ((unspecified_<A1 >))\n                              ((scalar_< floating_<A2> >))\n                            )\n  {\n    typedef A2 result_type;\n    BOOST_FORCEINLINE result_type operator()(A0 const& a0,A1 & cdf,A2 & a3) const\n    {\n      A2 a2;\n      kstest(a0, cdf, a2, a3);\n      return a2;\n    }\n  };\n\n} }\n\n#endif\n", "meta": {"hexsha": "89e53f5462393e6068ce0880243783469bb26929", "size": 3982, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/statistics/include/nt2/statistics/functions/tests/kstest.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/statistics/include/nt2/statistics/functions/tests/kstest.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/statistics/include/nt2/statistics/functions/tests/kstest.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 34.9298245614, "max_line_length": 92, "alphanum_fraction": 0.5231039679, "num_tokens": 1072, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4624596875835115}}
{"text": "#include <geometry.h>\n#include <tiny.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n\n#include <vector>\n\n\nBOOST_AUTO_TEST_SUITE(geometry);\n\nBOOST_AUTO_TEST_CASE(convert_test)\n{\n  typedef tiny::MathTypes<float> MT;\n  typedef MT::vector3_type       V;\n  typedef MT::value_traits       VT;\n  typedef MT::real_type          T;\n  \n  {\n    V                   const center = V::zero();\n    T                   const radius = VT::one();\n    geometry::Sphere<V> const sphere = geometry::make_sphere(center, radius);\n    geometry::DOP<T,6> const dop     = geometry::convert<6,V>(sphere);\n\n    BOOST_CHECK_EQUAL(  dop.size(), 6u);\n    BOOST_CHECK_CLOSE(  dop(0).lower(), -VT::one(), 0.01 );\n    BOOST_CHECK_CLOSE(  dop(1).lower(), -VT::one(), 0.01 );\n    BOOST_CHECK_CLOSE(  dop(2).lower(), -VT::one(), 0.01 );\n    BOOST_CHECK_CLOSE(  dop(0).upper(),  VT::one(), 0.01 );\n    BOOST_CHECK_CLOSE(  dop(1).upper(),  VT::one(), 0.01 );\n    BOOST_CHECK_CLOSE(  dop(2).upper(),  VT::one(), 0.01 );\n    \n  }\n\n  {\n    V                  const min_coord = V::make( -VT::one(), -VT::one(), -VT::one() );\n    V                  const max_coord = V::make(  VT::one(),  VT::one(),  VT::one() );\n    geometry::AABB<V>  const aabb      = geometry::make_aabb(min_coord, max_coord);\n    geometry::DOP<T,6> const dop       = geometry::convert<6,V>(aabb);\n\n    BOOST_CHECK_EQUAL(  dop.size(), 6u);\n    BOOST_CHECK_CLOSE(  dop(0).lower(), -VT::one(), 0.01 );\n    BOOST_CHECK_CLOSE(  dop(1).lower(), -VT::one(), 0.01 );\n    BOOST_CHECK_CLOSE(  dop(2).lower(), -VT::one(), 0.01 );\n    BOOST_CHECK_CLOSE(  dop(0).upper(),  VT::one(), 0.01 );\n    BOOST_CHECK_CLOSE(  dop(1).upper(),  VT::one(), 0.01 );\n    BOOST_CHECK_CLOSE(  dop(2).upper(),  VT::one(), 0.01 );\n\n  }\n\n\n\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "c5b375fa51d5a445cb2c896b1aa582a2d01db8af", "size": 1925, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/FOUNDATION/GEOMETRY/unit_tests/geometry_convert/geometry_convert.cpp", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-11-27T09:44:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-13T00:24:21.000Z", "max_issues_repo_path": "PROX/FOUNDATION/GEOMETRY/unit_tests/geometry_convert/geometry_convert.cpp", "max_issues_repo_name": "erleben/matchstick", "max_issues_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_issues_repo_licenses": ["MIT"], "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/FOUNDATION/GEOMETRY/unit_tests/geometry_convert/geometry_convert.cpp", "max_forks_repo_name": "erleben/matchstick", "max_forks_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_forks_repo_licenses": ["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.6271186441, "max_line_length": 87, "alphanum_fraction": 0.5963636364, "num_tokens": 575, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920211198871, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.4623959311379949}}
{"text": "#include <iostream>\n#include <fstream>\n#include <complex>\n#include <string>\n#include <boost/multi_array.hpp>\n\nusing std::string;\nusing std::complex;\nusing std::cout;\nusing std::endl;\n\ntypedef boost::multi_array<double,2> rarray;\ntypedef boost::multi_array<complex<double>,3> harray;\n//using rarray = boost::multi_array<double,2>; // for C++11 or later\n//using harray = boost::multi_array<complex<double>,3>; //for C++11 or later\n\nint input_hamiltonian(string &fname, rarray &rvec, harray &hop, const int &flag){\n  const int no=hop.size(), nr=rvec.size();\n  string fname_tmp,str;\n  switch(flag){\n  case 1:{\n    fname_tmp=fname;\n    break;\n  }\n  case 2:{\n    fname_tmp=fname+\"/irvec.txt\";\n    break;\n  }\n  case 3:{\n    fname_tmp=fname+\"_hr.dat\";\n    break;\n  }\n  case 4:{\n    fname_tmp=\"Hopping.dat\";\n  }\n  }\n  std::ifstream rfile(fname_tmp.c_str(),std::ios::in);\n  if(rfile.fail()){\n    cout<<\"fail input file\"<<endl;\n    return -1;\n  }\n\n  switch(flag){\n  case 1:{\n    for(int i=0; i<no; i++){\n      for(int j=0; j<no;j++){\n\tfor(int k=0;k<nr;k++){\n\t  getline(rfile,str);\n\t  sscanf(str.c_str(),\"%lf %lf %lf %lf %lf\",\n\t\t      &rvec[k][0], &rvec[k][1], &rvec[k][2],\n\t\t      &hop[j][i][k].real(), &hop[j][i][k].imag());\n\t}\n      }\n    }\n    break;\n  }\n  case 2:{\n    std::ifstream hfile((fname+\"/ham_r.txt\").c_str(),std::ios::in);\n    if(hfile.fail()){\n      cout<<\"fail input file\"<<endl;\n      return -1;\n    }\n    for(int i=0; i<nr; i++){\n      getline(rfile,str);\n      sscanf(str.c_str(),\"%lf %lf %lf\",&rvec[i][0], &rvec[i][1], &rvec[i][2]);\n      for(int j=0; j<no;j++){\n\tfor(int k=0;k<no;k++){\n          getline(hfile,str);\n          sscanf(str.c_str(),\"(%lf, %lf)\",&hop[k][j][i].real(), &hop[k][j][i].imag());\n\t}\n      }\n    }\n    break;\n  }\n  case 3:{\n    break;\n  }\n  case 4:{\n    int l,m;\n    double tmp[3];\n    for(int i=0;i<7+no;i++){\n      getline(rfile,str);\n    }\n    for(int i=0;i<nr;i++){\n      for(int j=0;j<no;j++){\n\tfor(int k=0;k<no;k++){\n\t  getline(rfile,str);\n\t  sscanf(str.c_str(),\"%lf %lf %lf %lf %lf %lf %ld %ld %lf %lf\",\n\t\t &rvec[i][0], &rvec[i][1], &rvec[i][2],\n\t\t &tmp[0], &tmp[1], &tmp[2], &l, &m,\n\t\t &hop[k][j][i].real(), &hop[k][j][i].imag());\n\t}\n      }\n    }\n    break;\n  }\n  }\n  return 0;\n}\n\nint main(){\n  static const int no=1,nr=4,flag=1;\n\n  int err;\n  string fname=\"ham.dat\";\n  rarray rvec(boost::extents[nr][3]);\n  harray hop(boost::extents[no][no][nr]);\n\n  err=input_hamiltonian(fname,rvec,hop,flag);\n  for(int i=0; i<nr; i++){\n    for(int j=0;j<3; j++){\n      cout<<rvec[i][j]<<\" \";\n    }\n    for(int j=0; j<no;j++){\n      for(int k=0;k<no;k++){\n\tcout<<hop[k][j][i];\n      }\n    }\n    cout<<endl;\n  }\n  return 0;\n}\n", "meta": {"hexsha": "b46a86e2b982183dcaf09891db4e86c7b8b133aa", "size": 2651, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "C++/input_ham_boost.cpp", "max_stars_repo_name": "ktszk/ham_input", "max_stars_repo_head_hexsha": "6db5e228b2e1a0d7e111bacd4d974aef5ca15ef5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "C++/input_ham_boost.cpp", "max_issues_repo_name": "ktszk/ham_input", "max_issues_repo_head_hexsha": "6db5e228b2e1a0d7e111bacd4d974aef5ca15ef5", "max_issues_repo_licenses": ["MIT"], "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++/input_ham_boost.cpp", "max_forks_repo_name": "ktszk/ham_input", "max_forks_repo_head_hexsha": "6db5e228b2e1a0d7e111bacd4d974aef5ca15ef5", "max_forks_repo_licenses": ["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.5528455285, "max_line_length": 86, "alphanum_fraction": 0.5345152773, "num_tokens": 923, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.46239592015176184}}
{"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_SINCOSPI_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_SINCOSPI_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n    @ingroup group-trigonometric\n    This function object computes simultaneously and\n    at lower cost the sine and cosine of the input in \\f$\\pi\\f$ multiples.\n\n    @par Header <boost/simd/function/sincospi.hpp>\n\n    @see sincosd, sincos\n\n    @par Example:\n\n      @snippet sincospi.cpp sincospi\n\n    @par Possible output:\n\n      @snippet sincospi.txt sincospi\n\n  **/\n  std::pair<IEEEValue, IEEEValue> sincospi(IEEEValue const& x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/sincospi.hpp>\n#include <boost/simd/function/simd/sincospi.hpp>\n\n#endif\n", "meta": {"hexsha": "2d779a57c74420443ae2f41434241bae948edc08", "size": 1115, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/sincospi.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/sincospi.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/sincospi.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": 25.3409090909, "max_line_length": 100, "alphanum_fraction": 0.600896861, "num_tokens": 249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959543, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.4623959201517618}}
{"text": "// Copyright (c) 2019 Franka Emika GmbH\n// Use of this source code is governed by the Apache-2.0 license, see LICENSE\n\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n\n#include <franka/lowpass_filter.h>\n\nnamespace franka {\n\ndouble lowpassFilter(double sample_time, double y, double y_last, double cutoff_frequency) {\n  if (sample_time < 0 || !std::isfinite(sample_time)) {\n    throw std::invalid_argument(\"lowpass-filter: sample_time is negative, infinite or NaN.\");\n  }\n  if (cutoff_frequency <= 0 || !std::isfinite(cutoff_frequency)) {\n    throw std::invalid_argument(\n        \"lowpass-filter: cutoff_frequency is zero, negative, infinite or NaN.\");\n  }\n  if (!std::isfinite(y) || !std::isfinite(y_last)) {\n    throw std::invalid_argument(\n        \"lowpass-filter: current or past input value of the signal to be filtered is infinite or \"\n        \"NaN.\");\n  }\n  double gain = sample_time / (sample_time + (1.0 / (2.0 * M_PI * cutoff_frequency)));\n  return gain * y + (1 - gain) * y_last;\n}\n\nstd::array<double, 16> cartesianLowpassFilter(double sample_time,\n                                              std::array<double, 16> y,\n                                              std::array<double, 16> y_last,\n                                              double cutoff_frequency) {\n  if (sample_time < 0 || !std::isfinite(sample_time)) {\n    throw std::invalid_argument(\n        \"Cartesian lowpass-filter: sample_time is negative, infinite or NaN.\");\n  }\n  if (cutoff_frequency <= 0 || !std::isfinite(cutoff_frequency)) {\n    throw std::invalid_argument(\n        \"Cartesian lowpass-filter: cutoff_frequency is zero, negative, infinite or NaN.\");\n  }\n  for (size_t i = 0; i < y.size(); i++) {\n    if (!std::isfinite(y[i]) || !std::isfinite(y_last[i])) {\n      throw std::invalid_argument(\n          \"Cartesian lowpass-filter: current or past input value of the signal to be filtered is \"\n          \"infinite or NaN.\");\n    }\n  }\n  Eigen::Affine3d transform(Eigen::Matrix4d::Map(y.data()));\n  Eigen::Affine3d transform_last(Eigen::Matrix4d::Map(y_last.data()));\n  Eigen::Quaterniond orientation(transform.linear());\n  Eigen::Quaterniond orientation_last(transform_last.linear());\n\n  double gain = sample_time / (sample_time + (1.0 / (2.0 * M_PI * cutoff_frequency)));\n  transform.translation() =\n      gain * transform.translation() + (1.0 - gain) * transform_last.translation();\n  orientation = orientation_last.slerp(gain, orientation);\n\n  transform.linear() << orientation.normalized().toRotationMatrix();\n  std::array<double, 16> filtered_values{};\n  Eigen::Map<Eigen::Matrix4d>(&filtered_values[0], 4, 4) = transform.matrix();\n\n  return filtered_values;\n}\n}  // namespace franka", "meta": {"hexsha": "e431ab3999621c55a595ec847e62d063d201c1af", "size": 2681, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/lowpass_filter.cpp", "max_stars_repo_name": "archie1983/libfranka", "max_stars_repo_head_hexsha": "f1f46fb008a37eb0d1dba00c971ff7e5a7bfbfd3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 133.0, "max_stars_repo_stars_event_min_datetime": "2017-09-15T22:58:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T12:25:47.000Z", "max_issues_repo_path": "src/lowpass_filter.cpp", "max_issues_repo_name": "archie1983/libfranka", "max_issues_repo_head_hexsha": "f1f46fb008a37eb0d1dba00c971ff7e5a7bfbfd3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 105.0, "max_issues_repo_issues_event_min_datetime": "2017-09-18T14:40:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T05:44:12.000Z", "max_forks_repo_path": "src/lowpass_filter.cpp", "max_forks_repo_name": "archie1983/libfranka", "max_forks_repo_head_hexsha": "f1f46fb008a37eb0d1dba00c971ff7e5a7bfbfd3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 98.0, "max_forks_repo_forks_event_min_datetime": "2017-09-15T21:30:15.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-10T10:51:41.000Z", "avg_line_length": 42.5555555556, "max_line_length": 98, "alphanum_fraction": 0.6531145095, "num_tokens": 663, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.46239591465864516}}
{"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_REMQUO_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_REMQUO_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-arithmetic\n    Function object implementing remquo capabilities\n\n    Remainder and bits of quotient\n\n    remquo computes the remainder (rem) and a part of the quotient (quo) upon division of\n    @c x by @c y. By design, the value of the remainder is the same as that\n    computed by the @ref remainder function. The value of the computed quotient has\n    the sign of @c x/y and agrees with the actual quotient in at least the low\n    order 3 bits.\n\n    @par semantic:\n\n    For any given value @c x, @c y of type @c T:\n\n    @code\n    as_integer_t<T>& quo;\n    T rem = remquo(x, y, quo);\n    @endcode\n\n    or\n\n    @code\n    std::pair< T, as_integer_t<T> > p = remquo(x, y);\n    @endcode\n\n    computes the two values.\n\n    @par Note\n\n      - This function mimics a standard C library one that was mainly written in its time to\n      help computation of periodic functions: three bits of quo allowing to know the\n      'octant'\n\n      - This implementation differs from std::remquo as the quotient is not returned as a pointer, and\n      his type is not int the the signed integer type associated to the floating one, to allow\n      proper SIMD implementation.\n\n      - also note that the double implementation of std::remquo is flawed in GNU C\n      Library until version 2.21 (2.22 been corrected).\n  **/\n  IntegerValue remquo(Value const & v0, Value const& y, IntegerValue const& quo);\n} }\n#endif\n\n#include <boost/simd/function/scalar/remquo.hpp>\n#include <boost/simd/function/simd/remquo.hpp>\n\n#endif\n", "meta": {"hexsha": "a3d35010af9d9be546ef8ab388bd5f0ebb21a52a", "size": 2077, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/remquo.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/remquo.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/remquo.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": 30.1014492754, "max_line_length": 102, "alphanum_fraction": 0.6384207992, "num_tokens": 479, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432182679957, "lm_q2_score": 0.6406358685621721, "lm_q1q2_score": 0.4623745935139748}}
{"text": "#include <vector>\n\n#include \"ClothoidList.hh\"\n#include <boost/python.hpp>\n#include <boost/python/return_internal_reference.hpp>\n#include <boost/python/suite/indexing/vector_indexing_suite.hpp>\n\nusing d_vector = std::vector<double>;\n\nd_vector extendClothoid(double x0, double y0, double th0, double k0, double dk, double L){\n  G2lib::ClothoidCurve clothoid(x0, y0, th0, k0, dk, L);\n  d_vector ret;\n  ret.emplace_back(clothoid.xEnd());\n  ret.emplace_back(clothoid.yEnd());\n  ret.emplace_back(clothoid.thetaEnd());\n  ret.emplace_back(k0 + dk * L);\n  \n  return ret;\n}\n\nd_vector g2Fitting(double x0, double y0, double th0, double k0, double x1, double y1, double th1, double k1){\n  G2lib::G2solve3arc g2solve3arc;\n\n  int iter = g2solve3arc.build(x0, y0, th0, k0, x1, y1, th1, k1);\n\n  const G2lib::ClothoidCurve &first = g2solve3arc.getS0();\n  const G2lib::ClothoidCurve &second = g2solve3arc.getSM();\n  const G2lib::ClothoidCurve &third = g2solve3arc.getS1();\n\n  d_vector ret;\n  // k1, k2, k3\n  ret.emplace_back(first.dkappa());\n  ret.emplace_back(second.dkappa());\n  ret.emplace_back(third.dkappa());\n  ret.emplace_back(first.length());\n  ret.emplace_back(second.length());\n  ret.emplace_back(third.length());\n\n  return ret;\n}\n\nd_vector pointsOnClothoid(double x0, double y0, double th0, double k0, double dk, double L, char XY, double tick){\n  d_vector arc;\n  G2lib::ClothoidCurve clothoid(x0, y0, th0, k0, dk, L);\n\n  int npts = L / tick;\n  clothoid.optimized_sample_ISO(0 /*offset*/,\n                                npts /*number of points*/,\n                                M_PI / 45 /*max angle*/,\n                                arc);\n  d_vector ret;\n  for(const auto s : arc){\n    if(XY == 'X') ret.emplace_back(clothoid.X(s));\n    else          ret.emplace_back(clothoid.Y(s));\n  }\n  \n  return ret;\n}\n\nBOOST_PYTHON_MODULE(PyClothoids){\n  using namespace boost::python;\n  def(\"extendClothoid\", &extendClothoid);\n  def(\"g2Fitting\", &g2Fitting);\n  def(\"pointsOnClothoid\", &pointsOnClothoid);\n\n  class_<::d_vector>(\"d_vector\")\n      .def(vector_indexing_suite<::d_vector>());\n}\n", "meta": {"hexsha": "7fab5cd45c19f13bbd697a364ce31b4f89c46ebf", "size": 2077, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src_python/python3.cc", "max_stars_repo_name": "soblin/Clothoids", "max_stars_repo_head_hexsha": "6cd8e2570436b4bee7cc20ed418e1589c599b8a2", "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_python/python3.cc", "max_issues_repo_name": "soblin/Clothoids", "max_issues_repo_head_hexsha": "6cd8e2570436b4bee7cc20ed418e1589c599b8a2", "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_python/python3.cc", "max_forks_repo_name": "soblin/Clothoids", "max_forks_repo_head_hexsha": "6cd8e2570436b4bee7cc20ed418e1589c599b8a2", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1014492754, "max_line_length": 114, "alphanum_fraction": 0.671641791, "num_tokens": 618, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975978, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.46237458089332945}}
{"text": "#include <mtl/dense1D.h>\n#include <mtl/mtl.h>\n#include <mtl/utils.h>\n\n/*\n  example output:\n\n  [6,6,6,6,6,6,6,6,6,6]\n\n  */\n\nint\nmain()\n{\n  using namespace mtl;\n  //begin\n  dense1D<double> x(10,4), y(10,2), z(10);\n  ele_div(scaled(x,3), y, z);\n  //end\n  print_vector(z);\n  return 0;\n}\n", "meta": {"hexsha": "6ef39cf926acd5c95371501273d7e7d265e22c09", "size": 283, "ext": "cc", "lang": "C++", "max_stars_repo_path": "stapl_release/tools/mtl-2.0/contrib/examples/vecvec_ele_div.cc", "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/tools/mtl-2.0/contrib/examples/vecvec_ele_div.cc", "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/tools/mtl-2.0/contrib/examples/vecvec_ele_div.cc", "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": 12.3043478261, "max_line_length": 42, "alphanum_fraction": 0.5795053004, "num_tokens": 120, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.4623745759413505}}
{"text": "#pragma once\n#include <algorithm>\n#include <varalgo/std_variant_traits.hpp>\n\n#include <boost/range.hpp>\n#include <boost/range/detail/range_return.hpp>\n\nnamespace varalgo\n{\n\t/************************************************************************/\n\t/*                     includes                                         */\n\t/************************************************************************/\n\ttemplate <class InputIterator1, class InputIterator2, class Pred>\n\tinline bool includes(InputIterator1 first1, InputIterator1 last1,\n\t                     InputIterator2 first2, InputIterator2 last2,\n\t                     Pred && pred)\n\t{\n\t\tauto alg = [&first1, &last1, &first2, &last2](auto && pred)\n\t\t{\n\t\t\treturn std::includes(first1, last1, first2, last2, std::forward<decltype(pred)>(pred));\n\t\t};\n\n\t\treturn variant_traits<std::decay_t<Pred>>::visit(std::move(alg), std::forward<Pred>(pred));\n\t}\n\t\n\t/// range overloads\n\ttemplate <class SinglePassRange1, class SinglePassRange2, class Pred>\n\tinline bool includes(const SinglePassRange1 & rng1, const SinglePassRange2 & rng2, Pred && pred)\n\t{\n\t\treturn varalgo::includes(\n\t\t\tboost::begin(rng1), boost::end(rng1),\n\t\t\tboost::begin(rng2), boost::end(rng2),\n\t\t\tstd::forward<Pred>(pred));\n\t}\n\n\t/************************************************************************/\n\t/*                       set_difference                                 */\n\t/************************************************************************/\n\ttemplate <class InputIterator1, class InputIterator2, class OutputIterator, class Pred>\n\tinline OutputIterator set_difference(InputIterator1 first1, InputIterator1 last1,\n\t                                     InputIterator2 first2, InputIterator2 last2,\n\t                                     OutputIterator out, Pred && pred)\n\t{\n\t\tauto alg = [&first1, &last1, &first2, &last2, &out](auto && pred)\n\t\t{\n\t\t\treturn std::set_difference(first1, last1, first2, last2, out, std::forward<decltype(pred)>(pred));\n\t\t};\n\n\t\treturn variant_traits<std::decay_t<Pred>>::visit(std::move(alg), std::forward<Pred>(pred));\n\t}\n\n\t/// range overloads\n\ttemplate <class SinglePassRange1, class SinglePassRange2, class OutputIterator, class Pred>\n\tinline bool set_difference(const SinglePassRange1 & rng1,\n\t                           const SinglePassRange2 & rng2,\n\t                           OutputIterator out, Pred && pred)\n\t{\n\t\treturn varalgo::set_difference(\n\t\t\tboost::begin(rng1), boost::end(rng1),\n\t\t\tboost::begin(rng2), boost::end(rng2),\n\t\t\tout, std::forward<Pred>(pred));\n\t}\n\n\t/************************************************************************/\n\t/*                       set_intersection                               */\n\t/************************************************************************/\n\ttemplate <class InputIterator1, class InputIterator2, class OutputIterator, class Pred>\n\tinline OutputIterator set_intersection(InputIterator1 first1, InputIterator1 last1,\n\t                                       InputIterator2 first2, InputIterator2 last2,\n\t                                       OutputIterator out, Pred && pred)\n\t{\n\t\tauto alg = [&first1, &last1, &first2, &last2, &out](auto && pred)\n\t\t{\n\t\t\treturn std::set_intersection(first1, last1, first2, last2, out, std::forward<decltype(pred)>(pred));\n\t\t};\n\n\t\treturn variant_traits<std::decay_t<Pred>>::visit(std::move(alg), std::forward<Pred>(pred));\n\t}\n\t\n\t/// range overloads\n\ttemplate <class SinglePassRange1, class SinglePassRange2, class OutputIterator, class Pred>\n\tinline bool set_intersection(const SinglePassRange1 & rng1,\n\t                             const SinglePassRange2 & rng2,\n\t                             OutputIterator out, Pred && pred)\n\t{\n\t\treturn varalgo::set_intersection(\n\t\t\tboost::begin(rng1), boost::end(rng1),\n\t\t\tboost::begin(rng2), boost::end(rng2),\n\t\t\tout, std::forward<Pred>(pred));\n\t}\n\n\t/************************************************************************/\n\t/*                       set_symmetric_difference                       */\n\t/************************************************************************/\n\ttemplate <class InputIterator1, class InputIterator2, class OutputIterator, class Pred>\n\tinline OutputIterator set_symmetric_difference(InputIterator1 first1, InputIterator1 last1,\n\t                                               InputIterator2 first2, InputIterator2 last2,\n\t                                               OutputIterator out, Pred && pred)\n\t{\n\t\tauto alg = [&first1, &last1, &first2, &last2, &out](auto && pred)\n\t\t{\n\t\t\treturn std::set_symmetric_difference(first1, last1, first2, last2, out, std::forward<decltype(pred)>(pred));\n\t\t};\n\n\t\treturn variant_traits<std::decay_t<Pred>>::visit(std::move(alg), std::forward<Pred>(pred));\n\t}\n\t\n\t/// range overloads\n\ttemplate <class SinglePassRange1, class SinglePassRange2, class OutputIterator, class Pred>\n\tinline bool set_symmetric_difference(const SinglePassRange1 & rng1,\n\t                                     const SinglePassRange2 & rng2,\n\t                                     OutputIterator out, Pred && pred)\n\t{\n\t\treturn varalgo::set_symmetric_difference(\n\t\t\tboost::begin(rng1), boost::end(rng1),\n\t\t\tboost::begin(rng2), boost::end(rng2),\n\t\t\tout, std::forward<Pred>(pred));\n\t}\n\n\t/************************************************************************/\n\t/*                       set_union                                      */\n\t/************************************************************************/\n\ttemplate <class InputIterator1, class InputIterator2, class OutputIterator, class Pred>\n\tinline OutputIterator set_union(InputIterator1 first1, InputIterator1 last1,\n\t                                InputIterator2 first2, InputIterator2 last2,\n\t                                OutputIterator out, Pred && pred)\n\t{\n\t\tauto alg = [&first1, &last1, &first2, &last2, &out](auto && pred)\n\t\t{\n\t\t\treturn std::set_union(first1, last1, first2, last2, out, std::forward<decltype(pred)>(pred));\n\t\t};\n\n\t\treturn variant_traits<std::decay_t<Pred>>::visit(std::move(alg), std::forward<Pred>(pred));\n\t}\n\t\n\t/// range overloads\n\ttemplate <class SinglePassRange1, class SinglePassRange2, class OutputIterator, class Pred>\n\tinline bool set_union(const SinglePassRange1 & rng1,\n\t                      const SinglePassRange2 & rng2,\n\t                      OutputIterator out, Pred && pred)\n\t{\n\t\treturn varalgo::set_union(\n\t\t\tboost::begin(rng1), boost::end(rng1),\n\t\t\tboost::begin(rng2), boost::end(rng2),\n\t\t\tout, std::forward<Pred>(pred));\n\t}\n\n}\n", "meta": {"hexsha": "986501522e7cc9a84083c3abd65710aac1646940", "size": 6452, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/varalgo/set_operations.hpp", "max_stars_repo_name": "dmlys/QtTools", "max_stars_repo_head_hexsha": "aaf9605a5dd9b01460c90641bb849bc9477e2fff", "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/varalgo/set_operations.hpp", "max_issues_repo_name": "dmlys/QtTools", "max_issues_repo_head_hexsha": "aaf9605a5dd9b01460c90641bb849bc9477e2fff", "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/varalgo/set_operations.hpp", "max_forks_repo_name": "dmlys/QtTools", "max_forks_repo_head_hexsha": "aaf9605a5dd9b01460c90641bb849bc9477e2fff", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-02-12T09:33:48.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-12T09:33:48.000Z", "avg_line_length": 43.3020134228, "max_line_length": 111, "alphanum_fraction": 0.5477371358, "num_tokens": 1396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217431943271999, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.4623745732246633}}
{"text": "//          Copyright Rein Halbersma 2010-2020.\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 <dctl/core/board/angle.hpp>    // angle, _deg\n#include <boost/test/unit_test.hpp>     // BOOST_AUTO_TEST_SUITE, BOOST_AUTO_TEST_SUITE_END, BOOST_AUTO_TEST_CASE\n\nusing namespace dctl::core;\nusing namespace literals;\n\nBOOST_AUTO_TEST_SUITE(AngleLiterals)\n\nBOOST_AUTO_TEST_CASE(DegreesLiteralIsAngleObject)\n{\n        static_assert(  0_deg == angle{  0});\n        static_assert( 45_deg == angle{ 45});\n        static_assert( 90_deg == angle{ 90});\n        static_assert(135_deg == angle{135});\n        static_assert(180_deg == angle{180});\n        static_assert(225_deg == angle{225});\n        static_assert(270_deg == angle{270});\n        static_assert(315_deg == angle{315});\n        static_assert(360_deg == angle{360});\n}\n\nBOOST_AUTO_TEST_CASE(UnaryPlusAppliesToAngleObject)\n{\n        static_assert(  +0_deg == +angle{  0});\n        static_assert( +45_deg == +angle{ 45});\n        static_assert( +90_deg == +angle{ 90});\n        static_assert(+135_deg == +angle{135});\n        static_assert(+180_deg == +angle{180});\n        static_assert(+225_deg == +angle{225});\n        static_assert(+270_deg == +angle{270});\n        static_assert(+315_deg == +angle{315});\n        static_assert(+360_deg == +angle{360});\n}\n\nBOOST_AUTO_TEST_CASE(UnaryMinusAppliesToAngleObject)\n{\n        static_assert(  -0_deg == -angle{  0});\n        static_assert( -45_deg == -angle{ 45});\n        static_assert( -90_deg == -angle{ 90});\n        static_assert(-135_deg == -angle{135});\n        static_assert(-180_deg == -angle{180});\n        static_assert(-225_deg == -angle{225});\n        static_assert(-270_deg == -angle{270});\n        static_assert(-315_deg == -angle{315});\n        static_assert(-360_deg == -angle{360});\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "cb31e921e5c4b92a327563ee26b968d9f4884fdd", "size": 1956, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/src/util/literals.cpp", "max_stars_repo_name": "sagarpant1/dctl", "max_stars_repo_head_hexsha": "b858fa139159eff73e8f3eec32da93ba077e0bd3", "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": "test/src/util/literals.cpp", "max_issues_repo_name": "sagarpant1/dctl", "max_issues_repo_head_hexsha": "b858fa139159eff73e8f3eec32da93ba077e0bd3", "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/src/util/literals.cpp", "max_forks_repo_name": "sagarpant1/dctl", "max_forks_repo_head_hexsha": "b858fa139159eff73e8f3eec32da93ba077e0bd3", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-27T14:19:28.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-27T14:19:28.000Z", "avg_line_length": 36.2222222222, "max_line_length": 113, "alphanum_fraction": 0.6441717791, "num_tokens": 510, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.46237456603739235}}
{"text": "#include <iostream>\n#include <fstream>\n#include <iomanip>\n#include <cmath>\n#include <memory>\n#include <boost/math/tools/roots.hpp>\n\n#include \"Config.hpp\"\n#include \"MirrorPlasma.hpp\"\n#include \"BatchRunner.hpp\"\n\nextern \"C\" {\n#include <fenv.h>\n}\n\nint main( int argc, char** argv )\n{\n\tstd::string fname( \"Mirror.conf\" );\n\tif ( argc == 2 )\n\t\tfname = argv[ 1 ];\n\tif ( argc > 2 )\n\t{\n\t\tstd::cerr << \"Usage: MCTrans++ ConfigFile.conf\" << std::endl;\n\t\treturn 1;\n\t}\n\n#if defined(DEBUG) && defined(FPEXCEPT)\n\tstd::cerr << \"Floating Point Exceptions Enabled\" << std::endl;\n\t::feenableexcept( FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW );\n#endif\n\n\n\tBatchRunner runner(fname);\n\trunner.runBatchSolve();\n\treturn 0;\n\n}\n\nstd::shared_ptr<MirrorPlasma> MCTransConfig::Solve()\n{\n\tswitch ( Type ) {\n\t\tcase SolveType::SteadyStateMachSolve:\n\t\t\tdoMachSolve( *ReferencePlasmaState );\n\t\t\tbreak;\n\t\tcase SolveType::SteadyStateTempSolve:\n\t\t\tdoTempSolve( *ReferencePlasmaState );\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tthrow std::invalid_argument( \"Unknown Solve Type\" );\n\t}\n\n\treturn std::move( ReferencePlasmaState );\n}\n\nvoid MCTransConfig::doMachSolve( MirrorPlasma& plasma ) const\n{\n\t// NB This uses power densities in W/m^3\n\tauto PowerBalance = [ &plasma ]( double M ) {\n\t\tplasma.MachNumber = M;\n\t\tplasma.ComputeSteadyStateNeutrals();\n\n\t\tdouble HeatLoss = plasma.IonHeatLosses() + plasma.ElectronHeatLosses();\n\t\tdouble Heating = plasma.IonHeating() + plasma.ElectronHeating();\n\n\t\treturn Heating - HeatLoss;\n\t};\n\n\tboost::uintmax_t iters = 1000;\n\tboost::math::tools::eps_tolerance<double> tol( 11 ); // only bother getting part in 1024 accuracy\n\tdouble InitialMach = plasma.initialMach(); // Usually M > 4 for these solutions\n\tdouble Factor = 1.25;\n\tbool rising = true; // Confinement gets uniformly better for increasing M, and Viscous heating increases with M\n\tauto M_bounds = boost::math::tools::bracket_and_solve_root( PowerBalance, InitialMach, Factor, rising, tol, iters );\n\tauto M_lower = M_bounds.first, M_upper = M_bounds.second;\n\tplasma.MachNumber = ( M_lower + M_upper )/2.0;\n\tplasma.ComputeSteadyStateNeutrals();\n}\n\n\n", "meta": {"hexsha": "b4cedf33dc775d1aec5624037d8fb7785a19b883", "size": 2081, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "MCTrans.cpp", "max_stars_repo_name": "MylesKelly/MCTrans", "max_stars_repo_head_hexsha": "9d38178d3150d4c1dcde16489a2df3cca2d49c74", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MCTrans.cpp", "max_issues_repo_name": "MylesKelly/MCTrans", "max_issues_repo_head_hexsha": "9d38178d3150d4c1dcde16489a2df3cca2d49c74", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MCTrans.cpp", "max_forks_repo_name": "MylesKelly/MCTrans", "max_forks_repo_head_hexsha": "9d38178d3150d4c1dcde16489a2df3cca2d49c74", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.0125, "max_line_length": 117, "alphanum_fraction": 0.7121576165, "num_tokens": 589, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.46236370327369075}}
{"text": "\n#include <cstdlib>\n#include <iostream>\n#include <fstream>\n#include <CGAL/Simple_cartesian.h>\n#include <CGAL/Surface_mesh.h>\n#include <boost/variant.hpp>\n#include <boost/lexical_cast.hpp>\n#include <CGAL/boost/graph/dijkstra_shortest_paths.h>\n\ntypedef CGAL::Simple_cartesian<double>      Kernel;\ntypedef CGAL::Surface_mesh<Kernel::Point_3> Triangle_mesh;\ntypedef boost::graph_traits<Triangle_mesh>  Graph_traits;\ntypedef Graph_traits::vertex_descriptor     vertex_descriptor;\n\ntypedef std::vector<vertex_descriptor>                  VertexDescriptorList;\ntypedef std::map<vertex_descriptor, int>                VertexIndexMap;\ntypedef boost::associative_property_map<VertexIndexMap> VertexIdPropertyMap;\n\ntypedef boost::iterator_property_map<VertexDescriptorList::iterator, VertexIdPropertyMap> PredecessorMap;\ntypedef boost::iterator_property_map<std::vector<double>::iterator, VertexIdPropertyMap>  DistanceMap;\n\n\nint main(int argc, char** argv)\n{\n    if (argc < 3) {\n        std::cerr << \"ERROR: need to specify .off and selection files\" << std::endl;\n        return 1;\n    }\n    \n    // read mesh\n    Triangle_mesh tmesh;\n    std::ifstream input(argv[1]);\n    input >> tmesh;\n    input.close();\n    \n    VertexIndexMap vertex_id_map;\n    VertexIdPropertyMap vertex_index_pmap(vertex_id_map);\n    int index = 0;\n    for(vertex_descriptor vd : vertices(tmesh)) {\n        vertex_id_map[vd] = index++;\n    }\n    \n    input.open(argv[2]);\n\n    std::ofstream out(std::string(argv[1])+\".selection.txt\");\n    out << std::endl << std::endl;\n    \n    while (!input.eof()) {\n        \n        int start, end;\n        input >> start >> end;\n        \n        vertex_descriptor vstart(start);\n        vertex_descriptor vend(end);\n        \n        // We first declare a vector\n        std::vector<vertex_descriptor> predecessor(num_vertices(tmesh));\n        // and then turn it into a property map\n        std::vector<double> distance(num_vertices(tmesh));\n        PredecessorMap predecessor_pmap(predecessor.begin(), vertex_index_pmap);\n        DistanceMap distance_pmap(distance.begin(), vertex_index_pmap);\n        \n        boost::dijkstra_shortest_paths(tmesh, vstart,\n                                 distance_map(distance_pmap)\n                                 .predecessor_map(predecessor_pmap)\n                                 .vertex_index_map(vertex_index_pmap));\n        \n        vertex_descriptor it = vend;\n        \n        out << vertex_id_map[it] << \" \";\n        it = boost::get(predecessor_pmap, it);\n        \n        while (it != vstart) {\n            out << vertex_id_map[it] << \" \" << vertex_id_map[it] << \" \";\n            it = boost::get(predecessor_pmap, it);\n        }\n        out << vertex_id_map[it] << \" \";\n        \n    }\n    input.close();\n    \n\n    return 0;\n}\n", "meta": {"hexsha": "ebdcb6fdd65a701cebcf31efcc258d226999a65b", "size": 2775, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main_dijkstra_seam.cpp", "max_stars_repo_name": "ricoseeds/simple_parametrization", "max_stars_repo_head_hexsha": "2b1fb9da6215881655f7914d101ad7ececeece8e", "max_stars_repo_licenses": ["Apache-2.0"], "max_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_dijkstra_seam.cpp", "max_issues_repo_name": "ricoseeds/simple_parametrization", "max_issues_repo_head_hexsha": "2b1fb9da6215881655f7914d101ad7ececeece8e", "max_issues_repo_licenses": ["Apache-2.0"], "max_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_dijkstra_seam.cpp", "max_forks_repo_name": "ricoseeds/simple_parametrization", "max_forks_repo_head_hexsha": "2b1fb9da6215881655f7914d101ad7ececeece8e", "max_forks_repo_licenses": ["Apache-2.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.2674418605, "max_line_length": 105, "alphanum_fraction": 0.6306306306, "num_tokens": 629, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339516289534, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.462363698856915}}
{"text": "// Copyright (c) 2015\n// Author: Chrono Law\n#include <std.hpp>\nusing namespace std;\n\n#include <boost/core/lightweight_test.hpp>\n#include <boost/utility.hpp>\n#include <boost/dynamic_bitset.hpp>\nusing namespace boost;\n\n//////////////////////////////////////////\nvoid case1()\n{\n    dynamic_bitset<> db1;\n    dynamic_bitset<> db2(10);\n    dynamic_bitset<> db3(0x16,\n    BOOST_BINARY(10101));       //\u6ce8\u610f\u8fd9\u91cc\n    dynamic_bitset<> db4(string(\"0100\"));\n    dynamic_bitset<> db5(db3);\n\n    dynamic_bitset<> db6;\n    db6 = db4;\n\n    cout << hex << db5.to_ulong() << endl;\n    cout << db4[0] << db4[1] << db4[2] << endl;\n\n}\n\n//////////////////////////////////////////\nvoid case2()\n{\n    dynamic_bitset<> db;\n\n    db.resize(10, true);\n    cout << db << endl;\n\n    db.resize(5);\n    cout << db << endl;\n\n    {\n        dynamic_bitset<> db(5,BOOST_BINARY(01110));\n\n        cout << db << endl;\n        assert(db.size() == 5);\n\n        db.clear();\n        assert(db.empty()&& db.size()==0);\n\n    }\n\n    assert(dynamic_bitset<>(64).num_blocks()==1);\n    assert(dynamic_bitset<>(65).num_blocks()==2);\n\n    {\n        dynamic_bitset<> db(5,BOOST_BINARY(01001));\n        db.push_back(true);\n        assert(db.to_ulong() == BOOST_BINARY_UL(101001));\n\n    }\n\n    {\n        dynamic_bitset<> db(5,BOOST_BINARY(01001));\n        db.append(BOOST_BINARY(101));\n        assert(db.size() == sizeof(unsigned long)*8 + 5);\n        cout << db << endl;             //0000000000000000000000000000010101001\n\n    }\n}\n\n//////////////////////////////////////////\nvoid case3()\n{\n    dynamic_bitset<> db1(4, BOOST_BINARY(1010));\n\n    db1[0] &= 1;\n    db1[1] ^= 1;\n    cout << db1 << endl;\n\n    dynamic_bitset<> db2(4, BOOST_BINARY(0101));\n    assert(db1 > db2);\n\n    cout << (db1 ^ db2) << endl;\n    cout << (db1 | db2) << endl;\n\n}\n\n//////////////////////////////////////////\nvoid case4()\n{\n    dynamic_bitset<> db(4, BOOST_BINARY(0101));\n\n    assert(db.test(0) && !db.test(1));\n    assert(db.any() && !db.none());\n    assert(db.count() == 2);\n\n    {\n        dynamic_bitset<> db(4, BOOST_BINARY(0101));\n\n        db.flip();\n        assert(db.to_ulong() == BOOST_BINARY(1010));\n\n        db.set();\n        assert(!db.none());\n\n        db.reset();\n        assert(!db.any() );\n\n        db.set(1, 1);\n        assert(db.count() == 1);\n\n    }\n\n    {\n        dynamic_bitset<> db(5, BOOST_BINARY(00101));\n\n        auto pos = db.find_first();\n        assert(pos == 0);\n\n        pos = db.find_next(pos);\n        assert(pos == 2);\n\n    }\n}\n\n//////////////////////////////////////////\nvoid case5()\n{\n    dynamic_bitset<> db(10, BOOST_BINARY(1010101));\n    cout << db.to_ulong() << endl;      //85\n\n    db.append(10);\n    cout << db.to_ulong() << endl;\n\n    db.push_back(1);\n    //cout << db.to_ulong() << endl;\n    BOOST_TEST_THROWS(db.to_ulong(), std::overflow_error);\n\n    string str;\n    to_string(db, str);\n    cout << str << endl;\n\n    dump_to_string(db , str);\n    cout << str << endl;\n}\n\n//////////////////////////////////////////\nvoid case6()\n{\n    dynamic_bitset<> db1(5, BOOST_BINARY(10101));\n    dynamic_bitset<> db2(5, BOOST_BINARY(10010));\n\n    cout << (db1 | db2) << endl;\n    cout << (db1 & db2) << endl;\n    cout << (db1 - db2) << endl;\n\n    dynamic_bitset<> db3(5, BOOST_BINARY(101));\n    assert(db3.is_proper_subset_of(db1));\n\n    dynamic_bitset<> db4(db2);\n    assert(db4.is_subset_of(db2));\n    assert(!db4.is_proper_subset_of(db2));\n}\n\n//////////////////////////////////////////\nvoid func(int n)\n{\n    //cout << \"test \" << n << endl;\n\n    dynamic_bitset<> db(n);\n    db.set();\n    //cout << db.size() << endl;\n\n    for (dynamic_bitset<>::size_type i = db.find_next(1);\n            i != dynamic_bitset<>::npos ;\n            i = db.find_next(i ) )\n    {\n        for (dynamic_bitset<>::size_type j = db.find_next(i);\n                j != dynamic_bitset<>::npos ;\n                j = db.find_next(j ))\n        {\n            if ( j % i == 0)\n            {\n                db[j] = 0;\n            }\n        }\n    }\n\n    cout << dec ;\n    for (dynamic_bitset<>::size_type i = db.find_next(2);\n            i != dynamic_bitset<>::npos ;\n            i = db.find_next(i) )\n    {\n        cout << i << \", \";\n    }\n\n}\n\nvoid case7()\n{\n    func(10);\n    func(50);\n}\n\nint main()\n{\n    case1();\n    case2();\n    case3();\n    case4();\n    case5();\n    case6();\n    case7();\n}\n", "meta": {"hexsha": "0f77eff655d5327b3ec1d7ed5007d05302222aaf", "size": 4318, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "container/dynamic_bitset.cpp", "max_stars_repo_name": "xystar2012/boost_guide", "max_stars_repo_head_hexsha": "6e3d78054d9ade9545a875199d8687001cdb9c97", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-01-05T08:18:22.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-29T05:51:27.000Z", "max_issues_repo_path": "container/dynamic_bitset.cpp", "max_issues_repo_name": "lak123456/boost_guide", "max_issues_repo_head_hexsha": "1886ec8014838717222484f0fe872ecebc324e91", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "container/dynamic_bitset.cpp", "max_forks_repo_name": "lak123456/boost_guide", "max_forks_repo_head_hexsha": "1886ec8014838717222484f0fe872ecebc324e91", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-24T09:09:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-24T09:09:04.000Z", "avg_line_length": 20.1775700935, "max_line_length": 79, "alphanum_fraction": 0.4865678555, "num_tokens": 1195, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.7341195385342971, "lm_q1q2_score": 0.4623298441683461}}
{"text": "#define PY_ARRAY_UNIQUE_SYMBOL pbcvt_ARRAY_API\n\n#include <boost/python.hpp>\n#include <pyboostcvconverter/pyboostcvconverter.hpp>\n\nnamespace pbcvt {\n\n    using namespace boost::python;\n\n/**\n * @brief Example function. Basic inner matrix product using explicit matrix conversion.\n * @param left left-hand matrix operand (NdArray required)\n * @param right right-hand matrix operand (NdArray required)\n * @return an NdArray representing the dot-product of the left and right operands\n */\n    PyObject *dot(PyObject *left, PyObject *right) {\n\n        cv::Mat leftMat, rightMat;\n        leftMat = pbcvt::fromNDArrayToMat(left);\n        rightMat = pbcvt::fromNDArrayToMat(right);\n        auto c1 = leftMat.cols, r2 = rightMat.rows;\n        // Check that the 2-D matrices can be legally multiplied.\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        PyObject *ret = pbcvt::fromMatToNDArray(result);\n        return ret;\n    }\n/**\n * @brief Example function. Simply makes a new CV_16UC3 matrix and returns it as a numpy array.\n * @return The resulting numpy array.\n */\n\n\tPyObject* makeCV_16UC3Matrix(){\n\t\tcv::Mat image = cv::Mat::zeros(240,320, CV_16UC3);\n\t\tPyObject* py_image = pbcvt::fromMatToNDArray(image);\n\t\treturn py_image;\n\t}\n\n//\n/**\n * @brief Example function. Basic inner matrix product using implicit matrix conversion.\n * @details This example uses Mat directly, but we won't need to worry about the conversion in the body of the function.\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 dot2(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     * \\brief Example function. Increments all elements of the given matrix by one.\n     * @details This example uses Mat directly, but we won't need to worry about the conversion anywhere at all,\n     * it is handled automatically by boost.\n     * \\param matrix (numpy array) to increment\n     * \\return\n     */\n    cv::Mat increment_elements_by_one(cv::Mat matrix){\n        matrix += 1.0;\n        return matrix;\n    }\n\n\n#if (PY_VERSION_HEX >= 0x03000000)\n#ifndef NUMPY_IMPORT_ARRAY_RETVAL\n#define NUMPY_IMPORT_ARRAY_RETVAL NULL\n#endif\n    static void* init_ar() {\n#else\n#ifndef NUMPY_IMPORT_ARRAY_RETVAL\n#define NUMPY_IMPORT_ARRAY_RETVAL\n#endif\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 (pbcvt) {\n        //using namespace XM;\n        init_ar();\n\n        //initialize converters\n        to_python_converter<cv::Mat,pbcvt::matToNDArrayBoostConverter>();\n        matFromNDArrayBoostConverter();\n\n        //expose module-level functions\n        def(\"dot\", dot);\n        def(\"dot2\", dot2);\n\t\tdef(\"makeCV_16UC3Matrix\", makeCV_16UC3Matrix);\n\n\t\t//from PEP8 (https://www.python.org/dev/peps/pep-0008/?#prescriptive-naming-conventions)\n        //\"Function names should be lowercase, with words separated by underscores as necessary to improve readability.\"\n        def(\"increment_elements_by_one\", increment_elements_by_one);\n    }\n\n} //end namespace pbcvt\n", "meta": {"hexsha": "a83c0b4dbfbb71f2489df43171c96dd4765a9005", "size": 3664, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/python_module.cpp", "max_stars_repo_name": "Algomorph/pyboostcvconverter", "max_stars_repo_head_hexsha": "269b9c052ec128fc7f8266a092cad3cfb6d3f29d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 275.0, "max_stars_repo_stars_event_min_datetime": "2015-02-02T19:12:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T09:06:59.000Z", "max_issues_repo_path": "src/python_module.cpp", "max_issues_repo_name": "Algomorph/pyboostcvconverter", "max_issues_repo_head_hexsha": "269b9c052ec128fc7f8266a092cad3cfb6d3f29d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 47.0, "max_issues_repo_issues_event_min_datetime": "2015-05-07T18:42:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-01T06:39:58.000Z", "max_forks_repo_path": "src/python_module.cpp", "max_forks_repo_name": "Algomorph/pyboostcvconverter", "max_forks_repo_head_hexsha": "269b9c052ec128fc7f8266a092cad3cfb6d3f29d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 91.0, "max_forks_repo_forks_event_min_datetime": "2015-10-01T10:33:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T16:15:55.000Z", "avg_line_length": 32.7142857143, "max_line_length": 120, "alphanum_fraction": 0.6738537118, "num_tokens": 872, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.7341195385342971, "lm_q1q2_score": 0.4623298441683461}}
{"text": "static char help[] = \"Solve small CMEs to benchmark intranode performance.\\n\\n\";\n\n#include<iomanip>\n#include <petscmat.h>\n#include <petscvec.h>\n#include <petscviewer.h>\n#include <Sys.h>\n#include <armadillo>\n#include <cmath>\n#include <sys/stat.h>\n#include \"FspSolverMultiSinks.h\"\n\nnamespace six_species_cme {\n// stoichiometric matrix of the toggle switch model\narma::Mat<PetscInt> SM{{1, -1, 0, 0, 0, 0, 0, 0, -2, 2},\n                       {0, 0, 0, 0, -1, 1, -1, 1, 1, -1},\n                       {0, 0, 0, 0, -1, 1, 0, 0, 0, 0},\n                       {0, 0, 0, 0, 1, -1, -1, 1, 0, 0},\n                       {0, 0, 0, 0, 0, 0, 1, -1, 0, 0},\n                       {0, 0, 1, -1, 0, 0, 0, 0, 0, 0}};\n\n// reaction parameters\nconst PetscReal Avo = 6.022140857e23, c0 = 0.043, c1 = 0.0007, c2 = 0.078, c3 = 0.0039, c4 =\n    0.012e09 / (Avo), c5 = 0.4791, c6 = 0.00012e09 / (Avo), c7 = 0.8765e-11, c8 =\n    0.05e09 / (Avo), c9 = 0.5, avg_cell_cyc_time = 35 * 60.0;\n\n// propensity function\ninline PetscReal transreg_propensity(const PetscInt *X, const PetscInt k) {\n  switch (k) {\n    case 0:return c0 * PetscReal(X[5]);\n    case 1:return c1 * PetscReal(X[0]);\n    case 2:return c2 * PetscReal(X[3]);\n    case 3:return c3 * PetscReal(X[5]);\n    case 4:return PetscReal(X[1]) * PetscReal(X[2]);\n    case 5:return c5 * PetscReal(X[3]);\n    case 6:return PetscReal(X[3]) * PetscReal(X[1]);\n    case 7:return c7 * PetscReal(X[4]);\n    case 8:return 0.5 * PetscReal(X[0]) * PetscReal(X[0] - 1);\n    case 9:return c9 * PetscReal(X[1]);\n    default:return 0.0;\n  }\n}\nint propensity(const int reaction,\n               const int num_species,\n               const int num_states,\n               const int *states,\n               PetscReal *outputs,\n               void *args) {\n  int (*X)[6] = ( int (*)[6] ) states;\n  for (int i = 0; i < num_states; ++i) {\n    outputs[i] = transreg_propensity(X[i], reaction);\n  }\n  return 0;\n}\n\n// Function to constraint the shape of the Fsp\nvoid lhs_constr(PetscInt num_species, PetscInt num_constrs, PetscInt num_states, PetscInt *states, int *vals,\n                void *args) {\n  for (int j{0}; j < num_states; ++j) {\n    for (int i{0}; i < 6; ++i) {\n      vals[j * num_constrs + i] = states[num_species * j + i];\n    }\n  }\n}\n\narma::Row<int> rhs_constr{10, 6, 1, 2, 1, 1};\narma::Row<double> expansion_factors{0.5, 0.5, 0.5, 0.5, 0.5, 0.5};\narma::Row<int> rhs_constr_hyperrec{10, 6, 1, 2, 1, 1};\narma::Row<double> expansion_factors_hyperrec{0.2, 0.2, 0.2, 0.2, 0.2, 0.2};\n\n// function to compute the time-dependent coefficients of the propensity functions\nint t_fun(PetscReal t, int nc, double *vals, void *args) {\n  arma::Row<PetscReal> u(vals, 10, false, true);\n  u.fill(1.0);\n\n  PetscReal AV = 6.022140857 * 1.0e8 * pow(2.0, t / avg_cell_cyc_time); // cell's volume\n  u(4) = 0.012e09 / AV;\n  u(6) = 0.00012e09 / AV;\n  u(8) = 0.05e09 / AV;\n  return 0;\n}\n}\n\nusing arma::dvec;\nusing arma::Col;\nusing arma::Row;\n\nusing std::cout;\nusing std::endl;\n\nusing namespace six_species_cme;\nusing namespace pacmensl;\n\nvoid output_marginals(MPI_Comm comm, std::string model_name, PartitioningType fsp_par_type,\n                      PartitioningApproach fsp_repart_approach, std::string constraint_type,\n                      DiscreteDistribution &solution, arma::Row<int> constraints);\n\nvoid output_performance(MPI_Comm comm,std::string &model_name,PartitioningType fsp_par_type,\n                        PartitioningApproach fsp_repart_approach,std::string constraint_type,\n                        ODESolverType ode_type,\n                        FspSolverMultiSinks &fsp_solver);\n\nint ParseOptions(MPI_Comm comm, PartitioningType &fsp_par_type, PartitioningApproach &fsp_repart_approach,\n                 PetscBool &output_marginal, PetscBool &fsp_log_events);\n\nint main(int argc, char *argv[]) {\n  Environment my_env(&argc, &argv, help);\n  PetscMPIInt ierr, myRank, num_procs;\n  PetscErrorCode petsc_err;\n\n  MPI_Comm comm;\n  MPI_Comm_dup(PETSC_COMM_WORLD, &comm);\n  MPI_Comm_size(comm, &num_procs);\n\n  // Register PETSc stages for profiling\n  PetscLogStage stages[2];\n  petsc_err = PetscLogStageRegister(\"Solve with adaptive default state set shape\", &stages[0]);\n  CHKERRQ(petsc_err);\n  petsc_err = PetscLogStageRegister(\"Solve with fixed default state set shape\", &stages[1]);\n  CHKERRQ(petsc_err);\n\n  std::string part_type;\n  std::string part_approach;\n\n  std::string model_name = \"transcr_reg_6d\";\n  Model model(SM, t_fun, propensity, nullptr, nullptr, {4, 6, 8});\n\n  PetscReal t_final = 60.00 * 5;\n  PetscReal fsp_tol = 1.0e-4;\n  arma::Mat<PetscInt> X0 = {2, 6, 0, 2, 0, 0};\n  X0 = X0.t();\n  arma::Col<PetscReal> p0 = {1.0};\n  arma::Mat<PetscInt> stoich_mat = SM;\n\n  // Default options\n  PartitioningType fsp_par_type = PartitioningType::GRAPH;\n  PartitioningApproach fsp_repart_approach = PartitioningApproach::REPARTITION;\n  ODESolverType fsp_odes_type = CVODE;\n  PetscBool output_marginal = PETSC_FALSE;\n  PetscBool fsp_log_events = PETSC_FALSE;\n\n  ierr = ParseOptions(comm, fsp_par_type, fsp_repart_approach, output_marginal, fsp_log_events);\n  CHKERRQ(ierr);\n\n  FspSolverMultiSinks fsp_solver(comm, fsp_par_type, CVODE);\n  fsp_solver.SetFromOptions();\n  fsp_solver.SetInitialDistribution(X0, p0);\n  fsp_solver.SetModel(model);\n  DiscreteDistribution solution;\n\n  petsc_err = PetscLogStagePush(stages[0]);\n  CHKERRQ(petsc_err);\n  // Solve using adaptive default constraints\n  fsp_solver.SetInitialBounds(rhs_constr);\n  fsp_solver.SetInitialBounds(rhs_constr_hyperrec);\n  fsp_solver.SetExpansionFactors(expansion_factors_hyperrec);\n  fsp_solver.SetFromOptions();\n  fsp_solver.SetUp();\n  solution = fsp_solver.Solve(t_final, fsp_tol, 0);\n  std::shared_ptr<const StateSetConstrained> fss = std::static_pointer_cast<const StateSetConstrained>(fsp_solver.GetStateSet());\n  arma::Row<int> final_hyperrec_constr = fss->GetShapeBounds();\n  if (fsp_log_events) {\n    output_performance(PETSC_COMM_WORLD, model_name, fsp_par_type, fsp_repart_approach,\n                       std::string(\"adaptive_default\"), fsp_odes_type, fsp_solver);\n  }\n  if (output_marginal) {\n    output_marginals(PETSC_COMM_WORLD, model_name, fsp_par_type, fsp_repart_approach,\n                     std::string(\"adaptive_default\"), solution, final_hyperrec_constr);\n  }\n  fsp_solver.ClearState();\n  PetscPrintf(comm, \"\\n ================ \\n\");\n\n  petsc_err = PetscLogStagePop();\n  CHKERRQ(petsc_err);\n  petsc_err = PetscLogStagePush(stages[1]);\n  CHKERRQ(petsc_err);\n  // Solve using fixed default constraints\n  fsp_solver.SetInitialBounds(final_hyperrec_constr);\n  fsp_solver.SetUp();\n  solution = fsp_solver.Solve(t_final, fsp_tol, 0);\n  if (fsp_log_events) {\n    output_performance(PETSC_COMM_WORLD, model_name, fsp_par_type, fsp_repart_approach,\n                       std::string(\"fixed_default\"), fsp_odes_type, fsp_solver);\n  }\n  if (output_marginal) {\n    output_marginals(PETSC_COMM_WORLD, model_name, fsp_par_type, fsp_repart_approach,\n                     std::string(\"fixed_default\"), solution, final_hyperrec_constr);\n  }\n  fsp_solver.ClearState();\n  PetscPrintf(comm, \"\\n ================ \\n\");\n\n  return ierr;\n}\n\nint ParseOptions(MPI_Comm comm, PartitioningType &fsp_par_type, PartitioningApproach &fsp_repart_approach,\n                 PetscBool &output_marginal, PetscBool &fsp_log_events) {\n  std::string part_type;\n  std::string part_approach;\n  part_type = part2str(fsp_par_type);\n  part_approach = partapproach2str(fsp_repart_approach);\n\n  // Read options for fsp\n  char opt[100];\n  PetscBool opt_set;\n  int ierr;\n  ierr = PetscOptionsGetString(NULL, PETSC_NULL, \"-fsp_partitioning_type\", opt, 100, &opt_set);\n  CHKERRQ(ierr);\n  if (opt_set) {\n    fsp_par_type = str2part(std::string(opt));\n  }\n\n  ierr = PetscOptionsGetString(NULL, PETSC_NULL, \"-fsp_repart_approach\", opt, 100, &opt_set);\n  CHKERRQ(ierr);\n  if (opt_set) {\n    fsp_repart_approach = str2partapproach(std::string(opt));\n  }\n\n  ierr = PetscOptionsGetString(NULL, PETSC_NULL, \"-fsp_output_marginal\", opt, 100, &opt_set);\n  CHKERRQ(ierr);\n  if (opt_set) {\n    if (strcmp(opt, \"1\") == 0 || strcmp(opt, \"true\") == 0) {\n      output_marginal = PETSC_TRUE;\n    }\n  }\n\n  ierr = PetscOptionsGetString(NULL, PETSC_NULL, \"-fsp_log_events\", opt, 100, &opt_set);\n  CHKERRQ(ierr);\n  if (opt_set) {\n    if (strcmp(opt, \"1\") == 0 || strcmp(opt, \"true\") == 0) {\n      fsp_log_events = PETSC_TRUE;\n    }\n  }\n  PetscPrintf(comm, \"Partitiniong option %s \\n\", part2str(fsp_par_type).c_str());\n  PetscPrintf(comm, \"Repartitoning option %s \\n\", partapproach2str(fsp_repart_approach).c_str());\n  return 0;\n}\n\nvoid output_performance(MPI_Comm comm,std::string &model_name,PartitioningType fsp_par_type,\n                        PartitioningApproach fsp_repart_approach,std::string constraint_type,\n                        ODESolverType ode_type,\n                        FspSolverMultiSinks &fsp_solver)\n{\n  int myRank,num_procs;\n  MPI_Comm_rank(comm,&myRank);\n  MPI_Comm_size(comm,&num_procs);\n\n  std::string ode;\n  if (ode_type == KRYLOV)\n  {\n    ode = \"krylov\";\n  } else\n  {\n    ode = \"cvode\";\n  }\n\n  std::string part_type;\n  std::string part_approach;\n  part_type     = part2str(fsp_par_type);\n  part_approach = partapproach2str(fsp_repart_approach);\n\n  // Output time breakdowns\n  FspSolverComponentTiming    sum_times, min_times, max_times;\n  sum_times = fsp_solver.ReduceComponentTiming(\"sum\");\n  min_times = fsp_solver.ReduceComponentTiming(\"min\");\n  max_times = fsp_solver.ReduceComponentTiming(\"max\");\n\n  if (myRank == 0)\n  {\n    struct stat buffer;\n    int fstat;\n\n    std::string   filename =\n                      model_name + \"_time_breakdown.dat\";\n\n    fstat = stat (filename.c_str(), &buffer);\n\n    std::ofstream file;\n    file.open(filename,std::ios_base::app);\n\n    if (fstat != 0){\n      file << \"ncpu, partitioner, fsp_shape, ode_solver, min_cput, max_cput, avg_cput, mat_gen_time, ode_time, state_expand_time, min_flops, max_flops, avg_flops \\n\";\n    }\n\n    file << num_procs << \",\"\n         << part_type << \",\"\n         << constraint_type << \",\"\n         << ode << \",\"\n         << min_times.TotalTime << \",\"\n         << max_times.TotalTime << \",\"\n         << sum_times.TotalTime/num_procs << \",\"\n         << sum_times.MatrixGenerationTime/num_procs << \",\"\n         << sum_times.ODESolveTime/num_procs << \",\"\n         << sum_times.StatePartitioningTime/num_procs\n         << min_times.TotalFlops << \",\"\n         << max_times.TotalFlops << \",\"\n         << sum_times.TotalFlops/num_procs << \"\\n\"\n        ;\n    file.close();\n  }\n\n  FiniteProblemSolverPerfInfo perf_info   = fsp_solver.GetSolverPerfInfo();\n\n  if (myRank == 0){\n    std::string filename =\n                    model_name + \"_perf_info_\" + std::to_string(num_procs) + \"_\" + part_type + \"_\" + part_approach + \"_\" +\n                        constraint_type + \".dat\";\n    std::ofstream file;\n    file.open(filename);\n    file << \"Model time, ODEs size, Average processor time (sec) \\n\";\n    for (auto i{0}; i < perf_info.n_step; ++i)\n    {\n      file << perf_info.model_time[i] << \",\" << perf_info.n_eqs[i] << \",\" << perf_info.cpu_time[i] << \"\\n\";\n    }\n    file.close();\n  }\n}\n\nvoid output_marginals(MPI_Comm comm, std::string model_name, PartitioningType fsp_par_type,\n                      PartitioningApproach fsp_repart_approach, std::string constraint_type,\n                      DiscreteDistribution &solution, arma::Row<int> constraints) {\n  int myRank, num_procs;\n  MPI_Comm_rank(comm, &myRank);\n  MPI_Comm_size(comm, &num_procs);\n\n  std::string part_type;\n  std::string part_approach;\n  part_type = part2str(fsp_par_type);\n  part_approach = partapproach2str(fsp_repart_approach);\n\n  /* Compute the marginal distributions */\n  std::vector<arma::Col<PetscReal>> marginals(solution.states_.n_rows);\n  for (PetscInt i{0}; i < marginals.size(); ++i) {\n    marginals[i] = Compute1DMarginal(solution, i);\n  }\n\n  MPI_Comm_rank(PETSC_COMM_WORLD, &myRank);\n  if (myRank == 0) {\n    for (PetscInt i{0}; i < marginals.size(); ++i) {\n      std::string filename =\n          model_name + \"_marginal_\" + std::to_string(i) + \"_\" + std::to_string(num_procs) + \"_\" +\n              part_type + \"_\" + part_approach + \"_\" + constraint_type + \".dat\";\n      marginals[i].save(filename, arma::raw_ascii);\n    }\n    std::string filename =\n        model_name + \"_constraint_bounds_\" + std::to_string(num_procs) + \"_\" + part_type + \"_\" + part_approach +\n            \"_\" + constraint_type + \".dat\";\n    constraints.save(filename, arma::raw_ascii);\n  }\n}\n", "meta": {"hexsha": "a4c5077468c34eecc85804ec0a75c6db13e2b878", "size": 12459, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/transcr_reg_6d.cpp", "max_stars_repo_name": "voduchuy/pacmensl", "max_stars_repo_head_hexsha": "d35adb165caef5c8fa992be6fda16e1bfb1dfd4a", "max_stars_repo_licenses": ["MIT"], "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/transcr_reg_6d.cpp", "max_issues_repo_name": "voduchuy/pacmensl", "max_issues_repo_head_hexsha": "d35adb165caef5c8fa992be6fda16e1bfb1dfd4a", "max_issues_repo_licenses": ["MIT"], "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/transcr_reg_6d.cpp", "max_forks_repo_name": "voduchuy/pacmensl", "max_forks_repo_head_hexsha": "d35adb165caef5c8fa992be6fda16e1bfb1dfd4a", "max_forks_repo_licenses": ["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.5971428571, "max_line_length": 166, "alphanum_fraction": 0.6559916526, "num_tokens": 3737, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195152660687, "lm_q2_score": 0.629774621301746, "lm_q1q2_score": 0.4623298397169097}}
{"text": "//==================================================================================================\n/*\n  Copyright 2017 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//! [stirling]\n#include <boost/simd/eulerian.hpp>\n#include <boost/simd/pack.hpp>\n#include <iostream>\n\n\nnamespace bs =  boost::simd;\nusing pack_fd = bs::pack <double, 4>;\n\nint main() {\n  pack_fd pd = {170.0, 2.0, 35.0, 10.0};\n\n  std::cout\n    << \"---- simd\" << '\\n'\n    << \"<- pd =               \" << pd << '\\n'\n    << \"-> bs::stirling(pd) = \" << bs::stirling(pd) << '\\n';\n\n  double xf = 40.0;\n\n  std::cout\n    << \"---- scalar\"  << '\\n'\n    << \"<- xf =               \" << xf << '\\n'\n    << \"-> bs::stirling(xf) = \" << bs::stirling(xf) << '\\n';\n  return 0;\n}\n//! [stirling]\n", "meta": {"hexsha": "35959bbba73caa2fdaed9430e1d6241388ef85c2", "size": 953, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/doc/eulerian/stirling.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": "test/doc/eulerian/stirling.cpp", "max_issues_repo_name": "remymuller/boost.simd", "max_issues_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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/doc/eulerian/stirling.cpp", "max_forks_repo_name": "remymuller/boost.simd", "max_forks_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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": 27.2285714286, "max_line_length": 100, "alphanum_fraction": 0.4113326338, "num_tokens": 255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195152660687, "lm_q2_score": 0.6297746004557471, "lm_q1q2_score": 0.4623298244134551}}
{"text": "#include <boost/range/adaptors.hpp>\nnamespace ba = boost::adaptors;\n\n#include <pybind11/pybind11.h>\n#include <pybind11/stl.h>\nnamespace py = pybind11;\n\n#include \"filtration.h\"\n#include \"diagram.h\"\n#include \"omni-field-persistence.h\"\n\nPyOmniFieldPersistence\nomnifield_homology_persistence(const PyFiltration& filtration)\n{\n    PyOmniFieldPersistence persistence;\n    for(auto& s : filtration)\n    {\n        using SimplexChainEntry = dionysus::ChainEntry<PyOmniFieldPersistence::Field, PySimplex>;\n        using ChainEntry        = dionysus::ChainEntry<PyOmniFieldPersistence::Field, PyOmniFieldPersistence::Index>;\n        persistence.add(s.boundary(persistence.field()) |\n                                                 ba::transformed([&filtration](const SimplexChainEntry& e)\n                                                 { return ChainEntry(e.element(), filtration.index(e.index())); }));\n    }\n    return persistence;\n}\n\nstd::vector<PyDiagram>\npy_init_omni_diagrams(const PyOmniFieldPersistence& persistence, const PyFiltration& f, PyOmniFieldPersistence::BaseElement p)\n{\n    return init_diagrams(prime_adapter(persistence, p), f,\n                         [](const PySimplex& s)                         { return s.data(); },        // value\n                         [](PyOmniFieldPersistence::Index i) -> PyIndex { return i; });              // data\n}\n\nPYBIND11_MAKE_OPAQUE(PyOmniFieldPersistence::ZpChain);      // persistence.cpp provides a binding for Chain, which is exactly what this is\n\nvoid init_omnifield_persistence(py::module& m)\n{\n    using namespace pybind11::literals;\n    m.def(\"omnifield_homology_persistence\",   &omnifield_homology_persistence, \"filtration\"_a,\n          \"compute homology persistence of the filtration (pair simplices) over all fields at once\");\n\n    m.def(\"init_diagrams\",      &py_init_omni_diagrams,  \"ofp\"_a, \"f\"_a, \"p\"_a,  \"initialize diagrams for a specific prime from omnifield persistence and filtration\");\n\n    using Index         = PyOmniFieldPersistence::Index;\n    using BaseElement   = PyOmniFieldPersistence::BaseElement;\n    py::class_<PyOmniFieldPersistence>(m, \"OmniFieldPersistence\", \"compact composition of multiple reduced matrices\")\n        .def(\"primes\",  &PyOmniFieldPersistence::primes,    \"primes over which the matrix differs from the rest\")\n        .def(\"column\",  [](const PyOmniFieldPersistence& ofp, Index i, BaseElement p)\n                        {\n                            auto it = ofp.zp_chains().find(i);\n                            if (it != ofp.zp_chains().end())\n                            {\n                                auto pit = it->second.find(p);\n                                if (pit != it->second.end())\n                                    return pit->second;\n                            }\n                            return ofp.convert(ofp.q_chains()[i], ofp.zp(p));\n                        },                                  \"get the column over a specific prime\")\n        .def(\"special\", &PyOmniFieldPersistence::special,   \"test whether the column has a special value over the given prime\")\n        .def(\"__len__\", &PyOmniFieldPersistence::size,      \"size of the persistence object\")\n        .def(\"__repr__\",    [](const PyOmniFieldPersistence& ofp)\n                            { std::ostringstream oss; oss << \"OmniFieldPersistence with \" << ofp.size() << \" columns\"; return oss.str(); })\n    ;\n}\n", "meta": {"hexsha": "eb6d785c4f89d4223461faac5bf73ea10cf35a19", "size": 3400, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bindings/python/omni-field-persistence.cpp", "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": "bindings/python/omni-field-persistence.cpp", "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": "bindings/python/omni-field-persistence.cpp", "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": 51.5151515152, "max_line_length": 167, "alphanum_fraction": 0.6047058824, "num_tokens": 781, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195152660687, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.4623298193123035}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2012-2015 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_CONSTANT_LOGEPS_HPP_INCLUDED\n#define BOOST_SIMD_CONSTANT_LOGEPS_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n  /*!\n    @ingroup group-constant\n\n    Generate the  logarithm of the Eps constant.\n\n    @par Semantic:\n\n    @code\n    T r = Logeps<T>();\n    @endcode\n\n    is similar to:\n\n    @code\n      r =  log(Eps<T>());\n    @endcode\n\n    @return The Logeps constant for the proper type\n  **/\n  template<typename T> T Logeps();\n\n  namespace functional\n  {\n    /*!\n      @ingroup group-callable-constant\n      Generate the  constant logeps.\n\n      @return The Logeps constant for the proper type\n    **/\n    const boost::dispatch::functor<tag::logeps_> logeps = {};\n  }\n} }\n#endif\n\n#include <boost/simd/constant/definition/logeps.hpp>\n#include <boost/simd/arch/common/scalar/constant/constant_value.hpp>\n#include <boost/simd/arch/common/simd/constant/constant_value.hpp>\n\n#endif\n", "meta": {"hexsha": "241eb05c6b0334bace2b4a605885052344444df6", "size": 1320, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/constant/logeps.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/constant/logeps.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/constant/logeps.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": 23.5714285714, "max_line_length": 100, "alphanum_fraction": 0.5886363636, "num_tokens": 294, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195152660687, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.4623298193123035}}
{"text": "/*\n * lorenz_reconstruct.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 \"serialize.hpp\"\n\n#include <boost/numeric/odeint/stepper/runge_kutta4.hpp>\n#include <boost/numeric/odeint/integrate/integrate_const.hpp>\n\n\n#include <iostream>\n#include <fstream>\n#include <iterator>\n\nstruct lorenz_reconstructed\n{\n    lorenz_reconstructed( dynsys::individual_type individual , dynsys::norm_type xnorm , dynsys::norm_type ynorm )\n    : m_individual( std::move( individual ) ) , m_xnorm( std::move( xnorm ) ) , m_ynorm( std::move( ynorm ) )\n    {}\n    \n    void operator()( dynsys::state_type x , dynsys::state_type& dxdt , double t ) const\n    {\n        denormalize( x , m_xnorm );\n        dxdt[0] = m_individual[0].root()->eval( x );\n        dxdt[1] = m_individual[1].root()->eval( x );\n        dxdt[2] = m_individual[2].root()->eval( x );\n        denormalize( dxdt , m_ynorm );\n    }\n    \n    static void denormalize( dynsys::state_type& x , dynsys::norm_type const& norm )\n    {\n        assert( x.size() == norm.size() );\n        for( size_t i=0 ; i<x.size() ; ++i )\n            x[i] = ( x[i] - norm[i].first ) / norm[i].second;\n    }\n    \n    static void normalize( dynsys::state_type& x , dynsys::norm_type const& norm )\n    {\n        assert( x.size() == norm.size() );\n        for( size_t i=0 ; i<x.size() ; ++i )\n            x[i] = ( x[i] + norm[i].first ) * norm[i].second;\n    }\n    \n    dynsys::individual_type m_individual;\n    dynsys::norm_type m_xnorm;\n    dynsys::norm_type m_ynorm;\n};\n\nint main( int argc , char** argv )\n{\n    if( argc != 2 )\n    {\n        std::cerr << \"usage: \" << argv[0] << \" winner-file\" << \"\\n\";\n        return -1;\n    }\n    \n    std::ifstream fin { argv[1] };\n    \n    std::string json_string { std::istream_iterator< char >{ fin } , std::istream_iterator< char >{ } };\n    auto winner = dynsys::deserialize_winner( json_string );\n    \n    std::cout << \"Expressions\" << std::endl;\n    std::cout << gpcxx::polish_string( winner.trees[0] ) << std::endl;\n    std::cout << gpcxx::polish_string( winner.trees[1] ) << std::endl;\n    std::cout << gpcxx::polish_string( winner.trees[2] ) << std::endl;    \n    std::cout << std::endl;\n    \n    std::cout << \"Normalization\" << std::endl;\n    for( size_t i=0 ; i<dynsys::dim ; ++i )\n        std::cout << winner.xnorm[i].first << \" \" << winner.xnorm[i].second << \" \" << winner.ynorm[i].first << \" \" << winner.ynorm[i].second << \"\\n\";\n    std::cout << std::endl;\n    \n    auto sys = lorenz_reconstructed { winner.trees , winner.xnorm , winner.ynorm };\n    \n    using stepper_type = boost::numeric::odeint::runge_kutta4< dynsys::state_type > ;\n    \n    dynsys::state_type x {{ 10.0 , 10.0 , 10.0 }};\n    stepper_type stepper;\n    std::ofstream fout { \"reconstruct.dat\" };\n    boost::numeric::odeint::integrate_const( stepper , sys , x , 0.0 , 100.0 , 0.1 , [&fout]( auto const& x , auto t ) {\n        fout << x[0] << \" \" << x[1] << \" \" << x[2] << \"\\n\"; } );\n    \n    std::ofstream fout2 { \"functions.dat\" };\n    for( double x = -20.0 ; x <= 20.0 ; x += 2.0 )\n    {\n        for( double y = -20.0 ; y <= 20.0 ; y += 2.0 )\n        {\n            for( double z = -20.0 ; z <= 20.0 ; z += 2.0 )\n            {\n                dynsys::state_type xx {{ x , y , z }};\n                dynsys::state_type f;\n                sys( xx , f , 0.0 );\n                fout2 << x << \" \" << y << \" \" << z << \" \" << f[0] << \" \" << f[1] << \" \" << f[2] << \"\\n\";\n            }\n        }\n    }\n\n    \n    \n    return 0;\n}", "meta": {"hexsha": "fb1d253304569529aa15c8e15d321675ac54b237", "size": 3682, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/dynamical_system/lorenz_reconstruct.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_reconstruct.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_reconstruct.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.0925925926, "max_line_length": 149, "alphanum_fraction": 0.5448126018, "num_tokens": 1155, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4622757401819154}}
{"text": "#pragma once\n\n#include <iostream>\n#include <cmath>\n#include <string>\n\n#include \"GNAObject.hh\"\n#include \"TypesFunctions.hh\"\n#include <Eigen/Dense>\n\n\nclass GeoNeutrinoFluxNormed: public GNASingleObject,\n                public TransformationBind<GeoNeutrinoFluxNormed> {\npublic:\n  GeoNeutrinoFluxNormed(double livetime_years): m_livetime_years(livetime_years) {\n    variable_(&m_fluxnorm, \"FluxNorm\");\n    transformation_(\"flux_norm\")\n      .input(\"flux\")\n      .output(\"normed_flux\")\n      .types(TypesFunctions::ifSame, TypesFunctions::pass<0>)\n      .func(&GeoNeutrinoFluxNormed::CalcNorm);\n  }\nprotected:\n  void CalcNorm(FunctionArgs& fargs) {\n      auto& args=fargs.args;\n      const double* events = args[0].x.data();\n      const size_t insize = args[0].type.size();\n      size_t first_non_nan_idx{0};\n      // find first not nan assuming all other values are not NaN!\n      for (; first_non_nan_idx < insize; ++first_non_nan_idx) {\n        if (std::isnan(events[first_non_nan_idx])) {\n            ++first_non_nan_idx;\n        }\n        else {\n            break;\n        }\n      }\n      const double total_events = std::accumulate(events + first_non_nan_idx, events + insize, 0.);\n\n      fargs.rets[0].x = (m_fluxnorm/total_events) * m_livetime_years * fargs.args[0].x;\n  }\n\n  variable<double> m_fluxnorm;\n\n  double m_livetime_years;\n};\n", "meta": {"hexsha": "40129f7e19f2e790eb5b82ef7da9a4f6af12307a", "size": 1340, "ext": "hh", "lang": "C++", "max_stars_repo_path": "transformations/backgrounds/GeoNeutrinoFluxNormed.hh", "max_stars_repo_name": "gnafit/gna", "max_stars_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-10-14T01:06:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-02T16:33:06.000Z", "max_issues_repo_path": "transformations/backgrounds/GeoNeutrinoFluxNormed.hh", "max_issues_repo_name": "gnafit/gna", "max_issues_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "transformations/backgrounds/GeoNeutrinoFluxNormed.hh", "max_forks_repo_name": "gnafit/gna", "max_forks_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_forks_repo_licenses": ["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.5106382979, "max_line_length": 99, "alphanum_fraction": 0.6664179104, "num_tokens": 359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4622757401819154}}
{"text": "#include <iostream>\n#include <cstdlib>\n#include <utility>\n\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix_sparse.hpp>\n\n#include <amgcl/amg.hpp>\n#include <amgcl/make_solver.hpp>\n#include <amgcl/backend/builtin.hpp>\n#include <amgcl/adapter/ublas.hpp>\n#include <amgcl/coarsening/smoothed_aggregation.hpp>\n#include <amgcl/relaxation/spai0.hpp>\n#include <amgcl/solver/bicgstabl.hpp>\n#include <amgcl/profiler.hpp>\n\n#include \"sample_problem.hpp\"\n\ntypedef boost::numeric::ublas::compressed_matrix<\n    double, boost::numeric::ublas::row_major\n    > ublas_matrix;\n\ntypedef boost::numeric::ublas::vector<double> ublas_vector;\n\nnamespace amgcl {\n    profiler<> prof;\n}\n\nint main(int argc, char *argv[]) {\n    using amgcl::prof;\n\n    std::vector<int>    ptr;\n    std::vector<int>    col;\n    std::vector<double> val;\n    std::vector<double> rhs;\n\n    prof.tic(\"assemble\");\n    int m = argc > 1 ? atoi(argv[1]) : 128;\n    int n = sample_problem(m, val, col, ptr, rhs);\n\n    // Create ublas matrix with the data.\n    ublas_matrix A(n, n);\n    A.reserve(ptr[n]);\n\n    for(int i = 0; i < n; ++i)\n        for(int j = ptr[i], e = ptr[i+1]; j < e; ++j)\n            A.push_back(i, col[j], val[j]);\n    prof.toc(\"assemble\");\n\n    prof.tic(\"build\");\n    amgcl::make_solver<\n        amgcl::amg<\n            amgcl::backend::builtin<double>,\n            amgcl::coarsening::smoothed_aggregation,\n            amgcl::relaxation::spai0\n            >,\n        amgcl::solver::bicgstabl<\n            amgcl::backend::builtin<double>\n            >\n        > solve( amgcl::backend::map(A) );\n    prof.toc(\"build\");\n\n    std::cout << solve.precond() << std::endl;\n\n    ublas_vector x(n, 0);\n\n    prof.tic(\"solve\");\n    size_t iters;\n    double resid;\n    std::tie(iters, resid) = solve(rhs, x);\n    prof.toc(\"solve\");\n\n    std::cout << \"Iterations: \" << iters << std::endl\n              << \"Error:      \" << resid << std::endl\n              << std::endl << prof << std::endl;\n}\n", "meta": {"hexsha": "1fcd3d9c7cf861280aa8b9e54506803e8cab82f8", "size": 1974, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/ublas.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/ublas.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/ublas.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": 25.6363636364, "max_line_length": 59, "alphanum_fraction": 0.600810537, "num_tokens": 578, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4622757401819154}}
{"text": "#include \"interpolate_bilinearly.h\"\n#include \"matrix.h\"\n#include \"round_point.h\"\n#include <boost/multi_array.hpp>\n#include <iostream>\n#include <vector>\n\nPoint interpolate_point_bilinearly(Point p1,\n                                   const boost::multi_array<double, 2> *xdisp,\n                                   const boost::multi_array<double, 2> *ydisp,\n                                   const unsigned int lx,\n                                   const unsigned int ly)\n{\n  const double intp_x =\n    interpolate_bilinearly(p1.x(), p1.y(), xdisp, 'x', lx, ly);\n  const double intp_y =\n    interpolate_bilinearly(p1.x(), p1.y(), ydisp, 'y', lx, ly);\n  return Point(p1.x() + intp_x, p1.y() + intp_y);\n}\n\nvoid InsetState::project()\n{\n  // Calculate displacement from proj array\n  boost::multi_array<double, 2> xdisp(boost::extents[lx_][ly_]);\n  boost::multi_array<double, 2> ydisp(boost::extents[lx_][ly_]);\n  for (unsigned int i = 0; i < lx_; ++i) {\n    for (unsigned int j=0; j<ly_; ++j) {\n      xdisp[i][j] = proj_[i][j].x - i - 0.5;\n      ydisp[i][j] = proj_[i][j].y - j - 0.5;\n    }\n  }\n\n  // Cumulative projection\n  for (unsigned int i = 0; i < lx_; ++i) {\n    for (unsigned int j = 0; j < ly_; ++j) {\n\n      // TODO: Should the interpolation be made on the basis of triangulation?\n      // Calculate displacement for cumulative graticule coordinates\n      const double graticule_intp_x = interpolate_bilinearly(\n        cum_proj_[i][j].x,\n        cum_proj_[i][j].y,\n        &xdisp, 'x', lx_, ly_);\n      const double graticule_intp_y = interpolate_bilinearly(\n        cum_proj_[i][j].x,\n        cum_proj_[i][j].y,\n        &ydisp, 'y', lx_, ly_);\n\n      // Update cumulative graticule coordinates\n      cum_proj_[i][j].x += graticule_intp_x;\n      cum_proj_[i][j].y += graticule_intp_y;\n    }\n  }\n\n  // Specialise/curry interpolate_point_bilinearly such that it only requires\n  // one argument (Point p1).\n  std::function<Point(Point)> lambda =\n    [&xdisp, &ydisp, lx = lx_, ly = ly_](Point p1) {\n      return interpolate_point_bilinearly(p1, &xdisp, &ydisp, lx, ly);\n    };\n\n  // Apply \"lambda\" to all points\n  transform_points(lambda);\n  return;\n}\n\n// In chosen_diag() and transformed_triangle(), the input x-coordinates can\n// only be 0, lx, or 0.5, 1.5, ..., lx-0.5. A similar rule applies to the\n// y-coordinates.\nvoid InsetState::exit_if_not_on_grid_or_edge(const Point p1) const\n{\n  if ((p1.x() != 0.0 && p1.x() != lx_ && p1.x() - int(p1.x()) != 0.5) ||\n      (p1.y() != 0.0 && p1.y() != ly_ && p1.y() - int(p1.y()) != 0.5)) {\n    std::cerr << \"Error: Invalid input coordinate in triangulation\\n\"\n              << \"\\tpt = (\"\n              << p1.x()\n              << \", \"\n              << p1.y()\n              << \")\"\n              << std::endl;\n    exit(1);\n  }\n  return;\n}\n\nPoint InsetState::projected_point(const Point p1)\n{\n  exit_if_not_on_grid_or_edge(p1);\n  const unsigned int proj_x = std::min(\n    static_cast<unsigned int>(lx_) - 1,\n    static_cast<unsigned int>(p1.x()));\n  const unsigned int proj_y = std::min(\n    static_cast<unsigned int>(ly_) - 1,\n    static_cast<unsigned int>(p1.y()));\n  return Point((p1.x() == 0.0 || p1.x() == lx_) ?\n               p1.x() :\n               proj_[proj_x][proj_y].x,\n               (p1.y() == 0.0 || p1.y() == ly_) ?\n               p1.y() :\n               proj_[proj_x][proj_y].y);\n}\n\n// TODO: chosen_diag() seems to be more naturally thought of as a boolean\n// than an integer.\n\n// For a graticule cell with corners stored in the XYPoint array v, determine\n// whether the diagonal from v[0] to v[2] is inside the graticule cell. If\n// yes, return 0. Otherwise, if the diagonal from v[1] to v[3] is inside the\n// graticule cell, return 1. If neither of the two diagonals is inside the\n// graticule cell, then the cell's topology is invalid; thus, we exit with an\n// error message.\nint InsetState::chosen_diag(const Point v[4], unsigned int *num_concave)\n{\n  // The input v[i].x can only be 0, lx, or 0.5, 1.5, ..., lx-0.5. A similar\n  // rule applies to the y-coordinates.\n  for (unsigned int i = 0; i < 4; ++i) {\n    exit_if_not_on_grid_or_edge(v[i]);\n  }\n\n  // Transform the coordinates in v to the corresponding coordinates on the\n  // projected grid. If the x-coordinate is 0 or lx, we keep the input. The\n  // input v[i].x can only be 0, lx, or 0.5, 1.5, ..., lx-0.5. A similar rule\n  // applies to the y-coordinates. This condition is checked in\n  // projected_point().\n  Point tv[4];\n  for (unsigned int i = 0; i < 4; ++i) {\n    tv[i] = projected_point(v[i]);\n  }\n\n  // Get the two possible midpoints\n  const Point midpoint0(\n    (tv[0].x() + tv[2].x()) / 2,\n    (tv[0].y() + tv[2].y()) / 2);\n  const Point midpoint1(\n    (tv[1].x() + tv[3].x()) / 2,\n    (tv[1].y() + tv[3].y()) / 2);\n\n  // Get the transformed graticule cell as a polygon\n  Polygon trans_graticule;\n  for (unsigned int i = 0; i < 4; ++i) {\n    trans_graticule.push_back(tv[i]);\n  }\n\n  // Check if graticule cell is concave\n  if (!trans_graticule.is_convex()) {\n    *num_concave += 1;\n  }\n  if (trans_graticule.bounded_side(midpoint0) == CGAL::ON_BOUNDED_SIDE) {\n    return 0;\n  }\n  if (trans_graticule.bounded_side(midpoint1) == CGAL::ON_BOUNDED_SIDE) {\n    return 1;\n  }\n  std::cerr << \"Invalid graticule cell! At\\n\";\n  std::cerr << \"(\" << tv[0].x() << \", \" << tv[0].y() << \")\\n\";\n  std::cerr << \"(\" << tv[1].x() << \", \" << tv[1].y() << \")\\n\";\n  std::cerr << \"(\" << tv[2].x() << \", \" << tv[2].y() << \")\\n\";\n  std::cerr << \"(\" << tv[3].x() << \", \" << tv[3].y() << \")\\n\";\n  std::cerr << \"Original: \\n\";\n  std::cerr << \"(\" << v[0].x() << \", \" << v[0].y() << \")\\n\";\n  std::cerr << \"(\" << v[1].x() << \", \" << v[1].y() << \")\\n\";\n  std::cerr << \"(\" << v[2].x() << \", \" << v[2].y() << \")\\n\";\n  std::cerr << \"(\" << v[3].x() << \", \" << v[3].y() << \")\\n\";\n  std::cerr << \"i: \"\n            << static_cast<unsigned int>(v[0].x())\n            << \", j: \"\n            << static_cast<unsigned int>(v[0].y())\n            << std::endl;\n  exit(1);\n}\n\nvoid InsetState::fill_graticule_diagonals()\n{\n  // Initialize array if running for the first time\n  if (graticule_diagonals_.shape()[0] != lx_ ||\n      graticule_diagonals_.shape()[1] != ly_) {\n    graticule_diagonals_.resize(boost::extents[lx_ - 1][ly_ - 1]);\n  }\n  unsigned int n_concave = 0;  // Count concave graticule cells\n  for (unsigned int i = 0; i < lx_ - 1; ++i) {\n    for (unsigned int j = 0; j < ly_ - 1; ++j) {\n      Point v[4];\n      v[0] = Point(double(i) + 0.5, double(j) + 0.5);\n      v[1] = Point(double(i) + 1.5, double(j) + 0.5);\n      v[2] = Point(double(i) + 1.5, double(j) + 1.5);\n      v[3] = Point(double(i) + 0.5, double(j) + 1.5);\n      graticule_diagonals_[i][j] = chosen_diag(v, &n_concave);\n    }\n  }\n  std::cerr << \"Number of concave graticule cells: \"\n            << n_concave\n            << std::endl;\n  return;\n}\n\nstd::array<Point, 3> InsetState::transformed_triangle(const std::array<Point, 3>\n                                                      tri)\n{\n  std::array<Point, 3> transf_tri;\n  for (unsigned int i = 0; i < 3; ++i) {\n    exit_if_not_on_grid_or_edge(tri[i]);\n    const auto transf_pt = projected_point(tri[i]);\n    transf_tri[i] = transf_pt;\n  }\n  return transf_tri;\n}\n\n// Determine if a point `pt` is on the boundary of a triangle by using cross\n// products to find areas spanned by pt and each triangle edge. Idea from:\n// https://stackoverflow.com/questions/7050186/find-if-point-lies-on-line-segment\n// This function is needed because, sometimes,\n// `triangle.bounded_side(Point(x, y)) == CGAL::ON_BOUNDARY` does not return\n// `true` even if the point is on the boundary.\nbool is_on_triangle_boundary(const Point pt, const Polygon triangle)\n{\n  for (unsigned int i = 0; i < triangle.size(); ++i) {\n    const auto t1 = triangle[i];\n    const auto t2 = triangle[(i == triangle.size() - 1) ? 0 : i + 1];\n    const double area = (t1.x() - pt.x()) * (t2.y() - pt.y()) -\n                        (t2.x() - pt.x()) * (t1.y() - pt.y());\n    if (almost_equal(area, 0.0)) {\n      return true;\n    }\n  }\n  return false;\n}\n\n// Get the untransformed coordinates of the triangle in which the point `pt`\n// is located. After transformation, this triangle must be entirely inside\n// the transformed graticule cell.\nstd::array<Point, 3> InsetState::untransformed_triangle(const Point pt)\n{\n  if (pt.x() < 0 || pt.x() > lx_ || pt.y() < 0 || pt.y() > ly_) {\n    CGAL::set_pretty_mode(std::cerr);\n    std::cerr << \"ERROR: coordinate outside bounding box in \"\n              << __func__\n              << \"().\\npt = \"\n              << pt\n              << std::endl;\n    exit(1);\n  }\n\n  // Get original graticule coordinates\n  Point v[4];\n  v[0] = Point(std::max(0.0, floor(pt.x() + 0.5) - 0.5),\n               std::max(0.0, floor(pt.y() + 0.5) - 0.5));\n  v[1] = Point(std::min(static_cast<double>(lx_), floor(pt.x() + 0.5) + 0.5),\n               v[0].y());\n  v[2] = Point(v[1].x(),\n               std::min(static_cast<double>(ly_), floor(pt.y() + 0.5) + 0.5));\n  v[3] = Point(v[0].x(),\n               v[2].y());\n\n  // TODO: diag SEEMS TO BE MORE NATURALLY THOUGHT OF AS bool INSTEAD OF int.\n  // Assuming that the transformed graticule does not have self-intersections,\n  // at least one of the diagonals must be completely inside the graticule.\n  // We use that diagonal to split the graticule into two triangles.\n  int diag;\n  if (v[0].x() == 0.0 || v[0].y() == 0.0 || v[2].x() == lx_ || v[2].y() == ly_) {\n\n    // Case where the graticule is on the edge of the grid.\n    // We calculate the chosen diagonal, as graticule_diagonals does not store\n    // the diagonals for edge grid cells.\n    unsigned int n_concave = 0;\n    diag = chosen_diag(v, &n_concave);\n  } else {\n\n    // Case where the graticule is not on the edge of the grid. We can find the\n    // already computed chosen diagonal in graticule_diagonals_.\n    const unsigned int x = static_cast<unsigned int>(v[0].x());\n    const unsigned int y = static_cast<unsigned int>(v[0].y());\n    diag = graticule_diagonals_[x][y];\n  }\n\n  // Get the two possible triangles\n  Polygon triangle1;\n  Polygon triangle2;\n  if (diag == 0) {\n    triangle1.push_back(v[0]);\n    triangle1.push_back(v[1]);\n    triangle1.push_back(v[2]);\n    triangle2.push_back(v[0]);\n    triangle2.push_back(v[2]);\n    triangle2.push_back(v[3]);\n  } else {\n    triangle1.push_back(v[0]);\n    triangle1.push_back(v[1]);\n    triangle1.push_back(v[3]);\n    triangle2.push_back(v[1]);\n    triangle2.push_back(v[2]);\n    triangle2.push_back(v[3]);\n  }\n\n  // Determine which untransformed triangle the given point is in. If the\n  // point is in neither, an error is raised.\n  std::array<Point, 3> triangle_coordinates;\n  if ((triangle1.bounded_side(pt) == CGAL::ON_BOUNDED_SIDE) ||\n      is_on_triangle_boundary(pt, triangle1)) {\n    for (unsigned int i = 0; i < triangle1.size(); ++i) {\n      triangle_coordinates[i] = triangle1[i];\n    }\n  } else if ((triangle2.bounded_side(pt) == CGAL::ON_BOUNDED_SIDE) ||\n             is_on_triangle_boundary(pt, triangle2)) {\n    for (unsigned int i = 0; i < triangle2.size(); ++i) {\n      triangle_coordinates[i] = triangle2[i];\n    }\n  } else {\n    std::cerr << \"Point not in graticule cell!\\n\";\n    std::cerr << \"Point coordinates:\\n\";\n    std::cerr << \"(\" << pt.x() << \", \" << pt.y() << \")\\n\";\n    std::cerr << \"Original graticule cell:\\n\";\n    std::cerr << \"(\" << v[0].x() << \", \" << v[0].y() << \")\\n\";\n    std::cerr << \"(\" << v[1].x() << \", \" << v[1].y() << \")\\n\";\n    std::cerr << \"(\" << v[2].x() << \", \" << v[2].y() << \")\\n\";\n    std::cerr << \"(\" << v[3].x() << \", \" << v[3].y() << \")\\n\";\n    std::cerr << \"Chosen diagonal: \" << diag << \"\\n\";\n    exit(1);\n  }\n  return triangle_coordinates;\n}\n\nPoint affine_trans(const std::array<Point, 3> tri,\n                   const std::array<Point, 3> org_tri,\n                   const Point pt)\n{\n  // For each point, we make the following transformation. Suppose we find\n  // that, before the cartogram transformation, a point (x, y) is in the\n  // triangle (a, b, c). We want to find its position in the projected\n  // triangle (p, q, r). We locally approximate the cartogram transformation\n  // by an affine transformation T such that T(a) = p, T(b) = q and T(c) = r.\n  // We can think of T as a 3x3 matrix\n  //    -----------\n  //   |t11 t12 t13|\n  //   |t21 t22 t23|  such that\n  //   | 0   0   1 |\n  //    -----------\n  //    -----------   ----------     ----------\n  //   |t11 t12 t13| | a1 b1 c1 |   | p1 q1 r1 |\n  //   |t21 t22 t23| | a2 b2 c2 | = | p2 q2 r2 | or TA = P.\n  //   | 0   0   1 | | 1  1  1  |   |  1  1  1 |\n  //    -----------   ----------     ----------\n  // Hence, T = PA^{-1}.\n  //                              -----------------------\n  //                             |b2-c2 c1-b1 b1*c2-b2*c1|\n  // We have A^{-1} = (1/det(A)) |c2-a2 a1-c1 a2*c1-a1*c2|. By multiplying\n  //                             |a2-b2 b1-a1 a1*b2-a2*b1|\n  //                              -----------------------\n  // PA^{-1} we obtain t11, t12, t13, t21, t22, and t23. If the original\n  // coordinates are (x, y) on the unprojected map, then the transformed\n  // coordinates are:\n  // post.x = t11*x + t12*y + t13, post.y = t21*x + t22*y + t23.\n  const Point pre(pt.x(),pt.y());\n\n  // Old triangle (a, b, c) expressed as matrix A\n  const Matrix abc_mA(org_tri[0], org_tri[1], org_tri[2]);\n\n  // New triangle (p, q, r) expressed as matrix P\n  const Matrix pqr_mP(tri[0], tri[1], tri[2]);\n\n  // Transformation matrix T\n  const auto mT = pqr_mP.multiplied_with(abc_mA.inverse());\n\n  // Transformed point\n  return mT.transformed_point(pre);\n}\n\nPoint InsetState::projected_point_with_triangulation(const Point pt)\n{\n  // Get the untransformed triangle the point is in\n  const auto old_triangle = untransformed_triangle(pt);\n\n  // Get the coordinates of the transformed triangle\n  const auto new_triangle = transformed_triangle(old_triangle);\n\n  // Get the transformed point and return it\n  const auto transformed_pt = affine_trans(new_triangle, old_triangle, pt);\n  return rounded_point(transformed_pt, lx_, ly_);\n}\n\nvoid InsetState::project_with_triangulation()\n{\n\n  // Store reference to current object and call member function\n  // projected_point_with_triangulation\n  // https://www.nextptr.com/tutorial/ta1430524603/\n  // capture-this-in-lambda-expression-timeline-of-change\n  std::function<Point(Point)> lambda =\n    [&](Point p1) {\n      return projected_point_with_triangulation(p1);\n    };\n\n  // Transforming all points based on triangulation\n  transform_points(lambda);\n\n  // Cumulative projection\n  for (unsigned int i = 0; i < lx_; ++i) {\n    for (unsigned int j = 0; j < ly_; ++j) {\n      const Point old_cum_proj(cum_proj_[i][j].x, cum_proj_[i][j].y);\n      const auto new_cum_proj_pt =\n        projected_point_with_triangulation(old_cum_proj);\n      cum_proj_[i][j].x = new_cum_proj_pt.x();\n      cum_proj_[i][j].y = new_cum_proj_pt.y();\n    }\n  }\n  return;\n}\n", "meta": {"hexsha": "f6ec10827cbfd75654d2566135d2f7ad3986959c", "size": 14874, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/inset_state/project.cpp", "max_stars_repo_name": "mgastner/cartogram-cpp", "max_stars_repo_head_hexsha": "007e4cf87c9590abef280feb43052280c454a0c5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/inset_state/project.cpp", "max_issues_repo_name": "mgastner/cartogram-cpp", "max_issues_repo_head_hexsha": "007e4cf87c9590abef280feb43052280c454a0c5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2022-03-13T02:58:14.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-26T09:53:52.000Z", "max_forks_repo_path": "src/inset_state/project.cpp", "max_forks_repo_name": "mgastner/cartogram-cpp", "max_forks_repo_head_hexsha": "007e4cf87c9590abef280feb43052280c454a0c5", "max_forks_repo_licenses": ["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.6354679803, "max_line_length": 81, "alphanum_fraction": 0.5752319484, "num_tokens": 4652, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.5926665999540697, "lm_q1q2_score": 0.4622757401819153}}
{"text": "#include \"learning/learningIO.h\"\n#include <learning/learningMath.h>\n#include <processing/graphCut.h>\n#include <util/helper.h>\n#include <cstdlib>\n#include <ctime>\n#include <CGAL/Random.h>\n#include <boost/filesystem.hpp>\n\n#include <xtensor/xbuilder.hpp>\n#include <xtensor/xmath.hpp>\n#include <xtensor-io/xnpz.hpp>\n\nnamespace fs = boost::filesystem;\n\n///////////////////////////////////////////////////////////////////////////////////\n//////////////////////////////// EXPORT FROM POISSON INPUT ///////////////////////////////\n///////////////////////////////////////////////////////////////////////////////////\n\n\n\nvoid cellIndexAndLabel(ofstream& out, Delaunay& Dt, Delaunay::All_cells_iterator& fci, int idx, runningOptions options){\n\n    if(options.ground_truth){\n        //    il << \"global_index inside_perc outside_perc inside_outside_max gc_label\" << endl;\n        out << idx << \" \";\n        out << fci->info().inside_score << \" \";\n        out << fci->info().outside_score << \" \";\n        // this means 50/50 cells will be labelled as inside\n        int l = fci->info().outside_score > fci->info().inside_score ? 1 : 0;\n        out << l << \" \";\n        out << fci->info().gc_label << \" \";\n        out << Dt.is_infinite(fci) << endl;\n    }\n    else\n        out << \"999 999 999 999 999 \" << Dt.is_infinite(fci) << endl;\n\n\n\n}\nvoid cellBasedGeometricFeatures(ofstream& out, Delaunay& Dt, Delaunay::All_cells_iterator& fci){\n\n//        cgeom << \"radius vol longest_edge shortest_edge\" << endl;\n    if(Dt.is_infinite(fci))\n        out << \"0 0 0 0\" << endl;\n    else{\n        auto tet = Dt.tetrahedron(fci);\n        tetFeatures tf = calcTetFeatures(tet);\n        out << tf.radius << \" \";\n        out << tf.vol << \" \";\n        out << tf.longest_edge << \" \";\n        out << tf.shortest_edge << \" \";\n        out << endl;\n    }\n}\n\nvoid cellBasedVertexFeatures(ofstream& out, Delaunay& Dt, Delaunay::All_cells_iterator& fci){\n\n//    cbvf << \"cb_vertex_inside_count cb_vertex_inside_dist_min cb_vertex_inside_dist_max cb_vertex_inside_dist_sum \";\n//    cbvf << \"cb_vertex_outside_count cb_vertex_outside_dist_min cb_vertex_outside_dist_max cb_vertex_outside_dist_sum \";\n//    cbvf << \"cb_vertex_last_count cb_vertex_last_dist_min cb_vertex_last_dist_max cb_vertex_last_dist_sum\" << endl;\n\n    // inside\n    int vdi = fci->info().cb_vertex_inside.size();\n    out << vdi << \" \";\n    if(vdi > 0){\n        out << *min_element(fci->info().cb_vertex_inside.begin(), fci->info().cb_vertex_inside.end()) << \" \";\n        out << *max_element(fci->info().cb_vertex_inside.begin(), fci->info().cb_vertex_inside.end()) << \" \";\n        out << accumulate(fci->info().cb_vertex_inside.begin(), fci->info().cb_vertex_inside.end(),0.0) << \" \";\n\n    }\n    else\n        out << \"0 0 0 \";\n    // outside\n    int vdo = fci->info().cb_vertex_outside.size();\n    out << vdo << \" \";\n    if(vdo > 0){\n        out << *min_element(fci->info().cb_vertex_outside.begin(), fci->info().cb_vertex_outside.end()) << \" \";\n        out << *max_element(fci->info().cb_vertex_outside.begin(), fci->info().cb_vertex_outside.end()) << \" \";\n        out << accumulate(fci->info().cb_vertex_outside.begin(), fci->info().cb_vertex_outside.end(),0.0) << \" \";\n    }\n    else\n        out << \"0 0 0 \";\n    // last\n    int vdl = fci->info().cb_vertex_last.size();\n    out << vdl << \" \";\n    if(vdl > 0){\n        out << *min_element(fci->info().cb_vertex_last.begin(), fci->info().cb_vertex_last.end()) << \" \";\n        out << *max_element(fci->info().cb_vertex_last.begin(), fci->info().cb_vertex_last.end()) << \" \";\n        out << accumulate(fci->info().cb_vertex_last.begin(), fci->info().cb_vertex_last.end(),0.0) << \" \";\n    }\n    else\n        out << \"0 0 0 \";\n\n    out << endl;\n}\n\nvoid cellBasedFacetFeatures(ofstream& out, Delaunay& Dt, Delaunay::All_cells_iterator& fci){\n\n//    cbff << \"cb_facet_inside_first_count cb_facet_inside_first_dist_min cb_facet_inside_first_dist_max cb_facet_inside_first_dist_sum \";\n//    cbff << \"cb_facet_inside_second_count cb_facet_inside_second_dist_min cb_facet_inside_second_dist_max cb_facet_inside_second_dist_sum \";\n//    cbff << \"cb_facet_outside_first_count cb_facet_outside_first_dist_min cb_facet_outside_first_dist_max cb_facet_outside_first_dist_sum \";\n//    cbff << \"cb_facet_outside_second_count cb_facet_outside_second_dist_min cb_facet_outside_second_dist_max cb_facet_outside_second_dist_sum \";\n//    cbff << \"cb_facet_last_first_count cb_facet_last_first_dist_min cb_facet_last_first_dist_max cb_facet_last_first_dist_sum\" << endl;\n//    cbff << \"cb_facet_last_second_count cb_facet_last_second_dist_min cb_facet_last_second_dist_max cb_facet_last_second_dist_sum\" << endl;\n\n    // inside first\n    int fdif = fci->info().cb_facet_inside_first.size();\n    out << fdif << \" \";\n    if(fdif > 0){\n        out << *min_element(fci->info().cb_facet_inside_first.begin(), fci->info().cb_facet_inside_first.end()) << \" \";\n        out << *max_element(fci->info().cb_facet_inside_first.begin(), fci->info().cb_facet_inside_first.end()) << \" \";\n        out << accumulate(fci->info().cb_facet_inside_first.begin(), fci->info().cb_facet_inside_first.end(),0.0) << \" \";\n    }\n    else\n        out << \"0 0 0 \";\n    // inside second\n    int fdis = fci->info().cb_facet_inside_second.size();\n    out << fdis << \" \";\n    if(fdis > 0){\n        out << *min_element(fci->info().cb_facet_inside_second.begin(), fci->info().cb_facet_inside_second.end()) << \" \";\n        out << *max_element(fci->info().cb_facet_inside_second.begin(), fci->info().cb_facet_inside_second.end()) << \" \";\n        out << accumulate(fci->info().cb_facet_inside_second.begin(), fci->info().cb_facet_inside_second.end(),0.0) << \" \";\n    }\n    else\n        out << \"0 0 0 \";\n    // outside first\n    int fdof = fci->info().cb_facet_outside_first.size();\n    out << fdof << \" \";\n    if(fdof > 0){\n        out << *min_element(fci->info().cb_facet_outside_first.begin(), fci->info().cb_facet_outside_first.end()) << \" \";\n        out << *max_element(fci->info().cb_facet_outside_first.begin(), fci->info().cb_facet_outside_first.end()) << \" \";\n        out << accumulate(fci->info().cb_facet_outside_first.begin(), fci->info().cb_facet_outside_first.end(),0.0) << \" \";\n    }\n    else\n        out << \"0 0 0 \";\n    // outside second\n    int fdos = fci->info().cb_facet_outside_second.size();\n    out << fdos << \" \";\n    if(fdos > 0){\n        out << *min_element(fci->info().cb_facet_outside_second.begin(), fci->info().cb_facet_outside_second.end()) << \" \";\n        out << *max_element(fci->info().cb_facet_outside_second.begin(), fci->info().cb_facet_outside_second.end()) << \" \";\n        out << accumulate(fci->info().cb_facet_outside_second.begin(), fci->info().cb_facet_outside_second.end(),0.0) << \" \";\n    }\n    else\n        out << \"0 0 0 \";\n    // last first\n    int fdlf = fci->info().cb_facet_last_first.size();\n    out << fdlf << \" \";\n    if(fdlf > 0){\n        out << *min_element(fci->info().cb_facet_last_first.begin(), fci->info().cb_facet_last_first.end()) << \" \";\n        out << *max_element(fci->info().cb_facet_last_first.begin(), fci->info().cb_facet_last_first.end()) << \" \";\n        out << accumulate(fci->info().cb_facet_last_first.begin(), fci->info().cb_facet_last_first.end(),0.0) << \" \";\n    }\n    else\n        out << \"0 0 0 \";\n    // last second\n    int fdls = fci->info().cb_facet_last_second.size();\n    out << fdls << \" \";\n    if(fdls > 0){\n        out << *min_element(fci->info().cb_facet_last_second.begin(), fci->info().cb_facet_last_second.end()) << \" \";\n        out << *max_element(fci->info().cb_facet_last_second.begin(), fci->info().cb_facet_last_second.end()) << \" \";\n        out << accumulate(fci->info().cb_facet_last_second.begin(), fci->info().cb_facet_last_second.end(),0.0) << \" \";\n    }\n    else\n        out << \"0 0 0 \";\n\n    out << endl;\n}\n\nvoid facetBasedGeometricFeatures(ofstream& out, Delaunay& Dt, Delaunay::All_cells_iterator& fci, int j){\n\n//    fgeom << \"area angle beta dist\" << endl;\n    // export the area and angle off the current facet as edge feature\n    auto fac = make_pair(fci,j);\n    out << computeFacetArea(Dt,fac) << \" \";\n    out << computeCosFacetCellAngle(Dt,fac) << \" \";\n    out << 1-min(computeCosFacetCellAngle(Dt, fac),\n                             computeCosFacetCellAngle(Dt, Dt.mirror_facet(fac))) << \" \";\n\n    auto neighbor = fci->neighbor(j);\n    if(!Dt.is_infinite(neighbor) && !Dt.is_infinite(fci)){\n        auto cen1 = CGAL::centroid(fci->vertex(0)->point(),\n                                   fci->vertex(1)->point(),\n                                   fci->vertex(2)->point(),\n                                   fci->vertex(3)->point());\n        auto cen2 = CGAL::centroid(neighbor->vertex(0)->point(),\n                       neighbor->vertex(1)->point(),\n                       neighbor->vertex(2)->point(),\n                       neighbor->vertex(3)->point());\n        out << CGAL::squared_distance(cen1,cen2);\n    }\n    else\n        out << \"-1\";\n    out << endl;\n}\nvoid facetBasedVertexFeatures(ofstream& out, Delaunay& Dt, Delaunay::All_cells_iterator& fci, int j){\n\n//    fbvf << \"fb_vertex_inside_count fb_vertex_inside_dist_min fb_vertex_inside_dist_max fb_vertex_inside_dist_sum \";\n//    fbvf << \"fb_vertex_outside_count fb_vertex_outside_dist_min fb_vertex_outside_dist_max fb_vertex_outside_dist_sum\" << endl;\n//    fbvf << \"fb_vertex_last_count fb_vertex_last_dist_min fb_vertex_last_dist_max fb_vertex_last_dist_sum\" << endl;\n\n    // inside\n    int vdi = fci->info().fb_vertex_inside[j].size();\n    out << vdi << \" \";\n    if(vdi > 0){\n        out << *min_element(fci->info().fb_vertex_inside[j].begin(), fci->info().fb_vertex_inside[j].end()) << \" \";\n        out << *max_element(fci->info().fb_vertex_inside[j].begin(), fci->info().fb_vertex_inside[j].end()) << \" \";\n        out << accumulate(fci->info().fb_vertex_inside[j].begin(), fci->info().fb_vertex_inside[j].end(),0.0) << \" \";\n\n    }\n    else\n        out << \"0 0 0 \";\n    // outside\n    int vdo = fci->info().fb_vertex_outside[j].size();\n    out << vdo << \" \";\n    if(vdo > 0){\n        out << *min_element(fci->info().fb_vertex_outside[j].begin(), fci->info().fb_vertex_outside[j].end()) << \" \";\n        out << *max_element(fci->info().fb_vertex_outside[j].begin(), fci->info().fb_vertex_outside[j].end()) << \" \";\n        out << accumulate(fci->info().fb_vertex_outside[j].begin(), fci->info().fb_vertex_outside[j].end(),0.0) << \" \";\n    }\n    else\n        out << \"0 0 0 \";\n    // last\n    int vdl = fci->info().fb_vertex_last[j].size();\n    out << vdl << \" \";\n    if(vdl > 0){\n        out << *min_element(fci->info().fb_vertex_last[j].begin(), fci->info().fb_vertex_last[j].end()) << \" \";\n        out << *max_element(fci->info().fb_vertex_last[j].begin(), fci->info().fb_vertex_last[j].end()) << \" \";\n        out << accumulate(fci->info().fb_vertex_last[j].begin(), fci->info().fb_vertex_last[j].end(),0.0) << \" \";\n    }\n    else\n        out << \"0 0 0 \";\n\n    out << endl;\n\n}\n\nvoid facetBasedFacetFeatures(ofstream& out, Delaunay& Dt, Delaunay::All_cells_iterator& fci, int j){\n\n//    fbff << \"fb_facet_inside_count fb_facet_inside_dist_min fb_facet_inside_dist_max fb_facet_inside_dist_sum \";\n//    fbff << \"fb_facet_outside_count fb_facet_outside_dist_min fb_facet_outside_dist_max fb_facet_outside_dist_sum\" << endl;\n//    fbff << \"fb_facet_last_count fb_facet_last_dist_min fb_facet_last_dist_max fb_facet_last_dist_sum\" << endl;\n\n    // inside\n    int vdi = fci->info().fb_facet_inside[j].size();\n    out << vdi << \" \";\n    if(vdi > 0){\n        out << *min_element(fci->info().fb_facet_inside[j].begin(), fci->info().fb_facet_inside[j].end()) << \" \";\n        out << *max_element(fci->info().fb_facet_inside[j].begin(), fci->info().fb_facet_inside[j].end()) << \" \";\n        out << accumulate(fci->info().fb_facet_inside[j].begin(), fci->info().fb_facet_inside[j].end(),0.0) << \" \";\n\n    }\n    else\n        out << \"0 0 0 \";\n    // outside\n    int vdo = fci->info().fb_facet_outside[j].size();\n    out << vdo << \" \";\n    if(vdo > 0){\n        out << *min_element(fci->info().fb_facet_outside[j].begin(), fci->info().fb_facet_outside[j].end()) << \" \";\n        out << *max_element(fci->info().fb_facet_outside[j].begin(), fci->info().fb_facet_outside[j].end()) << \" \";\n        out << accumulate(fci->info().fb_facet_outside[j].begin(), fci->info().fb_facet_outside[j].end(),0.0) << \" \";\n    }\n    else\n        out << \"0 0 0 \";\n    // last\n    int vdl = fci->info().fb_facet_last[j].size();\n    out << vdl << \" \";\n    if(vdl > 0){\n        out << *min_element(fci->info().fb_facet_last[j].begin(), fci->info().fb_facet_last[j].end()) << \" \";\n        out << *max_element(fci->info().fb_facet_last[j].begin(), fci->info().fb_facet_last[j].end()) << \" \";\n        out << accumulate(fci->info().fb_facet_last[j].begin(), fci->info().fb_facet_last[j].end(),0.0) << \" \";\n    }\n    else\n        out << \"0 0 0 \";\n\n    out << endl;\n\n}\n\n\n\n\n\nvoid exportGraph(dirHolder& dir, runningOptions& options, Delaunay& Dt){\n\n    auto start = std::chrono::high_resolution_clock::now();\n    cout << \"\\nExport graph...\" << endl;\n    boost::filesystem::path p(dir.write_file);\n    string outfile = p.stem().string();\n    cout << \"\\t-to \" << \"gt/\"+outfile+\"_X.txt\" << endl;\n    string rays = (options.export_rays) ? \"\\t-with rays\" : \"\\t-without rays\";\n    cout << rays << endl;\n    int print_precision = 8;\n\n\n    ////////////////////////////////////////////\n    //////////////    HEADERS    ///////////////\n    ////////////////////////////////////////////\n\n    /////////////////////////////////////////////\n    //////////////////// CELLS //////////////////\n    /////////////////////////////////////////////\n    ////// info file\n    ofstream info;\n    info.open(dir.path+\"gt/\"+outfile+\"_info.txt\");\n    info << \"vertices \" << Dt.number_of_vertices() << endl;\n    info << \"facets \" << Dt.number_of_facets() << endl;\n    info << \"cells \" << Dt.number_of_cells() << endl;\n    info.close();\n\n    ////// label and index\n    // cell index and labels\n    ofstream il;\n    il.open(dir.path+\"gt/\"+outfile+\"_labels.txt\");\n    il << \"global_index inside_perc outside_perc inside_outside_max gc_label infinite\" << endl;\n\n    ////// geometric features\n    ofstream cgeom;\n    cgeom.open(dir.path+\"gt/\"+outfile+\"_cgeom.txt\");\n    cgeom << \"radius vol longest_edge shortest_edge\" << endl;\n    cgeom << setprecision(print_precision);\n\n    ////// cell based vertex features\n    ofstream cbvf;\n    cbvf.open(dir.path+\"gt/\"+outfile+\"_cbvf.txt\");\n    cbvf << \"cb_vertex_inside_count cb_vertex_inside_dist_min cb_vertex_inside_dist_max cb_vertex_inside_dist_sum \";\n    cbvf << \"cb_vertex_outside_count cb_vertex_outside_dist_min cb_vertex_outside_dist_max cb_vertex_outside_dist_sum \";\n    cbvf << \"cb_vertex_last_count cb_vertex_last_dist_min cb_vertex_last_dist_max cb_vertex_last_dist_sum\" << endl;\n    cbvf << setprecision(print_precision);\n\n    ////// cell based facet features\n    ofstream cbff;\n    cbff.open(dir.path+\"gt/\"+outfile+\"_cbff.txt\");\n    cbff << \"cb_facet_inside_first_count cb_facet_inside_first_dist_min cb_facet_inside_first_dist_max cb_facet_inside_first_dist_sum \";\n    cbff << \"cb_facet_inside_second_count cb_facet_inside_second_dist_min cb_facet_inside_second_dist_max cb_facet_inside_second_dist_sum \";\n    cbff << \"cb_facet_outside_first_count cb_facet_outside_first_dist_min cb_facet_outside_first_dist_max cb_facet_outside_first_dist_sum \";\n    cbff << \"cb_facet_outside_second_count cb_facet_outside_second_dist_min cb_facet_outside_second_dist_max cb_facet_outside_second_dist_sum \";\n    cbff << \"cb_facet_last_first_count cb_facet_last_first_dist_min cb_facet_last_first_dist_max cb_facet_last_first_dist_sum \";\n    cbff << \"cb_facet_last_second_count cb_facet_last_second_dist_min cb_facet_last_second_dist_max cb_facet_last_second_dist_sum\" << endl;\n    cbff << setprecision(print_precision);\n\n\n    /////////////////////////////////////////////\n    //////////////////// EDGES //////////////////\n    /////////////////////////////////////////////\n    // adjacency files\n    ofstream adjacency_ij, adjacency_ji;\n    adjacency_ij.open(dir.path+\"gt/\"+outfile+\"_adjacency_ij.txt\");\n    adjacency_ij << \"# list of edges\" << endl;\n    adjacency_ji.open(dir.path+\"gt/\"+outfile+\"_adjacency_ji.txt\");\n    adjacency_ji << \"# list of edges\" << endl;\n\n    // geometric features\n    ofstream fgeom;\n    fgeom.open(dir.path+\"gt/\"+outfile+\"_fgeom.txt\");\n    fgeom << \"area angle beta dist\" << endl;\n    // facet based vertex features\n    ofstream fbvf;\n    fbvf.open(dir.path+\"gt/\"+outfile+\"_fbvf.txt\");\n    fbvf << \"fb_vertex_inside_count fb_vertex_inside_dist_min fb_vertex_inside_dist_max fb_vertex_inside_dist_sum \";\n    fbvf << \"fb_vertex_outside_count fb_vertex_outside_dist_min fb_vertex_outside_dist_max fb_vertex_outside_dist_sum \";\n    fbvf << \"fb_vertex_last_count fb_vertex_last_dist_min fb_vertex_last_dist_max fb_vertex_last_dist_sum\" << endl;\n\n    // facet based facet features\n    ofstream fbff;\n    fbff.open(dir.path+\"gt/\"+outfile+\"_fbff.txt\");\n    fbff << \"fb_facet_inside_count fb_facet_inside_dist_min fb_facet_inside_dist_max fb_facet_inside_dist_sum \";\n    fbff << \"fb_facet_outside_count fb_facet_outside_dist_min fb_facet_outside_dist_max fb_facet_outside_dist_sum \";\n    fbff << \"fb_facet_last_count fb_facet_last_dist_min fb_facet_last_dist_max fb_facet_last_dist_sum\" << endl;\n\n    int edge_count = 0;\n    int i, j;\n\n    string npz_out = dir.path+\"gt/\"+outfile+\"_npz.npz\";\n    Delaunay::All_cells_iterator fci;\n    for(fci = Dt.all_cells_begin(); fci != Dt.all_cells_end(); fci++){\n\n        // TODO: there is a problem here, not all cells are exported, running index i < nc at the end;\n        i = fci->info().global_idx;\n\n        /////////////////////////////////////////////\n        //////////////     LABELS    ////////////////\n        /////////////////////////////////////////////\n        cellIndexAndLabel(il, Dt, fci, i, options);\n\n        /////////////////////////////////////////////\n        ////////////// CELL FEATURES ////////////////\n        /////////////////////////////////////////////\n        cellBasedGeometricFeatures(cgeom, Dt, fci);\n        cellBasedVertexFeatures(cbvf,Dt,fci);\n        cellBasedFacetFeatures(cbff,Dt,fci);\n\n//        xt::xarray<double> radius;\n//        xt::xarray<double> vol;\n//        if(Dt.is_infinite(fci)){\n//            radius = {0.0};\n//            vol = {0.0};\n//        }\n//        else{\n//            auto tet = Dt.tetrahedron(fci);\n//            tetFeatures tf = calcTetFeatures(tet);\n//            radius = {tf.radius};\n//            vol = {tf.vol};\n//        }\n\n//        xt::dump_npz(npz_out,\"radius\",radius,true,true);\n//        xt::dump_npz(npz_out,\"volume\",vol,true,true);\n\n\n        /////////////////////////////////////////////\n        ////////////// EDGE FEATURES ////////////////\n        /////////////////////////////////////////////\n        for(int c = 0; c < 4; c++){\n            // set the edge to the mirror cell\n            j = fci->neighbor(c)->info().global_idx;\n\n            if(j == i) // skip self loops\n                continue;\n            adjacency_ij << i << \" \";\n            adjacency_ji << j << \" \";\n\n            //// geometric features\n            facetBasedGeometricFeatures(fgeom,Dt,fci,c);\n            facetBasedVertexFeatures(fbvf,Dt,fci,c);\n            facetBasedFacetFeatures(fbff,Dt,fci,c);\n\n            edge_count++;\n        }\n    }\n\n    il.close();\n    cgeom.close();\n    cbvf.close();\n    cbff.close();\n\n    adjacency_ij.close();\n    adjacency_ji.close();\n    fgeom.close();\n    fbvf.close();\n    fbff.close();\n\n    auto stop = std::chrono::high_resolution_clock::now();\n    auto duration = std::chrono::duration_cast<std::chrono::seconds>(stop - start);\n    cout << \"\\t-Exported \" << i << \" nodes and \" << edge_count << \" edges\" << endl;\n    cout << \"\\t-in \" << duration.count() << \"s\" << endl;\n}\n\n\n////////////////////////////////////////////////////////////////////////////////////////////////////////\n//////////////////////////////////////////////// IMPORT ////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////////////////////////////\nint loadPrediction(dirHolder dir, dataHolder& data, runningOptions options){\n\n\n    fs::path path = fs::path(dir.path) / fs::path(dir.prediction_file);\n    ifstream file(path.string());\n\n    cout << \"\\nLoad prediction score...\" << endl;\n    cout << \"\\t-from \" << path.string() << endl;\n\n    if(!file){\n        cout << \"\\nFILE DOES NOT EXIST OR IS EMPTY!\" << endl;\n        return 1;\n    }\n    auto npz_map = xt::load_npz(path.string());\n\n    Delaunay::All_cells_iterator fci;\n    int b = data.Dt.number_of_cells();\n    auto nc = npz_map[\"number_of_cells\"].cast<long>();\n    const int a = nc(0,0);\n    // check for same sampling of input and scan\n    if(a != b){\n        cout << \"ERROR: SAMPLING IS NOT THE SAME!\" << endl;\n        cout << \"\\t-\" << b << \" Delaunay cells\" << endl;\n        cout << \"\\t-\" << a << \" imported cells\" << endl;\n        return 1;\n    }\n\n    int i = 0;\n    array<size_t, 2> shape = { a, 2 };\n    xt::xtensor<float, 2> pred(shape);\n    if(options.prediction_type == \"lo\"){\n        pred = npz_map[\"logits\"].cast<float>();\n    }\n    else if(options.prediction_type == \"sm\"){\n        pred = npz_map[\"softmax\"].cast<float>();\n    }\n    else if(options.prediction_type == \"si\"){\n        pred = npz_map[\"sigmoid\"].cast<float>();\n    }\n    else{\n        cout << options.prediction_type << \" is not a valid prediction type, choose either lo or sm\" << endl;\n        return 1;\n    }\n    for(fci = data.Dt.all_cells_begin(); fci != data.Dt.all_cells_end(); fci++){\n\n        if(data.Dt.is_infinite(fci)){\n            fci->info().outside_score = 1.0;\n            fci->info().inside_score = 0.0;\n        }\n        else{\n\n            // check if there is a camera inside the cell\n            for(auto s = data.sensor_map.begin(); s != data.sensor_map.end(); s++){\n                if(data.Dt.tetrahedron(fci).has_on_positive_side(s->second)){\n                    fci->info().outside_score = 1000;\n                    fci->info().inside_score = -1000;\n                    break;\n                }\n            }\n\n\n//            xt::xtensor_fixed<double, xt::xshape<a, 2>> pred;\n            if(pred.shape(1)==1){\n//                cout << pred(i,0) << endl;\n                if(pred(i,0)<=0.0){\n                    fci->info().outside_score = 0;\n                    fci->info().inside_score = 1;\n                }\n                else{\n                    fci->info().outside_score = 1;\n                    fci->info().inside_score = 0;\n                }\n            }\n            else{\n                fci->info().inside_score = pred(i,0);\n                fci->info().outside_score = pred(i,1);\n                // TODO: maybe it should be\n                // fci->info().inside_score = pred(i,0) - pred(i,1);\n                // fci->info().outside_score = pred(i,1) - pred(i,0);\n                // because in the case of logits pred(i,0) = 1 - pred(i,1)\n                // UPDATE: in fact it doesn't matter! what matters in  the graph cut is the difference between the two labelling options.\n            }\n        }\n        i++;\n\n    }\n    cout<< \"\\t-read \" << a << \" cell scores. \" << endl;\n\n    return 0;\n}\n\n", "meta": {"hexsha": "4de7f9ad450a498320ed1fc0dca52854ff696828", "size": 23296, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/learning/learningIO.cpp", "max_stars_repo_name": "raphaelsulzer/mesh-tools", "max_stars_repo_head_hexsha": "73150bec58813e2b9b750205807002a1c3f18884", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-24T03:39:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T03:39:05.000Z", "max_issues_repo_path": "src/learning/learningIO.cpp", "max_issues_repo_name": "raphaelsulzer/mesh-tools", "max_issues_repo_head_hexsha": "73150bec58813e2b9b750205807002a1c3f18884", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-02-24T06:59:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T01:25:09.000Z", "max_forks_repo_path": "src/learning/learningIO.cpp", "max_forks_repo_name": "raphaelsulzer/mesh-tools", "max_forks_repo_head_hexsha": "73150bec58813e2b9b750205807002a1c3f18884", "max_forks_repo_licenses": ["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.8235294118, "max_line_length": 146, "alphanum_fraction": 0.5777815934, "num_tokens": 6162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257126, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.46227573411988776}}
{"text": "// Boost.Geometry\n\n// Copyright (c) 2017-2018 Oracle and/or its affiliates.\n\n// Contributed and/or modified by Vissarion Fysikopoulos, 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_FORMULAS_MERIDIAN_INVERSE_HPP\n#define BOOST_GEOMETRY_FORMULAS_MERIDIAN_INVERSE_HPP\n\n#include <boost/math/constants/constants.hpp>\n\n#include <boost/geometry/core/radius.hpp>\n\n#include <boost/geometry/util/condition.hpp>\n#include <boost/geometry/util/math.hpp>\n#include <boost/geometry/util/normalize_spheroidal_coordinates.hpp>\n\n#include <boost/geometry/formulas/flattening.hpp>\n#include <boost/geometry/formulas/meridian_segment.hpp>\n\nnamespace boost { namespace geometry { namespace formula\n{\n\n/*!\n\\brief Compute the arc length of an ellipse.\n*/\n\ntemplate <typename CT, unsigned int Order = 1>\nclass meridian_inverse\n{\n\npublic :\n\n    struct result\n    {\n        result()\n            : distance(0)\n            , meridian(false)\n        {}\n\n        CT distance;\n        bool meridian;\n    };\n\n    template <typename T>\n    static bool meridian_not_crossing_pole(T lat1, T lat2, CT diff)\n    {\n        CT half_pi = math::pi<CT>()/CT(2);\n        return math::equals(diff, CT(0)) ||\n                    (math::equals(lat2, half_pi) && math::equals(lat1, -half_pi));\n    }\n\n    static bool meridian_crossing_pole(CT diff)\n    {\n        return math::equals(math::abs(diff), math::pi<CT>());\n    }\n\n\n    template <typename T, typename Spheroid>\n    static CT meridian_not_crossing_pole_dist(T lat1, T lat2, Spheroid const& spheroid)\n    {\n        return math::abs(apply(lat2, spheroid) - apply(lat1, spheroid));\n    }\n\n    template <typename T, typename Spheroid>\n    static CT meridian_crossing_pole_dist(T lat1, T lat2, Spheroid const& spheroid)\n    {\n        CT c0 = 0;\n        CT half_pi = math::pi<CT>()/CT(2);\n        CT lat_sign = 1;\n        if (lat1+lat2 < c0)\n        {\n            lat_sign = CT(-1);\n        }\n        return math::abs(lat_sign * CT(2) * apply(half_pi, spheroid)\n                         - apply(lat1, spheroid) - apply(lat2, spheroid));\n    }\n\n    template <typename T, typename Spheroid>\n    static result apply(T lon1, T lat1, T lon2, T lat2, Spheroid const& spheroid)\n    {\n        result res;\n\n        CT diff = geometry::math::longitude_distance_signed<geometry::radian>(lon1, lon2);\n\n        if (lat1 > lat2)\n        {\n            std::swap(lat1, lat2);\n        }\n\n        if ( meridian_not_crossing_pole(lat1, lat2, diff) )\n        {\n            res.distance = meridian_not_crossing_pole_dist(lat1, lat2, spheroid);\n            res.meridian = true;\n        }\n        else if ( meridian_crossing_pole(diff) )\n        {\n            res.distance = meridian_crossing_pole_dist(lat1, lat2, spheroid);\n            res.meridian = true;\n        }\n        return res;\n    }\n\n    // Distance computation on meridians using series approximations\n    // to elliptic integrals. Formula to compute distance from lattitude 0 to lat\n    // https://en.wikipedia.org/wiki/Meridian_arc\n    // latitudes are assumed to be in radians and in [-pi/2,pi/2]\n    template <typename T, typename Spheroid>\n    static CT apply(T lat, Spheroid const& spheroid)\n    {\n        CT const a = get_radius<0>(spheroid);\n        CT const f = formula::flattening<CT>(spheroid);\n        CT n = f / (CT(2) - f);\n        CT M = a/(1+n);\n        CT C0 = 1;\n\n        if (Order == 0)\n        {\n           return M * C0 * lat;\n        }\n\n        CT C2 = -1.5 * n;\n\n        if (Order == 1)\n        {\n            return M * (C0 * lat + C2 * sin(2*lat));\n        }\n\n        CT n2 = n * n;\n        C0 += .25 * n2;\n        CT C4 = 0.9375 * n2;\n\n        if (Order == 2)\n        {\n            return M * (C0 * lat + C2 * sin(2*lat) + C4 * sin(4*lat));\n        }\n\n        CT n3 = n2 * n;\n        C2 += 0.1875 * n3;\n        CT C6 = -0.729166667 * n3;\n\n        if (Order == 3)\n        {\n            return M * (C0 * lat + C2 * sin(2*lat) + C4 * sin(4*lat)\n                      + C6 * sin(6*lat));\n        }\n\n        CT n4 = n2 * n2;\n        C4 -= 0.234375 * n4;\n        CT C8 = 0.615234375 * n4;\n\n        if (Order == 4)\n        {\n            return M * (C0 * lat + C2 * sin(2*lat) + C4 * sin(4*lat)\n                      + C6 * sin(6*lat) + C8 * sin(8*lat));\n        }\n\n        CT n5 = n4 * n;\n        C6 += 0.227864583 * n5;\n        CT C10 = -0.54140625 * n5;\n\n        // Order 5 or higher\n        return M * (C0 * lat + C2 * sin(2*lat) + C4 * sin(4*lat)\n                  + C6 * sin(6*lat) + C8 * sin(8*lat) + C10 * sin(10*lat));\n\n    }\n};\n\n}}} // namespace boost::geometry::formula\n\n\n#endif // BOOST_GEOMETRY_FORMULAS_MERIDIAN_INVERSE_HPP\n", "meta": {"hexsha": "43bec199703a7b5cf3fd074cfe675a311420f08d", "size": 4782, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/formulas/meridian_inverse.hpp", "max_stars_repo_name": "Harshitha91/Tmdb-react-native-node", "max_stars_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/formulas/meridian_inverse.hpp", "max_issues_repo_name": "Harshitha91/Tmdb-react-native-node", "max_issues_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/formulas/meridian_inverse.hpp", "max_forks_repo_name": "Harshitha91/Tmdb-react-native-node", "max_forks_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 27.0169491525, "max_line_length": 90, "alphanum_fraction": 0.5644081974, "num_tokens": 1410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257126, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.46227573411988776}}
{"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 \"toplevelfixture.hpp\"\n#include <boost/test/unit_test.hpp>\n#include <ql/termstructures/yield/piecewiseyieldcurve.hpp>\n#include <ql/termstructures/yield/ratehelpers.hpp>\n#include <ql/time/calendars/target.hpp>\n#include <ql/time/daycounters/actual360.hpp>\n#include <qle/pricingengines/depositengine.hpp>\n\n#include <boost/make_shared.hpp>\n\nusing namespace QuantLib;\nusing namespace QuantExt;\nusing namespace boost::unit_test_framework;\n\nBOOST_FIXTURE_TEST_SUITE(QuantExtTestSuite, qle::test::TopLevelFixture)\n\nBOOST_AUTO_TEST_SUITE(DepositTest)\n\nBOOST_AUTO_TEST_CASE(testRepricing) {\n\n    BOOST_TEST_MESSAGE(\"Testing Repricing of a Deposit on a depo curve...\");\n\n    SavedSettings backup;\n\n    Date refDate = Date(8, Dec, 2016);\n    Settings::instance().evaluationDate() = refDate;\n\n    std::vector<boost::shared_ptr<RateHelper> > helper;\n    helper.push_back(boost::make_shared<DepositRateHelper>(Handle<Quote>(boost::make_shared<SimpleQuote>(0.02)),\n                                                           7 * Months, 2, TARGET(), ModifiedFollowing, false,\n                                                           Actual360()));\n\n    Handle<YieldTermStructure> curve(\n        boost::make_shared<PiecewiseYieldCurve<Discount, LogLinear> >(refDate, helper, Actual365Fixed()));\n\n    boost::shared_ptr<PricingEngine> engine = boost::make_shared<DepositEngine>(curve);\n\n    Deposit depo(100.0, 0.02, 7 * Months, 2, TARGET(), ModifiedFollowing, false, Actual360(), refDate, true, 0 * Days);\n    depo.setPricingEngine(engine);\n\n    Real tol = 1.0E-8;\n    BOOST_CHECK_MESSAGE(std::abs(depo.NPV()) <= tol,\n                        \"Deposit NPV(\" << depo.NPV() << \") could not be verified, expected 0.0\");\n\n    BOOST_CHECK_MESSAGE(std::abs(depo.fairRate() - 0.02) <= tol,\n                        \"Deposit fair rate (\" << depo.fairRate() << \") could not be verified, expected 0.02\");\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "39d771d9f8f649083e680cb9fd4539e326587f44", "size": 2694, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QuantExt/test/deposit.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/test/deposit.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/test/deposit.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": 38.4857142857, "max_line_length": 119, "alphanum_fraction": 0.7086117298, "num_tokens": 634, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289835, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4622193933355144}}
{"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\n#include <random>\n#include <benchmark/benchmark.h>\n#include <boost/math/special_functions/jacobi_theta.hpp>\n#include <boost/multiprecision/float128.hpp>\n#include <boost/multiprecision/mpfr.hpp>\n#include <boost/multiprecision/cpp_bin_float.hpp>\n\nusing boost::multiprecision::number;\nusing boost::multiprecision::mpfr_float_backend;\nusing boost::multiprecision::float128;\nusing boost::multiprecision::cpp_bin_float_50;\nusing boost::multiprecision::cpp_bin_float_100;\nusing boost::math::jacobi_theta1;\nusing boost::math::jacobi_theta1tau;\n\ntemplate<class Real>\nvoid JacobiTheta1(benchmark::State& state)\n{\n    std::random_device rd;\n    std::mt19937_64 mt(rd());\n    std::uniform_real_distribution<long double> unif(0,0.01);\n\n    Real x = static_cast<Real>(unif(mt));\n    Real q = static_cast<Real>(unif(mt));\n    for (auto _ : state)\n    {\n        benchmark::DoNotOptimize(jacobi_theta1(x, q));\n        x += std::numeric_limits<Real>::epsilon();\n    }\n}\n\nBENCHMARK_TEMPLATE(JacobiTheta1, float);\nBENCHMARK_TEMPLATE(JacobiTheta1, double);\nBENCHMARK_TEMPLATE(JacobiTheta1, long double);\nBENCHMARK_TEMPLATE(JacobiTheta1, float128);\nBENCHMARK_TEMPLATE(JacobiTheta1, number<mpfr_float_backend<100>>);\nBENCHMARK_TEMPLATE(JacobiTheta1, number<mpfr_float_backend<200>>);\nBENCHMARK_TEMPLATE(JacobiTheta1, number<mpfr_float_backend<300>>);\nBENCHMARK_TEMPLATE(JacobiTheta1, number<mpfr_float_backend<400>>);\nBENCHMARK_TEMPLATE(JacobiTheta1, number<mpfr_float_backend<1000>>);\nBENCHMARK_TEMPLATE(JacobiTheta1, cpp_bin_float_50);\nBENCHMARK_TEMPLATE(JacobiTheta1, cpp_bin_float_100);\n\ntemplate<class Real>\nvoid JacobiTheta1Tau(benchmark::State& state)\n{\n    std::random_device rd;\n    std::mt19937_64 mt(rd());\n    std::uniform_real_distribution<long double> unif(0,0.01);\n\n    Real x = static_cast<Real>(unif(mt));\n    Real q = static_cast<Real>(unif(mt));\n    for (auto _ : state)\n    {\n        benchmark::DoNotOptimize(jacobi_theta1tau(x, q));\n        x += std::numeric_limits<Real>::epsilon();\n    }\n}\n\nBENCHMARK_TEMPLATE(JacobiTheta1Tau, float);\nBENCHMARK_TEMPLATE(JacobiTheta1Tau, double);\nBENCHMARK_TEMPLATE(JacobiTheta1Tau, long double);\nBENCHMARK_TEMPLATE(JacobiTheta1Tau, float128);\nBENCHMARK_TEMPLATE(JacobiTheta1Tau, number<mpfr_float_backend<100>>);\nBENCHMARK_TEMPLATE(JacobiTheta1Tau, number<mpfr_float_backend<200>>);\nBENCHMARK_TEMPLATE(JacobiTheta1Tau, number<mpfr_float_backend<300>>);\nBENCHMARK_TEMPLATE(JacobiTheta1Tau, number<mpfr_float_backend<400>>);\nBENCHMARK_TEMPLATE(JacobiTheta1Tau, number<mpfr_float_backend<1000>>);\nBENCHMARK_TEMPLATE(JacobiTheta1Tau, cpp_bin_float_50);\nBENCHMARK_TEMPLATE(JacobiTheta1Tau, cpp_bin_float_100);\n\nBENCHMARK_MAIN();\n", "meta": {"hexsha": "a1eea6ad0f0b497834070e27016ec90c66a0e359", "size": 2888, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "reporting/performance/jacobi_theta_performance.cpp", "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": "reporting/performance/jacobi_theta_performance.cpp", "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": "Libs/boost_1_76_0/libs/math/reporting/performance/jacobi_theta_performance.cpp", "max_forks_repo_name": "Antd23rus/S2DE", "max_forks_repo_head_hexsha": "47cc7151c2934cd8f0399a9856c1e54894571553", "max_forks_repo_licenses": ["MIT"], "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": 37.0256410256, "max_line_length": 70, "alphanum_fraction": 0.7783933518, "num_tokens": 788, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.46221938674133894}}
{"text": "#include <boost/python/numpy.hpp>\n#include <Eigen/Dense>\n\nnamespace p = boost::python;\nnamespace np = boost::python::numpy;\n\n/* python helper */\ntemplate <typename T, typename U>\nstatic Eigen::Matrix<T, -1, -1> npToEigen2d(np::ndarray np){\n\tint r = np.shape(0), c = np.shape(1);\n\tEigen::Matrix<T, -1, -1> mat(r, c);\n\tU *data = reinterpret_cast<U *>(np.get_data());\n\tfor (int i = 0; i < r; i++)\n\t\tfor (int j = 0; j < c; j++)\n\t\t\tmat(i, j) = data[i * c + j];\n\treturn mat;\n}\n\ntemplate <typename T, typename U>\nstatic np::ndarray eigenTonp2d(const Eigen::Matrix<U, -1, -1> &mat){\n\tint r = mat.rows(), c = mat.cols();\n\tp::tuple shape = p::make_tuple(r, c);\n\tnp::dtype dtype = np::dtype::get_builtin<T>();\n\tnp::ndarray np = np::empty(shape, dtype);\n\tfor (int i = 0; i < r; i++)\n\t\tfor (int j = 0; j < c; j++)\n\t\t\tnp[i][j] = mat(i, j);\n\treturn np;\n}\n\ntemplate <typename T, typename U>\nstatic Eigen::Matrix<T, -1, 1> npToEigen(np::ndarray np){\n\tint sz = np.shape(0);\n\tEigen::Matrix<T, -1, 1> vec(sz);\n\tU *data = reinterpret_cast<U *>(np.get_data());\n\tfor (int i = 0; i < sz; i++)\n\t\tvec[i] = data[i];\n\treturn vec;\n}\n\ntemplate <typename T, typename U>\nstatic np::ndarray eigenTonp(const Eigen::Matrix<U, -1, 1> &vec){\n\tp::tuple shape = p::make_tuple(vec.size());\n\tnp::dtype dtype = np::dtype::get_builtin<T>();\n\tnp::ndarray np = np::empty(shape, dtype);\n\tfor (int i = 0; i < vec.size(); i++)\n\t\tnp[i] = vec[i];\n\treturn np;\n}\n\nboost::python::tuple getGAE(np::ndarray values_np, np::ndarray reward_np, np::ndarray done_np, double gamma, double lamda){\n\tEigen::VectorXd values = npToEigen<double, float>(values_np);\n\tEigen::VectorXd reward = npToEigen<double, float>(reward_np);\n\tEigen::VectorXi done = npToEigen<int, int>(done_np);\n\tint n = values.size();\n\tEigen::VectorXd returns = Eigen::VectorXd::Zero(n);\n\tEigen::VectorXd advants = Eigen::VectorXd::Zero(n);\n\n\tdouble prev_return = 0., current_return = 0.;\n\tdouble prev_value = 0., current_value = 0.;\n\tdouble prev_advant = 0., current_advant = 0.;\n\tfor (int i = n - 1; i >= 0; i--){\n\t\tprev_return = done[i] ? 0. : current_return;\n\t\tprev_advant = done[i] ? 0. : current_advant;\n\t\tprev_value = done[i] ? 0. : current_value;\n\n\t\tcurrent_return = reward[i] + gamma * prev_return;\n\t\tcurrent_advant = prev_advant * gamma * lamda + (reward[i] - values[i] + gamma * prev_value);\n\t\tcurrent_value = values[i];\n\n\t\treturns[i] = current_return;\n\t\tadvants[i] = current_advant;\n\t}\n\tadvants = advants / sqrt(advants.squaredNorm() / n);\n\treturn p::make_tuple(eigenTonp<float>(returns), eigenTonp<float>(advants));\n}\n\nBOOST_PYTHON_MODULE(libRLHelper){\n\tnp::initialize();\n\n\tp::def(\"getGAE\", getGAE);\n}\n\nint main(){}", "meta": {"hexsha": "584979452d18928debd1541113f9f4767f0391f7", "size": 2633, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "RLPython/RLHelper/RLHelper.cpp", "max_stars_repo_name": "snumrl/DistributedDeepMimic", "max_stars_repo_head_hexsha": "364d07dbdd5378b6d46d944e472e1632712ef5f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "RLPython/RLHelper/RLHelper.cpp", "max_issues_repo_name": "snumrl/DistributedDeepMimic", "max_issues_repo_head_hexsha": "364d07dbdd5378b6d46d944e472e1632712ef5f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RLPython/RLHelper/RLHelper.cpp", "max_forks_repo_name": "snumrl/DistributedDeepMimic", "max_forks_repo_head_hexsha": "364d07dbdd5378b6d46d944e472e1632712ef5f6", "max_forks_repo_licenses": ["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.3452380952, "max_line_length": 123, "alphanum_fraction": 0.6456513483, "num_tokens": 839, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.46221938674133883}}
{"text": "#include <boost/math/common_factor.hpp>\n", "meta": {"hexsha": "6f98818b65b06d08c2583f2e63861c8fcbb795fc", "size": 40, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_common_factor.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_common_factor.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_common_factor.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 20.0, "max_line_length": 39, "alphanum_fraction": 0.8, "num_tokens": 8, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255928, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4622193801471632}}
{"text": "#ifdef MATLAB_MEX_FILE\n#include \"mex.h\"\n#include \"posedata.h\"\n#include \"get_floor_fHf.h\"\n#include <Eigen/Dense>\n\nusing namespace Eigen;\n\nvoid mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])\n{\n\tif (nrhs != 4) {\n\t\tmexErrMsgIdAndTxt(\"get_floor_fHf:nrhs\", \"Four input arguments are required.\");\n\t}\n\tif (nlhs != 2) {\n\t\tmexErrMsgIdAndTxt(\"get_floor_fHf:nlhs\", \"Two output arguments are required.\");\n\t}\n\tif (!mxIsDouble(prhs[0]) || mxIsComplex(prhs[0])) {\n\t\tmexErrMsgIdAndTxt(\"get_floor_fHf:notDouble\", \"Input data must be type double.\");\n\t}\n\tif(mxGetNumberOfElements(prhs[0]) != 6 && mxGetNumberOfElements(prhs[1]) != 6 && mxGetNumberOfElements(prhs[2]) != 9 && mxGetNumberOfElements(prhs[3]) != 9) {\n\t\tmexErrMsgIdAndTxt(\"get_floor_fHf:incorrectSize\", \"Input dimensions incorrect.\");\n\t}\n    // Convert to expected input\n    VectorXd x1_tmp = Map<VectorXd>(mxGetPr(prhs[0]), 6);\n    VectorXd x2_tmp = Map<VectorXd>(mxGetPr(prhs[1]), 6);\n    MatrixXd x1 = Map<MatrixXd>(x1_tmp.data(), 2, 3);\n    MatrixXd x2 = Map<MatrixXd>(x2_tmp.data(), 2, 3);\n\n    VectorXd R1_tmp = Map<VectorXd>(mxGetPr(prhs[2]), 9);\n    VectorXd R2_tmp = Map<VectorXd>(mxGetPr(prhs[3]), 9);\n    Matrix3d R1 = Map<Matrix3d>(R1_tmp.data(), 3, 3);\n    Matrix3d R2 = Map<Matrix3d>(R2_tmp.data(), 3, 3);\n\n    // Compute output\n\tPoseData posedata = get_floor_fHf(x1, x2, R1, R2);\n\n    // Wrap it up to Matlab compatible output\n\tplhs[0] = mxCreateDoubleMatrix(3, 3, mxREAL);\n\tdouble* zr = mxGetPr(plhs[0]);\n    for (Index i = 0; i < posedata.homography.size(); i++) {\n        zr[i] = posedata.homography(i);\n    }\n\n    plhs[1] = mxCreateDoubleMatrix(1, 1, mxREAL);\n    zr = mxGetPr(plhs[1]);\n    zr[0] = posedata.focal_length;\n}\n#endif\n\n", "meta": {"hexsha": "6292699f51681f8a9504fe9e3a78741725288177", "size": 1718, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "c++/floor_fHf/mex_get_floor_fHf.cpp", "max_stars_repo_name": "marcusvaltonen/minimal_indoor_uav", "max_stars_repo_head_hexsha": "79f3a26f2a6c10ee74a9fb70c5f3b42e4cf105ca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "c++/floor_fHf/mex_get_floor_fHf.cpp", "max_issues_repo_name": "marcusvaltonen/minimal_indoor_uav", "max_issues_repo_head_hexsha": "79f3a26f2a6c10ee74a9fb70c5f3b42e4cf105ca", "max_issues_repo_licenses": ["MIT"], "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++/floor_fHf/mex_get_floor_fHf.cpp", "max_forks_repo_name": "marcusvaltonen/minimal_indoor_uav", "max_forks_repo_head_hexsha": "79f3a26f2a6c10ee74a9fb70c5f3b42e4cf105ca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-09-15T17:05:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-15T17:05:32.000Z", "avg_line_length": 34.36, "max_line_length": 159, "alphanum_fraction": 0.6670547148, "num_tokens": 590, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255928, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4622193801471632}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n\n#include <PnC/WBC/Task.hpp>\n\nclass AngularMomentumTask : public Task {\n public:\n  AngularMomentumTask(RobotSystem* robot_, const double dt_eps);\n  virtual ~AngularMomentumTask();\n\n private:\n  /* Update op_cmd, pos_err, vel_des, acc_des\n   *\n   * vel_des_ = [w_x, w_y, w_z] // angular momentum\n   * acc_des_ = [a_x, a_y, a_z] // angular momentum rate\n   *\n   */\n  virtual bool _UpdateCommand(const Eigen::VectorXd& pos_des,\n                              const Eigen::VectorXd& vel_des,\n                              const Eigen::VectorXd& acc_des);\n  virtual bool _UpdateTaskJacobian();\n  virtual bool _UpdateTaskJDotQdot();\n\n  Eigen::MatrixXd Ag_cur_;   // Current centroidal inertia matrix\n  Eigen::MatrixXd Ag_prev_;  // Previous centroidal inertia matrix\n  Eigen::MatrixXd Agdot_;    // Current Estimate for centroidal inertia matrix\n  double dt_eps_;            // time interval to use for approximating Agdot_\n  bool first_pass_;          // first time computing Jdotqdot\n};\n", "meta": {"hexsha": "1709808075bc9ccf78c168a53fbcf85617b2df1b", "size": 1018, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "PnC/ValkyriePnC/ValkyrieTask/AngularMomentumTask.hpp", "max_stars_repo_name": "BharathMasetty/PnC", "max_stars_repo_head_hexsha": "3800bd7e3c5dd5ffa00e6a5f09d48d21c405206f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PnC/ValkyriePnC/ValkyrieTask/AngularMomentumTask.hpp", "max_issues_repo_name": "BharathMasetty/PnC", "max_issues_repo_head_hexsha": "3800bd7e3c5dd5ffa00e6a5f09d48d21c405206f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PnC/ValkyriePnC/ValkyrieTask/AngularMomentumTask.hpp", "max_forks_repo_name": "BharathMasetty/PnC", "max_forks_repo_head_hexsha": "3800bd7e3c5dd5ffa00e6a5f09d48d21c405206f", "max_forks_repo_licenses": ["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.8387096774, "max_line_length": 78, "alphanum_fraction": 0.6768172888, "num_tokens": 251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255927, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.46221938014716313}}
{"text": "#include <limits>\n#include <ctime>\n#include <fstream>\n#include <cmath>\n#include <random>\n#include <boost/math/distributions/binomial.hpp>\n#include <boost/math/distributions/normal.hpp>\n#include <boost/math/special_functions/digamma.hpp>\n\n#define LNINVSQRT2PI -0.918938533\n#define INVSQRT2PI 0.3989422804\n#define LN2 0.69314718056\n#define PEAKWIDTH 0.325\n#define MAX_EM_ITERATIONS 500\n#define EM_CONVERGE 1e-3\n//this is used for the minimum logValue as well - to distinguish it from an undef value which is 0\n#define MIN_NOISE 1e-8\n //lookup tables\nstatic double logx[32768]; //log base2\nstatic double lnx[32768];  //natural logs\n \nvoid init_logx();\ntemplate <class T> int fitLogNormEM(T *smooth, int nBins,vector<T> &peakBins,vector<T> &peakValues, vector<T> &peakMeans);\nusing namespace std;\nusing namespace boost::math;\n\n\ntemplate <class T> class MedianRecord{\n\tpublic:\n\t vector<T> means0;\n\t vector<T> means1;\n\t T median0;\n\t T median1;\n\t\tMedianRecord(){\t\t\n   blank();\n\t }\n  void blank(){\n\t\t\tconst T null=std::numeric_limits<T>::quiet_NaN();\n\t\t\tmeans0.clear();\n\t\t\tmeans1.clear();\n\t\t\tmedian0=null;\n\t\t median1=null;\t\t\t\t\n\t\t}\n\n\t void addValues(T mean0, T mean1){\n\t\t\tif(!mean0 || !mean1 || isnan(mean0) || isnan(mean1)) return;\n\t\t\tmeans0.push_back(mean0);\n\t\t\tmeans1.push_back(mean1);\n\t\t}\n\t\tvoid calculate_medians()\t{\n\t\t\tif( means0.size() &&  means1.size() ){\n    median0=median(means0.begin(),means0.end());\n\t   median1=median(means1.begin(),means1.end());\n\t\t\t}\n\t\t}\n\t\tprivate:\t\n  template <typename Iterator>  T median(Iterator begin, Iterator end) {\n\t Iterator middle = begin + (end - begin)/2;\n\t std::nth_element(begin, middle, end);\n  if ((end - begin) % 2) return *middle;\n\t\tIterator lower_middle = std::max_element(begin, middle);\n\t\treturn (*middle + *lower_middle) / 2.0;\n }\t   \n};\n\ntemplate <class T> class DeconRecord{\n\tpublic:\n\tT means0 [501];\n\tT means1 [501];\n\tT stdevs0 [501];\n\tT stdevs1 [501];\n\tT a0[501];\n\tT a1[501];\n\tT noiseFractions[501];\n\tT meansEst0[501];\n\tT meansEst1[501];\n\tint dataSizes[501];\n\tT loglikelihoods[501];\n\tbool flipped[501];\n\tbool converged[501];\n\tDeconRecord(){\n\t\tblank();\n\t}\n\tvoid blank(){\n\t\tconst T null=std::numeric_limits<T>::quiet_NaN();\n\t\tfill(means0,means0+501,null);\n\t\tfill(means1,means1+501,null);\n\t\tfill(stdevs0,stdevs0+501,null);\n\t\tfill(stdevs1,stdevs1+501,null);\n\t\tfill(a0,a0+501,null);\n\t\tfill(a1,a1+501,null);\n\t\tfill(loglikelihoods,loglikelihoods+501,null);\n\t\tfill(meansEst0,meansEst0+501,null);\n\t\tfill(meansEst1,meansEst1+501,null);\n\t\tfill(dataSizes,dataSizes+501,0);\n\t\tfill(noiseFractions,noiseFractions+501,0);\n\t\tfill(flipped,flipped+501,0);\t\t\t\n\t\tfill(converged,converged+501,0);\t\t\t\t\t\n\t}\n\tvoid transfer(int i,T *meanVars){\n\t\tmeansEst0[i]=meanVars[0];\n\t\tmeansEst1[i]=meanVars[1];\n\t}\n\t\n\tvoid print_binary(FILE *fp){\n\t\t//prints out a short binary file with just the fields\n\t\tfor (int i=11;i<501;i++){\n\t\t\tfwrite(means0+i,sizeof(T),1,fp);\n\t\t\tfwrite(means1+i,sizeof(T),1,fp);\n\t\t}\n\t}\t\t\n\tvoid print_binary(FILE *fp,int colorStart,int colorEnd){\n\t\t//prints out a short binary file with just the fields\n\t\tfor (int i=colorStart;i<=colorEnd;i++){\n\t\t\tfwrite(means0+i,sizeof(T),1,fp);\n\t\t\tfwrite(means1+i,sizeof(T),1,fp);\n\t\t}\n\t}\n\tvoid print_text(FILE *fp,int verbosity){\n\t\tif(verbosity <0){\n\t\t\tprint_binary(fp);\n\t\t\treturn;\n  }\t\n\t\tstring headers[14]={\"Analyte\",\"Mean1\",\"Mean2\",\"StDev1\",\"StDev2\",\"a1\",\"a2\",\"LogLike\",\"DataSize\",\"NoiseFraction\",\"Converged\",\"Flip\",\"CMean1\",\"CMean2\"};\n\t\tint nfields=3;\n\t\tif(verbosity ==1) nfields=8;\n\t\telse if (verbosity >1) nfields=14;\n\t\tfor(int i=0;i<nfields-1;i++){\n\t\t\tfprintf(fp,\"%s\\t\",headers[i].c_str());\n\t\t}\t\n\t\tfprintf(fp,\"%s\\n\",headers[nfields-1].c_str());\n\t\tfor (int i=1;i<501;i++){\n\t\t\tif(verbosity==0) fprintf(fp,\"%3d\\t%f\\t%f\\n\",i,means0[i],means1[i]);\t\n\t\t\telse if(verbosity==1)\tfprintf(fp,\"%3d\\t%f\\t%f\\t%f\\t%f\\t%f\\t%f\\t%e\\n\",i,means0[i],means1[i],stdevs0[i],stdevs1[i],a0[i],a1[i],loglikelihoods);\n   else{\n\t\t\t\tif((means0[i] > means1 [i] && \tmeansEst0[i] < meansEst1[i]) ||  (means0[i] < means1 [i] && \tmeansEst0[i] > meansEst1[i])){\n\t\t\t\t\tflipped[i]=1;\n\t\t\t\t}\t\n\t\t\t\tfprintf(fp,\"%3d\\t%f\\t%f\\t%f\\t%f\\t%f\\t%f\\t%e\\t%d\\t%f\\t%s\\t%s\\t%f\\t%f\\n\",i,means0[i],means1[i],stdevs0[i],stdevs1[i],a0[i],a1[i],loglikelihoods[i],dataSizes[i],noiseFractions[i],\"false\\0true\"+6*(int)converged[i],\"false\\0true\"+6*(int)flipped[i],meansEst0[i],meansEst1[i]);\n\t\t\t}\t\t\n\t\t}\t\n\t}\n\tvoid print_text(FILE *fp,int colorStart,int colorEnd,int verbosity){\n\t\tif(verbosity <0){\n\t\t\tprint_binary(fp,colorStart,colorEnd);\n\t\t\treturn;\n  }\t\n\t\tstring headers[14]={\"Analyte\",\"Mean1\",\"Mean2\",\"StDev1\",\"StDev2\",\"a1\",\"a2\",\"LogLike\",\"DataSize\",\"NoiseFraction\",\"Converged\",\"Flip\",\"CMean1\",\"CMean2\"};\n\t\tint nfields=3;\n\t\tif(verbosity ==1) nfields=8;\n\t\telse if (verbosity >1) nfields=14;\n\t\tfor(int i=0;i<nfields-1;i++){\n\t\t\tfprintf(fp,\"%s\\t\",headers[i].c_str());\n\t\t}\t\n\t\tfprintf(fp,\"%s\\n\",headers[nfields-1].c_str());\n\t\tfor (int i=colorStart;i<=colorEnd;i++){\n\t\t\tif(verbosity==0) fprintf(fp,\"%3d\\t%f\\t%f\\n\",i,means0[i],means1[i]);\t\n\t\t\telse if(verbosity==1)\tfprintf(fp,\"%3d\\t%f\\t%f\\t%f\\t%f\\t%f\\t%f\\t%e\\n\",i,means0[i],means1[i],stdevs0[i],stdevs1[i],a0[i],a1[i],loglikelihoods);\n   else{\n\t\t\t\tif((means0[i] > means1 [i] && \tmeansEst0[i] < meansEst1[i]) ||  (means0[i] < means1 [i] && \tmeansEst0[i] > meansEst1[i])){\n\t\t\t\t\tflipped[i]=1;\n\t\t\t\t}\n\t\t\t\t//something wrong with format string near space <-fix\t\n\t\t\t\tfprintf(fp,\"%3d\\t%f\\t%f\\t%f\\t%f\\t%f\\t%f\\t%e\\t%d\\t%f\\t%s\\t%s \\t%f\\t%f\\n\",i,means0[i],means1[i],stdevs0[i],stdevs1[i],a0[i],a1[i],loglikelihoods[i],dataSizes[i],noiseFractions[i],\"false\\0true\"+6*(int)converged[i],\"false\\0true\"+6*(int)flipped[i],meansEst0[i],meansEst1[i]);\n\t\t\t}\t\t\n\t\t}\t\n\t}\n};\ntemplate <class T> class EM_GMM{\n\tpublic:\n\t //these are for lognormals usually expressed using base 2 - we change to natural logs so that normalization works\n\t T var0,var1,var_est,var_lower,var_upper,mean0,mean1,meanEst0,meanEst1,mean_lower,mean_upper,a0,a1,p_est,p_upper,p_sigma;\n\t T *data;\n\t int nBins;\n\t int nPoints;\n\t int maxValue;\n\t int minValue;\n\t T loglikelihood;\n\t bool converged;\n\t bool normed; //normalized data?\n\n\t EM_GMM(T *_data,bool _normed,int _nBins,int _nPoints, int _minValue,int _maxValue,T _mus[2],T _vars[2],T _a, T _p_est, T _p_sigma,T _p_upper, T _sigma_lower, T _sigma_est, T _sigma_upper){\n\t\t\tnPoints=_nPoints;\n\t\t\tmean0=_mus[0]*LN2;\n\t\t\tmean1=_mus[1]*LN2;\n\t\t\tmeanEst0=mean0;\n\t\t\tmeanEst1=mean1;\n\t\t\tvar0=_vars[0]*LN2*LN2;\n\t\t\tvar1=_vars[1]*LN2*LN2;;\n\t\t\tvar_est=_sigma_est*_sigma_est*LN2*LN2;   \n\t\t\tvar_lower=_sigma_lower*_sigma_lower*LN2*LN2;\n\t\t\tvar_upper=_sigma_upper*_sigma_upper*LN2*LN2;\n\t\t\ta0=_a;\n\t\t\ta1=1.0-a0;\n\t\t\tdata=_data;\n\t\t\tnBins=_nBins;\n\t\t\tminValue=_minValue;\n\t\t\tmean_lower=lnx[minValue];\n\t\t\tmaxValue=_maxValue;\n\t\t\tmean_upper=lnx[maxValue];\n\t\t\tp_est=_p_est;\t \n   p_upper=_p_upper;\n   p_sigma=_p_sigma;\n   loglikelihood=0;\n   normed=_normed;\n\t\t\t//hard estimate for p distorts the distribution\n\t\t\t//with large number of points (i.e. composite of many wells) the spread of possible p values needs incresased as using a binomial correction is the same as a hard limit\n\t\t\t//we assume that the mixture value is not exactly _p since we have estimates from .625 - .700 and there is probably some mixture error in addition to sampling variation which would be binomial\n\t\t\t//for lower numbers (i.e. individual wells) we use the estimate of mixture error to determine the beta distribution and add binomial correction \n\t\t\t//for higher numbers the data swamps the prior if we do this - so we explicitly calculate beta to limit the possible values \n\t\t\t\n\t\t\t//when given limiting based on distribution\n\t\t\t//calculate alpha and beta of beta distribution\n\t\t\t//alpha=((1-_p)/(_pErr*_pErr) -1/_p)*_p*_p\n\t\t\t//beta=alpha*(1/_p-1)\n\t\t\t//update is now (alpha+k)/(alpha+beta+n) instead of k/n\n\t\t\t//use this formula to derive beta-binomial correction to loglikelihood \n\t\t\t\n\t\t\t//will not use k/n as estimate of partition ratio - instead calculate an alpha and beta so that the\n\t\t\t//so that the maximum value if the entire sample partitioned 1 way the value equal to the limit\n   //alpha =-(N*p_est*p_upper-N*p_est)/(p_upper-p_est)\n   //beta=((N*p_est-N)*p_upper-N*p_est+N)/(p_upper-p_est)\n   \n   //for betabinomial loglikelihood for y successes in n trials \n   //lgamma(n+a+b)-lgamma(y+alpha) -lgamma(n-y+beta) +(alpha+y-1)log(p)+(b+n-y-1)*log(1-p)\n   \n   //NB check and flip a1 a0 if a1>a0 - check - define alarger asmaller  \n\t }\n\t void reset(T _mean0,T _mean1, T _var0,T _var1, T _a){\n\t\t\tmean0=_mean0*LN2;;\n\t\t\tmean1=_mean1*LN2;;\n\t\t\tvar0=_var0*LN2*LN2;\n\t\t\tvar1=_var1*LN2*LN2;\n\t\t\ta0=_a;\n\t\t\ta1=1.0-a0;\n\t\t\tloglikelihood=0;\n\t\t}\t\n\t int seed_mclust(T input_p){\n   //use m-clust to provide initial points\n   //very similar to optimize function but with different estimates\n   const int maxIterations=MAX_EM_ITERATIONS;\n   const double converge=EM_CONVERGE;\n   bool done=0;\n   int nIterations=0;\n   const int last=(nBins-1<maxValue)? nBins-1 : maxValue;\n   T df=3.0,kp=0.01,svar=var_est;\n   \n   \n  \t//T alpha1=((1.0-p_est)/(p_sigma*p_sigma) -1.0/p_est)*p_est*p_est;\n\t\t\t//T beta1=alpha1*(1.0/(p_est-1));\n\n   //fit mean stdevs to normals norma a*invsqrtpi/sigma * exp((-(x-mean)**2)/(2*var*var))\n   //however the  invsqrtpi/sigma needs to be in natural log scale to properly normalize\n   \n   //adjust ln\n   vector <int> map;\n   vector <T> mylnx; //mapped copy of lnx\n   vector <T> mydata;\n   for (int j=minValue;j<=last; j++){\n\t\t\t//check for underflow\n\t\t\t if(data[j] && !isnan(data[j])){\n\t\t\t\t\tmap.push_back(j);\n\t\t\t\t\tmylnx.push_back(lnx[j]);\n\t\t\t\t\tmydata.push_back(data[j]);\n\t\t\t\t}\t\n\t\t\t} \n\t\t\t\n   while(!done){\n    double term0=log(a0)+LNINVSQRT2PI-log(sqrt(var0));\n    double term1=log(a1)+LNINVSQRT2PI-log(sqrt(var1));\n    double inv2Var0=1.0/(2.0*var0);\n    double inv2Var1=1.0/(2.0*var1); \n\n   \n  //calculate weighted percentage that points in j come from distribution 1 or 2\n  //then calculate stdevs and mean for expectation maximization\n   double L=0,sum0=0,sumsq0=0,sum1=0,sumsq1=0,counts0=0,counts1=0;\n   const int setSize=map.size();\n   for (int m=0;m<setSize; m++){\n\t\t\t\tconst int j=map[m];\n\t\t\t//check for underflow\n\t\t\t \tT logLike0=term0-inv2Var0*(mylnx[m]-mean0)*(mylnx[m]-mean0);\n\t\t\t \tT logLike1=term1-inv2Var1*(mylnx[m]-mean1)*(mylnx[m]-mean1);\n\n\t\t\t \t//check for underflows\n\t\t\t \tif((!logLike1 || std::isnan(logLike1)) && logLike0 && !std::isnan(logLike0)){\n\t\t     L+=mydata[m]*logLike0;\n\t\t\t \t\t counts0+=mydata[m];\n\t\t\t \t\t sum0+=mylnx[m]*mydata[m];\n\t\t\t \t\t sumsq0+=mylnx[m]*mylnx[m]*mydata[m];\n\t\t\t \t}\n\t\t\t \telse if\t((!logLike0 || std::isnan(logLike0)) && logLike1 && !std::isnan(logLike1)){\n\t\t     L+=mydata[m]*logLike1;\n\t\t\t \t\t counts1+=mydata[m];\n\t\t\t \t\t sum1+=mylnx[m]*mydata[m];\n\t\t\t \t\t sumsq1+=mylnx[m]*mylnx[m]*mydata[m];\n\t\t\t \t}\n\t\t\t \telse{\n\t\t\t \t\tconst T logRatio=logLike0-logLike1;\n\t\t\t \t if(logRatio > 15){\n\t\t     L+=mydata[m]*logLike0;\n\t\t\t \t\t counts0+=mydata[m];\n\t\t\t \t\t sum0+=mylnx[m]*mydata[m];\n\t\t\t \t\t sumsq0+=mylnx[m]*mylnx[m]*mydata[m];\t\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (logRatio < -15){\n\t\t     L+=mydata[m]*logLike1;\n\t\t\t \t\t counts1+=mydata[m];\n\t\t\t \t\t sum1+=mylnx[m]*mydata[m];\n\t\t\t \t\t sumsq1+=mylnx[m]*mylnx[m]*mydata[m];\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse{\n\t\t\t \t\t const T ratio=exp(logRatio);\n\t\t\t \t\t const T r0=ratio/(ratio+1.0);\n\t\t\t \t\t const T r1=1.0-r0;\n\t\t\t \t\n\t\t\t\t\t  T nPoints0=mydata[m]*r0;\n\t\t\t\t \t T nPoints1=mydata[m]*r1;\n\t\t\t\t \t \n\n\t\t\t\t   counts0+=nPoints0;\n\t\t\t\t   counts1+=nPoints1;\n\t\t\t\t   L+=nPoints0*logLike0+nPoints1*logLike1;\n\t\t\t\t \t sum0+=nPoints0*mylnx[m];\n\t\t\t\t\t  sumsq0+=nPoints0*mylnx[m]*mylnx[m];\n\t\t\t\t \t sum1+=nPoints1*mylnx[m];\n\t\t\t\t\t  sumsq1+=nPoints1*mylnx[m]*mylnx[m];\n\t\t\t\t\t }\n\t\t\t\t\t}\t\t\n\t\t\t}\n\t\t //calculate estimate of mean\n\t\t T mean0MLE=(sum0+kp*meanEst0)/(kp+counts0); \n   T mean1MLE=(sum1+kp*meanEst1)/(kp+counts1); \n\n   mean0MLE= (mean0MLE > mean_upper)? mean_upper : mean0MLE;  \n   mean0MLE= (mean0MLE < mean_lower)? mean_lower: mean0MLE;  \n   mean1MLE= (mean1MLE > mean_upper)? mean_upper: mean1MLE; \n   mean1MLE= (mean1MLE < mean_lower)? mean_lower : mean1MLE; \n\n   //estimate a0 a1\n   //check if estimated a1 > a0 - if so switch means and var\n   T a0MLE,a1MLE;\n   if(counts1) a0MLE = counts0/(counts0+counts1);\n   else a0MLE=1;\n  \n   if(a0MLE < .5){\n\t\t\t//swap terms \n\t\t\t swap(mean0,mean1);\n\t\t\t swap(var0,var1);\n\t\t\t swap(mean0MLE,mean1MLE);\n\t\t\t swap(counts1,counts0);\n\t\t\t swap(a0,a1);\n\t\t\t a0MLE=1.0-a0;\n\t\t }\n\t\t //find unormalized counts\n\t\t T ucounts,ucounts0,ucounts1;\n\t\t if(normed){\n\t\t\t\tT totalCounts=counts0+counts1;\n\t\t\t\tucounts=(T) nPoints * totalCounts;\n\t\t\t\tucounts0=(T) nPoints * counts0;\t\n\t\t\t\tucounts1=(T) nPoints * counts1;\n\t\t\t}\t\n\t\t else{\n\t\t\t\tucounts=counts0+counts1;\n\t\t\t\tucounts0=counts0;\n\t\t\t\tucounts1=counts1;\n\t\t\t}\t\n   \n   a0MLE=(a0MLE > MIXTURE_RATIO + 2*MIXTURE_STD)?MIXTURE_RATIO + 2*MIXTURE_STD :a0MLE;\n   a0MLE=(a0MLE < MIXTURE_RATIO - 2*MIXTURE_STD)?MIXTURE_RATIO - 2*MIXTURE_STD :a0MLE;\n   a1MLE=1.0-a0MLE;\n   T rawVar0MLE= sumsq0-mean0MLE*mean0MLE*counts0/(counts0+6.0);\n   T rawVar1MLE= sumsq1-counts1-mean1MLE*mean1MLE*counts1/(counts1+6.0);\n   \n   if(isnan(rawVar0MLE)){\n  \t\trawVar0MLE=(var_est+(kp*counts0)*(meanEst0-mean0MLE)*(meanEst0-mean0MLE))/(counts0+kp);\t\n\t\t\t}\n\t\t\telse{\n\t\t\t\trawVar0MLE+=(var_est+(kp*counts0)*(meanEst0-mean0MLE)*(meanEst0-mean0MLE))/(counts0+kp);\t\n\t\t\t}\n   if(isnan(rawVar1MLE)){\n  \t\trawVar1MLE=(var_est+(kp*counts1)*(meanEst1-mean1MLE)*(meanEst1-mean1MLE))/(counts1+kp);\t\n\t\t\t}\n\t\t\telse{\n\t\t\t\trawVar1MLE+=(var_est+(kp*counts1)*(meanEst1-mean1MLE)*(meanEst1-mean1MLE))/(counts1+kp);\t\n\t\t\t}\t\t\t\t\n\n   T var0MLE=rawVar0MLE;\n   T var1MLE=rawVar1MLE;\n\n  //enforce limits\n   var0MLE=(var0MLE > var_upper)? var_upper : var0MLE;\n   var0MLE=(var0MLE < var_lower)? var_lower : var0MLE;\n   var1MLE=(var1MLE > var_upper)? var_upper : var1MLE;\n   var1MLE=(var1MLE < var_lower)? var_lower : var1MLE;\n\n   if(fabs(mean0MLE-mean0) > converge || fabs(mean1MLE-mean1) > converge){\n\t   mean0=mean0MLE;mean1=mean1MLE;\n\t   var0=var0MLE;var1=var1MLE;\n\t   a0=a0MLE;a1=a1MLE;\t   \n\t\t }\n\t\t else{\t\n\t\t\t\tloglikelihood=L;\n\t\t\t\tconverged=1;\n    var0=rawVar0MLE;var1=rawVar1MLE;\n\t\t\t var0=(var0 > var_upper*2.0)? var_upper*2.0 : var0;\n    var0=(var0 < var_lower/2.0)? var_lower/2.0 : var0;\n    var1=(var1 > var_upper*2.0)? var_upper*2.0 : var1;\n    var1=(var1< var_lower/2.0)? var_lower/2.0 : var1;    \n    a1=1.0-a0;\n     mean0=mean0MLE;mean1=mean1MLE;\n    return(1);\n\t\t\t}\n\t\t\t\t//adjustment for binomial - seems to give worse results - enough to soft constrain p \n\t\t\t\t//loglikelihood=L+(ucounts0+alpha1-1)*log(p_est)+(ucounts1+beta1-1)*log(1.0-p_est);\t\t\t\treturn(1);\n\n\t\t if(++nIterations > maxIterations){\n\t\t\t\tloglikelihood=L;\n\t\t\t\tvar0=rawVar0MLE;var1=rawVar1MLE;   \n\t\t\t\t\n\t\t\t var0=(var0 > var_upper*2.0)? var_upper*2.0 : var0;\n    var0=(var0 < var_lower/2.0)? var_lower/2.0 : var0;\n    var1=(var1 > var_upper*2.0)? var_upper*2.0 : var1;\n    var1=(var1< var_lower/2.0)? var_lower/2.0 : var1;\n    a1=1.0-a0;\n\t\t\t\tmean0=mean0MLE;mean1=mean1MLE;\n\t\t\t\treturn(0);           \n\t\t\t}\n\t\t}\n\t}  \n  int optimize(T input_p){\n   //optimize mean and use common variance\n    //return loglikelihood after convergence with betabinomial term   \n   const int maxIterations=MAX_EM_ITERATIONS;\n   const double converge=EM_CONVERGE;\n   bool done=0;\n   int nIterations=0;\n   const int last=(nBins-1<maxValue)? nBins-1 : maxValue;\n   \n  \t//T alpha1=((1.0-p_est)/(p_sigma*p_sigma) -1.0/p_est)*p_est*p_est;\n\t\t\t//T beta1=alpha1*(1.0/(p_est-1));\n\n   //fit mean stdevs to normals norma a*invsqrtpi/sigma * exp((-(x-mean)**2)/(2*var*var))\n   //however the  invsqrtpi/sigma needs to be in natural log scale to properly normalize\n   \n   //adjust ln\n   vector <int> map;\n   vector <T> mylnx; //mapped copy of lnx\n   vector <T> mydata;\n   for (int j=minValue;j<=last; j++){\n\t\t\t//check for underflow\n\t\t\t if(data[j] && !isnan(data[j])){\n\t\t\t\t\tmap.push_back(j);\n\t\t\t\t\tmylnx.push_back(lnx[j]);\n\t\t\t\t\tmydata.push_back(data[j]);\n\t\t\t\t}\t\n\t\t\t} \n   while(!done){\n    double term0=log(a0)+LNINVSQRT2PI-log(sqrt(var0));\n    double term1=log(a1)+LNINVSQRT2PI-log(sqrt(var1));\n    double inv2Var0=1.0/(2.0*var0);\n    double inv2Var1=1.0/(2.0*var1); \n\n   \n  //calculate weighted percentage that points in j come from distribution 1 or 2\n  //then calculate stdevs and mean for expectation maximization\n   double L=0,sum0=0,sumsq0=0,sum1=0,sumsq1=0,counts0=0,counts1=0;\n   const int setSize=map.size();\n   for (int m=0;m<setSize; m++){\n\t\t\t//check for underflow\n\t\t\t \tT logLike0=term0-inv2Var0*(mylnx[m]-mean0)*(mylnx[m]-mean0);\n\t\t\t \tT logLike1=term1-inv2Var1*(mylnx[m]-mean1)*(mylnx[m]-mean1);\n\n\t\t\t \t//check for underflows\n\t\t\t \tif((!logLike1 || std::isnan(logLike1)) && logLike0 && !std::isnan(logLike0)){\n\t\t     L+=mydata[m]*logLike0;\n\t\t\t \t\t counts0+=mydata[m];\n\t\t\t \t\t sum0+=mylnx[m]*mydata[m];\n\t\t\t \t\t sumsq0+=mylnx[m]*mylnx[m]*mydata[m];\n\t\t\t \t}\n\t\t\t \telse if\t((!logLike0 || std::isnan(logLike0)) && logLike1 && !std::isnan(logLike1)){\n\t\t     L+=mydata[m]*logLike1;\n\t\t\t \t\t counts1+=mydata[m];\n\t\t\t \t\t sum1+=mylnx[m]*mydata[m];\n\t\t\t \t\t sumsq1+=mylnx[m]*mylnx[m]*mydata[m];\n\t\t\t \t}\n\t\t\t \telse{\n\t\t\t \t\tconst T logRatio=logLike0-logLike1;\n\t\t\t \t if(logRatio > 15){\n\t\t     L+=mydata[m]*logLike0;\n\t\t\t \t\t counts0+=mydata[m];\n\t\t\t \t\t sum0+=mylnx[m]*mydata[m];\n\t\t\t \t\t sumsq0+=mylnx[m]*mylnx[m]*mydata[m];\t\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (logRatio < -15){\n\t\t     L+=mydata[m]*logLike1;\n\t\t\t \t\t counts1+=mydata[m];\n\t\t\t \t\t sum1+=mylnx[m]*mydata[m];\n\t\t\t \t\t sumsq1+=mylnx[m]*mylnx[m]*mydata[m];\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse{\n\t\t\t \t\t const T ratio=exp(logRatio);\n\t\t\t \t\t const T r0=ratio/(ratio+1.0);\n\t\t\t \t\t const T r1=1.0-r0;\n\t\t\t \t\n\t\t\t\t\t  T nPoints0=mydata[m]*r0;\n\t\t\t\t \t T nPoints1=mydata[m]*r1;\n\t\t\t\t   counts0+=nPoints0;\n\t\t\t\t   counts1+=nPoints1;\n\t\t\t\t   L+=nPoints0*logLike0+nPoints1*logLike1;\n\t\t\t\t \t sum0+=nPoints0*mylnx[m];\n\t\t\t\t\t  sumsq0+=nPoints0*mylnx[m]*mylnx[m];\n\t\t\t\t \t sum1+=nPoints1*mylnx[m];\n\t\t\t\t\t  sumsq1+=nPoints1*mylnx[m]*mylnx[m];\n\t\t\t\t\t }\n\t\t\t\t\t}\t\t\n\t\t\t}\n\t\t //calculate estimate of mean\n\t\t T mean0MLE=sum0/(counts0); \n   T mean1MLE=sum1/(counts1);\n\t\n   mean0MLE= (mean0MLE > mean_upper)? mean_upper : mean0MLE;  \n   mean0MLE= (mean0MLE < mean_lower)? mean_lower: mean0MLE;  \n   mean1MLE= (mean1MLE > mean_upper)? mean_upper: mean1MLE; \n   mean1MLE= (mean1MLE < mean_lower)? mean_lower : mean1MLE; \n \n   //estimate a0 a1\n   //check if estimated a1 > a0 - if so switch means and var\n   T a0MLE,a1MLE;\n   if(counts1) a0MLE = counts0/(counts0+counts1);\n   else a0MLE=1;\n  \n   if(a0MLE < .5){\n\t\t\t//swap terms \n\t\t\t swap(mean0,mean1);\n\t\t\t swap(var0,var1);\n\t\t\t swap(mean0MLE,mean1MLE);\n\t\t\t swap(counts1,counts0);\n\t\t\t swap(a0,a1);\n\t\t\t a0MLE=1.0-a0;\n\t\t }\n\t\t //find unormalized counts\n\t\t T ucounts,ucounts0,ucounts1;\n\t\t if(normed){\n\t\t\t\tT totalCounts=counts0+counts1;\n\t\t\t\tucounts=(T) nPoints * totalCounts;\n\t\t\t\tucounts0=(T) nPoints * counts0;\t\n\t\t\t\tucounts1=(T) nPoints * counts1;\n\t\t\t}\t\n\t\t else{\n\t\t\t\tucounts=counts0+counts1;\n\t\t\t\tucounts0=counts0;\n\t\t\t\tucounts1=counts1;\n\t\t\t}\t\n   \n   a0MLE=(a0MLE > MIXTURE_RATIO + 2*MIXTURE_STD)?MIXTURE_RATIO + 2*MIXTURE_STD :a0MLE;\n   a0MLE=(a0MLE < MIXTURE_RATIO - 2*MIXTURE_STD)?MIXTURE_RATIO - 2*MIXTURE_STD :a0MLE;\n   a1MLE=1.0-a0MLE;\n   T rawVar0MLE=(sumsq0/(counts0)-mean0MLE*mean0MLE)*.6;\n   T rawVar1MLE=(sumsq1/(counts1)-mean1MLE*mean1MLE)*.6;\n   if(isnan( rawVar0MLE))rawVar0MLE=var_lower/2.0;  \n   if(isnan( rawVar1MLE))rawVar1MLE=var_lower/2.0;\n   T var0MLE=rawVar0MLE;\n   T var1MLE=rawVar1MLE;\n\n  //enforce limits\n   var0MLE=(var0MLE > var_upper)? var_upper : var0MLE;\n   var0MLE=(var0MLE < var_lower)? var_lower : var0MLE;\n   var1MLE=(var1MLE > var_upper)? var_upper : var1MLE;\n   var1MLE=(var1MLE < var_lower)? var_lower : var1MLE;\n\n   if(fabs(mean0MLE-mean0) > converge || fabs(mean1MLE-mean1) > converge){\n\t   mean0=mean0MLE;mean1=mean1MLE;\n\t   var0=var0MLE;var1=var1MLE;\n\t   a0=a0MLE;a1=a1MLE;\t   \n\t\t }\n\t\t else{\t\n\t\t\t\tloglikelihood=L;\n\t\t\t\tconverged=1;\n    var0=rawVar0MLE;var1=rawVar1MLE;\n\t\t\t var0=(var0 > var_upper*2.0)? var_upper*2.0 : var0;\n    var0=(var0 < var_lower/2.0)? var_lower/2.0 : var0;\n    var1=(var1 > var_upper*2.0)? var_upper*2.0 : var1;\n    var1=(var1< var_lower/2.0)? var_lower/2.0 : var1;    \n    a1=1.0-a0;\n     mean0=mean0MLE;mean1=mean1MLE;\n    //fprintf(stderr,\"%f %f %f %f %f %f\\n\",mean0MLE*INVLOG2,mean1MLE*INVLOG2,var0MLE*INVLOG2*INVLOG2,var1MLE*INVLOG2*INVLOG2,a0MLE,a1MLE);\n\n    return(1);\n\t\t\t}\n\t\t\t\t//adjustment for binomial - seems to give worse results - enough to soft constrain p \n\t\t\t\t//loglikelihood=L+(ucounts0+alpha1-1)*log(p_est)+(ucounts1+beta1-1)*log(1.0-p_est);\t\t\t\treturn(1);\n\n\t\t if(++nIterations > maxIterations){\n\t\t\t\tloglikelihood=L;\n\t\t\t\tvar0=rawVar0MLE;var1=rawVar1MLE;   \n\t\t\t\t\n\t\t\t var0=(var0 > var_upper*2.0)? var_upper*2.0 : var0;\n    var0=(var0 < var_lower/2.0)? var_lower/2.0 : var0;\n    var1=(var1 > var_upper*2.0)? var_upper*2.0 : var1;\n    var1=(var1< var_lower/2.0)? var_lower/2.0 : var1;\n    a1=1.0-a0;\n\t\t\t\tmean0=mean0MLE;mean1=mean1MLE;\n\t\t\t //fprintf(stderr,\"%f %f %f %f %f %f\\n\",mean0MLE*INVLOG2,mean1MLE*INVLOG2,var0MLE*INVLOG2*INVLOG2,var1MLE*INVLOG2*INVLOG2,a0MLE,a1MLE);\n\n\t\t\t\treturn(0);           \n\t\t\t}\n\t\t}\n\t}\n};\t\n\nvoid init_logx(){\n\tlogx[0]=0;\n\tlnx[0]=0;\n for (int i=1;i<32768;i++){ \n\t\tlnx[i]=log((double)i);  \n  logx[i]=lnx[i]*INVLOG2;\n\t}\n}\ntemplate <class T> void transferData(int color,DeconRecord<T> &deconRecord,EM_GMM<T> &EM){\n\t\n\tdeconRecord.means0[color]=(EM.mean0*INVLOG2 < MIN_NOISE)? MIN_NOISE : EM.mean0*INVLOG2;\n\tdeconRecord.means1[color]=(EM.mean1*INVLOG2 < MIN_NOISE)? MIN_NOISE : EM.mean1*INVLOG2;\n\tdeconRecord.meansEst0[color]=EM.meanEst0*INVLOG2;\n\tdeconRecord.meansEst1[color]=EM.meanEst1*INVLOG2;\n\tdeconRecord.stdevs0[color]=sqrt(EM.var0)*INVLOG2;\n\tdeconRecord.stdevs1[color]=sqrt(EM.var1)*INVLOG2;\n\tdeconRecord.a0[color]=EM.a0;\n\tdeconRecord.a1[color]=EM.a1;\t\t\t\n\tdeconRecord.loglikelihoods[color]=-EM.loglikelihood;\n\tdeconRecord.dataSizes[color]=EM.nPoints;\n\tdeconRecord.converged[color]=EM.converged;\n\tif((EM.meanEst0-EM.meanEst1)*(EM.mean0-EM.mean1) <0) deconRecord.flipped[color]=1;\n\telse\t deconRecord.flipped[color]=0;\n}\n\ntemplate <typename T1, typename T2> class wellRecord{\n\t//qnorm is done by well\n\t//these are then combined\n\tpublic:\n\t vector <T1> values[NCOLORS1OFF]; //original values in int16\n\t vector <string> groupNames;\n\t vector <T2> offsets[NCOLORS1OFF];\n\t vector <int> nBeads;\n\t vector <int> groupOffsets; //the well where the group starts\n\t int nTotalWells;\n\t \n\t int minValue; //minimum value for peak \n\t int maxValue; //maximum value for peak\n\t float peakGridSize; //gridSize for peakSearch\n\t float smoothHalfWindowSize; //half window size for smoothing\n\t wellRecord(string list,float minLogValue, float maxLogValue,float _smoothHalfWindowSize,float _peakGridSize){\n\t  int16_t header[2];\n\t\t int16_t v;\n\t\t nTotalWells=0;\n\t\t minValue=pow(2.0,minLogValue); //round down bin\n\t\t maxValue=pow(2.0,maxLogValue)+1;\n\t\t if(maxValue > 32767){\n\t\t\t\tmaxValue=32767;\n\t\t\t}\n\t\t\tsmoothHalfWindowSize=_smoothHalfWindowSize;\n\t\t\tpeakGridSize=_peakGridSize;\t  \n\t\t FILE *fp=fopen(list.c_str(),\"r\");\n\t\t //can have very long lines\n\t\t fseek(fp,0,SEEK_END);\n\t\t int size=ftell(fp)+1;\n\t\t fseek(fp,0,SEEK_SET);\n\t\t char *line=new char[size];\n\t\t //cerr << \"allocated \" << size << \" bytes\"<<endl;\n\t\t if(!line){\n\t\t\t\tcerr << \"unable to allocate \" << size << \" bytes\" <<endl;\n\t\t\t\texit(0);\n\t\t\t}\t\n\t\t int n=0;\n\t\t for(int i=1;i<NCOLORS1OFF;i++){\n\t\t \toffsets[i].push_back(0);\n\t\t }\n\t\t groupOffsets.push_back(0);\n   while(fgets(line,size,fp) != NULL){\n\t\t\t\t//format is name\\tfileName1\\tfileName2...fileNamen\\n\n\t\t\t\tvector <string> fileNames;\n\t\t\t\tstring groupName;\n\t\t\t\tconst char delimit[]=\" \\t\\r\\n\\v\\f\";\n\t\t\t\tchar *pch = strtok (line,delimit);\n\t\t\t groupName=(pch);\n\t\t\t pch = strtok (NULL,delimit); \n\t\t\t //start extracting list of fileNames\n\t\t\t \n\t\t\t //check for case when there is only one element per line in which case the groupName is also the file\n\t\t\t if(pch == NULL){\n\t\t\t\t\tfileNames.push_back(groupName);\n\t\t\t\t}\n\t\t\t\telse{\t  \n\t\t\t\t while (pch != NULL){\n      fileNames.push_back(pch);\n      pch = strtok (NULL,delimit);  \t\t\t\t\t\t\t\t\t\t\n\t\t\t\t }\n\t\t\t\t}\n\t\t\t\t//now extract the information from the filenames\n\t\t\t\tint nFilesRead=0;\n\t\t\t\tfor (int k=0;k<fileNames.size();k++){\n\t\t\t\t//\tfprintf(stderr,\"opening %s\\n\",fileNames[k].c_str());\n\t\t\t  FILE *fp1=fopen(fileNames[k].c_str(),\"r\");\n\t\t\t  if(fp1 == NULL){\n\t\t\t   fprintf(stderr,\"unable to open %s\\n\",fileNames[k].c_str());\n\t\t\t   continue;\n\t\t\t  }\n\t\t\t  while(fread(&header,2*sizeof(int16_t),1,fp1)){\n\t\t\t \t const int id=header[0];\n      for(int k=0;k<header[1];k++){\n\t\t     if(fread(&v,sizeof(int16_t),1,fp1)){\n\t\t\t\t  \t if(v>=0){values[id].push_back(v);}\t\n\t\t\t\t \t }\n\t\t\t   }\n\t\t\t  }\n\t\t   fclose(fp1);\n\t\t   //save sizes to offset\n\t\t   int totalRead=0;\n\t\t   for(int i=1;i<NCOLORS1OFF;i++){\n\t\t\t  \toffsets[i].push_back(values[i].size());\n\t\t\t  \ttotalRead+=values[i].size()-offsets[i][nBeads.size()];\n\t\t\t  }\t\n\t\t   nBeads.push_back(totalRead);\t\t\t  \n\t\t\t\t\tnFilesRead++;\t\n\t\t\t }\n\t\t\t if(nFilesRead){\n\t\t\t\t groupOffsets.push_back(groupOffsets[groupOffsets.size()-1]+nFilesRead);\n\t\t\t\t groupNames.push_back(groupName);\n\t\t\t\t nTotalWells+=nFilesRead;\t\n\t\t\t\t}\n\t\t }\n\t\t fprintf(stderr,\"closing file\\n\");\n\t\t fclose(fp);\n\t\t delete[] line;\n\t }\t\n  wellRecord(const wellRecord &A): values(A.values),groupNames(A.groupNames),groupOffsets(A.groupOffsets),offsets(A.offsets),maxValue(A.maxValue),minValue(A.minValue),smoothHalfWindowSize(A.smoothHalfWindowSize),peakGridSize(A.peakGridSize),nTotalWells(A.nTotalWells),nBeads(A.nBeads){}\n  \n\tvoid dumpEnsemble(string outputFile){\n\t\tcerr << \"dumping density to \" << outputFile <<endl;\n\t\tFILE *fp=fopen(outputFile.c_str(),\"w\");\n\t\tint counts[32768];\n\t\tfill(counts,counts+32768,0);\t\t\n\t\t//the 0th slice can be used to store errors in the old PERL script - keep it in case this is to be implemented later in C++\n\t\tfwrite(counts,sizeof(int),32768,fp);\n\t\tfor(int id=1;id<NCOLORS1OFF;id++){\n\t\t\tfill(counts,counts+32768,0); \n\t\t\tfor(int k=0;k<values[id].size();k++){\n\t\t\t\tcounts[values[id][k]]++;\n\t\t\t}\n\t\t\tfwrite(counts,sizeof(int),32768,fp);\n\t\t}\n\t\tfclose(fp);\n\t}\n\tvoid dumpWells(string outputDir){\n\t\tcerr << \"dumping density to directory \" << outputDir <<endl;\n\t\tfor(int n=0;n<nTotalWells;n++){\n\t\t\tostringstream nstream;\n\t\t\tnstream << \".\" << n;\n\t\t\t\n\t\t\tstring outputFile=outputDir+\"/\"+groupNames[n]+nstream.str()+\".den\";\t\n\t \tFILE *fp;\n\t \tif(fp=fopen(outputFile.c_str(),\"w\")){\n\t \t int counts[32768];\n\t \t fill(counts,counts+32768,0);\n\t\t  //the 0th slice can be used to store errors in the old PERL script - keep it in case this is to be implemented later in C++\n    fwrite(counts,sizeof(int),32768,fp);\t\t\n\t\t  for(int id=1;id<NCOLORS1OFF;id++){\n\t\t\t\t\tfill(counts,counts+32768,0); \n\t\t\t  for(int k=offsets[id][n];k<offsets[id][n+1];k++){\n\t\t\t  \tcounts[values[id][k]]++;\n\t\t\t  }\t\n\t\t  \tfwrite(counts,sizeof(int),32768,fp);\n\t\t  }\n\t\t  fclose(fp);\n\t  }\n\t\t}\n\t}\t\n\tvoid dumpSingleWell(string outputFile,int slice){\n\t\tcerr << \"dumping density of well \" << slice << \" to file \" << outputFile <<endl;\n\t FILE *fp;\n\t if(fp=fopen(outputFile.c_str(),\"w\")){\n\t  int counts[32768];\n\t  fill(counts,counts+32768,0);\n\t\t //the 0th slice can be used to store errors in the old PERL script - keep it in case this is to be implemented later in C++\n   fwrite(counts,sizeof(int),32768,fp);\t\t\n\t\t for(int id=1;id<NCOLORS1OFF;id++){ \n\t\t\t\tfill(counts,counts+32768,0);\n\t\t\t for(int k=offsets[id][slice];k<offsets[id][slice+1];k++){\n\t\t\t  counts[values[id][k]]++;\n\t\t\t }\t\n\t\t  fwrite(counts,sizeof(int),32768,fp);\n\t\t }\n\t\t fclose(fp);\n\t }\n\t}\n\tvoid dumpDensity(string outputFile,float densitySmoothHalfWindowSize){\n\t FILE *fp;\n\t if(fp=fopen(outputFile.c_str(),\"w\")){\n\t \tint counts[32768];\n\t \tfill(counts,counts+32768,0);\n\t \tfloat smooth[32768];\n\t \tfill(smooth,smooth+32768,0);\n   fwrite(smooth,1,sizeof(float)*32768,fp);//0 well - keep it for errors\n\t\t int upper[32768];\n\t\t int lower [32768];\n\t\t memset (lower,0,32768*sizeof(int));\n\t\t memset (upper,0,32768*sizeof(int));\n\t\t const float upperConstant=pow(2,densitySmoothHalfWindowSize);\n\t\t const float lowerConstant=1.0/upperConstant;\n\t\t for (int i=0;i<32768;i++){\n\t\t \tlower[i]= (int) (((float)i)*lowerConstant+.5);\n    upper[i]= (int) (((float)i)*upperConstant+.5);\t\n    if(upper[i] > 32767)upper[i]=32767;\n\t  }\n\t\t for (int i=1; i<=NCOLORS; i++){\n\t\t\t fill(smooth,smooth+32768,0);\t\n\t\t\t int nBins=logWindowSmooth(lower,upper,smooth,&(values[i][0]),values[i].size());\n\t\t \tfwrite(smooth,1,32768*sizeof(float),fp);\n\t\t\t}\n\t\t fclose(fp);\n\t\t}\n\t}\ntemplate<class Ta, class Tb> int logWindowSmooth(int *lower,int *upper,Ta *smooth,Tb *colorValues,int nValues){\n\t\tint maxBin=0;\n\t\tint counts[32768];\n\t\tfill(counts,counts+32768,0);\t\n\t\tdouble totalWeight=0;\n\t\tfor(int i=0;i<nValues;i++){\n\t\t counts[colorValues[i]]++;\n\t }\n\t\tfor(int i=1;i<32768;i++){\n\t\t if(counts[i])maxBin=i;\t\n\t }\t\t\n\t\tfor(int i=1;i<=maxBin;i++){\n   int sum=0;\n   //const int limit=(upper[i]<maxBin)? maxBin:upper[i];\n\t \tfor(int k=lower[i];k<=upper[i];k++){\n\t\t\t\tsum+=counts[k];\n\t\t\t}\n\t\t\tsmooth[i]=(Ta)sum/(Ta)(upper[i]-lower[i]+1);\n\t\t\t//fprintf(stderr,\"%d %d %d %e\\n\",i,lower[i],upper[i],smooth[i]);\t\n\t\t totalWeight+=smooth[i];\n\t\t}\n\t\tdouble invTotalWeight=1.0/totalWeight;\n\t\tfor(int i=0;i<=maxBin;i++){\n\t\t smooth[i]*=invTotalWeight;\n\t }\n\t\treturn(maxBin+1);\n\t}\n\ttemplate <class T> double dampenLowNoise(T *smooth,int nBins){\n\t\t//version for a single file in wells\n\t double lowNoiseFraction=0;\n  for(int i=0;i<minValue;i++){\n  \tconst double factor= exp(-0.3*(minValue-i));\n  \tlowNoiseFraction +=(1.0-factor)*smooth[i];\n  \tsmooth[i]*=factor;\n\t\t}\t\n  //renormalize\n  double normFactor=1.0/(1.0-lowNoiseFraction);\n  for(int i=minValue;i<nBins;i++)\n   smooth[i]*=normFactor; \n\t return (lowNoiseFraction);\n\t}\n\ttemplate <class T> void findPeaks(T *smooth, int nBins, T gridSize,vector<int> &peakBins, vector<T> &peakValues, vector<T> &peakMeans){\n\t\t//finds peaks using a interval (grid) search\n\t\t//uses equal log intervals and logSmoothed data\n\t\t//an interval contains a peak if the previous interval and and the following interval have lower mean values\n\t\t//the bin with the maxCounts in that interval is the location of a peak\n\t\t//peaks are then sorted by mean values (max values is more vulnerable to spikes)\n\t\t//a good value for grid size is roughly the std deviation of the expected peaks\n\t\t\n  vector<T> maxValues,meanValues;\n  vector<int>maxBins;\n  if(nBins <4){\n\t\t\t//edge case - return the middle bin\n\t\t\tpeakBins.resize(1);\n\t\t peakMeans.resize(1);\n\t\t peakValues.resize(1);\n\t\t\tpeakBins[0]=nBins/2;\n\t\t\tpeakMeans[0]=smooth[nBins/2];\n\t\t\tpeakValues[0]=smooth[nBins/2];\n\t\t\treturn;\n\t\t}\n\t \n\t int minBin=pow(2,minValue);int maxBin=(pow(2,maxValue) < nBins)?pow(2,maxValue) : nBins;\n\t T gridFactor=pow(2,gridSize);\n\t \n\n\t int i=minBin;\n\t\twhile(i<nBins){\n\t\t\tint upperBin=(int) ((T)i*gridFactor + 0.5);\n\t  if (upperBin >nBins-1) upperBin=nBins-1;\n\t\t T maxValue=smooth[i];\n\t  int maxBin=i;\n   double sum=0;\t \n   for (int k=i+1;k<=upperBin;k++){\n\t\t \tif(smooth[k] > maxValue){\n\t\t\t\t maxValue=smooth[k];\n\t\t\t\t maxBin=k;\n\t\t\t }\n \t\t sum+=smooth[k];\t\t \n\t\t }\n\t\t maxValues.push_back(maxValue);\n\t\t maxBins.push_back(maxBin);\n\t\t //meanValues.push_back((T)sum/(T)(upperBin-i+1));\t\n\t\t meanValues.push_back((T)sum);\t\t\t \t\t \n\t\t i=upperBin+1;\n\t\t}\t \n\t\tvector <T> myPeakValues,myPeakBins,myPeakMeans;\n\t for  (int i=2;i<maxBins.size()-2;i++){\n\t\t\tif(maxBins[i-2] > minValue && maxBins[i+1] < maxValue){ //-2 necessary otherwise there is an edge effect\n \t\t if(meanValues[i] > meanValues[i-1] && meanValues[i] > meanValues[i+1]){\t\n\t\t  \tmyPeakBins.push_back(maxBins[i]);\n\t\t\t  myPeakValues.push_back(maxValues[i]);\t\n\t\t\t  myPeakMeans.push_back(meanValues[i]);\n\t\t  }\n\t\t\t}\n\t\t}\n\t\t//check for empty case - no peaks - seed with middle\n\t\tif(!myPeakBins.size()){\n\t\t\tfor  (int i=maxBins.size()/3;i<maxBins.size();i+=maxBins.size()/2){\n\t\t\t myPeakBins.push_back(maxBins[i]);\n\t\t\t myPeakValues.push_back(maxValues[i]);\t\n\t\t\t myPeakMeans.push_back(meanValues[i]);\n\t\t\t}\n\t\t}\t\n\t\t \n\t\tvector<int> index;\n\t\tindex.resize(myPeakMeans.size());\n\t\tpeakBins.resize(1);\n\t\tpeakMeans.resize(1);\n\t\tpeakValues.resize(1);\n\t\tsort_by_scores(myPeakMeans.size(),myPeakMeans.data(),index.data(),0);\n\t\t\t\t \n\t\tpeakBins[0]=myPeakBins[index[0]];\n\t\tpeakValues[0]=myPeakValues[index[0]];\n\t\tpeakMeans[0]=myPeakMeans[index[0]];\n\t for (int i=1;i<index.size();i++){\n\t\t\tconst int s=index[i];\n\t\t\tif(myPeakMeans[s] < 0.2*myPeakMeans[0])break; \n\t\t peakBins.push_back(myPeakBins[s]);\n\t\t peakValues.push_back(myPeakValues[s]);\n\t\t peakMeans.push_back(myPeakMeans[s]);\n\t\t}\t \n\t}\n\ttemplate <class T> void findPeaks(int *counts, int nBins, T gridSize,vector<int> &peakBins, vector<T> &peakValues, vector<T> &peakMeans){\n\t\t//finds peaks using a interval (grid) search\n\t\t//uses equal log intervals\n\t\t//an interval contains a peak if the previous interval and and the following interval have lower mean values\n\t\t//the bin with the maxCounts in that interval is the location of a peak\n\t\t//peaks are then sorted by mean values (max values is more vulnerable to spikes)\n\t\t//a good value for grid size is roughly the std deviation of the expected peaks\n\t\t\n  vector<T> maxValues,meanValues;\n  vector<int>maxBins;\n  if(nBins <4){\n\t\t\t//edge case - return the middle bin\n\t\t\tpeakBins.resize(1);\n\t\t peakMeans.resize(1);\n\t\t peakValues.resize(1);\n\t\t\tpeakBins[0]=nBins/2;\n\t\t\tpeakMeans[0]=counts[nBins/2];\n\t\t\tpeakValues[0]=counts[nBins/2];\n\t\t\treturn;\n\t\t}\n\t \n\t \n\t int minBin=pow(2,minValue);int maxBin=(pow(2,maxValue) < nBins)?pow(2,maxValue) : nBins;\n\t T gridFactor=pow(2,gridSize);\n\t \n\n\t int i=minBin;\n\t\twhile(i<nBins){\n\t\t\tint upperBin=(int) ((T)i*gridFactor + 0.5);\n\t  if (upperBin >nBins-1) upperBin=nBins-1;\n\t\t T maxValue=counts[i];\n\t  int maxBin=i;\n   double sum=0;\t \n   for (int k=i+1;k<=upperBin;k++){\n\t\t \tif(counts[k] > maxValue){\n\t\t\t\t maxValue=counts[k];\n\t\t\t\t maxBin=k;\n\t\t\t }\n \t\t sum+=counts[k];\t\t \n\t\t }\n\t\t maxValues.push_back(maxValue);\n\t\t maxBins.push_back(maxBin);\n\t\t //meanValues.push_back((T)sum/(T)(upperBin-i+1));\t\n\t\t meanValues.push_back((T)sum);\t\t\t \t\t \n\t\t i=upperBin+1;\n\t\t}\t \n\t\tvector <T> myPeakValues,myPeakBins,myPeakMeans;\n\t for  (int i=2;i<maxBins.size()-2;i++){\n\t\t\tif(maxBins[i-2] > minValue && maxBins[i+1] < maxValue){ //-2 necessary otherwise there is an edge effect\n \t\t if(meanValues[i] > meanValues[i-1] && meanValues[i] > meanValues[i+1]){\t\n\t\t  \tmyPeakBins.push_back(maxBins[i]);\n\t\t\t  myPeakValues.push_back(maxValues[i]);\t\n\t\t\t  myPeakMeans.push_back(meanValues[i]);\n\t\t  }\n\t\t\t}\n\t\t}\n\t\t//check for empty case - no peaks - seed with middle\n\t\tif(!myPeakBins.size()){\n\t\t\tfor  (int i=maxBins.size()/3;i<maxBins.size();i+=maxBins.size()/2){\n\t\t\t myPeakBins.push_back(maxBins[i]);\n\t\t\t myPeakValues.push_back(maxValues[i]);\t\n\t\t\t myPeakMeans.push_back(meanValues[i]);\n\t\t\t}\n\t\t}\t\n\t\t \n\t\tvector<int> index;\n\t\tindex.resize(myPeakMeans.size());\n\t\tpeakBins.resize(1);\n\t\tpeakMeans.resize(1);\n\t\tpeakValues.resize(1);\n\t\tsort_by_scores(myPeakMeans.size(),myPeakMeans.data(),index.data(),0);\n\t\t\t\t \n\t\tpeakBins[0]=myPeakBins[index[0]];\n\t\tpeakValues[0]=myPeakValues[index[0]];\n\t\tpeakMeans[0]=myPeakMeans[index[0]];\n\t for (int i=1;i<index.size();i++){\n\t\t\tconst int s=index[i];\n\t\t\tif(myPeakMeans[s] < 0.2*myPeakMeans[0])break; \n\t\t peakBins.push_back(myPeakBins[s]);\n\t\t peakValues.push_back(myPeakValues[s]);\n\t\t peakMeans.push_back(myPeakMeans[s]);\n\t\t}\t \n\t}\n\ttemplate <class T> int deconvolute(DeconRecord<T> &deconRecord,FILE *fpRaw,FILE *fpSmooth){\n\t if(!logx[2]){init_logx();}\n\t\tT smooth[32768];\n\t\tint counts[32768];\n\t\tfill(smooth,smooth+32768,0);\n\t\tfill(counts,counts+32768,0);\n\t\tif(fpSmooth) fwrite(smooth,1,sizeof(T)*32768,fpSmooth); \n\t if(fpRaw) fwrite(counts,1,sizeof(T)*32768,fpRaw);\n\t\tint upper[32768];\n\t\tint lower [32768];\n\t\tmemset (lower,0,32768*sizeof(int));\n\t\tmemset (upper,0,32768*sizeof(int));\n\t\tconst T upperConstant=pow(2,smoothHalfWindowSize);\n\t\tconst T lowerConstant=1.0/upperConstant;\n\t\tfor (int i=0;i<32768;i++){\n\t\t\tlower[i]= (int) (((T)i)*lowerConstant+.5);\n   upper[i]= (int) (((T)i)*upperConstant+.5);\t\n   if(upper[i] > 32767)upper[i]=32767;\n\t }\n\t\tfor (int i=1; i<=NCOLORS; i++){\n\t\t\tfill(smooth,smooth+32768,0);\n\t\t\tvector<T> peakValues,peakMeans;\n\t\t\tvector<int>peakBins;\t\t\t\n\t\t\tint nBins=logWindowSmooth(lower,upper,smooth,&(values[i][0]),values[i].size());\n\t\t\tdouble lowNoiseFraction=dampenLowNoise(smooth,nBins);\n\t\t\tif(fpSmooth)fwrite(smooth,1,32768*sizeof(T),fpSmooth);\n\t\t\tfill(counts,counts+32768,0);\n\t\t\tfor(int k=0;k<values[i].size();k++)\n\t\t\t counts[values[i][k]]++;\n\t\t\t \n\t\t\tif(fpRaw){\n    fwrite(counts,1,32768*sizeof(T),fpRaw);\n\t\t\t}\n   findPeaks<T>(smooth,nBins,0.2,peakBins,peakValues,peakMeans);\n   if(i >10){\n\t\t\t\tT nPoints=(double)values[i].size()-lowNoiseFraction*(double)values[i].size();\n\t\t\t for(int k=0;k<32768;k++){\n\t \t\t\tsmooth[k]=counts[k];\n \t\t\t} \n    fitLogNormEM(smooth,0,nBins,nPoints,peakBins,deconRecord,i,1,0);\n    deconRecord.noiseFractions[i]=lowNoiseFraction;\n\t\t\t}\n\t\t}\n\t}\n\ttemplate <class T> int deconvolute(int nFold,int n,int nGroups,vector<DeconRecord<T>> &deconRecords,vector<MedianRecord<T>>&medianRecords,FILE *fpRaw){\n\t\treturn deconvolute_peakSeed(nFold,n,nGroups,deconRecords,medianRecords,fpRaw);\n\t\t//return deconvolute_peakSeed(n,nGroups,deconRecords[0],fpRaw);\n\t}\t\n template <class T> int deconvolute_peakSeed(int n,int nGroups,DeconRecord<T> &deconRecord,FILE *fpRaw){\n\t if(!logx[2]){init_logx();}\n\t\tint counts[32768];\n\t\tfill(counts,counts+32768,0);\n\t if (fpRaw) fwrite(counts,1,sizeof(T)*32768,fpRaw);\n\t int finalGroupOffset= (n+nGroups >= groupOffsets.size())? groupOffsets[groupOffsets.size()-1] : groupOffsets[n+nGroups];\n\t //fprintf(stderr,\"%d start %d final offset %d\\n\",n,groupOffsets[n],finalGroupOffset);\n\t\tfor (int i=1; i<=NCOLORS; i++){\n\t\t\tconst int start=offsets[i][groupOffsets[n]];\n\t\t\tconst int finish= offsets[i][finalGroupOffset];\n\t\t\tint nBins=0;\n\t\t\tT nPoints=finish-start;\n\t\t\tif(nPoints >= MINBEADS){ \n\t\t\t vector<int>peakBins;\n\t\t\t peakBins.resize(2);\t\t\n\t\t\t \n\t\t\t fill(counts,counts+32768,0);\n\t\t\t for(int k=start;k<finish;k++){\n\t\t\t\t\tif(values[i][k]>nBins) nBins=values[i][k]+1;\n\t\t\t  counts[values[i][k]]++;\n\t\t\t\t}\n\t\t\t if(fpRaw) fwrite(counts,1,32768*sizeof(int),fpRaw);\n    peakBins[0]=pow(2,8.1);\n    peakBins[1]=pow(2,7.9);\t\t \n    if(i >10){\n\t\t\t\t\tT tcounts[32768];\n\t\t\t\t\tfill(tcounts,tcounts+32768,0);\n\t\t\t\t\tint k=0;\n\t\t\t\t\twhile (k<minValue){\n\t\t\t\t\t\tnPoints-=counts[k];\n\t\t\t\t\t\t//tcounts[k]=counts[k];\n\t\t\t\t\t\tk++;\n\t\t\t\t\t}\n\t\t\t\t\twhile (k<32768){\n\t \t\t\t tcounts[k]=counts[k];\n\t \t\t\t k++;\n \t\t\t }\n     fitLogNormEM(tcounts,0,nBins,nPoints,peakBins,deconRecord,i,1,1);\n     deconRecord.noiseFractions[i]=1.0-(nPoints/(T)(finish-start));\n\t\t\t\t}\n\t\t\t}\n\t\t\telse{\n\t\t\t deconRecord.dataSizes[i]=finish-start;\n\t\t\t\tif(fpRaw){\n\t\t   fill(counts,counts+32768,0);\n\t\t   for(int k=start;k<finish;k++)\n\t\t\t   counts[values[i][k]]++;\n\t    fwrite(counts,1,sizeof(int)*32768,fpRaw);\n\t\t\t }\t\t\t\t\n\t\t\t}\t\n\t\t}\n\t\treturn(1);\n\t}\n\ttemplate <class T> int deconvolute_peakSeed(int nFold,int n,int nGroups,vector<DeconRecord<T>> &deconRecords,vector<MedianRecord<T>>&medianRecords,FILE *fpRaw){\n  //this overload takes 1/10 slices and finds the median value\n\t if(!logx[2]){init_logx();}\n\t\tint counts[32768];\n\t if (fpRaw) fwrite(counts,1,sizeof(T)*32768,fpRaw);\n\t int finalGroupOffset= (n+nGroups >= groupOffsets.size())? groupOffsets[groupOffsets.size()-1] : groupOffsets[n+nGroups];\n\t //fprintf(stderr,\"%d start %d final offset %d\\n\",n,groupOffsets[n],finalGroupOffset);\n\t\tfor (int i=1; i<=NCOLORS; i++){\n\t\t\tconst int start=offsets[i][groupOffsets[n]];\n\t\t\tconst int finish= offsets[i][finalGroupOffset];\t\t\t\n\t\t\tif(i >10){\n\t\t\t int nBins=0;\n\t\t\t int totalPoints=finish-start;\n\t\t\t if(totalPoints >= MINBEADS){ \n\t\t\t  vector<int>peakBins(2);\n\t\t\t  vector<unsigned int>foldIndices=getFolds(totalPoints,nFold);; \n\t\t\t  for(int f=0;f<nFold;f++){\n\t\t\t\t\t\tint nPoints=0;\n\t\t\t\t\t\tfill(counts,counts+32768,0);\n\t\t\t\t\t\tunsigned int j=0;\n\t\t  \t for(int k=start;k<finish;k++){\n\t\t\t\t\t\t\tif(nFold >1 && foldIndices[j++] == f ) continue;\n\t\t  \t\t\tif(values[i][k]>nBins) nBins=values[i][k]+1;\n\t\t \t   counts[values[i][k]]++;\n\t\t \t   nPoints++;\n\t\t \t \t}\n\t\t \t  if(fpRaw) fwrite(counts,1,32768*sizeof(int),fpRaw);\n      peakBins[0]=pow(2,8.1);\n      peakBins[1]=pow(2,7.9);\t\t \n\n\t\t\t \t\tT tcounts[32768];\n\t\t\t \t\tfill(tcounts,tcounts+32768,0);\n\t\t\t \t\tint k=0;\n\t\t\t \t\twhile (k<minValue){\n\t\t\t\t \t\tnPoints-=counts[k];\n\t\t\t \t\t\t//tcounts[k]=counts[k];\n\t\t\t\t \t\tk++;\n\t\t\t\t \t}\n\t\t\t\t \twhile (k<32768){\n\t \t\t \t tcounts[k]=counts[k];\n\t \t\t \t k++;\n \t\t\t  }\n      fitLogNormEM(tcounts,0,nBins,nPoints,peakBins,deconRecords[f],i,1,1);\n      medianRecords[i].addValues(deconRecords[f].means0[i], deconRecords[f].means1[i]);\n      deconRecords[f].noiseFractions[i]=1.0-(nPoints/(T)(totalPoints));\n\t\t\t\t }\n\t\t\t\t}\n\t\t\t}\n\t\t\telse{\n\t\t\t\t//write a blank Deconrecord with nPoints\n\t\t\t\tfor(int f=0;f<nFold;f++){\n\t\t\t\t deconRecords[f].dataSizes[i]=finish-start;\n\t\t\t\t}\n\t\t\t\tif(fpRaw){\n\t\t   fill(counts,counts+32768,0);\n\t\t   for(int k=start;k<finish;k++)\n\t\t\t   counts[values[i][k]]++;\n\t    fwrite(counts,1,sizeof(int)*32768,fpRaw);\n\t\t\t }\t\t\t\t\n\t\t\t}\n\t\t}\n\t\treturn(1);\n\t}\n template <class T> int fitLogNormEM(T *smooth,bool normed, int nBins,int nPoints,vector<int> &peakBins,DeconRecord<T> &deconRecord,int color,bool isMode,bool seed){\n  const T s0=PEAKWIDTH;\n  const T s1=PEAKWIDTH;\n  T sigmasqs[2]={s0*s0,s1*s1};\n  vector<T> mus;\n  mus.resize(peakBins.size());\n  if(isMode){\n   for(int i=0;i<peakBins.size();i++)\n    mus[i]=logx[peakBins[i]]-s0*s0; \n\t\t}\n\t\telse{\n\t  for(int i=0;i<peakBins.size();i++)\n    mus[i]=logx[peakBins[i]]; \t\t\n\t\t}\t\n  //starting for search is both lognormals at the estimated medians\n  \n  //keep record of initial mode estimate\n\t\tdeconRecord.meansEst0[color]=logx[peakBins[0]];\n\t\tdeconRecord.meansEst1[color]=logx[peakBins[1]];\n\t\tT input_mus[2]={mus[0]+ (T).05,mus[0]-(T).05};\n\t\tEM_GMM <float> EM (smooth,normed,nBins,nPoints,minValue,maxValue,input_mus,sigmasqs,.5, MIXTURE_RATIO, 0.15,0.7,.275,PEAKWIDTH,.355); \n\t\tif (seed){\n\t\t\tEM.reset(mus[0],mus[1],sigmasqs[0],sigmasqs[1],MIXTURE_RATIO);       \t\t\t\n\t\t\tEM.seed_mclust(0.5);\n\t\t\tmus.resize(2);\n\t\t\tif(isnan(EM.mean0)){\n\t\t\t\tmus[0]=EM.mean1*INVLOG2+.05;\n\t\t\t mus[1]=EM.mean1*INVLOG2-.05;\n\t\t\t}\n\t\t\telse if(isnan(EM.mean1)){\n\t\t\t mus[0]=EM.mean0*INVLOG2+.05;\n\t\t\t mus[1]=EM.mean0*INVLOG2-.05;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tmus[0]=EM.mean0*INVLOG2+.05;\n\t\t\t mus[1]=EM.mean1*INVLOG2-.05;\t\n\t\t\t}\n\t\t\tEM.reset(mus[0]+.05,mus[1]-.05,sigmasqs[0],sigmasqs[1],MIXTURE_RATIO); \n\t\t}\n\t\t\n  int converged=EM.optimize(MIXTURE_RATIO);\n  transferData(color,deconRecord,EM);\n  double best_likelihood=EM.loglikelihood;\n\n  for(int j=0;j<mus.size()-1;j++){\n\t\t\tfor (int k=j+1;k<mus.size();k++){ \n\t\t\t\tEM.reset(mus[j],mus[k],sigmasqs[0],sigmasqs[1],MIXTURE_RATIO); \n\t\t\t\tint converged=EM.optimize(MIXTURE_RATIO);\n\t\t\t\tdouble likelihood=EM.loglikelihood;   \n\t\t\t\tif(likelihood < best_likelihood){\n\t\t\t\t\tbest_likelihood=likelihood;\n\t\t\t\t transferData(color,deconRecord,EM);\n\t\t\t\t deconRecord.meansEst0[color]=mus[j];deconRecord.meansEst1[color]=mus[k];\n\t\t\t\t}\n\t\t\t\tEM.reset(mus[k],mus[j],sigmasqs[1],sigmasqs[0],MIXTURE_RATIO); \n\t\t\t\tconverged=EM.optimize(MIXTURE_RATIO);\n\t\t\t\tlikelihood=EM.loglikelihood;   \n\t\t\t\tif(likelihood < best_likelihood){\n\t\t\t\t\tbest_likelihood=likelihood;\n\t\t\t\t transferData(color,deconRecord,EM);\n\t\t\t\t deconRecord.meansEst0[color]=mus[j];deconRecord.meansEst1[color]=mus[k];\n\t\t\t\t}\t\t\t\t\t\n\t\t\t}\t \n\t\t}\n }\t  \n\tvector<unsigned int> getFolds(unsigned int size, unsigned int nFold){\n\t\t//for assigning nfolds\n\t\tvector<unsigned int> shuffledIndices(size);\n  std::random_device rd;\n  std::mt19937 rng(rd());\n\t\tfor(unsigned int i=0;i<size;i++){\n\t\t\tshuffledIndices[i]=i%nFold;\n\t\t}\n\t\tfor\t(unsigned int i=0;i<size;i++){\n\t\t\tstd::uniform_int_distribution<int> uni(i,size-1);\n\t\t\tunsigned int j=uni(rng);\n \t swap(shuffledIndices[i],shuffledIndices[j]);\n\t\t}\n\t\treturn shuffledIndices;\n\t}\t\t\n};\n\n", "meta": {"hexsha": "4f87305377ba8429ef766c44be5b5f7743335b8c", "size": 43213, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/gmm.hpp", "max_stars_repo_name": "BioDepot/L1kpp", "max_stars_repo_head_hexsha": "a08b568fff9879a3ee56cdc339890dfb8a32a54c", "max_stars_repo_licenses": ["BSD-2-Clause", "MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/gmm.hpp", "max_issues_repo_name": "BioDepot/L1kpp", "max_issues_repo_head_hexsha": "a08b568fff9879a3ee56cdc339890dfb8a32a54c", "max_issues_repo_licenses": ["BSD-2-Clause", "MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gmm.hpp", "max_forks_repo_name": "BioDepot/L1kpp", "max_forks_repo_head_hexsha": "a08b568fff9879a3ee56cdc339890dfb8a32a54c", "max_forks_repo_licenses": ["BSD-2-Clause", "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.8925490196, "max_line_length": 286, "alphanum_fraction": 0.6540624349, "num_tokens": 14712, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255927, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.46221938014716313}}
{"text": "#define CATCH_CONFIG_MAIN\n#include <catch2/catch.hpp>\n\n#include \"utils.h\"\n#include <NTL/GF2E.h>\n#include <NTL/GF2EX.h>\n\nTEST_CASE(\"Precomputed Lagrange Interpolation\", \"[util]\") {\n  utils::init_ntl_extension_field(utils::NTL_INSTANCE::GF2_128);\n  size_t dimension = 20;\n  vec_GF2E x_values;\n  vec_GF2E y_values1;\n  vec_GF2E y_values2;\n  for (size_t i = 0; i < dimension; i++) {\n    x_values.append(random_GF2E());\n    y_values1.append(random_GF2E());\n    y_values2.append(random_GF2E());\n  }\n\n  // builtin interpolate\n  GF2EX poly1 = interpolate(x_values, y_values1);\n  GF2EX poly2 = interpolate(x_values, y_values2);\n  // precomputed interpolate\n  auto precomputation = utils::precompute_lagrange_polynomials(x_values);\n  GF2EX poly1_with_precom =\n      utils::interpolate_with_precomputation(precomputation, y_values1);\n  GF2EX poly2_with_precom =\n      utils::interpolate_with_precomputation(precomputation, y_values2);\n\n  REQUIRE(poly1 == poly1_with_precom);\n  REQUIRE(poly2 == poly2_with_precom);\n}\n", "meta": {"hexsha": "16d5045c1d75a3bbc3e99bb9602479361e2d46a6", "size": 1004, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "field/tests/util_test.cpp", "max_stars_repo_name": "shibammukherjee/rainier-signatures", "max_stars_repo_head_hexsha": "cd7c89e418d52c1288c1d802b30043d09bb89cd8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-12T03:53:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-12T03:53:58.000Z", "max_issues_repo_path": "field/tests/util_test.cpp", "max_issues_repo_name": "shibammukherjee/rainier-signatures", "max_issues_repo_head_hexsha": "cd7c89e418d52c1288c1d802b30043d09bb89cd8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "field/tests/util_test.cpp", "max_forks_repo_name": "shibammukherjee/rainier-signatures", "max_forks_repo_head_hexsha": "cd7c89e418d52c1288c1d802b30043d09bb89cd8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-09-22T11:30:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T11:30:36.000Z", "avg_line_length": 30.4242424242, "max_line_length": 73, "alphanum_fraction": 0.7470119522, "num_tokens": 290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4622154084631668}}
{"text": "//\n// Created by Sylvain  on 5/30/20.\n//\n\n#include \"SatOps/MagneticField.h\"\n#include \"SatOps/constants.h\"\n#include \"SatOps/ReferenceFrame.h\"\n#include <cmath>\n#include <fstream>\n#include <sstream>\n#include <stdexcept>\n#include <string>\n#include <boost/math/special_functions/factorials.hpp>\n\n\nMagneticField::MagneticField(Model model, unsigned int max_degree, const std::filesystem::path& file, double year)\n    :\n    PotentialField(max_degree),\n    m_model(model)\n{\n    // Allocates and initializes vectors containing the coefficients\n    unsigned int num_entries = (max_degree + 1) * (max_degree + 2) / 2;\n    m_c_coeffs = std::vector(num_entries, 0.0);\n    m_s_coeffs = std::vector(num_entries, 0.0);\n\n    switch (m_model) {\n        case Model::IGRF13:\n            if (m_max_degree > 13)\n                throw std::invalid_argument(\"MagneticField: The degree of expansion is out of range (max 13).\");\n            if (year < 1900. || year > 2025.)\n                throw std::invalid_argument(\"MagneticField: The year is out of range. The model is valide from 1900 to 2025.\");\n\n            loadIGRF13Coeffs(file, year);\n            m_radius = constants::IGRF13_RADIUS;\n            m_scale_factor = 1E-9 * constants::IGRF13_RADIUS * constants::IGRF13_RADIUS;\n            break;\n    }\n}\n\n// The coefficients of the model are computed for the initial epoch of the simulation\nvoid MagneticField::loadIGRF13Coeffs(const std::filesystem::path& path, double year) {\n\n    // Gets reference epoch of the model and difference with desired time\n    int T0 = static_cast<int>(year) - static_cast<int>(std::floor(year)) % 5;\n    double dt = year - T0;\n    int year_col = (T0 - 1900) / 5 + 3;\n\n    // Opens file containing the geomagnetic coefficients and populates arrays\n    std::ifstream data_file(path);\n    if (data_file.is_open()) {\n\n        // Skips first four lines (header)\n        std::string str;\n        for (int i = 0; i < 4; ++i) {\n            std::getline(data_file, str);\n        }\n\n        // Reads required lines\n        while (std::getline(data_file, str)) {\n            std::istringstream iss(str);\n            std::string value;\n            std::string coeff;\n            int col = 0, degree = 0, order = 0;\n            double main_field_coeff = 0., secular_variation_coeff = 0.;\n\n            while (iss >> value) {\n                if (col == 0)\n                    coeff = value;\n                else if (col == 1)\n                    degree = stoi(value);\n                else if (col == 2)\n                    order = stoi(value);\n                else if (col == year_col)\n                    main_field_coeff = stod(value);\n                else if (col == 28) // if last column, secular variation is directly given\n                    secular_variation_coeff = stod(value);\n                else if (col == year_col + 1)\n                    secular_variation_coeff = (stod(value) - main_field_coeff) / 5.0;\n\n                ++col;\n            }\n\n            if (degree > m_max_degree)\n                break;\n\n            int i = getIndex(degree, order);\n            double kron_delta = (0 == order) ? 1. : 0.;\n            double unnormalization_factor = std::sqrt(2.0 * boost::math::factorial<double>(degree-order) / boost::math::factorial<double>(degree+order) - kron_delta);\n            if (coeff == \"g\") {\n                m_c_coeffs[i] = unnormalization_factor * (main_field_coeff + dt * secular_variation_coeff);\n            } else if (coeff == \"h\") {\n                m_s_coeffs[i] = unnormalization_factor * (main_field_coeff + dt * secular_variation_coeff);\n            }\n        }\n        data_file.close();\n    } else {\n        throw std::invalid_argument(\"MagneticField: The file containing the magnetic coefficients could not be opened.\");\n    }\n}\n\nVector3d MagneticField::getMagneticField(const Vector3d& itrf93_position, Matrix3d* jacobian) {\n    double x = itrf93_position[0];\n    double y = itrf93_position[1];\n    double z = itrf93_position[2];\n    double r = itrf93_position.norm();\n\n    std::array<double, 12> sums{};\n    sums.fill(0.0);\n    sums[0] = m_radius / (r*r) * (3. * (m_c_coeffs[getIndex(1,1)] * x + m_s_coeffs[getIndex(1,1)] * y) + 2. * m_c_coeffs[getIndex(1,0)] * z);\n    sums[1] = m_radius / r * m_c_coeffs[getIndex(1,0)];\n    sums[2] = m_radius / r * m_c_coeffs[getIndex(1,1)];\n    sums[3] = m_radius / r * m_s_coeffs[getIndex(1,1)];\n    sums[4] = 2.0;\n\n    Vector3d mag_field = computeGradient(x, y, z, sums, jacobian);\n    mag_field.setFrame(ReferenceFrame::ITRF93);\n    return mag_field;\n}", "meta": {"hexsha": "109a24c8e43e8d1b7dd78afee64b959e7f079d8e", "size": 4533, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/MagneticField.cpp", "max_stars_repo_name": "srenevey/satops", "max_stars_repo_head_hexsha": "7051d7734d5761c49ae23e446b6b2dfc893daf04", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-02-16T07:37:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T07:07:09.000Z", "max_issues_repo_path": "src/MagneticField.cpp", "max_issues_repo_name": "srenevey/satops", "max_issues_repo_head_hexsha": "7051d7734d5761c49ae23e446b6b2dfc893daf04", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/MagneticField.cpp", "max_forks_repo_name": "srenevey/satops", "max_forks_repo_head_hexsha": "7051d7734d5761c49ae23e446b6b2dfc893daf04", "max_forks_repo_licenses": ["Apache-2.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.4152542373, "max_line_length": 166, "alphanum_fraction": 0.5965144496, "num_tokens": 1176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891130942472, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.46221539866572164}}
{"text": "\n#pragma once\n\n/// @file\n\n#include <cstdint>\n#include <utility>\n#include <Eigen/Core>\n\nnamespace neon\n{\nusing indices = Eigen::Array<std::int32_t, Eigen::Dynamic, Eigen::Dynamic>;\n\n/// Type alias for whatever type is returned from these views\nusing index_view = decltype(std::declval<const indices>()(Eigen::all, 0l));\n}\n", "meta": {"hexsha": "ed5bcd667e51bf6f9d666d8beae114fb02953bf1", "size": 321, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/numeric/index_types.hpp", "max_stars_repo_name": "dbeurle/neon", "max_stars_repo_head_hexsha": "63cd2929a6eaaa0e1654c729cd35a9a52a706962", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2018-07-12T17:06:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-20T23:13:26.000Z", "max_issues_repo_path": "src/numeric/index_types.hpp", "max_issues_repo_name": "dbeurle/neon", "max_issues_repo_head_hexsha": "63cd2929a6eaaa0e1654c729cd35a9a52a706962", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 119.0, "max_issues_repo_issues_event_min_datetime": "2016-06-22T07:36:04.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-10T19:38:12.000Z", "max_forks_repo_path": "src/numeric/index_types.hpp", "max_forks_repo_name": "dbeurle/neon", "max_forks_repo_head_hexsha": "63cd2929a6eaaa0e1654c729cd35a9a52a706962", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2017-10-08T16:51:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-15T08:08:04.000Z", "avg_line_length": 18.8823529412, "max_line_length": 75, "alphanum_fraction": 0.7165109034, "num_tokens": 79, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.7057850340255385, "lm_q1q2_score": 0.4622148986201438}}
{"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <armadillo>\n#include <iostream>\n\n\nusing namespace arma;\nusing namespace std;\n\nint main(void)\n{\n///read\n  ofstream myFile;\n  vec v(7);\n  for (int i = 0;i<7;i++)\n    v(i) = i;\n   // v = {1, 2, 3, 4, 5, 6, 7};\n  myFile.open(\"Collector/todelete.log\");\n  for (int i = 0;i<20;i++)\n    myFile<<v;\n  myFile.close();\n\n\n    /* read */\n\n      std::ifstream ifile(\"Collector/todelete.log\", std::ios::in);\n      // std::ifstream ifile(\"Collector/posCollected.txt\", std::ios::in);\n\n      std::vector<double> scores;\n\n      //check to see that the file was opened correctly:\n      if (!ifile.is_open()) {\n          std::cerr << \"There was a problem opening the input file!\\n\";\n          exit(1);//exit or do additional error checking\n      }\n\n      int DIM = 7;\n      double num = 0.0;\n      int i = 0;\n\n      //keep storing values from the text file so long as data exists:\n      while (ifile >> num) {\n          scores.push_back(num);\n      }\n\n      mat m(DIM,int(scores.size()/DIM));\n      int t=-1;\n\n      for (int i = 0; i < int(scores.size()/DIM); ++i)\n      {\n        for (int e = 0; e<DIM; e++)\n        {\n          t++;\n          m(e,i) = scores[t] ;\n        }\n      }\ncout<<\"start out m\"<<endl;\n      //verify that the scores were stored correctly:\n      for (int i = 0; i < int(scores.size()/DIM); ++i) {\n          for (int e = 0; e<DIM; e++)\n          {\n            // std::cout << scores[i+e] << \"\\t\";\n            std::cout << m(e,i) << \"\\t\" ;\n          }\n          cout<<endl;\n      }\n\n  //// get\n    // FILE *fp;\n    // char ch=' ';\n    // int cnt=0;\n   \t// fp=fopen(\"Collector/todelete.log\",\"r\");\n    // if (fp==NULL) exit(2);\n    // vec vv(1);\n    // while((ch=fgetc(fp))!=EOF)\n    // {\n\t  //    vv(1) = putchar(ch);\n    //\n    // }\n    //\n    // fclose(fp);\n    // printf(\"\\n b meros\\n\");\n    // //------------------------------------------\n    // FILE *fp1;\n    // int ar0,ar1,ar2,ar3,ar4,ar5,ar6,k;\n    //  fp1=fopen(\"Collector/todelete.log\",\"r\");\n    //  if (fp1==NULL)\n    //  {\n    //     puts(\"Provlima sto anoigma toy arxeioy\");\n    //     exit(2);\n    //  }\n    //\n    //   while (k=fscanf(fp1,\"%d %d %d %d %d %d %d\", &ar0, &ar1, &ar2, &ar3, &ar4, &ar5, &ar6)>=1)\n    //  {\n    //\n\t  //  //  a++;\n\t  //  //  printf(\"%d\",a);\n    //\n    //      printf(\"%d %d %d %d %d %d %d \\n\",ar0,ar1,ar2, ar3,ar4,ar5,ar6);\n    //      fgetc(fp1);\n    //  }\n    //  fclose(fp1);\n\n    return 0;\n}\n", "meta": {"hexsha": "2e4cf060a74b958d43c05661e7374dff252d3812", "size": 2437, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test_file.cpp", "max_stars_repo_name": "despargy/KukaImplementation-kinetic", "max_stars_repo_head_hexsha": "3a9ab106b117acfc6478fbf3e60e49b7e94b2722", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-21T12:49:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-21T12:49:27.000Z", "max_issues_repo_path": "src/test_file.cpp", "max_issues_repo_name": "despargy/KukaImplementation-kinetic", "max_issues_repo_head_hexsha": "3a9ab106b117acfc6478fbf3e60e49b7e94b2722", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/test_file.cpp", "max_forks_repo_name": "despargy/KukaImplementation-kinetic", "max_forks_repo_head_hexsha": "3a9ab106b117acfc6478fbf3e60e49b7e94b2722", "max_forks_repo_licenses": ["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.9905660377, "max_line_length": 98, "alphanum_fraction": 0.4546573656, "num_tokens": 800, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850154599562, "lm_q2_score": 0.6548947155710233, "lm_q1q2_score": 0.4622148769539383}}
{"text": "/*\n * OrientationBox.hpp\n *\n *  Created on: 01.11.2018\n *      Author: tomlucas\n */\n\n#ifndef ESTIMATORS_STATEBOXES_HOMOCOORDBOX_HPP_\n#define ESTIMATORS_STATEBOXES_HOMOCOORDBOX_HPP_\n\n#include \"StateBox.hpp\"\n#include <eigen3/Eigen/Core>\n#include <Eigen_Utils.hpp>\n#include <stdio.h>\n\nnamespace zavi\n::estimator::state_boxes {\n\t/**\n\t * A Box which contains homogenous coordinates\n\t * This is basically the calibration matrix for the offset between IMU and body coordinates\n\t */\n\tclass HomoCoordBox : public StateBox<16,6,0> {\n\t\ttemplate<typename T>\n\t\tusing ROT_MATRIX= Eigen::Matrix<T,3,3>;\n\n\n\t\ttemplate<typename T>\n\t\tinline static const Eigen::Matrix<T,4,4> remap(const OUTER_T<T> & state){\n\t\t\treturn Eigen::Map<const Eigen::Matrix<T,4,4>>(state.data());\n\t\t}\n\n\n\tpublic:\n\t\tHomoCoordBox(std::shared_ptr<plugin::SensorPlugin> sensor):StateBox<outer_size,inner_size,input_size>(sensor) {\n\t\t}\n\t\tvirtual ~HomoCoordBox() {};\n\n\t\ttemplate<typename T>\n\t\tinline static OUTER_T<T> boxPlus(const OUTER_T<T> &state,const INNER_T<T> &delta) {\n\t\t\tassert_inputs(state,delta);\n\t\t\tEigen::Matrix<T,4,4> result=result.Identity();\n\t\t\tresult.template block<3,3>(0,0)=zavi::eigen_util::boxPlusOrientation<T>(remap(state).template block<3,3>(0,0),delta.template block<3,1>(0,0));\n\t\t\tresult.template block<3,1>(0,3)=state.template block<3,1>(12,0)+delta.template block<3,1>(3,0);\n\t\t\treturn Eigen::Map<OUTER_T<T>>(result.data());\n\t\t}\n\t\ttemplate<typename T>\n\t\tinline static INNER_T<T> boxPlusInnerSpace(const INNER_T<T> &delta1,const INNER_T<T> &delta2) {\n\t\t\tassert_inputs(delta1,delta2);\n\t\t\treturn delta1+delta2;\n\t\t}\n\n\t\ttemplate<typename T>\n\t\tinline static INNER_T<T> boxMinus(const OUTER_T<T> &a,const OUTER_T<T> &b) {\n\t\t\tassert_inputs(a,b);\n\t\t\tINNER_T<T> result=result.Zero();\n\t\t\tresult.template block<3,1>(0,0)=zavi::eigen_util::boxMinusOrientation<T,T>(remap(a).template block<3,3>(0,0),remap(b).template block<3,3>(0,0));\n\t\t\tresult.template block<3,1>(3,0)=b.template block<3,1>(12,0)-a.template block<3,1>(12,0);\n\t\t\treturn result;\n\t\t}\n\n\t\ttemplate<typename T>\n\t\tinline static OUTER_T<T> stateTransition(const OUTER_T<T> & state,double time_diff ) {\n\t\t\tassert_inputs(state,time_diff);\n\t\t\treturn state;\n\t\t}\n\t\tinline INNER_T<double> getSTD(double time_diff) {\n\t\t\tINNER_T<double> noise=INNER_T<double>::Ones()*30*time_diff;\n\t\t\treturn noise;\n\t\t}\n\t};\n}\n//zavi::estimator::state_boxes\n\n#endif /* ESTIMATORS_STATEBOXES_HOMOCOORDBOX_HPP_ */\n", "meta": {"hexsha": "1f687919f61ef6c17b85f7bbe10d1bce589d5470", "size": 2408, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "SixdaysCode/Estimators/StateBoxes/HomogeneousCoordinatesBox.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/StateBoxes/HomogeneousCoordinatesBox.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/StateBoxes/HomogeneousCoordinatesBox.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": 32.1066666667, "max_line_length": 147, "alphanum_fraction": 0.7159468439, "num_tokens": 726, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812554, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.462173791167246}}
{"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.\r\n// Modifications copyright (c) 2014, 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_ALGORITHMS_DETAIL_COURSE_HPP\r\n#define BOOST_GEOMETRY_ALGORITHMS_DETAIL_COURSE_HPP\r\n\r\n#include <boost/geometry/core/cs.hpp>\r\n#include <boost/geometry/core/access.hpp>\r\n#include <boost/geometry/core/radian_access.hpp>\r\n#include <boost/geometry/util/math.hpp>\r\n\r\nnamespace boost { namespace geometry\r\n{\r\n\r\n#ifndef DOXYGEN_NO_DETAIL\r\nnamespace detail\r\n{\r\n\r\n/// Calculate course (bearing) between two points.\r\ntemplate <typename ReturnType, typename Point1, typename Point2>\r\ninline ReturnType course(Point1 const& p1, Point2 const& p2)\r\n{\r\n    // http://williams.best.vwh.net/avform.htm#Crs\r\n    ReturnType dlon = get_as_radian<0>(p2) - get_as_radian<0>(p1);\r\n    ReturnType cos_p2lat = cos(get_as_radian<1>(p2));\r\n\r\n    // An optimization which should kick in often for Boxes\r\n    //if ( math::equals(dlon, ReturnType(0)) )\r\n    //if ( get<0>(p1) == get<0>(p2) )\r\n    //{\r\n    //    return - sin(get_as_radian<1>(p1)) * cos_p2lat);\r\n    //}\r\n\r\n    // \"An alternative formula, not requiring the pre-computation of d\"\r\n    // In the formula below dlon is used as \"d\"\r\n    return atan2(sin(dlon) * cos_p2lat,\r\n        cos(get_as_radian<1>(p1)) * sin(get_as_radian<1>(p2))\r\n        - sin(get_as_radian<1>(p1)) * cos_p2lat * cos(dlon));\r\n}\r\n\r\n} // namespace detail\r\n#endif // DOXYGEN_NO_DETAIL\r\n\r\n}} // namespace boost::geometry\r\n\r\n#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_COURSE_HPP\r\n", "meta": {"hexsha": "436c823c4508c0f2a24b02abf33ece24ab966527", "size": 1915, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactAndroid/build/third-party-ndk/boost/boost_1_57_0/boost/geometry/algorithms/detail/course.hpp", "max_stars_repo_name": "kimwoongkyu/react-native-0-36-1-woogie", "max_stars_repo_head_hexsha": "4fb2d44945a6305ae3ca87be3872f9432d16f1fb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 85.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T20:36:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T20:38:31.000Z", "max_issues_repo_path": "ReactAndroid/build/third-party-ndk/boost/boost_1_57_0/boost/geometry/algorithms/detail/course.hpp", "max_issues_repo_name": "kimwoongkyu/react-native-0-36-1-woogie", "max_issues_repo_head_hexsha": "4fb2d44945a6305ae3ca87be3872f9432d16f1fb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "ReactAndroid/build/third-party-ndk/boost/boost_1_57_0/boost/geometry/algorithms/detail/course.hpp", "max_forks_repo_name": "kimwoongkyu/react-native-0-36-1-woogie", "max_forks_repo_head_hexsha": "4fb2d44945a6305ae3ca87be3872f9432d16f1fb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2015-01-28T16:33:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-12T05:04:39.000Z", "avg_line_length": 33.5964912281, "max_line_length": 80, "alphanum_fraction": 0.7018276762, "num_tokens": 509, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812552, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.4621737911672459}}
{"text": "#include <boost/math/distributions/cauchy.hpp>\n", "meta": {"hexsha": "71d14a17c3ed61e6a55b9c9191d1c24313e2c8ac", "size": 47, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_distributions_cauchy.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_distributions_cauchy.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_distributions_cauchy.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 23.5, "max_line_length": 46, "alphanum_fraction": 0.8085106383, "num_tokens": 11, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478255, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4621737858128587}}
{"text": "// Copyright (C) 2021 Igor A. Baratta\n//\n// This file is part of DOLFINx_CUAS\n//\n// SPDX-License-Identifier:    MIT\n\n#include \"volume.h\"\n#include <basix/finite-element.h>\n#include <basix/quadrature.h>\n#include <boost/program_options.hpp>\n#include <dolfinx.h>\n#include <dolfinx/fem/petsc.h>\n#include <dolfinx_cuas/QuadratureRule.hpp>\n#include <dolfinx_cuas/kernels.hpp>\n#include <dolfinx_cuas/matrix_assembly.hpp>\n#include <dolfinx_cuas/utils.hpp>\n#include <xtensor/xio.hpp>\n\nusing namespace dolfinx;\nnamespace po = boost::program_options;\n\nint main(int argc, char* argv[])\n{\n  common::subsystem::init_logging(argc, argv);\n  common::subsystem::init_petsc(argc, argv);\n\n  po::options_description desc(\"Allowed options\");\n  desc.add_options()(\"help,h\", \"print usage message\")(\n      \"kernel\", po::value<std::string>()->default_value(\"mass\"),\n      \"kernel (mass or stiffness)\")(\"degree\", po::value<int>()->default_value(1),\n                                    \"Degree of function space (1-5)\");\n  po::variables_map vm;\n  po::store(po::command_line_parser(argc, argv).options(desc).run(), vm);\n  po::notify(vm);\n\n  if (vm.count(\"help\"))\n  {\n    std::cout << desc << \"\\n\";\n    return 0;\n  }\n  const std::string problem_type = vm[\"kernel\"].as<std::string>();\n  const int degree = vm[\"degree\"].as<int>();\n\n  MPI_Comm mpi_comm{MPI_COMM_WORLD};\n\n  std::shared_ptr<mesh::Mesh> mesh = std::make_shared<mesh::Mesh>(\n      mesh::create_box(mpi_comm, {{{0.0, 0.0, 0.0}, {1.0, 1.0, 1.0}}}, {10, 10, 10},\n                       mesh::CellType::tetrahedron, mesh::GhostMode::none));\n\n  mesh->topology().create_entity_permutations();\n\n  auto kappa = std::make_shared<fem::Constant<PetscScalar>>(1.0);\n\n  // Define variational forms\n  ufcx_form form;\n  std::shared_ptr<fem::FunctionSpace> V;\n  dolfinx_cuas::Kernel kernel_type;\n\n  int q_degree = 0;\n  if (problem_type == \"mass\")\n  {\n    q_degree = 2 * degree;\n    kernel_type = dolfinx_cuas::Kernel::Mass;\n    std::vector spaces_mass = {functionspace_form_volume_a_mass1, functionspace_form_volume_a_mass2,\n                               functionspace_form_volume_a_mass3, functionspace_form_volume_a_mass4,\n                               functionspace_form_volume_a_mass5};\n    std::vector forms_mass = {form_volume_a_mass1, form_volume_a_mass2, form_volume_a_mass3,\n                              form_volume_a_mass4, form_volume_a_mass5};\n    V = std::make_shared<fem::FunctionSpace>(\n        fem::create_functionspace(spaces_mass[degree - 1], \"v_0\", mesh));\n    form = *forms_mass[degree - 1];\n  }\n  else if (problem_type == \"stiffness\")\n  {\n    q_degree = 2 * (degree - 1);\n    kernel_type = dolfinx_cuas::Kernel::Stiffness;\n    std::vector spaces_stiffness\n        = {functionspace_form_volume_a_stiffness1, functionspace_form_volume_a_stiffness2,\n           functionspace_form_volume_a_stiffness3, functionspace_form_volume_a_stiffness4,\n           functionspace_form_volume_a_stiffness5};\n    std::vector forms_stiffness\n        = {form_volume_a_stiffness1, form_volume_a_stiffness2, form_volume_a_stiffness3,\n           form_volume_a_stiffness4, form_volume_a_stiffness5};\n    V = std::make_shared<fem::FunctionSpace>(\n        fem::create_functionspace(spaces_stiffness[degree - 1], \"v_0\", mesh));\n    form = *forms_stiffness[degree - 1];\n  }\n  else\n    throw std::runtime_error(\"Unsupported kernel\");\n\n  auto a = std::make_shared<fem::Form<PetscScalar>>(\n      fem::create_form<PetscScalar>(form, {V, V}, {}, {{\"kappa\", kappa}}, {}));\n\n  // Matrix to be used with custom assembler\n  la::petsc::Matrix A = la::petsc::Matrix(fem::petsc::create_matrix(*a), false);\n  MatZeroEntries(A.mat());\n\n  // Matrix to be used with custom DOLFINx/FFCx\n  la::petsc::Matrix B = la::petsc::Matrix(fem::petsc::create_matrix(*a), false);\n  MatZeroEntries(B.mat());\n\n  // Generate Kernel\n  dolfinx_cuas::QuadratureRule q_rule(mesh->topology().cell_type(), q_degree,\n                                      mesh->topology().dim(), basix::quadrature::type::Default);\n  auto kernel = dolfinx_cuas::generate_kernel<PetscScalar>(kernel_type, degree,\n                                                           V->dofmap()->index_map_bs(), q_rule);\n\n  // Define active cells\n  const std::int32_t tdim = mesh->topology().dim();\n  const std::int32_t ncells = mesh->topology().index_map(tdim)->size_local();\n  xt::xarray<std::int32_t> active_cells = xt::arange<std::int32_t>(0, ncells);\n  const std::vector<PetscScalar> coeffs(0);\n  const std::vector<PetscScalar> consts(0);\n\n  common::Timer t0(\"~Assemble Matrix Custom\");\n  dolfinx_cuas::assemble_matrix<PetscScalar>(la::petsc::Matrix::set_block_fn(A.mat(), ADD_VALUES),\n                                             V, {}, active_cells, kernel, coeffs, 0, consts,\n                                             dolfinx::fem::IntegralType::cell);\n  MatAssemblyBegin(A.mat(), MAT_FINAL_ASSEMBLY);\n  MatAssemblyEnd(A.mat(), MAT_FINAL_ASSEMBLY);\n  t0.stop();\n\n  {\n    // Prepare constants and coefficients\n    const auto constants = pack_constants(*a);\n    const auto coeffs = pack_coefficients(*a);\n    common::Timer t1(\"~Assemble Matrix DOLINFx/FFCx\");\n    dolfinx::fem::assemble_matrix(la::petsc::Matrix::set_block_fn(B.mat(), ADD_VALUES), *a,\n                                  tcb::make_span(constants),\n                                  dolfinx::fem::make_coefficients_span(coeffs), {});\n    MatAssemblyBegin(B.mat(), MAT_FINAL_ASSEMBLY);\n    MatAssemblyEnd(B.mat(), MAT_FINAL_ASSEMBLY);\n    t1.stop();\n  }\n\n  dolfinx::list_timings(mpi_comm, {dolfinx::TimingType::wall});\n\n  if (!dolfinx_cuas::allclose(A.mat(), B.mat()))\n    throw std::runtime_error(\"Matrices are not the same\");\n\n  return 0;\n}\n", "meta": {"hexsha": "ac2bbd273f1475e938caef632a7a705e8190b259", "size": 5654, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/demo/volume/main.cpp", "max_stars_repo_name": "Wells-Group/asimov-custom-assemblers", "max_stars_repo_head_hexsha": "79122743401b9475d07e8f1f0e7684b5deda80f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-10-05T11:44:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-05T11:44:21.000Z", "max_issues_repo_path": "cpp/demo/volume/main.cpp", "max_issues_repo_name": "Wells-Group/asimov-custom-assemblers", "max_issues_repo_head_hexsha": "79122743401b9475d07e8f1f0e7684b5deda80f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17.0, "max_issues_repo_issues_event_min_datetime": "2021-07-19T10:45:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-15T14:15:39.000Z", "max_forks_repo_path": "cpp/demo/volume/main.cpp", "max_forks_repo_name": "Wells-Group/asimov-custom-assemblers", "max_forks_repo_head_hexsha": "79122743401b9475d07e8f1f0e7684b5deda80f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-07-21T21:12:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-21T21:12:49.000Z", "avg_line_length": 39.5384615385, "max_line_length": 100, "alphanum_fraction": 0.656703219, "num_tokens": 1559, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478254, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4621737858128586}}
{"text": "#include \"point_source_panner.hpp\"\n\n#include <Eigen/Dense>\n#include <boost/algorithm/clamp.hpp>\n#include <boost/make_unique.hpp>\n#include \"convex_hull.hpp\"\n#include \"ear/bs2051.hpp\"\n#include \"ear/helpers/assert.hpp\"\n#include \"facets.hpp\"\n#include \"geom.hpp\"\n#include \"helpers/eigen_helpers.hpp\"\n\nnamespace ear {\n\n  RegionHandler::RegionHandler(Eigen::VectorXi outputChannels,\n                               Eigen::MatrixXd positions)\n      : _outputChannels(outputChannels), _positions(positions){};\n\n  boost::optional<Eigen::VectorXd> RegionHandler::handleRemap(\n      Eigen::Vector3d position, int numberOfChannels) const {\n    boost::optional<Eigen::VectorXd> pv = handle(position);\n\n    if (pv) {\n      Eigen::VectorXd _pv = pv.get();\n      Eigen::VectorXd out = Eigen::VectorXd::Zero(numberOfChannels);\n      for (int i = 0; i < _pv.size(); ++i) {\n        out(_outputChannels(i)) = _pv(i);\n      }\n      return out;\n    }\n    return boost::none;\n  };\n\n  Eigen::VectorXi RegionHandler::outputChannels() { return _outputChannels; }\n\n  Triplet::Triplet(Eigen::Vector3i outputChannels, Eigen::Matrix3d positions)\n      : RegionHandler(outputChannels, positions) {\n    _basis = _positions.inverse();\n  };\n\n  boost::optional<Eigen::VectorXd> Triplet::handle(\n      Eigen::Vector3d position) const {\n    Eigen::VectorXd pv = position.transpose() * _basis;\n    double epsilon = -1e-11;\n    if (pv(0) >= epsilon && pv(1) >= epsilon && pv(2) >= epsilon) {\n      pv /= pv.norm();\n      return pv.cwiseMax(0.0).cwiseMin(1.0).eval();\n    }\n    return boost::none;\n  }\n\n  VirtualNgon::VirtualNgon(Eigen::VectorXi outputChannels,\n                           Eigen::MatrixXd positions,\n                           Eigen::Vector3d centrePosition,\n                           Eigen::VectorXd centreDownmix)\n      : RegionHandler(outputChannels, positions),\n        _centrePosition(centrePosition),\n        _centreDownmix(centreDownmix) {\n    int n = static_cast<int>(_outputChannels.size());\n\n    ear_assert(\n        n == _positions.rows(),\n        \"number of downmix coeffs does not match number of output channels\");\n\n    ear_assert(\n        n == _centreDownmix.size(),\n        \"number of downmix coeffs does not match number of output channels\");\n\n    Eigen::VectorXi order = ngonVertexOrder(positions);\n\n    for (int i = 0; i < n; ++i) {\n      int j = (i + 1) % n;\n      Eigen::Matrix3d tripletPositions;\n      Eigen::RowVector3d position1 = _positions.row(order(i));\n      Eigen::RowVector3d position2 = _positions.row(order(j));\n      tripletPositions << position1, position2, _centrePosition.transpose();\n      Eigen::Vector3i tripletChannels;\n      tripletChannels << order(i), order(j), n;\n      _regions.push_back(\n          boost::make_unique<Triplet>(tripletChannels, tripletPositions));\n    }\n  }\n\n  boost::optional<Eigen::VectorXd> VirtualNgon::handle(\n      Eigen::Vector3d position) const {\n    for (const auto& region : _regions) {\n      boost::optional<Eigen::VectorXd> pv = region->handleRemap(\n          position, static_cast<int>(_centreDownmix.size() + 1));\n      if (pv) {\n        // downmix the last channel containing the virtual centre\n        // speaker into the real speakers, and renormalise\n        Eigen::VectorXd _pv = pv.get();\n        _pv = _pv.head(_pv.size() - 1) + _centreDownmix * _pv.tail(1);\n        _pv /= _pv.norm();\n        return _pv;\n      }\n    }\n    return boost::none;\n  }\n\n  QuadRegion::QuadRegion(Eigen::VectorXi outputChannels,\n                         Eigen::MatrixXd positions)\n      : RegionHandler(outputChannels, positions) {\n    _order = ngonVertexOrder(positions);\n    Eigen::MatrixXd reorderedPositions = positions(_order, Eigen::all);\n    Eigen::MatrixXd reorderedAndShiftedPositions =\n        reorderedPositions(Eigen::Vector4i{1, 2, 3, 0}, Eigen::all);\n    _polyBasisX = _calcPolyBasis(reorderedPositions);\n    _polyBasisY = _calcPolyBasis(reorderedAndShiftedPositions);\n  };\n\n  boost::optional<Eigen::VectorXd> QuadRegion::handle(\n      Eigen::Vector3d position) const {\n    boost::optional<double> x = _pan(position, _polyBasisX);\n    boost::optional<double> y = _pan(position, _polyBasisY);\n\n    if (x == boost::none || y == boost::none) {\n      return boost::none;\n    }\n\n    Eigen::VectorXd pvs = Eigen::Vector4d::Zero();\n    pvs(_order) << (1 - x.get()) * (1 - y.get()), x.get() * (1 - y.get()),\n        x.get() * y.get(), (1 - x.get()) * y.get();\n    if ((pvs.transpose() * _positions) * position <= 0) {\n      return boost::none;\n    }\n    pvs /= pvs.norm();\n    return pvs;\n  }\n\n  Eigen::Matrix3d QuadRegion::_calcPolyBasis(Eigen::MatrixXd positions) {\n    Eigen::Vector3d a = positions.row(0);\n    Eigen::Vector3d b = positions.row(1);\n    Eigen::Vector3d c = positions.row(2);\n    Eigen::Vector3d d = positions.row(3);\n\n    Eigen::Matrix3d polyBasis;\n    polyBasis <<  //\n        (b - a).cross(c - d),  //\n        a.cross(c - d) + (b - a).cross(d),  //\n        a.cross(d);\n\n    return polyBasis.transpose();\n  }\n\n  /** @brief Calculate the real roots of a quadratic\n   *\n   * @param a Quadratic term.\n   * @param b Linear term.\n   * @param c Constant term.\n   *\n   * @note The equation solved is given by\n   *\n   *  a x^2 + bx + c = 0\n   *\n   * @returns The real roots of the quadratic.\n   */\n  std::vector<double> real_quadratic_roots(double a, double b, double c) {\n    double eps = 1e-10;\n\n    if (std::abs(c) < eps) return {0.0};\n    if (std::abs(a) < eps) return {-c / b};\n\n    double det = b * b - 4.0 * a * c;\n    if (det > eps)\n      return {(-b + sqrt(det)) / (2.0 * a), (-b - sqrt(det)) / (2.0 * a)};\n    else if (det > -eps)\n      return {-b / (2.0 * a)};\n    else\n      return {};\n  }\n\n  boost::optional<double> QuadRegion::_pan(Eigen::Vector3d position,\n                                           Eigen::Matrix3d polyBasis) const {\n    double epsilon = 1e-10;\n\n    Eigen::Vector3d poly = polyBasis * position;\n\n    for (double root : real_quadratic_roots(poly(0), poly(1), poly(2))) {\n      if (-epsilon < root && root < 1.0 + epsilon) {\n        return boost::algorithm::clamp(root, 0.0, 1.0);\n      }\n    }\n    return boost::none;\n  }\n\n  PolarPointSourcePanner::PolarPointSourcePanner(\n      std::vector<std::unique_ptr<RegionHandler>> regions,\n      boost::optional<int> numberOfChannels)\n      : _regions(std::move(regions)) {\n    if (!numberOfChannels) {\n      _numberOfOutputChannels = _numberOfRequiredChannels();\n    } else {\n      _numberOfOutputChannels = numberOfChannels.get();\n      ear_assert(_numberOfOutputChannels >= _numberOfRequiredChannels(),\n                 \"not enough output channels in PolarPointSourcePanner\");\n    }\n  };\n\n  boost::optional<Eigen::VectorXd> PolarPointSourcePanner::handle(\n      Eigen::Vector3d position) {\n    boost::optional<Eigen::VectorXd> pv;\n    for (const auto& region : _regions) {\n      pv = region->handleRemap(position, _numberOfOutputChannels);\n      if (pv) {\n        return pv;\n      }\n    }\n    return boost::none;\n  }\n\n  int PolarPointSourcePanner::numberOfOutputChannels() const {\n    return _numberOfOutputChannels;\n  }\n\n  int PolarPointSourcePanner::_numberOfRequiredChannels() {\n    int ret = 0;\n    for (const auto& region : _regions) {\n      auto maxRegion = region->outputChannels().maxCoeff();\n      if (ret < maxRegion) {\n        ret = maxRegion;\n      }\n    }\n    return ret + 1;\n  }\n\n  PointSourcePannerDownmix::PointSourcePannerDownmix(\n      std::shared_ptr<PointSourcePanner> psp, Eigen::MatrixXd downmix)\n      : _psp(psp), _downmix(downmix){};\n\n  boost::optional<Eigen::VectorXd> PointSourcePannerDownmix::handle(\n      Eigen::Vector3d position) {\n    boost::optional<Eigen::VectorXd> pv = _psp->handle(position);\n    if (pv) {\n      Eigen::VectorXd _pv = pv.get();\n      _pv = _downmix.transpose() * _pv;\n      _pv /= _pv.norm();\n      return _pv;\n    }\n    return boost::none;\n  }\n\n  int PointSourcePannerDownmix::numberOfOutputChannels() const {\n    return static_cast<int>(_downmix.cols());\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    std::vector<Channel> extraChannels;\n    Eigen::MatrixXd downmix = Eigen::MatrixXd::Identity(\n        layout.channels().size(), layout.channels().size());\n\n    Layout midLayerLayout;\n    std::copy_if(layout.channels().begin(), layout.channels().end(),\n                 std::back_inserter(midLayerLayout.channels()), [](Channel c) {\n                   return -10 <= c.polarPositionNominal().elevation &&\n                          c.polarPositionNominal().elevation <= 10;\n                 });\n\n    auto layers = {std::make_tuple(-30.0, -70.0, -10.0),\n                   std::make_tuple(30.0, 10.0, 70.0)};\n\n    double layerNominalElevation, layerLowerBound, layerUpperBound;\n    for (const auto& layer : layers) {\n      std::tie(layerNominalElevation, layerLowerBound, layerUpperBound) = layer;\n\n      Layout currentLayerLayout;\n      std::copy_if(\n          layout.channels().begin(), layout.channels().end(),\n          std::back_inserter(currentLayerLayout.channels()), [&](Channel c) {\n            return layerLowerBound <= c.polarPositionNominal().elevation &&\n                   c.polarPositionNominal().elevation <= layerUpperBound;\n          });\n\n      // for each loudspeaker in the mid layer that has an azimuth greater\n      // than az_limit, add a virtual speaker directly above/below it at the\n      // elevation of the current layer, which is downmixed directly to the\n      // mid layer loudspeaker. az_limit is set to the range of azimuths in\n      // the current layer, with some space added to prevent fast vertical\n      // source movements when sources move horizontally. If there are no\n      // channels on this layer then a copy of all mid layer speakers is\n      // made.\n      double azimuthLimit = 0.0;\n      double layerRealElevation = 0.0;\n      if (currentLayerLayout.channels().size() != 0) {\n        double azimuthRange = std::numeric_limits<double>::min();\n        for (const auto& channel : currentLayerLayout.channels()) {\n          if (azimuthRange < std::abs(channel.polarPositionNominal().azimuth)) {\n            azimuthRange = std::abs(channel.polarPositionNominal().azimuth);\n          }\n        }\n        azimuthLimit = azimuthRange + 40.0;\n        layerRealElevation =\n            std::accumulate(currentLayerLayout.channels().begin(),\n                            currentLayerLayout.channels().end(), 0.0,\n                            [&](double sum, const Channel& c) -> double {\n                              return sum + c.polarPosition().elevation;\n                            }) /\n            static_cast<double>(currentLayerLayout.channels().size());\n      } else {\n        layerRealElevation = layerNominalElevation;\n      }\n\n      double epsilon = 1e-5;\n      for (const auto& midChannel : midLayerLayout.channels()) {\n        if (std::abs(midChannel.polarPosition().azimuth) >=\n            azimuthLimit - epsilon) {\n          extraChannels.push_back(Channel(\n              \"extra\",\n              PolarPosition(midChannel.polarPosition().azimuth,\n                            layerRealElevation, 1.0),\n              PolarPosition(midChannel.polarPositionNominal().azimuth,\n                            layerNominalElevation, 1.0)\n\n                  ));\n          Eigen::VectorXd downmixRow =\n              Eigen::VectorXd::Zero(layout.channels().size());\n          auto names = layout.channelNames();\n          int midChannelIndex = static_cast<int>(std::distance(\n              names.begin(),\n              std::find(names.begin(), names.end(), midChannel.name())));\n          downmixRow(midChannelIndex) = 1.0;\n          downmix.conservativeResize(downmix.rows() + 1, Eigen::NoChange);\n          downmix.row(downmix.rows() - 1) = downmixRow;\n        }\n      }\n    }\n    return std::make_pair(extraChannels, downmix);\n  }\n\n  /** @brief Find the adjacent vertices in a hull to the given vertex.\n   *\n   * @param  facets (list of sets of ints): Convex hull facets, each item\n   * represents a facet, with the contents of the set being its vertex indices.\n   * @param  vert (int): Vertex index to find vertices adjacent to.\n   *\n   * @returns Vertices adjacent to `vert`.\n   */\n  Facet _adjacent_verts(std::vector<Facet> facets, int vert) {\n    std::set<int> ret;\n    for (const auto& facetVerts : facets) {\n      if (std::find(facetVerts.begin(), facetVerts.end(), vert) !=\n          facetVerts.end()) {\n        ret.insert(facetVerts.begin(), facetVerts.end());\n      }\n    }\n    ret.erase(vert);\n    return ret;\n  }\n\n  StereoPannerDownmix::StereoPannerDownmix(Eigen::VectorXi outputChannels,\n                                           Eigen::MatrixXd positions)\n      : RegionHandler(outputChannels, positions) {\n    auto layout = getLayout(\"0+5+0\").withoutLfe();\n    _psp = configureFullPolarPanner(layout);\n  }\n\n  boost::optional<Eigen::VectorXd> StereoPannerDownmix::handle(\n      Eigen::Vector3d position) const {\n    Eigen::MatrixXd downmix(2, 5);\n    downmix << 1.0, 0.0, std::sqrt(3.0) / 3.0, std::sqrt(0.5), 0.0,  //\n        0.0, 1.0, std::sqrt(3.0) / 3.0, 0.0, std::sqrt(0.5);\n\n    // pan with 0+5+0, downmix and power normalise\n    boost::optional<Eigen::VectorXd> pv = _psp->handle(position);\n\n    if (pv) {\n      Eigen::VectorXd _pv = pv.get();\n      Eigen::VectorXd pvDownmix = downmix * _pv;\n      pvDownmix /= pvDownmix.norm();\n\n      // vary the output level by the balance between the front and rear\n      // loudspeakers; 0dB at the front to -3dB at the back\n      double front = _pv.head(3).maxCoeff();\n      double back = _pv.tail(2).maxCoeff();\n\n      pvDownmix = pvDownmix * std::pow(0.5, (0.5 * back / (front + back)));\n      return pvDownmix;\n    }\n    return boost::none;\n  }\n\n  boost::optional<Eigen::VectorXd> AllocentricPanner::handle(\n      Eigen::Vector3d position) {\n    return boost::none;\n  }\n\n  int AllocentricPanner::numberOfOutputChannels() const { return 0; }\n\n  std::shared_ptr<PointSourcePanner> configureStereoPolarPanner(\n      const Layout& layout) {\n    auto leftChannel = layout.channelWithName(\"M+030\");\n    auto rightChannel = layout.channelWithName(\"M-030\");\n    auto channelNames = layout.channelNames();\n    auto leftChannelIndex =\n        distance(channelNames.begin(),\n                 find(channelNames.begin(), channelNames.end(), \"M+030\"));\n    auto rightChannelIndex =\n        distance(channelNames.begin(),\n                 find(channelNames.begin(), channelNames.end(), \"M-030\"));\n\n    Eigen::MatrixXd positions(2, 3);\n    positions << toCartesianVector3d(leftChannel.polarPosition()).transpose(),\n        toCartesianVector3d(rightChannel.polarPosition()).transpose();\n    Eigen::Vector2i outputChannels{leftChannelIndex, rightChannelIndex};\n\n    auto panner =\n        boost::make_unique<StereoPannerDownmix>(outputChannels, positions);\n\n    std::vector<std::unique_ptr<RegionHandler>> regions;\n    regions.push_back(std::move(panner));\n    return std::make_shared<PolarPointSourcePanner>(std::move(regions));\n  }\n\n  std::tuple<std::vector<Eigen::Vector3d>, std::vector<Eigen::Vector3d>,\n             std::set<int>, Eigen::MatrixXd>\n  getAugmentedLayout(const Layout& layout) {\n    // add some extra height speakers that are treated as real speakers until\n    // the downmix in PointSourcePannerDownmix\n    std::vector<Channel> allChannels(layout.channels());\n\n    std::vector<Channel> extraChannels;\n    Eigen::MatrixXd downmix;\n    std::tie(extraChannels, downmix) = extraPosVerticalNominal(layout);\n    for (const auto& extraChannel : extraChannels) {\n      allChannels.push_back(extraChannel);\n    }\n\n    // add some virtual speakers above and below that will be used as the\n    // centre speaker in a virtual ngon. No upper speaker is added for\n    // layouts with UH+180 as this speaker may actually be directly\n    // overhead, which may cause a step in the gains wrt the source\n    // position.\n    auto channelNames = layout.channelNames();\n\n    std::vector<Eigen::Vector3d> virtualPositions;\n    virtualPositions.push_back(Eigen::Vector3d{0.0, 0.0, -1.0});\n    if (std::find(channelNames.begin(), channelNames.end(), \"T+000\") ==\n            channelNames.end() &&\n        std::find(channelNames.begin(), channelNames.end(), \"UH+180\") ==\n            channelNames.end()) {\n      virtualPositions.push_back(Eigen::Vector3d{0.0, 0.0, 1.0});\n    }\n\n    std::vector<Eigen::Vector3d> positionsReal;\n    std::vector<Eigen::Vector3d> positionsNominal;\n    std::set<int> virtualVerts;\n\n    for (const Channel& channel : allChannels) {\n      positionsReal.push_back(toNormalisedVector3d(channel.polarPosition()));\n      positionsNominal.push_back(\n          toNormalisedVector3d(channel.polarPositionNominal()));\n    }\n    for (const Eigen::Vector3d& pos : virtualPositions) {\n      virtualVerts.insert(static_cast<int>(positionsReal.size()));\n      positionsReal.push_back(pos);\n      positionsNominal.push_back(pos);\n    }\n\n    return {positionsReal, positionsNominal, virtualVerts, downmix};\n  }\n\n  std::shared_ptr<PointSourcePanner> configureFullPolarPanner(\n      const Layout& layout) {\n    std::vector<Eigen::Vector3d> positionsReal;\n    std::vector<Eigen::Vector3d> positionsNominal;\n    std::set<int> virtualVerts;\n    Eigen::MatrixXd downmix;\n    std::tie(positionsReal, positionsNominal, virtualVerts, downmix) =\n        getAugmentedLayout(layout);\n\n    // Facets of the convex hull; each set represents a facet and contains the\n    // indices of its corners in positions.\n    auto facets_it = FACETS.find(layout.name());\n    std::vector<Facet> facets = facets_it != FACETS.end()\n                                    ? facets_it->second\n                                    : convex_hull(positionsNominal);\n\n    // Turn the facets into regions for the point source panner.\n    std::vector<std::unique_ptr<RegionHandler>> regions;\n\n    // Facets adjacent to one of the virtual speakers are turned into virtual\n    // ngons, with an equal power downmix from the virtual speaker to the real\n    // speakers.\n    for (int virtualVert : virtualVerts) {\n      Facet realVerts = _adjacent_verts(facets, virtualVert);\n\n      ear_assert(!doIntersect(realVerts.begin(), realVerts.end(),\n                              virtualVerts.begin(), virtualVerts.end()),\n                 \"invalid triangulation\");\n\n      std::vector<int> realVertsVec(realVerts.begin(), realVerts.end());\n      Eigen::Map<Eigen::VectorXi> outputChannels(realVertsVec.data(),\n                                                 realVertsVec.size());\n      Eigen::MatrixXd positions(outputChannels.size(), 3);\n      int rowIndex = 0;\n      for (int vert : realVerts) {\n        positions.row(rowIndex) = positionsReal[vert];\n        ++rowIndex;\n      }\n      Eigen::Vector3d centrePosition = positionsReal[virtualVert];\n      Eigen::VectorXd centreDownmix(outputChannels.size());\n      centreDownmix.fill(1.0 /\n                         std::sqrt(static_cast<double>(outputChannels.size())));\n\n      regions.push_back(boost::make_unique<VirtualNgon>(\n          outputChannels, positions, centrePosition, centreDownmix));\n    }\n    // Facets not adjacent to virtual speakers are turned into triplets or\n    // quads. In the supported layouts there are never facets with more\n    // vertices.\n    for (const auto& facetVerts : facets) {\n      if (doIntersect(facetVerts.begin(), facetVerts.end(),\n                      virtualVerts.begin(), virtualVerts.end())) {\n        continue;\n      }\n\n      if (facetVerts.size() == 3) {\n        std::vector<int> facetVertsVec(facetVerts.begin(), facetVerts.end());\n        Eigen::Vector3i outputChannels(facetVertsVec.data());\n        Eigen::MatrixXd positions(outputChannels.size(), 3);\n        int rowIndex = 0;\n        for (int vert : facetVerts) {\n          positions.row(rowIndex) = positionsReal[vert];\n          ++rowIndex;\n        }\n        regions.push_back(\n            boost::make_unique<Triplet>(outputChannels, positions));\n      } else if (facetVerts.size() == 4) {\n        std::vector<int> facetVertsVec(facetVerts.begin(), facetVerts.end());\n        Eigen::Vector4i outputChannels(facetVertsVec.data());\n        Eigen::MatrixXd positions(outputChannels.size(), 3);\n        int rowIndex = 0;\n        for (int vert : facetVerts) {\n          positions.row(rowIndex) = positionsReal[vert];\n          ++rowIndex;\n        }\n        regions.push_back(\n            boost::make_unique<QuadRegion>(outputChannels, positions));\n      } else {\n        throw internal_error(\n            \"facets with more than 4 vertices are not supported\");\n      }\n    }\n    return std::make_shared<PointSourcePannerDownmix>(\n        std::make_shared<PolarPointSourcePanner>(std::move(regions)), downmix);\n  }\n\n  // Check that screen loudspeakers are within allowed ranges.\n  void checkScreenSpeakers(const Layout& layout) {\n    for (auto& channel : layout.channels()) {\n      if (channel.name() == \"M+SC\" || channel.name() == \"M-SC\") {\n        double abs_az = std::abs(channel.polarPosition().azimuth);\n        if (!((5.0 <= abs_az && abs_az < 25.0) ||\n              (35.0 <= abs_az && abs_az < 60.0))) {\n          throw invalid_argument(\n              \"M+SC or M-SC has azimuth not in the allowed ranges of 5 to 25 \"\n              \"and 35 to 60 degrees\");\n        }\n\n        if (25.0 < abs_az) {\n          throw not_implemented(\n              \"M+SC and M-SC with azimuths wider than 25 degrees are not \"\n              \"currently supported\");\n        }\n      }\n    }\n  }\n\n  std::shared_ptr<PointSourcePanner> configureAllocentricPanner(\n      const Layout& layout) {\n    checkScreenSpeakers(layout);\n    return std::make_shared<AllocentricPanner>();\n  }\n\n  std::shared_ptr<PointSourcePanner> configurePolarPanner(\n      const Layout& layout) {\n    auto isLfe = layout.isLfe();\n    if (find(isLfe.begin(), isLfe.end(), true) != isLfe.end()) {\n      throw internal_error(\"lfe channel passed to point source panner\");\n    }\n\n    checkScreenSpeakers(layout);\n\n    if (layout.name() == std::string(\"0+2+0\")) {\n      return configureStereoPolarPanner(layout);\n    } else {\n      return configureFullPolarPanner(layout);\n    }\n  }\n}  // namespace ear\n", "meta": {"hexsha": "a398c92861e6dff3cbee7062b34b1760347024bc", "size": 22373, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/common/point_source_panner.cpp", "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.cpp", "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.cpp", "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": 37.2883333333, "max_line_length": 80, "alphanum_fraction": 0.6282572744, "num_tokens": 5581, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.4620538712352839}}
{"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_DIV_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_DIV_HPP_INCLUDED\n\n#include <boost/simd/function/divides.hpp>\n#include <boost/simd/function/iceil.hpp>\n#include <boost/simd/function/ifloor.hpp>\n#include <boost/simd/function/ifix.hpp>\n#include <boost/simd/function/iround.hpp>\n#include <boost/simd/function/inearbyint.hpp>\n#include <boost/simd/function/ceil.hpp>\n#include <boost/simd/function/fix.hpp>\n#include <boost/simd/function/floor.hpp>\n#include <boost/simd/function/round.hpp>\n#include <boost/simd/function/nearbyint.hpp>\n#include <boost/simd/function/toint.hpp>\n#include <boost/simd/detail/dispatch/function/overload.hpp>\n#include <boost/simd/detail/dispatch/meta/as_integer.hpp>\n#include <boost/simd/detail/dispatch/hierarchy.hpp>\n#include <boost/config.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n#ifdef BOOST_MSVC\n  #pragma warning(push)\n  #pragma warning(disable: 4723) // potential divide by 0\n#endif\n\n  namespace bd = boost::dispatch;\n  namespace bs = boost::simd;\n  BOOST_DISPATCH_OVERLOAD_IF ( div_\n                          , (typename T, typename X)\n                          , (detail::is_native<X>)\n                          , bd::cpu_\n                          , bs::tag::ifix_\n                          , bs::pack_<bd::floating_<T>, X>\n                          , bs::pack_<bd::floating_<T>, X>\n                          )\n  {\n    BOOST_FORCEINLINE bd::as_integer_t<T> operator()( bd::functor<bs::tag::ifix_> const&\n                                                    , T const& a, T const& b ) const BOOST_NOEXCEPT\n    {\n      return saturated_(toint)(a/b);\n    }\n  };\n  BOOST_DISPATCH_OVERLOAD_IF ( div_\n                          , (typename T, typename X)\n                          , (detail::is_native<X>)\n                          , bd::cpu_\n                          , bs::tag::iceil_\n                          , bs::pack_<bd::floating_<T>, X>\n                          , bs::pack_<bd::floating_<T>, X>\n                          )\n  {\n    BOOST_FORCEINLINE bd::as_integer_t<T> operator()( bd::functor<bs::tag::iceil_> const&\n                                                    , T const& a, T const& b ) const BOOST_NOEXCEPT\n    {\n      return iceil(a/b);\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD_IF ( div_\n                          , (typename T, typename X)\n                          , (detail::is_native<X>)\n                          , bd::cpu_\n                          , bs::tag::ifloor_\n                          , bs::pack_<bd::floating_<T>, X>\n                          , bs::pack_<bd::floating_<T>, X>\n                          )\n  {\n    BOOST_FORCEINLINE bd::as_integer_t<T> operator()( bd::functor<bs::tag::ifloor_> const&\n                                                    ,T const& a, T const& b) const BOOST_NOEXCEPT\n    {\n      return ifloor(a/b);\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD_IF ( div_\n                          , (typename T, typename X)\n                          , (detail::is_native<X>)\n                          , bd::cpu_\n                          , bs::tag::iround_\n                          , bs::pack_<bd::floating_<T>, X>\n                          , bs::pack_<bd::floating_<T>, X>\n                          )\n  {\n    BOOST_FORCEINLINE  bd::as_integer_t<T>  operator()( bd::functor<bs::tag::iround_> const&\n                                                      ,T const& a, T const& b) const BOOST_NOEXCEPT\n    {\n      return iround(a/b);\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD_IF ( div_\n                          , (typename T, typename X)\n                          , (detail::is_native<X>)\n                          , bd::cpu_\n                          , bs::tag::inearbyint_\n                          , bs::pack_<bd::floating_<T>, X>\n                          , bs::pack_<bd::floating_<T>, X>\n                          )\n  {\n    BOOST_FORCEINLINE bd::as_integer_t<T> operator()( bd::functor<bs::tag::inearbyint_> const&\n                                                    ,T const& a, T const& b) const BOOST_NOEXCEPT\n    {\n      return inearbyint(a/b);\n    }\n  };\n\n#ifdef BOOST_MSVC\n#pragma warning(pop)\n#endif\n\n  BOOST_DISPATCH_OVERLOAD_IF ( div_\n                          , (typename T, typename X)\n                          , (detail::is_native<X>)\n                          , bd::cpu_\n                          , bs::tag::ifix_\n                          , bs::pack_<bd::integer_<T>, X>\n                          , bs::pack_<bd::integer_<T>, X>\n                          )\n  {\n    BOOST_FORCEINLINE T operator()( bd::functor<bs::tag::ifix_> const&\n                                                    , T const& a, T const& b ) const BOOST_NOEXCEPT\n    {\n      return  div(fix, a, b);\n    }\n  };\n  BOOST_DISPATCH_OVERLOAD_IF ( div_\n                          , (typename T, typename X)\n                          , (detail::is_native<X>)\n                          , bd::cpu_\n                          , bs::tag::iceil_\n                          , bs::pack_<bd::integer_<T>, X>\n                          , bs::pack_<bd::integer_<T>, X>\n                          )\n  {\n    BOOST_FORCEINLINE T operator()( bd::functor<bs::tag::iceil_> const&\n                                                    , T const& a, T const& b ) const BOOST_NOEXCEPT\n    {\n      return div(ceil, a, b);\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD_IF ( div_\n                          , (typename T, typename X)\n                          , (detail::is_native<X>)\n                          , bd::cpu_\n                          , bs::tag::ifloor_\n                          , bs::pack_<bd::integer_<T>, X>\n                          , bs::pack_<bd::integer_<T>, X>\n                          )\n  {\n    BOOST_FORCEINLINE T operator()( bd::functor<bs::tag::ifloor_> const&\n                                                    ,T const& a, T const& b) const BOOST_NOEXCEPT\n    {\n      return  div(floor, a, b);\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD_IF ( div_\n                          , (typename T, typename X)\n                          , (detail::is_native<X>)\n                          , bd::cpu_\n                          , bs::tag::iround_\n                          , bs::pack_<bd::integer_<T>, X>\n                          , bs::pack_<bd::integer_<T>, X>\n                          )\n  {\n    BOOST_FORCEINLINE T operator()( bd::functor<bs::tag::iround_> const&\n                                                    ,T const& a, T const& b) const BOOST_NOEXCEPT\n    {\n      return div(round, a, b);\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD_IF ( div_\n                          , (typename T, typename X)\n                          , (detail::is_native<X>)\n                          , bd::cpu_\n                          , bs::tag::inearbyint_\n                          , bs::pack_<bd::integer_<T>, X>\n                          , bs::pack_<bd::integer_<T>, X>\n                          )\n  {\n    BOOST_FORCEINLINE T operator()( bd::functor<bs::tag::inearbyint_> const&\n                                  ,T const& a, T const& b) const BOOST_NOEXCEPT\n    {\n      return  div(nearbyint, a, b);\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD_IF ( div_\n                          , (typename T, typename X)\n                          , (detail::is_native<X>)\n                          , bd::cpu_\n                          , bs::pack_<bd::arithmetic_<T>, X>\n                          , bs::pack_<bd::arithmetic_<T>, X>\n                          )\n  {\n    BOOST_FORCEINLINE T operator()(T const& a, T const& b ) const BOOST_NOEXCEPT\n    {\n      return divides(a, b);\n    }\n  };\n\n} } }\n\n#endif\n", "meta": {"hexsha": "f78878cc65e84e85d1e439c375f2efff5c61e39e", "size": 7948, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/simd/function/div.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/div.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/div.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.2922374429, "max_line_length": 100, "alphanum_fraction": 0.439859084, "num_tokens": 1745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.4620538712352839}}
{"text": "/**\n * \\file PedalToneStackFilter.hxx\n */\n\n#include <boost/math/tools/polynomial.hpp>\n\n#include <ATK/EQ/PedalToneStackFilter.h>\n\nnamespace ATK\n{\n  template<typename DataType>\n  SD1ToneCoefficients<DataType>::SD1ToneCoefficients(gsl::index nb_channels)\n  :TypedBaseFilter<DataType>(nb_channels, nb_channels)\n  {\n  }\n\n  template<typename DataType>\n  void SD1ToneCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n    \n    coefficients_in.assign(in_order+1, 0);\n    coefficients_out.assign(out_order, 0);\n\n    CoeffDataType tempm[2] = {static_cast<CoeffDataType>(-2) * input_sampling_rate, static_cast<CoeffDataType>(2) * input_sampling_rate};\n    CoeffDataType tempp[2] = {static_cast<CoeffDataType>(1), static_cast<CoeffDataType>(1)};\n    boost::math::tools::polynomial<CoeffDataType> poly1(tempm, 1);\n    boost::math::tools::polynomial<CoeffDataType> poly2(tempp, 1);\n\n    boost::math::tools::polynomial<CoeffDataType> b;\n    boost::math::tools::polynomial<CoeffDataType> a;\n    \n    b += poly2 * poly2;\n    b += poly2 * poly1 * (C2*R3+R4*C3+alpha*(1-alpha)*R2*C2+alpha*C2*R4);\n    b += poly1 * poly1 * (C3*R4*(R3*C2+alpha*(1-alpha)*R2*C2));\n\n    a += poly2 * poly2;\n    a += poly2 * poly1 * (C2*R3+R1*C1+alpha*(1-alpha)*R2*C2+(1-alpha)*C2*R1);\n    a += poly1 * poly1 * (C1*R1*(R3*C2+alpha*(1-alpha)*R2*C2));\n\n    for(gsl::index i = 0; i < in_order + 1; ++i)\n    {\n      coefficients_in[i] = b[i] / a[out_order];\n    }\n    for(gsl::index i = 0; i < out_order; ++i)\n    {\n      coefficients_out[i] = -a[i] / a[out_order];\n    }\n  }\n\n  template<typename DataType_>\n  void SD1ToneCoefficients<DataType_>::set_tone(CoeffDataType alpha)\n  {\n    if(alpha < 0 || alpha > 1)\n    {\n      throw std::out_of_range(\"Tone is outside the interval [0,1]\");\n    }\n    this->alpha = alpha;\n\n    setup();\n  }\n  \n  template<typename DataType_>\n  typename SD1ToneCoefficients<DataType_>::CoeffDataType SD1ToneCoefficients<DataType_>::get_tone() const\n  {\n    return alpha;\n  }\n\n  template<typename DataType>\n  TS9ToneCoefficients<DataType>::TS9ToneCoefficients(gsl::index nb_channels)\n  :TypedBaseFilter<DataType>(nb_channels, nb_channels)\n  {\n  }\n  \n  template<typename DataType>\n  void TS9ToneCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n    \n    coefficients_in.assign(in_order+1, 0);\n    coefficients_out.assign(out_order, 0);\n    \n    CoeffDataType tempm[2] = {static_cast<CoeffDataType>(-2) * input_sampling_rate, static_cast<CoeffDataType>(2) * input_sampling_rate};\n    CoeffDataType tempp[2] = {static_cast<CoeffDataType>(1), static_cast<CoeffDataType>(1)};\n    boost::math::tools::polynomial<CoeffDataType> poly1(tempm, 1);\n    boost::math::tools::polynomial<CoeffDataType> poly2(tempp, 1);\n    \n    boost::math::tools::polynomial<CoeffDataType> b;\n    boost::math::tools::polynomial<CoeffDataType> a;\n    \n    b += poly2 * poly2 * R2;\n    b += poly2 * poly1 * (alpha * C2 * R2 * R3 + alpha * (1-alpha) * C2 * P * R2 + R2 * R4 * C2);\n    \n    a += poly2 * poly2 * (R2 + R1);\n    a += poly2 * poly1 * ((1-alpha) * C2 * (alpha * P * R2 + R1 * alpha * P + R1 * R2) + R4 * C2 * (R2 + R1) + R1 * C1 * R2);\n    a += poly1 * poly1 * (C2 * R4 * C1 * R2 * R1 + (1-alpha) * C2 * R1 * P * C1 * R2);\n    \n    for(gsl::index i = 0; i < in_order + 1; ++i)\n    {\n      coefficients_in[i] = b[i] / a[out_order];\n    }\n    for(gsl::index i = 0; i < out_order; ++i)\n    {\n      coefficients_out[i] = -a[i] / a[out_order];\n    }\n  }\n  \n  template<typename DataType_>\n  void TS9ToneCoefficients<DataType_>::set_tone(CoeffDataType alpha)\n  {\n    if(alpha < 0 || alpha > 1)\n    {\n      throw std::out_of_range(\"Tone is outside the interval [0,1]\");\n    }\n    this->alpha = alpha;\n    \n    setup();\n  }\n  \n  template<typename DataType_>\n  typename TS9ToneCoefficients<DataType_>::CoeffDataType TS9ToneCoefficients<DataType_>::get_tone() const\n  {\n    return alpha;\n  }\n}\n", "meta": {"hexsha": "f53fa9924015217b614ccec68955ccea356ce67b", "size": 3856, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "ATK/EQ/PedalToneStackFilter.hxx", "max_stars_repo_name": "D-J-Roberts/AudioTK", "max_stars_repo_head_hexsha": "accf009d7238f32702eb1d5ee23c5148fc68e3bd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 249.0, "max_stars_repo_stars_event_min_datetime": "2015-01-05T13:36:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T18:47:46.000Z", "max_issues_repo_path": "ATK/EQ/PedalToneStackFilter.hxx", "max_issues_repo_name": "D-J-Roberts/AudioTK", "max_issues_repo_head_hexsha": "accf009d7238f32702eb1d5ee23c5148fc68e3bd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 22.0, "max_issues_repo_issues_event_min_datetime": "2015-07-28T15:20:24.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-11T14:18:19.000Z", "max_forks_repo_path": "ATK/EQ/PedalToneStackFilter.hxx", "max_forks_repo_name": "D-J-Roberts/AudioTK", "max_forks_repo_head_hexsha": "accf009d7238f32702eb1d5ee23c5148fc68e3bd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 48.0, "max_forks_repo_forks_event_min_datetime": "2015-08-15T12:08:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-07T02:33:07.000Z", "avg_line_length": 30.6031746032, "max_line_length": 137, "alphanum_fraction": 0.6384854772, "num_tokens": 1246, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391617003942, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.4619994975481985}}
{"text": "// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n// \n//     https://www.apache.org/licenses/LICENSE-2.0\n// \n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#include \"SphereWeights.h\"\n\n#include <algorithm>\n#include <cfloat>\n#include <numeric>\n\n#include <Eigen/Sparse>\n#include <Eigen/SparseQR>\n\n#include <igl/harmonic.h>\n\n#include <OpenGP/Image/Image.h>\n#include <OpenGP/SphereMesh/helpers.h>\n\nusing namespace OpenGP;\nusing Vec2i = Eigen::Vector2i;\nusing Vec3i = Eigen::Vector3i;\nusing Vec4i = Eigen::Vector4i;\n\nvoid calc_weights(const SphereMesh &smesh, SurfaceMesh &mesh) {\n\n    auto vpoint = smesh.get_vertex_property<Vec4>(\"v:point\");\n\n    auto distribute = [&](Vec3 p, SphereMesh::Edge edge) -> Vec2 {\n        Vec4 s0 = vpoint[smesh.vertex(edge, 0)];\n        Vec4 s1 = vpoint[smesh.vertex(edge, 1)];\n\n        Vec3 c0 = s0.head<3>();\n        Vec4 a = s1 - s0;\n        Vec3 d = a.head<3>();\n        float l = d.norm();\n        Vec3 an = d / l;\n        Vec3 d2 = p - c0;\n        Vec3 p_proj = d2 - an * d2.dot(an);\n        float beta = asin(a(3) / l);\n        Vec3 offset = an * p_proj.norm() * tan(beta);\n        float t = an.dot(p + p_proj + offset - c0) / l;\n        t = fmax(fmin(t, 1), 0);\n        return Vec2(1 - t, t);\n    };\n\n    int n_pills = smesh.n_edges();\n    int n_verts = mesh.n_vertices();\n\n    Eigen::MatrixXf P(n_verts, n_pills);\n    P.setZero();\n\n    float lambda = 0.1;\n\n    for (int i = 0; i < n_verts; ++i) {\n\n        auto vert_i = SurfaceMesh::Vertex(i);\n\n        for (int j = 0; j < smesh.n_edges(); ++j) {\n\n            auto edge_j = SphereMesh::Edge(j);\n\n            Vec4 s0 = vpoint[smesh.vertex(edge_j, 0)];\n            Vec4 s1 = vpoint[smesh.vertex(edge_j, 1)];\n\n            float sdf;\n            pill_project(mesh.position(vert_i), s0, s1, &sdf);\n\n            P(i, j) = 1.f / (1e-6 + std::pow(std::max(sdf, 0.f), 2.f));\n        }\n\n        float sum = P.row(i).sum();\n        P.row(i) /= sum;\n    }\n\n    P *= lambda;\n\n    Eigen::Matrix<double, -1, -1> V(n_verts, 3);\n    Eigen::Matrix<int, -1, -1> F(mesh.n_faces(), 3);\n\n    for (int i = 0; i < n_verts; ++i) {\n        V.row(i) =\n            mesh.position(SurfaceMesh::Vertex(i)).transpose().cast<double>();\n    }\n\n    for (int i = 0; i < mesh.n_faces(); ++i) {\n        int j = 0;\n        for (auto vert : mesh.vertices(SurfaceMesh::Face(i)))\n            F(i, j++) = vert.idx();\n    }\n\n    Eigen::SparseMatrix<double> Ld(n_verts, n_verts);\n\n    igl::harmonic(V, F, 1, Ld);\n\n    for (int i = 0; i < n_verts; ++i) {\n        Ld.coeffRef(i, i) += lambda;\n    }\n\n    Eigen::SparseMatrix<float> L = Ld.cast<float>();\n\n    Eigen::SparseLU<Eigen::SparseMatrix<float>> solver(L);\n\n    Eigen::MatrixXf weights(n_verts, n_pills);\n    for (int i = 0; i < n_pills; ++i) {\n        weights.col(i) = solver.solve(P.col(i));\n    }\n\n    auto weights_prop =\n        mesh.add_vertex_property<std::vector<float>>(\"v:skinweight\");\n    auto bone_ids_prop = mesh.add_vertex_property<std::vector<int>>(\"v:boneid\");\n\n    for (int i = 0; i < n_verts; ++i) {\n        Vec3 p = mesh.position(SurfaceMesh::Vertex(i));\n        Eigen::VectorXf row = weights.row(i).transpose();\n        std::vector<float> per_cap_weights;\n        for (int j = 0; j < n_pills; ++j) {\n            Vec2 cap_weights = distribute(p, SphereMesh::Edge(j)) * row[j];\n            per_cap_weights.push_back(cap_weights[0]);\n            per_cap_weights.push_back(cap_weights[1]);\n        }\n        std::vector<int> inds(2 * n_pills);\n        std::iota(inds.begin(), inds.end(), 0);\n        std::sort(inds.begin(), inds.end(), [&](int i, int j) {\n            return per_cap_weights[i] > per_cap_weights[j];\n        });\n\n        std::vector<float> w;\n        std::vector<int> wi;\n        for (int j = 0; j < inds.size(); ++j) {\n            w.push_back(per_cap_weights[inds[j]]);\n            wi.push_back(inds[j]);\n            if (w.back() / w.front() < 0.01)\n                break;\n        }\n\n        float sum = std::accumulate(w.begin(), w.end(), 0.f);\n        std::transform(w.begin(), w.end(), w.begin(),\n                       [sum](float x) { return x / sum; });\n\n        SurfaceMesh::Vertex vert(i);\n        weights_prop[vert] = w;\n        bone_ids_prop[vert] = wi;\n\n    }\n\n}", "meta": {"hexsha": "3647c58644f2661d1cc4adca4e875462ffb7dcb6", "size": 4602, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SphereWeights/SphereWeights.cpp", "max_stars_repo_name": "papagiannakis/viper", "max_stars_repo_head_hexsha": "2f25416385b0cf42c60e19ff787fe4a6a4c26223", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 847.0, "max_stars_repo_stars_event_min_datetime": "2019-07-29T15:21:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T16:28:55.000Z", "max_issues_repo_path": "SphereWeights/SphereWeights.cpp", "max_issues_repo_name": "Open-AGI/viper", "max_issues_repo_head_hexsha": "2f25416385b0cf42c60e19ff787fe4a6a4c26223", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 17.0, "max_issues_repo_issues_event_min_datetime": "2020-04-08T16:41:11.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-18T09:39:20.000Z", "max_forks_repo_path": "SphereWeights/SphereWeights.cpp", "max_forks_repo_name": "Open-AGI/viper", "max_forks_repo_head_hexsha": "2f25416385b0cf42c60e19ff787fe4a6a4c26223", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 100.0, "max_forks_repo_forks_event_min_datetime": "2019-12-27T10:18:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:30:40.000Z", "avg_line_length": 29.8831168831, "max_line_length": 80, "alphanum_fraction": 0.5634506736, "num_tokens": 1326, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391617003942, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.4619994975481985}}
{"text": "/*\n * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\n#define BOOST_TEST_MAIN\n#define BOOST_TEST_MODULE CudaPipeline_test\n\n// Standard includes\n#include <string>\n\n// Third party includes\n#include <boost/test/unit_test.hpp>\n\n// Local VOTCA includes\n#include \"votca/xtp/cudapipeline.h\"\n#include \"votca/xtp/eigen.h\"\n\nusing namespace votca::xtp;\n\nBOOST_AUTO_TEST_SUITE(CudaPipeline_test)\n\nBOOST_AUTO_TEST_CASE(matmul) {\n  // Call the class to handle GPU resources\n  CudaPipeline cuda_pip(0);\n\n  Eigen::MatrixXd A = Eigen::MatrixXd::Random(6, 10);\n  Eigen::MatrixXd B = Eigen::MatrixXd::Random(10, 6);\n\n  Eigen::MatrixXd C = Eigen::MatrixXd::Zero(6, 6);\n\n  CudaMatrix Ag{A, cuda_pip.get_stream()};\n  CudaMatrix Bg{B, cuda_pip.get_stream()};\n  CudaMatrix Cg{C, cuda_pip.get_stream()};\n\n  cuda_pip.gemm(Ag, Bg, Cg);\n\n  Eigen::MatrixXd GPU_result = Cg;\n  Eigen::MatrixXd CPU_result = A * B;\n  bool check = CPU_result.isApprox(GPU_result, 1e-9);\n  BOOST_CHECK_EQUAL(check, true);\n  if (!check) {\n    std::cout << \"CPU\\n\" << CPU_result << std::endl;\n    std::cout << \"GPU\\n\" << GPU_result << std::endl;\n  }\n}\n\nBOOST_AUTO_TEST_CASE(matmul_Cb) {\n  // Call the class to handle GPU resources\n  CudaPipeline cuda_pip(0);\n\n  Eigen::MatrixXd A = Eigen::MatrixXd::Random(6, 10);\n  Eigen::MatrixXd B = Eigen::MatrixXd::Random(10, 6);\n\n  Eigen::MatrixXd C = Eigen::MatrixXd::Zero(8, 10);\n\n  CudaMatrix Ag{A, cuda_pip.get_stream()};\n  CudaMatrix Bg{B, cuda_pip.get_stream()};\n  CudaMatrix Cg{C, cuda_pip.get_stream()};\n\n  cuda_pip.gemm(Ag, Bg, Cg.block(1, 2, 6, 6));\n\n  Eigen::MatrixXd GPU_result = Cg;\n  Eigen::MatrixXd CPU_result = A * B;\n  bool check = CPU_result.isApprox(GPU_result.block(1, 2, 6, 6), 1e-9);\n  BOOST_CHECK_EQUAL(check, true);\n  if (!check) {\n    std::cout << \"CPU\\n\" << CPU_result << std::endl;\n    std::cout << \"GPU\\n\" << GPU_result << std::endl;\n  }\n}\n\nBOOST_AUTO_TEST_CASE(matmul_ABb) {\n  // Call the class to handle GPU resources\n  CudaPipeline cuda_pip(0);\n\n  Eigen::MatrixXd A = Eigen::MatrixXd::Random(6, 10);\n  Eigen::MatrixXd B = Eigen::MatrixXd::Random(15, 10);\n\n  Eigen::MatrixXd C = Eigen::MatrixXd::Zero(6, 6);\n\n  CudaMatrix Ag{A, cuda_pip.get_stream()};\n  CudaMatrix Bg{B, cuda_pip.get_stream()};\n  CudaMatrix Cg{C, cuda_pip.get_stream()};\n\n  cuda_pip.gemm(Ag, Bg.block(2, 3, 10, 6), Cg);\n\n  Eigen::MatrixXd GPU_result = Cg;\n  Eigen::MatrixXd CPU_result = A * B.block(2, 3, 10, 6);\n  bool check = CPU_result.isApprox(GPU_result, 1e-9);\n  BOOST_CHECK_EQUAL(check, true);\n  if (!check) {\n    std::cout << \"CPU\\n\" << CPU_result << std::endl;\n    std::cout << \"GPU\\n\" << GPU_result << std::endl;\n  }\n}\n\nBOOST_AUTO_TEST_CASE(matmul_AbB) {\n  // Call the class to handle GPU resources\n  CudaPipeline cuda_pip(0);\n\n  Eigen::MatrixXd A = Eigen::MatrixXd::Random(10, 15);\n  Eigen::MatrixXd B = Eigen::MatrixXd::Random(10, 6);\n\n  Eigen::MatrixXd C = Eigen::MatrixXd::Zero(6, 6);\n\n  CudaMatrix Ag{A, cuda_pip.get_stream()};\n  CudaMatrix Bg{B, cuda_pip.get_stream()};\n  CudaMatrix Cg{C, cuda_pip.get_stream()};\n\n  cuda_pip.gemm(Ag.block(2, 3, 6, 10), Bg, Cg);\n\n  Eigen::MatrixXd GPU_result = Cg;\n  Eigen::MatrixXd CPU_result = A.block(2, 3, 6, 10) * B;\n  bool check = CPU_result.isApprox(GPU_result, 1e-9);\n  BOOST_CHECK_EQUAL(check, true);\n  if (!check) {\n    std::cout << \"CPU\\n\" << CPU_result << std::endl;\n    std::cout << \"GPU\\n\" << GPU_result << std::endl;\n  }\n}\n\nBOOST_AUTO_TEST_CASE(matmul_add) {\n  // Call the class to handle GPU resources\n  CudaPipeline cuda_pip(0);\n\n  Eigen::MatrixXd A = Eigen::MatrixXd::Random(6, 10);\n  Eigen::MatrixXd B = Eigen::MatrixXd::Random(10, 6);\n\n  Eigen::MatrixXd C = Eigen::MatrixXd::Random(6, 6);\n\n  CudaMatrix Ag{A, cuda_pip.get_stream()};\n  CudaMatrix Bg{B, cuda_pip.get_stream()};\n  CudaMatrix Cg{C, cuda_pip.get_stream()};\n\n  cuda_pip.gemm(Ag, Bg, Cg, 2.0);\n\n  Eigen::MatrixXd GPU_result = Cg;\n  Eigen::MatrixXd CPU_result = A * B + 2 * C;\n  bool check = CPU_result.isApprox(GPU_result, 1e-9);\n  BOOST_CHECK_EQUAL(check, true);\n  if (!check) {\n    std::cout << \"CPU\\n\" << CPU_result << std::endl;\n    std::cout << \"GPU\\n\" << GPU_result << std::endl;\n  }\n}\n\nBOOST_AUTO_TEST_CASE(matmul_AB_Cbadd) {\n  // Call the class to handle GPU resources\n  CudaPipeline cuda_pip(0);\n\n  Eigen::MatrixXd A = Eigen::MatrixXd::Random(6, 10);\n  Eigen::MatrixXd B = Eigen::MatrixXd::Random(10, 6);\n\n  Eigen::MatrixXd C = Eigen::MatrixXd::Random(9, 9);\n\n  CudaMatrix Ag{A, cuda_pip.get_stream()};\n  CudaMatrix Bg{B, cuda_pip.get_stream()};\n  CudaMatrix Cg{C, cuda_pip.get_stream()};\n\n  cuda_pip.gemm(Ag, Bg, Cg.block(1, 1, 6, 6), 1.0);\n\n  Eigen::MatrixXd GPU_result = Cg;\n  C.block(1, 1, 6, 6) += A * B;\n  Eigen::MatrixXd CPU_result = C;\n  bool check = CPU_result.isApprox(GPU_result, 1e-9);\n  BOOST_CHECK_EQUAL(check, true);\n  if (!check) {\n    std::cout << \"CPU\\n\" << CPU_result << std::endl;\n    std::cout << \"GPU\\n\" << GPU_result << std::endl;\n  }\n}\n\nBOOST_AUTO_TEST_CASE(matmul_ABt) {\n  // Call the class to handle GPU resources\n  CudaPipeline cuda_pip(0);\n\n  Eigen::MatrixXd A = Eigen::MatrixXd::Random(6, 10);\n  Eigen::MatrixXd B = Eigen::MatrixXd::Random(6, 10);\n\n  Eigen::MatrixXd C = Eigen::MatrixXd::Zero(6, 6);\n\n  CudaMatrix Ag{A, cuda_pip.get_stream()};\n  CudaMatrix Bg{B, cuda_pip.get_stream()};\n  CudaMatrix Cg{C, cuda_pip.get_stream()};\n\n  cuda_pip.gemm(Ag, Bg.transpose(), Cg);\n\n  Eigen::MatrixXd GPU_result = Cg;\n  Eigen::MatrixXd CPU_result = A * B.transpose();\n  bool check = CPU_result.isApprox(GPU_result, 1e-9);\n  BOOST_CHECK_EQUAL(check, true);\n  if (!check) {\n    std::cout << \"CPU\\n\" << CPU_result << std::endl;\n    std::cout << \"GPU\\n\" << GPU_result << std::endl;\n  }\n}\n\nBOOST_AUTO_TEST_CASE(matmul_AtB) {\n  // Call the class to handle GPU resources\n  CudaPipeline cuda_pip(0);\n\n  Eigen::MatrixXd A = Eigen::MatrixXd::Random(10, 6);\n  Eigen::MatrixXd B = Eigen::MatrixXd::Random(10, 6);\n\n  Eigen::MatrixXd C = Eigen::MatrixXd::Zero(6, 6);\n\n  CudaMatrix Ag{A, cuda_pip.get_stream()};\n  CudaMatrix Bg{B, cuda_pip.get_stream()};\n  CudaMatrix Cg{C, cuda_pip.get_stream()};\n\n  cuda_pip.gemm(Ag.transpose(), Bg, Cg);\n\n  Eigen::MatrixXd GPU_result = Cg;\n  Eigen::MatrixXd CPU_result = A.transpose() * B;\n  bool check = CPU_result.isApprox(GPU_result, 1e-9);\n  BOOST_CHECK_EQUAL(check, true);\n  if (!check) {\n    std::cout << \"CPU\\n\" << CPU_result << std::endl;\n    std::cout << \"GPU\\n\" << GPU_result << std::endl;\n  }\n}\n\nBOOST_AUTO_TEST_CASE(matmul_AtBt) {\n  // Call the class to handle GPU resources\n  CudaPipeline cuda_pip(0);\n\n  Eigen::MatrixXd A = Eigen::MatrixXd::Random(10, 6);\n  Eigen::MatrixXd B = Eigen::MatrixXd::Random(6, 10);\n\n  Eigen::MatrixXd C = Eigen::MatrixXd::Zero(6, 6);\n\n  CudaMatrix Ag{A, cuda_pip.get_stream()};\n  CudaMatrix Bg{B, cuda_pip.get_stream()};\n  CudaMatrix Cg{C, cuda_pip.get_stream()};\n\n  cuda_pip.gemm(Ag.transpose(), Bg.transpose(), Cg);\n\n  Eigen::MatrixXd GPU_result = Cg;\n  Eigen::MatrixXd CPU_result = A.transpose() * B.transpose();\n  bool check = CPU_result.isApprox(GPU_result, 1e-9);\n  BOOST_CHECK_EQUAL(check, true);\n  if (!check) {\n    std::cout << \"CPU\\n\" << CPU_result << std::endl;\n    std::cout << \"GPU\\n\" << GPU_result << std::endl;\n  }\n}\n\nBOOST_AUTO_TEST_CASE(diag_matrix_mul) {\n  // Call the class to handle GPU resources\n  CudaPipeline cuda_pip(0);\n\n  Eigen::MatrixXd A = Eigen::MatrixXd::Random(6, 10);\n  Eigen::VectorXd b = Eigen::VectorXd::Random(10);\n\n  Eigen::MatrixXd C = Eigen::MatrixXd::Zero(6, 10);\n\n  CudaMatrix Ag{A, cuda_pip.get_stream()};\n  CudaMatrix bg{b, cuda_pip.get_stream()};\n  CudaMatrix Cg{C, cuda_pip.get_stream()};\n\n  cuda_pip.diag_gemm(Ag, bg, Cg);\n\n  Eigen::MatrixXd GPU_result = Cg;\n  Eigen::MatrixXd CPU_result = A * b.asDiagonal();\n  bool check = CPU_result.isApprox(GPU_result, 1e-9);\n  BOOST_CHECK_EQUAL(check, true);\n  if (!check) {\n    std::cout << \"CPU\\n\" << CPU_result << std::endl;\n    std::cout << \"GPU\\n\" << GPU_result << std::endl;\n  }\n}\n\nBOOST_AUTO_TEST_CASE(diag_matrix_mulT) {\n  // Call the class to handle GPU resources\n  CudaPipeline cuda_pip(0);\n\n  Eigen::MatrixXd A = Eigen::MatrixXd::Random(10, 6);\n  Eigen::VectorXd b = Eigen::VectorXd::Random(10);\n\n  Eigen::MatrixXd C = Eigen::MatrixXd::Zero(10, 6);\n\n  CudaMatrix Ag{A, cuda_pip.get_stream()};\n  CudaMatrix bg{b, cuda_pip.get_stream()};\n  CudaMatrix Cg{C, cuda_pip.get_stream()};\n\n  cuda_pip.diag_gemm(Ag.transpose(), bg, Cg);\n\n  Eigen::MatrixXd GPU_result = Cg;\n  Eigen::MatrixXd CPU_result = b.asDiagonal() * A;\n  bool check = CPU_result.isApprox(GPU_result, 1e-9);\n  BOOST_CHECK_EQUAL(check, true);\n  if (!check) {\n    std::cout << \"CPU\\n\" << CPU_result << std::endl;\n    std::cout << \"GPU\\n\" << GPU_result << std::endl;\n  }\n}\n\nBOOST_AUTO_TEST_CASE(diag_matrix_mul_onemat) {\n  // Call the class to handle GPU resources\n  CudaPipeline cuda_pip(0);\n\n  Eigen::MatrixXd A = Eigen::MatrixXd::Random(10, 6);\n  Eigen::VectorXd b = Eigen::VectorXd::Random(10);\n\n  CudaMatrix Ag{A, cuda_pip.get_stream()};\n  CudaMatrix bg{b, cuda_pip.get_stream()};\n\n  cuda_pip.diag_gemm(Ag.transpose(), bg, Ag);\n\n  Eigen::MatrixXd GPU_result = Ag;\n  Eigen::MatrixXd CPU_result = b.asDiagonal() * A;\n  bool check = CPU_result.isApprox(GPU_result, 1e-9);\n  BOOST_CHECK_EQUAL(check, true);\n  if (!check) {\n    std::cout << \"CPU\\n\" << CPU_result << std::endl;\n    std::cout << \"GPU\\n\" << GPU_result << std::endl;\n  }\n}\n\nBOOST_AUTO_TEST_CASE(axpy) {\n  // Call the class to handle GPU resources\n  CudaPipeline cuda_pip(0);\n\n  Eigen::MatrixXd A = Eigen::MatrixXd::Random(8, 10);\n  Eigen::MatrixXd B = Eigen::MatrixXd::Random(8, 10);\n\n  CudaMatrix Ag{A, cuda_pip.get_stream()};\n  CudaMatrix Bg{B, cuda_pip.get_stream()};\n\n  cuda_pip.axpy(Ag, Bg, 3.0);\n\n  Eigen::MatrixXd GPU_result = Bg;\n  Eigen::MatrixXd CPU_result = B + 3.0 * A;\n  bool check = CPU_result.isApprox(GPU_result, 1e-9);\n  BOOST_CHECK_EQUAL(check, true);\n  if (!check) {\n    std::cout << \"CPU\\n\" << CPU_result << std::endl;\n    std::cout << \"GPU\\n\" << GPU_result << std::endl;\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "90e8dff8a609554c5d4882403ca2419b733f73a7", "size": 10490, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/tests/test_cudapipeline.cc", "max_stars_repo_name": "rubengerritsen/xtp", "max_stars_repo_head_hexsha": "af4db53ca99853280d0e2ddc7f3c41bce8ae6e91", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/tests/test_cudapipeline.cc", "max_issues_repo_name": "rubengerritsen/xtp", "max_issues_repo_head_hexsha": "af4db53ca99853280d0e2ddc7f3c41bce8ae6e91", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tests/test_cudapipeline.cc", "max_forks_repo_name": "rubengerritsen/xtp", "max_forks_repo_head_hexsha": "af4db53ca99853280d0e2ddc7f3c41bce8ae6e91", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5492957746, "max_line_length": 75, "alphanum_fraction": 0.6729265968, "num_tokens": 3299, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721305, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4619872110689896}}
{"text": "#include <iostream>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/kruskal_min_spanning_tree.hpp>\n\nusing namespace boost;\nusing namespace std;\n\n#include \"tsp-types.h\"\n#include \"tsp-hkbound.h\"\n#include \"tsp-tsp.h\"\n\n\ntypedef property<edge_weight_t, int> ewProperty;\ntypedef adjacency_list< slistS, vecS, undirectedS,\n\t\t\tno_property, ewProperty > Graph;\n\ntypedef Graph::edge_descriptor Edge;\n\n\n\nint lower_bound_using_hk(tsp_path_t path, int hops, int len, uint64_t vpres) {\n  Graph g;\n\n  /* construire le graph complet avec les villes et ar\u00eates restantes */\n  for (int i = 0; i < nb_towns; i++) {\n    if ( present( i, hops, path, vpres ) )\n      continue;\n\n    /* aretes vers 0 et la derni\u00e8re ville */\n    add_edge( 0, i, tsp_distance[0][i], g);\n    add_edge( i, path[hops-1], tsp_distance[i][ path[hops-1] ], g);\n\n    for(int j = i+1; j < nb_towns; j++) {\n      if (present( j , hops, path, vpres) )\n\tcontinue;\n      add_edge( i, j, tsp_distance[i][j], g);\n    }\n  }\n\n  std::list < Edge > spt;\n  kruskal_minimum_spanning_tree ( g, std::back_inserter(spt) );\n\n  int somme = 0;\n  for(auto const & e: spt) {\n    somme += get(edge_weight, g)[e];\n  }\n\n  return somme + len;\n}\n", "meta": {"hexsha": "3b808e28152771a0b0a5f219c0288fe8318e4fde", "size": 1186, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tsp-hkbound.cpp", "max_stars_repo_name": "Roth1/multithreaded-tsp", "max_stars_repo_head_hexsha": "2d12a8c7bef5643b3794046bf9c9742e6c30d3c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/tsp-hkbound.cpp", "max_issues_repo_name": "Roth1/multithreaded-tsp", "max_issues_repo_head_hexsha": "2d12a8c7bef5643b3794046bf9c9742e6c30d3c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tsp-hkbound.cpp", "max_forks_repo_name": "Roth1/multithreaded-tsp", "max_forks_repo_head_hexsha": "2d12a8c7bef5643b3794046bf9c9742e6c30d3c2", "max_forks_repo_licenses": ["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.72, "max_line_length": 78, "alphanum_fraction": 0.6593591906, "num_tokens": 366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.46198721106898955}}
{"text": "/////////////////////////////////////////////////////////////////////////////////\n// distribution::toolkit::distributions::chi_squared::random.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_CHI_SQUARED_RANDOM_HPP_ER_2009\n#define BOOST_STATISTICS_DETAIL_DISTRIBUTION_TOOLKIT_CHI_SQUARED_RANDOM_HPP_ER_2009\n#include <boost/math/distributions/chi_squared.hpp>\n#include <boost/random/chi_squared.hpp>\n#include <boost/statistics/detail/distribution_common/meta/random/distribution.hpp>\n\nnamespace boost{\nnamespace statistics{\nnamespace detail{\nnamespace distribution{\nnamespace meta{\n\n    template<typename T,typename P>\n    struct random_distribution< \n        boost::math::chi_squared_distribution<T,P> \n    >{\n        typedef boost::math::chi_squared_distribution<T,P> dist_;\n        typedef boost::random::chi_squared_distribution<T> type;\n        \n        static type call(const dist_& d){ \n            return type(d.degrees_of_freedom()); \n        }\n    };\n    \n}// meta\n}// distribution\n}// detail\n}// statistics\n}// boost\n\n#endif\n\n", "meta": {"hexsha": "24120c1650bfea808f3d33508b8a31cae1e03cb6", "size": 1553, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "distribution_toolkit/boost/statistics/detail/distribution_toolkit/distributions/chi_squared/random.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/distributions/chi_squared/random.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/distributions/chi_squared/random.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.8780487805, "max_line_length": 83, "alphanum_fraction": 0.5724404379, "num_tokens": 290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.46198721106898955}}
{"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#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE spkm test\n#include <boost/test/unit_test.hpp>\n\n#include <boost/shared_ptr.hpp>\n\n#include <stdint.h>\n\n#include \"kmeans.hpp\"\n#include \"sphericalKMeans.hpp\"\n#include \"normalSphere.hpp\"\n#include \"karcherMean.hpp\"\n\nusing namespace Eigen;\nusing std::cout;\nusing std::endl;\n\nBOOST_AUTO_TEST_CASE(spkm_test)\n{\n  boost::mt19937 rndGen(91);\n  \n  uint32_t N=20;\n  uint32_t D=3;\n  uint32_t K=2;\n  boost::shared_ptr<MatrixXd> spx(new MatrixXd(D,N));\n  sampleClustersOnSphere<double>(*spx, K);\n\n\n  uint32_t T=10;\n  cout<<\" -------------------- spkm ----------------------\"<<endl;\n  SphericalKMeans<double> spkm(spx,K,&rndGen);\n  for(uint32_t t=0; t<T; ++t)\n  {\n    spkm.updateCenters();\n    spkm.updateLabels();\n    cout<<spkm.z().transpose()<<\" \"<<spkm.avgIntraClusterDeviation()<<endl;\n//    cout<<spkm.centroids()<<endl;\n  }\n  MatrixXd deviates;\n  MatrixXu inds = spkm.mostLikelyInds(10,deviates);\n  cout<<\"most likely indices\"<<endl;\n  cout<<inds<<endl;\n\n  cout<<\" ---------------- spkm_karch -------------------\"<<endl;\n  boost::mt19937 rndGen2(91);\n  SphericalKMeansKarcher<double> spkmKarch(spx,K,&rndGen2);\n \n  for(uint32_t t=0; t<T; ++t)\n  {\n    spkmKarch.updateCenters();\n    spkmKarch.updateLabels();\n    cout<<spkmKarch.z().transpose()<<\" \"\n      <<spkmKarch.avgIntraClusterDeviation()<<endl;\n//    cout<<spkmKarch.centroids()<<endl;\n  }\n  inds = spkmKarch.mostLikelyInds(10,deviates);\n  cout<<\"most likely indices\"<<endl;\n  cout<<inds<<endl;\n\n  cout<<\" ---------------- kmeans -------------------\"<<endl;\n  boost::mt19937 rndGen3(91);\n  KMeans<double> kmeans(spx,K,&rndGen3);\n  for(uint32_t t=0; t<T; ++t)\n  {\n    kmeans.updateCenters();\n    kmeans.updateLabels();\n    cout<<kmeans.z().transpose()<<\" \"\n      <<kmeans.avgIntraClusterDeviation()<<endl;\n//    cout<<kmeans.centroids()<<endl;\n  }\n  inds = kmeans.mostLikelyInds(10,deviates);\n  cout<<\"most likely indices\"<<endl;\n  cout<<inds<<endl;\n\n//  double lambda = - 0.9; //cos(15.0*M_PI/180.0);\n//  cout<<\" -------------------- DpvMF means ----------------------\"<<endl;\n//  DPvMFMeans<double> dpvmfmeans(spx,K,lambda,&rndGen);\n//  for(uint32_t t=0; t<T; ++t)\n//  {\n//    dpvmfmeans.updateCenters();\n//    cout<<dpvmfmeans.z().transpose()<<\" \"\n//      <<dpvmfmeans.avgIntraClusterDeviation()<<endl;\n//    dpvmfmeans.updateLabels();\n//    cout<<dpvmfmeans.z().transpose()<<\" \"\n//      <<dpvmfmeans.avgIntraClusterDeviation()<<endl;\n////    cout<<spkm.centroids()<<endl;\n//  }\n//  inds = dpvmfmeans.mostLikelyInds(10,deviates);\n//  cout<<\"most likely indices\"<<endl;\n//  cout<<inds<<endl;\n//\n//  lambda = cos(15.0*M_PI/180.0);\n//  cout<<\" -------------------- DP-means ----------------------\"<<endl;\n//  DPMeans<double> dpmeans(spx,K,lambda,&rndGen);\n//  for(uint32_t t=0; t<T; ++t)\n//  {\n//    dpmeans.updateCenters();\n//    cout<<dpmeans.z().transpose()<<\" \"\n//      <<dpmeans.avgIntraClusterDeviation()<<endl;\n//    dpmeans.updateLabels();\n//    cout<<dpmeans.z().transpose()<<\" \"\n//      <<dpmeans.avgIntraClusterDeviation()<<endl;\n////    cout<<spkm.centroids()<<endl;\n//  }\n//  inds = dpmeans.mostLikelyInds(10,deviates);\n//  cout<<\"most likely indices\"<<endl;\n//  cout<<inds<<endl;\n//\n////  if(false)\n////  {\n//    lambda = cos(15.0*M_PI/180.0);\n//    double Q = 5.0*M_PI/180.0;\n//    double tau = 5.0*M_PI/180.0;\n//    cout<<\" -------------------- DDP-means ----------------------\"<<endl;\n//    DDPMeans<double> ddpmeans(spx,lambda,Q,tau,&rndGen);\n//\n//    for(uint32_t t=0; t<10; ++t)\n//    {\n//      cout<<\" -- t = \"<<t<<endl;\n//      if(t<4)\n//        for (uint32_t i=0; i<N; ++i)\n//          spx->col(i) = spx->col(i) + VectorXd::Ones(D)*0.1;\n//      else if(t==7)\n//        for (uint32_t i=0; i<N/2; ++i)\n//          spx->col(i+N/2) = spx->col(i); // single cluster from now on\n//      else if(t==4)\n//      {\n//        boost::shared_ptr<MatrixXd> spx3(new MatrixXd(D,N*2));\n//        //      boost::shared_ptr<MatrixXd> spxTmp(new MatrixXd(D,N));\n//        //      sampleClustersOnSphere<double>(*spxTmp, 1);\n//        spx3->rightCols(N) = MatrixXd::Zero(D,N);\n//        spx = spx3;\n//      }\n//\n//      ddpmeans.nextTimeStep(spx); // feed in new data (here just the same\n//      for(uint32_t i=0; i<10; ++i)\n//      { // run clustering till \"converence\"\n//        ddpmeans.updateLabels();\n//        //      cout<<ddpmeans.z().transpose()<<\" \"\n//        //        <<ddpmeans.avgIntraClusterDeviation()<<endl;\n//        ddpmeans.updateCenters();\n//        cout<<ddpmeans.z().transpose()<<\" \"\n//          <<ddpmeans.avgIntraClusterDeviation()<<endl;\n//        //    cout<<spkm.centroids()<<endl;\n//      }\n//      ddpmeans.updateState(); // update the state internally\n//    }\n//\n//  inds = ddpmeans.mostLikelyInds(10,deviates);\n//  cout<<\"most likely indices\"<<endl;\n//  cout<<inds<<endl;\n//  return;\n////  }\n//\n//  cout<<spx->transpose()<<endl;\n//\n//  lambda = -0.5; //cos(15.0*M_PI/180.0);\n//  double beta = 5.0*M_PI/180.0;\n//  double w = 5.0*M_PI/180.0;\n//  cout<<\" -------------------- DDP-vMF-means ----------------------\"<<endl;\n//  DDPvMFMeans<double> ddpvmfmeans(spx,lambda,beta,w,&rndGen);\n//\n//  double dAng = 5.0*M_PI/180.0;\n//  MatrixXd dR = MatrixXd::Zero(3,3);\n//  dR << cos(dAng), sin(dAng), 0,\n//       -sin(dAng), cos(dAng), 0,\n//       0         , 0        , 1;\n//\n//  MatrixXd means = spkm.centroids();\n//\n//  for(uint32_t t=0; t<10; ++t)\n//  {\n//    cout<<\" -- t = \"<<t<<endl;\n//\n//    if(t==7)\n//    {\n//      boost::shared_ptr<MatrixXd> spx3(new MatrixXd(D,N*2));\n//      //      boost::shared_ptr<MatrixXd> spxTmp(new MatrixXd(D,N));\n//      //      sampleClustersOnSphere<double>(*spxTmp, 1);\n//      spx3->leftCols(N) = *spx;\n//      spx3->rightCols(N) = - (*spx);\n//      spx = spx3;\n//    }\n//\n//    if(t>=3)\n//    {\n//      *spx = dR * (*spx);\n//\n//      means = dR*means;\n//      cout<<\"new means:\"<<endl\n//        <<means.transpose()<<endl\n//        <<\" ----------------------------- \"<<endl;\n//    }\n//\n//\n//    ddpvmfmeans.nextTimeStep(spx); // feed in new data (here just the same\n//    for(uint32_t i=0; i<20; ++i)\n//    { // run clustering till \"converence\"\n////      cout<<\"========================= label udaptes =========================\"<<endl;\n//      ddpvmfmeans.updateLabels();\n////      cout<<ddpvmfmeans.z().transpose()<<\" \"\n////        <<ddpvmfmeans.avgIntraClusterDeviation()<<endl;\n////      cout<<\"========================= center udaptes =========================\"<<endl;\n//      ddpvmfmeans.updateCenters();\n//      cout<<ddpvmfmeans.z().transpose()<<\" \"\n//        <<ddpvmfmeans.avgIntraClusterDeviation()<<endl;\n//      //    cout<<spkm.centroids()<<endl;\n//    }\n//    ddpvmfmeans.updateState(); // update the state internally\n//  }\n//\n////  inds = ddpvmfmeans.mostLikelyInds(10,deviates);\n////  cout<<\"most likely indices\"<<endl;\n////  cout<<inds<<endl;\n}\n", "meta": {"hexsha": "494caaf0ba3f41f8e2b8f2c80623b215b0cb1c39", "size": 6977, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/deprecated/spkm.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": "test/deprecated/spkm.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": "test/deprecated/spkm.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": 31.5701357466, "max_line_length": 91, "alphanum_fraction": 0.5483732263, "num_tokens": 2193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.46198721106898955}}
{"text": "//\n// Copyright (c) 2016-2018 CNRS\n//\n\n#ifndef __pinocchio_dynamics_hpp__\n#define __pinocchio_dynamics_hpp__\n\n#include \"pinocchio/multibody/model.hpp\"\n#include \"pinocchio/multibody/data.hpp\"\n#include \"pinocchio/algorithm/compute-all-terms.hpp\"\n#include \"pinocchio/algorithm/cholesky.hpp\"\n#include \"pinocchio/algorithm/crba.hpp\"\n#include \"pinocchio/algorithm/check.hpp\"\n\n#include <Eigen/Cholesky>\n\nnamespace pinocchio\n{\n  \n  ///\n  /// \\brief Compute the forward dynamics with contact constraints.\n  /// \\note It computes the following problem: <BR>\n  ///       <CENTER> \\f$ \\begin{eqnarray} \\underset{\\ddot{q}}{\\min} & & \\| \\ddot{q} - \\ddot{q}_{\\text{free}} \\|_{M(q)} \\\\\n  ///           \\text{s.t.} & & J (q) \\ddot{q} + \\gamma (q, \\dot{q}) = 0 \\end{eqnarray} \\f$ </CENTER> <BR>\n  ///       where \\f$ \\ddot{q}_{\\text{free}} \\f$ is the free acceleration (i.e. without constraints),\n  ///       \\f$ M \\f$ is the mass matrix, \\f$ J \\f$ the constraint Jacobian and \\f$ \\gamma \\f$ is the constraint drift.\n  ///  By default, the constraint Jacobian is assumed to be full rank, and undamped Cholesky inverse is performed.\n  ///\n  /// \\tparam JointCollection Collection of Joint types.\n  /// \\tparam ConfigVectorType Type of the joint configuration vector.\n  /// \\tparam TangentVectorType1 Type of the joint velocity vector.\n  /// \\tparam TangentVectorType2 Type of the joint torque vector.\n  /// \\tparam ConstraintMatrixType Type of the constraint matrix.\n  /// \\tparam DriftVectorType Type of the drift vector.\n\n  ///\n  /// \\param[in] model The model structure of the rigid body system.\n  /// \\param[in] data The data structure of the rigid body system.\n  /// \\param[in] q The joint configuration (vector dim model.nq).\n  /// \\param[in] v The joint velocity (vector dim model.nv).\n  /// \\param[in] tau The joint torque vector (dim model.nv).\n  /// \\param[in] J The Jacobian of the constraints (dim nb_constraints*model.nv).\n  /// \\param[in] gamma The drift of the constraints (dim nb_constraints).\n  /// \\param[in] inv_damping Damping factor for cholesky decomposition of JMinvJt. Set to zero if constraints are full rank.    \n  /// \\param[in] updateKinematics If true, the algorithm calls first pinocchio::computeAllTerms. Otherwise, it uses the current dynamic values stored in data. \\\\\n  ///            \\note A hint: 1e-12 as the damping factor gave good result in the particular case of redundancy in contact constraints on the two feet.\n  ///\n  /// \\return A reference to the joint acceleration stored in data.ddq. The Lagrange Multipliers linked to the contact forces are available throw data.lambda_c vector.\n  ///\n  template<typename Scalar, int Options, template<typename,int> class JointCollectionTpl, typename ConfigVectorType, typename TangentVectorType1, typename TangentVectorType2,\n  typename ConstraintMatrixType, typename DriftVectorType>\n  inline const typename DataTpl<Scalar,Options,JointCollectionTpl>::TangentVectorType &\n  forwardDynamics(const ModelTpl<Scalar,Options,JointCollectionTpl> & model,\n                  DataTpl<Scalar,Options,JointCollectionTpl> & data,\n                  const Eigen::MatrixBase<ConfigVectorType> & q,\n                  const Eigen::MatrixBase<TangentVectorType1> & v,\n                  const Eigen::MatrixBase<TangentVectorType2> & tau,\n                  const Eigen::MatrixBase<ConstraintMatrixType> & J,\n                  const Eigen::MatrixBase<DriftVectorType> & gamma,\n                  const Scalar inv_damping = 0.,\n                  const bool updateKinematics = true\n                  )\n  {\n    assert(q.size() == model.nq);\n    assert(v.size() == model.nv);\n    assert(tau.size() == model.nv);\n    assert(J.cols() == model.nv);\n    assert(J.rows() == gamma.size());\n    assert(model.check(data) && \"data is not consistent with model.\");\n    \n    typedef DataTpl<Scalar,Options,JointCollectionTpl> Data;\n    \n    typename Data::TangentVectorType & a = data.ddq;\n    typename Data::VectorXs & lambda_c = data.lambda_c;\n    \n    if (updateKinematics)\n      computeAllTerms(model, data, q, v);\n    \n    // Compute the UDUt decomposition of data.M\n    cholesky::decompose(model, data);\n    \n    // Compute the dynamic drift (control - nle)\n    data.torque_residual = tau - data.nle;\n    cholesky::solve(model, data, data.torque_residual);\n    \n    data.sDUiJt = J.transpose();\n    // Compute U^-1 * J.T\n    cholesky::Uiv(model, data, data.sDUiJt);\n    for(Eigen::DenseIndex k=0;k<model.nv;++k)\n      data.sDUiJt.row(k) /= sqrt(data.D[k]);\n    \n    data.JMinvJt.noalias() = data.sDUiJt.transpose() * data.sDUiJt;\n\n    data.JMinvJt.diagonal().array() += inv_damping;\n    data.llt_JMinvJt.compute(data.JMinvJt);\n    \n    // Compute the Lagrange Multipliers\n    lambda_c.noalias() = -J*data.torque_residual;\n    lambda_c -= gamma;\n    data.llt_JMinvJt.solveInPlace(lambda_c);\n    \n    // Compute the joint acceleration\n    a.noalias() = J.transpose() * lambda_c;\n    cholesky::solve(model, data, a);\n    a += data.torque_residual;\n    \n    return a;\n  }\n  \n  ///\n  /// \\brief Compute the impulse dynamics with contact constraints.\n  /// \\note It computes the following problem: <BR>\n  ///       <CENTER> \\f$ \\begin{eqnarray} \\underset{\\dot{q}^{+}}{\\min} & & \\| \\dot{q}^{+} - \\dot{q}^{-} \\|_{M(q)} \\\\\n  ///           \\text{s.t.} & & J (q) \\dot{q}^{+} = - \\epsilon J (q) \\dot{q}^{-}  \\end{eqnarray} \\f$ </CENTER> <BR>\n  ///       where \\f$ \\dot{q}^{-} \\f$ is the generalized velocity before impact,\n  ///       \\f$ M \\f$ is the joint space mass matrix, \\f$ J \\f$ the constraint Jacobian and \\f$ \\epsilon \\f$ is the coefficient of restitution (1 for a fully elastic impact or 0 for a rigid impact).\n  ///\n  /// \\tparam JointCollection Collection of Joint types.\n  /// \\tparam ConfigVectorType Type of the joint configuration vector.\n  /// \\tparam TangentVectorType Type of the joint velocity vector.\n  /// \\tparam ConstraintMatrixType Type of the constraint matrix.\n  ///\n  /// \\param[in] model The model structure of the rigid body system.\n  /// \\param[in] data The data structure of the rigid body system.\n  /// \\param[in] q The joint configuration (vector dim model.nq).\n  /// \\param[in] v_before The joint velocity before impact (vector dim model.nv).\n  /// \\param[in] J The Jacobian of the constraints (dim nb_constraints*model.nv).\n  /// \\param[in] r_coeff The coefficient of restitution. Must be in [0;1].\n  /// \\param[in] updateKinematics If true, the algorithm calls first pinocchio::crba. Otherwise, it uses the current mass matrix value stored in data.\n  ///\n  /// \\return A reference to the generalized velocity after impact stored in data.dq_after. The Lagrange Multipliers linked to the contact impulsed are available throw data.impulse_c vector.\n  ///\n  template<typename Scalar, int Options, template<typename,int> class JointCollectionTpl, typename ConfigVectorType, typename TangentVectorType, typename ConstraintMatrixType>\n  inline const typename DataTpl<Scalar,Options,JointCollectionTpl>::TangentVectorType &\n  impulseDynamics(const ModelTpl<Scalar,Options,JointCollectionTpl> & model,\n                  DataTpl<Scalar,Options,JointCollectionTpl> & data,\n                  const Eigen::MatrixBase<ConfigVectorType> & q,\n                  const Eigen::MatrixBase<TangentVectorType> & v_before,\n                  const Eigen::MatrixBase<ConstraintMatrixType> & J,\n                  const Scalar r_coeff = 0,\n                  const bool updateKinematics = true\n                  )\n  {\n    assert(q.size() == model.nq);\n    assert(v_before.size() == model.nv);\n    assert(J.cols() == model.nv);\n    assert(model.check(data) && \"data is not consistent with model.\");\n    \n    typedef DataTpl<Scalar,Options,JointCollectionTpl> Data;\n    \n    typename Data::VectorXs & impulse_c = data.impulse_c;\n    typename Data::TangentVectorType & dq_after = data.dq_after;\n    \n    // Compute the mass matrix\n    if (updateKinematics)\n      crba(model, data, q);\n    \n    // Compute the UDUt decomposition of data.M\n    cholesky::decompose(model, data);\n    \n    data.sDUiJt = J.transpose();\n    // Compute U^-1 * J.T\n    cholesky::Uiv(model, data, data.sDUiJt);\n    for(int k=0;k<model.nv;++k) data.sDUiJt.row(k) /= sqrt(data.D[k]);\n    \n    data.JMinvJt.noalias() = data.sDUiJt.transpose() * data.sDUiJt;\n    data.llt_JMinvJt.compute(data.JMinvJt);\n    \n    // Compute the Lagrange Multipliers related to the contact impulses\n    impulse_c.noalias() = (-r_coeff - 1.) * (J * v_before);\n    data.llt_JMinvJt.solveInPlace(impulse_c);\n    \n    // Compute the joint velocity after impacts\n    dq_after.noalias() = J.transpose() * impulse_c;\n    cholesky::solve(model, data, dq_after);\n    dq_after += v_before;\n    \n    return dq_after;\n  }\n} // namespace pinocchio\n\n\n#endif // ifndef __pinocchio_dynamics_hpp__\n", "meta": {"hexsha": "a78144ffb96a9002efeefaa3619ec511844bf0f3", "size": 8761, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/algorithm/dynamics.hpp", "max_stars_repo_name": "matthieuvigne/pinocchio", "max_stars_repo_head_hexsha": "01f211eceda3ac2e5edc8cf101690afb6f3184d3", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-22T15:42:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-22T15:42:45.000Z", "max_issues_repo_path": "src/algorithm/dynamics.hpp", "max_issues_repo_name": "matthieuvigne/pinocchio", "max_issues_repo_head_hexsha": "01f211eceda3ac2e5edc8cf101690afb6f3184d3", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/algorithm/dynamics.hpp", "max_forks_repo_name": "matthieuvigne/pinocchio", "max_forks_repo_head_hexsha": "01f211eceda3ac2e5edc8cf101690afb6f3184d3", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-21T09:14:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-21T09:14:26.000Z", "avg_line_length": 47.6141304348, "max_line_length": 198, "alphanum_fraction": 0.6706996918, "num_tokens": 2324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.46198720486178635}}
{"text": "#include <ceres/ceres.h>\n#include \"ceres/rotation.h\"\n#include <pybind11/pybind11.h>\n#include <pybind11/numpy.h>\n#include <algorithm>\n#include <glog/logging.h>\n#include <iterator>\n#include <unordered_set>\n#include <cmath>\n#include <math.h>\n#include <Eigen/Dense>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#define EPS T(0.00001)\n\nusing namespace pybind11::literals;\nnamespace py = pybind11;\nusing namespace Eigen;\n\nstruct FittingResidual {\n    FittingResidual(double *rt_in, double* time_in, double coeff_3_in): rt(rt_in), time(time_in), coeff_3(coeff_3_in){}\n    double *rt;\n    double *time;\n    double coeff_3;\n\n    template<typename T>\n    bool operator()(const T* const spline, T *residual) const {\n        // parameter to be optimized\n        // residual size 2\n        residual[0] = spline[0]*time[0]*time[0]*time[0] + spline[1]*time[0]*time[0] +\\\n                      spline[2]*time[0] + spline[3] - rt[3];\n        residual[1] = spline[4]*time[0]*time[0]*time[0] + spline[5]*time[0]*time[0] +\\\n                      spline[6]*time[0] + spline[7]  - rt[4];\n        auto vx = 3.0*spline[0]*time[0]*time[0] + 2*time[0]*spline[1] + spline[2];\n        auto vy = 3.0*spline[4]*time[0]*time[0] + 2*time[0]*spline[5] + spline[6];\n        auto v_norm = sqrt(vx*vx + vy*vy);\n        vx /= v_norm, vy /= v_norm;\n        residual[2] = 1.0*(vx - rt[0]);\n        residual[3] = 1.0*(vy - rt[1]);\n        residual[4] = coeff_3*spline[0];\n        residual[5] = coeff_3*spline[4];\n        residual[6] = 0.0*spline[1];\n        residual[7] = 0.0*spline[5];\n        // auto grad_square = (spline[0]*time[0]+spline[1])*(spline[0]*time[0]+spline[1]) +\\\n        //          (spline[3]*time[0]+spline[4])*(spline[3]*time[0]+spline[4]);\n        // auto cross = (spline[0]*time[0]+spline[1])*spline[3]-(spline[3]*time[0]+spline[4])*spline[0];\n        return true;\n    }\n};\n\n\npy::object spline_fitting(py::buffer rt_, py::buffer time_, py::buffer spline_, py::buffer cost_,\n                int num_obj, int num_iter, double coeff_3){\n    auto buf0 = rt_.request(); // num_obj*6\n    double *rt = static_cast<double *>(buf0.ptr);\n    auto buf1 = time_.request();\n    double *time = static_cast<double *>(buf1.ptr);\n    auto buf2 = spline_.request();\n    double *spline = static_cast<double *>(buf2.ptr); // 6\n    auto buf3 = cost_.request();\n    double *cost = static_cast<double *>(buf3.ptr);\n    double *rt_i, *time_i;\n    ceres::Problem problem;\n    for (int i = 0; i <num_obj; i++){\n        rt_i = rt + 6*i;\n        time_i = time + i;\n        ceres::CostFunction *cost_function;\n        cost_function = new ceres::AutoDiffCostFunction <FittingResidual, 8, 8>(\n                      new FittingResidual(rt_i, time_i, coeff_3)\n                );\n        problem.AddResidualBlock(cost_function, NULL, spline);\n\n    }\n    ceres::Solver::Options options;\n    options.max_num_iterations = num_iter;\n    options.minimizer_progress_to_stdout = false;\n    options.linear_solver_type = ceres::SPARSE_NORMAL_CHOLESKY;  //ceres::SPARSE_SCHUR;  //ceres::DENSE_SCHUR;\n    ceres::Solver::Summary summary;\n    ceres::Solve(options, &problem, &summary);\n\n    // std::cout<<summary.FullReport()<<\"\\n\";\n    cost[0] = summary.final_cost;\n    // return optimized values\n    py::array_t <double> x_spline = py::array_t <double>(\n            py::buffer_info(\n                    spline,\n                    sizeof(double), //itemsize\n                    py::format_descriptor <double>::format(),\n                    1, // ndim\n                    std::vector<size_t>{(unsigned long) (8)}, // shape\n                    std::vector<size_t>{sizeof(double)} // strides\n            )\n    );\n    py::array_t <double> x_cost = py::array_t <double>(\n            py::buffer_info(\n                    cost,\n                    sizeof(double), //itemsize\n                    py::format_descriptor <double>::format(),\n                    1, // ndim\n                    std::vector<size_t>{(unsigned long) (1)}, // shape\n                    std::vector<size_t>{sizeof(double)} // strides\n            )\n    );\n    py::list outputs;\n    outputs.append(x_spline);\n    outputs.append(x_cost);\n    return outputs;\n}\n\n\nPYBIND11_PLUGIN(ceres_spline) {\n        py::module m(\"ceres_spline\", \"Python bindings to the Ceres-Solver minimizer.\");\n        // google::InitGoogleLogging(\"ceres_spline\");\n        m.def(\"spline_fitting\", &spline_fitting, \"Fitting a spline to a car trajectory\");\n        return m.ptr();\n}\n", "meta": {"hexsha": "4339e56b2f36ce9a69cf219305712f8259160927", "size": 4455, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/ceres/ceres_spline.cc", "max_stars_repo_name": "Emrys-Lee/Traffic4D-Release", "max_stars_repo_head_hexsha": "17cdc84a3a8108f28b4a35e6aa8af1cad19ff6f3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2021-09-16T17:32:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-28T01:51:36.000Z", "max_issues_repo_path": "src/ceres/ceres_spline.cc", "max_issues_repo_name": "Emrys-Lee/Traffic4D-Release", "max_issues_repo_head_hexsha": "17cdc84a3a8108f28b4a35e6aa8af1cad19ff6f3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ceres/ceres_spline.cc", "max_forks_repo_name": "Emrys-Lee/Traffic4D-Release", "max_forks_repo_head_hexsha": "17cdc84a3a8108f28b4a35e6aa8af1cad19ff6f3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-08-24T07:25:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-07T23:44:36.000Z", "avg_line_length": 37.7542372881, "max_line_length": 119, "alphanum_fraction": 0.5818181818, "num_tokens": 1286, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4619872048617862}}
{"text": "#include <boost/test/unit_test.hpp>\n#include \"data/matrix.hh\"\n#include \"functions/function_matrix.hh\"\n#include \"functions/std_functions.hh\"\n#include \"functions/operators.hh\"\n#include \"functions/transpose.hh\"\n#include \"functions/streaming.hh\"\n#include \"data/matrix_operators.hh\"\n\nBOOST_AUTO_TEST_CASE(matrix_test) {\n  using namespace manifolds;\n  auto m1 = GetMatrix<2, 2>(1, 2, 3, 4);\n\n  BOOST_CHECK_EQUAL(m1.Coeff(0, 0), 1);\n  BOOST_CHECK_EQUAL(m1.Coeff(0, 1), 2);\n  BOOST_CHECK_EQUAL(m1.Coeff(1, 0), 3);\n  BOOST_CHECK_EQUAL(m1.Coeff(1, 1), 4);\n\n  auto m2 = m1 + m1;\n\n  BOOST_CHECK_EQUAL(m2.Coeff(0, 0), 2);\n  BOOST_CHECK_EQUAL(m2.Coeff(0, 1), 4);\n  BOOST_CHECK_EQUAL(m2.Coeff(1, 0), 6);\n  BOOST_CHECK_EQUAL(m2.Coeff(1, 1), 8);\n\n  auto m3 = m2 * m1;\n  BOOST_CHECK_EQUAL(m3.Coeff(0, 0), 14);\n  BOOST_CHECK_EQUAL(m3.Coeff(0, 1), 20);\n  BOOST_CHECK_EQUAL(m3.Coeff(1, 0), 30);\n  BOOST_CHECK_EQUAL(m3.Coeff(1, 1), 44);\n\n  auto mf = GetFunctionMatrix(Row(Cos(), -Sin()), Row(Sin(), Cos()));\n  BOOST_CHECK_EQUAL(mf(3), (GetMatrix<2, 2>(std::cos(3), -std::sin(3),\n                                            std::sin(3), std::cos(3))));\n\n  static_assert(is_function<decltype(mf)>::value, \"Huh?\");\n  auto mf2 = transpose(mf) * mf;\n  static_assert(decltype(mf2)::stateless, \"What the dilly?\");\n\n  // std::cout << mf2 << \"\\n\\n\";\n  // Stream2(std::cout, mf2) << \"\\n\\n\";\n\n  BOOST_CHECK_EQUAL(mf2(4), (GetMatrix<2, 2>(1, 0, 0, 1)));\n}\n", "meta": {"hexsha": "b1b7d53cafe3737248eaff322d9cf1c4acd941b4", "size": 1422, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "data/tests/test_matrix.cpp", "max_stars_repo_name": "GuylainGreer/manifolds", "max_stars_repo_head_hexsha": "96f996f67fc523c726f2edbc9705125c212bedae", "max_stars_repo_licenses": ["MIT"], "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/tests/test_matrix.cpp", "max_issues_repo_name": "GuylainGreer/manifolds", "max_issues_repo_head_hexsha": "96f996f67fc523c726f2edbc9705125c212bedae", "max_issues_repo_licenses": ["MIT"], "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/tests/test_matrix.cpp", "max_forks_repo_name": "GuylainGreer/manifolds", "max_forks_repo_head_hexsha": "96f996f67fc523c726f2edbc9705125c212bedae", "max_forks_repo_licenses": ["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.6, "max_line_length": 72, "alphanum_fraction": 0.6455696203, "num_tokens": 496, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.4619871986545828}}
{"text": "#include <eigen_conversions/eigen_msg.h>\n#include <libsbp_ros_msgs/ros_conversion.h>\n#include <piksi_rtk_msgs/PositionSampling.h>\n#include <piksi_rtk_msgs/PositionWithCovarianceStamped.h>\n#include <ros/assert.h>\n#include <Eigen/Dense>\n#include <chrono>\n#include <cstdlib>\n#include <ctime>\n#include <experimental/filesystem>\n#include <fstream>\n#include <iostream>\n#include \"piksi_multi_cpp/sbp_callback_handler/position_sampler.h\"\n\nnamespace piksi_multi_cpp {\n\nnamespace lrm = libsbp_ros_msgs;\nnamespace prm = piksi_rtk_msgs;\nnamespace fs = std::experimental::filesystem;\n\nPositionSampler::PositionSampler(const ros::NodeHandle& nh,\n                                 const std::shared_ptr<sbp_state_t>& state,\n                                 const RosTimeHandler::Ptr& ros_time_handler,\n                                 const GeoTfHandler::Ptr& geotf_handler)\n    : SBPCallbackHandler(SBP_MSG_POS_ECEF_COV, state),\n      nh_(nh),\n      ros_time_handler_(ros_time_handler),\n      geotf_handler_(geotf_handler) {\n  sample_pos_srv_ = nh_.advertiseService(\n      \"sample_position\", &PositionSampler::samplePositionCallback, this);\n}\n\nbool PositionSampler::startSampling(const uint32_t num_desired_fixes,\n                                    const std::string& file, bool set_enu,\n                                    double offset_z) {\n  if (num_desired_fixes < 1) {\n    ROS_ERROR(\n        \"Cannot sample position. num_desired_fixes needs to be greater than \"\n        \"0.\");\n    return false;\n  }\n\n  if (num_desired_fixes_.has_value() && num_fixes_ < num_desired_fixes_) {\n    ROS_WARN(\"Cannot sample position. Sampling already running.\");\n    return false;\n  }\n\n  set_enu_ = set_enu;\n  num_desired_fixes_ = std::optional<uint32_t>(num_desired_fixes);\n  num_fixes_ = 0;\n  offset_z_ = offset_z;\n  file_ = file;\n  x_.reset();\n  P_.reset();\n  y_.reset();\n  R_inv_.reset();\n  x_ml_.reset();\n  P_ml_.reset();\n  ROS_INFO(\"Start position sampling with %u samples.\", num_desired_fixes);\n\n  return true;\n}\n\nbool PositionSampler::getResult(Eigen::Vector3d* x_ecef, Eigen::Matrix3d* cov) {\n  ROS_ASSERT(x_ecef);\n  ROS_ASSERT(cov);\n\n  if (isSampling()) return false;\n\n  *x_ecef = x_ml_.value();\n  *cov = P_ml_.value();\n\n  return true;\n}\n\nbool PositionSampler::samplePositionCallback(\n    piksi_rtk_msgs::SamplePosition::Request& req,\n    piksi_rtk_msgs::SamplePosition::Response& res) {\n  return startSampling(req.num_desired_fixes, req.file, req.set_enu,\n                       req.offset_z);\n}\n\nvoid PositionSampler::callback(uint16_t sender_id, uint8_t len, uint8_t msg[]) {\n  if (!num_desired_fixes_.has_value()) return;\n  if (num_fixes_ >= num_desired_fixes_.value()) return;\n  if (!ros_time_handler_.get()) {\n    ROS_ERROR(\"No time handler set.\");\n    return;\n  }\n\n  // Set least square variables.\n  if (!y_.has_value()) {\n    y_ = Eigen::VectorXd(3 * num_desired_fixes_.value());\n  }\n  if (!R_inv_.has_value()) {\n    R_inv_ = Eigen::MatrixXd::Zero(3 * num_desired_fixes_.value(),\n                                   3 * num_desired_fixes_.value());\n  }\n\n  // Advertise topic on first callback.\n  if (!ml_pos_pub_.has_value()) {\n    ml_pos_pub_ = nh_.advertise<piksi_rtk_msgs::PositionWithCovarianceStamped>(\n        \"position_sampler/ml_position\", kQueueSize, kLatchTopic);\n  }\n  if (!kf_pos_pub_.has_value()) {\n    kf_pos_pub_ = nh_.advertise<piksi_rtk_msgs::PositionWithCovarianceStamped>(\n        \"position_sampler/kf_position\", kQueueSize, kLatchTopic);\n  }\n  if (!info_pub_.has_value()) {\n    info_pub_ = nh_.advertise<piksi_rtk_msgs::PositionSampling>(\n        \"position_sampler/position_sampling\", kQueueSize, kLatchTopic);\n  }\n\n  // Cast message.\n  auto sbp_msg = (msg_pos_ecef_cov_t*)msg;\n  if (!sbp_msg) {\n    ROS_WARN(\"Cannot cast SBP message.\");\n    return;\n  }\n\n  // Check if fix mode is valid.\n  if (((sbp_msg->flags >> 0) && 0x7) == 0) {\n    ROS_WARN_THROTTLE(5, \"Cannot sample position. Fix mode invalid.\");\n    return;\n  }\n\n  // Convert measurement to Eigen.\n  Eigen::Vector3d z;\n  lrm::convertCartesianPoint<msg_pos_ecef_cov_t>(*sbp_msg, &z);\n  Eigen::Matrix3d R;\n  lrm::convertCartesianCov<msg_pos_ecef_cov_t>(*sbp_msg, &R);\n\n  // Subtract offset. Convert from ECEF to WGS84, subtract, convert back.\n  Eigen::Vector3d z_wgs84 = z;\n  if (geotf_handler_.get() &&\n      geotf_handler_->getGeoTf().convert(\"ecef\", z, \"wgs84\", &z_wgs84)) {\n    z_wgs84.z() -= offset_z_;\n  } else {\n    ROS_ERROR(\"Cannot convert ECEF to WGS84.\");\n    ROS_ERROR(\"Ignoring requested sampling offset.\");\n  }\n\n  if (!geotf_handler_.get() ||\n      !geotf_handler_->getGeoTf().convert(\"wgs84\", z_wgs84, \"ecef\", &z)) {\n    ROS_ERROR(\"Cannot convert WGS84 to ECEF.\");\n    ROS_ERROR(\"Ignoring requested sampling offset.\");\n  }\n\n  // Cache least square measurement values.\n  size_t block_idx = 3 * num_fixes_++;\n  y_.value().segment(block_idx, 3) = z;\n  R_inv_.value().block<3, 3>(block_idx, block_idx) = R.inverse();\n\n  // Kalman filter measurement update.\n  if (x_.has_value() && P_.has_value()) {\n    // Innovation.\n    auto y = z - x_.value();\n    auto S = P_.value() + R;\n    // Gain.\n    auto K = P_.value() * S.inverse();\n    // Update.\n    x_.value() += K * y;\n    P_.value() = (Eigen::Matrix3d::Identity() - K) * P_.value();\n  } else {\n    // Initialize.\n    x_ = z;\n    P_ = R;\n  }\n\n  // Logging.\n  ROS_DEBUG_STREAM(\"Measurement: \"\n                   << z.transpose() << \"; 3-sigma bound: \"\n                   << R.eigenvalues().real().cwiseSqrt().transpose()\n                   << \"; temporary mean: \" << x_.value().transpose()\n                   << \"; 3-sigma bound: \"\n                   << P_.value().eigenvalues().real().cwiseSqrt().transpose());\n  publishPosition(kf_pos_pub_.value(), x_.value(), P_.value(), sbp_msg->tow);\n  publishProgress();\n\n  // Compute final least squares solution.\n  if (num_fixes_ >= num_desired_fixes_.value()) {\n    auto H =\n        Eigen::Matrix3d::Identity().replicate(num_desired_fixes_.value(), 1);\n    auto A = H.transpose() * R_inv_.value() * H;\n    auto b = H.transpose() * R_inv_.value() * y_.value();\n    auto dec = A.colPivHouseholderQr();\n    x_ml_ = dec.solve(b);\n    P_ml_ = A.inverse();\n    ROS_INFO_STREAM(\n        \"Finished sampling. ML estimate: \"\n        << x_ml_.value().transpose() << \"; 3-sigma bound: \"\n        << P_ml_.value().eigenvalues().real().cwiseSqrt().transpose());\n    publishPosition(ml_pos_pub_.value(), x_ml_.value(), P_ml_.value(),\n                    sbp_msg->tow);\n    // (Re)Set ENU origin.\n    if (geotf_handler_.get() && set_enu_)\n      geotf_handler_->setEnuOriginEcef(x_ml_.value());\n    set_enu_ = false;\n    // Save to file.\n    ROS_ERROR_COND(\n        !savePositionToFile(x_ml_.value(), P_ml_.value(), num_fixes_),\n        \"Failed to save position to file.\");\n  }\n}\n\nvoid PositionSampler::publishPosition(const ros::Publisher& pub,\n                                      const Eigen::Vector3d& x,\n                                      const Eigen::Matrix3d& cov,\n                                      const uint32_t tow) const {\n  prm::PositionWithCovarianceStamped pos;\n  tf::pointEigenToMsg(x, pos.position.position);\n  typedef Eigen::Matrix<double, 3, 3, Eigen::RowMajor> Matrix3dRow;\n  Matrix3dRow::Map(pos.position.covariance.data()) = cov;\n  pos.header.frame_id = \"ecef\";\n  pos.header.stamp = ros_time_handler_->lookupTime(tow);\n  pub.publish(pos);\n}\n\nvoid PositionSampler::publishProgress() {\n  prm::PositionSampling sampling;\n  if (num_desired_fixes_.has_value() && num_desired_fixes_ > 0) {\n    sampling.progress = 100 * num_fixes_ / num_desired_fixes_.value();\n  } else {\n    sampling.progress = 0xFF;  // Error.\n  }\n  if (info_pub_.has_value()) {\n    info_pub_.value().publish(sampling);\n  }\n}\n\nstd::string PositionSampler::getTimeStr() const {\n  std::time_t now =\n      std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());\n  char buffer[80];\n  std::strftime(buffer, 80, \"%Y-%m-%d-%H-%M-%S\", std::localtime(&now));\n  return std::string(buffer);\n}\n\nbool PositionSampler::savePositionToFile(const Eigen::Vector3d& x,\n                                         const Eigen::Matrix3d& cov,\n                                         const uint32_t num_fixes) const {\n  std::string file = file_;\n  std::string current_time = getTimeStr();\n  if (file.empty()) {\n    // Save to default path.\n    file = std::string(std::getenv(\"HOME\")) + \"/.ros/position_samples/\";\n    file += current_time;\n    file += \"_sampled_position_\";\n    file += nh_.getUnresolvedNamespace();\n    file += \".txt\";\n  }\n  ROS_INFO(\"Saving sampled position to %s\", file.c_str());\n\n  // Create directory recursively.\n  fs::path path = file;\n  if (!fs::exists(path.parent_path())) {\n    if (!fs::create_directories(path.parent_path())) return false;\n  }\n\n  // Convert to common coordinate frames.\n  std::optional<Eigen::Vector3d> x_wgs84;\n  if (geotf_handler_.get()) {\n    Eigen::Vector3d x_wgs84_temp;\n    if (geotf_handler_->getGeoTf().convert(\"ecef\", x, \"wgs84\", &x_wgs84_temp))\n      x_wgs84 = std::make_optional(x_wgs84_temp);\n  }\n\n  std::optional<Eigen::Vector3d> x_enu;\n  if (geotf_handler_.get()) {\n    Eigen::Vector3d x_enu_temp;\n    if (geotf_handler_->getGeoTf().convert(\"ecef\", x, \"enu\", &x_enu_temp))\n      x_enu = std::make_optional(x_enu_temp);\n  }\n\n  std::optional<Eigen::Vector3d> x_enu_origin_wgs84;\n  Eigen::Vector3d x_enu_origin_wgs84_temp;\n  if (geotf_handler_.get() &&\n      geotf_handler_->getEnuOriginWgs84(&x_enu_origin_wgs84_temp)) {\n    x_enu_origin_wgs84 = std::make_optional(x_enu_origin_wgs84_temp);\n  }\n\n  std::fstream fs;\n  fs.open(file, std::fstream::out);\n  if (!fs.is_open()) return false;\n  if (x_wgs84.has_value()) {\n    fs << \"lat_wgs84: \" << boost::lexical_cast<std::string>(x_wgs84.value().x())\n       << std::endl;\n    fs << \"lon_wgs84: \" << boost::lexical_cast<std::string>(x_wgs84.value().y())\n       << std::endl;\n    fs << \"alt_wgs84: \" << boost::lexical_cast<std::string>(x_wgs84.value().z())\n       << std::endl;\n  }\n  if (x_enu.has_value()) {\n    fs << \"x_enu: \" << boost::lexical_cast<std::string>(x_enu.value().x())\n       << std::endl;\n    fs << \"y_enu: \" << boost::lexical_cast<std::string>(x_enu.value().y())\n       << std::endl;\n    fs << \"z_enu: \" << boost::lexical_cast<std::string>(x_enu.value().z())\n       << std::endl;\n  }\n  if (x_enu_origin_wgs84.has_value()) {\n    fs << \"lat_enu_origin_wgs84: \"\n       << boost::lexical_cast<std::string>(x_enu_origin_wgs84.value().x())\n       << std::endl;\n    fs << \"lon_enu_origin_wgs84: \"\n       << boost::lexical_cast<std::string>(x_enu_origin_wgs84.value().y())\n       << std::endl;\n    fs << \"alt_enu_origin_wgs84: \"\n       << boost::lexical_cast<std::string>(x_enu_origin_wgs84.value().z())\n       << std::endl;\n  }\n  fs << \"x_ecef: \" << boost::lexical_cast<std::string>(x.x()) << std::endl;\n  fs << \"y_ecef: \" << boost::lexical_cast<std::string>(x.y()) << std::endl;\n  fs << \"z_ecef: \" << boost::lexical_cast<std::string>(x.z()) << std::endl;\n  fs << \"cov_x_x_ecef: \" << boost::lexical_cast<std::string>(cov(0, 0))\n     << std::endl;\n  fs << \"cov_x_y_ecef: \" << boost::lexical_cast<std::string>(cov(0, 1))\n     << std::endl;\n  fs << \"cov_x_z_ecef: \" << boost::lexical_cast<std::string>(cov(0, 2))\n     << std::endl;\n  fs << \"cov_y_y_ecef: \" << boost::lexical_cast<std::string>(cov(1, 1))\n     << std::endl;\n  fs << \"cov_y_z_ecef: \" << boost::lexical_cast<std::string>(cov(1, 2))\n     << std::endl;\n  fs << \"cov_z_z_ecef: \" << boost::lexical_cast<std::string>(cov(2, 2))\n     << std::endl;\n  fs << \"offset_z: \" << boost::lexical_cast<std::string>(offset_z_)\n     << std::endl;\n  fs << \"num_fixes: \" << boost::lexical_cast<std::string>(num_fixes)\n     << std::endl;\n  fs << \"datetime: \" << boost::lexical_cast<std::string>(current_time)\n     << std::endl;\n  fs.close();\n\n  return true;\n}\n\n}  // namespace piksi_multi_cpp\n", "meta": {"hexsha": "4f6eb3b04eb6fe8a8f46a33d3d38edf08b0bd3c3", "size": 11771, "ext": "cc", "lang": "C++", "max_stars_repo_path": "piksi_multi_cpp/src/sbp_callback_handler/position_sampler.cc", "max_stars_repo_name": "fm-uulm/ethz_piksi_ros", "max_stars_repo_head_hexsha": "a228dc3bfb29266897c2bb38bdfb098ac475ffa0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 65.0, "max_stars_repo_stars_event_min_datetime": "2018-01-03T21:58:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T22:02:33.000Z", "max_issues_repo_path": "piksi_multi_cpp/src/sbp_callback_handler/position_sampler.cc", "max_issues_repo_name": "fm-uulm/ethz_piksi_ros", "max_issues_repo_head_hexsha": "a228dc3bfb29266897c2bb38bdfb098ac475ffa0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 138.0, "max_issues_repo_issues_event_min_datetime": "2017-11-30T15:46:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-22T06:57:53.000Z", "max_forks_repo_path": "piksi_multi_cpp/src/sbp_callback_handler/position_sampler.cc", "max_forks_repo_name": "fm-uulm/ethz_piksi_ros", "max_forks_repo_head_hexsha": "a228dc3bfb29266897c2bb38bdfb098ac475ffa0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 86.0, "max_forks_repo_forks_event_min_datetime": "2017-12-06T19:32:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T17:57:26.000Z", "avg_line_length": 34.7227138643, "max_line_length": 80, "alphanum_fraction": 0.6332512106, "num_tokens": 3404, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.810478926981208, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4618535654555424}}
{"text": "#include \"InverseProblem_Adjoint_YoungsModulus.h\"\n\n#include <Eigen/Dense>\n#include <tinyformat.h>\n#include <cinder/Log.h>\n#include <numeric>\n#include <LBFGS.h>\n#include <fstream>\n\n#include \"GradientDescent.h\"\n#include \"AdjointUtilities.h\"\n\nusing namespace std;\nusing namespace Eigen;\n\n#define DEBUG_SAVE_MATRICES 0\n\n\nnamespace ar {\n\n    InverseProblem_Adjoint_YoungsModulus::InverseProblem_Adjoint_YoungsModulus()\n        : initialYoungsModulus(50)\n        , youngsModulusPrior(0.1)\n        , numIterations(10)\n    {\n    }\n\n    InverseProblemOutput InverseProblem_Adjoint_YoungsModulus::solveGrid(int deformedTimestep,\n        BackgroundWorker* worker, IntermediateResultCallback_t callback)\n    {\n        CI_LOG_I(\"Solve for Young's Modulus at timestep \" << deformedTimestep);\n        // Create simulation\n        worker->setStatus(\"Adjoint - Young's Modulus Grid: create simulation\");\n        SoftBodyGrid2D simulation;\n        simulation.setGridResolution(input->gridResolution_);\n        simulation.setSDF(input->gridReferenceSdf_);\n        simulation.setExplicitDiffusion(true);\n        simulation.setHardDirichletBoundaries(false);\n        simulation.resetBoundaries();\n        for (const auto& b : input->gridDirichletBoundaries_)\n            simulation.addDirichletBoundary(b.first.first, b.first.second, b.second);\n        for (const auto& b : input->gridNeumannBoundaries_)\n            simulation.addNeumannBoundary(b.first.first, b.first.second, b.second);\n        if (worker->isInterrupted()) return InverseProblemOutput();\n\n        // Set parameters with everything that can't be reconstructed here\n        simulation.setGravity(input->settings_.gravity_);\n        simulation.setMass(input->settings_.mass_);\n        simulation.setDamping(input->settings_.dampingAlpha_, input->settings_.dampingBeta_);\n        simulation.setRotationCorrection(SoftBodySimulation::RotationCorrection::None);\n        if (worker->isInterrupted()) return InverseProblemOutput();\n\n        //cost function:\n        //F(youngsModulus) = 0.5*|| disp(youngsModulus) - dispRef ||^2 + priorWeight / youngsModulus\n\n        GridUtils2D::grid_t outputSdf(input->gridResolution_, input->gridResolution_);\n\n\t\t//TODO: once the gradient is fixed, switch to LBFGS\n#if 1\n\t\t//Gradient Descent\n\t\t//define gradient of the cost function\n\t\treal finalCost = 0;\n        const auto gradient = [&simulation, &outputSdf, &finalCost, this, worker, deformedTimestep](const Vector1& youngsModulusV)\n        {\n            real youngsModulus = youngsModulusV.x();\n            real cost;\n            real gradient = gradientGrid(deformedTimestep, simulation, youngsModulus, outputSdf, cost, worker);\n\t\t\tfinalCost = cost;\n            return Vector1(gradient);\n        };\n\t\t//Optimize\n        GradientDescent<Vector1> gd(Vector1(initialYoungsModulus), gradient, 1e-10, 10);\n\t\tgd.setMinStepsize(0.0001);\n\t\tgd.setMaxStepsize(0.5);\n        int oi;\n        for (oi = 0; oi < numIterations; ++oi) {\n            worker->setStatus(tfm::format(\"Adjoint - Young's Modulus Grid: optimization %d/%d\", (oi + 1), numIterations));\n            if (gd.step()) break;\n\n            {\n\t\t\t\tInverseProblemOutput output;\n\t\t\t\toutput.youngsModulus_ = gd.getCurrentSolution()[0];\n\t\t\t\toutput.resultGridSdf_ = outputSdf;\n\t\t\t\toutput.finalCost_ = finalCost;\n\t\t\t\tcallback(output);\n            }\n\n            if (worker->isInterrupted()) return InverseProblemOutput();\n        }\n        real finalValue = gd.getCurrentSolution()[0];\n#else\n\t\t//LBFGS\n\t\tLBFGSpp::LBFGSParam<real> params;\n\t\tparams.epsilon = 1e-10;\n\t\tparams.max_iterations = numIterations;\n\t\tLBFGSpp::LBFGSSolver<real> lbfgs(params);\n\t\t//define gradient\n\t\tLBFGSpp::LBFGSSolver<real>::ObjectiveFunction_t fun([&simulation, &outputSdf, this, worker, deformedTimestep](const VectorX& x, VectorX& gradient) -> real {\n\t\t\treal youngsModulus = x[0];\n\t\t\treal cost;\n\t\t\treal grad = gradientGrid(deformedTimestep, simulation, youngsModulus, outputSdf, cost, worker);\n\t\t\tgradient[0] = grad;\n\t\t\treturn cost;\n\t\t});\n\t\tLBFGSpp::LBFGSSolver<real>::CallbackFunction_t lbfgsCallback([worker, callback, &outputSdf, this](const VectorX& x, const real& v, int k) -> bool {\n\t\t\tworker->setStatus(tfm::format(\"Adjoint - Young's Modulus: optimization %d/%d\", k, numIterations));\n\n\t\t\tInverseProblemOutput output;\n\t\t\toutput.youngsModulus_ = x[0];\n\t\t\toutput.resultGridSdf_ = outputSdf;\n\t\t\toutput.finalCost_ = v;\n\t\t\tcallback(output);\n\n\t\t\treturn !worker->isInterrupted();\n\t\t});\n\t\t//optimize\n\t\treal finalCost = 0;\n\t\tVectorX finalValueV = VectorX::Constant(1, initialYoungsModulus);\n\t\tint oi = lbfgs.minimize(fun, finalValueV, finalCost, lbfgsCallback);\n\t\tif (worker->isInterrupted()) return InverseProblemOutput();\n\t\treal finalValue = finalValueV[0];\n#endif\n        CI_LOG_I(\"Optimization: final Youngs' Modulus is \" << finalValue << \" after \" << oi << \" optimization steps, reference value is \" << input->settings_.youngsModulus_);\n\n        InverseProblemOutput output;\n        output.youngsModulus_ = finalValue;\n        output.resultGridSdf_ = outputSdf;\n\t\toutput.finalCost_ = finalCost;\n        return output;\n    }\n\n    InverseProblemOutput InverseProblem_Adjoint_YoungsModulus::solveMesh(int deformedTimestep,\n        BackgroundWorker* worker, IntermediateResultCallback_t callback)\n    {\n        CI_LOG_I(\"Solve for Young's Modulus at timestep \" << deformedTimestep);\n        // Create simulation\n        worker->setStatus(\"Adjoint - Young's Modulus: create simulation\");\n        SoftBodyMesh2D simulation;\n        simulation.setMesh(input->meshReferencePositions_, input->meshReferenceIndices_);\n        simulation.resetBoundaries();\n        for (const auto& b : input->meshDirichletBoundaries_)\n            simulation.addDirichletBoundary(b.first, b.second);\n        for (const auto& b : input->meshNeumannBoundaries_)\n            simulation.addNeumannBoundary(b.first, b.second);\n        simulation.reorderNodes();\n        if (worker->isInterrupted()) return InverseProblemOutput();\n\n        // Set parameters with everything that can't be reconstructed here\n        simulation.setGravity(input->settings_.gravity_);\n        simulation.setMass(input->settings_.mass_);\n        simulation.setDamping(input->settings_.dampingAlpha_, input->settings_.dampingBeta_);\n        simulation.setRotationCorrection(SoftBodySimulation::RotationCorrection::None);\n        if (worker->isInterrupted()) return InverseProblemOutput();\n\n        //cost function:\n        //F(youngsModulus) = 0.5*|| disp(youngsModulus) - dispRef ||^2 + priorWeight / youngsModulus\n\n\t\tVectorX outputU;\n#if 0\n\t\t//Gradient Descent\n        //define gradient of the cost function\n        const auto gradient = [&simulation, &outputU, this, worker, deformedTimestep](const Vector1& youngsModulusV)\n        {\n            real youngsModulus = youngsModulusV.x();\n            real cost;\n            real gradient = gradientMesh(deformedTimestep, simulation, youngsModulus, outputU, cost, worker);\n            return Vector1(gradient);\n        };\n\n        //run optimization\n        GradientDescent<Vector1> gd(Vector1(initialYoungsModulus), gradient, 1e-10, 10);\n        int oi;\n        for (oi = 0; oi < numIterations; ++oi) {\n            worker->setStatus(tfm::format(\"Adjoint - Young's Modulus: optimization %d/%d\", (oi + 1), numIterations));\n            if (gd.step()) break;\n            if (worker->isInterrupted()) return InverseProblemOutput();\n        }\n        real finalValue = gd.getCurrentSolution()[0];\n#else\n\t\t//LBFGS\n\t\tLBFGSpp::LBFGSParam<real> params;\n\t\tparams.epsilon = 1e-15;\n\t\tparams.max_iterations = numIterations;\n\t\tLBFGSpp::LBFGSSolver<real> lbfgs(params);\n\t\t//define gradient\n\t\tLBFGSpp::LBFGSSolver<real>::ObjectiveFunction_t fun([&simulation, &outputU, this, worker, deformedTimestep](const VectorX& x, VectorX& gradient) -> real {\n\t\t\treal youngsModulus = x[0];\n\t\t\treal cost;\n\t\t\treal grad = gradientMesh(deformedTimestep, simulation, youngsModulus, outputU, cost, worker);\n\t\t\tgradient[0] = grad;\n\t\t\treturn cost;\n\t\t});\n\t\tLBFGSpp::LBFGSSolver<real>::CallbackFunction_t lbfgsCallback([worker, &simulation, &outputU, callback, this](const VectorX& x, const VectorX& g, const real& v, int k) -> bool {\n\t\t\tworker->setStatus(tfm::format(\"Adjoint - Young's Modulus: optimization %d/%d\", k, numIterations));\n\n\t\t\tInverseProblemOutput output;\n\t\t\toutput.youngsModulus_ = x[0];\n\t\t\toutput.resultMeshDisp_ = SoftBodyMesh2D::Vector2List(simulation.getNumNodes());\n\t\t\tfor (int i = 0; i<simulation.getNumNodes(); ++i)\n\t\t\t{\n\t\t\t\tif (simulation.getNodeToFreeMap()[i] < 0)\n\t\t\t\t\toutput.resultMeshDisp_->at(i).setZero();\n\t\t\t\telse\n\t\t\t\t\toutput.resultMeshDisp_->at(i) = outputU.segment<2>(2 * simulation.getNodeToFreeMap()[i]);\n\t\t\t}\n\t\t\toutput.finalCost_ = v;\n\t\t\tcallback(output);\n\n\t\t\treturn !worker->isInterrupted();\n\t\t});\n\t\t//optimize\n\t\treal finalCost = 0;\n\t\tVectorX finalValueV = VectorX::Constant(1, initialYoungsModulus);\n\t\tint oi = lbfgs.minimize(fun, finalValueV, finalCost, lbfgsCallback);\n\t\tif (worker->isInterrupted()) return InverseProblemOutput();\n\t\treal finalValue = finalValueV[0];\n#endif\n        CI_LOG_I(\"Optimization: final Youngs' Modulus is \" << finalValue << \" after \" << oi << \" optimization steps, reference value is \" << input->settings_.youngsModulus_);\n\n        InverseProblemOutput output;\n        output.youngsModulus_ = finalValue;\n        output.resultMeshDisp_ = SoftBodyMesh2D::Vector2List(simulation.getNumNodes());\n        for (int i=0; i<simulation.getNumNodes(); ++i)\n        {\n            if (simulation.getNodeToFreeMap()[i] < 0)\n                output.resultMeshDisp_->at(i).setZero();\n            else\n                output.resultMeshDisp_->at(i) = outputU.segment<2>(2 * simulation.getNodeToFreeMap()[i]);\n        }\n\t\toutput.finalCost_ = finalCost;\n        return output;\n    }\n\n    real InverseProblem_Adjoint_YoungsModulus::gradientMesh(\n        int deformedTimestep, const SoftBodyMesh2D& simulation,\n        real youngsModulus, VectorX& outputU, real& outputCost, BackgroundWorker* worker) const\n    {\n        real poissonsRatio = input->settings_.poissonsRatio_;\n\n        //FORWARD\n\n        MatrixX K = MatrixX::Zero(2 * simulation.getNumFreeNodes(), 2 * simulation.getNumFreeNodes());\n        VectorX F = VectorX::Zero(2 * simulation.getNumFreeNodes());\n\n        //assemble force vector F and stiffness matrix K\n        simulation.assembleForceVector(F);\n        if (worker->isInterrupted()) return 0;\n        real materialMu, materialLambda;\n        SoftBodySimulation::computeMaterialParameters(youngsModulus, poissonsRatio, materialMu, materialLambda);\n        Matrix3 C = SoftBodySimulation::computeMaterialMatrix(materialMu, materialLambda);\n        simulation.assembleStiffnessMatrix(C, K, &F, SoftBodyMesh2D::Vector2List(simulation.getNumNodes(), Vector2::Zero()));\n        if (worker->isInterrupted()) return 0;\n#if DEBUG_SAVE_MATRICES==1\n        saveAsCSV(K, tfm::format(\"AdjointYoung-GradientMesh-K-k%f.csv\", youngsModulus));\n#endif\n\n        //assemble derivate of matrix K with respect to the youngsModulus\n        MatrixX KDyoung = MatrixX::Zero(2 * simulation.getNumFreeNodes(), 2 * simulation.getNumFreeNodes());\n        real muDyoung, lambdaDyoung;\n        AdjointUtilities::computeMaterialParameters_D_YoungsModulus(youngsModulus, poissonsRatio, muDyoung, lambdaDyoung);\n        Matrix3 CDyoung = SoftBodySimulation::computeMaterialMatrix(muDyoung, lambdaDyoung);\n        simulation.assembleStiffnessMatrix(CDyoung, KDyoung, nullptr, SoftBodyMesh2D::Vector2List(simulation.getNumNodes(), Vector2::Zero()));\n#if DEBUG_SAVE_MATRICES==1\n        saveAsCSV(KDyoung, tfm::format(\"AdjointYoung-GradientMesh-KDyoung-k%f.csv\", youngsModulus));\n#endif\n\n        //solve for the current displacement\n        PartialPivLU<MatrixX> Klu = K.partialPivLu();\n        VectorX u = Klu.solve(F);\n        outputU = u;\n\n        //compute the partial gradient of the operations with respect to Young's Modulus\n        VectorX EDyoung = -KDyoung * u;\n        //VectorX EDyoung = Klu.solve(-KDyoung * u);\n\n        // BACKWARD\n\n        //compute derivate of the cost function with respect to the output u (displacement)\n        VectorX costDu(2 * simulation.getNumFreeNodes());\n        for (int i = 0; i < simulation.getNumNodes(); ++i)\n        {\n            if (simulation.getNodeToFreeMap()[i] < 0) continue;\n            costDu.segment<2>(2 * simulation.getNodeToFreeMap()[i])\n                = u.segment<2>(2 * simulation.getNodeToFreeMap()[i])\n                - input->meshResultsDisplacement_[deformedTimestep][i];\n        }\n#if DEBUG_SAVE_MATRICES==1\n        saveAsCSV(costDu, tfm::format(\"AdjointYoung-GradientMesh-costDu-k%f.csv\", youngsModulus));\n#endif\n\n        //solve for the dual\n        //In theory, I have to use K', but because I know that K is symmetric,\n        //I can use K directly and not the transpose.\n        VectorX lambda = Klu.solve(costDu);\n\n        //compute gradient of the prior term\n        real priorDyoung = -youngsModulusPrior / (youngsModulus*youngsModulus);\n\n        //evalue the final gradient\n        real gradient = lambda.transpose() * EDyoung + priorDyoung;\n\n        //For testing: evaluate cost\n        real cost = youngsModulusPrior / youngsModulus;\n        for (int i = 0; i < simulation.getNumNodes(); ++i)\n        {\n            if (simulation.getNodeToFreeMap()[i] < 0) continue;\n            cost += (u.segment<2>(2 * simulation.getNodeToFreeMap()[i])\n                - input->meshResultsDisplacement_[deformedTimestep][i]).squaredNorm() / 2;\n        }\n        outputCost = cost;\n        CI_LOG_I(\"Optimization: Youngs Modulus \" << youngsModulus << \" -> cost \" << cost << \", gradient \" << gradient);\n\n        return gradient;\n    }\n\n    real InverseProblem_Adjoint_YoungsModulus::gradientGrid(int deformedTimestep, const SoftBodyGrid2D& simulation,\n        real youngsModulus, GridUtils2D::grid_t& outputSdf, real& outputCost, BackgroundWorker* worker) const\n    {\n        real poissonsRatio = input->settings_.poissonsRatio_;\n\n        //FORWARD\n        int resolution = input->gridResolution_;\n        real h = 1.0 / (resolution - 1);\n        Vector2 pos(0, 0); //lower left corner of the grid\n        Vector2 size(h, h); //size of each cell\n\n\t\t//collect degrees of freedom in the stifness solve\n\t\tconst Eigen::MatrixXi& posToIndex = simulation.getPosToIndex();\n\t\tconst SoftBodyGrid2D::indexToPos_t& indexToPos = simulation.getIndexToPos();\n\t\tconst int dof = simulation.getDoF();\n\n        MatrixX K = MatrixX::Zero(dof * 2, dof * 2);\n        VectorX f = VectorX::Zero(dof * 2);\n\t\tconst VectorX prevU = VectorX::Zero(dof * 2); //previous displacements for rotation correction. Not needed here\n\n        //assemble force vector F and stiffness matrix K\n\t\tVectorX collisionForces = VectorX::Zero(2 * dof);\n        simulation.assembleForceVector(f, posToIndex, collisionForces);\n        if (worker->isInterrupted()) return 0;\n        real materialMu, materialLambda;\n        SoftBodySimulation::computeMaterialParameters(youngsModulus, poissonsRatio, materialMu, materialLambda);\n        Matrix3 C = SoftBodySimulation::computeMaterialMatrix(materialMu, materialLambda);\n        simulation.assembleStiffnessMatrix(C, materialMu, materialLambda, K, &f, posToIndex, prevU);\n        if (worker->isInterrupted()) return 0;\n#if DEBUG_SAVE_MATRICES==1\n        saveAsCSV(K, tfm::format(\"AdjointYoung-GradientGrid-K-k%f.csv\", youngsModulus));\n#endif\n\n        //assemble derivate of matrix K with respect to the youngsModulus\n        MatrixX KDyoung = MatrixX::Zero(dof * 2, dof * 2);\n        real muDyoung, lambdaDyoung;\n\t\tAdjointUtilities::computeMaterialParameters_D_YoungsModulus(youngsModulus, poissonsRatio, muDyoung, lambdaDyoung);\n        Matrix3 CDyoung = SoftBodySimulation::computeMaterialMatrix(muDyoung, lambdaDyoung);\n        simulation.assembleStiffnessMatrix(CDyoung, muDyoung, lambdaDyoung, KDyoung, nullptr, posToIndex, prevU);\n        if (worker->isInterrupted()) return 0;\n#if DEBUG_SAVE_MATRICES==1\n        saveAsCSV(KDyoung, tfm::format(\"AdjointYoung-GradientGrid-KDyoung-k%f.csv\", youngsModulus));\n#endif\n\n        //solve for the current displacement\n        PartialPivLU<MatrixX> Klu = K.partialPivLu();\n        VectorX solution = Klu.solve(f);\n        if (worker->isInterrupted()) return 0;\n        \n        //map back to a grid\n        SoftBodyGrid2D::grid_t uGridX = SoftBodyGrid2D::grid_t::Zero(resolution, resolution);\n        SoftBodyGrid2D::grid_t uGridY = SoftBodyGrid2D::grid_t::Zero(resolution, resolution);\n        for (int i = 0; i < dof; ++i) {\n            Vector2i p = indexToPos.at(i);\n            uGridX(p.x(), p.y()) = solution[2 * i];\n            uGridY(p.x(), p.y()) = solution[2 * i + 1];\n        }\n        if (worker->isInterrupted()) return 0;\n\n        //perform diffusion step\n        GridUtils2D::bgrid_t validCells = simulation.computeValidCells(uGridX, uGridY, posToIndex);\n        uGridX = GridUtils2D::fillGridDiffusion(uGridX, validCells);\n        uGridY = GridUtils2D::fillGridDiffusion(uGridY, validCells);\n        if (worker->isInterrupted()) return 0;\n\n#if 0\n        //invert displacements\n        SoftBodyGrid2D::grid_t uGridInvX = SoftBodyGrid2D::grid_t::Zero(resolution, resolution);\n        SoftBodyGrid2D::grid_t uGridInvY = SoftBodyGrid2D::grid_t::Zero(resolution, resolution);\n        GridUtils2D::invertDisplacement(uGridX, uGridY, uGridInvX, uGridInvY, h);\n        if (worker->isInterrupted()) return 0;\n\n        //advect levelset\n        outputSdf = GridUtils2D::advectGridSemiLagrange(input->gridReferenceSdf_, uGridInvX, uGridInvY, -1 / h);\n        if (worker->isInterrupted()) return 0;\n#else\n        //advect levelset\n\t\tGridUtils2D::grid_t advectionWeights(resolution, resolution);\n        outputSdf = GridUtils2D::advectGridDirectForward(input->gridReferenceSdf_, uGridX, uGridY, -1 / h, &advectionWeights);\n        if (worker->isInterrupted()) return 0;\n#endif\n\n        //compute the partial gradient of the operations with respect to Young's Modulus\n        VectorX EDyoung = -KDyoung * solution;\n        //VectorX EDyoung = Klu.solve(-KDyoung * solution);\n        if (worker->isInterrupted()) return 0;\n\n        // BACKWARD\n\n#if 1\n        //compute derivate of the cost function with respect to the output u (displacement)\n        //SoftBodyGrid2D::grid_t costDu = outputSdf - input->gridResultsSdf_[deformedTimestep];\n        SoftBodyGrid2D::grid_t costDu =\n            (2 * ((2 / M_PI)*outputSdf.atan() - (2 / M_PI)*input->gridResultsSdf_[deformedTimestep].atan())) /\n            (M_PI * (1 + outputSdf.square()));\n\n#if 0\n        //Adjoint: advect levelset\n        SoftBodyGrid2D::grid_t adjInputSdf = SoftBodyGrid2D::grid_t::Zero(resolution, resolution);\n        SoftBodyGrid2D::grid_t adjUGridInvX = SoftBodyGrid2D::grid_t::Zero(resolution, resolution);\n        SoftBodyGrid2D::grid_t adjUGridInvY = SoftBodyGrid2D::grid_t::Zero(resolution, resolution);\n        GridUtils2D::advectGridSemiLagrangeAdjoint(\n            adjInputSdf, adjUGridInvX, adjUGridInvY, -1 / h, costDu,\n            uGridInvX, uGridInvY, input->gridReferenceSdf_);\n        if (worker->isInterrupted()) return 0;\n\n        //Adjoint: invert levelset\n        SoftBodyGrid2D::grid_t adjUGridX = SoftBodyGrid2D::grid_t::Zero(resolution, resolution);\n        SoftBodyGrid2D::grid_t adjUGridY = SoftBodyGrid2D::grid_t::Zero(resolution, resolution);\n        GridUtils2D::invertDisplacementDirectShepardAdjoint(\n            adjUGridX, adjUGridY, adjUGridInvX, adjUGridInvY, \n            uGridX, uGridY, uGridInvX, uGridInvY, h);\n        if (worker->isInterrupted()) return 0;\n#else\n        SoftBodyGrid2D::grid_t adjInputSdf = SoftBodyGrid2D::grid_t::Zero(resolution, resolution);\n        SoftBodyGrid2D::grid_t adjUGridX = SoftBodyGrid2D::grid_t::Zero(resolution, resolution);\n        SoftBodyGrid2D::grid_t adjUGridY = SoftBodyGrid2D::grid_t::Zero(resolution, resolution);\n        GridUtils2D::advectGridDirectForwardAdjoint(adjInputSdf, adjUGridX, adjUGridY, \n            costDu, uGridX, uGridY, input->gridReferenceSdf_, outputSdf, -1 / h, advectionWeights);\n        if (worker->isInterrupted()) return 0;\n#endif\n\n        //Adjoint: perform diffusion step\n        GridUtils2D::fillGridDiffusionAdjoint(adjUGridX, adjUGridX, uGridX, validCells); //note that the adjoint is both input and output\n        GridUtils2D::fillGridDiffusionAdjoint(adjUGridY, adjUGridY, uGridY, validCells); //it is modified in-place\n        if (worker->isInterrupted()) return 0;\n\n        //Adjoint: map back to a grid\n        VectorX adjSolution(2 * dof);\n        for (int i = 0; i < dof; ++i) {\n            Vector2i p = indexToPos.at(i);\n            adjSolution[2 * i] = adjUGridX(p.x(), p.y());\n            adjSolution[2 * i + 1] = adjUGridY(p.x(), p.y());\n        }\n        if (worker->isInterrupted()) return 0;\n\n        //Adjoint: solve for the current displacement\n        //since K is symmetric, I can use K directly instead of K' as normally required by the Adjoint Method.\n        VectorX lambda = Klu.solve(adjSolution);\n        if (worker->isInterrupted()) return 0;\n\n#else\n        //Recompute inverted true solution\n        SoftBodyGrid2D::grid_t gridResultsInvUx = SoftBodyGrid2D::grid_t::Zero(resolution, resolution);\n        SoftBodyGrid2D::grid_t gridResultsInvUy = SoftBodyGrid2D::grid_t::Zero(resolution, resolution);\n        GridUtils2D::invertDisplacementDirectShepard(\n            input->gridResultsUx_[deformedTimestep], input->gridResultsUy_[deformedTimestep],\n            gridResultsInvUx, gridResultsInvUy, h);\n\n        //Reduced problem only on the levelset\n        SoftBodyGrid2D::grid_t adjUGridInvX = uGridInvX - gridResultsInvUx;\n        SoftBodyGrid2D::grid_t adjUGridInvY = uGridInvY - gridResultsInvUy;\n\n        //Adjoint: invert levelset\n        SoftBodyGrid2D::grid_t adjUGridX = SoftBodyGrid2D::grid_t::Zero(resolution, resolution);\n        SoftBodyGrid2D::grid_t adjUGridY = SoftBodyGrid2D::grid_t::Zero(resolution, resolution);\n        GridUtils2D::invertDisplacementDirectShepardAdjoint(\n            adjUGridX, adjUGridY, adjUGridInvX, adjUGridInvY,\n            uGridX, uGridY, uGridInvX, uGridInvY, h);\n        if (worker->isInterrupted()) return 0;\n\n        //Adjoint: perform diffusion step\n        GridUtils2D::fillGridDiffusionAdjoint(adjUGridX, adjUGridX, uGridX, validCells); //note that the adjoint is both input and output\n        GridUtils2D::fillGridDiffusionAdjoint(adjUGridY, adjUGridY, uGridY, validCells); //it is modified in-place\n        if (worker->isInterrupted()) return 0;\n\n        //Adjoint: map back to a grid\n        VectorX adjSolution(2 * dof);\n        for (int i = 0; i < dof; ++i) {\n            Vector2i p = indexToPos[i];\n            adjSolution[2 * i] = adjUGridX(p.x(), p.y());\n            adjSolution[2 * i + 1] = adjUGridY(p.x(), p.y());\n        }\n        if (worker->isInterrupted()) return 0;\n#if DEBUG_SAVE_MATRICES==1\n        saveAsCSV(adjSolution, tfm::format(\"AdjointYoung-GradientGrid-costDu-k%f.csv\", youngsModulus));\n#endif\n\n        //Adjoint: solve for the current displacement\n        //since K is symmetric, I can use K directly instead of K' as normally required by the Adjoint Method.\n        VectorX lambda = -Klu.solve(adjSolution);\n        if (worker->isInterrupted()) return 0;\n#endif\n\n        //Done with the adjoint computation\n        //Now I can assemble the final gradient\n\n        //compute gradient of the prior term\n        real priorDyoung = -youngsModulusPrior / (youngsModulus*youngsModulus);\n\n        //evalue the final gradient\n        real gradient = -lambda.transpose() * EDyoung + priorDyoung;\n\n        //For testing: evaluate cost\n#if 1\n        real cost = youngsModulusPrior / youngsModulus\n            + ((2/M_PI)*outputSdf.atan() - (2/M_PI)*input->gridResultsSdf_[deformedTimestep].atan()).matrix().squaredNorm() / 2;\n#else\n        //reduced problem\n        real cost = (uGridInvX - gridResultsInvUx).matrix().squaredNorm() / 2 +\n                    (uGridInvY - gridResultsInvUy).matrix().squaredNorm() / 2;\n#endif\n        outputCost = cost;\n        CI_LOG_I(\"Optimization: Youngs Modulus \" << youngsModulus << \" -> cost \" << cost << \", gradient \" << gradient);\n\n        return gradient;\n    }\n\n    void InverseProblem_Adjoint_YoungsModulus::setupParams(cinder::params::InterfaceGlRef params,\n        const std::string& group)\n    {\n        params->addParam(\"InverseProblem_Adjoint_YoungsModulus_InitialYoungsModulus\", &initialYoungsModulus)\n            .group(group).label(\"Initial Young's Modulus\").min(0).step(0.01f);\n        params->addParam(\"InverseProblem_Adjoint_YoungsModulus_YoungsModulusPrior\", &youngsModulusPrior)\n            .group(group).label(\"Prior on Young's Modulus\").min(0).step(0.01f);\n        params->addParam(\"InverseProblem_Adjoint_YoungsModulus_NumIterations\", &numIterations)\n            .group(group).label(\"Iterations\").min(1);\n    }\n\n    void InverseProblem_Adjoint_YoungsModulus::setParamsVisibility(cinder::params::InterfaceGlRef params,\n        bool visible) const\n    {\n        std::string option = visible ? \"visible=true\" : \"visible=false\";\n        params->setOptions(\"InverseProblem_Adjoint_YoungsModulus_InitialYoungsModulus\", option);\n        params->setOptions(\"InverseProblem_Adjoint_YoungsModulus_YoungsModulusPrior\", option);\n        params->setOptions(\"InverseProblem_Adjoint_YoungsModulus_NumIterations\", option);\n    }\n\n    std::vector<InverseProblem_Adjoint_YoungsModulus::DataPoint> InverseProblem_Adjoint_YoungsModulus::plotEnergy(int deformedTimestep, BackgroundWorker * worker) const\n    {\n        //control points\n        real trueYoung = input->settings_.youngsModulus_;\n        real minYoung = trueYoung / 4;\n        real maxYoung = trueYoung + (trueYoung - minYoung);\n        int steps = 25; // has to be odd\n        std::vector<DataPoint> points(steps);\n        for (int i = 0; i < steps; ++i)\n            points[i].youngsModulus = minYoung + (maxYoung - minYoung) * i / (steps - 1.0);\n\n        // Create grid simulation\n        worker->setStatus(\"Test Plot Grid: create simulation\");\n        SoftBodyGrid2D simulationGrid;\n        simulationGrid.setGridResolution(input->gridResolution_);\n        simulationGrid.setSDF(input->gridReferenceSdf_);\n        simulationGrid.setExplicitDiffusion(true);\n        simulationGrid.setHardDirichletBoundaries(false);\n        simulationGrid.resetBoundaries();\n        for (const auto& b : input->gridDirichletBoundaries_)\n            simulationGrid.addDirichletBoundary(b.first.first, b.first.second, b.second);\n        for (const auto& b : input->gridNeumannBoundaries_)\n            simulationGrid.addNeumannBoundary(b.first.first, b.first.second, b.second);\n        simulationGrid.setGravity(input->settings_.gravity_);\n        simulationGrid.setMass(input->settings_.mass_);\n        simulationGrid.setDamping(input->settings_.dampingAlpha_, input->settings_.dampingBeta_);\n        simulationGrid.setRotationCorrection(input->settings_.rotationCorrection_);\n\n        //Run grid simulation\n        GridUtils2D::grid_t outputGrid;\n        for (int i = 0; i < steps; ++i)\n        {\n            worker->setStatus(tfm::format(\"Test Plot Grid: simulation %d/%d\",i+1,steps));\n            real cost;\n            real gradient = gradientGrid(deformedTimestep, simulationGrid, points[i].youngsModulus, outputGrid, cost, worker);\n            if (worker->isInterrupted()) return {};\n            points[i].costGrid = cost;\n            points[i].gradientGrid = gradient;\n        }\n\n        //Create mesh simulation\n        worker->setStatus(\"Test Plot Mesh: create simulation\");\n        SoftBodyMesh2D simulationMesh;\n        simulationMesh.setMesh(input->meshReferencePositions_, input->meshReferenceIndices_);\n        simulationMesh.resetBoundaries();\n        for (const auto& b : input->meshDirichletBoundaries_)\n            simulationMesh.addDirichletBoundary(b.first, b.second);\n        for (const auto& b : input->meshNeumannBoundaries_)\n            simulationMesh.addNeumannBoundary(b.first, b.second);\n        simulationMesh.reorderNodes();\n        simulationMesh.setGravity(input->settings_.gravity_);\n        simulationMesh.setMass(input->settings_.mass_);\n        simulationMesh.setDamping(input->settings_.dampingAlpha_, input->settings_.dampingBeta_);\n        simulationMesh.setRotationCorrection(input->settings_.rotationCorrection_);\n\n        //Run mesh simulation\n        VectorX outputMesh;\n        for (int i = 0; i < steps; ++i)\n        {\n            worker->setStatus(tfm::format(\"Test Plot Mesh: simulation %d/%d\", i + 1, steps));\n            real cost;\n            real gradient = gradientMesh(deformedTimestep, simulationMesh, points[i].youngsModulus, outputMesh, cost, worker);\n            if (worker->isInterrupted()) return {};\n            points[i].costMesh = cost;\n            points[i].gradientMesh = gradient;\n        }\n\n        return points;\n    }\n\n\tvoid InverseProblem_Adjoint_YoungsModulus::testPlot(int deformedTimestep, BackgroundWorker* worker)\n\t{\n\t\tauto points = plotEnergy(deformedTimestep-1, worker);\n\t\tif (worker->isInterrupted()) return;\n\t\tfstream file(\"../plots/Adjoint-YoungsModulus.csv\", fstream::out | fstream::trunc);\n\t\tfile << \"Youngs Modulus , Cost Mesh , Gradient Mesh , Cost Grid , Gradient Grid\" << endl;\n\t\tfile << std::fixed;\n\t\tfor (auto point : points)\n\t\t{\n\t\t\tfile << point.youngsModulus << \" , \"\n\t\t\t\t<< point.costMesh << \" , \" << point.gradientMesh << \" , \"\n\t\t\t\t<< point.costGrid << \" , \" << point.gradientGrid << endl;\n\t\t}\n\t\tfile.close();\n\t}\n\n}\n", "meta": {"hexsha": "7029c66d32fd9f4ecf0867cfc2a1c4f396240cc1", "size": 29406, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ActionReconstructionLib/InverseProblem_Adjoint_YoungsModulus.cpp", "max_stars_repo_name": "shamanDevel/SparseSurfaceConstraints", "max_stars_repo_head_hexsha": "88357ff847369a45b9f16f9f44159196138f9147", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2020-03-08T18:28:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T20:32:56.000Z", "max_issues_repo_path": "ActionReconstructionLib/InverseProblem_Adjoint_YoungsModulus.cpp", "max_issues_repo_name": "shamanDevel/SparseSurfaceConstraints", "max_issues_repo_head_hexsha": "88357ff847369a45b9f16f9f44159196138f9147", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ActionReconstructionLib/InverseProblem_Adjoint_YoungsModulus.cpp", "max_forks_repo_name": "shamanDevel/SparseSurfaceConstraints", "max_forks_repo_head_hexsha": "88357ff847369a45b9f16f9f44159196138f9147", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-03-26T01:54:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-18T13:32:46.000Z", "avg_line_length": 46.6022187005, "max_line_length": 178, "alphanum_fraction": 0.6783649595, "num_tokens": 7778, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4618535550210357}}
{"text": "// #include <map>\n// #include <string>\n// #include <Eigen/Dense>\n// #include \"simple_layer.h\"\n// #include \"simple_mlp.h\"\n\n// namespace MyDL{\n\n//     using namespace Eigen;\n\n//     TwoLayerNetwork::TwoLayerNetwork(int input_size, int hidden_size, int output_size, double weight_init_std){\n//         _input_size = input_size;\n//         _hidden_size = hidden_size;\n//         _output_size = output_size;\n\n//         _params[\"W1\"] = weight_init_std * MatrixXd::Random(input_size, hidden_size);\n//         _params[\"b1\"] = VectorXd::Zero(hidden_size);\n//         _params[\"W2\"] = weight_init_std * MatrixXd::Random(hidden_size, output_size);\n//         _params[\"b1\"] = VectorXd::Zero(output_size);\n\n        \n//     }\n\n//     MatrixXd TwoLayerNetwork::predict(MatrixXd& X){\n\n//     }\n\n\n\n// }", "meta": {"hexsha": "8a46f430cb1de17779ca1bf320b1ed1629651271", "size": 785, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "simple_lib/src/simple_mlp.cpp", "max_stars_repo_name": "potedo/zeroDL_cpp", "max_stars_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-22T15:26:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-22T15:26:20.000Z", "max_issues_repo_path": "simple_lib/src/simple_mlp.cpp", "max_issues_repo_name": "potedo/zeroDL_cpp", "max_issues_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "simple_lib/src/simple_mlp.cpp", "max_forks_repo_name": "potedo/zeroDL_cpp", "max_forks_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_forks_repo_licenses": ["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.1666666667, "max_line_length": 114, "alphanum_fraction": 0.625477707, "num_tokens": 202, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4618535550210357}}
{"text": "\n\n#include <deal.II/base/conditional_ostream.h>\n#include <deal.II/base/function.h>\n#include <deal.II/base/index_set.h>\n#include <deal.II/base/logstream.h>\n#include <deal.II/base/parameter_handler.h>\n#include <deal.II/base/quadrature_lib.h>\n#include <deal.II/base/tensor_function.h>\n#include <deal.II/base/timer.h>\n#include <deal.II/base/utilities.h>\n\n#include <deal.II/lac/generic_linear_algebra.h>\nnamespace LA {\nusing namespace dealii::LinearAlgebraPETSc;\n#define USE_PETSC_LA\n} // namespace LA\n\n#include <deal.II/lac/dynamic_sparsity_pattern.h>\n#include <deal.II/lac/full_matrix.h>\n#include <deal.II/lac/vector.h>\n//#include <deal.II/lac/sparse_matrix.h>\n#include <deal.II/lac/constraint_matrix.h>\n#include <deal.II/lac/precondition.h>\n#include <deal.II/lac/solver_bicgstab.h>\n#include <deal.II/lac/solver_cg.h>\n#include <deal.II/lac/sparsity_tools.h>\n//#include <deal.II/lac/petsc_precondition.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\n#include <deal.II/dofs/dof_accessor.h>\n#include <deal.II/dofs/dof_handler.h>\n#include <deal.II/dofs/dof_tools.h>\n#include <deal.II/dofs/dof_renumbering.h>\n\n#include <deal.II/fe/fe_dgq.h>\n#include <deal.II/fe/fe_q.h>\n#include <deal.II/fe/fe_values.h>\n#include <deal.II/fe/fe_system.h>\n\n#include <deal.II/numerics/data_out.h>\n#include <deal.II/numerics/error_estimator.h>\n#include <deal.II/numerics/vector_tools.h>\n//#include <deal.II/numerics/solution_transfer.h>\n//#include <deal.II/numerics/matrix_tools.h>\n\n#include <deal.II/lac/petsc_parallel_sparse_matrix.h>\n#include <deal.II/lac/petsc_parallel_vector.h>\n#include <deal.II/lac/petsc_precondition.h>\n#include <deal.II/lac/petsc_solver.h>\n\n#include <deal.II/distributed/grid_refinement.h>\n#include <deal.II/distributed/tria.h>\n#include <deal.II/grid/filtered_iterator.h>\n\n#include <fstream>\n#include <iostream>\n#include <functional>\n\n#include \"level_set_solver.h\"\n#include \"material_data.h\"\n#include \"my_utility_functions.h\"\n#include \"parameters.h\"\n#include \"physical_functions.h\"\n\nnamespace CPPLS {\nusing namespace dealii;\n\n\ntemplate <int dim>\nclass LayerMovementProblem {\npublic:\n    LayerMovementProblem(const CPPLS::Parameters& parameters, const CPPLS::MaterialData& material_data);\n    ~LayerMovementProblem();\n    void run();\n\nprivate:\n\n    // Member Data\n    // runtime parameters\n    const CPPLS::Parameters parameters;\n    const CPPLS::MaterialData material_data;\n\n    // mpi communication\n    MPI_Comm mpi_communicator;\n    const unsigned int n_mpi_processes;\n    const unsigned int this_mpi_process;\n\n    // mesh\n    parallel::distributed::Triangulation<dim> triangulation;\n\n    // FE basis space (for P,T, F, and sigma)\n    // LS separate\n\n    // pressure\n    int degree;\n    DoFHandler<dim> dof_handler;\n    FE_Q<dim> fe;\n    IndexSet locally_owned_dofs;\n    IndexSet locally_relevant_dofs;\n\n\n    int degree_LS;\n    DoFHandler<dim> dof_handler_LS;\n    FE_Q<dim> fe_LS;\n    IndexSet locally_owned_dofs_LS;\n    IndexSet locally_relevant_dofs_LS;\n\n    // output stream where only mpi rank 0 output gets to stdout\n    ConditionalOStream pcout;\n\n    TimerOutput computing_timer;\n\n    double time_step;\n    double current_time;\n    double output_number;\n    double final_time;\n    int timestep_number;\n    int out_index;\n\n    // set timestepping scheme 1 implicit euler, 1/2 CN, 0 explicit euler\n    const double theta;\n\n    ConstraintMatrix constraints_P;\n    ConstraintMatrix constraints_T;\n    ConstraintMatrix constraints_LS;\n    ConstraintMatrix constraints_F;\n    ConstraintMatrix constraints_Sigma;\n    ConstraintMatrix constraints_shift;\n\n    // FE Field Solution Vectors\n    // Ghosted\n    // LS\n    LA::MPI::Vector locally_relevant_solution_LS_0; // ls\n    LA::MPI::Vector old_locally_relevant_solution_LS_0;\n\n    // Pressure\n    LA::MPI::Vector locally_relevant_solution_P;\n    LA::MPI::Vector old_locally_relevant_solution_P;\n    // for use in nonlinear iteration\n    LA::MPI::Vector temp_locally_relevant_solution_P;\n    LA::MPI::Vector old_temp_locally_relevant_solution_P;\n\n    // Temperature\n\n    LA::MPI::Vector locally_relevant_solution_T;\n    LA::MPI::Vector old_locally_relevant_solution_T;\n\n    // Speed function\n    LA::MPI::Vector locally_relevant_solution_F;\n    LA::MPI::Vector old_locally_relevant_solution_F;\n\n    // this is 0 now\n    LA::MPI::Vector locally_relevant_solution_Wxy;\n\n    // Overburden\n    LA::MPI::Vector locally_relevant_solution_Sigma;\n    LA::MPI::Vector old_locally_relevant_solution_Sigma;\n    LA::MPI::Vector temp_locally_relevant_solution_Sigma;\n\n    // Non-ghosted\n    LA::MPI::Vector completely_distributed_solution_LS_0;\n    LA::MPI::Vector completely_distributed_solution_P;\n    LA::MPI::Vector completely_distributed_solution_T;\n    LA::MPI::Vector completely_distributed_solution_F;\n    // LA::MPI::Vector completely_distributed_solution_Sigma;\n\n    LA::MPI::Vector rhs_P;\n    LA::MPI::Vector old_rhs_P;\n    LA::MPI::Vector system_rhs_P;\n\n    LA::MPI::Vector rhs_T;\n    LA::MPI::Vector old_rhs_T;\n    LA::MPI::Vector system_rhs_T;\n\n    LA::MPI::Vector rhs_Sigma;\n\n    LA::MPI::Vector rhs_F;\n\n    // Sparse Matrices\n    LA::MPI::SparseMatrix laplace_matrix_P;\n    LA::MPI::SparseMatrix mass_matrix_P;\n    LA::MPI::SparseMatrix system_matrix_P;\n\n    LA::MPI::SparseMatrix laplace_matrix_T;\n    LA::MPI::SparseMatrix mass_matrix_T;\n    LA::MPI::SparseMatrix system_matrix_T;\n\n    LA::MPI::SparseMatrix system_matrix_F;\n\n    LA::MPI::SparseMatrix system_matrix_Sigma;\n\n    // for LS boundary conditions\n    std::vector<unsigned int> boundary_values_id_LS;\n    std::vector<double> boundary_values_LS;\n\n    std::vector<std::unique_ptr<LevelSetSolver<dim>>> layers;\n    std::vector<std::unique_ptr<LA::MPI::Vector>> layers_solutions;\n    int n_layers;\n    int active_layer_id;\n    double min_h;\n    double grav_acc;\n    double sec_in_year;\n\n    // store functions for porosity, permeability and compressibility\n    std::function\n      <const double(const double pressure, const double overburden, const double initial_porosity,\n      const double compaction_coefficient, const double hydrostatic, const unsigned int material_id)>\n        porosity;\n\n    std::function\n      <const double( const double current_porosity, const double compaction_coefficient, const unsigned int material_id)>\n        compressibility;\n\n//    std::function\n//      <const double(const double pressure, const double overburden, const double initial_porosity,\n//      const double compaction_coefficient, const double hydrostatic)>\n//        permeability;\n\n\n\n    bool compute_inv_mass_matrix;\n    LA::MPI::SparseMatrix system_B_matrix;\n    LA::MPI::SparseMatrix mass_matrix;\n    LA::MPI::SparseMatrix inverse_mass_matrix;\n\n    // Member Functions\n\n\n    void set_physical_functions();\n\n    // create mesh\n    void setup_geometry();\n\n    // create fe space\n    void setup_dofs();\n\n    // create appropriately sized vectors and matrices\n    void setup_system_P();\n    void setup_system_T();\n    void setup_system_LS();\n    void setup_system_F();\n    void setup_system_Sigma();\n    void setup_system_shift();\n\n    void initial_conditions();\n    void set_boundary_inlet();\n    void get_boundary_values_LS(std::vector<unsigned int>& boundary_values_id_LS,\n                                std::vector<double>& boundary_values_LS);\n\n    // use level set values to set cell->material_id\n    void setup_material_configuration();\n\n    // Pressure\n    void assemble_matrices_P();\n    void forge_system_P();\n    void solve_time_step_P();\n    // Temperature\n    void assemble_matrices_T();\n    void forge_system_T();\n    void solve_time_step_T();\n\n    // symbol used for overburden is Sigma\n    void assemble_Sigma();\n    void solve_Sigma();\n\n    // Speed function (scalar)\n    void assemble_F();\n    void solve_F();\n\n    bool estimate_nl_error();\n    int active_layers_in_time(double time);\n\n    void prepare_advance_old_vectors();\n    void advance_old_vectors(LA::MPI::Vector &);\n\n\n    void prepare_next_time_step();\n\n    void output_vectors_LS();\n    void output_vectors();\n    void output_results_pp();\n\n    void display_vectors()\n    {\n        output_vectors_LS();\n        output_vectors();\n        output_results_pp();\n        output_number++;\n    }\n\n    void compute_hydrostatic_thicknesses();\n\n\n    class Postprocessor;\n\n};\n\n// Constructor\n\ntemplate <int dim>\nLayerMovementProblem<dim>::LayerMovementProblem(const CPPLS::Parameters& parameters,\n        const CPPLS::MaterialData& material_data)\n    : parameters(parameters)\n    , material_data(material_data)\n    , mpi_communicator(MPI_COMM_WORLD)\n    , n_mpi_processes {Utilities::MPI::n_mpi_processes(mpi_communicator)}\n, this_mpi_process {Utilities::MPI::this_mpi_process(mpi_communicator)}\n, triangulation(mpi_communicator,\n                typename Triangulation<dim>::MeshSmoothing(Triangulation<dim>::smoothing_on_refinement |\n                        Triangulation<dim>::smoothing_on_coarsening))\n, degree(parameters.degree)\n, degree_LS(parameters.degree_LS)\n, fe(degree)\n, fe_LS(degree_LS)\n, dof_handler(triangulation)\n, dof_handler_LS(triangulation)\n, pcout(std::cout, (Utilities::MPI::this_mpi_process(mpi_communicator) == 0))\n, computing_timer(mpi_communicator, pcout, TimerOutput::summary, TimerOutput::wall_times)\n, time_step{0}\n, current_time {0}\n, final_time {parameters.stop_time}\n, output_number {0}\n, out_index{0}\n, theta(parameters.theta)\n, compute_inv_mass_matrix(true)\n{};\n\n// Destructor\ntemplate <int dim>\nLayerMovementProblem<dim>::~LayerMovementProblem()\n{\n    dof_handler.clear();\n    dof_handler_LS.clear();\n    triangulation.clear();\n}\n\n\n\n\n\ntemplate <int dim>\nvoid LayerMovementProblem<dim>::set_physical_functions()\n{\n  //The purpose of this method is to set, according to the parameter file what compaction rule\n  //and associated compressibility, derivative with respect to VES, to use in the assembly methods\n  if(parameters.linear_in_void_ratio)\n  {\n      pcout<<\"Using Linear in Void Ratio Compaction Law\"<<std::endl;\n      porosity= [](const double pressure, const double overburden, const double initial_porosity,\n                   const double compaction_coefficient, const double hydrostatic, const unsigned int material_id)\n                  {\n                    if(material_id ==0) {return initial_porosity;}\n                    //below is LINEAR IN VOID RATIO\n                     const double init_void_ratio = initial_porosity/(1.-initial_porosity);\n                     const double computed_void_ratio = init_void_ratio - compaction_coefficient*(overburden - pressure - hydrostatic);\n\n                     // Assert(init_void_ratio >= computed_void_ratio, ExcInternalError());\n                     return (computed_void_ratio/(1.+computed_void_ratio));\n\n                   };\n\n      compressibility = []( const double current_porosity, const double compaction_coefficient, const unsigned int material_id)\n         {\n          if(material_id ==0) {return 0.;}\n           return ((1.-current_porosity)*(1.-current_porosity) * compaction_coefficient);\n          };\n  }\n\n  //Here we default to Athy's law\n  else\n  {\n      pcout<<\"Using Athy's Compaction Law\"<<std::endl;\n      porosity= [](const double pressure, const double overburden, const double initial_porosity,\n          const double compaction_coefficient, const double hydrostatic, const double material_id)\n         {\n          if(material_id ==0) {return initial_porosity;}\n          const double VES= overburden - pressure - hydrostatic;\n          //std::cout<<\"ves\"<<VES<<std::endl;\n          //Assert(VES >= 0, ExcInternalError());\n\n           return (initial_porosity *\n                   std::exp(-1 * compaction_coefficient * (overburden - pressure - hydrostatic)));\n          };\n\n      compressibility = []( const double current_porosity, const double compaction_coefficient, const unsigned int material_id)\n         {\n          if(material_id ==0) {return 0.;}\n           return (current_porosity * compaction_coefficient);\n          };\n  }\n  //Permeability as a function of porosity:\n  // We leave the current implementation of the linear in porosity rule hard-coded.\n  //One could here put in other relationships, e.g. Kozeny-Carman, following the approach above\n  //allowing for selection from the input parameter file\n\n}\n\n\n\n//\ntemplate <int dim>\nvoid LayerMovementProblem<dim>::setup_geometry()\n{\n    TimerOutput::Scope t(computing_timer, \"setup_geometry\");\n    if (parameters.cubic)\n    {\n        GridGenerator::hyper_cube(triangulation, 0, parameters.box_size, true);\n    }\n    else\n    {\n        //For weak scaling, want to have for same depth different basin widths (and breadths)\n        //get a rectangle with x_length in multiples of the z_length,(3d y too)\n        //want cell structure(i.e. location of vertices) to be same, just more - \"grown basin\"\n\n        std::vector<unsigned int> repetitions(dim);\n        if(dim==2)\n          {\n            if(parameters.x_length >= parameters.z_length)\n              {\n\n\n\n            //Assuming that this is an integer\n            repetitions[0] = parameters.x_length / parameters.z_length;\n            repetitions[1] = 1;\n\n            Point<dim> bottom_left (0,0);\n            Point<dim> top_right (parameters.x_length,parameters.z_length);\n            GridGenerator::subdivided_hyper_rectangle(triangulation, repetitions, bottom_left, top_right, true);\n              }\n            else\n              {\n                //Assuming that this is an integer\n                repetitions[0] = 1;\n                repetitions[1] = parameters.z_length / parameters.x_length;\n\n                Point<dim> bottom_left (0,0);\n                Point<dim> top_right (parameters.x_length,parameters.z_length);\n                GridGenerator::subdivided_hyper_rectangle(triangulation, repetitions, bottom_left, top_right, true);\n              }\n\n\n          }\n        else if(dim==3)\n          {\n            if(parameters.x_length >= parameters.z_length)\n              {\n\n              //Assuming that these are integers\n              repetitions[0] = parameters.x_length / parameters.z_length;\n              repetitions[1] = parameters.y_length / parameters.z_length;\n              repetitions[2] = 1;\n\n              Point<dim> bottom_left (0,0,0);\n              Point<dim> top_right (parameters.x_length, parameters.y_length, parameters.z_length );\n              GridGenerator::subdivided_hyper_rectangle(triangulation, repetitions, bottom_left, top_right, true);\n              }\n            else\n              {\n                //Assuming that this is an integer\n                repetitions[0] = 1;\n                repetitions[1] = 1;\n                repetitions[2] = parameters.z_length / parameters.x_length;\n\n                Point<dim> bottom_left (0,0, 0);\n                Point<dim> top_right (parameters.x_length, parameters.y_length, parameters.z_length);\n                GridGenerator::subdivided_hyper_rectangle(triangulation, repetitions, bottom_left, top_right, true);\n              }\n\n\n          }\n          else\n          {\n             AssertThrow (false, ExcNotImplemented());\n          }\n\n\n\n    }\n    //print_mesh_info(triangulation, \"my_grid\");\n    triangulation.refine_global(parameters.initial_refinement_level);\n\n    for (auto cell : filter_iterators(triangulation.active_cell_iterators(), IteratorFilters::LocallyOwnedCell())) {\n        cell->set_material_id(0);\n    }\n}\n\ntemplate <int dim>\nvoid LayerMovementProblem<dim>::setup_dofs()\n{\n    TimerOutput::Scope t(computing_timer, \"setup_dofs\");\n\n\n    dof_handler.distribute_dofs(fe);\n    locally_owned_dofs = dof_handler.locally_owned_dofs();\n    DoFTools::extract_locally_relevant_dofs(dof_handler, locally_relevant_dofs);\n    //TODO: put out the sparsity patterns\n    //Point<dim> direction (0,-1);\n    //locally_owned_dofs = dof_handler.locally_owned_dofs();\n\n    std::vector<types::global_dof_index> starting_indices;\n    starting_indices.clear();\n\n    pcout<<std::endl<<\"Dofs on this proc:\"<< dof_handler.n_locally_owned_dofs();\n\n\n    //re-check this algorithm for AMR case\n    //how to get face normals without FEFaceValues TODO\n    const QMidpoint<dim - 1> face_quadrature_formula;\n    FEFaceValues<dim> fe_face_values(fe, face_quadrature_formula,\n                                     update_values | update_quadrature_points | update_normal_vectors |\n                                     update_JxW_values);\n\n    Tensor<1, dim> u;\n    Point<dim> down;\n    down(dim-1)=-1;\n\n\n    std::vector< types::global_dof_index >dof_indices (fe.n_dofs_per_face(), 0);\n\n\n    for (const auto &cell: dof_handler.active_cell_iterators())\n    {\n        if(cell->is_locally_owned())\n        {\n\n            for (unsigned int face = 0; face < GeometryInfo<dim>::faces_per_cell; ++face)\n            {\n                if ((cell->face(face)->at_boundary()) || (cell->neighbor(face)->is_ghost()))\n                {\n                    fe_face_values.reinit(cell, face);\n                    u=fe_face_values.normal_vector(0);\n                    if(u*down< 0)\n                    {\n                        cell->face(face)->get_dof_indices(dof_indices);\n                        starting_indices.insert(std::end(starting_indices),\n                                                std::begin(dof_indices), std::end(dof_indices));\n                    }\n                }\n            }\n        }\n    }\n\n//  //remove duplicates by creating a set\n    std::set<types::global_dof_index> no_duplicates_please (starting_indices.begin(),\n            starting_indices.end());\n//  //back to vector for the DoFRenumbering function\n//  starting_indices.clear();\n    starting_indices.assign(no_duplicates_please.begin(), no_duplicates_please.end());\n//  starting_indices.insert(std::end(starting_indices),\n//                                 std::begin(no_duplicates_please), std::end(no_duplicates_please));\n\n    //starting_indices=locally_owned_dofs;\n// DoFTools::extract_locally_owned_dofs(dof_handler, starting_indices);\nDoFRenumbering::Cuthill_McKee(dof_handler,false, true, starting_indices);\n    //Not working in parallel now\n    //DoFRenumbering::downstream(dof_handler, direction, true);\n\n\n    pcout << std::endl\n          << \"============DofHandler===============\" << std::endl\n          << \"Number of active cells: \" << triangulation.n_global_active_cells() << std::endl\n          << \"Number of degrees of freedom: \" << dof_handler.n_dofs() << std::endl\n          << std::endl;\n\n  locally_owned_dofs = dof_handler.locally_owned_dofs();\n  DoFTools::extract_locally_relevant_dofs(dof_handler, locally_relevant_dofs);\n}\n\ntemplate <int dim>\nvoid LayerMovementProblem<dim>::setup_system_P()\n{\n    TimerOutput::Scope t(computing_timer, \"setup_P\");\n\n    pcout << std::endl << \"============Pressure===============\" << std::endl << std::endl;\n\n    // vector setup\n    locally_relevant_solution_P.reinit(locally_owned_dofs, locally_relevant_dofs, mpi_communicator);\n    temp_locally_relevant_solution_P.reinit(locally_owned_dofs, locally_relevant_dofs, mpi_communicator);\n    old_temp_locally_relevant_solution_P.reinit(locally_owned_dofs, locally_relevant_dofs, mpi_communicator);\n\n    completely_distributed_solution_P.reinit(locally_owned_dofs, mpi_communicator);\n\n    old_locally_relevant_solution_P.reinit(locally_owned_dofs, locally_relevant_dofs, mpi_communicator);\n    rhs_P.reinit(locally_owned_dofs, mpi_communicator);\n    old_rhs_P.reinit(locally_owned_dofs, mpi_communicator);\n\n    system_rhs_P.reinit(locally_owned_dofs, mpi_communicator);\n\n    // constraints\n\n    constraints_P.clear();\n\n    constraints_P.reinit(locally_relevant_dofs);\n\n    DoFTools::make_hanging_node_constraints(dof_handler, constraints_P);\n    // zero dirichlet at top\n    //the \"top\" has boundary_id = dim*2-1; (so 3 for 2d, 5 for 3d)\n    VectorTools::interpolate_boundary_values(dof_handler, dim*2-1, ZeroFunction<dim>(),\n            constraints_P); // TODO get rid of raw number\n    constraints_P.close();\n\n    // create sparsity pattern\n\n    DynamicSparsityPattern dsp(locally_relevant_dofs);\n\n    DoFTools::make_sparsity_pattern(dof_handler, dsp, constraints_P, false);\n    SparsityTools::distribute_sparsity_pattern(dsp, dof_handler.n_locally_owned_dofs_per_processor(), mpi_communicator,\n            locally_relevant_dofs);\n    // setup matrices\n\n    system_matrix_P.reinit(locally_owned_dofs, locally_owned_dofs, dsp, mpi_communicator);\n    laplace_matrix_P.reinit(locally_owned_dofs, locally_owned_dofs, dsp, mpi_communicator);\n    mass_matrix_P.reinit(locally_owned_dofs, locally_owned_dofs, dsp, mpi_communicator);\n}\n\ntemplate <int dim>\nvoid LayerMovementProblem<dim>::setup_system_T()\n{\n    TimerOutput::Scope t(computing_timer, \"setup_system_T\");\n\n    pcout << std::endl << \"============Temperature===============\" << std::endl << std::endl;\n\n    // vector setup\n    locally_relevant_solution_T.reinit(locally_owned_dofs, locally_relevant_dofs, mpi_communicator);\n    old_locally_relevant_solution_T.reinit(locally_owned_dofs, locally_relevant_dofs, mpi_communicator);\n    completely_distributed_solution_T.reinit(locally_owned_dofs, mpi_communicator);\n\n    rhs_T.reinit(locally_owned_dofs, mpi_communicator);\n    old_rhs_T.reinit(locally_owned_dofs, mpi_communicator);\n    system_rhs_T.reinit(locally_owned_dofs, mpi_communicator);\n\n    // constraints\n\n    constraints_T.clear();\n    constraints_T.reinit(locally_relevant_dofs);\n\n    DoFTools::make_hanging_node_constraints(dof_handler, constraints_T);\n    // zero dirichlet at top\n    //the \"top\" has boundary_id = dim*2-1; (so 3 for 2d, 5 for 3d)\n    VectorTools::interpolate_boundary_values(dof_handler, dim*2-1, ZeroFunction<dim>(),\n            constraints_T); // TODO again raw number for boundary_id\n    // Keep top at fixed temperature, TODO check compatibility condition\n    // VectorTools::interpolate_boundary_values(dof_handler_T, 3, ConstantFunction<dim>(20), constraints_T);\n    constraints_T.close();\n\n    // create sparsity pattern\n\n    DynamicSparsityPattern dsp(locally_relevant_dofs);\n    DoFTools::make_sparsity_pattern(dof_handler, dsp, constraints_T, false);\n    SparsityTools::distribute_sparsity_pattern(dsp, dof_handler.n_locally_owned_dofs_per_processor(), mpi_communicator,\n            locally_relevant_dofs);\n    // setup matrices\n\n    system_matrix_T.reinit(locally_owned_dofs, locally_owned_dofs, dsp, mpi_communicator);\n    laplace_matrix_T.reinit(locally_owned_dofs, locally_owned_dofs, dsp, mpi_communicator);\n    mass_matrix_T.reinit(locally_owned_dofs, locally_owned_dofs, dsp, mpi_communicator);\n}\n\ntemplate <int dim>\nvoid LayerMovementProblem<dim>::setup_system_Sigma()\n{\n    // First of two SUPG problems\n    TimerOutput::Scope t(computing_timer, \"setup_system_Sigma\");\n\n    pcout << std::endl << \"============Overburden===============\" << std::endl << std::endl;\n\n    // vector setup\n    locally_relevant_solution_Sigma.reinit(locally_owned_dofs, locally_relevant_dofs, mpi_communicator);\n    old_locally_relevant_solution_Sigma.reinit(locally_owned_dofs, locally_relevant_dofs, mpi_communicator);\n    temp_locally_relevant_solution_Sigma.reinit(locally_owned_dofs, locally_relevant_dofs, mpi_communicator);\n\n    rhs_Sigma.reinit(locally_owned_dofs, mpi_communicator);\n\n    // constraints\n\n    constraints_Sigma.clear();\n    constraints_Sigma.reinit(locally_relevant_dofs);\n\n    DoFTools::make_hanging_node_constraints(dof_handler, constraints_Sigma);\n\n    // inflow bc at top\n    //the \"top\" has boundary_id = dim*2-1; (so 3 for 2d, 5 for 3d)\n//VectorTools::interpolate_boundary_values(dof_handler, 3, ConstantFunction<dim>(inflow_rate*15000),\n//                                           constraints_Sigma); // TODO put in sedimentation(x,y,t)\n    VectorTools::interpolate_boundary_values(dof_handler, dim*2-1, ZeroFunction<dim>(),\n            constraints_Sigma);\n    constraints_Sigma.close();\n\n    // create sparsity pattern\n\n    DynamicSparsityPattern dsp(locally_relevant_dofs);\n    DoFTools::make_sparsity_pattern(dof_handler, dsp, constraints_Sigma, false);\n    SparsityTools::distribute_sparsity_pattern(dsp, dof_handler.n_locally_owned_dofs_per_processor(), mpi_communicator,\n            locally_relevant_dofs);\n    // setup matrix\n\n    system_matrix_Sigma.reinit(locally_owned_dofs, locally_owned_dofs, dsp, mpi_communicator);\n}\n\ntemplate <int dim>\nvoid LayerMovementProblem<dim>::setup_system_F()\n{\n    // Second of two SUPG problems\n    TimerOutput::Scope t(computing_timer, \"setup_system_F\");\n\n    pcout << std::endl << \"============Speed Function===============\" << std::endl << std::endl;\n\n    // vector setup\n    locally_relevant_solution_F.reinit(locally_owned_dofs, locally_relevant_dofs, mpi_communicator);\n\n    //old_locally_relevant_solution_F.reinit(locally_owned_dofs, locally_relevant_dofs, mpi_communicator);\n\n    completely_distributed_solution_F.reinit(locally_owned_dofs, mpi_communicator);\n\n    rhs_F.reinit(locally_owned_dofs, mpi_communicator);\n\n    // constraints\n\n    constraints_F.clear();\n    constraints_F.reinit(locally_relevant_dofs);\n\n    DoFTools::make_hanging_node_constraints(dof_handler, constraints_F);\n    SedimentationRate<dim> sedrate(current_time, parameters);\n    sedrate.set_time(current_time);\n\n    // inflow bc at top\n    //the \"top\" has boundary_id = dim*2-1; (so 3 for 2d, 5 for 3d)\n    VectorTools::interpolate_boundary_values(dof_handler, dim*2-1, sedrate,\n            constraints_F);\n    constraints_F.close();\n\n    // create sparsity pattern\n\n    DynamicSparsityPattern dsp(locally_relevant_dofs);\n    DoFTools::make_sparsity_pattern(dof_handler, dsp, constraints_F, false);\n    SparsityTools::distribute_sparsity_pattern(dsp, dof_handler.n_locally_owned_dofs_per_processor(), mpi_communicator,\n            locally_relevant_dofs);\n    // setup matrix\n\n    system_matrix_F.reinit(locally_owned_dofs, locally_owned_dofs, dsp, mpi_communicator);\n}\n\ntemplate <int dim>\nvoid LayerMovementProblem<dim>::setup_system_LS()\n{\n    // Note: just solution vectors here, no matrices\n    TimerOutput::Scope t(computing_timer, \"setup_system_LS\");\n\n    dof_handler_LS.distribute_dofs(fe_LS);\n\n    pcout << std::endl\n          << \"============LEVEL SETS===============\" << std::endl\n          << \"Number of active cells: \" << triangulation.n_global_active_cells() << std::endl\n          << \"Number of degrees of freedom: \" << dof_handler_LS.n_dofs() << std::endl\n          << std::endl;\n\n    locally_owned_dofs_LS = dof_handler_LS.locally_owned_dofs();\n    DoFTools::extract_locally_relevant_dofs(dof_handler_LS, locally_relevant_dofs_LS);\n\n    // vector setup\n    locally_relevant_solution_LS_0.reinit(locally_owned_dofs_LS, locally_relevant_dofs_LS, mpi_communicator);\n\n    completely_distributed_solution_LS_0.reinit(locally_owned_dofs_LS, mpi_communicator);\n\n    // non-vertical zero vector to feed into LevelSetSolver\n    locally_relevant_solution_Wxy.reinit(locally_owned_dofs_LS, locally_relevant_dofs_LS, mpi_communicator);\n\n    //locally_relevant_solution_F.reinit(locally_owned_dofs_LS, locally_relevant_dofs_LS, mpi_communicator);\n    //completely_distributed_solution_F.reinit(locally_owned_dofs_LS, mpi_communicator);\n\n    // constraints\n\n    constraints_LS.clear();\n\n    constraints_LS.reinit(locally_relevant_dofs_LS);\n\n    DoFTools::make_hanging_node_constraints(dof_handler_LS, constraints_LS);\n\n    constraints_LS.close();\n}\n\n\ntemplate <int dim>\nvoid LayerMovementProblem<dim>::setup_system_shift()\n{\n\n\n\n  // constraints\n\n  constraints_shift.clear();\n\n  constraints_shift.reinit(locally_relevant_dofs);\n\n  DoFTools::make_hanging_node_constraints(dof_handler, constraints_shift);\n  VectorTools::interpolate_boundary_values(dof_handler, dim*2-1, ZeroFunction<dim>(),\n          constraints_shift);\n\n  constraints_shift.close();\n\n\n  // create sparsity pattern\n\n  DynamicSparsityPattern dsp(locally_relevant_dofs);\n  DoFTools::make_sparsity_pattern(dof_handler, dsp, constraints_shift, false);\n  SparsityTools::distribute_sparsity_pattern(dsp, dof_handler.n_locally_owned_dofs_per_processor(), mpi_communicator,\n          locally_relevant_dofs);\n  // setup matrix\n\n  system_B_matrix.reinit(locally_owned_dofs, locally_owned_dofs, dsp, mpi_communicator);\n  mass_matrix.reinit(locally_owned_dofs, locally_owned_dofs, dsp, mpi_communicator);\n\n}\n\n\n\n\n\n\ntemplate <int dim>\nvoid LayerMovementProblem<dim>::initial_conditions()\n{\n    // Precondition: the non/ghosted vectors have been initialized, and constraints closed (in setup functions)\n    //For P, T, 0 initial values\n\n    // init condition for P (TODO should use call to VectorTools::interpolate)\n    completely_distributed_solution_P = 0;\n    //VectorTools::interpolate_boundary_values(dof_handler, /*top boundary*/ 3, ZeroFunction<dim>(), constraints_P);\n    VectorTools::interpolate(dof_handler, ZeroFunction<dim>(), completely_distributed_solution_P);\n    constraints_P.distribute(completely_distributed_solution_P);\n    locally_relevant_solution_P = completely_distributed_solution_P;\n\n    // init condition for T   //TODO\n    completely_distributed_solution_T = 0;\n    //VectorTools::interpolate_boundary_values(dof_handler, /*top boundary*/ 3, ZeroFunction<dim>(), constraints_T);\n    VectorTools::interpolate(dof_handler, ZeroFunction<dim>(),completely_distributed_solution_T);\n    constraints_T.distribute(completely_distributed_solution_T);\n    locally_relevant_solution_T = completely_distributed_solution_T;\n\n    // init condition for LS\n    // all the others will share this\n    completely_distributed_solution_LS_0 = 0;\n    const double min_h = GridTools::minimal_cell_diameter(triangulation) / std::sqrt(2);\n    pcout <<\"min_h is:\"<<min_h<<std::endl;\n\n    VectorTools::interpolate(dof_handler_LS, Initial_LS<dim>(min_h/100., parameters.box_size),\n                             completely_distributed_solution_LS_0);\n\n    constraints_LS.distribute(completely_distributed_solution_LS_0);\n    locally_relevant_solution_LS_0 = completely_distributed_solution_LS_0;\n\n}\n\ntemplate <int dim>\nvoid LayerMovementProblem<dim>::get_boundary_values_LS(std::vector<unsigned int>& boundary_values_id_LS,\n        std::vector<double>& boundary_values_LS)\n{\n    std::map<unsigned int, double> map_boundary_values_LS;\n    unsigned int boundary_id = 0;\n\n    // set_boundary_inlet();\n   // boundary_id = 10; // inlet\n    // we define the inlet to be at the top, i.e. boundary_id=3\n    //the \"top\" has boundary_id = dim*2-1; (so 3 for 2d, 5 for 3d)\n    VectorTools::interpolate_boundary_values(dof_handler_LS, dim*2-1, BoundaryPhi<dim>(1.0), map_boundary_values_LS);\n    boundary_values_id_LS.resize(map_boundary_values_LS.size());\n    boundary_values_LS.resize(map_boundary_values_LS.size());\n    std::map<unsigned int, double>::const_iterator boundary_value_LS = map_boundary_values_LS.begin();\n    for (int i = 0; boundary_value_LS != map_boundary_values_LS.end(); ++boundary_value_LS, ++i) {\n        boundary_values_id_LS[i] = boundary_value_LS->first;\n        boundary_values_LS[i] = boundary_value_LS->second;\n    }\n}\n\ntemplate <int dim>\nvoid LayerMovementProblem<dim>::assemble_Sigma()\n{\n    TimerOutput::Scope t(computing_timer, \"assemble_Sigma\");\n    const AdvectionField<dim> advection_field;\n    const QGauss<dim> quadrature_formula(degree + 2);\n    const QGauss<dim - 1> face_quadrature_formula(degree + 1);\n\n    FEValues<dim> fe_values(fe, quadrature_formula,\n                            update_values | update_quadrature_points | update_JxW_values | update_gradients);\n\n//    FEFaceValues<dim> fe_face_values(fe, face_quadrature_formula,\n//                                     update_values | update_quadrature_points | update_normal_vectors |\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    const unsigned int n_face_q_points = face_quadrature_formula.size();\n\n    std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell);\n\n    std::vector<double> rhs_at_quad(n_q_points);\n    std::vector<Tensor<1, dim>> advection_directions(n_q_points);\n//    std::vector<Tensor<1, dim>> face_advection_directions(n_face_q_points);\n\n\n    std::vector<double> overburden_at_quad(n_q_points);\n    std::vector<double> pressure_at_quad(n_q_points);\n\n    Point<dim> point_for_depth;\n    SedimentationRate<dim> sedRate(current_time, parameters); // rate is a negative quantity\n\n    std::vector<double> sedimentation_rate(n_q_points);\n\n    Vector<double> cell_rhs(dofs_per_cell);\n    FullMatrix<double> cell_matrix(dofs_per_cell, dofs_per_cell);\n\n    rhs_Sigma = 0;\n    system_matrix_Sigma = 0;\n\n    int material_id;\n\n    for (auto cell : filter_iterators(dof_handler.active_cell_iterators(), IteratorFilters::LocallyOwnedCell())) {\n\n        material_id=cell->material_id();\n        fe_values.reinit(cell);\n\n        fe_values.get_function_values(temp_locally_relevant_solution_P, pressure_at_quad);\n\n        fe_values.get_function_values(temp_locally_relevant_solution_Sigma, overburden_at_quad);\n\n        // TODO consider moving these properties to the quad point level, not just cell level\n        const double initial_porosity = material_data.get_surface_porosity(material_id);\n        const double compaction_coefficient = material_data.get_compaction_coefficient(material_id);\n        const double rock_density = material_data.get_solid_density(material_id);\n\n         sedRate.value_list(fe_values.get_quadrature_points(), sedimentation_rate, 1);\n         advection_field.value_list(fe_values.get_quadrature_points(), advection_directions);\n\n        cell_rhs = 0;\n        cell_matrix = 0;\n        const double delta = 1 * cell->diameter();\n\n        for (unsigned int q_point = 0; q_point < n_q_points; ++q_point) {\n            point_for_depth = fe_values.quadrature_point(q_point);\n            const double hydrostatic = grav_acc * material_data.fluid_density *\n                                       (parameters.box_size - point_for_depth[dim-1]);\n            const double phi = porosity(pressure_at_quad[q_point], overburden_at_quad[q_point], initial_porosity,\n                                       compaction_coefficient, hydrostatic, material_id);\n\n            Assert(0 < hydrostatic, ExcInternalError());\n            Assert(0 <= phi, ExcInternalError());\n            Assert(phi < 1, ExcInternalError());\n\n            const double rho_b = bulkdensity(phi, material_data.fluid_density, rock_density);\n\n            rhs_at_quad[q_point] = grav_acc * rho_b;\n\n\n\n            //this should point \"down\"\n            Assert( 0 > advection_directions[q_point][dim-1], ExcInternalError());\n\n            //Assert ( 0 <sedimentation_rate[q_point], ExcInternalError());\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                    cell_matrix(i, j) += ((advection_directions[q_point] * fe_values.shape_grad(j, q_point) *\n                                           (fe_values.shape_value(i, q_point) +\n                                            delta * (advection_directions[q_point] * 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 * (advection_directions[q_point] * fe_values.shape_grad(i, q_point))) *\n                               rhs_at_quad[q_point] * fe_values.JxW(q_point);\n\n            }   // end i\n        }     // end q\n\n        //Rather than implement the boundary term, we specify as an essential condition on the test space\n        //So it is handled in a call to the constraints_Sigma\n\n        // For the inflow boundary term\n//    for (unsigned int face = 0; face < GeometryInfo<dim>::faces_per_cell; ++face)\n//      if (cell->face(face)->at_boundary()) {\n//        fe_face_values.reinit(cell, face);\n\n//        advection_field.value_list(fe_face_values.get_quadrature_points(), face_advection_directions);\n//        for (unsigned int q_point = 0; q_point < n_face_q_points; ++q_point)\n//          // the following determines whether inflow or not\n//          if (fe_face_values.normal_vector(q_point) * face_advection_directions[q_point] < 0)\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) -= (face_advection_directions[q_point] * fe_face_values.normal_vector(q_point) *\n//                                      fe_face_values.shape_value(i, q_point) * fe_face_values.shape_value(j, q_point) *\n//                                      fe_face_values.JxW(q_point));\n//              cell_rhs(i) -=\n//                  (face_advection_directions[q_point] * fe_face_values.normal_vector(q_point) *\n//                   sedimentation_rate[q_point] * fe_face_values.shape_value(i, q_point) * fe_face_values.JxW(q_point));\n//            }\n//      }\n\n        cell->get_dof_indices(local_dof_indices); // distribute to correct globally numbered vector\n\n        constraints_Sigma.distribute_local_to_global(cell_matrix, cell_rhs, local_dof_indices, system_matrix_Sigma,\n                rhs_Sigma);\n    } // end cell loop\n\n    rhs_Sigma.compress(VectorOperation::add);\n    system_matrix_Sigma.compress(VectorOperation::add);\n}\n\ntemplate <int dim>\nvoid LayerMovementProblem<dim>::solve_Sigma()\n{\n    TimerOutput::Scope t(computing_timer, \"solve_Sigma\");\n\n    LA::MPI::Vector completely_distributed_solution(locally_owned_dofs, mpi_communicator);\n\n    SolverControl solver_control(dof_handler.n_dofs(), parameters.sigma_tol * rhs_Sigma.l2_norm());\n    //  LA::SolverBicgstab solver(solver_control, mpi_communicator);\n    LA::SolverGMRES solver(solver_control, mpi_communicator);\n    //  LA::MPI::PreconditionAMG preconditioner;\n    //  LA::MPI::PreconditionAMG::AdditionalData data;\n    //  LA::MPI::PreconditionSSOR preconditioner;\n    //  LA::MPI::PreconditionSSOR::AdditionalData data;\n    //LA::MPI::PreconditionJacobi preconditioner;\n    //LA::MPI::PreconditionJacobi::AdditionalData data;\n    //LA::PreconditionSSOR preconditioner;\n    //does not compile with this\n    //LA::MPI::PreconditionBlockJacobi preconditioner;\n    //LA::PreconditionBlockJacobi preconditioner;\n    //does with this\n    PETScWrappers::PreconditionBlockJacobi preconditioner;\n    PETScWrappers::PreconditionBlockJacobi::AdditionalData data;\n    //data.symmetric_operator = false;\n    preconditioner.initialize(system_matrix_Sigma, data);\n\n    solver.solve(system_matrix_Sigma, completely_distributed_solution, rhs_Sigma, preconditioner);\n\n    pcout << \" Overburden supg system solved in \" << solver_control.last_step() << \" iterations.\" << std::endl;\n\n    constraints_Sigma.distribute(completely_distributed_solution);\n    //old_locally_relevant_solution_Sigma=locally_relevant_solution_Sigma;\n    temp_locally_relevant_solution_Sigma = completely_distributed_solution;\n\n\n}\n\ntemplate <int dim>\nvoid LayerMovementProblem<dim>::assemble_F()\n{\n\n    TimerOutput::Scope t(computing_timer, \"assemble_F\");\n    const AdvectionField<dim> advection_field;\n    const QGauss<dim> quadrature_formula(degree + 2);\n    const QGauss<dim - 1> face_quadrature_formula(degree + 1);\n\n    FEValues<dim> fe_values(fe, quadrature_formula,\n                            update_values | update_quadrature_points | update_JxW_values | update_gradients);\n\n//    FEFaceValues<dim> fe_face_values(fe, face_quadrature_formula,\n//                                     update_values | update_quadrature_points | update_normal_vectors |\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    const unsigned int n_face_q_points = face_quadrature_formula.size();\n\n    std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell);\n\n    std::vector<double> rhs_at_quad(n_q_points);\n    std::vector<Tensor<1, dim>> advection_directions(n_q_points);\n//    std::vector<Tensor<1, dim>> face_advection_directions(n_face_q_points);\n\n\n    std::vector<double> overburden_at_quad(n_q_points);\n    std::vector<double> old_overburden_at_quad(n_q_points);\n    std::vector<double> pressure_at_quad(n_q_points);\n    std::vector<double> old_pressure_at_quad(n_q_points);\n\n    std::vector<double> speed_at_quad(n_q_points);\n\n    Point<dim> point_for_depth;\n    SedimentationRate<dim> sedRate(current_time, parameters);\n\n    std::vector<double> sedimentation_rate(n_q_points);\n\n    Vector<double> cell_rhs(dofs_per_cell);\n    FullMatrix<double> cell_matrix(dofs_per_cell, dofs_per_cell);\n\n    rhs_F = 0;\n    system_matrix_F = 0;\n\n    int material_id;\n    const double min_h = GridTools::minimal_cell_diameter(triangulation) / std::sqrt(2);\n\n    for (auto cell : filter_iterators(dof_handler.active_cell_iterators(), IteratorFilters::LocallyOwnedCell())) {\n\n        material_id=cell->material_id();\n\n        fe_values.reinit(cell);\n        fe_values.get_function_values(old_locally_relevant_solution_F, speed_at_quad);\n        fe_values.get_function_values(locally_relevant_solution_P, pressure_at_quad);\n        fe_values.get_function_values(locally_relevant_solution_Sigma, overburden_at_quad);\n        fe_values.get_function_values(old_locally_relevant_solution_P, old_pressure_at_quad);\n        fe_values.get_function_values(old_locally_relevant_solution_Sigma, old_overburden_at_quad);\n\n        // TODO consider moving these properties to the quad point level, not just cell level\n        const double initial_porosity = material_data.get_surface_porosity(material_id);\n        const double compaction_coefficient = material_data.get_compaction_coefficient(material_id);\n        advection_field.value_list(fe_values.get_quadrature_points(), advection_directions);\n        sedRate.value_list(fe_values.get_quadrature_points(), sedimentation_rate, 1);\n\n\n        cell_rhs = 0;\n        cell_matrix = 0;\n        const double delta = 0.1 * cell->diameter();\n\n        for (unsigned int q_point = 0; q_point < n_q_points; ++q_point) {\n            point_for_depth = fe_values.quadrature_point(q_point);\n            const double hydrostatic = grav_acc * material_data.fluid_density *\n                                       (parameters.box_size - point_for_depth[dim-1]);\n            const double old_hydrostatic = grav_acc * material_data.fluid_density *\n                                    //   (parameters.box_size - (point_for_depth[dim-1]+(-1.*sedimentation_rate[q_point]*time_step)));//(old_speed_at_quad[q_point]*time_step)));\n                                      (parameters.box_size - (point_for_depth[dim-1]+(-1.*speed_at_quad[q_point]*time_step)));//()));\n\n            Assert(0 < hydrostatic, ExcInternalError());\n            const double phi = porosity(pressure_at_quad[q_point], overburden_at_quad[q_point], initial_porosity,\n                                        compaction_coefficient, hydrostatic, material_id);\n\n            Assert(0 <= phi, ExcInternalError());\n            Assert(phi < 1, ExcInternalError());\n\n\n            const double active_rock_density = material_data.get_solid_density(active_layer_id);\n            const double active_init_porosity = material_data.get_surface_porosity(active_layer_id);\n            const double bulk_deposit=bulkdensity (active_init_porosity, material_data.fluid_density, active_rock_density);\n            //pcout<<\"b\"<<bulk_deposit<<std::endl;\n\n            const double temp_old_overburden= overburden_at_quad[q_point]-grav_acc*bulk_deposit*-1.*sedimentation_rate[q_point]*time_step;\n\n\n            const double old_phi = porosity(old_pressure_at_quad[q_point], temp_old_overburden/* old_overburden_at_quad[q_point]*/, initial_porosity,\n                                            compaction_coefficient, old_hydrostatic, material_id);\n          //  pcout<<\"phi\"<<phi<<\" \";\n          //  pcout<<\"old_phi\"<<old_phi<<std::endl;\n            Assert(0 <= old_phi, ExcInternalError());\n            Assert(old_phi < 1, ExcInternalError());\n//            pcout<<std::endl<<\"cell\"<<cell->center()<<\" \"<<material_id<<std::endl;\n//            pcout<<\"min_h\"<<sedimentation_rate[q_point]*time_step<<std::endl;\n//            pcout<<\"min_h_compac\"<<speed_at_quad[q_point]*time_step<<std::endl;\n//            pcout<<\"min_h_compac\"<<speed_at_quad[q_point]<<std::endl;\n//            pcout<<\"old: \"<<temp_old_overburden<<\" \"<<old_pressure_at_quad[q_point]<<\" \"<<old_hydrostatic<<std::endl;\n//            pcout<<\"old_VES: \"<<temp_old_overburden-old_pressure_at_quad[q_point]-old_hydrostatic<<std::endl;\n//            pcout<<\"now: \"<<overburden_at_quad[q_point]<<\" \"<<pressure_at_quad[q_point]<<\" \"<<hydrostatic<<std::endl;\n\n//            pcout<<\"now_VES: \"<<overburden_at_quad[q_point]-pressure_at_quad[q_point]-hydrostatic<<std::endl;\n             double dphidt = (phi - old_phi) / time_step;\n//            pcout<<\"dphi: \"<<phi - old_phi<<std::endl;\n//            pcout<<\"dphidt: \"<<dphidt<<std::endl;\n\n            Assert(dphidt < 0.1, ExcInternalError());\n            const double VES=overburden_at_quad[q_point]-pressure_at_quad[q_point]-hydrostatic;\n            const double old_VES=temp_old_overburden-old_pressure_at_quad[q_point]-old_hydrostatic;\n\n\n            rhs_at_quad[q_point] =-dphidt /((1.-phi));\n           //\n         //   pcout<<\"dphidt: \"<<rhs_at_quad[q_point]<<std::endl;\n           // rhs_at_quad[q_point] = (1./(1. - phi))*compaction_coefficient*(1. - phi)*(1. - phi)*(VES-old_VES)/time_step;\n//            pcout<<\"other_rhs: \"<<rhs_at_quad[q_point]<<std::endl;\n\n            //Athy\n            //rhs_at_quad[q_point] =compaction_coefficient*phi*(VES-old_VES)/time_step;\n            //linear void ratio\n//            rhs_at_quad[q_point] =  (1./(1. - phi))*compaction_coefficient*(1. - phi)*(1. - phi)*\n//                                    ((1. - phi)*(2720-1024)*-9.81*sedimentation_rate[q_point]+\n//                                      (pressure_at_quad[q_point]-old_pressure_at_quad[q_point])/time_step);\n\n            // pcout<<\"dooverpreesure: \"<<pressure_at_quad[q_point]-old_pressure_at_quad[q_point]<<std::endl;\n            //  pcout<<\"rhs: \"<<rhs_at_quad[q_point]<<std::endl;\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                    cell_matrix(i, j) += ((advection_directions[q_point] * fe_values.shape_grad(j, q_point) *\n                                           (fe_values.shape_value(i, q_point) +\n                                            delta * (advection_directions[q_point] * 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 * (advection_directions[q_point] * fe_values.shape_grad(i, q_point))) *\n                               rhs_at_quad[q_point] * fe_values.JxW(q_point);\n\n            }   // end i\n        }     // end q\n\n        // For the inflow boundary term\n\n//    for (unsigned int face = 0; face < GeometryInfo<dim>::faces_per_cell; ++face)\n//      if (cell->face(face)->at_boundary()) {\n//        fe_face_values.reinit(cell, face);\n\n//        advection_field.value_list(fe_face_values.get_quadrature_points(), face_advection_directions);\n//        for (unsigned int q_point = 0; q_point < n_face_q_points; ++q_point)\n//          // the following determines whether inflow or not\n//          if (fe_face_values.normal_vector(q_point) * face_advection_directions[q_point] < 0)\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) -= (face_advection_directions[q_point] * fe_face_values.normal_vector(q_point) *\n//                                      fe_face_values.shape_value(i, q_point) * fe_face_values.shape_value(j, q_point) *\n//                                      fe_face_values.JxW(q_point));\n//              cell_rhs(i) -=\n//                  (face_advection_directions[q_point] * fe_face_values.normal_vector(q_point) *\n//                   sedimentation_rate[q_point] * fe_face_values.shape_value(i, q_point) * fe_face_values.JxW(q_point));\n//            }\n//      }\n\n        cell->get_dof_indices(local_dof_indices); // distribute to correct globally numbered vector\n\n        constraints_F.distribute_local_to_global(cell_matrix, cell_rhs, local_dof_indices, system_matrix_F, rhs_F);\n    } // end cell loop\n\n    rhs_F.compress(VectorOperation::add);\n    system_matrix_F.compress(VectorOperation::add);\n}\n\ntemplate <int dim>\nvoid LayerMovementProblem<dim>::solve_F()\n{\n    TimerOutput::Scope t(computing_timer, \"solve_F\");\n\n    LA::MPI::Vector completely_distributed_solution(locally_owned_dofs, mpi_communicator);\n\n    SolverControl solver_control(dof_handler.n_dofs(), 1e-12 * rhs_F.l2_norm());\n    //  LA::SolverBicgstab solver(solver_control, mpi_communicator);\n    LA::SolverGMRES solver(solver_control, mpi_communicator);\n    //  LA::MPI::PreconditionAMG preconditioner;\n    //  LA::MPI::PreconditionAMG::AdditionalData data;\n    //  LA::MPI::PreconditionSSOR preconditioner;\n    //  LA::MPI::PreconditionSSOR::AdditionalData data;\n    PETScWrappers::PreconditionBlockJacobi preconditioner;\n    PETScWrappers::PreconditionBlockJacobi::AdditionalData data;\n//  LA::MPI::PreconditionJacobi preconditioner;\n//  LA::MPI::PreconditionJacobi::AdditionalData data;\n\n    // data.symmetric_operator = false;\n    preconditioner.initialize(system_matrix_F, data);\n\n    solver.solve(system_matrix_F, completely_distributed_solution, rhs_F, preconditioner);\n\n    pcout << \" Speed function system solved in \" << solver_control.last_step() << \" iterations.\" << std::endl;\n\n    constraints_F.distribute(completely_distributed_solution);\n\n    locally_relevant_solution_F = completely_distributed_solution;\n}\n\n\n// TODO fold this into P,F,Sigma, T assemblies to assign at quad point level\ntemplate <int dim>\nvoid LayerMovementProblem<dim>::setup_material_configuration()\n{\n    //TODO\n\n    TimerOutput::Scope t(computing_timer, \"set_material_configuration\");\n    // This function sets material ids of cells based on the location of the interface, i.e. loc_rel_solution_LS\n\n    const QGauss<dim> quadrature_formula(degree + 2);\n\n    FEValues<dim> fe_values(fe_LS, quadrature_formula, update_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    //  std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell);\n\n\n    //TODO: a better structure than vec(vec))\n    std::vector<std::vector<double>> LS_at_quad (n_layers, std::vector<double>(n_q_points));\n\n    // std::vector<double> bulkdensity_at_quad(n_q_points);\n    // double eps= GridTools::minimal_cell_diameter(triangulation)/std::sqrt(2);\n    //      const double eps=0.001;\n    //        double H=0;\n    //          // get rho, nu\n    //          if (phi>eps)\n    //            H=1;\n    //          else if (phi<-eps)\n    //            H=-1;\n    //          else\n    //            H=phi/eps;\n    //          diff_coeff=1000*(1+H)/2.+10*(1-H)/2.;\n\n    // std::vector<double> id_sum(5);\n    std::vector<double> id_sum(n_layers, 0);\n    Point<dim> interface_depth;\n\n\n\n    for (auto cell : filter_iterators(dof_handler_LS.active_cell_iterators(), IteratorFilters::LocallyOwnedCell())) {\n\n        std::fill(id_sum.begin(), id_sum.end(), 0);\n\n        fe_values.reinit(cell);\n        int i=0;//for n_layers\n        for(auto & layer_sol : layers_solutions)\n        {\n            fe_values.get_function_values( *layer_sol, LS_at_quad[i]);\n\n            for (unsigned int q_point = 0; q_point < n_q_points; ++q_point)\n            {\n\n                Assert(LS_at_quad[i][q_point] < 1.5, ExcInternalError());\n                Assert(-1.5 < LS_at_quad[i][q_point], ExcInternalError());\n                //do the y=2x-1 switch so the -/+ still works\n                id_sum[i] += 2*LS_at_quad[i][q_point]-1;\n                if(LS_at_quad[i][q_point]-0.5< 0.01)\n                  {\n                    interface_depth= fe_values.quadrature_point(q_point);\n\n                  }\n            }\n            ++i;\n            //TODO representation of interface (0 level set or 0.5, etc.) needs to be taken\n            //into account in this averaging, as above for 0.5\n        }\n        //defining the negative to be below an interface,\n        //if a LS has takes a positive value on the cell\n        //it is added to the counter (cell is \"inside\" the layer)\n        //the innermost layer is the material id\n        int counter{0};\n        for (i=0; i<n_layers; ++i)\n        {\n\n            if(id_sum[i]>0)\n            {\n                ++counter;\n            }\n        }\n        cell->set_material_id(counter);\n\n    } // end cell loop\n    pcout<<std::endl<<\"Interface depth\"<<\n           interface_depth[1]<<std::endl;\n}\n\ntemplate <int dim>\nvoid LayerMovementProblem<dim>::assemble_matrices_P()\n{\n    TimerOutput::Scope t(computing_timer, \"assembly_P\");\n    const QGauss<dim> quadrature_formula(degree + 2);\n\n    FEValues<dim> fe_values(fe, quadrature_formula,\n                            update_values | update_gradients | 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 = quadrature_formula.size();\n\n    FullMatrix<double> cell_laplace_matrix(dofs_per_cell, dofs_per_cell);\n    FullMatrix<double> cell_mass_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    Point<dim> point_for_depth;\n\n    SedimentationRate<dim> sedRate(current_time, parameters );\n\n    std::vector<double> pressure_at_quad(n_q_points);\n    std::vector<double> overburden_at_quad(n_q_points);\n    std::vector<double> old_overburden_at_quad(n_q_points);\n    std::vector<double> old_pressure_at_quad(n_q_points);\n    std::vector<double> sedimentation_rates(n_q_points);\n\n    int material_id;\n\n    for (auto cell : filter_iterators(dof_handler.active_cell_iterators(), IteratorFilters::LocallyOwnedCell())) {\n        cell_laplace_matrix = 0;\n        cell_mass_matrix = 0;\n        cell_rhs = 0;\n\n        material_id=cell->material_id();\n\n        fe_values.reinit(cell);\n\n        fe_values.get_function_values(temp_locally_relevant_solution_P, pressure_at_quad);\n        fe_values.get_function_values(temp_locally_relevant_solution_Sigma, overburden_at_quad);\n        fe_values.get_function_values(old_locally_relevant_solution_P, old_pressure_at_quad);\n        fe_values.get_function_values(old_locally_relevant_solution_Sigma, old_overburden_at_quad);\n\n        // TODO consider moving these properties to the quad point level, not just cell level\n        const double initial_porosity = material_data.get_surface_porosity(material_id);\n        const double compaction_coefficient = material_data.get_compaction_coefficient(material_id);\n        const double initial_permeability = material_data.get_surface_permeability(material_id);\n\n        const double active_rock_density = material_data.get_solid_density(active_layer_id);\n        const double active_init_porosity = material_data.get_surface_porosity(active_layer_id);\n        const double bulk_deposit=bulkdensity (active_init_porosity, material_data.fluid_density, active_rock_density);\n\n        sedRate.value_list(fe_values.get_quadrature_points(), sedimentation_rates, 1);\n\n\n        for (unsigned int q_point = 0; q_point < n_q_points; ++q_point) {\n\n            Assert(-0.1 <overburden_at_quad[q_point], ExcInternalError());\n\n            point_for_depth = fe_values.quadrature_point(q_point);\n            const double hydrostatic =grav_acc * material_data.fluid_density *\n                                       (parameters.box_size - point_for_depth[dim-1]);\n            Assert(0 < hydrostatic, ExcInternalError());\n            const double phi = porosity(pressure_at_quad[q_point], overburden_at_quad[q_point], initial_porosity,\n                                        compaction_coefficient, hydrostatic, material_id);\n\n            Assert(0 <= phi, ExcInternalError());\n            Assert(phi < 1, ExcInternalError());\n\n           const double compress = compressibility(phi, compaction_coefficient, material_id);\n\n            const double perm_k = permeability(phi, initial_permeability, initial_porosity, material_id);\n\n            Assert(0 <= perm_k, ExcInternalError());\n            Assert(perm_k <= initial_permeability, ExcInternalError());\n\n            const double diffusion_coeff =(perm_k) *(sec_in_year) / (material_data.fluid_viscosity) ;\n            const double rhs_coeff =compress/((1.-phi)*(1.-phi));\n            const double mass_matrix_coeff = rhs_coeff;\n\n            const double additional_overburden = grav_acc*bulk_deposit*-1.*sedimentation_rates[q_point]; //[M L^-1 T^-3]\n\n\n            const double rhs_at_quad = additional_overburden - (grav_acc * material_data.fluid_density* -1.*sedimentation_rates[q_point]);\n\n            Assert (0 <= rhs_at_quad, ExcInternalError());\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                    cell_laplace_matrix(i, j) += diffusion_coeff * (fe_values.shape_grad(i, q_point)\n                                                                 * fe_values.shape_grad(j, q_point)\n                                                                 * fe_values.JxW(q_point));\n\n                    cell_mass_matrix(i, j) += mass_matrix_coeff * (fe_values.shape_value(i, q_point)\n                                                                * fe_values.shape_value(j, q_point)\n                                                                * fe_values.JxW(q_point));\n                } //end of j\n\n                cell_rhs(i) += rhs_coeff * (rhs_at_quad\n                               * fe_values.shape_value(i, q_point) * fe_values.JxW(q_point));\n            } //end of i\n        } // end q\n\n        cell->get_dof_indices(local_dof_indices);\n        constraints_P.distribute_local_to_global(cell_laplace_matrix, cell_rhs, local_dof_indices, laplace_matrix_P, rhs_P);\n        constraints_P.distribute_local_to_global(cell_mass_matrix, local_dof_indices, mass_matrix_P);\n    } // end cell\n\n    laplace_matrix_P.compress(VectorOperation::add);\n    mass_matrix_P.compress(VectorOperation::add);\n    rhs_P.compress(VectorOperation::add);\n}\n\ntemplate <int dim>\nvoid LayerMovementProblem<dim>::forge_system_P()\n{\n    // in this function we manipulate A, M, F, resulting from assemble_matrices_P\n    TimerOutput::Scope t(computing_timer, \"forge_P\");\n    LA::MPI::Vector tmp;\n    LA::MPI::Vector forcing_terms;\n\n    tmp.reinit(locally_owned_dofs, locally_relevant_dofs, mpi_communicator);\n\n    forcing_terms.reinit(locally_owned_dofs, mpi_communicator);\n\n    //the statement below is now placed into the prepare_next_time_step method\n    //old_locally_relevant_solution_P = locally_relevant_solution_P;\n\n    mass_matrix_P.vmult(system_rhs_P, old_locally_relevant_solution_P);\n\n    laplace_matrix_P.vmult(tmp, old_locally_relevant_solution_P);\n\n    system_rhs_P.add(-(1. - theta) * time_step, tmp);\n\n    forcing_terms.add(time_step * theta, rhs_P);\n\n   forcing_terms.add(time_step * (1. - theta), old_rhs_P);\n\n    system_rhs_P += forcing_terms;\n    system_rhs_P.compress (VectorOperation::add);\n\n    system_matrix_P.copy_from(mass_matrix_P);\n    // system_matrix.compress (VectorOperation::add);\n\n    system_matrix_P.add(time_step * theta, laplace_matrix_P);\n    system_matrix_P.compress(VectorOperation::add);\n}\n\ntemplate <int dim>\nvoid LayerMovementProblem<dim>::solve_time_step_P()\n{\n    TimerOutput::Scope t(computing_timer, \"solve_time_step_P\");\n\n    LA::MPI::Vector completely_distributed_solution(locally_owned_dofs, mpi_communicator);\n\n    SolverControl solver_control(dof_handler.n_dofs(), 1e-12 * system_rhs_P.l2_norm());\n    LA::SolverCG solver(solver_control, mpi_communicator);\n\n    LA::MPI::PreconditionAMG preconditioner;\n\n    LA::MPI::PreconditionAMG::AdditionalData data;\n\n    data.symmetric_operator = true;\n    preconditioner.initialize(system_matrix_P, data);\n\n    solver.solve(system_matrix_P, completely_distributed_solution, system_rhs_P, preconditioner);\n\n    pcout << \" Pressure system solved in \" << solver_control.last_step() << \" iterations.\" << std::endl;\n\n    constraints_P.distribute(completely_distributed_solution);\n\n    temp_locally_relevant_solution_P = completely_distributed_solution;\n}\n\ntemplate <int dim>\nvoid LayerMovementProblem<dim>::assemble_matrices_T()\n{\n  //TODO retool the rhs and fix the forge sign problem\n    TimerOutput::Scope t(computing_timer, \"assembly_T\");\n    const QGauss<dim> quadrature_formula(degree + 2);\n    const QGauss<dim - 1> face_quadrature_formula(degree + 1);\n\n    FEValues<dim> fe_values(fe, quadrature_formula,\n                            update_values | update_gradients | update_quadrature_points | update_JxW_values);\n    FEFaceValues<dim> fe_face_values(fe, face_quadrature_formula,\n                                     update_values | update_quadrature_points | update_normal_vectors |\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    const unsigned int n_face_q_points = face_quadrature_formula.size();\n\n    FullMatrix<double> cell_laplace_matrix(dofs_per_cell, dofs_per_cell);\n    FullMatrix<double> cell_mass_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    Point<dim> point_for_depth;\n\n    std::vector<double> pressure_at_quad(n_q_points);\n    std::vector<double> overburden_at_quad(n_q_points);\n    std::vector<double> bulkheat_capacity_at_quad(n_q_points);\n    std::vector<double> thermal_conductivity_at_quad(n_q_points);\n\n    int material_id;\n\n    for (auto cell : filter_iterators(dof_handler.active_cell_iterators(), IteratorFilters::LocallyOwnedCell())) {\n        cell_laplace_matrix = 0;\n        cell_mass_matrix = 0;\n        cell_rhs = 0;\n\n        material_id = cell->material_id();\n\n        fe_values.reinit(cell);\n        fe_values.get_function_values(locally_relevant_solution_P, pressure_at_quad);\n        fe_values.get_function_values(locally_relevant_solution_Sigma, overburden_at_quad);\n\n        // TODO consider moving these properties to the quad point level, not just cell level\n        const double initial_porosity = material_data.get_surface_porosity(cell->material_id());\n        const double compaction_coefficient = material_data.get_compaction_coefficient(cell->material_id());\n        const double rock_density = material_data.get_solid_density(cell->material_id());\n        const double heat_capacity = material_data.get_heat_capacity(cell->material_id());\n  //      const double ther\n\n        for (unsigned int q_point = 0; q_point < n_q_points; ++q_point) {\n            point_for_depth = fe_values.quadrature_point(q_point);\n            const double hydrostatic = grav_acc * material_data.fluid_density *\n                                       (parameters.box_size - point_for_depth[dim-1]); \n            const double phi = porosity(pressure_at_quad[q_point], overburden_at_quad[q_point], initial_porosity,\n                                        compaction_coefficient, hydrostatic, material_id);\n            //Assert(0 < phi < 1, ExcInternalError());\n\n            const double rho_b = bulkdensity(phi, material_data.fluid_density, rock_density);\n            const double bulk_hc = bulkheatcapacity(phi, material_data.fluid_heat_capacity, heat_capacity);\n\n            //      fe_values.get_function_values(thermal_conductivity, thermal_conductivity_at_quad);\n            // TODO\n            const double diff_coeff_at_quad = thermal_conductivity_at_quad[q_point]\n                                                /(bulk_hc\n                                                  *rho_b );\n            const double rhs_at_quad = 0; // TODO bottom boundary flux from parameter file\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                    cell_laplace_matrix(i, j) += diff_coeff_at_quad * fe_values.shape_grad(i, q_point) *\n                                                 fe_values.shape_grad(j, q_point) * fe_values.JxW(q_point);\n\n                    cell_mass_matrix(i, j) += (rho_b * bulk_hc * fe_values.shape_value(i, q_point) *\n                                               fe_values.shape_value(j, q_point) * fe_values.JxW(q_point));\n                } // end j\n\n                //          cell_rhs(i) += (right_hand_side.value(fe_values.quadrature_point(q_point)) *\n                //                          fe_values.shape_value(i, q_point) * fe_values.JxW(q_point));\n                cell_rhs(i) += (rhs_at_quad * fe_values.shape_value(i, q_point) * fe_values.JxW(q_point));\n\n            }   // end i\n        }     // end q\n\n        for (unsigned int face_number = 0; face_number < GeometryInfo<dim>::faces_per_cell; ++face_number) {\n            if (cell->face(face_number)->at_boundary() &&\n                    (cell->face(face_number)->boundary_id() == 2)) // bottom of domain TODO remove raw number\n            {\n                fe_face_values.reinit(cell, face_number);\n                for (unsigned int q_point = 0; q_point < n_face_q_points; ++q_point) {\n                    //                const double neumann_value\n                    //                  = (exact_solution.gradient (fe_face_values.quadrature_point(q_point)) *\n                    //                     fe_face_values.normal_vector(q_point));\n                    // TODO pick the right flux value\n                    const double neumann_value = 100; // represents the bottom flux boundary condition\n                    for (unsigned int i = 0; i < dofs_per_cell; ++i) {\n                        cell_rhs(i) += (neumann_value * fe_face_values.shape_value(i, q_point) * fe_face_values.JxW(q_point));\n                    }\n                }\n            }\n        } // end face loop\n\n        cell->get_dof_indices(local_dof_indices);\n        constraints_T.distribute_local_to_global(cell_laplace_matrix, cell_rhs, local_dof_indices, laplace_matrix_T, rhs_T);\n        constraints_T.distribute_local_to_global(cell_mass_matrix, local_dof_indices, mass_matrix_T);\n    } // end cell\n\n    laplace_matrix_T.compress(VectorOperation::add);\n    mass_matrix_T.compress(VectorOperation::add);\n    rhs_T.compress(VectorOperation::add);\n}\n\ntemplate <int dim>\nvoid LayerMovementProblem<dim>::forge_system_T()\n{\n    // in this function we manipulate A, M, F, resulting from assemble_matrices_T\n    TimerOutput::Scope t(computing_timer, \"forge_T\");\n    LA::MPI::Vector tmp;\n    LA::MPI::Vector forcing_terms;\n\n    tmp.reinit(locally_owned_dofs, locally_relevant_dofs, mpi_communicator);\n\n    forcing_terms.reinit(locally_owned_dofs, mpi_communicator);\n\n    //old_locally_relevant_solution_T = locally_relevant_solution_T;\n    mass_matrix_T.vmult(system_rhs_T, old_locally_relevant_solution_T);\n\n    laplace_matrix_T.vmult(tmp, old_locally_relevant_solution_T);\n    //  pcout << \"laplace symmetric: \" << laplace_matrix.is_symmetric()<<std::endl;\n    system_rhs_T.add(-(1. - theta) * time_step, tmp);\n\n    forcing_terms.add(time_step * theta, rhs_T);\n\n   forcing_terms.add(time_step * (1. - theta), old_rhs_T);\n\n    system_rhs_T += forcing_terms;\n   // system_matrix.compress (VectorOperation::add);\n\n    system_matrix_T.copy_from(mass_matrix_T);\n    // system_matrix.compress (VectorOperation::add);\n\n    system_matrix_T.add(laplace_matrix_T, time_step * theta);\n}\n\ntemplate <int dim>\nvoid LayerMovementProblem<dim>::solve_time_step_T()\n{\n    TimerOutput::Scope t(computing_timer, \"solve_time_step_T\");\n\n    LA::MPI::Vector completely_distributed_solution(locally_owned_dofs, mpi_communicator);\n\n    SolverControl solver_control(dof_handler.n_dofs(), 1e-12 * system_rhs_T.l2_norm());\n    LA::SolverCG solver(solver_control, mpi_communicator);\n\n    LA::MPI::PreconditionAMG preconditioner;\n\n    LA::MPI::PreconditionAMG::AdditionalData data;\n\n    data.symmetric_operator = true;\n    preconditioner.initialize(system_matrix_T, data);\n\n    solver.solve(system_matrix_T, completely_distributed_solution, system_rhs_T, preconditioner);\n\n    pcout << \" Temperature system solved in \" << solver_control.last_step() << \" iterations.\" << std::endl;\n\n    constraints_T.distribute(completely_distributed_solution);\n\n    locally_relevant_solution_T = completely_distributed_solution;\n}\n\n\ntemplate <int dim>\nbool LayerMovementProblem<dim>::estimate_nl_error()\n{\n\n}\n\n\n\ntemplate <int dim>\nvoid LayerMovementProblem<dim>::prepare_next_time_step()\n{\n    old_locally_relevant_solution_P=locally_relevant_solution_P;\n    old_locally_relevant_solution_Sigma=locally_relevant_solution_Sigma;\n    old_locally_relevant_solution_T=locally_relevant_solution_T;\n    old_rhs_P=rhs_P;\n    old_rhs_T=rhs_T;\n}\n\ntemplate <int dim>\nvoid LayerMovementProblem<dim>::output_vectors_LS()\n{\n    TimerOutput::Scope t(computing_timer, \"output_LS\");\n    DataOut<dim> data_out;\n    data_out.attach_dof_handler(dof_handler_LS);\n    int i=0;\n    for( auto & layer_sol : layers_solutions)\n    {\n        std::string layer_out = \"LS\"+  Utilities::int_to_string(i, 3);\n        data_out.add_data_vector(*layer_sol, layer_out);\n        ++i;\n    }\n//    LA::MPI::Vector ng_material_kind;\n//    ng_material_kind.reinit(locally_owned_dofs,  mpi_communicator);\n//    LA::MPI::Vector g_material_kind;\n//    g_material_kind.reinit(locally_owned_dofs,locally_relevant_dofs,  mpi_communicator);\n\n//    //std::vector<unsigned int> material_kind(triangulation.n_active_cells());\n//     i = 0;\n//    for (auto cell : filter_iterators(triangulation.active_cell_iterators(), IteratorFilters::LocallyOwnedCell())) {\n//    ng_material_kind[i]=cell->material_id();\n//      ++i;\n//    }\n//    ng_material_kind.compress(VectorOperation::insert);\n//    g_material_kind=ng_material_kind;\n//    ComputePorosity<dim> porosity;\n\n\n\n    data_out.add_data_vector(locally_relevant_solution_LS_0, \"LS\");\n    Vector<float> subdomain(triangulation.n_active_cells());\n    for (unsigned int i = 0; i < subdomain.size(); ++i)\n        subdomain(i) = triangulation.locally_owned_subdomain();\n    data_out.add_data_vector(subdomain, \"subdomain\");\n\n    data_out.build_patches();\n\n    const std::string filename = (\"sol_LS_vectors-\" + Utilities::int_to_string(output_number, 3) + \".\" +\n                                  Utilities::int_to_string(triangulation.locally_owned_subdomain(), 4));\n    std::ofstream output((filename + \".vtu\").c_str());\n    data_out.write_vtu(output);\n\n    if (Utilities::MPI::this_mpi_process(mpi_communicator) == 0) {\n        std::vector<std::string> filenames;\n        for (unsigned int i = 0; i < Utilities::MPI::n_mpi_processes(mpi_communicator); ++i)\n            filenames.push_back(\"sol_LS_vectors-\" + Utilities::int_to_string(output_number, 3) + \".\" +\n                                Utilities::int_to_string(i, 4) + \".vtu\");\n\n        std::ofstream master_output((\"sol_LS_vectors-\" + Utilities::int_to_string(output_number, 3) + \".pvtu\").c_str());\n        data_out.write_pvtu_record(master_output, filenames);\n    }\n}\n\n\n\ntemplate <int dim>\nvoid LayerMovementProblem<dim>::output_vectors()\n{\n    TimerOutput::Scope t(computing_timer, \"output\");\n    // output_number++;\n    DataOut<dim> data_out;\n    data_out.attach_dof_handler(dof_handler);\n    data_out.add_data_vector(locally_relevant_solution_P, \"P\");\n    data_out.add_data_vector(old_locally_relevant_solution_P, \"old_P\");\n    data_out.add_data_vector(locally_relevant_solution_T, \"T\");\n    data_out.add_data_vector(old_locally_relevant_solution_T, \"old_T\");\n    data_out.add_data_vector(locally_relevant_solution_Sigma, \"Sigma\");\n    data_out.add_data_vector(old_locally_relevant_solution_Sigma, \"old_Sigma\");\n    data_out.add_data_vector(locally_relevant_solution_F, \"F\");\n    data_out.add_data_vector(temp_locally_relevant_solution_P, \"temp_P\");\n    data_out.add_data_vector(temp_locally_relevant_solution_Sigma, \"temp_sigma\");\n\n//  data_out.add_data_vector(system_rhs_P, \"s_rhs_P\");\n//  data_out.add_data_vector(rhs_F, \"rhs_F\" );\n//  data_out.add_data_vector(rhs_Sigma, \"rhs_s\");\n\n\n\n//      Vector<float> material_id(triangulation.n_active_cells());\n//      for (unsigned int i = 0; i < material_id.size(); ++i)\n//          material_id(i) = cell->material_id();\n//      data_out.add_data_vector(material_id, \"material_id\");\n\n    Vector<float> subdomain(triangulation.n_active_cells());\n    for (unsigned int i = 0; i < subdomain.size(); ++i)\n        subdomain(i) = triangulation.locally_owned_subdomain();\n    data_out.add_data_vector(subdomain, \"subdomain\");\n\n    data_out.build_patches();\n\n    const std::string filename = (\"sol_vectors-\" + Utilities::int_to_string(output_number, 3) + \".\" +\n                                  Utilities::int_to_string(triangulation.locally_owned_subdomain(), 4));\n    std::ofstream output((filename + \".vtu\").c_str());\n    data_out.write_vtu(output);\n\n    if (Utilities::MPI::this_mpi_process(mpi_communicator) == 0) {\n        std::vector<std::string> filenames;\n        for (unsigned int i = 0; i < Utilities::MPI::n_mpi_processes(mpi_communicator); ++i)\n            filenames.push_back(\"sol_vectors-\" + Utilities::int_to_string(output_number, 3) + \".\" +\n                                Utilities::int_to_string(i, 4) + \".vtu\");\n\n        std::ofstream master_output((\"sol_vectors-\" + Utilities::int_to_string(output_number, 3) + \".pvtu\").c_str());\n        data_out.write_pvtu_record(master_output, filenames);\n    }\n}\n\ntemplate <int dim>\nint LayerMovementProblem<dim>::active_layers_in_time (double time)\n{\n//  //TODO bool flag\n//  //equitemporal division over layers\n//  for (int i=1;i<=n_layers;++i)\n//    {\n//      double current_fraction= static_cast<double>(i)/(n_layers);\n//      if(time<(current_fraction*final_time))\n//        {\n//          pcout<<\"layer\"<<i<<std::endl;\n//          active_layer_id=i;\n//          return i;\n\n//        }\n\n//    }\n  //draw from parameter file\n  //Do time division by specified depositional period.\n  //std::vector<double> sum_phases(n_layers, 0);\n  double sum_depositional_times=0;\n  for (int i=1; i<=n_layers; ++i)\n    {\n      double layer_time = material_data.get_depositional_period(i);\n      sum_depositional_times+=layer_time*1e6;\n      if(time<sum_depositional_times)\n        {\n          pcout<<\"layer\"<<i<<std::endl;\n          active_layer_id=i;\n          return i;\n        }\n\n    }\n\n\n\n}\n\n\n\n\ntemplate <int dim>\nclass LayerMovementProblem<dim>::Postprocessor : public DataPostprocessor<dim>\n{\npublic:\n  Postprocessor (const CPPLS::MaterialData& material_data,\n                 const CPPLS::Parameters& parameters);\n  virtual\n  void\n  evaluate_vector_field\n  (const DataPostprocessorInputs::Vector<dim> &inputs,\n   std::vector<Vector<double> >               &computed_quantities) const override;\n  virtual std::vector<std::string> get_names () const override;\n  virtual\n  std::vector<DataComponentInterpretation::DataComponentInterpretation>\n  get_data_component_interpretation () const override;\n  virtual UpdateFlags get_needed_update_flags () const override;\nprivate:\n  const CPPLS::MaterialData& material_data;\n  const CPPLS::Parameters& parameters;\n};\ntemplate <int dim>\nLayerMovementProblem<dim>::Postprocessor::\nPostprocessor (const CPPLS::MaterialData& material_data,\n               const CPPLS::Parameters& parameters)\n  :\n  material_data (material_data),\n  parameters (parameters)\n{}\ntemplate <int dim>\nstd::vector<std::string>\nLayerMovementProblem<dim>::Postprocessor::get_names() const\n{\n  std::vector<std::string> solution_names;\n\n  solution_names.push_back (\"porosity\");\n  solution_names.push_back (\"permeability\");\n  solution_names.push_back (\"VES\");\n  solution_names.push_back (\"material\");\n  solution_names.push_back (\"hydrostatic\");\n  solution_names.push_back (\"overpressure\");\n  solution_names.push_back (\"overburden\");\n  solution_names.push_back (\"pore_pressure\");\n  solution_names.push_back (\"speed_function\");\n\n\n\n  //solution_names.push_back (\"T\");\n\n  return solution_names;\n}\ntemplate <int dim>\nstd::vector<DataComponentInterpretation::DataComponentInterpretation>\nLayerMovementProblem<dim>::Postprocessor::\nget_data_component_interpretation () const\n{\n  std::vector<DataComponentInterpretation::DataComponentInterpretation>\n  interpretation;\n  interpretation.push_back (DataComponentInterpretation::component_is_scalar);\n  interpretation.push_back (DataComponentInterpretation::component_is_scalar);\n  interpretation.push_back (DataComponentInterpretation::component_is_scalar);\n  interpretation.push_back (DataComponentInterpretation::component_is_scalar);\n  interpretation.push_back (DataComponentInterpretation::component_is_scalar);\n  interpretation.push_back (DataComponentInterpretation::component_is_scalar);\n  interpretation.push_back (DataComponentInterpretation::component_is_scalar);\n  interpretation.push_back (DataComponentInterpretation::component_is_scalar);\n  interpretation.push_back (DataComponentInterpretation::component_is_scalar);\n\n  return interpretation;\n}\ntemplate <int dim>\nUpdateFlags\nLayerMovementProblem<dim>::Postprocessor::get_needed_update_flags() const\n{\n  return update_values | update_gradients | update_q_points;\n}\ntemplate <int dim>\nvoid\nLayerMovementProblem<dim>::Postprocessor::\nevaluate_vector_field\n(const DataPostprocessorInputs::Vector<dim> &inputs,\n std::vector<Vector<double> >               &computed_quantities) const\n{\n  const unsigned int n_quadrature_points = inputs.solution_values.size();\n  Assert (inputs.solution_gradients.size() == n_quadrature_points,\n          ExcInternalError());\n  Assert (computed_quantities.size() == n_quadrature_points,\n          ExcInternalError());\n  Assert (inputs.solution_values[0].size() == 3,\n          ExcInternalError());\n\n    //cell properties\n  const typename DoFHandler<dim>::cell_iterator\n    current_cell = inputs.template get_cell<DoFHandler<dim>>();\n  const unsigned int mat_id = current_cell->material_id();\n//  const Point<dim> center = current_cell->center();\n//  const double depth = parameters.box_size- center[1];\n\n  const double initial_porosity = material_data.get_surface_porosity(mat_id);\n  const double compaction_coefficient = material_data.get_compaction_coefficient(mat_id);\n  const double initial_permeability = material_data.get_surface_permeability(mat_id);\n\n  for (unsigned int q=0; q<n_quadrature_points; ++q)\n    {\n      //point values\n      const Point<dim> point_for_depth = inputs.evaluation_points[q];\n      const double hydrostatic = 9.81*material_data.fluid_density*(parameters.box_size - point_for_depth[dim-1]);//point_for_depth;\n\n      //relabel the incoming components\n      const double overpressure=inputs.solution_values[q](0);\n      const double sigma = inputs.solution_values[q](1);\n      const double speed_function = inputs.solution_values[q](2);\n      double porosity_return_value;\n\n\n    //TODO: using the std::function in the LayerMovementProblem class is not working within this inherited DataPostProcessor class\n    // so as a work around we branch based on input file\n//      //porosity\n//      computed_quantities[q](0)\n//          = LayerMovementProblem<dim>::porosity(overpressure, sigma, initial_porosity, compaction_coefficient, hydrostatic);\n\n      //porosity\n\n\n      if (parameters.linear_in_void_ratio)\n      {\n          //below is LINEAR IN VOID RATIO\n           const double init_void_ratio = initial_porosity/(1.-initial_porosity);\n           const double computed_void_ratio = init_void_ratio - compaction_coefficient*(sigma - overpressure - hydrostatic);\n\n           // Assert(init_void_ratio >= computed_void_ratio, ExcInternalError());\n\n            porosity_return_value=(computed_void_ratio/(1.+computed_void_ratio));\n\n      }\n      //Athy's law\n      else\n      {\n            porosity_return_value=initial_porosity *\n                (std::exp(-1. * compaction_coefficient * (sigma - overpressure - hydrostatic)));\n      }\n       if(mat_id ==0) {porosity_return_value=initial_porosity;}\n      //porosity\n      computed_quantities[q](0)=porosity_return_value;\n\n\n\n      //permeability\n      computed_quantities[q](1)\n          = CPPLS::permeability(computed_quantities[q](0), initial_permeability, initial_porosity, mat_id);\n      //VES\n      computed_quantities[q](2)\n          = CPPLS::VES(sigma, overpressure, hydrostatic, mat_id);\n      //material_id\n      computed_quantities[q](3)\n          =mat_id;\n      computed_quantities[q](4)\n          =hydrostatic;\n      computed_quantities[q](5)\n          =overpressure;\n      computed_quantities[q](6)\n          =sigma;\n      computed_quantities[q](7)\n          =overpressure+hydrostatic;\n      computed_quantities[q](8)\n          =speed_function;\n\n\n\n    }\n}\ntemplate <int dim>\nvoid LayerMovementProblem<dim>::output_results_pp ()\n{\n  TimerOutput::Scope t(computing_timer, \"output_pp\");\n  //computing_timer.enter_section (\"Postprocessing\");\n  //the purpose of this is to create a vector-valued solution vector, composed of\n  //gluing together the scalar solution vectors(i.e., pressure, overburden and speed function)\n  //for use in the Postprocessor class.\n  //Note these all share one DoFHandler (i.e., dof_handler), so there might be a better way to make the\n  //vector-valued solution.\n  //The current method would allow for joining in the dof_handler_LS solution vectors\n\n\n  const FESystem<dim> joint_fe(fe, 1, fe, 1, fe, 1);\n  //FESystem<dim, dim> joint_fe (FE_Q<dim>(2), 2);\n\n  DoFHandler<dim> joint_dof_handler (triangulation);\n  joint_dof_handler.distribute_dofs (joint_fe);\n  Assert (joint_dof_handler.n_dofs() ==\n          dof_handler.n_dofs()*3,\n          ExcInternalError());\n  LA::MPI::Vector joint_solution;\n  joint_solution.reinit (joint_dof_handler.locally_owned_dofs(), mpi_communicator);\n  {\n    std::vector<types::global_dof_index> local_joint_dof_indices (joint_fe.dofs_per_cell);\n    std::vector<types::global_dof_index> local_dof_indices (fe.dofs_per_cell);\n\n    //std::vector<types::global_dof_index> 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    cell      = dof_handler.begin_active();\n//    temperature_cell = temperature_dof_handler.begin_active();\n    for (; joint_cell!=joint_endc;\n         ++joint_cell, ++cell/*, ++temperature_cell*/)\n      if (joint_cell->is_locally_owned())\n        {\n          joint_cell->get_dof_indices (local_joint_dof_indices);\n          cell->get_dof_indices (local_dof_indices);\n//          temperature_cell->get_dof_indices (local_temperature_dof_indices);\n          for (unsigned int i=0; i<joint_fe.dofs_per_cell; ++i)\n            {\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_dof_indices.size(),\n                        ExcInternalError());\n                joint_solution(local_joint_dof_indices[i])\n                  = locally_relevant_solution_P(local_dof_indices\n                                    [joint_fe.system_to_base_index(i).second]);\n              }\n            else if (joint_fe.system_to_base_index(i).first.first == 1)\n              {\n\n                Assert (joint_fe.system_to_base_index(i).second\n                        <\n                        local_dof_indices.size(),\n                        ExcInternalError());\n                joint_solution(local_joint_dof_indices[i])\n                  = locally_relevant_solution_Sigma(local_dof_indices\n                                         [joint_fe.system_to_base_index(i).second]);\n              }\n              else\n              {\n                Assert (joint_fe.system_to_base_index(i).first.first == 2,\n                        ExcInternalError());\n                Assert (joint_fe.system_to_base_index(i).second\n                        <\n                        local_dof_indices.size(),\n                        ExcInternalError());\n                joint_solution(local_joint_dof_indices[i])\n                  = locally_relevant_solution_F(local_dof_indices\n                                         [joint_fe.system_to_base_index(i).second]);\n\n\n               }\n\n            }\n        }\n  }\n\n  joint_solution.compress(VectorOperation::insert);\n  IndexSet locally_relevant_joint_dofs(joint_dof_handler.n_dofs());\n  DoFTools::extract_locally_relevant_dofs (joint_dof_handler, locally_relevant_joint_dofs);\n  LA::MPI::Vector locally_relevant_joint_solution;\n\n  locally_relevant_joint_solution.reinit (joint_dof_handler.locally_owned_dofs(), locally_relevant_joint_dofs, mpi_communicator);\n  locally_relevant_joint_solution = joint_solution;\n  Postprocessor postprocessor ( material_data, parameters);\n  DataOut<dim> data_out;\n  data_out.attach_dof_handler (joint_dof_handler);\n  data_out.add_data_vector (locally_relevant_joint_solution, postprocessor);\n  data_out.build_patches ();\n  static int out_index=0;\n  const std::string filename = (\"solution-\" +\n                                Utilities::int_to_string (out_index, 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  if (Utilities::MPI::this_mpi_process(mpi_communicator) == 0)\n    {\n      std::vector<std::string> filenames;\n      for (unsigned int i=0; i<Utilities::MPI::n_mpi_processes(mpi_communicator); ++i)\n        filenames.push_back (std::string(\"solution-\") +\n                             Utilities::int_to_string (out_index, 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 (out_index, 5) +\n                              \".pvtu\");\n      std::ofstream pvtu_master (pvtu_master_filename.c_str());\n      data_out.write_pvtu_record (pvtu_master, filenames);\n//      const std::string\n//      visit_master_filename = (\"solution-\" +\n//                               Utilities::int_to_string (out_index, 5) +\n//                               \".visit\");\n//      std::ofstream visit_master (visit_master_filename.c_str());\n//      DataOutBase::write_visit_record (visit_master, filenames);\n    }\n  //computing_timer.exit_section ();\n out_index++;\n}\n\n\ntemplate <int dim>\nvoid LayerMovementProblem<dim>::prepare_advance_old_vectors()\n{\n  //This method ensures that the M^-1 and B matrices are constructed\n  TimerOutput::Scope t(computing_timer, \"prepare to advance old vectors\");\n\n  //The idea is that we have to update the existing vector by multiplication of it with (I + M^-1 B)\n  //Where M^-1 is the inverse of the mass matrix\n  //This can be computed by solving a CG system for it.\n  //This needs to be solved whenever basis changes (i.e. a grid refinement)\n  //The B matrix can be computed whenever speed function F changes\n\n  //we just do it at same time\n\n//  if(compute_inv_mass_matrix)\n//  {\n//       compute_inverse_mass_matrix();\n//  }\n//  compute_inv_mass_matrix=false;\n\n\n   const AdvectionField<dim> advection_field;\n\n   const QGauss<dim>  quadrature_formula(degree+2);\n   FEValues<dim> fe_values (fe, quadrature_formula,\n                            update_values | update_gradients |\n                            update_quadrature_points |\n                            update_JxW_values);\n   const unsigned int   dofs_per_cell = fe.dofs_per_cell;\n   const unsigned int   n_q_points    = quadrature_formula.size();\n   FullMatrix<double>   cell_B_matrix (dofs_per_cell, dofs_per_cell);\n   FullMatrix<double>   cell_mass_matrix (dofs_per_cell, dofs_per_cell);\n   std::vector<types::global_dof_index> local_dof_indices (dofs_per_cell);\n\n    std::vector<Tensor<1, dim>> advection_directions(n_q_points);\n    std::vector<double> speed_at_quad(n_q_points);\n\n\n   for (auto cell : filter_iterators(dof_handler.active_cell_iterators(),\n                                     IteratorFilters::LocallyOwnedCell()))\n   {\n\n\n        cell_B_matrix = 0;\n        cell_mass_matrix =0;\n        fe_values.reinit (cell);\n\n\n        advection_field.value_list(fe_values.get_quadrature_points(), advection_directions);\n        fe_values.get_function_values(locally_relevant_solution_F, speed_at_quad);\n\n        const double delta = 1 * cell->diameter();\n\n\n        for (unsigned int q_point=0; q_point<n_q_points; ++q_point)\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                       cell_B_matrix(i,j) += time_step* speed_at_quad[q_point] *\n                            (fe_values.shape_value(i, q_point)+ delta *(advection_directions[q_point])*fe_values.shape_grad(i,q_point)) *\n\n                                            (advection_directions[q_point] *\n                                            fe_values.shape_grad(j,q_point)) *\n                                            fe_values.JxW(q_point);\n\n                       cell_mass_matrix(i,j) +=  (fe_values.shape_value(i, q_point)+ delta *(advection_directions[q_point])*fe_values.shape_grad(i,q_point))\n                                               * fe_values.shape_value(j, q_point)\n                                               * fe_values.JxW(q_point);\n                   }\n\n               }\n          }\n          cell->get_dof_indices (local_dof_indices);\n\n          constraints_shift.distribute_local_to_global (cell_B_matrix,\n                                                  local_dof_indices,\n                                                  system_B_matrix);\n\n          constraints_shift.distribute_local_to_global (cell_mass_matrix,\n                                                  local_dof_indices,\n                                                  mass_matrix);\n\n      } //end cell\n\n    system_B_matrix.compress (VectorOperation::add);\n    mass_matrix.compress (VectorOperation::add);\n\n}\n\n\ntemplate <int dim>\nvoid LayerMovementProblem<dim>::advance_old_vectors( LA::MPI::Vector &locally_relevant_vector)\n{\n  TimerOutput::Scope t(computing_timer, \"advance old vectors\");\n\n  //must be a NONZERO vector for linear system to have solution\n\n\n  //precondition: have M and B matrices. We form the linear system MU^{k+1}=(M+B)U^{k}\n  // and solve with CG for U^{k+1}\n\n  //postcondtion: U will be \"shifted\" locally by the amount dt*F, thus bringing the old_values\n  //              onto the current time step's computational grid.\n  //              This is a complement to updating the material ids of the cells\n\n\n    LA::MPI::Vector tmp;\n    LA::MPI::Vector tmp2;\n    LA::MPI::Vector rhs_terms;\n    LA::MPI::Vector rhs;\n    tmp.reinit(locally_owned_dofs, locally_relevant_dofs, mpi_communicator);\n    tmp2.reinit(locally_owned_dofs, locally_relevant_dofs, mpi_communicator);\n\n    rhs_terms.reinit(locally_owned_dofs,locally_relevant_dofs, mpi_communicator);\n    rhs.reinit(locally_owned_dofs, mpi_communicator);\n\n\n    //M*U\n    mass_matrix.vmult(tmp, old_locally_relevant_solution_P);\n\n//    rhs_terms.add(1, tmp);\n//    rhs_terms.compress(VectorOperation::add);\n\n    rhs=tmp;\n    //B*U\n    //tmp.reinit(locally_owned_dofs, locally_relevant_dofs, mpi_communicator);\n    system_B_matrix.vmult(tmp2, old_locally_relevant_solution_P);\n    rhs += tmp2;\n//    system_B_matrix.compress(VectorOperation::add);\n//    rhs_terms.add(1, tmp);\n//    rhs_terms.compress(VectorOperation::add);\n    //rhs=rhs_terms;\n\n    LA::MPI::Vector completely_distributed_solution(locally_owned_dofs, mpi_communicator);\n\n    SolverControl solver_control(dof_handler.n_dofs(), 1e-12 * rhs.l2_norm());\n    //LA::SolverCG solver(solver_control, mpi_communicator);\n    LA::SolverGMRES solver(solver_control, mpi_communicator);\n\n    //LA::MPI::PreconditionAMG preconditioner;\n    //LA::MPI::PreconditionAMG::AdditionalData data;\n    //LA::MPI::PreconditionSSOR preconditioner;\n    //LA::MPI::PreconditionSSOR::AdditionalData data;\n    PETScWrappers::PreconditionBlockJacobi preconditioner;\n    PETScWrappers::PreconditionBlockJacobi::AdditionalData data;\n    //data.symmetric_operator = true;\n    preconditioner.initialize(mass_matrix, data);\n\n    solver.solve(mass_matrix, completely_distributed_solution, rhs, preconditioner);\n\n    pcout << \" Advance vector mass matrix system solved in \" << solver_control.last_step() << \" iterations.\" << std::endl;\n\n   constraints_shift.distribute(completely_distributed_solution);\n\n   old_locally_relevant_solution_P = completely_distributed_solution;\n   //old_locally_relevant_solution_P.compress(VectorOperation::add);\n\n\n}\n\n\n\ntemplate <int dim>\nvoid LayerMovementProblem<dim>::compute_hydrostatic_thicknesses()\n{\n\n\n\n\n\n}\n\n\ntemplate <int dim>\nvoid LayerMovementProblem<dim>::run()\n{\n\n  pcout<<\"CPPLS running in \"<<dim<<\" dimensions\"<<std::endl;\n  sec_in_year=60*60*24*365.25;\n  grav_acc=9.81;\n\n\n    //this sets porosity, compressibility, permeability based on choices in parameter file\n    set_physical_functions();\n\n\n    // common mesh\n    setup_geometry();\n    // common dofhandler, except for LS\n    setup_dofs();\n    // these are the 4 systems treated in this code\n    setup_system_P();\n    setup_system_T();\n    setup_system_Sigma();\n    setup_system_F();\n    old_locally_relevant_solution_F.reinit(locally_owned_dofs, locally_relevant_dofs, mpi_communicator);\n    // the solution of this system is done in the LevelSetSolver class\n    setup_system_LS();\n    setup_system_shift();\n\n    initial_conditions();\n\n    bool compute_inv_mass_matrix = true;\n\n\n    const unsigned int output_interval= parameters.output_interval;\n    const bool compute_temperature = parameters.compute_temperature;\n\n    const double tolerance = parameters.nl_tol;\n    const unsigned int maxiter = parameters.maxiter;\n\n    //const SedimentationRate SedRate(parameters);\n    const double base_sedimentation_rate = parameters.base_sedimentation_rate;\n    // initialize level set solver\n    // we use some hardcode defaults for now\n\n    min_h = GridTools::minimal_cell_diameter(triangulation) / std::sqrt(2);\n\n    //We make the following choice. We set the cfl condition to 1/2 and then we have the\n    //Level set run twice. So the dt for the level set solver is dt_physics=2*dt_ls\n\n    //n_reps is for the number of repetitions of the LS time stepping per \"physical time step\"\n    //The CFL is independent of this.\n    const double n_reps=parameters.n_reps;\n    const double cfl =parameters.cfl;\n    const double umax = base_sedimentation_rate;  //max_sedRate\n    const double time_step_ls = cfl * min_h / umax;\n    time_step=n_reps*time_step_ls/cfl;\n    const double n_marches = n_reps/cfl;\n    // pcout<<\"min_h\"<<min_h;\n\n\n    const double cK = 1.0;//compression coeff\n    const double cE = 1.0;//entropy-visc coeff (non-dimensional cf. p 452 (around eq 18) Guermond, 2017)\n    const bool verbose = true;\n    std::string ALGORITHM = \"MPP_uH\";\n    const unsigned int TIME_INTEGRATION = 1; // corresponds to SSP33\n   // const unsigned int TIME_INTEGRATION = 0; // corresponds to explicit euler\n\n\n    n_layers=parameters.n_layers;\n    int n_active_layers=0;\n\n\n    // BOUNDARY CONDITIONS FOR LS\n    get_boundary_values_LS(boundary_values_id_LS, boundary_values_LS);\n\n    locally_relevant_solution_F = -1.*base_sedimentation_rate;\n\n\n    //assume locally_relevant_solution_LS_0 is a good initial value for all level sets\n\n    for(int i=0; i<n_layers; ++i)\n    {\n        layers.emplace_back(new LevelSetSolver<dim>(degree_LS, degree, time_step_ls,\n                            cK, cE, verbose, ALGORITHM, TIME_INTEGRATION,\n                            triangulation, mpi_communicator,\n                            dof_handler, dof_handler_LS, computing_timer, i));\n        layers_solutions.emplace_back(new LA::MPI::Vector);\n        layers_solutions[i]->reinit(locally_owned_dofs_LS, locally_relevant_dofs_LS, mpi_communicator);\n\n        layers[i]->set_boundary_conditions(boundary_values_id_LS, boundary_values_LS);\n        if(dim==3){\n        layers[i]->initial_condition(locally_relevant_solution_LS_0, locally_relevant_solution_Wxy,\n                                     locally_relevant_solution_Wxy, locally_relevant_solution_F);\n          }\n        else\n          {\n            layers[i]->initial_condition(locally_relevant_solution_LS_0, locally_relevant_solution_Wxy,\n                                        locally_relevant_solution_F);\n\n          }\n    }\n\n    display_vectors();\n\n    // TIME STEPPING\n    timestep_number = 0;\n    for (double time = time_step; time <= final_time; time += time_step, ++timestep_number) {\n        pcout << \"Time step \" << timestep_number << \" at t=\" << time <<\"year: \"<<time<<\"Ma\"<< std::endl;\n        pcout<< \" % complete:\"<<100.*(timestep_number*time_step)/final_time<<std::endl; //for constant time_step\n        Assert (time_step< final_time, ExcNotImplemented());\n\n        current_time=time;\n\n        // Solve for F the scalar speed function which is passed to the LevelSetSolver\n        // which expects the vector (wx,wy) or (wx,wy,wz)\n        // dim=2 we pass F as wy and dim=3 we pass F as wz with 0 otherwise\n\n        // Level set computation\n        // original level_set_solver.set_velocity(locally_relevant_solution_u, locally_relevant_solution_v);\n         n_active_layers=active_layers_in_time(time);\n\n        //We evolve the ls TWO times  per time_step for the physics\n         //DEBUG CONSTANT SPEED\n         //locally_relevant_solution_F = -1.*base_sedimentation_rate;\n         for(int h=0;h<n_marches;++h)\n          {\n            TimerOutput::Scope t(computing_timer, \"Total LS\");\n            for(int i=0; i<n_active_layers; ++i)\n            {\n                if(dim==3)\n                {\n                  layers[i]->set_velocity(locally_relevant_solution_Wxy,locally_relevant_solution_Wxy, locally_relevant_solution_F);\n                }\n                else\n                {\n                  layers[i]->set_velocity(locally_relevant_solution_Wxy, locally_relevant_solution_F);\n                }\n                layers[i]->nth_time_step();\n                layers[i]->get_unp1(locally_relevant_solution_LS_0);\n                (*layers_solutions[i])=locally_relevant_solution_LS_0;\n            }\n           // display_vectors();\n          }\n\n        // set material ids based on locally_relevant_solution_LS\n        setup_material_configuration(); // TODO: move away from cell id to values at quad points\n\n\n        if (parameters.use_advance)\n        {\n          if(timestep_number>=10)\n          {\n            prepare_advance_old_vectors();\n            advance_old_vectors(old_locally_relevant_solution_P);\n            //advance_old_vectors(old_locally_relevant_solution_Sigma);\n            //advance_old_vectors(old_locally_relevant_solution_T);\n\n          }\n        }\n\n        //prepare for nonlinear Picard iteration\n        temp_locally_relevant_solution_Sigma=locally_relevant_solution_Sigma;\n        temp_locally_relevant_solution_P=locally_relevant_solution_P;\n        bool is_converged=false;\n        int nl_loop_count=0;\n        double deviation{0};\n\n\n        while (is_converged==false && nl_loop_count<maxiter)\n        {\n            old_temp_locally_relevant_solution_P=temp_locally_relevant_solution_P;\n            assemble_Sigma();\n            solve_Sigma();    // generates temp_l_r_s_Sigma\n\n            // pressure solution\n            assemble_matrices_P();\n            forge_system_P();\n            solve_time_step_P(); // temp_loc_r_s_P\n\n            //is_converged=estimate_nl_error();//l\n            deviation=(temp_locally_relevant_solution_P.l2_norm()\n                       - old_temp_locally_relevant_solution_P.l2_norm() )\n                       /  temp_locally_relevant_solution_P.l2_norm();\n            pcout<<\"deviation: \"<<deviation<<std::endl;\n\n            if(std::abs(deviation)<tolerance)\n              {\n                is_converged=true;\n              }\n            nl_loop_count++;\n\n\n          }//end nonlinear loop\n        if(nl_loop_count>=maxiter)\n          {\n            pcout<<\"not converged\";\n\n          }\n        locally_relevant_solution_P=temp_locally_relevant_solution_P;\n        locally_relevant_solution_Sigma=temp_locally_relevant_solution_Sigma;\n\n\n\n\n        // Solve temperature (coefficients depend on porosity, and TODO: should influence viscosity)\n        if (compute_temperature)\n          {\n            assemble_matrices_T();\n            forge_system_T();\n            solve_time_step_T();\n          }\n        old_locally_relevant_solution_F=locally_relevant_solution_F;\n\n        setup_system_F();\n        assemble_F();\n        solve_F();\n        //setup_system_F();\n//locally_relevant_solution_F = -1*base_sedimentation_rate;\n        //    if (get_output && time - (output_number)*output_time > 0)\n        //      output_results();\n        if (timestep_number % output_interval == 0) {\n            display_vectors();\n\n        }\n\n        prepare_next_time_step();\n    } // end of time loop\n\n    //output once at the end\n    display_vectors();\n    compute_hydrostatic_thicknesses();\n    pcout<< \"End of Time Stepping\"<<std::endl;\n    pcout<< \" % complete:\"<<100.*(timestep_number*time_step)/final_time<<std::endl;\n    pcout<<std::endl<<\"Simulation Completed\"<<std::endl;\n    pcout<<\"Summary\"<<std::endl;\n    pcout<<\"min_h:\"<<min_h<<std::endl;\n    pcout<<\"linear in void ratio:\"<<parameters.linear_in_void_ratio<<std::endl;\n\n} //end of run function\n\n\n} // end namespace CPPLS\n\n\nint main(int argc, char* argv[])\n{\n\n    try {\n        using namespace dealii;\n        using namespace CPPLS;\n\n        auto t0 = std::chrono::high_resolution_clock::now();\n\n        Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv, 1);\n\n        CPPLS::Parameters parameters;\n        parameters.read_parameter_file(\"parameters.prm\");\n        CPPLS::MaterialData material_data;\n        if (parameters.dimension==2)\n        {\n            LayerMovementProblem<2> run_layers(parameters, material_data);\n            run_layers.run();\n        }\n        else if (parameters.dimension==3)\n          {\n            LayerMovementProblem<3> run_layers(parameters, material_data);\n            run_layers.run();\n\n          }\n        else\n          {\n             AssertThrow (false, ExcNotImplemented());\n          }\n\n        auto t1 = std::chrono::high_resolution_clock::now();\n        if (Utilities::MPI::this_mpi_process(MPI_COMM_WORLD) == 0) {\n            std::cout << \"time elapsed: \" << std::chrono::duration_cast<std::chrono::milliseconds>(t1 - t0).count()\n                      << \" milliseconds.\" << std::endl;\n        }\n    }\n    catch (std::exception& exc) {\n        std::cerr << std::endl << std::endl << \"----------------------------------------------------\" << std::endl;\n        std::cerr << \"Exception on processing: \" << std::endl\n                  << exc.what() << std::endl\n                  << \"Aborting!\" << std::endl\n                  << \"----------------------------------------------------\" << std::endl;\n\n        return 1;\n    }\n    catch (...) {\n        std::cerr << std::endl << std::endl << \"----------------------------------------------------\" << std::endl;\n        std::cerr << \"Unknown exception!\" << std::endl\n                  << \"Aborting!\" << std::endl\n                  << \"----------------------------------------------------\" << std::endl;\n        return 1;\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "763e1728d9b01f3f021feca03f95277732e09137", "size": 104078, "ext": "cc", "lang": "C++", "max_stars_repo_path": "source/cppls.cc", "max_stars_repo_name": "stmcgovern/CPPLS", "max_stars_repo_head_hexsha": "b73b73d158323fb4fd482cc144e3c0df6105c6ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-04T17:57:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-04T17:57:16.000Z", "max_issues_repo_path": "source/cppls.cc", "max_issues_repo_name": "stmcgovern/CPPLS", "max_issues_repo_head_hexsha": "b73b73d158323fb4fd482cc144e3c0df6105c6ee", "max_issues_repo_licenses": ["MIT"], "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/cppls.cc", "max_forks_repo_name": "stmcgovern/CPPLS", "max_forks_repo_head_hexsha": "b73b73d158323fb4fd482cc144e3c0df6105c6ee", "max_forks_repo_licenses": ["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.3787362845, "max_line_length": 177, "alphanum_fraction": 0.6741194104, "num_tokens": 24164, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788995148792, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.46185354980378207}}
{"text": "/*\n@copyright Louis Dionne 2014\nDistributed under the Boost Software License, Version 1.0.\n(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n */\n\n#include <boost/hana/detail/assert.hpp>\n#include <boost/hana/detail/constexpr.hpp>\n#include <boost/hana/ext/std/integral_constant.hpp>\n#include <boost/hana/integral.hpp>\n#include <boost/hana/list/instance.hpp>\n#include <boost/hana/type.hpp>\n\n#include <type_traits>\nusing namespace boost::hana;\nusing namespace literals;\n\n\nint main() {\n    //! [main]\n    BOOST_HANA_CONSTEXPR_LAMBDA auto odd = [](auto x) {\n        return x % 2_c != 0_c;\n    };\n\n    BOOST_HANA_CONSTEXPR_ASSERT(all(list(1, 3), odd));\n    BOOST_HANA_CONSTANT_ASSERT(!all(list(3_c, 4_c), odd));\n\n    BOOST_HANA_CONSTANT_ASSERT(\n        !all(list(type<void>, type<char&>), trait<std::is_void>)\n    );\n    BOOST_HANA_CONSTANT_ASSERT(\n        all(list(type<int>, type<char>), trait<std::is_integral>)\n    );\n    //! [main]\n}\n", "meta": {"hexsha": "38e864d355eb9655e8d6476b071702e782f8237d", "size": 961, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/searchable/all.cpp", "max_stars_repo_name": "rbock/hana", "max_stars_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-05-07T14:29:13.000Z", "max_stars_repo_stars_event_max_datetime": "2015-07-04T10:59:46.000Z", "max_issues_repo_path": "example/searchable/all.cpp", "max_issues_repo_name": "rbock/hana", "max_issues_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/searchable/all.cpp", "max_forks_repo_name": "rbock/hana", "max_forks_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6944444444, "max_line_length": 78, "alphanum_fraction": 0.6909469303, "num_tokens": 252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.6513548714339145, "lm_q1q2_score": 0.4618230667307748}}
{"text": "//\n// Copyright 2005-2007 Adobe Systems Incorporated\n//\n// Distributed under the Boost Software License, Version 1.0\n// See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt\n//\n#ifndef BOOST_GIL_POINT_HPP\n#define BOOST_GIL_POINT_HPP\n\n#include <boost/gil/utilities.hpp>\n#include <boost/gil/detail/std_common_type.hpp>\n\n#include <boost/config.hpp>\n\n#include <cstddef>\n#include <type_traits>\n\nnamespace boost { namespace gil {\n\n/// \\addtogroup PointModel\n///\n/// Example:\n/// \\code\n/// point<std::ptrdiff_t> p(3,2);\n/// assert((p[0] == p.x) && (p[1] == p.y));\n/// assert(axis_value<0>(p) == 3);\n/// assert(axis_value<1>(p) == 2);\n/// \\endcode\n\n/// \\brief 2D point both axes of which have the same dimension type\n/// \\ingroup PointModel\n/// Models: Point2DConcept\ntemplate <typename T>\nclass point\n{\npublic:\n    using value_type = T;\n\n    template<std::size_t D>\n    struct axis\n    {\n        using coord_t = value_type;\n    };\n\n    static constexpr std::size_t num_dimensions = 2;\n\n    point() = default;\n    point(T px, T py) : x(px), y(py) {}\n\n    point operator<<(std::ptrdiff_t shift) const\n    {\n        return point(x << shift, y << shift);\n    }\n\n    point operator>>(std::ptrdiff_t shift) const\n    {\n        return point(x >> shift, y >> shift);\n    }\n\n    point& operator+=(point const& p)\n    {\n        x += p.x;\n        y += p.y;\n        return *this;\n    }\n\n    point& operator-=(point const& p)\n    {\n        x -= p.x;\n        y -= p.y;\n        return *this;\n    }\n\n    point& operator/=(double d)\n    {\n        if (d < 0 || 0 < d)\n        {\n            x = static_cast<T>(x / d);\n            y = static_cast<T>(y / d);\n        }\n        return *this;\n    }\n\n    point& operator*=(double d)\n    {\n        x = static_cast<T>(x * d);\n        y = static_cast<T>(y * d);\n        return *this;\n    }\n\n    T const& operator[](std::size_t i) const\n    {\n        return this->*mem_array[i];\n    }\n\n    T& operator[](std::size_t i)\n    {\n        return this->*mem_array[i];\n    }\n\n    T x{0};\n    T y{0};\n\nprivate:\n    // this static array of pointers to member variables makes operator[] safe\n    // and doesn't seem to exhibit any performance penalty.\n    static T point<T>::* const mem_array[num_dimensions];\n};\n\n/// Alias template for backward compatibility with Boost <=1.68.\ntemplate <typename T>\nusing point2 = point<T>;\n\n/// Common type to represent 2D dimensions or in-memory size of image or view.\n/// @todo TODO: rename to dims_t or dimensions_t for purpose clarity?\nusing point_t = point<std::ptrdiff_t>;\n\ntemplate <typename T>\nT point<T>::* const point<T>::mem_array[point<T>::num_dimensions] =\n{\n    &point<T>::x,\n    &point<T>::y\n};\n\n/// \\ingroup PointModel\ntemplate <typename T>\nBOOST_FORCEINLINE\nbool operator==(const point<T>& p1, const point<T>& p2)\n{\n    return p1.x == p2.x && p1.y == p2.y;\n}\n\n/// \\ingroup PointModel\ntemplate <typename T>\nBOOST_FORCEINLINE\nbool operator!=(const point<T>& p1, const point<T>& p2)\n{\n    return p1.x != p2.x || p1.y != p2.y;\n}\n\n/// \\ingroup PointModel\ntemplate <typename T>\nBOOST_FORCEINLINE\npoint<T> operator+(const point<T>& p1, const point<T>& p2)\n{\n    return { p1.x + p2.x, p1.y + p2.y };\n}\n\n/// \\ingroup PointModel\ntemplate <typename T>\nBOOST_FORCEINLINE\npoint<T> operator-(const point<T>& p)\n{\n    return { -p.x, -p.y };\n}\n\n/// \\ingroup PointModel\ntemplate <typename T>\nBOOST_FORCEINLINE\npoint<T> operator-(const point<T>& p1, const point<T>& p2)\n{\n    return { p1.x - p2.x, p1.y - p2.y };\n}\n\n/// \\ingroup PointModel\ntemplate <typename T, typename D>\nBOOST_FORCEINLINE\nauto operator/(point<T> const& p, D d)\n    -> typename std::enable_if\n    <\n        std::is_arithmetic<D>::value,\n        point<typename detail::std_common_type<T, D>::type>\n    >::type\n{\n    static_assert(std::is_arithmetic<D>::value, \"denominator is not arithmetic type\");\n    using result_type = typename detail::std_common_type<T, D>::type;\n    if (d < 0 || 0 < d)\n    {\n        double const x = static_cast<double>(p.x) / static_cast<double>(d);\n        double const y = static_cast<double>(p.y) / static_cast<double>(d);\n        return point<result_type>{\n            static_cast<result_type>(iround(x)),\n            static_cast<result_type>(iround(y))};\n    }\n    else\n    {\n        return point<result_type>{0, 0};\n    }\n}\n\n/// \\ingroup PointModel\ntemplate <typename T, typename M>\nBOOST_FORCEINLINE\nauto operator*(point<T> const& p, M m)\n    -> typename std::enable_if\n    <\n        std::is_arithmetic<M>::value,\n        point<typename detail::std_common_type<T, M>::type>\n    >::type\n{\n    static_assert(std::is_arithmetic<M>::value, \"multiplier is not arithmetic type\");\n    using result_type = typename detail::std_common_type<T, M>::type;\n    return point<result_type>{p.x * m, p.y * m};\n}\n\n/// \\ingroup PointModel\ntemplate <typename T, typename M>\nBOOST_FORCEINLINE\nauto operator*(M m, point<T> const& p)\n    -> typename std::enable_if\n    <\n        std::is_arithmetic<M>::value,\n        point<typename detail::std_common_type<T, M>::type>\n    >::type\n{\n    static_assert(std::is_arithmetic<M>::value, \"multiplier is not arithmetic type\");\n    using result_type = typename detail::std_common_type<T, M>::type;\n    return point<result_type>{p.x * m, p.y * m};\n}\n\n/// \\ingroup PointModel\ntemplate <std::size_t K, typename T>\nBOOST_FORCEINLINE\nT const& axis_value(point<T> const& p)\n{\n    static_assert(K < point<T>::num_dimensions, \"axis index out of range\");\n    return p[K];\n}\n\n/// \\ingroup PointModel\ntemplate <std::size_t K, typename T>\nBOOST_FORCEINLINE\nT& axis_value(point<T>& p)\n{\n    static_assert(K < point<T>::num_dimensions, \"axis index out of range\");\n    return p[K];\n}\n\n/// \\addtogroup PointAlgorithm\n///\n/// Example:\n/// \\code\n/// assert(iround(point<double>(3.1, 3.9)) == point<std::ptrdiff_t>(3,4));\n/// \\endcode\n\n/// \\ingroup PointAlgorithm\ntemplate <typename T>\ninline point<std::ptrdiff_t> iround(point<T> const& p)\n{\n    static_assert(std::is_integral<T>::value, \"T is not integer\");\n    return { static_cast<std::ptrdiff_t>(p.x), static_cast<std::ptrdiff_t>(p.y) };\n}\n\n/// \\ingroup PointAlgorithm\ninline point<std::ptrdiff_t> iround(point<float> const& p)\n{\n    return { iround(p.x), iround(p.y) };\n}\n\n/// \\ingroup PointAlgorithm\ninline point<std::ptrdiff_t> iround(point<double> const& p)\n{\n    return { iround(p.x), iround(p.y) };\n}\n\n/// \\ingroup PointAlgorithm\ninline point<std::ptrdiff_t> ifloor(point<float> const& p)\n{\n    return { ifloor(p.x), ifloor(p.y) };\n}\n\n/// \\ingroup PointAlgorithm\ninline point<std::ptrdiff_t> ifloor(point<double> const& p)\n{\n    return { ifloor(p.x), ifloor(p.y) };\n}\n\n/// \\ingroup PointAlgorithm\ninline point<std::ptrdiff_t> iceil(point<float> const& p)\n{\n    return { iceil(p.x), iceil(p.y) };\n}\n\n/// \\ingroup PointAlgorithm\ninline point<std::ptrdiff_t> iceil(point<double> const& p)\n{\n    return { iceil(p.x), iceil(p.y) };\n}\n\n}} // namespace boost::gil\n\n#endif\n", "meta": {"hexsha": "0f40faf46fde8e7b96f575a89ce5ba6bcab71a91", "size": 6899, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/gil/point.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": 153.0, "max_stars_repo_stars_event_min_datetime": "2015-02-03T06:03:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T15:06:34.000Z", "max_issues_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/gil/point.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": 429.0, "max_issues_repo_issues_event_min_datetime": "2015-03-22T09:49:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T08:32:08.000Z", "max_forks_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/gil/point.hpp", "max_forks_repo_name": "Harshitha91/Tmdb-react-native-node", "max_forks_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-03-15T09:20:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T12:40:07.000Z", "avg_line_length": 23.4659863946, "max_line_length": 86, "alphanum_fraction": 0.6295115234, "num_tokens": 1908, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.46182305713369}}
{"text": "// This file is part of Eigen, a lightweight C++ template library\n// for linear algebra.\n//\n// Copyright (C) 2008-2010 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\n// import basic and product tests for deprectaed DynamicSparseMatrix\n#define EIGEN_NO_DEPRECATED_WARNING\n\n#include \"main.h\"\n#include <Eigen/SparseExtra>\n#include \"unsupported/Eigen/src/SparseExtra/BlockDiagonalSparseQR.h\"\n\n\n\ntemplate<typename Scalar, typename BlockSparseSolver>\nvoid block_diagonal_sparse_qr(int nBlocks, int blockRows, int blockCols) \n{\n    typedef Eigen::Matrix<Scalar, Dynamic, Dynamic> DenseMatrix;\n\n    std::cout << \"block_diagonal_sparse_qr< \" << eigen_test_nice_typename<BlockSparseSolver>() << \"> \" << nBlocks << \" blocks of size \" << blockRows << \"x\" << blockCols << \"\\n\";\n\n    // Generate random block diagonal matrix\n    SparseMatrix<Scalar> mat;\n    mat.resize(blockRows*nBlocks, blockCols*nBlocks);\n    std::vector< Eigen::Triplet<Scalar> > triplets;\n    triplets.reserve(blockRows*blockCols*nBlocks);\n    for(int i=0; i<nBlocks; i++) \n        for(int r=0; r<blockRows; r++) \n            for(int c=0; c<blockCols; c++) \n                triplets.push_back( Eigen::Triplet<Scalar>( i*blockRows+r, i*blockCols+c, Eigen::internal::random<Scalar>() ) );\n\n    mat.setFromTriplets(triplets.begin(), triplets.end());\n\n    // solve using BlockDiagonalSparseQR\n    BlockDiagonalSparseQR<SparseMatrix<Scalar, ColMajor, Index>, BlockSparseSolver > solver;\n    solver.setSparseBlockParams(blockRows, blockCols);\n    solver.compute(mat);\n\n    // check result\n    SparseMatrix<Scalar> Q = solver.matrixQ();\n    SparseMatrix<Scalar> R = solver.matrixR();\n\n    // check A*P = Q*R\n    DenseMatrix  Q_dot_R = Q.toDense()*R.toDense();\n    DenseMatrix AP = mat.toDense();\n    solver.colsPermutation().applyThisOnTheRight(AP);\n    VERIFY_IS_APPROX( Q_dot_R, AP );\n\n    // check Q*Qt = I\n    DenseMatrix QQt = (Q*Q.transpose()).toDense();\n    DenseMatrix I = Matrix<Scalar, Dynamic, Dynamic>::Identity(Q.rows(), Q.cols());\n    VERIFY_IS_APPROX( QQt, I );\n\n    // check R = upper triangular\n    for(int i=0; i<R.rows(); i++)\n        for(int j=0; j<R.cols() && j<i; j++)\n            eigen_assert( fabs(R.coeff(i,j)) < 0.00001 );\n        \n}\n\n\nvoid block_diagonal_sparse_qr_check_invalid_structure(int nBlocks, int blockRows, int blockCols) {\n\n    // Generate random matrix with incorrect size\n    SparseMatrix<double> mat;\n    mat.resize(blockRows*nBlocks, blockCols*nBlocks+Eigen::internal::random<int>(1,10));\n\n    // try to solve using BlockDiagonalSparseQR\n    BlockDiagonalSparseQR<SparseMatrix<double, ColMajor, Index>, SparseQR<SparseMatrix<double>, COLAMDOrdering<int> > > solver;\n    solver.setSparseBlockParams(blockRows, blockCols);\n    VERIFY_RAISES_ASSERT( solver.compute(mat) );\n\n    // again\n    mat.resize(blockRows*nBlocks+Eigen::internal::random<int>(1,10), blockCols*nBlocks);\n    VERIFY_RAISES_ASSERT( solver.compute(mat) );\n}\n\n\nvoid block_diagonal_sparse_qr_check_values_outside_blocks(int nBlocks, int blockRows, int blockCols) {\n\n    // Generate full random matrix\n    SparseMatrix<double> mat;\n    mat.resize(blockRows*nBlocks, blockCols*nBlocks);\n    std::vector< Eigen::Triplet<double> > triplets;\n    for(int i=0; i<mat.rows(); i++) {\n        for(int j=0; j<mat.cols(); j++) {\n            triplets.push_back( Eigen::Triplet<double>( i, j, Eigen::internal::random<double>() ) );\n        }\n    }\n    mat.setFromTriplets(triplets.begin(), triplets.end());\n\n    // try to solve using BlockDiagonalSparseQR\n    BlockDiagonalSparseQR<SparseMatrix<double, ColMajor, Index>, SparseQR<SparseMatrix<double>, COLAMDOrdering<int> > > solver;\n    solver.setSparseBlockParams(blockRows, blockCols);\n    VERIFY_RAISES_ASSERT( solver.compute(mat) );\n\n}\n\n\nvoid test_block_diagonal_sparse_qr()\n{\n  for(int i = 0; i < g_repeat; i++) {\n\n    typedef double Scalar;\n\n    // Fixed-size blocks\n    CALL_SUBTEST((block_diagonal_sparse_qr<Scalar, ColPivHouseholderQR<Matrix<Scalar, 3, 2>>>(3, 3, 2)));\n\n\n    // check BlockDiagonalSparseQR with sparse solver (for internal blocks)\n    typedef SparseQR<SparseMatrix<Scalar>, COLAMDOrdering<int> > BlockSparseSolver;\n    CALL_SUBTEST((block_diagonal_sparse_qr<Scalar, BlockSparseSolver>(2, 3, 5)));\n    CALL_SUBTEST(( block_diagonal_sparse_qr<Scalar, BlockSparseSolver>( 1,1,1 ) ));\n    CALL_SUBTEST(( block_diagonal_sparse_qr<Scalar, BlockSparseSolver>( 1,2,2 ) ));\n    CALL_SUBTEST(( block_diagonal_sparse_qr<Scalar, BlockSparseSolver>( 1,3,5 ) ));\n    CALL_SUBTEST(( block_diagonal_sparse_qr<Scalar, BlockSparseSolver>( 1,5,3 ) ));\n    CALL_SUBTEST(( block_diagonal_sparse_qr<Scalar, BlockSparseSolver>( 2,1,1 ) ));\n    CALL_SUBTEST(( block_diagonal_sparse_qr<Scalar, BlockSparseSolver>( 2,2,2 ) ));\n    CALL_SUBTEST(( block_diagonal_sparse_qr<Scalar, BlockSparseSolver>( 2,5,3 ) ));\n    CALL_SUBTEST(( block_diagonal_sparse_qr<Scalar, BlockSparseSolver>( 11,1,1 ) ));\n    CALL_SUBTEST(( block_diagonal_sparse_qr<Scalar, BlockSparseSolver>( 11,2,2 ) ));\n    CALL_SUBTEST(( block_diagonal_sparse_qr<Scalar, BlockSparseSolver>( 11,3,5 ) ));\n    CALL_SUBTEST(( block_diagonal_sparse_qr<Scalar, BlockSparseSolver>( 11,5,3 ) ));\n\n    // check BlockDiagonalSparseQR with dense solver (for internal blocks)\n    typedef ColPivHouseholderQR<Matrix<Scalar,Dynamic,Dynamic> > BlockDenseSolver;\n    CALL_SUBTEST(( block_diagonal_sparse_qr<Scalar, BlockDenseSolver>( 1,1,1 ) ));\n    CALL_SUBTEST(( block_diagonal_sparse_qr<Scalar, BlockDenseSolver>( 1,2,2 ) ));\n    CALL_SUBTEST(( block_diagonal_sparse_qr<Scalar, BlockDenseSolver>( 1,3,5 ) ));\n    CALL_SUBTEST(( block_diagonal_sparse_qr<Scalar, BlockDenseSolver>( 1,5,3 ) ));\n    CALL_SUBTEST(( block_diagonal_sparse_qr<Scalar, BlockDenseSolver>( 2,1,1 ) ));\n    CALL_SUBTEST(( block_diagonal_sparse_qr<Scalar, BlockDenseSolver>( 2,2,2 ) ));\n    CALL_SUBTEST(( block_diagonal_sparse_qr<Scalar, BlockDenseSolver>( 2,3,5 ) ));\n    CALL_SUBTEST(( block_diagonal_sparse_qr<Scalar, BlockDenseSolver>( 2,5,3 ) ));\n    CALL_SUBTEST(( block_diagonal_sparse_qr<Scalar, BlockDenseSolver>( 11,1,1 ) ));\n    CALL_SUBTEST(( block_diagonal_sparse_qr<Scalar, BlockDenseSolver>( 11,2,2 ) ));\n    CALL_SUBTEST(( block_diagonal_sparse_qr<Scalar, BlockDenseSolver>( 11,3,5 ) ));\n    CALL_SUBTEST(( block_diagonal_sparse_qr<Scalar, BlockDenseSolver>( 11,5,3 ) ));\n\n    // check BlockDiagonalSparseQR fails with an invalid block structure\n    CALL_SUBTEST(( block_diagonal_sparse_qr_check_invalid_structure( 1,1,1 ) ));\n    CALL_SUBTEST(( block_diagonal_sparse_qr_check_invalid_structure( 1,2,2 ) ));\n    CALL_SUBTEST(( block_diagonal_sparse_qr_check_invalid_structure( 2,3,5 ) ));\n    CALL_SUBTEST(( block_diagonal_sparse_qr_check_invalid_structure( 11,5,3 ) ));\n\n    // check BlockDiagonalSparseQR fails with data outside of the blocks\n    CALL_SUBTEST(( block_diagonal_sparse_qr_check_values_outside_blocks( 3,1,1 ) ));\n    CALL_SUBTEST(( block_diagonal_sparse_qr_check_values_outside_blocks( 5,2,2 ) ));\n    CALL_SUBTEST(( block_diagonal_sparse_qr_check_values_outside_blocks( 7,3,5 ) ));\n    CALL_SUBTEST(( block_diagonal_sparse_qr_check_values_outside_blocks( 11,5,3 ) ));\n\n  }\n}\n\n\n//triplets.push_back( Eigen::Triplet<Scalar>(0,blockCols*nBlocks-1,4));\n", "meta": {"hexsha": "81e5f2eb36f39c049b72a81d75ebb3335c2787dd", "size": 7391, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "eigen_pr/unsupported/test/block_diagonal_sparse_qr.cpp", "max_stars_repo_name": "pmkalshetti/parametric_sphere_fitting", "max_stars_repo_head_hexsha": "1d86a18a997ecbc6ab4234c9550db1cc6c707b42", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-10-26T07:50:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T00:41:14.000Z", "max_issues_repo_path": "eigen_pr/unsupported/test/block_diagonal_sparse_qr.cpp", "max_issues_repo_name": "pmkalshetti/parametric_sphere_fitting", "max_issues_repo_head_hexsha": "1d86a18a997ecbc6ab4234c9550db1cc6c707b42", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "eigen_pr/unsupported/test/block_diagonal_sparse_qr.cpp", "max_forks_repo_name": "pmkalshetti/parametric_sphere_fitting", "max_forks_repo_head_hexsha": "1d86a18a997ecbc6ab4234c9550db1cc6c707b42", "max_forks_repo_licenses": ["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.6234567901, "max_line_length": 177, "alphanum_fraction": 0.7197943445, "num_tokens": 2040, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.4618230523351476}}
{"text": "#include \"NBC.h\"\n//#include <boost/algorithm/string.hpp>\n\n\nint main(int argc, char* argv[])\n{\n\tif (argc != 6){\n\t\tcout<< \"Usuage: 5 arguments, the 1. executable followded by 2. training set, 3. training label, \\\n\t\t4. test set, 5. tes label, 6. Number of Classe \" << endl;\n\t\texit(1);\n\t}\n\tint nC = atoi(argv[5]);\n\tcout<<\"Number of Classe: \" <<nC<<endl;\n\n\tNBC nbc;\n\tnbc.set_numClass(nC);\n\t//Start get Input data\n\tifstream traindata(argv[1]);\n\tifstream trainlable(argv[2]);\n\tifstream testdata(argv[3]);\n\tifstream testlable(argv[4]);\t\n\tif(trainlable.is_open() && traindata.is_open()){\n\t\tstring line, lable;\n\t\tint l =-1;\n\n\t\twhile (!trainlable.eof()){\n\t\t\tgetline(traindata, line, '\\n');\n\t\t\tgetline(trainlable, lable, '\\n');\n\t\t\tistringstream linestr(line);\n\t\t\tvector<int> sample;\n\t\t\tint v = 0;\n\t\t\tif (lable.size() ==0 )\n\t\t\t\tbreak;\n\n\t\t\tl = atoi(lable.c_str());\n\t\t\t//cout << \"l: \" <<l <<endl;\n\t\t\tnbc.ltrain.push_back(l);\n\t\t\twhile(linestr >> v){\n\t\t\t\tsample.push_back(v);\n\t\t\t}\n\t\t\tnbc.trainset.push_back(sample);\n\t\t}\n\t}\n\n\tif(testlable.is_open() && testdata.is_open()){\n\t\tstring line, lable;\n\t\tint l =-1;\n\n\t\twhile (!testlable.eof()){\n\t\t\tgetline(testdata, line, '\\n');\n\t\t\tgetline(testlable, lable, '\\n');\n\t\t\tistringstream linestr(line);\n\t\t\tvector<int> sample;\n\t\t\tint v = 0;\n\t\t\tif (lable.size() ==0 )\n\t\t\t\tbreak;\n\n\t\t\tl = atoi(lable.c_str());\n\t\t\t//cout << \"l: \" <<l <<endl;\n\t\t\tnbc.ltest.push_back(l);\n\t\t\twhile(linestr >> v){\n\t\t\t\tsample.push_back(v);\n\t\t\t}\n\t\t\tnbc.testset.push_back(sample);\n\t\t}\n\t}\n\n\ttraindata.close();\n\ttrainlable.close();\n\ttestdata.close();\n\ttestlable.close();\n\n\t// Start Training Naive Baysian Classifier\n\n\n\tnbc.Train(nbc.trainset, nbc.ltrain);\n\n\t//nbc.Print_Ptable();\n\t//nbc.check_Ptable();\n\n\tnbc.Test(nbc.testset);\n\n\tnbc.Print_confusionMatrix();\n\n\tcout<<\"total correct: \" << nbc.totalCorrect << \" , with ratio: \" <<double(nbc.totalCorrect)/nbc.totalTest << endl;\n\tnbc.confusionOutput(8, 9);\n\tcout<<\"\\n\\n\"<<endl;\n\tnbc.confusionOutput(7, 9);\n\tcout<<\"\\n\\n\"<<endl;\n\tnbc.confusionOutput(4, 9);\n\tcout<<\"\\n\\n\"<<endl;\n\tnbc.confusionOutput(5, 3);\n\n/*\n\tint nlabel = nbc.pltest.size();\n\n\tcout << \"# of lable: \" <<nlabel<<endl;\n\tnbc.TP = 0;\n\tnbc.TN = 0;\n\tnbc.FP = 0;\n\tnbc.FN = 0;\n    for (int n = 0; n<nlabel; n++)\n\t{\n\t\tcout<<\"n =\"<<n <<\", nbc.ltest[n]: \" << nbc.ltest[n] << \", nbc.pltest[n] \" << nbc.pltest[n] << endl;\n\t\tif(nbc.ltest[n] ==1 && nbc.pltest[n] == 1)    nbc.TP+=1;\n\t\tif(nbc.ltest[n] ==-1 && nbc.pltest[n] == -1)  nbc.TN+=1;\n\t\tif(nbc.ltest[n] ==-1 && nbc.pltest[n] == 1)   nbc.FP+=1;\n\t\tif(nbc.ltest[n] ==1 && nbc.pltest[n] == -1)   nbc.FN+=1;\n\t}\n\n    cout<<nbc.TP<<endl;\n\tcout<<nbc.FN<<endl;\n\tcout<<nbc.FP<<endl;\n\tcout<<nbc.TN<<endl;\n*/\n}", "meta": {"hexsha": "046ffb0931ec1b4f2a071ac3aaa54ef46d4b58c0", "size": 2639, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "haoranyu/cs440-Text-digit-classification-NaiveBayes", "max_stars_repo_head_hexsha": "6e5594c90fe2ea0159898049f152376afd29a75e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-11-04T10:38:11.000Z", "max_stars_repo_stars_event_max_datetime": "2015-11-04T10:38:11.000Z", "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "haoranyu/cs440-Text-digit-classification-NaiveBayes", "max_issues_repo_head_hexsha": "6e5594c90fe2ea0159898049f152376afd29a75e", "max_issues_repo_licenses": ["MIT"], "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": "haoranyu/cs440-Text-digit-classification-NaiveBayes", "max_forks_repo_head_hexsha": "6e5594c90fe2ea0159898049f152376afd29a75e", "max_forks_repo_licenses": ["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.75, "max_line_length": 115, "alphanum_fraction": 0.5953012505, "num_tokens": 926, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.46176469791825503}}
{"text": "#pragma once\n#include <cmath>\n#include <Eigen/Eigen>\n#include <random>\n\n#include <nlohmann/json.hpp>\n\nnamespace yannq\n{\n\nclass LocalSweeper\n{\nprivate:\n\tconst uint32_t n_;\n\tconst uint32_t nSweep_;\n\npublic:\n\n\tLocalSweeper(uint32_t n, uint32_t nSweep = 1) noexcept\n\t\t: n_(n), nSweep_(nSweep)\n\t{\n\t}\n\n\tnlohmann::json desc() const\n\t{\n\t\tnlohmann::json res;\n\t\tres[\"name\"] = \"Local Sweeper\";\n\t\tres[\"num_sweep_per\"] = nSweep_;\n\t\treturn res;\n\t}\n\n\ttemplate<class StateValue, class RandomEngine>\n\tuint32_t sweep(StateValue& sv, typename StateValue::RealScalar beta, \n\t\t\tRandomEngine& re) const noexcept\n\t{\n\t\tusing RealScalar = typename StateValue::RealScalar;\n\n\t\tuint32_t acc = 0;\n\t\tstd::uniform_real_distribution<RealScalar> urd(0.0, 1.0);\n\t\tstd::uniform_int_distribution<int> uid_(0,n_-1);\n\t\tfor(uint32_t sidx = 0; sidx < n_*nSweep_; sidx++)\n\t\t{\n\t\t\tint toFlip = uid_(re);\n\t\t\tRealScalar p = std::min(1.0,exp(beta*2.0*sv.logRatioRe(toFlip)));\n\t\t\tRealScalar u = urd(re);\n\t\t\tif(u < p)//accept\n\t\t\t{\n\t\t\t\tsv.flip(toFlip);\n\t\t\t\t++acc;\n\t\t\t}\n\t\t}\n\t\treturn acc;\n\t}\n};\n} //NNQS\n", "meta": {"hexsha": "c1e11c7646b02fa5382fa77c5ea1a4850c055106", "size": 1053, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Yannq/Samplers/LocalSweeper.hpp", "max_stars_repo_name": "cecri/yannq", "max_stars_repo_head_hexsha": "b78c1f86a255059f06b34dd5e538449e7261d0ee", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Yannq/Samplers/LocalSweeper.hpp", "max_issues_repo_name": "cecri/yannq", "max_issues_repo_head_hexsha": "b78c1f86a255059f06b34dd5e538449e7261d0ee", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Yannq/Samplers/LocalSweeper.hpp", "max_forks_repo_name": "cecri/yannq", "max_forks_repo_head_hexsha": "b78c1f86a255059f06b34dd5e538449e7261d0ee", "max_forks_repo_licenses": ["BSD-3-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.8035714286, "max_line_length": 70, "alphanum_fraction": 0.6742640076, "num_tokens": 354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768249, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.4617646879281376}}
{"text": "//Copyright (c) 2008-2016 Emil Dotchevski and Reverge Studios, Inc.\r\r\n\r\r\n//Distributed under the Boost Software License, Version 1.0. (See accompanying\r\r\n//file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\r\n\r\r\n#include <boost/qvm/quat_operations.hpp>\r\r\n#include <boost/qvm/mat_operations.hpp>\r\r\n#include \"test_qvm_matrix.hpp\"\r\r\n#include \"test_qvm_quaternion.hpp\"\r\r\n#include \"test_qvm_vector.hpp\"\r\r\n#include \"gold.hpp\"\r\r\n\r\r\nnamespace\r\r\n    {\r\r\n    void\r\r\n    test_x()\r\r\n        {\r\r\n        using namespace boost::qvm;\r\r\n        test_qvm::vector<V1,3> axis; axis.a[0]=1;\r\r\n        for( float r=0; r<6.28f; r+=0.5f )\r\r\n            {\r\r\n            test_qvm::quaternion<Q1> q1=rot_quat(axis,r);\r\r\n            test_qvm::matrix<M1,3,3> x1=convert_to< test_qvm::matrix<M1,3,3> >(q1);\r\r\n            test_qvm::rotation_x(x1.b,r);\r\r\n            BOOST_QVM_TEST_CLOSE(x1.a,x1.b,0.000001f);\r\r\n            test_qvm::quaternion<Q2> q2(42,1);\r\r\n            set_rot(q2,axis,r);\r\r\n            test_qvm::matrix<M2,3,3> x2=convert_to< test_qvm::matrix<M2,3,3> >(q2);\r\r\n            test_qvm::rotation_x(x2.b,r);\r\r\n            BOOST_QVM_TEST_CLOSE(x2.a,x2.b,0.000001f);\r\r\n            test_qvm::quaternion<Q1> q3(42,1);\r\r\n            test_qvm::quaternion<Q1> q4(42,1);\r\r\n            rotate(q3,axis,r);\r\r\n            q3 = q3*q1;\r\r\n            BOOST_QVM_TEST_EQ(q3.a,q3.a);\r\r\n            }\r\r\n        }\r\r\n\r\r\n    void\r\r\n    test_y()\r\r\n        {\r\r\n        using namespace boost::qvm;\r\r\n        test_qvm::vector<V1,3> axis; axis.a[1]=1;\r\r\n        for( float r=0; r<6.28f; r+=0.5f )\r\r\n            {\r\r\n            test_qvm::quaternion<Q1> q1=rot_quat(axis,r);\r\r\n            test_qvm::matrix<M1,3,3> x1=convert_to< test_qvm::matrix<M1,3,3> >(q1);\r\r\n            test_qvm::rotation_y(x1.b,r);\r\r\n            BOOST_QVM_TEST_CLOSE(x1.a,x1.b,0.000001f);\r\r\n            test_qvm::quaternion<Q2> q2(42,1);\r\r\n            set_rot(q2,axis,r);\r\r\n            test_qvm::matrix<M2,3,3> x2=convert_to< test_qvm::matrix<M2,3,3> >(q2);\r\r\n            test_qvm::rotation_y(x2.b,r);\r\r\n            BOOST_QVM_TEST_CLOSE(x2.a,x2.b,0.000001f);\r\r\n            test_qvm::quaternion<Q1> q3(42,1);\r\r\n            test_qvm::quaternion<Q1> q4(42,1);\r\r\n            rotate(q3,axis,r);\r\r\n            q3 = q3*q1;\r\r\n            BOOST_QVM_TEST_EQ(q3.a,q3.a);\r\r\n            }\r\r\n        }\r\r\n\r\r\n    void\r\r\n    test_z()\r\r\n        {\r\r\n        using namespace boost::qvm;\r\r\n        test_qvm::vector<V1,3> axis; axis.a[2]=1;\r\r\n        for( float r=0; r<6.28f; r+=0.5f )\r\r\n            {\r\r\n            test_qvm::quaternion<Q1> q1=rot_quat(axis,r);\r\r\n            test_qvm::matrix<M1,3,3> x1=convert_to< test_qvm::matrix<M1,3,3> >(q1);\r\r\n            test_qvm::rotation_z(x1.b,r);\r\r\n            BOOST_QVM_TEST_CLOSE(x1.a,x1.b,0.000001f);\r\r\n            test_qvm::quaternion<Q2> q2(42,1);\r\r\n            set_rot(q2,axis,r);\r\r\n            test_qvm::matrix<M2,3,3> x2=convert_to< test_qvm::matrix<M2,3,3> >(q2);\r\r\n            test_qvm::rotation_z(x2.b,r);\r\r\n            BOOST_QVM_TEST_CLOSE(x2.a,x2.b,0.000001f);\r\r\n            test_qvm::quaternion<Q1> q3(42,1);\r\r\n            test_qvm::quaternion<Q1> q4(42,1);\r\r\n            rotate(q3,axis,r);\r\r\n            q3 = q3*q1;\r\r\n            BOOST_QVM_TEST_EQ(q3.a,q3.a);\r\r\n            }\r\r\n        }\r\r\n    }\r\r\n\r\r\nint\r\r\nmain()\r\r\n    {\r\r\n    test_x();\r\r\n    test_y();\r\r\n    test_z();\r\r\n    return boost::report_errors();\r\r\n    }\r\r\n", "meta": {"hexsha": "a3b6bb5e964e1c1366f705ced2a9cf61c92a3ad8", "size": 3402, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "deps/boost_1_63_0/libs/qvm/test/rot_quat_test.cpp", "max_stars_repo_name": "newtondev/drachtio-server", "max_stars_repo_head_hexsha": "cd18c6c0e1aa05501b068fc373682333bab5640c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "deps/boost_1_63_0/libs/qvm/test/rot_quat_test.cpp", "max_issues_repo_name": "newtondev/drachtio-server", "max_issues_repo_head_hexsha": "cd18c6c0e1aa05501b068fc373682333bab5640c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "deps/boost_1_63_0/libs/qvm/test/rot_quat_test.cpp", "max_forks_repo_name": "newtondev/drachtio-server", "max_forks_repo_head_hexsha": "cd18c6c0e1aa05501b068fc373682333bab5640c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.4375, "max_line_length": 85, "alphanum_fraction": 0.5164609053, "num_tokens": 1075, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768249, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.4617646879281376}}
{"text": "#ifndef DRC_CONTROL_EXPONENTIAL_FORM_HPP_\n#define DRC_CONTROL_EXPONENTIAL_FORM_HPP_\n#include \"drake/util/Polynomial.h\"\n#include <Eigen/Dense>\n\nclass ExponentialForm {\n  private: \n    double m_a;\n    double m_b;\n    double m_c;\n\n  public:\n    ExponentialForm(double a, double b, double c) {\n      m_a = a;\n      m_b = b;\n      m_c = c;\n    }\n\n    Polynomial<double> taylorExpand(int degree) const;\n\n    ExponentialForm operator+(const double x) {\n      ExponentialForm expform(this->m_a, this->m_b, this->m_c + x);\n      return expform;\n    }\n    ExponentialForm operator-(const double x) {\n      ExponentialForm expform(this->m_a, this->m_b, this->m_c - x);\n      return expform;\n    };\n\n    double value(double t) const;\n};\n\n#endif", "meta": {"hexsha": "a464f755f1089975dafc546f6f244214aedcf3c0", "size": 732, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "software/control/src/ExponentialForm.hpp", "max_stars_repo_name": "liangfok/oh-distro", "max_stars_repo_head_hexsha": "eeee1d832164adce667e56667dafc64a8d7b8cee", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 92.0, "max_stars_repo_stars_event_min_datetime": "2016-01-14T21:03:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-01T17:57:46.000Z", "max_issues_repo_path": "software/control/src/ExponentialForm.hpp", "max_issues_repo_name": "liangfok/oh-distro", "max_issues_repo_head_hexsha": "eeee1d832164adce667e56667dafc64a8d7b8cee", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 62.0, "max_issues_repo_issues_event_min_datetime": "2016-01-16T18:08:14.000Z", "max_issues_repo_issues_event_max_datetime": "2016-03-24T15:16:28.000Z", "max_forks_repo_path": "software/control/src/ExponentialForm.hpp", "max_forks_repo_name": "liangfok/oh-distro", "max_forks_repo_head_hexsha": "eeee1d832164adce667e56667dafc64a8d7b8cee", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2016-01-14T21:26:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T03:10:39.000Z", "avg_line_length": 22.1818181818, "max_line_length": 67, "alphanum_fraction": 0.6612021858, "num_tokens": 201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7248702642896702, "lm_q2_score": 0.6370308013713526, "lm_q1q2_score": 0.46176468535071274}}
{"text": "/*=============================================================================\r\n    Spirit v1.6.0\r\n    Copyright (c) 2002-2003 Joel de Guzman\r\n    http://spirit.sourceforge.net/\r\n\r\n    Permission to copy, use, modify, sell and distribute this software is\r\n    granted provided this copyright notice appears in all copies. This\r\n    software is provided \"as is\" without express or implied warranty, and\r\n    with no claim as to its suitability for any purpose.\r\n=============================================================================*/\r\n///////////////////////////////////////////////////////////////////////////////\r\n//\r\n//  A Roman Numerals Parser (demonstrating the symbol table)\r\n//\r\n//  [ JDG 8/22/2002 ]\r\n//\r\n///////////////////////////////////////////////////////////////////////////////\r\n#include <boost/spirit/core.hpp>\r\n#include <boost/spirit/symbols/symbols.hpp>\r\n#include <iostream>\r\n#include <string>\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\nusing namespace std;\r\nusing namespace boost::spirit;\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n//\r\n//  Parse roman hundreds (100..900) numerals using the symbol table.\r\n//  Notice that the data associated with each slot is passed\r\n//  to attached semantic actions.\r\n//\r\n///////////////////////////////////////////////////////////////////////////////\r\nstruct hundreds : symbols<unsigned>\r\n{\r\n    hundreds()\r\n    {\r\n        add\r\n            (\"C\"    , 100)\r\n            (\"CC\"   , 200)\r\n            (\"CCC\"  , 300)\r\n            (\"CD\"   , 400)\r\n            (\"D\"    , 500)\r\n            (\"DC\"   , 600)\r\n            (\"DCC\"  , 700)\r\n            (\"DCCC\" , 800)\r\n            (\"CM\"   , 900)\r\n        ;\r\n    }\r\n\r\n} hundreds_p;\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n//\r\n//  Parse roman tens (10..90) numerals using the symbol table.\r\n//\r\n///////////////////////////////////////////////////////////////////////////////\r\nstruct tens : symbols<unsigned>\r\n{\r\n    tens()\r\n    {\r\n        add\r\n            (\"X\"    , 10)\r\n            (\"XX\"   , 20)\r\n            (\"XXX\"  , 30)\r\n            (\"XL\"   , 40)\r\n            (\"L\"    , 50)\r\n            (\"LX\"   , 60)\r\n            (\"LXX\"  , 70)\r\n            (\"LXXX\" , 80)\r\n            (\"XC\"   , 90)\r\n        ;\r\n    }\r\n\r\n} tens_p;\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n//\r\n//  Parse roman ones (1..9) numerals using the symbol table.\r\n//\r\n///////////////////////////////////////////////////////////////////////////////\r\nstruct ones : symbols<unsigned>\r\n{\r\n    ones()\r\n    {\r\n        add\r\n            (\"I\"    , 1)\r\n            (\"II\"   , 2)\r\n            (\"III\"  , 3)\r\n            (\"IV\"   , 4)\r\n            (\"V\"    , 5)\r\n            (\"VI\"   , 6)\r\n            (\"VII\"  , 7)\r\n            (\"VIII\" , 8)\r\n            (\"IX\"   , 9)\r\n        ;\r\n    }\r\n\r\n} ones_p;\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n//\r\n//  Semantic actions\r\n//\r\n///////////////////////////////////////////////////////////////////////////////\r\nstruct add_1000\r\n{\r\n    add_1000(unsigned& r_) : r(r_) {}\r\n    void operator()(char) const { r += 1000; }\r\n    unsigned& r;\r\n};\r\n\r\nstruct add_roman\r\n{\r\n    add_roman(unsigned& r_) : r(r_) {}\r\n    void operator()(unsigned n) const { r += n; }\r\n    unsigned& r;\r\n};\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n//\r\n//  roman (numerals) grammar\r\n//\r\n///////////////////////////////////////////////////////////////////////////////\r\nstruct roman : public grammar<roman>\r\n{\r\n    template <typename ScannerT>\r\n    struct definition\r\n    {\r\n        definition(roman const& self)\r\n        {\r\n            first\r\n                =   +ch_p('M')  [add_1000(self.r)]\r\n                ||  hundreds_p  [add_roman(self.r)]\r\n                ||  tens_p      [add_roman(self.r)]\r\n                ||  ones_p      [add_roman(self.r)];\r\n\r\n            //  Note the use of the || operator. The expression\r\n            //  a || b reads match a or b and in sequence. Try\r\n            //  defining the roman numerals grammar in YACC or\r\n            //  PCCTS. Spirit rules! :-)\r\n        }\r\n\r\n        rule<ScannerT> first;\r\n        rule<ScannerT> const&\r\n        start() const { return first; }\r\n    };\r\n\r\n    roman(unsigned& r_) : r(r_) {}\r\n    unsigned& r;\r\n};\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n//\r\n//  Main driver code\r\n//\r\n///////////////////////////////////////////////////////////////////////////////\r\nint\r\nmain()\r\n{\r\n    cout << \"/////////////////////////////////////////////////////////\\n\\n\";\r\n    cout << \"\\t\\tRoman Numerals Parser\\n\\n\";\r\n    cout << \"/////////////////////////////////////////////////////////\\n\\n\";\r\n    cout << \"Type a Roman Numeral ...or [q or Q] to quit\\n\\n\";\r\n\r\n    //  Start grammar definition\r\n\r\n    string str;\r\n    while (getline(cin, str))\r\n    {\r\n        if (str[0] == 'q' || str[0] == 'Q')\r\n            break;\r\n\r\n        unsigned n = 0;\r\n        roman roman_p(n);\r\n        if (parse(str.c_str(), roman_p).full)\r\n        {\r\n            cout << \"parsing succeeded\\n\";\r\n            cout << \"result = \" << n << \"\\n\\n\";\r\n        }\r\n        else\r\n        {\r\n            cout << \"parsing failed\\n\\n\";\r\n        }\r\n    }\r\n\r\n    cout << \"Bye... :-) \\n\\n\";\r\n\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "816eda6cdef9e42ff511642203c8d259988f18b6", "size": 5363, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sdk/boost_1_30_0/libs/spirit/example/fundamental/roman_numerals.cpp", "max_stars_repo_name": "acidicMercury8/xray-1.0", "max_stars_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-01-30T12:51:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-31T08:36:49.000Z", "max_issues_repo_path": "sdk/boost_1_30_0/libs/spirit/example/fundamental/roman_numerals.cpp", "max_issues_repo_name": "acidicMercury8/xray-1.0", "max_issues_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_issues_repo_licenses": ["Linux-OpenIB"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sdk/boost_1_30_0/libs/spirit/example/fundamental/roman_numerals.cpp", "max_forks_repo_name": "acidicMercury8/xray-1.0", "max_forks_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0785340314, "max_line_length": 80, "alphanum_fraction": 0.3279880664, "num_tokens": 1081, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.46176468414189575}}
{"text": "#include \"HelmertTransformation.h\"\n#include <boost/test/included/unit_test.hpp>\n\n#include <cstdio>\n\nusing namespace boost::unit_test;\n\nnamespace\n{\nconst double GR = M_PI / 180.0;\n}\n\nusing namespace boost::unit_test;\n\ntest_suite* init_unit_test_suite(int argc, char* argv[])\n{\n  const char* name = \"HelmertTransformationTest tester\";\n  unit_test_log.set_threshold_level(log_messages);\n  framework::master_test_suite().p_name.value = name;\n  BOOST_TEST_MESSAGE(\"\");\n  BOOST_TEST_MESSAGE(name);\n  BOOST_TEST_MESSAGE(std::string(std::strlen(name), '='));\n  return NULL;\n}\n\nBOOST_AUTO_TEST_CASE(toGeocentricTestZeroHeight)\n{\n  unit_test_log.set_threshold_level(log_messages);\n  BOOST_TEST_MESSAGE(\"+ [Testing conversion from FMI sphere to WGS84]\");\n\n  const double R0 = 6371220.0;\n  const double lat0 = 60;\n  const double lon0 = 25;\n\n  Fmi::ReferenceEllipsoid fmi(R0, 0);\n  Fmi::HelmertTransformation conv, conv2;\n\n  for (int i = 0; i <= 2; i++)\n  {\n    Fmi::HelmertTransformation::FmiSphereConvScalingType scaling_type =\n        static_cast<Fmi::HelmertTransformation::FmiSphereConvScalingType>(i);\n\n    conv.set_fmi_sphere_to_reference_ellipsoid_conv(\n        R0, GR * lat0, GR * lon0, Fmi::ReferenceEllipsoid::wgs84, scaling_type);\n\n    conv2.set_reference_ellipsoid_to_fmi_sphere_conv(\n        R0, GR * lat0, GR * lon0, Fmi::ReferenceEllipsoid::wgs84, scaling_type);\n\n    // printf(\"H: %16.5f %16.5f %16.5f %16.12f\\n\", conv.tx, conv.ty, conv.tz, conv.m);\n    // printf(\"H: %16.5f %16.5f %16.5f %16.12f\\n\", conv2.tx, conv2.ty, conv2.tz, conv2.m);\n    // printf(\"## %s\\n\", Fmi::get_fmi_sphere_towgs84_proj4_string(R0, lat0*GR, lon0*GR,\n    //                                                           scaling_type).c_str());\n\n    const int N = 1;\n    double y_step = 0.01;\n    double x_step = 2 * y_step;\n    for (int ix = -N; ix <= N; ix++)\n      for (int iy = -N; iy <= N; iy++)\n      {\n        double lat1 = GR * (lat0 + iy * y_step);\n        double lon1 = GR * (lon0 + ix * x_step);\n        const auto fmi_xyz = fmi.to_geocentric(lat1, lon1, 0.0);\n        const auto wgs_xyz = conv(fmi_xyz);\n        double lat2, lon2, h2;\n        double lat3, lon3, h3;\n        Fmi::ReferenceEllipsoid::wgs84.to_geodetic(wgs_xyz, &lat2, &lon2, &h2);\n\n        BOOST_CHECK_CLOSE(lat2 / GR, lat1 / GR, 0.008);\n        BOOST_CHECK_CLOSE(lon2 / GR, lon1 / GR, 0.008);\n        BOOST_CHECK_SMALL(h2, 0.5);\n\n        const auto fmi2_xyz = conv2(wgs_xyz);\n        fmi.to_geodetic(fmi2_xyz, &lat3, &lon3, &h3);\n\n        BOOST_CHECK_CLOSE(lat3 / GR, lat1 / GR, 1e-5);\n        BOOST_CHECK_CLOSE(lon3 / GR, lon1 / GR, 1e-5);\n        BOOST_CHECK_SMALL(h3, 0.001);\n\n#if 0\n            printf(\"## %15.8f %15.8f \", lat1/GR, lon1/GR);\n            printf(\" : %15.8f %15.8f %12.4f\", (lat2-lat1)/GR, (lon2-lon1)/GR, h2);\n            printf(\" : %15.8f %15.8f %12.4f\", (lat3-lat1)/GR, (lon3-lon1)/GR, h3);\n            printf(\"\\n\");\n            //printf(\" : %15.3f %15.3f %15.3f \", fmi_xyz[0] , fmi_xyz[1], fmi_xyz[2]);\n            //printf(\" : %15.3f %15.3f %15.3f \", wgs_xyz[0] , wgs_xyz[1], wgs_xyz[2]);\n            //printf(\" : %15.3f %15.3f %15.3f \", fmi2_xyz[0] , fmi2_xyz[1], fmi2_xyz[2]);\n            //printf(\"\\n\");\n#endif\n      }\n  }\n}\n", "meta": {"hexsha": "5d49fc8d92f652a9a77f7e277679d0c57e3f1995", "size": 3205, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/HelmertTransformationTest.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": "test/HelmertTransformationTest.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": "test/HelmertTransformationTest.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": 34.8369565217, "max_line_length": 90, "alphanum_fraction": 0.6115444618, "num_tokens": 1078, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208004, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.46169621672682926}}
{"text": "// This file is part of PoseEstimation.\n// Copyright (c) 2021, Eijiro Shibusawa <phd_kimberlite@yahoo.co.jp>\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#ifndef THREE_POINT_UTIL_HPP_\n#define THREE_POINT_UTIL_HPP_\n\n#include \"ThreePoint.hpp\"\n\n#include <Eigen/Geometry>\n\n#include <random>\n\nnamespace ThreePoint\n{\ntemplate <typename FloatType, typename RNG>\nvoid getRandomRotation(RNG &rng, FloatType *R, FloatType *q = NULL)\n{\n\t// construct random rotation\n\tstd::uniform_real_distribution<FloatType> urd(0, static_cast<FloatType>(2 * M_PI));\n\tFloatType rx = urd(rng);\n\tFloatType ry = urd(rng);\n\tFloatType rz = urd(rng);\n\tEigen::Quaternion<FloatType> mq;\n\tmq = Eigen::AngleAxis<FloatType>(rz, Eigen::Matrix<FloatType, 3, 1>::UnitZ()) *\n\t\tEigen::AngleAxis<FloatType>(ry, Eigen::Matrix<FloatType, 3, 1>::UnitY()) *\n\t\tEigen::AngleAxis<FloatType>(rx, Eigen::Matrix<FloatType, 3, 1>::UnitX());\n\n\tEigen::Map<Eigen::Matrix<FloatType, 3, 3, Eigen::RowMajor> > mR(R);\n\tmR = mq.toRotationMatrix();\n\n\tif (q != NULL)\n\t{\n\t\tq[0] = mq.x();\n\t\tq[1] = mq.y();\n\t\tq[2] = mq.z();\n\t\tq[3] = mq.w();\n\t}\n}\n\ntemplate <typename FloatType, typename RNG>\nvoid getRandomTranslation(RNG &rng, FloatType *t)\n{\n\t// cosntruct random translation\n\tstd::uniform_real_distribution<FloatType> urd(static_cast<FloatType>(-0.5), static_cast<FloatType>(0.5));\n\tt[0] = 5 + urd(rng);\n\tt[1] = 5 + urd(rng);\n\tt[2] = 5 + urd(rng);\n}\n\ntemplate <typename FloatType, typename RNG>\ninline void getRandomScale(RNG &rng, FloatType &s)\n{\n\tstd::uniform_real_distribution<FloatType> urd(static_cast<FloatType>(-0.05), static_cast<FloatType>(0.05));\n\ts = 1 + urd(rng);\n}\n\ntemplate <typename FloatType, typename RNG>\nvoid getRandomPoint(int n, RNG &rng, FloatType *X)\n{\n\t// construct random point on unit shpere\n\tstd::uniform_real_distribution<FloatType> urd(static_cast<FloatType>(-0.5), static_cast<FloatType>(0.5));\n\tfor (int i = 0; i < 3 * n; i++)\n\t{\n\t\tX[i] = urd(rng);\n\t}\n\tEigen::Map<Eigen::Matrix<FloatType, 3, Eigen::Dynamic> > mX(X, 3, n);\n\tmX.colwise().normalize();\n}\n\ntemplate <typename FloatType>\nvoid getRandomCorrespondences(int n, FloatType *R, FloatType *t, FloatType &s, std::vector<FloatType> &pts1, std::vector<FloatType> &pts2)\n{\n\tstd::random_device rd;\n\tstd::mt19937 rng(rd());\n\n\t// construct random rotation\n\tgetRandomRotation(rng, R);\n\n\t// construct random translation\n\tgetRandomTranslation(rng, t);\n\n\t// random scale\n\tgetRandomScale(rng, s);\n\n\t// construct random point on unit shpere\n\tpts1.resize(3 * n);\n\tgetRandomPoint(n, rng, &(pts1[0]));\n\n\t// transform\n\tpts2.resize(3 * n);\n\tThreePoint<FloatType>::transformPoints(n, s, R, t, &(pts1[0]), &(pts2[0]));\n}\n\n}\n\n#endif // THREE_POINT_UTIL_HPP_", "meta": {"hexsha": "a7a5c706443ff44ccd58c88c0dcd2e820b99db81", "size": 3930, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/ThreePointUtil.hpp", "max_stars_repo_name": "eshibusawa/PoseEstimation", "max_stars_repo_head_hexsha": "7eca2b21673b2cd42f40c1f05d4f67ee89bdc279", "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/ThreePointUtil.hpp", "max_issues_repo_name": "eshibusawa/PoseEstimation", "max_issues_repo_head_hexsha": "7eca2b21673b2cd42f40c1f05d4f67ee89bdc279", "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/ThreePointUtil.hpp", "max_forks_repo_name": "eshibusawa/PoseEstimation", "max_forks_repo_head_hexsha": "7eca2b21673b2cd42f40c1f05d4f67ee89bdc279", "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.5897435897, "max_line_length": 138, "alphanum_fraction": 0.724173028, "num_tokens": 1063, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4616962167268292}}
{"text": "//\n//  InverseKinematics.cpp\n//  Eigen_test\n//\n//  Created by Emil-Iliev on 5.02.20.\n//  Copyright \u00a9 2020 Emil Iliev. All rights reserved.\n//\n\n#include \"InverseKinematicsCommand.hpp\"\n#include <iostream>\n#include <Eigen/Dense>\n#include \"AbstractSolver.hpp\"\n\nusing namespace Eigen;\n\nInverseKinematicsCommand::InverseKinematicsCommand(std::shared_ptr<AbstractSolver> solver):\n    solver(solver) {\n}\n\nvoid InverseKinematicsCommand::execute() {\n    VectorXf desired_position(6);\n    float posX, posY, posZ;\n    std::cout<< \"Enter position (X, Y, Z): \";\n    std::cin >> posX >> posY >> posZ;\n    std::cout<< \"Calculating ... \\n\";\n    desired_position << posX, posY, posZ, 0.0, 0.0, 0.0;\n\n    solver->setDesiredPosistion(desired_position);\n    solver->calculateData();\n}\n\nstd::string InverseKinematicsCommand::key() {\n    return \"inverse_kinematics_command\";\n}\n", "meta": {"hexsha": "b901e0a399d56fa7c0af570db76e6c98dbcccb2a", "size": 854, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Eigen_test/Eigen_test/Commands/InverseKinematicsCommand.cpp", "max_stars_repo_name": "emiliev/RoboticArm", "max_stars_repo_head_hexsha": "69d0a73166c819d93cef28b7a6b6cc267345dd68", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Eigen_test/Eigen_test/Commands/InverseKinematicsCommand.cpp", "max_issues_repo_name": "emiliev/RoboticArm", "max_issues_repo_head_hexsha": "69d0a73166c819d93cef28b7a6b6cc267345dd68", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Eigen_test/Eigen_test/Commands/InverseKinematicsCommand.cpp", "max_forks_repo_name": "emiliev/RoboticArm", "max_forks_repo_head_hexsha": "69d0a73166c819d93cef28b7a6b6cc267345dd68", "max_forks_repo_licenses": ["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.4, "max_line_length": 91, "alphanum_fraction": 0.6967213115, "num_tokens": 237, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.6187804407739559, "lm_q1q2_score": 0.4616962149862037}}
{"text": "/**\n   \\file lbfgs_method.hpp\n   \\brief large bfgs method, used to perform large scale optimization\n   \\author Junhua Gu\n */\n\n#ifndef LBFGS_METHOD\n#define LBFGS_METHOD\n#define OPT_HEADER\n#include <core/optimizer.hpp>\n//#include <blitz/array.h>\n#include <limits>\n#include <cstdlib>\n#include <core/opt_traits.hpp>\n#include \"../linmin/linmin.hpp\"\n#include <math/num_diff.hpp>\n#include <cassert>\n#include <cmath>\n#include <ctime>\n#include <vector>\n#include <algorithm>\n#include \"lbfgs.h\"\n#include \"lbfgs.cpp\"\n/*\n *\n*/\n#include <iostream>\nusing std::cerr;\nusing std::endl;\n\nnamespace opt_utilities\n{\n\n  template<typename rT,typename pT>\n  lbfgsfloatval_t lbfgs_adapter(\n\t\t\t\tvoid *instance,\n\t\t\t\tconst lbfgsfloatval_t *x,\n\t\t\t\tlbfgsfloatval_t *g,\n\t\t\t\tconst int n,\n\t\t\t\tconst lbfgsfloatval_t step\n\t\t\t\t)\n  {\n    pT px;\n    resize(px,n);\n    for(int i=0;i<n;++i)\n      {\n\tset_element(px,i,x[i]);\n      }\n    \n    lbfgsfloatval_t result=((func_obj<rT,pT>*)instance)->eval(px);\n    pT grad(gradient(*static_cast<func_obj<rT,pT>*>(instance),px));\n    for(int i=0;i<n;++i)\n      {\n\tg[i]=get_element(grad,i);\n      }\n    return result;\n  }\n\n\n  \n  template <typename rT,typename pT>\n  class lbfgs_method\n    :public opt_method<rT,pT>\n  {\n  public:\n    typedef pT array1d_type;\n    typedef rT T;\n  private:\n    func_obj<rT,pT>* p_fo;\n    optimizer<rT,pT>* p_optimizer;\n    \n    //typedef blitz::Array<rT,2> array2d_type;\n    \n    \n  private:\n    array1d_type start_point;\n    array1d_type end_point;\n    \n  private:\n    rT threshold;\n  private:\n    rT func(const pT& x)\n    {\n      assert(p_fo!=0);\n      return p_fo->eval(x);\n    }\n\n    const char* do_get_type_name()const\n    {\n      return \"large scale bfgs\";\n    }\n  public:\n    lbfgs_method()\n      :threshold(1e-4)\n    {}\n\n    virtual ~lbfgs_method()\n    {\n    };\n\n    lbfgs_method(const lbfgs_method<rT,pT>& rhs)\n      :p_fo(rhs.p_fo),p_optimizer(rhs.p_optimizer),\n       start_point(rhs.start_point),\n       end_point(rhs.end_point),\n       threshold(rhs.threshold)\n    {\n    }\n\n    lbfgs_method<rT,pT>& operator=(const lbfgs_method<rT,pT>& rhs)\n    {\n      threshold=rhs.threshold;\n      p_fo=rhs.p_fo;\n      p_optimizer=rhs.p_optimizer;\n      opt_eq(start_point,rhs.start_point);\n      opt_eq(end_point,rhs.end_point);\n    }\n    \n    opt_method<rT,pT>* do_clone()const\n    {\n      return new lbfgs_method<rT,pT>(*this);\n    }\n    \n    void do_set_start_point(const array1d_type& p)\n    {\n      start_point.resize(get_size(p));\n      opt_eq(start_point,p);\n      \n    }\n\n    array1d_type do_get_start_point()const\n    {\n      return start_point;\n    }\n\n    void do_set_precision(rT t)\n    {\n      threshold=t;\n    }\n\n    rT do_get_precision()const\n    {\n      return threshold;\n    }\n\n    void do_set_optimizer(optimizer<rT,pT>& o)\n    {\n      p_optimizer=&o;\n      p_fo=p_optimizer->ptr_func_obj();\n    }\n    \n    \n    \n    pT do_optimize()\n    {\n      lbfgs_parameter_t param;\n      lbfgs_parameter_init(&param);\n      param.ftol=threshold;\n      std::vector<lbfgsfloatval_t> buffer(get_size(start_point));\n      for(int i=0;i<buffer.size();++i)\n\t{\n\t  buffer[i]=get_element(start_point,i);\n\t}\n      lbfgsfloatval_t fx;\n      lbfgs(get_size(start_point),&buffer[0],&fx,\n\t    lbfgs_adapter<rT,pT>,0,p_fo,&param);\n      for(int i=0;i<buffer.size();++i)\n\t{\n\t  set_element(start_point,i,buffer[i]);\n\t}\n      return start_point;\n    } \n  };\n  \n}\n\n\n#endif\n//EOF\n", "meta": {"hexsha": "a719f1dc1e10de9f38f5a9419bbe7ef59067adb4", "size": 3397, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "methods/lbfgs/lbfgs_method.hpp", "max_stars_repo_name": "liweitianux/opt_utilities", "max_stars_repo_head_hexsha": "17363d2b870c88db108984a9a59d79c12d677e93", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "methods/lbfgs/lbfgs_method.hpp", "max_issues_repo_name": "liweitianux/opt_utilities", "max_issues_repo_head_hexsha": "17363d2b870c88db108984a9a59d79c12d677e93", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "methods/lbfgs/lbfgs_method.hpp", "max_forks_repo_name": "liweitianux/opt_utilities", "max_forks_repo_head_hexsha": "17363d2b870c88db108984a9a59d79c12d677e93", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-05T16:14:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-05T16:14:44.000Z", "avg_line_length": 18.9776536313, "max_line_length": 69, "alphanum_fraction": 0.6205475419, "num_tokens": 987, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4616962097407677}}
{"text": "#include \"observable.hpp\"\n\n#include <stdarg.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n#undef NDEBUG\n#include <Eigen/Dense>\n#include <array>\n#include <cassert>\n#include <cmath>\n#include <fstream>\n#include <iostream>\n\n#include \"state.hpp\"\n#include \"utility.hpp\"\n\nvoid HermitianQuantumOperator::add_operator(const PauliOperator* mpt) {\n    if (std::abs(mpt->get_coef().imag()) > 0) {\n        std::cerr << \"Error: HermitianQuantumOperator::add_operator(const \"\n                     \"PauliOperator* mpt): PauliOperator must be Hermitian.\"\n                  << std::endl;\n        return;\n    }\n    GeneralQuantumOperator::add_operator(mpt);\n}\n\nvoid HermitianQuantumOperator::add_operator(\n    CPPCTYPE coef, std::string pauli_string) {\n    if (std::abs(coef.imag()) > 0) {\n        std::cerr << \"Error: HermitianQuantumOperator::add_operator(const \"\n                     \"PauliOperator* mpt): PauliOperator must be Hermitian.\"\n                  << std::endl;\n        return;\n    }\n    GeneralQuantumOperator::add_operator(coef, pauli_string);\n}\n\nCPPCTYPE HermitianQuantumOperator::get_expectation_value(\n    const QuantumStateBase* state) const {\n    return GeneralQuantumOperator::get_expectation_value(state).real();\n}\n\nCPPCTYPE\nHermitianQuantumOperator::solve_ground_state_eigenvalue_by_lanczos_method(\n    QuantumStateBase* init_state, const UINT iter_count,\n    const CPPCTYPE mu) const {\n    if (this->get_term_count() == 0) {\n        std::cerr << \"Error: \"\n                     \"HermitianQuantumOperator::solve_ground_state_eigenvalue_\"\n                     \"by_lanczos_method(\"\n                     \"QuantumStateBase * state, const UINT iter_count, const \"\n                     \"CPPCTYPE mu): At least one PauliOperator is required.\";\n        return 0;\n    }\n\n    // Implemented based on\n    // https://files.transtutors.com/cdn/uploadassignments/472339_1_-numerical-linear-aljebra.pdf\n    CPPCTYPE mu_;\n    if (mu == 0.0) {\n        // mu is not changed from default value.\n        mu_ = this->calculate_default_mu();\n    } else {\n        mu_ = mu;\n    }\n\n    const auto qubit_count = this->get_qubit_count();\n    QuantumState tmp_state(qubit_count);\n    QuantumState mu_timed_state(qubit_count);\n    // work_states: [q_{i-1}, q_i, q_{i+1}]\n    // q_0, q_1, q_2,... span Krylov subspace.\n    init_state->normalize(init_state->get_squared_norm());\n    std::array<QuantumState, 3> work_states = {QuantumState(qubit_count),\n        QuantumState(qubit_count), QuantumState(qubit_count)};\n    work_states.at(1).load(init_state);\n\n    Eigen::VectorXd alpha_v(iter_count);\n    Eigen::VectorXd beta_v(iter_count - 1);\n    for (UINT i = 0; i < iter_count; i++) {\n        // v = (A - \u03bcI) * q_i\n        mu_timed_state.load(&work_states.at(1));\n        mu_timed_state.multiply_coef(-mu_);\n        this->apply_to_state(&tmp_state, work_states.at(1), &work_states.at(2));\n        work_states.at(2).add_state(&mu_timed_state);\n\n        // \u03b1_i = q_i^T * v\n        alpha_v(i) =\n            state::inner_product(&work_states.at(1), &work_states.at(2)).real();\n        // In the last iteration, no need to calculate \u03b2.\n        if (i == iter_count - 1) {\n            break;\n        }\n        // v -= \u03b1_i * q_i\n        tmp_state.load(&work_states.at(1));\n        tmp_state.multiply_coef(-alpha_v(i));\n        work_states.at(2).add_state(&tmp_state);\n        if (i != 0) {\n            // v -= \u03b2_{i-1} * q_{i-1}\n            tmp_state.load(&work_states.at(0));\n            tmp_state.multiply_coef(-beta_v(i - 1));\n            work_states.at(2).add_state(&tmp_state);\n        }\n\n        // \u03b2_i = ||v||\n        beta_v(i) = std::sqrt(work_states.at(2).get_squared_norm());\n        // q_{i+1} = v / \u03b2_i\n        work_states.at(2).multiply_coef(1 / beta_v(i));\n        work_states.at(0).load(&work_states.at(1));\n        work_states.at(1).load(&work_states.at(2));\n    }\n\n    // Compute eigenvalue of a symmetric matrix T whose diagonal elements are\n    // `alpha_v` and subdiagonal elements are `beta_v`.\n    Eigen::SelfAdjointEigenSolver<ComplexMatrix> solver;\n    solver.computeFromTridiagonal(alpha_v, beta_v);\n    const auto eigenvalues = solver.eigenvalues();\n    // Find ground state eigenvalue.\n    UINT minimum_eigenvalue_index = 0;\n    auto minimum_eigenvalue = eigenvalues(0);\n    for (UINT i = 0; i < eigenvalues.size(); i++) {\n        if (eigenvalues(i) < minimum_eigenvalue) {\n            minimum_eigenvalue_index = i;\n            minimum_eigenvalue = eigenvalues(i);\n        }\n    }\n\n    auto eigenvectors = solver.eigenvectors();\n    auto eigenvector_in_krylov = eigenvectors.col(minimum_eigenvalue_index);\n    // Store ground state eigenvector to `init_state`.\n    // If \u03bb is an eigenvalue of T and q is the eigenvector, Tq = \u03bbq.\n    // And let V be a matrix whose column vectors span Krylov subspace.\n    // Then, T = V^* AV where A is this observable.\n    // Tq = \u03bbq, VV^* AVq = V\u03bbq, A(Vq) = \u03bb(Vq).\n    // So, an eigenvector of A for \u03bb is Vq.\n    // q_0 = init_state\n    work_states.at(1).load(init_state);\n    init_state->multiply_coef(0.0);\n    assert(eigenvector_in_krylov.size() == iter_count);\n    for (UINT i = 0; i < iter_count; i++) {\n        // q += v_i * q_i, where q is eigenvector to compute\n        tmp_state.load(&work_states.at(1));\n        tmp_state.multiply_coef(eigenvector_in_krylov(i));\n        init_state->add_state(&tmp_state);\n\n        // v = (A - \u03bcI) * q_i\n        mu_timed_state.load(&work_states.at(1));\n        mu_timed_state.multiply_coef(-mu_);\n        this->apply_to_state(&tmp_state, work_states.at(1), &work_states.at(2));\n        work_states.at(2).add_state(&mu_timed_state);\n        if (i == iter_count - 1) {\n            break;\n        }\n\n        // v -= \u03b1_i * q_i\n        tmp_state.load(&work_states.at(1));\n        tmp_state.multiply_coef(-alpha_v(i));\n        work_states.at(2).add_state(&tmp_state);\n        if (i != 0) {\n            // v -= \u03b2_{i-1} * q_{i-1}\n            tmp_state.load(&work_states.at(0));\n            tmp_state.multiply_coef(-beta_v(i - 1));\n            work_states.at(2).add_state(&tmp_state);\n        }\n\n        // q_{i+1} = v / \u03b2_i\n        work_states.at(2).multiply_coef(1 / beta_v[i]);\n        work_states.at(0).load(&work_states.at(1));\n        work_states.at(1).load(&work_states.at(2));\n    }\n\n    return minimum_eigenvalue + mu_;\n}\n\nstd::string HermitianQuantumOperator::to_string() const {\n    std::stringstream os;\n    auto term_count = this->get_term_count();\n    for (UINT index = 0; index < term_count; index++) {\n        os << this->get_term(index)->get_coef().real() << \" \";\n        os << this->get_term(index)->get_pauli_string();\n        if (index != term_count - 1) {\n            os << \" + \";\n        }\n    }\n    return os.str();\n}\n\nnamespace observable {\nHermitianQuantumOperator* create_observable_from_openfermion_file(\n    std::string file_path) {\n    UINT qubit_count = 0;\n    std::vector<CPPCTYPE> coefs;\n    std::vector<std::string> ops;\n\n    std::ifstream ifs;\n    ifs.open(file_path);\n\n    if (!ifs) {\n        std::cerr << \"ERROR: Cannot open file\" << std::endl;\n        return NULL;\n    }\n\n    // loading lines and check qubit_count\n    std::string str_buf;\n    std::vector<std::string> index_list;\n\n    std::string line;\n    while (getline(ifs, line)) {\n        std::tuple<double, double, std::string> parsed_items =\n            parse_openfermion_line(line);\n        const auto coef_real = std::get<0>(parsed_items);\n        const auto coef_imag = std::get<1>(parsed_items);\n        str_buf = std::get<2>(parsed_items);\n\n        CPPCTYPE coef(coef_real, coef_imag);\n        coefs.push_back(coef);\n        ops.push_back(str_buf);\n        index_list = split(str_buf, \"IXYZ \");\n\n        for (UINT i = 0; i < index_list.size(); ++i) {\n            UINT n = std::stoi(index_list[i]) + 1;\n            if (qubit_count < n) qubit_count = n;\n        }\n    }\n    if (!ifs.eof()) {\n        std::cerr << \"ERROR: Invalid format\" << std::endl;\n        return NULL;\n    }\n    ifs.close();\n\n    HermitianQuantumOperator* observable =\n        new HermitianQuantumOperator(qubit_count);\n\n    for (UINT i = 0; i < ops.size(); ++i) {\n        observable->add_operator(new PauliOperator(ops[i].c_str(), coefs[i]));\n    }\n\n    return observable;\n}\n\nHermitianQuantumOperator* create_observable_from_openfermion_text(\n    const std::string& text) {\n    UINT qubit_count = 0;\n    std::vector<CPPCTYPE> coefs;\n    std::vector<std::string> ops;\n\n    std::vector<std::string> lines;\n    std::string str_buf;\n    std::vector<std::string> index_list;\n\n    lines = split(text, \"\\n\");\n    for (std::string line : lines) {\n        std::tuple<double, double, std::string> parsed_items =\n            parse_openfermion_line(line);\n        const auto coef_real = std::get<0>(parsed_items);\n        const auto coef_imag = std::get<1>(parsed_items);\n        str_buf = std::get<2>(parsed_items);\n\n        CPPCTYPE coef(coef_real, coef_imag);\n        coefs.push_back(coef);\n        ops.push_back(str_buf);\n        index_list = split(str_buf, \"IXYZ \");\n\n        for (UINT i = 0; i < index_list.size(); ++i) {\n            UINT n = std::stoi(index_list[i]) + 1;\n            if (qubit_count < n) qubit_count = n;\n        }\n    }\n    HermitianQuantumOperator* hermitian_quantum_operator =\n        new HermitianQuantumOperator(qubit_count);\n\n    for (UINT i = 0; i < ops.size(); ++i) {\n        hermitian_quantum_operator->add_operator(\n            new PauliOperator(ops[i].c_str(), coefs[i]));\n    }\n\n    return hermitian_quantum_operator;\n}\n\nstd::pair<HermitianQuantumOperator*, HermitianQuantumOperator*>\ncreate_split_observable(std::string file_path) {\n    UINT qubit_count = 0;\n    std::vector<CPPCTYPE> coefs;\n    std::vector<std::string> ops;\n\n    std::ifstream ifs;\n    ifs.open(file_path);\n\n    if (!ifs) {\n        std::cerr << \"ERROR: Cannot open file\" << std::endl;\n        return std::make_pair(\n            (HermitianQuantumOperator*)NULL, (HermitianQuantumOperator*)NULL);\n    }\n\n    // loading lines and check qubit_count\n    std::string str_buf;\n    std::vector<std::string> index_list;\n\n    std::string line;\n    while (getline(ifs, line)) {\n        std::tuple<double, double, std::string> parsed_items =\n            parse_openfermion_line(line);\n        const auto coef_real = std::get<0>(parsed_items);\n        const auto coef_imag = std::get<1>(parsed_items);\n        str_buf = std::get<2>(parsed_items);\n\n        CPPCTYPE coef(coef_real, coef_imag);\n        coefs.push_back(coef);\n        ops.push_back(str_buf);\n        index_list = split(str_buf, \"IXYZ \");\n\n        for (UINT i = 0; i < index_list.size(); ++i) {\n            UINT n = std::stoi(index_list[i]) + 1;\n            if (qubit_count < n) qubit_count = n;\n        }\n    }\n    if (!ifs.eof()) {\n        std::cerr << \"ERROR: Invalid format\" << std::endl;\n        return std::make_pair(\n            (HermitianQuantumOperator*)NULL, (HermitianQuantumOperator*)NULL);\n    }\n    ifs.close();\n\n    HermitianQuantumOperator* observable_diag =\n        new HermitianQuantumOperator(qubit_count);\n    HermitianQuantumOperator* observable_non_diag =\n        new HermitianQuantumOperator(qubit_count);\n\n    for (UINT i = 0; i < ops.size(); ++i) {\n        if (ops[i].find(\"X\") != std::string::npos ||\n            ops[i].find(\"Y\") != std::string::npos) {\n            observable_non_diag->add_operator(\n                new PauliOperator(ops[i].c_str(), coefs[i]));\n        } else {\n            observable_diag->add_operator(\n                new PauliOperator(ops[i].c_str(), coefs[i]));\n        }\n    }\n\n    return std::make_pair(observable_diag, observable_non_diag);\n}\n}  // namespace observable\n", "meta": {"hexsha": "f50f16548c177767ac520d4404742a5554244981", "size": 11592, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cppsim/observable.cpp", "max_stars_repo_name": "kodack64/qulacs-osaka", "max_stars_repo_head_hexsha": "4ccc3ff084f10942e22d8663a01ed67efd24d9f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cppsim/observable.cpp", "max_issues_repo_name": "kodack64/qulacs-osaka", "max_issues_repo_head_hexsha": "4ccc3ff084f10942e22d8663a01ed67efd24d9f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cppsim/observable.cpp", "max_forks_repo_name": "kodack64/qulacs-osaka", "max_forks_repo_head_hexsha": "4ccc3ff084f10942e22d8663a01ed67efd24d9f7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.8947368421, "max_line_length": 97, "alphanum_fraction": 0.6099033816, "num_tokens": 3135, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.46169620974076764}}
{"text": "#define BOOST_TEST_MODULE fastforestTests\n#include <boost/test/unit_test.hpp>\n\n#include \"fastforest.h\"\n\n#include <fstream>\n#include <cmath>\n\nconstexpr fastforest::FeatureType tolerance = 1e-4;\nconstexpr std::size_t nSamples = 100;\nusing RefPredictionType = float;\n\nBOOST_AUTO_TEST_CASE(ExampleTest) {\n    std::vector<std::string> features{\"f0\", \"f1\", \"f2\", \"f3\", \"f4\"};\n\n    const auto fastForest = fastforest::load_txt(\"continuous/model.txt\", features);\n\n    std::vector<fastforest::FeatureType> input{0.0, 0.2, 0.4, 0.6, 0.8};\n\n    fastforest::FeatureType score = fastForest(input.data());\n    fastforest::FeatureType logistcScore = 1. / (1. + std::exp(-score));\n}\n\nBOOST_AUTO_TEST_CASE(BasicTest) {\n    std::vector<std::string> features{\"f0\", \"f1\", \"f2\", \"f3\", \"f4\"};\n\n    const auto fastForest = fastforest::load_txt(\"continuous/model.txt\", features);\n\n    std::ifstream fileX(\"continuous/X.csv\");\n    std::ifstream filePreds(\"continuous/preds.csv\");\n\n    std::vector<fastforest::FeatureType> input(5);\n    fastforest::FeatureType score;\n    RefPredictionType ref;\n\n    for (std::size_t i = 0; i < nSamples; ++i) {\n        for (auto& x : input) {\n            fileX >> x;\n        }\n        score = fastForest(input.data());\n        filePreds >> ref;\n\n        BOOST_CHECK_CLOSE(score, ref, tolerance);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(SoftmaxTest) {\n    std::vector<std::string> features{\"f0\", \"f1\", \"f2\", \"f3\", \"f4\"};\n\n    const auto fastForest = fastforest::load_txt(\"softmax/model.txt\", features);\n\n    std::ifstream fileX(\"softmax/X.csv\");\n    std::ifstream filePreds(\"softmax/preds.csv\");\n\n    std::vector<fastforest::FeatureType> input(5);\n    fastforest::FeatureType score;\n    RefPredictionType ref;\n\n    for (std::size_t i = 0; i < nSamples; ++i) {\n        for (auto& x : input) {\n            fileX >> x;\n        }\n        for (auto& x : fastForest.softmax(input.data(), 3)) {\n            filePreds >> ref;\n            BOOST_CHECK_CLOSE(x, ref, tolerance);\n        }\n    }\n}\n\n// This test covers the case of trees with a single leaf node.\nBOOST_AUTO_TEST_CASE(SoftmaxNSamples100NFeatures100Test) {\n    std::vector<std::string> features;\n    for (std::size_t i = 0; i < 100; ++i) {\n        features.emplace_back(std::string(\"f\") + std::to_string(i));\n    }\n\n    const auto fastForest = fastforest::load_txt(\"softmax_n_samples_100_n_features_100/model.txt\", features);\n\n    std::ifstream fileX(\"softmax_n_samples_100_n_features_100/X.csv\");\n    std::ifstream filePreds(\"softmax_n_samples_100_n_features_100/preds.csv\");\n\n    std::vector<fastforest::FeatureType> input(features.size());\n    fastforest::FeatureType score;\n    RefPredictionType ref;\n\n    for (std::size_t i = 0; i < nSamples; ++i) {\n        for (auto& x : input) {\n            fileX >> x;\n        }\n        for (auto& x : fastForest.softmax(input.data(), 3)) {\n            filePreds >> ref;\n            BOOST_CHECK_CLOSE(x, ref, tolerance);\n        }\n    }\n}\n\nBOOST_AUTO_TEST_CASE(SoftmaxArrayTest) {\n    std::vector<std::string> features{\"f0\", \"f1\", \"f2\", \"f3\", \"f4\"};\n\n    const auto fastForest = fastforest::load_txt(\"softmax/model.txt\", features);\n\n    std::ifstream fileX(\"softmax/X.csv\");\n    std::ifstream filePreds(\"softmax/preds.csv\");\n\n    std::vector<fastforest::FeatureType> input(5);\n    fastforest::FeatureType score;\n    RefPredictionType ref;\n\n    for (std::size_t i = 0; i < nSamples; ++i) {\n        for (auto& x : input) {\n            fileX >> x;\n        }\n        for (auto& x : fastForest.softmax<3>(input.data())) {\n            filePreds >> ref;\n            BOOST_CHECK_CLOSE(x, ref, tolerance);\n        }\n    }\n}\n\nBOOST_AUTO_TEST_CASE(SerializationTest) {\n    {\n        std::vector<std::string> features{\"f0\", \"f1\", \"f2\", \"f3\", \"f4\"};\n        const auto fastForest = fastforest::load_txt(\"continuous/model.txt\", features);\n        fastForest.write_bin(\"continuous/forest.bin\");\n    }\n\n    const auto fastForest = fastforest::load_bin(\"continuous/forest.bin\");\n\n    std::ifstream fileX(\"continuous/X.csv\");\n    std::ifstream filePreds(\"continuous/preds.csv\");\n\n    std::vector<fastforest::FeatureType> input(5);\n    fastforest::FeatureType score;\n    RefPredictionType ref;\n\n    for (std::size_t i = 0; i < nSamples; ++i) {\n        for (auto& x : input) {\n            fileX >> x;\n        }\n        score = fastForest(input.data());\n        filePreds >> ref;\n\n        BOOST_CHECK_CLOSE(score, ref, tolerance);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(DiscreteTest) {\n    std::vector<std::string> features{\"f0\", \"f1\", \"f2\", \"f3\", \"f4\"};\n\n    const auto fastForest = fastforest::load_txt(\"discrete/model.txt\", features);\n\n    std::ifstream fileX(\"discrete/X.csv\");\n    std::ifstream filePreds(\"discrete/preds.csv\");\n\n    std::vector<fastforest::FeatureType> input(5);\n    fastforest::FeatureType score;\n    RefPredictionType ref;\n\n    for (std::size_t i = 0; i < nSamples; ++i) {\n        for (auto& x : input) {\n            fileX >> x;\n        }\n        score = fastForest(input.data());\n        filePreds >> ref;\n\n        BOOST_CHECK_CLOSE(score, ref, tolerance);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(ManyfeaturesTest) {\n    std::vector<std::string> features{};\n    for (int i = 0; i < 311; ++i) {\n        features.push_back(std::string(\"f\") + std::to_string(i));\n    }\n\n    const auto fastForest = fastforest::load_txt(\"manyfeatures/model.txt\", features);\n\n    std::ifstream fileX(\"manyfeatures/X.csv\");\n    std::ifstream filePreds(\"manyfeatures/preds.csv\");\n\n    std::vector<fastforest::FeatureType> input(features.size());\n    fastforest::FeatureType score;\n    RefPredictionType ref;\n\n    for (std::size_t i = 0; i < nSamples; ++i) {\n        for (auto& x : input) {\n            fileX >> x;\n        }\n        score = fastForest(input.data());\n        filePreds >> ref;\n\n        BOOST_CHECK_CLOSE(score, ref, tolerance);\n    }\n}\n\n#ifdef EXPERIMENTAL_TMVA_SUPPORT\n\nBOOST_AUTO_TEST_CASE(BasicTMVAXMLTest) {\n    std::vector<std::string> features{\"f0\", \"f1\", \"f2\", \"f3\", \"f4\"};\n\n    const auto fastForest = fastforest::load_tmva_xml(\"continuous/model.xml\", features);\n\n    std::ifstream fileX(\"continuous/X.csv\");\n    std::ifstream filePreds(\"continuous/preds.csv\");\n\n    std::vector<fastforest::FeatureType> input(5);\n    fastforest::FeatureType score;\n    RefPredictionType ref;\n\n    for (std::size_t i = 0; i < nSamples; ++i) {\n        for (auto& x : input) {\n            fileX >> x;\n        }\n        score = fastForest(input.data());\n        filePreds >> ref;\n\n        BOOST_CHECK_CLOSE(score, ref, tolerance);\n    }\n}\n\n#endif\n", "meta": {"hexsha": "75430d903e6087668a2ac38ea971f39c2ea675c6", "size": 6502, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test.cpp", "max_stars_repo_name": "kpedro88/XGBoost-FastForest", "max_stars_repo_head_hexsha": "5a784d5c2642a377a919b530a2dc465aa0529df7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 58.0, "max_stars_repo_stars_event_min_datetime": "2019-06-25T07:09:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T03:16:20.000Z", "max_issues_repo_path": "test/test.cpp", "max_issues_repo_name": "kpedro88/XGBoost-FastForest", "max_issues_repo_head_hexsha": "5a784d5c2642a377a919b530a2dc465aa0529df7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17.0, "max_issues_repo_issues_event_min_datetime": "2019-07-30T12:07:54.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T13:35:03.000Z", "max_forks_repo_path": "test/test.cpp", "max_forks_repo_name": "kpedro88/XGBoost-FastForest", "max_forks_repo_head_hexsha": "5a784d5c2642a377a919b530a2dc465aa0529df7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2019-06-25T12:56:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T06:47:59.000Z", "avg_line_length": 29.2882882883, "max_line_length": 109, "alphanum_fraction": 0.6213472778, "num_tokens": 1778, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.46169620974076764}}
{"text": "#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE SinogramCreatorTest\n#include <boost/test/unit_test.hpp>\n\n#include \"../SinogramCreatorTools.h\"\n#include <iostream>\n\nBOOST_AUTO_TEST_SUITE(FirstSuite)\n\nBOOST_AUTO_TEST_CASE(roundToNearesMultiplicity_test) {\n  BOOST_REQUIRE_EQUAL(\n      SinogramCreatorTools::roundToNearesMultiplicity(0.0f, 1.f), 0u);\n  BOOST_REQUIRE_EQUAL(\n      SinogramCreatorTools::roundToNearesMultiplicity(0.4f, 1.f), 0u);\n  BOOST_REQUIRE_EQUAL(\n      SinogramCreatorTools::roundToNearesMultiplicity(0.5f, 1.f), 1u);\n  BOOST_REQUIRE_EQUAL(\n      SinogramCreatorTools::roundToNearesMultiplicity(30.f, 1.f), 30u);\n  BOOST_REQUIRE_EQUAL(\n      SinogramCreatorTools::roundToNearesMultiplicity(0.00f, 0.01f), 0u);\n  BOOST_REQUIRE_EQUAL(\n      SinogramCreatorTools::roundToNearesMultiplicity(0.01f, 0.01f), 1u);\n  BOOST_REQUIRE_EQUAL(\n      SinogramCreatorTools::roundToNearesMultiplicity(0.02f, 0.01f), 2u);\n}\n\nBOOST_AUTO_TEST_CASE(test_angle_middle) {\n  const float EPSILON = 0.01f;\n  const float r = 10;\n  const float maxDistance = 20.f;\n  const float accuracy = 0.1f;\n\n  for (int i = 0; i < 360; i++) {\n    const float x1 = r * std::cos((i - 1) * (M_PI / 180.f));\n    const float y1 = r * std::sin((i - 1) * (M_PI / 180.f));\n    const float x2 = r * std::cos((i + 1) * (M_PI / 180.f));\n    const float y2 = r * std::sin((i + 1) * (M_PI / 180.f));\n    const auto result = SinogramCreatorTools::getSinogramRepresentation(\n        x1, y1, x2, y2, maxDistance, accuracy,\n        std::ceil(maxDistance * 2.f * (1.f / accuracy)), 180);\n    BOOST_REQUIRE_EQUAL(result.second, i % 180);\n    const float distance = i < 180 ? r : -r;\n    const float distanceResult =\n        SinogramCreatorTools::roundToNearesMultiplicity(distance + maxDistance,\n                                                        accuracy);\n    BOOST_REQUIRE_CLOSE(result.first, distanceResult, EPSILON);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(test_lor_slice) {\n  const float EPSILON = 0.0001f;\n\n  float x1 = 0.f;\n  float y1 = 0.f;\n  float z1 = 0.f;\n  float t1 = 0.f;\n  float x2 = 0.f;\n  float y2 = 0.f;\n  float z2 = 0.f;\n  float t2 = 0.f;\n  BOOST_REQUIRE_CLOSE(\n      SinogramCreatorTools::calculateLORSlice(x1, y1, z1, t1, x2, y2, z2, t2),\n      0.f, EPSILON);\n  x1 = 1.f;\n  x2 = -1.f;\n  BOOST_REQUIRE_CLOSE(\n      SinogramCreatorTools::calculateLORSlice(x1, y1, z1, t1, x2, y2, z2, t2),\n      0.f, EPSILON);\n  t1 = 10 * 3.33564095; // speed-of-light * 10 * 3.33564095 ~= 1\n  t2 = 10 * 3.33564095;\n  BOOST_REQUIRE_CLOSE(\n      SinogramCreatorTools::calculateLORSlice(x1, y1, z1, t1, x2, y2, z2, t2),\n      0.f, EPSILON);\n  x1 = 0.f;\n  x2 = 0.f;\n  z1 = 1.f;\n  z2 = -1.f;\n  BOOST_REQUIRE_CLOSE(\n      SinogramCreatorTools::calculateLORSlice(x1, y1, z1, t1, x2, y2, z2, t2),\n      0.f, EPSILON);\n  z1 = -1.f;\n  z2 = 1.f;\n  BOOST_REQUIRE_CLOSE(\n      SinogramCreatorTools::calculateLORSlice(x1, y1, z1, t1, x2, y2, z2, t2),\n      0.f, EPSILON);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "f863ea26f711417bba9b4f7681f8d160e609a836", "size": 2948, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ImageReconstruction/tests/SinogramCreatorToolsTest.cpp", "max_stars_repo_name": "pnp-sushil/j-pet-framework-examples", "max_stars_repo_head_hexsha": "2d3f3aba1064bfb215179f88be9c2bf383851deb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ImageReconstruction/tests/SinogramCreatorToolsTest.cpp", "max_issues_repo_name": "pnp-sushil/j-pet-framework-examples", "max_issues_repo_head_hexsha": "2d3f3aba1064bfb215179f88be9c2bf383851deb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ImageReconstruction/tests/SinogramCreatorToolsTest.cpp", "max_forks_repo_name": "pnp-sushil/j-pet-framework-examples", "max_forks_repo_head_hexsha": "2d3f3aba1064bfb215179f88be9c2bf383851deb", "max_forks_repo_licenses": ["Apache-2.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.1235955056, "max_line_length": 79, "alphanum_fraction": 0.657394844, "num_tokens": 1010, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.46169620974076764}}
{"text": "// smooth_feedback: Control theory on Lie groups\n// https://github.com/pettni/smooth_feedback\n//\n// Licensed under the MIT License <http://opensource.org/licenses/MIT>.\n//\n// Copyright (c) 2021 Petter Nilsson, John B. Mains\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n#ifndef SMOOTH__FEEDBACK__NLP_HPP_\n#define SMOOTH__FEEDBACK__NLP_HPP_\n\n/**\n * @file\n * @brief Nonlinear program definition.\n */\n\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n#include <smooth/diff.hpp>\n\n#include <limits>\n\n#include \"collocation.hpp\"\n\nnamespace smooth::feedback {\n\n/**\n * @brief Nonlinear Programming Problem\n * \\f[\n *  \\begin{cases}\n *   \\min_{x}    & f(x)                    \\\\\n *   \\text{s.t.} & x_l \\leq x \\leq x_u     \\\\\n *               & g_l \\leq g(x) \\leq g_u\n *  \\end{cases}\n * \\f]\n * for \\f$ f : \\mathbb{R}^n \\rightarrow \\mathbb{R} \\f$ and\n * \\f$ g : \\mathbb{R}^n \\rightarrow \\mathbb{R}^m \\f$.\n */\nstruct NLP\n{\n  /// @brief Number of variables\n  std::size_t n;\n\n  /// @brief Number of constraints\n  std::size_t m;\n\n  /// @brief Objective function (R^n -> R)\n  std::function<double(Eigen::VectorXd)> f;\n\n  /// @brief Variable bounds (R^n)\n  Eigen::VectorXd xl, xu;\n\n  /// @brief Constraint function (R^n -> R^m)\n  std::function<Eigen::VectorXd(Eigen::VectorXd)> g;\n\n  /// @brief Constaint bounds (R^m)\n  Eigen::VectorXd gl, gu;\n\n  /// @brief Jacobian of objective function (R^n -> R^{n x n})\n  std::function<Eigen::SparseMatrix<double>(Eigen::VectorXd)> df_dx;\n\n  /// @brief Jacobian of constraint function (R^n -> R^{m x n})\n  std::function<Eigen::SparseMatrix<double>(Eigen::VectorXd)> dg_dx;\n\n  /// @brief Hessian of objective function (R^n -> R^{n x n}) [optional]\n  std::optional<std::function<Eigen::SparseMatrix<double>(Eigen::VectorXd, Eigen::VectorXd)>>\n    d2f_dx2 = std::nullopt;\n\n  /**\n   * @brief Projected Hessian of constraint function (R^m, R^n -> R^{n x n}) [optional]\n   *\n   * Should return the derivative\n   * \\f[\n   *  H_g(\\lambda, x) = \\nabla^2_x \\lambda^T g(x), \\quad \\lambda \\in \\mathbb{R}^m, x \\in\n   * \\mathbb{R}^n \\f]\n   */\n  std::optional<std::function<Eigen::SparseMatrix<double>(Eigen::VectorXd, Eigen::VectorXd)>>\n    d2g_dx2 = std::nullopt;\n};\n\nstruct NLPSolution\n{\n  /// @brief Solver status\n  enum class Status {\n    Optimal,\n    PrimalInfeasible,\n    DualInfeasible,\n    MaxIterations,\n    MaxTime,\n    Unknown,\n  } status;\n\n  /// @brief Number of iterations\n  std::size_t iter{0};\n\n  /// @brief Variable values\n  Eigen::VectorXd x;\n\n  /// @brief Inequality multipliers\n  Eigen::VectorXd zl, zu;\n\n  /// @brief Constraint multipliers\n  Eigen::VectorXd lambda;\n\n  /// @brief Objective\n  double objective{0};\n};\n\n}  // namespace smooth::feedback\n\n#endif  // SMOOTH__FEEDBACK__NLP_HPP_\n", "meta": {"hexsha": "2efa86c2370563b1eed9137c38c29264b6af3530", "size": 3741, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/smooth/feedback/nlp.hpp", "max_stars_repo_name": "pettni/smooth_feedback", "max_stars_repo_head_hexsha": "5f967a6b513a7eeea7c70406416440e7c9a5d2e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-09-08T16:18:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-28T06:13:55.000Z", "max_issues_repo_path": "include/smooth/feedback/nlp.hpp", "max_issues_repo_name": "pettni/smooth_feedback", "max_issues_repo_head_hexsha": "5f967a6b513a7eeea7c70406416440e7c9a5d2e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2021-09-08T16:39:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-10T03:51:41.000Z", "max_forks_repo_path": "include/smooth/feedback/nlp.hpp", "max_forks_repo_name": "pettni/smooth_feedback", "max_forks_repo_head_hexsha": "5f967a6b513a7eeea7c70406416440e7c9a5d2e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2022-02-07T15:56:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T07:23:18.000Z", "avg_line_length": 29.0, "max_line_length": 93, "alphanum_fraction": 0.6773589949, "num_tokens": 1035, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802476562643, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4615930119802453}}
{"text": "/* Copyright (c) 2015, Julian Straub <jstraub@csail.mit.edu> Licensed\n * under the MIT license. See the license file LICENSE.\n */\n#pragma once\n\n#include <stdint.h>\n#include <iostream>\n#include <vector>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/QR>\n\n// CUDA runtime\n#include <cuda_runtime.h>\n// Utilities and system includes\n//#include <helper_functions.h>\n#include <nvidia/helper_cuda.h>\n\n//#include <mmf/defines.h>\n\nusing namespace Eigen;\nusing std::min;\nusing std::max;\nusing std::cout;\nusing std::endl;\n\ntemplate<typename T>\nclass OptSO3ApproxCpu\n{\n  public:\n  OptSO3ApproxCpu(T t_max = 5.0, T dt = 0.05)\n    : t_max_(t_max), dt_(dt), t_(0)\n  { \n    R_ = Matrix<T,3,3>::Identity();\n  };\n\n  virtual ~OptSO3ApproxCpu()\n  { };\n\n//  virtual T conjugateGradient(Matrix<T,3,3>& R, uint32_t maxIter=100);\n  virtual T conjugateGradient(Matrix<T,3,3>& R, \n      const Matrix<T,Dynamic,Dynamic>& qKarch, \n      const Matrix<T,Dynamic,1>& Ns, \n      uint32_t maxIter=100);\n\n  /* return a skew symmetric matrix from A */\n  Matrix<T,3,3> enforceSkewSymmetry(const Matrix<T,3,3> &A) const\n  {return 0.5*(A-A.transpose());};\n\n  const Matrix<T,3,3>& R() const {return R_;};\n  /* matrix of the 6 directions of the MF */\n  Matrix<T,Dynamic,Dynamic> M() const;\n\n  static Matrix<T,Dynamic,Dynamic> Rot2M(const Matrix<T,3,3>& R);\n\nprotected:\n  T t_max_, dt_;\n  uint32_t t_; // timestep\n  Matrix<T,3,3> R_; // previous rotation\n  Matrix<T,3,6> qKarch_; // karcher means for all axes\n  Matrix<T,1,6> Ns_; // number of normals for each axis\n\n  virtual void conjugateGradientPostparation_impl(Matrix<T,3,3>& R);\n  virtual T conjugateGradient_impl(Matrix<T,3,3>& R, T res0,\n      uint32_t maxIter=100);\n  /* \n   * evaluate cost function for a given assignment of npormals to axes\n   */\n  virtual T evalCostFunction(Matrix<T,3,3>& R);\n  /* compute Jacobian */\n  virtual void computeJacobian(Matrix<T,3,3>&J, Matrix<T,3,3>& R);\n\n  /* \n   * updates G and H from rotation R and jacobian J\n   */\n  virtual void updateGandH(Matrix<T,3,3>& G, Matrix<T,3,3>& G_prev,\n      Matrix<T,3,3>& H, const Matrix<T,3,3>& R, const Matrix<T,3,3>& J,\n      const Matrix<T,3,3>& M_t_min, bool resetH);\n  /* \n   * performs line search starting at R in direction of H returns min\n   * of cost function and updates R, and M_t_min\n   */\n  virtual T linesearch(Matrix<T,3,3>& R, Matrix<T,3,3>& M_t_min, const\n      Matrix<T,3,3>& H, T t_max=1.0, T dt=0.1);\n  /* convert a Rotation matrix R to a MF representaiton of the axes */\n  void Rot2M(Matrix<T,3,3>& R, T *mu);\n};\n\n", "meta": {"hexsha": "94d0714cb70d236d16149f4e358e5497b2949ded", "size": 2541, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mmf/optimizationSO3_approx.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/mmf/optimizationSO3_approx.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/mmf/optimizationSO3_approx.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": 28.5505617978, "max_line_length": 72, "alphanum_fraction": 0.6686343959, "num_tokens": 808, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.46159301198024527}}
{"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/estimators/estimate_calibrated_absolute_pose.h\"\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <memory>\n#include <vector>\n\n#include \"theia/sfm/create_and_initialize_ransac_variant.h\"\n#include \"theia/sfm/estimators/feature_correspondence_2d_3d.h\"\n#include \"theia/sfm/pose/perspective_three_point.h\"\n#include \"theia/solvers/estimator.h\"\n#include \"theia/solvers/sample_consensus_estimator.h\"\n#include \"theia/util/util.h\"\n\nnamespace theia {\nnamespace {\n\nusing Eigen::Matrix3d;\nusing Eigen::Vector3d;\n\n// An estimator for computing the absolute pose from 3 feature\n// correspondences. The feature correspondences should be normalized by the\n// focal length with the principal point at (0, 0).\nclass CalibratedAbsolutePoseEstimator\n    : public Estimator<FeatureCorrespondence2D3D, CalibratedAbsolutePose> {\n private:\n    // note: not \"fixed-size-vectorizable\" so no need to use aligned_allocator\n    // https://eigen.tuxfamily.org/dox/group__TopicFixedSizeVectorizable.html\n    std::vector<Eigen::Matrix3d> rotations;\n    std::vector<Eigen::Vector3d> translations;\n public:\n  CalibratedAbsolutePoseEstimator() {}\n\n  // 3 correspondences are needed to determine the absolute pose.\n  double SampleSize() const { return 3; }\n\n  // Estimates candidate absolute poses from correspondences.\n  bool EstimateModel(\n      const std::vector<FeatureCorrespondence2D3D>& correspondences,\n      std::vector<CalibratedAbsolutePose>* absolute_poses) const {\n    const Eigen::Vector2d features[3] = {correspondences[0].feature,\n                                         correspondences[1].feature,\n                                         correspondences[2].feature};\n    const Eigen::Vector3d world_points[3] = {correspondences[0].world_point,\n                                             correspondences[1].world_point,\n                                             correspondences[2].world_point};\n\n    // avoid massive reallocation if called frequently\n    auto mutable_this = const_cast<CalibratedAbsolutePoseEstimator&>(*this);\n    auto &rotations = mutable_this.rotations;\n    auto &translations = mutable_this.translations;\n    rotations.clear();\n    translations.clear();\n    if (!PoseFromThreePoints(features,\n                             world_points,\n                             &rotations,\n                             &translations)) {\n      return false;\n    }\n\n    for (int i = 0; i < rotations.size(); i++) {\n      CalibratedAbsolutePose pose;\n      pose.rotation = rotations[i];\n      pose.position = -pose.rotation.transpose() * translations[i];\n      absolute_poses->emplace_back(pose);\n    }\n\n    return absolute_poses->size() > 0;\n  }\n\n  // The error for a correspondences given an absolute pose. This is the squared\n  // reprojection error.\n  double Error(const FeatureCorrespondence2D3D& correspondence,\n               const CalibratedAbsolutePose& absolute_pose) const {\n    // The reprojected point is computed as R * (X - c) where R is the camera\n    // rotation, c is the position, and X is the 3D point.\n    const Eigen::Vector2d reprojected_feature =\n        (absolute_pose.rotation *\n         (correspondence.world_point - absolute_pose.position)).hnormalized();\n    return (reprojected_feature - correspondence.feature).squaredNorm();\n  }\n};\n\nclass ReusableCalibratedAbsolutePoseEstimatorImpl : public ReusableCalibratedAbsolutePoseEstimator {\nprivate:\n  CalibratedAbsolutePoseEstimator absolute_pose_estimator;\n  std::unique_ptr<SampleConsensusEstimator<CalibratedAbsolutePoseEstimator> > ransac;\n\npublic:\n  ReusableCalibratedAbsolutePoseEstimatorImpl(\n    const RansacParameters& ransac_params,\n    const RansacType& ransac_type)\n  {\n    ransac = CreateAndInitializeRansacVariant(ransac_type, ransac_params, absolute_pose_estimator);\n  }\n\n  bool estimate(\n      const std::vector<FeatureCorrespondence2D3D>& normalized_correspondences,\n      CalibratedAbsolutePose* absolute_pose,\n      RansacSummary* ransac_summary) final {\n      // Estimate the absolute pose.\n      return ransac->Estimate(normalized_correspondences, absolute_pose, ransac_summary);\n  }\n};\n}  // namespace\n\nstd::unique_ptr<ReusableCalibratedAbsolutePoseEstimator> ReusableCalibratedAbsolutePoseEstimator::build(\n      const RansacParameters& ransac_params,\n      const RansacType& ransac_type) {\n  return std::make_unique<ReusableCalibratedAbsolutePoseEstimatorImpl>(ransac_params, ransac_type);\n}\n\nReusableCalibratedAbsolutePoseEstimator::~ReusableCalibratedAbsolutePoseEstimator() = default;\n\nbool EstimateCalibratedAbsolutePose(\n    const RansacParameters& ransac_params,\n    const RansacType& ransac_type,\n    const std::vector<FeatureCorrespondence2D3D>& normalized_correspondences,\n    CalibratedAbsolutePose* absolute_pose,\n    RansacSummary* ransac_summary)\n{\n  return ReusableCalibratedAbsolutePoseEstimatorImpl(ransac_params, ransac_type)\n    .estimate(normalized_correspondences, absolute_pose, ransac_summary);\n}\n}  // namespace theia\n", "meta": {"hexsha": "90c4a9bc5c48e9c719fdd22ee39e2feb28d270e9", "size": 6759, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/sfm/estimators/estimate_calibrated_absolute_pose.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/estimators/estimate_calibrated_absolute_pose.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/estimators/estimate_calibrated_absolute_pose.cc", "max_forks_repo_name": "SpectacularAI/TheiaSfM", "max_forks_repo_head_hexsha": "3dbb45cd6c239a4bab2beb46812c4ba7094a0625", "max_forks_repo_licenses": ["BSD-3-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.24375, "max_line_length": 104, "alphanum_fraction": 0.735463826, "num_tokens": 1519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.46159301198024527}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n//                                                                           //\n//                 polar v1.0 - August the 15th 2019                         //\n//                                                                           //\n///////////////////////////////////////////////////////////////////////////////\n\n///////////////////////////////////////////////////////////////////////////////\n//                                                                           //\n//  Copyright 2019 Matteo Tommasini                                          //\n//                                                                           //\n//  Licensed under the Apache License, Version 2.0 (the \"License\");          //\n//  you may not use this file except in compliance with the License.         //\n//  You may obtain a copy of the License at                                  //\n//                                                                           //\n//      http://www.apache.org/licenses/LICENSE-2.0                           //\n//                                                                           //\n//  Unless required by applicable law or agreed to in writing, software      //\n//  distributed under the License is distributed on an \"AS IS\" BASIS,        //\n//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //\n//  See the License for the specific language governing permissions and      //\n//  limitations under the License.                                           //\n//                                                                           //\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef ICM_H\n#define ICM_H\n\n#include <Eigen/Core>\n#include <Eigen/Eigenvalues> \n\n#include \"units.hpp\"\n#include \"options.hpp\"\n#include \"gaussiandataset.hpp\"\n\n///////////////////////////////////\n// ICM: Intensity Carrying Modes //\n///////////////////////////////////\nclass ICM \n{\n   private:\n\n   bool has_ICM_IR  = false,\n        has_ICM_VCD = false,\n        has_ICM_MAG = false;\n\n   Eigen::VectorXd ICM_intensity;\n   Eigen::MatrixXd ICM_displacement;\n\n   public:\n   ICM() = default;\n   explicit ICM(const GaussianDataset&, const std::string&);\n   void Diagonalize(const Eigen::MatrixXd&, Eigen::VectorXd&, Eigen::MatrixXd&);\n   void WriteMolden(const GaussianDataset&, const std::string&) const; \n   void PrintReport() const;\n\n};\n\n#endif // ICM_H\n\n", "meta": {"hexsha": "42fba76cf4c5d56b67c8b16c1cd6fb9681aa0461", "size": 2510, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "icm.hpp", "max_stars_repo_name": "matteo-maria-tommasini/polar", "max_stars_repo_head_hexsha": "276b45a081af1b0dd0853fcb5111f8da1514bd18", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "icm.hpp", "max_issues_repo_name": "matteo-maria-tommasini/polar", "max_issues_repo_head_hexsha": "276b45a081af1b0dd0853fcb5111f8da1514bd18", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "icm.hpp", "max_forks_repo_name": "matteo-maria-tommasini/polar", "max_forks_repo_head_hexsha": "276b45a081af1b0dd0853fcb5111f8da1514bd18", "max_forks_repo_licenses": ["Apache-2.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.8333333333, "max_line_length": 80, "alphanum_fraction": 0.3733067729, "num_tokens": 377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.46159300562692984}}
{"text": "//\n// Created by Yosuke Takahashi on 10/14/18.\n//\n\n#include <gtest/gtest.h>\n#include \"../src/particle_filter.h\"\n#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace std;\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\n\nTEST(ParticleFilter, SimpleTest) {\n    ASSERT_EQ(2, 2);\n}\n\nTEST(ParticleFilter, prediction) {\n    std::vector<Particle> particles;\n\n    Particle p;\n\n    p.x = 102;\n    p.y = 65;\n    p.theta = 5*M_PI/8;\n\n    double velocity = 110.0;\n    double yaw_rate = M_PI/8;\n    double delta_t = 0.1;\n\n    double sigma_pos[3] = {0.0, 0.0, 0.0}; // GPS measurement uncertainty [x [m], y [m], theta [rad]]\n\n    particles.push_back(p);\n\n    ParticleFilter pf;\n    pf.setParticles(particles);\n\n    pf.prediction(delta_t, sigma_pos, velocity, yaw_rate);\n\n    EXPECT_NEAR(pf.particles[0].x, 97.59, 0.01);\n    EXPECT_NEAR(pf.particles[0].y, 75.08, 0.01);\n    EXPECT_NEAR(pf.particles[0].theta, 51*M_PI/80, 0.01);\n}\n\nTEST(ParticleFilter, transformObservationCoordinateVehicleToMap_1) {\n    ParticleFilter pf;\n\n    Particle p;\n    LandmarkObs obs;\n\n    p.x = 4;\n    p.y = 5;\n    p.theta = -M_PI/2;\n    obs.x = 2;\n    obs.y = 2;\n\n    LandmarkObs map;\n\n    map = pf.transformObservationCoordinateVehicleToMap(p, obs);\n\n    EXPECT_NEAR(map.x, 6.0, 0.1);\n    EXPECT_NEAR(map.y, 3.0, 0.1);\n}\n\nTEST(ParticleFilter, transformObservationCoordinateVehicleToMap_2) {\n    ParticleFilter pf;\n\n    Particle p;\n    LandmarkObs obs;\n\n    p.x = 4;\n    p.y = 5;\n    p.theta = -M_PI/2;\n    obs.x = 3;\n    obs.y = -2;\n\n    LandmarkObs map;\n\n    map = pf.transformObservationCoordinateVehicleToMap(p, obs);\n\n    EXPECT_NEAR(map.x, 2.0, 0.1);\n    EXPECT_NEAR(map.y, 2.0, 0.1);\n}\n\nTEST(ParticleFilter, getNearestLandmark) {\n    ParticleFilter pf;\n\n    Particle p;\n    p.x = 4;\n    p.y = 5;\n    p.theta = -M_PI/2;\n\n    Map map;\n    Map::single_landmark_s l1, l2, l3, l4, l5;\n\n    l1.id_i = 1;\n    l1.x_f  = 5;\n    l1.y_f  = 3;\n    map.landmark_list.push_back(l1);\n\n    l2.id_i = 2;\n    l2.x_f  = 2;\n    l2.y_f  = 1;\n    map.landmark_list.push_back(l2);\n\n    l3.id_i = 3;\n    l3.x_f  = 6;\n    l3.y_f  = 1;\n    map.landmark_list.push_back(l3);\n\n    l4.id_i = 4;\n    l4.x_f  = 7;\n    l4.y_f  = 4;\n    map.landmark_list.push_back(l4);\n\n    l5.id_i = 5;\n    l5.x_f  = 4;\n    l5.y_f  = 7;\n    map.landmark_list.push_back(l5);\n\n    LandmarkObs obs1, obs2, obs3;\n    obs1.x = 2;\n    obs1.y = 2;\n\n    obs2.x = 3;\n    obs2.y = -2;\n\n    obs3.x = 0;\n    obs3.y = -4;\n\n    LandmarkObs obs_map1, obs_map2, obs_map3;\n    obs_map1 = pf.transformObservationCoordinateVehicleToMap(p, obs1);\n    obs_map2 = pf.transformObservationCoordinateVehicleToMap(p, obs2);\n    obs_map3 = pf.transformObservationCoordinateVehicleToMap(p, obs3);\n\n    LandmarkObs nearest_obs1, nearest_obs2, nearest_obs3;\n    nearest_obs1 = pf.getNearestLandmark(obs_map1, map);\n    nearest_obs2 = pf.getNearestLandmark(obs_map2, map);\n    nearest_obs3 = pf.getNearestLandmark(obs_map3, map);\n\n    EXPECT_EQ(nearest_obs1.id, 1);\n    EXPECT_EQ(nearest_obs2.id, 2);\n    EXPECT_EQ(nearest_obs3.id, 2);\n\n    double weight1, weight2, weight3;\n    double std_landmark[3] = {0.3, 0.3, 0.0};\n    weight1 = pf.getObservationWeight(obs_map1, nearest_obs1, std_landmark);\n    weight2 = pf.getObservationWeight(obs_map2, nearest_obs2, std_landmark);\n    weight3 = pf.getObservationWeight(obs_map3, nearest_obs3, std_landmark);\n\n    EXPECT_NEAR(weight1, 6.84e-3, 0.01e-3);\n    EXPECT_NEAR(weight2, 6.84e-3, 0.01e-3);\n    EXPECT_NEAR(weight3, 9.83e-49, 0.01e-49);\n}\n\nTEST(ParticleFilter, getParticleWeight) {\n    ParticleFilter pf;\n\n    Particle p;\n    p.x = 4;\n    p.y = 5;\n    p.theta = -M_PI/2;\n\n    Map map;\n    Map::single_landmark_s l1, l2, l3, l4, l5;\n\n    l1.id_i = 1;\n    l1.x_f  = 5;\n    l1.y_f  = 3;\n    map.landmark_list.push_back(l1);\n\n    l2.id_i = 2;\n    l2.x_f  = 2;\n    l2.y_f  = 1;\n    map.landmark_list.push_back(l2);\n\n    l3.id_i = 3;\n    l3.x_f  = 6;\n    l3.y_f  = 1;\n    map.landmark_list.push_back(l3);\n\n    l4.id_i = 4;\n    l4.x_f  = 7;\n    l4.y_f  = 4;\n    map.landmark_list.push_back(l4);\n\n    l5.id_i = 5;\n    l5.x_f  = 4;\n    l5.y_f  = 7;\n    map.landmark_list.push_back(l5);\n\n    LandmarkObs obs1, obs2, obs3;\n    obs1.x = 2;\n    obs1.y = 2;\n\n    obs2.x = 3;\n    obs2.y = -2;\n\n    obs3.x = 0;\n    obs3.y = -4;\n\n    std::vector<LandmarkObs> observations;\n    observations.push_back(obs1);\n    observations.push_back(obs2);\n    observations.push_back(obs3);\n\n    double std_landmark[3] = {0.3, 0.3, 0.0};\n    double weight = pf.getParticleWeight(p, std_landmark, observations, map);\n\n    EXPECT_NEAR(weight, 4.60e-53, 0.01e-53);\n}\n\n", "meta": {"hexsha": "f98ced86f4318dce5905af8223e79b1fa19960e9", "size": 4576, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/Tests.cpp", "max_stars_repo_name": "yostaka/particle-filter", "max_stars_repo_head_hexsha": "9aeb6a098a61c7f5ea0e4c8a2c468c7d77c9f013", "max_stars_repo_licenses": ["MIT"], "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/Tests.cpp", "max_issues_repo_name": "yostaka/particle-filter", "max_issues_repo_head_hexsha": "9aeb6a098a61c7f5ea0e4c8a2c468c7d77c9f013", "max_issues_repo_licenses": ["MIT"], "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/Tests.cpp", "max_forks_repo_name": "yostaka/particle-filter", "max_forks_repo_head_hexsha": "9aeb6a098a61c7f5ea0e4c8a2c468c7d77c9f013", "max_forks_repo_licenses": ["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.4835680751, "max_line_length": 101, "alphanum_fraction": 0.625, "num_tokens": 1622, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.46159300562692984}}
{"text": "#ifndef __Physical_Parameters_hpp_\n#define __Physical_Parameters_hpp_\n\n#include <Eigen/Geometry>\n#include <vector>\n\n\nusing namespace std;\n\n\n//Units:\n\t//Energy\n\textern const double GeV,eV,keV,MeV,TeV;\n\t//Mass\n\textern const double gram,kg;\n\t//Length\n\textern const double cm,mm,meter,km,fm,pb,parsec,kpc,Mpc;\n\t//Time\n\textern const double sec,minute,hour,day,year;\n\t//Temperature\n\textern const double Kelvin;\n\t//Others\n\textern const double erg;\n\n//Specific Parameters:\n\t//Masses\n\textern const double mPlanck,GNewton,mProton,mElectron,mNucleon;\n\t//Geographic Parameters\n\textern const double mEarth,rEarth,rhoEarth;\n\t//Solar Parameters\n\textern const double mSun,rSun,rhoSun;\n\t//Dark Matter Halo Parameters\n\textern const double v0,vesc;\n\textern const double Nesc;\n\textern const double ymax;\n\t//degree to rad\n\textern const double deg;\n\n//Unit Conversion\n\textern double InUnits(double quantity, double dimension);\n//Reduced Mass\n\textern double Mu(double m1,double m2);\n\n//Average inverse velocity\n\textern double AverageInvVelocity(double vE);\n\n//Nucleus Mass\n\textern double NucleusMass(double A);\n\n//Wimp Nucleus Cross-section with zero momentum transfer:\n\textern double sigmaSI(double mX,double sigman0,double A);\n//Total Wimp Nucleus Cross-section:\n\textern double TotalsigmaSI(double mX,double sigman0,double A,double vX=0.0);\n//Helm Form Factor (approximation)\n\textern double FF_HelmApproximation(double qSquared,double A);\n\textern double FF_HelmApproximation_Integrated(double mX,double vDM,double A);\n\t\n//Coordinate System Change\n\textern Eigen::Vector3d SphericalCoordinates(double r,double theta,double phi);\n\textern Eigen::Vector3d Equat2Gal(Eigen::Vector3d& v,double T=0.0);\n\textern Eigen::Vector3d GeoEcl2Gal(Eigen::Vector3d& v,double T=0.0);\n\textern Eigen::Vector3d HelEcl2Gal(Eigen::Vector3d& v,double T=0.0);\n\textern Eigen::Vector3d Gal2Equat(Eigen::Vector3d& v,double T=0.0);\n\n//fractional days\n\textern double FractionalDays(int date[3], int time[3]);\n\textern double LASTinSeconds(double nJ2000,double longitude=0);\n//Earth's Velocity in the galactic frame\n\textern Eigen::Vector3d EarthVelocity(double n=0.0);\n\n\t\n#endif\n\n\n\n\n\n\n\n", "meta": {"hexsha": "64794f6a9bda200309ede22446e5de8b2712d7bd", "size": 2131, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/Physical_Parameters.hpp", "max_stars_repo_name": "temken/DaMaSCUS", "max_stars_repo_head_hexsha": "14be6907230e5ef1b93809a6fb5842330497a7a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-09-13T13:36:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-30T19:35:12.000Z", "max_issues_repo_path": "include/Physical_Parameters.hpp", "max_issues_repo_name": "temken/DaMaSCUS", "max_issues_repo_head_hexsha": "14be6907230e5ef1b93809a6fb5842330497a7a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-06-06T14:43:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T13:01:56.000Z", "max_forks_repo_path": "include/Physical_Parameters.hpp", "max_forks_repo_name": "temken/DaMaSCUS", "max_forks_repo_head_hexsha": "14be6907230e5ef1b93809a6fb5842330497a7a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-06-09T09:48:10.000Z", "max_forks_repo_forks_event_max_datetime": "2017-06-09T09:48:10.000Z", "avg_line_length": 26.6375, "max_line_length": 79, "alphanum_fraction": 0.7752229, "num_tokens": 566, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4615930056269298}}
{"text": "#include <iostream>\n#include <fstream>\n#include <vector>\n#include <string>\n#include \"jefflib.h\" \n#include <boost/tokenizer.hpp>\n#include <thread>\n#include <chrono>\n#include <ncurses.h>\n\nusing namespace std;\nusing namespace boost;\n\nstruct star{\n    int x, y, dx, dy;\n};\n\nvoid PrintStars(vector<star>& stars, int rows, int cols, int maxX, int maxY, int minX, int minY, int time){\n   \n    // -----> Status <----- //\n    mvprintw(0,0,\"Screen Columns: %d\",cols);\n    mvprintw(1,0,\"Screen Rows: %d\",rows);\n    mvprintw(2,0,\"Nunber of Stars: %d\",stars.size());\n    mvprintw(4,0,\"Time: %d\",time);\n\n    int miX = INT_MAX;\n    int miY = INT_MAX;\n    int maX = 0;\n    int maY = 0;\n    for(auto star : stars){\n        int y = (rows*star.y)/maxY;\n        int x = (cols*star.x)/maxX;\n        mvaddch(y,x,'*');\n\n        if(x<miX)miX=x;\n        if(x>maX)maX=x;\n        if(y>maY)maY=y;\n        if(y<miY)miY=y;\n    }\n    mvprintw(3,0,\"MinX %d, MinX %d, MaxX %d, MaxY %d\", miX, miY, maX, maY);\n    refresh();\n}\n\n\nvoid TranslateStars(int minX, int minY, vector<star>& stars, int& maxX, int& maxY){\n    maxX = 0;\n    maxY = 0;\n    for(auto& star : stars){\n        if(minX < 0){\n            star.x += abs(minX);\n        }\n        if(minX > 0){\n            star.x -= minX;\n        }\n\n        if(minY < 0){\n            star.y += abs(minY);\n        }\n        if(minY > 0){\n            star.y -= minY;\n        }\n        if(star.x>maxX) maxX = star.x;\n        if(star.y>maxY) maxY = star.y;\n    }\n}\n\nvoid UpdateStars(vector<star>& stars, int& maxX, int& maxY, int& minX, int& minY){\n    \n    // Update them\n    for(auto& star : stars){\n        star.x += star.dx;\n        star.y += star.dy;\n    }\n    minX = INT_MAX;\n    minY = INT_MAX;\n    maxX = 0;\n    maxY = 0;\n\n    for(auto star : stars){\n        if(star.x < minX) minX = star.x;\n        if(star.x > maxX) maxX = star.x;\n        if(star.y < minY) minY = star.y;\n        if(star.y > maxY) maxY = star.y;\n    }\n    \n    TranslateStars(minX, minY, stars, maxX, maxY);\n\n}\n\nint main()\n{\n    initscr();\n    cbreak();\n    noecho();\n    clear();\n    \n    int row, col;\n    getmaxyx(stdscr,row,col);\n\n    vector<string> vect;\n    GetStringInput(vect);\n   \n    // Example input line, nicely well-formed :)\n    //  ..........10.....17.................36.39..\n    //  position=<-31503, -52596> velocity=< 3,  5>\n    \n    vector<star> stars;\n    for(auto line : vect){\n        star tempStar;\n        tempStar.x  = stoi(line.substr(10,6));\n        tempStar.y  = stoi(line.substr(17, 7));\n        tempStar.dx = stoi(line.substr(36, 2));\n        tempStar.dy = stoi(line.substr(39, 3));\n        stars.push_back(tempStar);\n    }\n\n    int time = 0;\n    int maxX = 0;\n    int maxY = 0;\n    int minX = INT_MAX;\n    int minY = INT_MAX;\n    int delay = 0;\n    for(;;){\n        clear();\n        time++;\n        UpdateStars(stars, maxX, maxY, minX, minY);\n        PrintStars(stars, row, col, maxX, maxY, minX, minY, time);\n        this_thread::sleep_for(chrono::milliseconds(delay));\n        if(time > 10000) delay = 10; //100\n        if(time > 10500) delay = 100; //500\n        if(time > 10550) delay = 500; //1000\n        if(time == 10558) delay = 5000;\n        if(time > 10558) delay = 500; \n        /*\n        if(time == 10558){\n            ofstream myfile;\n            myfile.open (\"out-558.csv\");\n            for(auto star : stars){\n                myfile << star.x <<\",\"<<star.y<<endl;\n            }\n            myfile << \"Writing this to a file.\\n\";\n            myfile.close();\n            return 0;\n        }\n        */\n    }\n}\n\n\n", "meta": {"hexsha": "268824ca2d1ec78bb60de7bc27beb10f6db6dcb5", "size": 3541, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "jeff/day-10/part-1.cpp", "max_stars_repo_name": "jeffphi/advent-of-code-2018", "max_stars_repo_head_hexsha": "8e54bd23ebfe42fcbede315f0ab85db903551532", "max_stars_repo_licenses": ["MIT"], "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/day-10/part-1.cpp", "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/day-10/part-1.cpp", "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": 23.6066666667, "max_line_length": 107, "alphanum_fraction": 0.5032476701, "num_tokens": 1064, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851919, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4615929992736142}}
{"text": "//------------------------------------------------------------------------------\n/// \\file BinaryTrees_tests.cpp\n/// \\date 20201023 03:44\n//------------------------------------------------------------------------------\n#include \"DataStructures/BinaryTrees.h\"\n\n#include <boost/test/unit_test.hpp>\n#include <string>\n#include <vector>\n\nusing DataStructures::BinaryTrees::TreeNode;\nusing DataStructures::BinaryTrees::balance_max_height_recursive;\nusing DataStructures::BinaryTrees::inorder_traversal_iterative;\nusing DataStructures::BinaryTrees::inorder_traversal_recursive;\nusing DataStructures::BinaryTrees::is_same_recursive;\nusing DataStructures::BinaryTrees::level_order_traversal;\nusing DataStructures::BinaryTrees::max_depth;\nusing DataStructures::BinaryTrees::postorder_traversal_iterative_simple;\nusing DataStructures::BinaryTrees::postorder_traversal_recursive;\nusing DataStructures::BinaryTrees::preorder_traversal;\nusing DataStructures::BinaryTrees::preorder_traversal_recursive;\nusing DataStructures::BinaryTrees::serialize;\nusing std::string;\nusing std::vector;\n\nBOOST_AUTO_TEST_SUITE(DataStructures)\nBOOST_AUTO_TEST_SUITE(BinaryTrees_tests)\n\n// cf. https://leetcode.com/explore/learn/card/data-structure-tree/134/traverse-a-tree/992/\nTreeNode example_root {6};\nTreeNode d11 {2};\nTreeNode d12 {7};\nTreeNode d21 {1};\nTreeNode d22 {4};\nTreeNode d23 {9};\nTreeNode d31 {3};\nTreeNode d32 {5};\nTreeNode d33 {8};\n\nTreeNode example_root_A {1};\nTreeNode d11_A {2};\nTreeNode d12_A {3};\nTreeNode d21_A {4};\nTreeNode d22_A {5};\nTreeNode d23_A {6};\n\nTreeNode example_root_B {3};\nTreeNode d11_B {9};\nTreeNode d12_B {20};\nTreeNode d21_B {15};\nTreeNode d22_B {7};\n\nTreeNode leaf {42};\n\nTreeNode base_case_1_root {1};\nTreeNode base_case_1_d11 {2};\nTreeNode base_case_1_d12 {3};\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(PreorderTraversalTraversesFirstEncounters)\n{\n  example_root.left_ = &d11;\n  example_root.right_ = &d12;\n  d11.left_ = &d21;\n  d11.right_ = &d22;\n  d22.left_ = &d31;\n  d22.right_ = &d32;\n  d12.right_ = &d23;\n  d23.right_ = &d33;\n\n  TreeNode* example_root_ptr {&example_root};\n\n  vector<int> result {preorder_traversal(example_root_ptr)};\n\n  vector<int> expected {6, 2, 1, 4, 3, 5, 7, 9, 8};\n\n  BOOST_TEST(result == expected);\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(PreorderTraversalRecursiveTraversesFirstEncounters)\n{\n  example_root.left_ = &d11;\n  example_root.right_ = &d12;\n  d11.left_ = &d21;\n  d11.right_ = &d22;\n  d22.left_ = &d31;\n  d22.right_ = &d32;\n  d12.right_ = &d23;\n  d23.right_ = &d33;\n\n  TreeNode* example_root_ptr {&example_root};\n\n  vector<int> result {preorder_traversal_recursive(example_root_ptr)};\n\n  vector<int> expected {6, 2, 1, 4, 3, 5, 7, 9, 8};\n\n  BOOST_TEST(result == expected);\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(InorderTraversalIterativeTraversesAfterLeftSubtree)\n{\n  example_root_A.left_ = &d11_A;\n  example_root_A.right_ = &d12_A;\n  d11_A.left_ = &d21_A;\n  d11_A.right_ = &d22_A;\n  d12_A.left_ = &d23_A;\n\n  TreeNode* example_root_ptr {&example_root_A};\n\n  vector<int> result {inorder_traversal_iterative(example_root_ptr)};\n\n  vector<int> expected {4, 2, 5, 1, 6, 3};\n\n  BOOST_TEST(result == expected);\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(InorderTraversalRecursiveTraversesAfterLeftSubtree)\n{\n  example_root.left_ = &d11;\n  example_root.right_ = &d12;\n  d11.left_ = &d21;\n  d11.right_ = &d22;\n  d22.left_ = &d31;\n  d22.right_ = &d32;\n  d12.right_ = &d23;\n  d23.right_ = &d33;\n\n  TreeNode* example_root_ptr {&example_root};\n\n  vector<int> result {inorder_traversal_recursive(example_root_ptr)};\n\n  vector<int> expected {1, 2, 3, 4, 5, 6, 7, 9, 8};\n\n  BOOST_TEST(result == expected);\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(PostorderTraversalIterativeTraversesAfterRightSubtree)\n{\n  example_root_A.left_ = &d11_A;\n  example_root_A.right_ = &d12_A;\n  d11_A.left_ = &d21_A;\n  d11_A.right_ = &d22_A;\n  d12_A.left_ = &d23_A;\n\n  TreeNode* example_root_ptr {&example_root_A};\n\n  vector<int> result {postorder_traversal_iterative(example_root_ptr)};\n\n  vector<int> expected {4, 5, 2, 6, 3, 1};\n\n  BOOST_TEST(result == expected);\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(PostorderTraversalRecursiveTraversesAfterRightSubtree)\n{\n  example_root.left_ = &d11;\n  example_root.right_ = &d12;\n  d11.left_ = &d21;\n  d11.right_ = &d22;\n  d22.left_ = &d31;\n  d22.right_ = &d32;\n  d12.right_ = &d23;\n  d23.right_ = &d33;\n\n  TreeNode* example_root_ptr {&example_root};\n\n  vector<int> result {postorder_traversal_recursive(example_root_ptr)};\n\n  vector<int> expected {1, 3, 5, 4, 2, 8, 9, 7, 6};\n\n  BOOST_TEST(result == expected);\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(\n  PostorderTraversalIterativeSimpleTraversesAfterRightSubtree)\n{\n  example_root_A.left_ = &d11_A;\n  example_root_A.right_ = &d12_A;\n  d11_A.left_ = &d21_A;\n  d11_A.right_ = &d22_A;\n  d12_A.left_ = &d23_A;\n\n  TreeNode* example_root_ptr {&example_root_A};\n\n  vector<int> result {postorder_traversal_iterative_simple(example_root_ptr)};\n\n  vector<int> expected {4, 5, 2, 6, 3, 1};\n\n  BOOST_TEST(result == expected);\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(LevelOrderTraversalReturnsNodesInByLevels)\n{\n  example_root_B.left_ = &d11_B;\n  example_root_B.right_ = &d12_B;\n  d12_B.left_ = &d21_B;\n  d12_B.right_ = &d22_B;\n\n  TreeNode* example_root_ptr {&example_root_B};\n\n  vector<vector<int>> result {level_order_traversal(example_root_ptr)};\n\n  BOOST_TEST(result.at(0) == vector<int>{3});\n  BOOST_TEST(result.at(1) == vector<int>({9, 20}));\n  BOOST_TEST(result.at(2) == vector<int>({15, 7}));\n  BOOST_TEST(result.size() == 3);\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(MaxDepthFindsMaximumDepth)\n{\n  example_root_B.left_ = &d11_B;\n  example_root_B.right_ = &d12_B;\n  d12_B.left_ = &d21_B;\n  d12_B.right_ = &d22_B;\n\n  TreeNode* example_root_ptr {&example_root_B};\n\n  const int result {max_depth(example_root_ptr)};\n\n  BOOST_TEST(result == 3);\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(BalanceMaxHeightRecursiveWorksOnSimpleBaseCases)\n{\n  {\n    TreeNode* example_ptr {nullptr};\n\n    const auto result = balance_max_height_recursive(example_ptr);\n    BOOST_TEST(result.first == true);\n    BOOST_TEST(result.second == -1);\n  }\n  {\n    // Check if we have the test setup initial conditions we want.\n    TreeNode* example_root_ptr {&leaf};\n    BOOST_TEST(example_root_ptr->left_ == nullptr);\n    BOOST_TEST(example_root_ptr->right_ == nullptr);\n\n    const auto result = balance_max_height_recursive(example_root_ptr);\n    BOOST_TEST(result.first == true);\n    BOOST_TEST(result.second == 0);\n  }\n  {\n    base_case_1_root.left_ = &base_case_1_d11;\n    base_case_1_root.right_ = &base_case_1_d12;\n    TreeNode* example_root_ptr {&base_case_1_root};\n\n    const auto result = balance_max_height_recursive(example_root_ptr);\n    BOOST_TEST(result.first == true);\n    BOOST_TEST(result.second == 1);\n  }\n  {\n    TreeNode* example_root_ptr {&example_root_B};\n    BOOST_TEST(example_root_ptr->left_ != nullptr);\n    BOOST_TEST(example_root_ptr->right_ != nullptr);\n\n    const auto result = balance_max_height_recursive(example_root_ptr);\n    BOOST_TEST(result.first == true);\n    BOOST_TEST(result.second == 2);\n  }\n}\n\nTreeNode height_example_1_root {3};\nTreeNode height_example_1_d11 {9};\nTreeNode height_example_1_d12 {20};\nTreeNode height_example_1_d21 {15};\nTreeNode height_example_1_d22 {7};\n\nTreeNode height_example_2_root {1};\nTreeNode height_example_2_d11 {2};\nTreeNode height_example_2_d12 {2};\nTreeNode height_example_2_d21 {3};\nTreeNode height_example_2_d22 {3};\nTreeNode height_example_2_d31 {4};\nTreeNode height_example_2_d32 {4};\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(BalanceMaxHeightRecursiveDeterminesBalanceProperty)\n{\n  {\n    TreeNode* example_root_ptr {&example_root_B};\n    BOOST_TEST(example_root_ptr->left_ != nullptr);\n    BOOST_TEST(example_root_ptr->right_ != nullptr);\n\n    const auto result = balance_max_height_recursive(example_root_ptr);\n    BOOST_TEST(result.first == true);\n    BOOST_TEST(result.second == 2);\n  }\n  {\n    TreeNode* example_root_ptr {&example_root_A};\n    BOOST_TEST(example_root_ptr->left_ != nullptr);\n    BOOST_TEST(example_root_ptr->right_ != nullptr);\n\n    const auto result = balance_max_height_recursive(example_root_ptr);\n    BOOST_TEST(result.first == true);\n    BOOST_TEST(result.second == 2);\n  }\n  {\n    TreeNode* example_root_ptr {&example_root};\n    BOOST_TEST(example_root_ptr->left_ != nullptr);\n    BOOST_TEST(example_root_ptr->right_ != nullptr);\n\n    const auto result = balance_max_height_recursive(example_root_ptr);\n    BOOST_TEST(result.first == false);\n    BOOST_TEST(result.second == 3);\n  }\n  {\n    height_example_1_root.left_ = &height_example_1_d11;\n    height_example_1_root.right_ = &height_example_1_d12;\n    height_example_1_d12.left_ = &height_example_1_d21;\n    height_example_1_d12.right_ = &height_example_1_d22;\n\n    TreeNode* example_root_ptr {&height_example_1_root};\n    BOOST_TEST(example_root_ptr->left_ != nullptr);\n    BOOST_TEST(example_root_ptr->right_ != nullptr);\n\n    const auto result = balance_max_height_recursive(example_root_ptr);\n    BOOST_TEST(result.first == true);\n    BOOST_TEST(result.second == 2);\n  }\n  {\n    height_example_2_root.left_ = &height_example_2_d11;\n    height_example_2_root.right_ = &height_example_2_d12;\n    height_example_2_d11.left_ = &height_example_2_d21;\n    height_example_2_d11.right_ = &height_example_2_d22;\n    height_example_2_d21.left_ = &height_example_2_d31;\n    height_example_2_d21.right_ = &height_example_2_d32;\n\n    TreeNode* example_root_ptr {&height_example_2_root};\n    BOOST_TEST(example_root_ptr->left_ != nullptr);\n    BOOST_TEST(example_root_ptr->right_ != nullptr);\n\n    const auto result = balance_max_height_recursive(example_root_ptr);\n    BOOST_TEST(result.first == false);\n    BOOST_TEST(result.second == 3);\n  }\n}\n\n/// cf. https://www.techiedelight.com/check-if-two-binary-trees-are-identical-not-iterative-recursive/\n/// cf. https://medium.com/techie-delight/binary-tree-interview-questions-and-practice-problems-439df7e5ea1f\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(IsSameRecursiveReturnsTrueForSameTrees)\n{\n  {\n    TreeNode x {15};\n    TreeNode x_d11 {10};\n    TreeNode x_d12 {20};\n    TreeNode x_d21 {8};\n    TreeNode x_d22 {12};\n    TreeNode x_d23 {16};\n    TreeNode x_d24 {25};\n\n    TreeNode* x_ptr {&x};\n    x_ptr->left_ = &x_d11;\n    x_ptr->right_ = &x_d12;\n    x_ptr->left_->left_ = &x_d21;\n    x_ptr->left_->right_ = &x_d22;\n    x_ptr->right_->left_ = &x_d23;\n    x_ptr->right_->left_ = &x_d24;\n\n    TreeNode y {15};\n    TreeNode y_d11 {10};\n    TreeNode y_d12 {20};\n    TreeNode y_d21 {8};\n    TreeNode y_d22 {12};\n    TreeNode y_d23 {16};\n    TreeNode y_d24 {25};\n\n    TreeNode* y_ptr {&y};\n    y_ptr->left_ = &y_d11;\n    y_ptr->right_ = &y_d12;\n    y_ptr->left_->left_ = &y_d21;\n    y_ptr->left_->right_ = &y_d22;\n    y_ptr->right_->left_ = &y_d23;\n    y_ptr->right_->left_ = &y_d24;\n\n    BOOST_TEST(is_same_recursive(x_ptr, y_ptr));\n  }\n  {\n    TreeNode* example_root_ptr {&example_root};\n    TreeNode* example_root_A_ptr {&example_root_A};\n    BOOST_TEST(!is_same_recursive(example_root_ptr, example_root_A_ptr));\n  }\n}\n\n//------------------------------------------------------------------------------\n/// cf. https://leetcode.com/problems/serialize-and-deserialize-binary-tree/\n//------------------------------------------------------------------------------\n\nTreeNode serialize_example_1_root {1};\nTreeNode serialize_example_1_d11 {2};\nTreeNode serialize_example_1_d12 {3};\nTreeNode serialize_example_1_d21 {4};\nTreeNode serialize_example_1_d22 {5};\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(SerializeSerializesBinaryTree)\n{\n  serialize_example_1_root.left_ = &serialize_example_1_d11;\n  serialize_example_1_root.right_ = &serialize_example_1_d12;\n  serialize_example_1_d12.left_ = &serialize_example_1_d21;\n  serialize_example_1_d12.right_ = &serialize_example_1_d22;\n\n  TreeNode* example_root_ptr {&serialize_example_1_root};\n\n  const string result {serialize(example_root_ptr)};\n\n  BOOST_TEST(result == \"1,2,null,null,3,4,null,null,5,null,null\");\n}\n\nBOOST_AUTO_TEST_SUITE_END() // BinaryTrees_tests\nBOOST_AUTO_TEST_SUITE_END() // DataStructures", "meta": {"hexsha": "fdef3fd2d83d39ae79ff4f1f73d122e21275c9c9", "size": 13990, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Voltron/Source/UnitTests/DataStructures/BinaryTrees_tests.cpp", "max_stars_repo_name": "ernestyalumni/HrdwCCppCUDA", "max_stars_repo_head_hexsha": "17ed937dea06431a4d5ca103f993ea69a6918734", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-02-09T19:44:51.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-09T19:44:51.000Z", "max_issues_repo_path": "Voltron/Source/UnitTests/DataStructures/BinaryTrees_tests.cpp", "max_issues_repo_name": "ernestyalumni/HrdwCCppCUDA", "max_issues_repo_head_hexsha": "17ed937dea06431a4d5ca103f993ea69a6918734", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Voltron/Source/UnitTests/DataStructures/BinaryTrees_tests.cpp", "max_forks_repo_name": "ernestyalumni/HrdwCCppCUDA", "max_forks_repo_head_hexsha": "17ed937dea06431a4d5ca103f993ea69a6918734", "max_forks_repo_licenses": ["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.3094688222, "max_line_length": 108, "alphanum_fraction": 0.6109363831, "num_tokens": 3355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.7690802264851919, "lm_q1q2_score": 0.4615929992736142}}
{"text": "#include <am_gazebo_wheelencoder/am_gazebo_wheelencoder.h>\n#include <ros/ros.h>\n\n#include <boost/lexical_cast.hpp>\n\n#include <am_driver/WheelEncoder.h>\n\nnamespace gazebo\n{\n// Register this plugin with the simulator\nGZ_REGISTER_MODEL_PLUGIN(GazeboRosWheelEncoder);\n\n\n#define RADIANS_PER_TICK\t\t(M_PI*2.0/1093.0)\n#define WHEEL_METER_PER_TICK\t(0.000704)\n\n////////////////////////////////////////////////////////////////////////////////\n// Constructor\nGazeboRosWheelEncoder::GazeboRosWheelEncoder()\n{\n}\n\n////////////////////////////////////////////////////////////////////////////////\n// Destructor\nGazeboRosWheelEncoder::~GazeboRosWheelEncoder()\n{\n}\n\n////////////////////////////////////////////////////////////////////////////////\n// Load the controller\nvoid GazeboRosWheelEncoder::Load( physics::ModelPtr _parent, sdf::ElementPtr _sdf )\n{\n\t// Make sure the ROS node for Gazebo has already been initalized\n\tif (!ros::isInitialized())\n\t{\n\t\tROS_FATAL_STREAM(\"A ROS node for Gazebo has not been initialized, unable to load plugin. Load the Gazebo system plugin 'libam_gazebo_wheelencoder.so' in the gazebo_ros package)\");\n\t\treturn;\n\t}\n\n\tROS_INFO(\"WheelEncoder: am_gazebo_wheelencoder loaded...\");\n  \n\tparent = _parent;\n\tworld = _parent->GetWorld();\n\t\n\t\n\tgazebo_ros_ = GazeboRosPtr ( new GazeboRos ( _parent, _sdf, \"WheelEncoder\" ) );\n\t// Make sure the ROS node for Gazebo has already been initialized\n\tgazebo_ros_->isInitialized();\n\n\t// Publisher\n\tencoderPub = gazebo_ros_->node()->advertise<am_driver::WheelEncoder>(\"wheel_encoder\", 100);\n\n\t// Get the links/joints required...\n\t\n\tstd::string name = \"back_left_wheel\";\n\tleftWheelLink = _parent->GetLink(name);\n\t\n\tif (!leftWheelLink)\n\t{\n\t\tROS_FATAL(\"WheelEncoder plugin error: link %s does not exist\\n\", name.c_str());\n\t\treturn;\n\t}\n\tname = \"back_left_wheel_joint\";\n\tleftWheelJoint = _parent->GetJoint(name);\n\t\n\tif (!leftWheelJoint)\n\t{\n\t\tROS_FATAL(\"WheelEncoder plugin error: joint %s does not exist\\n\", name.c_str());\n\t\treturn;\n\t}\n\n\n\tname = \"back_right_wheel\";\n\trightWheelLink = _parent->GetLink(name);\n\t\n\tif (!rightWheelLink)\n\t{\n\t\tROS_FATAL(\"WheelEncoder plugin error: link %s does not exist\\n\", name.c_str());\n\t\treturn;\n\t}\n\tname = \"back_right_wheel_joint\";\n\trightWheelJoint = _parent->GetJoint(name);\n\t\n\tif (!rightWheelJoint)\n\t{\n\t\tROS_FATAL(\"WheelEncoder plugin error: joint %s does not exist\\n\", name.c_str());\n\t\treturn;\n\t}\n\n\tlastLeftAngle = leftWheelJoint->GetAngle(0).Radian();\n\tlastRightAngle = rightWheelJoint->GetAngle(0).Radian();\n\n \t// listen to the update event (broadcast every simulation iteration)\n\t//updateConnection = event::Events::ConnectWorldUpdateBegin ( boost::bind ( &GazeboRosWheelEncoder::Update, this ) );\n\n\t// connect Update function\n\tupdateTimer.setUpdateRate(50.0);\n\tupdateTimer.Load(world, _sdf);\n\tupdateConnection = updateTimer.Connect(boost::bind(&GazeboRosWheelEncoder::Update, this));\t\n\n\n}\n\n////////////////////////////////////////////////////////////////////////////////\n// Update the controller\nvoid GazeboRosWheelEncoder::Update()\n{\n\n\t// Get the actual angle of the Joints\n\t\n\t// LEFT\n\tdouble leftAngle = leftWheelJoint->GetAngle(0).Radian();\n\tdouble dLeftAngle = leftAngle - lastLeftAngle;\n\tlastLeftAngle = leftAngle;\n\t//std::cout << \"LeftAngle: \" <<  leftAngle*180/M_PI << std::endl;\n\t\n\tdouble leftPulses = dLeftAngle / RADIANS_PER_TICK;\n\tdouble leftDist = leftPulses * WHEEL_METER_PER_TICK;\n\n\t// RIGHT\n\tdouble rightAngle = rightWheelJoint->GetAngle(0).Radian();\n\tdouble dRightAngle = rightAngle - lastRightAngle;\n\tlastRightAngle = rightAngle;\n\t//std::cout << \"RightAngle: \" <<  rightAngle*180/M_PI << std::endl;\n\t\n\tdouble rightPulses = dRightAngle / RADIANS_PER_TICK;\n\tdouble rightDist = rightPulses * WHEEL_METER_PER_TICK;\n\n\t// ACCUM \n\tdouble leftAccum = -leftAngle/RADIANS_PER_TICK;\n\tdouble rightAccum = rightAngle/RADIANS_PER_TICK;\n\n\t// PUBLISH\n\t//std::cout << \"LeftDist: \" << leftDist << \" RightDist: \" << rightDist;\n\t//std::cout << \" LeftAccum: \" << leftAccum << \" RightAccum: \" << rightAccum << std::endl;\n\n\t// Limit if small values...\n\tif (fabs(leftDist) < 0.0001)\n\t{\n\t\tleftDist = 0.0;\n\t}\n\tif (fabs(rightDist) < 0.0001)\n\t{\n\t\trightDist = 0.0;\n\t}\n\n\n\tam_driver::WheelEncoder encoder;\n\t\t\n\tencoder.header.frame_id = \"wheel_encoder\";\n\tencoder.header.stamp = ros::Time::now();\n\tencoder.lwheel = leftDist;\n\tencoder.rwheel = rightDist;\n\tencoder.lwheelAccum = leftAccum;\n\tencoder.rwheelAccum = rightAccum;\n\t\n\tencoderPub.publish(encoder);\n}\n\n}\n", "meta": {"hexsha": "ed0da1d8738c47267088614333493776ef5d0fd6", "size": 4421, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "am_gazebo_wheelencoder/src/am_gazebo_wheelencoder.cpp", "max_stars_repo_name": "johwenns/hrp-pi3", "max_stars_repo_head_hexsha": "6425fd61785b44185738228fde70b3c9088efa92", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "am_gazebo_wheelencoder/src/am_gazebo_wheelencoder.cpp", "max_issues_repo_name": "johwenns/hrp-pi3", "max_issues_repo_head_hexsha": "6425fd61785b44185738228fde70b3c9088efa92", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "am_gazebo_wheelencoder/src/am_gazebo_wheelencoder.cpp", "max_forks_repo_name": "johwenns/hrp-pi3", "max_forks_repo_head_hexsha": "6425fd61785b44185738228fde70b3c9088efa92", "max_forks_repo_licenses": ["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.4596273292, "max_line_length": 181, "alphanum_fraction": 0.6740556435, "num_tokens": 1164, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851918, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.46159299927361414}}
{"text": "\n//          Copyright Gavin Band 2008 - 2012.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef SNPTEST_CASE_CONTROL_MULTINOMIAL_LOG_LIKELIHOOD_HPP\n#define SNPTEST_CASE_CONTROL_MULTINOMIAL_LOG_LIKELIHOOD_HPP\n\n#include <vector>\n#include <memory>\n#include <boost/noncopyable.hpp>\n#include \"Eigen/Core\"\n#include \"metro/regression/Design.hpp\"\n#include \"metro/regression/LogLikelihood.hpp\"\n\nnamespace metro {\n\tnamespace regression {\n\t\t/*\n\t\t* This class implements a log-likelihood for multinomial logistic regression, allowing predictors\n\t\t* to take one of a finite set of values with associated probabilities. (A \"missing data log-likelihood\" ).\n\t\t* The outcome variables must form a contiguous set of numbers in the range 0,1,...,M\n\t\t* for some positive integer M > 0.\n\t\t*\n\t\t* Notation:\n\t\t* N - number of samples\n\t\t* L - number of predictor levels\n\t\t* M - number of outcome levels not counting the baseline.\n\t\t* \n\t\t*/\n\t\tstruct MultinomialRegressionLogLikelihood: public LogLikelihood\n\t\t{\n\t\tpublic:\n\t\t\ttypedef regression::Design::Vector Vector ;\n\t\t\ttypedef regression::Design::RowVector RowVector ;\n\t\t\ttypedef regression::Design::Matrix Matrix ;\n\t\t\ttypedef Eigen::Block< Matrix > MatrixBlock ;\n\t\t\ttypedef Eigen::Block< Matrix const > ConstMatrixBlock ;\n\t\t\ttypedef Eigen::PermutationMatrix< Eigen::Dynamic, Eigen::Dynamic > PermutationMatrix ;\n\t\t\ttypedef boost::function< std::string( std::string const& predictor_name, int outcome_level ) > GetParameterName ;\n\t\tpublic:\n\t\t\ttypedef std::auto_ptr< MultinomialRegressionLogLikelihood > UniquePtr ;\n\t\t\tstatic UniquePtr create( regression::Design::UniquePtr ) ;\n\t\t\t\n\t\tpublic:\n\t\t\tMultinomialRegressionLogLikelihood( regression::Design::UniquePtr ) ;\n\n\t\t\tregression::Design& design() const { return *m_design ; }\n\t\t\tvoid set_predictor_levels( Matrix const& levels, Matrix const& probabilities, std::vector< metro::SampleRange > const& included_samples ) ;\n\t\t\n\t\t\tvoid set_parameter_naming_scheme( GetParameterName ) ;\n\t\t\tint number_of_parameters() const ;\n\t\t\tint number_of_outcomes() const ;\n\t\t\tstd::string get_parameter_name( std::size_t i ) const ;\t\t\n\t\t\tIntegerMatrix identify_parameters() const ;\n\t\t\t\n\t\t\tvoid evaluate_at( Vector const& parameters, int const numberOfDerivatives = 2 ) ;\n\t\t\tvoid evaluate( int const numberOfDerivatives = 2 ) ;\n\n\t\t\tVector const& parameters() const ;\n\t\t\tdouble get_value_of_function() const ;\n\t\t\tVector get_value_of_first_derivative() const ;\n\t\t\tMatrix get_value_of_second_derivative() const ;\n\n\t\t\tstd::string get_summary() const ;\n\n\t\tprivate:\n\t\t\tregression::Design::UniquePtr m_design ;\n\t\t\tint const m_number_of_samples ;\n\t\t\tGetParameterName m_get_parameter_name ;\n\t\t\tVector m_parameter_vector ;\n\t\t\tMatrix m_parameter_matrix ;\n\t\t\tIntegerMatrix m_parameter_identity ;\n\t\t\tstd::size_t m_numberOfDerivativesComputed ;\n\n\t\t\t// rearranger.  This matrix rearranges columns of an NxLM matrix from L blocks of NxM to M blocks of NxL.\n\t\t\tPermutationMatrix m_outcome_wise_to_predictor_wise_rearranger ;\n\t\t\t// Psi matrix, (NxLM).  This represents phenotype data as indicator 1's in each row.\n\t\t\tMatrix m_psi ;\n\t\t\t// F matrix (Nx(L(M+1))).  Stores outcome probabilities.\n\t\t\tMatrix m_F ;\n\t\t\t// A matrix (NxL).  Stores outcome probabilities times predictor probability, renormalised.\n\t\t\tMatrix m_A ;\n\t\t\t// B matrix (Nx(LM)).  Used in the computation of 1st and 2nd derivatives.\n\t\t\tMatrix m_B ;\n\t\t\t// C matrix (Nx(LM^2)).  Used in the computation of 2nd derivative.\n\t\t\tMatrix m_C ;\n\t\t\t// temp matrix.  Stores the terms that are summed to make the 1st derivative\n\t\t\tMatrix m_first_derivative_terms ;\n\t\t\t// temp matrix.  Stores rows of the design matrix tensor squares.\n\t\t\tmutable Matrix m_design_matrix_tensor_square_rows ;\n\n\t\t\tdouble m_value_of_function ;\n\t\t\tVector m_value_of_first_derivative ;\n\t\t\tMatrix m_value_of_second_derivative ;\n\n\t\tprivate:\n\t\t\t\n\t\t\tvoid compute_psi(\n\t\t\t\tMatrix const& outcome,\n\t\t\t\tint const number_of_levels,\n\t\t\t\tstd::vector< metro::SampleRange > const& included_samples,\n\t\t\t\tMatrix* result\n\t\t\t) const ;\n\t\t\tvoid compute_rearranger( int const number_of_predictor_levels, PermutationMatrix* result ) const ;\n\t\t\tIntegerMatrix compute_parameter_identity() const ;\n\n\t\t\tvoid evaluate_impl( int const numberOfDerivatives ) ;\n\t\t\tvoid compute_F( Matrix const& parameters, Matrix* result ) const ;\n\t\t\tvoid rearrange_F( Matrix* result ) const ;\n\t\t\tvoid compute_A_and_function_value(\n\t\t\t\tMatrix const& F,\n\t\t\t\tMatrix const& predictor_probabilities,\n\t\t\t\tstd::vector< metro::SampleRange > const& included_samples,\n\t\t\t\tMatrix* result,\n\t\t\t\tdouble* value_of_function\n\t\t\t) const ;\n\t\t\tvoid compute_B(\n\t\t\t\tMatrix const& A,\n\t\t\t\tMatrix const& F,\n\t\t\t\tMatrix const& psi,\n\t\t\t\tMatrix* result\n\t\t\t) const ;\n\t\t\tvoid compute_value_of_first_derivative(\n\t\t\t\tMatrix const& B,\n\t\t\t\tstd::vector< metro::SampleRange > const& included_samples,\n\t\t\t\tVector* result,\n\t\t\t\tMatrix* terms\n\t\t\t) const ;\n\t\t\t// void compute_C( Matrix const& B, Matrix const& F, Matrix const& Gamma, Matrix* result ) const ;\n\t\t\tvoid compute_C(\n\t\t\t\tMatrix const& B,\n\t\t\t\tMatrix const& F,\n\t\t\t\tMatrix const& Gamma,\n\t\t\t\tstd::vector< metro::SampleRange > const& included_samples,\n\t\t\t\tMatrix* result\n\t\t\t) const ;\n\t\t\tvoid compute_value_of_second_derivative(\n\t\t\t\tMatrix const& B,\n\t\t\t\tMatrix const& C,\n\t\t\t\tstd::vector< metro::SampleRange > const& included_samples,\n\t\t\t\tMatrix* result\n\t\t\t) const ;\n\t\t} ;\n\t}\n}\n\n#endif\n", "meta": {"hexsha": "336c35a91c8e0a2ede88663d5d8440549aababee", "size": 5446, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "metro/include/metro/regression/MultinomialRegressionLogLikelihood.hpp", "max_stars_repo_name": "gavinband/qctool", "max_stars_repo_head_hexsha": "8d8adb45151c91f953fe4a9af00498073b1132ba", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-04-21T05:42:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T14:59:43.000Z", "max_issues_repo_path": "metro/include/metro/regression/MultinomialRegressionLogLikelihood.hpp", "max_issues_repo_name": "gavinband/qctool", "max_issues_repo_head_hexsha": "8d8adb45151c91f953fe4a9af00498073b1132ba", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-09T16:11:04.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-10T11:18:56.000Z", "max_forks_repo_path": "metro/include/metro/regression/MultinomialRegressionLogLikelihood.hpp", "max_forks_repo_name": "gavinband/qctool", "max_forks_repo_head_hexsha": "8d8adb45151c91f953fe4a9af00498073b1132ba", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.5503355705, "max_line_length": 142, "alphanum_fraction": 0.7300771208, "num_tokens": 1347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117983401363, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.4615755135488404}}
{"text": "#include <vector>\n\n#include <glm/glm.hpp>\n\n#include <Eigen/Sparse>\n\n#include \"Types.h\"\n#include \"Viewer.h\"\n#include \"controls.h\"\n#include \"Dynamic.h\"\n\nextern int shadFlag;\nextern View::Viewer *p_viewer;\n\nnamespace BalloonFEM\n{\n    Engine::Engine(TetraMesh* tetra, \n            ElasticModel*   volume_model, \n            AirModel*       air_model, \n            FilmModel*      film_model,\n            BendingModel*   bend_model)\n    {\n        m_tetra = tetra;\n        m_size = tetra->vertices.size();\n        m_volume_model = volume_model;\n        m_air_model = air_model;\n\t\tm_film_model = film_model;\n        m_bend_model = bend_model;\n\n\t\tf_ext.assign(m_size, Vec3(0));\n\n\t\tthis->inputData();\n    }\n\n\tvoid Engine::inputData()\n\t{\n        cur_state.input(m_tetra);\n\n\t\t/* load data */\n\t\tfor (size_t i = 0; i < m_size; i++)\n\t\t{\n\t\t\tVertex &v = m_tetra->vertices[i];\n\t\t\tf_ext[i] = v.m_f_ext;\n\t\t}\n\t}\n\n    void Engine::outputData()\n    {\n        cur_state.project();\n        cur_state.output();\n    }\n\n    void Engine::stepToNext()\n    {\n        std::swap(cur_state, next_state);\n    }\n    \n    void Engine::computeForceAndGradient(ObjState &state, SpVec &f, SpMat &A)\n    {\n        Vvec3 f_sum;\n        f_sum.assign( m_size, Vec3(0.0));\n\n        /* compute elastic forces by tetrahedrons */\n        computeElasticForces(state, f_sum); \n\n\t\t/* compute film forces by pieces */\n\t\tcomputeFilmForces(state, f_sum);\n        \n        /* compute forces by air pressure */\n\t\tcomputeAirForces(state, f_sum);\n\n        for(size_t i = 0; i < m_size; i++)\n            f_sum[i] += f_ext[i];\n\n\t\t/* compute forces diff by air pressure */\n        SpMat K = computeAirDiffMat(state);\n\n\t\t/* compute film forces by pieces */\n\t\tK += computeFilmDiffMat(state);\n\n\t\t/* compute elastic forces diff by tetrahedrons */\n\t\tK += computeElasticDiffMat(state);\n\n        /* compute bending force and gradient */\n        K -= bendingForceAndGradient(state, f_sum);\n        \n        /* convert force to SpVec */\n        SpVec f_real = SpVec::Zero(3 * m_size);\n        for (size_t i = 0; i < f_sum.size(); i++)\n        {\n            f_real( 3 * i ) = f_sum[i].x;\n            f_real( 3 * i + 1) = f_sum[i].y;\n            f_real( 3 * i + 2) = f_sum[i].z;\n        }\n\n        /* convert K to \\tilde K with W transfer. The restricted vertices\n         * has all 0 colume and raw so we add 1 to its diagnal */\n        A = - state.projectMat().transpose() * K * state.projectMat() + state.restrictedMat();\n\n        f = state.projectMat().transpose() * f_real;\n\n    }\n\n    #define CONVERGE_ERROR_RATE 1e-4\n    void Engine::solveStaticPos()\n    {\n      /* initialize next_state */\n        next_state = cur_state;\n\t\tnext_state.project();\n        SpVec f_sum = SpVec::Zero(next_state.freedomDegree());\n\n        /* initialize temp variable for iterative implicit solving */\n        /* f is total force on each vertex */\n        /* K = - df/dr, here Force Diff Mat compute df/dr */\n        SpMat K;\n        computeForceAndGradient(next_state, f_sum, K);\n\n        SpVec dstate = SpVec::Zero(next_state.freedomDegree());\n        \n        /* solver */\n        Eigen::SimplicialLDLT<SpMat> solver;\n        SpVec &b = f_sum;\n\t\t\n\t\tdouble err_f = f_sum.dot(f_sum);\n\t\tdouble err_begin = err_f;\n\t\tint count_iter = 0;\t\t/* K dx = f iter count */\n        /* while not converge f == 0, iterate */\n\t\twhile ((err_f > CONVERGE_ERROR_RATE * err_begin) && (err_f > 1e-10))\n        {\n            /* debug use */\n\t\t\tcount_iter++;\n            printf(\"%d iter of K dv = f , err_felas = %.4e \\n\", count_iter, err_f);\n\n            /* r0 = b - Ax0 */\n            SpVec r = b - K * dstate;\n\n            printf(\"building solver\\n\");\n            solver.compute(K);\n            if (solver.info() != Eigen::Success)\n            {\n                printf(\"decomposition failed!\\n\");\n\t\t\t\tprintf(\"Number of non zeros: %d \\n\", K.nonZeros());\n                return;\n            }\n\t\t\tprintf(\"solve delta_x \\n\");\n            SpVec dstate = solver.solve(r);\n\n            /* update v_pos_next and f_sum */\n            next_state.update(dstate);\n            dstate.setZero();\n\n\t\t\t/* debug watch use*/\n\t\t\tnext_state.output();\n\t\t\tshadFlag = 1;\n\t\t\tp_viewer->refresh();\n\t\t\t//Control::mOutput();\n\t\t\t\n            /* update K and f*/\n            computeForceAndGradient(next_state, f_sum, K);\n\n\t\t\terr_f = f_sum.dot(f_sum);\n        }\n\n\t\tprintf(\"f_sum error %f \\n\", err_f);\n\t\tprintf(\"finish solving \\n\");\n    }\n\n\n  //  void Engine::forceTest(Vvec3 &f_sum, Vvec3 &f_loc)\n  //  {\n  //      f_sum.assign( m_size, Vec3(0) );\n\t\t//f_loc = cur_state.world_space_pos;\n\n\t\t//SpVec f = SpVec::Zero(cur_state.freedomDegree());\n  //      /* compute nodal force for each vertex */\n  //      return computeForceAndGradient(cur_state, f_sum);\n  //  }\n\n}\n", "meta": {"hexsha": "ea1758a627d62d617f0c3e73b2d933e8c1a76b8b", "size": 4731, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Dynamic.cpp", "max_stars_repo_name": "milkpku/FEM_practice", "max_stars_repo_head_hexsha": "5498de6c8d99c5336f7aaf0044335d61ffc0a02c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Dynamic.cpp", "max_issues_repo_name": "milkpku/FEM_practice", "max_issues_repo_head_hexsha": "5498de6c8d99c5336f7aaf0044335d61ffc0a02c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Dynamic.cpp", "max_forks_repo_name": "milkpku/FEM_practice", "max_forks_repo_head_hexsha": "5498de6c8d99c5336f7aaf0044335d61ffc0a02c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-08-10T08:20:06.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-10T08:20:06.000Z", "avg_line_length": 26.2833333333, "max_line_length": 94, "alphanum_fraction": 0.5649968294, "num_tokens": 1278, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.46157551116508416}}
{"text": "#include <gtest/gtest.h>\n#include <boost/optional.hpp>\n#include <snark/actuators/wheels/wheel_command.h>\n\nusing namespace snark::wheels;\n\nclass wheels_test : public ::testing::Test\n{\n    protected:\n        virtual void SetUp()\n        {\n            rear_left_pose\n                << -1,  0,  0, -1,\n                    0,  0, -1,  1,\n                    0, -1,  0,  0,\n                    0,  0,  0,  1;\n            front_left_pose\n                << -1,  0,  0,  1,\n                    0,  0, -1,  1,\n                    0, -1,  0,  0,\n                    0,  0,  0,  1;\n            front_right_pose\n                <<  1,  0,  0,  1,\n                    0,  0,  1, -1,\n                    0, -1,  0,  0,\n                    0,  0,  0,  1;\n            rear_right_pose\n                <<  1,  0,  0, -1,\n                    0,  0,  1, -1,\n                    0, -1,  0,  0,\n                    0,  0,  0,  1;\n            wheel_offset = 0;\n            angle_limit = limit( M_PI*0.5 );\n        }\n\n        virtual void TearDown()\n        {\n        }\n\n    public:\n        Eigen::Matrix4d rear_left_pose;\n        Eigen::Matrix4d front_left_pose;\n        Eigen::Matrix4d rear_right_pose;\n        Eigen::Matrix4d front_right_pose;\n        double wheel_offset;\n        boost::optional< limit > angle_limit;\n};\n\nclass wheels_test_180 : public wheels_test\n{\n    protected:\n        virtual void SetUp()\n        {\n            wheels_test::SetUp();\n            angle_limit = limit( M_PI );\n        }\n};\n\nclass wheels_test_540 : public wheels_test\n{\n    protected:\n        virtual void SetUp()\n        {\n            wheels_test::SetUp();\n            angle_limit = limit( M_PI*3 );\n        }\n};\n\nclass wheels_test_720 : public wheels_test\n{\n    protected:\n        virtual void SetUp()\n        {\n            wheels_test::SetUp();\n            angle_limit = limit( M_PI*4 );\n        }\n};\n\nclass wheels_test_no_limit : public wheels_test\n{\n    protected:\n        virtual void SetUp()\n        {\n            wheels_test::SetUp();\n            angle_limit = boost::optional< limit >();\n        }\n};\n\nTEST_F( wheels_test, crab_north_west )\n{\n    steer_command steer( 1, 1, 0 );\n    wheel_command rear_left = compute_wheel_command( steer, rear_left_pose, wheel_offset, angle_limit );\n    wheel_command front_left = compute_wheel_command( steer, front_left_pose, wheel_offset, angle_limit );\n    wheel_command front_right = compute_wheel_command( steer, front_right_pose, wheel_offset, angle_limit );\n    wheel_command rear_right = compute_wheel_command( steer, rear_right_pose, wheel_offset, angle_limit );\n    EXPECT_NEAR(  M_PI*0.25, rear_left.turnrate, 1e-9 );\n    EXPECT_NEAR( -std::sqrt(2), rear_left.velocity, 1e-9 );\n    EXPECT_NEAR(  M_PI*0.25, front_left.turnrate, 1e-9 );\n    EXPECT_NEAR( -std::sqrt(2), front_left.velocity, 1e-9 );\n    EXPECT_NEAR(  M_PI*0.25, front_right.turnrate, 1e-9 );\n    EXPECT_NEAR(  std::sqrt(2), front_right.velocity, 1e-9 );\n    EXPECT_NEAR(  M_PI*0.25, rear_right.turnrate, 1e-9 );\n    EXPECT_NEAR(  std::sqrt(2), rear_right.velocity, 1e-9 );\n}\n\nTEST_F( wheels_test, crab_north )\n{\n    steer_command steer( 1, 0, 0 );\n    wheel_command rear_left = compute_wheel_command( steer, rear_left_pose, wheel_offset, angle_limit );\n    wheel_command front_left = compute_wheel_command( steer, front_left_pose, wheel_offset, angle_limit );\n    wheel_command front_right = compute_wheel_command( steer, front_right_pose, wheel_offset, angle_limit );\n    wheel_command rear_right = compute_wheel_command( steer, rear_right_pose, wheel_offset, angle_limit );\n    EXPECT_EQ(  0, rear_left.turnrate );\n    EXPECT_EQ( -1, rear_left.velocity );\n    EXPECT_EQ(  0, front_left.turnrate );\n    EXPECT_EQ( -1, front_left.velocity );\n    EXPECT_EQ(  0, front_right.turnrate );\n    EXPECT_EQ(  1, front_right.velocity );\n    EXPECT_EQ(  0, rear_right.turnrate );\n    EXPECT_EQ(  1, rear_right.velocity );\n}\n\nTEST_F( wheels_test, crab_north_east )\n{\n    steer_command steer( 1, -1, 0 );\n    wheel_command rear_left = compute_wheel_command( steer, rear_left_pose, wheel_offset, angle_limit );\n    wheel_command front_left = compute_wheel_command( steer, front_left_pose, wheel_offset, angle_limit );\n    wheel_command front_right = compute_wheel_command( steer, front_right_pose, wheel_offset, angle_limit );\n    wheel_command rear_right = compute_wheel_command( steer, rear_right_pose, wheel_offset, angle_limit );\n    EXPECT_NEAR( -M_PI*0.25, rear_left.turnrate, 1e-9 );\n    EXPECT_NEAR( -std::sqrt(2), rear_left.velocity, 1e-9 );\n    EXPECT_NEAR( -M_PI*0.25, front_left.turnrate, 1e-9 );\n    EXPECT_NEAR( -std::sqrt(2), front_left.velocity, 1e-9 );\n    EXPECT_NEAR( -M_PI*0.25, front_right.turnrate, 1e-9 );\n    EXPECT_NEAR(  std::sqrt(2), front_right.velocity, 1e-9 );\n    EXPECT_NEAR( -M_PI*0.25, rear_right.turnrate, 1e-9 );\n    EXPECT_NEAR(  std::sqrt(2), rear_right.velocity, 1e-9 );\n}\n\nTEST_F( wheels_test, crab_east )\n{\n    steer_command steer( 0, -1, 0 );\n    wheel_command rear_left = compute_wheel_command( steer, rear_left_pose, wheel_offset, angle_limit );\n    wheel_command front_left = compute_wheel_command( steer, front_left_pose, wheel_offset, angle_limit );\n    wheel_command front_right = compute_wheel_command( steer, front_right_pose, wheel_offset, angle_limit );\n    wheel_command rear_right = compute_wheel_command( steer, rear_right_pose, wheel_offset, angle_limit );\n    EXPECT_NEAR(  M_PI*0.5, rear_left.turnrate, 1e-9 );\n    EXPECT_NEAR(  1, rear_left.velocity, 1e-9 );\n    EXPECT_NEAR(  M_PI*0.5, front_left.turnrate, 1e-9 );\n    EXPECT_NEAR(  1, front_left.velocity, 1e-9 );\n    EXPECT_NEAR( -M_PI*0.5, front_right.turnrate, 1e-9 );\n    EXPECT_NEAR(  1, front_right.velocity, 1e-9 );\n    EXPECT_NEAR( -M_PI*0.5, rear_right.turnrate, 1e-9 );\n    EXPECT_NEAR(  1, rear_right.velocity, 1e-9 );\n}\n\nTEST_F( wheels_test, crab_south_east )\n{\n    steer_command steer( -1, -1, 0 );\n    wheel_command rear_left = compute_wheel_command( steer, rear_left_pose, wheel_offset, angle_limit );\n    wheel_command front_left = compute_wheel_command( steer, front_left_pose, wheel_offset, angle_limit );\n    wheel_command front_right = compute_wheel_command( steer, front_right_pose, wheel_offset, angle_limit );\n    wheel_command rear_right = compute_wheel_command( steer, rear_right_pose, wheel_offset, angle_limit );\n    EXPECT_NEAR(  M_PI*0.25, rear_left.turnrate, 1e-9 );\n    EXPECT_NEAR(  std::sqrt(2), rear_left.velocity, 1e-9 );\n    EXPECT_NEAR(  M_PI*0.25, front_left.turnrate, 1e-9 );\n    EXPECT_NEAR(  std::sqrt(2), front_left.velocity, 1e-9 );\n    EXPECT_NEAR(  M_PI*0.25, front_right.turnrate, 1e-9 );\n    EXPECT_NEAR( -std::sqrt(2), front_right.velocity, 1e-9 );\n    EXPECT_NEAR(  M_PI*0.25, rear_right.turnrate, 1e-9 );\n    EXPECT_NEAR( -std::sqrt(2), rear_right.velocity, 1e-9 );\n}\n\nTEST_F( wheels_test, crab_south )\n{\n    steer_command steer( -1, 0, 0 );\n    wheel_command rear_left = compute_wheel_command( steer, rear_left_pose, wheel_offset, angle_limit );\n    wheel_command front_left = compute_wheel_command( steer, front_left_pose, wheel_offset, angle_limit );\n    wheel_command front_right = compute_wheel_command( steer, front_right_pose, wheel_offset, angle_limit );\n    wheel_command rear_right = compute_wheel_command( steer, rear_right_pose, wheel_offset, angle_limit );\n    EXPECT_EQ(  0, rear_left.turnrate );\n    EXPECT_EQ(  1, rear_left.velocity );\n    EXPECT_EQ(  0, front_left.turnrate );\n    EXPECT_EQ(  1, front_left.velocity );\n    EXPECT_EQ(  0, front_right.turnrate );\n    EXPECT_EQ( -1, front_right.velocity );\n    EXPECT_EQ(  0, rear_right.turnrate );\n    EXPECT_EQ( -1, rear_right.velocity );\n}\n\nTEST_F( wheels_test, crab_south_west )\n{\n    steer_command steer( -1,  1, 0 );\n    wheel_command rear_left = compute_wheel_command( steer, rear_left_pose, wheel_offset, angle_limit );\n    wheel_command front_left = compute_wheel_command( steer, front_left_pose, wheel_offset, angle_limit );\n    wheel_command front_right = compute_wheel_command( steer, front_right_pose, wheel_offset, angle_limit );\n    wheel_command rear_right = compute_wheel_command( steer, rear_right_pose, wheel_offset, angle_limit );\n    EXPECT_NEAR( -M_PI*0.25, rear_left.turnrate, 1e-9 );\n    EXPECT_NEAR(  std::sqrt(2), rear_left.velocity, 1e-9 );\n    EXPECT_NEAR( -M_PI*0.25, front_left.turnrate, 1e-9 );\n    EXPECT_NEAR(  std::sqrt(2), front_left.velocity, 1e-9 );\n    EXPECT_NEAR( -M_PI*0.25, front_right.turnrate, 1e-9 );\n    EXPECT_NEAR( -std::sqrt(2), front_right.velocity, 1e-9 );\n    EXPECT_NEAR( -M_PI*0.25, rear_right.turnrate, 1e-9 );\n    EXPECT_NEAR( -std::sqrt(2), rear_right.velocity, 1e-9 );\n}\n\nTEST_F( wheels_test, crab_west )\n{\n    steer_command steer( 0, 1, 0 );\n    wheel_command rear_left = compute_wheel_command( steer, rear_left_pose, wheel_offset, angle_limit );\n    wheel_command front_left = compute_wheel_command( steer, front_left_pose, wheel_offset, angle_limit );\n    wheel_command front_right = compute_wheel_command( steer, front_right_pose, wheel_offset, angle_limit );\n    wheel_command rear_right = compute_wheel_command( steer, rear_right_pose, wheel_offset, angle_limit );\n    EXPECT_NEAR( -M_PI*0.5, rear_left.turnrate, 1e-9 );\n    EXPECT_NEAR(  1, rear_left.velocity, 1e-9 );\n    EXPECT_NEAR( -M_PI*0.5, front_left.turnrate, 1e-9 );\n    EXPECT_NEAR(  1, front_left.velocity, 1e-9 );\n    EXPECT_NEAR(  M_PI*0.5, front_right.turnrate, 1e-9 );\n    EXPECT_NEAR(  1, front_right.velocity, 1e-9 );\n    EXPECT_NEAR(  M_PI*0.5, rear_right.turnrate, 1e-9 );\n    EXPECT_NEAR(  1, rear_right.velocity, 1e-9 );\n}\n\nTEST_F( wheels_test, spot_turn )\n{\n    steer_command steer( 0, 0, 1 );\n    wheel_command rear_left = compute_wheel_command( steer, rear_left_pose, wheel_offset, angle_limit );\n    wheel_command front_left = compute_wheel_command( steer, front_left_pose, wheel_offset, angle_limit );\n    wheel_command front_right = compute_wheel_command( steer, front_right_pose, wheel_offset, angle_limit );\n    wheel_command rear_right = compute_wheel_command( steer, rear_right_pose, wheel_offset, angle_limit );\n    EXPECT_NEAR(  M_PI*0.25, rear_left.turnrate, 1e-9 );\n    EXPECT_NEAR(  std::sqrt(2), rear_left.velocity, 1e-9 );\n    EXPECT_NEAR( -M_PI*0.25, front_left.turnrate, 1e-9 );\n    EXPECT_NEAR(  std::sqrt(2), front_left.velocity, 1e-9 );\n    EXPECT_NEAR(  M_PI*0.25, front_right.turnrate, 1e-9 );\n    EXPECT_NEAR(  std::sqrt(2), front_right.velocity, 1e-9 );\n    EXPECT_NEAR( -M_PI*0.25, rear_right.turnrate, 1e-9 );\n    EXPECT_NEAR(  std::sqrt(2), rear_right.velocity, 1e-9 );\n}\n\nTEST_F( wheels_test_180, crab_nearest_north )\n{\n    steer_command steer( 1, 0, 0 );\n    {\n        boost::optional< double > current_angle( 0 );\n        wheel_command rear_left = compute_wheel_command( steer, rear_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_left = compute_wheel_command( steer, front_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_right = compute_wheel_command( steer, front_right_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command rear_right = compute_wheel_command( steer, rear_right_pose, wheel_offset, angle_limit, current_angle );\n        EXPECT_NEAR(  0, rear_left.turnrate, 1e-9 );\n        EXPECT_NEAR( -1, rear_left.velocity, 1e-9 );\n        EXPECT_NEAR(  0, front_left.turnrate, 1e-9 );\n        EXPECT_NEAR( -1, front_left.velocity, 1e-9 );\n        EXPECT_NEAR(  0, front_right.turnrate, 1e-9 );\n        EXPECT_NEAR(  1, front_right.velocity, 1e-9 );\n        EXPECT_NEAR(  0, rear_right.turnrate, 1e-9 );\n        EXPECT_NEAR(  1, rear_right.velocity, 1e-9 );\n    }\n    {\n        boost::optional< double > current_angle( M_PI );\n        wheel_command rear_left = compute_wheel_command( steer, rear_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_left = compute_wheel_command( steer, front_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_right = compute_wheel_command( steer, front_right_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command rear_right = compute_wheel_command( steer, rear_right_pose, wheel_offset, angle_limit, current_angle );\n        EXPECT_NEAR(  M_PI, rear_left.turnrate, 1e-9 );\n        EXPECT_NEAR(  1, rear_left.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI, front_left.turnrate, 1e-9 );\n        EXPECT_NEAR(  1, front_left.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI, front_right.turnrate, 1e-9 );\n        EXPECT_NEAR( -1, front_right.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI, rear_right.turnrate, 1e-9 );\n        EXPECT_NEAR( -1, rear_right.velocity, 1e-9 );\n    }\n}\n\nTEST_F( wheels_test_180, crab_nearest_south )\n{\n    steer_command steer( -1, 0, 0 );\n    {\n        boost::optional< double > current_angle( 0 );\n        wheel_command rear_left = compute_wheel_command( steer, rear_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_left = compute_wheel_command( steer, front_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_right = compute_wheel_command( steer, front_right_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command rear_right = compute_wheel_command( steer, rear_right_pose, wheel_offset, angle_limit, current_angle );\n        EXPECT_NEAR(  0, rear_left.turnrate, 1e-9 );\n        EXPECT_NEAR(  1, rear_left.velocity, 1e-9 );\n        EXPECT_NEAR(  0, front_left.turnrate, 1e-9 );\n        EXPECT_NEAR(  1, front_left.velocity, 1e-9 );\n        EXPECT_NEAR(  0, front_right.turnrate, 1e-9 );\n        EXPECT_NEAR( -1, front_right.velocity, 1e-9 );\n        EXPECT_NEAR(  0, rear_right.turnrate, 1e-9 );\n        EXPECT_NEAR( -1, rear_right.velocity, 1e-9 );\n    }\n    {\n        boost::optional< double > current_angle( M_PI );\n        wheel_command rear_left = compute_wheel_command( steer, rear_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_left = compute_wheel_command( steer, front_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_right = compute_wheel_command( steer, front_right_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command rear_right = compute_wheel_command( steer, rear_right_pose, wheel_offset, angle_limit, current_angle );\n        EXPECT_NEAR(  M_PI, rear_left.turnrate, 1e-9 );\n        EXPECT_NEAR( -1, rear_left.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI, front_left.turnrate, 1e-9 );\n        EXPECT_NEAR( -1, front_left.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI, front_right.turnrate, 1e-9 );\n        EXPECT_NEAR(  1, front_right.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI, rear_right.turnrate, 1e-9 );\n        EXPECT_NEAR(  1, rear_right.velocity, 1e-9 );\n    }\n}\n\nTEST_F( wheels_test_180, crab_nearest_east )\n{\n    steer_command steer( 0, -1, 0 );\n    {\n        boost::optional< double > current_angle( 0 );\n        wheel_command rear_left = compute_wheel_command( steer, rear_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_left = compute_wheel_command( steer, front_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_right = compute_wheel_command( steer, front_right_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command rear_right = compute_wheel_command( steer, rear_right_pose, wheel_offset, angle_limit, current_angle );\n        EXPECT_NEAR(  M_PI*0.5, rear_left.turnrate, 1e-9 );\n        EXPECT_NEAR(  1, rear_left.velocity, 1e-9 );\n        EXPECT_NEAR( -M_PI*0.5, front_left.turnrate, 1e-9 );\n        EXPECT_NEAR( -1, front_left.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*0.5, front_right.turnrate, 1e-9 );\n        EXPECT_NEAR( -1, front_right.velocity, 1e-9 );\n        EXPECT_NEAR( -M_PI*0.5, rear_right.turnrate, 1e-9 );\n        EXPECT_NEAR(  1, rear_right.velocity, 1e-9 );\n    }\n    {\n        boost::optional< double > current_angle( M_PI*0.25 );\n        wheel_command rear_left = compute_wheel_command( steer, rear_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_left = compute_wheel_command( steer, front_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_right = compute_wheel_command( steer, front_right_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command rear_right = compute_wheel_command( steer, rear_right_pose, wheel_offset, angle_limit, current_angle );\n        EXPECT_NEAR(  M_PI*0.5, rear_left.turnrate, 1e-9 );\n        EXPECT_NEAR(  1, rear_left.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*0.5, front_left.turnrate, 1e-9 );\n        EXPECT_NEAR(  1, front_left.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*0.5, front_right.turnrate, 1e-9 );\n        EXPECT_NEAR( -1, front_right.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*0.5, rear_right.turnrate, 1e-9 );\n        EXPECT_NEAR( -1, rear_right.velocity, 1e-9 );\n    }\n}\n\nTEST_F( wheels_test_180, crab_nearest_west )\n{\n    steer_command steer( 0, 1, 0 );\n    {\n        boost::optional< double > current_angle( 0 );\n        wheel_command rear_left = compute_wheel_command( steer, rear_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_left = compute_wheel_command( steer, front_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_right = compute_wheel_command( steer, front_right_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command rear_right = compute_wheel_command( steer, rear_right_pose, wheel_offset, angle_limit, current_angle );\n        EXPECT_NEAR(  M_PI*0.5, rear_left.turnrate, 1e-9 );\n        EXPECT_NEAR( -1, rear_left.velocity, 1e-9 );\n        EXPECT_NEAR( -M_PI*0.5, front_left.turnrate, 1e-9 );\n        EXPECT_NEAR(  1, front_left.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*0.5, front_right.turnrate, 1e-9 );\n        EXPECT_NEAR(  1, front_right.velocity, 1e-9 );\n        EXPECT_NEAR( -M_PI*0.5, rear_right.turnrate, 1e-9 );\n        EXPECT_NEAR( -1, rear_right.velocity, 1e-9 );\n    }\n    {\n        boost::optional< double > current_angle( -M_PI*0.25 );\n        wheel_command rear_left = compute_wheel_command( steer, rear_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_left = compute_wheel_command( steer, front_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_right = compute_wheel_command( steer, front_right_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command rear_right = compute_wheel_command( steer, rear_right_pose, wheel_offset, angle_limit, current_angle );\n        EXPECT_NEAR( -M_PI*0.5, rear_left.turnrate, 1e-9 );\n        EXPECT_NEAR(  1, rear_left.velocity, 1e-9 );\n        EXPECT_NEAR( -M_PI*0.5, front_left.turnrate, 1e-9 );\n        EXPECT_NEAR(  1, front_left.velocity, 1e-9 );\n        EXPECT_NEAR( -M_PI*0.5, front_right.turnrate, 1e-9 );\n        EXPECT_NEAR( -1, front_right.velocity, 1e-9 );\n        EXPECT_NEAR( -M_PI*0.5, rear_right.turnrate, 1e-9 );\n        EXPECT_NEAR( -1, rear_right.velocity, 1e-9 );\n    }\n}\n\nTEST_F( wheels_test_180, crab_nearest_south_west )\n{\n    steer_command steer( -1, 1, 0 );\n    {\n        boost::optional< double > current_angle( 0 );\n        wheel_command rear_left = compute_wheel_command( steer, rear_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_left = compute_wheel_command( steer, front_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_right = compute_wheel_command( steer, front_right_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command rear_right = compute_wheel_command( steer, rear_right_pose, wheel_offset, angle_limit, current_angle );\n        EXPECT_NEAR( -M_PI*0.25, rear_left.turnrate, 1e-9 );\n        EXPECT_NEAR(  std::sqrt(2), rear_left.velocity, 1e-9 );\n        EXPECT_NEAR( -M_PI*0.25, front_left.turnrate, 1e-9 );\n        EXPECT_NEAR(  std::sqrt(2), front_left.velocity, 1e-9 );\n        EXPECT_NEAR( -M_PI*0.25, front_right.turnrate, 1e-9 );\n        EXPECT_NEAR( -std::sqrt(2), front_right.velocity, 1e-9 );\n        EXPECT_NEAR( -M_PI*0.25, rear_right.turnrate, 1e-9 );\n        EXPECT_NEAR( -std::sqrt(2), rear_right.velocity, 1e-9 );\n    }\n    {\n        boost::optional< double > current_angle( M_PI );\n        wheel_command rear_left = compute_wheel_command( steer, rear_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_left = compute_wheel_command( steer, front_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_right = compute_wheel_command( steer, front_right_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command rear_right = compute_wheel_command( steer, rear_right_pose, wheel_offset, angle_limit, current_angle );\n        EXPECT_NEAR(  M_PI*0.75, rear_left.turnrate, 1e-9 );\n        EXPECT_NEAR( -std::sqrt(2), rear_left.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*0.75, front_left.turnrate, 1e-9 );\n        EXPECT_NEAR( -std::sqrt(2), front_left.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*0.75, front_right.turnrate, 1e-9 );\n        EXPECT_NEAR(  std::sqrt(2), front_right.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*0.75, rear_right.turnrate, 1e-9 );\n        EXPECT_NEAR(  std::sqrt(2), rear_right.velocity, 1e-9 );\n    }\n    {\n        boost::optional< double > current_angle( -M_PI );\n        wheel_command rear_left = compute_wheel_command( steer, rear_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_left = compute_wheel_command( steer, front_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_right = compute_wheel_command( steer, front_right_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command rear_right = compute_wheel_command( steer, rear_right_pose, wheel_offset, angle_limit, current_angle );\n        EXPECT_NEAR( -M_PI*0.25, rear_left.turnrate, 1e-9 );\n        EXPECT_NEAR(  std::sqrt(2), rear_left.velocity, 1e-9 );\n        EXPECT_NEAR( -M_PI*0.25, front_left.turnrate, 1e-9 );\n        EXPECT_NEAR(  std::sqrt(2), front_left.velocity, 1e-9 );\n        EXPECT_NEAR( -M_PI*0.25, front_right.turnrate, 1e-9 );\n        EXPECT_NEAR( -std::sqrt(2), front_right.velocity, 1e-9 );\n        EXPECT_NEAR( -M_PI*0.25, rear_right.turnrate, 1e-9 );\n        EXPECT_NEAR( -std::sqrt(2), rear_right.velocity, 1e-9 );\n    }\n}\n\nTEST_F( wheels_test_180, spot_turn )\n{\n    steer_command steer( 0, 0, 1 );\n    {\n        boost::optional< double > current_angle( 0 );\n        wheel_command rear_left = compute_wheel_command( steer, rear_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_left = compute_wheel_command( steer, front_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_right = compute_wheel_command( steer, front_right_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command rear_right = compute_wheel_command( steer, rear_right_pose, wheel_offset, angle_limit, current_angle );\n        EXPECT_NEAR(  M_PI*0.25, rear_left.turnrate, 1e-9 );\n        EXPECT_NEAR(  std::sqrt(2), rear_left.velocity, 1e-9 );\n        EXPECT_NEAR( -M_PI*0.25, front_left.turnrate, 1e-9 );\n        EXPECT_NEAR(  std::sqrt(2), front_left.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*0.25, front_right.turnrate, 1e-9 );\n        EXPECT_NEAR(  std::sqrt(2), front_right.velocity, 1e-9 );\n        EXPECT_NEAR( -M_PI*0.25, rear_right.turnrate, 1e-9 );\n        EXPECT_NEAR(  std::sqrt(2), rear_right.velocity, 1e-9 );\n    }\n    {\n        boost::optional< double > current_angle( M_PI*0.5 );\n        wheel_command rear_left = compute_wheel_command( steer, rear_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_left = compute_wheel_command( steer, front_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_right = compute_wheel_command( steer, front_right_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command rear_right = compute_wheel_command( steer, rear_right_pose, wheel_offset, angle_limit, current_angle );\n        EXPECT_NEAR(  M_PI*0.25, rear_left.turnrate, 1e-9 );\n        EXPECT_NEAR(  std::sqrt(2), rear_left.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*0.75, front_left.turnrate, 1e-9 );\n        EXPECT_NEAR( -std::sqrt(2), front_left.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*0.25, front_right.turnrate, 1e-9 );\n        EXPECT_NEAR(  std::sqrt(2), front_right.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*0.75, rear_right.turnrate, 1e-9 );\n        EXPECT_NEAR( -std::sqrt(2), rear_right.velocity, 1e-9 );\n    }\n    {\n        boost::optional< double > current_angle( -M_PI*0.5 );\n        wheel_command rear_left = compute_wheel_command( steer, rear_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_left = compute_wheel_command( steer, front_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_right = compute_wheel_command( steer, front_right_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command rear_right = compute_wheel_command( steer, rear_right_pose, wheel_offset, angle_limit, current_angle );\n        EXPECT_NEAR( -M_PI*0.75, rear_left.turnrate, 1e-9 );\n        EXPECT_NEAR( -std::sqrt(2), rear_left.velocity, 1e-9 );\n        EXPECT_NEAR( -M_PI*0.25, front_left.turnrate, 1e-9 );\n        EXPECT_NEAR(  std::sqrt(2), front_left.velocity, 1e-9 );\n        EXPECT_NEAR( -M_PI*0.75, front_right.turnrate, 1e-9 );\n        EXPECT_NEAR( -std::sqrt(2), front_right.velocity, 1e-9 );\n        EXPECT_NEAR( -M_PI*0.25, rear_right.turnrate, 1e-9 );\n        EXPECT_NEAR(  std::sqrt(2), rear_right.velocity, 1e-9 );\n    }\n}\n\nTEST_F( wheels_test_720, crab_nearest_north )\n{\n    steer_command steer( 1, 0, 0 );\n    {\n        boost::optional< double > current_angle( 350/180.0*M_PI );\n        wheel_command rear_left = compute_wheel_command( steer, rear_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_left = compute_wheel_command( steer, front_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_right = compute_wheel_command( steer, front_right_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command rear_right = compute_wheel_command( steer, rear_right_pose, wheel_offset, angle_limit, current_angle );\n        EXPECT_NEAR(  M_PI*2, rear_left.turnrate, 1e-9 );\n        EXPECT_NEAR( -1, rear_left.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*2, front_left.turnrate, 1e-9 );\n        EXPECT_NEAR( -1, front_left.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*2, front_right.turnrate, 1e-9 );\n        EXPECT_NEAR(  1, front_right.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*2, rear_right.turnrate, 1e-9 );\n        EXPECT_NEAR(  1, rear_right.velocity, 1e-9 );\n    }\n}\n\nTEST_F( wheels_test_540, crab_nearest_north )\n{\n    steer_command steer( 1, 0, 0 );\n    {\n        boost::optional< double > current_angle( 0 );\n        wheel_command rear_left = compute_wheel_command( steer, rear_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_left = compute_wheel_command( steer, front_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_right = compute_wheel_command( steer, front_right_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command rear_right = compute_wheel_command( steer, rear_right_pose, wheel_offset, angle_limit, current_angle );\n        EXPECT_NEAR(  0, rear_left.turnrate, 1e-9 );\n        EXPECT_NEAR( -1, rear_left.velocity, 1e-9 );\n        EXPECT_NEAR(  0, front_left.turnrate, 1e-9 );\n        EXPECT_NEAR( -1, front_left.velocity, 1e-9 );\n        EXPECT_NEAR(  0, front_right.turnrate, 1e-9 );\n        EXPECT_NEAR(  1, front_right.velocity, 1e-9 );\n        EXPECT_NEAR(  0, rear_right.turnrate, 1e-9 );\n        EXPECT_NEAR(  1, rear_right.velocity, 1e-9 );\n    }\n    {\n        boost::optional< double > current_angle( M_PI );\n        wheel_command rear_left = compute_wheel_command( steer, rear_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_left = compute_wheel_command( steer, front_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_right = compute_wheel_command( steer, front_right_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command rear_right = compute_wheel_command( steer, rear_right_pose, wheel_offset, angle_limit, current_angle );\n        EXPECT_NEAR(  M_PI, rear_left.turnrate, 1e-9 );\n        EXPECT_NEAR(  1, rear_left.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI, front_left.turnrate, 1e-9 );\n        EXPECT_NEAR(  1, front_left.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI, front_right.turnrate, 1e-9 );\n        EXPECT_NEAR( -1, front_right.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI, rear_right.turnrate, 1e-9 );\n        EXPECT_NEAR( -1, rear_right.velocity, 1e-9 );\n    }\n    {\n        boost::optional< double > current_angle( M_PI*2 );\n        wheel_command rear_left = compute_wheel_command( steer, rear_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_left = compute_wheel_command( steer, front_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_right = compute_wheel_command( steer, front_right_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command rear_right = compute_wheel_command( steer, rear_right_pose, wheel_offset, angle_limit, current_angle );\n        EXPECT_NEAR(  M_PI*2, rear_left.turnrate, 1e-9 );\n        EXPECT_NEAR( -1, rear_left.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*2, front_left.turnrate, 1e-9 );\n        EXPECT_NEAR( -1, front_left.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*2, front_right.turnrate, 1e-9 );\n        EXPECT_NEAR(  1, front_right.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*2, rear_right.turnrate, 1e-9 );\n        EXPECT_NEAR(  1, rear_right.velocity, 1e-9 );\n    }\n    {\n        boost::optional< double > current_angle( M_PI*3 );\n        wheel_command rear_left = compute_wheel_command( steer, rear_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_left = compute_wheel_command( steer, front_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_right = compute_wheel_command( steer, front_right_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command rear_right = compute_wheel_command( steer, rear_right_pose, wheel_offset, angle_limit, current_angle );\n        EXPECT_NEAR(  M_PI*3, rear_left.turnrate, 1e-9 );\n        EXPECT_NEAR(  1, rear_left.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*3, front_left.turnrate, 1e-9 );\n        EXPECT_NEAR(  1, front_left.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*3, front_right.turnrate, 1e-9 );\n        EXPECT_NEAR( -1, front_right.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*3, rear_right.turnrate, 1e-9 );\n        EXPECT_NEAR( -1, rear_right.velocity, 1e-9 );\n    }\n}\n\nTEST_F( wheels_test_540, crab_nearest_south )\n{\n    steer_command steer( -1, 0, 0 );\n    {\n        boost::optional< double > current_angle( 0 );\n        wheel_command rear_left = compute_wheel_command( steer, rear_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_left = compute_wheel_command( steer, front_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_right = compute_wheel_command( steer, front_right_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command rear_right = compute_wheel_command( steer, rear_right_pose, wheel_offset, angle_limit, current_angle );\n        EXPECT_NEAR(  0, rear_left.turnrate, 1e-9 );\n        EXPECT_NEAR(  1, rear_left.velocity, 1e-9 );\n        EXPECT_NEAR(  0, front_left.turnrate, 1e-9 );\n        EXPECT_NEAR(  1, front_left.velocity, 1e-9 );\n        EXPECT_NEAR(  0, front_right.turnrate, 1e-9 );\n        EXPECT_NEAR( -1, front_right.velocity, 1e-9 );\n        EXPECT_NEAR(  0, rear_right.turnrate, 1e-9 );\n        EXPECT_NEAR( -1, rear_right.velocity, 1e-9 );\n    }\n    {\n        boost::optional< double > current_angle( M_PI );\n        wheel_command rear_left = compute_wheel_command( steer, rear_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_left = compute_wheel_command( steer, front_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_right = compute_wheel_command( steer, front_right_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command rear_right = compute_wheel_command( steer, rear_right_pose, wheel_offset, angle_limit, current_angle );\n        EXPECT_NEAR(  M_PI, rear_left.turnrate, 1e-9 );\n        EXPECT_NEAR( -1, rear_left.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI, front_left.turnrate, 1e-9 );\n        EXPECT_NEAR( -1, front_left.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI, front_right.turnrate, 1e-9 );\n        EXPECT_NEAR(  1, front_right.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI, rear_right.turnrate, 1e-9 );\n        EXPECT_NEAR(  1, rear_right.velocity, 1e-9 );\n    }\n    {\n        boost::optional< double > current_angle( M_PI*2 );\n        wheel_command rear_left = compute_wheel_command( steer, rear_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_left = compute_wheel_command( steer, front_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_right = compute_wheel_command( steer, front_right_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command rear_right = compute_wheel_command( steer, rear_right_pose, wheel_offset, angle_limit, current_angle );\n        EXPECT_NEAR(  M_PI*2, rear_left.turnrate, 1e-9 );\n        EXPECT_NEAR(  1, rear_left.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*2, front_left.turnrate, 1e-9 );\n        EXPECT_NEAR(  1, front_left.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*2, front_right.turnrate, 1e-9 );\n        EXPECT_NEAR( -1, front_right.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*2, rear_right.turnrate, 1e-9 );\n        EXPECT_NEAR( -1, rear_right.velocity, 1e-9 );\n    }\n    {\n        boost::optional< double > current_angle( M_PI*3 );\n        wheel_command rear_left = compute_wheel_command( steer, rear_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_left = compute_wheel_command( steer, front_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_right = compute_wheel_command( steer, front_right_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command rear_right = compute_wheel_command( steer, rear_right_pose, wheel_offset, angle_limit, current_angle );\n        EXPECT_NEAR(  M_PI*3, rear_left.turnrate, 1e-9 );\n        EXPECT_NEAR( -1, rear_left.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*3, front_left.turnrate, 1e-9 );\n        EXPECT_NEAR( -1, front_left.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*3, front_right.turnrate, 1e-9 );\n        EXPECT_NEAR(  1, front_right.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*3, rear_right.turnrate, 1e-9 );\n        EXPECT_NEAR(  1, rear_right.velocity, 1e-9 );\n    }\n}\n\nTEST_F( wheels_test_540, crab_nearest_east )\n{\n    steer_command steer( 0, -1, 0 );\n    {\n        boost::optional< double > current_angle( 0 );\n        wheel_command rear_left = compute_wheel_command( steer, rear_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_left = compute_wheel_command( steer, front_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_right = compute_wheel_command( steer, front_right_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command rear_right = compute_wheel_command( steer, rear_right_pose, wheel_offset, angle_limit, current_angle );\n        EXPECT_NEAR(  M_PI*0.5, rear_left.turnrate, 1e-9 );\n        EXPECT_NEAR(  1, rear_left.velocity, 1e-9 );\n        EXPECT_NEAR( -M_PI*0.5, front_left.turnrate, 1e-9 );\n        EXPECT_NEAR( -1, front_left.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*0.5, front_right.turnrate, 1e-9 );\n        EXPECT_NEAR( -1, front_right.velocity, 1e-9 );\n        EXPECT_NEAR( -M_PI*0.5, rear_right.turnrate, 1e-9 );\n        EXPECT_NEAR(  1, rear_right.velocity, 1e-9 );\n    }\n    {\n        boost::optional< double > current_angle( M_PI*0.25 );\n        wheel_command rear_left = compute_wheel_command( steer, rear_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_left = compute_wheel_command( steer, front_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_right = compute_wheel_command( steer, front_right_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command rear_right = compute_wheel_command( steer, rear_right_pose, wheel_offset, angle_limit, current_angle );\n        EXPECT_NEAR(  M_PI*0.5, rear_left.turnrate, 1e-9 );\n        EXPECT_NEAR(  1, rear_left.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*0.5, front_left.turnrate, 1e-9 );\n        EXPECT_NEAR(  1, front_left.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*0.5, front_right.turnrate, 1e-9 );\n        EXPECT_NEAR( -1, front_right.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*0.5, rear_right.turnrate, 1e-9 );\n        EXPECT_NEAR( -1, rear_right.velocity, 1e-9 );\n    }\n    {\n        boost::optional< double > current_angle( M_PI*2 );\n        wheel_command rear_left = compute_wheel_command( steer, rear_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_left = compute_wheel_command( steer, front_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_right = compute_wheel_command( steer, front_right_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command rear_right = compute_wheel_command( steer, rear_right_pose, wheel_offset, angle_limit, current_angle );\n        EXPECT_NEAR(  M_PI*2.5, rear_left.turnrate, 1e-9 );\n        EXPECT_NEAR(  1, rear_left.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*1.5, front_left.turnrate, 1e-9 );\n        EXPECT_NEAR( -1, front_left.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*2.5, front_right.turnrate, 1e-9 );\n        EXPECT_NEAR( -1, front_right.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*1.5, rear_right.turnrate, 1e-9 );\n        EXPECT_NEAR(  1, rear_right.velocity, 1e-9 );\n    }\n    {\n        boost::optional< double > current_angle( M_PI*3 );\n        wheel_command rear_left = compute_wheel_command( steer, rear_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_left = compute_wheel_command( steer, front_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_right = compute_wheel_command( steer, front_right_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command rear_right = compute_wheel_command( steer, rear_right_pose, wheel_offset, angle_limit, current_angle );\n        EXPECT_NEAR(  M_PI*2.5, rear_left.turnrate, 1e-9 );\n        EXPECT_NEAR(  1, rear_left.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*2.5, front_left.turnrate, 1e-9 );\n        EXPECT_NEAR(  1, front_left.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*2.5, front_right.turnrate, 1e-9 );\n        EXPECT_NEAR( -1, front_right.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*2.5, rear_right.turnrate, 1e-9 );\n        EXPECT_NEAR( -1, rear_right.velocity, 1e-9 );\n    }\n}\n\nTEST_F( wheels_test_540, crab_nearest_west )\n{\n    steer_command steer( 0, 1, 0 );\n    {\n        boost::optional< double > current_angle( 0 );\n        wheel_command rear_left = compute_wheel_command( steer, rear_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_left = compute_wheel_command( steer, front_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_right = compute_wheel_command( steer, front_right_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command rear_right = compute_wheel_command( steer, rear_right_pose, wheel_offset, angle_limit, current_angle );\n        EXPECT_NEAR(  M_PI*0.5, rear_left.turnrate, 1e-9 );\n        EXPECT_NEAR( -1, rear_left.velocity, 1e-9 );\n        EXPECT_NEAR( -M_PI*0.5, front_left.turnrate, 1e-9 );\n        EXPECT_NEAR(  1, front_left.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*0.5, front_right.turnrate, 1e-9 );\n        EXPECT_NEAR(  1, front_right.velocity, 1e-9 );\n        EXPECT_NEAR( -M_PI*0.5, rear_right.turnrate, 1e-9 );\n        EXPECT_NEAR( -1, rear_right.velocity, 1e-9 );\n    }\n    {\n        boost::optional< double > current_angle( -M_PI*0.25 );\n        wheel_command rear_left = compute_wheel_command( steer, rear_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_left = compute_wheel_command( steer, front_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_right = compute_wheel_command( steer, front_right_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command rear_right = compute_wheel_command( steer, rear_right_pose, wheel_offset, angle_limit, current_angle );\n        EXPECT_NEAR( -M_PI*0.5, rear_left.turnrate, 1e-9 );\n        EXPECT_NEAR(  1, rear_left.velocity, 1e-9 );\n        EXPECT_NEAR( -M_PI*0.5, front_left.turnrate, 1e-9 );\n        EXPECT_NEAR(  1, front_left.velocity, 1e-9 );\n        EXPECT_NEAR( -M_PI*0.5, front_right.turnrate, 1e-9 );\n        EXPECT_NEAR( -1, front_right.velocity, 1e-9 );\n        EXPECT_NEAR( -M_PI*0.5, rear_right.turnrate, 1e-9 );\n        EXPECT_NEAR( -1, rear_right.velocity, 1e-9 );\n    }\n    {\n        boost::optional< double > current_angle( M_PI*2 );\n        wheel_command rear_left = compute_wheel_command( steer, rear_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_left = compute_wheel_command( steer, front_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_right = compute_wheel_command( steer, front_right_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command rear_right = compute_wheel_command( steer, rear_right_pose, wheel_offset, angle_limit, current_angle );\n        EXPECT_NEAR(  M_PI*2.5, rear_left.turnrate, 1e-9 );\n        EXPECT_NEAR( -1, rear_left.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*1.5, front_left.turnrate, 1e-9 );\n        EXPECT_NEAR(  1, front_left.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*2.5, front_right.turnrate, 1e-9 );\n        EXPECT_NEAR(  1, front_right.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*1.5, rear_right.turnrate, 1e-9 );\n        EXPECT_NEAR( -1, rear_right.velocity, 1e-9 );\n    }\n    {\n        boost::optional< double > current_angle( M_PI*3 );\n        wheel_command rear_left = compute_wheel_command( steer, rear_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_left = compute_wheel_command( steer, front_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_right = compute_wheel_command( steer, front_right_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command rear_right = compute_wheel_command( steer, rear_right_pose, wheel_offset, angle_limit, current_angle );\n        EXPECT_NEAR(  M_PI*2.5, rear_left.turnrate, 1e-9 );\n        EXPECT_NEAR( -1, rear_left.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*2.5, front_left.turnrate, 1e-9 );\n        EXPECT_NEAR( -1, front_left.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*2.5, front_right.turnrate, 1e-9 );\n        EXPECT_NEAR(  1, front_right.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*2.5, rear_right.turnrate, 1e-9 );\n        EXPECT_NEAR(  1, rear_right.velocity, 1e-9 );\n    }\n}\n\nTEST_F( wheels_test_540, crab_nearest_south_west )\n{\n    steer_command steer( -1, 1, 0 );\n    {\n        boost::optional< double > current_angle( 0 );\n        wheel_command rear_left = compute_wheel_command( steer, rear_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_left = compute_wheel_command( steer, front_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_right = compute_wheel_command( steer, front_right_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command rear_right = compute_wheel_command( steer, rear_right_pose, wheel_offset, angle_limit, current_angle );\n        EXPECT_NEAR( -M_PI*0.25, rear_left.turnrate, 1e-9 );\n        EXPECT_NEAR(  std::sqrt(2), rear_left.velocity, 1e-9 );\n        EXPECT_NEAR( -M_PI*0.25, front_left.turnrate, 1e-9 );\n        EXPECT_NEAR(  std::sqrt(2), front_left.velocity, 1e-9 );\n        EXPECT_NEAR( -M_PI*0.25, front_right.turnrate, 1e-9 );\n        EXPECT_NEAR( -std::sqrt(2), front_right.velocity, 1e-9 );\n        EXPECT_NEAR( -M_PI*0.25, rear_right.turnrate, 1e-9 );\n        EXPECT_NEAR( -std::sqrt(2), rear_right.velocity, 1e-9 );\n    }\n    {\n        boost::optional< double > current_angle( M_PI );\n        wheel_command rear_left = compute_wheel_command( steer, rear_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_left = compute_wheel_command( steer, front_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_right = compute_wheel_command( steer, front_right_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command rear_right = compute_wheel_command( steer, rear_right_pose, wheel_offset, angle_limit, current_angle );\n        EXPECT_NEAR(  M_PI*0.75, rear_left.turnrate, 1e-9 );\n        EXPECT_NEAR( -std::sqrt(2), rear_left.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*0.75, front_left.turnrate, 1e-9 );\n        EXPECT_NEAR( -std::sqrt(2), front_left.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*0.75, front_right.turnrate, 1e-9 );\n        EXPECT_NEAR(  std::sqrt(2), front_right.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*0.75, rear_right.turnrate, 1e-9 );\n        EXPECT_NEAR(  std::sqrt(2), rear_right.velocity, 1e-9 );\n    }\n    {\n        boost::optional< double > current_angle( -M_PI );\n        wheel_command rear_left = compute_wheel_command( steer, rear_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_left = compute_wheel_command( steer, front_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_right = compute_wheel_command( steer, front_right_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command rear_right = compute_wheel_command( steer, rear_right_pose, wheel_offset, angle_limit, current_angle );\n        EXPECT_NEAR( -M_PI*1.25, rear_left.turnrate, 1e-9 );\n        EXPECT_NEAR( -std::sqrt(2), rear_left.velocity, 1e-9 );\n        EXPECT_NEAR( -M_PI*1.25, front_left.turnrate, 1e-9 );\n        EXPECT_NEAR( -std::sqrt(2), front_left.velocity, 1e-9 );\n        EXPECT_NEAR( -M_PI*1.25, front_right.turnrate, 1e-9 );\n        EXPECT_NEAR(  std::sqrt(2), front_right.velocity, 1e-9 );\n        EXPECT_NEAR( -M_PI*1.25, rear_right.turnrate, 1e-9 );\n        EXPECT_NEAR(  std::sqrt(2), rear_right.velocity, 1e-9 );\n    }\n    {\n        boost::optional< double > current_angle( M_PI*2 );\n        wheel_command rear_left = compute_wheel_command( steer, rear_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_left = compute_wheel_command( steer, front_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_right = compute_wheel_command( steer, front_right_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command rear_right = compute_wheel_command( steer, rear_right_pose, wheel_offset, angle_limit, current_angle );\n        EXPECT_NEAR(  M_PI*1.75, rear_left.turnrate, 1e-9 );\n        EXPECT_NEAR(  std::sqrt(2), rear_left.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*1.75, front_left.turnrate, 1e-9 );\n        EXPECT_NEAR(  std::sqrt(2), front_left.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*1.75, front_right.turnrate, 1e-9 );\n        EXPECT_NEAR( -std::sqrt(2), front_right.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*1.75, rear_right.turnrate, 1e-9 );\n        EXPECT_NEAR( -std::sqrt(2), rear_right.velocity, 1e-9 );\n    }\n    {\n        boost::optional< double > current_angle( -M_PI*2 );\n        wheel_command rear_left = compute_wheel_command( steer, rear_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_left = compute_wheel_command( steer, front_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_right = compute_wheel_command( steer, front_right_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command rear_right = compute_wheel_command( steer, rear_right_pose, wheel_offset, angle_limit, current_angle );\n        EXPECT_NEAR( -M_PI*2.25, rear_left.turnrate, 1e-9 );\n        EXPECT_NEAR(  std::sqrt(2), rear_left.velocity, 1e-9 );\n        EXPECT_NEAR( -M_PI*2.25, front_left.turnrate, 1e-9 );\n        EXPECT_NEAR(  std::sqrt(2), front_left.velocity, 1e-9 );\n        EXPECT_NEAR( -M_PI*2.25, front_right.turnrate, 1e-9 );\n        EXPECT_NEAR( -std::sqrt(2), front_right.velocity, 1e-9 );\n        EXPECT_NEAR( -M_PI*2.25, rear_right.turnrate, 1e-9 );\n        EXPECT_NEAR( -std::sqrt(2), rear_right.velocity, 1e-9 );\n    }\n    {\n        boost::optional< double > current_angle( M_PI*3 );\n        wheel_command rear_left = compute_wheel_command( steer, rear_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_left = compute_wheel_command( steer, front_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_right = compute_wheel_command( steer, front_right_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command rear_right = compute_wheel_command( steer, rear_right_pose, wheel_offset, angle_limit, current_angle );\n        EXPECT_NEAR(  M_PI*2.75, rear_left.turnrate, 1e-9 );\n        EXPECT_NEAR( -std::sqrt(2), rear_left.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*2.75, front_left.turnrate, 1e-9 );\n        EXPECT_NEAR( -std::sqrt(2), front_left.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*2.75, front_right.turnrate, 1e-9 );\n        EXPECT_NEAR(  std::sqrt(2), front_right.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*2.75, rear_right.turnrate, 1e-9 );\n        EXPECT_NEAR(  std::sqrt(2), rear_right.velocity, 1e-9 );\n    }\n    {\n        boost::optional< double > current_angle( -M_PI*3 );\n        wheel_command rear_left = compute_wheel_command( steer, rear_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_left = compute_wheel_command( steer, front_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_right = compute_wheel_command( steer, front_right_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command rear_right = compute_wheel_command( steer, rear_right_pose, wheel_offset, angle_limit, current_angle );\n        EXPECT_NEAR( -M_PI*2.25, rear_left.turnrate, 1e-9 );\n        EXPECT_NEAR(  std::sqrt(2), rear_left.velocity, 1e-9 );\n        EXPECT_NEAR( -M_PI*2.25, front_left.turnrate, 1e-9 );\n        EXPECT_NEAR(  std::sqrt(2), front_left.velocity, 1e-9 );\n        EXPECT_NEAR( -M_PI*2.25, front_right.turnrate, 1e-9 );\n        EXPECT_NEAR( -std::sqrt(2), front_right.velocity, 1e-9 );\n        EXPECT_NEAR( -M_PI*2.25, rear_right.turnrate, 1e-9 );\n        EXPECT_NEAR( -std::sqrt(2), rear_right.velocity, 1e-9 );\n    }\n}\n\nTEST_F( wheels_test_540, spot_turn )\n{\n    steer_command steer( 0, 0, 1 );\n    {\n        boost::optional< double > current_angle( 0 );\n        wheel_command rear_left = compute_wheel_command( steer, rear_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_left = compute_wheel_command( steer, front_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_right = compute_wheel_command( steer, front_right_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command rear_right = compute_wheel_command( steer, rear_right_pose, wheel_offset, angle_limit, current_angle );\n        EXPECT_NEAR(  M_PI*0.25, rear_left.turnrate, 1e-9 );\n        EXPECT_NEAR(  std::sqrt(2), rear_left.velocity, 1e-9 );\n        EXPECT_NEAR( -M_PI*0.25, front_left.turnrate, 1e-9 );\n        EXPECT_NEAR(  std::sqrt(2), front_left.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*0.25, front_right.turnrate, 1e-9 );\n        EXPECT_NEAR(  std::sqrt(2), front_right.velocity, 1e-9 );\n        EXPECT_NEAR( -M_PI*0.25, rear_right.turnrate, 1e-9 );\n        EXPECT_NEAR(  std::sqrt(2), rear_right.velocity, 1e-9 );\n    }\n    {\n        boost::optional< double > current_angle( M_PI*0.5 );\n        wheel_command rear_left = compute_wheel_command( steer, rear_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_left = compute_wheel_command( steer, front_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_right = compute_wheel_command( steer, front_right_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command rear_right = compute_wheel_command( steer, rear_right_pose, wheel_offset, angle_limit, current_angle );\n        EXPECT_NEAR(  M_PI*0.25, rear_left.turnrate, 1e-9 );\n        EXPECT_NEAR(  std::sqrt(2), rear_left.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*0.75, front_left.turnrate, 1e-9 );\n        EXPECT_NEAR( -std::sqrt(2), front_left.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*0.25, front_right.turnrate, 1e-9 );\n        EXPECT_NEAR(  std::sqrt(2), front_right.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*0.75, rear_right.turnrate, 1e-9 );\n        EXPECT_NEAR( -std::sqrt(2), rear_right.velocity, 1e-9 );\n    }\n    {\n        boost::optional< double > current_angle( -M_PI*0.5 );\n        wheel_command rear_left = compute_wheel_command( steer, rear_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_left = compute_wheel_command( steer, front_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_right = compute_wheel_command( steer, front_right_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command rear_right = compute_wheel_command( steer, rear_right_pose, wheel_offset, angle_limit, current_angle );\n        EXPECT_NEAR( -M_PI*0.75, rear_left.turnrate, 1e-9 );\n        EXPECT_NEAR( -std::sqrt(2), rear_left.velocity, 1e-9 );\n        EXPECT_NEAR( -M_PI*0.25, front_left.turnrate, 1e-9 );\n        EXPECT_NEAR(  std::sqrt(2), front_left.velocity, 1e-9 );\n        EXPECT_NEAR( -M_PI*0.75, front_right.turnrate, 1e-9 );\n        EXPECT_NEAR( -std::sqrt(2), front_right.velocity, 1e-9 );\n        EXPECT_NEAR( -M_PI*0.25, rear_right.turnrate, 1e-9 );\n        EXPECT_NEAR(  std::sqrt(2), rear_right.velocity, 1e-9 );\n    }\n    {\n        boost::optional< double > current_angle( M_PI*2 );\n        wheel_command rear_left = compute_wheel_command( steer, rear_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_left = compute_wheel_command( steer, front_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_right = compute_wheel_command( steer, front_right_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command rear_right = compute_wheel_command( steer, rear_right_pose, wheel_offset, angle_limit, current_angle );\n        EXPECT_NEAR(  M_PI*2.25, rear_left.turnrate, 1e-9 );\n        EXPECT_NEAR(  std::sqrt(2), rear_left.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*1.75, front_left.turnrate, 1e-9 );\n        EXPECT_NEAR(  std::sqrt(2), front_left.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*2.25, front_right.turnrate, 1e-9 );\n        EXPECT_NEAR(  std::sqrt(2), front_right.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*1.75, rear_right.turnrate, 1e-9 );\n        EXPECT_NEAR(  std::sqrt(2), rear_right.velocity, 1e-9 );\n    }\n    {\n        boost::optional< double > current_angle( -M_PI*2 );\n        wheel_command rear_left = compute_wheel_command( steer, rear_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_left = compute_wheel_command( steer, front_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_right = compute_wheel_command( steer, front_right_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command rear_right = compute_wheel_command( steer, rear_right_pose, wheel_offset, angle_limit, current_angle );\n        EXPECT_NEAR( -M_PI*1.75, rear_left.turnrate, 1e-9 );\n        EXPECT_NEAR(  std::sqrt(2), rear_left.velocity, 1e-9 );\n        EXPECT_NEAR( -M_PI*2.25, front_left.turnrate, 1e-9 );\n        EXPECT_NEAR(  std::sqrt(2), front_left.velocity, 1e-9 );\n        EXPECT_NEAR( -M_PI*1.75, front_right.turnrate, 1e-9 );\n        EXPECT_NEAR(  std::sqrt(2), front_right.velocity, 1e-9 );\n        EXPECT_NEAR( -M_PI*2.25, rear_right.turnrate, 1e-9 );\n        EXPECT_NEAR(  std::sqrt(2), rear_right.velocity, 1e-9 );\n    }\n    {\n        boost::optional< double > current_angle( M_PI*3 );\n        wheel_command rear_left = compute_wheel_command( steer, rear_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_left = compute_wheel_command( steer, front_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_right = compute_wheel_command( steer, front_right_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command rear_right = compute_wheel_command( steer, rear_right_pose, wheel_offset, angle_limit, current_angle );\n        EXPECT_NEAR(  M_PI*2.25, rear_left.turnrate, 1e-9 );\n        EXPECT_NEAR(  std::sqrt(2), rear_left.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*2.75, front_left.turnrate, 1e-9 );\n        EXPECT_NEAR( -std::sqrt(2), front_left.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*2.25, front_right.turnrate, 1e-9 );\n        EXPECT_NEAR(  std::sqrt(2), front_right.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*2.75, rear_right.turnrate, 1e-9 );\n        EXPECT_NEAR( -std::sqrt(2), rear_right.velocity, 1e-9 );\n    }\n    {\n        boost::optional< double > current_angle( -M_PI*3 );\n        wheel_command rear_left = compute_wheel_command( steer, rear_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_left = compute_wheel_command( steer, front_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_right = compute_wheel_command( steer, front_right_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command rear_right = compute_wheel_command( steer, rear_right_pose, wheel_offset, angle_limit, current_angle );\n        EXPECT_NEAR( -M_PI*2.75, rear_left.turnrate, 1e-9 );\n        EXPECT_NEAR( -std::sqrt(2), rear_left.velocity, 1e-9 );\n        EXPECT_NEAR( -M_PI*2.25, front_left.turnrate, 1e-9 );\n        EXPECT_NEAR(  std::sqrt(2), front_left.velocity, 1e-9 );\n        EXPECT_NEAR( -M_PI*2.75, front_right.turnrate, 1e-9 );\n        EXPECT_NEAR( -std::sqrt(2), front_right.velocity, 1e-9 );\n        EXPECT_NEAR( -M_PI*2.25, rear_right.turnrate, 1e-9 );\n        EXPECT_NEAR(  std::sqrt(2), rear_right.velocity, 1e-9 );\n    }\n}\n\nTEST_F( wheels_test_no_limit, crab_north )\n{\n    steer_command steer( 1, 0, 0 );\n    boost::optional< double > current_angle;\n    wheel_command rear_left = compute_wheel_command( steer, rear_left_pose, wheel_offset, angle_limit, current_angle );\n    wheel_command front_left = compute_wheel_command( steer, front_left_pose, wheel_offset, angle_limit, current_angle );\n    wheel_command front_right = compute_wheel_command( steer, front_right_pose, wheel_offset, angle_limit, current_angle );\n    wheel_command rear_right = compute_wheel_command( steer, rear_right_pose, wheel_offset, angle_limit, current_angle );\n    EXPECT_NEAR(  0, rear_left.turnrate, 1e-9 );\n    EXPECT_NEAR( -1, rear_left.velocity, 1e-9 );\n    EXPECT_NEAR(  0, front_left.turnrate, 1e-9 );\n    EXPECT_NEAR( -1, front_left.velocity, 1e-9 );\n    EXPECT_NEAR(  0, front_right.turnrate, 1e-9 );\n    EXPECT_NEAR(  1, front_right.velocity, 1e-9 );\n    EXPECT_NEAR(  0, rear_right.turnrate, 1e-9 );\n    EXPECT_NEAR(  1, rear_right.velocity, 1e-9 );\n}\n\nTEST_F( wheels_test_no_limit, crab_nearest_south_west )\n{\n    steer_command steer( -1, 1, 0 );\n    {\n        boost::optional< double > current_angle( 0 );\n        wheel_command rear_left = compute_wheel_command( steer, rear_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_left = compute_wheel_command( steer, front_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_right = compute_wheel_command( steer, front_right_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command rear_right = compute_wheel_command( steer, rear_right_pose, wheel_offset, angle_limit, current_angle );\n        EXPECT_NEAR( -M_PI*0.25, rear_left.turnrate, 1e-9 );\n        EXPECT_NEAR(  std::sqrt(2), rear_left.velocity, 1e-9 );\n        EXPECT_NEAR( -M_PI*0.25, front_left.turnrate, 1e-9 );\n        EXPECT_NEAR(  std::sqrt(2), front_left.velocity, 1e-9 );\n        EXPECT_NEAR( -M_PI*0.25, front_right.turnrate, 1e-9 );\n        EXPECT_NEAR( -std::sqrt(2), front_right.velocity, 1e-9 );\n        EXPECT_NEAR( -M_PI*0.25, rear_right.turnrate, 1e-9 );\n        EXPECT_NEAR( -std::sqrt(2), rear_right.velocity, 1e-9 );\n    }\n    {\n        boost::optional< double > current_angle( M_PI );\n        wheel_command rear_left = compute_wheel_command( steer, rear_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_left = compute_wheel_command( steer, front_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_right = compute_wheel_command( steer, front_right_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command rear_right = compute_wheel_command( steer, rear_right_pose, wheel_offset, angle_limit, current_angle );\n        EXPECT_NEAR(  M_PI*0.75, rear_left.turnrate, 1e-9 );\n        EXPECT_NEAR( -std::sqrt(2), rear_left.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*0.75, front_left.turnrate, 1e-9 );\n        EXPECT_NEAR( -std::sqrt(2), front_left.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*0.75, front_right.turnrate, 1e-9 );\n        EXPECT_NEAR(  std::sqrt(2), front_right.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*0.75, rear_right.turnrate, 1e-9 );\n        EXPECT_NEAR(  std::sqrt(2), rear_right.velocity, 1e-9 );\n    }\n    {\n        boost::optional< double > current_angle( -M_PI );\n        wheel_command rear_left = compute_wheel_command( steer, rear_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_left = compute_wheel_command( steer, front_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_right = compute_wheel_command( steer, front_right_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command rear_right = compute_wheel_command( steer, rear_right_pose, wheel_offset, angle_limit, current_angle );\n        EXPECT_NEAR( -M_PI*1.25, rear_left.turnrate, 1e-9 );\n        EXPECT_NEAR( -std::sqrt(2), rear_left.velocity, 1e-9 );\n        EXPECT_NEAR( -M_PI*1.25, front_left.turnrate, 1e-9 );\n        EXPECT_NEAR( -std::sqrt(2), front_left.velocity, 1e-9 );\n        EXPECT_NEAR( -M_PI*1.25, front_right.turnrate, 1e-9 );\n        EXPECT_NEAR(  std::sqrt(2), front_right.velocity, 1e-9 );\n        EXPECT_NEAR( -M_PI*1.25, rear_right.turnrate, 1e-9 );\n        EXPECT_NEAR(  std::sqrt(2), rear_right.velocity, 1e-9 );\n    }\n}\n\nTEST_F( wheels_test_no_limit, spot_turn_nearest )\n{\n    steer_command steer( 0, 0, 1 );\n    {\n        boost::optional< double > current_angle( 0 );\n        wheel_command rear_left = compute_wheel_command( steer, rear_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_left = compute_wheel_command( steer, front_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_right = compute_wheel_command( steer, front_right_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command rear_right = compute_wheel_command( steer, rear_right_pose, wheel_offset, angle_limit, current_angle );\n        EXPECT_NEAR(  M_PI*0.25, rear_left.turnrate, 1e-9 );\n        EXPECT_NEAR(  std::sqrt(2), rear_left.velocity, 1e-9 );\n        EXPECT_NEAR( -M_PI*0.25, front_left.turnrate, 1e-9 );\n        EXPECT_NEAR(  std::sqrt(2), front_left.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*0.25, front_right.turnrate, 1e-9 );\n        EXPECT_NEAR(  std::sqrt(2), front_right.velocity, 1e-9 );\n        EXPECT_NEAR( -M_PI*0.25, rear_right.turnrate, 1e-9 );\n        EXPECT_NEAR(  std::sqrt(2), rear_right.velocity, 1e-9 );\n    }\n    {\n        boost::optional< double > current_angle( M_PI );\n        wheel_command rear_left = compute_wheel_command( steer, rear_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_left = compute_wheel_command( steer, front_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_right = compute_wheel_command( steer, front_right_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command rear_right = compute_wheel_command( steer, rear_right_pose, wheel_offset, angle_limit, current_angle );\n        EXPECT_NEAR(  M_PI*1.25, rear_left.turnrate, 1e-9 );\n        EXPECT_NEAR( -std::sqrt(2), rear_left.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*0.75, front_left.turnrate, 1e-9 );\n        EXPECT_NEAR( -std::sqrt(2), front_left.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*1.25, front_right.turnrate, 1e-9 );\n        EXPECT_NEAR( -std::sqrt(2), front_right.velocity, 1e-9 );\n        EXPECT_NEAR(  M_PI*0.75, rear_right.turnrate, 1e-9 );\n        EXPECT_NEAR( -std::sqrt(2), rear_right.velocity, 1e-9 );\n    }\n    {\n        boost::optional< double > current_angle( -M_PI );\n        wheel_command rear_left = compute_wheel_command( steer, rear_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_left = compute_wheel_command( steer, front_left_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command front_right = compute_wheel_command( steer, front_right_pose, wheel_offset, angle_limit, current_angle );\n        wheel_command rear_right = compute_wheel_command( steer, rear_right_pose, wheel_offset, angle_limit, current_angle );\n        EXPECT_NEAR( -M_PI*0.75, rear_left.turnrate, 1e-9 );\n        EXPECT_NEAR( -std::sqrt(2), rear_left.velocity, 1e-9 );\n        EXPECT_NEAR( -M_PI*1.25, front_left.turnrate, 1e-9 );\n        EXPECT_NEAR( -std::sqrt(2), front_left.velocity, 1e-9 );\n        EXPECT_NEAR( -M_PI*0.75, front_right.turnrate, 1e-9 );\n        EXPECT_NEAR( -std::sqrt(2), front_right.velocity, 1e-9 );\n        EXPECT_NEAR( -M_PI*1.25, rear_right.turnrate, 1e-9 );\n        EXPECT_NEAR( -std::sqrt(2), rear_right.velocity, 1e-9 );\n    }\n}\n", "meta": {"hexsha": "3ef610374bab966870d4a086b111cbb2c6430655", "size": 66629, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "actuators/wheels/test/test_wheels.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": "actuators/wheels/test/test_wheels.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": "actuators/wheels/test/test_wheels.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": 60.626933576, "max_line_length": 127, "alphanum_fraction": 0.6929265035, "num_tokens": 18260, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.46157550639757117}}
{"text": "/*\n * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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#define BOOST_TEST_MAIN\n\n#define BOOST_TEST_MODULE threecenter_gwbse_test\n\n// Third party includes\n#include <boost/test/unit_test.hpp>\n\n// VOTCA inlcudes\n#include <votca/tools/eigenio_matrixmarket.h>\n#include <votca/tools/tokenizer.h>\n\n// Local VOTCA includes\n#include \"votca/xtp/aobasis.h\"\n#include \"votca/xtp/qmmolecule.h\"\n#include \"votca/xtp/threecenter.h\"\n\nusing namespace votca::xtp;\nusing namespace std;\n\nBOOST_AUTO_TEST_SUITE(threecenter_gwbse_test)\nBOOST_AUTO_TEST_CASE(threecenter_gwbse) {\n\n  QMMolecule mol(\" \", 0);\n  mol.LoadFromFile(std::string(XTP_TEST_DATA_FOLDER) +\n                   \"/threecenter_gwbse/molecule.xyz\");\n  BasisSet basis;\n  basis.Load(std::string(XTP_TEST_DATA_FOLDER) +\n             \"/threecenter_gwbse/3-21G.xml\");\n  AOBasis aobasis;\n  aobasis.Fill(basis, mol);\n\n  Eigen::MatrixXd MOs = votca::tools::EigenIO_MatrixMarket::ReadMatrix(\n      std::string(XTP_TEST_DATA_FOLDER) + \"/threecenter_gwbse/MOs.mm\");\n\n  Logger log;\n  TCMatrix_gwbse tc{log};\n  tc.Initialize(aobasis.AOBasisSize(), 0, 5, 0, 7);\n  tc.Fill(aobasis, aobasis, MOs);\n\n  Eigen::MatrixXd ref0b = votca::tools::EigenIO_MatrixMarket::ReadMatrix(\n      std::string(XTP_TEST_DATA_FOLDER) + \"/threecenter_gwbse/ref0b.mm\");\n\n  bool check0_before = ref0b.isApprox(tc[0], 1e-5);\n  if (!check0_before) {\n    cout << \"tc0\" << endl;\n    cout << tc[0] << endl;\n    cout << \"tc0_ref\" << endl;\n    cout << ref0b << endl;\n  }\n  BOOST_CHECK_EQUAL(check0_before, true);\n\n  Eigen::MatrixXd ref2b = votca::tools::EigenIO_MatrixMarket::ReadMatrix(\n      std::string(XTP_TEST_DATA_FOLDER) + \"/threecenter_gwbse/ref2b.mm\");\n\n  bool check2_before = ref2b.isApprox(tc[2], 1e-5);\n  if (!check2_before) {\n    cout << \"tc2\" << endl;\n    cout << tc[2] << endl;\n    cout << \"tc2_ref\" << endl;\n    cout << ref2b << endl;\n  }\n\n  BOOST_CHECK_EQUAL(check2_before, true);\n\n  Eigen::MatrixXd ref4b = votca::tools::EigenIO_MatrixMarket::ReadMatrix(\n      std::string(XTP_TEST_DATA_FOLDER) + \"/threecenter_gwbse/ref4b.mm\");\n\n  bool check4_before = ref4b.isApprox(tc[4], 1e-5);\n  if (!check4_before) {\n    cout << \"tc4\" << endl;\n    cout << tc[4] << endl;\n    cout << \"tc4_ref\" << endl;\n    cout << ref4b << endl;\n  }\n\n  BOOST_CHECK_EQUAL(check4_before, true);\n\n  Eigen::MatrixXd auxmatrix =\n      Eigen::MatrixXd::Identity(aobasis.AOBasisSize(), aobasis.AOBasisSize());\n  tc.MultiplyRightWithAuxMatrix(auxmatrix);\n\n  bool check0_after = ref0b.isApprox(tc[0], 1e-5);\n  if (!check0_after) {\n    cout << \"tc0\" << endl;\n    cout << tc[0] << endl;\n    cout << \"tc0_ref\" << endl;\n    cout << ref0b << endl;\n  }\n  BOOST_CHECK_EQUAL(check0_after, true);\n\n  bool check2_after = ref2b.isApprox(tc[2], 1e-5);\n  if (!check2_after) {\n    cout << \"tc2\" << endl;\n    cout << tc[2] << endl;\n    cout << \"tc2_ref\" << endl;\n    cout << ref2b << endl;\n  }\n\n  BOOST_CHECK_EQUAL(check2_after, true);\n\n  bool check4_after = ref4b.isApprox(tc[4], 1e-5);\n  if (!check4_after) {\n    cout << \"tc4\" << endl;\n    cout << tc[4] << endl;\n    cout << \"tc4_ref\" << endl;\n    cout << ref4b << endl;\n  }\n\n  BOOST_CHECK_EQUAL(check4_after, true);\n}\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "1229a3ae63a91f5f3669cb18d1fb82e241f76112", "size": 3702, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/tests/test_threecenter_gwbse.cc", "max_stars_repo_name": "fossabot/xtp", "max_stars_repo_head_hexsha": "e82cc53f23e213d09da15da80ada6e32ac031a07", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/tests/test_threecenter_gwbse.cc", "max_issues_repo_name": "fossabot/xtp", "max_issues_repo_head_hexsha": "e82cc53f23e213d09da15da80ada6e32ac031a07", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tests/test_threecenter_gwbse.cc", "max_forks_repo_name": "fossabot/xtp", "max_forks_repo_head_hexsha": "e82cc53f23e213d09da15da80ada6e32ac031a07", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.1496062992, "max_line_length": 78, "alphanum_fraction": 0.6763911399, "num_tokens": 1130, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317473, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.4615755063975711}}
{"text": "/*\n* Copyright (c) by CryptoLab inc.\n* This program is licensed under a\n* Creative Commons Attribution-NonCommercial 3.0 Unported License.\n* You should have received a copy of the license along with this\n* work.  If not, see <http://creativecommons.org/licenses/by-nc/3.0/>.\n*/\n#include \"TestScheme.h\"\n\n#include <NTL/BasicThreadPool.h>\n#include <NTL/ZZ.h>\n\n#include \"Ciphertext.h\"\n#include \"EvaluatorUtils.h\"\n#include \"Ring.h\"\n#include \"Scheme.h\"\n#include \"SchemeAlgo.h\"\n#include \"SecretKey.h\"\n#include \"StringUtils.h\"\n#include \"TimeUtils.h\"\n#include \"SerializationUtils.h\"\n\nusing namespace std;\nusing namespace NTL;\n\n\n//----------------------------------------------------------------------------------\n//   STANDARD TESTS\n//----------------------------------------------------------------------------------\n\n\nvoid TestScheme::testEncrypt(long logq, long logp, long logn) {\n\tcout << \"!!! START TEST ENCRYPT !!!\" << endl;\n\tsrand(time(NULL));\n\tSetNumThreads(8);\n\tTimeUtils timeutils;\n\tRing ring;\n\tSecretKey secretKey(ring);\n\tScheme scheme(secretKey, ring);\n\n\tlong n = (1 << logn);\n\tcomplex<double>* mvec = EvaluatorUtils::randomComplexArray(n);\n\tCiphertext cipher;\n\n\ttimeutils.start(\"Encrypt\");\n\tscheme.encrypt(cipher, mvec, n, logp, logq);\n\ttimeutils.stop(\"Encrypt\");\n\n\ttimeutils.start(\"Decrypt\");\n\tcomplex<double>* dvec = scheme.decrypt(secretKey, cipher);\n\ttimeutils.stop(\"Decrypt\");\n\n\tStringUtils::compare(mvec, dvec, n, \"val\");\n\n\tcout << \"!!! END TEST ENCRYPT !!!\" << endl;\n}\n\nvoid TestScheme::testEncryptSingle(long logq, long logp) {\n\tcout << \"!!! START TEST ENCRYPT SINGLE !!!\" << endl;\n\tsrand(time(NULL));\n\tSetNumThreads(8);\n\tTimeUtils timeutils;\n\tRing ring;\n\tSecretKey secretKey(ring);\n\tScheme scheme(secretKey, ring);\n\n\tcomplex<double> mval = EvaluatorUtils::randomComplex();\n\tCiphertext cipher;\n\n\ttimeutils.start(\"Encrypt Single\");\n\tscheme.encryptSingle(cipher, mval, logp, logq);\n\ttimeutils.stop(\"Encrypt Single\");\n\n\tcomplex<double> dval = scheme.decryptSingle(secretKey, cipher);\n\n\tStringUtils::compare(mval, dval, \"val\");\n\n\tcout << \"!!! END TEST ENCRYPT SINGLE !!!\" << endl;\n}\n\nvoid TestScheme::testAdd(long logq, long logp, long logn) {\n\tcout << \"!!! START TEST ADD !!!\" << endl;\n\n\tsrand(time(NULL));\n\tSetNumThreads(8);\n\tTimeUtils timeutils;\n\tRing ring;\n\tSecretKey secretKey(ring);\n\tScheme scheme(secretKey, ring);\n\n\tlong n = (1 << logn);\n\tcomplex<double>* mvec1 = EvaluatorUtils::randomComplexArray(n);\n\tcomplex<double>* mvec2 = EvaluatorUtils::randomComplexArray(n);\n\tcomplex<double>* madd = new complex<double>[n];\n\n\tfor(long i = 0; i < n; i++) {\n\t\tmadd[i] = mvec1[i] + mvec2[i];\n\t}\n\n\tCiphertext cipher1, cipher2;\n\tscheme.encrypt(cipher1, mvec1, n, logp, logq);\n\tscheme.encrypt(cipher2, mvec2, n, logp, logq);\n\n\ttimeutils.start(\"Addition\");\n\tscheme.addAndEqual(cipher1, cipher2);\n\ttimeutils.stop(\"Addition\");\n\n\tcomplex<double>* dadd = scheme.decrypt(secretKey, cipher1);\n\n\tStringUtils::compare(madd, dadd, n, \"add\");\n\n\tcout << \"!!! END TEST ADD !!!\" << endl;\n}\n\nvoid TestScheme::testMult(long logq, long logp, long logn) {\n\tcout << \"!!! START TEST MULT !!!\" << endl;\n\n\tsrand(time(NULL));\n\tSetNumThreads(8);\n\tTimeUtils timeutils;\n\tRing ring;\n\tSecretKey secretKey(ring);\n\tScheme scheme(secretKey, ring);\n\n\tlong n = (1 << logn);\n\tcomplex<double>* mvec1 = EvaluatorUtils::randomComplexArray(n);\n\tcomplex<double>* mvec2 = EvaluatorUtils::randomComplexArray(n);\n\tcomplex<double>* mmult = new complex<double>[n];\n\tfor(long i = 0; i < n; i++) {\n\t\tmmult[i] = mvec1[i] * mvec2[i];\n\t}\n\n\tCiphertext cipher1, cipher2;\n\tscheme.encrypt(cipher1, mvec1, n, logp, logq);\n\tscheme.encrypt(cipher2, mvec2, n, logp, logq);\n\n\ttimeutils.start(\"Multiplication\");\n\tscheme.multAndEqual(cipher1, cipher2);\n\ttimeutils.stop(\"Multiplication\");\n\n\tcomplex<double>* dmult = scheme.decrypt(secretKey, cipher1);\n\n\tStringUtils::compare(mmult, dmult, n, \"mult\");\n\n\tcout << \"!!! END TEST MULT !!!\" << endl;\n}\n\nvoid TestScheme::testiMult(long logq, long logp, long logn) {\n\tcout << \"!!! START TEST i MULTIPLICATION !!!\" << endl;\n\n\tsrand(time(NULL));\n\tSetNumThreads(8);\n\tTimeUtils timeutils;\n\tRing ring;\n\tSecretKey secretKey(ring);\n\tScheme scheme(secretKey, ring);\n\n\tlong n = (1 << logn);\n\n\tcomplex<double>* mvec = EvaluatorUtils::randomComplexArray(n);\n\tcomplex<double>* imvec = new complex<double>[n];\n\tfor (long i = 0; i < n; ++i) {\n\t\timvec[i].real(-mvec[i].imag());\n\t\timvec[i].imag(mvec[i].real());\n\t}\n\n\tCiphertext cipher;\n\tscheme.encrypt(cipher, mvec, n, logp, logq);\n\n\ttimeutils.start(\"Multiplication by i\");\n\tscheme.imultAndEqual(cipher);\n\ttimeutils.stop(\"Multiplication by i\");\n\n\tcomplex<double>* idvec = scheme.decrypt(secretKey, cipher);\n\n\tStringUtils::compare(imvec, idvec, n, \"imult\");\n\n\tcout << \"!!! END TEST i MULTIPLICATION !!!\" << endl;\n}\n\n\n//----------------------------------------------------------------------------------\n//   ROTATE & CONJUGATE\n//----------------------------------------------------------------------------------\n\n\nvoid TestScheme::testRotateFast(long logq, long logp, long logn, long logr) {\n\tcout << \"!!! START TEST ROTATE FAST !!!\" << endl;\n\n\tsrand(time(NULL));\n\tSetNumThreads(8);\n\tTimeUtils timeutils;\n\tRing ring;\n\tSecretKey secretKey(ring);\n\tScheme scheme(secretKey, ring);\n\n\tlong n = (1 << logn);\n\tlong r = (1 << logr);\n\tscheme.addLeftRotKey(secretKey, r);\n\tcomplex<double>* mvec = EvaluatorUtils::randomComplexArray(n);\n\tCiphertext cipher;\n\tscheme.encrypt(cipher, mvec, n, logp, logq);\n\n\ttimeutils.start(\"Left Rotate Fast\");\n\tscheme.leftRotateFastAndEqual(cipher, r);\n\ttimeutils.stop(\"Left Rotate Fast\");\n\n\tcomplex<double>* dvec = scheme.decrypt(secretKey, cipher);\n\n\tEvaluatorUtils::leftRotateAndEqual(mvec, n, r);\n\tStringUtils::compare(mvec, dvec, n, \"rot\");\n\n\tcout << \"!!! END TEST ROTATE BY POWER OF 2 BATCH !!!\" << endl;\n}\n\nvoid TestScheme::testConjugate(long logq, long logp, long logn) {\n\tcout << \"!!! START TEST CONJUGATE !!!\" << endl;\n\n\tsrand(time(NULL));\n\tSetNumThreads(8);\n\tTimeUtils timeutils;\n\tRing ring;\n\tSecretKey secretKey(ring);\n\tScheme scheme(secretKey, ring);\n\n\tscheme.addConjKey(secretKey);\n\n\tlong n = (1 << logn);\n\n\tcomplex<double>* mvec = EvaluatorUtils::randomComplexArray(n);\n\tcomplex<double>* mvecconj = new complex<double>[n];\n\tfor (long i = 0; i < n; ++i) {\n\t\tmvecconj[i] = conj(mvec[i]);\n\t}\n\n\tCiphertext cipher;\n\tscheme.encrypt(cipher, mvec, n, logp, logq);\n\n\ttimeutils.start(\"Conjugate\");\n\tscheme.conjugateAndEqual(cipher);\n\ttimeutils.stop(\"Conjugate\");\n\n\tcomplex<double>* dvecconj = scheme.decrypt(secretKey, cipher);\n\tStringUtils::compare(mvecconj, dvecconj, n, \"conj\");\n\n\tcout << \"!!! END TEST CONJUGATE !!!\" << endl;\n}\n\n\n//----------------------------------------------------------------------------------\n//   POWER & PRODUCT TESTS\n//----------------------------------------------------------------------------------\n\n\nvoid TestScheme::testPowerOf2(long logq, long logp, long logn, long logdeg) {\n\tcout << \"!!! START TEST POWER OF 2 !!!\" << endl;\n\n\tsrand(time(NULL));\n\tSetNumThreads(8);\n\tTimeUtils timeutils;\n\tRing ring;\n\tSecretKey secretKey(ring);\n\tScheme scheme(secretKey, ring);\n\tSchemeAlgo algo(scheme);\n\n\tlong n = 1 << logn;\n\tlong degree = 1 << logdeg;\n\tcomplex<double>* mvec = new complex<double>[n];\n\tcomplex<double>* mpow = new complex<double>[n];\n\tfor (long i = 0; i < n; ++i) {\n\t\tmvec[i] = EvaluatorUtils::randomCircle();\n\t\tmpow[i] = pow(mvec[i], degree);\n\t}\n\n\tCiphertext cipher, cpow;\n\tscheme.encrypt(cipher, mvec, n, logp, logq);\n\n\ttimeutils.start(\"Power of 2\");\n\talgo.powerOf2(cpow, cipher, logp, logdeg);\n\ttimeutils.stop(\"Power of 2\");\n\n\tcomplex<double>* dpow = scheme.decrypt(secretKey, cpow);\n\tStringUtils::compare(mpow, dpow, n, \"pow2\");\n\n\tcout << \"!!! END TEST POWER OF 2 !!!\" << endl;\n}\n\n//-----------------------------------------\n\nvoid TestScheme::testPower(long logq, long logp, long logn, long degree) {\n\tcout << \"!!! START TEST POWER !!!\" << endl;\n\n\tsrand(time(NULL));\n\tSetNumThreads(8);\n\tTimeUtils timeutils;\n\tRing ring;\n\tSecretKey secretKey(ring);\n\tScheme scheme(secretKey, ring);\n\tSchemeAlgo algo(scheme);\n\n\tlong n = 1 << logn;\n\tcomplex<double>* mvec = EvaluatorUtils::randomCircleArray(n);\n\tcomplex<double>* mpow = new complex<double>[n];\n\tfor (long i = 0; i < n; ++i) {\n\t\tmpow[i] = pow(mvec[i], degree);\n\t}\n\n\tCiphertext cipher, cpow;\n\tscheme.encrypt(cipher, mvec, n, logp, logq);\n\n\ttimeutils.start(\"Power\");\n\talgo.power(cpow, cipher, logp, degree);\n\ttimeutils.stop(\"Power\");\n\n\tcomplex<double>* dpow = scheme.decrypt(secretKey, cpow);\n\tStringUtils::compare(mpow, dpow, n, \"pow\");\n\n\tcout << \"!!! END TEST POWER !!!\" << endl;\n}\n\n\n//----------------------------------------------------------------------------------\n//   FUNCTION TESTS\n//----------------------------------------------------------------------------------\n\n\nvoid TestScheme::testInverse(long logq, long logp, long logn, long steps) {\n\tcout << \"!!! START TEST INVERSE !!!\" << endl;\n\n\tsrand(time(NULL));\n\tSetNumThreads(8);\n\tTimeUtils timeutils;\n\tRing ring;\n\tSecretKey secretKey(ring);\n\tScheme scheme(secretKey, ring);\n\tSchemeAlgo algo(scheme);\n\n\tlong n = 1 << logn;\n\tcomplex<double>* mvec = EvaluatorUtils::randomCircleArray(n, 0.1);\n\tcomplex<double>* minv = new complex<double>[n];\n\tfor (long i = 0; i < n; ++i) {\n\t\tminv[i] = 1. / mvec[i];\n\t}\n\n\tCiphertext cipher, cinv;\n\tscheme.encrypt(cipher, mvec, n, logp, logq);\n\n\ttimeutils.start(\"Inverse\");\n\talgo.inverse(cinv, cipher, logp, steps);\n\ttimeutils.stop(\"Inverse\");\n\n\tcomplex<double>* dinv = scheme.decrypt(secretKey, cinv);\n\tStringUtils::compare(minv, dinv, n, \"inv\");\n\n\tcout << \"!!! END TEST INVERSE !!!\" << endl;\n}\n\nvoid TestScheme::testLogarithm(long logq, long logp, long logn, long degree) {\n\tcout << \"!!! START TEST LOGARITHM !!!\" << endl;\n\n\tsrand(time(NULL));\n\tSetNumThreads(8);\n\tTimeUtils timeutils;\n\tRing ring;\n\tSecretKey secretKey(ring);\n\tScheme scheme(secretKey, ring);\n\tSchemeAlgo algo(scheme);\n\n\tlong n = 1 << logn;\n\tcomplex<double>* mvec = EvaluatorUtils::randomComplexArray(n, 0.1);\n\tcomplex<double>* mlog = new complex<double>[n];\n\tfor (long i = 0; i < n; ++i) {\n\t\tmlog[i] = log(mvec[i] + 1.);\n\t}\n\n\tCiphertext cipher, clog;\n\tscheme.encrypt(cipher, mvec, n, logp, logq);\n\n\ttimeutils.start(LOGARITHM);\n\talgo.function(clog, cipher, LOGARITHM, logp, degree);\n\ttimeutils.stop(LOGARITHM);\n\n\tcomplex<double>* dlog = scheme.decrypt(secretKey, clog);\n\tStringUtils::compare(mlog, dlog, n, LOGARITHM);\n\n\tcout << \"!!! END TEST LOGARITHM !!!\" << endl;\n}\n\nvoid TestScheme::testExponent(long logq, long logp, long logn, long degree) {\n\tcout << \"!!! START TEST EXPONENT !!!\" << endl;\n\n\tsrand(time(NULL));\n\tSetNumThreads(8);\n\tTimeUtils timeutils;\n\tRing ring;\n\tSecretKey secretKey(ring);\n\tScheme scheme(secretKey, ring);\n\tSchemeAlgo algo(scheme);\n\n\tlong n = 1 << logn;\n\tcomplex<double>* mvec = EvaluatorUtils::randomComplexArray(n);\n\tcomplex<double>* mexp = new complex<double>[n];\n\tfor (long i = 0; i < n; ++i) {\n\t\tmexp[i] = exp(mvec[i]);\n\t}\n\n\tCiphertext cipher, cexp;\n\tscheme.encrypt(cipher, mvec, n, logp, logq);\n\n\ttimeutils.start(EXPONENT);\n\talgo.function(cexp, cipher, EXPONENT, logp, degree);\n\ttimeutils.stop(EXPONENT);\n\n\tcomplex<double>* dexp = scheme.decrypt(secretKey, cexp);\n\tStringUtils::compare(mexp, dexp, n, EXPONENT);\n\n\tcout << \"!!! END TEST EXPONENT !!!\" << endl;\n}\n\nvoid TestScheme::testExponentLazy(long logq, long logp, long logn, long degree) {\n\tcout << \"!!! START TEST EXPONENT LAZY !!!\" << endl;\n\n\tsrand(time(NULL));\n\tSetNumThreads(8);\n\tTimeUtils timeutils;\n\tRing ring;\n\tSecretKey secretKey(ring);\n\tScheme scheme(secretKey, ring);\n\tSchemeAlgo algo(scheme);\n\n\tlong n = 1 << logn;\n\tcomplex<double>* mvec = EvaluatorUtils::randomComplexArray(n);\n\tcomplex<double>* mexp = new complex<double>[n];\n\tfor (long i = 0; i < n; ++i) {\n\t\tmexp[i] = exp(mvec[i]);\n\t}\n\tCiphertext cipher, cexp;\n\tscheme.encrypt(cipher, mvec, n, logp, logQ);\n\n\ttimeutils.start(EXPONENT + \" lazy\");\n\talgo.functionLazy(cexp, cipher, EXPONENT, logp, degree);\n\ttimeutils.stop(EXPONENT + \" lazy\");\n\n\tcomplex<double>* dexp = scheme.decrypt(secretKey, cexp);\n\tStringUtils::compare(mexp, dexp, n, EXPONENT);\n\n\tcout << \"!!! END TEST EXPONENT LAZY !!!\" << endl;\n}\n\n//-----------------------------------------\n\nvoid TestScheme::testSigmoid(long logq, long logp, long logn, long degree) {\n\tcout << \"!!! START TEST SIGMOID !!!\" << endl;\n\n\tsrand(time(NULL));\n\tSetNumThreads(8);\n\tTimeUtils timeutils;\n\tRing ring;\n\tSecretKey secretKey(ring);\n\tScheme scheme(secretKey, ring);\n\tSchemeAlgo algo(scheme);\n\n\tlong n = 1 << logn;\n\n\tcomplex<double>* mvec = EvaluatorUtils::randomComplexArray(n);\n\tcomplex<double>* msig = new complex<double>[n];\n\tfor (long i = 0; i < n; ++i) {\n\t\tmsig[i] = exp(mvec[i]) / (1. + exp(mvec[i]));\n\t}\n\n\tCiphertext cipher, csig;\n\tscheme.encrypt(cipher, mvec, n, logp, logq);\n\n\ttimeutils.start(SIGMOID);\n\talgo.function(csig, cipher, SIGMOID, logp, degree);\n\ttimeutils.stop(SIGMOID);\n\n\tcomplex<double>* dsig = scheme.decrypt(secretKey, csig);\n\tStringUtils::compare(msig, dsig, n, SIGMOID);\n\n\tcout << \"!!! END TEST SIGMOID !!!\" << endl;\n}\n\nvoid TestScheme::testSigmoidLazy(long logq, long logp, long logn, long degree) {\n\tcout << \"!!! START TEST SIGMOID LAZY !!!\" << endl;\n\n\tsrand(time(NULL));\n//\tSetNumThreads(8);\n\tTimeUtils timeutils;\n\tRing ring;\n\tSecretKey secretKey(ring);\n\tScheme scheme(secretKey, ring);\n\tSchemeAlgo algo(scheme);\n\n\tlong n = 1 << logn;\n\tcomplex<double>* mvec = EvaluatorUtils::randomComplexArray(n);\n\tcomplex<double>* msig = new complex<double>[n];\n\tfor (long i = 0; i < n; ++i) {\n\t\tmsig[i] = exp(mvec[i]) / (1. + exp(mvec[i]));\n\t}\n\n\tCiphertext cipher, csig;\n\tscheme.encrypt(cipher, mvec, n, logp, logq);\n\n\ttimeutils.start(SIGMOID + \" lazy\");\n\talgo.functionLazy(csig, cipher, SIGMOID, logp, degree);\n\ttimeutils.stop(SIGMOID + \" lazy\");\n\n\tcomplex<double>* dsig = scheme.decrypt(secretKey, csig);\n\tStringUtils::compare(msig, dsig, n, SIGMOID);\n\n\tcout << \"!!! END TEST SIGMOID LAZY !!!\" << endl;\n}\n\n\nvoid TestScheme::testWriteAndRead(long logq, long logp, long logSlots) {\n\tcout << \"!!! START TEST WRITE AND READ !!!\" << endl;\n\n\tcout << \"!!! END TEST WRITE AND READ !!!\" << endl;\n}\n\n\nvoid TestScheme::testBootstrap(long logq, long logp, long logSlots, long logT) {\n\tcout << \"!!! START TEST BOOTSTRAP !!!\" << endl;\n\n\tsrand(time(NULL));\n\tSetNumThreads(8);\n\tTimeUtils timeutils;\n\tRing ring;\n\tSecretKey secretKey(ring);\n\tScheme scheme(secretKey, ring);\n\n\ttimeutils.start(\"Key generating\");\n\tscheme.addBootKey(secretKey, logSlots, logq + 4);\n\ttimeutils.stop(\"Key generated\");\n\n\tlong slots = (1 << logSlots);\n\tcomplex<double>* mvec = EvaluatorUtils::randomComplexArray(slots);\n\n\tCiphertext cipher;\n\tscheme.encrypt(cipher, mvec, slots, logp, logq);\n\n\tcout << \"cipher logq before: \" << cipher.logq << endl;\n\n\tscheme.modDownToAndEqual(cipher, logq);\n\tscheme.normalizeAndEqual(cipher);\n\tcipher.logq = logQ;\n\tcipher.logp = logq + 4;\n\n\tCiphertext rot;\n\ttimeutils.start(\"SubSum\");\n\tfor (long i = logSlots; i < logNh; ++i) {\n\t\tscheme.leftRotateFast(rot, cipher, (1 << i));\n\t\tscheme.addAndEqual(cipher, rot);\n\t}\n\tscheme.divByPo2AndEqual(cipher, logNh);\n\ttimeutils.stop(\"SubSum\");\n\n\ttimeutils.start(\"CoeffToSlot\");\n\tscheme.coeffToSlotAndEqual(cipher);\n\ttimeutils.stop(\"CoeffToSlot\");\n\n\ttimeutils.start(\"EvalExp\");\n\tscheme.evalExpAndEqual(cipher, logT);\n\ttimeutils.stop(\"EvalExp\");\n\n\ttimeutils.start(\"SlotToCoeff\");\n\tscheme.slotToCoeffAndEqual(cipher);\n\ttimeutils.stop(\"SlotToCoeff\");\n\n\tcipher.logp = logp;\n\tcout << \"cipher logq after: \" << cipher.logq << endl;\n\n\tcomplex<double>* dvec = scheme.decrypt(secretKey, cipher);\n\n\tStringUtils::compare(mvec, dvec, slots, \"boot\");\n\n\tcout << \"!!! END TEST BOOTSRTAP !!!\" << endl;\n}\n\nvoid TestScheme::testBootstrapSingleReal(long logq, long logp, long logT) {\n\tcout << \"!!! START TEST BOOTSTRAP SINGLE REAL !!!\" << endl;\n\n\tsrand(time(NULL));\n\tSetNumThreads(8);\n\tTimeUtils timeutils;\n\tRing ring;\n\tSecretKey secretKey(ring);\n\tScheme scheme(secretKey, ring);\n\n\ttimeutils.start(\"Key generating\");\n\tscheme.addBootKey(secretKey, 0, logq + 4);\n\ttimeutils.stop(\"Key generated\");\n\n\tdouble mval = EvaluatorUtils::randomReal();\n\n\tCiphertext cipher;\n\tscheme.encryptSingle(cipher, mval, logp, logq);\n\n\tcout << \"cipher logq before: \" << cipher.logq << endl;\n\tscheme.modDownToAndEqual(cipher, logq);\n\tscheme.normalizeAndEqual(cipher);\n\tcipher.logq = logQ;\n\n\tCiphertext rot, cconj;\n\ttimeutils.start(\"SubSum\");\n\tfor (long i = 0; i < logNh; ++i) {\n\t\tscheme.leftRotateFast(rot, cipher, 1 << i);\n\t\tscheme.addAndEqual(cipher, rot);\n\t}\n\tscheme.conjugate(cconj, cipher);\n\tscheme.addAndEqual(cipher, cconj);\n\tscheme.divByPo2AndEqual(cipher, logN);\n\ttimeutils.stop(\"SubSum\");\n\n\ttimeutils.start(\"EvalExp\");\n\tscheme.evalExpAndEqual(cipher, logT);\n\ttimeutils.stop(\"EvalExp\");\n\n\tcout << \"cipher logq after: \" << cipher.logq << endl;\n\n\tcipher.logp = logp;\n\tcomplex<double> dval = scheme.decryptSingle(secretKey, cipher);\n\n\tStringUtils::compare(mval, dval.real(), \"boot\");\n\n\tcout << \"!!! END TEST BOOTSRTAP SINGLE REAL !!!\" << endl;\n}\n", "meta": {"hexsha": "17a89cabb9bd3fae259959366a2f8199fb296c15", "size": 16828, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "HEAAN/src/TestScheme.cpp", "max_stars_repo_name": "Huelse/HEAAN-Python", "max_stars_repo_head_hexsha": "034ee757a7b7949d96b27d3228819dd9be6579ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2020-01-04T13:02:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T08:37:58.000Z", "max_issues_repo_path": "HEAAN/src/TestScheme.cpp", "max_issues_repo_name": "Huelse/PYHEAAN", "max_issues_repo_head_hexsha": "034ee757a7b7949d96b27d3228819dd9be6579ae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-07-03T09:43:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-02T08:30:56.000Z", "max_forks_repo_path": "HEAAN/src/TestScheme.cpp", "max_forks_repo_name": "Huelse/PYHEAAN", "max_forks_repo_head_hexsha": "034ee757a7b7949d96b27d3228819dd9be6579ae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-01-04T13:02:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-14T00:04:53.000Z", "avg_line_length": 26.7535771065, "max_line_length": 84, "alphanum_fraction": 0.6525433801, "num_tokens": 4730, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581741774411, "lm_q2_score": 0.6261241842048092, "lm_q1q2_score": 0.46155256043675696}}
{"text": "#ifndef HAMILTONIANS_KITAEVHEX_HPP\n#define HAMILTONIANS_KITAEVHEX_HPP\n#include <Eigen/Eigen>\n#include <nlohmann/json.hpp>\n\nclass KitaevHex\n{\nprivate:\n\tconst int n_;\n\tconst int m_;\n\tconst double Jx_;\n\tconst double Jy_;\n\tconst double Jz_;\n\n\tconst double h_;\n\npublic:\n\n\tKitaevHex(int n, int m, double J, double h = 0.0)\n\t\t: n_(n), m_(m), Jx_(J), Jy_(J), Jz_(J), h_(h)\n\t{\n\t\tassert(n % 2 == 0);\n\t\tassert(m % 2 == 0);\n\t}\n\n\tKitaevHex(int n, int m, double Jx, double Jy, double Jz)\n\t\t: n_(n), m_(m), Jx_(Jx), Jy_(Jy), Jz_(Jz), h_{0.0}\n\t{\n\t\tassert(n % 2 == 0);\n\t\tassert(m % 2 == 0);\n\t}\n\n\tint blackIdx(int row, int col) const\n\t{\n\t\tconst int k = n_/2;\n\t\trow = ((row%m_) + m_) % m_;\n\t\tcol = ((col%k) + k) % k;\n\t\treturn row*n_ + col;\n\t}\n\tint whiteIdx(int row, int col) const\n\t{\n\t\tconst int k = n_/2;\n\t\trow = ((row%m_) + m_) % m_;\n\t\tcol = ((col%k) + k) % k;\n\t\treturn row*n_ + col + (n_/2);\n\t}\n\n\tstd::vector<std::pair<int,int> > xLinks() const\n\t{\n\t\tstd::vector<std::pair<int,int> > res;\n\t\tconst int k = n_/2;\n\t\tfor(int row = 0; row < m_; row += 2)\n\t\t{\n\t\t\tfor(int i = 0; i < k; i++)\n\t\t\t{\n\t\t\t\tres.emplace_back(blackIdx(row, i), whiteIdx(row, i-1));\n\t\t\t}\n\t\t}\n\t\tfor(int row = 1; row < m_; row += 2)\n\t\t{\n\t\t\tfor(int i = 0; i < k; i++)\n\t\t\t{\n\t\t\t\tres.emplace_back(blackIdx(row,i), whiteIdx(row,i));\n\t\t\t}\n\t\t}\n\t\treturn res;\n\t}\n\n\tstd::vector<std::pair<int,int> > yLinks() const\n\t{\n\t\tstd::vector<std::pair<int,int> > res;\n\t\tconst int k = n_/2;\n\t\tfor(int row = 0; row < m_; row += 2)\n\t\t{\n\t\t\tfor(int i = 0; i < k; i++)\n\t\t\t{\n\t\t\t\tres.emplace_back(blackIdx(row, i), whiteIdx(row,i));\n\t\t\t}\n\t\t}\n\t\tfor(int row = 1; row < m_; row += 2)\n\t\t{\n\t\t\tfor(int i = 0; i < k; i++)\n\t\t\t{\n\t\t\t\tres.emplace_back(blackIdx(row, i), whiteIdx(row,i+1));\n\t\t\t}\n\t\t}\n\n\t\treturn res;\n\t}\n\n\tstd::vector<std::pair<int,int> > zLinks() const\n\t{\n\t\tstd::vector<std::pair<int,int> > res;\n\t\tconst int k = n_/2;\n\t\tfor(int row = 0; row < m_; row++)\n\t\t{\n\t\t\tfor(int i = 0; i < k; i++)\n\t\t\t{\n\t\t\t\tres.emplace_back(whiteIdx(row, i), blackIdx(row+1,i));\n\t\t\t}\n\t\t}\n\t\treturn res;\n\t}\n\n\tnlohmann::json params() const\n\t{\n\t\treturn nlohmann::json\n\t\t{\n\t\t\t{\"name\", \"KITAEVHEX\"},\n\t\t\t{\"Jx\", Jx_},\n\t\t\t{\"Jy\", Jy_},\n\t\t\t{\"Jz\", Jz_},\n\t\t\t{\"h\", h_},\n\t\t\t{\"n\", n_},\n\t\t\t{\"m\", m_},\n\t\t};\n\t}\n\t\n\ttemplate<class State>\n\ttypename State::Scalar operator()(const State& smp) const\n\t{\n\t\ttypename State::Scalar s = 0.0;\n\t\tconstexpr std::complex<double> I(0.,1.);\n\n\t\tfor(int i = 0; i < n_*m_; ++i)\n\t\t{\n\t\t\t//s += h_*smp.sigmaAt(i); //hz\n\t\t\ts += h_*smp.ratio(i); //hx\n\t\t}\n\n\t\tfor(auto &xx: xLinks())\n\t\t{\n\t\t\ts += Jx_*smp.ratio(xx.first, xx.second); //xx\n\t\t}\n\t\tfor(auto &yy: yLinks())\n\t\t{\n\t\t\tint zzval = smp.sigmaAt(yy.first)*smp.sigmaAt(yy.second);\n\t\t\ts += -Jy_*zzval*smp.ratio(yy.first, yy.second); //yy\n\t\t}\n\t\tfor(auto &zz: zLinks())\n\t\t{\n\t\t\tint zzval = smp.sigmaAt(zz.first)*smp.sigmaAt(zz.second);\n\t\t\ts += Jz_*zzval; //yy\n\t\t}\n\t\treturn s;\n\t}\n\n\tstd::map<uint32_t, double> operator()(uint32_t col) const\n\t{\n\t\tstd::map<uint32_t, double> m;\n\n\t\tfor(int i = 0; i < n_*m_; ++i)\n\t\t{\n\t\t\tdouble k = (1-2*int((col >> i) & 1));\n\t\t\t//m[col] += h_*k; //hz\n\t\t\tm[col ^ (1<<i)] += h_; //hx\n\t\t}\n\n\t\tfor(auto &xx: xLinks())\n\t\t{\n\t\t\tint t = (1 << xx.first) | (1 << xx.second);\n\t\t\tm[col ^ t] += Jx_; //xx\n\t\t}\n\t\tfor(auto &yy: yLinks())\n\t\t{\n\t\t\tint zzval = (1-2*int((col >> yy.first) & 1))*(1-2*int((col >> yy.second) & 1));\n\t\t\tint t = (1 << yy.first) | (1 << yy.second);\n\t\t\tm[col ^ t] += -Jy_*zzval; //yy\n\t\t}\n\t\tfor(auto &zz: zLinks())\n\t\t{\n\t\t\tint zzval = (1-2*int((col >> zz.first) & 1))*(1-2*int((col >> zz.second) & 1));\n\t\t\tm[col] += Jz_*zzval; //zz\n\t\t}\n\n\t\treturn m;\n\t}\n};\n#endif//HAMILTONIANS_KITAEVHEX_HPP\n", "meta": {"hexsha": "4dd0bf525bfc7b172ec8bad0ab9a8343d7770b23", "size": 3567, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Yannq/Hamiltonians/KitaevHex.hpp", "max_stars_repo_name": "cecri/yannq", "max_stars_repo_head_hexsha": "b78c1f86a255059f06b34dd5e538449e7261d0ee", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Yannq/Hamiltonians/KitaevHex.hpp", "max_issues_repo_name": "cecri/yannq", "max_issues_repo_head_hexsha": "b78c1f86a255059f06b34dd5e538449e7261d0ee", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Yannq/Hamiltonians/KitaevHex.hpp", "max_forks_repo_name": "cecri/yannq", "max_forks_repo_head_hexsha": "b78c1f86a255059f06b34dd5e538449e7261d0ee", "max_forks_repo_licenses": ["BSD-3-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.8166666667, "max_line_length": 82, "alphanum_fraction": 0.5343425848, "num_tokens": 1451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581741774411, "lm_q2_score": 0.6261241842048092, "lm_q1q2_score": 0.46155256043675696}}
{"text": "#ifndef TURBOTRACK_HPP\n#define TURBOTRACK_HPP\n\n#if defined TURBOTRACK_USE_EIGEN\n\t#include <Eigen/Dense>\n\n\tnamespace turbotrack {\n\t\tusing vec2 = Eigen::Vector2f;\n\t\tusing vec3 = Eigen::Vector3f;\n\t\tusing quat = Eigen::Quaternionf;\n\t}\n#elif defined TURBOTRACK_USE_GLM\n\t#define GLM_ENABLE_EXPERIMENTAL\n\t#include <glm/ext.hpp>\n\t#include <glm/glm.hpp>\n\t#include <glm/gtc/quaternion.hpp>\n\n\tnamespace turbotrack {\n\t\tusing vec2 = glm::vec2;\n\t\tusing vec3 = glm::vec3;\n\t\tusing quat = glm::quat;\n\t}\n#endif\n\nnamespace turbotrack {\n\nenum class TrackballType {\n\t// chen_et_al, not implemented yet\n\tshoemake,\n\tholroyd\n};\n\n// See equation 33 in Henriksen et al.\nvec3 shoemake_projection(const vec2 &mouse, float radius);\n\n// See equation 46 in Henriksen et al.\nvec3 holroyd_projection(const vec2 &mouse, float radius);\n\nquat mouse_move(const vec2 &old_pos,\n                const vec2 &new_pos, float radius = 1.0,\n                TrackballType type = TrackballType::holroyd);\n\n} // namespace turbotrack\n\n#endif // TURBOTRACK_HPP\n", "meta": {"hexsha": "56b19f39f93192bfa77d7a56752f7b07c957aa8e", "size": 1011, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/turbotrack.hpp", "max_stars_repo_name": "Heerdam/turbotrack", "max_stars_repo_head_hexsha": "d960d9c05f966bf61093015d37a18bd290b42bc7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-08-29T01:10:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-29T01:10:20.000Z", "max_issues_repo_path": "include/turbotrack.hpp", "max_issues_repo_name": "Heerdam/turbotrack", "max_issues_repo_head_hexsha": "d960d9c05f966bf61093015d37a18bd290b42bc7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-07-23T02:42:26.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-21T22:36:51.000Z", "max_forks_repo_path": "include/turbotrack.hpp", "max_forks_repo_name": "Heerdam/turbotrack", "max_forks_repo_head_hexsha": "d960d9c05f966bf61093015d37a18bd290b42bc7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-07-22T23:43:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-20T08:43:42.000Z", "avg_line_length": 21.9782608696, "max_line_length": 61, "alphanum_fraction": 0.7220573689, "num_tokens": 297, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581741774411, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.46155255529396866}}
{"text": "//          Copyright Carl Philipp Reh 2009 - 2016.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n\n#include <fcppt/strong_typedef.hpp>\n#include <fcppt/text.hpp>\n#include <fcppt/io/cout.hpp>\n#include <fcppt/random/variate.hpp>\n#include <fcppt/random/distribution/basic.hpp>\n#include <fcppt/random/distribution/parameters/uniform_int.hpp>\n#include <fcppt/random/generator/minstd_rand.hpp>\n#include <fcppt/random/generator/seed_from_chrono.hpp>\n#include <fcppt/type_iso/boost_units.hpp>\n#include <fcppt/type_iso/strong_typedef.hpp>\n#include <fcppt/config/external_begin.hpp>\n#include <boost/units/quantity.hpp>\n#include <boost/units/systems/si/length.hpp>\n#include <fcppt/config/external_end.hpp>\n\n\nint\nmain()\n{\n//![random_complex_distribution]\n\ttypedef\n\tboost::units::quantity<\n\t\tboost::units::si::length,\n\t\tint\n\t> meter;\n\n\tFCPPT_MAKE_STRONG_TYPEDEF(\n\t\tmeter,\n\t\tradius\n\t);\n\n\ttypedef\n\tfcppt::random::distribution::basic<\n\t\tfcppt::random::distribution::parameters::uniform_int<\n\t\t\tradius\n\t\t>\n\t>\n\tdistribution;\n//![random_complex_distribution]\n\n\ttypedef\n\tfcppt::random::generator::minstd_rand\n\tgenerator_type;\n\n\tgenerator_type generator(\n\t\tfcppt::random::generator::seed_from_chrono<\n\t\t\tgenerator_type::seed\n\t\t>()\n\t);\n\n\ttypedef fcppt::random::variate<\n\t\tgenerator_type,\n\t\tdistribution\n\t> variate;\n\n//![random_complex_variate]\n\tvariate rng(\n\t\tgenerator,\n\t\tdistribution(\n\t\t\tdistribution::param_type::min(\n\t\t\t\tradius(\n\t\t\t\t\t0 * boost::units::si::meter\n\t\t\t\t)\n\t\t\t),\n\t\t\tdistribution::param_type::max(\n\t\t\t\tradius(\n\t\t\t\t\t10 * boost::units::si::meter\n\t\t\t\t)\n\t\t\t)\n\t\t)\n\t);\n//![random_complex_variate]\n\n//![random_complex_output]\n\tfor(\n\t\tunsigned i = 0;\n\t\ti < 10;\n\t\t++i\n\t)\n\t\tfcppt::io::cout()\n\t\t\t<< rng().get().value()\n\t\t\t<< FCPPT_TEXT(' ');\n//![random_complex_output]\n\n\tfcppt::io::cout()\n\t\t<< FCPPT_TEXT('\\n');\n\n\ttypedef\n\tfcppt::random::distribution::basic<\n\t\tfcppt::random::distribution::parameters::uniform_int<\n\t\t\tmeter\n\t\t>\n\t>\n\tmeter_distribution;\n\n\ttypedef fcppt::random::variate<\n\t\tgenerator_type,\n\t\tmeter_distribution\n\t> meter_variate;\n\n\tmeter_variate meter_rng(\n\t\tgenerator,\n\t\tmeter_distribution(\n\t\t\tmeter_distribution::param_type::min(\n\t\t\t\t0 * boost::units::si::meter\n\t\t\t),\n\t\t\tmeter_distribution::param_type::max(\n\t\t\t\t10 * boost::units::si::meter\n\t\t\t)\n\t\t)\n\t);\n\n\tfor(\n\t\tunsigned i = 0;\n\t\ti < 10;\n\t\t++i\n\t)\n\t\tfcppt::io::cout()\n\t\t\t<< meter_rng().value()\n\t\t\t<< FCPPT_TEXT(' ');\n\n\tfcppt::io::cout()\n\t\t<< FCPPT_TEXT('\\n');\n}\n", "meta": {"hexsha": "fa67f86dc33f3a63e58abfcf6df8784f5a5c3aaa", "size": 2530, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/random/complex.cpp", "max_stars_repo_name": "vinzenz/fcppt", "max_stars_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "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/random/complex.cpp", "max_issues_repo_name": "vinzenz/fcppt", "max_issues_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "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/random/complex.cpp", "max_forks_repo_name": "vinzenz/fcppt", "max_forks_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "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": 19.3129770992, "max_line_length": 63, "alphanum_fraction": 0.6877470356, "num_tokens": 769, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.6261241842048092, "lm_q1q2_score": 0.46155255320580046}}
{"text": "static bool eigen_did_assert = false;\n#define eigen_assert(X) if(!eigen_did_assert && !(X)){ std::cout << \"### Assertion raised in \" << __FILE__ << \":\" << __LINE__ << \":\\n\" #X << \"\\n### The following would happen without assertions:\\n\"; eigen_did_assert = true;}\n\n#include <iostream>\n#include <Eigen/Eigen>\n\n#ifndef M_PI\n#define M_PI 3.1415926535897932384626433832795\n#endif\n\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n// intentionally remove indentation of snippet\n{\ntypedef Matrix<float,1,Dynamic> MatrixType;\ntypedef Map<MatrixType> MapType;\ntypedef Map<const MatrixType> MapTypeConst;   // a read-only map\nconst int n_dims = 5;\n  \nMatrixType m1(n_dims), m2(n_dims);\nm1.setRandom();\nm2.setRandom();\nfloat *p = &m2(0);  // get the address storing the data for m2\nMapType m2map(p,m2.size());   // m2map shares data with m2\nMapTypeConst m2mapconst(p,m2.size());  // a read-only accessor for m2\n\ncout << \"m1: \" << m1 << endl;\ncout << \"m2: \" << m2 << endl;\ncout << \"Squared euclidean distance: \" << (m1-m2).squaredNorm() << endl;\ncout << \"Squared euclidean distance, using map: \" <<\n  (m1-m2map).squaredNorm() << endl;\nm2map(3) = 7;   // this will change m2, since they share the same array\ncout << \"Updated m2: \" << m2 << endl;\ncout << \"m2 coefficient 2, constant accessor: \" << m2mapconst(2) << endl;\n/* m2mapconst(2) = 5; */   // this yields a compile-time error\n\n}\n  return 0;\n}\n", "meta": {"hexsha": "a6ed88eccae983554af70d588622a84ac9efb7a6", "size": 1429, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "build/compiled_eigen/doc/snippets/compile_Tutorial_Map_using.cpp", "max_stars_repo_name": "aminulce/soil_model_cpp", "max_stars_repo_head_hexsha": "027803c29cbf5bddd1222839ba73019876533f87", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "build/compiled_eigen/doc/snippets/compile_Tutorial_Map_using.cpp", "max_issues_repo_name": "aminulce/soil_model_cpp", "max_issues_repo_head_hexsha": "027803c29cbf5bddd1222839ba73019876533f87", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "build/compiled_eigen/doc/snippets/compile_Tutorial_Map_using.cpp", "max_forks_repo_name": "aminulce/soil_model_cpp", "max_forks_repo_head_hexsha": "027803c29cbf5bddd1222839ba73019876533f87", "max_forks_repo_licenses": ["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.7555555556, "max_line_length": 224, "alphanum_fraction": 0.6745976207, "num_tokens": 438, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.46155255167849046}}
{"text": "// include statements\n#include <iostream>\n#include <cstddef>\n#include <cstdlib>\n#include <ctime>\n#include <limits>\n#include <cmath>\n#include <random>\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/geometries.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/linestring.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n#include <boost/geometry/algorithms/intersects.hpp>\n#include \"matplotlibcpp.h\"\n\n// Node definiton \nstruct Node{\n    float x;\n    float y;\n    Node *parent;\n};\n\n//array of all nodes\nNode node_list[1000];  \n\n// counter to keep track of no of elements in node_list \nint counter=0;\n\n// for finding the final path\nNode location[500];\n\n// for back propagation\nint backprop = 0;\n\n//Obstcale Points\n//change point to change the location of obstacle\nint obstacle_array[][2]={{4,4}, {5, 4}, {5, 6}, {6, 6}, {6,7}, {5, 7}, {5,8}, {4,8}, {4,7}, {3,7}, {3,6}, {4,6}};\n\n//no of elements in obstacle array\nint obstacle_size = sizeof(obstacle_array)/sizeof(obstacle_array[0]);\n\n//  sampling probablity to set rate of sampling\nfloat sampling_probablity;\n// variable for sampling radius\nfloat sampling_radius;\n\n// function to sample random points, the rate of sampling is biased by using a sampling probablity \nNode sampler(int goal_x, int goal_y, float prob)\n{\n    std::random_device rd; //Will be used to obtain a seed for the random number engine\n    std::mt19937 generator(rd()); //Standard mersenne_twister_engine seeded with rd()\n    std::uniform_real_distribution<float> distribution_biased(0.0, 1.0);\n    std::uniform_real_distribution<float> distribution_x(0.0, 15.0);\n\tstd::uniform_real_distribution<float> distribution_y(0.0, 15.0);\n    float random_prob = distribution_biased(generator);\n    Node sample_node={};\n    if(random_prob>prob)\n    {   \n        sample_node.x= distribution_x(generator);\n        sample_node.y= distribution_y(generator);\n        sample_node.parent= NULL;\n    }\n    else\n    {\n        sample_node.x= goal_x;\n        sample_node.y= goal_y;\n        sample_node.parent= NULL;\n    }\n\n    return sample_node;\n}\n\n//finds distance between two Node's\nfloat distance(Node node1,Node node2)\n{\n    float dist=sqrt(((node1.x-node2.x)*(node1.x-node2.x))+((node1.y-node2.y)*(node1.y-node2.y)));\n    return dist;\n}\n\n//function to find the nearest node\nint find_nearest(Node current)\n{\n    int nearest_node;\n    float minimum_dist= 20;\n    for(int i=0;i<counter;i++)\n    {\n        float dist=distance(current,node_list[i]);\n        if(dist<minimum_dist)\n        {\n            minimum_dist=dist;\n            nearest_node=i;\n        }\n    }\n\n    return nearest_node;\n\n}\n\n//checks intersection between obstacles and path\nbool check_collision(Node end1, Node end2)\n{   \n\n    typedef boost::geometry::model::d2::point_xy<double> point_xy;\n    typedef boost::geometry::model::polygon<point_xy> polygon_t;\n    typedef boost::geometry::model::linestring<point_xy> linestring_t;\n\n    polygon_t obstacle;\n    linestring_t ls1;\n\n    std::vector< point_xy > pointls; \n\n    point_xy point1(end1.x , end1.y);\n    pointls.push_back( point1 );\n\n    point_xy point2(end2.x , end2.y);\n    pointls.push_back( point2 );\n\n    boost::geometry::assign_points( ls1, pointls );\n\n    std::vector< point_xy > ObstaclePoints; \n\n    for(int i=0;i<obstacle_size;i++)\n    {   \n        point_xy point(obstacle_array[i][0] ,obstacle_array[i][1]);\n        ObstaclePoints.push_back( point );\n    }\n    boost::geometry::assign_points( obstacle, ObstaclePoints);\n    bool collision= boost::geometry::intersects(ls1, obstacle);\n\n    return collision;\n}\n//main planner\nbool planner(float start_x, float start_y, float goal_x, float goal_y, float sampling_radius)\n{\n    //variable to see if goal has been reached\n    bool flag = 1;\n\n    // defining the start as a Node\n    Node start={start_x,start_y};\n    Node goal={goal_x,goal_y};\n    Node sample_node={};  \n    int nearest_node;  \n\n    //add start to the node_list\n    node_list[counter]=start;\n    counter++;\n\n    for (int j=0; j<500;)\n    {\n        //samples a random point\n        sample_node = sampler(goal_x,goal_y,sampling_probablity);\n\n        // finds the nearest node to the sampled point\n        nearest_node = find_nearest(sample_node);\n        float dist = distance(sample_node,node_list[nearest_node]);\n\n        // checking if tghe sampled node lies inside the sampling radius\n        if (dist > sampling_radius)\n        {                                                                                                                                                                                                                                                                                                                                                                                                       \n         //computing the angle b/w near and rand wrt x-axis\n         float angle = atan2(sample_node.y - node_list[nearest_node].y,sample_node.x - node_list[nearest_node].x);                                                                                                                                                                                                                                                                                                                                                                                   \n\n        // modifies sample_node in the direction of nearest node 0.5 distance from it\n        sample_node.x=  node_list[nearest_node].x + sampling_radius*cos(angle);\n        sample_node.y=  node_list[nearest_node].y + sampling_radius*sin(angle);\n        }\n\n        //obstacle checking\n        bool collision = check_collision(sample_node, node_list[nearest_node]);\n        if(collision==1)\n        {\n            continue;\n        }\n        else\n        {\n            sample_node.parent= &node_list[nearest_node];\n            node_list[counter]= sample_node;\n            counter++;\n            j++;\n\n        }\n\n        float goal_dist=distance(sample_node,goal);\n        // to check if we have reached the goal, tolerance of 0.1 is considered\n        if(goal_dist<=0.1)\n        {\n            goal.parent= &sample_node;\n            node_list[counter]=goal;\n            counter++;\n            flag = 0;\n            //Goal Reached\n            break;\n        }\n    }\n    if(flag==1)\n    {\n        //Goal not found\n        return 0;\n    }\n        \n    //back propogation to find the final path from goal to start\n    Node *current= &goal;\n    while(current->parent != NULL)\n    {   \n        location[backprop]=*current;\n        backprop++;\n        current=current->parent;\n    }\n     \n    // to add the starting node \n    location[backprop]=start;\n    backprop++;\n\n    return 1;\n}\n\n//plotting function\nvoid plotting(bool sucess)\n{   \n    namespace plt = matplotlibcpp;\n    //plot obstacle\n    std::vector<double> obstacle_x = {};\n    std::vector<double> obstacle_y = {};\n\n    for(int i=0;i<obstacle_size;i++)\n    {\n        obstacle_x.push_back(obstacle_array[i][0]);\n        obstacle_y.push_back(obstacle_array[i][1]);\n    }\n    obstacle_x.push_back(obstacle_array[0][0]);\n    obstacle_y.push_back(obstacle_array[0][1]);\n\n    plt::plot(obstacle_x, obstacle_y,\"k\");\n    \n    //plotiing nodes\n    std::vector<double> scatter_x = {};\n    std::vector<double> scatter_y = {};\n    \n    for(int i=0;i<counter;i++)\n    {  \n        \n            scatter_x.push_back(node_list[i].x);\n            scatter_y.push_back(node_list[i].y);\n       \n    }\n\n    plt::plot(scatter_x, scatter_y,\".m\");\n\n    //plotting tree\n    for(int i=0;i<counter;i++)\n    {   \n        if(node_list[i].parent != NULL)\n        {\n            std::vector<double> tree_x = {};\n            std::vector<double> tree_y = {};\n            tree_x.push_back(node_list[i].x);\n            tree_y.push_back(node_list[i].y);\n            tree_x.push_back(node_list[i].parent->x);\n            tree_y.push_back(node_list[i].parent->y);\n            plt::plot(tree_x, tree_y,\"m\");\n        }\n    }\n\n    if(sucess==1)\n    {\n        //plot final path from start to goal\n        int i = 0;\n        while(i<backprop)\n        {   \n            if(location[i].parent != NULL)\n            {\n                std::vector<double> final_x = {};\n                std::vector<double> final_y = {};\n                final_x.push_back(location[i].x);\n                final_y.push_back(location[i].y);\n                final_x.push_back(location[i].parent->x);\n                final_y.push_back(location[i].parent->y);\n                plt::plot(final_x, final_y,\".b-\");\n            }\n            i++;\n        }\n    }\n    // plotting start and goal\n    std::vector<double> starting_x = {};\n    std::vector<double> starting_y = {};\n    starting_x.push_back(location[0].x);\n    starting_y.push_back(location[0].y);\n    plt::plot(starting_x,starting_y,\".k\");   \n    std::vector<double> ending_x = {};\n    std::vector<double> ending_y = {};\n    ending_x.push_back(location[backprop].x);\n    ending_y.push_back(location[backprop].y);\n    plt::plot(ending_x,ending_y,\".k\");  \n    plt::grid(true);\n    plt::show();\n\n\n}\nusing namespace std;\n//starting of the main function\nint main()\n{   float start_x, start_y, goal_x, goal_y;\n    \n    // taking inputs from the user\n    cout<<\"Enter sampling probablity : \";\n    cin>> sampling_probablity;\n\n    cout<<\"Enter sampling radius (prefered to be less than 1): \";\n    cin>> sampling_radius;\n\n    cout<<\"Enter x postion of start : \";\n    cin>> start_x;\n    \n    cout<<\"Enter y postion of start : \";\n    cin>> start_y;\n\n    cout<<\"Enter x postion of goal: \";\n    cin>> goal_x;\n\n    cout<<\"Enter y postion of goal : \";\n    cin>> goal_y;\n\n    \n    \n    \n    //calling planner\n    bool sucesss = planner(start_x,start_y,goal_x,goal_y,sampling_radius);\n    //calling plotting\n    plotting(sucesss);\n\n    if(sucesss)\n    {\n        std::cout<<\"goal reached\"<<\"\\n\";\n    }\n    else\n    {\n        std::cout<<\"goal not reached\";\n    }\n\n    std::cout<<\"Total no of nodes = \"<<counter<<\"\\n\"<<\"No of nodes in final path = \"<<backprop<<\"\\n\";\n\n    return 0;\n}", "meta": {"hexsha": "0a401adbce29e3e7e7a694b4a7f7cb99df9cb395", "size": 10066, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rrt.cpp", "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": "rrt.cpp", "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": "rrt.cpp", "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": 29.261627907, "max_line_length": 485, "alphanum_fraction": 0.5701370952, "num_tokens": 2361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799253, "lm_q2_score": 0.6261241842048092, "lm_q1q2_score": 0.46155254597484374}}
{"text": "/** \\file ITL_Preconditioner.h */\n\n#pragma once\n\n// MTL4 headers\n#include <boost/numeric/itl/itl.hpp>\n#include <boost/numeric/itl/pc/ilu_0.hpp>\n#include <boost/numeric/itl/pc/ic_0.hpp>\n#include <boost/numeric/mtl/vector/assigner.hpp>\n\n// AMDiS headers\n#include \"MTL4Types.hpp\"\n#include \"DOFMatrix.hpp\"\n#include \"CreatorInterface.hpp\"\n#include \"solver/LinearSolverInterface.hpp\"\n#include \"solver/itl/masslumping.hpp\"\n\nnamespace AMDiS\n{\n  /**\n   * \\ingroup Solver\n   *\n   * \\brief Common base class for wrappers to use ITL preconditioners in AMDiS.\n   */\n  template <class MatrixType, class VectorType>\n  struct ITL_PreconditionerBase : public PreconditionerInterface\n  {\n    virtual void init(SolverMatrix<Matrix<DOFMatrix*>> const& A,\n                      MatrixType const& fullMatrix) = 0;\n\n    virtual void exit() {}\n\n    virtual void solve(VectorType const& x, VectorType& y) const = 0;\n\n    virtual void adjoint_solve(VectorType const& x, VectorType& y) const = 0;\n  };\n\n\n  template <class MatrixType, class VectorType>\n  itl::pc::solver<ITL_PreconditionerBase<MatrixType, VectorType>, VectorType, false>\n  solve(ITL_PreconditionerBase<MatrixType, VectorType> const& P, VectorType const& vin)\n  {\n    return {P, vin};\n  }\n\n  template <class MatrixType, class VectorType>\n  itl::pc::solver<ITL_PreconditionerBase<MatrixType, VectorType>, VectorType, true>\n  adjoint_solve(ITL_PreconditionerBase<MatrixType, VectorType> const& P, VectorType const& vin)\n  {\n    return {P, vin};\n  }\n\n\n  /**\n   * \\ingroup Solver\n   *\n   * \\brief Wrapper for using ITL preconditioners in AMDiS.\n   */\n  template <class Preconditioner, class MatrixType, class VectorType>\n  class ITL_Preconditioner : public ITL_PreconditionerBase<MatrixType, VectorType>\n  {\n  public:\n    using Self        = ITL_Preconditioner;\n    using precon_base = ITL_PreconditionerBase<MatrixType, VectorType>;\n\n    /// Creator class\n    struct Creator : public CreatorInterfaceName<precon_base>\n    {\n      virtual precon_base* create() override\n      {\n        return new Self();\n      }\n    };\n\n    /// Constructor.\n//     ITL_Preconditioner() = default;\n\n    /// Destructor.\n    ~ITL_Preconditioner()\n    {\n      delete precon;\n      precon = NULL;\n    }\n\n    /// Implementation of \\ref ITL_PreconditionerBase::init()\n    virtual void init(SolverMatrix<Matrix<DOFMatrix*>> const& /*A*/,\n                      MatrixType const& fullMatrix) override\n    {\n      delete precon;\n      precon = new Preconditioner(fullMatrix);\n    }\n\n    /// Implementation of \\ref PreconditionerInterface::exit()\n    virtual void exit() override\n    {\n      delete precon;\n      precon = NULL;\n    }\n\n    /// Implementation of \\ref ITL_PreconditionerBase::solve()\n    virtual void solve(VectorType const& vin, VectorType& vout) const override\n    {\n      TEST_EXIT_DBG(precon)(\"No preconditioner initialized!\\n\");\n      precon->solve(vin, vout);\n    }\n\n    /// Implementation of \\ref ITL_PreconditionerBase::adjoint_solve()\n    virtual void adjoint_solve(VectorType const& vin, VectorType& vout) const override\n    {\n      TEST_EXIT_DBG(precon)(\"No preconditioner initialized!\\n\");\n      precon->adjoint_solve(vin, vout);\n    }\n\n  private:\n    Preconditioner* precon = NULL;\n  };\n\n\n  /**\n   * \\ingroup Solver\n   * \\class AMDiS::DiagonalPreconditioner\n   * \\brief ITL_Preconditioner implementation of diagonal (jacobi) preconditioner,\n   * \\implements ITL_Preconditioner\n   *\n   * Diagonal preconditioner \\f$ M^{-1} \\f$ for the system \\f$ Ax=b \\f$ is defined as: \\f$ M=diag(A) \\f$.\n   */\n  using DiagonalPreconditioner =\n    ITL_Preconditioner<itl::pc::diagonal<MTLTypes::MTLMatrix>,\n\t\t       MTLTypes::MTLMatrix, MTLTypes::MTLVector>;\n\n  /**\n   * \\ingroup Solver\n   * \\class AMDiS::DiagonalPreconditioner\n   * \\brief ITL_Preconditioner implementation of diagonal (jacobi) preconditioner,\n   * \\implements ITL_Preconditioner\n   *\n   * Diagonal preconditioner \\f$ M^{-1} \\f$ for the system \\f$ Ax=b \\f$ is defined as: \\f$ M_ii=sum_j(A_ij) \\f$.\n   */\n  using MassLumpingPreconditioner =\n    ITL_Preconditioner<itl::pc::masslumping<MTLTypes::MTLMatrix>,\n\t\t       MTLTypes::MTLMatrix, MTLTypes::MTLVector>;\n\n\n  /**\n   * \\ingroup Solver\n   * \\class AMDiS::IdentityPreconditioner\n   * \\brief ITL_Preconditioner implementation of identity preconditioner,\n   * \\implements ITL_Preconditioner\n   *\n   * Identity preconditioner. Behaves like no preconditioning.\n   */\n  using IdentityPreconditioner =\n    ITL_Preconditioner<itl::pc::identity<MTLTypes::MTLMatrix>,\n\t\t       MTLTypes::MTLMatrix, MTLTypes::MTLVector>;\n\n\n  /**\n   * \\ingroup Solver\n   * \\class AMDiS::ILUPreconditioner\n   * \\brief ITL_Preconditioner implementation of ILU (Incomplete LU factorization)\n   * preconditioner. \\implements ITL_Preconditioner\n   *\n   * The preconditioner is used from ITL. It corresponds for instance to\n   * \"Iterative Methods for Sparce Linear Systems\", second edition, Yousef Saad.\n   *  The preconditioner is described in chapter 10.3 (algorithm 10.4).\n   */\n  using ILUPreconditioner =\n    ITL_Preconditioner<itl::pc::ilu_0<MTLTypes::MTLMatrix>,\n\t\t       MTLTypes::MTLMatrix, MTLTypes::MTLVector>;\n\n\n  /**\n   * \\ingroup Solver\n   * \\class AMDiS::ICPreconditioner\n   * \\brief ITL_Preconditioner implementation of IC (Incomplete Cholesky factorization)\n   * preconditioner. \\implements ITL_Preconditioner\n   *\n   * IC (Incomplete Cholesky factorization) preconditioner.\n   */\n  using ICPreconditioner =\n    ITL_Preconditioner<itl::pc::ic_0<MTLTypes::MTLMatrix>,\n\t\t       MTLTypes::MTLMatrix, MTLTypes::MTLVector>;\n\n\n} // namespace AMDiS\n", "meta": {"hexsha": "47e2d4ca12b1a81b8f07841b425ab0fb94337e32", "size": 5560, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/solver/ITL_Preconditioner.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/solver/ITL_Preconditioner.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/solver/ITL_Preconditioner.hpp", "max_forks_repo_name": "spraetor/amdis2", "max_forks_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8924731183, "max_line_length": 112, "alphanum_fraction": 0.6955035971, "num_tokens": 1554, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799252, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.46155254083205555}}
{"text": "/*! \\file svg_test_boxplot.cpp\n   \\brief Tests for svg boxplot.\n   \\details\n\n   \\author Jacob Voytko and Paul A. Bristow\n*/\n\n// Copyright Jacob Voytko 2007\n// Copyright Paul A. Bristow 2007\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#include <boost/svg_plot/svg_1d_plot.hpp>\n#include <boost/svg_plot/svg_boxplot.hpp>\n\n#include <vector>\nusing std::vector;\n#include <map>\nusing std::multimap;\n#include <cmath>\nusing ::sin;\n#include <iostream>\nusing std::cout;\nusing std::endl;\n\ndouble h(double x)\n{\n    return 50 / (x);\n}\n\ndouble f(double x)\n{ \n    return 40 + 25 * sin(x * 50);\n}\n\nint main()\n{\n    using namespace boost::svg;\n    std::vector<double> data1, data2;\n\n    for(double i=.1; i < 10; i+=.1)\n    { // Fill the vectors with some data.\n        data1.push_back(h(i));\n        data2.push_back(f(i));\n    }\n\n    svg_1d_plot my_1d_plot;\n    my_1d_plot.background_border_color(black)\n           .title(\"1D plots of Common Functions\");\n    my_1d_plot.plot(data1, \"[50 / x]\");\n    my_1d_plot.plot(data2, \"[40 + 25 * sin(50x)]\");\n\n    my_1d_plot.write(\"./svg_test_1d.svg\");\n\n    // Now plot the same data using boxplot.\n    svg_boxplot my_box_plot;\n    my_box_plot.background_border_color(black)\n           .title(\"Boxplots of Common Functions\");\n\n    my_box_plot.plot(data1, \"[50 / x]\");\n    my_box_plot.plot(data2, \"[40 + 25 * sin(50x)]\");\n    my_box_plot.y_autoscale(data1);  // Compute autoscale values for the plot.\n\n\n    my_box_plot.write(\"./svg_test_boxplot.svg\");\n   return 0;\n} // int main()\n\n", "meta": {"hexsha": "0d9ef546ac5ad0ac6599ef4d2f2b2eb0859236c8", "size": 1650, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/svg_test_boxplot.cpp", "max_stars_repo_name": "pabristow/svg_plot", "max_stars_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2016-03-09T03:23:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T14:02:07.000Z", "max_issues_repo_path": "example/svg_test_boxplot.cpp", "max_issues_repo_name": "pabristow/svg_plot", "max_issues_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2018-03-05T14:39:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-22T09:00:33.000Z", "max_forks_repo_path": "example/svg_test_boxplot.cpp", "max_forks_repo_name": "pabristow/svg_plot", "max_forks_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2016-11-04T14:36:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-17T08:12:03.000Z", "avg_line_length": 22.9166666667, "max_line_length": 78, "alphanum_fraction": 0.66, "num_tokens": 480, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6261241632752915, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.46155253777743566}}
{"text": "#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point.hpp>\n#include <boost/geometry/geometries/box.hpp>\n\n#include <boost/geometry/index/rtree.hpp>\n\n// to store queries results\n#include <vector>\n\n// just for output\n#include <iostream>\n#include <boost/foreach.hpp>\n#include <omp.h>\n\nnamespace bg = boost::geometry;\nnamespace bgi = boost::geometry::index;\n\nint main()\n{\n    typedef bg::model::point<float, 2, bg::cs::cartesian> point;\n    typedef bg::model::box<point> box;\n    typedef std::pair<box, unsigned> value;\n\n    // create the rtree using default constructor\n    bgi::rtree< value, bgi::quadratic<16> > rtree;\n\n    // create some values\n    for ( unsigned i = 0 ; i < 10 ; ++i )\n    {\n        // create a box\n        box b(point(i + 0.0f, i + 0.0f), point(i + 0.5f, i + 0.5f));\n        // insert new value\n        rtree.insert(std::make_pair(b, i));\n    }\n\n    // find values intersecting some area defined by a box\n\n    std::vector<box> boxes;\n    boxes.push_back(box(point(0, 0), point(5, 5)));\n    boxes.push_back(box(point(1, 1), point(4, 4)));\n    boxes.push_back(box(point(2, 2), point(3, 3)));\n\n    #pragma omp parallel for \n    for(int i=0; i < boxes.size(); i++)\n    {\n        int tid = omp_get_thread_num();\n        // Borrowed from here\n        // https://stackoverflow.com/questions/4106992/parallelize-output-using-openmp\n        std::stringstream buf;\n        buf << \"---- spatial query from thread: \" << tid << \"----\\n\";\n        std::vector<value> result_s;\n        rtree.query(bgi::intersects(boxes[i]),std::back_inserter(result_s));\n        // display results\n        buf << \"spatial query box:\" << \"\\n\";\n        buf << bg::wkt<box>(boxes[i]) << \"\\n\";\n        buf << \"spatial query result:\" << \"\\n\";\n        BOOST_FOREACH(value const& v, result_s)\n            buf << bg::wkt<box>(v.first) << \" - \" << v.second << \"\\n\";\n        // Write the buffer to output\n        // #pragma omp critical\n        std::cout << buf.rdbuf();\n    }\n    return 0;\n}", "meta": {"hexsha": "723686c211208ad6e4aae3315e6e6a31701417e2", "size": 1986, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dev/omp/parallel_rtree.cpp", "max_stars_repo_name": "BeichuanH/fmm", "max_stars_repo_head_hexsha": "8564a0e8c2dc03a7bca70d0b69a70b5c06340508", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-06-13T20:52:13.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-13T20:52:13.000Z", "max_issues_repo_path": "dev/omp/parallel_rtree.cpp", "max_issues_repo_name": "BeichuanH/fmm", "max_issues_repo_head_hexsha": "8564a0e8c2dc03a7bca70d0b69a70b5c06340508", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dev/omp/parallel_rtree.cpp", "max_forks_repo_name": "BeichuanH/fmm", "max_forks_repo_head_hexsha": "8564a0e8c2dc03a7bca70d0b69a70b5c06340508", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.03125, "max_line_length": 86, "alphanum_fraction": 0.5916414904, "num_tokens": 566, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799253, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.46155253054647916}}
{"text": "// Copyright Louis Dionne 2015\n// Distributed under the Boost Software License, Version 1.0.\n//\n// This is an adapted version of the \"Calc1\" example in Proto's documentation\n// to work with compile-time integers too.\n\n#include <boost/hana.hpp>\n\n#include <boost/proto/context.hpp>\n#include <boost/proto/core.hpp>\n\n#include <cassert>\nnamespace proto = boost::proto;\nnamespace hana = boost::hana;\nusing namespace hana::literals;\n\n\ntemplate <int n>\nstruct placeholder { };\n\n// Define some placeholders\nproto::terminal<placeholder<1>>::type const _1 = {{}};\nproto::terminal<placeholder<2>>::type const _2 = {{}};\n\n// Define a calculator context, for evaluating arithmetic expressions\ntemplate <typename M, typename N>\nstruct calculator_context\n  : proto::callable_context<calculator_context<M, N> const>\n{\n  // The values bound to the placeholders\n  M m;\n  N n;\n\n  constexpr calculator_context(M m, N n) : m{m}, n{n} { }\n\n  // The result of evaluating arithmetic expressions\n  template <typename Sig>\n  struct result;\n\n  template <typename This, typename Terminal>\n  struct result<This(Terminal, placeholder<1> const&)> {\n    using type = M;\n  };\n\n  template <typename This, typename Terminal>\n  struct result<This(Terminal, placeholder<2> const&)> {\n    using type = N;\n  };\n\n  // Handle the evaluation of the placeholder terminals\n  constexpr auto operator()(proto::tag::terminal, placeholder<1>) const\n  { return m; }\n\n  constexpr auto operator()(proto::tag::terminal, placeholder<2>) const\n  { return n; }\n};\n\ntemplate <typename Expr, typename M, typename N>\nconstexpr auto evaluate(Expr expr, M m, N n) {\n  // Create a calculator context with d1 and d2 substituted for _1 and _2\n  calculator_context<M, N> const ctx{m, n};\n\n  // Evaluate the calculator expression with the calculator_context\n  return proto::eval(expr, ctx);\n}\n\nint main() {\n// sample(proto)\nauto expr = (_1 - _2) / _2;\n\n// compile-time computations\nstatic_assert(decltype(evaluate(expr, 6_c, 2_c))::value == 2, \"\");\n\n// runtime computations\nint i = 6, j = 2;\nassert(evaluate(expr, i, j) == 2);\n// end-sample\n}\n", "meta": {"hexsha": "529008723e2b0230f53b2d2dc9f4034cd07da161", "size": 2077, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/proto.cpp", "max_stars_repo_name": "ldionne/cppcon-2015-hana", "max_stars_repo_head_hexsha": "f917c492ff14953bad8d08bd43d53e907ccfb2ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2015-09-24T15:43:27.000Z", "max_stars_repo_stars_event_max_datetime": "2017-04-15T20:39:35.000Z", "max_issues_repo_path": "code/proto.cpp", "max_issues_repo_name": "ldionne/hana-cppcon-2015", "max_issues_repo_head_hexsha": "f917c492ff14953bad8d08bd43d53e907ccfb2ee", "max_issues_repo_licenses": ["MIT"], "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/proto.cpp", "max_forks_repo_name": "ldionne/hana-cppcon-2015", "max_forks_repo_head_hexsha": "f917c492ff14953bad8d08bd43d53e907ccfb2ee", "max_forks_repo_licenses": ["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.2911392405, "max_line_length": 77, "alphanum_fraction": 0.7082330284, "num_tokens": 526, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149978955811, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4615414210827503}}
{"text": "/*\n * AttitudeMagCalib.cpp\n *\n *  Copyright (c) 2013 Gareth Cross. All rights reserved.\n *\n *  This file is part of kr_attitude_eskf.\n *\n *\tCreated on: 23/06/2014\n *\t\t  Author: gareth\n */\n\n#include <kr_attitude_eskf/AttitudeMagCalib.hpp>\n#include <Eigen/Cholesky>\n#include <cmath>\n\nusing namespace Eigen;\n\nnamespace kr {\n\nAttitudeMagCalib::AttitudeMagCalib() { reset(); }\n\nvoid AttitudeMagCalib::reset() {\n  binH_.clear();\n  binV_.clear();\n  calibrated_ = false;\n  bias_.setZero();\n  scale_.setOnes();\n}\n\nvoid AttitudeMagCalib::appendSample(const quat &att,\n                                    const vec3 &field) {\n  SampleBin bin;\n  bin.field = field;\n  bin.q = att;\n  \n  const vec3 localG = att.conjugate().matrix() * vec3(0,0,1);\n  \n  //  determine local angle\n  if (std::abs(localG[2]) < 0.1) {\n    //  world vertical is approx. in the local X/Y plane\n    const vec3 worldZ = att.matrix() * vec3(0,0,1);\n    const scalar_t ang = std::atan2(worldZ[1], worldZ[0]); \n    const int key = (ang + M_PI) / (2*M_PI) * kBinMaxCount;\n    binV_[key] = bin;\n  } else if (std::abs(localG[2]) > 0.9) {\n    //  world vertical is approx. vertical\n    const vec3 worldX = att.matrix() * vec3(1,0,0);\n    const scalar_t ang = std::atan2(worldX[1], worldX[0]);\n    const int key = (ang + M_PI) / (2*M_PI) * kBinMaxCount;\n    binH_[key] = bin;\n  }\n}\n\nbool AttitudeMagCalib::isReady() const {\n  if (binV_.size() < kBinMaxCount*8/10) {\n    return false;\n  }\n  if (binH_.size() < kBinMaxCount*8/10) {\n    return false;\n  }\n  return true;\n}\n\nbool AttitudeMagCalib::isCalibrated() const { return calibrated_; }\n\nvoid AttitudeMagCalib::calibrate(AttitudeMagCalib::CalibrationType type) {\n\n  if (!isReady()) {\n    throw insufficient_data();\n  }\n\n  if (type == AttitudeMagCalib::FullCalibration) {\n    //  perform full estimation of bias and scale\n    vec3 bias(0,0,0), scl(1,1,1);\n\n    std::vector<vec3> meas;\n    for (const std::pair<int, SampleBin>& s : binH_) {\n      meas.push_back(s.second.field);\n    }\n    for (const std::pair<int, SampleBin>&s : binV_) {\n      meas.push_back(s.second.field);\n    }\n    const size_t N = meas.size();\n\n    //  fit to sphere\n    Matrix<scalar_t,Eigen::Dynamic,Eigen::Dynamic> A(N, 4);\n    Matrix<scalar_t,Eigen::Dynamic,1> b(N, 1);\n    for (size_t i=0; i < meas.size(); i++) {\n      A(i,0) = 2*meas[i][0];\n      A(i,1) = 2*meas[i][1];\n      A(i,2) = 2*meas[i][2];\n      A(i,3) = 1;\n      b(i,0) = meas[i][0]*meas[i][0] + meas[i][1]*meas[i][1] + \n          meas[i][2]*meas[i][2];\n    }\n    //  solve system for center\n    const Matrix<scalar_t,4,1> x = A.colPivHouseholderQr().solve(b);\n    bias = x.block<3,1>(0,0);\n\n    scalar_t mean_rad = 0.0, mean_rad_sqr = 0.0;\n    //  calculate estimate of mean radius\n    for (const vec3 &v : meas) {\n      const scalar_t r = (v - bias).norm();\n      mean_rad += r;\n      mean_rad_sqr += r * r;\n    }\n    mean_rad /= N;\n    mean_rad_sqr /= N;\n\n    //  refine with GN-NLS\n    Matrix<scalar_t, Eigen::Dynamic, 6> J(N, 6);\n    Matrix<scalar_t, Eigen::Dynamic, 1> r(N, 1);\n    Matrix<scalar_t, Eigen::Dynamic, Eigen::Dynamic> W(N,N);\n    W.setZero();\n\n    for (int iter = 0; iter < 20; iter++) {\n      for (size_t i = 0; i < meas.size(); i++) {\n        const scalar_t x = (meas[i][0] - bias[0]) / scl[0];\n        const scalar_t y = (meas[i][1] - bias[1]) / scl[1];\n        const scalar_t z = (meas[i][2] - bias[2]) / scl[2];\n        const scalar_t r2 = x*x + y*y + z*z;\n        \n        //  residual\n        r(i,0) = mean_rad*mean_rad - r2;\n        //  jacobian\n        J(i,0) = -2 * x * x / scl[0];\n        J(i,1) = -2 * y * y / scl[1];\n        J(i,2) = -2 * z * z / scl[2];\n        J(i,3) = -2 * x / scl[0];\n        J(i,4) = -2 * y / scl[1];\n        J(i,5) = -2 * z / scl[2];\n      }\n\n      //  calculate mean squared error\n      scalar_t sigmaSquared=0;\n      for (int j=0; j < r.rows(); j++) {\n        sigmaSquared += r(j,0)*r(j,0);\n      }\n      sigmaSquared /= r.rows();\n      //  calculate cauchy weights\n      for (int j=0; j < r.rows(); j++) {\n        const scalar_t errSqr = r(j,0)*r(j,0);\n        W(j,j) = 1.0 / (1 + errSqr/sigmaSquared);\n      }\n      \n      Matrix<scalar_t, 6, 6> H = J.transpose() * W * J;\n      for (int i = 0; i < 3; i++) {  //  prior on scale\n        H(i,i) *= 1.01;\n      }\n      Eigen::LDLT<Matrix<scalar_t,6,6>> LDLT(H);\n      const Matrix<scalar_t, 6, 1> update = LDLT.solve(J.transpose() * W * r);\n\n      scl += update.block<3, 1>(0, 0);\n      bias += update.block<3, 1>(3, 0);\n    }\n\n    bias_ = bias;\n    scale_ = scl;\n  } else {\n    bias_.setZero();\n    scale_.setOnes();\n  }\n  \n  calibrated_ = true;\n}\n\n} //  namespace kr\n", "meta": {"hexsha": "ec15ca849211947585d08b0f9382f55a279c139c", "size": 4617, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/AttitudeMagCalib.cpp", "max_stars_repo_name": "CTSHEN/kr_attitude_eskf", "max_stars_repo_head_hexsha": "f64d6bf5f4b5b91d7ac14093dbe88471c27976a5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 33.0, "max_stars_repo_stars_event_min_datetime": "2016-10-11T00:58:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T02:06:01.000Z", "max_issues_repo_path": "src/AttitudeMagCalib.cpp", "max_issues_repo_name": "jackiecx/kr_attitude_eskf", "max_issues_repo_head_hexsha": "f64d6bf5f4b5b91d7ac14093dbe88471c27976a5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-08-13T08:37:35.000Z", "max_issues_repo_issues_event_max_datetime": "2016-08-13T08:37:35.000Z", "max_forks_repo_path": "src/AttitudeMagCalib.cpp", "max_forks_repo_name": "jackiecx/kr_attitude_eskf", "max_forks_repo_head_hexsha": "f64d6bf5f4b5b91d7ac14093dbe88471c27976a5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2016-01-25T09:53:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-19T21:20:31.000Z", "avg_line_length": 27.4821428571, "max_line_length": 78, "alphanum_fraction": 0.5501407841, "num_tokens": 1603, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149978955813, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.4615414210827503}}
{"text": "#pragma once\n\n#include <polyfem/ProblemWithSolution.hpp>\n\n#include <vector>\n#include <Eigen/Dense>\n\nnamespace polyfem\n{\n\tclass LinearProblem : public ProblemWithSolution\n\t{\n\tpublic:\n\t\tLinearProblem(const std::string &name);\n\n\t\tVectorNd eval_fun(const VectorNd &pt, const double t) const override;\n\t\tAutodiffGradPt eval_fun(const AutodiffGradPt &pt, const double t) const override;\n\t\tAutodiffHessianPt eval_fun(const AutodiffHessianPt &pt, const double t) const override;\n\n\t\tbool is_scalar() const override { return true; }\n\t};\n\n\tclass QuadraticProblem : public ProblemWithSolution\n\t{\n\tpublic:\n\t\tQuadraticProblem(const std::string &name);\n\n\t\tVectorNd eval_fun(const VectorNd &pt, const double t) const override;\n\t\tAutodiffGradPt eval_fun(const AutodiffGradPt &pt, const double t) const override;\n\t\tAutodiffHessianPt eval_fun(const AutodiffHessianPt &pt, const double t) const override;\n\n\t\tbool is_scalar() const override { return true; }\n\t};\n\n\tclass CubicProblem : public ProblemWithSolution\n\t{\n\tpublic:\n\t\tCubicProblem(const std::string &name);\n\n\t\tVectorNd eval_fun(const VectorNd &pt, const double t) const override;\n\t\tAutodiffGradPt eval_fun(const AutodiffGradPt &pt, const double t) const override;\n\t\tAutodiffHessianPt eval_fun(const AutodiffHessianPt &pt, const double t) const override;\n\n\t\tbool is_scalar() const override { return true; }\n\t};\n\n\tclass SineProblem : public ProblemWithSolution\n\t{\n\tpublic:\n\t\tSineProblem(const std::string &name);\n\n\t\tVectorNd eval_fun(const VectorNd &pt, const double t) const override;\n\t\tAutodiffGradPt eval_fun(const AutodiffGradPt &pt, const double t) const override;\n\t\tAutodiffHessianPt eval_fun(const AutodiffHessianPt &pt, const double t) const override;\n\n\t\tbool is_scalar() const override { return true; }\n\t};\n\n\tclass ZeroBCProblem : public ProblemWithSolution\n\t{\n\tpublic:\n\t\tZeroBCProblem(const std::string &name);\n\n\t\tVectorNd eval_fun(const VectorNd &pt, const double t) const override;\n\t\tAutodiffGradPt eval_fun(const AutodiffGradPt &pt, const double t) const override;\n\t\tAutodiffHessianPt eval_fun(const AutodiffHessianPt &pt, const double t) const override;\n\n\t\tbool is_scalar() const override { return true; }\n\t};\n\n\tclass MinSurfProblem : public Problem\n\t{\n\tpublic:\n\t\tMinSurfProblem(const std::string &name);\n\n\t\tvoid rhs(const AssemblerUtils &assembler, const std::string &formulation, const Eigen::MatrixXd &pts, const double t, Eigen::MatrixXd &val) const override;\n\t\tbool is_rhs_zero() const override { return false; }\n\n\t\tvoid bc(const Mesh &mesh, const Eigen::MatrixXi &global_ids, const Eigen::MatrixXd &uv, const Eigen::MatrixXd &pts, const double t, Eigen::MatrixXd &val) const override;\n\n\t\tbool is_scalar() const override { return true; }\n\t\tbool has_exact_sol() const override { return false; }\n\t};\n\n\tclass TimeDependentProblem : public Problem\n\t{\n\tpublic:\n\t\tTimeDependentProblem(const std::string &name);\n\n\t\tvoid rhs(const AssemblerUtils &assembler, const std::string &formulation, const Eigen::MatrixXd &pts, const double t, Eigen::MatrixXd &val) const override;\n\t\tbool is_rhs_zero() const override { return false; }\n\n\t\tvoid bc(const Mesh &mesh, const Eigen::MatrixXi &global_ids, const Eigen::MatrixXd &uv, const Eigen::MatrixXd &pts, const double t, Eigen::MatrixXd &val) const override;\n\t\tvoid initial_solution(const Mesh &mesh, const Eigen::MatrixXi &global_ids, const Eigen::MatrixXd &pts, Eigen::MatrixXd &val) const override;\n\n\t\tbool has_exact_sol() const override { return false; }\n\t\tbool is_scalar() const override { return true; }\n\t\tbool is_time_dependent() const override { return true; }\n\t};\n\n\tclass GenericScalarProblemExact : public ProblemWithSolution\n\t{\n\tpublic:\n\t\tGenericScalarProblemExact(const std::string &name);\n\n\t\tbool is_scalar() const override { return true; }\n\t\tbool is_time_dependent() const override { return func_ <= 1; }\n\t\tbool is_constant_in_time() const override { return false; }\n\n\t\tvoid initial_solution(const Mesh &mesh, const Eigen::MatrixXi &global_ids, const Eigen::MatrixXd &pts, Eigen::MatrixXd &val) const override;\n\n\t\tvoid set_parameters(const json &params) override;\n\n\t\tVectorNd eval_fun(const VectorNd &pt, double t) const override;\n\t\tAutodiffGradPt eval_fun(const AutodiffGradPt &pt, double t) const override;\n\t\tAutodiffHessianPt eval_fun(const AutodiffHessianPt &pt, double t) const override;\n\n\t\tvoid rhs(const AssemblerUtils &assembler, const std::string &formulation, const Eigen::MatrixXd &pts, const double t, Eigen::MatrixXd &val) const override;\n\n\tprivate:\n\t\tint func_;\n\t};\n} // namespace polyfem\n", "meta": {"hexsha": "e7e92ab0d60da2bee779d204126b718a170c61e2", "size": 4503, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/problem/MiscProblem.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/problem/MiscProblem.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/problem/MiscProblem.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": 36.6097560976, "max_line_length": 171, "alphanum_fraction": 0.7603819676, "num_tokens": 1159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149978955811, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.46154142108275026}}
{"text": "#include <igl/decimate.h>\n#include <igl/qslim.h>\n#include <Eigen/Core>\n#include <iostream>\n#include <set>\n\n#ifdef MEX\n#  include <mex.h>\n#  include <igl/C_STR.h>\n#  include <igl/matlab/mexErrMsgTxt.h>\n#  undef assert\n#  define assert( isOK ) ( (isOK) ? (void)0 : (void) ::mexErrMsgTxt(C_STR(__FILE__<<\":\"<<__LINE__<<\": failed assertion `\"<<#isOK<<\"'\"<<std::endl) ) )\n#endif\n\n#include <igl/matlab/MexStream.h>\n#include <igl/matlab/parse_rhs.h>\n#include <igl/matlab/prepare_lhs.h>\n#include <igl/matlab/validate_arg.h>\n\nvoid mexFunction(\n         int          nlhs,\n         mxArray      *plhs[],\n         int          nrhs,\n         const mxArray *prhs[]\n         )\n{\n  using namespace std;\n  using namespace igl;\n  using namespace igl::matlab;\n  using namespace Eigen;\n  MatrixXd V,W;\n  MatrixXi F,G;\n  VectorXi J,I;\n\n  igl::matlab::MexStream mout;        \n  std::streambuf *outbuf = std::cout.rdbuf(&mout);\n\n  mexErrMsgTxt(nrhs>=3,\"nrhs should be >= 3\");\n  parse_rhs_double(prhs,V);\n  parse_rhs_index(prhs+1,F);\n  mexErrMsgTxt(V.cols()==3,\"V must be #V by 3\");\n  mexErrMsgTxt(F.cols()==3,\"F must be #F by 3\");\n  mexErrMsgTxt(\n    mxIsDouble(prhs[2]) && mxGetM(prhs[2])==1 && mxGetN(prhs[2])==1,\n    \"fraction to decimate should be scalar\");\n  double ratio = * mxGetPr(prhs[2]);\n  mexErrMsgTxt((ratio>0 && ratio<1) || (ratio>0 && ratio<F.rows()) ,\n    \"Ratio should be in (0,1) or [1,#F)\");\n  const size_t max_m = ratio<1 ? ratio*F.rows() : ratio;\n\n\n  enum DecimateMethod\n  {\n    DECIMATE_METHOD_NAIVE = 0,\n    DECIMATE_METHOD_QSLIM = 1,\n    NUM_DECIMATE_METHODS = 2\n  } method = DECIMATE_METHOD_NAIVE;\n  {\n    int i = 3;\n    while(i<nrhs)\n    {\n      mexErrMsgTxt(mxIsChar(prhs[i]),\"Parameter names should be strings\");\n      // Cast to char\n      const char * name = mxArrayToString(prhs[i]);\n      if(strcmp(\"Method\",name) == 0)\n      {\n        validate_arg_char(i,nrhs,prhs,name);\n        const char * type_name = mxArrayToString(prhs[++i]);\n        if(strcmp(\"naive\",type_name)==0)\n        {\n          method = DECIMATE_METHOD_NAIVE;\n        }else if(strcmp(\"qslim\",type_name)==0)\n        {\n          method = DECIMATE_METHOD_QSLIM;\n        }else\n        {\n          mexErrMsgTxt(false,C_STR(\"Unknown method: \"<<method));\n        }\n      }else\n      {\n        mexErrMsgTxt(false,C_STR(\"Unknown parameter: \"<<name));\n      }\n      i++;\n    }\n  }\n\n\n  switch(method)\n  {\n    case DECIMATE_METHOD_NAIVE:\n      decimate(V,F,max_m,W,G,J,I);\n      break;\n    case DECIMATE_METHOD_QSLIM:\n      qslim(V,F,max_m,W,G,J,I);\n      break;\n    default:\n      mexErrMsgTxt(false,\"Unkown method.\");\n      break;\n  }\n\n  switch(nlhs)\n  {\n    case 4:\n      prepare_lhs_index(I,plhs+3);\n    case 3:\n      prepare_lhs_index(J,plhs+2);\n    case 2:\n      prepare_lhs_index(G,plhs+1);\n    case 1:\n      prepare_lhs_double(W,plhs+0);\n    default:break;\n  }\n\n  // Restore the std stream buffer Important!\n  std::cout.rdbuf(outbuf);\n  return;\n}\n", "meta": {"hexsha": "cd63336dc3fd2eb07c34c38ef8c858f23656902a", "size": 2921, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Geometry_Processing_Toolbox/src/cppmex/decimate_libigl.cpp", "max_stars_repo_name": "sidgairo18/SCILAB_MEX_TOOLBOX", "max_stars_repo_head_hexsha": "fc679f6d226c03b992b632823a5e57abea05cefa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-09-16T19:46:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-11T14:51:37.000Z", "max_issues_repo_path": "Geometry_Processing_Toolbox/src/cppmex/decimate_libigl.cpp", "max_issues_repo_name": "sidgairo18/SCILAB_MEX_TOOLBOX", "max_issues_repo_head_hexsha": "fc679f6d226c03b992b632823a5e57abea05cefa", "max_issues_repo_licenses": ["MIT"], "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_Processing_Toolbox/src/cppmex/decimate_libigl.cpp", "max_forks_repo_name": "sidgairo18/SCILAB_MEX_TOOLBOX", "max_forks_repo_head_hexsha": "fc679f6d226c03b992b632823a5e57abea05cefa", "max_forks_repo_licenses": ["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.7542372881, "max_line_length": 149, "alphanum_fraction": 0.5994522424, "num_tokens": 890, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7549149868676281, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.46154141434045864}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2012-2014 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_STRATEGIES_CARTESIAN_BUFFER_JOIN_ROUND_HPP\n#define BOOST_GEOMETRY_STRATEGIES_CARTESIAN_BUFFER_JOIN_ROUND_HPP\n\n#include <boost/assert.hpp>\n#include <boost/geometry/core/cs.hpp>\n#include <boost/geometry/policies/compare.hpp>\n#include <boost/geometry/strategies/buffer.hpp>\n#include <boost/geometry/util/math.hpp>\n#include <boost/geometry/util/select_most_precise.hpp>\n\n#ifdef BOOST_GEOMETRY_DEBUG_BUFFER_WARN\n#include <boost/geometry/io/wkt/wkt.hpp>\n#endif\n\n\nnamespace boost { namespace geometry\n{\n\n\nnamespace strategy { namespace buffer\n{\n\n/*!\n\\brief Let the buffer create rounded corners\n\\ingroup strategies\n\\details This strategy can be used as JoinStrategy for the buffer algorithm.\n    It creates a rounded corners around each convex vertex. It can be applied\n    for (multi)linestrings and (multi)polygons.\n    This strategy is only applicable for Cartesian coordinate systems.\n\n\\qbk{\n[heading Example]\n[buffer_join_round]\n[heading Output]\n[$img/strategies/buffer_join_round.png]\n[heading See also]\n\\* [link geometry.reference.algorithms.buffer.buffer_7_with_strategies buffer (with strategies)]\n\\* [link geometry.reference.strategies.strategy_buffer_join_miter join_miter]\n}\n */\nclass join_round\n{\npublic :\n\n    //! \\brief Constructs the strategy\n    //! \\param points_per_circle points which would be used for a full circle\n    explicit inline join_round(std::size_t points_per_circle = 90)\n        : m_points_per_circle(points_per_circle)\n    {}\n\nprivate :\n    template\n    <\n        typename PromotedType,\n        typename Point,\n        typename DistanceType,\n        typename RangeOut\n    >\n    inline void generate_points(Point const& vertex,\n                Point const& perp1, Point const& perp2,\n                DistanceType const& buffer_distance,\n                RangeOut& range_out) const\n    {\n        PromotedType dx1 = get<0>(perp1) - get<0>(vertex);\n        PromotedType dy1 = get<1>(perp1) - get<1>(vertex);\n        PromotedType dx2 = get<0>(perp2) - get<0>(vertex);\n        PromotedType dy2 = get<1>(perp2) - get<1>(vertex);\n\n        BOOST_ASSERT(buffer_distance != 0);\n\n        dx1 /= buffer_distance;\n        dy1 /= buffer_distance;\n        dx2 /= buffer_distance;\n        dy2 /= buffer_distance;\n\n        PromotedType angle_diff = acos(dx1 * dx2 + dy1 * dy2);\n\n        PromotedType two = 2.0;\n        PromotedType steps = m_points_per_circle;\n        int n = boost::numeric_cast<int>(steps * angle_diff\n                    / (two * geometry::math::pi<PromotedType>()));\n\n        if (n <= 1)\n        {\n            return;\n        }\n\n        PromotedType const angle1 = atan2(dy1, dx1);\n        PromotedType diff = angle_diff / PromotedType(n);\n        PromotedType a = angle1 - diff;\n\n        for (int i = 0; i < n - 1; i++, a -= diff)\n        {\n            Point p;\n            set<0>(p, get<0>(vertex) + buffer_distance * cos(a));\n            set<1>(p, get<1>(vertex) + buffer_distance * sin(a));\n            range_out.push_back(p);\n        }\n    }\n\npublic :\n\n\n#ifndef DOXYGEN_SHOULD_SKIP_THIS\n    //! Fills output_range with a rounded shape around a vertex\n    template <typename Point, typename DistanceType, typename RangeOut>\n    inline bool apply(Point const& ip, Point const& vertex,\n                Point const& perp1, Point const& perp2,\n                DistanceType const& buffer_distance,\n                RangeOut& range_out) const\n    {\n        typedef typename coordinate_type<Point>::type coordinate_type;\n        typedef typename boost::range_value<RangeOut>::type output_point_type;\n\n        typedef typename geometry::select_most_precise\n            <\n                typename geometry::select_most_precise\n                    <\n                        coordinate_type,\n                        typename geometry::coordinate_type<output_point_type>::type\n                    >::type,\n                double\n            >::type promoted_type;\n\n        geometry::equal_to<Point> equals;\n        if (equals(perp1, perp2))\n        {\n#ifdef BOOST_GEOMETRY_DEBUG_BUFFER_WARN\n            std::cout << \"Corner for equal points \" << geometry::wkt(ip) << \" \" << geometry::wkt(perp1) << std::endl;\n#endif\n            return false;\n        }\n\n        // Generate 'vectors'\n        coordinate_type vix = (get<0>(ip) - get<0>(vertex));\n        coordinate_type viy = (get<1>(ip) - get<1>(vertex));\n\n        promoted_type length_i = geometry::math::sqrt(vix * vix + viy * viy);\n        DistanceType const bd = geometry::math::abs(buffer_distance);\n        promoted_type prop = bd / length_i;\n\n        Point bp;\n        set<0>(bp, get<0>(vertex) + vix * prop);\n        set<1>(bp, get<1>(vertex) + viy * prop);\n\n        range_out.push_back(perp1);\n        generate_points<promoted_type>(vertex, perp1, perp2, bd, range_out);\n        range_out.push_back(perp2);\n        return true;\n    }\n\n    template <typename NumericType>\n    static inline NumericType max_distance(NumericType const& distance)\n    {\n        return distance;\n    }\n\n#endif // DOXYGEN_SHOULD_SKIP_THIS\n\nprivate :\n    std::size_t m_points_per_circle;\n};\n\n\n}} // namespace strategy::buffer\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_STRATEGIES_CARTESIAN_BUFFER_JOIN_ROUND_HPP\n", "meta": {"hexsha": "9e467c85a08444b8c23c7c69da9e12715f8126ca", "size": 5520, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/boost_1_56_0/boost/geometry/strategies/cartesian/buffer_join_round.hpp", "max_stars_repo_name": "cooparation/caffe-android", "max_stars_repo_head_hexsha": "cd91078d1f298c74fca4c242531989d64a32ba03", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 133.0, "max_stars_repo_stars_event_min_datetime": "2018-04-20T14:09:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-15T11:51:25.000Z", "max_issues_repo_path": "boost/boost_1_56_0/boost/geometry/strategies/cartesian/buffer_join_round.hpp", "max_issues_repo_name": "cooparation/caffe-android", "max_issues_repo_head_hexsha": "cd91078d1f298c74fca4c242531989d64a32ba03", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": 61.0, "max_issues_repo_issues_event_min_datetime": "2015-05-27T11:20:11.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-20T15:06:21.000Z", "max_forks_repo_path": "boost/boost_1_56_0/boost/geometry/strategies/cartesian/buffer_join_round.hpp", "max_forks_repo_name": "cooparation/caffe-android", "max_forks_repo_head_hexsha": "cd91078d1f298c74fca4c242531989d64a32ba03", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 83.0, "max_forks_repo_forks_event_min_datetime": "2018-04-27T03:58:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-11T09:23:40.000Z", "avg_line_length": 31.0112359551, "max_line_length": 117, "alphanum_fraction": 0.6492753623, "num_tokens": 1321, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.46154140759816703}}
{"text": "#include <exception>\n#include <fstream>\n#include <sstream>\n#include <iostream>\n#include <iterator>\n#include <string>\n#include <range/v3/all.hpp>\n#include <cstdint>\n#include <boost/circular_buffer.hpp>\n#include <initializer_list>\nusing Ring = boost::circular_buffer<int>;\nnamespace views = ranges::views;\nstruct CrabCup\n{\nprivate:\n  Ring ring_;\n\npublic:\n  CrabCup(std::initializer_list<int> l, int n) : ring_(n)\n  {\n    ranges::copy(l, std::back_inserter(ring_));\n\n    auto indexs = views::ints | views::drop(l.size() + 1) | views::take(n - l.size()) | views::common;\n    ranges::copy(indexs, std::back_inserter(ring_));\n  }\n  CrabCup(std::initializer_list<int> l) : ring_(l.begin(), l.end())\n  {\n  }\n\n  friend std::ostream &operator<<(std::ostream &os, const CrabCup &crabcup)\n  {\n    std::ostream_iterator<int> oit(std::cout, \"\");\n    ranges::copy(crabcup.ring_, oit);\n    return os;\n  }\n  void round()\n  {\n    std::ostream_iterator<int> oit(std::cout, \",\");\n    auto n = ring_.front();\n    std::vector<int> v(ring_.begin() + 4, ring_.end());\n    auto indexs = views::ints | views::take(ring_.size()) | views::drop(4) | views::common;\n    std::vector<int> vi(indexs.begin(), indexs.end());\n    ranges::zip_view flatmap(v, vi);\n    ranges::sort(flatmap);\n    auto dstpos = ranges::lower_bound(v, n);\n    if (dstpos == v.begin()) {\n      dstpos = v.end();\n    }\n    --dstpos;\n    int len = dstpos - v.begin();\n    auto id = vi[len];\n    std::rotate(ring_.begin() + 1, ring_.begin() + 4, ring_.begin() + id + 1);\n\n    ring_.push_back(n);\n  }\n  void findone()\n  {\n    while (ring_.front() != 1) {\n      ring_.push_back(ring_.front());\n    }\n    ring_.pop_front();\n  }\n};\n\n\nint main()\n{\n  CrabCup c({ 4, 6, 7, 5, 2, 8, 1, 9, 3 }, 20);\n  for (auto i : views::ints | views::take(30) | views::common) {\n    c.round();\n  }\n  c.findone();\n  std::cout << c << std::endl;\n  return 0;\n}\n", "meta": {"hexsha": "9e29d1589ab18eef2bb51bf989f1d46b0180e227", "size": 1875, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "game24/aoc202301.cpp", "max_stars_repo_name": "jiayuehua/adventOfCode", "max_stars_repo_head_hexsha": "fd47ddefd286fe94db204a9850110f8d1d74d15b", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "game24/aoc202301.cpp", "max_issues_repo_name": "jiayuehua/adventOfCode", "max_issues_repo_head_hexsha": "fd47ddefd286fe94db204a9850110f8d1d74d15b", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "game24/aoc202301.cpp", "max_forks_repo_name": "jiayuehua/adventOfCode", "max_forks_repo_head_hexsha": "fd47ddefd286fe94db204a9850110f8d1d74d15b", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.6710526316, "max_line_length": 102, "alphanum_fraction": 0.6048, "num_tokens": 585, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.754914975839675, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4615414075981669}}
{"text": "/*\n * Copyright 2020-2021 CNRS-UM LIRMM, CNRS-AIST JRL\n */\n\n#include \"coma/Core\"\n#include \"macros.hpp\"\n#include \"doctest/doctest.h\"\n#include <Eigen/QR>\n#include <tuple>\n\nstruct Space4 {\n    static constexpr int space = 4;\n};\n\nstruct Space6 {\n    static constexpr int space = 6;\n};\n\nstruct OrderF {\n    static constexpr int order = 5;\n};\n\nstruct OrderD {\n    static constexpr int order = coma::Dynamic;\n};\n\ntemplate <typename T1, typename T2, typename T3>\nstruct TypeTriple\n{\n    using first_type = T1;\n    using second_type = T2;\n    using third_type = T3;\n};\n\n#define test_triples \\\n    TypeTriple<float, Space4, OrderF>, \\\n    TypeTriple<double, Space4, OrderF>, \\\n    TypeTriple<float, Space6, OrderF>, \\\n    TypeTriple<double, Space6, OrderF>, \\\n    TypeTriple<float, Space4, OrderD>, \\\n    TypeTriple<double, Space4, OrderD>, \\\n    TypeTriple<float, Space6, OrderD>, \\\n    TypeTriple<double, Space6, OrderD>\n\nclass CMTM24 {\n    using PMat = coma::Transform<double>;\n    using MVd = coma::MotionVector<double>;\n\npublic:\n    CMTM24(const PMat& pt, const MVd& n, const MVd& dn, const MVd& ddn)\n        : A(pt)\n        , nu(n)\n        , dnu(dn)\n        , ddnu(ddn)\n    {\n    }\n\n    friend CMTM24 operator*(const CMTM24& lhs, const CMTM24& rhs)\n    {\n        MVd Anu = rhs.A.invMul(lhs.nu);\n        MVd Adnu = rhs.A.invMul(lhs.dnu);\n\n        PMat A = lhs.A * rhs.A;\n        MVd nu = Anu + rhs.nu;\n        MVd dnu = Adnu + rhs.dnu + Anu.cross(rhs.nu);\n        MVd ddnu = rhs.A.invMul(lhs.ddnu) + rhs.ddnu + (Anu.cross(rhs.nu) + 2. * Adnu).cross(rhs.nu) + Anu.cross(rhs.dnu);\n        return CMTM24{ A, nu, dnu, ddnu };\n    }\n\npublic:\n    PMat A;\n    MVd nu;\n    MVd dnu;\n    MVd ddnu;\n};\n\nTEST_CASE_TEMPLATE(\"CMTM\", T, test_triples)\n{\n    using namespace coma;\n    using Scalar = typename T::first_type;\n    constexpr int space = T::second_type::space;\n    constexpr int order = T::third_type::order;\n    constexpr int dynOrder = OrderF::order;\n    using qt_t = Eigen::Quaternion<Scalar>;\n    using v3_t = Eigen::Matrix<Scalar, 3, 1>;\n    using v6_t = Eigen::Matrix<Scalar, 6, 1>;\n    using m3_t = Eigen::Matrix<Scalar, 3, 3>;\n    using mv_t = MotionVector<Scalar>;\n    using cmtm_t = CMTM<Scalar, space, order>;\n    using transform_t = typename cmtm_t::transform_t;\n    using mvx_t = typename cmtm_t::mvx_t;\n\n    DISABLE_CONVERSION_WARNING_BEGIN\n    qt_t q = qt_t::UnitRandom();\n    DISABLE_CONVERSION_WARNING_END\n\n    m3_t R = q.toRotationMatrix();\n    v3_t p = v3_t::Random();\n\n    transform_t A{ R, p };\n    mv_t m{ v6_t::Random() };\n    mvx_t mx{ m, m, m, m, m };\n\n    {\n        // default ctor\n        cmtm_t cmtm;\n        if constexpr (order == Dynamic) {\n            cmtm_t cmtm2{ dynOrder };\n            REQUIRE(cmtm2.order() == dynOrder);\n            REQUIRE(cmtm2.nMat() == dynOrder + 1);\n            REQUIRE(cmtm2.rows() == space * (dynOrder + 1));\n            REQUIRE(cmtm2.rows() == cmtm2.cols());\n            REQUIRE(cmtm2.size() == static_cast<int>(std::pow((dynOrder + 1) * space, 2)));\n            REQUIRE(cmtm2.matrix().size() == cmtm2.size());\n            REQUIRE(cmtm2.matrix(dynOrder / 2) == cmtm2.matrix().template topLeftCorner<space*(dynOrder / 2), space*(dynOrder / 2)>());\n            if constexpr (space == 6) {\n                REQUIRE(cmtm2.dualMatrix().size() == cmtm2.size());\n                REQUIRE(cmtm2.dualMatrix(dynOrder / 2) == cmtm2.dualMatrix().template topLeftCorner<6 * (dynOrder / 2), 6 * (dynOrder / 2)>());\n            }\n        } else {\n            REQUIRE(cmtm.order() == order);\n            REQUIRE(cmtm.nMat() == order + 1);\n            REQUIRE(cmtm.rows() == space * (order + 1));\n            REQUIRE(cmtm.rows() == cmtm.cols());\n            REQUIRE(cmtm.size() == static_cast<int>(std::pow((order + 1) * space, 2)));\n            REQUIRE(cmtm.matrix().size() == cmtm.size());\n            REQUIRE(cmtm.template matrix<order / 2>() == cmtm.matrix().template topLeftCorner<space*(order / 2), space*(order / 2)>());\n            if constexpr (space == 6) {\n                REQUIRE(cmtm.dualMatrix().size() == cmtm.size());\n                REQUIRE(cmtm.template dualMatrix<order / 2>() == cmtm.dualMatrix().template topLeftCorner<6 * (order / 2), 6 * (order / 2)>());\n            }\n        }\n    }\n    {\n        // Identity\n        cmtm_t cmtm;\n        cmtm = cmtm_t::Identity(5);\n        REQUIRE(cmtm.transform() == transform_t::Identity());\n        REQUIRE(cmtm.motion() == mvx_t::Zero(5));\n        if constexpr (order != Dynamic) {\n            cmtm = cmtm_t::Identity();\n            REQUIRE(cmtm.transform() == transform_t::Identity());\n            REQUIRE(cmtm.motion() == mvx_t::Zero());\n        }\n    }\n    {\n        // setIdentity\n        cmtm_t cmtm;\n        cmtm.setIdentity(dynOrder);\n        REQUIRE(cmtm == cmtm_t::Identity(dynOrder));\n        if constexpr (order != Dynamic) {\n            cmtm.transform() = A;\n            cmtm.motion()[0] = m;\n            cmtm.setIdentity();\n            REQUIRE(cmtm == cmtm_t::Identity());\n        }\n    }\n    {\n        // lvalues ctor with tangent vector\n        cmtm_t cmtm{ A, mx };\n        REQUIRE(cmtm.transform() == A);\n        REQUIRE(cmtm.motion() == mx);\n    }\n    {\n        // lvalues ctor without tangent vector\n        cmtm_t cmtm{ A, m, m, m, m, m };\n        REQUIRE(cmtm.transform() == A);\n        REQUIRE(cmtm.motion() == mx);\n    }\n    {\n        // rvalues ctor with tangent vector\n        cmtm_t cmtm{ transform_t{ q, p }, mvx_t{ m, m, m, m, m } };\n        REQUIRE(cmtm.transform() == A);\n        REQUIRE(cmtm.motion() == mx);\n    }\n    {\n        // rvalues ctor without tangent vector\n        mvx_t smi{ v6_t::Ones(), v6_t::Ones(), v6_t::Ones(), v6_t::Ones(), v6_t::Ones() };\n        cmtm_t cmtm{ transform_t{ q, p }, v6_t::Ones(), v6_t::Ones(), v6_t::Ones(), v6_t::Ones(), v6_t::Ones() };\n        REQUIRE(cmtm.transform() == A);\n        REQUIRE(cmtm.motion() == smi);\n    }\n    {\n        // copy ctor\n        cmtm_t cmtm1{ A, m, m, m, m, m };\n        cmtm_t cmtm2{ cmtm1 };\n        REQUIRE(cmtm2.transform() == A);\n        REQUIRE(cmtm2.motion() == mx);\n    }\n    {\n        // move ctor\n        cmtm_t cmtm1{ A, m, m, m, m, m };\n        cmtm_t cmtm2{ std::move(cmtm1) };\n        REQUIRE(cmtm2.transform() == A);\n        REQUIRE(cmtm2.motion() == mx);\n    }\n    {\n        // assign op\n        cmtm_t cmtm1{ A, m, m, m, m, m };\n        cmtm_t cmtm2;\n        cmtm2 = cmtm1;\n        REQUIRE(cmtm2.transform() == A);\n        REQUIRE(cmtm2.motion() == mx);\n    }\n    {\n        // move-assign op\n        cmtm_t cmtm1{ A, m, m, m, m, m };\n        cmtm_t cmtm2;\n        cmtm2 = std::move(cmtm1);\n        REQUIRE(cmtm2.transform() == A);\n        REQUIRE(cmtm2.motion() == mx);\n    }\n    {\n        // lvalues set with tangent vector\n        cmtm_t cmtm;\n        cmtm.set(A, mx);\n        REQUIRE(cmtm.transform() == A);\n        REQUIRE(cmtm.motion() == mx);\n    }\n    {\n        // lvalues set without tangent vector\n        cmtm_t cmtm;\n        cmtm.set(A, m, m, m, m, m);\n        REQUIRE(cmtm.transform() == A);\n        REQUIRE(cmtm.motion() == mx);\n    }\n    {\n        // rvalues ctor with tangent vector\n        cmtm_t cmtm;\n        cmtm.set(transform_t{ q, p }, mvx_t{ m, m, m, m, m });\n        REQUIRE(cmtm.transform() == A);\n        REQUIRE(cmtm.motion() == mx);\n    }\n    {\n        // rvalues ctor without tangent vector\n        mvx_t smi{ v6_t::Ones(), v6_t::Ones(), v6_t::Ones(), v6_t::Ones(), v6_t::Ones() };\n        cmtm_t cmtm;\n        cmtm.set(transform_t{ q, p }, v6_t::Ones(), v6_t::Ones(), v6_t::Ones(), v6_t::Ones(), v6_t::Ones());\n        REQUIRE(cmtm.transform() == A);\n        REQUIRE(cmtm.motion() == smi);\n    }\n    {\n        // deconstruction\n        cmtm_t cmtm{ A, mx };\n        cmtm.deconstruct();\n        REQUIRE(cmtm.transform() == A);\n        REQUIRE(cmtm.motion().isApprox(mx));\n    }\n    {\n        // operator==(CMTM6n)\n        cmtm_t cmtm1{ A, m, m, m, m, m };\n        cmtm_t cmtm2{ A, m, m, m, m, m };\n        REQUIRE(cmtm1 == cmtm2);\n    }\n    {\n        // operator!=(CMTM6n)\n        cmtm_t cmtm1{ A, m, m, m, m, m };\n        cmtm_t cmtm2{ transform_t::Identity(), m, m, m, m, m };\n        REQUIRE(cmtm1 != cmtm2);\n        for (int i = 0; i < order; ++i) {\n            mvx_t smt{ m, m, m, m, m };\n            smt[i] = mv_t::Zero();\n            cmtm_t cmtm3{ A, smt };\n            REQUIRE(cmtm1 != cmtm3);\n        }\n    }\n    {\n        // isApprox(CMTM6n)\n        m3_t m_eps = m3_t::Ones() * 0.1 * dummy_precision<Scalar>();\n        v6_t v_eps = v6_t::Ones() * 0.1 * dummy_precision<Scalar>();\n        cmtm_t cmtm1{ A, m, m, m, m, m };\n        cmtm_t cmtm2{ transform_t{ R + m_eps, p }, m, m, m, m, m };\n        REQUIRE(cmtm1 != cmtm2);\n        REQUIRE(cmtm1.isApprox(cmtm2));\n        for (int i = 0; i < order; ++i) {\n            mvx_t smt{ m, m, m, m, m };\n            smt[i] = mv_t{ m.vector() + v_eps };\n            cmtm_t cmtm3{ A, smt };\n            REQUIRE(cmtm1 != cmtm3);\n            REQUIRE(cmtm1.isApprox(cmtm2));\n        }\n    }\n}\n\nTEST_CASE(\"CMTM 0-order\")\n{\n    using namespace coma;\n    using cmtm0_t = CMTM<double, 4, 0>;\n    using cmtmd_t = CMTM<double, 4, Dynamic>;\n\n    {\n        // Init\n        cmtm0_t cmtm0{};\n        cmtmd_t cmtmd{ 0 };\n        REQUIRE(cmtm0.order() == 0);\n        REQUIRE(cmtmd.order() == 0);\n        REQUIRE(cmtm0.nMat() == 1);\n        REQUIRE(cmtmd.nMat() == 1);\n        REQUIRE(cmtm0.rows() == 4);\n        REQUIRE(cmtmd.rows() == 4);\n        REQUIRE(cmtm0.cols() == 4);\n        REQUIRE(cmtmd.cols() == 4);\n        REQUIRE(cmtm0.size() == 16);\n        REQUIRE(cmtmd.size() == 16);\n        REQUIRE(cmtm0.matrix().size() == cmtm0.size());\n        REQUIRE(cmtmd.matrix().size() == cmtmd.size());\n    }\n    {\n        // Resize\n        cmtm0_t cmtm0{};\n        cmtmd_t cmtmd;\n        cmtm0.resize(0);\n        cmtmd.resize(1);\n        REQUIRE(cmtmd.order() == 1);\n        REQUIRE(cmtmd.nMat() == 2);\n        REQUIRE(cmtmd.rows() == 8);\n        REQUIRE(cmtmd.cols() == 8);\n        REQUIRE(cmtmd.size() == 64);\n        REQUIRE(cmtmd.matrix().size() == cmtmd.size());\n    }\n}\n\nTEST_CASE_TEMPLATE(\"CMTM operations\", T, Space4, Space6)\n{\n    using namespace coma;\n    constexpr int space = T::space;\n    constexpr int order = 3;\n    Eigen::Matrix3d R = Eigen::Quaterniond::UnitRandom().toRotationMatrix();\n    Eigen::Vector3d p = Eigen::Vector3d::Random();\n    Transform<double> A{ R, p };\n    MotionVector<double> nu{ Eigen::Vector6d::Random() };\n    MotionVector<double> dnu{ Eigen::Vector6d::Random() };\n    MotionVector<double> ddnu{ Eigen::Vector6d::Random() };\n\n    CMTM24 c1{ Transform<double>{ R, p }, nu, dnu, ddnu };\n    CMTM24 c2{ Transform<double>{ R, p }, nu, dnu, ddnu };\n    MotionVectorX<double, order> mvx1{ nu, dnu, ddnu };\n    MotionVectorX<double, order> mvx2{ nu, dnu, ddnu };\n    CMTM<double, space, order> c3{ A, mvx1 };\n    CMTM<double, space, order> c4{ A, mvx2 };\n\n    auto c12 = c1 * c2;\n    auto c34 = c3 * c4;\n    REQUIRE(c34.order() == order);\n\n    auto checkEq = [](auto c1, auto c2) {\n        REQUIRE(c1.angular().isApprox(c2.angular()));\n        REQUIRE(c1.linear().isApprox(c2.linear()));\n    };\n\n    auto motions34 = c34.motion();\n\n    // Multiplication test\n    REQUIRE(c12.A.rotation() == c34.transform().rotation());\n    REQUIRE(c12.A.translation() == c34.transform().translation());\n    checkEq(c12.nu, motions34[0]);\n    checkEq(c12.dnu, motions34[1]);\n    checkEq(c12.ddnu, motions34[2]);\n\n    // Matrix test\n    REQUIRE(c34.matrix().isApprox(c3.matrix() * c4.matrix()));\n\n    // Dual matrix test\n    if constexpr (space == 6) {\n        REQUIRE(c34.dualMatrix().isApprox(c3.dualMatrix() * c4.dualMatrix()));\n        Eigen::Vector6d randVec = Eigen::Vector6d::Random();\n        ForceVector<double> fv{ randVec };\n        MotionVector<double> mv{ randVec };\n\n        const auto& factors = factorial_factors<double, order + 1>;\n        MotionVectorX<double, order + 1> v{ mv, mv, mv, mv };\n        ForceVectorX<double, order + 1> f{ fv, fv, fv, fv };\n        Eigen::Matrix<double, 6 * (order + 1), 1> v2, f2;\n        v2 << randVec, randVec, randVec, randVec;\n        f2 << randVec, randVec, randVec, randVec;\n        for (int i = 0; i < order + 1; ++i) {\n            size_t ui = static_cast<size_t>(i);\n            v2.segment<6>(6 * i) /= factors[ui];\n            f2.segment<6>(6 * i) /= factors[ui];\n        }\n        Eigen::VectorXd vr = c3.matrix() * v2;\n        Eigen::VectorXd fr = c3.dualMatrix() * f2;\n        for (int i = 0; i < order + 1; ++i) {\n            size_t ui = static_cast<size_t>(i);\n            vr.segment<6>(6 * i) *= factors[ui];\n            fr.segment<6>(6 * i) *= factors[ui];\n        }\n\n        auto c3v = c3 * v;\n        auto c3f = c3.dualMul(f);\n        REQUIRE(c3v.vector().isApprox(vr));\n        REQUIRE(c3f.vector().isApprox(fr));\n    }\n\n    // Inverse test\n    Eigen::ColPivHouseholderQR<Eigen::MatrixXd> qr{ c3.rows(), c3.cols() };\n    Eigen::MatrixXd c3Inv = c3.inverse().matrix();\n    Eigen::MatrixXd m3Inv = qr.compute(c3.matrix()).inverse();\n    Eigen::MatrixXd c34Inv = c34.inverse().matrix();\n    Eigen::MatrixXd m34Inv = qr.compute(c34.matrix()).inverse();\n\n    REQUIRE(c3.inverse().matrix().isApprox(qr.compute(c3.matrix()).inverse(), dummy_precision<double>()));\n    REQUIRE(c34.inverse().matrix().isApprox(qr.compute(c34.matrix()).inverse(), dummy_precision<double>()));\n\n    // test for Dynamic\n    MotionVectorX<double, Dynamic> mvxd{ nu, dnu, ddnu };\n    CMTM<double, space, Dynamic> c5{ A, mvxd };\n    CMTM<double, space, Dynamic> c6;\n    c6.set(A, nu, dnu, ddnu);\n\n    auto c56 = c5 * c6;\n\n    auto motions56 = c56.motion();\n\n    // Test\n    REQUIRE(c12.A.rotation() == c56.transform().rotation());\n    REQUIRE(c12.A.translation() == c56.transform().translation());\n    checkEq(c12.nu, motions56[0]);\n    checkEq(c12.dnu, motions56[1]);\n    checkEq(c12.ddnu, motions56[2]);\n\n    c6.set(A, nu, dnu, ddnu, MotionVector<double>{ Eigen::Vector6d::Random() });\n    REQUIRE_THROWS_AS(c5 * c6, std::runtime_error);\n}\n", "meta": {"hexsha": "261f9866f89d859b8f4fcee95e49395dda8adef3", "size": 13958, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/cmtm_test.cpp", "max_stars_repo_name": "vsamy/coma", "max_stars_repo_head_hexsha": "8380d84f7ab5bd523f6fe1d7597466e1036a830f", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-08-16T11:40:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-04T16:48:32.000Z", "max_issues_repo_path": "test/cmtm_test.cpp", "max_issues_repo_name": "vsamy/coma", "max_issues_repo_head_hexsha": "8380d84f7ab5bd523f6fe1d7597466e1036a830f", "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": "test/cmtm_test.cpp", "max_forks_repo_name": "vsamy/coma", "max_forks_repo_head_hexsha": "8380d84f7ab5bd523f6fe1d7597466e1036a830f", "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.8423529412, "max_line_length": 143, "alphanum_fraction": 0.5454219802, "num_tokens": 4405, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.754914975839675, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4615414075981669}}
{"text": "/* vim: set sw=4 sts=4 et foldmethod=syntax : */\n\n#include <gcs/constraints/all_different.hh>\n#include <gcs/constraints/arithmetic.hh>\n#include <gcs/constraints/comparison.hh>\n#include <gcs/constraints/abs.hh>\n#include <gcs/problem.hh>\n#include <gcs/solve.hh>\n\n#include <cstdlib>\n#include <iostream>\n#include <string>\n#include <vector>\n\n#include <boost/program_options.hpp>\n\nusing namespace gcs;\n\nusing std::cerr;\nusing std::cout;\nusing std::endl;\nusing std::string;\nusing std::to_string;\nusing std::pair;\nusing std::vector;\n\nusing namespace std::literals::string_literals;\n\nnamespace po = boost::program_options;\n\nauto main(int argc, char * argv[]) -> int\n{\n    po::options_description display_options{ \"Program options\" };\n    display_options.add_options()\n        (\"help\", \"Display help information\")\n        (\"prove\", \"Create a proof\");\n\n    po::options_description all_options{ \"All options\" };\n    all_options.add_options()\n        (\"abs\", \"Use abs constraint\")\n        ;\n\n    all_options.add(display_options);\n\n    po::variables_map options_vars;\n\n    try {\n        po::store(po::command_line_parser(argc, argv)\n                .options(all_options)\n                .run(), options_vars);\n        po::notify(options_vars);\n    }\n    catch (const po::error & e) {\n        cerr << \"Error: \" << e.what() << endl;\n        cerr << \"Try \" << argv[0] << \" --help\" << endl;\n        return EXIT_FAILURE;\n    }\n\n    if (options_vars.count(\"help\")) {\n        cout << \"Usage: \" << argv[0] << \" [options] [size]\" << endl;\n        cout << endl;\n        cout << display_options << endl;\n        return EXIT_SUCCESS;\n    }\n\n    Problem p = options_vars.count(\"prove\") ? Problem{ Proof{ \"crystal_maze.opb\", \"crystal_maze.veripb\" } } : Problem{ };\n\n    vector<IntegerVariableID> xs;\n    for (int i = 0 ; i < 8 ; ++i)\n        xs.push_back(p.create_integer_variable(1_i, 8_i, \"box\" + to_string(i)));\n\n    p.post(AllDifferent{ xs });\n    p.branch_on(xs);\n\n    vector<pair<int, int> > edges{ { 0, 1 }, { 0, 2 }, { 0, 3 }, { 0, 4 },\n        { 1, 3 }, { 1, 4 }, { 1, 5 }, { 2, 3 }, { 2, 6 }, { 3, 4 }, { 3, 6 },\n        { 3, 7 }, { 4, 5 }, { 4, 6 }, { 4, 7 }, { 5, 7 }, { 6, 7 } };\n\n    vector<IntegerVariableID> diffs, abs_diffs;\n    for (auto & [ x1, x2 ] : edges) {\n        diffs.push_back(p.create_integer_variable(-7_i, 7_i, \"diff\" + to_string(x1) + \"_\" + to_string(x2)));\n        if (options_vars.count(\"abs\")) {\n            abs_diffs.push_back(p.create_integer_variable(2_i, 7_i, \"absdiff\" + to_string(x1) + \"_\" + to_string(x2)));\n            p.post(Abs{ diffs.back(), abs_diffs.back() });\n        }\n        else {\n            p.post(NotEquals{ diffs.back(), constant_variable(0_i) });\n            p.post(NotEquals{ diffs.back(), constant_variable(1_i) });\n            p.post(NotEquals{ diffs.back(), constant_variable(-1_i) });\n        }\n\n        p.post(Minus{ xs[x1], xs[x2], diffs.back() });\n    }\n\n    auto stats = solve(p, [&] (const State & s) -> bool {\n            cout << \"  \" << s(xs[0]) << \" \" << s(xs[1]) << endl;\n            cout << s(xs[2]) << \" \" << s(xs[3]) << \" \" << s(xs[4]) << \" \" << s(xs[5]) << endl;\n            cout << \"  \" << s(xs[6]) << \" \" << s(xs[7]) << endl;\n            cout << endl;\n            return true;\n            });\n\n    cout << stats;\n\n    return EXIT_SUCCESS;\n}\n\n", "meta": {"hexsha": "e242ff22d19f80121986fbf0b307412c6f1bfba5", "size": 3291, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/crystal_maze/crystal_maze.cc", "max_stars_repo_name": "ciaranm/glasgow-constraint-solver", "max_stars_repo_head_hexsha": "39d925c776474743a51a80492585db3a07801908", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-08-13T11:36:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T11:13:04.000Z", "max_issues_repo_path": "examples/crystal_maze/crystal_maze.cc", "max_issues_repo_name": "ciaranm/glasgow-constraint-solver", "max_issues_repo_head_hexsha": "39d925c776474743a51a80492585db3a07801908", "max_issues_repo_licenses": ["MIT"], "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/crystal_maze/crystal_maze.cc", "max_forks_repo_name": "ciaranm/glasgow-constraint-solver", "max_forks_repo_head_hexsha": "39d925c776474743a51a80492585db3a07801908", "max_forks_repo_licenses": ["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.4722222222, "max_line_length": 121, "alphanum_fraction": 0.5515041021, "num_tokens": 952, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152325073083131, "lm_q2_score": 0.5660185351961013, "lm_q1q2_score": 0.46143670963089634}}
{"text": "/*\n * simulated_telemetry_server.cpp\n *\n *  Created on: Dec 5, 2018\n *      Author: ttw2xk\n */\n\n\n\n#include \"f1_datalogger/car_data/f1_2018/car_data.h\"\n#include \"f1_datalogger/car_data/f1_2020/car_data.h\"\n#include <boost/program_options.hpp>\n#include <iostream>\n#include <boost/asio.hpp>\n#include <memory>\n#include <thread>\n#include <math.h> \n#include <boost/math/constants/constants.hpp>\n#include <boost/math_fwd.hpp>\nnamespace po = boost::program_options;\nvoid exit_with_help(po::options_description& desc)\n{\n        std::stringstream ss;\n        ss << \"F1 Simulated Telemetry Server. Command line arguments are as follows:\" << std::endl;\n        desc.print(ss);\n        std::printf(\"%s\", ss.str().c_str());\n        exit(0); // @suppress(\"Invalid arguments\")\n}\nint main(int argc, char** argv) {\n        using boost::asio::ip::udp;\n        using namespace deepf1;\n        using namespace deepf1::twenty_eighteen;\n\tunsigned int packet_size = sizeof(deepf1::twenty_eighteen::PacketMotionData);// BUFLEN;\n        unsigned int sleep_time;\n\n        std::string address, port;\n        po::options_description desc(\"Allowed Options\");\n\t\n        try{\n                desc.add_options()\n                (\"help,h\", \"Displays options and exits\")\n                (\"address,a\", po::value<std::string>(&address)->default_value(\"127.0.0.1\"), \"IPv4 Address to send data to\")\n                (\"port_number,p\", po::value<std::string>(&port)->default_value(\"20777\"), \"Port number to send data to\")\n                (\"sleep_time,s\", po::value<unsigned int>(&sleep_time)->default_value(17), \"Number of milliseconds to sleep between simulated packets\")\n                ;\n\t        po::variables_map vm;\n                po::store(po::parse_command_line(argc, argv, desc), vm);\n                po::notify(vm);\n                if (vm.find(\"help\") != vm.end()) {\n                        exit_with_help(desc);\n                }\n        }catch(boost::exception& e){\n                exit_with_help(desc);\n        }\n        boost::asio::io_service io_service;\n        udp::resolver resolver(io_service);\n        udp::resolver::query query(udp::v4(), address, port);\n        udp::endpoint receiver_endpoint = *resolver.resolve(query);\n        udp::socket socket(io_service);\n        socket.open(udp::v4());\n\n\n        std::shared_ptr<PacketCarTelemetryData> data(new PacketCarTelemetryData);\n        data->m_header.m_packetFormat=2018;\n        data->m_header.m_packetId=PacketID::CARTELEMETRY;\n        data->m_header.m_packetVersion=18;\n        data->m_header.m_playerCarIndex=0;\n        float fake_time = 0;\n        float dt = 1E-3*( (float) sleep_time );\n        float period = 1.0;\n        float freq=1/period;\n\tfloat pi = boost::math::constants::pi<float>();\n\tfloat twopi = boost::math::constants::two_pi<float>();\n        float factor = 2.0;\n        int id=0;\n        while (true) {\n                data->m_header.m_frameIdentifier=id;\n                data->m_header.m_sessionTime=fake_time;\n                data->m_header.m_sessionUID=id;\n                data->m_carTelemetryData[data->m_header.m_playerCarIndex].m_steer = (int8_t)(100.0*std::sin(twopi*freq*fake_time));\n                data->m_carTelemetryData[data->m_header.m_playerCarIndex].m_throttle = (uint8_t)50 + (uint8_t)(50.0*std::cos(twopi*freq*fake_time));\n                data->m_carTelemetryData[data->m_header.m_playerCarIndex].m_brake = (uint8_t)50;\n                std::printf(\"Sending fake UDP data\\n\");\n                std::printf(\"Fake Time: %f.\\n\", fake_time);\n                std::printf(\"Steering: %d.\\n\", data->m_carTelemetryData[data->m_header.m_playerCarIndex].m_steer);\n                std::printf(\"Throttle: %u.\\n\", data->m_carTelemetryData[data->m_header.m_playerCarIndex].m_throttle);\n                std::printf(\"Brake: %u.\\n\", data->m_carTelemetryData[data->m_header.m_playerCarIndex].m_brake);\n                socket.send_to(boost::asio::buffer(boost::asio::buffer(data.get(), packet_size)), receiver_endpoint);\n                fake_time += dt;\n                id++;\n                std::this_thread::sleep_for(std::chrono::milliseconds(sleep_time));\n        }\n        return 0;\n\t\t/* */\n}\n", "meta": {"hexsha": "c99af64559365212515703bfcea19b733d35f9c5", "size": 4145, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "data-logger/src/udp_logging/simulated_telemetry_server.cpp", "max_stars_repo_name": "linklab-uva/deepracing", "max_stars_repo_head_hexsha": "fc25c47658277df029e7399d295d97a75fe85216", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2020-06-29T15:21:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-12T00:42:26.000Z", "max_issues_repo_path": "data-logger/src/udp_logging/simulated_telemetry_server.cpp", "max_issues_repo_name": "linklab-uva/deepracing", "max_issues_repo_head_hexsha": "fc25c47658277df029e7399d295d97a75fe85216", "max_issues_repo_licenses": ["Apache-2.0"], "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-logger/src/udp_logging/simulated_telemetry_server.cpp", "max_forks_repo_name": "linklab-uva/deepracing", "max_forks_repo_head_hexsha": "fc25c47658277df029e7399d295d97a75fe85216", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-01-23T23:36:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-02T00:18:37.000Z", "avg_line_length": 43.1770833333, "max_line_length": 150, "alphanum_fraction": 0.6130277443, "num_tokens": 1031, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152325073083131, "lm_q2_score": 0.5660185351961013, "lm_q1q2_score": 0.46143670963089634}}
{"text": "#ifndef SYMMETRICCORRESPONDENCEFILTER_HPP\n#define SYMMETRICCORRESPONDENCEFILTER_HPP\n\n#include <Eigen/Dense>\n#include <Eigen/SparseCore>\n#include <stdio.h>\n#include \"../global.hpp\"\n#include \"BaseCorrespondenceFilter.hpp\"\n#include \"CorrespondenceFilter.hpp\"\n#include \"helper_functions.hpp\"\n\ntypedef Eigen::VectorXf VecDynFloat;\ntypedef Eigen::Matrix< float, Eigen::Dynamic, registration::NUM_FEATURES> FeatureMat; //matrix Mx6 of type float\ntypedef Eigen::Matrix< float, 1, registration::NUM_FEATURES> FeatureVec; //matrix Mx6 of type float\ntypedef Eigen::Vector3f Vec3Float;\ntypedef Eigen::SparseMatrix<float, 0, int> SparseMat;\ntypedef Eigen::Triplet<float> Triplet;\ntypedef Eigen::Matrix< int, Eigen::Dynamic, Eigen::Dynamic> MatDynInt; //matrix MxN of type unsigned int\ntypedef Eigen::Matrix< float, Eigen::Dynamic, Eigen::Dynamic> MatDynFloat;\n\nnamespace registration {\n\nclass SymmetricCorrespondenceFilter: public BaseCorrespondenceFilter\n{\n    /*\n    # GOAL\n    For each element in inFloatingFeatures, we're going to find corresponding\n    features in the elements of inTargetFeatures.\n\n    A push-pull approach is used to find correspondences. Not only\n    will we look for correspondences for inFloatingFeatures in the\n    inTargetFeatures set, we'll also do the opposite: find correspondences for\n    the inTargetFeatures set in the inFloatingFeatures set. These findings are\n    combined which creates an effect where the inTargetFeatures sort of attract\n    the inFloatingFeatures towards itself.\n\n    # INPUTS\n    -inFloatingFeatures\n    -inTargetFeatures\n    -inTargetFlags\n\n    # PARAMETERS\n    -numNeighbours(=3):\n    number of nearest neighbours\n    -flagThreshold(=0.9):\n    threshold that the weighted corresponding flag needs to make in order to be flagged as 1.0.\n    Otherwise, it receives flag 0.0f.\n\n    # OUTPUT\n    -outCorrespondingFeatures\n    -outCorrespondingFlags\n    */\n\n    public:\n        //CorrespondenceFilter(); //default constructor\n        //~CorrespondenceFilter(); //destructor\n\n        void set_floating_input(const FeatureMat * const inFloatingFeatures,\n                                const VecDynFloat * const inFloatingFlags);\n        void set_target_input(const FeatureMat * const inTargetFeatures,\n                            const VecDynFloat * const inTargetFlags);\n        void set_parameters(const size_t numNeighbours,\n                            const float flagThreshold,\n                            const bool _equalizePushPull);\n        void update();\n\n    protected:\n\n    private:\n\n        //# Internal Data structures\n        CorrespondenceFilter _pushFilter;\n        CorrespondenceFilter _pullFilter;\n\n        //# Parameters\n        bool _equalizePushPull = false;\n\n        //# Internal functions\n        //## Function to update the internal push and pull correspondence filters\n        void _update_push_and_pull();\n        //## Function to convert the sparse affinity weights into corresponding\n        //## features and flags\n        void _affinity_to_correspondences();\n};\n\n}//namespace registration\n\n#endif // SYMMETRICCORRESPONDENCEFILTER_HPP\n", "meta": {"hexsha": "7883b3b15fce4f7454d3e5cd0a2e09774588d079", "size": 3106, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/SymmetricCorrespondenceFilter.hpp", "max_stars_repo_name": "brisyramshere/meshmonk", "max_stars_repo_head_hexsha": "a0a7cf79902541cf9c800d83a4d4f14fcd756f6f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 53.0, "max_stars_repo_stars_event_min_datetime": "2017-02-03T14:59:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T05:40:58.000Z", "max_issues_repo_path": "src/SymmetricCorrespondenceFilter.hpp", "max_issues_repo_name": "brisyramshere/meshmonk", "max_issues_repo_head_hexsha": "a0a7cf79902541cf9c800d83a4d4f14fcd756f6f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 16.0, "max_issues_repo_issues_event_min_datetime": "2018-07-16T10:34:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-18T04:37:12.000Z", "max_forks_repo_path": "src/SymmetricCorrespondenceFilter.hpp", "max_forks_repo_name": "brisyramshere/meshmonk", "max_forks_repo_head_hexsha": "a0a7cf79902541cf9c800d83a4d4f14fcd756f6f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 23.0, "max_forks_repo_forks_event_min_datetime": "2018-07-05T14:59:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T07:01:47.000Z", "avg_line_length": 34.8988764045, "max_line_length": 112, "alphanum_fraction": 0.7163554411, "num_tokens": 690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.5660185351961016, "lm_q1q2_score": 0.4614366994672905}}
{"text": "#include \"kalman_filter.hpp\"\n#include \"kalman_filter_cache.hpp\"\n#include \"samplers.hpp\"\n#include \"sampling/simple.hpp\"\n\n#include <boost/foreach.hpp>\n#include <boost/random.hpp>\n//#include <boost/random/exponential_distribution.hpp>\n#include <boost/shared_ptr.hpp>\n#include <cmath>\n#include <ctime>\n#include <Eigen/Cholesky>\n#include <Eigen/Dense>\n#include <limits>\n#include <cmath>\n\nextern \"C\" {\n#include \"third-party/gen_beta.h\"\n}\n\n#include \"detail/random.hpp\"\n\nnamespace biggles\n{\n\nvoid sample_birth_rate_given_partition_orig(const partition& part_sample, model::parameters& params) {\n    off_t n_total_born(part_sample.tracks().size());\n    model::mean_new_tracks_per_frame(params) = sampling::sample_gamma(1.f + n_total_born, 1.f) /\n        static_cast<float>(part_sample.duration());\n    if (not std::isfinite(model::mean_new_tracks_per_frame(params))) {\n        std::cerr << \"duration = \" << part_sample.duration() << std::endl;\n        std::cerr << \"number of tracks = \" << n_total_born << std::endl;\n        std::cerr << \"sampled birth rate = \" << model::mean_new_tracks_per_frame(params) << std::endl;\n        BOOST_ASSERT(std::isfinite(model::mean_new_tracks_per_frame(params)));\n    }\n    //BOOST_ASSERT(model::mean_new_tracks_per_frame(params)>0.f);\n    if (model::mean_new_tracks_per_frame(params) == 0.f)\n        model::mean_new_tracks_per_frame(params) = std::numeric_limits<float>::min();\n}\n\nvoid sample_birth_rate_given_partition_alt(const partition& part_sample, model::parameters& params) {\n    off_t n_total_born(part_sample.tracks().size());\n    const size_t min_surv(1);\n    model::mean_new_tracks_per_frame(params) = sampling::sample_gamma(1.f + n_total_born, 1.f) /\n        static_cast<float>(part_sample.duration() - min_surv); // no birth in the last frames\n    BOOST_ASSERT(std::isfinite(model::mean_new_tracks_per_frame(params)));\n    BOOST_ASSERT(model::mean_new_tracks_per_frame(params)>0.f);\n}\n\nvoid sample_birth_rate_given_partition(const partition& part_sample, model::parameters& params) {\n    sample_birth_rate_given_partition_orig(part_sample, params);\n}\n\nvoid sample_clutter_rate_given_partition(const partition& part_sample, model::parameters& params) {\n    off_t n_total_false(part_sample.clutter().size());\n    model::mean_false_observations_per_frame(params) = sampling::sample_gamma(1 + n_total_false, 1.f) /\n        static_cast<float>(part_sample.duration());\n    if (not std::isfinite(model::mean_false_observations_per_frame(params))) {\n        std::cerr << \"number of clutter = \" << n_total_false << std::endl;\n        std::cerr << \"partition duration = \" << part_sample.duration() << std::endl;\n        std::cerr << \"sampled clutter rate = \" << model::mean_false_observations_per_frame(params) << std::endl;\n        throw std::logic_error(\"clutter rate sampling returned a not finite value\");\n    }\n    if (model::mean_false_observations_per_frame(params) == 0.f)\n        model::mean_false_observations_per_frame(params) = std::numeric_limits<float>::min();\n}\n\nvoid sample_observation_probability_given_partition_orig(const partition& part_sample, model::parameters& params) {\n\n    if (part_sample.tracks().empty()) {\n        model::generate_observation_probability(params) = sampling::uniform_real(0.f, 1.f);\n        return;\n    }\n    off_t n_total_generated(0);\n    off_t sum_of_durations(0);\n    // calculate sum_of_durations and n_total_generated\n    BOOST_FOREACH(const boost::shared_ptr<const track>& t_ptr, part_sample.tracks())\n    {\n        sum_of_durations += t_ptr->duration();\n        // the track's size is the number of observations within it\n        n_total_generated += t_ptr->size();\n    }\n    //BOOST_ASSERT(n_total_generated > 0); // there would be no tracks otherwise\n    // the 1.0001s below should be 1 but the sampling functions for beta distributions hit an infinite loop if the sizes\n    // are zero.\n    // beta(1,1) is uniform distribution FIXME\n    model::generate_observation_probability(params) =\n        sampling::sample_beta(1.0001f + n_total_generated, 1.0001f + (sum_of_durations - n_total_generated));\n\n}\n\nvoid sample_observation_probability_given_partition_alt(const partition& part_sample, model::parameters& params) {\n\n    if (part_sample.tracks().empty()) {\n        model::generate_observation_probability(params) = sampling::uniform_real(0.f, 1.f);\n        return;\n    }\n    off_t n_total_generated(0);\n    off_t sum_of_durations(0);\n    const size_t min_obs(2);\n    // calculate sum_of_durations and n_total_generated\n    BOOST_FOREACH(const boost::shared_ptr<const track>& t_ptr, part_sample.tracks())\n    {\n        sum_of_durations += t_ptr->duration() - min_obs;\n        n_total_generated += t_ptr->size() - min_obs;\n    }\n    BOOST_ASSERT(n_total_generated >= 0);\n    BOOST_ASSERT(sum_of_durations >= n_total_generated);\n    model::generate_observation_probability(params) =\n        sampling::sample_beta(1.0001f + n_total_generated, 1.0001f + sum_of_durations - n_total_generated);\n}\n\nvoid sample_observation_probability_given_partition(const partition& part_sample, model::parameters& params) {\n    sample_observation_probability_given_partition_orig(part_sample, params);\n}\n\n\nvoid sample_survival_probability_given_partition_orig(const partition& part_sample, model::parameters& params) {\n    if(part_sample.tracks().empty()) {\n        model::frame_to_frame_survival_probability(params) = sampling::uniform_real(0.f, 1.f);\n        return;\n    }\n\n    off_t n_total_died(part_sample.tracks().size()); // everything that has a beginning has an end, Neo. Whatever.\n    off_t n_total_survived(0);\n\n    // calculate n_total_survived\n    BOOST_FOREACH(const boost::shared_ptr<const track>& t_ptr, part_sample.tracks())\n    {\n        // a track 'survives' for one fewer ticks than it's duration\n        if(t_ptr->duration() >= 1)\n            n_total_survived += t_ptr->duration() - 1;\n    }\n    //BOOST_ASSERT(n_total_survived > 0); // there would be no tracks otherwise\n    //BOOST_ASSERT(n_total_died > 0); // there would be no tracks otherwise\n    do model::frame_to_frame_survival_probability(params) = sampling::sample_beta(\n            1.0001f + n_total_survived, 1.0001f + n_total_died);\n    while (model::frame_to_frame_survival_probability(params) == 1.f);\n}\n\nvoid sample_survival_probability_given_partition_alt(const partition& part_sample, model::parameters& params) {\n    if(part_sample.tracks().empty()) {\n        model::frame_to_frame_survival_probability(params) = sampling::uniform_real(0.f, 1.f);\n        return;\n    }\n\n    off_t n_total_died(0);\n    off_t n_total_survived(0);\n\n    const size_t min_surv(1);\n\n    // calculate n_total_survived\n    // a track 'survives' for one fewer ticks than it's duration and one survival is guaranteed\n    BOOST_FOREACH(const boost::shared_ptr<const track>& t_ptr, part_sample.tracks()) {\n        n_total_survived += t_ptr->duration() - 1 - min_surv ;\n        n_total_died += off_t(t_ptr->last_time_stamp() < part_sample.last_time_stamp());\n    }\n    BOOST_ASSERT(n_total_survived >= 0);\n    BOOST_ASSERT(n_total_died >= 0);\n    model::frame_to_frame_survival_probability(params) = sampling::sample_beta(1.0001f + n_total_survived, 1.0001f + n_total_died);\n}\n\nvoid sample_survival_probability_given_partition(const partition& part_sample, model::parameters& params) {\n    sample_survival_probability_given_partition_orig(part_sample, params);\n}\n\nvoid sample_tracking_control_parameters_given_partition(const partition& partition, model::parameters& params) {\n    sample_birth_rate_given_partition(partition, params);\n    sample_clutter_rate_given_partition(partition, params);\n    sample_observation_probability_given_partition(partition, params);\n    sample_survival_probability_given_partition(partition, params);\n}\n\nvoid sample_observation_error_given_partition(const partition& partition, model::parameters& params) {\n    // special case: no tracks. sample from a fairly all-encompassing distribution\n    if (not is_symmetric(model::observation_error_covariance(params))) {\n        std::cout << measure_asymmetry(model::observation_error_covariance(params)) << std::endl;\n        throw std::runtime_error(\"R is not symmetric at the start\");\n    }\n\n    if(partition.tracks().empty())\n    {\n        model::observation_error_covariance(params) = sampling::sample_inverse_wishart(Eigen::Matrix2f::Identity() * 2.f, 5);\n        //model::observation_error_covariance(params) = Eigen::Matrix2f::Identity() * 0.09f; // FIXME PRIOR calculation\n        return;\n    }\n\n    if (not is_symmetric(model::observation_error_covariance(params))) {\n        std::cout << measure_asymmetry(model::observation_error_covariance(params)) << std::endl;\n        throw std::runtime_error(\"R is not symmetric after track empty.\");\n    }\n\n    // calculate Wishart Phi parameters for sampling R\n\n    // this is the Wishart prior\n    Eigen::Matrix2f Phi = Eigen::Matrix2f::Identity() * 2.f;\n    size_t s = 5;\n\n    if (not is_symmetric(Phi)) {\n        std::cout << measure_asymmetry(Phi) << std::endl;\n        throw std::runtime_error(\"Phi is not symmetric after init\");\n    }\n\n\n\n    // update parameters for each track\n    BOOST_FOREACH(const boost::shared_ptr<const track>& t_ptr, partition.tracks())\n    {\n        Phi += wishart_phi_parameter_for_track(t_ptr, params);\n        s += t_ptr->size(); // number of observations in track\n    }\n\n    if (not is_symmetric(Phi)) {\n        std::cout << measure_asymmetry(Phi) << std::endl;\n        throw std::runtime_error(\"Phi is not symmetric after update\");\n    }\n\n    model::observation_error_covariance(params) = sampling::sample_inverse_wishart(Phi, s);\n    //model::observation_error_covariance(params) = Eigen::Matrix2f::Identity() * 0.09f; // FIXME PRIOR test\n    if (not is_symmetric(model::observation_error_covariance(params))) {\n        std::cout << measure_asymmetry(model::observation_error_covariance(params)) << std::endl;\n        throw std::runtime_error(\"R is not symmetric after sampling.\");\n    }\n\n\n}\n\nvoid sample_model_parameters_given_partition(const partition& partition, model::parameters& params) {\n    sample_tracking_control_parameters_given_partition(partition, params);\n    /*\n    model::mean_new_tracks_per_frame(params) = 0.2f; // FIXME PRIOR calculation\n    model::mean_false_observations_per_frame(params) = 0.01f; // FIXME PRIOR calculation\n    model::generate_observation_probability(params) = .9f; // FIXME PRIOR calculation\n    model::frame_to_frame_survival_probability(params) = .9f; // FIXME PRIOR calculation\n    */\n\n    // sample constraint radius [removed]\n\n    sample_observation_error_given_partition(partition, params);\n\n}\n\nEigen::Matrix2f wishart_phi_parameter_for_track(const boost::shared_ptr<const track>& track_p, model::parameters& params)\n{\n    const track& track(*track_p);\n    Eigen::Matrix2f Phi = Eigen::Matrix2f::Zero();\n    BOOST_ASSERT(is_symmetric(Phi));\n\n    // create a Kalman filter for the track\n    static kalman_filter_cache kf_cache;\n    const matrix2f& R(model::observation_error_covariance(params));\n    const matrix4f& Q(model::process_noise_covariance(params));\n    const kalman_filter& kf(kf_cache.get(track_p, R, Q));\n\n    // ... and a list of smoothed states and covariances\n    kalman_filter::states_and_cov_deque smoothed_states_and_covariances;\n\n    // use a _front_ inserter since we generate results in reverse order\n    rts_smooth(kf, std::front_inserter(smoothed_states_and_covariances));\n\n    // the observation matrix\n    Eigen::Matrix<float, 2, 4> B;\n    B << 1, 0, 0, 0,\n         0, 0, 1, 0;\n\n    // iterate over state and covariances for the track. keep a track of which time stamp this is\n    time_stamp time_stamp(track.first_time_stamp());\n    track::const_iterator track_obs_it(track.begin()); // also start iterating over track observations\n    BOOST_FOREACH(const kalman_filter::state_covariance_pair& state_and_cov, smoothed_states_and_covariances)\n    {\n        BOOST_ASSERT(time_stamp < track.last_time_stamp());\n\n        // extract the state and covariance\n        const Eigen::Vector4f& state(state_and_cov.first);\n        const Eigen::Matrix4f& cov(state_and_cov.second);\n\n        // do we have an associated observation?\n        if((track_obs_it != track.end()) && (t(*track_obs_it) == time_stamp))\n        {\n            // extract observation\n            const observation& obs(*track_obs_it);\n\n            // sample state\n            Eigen::Vector4f sampled_state(sampling::sample_multivariate_gaussian(state, cov));\n\n            // sampled observation\n            Eigen::Vector2f sampled_obs = B * sampled_state;\n\n            // calculate delta\n            Eigen::Vector2f obs_vector, delta;\n            obs_vector << x(obs), y(obs);\n            delta = obs_vector - sampled_obs;\n\n            // update Wishart parameter\n            Phi += delta * delta.transpose();\n            if (not is_symmetric(Phi)) {\n                OK1(cov);\n                OK(time_stamp - track.first_time_stamp());\n                OK1(Phi);\n                OK1(obs_vector);\n                OK1(sampled_obs);\n                BOOST_ASSERT(is_symmetric(Phi));\n            }\n\n\n            ++track_obs_it;\n        }\n\n        ++time_stamp;\n    }\n    if (not is_symmetric(Phi)) {\n        std::cout << \"Phi = \" << std::endl;\n        std::cout << Phi << std::endl;\n        throw std::runtime_error(\"Phi is not symmetric\");\n    }\n    return Phi;\n}\n\n\n} // namespace biggles\n", "meta": {"hexsha": "d90c67c801feb2daae54ed29053847bb7cb5f8b1", "size": 13404, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "biggles/samplers.cpp", "max_stars_repo_name": "fbi-octopus/biggles", "max_stars_repo_head_hexsha": "2dac4f1748ab87242951239caf274f302be1143a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-15T14:01:59.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-15T14:01:59.000Z", "max_issues_repo_path": "biggles/samplers.cpp", "max_issues_repo_name": "fbi-octopus/biggles", "max_issues_repo_head_hexsha": "2dac4f1748ab87242951239caf274f302be1143a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "biggles/samplers.cpp", "max_forks_repo_name": "fbi-octopus/biggles", "max_forks_repo_head_hexsha": "2dac4f1748ab87242951239caf274f302be1143a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.7570093458, "max_line_length": 131, "alphanum_fraction": 0.7030737093, "num_tokens": 3179, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711756575749, "lm_q2_score": 0.5428632831725053, "lm_q1q2_score": 0.4614181430194653}}
{"text": "#include <iostream>\n#include <armadillo>\n\nint main() {\n    arma::vec v0(5, arma::fill::randn);\n    arma::vec v = 1.0 / (1 + arma::exp(-v0));\n    std::cout << v << std::endl;\n}\n", "meta": {"hexsha": "a81c1ed3be8b8f13a7b4d461e9dd2ae520214442", "size": 176, "ext": "cc", "lang": "C++", "max_stars_repo_path": "ex/test.cc", "max_stars_repo_name": "igorcoding/cppnet", "max_stars_repo_head_hexsha": "e4b921cb5d0e8bd17228c0cb802cc48100e1b242", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ex/test.cc", "max_issues_repo_name": "igorcoding/cppnet", "max_issues_repo_head_hexsha": "e4b921cb5d0e8bd17228c0cb802cc48100e1b242", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ex/test.cc", "max_forks_repo_name": "igorcoding/cppnet", "max_forks_repo_head_hexsha": "e4b921cb5d0e8bd17228c0cb802cc48100e1b242", "max_forks_repo_licenses": ["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.5555555556, "max_line_length": 45, "alphanum_fraction": 0.5454545455, "num_tokens": 63, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.4613896531325722}}
{"text": "/***********************************************************************************\n * Copyright (c) 2018, UT-Battelle\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 xacc nor the\n *     names of its contributors may be used to endorse or promote products\n *     derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Contributors:\n *   Initial implementation - H. Charles Zhao\n *\n **********************************************************************************/\n\n#include <boost/math/constants/constants.hpp>\n#include \"ProjectQBaseListener.h\"\n#include \"exprtk.hpp\"\n#include \"XACC.hpp\"\n#include \"IRProvider.hpp\"\n#include \"IR.hpp\"\n#include \"ProjectQToXACCListener.hpp\"\n\nusing namespace projectq;\n\nusing symbol_table_t = exprtk::symbol_table<double>;\nusing expression_t = exprtk::expression<double>;\nusing parser_t = exprtk::parser<double>;\n\nnamespace xacc {\n    namespace quantum {\n        constexpr static double pi = boost::math::constants::pi<double>();\n\n        ProjectQToXACCListener::ProjectQToXACCListener(std::shared_ptr<xacc::IR> ir) : ir(ir) {\n            gateRegistry = xacc::getService<IRProvider>(\"gate\");\n        }\n\n        double evalMathExpression(const std::string &expression) {\n            symbol_table_t symbol_table;\n            symbol_table.add_constant(\"pi\", pi);\n            expression_t expr;\n            expr.register_symbol_table(symbol_table);\n            parser_t parser;\n            parser.compile(expression, expr);\n            return expr.value();\n        }\n\n        InstructionParameter strToParam(const std::string &str) {\n            double num = evalMathExpression(str);\n            if (std::isnan(num)) {\n                return InstructionParameter(str);\n            } else {\n                return InstructionParameter(num);\n            }\n        }\n\n        void ProjectQToXACCListener::enterXacckernel(projectq::ProjectQParser::XacckernelContext *ctx) {\n            std::vector<InstructionParameter> params;\n            for (int i = 0; i < ctx->typedparam().size(); i++) {\n                params.push_back(InstructionParameter(ctx->typedparam(static_cast<size_t>(i))->IDENTIFIER()->getText()));\n            }\n            curFunc = gateRegistry->createFunction(ctx->kernelname->getText(), {}, params);\n            functions.insert({curFunc->name(), curFunc});\n        }\n\n        void ProjectQToXACCListener::exitXacckernel(projectq::ProjectQParser::XacckernelContext *ctx) {\n            ir->addKernel(curFunc);\n        }\n\n        void ProjectQToXACCListener::exitKernelcall(projectq::ProjectQParser::KernelcallContext *ctx) {\n            std::string gateName = ctx->kernelname->getText();\n            if (functions.count(gateName)) {\n                curFunc->addInstruction(functions[gateName]);\n            } else {\n                xacc::error(\"Tried calling an undefined kernel.\");\n            }\n        }\n\n        void ProjectQToXACCListener::exitGate(projectq::ProjectQParser::GateContext *ctx) {\n            std::string gateName = ctx->gatename()->getText();\n            if (gateName == \"CX\") gateName = \"CNOT\";\n\n            std::vector<std::shared_ptr<xacc::Instruction>> instructions;\n            std::shared_ptr<xacc::Instruction> instruction;\n\n            // Check for qubit range\n            if (ctx->qbitarglist()->qbit().size() == 1 && ctx->qbitarglist()->qbit(0)->INT().size() == 2) {\n                int startQbit = std::stoi(ctx->qbitarglist()->qbit(0)->INT(0)->getText());\n                int endQbit = std::stoi(ctx->qbitarglist()->qbit(0)->INT(1)->getText());\n                if (endQbit <= startQbit)\n                    xacc::error(\"Invalid qubit range.\");\n                for (int i = startQbit; i <= endQbit; i++) {\n                    instruction = gateRegistry->createInstruction(gateName, { i });\n                    instructions.push_back(instruction);\n                }\n            } else {\n                std::vector<int> qubits;\n                for (int i = 0; i < ctx->qbitarglist()->qbit().size(); i++) {\n                    qubits.push_back(std::stoi(ctx->qbitarglist()->qbit(static_cast<size_t>(i))->INT(0)->getText()));\n                }\n                instruction = gateRegistry->createInstruction(gateName, qubits);\n                instructions.push_back(instruction);\n            }\n\n            if (ctx->paramlist() != nullptr) {\n                InstructionParameter param;\n                for (int i = 0; i < ctx->paramlist()->param().size(); i++) {\n                    param = strToParam(ctx->paramlist()->param(static_cast<size_t>(i))->getText());\n                    for (int j = 0; j < instructions.size(); j++) {\n                        instructions[j]->setParameter(i, param);\n                    }\n                }\n            }\n\n            for (int i = 0; i < instructions.size(); i++) {\n                curFunc->addInstruction(instructions[i]);\n            }\n        }\n\n        void ProjectQToXACCListener::exitMeasure(projectq::ProjectQParser::MeasureContext *ctx) {\n            std::shared_ptr<xacc::Instruction> instruction;\n            InstructionParameter param;\n\n            // Check for qubit range\n\n            if (ctx->qbit()->INT().size() == 2) {\n                int startQbit = std::stoi(ctx->qbit()->INT(0)->getText());\n                int endQbit = std::stoi(ctx->qbit()->INT(1)->getText());\n                if (endQbit <= startQbit)\n                    xacc::error(\"Invalid qubit range.\");\n                for (int i = startQbit; i <= endQbit; i++) {\n                    instruction = gateRegistry->createInstruction(\"Measure\", { i });\n                    param = i;\n                    instruction->setParameter(0, param);\n                    curFunc->addInstruction(instruction);\n                }\n            } else {\n                std::vector<int> qubits;\n                qubits.push_back(std::stoi(ctx->qbit()->INT(0)->getText()));\n                instruction = gateRegistry->createInstruction(\"Measure\", qubits);\n                param = 0;\n                instruction->setParameter(0, param);\n                curFunc->addInstruction(instruction);\n            }\n        }\n    }\n}\n", "meta": {"hexsha": "3158ac67c7beac2cea36d8edd105f00beca2c9fc", "size": 7407, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "compiler/ProjectQToXACCListener.cpp", "max_stars_repo_name": "czhao39/xacc-projectq", "max_stars_repo_head_hexsha": "16e714b961f1341c70c174416c500dae3d3b9bdd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "compiler/ProjectQToXACCListener.cpp", "max_issues_repo_name": "czhao39/xacc-projectq", "max_issues_repo_head_hexsha": "16e714b961f1341c70c174416c500dae3d3b9bdd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "compiler/ProjectQToXACCListener.cpp", "max_forks_repo_name": "czhao39/xacc-projectq", "max_forks_repo_head_hexsha": "16e714b961f1341c70c174416c500dae3d3b9bdd", "max_forks_repo_licenses": ["BSD-3-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.1646341463, "max_line_length": 121, "alphanum_fraction": 0.5829620629, "num_tokens": 1571, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951064805861, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.46138965098605456}}
{"text": "\ufeff#include \"pose_regression.h\"\n#include <Eigen/Dense>\n#include <Eigen/LU>\n#include <cmath>\n\nvoid PoseRegression::InitializePose(const HybridPredictionContainer& predictions,\n                                    const PoseRegressionPara& para,\n                                    AffineXform3d* rigid_pose) {\n \n  const vector<Keypoint>* keypoints = predictions.GetKeypoints();\n  const vector<EdgeVector>* edges = predictions.GetEdgeVectors();\n  const vector<SymmetryCorres>* symcorres = predictions.GetSymmetryCorres();\n\n  // initial weights of different representations \n  vector<double> weight_keypts (keypoints->size()), weight_edges (edges->size()), weight_symcorres (symcorres->size());\n  for (unsigned id = 0; id < keypoints->size(); ++id)\n    weight_keypts[id] = 1;\n  for (unsigned id = 0; id < edges->size(); ++id)\n    weight_edges[id] = 1;\n  for (unsigned id = 0; id < symcorres->size(); ++id)\n    weight_symcorres[id] = 1;\n\n  // Generate 12x12 Data matrix from different representations\n  Matrix<double, 12, 12> DataMatrix;\n  GenerateDataMatrix(predictions, weight_keypts, weight_edges, weight_symcorres,\n    para, &DataMatrix);\n\n  // Calculate Pose initial\n  vector<Vector12d> eigenVectors;\n  const unsigned numEigs = 4;\n  //LeadingEigenSpace(DataMatrix, numEigs, predictions, &eigenVectors);\n  LeadingEigenSpace(DataMatrix, numEigs, predictions, &eigenVectors, rigid_pose); \n}\n/*\nCompute the 12x12 matrix \n*/\nvoid PoseRegression::GenerateDataMatrix(const HybridPredictionContainer& predictions,\n                                        const vector<double>& weight_keypts,\n                                        const vector<double>& weight_edges,\n                                        const vector<double>& weight_symcorres,\n                                        const PoseRegressionPara& para,\n                                        Matrix12d* data_matrix) {\n  const vector<Keypoint>* keypoints = predictions.GetKeypoints();\n  const vector<EdgeVector>* edges = predictions.GetEdgeVectors();\n  const vector<SymmetryCorres>* symcorres = predictions.GetSymmetryCorres();\n\n  // Step1: add contribution of keypoint to data matrix\n  unsigned numKpts = keypoints->size();\n  Matrix<double, 12, Dynamic> J_kpts;\n  Matrix<double, Dynamic, Dynamic> W_kpts;\n  J_kpts.resize(12, numKpts*3);\n  W_kpts.resize(numKpts*3, numKpts*3);\n  Matrix<double, 12, 12> M_kpts; \n  \n  J_kpts.fill(0.0);\n  W_kpts.fill(0.0);\n  M_kpts.fill(0.0);\n\n  for (unsigned ptId = 0; ptId < numKpts; ++ptId) {  \n    const Keypoint& kp = (*keypoints)[ptId];\n    //kp.point3D_gt\n    //kp.point2D_pred\n    double x_hc, y_hc, z_hc;\n    x_hc = kp.point2D_pred[0];  \n    y_hc = kp.point2D_pred[1]; \n    z_hc = 1.0;\n\n    double x_3d, y_3d, z_3d;\n    x_3d = kp.point3D_gt[0];\n    y_3d = kp.point3D_gt[1];\n    z_3d = kp.point3D_gt[2];\n    \n    J_kpts(0, ptId * 3) = 0 * x_3d;     J_kpts(0, ptId * 3 + 1) = -z_hc * x_3d; J_kpts(0, ptId * 3 + 2) = y_hc * x_3d;\n    J_kpts(1, ptId * 3) = z_hc * x_3d;  J_kpts(1, ptId * 3 + 1) = 0 * x_3d;     J_kpts(1, ptId * 3 + 2) = -x_hc * x_3d;\n    J_kpts(2, ptId * 3) = -y_hc * x_3d; J_kpts(2, ptId * 3 + 1) = x_hc * x_3d;  J_kpts(2, ptId * 3 + 2) = 0 * x_3d;\n\n    J_kpts(3, ptId * 3) = 0 * y_3d;     J_kpts(3, ptId * 3 + 1) = -z_hc * y_3d; J_kpts(3, ptId * 3 + 2) = y_hc * y_3d;\n    J_kpts(4, ptId * 3) = z_hc * y_3d;  J_kpts(4, ptId * 3 + 1) = 0 * y_3d;     J_kpts(4, ptId * 3 + 2) = -x_hc * y_3d;\n    J_kpts(5, ptId * 3) = -y_hc * y_3d; J_kpts(5, ptId * 3 + 1) = x_hc * y_3d;  J_kpts(5, ptId * 3 + 2) = 0 * y_3d;\n\n    J_kpts(6, ptId * 3) = 0 * z_3d;     J_kpts(6, ptId * 3 + 1) = -z_hc * z_3d; J_kpts(6, ptId * 3 + 2) = y_hc * z_3d;\n    J_kpts(7, ptId * 3) = z_hc * z_3d;  J_kpts(7, ptId * 3 + 1) = 0 * z_3d;     J_kpts(7, ptId * 3 + 2) = -x_hc * z_3d;\n    J_kpts(8, ptId * 3) = -y_hc * z_3d; J_kpts(8, ptId * 3 + 1) = x_hc * z_3d;  J_kpts(8, ptId * 3 + 2) = 0 * z_3d;\n\n    J_kpts(9, ptId * 3) = 0 * 1.0;      J_kpts(9, ptId * 3 + 1) = -z_hc * 1.0; J_kpts(9, ptId * 3 + 2) = y_hc * 1.0;\n    J_kpts(10, ptId * 3) = z_hc * 1.0;  J_kpts(10, ptId * 3 + 1) = 0 * 1.0;    J_kpts(10, ptId * 3 + 2) = -x_hc * 1.0;\n    J_kpts(11, ptId * 3) = -y_hc * 1.0; J_kpts(11, ptId * 3 + 1) = x_hc * 1.0; J_kpts(11, ptId * 3 + 2) = 0 * 1.0;\n    \n    // calculate weight for keypoints\n    //kp.inv_half_var    \n    EigenSolver<Matrix2d> es_kp(kp.inv_half_var);   \n    W_kpts(ptId * 3, ptId * 3) = es_kp.eigenvalues().norm() * 0.02;\n    W_kpts(ptId * 3 + 1, ptId * 3 + 1) = es_kp.eigenvalues().norm() * 0.02;\n    W_kpts(ptId * 3 + 2, ptId * 3 + 2) = es_kp.eigenvalues().norm() * 2;        \n  }  \n  // add J_kpts into Datamatrix\n  M_kpts = J_kpts * W_kpts * J_kpts.transpose();  \n  for (unsigned row_id = 0; row_id < 12; ++row_id) {\n    for (unsigned com_id = 0; com_id < 12; ++com_id) {\n      (*data_matrix)(row_id, com_id) = M_kpts(row_id, com_id) * para.gamma_kpts;     \n    }\n  }  \n  //  Step2: add contribution of edge for data matrix\n  unsigned numedges = edges->size();\n  Matrix<double, 12, Dynamic> J_edge(12, numedges*3);\n  Matrix<double, Dynamic, Dynamic> W_edge(numedges*3, numedges*3);\n  Matrix<double, 12, 12> M_edge;\n  J_edge.fill(0.0);\n  W_edge.fill(0.0);\n  M_edge.fill(0.0);\n \n  for (unsigned edgeId = 0; edgeId < numedges; ++edgeId) {\n    const EdgeVector& ev = (*edges)[edgeId];\n    const Keypoint& kp_start = (*keypoints)[ev.start_id]; // edge = s - e\n    const Keypoint& kp_end = (*keypoints)[ev.end_id];\n    // ev.vec_pred\n    // pts2d_s\n    // pts3d_t\n    // edge3d\n    // Part1 of step2\n    double x_hc, y_hc, z_hc; // denotes pts2d_s\n    x_hc = kp_end.point2D_pred[0];  \n    y_hc = kp_end.point2D_pred[1]; \n    z_hc = 1.0;\n\n    double x_3d, y_3d, z_3d; // denotes edge3d\n    x_3d = kp_start.point3D_gt[0] - kp_end.point3D_gt[0];\n    y_3d = kp_start.point3D_gt[1] - kp_end.point3D_gt[1];\n    z_3d = kp_start.point3D_gt[2] - kp_end.point3D_gt[2];\n\n    J_edge(0, edgeId * 3) = 0 * x_3d;     J_edge(0, edgeId * 3 + 1) = -z_hc * x_3d; J_edge(0, edgeId * 3 + 2) = y_hc * x_3d;\n    J_edge(1, edgeId * 3) = z_hc * x_3d;  J_edge(1, edgeId * 3 + 1) = 0 * x_3d;     J_edge(1, edgeId * 3 + 2) = -x_hc * x_3d;\n    J_edge(2, edgeId * 3) = -y_hc * x_3d; J_edge(2, edgeId * 3 + 1) = x_hc * x_3d;  J_edge(2, edgeId * 3 + 2) = 0 * x_3d;\n\n    J_edge(3, edgeId * 3) = 0 * y_3d;     J_edge(3, edgeId * 3 + 1) = -z_hc * y_3d; J_edge(3, edgeId * 3 + 2) = y_hc * y_3d;\n    J_edge(4, edgeId * 3) = z_hc * y_3d;  J_edge(4, edgeId * 3 + 1) = 0 * y_3d;     J_edge(4, edgeId * 3 + 2) = -x_hc * y_3d;\n    J_edge(5, edgeId * 3) = -y_hc * y_3d; J_edge(5, edgeId * 3 + 1) = x_hc * y_3d;  J_edge(5, edgeId * 3 + 2) = 0 * y_3d;\n\n    J_edge(6, edgeId * 3) = 0 * z_3d;     J_edge(6, edgeId * 3 + 1) = -z_hc * z_3d; J_edge(6, edgeId * 3 + 2) = y_hc * z_3d;\n    J_edge(7, edgeId * 3) = z_hc * z_3d;  J_edge(7, edgeId * 3 + 1) = 0 * z_3d;     J_edge(7, edgeId * 3 + 2) = -x_hc * z_3d;\n    J_edge(8, edgeId * 3) = -y_hc * z_3d; J_edge(8, edgeId * 3 + 1) = x_hc * z_3d;  J_edge(8, edgeId * 3 + 2) = 0 * z_3d;\n\n    //Part2 of step2   \n    x_hc = ev.vec_pred[0];   // denote edge_pred_2d\n    y_hc = ev.vec_pred[1]; \n    z_hc = 0.0;    \n    \n    x_3d = kp_start.point3D_gt[0];// denotes pts3d_t\n    y_3d = kp_start.point3D_gt[1];\n    z_3d = kp_start.point3D_gt[2];\n\n    J_edge(0, edgeId * 3) += 0 * x_3d;     J_edge(0, edgeId * 3 + 1) += -z_hc * x_3d; J_edge(0, edgeId * 3 + 2) += y_hc * x_3d;\n    J_edge(1, edgeId * 3) += z_hc * x_3d;  J_edge(1, edgeId * 3 + 1) += 0 * x_3d;     J_edge(1, edgeId * 3 + 2) += -x_hc * x_3d;\n    J_edge(2, edgeId * 3) += -y_hc * x_3d; J_edge(2, edgeId * 3 + 1) += x_hc * x_3d;  J_edge(2, edgeId * 3 + 2) += 0 * x_3d;\n\n    J_edge(3, edgeId * 3) += 0 * y_3d;     J_edge(3, edgeId * 3 + 1) += -z_hc * y_3d; J_edge(3, edgeId * 3 + 2) += y_hc * y_3d;\n    J_edge(4, edgeId * 3) += z_hc * y_3d;  J_edge(4, edgeId * 3 + 1) += 0 * y_3d;     J_edge(4, edgeId * 3 + 2) += -x_hc * y_3d;\n    J_edge(5, edgeId * 3) += -y_hc * y_3d; J_edge(5, edgeId * 3 + 1) += x_hc * y_3d;  J_edge(5, edgeId * 3 + 2) += 0 * y_3d;\n\n    J_edge(6, edgeId * 3) += 0 * z_3d;     J_edge(6, edgeId * 3 + 1) += -z_hc * z_3d; J_edge(6, edgeId * 3 + 2) += y_hc * z_3d;\n    J_edge(7, edgeId * 3) += z_hc * z_3d;  J_edge(7, edgeId * 3 + 1) += 0 * z_3d;     J_edge(7, edgeId * 3 + 2) += -x_hc * z_3d;\n    J_edge(8, edgeId * 3) += -y_hc * z_3d; J_edge(8, edgeId * 3 + 1) += x_hc * z_3d;  J_edge(8, edgeId * 3 + 2) += 0 * z_3d;\n\n    J_edge(9, edgeId * 3) = 0 * 1.0;      J_edge(9, edgeId * 3 + 1) = -z_hc * 1.0;  J_edge(9, edgeId * 3 + 2) = y_hc * 1.0;\n    J_edge(10, edgeId * 3) = z_hc * 1.0;  J_edge(10, edgeId * 3 + 1) = 0 * 1.0;     J_edge(10, edgeId * 3 + 2) = -x_hc * 1.0;\n    J_edge(11, edgeId * 3) = -y_hc * 1.0; J_edge(11, edgeId * 3 + 1) = x_hc * 1.0;  J_edge(11, edgeId * 3 + 2) = 0 * 1.0;\n  \n    W_edge(edgeId * 3, edgeId * 3) = weight_edges[edgeId];\n    W_edge(edgeId * 3 + 1, edgeId * 3 + 1) = weight_edges[edgeId];\n    W_edge(edgeId * 3 + 2, edgeId * 3 + 2) = weight_edges[edgeId];    \n  }\n  // add J_edge into Datamatrix\n  M_edge = J_edge * W_edge * J_edge.transpose();  \n  for (unsigned row_id = 0; row_id < 12; ++row_id) {\n    for (unsigned com_id = 0; com_id < 12; ++com_id) {\n      (*data_matrix)(row_id, com_id) += M_edge(row_id, com_id) * para.gamma_edge;       \n    }   \n  }\n\n  // Step3: add contribution of symmetry for data matrix\n  unsigned numSym = symcorres->size();\n  Matrix<double, 9, Dynamic> J_sym(9, numSym);\n  Matrix<double, Dynamic, Dynamic> W_sym(numSym, numSym);\n  Matrix<double, 9, 9> M_sym; \n\n  J_sym.fill(0.0);\n  W_sym.fill(0.0);\n  M_sym.fill(0.0);\n  \n  const Vector3d &normal_gt = predictions.GetReflectionPlaneNormal();\n  for (unsigned symId = 0; symId < numSym; ++symId) {\n    const SymmetryCorres& sc = (*symcorres)[symId];\n    \n    double x_hc, y_hc, z_hc; // denotes sym_pred_2d\n    x_hc = sc.qs1_cross_qs2[0];\n    y_hc = sc.qs1_cross_qs2[1];\n    z_hc = sc.qs1_cross_qs2[2];\n    \n    J_sym(0, symId) = x_hc * normal_gt[0]; J_sym(1, symId) = y_hc * normal_gt[0]; J_sym(2, symId) = z_hc * normal_gt[0];\n    J_sym(3, symId) = x_hc * normal_gt[1]; J_sym(4, symId) = y_hc * normal_gt[1]; J_sym(5, symId) = z_hc * normal_gt[1];\n    J_sym(6, symId) = x_hc * normal_gt[2]; J_sym(7, symId) = y_hc * normal_gt[2]; J_sym(8, symId) = z_hc * normal_gt[2];\n    W_sym(symId, symId) = weight_symcorres[symId];\n  }  // add J_kpts into Datamatrix\n  M_sym = J_sym * W_sym * J_sym.transpose();\n  for (unsigned row_id = 0; row_id < 9; ++row_id) {\n    for (unsigned com_id = 0; com_id < 9; ++com_id) {\n      (*data_matrix)(row_id, com_id) += M_sym(row_id, com_id) * para.gamma_sym;      \n    }\n  } \n}\n\n// Leading eigen-space computation\nvoid PoseRegression::LeadingEigenSpace(Matrix12d& data_matrix, const unsigned& numEigs, \n                                       const HybridPredictionContainer& predictions, vector<Vector12d>* eigenVectors,\n                                       AffineXform3d* rigid_pose) {\n  Matrix<double, 12, 4> eigenvector;\n  // SVD of data_matrix svd.singularValues()[0]\n  JacobiSVD<Matrix12d> svd(data_matrix, ComputeFullV | ComputeFullU);\n  for (unsigned com_id = 0; com_id < numEigs; ++com_id) {\n    for (unsigned row_id = 0; row_id < 12; ++row_id)    \n      eigenvector(row_id, com_id) = svd.matrixV().col(11 - com_id)[row_id];    \n  }  \n  // Calculate initial coefficient(beta) of different eigenvectors  \n  Map<MatrixXd> A1(eigenvector.col(0).head(9).data(), 3,3); \n  Map<MatrixXd> A2(eigenvector.col(1).head(9).data(), 3,3);\n  Map<MatrixXd> A3(eigenvector.col(2).head(9).data(), 3,3);\n  Map<MatrixXd> A4(eigenvector.col(3).head(9).data(), 3,3);\n\n  Matrix3d B1 = A1.transpose() * A1;\n  Matrix3d B2 = A1.transpose() * A2 + A2.transpose() * A1;\n  Matrix3d B3 = A1.transpose() * A3 + A3.transpose() * A1;\n  Matrix3d B4 = A2.transpose() * A2;\n  Matrix3d B5 = A2.transpose() * A3 + A3.transpose() * A2;\n  Matrix3d B6 = A3.transpose() * A3;\n\n  // form linear system Cx = y to solve gamma(x) which contains coefficient \n  Matrix6d C;\n  Vector6d y(1.0, 0.0, 0.0, 1.0, 0.0, 1.0);\n  Vector6d gamma;\n \n  C(0, 0) = B1(0, 0); C(0, 1) = B2(0, 0); C(0, 2) = B3(0, 0); C(0, 3) = B4(0, 0); C(0, 4) = B5(0, 0); C(0, 5) = B6(0, 0);\n  C(1, 0) = B1(0, 1); C(1, 1) = B2(0, 1); C(1, 2) = B3(0, 1); C(1, 3) = B4(0, 1); C(1, 4) = B5(0, 1); C(1, 5) = B6(0, 1);\n  C(2, 0) = B1(0, 2); C(2, 1) = B2(0, 2); C(2, 2) = B3(0, 2); C(2, 3) = B4(0, 2); C(2, 4) = B5(0, 2); C(2, 5) = B6(0, 2);\n  C(3, 0) = B1(1, 1); C(3, 1) = B2(1, 1); C(3, 2) = B3(1, 1); C(3, 3) = B4(1, 1); C(3, 4) = B5(1, 1); C(3, 5) = B6(1, 1);\n  C(4, 0) = B1(1, 2); C(4, 1) = B2(1, 2); C(4, 2) = B3(1, 2); C(4, 3) = B4(1, 2); C(4, 4) = B5(1, 2); C(4, 5) = B6(1, 2);\n  C(5, 0) = B1(2, 2); C(5, 1) = B2(2, 2); C(5, 2) = B3(2, 2); C(5, 3) = B4(2, 2); C(5, 4) = B5(2, 2); C(5, 5) = B6(2, 2);\n  \n  gamma = C.lu().solve(y);\n  //project gamma in to valid coefficient space\n  MatrixXd Gamma = MatrixXd::Random(3, 3);\n  Gamma(0, 0) = gamma[0];  Gamma(0, 1) = gamma[1];  Gamma(0, 2) = gamma[2]; \n  Gamma(1, 0) = gamma[1];  Gamma(1, 1) = gamma[3];  Gamma(1, 2) = gamma[4]; \n  Gamma(2, 0) = gamma[2];  Gamma(2, 1) = gamma[4];  Gamma(2, 2) = gamma[5]; \n  // calculated sorted eigen vector and eigen value in increasing order\n  SelfAdjointEigenSolver<MatrixXd> es(Gamma); \n  MatrixXcd D = es.eigenvalues().asDiagonal();\n  MatrixXcd V = es.eigenvectors();\n  D(0, 0) = 0;\n  D(1, 1) = 0;  \n  Gamma = (V * D * V.inverse()).real();  \n  // assign new gamma\n  gamma[0] = Gamma(0, 0); gamma[1] = Gamma(0, 1); gamma[2] = Gamma(0, 2);\n  gamma[3] = Gamma(1, 1); gamma[4] = Gamma(1, 2); gamma[5] = Gamma(2, 2);\n  if (gamma[0] < 0)\n    gamma *= -1.0;\n  // recover initial coefficient beta from gamma with following equations:\n  // gamma[0] = beta[0]^2; gamma[1] = beta[0] * beta[1]; gamma[2] = beta[0]*beta[2]\n  // gamma[3] = beta[1]^2; gamma[4] = beta[1] * beta[2]; gamma[5] = beta[2]^2;\n  Vector4d beta;\n  double temp;\n  beta[3] = 0;\n  beta[0] = sqrt(gamma[0]);  \n  beta[1] = gamma[1] / beta[0];\n  temp = sqrt(gamma[3]);\n  if (gamma[1] < 0)\n    temp = temp * -1.0;\n  beta[1] = 0.5 * (temp + beta[1]);\n  beta[2] = gamma[4] / beta[1];\n  temp = gamma[2] / beta[0];\n  beta[2] = 0.5 * (beta[2] + temp);\n  \n  // check the validation of betas\n  Matrix3d R_init;\n  Vector3d t_init;\n  Matrix<double, 12, 9> At1;\n  Matrix<double, 12, 3> At2;\n  At1 = data_matrix.leftCols(9);\n  At2 = data_matrix.rightCols(3);   \n  R_init = beta[0] * A1 + beta[1] * A2 + beta[2] * A3 + beta[3] * A4;  \n\n  // check1 det(R) > 0\n  if (R_init.determinant() < 0) {\n    beta = beta * -1.0;\n    R_init = beta[0] * A1 + beta[1] * A2 + beta[2] * A3 + beta[3] * A4;    \n  }\n  \n  Map<VectorXd> R_vec(R_init.data(), 9, 1); \n  t_init = -1.0 * (At2.transpose() * At2).lu().solve(At2.transpose() * At1 * R_vec);\n\n // check2 depth > 0\n  const vector<Keypoint>* keypoints = predictions.GetKeypoints();\n  double z = 0;\n  unsigned numKpts = keypoints->size();\n  \n  for (unsigned ptId = 0; ptId < numKpts; ++ptId) {  \n    const Keypoint& kp = (*keypoints)[ptId];\n    z = z + (R_init * kp.point3D_gt + t_init)[2];\n  }\n  \n  if (z < 0){\n    t_init = t_init * -1.0;\n    R_vec = -1.0 * (At1.transpose() * At1).lu().solve(At1.transpose() * At2 * t_init);\n    Map<Matrix3d> R_temp(R_vec.data(), 3,3);\n    // map R_init into SO(3)\n    JacobiSVD<Matrix3d> svd(R_temp, ComputeFullV | ComputeFullU);\n    R_init = svd.matrixU() * svd.matrixV().transpose();\n    if (R_init.determinant() < 0){\n      Vector3d dia(1.0,1.0,-1.0);\n      R_init = svd.matrixU() * dia.asDiagonal() * svd.matrixV().transpose();\n    }\n    t_init = -1.0 * (At2.transpose() * At2).lu().solve(At2.transpose() * At1 * R_vec);\n  }\n\n  // optimize beta and R_init simutaneously\n  Matrix3d A = R_init;\n  Matrix3d R;\n  for(unsigned iter = 0; iter < 10; ++iter) {\n    // optimize R_init\n    JacobiSVD<Matrix3d> svd(A, ComputeFullV | ComputeFullU);\n    if (A.determinant() > 0) {\n      R = svd.matrixU() * svd.matrixV().transpose();\n    }else {\n      Vector3d dia(1.0, 1.0, -1.0);\n      R = svd.matrixU() * dia.asDiagonal() * svd.matrixV().transpose();\n    }\n    // optimize betas by forming a linear system for beta\n    Matrix<double, 9, 4> D;    \n    unsigned row_id;\n    for(row_id = 0; row_id < 3; ++row_id) {   \n      D(row_id, 0) = A1(0, row_id); D(row_id, 1) = A2(0, row_id); \n      D(row_id, 2) = A3(0, row_id); D(row_id, 3) = A4(0, row_id); \n    }\n    for(row_id = 3; row_id < 6; ++row_id) {   \n      D(row_id, 0) = A1(1, row_id - 3); D(row_id, 1) = A2(1, row_id - 3); \n      D(row_id, 2) = A3(1, row_id - 3); D(row_id, 3) = A4(1, row_id - 3); \n    }\n    for(row_id = 6; row_id < 9; ++row_id) {   \n      D(row_id, 0) = A1(2, row_id - 6); D(row_id, 1) = A2(2, row_id - 6); \n      D(row_id, 2) = A3(2, row_id - 6); D(row_id, 3) = A4(2, row_id - 6); \n    }   \n    Matrix3d R_temp = R.transpose();  \n    Map<VectorXd> dy(R_temp.data(), 9, 1);\n    beta = D.bdcSvd(ComputeFullV | ComputeFullU).solve(dy);    \n    A = beta[0] * A1 + beta[1] * A2 + beta[2] * A3 + beta[3] * A4;\n  }\n\n  R_init = R;  \n  Map<Matrix<double, 9, 1>> R_vec1(R.data(), 9, 1); \n  t_init = -1.0 * (At2.transpose() * At2).lu().solve(At2.transpose() * At1 * R_vec1); \n  // check R_init and t_init again\n  z = 0;\n  for (unsigned ptId = 0; ptId < numKpts; ++ptId) {  \n    const Keypoint& kp = (*keypoints)[ptId];\n    z = z + (R_init * kp.point3D_gt + t_init)[2];\n  }\n  if (z < 0) {\n    t_init = t_init * -1.0;\n    R_vec = -1.0 * (At1.transpose() * At1).lu().solve(At1.transpose() * At2 * t_init);\n    Map<Matrix3d> R_temp1(R_vec.data(), 3, 3);\n\n    // map R_init into SO(3)   \n    JacobiSVD<Matrix3d> svd(R_temp1, ComputeFullV | ComputeFullU);\n    R_init = svd.matrixU() * svd.matrixV().transpose();\n    if (R_init.determinant() < 0) {\n      Vector3d dia1(1.0, 1.0, -1.0);\n      R_init = svd.matrixU() * dia1.asDiagonal() * svd.matrixV().transpose();\n    }\n    t_init = -1.0 * (At2.transpose() * At2).lu().solve(At2.transpose() * At1 * R_vec);\n  }\n\n // Assign pose initial to rigid_pose\n  for (unsigned row_id = 0; row_id < 3; ++row_id) {\n    (*rigid_pose)[0][row_id] = t_init[row_id];\n    for (unsigned com_id = 0; com_id < 3; ++com_id)\n      (*rigid_pose)[com_id + 1][row_id] = R_init(row_id, com_id);    \n  }\n}\n", "meta": {"hexsha": "648c580c35cb0cf159fd456c52c4cd44d468c4a0", "size": 18097, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/regressor/Operation/pose_regression_init.cpp", "max_stars_repo_name": "ParikhKadam/HybridPose", "max_stars_repo_head_hexsha": "3d112425f9b6319c8f62dfd92bb38253fe4ffdcd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 369.0, "max_stars_repo_stars_event_min_datetime": "2020-01-08T05:23:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T02:22:21.000Z", "max_issues_repo_path": "lib/regressor/Operation/pose_regression_init.cpp", "max_issues_repo_name": "ParikhKadam/HybridPose", "max_issues_repo_head_hexsha": "3d112425f9b6319c8f62dfd92bb38253fe4ffdcd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 66.0, "max_issues_repo_issues_event_min_datetime": "2020-01-21T12:58:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-14T07:50:01.000Z", "max_forks_repo_path": "lib/regressor/Operation/pose_regression_init.cpp", "max_forks_repo_name": "ParikhKadam/HybridPose", "max_forks_repo_head_hexsha": "3d112425f9b6319c8f62dfd92bb38253fe4ffdcd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 64.0, "max_forks_repo_forks_event_min_datetime": "2020-01-08T07:37:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T07:07:33.000Z", "avg_line_length": 46.6417525773, "max_line_length": 128, "alphanum_fraction": 0.5737415041, "num_tokens": 7758, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.546738151984614, "lm_q1q2_score": 0.46138964883953687}}
{"text": "// Filename: complete_iteration.cpp (part of MTL4)\n\n#include <iostream>\n#include <boost/numeric/mtl/mtl.hpp>\n\nusing namespace mtl;\n    \ntemplate <typename Matrix>\nvoid f(Matrix& A)\n{\n    using traits::range_generator; \n    A= 7.0;    // Set values in diagonal\n \n    // Types of outer and inner cursor\n    typedef typename range_generator<tag::major, Matrix>::type c_type;\n    typedef typename range_generator<tag::nz, c_type>::type    ic_type;\n\n    // Define the property maps\n    typename traits::row<Matrix>::type               row(A); \n    typename traits::col<Matrix>::type               col(A);\n    typename traits::const_value<Matrix>::type       value(A); \n\n    // Now iterate over the matrix    \n    for (c_type cursor= begin<tag::major>(A), cend= end<tag::major>(A); cursor != cend; ++cursor)\n       for (ic_type icursor= begin<tag::nz>(cursor), icend= end<tag::nz>(cursor); icursor != icend; ++icursor)\n\t   std::cout << \"A[\" << row(*icursor) << \", \" << col(*icursor) << \"] = \" << value(*icursor) << '\\n';    \n}\n\n\nint main(int, char**)\n{\n    // Define a row-major sparse and a column-major dense matrix\n    compressed2D<double>                             A(3, 3);\n    dense2D<double, mat::parameters<col_major> >  B(3, 3);\n\n    f(A);\n    f(B);\n    \n    return 0;\n}\n", "meta": {"hexsha": "7c5bf220d30a4487fee9302e3db7e7bfefa8a6f2", "size": 1275, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/examples/complete_iteration.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/complete_iteration.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/complete_iteration.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": 31.0975609756, "max_line_length": 110, "alphanum_fraction": 0.5992156863, "num_tokens": 348, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.46138274940387314}}
{"text": "#include \"laplacian_smoothing.h\"\n#include <vector>\n#include <set>\n// #include <unordered_set>\n#include <iostream>\n\n\n// #include <boost/container/flat_set.hpp>\n\n// typedef std::vector<boost::container::flat_set<size_t>> Adjacency;\ntypedef std::vector<std::set<size_t> > Adjacency;\n//typedef std::vector<std::unordered_set<size_t> > Adjacency;\n/**\n * maps each vertex to all its neighbours\n */\n\n\ntemplate<typename T>\nvoid swap(T& a, T&b)\n{\n\tT tmp = a;\n\ta = b;\n\tb = tmp;\n}\n\n\n/**\n * generates the adjacency list for the vertices in the mesh\n * returns the adjacency list\n */\nAdjacency adjacencyList(Mesh& mesh)\n{\n\tAdjacency adjacency(mesh.vertexCount);\n\n\tsize_t faceCount = mesh.faceCount;\n\tsize_t* faces = mesh.faces;\n\n\n\t//#pragma omp parallel for\n\tfor (int i = 0; i < faceCount * 3; i += 3)\n\t{\n\t\t//#pragma omp critical\n\t\t{\n\t\t\tsize_t a, b, c;\n\t\t\ta = mesh.faces[i];\n\t\t\tb = faces[i + 1];\n\t\t\tc = faces[i + 2];\n\t\t\t//std::cout<<\"i\"<<i<<\" (\"<<a<<\",\"<<b<<\",\"<<c<<\")\\n\";\n\n\t\t\tadjacency[a].insert(b);\n\t\t\tadjacency[a].insert(c);\n\t\t\tadjacency[b].insert(a);\n\t\t\tadjacency[b].insert(c);\n\t\t\tadjacency[c].insert(a);\n\t\t\tadjacency[c].insert(b);\n\t\t}\n\t}\n\t//std::cout<<\"adjacency done\\n\";\n\treturn adjacency;\n}\n\n\nvoid smooth(Mesh& mesh, unsigned int rounds)\n{\n\tauto adjacency = adjacencyList(mesh);\n\n\tPoint* vertices = mesh.vertices;\n\tPoint* normals = mesh.normals;\n\tsize_t vertexCount = mesh.vertexCount;\n\n\tPoint* new_verts = new Point[vertexCount];\n\tPoint* new_norms = new Point[vertexCount];\n\n\tfor (unsigned int i = 0; i < rounds; ++i)\n\t{\n\t\t#pragma omp parallel for\n\t\tfor (int vert = 0; vert < vertexCount; ++vert)\n\t\t{\n\t\t\tfor (unsigned int off = 0; off < 3; ++off)\n\t\t\t{\n\t\t\t\tfloat new_vert = vertices[vert][off];\n\t\t\t\tfloat new_norm = normals[vert][off];\n\t\t\t\tauto& neis = adjacency[vert];\n\t\t\t\tfor (auto nei : neis)\n\t\t\t\t{\n\t\t\t\t\tnew_vert += vertices[nei][off];\n\t\t\t\t\tnew_norm += normals[nei][off];\n\t\t\t\t}\n\t\t\t\tnew_verts[vert][off] = new_vert / (neis.size() + 1);\n\t\t\t\tnew_norms[vert][off] = new_norm / (neis.size() + 1);\n\t\t\t}\n\n\t\t}\n\t\tswap(normals, new_norms);\n\t\tswap(vertices, new_verts);\n\t}\n\tswap(normals, new_norms);\n\tswap(vertices, new_verts);\n\tdelete[] new_norms;\n\tdelete[] new_verts;\n\tmesh.normals = normals;\n\tmesh.vertices = vertices;\n}", "meta": {"hexsha": "dc12280f525ccd79b6ff0f51244c848dcf88fdb3", "size": 2209, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/laplacian_smoothing.cpp", "max_stars_repo_name": "fangyunfeng/marching_cubes", "max_stars_repo_head_hexsha": "cd9e7de3c4b824697507b270d39b2abc21d31c4d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-06-23T07:17:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-18T04:07:09.000Z", "max_issues_repo_path": "src/laplacian_smoothing.cpp", "max_issues_repo_name": "fangyunfeng/marching_cubes", "max_issues_repo_head_hexsha": "cd9e7de3c4b824697507b270d39b2abc21d31c4d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-10-16T08:45:27.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-16T08:45:27.000Z", "max_forks_repo_path": "src/laplacian_smoothing.cpp", "max_forks_repo_name": "fangyunfeng/marching_cubes", "max_forks_repo_head_hexsha": "cd9e7de3c4b824697507b270d39b2abc21d31c4d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-06-23T07:17:21.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-12T12:03:35.000Z", "avg_line_length": 21.4466019417, "max_line_length": 69, "alphanum_fraction": 0.6392032594, "num_tokens": 659, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.4613827397181289}}
{"text": "#include <base/eigen2hdf.hpp>\n#include <base/init.hpp>\n#include <base/timer.hpp>\n#include <boost/program_options.hpp>\n#include <ridgelet/construction/ft.hpp>\n#include <ridgelet/ridgelet_frame.hpp>\n#include \"ridgelet/basis.hpp\"\n\n#include <fstream>\n#include <iostream>\n#include <sstream>\n\nusing namespace std;\n\nvoid dump(const RidgeletFrame& RF)\n{\n  const char* fname = \"assemble.h5\";\n  hid_t file = H5Fcreate(fname, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);\n  auto& lambdas = RF.lambdas();\n\n  for (auto& lam : lambdas) {\n    if (lam.t == rt_type::S) {\n      auto& M = RF.get_dense(lam);\n      stringstream ss;\n      ss << lam;\n      string dset = ss.str();\n      //      cout << \"creating dset: \" << dset << \"\\n\";\n      eigen2hdf::save(file, dset, M);\n    } else {\n      auto& M = RF.get_sparse(lam);\n      stringstream ss;\n      ss << lam;\n      string dset = ss.str();\n      //      cout << \"creating dset:\" << dset << \"\\n\";\n      eigen2hdf::save_sparse(file, dset, M);\n    }\n  }\n  H5Fclose(file);\n  cout << \"wrote ridgelet coeffs to \" << fname << \"\\n\";\n}\n\nvoid listb(const RidgeletFrame& RF, unsigned int rho_x, unsigned int rho_y)\n{\n  for (auto& lam : RF.lambdas()) {\n    unsigned int tx = translation_size(lam.t, lam.j, rho_x, 0);\n    unsigned int ty = translation_size(lam.t, lam.j, rho_y, 1);\n\n    if (lam.t == rt_type::S) {\n      auto& M = RF.get_dense(lam);\n      stringstream ss;\n      ss << lam;\n      string sl = ss.str();\n      stringstream dim;\n      dim << M.rows() << \" x \" << M.cols();\n      cout << setw(15) << sl << \", rt_size: \" << setw(15) << dim.str() << \", T: \" << setw(5) << tx\n           << \" x \" << setw(5) << ty << \"\\n\";\n    } else {\n      auto& M = RF.get_sparse(lam);\n      stringstream ss;\n      ss << lam;\n      string sl = ss.str();\n      stringstream dim;\n      dim << M.rows() << \" x \" << M.cols();\n      cout << setw(15) << sl << \", rt_size: \" << setw(15) << dim.str() << \", T: \" << setw(5) << tx\n           << \" x \" << setw(5) << ty << \"\\n\";\n    }\n  }\n  cout << \"T: translation set dimensions, rt_size: ridgelet coefficient array dimensions\"\n       << \"\\n\";\n}\n\nint main(int argc, char* argv[])\n{\n  SOURCE_INFO();\n  namespace po = boost::program_options;\n\n  unsigned int Jx, Jy, rho_x, rho_y;\n\n  po::options_description options(\"options\");\n  options.add_options()(\"help\", \"produce help message\")\n      (\"Jx,i\", po::value<unsigned int>(&Jx)->default_value(3), \"Jx\")\n      (\"Jy,j\", po::value<unsigned int>(&Jy)->default_value(3), \"Jy\")\n      (\"rx,x\", po::value<unsigned int>(&rho_x)->default_value(1), \"rho_x\")\n      (\"ry,y\", po::value<unsigned int>(&rho_y)->default_value(1), \"rho_x\")\n      (\"dump\", \"dump coefficients to hdf5\")\n      (\"list\", \"list basis and sizes\");\n  po::variables_map vm;\n  po::store(po::parse_command_line(argc, argv, options), vm);\n  po::notify(vm);\n\n  if (vm.count(\"help\")) {\n    std::cout << options << \"\\n\";\n    return 0;\n  }\n  cout << setw(20) << \"Jx\"\n       << \": \" << Jx << \"\\n\"\n       << setw(20) << \"Jy\"\n       << \": \" << Jy << \"\\n\"\n       << setw(20) << \"rho_x\"\n       << \": \" << rho_x << \"\\n\"\n       << setw(20) << \"rho_y\"\n       << \": \" << rho_y << \"\\n\";\n\n  RDTSCTimer timer;\n  timer.start();\n  RidgeletFrame frame(Jx, Jy, rho_x, rho_y);\n  auto tlap = timer.stop();\n  cout << \"RidgeletFrame::RidgeletFrame(): \" << tlap / 1e9 << \" [Gcycles]\"\n       << \"\\n\";\n\n  cout << \"frame.size: \" << frame.size() << \"\\n\";\n  cout << \"frame.Nx: \" << frame.Nx() << \"\\n\";\n  cout << \"frame.Ny: \" << frame.Ny() << \"\\n\";\n\n  {\n    ofstream fout(\"assemble_rt.txt\");\n    for (auto& lam : frame.lambdas()) {\n      fout << lam << endl;\n    }\n    fout.close();\n  }\n\n  if (vm.count(\"dump\")) dump(frame);\n\n  if (vm.count(\"list\")) listb(frame, rho_x, rho_y);\n\n  return 0;\n}\n", "meta": {"hexsha": "e3dc6b24e288583bf37eb56faaffc809aac7ad78", "size": 3711, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/main_assemble.cpp", "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": "test/main_assemble.cpp", "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": "test/main_assemble.cpp", "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.7674418605, "max_line_length": 98, "alphanum_fraction": 0.5421719213, "num_tokens": 1140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982043529716, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.46138273398927176}}
{"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>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n\nusing namespace boost;\n\nint main(int, char *[])\n{\n    std::cout << sizeof(long unsigned int) << std::endl;\n    // create a typedef for the Graph type\n    typedef adjacency_list<vecS, vecS, bidirectionalS> Graph;\n\n    // Make convenient labels for the vertices\n    enum\n    {\n        A, B, C, D, E, N\n    };\n    const int num_vertices = N;\n    const char *name = \"ABCDE\";\n\n    // writing out the edges in the graph\n    typedef std::pair<int, int> Edge;\n    Edge edge_array[] =\n            {Edge(A, B), Edge(A, D), Edge(C, A), Edge(D, C),\n             Edge(C, E), Edge(B, D), Edge(D, E)};\n    const int num_edges = sizeof(edge_array) / sizeof(edge_array[0]);\n\n    // declare a graph object\n    Graph g(num_vertices);\n\n    // add the edges to the graph object\n    for (int i = 0; i < num_edges; ++i)\n        add_edge(edge_array[i].first, edge_array[i].second, g);\n\n    Graph g1(edge_array, edge_array + sizeof(edge_array) / sizeof(Edge), num_vertices);\n}", "meta": {"hexsha": "f387d750ac6c009e577cf9c86e00b4924fa8c90d", "size": 1251, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tryboost/main.cpp", "max_stars_repo_name": "Machimedes/cppnotebook", "max_stars_repo_head_hexsha": "737faa2b26a63332bdbb9fffba46e5b6cfcaef9a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tryboost/main.cpp", "max_issues_repo_name": "Machimedes/cppnotebook", "max_issues_repo_head_hexsha": "737faa2b26a63332bdbb9fffba46e5b6cfcaef9a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tryboost/main.cpp", "max_forks_repo_name": "Machimedes/cppnotebook", "max_forks_repo_head_hexsha": "737faa2b26a63332bdbb9fffba46e5b6cfcaef9a", "max_forks_repo_licenses": ["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.0769230769, "max_line_length": 87, "alphanum_fraction": 0.6107114309, "num_tokens": 325, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.6477982043529716, "lm_q1q2_score": 0.4613827300323846}}
{"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#define NT2_UNIT_MODULE \"nt2 polynomials toolbox - plevl/simd Mode\"\n\n//////////////////////////////////////////////////////////////////////////////\n// unit test behavior of polynomials components in simd mode\n//////////////////////////////////////////////////////////////////////////////\n/// created  by jt the 06/03/2011\n///\n#include <nt2/polynomials/include/functions/plevl.hpp>\n#include <boost/simd/sdk/simd/native.hpp>\n\n#include <nt2/sdk/unit/tests/relation.hpp>\n#include <nt2/sdk/unit/module.hpp>\n#include <nt2/include/functions/splat.hpp>\n\n#include <boost/array.hpp>\n\nNT2_TEST_CASE_TPL ( plevl_real__2_0,  NT2_SIMD_REAL_TYPES)\n{\n  using nt2::plevl;\n  using nt2::tag::plevl_;\n  using boost::simd::native;\n\n  typedef NT2_SIMD_DEFAULT_EXTENSION  ext_t;\n  typedef native<T,ext_t>             vT;\n\n  static const boost::array<T, 3 > A = {{T(2), T(3), T(4) }};\n\n  NT2_TEST_EQUAL(plevl( nt2::splat<vT>(1), A)[0], T(10)); //1*1^3 + 2*1^2 + 3*1 +4\n  NT2_TEST_EQUAL(plevl( nt2::splat<vT>(2), A)[0], T(26)); //1*2^3 + 2*2^2 + 3*2 +4\n  NT2_TEST_EQUAL(plevl( nt2::splat<vT>(3), A)[0], T(58)); //1*3^3 + 2*3^2 + 3*3 +4\n\n} // end of test for floating_\n", "meta": {"hexsha": "23273c2105b2e007fc6a472802438458eb85e7ba", "size": 1651, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/core/polynomials/unit/simd/plevl.cpp", "max_stars_repo_name": "pbrunet/nt2", "max_stars_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/core/polynomials/unit/simd/plevl.cpp", "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/polynomials/unit/simd/plevl.cpp", "max_forks_repo_name": "pbrunet/nt2", "max_forks_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 40.2682926829, "max_line_length": 82, "alphanum_fraction": 0.5245305875, "num_tokens": 466, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.4612837142344487}}
{"text": "/*\r\n [auto_generated]\r\n libs/numeric/odeint/test_external/eigen/runge_kutta4.cpp\r\n\r\n [begin_description]\r\n tba.\r\n [end_description]\r\n\r\n Copyright 2013 Karsten Ahnert\r\n Copyright 2013 Mario Mulansky\r\n\r\n Distributed under the Boost Software License, Version 1.0.\r\n (See accompanying file LICENSE_1_0.txt or\r\n copy at http://www.boost.org/LICENSE_1_0.txt)\r\n */\r\n\r\n#include <boost/config.hpp>\r\n#ifdef BOOST_MSVC\r\n    #pragma warning(disable:4996)\r\n#endif\r\n\r\n#define BOOST_TEST_MODULE odeint_eigen_runge_kutta4\r\n\r\n#include <boost/test/unit_test.hpp>\r\n\r\n#include <boost/numeric/odeint/algebra/vector_space_algebra.hpp>\r\n#include <boost/numeric/odeint/stepper/runge_kutta4.hpp>\r\n#include <boost/numeric/odeint/external/eigen/eigen_resize.hpp>\r\n\r\nusing namespace boost::unit_test;\r\nusing namespace boost::numeric::odeint;\r\n\r\nstruct sys\r\n{\r\n    template< class State , class Deriv >\r\n    void operator()( const State &x , Deriv &dxdt , double t ) const\r\n    {\r\n        dxdt[0] = 1.0;\r\n    }\r\n};\r\n\r\n\r\nBOOST_AUTO_TEST_SUITE( eigen_runge_kutta4 )\r\n\r\nBOOST_AUTO_TEST_CASE( compile_time_matrix )\r\n{\r\n    typedef Eigen::Matrix< double , 1 , 1 > state_type;\r\n    state_type x;\r\n    x[0] = 10.0;\r\n    runge_kutta4< state_type , double , state_type , double , vector_space_algebra > rk4;\r\n    rk4.do_step( sys() , x , 0.0 , 0.1 );\r\n    BOOST_CHECK_CLOSE( x[0] , 10.1 , 1.0e-13 );\r\n    \r\n}\r\n\r\nBOOST_AUTO_TEST_CASE( runtime_matrix )\r\n{\r\n    typedef Eigen::Matrix< double , Eigen::Dynamic , 1 > state_type;\r\n    state_type x( 1 );\r\n    x[0] = 10.0;\r\n    runge_kutta4< state_type , double , state_type , double , vector_space_algebra > rk4;\r\n    rk4.do_step( sys() , x , 0.0 , 0.1 );\r\n    BOOST_CHECK_CLOSE( x[0] , 10.1 , 1.0e-13 );\r\n}\r\n\r\n\r\n\r\n\r\n\r\n\r\nBOOST_AUTO_TEST_CASE( compile_time_array )\r\n{\r\n    typedef Eigen::Array< double , 1 , 1 > state_type;\r\n    state_type x;\r\n    x[0] = 10.0;\r\n    runge_kutta4< state_type , double , state_type , double , vector_space_algebra > rk4;\r\n    rk4.do_step( sys() , x , 0.0 , 0.1 );\r\n    BOOST_CHECK_CLOSE( x[0] , 10.1 , 1.0e-13 );\r\n    \r\n}\r\n\r\nBOOST_AUTO_TEST_CASE( runtime_array )\r\n{\r\n    typedef Eigen::Array< double , Eigen::Dynamic , 1 > state_type;\r\n    state_type x( 1 );\r\n    x[0] = 10.0;\r\n    runge_kutta4< state_type , double , state_type , double , vector_space_algebra > rk4;\r\n    rk4.do_step( sys() , x , 0.0 , 0.1 );\r\n    BOOST_CHECK_CLOSE( x[0] , 10.1 , 1.0e-13 );\r\n}\r\n\r\n\r\n\r\nBOOST_AUTO_TEST_SUITE_END()\r\n", "meta": {"hexsha": "73c9494a6b3212bac42657317674ab8eb5dffcbb", "size": 2435, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/numeric/odeint/test_external/eigen/runge_kutta4.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": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/numeric/odeint/test_external/eigen/runge_kutta4.cpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-04T18:00:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-04T18:00:00.000Z", "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/numeric/odeint/test_external/eigen/runge_kutta4.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 25.6315789474, "max_line_length": 90, "alphanum_fraction": 0.6566735113, "num_tokens": 734, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.46128370100314403}}
{"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\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include <iostream>\n#include <cmath>\n\n#include <boost/numeric/mtl/matrix/inserter.hpp>\n#include <boost/numeric/mtl/matrix/dense2D.hpp>\n#include <boost/numeric/mtl/matrix/morton_dense.hpp> \n#include <boost/numeric/mtl/recursion/predefined_masks.hpp>\n#include <boost/numeric/mtl/matrix/compressed2D.hpp>\n\n#include <boost/numeric/mtl/operation/print_matrix.hpp>\n#include <boost/numeric/mtl/operation/frobenius_norm.hpp>\n\n\n\nusing namespace std;  \n\n\ntemplate <typename MatrixA>\nvoid test(MatrixA& a, const char* name)\n{\n    a= 0.0;\n    {\n\tmtl::mat::inserter<MatrixA>  ins(a);\n\t                  ins(0, 1) << 1.0; ins(0, 2) << 4.0;\n\tins(1, 0) << 1.0; ins(1, 1) << 3.0; ins(1, 2) << 4.0; ins(1, 3) << 4.0; \n\t                  ins(2, 1) << 9.0; ins(2, 2) << 4.0; ins(2, 3) << 2.0; \n\t                                    ins(3, 2) << 4.0;\n    }\n\n    std::cout << \"\\n\" << name << \" a = \\n\" << a << \"\\n\";\n    std::cout.precision (6);\n    std::cout << \"frobenius_norm(a) = \" << frobenius_norm(a) << \"\\n\"; std::cout.flush();\n\n    MTL_THROW_IF(frobenius_norm(a) < 13.266 || frobenius_norm(a) > 13.267, mtl::runtime_error(\"wrong frobenius_norm\")); \n}\n\n\nint main(int, char**)\n{\n    using namespace mtl;\n    unsigned size= 4;\n\n    dense2D<double>                                      dr(size, size);\n    dense2D<double, mat::parameters<col_major> >      dc(size, size);\n    morton_dense<double, recursion::morton_z_mask>       mzd(size, size);\n    morton_dense<double, recursion::doppled_2_row_mask>  d2r(size, size);\n    compressed2D<double>                                 cr(size, size);\n    compressed2D<double, mat::parameters<col_major> > cc(size, size);\n\n    dense2D<complex<double> >                            drc(size, size);\n    compressed2D<complex<double> >                       crc(size, size);\n\n    test(dr, \"Dense row major\");\n    test(dc, \"Dense column major\");\n    test(mzd, \"Morton Z-order\");\n    test(d2r, \"Hybrid 2 row-major\");\n    test(cr, \"Compressed row major\");\n    test(cc, \"Compressed column major\");\n    test(drc, \"Dense row major complex\");\n    test(crc, \"Compressed row major complex\");\n\n    return 0;\n}\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "c80ec9625b82ba2a2f20e71edeceaaae3d912773", "size": 2577, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/frobenius_norm_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/frobenius_norm_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/frobenius_norm_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.3186813187, "max_line_length": 120, "alphanum_fraction": 0.5999223904, "num_tokens": 775, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646140788307, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.4612591762154905}}
{"text": "/*\n * test_DIFF.cpp\n *\n *  Created on: 2013-4-18\n *      Author: fasiondog\n */\n\n\n#ifdef TEST_ALL_IN_ONE\n    #include <boost/test/unit_test.hpp>\n#else\n    #define BOOST_TEST_MODULE test_hikyuu_indicator_suite\n    #include <boost/test/unit_test.hpp>\n#endif\n\n#include <fstream>\n#include <hikyuu/StockManager.h>\n#include <hikyuu/indicator/crt/KDATA.h>\n#include <hikyuu/indicator/crt/DIFF.h>\n#include <hikyuu/indicator/crt/PRICELIST.h>\n\nusing namespace hku;\n\n/**\n * @defgroup test_indicator_DIFF test_indicator_DIFF\n * @ingroup test_hikyuu_indicator_suite\n * @{\n */\n\n/** @par \u68c0\u6d4b\u70b9 */\nBOOST_AUTO_TEST_CASE( test_DIFF ) {\n    /** @arg \u6b63\u5e38\u6d4b\u8bd5 */\n    PriceList d;\n    for (size_t i = 0; i < 10; ++i) {\n        d.push_back(i);\n    }\n\n    Indicator ind = PRICELIST(d);\n    Indicator diff = DIFF(ind);\n    BOOST_CHECK(diff.size() == 10);\n    BOOST_CHECK(diff.discard() == 1);\n    BOOST_CHECK(std::isnan(diff[0]));\n    for (size_t i = 1; i < 10; ++i) {\n        BOOST_CHECK(diff[i] == d[i] - d[i-1]);\n    }\n\n    /** @arg operator */\n    diff = DIFF();\n    Indicator expect = DIFF(ind);\n    Indicator result = diff(ind);\n    BOOST_CHECK(expect.size() == result.size());\n    for (size_t i = 0; i < result.discard(); i++) {\n        BOOST_CHECK(std::isnan(result[i]));\n    }\n    for (size_t i = result.discard(); i < expect.size(); ++i) {\n        BOOST_CHECK(result[i] == expect[i]);\n    }\n}\n\n\n//-----------------------------------------------------------------------------\n// test export\n//-----------------------------------------------------------------------------\n#if HKU_SUPPORT_SERIALIZATION\n\n/** @par \u68c0\u6d4b\u70b9 */\nBOOST_AUTO_TEST_CASE( test_DIFF_export ) {\n    StockManager& sm = StockManager::instance();\n    string filename(sm.tmpdir());\n    filename += \"/DIFF.xml\";\n\n    Stock stock = sm.getStock(\"sh000001\");\n    KData kdata = stock.getKData(KQuery(-20));\n    Indicator ma1 = DIFF(CLOSE(kdata));\n    {\n        std::ofstream ofs(filename);\n        boost::archive::xml_oarchive oa(ofs);\n        oa << BOOST_SERIALIZATION_NVP(ma1);\n    }\n\n    Indicator ma2;\n    {\n        std::ifstream ifs(filename);\n        boost::archive::xml_iarchive ia(ifs);\n        ia >> BOOST_SERIALIZATION_NVP(ma2);\n    }\n\n    BOOST_CHECK(ma1.size() == ma2.size());\n    BOOST_CHECK(ma1.discard() == ma2.discard());\n    BOOST_CHECK(ma1.getResultNumber() == ma2.getResultNumber());\n    for (size_t i = ma1.discard(); i < ma1.size(); ++i) {\n        BOOST_CHECK_CLOSE(ma1[i], ma2[i], 0.00001);\n    }\n}\n#endif /* #if HKU_SUPPORT_SERIALIZATION */\n\n/** @} */\n\n\n", "meta": {"hexsha": "fffcca9b6401eca1f8b76e16828c04f49a75e13c", "size": 2511, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "hikyuu_cpp/unit_test/libs/hikyuu/indicator/test_DIFF.cpp", "max_stars_repo_name": "awesome-archive/hikyuu", "max_stars_repo_head_hexsha": "c9dfcf6635c91e69ac1452fd27633085913806ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hikyuu_cpp/unit_test/libs/hikyuu/indicator/test_DIFF.cpp", "max_issues_repo_name": "awesome-archive/hikyuu", "max_issues_repo_head_hexsha": "c9dfcf6635c91e69ac1452fd27633085913806ce", "max_issues_repo_licenses": ["MIT"], "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_cpp/unit_test/libs/hikyuu/indicator/test_DIFF.cpp", "max_forks_repo_name": "awesome-archive/hikyuu", "max_forks_repo_head_hexsha": "c9dfcf6635c91e69ac1452fd27633085913806ce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-11-23T06:36:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-23T06:36:15.000Z", "avg_line_length": 25.11, "max_line_length": 79, "alphanum_fraction": 0.5738749502, "num_tokens": 681, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646010190477, "lm_q2_score": 0.6825737473266735, "lm_q1q2_score": 0.4612591760282858}}
{"text": "// Copyright 2015-2018 Hans Dembinski\n//\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n//[ guide_axis_with_uoflow_off\n\n#include <boost/histogram.hpp>\n#include <string>\n\nint main() {\n  using namespace boost::histogram;\n\n  // create a 1d-histogram over integer values from 1 to 6\n  auto h1 = make_histogram(axis::integer<int>(1, 7));\n  // axis has size 6...\n  assert(h1.axis().size() == 6);\n  // ... but histogram has size 8, because of overflow and underflow bins\n  assert(h1.size() == 8);\n\n  // create a 1d-histogram for throws of a six-sided die without extra bins,\n  // since the values cannot be smaller than 1 or larger than 6\n  auto h2 = make_histogram(axis::integer<int, use_default, axis::option::none>(1, 7));\n  // now size of axis and histogram is equal\n  assert(h2.axis().size() == 6);\n  assert(h2.size() == 6);\n}\n\n//]\n", "meta": {"hexsha": "2dd95b72bbab9b823dc8bd80ab951330c155e3ba", "size": 940, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/guide_axis_with_uoflow_off.cpp", "max_stars_repo_name": "henryiii/histogram", "max_stars_repo_head_hexsha": "d9f000cb86a4b4ac5ebfcb395616fa9aaa28e06c", "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/guide_axis_with_uoflow_off.cpp", "max_issues_repo_name": "henryiii/histogram", "max_issues_repo_head_hexsha": "d9f000cb86a4b4ac5ebfcb395616fa9aaa28e06c", "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/guide_axis_with_uoflow_off.cpp", "max_forks_repo_name": "henryiii/histogram", "max_forks_repo_head_hexsha": "d9f000cb86a4b4ac5ebfcb395616fa9aaa28e06c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3225806452, "max_line_length": 86, "alphanum_fraction": 0.6882978723, "num_tokens": 271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737473266735, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.4612591760282857}}
{"text": "/*\n    tests/eigen.cpp -- automatic conversion of Eigen types\n\n    Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>\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*/\n\n#include \"pybind11_tests.h\"\n#include \"constructor_stats.h\"\n#include <pybind11/eigen.h>\n#include <pybind11/stl.h>\n\n#if defined(_MSC_VER)\n#  pragma warning(disable: 4996) // C4996: std::unary_negation is deprecated\n#endif\n\n#include <Eigen/Cholesky>\n\nusing MatrixXdR = Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;\n\n\n\n// Sets/resets a testing reference matrix to have values of 10*r + c, where r and c are the\n// (1-based) row/column number.\ntemplate <typename M> void reset_ref(M &x) {\n    for (int i = 0; i < x.rows(); i++) for (int j = 0; j < x.cols(); j++)\n        x(i, j) = 11 + 10*i + j;\n}\n\n// Returns a static, column-major matrix\nEigen::MatrixXd &get_cm() {\n    static Eigen::MatrixXd *x;\n    if (!x) {\n        x = new Eigen::MatrixXd(3, 3);\n        reset_ref(*x);\n    }\n    return *x;\n}\n// Likewise, but row-major\nMatrixXdR &get_rm() {\n    static MatrixXdR *x;\n    if (!x) {\n        x = new MatrixXdR(3, 3);\n        reset_ref(*x);\n    }\n    return *x;\n}\n// Resets the values of the static matrices returned by get_cm()/get_rm()\nvoid reset_refs() {\n    reset_ref(get_cm());\n    reset_ref(get_rm());\n}\n\n// Returns element 2,1 from a matrix (used to test copy/nocopy)\ndouble get_elem(Eigen::Ref<const Eigen::MatrixXd> m) { return m(2, 1); };\n\n\n// Returns a matrix with 10*r + 100*c added to each matrix element (to help test that the matrix\n// reference is referencing rows/columns correctly).\ntemplate <typename MatrixArgType> Eigen::MatrixXd adjust_matrix(MatrixArgType m) {\n    Eigen::MatrixXd ret(m);\n    for (int c = 0; c < m.cols(); c++) for (int r = 0; r < m.rows(); r++)\n        ret(r, c) += 10*r + 100*c;\n    return ret;\n}\n\nstruct CustomOperatorNew {\n    CustomOperatorNew() = default;\n\n    Eigen::Matrix4d a = Eigen::Matrix4d::Zero();\n    Eigen::Matrix4d b = Eigen::Matrix4d::Identity();\n\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n};\n\nTEST_SUBMODULE(eigen, m) {\n    using FixedMatrixR = Eigen::Matrix<float, 5, 6, Eigen::RowMajor>;\n    using FixedMatrixC = Eigen::Matrix<float, 5, 6>;\n    using DenseMatrixR = Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;\n    using DenseMatrixC = Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic>;\n    using FourRowMatrixC = Eigen::Matrix<float, 4, Eigen::Dynamic>;\n    using FourColMatrixC = Eigen::Matrix<float, Eigen::Dynamic, 4>;\n    using FourRowMatrixR = Eigen::Matrix<float, 4, Eigen::Dynamic>;\n    using FourColMatrixR = Eigen::Matrix<float, Eigen::Dynamic, 4>;\n    using SparseMatrixR = Eigen::SparseMatrix<float, Eigen::RowMajor>;\n    using SparseMatrixC = Eigen::SparseMatrix<float>;\n\n    m.attr(\"have_eigen\") = true;\n\n    // various tests\n    m.def(\"double_col\", [](const Eigen::VectorXf &x) -> Eigen::VectorXf { return 2.0f * x; });\n    m.def(\"double_row\", [](const Eigen::RowVectorXf &x) -> Eigen::RowVectorXf { return 2.0f * x; });\n    m.def(\"double_complex\", [](const Eigen::VectorXcf &x) -> Eigen::VectorXcf { return 2.0f * x; });\n    m.def(\"double_threec\", [](py::EigenDRef<Eigen::Vector3f> x) { x *= 2; });\n    m.def(\"double_threer\", [](py::EigenDRef<Eigen::RowVector3f> x) { x *= 2; });\n    m.def(\"double_mat_cm\", [](Eigen::MatrixXf x) -> Eigen::MatrixXf { return 2.0f * x; });\n    m.def(\"double_mat_rm\", [](DenseMatrixR x) -> DenseMatrixR { return 2.0f * x; });\n\n    // test_eigen_ref_to_python\n    // Different ways of passing via Eigen::Ref; the first and second are the Eigen-recommended\n    m.def(\"cholesky1\", [](Eigen::Ref<MatrixXdR> x) -> Eigen::MatrixXd { return x.llt().matrixL(); });\n    m.def(\"cholesky2\", [](const Eigen::Ref<const MatrixXdR> &x) -> Eigen::MatrixXd { return x.llt().matrixL(); });\n    m.def(\"cholesky3\", [](const Eigen::Ref<MatrixXdR> &x) -> Eigen::MatrixXd { return x.llt().matrixL(); });\n    m.def(\"cholesky4\", [](Eigen::Ref<const MatrixXdR> x) -> Eigen::MatrixXd { return x.llt().matrixL(); });\n\n    // test_eigen_ref_mutators\n    // Mutators: these add some value to the given element using Eigen, but Eigen should be mapping into\n    // the numpy array data and so the result should show up there.  There are three versions: one that\n    // works on a contiguous-row matrix (numpy's default), one for a contiguous-column matrix, and one\n    // for any matrix.\n    auto add_rm = [](Eigen::Ref<MatrixXdR> x, int r, int c, double v) { x(r,c) += v; };\n    auto add_cm = [](Eigen::Ref<Eigen::MatrixXd> x, int r, int c, double v) { x(r,c) += v; };\n\n    // Mutators (Eigen maps into numpy variables):\n    m.def(\"add_rm\", add_rm); // Only takes row-contiguous\n    m.def(\"add_cm\", add_cm); // Only takes column-contiguous\n    // Overloaded versions that will accept either row or column contiguous:\n    m.def(\"add1\", add_rm);\n    m.def(\"add1\", add_cm);\n    m.def(\"add2\", add_cm);\n    m.def(\"add2\", add_rm);\n    // This one accepts a matrix of any stride:\n    m.def(\"add_any\", [](py::EigenDRef<Eigen::MatrixXd> x, int r, int c, double v) { x(r,c) += v; });\n\n    // Return mutable references (numpy maps into eigen variables)\n    m.def(\"get_cm_ref\", []() { return Eigen::Ref<Eigen::MatrixXd>(get_cm()); });\n    m.def(\"get_rm_ref\", []() { return Eigen::Ref<MatrixXdR>(get_rm()); });\n    // The same references, but non-mutable (numpy maps into eigen variables, but is !writeable)\n    m.def(\"get_cm_const_ref\", []() { return Eigen::Ref<const Eigen::MatrixXd>(get_cm()); });\n    m.def(\"get_rm_const_ref\", []() { return Eigen::Ref<const MatrixXdR>(get_rm()); });\n\n    m.def(\"reset_refs\", reset_refs); // Restores get_{cm,rm}_ref to original values\n\n    // Increments and returns ref to (same) matrix\n    m.def(\"incr_matrix\", [](Eigen::Ref<Eigen::MatrixXd> m, double v) {\n        m += Eigen::MatrixXd::Constant(m.rows(), m.cols(), v);\n        return m;\n    }, py::return_value_policy::reference);\n\n    // Same, but accepts a matrix of any strides\n    m.def(\"incr_matrix_any\", [](py::EigenDRef<Eigen::MatrixXd> m, double v) {\n        m += Eigen::MatrixXd::Constant(m.rows(), m.cols(), v);\n        return m;\n    }, py::return_value_policy::reference);\n\n    // Returns an eigen slice of even rows\n    m.def(\"even_rows\", [](py::EigenDRef<Eigen::MatrixXd> m) {\n        return py::EigenDMap<Eigen::MatrixXd>(\n                m.data(), (m.rows() + 1) / 2, m.cols(),\n                py::EigenDStride(m.outerStride(), 2 * m.innerStride()));\n    }, py::return_value_policy::reference);\n\n    // Returns an eigen slice of even columns\n    m.def(\"even_cols\", [](py::EigenDRef<Eigen::MatrixXd> m) {\n        return py::EigenDMap<Eigen::MatrixXd>(\n                m.data(), m.rows(), (m.cols() + 1) / 2,\n                py::EigenDStride(2 * m.outerStride(), m.innerStride()));\n    }, py::return_value_policy::reference);\n\n    // Returns diagonals: a vector-like object with an inner stride != 1\n    m.def(\"diagonal\", [](const Eigen::Ref<const Eigen::MatrixXd> &x) { return x.diagonal(); });\n    m.def(\"diagonal_1\", [](const Eigen::Ref<const Eigen::MatrixXd> &x) { return x.diagonal<1>(); });\n    m.def(\"diagonal_n\", [](const Eigen::Ref<const Eigen::MatrixXd> &x, int index) { return x.diagonal(index); });\n\n    // Return a block of a matrix (gives non-standard strides)\n    m.def(\"block\", [](const Eigen::Ref<const Eigen::MatrixXd> &x, int start_row, int start_col, int block_rows, int block_cols) {\n        return x.block(start_row, start_col, block_rows, block_cols);\n    });\n\n    // test_eigen_return_references, test_eigen_keepalive\n    // return value referencing/copying tests:\n    class ReturnTester {\n        Eigen::MatrixXd mat = create();\n    public:\n        ReturnTester() { print_created(this); }\n        ~ReturnTester() { print_destroyed(this); }\n        static Eigen::MatrixXd create() { return Eigen::MatrixXd::Ones(10, 10); }\n        static const Eigen::MatrixXd createConst() { return Eigen::MatrixXd::Ones(10, 10); }\n        Eigen::MatrixXd &get() { return mat; }\n        Eigen::MatrixXd *getPtr() { return &mat; }\n        const Eigen::MatrixXd &view() { return mat; }\n        const Eigen::MatrixXd *viewPtr() { return &mat; }\n        Eigen::Ref<Eigen::MatrixXd> ref() { return mat; }\n        Eigen::Ref<const Eigen::MatrixXd> refConst() { return mat; }\n        Eigen::Block<Eigen::MatrixXd> block(int r, int c, int nrow, int ncol) { return mat.block(r, c, nrow, ncol); }\n        Eigen::Block<const Eigen::MatrixXd> blockConst(int r, int c, int nrow, int ncol) const { return mat.block(r, c, nrow, ncol); }\n        py::EigenDMap<Eigen::Matrix2d> corners() { return py::EigenDMap<Eigen::Matrix2d>(mat.data(),\n                    py::EigenDStride(mat.outerStride() * (mat.outerSize()-1), mat.innerStride() * (mat.innerSize()-1))); }\n        py::EigenDMap<const Eigen::Matrix2d> cornersConst() const { return py::EigenDMap<const Eigen::Matrix2d>(mat.data(),\n                    py::EigenDStride(mat.outerStride() * (mat.outerSize()-1), mat.innerStride() * (mat.innerSize()-1))); }\n    };\n    using rvp = py::return_value_policy;\n    py::class_<ReturnTester>(m, \"ReturnTester\")\n        .def(py::init<>())\n        .def_static(\"create\", &ReturnTester::create)\n        .def_static(\"create_const\", &ReturnTester::createConst)\n        .def(\"get\", &ReturnTester::get, rvp::reference_internal)\n        .def(\"get_ptr\", &ReturnTester::getPtr, rvp::reference_internal)\n        .def(\"view\", &ReturnTester::view, rvp::reference_internal)\n        .def(\"view_ptr\", &ReturnTester::view, rvp::reference_internal)\n        .def(\"copy_get\", &ReturnTester::get)   // Default rvp: copy\n        .def(\"copy_view\", &ReturnTester::view) //         \"\n        .def(\"ref\", &ReturnTester::ref) // Default for Ref is to reference\n        .def(\"ref_const\", &ReturnTester::refConst) // Likewise, but const\n        .def(\"ref_safe\", &ReturnTester::ref, rvp::reference_internal)\n        .def(\"ref_const_safe\", &ReturnTester::refConst, rvp::reference_internal)\n        .def(\"copy_ref\", &ReturnTester::ref, rvp::copy)\n        .def(\"copy_ref_const\", &ReturnTester::refConst, rvp::copy)\n        .def(\"block\", &ReturnTester::block)\n        .def(\"block_safe\", &ReturnTester::block, rvp::reference_internal)\n        .def(\"block_const\", &ReturnTester::blockConst, rvp::reference_internal)\n        .def(\"copy_block\", &ReturnTester::block, rvp::copy)\n        .def(\"corners\", &ReturnTester::corners, rvp::reference_internal)\n        .def(\"corners_const\", &ReturnTester::cornersConst, rvp::reference_internal)\n        ;\n\n    // test_special_matrix_objects\n    // Returns a DiagonalMatrix with diagonal (1,2,3,...)\n    m.def(\"incr_diag\", [](int k) {\n        Eigen::DiagonalMatrix<int, Eigen::Dynamic> m(k);\n        for (int i = 0; i < k; i++) m.diagonal()[i] = i+1;\n        return m;\n    });\n\n    // Returns a SelfAdjointView referencing the lower triangle of m\n    m.def(\"symmetric_lower\", [](const Eigen::MatrixXi &m) {\n            return m.selfadjointView<Eigen::Lower>();\n    });\n    // Returns a SelfAdjointView referencing the lower triangle of m\n    m.def(\"symmetric_upper\", [](const Eigen::MatrixXi &m) {\n            return m.selfadjointView<Eigen::Upper>();\n    });\n\n    // Test matrix for various functions below.\n    Eigen::MatrixXf mat(5, 6);\n    mat << 0,  3,  0,  0,  0, 11,\n           22, 0,  0,  0, 17, 11,\n           7,  5,  0,  1,  0, 11,\n           0,  0,  0,  0,  0, 11,\n           0,  0, 14,  0,  8, 11;\n\n    // test_fixed, and various other tests\n    m.def(\"fixed_r\", [mat]() -> FixedMatrixR { return FixedMatrixR(mat); });\n    m.def(\"fixed_r_const\", [mat]() -> const FixedMatrixR { return FixedMatrixR(mat); });\n    m.def(\"fixed_c\", [mat]() -> FixedMatrixC { return FixedMatrixC(mat); });\n    m.def(\"fixed_copy_r\", [](const FixedMatrixR &m) -> FixedMatrixR { return m; });\n    m.def(\"fixed_copy_c\", [](const FixedMatrixC &m) -> FixedMatrixC { return m; });\n    // test_mutator_descriptors\n    m.def(\"fixed_mutator_r\", [](Eigen::Ref<FixedMatrixR>) {});\n    m.def(\"fixed_mutator_c\", [](Eigen::Ref<FixedMatrixC>) {});\n    m.def(\"fixed_mutator_a\", [](py::EigenDRef<FixedMatrixC>) {});\n    // test_dense\n    m.def(\"dense_r\", [mat]() -> DenseMatrixR { return DenseMatrixR(mat); });\n    m.def(\"dense_c\", [mat]() -> DenseMatrixC { return DenseMatrixC(mat); });\n    m.def(\"dense_copy_r\", [](const DenseMatrixR &m) -> DenseMatrixR { return m; });\n    m.def(\"dense_copy_c\", [](const DenseMatrixC &m) -> DenseMatrixC { return m; });\n    // test_sparse, test_sparse_signature\n    m.def(\"sparse_r\", [mat]() -> SparseMatrixR { return Eigen::SparseView<Eigen::MatrixXf>(mat); });\n    m.def(\"sparse_c\", [mat]() -> SparseMatrixC { return Eigen::SparseView<Eigen::MatrixXf>(mat); });\n    m.def(\"sparse_copy_r\", [](const SparseMatrixR &m) -> SparseMatrixR { return m; });\n    m.def(\"sparse_copy_c\", [](const SparseMatrixC &m) -> SparseMatrixC { return m; });\n    // test_partially_fixed\n    m.def(\"partial_copy_four_rm_r\", [](const FourRowMatrixR &m) -> FourRowMatrixR { return m; });\n    m.def(\"partial_copy_four_rm_c\", [](const FourColMatrixR &m) -> FourColMatrixR { return m; });\n    m.def(\"partial_copy_four_cm_r\", [](const FourRowMatrixC &m) -> FourRowMatrixC { return m; });\n    m.def(\"partial_copy_four_cm_c\", [](const FourColMatrixC &m) -> FourColMatrixC { return m; });\n\n    // test_cpp_casting\n    // Test that we can cast a numpy object to a Eigen::MatrixXd explicitly\n    m.def(\"cpp_copy\", [](py::handle m) { return m.cast<Eigen::MatrixXd>()(1, 0); });\n    m.def(\"cpp_ref_c\", [](py::handle m) { return m.cast<Eigen::Ref<Eigen::MatrixXd>>()(1, 0); });\n    m.def(\"cpp_ref_r\", [](py::handle m) { return m.cast<Eigen::Ref<MatrixXdR>>()(1, 0); });\n    m.def(\"cpp_ref_any\", [](py::handle m) { return m.cast<py::EigenDRef<Eigen::MatrixXd>>()(1, 0); });\n\n\n    // test_nocopy_wrapper\n    // Test that we can prevent copying into an argument that would normally copy: First a version\n    // that would allow copying (if types or strides don't match) for comparison:\n    m.def(\"get_elem\", &get_elem);\n    // Now this alternative that calls the tells pybind to fail rather than copy:\n    m.def(\"get_elem_nocopy\", [](Eigen::Ref<const Eigen::MatrixXd> m) -> double { return get_elem(m); },\n            py::arg().noconvert());\n    // Also test a row-major-only no-copy const ref:\n    m.def(\"get_elem_rm_nocopy\", [](Eigen::Ref<const Eigen::Matrix<long, -1, -1, Eigen::RowMajor>> &m) -> long { return m(2, 1); },\n            py::arg().noconvert());\n\n    // test_issue738\n    // Issue #738: 1xN or Nx1 2D matrices were neither accepted nor properly copied with an\n    // incompatible stride value on the length-1 dimension--but that should be allowed (without\n    // requiring a copy!) because the stride value can be safely ignored on a size-1 dimension.\n    m.def(\"iss738_f1\", &adjust_matrix<const Eigen::Ref<const Eigen::MatrixXd> &>, py::arg().noconvert());\n    m.def(\"iss738_f2\", &adjust_matrix<const Eigen::Ref<const Eigen::Matrix<double, -1, -1, Eigen::RowMajor>> &>, py::arg().noconvert());\n\n    // test_issue1105\n    // Issue #1105: when converting from a numpy two-dimensional (Nx1) or (1xN) value into a dense\n    // eigen Vector or RowVector, the argument would fail to load because the numpy copy would fail:\n    // numpy won't broadcast a Nx1 into a 1-dimensional vector.\n    m.def(\"iss1105_col\", [](Eigen::VectorXd) { return true; });\n    m.def(\"iss1105_row\", [](Eigen::RowVectorXd) { return true; });\n\n    // test_named_arguments\n    // Make sure named arguments are working properly:\n    m.def(\"matrix_multiply\", [](const py::EigenDRef<const Eigen::MatrixXd> A, const py::EigenDRef<const Eigen::MatrixXd> B)\n            -> Eigen::MatrixXd {\n        if (A.cols() != B.rows()) throw std::domain_error(\"Nonconformable matrices!\");\n        return A * B;\n    }, py::arg(\"A\"), py::arg(\"B\"));\n\n    // test_custom_operator_new\n    py::class_<CustomOperatorNew>(m, \"CustomOperatorNew\")\n        .def(py::init<>())\n        .def_readonly(\"a\", &CustomOperatorNew::a)\n        .def_readonly(\"b\", &CustomOperatorNew::b);\n\n    // test_eigen_ref_life_support\n    // In case of a failure (the caster's temp array does not live long enough), creating\n    // a new array (np.ones(10)) increases the chances that the temp array will be garbage\n    // collected and/or that its memory will be overridden with different values.\n    m.def(\"get_elem_direct\", [](Eigen::Ref<const Eigen::VectorXd> v) {\n        py::module::import(\"numpy\").attr(\"ones\")(10);\n        return v(5);\n    });\n    m.def(\"get_elem_indirect\", [](std::vector<Eigen::Ref<const Eigen::VectorXd>> v) {\n        py::module::import(\"numpy\").attr(\"ones\")(10);\n        return v[0](5);\n    });\n}\n\n", "meta": {"hexsha": "29d9c537be7a5cf26b2acf195f5c898e0737110d", "size": 16684, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_eigen.cpp", "max_stars_repo_name": "JessvLS/project_spring_2020", "max_stars_repo_head_hexsha": "ae5387afce3faabba1d8ab579de2dd8c80f6ffa7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/test_eigen.cpp", "max_issues_repo_name": "JessvLS/project_spring_2020", "max_issues_repo_head_hexsha": "ae5387afce3faabba1d8ab579de2dd8c80f6ffa7", "max_issues_repo_licenses": ["Apache-2.0"], "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/test_eigen.cpp", "max_forks_repo_name": "JessvLS/project_spring_2020", "max_forks_repo_head_hexsha": "ae5387afce3faabba1d8ab579de2dd8c80f6ffa7", "max_forks_repo_licenses": ["Apache-2.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.4048338369, "max_line_length": 136, "alphanum_fraction": 0.6350994965, "num_tokens": 4739, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.46125916730122557}}
{"text": "//---------------------------------------------------------------------------//\r\n// Copyright (c) 2013 Kyle Lutz <kyle.r.lutz@gmail.com>\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://boostorg.github.com/compute for more information.\r\n//---------------------------------------------------------------------------//\r\n\r\n#define BOOST_TEST_MODULE TestMerge\r\n#include <boost/test/unit_test.hpp>\r\n\r\n#include <boost/compute/system.hpp>\r\n#include <boost/compute/types/pair.hpp>\r\n#include <boost/compute/algorithm/copy_n.hpp>\r\n#include <boost/compute/algorithm/merge.hpp>\r\n#include <boost/compute/container/vector.hpp>\r\n#include <boost/compute/lambda.hpp>\r\n\r\n#include \"check_macros.hpp\"\r\n#include \"context_setup.hpp\"\r\n\r\nBOOST_AUTO_TEST_CASE(simple_merge_int)\r\n{\r\n    int data1[] = { 1, 3, 5, 7 };\r\n    int data2[] = { 2, 4, 6, 8 };\r\n\r\n    boost::compute::vector<int> v1(4, context);\r\n    boost::compute::vector<int> v2(4, context);\r\n    boost::compute::vector<int> v3(8, context);\r\n\r\n    boost::compute::copy_n(data1, 4, v1.begin(), queue);\r\n    boost::compute::copy_n(data2, 4, v2.begin(), queue);\r\n    boost::compute::fill(v3.begin(), v3.end(), 0, queue);\r\n\r\n    // merge v1 with v2 into v3\r\n    boost::compute::merge(\r\n        v1.begin(), v1.end(),\r\n        v2.begin(), v2.end(),\r\n        v3.begin(),\r\n        queue\r\n    );\r\n    CHECK_RANGE_EQUAL(int, 8, v3, (1, 2, 3, 4, 5, 6, 7, 8));\r\n\r\n    // merge v2 with v1 into v3\r\n    boost::compute::merge(\r\n        v2.begin(), v2.end(),\r\n        v1.begin(), v1.end(),\r\n        v3.begin(),\r\n        queue\r\n    );\r\n    CHECK_RANGE_EQUAL(int, 8, v3, (1, 2, 3, 4, 5, 6, 7, 8));\r\n\r\n    // merge v1 with v1 into v3\r\n    boost::compute::merge(\r\n        v1.begin(), v1.end(),\r\n        v1.begin(), v1.end(),\r\n        v3.begin(),\r\n        queue\r\n    );\r\n    CHECK_RANGE_EQUAL(int, 8, v3, (1, 1, 3, 3, 5, 5, 7, 7));\r\n\r\n    // merge v2 with v2 into v3\r\n    boost::compute::merge(\r\n        v2.begin(), v2.end(),\r\n        v2.begin(), v2.end(),\r\n        v3.begin(),\r\n        queue\r\n    );\r\n    CHECK_RANGE_EQUAL(int, 8, v3, (2, 2, 4, 4, 6, 6, 8, 8));\r\n\r\n    // merge v1 with empty range into v3\r\n    boost::compute::merge(\r\n        v1.begin(), v1.end(),\r\n        v1.begin(), v1.begin(),\r\n        v3.begin(),\r\n        queue\r\n    );\r\n    CHECK_RANGE_EQUAL(int, 4, v3, (1, 3, 5, 7));\r\n\r\n    // merge v2 with empty range into v3\r\n    boost::compute::merge(\r\n        v1.begin(), v1.begin(),\r\n        v2.begin(), v2.end(),\r\n        v3.begin(),\r\n        queue\r\n    );\r\n    CHECK_RANGE_EQUAL(int, 4, v3, (2, 4, 6, 8));\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(merge_pairs)\r\n{\r\n    std::vector<std::pair<int, float> > data1;\r\n    std::vector<std::pair<int, float> > data2;\r\n\r\n    data1.push_back(std::make_pair(0, 0.1f));\r\n    data1.push_back(std::make_pair(2, 2.1f));\r\n    data1.push_back(std::make_pair(4, 4.1f));\r\n    data1.push_back(std::make_pair(6, 6.1f));\r\n    data2.push_back(std::make_pair(1, 1.1f));\r\n    data2.push_back(std::make_pair(3, 3.1f));\r\n    data2.push_back(std::make_pair(5, 5.1f));\r\n    data2.push_back(std::make_pair(7, 7.1f));\r\n\r\n    std::vector<std::pair<int, float> > data3(data1.size() + data2.size());\r\n    std::fill(data3.begin(), data3.end(), std::make_pair(-1, -1.f));\r\n\r\n    boost::compute::vector<std::pair<int, float> > v1(data1.size(), context);\r\n    boost::compute::vector<std::pair<int, float> > v2(data2.size(), context);\r\n    boost::compute::vector<std::pair<int, float> > v3(data3.size(), context);\r\n\r\n    boost::compute::copy(data1.begin(), data1.end(), v1.begin(), queue);\r\n    boost::compute::copy(data2.begin(), data2.end(), v2.begin(), queue);\r\n\r\n    using ::boost::compute::lambda::_1;\r\n    using ::boost::compute::lambda::_2;\r\n    using ::boost::compute::lambda::get;\r\n\r\n    boost::compute::merge(\r\n        v1.begin(), v1.end(),\r\n        v2.begin(), v2.end(),\r\n        v3.begin(),\r\n        get<0>(_1) < get<0>(_2),\r\n        queue\r\n    );\r\n\r\n    boost::compute::copy(v3.begin(), v3.end(), data3.begin(), queue);\r\n\r\n    BOOST_CHECK(v3[0] == std::make_pair(0, 0.1f));\r\n    BOOST_CHECK(v3[1] == std::make_pair(1, 1.1f));\r\n    BOOST_CHECK(v3[2] == std::make_pair(2, 2.1f));\r\n    BOOST_CHECK(v3[3] == std::make_pair(3, 3.1f));\r\n    BOOST_CHECK(v3[4] == std::make_pair(4, 4.1f));\r\n    BOOST_CHECK(v3[5] == std::make_pair(5, 5.1f));\r\n    BOOST_CHECK(v3[6] == std::make_pair(6, 6.1f));\r\n    BOOST_CHECK(v3[7] == std::make_pair(7, 7.1f));\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(merge_floats)\r\n{\r\n    float data1[] = { 1.1f, 2.2f, 3.3f, 4.4f,\r\n                      5.5f, 6.6f, 7.7f, 8.8f };\r\n    float data2[] = { 1.0f, 2.0f, 3.9f, 4.9f,\r\n                      6.8f, 6.9f, 7.0f, 7.1f };\r\n\r\n    boost::compute::vector<float> v1(8, context);\r\n    boost::compute::vector<float> v2(8, context);\r\n    boost::compute::vector<float> v3(v1.size() + v2.size(), context);\r\n\r\n    boost::compute::copy_n(data1, 8, v1.begin(), queue);\r\n    boost::compute::copy_n(data2, 8, v2.begin(), queue);\r\n    boost::compute::fill(v3.begin(), v3.end(), 0.f, queue);\r\n\r\n    boost::compute::merge(\r\n        v1.begin(), v1.end(),\r\n        v2.begin(), v2.end(),\r\n        v3.begin(),\r\n        queue\r\n    );\r\n    CHECK_RANGE_EQUAL(float, 16, v3,\r\n      (1.0f, 1.1f, 2.0f, 2.2f, 3.3f, 3.9f, 4.4f, 4.9f,\r\n       5.5f, 6.6f, 6.8f, 6.9f, 7.0f, 7.1f, 7.7f, 8.8f)\r\n    );\r\n}\r\n\r\nBOOST_AUTO_TEST_SUITE_END()\r\n", "meta": {"hexsha": "185e9161b56d3c1905715cf9c49c824e47756895", "size": 5427, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/compute/test/test_merge.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": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/compute/test/test_merge.cpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-04T18:00:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-04T18:00:00.000Z", "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/compute/test/test_merge.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 32.3035714286, "max_line_length": 80, "alphanum_fraction": 0.5437626681, "num_tokens": 1793, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.4612591629376954}}
{"text": "//  (C) Copyright Eric Niebler 2005.\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 <boost/test/unit_test.hpp>\r\n#include <boost/time_series/characteristic_series.hpp>\r\n#include <boost/time_series/constant_series.hpp>\r\n#include <boost/time_series/delta_series.hpp>\r\n#include <boost/time_series/dense_series.hpp>\r\n#include <boost/time_series/heaviside_series.hpp>\r\n#include <boost/time_series/inverse_heaviside_series.hpp>\r\n#include <boost/time_series/piecewise_constant_series.hpp>\r\n#include <boost/time_series/clipped_series.hpp>\r\n#include <boost/time_series/sparse_series.hpp>\r\n#include <boost/time_series/ordered_inserter.hpp>\r\n#include <boost/time_series/numeric/clip.hpp>\r\n\r\nusing namespace boost;\r\nusing namespace unit_test;\r\n\r\nnamespace seq = boost::sequence;\r\nnamespace rrs = boost::range_run_storage;\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// test_shift\r\n//\r\ntemplate<typename Series>\r\nvoid test_clip()\r\n{\r\n    Series base;\r\n\r\n    time_series::make_ordered_inserter(base)\r\n        (1, -1, 2)\r\n        (2, 3, 5)\r\n        (3, 6, 9)\r\n    .commit();\r\n\r\n    // Sanity check\r\n    time_series::piecewise_constant_series<int> base_result;\r\n    time_series::make_ordered_inserter(base_result)\r\n        (1, -1, 2)\r\n        (2, 3, 5)\r\n        (3, 6, 9)\r\n    .commit();\r\n    BOOST_CHECK_EQUAL(base, base_result);\r\n\r\n    // Test1: clip right 1\r\n    Series test1 = time_series::clip(base, -1, 8);\r\n    time_series::piecewise_constant_series<int> test1_result;\r\n    time_series::make_ordered_inserter(test1_result)\r\n        (1, -1, 2)\r\n        (2, 3, 5)\r\n        (3, 6, 8)\r\n    .commit();\r\n    BOOST_CHECK_EQUAL(test1.discretization(), 1);\r\n    BOOST_CHECK_EQUAL(test1, test1_result);\r\n\r\n    // Test2: clip left 1\r\n    Series test2 = time_series::clip(base, 0, 9);\r\n    time_series::piecewise_constant_series<int> test2_result;\r\n    time_series::make_ordered_inserter(test2_result)\r\n        (1, 0, 2)\r\n        (2, 3, 5)\r\n        (3, 6, 9)\r\n    .commit();\r\n    BOOST_CHECK_EQUAL(test2.discretization(), 1);\r\n    BOOST_CHECK_EQUAL(test2, test2_result);\r\n\r\n    // Test3: clip right 5\r\n    Series test3 = time_series::clip(base, -1, 4);\r\n    time_series::piecewise_constant_series<int> test3_result;\r\n    time_series::make_ordered_inserter(test3_result)\r\n        (1, -1, 2)\r\n        (2, 3, 4)\r\n    .commit();\r\n    BOOST_CHECK_EQUAL(test3.discretization(), 1);\r\n    BOOST_CHECK_EQUAL(test3, test3_result);\r\n\r\n    // Test4: clip left 5\r\n    Series test4 = time_series::clip(base, 4, 9);\r\n    time_series::piecewise_constant_series<int> test4_result;\r\n    time_series::make_ordered_inserter(test4_result)\r\n        (2, 4, 5)\r\n        (3, 6, 9)\r\n    .commit();\r\n    BOOST_CHECK_EQUAL(test4.discretization(), 1);\r\n    BOOST_CHECK_EQUAL(test4, test4_result);\r\n\r\n    // Test5: clip right 4, self-assign\r\n    test3 = time_series::clip(test3, -1, 0);\r\n    time_series::piecewise_constant_series<int> test5_result;\r\n    time_series::make_ordered_inserter(test5_result)\r\n        (1, -1, 0)\r\n    .commit();\r\n    BOOST_CHECK_EQUAL(test3.discretization(), 1);\r\n    BOOST_CHECK_EQUAL(test3, test5_result);\r\n\r\n    // Test6: clip left 4, self-assign\r\n    test4 = time_series::clip(test4, 8, 9);\r\n    time_series::piecewise_constant_series<int> test6_result;\r\n    time_series::make_ordered_inserter(test6_result)\r\n        (3, 8, 9)\r\n    .commit();\r\n    BOOST_CHECK_EQUAL(test4.discretization(), 1);\r\n    BOOST_CHECK_EQUAL(test4, test6_result);\r\n}\r\n\r\nvoid test_clip2()\r\n{\r\n    using namespace boost;\r\n    using namespace time_series;\r\n\r\n    dense_series<int> d(start = -2, stop = 8, value = 5);\r\n    clipped_series<dense_series<int> > cd = clip(d, 3, 8);\r\n\r\n    piecewise_constant_series<int> test1_result;\r\n    make_ordered_inserter(test1_result)\r\n        (5, 3, 8)\r\n    .commit();\r\n    BOOST_CHECK_EQUAL(cd, test1_result);\r\n\r\n    for(int i = -10; i < 20; ++i)\r\n    {\r\n        BOOST_CHECK_EQUAL(cd[i], test1_result[i]);\r\n    }\r\n\r\n    for(int i = -10; i < 20; ++i)\r\n    {\r\n        BOOST_CHECK_EQUAL(range_run_storage::get_at(cd, i), range_run_storage::get_at(test1_result, i));\r\n    }\r\n\r\n    constant_series<int> c(5);\r\n    clipped_series<constant_series<int> > cc = clip(c, 3, 8);\r\n\r\n    BOOST_CHECK_EQUAL(0, std::distance(seq::begin(cc), seq::end(cc)));\r\n    BOOST_CHECK_EQUAL(3, rrs::offset(rrs::pre_run(cc)));\r\n    BOOST_CHECK_EQUAL(5u, rrs::length(rrs::pre_run(cc)));\r\n    BOOST_CHECK_EQUAL(5, rrs::pre_value(cc));\r\n\r\n    clipped_series<constant_series<int> > cc2 = clip(c, 3, inf);\r\n\r\n    BOOST_CHECK_EQUAL(0, std::distance(seq::begin(cc2), seq::end(cc2)));\r\n    BOOST_CHECK_EQUAL(5, rrs::pre_value(cc2));\r\n    BOOST_CHECK_EQUAL(3, rrs::offset(rrs::pre_run(cc2)));\r\n    BOOST_CHECK(inf == rrs::end_offset(rrs::pre_run(cc2)));\r\n}\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// init_unit_test_suite\r\n//\r\ntest_suite* init_unit_test_suite( int argc, char* argv[] )\r\n{\r\n    test_suite *test = BOOST_TEST_SUITE(\"clip test\");\r\n\r\n    void (*pfn_dense)() = &test_clip<time_series::dense_series<int> >;\r\n    test->add(BOOST_TEST_CASE(pfn_dense));\r\n\r\n    void (*pfn_sparse)() = &test_clip<time_series::sparse_series<int> >;\r\n    test->add(BOOST_TEST_CASE(pfn_sparse));\r\n\r\n    void (*pfn_piecewise_constant)() = &test_clip<time_series::piecewise_constant_series<int> >;\r\n    test->add(BOOST_TEST_CASE(pfn_piecewise_constant));\r\n\r\n    test->add(BOOST_TEST_CASE(&test_clip2));\r\n\r\n    return test;\r\n}\r\n", "meta": {"hexsha": "ba39adb1b2af8e0ceb640cb4a0f898019d8ea7eb", "size": 5606, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/time_series/test/clip.cpp", "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": "libs/time_series/test/clip.cpp", "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": "libs/time_series/test/clip.cpp", "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": 33.1715976331, "max_line_length": 105, "alphanum_fraction": 0.6432393864, "num_tokens": 1510, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.4612591628440931}}
{"text": "#include \"ICPReg.h\"\n#include <Eigen/src/Core/IO.h>\n\ntypedef pcl::PointXYZ PointT;\ntypedef pcl::PointCloud<PointT> PointCloudT;\n\nbool next_iteration = false;\n\nvoid\nkeyboardEventOccurred(const pcl::visualization::KeyboardEvent& event,\n\tvoid* nothing)\n{\n\tif (event.getKeySym() == \"space\" && event.keyDown())\n\t\tnext_iteration = true;\n}\n\nICPReg::ICPReg(QString filename_model, QString filename_data, int iterations)\n\t: filename_model(filename_model),filename_data(filename_data),iterations(iterations)\n{\n\n\t// The point clouds we will be using\n\tcloud_in.reset(new PointCloudT);  // Original point cloud\n\tcloud_tr.reset(new PointCloudT);  // Transformed point cloud\n\tcloud_icp.reset(new PointCloudT);  // ICP output point cloud\n\tviewer.reset(new pcl::visualization::PCLVisualizer(\"viewer\", false));\n}\n\n\nICPReg::~ICPReg()\n{\n}\n\nvoid\nICPReg::print4x4Matrix(const Eigen::Matrix4d & matrix)\n{\n\tprintf(\"Rotation matrix :\\n\");\n\tprintf(\"    | %6.3f %6.3f %6.3f | \\n\", matrix(0, 0), matrix(0, 1), matrix(0, 2));\n\tprintf(\"R = | %6.3f %6.3f %6.3f | \\n\", matrix(1, 0), matrix(1, 1), matrix(1, 2));\n\tprintf(\"    | %6.3f %6.3f %6.3f | \\n\", matrix(2, 0), matrix(2, 1), matrix(2, 2));\n\tprintf(\"Translation vector :\\n\");\n\tprintf(\"t = < %6.3f, %6.3f, %6.3f >\\n\\n\", matrix(0, 3), matrix(1, 3), matrix(2, 3));\n}\n\nvoid\nICPReg::proceed(QString filename_model, QString filename_data, int iterations)\n{\n\tpcl::console::TicToc time;\n\ttime.tic();\n\tstd::string file_name = filename_model.toStdString();\n\n\temit infoRec(\"Loading model...\");\n\temit progressBarUpdate(10);\n\n\tpcl::io::loadPLYFile(file_name, *cloud_in);\n\n\temit infoRec(\"Loading model finished.\");\n\temit progressBarUpdate(20);\n\t\n\t\t\t\t\t\t //Downsampling\n\tpcl::console::print_highlight(\"Downsampling...\\n\");\n\tpcl::VoxelGrid<pcl::PointXYZ> grid;\n\tconst float leaf = 0.005f;\n\tgrid.setLeafSize(leaf, leaf, leaf);\n\tgrid.setInputCloud(cloud_in);\n\tgrid.filter(*cloud_in);\n\n\temit infoRec(\"Downsampling finished.\");\n\temit progressBarUpdate(30);\n\n\t// Defining a rotation matrix and translation vector\n\tEigen::Matrix4d transformation_matrix = Eigen::Matrix4d::Identity();\n\n\t// A rotation matrix (see https://en.wikipedia.org/wiki/Rotation_matrix)\n\tdouble theta = M_PI / 8;  // The angle of rotation in radians\n\ttransformation_matrix(0, 0) = cos(theta);\n\ttransformation_matrix(0, 1) = -sin(theta);\n\ttransformation_matrix(1, 0) = sin(theta);\n\ttransformation_matrix(1, 1) = cos(theta);\n\n\t// A translation on Z axis (0.4 meters)\n\ttransformation_matrix(2, 3) = 0.4;\n\n\t// Display in terminal the transformation matrix\n\tstd::cout << \"Applying this rigid transformation to: cloud_in -> cloud_icp\" << std::endl;\n\tprint4x4Matrix(transformation_matrix);\n\n\t// Executing the transformation\n\tpcl::transformPointCloud(*cloud_in, *cloud_icp, transformation_matrix);\n\t*cloud_tr = *cloud_icp;  // We backup cloud_icp into cloud_tr for later use\n\n\temit infoRec(\"Transform finished.\");\n\temit progressBarUpdate(40);\n\tQString matrix;\n\tEigen::IOFormat OctaveFmt(Eigen::StreamPrecision, 0, \", \", \";\\n\", \"\", \"\", \"[\", \"]\");\n\tstd::stringstream trans;\n\ttrans << transformation_matrix.format(OctaveFmt);\n\temit infoRec(QString::fromStdString(trans.str()));\n\n\t\t\t\t\t\t\t // The Iterative Closest Point algorithm\n\ttime.tic();\n\tpcl::IterativeClosestPoint<PointT, PointT> icp;\n\ticp.setMaximumIterations(iterations);\n\ticp.setInputSource(cloud_icp);\n\ticp.setInputTarget(cloud_in);\n\ticp.align(*cloud_icp);\n\ticp.setMaximumIterations(1);  // We set this variable to 1 for the next time we will call .align () function\n\tstd::cout << \"Applied \" << iterations << \" ICP iteration(s) in \" << time.toc() << \" ms\" << std::endl;\n\n\tif (icp.hasConverged())\n\t{\n\t\tstd::cout << \"\\nICP has converged, score is \" << icp.getFitnessScore() << std::endl;\n\t\tstd::cout << \"\\nICP transformation \" << iterations << \" : cloud_icp -> cloud_in\" << std::endl;\n\t\ttransformation_matrix = icp.getFinalTransformation().cast<double>();\n\t\tprint4x4Matrix(transformation_matrix);\n\n\t\ttrans.str(\"\");\n\t\ttrans << transformation_matrix.format(OctaveFmt);\n\t\temit infoRec(QString::fromStdString(trans.str()));\n\t}\n\telse\n\t{\n\t\tPCL_ERROR(\"\\nICP has not converged.\\n\");\n\t\treturn;\n\t}\n\n\tviewer.reset(new pcl::visualization::PCLVisualizer(\"icp_demo\", true));\n\t// Create two verticaly separated viewports\n\tint v1(0);\n\tint v2(1);\n\tviewer->createViewPort(0.0, 0.0, 0.5, 1.0, v1);\n\tviewer->createViewPort(0.5, 0.0, 1.0, 1.0, v2);\n\n\t// The color we will be using\n\tfloat bckgr_gray_level = 0.0;  // Black\n\tfloat txt_gray_lvl = 1.0 - bckgr_gray_level;\n\n\t// Original point cloud is white\n\tpcl::visualization::PointCloudColorHandlerCustom<PointT> cloud_in_color_h(cloud_in, (int)255 * txt_gray_lvl, (int)255 * txt_gray_lvl,\n\t\t(int)255 * txt_gray_lvl);\n\tviewer->addPointCloud(cloud_in, cloud_in_color_h, \"cloud_in_v1\", v1);\n\tviewer->addPointCloud(cloud_in, cloud_in_color_h, \"cloud_in_v2\", v2);\n\n\t// Transformed point cloud is green\n\tpcl::visualization::PointCloudColorHandlerCustom<PointT> cloud_tr_color_h(cloud_tr, 20, 180, 20);\n\tviewer->addPointCloud(cloud_tr, cloud_tr_color_h, \"cloud_tr_v1\", v1);\n\n\t// ICP aligned point cloud is red\n\tpcl::visualization::PointCloudColorHandlerCustom<PointT> cloud_icp_color_h(cloud_icp, 180, 20, 20);\n\tviewer->addPointCloud(cloud_icp, cloud_icp_color_h, \"cloud_icp_v2\", v2);\n\n\t// Adding text descriptions in each viewport\n\tviewer->addText(\"White: Original point cloud\\nGreen: Matrix transformed point cloud\", 10, 15, 16, txt_gray_lvl, txt_gray_lvl, txt_gray_lvl, \"icp_info_1\", v1);\n\tviewer->addText(\"White: Original point cloud\\nRed: ICP aligned point cloud\", 10, 15, 16, txt_gray_lvl, txt_gray_lvl, txt_gray_lvl, \"icp_info_2\", v2);\n\n\tstd::stringstream ss;\n\tss << iterations;\n\tstd::string iterations_cnt = \"ICP iterations = \" + ss.str();\n\tviewer->addText(iterations_cnt, 10, 60, 16, txt_gray_lvl, txt_gray_lvl, txt_gray_lvl, \"iterations_cnt\", v2);\n\n\t// Set background color\n\tviewer->setBackgroundColor(bckgr_gray_level, bckgr_gray_level, bckgr_gray_level, v1);\n\tviewer->setBackgroundColor(bckgr_gray_level, bckgr_gray_level, bckgr_gray_level, v2);\n\n\t// Set camera position and orientation\n\tviewer->setCameraPosition(-3.68332, 2.94092, 5.71266, 0.289847, 0.921947, -0.256907, 0);\n\tviewer->setSize(640, 512);  // Visualiser window size\n\n\t\t\t\t\t\t\t\t  // Register keyboard callback :\n\tviewer->registerKeyboardCallback(&keyboardEventOccurred, (void*)NULL);\n\n\t// Display the visualiser\n\twhile (!viewer->wasStopped())\n\t{\n\t\tviewer->spinOnce();\n\n\t\t// The user pressed \"space\" :\n\t\tif (next_iteration)\n\t\t{\n\t\t\t// The Iterative Closest Point algorithm\n\t\t\ttime.tic();\n\t\t\ticp.align(*cloud_icp);\n\t\t\tstd::cout << \"Applied 1 ICP iteration in \" << time.toc() << \" ms\" << std::endl;\n\n\t\t\tstd::stringstream info_ss;\n\t\t\tinfo_ss << \"Applied 1 ICP iteration in \" << time.toc() << \" ms\";\n\t\t\temit infoRec(QString::fromStdString(info_ss.str()));\n\t\t\temit progressBarUpdate(50);\n\n\t\t\tif (icp.hasConverged())\n\t\t\t{\n\t\t\t\tprintf(\"\\033[11A\");  // Go up 11 lines in terminal output.\n\t\t\t\tprintf(\"\\nICP has converged, score is %+.0e\\n\", icp.getFitnessScore());\n\t\t\t\tstd::cout << \"\\nICP transformation \" << ++iterations << \" : cloud_icp -> cloud_in\" << std::endl;\n\t\t\t\ttransformation_matrix *= icp.getFinalTransformation().cast<double>();  // WARNING /!\\ This is not accurate! For \"educational\" purpose only!\n\t\t\t\tprint4x4Matrix(transformation_matrix);  // Print the transformation between original pose and current pose\n\n\t\t\t\ttrans.str(\"\");\n\t\t\t\ttrans << transformation_matrix.format(OctaveFmt);\n\t\t\t\temit infoRec(QString::fromStdString(trans.str()));\n\n\t\t\t\tinfo_ss.str(\"\");\n\t\t\t\tinfo_ss << \"ICP has converged, score is \" << icp.getFitnessScore();\n\t\t\t\temit infoRec(QString::fromStdString(info_ss.str()));\n\t\t\t\temit progressBarUpdate(100);\n\n\t\t\t\tss.str(\"\");\n\t\t\t\tss << iterations;\n\t\t\t\tstd::string iterations_cnt = \"ICP iterations = \" + ss.str();\n\t\t\t\tviewer->updateText(iterations_cnt, 10, 60, 16, txt_gray_lvl, txt_gray_lvl, txt_gray_lvl, \"iterations_cnt\");\n\t\t\t\tviewer->updatePointCloud(cloud_icp, cloud_icp_color_h, \"cloud_icp_v2\");\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tPCL_ERROR(\"\\nICP has not converged.\\n\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tnext_iteration = false;\n\n\t\t//emit progressBarUpdate(100);\n\t}\n\tqDebug(\"123\");\n}\n\nvoid\nICPReg::OnStarted()\n{\n\tthis->proceed(filename_model, filename_data, iterations);\n\temit finished();\n}\n\n//void\n//ICPReg::OnFinished()\n//{\n//\t\n//}\n", "meta": {"hexsha": "4b5429a9c99c22a809525e90a79de3118449d417", "size": 8241, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "auto_registration/src/ICPReg.cpp", "max_stars_repo_name": "isnow4ever/pcl", "max_stars_repo_head_hexsha": "4a0f386f652835fca53fa84ad3e8e4ebf8181bb3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-08-18T03:03:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-31T09:40:27.000Z", "max_issues_repo_path": "auto_registration/src/ICPReg.cpp", "max_issues_repo_name": "isnow4ever/pcl", "max_issues_repo_head_hexsha": "4a0f386f652835fca53fa84ad3e8e4ebf8181bb3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "auto_registration/src/ICPReg.cpp", "max_forks_repo_name": "isnow4ever/pcl", "max_forks_repo_head_hexsha": "4a0f386f652835fca53fa84ad3e8e4ebf8181bb3", "max_forks_repo_licenses": ["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.7721518987, "max_line_length": 159, "alphanum_fraction": 0.7075597622, "num_tokens": 2383, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757645879592642, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.46125916275049045}}
{"text": "// Copyright 2015 Conrad Sanderson (http://conradsanderson.id.au)\n// Copyright 2015 National ICT Australia (NICTA)\n// \n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n// http://www.apache.org/licenses/LICENSE-2.0\n// \n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS 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 <armadillo>\n#include \"catch.hpp\"\n\nusing namespace arma;\n\n\nTEST_CASE(\"fn_find_unique_1\")\n  {\n  mat A = \n    {\n    {  1,  3,  5,  6,  7 },\n    {  2,  4,  5,  7,  8 },\n    {  3,  5,  5,  6,  9 },\n    };\n  \n  uvec indices = find_unique(A);\n  \n  uvec indices2 = { 0, 1, 2, 4, 5, 9, 10, 13, 14 };\n  \n  REQUIRE( indices.n_elem == indices2.n_elem );\n  \n  bool same = true;\n  \n  for(uword i=0; i < indices.n_elem; ++i)\n    {\n    if(indices(i) != indices2(i))  { same = false; break; }\n    }\n  \n  REQUIRE( same == true );\n  \n  vec unique_elem = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };\n  \n  REQUIRE( accu(abs( A.elem(indices) - unique_elem )) == Approx(0.0) );\n  \n  // REQUIRE_THROWS(  );\n  }\n\n\n\nTEST_CASE(\"fn_find_unique_2\")\n  {\n  cx_mat A = \n    {\n    { cx_double(1,-1), cx_double(3, 2), cx_double(5, 2), cx_double(6, 1), cx_double(7,-1) },\n    { cx_double(2, 1), cx_double(4, 4), cx_double(5, 2), cx_double(7,-1), cx_double(8, 1) },\n    { cx_double(3, 2), cx_double(5, 1), cx_double(5, 3), cx_double(6, 1), cx_double(9,-9) }\n    };\n  \n  uvec indices = find_unique(A);\n  \n  uvec indices2 = { 0, 1, 2, 4, 5, 6, 8, 9, 10, 13, 14 };\n  \n  REQUIRE( indices.n_elem == indices2.n_elem );\n  \n  bool same = true;\n  \n  for(uword i=0; i < indices.n_elem; ++i)\n    {\n    if(indices(i) != indices2(i))  { same = false; break; }\n    }\n  \n  REQUIRE( same == true );\n  \n  cx_vec unique_elem =\n    {\n    cx_double(1,-1), \n    cx_double(2, 1), \n    cx_double(3, 2), \n    cx_double(4, 4),\n    cx_double(5, 1),\n    cx_double(5, 2),\n    cx_double(5, 3),\n    cx_double(6, 1),\n    cx_double(7,-1),\n    cx_double(8, 1),\n    cx_double(9,-9)\n    };\n  \n  REQUIRE( accu(abs( A.elem(indices) - unique_elem )) == Approx(0.0) );\n  \n  // REQUIRE_THROWS(  );\n  }\n", "meta": {"hexsha": "f528eef59bdf0c4f1d95624c6e59d37244bc0d87", "size": 2467, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "external/armadillo-10.1.2/tests2/fn_find_unique.cpp", "max_stars_repo_name": "hb407/libnome", "max_stars_repo_head_hexsha": "cf11c6e34e6d147e28bfc6f54dd3ca81d2443438", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 55.0, "max_stars_repo_stars_event_min_datetime": "2020-10-07T20:22:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-28T10:58:36.000Z", "max_issues_repo_path": "external/armadillo-10.1.2/tests2/fn_find_unique.cpp", "max_issues_repo_name": "hb407/libnome", "max_issues_repo_head_hexsha": "cf11c6e34e6d147e28bfc6f54dd3ca81d2443438", "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": "external/armadillo-10.1.2/tests2/fn_find_unique.cpp", "max_forks_repo_name": "hb407/libnome", "max_forks_repo_head_hexsha": "cf11c6e34e6d147e28bfc6f54dd3ca81d2443438", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2019-12-16T16:06:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-15T15:28:31.000Z", "avg_line_length": 24.9191919192, "max_line_length": 92, "alphanum_fraction": 0.5707336846, "num_tokens": 851, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723317123102955, "lm_q2_score": 0.685949467848392, "lm_q1q2_score": 0.46118558027684536}}
{"text": "// Erwann Rogard, wrote in July 2009:\n//\n// This iterator is by nbecker and was found in the boost's vault. \n// Changes that I made are shown by ER_2007_07\n//\n// arch-tag: d007cbba-7c3d-48e0-9567-af7299fe5708\n#ifndef cycle_iterator2_ext_H\n#define cycle_iterator2_ext_H\n\n#include <boost/iterator/iterator_adaptor.hpp>\n#include <iterator>\n\n// See http://www.nabble.com/cycle-iterators-td25215321.html\n\nnamespace boost {\n\n  //! This is a cycle iterator that does NOT keep track of wraparound.\n  template<typename BaseIterator, typename offset_t>\n  class cycle_iterator2_ext : public boost::iterator_adaptor<cycle_iterator2_ext<BaseIterator, offset_t>,\n\t\t\t\t\t\t\t BaseIterator\n\t\t\t\t\t\t       >\n  {\n  public:\n    typedef typename boost::iterator_adaptor<cycle_iterator2_ext<BaseIterator, offset_t>,\n\t\t\t\t\t     BaseIterator\n\t\t\t\t\t    > super_t;\n\n    typedef typename super_t::difference_type difference_type;\n    typedef typename super_t::reference reference;\n\n    explicit cycle_iterator2_ext()\n    :size(0),position(0) // ER_2009_07\n      {}\n\n    explicit cycle_iterator2_ext (BaseIterator const& _b, BaseIterator const& _e, offset_t offset=0) :\n      // base(_b),  // ER_2009_07\n      super_t(_b),\n      size (std::distance (_b, _e)) {\n      SetPos (offset);\n    }\n\n    template <typename OtherBase, typename OtherOffset>\n    cycle_iterator2_ext (cycle_iterator2_ext<OtherBase,OtherOffset> const& other,\n\t\t     typename enable_if_convertible<OtherBase, BaseIterator>::type* = 0) :\n      // base (other.base), //ER_2009_07\n      super_t(other),\n      size (other.size),\n      position (other.position)\n    {}\n\n  private:\n    friend class boost::iterator_core_access;\n  \n\n    void increment () {\n      ++position;\n      if (position >= size) {\n\tposition -= size;\n      }\n    }\n\n    void decrement () {\n      --position;\n      if (position < 0) {\n\tposition += size;\n      }\n    }\n\n    void SetPos (offset_t newpos) {\n      position = newpos % size;\n      if (position < 0)\n\tposition += size;\n    }\n\n    void advance (difference_type n) {\n      offset_t newpos = position + n;\n      SetPos (newpos);\n    }\n\n    template<typename OtherBase, typename OtherOffset>\n    difference_type\n    distance_to (cycle_iterator2_ext<OtherBase, OtherOffset> const& y) const {\n      if (size == 0)\n\treturn 0;\n\n      else {\n\toffset_t pos1 = realposition();\n\toffset_t pos2 = y.realposition();\n\t//\treturn -(pos1 - pos2);\n\toffset_t diff = pos1 - pos2;\n\tif (diff < 0)\n\t  diff += size;\n\treturn -diff;\n      }\n    }\n\n    template<typename OtherBase, typename OtherOffset>\n    bool equal (cycle_iterator2_ext<OtherBase, OtherOffset> const& y) const {\n      return distance_to (y) == 0;\n    }\n\n    reference dereference() const { \n        //return *(base + position); //ER_2009_07\n        return  *(this->base_reference() + position);\n    }\n\n    offset_t PositiveMod (offset_t x) const {\n      offset_t y = x % size;\n      if (y < 0)\n\ty += size;\n      return y;\n    }\n\n  public:\n\n\n    reference operator[] (difference_type n) const { \n//        return *(base + PositiveMod (position + n)); //ER_2009_07\n        return *(this->base_reference() + PositiveMod (position + n)); \n    }\n\n    offset_t offset() const { return position; }\n\n    offset_t realposition () const {\n      return position;\n    }\n\n\n    //  private:\n\n    //BaseIterator base; //ER_2009_07\n    offset_t size;\n    offset_t position;\n  };\n\n  template<typename offset_t, typename BaseIterator>\n  cycle_iterator2_ext<BaseIterator, offset_t> make_cycle_iterator2_ext(BaseIterator b, BaseIterator e, offset_t offset=0) {\n    return cycle_iterator2_ext<BaseIterator, offset_t> (b, e, offset);\n  }\n\n  template<typename BaseIterator>\n  cycle_iterator2_ext<BaseIterator, int> make_cycle_iterator2_ext(BaseIterator b, BaseIterator e, int offset=0) {\n    return cycle_iterator2_ext<BaseIterator, int> (b, e, offset);\n  }\n\n} //namespace boost\n\n#endif\n", "meta": {"hexsha": "c2b2686cee0ea5cade51aa3e33848392050a8e2c", "size": 3865, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "iterator/boost/iterator/cycle_iterator2_ext.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": "iterator/boost/iterator/cycle_iterator2_ext.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": "iterator/boost/iterator/cycle_iterator2_ext.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": 25.9395973154, "max_line_length": 123, "alphanum_fraction": 0.6628719276, "num_tokens": 1010, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723317123102956, "lm_q2_score": 0.6859494678483918, "lm_q1q2_score": 0.46118558027684536}}
{"text": "//\n//  Copyright Toon Knapen, Karl Meerbergen\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\n#include \"../../blas/test/random.hpp\"\n\n#include <boost/numeric/bindings/lapack/computational/sytrd.hpp>\n#include <boost/numeric/bindings/ublas/matrix.hpp>\n#include <boost/numeric/bindings/ublas/symmetric.hpp>\n#include <boost/numeric/bindings/ublas/vector.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <algorithm>\n#include <limits>\n#include <iostream>\n\n\nnamespace ublas = boost::numeric::ublas;\nnamespace lapack = boost::numeric::bindings::lapack;\nnamespace bindings = boost::numeric::bindings;\n\n\ntemplate <typename T, typename UPLO>\nint do_value_type()\n{\n  const int n = 10 ;\n\n  typedef typename bindings::remove_imaginary<T>::type real_type ;\n  typedef std::complex< real_type >                                            complex_type ;\n\n  typedef ublas::matrix<T, ublas::column_major> matrix_type ;\n  typedef ublas::symmetric_adaptor<matrix_type, UPLO> symmetric_type ;\n  typedef ublas::vector<T>                      vector_type ;\n\n  // Set matrix\n  matrix_type a(n, n);\n  vector_type d(n), e(n - 1), tau(n - 1) ;\n\n  for(int i=0; i<n; ++i)\n  {\n    for(int j=0; j<n; ++j)\n    {\n      a(j,i) = 0.0 ;\n    }\n  }\n\n  a(0,0) = 2.0 ;\n  for(int i=1; i<n; ++i)\n  {\n    a(i,i) = 2.0 ;\n    a(i-1,i) = -1.0 ;\n  }\n\n  // Compute eigendecomposition.\n  symmetric_type s_a(a);\n  lapack::sytrd(s_a, d, e, tau) ;\n\n  for(int i=0; i<d.size(); ++i)\n  {\n    if(std::abs(d(i) - 2.0) > 10 * std::numeric_limits<T>::epsilon()) return 1 ;\n  }\n  for(int i=0; i<e.size(); ++i)\n  {\n    if(std::abs(e(i) + 1.0) > 10 * std::numeric_limits<T>::epsilon()) return 1 ;\n  }\n\n  return 0 ;\n} // do_value_type()\n\n\n\nint main()\n{\n  // Run tests for different value_types\n  if(do_value_type<float, ublas::upper>()) return 255;\n  if(do_value_type<double, ublas::upper>()) return 255;\n\n  std::cout << \"Regression test succeeded\\n\" ;\n  return 0;\n}\n\n", "meta": {"hexsha": "93aafc1cd7b683fdbf5651c1a71fadc27262f8d5", "size": 2021, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "externals/numeric_bindings/libs/numeric/bindings/lapack/test/ublas_sytrd.cpp", "max_stars_repo_name": "fperignon/sandbox", "max_stars_repo_head_hexsha": "649f09d6db7bbd84c2418de74eb9453c0131f070", "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/lapack/test/ublas_sytrd.cpp", "max_issues_repo_name": "fperignon/sandbox", "max_issues_repo_head_hexsha": "649f09d6db7bbd84c2418de74eb9453c0131f070", "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/lapack/test/ublas_sytrd.cpp", "max_forks_repo_name": "fperignon/sandbox", "max_forks_repo_head_hexsha": "649f09d6db7bbd84c2418de74eb9453c0131f070", "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": 23.5, "max_line_length": 93, "alphanum_fraction": 0.6313706086, "num_tokens": 614, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081925, "lm_q2_score": 0.6723317123102956, "lm_q1q2_score": 0.46118557164397217}}
{"text": "#ifndef DIJKSTRA_HPP\n#define DIJKSTRA_HPP\n\n#include <boost/range.hpp>\n\n#include <list>\n#include <optional>\n\ntemplate <typename Graph>\nusing Vertex = typename Graph::vertex_descriptor;\n\ntemplate <typename Graph>\nusing Edge = typename Graph::edge_descriptor;\n\n/**\n * Find the shortest path in graph g to t.\n */\ntemplate <typename Graph, typename Solution, typename Queue,\n          typename Label, typename Functor>\nvoid\ndijkstra(const Graph &g, Solution &S, Queue &Q, const Label &l,\n         const Functor &f, Vertex<Graph> t)\n{\n  // Boot the search.\n  Q.push(l);\n\n  while(!Q.empty())\n    {\n      const Label &l = move_label(S, Q);\n      Vertex<Graph> v = get_target(l);\n\n      // Stop searching when we reach the destination node.\n      if (v == t)\n        break;\n\n      // Itereate over the out edges of vertex v.\n      for(const auto &e: boost::make_iterator_range(out_edges(v, g)))\n        relax(g, S, Q, e, l, f);\n    }\n}\n\n/**\n * Try to relax edge e, given label l.\n */\ntemplate <typename Graph, typename Solution, typename Queue,\n          typename Label, typename Functor>\nvoid\nrelax(const Graph &g, Solution &S, Queue &Q, const Edge<Graph> &e,\n      const Label &l, const Functor &f)\n{\n  try\n    {\n      // Candidate labels.\n      auto cls = f(e, l);\n\n      for (auto &cl: cls)\n\tif (!has_better_or_equal(S, cl) && !has_better_or_equal(Q, cl))\n\t  {\n\t    purge_worse(Q, cl);\n\t    // We push the new label after purging, so that purging\n\t    // has less work, i.e., a smaller Q.  Furthermore, in\n\t    // purge_worse we are using the <= operator, which would\n\t    // remove the label we push below.\n\t    Q.push(std::move(cl));\n\t  }\n    } catch (bool no_label)\n    {\n      assert(no_label);\n    }\n}\n\n/**\n * Build the path by tracing labels.\n */\ntemplate <typename Solution, typename Vertex, typename Label,\n          typename Tracer>\nstd::optional<typename Tracer::path_type>\ntrace(const Solution &S, Vertex dst, const Label &sl, Tracer &t)\n{\n  // Find the solution for the dst node, the destination iterator.\n  // This mundane work should be done here, not in the user functor.\n  // We want to reuse the iterator i, and so the user functor should\n  // accept this iterator.\n  auto i = S.find(dst);\n\n  // Check whether there is a solution for node dst in S.\n  if (i != S.end())\n    {\n      // This is the path we're building.\n      typename Tracer::path_type result;\n\n      // Get the initial label, i.e. the label for the destination.\n      for(auto li = t.init(result, i); *li != sl; li = t.advance(S, li))\n        t.push(result, li);\n\n      // Move the result to the optional object we return.\n      return std::move(result);\n    }\n\n  // We return an empty optional, becase no path was found.\n  return std::optional<typename Tracer::path_type>();\n}\n\n#endif // DIJKSTRA_HPP\n", "meta": {"hexsha": "0275116c4c242499fee690a14dcc9e4bfab3a003", "size": 2779, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dijkstra.hpp", "max_stars_repo_name": "iszczesniak/gde", "max_stars_repo_head_hexsha": "0b336c8fff91d169f9eb533687745b44312a1d55", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-04-27T12:17:33.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-27T12:17:33.000Z", "max_issues_repo_path": "dijkstra.hpp", "max_issues_repo_name": "iszczesniak/gde", "max_issues_repo_head_hexsha": "0b336c8fff91d169f9eb533687745b44312a1d55", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-27T15:03:14.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-03T16:55:37.000Z", "max_forks_repo_path": "dijkstra.hpp", "max_forks_repo_name": "iszczesniak/gde", "max_forks_repo_head_hexsha": "0b336c8fff91d169f9eb533687745b44312a1d55", "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.4666666667, "max_line_length": 72, "alphanum_fraction": 0.640518172, "num_tokens": 712, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723316991792861, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.46118556695319995}}
{"text": "/*\n * GraphBLAS Template Library (GBTL), Version 3.0\n *\n * Copyright 2020 Carnegie Mellon University, Battelle Memorial Institute, and\n * Authors.\n *\n * THIS MATERIAL WAS PREPARED AS AN ACCOUNT OF WORK SPONSORED BY AN AGENCY OF\n * THE UNITED STATES GOVERNMENT.  NEITHER THE UNITED STATES GOVERNMENT NOR THE\n * UNITED STATES DEPARTMENT OF ENERGY, NOR THE UNITED STATES DEPARTMENT OF\n * DEFENSE, NOR CARNEGIE MELLON UNIVERSITY, NOR BATTELLE, NOR ANY OF THEIR\n * EMPLOYEES, NOR ANY JURISDICTION OR ORGANIZATION THAT HAS COOPERATED IN THE\n * DEVELOPMENT OF THESE MATERIALS, MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR\n * ASSUMES ANY LEGAL LIABILITY OR RESPONSIBILITY FOR THE ACCURACY, COMPLETENESS,\n * OR USEFULNESS OR ANY INFORMATION, APPARATUS, PRODUCT, SOFTWARE, OR PROCESS\n * DISCLOSED, OR REPRESENTS THAT ITS USE WOULD NOT INFRINGE PRIVATELY OWNED\n * RIGHTS.\n *\n * Released under a BSD-style license, please see LICENSE file or contact\n * permission@sei.cmu.edu for full terms.\n *\n * [DISTRIBUTION STATEMENT A] This material has been approved for public release\n * and unlimited distribution.  Please see Copyright notice for non-US\n * Government use and distribution.\n *\n * This Software includes and/or makes use of the following Third-Party Software\n * subject to its own license:\n *\n * 1. Boost Unit Test Framework\n * (https://www.boost.org/doc/libs/1_45_0/libs/test/doc/html/utf.html)\n * Copyright 2001 Boost software license, Gennadiy Rozental.\n *\n * DM20-0442\n */\n\n//#define GRAPHBLAS_LOGGING_LEVEL 2\n\n#include <graphblas/graphblas.hpp>\n\n#define BOOST_TEST_MAIN\n#define BOOST_TEST_MODULE mxm_test_suite\n\n#include <boost/test/included/unit_test.hpp>\n\nusing namespace grb;\n\nBOOST_AUTO_TEST_SUITE(BOOST_TEST_MODULE)\n\n//****************************************************************************\n\nnamespace\n{\n    static std::vector<std::vector<double> > mA_dense_3x3 =\n    {{12, 7, 3},\n     {4,  5, 6},\n     {7,  8, 9}};\n\n    static std::vector<std::vector<double> > mAT_dense_3x3 =\n    {{12, 4, 7},\n     {7,  5, 8},\n     {3,  6, 9}};\n\n    static std::vector<std::vector<double> > mB_dense_3x4 =\n    {{5, 8, 1, 2},\n     {6, 7, 3, 0.},\n     {4, 5, 9, 1}};\n\n    static std::vector<std::vector<double> > mBT_dense_3x4 =\n    {{5, 6, 4},\n     {8, 7, 5},\n     {1, 3, 9},\n     {2, 0, 1}};\n\n    static std::vector<std::vector<double> > mAnswer_dense =\n    {{114, 160, 60,  27},\n     {74,  97,  73,  14},\n     {119, 157, 112, 23}};\n\n    static std::vector<std::vector<double> > mAnswer_plus1_dense =\n    {{115, 161, 61,  28},\n     {75,  98,  74,  15},\n     {120, 158, 113, 24}};\n\n    static std::vector<std::vector<double> > mA_sparse_3x3 =\n    {{12.3, 7.5,  0},\n     {0,    -5.2, 0},\n     {7.0,  0,    9.0}};\n\n    static std::vector<std::vector<double> > mA_sparse_1337zero_3x3 =\n    {{12.3, 7.5,  1337},\n     {1337, -5.2, 1337},\n     {7.0,  1337, 9.0}};\n\n    static std::vector<std::vector<double> > mB_sparse_3x4 =\n    {{5.0, 8.5, 0,   -2.1},\n     {0.0, -7,  3.8, 0.0},\n     {4.0, 0,   0,   1.3}};\n\n    // mA_sparse_3x3 * mA_sparse_3x3\n    static std::vector<std::vector<double> > mAmA_answer_sparse =\n    {{12.3*12.3,      12.3*7.5-7.5*5.2,  0.0  },\n     {0.0,             5.2*5.2,          0.0  },\n     {12.3*7. + 7.*9., 7.5*7.,           9.*9.}};\n\n    // mA_sparse_3x3 * mB_sparse_3x4\n    static std::vector<std::vector<double> > mAnswer_sparse =\n    {{61.5, 52.05, 28.5,   -25.83},\n     {0.0,  36.4,  -19.76, 0.0},\n     {71.0, 59.5,  0.0,    -3.0}};\n\n    //static Matrix<double, DirectedMatrixTag> mAns(mAns_dense);\n    grb::IndexArrayType i_all3x4 = {0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2};\n    grb::IndexArrayType j_all3x4 = {0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3};\n\n    static std::vector<std::vector<double> > mOnes_4x4 =\n    {{1, 1, 1, 1},\n     {1, 1, 1, 1},\n     {1, 1, 1, 1},\n     {1, 1, 1, 1}};\n\n    static std::vector<std::vector<double> > mOnes_3x4 =\n    {{1, 1, 1, 1},\n     {1, 1, 1, 1},\n     {1, 1, 1, 1}};\n\n    static std::vector<std::vector<double> > mOnes_3x3 =\n    {{1, 1, 1},\n     {1, 1, 1},\n     {1, 1, 1}};\n\n    static std::vector<std::vector<double> > mIdentity_3x3 =\n    {{1, 0, 0},\n     {0, 1, 0},\n     {0, 0, 1}};\n\n    static std::vector<std::vector<double> > mLowerMask_3x4 =\n    {{1, 0,    0,   0},\n     {1, 0.5,  0,   0},\n     {1, -1.0, 1.5, 0}};\n\n    static std::vector<std::vector<bool> > mLowerBoolMask_3x4 =\n    {{true, false, false, false},\n     {true, true,  false, false},\n     {true, true,  true,  false}};\n\n    static std::vector<std::vector<bool> > mLowerBoolMask_3x3 =\n    {{true, false, false},\n     {true, true,  false},\n     {true, true,  true}};\n\n    static std::vector<std::vector<bool> > mScmpLowerBoolMask_3x3 =\n    {{false,  true, true},\n     {false, false, true},\n     {false, false, false}};\n\n}\n\n//****************************************************************************\n// API error tests\n//****************************************************************************\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_bad_dimensions)\n{\n    grb::Matrix<double, grb::DirectedMatrixTag> mA(mA_dense_3x3, 0.); // 3x3\n    grb::Matrix<double, grb::DirectedMatrixTag> mB(mB_dense_3x4, 0.); // 3x4\n    grb::Matrix<double, grb::DirectedMatrixTag> result3x4(3, 4);\n    grb::Matrix<double, grb::DirectedMatrixTag> result3x3(3, 3);\n    grb::Matrix<double, grb::DirectedMatrixTag> ones3x4(mOnes_3x4, 0.);\n\n    static std::vector<std::vector<double> > mMask_3x3 = {{1, 0, 0},\n                                                          {1, 1, 0},\n                                                          {1, 1, 1}};\n    grb::Matrix<double, grb::DirectedMatrixTag> mMask(mMask_3x3, 0.);\n    BOOST_CHECK_EQUAL(mMask.nvals(), 6);\n\n    // NoMask_NoAccum_AB\n\n    // ncols(A) != nrows(B)\n    BOOST_CHECK_THROW(\n        (mxm(result3x4,\n             grb::NoMask(), grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(),\n             mB, mA)),\n        DimensionException);\n\n    // dim(C) != dim(A*B)\n    BOOST_CHECK_THROW(\n        (mxm(result3x3,\n             grb::NoMask(), grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(),\n             mA, mB)),\n        DimensionException);\n\n    // NoMask_Accum_AB\n\n    // incompatible input matrix dimensions\n    BOOST_CHECK_THROW(\n        (grb::mxm(result3x4,\n                  grb::NoMask(),\n                  grb::Second<double>(),\n                  grb::ArithmeticSemiring<double>(), mB, mA)),\n        grb::DimensionException);\n\n    // incompatible output matrix dimensions\n    BOOST_CHECK_THROW(\n        (grb::mxm(result3x3,\n                  grb::NoMask(),\n                  grb::Second<double>(),\n                  grb::ArithmeticSemiring<double>(), mA, mB)),\n        grb::DimensionException);\n\n    // Mask_NoAccum\n\n    // incompatible mask matrix dimensions\n    BOOST_CHECK_THROW(\n        (grb::mxm(ones3x4,\n                  mMask,\n                  grb::NoAccumulate(),\n                  grb::ArithmeticSemiring<double>(), mA, mB,\n                  REPLACE)),\n        grb::DimensionException);\n\n    // Mask_Accum (replace and merge)\n\n    // incompatible mask matrix dimensions\n    BOOST_CHECK_THROW(\n        (grb::mxm(ones3x4,\n                  mMask,\n                  grb::Second<double>(),\n                  grb::ArithmeticSemiring<double>(), mA, mB, REPLACE)),\n        grb::DimensionException);\n\n    // incompatible mask matrix dimensions\n    BOOST_CHECK_THROW(\n        (grb::mxm(ones3x4,\n                  mMask,\n                  grb::Second<double>(),\n                  grb::ArithmeticSemiring<double>(), mA, mB)),\n        grb::DimensionException);\n\n    // CompMask_NoAccum (replace and merge)\n\n    // incompatible mask matrix dimensions\n    BOOST_CHECK_THROW(\n        (grb::mxm(ones3x4,\n                  grb::complement(mMask),\n                  grb::NoAccumulate(),\n                  grb::ArithmeticSemiring<double>(), mA, mB, REPLACE)),\n        grb::DimensionException);\n\n    // incompatible mask matrix dimensions\n    BOOST_CHECK_THROW(\n        (grb::mxm(result3x4,\n                  grb::complement(mMask),\n                  grb::NoAccumulate(),\n                  grb::ArithmeticSemiring<double>(), mA, mB)),\n        grb::DimensionException);\n\n    // CompMask_Accum (replace and merge)\n\n    // incompatible mask matrix dimensions\n    BOOST_CHECK_THROW(\n        (grb::mxm(ones3x4,\n                  grb::complement(mMask),\n                  grb::Second<double>(),\n                  grb::ArithmeticSemiring<double>(), mA, mB, REPLACE)),\n        grb::DimensionException);\n\n    // incompatible mask matrix dimensions\n    BOOST_CHECK_THROW(\n        (grb::mxm(result3x4,\n                  grb::complement(mMask),\n                  grb::Second<double>(),\n                  grb::ArithmeticSemiring<double>(), mA, mB)),\n        grb::DimensionException);\n}\n\n//****************************************************************************\n// NoMask_NoAccum\n//****************************************************************************\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_NoAccum_AB)\n{\n    grb::Matrix<double> mC(3, 4);\n    grb::Matrix<double> mA(mA_sparse_3x3, 0.);\n    grb::Matrix<double> mB(mB_sparse_3x4, 0.);\n\n    grb::Matrix<double> answer(mAnswer_sparse, 0.);\n\n    grb::mxm(mC,\n             grb::NoMask(),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mA, mB);\n    for (grb::IndexType ix = 0; ix < answer.nrows(); ++ix)\n    {\n        for (grb::IndexType iy = 0; iy < answer.ncols(); ++iy)\n        {\n            BOOST_CHECK_EQUAL(mC.hasElement(ix, iy), answer.hasElement(ix, iy));\n            if (mC.hasElement(ix, iy))\n            {\n                BOOST_CHECK_CLOSE(mC.extractElement(ix,iy),\n                                  answer.extractElement(ix,iy), 0.0001);\n            }\n        }\n    }\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_NoAccum_AB_empty)\n{\n    grb::Matrix<double> mZero(3, 3);\n    grb::Matrix<double> mOnes(mOnes_3x3, 0.);\n    grb::Matrix<double> mC(mOnes_3x3, 0.);\n    grb::Matrix<double> mD(mOnes_3x3, 0.);\n\n    grb::mxm(mC,\n             NoMask(), NoAccumulate(),\n             ArithmeticSemiring<double>(), mZero, mOnes);\n    BOOST_CHECK_EQUAL(mC, mZero);\n\n    grb::mxm(mD,\n             NoMask(), NoAccumulate(),\n             ArithmeticSemiring<double>(), mOnes, mZero);\n    BOOST_CHECK_EQUAL(mD, mZero);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_NoAccum_AB_dense)\n{\n    IndexArrayType i_mA    = {0, 0, 0, 1, 1, 1, 2, 2, 2};\n    IndexArrayType j_mA    = {0, 1, 2, 0, 1, 2, 0, 1, 2};\n    std::vector<double> v_mA = {12, 7, 3, 4, 5, 6, 7, 8, 9};\n    Matrix<double, DirectedMatrixTag> mA(3, 3);\n    mA.build(i_mA, j_mA, v_mA);\n\n    IndexArrayType i_mB    = {0, 0, 0, 0, 1, 1, 1, 2, 2, 2, 2};\n    IndexArrayType j_mB    = {0, 1, 2, 3, 0, 1, 2, 0, 1, 2, 3};\n    std::vector<double> v_mB = {5, 8, 1, 2, 6, 7, 3, 4, 5, 9, 1};\n    Matrix<double, DirectedMatrixTag> mB(3, 4);\n    mB.build(i_mB, j_mB, v_mB);\n\n    Matrix<double, DirectedMatrixTag> result(3, 4);\n\n    IndexArrayType i_answer = {0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2};\n    IndexArrayType j_answer = {0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3};\n    std::vector<double> v_answer = {114, 160, 60, 27, 74, 97,\n                                    73, 14, 119, 157, 112, 23};\n    Matrix<double, DirectedMatrixTag> answer(3, 4);\n    answer.build(i_answer, j_answer, v_answer);\n\n    mxm(result,\n        grb::NoMask(), grb::NoAccumulate(),\n        grb::ArithmeticSemiring<double>(),\n        mA, mB);\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_NoAccum_AB_emptyRowA_emptyColB)\n{\n    std::vector<std::vector<double>> mA_vals = {{8, 1, 6},\n                                                {0, 0, 0},\n                                                {4, 9, 2}};\n\n    std::vector<std::vector<double>> mB_vals = {{0, 0, 0, 1},\n                                                {1, 0, 1, 1},\n                                                {0, 0, 1, 1}};\n\n    std::vector<std::vector<double>> answer_vals = {{1, 0, 7, 15},\n                                                    {0, 0, 0, 0},\n                                                    {9, 0, 11, 15}};\n\n    grb::Matrix<double> mA(mA_vals, 0.);\n    grb::Matrix<double> mB(mB_vals, 0.);\n    grb::Matrix<double> result(3, 4);\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    grb::mxm(result,\n             grb::NoMask(),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mA, mB);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_NoAccum_AB_emptyColA_emptyRowB)\n{\n    std::vector<std::vector<double>> mA_vals = {{8, 0, 6},\n                                                {1, 0, 9},\n                                                {4, 0, 2}};\n\n    std::vector<std::vector<double>> mB_vals = {{0, 1, 0, 1},\n                                                {1, 0, 1, 1},\n                                                {0, 0, 0, 0}};\n\n    std::vector<std::vector<double>> answer_vals = {{0, 8, 0, 8},\n                                                    {0, 1, 0, 1},\n                                                    {0, 4, 0, 4}};\n\n    grb::Matrix<double> mA(mA_vals, 0.);\n    grb::Matrix<double> mB(mB_vals, 0.);\n    grb::Matrix<double> result(3, 4);\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    grb::mxm(result,\n             grb::NoMask(),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mA, mB);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_NoAccum_AB_ABdup)\n{\n    // Build some matrices.\n    IndexArrayType      i = {0, 0, 1, 1, 1, 2, 2, 2, 3, 3};\n    IndexArrayType      j = {0, 1, 0, 1, 2, 1, 2, 3, 2, 3};\n    std::vector<double> v = {1, 1, 1, 2, 2, 2, 3, 3, 3, 4};\n    Matrix<double, DirectedMatrixTag> mat(4, 4);\n    mat.build(i, j, v);\n\n    Matrix<double, DirectedMatrixTag> m3(4, 4);\n\n    IndexArrayType      i_answer = {0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3};\n    IndexArrayType      j_answer = {0, 1, 2, 0, 1, 2, 3, 0, 1, 2, 3, 1, 2, 3};\n    std::vector<double> v_answer = {2, 3, 2, 3, 9,10, 6, 2,10,22,21, 6,21,25};\n    Matrix<double, DirectedMatrixTag> answer(4, 4);\n    answer.build(i_answer, j_answer, v_answer);\n\n    mxm(m3,\n        grb::NoMask(), grb::NoAccumulate(),\n        grb::ArithmeticSemiring<double>(),\n        mat, mat);\n\n    BOOST_CHECK_EQUAL(m3, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_NoAccum_AB_ACdup)\n{\n    grb::Matrix<double> mC(mA_sparse_3x3, 0.);\n    grb::Matrix<double> mB(mA_sparse_3x3, 0.);\n\n    grb::Matrix<double> answer(mAmA_answer_sparse, 0.);\n\n    grb::mxm(mC,\n             grb::NoMask(),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mC, mB);\n\n    BOOST_CHECK_EQUAL(mC, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_NoAccum_AB_BCdup)\n{\n    grb::Matrix<double> mC(mA_sparse_3x3, 0.);\n    grb::Matrix<double> mA(mA_sparse_3x3, 0.);\n\n    grb::Matrix<double> answer(mAmA_answer_sparse, 0.);\n\n    grb::mxm(mC,\n             grb::NoMask(),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mA, mC);\n\n    BOOST_CHECK_EQUAL(mC, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_NoAccum_ATB)\n{\n    IndexArrayType i_mA    = {0, 0, 0, 1, 1, 1, 2, 2, 2};\n    IndexArrayType j_mA    = {0, 1, 2, 0, 1, 2, 0, 1, 2};\n    std::vector<double> v_mA = {12, 7, 3, 4, 5, 6, 7, 8, 9};\n    Matrix<double, DirectedMatrixTag> mA(3, 3);\n    mA.build(i_mA, j_mA, v_mA);\n\n    IndexArrayType i_mB    = {0, 0, 0, 0, 1, 1, 1, 2, 2, 2, 2};\n    IndexArrayType j_mB    = {0, 1, 2, 3, 0, 1, 2, 0, 1, 2, 3};\n    std::vector<double> v_mB = {5, 8, 1, 2, 6, 7, 3, 4, 5, 9, 1};\n    Matrix<double, DirectedMatrixTag> mB(3, 4);\n    mB.build(i_mB, j_mB, v_mB);\n\n    Matrix<double, DirectedMatrixTag> result(3, 4);\n\n    IndexArrayType i_answer = {0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2};\n    IndexArrayType j_answer = {0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3};\n    std::vector<double> v_answer = {112, 159, 87, 31, 97, 131,\n                                    94, 22, 87, 111, 102, 15};\n    Matrix<double, DirectedMatrixTag> answer(3, 4);\n    answer.build(i_answer, j_answer, v_answer);\n\n    mxm(result,\n        grb::NoMask(), grb::NoAccumulate(),\n        grb::ArithmeticSemiring<double>(),\n        transpose(mA), mB);\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_NoAccum_ATB_empty)\n{\n    grb::Matrix<double> mZero(3, 3);\n    grb::Matrix<double> mOnes(mOnes_3x3, 0.);\n    grb::Matrix<double> mC(mOnes_3x3, 0.);\n    grb::Matrix<double> mD(mOnes_3x3, 0.);\n\n    grb::mxm(mC,\n             NoMask(), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(mZero), mOnes);\n    BOOST_CHECK_EQUAL(mC, mZero);\n\n    grb::mxm(mD,\n             NoMask(), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(mOnes), mZero);\n    BOOST_CHECK_EQUAL(mD, mZero);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_NoAccum_ATB_identity_B)\n{\n    IndexArrayType i_mA    = {0, 0, 0, 1, 1, 1, 2, 2, 2};\n    IndexArrayType j_mA    = {0, 1, 2, 0, 1, 2, 0, 1, 2};\n    std::vector<double> v_mA = {12, 7, 3, 4, 5, 6, 7, 8, 9};\n    Matrix<double, DirectedMatrixTag> mA(3, 3);\n    mA.build(i_mA, j_mA, v_mA);\n\n    IndexArrayType i_mB    = {0, 0, 0, 1, 1, 1, 2, 2, 2};\n    IndexArrayType j_mB    = {0, 1, 2, 0, 1, 2, 0, 1, 2};\n    std::vector<double> v_mB = {1, 0, 0, 0, 1, 0, 0, 0, 1};\n    Matrix<double, DirectedMatrixTag> mB(3, 3);\n    mB.build(i_mB, j_mB, v_mB);\n\n    Matrix<double, DirectedMatrixTag> result(3, 3);\n\n    IndexArrayType i_answer = {0, 0, 0, 1, 1, 1, 2, 2, 2};\n    IndexArrayType j_answer = {0, 1, 2, 0, 1, 2, 0, 1, 2};\n    std::vector<double> v_answer = {12, 4, 7, 7, 5, 8, 3, 6, 9};\n    Matrix<double, DirectedMatrixTag> answer(3, 3);\n    answer.build(i_answer, j_answer, v_answer);\n\n    mxm(result,\n        grb::NoMask(), grb::NoAccumulate(),\n        grb::ArithmeticSemiring<double>(),\n        transpose(mA), mB);\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_NoAccum_ATB_emptyRowA_emptyColB)\n{\n    std::vector<std::vector<double>> mA_vals = {{8, 1, 6},\n                                                {0, 0, 0},\n                                                {4, 9, 2}};\n\n    std::vector<std::vector<double>> mB_vals = {{1, 0, 0},\n                                                {1, 0, 1},\n                                                {0, 0, 1}};\n\n    std::vector<std::vector<double>> answer_vals = {{8, 0, 4},\n                                                    {1, 0, 9},\n                                                    {6, 0, 2}};\n\n    grb::Matrix<double> mA(mA_vals, 0.);\n    grb::Matrix<double> mB(mB_vals, 0.);\n    grb::Matrix<double> result(3, 3);\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    grb::mxm(result,\n             grb::NoMask(),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(mA), mB);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_NoAccum_ATB_emptyColA_emptyRowB)\n{\n    std::vector<std::vector<double>> mA_vals = {{8, 0, 6},\n                                                {1, 0, 9},\n                                                {4, 0, 2}};\n\n    std::vector<std::vector<double>> mB_vals = {{0, 1, 0},\n                                                {1, 0, 1},\n                                                {0, 0, 0}};\n\n    std::vector<std::vector<double>> answer_vals = {{1, 8, 1},\n                                                    {0, 0, 0},\n                                                    {9, 6, 9}};\n\n    grb::Matrix<double> mA(mA_vals, 0.);\n    grb::Matrix<double> mB(mB_vals, 0.);\n    grb::Matrix<double> result(3, 3);\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    grb::mxm(result,\n             grb::NoMask(),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(mA), mB);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_NoAccum_ATB_ABdup)\n{\n    // Build some matrices.\n    static std::vector<std::vector<double> > mat3x3 = {{1, 0, 0},\n                                                       {1, 2, 0},\n                                                       {0, 2, 3}};\n    Matrix<double> mat(mat3x3, 0.);\n\n    Matrix<double> res(3,3);\n\n    static std::vector<std::vector<double> > ans3x3 =  {{2, 2, 0},\n                                                        {2, 8, 6},\n                                                        {0, 6, 9}};\n    Matrix<double> answer(ans3x3, 0.);\n\n    mxm(res,\n        grb::NoMask(), grb::NoAccumulate(),\n        grb::ArithmeticSemiring<double>(),\n        transpose(mat), mat);\n\n    BOOST_CHECK_EQUAL(res, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_NoAccum_ATB_ACdup)\n{\n    // Build some matrices.\n    static std::vector<std::vector<double> > mat3x3 = {{1, 0, 0},\n                                                       {1, 2, 0},\n                                                       {0, 2, 3}};\n    grb::Matrix<double> mC(mat3x3, 0.);\n    grb::Matrix<double> mB(mat3x3, 0.);\n\n    static std::vector<std::vector<double> > ans3x3 =  {{2, 2, 0},\n                                                        {2, 8, 6},\n                                                        {0, 6, 9}};\n    Matrix<double> answer(ans3x3, 0.);\n\n    grb::mxm(mC,\n             grb::NoMask(),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(mC), mB);\n\n    BOOST_CHECK_EQUAL(mC, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_NoAccum_ATB_BCdup)\n{\n    static std::vector<std::vector<double> > mat3x3 = {{1, 0, 0},\n                                                       {1, 2, 0},\n                                                       {0, 2, 3}};\n    grb::Matrix<double> mA(mat3x3, 0.);\n    grb::Matrix<double> mC(mat3x3, 0.);\n\n    static std::vector<std::vector<double> > ans3x3 =  {{2, 2, 0},\n                                                        {2, 8, 6},\n                                                        {0, 6, 9}};\n    Matrix<double> answer(ans3x3, 0.);\n    grb::mxm(mC,\n             grb::NoMask(),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(mA), mC);\n\n    BOOST_CHECK_EQUAL(mC, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_NoAccum_ABT)\n{\n    IndexArrayType i_mA    = {0, 0, 0, 1, 1, 1, 2, 2, 2};\n    IndexArrayType j_mA    = {0, 1, 2, 0, 1, 2, 0, 1, 2};\n    std::vector<double> v_mA = {12, 7, 3, 4, 5, 6, 7, 8, 9};\n    Matrix<double, DirectedMatrixTag> mA(3, 3);\n    mA.build(i_mA, j_mA, v_mA);\n\n    IndexArrayType i_mB    = {0, 0, 0, 1, 1, 1, 2, 2, 2};\n    IndexArrayType j_mB    = {0, 1, 2, 0, 1, 2, 0, 1, 2};\n    std::vector<double> v_mB = {5, 8, 1, 2, 6, 7, 3, 4, 5};\n    Matrix<double, DirectedMatrixTag> mB(3, 3);\n    mB.build(i_mB, j_mB, v_mB);\n\n    Matrix<double, DirectedMatrixTag> result(3, 3);\n\n    IndexArrayType i_answer = {0, 0, 0, 1, 1, 1, 2, 2, 2};\n    IndexArrayType j_answer = {0, 1, 2, 0, 1, 2, 0, 1, 2};\n    std::vector<double> v_answer = {119, 87, 79, 66, 80, 62, 108, 125, 98};\n    Matrix<double, DirectedMatrixTag> answer(3, 3);\n    answer.build(i_answer, j_answer, v_answer);\n\n    mxm(result,\n        grb::NoMask(), grb::NoAccumulate(),\n        grb::ArithmeticSemiring<double>(),\n        mA, transpose(mB));\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_NoAccum_ABT_empty)\n{\n    grb::Matrix<double> mZero(3, 3);\n    grb::Matrix<double> mOnes(mOnes_3x3, 0.);\n    grb::Matrix<double> mC(mOnes_3x3, 0.);\n    grb::Matrix<double> mD(mOnes_3x3, 0.);\n\n    grb::mxm(mC,\n             NoMask(), NoAccumulate(),\n             ArithmeticSemiring<double>(), mOnes, transpose(mZero));\n    BOOST_CHECK_EQUAL(mC, mZero);\n\n    grb::mxm(mD,\n             NoMask(), NoAccumulate(),\n             ArithmeticSemiring<double>(), mZero, transpose(mOnes));\n    BOOST_CHECK_EQUAL(mD, mZero);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_NoAccum_ABT_emptyRowA_emptyColB)\n{\n    std::vector<std::vector<double>> mA_vals = {{8, 1, 6},\n                                                {0, 0, 0},\n                                                {4, 9, 2}};\n\n    std::vector<std::vector<double>> mB_vals = {{1, 0, 0},\n                                                {1, 0, 1},\n                                                {0, 0, 1}};\n\n    std::vector<std::vector<double>> answer_vals = {{8, 14, 6},\n                                                    {0, 0,  0},\n                                                    {4, 6,  2}};\n\n    grb::Matrix<double> mA(mA_vals, 0.);\n    grb::Matrix<double> mB(mB_vals, 0.);\n    grb::Matrix<double> result(3, 3);\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    grb::mxm(result,\n             grb::NoMask(),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mA, transpose(mB));\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_NoAccum_ABT_emptyColA_emptyRowB)\n{\n    std::vector<std::vector<double>> mA_vals = {{8, 0, 6},\n                                                {1, 0, 9},\n                                                {4, 0, 2}};\n\n    std::vector<std::vector<double>> mB_vals = {{0, 1, 0},\n                                                {1, 0, 1},\n                                                {0, 0, 0}};\n\n    std::vector<std::vector<double>> answer_vals = {{0, 14, 0},\n                                                    {0, 10, 0},\n                                                    {0,  6, 0}};\n\n    grb::Matrix<double> mA(mA_vals, 0.);\n    grb::Matrix<double> mB(mB_vals, 0.);\n    grb::Matrix<double> result(3, 3);\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    grb::mxm(result,\n             grb::NoMask(),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mA, transpose(mB));\n    BOOST_CHECK_EQUAL(result, answer);\n}\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_NoAccum_ABT_ABdup)\n{\n    // Build some matrices.\n    static std::vector<std::vector<double> > mat3x3 = {{1, 0, 0},\n                                                       {1, 2, 0},\n                                                       {0, 2, 3}};\n    Matrix<double> mat(mat3x3, 0.);\n\n    Matrix<double> res(3,3);\n\n    static std::vector<std::vector<double> > ans3x3 =  {{1, 1, 0},\n                                                        {1, 5, 4},\n                                                        {0, 4,13}};\n    Matrix<double> answer(ans3x3, 0.);\n\n    mxm(res,\n        grb::NoMask(), grb::NoAccumulate(),\n        grb::ArithmeticSemiring<double>(),\n        mat, transpose(mat));\n\n    BOOST_CHECK_EQUAL(res, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_NoAccum_ABT_ACdup)\n{\n    // Build some matrices.\n    static std::vector<std::vector<double> > mat3x3 = {{1, 0, 0},\n                                                       {1, 2, 0},\n                                                       {0, 2, 3}};\n    grb::Matrix<double> mC(mat3x3, 0.);\n    grb::Matrix<double> mB(mat3x3, 0.);\n\n    static std::vector<std::vector<double> > ans3x3 =  {{1, 1, 0},\n                                                        {1, 5, 4},\n                                                        {0, 4,13}};\n    Matrix<double> answer(ans3x3, 0.);\n\n    grb::mxm(mC,\n             grb::NoMask(),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mC, transpose(mB));\n\n    BOOST_CHECK_EQUAL(mC, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_NoAccum_ABT_BCdup)\n{\n    static std::vector<std::vector<double> > mat3x3 = {{1, 0, 0},\n                                                       {1, 2, 0},\n                                                       {0, 2, 3}};\n    grb::Matrix<double> mA(mat3x3, 0.);\n    grb::Matrix<double> mC(mat3x3, 0.);\n\n    static std::vector<std::vector<double> > ans3x3 =  {{1, 1, 0},\n                                                        {1, 5, 4},\n                                                        {0, 4,13}};\n    Matrix<double> answer(ans3x3, 0.);\n    grb::mxm(mC,\n             grb::NoMask(),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mA, transpose(mC));\n\n    BOOST_CHECK_EQUAL(mC, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_NoAccum_ATBT)\n{\n    IndexArrayType i_mA    = {0, 0, 0, 1, 1, 1, 2, 2, 2};\n    IndexArrayType j_mA    = {0, 1, 2, 0, 1, 2, 0, 1, 2};\n    std::vector<double> v_mA = {12, 7, 3, 4, 5, 6, 7, 8, 9};\n    Matrix<double, DirectedMatrixTag> mA(3, 3);\n    mA.build(i_mA, j_mA, v_mA);\n\n    IndexArrayType i_mB    = {0, 0, 0, 1, 1, 1, 2, 2, 2};\n    IndexArrayType j_mB    = {0, 1, 2, 0, 1, 2, 0, 1, 2};\n    std::vector<double> v_mB = {5, 8, 1, 2, 6, 7, 3, 4, 5};\n    Matrix<double, DirectedMatrixTag> mB(3, 3);\n    mB.build(i_mB, j_mB, v_mB);\n\n    Matrix<double, DirectedMatrixTag> result(3, 3);\n\n    IndexArrayType i_answer = {0, 0, 0, 1, 1, 1, 2, 2, 2};\n    IndexArrayType j_answer = {0, 1, 2, 0, 1, 2, 0, 1, 2};\n    std::vector<double> v_answer = {99, 97, 87, 83, 100, 81, 72, 105, 78};\n    Matrix<double, DirectedMatrixTag> answer(3, 3);\n    answer.build(i_answer, j_answer, v_answer);\n\n    mxm(result,\n        grb::NoMask(), grb::NoAccumulate(),\n        grb::ArithmeticSemiring<double>(),\n        transpose(mA), transpose(mB));\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_NoAccum_ATBT_empty)\n{\n    grb::Matrix<double> mZero(3, 3);\n    grb::Matrix<double> mOnes(mOnes_3x3, 0.);\n    grb::Matrix<double> mC(mOnes_3x3, 0.);\n    grb::Matrix<double> mD(mOnes_3x3, 0.);\n\n    grb::mxm(mC,\n             NoMask(), NoAccumulate(),\n             ArithmeticSemiring<double>(),\n             transpose(mOnes), transpose(mZero));\n    BOOST_CHECK_EQUAL(mC, mZero);\n\n    grb::mxm(mD,\n             NoMask(), NoAccumulate(),\n             ArithmeticSemiring<double>(),\n             transpose(mZero), transpose(mOnes));\n    BOOST_CHECK_EQUAL(mD, mZero);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_NoAccum_ATBT_emptyRowA_emptyColB)\n{\n    std::vector<std::vector<double>> mA_vals = {{8, 1, 6},\n                                                {0, 0, 0},\n                                                {4, 9, 2}};\n\n    std::vector<std::vector<double>> mB_vals = {{1, 0, 0},\n                                                {1, 0, 1},\n                                                {0, 0, 1}};\n\n    std::vector<std::vector<double>> answer_vals = {{8, 12, 4},\n                                                    {1, 10, 9},\n                                                    {6, 8,  2}};\n\n    grb::Matrix<double> mA(mA_vals, 0.);\n    grb::Matrix<double> mB(mB_vals, 0.);\n    grb::Matrix<double> result(3, 3);\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    grb::mxm(result,\n             grb::NoMask(),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(),\n             transpose(mA), transpose(mB));\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_NoAccum_ATBT_emptyColA_emptyRowB)\n{\n    std::vector<std::vector<double>> mA_vals = {{8, 0, 6},\n                                                {1, 0, 9},\n                                                {4, 0, 2}};\n\n    std::vector<std::vector<double>> mB_vals = {{0, 1, 0},\n                                                {1, 0, 1},\n                                                {0, 0, 0}};\n\n    std::vector<std::vector<double>> answer_vals = {{1, 12, 0},\n                                                    {0,  0, 0},\n                                                    {9,  8, 0}};\n\n    grb::Matrix<double> mA(mA_vals, 0.);\n    grb::Matrix<double> mB(mB_vals, 0.);\n    grb::Matrix<double> result(3, 3);\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    grb::mxm(result,\n             grb::NoMask(),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(),\n             transpose(mA), transpose(mB));\n    BOOST_CHECK_EQUAL(result, answer);\n}\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_NoAccum_ATBT_ABdup)\n{\n    // Build some matrices.\n    static std::vector<std::vector<double> > mat3x3 = {{1, 0, 0},\n                                                       {1, 2, 0},\n                                                       {0, 2, 3}};\n    Matrix<double> mat(mat3x3, 0.);\n\n    Matrix<double> res(3,3);\n\n    static std::vector<std::vector<double> > ans3x3 =  {{1, 3, 2},\n                                                        {0, 4,10},\n                                                        {0, 0, 9}};\n    Matrix<double> answer(ans3x3, 0.);\n\n    mxm(res,\n        grb::NoMask(), grb::NoAccumulate(),\n        grb::ArithmeticSemiring<double>(),\n        transpose(mat), transpose(mat));\n\n    BOOST_CHECK_EQUAL(res, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_NoAccum_ATBT_ACdup)\n{\n    // Build some matrices.\n    static std::vector<std::vector<double> > mat3x3 = {{1, 0, 0},\n                                                       {1, 2, 0},\n                                                       {0, 2, 3}};\n    grb::Matrix<double> mC(mat3x3, 0.);\n    grb::Matrix<double> mB(mat3x3, 0.);\n\n    static std::vector<std::vector<double> > ans3x3 =  {{1, 3, 2},\n                                                        {0, 4,10},\n                                                        {0, 0, 9}};\n    Matrix<double> answer(ans3x3, 0.);\n\n    grb::mxm(mC,\n             grb::NoMask(),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(),\n             transpose(mC), transpose(mB));\n\n    BOOST_CHECK_EQUAL(mC, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_NoAccum_ATBT_BCdup)\n{\n    static std::vector<std::vector<double> > mat3x3 = {{1, 0, 0},\n                                                       {1, 2, 0},\n                                                       {0, 2, 3}};\n    grb::Matrix<double> mA(mat3x3, 0.);\n    grb::Matrix<double> mC(mat3x3, 0.);\n\n    static std::vector<std::vector<double> > ans3x3 =  {{1, 3, 2},\n                                                        {0, 4,10},\n                                                        {0, 0, 9}};\n    Matrix<double> answer(ans3x3, 0.);\n    grb::mxm(mC,\n             grb::NoMask(),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(),\n             transpose(mA), transpose(mC));\n\n    BOOST_CHECK_EQUAL(mC, answer);\n}\n\n//****************************************************************************\n// NoMask_Accum\n//****************************************************************************\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_Accum_AB)\n{\n    grb::Matrix<double> mA(mA_dense_3x3, 0.); // 3x3\n    grb::Matrix<double> mB(mB_dense_3x4, 0.); // 3x4\n    grb::Matrix<double> result(3, 4);\n    grb::Matrix<double> answer(mAnswer_dense, 0.);\n\n    grb::mxm(result,\n             grb::NoMask(),\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), mA, mB);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_Accum_AB_empty)\n{\n    grb::Matrix<double> mZero(3, 3);\n    grb::Matrix<double> mOnes(mOnes_3x3, 0.);\n    grb::Matrix<double> mC(mOnes_3x3, 0.);\n    grb::Matrix<double> mD(mOnes_3x3, 0.);\n\n    grb::mxm(mC,\n             NoMask(), Plus<double>(),\n             ArithmeticSemiring<double>(), mZero, mOnes);\n    BOOST_CHECK_EQUAL(mC, mOnes);\n\n    grb::mxm(mD,\n             NoMask(), Plus<double>(),\n             ArithmeticSemiring<double>(), mOnes, mZero);\n    BOOST_CHECK_EQUAL(mD, mOnes);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_Accum_AB_stored_zero_result)\n{\n    // Build some matrices.\n    std::vector<std::vector<int> > A = {{1, 1, 0, 0},\n                                        {1, 2, 2, 0},\n                                        {0, 2, 3, 3},\n                                        {0, 0, 3, 4}};\n    std::vector<std::vector<int> > B = {{ 1,-2, 0,  0},\n                                        {-1, 1, 0,  0},\n                                        { 0, 0, 3, -4},\n                                        { 0, 0,-3,  3}};\n    grb::Matrix<int> mA(A, 0);\n    grb::Matrix<int> mB(B, 0);\n    grb::Matrix<int> result(4, 4);\n\n    // use a different sentinel value so that stored zeros are preserved.\n    int const NIL(666);\n    std::vector<std::vector<int> > ans = {{  0,  -1, NIL, NIL},\n                                          { -1,   0,   6,  -8},\n                                          { -2,   2,   0,  -3},\n                                          {NIL, NIL,  -3,   0}};\n    grb::Matrix<int> answer(ans, NIL);\n\n    grb::mxm(result,\n             grb::NoMask(),\n             grb::Second<int>(),\n             grb::ArithmeticSemiring<int>(), mA, mB);\n    BOOST_CHECK_EQUAL(result, answer);\n    BOOST_CHECK_EQUAL(result.nvals(), 12);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_Accum_AB_ABdup_Cempty)\n{\n    // Build some matrices.\n    std::vector<std::vector<double> > m = {{1, 1, 0, 0},\n                                           {1, 2, 2, 0},\n                                           {0, 2, 3, 3},\n                                           {0, 0, 3, 4}};\n    grb::Matrix<double> mat(m, 0.);\n\n    grb::Matrix<double> result(4, 4);\n\n    std::vector<std::vector<double> > ans = {{2,  3,  2,  0},\n                                             {3,  9, 10,  6},\n                                             {2, 10, 22, 21},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             grb::NoMask(),\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), mat, mat);\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_Accum_ATB)\n{\n    grb::Matrix<double> mA(mAT_dense_3x3, 0.); // 3x3\n    grb::Matrix<double> mB(mB_dense_3x4, 0.); // 3x4\n    grb::Matrix<double> result(3, 4);\n    grb::Matrix<double> answer(mAnswer_dense, 0.);\n    grb::Matrix<double> answerp1(mAnswer_plus1_dense, 0.);\n\n    grb::mxm(result,\n             grb::NoMask(),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mA), mB);\n    BOOST_CHECK_EQUAL(result, answer);\n\n    grb::Matrix<double> res1(mOnes_3x4, 0.);\n    grb::mxm(res1,\n             grb::NoMask(),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mA), mB);\n    BOOST_CHECK_EQUAL(res1, answerp1);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_Accum_ATB_empty)\n{\n    grb::Matrix<double> mZero(3, 3);\n    grb::Matrix<double> mOnes(mOnes_3x3, 0.);\n    grb::Matrix<double> mC(mOnes_3x3, 0.);\n    grb::Matrix<double> mD(mOnes_3x3, 0.);\n\n    grb::mxm(mC,\n             NoMask(), Plus<double>(),\n             ArithmeticSemiring<double>(),\n             transpose(mZero), mOnes);\n    BOOST_CHECK_EQUAL(mC, mOnes);\n\n    grb::mxm(mD,\n             NoMask(), Plus<double>(),\n             ArithmeticSemiring<double>(),\n             transpose(mOnes), mZero);\n    BOOST_CHECK_EQUAL(mD, mOnes);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_Accum_ATB_Bidentity_Cempty)\n{\n    grb::Matrix<double> mA(mA_dense_3x3, 0.);\n    grb::Matrix<double> mB(mIdentity_3x3, 0.);\n    grb::Matrix<double> result(3, 3);\n\n    std::vector<std::vector<double> > ans = {{12, 4, 7},\n                                             { 7, 5, 8},\n                                             { 3, 6, 9}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    //auto answer = grb::transpose(mA);\n\n    grb::mxm(result,\n             grb::NoMask(),\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mA), mB);\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_Accum_ABT)\n{\n    grb::Matrix<double> mA(mA_dense_3x3, 0.);\n\n    std::vector<std::vector<double> > B = {{5, 8, 1},\n                                           {2, 6, 7},\n                                           {3, 4, 5}};\n    grb::Matrix<double> mB(B, 0.);\n\n    // empty dst\n    grb::Matrix<double> result(3, 3);\n\n    std::vector<std::vector<double> > ans = {{119,  87, 79},\n                                             { 66,  80, 62},\n                                             {108, 125, 98}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             grb::NoMask(),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), mA, transpose(mB));\n\n    BOOST_CHECK_EQUAL(result, answer);\n\n    // filled dst\n    grb::Matrix<double> res1(mOnes_3x3, 0.);\n    std::vector<std::vector<double> > ans1 = {{120,  88, 80},\n                                              { 67,  81, 63},\n                                              {109, 126, 99}};\n    grb::Matrix<double> answer1(ans1, 0.);\n    grb::mxm(res1,\n             grb::NoMask(),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), mA, transpose(mB));\n\n    BOOST_CHECK_EQUAL(res1, answer1);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_Accum_ABT_empty)\n{\n    grb::Matrix<double> mZero(3, 3);\n    grb::Matrix<double> mOnes(mOnes_3x3, 0.);\n    grb::Matrix<double> mC(mOnes_3x3, 0.);\n    grb::Matrix<double> mD(mOnes_3x3, 0.);\n\n    grb::mxm(mC,\n             NoMask(), Plus<double>(),\n             ArithmeticSemiring<double>(),\n             mOnes, transpose(mZero));\n    BOOST_CHECK_EQUAL(mC, mOnes);\n\n    grb::mxm(mD,\n             NoMask(), Plus<double>(),\n             ArithmeticSemiring<double>(),\n             mZero, transpose(mOnes));\n    BOOST_CHECK_EQUAL(mD, mOnes);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_Accum_ATBT)\n{\n    grb::Matrix<double> mA(mA_dense_3x3, 0.);\n    std::vector<std::vector<double> > B =  {{5, 8, 1},\n                                            {2, 6, 7},\n                                            {3, 4, 5}};\n    grb::Matrix<double> mB(B, 0.);\n\n    // Empty dst\n    grb::Matrix<double> result(3, 3);\n\n    std::vector<std::vector<double> > ans =  {{99,  97, 87},\n                                              {83, 100, 81},\n                                              {72, 105, 78}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             grb::NoMask(),\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(),\n             transpose(mA), transpose(mB));\n\n    BOOST_CHECK_EQUAL(result, answer);\n\n    // Filled dst\n    grb::Matrix<double> res1(mOnes_3x3, 0.);\n\n    std::vector<std::vector<double> > ans1=  {{100,  98, 88},\n                                              { 84, 101, 82},\n                                              { 73, 106, 79}};\n    grb::Matrix<double> answer1(ans1, 0.);\n\n    grb::mxm(res1,\n             grb::NoMask(),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(),\n             transpose(mA), transpose(mB));\n\n    BOOST_CHECK_EQUAL(res1, answer1);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_Accum_ATBT_empty)\n{\n    grb::Matrix<double> mZero(3, 3);\n    grb::Matrix<double> mOnes(mOnes_3x3, 0.);\n    grb::Matrix<double> mC(mOnes_3x3, 0.);\n    grb::Matrix<double> mD(mOnes_3x3, 0.);\n\n    grb::mxm(mC,\n             NoMask(), Plus<double>(),\n             ArithmeticSemiring<double>(),\n             transpose(mOnes), transpose(mZero));\n    BOOST_CHECK_EQUAL(mC, mOnes);\n\n    grb::mxm(mD,\n             NoMask(), Plus<double>(),\n             ArithmeticSemiring<double>(),\n             transpose(mZero), transpose(mOnes));\n    BOOST_CHECK_EQUAL(mD, mOnes);\n}\n\n// ****************************************************************************\n// ****************************************************************************\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_NoAccum_AB_empty)\n{\n    grb::Matrix<double> mZero(3, 3);\n    grb::Matrix<double> mOnes(mOnes_3x3, 0.);\n    grb::Matrix<double> mC(3,3);\n\n    // NOTE: The mask is true for any non-zero.\n    grb::Matrix<bool> mMask(mLowerBoolMask_3x3, false);\n\n    std::vector<std::vector<double>> upper = {{0, 1, 1},\n                                              {0, 0, 1},\n                                              {0, 0, 0}};\n    grb::Matrix<double> mUpper(upper, 0.);\n\n    // Merge\n    mC = mOnes;\n    grb::mxm(mC,\n             mMask, NoAccumulate(),\n             ArithmeticSemiring<double>(), mZero, mOnes);\n    BOOST_CHECK_EQUAL(mC, mUpper);\n\n    mC = mOnes;\n    grb::mxm(mC,\n             mMask, NoAccumulate(),\n             ArithmeticSemiring<double>(), mOnes, mZero);\n    BOOST_CHECK_EQUAL(mC, mUpper);\n\n    // Replace\n    mC = mOnes;\n    grb::mxm(mC,\n             mMask, NoAccumulate(),\n             ArithmeticSemiring<double>(), mZero, mOnes, REPLACE);\n    BOOST_CHECK_EQUAL(mC, mZero);\n\n    mC = mOnes;\n    grb::mxm(mC,\n             mMask, NoAccumulate(),\n             ArithmeticSemiring<double>(), mOnes, mZero, REPLACE);\n    BOOST_CHECK_EQUAL(mC, mZero);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_NoAccum_AB_Merge_full_mask)\n{\n    IndexArrayType i_mA      =  {0, 0, 0, 1, 1, 1, 2, 2, 2};\n    IndexArrayType j_mA      =  {0, 1, 2, 0, 1, 2, 0, 1, 2};\n    std::vector<double> v_mA = {12, 7, 3, 4, 5, 6, 7, 8, 9};\n    Matrix<double, DirectedMatrixTag> mA(3, 3);\n    mA.build(i_mA, j_mA, v_mA);\n\n    IndexArrayType i_mB      = {0, 0, 0, 0, 1, 1, 1, 2, 2, 2, 2};\n    IndexArrayType j_mB      = {0, 1, 2, 3, 0, 1, 2, 0, 1, 2, 3};\n    std::vector<double> v_mB = {5, 8, 1, 2, 6, 7, 3, 4, 5, 9, 1};\n    Matrix<double, DirectedMatrixTag> mB(3, 4);\n    mB.build(i_mB, j_mB, v_mB);\n\n    Matrix<double, DirectedMatrixTag> result(3, 4);\n\n    IndexArrayType i_answer = {0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2};\n    IndexArrayType j_answer = {0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3};\n    std::vector<double> v_answer = {114, 160, 60, 27, 74, 97,\n                                    73, 14, 119, 157, 112, 23};\n    Matrix<double, DirectedMatrixTag> answer(3, 4);\n    answer.build(i_answer, j_answer, v_answer);\n\n    Matrix<unsigned int, DirectedMatrixTag> mask(3,4);\n    std::vector<unsigned int> v_mask(i_answer.size(), 1);\n    mask.build(i_answer, j_answer, v_mask);\n\n    mxm(result,\n        mask, grb::NoAccumulate(),\n        grb::ArithmeticSemiring<double>(),\n        mA, mB);\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_NoAccum_AB_mask_not_full)\n{\n    IndexArrayType i_mA    = {0, 0, 0, 1, 1, 1, 2, 2, 2};\n    IndexArrayType j_mA    = {0, 1, 2, 0, 1, 2, 0, 1, 2};\n    std::vector<double> v_mA = {12, 7, 3, 4, 5, 6, 7, 8, 9};\n    Matrix<double, DirectedMatrixTag> mA(3, 3);\n    mA.build(i_mA, j_mA, v_mA);\n\n    IndexArrayType i_mB    = {0, 0, 0, 0, 1, 1, 1, 2, 2, 2, 2};\n    IndexArrayType j_mB    = {0, 1, 2, 3, 0, 1, 2, 0, 1, 2, 3};\n    std::vector<double> v_mB = {5, 8, 1, 2, 6, 7, 3, 4, 5, 9, 1};\n    Matrix<double, DirectedMatrixTag> mB(3, 4);\n    mB.build(i_mB, j_mB, v_mB);\n\n    Matrix<double, DirectedMatrixTag> result(3, 4);\n\n    IndexArrayType i_answer = {0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2};\n    IndexArrayType j_answer = {0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2};\n    std::vector<double> v_answer = {114, 160, 60, 27, 74, 97,\n                                    73, 14, 119, 157, 112};\n    Matrix<double, DirectedMatrixTag> answer(3, 4);\n    answer.build(i_answer, j_answer, v_answer);\n\n    Matrix<unsigned int, DirectedMatrixTag> mask(3,4);\n    std::vector<unsigned int> v_mask(i_answer.size(), 1);\n    mask.build(i_answer, j_answer, v_mask);\n\n    mxm(result,\n        mask, grb::NoAccumulate(),\n        grb::ArithmeticSemiring<double>(),\n        mA, mB);\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_NoAccum_AB_Merge_Cones_Mlower_stored_zero)\n{\n    grb::Matrix<double> mA(mA_dense_3x3, 0.);\n    grb::Matrix<double> mB(mB_dense_3x4, 0.);\n\n    static std::vector<std::vector<double> > mMask_3x4 = {{1, 0, 0, 0},\n                                                          {1, 1, 0, 0},\n                                                          {1, 1, 1, 0}};\n    grb::Matrix<double> mMask(mMask_3x4, 0.);\n    mMask.setElement(0, 1, 0.);\n    BOOST_CHECK_EQUAL(mMask.nvals(), 7);\n\n    grb::Matrix<double> result(mOnes_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   1,   1,  1},\n                                             { 74,  97,   1,  1},\n                                             {119, 157, 112,  1}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             mMask,\n//                   grb::Second<double>(),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mA, mB);\n    BOOST_CHECK_EQUAL(result.nvals(), 12);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_NoAccum_AB_Merge_Cones_ABdup)\n{\n    // Build some matrices.\n    std::vector<std::vector<double> > m = {{1, 1, 0, 0},\n                                           {1, 2, 2, 0},\n                                           {0, 2, 3, 3},\n                                           {0, 0, 3, 4}};\n    grb::Matrix<double> mat(m, 0.);\n\n    grb::Matrix<double> result(mOnes_4x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{2,  1,  1,  1},\n                                             {3,  9,  1,  1},\n                                             {2, 10, 22,  1},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    static std::vector<std::vector<double> > mMask_4x4 = {{1, 0, 0, 0},\n                                                          {1, 1, 0, 0},\n                                                          {1, 1, 1, 0},\n                                                          {1, 1, 1, 1}};\n    grb::Matrix<double> mMask(mMask_4x4, 0.);\n\n    grb::mxm(result,\n             mMask,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mat, mat);\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_NoAccum_AB_Replace_ABdup_result_ones)\n{\n    // Build some matrices.\n    std::vector<std::vector<double> > m = {{1, 1, 0, 0},\n                                           {1, 2, 2, 0},\n                                           {0, 2, 3, 3},\n                                           {0, 0, 3, 4}};\n    grb::Matrix<double> mat(m, 0.);\n\n    grb::Matrix<double> result(mOnes_4x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{2,  0,  0,  0},\n                                             {3,  9,  0,  0},\n                                             {2, 10, 22,  0},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    static std::vector<std::vector<double> > mMask_4x4 = {{1, 0, 0, 0},\n                                                          {1, 1, 0, 0},\n                                                          {1, 1, 1, 0},\n                                                          {1, 1, 1, 1}};\n    grb::Matrix<double> mMask(mMask_4x4, 0.);\n\n    grb::mxm(result,\n             mMask,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mat, mat,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_AB_Replace_lower_mask_result_ones)\n{\n    grb::Matrix<double> mA(mA_dense_3x3, 0.);\n    grb::Matrix<double> mB(mB_dense_3x4, 0.);\n\n    // NOTE: The mask is true for any non-zero.\n    grb::Matrix<double> mMask(mLowerMask_3x4, 0.);\n    BOOST_CHECK_EQUAL(mMask.nvals(), 6);\n\n    grb::Matrix<double> result(mOnes_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   0,   0,  0},\n                                             { 74,  97,   0,  0},\n                                             {119, 157, 112,  0}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             mMask,\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), mA, mB,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(result.nvals(), 6);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_AB_Replace_bool_masked_result_ones)\n{\n    grb::Matrix<double> mA(mA_dense_3x3, 0.);\n    grb::Matrix<double> mB(mB_dense_3x4, 0.);\n\n    grb::Matrix<bool> mMask(mLowerBoolMask_3x4, false);\n    BOOST_CHECK_EQUAL(mMask.nvals(), 6);\n\n    grb::Matrix<double> result(mOnes_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   0,   0,  0},\n                                             { 74,  97,   0,  0},\n                                             {119, 157, 112,  0}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             mMask,\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), mA, mB,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(result.nvals(), 6);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_AB_Replace_mask_stored_zero_result_ones)\n{\n    grb::Matrix<double> mA(mA_dense_3x3, 0.);\n    grb::Matrix<double> mB(mB_dense_3x4, 0.);\n\n    static std::vector<std::vector<double> > mMask_3x4 = {{1, 0, 0, 0},\n                                                          {1, 1, 0, 0},\n                                                          {1, 1, 1, 0}};\n    grb::Matrix<double> mMask(mMask_3x4, 0.);\n    mMask.setElement(0, 1, 0.);\n    BOOST_CHECK_EQUAL(mMask.nvals(), 7);\n\n    grb::Matrix<double> result(mOnes_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   0,   0,  0},\n                                             { 74,  97,   0,  0},\n                                             {119, 157, 112,  0}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             mMask,\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), mA, mB,\n             REPLACE);\n    BOOST_CHECK_EQUAL(result.nvals(), 6);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_AB_Merge_Cones_Mlower)\n{\n    grb::Matrix<double> mA(mA_dense_3x3, 0.);\n    grb::Matrix<double> mB(mB_dense_3x4, 0.);\n\n    static std::vector<std::vector<double> > mMask_3x4 = {{1, 0, 0, 0},\n                                                          {1, 1, 0, 0},\n                                                          {1, 1, 1, 0}};\n    grb::Matrix<double> mMask(mMask_3x4, 0.);\n    BOOST_CHECK_EQUAL(mMask.nvals(), 6);\n\n    grb::Matrix<double> result(mOnes_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   1,   1,  1},\n                                             { 74,  97,   1,  1},\n                                             {119, 157, 112,  1}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             mMask,\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), mA, mB);\n    BOOST_CHECK_EQUAL(result.nvals(), 12);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_ATB_Replace_Mlower_Cones)\n{\n    grb::Matrix<double> mA(mA_dense_3x3, 0.);\n    grb::Matrix<double> mB(mB_dense_3x4, 0.);\n\n    grb::Matrix<double> result(mOnes_3x4, 0.);\n\n    static std::vector<std::vector<double> > mMask_3x4 = {{1, 0, 0, 0},\n                                                          {1, 1, 0, 0},\n                                                          {1, 1, 1, 0}};\n    grb::Matrix<double> mMask(mMask_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{112,   0,   0,  0},\n                                             { 97, 131,   0,  0},\n                                             { 87, 111, 102,  0}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             mMask,\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mA), mB,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_ATB_Replace_Mlower_Cones_Bidentity)\n{\n    grb::Matrix<double> mA(mA_dense_3x3, 0.);\n    grb::Matrix<double> mB(mIdentity_3x3, 0.);\n    grb::Matrix<double> result(mOnes_3x3, 0.);\n\n    static std::vector<std::vector<double> > mMask_3x3 = {{1, 0, 0},\n                                                          {1, 1, 0},\n                                                          {1, 1, 1}};\n    grb::Matrix<double> mMask(mMask_3x3, 0.);\n\n    std::vector<std::vector<double> > ans = {{12, 0, 0},\n                                             { 7, 5, 0},\n                                             { 3, 6, 9}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    //auto answer = grb::transpose(mA);\n\n    grb::mxm(result,\n             mMask,\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mA), mB,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_ATB_Merge_Cones_Mlower)\n{\n    grb::Matrix<double> mA(mA_dense_3x3, 0.);\n\n    std::vector<std::vector<double> > B = {{5, 8, 1},\n                                           {2, 6, 7},\n                                           {3, 4, 5}};\n    grb::Matrix<double> mB(B, 0.);\n\n    grb::Matrix<double> result(mOnes_3x3, 0.);\n\n    static std::vector<std::vector<double> > mMask_3x3 = {{1, 0, 0},\n                                                          {1, 1, 0},\n                                                          {1, 1, 1}};\n    grb::Matrix<double> mMask(mMask_3x3, 0.);\n\n    std::vector<std::vector<double> > ans = {{119,   1,  1},\n                                             { 66,  80,  1},\n                                             {108, 125, 98}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             mMask,\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), mA, transpose(mB));\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_ATB_Merge_Cones_Mmasked_Bidentity)\n{\n    grb::Matrix<double> mA(mA_dense_3x3, 0.);\n    grb::Matrix<double> mB(mIdentity_3x3, 0.);\n    grb::Matrix<double> result(mOnes_3x3, 0.);\n\n    static std::vector<std::vector<double> > mMask_3x3 = {{1, 0, 0},\n                                                          {1, 1, 0},\n                                                          {1, 1, 1}};\n    grb::Matrix<double> mMask(mMask_3x3, 0.);\n\n    std::vector<std::vector<double> > ans = {{12, 1, 1},\n                                             { 7, 5, 1},\n                                             { 3, 6, 9}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    //auto answer = grb::transpose(mA);\n\n    grb::mxm(result,\n             mMask,\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mA), mB);\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_ATB_Cones_Mlower)\n{\n    grb::Matrix<double> mA(mA_dense_3x3, 0.);\n    grb::Matrix<double> mB(mB_dense_3x4, 0.);\n\n    grb::Matrix<double> result(mOnes_3x4, 0.);\n\n    static std::vector<std::vector<double> > mMask_3x4 = {{1, 0, 0, 0},\n                                                          {1, 1, 0, 0},\n                                                          {1, 1, 1, 0}};\n    grb::Matrix<double> mMask(mMask_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{112,   1,   1,  1},\n                                             { 97, 131,   1,  1},\n                                             { 87, 111, 102,  1}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             mMask,\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mA), mB);\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_ABT_Mlower_Cones)\n{\n    grb::Matrix<double> mA(mA_dense_3x3, 0.);\n\n    std::vector<std::vector<double> > B = {{5, 8, 1},\n                                           {2, 6, 7},\n                                           {3, 4, 5}};\n    grb::Matrix<double> mB(B, 0.);\n\n    grb::Matrix<double> result(mOnes_3x3, 0.);\n\n    static std::vector<std::vector<double> > mMask_3x3 = {{1, 0, 0},\n                                                          {1, 1, 0},\n                                                          {1, 1, 1}};\n    grb::Matrix<double> mMask(mMask_3x3, 0.);\n\n    std::vector<std::vector<double> > ans = {{119,   0,  0},\n                                             { 66,  80,  0},\n                                             {108, 125, 98}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             mMask,\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), mA, transpose(mB),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_ATBT_Mlower_Cones)\n{\n    grb::Matrix<double> mA(mA_dense_3x3, 0.);\n    std::vector<std::vector<double> > B =  {{5, 8, 1},\n                                            {2, 6, 7},\n                                            {3, 4, 5}};\n    grb::Matrix<double> mB(B, 0.);\n\n    grb::Matrix<double> result(mOnes_3x3, 0.);\n\n    static std::vector<std::vector<double> > mMask_3x3 = {{1, 0, 0},\n                                                          {1, 1, 0},\n                                                          {1, 1, 1}};\n    grb::Matrix<double> mMask(mMask_3x3, 0.);\n\n    std::vector<std::vector<double> > ans =  {{99,   0,  0},\n                                              {83, 100,  0},\n                                              {72, 105, 78}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             mMask,\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mA), transpose(mB),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_ATBT_Merge_Cones_Mlower)\n{\n    grb::Matrix<double> mA(mA_dense_3x3, 0.);\n    std::vector<std::vector<double> > B =  {{5, 8, 1},\n                                            {2, 6, 7},\n                                            {3, 4, 5}};\n    grb::Matrix<double> mB(B, 0.);\n\n    grb::Matrix<double> result(mOnes_3x3, 0.);\n\n    static std::vector<std::vector<double> > mMask_3x3 = {{1, 0, 0},\n                                                          {1, 1, 0},\n                                                          {1, 1, 1}};\n    grb::Matrix<double> mMask(mMask_3x3, 0.);\n\n    std::vector<std::vector<double> > ans =  {{99,   1,  1},\n                                              {83, 100,  1},\n                                              {72, 105, 78}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             mMask,\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mA), transpose(mB));\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\n//****************************************************************************\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_NoAccum_AB_Replace_ABdup)\n{\n    // Build some matrices.\n    std::vector<std::vector<double> > m = {{1, 1, 0, 0},\n                                           {1, 2, 2, 0},\n                                           {0, 2, 3, 3},\n                                           {0, 0, 3, 4}};\n    grb::Matrix<double> mat(m, 0.);\n\n    grb::Matrix<double> result(mOnes_4x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{2,  0,  0,  0},\n                                             {3,  9,  0,  0},\n                                             {2, 10, 22,  0},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    static std::vector<std::vector<double> > mMask_4x4 = {{0, 1, 1, 1},\n                                                          {0, 0, 1, 1},\n                                                          {0, 0, 0, 1},\n                                                          {0, 0, 0, 0}};\n    grb::Matrix<double> mMask(mMask_4x4, 0.);\n\n    grb::mxm(result,\n             grb::complement(mMask),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mat, mat,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_AB_Replace_Cones_Mnlower)\n{\n    grb::Matrix<double> mA(mA_dense_3x3, 0.);\n    grb::Matrix<double> mB(mB_dense_3x4, 0.);\n\n    static std::vector<std::vector<double> > mMask_3x4 = {{0, 1, 1, 1},\n                                                          {0, 0, 1, 1},\n                                                          {0, 0, 0, 1}};\n    grb::Matrix<double> mMask(mMask_3x4, 0.);\n    BOOST_CHECK_EQUAL(mMask.nvals(), 6);\n\n    grb::Matrix<double> result(mOnes_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   0,   0,  0},\n                                             { 74,  97,   0,  0},\n                                             {119, 157, 112,  0}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             grb::complement(mMask),\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), mA, mB,\n             REPLACE);\n    BOOST_CHECK_EQUAL(result.nvals(), 6);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_AB_Replace_Mstored_zero)\n{\n    grb::Matrix<double> mA(mA_dense_3x3, 0.);\n    grb::Matrix<double> mB(mB_dense_3x4, 0.);\n\n    static std::vector<std::vector<double> > mMask_3x4 = {{0, 1, 1, 1},\n                                                          {0, 0, 1, 1},\n                                                          {0, 0, 0, 1}};\n    grb::Matrix<double> mMask(mMask_3x4, 0.);\n    mMask.setElement(0, 0, 0.);\n    BOOST_CHECK_EQUAL(mMask.nvals(), 7);\n\n    grb::Matrix<double> result(mOnes_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   0,   0,  0},\n                                             { 74,  97,   0,  0},\n                                             {119, 157, 112,  0}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             grb::complement(mMask),\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), mA, mB,\n             REPLACE);\n    BOOST_CHECK_EQUAL(result.nvals(), 6);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_AB_Merge)\n{\n    grb::Matrix<double> mA(mA_dense_3x3, 0.);\n    grb::Matrix<double> mB(mB_dense_3x4, 0.);\n\n    static std::vector<std::vector<double> > mMask_3x4 = {{0, 1, 1, 1},\n                                                          {0, 0, 1, 1},\n                                                          {0, 0, 0, 1}};\n    grb::Matrix<double> mMask(mMask_3x4, 0.);\n    BOOST_CHECK_EQUAL(mMask.nvals(), 6);\n\n    grb::Matrix<double> result(mOnes_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   1,   1,  1},\n                                             { 74,  97,   1,  1},\n                                             {119, 157, 112,  1}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             grb::complement(mMask),\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), mA, mB);\n    BOOST_CHECK_EQUAL(result.nvals(), 12);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_AB_Merge_Mstored_zero)\n{\n    grb::Matrix<double> mA(mA_dense_3x3, 0.);\n    grb::Matrix<double> mB(mB_dense_3x4, 0.);\n\n    static std::vector<std::vector<double> > mMask_3x4 = {{0, 1, 1, 1},\n                                                          {0, 0, 1, 1},\n                                                          {0, 0, 0, 1}};\n    grb::Matrix<double> mMask(mMask_3x4, 0.);\n    mMask.setElement(0, 0, 0.);\n    BOOST_CHECK_EQUAL(mMask.nvals(), 7);\n\n    grb::Matrix<double> result(mOnes_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   1,   1,  1},\n                                             { 74,  97,   1,  1},\n                                             {119, 157, 112,  1}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             grb::complement(mMask),\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), mA, mB);\n    BOOST_CHECK_EQUAL(result.nvals(), 12);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_AB_Merge_ABdup)\n{\n    // Build some matrices.\n    std::vector<std::vector<double> > m = {{1, 1, 0, 0},\n                                           {1, 2, 2, 0},\n                                           {0, 2, 3, 3},\n                                           {0, 0, 3, 4}};\n    grb::Matrix<double> mat(m, 0.);\n\n    grb::Matrix<double> result(mOnes_4x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{2,  1,  1,  1},\n                                             {3,  9,  1,  1},\n                                             {2, 10, 22,  1},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    static std::vector<std::vector<double> > mMask_4x4 = {{0, 1, 1, 1},\n                                                          {0, 0, 1, 1},\n                                                          {0, 0, 0, 1},\n                                                          {0, 0, 0, 0}};\n    grb::Matrix<double> mMask(mMask_4x4, 0.);\n\n    grb::mxm(result,\n             grb::complement(mMask),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), mat, mat);\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_ATB_Replace)\n{\n    grb::Matrix<double> mA(mA_dense_3x3, 0.);\n    grb::Matrix<double> mB(mB_dense_3x4, 0.);\n\n    grb::Matrix<double> result(mOnes_3x4, 0.);\n\n    static std::vector<std::vector<double> > mMask_3x4 = {{0, 1, 1, 1},\n                                                          {0, 0, 1, 1},\n                                                          {0, 0, 0, 1}};\n    grb::Matrix<double> mMask(mMask_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{112,   0,   0,  0},\n                                             { 97, 131,   0,  0},\n                                             { 87, 111, 102,  0}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             grb::complement(mMask),\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mA), mB,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_ATB_Replace_Bidentity)\n{\n    grb::Matrix<double> mA(mA_dense_3x3, 0.);\n    grb::Matrix<double> mB(mIdentity_3x3, 0.);\n    grb::Matrix<double> result(mOnes_3x3, 0.);\n\n    static std::vector<std::vector<double> > mMask_3x3 = {{0, 1, 1},\n                                                          {0, 0, 1},\n                                                          {0, 0, 0}};\n    grb::Matrix<double> mMask(mMask_3x3, 0.);\n\n    std::vector<std::vector<double> > ans = {{12, 0, 0},\n                                             { 7, 5, 0},\n                                             { 3, 6, 9}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    //auto answer = grb::transpose(mA);\n\n    grb::mxm(result,\n             grb::complement(mMask),\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mA), mB,\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_ATB_Merge)\n{\n    grb::Matrix<double> mA(mA_dense_3x3, 0.);\n    grb::Matrix<double> mB(mB_dense_3x4, 0.);\n\n    grb::Matrix<double> result(mOnes_3x4, 0.);\n\n    static std::vector<std::vector<double> > mMask_3x4 = {{0, 1, 1, 1},\n                                                          {0, 0, 1, 1},\n                                                          {0, 0, 0, 1}};\n    grb::Matrix<double> mMask(mMask_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{112,   1,   1,  1},\n                                             { 97, 131,   1,  1},\n                                             { 87, 111, 102,  1}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             grb::complement(mMask),\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mA), mB);\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_ATB_Merge_Bidentity)\n{\n    grb::Matrix<double> mA(mA_dense_3x3, 0.);\n    grb::Matrix<double> mB(mIdentity_3x3, 0.);\n    grb::Matrix<double> result(mOnes_3x3, 0.);\n\n    static std::vector<std::vector<double> > mMask_3x3 = {{0, 1, 1},\n                                                          {0, 0, 1},\n                                                          {0, 0, 0}};\n    grb::Matrix<double> mMask(mMask_3x3, 0.);\n\n    std::vector<std::vector<double> > ans = {{12, 1, 1},\n                                             { 7, 5, 1},\n                                             { 3, 6, 9}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    //auto answer = grb::transpose(mA);\n\n    grb::mxm(result,\n             grb::complement(mMask),\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mA), mB);\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_ABT_Replace)\n{\n    grb::Matrix<double> mA(mA_dense_3x3, 0.);\n\n    std::vector<std::vector<double> > B = {{5, 8, 1},\n                                           {2, 6, 7},\n                                           {3, 4, 5}};\n    grb::Matrix<double> mB(B, 0.);\n\n    grb::Matrix<double> result(mOnes_3x3, 0.);\n\n    static std::vector<std::vector<double> > mMask_3x3 = {{0, 1, 1},\n                                                          {0, 0, 1},\n                                                          {0, 0, 0}};\n    grb::Matrix<double> mMask(mMask_3x3, 0.);\n\n    std::vector<std::vector<double> > ans = {{119,   0,  0},\n                                             { 66,  80,  0},\n                                             {108, 125, 98}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             grb::complement(mMask),\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), mA, transpose(mB),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_ABT_Merge)\n{\n    grb::Matrix<double> mA(mA_dense_3x3, 0.);\n\n    std::vector<std::vector<double> > B = {{5, 8, 1},\n                                           {2, 6, 7},\n                                           {3, 4, 5}};\n    grb::Matrix<double> mB(B, 0.);\n\n    grb::Matrix<double> result(mOnes_3x3, 0.);\n\n    static std::vector<std::vector<double> > mMask_3x3 = {{0, 1, 1},\n                                                          {0, 0, 1},\n                                                          {0, 0, 0}};\n    grb::Matrix<double> mMask(mMask_3x3, 0.);\n\n    std::vector<std::vector<double> > ans = {{119,   1,  1},\n                                             { 66,  80,  1},\n                                             {108, 125, 98}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             grb::complement(mMask),\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), mA, transpose(mB));\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_ATBT_Replace)\n{\n    grb::Matrix<double> mA(mA_dense_3x3, 0.);\n    std::vector<std::vector<double> > B =  {{5, 8, 1},\n                                            {2, 6, 7},\n                                            {3, 4, 5}};\n    grb::Matrix<double> mB(B, 0.);\n\n    grb::Matrix<double> result(mOnes_3x3, 0.);\n\n    static std::vector<std::vector<double> > mMask_3x3 = {{0, 1, 1},\n                                                          {0, 0, 1},\n                                                          {0, 0, 0}};\n    grb::Matrix<double> mMask(mMask_3x3, 0.);\n\n    std::vector<std::vector<double> > ans =  {{99,   0,  0},\n                                              {83, 100,  0},\n                                              {72, 105, 78}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             grb::complement(mMask),\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mA), transpose(mB),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_ATBT_Merge)\n{\n    grb::Matrix<double> mA(mA_dense_3x3, 0.);\n    std::vector<std::vector<double> > B =  {{5, 8, 1},\n                                            {2, 6, 7},\n                                            {3, 4, 5}};\n    grb::Matrix<double> mB(B, 0.);\n\n    grb::Matrix<double> result(mOnes_3x3, 0.);\n\n    static std::vector<std::vector<double> > mMask_3x3 = {{0, 1, 1},\n                                                          {0, 0, 1},\n                                                          {0, 0, 0}};\n    grb::Matrix<double> mMask(mMask_3x3, 0.);\n\n    std::vector<std::vector<double> > ans =  {{99,   1,  1},\n                                              {83, 100,  1},\n                                              {72, 105, 78}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             grb::complement(mMask),\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mA), transpose(mB));\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "395df9669ba55ff44c6fa32f418c68b256a7b509", "size": 82708, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/test_mxm.cpp", "max_stars_repo_name": "KIwabuchi/gbtl", "max_stars_repo_head_hexsha": "62c6b1e3262f3623359e793edb5ec4fa7bb471f0", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 112.0, "max_stars_repo_stars_event_min_datetime": "2016-04-26T05:54:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T05:56:16.000Z", "max_issues_repo_path": "src/test/test_mxm.cpp", "max_issues_repo_name": "KIwabuchi/gbtl", "max_issues_repo_head_hexsha": "62c6b1e3262f3623359e793edb5ec4fa7bb471f0", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 21.0, "max_issues_repo_issues_event_min_datetime": "2016-03-22T19:06:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-07T15:40:18.000Z", "max_forks_repo_path": "src/test/test_mxm.cpp", "max_forks_repo_name": "KIwabuchi/gbtl", "max_forks_repo_head_hexsha": "62c6b1e3262f3623359e793edb5ec4fa7bb471f0", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2016-04-26T05:54:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-21T03:33:20.000Z", "avg_line_length": 36.483458315, "max_line_length": 81, "alphanum_fraction": 0.4409730619, "num_tokens": 23575, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723317123102956, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.4611855630110988}}
{"text": "static bool eigen_did_assert = false;\n#define eigen_assert(X) if(!eigen_did_assert && !(X)){ std::cout << \"### Assertion raised in \" << __FILE__ << \":\" << __LINE__ << \":\\n\" #X << \"\\n### The following would happen without assertions:\\n\"; eigen_did_assert = true;}\n\n#include <iostream>\n#include <Eigen/Eigen>\n\n#ifndef M_PI\n#define M_PI 3.1415926535897932384626433832795\n#endif\n\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n// intentionally remove indentation of snippet\n{\nSparseMatrix<double> A(3,3);\nA.insert(1,2) = 0;\nA.insert(0,1) = 1;\nA.insert(2,0) = 2;\nA.makeCompressed();\ncout << \"The matrix A is:\" << endl << MatrixXd(A) << endl;\ncout << \"it has \" << A.nonZeros() << \" stored non zero coefficients that are: \" << A.coeffs().transpose() << endl;\nA.coeffs() += 10;\ncout << \"After adding 10 to every stored non zero coefficient, the matrix A is:\" << endl << MatrixXd(A) << endl;\n\n}\n  return 0;\n}\n", "meta": {"hexsha": "f1cc9840fe118010ffd5544206cda9dfbe3ab4e8", "size": 944, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "build/compiled_eigen/doc/snippets/compile_SparseMatrix_coeffs.cpp", "max_stars_repo_name": "aminulce/soil_model_cpp", "max_stars_repo_head_hexsha": "027803c29cbf5bddd1222839ba73019876533f87", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "build/compiled_eigen/doc/snippets/compile_SparseMatrix_coeffs.cpp", "max_issues_repo_name": "aminulce/soil_model_cpp", "max_issues_repo_head_hexsha": "027803c29cbf5bddd1222839ba73019876533f87", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "build/compiled_eigen/doc/snippets/compile_SparseMatrix_coeffs.cpp", "max_forks_repo_name": "aminulce/soil_model_cpp", "max_forks_repo_head_hexsha": "027803c29cbf5bddd1222839ba73019876533f87", "max_forks_repo_licenses": ["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.6060606061, "max_line_length": 224, "alphanum_fraction": 0.6641949153, "num_tokens": 278, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723316991792861, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.4611855626367634}}
{"text": "/**\n* @file: CrowdBT.hpp\n* @brief:\n* @author: Changjiang Cai, ccai1@stevens.edu, caicj5351@gmail.com\n* @version: 0.0.1\n* @creation date: 17-12-2015\n* @last modified: Thu 10 Mar 2016 09:32:02 AM EST\n*/\n\n#ifndef __HEADER__CROWD_SOURCING_CROWD_BT_H_\n#define __HEADER__CROWD_SOURCING_CROWD_BT_H_\n#include <cmath>\n#include <vector>\n#include <random>\n#include <algorithm>\n#include <ctime>\n#include <climits>\n#include <utility> // std::pair, std::make_pair\n#include <tuple>\n#include <boost/math/special_functions/digamma.hpp>\n#include <iostream>\n#include \"ktaub.hpp\"\n#include \"MyUtility.hpp\"\n\nusing namespace std;\n/*\n* KL(p || q) = ...\n* p = N(mu_1, var_1), q = N(mu_2, var_2);\n* where var_1 = sigma_1^2; and var_2 = sigma_2^2;\n*/\n// KL divergence of two Gaussian distributions.\n// See its definition in Equation (1.113) on Page 55, PRML. M. Bishop. \ndouble KLGaussian(const double mu_p, const double var_p, const double mu_q,\n\tconst double var_q);\n\n// Beta function B(a, b) = Gamma(a)* Gamma(b)/ Gamma(a+ b);\n// Note that Beat function is different from Beta distribution.\n// see Wikipedia for detailed information about its definition. \ndouble Beta(const double & a, const double & b);\n\n// KL divergence of two Beta distributions.\n// Beta(x | a, b) = constant * x^(a -1) *(1-x)^(b -1)\n// = Gamma(a + b)/ (Gamma(a)*Gamma(b)) * x^(a -1) *(1-x)^(b -1).\ndouble KLBeta(const double alpha_p, const double beta_p,\n\tconst double alpha_q, const double beta_q);\n\n\n/* ***************************************\n* for the first voting, (o_i, o_j), this pairwise comparison could generate\n* the two possible voting results, i.e., o_i > o_j, and o_i < o_j.\n* How will they affect the final global ranking, if they are chosen separately?\n* ***************************************\n*/\n\n\n\n/* Here we want to study the problem that how two opposite outcomes of the\n* first pair comparison, like (o_i, o_j) will impact the final global ranking?\n* Specifically speaking,\r\n* 1) For the first pair comparison, I do not set a specific one. Which pair\r\nis chosen totally depends on maximum KL divergence in Equation 10 in this paper.\r\n* 2) 1st-trial: For example, there are two cases (or two curves), one is normal,\r\nthe other is reverse. They are assigned two copies of the same initial prior distributions\r\n(that is with the same \\mu and \\sigma etc, even though those parameters\r\nare randomly generated.) Therefore, the same first pair comparison,\r\nfor example, (object 13, object 16) will be chosen for both of them.\r\nThen they will vote (object 13 > object 16) and (object 13 < object 16),\r\nrespectively. The subsequent processes will continue as usual.\r\n\r\n* 3) 2nd-trial: Since a different setting of initialization of those prior distributions,\nprobably a new pair, different from that in Fig 1, will be selected,\nfor example, (object 1, object 5). And so on ...\n*/\nvoid run_CrowdBT_1st_pair(const int & num_o, const int * p_num_w,\n\tconst int num_w_size, const int & num_repeat);\n\n// different setting of number of workers;\n// meaning graphs with different degrees. \nvoid run_CrowdBT_diff_w_num(const int & num_o,\n\tconst int & num_repeat);\n\n\n\nstruct INITIALS{\n\tdouble alpha_init;\n\tdouble beta_init;\n\tdouble eta_init;\n\tdouble mu_init;\n\tdouble var_init;\n\tdouble kappa_init;\n};\n\n\nstruct PARAMS {\n\t// vector<double> v_alpha; // Beta distribution\n\t// vector<double> v_beta; // Beta distribution\n\tdouble alpha, beta, kappa; // Beta distribution\n\t/* the probability that the k-th annotator agrees\n\t * with the true pairwise preference.\n\t */\n\t// vector<double> v_eta;\n\tdouble eta;\n\tvector<double> v_mu; // mean of Gaussian;\n\tvector<double> v_emu;// exp(mu)\n\tvector<double> v_var; // variance of Gaussian;\n\tvector<vector<double>> vv_history;\n\n\t// 1) default constructor;\n\tPARAMS(){}\n\t// 2) user defined constructor;\n\tPARAMS(const int & num_o, const INITIALS & a){\n\t\t//v_alpha = vector<double>(num_o, a.alpha_init);\n\t\t//v_beta =  vector<double>(num_o, a.beta_init);\n\t\talpha = a.alpha_init;\n\t\tbeta = a.beta_init;\n\t\tkappa = a.kappa_init;\n\t\t// v_eta =   vector<double>(num_o, a.eta_init);\n\t\teta = a.eta_init;\n\n\t\tsrand((unsigned)time(NULL));\r\n\r\n\t\tv_mu = vector<double>(num_o, a.mu_init);\r\n\t\tv_emu = vector<double>(num_o, 0.0);\r\n\r\n\r\n\t\tfor (int i = 0; i < num_o; ++i){\r\n\t\t\t// generate a uniform random value [0, 1]\r\n\t\t\tv_mu[i] *= rand() / double(RAND_MAX);\r\n\t\t\tv_emu[i] = exp(v_mu[i]);\r\n\t\t}\n\t\tv_var = vector<double>(num_o, a.var_init);\n\t\tvv_history = vector<vector<double>>(num_o, vector<double>(num_o, 0));\n\t}\n\n\t// 3) copy constructor;\n\tPARAMS(const PARAMS & p){\n\t\t//v_alpha = vector<double>(num_o, a.alpha_init);\n\t\t//v_beta =  vector<double>(num_o, a.beta_init);\n\t\talpha = p.alpha;\n\t\tbeta = p.beta;\n\t\tkappa = p.kappa;\n\t\teta = p.eta;\n\r\n\t\t// vector : copy constructor\r\n\t\tv_mu = vector<double>(p.v_mu);\r\n\t\tv_emu = vector<double>(p.v_emu);\n\t\tv_var = vector<double>(p.v_var);\n\t\tvv_history = vector<vector<double>>(p.vv_history);\n\t}\n\n\t// destructor\n\t~PARAMS(){\n\t\t// release memory space;\n\t\t//vector<double>().swap(v_alpha);\n\t\t//vector<double>().swap(v_beta);\n\t\t//vector<double>().swap(v_eta);\n\t\tvector<double>().swap(v_mu);\n\t\tvector<double>().swap(v_emu);\n\t\tvector<double>().swap(v_var);\n\t\tvector<vector<double>>().swap(vv_history);\n\t}\n\n};\n\nstruct NEW_PARAMS {\n\t// we assume object i > object j;\n\t// for the opposite case (i.e., object j > object i), \n\t// just swap i and j before calling this function,\n\t// or consider always \"mu_i_new\" as the preferred object,\n\t// and \"mu_j_new\" as the less one.\n\tdouble mu_i_new,\n\t\tmu_j_new,\n\t\tvar_i_new,\n\t\tvar_j_new,\n\t\talpha_new,\n\t\tbeta_new;\n};\n\n\n\n\nclass Crowd_BT{\n\nprivate:\n\tint num_o; // number of objects;\n\tPARAMS params;\npublic:\n\t// constructor\n\tCrowd_BT(const int & num_o, const INITIALS & a){\n\t\tparams = PARAMS(num_o, a);\n\t\tthis->num_o = num_o;\n\t}\n\n\t// copy constructor\n\t// constructor\n\tCrowd_BT(const Crowd_BT & bt){\n\t\tparams = PARAMS(bt.params);\n\t\tthis->num_o = bt.num_o;\n\t}\n\t// destructor\n\t~Crowd_BT(){ params.~PARAMS(); }\n\n\t// To rank objects by sorting the obtained {mu_i}(means of Gaussians.);\n\t// return the object ranking in an ascending order.\n\tint * get_ascending_ranking();\n\t/*Equation (19), (16)*/\n\tvoid get_C(const int & i, const int & j, double & c1, double & c);\n\n\t\n\t/*\n\t* Update the parameters based on the equations shown in the paper:\n\t* \"Pairwise Ranking Aggregation in a CrowdSourced Setting\".\n\t* The equation will be named according to the number originally shown\n\t* in this paper.\n\t* Pay attention to this function:\n\t* its first parameter means the preferred object,\n\t* therefore, if o_j > o_i, we should input j as the first\n\t* parameter to this function. For the opposite case of o_i > o_j, \n\t* we should pass i as the first parameter to this function.\n\t*/\n\tNEW_PARAMS get_updated_parameters(const int & i, const int& j,\n\t\tdouble & c1, double & c);\n\n\n\t/* v_layers describes how to measure the similarity of objects to be ranked.\n\t * If we have L = 20 objects, the ranking is 1, 2, ..., L.\n\t * We can set the ambiguity level, for example, we set v_layers = [0.25, 0.5, 1],\n\t * generating the following ranking layers:\n\t *  1) level 1: [0, 0.25]* L  = [0, 5];\n\t *  2) level 2: [0.25, 0.75] * L = [5, 14];\n\t *  3) level 3: [0.75, 1.0] * L = [14, 20];\n\t * If object 1 and object 2 come from the same layer, like, they belong to level 2,\n\t * there is a possibility that wrong ranking will occur,\n\t * according to some probability distribution.\n\t * We will implement the above idea in the following function.\n\t */\n\tbool get_preference(const vector<double> & v_scores,\n\t\tconst int & i, const int & j, const vector<double> & v_layers);\n\n\t/* Select a pair (o_i, o_j) for some annotator k which\n\t * maximize the expected information gain in E.q.(10).\n\t * parameter: gamma, exploration-exploitation trade-off,\n\t * see Section 5.1.2 in this paper.\n\t */\n\t//**********************************\n\t// before actual voting, try to select a pair of objects o_i and o_j,\n\t// such that they can maximize the expected information gain \n\t// in E.q.(10) in this paper.\n\t//**********************************\n\tstd::tuple<int, int, double> get_pair(const double & gamma);\n\n\t/* assign the new parameters to the member variables in this class.\n\t * Inputs:\n\t * - i_max: (object i, object j) with maximum KL divergence;\n\t * - j_max: (object i, object j) with maximum KL divergence;\n\t */\n\tvoid keep_new_params(const NEW_PARAMS & new_para, const int & i_max,\n\t\tconst int & j_max);\n\n\n\t/* For one worker, like worker k, he/she will select a pair (o_i, o_j),\n\t* 1) after he/she do once (i.e., 1 time ) voting, we could update the \n\t* parameters of those distribution according to Bayes' Theorem.\n\t* 2) If we consider the wrong voting probability that a worker will give wrong\n\t* voting result, probably due to the high similarity between o_i, o_j, or\n\t* due to the work quality or even the malicious behavior of this worker.\n\t*/\n\tvector<pair<int, int>> repeated_voting_1_worker(const int * p_rank_gt,\n\t\tconst int & num_repeat, const vector<double> & v_scores,\n\t\tconst vector<double> & v_layers, const double & gamma,\n\t\tconst bool & IsDisplay, const bool & IsReverse,\n\t\tconst pair<int, int> & p_ij);\n\n\n\t// calculate the Kendall-tau distance between two ranking:\n\t//  1) ranking 1: is the input, usually the ground truth ranking or\n\t//     the result obtained from other algorithms;\n\t//  2) ranking 2: is the ranking obtained by this algorithm. \n\tdouble get_kendall_tau_distance(\n\t\t// ranking 1\n\t\tconst int * p_rank_gt, /*ground truth ranking*/\n\t\tconst bool & IsDisplay);\n\n\tvoid Crowd_BT::repeated_voting_1_worker(\n\t\tconst vector<int> & v_scores, // scores of each object.\n\t\tconst int & n, // vertex number\n\t\tconst int & distribution,\n\t\tconst int & num_repeat,\n\t\t//const double & stddev, // Gaussian variance to control the worker's quality.\n\t\tconst int& quality, // different levels of error-rate for the worker's quality.\n\t\tconst bool & IsDisplay, const pair<int, int> & p_ij,\n\t\tconst bool & Is_Beta_Simu_data_type // == true, using Beta distribution to simulate the voting result.\n\t\t);\n\n};\n\ndouble one_worker_reverse_or_not(const int & num_o, const int num_w,\n\tconst int * p_rank_gt,\n\tconst int & num_repeat, const vector<double> & v_scores,\n\tconst vector<double> & v_layers,\n\tconst double & gamma, const bool & IsDisplay, const bool & IsReverse,\n\tCrowd_BT & c_bt1);\n\n#endif", "meta": {"hexsha": "94d9a9a2fc8a400d8e52407758bec52cd8861cb6", "size": 10259, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/CrowdBT.hpp", "max_stars_repo_name": "ccj5351/crowdsourcing", "max_stars_repo_head_hexsha": "b0c2052ed4ae7ca42aa20436c271e6de5c5258a1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/CrowdBT.hpp", "max_issues_repo_name": "ccj5351/crowdsourcing", "max_issues_repo_head_hexsha": "b0c2052ed4ae7ca42aa20436c271e6de5c5258a1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/CrowdBT.hpp", "max_forks_repo_name": "ccj5351/crowdsourcing", "max_forks_repo_head_hexsha": "b0c2052ed4ae7ca42aa20436c271e6de5c5258a1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7467105263, "max_line_length": 104, "alphanum_fraction": 0.6883711863, "num_tokens": 2858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723316991792861, "lm_q2_score": 0.6859494485880927, "lm_q1q2_score": 0.46118555832032676}}
{"text": "#pragma once\n\n#include \"cfl_condition.hpp\"\n#include \"mesh.hpp\"\n#include \"numerical_flux.hpp\"\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <chrono>\n#include <fmt/format.h>\n\nvoid print_progress(\n    int n_steps,\n    double T,\n    double t,\n    double dt,\n    const std::chrono::high_resolution_clock::time_point &time_start);\n\nEigen::MatrixXd solveEuler(Eigen::MatrixXd U0, const Mesh &mesh, double T) {\n\n    int n_cells = mesh.getNumberOfTriangles();\n\n    Eigen::MatrixXd U_tmp(n_cells, 4);\n    Eigen::MatrixXd dUdt(n_cells, 4);\n\n    double t = 0;\n\n    auto cfl_condition = CFLCondition(mesh);\n    auto computeNetFlux = FluxRateOfChange(n_cells);\n\n    int n_steps = 0;\n\n    auto time_start = std::chrono::high_resolution_clock::now();\n\n    std::cout << std::endl;\n    while (t < T) {\n        double dt = cfl_condition(U0);\n\n        // Compute u^(*)\n        computeNetFlux(dUdt, U0, mesh);\n#pragma omp parallel for\n        for (int i = 0; i < n_cells; ++i) {\n            U_tmp.row(i) = U0.row(i) + dt * dUdt.row(i);\n        }\n\n        // Compute u^(**) and u^{n+1} in one step. We can update U0 directly.\n        computeNetFlux(dUdt, U_tmp, mesh);\n#pragma omp parallel for\n        for (int i = 0; i < n_cells; ++i) {\n            U0.row(i) = 0.5 * (U0.row(i) + U_tmp.row(i) + dt * dUdt.row(i));\n        }\n\n        t += dt;\n        n_steps++;\n\n        print_progress(n_steps, T, t, dt, time_start);\n    }\n    std::cout << \"\\n\";\n\n    return U0;\n}\n\nvoid print_progress(\n    int n_steps,\n    double T,\n    double t,\n    double dt,\n    const std::chrono::high_resolution_clock::time_point &time_start) {\n\n    auto now = std::chrono::high_resolution_clock::now();\n    auto duration = std::chrono::duration_cast<std::chrono::duration<double>>(\n        now - time_start);\n    double elapsed = duration.count();\n    double eta = elapsed * (T - t) / t;\n\n    std::cout << fmt::format(\"\\r\"\n                             \"n_steps = {: 3d}, t = {:.3e}, dt = {:.2e}, \"\n                             \"elased = {:6.1f}s, eta = {:6.1f}s\",\n                             n_steps,\n                             t,\n                             dt,\n                             elapsed,\n                             eta);\n    std::cout.flush();\n}\n", "meta": {"hexsha": "9e01c88d4d6087e6fe58ec3d67f84b375ecea7d7", "size": 2227, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "series2_handout/unstructured_euler/solve_euler.hpp", "max_stars_repo_name": "BeatHubmann/19H-AdvNCSE", "max_stars_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-05T22:38:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-05T22:38:47.000Z", "max_issues_repo_path": "series2_handout/unstructured_euler/solve_euler.hpp", "max_issues_repo_name": "BeatHubmann/19H-AdvNCSE", "max_issues_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "series2_handout/unstructured_euler/solve_euler.hpp", "max_forks_repo_name": "BeatHubmann/19H-AdvNCSE", "max_forks_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-12-08T20:43:27.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-08T20:43:27.000Z", "avg_line_length": 25.8953488372, "max_line_length": 78, "alphanum_fraction": 0.5406376291, "num_tokens": 595, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723316860482763, "lm_q2_score": 0.6859494614282922, "lm_q1q2_score": 0.46118555794599075}}
{"text": "#define BOOST_TEST_MODULE \"root_name\"\n// #define BOOST_TEST_MAIN\n\n// note we only test CalibratorSample.\n#include \"CalibratorSample.h\"\n\n#include <boost/test/unit_test.hpp>\n#include <boost/shared_ptr.hpp>\n\n#include <random>\n#include <iostream>\n\n\n// this bitpacker is only used in the unittests, so doesn't need to be fast.\nstruct BitPacker\n{\n    void clear()\n    {\n        m_val = 0;\n    }\n\n    void setCoarse(uint16_t c)\n    {\n        uint16_t mask = 0x001f;\n        c <<= 0;\n        c &= mask;\n        m_val &= ~mask;\n        m_val |= c;\n    }\n    void setFine(uint16_t f)\n    {\n        uint16_t mask = 0x1fe0;\n        f <<= 5;\n        f &= mask;\n        m_val &= ~mask;\n        m_val |= f;\n    }\n    void setGain(uint16_t g)\n    {\n        uint16_t mask = 0x6000;\n        g <<= 13;\n        g &= mask;\n        m_val &= ~mask;\n        m_val |= g;\n    }\n    uint16_t getBits()\n    {\n        return m_val;\n    }\n    void setBits(uint16_t val)\n    {\n        m_val = val;\n    }\n    uint16_t m_val = 0;\n};\n\n\n// note there are two versions of the same function: processFrameRowSIMD and processFrameRow\n// These unit-tests should pass on BOTH, but our strategy is to test one of them, and then\n// check they both produce the same results. Although we can also do a search-replace.\n// recall the equation we are testing is:\n// res = IdOf + Gc * (c-Oc) + Gf * (f-Of)\n\n\n// these k values should be non-zero\nstatic const float k1 = 1.1f;\nstatic const float k2 = 2.2f;\nstatic const float k3 = 3.4f;\nstatic const float k4 = 4.8f;\nstatic const float k5 = 5.2f;\nstatic const float k6 = 6.5f;\nstatic const float k7 = 7.8f;\nstatic const float k8 = 8.3f;\nstatic const float smallPercent = 0.001f;\nstatic const float idealOffset = 128.0 * 32.0f;\n\nBOOST_AUTO_TEST_CASE(CalibratorCreateAndDestroy)\n{\n    CalibratorSample calibrator;\n    \n    BOOST_CHECK_CLOSE(1000.0F, 1000.001f, smallPercent);\n    // alignment check\n    BOOST_CHECK((uint64_t)calibrator.m_Gc.data()%32 == 0);\n}\n\n// this one checks that IdOf is ok.\nBOOST_AUTO_TEST_CASE(CalibratorIdealOffset)\n{\n    int rows=1, cols=8;\n    CalibratorSample calibrator(rows,cols);\n\n    calibrator.m_Gc.at(0,0) = 0.0;\n    calibrator.m_Oc.at(0,0) = k2;\n    calibrator.m_Gf.at(0,0) = 0.0;\n    calibrator.m_Of.at(0,0) = k4;\n    calibrator.m_Gain0.at(0,0) = 1.0;\n\n    BitPacker bp;\n    bp.clear();\n    bp.setCoarse(4); // random value\n    bp.setFine(4);\n    bp.setGain(0);\n\n    MemBlockI16 input;\n    MemBlockF output;\n\n    input.init(rows,cols);\n    output.init(rows,cols);\n\n    input.at(0,0) = bp.getBits();\n\n    calibrator.processFrameRow(input, output, 0);\n    BOOST_CHECK_CLOSE(output.at(0,0), idealOffset, smallPercent);\n}\n\n// this one checks that the coarse value is processed ok\n// then it checks that the fine value is processed ok\n// then it checks the complete sum works out ok\n// also known as ADC stage\nBOOST_AUTO_TEST_CASE(CalibratorCoarseAndFine)\n{\n    int rows=1, cols=8;\n    CalibratorSample calibrator(rows,cols);\n\n    calibrator.m_Gc.at(0,0) = k1;\n    calibrator.m_Oc.at(0,0) = k2;\n    calibrator.m_Gf.at(0,0) = k3;\n    calibrator.m_Of.at(0,0) = k4;\n    calibrator.m_Gain0.at(0,0) = 1.0;\n\n    BitPacker bp;\n    bp.clear();\n    bp.setCoarse(8);\n    bp.setFine(150);\n    bp.setGain(0);\n\n    MemBlockI16 input;\n    MemBlockF output;\n\n    input.init(rows,cols);\n    output.init(rows,cols);\n\n    input.at(0,0) = bp.getBits();\n\n    // check coarse alone\n    calibrator.m_Gf.at(0,0) = 0.0;\n    calibrator.processFrameRow(input, output, 0);\n    BOOST_CHECK_CLOSE(output.at(0,0), idealOffset + k1 * (8.0f - k2), smallPercent);\n\n    // check fine alone\n    input.at(0,0) = bp.getBits();\n    calibrator.m_Gc.at(0,0) = 0.0;\n    calibrator.m_Gf.at(0,0) = k3;\n    calibrator.processFrameRow(input, output, 0);\n    BOOST_CHECK_CLOSE(output.at(0,0), idealOffset + k3 * (150.0f - k4), smallPercent);\n\n    // now do both together:\n    input.at(0,0) = bp.getBits();\n    calibrator.m_Gc.at(0,0) = k1;\n    calibrator.processFrameRow(input, output, 0);\n    BOOST_CHECK_CLOSE(output.at(0,0), idealOffset + k1 * (8.0f - k2) + k3 * (150.0f - k4), smallPercent);\n}\n\n// this one checks that the cds-stage = subtract reset frame, is ok\nBOOST_AUTO_TEST_CASE(CalibratorReset)\n{\n    int rows=1, cols=8;\n    CalibratorSample calibrator(rows,cols);\n\n    calibrator.m_Gc.at(0,0) = 0.0;\n    calibrator.m_Gf.at(0,0) = 0.0;\n    calibrator.m_Gc.at(0,1) = 0.0;\n    calibrator.m_Gf.at(0,1) = 0.0;\n    calibrator.m_resetFrame.at(0,0) = k8;\n\n    BitPacker bp;\n    bp.clear();\n    bp.setGain(0);\n\n    MemBlockI16 input;\n    MemBlockF output;\n\n    input.init(rows,cols);\n    output.init(rows,cols);\n\n    input.at(0,0) = bp.getBits();\n    bp.setGain(1);\n    input.at(0,1) = bp.getBits();\n\n    float idOf = 128.0f * 32.0f;\n    // check reset frame is subtracted\n    calibrator.processFrameRow(input, output, 0);\n    BOOST_CHECK_CLOSE(output.at(0,0), idOf - k8, smallPercent);\n    // but not when gain = 1\n    BOOST_CHECK_CLOSE(output.at(0,1), idOf, smallPercent);\n}\n\n// this one checks the Lat stage: subtract Ped and multiply\nBOOST_AUTO_TEST_CASE(CalibratorLatPedGain)\n{\n    int rows=1, cols=8;\n    CalibratorSample calibrator(rows,cols);\n\n    calibrator.m_Gc.at(0,0) = 0.0;\n    calibrator.m_Gf.at(0,0) = 0.0;\n    calibrator.m_Gc.at(0,1) = 0.0;\n    calibrator.m_Gf.at(0,1) = 0.0;\n    calibrator.m_Ped0.at(0,0) = k1;\n    calibrator.m_Ped1.at(0,1) = k2;\n    calibrator.m_Ped2.at(0,2) = k3;\n    calibrator.m_Gain0.at(0,0) = k4;\n    calibrator.m_Gain1.at(0,1) = k5;\n    calibrator.m_Gain2.at(0,2) = k6;\n\n    BitPacker bp;\n    bp.clear();\n    bp.setGain(0);\n\n    MemBlockI16 input;\n    MemBlockF output;\n\n    input.init(rows,cols);\n    output.init(rows,cols);\n\n    input.at(0,0) = bp.getBits();\n    bp.setGain(1);\n    input.at(0,1) = bp.getBits();\n    bp.setGain(2);\n    input.at(0,2) = bp.getBits();\n    bp.setGain(3);\n    input.at(0,3) = bp.getBits();\n\n    float idOf = 128.0f * 32.0f;\n    // check right things subtracted in each case\n    calibrator.processFrameRow(input, output, 0);\n    BOOST_CHECK_CLOSE(output.at(0,0), k4 * (idOf - k1), smallPercent);\n    BOOST_CHECK_CLOSE(output.at(0,1), k5 * (idOf - k2), smallPercent);\n    BOOST_CHECK_CLOSE(output.at(0,2), k6 * (idOf - k3), smallPercent);\n    BOOST_CHECK(isnan(output.at(0,3)));\n\n}\n\nBOOST_AUTO_TEST_CASE(CalibratorAlgNanOk)\n{\n    int rows=1, cols=24;\n    CalibratorSample calibrator(rows,cols);\n\n    MemBlockI16 input;\n    input.init(rows,cols);\n\n    for(int c=0;c<cols;++c)\n    {\n        calibrator.m_Gc.at(0,c) = k1;\n        calibrator.m_Oc.at(0,c) = k2;\n        calibrator.m_Gf.at(0,c) = k3;\n        calibrator.m_Of.at(0,c) = k4;\n        calibrator.m_Gain0.at(0,c) = k5;\n        calibrator.m_Gain1.at(0,c) = k6;\n        calibrator.m_Gain2.at(0,c) = k7;\n        calibrator.m_Gain3 = k8;\n\n        input.at(0,c) = rand();\n    }\n\n    BitPacker bp;\n    bp.clear();\n    bp.setCoarse(1);\n    bp.setFine(1);\n    bp.setGain(0);\n\n    input.at(0,0) = bp.getBits();\n    calibrator.m_Gain0.at(0,0) = std::numeric_limits<float>::quiet_NaN();\n\n    calibrator.m_Gc.at(0,1) = std::numeric_limits<float>::quiet_NaN();\n\n    MemBlockF output1;\n    output1.init(rows,cols);\n    calibrator.processFrameRow(input, output1, 0);\n\n    float lastOne = 0.0f;\n    for(int c=0;c<cols;++c)\n    {\n        if( c==0 || c==1 )\n        {\n            BOOST_CHECK( isnan(output1.at(0,c)) );\n        }\n        else\n        {\n            BOOST_CHECK( !isnan(output1.at(0,c)) );\n        }\n    }\n}\n\n// this tests it when the cma value is not nan (all g0 on cma cols)\nBOOST_AUTO_TEST_CASE(CalibratorCMA_real)\n{\n    int rows=1, cols=64;\n    int col1 = 40;\n    CalibratorSample calibrator(rows,cols);\n    calibrator.setCMA(true, 0);\n\n    MemBlockF pic;\n    MemBlockI16 gain;\n    pic.init(rows,cols);\n    gain.init(rows,cols);\n    gain.setAll(0);\n    gain.at(0, col1) = 1;\n    \n    for(int c=0;c<cols;++c)\n    {\n        pic.at(0,c) = static_cast<float>(c);\n    }\n\n    calibrator.applyCMA(gain, pic, 0);\n\n    for(int c=0;c<cols;++c)\n    {\n        if(c==col1)\n        {\n            // cma value not subtracted here cos G1\n            BOOST_CHECK_CLOSE(pic.at(0,c), c, smallPercent);           \n        }\n        else\n        {\n            BOOST_CHECK_CLOSE(pic.at(0,c), c - (31.0f/2.0f), smallPercent);\n        }\n    }\n}\n\n// this tests it when the cma value is nan (not G0 on cma cols)\nBOOST_AUTO_TEST_CASE(CalibratorCMA_nan)\n{\n    int rows=1, cols=64;\n    int col1 = 40, col2 = 0;\n    CalibratorSample calibrator(rows,cols);\n    calibrator.setCMA(true, 0);\n\n    MemBlockF pic;\n    MemBlockI16 gain;\n    pic.init(rows,cols);\n    gain.init(rows,cols);\n    gain.setAll(0);\n    gain.at(0, col2) = 2;\n    gain.at(0, col1) = 1;\n    \n    for(int c=0;c<cols;++c)\n    {\n        pic.at(0,c) = static_cast<float>(c);\n    }\n\n    calibrator.applyCMA(gain, pic, 0);\n\n    for(int c=0;c<cols;++c)\n    {\n        if(c==col1 || c==col2)\n        {\n            // cma value not subtracted here cos G1\n            BOOST_CHECK_CLOSE(pic.at(0,c), c, smallPercent);           \n        }\n        else\n        {\n            BOOST_CHECK(isnan(pic.at(0,c)));\n        }\n    }\n}\n\n// this one tests processFrameRowSIMD produces the same as processFrameRow for\n// some random data. If they agree, they are both right because they are on\n// different code paths. We can't test CMA because it requires gain 0 on its row.\nBOOST_AUTO_TEST_CASE(CalibratorAlgSIMDSameAsNormal)\n{\n    const float percentDiff = 0.2;\n    int rows=1, cols=24;\n    CalibratorSample calibrator(rows,cols);\n\n    MemBlockI16 input, input2;\n    input.init(rows,cols);\n\n    calibrator.m_resetFrame.setAll(k4);\n\n    for(int c=0;c<cols;++c)\n    {\n        calibrator.m_Gc.at(0,c) = k1;\n        calibrator.m_Oc.at(0,c) = k2;\n        calibrator.m_Gf.at(0,c) = k3;\n        calibrator.m_Of.at(0,c) = k4;\n\n        calibrator.m_Ped0.at(0,c) = k3;\n        calibrator.m_Ped1.at(0,c) = k6;\n        calibrator.m_Ped2.at(0,c) = k7;\n\n        calibrator.m_Gain0.at(0,c) = k5;\n        calibrator.m_Gain1.at(0,c) = k6;\n        calibrator.m_Gain2.at(0,c) = k7;\n        calibrator.m_Gain3 = k8;\n\n        input.at(0,c) = rand();\n    }\n\n    input2.clone(input);\n\n    MemBlockF output1, output2;\n    output1.init(rows,cols);\n    output2.init(rows,cols);\n\n    calibrator.processFrameRowSIMD(input, output1, 0);\n    calibrator.processFrameRow(input2, output2, 0);\n\n    float lastOne = 0.0f;\n    for(int c=0;c<cols;++c)\n    {\n        {\n            BOOST_CHECK_CLOSE(output1.at(0,c), output2.at(0,c), percentDiff);\n            BOOST_CHECK(input.at(0,c) == input2.at(0,c));\n            // just check it's not all the same garbage data\n            BOOST_CHECK(lastOne != output1.at(0,c));\n            lastOne = output1.at(0,c);\n        }\n    }\n}\n\n\n", "meta": {"hexsha": "b33fc4ddb651c505a23b56d78474669b34d6774a", "size": 10662, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "data/frameProcessor/test/PercivalCalibTests.cpp", "max_stars_repo_name": "karmagh/percival-detector", "max_stars_repo_head_hexsha": "733bd0bec49da6f58fdf7ee8e167348542159ae5", "max_stars_repo_licenses": ["Apache-2.0"], "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/frameProcessor/test/PercivalCalibTests.cpp", "max_issues_repo_name": "karmagh/percival-detector", "max_issues_repo_head_hexsha": "733bd0bec49da6f58fdf7ee8e167348542159ae5", "max_issues_repo_licenses": ["Apache-2.0"], "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/frameProcessor/test/PercivalCalibTests.cpp", "max_forks_repo_name": "karmagh/percival-detector", "max_forks_repo_head_hexsha": "733bd0bec49da6f58fdf7ee8e167348542159ae5", "max_forks_repo_licenses": ["Apache-2.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.2056737589, "max_line_length": 105, "alphanum_fraction": 0.6077658976, "num_tokens": 3461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.46118555400389005}}
{"text": "/*  $Id$\n * \n *  Copyright 2010-2011 Anders Wallin (anders.e.e.wallin \"at\" gmail.com)\n *  \n *  This file is part of OpenCAMlib.\n *\n *  OpenCAMlib is free software: you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n *\n *  OpenCAMlib is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n *\n *  You should have received a copy of the GNU General Public License\n *  along with OpenCAMlib.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef TSP_H\n#define TSP_H\n\n#include <iostream>\n#include <vector>\n#include <fstream>\n#include <set>\n#include <ctime>\n\n#include <boost/assert.hpp>\n#include <boost/graph/adjacency_matrix.hpp>\n#include <boost/graph/simple_point.hpp>\n#include <boost/graph/metric_tsp_approx.hpp>\n\n#include <boost/python.hpp>\n\nnamespace ocl {\n\nnamespace tsp {\n\n// loosely based on metric tsp example:\n// http://www.boost.org/doc/libs/1_46_1/libs/graph/test/metric_tsp_approx.cpp\n\n//add edges to the graph (for each node connect it to all other nodes)\ntemplate< typename VertexListGraph, \n          typename PointContainer,\n          typename WeightMap, \n          typename VertexIndexMap>\nvoid connectAllEuclidean(VertexListGraph& g,\n                        const PointContainer& points,  // vector of (x,y) points\n                        WeightMap wmap,            // Property maps passed by value\n                        const VertexIndexMap vmap) // Property maps passed by value\n{\n    using namespace boost;\n    using namespace std;\n    typedef typename graph_traits<VertexListGraph>::edge_descriptor Edge;\n    typedef typename graph_traits<VertexListGraph>::vertex_iterator VItr;\n    Edge e;\n    bool inserted;\n    pair<VItr, VItr> verts(vertices(g));\n    for (VItr src(verts.first); src != verts.second; src++) {\n        for (VItr dest(src); dest != verts.second; dest++) {\n            if (dest != src) {\n                double weight( sqrt(\n                    pow(static_cast<double>( points[vmap[*src ]].x - points[vmap[*dest]].x), 2.0) +\n                    pow(static_cast<double>( points[vmap[*dest]].y - points[vmap[*src ]].y), 2.0)) );\n                boost::tie(e, inserted) = add_edge(*src, *dest, g);\n                wmap[e] = weight; // passed by value??\n            }\n        }\n    }\n}\n\nclass TSPSolver {\n    typedef boost::adjacency_matrix< boost::undirectedS, \n                                     boost::no_property,\n                                     boost::property< boost::edge_weight_t, double,\n                                     boost::property< boost::edge_index_t, long unsigned int> >,\n                                     boost::no_property \n                                    > Graph;\n    typedef boost::graph_traits<Graph>::vertex_descriptor Vertex;\n    typedef boost::graph_traits<Graph>::edge_descriptor Edge;\n    typedef boost::property_map<Graph, boost::edge_weight_t>::type WeightMap;\n    typedef std::vector< boost::simple_point<double> > PointSet; // was std::set\n    typedef std::vector< Vertex > Container;\n    \npublic:\n    TSPSolver () {}\n    virtual ~TSPSolver() {\n        if (g)\n            delete g;\n    }\n    void run() {\n        g = new Graph( points.size() );\n        // connect all vertices\n        WeightMap weight_map = boost::get( boost::edge_weight, *g);\n        connectAllEuclidean( *g, points, weight_map, boost::get( boost::vertex_index, *g) );\n        length = 0.0;\n        // Run the TSP approx, creating the visitor on the fly.\n        boost::metric_tsp_approx(*g, boost::make_tsp_tour_len_visitor(*g, std::back_inserter(output), length, weight_map) );\n        //length = len;\n        //std::cout << \"Number of points: \" << boost::num_vertices(*g) << std::endl;\n        //std::cout << \"Number of edges: \" << boost::num_edges(*g) << std::endl;\n        //std::cout << \"Length of tour: \" << len << std::endl;\n        //std::cout << \"vertices in tour: \" << output.size() << std::endl;\n        //std::cout << \"Elapsed: \" << t.elapsed() << std::endl;\n    }\n    void addPoint(double x, double y) {\n        boost::simple_point<double> pnt;\n        pnt.x=x;\n        pnt.y=y;\n        points.push_back(pnt);\n    }\n    void reset() {\n        output.clear();\n        points.clear();\n        if (g)\n            delete g;\n    }\n    void printOutput() const {\n        int n=0;\n        BOOST_FOREACH( Vertex v, output ) {\n            std::cout << n++ << \" : \" << v << \"\\n\" ;\n        }\n    }\n    double getLength() const {\n        return length;\n    }\n    boost::python::list getOutput() const {\n        boost::python::list plist;\n        BOOST_FOREACH(Vertex v, output) {\n            plist.append( v );\n        }\n        return plist;\n    }\n    \nprotected:\n    Container output;\n    PointSet points;\n    Graph* g;\n    double length;\n};\n\n\n} // end tsp namespace\n\n} // end ocl namespace\n#endif\n", "meta": {"hexsha": "9fc64a2c2e14618f467703e712e2a3d98922b6fd", "size": 5104, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "opencamlib/src/algo/tsp.hpp", "max_stars_repo_name": "JohnyEngine/CNC", "max_stars_repo_head_hexsha": "e4c77250ab2b749d3014022cbb5eb9924e939993", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "opencamlib/src/algo/tsp.hpp", "max_issues_repo_name": "JohnyEngine/CNC", "max_issues_repo_head_hexsha": "e4c77250ab2b749d3014022cbb5eb9924e939993", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "opencamlib/src/algo/tsp.hpp", "max_forks_repo_name": "JohnyEngine/CNC", "max_forks_repo_head_hexsha": "e4c77250ab2b749d3014022cbb5eb9924e939993", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.255033557, "max_line_length": 124, "alphanum_fraction": 0.5936520376, "num_tokens": 1228, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.63341027059799, "lm_q1q2_score": 0.4611071260802284}}
{"text": "/*!\n * Copyright (C) tkornuta, IBM Corporation 2015-2019\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: MatrixTests.cpp\n * @Author: Tomasz Kornuta <tkornut@us.ibm.com>\n * @Date:   Nov 22, 2016\n *\n * Copyright (c) 2016, IBM Corporation. All rights reserved.\n *\n */\n\n#include <gtest/gtest.h>\n\n#include <fstream>\n// Include headers that implement a archive in simple text format\n#include <boost/archive/text_iarchive.hpp>\n#include <boost/archive/text_oarchive.hpp>\n\n// Redefine word \"public\" so every class field/method will be accessible for tests.\n#define private public\n#include <types/Tensor.hpp>\n#include <types/Matrix.hpp>\n\n/*!\n * Tests whether matrix has proper dimensions (2x5).\n */\nTEST(Tensor, Dimensions2x5) {\n\t// Default sizes of matrices.\n\tconst size_t N = 2;\n\tconst size_t M = 5;\n\tconst size_t K = 13;\n\n\tmic::types::Tensor<float> nm({N, M, K});\n\n\tASSERT_EQ(nm.dim(0), N);\n\tASSERT_EQ(nm.dim(1), M);\n\tASSERT_EQ(nm.dim(2), K);\n}\n\n\n/*!\n * Tests enumeration.\n */\nTEST(Tensor, Enumeration2x3) {\n\t// Default sizes of matrices.\n\tconst size_t N = 2;\n\tconst size_t M = 3;\n\n\tmic::types::Tensor<float> nm({N, M});\n\tnm.enumerate();\n\n//\tstd::cout << nm << std::endl;\n\n\tfor (size_t i =0; i< N*M; i++)\n\t\tASSERT_EQ(nm(i), i);\n\n/*\tfor(size_t row=0; row<N; row++) {\n\t\tfor(size_t col=0; col<M; col++)\n\t\t\tstd::cout << \" nm(\" << row << \",\" << col << \") = \" << nm({row,col});\n\t\tstd::cout << std::endl;\n\t}//: for*/\n\n\tASSERT_EQ(nm({0,0}), 0);\n\tASSERT_EQ(nm({1,0}), 1);\n\tASSERT_EQ(nm({0,1}), 2);\n\tASSERT_EQ(nm({1,1}), 3);\n\tASSERT_EQ(nm({0,2}), 4);\n\tASSERT_EQ(nm({1,2}), 5);\n\n}\n\n\n/*!\n * Tests Tensor serialization.\n */\nTEST(Tensor, Serialization) {\n\t// Default sizes of matrices.\n\tconst size_t N = 2;\n\tconst size_t M = 5;\n\tconst size_t K = 11;\n\n\tmic::types::Tensor<float> nm({N, M, K});\n\tnm.randn();\n\n\tconst char* fileName = \"saved.txt\";\n\t// Save data\n\t{\n\t\t// Create an output archive\n\t\tstd::ofstream ofs(fileName);\n\t\tboost::archive::text_oarchive ar(ofs);\n\t\t// Write data\n\t\tar & nm;\n\t\t//std::cout << \"Saved matrix = \" << nm << std::endl;\n\t}\n\n\t// Restore data\n\tmic::types::Tensor<float> restored_tensor;\n\trestored_tensor.randn();\n\n\t{\n\t\t// Create and input archive\n\t\tstd::ifstream ifs(fileName);\n\t\tboost::archive::text_iarchive ar(ifs);\n\t\t// Load data\n\t\tar & restored_tensor;\n\t\t//std::cout << \"Restored tensor = \" << restored_tensor << std::endl;\n\t}\n\n\t// Check dimensions.\n\tASSERT_EQ(nm.elements, restored_tensor.elements);\n\tASSERT_EQ(nm.dimensions.size(), restored_tensor.dimensions.size());\n\tfor (size_t i =0; i< (size_t)nm.dimensions.size(); i++)\n\t\tASSERT_EQ(nm.dimensions[i], restored_tensor.dimensions[i]);\n\n\t// Check values.\n\tfloat eps = 1e-8;\n\tfor (size_t i =0; i< (size_t)nm.size(); i++)\n\t\tEXPECT_LE(fabs(nm(i) - restored_tensor(i)), eps);\n\n}\n\n/*!\n * Tests im2col.\n */\nTEST(Tensor, Im2Col2x3) {\n\t// Default sizes of matrices.\n\tconst size_t N = 2;\n\tconst size_t M = 3;\n\n\tmic::types::Tensor<float> nm({N, M});\n\tnm.enumerate();\n\n\n}\n\nint main(int argc, char **argv) {\n    testing::InitGoogleTest(&argc, argv);\n    return RUN_ALL_TESTS();\n}\n\n\n", "meta": {"hexsha": "e5f99026eb65bb5e432282cf5a781e87aedbbadc", "size": 3559, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/types/TensorTests.cpp", "max_stars_repo_name": "kant/mi-algorithms", "max_stars_repo_head_hexsha": "7e510577f57cb5e7d36c9d2506b61395739b0bef", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/types/TensorTests.cpp", "max_issues_repo_name": "kant/mi-algorithms", "max_issues_repo_head_hexsha": "7e510577f57cb5e7d36c9d2506b61395739b0bef", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/types/TensorTests.cpp", "max_forks_repo_name": "kant/mi-algorithms", "max_forks_repo_head_hexsha": "7e510577f57cb5e7d36c9d2506b61395739b0bef", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-30T09:51:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-30T09:51:14.000Z", "avg_line_length": 22.9612903226, "max_line_length": 83, "alphanum_fraction": 0.6529924136, "num_tokens": 1035, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102636778403, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.4611071247807078}}
{"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\u00e4nkt), www.simunova.com. \n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#ifndef MTL_MATRIX_INV_INCLUDE\n#define MTL_MATRIX_INV_INCLUDE\n\n#include <boost/numeric/mtl/mtl_fwd.hpp>\n#include <boost/numeric/mtl/concept/collection.hpp>\n#include <boost/numeric/mtl/matrix/identity.hpp>\n#include <boost/numeric/mtl/operation/upper_trisolve.hpp>\n#include <boost/numeric/mtl/operation/lu.hpp>\n#include <boost/numeric/mtl/utility/exception.hpp>\n#include <boost/numeric/mtl/utility/irange.hpp>\n#include <boost/numeric/mtl/utility/tag.hpp>\n#include <boost/numeric/mtl/vector/parameter.hpp>\n#include <boost/numeric/mtl/vector/dense_vector.hpp>\n#include <boost/numeric/mtl/vector/unit_vector.hpp>\n#include <boost/numeric/mtl/interface/vpt.hpp>\n\nnamespace mtl { namespace mat {\n\nnamespace traits {\n\n    /// Return type of inv(Matrix)\n    /** Might be specialized later for the sake of efficiency **/\n    template <typename Matrix>\n    struct inv\n    {\n\ttypedef typename Collection<Matrix>::value_type    value_type;\n\ttypedef ::mtl::mat::dense2D<value_type>         type;\n    };\n\t\n} // traits\n\n/// Invert upper triangular matrix\ntemplate <typename Matrix, typename MatrixOut>\nvoid inv_upper(Matrix const& A, MatrixOut& Inv)\n{\n    vampir_trace<5019> tracer;\n    typedef typename Collection<Matrix>::value_type    value_type;\n    typedef typename Collection<Matrix>::size_type     size_type;\n   \n    const size_type N= num_rows(A);\n    MTL_DEBUG_THROW_IF(num_cols(A) != N, matrix_not_square());\n    MTL_DEBUG_THROW_IF(N != num_rows(Inv) || num_cols(A) != num_cols(Inv), incompatible_size());\n\n    Inv= math::zero(value_type());\n\n    for (size_type k= 0; k < N; ++k) {\n\tirange r(k+1);\n\ttypename mtl::ColumnInMatrix<MatrixOut>::type col_k(Inv[r][k]);\n\tupper_trisolve(A[r][r], vec::unit_vector<value_type>(k, k+1), col_k, mtl::tag::regular_diagonal());\n    }\n}\n\n\n/// Invert upper triangular matrix\ntemplate <typename Matrix>\ninline typename traits::inv<Matrix>::type \ninv_upper(Matrix const& A)\n{\n    typedef typename Collection<Matrix>::size_type     size_type;\n    const size_type N= num_rows(A);\n    typename traits::inv<Matrix>::type Inv(N, N);\n    inv_upper(A, Inv);\n    return Inv;\n}\n\n#if 0\n/// Invert lower triangular matrix\ntemplate <typename Matrix, typename MatrixOut>\ninline void inv_lower(Matrix const& A, MatrixOut& Inv)\n{\n    vampir_trace<5020> tracer;\n    typedef typename Collection<Matrix>::value_type    value_type;\n    typedef typename Collection<Matrix>::size_type     size_type;\n\n    const size_type N= num_rows(A);\n    MTL_DEBUG_THROW_IF(num_cols(A) != N, matrix_not_square());\n    MTL_DEBUG_THROW_IF(N != num_rows(Inv) || num_cols(A) != num_cols(Inv), incompatible_size());\n\n    Inv= math::zero(value_type());\n\n    for (size_type k= 0; k < N; ++k) {\n\tirange r(k, N);\n\ttypename mtl::ColumnInMatrix<MatrixOut>::type col_k(Inv[r][k]);\n\tlower_trisolve(A[r][r], unit_vector<value_type>(0, N-k), col_k, mtl::tag::regular_diagonal());\n    }\n}\n\ntemplate <typename Matrix>\ntypename traits::inv<Matrix>::type\ninline inv_lower(Matrix const& A)\n{\n    typedef typename Collection<Matrix>::size_type     size_type;\n    const size_type N= num_rows(A);\n    typename traits::inv<Matrix>::type Inv(N, N);\n    inv_lower(A, Inv);\n    return Inv;\n}\n#endif\n\n#if 1\n/// Invert lower triangular matrix\ntemplate <typename Matrix>\ntypename traits::inv<Matrix>::type\ninline inv_lower(Matrix const& A)\n{\n    vampir_trace<5020> tracer;\n    Matrix T(trans(A)); // Shouldn't be needed\n    return typename traits::inv<Matrix>::type(trans(inv_upper(T)));\n}\n#endif\n\n\n\n\n/// Invert matrix\n/** Uses pivoting LU factorization and triangular inversion\n    \\sa \\ref lu, \\ref inv_upper, \\ref inv_lower **/\ntemplate <typename Matrix, typename MatrixOut>\ninline void inv(Matrix const& A, MatrixOut& Inv)\n{\n    vampir_trace<5021> tracer;\n    typedef typename Collection<Matrix>::size_type     size_type;\n    typedef typename Collection<Matrix>::value_type    value_type;\n    typedef typename traits::inv<Matrix>::type         result_type;\n\n    const size_type N= num_rows(A);\n    MTL_THROW_IF(num_cols(A) != num_cols(A), matrix_not_square());\n    MTL_DEBUG_THROW_IF(N != num_rows(Inv) || num_cols(A) != num_cols(Inv), incompatible_size());\n\n    if (N == 1) {\n\tInv[0][0]= value_type(1) / A[0][0];\n\treturn;\n    }\n\n    result_type                    PLU(A);\n    mtl::dense_vector<size_type, vec::parameters<> >   Pv(num_rows(A));\n\n    lu(PLU, Pv);\n    result_type  PU(upper(PLU)), PL(strict_lower(PLU));\n    for (size_type i= 0; i < num_rows(A); i++)\n\tPL[i][i]= value_type(1);\n\n    Inv= inv_upper(PU) * inv_lower(PL) * permutation(Pv);\n}\n\ntemplate <typename Matrix>\ntypename traits::inv<Matrix>::type\ninline inv(Matrix const& A)\n{\n    typedef typename Collection<Matrix>::size_type     size_type;\n    const size_type N= num_rows(A);\n    typename traits::inv<Matrix>::type Inv(N, N);\n    inv(A, Inv);\n    return Inv;\n}\n\n}} // namespace mtl::matrix\n\n#endif // MTL_MATRIX_INV_INCLUDE\n", "meta": {"hexsha": "edb62a0ef18043afc87834c30daf45bacf0402ef", "size": 5306, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/mtl/operation/inv.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/inv.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/inv.hpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 30.8488372093, "max_line_length": 100, "alphanum_fraction": 0.6973237844, "num_tokens": 1410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059775, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.46110712104252927}}
{"text": "/* Main.cpp (exercise 1.5 problems 1-5)\nDescription:\n\t*Solutions to problems 1-5.\n*/\n\n#define _SILENCE_ALL_CXX17_DEPRECATION_WARNINGS\n\n#include <boost\\assign.hpp>\n#include <boost\\date_time.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <algorithm>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include <tuple>\n#include <vector>\n#include \"Builder.hpp\"\n#include \"Calculator.hpp\"\n#include \"Circle.hpp\"\n#include \"CircleMonitorBuilder.hpp\"\n#include \"CircleTVBuilder.hpp\"\n#include \"Exception.hpp\"\n#include \"Functions-1.hpp\"\n#include \"Functions-3.hpp\"\n#include \"Functions-4.hpp\"\n#include \"LineMonitorBuilder.hpp\"\n#include \"LineTVBuilder.hpp\"\n#include \"Monitor.hpp\"\n#include \"SizeExcept.hpp\"\n#include \"TV.hpp\"\n\nint main()\n{\n\t/* 1.5.1 */\n\t// a) Use std:tuple<> to emulate a Person class (std::tuple<Name, Address, DateOfBirth>)\n\tPerson personA, personB, personC;\n\t// Set the name of each person:\n\tstd::get<0>(personA) = \"A\";\n\tstd::get<0>(personB) = \"B\";\n\tstd::get<0>(personC) = \"C\";\n\t// Set the address of each person:\n\tstd::get<1>(personA) = \"123 Main St\";\n\tstd::get<1>(personB) = \"124 Main St\";\n\tstd::get<1>(personC) = \"125 Main St\";\n\t// Set the date of birth for each person:\n\tstd::get<2>(personA) = std::move(boost::gregorian::from_string(\"2016-3-14\"));\n\tstd::get<2>(personB) = std::move(boost::gregorian::from_string(\"2017-3-14\"));\n\tstd::get<2>(personC) = std::move(boost::gregorian::from_string(\"2018-3-14\"));\n\t// c) Create a list/vector of Persons and add instances:\n\tstd::vector<Person> persons = { personA, personB, personC };\n\t// d) Test the sorting function:\n\t// Display unsorted persons vector:\n\tstd::cout << \"Unsorted persons vector: \" << std::endl;\n\tstd::for_each(persons.begin(), persons.end(), printPerson);\n\t// Sort and display sorted persons vector (by Name ascending):\n\tSortPersons<0>(persons, false);\n\tstd::cout << \"Sorted persons vector (by Name ascending): \" << std::endl;\n\tstd::for_each(persons.begin(), persons.end(), printPerson);\n\t// Sort and display sorted persons vector (by Name descending):\n\tSortPersons<0>(persons, true);\n\tstd::cout << \"Sorted persons vector (by Name descending): \" << std::endl;\n\tstd::for_each(persons.begin(), persons.end(), printPerson);\n\t// Sort and display sorted persons vector (by Date ascending):\n\tSortPersons<2>(persons, false);\n\tstd::cout << \"Sorted persons vector (by Date ascending): \" << std::endl;\n\tstd::for_each(persons.begin(), persons.end(), printPerson);\n\t// Sort and display sorted persons vector (by Date descending):\n\tSortPersons<2>(persons, true);\n\tstd::cout << \"Sorted persons vector (by Date descending): \" << std::endl;\n\tstd::for_each(persons.begin(), persons.end(), printPerson);\n\n\t/* 1.5.2 */\n\t// b) Test Calculator struct's static functions on tuples of varying sizes:\n\tstd::tuple<double, double> pair = std::make_tuple<double, double>(1.0, 2.0);\n\tstd::tuple<double, double, double> triplet = std::make_tuple<double, double, double>(1.0, 2.0, 3.0);\n\tstd::tuple<double, double, double, double> quadruplet = std::make_tuple<double, double, double, double>(1.0, 2.0, 3.0, 4.0);\n\tstd::cout << \"Pair { 1.0, 2.0 }\" << std::endl;\n\tstd::cout << \"Max: \" << Calculator<double, std::tuple<double, double>, 2>::maximum(pair) << std::endl;\n\tstd::cout << \"Sum: \" << Calculator<double, std::tuple<double, double>, 2>::sum(pair) << std::endl;\n\tstd::cout << \"Avg: \" << Calculator<double, std::tuple<double, double>, 2>::average(pair) << std::endl;\n\tstd::cout << \"Triplet { 1.0, 2.0, 3.0 }\" << std::endl;\n\tstd::cout << \"Max: \" << Calculator<double, std::tuple<double, double, double>, 3>::maximum(triplet) << std::endl;\n\tstd::cout << \"Sum: \" << Calculator<double, std::tuple<double, double, double>, 3>::sum(triplet) << std::endl;\n\tstd::cout << \"Avg: \" << Calculator<double, std::tuple<double, double, double>, 3>::average(triplet) << std::endl;\n\tstd::cout << \"Quadruplet { 1.0, 2.0, 3.0, 4.0 }\" << std::endl;\n\tstd::cout << \"Max: \" << Calculator<double, std::tuple<double, double, double, double>, 4>::maximum(quadruplet) << std::endl;\n\tstd::cout << \"Sum: \" << Calculator<double, std::tuple<double, double, double, double>, 4>::sum(quadruplet) << std::endl;\n\tstd::cout << \"Avg: \" << Calculator<double, std::tuple<double, double, double, double>, 4>::average(quadruplet) << std::endl;\n\t// c) Test sum and average functions with tuple of std::complex<int> type:\n\tstd::tuple<std::complex<int>, std::complex<int>> complexPair = std::make_tuple<std::complex<int>, std::complex<int>>(std::complex<int>(4, 3), std::complex<int>(5, 6));\n\tstd::cout << \"Complex Tuple {(4,3), (5,6)}: \" << std::endl;\n\tstd::cout << \"Sum: \" << Calculator<std::complex<int>, std::tuple<std::complex<int>, std::complex<int>>, 2>::sum(complexPair) << std::endl;\n\tstd::cout << \"Avg: \" << Calculator<std::complex<int>, std::tuple<std::complex<int>, std::complex<int>>, 2>::average(complexPair) << std::endl;\n\t\n\t/* 1.5.3: */\n\t// b) Test the function implemented in a):\n\tstd::vector<double> geyserDataVector{ 78,74,68,76,80,84,50, 93,55,76,58,74,75 };\n\tdouble mean, meanDev, range, stdDev, var;\n\tboost::numeric::ublas::vector<double, std::vector<double>> geyserData(geyserDataVector);\n\tstd::tuple<double, double, double, double, double> statProperties = GetStatisticalProperties(geyserData);\n\tstd::tie(mean, std::ignore, std::ignore, std::ignore, std::ignore) = statProperties;\n\tstd::tie(std::ignore, meanDev, std::ignore, std::ignore, std::ignore) = statProperties;\n\tstd::tie(std::ignore, std::ignore, range, std::ignore, std::ignore) = statProperties;\n\tstd::tie(std::ignore, std::ignore, std::ignore, var, std::ignore) = statProperties;\n\tstd::tie(std::ignore, std::ignore, std::ignore, std::ignore, stdDev) = statProperties;\n\tstd::cout << \"Geyser data { 78,74,68,76,80,84,50,93,55,76,58,74,75 } statistical properties: \" << std::endl;\n\tstd::cout << \"Mean :\" << mean << \", Mean Deviation: \" << meanDev << std::endl;\n\tstd::cout << \"Range:\" << range << \", Standard Deviation: \" << stdDev << \", Variance: \" << var << std::endl;\n\t// c) Sort the vector, then get the median and mode of the dataset:\n\tstd::sort(geyserData.begin(), geyserData.end());\n\tdouble med = median<boost::numeric::ublas::vector, double>(geyserData);\n\tdouble mod = mode<boost::numeric::ublas::vector, double>(geyserData);\n\tstd::cout << \"Median: \" << med << \", Mode: \" << mod << std::endl;\n\t/* 1.5.4 */\n\t//// TODO: ensure relative error and abs error are correct.\n\t// a) Test the findIndex() procedure that returns index where v[i] <= x < v[i + 1] for given vector v and passed value x:\n\tstd::vector<double> temp1 { 1, 2, 2, 3 };\n\tstd::vector<double> temp2 { 1, 1, 1, 3 };\n\tstd::vector<double> temp3 { 1, 1, 1, 1 };\n\tstd::size_t index1 = findIndex<std::vector, double>(temp1, 2);\n\tstd::size_t index2 = findIndex<std::vector, double>(temp2, 2);\n\tstd::size_t index3 = findIndex<std::vector, double>(temp3, 2);\n\tstd::cout << \"For v_1 = {1, 2, 2, 3}, index i where v[i] <= 2 < v[i + 1]: \" << index1 << std::endl;\n\tstd::cout << \"For v_2 = {1, 1, 1, 3}, index i where v[i] <= 2 < v[i + 1]: \" << index2 << std::endl;\n\tstd::cout << \"For v_3 = {1, 1, 1, 1}, index i where v[i] <= 2 < v[i + 1]: \" << index3 <<\" (i.e. not found)\" << std::endl;\n\t// b) Test the maximum error finding adapter for above vectors:\n\tstd::pair<double, std::size_t> mRelError = maxError<std::vector, double>(temp1, temp2, std::make_pair<std::size_t, std::size_t>(0, 3), true);\n\tstd::cout << \"For v_1 and v_2: \" << std::endl;\n\tstd::cout << \"Maximum relative error: \" << std::get<0>(mRelError) << \" at index \" << std::get<1>(mRelError) << std::endl;\n\tstd::pair<double, std::size_t> mAbsError = maxError<std::vector, double>(temp1, temp2, std::make_pair<std::size_t, std::size_t>(0, 3), false);\n\tstd::cout << \"Maximum absolute error: \" << std::get<0>(mAbsError) << \" at index \" << std::get<1>(mAbsError) << std::endl;\n\t\n\t/* 1.5.5 */\n\t// a) Instantiate circle and line objects and display using input-output devices:\n\tCircle circ(1.0, 2.0);\n\tLine lin(Point(1.0, 2.0), Point(2.0, 3.0));\n\tTV tv_io;\n\tMonitor mon;\n\ttv_io << circ;\n\tmon << circ;\n\ttv_io << lin;\n\tmon << lin;\n\t// b) Configure shapes for input-output devices with builder objects:\n\tCircleMonitorBuilder cm;\n\tCircleTVBuilder cTV;\n\tLineMonitorBuilder lm;\n\tLineTVBuilder lTV;\n\tstd::cout << \"Builder generated combinations of Circle/Line objects with Monitor/TV objects:\" << std::endl;\n\tstd::tuple<ShapePointer, IODevicePointer> output = cm.getProduct();\n\toutput = cTV.getProduct();\n\tstd::get<0>(output)->display(*std::get<1>(output));\n\toutput = lm.getProduct();\n\tstd::get<0>(output)->display(*std::get<1>(output));\n\toutput = lTV.getProduct();\n\tstd::get<0>(output)->display(*std::get<1>(output));\n\n\tsystem(\"pause\");\n\n\treturn 0;\n}", "meta": {"hexsha": "1facc028b050506a021a23c218bdefcd36691086", "size": 8644, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Advanced C++ Course/Benjamin Rutan HW 1 Submission/1.5/1.5/Main.cpp", "max_stars_repo_name": "BRutan/Cpp", "max_stars_repo_head_hexsha": "8acbc6c341f49d6d83168ccd5ba49bd6824214f9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Advanced C++ Course/Benjamin Rutan HW 1 Submission/1.5/1.5/Main.cpp", "max_issues_repo_name": "BRutan/Cpp", "max_issues_repo_head_hexsha": "8acbc6c341f49d6d83168ccd5ba49bd6824214f9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Advanced C++ Course/Benjamin Rutan HW 1 Submission/1.5/1.5/Main.cpp", "max_forks_repo_name": "BRutan/Cpp", "max_forks_repo_head_hexsha": "8acbc6c341f49d6d83168ccd5ba49bd6824214f9", "max_forks_repo_licenses": ["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.025, "max_line_length": 168, "alphanum_fraction": 0.6638130495, "num_tokens": 2674, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.4611071210425292}}
{"text": "/*****************************************************************************\n*\n* Rokko: Integrated Interface for libraries of eigenvalue decomposition\n*\n* Copyright (C) 2012-2015 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#define ROKKO_ENABLE_TIMER\n\n#include <mpi.h>\n#include <iostream>\n#include <fstream>\n\n#include <rokko/solver.hpp>\n#include <rokko/grid.hpp>\n#include <rokko/distributed_matrix.hpp>\n#include <rokko/localized_matrix.hpp>\n#include <rokko/localized_vector.hpp>\n\n#include <rokko/collective.hpp>\n\n#include <rokko/utility/heisenberg_hamiltonian_mpi.hpp>\n#include <rokko/utility/sort_eigenpairs.hpp>\n#include <rokko/config.h>\n#include <rokko/utility/timer.hpp>\n\n#include <boost/lexical_cast.hpp>\n#include <boost/asio.hpp>\n\nint main(int argc, char *argv[]) {\n  MPI_Init(&argc, &argv);\n  //typedef rokko::matrix_row_major matrix_major;\n  typedef rokko::matrix_col_major matrix_major;\n\n  if (argc <= 1) {\n    std::cerr << \"error: \" << argv[0] << \" solver_name\" << std::endl;\n    MPI_Abort(MPI_COMM_WORLD, 34);\n  }\n  rokko::timer timer;\n  timer.registrate( 1, \"diagonalize\");\n  std::string solver_name(argv[1]);\n\n  int L = 12;\n  std::vector<std::pair<int, int> > lattice;\n  for (int i=0; i<L-1; ++i) {\n    lattice.push_back(std::make_pair(i, i+1));\n  }\n  \n  std::cout << \"L=\" << L << std::endl;\n\n  int dim = 1 << L;\n  std::cout << \"dim=\" << dim << std::endl;\n  rokko::parallel_dense_solver solver(solver_name);\n  solver.initialize(argc, argv);\n\n  MPI_Comm comm = MPI_COMM_WORLD;\n  rokko::grid g(comm);\n  int myrank = g.get_myrank();\n  int nprocs = g.get_nprocs();\n\n  const int root = 0;\n\n  rokko::distributed_matrix<double, matrix_major> mat(dim, dim, g, solver);\n  rokko::heisenberg_hamiltonian::generate(L, lattice, mat);\n  std::cout << \"finished generate\" << std::endl;\n\n  rokko::localized_vector<double> w(dim);\n  rokko::distributed_matrix<double, matrix_major> Z(dim, dim, g, solver);\n\n  for (int count=0; count<1; ++count) {\n    try {\n      solver.diagonalize(mat, w, Z);\n    }\n\n    catch (const char *e) {\n      std::cout << \"Exception : \" << e << std::endl;\n      MPI_Abort(MPI_COMM_WORLD, 22);\n    }\n  }\n  std::cout << \"finished eigensolver\" << std::endl;\n\n  /*\n  // gather of eigenvectors\n  rokko::localized_matrix<double, matrix_major> eigvec_global;\n  rokko::localized_matrix<double, matrix_major> eigvec_sorted(dim, dim);\n  rokko::localized_vector<double> eigval_sorted(dim);\n  rokko::gather(Z, eigvec_global, root);\n  Z.print();\n  //if (myrank == root) {\n  //  std::cout << \"eigvec:\" << std::endl << eigvec_global << std::endl;\n  //}\n\n  std::cout.precision(20);\n  */\n\n  /*\n  std::cout << \"w=\" << std::endl;\n  for (int i=0; i<dim; ++i) {\n    std::cout << w[i] << \" \";\n  }\n  std::cout << std::endl;\n  */\n\n  if (myrank == 0) {\n\n    std::cout << \"num_procs = \" << nprocs << std::endl;\n#ifdef _OPENMP_\n    std::cout << \"num_threads = \" << omp_get_max_threads() << std::endl;\n    //std::cout << \"num_threads = \" << mkl_get_num_threads() << std::endl;\n#endif\n    std::cout << \"solver_name = \" << solver_name << std::endl;\n    std::cout << \"matrix = frank\" << std::endl;\n    std::cout << \"dim = \" << dim << std::endl;\n    std::cout << \"time = \" << timer.get_average(1) << std::endl;\n    std::cout << \"rokko_version = \" << ROKKO_VERSION << std::endl;\n    std::cout << \"hostname = \" << boost::asio::ip::host_name() << std::endl;\n    std::time_t now = std::time(0);\n    std::cout << \"date = \" << ctime(&now)<< std::endl;\n  }\n\n  solver.finalize();\n  MPI_Finalize();\n  return 0;\n}\n", "meta": {"hexsha": "90e12061480994a8c9e34230fa5bc761b1518fd5", "size": 3738, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "benchmark/dense/heisenberg_dense_mpi.cpp", "max_stars_repo_name": "wistaria/rokko", "max_stars_repo_head_hexsha": "7cd9d5155e82f038039a46c1dc8f382b3fe7e2b7", "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": "benchmark/dense/heisenberg_dense_mpi.cpp", "max_issues_repo_name": "wistaria/rokko", "max_issues_repo_head_hexsha": "7cd9d5155e82f038039a46c1dc8f382b3fe7e2b7", "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": "benchmark/dense/heisenberg_dense_mpi.cpp", "max_forks_repo_name": "wistaria/rokko", "max_forks_repo_head_hexsha": "7cd9d5155e82f038039a46c1dc8f382b3fe7e2b7", "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.976744186, "max_line_length": 79, "alphanum_fraction": 0.6126270733, "num_tokens": 1100, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.4611071210425292}}
{"text": "//////////////////////////////////////////////////////////////////////////////\n///   Copyright 2003 and onward LASMEA UMR 6602 CNRS/U.B.P Clermont-Ferrand\n///   Copyright 2009 and onward LRI    UMR 8623 CNRS/Univ Paris Sud XI\n///\n///          Distributed under the Boost Software License, Version 1.0\n///                 See accompanying file LICENSE.txt or copy at\n///                     http://www.boost.org/LICENSE_1_0.txt\n//////////////////////////////////////////////////////////////////////////////\n#ifndef NT2_TOOLBOX_IEEE_FUNCTION_SIMD_COMMON_NEXT_HPP_INCLUDED\n#define NT2_TOOLBOX_IEEE_FUNCTION_SIMD_COMMON_NEXT_HPP_INCLUDED\n#include <nt2/sdk/constant/infinites.hpp>\n#include <nt2/sdk/constant/real.hpp>\n#include <nt2/sdk/meta/as_integer.hpp>\n#include <nt2/sdk/constant/properties.hpp>\n#include <nt2/sdk/constant/digits.hpp>\n#include <nt2/sdk/constant/eps_related.hpp>\n#include <boost/fusion/tuple.hpp>\n#include <nt2/sdk/meta/strip.hpp>\n#include <nt2/include/functions/seladd.hpp>\n#include <nt2/include/functions/select.hpp>\n#include <nt2/include/functions/fast_frexp.hpp>\n#include <nt2/include/functions/fast_ldexp.hpp>\n#include <nt2/include/functions/is_eqz.hpp>\n#include <nt2/include/functions/is_finite.hpp>\n\n\n\n/////////////////////////////////////////////////////////////////////////////\n// Implementation when type A0 is arithmetic_\n/////////////////////////////////////////////////////////////////////////////\nNT2_REGISTER_DISPATCH(tag::next_, tag::cpu_,\n                       (A0)(X),\n                       ((simd_<arithmetic_<A0>,X>))\n                      );\n\nnamespace nt2 { namespace ext\n{\n  template<class X, class Dummy>\n  struct call<tag::next_(tag::simd_<tag::arithmetic_, X> ),\n              tag::cpu_, Dummy> : callable\n  {\n    template<class Sig> struct result;\n    template<class This,class A0>\n    struct result<This(A0)> : meta::strip<A0>{};//\n\n    NT2_FUNCTOR_CALL(1)\n    {\n      return a0+One<A0>();\n    }\n  };\n} }\n\n/////////////////////////////////////////////////////////////////////////////\n// Implementation when type A0 is real_\n/////////////////////////////////////////////////////////////////////////////\nNT2_REGISTER_DISPATCH(tag::next_, tag::cpu_,\n                       (A0)(X),\n                       ((simd_<real_<A0>,X>))\n                      );\n\nnamespace nt2 { namespace ext\n{\n  template<class X, class Dummy>\n  struct call<tag::next_(tag::simd_<tag::real_, X> ),\n              tag::cpu_, Dummy> : callable\n  {\n    template<class Sig> struct result;\n    template<class This,class A0>\n    struct result<This(A0)> : meta::strip<A0>{};//\n\n    NT2_FUNCTOR_CALL(1)\n    {\n      typedef typename meta::as_integer<A0, signed>::type itype;\n      A0 m;\n      itype expon;\n      boost::fusion::tie(m, expon) = fast_frexp(a0);\n      expon =  seladd(is_equal(m, Mhalf<A0>()), expon, Mone<itype>());\n      A0 diff =  fast_ldexp(One<A0>(), expon-Nbdigits<A0>());\n      diff = b_and(sel(is_eqz(diff)||is_eqz(a0),  Mindenormal<A0>(), diff), is_finite(a0));\n//       std::cout << \"diff  \"<< diff << std::endl;\n//       std::cout << \"a0    \"<< a0   << std::endl;\n      return sel(is_equal(a0, Minf<A0>()), Valmin<A0>(), a0+diff);\n    }\n  };\n} }\n\n#endif\n// modified by jt the 04/01/2011", "meta": {"hexsha": "6bbe5bd179fed89d2148f9ece16e651ac05657e1", "size": 3217, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/ieee/include/nt2/toolbox/ieee/function/simd/common/next.hpp", "max_stars_repo_name": "brycelelbach/nt2", "max_stars_repo_head_hexsha": "73d7e8dd390fa4c8d251c6451acdae65def70e0b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-24T03:35:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T03:35:10.000Z", "max_issues_repo_path": "modules/ieee/include/nt2/toolbox/ieee/function/simd/common/next.hpp", "max_issues_repo_name": "brycelelbach/nt2", "max_issues_repo_head_hexsha": "73d7e8dd390fa4c8d251c6451acdae65def70e0b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/ieee/include/nt2/toolbox/ieee/function/simd/common/next.hpp", "max_forks_repo_name": "brycelelbach/nt2", "max_forks_repo_head_hexsha": "73d7e8dd390fa4c8d251c6451acdae65def70e0b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.5568181818, "max_line_length": 91, "alphanum_fraction": 0.5399440472, "num_tokens": 768, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754371026368, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.4611071135661721}}
{"text": "/******************************************************************************\n *\n * \tfilename   : Camera.h\n *  author     : Do Won Cha\n *  content    : Container class to output a buffer to image.\n *\n ******************************************************************************/\n\n#pragma once\n#ifndef _RAY_CAMERA_\n#define _RAY_CAMERA_\n\n#include <Eigen/Core>\n#include <cassert>\n\n#include \"ray.hpp\"\n#include \"../utility.h\"\n\nnamespace raytracer\n{\n\nusing namespace Eigen;\n\nclass Camera\n{\npublic:\n  Camera() :\n    position  (0.0f, 0.0f, 0.0f),\n    target_    (0.0f, 0.0f, -1.0f),\n    right_     (1.0f, 0.0f, 0.0f),\n    up_        (0.0f, 1.0f, 0.0f),\n    forward_   (0.0f, 0.0f, 1.0f),\n    l(-0.1f), r(0.1f), t(0.1f), b(-0.1f), d(0.1f)\n  {\n  }\n\n  Camera(int width, int height) :\n    position  (0.0f, 0.0f, 0.0f),\n    target_    (0.0f, 0.0f, -1.0f),\n    right_     (1.0f, 0.0f, 0.0f),\n    up_        (0.0f, 1.0f, 0.0f),\n    forward_   (0.0f, 0.0f, 1.0f),\n    l(-0.1f), r(0.1f), t(0.1f), b(-0.1f), d(0.1f),\n    screen_width_(width),\n    screen_height_(height)\n  {}\n\n  // default offset is to the center of the pixel\n  Ray GetRayFromEye(int x, int y) const\n  {\n    assert(x < screen_width_);\n    assert(y < screen_height_);\n\n  \tfloat invW = 1.0f / screen_width_;\n  \tfloat invH = 1.0f / screen_height_;\n\n  \tfloat u = l + (r - l) * ((float)x + 0.5f) * invW;\n  \tfloat v = b + (t - b) * ((float)y + 0.5f) * invH;\n\n    // NOTE: Had to change up calculation to negative to set y to bottom?\n    // forward_ is also negative\n  \tVector3f dir = ((right_ * u) - (up_ * v) - (forward_ * d)).normalized();\n\n  \treturn Ray(position, dir);\n  }\n\n  //\n  Ray GetRayFromEye(int x, int y, float offsetx, float offsety) const\n  {\n    assert( x < screen_width_ );\n    assert( y < screen_height_ );\n\n    offsetx = Utility::clamp(0.0f, offsetx, 1.0f);\n    offsety = Utility::clamp(0.0f, offsety, 1.0f);\n\n    float invW = 1.0f / screen_width_;\n    float invH = 1.0f / screen_height_;\n\n    float u = l + (r - l) * (x + offsetx) * invW;\n  \tfloat v = b + (t - b) * (y + offsety) * invH;\n\n    Vector3f dir = ((right_ * u) - (up_ * v) - (forward_ * d)).normalized();\n\n  \treturn Ray(position, dir);\n  }\n\n  void resize(int width, int height)\n  {\n    screen_width_ = width;\n    screen_height_ = height;\n  }\n\n  int screen_width()  const { return screen_width_; }\n  int screen_height() const { return screen_height_; }\n\nprivate:\n  Vector3f position;                // position vector\n  Vector3f target_;                  // What are we looking at\n  Vector3f forward_;                 // forward_ vector\n  Vector3f up_;                      // up_ vector, typically y-axis\n  Vector3f right_;                   // right_ vector\n  float l, r, t, b, d;              // Viewport constants\n  int screen_width_, screen_height_;    // Resolution of camera\n};\n\n}     // end of namespace raytracer\n\n#endif // _RAY_CAMERA_\n", "meta": {"hexsha": "bc4bfc9c2dad7f2b4a6fde6b6575c11b199b55cc", "size": 2871, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "PA4/src/primitives/camera.hpp", "max_stars_repo_name": "dowoncha/COMP575", "max_stars_repo_head_hexsha": "6e48bdd80cb1a3e677c07655640efa941325e59c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PA4/src/primitives/camera.hpp", "max_issues_repo_name": "dowoncha/COMP575", "max_issues_repo_head_hexsha": "6e48bdd80cb1a3e677c07655640efa941325e59c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PA4/src/primitives/camera.hpp", "max_forks_repo_name": "dowoncha/COMP575", "max_forks_repo_head_hexsha": "6e48bdd80cb1a3e677c07655640efa941325e59c", "max_forks_repo_licenses": ["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.3394495413, "max_line_length": 80, "alphanum_fraction": 0.5430163706, "num_tokens": 951, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754371026367, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.461107113566172}}
{"text": "///////////////////////////////////////////////////////////////\n//  Copyright 2011 John Maddock. Distributed under the Boost\n//  Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_\n\n#define BOOST_MATH_MAX_ROOT_ITERATION_POLICY 750\n#define BOOST_MATH_PROMOTE_DOUBLE_POLICY false\n\n#if !defined(TEST_MPFR) && !defined(TEST_MPREAL) && !defined(TEST_MPF) && !defined(TEST_MPREAL) \\\n   && !defined(TEST_CPP_DEC_FLOAT) && !defined(TEST_MPFR_CLASS) && !defined(TEST_FLOAT) && !defined(TEST_CPP_BIN_FLOAT)\n#  define TEST_MPFR\n#  define TEST_MPF\n#  define TEST_CPP_DEC_FLOAT\n#  define TEST_CPP_BIN_FLOAT\n//#  define TEST_MPFR_CLASS\n//#  define TEST_MPREAL\n#  define TEST_FLOAT\n#endif\n\n#ifdef TEST_FLOAT\n#include \"arithmetic_backend.hpp\"\n#endif\n#ifdef TEST_MPFR_CLASS\n#include <boost/math/bindings/mpfr.hpp>\n#endif\n#ifdef TEST_MPFR\n#include <boost/multiprecision/mpfr.hpp>\n#endif\n#ifdef TEST_MPREAL\n#include <boost/math/bindings/mpreal.hpp>\n#endif\n#ifdef TEST_MPF\n#include <boost/multiprecision/gmp.hpp>\n#endif\n#ifdef TEST_CPP_DEC_FLOAT\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#endif\n#ifdef TEST_CPP_BIN_FLOAT\n#include <boost/multiprecision/cpp_bin_float.hpp>\n#include <boost/multiprecision/mpfr.hpp>\n#endif\n#include <boost/math/special_functions/bessel.hpp>\n#include <boost/math/tools/rational.hpp>\n#include <boost/math/distributions/non_central_t.hpp>\n#include <libs/math/test/table_type.hpp>\n#include <boost/chrono.hpp>\n#include <boost/array.hpp>\n#include <boost/thread.hpp>\n\ntemplate <class Real>\nReal test_bessel();\n\ntemplate <class Clock>\nstruct stopwatch\n{\n   typedef typename Clock::duration duration;\n   stopwatch()\n   {\n      m_start = Clock::now();\n   }\n   duration elapsed()\n   {\n      return Clock::now() - m_start;\n   }\n   void reset()\n   {\n      m_start = Clock::now();\n   }\n\nprivate:\n   typename Clock::time_point m_start;\n};\n\ntemplate <class Real>\nReal test_bessel()\n{\n   try{\n#  define T double\n#  define SC_(x) x\n#  include \"libs/math/test/bessel_i_int_data.ipp\"\n#  include \"libs/math/test/bessel_i_data.ipp\"\n\n      Real r;\n\n      for(unsigned i = 0; i < bessel_i_int_data.size(); ++i)\n      {\n         r += boost::math::cyl_bessel_i(Real(bessel_i_int_data[i][0]), Real(bessel_i_int_data[i][1]));\n      }\n      for(unsigned i = 0; i < bessel_i_data.size(); ++i)\n      {\n         r += boost::math::cyl_bessel_i(Real(bessel_i_data[i][0]), Real(bessel_i_data[i][1]));\n      }\n\n#include \"libs/math/test/bessel_j_int_data.ipp\"\n      for(unsigned i = 0; i < bessel_j_int_data.size(); ++i)\n      {\n         r += boost::math::cyl_bessel_j(Real(bessel_j_int_data[i][0]), Real(bessel_j_int_data[i][1]));\n      }\n\n#include \"libs/math/test/bessel_j_data.ipp\"\n      for(unsigned i = 0; i < bessel_j_data.size(); ++i)\n      {\n         r += boost::math::cyl_bessel_j(Real(bessel_j_data[i][0]), Real(bessel_j_data[i][1]));\n      }\n\n#include \"libs/math/test/bessel_j_large_data.ipp\"\n      for(unsigned i = 0; i < bessel_j_large_data.size(); ++i)\n      {\n         r += boost::math::cyl_bessel_j(Real(bessel_j_large_data[i][0]), Real(bessel_j_large_data[i][1]));\n      }\n\n#include \"libs/math/test/sph_bessel_data.ipp\"\n      for(unsigned i = 0; i < sph_bessel_data.size(); ++i)\n      {\n         r += boost::math::sph_bessel(static_cast<unsigned>(sph_bessel_data[i][0]), Real(sph_bessel_data[i][1]));\n      }\n\n      return r;\n   }\n   catch(const std::exception& e)\n   {\n      std::cout << e.what() << std::endl;\n   }\n   return 0;\n}\n\ntemplate <class Real>\nReal test_polynomial()\n{\n   static const unsigned t[] = {\n      2, 3, 4, 5, 6, 7, 8 };\n   Real result = 0;\n   for(Real k = 2; k < 1000; ++k)\n      result += boost::math::tools::evaluate_polynomial(t, k);\n\n   return result;\n}\n\ntemplate <class Real>\nReal test_nct()\n{\n#define T double\n#include \"libs/math/test/nct.ipp\"\n\n   Real result = 0;\n   for(unsigned i = 0; i < nct.size(); ++i)\n   {\n      try{\n         result += quantile(boost::math::non_central_t_distribution<Real>(nct[i][0], nct[i][1]), nct[i][3]);\n         result += cdf(boost::math::non_central_t_distribution<Real>(nct[i][0], nct[i][1]), nct[i][2]);\n      }\n      catch(const std::exception&)\n      {}\n   }\n   return result;\n}\n\nextern unsigned allocation_count;\n\ntemplate <class Real>\nvoid basic_allocation_test(const char* name, Real x)\n{\n   static const unsigned a[] = { 2, 3, 4, 5, 6, 7, 8 };\n   allocation_count = 0;\n   Real result = (((((a[6] * x + a[5]) * x + a[4]) * x + a[3]) * x + a[2]) * x + a[1]) * x + a[0];\n   std::cout << \"Allocation count for type \" << name << \" = \" << allocation_count << std::endl;\n}\n\ntemplate <class Real>\nvoid poly_allocation_test(const char* name, Real x)\n{\n   static const unsigned a[] = { 2, 3, 4, 5, 6, 7, 8 };\n   allocation_count = 0;\n   Real result = boost::math::tools::evaluate_polynomial(a, x);\n   std::cout << \"Allocation count for type \" << name << \" = \" << allocation_count << std::endl;\n}\n\ntemplate <class Real>\nvoid time_proc(const char* name, Real (*proc)(), unsigned threads = 1)\n{\n   try{\n      static Real total = 0;\n      allocation_count = 0;\n      boost::chrono::duration<double> time;\n      stopwatch<boost::chrono::high_resolution_clock> c;\n      total += proc();\n      time = c.elapsed();\n      std::cout << \"Time for \" << name << \" = \" << time << std::endl;\n      std::cout << \"Total allocations for \" << name << \" = \" << allocation_count << std::endl;\n\n      for(unsigned thread_count = 1; thread_count < threads; ++thread_count)\n      {\n         c.reset();\n         boost::thread_group g;\n         for(unsigned i = 0; i <= thread_count; ++i)\n            g.create_thread(proc);\n         g.join_all();\n         time = c.elapsed();\n         std::cout << \"Time for \" << name << \" (\" << (thread_count + 1) << \" threads) = \" << time << std::endl;\n         std::cout << \"Total allocations for \" << name << \" = \" << allocation_count << std::endl;\n      }\n   }\n   catch(const std::exception& e)\n   {\n      std::cout << e.what() << std::endl;\n   }\n}\n\nusing namespace boost::multiprecision;\n\nvoid basic_tests();\nvoid bessel_tests();\nvoid poly_tests();\nvoid nct_tests();\n", "meta": {"hexsha": "4b056e1e25e8d150d9edd5cad4de56704ceb9049", "size": 6100, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/multiprecision/performance/sf_performance.hpp", "max_stars_repo_name": "Manu343726/boost-cmake", "max_stars_repo_head_hexsha": "009c3843b49a56880d988ffdca6d909f881edb3d", "max_stars_repo_licenses": ["BSL-1.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": "libs/multiprecision/performance/sf_performance.hpp", "max_issues_repo_name": "Manu343726/boost-cmake", "max_issues_repo_head_hexsha": "009c3843b49a56880d988ffdca6d909f881edb3d", "max_issues_repo_licenses": ["BSL-1.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": "libs/multiprecision/performance/sf_performance.hpp", "max_forks_repo_name": "Manu343726/boost-cmake", "max_forks_repo_head_hexsha": "009c3843b49a56880d988ffdca6d909f881edb3d", "max_forks_repo_licenses": ["BSL-1.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": 28.3720930233, "max_line_length": 119, "alphanum_fraction": 0.6291803279, "num_tokens": 1717, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754371026367, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.461107113566172}}
{"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_ROUND_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_ROUND_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n\n    @ingroup group-arithmetic\n    This function object computes the rounding away from zero of its parameter.\n\n\n    @par Header <boost/simd/function/round.hpp>\n\n    @par Notes:\n\n    - With a second integral parameter  `round(x,n)` rounds aways from 0 to n digits:\n    this is similar to  `round(x*exp10(n))*exp10(-n)`\n\n      - n default to 0,\n      - n > 0: round to n digits to the right of the decimal point.\n      - n = 0: round to the nearest integer.\n      - n < 0: round to n digits to the left of the decimal point.\n\n    - aways from 0 means that half integer values are rounded to the nearest\n    integer of greatest absolute value\n\n    The current rounding mode has no effect.\n\n    - If x is \\f$\\pm\\infty\\f$ or \\f$\\pm0\\f$, it is returned, unmodified\n    - If x is a NaN, a NaN is returned\n\n    @par Example:\n\n      @snippet round.cpp round\n\n    @par Possible output:\n\n      @snippet round.txt round\n  **/\n  IEEEValue round(IEEEValue const& x, IntegerValue const& n = 0);\n} }\n#endif\n\n#include <boost/simd/function/scalar/round.hpp>\n#include <boost/simd/function/simd/round.hpp>\n\n#endif\n", "meta": {"hexsha": "3a7fcf582ea486a6eb216da787b4c7420e838d00", "size": 1652, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/round.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/round.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/round.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": 27.5333333333, "max_line_length": 100, "alphanum_fraction": 0.6065375303, "num_tokens": 387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754371026367, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.461107113566172}}
{"text": "//==================================================================================================\n/*!\n\n  Copyright 2015 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#include <boost/simd/function/scalar/muls.hpp>\n#include <simd_test.hpp>\n#include <boost/dispatch/meta/as_integer.hpp>\n#include <boost/simd/constant/inf.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/zero.hpp>\n\nSTF_CASE_TPL (\" mulssigned_int\",  STF_SIGNED_INTEGRAL_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n\n  using bs::muls;\n\n  using r_t = decltype(muls(T(), T()));\n\n  // return type conformity test\n  STF_TYPE_IS(r_t, T);\n\n  // specific values tests\n  STF_EQUAL(muls(bs::Mone<T>(), bs::Mone<T>()), bs::One<T>());\n  STF_EQUAL(muls(bs::One<T>(), bs::One<T>()), bs::One<T>());\n  STF_EQUAL(muls(bs::Valmax<T>(), bs::Valmax<T>()), bs::Valmax<T>());\n  STF_EQUAL(muls(bs::Valmax<T>(),T(2)), bs::Valmax<T>());\n  STF_EQUAL(muls(bs::Valmax<T>(),bs::Mone<T>()), bs::Valmin<T>()+bs::One<T>());\n  STF_EQUAL(muls(bs::Valmax<T>(),bs::One<T>()), bs::Valmax<T>());\n  STF_EQUAL(muls(bs::Valmin<T>(),bs::Mone<T>()), bs::Valmax<T>());\n  STF_EQUAL(muls(bs::Zero<T>(), bs::Zero<T>()), bs::Zero<T>());\n} // end of test for signed_int_\n\nSTF_CASE_TPL (\" mulsunsigned_int\",  STF_UNSIGNED_INTEGRAL_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::muls;\n  using r_t = decltype(muls(T(), T()));\n\n  // return type conformity test\n  STF_TYPE_IS(r_t, T);\n\n  // specific values tests\n  STF_EQUAL(muls(bs::One<T>(), bs::One<T>()), bs::One<T>());\n  STF_EQUAL(muls(bs::Valmax<T>(),T(2)), bs::Valmax<T>());\n  STF_EQUAL(muls(bs::Zero<T>(), bs::Zero<T>()), bs::Zero<T>());\n} // end of test for unsigned_int_\n\nSTF_CASE(\"mul sspecial\")\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::muls;\n  using bs::splat;\n  using bs::Valmin;\n\n  typedef short int T1;\n  STF_EQUAL(muls(splat<T1>(-5165), splat<T1>(23258)), Valmin<T1>());\n\n  typedef int T2;\n  STF_EQUAL(muls(splat<T2>(-1306766858), splat<T2>(1550772331)), Valmin<T2>());\n  STF_EQUAL(muls(splat<T2>(1467238299), splat<T2>(-900961598)), Valmin<T2>());\n}\n", "meta": {"hexsha": "b9989f25c7d1a4549439fb0f7346c09a9a6eea48", "size": 2489, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/scalar/muls.cpp", "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": "test/function/scalar/muls.cpp", "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": "test/function/scalar/muls.cpp", "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.6351351351, "max_line_length": 100, "alphanum_fraction": 0.6038569707, "num_tokens": 736, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.4611071109671306}}
{"text": "//---------------------------------------------------------------------------//\r\n// Copyright (c) 2013-2014 Kyle Lutz <kyle.r.lutz@gmail.com>\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://boostorg.github.com/compute for more information.\r\n//---------------------------------------------------------------------------//\r\n\r\n#include <iostream>\r\n\r\n#include <opencv2/core/core.hpp>\r\n#include <opencv2/highgui/highgui.hpp>\r\n#include <opencv2/imgproc/imgproc.hpp>\r\n\r\n#include <boost/compute/system.hpp>\r\n#include <boost/compute/algorithm/inclusive_scan.hpp>\r\n#include <boost/compute/algorithm/inclusive_scan.hpp>\r\n#include <boost/compute/interop/opencv/core.hpp>\r\n#include <boost/compute/interop/opencv/highgui.hpp>\r\n#include <boost/compute/random/default_random_engine.hpp>\r\n#include <boost/compute/random/uniform_real_distribution.hpp>\r\n#include <boost/compute/utility/source.hpp>\r\n\r\nnamespace compute = boost::compute;\r\n\r\n// this example uses the random-number generation functions in Boost.Compute\r\n// to calculate a large number of random \"steps\" and then plots the final\r\n// random \"walk\" in a 2D image on the GPU and displays it with OpenCV\r\nint main()\r\n{\r\n    // number of random steps to take\r\n    size_t steps = 250000;\r\n\r\n    // height and width of image\r\n    size_t height = 800;\r\n    size_t width = 800;\r\n\r\n    // get default device and setup context\r\n    compute::device gpu = compute::system::default_device();\r\n    compute::context context(gpu);\r\n    compute::command_queue queue(context, gpu);\r\n\r\n    using compute::int2_;\r\n\r\n    // calaculate random values for each step\r\n    compute::vector<float> random_values(steps, context);\r\n    compute::default_random_engine random_engine(queue);\r\n    compute::uniform_real_distribution<float> random_distribution(0.f, 4.f);\r\n\r\n    random_distribution.generate(\r\n        random_values.begin(), random_values.end(), random_engine, queue\r\n    );\r\n\r\n    // calaculate coordinates for each step\r\n    compute::vector<int2_> coordinates(steps, context);\r\n\r\n    // function to convert random values to random directions (in 2D)\r\n    BOOST_COMPUTE_FUNCTION(int2_, take_step, (const float x),\r\n    {\r\n        if(x < 1.f){\r\n            // move right\r\n            return (int2)(1, 0);\r\n        }\r\n        if(x < 2.f){\r\n            // move up\r\n            return (int2)(0, 1);\r\n        }\r\n        if(x < 3.f){\r\n            // move left\r\n            return (int2)(-1, 0);\r\n        }\r\n        else {\r\n            // move down\r\n            return (int2)(0, -1);\r\n        }\r\n    });\r\n\r\n    // transform the random values into random steps\r\n    compute::transform(\r\n        random_values.begin(), random_values.end(), coordinates.begin(), take_step, queue\r\n    );\r\n\r\n    // set staring position\r\n    int2_ starting_position(width / 2, height / 2);\r\n    compute::copy_n(&starting_position, 1, coordinates.begin(), queue);\r\n\r\n    // scan steps to calculate position after each step\r\n    compute::inclusive_scan(\r\n        coordinates.begin(), coordinates.end(), coordinates.begin(), queue\r\n    );\r\n\r\n    // create output image\r\n    compute::image2d image(\r\n        context, width, height, compute::image_format(CL_RGBA, CL_UNSIGNED_INT8)\r\n    );\r\n\r\n    // program with two kernels, one to fill the image with white, and then\r\n    // one the draw to points calculated in coordinates on the image\r\n    const char draw_walk_source[] = BOOST_COMPUTE_STRINGIZE_SOURCE(\r\n        __kernel void draw_walk(__global const int2 *coordinates,\r\n                                __write_only image2d_t image)\r\n        {\r\n            const uint i = get_global_id(0);\r\n            const int2 coord = coordinates[i];\r\n\r\n            if(coord.x > 0 && coord.x < get_image_width(image) &&\r\n               coord.y > 0 && coord.y < get_image_height(image)){\r\n                uint4 black = { 0, 0, 0, 0 };\r\n                write_imageui(image, coord, black);\r\n            }\r\n        }\r\n\r\n        __kernel void fill_white(__write_only image2d_t image)\r\n        {\r\n            const int2 coord = { get_global_id(0), get_global_id(1) };\r\n\r\n            if(coord.x < get_image_width(image) &&\r\n               coord.y < get_image_height(image)){\r\n                uint4 white = { 255, 255, 255, 255 };\r\n                write_imageui(image, coord, white);\r\n            }\r\n        }\r\n    );\r\n\r\n    // build the program\r\n    compute::program draw_program =\r\n        compute::program::build_with_source(draw_walk_source, context);\r\n\r\n    // fill image with white\r\n    compute::kernel fill_kernel(draw_program, \"fill_white\");\r\n    fill_kernel.set_arg(0, image);\r\n\r\n    const size_t offset[] = { 0, 0 };\r\n    const size_t bounds[] = { width, height };\r\n\r\n    queue.enqueue_nd_range_kernel(fill_kernel, 2, offset, bounds, 0);\r\n\r\n    // draw random walk\r\n    compute::kernel draw_kernel(draw_program, \"draw_walk\");\r\n    draw_kernel.set_arg(0, coordinates);\r\n    draw_kernel.set_arg(1, image);\r\n    queue.enqueue_1d_range_kernel(draw_kernel, 0, coordinates.size(), 0);\r\n\r\n    // show image\r\n    compute::opencv_imshow(\"random walk\", image, queue);\r\n\r\n    // wait and return\r\n    cv::waitKey(0);\r\n\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "ca12681b58c86571ef5e5e091c805b64582c7767", "size": 5242, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/compute/example/random_walk.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": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/compute/example/random_walk.cpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-04T18:00:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-04T18:00:00.000Z", "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/compute/example/random_walk.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 34.038961039, "max_line_length": 90, "alphanum_fraction": 0.6066386875, "num_tokens": 1176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.4611071109671306}}
{"text": "//\n// Copyright (c) 2020-2021 Huang Qinjin (huangqinjin@gmail.com)\n//\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          https://www.boost.org/LICENSE_1_0.txt)\n//\n#ifndef ICP2D_HPP\n#define ICP2D_HPP\n\n#if defined(_MSC_VER)\n#  define ICP2D_EXPORT __declspec(dllexport)\n#  define ICP2D_IMPORT __declspec(dllimport)\n#else\n#  define ICP2D_EXPORT __attribute__((visibility(\"default\")))\n#  define ICP2D_IMPORT __attribute__((visibility(\"default\")))\n#endif\n\n#if defined(ICP2D_EXPORTS)\n#  define ICP2D_API ICP2D_EXPORT\n#elif ICP2D_SHARED_LIBRARY\n#  define ICP2D_API ICP2D_IMPORT\n#else\n#  define ICP2D_API\n#endif\n\n\n#include <cstdio>\n#include <vector>\n#include <ostream>\n#include <Eigen/Geometry>\n\nnamespace ICP2D\n{\n    using Scaling = Eigen::UniformScaling<double>;\n    using Rotation = Eigen::Rotation2Dd;\n    using Translation = Eigen::Translation2d;\n    using Transform = Eigen::Affine2d;\n\n    using Point = Eigen::Vector2d;\n    using PointSet = std::vector<Point, Eigen::aligned_allocator<Point>>;\n    using WeightVector = Eigen::VectorXd;\n    using BoundingBox = Eigen::AlignedBox2d;\n\n    struct Sim2D\n    {\n        double s;\n        double r;\n        double x;\n        double y;\n\n        Scaling scaling() const noexcept\n        {\n            return Scaling(s);\n        }\n\n        Rotation rotation() const noexcept\n        {\n            return Rotation(r);\n        }\n\n        Translation translation() const noexcept\n        {\n            return Translation(x, y);\n        }\n\n        Transform transform() const noexcept\n        {\n            return translation() * rotation() * scaling();\n        }\n\n        static Sim2D Identity()\n        {\n            Sim2D T;\n            T.s = 1;\n            T.r = 0;\n            T.x = 0;\n            T.y = 0;\n            return T;\n        }\n\n        Sim2D operator*(const Sim2D& other) const noexcept\n        {\n            Eigen::Vector2d t = transform() * other.translation().vector();\n            Sim2D T;\n            T.s = s * other.s;\n            T.r = r + other.r;\n            T.x = t.x();\n            T.y = t.y();\n            return T;\n        }\n    };\n\n    template<class CharT, class Traits>\n    std::basic_ostream<CharT, Traits>& operator<<(std::basic_ostream<CharT, Traits>& os, const Sim2D& T)\n    {\n        return os\n            << '{'\n            << 's' << ':' << T.s << ',' << ' '\n            << 'r' << ':' << T.r << ',' << ' '\n            << 'x' << ':' << T.x << ',' << ' '\n            << 'y' << ':' << T.y\n            << '}'\n            ;\n    }\n\n    ICP2D_API Sim2D solve(const PointSet& src, const PointSet& dst, const WeightVector& w);\n    ICP2D_API double error(const Sim2D& T, const PointSet& src, const PointSet& dst, const WeightVector& w);\n\n    struct ICP2D_API Sampler\n    {\n        virtual ~Sampler() = default;\n        virtual std::size_t size() const noexcept = 0; // size() <= maximum() + 1\n        virtual std::size_t maximum() const noexcept = 0;\n        virtual void sample(std::size_t* output) noexcept = 0;\n        static std::size_t population(std::size_t num, size_t (max)) noexcept;\n        static Sampler* random(std::size_t num, std::size_t (max)) noexcept;\n        static Sampler* ordered(std::size_t num, std::size_t (max)) noexcept;\n    };\n\n    struct ICP2D_API RANSAC\n    {\n        Sim2D model;\n        double score; // [0, 1]\n\n        PointSet src;\n        PointSet dst;\n        WeightVector w;\n\n        double inlier_distance_threshold;\n        std::size_t num_min_inliers;\n        std::size_t num_max_iterations;\n\n        void solve() noexcept;\n    };\n\n    class ICP2D_API SVG\n    {\n        FILE* out;\n        Sim2D T;\n        Point scale;\n        BoundingBox view;\n\n    public:\n        SVG() noexcept;\n        ~SVG();\n        void open(const char* file, const Point& scale = Point::Ones()) noexcept;\n        void close() noexcept;\n        void push(const Sim2D& transform) noexcept;\n        void pop() noexcept;\n        void draw(const PointSet& points, double radius, const char* color) noexcept;\n    };\n}\n\n\n#endif //ICP2D_HPP\n", "meta": {"hexsha": "8a1e98511ca5436b4114f42490cfd38f3005507e", "size": 4089, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ICP2D.hpp", "max_stars_repo_name": "huangqinjin/ICP2D", "max_stars_repo_head_hexsha": "ed43a3b06f75f99f1fe6b1cf07e66b7ff61f8643", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-10-10T12:31:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-10T12:31:05.000Z", "max_issues_repo_path": "ICP2D.hpp", "max_issues_repo_name": "huangqinjin/ICP2D", "max_issues_repo_head_hexsha": "ed43a3b06f75f99f1fe6b1cf07e66b7ff61f8643", "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": "ICP2D.hpp", "max_forks_repo_name": "huangqinjin/ICP2D", "max_forks_repo_head_hexsha": "ed43a3b06f75f99f1fe6b1cf07e66b7ff61f8643", "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.0445859873, "max_line_length": 108, "alphanum_fraction": 0.5659085351, "num_tokens": 1055, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754371026368, "lm_q2_score": 0.63341024983754, "lm_q1q2_score": 0.46110710349077355}}
{"text": "/*\n* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or\n* its licensors.\n*\n* For complete copyright and license terms please see the LICENSE at the root of this\n* distribution (the \"License\"). All use of this software is governed by the License,\n* or, if provided, by the license below or the license accompanying this file. Do not\n* remove or modify any license notices. This file is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n*\n*/\n\n#include <NumericalMethods_precompiled.h>\n#include <NumericalMethods/Eigenanalysis.h>\n#include <NumericalMethods/Optimization.h>\n#include <Optimization/SolverBFGS.h>\n#include <Eigenanalysis/Solver3x3.h>\n\nnamespace NumericalMethods\n{\n    namespace Optimization\n    {\n        SolverResult SolverBFGS(const Function& function, const AZStd::vector<double>& initialGuess)\n        {\n            return MinimizeBFGS(function, initialGuess);\n        }\n    }\n\n    namespace Eigenanalysis\n    {\n        SolverResult<Real, 3> Solver3x3RealSymmetric(const SquareMatrix<Real, 3>& matrix)\n        {\n            // The matrix must be symmetric.\n            if (matrix[0][1] == matrix[1][0] && matrix[0][2] == matrix[2][0] && matrix[1][2] == matrix[2][1])\n            {\n                return NonIterativeSymmetricEigensolver3x3(\n                    matrix[0][0], matrix[0][1], matrix[0][2],\n                                  matrix[1][1], matrix[1][2],\n                                                matrix[2][2]\n                );\n            }\n            else\n            {\n                return SolverResult<Real, 3>{SolverOutcome::FailureInvalidInput};\n            }\n        }\n    }\n} // namespace NumericalMethods\n", "meta": {"hexsha": "552d98e76e133bfad68ac88c008e08d68f254ebb", "size": 1736, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dev/Gems/PhysX/Code/NumericalMethods/Source/NumericalMethods.cpp", "max_stars_repo_name": "BadDevCode/lumberyard", "max_stars_repo_head_hexsha": "3d688932f919dbf5821f0cb8a210ce24abe39e9e", "max_stars_repo_licenses": ["AML"], "max_stars_count": 1738.0, "max_stars_repo_stars_event_min_datetime": "2017-09-21T10:59:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:05:46.000Z", "max_issues_repo_path": "dev/Gems/PhysX/Code/NumericalMethods/Source/NumericalMethods.cpp", "max_issues_repo_name": "olivier-be/lumberyard", "max_issues_repo_head_hexsha": "3d688932f919dbf5821f0cb8a210ce24abe39e9e", "max_issues_repo_licenses": ["AML"], "max_issues_count": 427.0, "max_issues_repo_issues_event_min_datetime": "2017-09-29T22:54:36.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-15T19:26:50.000Z", "max_forks_repo_path": "dev/Gems/PhysX/Code/NumericalMethods/Source/NumericalMethods.cpp", "max_forks_repo_name": "olivier-be/lumberyard", "max_forks_repo_head_hexsha": "3d688932f919dbf5821f0cb8a210ce24abe39e9e", "max_forks_repo_licenses": ["AML"], "max_forks_count": 671.0, "max_forks_repo_forks_event_min_datetime": "2017-09-21T08:04:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T14:30:07.000Z", "avg_line_length": 35.4285714286, "max_line_length": 109, "alphanum_fraction": 0.6129032258, "num_tokens": 401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4610921558435708}}
{"text": "/*! \\headerfile Material.hpp \"include/Material.hpp\"\n* \"Material.hpp\" contains the class definition encapsulating the \n* data structure interface for a Geemetry in a swSim Model.\n*/\n\n// Copyright 2020 United States Government as represented by the Administrator of the National \n// Aeronautics and Space Administration. No copyright is claimed in the United States under \n// Title 17, U.S. Code. All Other Rights Reserved. See Appendix A for 3rd party licenses.\n//\n// The Solid-Wave Sim (swSIM) platform is licensed under the Apache License, Version 2.0 (the \n// \"License\"); you may not use this file except in compliance with the License. You may obtain \n// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0. \n// \n// Unless required by applicable law or agreed to in writing, software distributed under the \n// License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, \n// either express or implied. See the License for the specific language governing permissions \n// and limitations under the License.\n\n#ifndef MATERIAL_HPP\n#define MATERIAL_HPP\n\n\n#include <mpi.h>\n#include <stdint.h>\n#include <string>\n#include <vector>\n#include <stddef.h>\n#include <math.h>\n#include <libxml/xmlmemory.h>\n#include <libxml/parser.h>\n#include <Eigen/Dense>\n\n#include \"ParsableObject.hpp\"\n\ntypedef Eigen::Matrix<float, 6, 6> Matrix6f;\nnamespace swSim{\n    /*! \\class Material Material.hpp \"include/Material.hpp\"\n    *\n    * Defines data structures for Material in swSim\n    */\n    class Material: public ParsableObject {   \n    public:\n        struct material_s {\n            uint32_t materialID; /*!< Unique identification number for this material */\n            float density; /*!< Material density in kg/cubic meter */\n            float stiffnessValues[21]; /*!< 21 Unique stiffness values (in Pascals) in the 6x6, symmetric stiffness matrix */\n\n        };\n        material_s matS; /*!< Material struct */\n        MPI_Datatype mpi_material; /*!< MPI datatype for communication */\n        /*!\n        * Create the Material\n        */\n        Material();\n        /*!\n        * Destroy the Material\n        */\n        ~Material();\n        /*!\n        * Initilize data values\n        */\n        void Init(uint32_t id, float rho, float *c);\n        /*!\n        * Copy values of one Material to another.\n        */\n        void Copy(Material *other);\n        /*!\n        * Create the MPI datatype for the Material.\n        */\n        MPI_Datatype MPICreate();\n        /*!\n        * Get a local stiffness Matrix for that voxel base on the material stiffness matrix and a rotation vector.\n        */\n        void RotateStiffnessMatrix(float *rotVec, float *C);\n        /*!\n        * Provide parsing instructions for reading inputs associated with the Material\n        */\n        void ParseSwitch(xmlDocPtr doc, xmlNodePtr cur, int caseNumber) override;\n        /*!\n        * Convert the array of stiffness Values to an Eigen Matrix\n        */\n        Matrix6f StiffnessValuesArrayToMatrix(); \n     private:\n        /*!\n        * Get a 3D Rotation matrix based on a 3 element rotation vector.\n        */\n        Eigen::Matrix3f get3DRotation(float *rotVec);\n        /*!\n        * Get a Rotation Matrix from a rotation abotu the Z axis\n        */\n        Eigen::Matrix3f getRotationAboutZ(float angle);\n        /*!\n        * Get a Rotation Matrix from a rotation abotu the Y axis\n        */\n        Eigen::Matrix3f getRotationAboutY(float angle);\n        /*!\n        * Get a Rotation Matrix from a rotation abotu the X axis\n        */\n        Eigen::Matrix3f getRotationAboutX(float angle);\n        /*!\n        * Get a 3D Rotation Transformation Matrix\n        */\n        Matrix6f get3DTransformationMatrix(Eigen::Matrix3f R); \n        /*!\n        * Convert MAtrix Values back to an array\n        */ \n        void MatrixToStiffnessValuesArray(float *valueArray, Matrix6f C);\n    };\n};\n\n\n\n#endif", "meta": {"hexsha": "2ace086b0e1ab3ab2bc3f0d012331740a8aa1276", "size": 3918, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/Material.hpp", "max_stars_repo_name": "nasa/swSim", "max_stars_repo_head_hexsha": "348ba39ea149711a2285916a2dcddc2c71da4859", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-02-21T09:49:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T09:54:54.000Z", "max_issues_repo_path": "include/Material.hpp", "max_issues_repo_name": "ElsevierSoftwareX/SOFTX-D-21-00042", "max_issues_repo_head_hexsha": "348ba39ea149711a2285916a2dcddc2c71da4859", "max_issues_repo_licenses": ["Apache-2.0"], "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/Material.hpp", "max_forks_repo_name": "ElsevierSoftwareX/SOFTX-D-21-00042", "max_forks_repo_head_hexsha": "348ba39ea149711a2285916a2dcddc2c71da4859", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-04-27T09:52:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T07:22:16.000Z", "avg_line_length": 34.6725663717, "max_line_length": 125, "alphanum_fraction": 0.6429300664, "num_tokens": 862, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.46109215584357066}}
{"text": "#include <fstream>\n#include <string>\n#include <cerrno>\n#include <iostream>\n#include <Eigen/Dense>\n#include <json/json.h>\n\nusing Eigen::MatrixXd;\n\nstd::string get_file_contents(const char* filename)\n{\n    std::ifstream in(filename,std::ios::in|std::ios::binary);\n    if(in) {\n        std::string contents;\n        in.seekg(0,std::ios::end);\n        contents.reserve(in.tellg());\n        in.seekg(0,std::ios::beg);\n        contents.assign((std::istreambuf_iterator<char>(in)),std::istreambuf_iterator<char>());\n        in.close();\n        return(contents);\n    }\n    throw(errno);\n}\n\nint main()\n{\n    MatrixXd m(2,2);\n    m(0,0)=3;\n    m(1,0)=2.5;\n    m(0,1)=-1;\n    m(1,1)=m(1,0)+m(0,1);\n    std::cout<<m<<std::endl;\n\n    Json::Value root;\n    Json::Reader reader;\n    bool parsingSuccess=reader.parse(get_file_contents(\"test.json\"),root);\n    std::cout<<parsingSuccess<<std::endl;\n    const Json::Value objects=root[\"objects\"];\n    for (int index=0;index<objects.size();++index){\n        std::cout<<objects[index].asString()<<std::endl;\n    }\n}\n", "meta": {"hexsha": "96be71ee6e7b1f0397a85a92cad6125762f30148", "size": 1045, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Projects/Test/hello.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": "Projects/Test/hello.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": "Projects/Test/hello.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": 24.3023255814, "max_line_length": 95, "alphanum_fraction": 0.6076555024, "num_tokens": 297, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4610921493433398}}
{"text": "//\n// Copyright (c) 2021 INRIA\n//\n\n#include \"pinocchio/spatial/fwd.hpp\"\n#include \"pinocchio/algorithm/parallel/aba.hpp\"\n#include \"pinocchio/algorithm/aba.hpp\"\n#include \"pinocchio/algorithm/joint-configuration.hpp\"\n#include \"pinocchio/parsers/sample-models.hpp\"\n#include \"pinocchio/utils/timer.hpp\"\n\n#include <iostream>\n\n#include <boost/test/unit_test.hpp>\n#include <boost/utility/binary.hpp>\n\nusing namespace pinocchio;\n\nBOOST_AUTO_TEST_SUITE(BOOST_TEST_MODULE)\n\nBOOST_AUTO_TEST_CASE(test_parallel_aba)\n{\n  pinocchio::Model model; buildModels::humanoidRandom(model);\n  Data data_ref(model);\n  \n  model.lowerPositionLimit.head<3>().fill(-1.);\n  model.upperPositionLimit.head<3>().fill( 1.);\n  \n  const Eigen::DenseIndex batch_size = 128;\n  const int num_threads = omp_get_max_threads();\n\n  Eigen::MatrixXd q(model.nq,batch_size);\n  Eigen::MatrixXd v(model.nv,batch_size);\n  Eigen::MatrixXd tau(model.nv,batch_size);\n  Eigen::MatrixXd a(model.nv,batch_size);\n  Eigen::MatrixXd a_ref(model.nv,batch_size);\n  \n  for(Eigen::DenseIndex i = 0; i < batch_size; ++i)\n  {\n    q.col(i) = randomConfiguration(model);\n    v.col(i) = Eigen::VectorXd::Random(model.nv);\n    tau.col(i) = Eigen::VectorXd::Random(model.nv);\n  }\n  \n  ModelPool pool(model);\n  aba(num_threads,pool,q,v,tau,a);\n  \n  for(Eigen::DenseIndex i = 0; i < batch_size; ++i)\n  {\n    a_ref.col(i) = aba(model,data_ref,q.col(i),v.col(i),tau.col(i));\n  }\n\n  BOOST_CHECK(a == a_ref);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n", "meta": {"hexsha": "a5730f989fa1bc7fb69445b6b1829cb88a3950ca", "size": 1466, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittest/parallel-aba.cpp", "max_stars_repo_name": "Sreevis/pinocchio", "max_stars_repo_head_hexsha": "7e3f96e59047b40e678a53b3877b401af4b6d0bd", "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": "unittest/parallel-aba.cpp", "max_issues_repo_name": "Sreevis/pinocchio", "max_issues_repo_head_hexsha": "7e3f96e59047b40e678a53b3877b401af4b6d0bd", "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": "unittest/parallel-aba.cpp", "max_forks_repo_name": "Sreevis/pinocchio", "max_forks_repo_head_hexsha": "7e3f96e59047b40e678a53b3877b401af4b6d0bd", "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": 25.275862069, "max_line_length": 68, "alphanum_fraction": 0.7141882674, "num_tokens": 413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4610921493433398}}
{"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_FUNCTION_TWO_PROD_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_TWO_PROD_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-arithmetic\n    Function object implementing two_prod capabilities\n\n    For any two reals @c x and @c y two_prod computes two reals (in an std::pair)\n    @c r0 and @c r1 so that:\n\n    @code\n    r0 = x * y\n    r1 = r0 -(x * y)\n    @endcode\n\n    using perfect arithmetic.\n\n    Its main usage is to be able to compute\n    sum of reals and the residual error using IEEE 754 arithmetic.\n\n  **/\n  const boost::dispatch::functor<tag::two_prod_> two_prod = {};\n} }\n#endif\n\n#include <boost/simd/function/scalar/two_prod.hpp>\n#include <boost/simd/function/simd/two_prod.hpp>\n\n#endif\n", "meta": {"hexsha": "c64eaa3ca54d585e66877bf6d2f4700e1b07ca52", "size": 1184, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/two_prod.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/function/two_prod.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/function/two_prod.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": 25.7391304348, "max_line_length": 100, "alphanum_fraction": 0.5929054054, "num_tokens": 269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.46109214934333975}}
{"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_FUNCTION_IDIVFIX_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_IDIVFIX_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-arithmetic\n    Function object implementing idivfix capabilities\n\n    Computes the integer conversion of the truncated division of its parameters.\n\n    @par semantic:\n    For any given value @c x,  @c y of type @c T:\n\n    @code\n    T r = idivfix(x, y);\n    @endcode\n\n    The code is similar to:\n\n    @code\n    as_integer_t<T> r = toints(trunc(x/y));\n    @endcode\n\n    If y is @ref Zero, it returns @ref Valmax (resp. @ref Valmin)\n    if x is positive (resp. negative) and 0 if x is @ref Zero.\n\n    @see toints, trunc\n  **/\n  const boost::dispatch::functor<tag::idivfix_> idivfix = {};\n} }\n#endif\n\n#include <boost/simd/function/scalar/idivfix.hpp>\n#include <boost/simd/function/simd/idivfix.hpp>\n\n#endif\n", "meta": {"hexsha": "dcc7c665c145ed85635483e263ae6a5d152f2a09", "size": 1313, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/idivfix.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/function/idivfix.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/function/idivfix.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": 25.25, "max_line_length": 100, "alphanum_fraction": 0.5932977913, "num_tokens": 313, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.46109214934333975}}
{"text": "/*!\n  \\file 2d_uncertain_values.cpp\n  \\brief Simple 2D plot example showing how uncertain values can also be labelled with their uncertainty, confidence interval and degrees of freedom.\n*/\n\n// Copyright Jacob Voytko 2007\n// Copyright Paul A Bristow 2007, 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#include <boost/cstdlib.hpp> // Boost exit_success and failure values.\n\n#include <boost/svg_plot/svg_2d_plot.hpp> // svg_plot function\n#include <boost/svg_plot/show_2d_settings.hpp> // boost/libs/svg_plot/doc/html/header/boost/svg_plot/show_2d_settings_hpp.html\n\n#include <iostream>\n#include <map> // Container for data.\n// using std::map\n\n#include <vector>\n// using std::vector\n#include <utility>\n// using std::pair\n// using std::make_pair\n#include <algorithm>\n// using std::foreach\n#include <boost/quan/unc.hpp>\n//#include <boost/quan/unc_init.hpp>\n\nint main()\n{\n  std::cout << \"svg_plot 2D Uncertain value-labels.\" << std::endl;\n\n  using boost::quan::unc;\n  using boost::quan::uncun;\n  using boost::quan::setUncDefaults;\n  using boost::quan::adddegfree;\n  using boost::quan::addlimits;\n  using boost::quan::plusminus;\n\n  typedef unc<false> uncun; // Uncertain type to use (Uncorrelated the normal case).\n  setUncDefaults(std::cout);  // Initialisation of uncertain type.\n\n  try\n  {\n    //! Data to plot stored in container type `std::map`.\n\n   uncun ux1(2.23, 0.056F, 7); // For an X-value. \n   // Using the  uncertain class unc `operator<<` provided we can output all the details of the uncertain values.\n    std::cout << std::scientific << plusminus << addlimits << adddegfree << std::setw(20) << std::left \n      << \"ux = \" << ux1 << std::endl; // ux =             2.23 +/-0.056 <2.19, 2.27> (7)\n    uncun uy1(3.45, 0.67F, 9); // For a Y-value. \n    std::cout << \"uy = \" << uy1 << std::endl; // uy = 3.5 +/-0.67 <3.01, 3.89> (9)\n    std::pair<uncun, uncun > up1 = make_pair(ux1, uy1); // Make an X & Y pair of uncertain values.\n    std::cout << \"up1 = \" << up1 << std::endl; \n    // up1 = 2.23 +/-0.056 <2.19, 2.27> (7), 3.5 +/-0.67 <3.01, 3.89> (9)\n\n    uncun ux2(5.45, 0.45F, 8); // For 2nd X-value. \n    uncun uy2(6.08, 0.52F, 5); // For 2nd Y-value.\n    std::pair<uncun, uncun > up2 = make_pair(ux2, uy2); // Make a second X & Y pair of uncertain values.\n    std::cout << \"up2 = \" << up2 << std::endl; \n    // up2 = 5.5 +/-0.45 <5.14, 5.76> (8), 6.1 +/-0.52 <5.62, 6.54> (5)\n\n    std::vector<std::pair<uncun, uncun> > uncertains;\n    std::cout << uncertains.size() << std::endl; // zero.\n    uncertains.reserve(10);\n    uncertains.push_back(up1);\n    uncertains.push_back(up2);\n    // Display the uncertain values packaged in a vector using conventional for loop.\n    for (size_t i = 0; i < uncertains.size(); i++)\n    {\n      std::cout << \"#\" << i << \" \" << uncertains[i] << std::endl;\n    }\n\n   //// Display the uncertain values packaged in a vector using a C++ lambda with functor.\n   // auto show = [](const std::pair<uncun, uncun>& u) { std::cout << \" \" << u << std::endl; };\n   // std::for_each(uncertains.begin(), uncertains.end(), show); std::cout << std::endl;\n\n   // // Display using std::copy.\n   // std::copy(uncertains.begin(), uncertains.end(), std::ostream_iterator<std::pair<uncun, uncun>>(std::cout, \"\\n\"));\n   // std::cout << std::endl;\n\n    using namespace boost::svg;  // Convenient for access to all SVG functions and colors.\n\n    svg_2d_plot my_2d_plot;\n\n    my_2d_plot\n      .title(\"Uncertains - labelled with X and Y values and uncertainty info.\")\n      .title_font_size(10)\n      // No legend needed as only one data-series?\n      //.legend_on(true)\n      //.legend_title(\"Knowns\")\n      .x_range(0, 10)\n      .y_range(0, 10)\n      .x_major_grid_on(true)\n      .y_major_grid_on(true)\n     // .plusminus_sds(2.) // Optionally display uncertainty (standard deviation) multplied by a factor of two.\n      ;\n\n    /*`To put a value-label against each data-point, switch on or other, or both the options:\n*/\n//my_2d_plot.x_values_on(true); // Add a label for the X-axis.\n//my_2d_plot.y_values_on(true); // Add a label for the X-axis.\n    my_2d_plot.xy_values_on(true); // Add a label for both the X and Y-axis.\n\n    /*`If the default size and color are not to your taste, set more options, like:\n*/\n    my_2d_plot.x_values_font_size(8) // Change font size for the X-axis value-labels.\n      .x_values_font_family(\"Times New Roman\") // Change font for the X-axis value-labels.\n      .x_values_color(red); // Change X-values color from default black to red.\n\n    my_2d_plot.y_values_font_size(10) // Change font size for the Y-axis value-labels.\n      .y_values_font_family(\"Arial\") // Change font for the Y-axis value-labels.\n      .y_values_color(blue); // Change Y-values color from default black to blue.\n\n/*`The default value-label position is horizontal, centered slightly above the data_point marker,\nbut, depending on the type and density of data_points, and the length of the values\n(controlled in turn by choice of options, the `precision` and `ioflags` in use),\nit is often clearer to use a different orientation.\nThis can be controlled in steps using an 'enum rotate_style` for convenience (or in degrees).\n\n* `leftward` - writing level with the data_point but to its left.\n* `rightward` - writing level with the data-point but to its right.\n* `uphill` - writing up at 45 degree slope is often a good choice,\n* `upward` - writing vertically up and\n* `backup` - writing to the left are also useful.\n``\n    enum rotate_style\n    {\n      // Also need a no_rotate, = -1;\n      horizontal = 0, //!< normal horizontal left to right, centered.\n      slopeup = -30, //!< slope up.\n      uphill = -45, //!< 45 steep up.\n      steepup = -60, //!< up near vertical.\n      upward = -90, //!< vertical writing up.\n      backup = -135, //!< slope up backwards - upside down!\n      leftward= -180, //!< horizontal to left.\n      rightward = 360, //!< horizontal to right.\n      slopedownhill = 30, //!< 30 gentle slope down.\n      downhill = 45, //!< 45 down.\n      steepdown = 60, //!<  60 steeply down.\n      downward = 90,  //!< vertical writing downwards from marker.\n      backdown = 135, //!< slope down backwards.\n      upsidedown = 180 //!< upside down!  (== -180)\n    };\n\n\n``\n\n(For 1-D plots other directions are less attractive,\nplacing the values below the horizontal Y-axis line,\nbut for 2-D plots all writing orientations can be useful).\n*/\n    my_2d_plot.x_values_rotation(rightward); // Orientation for the Y-axis value-labels, placing information to the right of the data-point marker.\n   // my_2d_plot.x_values_rotation(horizontal); // Orientation for the Y-axis value-labels, placing information above the data-point marker.\n   // my_2d_plot.x_values_rotation(uphill); // Orientation for the Y-axis value-labels, placing information to the right of the data-point marker.\n   // my_2d_plot.x_values_rotation(upward); // Orientation for the Y-axis value-labels, placing information to the right of the data-point marker.\n  //  my_2d_plot.x_values_rotation(leftward); // Orientation for the Y-axis value-labels, placing information to the right of the data-point marker.\n    // This is only useful for x prefix and value, like \"X = 1.23\" not any following information.\n\n  /*`Add some information about uncertainty to both the X and Y-values:*/\n    my_2d_plot.x_plusminus_on(true); // Uncertainty (standard deviation) +/- value-label for the X-axis value.\n    my_2d_plot.x_plusminus_color(blue); // Change from default color black to color blue.\n    my_2d_plot.x_df_on(true); // Degrees of freedom (observations-1) value-label for the X-axis value.\n    my_2d_plot.x_addlimits_on(true); // Confidence limit value-label for the X-axis value.\n    my_2d_plot.x_datetime_on(true);\n    my_2d_plot.x_order_on(true);\n    my_2d_plot.x_decor(\"X=&#x200A;\", \"\",\"\"); // Suffix value-label for the X-axis value.\n    // https://jkorpela.fi/chars/spaces.html describes Unicode spaces that must be explicit, not just spaces in the string.\n    // Normal space is  \"&#x00A0;\", but hair space \"&#x200A;\" is most useful between digits and characters,\n    // for example: \"X=&#x200A;\" and \"X=&#x2001;\" is em quad, 1 em (nominally, the height of the font).\n    // and about Y-values:\n    my_2d_plot.y_decor(\", Y=\", \"\",\" g\"); // Suffix value-label for the Y-axis value.\n\n    my_2d_plot.y_plusminus_on(true); // Uncertainty (standard deviation) value-label for the X-axis value.\n    my_2d_plot.y_plusminus_color(green);\n    // Degrees of freedom for the Y-axis value is rather redundant if already shown for X-axis values.\n    my_2d_plot.y_df_on(true); // Degrees of freedom for the Y-axis value. \n    my_2d_plot.y_addlimits_on(true); // Confidence limit or interval for the X-axis value.\n\n    std::cout << \"x_values_color() = \" << my_2d_plot.x_values_color() << std::endl; // y_values_color() = RGB(0,0,255) == blue for fill and stroke\n    std::cout << \"y_values_color() = \" << my_2d_plot.y_values_color() << std::endl; // y_values_color() = RGB(0,0,255) == blue for fill and stroke\n\n  //  my_2d_plot.plot(doubles, \"data-series 1 - doubles\").stroke_color(blue).fill_color(red);\n\n    // These affect all the marker points.\n    //my_2d_plot.y_values_font_size(16) // Change font size for the Y-axis value-labels.\n    //  .y_values_font_family(\"bold\") // Change font for the Y-axis value-labels.\n    //  .y_values_color(green); // Change Y color from default black to blue.\n\n///   Change the data-point markers colors to green circle filled with a yellow center.\n    my_2d_plot.plot(uncertains, \"1 data-series - 2 uncertains\").stroke_color(green).fill_color(yellow);\n\n    my_2d_plot.write(\"./demo_2d_uncertain_values_1.svg\");\n\n  //  show_2d_plot_settings(my_2d_plot, std::cout); // Needs include <boost/svg_plot/show_2d_settings.hpp>\n\n    return boost::exit_success;\n  }\n  catch (std::exception& ex)\n  {\n    std::cout << \"svg_plot exception \" << ex.what() << std::endl;\n    return boost::exit_exception_failure;\n  }\n} // int main()\n\n/*\n\nBuild started...\n1>------ Build started: Project: demo_2d_uncertain_values, Configuration: Debug x64 ------\n1>demo_2d_uncertain_values.cpp\n1>demo_2d_uncertain_values.vcxproj -> I:\\Cpp\\SVG_plot\\svg_plot\\x64\\Debug\\demo_2d_uncertain_values.exe\n1>Autorun \"I:\\Cpp\\SVG_plot\\svg_plot\\x64\\Debug\\demo_2d_uncertain_values.exe\"\n1>svg_plot 2D Uncertain values\n1>ux =                5.2 +/-0.56 <4.82, 5.64> (7)\n1>uy = 8.4 +/-0.67 <8.01, 8.89> (9)\n1>0\n1> 5.2 +/-0.56 <4.82, 5.64> (7), 8.4 +/-0.67 <8.01, 8.89> (9)\n1> 7.5 +/-0.45 <7.14, 7.76> (8), 6.1 +/-0.52 <5.62, 6.54> (5)\n1>\n1>Done building project \"demo_2d_uncertain_values.vcxproj\".\n========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========\n\nProjects build report:\n  Status    | Project [Config|platform]\n -----------|---------------------------------------------------------------------------------------------------\n  Succeeded | demo_2d_uncertain_values\\demo_2d_uncertain_values.vcxproj [Debug|x64]\n\nBuild time 00:00:04.211\nBuild ended at 22Jan2021 17:36:03\n\n1>#0 5.2 +/-0.56 <4.82, 5.64> (7), 8.4 +/-0.67 <8.01, 8.89> (9)\n1>#1 7.5 +/-0.45 <7.14, 7.76> (8), 6.1 +/-0.52 <5.62, 6.54> (5)\n\n\n\n*/\n", "meta": {"hexsha": "bbcbab764c000f088b3531630324801ae25ef648", "size": 11257, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/demo_2d_uncertain_values.cpp", "max_stars_repo_name": "pabristow/svg_plot", "max_stars_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2016-03-09T03:23:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T14:02:07.000Z", "max_issues_repo_path": "example/demo_2d_uncertain_values.cpp", "max_issues_repo_name": "pabristow/svg_plot", "max_issues_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2018-03-05T14:39:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-22T09:00:33.000Z", "max_forks_repo_path": "example/demo_2d_uncertain_values.cpp", "max_forks_repo_name": "pabristow/svg_plot", "max_forks_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2016-11-04T14:36:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-17T08:12:03.000Z", "avg_line_length": 46.9041666667, "max_line_length": 149, "alphanum_fraction": 0.666429777, "num_tokens": 3300, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.7634837527911056, "lm_q1q2_score": 0.4610921428431087}}
{"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//////////////////////////////////////////////////////////////////////////////\n// cover test behavior of arithmetic components in scalar mode\n//////////////////////////////////////////////////////////////////////////////\n\n#include <nt2/ieee/include/functions/frexp.hpp>\n#include <boost/fusion/include/std_pair.hpp>\n#include <nt2/include/constants/valmin.hpp>\n#include <nt2/include/constants/valmax.hpp>\n#include <nt2/include/functions/mantissa.hpp>\n#include <nt2/include/functions/exponent.hpp>\n\n#include <nt2/sdk/unit/tests/cover.hpp>\n#include <nt2/sdk/unit/module.hpp>\n#include <vector>\n\nNT2_TEST_CASE_TPL ( frexp_real__1_0_1,  NT2_REAL_TYPES)\n{\n\n  using nt2::frexp;\n  using nt2::tag::frexp_;\n  typedef typename nt2::meta::call<frexp_(T)>::type r_t;\n\n  nt2::uint32_t NR = NT2_NB_RANDOM_TEST;\n  std::vector<T> in1(NR);\n  std::vector<r_t> ref(NR);\n  nt2::roll(in1, nt2::Valmin<T>()/2, nt2::Valmax<T>()/2);\n  for(nt2::uint32_t i=0; i < NR ; ++i)\n  {\n    ref[i].first = nt2::mantissa(in1[i])/2;\n    ref[i].second = nt2::exponent(in1[i])+1;\n  }\n  NT2_COVER_ULP_EQUAL(frexp_, ((T, in1)), ref, 0);\n}\n\n", "meta": {"hexsha": "8d7a353ba873258215baf2a2ae4569173341d32b", "size": 1604, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/core/base/cover/ieee/scalar/frexp.cpp", "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/base/cover/ieee/scalar/frexp.cpp", "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/base/cover/ieee/scalar/frexp.cpp", "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.3023255814, "max_line_length": 80, "alphanum_fraction": 0.5374064838, "num_tokens": 414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6893056295505783, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.46106292896899276}}
{"text": "//  Copyright 2013 John Maddock. Distributed under the Boost\r\n//  Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_\r\n\r\n#ifndef BOOST_MP_MATH_SETUP_HPP\r\n#define BOOST_MP_MATH_SETUP_HPP\r\n\r\n#ifdef _MSC_VER\r\n#  define _SCL_SECURE_NO_WARNINGS\r\n#endif\r\n\r\n#define BOOST_MATH_OVERFLOW_ERROR_POLICY ignore_error\r\n#undef BOOST_MATH_SMALL_CONSTANT\r\n#define BOOST_MATH_SMALL_CONSTANT(x) x\r\n\r\n#if !defined(TEST_MPF_50) && !defined(TEST_BACKEND) && !defined(TEST_CPP_DEC_FLOAT) \\\r\n      && !defined(TEST_MPFR_50) && !defined(TEST_FLOAT128) && !defined(TEST_CPP_BIN_FLOAT)\r\n#  define TEST_MPF_50\r\n#  define TEST_MPFR_50\r\n#  define TEST_CPP_DEC_FLOAT\r\n#  define TEST_FLOAT128\r\n#  define TEST_CPP_BIN_FLOAT\r\n\r\n#ifdef _MSC_VER\r\n#pragma message(\"CAUTION!!: No backend type specified so testing everything.... this will take some time!!\")\r\n#endif\r\n#ifdef __GNUC__\r\n#pragma warning \"CAUTION!!: No backend type specified so testing everything.... this will take some time!!\"\r\n#endif\r\n\r\n#endif\r\n\r\n#if defined(TEST_MPF_50)\r\n#include <boost/multiprecision/gmp.hpp>\r\n#include <boost/multiprecision/debug_adaptor.hpp>\r\n\r\n#define MPF_TESTS    /*test(number<gmp_float<18> >(), \"number<gmp_float<18> >\");*/\\\r\n   mpf_float::default_precision(20);\\\r\n   test(mpf_float(), \"number<gmp_float<0> > (20 digit precision)\");\\\r\n   mpf_float::default_precision(35);\\\r\n   test(mpf_float(), \"number<gmp_float<0> > (35 digit precision)\");\\\r\n   test(number<gmp_float<30> >(), \"number<gmp_float<30> >\");\\\r\n   test(number<gmp_float<35> >(), \"number<gmp_float<35> >\");\\\r\n   /* there should be at least one test with expression templates off: */ \\\r\n   test(number<gmp_float<35>, et_off>(), \"number<gmp_float<35>, et_off>\");\r\n#define MPF_SMALL_TESTS    /*test(number<gmp_float<18> >(), \"number<gmp_float<18> >\");*/\\\r\n   test(number<gmp_float<30> >(), \"number<gmp_float<30> >\");\\\r\n   test(number<gmp_float<35> >(), \"number<gmp_float<35> >\");\\\r\n   /* there should be at least one test with expression templates off: */ \\\r\n   test(number<gmp_float<35>, et_off>(), \"number<gmp_float<35>, et_off>\");\\\r\n   mpf_float::default_precision(20); \\\r\n   test(mpf_float(), \"number<gmp_float<0> > (20 digit precision)\"); \\\r\n   mpf_float::default_precision(35); \\\r\n   test(mpf_float(), \"number<gmp_float<0> > (35 digit precision)\"); \\\r\n\r\ntypedef boost::multiprecision::number<boost::multiprecision::gmp_float<18> > test_type_1;\r\ntypedef boost::multiprecision::number<boost::multiprecision::gmp_float<30> > test_type_2;\r\ntypedef boost::multiprecision::number<boost::multiprecision::gmp_float<35> > test_type_3;\r\ntypedef boost::multiprecision::number<boost::multiprecision::gmp_float<35>, boost::multiprecision::et_off> test_type_4;\r\ntypedef boost::multiprecision::mpf_float test_type_5;\r\n\r\n#else\r\n\r\n#define MPF_TESTS\r\n#define MPF_SMALL_TESTS\r\n\r\n#endif\r\n\r\n#if defined(TEST_MPFR_50)\r\n#include <boost/multiprecision/mpfr.hpp>\r\n\r\n#define MPFR_TESTS    test(number<mpfr_float_backend<18> >(), \"number<mpfr_float_backend<18> >\");\\\r\n   test(number<mpfr_float_backend<30> >(), \"number<mpfr_float_backend<30> >\");\\\r\n   test(number<mpfr_float_backend<35> >(), \"number<mpfr_float_backend<35> >\");\\\r\n  /* Test variable precision at 2 different precisions - checks our ability to handle dynamic changes in precision */\\\r\n  mpfr_float::default_precision(20);\\\r\n  test(mpfr_float(), \"number<mpfr_float_backend<0> > (20-digit precision)\");\\\r\n  mpfr_float::default_precision(35);\\\r\n  test(mpfr_float(), \"number<mpfr_float_backend<0> > (35-digit precision)\");\r\n\r\ntypedef boost::multiprecision::number<boost::multiprecision::mpfr_float_backend<18> > test_type_1;\r\ntypedef boost::multiprecision::number<boost::multiprecision::mpfr_float_backend<30> > test_type_2;\r\ntypedef boost::multiprecision::number<boost::multiprecision::mpfr_float_backend<35> > test_type_3;\r\ntypedef boost::multiprecision::mpfr_float test_type_4;\r\n\r\n#else\r\n\r\n#define MPFR_TESTS\r\n\r\n#endif\r\n\r\n#ifdef TEST_BACKEND\r\n#include <boost/multiprecision/concepts/mp_number_archetypes.hpp>\r\n#endif\r\n#ifdef TEST_CPP_DEC_FLOAT\r\n#include <boost/multiprecision/cpp_dec_float.hpp>\r\n\r\n#define CPP_DEC_FLOAT_TESTS    test(number<cpp_dec_float<18> >(), \"number<cpp_dec_float<18> >\");\\\r\n   test(number<cpp_dec_float<30> >(), \"number<cpp_dec_float<30> >\");\\\r\n   test(number<cpp_dec_float<35, long long, std::allocator<void> > >(), \"number<cpp_dec_float<35, long long, std::allocator<void> > >\");\r\n\r\ntypedef boost::multiprecision::number<boost::multiprecision::cpp_dec_float<18> > test_type_1;\r\ntypedef boost::multiprecision::number<boost::multiprecision::cpp_dec_float<30> > test_type_2;\r\ntypedef boost::multiprecision::number<boost::multiprecision::cpp_dec_float<35, long long, std::allocator<void> > > test_type_3;\r\n\r\n#else\r\n\r\n#define CPP_DEC_FLOAT_TESTS\r\n\r\n#endif\r\n\r\n#ifdef TEST_CPP_BIN_FLOAT\r\n#include <boost/multiprecision/cpp_bin_float.hpp>\r\n#include <boost/multiprecision/debug_adaptor.hpp>\r\n\r\n//#define CPP_BIN_FLOAT_TESTS test(number<debug_adaptor<cpp_bin_float_quad::backend_type>, et_off>(), \"cpp_bin_float_quad\");\r\n#define CPP_BIN_FLOAT_TESTS test(cpp_bin_float_quad(), \"cpp_bin_float_quad\");\r\n\r\n//typedef boost::multiprecision::number<boost::multiprecision::debug_adaptor<boost::multiprecision::cpp_bin_float_quad::backend_type>, boost::multiprecision::et_off> test_type_1;\r\ntypedef boost::multiprecision::cpp_bin_float_quad test_type_1;\r\n\r\n#else\r\n\r\n#define CPP_BIN_FLOAT_TESTS\r\n\r\n#endif\r\n\r\n#ifdef TEST_FLOAT128\r\n#include <boost/multiprecision/float128.hpp>\r\n\r\n#define FLOAT128_TESTS test(float128(), \"float128\");\r\n\r\ntypedef boost::multiprecision::float128 test_type_1;\r\n\r\n#else\r\n\r\n#define FLOAT128_TESTS\r\n\r\n#endif\r\n\r\n\r\n#ifndef BOOST_MATH_TEST_TYPE\r\n#define BOOST_TEST_MAIN\r\n#include <boost/test/unit_test.hpp>\r\n#include <boost/test/floating_point_comparison.hpp>\r\n#endif\r\n\r\n#define ALL_TESTS \\\r\n MPF_TESTS\\\r\n MPFR_TESTS\\\r\n CPP_DEC_FLOAT_TESTS\\\r\n FLOAT128_TESTS\\\r\n CPP_BIN_FLOAT_TESTS\r\n\r\n#define ALL_SMALL_TESTS\\\r\n MPF_SMALL_TESTS\\\r\n MPFR_TESTS\\\r\n CPP_DEC_FLOAT_TESTS\\\r\n FLOAT128_TESTS\\\r\n CPP_BIN_FLOAT_TESTS\r\n\r\n#endif\r\n\r\n", "meta": {"hexsha": "f646ffe1d31a2d7efaf969a1d460167e5c117f4d", "size": 6066, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/multiprecision/test/math/setup.hpp", "max_stars_repo_name": "lijgame/boost", "max_stars_repo_head_hexsha": "ec2214a19cdddd1048058321a8105dd0231dac47", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-12-15T19:57:24.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-15T19:57:24.000Z", "max_issues_repo_path": "thirdparty-cpp/boost_1_62_0/libs/multiprecision/test/math/setup.hpp", "max_issues_repo_name": "nxplatform/nx-mobile", "max_issues_repo_head_hexsha": "0dc174c893f2667377cb2ef7e5ffeb212fa8b3e5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thirdparty-cpp/boost_1_62_0/libs/multiprecision/test/math/setup.hpp", "max_forks_repo_name": "nxplatform/nx-mobile", "max_forks_repo_head_hexsha": "0dc174c893f2667377cb2ef7e5ffeb212fa8b3e5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-03-08T11:06:22.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-08T11:06:22.000Z", "avg_line_length": 36.987804878, "max_line_length": 179, "alphanum_fraction": 0.7429937356, "num_tokens": 1564, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.46106292469982035}}
{"text": "#include <iostream>\n#include <typeinfo>\r\n#define BOOST_TEST_MODULE ImplicitMIAFunctionTests\n\r\n\n\n#include \"MIAConfig.h\"\n\n#ifdef MIA_USE_HEADER_ONLY_TESTS\r\n#include <boost/test/included/unit_test.hpp>\r\n#else\r\n#include <boost/test/unit_test.hpp>\r\n#endif\n\r\n\r\n#include \"ImplicitMIA.h\"\r\n#include \"DenseMIA.h\"\r\n#include \"LibMIAUtil.h\"\n#include \"Index.h\"\n\r\ntemplate<class _data_type>\r\nvoid functions_work(){\r\n\r\n\r\n\n\r\n    size_t dim1=2;\r\n    size_t dim2=3;\r\n    size_t dim3=4;\r\n\n    typedef LibMIA::ImplicitMIA<_data_type,3> MIAType;\r\n    typedef LibMIA::ImplicitMIA<_data_type,3,true> MIAType_ref;\r\n    typedef LibMIA::DenseMIA<_data_type,3> DenseMIAType;\r\n    typedef typename LibMIA::internal::index_type<MIAType>::type index_type;\r\n    typedef typename LibMIA::internal::function_type<MIAType>::type function_type;\r\n    typedef typename LibMIA::internal::function_type<MIAType_ref>::type function_type_ref;\r\n    function_type _func=[](index_type idx){\r\n        if(idx%2==0)\r\n            return 1;\r\n        else\r\n            return 2;\r\n    };\r\n    MIAType a(_func,dim1,dim2,dim3);\r\n    bool _correct=true;\r\n    for(auto it=a.data_begin();it<a.data_end();++it){\r\n        if((it-a.data_begin())%2==0){\r\n            if(*it!=1)\r\n                _correct=false;\r\n        }\r\n        else{\r\n            if(*it!=2)\r\n                _correct=false;\r\n        }\r\n\r\n    }\r\n    BOOST_CHECK_MESSAGE(_correct,std::string(\"Basic data iterator test for ImplicitMIA for \")+typeid(_data_type).name());\r\n\r\n    DenseMIAType dense_a(dim1,dim2,dim3);\r\n    for(size_t idx=0;idx<dense_a.dimensionality();++idx){\r\n        if(idx%2==0)\r\n            dense_a.atIdx(idx)=1;\r\n        else\r\n            dense_a.atIdx(idx)=2;\r\n\r\n    }\r\n    BOOST_CHECK_MESSAGE(a==dense_a,std::string(\"Basic ImplicitMIA Function Test for \")+typeid(_data_type).name());\r\n\r\n    //Now test ImplicitMIAs that refer to another piece of data\r\n    function_type_ref _func_ref=[&dense_a](index_type idx)->_data_type&{\r\n\r\n        return dense_a.atIdx(idx);;\r\n    };\r\n    MIAType_ref a_ref(_func_ref,dim1,dim2,dim3);\r\n    BOOST_CHECK_MESSAGE(a_ref==dense_a,std::string(\"Value test for ImplicitMIA with reference for \")+typeid(_data_type).name());\r\n    _correct=true;\r\n    for(size_t idx=0;idx<dense_a.dimensionality();++idx){\r\n        if(&(dense_a.atIdx(idx))!=&(a_ref.atIdx(idx))){\r\n            _correct=false;\r\n            break;\r\n        }\r\n\r\n    }\r\n    BOOST_CHECK_MESSAGE(_correct,std::string(\"Reference test for ImplicitMIA with reference for \")+typeid(_data_type).name());\r\n\r\n    //now test the assign to data_type operation - which implicity tests the iterators of ImplicitMIA\r\n    a_ref.fill(2);\r\n    _correct=true;\r\n    for(size_t idx=0;idx<a_ref.dimensionality();++idx){\r\n        if(a_ref.atIdx(idx)!=2){\r\n            _correct=false;\r\n            break;\r\n        }\r\n\r\n    }\r\n    BOOST_CHECK_MESSAGE(_correct,std::string(\"Basic assignment functionality test to referred data for ImplicitMIA with reference for \")+typeid(_data_type).name());\r\n    _correct=true;\r\n    for(size_t idx=0;idx<dense_a.dimensionality();++idx){\r\n        if(dense_a.atIdx(idx)!=2){\r\n            _correct=false;\r\n            break;\r\n        }\r\n\r\n    }\r\n\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE( ImplicitMIAFunctionTests )\n{\n\n\r\n\r\n    functions_work<double>();\r\n\n    functions_work<float>();\r\n    functions_work<int>();\r\n    functions_work<long>();\r\n\r\n\r\n\r\n\r\n\n\n}\n", "meta": {"hexsha": "668f622986b77e57248e424f5ed0fe9bbe341836", "size": 3362, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tests/ImplicitMIA/implicit_mia_functions.cpp", "max_stars_repo_name": "extragoya/LibNT", "max_stars_repo_head_hexsha": "60372bf4e3c5d6665185358c4756da4fe547f093", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-26T05:11:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-26T05:11:32.000Z", "max_issues_repo_path": "src/tests/ImplicitMIA/implicit_mia_functions.cpp", "max_issues_repo_name": "extragoya/LibNT", "max_issues_repo_head_hexsha": "60372bf4e3c5d6665185358c4756da4fe547f093", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/ImplicitMIA/implicit_mia_functions.cpp", "max_forks_repo_name": "extragoya/LibNT", "max_forks_repo_head_hexsha": "60372bf4e3c5d6665185358c4756da4fe547f093", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-09-21T15:38:23.000Z", "max_forks_repo_forks_event_max_datetime": "2017-09-21T15:38:23.000Z", "avg_line_length": 27.1129032258, "max_line_length": 165, "alphanum_fraction": 0.6326591315, "num_tokens": 845, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056295505783, "lm_q2_score": 0.6688802471698041, "lm_q1q2_score": 0.46106291986932824}}
{"text": "#include <iostream>\n#include <iomanip>\n#include <chrono>\n#include <stack>\n#include <armadillo>\n#include \"nanmath.h\"\n\nclass Clock {\npublic:\n    void tic() {\n        ts.push(std::chrono::high_resolution_clock::now());\n    }\n\n    long toc() {\n        if(ts.empty()) {\n            throw \"unmatched tic/toc\";\n        }\n        auto t0 = ts.top();\n        ts.pop();\n        auto t1 = std::chrono::high_resolution_clock::now();\n        return std::chrono::duration_cast<std::chrono::milliseconds>(t1 - t0).count();\n    }\nprivate:\n    std::stack<std::chrono::high_resolution_clock::time_point> ts;\n};\n\nint main(int argc, char *argv[]) {\n    if(argc != 2) {\n        std::cerr << \"usage: \" << argv[0] << \" <input_matrix>\" << std::endl;\n        return -1;\n    }\n\n    Clock clk;\n    arma::Mat<float> mf;\n    arma::Mat<double> md;\n    mf.load(argv[1]);\n    md.load(argv[1]);\n\n    unsigned n_rows = mf.n_rows, n_cols = mf.n_cols;\n    std::cout << \"processing \" << n_rows << \" x \" << n_cols << \" matrix\" << std::endl;\n    double sum = 0.0;\n    unsigned count = 0;\n\n    clk.tic();\n    {\n        sum = 0.0;\n        count = 0;\n        float corr;\n        unsigned cnt;\n        for(unsigned i = 0; i < n_cols; ++i) {\n            for(unsigned j = i + 1; j < n_cols; ++j) {\n                nan_corr_float(mf.colptr(i), mf.colptr(j), n_rows, &corr, &cnt);\n                sum += corr;\n                count += cnt;\n            }\n        }\n    }\n    std::cout << std::setw(32) << std::right << \"nan_corr_float: \"\n              << std::setw(12) << std::left << std::to_string(clk.toc()) + \" ms\"\n              << std::setw(12) << std::right << \"sum: \"\n              << std::setw(12) << std::left << sum\n              << std::setw(12) << std::right << \"count: \"\n              << std::setw(12) << std::left << count << std::endl;\n\n    clk.tic();\n    {\n        sum = 0.0;\n        count = 0;\n        float corr;\n        unsigned cnt;\n        for(unsigned i = 0; i < n_cols; ++i) {\n            for(unsigned j = i + 1; j < n_cols; ++j) {\n                nan_corr_float_avx(mf.colptr(i), mf.colptr(j), n_rows, &corr, &cnt);\n                sum += corr;\n                count += cnt;\n            }\n        }\n    }\n    std::cout << std::setw(32) << std::right << \"nan_corr_float_avx: \"\n              << std::setw(12) << std::left << std::to_string(clk.toc()) + \" ms\"\n              << std::setw(12) << std::right << \"sum: \"\n              << std::setw(12) << std::left << sum\n              << std::setw(12) << std::right << \"count: \"\n              << std::setw(12) << std::left << count << std::endl;\n\n    clk.tic();\n    {\n        sum = 0.0;\n        count = 0;\n        double corr;\n        unsigned cnt;\n        for(unsigned i = 0; i < n_cols; ++i) {\n            for(unsigned j = i + 1; j < n_cols; ++j) {\n                nan_corr_double(md.colptr(i), md.colptr(j), n_rows, &corr, &cnt);\n                sum += corr;\n                count += cnt;\n            }\n        }\n    }\n    std::cout << std::setw(32) << std::right << \"nan_corr_double: \"\n              << std::setw(12) << std::left << std::to_string(clk.toc()) + \" ms\"\n              << std::setw(12) << std::right << \"sum: \"\n              << std::setw(12) << std::left << sum\n              << std::setw(12) << std::right << \"count: \"\n              << std::setw(12) << std::left << count << std::endl;\n\n    clk.tic();\n    {\n        sum = 0.0;\n        count = 0;\n        double corr;\n        unsigned cnt;\n        for(unsigned i = 0; i < n_cols; ++i) {\n            for(unsigned j = i + 1; j < n_cols; ++j) {\n                nan_corr_double_avx(md.colptr(i), md.colptr(j), n_rows, &corr, &cnt);\n                sum += corr;\n                count += cnt;\n            }\n        }\n    }\n    std::cout << std::setw(32) << std::right << \"nan_corr_double_avx: \"\n              << std::setw(12) << std::left << std::to_string(clk.toc()) + \" ms\"\n              << std::setw(12) << std::right << \"sum: \"\n              << std::setw(12) << std::left << sum\n              << std::setw(12) << std::right << \"count: \"\n              << std::setw(12) << std::left << count << std::endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "a4e59106dca1cead232ea5937c4f0f672b3576fc", "size": 4104, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "benchmark.cpp", "max_stars_repo_name": "crtn/nanmath", "max_stars_repo_head_hexsha": "6239427564af286f5243caee4ed315f2f1865e11", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "benchmark.cpp", "max_issues_repo_name": "crtn/nanmath", "max_issues_repo_head_hexsha": "6239427564af286f5243caee4ed315f2f1865e11", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "benchmark.cpp", "max_forks_repo_name": "crtn/nanmath", "max_forks_repo_head_hexsha": "6239427564af286f5243caee4ed315f2f1865e11", "max_forks_repo_licenses": ["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.5692307692, "max_line_length": 86, "alphanum_fraction": 0.445662768, "num_tokens": 1185, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056040203135, "lm_q2_score": 0.6688802669716106, "lm_q1q2_score": 0.4610629164421346}}
{"text": "#pragma once\n\n// system includes ---------------------------------------------------------\n#include <fstream>\n#include <iostream>\n\n#include <boost/static_assert.hpp>\n#include <regex>\n\n// own includes ------------------------------------------------------------\n#include \"enum/enum.hpp\"\n#include \"spectral_basis.hpp\"\n#include \"spectral_basis_factory_base.hpp\"\n#include \"spectral_elem.hpp\"\n#include \"spectral_elem_accessor.hpp\"\n#include \"spectral_function.hpp\"\n\nnamespace boltzmann {\n\nnamespace local_ {\ntemplate <typename BASIS>\nstruct CMP\n{\n  /**\n   * @brief lexicographical ordering for basis elements\n   *\n   *\n   * @return\n   */\n  template <typename E>\n  bool operator()(const E& e1, const E& e2) const\n  {\n    int l1 = get_xi(e1).get_id().l;\n    int l2 = get_xi(e2).get_id().l;\n\n    int t1 = get_xi(e1).get_id().t;\n    int t2 = get_xi(e2).get_id().t;\n\n    int k1 = get_phi(e1).get_id().k;\n    int k2 = get_phi(e2).get_id().k;\n\n    if (l1 < l2)\n      return true;\n    else if (l1 == l2) {\n      if (k1 < k2) return true;\n      if (k1 == k2) return t1 < t2;\n    }\n    return false;\n  }\n\n private:\n  typename BASIS::elem_t::Acc::template get<XiR> get_xi;\n  typename BASIS::elem_t::Acc::template get<LaguerreRR> get_phi;\n};\n}  // end namespace local_\n\n// ----------------------------------------------------------------------\nclass SpectralBasisFactory : public SpectralBasisFactoryBase<XiR, LaguerreRR>\n{\n public:\n  /// definition of element ordering, TODO: define this at a global place\n  /**\n   *\n   *\n   * @param basis\n   * @param K\n   * @param L\n   * @param beta\n   * @param sorted sort basis functions by `l`, the angular index\n   */\n  static void create(basis_type& basis, int K, int L, double beta, bool sorted = true);\n\n  /**\n   *\n   *\n   * @param basis\n   * @param K\n   * @param L\n   * @param beta\n   * @param sorted sort basis functions by `l`, the angular index\n   */\n  static void create_test(basis_type& basis, int K, int L, double beta, bool sorted = true);\n\n  static void write_basis_descriptor(const basis_type& basis,\n                                     std::string fname = \"spectral_basis.desc\");\n\n  /**\n   * @brief read basis_descriptor file\n   *\n   * @param basis\n   * @param descriptor_file\n   */\n  static void create(basis_type& basis, std::string descriptor_file);\n} __attribute__((deprecated));\n\n// ----------------------------------------------------------------------\nvoid\nSpectralBasisFactory::create(basis_type& basis, int K, int L, double beta, bool sorted)\n{\n  for (int k = 0; k < K; ++k) {\n    if (k % 2 == 0) {\n      // l = 0\n      fa_type xir(0, 0);\n      fr_type phi(1. / beta, k);\n      basis.add_elem(xir, phi);\n    }\n    for (int l = 1; l <= L; ++l) {\n      for (int t = 0; t < 2; ++t) {\n        if (k % 2 == l % 2) {\n          fa_type xir(t, l);\n          fr_type phi(1. / beta, k);\n\n          basis.add_elem(xir, phi);\n        }\n      }\n    }\n  }\n\n  /// sort basis functions by l-index\n  if (sorted) {\n    basis.sort(local_::CMP<basis_type>());\n  }\n\n  basis.finalize();\n}\n\n// ----------------------------------------------------------------------\nvoid\nSpectralBasisFactory::create_test(basis_type& basis, int K, int L, double beta, bool sorted)\n{\n  for (int k = 0; k < K; ++k) {\n    if (k % 2 == 0) {\n      // l = 0\n      fa_type xir(0, 0);\n\n      double fw = 1. / beta;\n      if (k == 0 || k == 2) fw = 0;\n      fr_type phi(fw, k);\n      basis.add_elem(xir, phi);\n    }\n\n    for (int l = 1; l <= L; ++l) {\n      for (int t = 0; t < 2; ++t) {\n        if (k % 2 == l % 2) {\n          fa_type xir(t, l);\n          double fw = 1 / beta;\n          if (k == 1 && l == 1) fw = 0;\n          fr_type phi(fw, k);\n          basis.add_elem(xir, phi);\n        }\n      }\n    }\n  }\n\n  /// sort basis functions by l-index\n  if (sorted) {\n    basis.sort(local_::CMP<basis_type>());\n  }\n\n  basis.finalize();\n}\n\n// ----------------------------------------------------------------------\nvoid\nSpectralBasisFactory::write_basis_descriptor(const basis_type& basis, std::string fname)\n{\n  // typename elem_t::Acc::template get<fa_type> xir_getter;\n  // typename elem_t::Acc::template get<fr_type> rr_getter;\n  typename elem_t::Acc::get<fa_type> xir_getter;\n  typename elem_t::Acc::get<fr_type> rr_getter;\n\n  std::ofstream fout(fname);\n  for (auto it = basis.begin(); it != basis.end(); ++it) {\n    fout << xir_getter(*it).get_id() << \"\\t\" << rr_getter(*it).get_id() << std::endl;\n  }\n  fout.close();\n}\n\n// ----------------------------------------------------------------------\nvoid\nSpectralBasisFactory::create(basis_type& basis, std::string descriptor_file)\n{\n  std::ifstream ifile;\n  ifile.open(descriptor_file);\n  std::string line;\n\n  std::regex basisf_regex(\n      \"(cos|sin)_([0-9]+)[[:space:]]*[(]beta_([0-9.]+),[[:space:]]*k_([0-9]+)[)]\");\n  // new descriptor\n  std::regex basisf_regex_new(\n      \"(cos|sin)_([0-9.]+)[[:space:]]*[(]fw_([0-9.]+),[[:space:]]*k_([0-9]+)[)]\");\n  std::smatch basisf_match;\n\n  while (std::getline(ifile, line)) {\n    std::regex_search(line, basisf_match, basisf_regex);\n    if (basisf_match.size() > 0) {\n      auto sincos_match = basisf_match[1];\n      auto l_match = basisf_match[2];\n      auto beta_match = basisf_match[3];\n      auto k_match = basisf_match[4];\n      int l = atoi(l_match.str().c_str());\n      int k = atoi(k_match.str().c_str());\n      double beta = atof(beta_match.str().c_str());\n\n      fr_type phi(1. / beta, k);\n      if (sincos_match.str().compare(\"sin\") == 0) {\n        fa_type xir(TRIG::SIN, l);\n        basis.add_elem(xir, phi);\n      } else {\n        fa_type xir(TRIG::COS, l);\n        basis.add_elem(xir, phi);\n      }\n    }\n    // try to match new descriptor\n    std::regex_search(line, basisf_match, basisf_regex_new);\n    if (basisf_match.size() > 0) {\n      auto sincos_match = basisf_match[1];\n      // angular frequency\n      auto l_match = basisf_match[2];\n      int l = atoi(l_match.str().c_str());\n      // exponential weight\n      auto fw_match = basisf_match[3];\n      double fw = atof(fw_match.str().c_str());\n      // laguerre poly index\n      auto k_match = basisf_match[4];\n      int k = atoi(k_match.str().c_str());\n\n      fr_type phi(fw, k);\n      if (sincos_match.str().compare(\"sin\") == 0) {\n        fa_type xir(TRIG::SIN, l);\n        basis.add_elem(xir, phi);\n      } else {\n        fa_type xir(TRIG::COS, l);\n        basis.add_elem(xir, phi);\n      }\n    }\n  }\n\n  basis.finalize();\n  ifile.close();\n}\n\n}  // end namespace boltzmann\n", "meta": {"hexsha": "f87518496968a4654957fca2f0e464087ebafe0d", "size": 6437, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/spectral/basis/spectral_basis_factory.hpp", "max_stars_repo_name": "simonpp/2dBoltzmann", "max_stars_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/spectral/basis/spectral_basis_factory.hpp", "max_issues_repo_name": "simonpp/2dBoltzmann", "max_issues_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/spectral/basis/spectral_basis_factory.hpp", "max_forks_repo_name": "simonpp/2dBoltzmann", "max_forks_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.381147541, "max_line_length": 92, "alphanum_fraction": 0.5386049402, "num_tokens": 1868, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802471698041, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.4610629156001559}}
{"text": "/*\n  Copyright (C) 2017 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#include <boost/range/irange.hpp>\n\n#include <test/catch.hpp>\n#include <base/types.hpp>\n#include <base/error.hpp>\n#include <time/daycounters/one.hpp>\n\nusing namespace MathFin;\n\n#define EPS 1.0E-12\n\nTEST_CASE(\"OneDayCounter\", \"[daycounters]\") {\n  Period p[] = {\n    Period(3, TimeUnit::Months),\n    Period(6, TimeUnit::Months),\n    Period(1, TimeUnit::Years)\n  };\n\n  Time expected[] = { 1.0, 1.0, 1.0 };\n  Date first(1, Month::January, 2004);\n  Date last(31, Month::December, 2004);\n\n  // generate dates from [first, last]\n  int days = last - first + 1;\n  std::vector<Date> dates;\n  for (auto i : boost::irange(0, days)) {\n    dates.push_back(first + i);\n  }\n\n  REQUIRE(dates[dates.size() - 1] == last);\n\n  DayCounter dayCounter = OneDayCounter();\n\n  int n = sizeof(p) / sizeof(Period);\n  for (Date& start : dates) {\n    for (auto i : boost::irange(0, n)) {\n      Date end = start + p[i];\n      Time calcualted = dayCounter.yearFraction(start, end);\n      REQUIRE(std::fabs(calcualted - expected[i]) <= EPS);\n    }\n  }\n}\n", "meta": {"hexsha": "66fa8b7ca3bc59cbed5a05b4252e8fe3e9431e95", "size": 1748, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "time/daycounters/oneTest.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/daycounters/oneTest.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/daycounters/oneTest.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": 28.1935483871, "max_line_length": 74, "alphanum_fraction": 0.6693363844, "num_tokens": 496, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.6893056040203135, "lm_q1q2_score": 0.4610629118923026}}
{"text": "/*\n * GeneralR_TreeManager.hpp\n *\n *  Created on: Nov 14, 2016\n *      Author: zhang huai peng\n */\n\n#ifndef GENERALRTREEMANAGER_HPP_\n#define GENERALRTREEMANAGER_HPP_\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point.hpp>\n#include <boost/geometry/geometries/box.hpp>\n#include <boost/geometry/index/rtree.hpp>\n#include <vector>\n\nnamespace bg = boost::geometry;\nnamespace bgi = boost::geometry::index;\nnamespace sim_mob {\n\nusing R_Point = bg::model::point<float, 2, bg::cs::cartesian>;\nusing R_Box = bg::model::box<R_Point>;\ntemplate<typename T> using R_Value = std::pair<R_Box, const T*>;\ntemplate<typename T> using R_Tree = bgi::rtree<R_Value<T>, bgi::linear<16> >;\n\ntemplate<typename T>\nclass GeneralR_TreeManager {\npublic:\n    GeneralR_TreeManager();\n    virtual ~GeneralR_TreeManager();\n\n    /**\n     * Update all objects into r-tree.\n     * @param objectsForR_Tree is a container including all objects into r-tree\n     */\n    void update(const std::set<T*> &objectsForR_Tree);\n\n    /**\n     * Return a collection of objects that are located in the axially-aligned rectangle.\n     * @param lowerLeft The lower left corner of the axially-aligned search rectangle.\n     * @param upperRight The upper right corner of the axially-aligned search rectangle.\n     * @return a collection of objects\n     * The caller is responsible to determine the \"type\" of each object in the returned array.\n     */\n    std::vector<T const *> objectsInBox(const R_Point &lowerLeft, const R_Point &upperRight) const;\n\n    /**\n     * Return nearest object\n     * @param xLocation is x coordinate of central location\n     * @param yLocation is y coordinate of central location\n     * @return nearest object if existed. otherwise nullptr\n     */\n    const T* searchNearestObject(double xLocation, double yLocation) const;\n\nprivate:\n    /**Internal r-tree to store objects*/\n    R_Tree<T>* rTree;\n};\n\n}\n#define _CLASS_RTREE_GENERAL_FUNCTIONS\n#include \"GeneralR_TreeManager.cpp\"\n#endif /* GENERALRTREEMANAGER_HPP_ */\n", "meta": {"hexsha": "e1b04635c96b26b6da310b3b08871f638a5b80a5", "size": 2013, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dev/Basic/shared/spatial_trees/GeneralR_TreeManager.hpp", "max_stars_repo_name": "gusugusu1018/simmobility-prod", "max_stars_repo_head_hexsha": "d30a5ba353673f8fd35f4868c26994a0206a40b6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 50.0, "max_stars_repo_stars_event_min_datetime": "2018-12-21T08:21:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T09:47:59.000Z", "max_issues_repo_path": "dev/Basic/shared/spatial_trees/GeneralR_TreeManager.hpp", "max_issues_repo_name": "gusugusu1018/simmobility-prod", "max_issues_repo_head_hexsha": "d30a5ba353673f8fd35f4868c26994a0206a40b6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-12-19T13:42:47.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-13T04:11:45.000Z", "max_forks_repo_path": "dev/Basic/shared/spatial_trees/GeneralR_TreeManager.hpp", "max_forks_repo_name": "gusugusu1018/simmobility-prod", "max_forks_repo_head_hexsha": "d30a5ba353673f8fd35f4868c26994a0206a40b6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2018-11-28T07:30:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-05T02:22:26.000Z", "avg_line_length": 31.9523809524, "max_line_length": 99, "alphanum_fraction": 0.7198211624, "num_tokens": 493, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.668880247169804, "lm_q2_score": 0.6893056167854461, "lm_q1q2_score": 0.46106291133098337}}
{"text": "/*\n * \n * Copyright (c) Kresimir Fresl 2002 \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 * Author acknowledges the support of the Faculty of Civil Engineering, \n * University of Zagreb, Croatia.\n *\n */\n\n#ifndef BOOST_NUMERIC_BINDINGS_CBLAS_LEVEL_1_HPP\n#define BOOST_NUMERIC_BINDINGS_CBLAS_LEVEL_1_HPP\n\n#include <cassert>\n\n#include <boost/numeric/bindings/traits/type_traits.hpp>\n#include <boost/numeric/bindings/traits/vector_traits.hpp>\n#include <boost/numeric/bindings/atlas/cblas1_overloads.hpp>\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_TYPE_CHECK\n#  include <boost/type_traits/same_traits.hpp>\n#  include <boost/static_assert.hpp>\n#endif \n\nnamespace boost { namespace numeric { namespace bindings { \n\n  namespace atlas {\n\n    // x_i <- alpha for all i\n    template <typename T, typename Vct> \n    inline \n    void set (T const& alpha, Vct& x) {\n      detail::set (traits::vector_size (x), alpha, \n                   traits::vector_storage (x), traits::vector_stride (x)); \n    }\n\n    // y <- x\n    template <typename VctX, typename VctY>\n    inline \n    void copy (VctX const& x, VctY& y) {\n      assert (traits::vector_size (y) >= traits::vector_size (x));\n      detail::copy (traits::vector_size (x),\n#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n                    traits::vector_storage (x), \n#else\n                    traits::vector_storage_const (x), \n#endif \n                    traits::vector_stride (x), \n                    traits::vector_storage (y), traits::vector_stride (y)); \n    }\n\n    // x <-> y\n    template <typename VctX, typename VctY>\n    inline \n    void swap (VctX& x, VctY& y) {\n      assert (traits::vector_size (y) >= traits::vector_size (x));\n      detail::swap (traits::vector_size (x),\n                    traits::vector_storage (x), traits::vector_stride (x), \n                    traits::vector_storage (y), traits::vector_stride (y)); \n    }\n\n    // x <- alpha * x\n    template <typename T, typename Vct> \n    inline \n    void scal (T const& alpha, Vct& x) {\n#ifndef BOOST_NUMERIC_BINDINGS_NO_TYPE_CHECK\n      typedef traits::vector_traits<Vct> vtraits;\n      BOOST_STATIC_ASSERT(\n       (boost::is_same<T, typename vtraits::value_type>::value\n        || \n        boost::is_same<T, \n          typename traits::type_traits<typename vtraits::value_type>::real_type\n        >::value\n        ));\n#endif \n      detail::scal (traits::vector_size (x), alpha, \n                    traits::vector_storage (x), traits::vector_stride (x)); \n    }\n\n    // y <- alpha * x + y\n    template <typename T, typename VctX, typename VctY>\n    inline \n    void axpy (T const& alpha, VctX const& x, VctY& y) {\n      assert (traits::vector_size (y) >= traits::vector_size (x));\n      detail::axpy (traits::vector_size (x), alpha, \n#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n                    traits::vector_storage (x), \n#else\n                    traits::vector_storage_const (x), \n#endif\n                    traits::vector_stride (x), \n                    traits::vector_storage (y), traits::vector_stride (y)); \n    }\n\n    // y <- x + y\n    template <typename VctX, typename VctY>\n    inline \n    void xpy (VctX const& x, VctY& y) {\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n      typedef typename traits::vector_traits<VctX>::value_type val_t; \n#else\n      typedef typename VctX::value_type val_t; \n#endif\n      axpy ((val_t) 1, x, y); \n    }\n\n    // y <- alpha * x + beta * y\n    template <typename T, typename VctX, typename VctY>\n    inline \n    void axpby (T const& alpha, VctX const& x, \n                T const& beta, VctY& y) { \n      assert (traits::vector_size (y) >= traits::vector_size (x));\n      detail::axpby (traits::vector_size (x), alpha, \n#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n                     traits::vector_storage (x), \n#else\n                     traits::vector_storage_const (x), \n#endif\n                     traits::vector_stride (x), \n                     beta, \n                     traits::vector_storage (y), traits::vector_stride (y)); \n    }\n\n    ///////////////////////////////////////////\n\n    // dot <- x^T * y \n    // .. real & complex types\n    template <typename VctX, typename VctY>\n    inline \n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n    typename traits::vector_traits<VctX>::value_type \n#else\n    typename VctX::value_type \n#endif\n    dot (VctX const& x, VctY const& y) {\n      assert (traits::vector_size (y) >= traits::vector_size (x));\n      return detail::dot (traits::vector_size (x),\n#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n                          traits::vector_storage (x), \n#else\n                          traits::vector_storage_const (x), \n#endif\n                          traits::vector_stride (x), \n#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n                          traits::vector_storage (y), \n#else\n                          traits::vector_storage_const (y), \n#endif\n                          traits::vector_stride (y)); \n    }\n\n    // dot <- x^T * y \n    // .. float only -- with double accumulation\n    template <typename VctX, typename VctY>\n    inline \n    double dsdot (VctX const& x, VctY const& y) {\n      assert (traits::vector_size (y) >= traits::vector_size (x));\n      return cblas_dsdot (traits::vector_size (x),\n#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n                          traits::vector_storage (x), \n#else\n                          traits::vector_storage_const (x), \n#endif\n                          traits::vector_stride (x), \n#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n                          traits::vector_storage (y), \n#else\n                          traits::vector_storage_const (y), \n#endif\n                          traits::vector_stride (y)); \n    }\n\n    // apdot <- alpha + x^T * y    \n    // .. float only -- computation uses double precision \n    template <typename VctX, typename VctY>\n    inline \n    float sdsdot (float const alpha, VctX const& x, VctY const& y) {\n      assert (traits::vector_size (y) >= traits::vector_size (x));\n      return cblas_sdsdot (traits::vector_size (x), alpha, \n#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n                           traits::vector_storage (x), \n#else\n                           traits::vector_storage_const (x), \n#endif\n                           traits::vector_stride (x), \n#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n                           traits::vector_storage (y), \n#else\n                           traits::vector_storage_const (y), \n#endif\n                           traits::vector_stride (y)); \n    }\n\n    // dotu <- x^T * y \n    // .. complex types only\n    // .. function\n    template <typename VctX, typename VctY>\n    inline \n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n    typename traits::vector_traits<VctX>::value_type \n#else\n    typename VctX::value_type \n#endif\n    dotu (VctX const& x, VctY const& y) {\n      assert (traits::vector_size (y) >= traits::vector_size (x));\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n      typename traits::vector_traits<VctX>::value_type val;\n#else\n      typename VctX::value_type val; \n#endif\n      detail::dotu (traits::vector_size (x),\n#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n                    traits::vector_storage (x), \n#else\n                    traits::vector_storage_const (x), \n#endif\n                    traits::vector_stride (x), \n#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n                    traits::vector_storage (y), \n#else\n                    traits::vector_storage_const (y), \n#endif\n                    traits::vector_stride (y), \n                    &val);\n      return val; \n    }\n    // .. procedure \n    template <typename VctX, typename VctY>\n    inline \n    void dotu (VctX const& x, VctY const& y, \n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n               typename traits::vector_traits<VctX>::value_type& val\n#else\n               typename VctX::value_type& val\n#endif\n    ) {\n      assert (traits::vector_size (y) >= traits::vector_size (x));\n      detail::dotu (traits::vector_size (x),\n#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n                    traits::vector_storage (x), \n#else\n                    traits::vector_storage_const (x), \n#endif\n                    traits::vector_stride (x), \n#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n                    traits::vector_storage (y), \n#else\n                    traits::vector_storage_const (y), \n#endif\n                    traits::vector_stride (y), \n                    &val);\n    }\n\n    // dotc <- x^H * y \n    // .. complex types only\n    // .. function\n    template <typename VctX, typename VctY>\n    inline \n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n    typename traits::vector_traits<VctX>::value_type \n#else\n    typename VctX::value_type \n#endif\n    dotc (VctX const& x, VctY const& y) {\n      assert (traits::vector_size (y) >= traits::vector_size (x));\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n      typename traits::vector_traits<VctX>::value_type val;\n#else\n      typename VctX::value_type val; \n#endif\n      detail::dotc (traits::vector_size (x),\n#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n                    traits::vector_storage (x), \n#else\n                    traits::vector_storage_const (x), \n#endif\n                    traits::vector_stride (x), \n#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n                    traits::vector_storage (y), \n#else\n                    traits::vector_storage_const (y), \n#endif\n                    traits::vector_stride (y),\n                    &val);\n      return val; \n    }\n    // .. procedure \n    template <typename VctX, typename VctY>\n    inline \n    void dotc (VctX const& x, VctY const& y, \n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n               typename traits::vector_traits<VctX>::value_type& val\n#else\n               typename VctX::value_type& val\n#endif\n    ) {\n      assert (traits::vector_size (y) >= traits::vector_size (x));\n      detail::dotc (traits::vector_size (x),\n#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n                    traits::vector_storage (x), \n#else\n                    traits::vector_storage_const (x), \n#endif\n                    traits::vector_stride (x), \n#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n                    traits::vector_storage (y), \n#else\n                    traits::vector_storage_const (y), \n#endif\n                    traits::vector_stride (y), \n                    &val);\n    }\n\n    // nrm2 <- ||x||_2\n    template <typename Vct> \n    inline \n    typename traits::type_traits<\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n      typename traits::vector_traits<Vct>::value_type \n#else \n      typename Vct::value_type \n#endif \n    >::real_type \n    nrm2 (Vct const& x) {\n      return detail::nrm2 (traits::vector_size (x),\n#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n                           traits::vector_storage (x), \n#else\n                           traits::vector_storage_const (x), \n#endif\n                           traits::vector_stride (x)); \n    }\n\n    // asum <- ||re (x)|| + ||im (x)||\n    template <typename Vct> \n    inline \n    typename traits::type_traits<\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n      typename traits::vector_traits<Vct>::value_type \n#else \n      typename Vct::value_type \n#endif \n    >::real_type  \n    asum (Vct const& x) {\n      return detail::asum (traits::vector_size (x),\n#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n                           traits::vector_storage (x), \n#else\n                           traits::vector_storage_const (x), \n#endif\n                           traits::vector_stride (x)); \n    }\n\n    // iamax <- 1st i: max (|re (x_i)| + |im (x_i)|)\n    template <typename Vct> \n    inline \n    CBLAS_INDEX iamax (Vct const& x) {\n      return detail::iamax (traits::vector_size (x),\n#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n                            traits::vector_storage (x), \n#else\n                            traits::vector_storage_const (x), \n#endif\n                            traits::vector_stride (x)); \n    }\n\n    // TO DO: plane rotations \n\n  } // namespace atlas\n\n}}} \n\n#endif // BOOST_NUMERIC_BINDINGS_CBLAS_LEVEL_1_HPP\n", "meta": {"hexsha": "1159021362e9eb42e6d306fbdd0c02094495293f", "size": 12195, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/boost/numeric/bindings/atlas/cblas1.hpp", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "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/atlas/cblas1.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/atlas/cblas1.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-11-23T09:56:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-23T09:56:06.000Z", "avg_line_length": 32.3474801061, "max_line_length": 79, "alphanum_fraction": 0.5936859369, "num_tokens": 2970, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.668880247169804, "lm_q2_score": 0.6893056104028797, "lm_q1q2_score": 0.4610629070618108}}
{"text": "#include <vector>\n#include <sstream>\n#define EIGEN_QUATERNION_PLUGIN <quaternion_plugin.h>\n#include <Eigen/Dense>\n#define private public\n#include \"DualQuaternion.h\"\n#undef private\n#include <pybind11/pybind11.h>\n#include <pybind11/eigen.h>\n#include <pybind11/operators.h>\n\nnamespace py = pybind11;\nusing namespace Eigen;\ntypedef double Float;\n\nPYBIND11_MODULE(_eigen_dq, m) {\n    py::class_<Quaternion<Float> >(m, \"quat\")\n      .def(py::init<>())\n      .def(py::init<Float, Float, Float, Float>())\n      .def(py::init<Matrix<Float, 4, 1>&>())\n      .def(py::init<Matrix<Float, 3, 3>&>())\n      .def(py::init([](Float ang, Matrix<Float, 3, 1>& axis) {\n          return std::unique_ptr<Quaternion<Float>>(new Quaternion<Float>(AngleAxis<Float>(ang, axis)));}))\n      .def_property(\"data\", &Quaternion<Float>::getData, &Quaternion<Float>::setData)\n      .def_property(\"w\", &Quaternion<Float>::getW, &Quaternion<Float>::setW)\n      .def_property(\"x\", &Quaternion<Float>::getX, &Quaternion<Float>::setX)\n      .def_property(\"y\", &Quaternion<Float>::getY, &Quaternion<Float>::setY)\n      .def_property(\"z\", &Quaternion<Float>::getZ, &Quaternion<Float>::setZ)\n      .def_property(\"vec\", &Quaternion<Float>::getVec, &Quaternion<Float>::setVec)\n      .def_static(\"identity\", &Quaternion<Float>::Identity)\n      .def(\"set_identity\", &Quaternion<Float>::setIdentity)\n      .def(\"squared_norm\", &Quaternion<Float>::squaredNorm)\n      .def(\"norm\", &Quaternion<Float>::norm)\n      .def(\"normalize\", &Quaternion<Float>::normalize)\n      .def(\"normalized\", &Quaternion<Float>::normalized)\n      .def(\"angular_distance\", &Quaternion<Float>::angularDistance<Quaternion<Float>>)\n      .def(\"dot\", &Quaternion<Float>::dot<Quaternion<Float>>)\n      .def(\"slerp\", &Quaternion<Float>::slerp<Quaternion<Float>>)\n      .def(\"to_rotation_matrix\", &Quaternion<Float>::toRotationMatrix)\n      .def(\"conjugate\", &Quaternion<Float>::conjugate)\n      .def(\"inverse\", &Quaternion<Float>::inverse)\n      .def(py::self * py::self)\n      .def(py::self *= py::self)\n      .def(\"__repr__\", [](const Quaternion<Float>& inst) {\n          std::stringstream ss;\n          ss << \"< \" << inst.getData().transpose() << \" >\";\n          return ss.str();\n        });\n\n    py::class_<DualQuaternion<Float> >(m, \"dualquat\")\n      .def(py::init<>())\n      .def(py::init<Quaternion<Float>&, Quaternion<Float>&>())\n      .def(py::init<Quaternion<Float>&, Matrix<Float, 3, 1>&>())\n      .def(py::init([](Quaternion<Float>& q) {\n           return std::unique_ptr<DualQuaternion<Float>>(new DualQuaternion<Float>(q, Matrix<Float, 3, 1>::Zero()));}))\n      .def_readwrite(\"real\", &DualQuaternion<Float>::m_real)\n      .def_readwrite(\"dual\", &DualQuaternion<Float>::m_dual)\n      .def_static(\"zeros\", &DualQuaternion<Float>::zeros)\n      .def_static(\"identity\", &DualQuaternion<Float>::identity)\n      .def(py::self + py::self)\n      .def(py::self - py::self)\n      .def(py::self * Float())\n      .def(Float() * py::self)\n      .def(py::self * py::self)\n      .def(\"from_screw\", &DualQuaternion<Float>::fromScrew)\n      .def(\"conjugate\", &DualQuaternion<Float>::conjugate)\n      .def(\"norm\", [](DualQuaternion<Float>& inst) {\n           Float x, y; inst.norm(x, y); return std::make_tuple(x, y);\n        })\n      .def(\"normalize\", &DualQuaternion<Float>::normalize)\n      .def(\"normalized\", &DualQuaternion<Float>::normalized)\n      .def(\"transform_point\", &DualQuaternion<Float>::transformPoint)\n      .def(\"transform_vector\", &DualQuaternion<Float>::transformVector)\n      .def(\"inverse\", &DualQuaternion<Float>::inverse)\n      .def(\"exp\", &DualQuaternion<Float>::exp)\n      .def(\"log\", &DualQuaternion<Float>::log)\n      .def(\"pow\", [](DualQuaternion<Float>& inst, Float t) {return (inst.log() * t).exp();})\n      .def(\"rotation\", &DualQuaternion<Float>::rotation)\n      .def(\"translation\", &DualQuaternion<Float>::translation)\n      .def(\"translation_quaternion\", &DualQuaternion<Float>::translationQuaternion)\n      .def(\"to_matrix\", &DualQuaternion<Float>::toMatrix)\n      .def(\"__repr__\", [](const DualQuaternion<Float>& inst) {\n          std::stringstream ss;\n          ss << \"<real: \" << inst.real().getData().transpose()\n             << \", dual: \"<< inst.dual().getData().transpose() << \" >\";\n          return ss.str();\n        });\n\n    m.def(\"expq\", &expq<Float>);\n    m.def(\"logq\", &logq<Float>);\n\n#ifdef VERSION_INFO\n    m.attr(\"__version__\") = VERSION_INFO;\n#else\n    m.attr(\"__version__\") = \"dev\";\n#endif\n}\n", "meta": {"hexsha": "42e9b7a122265a0a190dc40151154de0d36c15db", "size": 4464, "ext": "cc", "lang": "C++", "max_stars_repo_path": "dq3d/dual_quaternion_py.cc", "max_stars_repo_name": "neka-nat/dq3d", "max_stars_repo_head_hexsha": "365c363a47e3ec60fce0bf7b260f1e59d3556b24", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2019-01-21T05:31:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:44:59.000Z", "max_issues_repo_path": "dq3d/dual_quaternion_py.cc", "max_issues_repo_name": "neka-nat/dq3d", "max_issues_repo_head_hexsha": "365c363a47e3ec60fce0bf7b260f1e59d3556b24", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-06-07T13:03:20.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-20T14:57:58.000Z", "max_forks_repo_path": "dq3d/dual_quaternion_py.cc", "max_forks_repo_name": "neka-nat/dq3d", "max_forks_repo_head_hexsha": "365c363a47e3ec60fce0bf7b260f1e59d3556b24", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-01-23T19:57:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-01T21:41:48.000Z", "avg_line_length": 45.5510204082, "max_line_length": 119, "alphanum_fraction": 0.627016129, "num_tokens": 1164, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4610349406317222}}
{"text": "#ifndef __compiler_rt_fp_128_h__\n#define __compiler_rt_fp_128_h__\n\n#include <limits.h>\n#include <stdint.h>\n#include \"../softfloat/source/include/softfloat.h\"\n#ifdef _MSC_VER\n#include <boost/multiprecision/cpp_int.hpp>\ntypedef boost::multiprecision::int128_t int128_t;\ntypedef boost::multiprecision::uint128_t uint128_t;\n#endif\n\n#ifdef _MSC_VER\n#define REP_C (int128_t)\n#else\n#define REP_C (__int128)\n#endif\n#define significandBits 112\n#ifdef _MSC_VER\n#define typeWidth       (sizeof(int128_t)*CHAR_BIT)\n#else\n#define typeWidth       (sizeof(__int128)*CHAR_BIT)\n#endif\n#define exponentBits    (typeWidth - significandBits - 1)\n#define maxExponent     ((1 << exponentBits) - 1)\n#define exponentBias    (maxExponent >> 1)\n\n#define implicitBit     (REP_C(1) << significandBits)\n#define significandMask (implicitBit - 1U)\n#define signBit         (REP_C(1) << (significandBits + exponentBits))\n#define absMask         (signBit - 1U)\n#define exponentMask    (absMask ^ significandMask)\n#define oneRep          ((rep_t)exponentBias << significandBits)\n#define infRep          exponentMask\n#define quietBit        (implicitBit >> 1)\n#define qnanRep         (exponentMask | quietBit)\n\n#ifdef _MSC_VER\nstatic __inline int128_t toRep(float128_t x) {\n\tunion { float128_t f; int128_t i; } rep = { x };\n    return rep.i;\n}\n#else\nstatic __inline __int28 toRep(float128_t x) {\n\tconst union { float128_t f; __int28 i; } rep = { .f = x };\n\treturn rep.i;\n}\n#endif\n\n#endif //__compiler_rt_fp_h__\n", "meta": {"hexsha": "36a6b1ca23230048b1034126fddd45a6e9c961af", "size": 1475, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libraries/builtins/fp128.hpp", "max_stars_repo_name": "jxlczjp77/eos", "max_stars_repo_head_hexsha": "75437df5e4b584fc52d8160efe29aff30b656ff6", "max_stars_repo_licenses": ["MIT"], "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/builtins/fp128.hpp", "max_issues_repo_name": "jxlczjp77/eos", "max_issues_repo_head_hexsha": "75437df5e4b584fc52d8160efe29aff30b656ff6", "max_issues_repo_licenses": ["MIT"], "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/builtins/fp128.hpp", "max_forks_repo_name": "jxlczjp77/eos", "max_forks_repo_head_hexsha": "75437df5e4b584fc52d8160efe29aff30b656ff6", "max_forks_repo_licenses": ["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.9215686275, "max_line_length": 70, "alphanum_fraction": 0.7206779661, "num_tokens": 404, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.46103494063172207}}
{"text": "#include <dlib/graph_utils.h>\n#include <dlib/image_io.h>\n#include \"facerec.h\"\n#include \"utils.h\"\n\nusing namespace dlib;\n\nstd::vector<image_t> jitter_image(\n    const image_t& img,\n    int count\n)\n{\n    // All this function does is make count copies of img, all slightly jittered by being\n    // zoomed, rotated, and translated a little bit differently. They are also randomly\n    // mirrored left to right.\n    thread_local dlib::rand rnd;\n\n    std::vector<image_t> crops;\n    for (int i = 0; i < count; ++i)\n        crops.push_back(jitter_image(img,rnd));\n\n    return crops;\n}\n\n// Helper function to estimage the age\nuint8_t get_estimated_age(matrix<float, 1, number_of_age_classes>& p, float& confidence)\n{\n\tfloat estimated_age = (0.25f * p(0));\n\tconfidence = p(0);\n\n\tfor (uint16_t i = 1; i < number_of_age_classes; i++) {\n\t\testimated_age += (static_cast<float>(i) * p(i));\n\t\tif (p(i) > confidence) confidence = p(i);\n\t}\n\n\treturn std::lround(estimated_age);\n}\n", "meta": {"hexsha": "fb64ae462b239dc4f7b98f350ac68dace2775b39", "size": 962, "ext": "cc", "lang": "C++", "max_stars_repo_path": "utils.cc", "max_stars_repo_name": "silverark/alt-go-face", "max_stars_repo_head_hexsha": "ac3f5781623aa87b108df5ed79d55ae87dac26d0", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-04-23T12:53:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-11T13:03:37.000Z", "max_issues_repo_path": "utils.cc", "max_issues_repo_name": "silverark/alt-go-face", "max_issues_repo_head_hexsha": "ac3f5781623aa87b108df5ed79d55ae87dac26d0", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "utils.cc", "max_forks_repo_name": "silverark/alt-go-face", "max_forks_repo_head_hexsha": "ac3f5781623aa87b108df5ed79d55ae87dac26d0", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-08-24T21:29:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-14T23:44:24.000Z", "avg_line_length": 25.3157894737, "max_line_length": 89, "alphanum_fraction": 0.6808731809, "num_tokens": 270, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059414036511, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.46103493494631004}}
{"text": "// Copyright (c) 2022 CNES\r\n//\r\n// All rights reserved. Use of this source code is governed by a\r\n// BSD-style license that can be found in the LICENSE file.\r\n#pragma once\r\n#include <pybind11/numpy.h>\r\n\r\n#include <Eigen/Core>\r\n#include <boost/geometry.hpp>\r\n#include <iostream>\r\n#include <optional>\r\n\r\n#include \"pyinterp/axis.hpp\"\r\n#include \"pyinterp/detail/broadcast.hpp\"\r\n#include \"pyinterp/detail/geometry/point.hpp\"\r\n#include \"pyinterp/detail/math/binning.hpp\"\r\n#include \"pyinterp/detail/math/descriptive_statistics.hpp\"\r\n#include \"pyinterp/eigen.hpp\"\r\n#include \"pyinterp/geodetic/system.hpp\"\r\n\r\nnamespace pyinterp {\r\n\r\n/// Group a number of more or less continuous values into a smaller number of\r\n/// \"bins\" located on a grid.\r\ntemplate <typename T>\r\nclass Binning2D {\r\n public:\r\n  /// Statistics handled by this object.\r\n  using Accumulators = detail::math::Accumulators<T>;\r\n  using DescriptiveStatistics = detail::math::DescriptiveStatistics<T>;\r\n\r\n  /// Default constructor\r\n  ///\r\n  /// @param x Definition of the bin centers for the X axis of the grid.\r\n  /// @param y Definition of the bin centers for the Y axis of the grid.\r\n  /// @param wgs WGS of the coordinate system used to manipulate geographic\r\n  /// coordinates. If this parameter is not set, the handled coordinates will be\r\n  /// considered as Cartesian coordinates. Otherwise, \"x\" and \"y\" are considered\r\n  /// to represents the longitudes and latitudes on a grid.\r\n  Binning2D(std::shared_ptr<Axis<double>> x, std::shared_ptr<Axis<double>> y,\r\n            std::optional<geodetic::System> wgs)\r\n      : x_(std::move(x)),\r\n        y_(std::move(y)),\r\n        acc_(x_->size(), y_->size()),\r\n        wgs_(std::move(wgs)) {}\r\n\r\n  /// Default destructor\r\n  virtual ~Binning2D() = default;\r\n\r\n  /// Copy constructor\r\n  ///\r\n  /// @param rhs right value\r\n  Binning2D(const Binning2D& rhs) = delete;\r\n\r\n  /// Move constructor\r\n  ///\r\n  /// @param rhs right value\r\n  Binning2D(Binning2D&& rhs) noexcept = delete;\r\n\r\n  /// Copy assignment operator\r\n  ///\r\n  /// @param rhs right value\r\n  auto operator=(const Binning2D& rhs) -> Binning2D& = delete;\r\n\r\n  /// Move assignment operator\r\n  ///\r\n  /// @param rhs right value\r\n  auto operator=(Binning2D&& rhs) noexcept -> Binning2D& = delete;\r\n\r\n  /// Inserts new values in the grid from Z values for X, Y data coordinates.\r\n  void push(const pybind11::array_t<T>& x, const pybind11::array_t<T>& y,\r\n            const pybind11::array_t<T>& z, const bool simple) {\r\n    detail::check_array_ndim(\"x\", 1, x, \"y\", 1, y, \"z\", 1, z);\r\n    detail::check_ndarray_shape(\"x\", x, \"y\", y, \"z\", z);\r\n\r\n    if (simple) {\r\n      // Nearest\r\n      push_nearest(x, y, z);\r\n    } else if (!wgs_) {\r\n      // Cartesian linear\r\n      push_linear<detail::geometry::Point2D,\r\n                  boost::geometry::strategy::area::cartesian<>>(\r\n          x, y, z, boost::geometry::strategy::area::cartesian<>());\r\n    } else {\r\n      // Geographic linear\r\n      auto strategy = boost::geometry::strategy::area::geographic<\r\n          boost::geometry::strategy::vincenty, 5>(\r\n          boost::geometry::srs::spheroid(wgs_->semi_major_axis(),\r\n                                         wgs_->semi_minor_axis()));\r\n      push_linear<detail::geometry::GeographicPoint2D,\r\n                  boost::geometry::strategy::area::geographic<\r\n                      boost::geometry::strategy::vincenty, 5>>(x, y, z,\r\n                                                               strategy);\r\n    }\r\n  }\r\n\r\n  /// Reset the statistics.\r\n  void clear() {\r\n    acc_ = std::move(Matrix<DescriptiveStatistics>(x_->size(), y_->size()));\r\n  }\r\n\r\n  /// Compute the count of points within each bin.\r\n  [[nodiscard]] auto count() const -> pybind11::array_t<uint64_t> {\r\n    return calculate_statistics<decltype(&DescriptiveStatistics::count),\r\n                                uint64_t>(&DescriptiveStatistics::count);\r\n  }\r\n\r\n  /// Compute the minimum of values for points within each bin.\r\n  [[nodiscard]] auto min() const -> pybind11::array_t<T> {\r\n    return calculate_statistics(&DescriptiveStatistics::min);\r\n  }\r\n\r\n  /// Compute the maximum of values for points within each bin.\r\n  [[nodiscard]] auto max() const -> pybind11::array_t<T> {\r\n    return calculate_statistics(&DescriptiveStatistics::max);\r\n  }\r\n\r\n  /// Compute the mean of values for points within each bin.\r\n  [[nodiscard]] auto mean() const -> pybind11::array_t<T> {\r\n    return calculate_statistics(&DescriptiveStatistics::mean);\r\n  }\r\n\r\n  /// Compute the variance of values for points within each bin.\r\n  [[nodiscard]] auto variance(const int ddof = 0) const\r\n      -> pybind11::array_t<T> {\r\n    return calculate_statistics(&DescriptiveStatistics::variance, ddof);\r\n  }\r\n\r\n  /// Compute the kurtosis of values for points within each bin.\r\n  [[nodiscard]] auto kurtosis() const -> pybind11::array_t<T> {\r\n    return calculate_statistics(&DescriptiveStatistics::kurtosis);\r\n  }\r\n\r\n  /// Compute the skewness of values for points within each bin.\r\n  [[nodiscard]] auto skewness() const -> pybind11::array_t<T> {\r\n    return calculate_statistics(&DescriptiveStatistics::skewness);\r\n  }\r\n\r\n  /// Compute the sum of values for points within each bin.\r\n  [[nodiscard]] auto sum() const -> pybind11::array_t<T> {\r\n    return calculate_statistics(&DescriptiveStatistics::sum);\r\n  }\r\n\r\n  /// Compute the sum of weights within each bin.\r\n  [[nodiscard]] auto sum_of_weights() const -> pybind11::array_t<T> {\r\n    return calculate_statistics(&DescriptiveStatistics::sum_of_weights);\r\n  }\r\n\r\n  /// Gets the X-Axis\r\n  [[nodiscard]] inline auto x() const -> std::shared_ptr<Axis<double>> {\r\n    return x_;\r\n  }\r\n\r\n  /// Gets the Y-Axis\r\n  [[nodiscard]] inline auto y() const -> std::shared_ptr<Axis<double>> {\r\n    return y_;\r\n  }\r\n\r\n  /// Gets the WGS system\r\n  [[nodiscard]] inline auto wgs() const\r\n      -> const std::optional<geodetic::System>& {\r\n    return wgs_;\r\n  }\r\n\r\n  /// Pickle support: get state of this instance\r\n  [[nodiscard]] auto getstate() const -> pybind11::tuple {\r\n    return pybind11::make_tuple(\r\n        x_->getstate(), y_->getstate(),\r\n        wgs_.has_value() ? wgs_->getstate() : pybind11::make_tuple(), acc());\r\n  }\r\n\r\n  /// Pickle support: set state of this instance\r\n  static auto setstate(const pybind11::tuple& state)\r\n      -> std::unique_ptr<Binning2D<T>> {\r\n    if (state.size() != 4) {\r\n      throw std::invalid_argument(\"invalid state\");\r\n    }\r\n\r\n    // Unmarshalling X-Axis\r\n    auto x = std::make_shared<Axis<double>>();\r\n    *x = Axis<double>::setstate(state[0].cast<pybind11::tuple>());\r\n\r\n    // Unmarshalling Y-Axis\r\n    auto y = std::make_shared<Axis<double>>();\r\n    *y = Axis<double>::setstate(state[1].cast<pybind11::tuple>());\r\n\r\n    // Unmarshalling WGS system\r\n    auto wgs = std::optional<geodetic::System>();\r\n    auto wgs_state = state[2].cast<pybind11::tuple>();\r\n    if (!wgs_state.empty()) {\r\n      *wgs = geodetic::System::setstate(wgs_state);\r\n    }\r\n\r\n    // Unmarshalling computed statistics\r\n    auto acc = state[3].cast<Matrix<Accumulators>>();\r\n    if (acc.rows() != x->size() || acc.cols() != y->size()) {\r\n      throw std::invalid_argument(\"invalid state\");\r\n    }\r\n\r\n    // Unmarshalling instance\r\n    auto result = std::make_unique<Binning2D<T>>(x, y, wgs);\r\n    {\r\n      auto gil = pybind11::gil_scoped_release();\r\n      result->acc_ = std::move(acc.template cast<DescriptiveStatistics>());\r\n    }\r\n    return result;\r\n  }\r\n\r\n  /// Aggregation of statistics\r\n  auto operator+=(const Binning2D& other) -> Binning2D& {\r\n    if (*x_ != *(other.x_) || *y_ != *(other.y_)) {\r\n      throw std::invalid_argument(\"Unable to combine different grids\");\r\n    }\r\n    if ((wgs_ && !other.wgs_) || (!wgs_ && other.wgs_) ||\r\n        (wgs_.has_value() && other.wgs_.has_value() &&\r\n         (*wgs_ != *other.wgs_))) {\r\n      throw std::invalid_argument(\r\n          \"Unable to combine different geodetic system\");\r\n    }\r\n\r\n    for (Eigen::Index ix = 0; ix < acc_.rows(); ++ix) {\r\n      for (Eigen::Index iy = 0; iy < acc_.cols(); ++iy) {\r\n        auto& lhs = acc_(ix, iy);\r\n        auto& rhs = other.acc_(ix, iy);\r\n\r\n        // Statistics are defined only in the other instance.\r\n        if (lhs.count() == 0 && rhs.count() != 0) {\r\n          lhs = rhs;\r\n          // If the statistics are defined in both instances they can be\r\n          // combined.\r\n        } else if (lhs.count() != 0 && rhs.count() != 0) {\r\n          lhs += rhs;\r\n        }\r\n      }\r\n    }\r\n    return *this;\r\n  }\r\n\r\n private:\r\n  /// Grid axis\r\n  std::shared_ptr<Axis<double>> x_;\r\n  std::shared_ptr<Axis<double>> y_;\r\n\r\n  /// Statistics grid\r\n  Matrix<DescriptiveStatistics> acc_;\r\n\r\n  /// Geodetic coordinate system required to calculate areas (optional if the\r\n  /// user wishes to handle Cartesian coordinates).\r\n  std::optional<geodetic::System> wgs_;\r\n\r\n  /// Calculation of a given statistical variable.\r\n  template <typename Func, typename Type = T, typename... Args>\r\n  [[nodiscard]] auto calculate_statistics(const Func& func, Args... args) const\r\n      -> pybind11::array_t<Type> {\r\n    pybind11::array_t<Type> z({x_->size(), y_->size()});\r\n    auto _z = z.template mutable_unchecked<2>();\r\n    {\r\n      pybind11::gil_scoped_release release;\r\n\r\n      for (Eigen::Index ix = 0; ix < acc_.rows(); ++ix) {\r\n        for (Eigen::Index iy = 0; iy < acc_.cols(); ++iy) {\r\n          _z(ix, iy) = (acc_(ix, iy).*func)(args...);\r\n        }\r\n      }\r\n    }\r\n    return z;\r\n  }\r\n\r\n  /// Insertion of data on the nearest bin.\r\n  void push_nearest(const pybind11::array_t<T>& x,\r\n                    const pybind11::array_t<T>& y,\r\n                    const pybind11::array_t<T>& z) {\r\n    auto _x = x.template unchecked<1>();\r\n    auto _y = y.template unchecked<1>();\r\n    auto _z = z.template unchecked<1>();\r\n\r\n    {\r\n      pybind11::gil_scoped_release release;\r\n\r\n      const auto& x_axis = static_cast<pyinterp::detail::Axis<double>&>(*x_);\r\n      const auto& y_axis = static_cast<pyinterp::detail::Axis<double>&>(*y_);\r\n\r\n      for (pybind11::ssize_t idx = 0; idx < x.size(); ++idx) {\r\n        auto value = _z(idx);\r\n\r\n        if (!std::isnan(value)) {\r\n          auto ix = x_axis.find_index(_x(idx), true);\r\n          auto iy = y_axis.find_index(_y(idx), true);\r\n\r\n          if (ix != -1 && iy != -1) {\r\n            acc_(ix, iy)(value);\r\n          }\r\n        }\r\n      }\r\n    }\r\n  }\r\n\r\n  /// Update statistics for the linear binning (ignore zero weights).\r\n  void update_acc(const int64_t ix, const int64_t iy, const T& value,\r\n                  const T& weight) {\r\n    if (!detail::math::is_almost_zero(weight,\r\n                                      std::numeric_limits<T>::epsilon())) {\r\n      acc_(ix, iy)(value, weight);\r\n    }\r\n  }\r\n\r\n  /// Set bins with nearest binning.\r\n  template <template <class> class Point, typename Strategy>\r\n  void push_linear(const pybind11::array_t<T>& x, const pybind11::array_t<T>& y,\r\n                   const pybind11::array_t<T>& z, const Strategy& strategy) {\r\n    auto _x = x.template unchecked<1>();\r\n    auto _y = y.template unchecked<1>();\r\n    auto _z = z.template unchecked<1>();\r\n\r\n    {\r\n      pybind11::gil_scoped_release release;\r\n\r\n      const auto& x_axis = static_cast<pyinterp::detail::Axis<double>&>(*x_);\r\n      const auto& y_axis = static_cast<pyinterp::detail::Axis<double>&>(*y_);\r\n\r\n      for (pybind11::ssize_t idx = 0; idx < x.size(); ++idx) {\r\n        auto value = _z(idx);\r\n        if (std::isnan(value)) {\r\n          continue;\r\n        }\r\n\r\n        auto x_indexes = x_axis.find_indexes(_x(idx));\r\n        auto y_indexes = y_axis.find_indexes(_y(idx));\r\n\r\n        if (x_indexes.has_value() && y_indexes.has_value()) {\r\n          auto [ix0, ix1] = *x_indexes;\r\n          auto [iy0, iy1] = *y_indexes;\r\n\r\n          auto x0 = x_axis(ix0);\r\n\r\n          auto weights = detail::math::binning_2d<Point, Strategy, double>(\r\n              Point<double>(x_axis.is_angle()\r\n                                ? detail::math::normalize_angle<double>(\r\n                                      _x(idx), x0, 360.0)\r\n                                : _x(idx),\r\n                            _y(idx)),\r\n              Point<double>(x0, y_axis(iy0)),\r\n              Point<double>(x_axis(ix1), y_axis(iy1)), strategy);\r\n\r\n          update_acc(ix0, iy0, value, static_cast<T>(std::get<0>(weights)));\r\n          update_acc(ix0, iy1, value, static_cast<T>(std::get<1>(weights)));\r\n          update_acc(ix1, iy1, value, static_cast<T>(std::get<2>(weights)));\r\n          update_acc(ix1, iy0, value, static_cast<T>(std::get<3>(weights)));\r\n        }\r\n      }\r\n    }\r\n  }\r\n\r\n  /// Returns the matrix of raw statistics.\r\n  inline auto acc() const -> Matrix<Accumulators> {\r\n    auto gil = pybind11::gil_scoped_release();\r\n    return acc_.template cast<Accumulators>();\r\n  }\r\n};\r\n\r\n}  // namespace pyinterp\r\n", "meta": {"hexsha": "52cf2b3ecc3c2d45c1beb0f43f5af92c16a82d2f", "size": 12787, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/pyinterp/core/include/pyinterp/binning.hpp", "max_stars_repo_name": "readthedocs-assistant/pangeo-pyinterp", "max_stars_repo_head_hexsha": "e9dc18445dce36638d5a90f64c8e2f1b53164f90", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/pyinterp/core/include/pyinterp/binning.hpp", "max_issues_repo_name": "readthedocs-assistant/pangeo-pyinterp", "max_issues_repo_head_hexsha": "e9dc18445dce36638d5a90f64c8e2f1b53164f90", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pyinterp/core/include/pyinterp/binning.hpp", "max_forks_repo_name": "readthedocs-assistant/pangeo-pyinterp", "max_forks_repo_head_hexsha": "e9dc18445dce36638d5a90f64c8e2f1b53164f90", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.3232044199, "max_line_length": 81, "alphanum_fraction": 0.5938844139, "num_tokens": 3274, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879312155622449, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.46101946365822444}}
{"text": "#ifndef FOOT_STEP_PLANNER_H_\n#define FOOT_STEP_PLANNER_H_\n\n#ifdef PLANNER_DEBUG\nstatic constexpr bool planner_debug = true;\n#else\nstatic constexpr bool planner_debug = false;\n#endif\n\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#include <cmath>\n#include <fstream>\n#include <utility>\n#include <iostream>\n#include <deque>\n#include <vector>\n\ntemplate <class T>\nstatic void debugPrint(T &&s, const std::string &label)\n{\n    if (planner_debug)\n        std::cout << \"Debug planner:\" << label << \"::\" << std::forward<T>(s) << std::endl;\n}\n\nstatic constexpr double dt = 4.0 / 1000.0;   // sampling period (s)\nstatic constexpr double zh = 0.2;            // height of CoM (m)\nstatic constexpr double g = 9.8;             // gravity (m/s^2)\nstatic constexpr double MAX_X_STRIDE = 0.30; //(m)\nstatic constexpr double MAX_Y_STRIDE = 0.08; //(m)\nstatic constexpr double MIN_Y_STRIDE = 0.03; //(m)\n\nstruct FootPrint\n{\n    double time_;\n    double x_;                  //(m)\u30ed\u30dc\u30c3\u30c8\u306e\u30ed\u30fc\u30ab\u30eb\u5ea7\u6a19\u3067\u306e\u8db3\u914d\u7f6e\u4f4d\u7f6e\n    double y_;                  //(m)\u30ed\u30dc\u30c3\u30c8\u306e\u30ed\u30fc\u30ab\u30eb\u5ea7\u6a19\u3067\u306e\u8db3\u914d\u7f6e\u4f4d\u7f6e\n    bool support_foot_is_right; //\u652f\u6301\u811a\u304c\u3069\u3061\u3089\u304b\n};\n\nstd::vector<FootPrint> foot_plan = {{0, 0, 0, true}, {0.8, 0.0, 0.2, false}, {1.6, 0.3, 0.0, true}, {2.4, 0.6, 0.2, false}, {3.2, 0.9, 0.0, true}, {4.0, 0.9, 0.2, false}, {100.0, 0.9, 0.2, true}};\n\n/**\n * @brief foot step planner.\u5de6\u53f3\u306e\u811a\u3067\u8e0f\u307f\u51fa\u3059\u306e\u30921\u30bb\u30c3\u30c8\u30671\u6b69\u3068\u3059\u308b.\n *\n * @param x_destination (m) \u76ee\u6a19\u5730\u70b9:X.\u30ed\u30dc\u30c3\u30c8\u9032\u884c\u65b9\u5411\n * @param y_destination (m) \u76ee\u6a19\u5730\u70b9:Y\n * @param x_stride (m) 1\u6b69\u306e\u5927\u304d\u3055.\u904a\u811a\u304c\u8eab\u4f53\u306e\u524d\u306b\u51fa\u308b\u9577\u3055=x_stride/2.\n * @param support_time (s) \u6b69\u884c\u5468\u671f.(=\u652f\u6301\u811a\u304c\u652f\u6301\u3057\u3066\u3044\u308b\u6642\u9593:Tsup)\n * @param steps (none) \u6b69\u6570.\u76ee\u6a19\u5730\u70b9\u307e\u3067\u4f55\u6b69\u3067\u9032\u3080\u304b.0\u4ee5\u4e0b\u306b\u6307\u5b9a\u3059\u308b\u3068\u6700\u5927\u306e\u30b9\u30c8\u30e9\u30a4\u30c9\u3067\u9032\u3080.\n * @return std::vector<FootPrint> \u30ed\u30dc\u30c3\u30c8\u306e\u30ed\u30fc\u30ab\u30eb\u5ea7\u6a19\u3067\u8868\u3057\u305f\u7740\u5730\u4f4d\u7f6e\u3092\u8fd4\u3059.\n * @details \u4eca\u306e\u6240x\u65b9\u5411\u3078\u306e\u76f4\u7dda\u79fb\u52d5\u3057\u304b\u5bfe\u5fdc\u3057\u3066\u3044\u306a\u3044.\n * @todo y\u65b9\u5411\u306e\u79fb\u52d5\u306e\u5b9f\u88c5\n */\nstd::vector<FootPrint> footStepPlanner(const double &x_destination, const double &y_destination, const double &x_stride, const double &support_time = (320.0 / 1000.0), const int32_t &steps = 0) noexcept\n{\n    const double stride_x = [=]() -> double\n    {\n        if (steps < 1)\n        {\n            return std::min(x_stride, MAX_X_STRIDE);\n        }\n        else\n        {\n            return std::min(MAX_X_STRIDE, x_destination / steps);\n        }\n    }();\n    const double stride_y = std::clamp((y_destination / steps), MIN_Y_STRIDE, MAX_Y_STRIDE);\n    const int32_t steps_ = x_destination / stride_x; //(\u7121) \u6b69\u6570\n    std::cout << \"x_destination \" << x_destination << \" stride_x \" << stride_x << \"steps \" << steps << std::endl;\n    double x = 0, y = 0, xi = 0, yi = 0;     //(m) CoM\u306e\u30ef\u30fc\u30eb\u30c9\u5ea7\u6a19 {CoM = Center of Mass}\n    double xd = 0, yd = 0, xdi = 0, ydi = 0; // CoM\u306e\u901f\u5ea6 v(m/s) xdot(t)\n    double px = 0.0, py = 0.0;               //(m)\u3000\u7740\u5730\u4f4d\u7f6e\u306e\u30ef\u30fc\u30eb\u30c9\u5ea7\u6a19 \u3053\u308c\u306f\u5b9f\u7528\u7684\u306b\u306f\u30ed\u30fc\u30ab\u30eb\u306e\u65b9\u304c\u826f\u3044\u306e\u3067\u306f\uff1f\uff1f\n    constexpr double Tc = std::sqrt(zh / g); //\u5fae\u5206\u65b9\u7a0b\u5f0f\u306e\u6642\u5b9a\u6570\n    double C = 0.0;                          // cosh((t - t0) / Tc)\n    double S = 0.0;                          // sinh((t - t0) / Tc)\n    // const double Tsup = support_time - std::fmod(support_time, dt); //\u8aa4\u5dee\u3092\u7121\u304f\u3059\u305f\u3081\n    const double Tsup = support_time;\n    int_fast64_t step_n = 0;\n    debugPrint(Tsup, \"Tsup\");\n    std::deque<std::deque<double>> result;\n    std::ofstream velofs(\"velo.dat\");\n    std::vector<FootPrint> footprint_list(100);\n    for (double t = 0.0; t < (Tsup * static_cast<double>(steps_ * 2 + 1)); ++step_n)\n    {\n        //\u6c7a\u3081\u3089\u308c\u305f\u6b21\u306e\u4e00\u6b69\u3092\u7740\u304f\u5730\u70b9\u307e\u3067\u306e\u904a\u811a\u306e\u79fb\u52d5\u3092\u884c\u3063\u3066\u3044\u308b\u6642\u306e\u30b7\u30df\u30e5\u30ec\u30fc\u30b7\u30e7\u30f3---------------\n        for (double t_tmp = 0.0; t_tmp < Tsup; t_tmp += dt, t += dt)\n        {\n            C = std::cosh(t_tmp / Tc);\n            S = std::sinh(t_tmp / Tc);\n            x = (xi - px) * C + Tc * xdi * S + px; // x,xd\u3068\u3082\u306bn\u6b69\u76ee\u958b\u59cb\u6642\u306e\u72b6\u614b\n            y = (yi - py) * C + Tc * ydi * S + py;\n            xd = (xi - px) / Tc * S + xdi * C;\n            yd = (yi - py) / Tc * S + ydi * C;\n            result.push_back({x, y});\n            velofs << t << \" \" << xd << \" \" << yd << std::endl;\n        }\n        xi = x;\n        yi = y;\n        xdi = xd;\n        ydi = yd;\n        //\u6b21\u306e\u4e00\u6b69\u306e\u76ee\u6a19\u4f4d\u7f6e\u3092\u8a08\u7b97------------------\n        static constexpr double a = 10;\n        static constexpr double b = 1;\n        C = std::cosh(Tsup / Tc); //\u610f\u5473\u306f\u5168\u304f\u7121\u3044\u304c\u5206\u304b\u308a\u3084\u3059\u3055\u306e\u305f\u3081\n        S = std::sinh(Tsup / Tc);\n        const double D = a * (C - 1) * (C - 1) + b * (S / Tc) * (S / Tc);\n        double x_target = 0.0, y_target = 0.0, xd_target = 0.0, yd_target = 0.0;\n        double sx = 0.0, sy = 0.0; //\u6b69\u884c\u7d20\u7247\u306b\u3088\u308b\u4f4d\u7f6e\n        if (steps_ < step_n)\n        {\n            sx = 0.0;\n            sy = 0.0;\n        }\n        else\n        {\n            sx = stride_x / 2;\n            sy = ((step_n % 2) ? 1 : -1) * stride_y / 2;\n        }\n        x_target = px + sx;\n        y_target = py + sy;\n        std::cout << \"x target \" << x_target << \" y target \" << y_target;\n        xd_target = (C + 1) / (Tc * S) * sx;\n        yd_target = (C - 1) / (Tc * S) * sy;\n        px = -a * (C - 1) / D * (x_target - C * xi - Tc * S * xdi) - b * S / (Tc * D) * (xd_target - S * xi / Tc - C * xdi);\n        py = -a * (C - 1) / D * (y_target - C * yi - Tc * S * ydi) - b * S / (Tc * D) * (yd_target - S * yi / Tc - C * ydi);\n        std::cout << \" px::\" << px << \" py::\" << py << std::endl;\n        static bool is_right = true;\n        footprint_list.push_back({Tsup, px - xi, py - yi, is_right});\n        is_right = !is_right;\n        result.back().push_back(px);\n        result.back().push_back(py);\n    }\n    std::ofstream ofs(\"position.dat\");\n    for (auto &itr : result)\n    {\n        for (auto &item : itr)\n        {\n            ofs << item << \" \";\n        }\n        ofs << std::endl;\n    }\n    return footprint_list;\n    // ofs.close();\n}\n\ndouble spline(double x)\n{\n    return 0.02 * (x * x * x) + 0.01 * (x * x) - 0.1 * (x);\n}\n\nstd::vector<FootPrint> planAlongSpline() noexcept\n{\n    const double stride_x = 0.3;\n    const double stride_y = 0.20;\n    const int32_t steps_ = 30;               //(\u7121) \u6b69\u6570\n    double x = 0, y = 0, xi = 0, yi = 0;     //(m) CoM\u306e\u30ef\u30fc\u30eb\u30c9\u5ea7\u6a19 {CoM = Center of Mass}\n    double xd = 0, yd = 0, xdi = 0, ydi = 0; // CoM\u306e\u901f\u5ea6 v(m/s) xdot(t)\n    double px = 0.0, py = 0.0;               //(m)\u3000\u7740\u5730\u4f4d\u7f6e\u306e\u30ef\u30fc\u30eb\u30c9\u5ea7\u6a19 \u3053\u308c\u306f\u5b9f\u7528\u7684\u306b\u306f\u30ed\u30fc\u30ab\u30eb\u306e\u65b9\u304c\u826f\u3044\u306e\u3067\u306f\uff1f\uff1f\n    constexpr double Tc = std::sqrt(zh / g); //\u5fae\u5206\u65b9\u7a0b\u5f0f\u306e\u6642\u5b9a\u6570\n    double C = 0.0;                          // cosh((t - t0) / Tc)\n    double S = 0.0;                          // sinh((t - t0) / Tc)\n    const double Tsup = 0.32;\n    int_fast64_t step_n = 0;\n    double CoM_target_x = 0.0, CoM_target_y = 0.0;\n    std::deque<std::deque<double>> result;\n    std::ofstream velofs(\"velo2.dat\");\n    std::vector<FootPrint> footprint_list(100);\n    for (double t = 0.0; t < (Tsup * static_cast<double>(steps_ * 2 + 1)); ++step_n)\n    {\n        //\u6c7a\u3081\u3089\u308c\u305f\u6b21\u306e\u4e00\u6b69\u3092\u7740\u304f\u5730\u70b9\u307e\u3067\u306e\u904a\u811a\u306e\u79fb\u52d5\u3092\u884c\u3063\u3066\u3044\u308b\u6642\u306e\u30b7\u30df\u30e5\u30ec\u30fc\u30b7\u30e7\u30f3---------------\n        for (double t_tmp = 0.0; t_tmp < Tsup; t_tmp += dt, t += dt)\n        {\n            C = std::cosh(t_tmp / Tc);\n            S = std::sinh(t_tmp / Tc);\n            x = (xi - px) * C + Tc * xdi * S + px; // x,xd\u3068\u3082\u306bn\u6b69\u76ee\u958b\u59cb\u6642\u306e\u72b6\u614b\n            y = (yi - py) * C + Tc * ydi * S + py;\n            xd = (xi - px) / Tc * S + xdi * C;\n            yd = (yi - py) / Tc * S + ydi * C;\n            CoM_target_x = x;\n            CoM_target_y = spline(CoM_target_x);\n            result.push_back({x, y, CoM_target_x, CoM_target_y});\n            velofs << t << \" \" << xd << \" \" << yd << std::endl;\n        }\n        xi = x;\n        yi = y;\n        xdi = xd;\n        ydi = yd;\n        //\u6b21\u306e\u4e00\u6b69\u306e\u76ee\u6a19\u4f4d\u7f6e\u3092\u8a08\u7b97------------------\n        static constexpr double a = 30;\n        static constexpr double b = 1;\n        C = std::cosh(Tsup / Tc); //\u610f\u5473\u306f\u5168\u304f\u7121\u3044\u304c\u5206\u304b\u308a\u3084\u3059\u3055\u306e\u305f\u3081\n        S = std::sinh(Tsup / Tc);\n        const double D = a * (C - 1) * (C - 1) + b * (S / Tc) * (S / Tc);\n        double x_target = 0.0, y_target = 0.0, xd_target = 0.0, yd_target = 0.0;\n        double sx = 0.0, sy = 0.0; //\u6b69\u884c\u7d20\u7247\u306b\u3088\u308b\u4f4d\u7f6e\n\n        if (steps_ < step_n)\n        {\n            sx = 0.0;\n            sy = ((step_n % 2) ? 1 : -1) * stride_y / 2;\n        }\n        else\n        {\n            sx = stride_x / 2;\n            sy = ((step_n % 2) ? 1 : -1) * stride_y / 2;\n        }\n        double theta = std::atan((spline(x + sx) - y) / sx);\n        x_target = px + std::cos(theta) * sx - std::sin(theta) * sy;\n        y_target = py + std::sin(theta) * sx + std::cos(theta) * sy;\n        std::cout << \"theta \" << theta << \"------------------------------------------ \"<< std::endl;\n        // std::cout << \"(x_target - px)::\" << (x_target - px) << \" (y_target - py)::\" << (y_target - py) << std::endl;\n        std::cout << \"distance \" << std::sqrt((x_target - px) * (x_target - px) + (y_target - py) * (y_target - py)) << std::endl;\n        // std::cout << \"x target \" << x_target << \" y target \" << y_target;\n        xd_target = (C + 1) / (Tc * S) * (x_target - px);\n        yd_target = (C - 1) / (Tc * S) * (y_target - py);\n        double t_px = px,t_py = py;\n        px = -a * (C - 1) / D * (x_target - C * xi - Tc * S * xdi) - b * S / (Tc * D) * (xd_target - S * xi / Tc - C * xdi);\n        py = -a * (C - 1) / D * (y_target - C * yi - Tc * S * ydi) - b * S / (Tc * D) * (yd_target - S * yi / Tc - C * ydi);\n        std::cout << \"x:\" << (px - t_px) << \" y:\" << (py - t_py) << std::endl;\n        // std::cout << \" px::\" << px << \" py::\" << py << std::endl;\n        static bool is_right = true;\n        footprint_list.push_back({Tsup, px - xi, py - yi, is_right});\n        is_right = !is_right;\n        result.back().push_back(px);\n        result.back().push_back(py);\n    }\n    std::ofstream ofs(\"position2.dat\");\n    for (auto &itr : result)\n    {\n        for (auto &item : itr)\n        {\n            ofs << item << \" \";\n        }\n        ofs << std::endl;\n    }\n    return footprint_list;\n    // ofs.close();\n}\n\n#endif //  FOOT_STEP_PLANNER_H_\n\n/* memo\n * \u72b6\u614b\u3092\u306a\u308b\u3079\u304f\u6301\u305f\u305b\u306a\u3044.\n * \u53d6\u308a\u6562\u3048\u305a\u6b69\u3051\u308b\u4e8b\u3092\u793a\u3057\u305f\u3044\u306e\u3067\u306a\u308b\u3079\u304f\u7c21\u4fbf\u306a\u5b9f\u88c5\u306b\u3059\u308b\u3002\n * \u4e00\u9023\u306e\u91cd\u5fc3\u8ecc\u9053\u3092\u5168\u3066\u751f\u6210\u3057\u3066\u3057\u307e\u3063\u3066\u305d\u3053\u304b\u3089\u3069\u3046\u306b\u304b\u3059\u308b\u306e\u3067\u826f\u3044\n * todo \u901f\u5ea6\u304c\u6975\u5927\u306a\u6240\u306et\u3092\u8868\u793a\u3055\u305b\u305f\u3044\n *\n *\n *\n */\n", "meta": {"hexsha": "865754b3f9fb8c117b49cc435419dc11db61bf90", "size": 9710, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "inv_pend_walk/foot_step_planner.hpp", "max_stars_repo_name": "AD58-3104/bipedal_training", "max_stars_repo_head_hexsha": "f7bca20e12f65ed4be2a9ba93198286682642fca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "inv_pend_walk/foot_step_planner.hpp", "max_issues_repo_name": "AD58-3104/bipedal_training", "max_issues_repo_head_hexsha": "f7bca20e12f65ed4be2a9ba93198286682642fca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "inv_pend_walk/foot_step_planner.hpp", "max_forks_repo_name": "AD58-3104/bipedal_training", "max_forks_repo_head_hexsha": "f7bca20e12f65ed4be2a9ba93198286682642fca", "max_forks_repo_licenses": ["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.5317460317, "max_line_length": 202, "alphanum_fraction": 0.5029866117, "num_tokens": 3756, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879312006227324, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4610194549170984}}
{"text": "//Link to Boost\n #define BOOST_TEST_DYN_LINK\n\n//VERY IMPORTANT - include this last\n#include <boost/test/unit_test.hpp>\n#include <boost/timer.hpp>\n\n#include <vector>\n#include <iostream>\n#include <boost/math/special_functions/binomial.hpp>\n#include \"test.h\"\n#include \"../CrossingEquations.h\"\n#include \"../EquationSolver.h\"\nusing namespace std;\n\nBOOST_FIXTURE_TEST_SUITE(CrossingEquations_suite, SimpleTestFixture, * utf::label(\"CrossingEquations\"))\n\nBOOST_DATA_TEST_CASE(Constructor_test, CreateCfgConfigTestData(TCNumber), cfg)\n{\n    CftData cftData(cfg);\n    int numberOfScalarsToBootstrap = randomint(1, min(cftData.MaxScalarId(), 5));\n    CrossingEquations equations(&cftData, numberOfScalarsToBootstrap);\n\n    int equationNumber = (int)boost::math::binomial_coefficient<double>(numberOfScalarsToBootstrap + 3, 4);\n    if (numberOfScalarsToBootstrap >= 4) {\n        equationNumber += (int)boost::math::binomial_coefficient<double>(numberOfScalarsToBootstrap, 4);\n    }\n\n    BOOST_TEST(equations.EquationNumber() == equationNumber);\n\n    int parameterNumber = cftData.MaxPrimaryId() - 1;\n    parameterNumber += (int)boost::math::binomial_coefficient<double>(numberOfScalarsToBootstrap + 2, 3);\n    parameterNumber += (int)boost::math::binomial_coefficient<double>(numberOfScalarsToBootstrap + 1, 2) * (cftData.MaxPrimaryId() - 1 -numberOfScalarsToBootstrap);\n\n    BOOST_TEST(equations.ParameterNumber() == parameterNumber);\n}\n\nBOOST_DATA_TEST_CASE(GetSetParameter_test, CreateCfgConfigTestData(TCNumber), cfg)\n{\n    CftData cftData(cfg);\n    int numberOfScalarsToBootstrap = randomint(1, min(cftData.MaxScalarId(), 5));\n    CrossingEquations equations(&cftData, numberOfScalarsToBootstrap);\n\n    for (uint i = 0; i < equations.ParameterNumber(); i++) {\n        float_type value = random(-10.0, 10.0);\n        equations.SetParameter(i, value);\n        float_type actual = equations.GetParameter(i);\n        BOOST_TEST_INFO(\"i=\" << i);\n        MY_FLOAT_EQUAL(actual, value, tol);\n    }\n}\n\nBOOST_DATA_TEST_CASE(EquationDerivativeByParameter_test, CreateCfgConfigTestData(TCNumber), cfg)\n{\n    CftData cftData(cfg);\n    int numberOfScalarsToBootstrap = randomint(1, min(cftData.MaxScalarId(), 4));\n    CrossingEquations equations(&cftData, numberOfScalarsToBootstrap);\n    int equationId = randomint(0, equations.EquationNumber() - 1);\n    int parameterId = randomint(0, equations.ParameterNumber() - 1);\n\n    cpx_t input = RandomComplex(0.2) + .5;\n    float_type actual = equations.EquationDerivativeByParameter(input, equationId, parameterId);\n\n    float_type param = equations.GetParameter(parameterId);\n    equations.SetParameter(parameterId, param - inc);\n    equations.OnParameterUpdated();\n    float_type value1 = equations.EvaluateEquation(input, equationId);\n    equations.SetParameter(parameterId, param + inc);\n    equations.OnParameterUpdated();\n    float_type value2 = equations.EvaluateEquation(input, equationId);\n\n    float_type expected = (value2 - value1) / (2 * inc);\n\n    BOOST_TEST_INFO(\"numberOfScalarsToBootstrap=\" << numberOfScalarsToBootstrap << \", input=\" << input << \", equationId=\" << equationId << \", parameterId=\" << parameterId);\n    MY_FLOAT_EQUAL(actual, expected, tol);\n}\n\nBOOST_DATA_TEST_CASE(ConstraintsDerivativeByParameter_test, CreateCfgConfigTestData(TCNumber), cfg)\n{\n    CftData cftData(cfg);\n    int numberOfScalarsToBootstrap = randomint(1, min(cftData.MaxScalarId(), 4));\n    CrossingEquations equations(&cftData, numberOfScalarsToBootstrap);\n    int parameterId = randomint(0, equations.ParameterNumber() - 2);\n    float_type param = equations.GetParameter(parameterId);\n    float_type param2 = equations.GetParameter(parameterId + 1);\n    equations.SetParameter(parameterId, param2);\n    equations.SetParameter(parameterId + 1, param);\n\n    float_type actual = equations.ConstraintsDerivativeByParameter(parameterId);\n\n    equations.SetParameter(parameterId, param2 - inc);\n    float_type value1 = equations.EvaluateConstraints();\n    equations.SetParameter(parameterId, param2 + inc);\n    float_type value2 = equations.EvaluateConstraints();\n\n    float_type expected = (value2 - value1) / (2 * inc);\n\n    BOOST_TEST_INFO(\"numberOfScalarsToBootstrap=\" << numberOfScalarsToBootstrap << \", parameterId=\" << parameterId);\n    MY_FLOAT_EQUAL(actual, expected, tol);\n}\n\nBOOST_DATA_TEST_CASE(ConstraintsDerivativeByParameter_test2, CreateCfgConfigTestData(TCNumber), cfg)\n{\n    CftData cftData(cfg);\n    int numberOfScalarsToBootstrap = randomint(1, min(cftData.MaxScalarId(), 4));\n    CrossingEquations equations(&cftData, numberOfScalarsToBootstrap);\n    int parameterId = 0;\n    equations.SetParameter(parameterId, (cftData.D/2.0 - 1 - 0.3));\n    float_type actual = equations.ConstraintsDerivativeByParameter(parameterId);\n\n    float_type param = equations.GetParameter(parameterId);\n    equations.SetParameter(parameterId, param - inc);\n    float_type value1 = equations.EvaluateConstraints();\n    equations.SetParameter(parameterId, param + inc);\n    float_type value2 = equations.EvaluateConstraints();\n\n    float_type expected = (value2 - value1) / (2 * inc);\n\n    BOOST_TEST_INFO(\"numberOfScalarsToBootstrap=\" << numberOfScalarsToBootstrap << \", parameterId=\" << parameterId << \", value=\" << param);\n    MY_FLOAT_EQUAL(actual, expected, tol);\n}\n\n// test suite end\nBOOST_AUTO_TEST_SUITE_END()\n\nBOOST_AUTO_TEST_CASE(EquationDerivativeByParameter_Debug_test, * utf::label(\"CrossingEquations.debug\"))\n{\n    CftConfig cfg(2);\n    cfg.OperatorNumbers=vector<int>({5, 4, 4, 5, 4, 3});\n    CftData cftData(cfg);\n    int numberOfScalarsToBootstrap = 3;\n    CrossingEquations equations(&cftData, numberOfScalarsToBootstrap);\n    int equationId = 12;\n    int parameterId = 2;\n\n    cpx_t input = cpx_t(0.499168,0.00225563);\n    float_type actual = equations.EquationDerivativeByParameter(input, equationId, parameterId);\n    float_type param = equations.GetParameter(parameterId);\n    equations.SetParameter(parameterId, param - inc);\n    equations.OnParameterUpdated();\n    float_type value1 = equations.EvaluateEquation(input, equationId);\n    equations.SetParameter(parameterId, param + inc);\n    equations.OnParameterUpdated();\n    float_type value2 = equations.EvaluateEquation(input, equationId);\n\n    float_type expected = (value2 - value1) / (2 * inc);\n\n    BOOST_TEST_INFO(\"numberOfScalarsToBootstrap=\" << numberOfScalarsToBootstrap << \", input=\" << input << \", equationId=\" << equationId << \", parameterId=\" << parameterId);\n    MY_FLOAT_EQUAL(actual, expected, tol);\n}\n\n\n", "meta": {"hexsha": "1c1a485ce76ae792d49297bc39b9d89e517d573f", "size": 6517, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/CrossingEquationsTests.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/test/CrossingEquationsTests.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/test/CrossingEquationsTests.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": 42.5947712418, "max_line_length": 172, "alphanum_fraction": 0.7442074574, "num_tokens": 1570, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4610194520033896}}
{"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#include <boost/math/special_functions/hypergeometric_2f0.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/lexical_cast.hpp>\n#include <fstream>\n#include <map>\n#include <boost/math/tools/test_data.hpp>\n#include <boost/random.hpp>\n#include \"mp_t.hpp\"\n\nusing namespace boost::math::tools;\nusing namespace boost::math;\nusing namespace std;\n\nstruct hypergeometric_2f0_gen\n{\n   mp_t operator()(mp_t a1, mp_t a2, mp_t z)\n   {\n      std::cout << a1 << \" \" << a2 << \" \" << z << std::endl;\n      mp_t result = boost::math::detail::hypergeometric_2f0_generic_series(a1, a2, z, boost::math::policies::policy<>());\n      std::cout << a1 << \" \" << a2 << \" \" << z << \" \" << result << std::endl;\n      return result;\n   }\n};\n\nstruct hypergeometric_2f0_gen_spec1\n{\n   boost::math::tuple<mp_t, mp_t, mp_t, mp_t> operator()(mp_t a1, mp_t z)\n   {\n      mp_t result = boost::math::detail::hypergeometric_2f0_generic_series(a1, a1 + 0.5, z, boost::math::policies::policy<>());\n      std::cout << a1 << \" \" << a1 + 0.5 << \" \" << z << \" \" << result << std::endl;\n      return boost::math::make_tuple(a1, a1 + 0.5, z, result);\n   }\n};\n\nint main(int, char* [])\n{\n   parameter_info<mp_t> arg1, arg2, arg3;\n   test_data<mp_t> data;\n\n   std::cout << \"Welcome.\\n\"\n      \"This program will generate spot tests for 2F0:\\n\";\n\n   std::string line;\n   bool cont;\n\n#if 1\n   arg1 = make_periodic_param(mp_t(-20), mp_t(-1), 19);\n   arg2 = make_random_param(mp_t(-5), mp_t(5), 8);\n   arg1.type |= dummy_param;\n   arg2.type |= dummy_param;\n   data.insert(hypergeometric_2f0_gen_spec1(), arg1, arg2);\n\n\n#else\n\n   do {\n      get_user_parameter_info(arg1, \"a1\");\n      get_user_parameter_info(arg2, \"a2\");\n      get_user_parameter_info(arg3, \"z\");\n      data.insert(hypergeometric_2f0_gen(), arg1, arg2, arg3);\n      std::cout << \"Any more data [y/n]?\";\n      std::getline(std::cin, line);\n      boost::algorithm::trim(line);\n      cont = (line == \"y\");\n   } while (cont);\n\n#endif\n   std::cout << \"Enter name of test data file [default=hypergeometric_2f0.ipp]\";\n   std::getline(std::cin, line);\n   boost::algorithm::trim(line);\n   if(line == \"\")\n      line = \"hypergeometric_2f0.ipp\";\n   std::ofstream ofs(line.c_str());\n   ofs << std::scientific << std::setprecision(40);\n   write_code(ofs, data, line.c_str());\n   \n   return 0;\n}\n\n\n", "meta": {"hexsha": "a750dff510f41cc3d697a51fa3788cd90879517d", "size": 2538, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/tools/hyp_2f0_data.cpp", "max_stars_repo_name": "cpp-pm/boost", "max_stars_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_stars_repo_licenses": ["BSL-1.0"], "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": "libs/math/tools/hyp_2f0_data.cpp", "max_issues_repo_name": "cpp-pm/boost", "max_issues_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_issues_repo_licenses": ["BSL-1.0"], "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": "libs/math/tools/hyp_2f0_data.cpp", "max_forks_repo_name": "cpp-pm/boost", "max_forks_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-08-28T07:14:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-13T11:18:41.000Z", "avg_line_length": 29.511627907, "max_line_length": 127, "alphanum_fraction": 0.6359338061, "num_tokens": 786, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4610194520033896}}
{"text": "#include <Eigen/Dense>\n#include <cmath>\n#include <iostream>\n\n#include \"cudaSift.h\"\n\nint ImproveHomography(SiftData &data, float *homography, int numLoops, float minScore,\n                      float maxAmbiguity, float thresh) {\n#ifdef MANAGEDMEM\n  SiftPoint *mpts = data.m_data;\n#else\n  if (data.h_data == NULL) return 0;\n  SiftPoint *mpts = data.h_data;\n#endif\n  float limit = thresh * thresh;\n  int numPts = data.numPts;\n  Eigen::MatrixXd M(8, 8);\n  Eigen::VectorXd A(8);\n  Eigen::VectorXd X(8);\n  Eigen::VectorXd Y(8);\n  for (int i = 0; i < 8; i++) A(i) = homography[i] / homography[8];\n  for (int loop = 0; loop < numLoops; loop++) {\n    M = Eigen::MatrixXd::Zero(8, 8);\n    X = Eigen::VectorXd::Zero(8);\n    for (int i = 0; i < numPts; i++) {\n      SiftPoint &pt = mpts[i];\n      if (pt.score < minScore || pt.ambiguity > maxAmbiguity) continue;\n      float den = A(6) * pt.xpos + A(7) * pt.ypos + 1.0f;\n      float dx = (A(0) * pt.xpos + A(1) * pt.ypos + A(2)) / den - pt.match_xpos;\n      float dy = (A(3) * pt.xpos + A(4) * pt.ypos + A(5)) / den - pt.match_ypos;\n      float err = dx * dx + dy * dy;\n      float wei = (err < limit ? 1.0f : 0.0f);  // limit / (err + limit);\n      Y(0) = pt.xpos;\n      Y(1) = pt.ypos;\n      Y(2) = 1.0;\n      Y(3) = Y(4) = Y(5) = 0.0;\n      Y(6) = -pt.xpos * pt.match_xpos;\n      Y(7) = -pt.ypos * pt.match_xpos;\n      for (int c = 0; c < 8; c++)\n        for (int r = 0; r < 8; r++) M(r, c) += (Y(c) * Y(r) * wei);\n      X += (Y * pt.match_xpos * wei);\n      Y(0) = Y(1) = Y(2) = 0.0;\n      Y(3) = pt.xpos;\n      Y(4) = pt.ypos;\n      Y(5) = 1.0;\n      Y(6) = -pt.xpos * pt.match_ypos;\n      Y(7) = -pt.ypos * pt.match_ypos;\n      for (int c = 0; c < 8; c++)\n        for (int r = 0; r < 8; r++) M(r, c) += (Y(c) * Y(r) * wei);\n      X += (Y * pt.match_ypos * wei);\n    }\n    // cv::solve(M, X, A, cv::DECOMP_CHOLESKY);\n    A = M.colPivHouseholderQr().solve(X);\n  }\n  int numfit = 0;\n  for (int i = 0; i < numPts; i++) {\n    SiftPoint &pt = mpts[i];\n    float den = A(6) * pt.xpos + A(7) * pt.ypos + 1.0;\n    float dx = (A(0) * pt.xpos + A(1) * pt.ypos + A(2)) / den - pt.match_xpos;\n    float dy = (A(3) * pt.xpos + A(4) * pt.ypos + A(5)) / den - pt.match_ypos;\n    float err = dx * dx + dy * dy;\n    if (err < limit) numfit++;\n    pt.match_error = sqrt(err);\n  }\n  for (int i = 0; i < 8; i++) homography[i] = A(i);\n  homography[8] = 1.0f;\n  return numfit;\n}\n", "meta": {"hexsha": "3bb4800991fff29b1a82a180d581df476a52d2f0", "size": 2401, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "geomFuncs.cpp", "max_stars_repo_name": "kamino410/CudaSift", "max_stars_repo_head_hexsha": "21d98443f919f877246aadde1d5e1c16fb7afa14", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "geomFuncs.cpp", "max_issues_repo_name": "kamino410/CudaSift", "max_issues_repo_head_hexsha": "21d98443f919f877246aadde1d5e1c16fb7afa14", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "geomFuncs.cpp", "max_forks_repo_name": "kamino410/CudaSift", "max_forks_repo_head_hexsha": "21d98443f919f877246aadde1d5e1c16fb7afa14", "max_forks_repo_licenses": ["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.7971014493, "max_line_length": 86, "alphanum_fraction": 0.5127030404, "num_tokens": 955, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4610194520033896}}
{"text": "#include <examples/ml/LRModel.h>\n#include <Utils.h>\n#include <MlUtils.h>\n#include <Eigen/Dense>\n#include <utils/Log.h>\n#include <Checksum.h>\n#include <algorithm>\n\nLRModel::LRModel(uint64_t d) :\n    d(d) {\n    weights.resize(d);\n}\n\nLRModel::LRModel(const double* w, uint64_t d) :\n    d(d) {\n    weights.resize(d);\n    std::copy(w, w + d, weights.begin());\n}\n\nstd::unique_ptr<Model> LRModel::deserialize(void* data, uint64_t size) const {\n    uint64_t d = size / sizeof(double);\n    std::unique_ptr<LRModel> model = std::make_unique<LRModel>(\n            reinterpret_cast<double*>(data), d);\n    return model;\n}\n\nvoid check_dataset(Dataset& dataset) {\n    for (uint64_t i = 0; i < dataset.num_samples(); ++i) {\n        for (uint64_t j = 0; j < dataset.num_features(); ++j) {\n            const double* s = dataset.sample(i);\n            if (std::isnan(s[j]) || std::isinf(s[j])) {\n                throw std::runtime_error(\"Invalid dataset\");\n            }\n        }\n    }\n}\n\nstd::pair<std::unique_ptr<char[]>, uint64_t>\nLRModel::serialize() const {\n    std::pair<std::unique_ptr<char[]>, uint64_t> res;\n    uint64_t size = getSerializedSize();\n    res.first.reset(new char[size]);\n\n    res.second = size;\n    std::memcpy(res.first.get(), weights.data(), getSerializedSize());\n\n    return res;\n}\n\nvoid LRModel::serializeTo(void* mem) const {\n    std::memcpy(mem, weights.data(), getSerializedSize());\n}\n\nvoid LRModel::randomize() {\n    for (uint64_t i = 0; i < d; ++i) {\n        weights[i] = get_rand_between_0_1();\n    }\n}\n\nstd::unique_ptr<Model> LRModel::copy() const {\n    std::unique_ptr<LRModel> new_model =\n        std::make_unique<LRModel>(weights.data(), d);\n    return new_model;\n}\n\nvoid LRModel::sgd_update(double learning_rate,\n        const ModelGradient* gradient) {\n    const LRGradient* grad = dynamic_cast<const LRGradient*>(gradient);\n\n    if (grad == nullptr) {\n        throw std::runtime_error(\"Error in dynamic cast\");\n    }\n\n    for (uint64_t i = 0; i < d; ++i) {\n       weights[i] += learning_rate * grad->weights[i];\n    }\n}\n\nuint64_t LRModel::getSerializedSize() const {\n    return d * sizeof(double);\n}\n\nvoid LRModel::loadSerialized(const void* data) {\n    cirrus::LOG<cirrus::INFO>(\"loadSerialized d: \", d);\n    const double* v = reinterpret_cast<const double*>(data);\n    std::copy(v, v + d, weights.begin());\n}\n\nstd::unique_ptr<ModelGradient> LRModel::minibatch_grad(\n        int /* rank */, const Matrix& dataset,\n        double* labels,\n        uint64_t labels_size,\n        double epsilon) const {\n    auto w = weights;\n#ifdef DEBUG\n    dataset.check_values();\n#endif\n\n    const double* dataset_data = dataset.data.get();\n    // create Matrix for dataset\n    Eigen::Map<Eigen::Matrix<double, Eigen::Dynamic,\n        Eigen::Dynamic, Eigen::RowMajor>>\n          ds(const_cast<double*>(dataset_data), dataset.rows, dataset.cols);\n\n    // create weight vector\n    Eigen::Map<Eigen::VectorXd> weights(w.data(), d);\n\n    // create vector with labels\n    Eigen::Map<Eigen::VectorXd> lab(labels, labels_size);\n\n    // apply logistic function to matrix multiplication\n    // between dataset and weights\n    auto part1_1 = (ds * weights);\n    auto part1 = part1_1.unaryExpr(std::ptr_fun(mlutils::s_1));\n\n    Eigen::Map<Eigen::VectorXd> lbs(labels, labels_size);\n\n    // compute difference between labels and logistic probability\n    auto part2 = lbs - part1;\n    auto part3 = ds.transpose() * part2;\n    auto part4 = weights * 2 * epsilon;\n    auto res = part4 + part3;\n\n    std::vector<double> vec_res;\n    vec_res.resize(res.size());\n    Eigen::VectorXd::Map(vec_res.data(), res.size()) = res;\n\n    std::unique_ptr<LRGradient> ret = std::make_unique<LRGradient>(vec_res);\n\n#ifdef DEBUG\n    ret->check_values();\n#endif\n\n    return ret;\n}\n\ndouble LRModel::calc_loss(Dataset& dataset) const {\n    double total_loss = 0;\n\n    auto w = weights;\n\n#ifdef DEBUG\n    dataset.check_values();\n#endif\n#ifdef DEBUG\n    check_dataset(dataset);  // make sure dataset is valid\n#endif\n\n    const double* ds_data =\n        reinterpret_cast<const double*>(dataset.samples_.data.get());\n\n    Eigen::Map<Eigen::Matrix<double, Eigen::Dynamic,\n        Eigen::Dynamic, Eigen::RowMajor>>\n            ds(const_cast<double*>(ds_data),\n                    dataset.samples_.rows, dataset.samples_.cols);\n\n    Eigen::Map<Eigen::VectorXd> weights_eig(w.data(), d);\n\n    // count how many samples are wrongly classified\n    uint64_t wrong_count = 0;\n    for (uint64_t i = 0; i < dataset.num_samples(); ++i) {\n        // get labeled class for the ith sample\n        double class_i =\n            reinterpret_cast<const double*>(dataset.labels_.get())[i];\n\n        assert(is_integer(class_i));\n\n        int predicted_class = 0;\n\n        auto r1 = ds.row(i) *  weights_eig;\n        if (mlutils::s_1(r1) > 0.5) {\n            predicted_class = 1;\n        }\n        if (predicted_class != class_i) {\n            wrong_count++;\n        }\n\n        double v1 = mlutils::log_aux(1 - mlutils::s_1(ds.row(i) * weights_eig));\n        double v2 = mlutils::log_aux(mlutils::s_1(ds.row(i) *  weights_eig));\n\n        double value = class_i *\n            mlutils::log_aux(mlutils::s_1(ds.row(i) *  weights_eig)) +\n            (1 - class_i) * mlutils::log_aux(1 - mlutils::s_1(\n                        ds.row(i) * weights_eig));\n\n        // XXX not sure this check is necessary\n        if (value > 0 && value < 1e-6)\n            value = 0;\n\n        if (value > 0) {\n            std::cout << \"ds row: \" << std::endl << ds.row(i) << std::endl;\n            std::cout << \"weights: \" << std::endl << weights_eig << std::endl;\n            std::cout << \"Class: \" << class_i << \" \" << v1 << \" \" << v2\n                << std::endl;\n            throw std::runtime_error(\"Error: logistic loss is > 0\");\n        }\n\n        total_loss -= value;\n    }\n\n    if (total_loss < 0) {\n        throw std::runtime_error(\"total_loss < 0\");\n    }\n\n    std::cout\n        << \"Accuracy: \" << (1.0 - (1.0 * wrong_count / dataset.num_samples()))\n        << std::endl;\n\n    if (std::isnan(total_loss) || std::isinf(total_loss))\n        throw std::runtime_error(\"calc_log_loss generated nan/inf\");\n\n    return total_loss;\n}\n\nuint64_t LRModel::getSerializedGradientSize() const {\n    return d * sizeof(double);\n}\n\nstd::unique_ptr<ModelGradient> LRModel::loadGradient(void* mem) const {\n    auto grad = std::make_unique<LRGradient>(d);\n\n    for (uint64_t i = 0; i < d; ++i) {\n        grad->weights[i] = reinterpret_cast<double*>(mem)[i];\n    }\n\n    return grad;\n}\n\nbool LRModel::is_integer(double n) const {\n    return floor(n) == n;\n}\n\ndouble LRModel::checksum() const {\n    return crc32(weights.data(), weights.size() * sizeof(double));\n}\n\nvoid LRModel::print() const {\n    std::cout << \"MODEL: \";\n    for (const auto& w : weights) {\n        std::cout << \" \" << w;\n    }\n    std::cout << std::endl;\n}\n\n\n", "meta": {"hexsha": "9f2a3ed459ba2c1dc7d466fd750dd9433c873fa6", "size": 6839, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/ml/LRModel.cpp", "max_stars_repo_name": "jcarreira/cirrus-kv", "max_stars_repo_head_hexsha": "a44099185e02859385997956333b364ae836fee5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2018-07-18T22:13:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-24T12:28:42.000Z", "max_issues_repo_path": "examples/ml/LRModel.cpp", "max_issues_repo_name": "jcarreira/ddc", "max_issues_repo_head_hexsha": "a44099185e02859385997956333b364ae836fee5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2016-11-22T11:07:14.000Z", "max_issues_repo_issues_event_max_datetime": "2016-12-17T22:49:23.000Z", "max_forks_repo_path": "examples/ml/LRModel.cpp", "max_forks_repo_name": "jcarreira/ddc", "max_forks_repo_head_hexsha": "a44099185e02859385997956333b364ae836fee5", "max_forks_repo_licenses": ["Apache-2.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.8008130081, "max_line_length": 80, "alphanum_fraction": 0.6046205586, "num_tokens": 1803, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.46101945200338956}}
{"text": "/******************************************************************************\n * Copyright (C) 2014 by Jerome Maye                                          *\n * jerome.maye@gmail.com                                                      *\n ******************************************************************************/\n\n#include \"aslam/calibration/time-delay/error-terms/ErrorTermPose.h\"\n\n#include <Eigen/Dense>\n\n#include <sm/kinematics/rotations.hpp>\n#include <sm/kinematics/EulerAnglesYawPitchRoll.hpp>\n\nnamespace aslam {\n  namespace calibration {\n\n/******************************************************************************/\n/* Constructors and Destructor                                                */\n/******************************************************************************/\n\n    ErrorTermPose::ErrorTermPose(const aslam::backend::TransformationExpression&\n        T, const Input& Tm, const Covariance& sigma2) :\n        _T(T),\n        _Tm(Tm),\n        _sigma2(sigma2) {\n      setInvR(_sigma2.inverse());\n      aslam::backend::DesignVariable::set_t dv;\n      _T.getDesignVariables(dv);\n      setDesignVariablesIterator(dv.begin(), dv.end());\n    }\n\n    ErrorTermPose::ErrorTermPose(const ErrorTermPose& other) :\n        ErrorTermFs<6>(other),\n        _T(other._T),\n        _Tm(other._Tm),\n        _sigma2(other._sigma2) {\n    }\n\n    ErrorTermPose& ErrorTermPose::operator =\n        (const ErrorTermPose& other) {\n      if (this != &other) {\n        ErrorTermFs<6>::operator=(other);\n       _T = other._T;\n       _Tm = other._Tm;\n       _sigma2 = other._sigma2;\n      }\n      return *this;\n    }\n\n    ErrorTermPose::~ErrorTermPose() {\n    }\n\n/******************************************************************************/\n/* Accessors                                                                  */\n/******************************************************************************/\n\n    const ErrorTermPose::Input& ErrorTermPose::getInput() const {\n      return _Tm;\n    }\n\n    ErrorTermPose::Input& ErrorTermPose::getInput() {\n      return _Tm;\n    }\n\n    void ErrorTermPose::setInput(const Input& Tm) {\n      _Tm = Tm;\n    }\n\n    const ErrorTermPose::Covariance& ErrorTermPose::getCovariance() const {\n      return _sigma2;\n    }\n\n    ErrorTermPose::Covariance& ErrorTermPose::getCovariance() {\n      return _sigma2;\n    }\n\n    void ErrorTermPose::setCovariance(const Covariance& sigma2) {\n      _sigma2 = sigma2;\n    }\n\n/******************************************************************************/\n/* Methods                                                                    */\n/******************************************************************************/\n\n    double ErrorTermPose::evaluateErrorImplementation() {\n      const Eigen::Matrix4d T = _T.toTransformationMatrix();\n      Input e;\n      e.head<3>() = T.topRightCorner<3, 1>();\n      const sm::kinematics::EulerAnglesYawPitchRoll ypr;\n      e.tail<3>() =\n        ypr.rotationMatrixToParameters(T.topLeftCorner<3, 3>());\n      error_t error = _Tm - e;\n      error(3) = sm::kinematics::angleMod(error(3));\n      error(4) = sm::kinematics::angleMod(error(4));\n      error(5) = sm::kinematics::angleMod(error(5));\n      setError(error);\n      return evaluateChiSquaredError();\n    }\n\n    void ErrorTermPose::evaluateJacobiansImplementation(\n        aslam::backend::JacobianContainer& jacobians) {\n      Eigen::Matrix<double, 6, 6> J = Eigen::Matrix<double, 6, 6>::Identity();\n      const Eigen::Matrix4d T = _T.toTransformationMatrix();\n      J.topRightCorner<3, 3>() =\n        sm::kinematics::crossMx(T.topRightCorner<3, 1>());\n      const sm::kinematics::EulerAnglesYawPitchRoll ypr;\n      J.bottomRightCorner<3, 3>() = (ypr.parametersToSMatrix(\n        ypr.rotationMatrixToParameters(T.topLeftCorner<3, 3>()))).inverse();\n      _T.evaluateJacobians(jacobians, -J);\n    }\n\n  }\n}\n", "meta": {"hexsha": "2dbbf9d09e7e64c6da7deb805a6c835d7e342cf1", "size": 3869, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "incremental_calibration_examples/incremental_calibration_examples_time_delay/src/error-terms/ErrorTermPose.cpp", "max_stars_repo_name": "ethz-asl/aslam_incremental_calibration", "max_stars_repo_head_hexsha": "16a44b86b6e7eb5ae4ee247f10c429494697ae0b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2017-08-23T06:29:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-17T16:56:29.000Z", "max_issues_repo_path": "incremental_calibration_examples/incremental_calibration_examples_time_delay/src/error-terms/ErrorTermPose.cpp", "max_issues_repo_name": "ethz-asl/aslam_incremental_calibration", "max_issues_repo_head_hexsha": "16a44b86b6e7eb5ae4ee247f10c429494697ae0b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-02-14T16:02:18.000Z", "max_issues_repo_issues_event_max_datetime": "2017-02-14T16:02:18.000Z", "max_forks_repo_path": "incremental_calibration_examples/incremental_calibration_examples_time_delay/src/error-terms/ErrorTermPose.cpp", "max_forks_repo_name": "ethz-asl/aslam_incremental_calibration", "max_forks_repo_head_hexsha": "16a44b86b6e7eb5ae4ee247f10c429494697ae0b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2017-01-23T09:01:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-10T05:13:23.000Z", "avg_line_length": 34.2389380531, "max_line_length": 80, "alphanum_fraction": 0.4869475317, "num_tokens": 834, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.46101945200338956}}
{"text": "#include \"library_functions.hpp\"\n\n#include <Eigen/src/Core/Matrix.h>\n#include <cmath>\n#include <eigen3/Eigen/Core>\n#include \"eigen3/Eigen/Geometry\"\n#include <iostream>\n#include <math.h>\n#include <vector>\n#include \"amrl_shared_lib/math/geometry.h\"\n#include \"amrl_shared_lib/math/math_util.h\"\n\n#include \"ast.hpp\"\n\nusing AST::ast_ptr;\nusing AST::Bool;\nusing AST::bool_ptr;\nusing AST::Num;\nusing AST::num_ptr;\nusing AST::Type;\nusing AST::Vec;\nusing AST::vec_ptr;\nusing Eigen::Vector2f;\nusing Eigen::Vector3i;\nusing std::abs;\nusing std::array;\nusing std::cos;\nusing std::cout;\nusing std::dynamic_pointer_cast;\nusing std::endl;\nusing std::invalid_argument;\nusing std::make_shared;\nusing std::pow;\nusing std::sin;\nusing std::min;\nusing std::max;\nusing std::vector;\nusing geometry::Angle;\nusing math_util::AngleDist;\n\n#define ASSERT_DIM(expression, dimensionality)                  \\\n  {                                                             \\\n    if (expression->dims_ != dimensionality) {                  \\\n      throw invalid_argument(\"`\" #expression                    \\\n                             \"' has incorrect dimensionality\"); \\\n    }                                                           \\\n  }\n\n#define ASSERT_TYPE(expression, type)                                \\\n  {                                                                  \\\n    if (expression->type_ != type) {                                 \\\n      throw invalid_argument(\"type mismatch: expected `\" #expression \\\n                             \"' to have type `\" #type \"'\");          \\\n    }                                                                \\\n  }\n\n#define ASSERT_DIMS_EQUAL(left, right)                               \\\n  {                                                                  \\\n    if (left->dims_ != right->dims_) {                               \\\n      throw invalid_argument(\"expected `\" #left \"' and `\" #right     \\\n                             \"' to have the same dimensionalities\"); \\\n    }                                                                \\\n  }\n\n#define ASSERT_TYPES_EQUAL(left, right)                          \\\n  {                                                              \\\n    if (left->type_ != right->type_) {                           \\\n      throw invalid_argument(\"expected `\" #left \"' and `\" #right \\\n                             \"' to have the same types\");        \\\n    }                                                            \\\n  }\n\nast_ptr Plus(ast_ptr left, ast_ptr right) {\n  ASSERT_DIMS_EQUAL(left, right);\n  ASSERT_TYPES_EQUAL(left, right);\n  if (left->type_ == Type::NUM) {\n    num_ptr left_cast = dynamic_pointer_cast<Num>(left);\n    num_ptr right_cast = dynamic_pointer_cast<Num>(right);\n    Num result(left_cast->value_ + right_cast->value_, left->dims_);\n    return make_shared<Num>(result);\n  } else if (left->type_ == Type::VEC) {\n    vec_ptr left_cast = dynamic_pointer_cast<Vec>(left);\n    vec_ptr right_cast = dynamic_pointer_cast<Vec>(right);\n    Vec result(left_cast->value_ + right_cast->value_, left->dims_);\n    return make_shared<Vec>(result);\n  } else {\n    throw invalid_argument(\n        \"expected types of `left' and `right' to be `Type::NUM' or \"\n        \"`Type::VEC'\");\n  }\n}\n\nast_ptr Minus(ast_ptr left, ast_ptr right) {\n  ASSERT_DIMS_EQUAL(left, right);\n  ASSERT_TYPES_EQUAL(left, right);\n  if (left->type_ == Type::NUM) {\n    num_ptr left_cast = dynamic_pointer_cast<Num>(left);\n    num_ptr right_cast = dynamic_pointer_cast<Num>(right);\n    Num result(left_cast->value_ - right_cast->value_, left->dims_);\n    return make_shared<Num>(result);\n  } else if (left->type_ == Type::VEC) {\n    vec_ptr left_cast = dynamic_pointer_cast<Vec>(left);\n    vec_ptr right_cast = dynamic_pointer_cast<Vec>(right);\n    Vec result(left_cast->value_ - right_cast->value_, left->dims_);\n    return make_shared<Vec>(result);\n  } else {\n    throw invalid_argument(\n        \"expected types of `left' and `right' to be `Type::NUM' or \"\n        \"`Type::VEC'\");\n  }\n}\n\nast_ptr AngleDist(ast_ptr left, ast_ptr right) {\n  ASSERT_DIMS_EQUAL(left, right);\n  ASSERT_TYPES_EQUAL(left, right);\n  if (left->type_ == Type::NUM) {\n    num_ptr left_cast = dynamic_pointer_cast<Num>(left);\n    num_ptr right_cast = dynamic_pointer_cast<Num>(right);\n    Num result(AngleDist(left_cast->value_, right_cast->value_), left->dims_);\n    return make_shared<Num>(result);\n  } else {\n    throw invalid_argument(\n        \"expected types of `left' and `right' to be `Type::NUM'\");\n  }\n}\n\nast_ptr Times(ast_ptr left, ast_ptr right) {\n  ASSERT_TYPE(left, Type::NUM);\n\n  num_ptr left_cast = dynamic_pointer_cast<Num>(left);\n  if (right->type_ == Type::NUM) {\n    num_ptr right_cast = dynamic_pointer_cast<Num>(right);\n    Num result(left_cast->value_ * right_cast->value_,\n               left->dims_ + right->dims_);\n    return make_shared<Num>(result);\n  } else if (right->type_ == Type::VEC) {\n    vec_ptr right_cast = dynamic_pointer_cast<Vec>(right);\n    Vec result(left_cast->value_ * right_cast->value_,\n               left->dims_ + right->dims_);\n    return make_shared<Vec>(result);\n  } else {\n    throw invalid_argument(\n        \"expected type of `left' to be `Type::NUM' and/or expected type of \"\n        \"`right' to be `Type::NUM' or `Type::VEC'\");\n  }\n}\n\nast_ptr DividedBy(ast_ptr left, ast_ptr right) {\n  ASSERT_TYPE(left, Type::NUM);\n\n  num_ptr right_cast = dynamic_pointer_cast<Num>(right);\n  if (left->type_ == Type::NUM) {\n    num_ptr left_cast = dynamic_pointer_cast<Num>(left);\n    Num result(left_cast->value_ / right_cast->value_,\n               left->dims_ - right->dims_);\n    return make_shared<Num>(result);\n  } else if (left->type_ == Type::VEC) {\n    vec_ptr left_cast = dynamic_pointer_cast<Vec>(right);\n    Vec result(left_cast->value_ / right_cast->value_,\n               left->dims_ - right->dims_);\n    return make_shared<Vec>(result);\n  } else {\n    throw invalid_argument(\n        \"expected type of `left' to be `Type::NUM' and/or expected type of \"\n        \"`right' to be `Type::NUM' or `Type::VEC'\");\n  }\n}\n\nast_ptr Abs(ast_ptr operand) {\n  ASSERT_TYPE(operand, Type::NUM);\n\n  num_ptr operand_cast = dynamic_pointer_cast<Num>(operand);\n  Num result(abs(operand_cast->value_), operand->dims_);\n  return make_shared<Num>(result);\n}\n\nast_ptr Pow(ast_ptr base, ast_ptr power) {\n  ASSERT_DIM(power, Vector3i(0, 0, 0));\n  ASSERT_TYPE(base, Type::NUM);\n  ASSERT_TYPE(power, Type::NUM);\n\n  num_ptr base_cast = dynamic_pointer_cast<Num>(base);\n  num_ptr power_cast = dynamic_pointer_cast<Num>(power);\n  // TODO(simon) figure out something better for dimensionalities\n  Num result(pow(base_cast->value_, power_cast->value_),\n             base->dims_ * (int)power_cast->value_);\n  return make_shared<Num>(result);\n}\n\nast_ptr Sq(ast_ptr x) {\n  ASSERT_TYPE(x, Type::NUM);\n\n  num_ptr x_cast = dynamic_pointer_cast<Num>(x);\n  Num result(x_cast->value_ * x_cast->value_, 2 * x_cast->dims_);\n  return make_shared<Num>(result);\n}\n\nast_ptr Cos(ast_ptr theta) {\n  ASSERT_DIM(theta, Vector3i(0, 0, 0));\n  ASSERT_TYPE(theta, Type::NUM);\n\n  num_ptr theta_cast = dynamic_pointer_cast<Num>(theta);\n  Num result(cos(theta_cast->value_), {0, 0, 0});\n  return make_shared<Num>(result);\n}\n\nast_ptr Sin(ast_ptr theta) {\n  ASSERT_DIM(theta, Vector3i(0, 0, 0));\n  ASSERT_TYPE(theta, Type::NUM);\n\n  num_ptr theta_cast = dynamic_pointer_cast<Num>(theta);\n  Num result(sin(theta_cast->value_), {0, 0, 0});\n  return make_shared<Num>(result);\n}\n\nast_ptr Cross(ast_ptr u, ast_ptr v) {\n  ASSERT_DIMS_EQUAL(u, v);\n  ASSERT_TYPE(u, Type::VEC);\n  ASSERT_TYPE(v, Type::VEC);\n\n  vec_ptr u_cast = dynamic_pointer_cast<Vec>(u);\n  vec_ptr v_cast = dynamic_pointer_cast<Vec>(v);\n  // TODO(simon) check dimensionality is correct\n  Num result(u_cast->value_.x() * v_cast->value_.y() +\n                 u_cast->value_.y() * v_cast->value_.x(),\n             u_cast->dims_);\n  return make_shared<Num>(result);\n}\n\nast_ptr Dot(ast_ptr u, ast_ptr v) {\n  ASSERT_TYPE(u, Type::VEC);\n  ASSERT_TYPE(v, Type::VEC);\n\n  vec_ptr u_cast = dynamic_pointer_cast<Vec>(u);\n  vec_ptr v_cast = dynamic_pointer_cast<Vec>(v);\n  Num result(u_cast->value_.dot(v_cast->value_), u->dims_);\n  return make_shared<Num>(result);\n}\n\nast_ptr SqDist(ast_ptr u, ast_ptr v) {\n  ASSERT_DIMS_EQUAL(u, v)\n  ASSERT_TYPE(u, Type::VEC);\n  ASSERT_TYPE(v, Type::VEC);\n\n  vec_ptr u_cast = dynamic_pointer_cast<Vec>(u);\n  vec_ptr v_cast = dynamic_pointer_cast<Vec>(v);\n  const float euc_dist = (u_cast->value_ - v_cast->value_).norm();\n  Num result(euc_dist, u->dims_);\n  return make_shared<Num>(result);\n}\n\nast_ptr Angle(ast_ptr v) {\n  ASSERT_TYPE(v, Type::VEC);\n\n  vec_ptr v_cast = dynamic_pointer_cast<Vec>(v);\n  Num result(atan2(v_cast->value_.y(), v_cast->value_.x()), {0, 0, 0});\n  return make_shared<Num>(result);\n}\n\nast_ptr Heading(ast_ptr theta) {\n  ASSERT_DIM(theta, Vector3i(0, 0, 0));\n  ASSERT_TYPE(theta, Type::NUM);\n\n  num_ptr theta_cast = dynamic_pointer_cast<Num>(theta);\n  Vec result({cos(theta_cast->value_), sin(theta_cast->value_)}, {0, 0, 0});\n  return make_shared<Vec>(result);\n}\n\nast_ptr NormSq(ast_ptr v) {\n  ASSERT_TYPE(v, Type::VEC);\n\n  vec_ptr v_cast = dynamic_pointer_cast<Vec>(v);\n  const float norm = v_cast->value_.norm();\n  Num result(pow(norm, 2), v->dims_);\n  return make_shared<Num>(result);\n}\n\nast_ptr Perp(ast_ptr v) {\n  ASSERT_TYPE(v, Type::VEC);\n\n  vec_ptr v_cast = dynamic_pointer_cast<Vec>(v);\n  Vec result({-v_cast->value_.y(), v_cast->value_.x()}, v->dims_);\n  return make_shared<Vec>(result);\n}\n\nast_ptr VecX(ast_ptr v) {\n  ASSERT_TYPE(v, Type::VEC);\n\n  vec_ptr v_cast = dynamic_pointer_cast<Vec>(v);\n  Num result(v_cast->value_.x(), v->dims_);\n  return make_shared<Num>(result);\n}\n\nast_ptr VecY(ast_ptr v) {\n  ASSERT_TYPE(v, Type::VEC);\n\n  vec_ptr v_cast = dynamic_pointer_cast<Vec>(v);\n  Num result(v_cast->value_.y(), v->dims_);\n  return make_shared<Num>(result);\n}\n\nast_ptr And(ast_ptr P, ast_ptr Q) {\n  ASSERT_TYPE(P, Type::BOOL);\n  ASSERT_TYPE(Q, Type::BOOL);\n\n  bool_ptr P_cast = dynamic_pointer_cast<Bool>(P);\n  bool_ptr Q_cast = dynamic_pointer_cast<Bool>(Q);\n  Bool result(P_cast->value_ && Q_cast->value_);\n  return make_shared<Bool>(result);\n}\n\nast_ptr Or(ast_ptr P, ast_ptr Q) {\n  ASSERT_TYPE(P, Type::BOOL);\n  ASSERT_TYPE(Q, Type::BOOL);\n\n  bool_ptr P_cast = dynamic_pointer_cast<Bool>(P);\n  bool_ptr Q_cast = dynamic_pointer_cast<Bool>(Q);\n  Bool result(P_cast->value_ || Q_cast->value_);\n  return make_shared<Bool>(result);\n}\n\nast_ptr Not(ast_ptr P) {\n  ASSERT_TYPE(P, Type::BOOL);\n\n  bool_ptr P_cast = dynamic_pointer_cast<Bool>(P);\n  Bool result(!P_cast->value_);\n  return make_shared<Bool>(result);\n}\n\nast_ptr Eq(ast_ptr x, ast_ptr y) {\n  ASSERT_TYPE(x, Type::NUM);\n  ASSERT_TYPE(y, Type::NUM);\n\n  num_ptr x_cast = dynamic_pointer_cast<Num>(x);\n  num_ptr y_cast = dynamic_pointer_cast<Num>(y);\n  Bool result(x_cast->value_ == y_cast->value_);\n  return make_shared<Bool>(result);\n}\n\nast_ptr Lt(ast_ptr x, ast_ptr y) {\n  ASSERT_TYPE(x, Type::NUM);\n  ASSERT_TYPE(y, Type::NUM);\n\n  num_ptr x_cast = dynamic_pointer_cast<Num>(x);\n  num_ptr y_cast = dynamic_pointer_cast<Num>(y);\n  Bool result(x_cast->value_ - y_cast->value_ < 0.0);\n  return make_shared<Bool>(result);\n}\n\nast_ptr Gt(ast_ptr x, ast_ptr y) {\n  ASSERT_TYPE(x, Type::NUM);\n  ASSERT_TYPE(y, Type::NUM);\n\n  num_ptr x_cast = dynamic_pointer_cast<Num>(x);\n  num_ptr y_cast = dynamic_pointer_cast<Num>(y);\n  Bool result(x_cast->value_ - y_cast->value_ > 0);\n  return make_shared<Bool>(result);\n}\n\nast_ptr Lte(ast_ptr x, ast_ptr y) {\n  ASSERT_TYPE(x, Type::NUM);\n  ASSERT_TYPE(y, Type::NUM);\n\n  num_ptr x_cast = dynamic_pointer_cast<Num>(x);\n  num_ptr y_cast = dynamic_pointer_cast<Num>(y);\n  Bool result(x_cast->value_ <= y_cast->value_);\n  return make_shared<Bool>(result);\n}\n\nast_ptr Gte(ast_ptr x, ast_ptr y) {\n  ASSERT_TYPE(x, Type::NUM);\n  ASSERT_TYPE(y, Type::NUM);\n\n  num_ptr x_cast = dynamic_pointer_cast<Num>(x);\n  num_ptr y_cast = dynamic_pointer_cast<Num>(y);\n  Bool result(x_cast->value_ >= y_cast->value_);\n  return make_shared<Bool>(result);\n}\n\nast_ptr StraightFreePathLength(ast_ptr v,\n    const vector<Vector2f> obstacles) {\n  //TODO(jaholtz) need to set these to sane defaults (copy from sim)\n  const float kRobotLength = 0.5;\n  const float kRearAxleOffset = 0.0;\n  const float kObstacleMargin = 0.5;\n  const float kRobotWidth = 0.44;\n\n  ASSERT_TYPE(v, Type::VEC);\n  vec_ptr v_cast = dynamic_pointer_cast<Vec>(v);\n  const Vector2f end = v_cast->value_;\n\n  // How much the robot's body extends in front of its base link frame.\n  const float l = 0.5 * kRobotLength - kRearAxleOffset + kObstacleMargin;\n  // The robot's half-width.\n  const float w = 0.5 * kRobotWidth + kObstacleMargin;\n\n  float free_path_length = end.norm();\n  const float angle = Angle(end);\n  const Eigen::Rotation2Df rot(-angle);\n\n  for (const Vector2f& obst :obstacles) {\n    Vector2f pose(obst.x(), obst.y());\n    // Assuming robot frame, no transform.\n    const Vector2f p = rot * pose;\n    // If outside width, or behind robot, skip\n    if (fabs(p.y()) > w || p.x() < 0.0f) continue;\n    // Calculate distance and store if shorter.\n    free_path_length = min(free_path_length, p.x() - l);\n  }\n  // cout << \"Free Length: \" << free_path_length << endl;\n  // cout << \"End Norm: \" << end.norm() << endl;\n  if (fabs(free_path_length - end.norm()) < geometry::kEpsilon) {\n    free_path_length = 9999;\n  }\n  if (free_path_length < 0.0) {\n    free_path_length = 0;\n  }\n  Num result(free_path_length, {1, 0, 0});\n  return make_shared<Num>(result);\n}\n\n// TODO(simon) implement everything after this point with AST stuff\n\nfloat Average(vector<float> xs) {\n  float average = 0.0f;\n  for (float x : xs) {\n    average += x;\n  }\n  average /= xs.size();\n  return average;\n}\n\nenum Orientation { CLOCKWISE, COLINEAR, COUNTERCLOCKWISE };\n\nOrientation three_point_orientation(Vector2f p0, Vector2f p1, Vector2f p2) {\n  float difference = ((p1.y() - p0.y()) * (p2.x() - p1.x())) -\n                     ((p1.x() - p0.x()) * (p2.y() - p1.y()));\n  if (abs(difference) < 1.0e-6f) {\n    return COLINEAR;\n  } else if (difference > 0.0f) {\n    return CLOCKWISE;\n  } else {\n    return COUNTERCLOCKWISE;\n  }\n}\n\nPolygon ConvexHull(Polygon a, Polygon b) {\n  // Create a vector containing every in either polygon.\n  vector<Vector2f> all_vertices;\n  all_vertices.reserve(a.vertices.size() + b.vertices.size());\n  all_vertices.insert(all_vertices.end(), a.vertices.begin(), a.vertices.end());\n  all_vertices.insert(all_vertices.end(), b.vertices.begin(), b.vertices.end());\n\n  // Find the leftmost vertex, which is guaranteed to be in the hull.\n  size_t leftmost_point_index = 0;\n  for (size_t i = 1; i < all_vertices.size(); ++i) {\n    if (all_vertices[i].x() < all_vertices[leftmost_point_index].x()) {\n      leftmost_point_index = i;\n    }\n  }\n\n  // Find the rest of the hull using gift-wrapping/Jarvis's algorithm\n  vector<Vector2f> hull;\n  size_t current_point_index = leftmost_point_index;\n  do {\n    hull.push_back(all_vertices[current_point_index]);\n    size_t next_point_index = (current_point_index + 1) % all_vertices.size();\n    for (size_t i = 0; i < all_vertices.size(); ++i) {\n      if (three_point_orientation(\n              all_vertices[current_point_index], all_vertices[i],\n              all_vertices[next_point_index]) == COUNTERCLOCKWISE) {\n        next_point_index = i;\n      }\n    }\n    current_point_index = next_point_index;\n  } while (current_point_index != leftmost_point_index);\n\n  return {hull};\n}\n\nbool PointInPolygon(Vector2f point, Polygon polygon) {\n  const size_t vertex_count = polygon.vertices.size();\n  const Ray ray = {point, Vector2f(1, 0)};\n  size_t crossing_count = 0;\n  for (size_t i = 0; i < vertex_count; ++i) {\n    const size_t j = (i + 1) % vertex_count;\n    const LineSegment edge = {polygon.vertices[i], polygon.vertices[j]};\n    if (RayIntersection(ray, edge)) {\n      crossing_count += 1;\n    }\n  }\n  return (crossing_count % 2) == 1;\n}\n\nfloat cross2d(Vector2f u, Vector2f v) { return u.x() * v.y() - u.y() * v.x(); }\n\nbool RayIntersection(Ray ray, LineSegment line_segment) {\n  const Vector2f p = {-ray.direction.y(), ray.direction.x()};\n  const Vector2f a_to_origin = ray.origin - line_segment.a;\n  const Vector2f a_to_b = line_segment.b - line_segment.a;\n\n  const float denominator = a_to_b.dot(p);\n  if (denominator <= 1.0e-6f) {\n    return false;\n  }\n\n  const float t1 = abs(cross2d(a_to_b, a_to_origin)) / denominator;\n  const float t2 = a_to_origin.dot(p) / denominator;\n\n  return (t2 >= 0.0f) && (t2 <= 1.0f) && (t1 >= 0.0f);\n}\n", "meta": {"hexsha": "f600de13b4e47e7eca741cdba6ab40114d68786d", "size": 16525, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ast/library_functions.cpp", "max_stars_repo_name": "ut-amrl/pips", "max_stars_repo_head_hexsha": "1f553dc850f8c27a460f020d91b35c8a18c479bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ast/library_functions.cpp", "max_issues_repo_name": "ut-amrl/pips", "max_issues_repo_head_hexsha": "1f553dc850f8c27a460f020d91b35c8a18c479bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ast/library_functions.cpp", "max_forks_repo_name": "ut-amrl/pips", "max_forks_repo_head_hexsha": "1f553dc850f8c27a460f020d91b35c8a18c479bb", "max_forks_repo_licenses": ["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.275390625, "max_line_length": 80, "alphanum_fraction": 0.6434493192, "num_tokens": 4454, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.4609491702419888}}
{"text": "// Copyright John Maddock 2006.\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\r\n#include <boost/math/tools/test_data.hpp>\r\n#include <boost/test/included/prg_exec_monitor.hpp>\r\n#include <boost/math/special_functions/ellint_3.hpp>\r\n#include <fstream>\r\n#include <boost/math/tools/test_data.hpp>\r\n#include <boost/random.hpp>\r\n#include \"mp_t.hpp\"\r\n\r\nfloat extern_val;\r\n// confuse the compilers optimiser, and force a truncation to float precision:\r\nfloat truncate_to_float(float const * pf)\r\n{\r\n   extern_val = *pf;\r\n   return *pf;\r\n}\r\n\r\nboost::math::tuple<mp_t, mp_t> generate_data(mp_t n, mp_t phi)\r\n{\r\n   static boost::mt19937 r;\r\n   boost::uniform_real<float> ui(0, 1);\r\n   float k = ui(r);\r\n   mp_t kr(truncate_to_float(&k));\r\n   mp_t result = boost::math::ellint_3(kr, n, phi);\r\n   return boost::math::make_tuple(kr, result);\r\n}\r\n\r\nint cpp_main(int argc, char*argv [])\r\n{\r\n   using namespace boost::math::tools;\r\n\r\n   parameter_info<mp_t> arg1, arg2;\r\n   test_data<mp_t> data;\r\n\r\n   bool cont;\r\n   std::string line;\r\n\r\n   if(argc < 1)\r\n      return 1;\r\n\r\n   do{\r\n      if(0 == get_user_parameter_info(arg1, \"n\"))\r\n         return 1;\r\n      if(0 == get_user_parameter_info(arg2, \"phi\"))\r\n         return 1;\r\n\r\n      data.insert(&generate_data, arg1, arg2);\r\n\r\n      std::cout << \"Any more data [y/n]?\";\r\n      std::getline(std::cin, line);\r\n      boost::algorithm::trim(line);\r\n      cont = (line == \"y\");\r\n   }while(cont);\r\n\r\n   std::cout << \"Enter name of test data file [default=ellint_pi3_data.ipp]\";\r\n   std::getline(std::cin, line);\r\n   boost::algorithm::trim(line);\r\n   if(line == \"\")\r\n      line = \"ellint_pi3_data.ipp\";\r\n   std::ofstream ofs(line.c_str());\r\n   line.erase(line.find('.'));\r\n   ofs << std::scientific << std::setprecision(40);\r\n   write_code(ofs, data, line.c_str());\r\n\r\n   return 0;\r\n}\r\n\r\n\r\n", "meta": {"hexsha": "b77c951d12670472421974ff0b1e94d723283a31", "size": 1970, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/math/tools/ellint_pi3_data.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": 85.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T20:36:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T20:38:31.000Z", "max_issues_repo_path": "libs/boost/libs/math/tools/ellint_pi3_data.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/tools/ellint_pi3_data.cpp", "max_forks_repo_name": "flingone/frameworks_base_cmds_remoted", "max_forks_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2015-01-28T16:33:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-12T05:04:39.000Z", "avg_line_length": 25.9210526316, "max_line_length": 79, "alphanum_fraction": 0.6329949239, "num_tokens": 534, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. Yes\n2. Yes", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.7981867849406659, "lm_q1q2_score": 0.46094916885579884}}
{"text": "//\n// Created by huangkun on 2020/2/28.\n//\n\n#ifndef OPENGV2_SPLINEBUNDLEADJUSTMENTV2_HPP\n#define OPENGV2_SPLINEBUNDLEADJUSTMENTV2_HPP\n\n#include <Eigen/Eigen>\n#include <ceres/rotation.h>\n\n#include <opengv2/bundle_adjustment/BundleAdjustmentBase.hpp>\n#include <opengv2/spline/BsplineReal.hpp>\n\nnamespace opengv2 {\n    class SplineBundleAdjustmentV2 : public BundleAdjustmentBase {\n    public:\n        EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n        SplineBundleAdjustmentV2(bool fixTsb, bool robust);\n\n        void\n        run(const std::map<double, Bodyframe::Ptr> &keyframes,\n            const std::map<int, LandmarkBase::Ptr> &landmarks) override;\n\n        template<class T>\n        static inline void\n        derToRotMatrix(const Eigen::Matrix<T, 3, 1> &unitY, const T &theta, Eigen::Matrix<T, 3, 3> &Rbw) {\n            Rbw.row(1) = unitY.transpose();\n            Eigen::Matrix<T, 3, 1> n = unitY.cross(Eigen::Vector3d(0, 0, 1));\n            n.normalize();\n            Eigen::Matrix<T, 3, 1> z = n.cross(unitY);\n\n            Rbw.row(2) = (ceres::cos(theta) * z + ceres::sin(theta) * n).transpose();\n            Rbw.row(2) /= Rbw.row(2).norm();\n            Rbw.row(0) = Rbw.row(1).cross(Rbw.row(2)); // X = Y x Z\n        }\n\n        static inline void rotMatrixToDer(const Eigen::Matrix3d &Rbw, Eigen::Vector3d &unitY, double &theta) {\n            unitY = Rbw.row(1).transpose();\n\n            Eigen::Vector3d n = unitY.cross(Eigen::Vector3d(0, 0, 1));\n            n /= n.norm();\n            Eigen::Vector3d z = n.cross(unitY);\n            z /= z.norm();\n\n            double tmp = Rbw.row(2) * z;\n            theta = std::acos(tmp > 1.0 ? 1.0 : tmp);// [0, pi]\n\n            if (Rbw.row(2) * n < 0)\n                theta = -theta;\n        }\n\n\n        struct ReprojectionError {\n            EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n            ReprojectionError(const Eigen::Ref<const Eigen::Vector3d> &bearingVector,\n                              std::shared_ptr<std::vector<std::vector<double>>> basis,\n                              bool isMono)\n                    : isMono_(isMono), bearingVector_(bearingVector), basis_(std::move(basis)) {}\n\n            template<typename T>\n            bool operator()(const T *const cp0, const T *const cp1, const T *const cp2, const T *const cp3,\n                            const T *const lm, const T *const Tcb, T *residuals) const {\n                // Map to Eigen type\n                Eigen::Map<Eigen::Matrix<T, 4, 1> const> const cp_0(cp0);\n                Eigen::Map<Eigen::Matrix<T, 4, 1> const> const cp_1(cp1);\n                Eigen::Map<Eigen::Matrix<T, 4, 1> const> const cp_2(cp2);\n                Eigen::Map<Eigen::Matrix<T, 4, 1> const> const cp_3(cp3);\n                Eigen::Map<Eigen::Matrix<T, 3, 1> const> const lm_e(lm);\n                Eigen::Quaternion<T> Qcb(Tcb);\n                Qcb.normalize();\n                Eigen::Map<Eigen::Matrix<T, 3, 1> const> const tcb(Tcb + 4);\n                Eigen::Map<Eigen::Matrix<T, 3, 1>> res(residuals);\n\n                // spline evaluation\n                Eigen::Matrix<T, 4, 1> twb_theta = basis_->at(0)[0] * cp_0 + basis_->at(0)[1] * cp_1 +\n                                                   basis_->at(0)[2] * cp_2 + basis_->at(0)[3] * cp_3;\n                Eigen::Matrix<T, 3, 1> y = basis_->at(1)[0] * cp_0.head(3) + basis_->at(1)[1] * cp_1.head(3) +\n                                           basis_->at(1)[2] * cp_2.head(3) + basis_->at(1)[3] * cp_3.head(3);\n                y.normalize();\n\n                Eigen::Matrix<T, 3, 3> Rbw;\n                derToRotMatrix(y, twb_theta[3], Rbw);\n\n                Eigen::Matrix<T, 3, 1> Xb = Rbw * (lm_e - twb_theta.head(3));\n                Eigen::Matrix<T, 3, 1> Xc = Qcb * Xb + tcb;\n                if (isMono_)\n                    Xc.normalize();\n\n                res = bearingVector_ - Xc;\n                return true;\n            }\n\n            static ceres::CostFunction *\n            Create(const Eigen::Ref<const Eigen::Vector3d> &bearingVector,\n                   const std::shared_ptr<std::vector<std::vector<double>>> &basis, bool isMono) {\n                return (new ceres::AutoDiffCostFunction<ReprojectionError, 3, 4, 4, 4, 4, 3, 7>(\n                        new ReprojectionError(bearingVector, basis, isMono)));\n            }\n\n            bool isMono_;\n            Eigen::Vector3d bearingVector_;\n\n            // for spline evaluation\n            std::shared_ptr<std::vector<std::vector<double>>> basis_;\n        };\n\n    protected:\n        void optimize(ceres::Problem &problem,\n                      const std::map<double, Bodyframe::Ptr> &keyframes,\n                      const std::map<int, LandmarkBase::Ptr> &landmarks) override;\n\n        bool fixTsb_;\n        bool robust_;\n\n        BsplineReal<4> Tspline_; // twb[3] + angle, by cubic spline\n    };\n}\n\n#endif //OPENGV2_SPLINEBUNDLEADJUSTMENTV2_HPP\n", "meta": {"hexsha": "09f3cb9a032cbeab0f2b84c7ac5351f67cf4175a", "size": 4858, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/bundle_adjustment/include/opengv2/bundle_adjustment/SplineBundleAdjustmentV2.hpp", "max_stars_repo_name": "MobilePerceptionLab/EventCameraCalibration", "max_stars_repo_head_hexsha": "debd774ac989674b500caf27641b7ad4e94681e9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2021-08-06T03:21:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T03:40:54.000Z", "max_issues_repo_path": "modules/core/bundle_adjustment/include/opengv2/bundle_adjustment/SplineBundleAdjustmentV2.hpp", "max_issues_repo_name": "MobilePerceptionLab/MultiCamCalib", "max_issues_repo_head_hexsha": "2f0e94228c2c4aea7f20c26e3e8daa6321ce8022", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-02-25T02:55:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-25T15:18:45.000Z", "max_forks_repo_path": "modules/core/bundle_adjustment/include/opengv2/bundle_adjustment/SplineBundleAdjustmentV2.hpp", "max_forks_repo_name": "MobilePerceptionLab/MultiCamCalib", "max_forks_repo_head_hexsha": "2f0e94228c2c4aea7f20c26e3e8daa6321ce8022", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2021-08-11T12:29:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-25T03:41:01.000Z", "avg_line_length": 39.8196721311, "max_line_length": 110, "alphanum_fraction": 0.5321119802, "num_tokens": 1377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.46094916469722885}}
{"text": "#include <iostream>\n#include <string>\n#include <cmath>\n#include <boost/array.hpp>\n#include <boost/numeric/odeint.hpp>\n#include <boost/range/numeric.hpp>\n#include <OpenMesh/Core/IO/MeshIO.hh>\n#include <OpenMesh/Core/Mesh/TriMesh_ArrayKernelT.hh>\n#include <OpenMesh/Tools/Subdivider/Uniform/LoopT.hh>\n#include <tuple>\n\n\ntypedef OpenMesh::TriMesh_ArrayKernelT<>  MyMesh;\n\n\nusing namespace std;\nusing namespace boost::numeric::odeint;\n\nconst double sigma = 1.1;\nconst double beta = .4;\nconst double delta = .1;\nconst double phi = .4;\n\ntypedef boost::array< double , 2 > state_type;\n\n\n\n\nvoid ODE( const state_type &x , state_type &dxdt , double t )\n{\n    dxdt[0] = (sigma * x[0]) - (beta*x[0]*x[1]);\n    dxdt[1] = (delta * x[0] * x[1]) - (phi * x[1]);\n}\n\n\n\ndouble prey_count[100];\ndouble pred_count[100];\nint i = 0;\ntuple<double, double> write_ODE( const state_type &x , const double t )\n{\n    \n    prey_count[i] = x[0];\n    pred_count[i] = x[1];\n\n    cout << t << '\\t' << x[0] << '\\t' << x[1] << '\\t' << prey_count[i] << endl;\n\n\n    i++;\n    return std::make_tuple(pred_count[i], prey_count[i]);\n\n}\n\n \n\nint main()\n{\n  MyMesh mesh;\n\n  //Create Vertices\n  MyMesh::VertexHandle vhandle[3];\n  vhandle[0] = mesh.add_vertex(MyMesh::Point( 0, 0 ,  0));\n  vhandle[1] = mesh.add_vertex(MyMesh::Point( 1, 0 ,  0));\n  vhandle[2] = mesh.add_vertex(MyMesh::Point( 1, 1 ,  0));\n  vhandle[3] = mesh.add_vertex(MyMesh::Point( 0, 1 ,  0));\n \n  //Create Faces\n  std::vector<MyMesh::VertexHandle>  face_vhandles;\n  face_vhandles.clear();\n  face_vhandles.push_back(vhandle[0]);\n  face_vhandles.push_back(vhandle[1]);\n  face_vhandles.push_back(vhandle[2]);\n  face_vhandles.push_back(vhandle[3]);\n  mesh.add_face(face_vhandles);\n\n\n // Initialize Subdivider Tool\n OpenMesh::Subdivider::Uniform::LoopT<MyMesh> Loop;\n\n\n // Execute 5 subdivision steps\n Loop.attach(mesh);\n Loop( 3 );\n Loop.detach();\n\n // Solve ODE\n state_type x = { 30 , 30}; // initial conditions\n runge_kutta4< state_type > stepper;\n integrate(ODE, x, 0.0, 100.0, 0.01, write_ODE);\n  for (int k = 0; k<i; k++)\n  { cout << prey_count[k] << endl; }\n\n\n\n// integrate_n_steps( stepper , ODE , x , 0.0, 1.0 , 50, write_ODE );\n\n\nstring Output;\n\n\nOpenMesh::IO::Options wopt;\nwopt = OpenMesh::IO::Options::FaceColor;\n\n mesh.request_face_colors();\n\nfor (int count = 0; count<i; count++)\n{\n\tint count_prey = prey_count[count];\n\tint count_pred = pred_count[count];\n\tint total_count = count_prey + count_pred;\n\tint z = 0;\n\tint y = 0;\n\n\tfor (MyMesh::FaceIter f_it=mesh.faces_begin();  f_it !=mesh.faces_end(); ++f_it)\n\t{ \n\n\t\n\t      \t\n\t\tif ( z < count_prey)\n\t\t\t{\n\t\t    \t\tmesh.set_color(*f_it,MyMesh::Color(0,0,255));\n\t\t\t}\n\t\n\t\telse if ( (y > count_prey) && (y < total_count) )\n\t\t\t{\n\t\t\t\tmesh.set_color(*f_it,MyMesh::Color(255,0,0));\n\t\t\n\t\t\t}\n\t\n\t\telse\n\t\t\t{\n\t\t       \t        mesh.set_color(*f_it,MyMesh::Color(0,0,0));\n\t\t\t}\n\n\t\t\tz++;\n\t\t\ty++;\n\t}\n\n\n\n\n\t\t\n\nOutput = std::to_string(count) + \"output.off\";\nOpenMesh::IO::write_mesh(mesh, Output, wopt);\n\n}\n\nreturn 0;\n\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "c653ea5d1dd4dd82ff2e1aaf848e8665448826ab", "size": 2995, "ext": "cc", "lang": "C++", "max_stars_repo_path": "ODE Mesh Example.cc", "max_stars_repo_name": "wzinser/OpenMesh-Research", "max_stars_repo_head_hexsha": "28f49b2f0cd15f26cdb245dda391d9bde3426367", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ODE Mesh Example.cc", "max_issues_repo_name": "wzinser/OpenMesh-Research", "max_issues_repo_head_hexsha": "28f49b2f0cd15f26cdb245dda391d9bde3426367", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ODE Mesh Example.cc", "max_forks_repo_name": "wzinser/OpenMesh-Research", "max_forks_repo_head_hexsha": "28f49b2f0cd15f26cdb245dda391d9bde3426367", "max_forks_repo_licenses": ["BSD-3-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.1515151515, "max_line_length": 81, "alphanum_fraction": 0.6340567613, "num_tokens": 963, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867681382279, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.4609491591524687}}
{"text": "#ifndef CPP_TENSOR_LINE_DEFINITIONS_HH\n#define CPP_TENSOR_LINE_DEFINITIONS_HH\n\n#include <Eigen/Core>\n\nnamespace tl\n{\n\nusing Vec3d = Eigen::Vector3d;\nusing Mat3d = Eigen::Matrix3d;\n\n\n/**\n * Rank/order of an eigenvalue of a 3x3 matrix\n */\nenum class ERank : int\n{\n    First = 0,\n    Second = 1,\n    Third = 2\n};\n\n\n/**\n * Tensor line solution point.\n */\nstruct TLPoint\n{\n    Vec3d pos; ///< position\n    ERank s_rank; ///< rank of eigenvector of tensor field S\n    ERank t_rank; ///< rank of eigenvector of tensor field T\n    Vec3d eivec; ///< Eigenvector direction\n    double s_eival; ///< Eigenvalue for tensor field S\n    double t_eival; ///< Eigenvalue for tensor field T\n    bool s_has_imaginary; ///< S has any imaginary eigenvalues at the position\n    bool t_has_imaginary; ///< T has any imaginary eigenvalues at the position\n    std::size_t cluster_size; ///< Number of candidate points that contributed\n    double pos_uncertainty; ///< Size of the last subdivision cell in\n                            /// position space\n    double dir_uncertainty; ///< Size of the last subdivision cell in\n                            /// direction space\n    double line_stability; ///< Measure of numeric stability of the solution\n};\n\n} // namespace tl\n\n#endif\n", "meta": {"hexsha": "ab8cd153f267dca1b1fb9820f08f63c27c7181e8", "size": 1252, "ext": "hh", "lang": "C++", "max_stars_repo_path": "cpp/src/TensorLineDefinitions.hh", "max_stars_repo_name": "timo-oster/tensor-lines", "max_stars_repo_head_hexsha": "b4f489452f3ce5b5f48042cc035e53d3fdaa675e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cpp/src/TensorLineDefinitions.hh", "max_issues_repo_name": "timo-oster/tensor-lines", "max_issues_repo_head_hexsha": "b4f489452f3ce5b5f48042cc035e53d3fdaa675e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp/src/TensorLineDefinitions.hh", "max_forks_repo_name": "timo-oster/tensor-lines", "max_forks_repo_head_hexsha": "b4f489452f3ce5b5f48042cc035e53d3fdaa675e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-13T00:08:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-13T00:08:09.000Z", "avg_line_length": 26.0833333333, "max_line_length": 78, "alphanum_fraction": 0.6693290735, "num_tokens": 307, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867585368343, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4609491536077085}}
{"text": "//\n// Copyright (c) 2017-2020 CNRS INRIA\n//\n\n#include \"pinocchio/multibody/model.hpp\"\n#include \"pinocchio/multibody/data.hpp\"\n#include \"pinocchio/algorithm/jacobian.hpp\"\n#include \"pinocchio/algorithm/joint-configuration.hpp\"\n#include \"pinocchio/algorithm/kinematics.hpp\"\n#include \"pinocchio/algorithm/kinematics-derivatives.hpp\"\n#include \"pinocchio/algorithm/rnea.hpp\"\n#include \"pinocchio/algorithm/rnea-derivatives.hpp\"\n#include \"pinocchio/algorithm/crba.hpp\"\n#include \"pinocchio/parsers/sample-models.hpp\"\n\n#include <iostream>\n\n#include <boost/test/unit_test.hpp>\n#include <boost/utility/binary.hpp>\n\nBOOST_AUTO_TEST_SUITE(BOOST_TEST_MODULE)\n\nBOOST_AUTO_TEST_CASE(test_generalized_gravity_derivatives)\n{\n  using namespace Eigen;\n  using namespace pinocchio;\n\n  Model model;\n  buildModels::humanoidRandom(model);\n  \n  Data data(model), data_fd(model);\n  \n  model.lowerPositionLimit.head<3>().fill(-1.);\n  model.upperPositionLimit.head<3>().fill(1.);\n  VectorXd q = randomConfiguration(model);\n  VectorXd v(VectorXd::Zero(model.nv));\n  VectorXd a(VectorXd::Zero(model.nv));\n  \n  /// Check againt non-derivative algo\n  MatrixXd g_partial_dq(model.nv,model.nv); g_partial_dq.setZero();\n  computeGeneralizedGravityDerivatives(model,data,q,g_partial_dq);\n  \n  VectorXd g0 = computeGeneralizedGravity(model,data_fd,q);\n  BOOST_CHECK(data.g.isApprox(g0));\n\n  MatrixXd g_partial_dq_fd(model.nv,model.nv); g_partial_dq_fd.setZero();\n\n  VectorXd v_eps(Eigen::VectorXd::Zero(model.nv));\n  VectorXd q_plus(model.nq);\n  VectorXd g_plus(model.nv);\n  const double alpha = 1e-8;\n  for(int k = 0; k < model.nv; ++k)\n  {\n    v_eps[k] += alpha;\n    q_plus = integrate(model,q,v_eps);\n    g_plus = computeGeneralizedGravity(model,data_fd,q_plus);\n    \n    g_partial_dq_fd.col(k) = (g_plus - g0)/alpha;\n    v_eps[k] -= alpha;\n  }\n  \n  BOOST_CHECK(g_partial_dq.isApprox(g_partial_dq_fd,sqrt(alpha)));\n}\n\nBOOST_AUTO_TEST_CASE(test_generalized_gravity_derivatives_fext)\n{\n  using namespace Eigen;\n  using namespace pinocchio;\n\n  Model model;\n  buildModels::humanoidRandom(model);\n  \n  Data data(model), data_fd(model);\n  \n  model.lowerPositionLimit.head<3>().fill(-1.);\n  model.upperPositionLimit.head<3>().fill( 1.);\n  VectorXd q = randomConfiguration(model);\n\n  typedef PINOCCHIO_ALIGNED_STD_VECTOR(Force) ForceVector;\n  ForceVector fext((size_t)model.njoints);\n  for(ForceVector::iterator it = fext.begin(); it != fext.end(); ++it)\n    (*it).setRandom();\n  \n  // Check againt non-derivative algo\n  MatrixXd static_vec_partial_dq(model.nv,model.nv); static_vec_partial_dq.setZero();\n  computeStaticTorqueDerivatives(model,data,q,fext,static_vec_partial_dq);\n  \n  VectorXd tau0 = computeStaticTorque(model,data_fd,q,fext);\n  BOOST_CHECK(data.tau.isApprox(tau0));\n  \n  std::cout << \"data.tau: \" << data.tau.transpose() << std::endl;\n  std::cout << \"tau0: \" << tau0.transpose() << std::endl;\n\n  MatrixXd static_vec_partial_dq_fd(model.nv,model.nv);\n\n  VectorXd v_eps(Eigen::VectorXd::Zero(model.nv));\n  VectorXd q_plus(model.nq);\n  VectorXd tau_plus(model.nv);\n  const double alpha = 1e-8;\n  for(int k = 0; k < model.nv; ++k)\n  {\n    v_eps[k] += alpha;\n    q_plus = integrate(model,q,v_eps);\n    tau_plus = computeStaticTorque(model,data_fd,q_plus,fext);\n    \n    static_vec_partial_dq_fd.col(k) = (tau_plus - tau0)/alpha;\n    v_eps[k] = 0.;\n  }\n  \n  BOOST_CHECK(static_vec_partial_dq.isApprox(static_vec_partial_dq_fd,sqrt(alpha)));\n}\n\nBOOST_AUTO_TEST_CASE(test_rnea_derivatives)\n{\n  using namespace Eigen;\n  using namespace pinocchio;\n  \n  Model model;\n  buildModels::humanoidRandom(model);\n  \n  Data data(model), data_fd(model), data_ref(model);\n  \n  model.lowerPositionLimit.head<3>().fill(-1.);\n  model.upperPositionLimit.head<3>().fill(1.);\n  VectorXd q = randomConfiguration(model);\n  VectorXd v(VectorXd::Random(model.nv));\n  VectorXd a(VectorXd::Random(model.nv));\n  \n  /// Check againt computeGeneralizedGravityDerivatives\n  MatrixXd rnea_partial_dq(model.nv,model.nv); rnea_partial_dq.setZero();\n  MatrixXd rnea_partial_dv(model.nv,model.nv); rnea_partial_dv.setZero();\n  MatrixXd rnea_partial_da(model.nv,model.nv); rnea_partial_da.setZero();\n  computeRNEADerivatives(model,data,q,VectorXd::Zero(model.nv),VectorXd::Zero(model.nv),rnea_partial_dq,rnea_partial_dv,rnea_partial_da);\n  rnea(model,data_ref,q,VectorXd::Zero(model.nv),VectorXd::Zero(model.nv));\n  for(Model::JointIndex k = 1; k < (Model::JointIndex)model.njoints; ++k)\n  {\n    BOOST_CHECK(data.of[k].isApprox(data.oMi[k].act(data_ref.f[k])));\n  }\n  \n  MatrixXd g_partial_dq(model.nv,model.nv); g_partial_dq.setZero();\n  computeGeneralizedGravityDerivatives(model,data_ref,q,g_partial_dq);\n  \n  BOOST_CHECK(data.dFdq.isApprox(data_ref.dFdq));\n  BOOST_CHECK(rnea_partial_dq.isApprox(g_partial_dq));\n  BOOST_CHECK(data.tau.isApprox(data_ref.g));\n  \n  VectorXd tau0 = rnea(model,data_fd,q,VectorXd::Zero(model.nv),VectorXd::Zero(model.nv));\n  MatrixXd rnea_partial_dq_fd(model.nv,model.nv); rnea_partial_dq_fd.setZero();\n  \n  VectorXd v_eps(VectorXd::Zero(model.nv));\n  VectorXd q_plus(model.nq);\n  VectorXd tau_plus(model.nv);\n  const double alpha = 1e-8;\n  for(int k = 0; k < model.nv; ++k)\n  {\n    v_eps[k] += alpha;\n    q_plus = integrate(model,q,v_eps);\n    tau_plus = rnea(model,data_fd,q_plus,VectorXd::Zero(model.nv),VectorXd::Zero(model.nv));\n    \n    rnea_partial_dq_fd.col(k) = (tau_plus - tau0)/alpha;\n    v_eps[k] -= alpha;\n  }\n  BOOST_CHECK(rnea_partial_dq.isApprox(rnea_partial_dq_fd,sqrt(alpha)));\n\n  // Check with q and a non zero\n  tau0 = rnea(model,data_fd,q,0*v,a);\n  rnea_partial_dq_fd.setZero();\n\n  for(int k = 0; k < model.nv; ++k)\n  {\n    v_eps[k] += alpha;\n    q_plus = integrate(model,q,v_eps);\n    tau_plus = rnea(model,data_fd,q_plus,VectorXd::Zero(model.nv),a);\n\n    rnea_partial_dq_fd.col(k) = (tau_plus - tau0)/alpha;\n    v_eps[k] -= alpha;\n  }\n  \n  rnea_partial_dq.setZero();\n  computeRNEADerivatives(model,data,q,VectorXd::Zero(model.nv),a,rnea_partial_dq,rnea_partial_dv,rnea_partial_da);\n  forwardKinematics(model,data_ref,q,VectorXd::Zero(model.nv),a);\n  \n  for(Model::JointIndex k = 1; k < (Model::JointIndex)model.njoints; ++k)\n  {\n    BOOST_CHECK(data.a[k].isApprox(data_ref.a[k]));\n    BOOST_CHECK(data.v[k].isApprox(data_ref.v[k]));\n    BOOST_CHECK(data.oMi[k].isApprox(data_ref.oMi[k]));\n    BOOST_CHECK(data.oh[k].isApprox(Force::Zero()));\n  }\n  \n  BOOST_CHECK(data.tau.isApprox(tau0));\n  BOOST_CHECK(rnea_partial_dq.isApprox(rnea_partial_dq_fd,sqrt(alpha)));\n  \n  // Check with q and v non zero\n  const Motion gravity(model.gravity);\n  model.gravity.setZero();\n  tau0 = rnea(model,data_fd,q,v,VectorXd::Zero(model.nv));\n  rnea_partial_dq_fd.setZero();\n  \n  for(int k = 0; k < model.nv; ++k)\n  {\n    v_eps[k] += alpha;\n    q_plus = integrate(model,q,v_eps);\n    tau_plus = rnea(model,data_fd,q_plus,v,VectorXd::Zero(model.nv));\n    \n    rnea_partial_dq_fd.col(k) = (tau_plus - tau0)/alpha;\n    v_eps[k] -= alpha;\n  }\n  \n  VectorXd v_plus(v);\n  MatrixXd rnea_partial_dv_fd(model.nv,model.nv); rnea_partial_dv_fd.setZero();\n  \n  for(int k = 0; k < model.nv; ++k)\n  {\n    v_plus[k] += alpha;\n    tau_plus = rnea(model,data_fd,q,v_plus,VectorXd::Zero(model.nv));\n    \n    rnea_partial_dv_fd.col(k) = (tau_plus - tau0)/alpha;\n    v_plus[k] -= alpha;\n  }\n  \n  rnea_partial_dq.setZero();\n  rnea_partial_dv.setZero();\n  computeRNEADerivatives(model,data,q,v,VectorXd::Zero(model.nv),rnea_partial_dq,rnea_partial_dv,rnea_partial_da);\n  forwardKinematics(model,data_ref,q,v,VectorXd::Zero(model.nv));\n  \n  for(Model::JointIndex k = 1; k < (Model::JointIndex)model.njoints; ++k)\n  {\n    BOOST_CHECK(data.a[k].isApprox(data_ref.a[k]));\n    BOOST_CHECK(data.v[k].isApprox(data_ref.v[k]));\n    BOOST_CHECK(data.oMi[k].isApprox(data_ref.oMi[k]));\n  }\n  \n  BOOST_CHECK(data.tau.isApprox(tau0));\n  BOOST_CHECK(rnea_partial_dq.isApprox(rnea_partial_dq_fd,sqrt(alpha)));\n  BOOST_CHECK(rnea_partial_dv.isApprox(rnea_partial_dv_fd,sqrt(alpha)));\n  \n//    std::cout << \"rnea_partial_dv:\\n\" << rnea_partial_dv.block<10,10>(0,0) << std::endl;\n//    std::cout << \"rnea_partial_dv ref:\\n\" << rnea_partial_dv_fd.block<10,10>(0,0) << std::endl;\n//    std::cout << \"rnea_partial_dv:\\n\" << rnea_partial_dv.topRows<10>() << std::endl;\n//    std::cout << \"rnea_partial_dv ref:\\n\" << rnea_partial_dv_fd.topRows<10>() << std::endl;\n  // Check with q, v and a non zero\n  model.gravity = gravity;\n  v_plus = v;\n  tau0 = rnea(model,data_fd,q,v,a);\n  rnea_partial_dq_fd.setZero();\n  \n  for(int k = 0; k < model.nv; ++k)\n  {\n    v_eps[k] += alpha;\n    q_plus = integrate(model,q,v_eps);\n    tau_plus = rnea(model,data_fd,q_plus,v,a);\n    \n    rnea_partial_dq_fd.col(k) = (tau_plus - tau0)/alpha;\n    v_eps[k] -= alpha;\n  }\n  \n  rnea_partial_dv_fd.setZero();\n  for(int k = 0; k < model.nv; ++k)\n  {\n    v_plus[k] += alpha;\n    tau_plus = rnea(model,data_fd,q,v_plus,a);\n    \n    rnea_partial_dv_fd.col(k) = (tau_plus - tau0)/alpha;\n    v_plus[k] -= alpha;\n  }\n  \n  rnea_partial_dq.setZero();\n  rnea_partial_dv.setZero();\n  computeRNEADerivatives(model,data,q,v,a,rnea_partial_dq,rnea_partial_dv,rnea_partial_da);\n  forwardKinematics(model,data_ref,q,v,a);\n  \n  for(Model::JointIndex k = 1; k < (Model::JointIndex)model.njoints; ++k)\n  {\n    BOOST_CHECK(data.a[k].isApprox(data_ref.a[k]));\n    BOOST_CHECK(data.v[k].isApprox(data_ref.v[k]));\n    BOOST_CHECK(data.oMi[k].isApprox(data_ref.oMi[k]));\n  }\n  \n  computeJointJacobiansTimeVariation(model,data_ref,q,v);\n  BOOST_CHECK(data.dJ.isApprox(data_ref.dJ));\n  crba(model,data_ref,q);\n  \n  rnea_partial_da.triangularView<Eigen::StrictlyLower>()\n  = rnea_partial_da.transpose().triangularView<Eigen::StrictlyLower>();\n  data_ref.M.triangularView<Eigen::StrictlyLower>()\n  = data_ref.M.transpose().triangularView<Eigen::StrictlyLower>();\n  BOOST_CHECK(rnea_partial_da.isApprox(data_ref.M));\n\n  BOOST_CHECK(data.tau.isApprox(tau0));\n  BOOST_CHECK(rnea_partial_dq.isApprox(rnea_partial_dq_fd,sqrt(alpha)));\n  BOOST_CHECK(rnea_partial_dv.isApprox(rnea_partial_dv_fd,sqrt(alpha)));\n  \n  Data data2(model);\n  computeRNEADerivatives(model,data2,q,v,a);\n  data2.M.triangularView<Eigen::StrictlyLower>()\n  = data2.M.transpose().triangularView<Eigen::StrictlyLower>();\n\n  BOOST_CHECK(rnea_partial_dq.isApprox(data2.dtau_dq));\n  BOOST_CHECK(rnea_partial_dv.isApprox(data2.dtau_dv));\n  BOOST_CHECK(rnea_partial_da.isApprox(data2.M));\n  \n}\n\nBOOST_AUTO_TEST_CASE(test_rnea_derivatives_fext)\n{\n  using namespace Eigen;\n  using namespace pinocchio;\n  \n  Model model;\n  buildModels::humanoidRandom(model);\n  typedef Model::Force Force;\n  \n  Data data(model), data_fd(model), data_ref(model);\n  \n  model.lowerPositionLimit.head<3>().fill(-1.);\n  model.upperPositionLimit.head<3>().fill(1.);\n  VectorXd q = randomConfiguration(model);\n  VectorXd v(VectorXd::Random(model.nv));\n  VectorXd a(VectorXd::Random(model.nv));\n  \n  typedef PINOCCHIO_ALIGNED_STD_VECTOR(Force) ForceVector;\n  ForceVector fext((size_t)model.njoints);\n  for(ForceVector::iterator it = fext.begin(); it != fext.end(); ++it)\n    (*it).setRandom();\n  \n  /// Check againt computeGeneralizedGravityDerivatives\n  MatrixXd rnea_partial_dq(model.nv,model.nv); rnea_partial_dq.setZero();\n  MatrixXd rnea_partial_dv(model.nv,model.nv); rnea_partial_dv.setZero();\n  MatrixXd rnea_partial_da(model.nv,model.nv); rnea_partial_da.setZero();\n  \n  computeRNEADerivatives(model,data,q,v,a,fext,rnea_partial_dq,rnea_partial_dv,rnea_partial_da);\n  rnea(model,data_ref,q,v,a,fext);\n  \n  BOOST_CHECK(data.tau.isApprox(data_ref.tau));\n  \n  computeRNEADerivatives(model,data_ref,q,v,a);\n  BOOST_CHECK(rnea_partial_dv.isApprox(data_ref.dtau_dv));\n  BOOST_CHECK(rnea_partial_da.isApprox(data_ref.M));\n  \n  MatrixXd rnea_partial_dq_fd(model.nv,model.nv); rnea_partial_dq_fd.setZero();\n  MatrixXd rnea_partial_dv_fd(model.nv,model.nv); rnea_partial_dv_fd.setZero();\n  MatrixXd rnea_partial_da_fd(model.nv,model.nv); rnea_partial_da_fd.setZero();\n  \n  VectorXd v_eps(VectorXd::Zero(model.nv));\n  VectorXd q_plus(model.nq);\n  VectorXd tau_plus(model.nv);\n  const double eps = 1e-8;\n  \n  const VectorXd tau_ref = rnea(model,data_ref,q,v,a,fext);\n  for(int k = 0; k < model.nv; ++k)\n  {\n    v_eps[k] = eps;\n    q_plus = integrate(model,q,v_eps);\n    tau_plus = rnea(model,data_fd,q_plus,v,a,fext);\n    \n    rnea_partial_dq_fd.col(k) = (tau_plus - tau_ref) / eps;\n    \n    v_eps[k] = 0.;\n  }\n  BOOST_CHECK(rnea_partial_dq.isApprox(rnea_partial_dq_fd,sqrt(eps)));\n  \n  VectorXd v_plus(v);\n  for(int k = 0; k < model.nv; ++k)\n  {\n    v_plus[k] += eps;\n    \n    tau_plus = rnea(model,data_fd,q,v_plus,a,fext);\n    \n    rnea_partial_dv_fd.col(k) = (tau_plus - tau_ref) / eps;\n    \n    v_plus[k] -= eps;\n  }\n  BOOST_CHECK(rnea_partial_dv.isApprox(rnea_partial_dv_fd,sqrt(eps)));\n  \n  VectorXd a_plus(a);\n  for(int k = 0; k < model.nv; ++k)\n  {\n    a_plus[k] += eps;\n    \n    tau_plus = rnea(model,data_fd,q,v,a_plus,fext);\n    \n    rnea_partial_da_fd.col(k) = (tau_plus - tau_ref) / eps;\n    \n    a_plus[k] -= eps;\n  }\n  \n  rnea_partial_da.triangularView<Eigen::Lower>() = rnea_partial_da.transpose().triangularView<Eigen::Lower>();\n  BOOST_CHECK(rnea_partial_da.isApprox(rnea_partial_da_fd,sqrt(eps)));\n\n  // test the shortcut\n  Data data_shortcut(model);\n  computeRNEADerivatives(model,data_shortcut,q,v,a,fext);\n  BOOST_CHECK(data_shortcut.dtau_dq.isApprox(rnea_partial_dq));\n  BOOST_CHECK(data_shortcut.dtau_dv.isApprox(rnea_partial_dv));\n  data_shortcut.M.triangularView<Eigen::Lower>() = data_shortcut.M.transpose().triangularView<Eigen::Lower>();\n  BOOST_CHECK(data_shortcut.M.isApprox(rnea_partial_da));\n}\n\nBOOST_AUTO_TEST_CASE(test_rnea_derivatives_vs_kinematics_derivatives)\n{\n  using namespace Eigen;\n  using namespace pinocchio;\n  \n  Model model;\n  buildModels::humanoidRandom(model);\n\n  Data data(model), data_ref(model);\n  \n  model.lowerPositionLimit.head<3>().fill(-1.);\n  model.upperPositionLimit.head<3>().fill(1.);\n  VectorXd q = randomConfiguration(model);\n  VectorXd v(VectorXd::Random(model.nv));\n  VectorXd a(VectorXd::Random(model.nv));\n  \n  /// Check againt computeGeneralizedGravityDerivatives\n  MatrixXd rnea_partial_dq(model.nv,model.nv); rnea_partial_dq.setZero();\n  MatrixXd rnea_partial_dv(model.nv,model.nv); rnea_partial_dv.setZero();\n  MatrixXd rnea_partial_da(model.nv,model.nv); rnea_partial_da.setZero();\n  \n  computeRNEADerivatives(model,data,q,v,a,rnea_partial_dq,rnea_partial_dv,rnea_partial_da);\n  computeForwardKinematicsDerivatives(model,data_ref,q,v,a);\n  \n  BOOST_CHECK(data.J.isApprox(data_ref.J));\n  BOOST_CHECK(data.dJ.isApprox(data_ref.dJ));\n  \n  for(size_t k = 1; k < (size_t)model.njoints; ++k)\n  {\n    BOOST_CHECK(data.oMi[k].isApprox(data_ref.oMi[k]));\n    BOOST_CHECK(data.ov[k].isApprox(data_ref.ov[k]));\n    BOOST_CHECK(data.oa[k].isApprox(data_ref.oa[k]));\n  }\n}\n\nBOOST_AUTO_TEST_CASE(test_multiple_calls)\n{\n  using namespace Eigen;\n  using namespace pinocchio;\n  \n  Model model;\n  buildModels::humanoidRandom(model);\n  \n  Data data1(model), data2(model);\n  \n  model.lowerPositionLimit.head<3>().fill(-1.);\n  model.upperPositionLimit.head<3>().fill(1.);\n  VectorXd q = randomConfiguration(model);\n  VectorXd v(VectorXd::Random(model.nv));\n  VectorXd a(VectorXd::Random(model.nv));\n  \n  computeRNEADerivatives(model,data1,q,v,a);\n  data2 = data1;\n  \n  for(int k = 0; k < 20; ++k)\n  {\n    computeRNEADerivatives(model,data1,q,v,a);\n  }\n  \n  BOOST_CHECK(data1.J.isApprox(data2.J));\n  BOOST_CHECK(data1.dJ.isApprox(data2.dJ));\n  BOOST_CHECK(data1.dVdq.isApprox(data2.dVdq));\n  BOOST_CHECK(data1.dAdq.isApprox(data2.dAdq));\n  BOOST_CHECK(data1.dAdv.isApprox(data2.dAdv));\n  \n  BOOST_CHECK(data1.dFdq.isApprox(data2.dFdq));\n  BOOST_CHECK(data1.dFdv.isApprox(data2.dFdv));\n  BOOST_CHECK(data1.dFda.isApprox(data2.dFda));\n  \n  BOOST_CHECK(data1.dtau_dq.isApprox(data2.dtau_dq));\n  BOOST_CHECK(data1.dtau_dv.isApprox(data2.dtau_dv));\n  BOOST_CHECK(data1.M.isApprox(data2.M));\n}\n\nBOOST_AUTO_TEST_CASE(test_get_coriolis)\n{\n  using namespace Eigen;\n  using namespace pinocchio;\n  \n  Model model;\n  buildModels::humanoidRandom(model);\n  \n  model.lowerPositionLimit.head<3>().fill(-1.);\n  model.upperPositionLimit.head<3>().fill( 1.);\n  \n  Data data_ref(model);\n  Data data(model);\n  \n  VectorXd q = randomConfiguration(model);\n  VectorXd v = VectorXd::Random(model.nv);\n  VectorXd tau = VectorXd::Random(model.nv);\n  \n  computeCoriolisMatrix(model,data_ref,q,v);\n  \n  computeRNEADerivatives(model,data,q,v,tau);\n  getCoriolisMatrix(model,data);\n  \n  BOOST_CHECK(data.J.isApprox(data_ref.J));\n  BOOST_CHECK(data.dJ.isApprox(data_ref.dJ));\n  for(JointIndex k = 1; k < model.joints.size(); ++k)\n  {\n    BOOST_CHECK(data.B[k].isApprox(data_ref.B[k]));\n    BOOST_CHECK(data.oYcrb[k].isApprox(data_ref.oYcrb[k]));\n  }\n  \n  BOOST_CHECK(data.C.isApprox(data_ref.C));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "0f1c2a8ea8c0a29014ad1c876028d728a6c96211", "size": 16746, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittest/rnea-derivatives.cpp", "max_stars_repo_name": "duburcqa/pinocchio", "max_stars_repo_head_hexsha": "c2ad2c60eecc04555e265a8f80a9765d3b84f5f1", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "unittest/rnea-derivatives.cpp", "max_issues_repo_name": "duburcqa/pinocchio", "max_issues_repo_head_hexsha": "c2ad2c60eecc04555e265a8f80a9765d3b84f5f1", "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": "unittest/rnea-derivatives.cpp", "max_forks_repo_name": "duburcqa/pinocchio", "max_forks_repo_head_hexsha": "c2ad2c60eecc04555e265a8f80a9765d3b84f5f1", "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": 32.8998035363, "max_line_length": 137, "alphanum_fraction": 0.7160515944, "num_tokens": 4967, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624890918021, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.46090143288585916}}
{"text": "#include <ros/ros.h>\n#include <std_msgs/Int32.h>\n#include <std_srvs/Empty.h>\n#include <geometry_msgs/PointStamped.h>\n#include <geometry_msgs/Vector3.h>\n#include <geometry_msgs/PoseStamped.h>\n#include <geometry_msgs/Twist.h>\n#include <visualization_msgs/MarkerArray.h>\n#include <nav_msgs/OccupancyGrid.h>\n#include <ras_follower/moveTo.h>\n#include <ras_follower/Rotate.h>\n#include <nav_msgs/Path.h>\n#include <tf/tf.h>\n#include <tf/transform_datatypes.h>\n#include <math.h>\n#include <boost/math/special_functions/round.hpp>\n\n#define ZERO 1E-1\n/*\n * States: 0 idle\n *         1 Following\n *         -1 Error following\n *         2 Externally aborted\n *         8 rotating\n */\nclass PathFollower\n{\npublic:\n  ros::NodeHandle nH;\n  ros::Subscriber point_subscriber;\n  ros::Subscriber grid_subscriber;\n  ros::Publisher twist_publisher;\n  ros::Publisher marker_publisher;\n  ros::Publisher state_publisher;\n  ros::ServiceServer service;\n  ros::ServiceServer abort_follow_service;\n  ros::ServiceServer rotate_Service;\n  ros::ServiceServer relative_rotate_Service;\n  std_msgs::Int32 mStateMsg;\n  nav_msgs::OccupancyGrid gridMap;\n  tf::Vector3 mTarget;\n  geometry_msgs::Pose mTargetPose;\n\n  float windowSize;\n  double a;\n  double b;\n  int l;\n  float alpha; //rad\n  int T;\n  int s_max;\n  int targetSector;\n  int k_n;\n  int k_f;\n  float V_max;\n  float h_m;\n  float P_angle;\n  float robotWidth;\n  float mLengthFromCenterToFront;\n  bool mErrorFollowing;\n  int mMaxSearchWidth;\n  double mTolerance;\n  bool mShouldKillMotorsOnTarget;\n  double mTargetAngle;\n\n  int mState;\n  const static int RUNNING = 1;\n  const static int ROTATING_TO_POSE = 2;\n  const static int DONE_ROTATING = 3;\n  const static int ABORTED = 4;\n  const static int IDLE = 5;\n  const static int DONE = 6;\n\n  std::vector<double> smothHist;\n\n  tf::Stamped<tf::Pose> robotPoseInWorld;\n  tf::Vector3 robotPointInGrid;\n  tf::Transformer transFormer;\n\n  PathFollower() :\n                  nH(\"~\"),\n                  targetSector(18),\n                  k_n(18),\n                  k_f(18),\n                  mErrorFollowing(false)\n    {\n    windowSize = 2;\n    a = 2;\n    b = 2;\n    alpha =2*M_PI/72;\n    l = 5;\n    T = 100;\n    s_max = 15;\n    h_m = T*0.9;\n    V_max = 0.2;\n    P_angle = 1;\n    robotWidth = 0.4;\n    mLengthFromCenterToFront = 0.18;\n\n    smothHist.resize((int) 2*M_PI/alpha,0);\n\n    mStateMsg.data = 0;\n    mState = IDLE;\n\n    nH.getParam(\"window_size\", windowSize);\n    nH.getParam(\"a\", a);\n    nH.getParam(\"b\", b);\n    nH.getParam(\"alpha\", alpha);\n    nH.getParam(\"l\", l);\n    nH.getParam(\"T\", T);\n    nH.getParam(\"s_max\", s_max);\n    nH.getParam(\"V_max\", V_max);\n    nH.getParam(\"h_m\", h_m);\n    nH.getParam(\"P_angle\", P_angle);\n    nH.getParam(\"robot_width\", robotWidth);\n    nH.getParam(\"distance_between_front_and_center\", mLengthFromCenterToFront);\n    nH.getParam(\"max_search_width\", mMaxSearchWidth);\n\n    service = nH.advertiseService(\"/robot/goTo\", &PathFollower::servicCallBack, this);\n    abort_follow_service = nH.advertiseService(\"/robot/abort_follow_service\", &PathFollower::abortServicCallBack, this);\n    rotate_Service = nH.advertiseService(\"/robot/rotate_to_target\", &PathFollower::rotateToTarget, this);\n    relative_rotate_Service = nH.advertiseService(\"/robot/relative_rotate_to_target\", &PathFollower::relRotateToTarget, this);\n    point_subscriber = nH.subscribe(\"/localization/pose\",1, &PathFollower::PoseCallback, this);\n    grid_subscriber = nH.subscribe(\"/mapping/grid\",1, &PathFollower::gridCallback, this);\n    twist_publisher = nH.advertise<geometry_msgs::Twist>(\"/cmd_vel\", 1);\n    marker_publisher = nH.advertise<visualization_msgs::MarkerArray>(\"markers\", 1);\n    state_publisher = nH.advertise<std_msgs::Int32>(\"state\",1);\n\n    tf::Vector3 orig(0,0,0);\n    this->robotPoseInWorld.setOrigin(orig);\n  }\n  \n  bool abortServicCallBack(std_srvs::Empty::Request &req, std_srvs::Empty::Response &res) {\n    shutDownMotors();\n    mState = IDLE;\n    return true;\n  }\n  \n  bool relRotateToTarget(ras_follower::Rotate::Request &req, ras_follower::Rotate::Response &rsp){\n    tf::Quaternion angleQ = tf::createQuaternionFromYaw(req.target.angular.z + tf::getYaw(robotPoseInWorld.getRotation()));\n    geometry_msgs::Pose p;\n    tf::quaternionTFToMsg(angleQ, p.orientation);\n    mTargetPose = p;\n    mState = ROTATING_TO_POSE;\n    mErrorFollowing = false;\n    return true;\n\n  }\n\n  bool rotateToTarget(ras_follower::Rotate::Request &req, ras_follower::Rotate::Response &rsp){\n      double targetAngleInWorld = std::atan2(req.target.linear.y - robotPoseInWorld.getOrigin().getY(),\n                                             req.target.linear.x - robotPoseInWorld.getOrigin().getX());\n      tf::Quaternion angleQ = tf::createQuaternionFromYaw(targetAngleInWorld);\n      geometry_msgs::Pose p;\n      tf::quaternionTFToMsg(angleQ, p.orientation);\n      mTargetPose = p;\n      mState = ROTATING_TO_POSE;\n      mErrorFollowing = false;\n      return true;\n  }\n\n  void gridCallback(const nav_msgs::OccupancyGridConstPtr &grid){\n    //Assume grid is in world.\n    gridMap = *grid;\n  }\n\n  void PoseCallback(const geometry_msgs::PoseStampedConstPtr &pose) {\n      tf::poseStampedMsgToTF(*pose, this->robotPoseInWorld);\n  }\n\n  bool servicCallBack(ras_follower::moveTo::Request &req,\n                      ras_follower::moveTo::Response &res) {\n    mErrorFollowing = false;\n    mTarget = tf::Vector3(req.goal.pose.position.x, req.goal.pose.position.y, 0);\n    mTargetPose = req.goal.pose;\n    mTolerance = req.tolerance;\n    mShouldKillMotorsOnTarget = req.turnOffMotors.data;\n    mState = RUNNING;\n    return true;\n  }\n\n  void mainLoop(){\n    ros::Rate tRate(10);\n    mState = IDLE;\n    while(nH.ok()){\n      float velocity;\n      float angle;\n      tf::Quaternion tfQ;\n      tRate.sleep();\n      ros::spinOnce();\n      switch (mState) {\n      case IDLE:\n        mStateMsg.data = 0;\n        state_publisher.publish(mStateMsg);\n        break;\n      case RUNNING:\n        mStateMsg.data = 1;\n        state_publisher.publish(mStateMsg);\n        ROS_INFO(\"Calculating Vel and angle...\");\n        robotPointInGrid = tf::Vector3(gridMap.info.resolution*gridMap.info.width/2,gridMap.info.resolution*gridMap.info.height/2, 0 );\n        this->calculateVelocity(mTarget, velocity, angle);\n        broadcastSections();\n        ROS_INFO(\"Tol: %f\", mTolerance);\n        if(isRobotOnTarget(mTarget, mTolerance)) {\n          //Sucess!\n          if(mShouldKillMotorsOnTarget){\n            mState = ROTATING_TO_POSE;\n            continue;\n          } else {\n            mState = IDLE;\n            continue;\n          }\n        } else if (mErrorFollowing) {\n          //Fail...\n          shutDownMotors();\n          mStateMsg.data =  -1;\n          state_publisher.publish(mStateMsg);\n          mState = IDLE;\n          continue;\n        }\n        ROS_INFO(\"Sending Vel: %f, and angle: %f\", velocity, angle);\n        this->sendForceToMotorController(velocity,angle);\n        break;\n      case ROTATING_TO_POSE:\n        mStateMsg.data = 8;\n        state_publisher.publish(mStateMsg);\n        tf::quaternionMsgToTF(mTargetPose.orientation, tfQ);\n        mTargetAngle = tf::getYaw(tfQ);\n        angle =mTargetAngle- tf::getYaw(robotPoseInWorld.getRotation());\n        if(std::abs(angle) < M_PI/50){\n          shutDownMotors();\n          mState = IDLE;\n          continue;\n        }\n        velocity = 0;\n        ROS_INFO_STREAM(\"target: \" << mTargetAngle << \", angle: \" << tf::getYaw(robotPoseInWorld.getRotation()) << \", diff: \" << angle);\n        ROS_INFO(\"Sending Vel: %f, and angle: %f\", velocity, angle);\n        this->sendForceToMotorController(velocity,angle);\n        break;\n      case ABORTED:\n        mStateMsg.data = 2;\n        state_publisher.publish(mStateMsg);\n        mState = IDLE;\n        break;\n      default:\n        break;\n      }\n    }\n    shutDownMotors();\n  }\n\n  bool isRobotOnTarget(tf::Vector3& targetVector, float tolerance){\n    bool answer = (this->robotPoseInWorld.getOrigin() - targetVector).length() < tolerance;\n    tf::Transform robotCenterFromWorldTransform;\n    robotCenterFromWorldTransform.setOrigin(robotPoseInWorld.getOrigin());\n    robotCenterFromWorldTransform.setRotation(robotPoseInWorld.getRotation());\n    tf::Vector3 tipPose = robotCenterFromWorldTransform(tf::Vector3(mLengthFromCenterToFront,0,0));\n    answer |=   (tipPose - targetVector).length() < tolerance;\n    return answer;\n  }\n\n  void broadcastSections() {\n    int maxK = (int) 2*M_PI/alpha;\n    visualization_msgs::MarkerArray allSections;\n    allSections.markers.resize(maxK);\n    for (int k = 0; k < maxK; ++k) {\n      visualization_msgs::Marker aMarker;\n      tf::Stamped<tf::Pose> markerPose;\n      markerPose.setOrigin(robotPointInGrid);\n      markerPose.setRotation(tf::createQuaternionFromYaw(k*alpha));\n      geometry_msgs::PoseStamped aPose;\n      tf::poseStampedTFToMsg(markerPose, aPose);\n      aMarker.pose = aPose.pose;\n      aMarker.type = aMarker.ARROW;\n      aMarker.color.a = 0.6;\n      aMarker.scale.x = 0.5;\n      aMarker.scale.y = 0.01;\n      aMarker.scale.z = 0.01;\n      aMarker.header.frame_id = \"/live_map\";\n      aMarker.header.stamp = ros::Time::now();\n      aMarker.id = k;\n      aMarker.ns = \"sectors\";\n      if(smothHist[k] > T){\n        aMarker.color.r = 1;\n      } else {\n        aMarker.color.g = 1;\n      }\n      allSections.markers[k] = aMarker;\n    }\n    marker_publisher.publish(allSections);\n  }\n\n  void getSmoothPolarHistogram(std::vector<double>& smothHist, tf::Vector3& targetVector)\n  {\n    int cellMinX = int((robotPointInGrid.getX() - windowSize/2)/gridMap.info.resolution);\n    int cellMinY = int((robotPointInGrid.getY() - windowSize/2)/gridMap.info.resolution);\n    int cellMaxX = int((robotPointInGrid.getX() + windowSize/2)/gridMap.info.resolution);\n    int cellMaxY = int((robotPointInGrid.getY() + windowSize/2)/gridMap.info.resolution);\n    if(cellMinX<0){\n      cellMinX = 0;\n    }\n    if(cellMinY<0){\n      cellMinY = 0;\n    }\n    if(gridMap.info.width <= cellMaxX){\n      cellMaxX = gridMap.info.width-1;\n    }\n    if(gridMap.info.height <= cellMaxY){\n      cellMaxY = gridMap.info.height-1;\n    }\n    for (int Ycell = cellMinY ; Ycell <= cellMaxY; ++Ycell) {\n      for (int Xcell = cellMinX; Xcell <= cellMaxX; ++Xcell) {\n        int rowNr = Ycell*gridMap.info.width + Xcell;\n        float x = Xcell*gridMap.info.resolution;\n        float y = Ycell*gridMap.info.resolution;\n        tf::Vector3 objectVec(x,y,0);\n        objectVec = objectVec - robotPointInGrid; //Moves the vector to be robot -> object.\n        //See report @ <url:http://www-personal.umich.edu/~johannb/Papers/paper16.pdf/>\n        float beta = std::atan2((y - robotPointInGrid.getY()),(x - robotPointInGrid.getX()));\n        float distance = sqrt(std::pow(y - robotPointInGrid.getY(),2) + std::pow(x - robotPointInGrid.getX(), 2));\n        float extraAngle = std::atan2(robotWidth/2, distance);\n        float m = std::pow(gridMap.data[rowNr], 2)*(a-b*distance);\n        for (int sector = (int)( (beta-extraAngle)/alpha); sector <= (int)((beta+extraAngle)/alpha); sector++) {\n          if(objectVec.dot(targetVector)/targetVector.length() < targetVector.length())\n            smothHist[mod(sector,smothHist.size())] += m;\n        }\n      }\n    }\n  \n\n  }\n\n  void getKnKfWithTargetInside(int targetSector, std::vector<double> &smothHist, int &k_f, int &k_n)\n  {\n    k_n = targetSector;\n    k_f = targetSector;\n  }\n\n  void getKnKfWithTargetOutside(std::vector<double> &smothHist, int targetSector,int& k_n, int& k_f)\n  {\n    int i = 1;\n    bool haveNotFoundGoodVallyStart = true;\n    bool goingRight = true;\n\n    while(haveNotFoundGoodVallyStart) {\n      int upIndex = targetSector + i;\n      int downIndex = targetSector - i;\n      if(smothHist[mod(upIndex,smothHist.size())] < T){\n        haveNotFoundGoodVallyStart = false;\n        k_n = upIndex;\n        goingRight = false;\n      } else if(smothHist[mod(downIndex,smothHist.size())] < T){\n        haveNotFoundGoodVallyStart = false;\n        k_n = downIndex;\n        goingRight = true;\n      }\n      if(i > mMaxSearchWidth){ //We have searched the hole space and can not move... :(\n        mErrorFollowing = true;\n        return;\n      }\n      i++;\n    }\n    int direction;\n    if(goingRight){\n      direction = -1;\n    } else {\n      direction = 1;\n    }\n\n    bool haveNotFoundEnd = true;\n    i = 0;\n    while(haveNotFoundEnd) {\n      int index = k_n + i;\n      if(smothHist[mod(index,smothHist.size())] > T){\n        haveNotFoundEnd = false;\n        k_f = index;\n      }\n      i += direction;\n    }\n\n    if(abs(k_f-k_n) > s_max){\n      if(goingRight){\n        k_f = k_n - s_max;\n      } else {\n        k_f = k_n + s_max;\n      }\n    }\n    return;\n  }\n\n  void calculateVelocity(tf::Vector3 &target, float &velocity, float &angle) {\n    //Look for okey vally:\n    tf::Transform transform;\n    transform.setOrigin(robotPoseInWorld.getOrigin());\n    transform.setRotation(robotPoseInWorld.getRotation());\n    transform = transform.inverse();\n    tf::Vector3 targetInRobotCenter = transform(target);\n    targetSector = int(atan2(targetInRobotCenter.getY(), targetInRobotCenter.getX())/alpha);\n    if(std::isnan(targetSector)){\n      return;\n    }\n    //Create circle histogram\n    std::fill(smothHist.begin(), smothHist.end(), 0);\n    getSmoothPolarHistogram(smothHist, targetInRobotCenter);\n\n    bool targetIsInSection = smothHist[mod(targetSector,smothHist.size())] < T;\n    //Check if target is in good vally, if so look for edges.\n    if(targetIsInSection) {\n      getKnKfWithTargetInside(targetSector, smothHist, k_f, k_n);\n    } else {\n      getKnKfWithTargetOutside(smothHist, targetSector,k_n, k_f);\n      if(mErrorFollowing)\n        return;\n    }\n    //We have sektin k_n -> k_f\n    //Time to calculate direction.\n    int theata_sector = int((k_n + k_f)/2);\n\n     //Calculate speed\n    float h_prim = smothHist[mod(theata_sector,smothHist.size())];\n    float h_primprim = std::min(h_prim, h_m);\n    float V_prim = V_max*(1-h_primprim/h_m);\n    //Return force\n    velocity = V_prim;\n    angle = theata_sector*alpha;\n  }\n\n  void sendForceToMotorController(float velocity, float angle) {\n    geometry_msgs::Twist controllTwist;\n    double angleDiff = mod2(angle, 2*M_PI);\n    if(abs(angleDiff)> M_PI){\n      if(angleDiff< 0){\n        angleDiff += 2*M_PI;\n      } else {\n        angleDiff -= 2*M_PI;\n      }\n    }\n    controllTwist.linear.x = velocity*std::cos(angleDiff);\n    controllTwist.angular.z =P_angle*(angleDiff);\n    controllTwist.angular.z = std::min(std::max(controllTwist.angular.z,-2.0),2.0);\n\n    if(smothHist[0] >  T || controllTwist.linear.x < 0) {\n\t\tcontrollTwist.linear.x = 0;\n    \tif(controllTwist.angular.z > 0)\n            controllTwist.angular.z = std::max(controllTwist.angular.z, 0.5);\n    \telse if(controllTwist.angular.z < 0)\n            controllTwist.angular.z = std::min(controllTwist.angular.z, -0.5);\n        mStateMsg.data = 8;\n        state_publisher.publish(mStateMsg);\n    } else {\n    \tmStateMsg.data = 1;\n        state_publisher.publish(mStateMsg);\n    }\n    twist_publisher.publish(controllTwist);\n  }\n  void shutDownMotors() {\n    geometry_msgs::Twist controllTwist;\n    controllTwist.linear.x = 0;\n    controllTwist.angular.z = 0;\n    twist_publisher.publish(controllTwist);\n  }\n\n  int mod(int a, int b)\n  { return (a%b+b)%b; }\n\n  float mod2(float a, float b)\n  { return fmod((fmod(a,b)+b),b); }\n\n};\n\nint main(int argc, char **argv)\n{\n  // Set up ROS.\n  ros::init(argc, argv, \"path_follower\");\n  PathFollower pF;\n  pF.mainLoop();\n}\n", "meta": {"hexsha": "0c251fc1a8c9d50e6df5a0b1a5cb5a014c30e7b6", "size": 15501, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "data/RAS-2016/ras_follower/src/path_follower.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/RAS-2016/ras_follower/src/path_follower.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/RAS-2016/ras_follower/src/path_follower.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": 32.4968553459, "max_line_length": 136, "alphanum_fraction": 0.6463453971, "num_tokens": 4262, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.782662489091802, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4609014328858591}}
{"text": "#include \"LinearRegression_binding.hpp\"\n\n#include <armadillo>\n#include <libKriging/LinearRegression.hpp>\n#include <random>\n\n#include <pybind11/numpy.h>\n#include <pybind11/pybind11.h>\n#include <armadillo>\n\n#include <carma/carma.h>\n\nPyLinearRegression::PyLinearRegression() : m_internal{new LinearRegression{}} {}\n\nPyLinearRegression::~PyLinearRegression() {}\n\nvoid PyLinearRegression::fit(const py::array_t<double>& y, const py::array_t<double>& X) {\n  arma::mat mat_y = carma::arr_to_col<double>(y, true);\n  arma::mat mat_X = carma::arr_to_mat<double>(X, true);\n  m_internal->fit(mat_y, mat_X);\n}\n\nstd::tuple<py::array_t<double>, py::array_t<double>> PyLinearRegression::predict(const py::array_t<double>& X) {\n  arma::mat mat_X = carma::arr_to_mat<double>(X, true);\n  auto [y_predict, y_stderr] = m_internal->predict(mat_X);\n  return std::make_tuple(carma::col_to_arr(y_predict, true), carma::col_to_arr(y_stderr, true));\n}\n", "meta": {"hexsha": "a160294d9ab9ec8911dcecaa4aa40ece5ec324b7", "size": 925, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bindings/Python/src/LinearRegression_binding.cpp", "max_stars_repo_name": "yannrichet/libKriging", "max_stars_repo_head_hexsha": "25475d1de02d518401183e93f6a0fa5c12b3c96b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bindings/Python/src/LinearRegression_binding.cpp", "max_issues_repo_name": "yannrichet/libKriging", "max_issues_repo_head_hexsha": "25475d1de02d518401183e93f6a0fa5c12b3c96b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bindings/Python/src/LinearRegression_binding.cpp", "max_forks_repo_name": "yannrichet/libKriging", "max_forks_repo_head_hexsha": "25475d1de02d518401183e93f6a0fa5c12b3c96b", "max_forks_repo_licenses": ["Apache-2.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.0357142857, "max_line_length": 112, "alphanum_fraction": 0.7394594595, "num_tokens": 259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.782662489091802, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4609014328858591}}
{"text": "/*\r\n(c) 2012 Fengtao Fan\r\n*/\r\n#include \"AnnotationComputation.h\"\r\n\r\n\r\n#include \"Annotated_polyhedron_3.h\"\r\n#include \"Polyhedron_annotator_3.h\"\r\n\r\n#include <CGAL/Simple_cartesian.h>\r\n#include <CGAL/IO/Polyhedron_iostream.h>\r\n\r\n#include<CGAL/Polyhedron_incremental_builder_3.h>\r\n\r\n#include <boost/filesystem.hpp>\r\n\r\n#include <fstream>\r\n\r\n#include <boost/progress.hpp>\r\n\r\n#include \"SimpleMesh.h\"\r\n\r\n/********************************/\r\ntypedef CGAL::Simple_cartesian<float> Kernel;\r\ntypedef CGAL::Annotated_polyhedron_3<Kernel> Polyhedron;\r\ntypedef Polyhedron::HalfedgeDS HalfedgeDS;\r\n/*Modifier*/\r\n// A modifier creating a triangle with the incremental builder.\r\ntemplate<class HDS>\r\nclass polyhedron_builder : public CGAL::Modifier_base<HDS> {\r\npublic:\r\n    std::vector<float> &coords;\r\n    std::vector<int> &tris;\r\n\r\n    polyhedron_builder(std::vector<float> &_coords, std::vector<int> &_tris) : coords(_coords), tris(_tris) {}\r\n\r\n    void operator()(HDS &hds) {\r\n        typedef typename HDS::Vertex Vertex;\r\n        typedef typename Vertex::Point Point;\r\n\r\n        // create a cgal incremental builder\r\n        CGAL::Polyhedron_incremental_builder_3<HDS> B(hds, true);\r\n        B.begin_surface(coords.size() / 3, tris.size() / 3); //100\r\n\r\n        // add the polyhedron vertices\r\n        for (int i = 0; i < (int) coords.size(); i += 3) {\r\n            B.add_vertex(Point(coords[i + 0], coords[i + 1], coords[i + 2]));\r\n        }\r\n\r\n        // add the polyhedron triangles\r\n        for (int i = 0; i < (int) tris.size(); i += 3) {\r\n            B.begin_facet();\r\n            B.add_vertex_to_facet(tris[i + 0]);\r\n            B.add_vertex_to_facet(tris[i + 1]);\r\n            B.add_vertex_to_facet(tris[i + 2]);\r\n            B.end_facet();\r\n        }\r\n\r\n        // finish up the surface\r\n        B.end_surface();\r\n    }\r\n};\r\n\r\n/********************************/\r\nint ComputeAnnotation(_SimpleMesh &inMesh, std::vector<std::vector<char> > &vecEdgeAnno, std::vector<int> &tris) {\r\n    std::vector<float> coords;\r\n    //std::vector<int>\ttris;\r\n    //\r\n    for (unsigned int i = 0; i < inMesh.vecVertex.size(); i++) {\r\n        coords.push_back(inMesh.vecVertex[i].x);\r\n        coords.push_back(inMesh.vecVertex[i].y);\r\n        coords.push_back(inMesh.vecVertex[i].z);\r\n    }\r\n    //\r\n    //std::cout << coords.size() << std::endl;\r\n    //\r\n    //for (unsigned int i = 0; i < orientTri.size(); i++)\r\n    //{\r\n    //\ttris.push_back(orientTri[i][0]);\r\n    //\ttris.push_back(orientTri[i][1]);\r\n    //\ttris.push_back(orientTri[i][2]);\r\n    //}\r\n    //std::cout << tris.size() << std::endl;\r\n    /*******************************************/\r\n    using namespace std;\r\n    using namespace CGAL;\r\n    using namespace boost;\r\n    //using namespace filesystem;\r\n\r\n    typedef Polyhedron::Vertex_handle Vertex_handle;\r\n    typedef Polyhedron::Edge_iterator Edge_iterator;\r\n\r\n//\tstring input_filename( \"eight.off\" );\r\n//\tifstream input( input_filename.c_str() );\r\n//\tif ( !input.is_open() )\r\n//\t{\r\n//\t\tcerr << \"Cannot open \" << input_filename << \" for reading\" << endl;\r\n//\t\treturn EXIT_FAILURE;\r\n//\t}\r\n    Polyhedron polyhedron;\r\n    //input >> polyhedron;\r\n    //input.close();\r\n    polyhedron_builder<HalfedgeDS> builder(coords, tris);\r\n    polyhedron.delegate(builder);\r\n\r\n\r\n\r\n    //cout << polyhedron.size_of_vertices() << \" vertices\" << endl;\r\n    //cout << polyhedron.size_of_facets() << \" facets\" << endl;\r\n\r\n    //CGAL_assertion( polyhedron.is_triangle( polyhedron.halfedges_begin()));\r\n\r\n    std::cout << \"Time for computing edge annotation : \" << std::endl;\r\n    {\r\n        boost::progress_timer t;\r\n        annotate_edges(polyhedron);\r\n    }\r\n\r\n    size_t index(0);\r\n    Polyhedron::Vertex_iterator it_v(polyhedron.vertices_begin());\r\n    for (; it_v != polyhedron.vertices_end(); ++it_v)\r\n        it_v->index = index++;\r\n\r\n    /////////////\r\n    //string output_filename( \"model_annotations.txt\" );\r\n    //ofstream output( output_filename );\r\n    //if ( !output.is_open() )\r\n    //{\r\n    //\tcerr << \"Cannot open \" << output_filename << \" for writing\" << endl;\r\n    //\treturn EXIT_FAILURE;\r\n    //}\r\n    Edge_iterator it_e(polyhedron.edges_begin());\r\n    //output << it_e->annotation.size() << endl;\r\n    //\r\n    vecEdgeAnno.resize(inMesh.vecEdge.size());\r\n    std::vector<char> tempAnnotation(it_e->annotation.size());\r\n    //\r\n    for (; it_e != polyhedron.edges_end(); ++it_e) {\r\n        Vertex_handle h_a(it_e->vertex());\r\n        Vertex_handle h_b(it_e->opposite()->vertex());\r\n\r\n        //output << h_a->index << ' ' << h_b->index << ' ' <<\r\n        //\tit_e->annotation << endl;\r\n        for (boost::dynamic_bitset<>::size_type i = 0; i < it_e->annotation.size(); i++) {\r\n            tempAnnotation[i] = it_e->annotation[i];\r\n        }\r\n        //\r\n        int edge_index = -1;\r\n        for (int i = 0; i < inMesh.vecVertex[h_a->index].adjEdges.size(); i++) {\r\n            int loc_edge_index = inMesh.vecVertex[h_a->index].adjEdges[i];\r\n            if (inMesh.vecEdge[loc_edge_index].v0 == h_b->index ||\r\n                inMesh.vecEdge[loc_edge_index].v1 == h_b->index) {\r\n                edge_index = loc_edge_index;\r\n                break;\r\n            }\r\n        }\r\n        if (edge_index < 0) {\r\n            std::cout << \"EDGE NOT MATCHED in ANNOTATION COMPUTATION\" << std::endl;\r\n            exit(9);\r\n        }\r\n        //\r\n        vecEdgeAnno[edge_index] = tempAnnotation;\r\n        //\r\n\r\n    }\r\n    //std::cout << vecEdgeAnno[0].size() << std::endl;\r\n    //output.close();\r\n    //cout << \"Annotations written to \" << output_filename << endl;\r\n\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "683d99de043e284512e92aa88fc1ac8d67a50fae", "size": 5569, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/CycleOptimization/Annotation/AnnotationComputation.cpp", "max_stars_repo_name": "anapupa/ReebHanTun", "max_stars_repo_head_hexsha": "679ba774b75f4f53c502cb79f69bc9061c009eb8", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/CycleOptimization/Annotation/AnnotationComputation.cpp", "max_issues_repo_name": "anapupa/ReebHanTun", "max_issues_repo_head_hexsha": "679ba774b75f4f53c502cb79f69bc9061c009eb8", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/CycleOptimization/Annotation/AnnotationComputation.cpp", "max_forks_repo_name": "anapupa/ReebHanTun", "max_forks_repo_head_hexsha": "679ba774b75f4f53c502cb79f69bc9061c009eb8", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.3779069767, "max_line_length": 115, "alphanum_fraction": 0.5715568325, "num_tokens": 1427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.782662489091802, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4609014328858591}}
{"text": "/// \\file\n/// Maintainer: Felice Serena\n///\n\n#include \"disparity_registration.h\"\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <boost/log/trivial.hpp>\n\nnamespace MouseTrack {\nPointCloud DisparityRegistration::operator()(const FrameWindow &window) const {\n  const auto &frames = window.frames();\n\n  // how many points will there be at most?\n  int expected_points = 0;\n  for (const auto &f : frames) {\n    expected_points += f.normalizedDisparityMap.size();\n  }\n\n  // absolute transformation matrix relative to first camera\n  auto Ts = absoluteTransformations(window);\n\n  std::vector<Inverse> inverses(frames.size());\n  for (size_t i = 0; i < frames.size(); i += 1) {\n    Eigen::Matrix4d mat = frames[i].rotationCorrection * Ts[i];\n    inverses[i] = prepareInverseTransformation(mat);\n  }\n\n  int labelsCount = frames[0].labels.size();\n\n  // Allocate point cloud enough large to capture all points\n  PointCloud cloud;\n  cloud.resize(expected_points, labelsCount);\n  int next_insert = 0;\n  const int border = frameBorder();\n  const double xshift = correctingXShift();\n  const double yshift = correctingYShift();\n  const double minDisp = minDisparity();\n  // go through each frame, converting the disparity values to 3d points\n  // relative to first camera\n  for (size_t i = 0; i < frames.size(); i += 1) {\n    const auto &f = frames[i];\n    const auto &disp = f.normalizedDisparityMap;\n    // convert each pixel\n    for (int y = border - 1; y < disp.rows() - border; y += 1) {\n      for (int x = border - 1; x < disp.cols() - border; x += 1) {\n        // disparity is returned between [0,1],\n        // but originally stored as [0,255]\n        double disparity = 255 * disp(y, x);\n        if (disparity < minDisp) {\n          // just skip those points\n          continue;\n        }\n        const double invDisparity = 1.0 / disparity;\n        auto p = cloud[next_insert];\n        p.x((x + xshift - f.ccx) * f.baseline * invDisparity);\n        p.y((y + yshift - f.ccy) * f.baseline * invDisparity);\n        p.z(f.focallength * f.baseline * invDisparity);\n\n        Eigen::Vector4d tmp = applyInverseTransformation(\n            inverses[i], Eigen::Vector4d(p.x(), p.y(), p.z(), 1.0));\n        p.x(tmp[0]);\n        p.y(tmp[1]);\n        p.z(tmp[2]);\n        p.intensity(f.referencePicture(y, x));\n        PointCloud::LabelVec labels(f.labels.size());\n        for (size_t l = 0; l < f.labels.size(); ++l) {\n          labels[l] = f.labels[l](y, x);\n        }\n        p.labels(std::move(labels));\n        next_insert += 1;\n      }\n    }\n  }\n  cloud.resize(next_insert, labelsCount); // shrink to actual number of points\n\n  auto min = cloud.posMin();\n  auto max = cloud.posMax();\n\n  BOOST_LOG_TRIVIAL(debug) << \"Found point cloud with \" << cloud.size()\n                           << \" points, xyz-min: [\" << min[0] << \", \" << min[1]\n                           << \", \" << min[2] << \"], xyz-max: [\" << max[0]\n                           << \", \" << max[1] << \", \" << max[2] << \"]\"\n                           << std::flush;\n  return cloud;\n}\n\nstd::vector<Eigen::Matrix4d> DisparityRegistration::absoluteTransformations(\n    const FrameWindow &window) const {\n  const auto &frames = window.frames();\n  std::vector<Eigen::Matrix4d> Ts(frames.size());\n  Ts[0] = Eigen::Matrix4d::Identity();\n  for (size_t i = 1; i < frames.size(); i += 1) {\n    Ts[i] =\n        frames[i].camChainPicture * frames[i - 1].camChainDisparity * Ts[i - 1];\n  }\n  return Ts;\n}\n\nDisparityRegistration::Inverse\nDisparityRegistration::prepareInverseTransformation(\n    const Eigen::Matrix4d &mat) const {\n  // For the moment, we just return the inverse.\n  // We could also use a decomposition object from Eigen\n  // to increase robustness.\n  // Or we could use domain knowledge about the\n  // transformation to speed up computations.\n  return mat.inverse();\n}\n\nEigen::Vector4d DisparityRegistration::applyInverseTransformation(\n    const DisparityRegistration::Inverse &inv, const Eigen::Vector4d &p) const {\n  // for the moment just a simple multiplication\n  return inv * p;\n}\n\ndouble &DisparityRegistration::minDisparity() { return _min_disparity; }\n\n/// Lowest disparity value we accept (we remove points at infinity)\nconst double &DisparityRegistration::minDisparity() const {\n  return _min_disparity;\n}\n\n/// Set X shift to correct disparity map position\nint &DisparityRegistration::correctingXShift() { return _xshift; }\n\n/// Read X shift to correct disparity map position\nconst int &DisparityRegistration::correctingXShift() const { return _xshift; }\n\n/// Set Y shift to correct disparity map position\nint &DisparityRegistration::correctingYShift() { return _yshift; }\n\n/// Read Y shift to correct disparity map position\nconst int &DisparityRegistration::correctingYShift() const { return _yshift; }\n\n/// Ignores boder of n pixels around disparity map\nint &DisparityRegistration::frameBoder() { return _frame_border; }\n\n/// Ignores boder of n pixels around disparity map\nconst int &DisparityRegistration::frameBorder() const { return _frame_border; }\n\n} // namespace MouseTrack\n", "meta": {"hexsha": "c497839ccaf99a5a91b453663855d33d4ab1e413", "size": 5045, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/registration/disparity_registration.cpp", "max_stars_repo_name": "itko/scanbox", "max_stars_repo_head_hexsha": "9a00c11eafb4cc2faa69bfcc76bdf0d8e295dcf3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-09T09:30:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-09T09:30:23.000Z", "max_issues_repo_path": "lib/registration/disparity_registration.cpp", "max_issues_repo_name": "itko/scanbox", "max_issues_repo_head_hexsha": "9a00c11eafb4cc2faa69bfcc76bdf0d8e295dcf3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 23.0, "max_issues_repo_issues_event_min_datetime": "2018-03-19T20:54:52.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-16T12:36:59.000Z", "max_forks_repo_path": "lib/registration/disparity_registration.cpp", "max_forks_repo_name": "itko/scanbox", "max_forks_repo_head_hexsha": "9a00c11eafb4cc2faa69bfcc76bdf0d8e295dcf3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-03-14T20:00:43.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-14T20:00:43.000Z", "avg_line_length": 35.0347222222, "max_line_length": 80, "alphanum_fraction": 0.6485629336, "num_tokens": 1289, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624840223698, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.46090142990052557}}
{"text": "#include \"ADLER32Strategy.hpp\"\n#include \"checksum.h\"\n\n#include <sstream>\n#include <iostream>\n#include <iomanip>\n#include <cstring>\n#include <boost/algorithm/string/predicate.hpp>\n\n#include \"base64.h\"\n\nnamespace irods {\n\n    const std::string ADLER32_NAME( \"adler32\" );\n\n    struct adler32_parts {\n        uint32_t a;\n        uint32_t b;\n    };\n\n    adler32_parts adler32_init() {\n        return adler32_parts{1, 0};\n    }\n\n    static adler32_parts adler32_update(const adler32_parts& parts, const unsigned char *data, size_t len) {\n\n        const uint32_t MOD_ADLER = 65521;\n\n        uint32_t a = parts.a, b = parts.b;\n\n        // Process each byte of the data in order\n        for (size_t index = 0; index < len; ++index)\n        {\n            a = (a + data[index]) % MOD_ADLER;\n            b = (b + a) % MOD_ADLER;\n        }\n\n        return adler32_parts{a, b};\n    }\n\n    static uint32_t adler32_final(const adler32_parts& parts) {\n        return (parts.b << 16) | parts.a;\n    }\n\n\n    error\n    ADLER32Strategy::init( boost::any& _context ) const {\n        _context = adler32_init();\n        return SUCCESS();\n    }\n\n    error\n    ADLER32Strategy::update( const std::string& data, boost::any& _context ) const {\n\n        _context = adler32_update(boost::any_cast<adler32_parts>(_context), reinterpret_cast<const unsigned char*>(data.c_str()), data.size());\n        return SUCCESS();\n    }\n\n    error\n    ADLER32Strategy::digest( std::string& _messageDigest, boost::any& _context ) const {\n\n        const unsigned int ADLER32_DIGEST_LENGTH = 4;\n\n        uint32_t result = adler32_final(boost::any_cast<adler32_parts>(_context));\n\n        std::stringstream ss;\n        ss << std::setfill('0') << std::hex << std::setw(ADLER32_DIGEST_LENGTH * 2) << result;\n\n        _messageDigest = ADLER32_CHKSUM_PREFIX;\n        _messageDigest += ss.str();\n\n        return SUCCESS();\n    }\n\n    bool\n    ADLER32Strategy::isChecksum( const std::string& _chksum ) const {\n        return boost::starts_with( _chksum, ADLER32_CHKSUM_PREFIX );\n    }\n}; // namespace irods\n", "meta": {"hexsha": "b4207d868826d3a8399f4655ee4577726498d0a6", "size": 2053, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/hasher/src/ADLER32Strategy.cpp", "max_stars_repo_name": "JustinKyleJames/irods", "max_stars_repo_head_hexsha": "59e9db75200e95796ec51ec20eb3b185d9e4b5f5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 333.0, "max_stars_repo_stars_event_min_datetime": "2015-01-15T15:42:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T19:16:15.000Z", "max_issues_repo_path": "lib/hasher/src/ADLER32Strategy.cpp", "max_issues_repo_name": "JustinKyleJames/irods", "max_issues_repo_head_hexsha": "59e9db75200e95796ec51ec20eb3b185d9e4b5f5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3551.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T19:55:40.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T21:24:56.000Z", "max_forks_repo_path": "lib/hasher/src/ADLER32Strategy.cpp", "max_forks_repo_name": "JustinKyleJames/irods", "max_forks_repo_head_hexsha": "59e9db75200e95796ec51ec20eb3b185d9e4b5f5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 148.0, "max_forks_repo_forks_event_min_datetime": "2015-01-31T16:13:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T20:23:43.000Z", "avg_line_length": 25.6625, "max_line_length": 143, "alphanum_fraction": 0.6264003897, "num_tokens": 553, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529376, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.46090142691519204}}
{"text": "// Andrew Long\n// Updated: Feb 13, 2017\n// DFS Matrix Alignment Codes\n\n#ifndef __DFS_ALIGN__\n#define __DFS_ALIGN__\n\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <functional>\n#include <utility>\n#include <armadillo>\n\n#include \"GridDLL.hpp\"\n#include \"Heuristic.h\"\n\n\n#define DO_MAX_CUT 0\n#define MAX_EVALS (N1*N1*N2*N2*n_branch)\n\ninline double\nL11_norm(const arma::mat& A, const arma::mat& B)\n{\n\tif(A.size() != B.size())\n\t{\n\t\tthrow std::logic_error(\"L1,1-norm works only for equal sized graphs\");\n\t}\n\treturn arma::norm(arma::vectorise(A - B),1);\n}\n\ninline void\nfill_range(arma::uvec& v, long N)\n{\n\tv.set_size(N);\n\tfor(long i = 0; i < N; ++i)\n\t\tv(i) = i;\n}\n\n\ntypedef std::pair<double, int> MoveIndex;\n\nclass DFSAlign\n{\nprivate:\n\tdouble min_dist, opt_dist;\n\tlong N1, N2, Nelem;\n    long n_branch;\n\tarma::mat M1;\n\tarma::mat M1_t;\n\tarma::mat M2;\n\tarma::uvec min_perm1;\n\tarma::uvec min_perm2;\n\tarma::mat min_perm;\n\tarma::uvec fevals;\n\tarma::mat score;\n\tGridDLL full_list;\n    std::vector<GridPoint> all_moves;\n    std::vector<MoveIndex> all_move_dists;\n    MatchHeuristic heuristic;\n    long num_all;\n    \n\tbool isAligned;\n\t\n\t\n\tvoid recursiveHelper(int depth, double currentD, GridPoint root, GridDLL& list, arma::uvec& perm1, arma::uvec& perm2)\n\t{\n\t\tif(min_dist == opt_dist)\n\t\t\treturn;\n\n        perm1[depth] = root.first;\n        perm2[depth] = root.second;\n        //TODO: if N1 != N2, you're done \"matching\", so it shouldn't really matter what else happens\n        if(depth == N1-1)\n        {\n            \n            if(N1 != N2)\n            {\n                std::vector<int> vec2;\n                // fill in the rest of the values\n                // unassigned N1 will be N1..N2-1\n                // unassigned N2 requires identification\n                arma::uvec bp = arma::sort(perm2,\"ascend\");\n                int c = 0;\n                for(int i =0; i < N1; ++i)\n                {\n\n                    while(c < (int)bp[i])\n                    {\n                        vec2.push_back(c++);\n                    }\n                    ++c;\n                }\n                for(int i = (int)(bp[N1-1]+1); i < N2; ++i)\n                {\n                    vec2.push_back(i);\n                }\n                c = (int)vec2.size();\n                for(int i = 0; i < c; ++i)\n                {\n                    ++depth;\n                    perm1[depth] = N1+i;\n                    perm2[depth] = vec2[i];\n                    currentD = computeDist(perm1,perm2,currentD,depth);\n                }\n                \n                for(int i = 0; i < c; ++i)\n                {\n                    perm1[depth] = -1;\n                    perm2[depth] = -1;\n                    depth--;\n                }\n            }\n            \n            if(min_dist > currentD)\n            {\n                min_dist = currentD;\n                min_perm1 = perm1;\n                min_perm2 = perm2;\n            }\n            \n#if defined (DO_MAX_CUT)\n    #if DO_MAX_CUT == 1\n            if(fevals(depth-1)>=(uint32_t)MAX_EVALS){\n                opt_dist = min_dist;\n            }\n    #endif\n#endif\n            return;\n        }\n        \n\t\tlist.clearOverlaps(root.first, root.second);\n\n        long nK = list.topK(n_branch, all_moves, num_all);\n        sortAllMoves(nK, perm1, perm2, currentD, depth+1);\n        fevals(depth) += nK;\n        int start = (int)num_all;\n        num_all += nK;\n\n        for(int i = start; i < num_all; ++i)\n        {\n            // already worse than the best matching\n            if(all_move_dists[i].first > min_dist)\n                continue;\n            \n            recursiveHelper(depth+1,\n                            all_move_dists[i].first,\n                            all_moves[all_move_dists[i].second],\n                            list, perm1, perm2);\n\n            if(min_dist == opt_dist)\n                return;\n        }\n        num_all -= nK;\n        list.relinkStack(depth);\n\t}\n\t\n    void sortAllMoves(long nK, arma::uvec& perm1, arma::uvec& perm2, const double curD, int depth)\n    {\n        int start = (int)num_all;\n        int end = (int)(num_all+nK);\n        for(int i = start; i < end; ++i)\n        {\n            perm1[depth] = all_moves.at(i).first;\n            perm2[depth] = all_moves.at(i).second;\n            all_move_dists[i].first = computeDist(perm1,perm2,curD, depth);\n            all_move_dists[i].second = i;\n        }\n        std::sort(all_move_dists.begin()+start, all_move_dists.begin()+end,\n                  [](MoveIndex a, MoveIndex b) -> bool\n                  {\n                      return a.first < b.first;\n                  });\n        perm1[depth] = 0;\n        perm2[depth] = 0;\n    }\n    \n\tvoid sortMoves(long nK, const std::vector<GridPoint>& moves, std::vector<MoveIndex>& move_dists, arma::uvec& perm1, arma::uvec& perm2, const double curD, int depth)\n\t{\n\t\tfor(unsigned int i = 0; i < nK; ++i)\n\t\t{\n\t\t\tperm1[depth] = moves.at(i).first;\n\t\t\tperm2[depth] = moves.at(i).second;\n            move_dists[i].first = computeDist(perm1,perm2,curD, depth);\n            move_dists[i].second = i;\n\t\t}\n\t\tstd::sort(move_dists.begin(), move_dists.begin()+nK,\n\t\t\t[](MoveIndex a, MoveIndex b) -> bool\n\t\t\t\t{\n\t\t\t\t\treturn a.first < b.first;\n\t\t\t\t});\n        perm1[depth] = 0;\n        perm2[depth] = 0;\n\t}\n\n    // NOTE: uses symmetry of the underlying M1/M2 matrices to speed up the process\n    // WILL NOT WORK FOR NON-SYMMETRIC MATRICES\n\tdouble computeDist(const arma::uvec& p1, const arma::uvec& p2, const double curD, int depth)\n\t{\n        double d = curD;\n        int mdepth = depth-1;\n        for(int i = 0; i <= mdepth; ++i)\n        {\n            d += 2*std::abs(M1_t(p1(depth),p1(i))-M2(p2(depth),p2(i)));\n        }\n        d += std::abs(M1_t(p1(depth),p1(depth)) - M2(p2(depth),p2(depth)));\n\n        return d;\n\t}\n\npublic:\n\tDFSAlign(const arma::mat& m1, const arma::mat& m2, int branch = 1, MatchHeuristic h = MatchHeuristic::ISORANK) \n\t{\n\t\tinit(m1, m2, branch, h);\n\t\treset();\n\t}\n\n\tvoid init(const arma::mat& m1, const arma::mat& m2, int branch, MatchHeuristic h)\n\t{\n\t\tif(m1.n_rows <= m2.n_rows)\n\t\t{\n\t\t\tM1 = m1;\n\t\t\tM2 = m2;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tM1 = m2;\n\t\t\tM2 = m1;\n\t\t}\n\t\tN1 = M1.n_rows;\n\t\tN2 = M2.n_rows;\n\t\t\n\t\t// setting up number for normalization\n\t\tNelem = N2*(N2-1);\n\t\tif(Nelem == 0) \n\t\t\tNelem = 1;\n\t\t// optimal distance\n\t\tM1_t = M1;\n\t\tM1_t.resize(N2,N2);\n        \n\t\tarma::vec av = arma::vectorise(M1_t);\n\t\tav = arma::sort(av,\"descend\");\n\t\tarma::vec bv = arma::vectorise(M2);\n\t\tbv = arma::sort(bv,\"descend\");\n\t\topt_dist = arma::norm(av-bv,1);\n\t\tif(N1 == 1 || N2 == 1)\n\t\t{\n\t\t\tmin_dist = opt_dist;\n\t\t\tisAligned = true;\n\t\t\treturn;\n\t\t}\n        \n        // score measuring via matching heuristic\n        heuristic = h;\n        heuristic_func hfunc = heuristic_map[heuristic];\n        score = (*hfunc)(M1, M2);\n        /*\n\t\tav = arma::sum(M1,1);\n\t\tav = av/arma::norm(av,2);\n\t\tbv = arma::sum(M2,1);\n\t\tbv = bv/arma::norm(bv,2);\n\n\t\tscore = av * (bv.t());\n        */\n\t\tfull_list.buildFromMat(score);\n\t\t\n\t\tn_branch = branch;\n\t\tfevals = arma::uvec(N2,arma::fill::zeros);\n        \n        all_moves.resize(N2*N2*n_branch);\n        all_move_dists.resize(N2*N2*n_branch);\n        \n        num_all = 0;\n\t\tisAligned = false;\n\t}\n\t\n\tvoid reset(int branch = -1)\n\t{\n\t\tisAligned = false;\n\t\t\n\t\tmin_dist = L11_norm(M1_t,M2);\n\n\t\tfill_range(min_perm1,N2);\n\t\tfill_range(min_perm2,N2);\t\n\n\t\tif(branch != -1)\n        {\n\t\t\tn_branch = branch;\n            all_moves.resize(N2*N2*2);\n            all_move_dists.resize(N2*N2*n_branch);\n        }\n\t}\n\n\tvoid align()\n\t{\n\t\treset();\n\n\t\tint depth = 0;\n\t\t// grab the top BRANCH score pairs\n\t\tGridDLL current_list(full_list);\n\t\t\t\n        int nK = (int)current_list.topK(n_branch,all_moves,0);\n        num_all = nK;\n        \n\t\t// loop over the top values\n        arma::uvec perm1(N2,arma::fill::ones); perm1 *= -1;\n        arma::uvec perm2(N2,arma::fill::ones); perm2 *= -1;\n\n\t\tfor(int i = 0; i < nK; ++i)\n\t\t{\n            if(min_dist == opt_dist)\n                break;\n            recursiveHelper(depth, 0, all_moves.at(i), current_list, perm1, perm2);\n\t\t}\n\t\t\n\t\t// generate permutation\n\t\tmin_perm.zeros(N1,N2);\n\t\tfor(int i=0; i < N1; ++i)\n\t\t{\n\t\t\tmin_perm( min_perm1(i), min_perm2(i) ) = 1;\n\t\t}\n\t\tmin_dist = arma::norm(arma::vectorise(min_perm.t() * M1 * min_perm - M2),1);\n\t\tisAligned = true;\n\t}\n\t\n\tdouble getDistance(arma::mat& perm)\n\t{\n\t\tdouble d = getDistance();\n\t\tperm = min_perm;\n\t\treturn d;\n\t}\n\n\tdouble getDistance()\n\t{\n\t\tif(!isAligned)\n\t\t\talign();\n\t\treturn min_dist;\n\t}\n\t\n\tdouble getNormalizedDistance()\n\t{\n\t\tif(!isAligned)\n\t\t\talign();\n\t\treturn min_dist / Nelem;\n\t}\n\n\tarma::uvec getFEvals()\n\t{\n\t\treturn fevals;\n\t}\n    \n    unsigned long long getTotalEvals()\n    {\n        return arma::sum(fevals);\n    }\n};\n\n\ndouble\ndist_dfs(arma::mat& a, arma::mat& b, uint branches, MatchHeuristic h = MatchHeuristic::ISORANK)\n{\n\tDFSAlign aligner(a, b, branches, h);\n\treturn aligner.getNormalizedDistance();\n}\n\n#endif\n", "meta": {"hexsha": "795922f3886a95c099e8322e2bdb107e4eec4ef3", "size": 8884, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/DFSAlign.hpp", "max_stars_repo_name": "awlong/DiffusionMap", "max_stars_repo_head_hexsha": "64eac6871197723ddd1a2e536cf699c6fb905217", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2015-08-12T16:54:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T10:32:04.000Z", "max_issues_repo_path": "src/DFSAlign.hpp", "max_issues_repo_name": "awlong/DiffusionMap", "max_issues_repo_head_hexsha": "64eac6871197723ddd1a2e536cf699c6fb905217", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/DFSAlign.hpp", "max_forks_repo_name": "awlong/DiffusionMap", "max_forks_repo_head_hexsha": "64eac6871197723ddd1a2e536cf699c6fb905217", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2017-08-11T17:05:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-07T04:20:00.000Z", "avg_line_length": 24.2070844687, "max_line_length": 165, "alphanum_fraction": 0.5294912202, "num_tokens": 2632, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.460901426915192}}
{"text": "#include \"lineturtle.h\"\n#include \"lineshape.h\"\n#include <algorithm>\n#include <boost/lambda/bind.hpp>\n#include <lap/lap.h>\n#include <cmath>\n#include \"common.h\"\n\nusing namespace boost::lambda;\n\ninline float radians(float angleDegrees) { return M_PI * angleDegrees / 180.0f; }\n\nLineTurtle::LineTurtle(float lineLength):\n_advance(lineLength),\n_heading(),\n_x(),\n_y()\n{\n}\n\n\nbool LineTurtle::init(const std::string& program)\n{\n  _actions['F'] = &LineTurtle::draw;\n  _actions['f'] = &LineTurtle::forward;\n  _actions['+'] = &LineTurtle::left;\n  _actions['-'] = &LineTurtle::right;\n  _dol = DOL::makeDOL(program);\n  if (!_dol) return false;\n  std::cout << \"DOL: \" << *_dol << std::endl;\n  reset();\n  return true;\n}\n\nvoid LineTurtle::step()\n{\n//  shared_ptr<Mesh<VertexP> mesh(new Mesh<VertexP>());\n  _mesh = shared_ptr<lap::Mesh<lap::VertexP> >(new lap::Mesh<lap::VertexP>() );\n  for_each(_state.begin(), _state.end(), bind(&LineTurtle::doAction, this, _1));\n\n  _shape = makeLineShape(_mesh);\n  _state = _dol->step(_state);\n}\nvoid LineTurtle::reset()\n{\n  _state = _dol->axiom();\n  _x = _y = 0.0f;\n  _heading = 0.0f;\n  _shape.reset();\n}\nvoid LineTurtle::render(QGLShaderProgram* program)\n{\nif (_shape)  _shape->render(program);\n}\n\nvoid LineTurtle::draw()\n{\n  _mesh->_vertices.push_back(makeVertex(_x, _y, 0.0));\n  _x = _x + _advance * cosf(radians(_heading));\n  _y = _y + _advance * sinf(radians(_heading));\n  _mesh->_vertices.push_back(makeVertex(_x, _y, 0.0));\n\n}\nvoid LineTurtle::forward()\n{\n  _x = _x + _advance * cosf(radians(_heading));\n  _y = _y + _advance * sinf(radians(_heading));\n}\nvoid LineTurtle::left()\n{\n  _heading += _dol->theta();\n}\nvoid LineTurtle::right()\n{\n  _heading -= _dol->theta();\n}\n", "meta": {"hexsha": "beff28a7349b445a1eff5c3b3e4a68dda7e701bb", "size": 1697, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "toy-problems/lsystems/doldraw/lineturtle.cpp", "max_stars_repo_name": "danielgrigg/sandbox", "max_stars_repo_head_hexsha": "95128ef44ddc2df2a819b14b9930f95d9c9fd423", "max_stars_repo_licenses": ["WTFPL"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-02-23T03:57:39.000Z", "max_stars_repo_stars_event_max_datetime": "2017-02-23T03:57:39.000Z", "max_issues_repo_path": "toy-problems/lsystems/doldraw/lineturtle.cpp", "max_issues_repo_name": "danielgrigg/sandbox", "max_issues_repo_head_hexsha": "95128ef44ddc2df2a819b14b9930f95d9c9fd423", "max_issues_repo_licenses": ["WTFPL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "toy-problems/lsystems/doldraw/lineturtle.cpp", "max_forks_repo_name": "danielgrigg/sandbox", "max_forks_repo_head_hexsha": "95128ef44ddc2df2a819b14b9930f95d9c9fd423", "max_forks_repo_licenses": ["WTFPL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.038961039, "max_line_length": 81, "alphanum_fraction": 0.6652916912, "num_tokens": 547, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.5888891307678319, "lm_q1q2_score": 0.46090142691519187}}
{"text": "\n#include <QApplication>\n#include <QKeyEvent>\n#include <QPushButton>\n#include \"GLModelViewer.h\"\n#include \"GLModel.h\"\n#include \"GLShaderProgram.h\"\n#include \"Grid.h\"\n#include <iostream>\n#include <chrono>\n#include <sstream>\n#include <fstream>\n#include <Eigen/Dense>\n#include \"Timer.h\"\n#include \"Projection.h\"\n#include \"Volumetric_helper.h\"\n\n\n\n\n\n#if 0\nvoid raycast_volume()\n{\n\ttimer.start();\n\n\tEigen::Vector3d origin = T.first.col(3).head<3>();\n\tEigen::Vector3d window_coord_norm;\n\n\tstd::vector<Eigen::Vector3d> output_cloud;\n\n\t// Sweep the volume looking for the zero crossing\n\tfor (int y = 0; y < window_height * 0.1; ++y)\n\t{\n\t\tstd::cout << \"Ray casting to image... \" << (double)y / window_height * 100 << \"%\" << std::endl;\n\n\t\tfor (int x = 0; x < window_width * 0.1; ++x)\n\t\t{\n\t\t\twindow_coord_norm.x() = ((double)x / window_width * 2.0) - 1.0;\n\t\t\twindow_coord_norm.y() = ((double)y / window_height * 2.0) - 1.0;\n\t\t\twindow_coord_norm.z() = origin.z() + near_plane;\n\t\t\tEigen::Vector3d direction = (window_coord_norm - origin).normalized();\n\n\t\t\tstd::vector<int> intersections = Grid::find_intersections(grid.data, volume_size, voxel_size, grid.transformation, origin, direction, near_plane, far_plane);\n\t\t\tGrid::sort_intersections(intersections, grid.data, origin);\n\n\t\t\tfor (int i = 1; i < intersections.size(); ++i)\n\t\t\t{\n\t\t\t\tconst Voxeld& prev = grid.data.at(i - 1);\n\t\t\t\tconst Voxeld& curr = grid.data.at(i);\n\n\t\t\t\tconst bool& same_sign = ((prev.tsdf < 0) == (curr.tsdf < 0));\n\n\t\t\t\tif (!same_sign)\t\t// it is a zero-crossing\n\t\t\t\t{\n\t\t\t\t\toutput_cloud.push_back(curr.point);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\ttimer.print_interval(\"Raycasting volume   : \");\n\n\n\texport_obj(\"../../data/output_cloud.obj\", output_cloud);\n}\n#endif\n\n// Usage: ./Volumetricd.exe ../../data/monkey.obj 256 4 2 90\nint main(int argc, char **argv)\n{\n\tif (argc < 6)\n\t{\n\t\tstd::cerr << \"Missing parameters. Abort.\" \n\t\t\t<< std::endl\n\t\t\t<< \"Usage:  ./Volumetricd.exe ../../data/monkey.obj 256 8 2 90\"\n\t\t\t<< std::endl;\n\t\treturn EXIT_FAILURE;\n\t}\n\tTimer timer;\n\tconst std::string filepath = argv[1];\n\tconst int vol_size = atoi(argv[2]);\n\tconst int vx_size = atoi(argv[3]);\n\tconst int cloud_count = atoi(argv[4]);\n\tconst int rot_interval = atoi(argv[5]);\n\n\tstd::pair<std::vector<double>, std::vector<double>> depth_buffer;\n\n\t//\n\t// Projection and Modelview Matrices\n\t//\n\tEigen::Matrix4d K = perspective_matrix(fov_y, aspect_ratio, near_plane, far_plane);\n\tstd::pair<Eigen::Matrix4d, Eigen::Matrix4d>\tT(Eigen::Matrix4d::Identity(), Eigen::Matrix4d::Identity());\n\n\n\t//\n\t// Creating volume\n\t//\n\tEigen::Vector3d voxel_size(vx_size, vx_size, vx_size);\n\tEigen::Vector3d volume_size(vol_size, vol_size, vol_size);\n\tEigen::Vector3d voxel_count(volume_size.x() / voxel_size.x(), volume_size.y() / voxel_size.y(), volume_size.z() / voxel_size.z());\n\t//\n\tEigen::Affine3d grid_affine = Eigen::Affine3d::Identity();\n\tgrid_affine.translate(Eigen::Vector3d(0, 0, -256));\n\tgrid_affine.scale(Eigen::Vector3d(1, 1, -1));\t// z is negative inside of screen\n\n\n\tGrid<double> grid(volume_size, voxel_size, grid_affine.matrix());\n\n\n\t//\n\t// Importing .obj\n\t//\n\ttimer.start();\n\tstd::vector<Eigen::Vector3d> points3DOrig, pointsTmp;\n\timport_obj(filepath, points3DOrig);\n\ttimer.print_interval(\"Importing monkey    : \");\n\tstd::cout << \"Monkey point count  : \" << points3DOrig.size() << std::endl;\n\n\t// \n\t// Translating and rotating monkey point cloud \n\tstd::pair<std::vector<Eigen::Vector3d>, std::vector<Eigen::Vector3d>> cloud;\n\t//\n\tEigen::Affine3d rotate = Eigen::Affine3d::Identity();\n\tEigen::Affine3d translate = Eigen::Affine3d::Identity();\n\ttranslate.translate(Eigen::Vector3d(0, 0, -256));\n\n\n\t// \n\t// Compute first cloud\n\t//\n\tfor (Eigen::Vector3d p3d : points3DOrig)\n\t{\n\t\tEigen::Vector4d rot = translate.matrix() * rotate.matrix() * p3d.homogeneous();\n\t\trot /= rot.w();\n\t\tcloud.first.push_back(rot.head<3>());\n\t}\n\t//\n\t// Update grid with first cloud\n\t//\n\ttimer.start();\n\tcreate_depth_buffer<double>(depth_buffer.first, cloud.first, K, Eigen::Matrix4d::Identity(), far_plane);\n\ttimer.print_interval(\"CPU compute depth   : \");\n\n\ttimer.start();\n\tupdate_volume(grid, depth_buffer.first, K, T.first);\n\ttimer.print_interval(\"CPU Update volume   : \");\n\n\t//\n\t// Compute next clouds\n\tEigen::Matrix4d cloud_mat = Eigen::Matrix4d::Identity();\n\tTimer iter_timer;\n\tfor (int i = 1; i < cloud_count; ++i)\n\t{\n\t\tstd::cout << std::endl << i << \" : \" << i * rot_interval << std::endl;\n\t\titer_timer.start();\n\n\t\t// Rotation matrix\n\t\trotate = Eigen::Affine3d::Identity();\n\t\trotate.rotate(Eigen::AngleAxisd(DegToRad(i * rot_interval), Eigen::Vector3d::UnitY()));\n\n\t\tcloud.second.clear();\n\t\tfor (Eigen::Vector3d p3d : points3DOrig)\n\t\t{\n\t\t\tEigen::Vector4d rot = translate.matrix() * rotate.matrix() * p3d.homogeneous();\n\t\t\trot /= rot.w();\n\t\t\tcloud.second.push_back(rot.head<3>());\n\t\t}\n\n\t\t//export_obj(\"../../data/cloud_cpu_2.obj\", cloud.second);\n\n\t\ttimer.start();\n\t\tcreate_depth_buffer<double>(depth_buffer.second, cloud.second, K, Eigen::Matrix4d::Identity(), far_plane);\n\t\ttimer.print_interval(\"Compute depth buffer: \");\n\n\t\t//export_depth_buffer(\"../../data/cpu_depth_buffer_2.obj\", depth_buffer.second);\n\n\t\ttimer.start();\n\t\tEigen::Matrix4d icp_mat;\n\t\tComputeRigidTransform(cloud.first, cloud.second, icp_mat);\n\t\ttimer.print_interval(\"Compute rigid transf: \");\n\n\t\t//std::cout << std::fixed << std::endl << \"icp_mat \" << std::endl << icp_mat << std::endl;\n\n\t\t// accumulate matrix\n\t\tcloud_mat = cloud_mat * icp_mat;\n\n\t\t//std::cout << std::fixed << std::endl << \"cloud_mat \" << std::endl << cloud_mat << std::endl;\n\n\t\ttimer.start();\n\t\t//update_volume(grid, depth_buffer.second, K, cloud_mat.inverse());\n\t\tupdate_volume(grid, depth_buffer.second, K, cloud_mat.inverse());\n\t\ttimer.print_interval(\"Update volume       : \");\n\n\n\t\t// copy second point cloud to first\n\t\tcloud.first = cloud.second;\n\t\t//depth_buffer.first = depth_buffer.second;\n\n\t\titer_timer.print_interval(\"Iteration time      : \");\n\t}\n\n\n\t//std::cout << \"------- // --------\" << std::endl;\n\t//for (int i = 0; i <  grid.data.size(); ++i)\n\t//{\n\t//\tconst Eigen::Vector3d& point = grid.data[i].point;\n\n\t//\tstd::cout << point.transpose() << \"\\t\\t\" << grid.data[i].tsdf << \" \" << grid.data[i].weight << std::endl;\n\t//}\n\t//std::cout << \"------- // --------\" << std::endl;\n\n//\ttimer.start();\n//\texport_volume(\"../../data/grid_volume_cpu.obj\", grid.data);\n//\ttimer.print_interval(\"Exporting volume    : \");\n//\treturn 0;\n\n\n\tQApplication app(argc, argv);\n\n\t//\n\t// setup opengl viewer\n\t// \n\tGLModelViewer glwidget;\n\tglwidget.resize(640, 480);\n\tglwidget.setPerspective(60.0f, 0.1f, 10240.0f);\n\tglwidget.move(320, 0);\n\tglwidget.setWindowTitle(\"Point Cloud\");\n\tglwidget.setWeelSpeed(0.1f);\n\tglwidget.setPosition(0, 0, -0.5f);\n\tglwidget.show();\n\n\t\n\tEigen::Matrix4d to_origin = Eigen::Matrix4d::Identity();\n\tto_origin.col(3) << -(volume_size.x() / 2.0), -(volume_size.y() / 2.0), -(volume_size.z() / 2.0), 1.0;\t// set translate\n\n\n\tstd::vector<Eigen::Vector4f> vertices, colors;\n\n\tint i = 0;\n\tfor (int z = 0; z <= volume_size.z(); z += voxel_size.z())\n\t{\n\t\tfor (int y = 0; y <= volume_size.y(); y += voxel_size.y())\n\t\t{\n\t\t\tfor (int x = 0; x <= volume_size.x(); x += voxel_size.x(), i++)\n\t\t\t{\n\t\t\t\tconst float tsdf = grid.data.at(i).tsdf;\n\n\t\t\t\t//Eigen::Vector4d p = grid_affine.matrix() * to_origin * Eigen::Vector4d(x, y, z, 1);\n\t\t\t\tEigen::Vector4d p = to_origin * Eigen::Vector4d(x, y, z, 1);\n\t\t\t\tp /= p.w();\n\n\t\t\t\tif (tsdf > 0.1)\n\t\t\t\t{\n\t\t\t\t\tvertices.push_back(p.cast<float>());\n\t\t\t\t\tcolors.push_back(Eigen::Vector4f(0, 1, 0, 1));\n\t\t\t\t}\n\t\t\t\telse if (tsdf < -0.1)\n\t\t\t\t{\n\t\t\t\t\tvertices.push_back(p.cast<float>());\n\t\t\t\t\tcolors.push_back(Eigen::Vector4f(1, 0, 0, 1));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\n\n\n\t//\n\t// setup model\n\t// \n\tstd::shared_ptr<GLModel> model(new GLModel);\n\tmodel->initGL();\n\tmodel->setVertices(&vertices[0][0], vertices.size(), 4);\n\tmodel->setColors(&colors[0][0], colors.size(), 4);\n\tglwidget.addModel(model);\n\n\n\t//\n\t// setup kinect shader program\n\t// \n\tstd::shared_ptr<GLShaderProgram> kinectShaderProgram(new GLShaderProgram);\n\tif (kinectShaderProgram->build(\"color.vert\", \"color.frag\"))\n\t\tmodel->setShaderProgram(kinectShaderProgram);\n\n\treturn app.exec();\n}\n\n\n\n", "meta": {"hexsha": "8fff4e8a9a0634db15700870f3c3170b19285f3b", "size": 8098, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Volumetric.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/Volumetric.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/Volumetric.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": 27.7328767123, "max_line_length": 160, "alphanum_fraction": 0.6527537664, "num_tokens": 2416, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4609014209445247}}
{"text": "#ifndef POLIMIDL_LAYERS_INTERNAL_DEPTHWISE_CONVOLUTION_HPP\n#define POLIMIDL_LAYERS_INTERNAL_DEPTHWISE_CONVOLUTION_HPP\n\n#include <algorithm>\n#include <chrono>\n\n#include <Eigen/Dense>\n\n#include \"../alignment.hpp\"\n#include \"../layer.hpp\"\n\nnamespace polimidl {\nnamespace layers {\nnamespace internal {\ntemplate <typename type_t, typename components, typename kernel,\n          typename stride, typename padding>\nclass depthwise_convolution : public layer<type_t, components> {\n public:\n  depthwise_convolution(type_t const *coeff) :\n      coeff_(coeff),\n      batch_size_(1) {}\n\n  static std::size_t output_rows(std::size_t input_rows) {\n    return (input_rows + padding::rows - kernel::rows) / stride::rows + 1;\n  }\n  static std::size_t output_columns(std::size_t input_columns) {\n    return (input_columns + padding::columns - kernel::columns) /\n        stride::columns + 1;\n  }\n  static std::size_t temporary_size(std::size_t input_rows,\n                                    std::size_t input_columns,\n                                    std::size_t number_of_workers) {\n    return cell_size * number_of_workers;\n  }\n\n  template <typename input_t, typename temporary_t, typename output_t,\n            typename scheduler_t>\n  void operator()(input_t input, temporary_t temporary, output_t output,\n                  std::size_t input_rows, std::size_t input_columns,\n                  const scheduler_t& scheduler) const {\n    const std::size_t output_rows = this->output_rows(input_rows);\n    const std::size_t output_columns = this->output_columns(input_columns);\n    const std::size_t cells = output_rows * output_columns;\n    const unsigned int number_of_workers = scheduler.number_of_workers();\n\n    for (std::size_t start_cell = 0; start_cell < cells;\n         start_cell += batch_size_) {\n      const std::size_t end_cell = std::min(cells, start_cell + batch_size_);\n      scheduler.schedule([=] (std::size_t worker) {\n        auto temporary_worker = temporary.slice(worker, number_of_workers);\n        for (std::size_t cell = start_cell; cell < end_cell; ++cell) {\n          const std::size_t output_row = cell / output_columns;\n          const std::size_t output_column = cell % output_columns;\n          for (std::size_t kernel_row = 0; kernel_row < kernel::rows;\n               ++kernel_row) {\n            const std::size_t input_row =\n                stride::rows * output_row + kernel_row;\n            auto i_temp = &temporary_worker[\n                components::value * kernel::columns * kernel_row];\n            if constexpr (padding::top && padding::bottom) {\n              if (input_row < padding::top ||\n                  input_row >= input_rows + padding::top) {\n                std::fill_n(i_temp, components::value * kernel::columns,\n                            type_t(0));\n                continue;\n              }\n            } else if constexpr (padding::top) {\n              if (input_row < padding::top) {\n                std::fill_n(i_temp, components::value * kernel::columns,\n                            type_t(0));\n                continue;\n              }\n            } else if constexpr (padding::bottom) {\n              if (input_row >= input_rows) {\n                std::fill_n(i_temp, components::value * kernel::columns,\n                            type_t(0));\n                continue;\n              }\n            }\n            if constexpr (padding::left || padding::right) {\n              for (std::size_t kernel_column = 0;\n                   kernel_column < kernel::columns; ++kernel_column) {\n                const std::size_t input_column =\n                    stride::columns * output_column + kernel_column;\n                if constexpr (padding::left && padding::right) {\n                  if (input_column < padding::left ||\n                      input_column >= input_columns + padding::left) {\n                    std::fill_n(i_temp + components::value * kernel_column,\n                                components::value, type_t(0));\n                    continue;\n                  }\n                } else if constexpr (padding::left) {\n                  if (input_column < padding::left) {\n                    std::fill_n(i_temp + components::value * kernel_column,\n                                components::value, type_t(0));\n                    continue;\n                  }\n                } else if constexpr (padding::right) {\n                  if (input_column >= input_columns) {\n                    std::fill_n(i_temp + components::value * kernel_column,\n                                components::value, type_t(0));\n                    continue;\n                  }\n                }\n                auto i_input = &input[components::value * (\n                    input_columns * (input_row - padding::top) +\n                    (input_column - padding::left))];\n                std::copy_n(i_input, components::value,\n                            i_temp + components::value * kernel_column);\n              }\n            } else {\n              const std::size_t input_column = stride::columns * output_column;\n              auto i_input = &input[components::value * (\n                  input_columns * (input_row - padding::top) +\n                  input_column)];\n              std::copy_n(i_input, components::value * kernel::columns, i_temp);\n            }\n          }\n          matrix_input_t val(&temporary_worker[0]);\n          auto i_output = &output[components::value * (\n              output_columns * output_row + output_column)];\n          matrix_output_t out(i_output);\n          out.noalias() = (val * coeff_).diagonal();\n        }\n      });\n    }\n    scheduler.wait();\n  }\n\n  template <typename input_t, typename temporary_t, typename output_t,\n            typename scheduler_t>\n  void optimize_for(input_t input, temporary_t temporary, output_t output,\n                    std::size_t input_rows, std::size_t input_columns,\n                    const scheduler_t& scheduler) {\n      const std::size_t output_rows = this->output_rows(input_rows);\n      const std::size_t output_columns = this->output_columns(input_columns);\n      const std::size_t cells = output_rows * output_columns;\n\n      if (scheduler.number_of_workers() == 1) {\n        batch_size_ = cells;\n        return;\n      }\n\n      auto best_duration = std::chrono::high_resolution_clock::duration::max();\n\n      std::size_t best_batch_size = 1;\n      auto test_and_maybe_set = [&]() {\n          for (std::size_t iteration = 0; iteration < 3; ++iteration) {\n              const auto start = std::chrono::high_resolution_clock::now();\n              operator()(input, temporary, output, input_rows, input_columns,\n                         scheduler);\n              const auto current_duration =\n                  std::chrono::high_resolution_clock::now() - start;\n              if (current_duration < best_duration) {\n                  best_duration = current_duration;\n                  best_batch_size = batch_size_;\n              }\n          }\n      };\n      batch_size_ = 1;\n      while (batch_size_ < cells) {\n          test_and_maybe_set();\n          batch_size_ = batch_size_ * 2;\n      }\n      batch_size_ = cells;\n      test_and_maybe_set();\n      batch_size_ = cells / scheduler.number_of_workers() +\n                    cells % scheduler.number_of_workers() ? 1 : 0;\n      while (batch_size_ > 1) {\n          test_and_maybe_set();\n          batch_size_ = batch_size_ / 2;\n      }\n      batch_size_ = best_batch_size;\n  }\n\n private:\n  static constexpr std::size_t cell_size =\n     components::value * kernel::rows * kernel::columns;\n  using alignment_t = alignment<type_t>;\n  using matrix_input_t = Eigen::Map<\n     Eigen::Matrix<type_t, components::value, kernel::columns * kernel::rows>,\n     alignment_t::eigen_alignment>;\n  using matrix_output_t = Eigen::Map<\n     Eigen::Matrix<type_t, components::value, 1>>;\n  using matrix_coefficients_t = Eigen::Map<\n     const Eigen::Matrix<type_t, kernel::columns * kernel::rows,\n                         components::value, Eigen::RowMajor>,\n     alignment_t::eigen_alignment>;\n  matrix_coefficients_t coeff_;\n  std::size_t batch_size_;\n};\n}\n}\n}\n\n#endif  // POLIMIDL_LAYERS_INTERNAL_DEPTHWISE_CONVOLUTION_HPP\n", "meta": {"hexsha": "5e2b5bcb9475bf2a5498917cc39c40a832a7afe6", "size": 8194, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/polimidl/layers/internal/depthwise_convolution.hpp", "max_stars_repo_name": "B3rn475/polimidl", "max_stars_repo_head_hexsha": "133858c883d0b2ddc84e0471bcfebb712beea3d8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-04-12T17:15:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T02:53:12.000Z", "max_issues_repo_path": "include/polimidl/layers/internal/depthwise_convolution.hpp", "max_issues_repo_name": "B3rn475/polimidl", "max_issues_repo_head_hexsha": "133858c883d0b2ddc84e0471bcfebb712beea3d8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-06-25T15:28:13.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-26T06:56:47.000Z", "max_forks_repo_path": "include/polimidl/layers/internal/depthwise_convolution.hpp", "max_forks_repo_name": "B3rn475/polimidl", "max_forks_repo_head_hexsha": "133858c883d0b2ddc84e0471bcfebb712beea3d8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-01-21T18:52:20.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-30T14:01:43.000Z", "avg_line_length": 41.5939086294, "max_line_length": 80, "alphanum_fraction": 0.5763973639, "num_tokens": 1726, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4609014209445247}}
{"text": "//  (C) Copyright Jeremy Siek 2002.\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#include <boost/pending/disjoint_sets.hpp>\n#include <boost/test/minimal.hpp>\n#include <boost/cstdlib.hpp>\n\ntemplate <typename DisjointSet>\nstruct test_disjoint_set {\n  static void do_test()\n  {\n    // The following tests are pretty lame, just a basic sanity check.\n    // Industrial strength tests still need to be written.\n    \n#if !defined(__MWERKS__) || __MWERKS__ > 0x3003\n    std::size_t elts[]\n#else\n    std::size_t elts[4]\n#endif \n        = { 0, 1, 2, 3 };\n    \n    const int N = sizeof(elts)/sizeof(*elts);\n    \n    DisjointSet ds(N);\n\n    ds.make_set(elts[0]);\n    ds.make_set(elts[1]);\n    ds.make_set(elts[2]);\n    ds.make_set(elts[3]);\n\n    BOOST_CHECK(ds.find_set(0) != ds.find_set(1));\n    BOOST_CHECK(ds.find_set(0) != ds.find_set(2));\n    BOOST_CHECK(ds.find_set(0) != ds.find_set(3));\n    BOOST_CHECK(ds.find_set(1) != ds.find_set(2));\n    BOOST_CHECK(ds.find_set(1) != ds.find_set(3));\n    BOOST_CHECK(ds.find_set(2) != ds.find_set(3));\n\n\n    ds.union_set(0, 1);\n    ds.union_set(2, 3);\n    BOOST_CHECK(ds.find_set(0) != ds.find_set(3));\n    int a = ds.find_set(0);\n    BOOST_CHECK(a == ds.find_set(1));\n    int b = ds.find_set(2);\n    BOOST_CHECK(b == ds.find_set(3));\n\n    ds.link(a, b);\n    BOOST_CHECK(ds.find_set(a) == ds.find_set(b));\n    BOOST_CHECK(1 == ds.count_sets(elts, elts + N));\n\n    ds.normalize_sets(elts, elts + N);\n    ds.compress_sets(elts, elts + N);\n    BOOST_CHECK(1 == ds.count_sets(elts, elts + N));\n  }\n};\n\nint\ntest_main(int, char*[])\n{\n  using namespace boost;\n  {\n    typedef \n      disjoint_sets_with_storage<identity_property_map, identity_property_map,\n      find_with_path_halving> ds_type;\n    test_disjoint_set<ds_type>::do_test();\n  }\n  {\n    typedef \n      disjoint_sets_with_storage<identity_property_map, identity_property_map,\n      find_with_full_path_compression> ds_type;\n    test_disjoint_set<ds_type>::do_test();\n  }\n  return boost::exit_success;\n}\n", "meta": {"hexsha": "cd588396d17cad06a2f084c4f4fa479a06babe08", "size": 2104, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/disjoint_sets/disjoint_set_test.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "boost/libs/disjoint_sets/disjoint_set_test.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "boost/libs/disjoint_sets/disjoint_set_test.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 27.3246753247, "max_line_length": 78, "alphanum_fraction": 0.6620722433, "num_tokens": 611, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.4608941096401568}}
{"text": "#include <cxxtest/TestDrive.h>\n\n#include <Eigen_openma/Utils/sign.h>\n\nCXXTEST_SUITE(SignTest)\n{\n  CXXTEST_TEST(positive)\n  {\n    TS_ASSERT_EQUALS(sign(1292) > 0, true);\n    TS_ASSERT_EQUALS(sign(9999) > 0, true);\n    TS_ASSERT_EQUALS(sign(1) > 0, true);\n  };\n  \n  CXXTEST_TEST(negative)\n  {\n    TS_ASSERT_EQUALS(sign(-11) < 0, true);\n    TS_ASSERT_EQUALS(sign(-5000) < 0, true);\n    TS_ASSERT_EQUALS(sign(-1) < 0, true);\n  };\n  \n  CXXTEST_TEST(null)\n  {\n    TS_ASSERT_EQUALS(sign(+0) == 0, true);\n    TS_ASSERT_EQUALS(sign(-0) == 0, true);\n    TS_ASSERT_EQUALS(sign(0) == 0, true);\n  };\n};\n\nCXXTEST_SUITE_REGISTRATION(SignTest)\nCXXTEST_TEST_REGISTRATION(SignTest, positive)\nCXXTEST_TEST_REGISTRATION(SignTest, negative)\nCXXTEST_TEST_REGISTRATION(SignTest, null)\n", "meta": {"hexsha": "4c77b4642b45cbc045a61b46666e3907b1ab53c3", "size": 762, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdparty/eigen3/test/signTest.cpp", "max_stars_repo_name": "OpenMA/openma", "max_stars_repo_head_hexsha": "6f3b55292fd0a862b3444f11d71d0562cfe81ac1", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 41.0, "max_stars_repo_stars_event_min_datetime": "2016-06-28T13:51:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T16:33:00.000Z", "max_issues_repo_path": "3rdparty/eigen3/test/signTest.cpp", "max_issues_repo_name": "bmswgnp/openma", "max_issues_repo_head_hexsha": "6f3b55292fd0a862b3444f11d71d0562cfe81ac1", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 82.0, "max_issues_repo_issues_event_min_datetime": "2016-04-09T15:19:31.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-15T18:56:12.000Z", "max_forks_repo_path": "3rdparty/eigen3/test/signTest.cpp", "max_forks_repo_name": "bmswgnp/openma", "max_forks_repo_head_hexsha": "6f3b55292fd0a862b3444f11d71d0562cfe81ac1", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2016-03-29T14:28:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-29T07:39:19.000Z", "avg_line_length": 23.0909090909, "max_line_length": 45, "alphanum_fraction": 0.6916010499, "num_tokens": 240, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251201477016, "lm_q2_score": 0.7154239897159438, "lm_q1q2_score": 0.4608941057313019}}
{"text": "\n// Original work Copyright (c) 2017, University of Minnesota\n// Modified work Copyright 2020, Yue Peng\n//\n// ADMM-Elastic Uses the BSD 2-Clause License (http://www.opensource.org/licenses/BSD-2-Clause)\n// Redistribution and use in source and binary forms, with or without modification, are\n// permitted provided that the following conditions are met:\n// 1. Redistributions of source code must retain the above copyright notice, this list of\n//    conditions and the following disclaimer.\n// 2. Redistributions in binary form must reproduce the above copyright notice, this list\n//    of conditions and the following disclaimer in the documentation and/or other materials\n//    provided with the distribution.\n// THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR  A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL THE UNIVERSITY OF MINNESOTA, DULUTH OR CONTRIBUTORS BE\n// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,\n// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER\n// IN CONTRACT, STRICT 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 SUCH DAMAGE.\n#ifndef ADMM_FORCE_H\n#define ADMM_FORCE_H 1\n\n#include <Eigen/Sparse>\n#include <Eigen/Dense>\n#include <memory>\n#include <iostream>\n\nnamespace admm {\n\n\n//\n//\tLame constants\n//\nclass Lame {\npublic:\n    static Lame rubber(){ return Lame(10000000,0.499); } // true rubber\n    static Lame soft_rubber(){ return Lame(10000000,0.399); } // fun rubber!\n    static Lame very_soft_rubber(){ return Lame(1000000,0.299); } // more funner!\n\n    long double mu, lambda;\n    long double bulk_modulus() const { return lambda + (2.0/3.0)*mu; }\n\n    // Hard strain limiting (e.g. [0.95,1.05]), default no limit\n    // with  min: -inf to 1, max: 1 to inf.\n    // In practice if max>99 it's basically no limiting.\n    long double limit_min, limit_max;\n\n    // k: Youngs (Pa), measure of stretch\n    // v: Poisson, measure of incompressibility\n    Lame( long double k, long double v ) :\n        mu(k/(2.0*(1.0+v))),\n        lambda(k*v/((1.0+v)*(1.0-2.0*v))),\n        limit_min(-100.0),\n        limit_max(100.0) {\n    }\n\n    // Use custom mu, lambda\n    Lame(): limit_min(-100.0),\n        limit_max(100.0) {}\n};\n\n\n//\n//\tBase class tets: Linear (non-corotated) elastic\n//\nclass EnergyTerm {\nprivate:\n    typedef Eigen::Matrix<double,Eigen::Dynamic,1> VecX;\n    typedef Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> MatX;\n    typedef Eigen::SparseMatrix<double,Eigen::RowMajor> SparseMat;\n    int g_index; // global idx (starting row of reduction matrix)\n\npublic:\n\n    virtual ~EnergyTerm() {}\n\n    // Called by the solver to create the global reduction and weight matrices\n    inline void get_reduction( std::vector< Eigen::Triplet<double> > &triplets, std::vector<double> &weights );\n\n    // Called by the solver for a local step update\n    //inline void update( const SparseMat &D, const VecX &x, VecX &z, VecX &u );\n\n    // Called by the solver for a local step update\n    inline void update_z(const SparseMat &D, const SparseMat &W_inv, const SparseMat &W, const VecX &x, VecX &z, const VecX &u , const VecX &c);\n\n    // Called by the solver for DR update\n    inline void update_DR_z(const SparseMat &W_inv, const SparseMat &W, VecX &z,\n                                         const VecX &s, const VecX &u, const VecX &c );\n\n    inline void update_DR_xzu_z(const SparseMat &W_inv, const SparseMat &W, VecX &z,\n                                         const VecX &s);\n\n    // Called by the solver for a local step update\n    inline void update_u(const SparseMat &D, const SparseMat &W, const VecX &x, const VecX &z, VecX &u , const VecX &c);\n\n    // Computes energy of the force (used for debugging)\n    inline double energy( const SparseMat &D, const VecX &x );\n\n    inline double get_all_energy(const VecX &x );\n    // Compute energy and gradient for a first-order opt. solver\n//\tinline double gradient( const SparseMat &D, const VecX &x, VecX &grad );\n    inline void gradient( const SparseMat &D, const VecX &x, VecX &grad );\n\n    inline void get_all_gradient(const VecX &z, VecX &grad );\n\n    inline void compute_x_gradient(const VecX &grad, VecX &all_grad );\n\n    // Dimension of deformation gradient.\n    virtual int get_dim() const = 0;\n\n    // Return the scalar weight of the energy term\n    virtual double get_weight() const = 0;\n\n    virtual double get_volume() const = 0;\n\nprotected:\n\n    virtual void get_gradient_for_vertices( const VecX &grad, VecX &all_grad) = 0;\n\n    // Get a local reduction matrix\n    virtual void get_reduction( std::vector< Eigen::Triplet<double> > &triplets ) = 0;\n\n    // Proximal update\n    virtual void prox( const MatX &W, VecX &zi, const VecX &vi) = 0;\n\n    // Returns energy of the force\n    virtual double energy( const VecX &F ) = 0;\n\n    virtual double energyLBFGS( const VecX &F ) = 0;\n\n    // Computes a first-order update (energy and gradient)\n    virtual void gradient(const VecX &x, VecX &grad) = 0;\n\n    virtual void get_gradient( const VecX &F, VecX &grad ) = 0;\n\n}; // end class EnergyTerm\n\n//\n//  Implementation\n//\n\ninline void EnergyTerm::get_reduction( std::vector< Eigen::Triplet<double> > &triplets, std::vector<double> &weights ){\n    std::vector< Eigen::Triplet<double> > temp_triplets;\n\n    get_reduction( temp_triplets );\n    int n_trips = temp_triplets.size();\n    g_index = weights.size();\n\n    for( int i=0; i<n_trips; ++i ){\n        const Eigen::Triplet<double> &trip = temp_triplets[i];\n        triplets.emplace_back( trip.row()+g_index, trip.col(), trip.value() );\n    }\n\n    int dim = get_dim();\n    double w = get_weight();\n    if( w <= 0.0 ){\n        throw std::runtime_error(\"**EnergyTerm::get_reduction Error: Some weight leq 0\");\n    }\n    for( int i=0; i<dim; ++i ){ weights.emplace_back( w ); }\n}\n\ninline void EnergyTerm::update_u( const SparseMat &D, const SparseMat &W, const VecX &x, const VecX &z, VecX &u, const VecX &c ){\n    int dof = x.rows();\n    int dim = get_dim();\n    VecX Dix = D.block(g_index,0,dim,dof)*x;\n    VecX ui = u.segment(g_index,dim);\n//    VecX zi = W.block(g_index,g_index,dim,dim) * z.segment(g_index,dim);\n    VecX zi = z.segment(g_index,dim);\n    VecX ci = c.segment(g_index,dim);\n    ui += (Dix - zi - ci);\n    u.segment(g_index,dim) = ui;\n}\n\ninline void EnergyTerm::update_z( const SparseMat &D, const SparseMat &W_inv, const SparseMat &W, const VecX &x, VecX &z, const VecX &u, const VecX &c ){\n    int dof = x.rows();\n    const int dim = get_dim();\n    VecX Dix = D.block(g_index,0,dim,dof)*x;\n    VecX ui = u.segment(g_index,dim);\n    VecX ci = c.segment(g_index,dim);\n    VecX vi = Dix + ui - ci;\n//    VecX zi = W_inv.block(g_index,g_index,dim,dim) * vi;\n//    vi = zi;\n    VecX zi = vi;\n    Eigen::Matrix<double,9,9> Wi = W.block(g_index,g_index,dim,dim);\n    prox(Wi, zi, vi);\n    z.segment(g_index,dim) = zi;\n}\n\ninline void EnergyTerm::update_DR_z( const SparseMat &W_inv, const SparseMat &W, VecX &z,\n                                     const VecX &s, const VecX &u, const VecX &c ){\n    const int dim = get_dim();\n    VecX ui = u.segment(g_index,dim);\n    VecX ci = c.segment(g_index,dim);\n    VecX si = s.segment(g_index,dim);\n    VecX vi = 2*ui - si - ci;\n//    VecX zi = W_inv.block(g_index,g_index,dim,dim) * vi;\n//    vi = zi;\n    VecX zi = vi;\n    Eigen::Matrix<double,9,9> Wi = W.block(g_index,g_index,dim,dim);\n    prox(Wi, zi, vi);\n    z.segment(g_index,dim) = zi;\n}\n\ninline void EnergyTerm::update_DR_xzu_z( const SparseMat &W_inv, const SparseMat &W, VecX &z,\n                                     const VecX &s){\n    const int dim = get_dim();\n    VecX si = s.segment(g_index,dim);\n//    VecX zi = W_inv.block(g_index,g_index,dim,dim) * si;\n//    si = zi;\n    VecX zi = si;\n\n    Eigen::Matrix<double,9,9> Wi = W.block(g_index,g_index,dim,dim);\n    prox(Wi, zi, si);\n    z.segment(g_index,dim) = zi;\n}\n\ninline double EnergyTerm::energy( const SparseMat &D, const VecX &x ){\n    (void)(D);\n    int dim = get_dim();\n    VecX Dix = x.segment(g_index,dim);\n    return energy( Dix );\n}\n\ninline double EnergyTerm::get_all_energy( const VecX &x ){\n    int dim = get_dim();\n    VecX Dix = x.segment(g_index,dim);\n    return energyLBFGS( Dix );\n}\n\ninline void EnergyTerm::gradient( const SparseMat &D, const VecX &x, VecX &grad ){\n    int dof = x.rows();\n    int dim = get_dim();\n    VecX Dix = D.block(g_index,0,dim,dof)*x;\n    gradient( Dix, grad );\n}\n\ninline void EnergyTerm::get_all_gradient( const VecX &z, VecX &grad ){\n    int dim = get_dim();\n    VecX zi = z.segment(g_index,dim);\n    VecX grad_z = grad.segment(g_index,dim);\n    get_gradient( zi, grad_z );\n    grad.segment(g_index,dim) = grad_z;\n}\n\ninline void EnergyTerm::compute_x_gradient(const VecX &grad, VecX &all_grad ){\n    int dim = get_dim();\n    VecX gi = grad.segment(g_index,dim);\n    get_gradient_for_vertices(gi, all_grad);\n}\n} // end namespace admm\n\n#endif\n\n\n\n\n", "meta": {"hexsha": "b1acf99ecd73a9bb62a21c2fbfff7f33d385eb53", "size": 9210, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Fig2-simulation/src/EnergyTerm.hpp", "max_stars_repo_name": "YuePengUSTC/AADR", "max_stars_repo_head_hexsha": "ed19730fc56f5d019089dbfd7544eeb35ba9c9a2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2020-07-01T09:30:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-18T04:19:50.000Z", "max_issues_repo_path": "Fig2-simulation/src/EnergyTerm.hpp", "max_issues_repo_name": "YuePengUSTC/AADR", "max_issues_repo_head_hexsha": "ed19730fc56f5d019089dbfd7544eeb35ba9c9a2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Fig2-simulation/src/EnergyTerm.hpp", "max_forks_repo_name": "YuePengUSTC/AADR", "max_forks_repo_head_hexsha": "ed19730fc56f5d019089dbfd7544eeb35ba9c9a2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-19T03:09:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-19T03:09:38.000Z", "avg_line_length": 35.6976744186, "max_line_length": 153, "alphanum_fraction": 0.6599348534, "num_tokens": 2530, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239836484144, "lm_q2_score": 0.6442251201477015, "lm_q1q2_score": 0.460894101822447}}
{"text": "//\n// Created by Alex Beccaro on 18/01/18.\n//\n\n#define BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n#include \"../../src/problems/1-50/35/problem35.hpp\"\n\nBOOST_AUTO_TEST_SUITE( Problem35 )\n\n    BOOST_AUTO_TEST_CASE( Example ) {\n        auto res = problems::problem35::solve(100);\n        BOOST_CHECK_EQUAL(res, 13);\n    }\n\n    BOOST_AUTO_TEST_CASE( Solution ) {\n        auto res = problems::problem35::solve();\n        BOOST_CHECK_EQUAL(res, 55);\n    }\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "2a9d49031b5152db628875a5da3a66b13b99acf1", "size": 491, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/1-50/test_problem35.cpp", "max_stars_repo_name": "abeccaro/project-euler", "max_stars_repo_head_hexsha": "c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T10:17:15.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-25T10:17:15.000Z", "max_issues_repo_path": "tests/1-50/test_problem35.cpp", "max_issues_repo_name": "abeccaro/project-euler", "max_issues_repo_head_hexsha": "c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3", "max_issues_repo_licenses": ["MIT"], "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/1-50/test_problem35.cpp", "max_forks_repo_name": "abeccaro/project-euler", "max_forks_repo_head_hexsha": "c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3", "max_forks_repo_licenses": ["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.380952381, "max_line_length": 51, "alphanum_fraction": 0.6741344196, "num_tokens": 124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.4608940959576574}}
{"text": "#ifndef _TRIFORCE_MESH_GEN_H_\n#define _TRIFORCE_MESH_GEN_H_\n#include <array>\n#include <map>\n#include <vector>\n#include <string>\n#include <fstream>\n#include <Eigen/Dense>\n#include \"compat.h\"\ntemplate <typename Scalar>\nclass TriforceMeshFactory{\n    public:\n        typedef mtao::compat::array<int, 3> Face;\n        typedef mtao::compat::array<int, 2> Edge;\n        typedef Scalar Scalar;\n        typedef typename Eigen::Matrix<Scalar,3,1> Vector;\n        using VecVector = mtao::vector<Vector>;\n        TriforceMeshFactory(int depth=3);\n        void triforce(const Face & f, int depth);\n        int add_edge(Edge e);\n        void write(const std::string & filename);\n        void write(std::ostream & outstream);\n        const std::vector<Face> faces() const {return m_faces;}\n        const VecVector vertices() const {return m_vertices;}\n\n    private:\n        const int m_depth = 0;\n        VecVector m_vertices;\n        std::vector<Face> m_faces;\n        mtao::IndexMap<2> m_edges;\n        //std::map<Edge,  int> m_edges;\n\n};\n\n\n\ntemplate <typename T>\nTriforceMeshFactory<T>::TriforceMeshFactory(int depth): m_depth(depth) {\n}\ntemplate <typename T>\nvoid TriforceMeshFactory<T>::run_in_place(VecVector& vertices, std::vector<Face>& faces) {\n    //Create icosahedron base\n\n    Scalar gr = .5 * (1 + std::sqrt(Scalar(5)));\n    m_vertices.resize(5);\n\n    m_vertices[ 0] = Vector(     0,    - 1,      0);\n    m_vertices[ 1] = Vector(     0,      1,      0);\n    m_vertices[ 2] = Vector(   - 1,      0,      0);\n    m_vertices[ 3] = Vector(     1,      0,      0);\n    m_vertices[ 4] = Vector(     0,      0,      1);\n\n    triforce({{ 0, 1, 4}},depth);\n    triforce({{ 1, 2, 4}},depth);\n    triforce({{ 2, 3, 4}},depth);\n    triforce({{ 3, 0, 4}},depth);\n\n\n\n\n}\ntemplate <typename T>\nvoid TriforceMeshFactory<T>::triforce(const Face & f, int depth) {\n    if(depth <= 0) {\n        m_faces.push_back(f);\n    } else {\n        int e01 = add_edge({{f[0],f[1]}});\n        int e12 = add_edge({{f[1],f[2]}});\n        int e02 = add_edge({{f[0],f[2]}});\n        triforce({{f[0],e01,e02}},depth-1);\n        triforce({{f[1],e12,e01}},depth-1);\n        triforce({{f[2],e02,e12}},depth-1);\n        triforce({{e01 ,e12,e02}},depth-1);\n    }\n\n}\n\ntemplate <typename T>\nint TriforceMeshFactory<T>::add_edge(Edge e) {\n    if(e[0] > e[1]) {\n        int tmp = e[0];\n        e[0] = e[1];\n        e[1] = tmp;\n    }\n    auto it = m_edges.find(e);\n    if(it != m_edges.end()) {\n        return it->second;\n    } else {\n        m_edges[e] = m_vertices.size();\n        m_vertices.push_back(\n                (m_vertices[e[0]] + m_vertices[e[1]]).normalized()\n                );\n        return m_vertices.size()-1;\n    }\n\n\n}\n\n\ntemplate <typename T>\nvoid TriforceMeshFactory<T>::write(const std::string & filename) {\n    std::ofstream outstream(filename.c_str());\n    write(outstream);\n}\n\ntemplate <typename T>\nvoid TriforceMeshFactory<T>::write(std::ostream & outstream) {\n    outstream << \"#Icosahedral subdivision to depth \" << m_depth << std::endl;\n    for(auto&& v: m_vertices) {\n        outstream << \"v \" << v.transpose() << std::endl;\n    }\n\n    for(auto&& f: m_faces) {\n        outstream << \"f \" << f[0]+1 << \" \" << f[1]+1 << \" \" << f[2]+1 << std::endl;\n    }\n}\n#endif\n", "meta": {"hexsha": "108e2540221e0dda56abd7f38f2df23796e1623e", "size": 3239, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mtao/geometry/mesh/constructors/triforce_subdivision.hpp", "max_stars_repo_name": "mtao/core", "max_stars_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_stars_repo_licenses": ["MIT"], "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/mtao/geometry/mesh/constructors/triforce_subdivision.hpp", "max_issues_repo_name": "mtao/core", "max_issues_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-04-18T16:16:05.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-18T16:17:36.000Z", "max_forks_repo_path": "include/mtao/geometry/mesh/constructors/triforce_subdivision.hpp", "max_forks_repo_name": "mtao/core", "max_forks_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_forks_repo_licenses": ["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.4491525424, "max_line_length": 90, "alphanum_fraction": 0.5683853041, "num_tokens": 998, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239836484144, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.46089409204880255}}
{"text": "#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Surface_mesh.h>\n\n#include <CGAL/Polygon_mesh_processing/connected_components.h>\n#include <CGAL/Polygon_mesh_processing/IO/polygon_mesh_io.h>\n#include <CGAL/boost/graph/Face_filtered_graph.h>\n\n#include <boost/property_map/property_map.hpp>\n\n#include <iostream>\n#include <fstream>\n#include <map>\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel  Kernel;\ntypedef Kernel::Point_3                                      Point;\n\ntypedef CGAL::Surface_mesh<Point>                            Mesh;\ntypedef boost::graph_traits<Mesh>::face_descriptor           face_descriptor;\ntypedef boost::graph_traits<Mesh>::faces_size_type           faces_size_type;\n\ntypedef Mesh::Property_map<face_descriptor, faces_size_type> FCCmap;\ntypedef CGAL::Face_filtered_graph<Mesh>                      Filtered_graph;\n\nnamespace PMP = CGAL::Polygon_mesh_processing;\n\nint main(int argc, char* argv[])\n{\n  const std::string filename = (argc > 1) ? argv[1] : CGAL::data_file_path(\"meshes/blobby_3cc.off\");\n\n  Mesh mesh;\n  if(!PMP::IO::read_polygon_mesh(filename, mesh))\n  {\n    std::cerr << \"Invalid input.\" << std::endl;\n    return 1;\n  }\n\n  FCCmap fccmap = mesh.add_property_map<face_descriptor, faces_size_type>(\"f:CC\").first;\n  faces_size_type num = PMP::connected_components(mesh,fccmap);\n  std::cerr << \"- The graph has \" << num << \" connected components (face connectivity)\" << std::endl;\n\n  std::cout << \"The faces in component 0 are:\" << std::endl;\n  Filtered_graph ffg(mesh, 0, fccmap);\n  for(boost::graph_traits<Filtered_graph>::face_descriptor f : faces(ffg))\n    std::cout << f << std::endl;\n\n  if(num > 1)\n  {\n    std::vector<faces_size_type> components;\n    components.push_back(0);\n    components.push_back(1);\n\n    std::cout << \"The faces in components 0 and 1 are:\" << std::endl;\n    ffg.set_selected_faces(components, fccmap);\n    for(Filtered_graph::face_descriptor f : faces(ffg))\n      std::cout  << f << std::endl;\n  }\n\n  return 0;\n}\n\n", "meta": {"hexsha": "c8cfad134496acc58a15b4a45443419763b11098", "size": 2019, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Polygon_mesh_processing/examples/Polygon_mesh_processing/face_filtered_graph_example.cpp", "max_stars_repo_name": "ffteja/cgal", "max_stars_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 3227.0, "max_stars_repo_stars_event_min_datetime": "2015-03-05T00:19:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:20:35.000Z", "max_issues_repo_path": "Polygon_mesh_processing/examples/Polygon_mesh_processing/face_filtered_graph_example.cpp", "max_issues_repo_name": "ffteja/cgal", "max_issues_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 5574.0, "max_issues_repo_issues_event_min_datetime": "2015-03-05T00:01:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:08:11.000Z", "max_forks_repo_path": "Polygon_mesh_processing/examples/Polygon_mesh_processing/face_filtered_graph_example.cpp", "max_forks_repo_name": "ffteja/cgal", "max_forks_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1274.0, "max_forks_repo_forks_event_min_datetime": "2015-03-05T00:01:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:47:56.000Z", "avg_line_length": 33.0983606557, "max_line_length": 101, "alphanum_fraction": 0.6934125805, "num_tokens": 511, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239836484143, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.4608940920488025}}
{"text": "static bool eigen_did_assert = false;\n#define eigen_assert(X) if(!eigen_did_assert && !(X)){ std::cout << \"### Assertion raised in \" << __FILE__ << \":\" << __LINE__ << \":\\n\" #X << \"\\n### The following would happen without assertions:\\n\"; eigen_did_assert = true;}\n\n#include <iostream>\n#include <Eigen/Eigen>\n\n#ifndef M_PI\n#define M_PI 3.1415926535897932384626433832795\n#endif\n\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n// intentionally remove indentation of snippet\n{\nstruct pad {\n  Index size() const { return out_size; }\n  Index operator[] (Index i) const { return std::max<Index>(0,i-(out_size-in_size)); }\n  Index in_size, out_size;\n};\n\nMatrix3i A;\nA.reshaped() = VectorXi::LinSpaced(9,1,9);\ncout << \"Initial matrix A:\\n\" << A << \"\\n\\n\";\nMatrixXi B(5,5);\nB = A(pad{3,5}, pad{3,5});\ncout << \"A(pad{3,N}, pad{3,N}):\\n\" << B << \"\\n\\n\";\n\n}\n  return 0;\n}\n", "meta": {"hexsha": "bca2b5e904692091eda2797d0c1e50c6706a15d6", "size": 902, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "build/compiled_eigen/doc/snippets/compile_Slicing_custom_padding_cxx11.cpp", "max_stars_repo_name": "aminulce/soil_model_cpp", "max_stars_repo_head_hexsha": "027803c29cbf5bddd1222839ba73019876533f87", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "build/compiled_eigen/doc/snippets/compile_Slicing_custom_padding_cxx11.cpp", "max_issues_repo_name": "aminulce/soil_model_cpp", "max_issues_repo_head_hexsha": "027803c29cbf5bddd1222839ba73019876533f87", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "build/compiled_eigen/doc/snippets/compile_Slicing_custom_padding_cxx11.cpp", "max_forks_repo_name": "aminulce/soil_model_cpp", "max_forks_repo_head_hexsha": "027803c29cbf5bddd1222839ba73019876533f87", "max_forks_repo_licenses": ["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.0555555556, "max_line_length": 224, "alphanum_fraction": 0.6529933481, "num_tokens": 279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239836484143, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.4608940920488025}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// Unit Test\n\n// Copyright (c) 2015 Barend Gehrels, Amsterdam, the Netherlands.\n\n// This file was modified by Oracle on 2021.\n// Modifications copyright (c) 2021 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#include <cstddef>\n#include <string>\n\n#include <boost/geometry/algorithms/is_convex.hpp>\n\n#include <geometry_test_common.hpp>\n\n#include <boost/geometry/algorithms/correct.hpp>\n#include <boost/geometry/io/wkt/wkt.hpp>\n#include <boost/geometry/strategies/strategies.hpp>\n#include <boost/geometry/geometries/adapted/boost_variant.hpp>\n#include <boost/geometry/geometries/geometries.hpp>\n\n#include <boost/geometry/algorithms/is_valid.hpp>\n\n\ntemplate <typename Geometry>\nvoid test_one(std::string const& case_id, std::string const& wkt, bool expected)\n{\n    Geometry geometry;\n    bg::read_wkt(wkt, geometry);\n    bg::correct(geometry);\n\n    bool detected = bg::is_convex(geometry);\n    BOOST_CHECK_MESSAGE(detected == expected,\n        \"Not as expected, case: \" << case_id\n            << \" / expected: \" << expected\n            << \" / detected: \" << detected);\n}\n\n\ntemplate <typename P>\nvoid test_all()\n{\n    // rectangular, with concavity\n    std::string const concave1 = \"polygon((1 1, 1 4, 3 4, 3 3, 4 3, 4 4, 5 4, 5 1, 1 1))\";\n    std::string const triangle = \"polygon((1 1, 1 4, 5 1, 1 1))\";\n    std::string const rectangle_without_holes = \"polygon((1 1, 1 4, 4 4, 4 1, 1 1))\";\n    std::string const rectangle_with_holes = \"polygon((1 1, 1 4, 4 4, 4 1, 1 1),(2 2, 3 2, 3 3, 2 3, 2 2))\";\n\n    using box_t = bg::model::box<P>;\n    using ring_t = bg::model::ring<P>;\n    using polygon_t = bg::model::polygon<P>;\n    using mpolygon_t = bg::model::multi_polygon<polygon_t>;\n    using variant_t = boost::variant<polygon_t, mpolygon_t>;\n    using collection_t = bg::model::geometry_collection<variant_t>;\n\n    test_one<ring_t>(\"triangle\", triangle, true);\n    test_one<ring_t>(\"concave1\", concave1, false);\n    test_one<bg::model::ring<P, false, false> >(\"triangle\", triangle, true);\n    test_one<bg::model::ring<P, false, false> >(\"concave1\", concave1, false);\n\n    test_one<polygon_t>(\"triangle\", triangle, true);\n    test_one<polygon_t>(\"concave1\", concave1, false);\n    test_one<polygon_t>(\"rectangle_without_holes\", rectangle_without_holes, true);\n    test_one<polygon_t>(\"rectangle_with_holes\", rectangle_with_holes, false);\n\n    test_one<box_t>(\"box\", \"box(0 0,2 2)\", true);\n\n    test_one<mpolygon_t>(\"mpoly1\", \"multipolygon(((1 1, 1 4, 5 1, 1 1)))\", true);\n    test_one<mpolygon_t>(\"mpoly1\", \"multipolygon(((1 1, 1 4, 3 4, 3 3, 4 3, 4 4, 5 4, 5 1, 1 1)))\", false);\n    test_one<mpolygon_t>(\"mpoly2\", \"multipolygon(((1 1, 1 4, 5 1, 1 1)),((3 0, 3 1, 4 0, 3 0)))\", false);\n\n    test_one<variant_t>(\"variant1\", triangle, true);\n    test_one<variant_t>(\"variant2\", concave1, false);\n\n    std::string const pref = \"geometrycollection(\";\n    std::string const post = \")\";\n    test_one<collection_t>(\"collection1\", pref + triangle + post, true);\n    test_one<collection_t>(\"collection2\", pref + concave1 + post, false);\n    test_one<collection_t>(\"collection3\", pref + triangle + \", \" + concave1 + post, false);\n    test_one<collection_t>(\"collection4\", pref + triangle + \", polygon((3 0, 3 1, 4 0, 3 0))\" + post, false);\n}\n\n\nint test_main(int, char* [])\n{\n    test_all<bg::model::d2::point_xy<int> >();\n    test_all<bg::model::d2::point_xy<double> >();\n\n    return 0;\n}\n", "meta": {"hexsha": "7f0951e633d38afecc640236a1d176ce81adedb2", "size": 3672, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "console/src/boost_1_78_0/libs/geometry/test/algorithms/is_convex.cpp", "max_stars_repo_name": "vany152/FilesHash", "max_stars_repo_head_hexsha": "39f282807b7f1abc56dac389e8259ee3bb557a8d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 326.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T13:47:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T02:13:59.000Z", "max_issues_repo_path": "console/src/boost_1_78_0/libs/geometry/test/algorithms/is_convex.cpp", "max_issues_repo_name": "vany152/FilesHash", "max_issues_repo_head_hexsha": "39f282807b7f1abc56dac389e8259ee3bb557a8d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 623.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T23:45:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T11:15:23.000Z", "max_forks_repo_path": "console/src/boost_1_78_0/libs/geometry/test/algorithms/is_convex.cpp", "max_forks_repo_name": "vany152/FilesHash", "max_forks_repo_head_hexsha": "39f282807b7f1abc56dac389e8259ee3bb557a8d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-01-14T15:50:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T03:58:36.000Z", "avg_line_length": 38.25, "max_line_length": 109, "alphanum_fraction": 0.6723856209, "num_tokens": 1156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834734, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.46089409009286736}}
{"text": "//          Copyright Carl Philipp Reh 2009 - 2016.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n\n#include <fcppt/cast/size.hpp>\n#include <fcppt/container/grid/apply.hpp>\n#include <fcppt/container/grid/object.hpp>\n#include <fcppt/math/at_c.hpp>\n#include <fcppt/math/dim/comparison.hpp>\n#include <fcppt/math/dim/output.hpp>\n#include <fcppt/preprocessor/disable_gcc_warning.hpp>\n#include <fcppt/preprocessor/pop_warning.hpp>\n#include <fcppt/preprocessor/push_warning.hpp>\n#include <fcppt/config/external_begin.hpp>\n#include <boost/test/unit_test.hpp>\n#include <string>\n#include <fcppt/config/external_end.hpp>\n\n\nFCPPT_PP_PUSH_WARNING\nFCPPT_PP_DISABLE_GCC_WARNING(-Weffc++)\n\nBOOST_AUTO_TEST_CASE(\n\tcontainer_grid_apply\n)\n{\nFCPPT_PP_POP_WARNING\n\n\ttypedef\n\tfcppt::container::grid::object<\n\t\tstd::string,\n\t\t2\n\t>\n\tstring_grid;\n\n\ttypedef\n\tfcppt::container::grid::object<\n\t\tunsigned,\n\t\t2\n\t>\n\tuint_grid;\n\n\tuint_grid const grid1(\n\t\tuint_grid::dim{\n\t\t\t2u,\n\t\t\t3u\n\t\t},\n\t\t[](\n\t\t\tuint_grid::pos const _pos\n\t\t)\n\t\t{\n\t\t\treturn\n\t\t\t\tfcppt::cast::size<\n\t\t\t\t\tunsigned\n\t\t\t\t>(\n\t\t\t\t\tfcppt::math::at_c<\n\t\t\t\t\t\t0\n\t\t\t\t\t>(\n\t\t\t\t\t\t_pos\n\t\t\t\t\t)\n\t\t\t\t\t+\n\t\t\t\t\tfcppt::math::at_c<\n\t\t\t\t\t\t1\n\t\t\t\t\t>(\n\t\t\t\t\t\t_pos\n\t\t\t\t\t)\n\t\t\t\t);\n\t\t}\n\t);\n\n\tstring_grid const grid2(\n\t\tstring_grid::dim{\n\t\t\t2u,\n\t\t\t3u\n\t\t},\n\t\t[](\n\t\t\tstring_grid::pos const _pos\n\t\t)\n\t\t{\n\t\t\treturn\n\t\t\t\tstd::to_string(\n\t\t\t\t\tfcppt::math::at_c<\n\t\t\t\t\t\t0\n\t\t\t\t\t>(\n\t\t\t\t\t\t_pos\n\t\t\t\t\t)\n\t\t\t\t\t+\n\t\t\t\t\tfcppt::math::at_c<\n\t\t\t\t\t\t1\n\t\t\t\t\t>(\n\t\t\t\t\t\t_pos\n\t\t\t\t\t)\n\t\t\t\t);\n\t\t}\n\t);\n\n\tauto const function(\n\t\t[](\n\t\t\tunsigned const _value1,\n\t\t\tstd::string const &_value2\n\t\t)\n\t\t{\n\t\t\treturn\n\t\t\t\tstd::to_string(\n\t\t\t\t\t_value1\n\t\t\t\t)\n\t\t\t\t+\n\t\t\t\t_value2\n\t\t\t\t;\n\t\t}\n\t);\n\n\tstring_grid const result(\n\t\tfcppt::container::grid::apply(\n\t\t\tfunction,\n\t\t\tgrid1,\n\t\t\tgrid2\n\t\t)\n\t);\n\n\tBOOST_REQUIRE_EQUAL(\n\t\tgrid1.size(),\n\t\tresult.size()\n\t);\n\n\tBOOST_CHECK_EQUAL(\n\t\tresult[\n\t\t\tstring_grid::pos(\n\t\t\t\t0u,\n\t\t\t\t0u\n\t\t\t)\n\t\t],\n\t\tstd::string(\n\t\t\t\"00\"\n\t\t)\n\t);\n\n\tBOOST_CHECK_EQUAL(\n\t\tresult[\n\t\t\tstring_grid::pos(\n\t\t\t\t1u,\n\t\t\t\t2u\n\t\t\t)\n\t\t],\n\t\tstd::string(\n\t\t\t\"33\"\n\t\t)\n\t);\n\n\n\tBOOST_REQUIRE_EQUAL(\n\t\tfcppt::container::grid::apply(\n\t\t\tfunction,\n\t\t\tgrid1,\n\t\t\tstring_grid()\n\t\t).size(),\n\t\tstring_grid::dim(\n\t\t\t0u,\n\t\t\t0u\n\t\t)\n\t);\n}\n", "meta": {"hexsha": "a319ea054dec8e9a30e54262211236ff9b749ba3", "size": 2295, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/container/grid/apply.cpp", "max_stars_repo_name": "vinzenz/fcppt", "max_stars_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "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": "test/container/grid/apply.cpp", "max_issues_repo_name": "vinzenz/fcppt", "max_issues_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "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/container/grid/apply.cpp", "max_forks_repo_name": "vinzenz/fcppt", "max_forks_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "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": 13.9090909091, "max_line_length": 61, "alphanum_fraction": 0.6043572985, "num_tokens": 766, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6654105720171531, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.4608913024225364}}
{"text": "#include \"Object.h\"\n#include \"Ray.h\"\n#include \"Camera.h\"\n#include \"Sphere.h\"\n#include \"Plane.h\"\n#include \"read_json.h\"\n#include \"write_ppm.h\"\n#include \"viewing_ray.h\"\n#include \"first_hit.h\"\n#include <Eigen/Core>\n#include <vector>\n#include <iostream>\n#include <memory>\n#include <limits>\n#include <functional>\n\n\nint main(int argc, char * argv[])\n{\n  // list of colors used for per-object id coloring\n  const std::vector<unsigned char> color_map = {\n    228,26,28,\n    55,126,184,\n    77,175,74,\n    152,78,163,\n    255,127,0,\n    255,255,51,\n    166,86,40,\n    247,129,191,\n    153,153,153\n  };\n\n  Camera camera;\n  std::vector< std::shared_ptr<Object> > objects;\n  // Read a camera and scene description from given .json file\n  read_json(argc<=1?\"../data/sphere-and-plane.json\":argv[1],camera,objects);\n\n  int width = 640;\n  int height = 360;\n  std::vector<unsigned char> id_image(3*width*height);\n  std::vector<unsigned char> normal_image(3*width*height);\n  std::vector<unsigned char> depth_image(1*width*height);\n  // For each pixel (i,j)\n  for(unsigned i=0; i<height; ++i)\n  {\n    for(unsigned j=0; j<width; ++j)\n    {\n      // Set background color\n      normal_image[0+3*(j+width*i)] = 0;\n      normal_image[1+3*(j+width*i)] = 0;\n      normal_image[2+3*(j+width*i)] = 0;\n      depth_image[j+width*i] = 0;\n      id_image[0+3*(j+width*i)] = 0;\n      id_image[1+3*(j+width*i)] = 0;\n      id_image[2+3*(j+width*i)] = 0;\n\n      // Compute viewing ray\n      Ray ray;\n      viewing_ray(camera,i,j,width,height,ray);\n\n      // Find first visible object hit by ray and its surface normal n\n      double t;\n      Eigen::Vector3d n;\n      int hit_id;\n      if(first_hit(ray,1.0,objects,hit_id,t,n))\n      {\n        // object-id image\n        const int color_id = hit_id%(color_map.size()/3);\n        id_image[0+3*(j+width*i)] = color_map[0+3*color_id];\n        id_image[1+3*(j+width*i)] = color_map[1+3*color_id];\n        id_image[2+3*(j+width*i)] = color_map[2+3*color_id];\n\n        // depth image\n        const double zNear = camera.d;\n        double linearized_depth = zNear/(t*ray.direction.norm());\n        linearized_depth = linearized_depth<1?linearized_depth:1;\n        depth_image[j+width*i] = 255.0*(linearized_depth);\n\n        // set pixel color to value computed from hit point, light, and n\n        // normal image\n        auto normal_to_rgb = [](const Eigen::Vector3d & n, unsigned char & r, unsigned char & g, unsigned char & b)\n        {\n          r = 255.0*(n(0)*0.5+0.5);\n          g = 255.0*(n(1)*0.5+0.5);\n          b = 255.0*(n(2)*0.5+0.5);\n        };\n        normal_to_rgb(\n          n,\n          normal_image[0+3*(j+width*i)],\n          normal_image[1+3*(j+width*i)],\n          normal_image[2+3*(j+width*i)]);\n      }\n    }\n  }\n\n  write_ppm(\"normal.ppm\",normal_image,width,height,3);\n  write_ppm(\"depth.ppm\",depth_image,width,height,1);\n  write_ppm(\"id.ppm\",id_image,width,height,3);\n}\n", "meta": {"hexsha": "15c64fa9cb6f9f3cf3dbac5a969bdfe349b585c9", "size": 2900, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "ericpko/computer-graphics-ray-casting", "max_stars_repo_head_hexsha": "5aeeff4d7bebffe0c2844ccee72ebc6180c5f481", "max_stars_repo_licenses": ["MIT"], "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": "ericpko/computer-graphics-ray-casting", "max_issues_repo_head_hexsha": "5aeeff4d7bebffe0c2844ccee72ebc6180c5f481", "max_issues_repo_licenses": ["MIT"], "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": "ericpko/computer-graphics-ray-casting", "max_forks_repo_head_hexsha": "5aeeff4d7bebffe0c2844ccee72ebc6180c5f481", "max_forks_repo_licenses": ["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.0, "max_line_length": 115, "alphanum_fraction": 0.6037931034, "num_tokens": 907, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419958239132, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.46089130204849554}}
{"text": "/*-----------------------------------------------------------------------------+\nCopyright (c) 2008-2010: Joachim Faulhaber\n+------------------------------------------------------------------------------+\n   Distributed under the Boost Software License, Version 1.0.\n      (See accompanying file LICENCE.txt or copy at\n           http://www.boost.org/LICENSE_1_0.txt)\n+-----------------------------------------------------------------------------*/\n#ifndef LIBS_ICL_TEST_TEST_ICL_interval_shared_hpp_JOFA_100306__\n#define LIBS_ICL_TEST_TEST_ICL_interval_shared_hpp_JOFA_100306__\n\n#include <boost/icl/interval_set.hpp>\n\ntemplate <class DomainT, ICL_COMPARE Compare,\n          ICL_INTERVAL(ICL_COMPARE)  Interval>\nvoid test_inner_complement(const ICL_INTERVAL_TYPE(Interval,DomainT,Compare)& itv1,\n                           const ICL_INTERVAL_TYPE(Interval,DomainT,Compare)& itv2)\n{\n    typedef interval_set<DomainT,Compare,Interval> ItvSetT;\n    typedef ICL_INTERVAL_TYPE(Interval,DomainT,Compare) IntervalT;\n\n    BOOST_CHECK_EQUAL(icl::length(inner_complement(itv1,itv2)), icl::distance(itv1,itv2));\n    BOOST_CHECK_EQUAL(icl::length(inner_complement(itv1,itv2)), icl::distance(itv2,itv1));\n    BOOST_CHECK_EQUAL(icl::length(inner_complement(itv2,itv1)), icl::distance(itv1,itv2));\n    BOOST_CHECK_EQUAL(icl::length(inner_complement(itv2,itv1)), icl::distance(itv2,itv1));\n\n    IntervalT in_comp = inner_complement(itv1,itv2);\n    ItvSetT itvset, inner_comp;\n    itvset.add(itv1).add(itv2);\n    ItvSetT hullset = ItvSetT(hull(itvset));\n    inner_comp = hullset - itvset;\n    IntervalT inner_comp_itv;\n    if(inner_comp.begin() != inner_comp.end())\n        inner_comp_itv = *inner_comp.begin();\n\n    BOOST_CHECK_EQUAL(inner_complement(itv1,itv2), inner_comp_itv);\n    BOOST_CHECK_EQUAL(inner_complement(itv2,itv1), inner_comp_itv);\n    BOOST_CHECK_EQUAL(icl::length(inner_comp), icl::distance(itv1,itv2));\n    BOOST_CHECK_EQUAL(icl::length(inner_comp), icl::distance(itv2,itv1));\n\n    BOOST_CHECK(icl::disjoint(itv1, in_comp));\n    BOOST_CHECK(icl::disjoint(itv2, in_comp));\n\n    IntervalT itv1_comp = hull(itv1, in_comp);\n    IntervalT itv2_comp = hull(itv2, in_comp);\n\n    if(!icl::is_empty(in_comp))\n    {\n        BOOST_CHECK(icl::intersects(itv1_comp, in_comp));\n        BOOST_CHECK(icl::intersects(itv2_comp, in_comp));\n\n        BOOST_CHECK_EQUAL(itv1_comp & itv2_comp, in_comp);\n        BOOST_CHECK_EQUAL( icl::is_empty(itv1_comp & itv2_comp), icl::disjoint(itv1_comp, itv2_comp));\n        BOOST_CHECK_EQUAL(!icl::is_empty(itv1_comp & itv2_comp), icl::intersects(itv1_comp, itv2_comp));\n    }\n}\n\ntemplate <class IntervalT>\nvoid test_inner_complement_(const IntervalT& itv1, const IntervalT& itv2)\n{\n    typedef typename interval_traits<IntervalT>::domain_type DomainT;\n    // For the test of plain interval types we assume that std::less is\n    // the compare functor\n    test_inner_complement<DomainT, std::less, IntervalT>(itv1, itv2);\n}\n\n#ifndef BOOST_ICL_USE_STATIC_BOUNDED_INTERVALS\n\nvoid interval_ctor_specific()\n{\n    BOOST_CHECK_EQUAL(icl::length(icl::interval<double>::type()), 0.0);\n    BOOST_CHECK_EQUAL(icl::cardinality(icl::interval<double>::closed(5.0, 5.0)), 1);\n    BOOST_CHECK_EQUAL(icl::cardinality(icl::interval<std::string>::closed(\"test\", \"test\")), 1);\n    BOOST_CHECK_EQUAL(icl::cardinality(icl::interval<std::string>::closed(\"best\",\"test\")),\n                      icl::cardinality(icl::interval<double>::closed(0.0,0.1)));\n    BOOST_CHECK_EQUAL(icl::cardinality(icl::interval<std::string>::right_open(\"best\",\"test\")),\n                      icl::infinity<size_type_of<icl::interval<std::string>::type>::type >::value() );\n    BOOST_CHECK_EQUAL(icl::cardinality(icl::interval<double>::right_open(0.0, 1.0)),\n                      icl::infinity<size_type_of<icl::interval<double>::type>::type >::value() );\n}\n\n#endif // ndef BOOST_ICL_USE_STATIC_BOUNDED_INTERVALS\n\ntemplate <class T>\nvoid interval_equal_4_integral_types()\n{\n    typedef typename icl::interval<T>::type IntervalT;\n    T v2 = make<T>(2);\n    T v3 = make<T>(3);\n    T v7 = make<T>(7);\n    T v8 = make<T>(8);\n    BOOST_CHECK_EQUAL(IntervalT(), IntervalT(v7,v3));\n\n    //I: (I)nside  = closed bound\n    //C: left open bound\n    //D: right open bound\n    IntervalT  I3_7I  = icl::interval<T>::closed(v3,v7);\n    IntervalT  I3__8D = icl::interval<T>::right_open(v3,v8);\n    IntervalT C2__7I  = icl::interval<T>::left_open(v2,v7);\n    IntervalT C2___8D = icl::interval<T>::open(v2,v8);\n\n    BOOST_CHECK_EQUAL(  I3_7I ,  I3_7I  );\n    BOOST_CHECK_EQUAL(  I3_7I ,  I3__8D );\n    BOOST_CHECK_EQUAL(  I3_7I , C2__7I  );\n    BOOST_CHECK_EQUAL(  I3_7I , C2___8D );\n\n    BOOST_CHECK_EQUAL(  I3__8D,  I3__8D );\n    BOOST_CHECK_EQUAL(  I3__8D, C2__7I  );\n    BOOST_CHECK_EQUAL(  I3__8D, C2___8D );\n\n    BOOST_CHECK_EQUAL( C2__7I , C2__7I  );\n    BOOST_CHECK_EQUAL( C2__7I , C2___8D );\n\n    BOOST_CHECK_EQUAL( C2___8D, C2___8D );\n}\n\ntemplate <class T>\nvoid interval_less_4_integral_types()\n{\n    typedef typename icl::interval<T>::type IntervalT;\n    T v2 = make<T>(2);\n    T v3 = make<T>(3);\n    T v4 = make<T>(4);\n    T v7 = make<T>(7);\n    T v8 = make<T>(8);\n    BOOST_CHECK_EQUAL(IntervalT() < IntervalT(v7,v3), false);\n    BOOST_CHECK_EQUAL(icl::interval<T>::open(v2,v3) < icl::interval<T>::right_open(v7,v7), false);\n    BOOST_CHECK_EQUAL(icl::interval<T>::left_open(v3,v3) < icl::interval<T>::closed(v7,v3), false);\n\n    BOOST_CHECK_EQUAL(IntervalT() < IntervalT(v3,v4), true);\n    BOOST_CHECK_EQUAL(icl::interval<T>::open(v2,v3) < icl::interval<T>::right_open(v7,v8), true);\n\n    //I: (I)nside  = closed bound\n    //C: left open bound\n    //D: right open bound\n    IntervalT  I3_7I  = icl::interval<T>::closed(v3,v7);\n    IntervalT  I4_7I  = icl::interval<T>::closed(v4,v7);\n\n    IntervalT  I3__8D = icl::interval<T>::right_open(v3,v8);\n    IntervalT C2__7I  = icl::interval<T>::left_open(v2,v7);\n    IntervalT C2___8D = icl::interval<T>::open(v2,v8);\n\n    BOOST_CHECK_EQUAL(  I3_7I <  I3_7I  , false);\n    BOOST_CHECK_EQUAL(  I3_7I <  I3__8D , false);\n    BOOST_CHECK_EQUAL(  I3_7I < C2__7I  , false);\n    BOOST_CHECK_EQUAL(  I3_7I < C2___8D , false);\n\n    BOOST_CHECK_EQUAL(  I3_7I <  I4_7I  , true);\n\n\n    BOOST_CHECK_EQUAL(  I3__8D<  I3__8D , false);\n    BOOST_CHECK_EQUAL(  I3__8D< C2__7I  , false);\n    BOOST_CHECK_EQUAL(  I3__8D< C2___8D , false);\n\n    BOOST_CHECK_EQUAL( C2__7I < C2__7I  , false);\n    BOOST_CHECK_EQUAL( C2__7I < C2___8D , false);\n\n    BOOST_CHECK_EQUAL( C2___8D< C2___8D , false);\n}\n\ntemplate <class T>\nvoid interval_equal_4_bicremental_continuous_types()\n{\n    typedef typename icl::interval<T>::type IntervalT;\n    T v3 = make<T>(3);\n    T v7 = make<T>(7);\n    BOOST_CHECK_EQUAL(IntervalT(), IntervalT(v7,v3));\n\n    //I: (I)nside  = closed bound\n    //O: (O)utside = open bound\n    IntervalT I3_7I = icl::interval<T>::closed(v3,v7);\n    IntervalT I3_7D = icl::interval<T>::right_open(v3,v7);\n    IntervalT C3_7I = icl::interval<T>::left_open(v3,v7);\n    IntervalT C3_7D = icl::interval<T>::open(v3,v7);\n\n    BOOST_CHECK_EQUAL( I3_7I ,  I3_7I  );\n    BOOST_CHECK_EQUAL( I3_7I == I3_7D, false  );\n    BOOST_CHECK_EQUAL( I3_7I == C3_7D, false  );\n    BOOST_CHECK_EQUAL( I3_7I == C3_7D, false );\n    BOOST_CHECK_EQUAL( I3_7I != I3_7D, true  );\n    BOOST_CHECK_EQUAL( I3_7I != C3_7D, true  );\n    BOOST_CHECK_EQUAL( I3_7I != C3_7D, true );\n\n    BOOST_CHECK_EQUAL( I3_7D ,  I3_7D  );\n    BOOST_CHECK_EQUAL( I3_7D == C3_7I, false  );\n    BOOST_CHECK_EQUAL( I3_7D == C3_7D, false );\n    BOOST_CHECK_EQUAL( I3_7D != C3_7I, true  );\n    BOOST_CHECK_EQUAL( I3_7D != C3_7D, true );\n\n    BOOST_CHECK_EQUAL( C3_7I ,  C3_7I  );\n    BOOST_CHECK_EQUAL( C3_7I == C3_7D, false );\n    BOOST_CHECK_EQUAL( C3_7I != C3_7D, true );\n\n    BOOST_CHECK_EQUAL( C3_7D,   C3_7D  );\n}\n\ntemplate <class T>\nvoid interval_touches_4_bicremental_types()\n{\n    typedef typename icl::interval<T>::type IntervalT;\n    T v3 = make<T>(3);\n    T v7 = make<T>(7);\n    T v9 = make<T>(9);\n\n    IntervalT I3_7D = icl::interval<T>::right_open(v3,v7);\n    IntervalT I7_9I = icl::interval<T>::closed(v7,v9);\n    BOOST_CHECK_EQUAL( icl::touches(I3_7D, I7_9I), true );\n\n    IntervalT I3_7I = icl::interval<T>::closed(v3,v7);\n    IntervalT C7_9I = icl::interval<T>::left_open(v7,v9);\n    BOOST_CHECK_EQUAL( icl::touches(I3_7I, C7_9I), true );\n\n    BOOST_CHECK_EQUAL( icl::touches(I3_7D, C7_9I), false );\n    BOOST_CHECK_EQUAL( icl::touches(I3_7I, I7_9I), false );\n}\n\ntemplate <class T>\nvoid interval_touches_4_integral_types()\n{\n    typedef typename icl::interval<T>::type IntervalT;\n    T v3 = make<T>(3);\n    T v6 = make<T>(6);\n    T v7 = make<T>(7);\n    T v9 = make<T>(9);\n\n    IntervalT I3_6I = icl::interval<T>::closed(v3,v6);\n    IntervalT I7_9I = icl::interval<T>::closed(v7,v9);\n    BOOST_CHECK_EQUAL( icl::touches(I3_6I, I7_9I), true );\n\n    IntervalT I3_7D = icl::interval<T>::right_open(v3,v7);\n    IntervalT C6_9I = icl::interval<T>::left_open(v6,v9);\n    BOOST_CHECK_EQUAL( icl::touches(I3_7D, C6_9I), true );\n}\n\ntemplate <class T>\nvoid interval_infix_intersect_4_bicremental_types()\n{\n    typedef typename icl::interval<T>::type IntervalT;\n\n    IntervalT section;\n    IntervalT I3_7D = I_D(3,7);\n\n    IntervalT I0_3D = I_D(0,3);\n    section = I3_7D & I0_3D;\n    BOOST_CHECK_EQUAL( icl::disjoint(I0_3D, I3_7D), true );\n    BOOST_CHECK_EQUAL( icl::is_empty(section), true );\n    BOOST_CHECK_EQUAL( section, IntervalT() );\n\n    IntervalT I0_5D = I_D(0,5);\n    section = I3_7D & I0_5D;\n    BOOST_CHECK_EQUAL( section, I_D(3,5) );\n\n    IntervalT I0_9D = I_D(0,9);\n    section = I3_7D & I0_9D;\n    BOOST_CHECK_EQUAL( section, I3_7D );\n\n    IntervalT I4_5I = I_I(4,5);\n    section = I3_7D & I4_5I;\n    BOOST_CHECK_EQUAL( section, I4_5I );\n\n    IntervalT C4_6D = C_D(4,6);\n    section = I3_7D & C4_6D;\n    BOOST_CHECK_EQUAL( section, C4_6D );\n\n    IntervalT C4_9I = C_I(4,9);\n    section = I3_7D & C4_9I;\n    BOOST_CHECK_EQUAL( section, C_D(4,7) );\n\n    IntervalT I7_9I = I_I(7,9);\n    section = I3_7D & I7_9I;\n    BOOST_CHECK_EQUAL( icl::exclusive_less(I3_7D, I7_9I), true );\n    BOOST_CHECK_EQUAL( icl::disjoint(I3_7D, I7_9I), true );\n    BOOST_CHECK_EQUAL( icl::is_empty(section), true );\n}\n\ntemplate <class T>\nvoid interval_subtract_4_bicremental_types()\n{\n    typedef typename icl::interval<T>::type IntervalT;\n\n    IntervalT diff_1, diff_2;\n    IntervalT I0_3D = I_D(0,3);\n    IntervalT I2_6D = I_D(2,6);\n    IntervalT I4_7D = I_D(4,7);\n    IntervalT I6_7D = I_D(6,7);\n    IntervalT I2_4D = I_D(2,4);\n\n    diff_1 = right_subtract(I2_6D, I4_7D);\n    BOOST_CHECK_EQUAL( diff_1, I2_4D );\n\n    diff_1 = right_subtract(I0_3D, I4_7D);\n    BOOST_CHECK_EQUAL( diff_1, I0_3D );\n\n    // ---------------------------------\n    diff_1 = left_subtract(I4_7D, I2_6D);\n    BOOST_CHECK_EQUAL( diff_1, I6_7D );\n\n    diff_1 = left_subtract(I4_7D, I0_3D);\n    BOOST_CHECK_EQUAL( diff_1, I4_7D );\n}\n\n\n#endif // LIBS_ICL_TEST_TEST_ICL_interval_shared_hpp_JOFA_100306__\n", "meta": {"hexsha": "b6f82c879b7fa59d33fcf76d330cc68b05b16bf1", "size": 10917, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/libs/icl/test/test_icl_interval_shared.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/libs/icl/test/test_icl_interval_shared.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/libs/icl/test/test_icl_interval_shared.hpp", "max_forks_repo_name": "Bpowers4/turicreate", "max_forks_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 36.0297029703, "max_line_length": 104, "alphanum_fraction": 0.6619034533, "num_tokens": 3678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419958239132, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.46089129745269847}}
{"text": "//\n//  cnn.cpp\n//  Jacobian\n//\n//  Created by David Freifeld\n//\n\n#include \"bpnn.hpp\"\n#include \"utils.hpp\"\n\n//#include <Eigen/unsupported/CXX11/Tensor>\n#include \"cnn.hpp\"\n\n#define LARGE_NUM 1000000 // Remove me.\n\n#if (!RECKLESS)\n#define checknan(x, loc) if(x==INFINITY || x==NAN || x == -INFINITY) throw ValueError(\"Detected NaN in operation\", loc)\n#else\n#define checknan(x, loc)\n#endif\n\n// NOTE: Below three functions not mine, from https://compvisionlab.wordpress.com/2014/01/01/c-code-for-reading-mnist-data-set/\nint ReverseInt (int i)\n{\n    unsigned char ch1, ch2, ch3, ch4;\n    ch1=i&255;\n    ch2=(i>>8)&255;\n    ch3=(i>>16)&255;\n    ch4=(i>>24)&255;\n    return((int)ch1<<24)+((int)ch2<<16)+((int)ch3<<8)+ch4;\n}   \n\nvoid ReadMNIST(int NumberOfImages, int DataOfAnImage,std::vector<std::vector<double>> &arr)\n{\n    arr.resize(NumberOfImages,std::vector<double>(DataOfAnImage));\n    std::ifstream file (\"./t10k-images-idx3-ubyte\",std::ios::binary);\n    if (file.is_open())\n    {\n        int magic_number=0;\n        int number_of_images=0;\n        int n_rows=0;\n        int n_cols=0;\n        file.read((char*)&magic_number,sizeof(magic_number));\n        magic_number= ReverseInt(magic_number);\n        file.read((char*)&number_of_images,sizeof(number_of_images));\n        number_of_images= ReverseInt(number_of_images);\n        file.read((char*)&n_rows,sizeof(n_rows));\n        n_rows= ReverseInt(n_rows);\n        file.read((char*)&n_cols,sizeof(n_cols));\n        n_cols= ReverseInt(n_cols);\n        for(int i=0;i<number_of_images;++i)\n        {\n            for(int r=0;r<n_rows;++r)\n            {\n                for(int c=0;c<n_cols;++c)\n                {\n                    unsigned char temp=0;\n                    file.read((char*)&temp,sizeof(temp));\n                    arr[i][(n_rows*r)+c]= (double)temp;\n                }\n            }\n        }\n    }\n}\n\nunsigned char* read_mnist_labels(std::string full_path, int number_of_labels) {\n    auto reverseInt = [](int i) {\n        unsigned char c1, c2, c3, c4;\n        c1 = i & 255, c2 = (i >> 8) & 255, c3 = (i >> 16) & 255, c4 = (i >> 24) & 255;\n        return ((int)c1 << 24) + ((int)c2 << 16) + ((int)c3 << 8) + c4;\n    };\n\n    typedef unsigned char uchar;\n\n    std::ifstream file(full_path, std::ios::binary);\n\n    if(file.is_open()) {\n        int magic_number = 0;\n        file.read((char *)&magic_number, sizeof(magic_number));\n        magic_number = reverseInt(magic_number);\n\n        if(magic_number != 2049) throw std::runtime_error(\"Invalid MNIST label file!\");\n\n        file.read((char *)&number_of_labels, sizeof(number_of_labels)), number_of_labels = reverseInt(number_of_labels);\n\n        uchar* _dataset = new uchar[number_of_labels];\n        for(int i = 0; i < number_of_labels; i++) {\n            file.read((char*)&_dataset[i], 1);\n        }\n        return _dataset;\n    } else {\n        throw std::runtime_error(\"Unable to open file `\" + full_path + \"`!\");\n    }\n}\n\nConvLayer::ConvLayer(int x, int y, int stride, int kern_x, int kern_y, int pad, std::function<float(float)> activ, std::function<float(float)> activ_deriv)\n    :stride_len(stride), padding(pad), activation(activ), activation_deriv(activ_deriv)\n{\n    pad*=2;\n    input = new Eigen::MatrixXf (x+pad,y+pad);\n    dZ = new Eigen::MatrixXf (x+pad,y+pad);\n    for (int i = 0; i < (x+pad)*(y+pad); i++) {\n        (*input)((int)i / (y+pad),i%(y+pad)) = 0;\n        (*dZ)((int)i / (y+pad),i%(y+pad)) = 0;        \n    }\n    kernel = new Eigen::MatrixXf (kern_x, kern_y);\n    for (int i = 0; i < kern_x*kern_y; i++) {\n        (*kernel)((int)i / kern_y,i%kern_y) = (float) rand() / RAND_MAX;\n    }\n    output = new Eigen::MatrixXf ((x-kern_x+1+pad/stride_len), (y-kern_y+1+pad/stride_len));\n    for (int i = 0; i < (x-kern_y+1+pad/stride_len)*(y-kern_x+1+pad/stride_len); i++) {\n        (*output)((int)i / (y-kern_y+1+pad/stride_len),i%(y-kern_y+1+pad/stride_len)) = 0;\n    }\n    bias = 0;\n};\n\nvoid ConvLayer::convolute()\n{\n    for (int i = 0; i < (*input).rows(); i++) {\n        for (int j = 0; j < (*input).cols(); j++) {\n            (*dZ)(i, j) = activation_deriv((*input)(i, j));\n            (*input)(i, j) = activation((*input)(i, j));\n        }\n    }\n    for (int i = 0; i < output->rows(); i+=stride_len) {\n        for (int j = 0; j < output->cols(); j+=stride_len) {\n            (*output)(i, j) = (*kernel * (input->block(i, j, kernel->rows(), kernel->cols()))).sum();            \n        }\n    }\n    *output = (output->array() + bias).matrix();\n}\n\nvoid ConvLayer::set_input(Eigen::MatrixXf* matrix)\n{\n    input->block(padding, padding, matrix->rows(), matrix->cols()) = *matrix;\n}\n\n// Will eventually be different from ConvLayer\nPoolingLayer::PoolingLayer(int x, int y, int stride, int kern_x, int kern_y, int pad)\n    :stride_len(stride), padding(pad)\n{\n    input = new Eigen::MatrixXf (x+pad,y+pad);\n    for (int i = 0; i < (x+pad)*(y+pad); i++) {\n        (*input)((int)i / (y+pad),i%(y+pad)) = 0;\n    }\n    kernel = new Eigen::MatrixXf (kern_x, kern_y);\n    for (int i = 0; i < kern_x*kern_y; i++) {\n        (*kernel)((int)i / kern_y,i%kern_y) = (float) rand()/RAND_MAX;\n    }\n    output = new Eigen::MatrixXf (x-kern_x+1, y-kern_y+1);\n    for (int i = 0; i < (x-kern_x+1)*(y-kern_y+1); i++) {\n        (*output)((int)i / (y-kern_y+1),i%(y-kern_y+1)) = (float) rand()/RAND_MAX;\n    }\n};\n\nvoid PoolingLayer::pool()\n{\n  // It doesn't look like anything better than O(n^4) is doable for this as kernel needs to go through matrix and you need to index kernel. LOOK INTO ME!! \n    float maxnum = -LARGE_NUM;\n    for (int i = 0; i < input->cols() - kernel->cols(); i+=stride_len) {\n        for (int j = 0; j < input->rows() - kernel->rows(); j+=stride_len) {\n            for (int k = 0; k < kernel->cols(); k++) {\n                for (int l = 0; l < kernel->rows(); l++) {\n                    if ((input->block(j, i, kernel->rows(), kernel->cols()))(l, k) > maxnum) {\n                        maxnum = (input->block(j, i, kernel->rows(), kernel->cols()))(l, k);\n                    }\n                }\n            }\n        }\n    }\n}\n\nConvNet::ConvNet(const char* path, float learn_rate, float bias_rate, Regularization reg, float l, float ratio)\n    :Network(path, 1, learn_rate, bias_rate, reg, l, ratio), preprocess_length{0}\n{\n    ReadMNIST(10000,784,data);\n    data_labels = read_mnist_labels(\"./t10k-labels-idx1-ubyte\",10000);\n    labels = new Eigen::MatrixXf (1, 1);\n}\n\nvoid ConvNet::add_conv_layer(int x, int y, int stride, int kern_x, int kern_y, int pad, std::function<float(float)> activ, std::function<float(float)> activ_deriv)\n{\n    preprocess_length+=1;\n    conv_layers.emplace_back(x,y,stride,kern_x, kern_y,pad,activ,activ_deriv);\n}\n\n// May make this inaccessible to user code and just have it called from add_conv_layer as pooling is basically always paired with conv.\nvoid ConvNet::add_pool_layer(int x, int y, int stride, int kern_x, int kern_y, int pad)\n{\n    pool_layers.emplace_back(x,y,stride,kern_x,kern_y,pad);\n}\n\nvoid ConvNet::initialize()\n{\n    for (int i = 0; i < length-1; i++) {\n        layers[i].init_weights(layers[i+1]);\n    }\n}\n\nvoid ConvNet::next_batch()\n{\n    for (int i = 0; i < 784; i++) {\n        (*conv_layers[0].input)(i/28, i%28) = data[batches][i];\n    }\n    (*labels)(0,0) = (float)(int)data_labels[batches];\n}\n\nvoid ConvNet::process()\n{\n    // Assumes pooling is immediately after any conv layer.\n    for (int i = 0; i < preprocess_length-1; i++) {\n        conv_layers[i].convolute();\n        //   pool_layers[i].input = conv_layers[i].output;\n        //   pool_layers[i].pool();\n        conv_layers[i+1].input = conv_layers[i].output;\n    }\n    conv_layers[preprocess_length-1].convolute(); \n    //pool_layers[preprocess_length-1].input = conv_layers[preprocess_length-1].output;\n    //pool_layers[preprocess_length-1].pool();\n    //  std::cout << \"Output:\\n\" << *pool_layers[preprocess_length-1].output << \"\\n\\n\";\n    Eigen::Map<Eigen::RowVectorXf> flattened (conv_layers[preprocess_length-1].output->data(), conv_layers[preprocess_length-1].output->size());\n    // std::cout << \"Flattened:\\n\" << flattened << \"\\n\\n\";\n    for (int i = 0; i < flattened.cols(); i++) {\n        (*layers[0].contents)(0, i) = flattened[i];\n    }\n}\n\nvoid ConvNet::set_label(Eigen::MatrixXf newlabels)\n{\n    *labels = newlabels;\n}\n\nvoid ConvNet::list_net()\n{\n    for (int i = 0; i < preprocess_length; i++) {\n        std::cout << \"-----------------------\\nCONVOLUTIONAL LAYER \" << i << \"\\n-----------------------\\n\\n\\u001b[31mGENERAL INFO:\\x1B[0;37m\\nStride: \" << conv_layers[i].stride_len << \"\\nPadding: \" << conv_layers[i].padding <<  \"\\n\\n\\u001b[31mINPUT:\\x1B[0;37m\\n\" << *conv_layers[i].input << \"\\n\\n\\u001b[31mKERNEL:\\x1B[0;37m\\n\" << *conv_layers[i].kernel << \"\\n\\n\\u001b[31mOUTPUT:\\x1B[0;37m\\n\" << *conv_layers[i].output << \"\\n\\n\\u001b[31mBIAS:\\x1B[0;37m\\n\" << conv_layers[i].bias << \"\\n\\n\\n\";\n        //std::cout << \"-----------------------\\nPOOLING LAYER \" << i << \"\\n-----------------------\\n\\n\\u001b[31mGENERAL INFO:\\x1B[0;37m\\nStride: \" << pool_layers[i].stride_len << \"\\nPadding: \" << conv_layers[i].padding << \"\\n\\n\\u001b[31mINPUT:\\x1B[0;37m\\n\" << *pool_layers[i].input << \"\\n\\n\\u001b[31mKERNEL:\\x1B[0;37m\\n-\" << *pool_layers[i].kernel << \"\\n\\n\\u001b[31mOUTPUT:\\x1B[0;37m\\n\" << *pool_layers[i].output << \"\\n\\n\\n\";\n    }\n    std::cout << \"-----------------------\\nINPUT LAYER (LAYER 0)\\n-----------------------\\n\\n\\u001b[31mGENERAL INFO:\\x1B[0;37m\\nActivation Function: \" << layers[0].activation_str << \"\\n\\n\\u001b[31mACTIVATIONS:\\x1B[0;37m\\n\" << *layers[0].contents << \"\\n\\n\\u001b[31mWEIGHTS:\\x1B[0;37m\\n\" << *layers[0].weights << \"\\n\\n\\u001b[31mBIASES:\\x1B[0;37m\\n\" << *layers[0].bias << \"\\n\\n\\n\";\n    for (int i = 1; i < length-1; i++) {\n        std::cout << \"-----------------------\\nLAYER \" << i << \"\\n-----------------------\\n\\n\\u001b[31mGENERAL INFO:\\x1B[0;37m\\nActivation Function: \" << layers[i].activation_str << \"\\n\\n\\u001b[31mACTIVATIONS:\\x1B[0;37m\\n\" << *layers[i].contents << \"\\n\\n\\u001b[31mBIASES:\\x1B[0;37m\\n\" << *layers[i].bias << \"\\n\\n\\u001b[31mWEIGHTS:\\x1B[0;37m\\n\" << *layers[i].weights << \"\\n\\n\\n\";\n    }\n    std::cout << \"-----------------------\\nOUTPUT LAYER (LAYER \" << length-1 << \")\\n-----------------------\\n\\n\\u001b[31mGENERAL INFO:\\x1B[0;37m\\nActivation Function: \" << layers[length-1].activation_str <<\"\\n\\n\\u001b[31mACTIVATIONS:\\x1B[0;37m\\n\" << *layers[length-1].contents << \"\\n\\n\\u001b[31mBIASES:\\x1B[0;37m\\n\" << *layers[length-1].bias <<  \"\\n\\n\\n\";\n}\n\nvoid ConvNet::backpropagate()\n{\n    list_net();\n    char a;\n    std::cin >> a;\n    std::vector<Eigen::MatrixXf> gradients;\n    gradients.push_back(Network::backpropagate());    \n    Eigen::Map<Eigen::MatrixXf> reshaped(gradients[gradients.size()-1].data(),\n                           conv_layers.back().output->rows(),\n                           conv_layers.back().output->cols());\n    gradients[gradients.size()-1] = reshaped;\n    std::vector<Eigen::MatrixXf> conv_deltas;\n    for (int layer = conv_layers.size()-1; layer >= 0; layer--) {\n        conv_deltas.emplace_back(conv_layers[layer].kernel->rows(),\n                                 conv_layers[layer].kernel->cols());\n        std::cout << conv_layers[layer].input->cols() << \" \" << gradients.back().cols() << \"\\n\";\n        for (int i = 0; i < conv_layers[layer].input->rows() - gradients.back().rows() + 1; i++) {\n            for (int j = 0; j < conv_layers[layer].input->cols() - gradients.back().cols() + 1; j++) {\n                conv_deltas[conv_deltas.size()-1](i, j) = (gradients.back() * conv_layers[layer].input->block(i, j, gradients.back().rows(), gradients.back().cols())).sum();\n            }\n        }\n        *conv_layers[layer].kernel -= conv_deltas.back();\n\n        Eigen::MatrixXf flipped_kernel =\n            Eigen::MatrixXf::Zero(conv_layers[layer].kernel->rows(), conv_layers[layer].kernel->cols());\n        flipped_kernel = conv_layers[layer].kernel->transpose().colwise().reverse().transpose().colwise().reverse();\n        Eigen::MatrixXf padded_grad = Eigen::MatrixXf::Zero(gradients.back().rows() + ((flipped_kernel.rows() - 1)*2), gradients.back().cols() + ((flipped_kernel.cols() - 1)*2));\n        padded_grad.block(flipped_kernel.rows() - 1, flipped_kernel.cols() - 1, gradients.back().rows(), gradients.back().cols()) = gradients.back();\n        Eigen::MatrixXf final_grad (padded_grad.rows() - flipped_kernel.rows() + 1, padded_grad.cols() - flipped_kernel.cols() + 1);\n        for (int i = 0; i < padded_grad.rows() - flipped_kernel.rows() + 1; i++) {\n            for (int j = 0; j < padded_grad.cols() - gradients.back().cols() + 1; j++) {\n                final_grad(i, j) = (flipped_kernel * padded_grad.block(i, j, flipped_kernel.rows(), flipped_kernel.cols())).sum();\n            }\n        }\n        gradients.push_back(final_grad.cwiseProduct(*conv_layers[layer].dZ));\n    }\n    list_net();\n    assert(2<1);\n}\n\nvoid ConvNet::train()\n{\n    float cost_sum = 0;\n    float acc_sum = 0;\n    for (int i = 0; i <= 100; i++) {\n        if (i != instances-batch_size) { // Don't try to advance batch on final batch.\n            next_batch();\n        }\n        process();\n        feedforward();\n        backpropagate();\n        cost_sum += cost();\n        acc_sum += accuracy();\n        batches++;\n    }\n    list_net();\n    epoch_acc = 1.0/(100) * acc_sum;\n    epoch_cost = 1.0/(100) * cost_sum;\n    printf(\"Epoch %i complete - cost %f - acc %f\\n\", epochs, epoch_cost, epoch_acc);\n    batches=0;\n    decay();\n    epochs++;\n}\n\nint main()\n{\n    ConvNet net (\"../data_banknote_authentication.txt\", 0.05, 0.01, L2, 0, 0.9);\n    Eigen::MatrixXf labels (1,1);\n    net.add_conv_layer(28, 28, 1, 9, 9, 0, lecun_tanh, lecun_tanh_deriv);\n    //  net.add_pool_layer(20,20,1,6,6,0);\n    net.add_conv_layer(20, 20, 1, 6, 6, 0, lecun_tanh, lecun_tanh_deriv);\n    std::cout << net.conv_layers[net.conv_layers.size()-1].output->rows() << \"\\n\";\n    //net.add_pool_layer(10,10,1,2,2,0);\n    net.add_layer(400, \"sigmoid\", sigmoid, sigmoid_deriv);\n    net.add_layer(5, \"lecun_tanh\", lecun_tanh, lecun_tanh_deriv);\n    net.add_layer(10, \"resig\", rectifier(sigmoid), rectifier(sigmoid_deriv));\n    //  net.list_net();\n    //  net.init_decay(\"step\", 1, 2);\n    net.initialize();\n    //net.list_net();\n\n    for (int i = 0; i < 1; i++) {\n        net.train();\n    }\n    net.list_net();\n}\n", "meta": {"hexsha": "8802e95c7fbf3cca0b4dce9533e1050ce2489843", "size": 14299, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cnn.cpp", "max_stars_repo_name": "richardfeynmanrocks/ml-in-parallel", "max_stars_repo_head_hexsha": "6fd978b1f4a97ae789a13e0c2f20638672848aa5", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-10-01T23:28:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-29T02:21:20.000Z", "max_issues_repo_path": "src/cnn.cpp", "max_issues_repo_name": "quantumish/Jacobian", "max_issues_repo_head_hexsha": "6fd978b1f4a97ae789a13e0c2f20638672848aa5", "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/cnn.cpp", "max_forks_repo_name": "quantumish/Jacobian", "max_forks_repo_head_hexsha": "6fd978b1f4a97ae789a13e0c2f20638672848aa5", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-14T16:06:20.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-14T16:06:20.000Z", "avg_line_length": 43.0692771084, "max_line_length": 490, "alphanum_fraction": 0.5806699769, "num_tokens": 4432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419958239132, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.46089129745269847}}
{"text": "// Copyright (c) 2019 The Bitcoin developers\n// Distributed under the MIT software license, see the accompanying\n// file COPYING or http://www.opensource.org/licenses/mit-license.php.\n\n#include <test/test_bitcoin.h>\n#include <test/test_random.h>\n#include <bitmanip.h>\n\n#include <boost/test/unit_test.hpp>\n\nBOOST_FIXTURE_TEST_SUITE(bitmanip_tests, BasicTestingSetup)\n\nstatic void CheckBitCount(uint32_t value, uint32_t expected_count) {\n    // Count are rotation invariant.\n    for (int i = 0; i < 32; i++) {\n        BOOST_CHECK_EQUAL(countBits(value), expected_count);\n        value = (value << 1) | (value >> 31);\n    }\n}\n\nstatic uint32_t countBitsNaive(uint32_t value) {\n    uint32_t ret = 0;\n    while (value != 0) {\n        ret += (value & 0x01);\n        value >>= 1;\n    }\n\n    return ret;\n}\n\nconst size_t COUNT=4096;\n\nBOOST_AUTO_TEST_CASE(bit_count) {\n    // Check various known values.\n    CheckBitCount(0, 0);\n    CheckBitCount(1, 1);\n    CheckBitCount(0xffffffff, 32);\n    CheckBitCount(0x01234567, 12);\n    CheckBitCount(0x12345678, 13);\n    CheckBitCount(0xfedcba98, 20);\n    CheckBitCount(0x5a55aaa5, 16);\n    CheckBitCount(0xdeadbeef, 24);\n\n    for (uint32_t i = 2; i != 0; i <<= 1) {\n        // Check two bit set for all combinations.\n        CheckBitCount(i | 0x01, 2);\n    }\n\n    // Check many small values against a naive implementation.\n    for (uint32_t v = 0; v <= 0xfff; v++) {\n        CheckBitCount(v, countBitsNaive(v));\n    }\n\n    // Check random values against a naive implementation.\n    for (size_t i = 0; i < COUNT; i++) {\n        uint32_t v = insecure_rand();\n        CheckBitCount(v, countBitsNaive(v));\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "7382d5b259372c7db60401807eb85c75ee1a033d", "size": 1671, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/bitmanip_tests.cpp", "max_stars_repo_name": "dagurval/bitcoinunlimited", "max_stars_repo_head_hexsha": "581d205e4e254be4a9f3f80c95e140447002e458", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/test/bitmanip_tests.cpp", "max_issues_repo_name": "dagurval/bitcoinunlimited", "max_issues_repo_head_hexsha": "581d205e4e254be4a9f3f80c95e140447002e458", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/test/bitmanip_tests.cpp", "max_forks_repo_name": "dagurval/bitcoinunlimited", "max_forks_repo_head_hexsha": "581d205e4e254be4a9f3f80c95e140447002e458", "max_forks_repo_licenses": ["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.9516129032, "max_line_length": 70, "alphanum_fraction": 0.6535008977, "num_tokens": 485, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.6926419958239131, "lm_q1q2_score": 0.4608912974526984}}
{"text": "/*=============================================================================\n    Copyright (c) 2002-2003 Joel de Guzman\n    http://spirit.sourceforge.net/\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///////////////////////////////////////////////////////////////////////////////\n//\n//  A primitive calculator that knows how to add and subtract.\n//  [ demonstrating phoenix ]\n//\n//  [ JDG 6/28/2002 ]\n//\n///////////////////////////////////////////////////////////////////////////////\n#include <boost/spirit/core.hpp>\n#include <boost/spirit/phoenix/primitives.hpp>\n#include <boost/spirit/phoenix/operators.hpp>\n#include <iostream>\n#include <string>\n\n///////////////////////////////////////////////////////////////////////////////\nusing namespace std;\nusing namespace boost::spirit;\nusing namespace phoenix;\n\n///////////////////////////////////////////////////////////////////////////////\n//\n//  Our primitive calculator\n//\n///////////////////////////////////////////////////////////////////////////////\ntemplate <typename IteratorT>\nbool primitive_calc(IteratorT first, IteratorT last, double& n)\n{\n    return parse(first, last,\n\n        //  Begin grammar\n        (\n            real_p[var(n) = arg1]\n            >> *(   ('+' >> real_p[var(n) += arg1])\n                |   ('-' >> real_p[var(n) -= arg1])\n                )\n        )\n        ,\n        //  End grammar\n\n        space_p).full;\n}\n\n////////////////////////////////////////////////////////////////////////////\n//\n//  Main program\n//\n////////////////////////////////////////////////////////////////////////////\nint\nmain()\n{\n    cout << \"/////////////////////////////////////////////////////////\\n\\n\";\n    cout << \"\\t\\tA primitive calculator...\\n\\n\";\n    cout << \"/////////////////////////////////////////////////////////\\n\\n\";\n\n    cout << \"Give me a list of numbers to be added or subtracted.\\n\";\n    cout << \"Example: 1 + 10 + 3 - 4 + 9\\n\";\n    cout << \"The result is computed using Phoenix.\\n\";\n    cout << \"Type [q or Q] to quit\\n\\n\";\n\n    string str;\n    while (getline(cin, str))\n    {\n        if (str.empty() || str[0] == 'q' || str[0] == 'Q')\n            break;\n\n        double n;\n        if (primitive_calc(str.begin(), str.end(), n))\n        {\n            cout << \"-------------------------\\n\";\n            cout << \"Parsing succeeded\\n\";\n            cout << str << \" Parses OK: \" << endl;\n\n            cout << \"result = \" << n;\n            cout << \"\\n-------------------------\\n\";\n        }\n        else\n        {\n            cout << \"-------------------------\\n\";\n            cout << \"Parsing failed\\n\";\n            cout << \"-------------------------\\n\";\n        }\n    }\n\n    cout << \"Bye... :-) \\n\\n\";\n    return 0;\n}\n\n\n", "meta": {"hexsha": "9c25c0c4cdf0698f4852a14e5dff4fd790481e96", "size": 2919, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Source/boost_1_33_1/libs/spirit/example/fundamental/more_calculators/primitive_calc.cpp", "max_stars_repo_name": "spxuw/RFIM", "max_stars_repo_head_hexsha": "32b78fbb90c7008b1106b0cff4f8023ae83c9b6d", "max_stars_repo_licenses": ["MIT"], "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/boost_1_33_1/libs/spirit/example/fundamental/more_calculators/primitive_calc.cpp", "max_issues_repo_name": "spxuw/RFIM", "max_issues_repo_head_hexsha": "32b78fbb90c7008b1106b0cff4f8023ae83c9b6d", "max_issues_repo_licenses": ["MIT"], "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/boost_1_33_1/libs/spirit/example/fundamental/more_calculators/primitive_calc.cpp", "max_forks_repo_name": "spxuw/RFIM", "max_forks_repo_head_hexsha": "32b78fbb90c7008b1106b0cff4f8023ae83c9b6d", "max_forks_repo_licenses": ["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.0927835052, "max_line_length": 79, "alphanum_fraction": 0.3556012333, "num_tokens": 555, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419958239132, "lm_q2_score": 0.6654105454764747, "lm_q1q2_score": 0.4608912882611042}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// Unit Test\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#include <algorithms/test_length.hpp>\n\n#include <boost/geometry/geometries/geometries.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/adapted/std_pair_as_segment.hpp>\n\n#include <test_geometries/all_custom_linestring.hpp>\n#include <test_geometries/wrapped_boost_array.hpp>\n\n\ntemplate <typename P>\nvoid test_all()\n{\n    // 3-4-5 triangle\n    test_geometry<std::pair<P, P> >(\"LINESTRING(0 0,3 4)\", 5);\n\n    // 3-4-5 plus 1-1\n    test_geometry<bg::model::linestring<P> >(\"LINESTRING(0 0,3 4,4 3)\", 5 + sqrt(2.0));\n    test_geometry<all_custom_linestring<P> >(\"LINESTRING(0 0,3 4,4 3)\", 5 + sqrt(2.0));\n    test_geometry<test::wrapped_boost_array<P, 3> >(\"LINESTRING(0 0,3 4,4 3)\", 5 + sqrt(2.0));\n\n    // Geometries with length zero\n    test_geometry<P>(\"POINT(0 0)\", 0);\n    test_geometry<bg::model::polygon<P> >(\"POLYGON((0 0,0 1,1 1,1 0,0 0))\", 0);\n}\n\ntemplate <typename P>\nvoid test_empty_input()\n{\n    test_empty_input(bg::model::linestring<P>());\n}\n\nint test_main(int, char* [])\n{\n    test_all<bg::model::d2::point_xy<int> >();\n    test_all<bg::model::d2::point_xy<float> >();\n    test_all<bg::model::d2::point_xy<double> >();\n\n#if defined(HAVE_TTMATH)\n    test_all<bg::model::d2::point_xy<ttmath_big> >();\n#endif\n\n    // test_empty_input<bg::model::d2::point_xy<int> >();\n\n    return 0;\n}\n", "meta": {"hexsha": "11e18d396407ff47e439915c74daf50fa3330065", "size": 1663, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/geometry/test/algorithms/length.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "boost/libs/geometry/test/algorithms/length.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "boost/libs/geometry/test/algorithms/length.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "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": 29.6964285714, "max_line_length": 94, "alphanum_fraction": 0.6873120866, "num_tokens": 537, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419704455588, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.4608912759698765}}
{"text": "#include <iostream>\n#include <random>\n#include <Eigen/Dense>\n#include <cmath>\n#include <fstream>\n#include <nlohmann/json.hpp>\n#include <chrono>\n#include \"oful.h\"\n#include \"contlinrep.h\"\n#include \"utils.h\"\n#include \"gzip.h\"\n#include \"bandit.h\"\n#include \"leader.h\"\n#include \"adversarial_master.h\"\n\n\nusing json = nlohmann::json;\nusing namespace std;\nusing namespace Eigen;\n\nint PREC = 4;\nint EVERY = 1;\n\nint main()\n{\n    std::time_t t = std::time(nullptr);\n    char MY_TIME[100];\n    std::strftime(MY_TIME, sizeof(MY_TIME), \"%Y%m%d%H%M%S\", std::localtime(&t));\n    std::cout << MY_TIME << '\\n';\n\n    typedef std::vector<std::vector<double>> vec2double;\n\n    srand (time(NULL));\n    // rng.seed(10000); // warm it up\n    int n_runs = 20, T = 1000;\n    double delta = 0.01;\n    double reg_val = 1.;\n    double noise_std = 0.2;\n    double bonus_scale = 1;\n    bool adaptive_ci = true;\n\n    std::vector<long> seeds(n_runs);\n    std::generate(seeds.begin(), seeds.end(), [] ()\n    {\n        return rand();\n    });\n\n    vec2double regrets(n_runs), pseudo_regrets(n_runs);\n\n    ContToy1_phi1 lrep1 = ContToy1_phi1(noise_std, seeds[0]);\n    ContToy1_phi2 lrep2 = ContToy1_phi2(noise_std, seeds[0]);\n\n    std::cerr << \"OFUL\" << std::endl;\n    for (int i = 0; i < n_runs; ++i)\n    {\n        OFUL<std::vector<double>> localg(lrep1, reg_val, noise_std, bonus_scale, delta, adaptive_ci);\n        ContBanditProblem<std::vector<double>> prb(lrep1, localg);\n        prb.reset();\n        prb.run(T);\n        regrets[i] = prb.instant_regret;\n        pseudo_regrets[i] = prb.exp_instant_regret;\n    }\n    save_vector_csv_gzip(regrets, \"$\\\\phi#1$_regrets.csv.gz\", EVERY, PREC);\n    save_vector_csv_gzip(pseudo_regrets, \"$\\\\phi#1$_pseudoregrets.csv.gz\", EVERY, PREC);\n\n    for (int i = 0; i < n_runs; ++i)\n    {\n        OFUL<std::vector<double>> localg(lrep2, reg_val, noise_std, bonus_scale, delta, adaptive_ci);\n        ContBanditProblem<std::vector<double>> prb(lrep2, localg);\n        prb.reset();\n        prb.run(T);\n        regrets[i] = prb.instant_regret;\n        pseudo_regrets[i] = prb.exp_instant_regret;\n    }\n    save_vector_csv_gzip(regrets, \"$\\\\phi#2$_regrets.csv.gz\", EVERY, PREC);\n    save_vector_csv_gzip(pseudo_regrets, \"$\\\\phi#2$_pseudoregrets.csv.gz\", EVERY, PREC);\n\n    std::vector<std::shared_ptr<ContRepresentation<std::vector<double>>>> lreps;\n\n    auto tmp = std::make_shared<ContToy1_phi1>(lrep1);\n    lreps.push_back(tmp);\n    tmp = std::make_shared<ContToy1_phi2>(lrep2);\n    lreps.push_back(tmp);\n\n    //LEADER\n    std::cerr << \"LEADER\" << std::endl;\n    for (int i = 0; i < n_runs; ++i)\n    {\n        LEADER<std::vector<double>> localg(lreps, reg_val, noise_std, bonus_scale, delta/lreps.size(), adaptive_ci);\n        ContBanditProblem<std::vector<double>> prb(*lreps[0], localg);\n        prb.reset();\n        prb.run(T);\n        regrets[i] = prb.instant_regret;\n        pseudo_regrets[i] = prb.exp_instant_regret;\n        // delete localg;\n    }\n    save_vector_csv_gzip(regrets, \"\\\\algo_regrets.csv.gz\", EVERY, PREC);\n    save_vector_csv_gzip(pseudo_regrets, \"\\\\algo_pseudoregrets.csv.gz\", EVERY, PREC);\n\n    //EXP4.IX\n    std::cerr << \"EXP4\" << std::endl;\n    for (int i = 0; i < n_runs; ++i)\n    {\n        std::vector<std::shared_ptr<Algo<std::vector<double>>>> base_algs;\n        for(auto& ll : lreps)\n        {\n            base_algs.push_back(\n                std::make_shared<OFUL<std::vector<double>>>(\n                    OFUL<std::vector<double>>(*tmp, reg_val,noise_std,bonus_scale,delta,adaptive_ci)\n                )\n            );\n        }\n        double exp4_gamma = sqrt(2*log(base_algs.size())/(4*T));\n        double exp4_lr = 2*exp4_gamma;\n        EXP4dotIX<std::vector<double>> localg(base_algs, exp4_lr, exp4_gamma, seeds[i]);\n        ContBanditProblem<std::vector<double>> prb(*lreps[0], localg);\n        prb.reset();\n        prb.run(T);\n        regrets[i] = prb.instant_regret;\n        pseudo_regrets[i] = prb.exp_instant_regret;\n    }\n    save_vector_csv_gzip(regrets, \"\\\\expfour_regrets.csv.gz\", EVERY, PREC);\n    save_vector_csv_gzip(pseudo_regrets, \"\\\\expfour_pseudoregrets.csv.gz\", EVERY, PREC);\n\n    return 0;\n}\n", "meta": {"hexsha": "fd19dc123b216f0ec130a52ac64374fe6f0d0f7f", "size": 4147, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/cont_all.cpp", "max_stars_repo_name": "T3p/hidden-features", "max_stars_repo_head_hexsha": "7d3c27ab513e5a4c6a10c7550dc6363bd7735266", "max_stars_repo_licenses": ["MIT"], "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/cont_all.cpp", "max_issues_repo_name": "T3p/hidden-features", "max_issues_repo_head_hexsha": "7d3c27ab513e5a4c6a10c7550dc6363bd7735266", "max_issues_repo_licenses": ["MIT"], "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/cont_all.cpp", "max_forks_repo_name": "T3p/hidden-features", "max_forks_repo_head_hexsha": "7d3c27ab513e5a4c6a10c7550dc6363bd7735266", "max_forks_repo_licenses": ["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.6535433071, "max_line_length": 116, "alphanum_fraction": 0.6257535568, "num_tokens": 1238, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738152021788, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4607634752127422}}
{"text": "#pragma once\n\n#include <polyfem/Quadrature.hpp>\n#include <polyfem/ElementAssemblyValues.hpp>\n\n#include <Eigen/Dense>\n\nnamespace polyfem\n{\n\tclass RBFWithQuadratic\n\t{\n\tpublic:\n\t\tinline static int index_mapping(const int alpha, const int beta, const int d, const int ass_dim)\n\t\t{\n\t\t\treturn ass_dim*ass_dim*d + ass_dim * beta + alpha;\n\t\t}\n\n\t\tstatic void setup_monomials_vals_2d(const int star_index, const Eigen::MatrixXd &pts, ElementAssemblyValues &vals);\n\t\tstatic void setup_monomials_strong_2d(const int dim, const std::string &assembler_name, const Eigen::MatrixXd &pts, const QuadratureVector &da, std::array<Eigen::MatrixXd, 5> &strong);\n\n\t\t///\n\t\t/// @brief      { Initialize RBF functions over a polytope element. }\n\t\t///\n\t\t/// @param[in]  centers               { #C x dim positions of the kernels used to define\n\t\t///                                   functions over the polytope. The centers are placed at\n\t\t///                                   a small offset distance from the boundary of the\n\t\t///                                   element, due to the singularity at the centers }\n\t\t/// @param[in]  collocation_points    { #S x dim positions of the collocation points, used\n\t\t///                                   to approximate the RBF functions over the boundary of\n\t\t///                                   the element }\n\t\t/// @param[in]  local_basis_integral  { #B x dim+dim*(dim+1)/2 of the constant right-hand\n\t\t///                                   side for the integral constraint for each basis over\n\t\t///                                   the polytope }\n\t\t/// @param[in]  quadr                 { Quadrature points and weights inside the polytope }\n\t\t/// @param[in]  rhs                   { #S x #B of boundary conditions. Each column defines\n\t\t///                                   how the i-th basis of the mesh should evaluate on the\n\t\t///                                   collocation points sampled on the boundary of the\n\t\t///                                   polytope }\n\t\t/// @param[in]  with_constraints      { Impose integral constraints to guarantee linear\n\t\t///                                   reproduction for the Poisson equation }\n\t\t///\n\t\tRBFWithQuadratic(const std::string &assembler_name, const Eigen::MatrixXd &centers, const Eigen::MatrixXd &collocation_points,\n\t\t\tconst Eigen::MatrixXd &local_basis_integral, const Quadrature &quadr,\n\t\t\tEigen::MatrixXd &rhs, bool with_constraints = true);\n\n\t\t///\n\t\t/// @brief      { Evaluates one RBF function over a list of coordinates }\n\t\t///\n\t\t/// @param[in]  local_index  { i-th RBF function to evaluate }\n\t\t/// @param[in]  uv           { #uv x dim matrix of coordinates to evaluate (in object\n\t\t///                          domain) }\n\t\t/// @param[out] val          { #uv x 1 matrix of computed values }\n\t\t///\n\t\tvoid basis(const int local_index, const Eigen::MatrixXd &uv, Eigen::MatrixXd &val) const;\n\n\t\t///\n\t\t/// @brief      { Evaluates the gradient of one RBF function over a list of coordinates }\n\t\t///\n\t\t/// @param[in]  local_index  { i-th RBF function to evaluate }\n\t\t/// @param[in]  uv           { #uv x dim matrix of coordinates to evaluate (in object\n\t\t///                          domain) }\n\t\t/// @param[out] val          { #uv x dim matrix of computed gradients }\n\t\t///\n\t\tvoid grad(const int local_index, const Eigen::MatrixXd &uv, Eigen::MatrixXd &val) const;\n\n\t\t///\n\t\t/// @brief      { Batch evaluates the RBF + polynomials on a set of sample points }\n\t\t///\n\t\t/// @param[in]  uv    { #uv x dim matrix of points to evaluate }\n\t\t/// @param[out] val   { #uv x n_loc_bases of bases values over the sample points }\n\t\t///\n\t\tvoid bases_values(const Eigen::MatrixXd &samples, Eigen::MatrixXd &val) const;\n\n\t\t///\n\t\t/// @brief      { Batch evaluates the gradient of the RBF + polynomials on a set of sample\n\t\t///             points }\n\t\t///\n\t\t/// @param[in]  axis  { The axis (0, 1, 2) with respect to which to compute the gradient }\n\t\t/// @param[in]  uv    { #uv x dim matrix of points to evaluate }\n\t\t/// @param[out] val   { #uv x n_loc_bases of bases gradient wrt axis over the sample points }\n\t\t///\n\t\tvoid bases_grads(const int axis, const Eigen::MatrixXd &samples, Eigen::MatrixXd &val) const;\n\n\tprivate:\n\t\tbool is_volume() const { return centers_.cols() == 3; }\n\n\t\t// Computes the matrix that evaluates the kernels + polynomial terms on the given sample points\n\t\tvoid compute_kernels_matrix(const Eigen::MatrixXd &samples, Eigen::MatrixXd &A) const;\n\n\t\t// Computes the relationship w = L v + t between the unknowns (v) and the weights w\n\t\tvoid compute_constraints_matrix_2d_old(const int num_bases, const Quadrature &quadr,\n\t\t\tconst Eigen::MatrixXd &local_basis_integral, Eigen::MatrixXd &L, Eigen::MatrixXd &t) const;\n\n\t\t// Computes the relationship w = L v + t between the unknowns (v) and the weights w\n\t\tvoid compute_constraints_matrix_2d(const std::string &assembler_name, const int num_bases, const Quadrature &quadr,\n\t\t\tconst Eigen::MatrixXd &local_basis_integral, Eigen::MatrixXd &L, Eigen::MatrixXd &t) const;\n\n\t\t// Computes the relationship w = L v + t between the unknowns (v) and the weights w\n\t\tvoid compute_constraints_matrix_3d(const std::string &assembler_name, const int num_bases, const Quadrature &quadr,\n\t\t\tconst Eigen::MatrixXd &local_basis_integral, Eigen::MatrixXd &L, Eigen::MatrixXd &t) const;\n\n\t\t// Computes the weights by solving a (possibly constrained) linear least square\n\t\tvoid compute_weights(const std::string &assembler_name, const Eigen::MatrixXd &collocation_points,\n\t\t\tconst Eigen::MatrixXd &local_basis_integral, const Quadrature &quadr,\n\t\t\tEigen::MatrixXd &rhs, bool with_constraints);\n\n\tprivate:\n\t\t// #C x dim matrix of kernel center positions\n\t\tEigen::MatrixXd centers_;\n\n\t\t// (#C + dim + 1) x #B matrix of weights extending the #B bases that are non-vanishing on the polytope\n\t\tEigen::MatrixXd weights_;\n\t};\n}\n", "meta": {"hexsha": "db62dd5ef2ce1af3b6d5435232f793cc498617d9", "size": 5836, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/basis/function/RBFWithQuadratic.hpp", "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/basis/function/RBFWithQuadratic.hpp", "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/basis/function/RBFWithQuadratic.hpp", "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": 50.747826087, "max_line_length": 186, "alphanum_fraction": 0.6422206991, "num_tokens": 1451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4607634644016136}}
{"text": "#include <boost/python/module.hpp>\n#include <boost/python/class.hpp>\n#include <boost/python/args.hpp>\n\n#include <scitbx/math/zernike.h>\n#include <scitbx/math/zernike_moments.h>\n\nnamespace scitbx { namespace math {\nnamespace {\n\n//\n//\n  struct grid_wrapper\n  {\n    typedef grid  < double > w_t;\n    static void\n    wrap()\n    {\n      using namespace boost::python;\n      class_<w_t>(\"sphere_grid\", no_init)\n        .def( init<\n                   int const&,\n                   int const&\n                  >\n             ((\n                arg(\"np\"),\n                arg(\"n_max\")\n             ))\n            )\n        .def(\"get_ss\", &w_t::get_ss)\n        .def(\"get_ss\", &w_t::get_all_ss)\n        .def(\"clean_space\", &w_t::clean_space)\n        .def(\"construct_space_sum\",&w_t::construct_space_sum)\n        .def(\"construct_space_sum_via_list\",&w_t::construct_space_sum_via_list)\n        .def(\"construct_space_sum_via_list\",&w_t::construct_space_sum_via_list_only)\n        .def(\"unit_sphere_index\", &w_t::unit_sphere_index)\n        .def(\"occupied_sites\", &w_t::occupied_sites)\n      ;\n    }\n  };\n\n//\n//\n\n\n  struct moments_wrapper\n  {\n    typedef moments  < double > w_t;\n    static void\n    wrap()\n    {\n      using namespace boost::python;\n      class_<w_t>(\"zernike_moments\", no_init)\n        .def( init<\n                   grid<double>,\n                   int const&\n                  >\n             ((\n                arg(\"grid\"),\n                arg(\"nmax\")\n             ))\n            )\n        .def(\"moments\", &w_t::all_moments)\n        .def(\"get_moment\",&w_t::get_moment)\n        .def(\"calc_moments\",&w_t::calc_moments)\n        .def(\"update_ss\",&w_t::update_ss)\n        .def(\"fnn\",&w_t::fnn)\n        .def(\"fnl\",&w_t::fnl)\n        .def(\"fnnl\",&w_t::fnnl)\n      ;\n    }\n  };\n\n//\n//\n  struct voxel_wrapper\n  {\n    typedef voxel < double > w_t;\n    static void\n    wrap()\n    {\n      using namespace boost::python;\n      class_<w_t>(\"sphere_voxel\", no_init)\n        .def( init<\n                   int const&,\n                   int const&,\n                   bool const&,\n                   bool const&,\n                   double const&,\n                   double const&,\n                   double const&,\n                   scitbx::af::const_ref< scitbx::vec3<double> >,\n                   scitbx::af::const_ref< double >\n                  >\n             ((\n                arg(\"np\"),\n                arg(\"splat_range\"),\n                arg(\"uniform\"),\n                arg(\"fixed_dx\"),\n                arg(\"external_rmax\"),\n                arg(\"fraction\"),\n                arg(\"dx\"),\n                arg(\"xyz\"),\n                arg(\"density\")\n             ))\n            )\n        .def(\"value\", &w_t::get_value)\n        .def(\"rmax\", &w_t::rmax)\n        .def(\"rg\", &w_t::rg)\n        .def(\"map\", &w_t::map)\n        .def(\"xyz\", &w_t::xyz)\n        .def(\"rotate\", &w_t::rotate)\n        .def(\"np\",&w_t::np)\n        .def(\"weight_sum\",&w_t::weight_sum)\n        .def(\"occupied_sites\", &w_t::occupied_sites)\n        .def(\"status\", &w_t::print_status)\n        .def(\"border\", &w_t::border)\n      ;\n    }\n  };\n\n} //namespace <anonymous>\n\nnamespace boost_python {\n\n  void wrap_zernike_mom()\n  {\n    voxel_wrapper::wrap();\n    moments_wrapper::wrap();\n    grid_wrapper::wrap();\n  }\n\n}}}\n", "meta": {"hexsha": "b4c6a1ac79e5482fec71e5811e9731d51e15d642", "size": 3272, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "scitbx/math/boost_python/zernike_moments.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/zernike_moments.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/zernike_moments.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.4179104478, "max_line_length": 84, "alphanum_fraction": 0.4758557457, "num_tokens": 831, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4607634644016136}}
{"text": "#pragma once\n#include <Eigen/Core>\n#include <gtsam/nonlinear/NonlinearFactor.h>\n#include <gtsam/geometry/Pose3.h>\n#include <gtsam/geometry/Point3.h>\n\nnamespace gtsam\n{\n  class LidarPlaneFactor2 : public NoiseModelFactor2<Pose3, Pose3>\n  {\n\n    using X = Pose3;\n    using Base = NoiseModelFactor2<Pose3, Pose3>;\n    using This = LidarPlaneFactor2;\n\n  public:\n    LidarPlaneFactor2(Key key1, Key key2, const Point3 &point1, const Point3 &unit, const Point3 &point2, const SharedNoiseModel &model)\n        : Base(model, key1, key2), p1_(point1), p2_(point2), u_(unit.normalized())\n    {\n    }\n\n    virtual ~LidarPlaneFactor2() {}\n\n    /*\n    d(R*u)/dT =  R*[[-u]x 03x3]\n    d(T*p)/dT =  R*[[-p]x I3x3]\n\n    plane_err = (p2w-p1).dot(u)\n              = (T2*p2 - p1).dot(u)\n    dplane_err/dT2 = u'*d(T2*p2)/dT2 = u'*R2*[[-p2]x I3x3]\n    */\n\n    /*\n    d(R*u)/dT =  R*[[-u]x 03x3]\n    d(T*p)/dT =  R*[[-p]x I3x3]\n\n    plane_err = (p2w-p1w).dot(uw)\n              = (T2*p2 - T1*p1).dot(R1*u)\n    dplane_err/dT1 = (T2*p2 - T1*p1)'* d(R1*u)/dT1 - (R1*u)'*d(T1*p1)/dT1\n    dplane_err/dT2 = (R1*u)'*d(T2*p2)/dT2\n    */\n\n    Vector evaluateError(const X &pose1, const X &pose2,\n                         boost::optional<Matrix&> H1 = boost::none,\n                         boost::optional<Matrix&> H2 = boost::none) const\n    {\n      const auto &rotation1 = pose1.rotation().matrix();\n      const auto &rotation2 = pose2.rotation().matrix();\n      const auto p12w = pose2.transformFrom(p2_) - pose1.transformFrom(p1_);\n      const auto uw = rotation1 * u_;\n      if (H1)\n        *H1 = p12w.transpose() * rotation1 * (Matrix36() << skewSymmetric(-u_[0], -u_[1], -u_[2]), Z_3x3).finished()\n            - uw.transpose() * rotation1 * (Matrix36() << skewSymmetric(-p1_[0], -p1_[1], -p1_[2]), I_3x3).finished();\n      if (H2)\n        *H2 = uw.transpose() * rotation2 * (Matrix36() << skewSymmetric(-p2_[0], -p2_[1], -p2_[2]), I_3x3).finished();\n      return Vector1(p12w.dot(uw));\n    }\n\n    virtual NonlinearFactor::shared_ptr clone() const\n    {\n      return boost::static_pointer_cast<NonlinearFactor>(\n          NonlinearFactor::shared_ptr(new This(*this)));\n    }\n\n    virtual bool equals(const NonlinearFactor &expected, double tol = 1e-9) const\n    {\n      const This *e = dynamic_cast<const This *>(&expected);\n      return e != nullptr && Base::equals(*e, tol) && traits<Point3>::Equals(p1_, e->p1_, tol) &&\n             traits<Point3>::Equals(p2_, e->p2_, tol) && traits<Point3>::Equals(u_, e->u_, tol);\n    }\n\n    virtual void print(const std::string &s = \"\",\n                       const KeyFormatter &keyFormatter = DefaultKeyFormatter) const\n    {\n      cout << s << \":\\nLidarPlaneFactor2 on (\" << keyFormatter(key1())\n           << \", \" << keyFormatter(key2()) << \")\\n\"\n           << \"  Plane Point: \" << p1_.transpose() << \"\\n\"\n           << \"  Plane norm Axis: \" << u_.transpose() << \"\\n\"\n           << \"  Match Point: \" << p2_.transpose() << \"\\n\";\n      noiseModel_->print(\"  noise model: \");\n    }\n\n  private:\n    Point3 p1_, p2_, u_;\n  }; // class LidarPlaneFactor2\n\n  class LidarPlaneFactor1 : public NoiseModelFactor1<Pose3>\n  {\n\n    using X = Pose3;\n    using Base = NoiseModelFactor1<Pose3>;\n    using This = LidarPlaneFactor1;\n\n  public:\n    LidarPlaneFactor1(Key key, const Point3 &point1, const Point3 &unit, const Point3 &point2, const SharedNoiseModel &model)\n        : Base(model, key), p1_(point1), p2_(point2), u_(unit.normalized())\n    {\n    }\n\n    virtual ~LidarPlaneFactor1() {}\n\n    /*\n    d(R*u)/dT =  R*[[-u]x 03x3]\n    d(T*p)/dT =  R*[[-p]x I3x3]\n\n    plane_err = (p2w-p1).dot(u)\n              = (T2*p2 - p1).dot(u)\n    dplane_err/dT2 = u'*d(T2*p2)/dT2 = u'*R2*[[-p2]x I3x3]\n    */\n\n    /*\n    d(R*u)/dT =  R*[[-u]x 03x3]\n    d(T*p)/dT =  R*[[-p]x I3x3]\n\n    plane_err = (p2w-p1w).dot(uw)\n              = (T2*p2 - T1*p1).dot(R1*u)\n    dplane_err/dT1 = (T2*p2 - T1*p1)'* d(R1*u)/dT1 - (R1*u)'*d(T1*p1)/dT1\n    dplane_err/dT2 = (R1*u)'*d(T2*p2)/dT2\n    */\n\n    /*\n    d(R*u)/dT =  R*[[-u]x 03x3]\n    d(T*p)/dT =  R*[[-p]x I3x3]\n\n    plane_err = (p2w-p1).dot(u)\n              = (T2*p2 - p1).dot(u)\n    dplane_err/dT2 = u'*d(T2*p2)/dT2 = u'*R2*[[-p2]x I3x3]\n    */\n\n    Vector evaluateError(const X &pose,\n                         boost::optional<Matrix&> H = boost::none) const\n    {\n      const auto &rotation = pose.rotation();\n      if (H)\n        *H = u_.transpose() * rotation.matrix() * (Matrix36() << skewSymmetric(-p2_[0], -p2_[1], -p2_[2]), I_3x3).finished();\n      return Vector1((pose.transformFrom(p2_) - p1_).dot(u_));\n    }\n\n    virtual NonlinearFactor::shared_ptr clone() const\n    {\n      return boost::static_pointer_cast<NonlinearFactor>(\n          NonlinearFactor::shared_ptr(new This(*this)));\n    }\n\n    virtual bool equals(const NonlinearFactor &expected, double tol = 1e-9) const\n    {\n      const This *e = dynamic_cast<const This *>(&expected);\n      return e != nullptr && Base::equals(*e, tol) && traits<Point3>::Equals(p1_, e->p1_, tol) &&\n             traits<Point3>::Equals(p2_, e->p2_, tol) && traits<Point3>::Equals(u_, e->u_, tol);\n    }\n\n    virtual void print(const std::string &s = \"\",\n                       const KeyFormatter &keyFormatter = DefaultKeyFormatter) const\n    {\n      cout << s << \":\\nLidarPlaneFactor1 on (\" << keyFormatter(key()) <<  \")\\n\"\n           << \"  Plane Point: \" << p1_.transpose() << \"\\n\"\n           << \"  Plane norm Axis: \" << u_.transpose() << \"\\n\"\n           << \"  Match Point: \" << p2_.transpose() << \"\\n\";\n      noiseModel_->print(\"  noise model: \");\n    }\n\n  private:\n    Point3 p1_, p2_, u_;\n  }; // class LidarPlaneFactor1\n\n} // namespace gtsam\n", "meta": {"hexsha": "44c355f1cedc88b9acdae9ee84cef9405cd1bfac", "size": 5631, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/include/factors/LidarPlaneFactor.hpp", "max_stars_repo_name": "Saki-Chen/W-LOAM", "max_stars_repo_head_hexsha": "39ad29da0db760401c06d17c22a0e43d8562efec", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2021-08-24T02:24:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T09:56:10.000Z", "max_issues_repo_path": "src/include/factors/LidarPlaneFactor.hpp", "max_issues_repo_name": "xingchengzhi/W-LOAM", "max_issues_repo_head_hexsha": "eca5c1932fc48b0d4f47cfd7bc85c874afd09631", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-11-01T03:41:16.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-24T12:33:35.000Z", "max_forks_repo_path": "src/include/factors/LidarPlaneFactor.hpp", "max_forks_repo_name": "xingchengzhi/W-LOAM", "max_forks_repo_head_hexsha": "eca5c1932fc48b0d4f47cfd7bc85c874afd09631", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2021-10-30T05:11:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T08:59:59.000Z", "avg_line_length": 33.7185628743, "max_line_length": 136, "alphanum_fraction": 0.5604688332, "num_tokens": 1877, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.46076346440161353}}
{"text": "#include \"SignedDistance.h\"\n#include \"PointTriangleDistance.h\"\n#include <boost/assert.hpp>\n\nusing namespace MeshSdf;\n\nSignedDistance::SignedDistance(Mesh mesh)\n\t: mesh(std::forward<Mesh>(mesh))\n\t, meshadj(this->mesh.tris, static_cast<int>(this->mesh.verts.size()))\n\t, usdist(this->mesh.verts, this->mesh.tris)\n{\n}\n\ndouble SignedDistance::operator()(double x, double y, double z) const\n{\n\tauto udinfo = usdist(x, y, z, 0);\n\n\tauto pnormal = PseudoNormal(udinfo.triEntityNearest, udinfo.triNearest);\n\tauto qc = Vec3{ x,y,z } - udinfo.triPtNearest;\n\tauto sign = boost::math::sign(qc.Dot(pnormal));\n\n\treturn sign * udinfo.udist;\n}\n\nVec3 SignedDistance::PseudoNormal_Vertex(int vnearest) const\n{\n\tVec3 pnormal{ 0.0, 0.0, 0.0 };\n\n\tauto trisadj = meshadj.Vert2Tris(vnearest);\n\tBOOST_ASSERT_MSG(!trisadj.empty(), \"no incident triangles\");\n\n\tfor (auto itriadj : trisadj)\n\t{\n\t\tauto const& triadj = mesh.tris.at(itriadj);\n\n\t\t// find other 2 vertices of tri\n\t\tauto edgevert0 = -1;\n\t\tauto edgevert1 = -1;\n\n\t\tif (vnearest == triadj[0])\n\t\t{\n\t\t\tedgevert0 = triadj[1];\n\t\t\tedgevert1 = triadj[2];\n\t\t}\n\t\telse if (vnearest == triadj[1])\n\t\t{\n\t\t\tedgevert0 = triadj[0];\n\t\t\tedgevert1 = triadj[2];\n\t\t}\n\t\telse if (vnearest == triadj[2])\n\t\t{\n\t\t\tedgevert0 = triadj[0];\n\t\t\tedgevert1 = triadj[1];\n\t\t}\n\t\telse\n\t\t{\n\t\t\tBOOST_ASSERT_MSG(false, \"no nearest vertex\");\n\t\t}\n\n\t\t// weigh triangle normal by incident angle at nearest vertex\n\t\tauto edge1 = mesh.verts.at(edgevert0) - mesh.verts.at(vnearest);\n\t\tauto edge2 = mesh.verts.at(edgevert1) - mesh.verts.at(vnearest);\n\n\t\tauto incidentAngle = acos(edge1.Dot(edge2) / (edge1.Norm()*edge2.Norm()));\n\t\tpnormal += incidentAngle * mesh.triNormals.at(itriadj);\n\t}\n\n\treturn pnormal.Normalized();\n}\n\nVec3 SignedDistance::PseudoNormal_Edge(NearestTriEntity ent, int tri) const\n{\n\tauto const& triadj = mesh.tris.at(tri);\n\n\t// find edge vertices\n\tauto nearestvert0 = -1;\n\tauto nearestvert1 = -1;\n\n\tif (ent == NearestTriEntity::Edge0)\n\t{\n\t\tnearestvert0 = triadj[0];\n\t\tnearestvert1 = triadj[1];\n\t}\n\telse if (ent == NearestTriEntity::Edge1)\n\t{\n\t\tnearestvert0 = triadj[1];\n\t\tnearestvert1 = triadj[2];\n\t}\n\telse if (ent == NearestTriEntity::Edge2)\n\t{\n\t\tnearestvert0 = triadj[2];\n\t\tnearestvert1 = triadj[0];\n\t}\n\n\t// equal weight for triangle normal of both adjacent triangles\n\tauto adjtris = meshadj.Edge2Tris(nearestvert0, nearestvert1);\n\n\tBOOST_ASSERT_MSG(adjtris.size() == 1 || adjtris.size() == 2,\n\t\t\"invalid number of incident triangles\");\n\n\tVec3 pnormal{ 0.0, 0.0 };\n\n\tfor (auto adjtri : adjtris)\n\t{\n\t\tpnormal += mesh.triNormals.at(adjtri);\n\t}\n\n\treturn pnormal.Normalized();\n}\n\nVec3 SignedDistance::PseudoNormal(NearestTriEntity ent, int tri) const\n{\n\tswitch (ent)\n\t{\n\t\tcase NearestTriEntity::Vert0: return PseudoNormal_Vertex(mesh.tris.at(tri)[0]);\n\t\tcase NearestTriEntity::Vert1: return PseudoNormal_Vertex(mesh.tris.at(tri)[1]);\n\t\tcase NearestTriEntity::Vert2: return PseudoNormal_Vertex(mesh.tris.at(tri)[2]);\n\t\tcase NearestTriEntity::Edge0:\n\t\tcase NearestTriEntity::Edge1:\n\t\tcase NearestTriEntity::Edge2: return PseudoNormal_Edge(ent, tri);\n\t\tcase NearestTriEntity::Face: return mesh.triNormals.at(tri);\n\t\tdefault: throw std::runtime_error{\"unknown entity\"};\n\t}\n\n\treturn {};\n}\n", "meta": {"hexsha": "bb20dd97805b4822f738256848a4531512fb16d8", "size": 3182, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/SignedDistance.cpp", "max_stars_repo_name": "Kai-46/MeshSdf", "max_stars_repo_head_hexsha": "970fe65020cc2a9b76787391e7734c3c70a21e20", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 75.0, "max_stars_repo_stars_event_min_datetime": "2019-04-10T21:18:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T06:13:41.000Z", "max_issues_repo_path": "lib/SignedDistance.cpp", "max_issues_repo_name": "Kai-46/MeshSdf", "max_issues_repo_head_hexsha": "970fe65020cc2a9b76787391e7734c3c70a21e20", "max_issues_repo_licenses": ["MIT"], "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/SignedDistance.cpp", "max_forks_repo_name": "Kai-46/MeshSdf", "max_forks_repo_head_hexsha": "970fe65020cc2a9b76787391e7734c3c70a21e20", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2019-08-02T06:51:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-20T03:28:10.000Z", "avg_line_length": 25.0551181102, "max_line_length": 81, "alphanum_fraction": 0.7011313639, "num_tokens": 1008, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4607634589960489}}
{"text": "#include <iostream>\n#include \"turn_cost_grid_dijkstra.h\"\n#include \"DFieldId.h\"\n#include <fstream>\n#include <boost/algorithm/string.hpp>\n\nint\nmain()\n{\n  using namespace turncostgrid;\n  std::vector<GridCoordinate> coords;\n  std::string filename{\n          \"/home/doms/Repositories/IBR-SVN/thesis-alg-2015-krupke-ma-robots/MasterThesis/ALENEX/Code/gridgraph/apx/p_1400_dense_2.gg\"};\n  std::ifstream file(filename);\n  if (file.is_open()) {\n    std::string line;\n    while (std::getline(file, line)) {\n      if (line.empty()) { continue; }\n      if (line.at(0) == '#') { continue; }\n      std::vector<std::string> tokens;\n      boost::split(tokens, line, boost::is_any_of(\" \"));\n      if (tokens.size() >= 2) {\n        coords.push_back({std::stoi(tokens[0]), std::stoi(tokens[1])});\n      }\n    }\n    file.close();\n  } else {\n    std::cerr << \"Could not load grid graph from file \\\"\" << filename << \"\\\"\" << std::endl;\n  }\n  std::sort(coords.begin(), coords.end());\n\n  //std::vector<GridCoordinate> g{{0,0},{1,0}, {1,1}, {0,1}, {0,2}};\n  // std::sort(g.begin(), g.end());\n  GridGraph gd{coords, true};\n  gd.print_graph(coords);\n\n  for (unsigned int i = 0; i < coords.size(); ++i) {\n    TurnCostGridDijkstra lgd{gd, {3, 1}, i, NORTH};\n    lgd.lazy_dijkstra([&](int id, Direction d) {\n        //std::cout << id << \" \" << to_string(d) << \": \" << lgd.distance(state, id, d) << std::endl;\n        return true;\n    });\n  }\n\n  return 0;\n}", "meta": {"hexsha": "ae5e3b1efc8b1f10fd5f2b71808614146e2a32a1", "size": 1425, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/shortest_path/main.cpp", "max_stars_repo_name": "d-krupke/turncost", "max_stars_repo_head_hexsha": "2bbe1f1b31eddca5c6e686988e715be7d76c37a3", "max_stars_repo_licenses": ["MIT"], "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/shortest_path/main.cpp", "max_issues_repo_name": "d-krupke/turncost", "max_issues_repo_head_hexsha": "2bbe1f1b31eddca5c6e686988e715be7d76c37a3", "max_issues_repo_licenses": ["MIT"], "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/shortest_path/main.cpp", "max_forks_repo_name": "d-krupke/turncost", "max_forks_repo_head_hexsha": "2bbe1f1b31eddca5c6e686988e715be7d76c37a3", "max_forks_repo_licenses": ["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.9782608696, "max_line_length": 135, "alphanum_fraction": 0.5936842105, "num_tokens": 431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872243177518, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4607544544000886}}
{"text": "#define BOOST_TEST_MODULE blas\n\n#include <boost/test/unit_test.hpp>\n#include <boost/test/test_case_template.hpp>\n#include <boost/mpl/list.hpp>\n\n\n#include <mla/vector/all.h++>\n\n#include <mla/operations/level1/scale.h++>\n\n\ntypedef boost::mpl::list<\n\tmla::vector::Dense<float>,\n\tmla::vector::Dense<double>,\n\tmla::vector::SparseCS<float>,\n\tmla::vector::SparseCS<double>\n> vector_type_list;\n\n\n\nBOOST_AUTO_TEST_SUITE(test_boost_level1)\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( blas_level1_test_scale_one, VectorType, vector_type_list )\n{\n\tusing namespace mla;\n\n\tVectorType x(3);\n\tx.setValue(0, 1.0f);\n\tx.setValue(1, 1.0f);\n\tx.setValue(2, 1.0f);\n\n\ttypename VectorType::scalar_type value = 1.0f;\n\tscale( value, x);\n\n\tfor( unsigned int i = 0; i < x.size(); i++)\n\t{\n\t\tBOOST_CHECK_CLOSE(x.getValue(i), 1.0f, 1e-6f);\n\t}\n}\n\n\n\nBOOST_AUTO_TEST_SUITE_END()\n\n", "meta": {"hexsha": "7690204c61b9d6f0f59d24a0bce5f40e95854297", "size": 834, "ext": "c++", "lang": "C++", "max_stars_repo_path": "unit_tests/test_blas_level1_scale.c++", "max_stars_repo_name": "ruimaciel/mla", "max_stars_repo_head_hexsha": "b05f5913067af31a345cd2187de25871dbe31856", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "unit_tests/test_blas_level1_scale.c++", "max_issues_repo_name": "ruimaciel/mla", "max_issues_repo_head_hexsha": "b05f5913067af31a345cd2187de25871dbe31856", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unit_tests/test_blas_level1_scale.c++", "max_forks_repo_name": "ruimaciel/mla", "max_forks_repo_head_hexsha": "b05f5913067af31a345cd2187de25871dbe31856", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.7446808511, "max_line_length": 89, "alphanum_fraction": 0.721822542, "num_tokens": 249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4607544475092445}}
{"text": "#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/connected_components.hpp>\n#include <boost/graph/strong_components.hpp>\n#include <boost/graph/random.hpp>\n#include <boost/random.hpp>\n#include <stack>\n#include <iostream>\n#include <vector>\n\n//==============================================================================\nstruct node_properties\n{\n    int component;\n};\nstruct edge_properties\n{\n};\nstruct graph_properties\n{\n    int number_of_components;\n};\n\n//--------------------------------------\ntypedef boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS,\n                              node_properties, edge_properties, graph_properties>\n    graph_t;\ntypedef typename boost::graph_traits<graph_t>::vertex_descriptor vertex_t;\ntypedef typename boost::graph_traits<graph_t>::edge_descriptor edge_t;\n\n//==============================================================================\nvoid print_graph(const graph_t &graph)\n{\n    std::cout << \"Graph:\" << std::endl;\n    auto edges = boost::edges(graph);\n    for (auto it = edges.first; it != edges.second; ++it)\n    {\n        std::cout << boost::source(*it, graph) << \" -> \"\n                  << boost::target(*it, graph) << std::endl;\n    }\n}\n\n//==============================================================================\nvoid print_components(const graph_t &graph)\n{\n    std::cout << \"\\nComponents: \"\n              << graph[boost::graph_bundle].number_of_components << std::endl;\n    auto nodes = boost::vertices(graph);\n    for (auto it = nodes.first; it != nodes.second; ++it)\n    {\n        std::cout << \"Node: \" << *it << \" component: \" << graph[*it].component\n                  << std::endl;\n    }\n}\n\n//==============================================================================\nvoid strong_components(graph_t &graph)\n{\n    std::vector<edge_t> temp_edges;\n\n    auto edges = boost::edges(graph);\n\n    for (auto it = edges.first; it != edges.second; ++it)\n    {\n        auto pair = boost::add_edge(boost::target(*it, graph),\n                                    boost::source(*it, graph),\n                                    graph);\n        temp_edges.push_back(pair.first);\n    }\n\n    graph[boost::graph_bundle].number_of_components =\n        boost::strong_components(graph,\n                                 boost::get(&node_properties::component, graph));\n\n    for (const auto &e : temp_edges)\n    {\n        boost::remove_edge(e, graph);\n    }\n}\n\n//==============================================================================\n\ngraph_t graph;\nstd::vector<vertex_t> vertices;\n\nint nn = 10;\nstd::vector<int> r_index(nn, 0);\nstd::stack<int> S;\nint vindex = 1;\nint c = nn - 1;\n\nvoid visit(int v)\n{\n    bool root = true;\n    r_index[v] = vindex;\n    vindex = vindex + 1;\n    auto edges = boost::edges(graph);\n    for (auto it = edges.first; it != edges.second; ++it)\n    {\n        int w = boost::target(*it, graph);\n        int s = boost::source(*it, graph);\n        if (v == s)\n        {\n            // std::cout << \"\\n Visit for node: \" << v << \", edge: \" << s << \"->\" << w << \"\\n\";\n            if (r_index[w] == 0)\n            {\n                visit(w);\n            }\n            if (r_index[w] < r_index[v])\n\n            {\n                r_index[v] = r_index[w];\n                root = false;\n            }\n        }\n    }\n    if (root)\n    {\n        vindex = vindex - 1;\n        std::cout << \"scc: \";\n        while (!S.empty() && (r_index[v] <= r_index[S.top()]))\n        {\n            int w = S.top();\n            S.pop();\n            std::cout << \"\" << w;\n            r_index[w] = c;\n            vindex = vindex - 1;\n        }\n        std::cout << v << \"\\n\";\n        r_index[v] = c;\n        c = c - 1;\n    }\n    else\n    {\n        S.push(v);\n    }\n}\n\n//==============================================================================\nint main()\n{\n\n    ///graph 1\n\n    // vertices.push_back(boost::add_vertex(graph));\n    // vertices.push_back(boost::add_vertex(graph));\n    // vertices.push_back(boost::add_vertex(graph));\n    // vertices.push_back(boost::add_vertex(graph));\n    // vertices.push_back(boost::add_vertex(graph));\n    // vertices.push_back(boost::add_vertex(graph));\n\n    // boost::add_edge(vertices.at(0), vertices.at(1), graph);\n    // boost::add_edge(vertices.at(1), vertices.at(2), graph);\n    // boost::add_edge(vertices.at(2), vertices.at(0), graph);\n    // boost::add_edge(vertices.at(2), vertices.at(3), graph);\n    // boost::add_edge(vertices.at(3), vertices.at(4), graph);\n    // boost::add_edge(vertices.at(4), vertices.at(5), graph);\n    // boost::add_edge(vertices.at(5), vertices.at(3), graph);\n\n    //graph2\n    vertices.push_back(boost::add_vertex(graph));\n    vertices.push_back(boost::add_vertex(graph));\n    vertices.push_back(boost::add_vertex(graph));\n    vertices.push_back(boost::add_vertex(graph));\n    vertices.push_back(boost::add_vertex(graph));\n    vertices.push_back(boost::add_vertex(graph));\n    vertices.push_back(boost::add_vertex(graph));\n    vertices.push_back(boost::add_vertex(graph));\n    vertices.push_back(boost::add_vertex(graph));\n    vertices.push_back(boost::add_vertex(graph));\n    boost::add_edge(vertices.at(0), vertices.at(4), graph);\n    boost::add_edge(vertices.at(0), vertices.at(1), graph);\n    boost::add_edge(vertices.at(4), vertices.at(0), graph);\n    boost::add_edge(vertices.at(4), vertices.at(1), graph);\n    boost::add_edge(vertices.at(4), vertices.at(5), graph);\n    boost::add_edge(vertices.at(5), vertices.at(6), graph);\n    boost::add_edge(vertices.at(6), vertices.at(4), graph);\n    boost::add_edge(vertices.at(1), vertices.at(2), graph);\n    boost::add_edge(vertices.at(2), vertices.at(7), graph);\n    boost::add_edge(vertices.at(2), vertices.at(3), graph);\n    boost::add_edge(vertices.at(3), vertices.at(1), graph);\n    boost::add_edge(vertices.at(8), vertices.at(9), graph);\n    boost::add_edge(vertices.at(9), vertices.at(8), graph);\n    /*\n  boost::add_edge(vertices.at(0), vertices.at(1), graph);\n  boost::add_edge(vertices.at(2), vertices.at(3), graph);\n  boost::add_edge(vertices.at(3), vertices.at(4), graph);\n  boost::add_edge(vertices.at(4), vertices.at(5), graph);\n  boost::add_edge(vertices.at(7), vertices.at(8), graph);\n  boost::add_edge(vertices.at(8), vertices.at(9), graph);\n  boost::add_edge(vertices.at(9), vertices.at(7), graph);*/\n    boost::mt19937 rng;\n    //boost::generate_random_graph(graph, nn, 8, rng);\n    size_t e = boost::num_edges(graph);\n    size_t n = boost::num_vertices(graph);\n    std::cout << \"generated \" << e << \" edges, \" << n << \" vertices\\n\";\n\n    graph[boost::graph_bundle].number_of_components =\n        boost::connected_components(graph,\n                                    boost::get(&node_properties::component, graph));\n\n    for (int i = 0; i < nn; i++)\n    {\n        if (r_index[i] == 0)\n        {\n            visit(i);\n        }\n    }\n\n    std::cout\n        << \"\\n Components number SCC1: ----------\" << c - 1 << \"\\n\"\n        << std::endl;\n    for (auto i = r_index.begin(); i != r_index.end(); ++i)\n        std::cout << *i << ' ';\n    //std::cout << \"\\n ***************************************\" << std::endl;\n    //std::cout << \"\\nTrue boost graph implementation : \\n----------------------\" << std::endl;\n    //strong_components(graph);\n    //print_graph(graph);\n    //print_components(graph);\n}\n", "meta": {"hexsha": "19d358486da24b3c80a438a3213810297b446cd5", "size": 7315, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "old_work/boost2.cpp", "max_stars_repo_name": "andreicap/sccaa", "max_stars_repo_head_hexsha": "283bea6b644f2cc5dc982ec5db456ea60fdaf6a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "old_work/boost2.cpp", "max_issues_repo_name": "andreicap/sccaa", "max_issues_repo_head_hexsha": "283bea6b644f2cc5dc982ec5db456ea60fdaf6a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "old_work/boost2.cpp", "max_forks_repo_name": "andreicap/sccaa", "max_forks_repo_head_hexsha": "283bea6b644f2cc5dc982ec5db456ea60fdaf6a0", "max_forks_repo_licenses": ["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.25, "max_line_length": 95, "alphanum_fraction": 0.5324675325, "num_tokens": 1751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4607544475092444}}
{"text": "/*\n\n  C\u00f3digo con grafo ya establecido (se encuentra en el main)\n  Se realizan y se calcula el tiempo de insertar un vertice y una arista, eliminar un vertice y una arista, DFS, BFS, Prim, Kruskal, Dijkstra y Floyd Warshall\n  Equipo: Sebasti\u00e1n Medina  y Carlos de la Garza\n\n*/\n\n\n#include <iostream>\n#include <deque>\n#include <iterator>\n#include <vector>\n#include <time.h>\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/graph/prim_minimum_spanning_tree.hpp>\n#include <boost/graph/depth_first_search.hpp>\n#include <boost/graph/breadth_first_search.hpp>\n#include <boost/graph/kruskal_min_spanning_tree.hpp>\n#include <boost/graph/floyd_warshall_shortest.hpp>\n#include <boost/graph/exterior_property.hpp>\n\nusing namespace std;\nusing namespace boost;\n\nstruct node{\n    float id;\n};\n\ntypedef property<edge_weight_t, float> EdgeWeightProperty;\ntypedef adjacency_list<listS,vecS,directedS,node,EdgeWeightProperty> DirectedGraph;\ntypedef property_map<DirectedGraph, edge_weight_t>::type EdgeWeightMap;\ntypedef graph_traits<DirectedGraph>::vertex_descriptor vertex_descriptor;\ntypedef graph_traits < DirectedGraph >::edge_descriptor edge_descriptor;\ntypedef exterior_vertex_property<DirectedGraph, float> DistanceProperty;\ntypedef DistanceProperty::matrix_type DistanceMatrix;\ntypedef DistanceProperty::matrix_map_type DistanceMatrixMap;\ntypedef pair<int, int> Edge;\n\n\nvertex_descriptor addVertex(DirectedGraph & g, int n)\n{\n    vertex_descriptor v0 = add_vertex(g);\n    g[v0].id = n;\n    return v0;\n}\n\nvoid addEdge(int vertex1, int vertex2, float weight, DirectedGraph & g)\n{\n    add_edge(vertex1-1, vertex2-1, weight, g);\n}\n\nbool vertexExists(DirectedGraph & g, int n, int & t)\n{\n   int pos = 0;\n   DirectedGraph::vertex_iterator start,end;\n   for(tie(start,end) = vertices(g); start!=end; start++)\n   {\n       if(g[*start].id == n)\n       {\n           t = pos;\n           return true;\n       }\n       pos++;\n   }\n   return false;\n}\n\nbool edgeExists(DirectedGraph & g, int v1, int v2, float w)\n{\n   DirectedGraph::edge_iterator edgeIt, edgeEnd;\n   for (tie(edgeIt, edgeEnd) = edges(g); edgeIt != edgeEnd; ++edgeIt)\n   {\n       if(source(*edgeIt, g) == v1 && target(*edgeIt, g) == v2 && get(edge_weight, g, *edgeIt) == w)\n           return true;\n   }\n   return false;\n}\n\n\nvoid insertarVertice(DirectedGraph & g){\n  clock_t t;\n  int vertice;\n  cout << \"Ingrese el nodo que quiera agregar: \";\n  while(!(cin >> vertice)){\n    cin.clear();\n    cin.ignore(numeric_limits<streamsize>::max(), '\\n');\n    cout << \"Intente otra vez: \";\n    }\n  int posicion;\n  if(vertexExists(g, vertice, posicion)) {\n     cout << \"El v\u00e9rtice: \" << vertice << \" ya existe\" << endl;\n  } else {\n    t = clock();\n    vertex_descriptor v0 = addVertex(g,vertice);\n    t = clock() - t;\n    double time_taken = ((double)t)/CLOCKS_PER_SEC;\n    printf(\"Tiempo en insertar v\u00e9rtice: %f ms \\n\", time_taken*1000);\n  }\n  cout << \"\" << endl;\n}\n\nvoid insertarArista(DirectedGraph & g){\n  clock_t t;\n  bool negativeEdge = false;\n  bool unDirected = false;\n  float v1, v2;\n  int pos1, pos2;\n  cout << \"V\u00e9rtice 1: \";\n  while(!(cin >> v1)){\n    cin.clear();\n    cin.ignore(numeric_limits<streamsize>::max(), '\\n');\n    cout << \"Entrada inv\u00e1lida, intenta otra vez: \";\n  }\n  if(!vertexExists(g, v1, pos1)) {\n    cout << \"El v\u00e9rtice con id \" << v1 << \" no existe, debe crearse antes\" << endl;\n  } else {\n      cin.ignore();\n      cout << \"V\u00e9rtice 2: \";\n        while(!(cin >> v2)){\n          cin.clear();\n          cin.ignore(numeric_limits<streamsize>::max(), '\\n');\n          cout << \"Entrada inv\u00e1lida, intenta otra vez: \";\n        }\n        if(!vertexExists(g, v2, pos2)) {\n          cout << \"El v\u00e9rtice con id \" << v2 << \" no existe, debe crearse antes \" << endl;\n        } else {\n            float weight;\n            cin.ignore();\n            cout << \"Peso de la arista a insertar: \";\n            while(!(cin >> weight)){\n              cin.clear();\n              cin.ignore(numeric_limits<streamsize>::max(), '\\n');\n              cout << \"Entrada inv\u00e1lida, intenta otra vez: \";\n            }\n      EdgeWeightProperty w = weight;\n      if(edgeExists(g,pos1,pos2,weight)) {\n        cout << \"La arista de \" << pos1 << \" a \" << pos2 << \" con peso \" << weight << \" ya existe\" << endl;\n      } else {\n        if(weight < 0) {\n          negativeEdge = true;\n          cout << \"No se pueden agregar aristas negativas\" << endl;\n        }\n        t = clock();\n        add_edge(pos1,pos2,w,g);\n        if(unDirected){\n          add_edge(pos2,pos1,w,g);\n        }\n        t = clock() - t;\n        double time_taken = ((double)t)/CLOCKS_PER_SEC;\n        printf(\"Tiempo en insertar arista: %f ms \\n\", time_taken*1000);\n      }\n    }\n  }\n  cout << \"\" << endl;\n}\n\nvoid eliminarVertice(DirectedGraph & g){\n  clock_t t;\n  float vertice;\n  int pos;\n  cout << \"Ingrese el nodo que quiera borrar: \";\n  while(!(cin >> vertice)){\n    cin.clear();\n    cin.ignore(numeric_limits<streamsize>::max(), '\\n');\n    cout << \"Entrada inv\u00e1lida, intenta otra vez: \";\n  }\n  if(vertexExists(g, vertice, pos)){\n    graph_traits<DirectedGraph>::vertex_iterator start,end,next;\n    tie(start, end) = vertices(g);\n    for (next = start; start != end; start = next) {\n      ++next;\n      if(g[*start].id == vertice){\n        t = clock();\n        clear_vertex(*start, g);\n        remove_vertex(*start,g);\n        t = clock() - t;\n        double time_taken = ((double)t)/CLOCKS_PER_SEC;\n        printf(\"Tiempo en borrar v\u00e9rtice: %f ms \\n\", time_taken*1000);\n      }\n    }\n  } else {\n      cout << \"El v\u00e9rtice con id \" << vertice << \" no existe \" << endl;\n  }\n  cout << \"\" << endl;\n}\n\nvoid eliminarArista(DirectedGraph & g){\n  clock_t t;\n  float v1,v2;\n  int pos1,pos2;\n  cout << \"Id del v\u00e9rtice 1 conectado por la arista: \";\n  while(!(cin >> v1)){\n    cin.clear();\n    cin.ignore(numeric_limits<streamsize>::max(), '\\n');\n    cout << \"Entrada inv\u00e1lida, intenta otra vez: \";\n  }\n  if(vertexExists(g, v1,pos1)) {\n    cin.ignore();\n    cout << \"Id del v\u00e9rtice 2 conectado por la arista: \";\n    while(!(cin >> v2)){\n      cin.clear();\n      cin.ignore(numeric_limits<streamsize>::max(), '\\n');\n      cout << \"Entrada inv\u00e1lida, intenta otra vez: \";\n    }\n    if(vertexExists(g, v2,pos2)){\n      if(edge(pos1,pos2,g).second){\n        pair<DirectedGraph::edge_descriptor, bool> retrievedEdge = edge(pos1, pos2, g);\n        t = clock();\n        remove_edge(retrievedEdge.first,g);\n        t = clock() - t;\n        double time_taken = ((double)t)/CLOCKS_PER_SEC;\n        printf(\"Tiempo en borrar arista: %f ms \\n\", time_taken*1000);\n      } else {\n          cout << \"La arista de \" << v1 << \" a \" << v2 << \" no existe\" << endl;\n      }\n    } else {\n        cout << \"El v\u00e9rtice con id \" << v2 << \" no existe \" << endl;\n      }\n  } else {\n      cout << \"El v\u00e9rtice con id \" << v1 << \" no existe \" << endl;\n  }\n  cout << \"\" << endl;\n}\n\nvoid DFS(DirectedGraph & g){\n\n  clock_t t;\n  default_dfs_visitor vis;\n  t = clock();\n  depth_first_search(g, visitor(vis));\n  t = clock() - t;\n  double time_taken = ((double)t)/CLOCKS_PER_SEC;\n  printf(\"Tiempo de DFS: %f ms \\n\", time_taken*1000);\n  cout << \"\" << endl;\n\n}\n\nvoid BFS(DirectedGraph & g){\n\n  clock_t t;\n  default_bfs_visitor vis;\n  t = clock();\n  breadth_first_search(g, vertex(0, g), visitor(vis));\n  t = clock() - t;\n  double time_taken = ((double)t)/CLOCKS_PER_SEC;\n  printf(\"Tiempo de BFS: %f ms \\n\", time_taken*1000);\n  cout << \"\" << endl;\n\n\n}\n\nvoid Prim(DirectedGraph & g){\n\n  clock_t t;\n  vector <vertex_descriptor> p(num_vertices(g));\n  t = clock();\n  prim_minimum_spanning_tree(g, &p[0]);\n  t = clock() - t;\n  double time_taken = ((double)t)/CLOCKS_PER_SEC;\n  printf(\"Tiempo de Prim: %f ms \\n\", time_taken*1000);\n\n  cout << \"\" << endl;\n\n  for (size_t i = 0; i != p.size(); ++i)\n  {\n      if (p[i] != i)\n          cout << g[p[i]].id << \" --- \" << g[i].id << endl;\n      else\n          cout << \"start -> \" << g[i].id << endl;\n  }\n\n  cout << \"\" << endl;\n\n}\n\nvoid Kruskal(DirectedGraph & g){\n\n  clock_t t;\n  property_map<DirectedGraph, edge_weight_t>::type weight = get(edge_weight, g);\n  vector <edge_descriptor> spanning_tree;\n  t = clock();\n  kruskal_minimum_spanning_tree(g, back_inserter(spanning_tree));\n  t = clock() - t;\n  double time_taken = ((double)t)/CLOCKS_PER_SEC;\n  printf(\"Tiempo de Kruskal: %f ms \\n\", time_taken*1000);\n  cout << \"\" << endl;\n\n}\n\nvoid Dijkstra(DirectedGraph & g){\n\n  clock_t t;\n  vector<vertex_descriptor> p(num_vertices(g));\n  vector<int> d(num_vertices(g));\n  vertex_descriptor s = vertex(0, g);\n  t = clock();\n  dijkstra_shortest_paths(g, s, predecessor_map(&p[0]).distance_map(&d[0]));\n  t = clock() - t;\n  double time_taken = ((double)t)/CLOCKS_PER_SEC;\n  printf(\"Tiempo de Dijkstra: %f ms \\n\", time_taken*1000);\n  cout << \"\" << endl;\n\n}\n\nvoid FloydWarshall(DirectedGraph & g){\n\n  clock_t t;\n  map<vertex_descriptor, map<vertex_descriptor, float> >matrix;\n  EdgeWeightMap weight_pmap = get(edge_weight, g);\n  DistanceMatrix dist(num_vertices(g));\n  DistanceMatrixMap dm(dist, g);\n  t = clock();\n  bool noNegCycles = floyd_warshall_all_pairs_shortest_paths (g, dm, weight_map(weight_pmap));\n  t = clock() - t;\n  double time_taken = ((double)t)/CLOCKS_PER_SEC;\n  printf(\"Tiempo de Floyd Warshall: %f ms \\n\", time_taken*1000);\n  cout << \"\" << endl;\n\n}\n\n\nint main(int argc, const char * argv[]){\n\n  DirectedGraph g;\n  vector<vertex_descriptor> verts;\n\n  for(int i=1; i<15; i++)\n  {\n      verts.push_back(addVertex(g, i));\n  }\n\n  addEdge(1,4,8,g);\n  addEdge(1,3,8,g);\n  addEdge(2,5,7,g);\n  addEdge(3,10,4,g);\n  addEdge(3,2,7,g);\n  addEdge(3,5,8,g);\n  addEdge(4,7,3,g);\n  addEdge(4,5,1,g);\n  addEdge(4,8,2,g);\n  addEdge(5,6,9,g);\n  addEdge(6,13,4,g);\n  addEdge(7,4,6,g);\n  addEdge(8,9,3,g);\n  addEdge(8,7,3,g);\n  addEdge(9,10,2,g);\n  addEdge(9,12,4,g);\n  addEdge(10,3,10,g);\n  addEdge(10,6,6,g);\n  addEdge(11,12,6,g);\n  addEdge(12,11,8,g);\n  addEdge(12,9,2,g);\n  addEdge(12,14,9,g);\n  addEdge(13,14,6,g);\n  addEdge(14,13,2,g);\n\n  cout << \"\" << endl;\n\n  insertarVertice(g);\n  insertarArista(g);\n  eliminarVertice(g);\n  eliminarArista(g);\n  DFS(g);\n  BFS(g);\n  Prim(g);\n  Kruskal(g);\n  Dijkstra(g);\n  FloydWarshall(g);\n\n\n\n}\n", "meta": {"hexsha": "7d08674355f7e6a26b5d10f9d890c79014313a86", "size": 10201, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Grafos/BoostGraph/BoostGraph.cpp", "max_stars_repo_name": "tec-csf/TC2017-P1-Otono-2019-equipocs", "max_stars_repo_head_hexsha": "76c2d1489c1bf101949d09c61ab7718221b0340b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Grafos/BoostGraph/BoostGraph.cpp", "max_issues_repo_name": "tec-csf/TC2017-P1-Otono-2019-equipocs", "max_issues_repo_head_hexsha": "76c2d1489c1bf101949d09c61ab7718221b0340b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Grafos/BoostGraph/BoostGraph.cpp", "max_forks_repo_name": "tec-csf/TC2017-P1-Otono-2019-equipocs", "max_forks_repo_head_hexsha": "76c2d1489c1bf101949d09c61ab7718221b0340b", "max_forks_repo_licenses": ["Apache-2.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.1303191489, "max_line_length": 158, "alphanum_fraction": 0.6127830605, "num_tokens": 3021, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4607544475092444}}
{"text": "#include <iostream>\n#include <cassert>\n#include <time.h>\n#include <cstdint>\n#include <stdexcept>\n#include <chrono>\n#include <limits.h>\n\n#include <NTL/ZZX.h>\n\n#include \"FINAL.h\"\n\nusing namespace std;\nusing namespace NTL;\n\nvoid test_params()\n{\n    {\n        Param param(LWE);\n        cout << \"Ciphertext modulus of the base scheme (LWE): \" << param.q_base << endl;\n        cout << \"Dimension of the base scheme (LWE): \" << param.n << endl;\n        cout << \"Ciphertext modulus for bootstrapping (LWE): \" << q_boot << endl;\n        cout << \"Polynomial modulus (LWE): \" << Param::get_def_poly() << endl;\n        assert(param.l_ksk == int(ceil(log(double(param.q_base))/log(double(Param::B_ksk)))));\n        cout << \"Decomposition length for key-switching (LWE): \" << param.l_ksk << endl;\n        cout << \"Decomposition bases for key-switching (LWE): \" << Param::B_ksk << endl;\n        cout << \"Dimension for bootstrapping (LWE): \" << Param::N << endl;\n        cout << \"Decomposition bases for bootstrapping (LWE): \";\n        for (const auto &v: param.B_bsk) cout << v << ' ';\n        cout << endl;\n        cout << \"Delta (LWE): \" << param.delta_base << endl;\n        cout << \"Half Delta (LWE): \" << param.half_delta_base << endl;\n    }\n    {\n        Param param(NTRU);\n        cout << \"Ciphertext modulus of the base scheme (MNTRU): \" << param.q_base << endl;\n        cout << \"Dimension of the base scheme (NTRU): \" << param.n << endl;\n        cout << \"Ciphertext modulus for bootstrapping (NTRU): \" << q_boot << endl;\n        cout << \"Polynomial modulus (NTRU): \" << Param::get_def_poly() << endl;\n        assert(param.l_ksk == int(ceil(log(double(param.q_base))/log(double(Param::B_ksk)))));\n        cout << \"Decomposition length for key-switching (MNTRU): \" << param.l_ksk << endl;\n        cout << \"Decomposition bases for key-switching (MNTRU): \" << Param::B_ksk << endl;\n        cout << \"Dimension for bootstrapping (MNTRU): \" << Param::N << endl;\n        cout << \"Decomposition bases for bootstrapping (MNTRU): \";\n        for (const auto &v: param.B_bsk) cout << v << ' ';\n        cout << endl;\n        cout << \"Decomposition lengths for bootstrapping (MNTRU): \";\n        for (int i = 0; i < Param::B_bsk_size; i++) \n        {\n            assert(param.l_bsk[i] == int(ceil(log(double(q_boot))/log(double(param.B_bsk[i])))));\n            cout << param.l_bsk[i] << ' ';\n        }\n        cout << endl;\n        cout << \"Decomposition lengths for bootstrapping (MNTRU): \";\n        for (int i = 0; i < Param::B_bsk_size; i++) \n        {\n            assert(param.l_bsk[i] == int(ceil(log(double(q_boot))/log(double(param.B_bsk[i])))));\n            cout << param.l_bsk[i] << ' ';\n        }\n        cout << endl;\n        cout << \"Delta (MNTRU): \" << param.delta_base << endl;\n        cout << \"Half Delta (MNTRU): \" << param.half_delta_base << endl;\n\n        {\n            assert(0L == mod_q_boot(0L));\n            assert(1L == mod_q_boot(1L));\n            assert(0L == mod_q_boot(q_boot));\n            assert(half_q_boot == mod_q_boot(half_q_boot));\n            assert(-half_q_boot == mod_q_boot(-half_q_boot));\n            cout << \"MODULO REDUCTION IS OK\" << endl;\n        }\n    }\n    \n    cout << \"Plaintext modulus: \" << Param::t << endl;\n    cout << endl;\n    cout << \"PARAMS ARE OK\" << endl;\n\n    {\n        vector<int> res;\n        decompose(res, 0, 2, 3);\n        assert(res.size() == 3);\n        for (auto iter=res.begin(); iter < res.end(); iter++)\n            assert(0L == *iter);\n    }\n    {\n        vector<int> res;\n        decompose(res, 1, 2, 3);\n        assert(res.size() == 3);\n        assert(res[0] == 1);\n        for (auto iter=res.begin()+1; iter < res.end(); iter++)\n            assert(0L == *iter);\n    }\n    {\n        vector<int> res;\n        decompose(res, 2, 3, 3);\n        assert(res.size() == 3);\n        assert(res[0] == -1 && res[1] == 1 && res[2] == 0);\n    }\n    {\n        vector<int> res;\n        decompose(res, 2, 4, 3);\n        assert(res.size() == 3);\n        assert(res[0] == 2 && res[1] == 0 && res[2] == 0);\n        decompose(res, 3, 4, 3);\n        assert(res.size() == 3);\n        assert(res[0] == -1 && res[1] == 1 && res[2] == 0);\n    }\n    {\n        vector<int> res;\n        try\n        {\n            decompose(res, 14, 3, 3);\n            assert(false);\n        }\n        catch (overflow_error)\n        {\n            assert(true);\n        }\n    }\n    {\n        vector<int> res;\n        try\n        {\n            decompose(res, -14, 3, 3);\n            assert(false);\n        }\n        catch (overflow_error)\n        {\n            assert(true);\n        }\n    }\n    {\n        vector<int> res;\n        decompose(res, 13, 3, 3);\n        assert(res.size() == 3);\n        assert(res[0] == 1 && res[1] == 1 && res[2] == 1);\n        decompose(res, -13, 3, 3);\n        assert(res.size() == 3);\n        assert(res[0] == -1 && res[1] == -1 && res[2] == -1);\n    }\n\n\n    cout << \"DECOMPOSITION IS OK\" << endl;\n\n    \n}\n\nvoid test_sampler()\n{\n    int N = Param::N;\n\n    Param pLWE(LWE);\n    Param pNTRU(NTRU);\n    for (int run = 0; run < 1; run++)\n    {\n        //cout << \"Run: \" << run+1 << endl;\n        {\n            vector<int> vec(pNTRU.n, 0L);\n            Sampler::get_ternary_vector(vec);\n            \n            assert(vec.size() == pNTRU.n);\n            for (int i = 0; i < pNTRU.n; i++)\n            {\n                assert((vec[i]==0) || (vec[i]==-1) || (vec[i]==1) );\n            }\n        }\n\n        {\n            vector<int> vec(N,0L);\n            Sampler::get_ternary_vector(vec);\n            \n            assert(vec.size() == N);\n            for (int i = 0; i < N; i++)\n            {\n                assert((vec[i]==0) || (vec[i]==-1) || (vec[i]==1) );\n            }\n        }\n\n        {\n            vector<int> vec(N,0L);\n            Sampler::get_binary_vector(vec);\n            \n            assert(vec.size() == N);\n            for (int i = 0; i < N; i++)\n            {\n                assert((vec[i]==0) || (vec[i]==1) );\n            }\n        }\n\n        {\n            int n = pLWE.n;\n            vector<vector<int>> mat(n, vector<int>(N,0L));\n            Sampler::get_ternary_matrix(mat);\n            \n            assert(mat.size() == n && mat[0].size() == N);\n            for (int i = 0; i < n; i++)\n            {\n                vector<int>& row = mat[i];\n                for (int j = 0; j < N; j++)\n                    assert((row[j]==0) || (row[j]==-1) || (row[j]==1) );\n            }\n        }\n\n        {\n            int n = pLWE.n;\n            vector<int> vec(n, 0L);\n            double st_dev = 4.0;\n            Sampler::get_gaussian_vector(vec, st_dev);\n            \n            assert(vec.size() == n);\n            for (int i = 0; i < n; i++)\n            {\n                assert(conv<double>(abs(vec[i])) < 6*st_dev);\n            }\n        }\n\n        {\n            int n = pNTRU.n;\n            vector<vector<int>> mat(n, vector<int>(N,0L));\n            double st_dev = 4.0;\n            Sampler::get_gaussian_matrix(mat, st_dev);\n            \n            assert(mat.size() == n && mat[0].size() == N);\n            for (int i = 0; i < n; i++)\n            {\n                vector<int>& row = mat[i];\n                for (int j = 0; j < N; j++)\n                    assert(conv<double>(abs(row[j])) < 6*st_dev);\n            }\n        }\n\n        {\n            vector<int> vec_inv(N,0L);\n            vector<int> vec(N,0L);\n            Sampler s(pNTRU);\n            s.get_invertible_vector(vec, vec_inv, 4, 1);\n            \n            assert(vec.size() == N && vec_inv.size() == N);\n            assert((vec[0]==1) || (vec[0]==-3) || (vec[0]==5) );\n            for (int i = 1; i < N; i++)\n            {\n                assert((vec[i]==0) || (vec[i]==-4) || (vec[i]==4));\n            }\n        }\n\n        {\n            int n = pLWE.n;\n            vector<vector<int>> mat_inv(n, vector<int>(n,0L));\n            vector<vector<int>> mat(n, vector<int>(n,0L));\n            Sampler s(pLWE);\n            s.get_invertible_matrix(mat, mat_inv, 5, 1);\n            \n            assert(mat.size() == n && mat[0].size() == n \n                && mat_inv.size() == n && mat_inv[0].size() == n);\n            for (int i = 0; i < n; i++)\n                assert((mat[i][i]==1) || (mat[i][i]==-4) || (mat[i][i]==6) );\n            \n            for (int i = 0; i < n; i++)\n                for (int j = 0; (j < n) && (j != i); j++)\n                {\n                    assert((mat[i][j]==0) || (mat[i][j]==-5) || (mat[i][j]==5) );\n                }\n        }\n    }\n    cout << \"SAMPLER IS OK\" << endl;\n}\n\nenum GateType {NAND, AND, OR, XOR, NOT};\n\nvoid test_ntruhe_gate_helper(int in1, int in2, const SchemeNTRU& s, GateType g)\n{\n    float avg_time = 0.0;\n    int N_TESTS = (g == NOT ? 30 : 100);\n    for (int i = 0; i < N_TESTS; i++)\n    {\n        Ctxt_NTRU ct_res, ct1, ct2;\n        s.encrypt(ct1, in1);\n        s.encrypt(ct2, in2);\n        \n        if (g == NAND)\n        {\n            auto start = clock();\n            s.nand_gate(ct_res, ct1, ct2);\n            avg_time += float(clock()-start)/CLOCKS_PER_SEC;\n\n            int output = s.decrypt(ct_res);\n\n            //cout << \"NAND output: \" << output << endl;\n            assert(output == !(in1 & in2));\n        }\n        else if (g == AND) {\n            auto start = clock();\n            s.and_gate(ct_res, ct1, ct2);\n            avg_time += float(clock()-start)/CLOCKS_PER_SEC;\n\n            int output = s.decrypt(ct_res);\n\n            //cout << \"AND output: \" << output << endl;\n            assert(output == (in1 & in2));\n        }\n        else if (g == OR) {\n            auto start = clock();\n            s.or_gate(ct_res, ct1, ct2);\n            avg_time += float(clock()-start)/CLOCKS_PER_SEC;\n\n            int output = s.decrypt(ct_res);\n\n            //cout << \"OR output: \" << output << endl;\n            assert(output == (in1 | in2));\n        }\n        else if (g == XOR) {\n            auto start = clock();\n            s.xor_gate(ct_res, ct1, ct2);\n            avg_time += float(clock()-start)/CLOCKS_PER_SEC;\n\n            int output = s.decrypt(ct_res);\n\n            //cout << \"XOR output: \" << output << endl;\n            assert(output == (in1 ^ in2));\n        }\n        else if (g == NOT) {\n            auto start = clock();\n            s.not_gate(ct_res, ct1);\n            avg_time += float(clock()-start)/CLOCKS_PER_SEC;\n\n            int output = s.decrypt(ct_res);\n\n//            cout << \".... NOT output: \" << output << endl;\n            assert(output == (1 - in1));\n        }\n\n    }\n    cout << \"Avg. time: \" << avg_time/N_TESTS << endl;\n}\n\nvoid test_ntru_gate(SchemeNTRU& s, GateType g)\n{\n    test_ntruhe_gate_helper(0, 0, s, g);\n    test_ntruhe_gate_helper(0, 1, s, g);\n    test_ntruhe_gate_helper(1, 0, s, g);\n    test_ntruhe_gate_helper(1, 1, s, g);\n}\n\nvoid test_ntruhe_nand(SchemeNTRU& s)\n{\n    GateType g = NAND;\n\n    test_ntru_gate(s, g);\n\n    cout << \"NAND IS OK\" << endl;\n}\n\nvoid test_ntruhe_and(SchemeNTRU& s)\n{\n    GateType g = AND;\n    test_ntru_gate(s, g);\n    cout << \"AND IS OK\" << endl;\n}\n\nvoid test_ntruhe_or(SchemeNTRU& s)\n{\n    GateType g = OR;\n    test_ntru_gate(s, g);\n    cout << \"OR IS OK\" << endl;\n}\n\nvoid test_ntruhe_xor(SchemeNTRU& s)\n{\n    GateType g = XOR;\n    test_ntru_gate(s, g);\n    cout << \"XOR IS OK\" << endl;\n}\n\nvoid test_ntruhe_not(SchemeNTRU& s)\n{\n    GateType g = NOT;\n    for(int i = 0; i < 5; i++){\n        int bit = binary_sampler(rand_engine);\n        test_ntruhe_gate_helper(bit, 0, s, g);\n    }\n    cout << \"NOT GATE IS OK\" << endl;\n}\n\n\nvoid test_ntruhe_gate_composition_helper(SchemeNTRU& s, GateType g)\n{\n    float avg_time = 0.0;\n    int N_TESTS = 100;\n\n    int in1, in2, exp_out;\n    in1 = binary_sampler(rand_engine);\n    exp_out = in1;\n\n    Ctxt_NTRU ct_res, ct;\n    s.encrypt(ct_res, in1);\n    for (int i = 0; i < N_TESTS; i++)\n    {\n        in2 = binary_sampler(rand_engine);\n        s.encrypt(ct, in2);\n        if (g == NAND)\n        {\n            auto start = clock();\n            s.nand_gate(ct_res, ct_res, ct);// ct_res should encrypt NAND(exp_out, in2)\n            avg_time += float(clock()-start)/CLOCKS_PER_SEC;\n            exp_out = !(exp_out & in2); // exp_out = NAND(exp_out, in2)\n        }\n        else if (g == AND) {\n            auto start = clock();\n            s.and_gate(ct_res, ct_res, ct);\n            avg_time += float(clock()-start)/CLOCKS_PER_SEC;\n            exp_out = (exp_out & in2); // exp_out = AND(exp_out, in2)\n        }\n        else if (g == OR) {\n            auto start = clock();\n            s.or_gate(ct_res, ct_res, ct);\n            avg_time += float(clock()-start)/CLOCKS_PER_SEC;\n            exp_out = (exp_out | in2); // exp_out = OR(exp_out, in2)\n        }\n        else if (g == XOR) {\n            auto start = clock();\n            s.xor_gate(ct_res, ct_res, ct);\n            avg_time += float(clock()-start)/CLOCKS_PER_SEC;\n            exp_out = (exp_out ^ in2); // exp_out = XOR(exp_out, in2)\n        }\n        else if (g == NOT) {\n            auto start = clock();\n            s.not_gate(ct_res, ct_res);\n            avg_time += float(clock()-start)/CLOCKS_PER_SEC;\n            exp_out = (1 - exp_out); // exp_out = NOT(exp_out)\n        }\n\n        int output = s.decrypt(ct_res);\n        assert(output == exp_out);\n    }\n    cout << \"Avg. time: \" << avg_time/N_TESTS << endl;\n}\n\nvoid test_ntruhe_composition_of_gates(SchemeNTRU& s)\n{\n    test_ntruhe_gate_composition_helper(s, NAND);\n    cout << \"COMPOSING NAND IS OK\" << endl;\n\n    test_ntruhe_gate_composition_helper(s, AND);\n    cout << \"COMPOSING AND IS OK\" << endl;\n\n    test_ntruhe_gate_composition_helper(s, OR);\n    cout << \"COMPOSING OR IS OK\" << endl;\n\n    test_ntruhe_gate_composition_helper(s, XOR);\n    cout << \"COMPOSING XOR IS OK\" << endl;\n\n    test_ntruhe_gate_composition_helper(s, NOT);\n    cout << \"COMPOSING NOT GATE IS OK\" << endl;\n}\n\n\n// ----- LWE tests\n\nvoid test_lwehe_gate_helper(int in1, int in2, SchemeLWE& s, GateType g)\n{\n    float avg_time = 0.0;\n    for (int i = 0; i < 100; i++)\n    {\n        Ctxt_LWE ct_res, ct1, ct2;\n        s.encrypt(ct1, in1);\n        s.encrypt(ct2, in2);\n        \n        if (g == NAND)\n        {\n            auto start = clock();\n            s.nand_gate(ct_res, ct1, ct2);\n            avg_time += float(clock()-start)/CLOCKS_PER_SEC;\n\n            int output = s.decrypt(ct_res);\n\n            //cout << \"NAND output: \" << output << endl;\n            assert(output == !(in1 & in2));\n        }\n        else if (g == AND) {\n            auto start = clock();\n            s.and_gate(ct_res, ct1, ct2);\n            avg_time += float(clock()-start)/CLOCKS_PER_SEC;\n\n            int output = s.decrypt(ct_res);\n\n            //cout << \"AND output: \" << output << endl;\n            assert(output == (in1 & in2));\n        }\n        else if (g == OR) {\n            auto start = clock();\n            s.or_gate(ct_res, ct1, ct2);\n            avg_time += float(clock()-start)/CLOCKS_PER_SEC;\n\n            int output = s.decrypt(ct_res);\n\n            //cout << \"OR output: \" << output << endl;\n            assert(output == (in1 | in2));\n        }\n        else if (g == XOR) {\n            auto start = clock();\n            s.xor_gate(ct_res, ct1, ct2);\n            avg_time += float(clock()-start)/CLOCKS_PER_SEC;\n\n            int output = s.decrypt(ct_res);\n\n            //cout << \"OR output: \" << output << endl;\n            assert(output == (in1 ^ in2));\n        }\n        else if (g == NOT) {\n            auto start = clock();\n            s.not_gate(ct_res, ct1);\n            avg_time += float(clock()-start)/CLOCKS_PER_SEC;\n\n            int output = s.decrypt(ct_res);\n\n//            cout << \"NOT output: \" << output << endl;\n            assert(output == (1 - in1));\n        }\n\n\n\n    }\n    cout << \"Avg. time: \" << avg_time/100.0 << endl;\n}\n\nvoid test_lwe_gate(SchemeLWE& s, GateType g)\n{\n    test_lwehe_gate_helper(0, 0, s, g);\n    test_lwehe_gate_helper(0, 1, s, g);\n    test_lwehe_gate_helper(1, 0, s, g);\n    test_lwehe_gate_helper(1, 1, s, g);\n}\n\nvoid test_lwehe_nand(SchemeLWE& s)\n{\n    GateType g = NAND;\n    test_lwe_gate(s, g);\n    cout << \"NAND IS OK\" << endl;\n}\n\nvoid test_lwehe_and(SchemeLWE& s)\n{\n    GateType g = AND;\n    test_lwe_gate(s, g);\n    cout << \"AND IS OK\" << endl;\n}\n\nvoid test_lwehe_or(SchemeLWE& s)\n{\n    GateType g = OR;\n    test_lwe_gate(s, g);\n    cout << \"OR IS OK\" << endl;\n}\n\nvoid test_lwehe_xor(SchemeLWE& s)\n{\n    GateType g = XOR;\n    test_lwe_gate(s, g);\n    cout << \"XOR IS OK\" << endl;\n}\n\nvoid test_lwehe_not(SchemeLWE& s)\n{\n    GateType g = NOT;\n    for(int i = 0; i < 4; i++){\n        int bit = binary_sampler(rand_engine);\n        test_lwehe_gate_helper(bit, 0, s, g);\n    }\n\n    cout << \"NOT GATE IS OK\" << endl;\n}\n\n\nvoid test_lwehe_gate_composition_helper(SchemeLWE& s, GateType g)\n{\n    float avg_time = 0.0;\n    int N_TESTS = 110;\n\n    int in1, in2, exp_out;\n    in1 = binary_sampler(rand_engine);\n    exp_out = in1;\n\n    Ctxt_LWE ct_res, ct;\n    s.encrypt(ct_res, in1);\n    for (int i = 0; i < N_TESTS; i++)\n    {\n        in2 = binary_sampler(rand_engine);\n        s.encrypt(ct, in2);\n        if (g == NAND)\n        {\n            auto start = clock();\n            s.nand_gate(ct_res, ct_res, ct);// ct_res should encrypt NAND(exp_out, in2)\n            avg_time += float(clock()-start)/CLOCKS_PER_SEC;\n            exp_out = !(exp_out & in2); // exp_out = NAND(exp_out, in2)\n            //cout << \"NAND output: \" << output << endl;\n        }\n        else if (g == AND) {\n            auto start = clock();\n            s.and_gate(ct_res, ct_res, ct);\n            avg_time += float(clock()-start)/CLOCKS_PER_SEC;\n            exp_out = (exp_out & in2); // exp_out = AND(exp_out, in2)\n            //cout << \"AND output: \" << output << endl;\n        }\n        else if (g == OR) {\n            auto start = clock();\n            s.or_gate(ct_res, ct_res, ct);\n            avg_time += float(clock()-start)/CLOCKS_PER_SEC;\n            exp_out = (exp_out | in2); // exp_out = OR(exp_out, in2)\n            //cout << \"OR output: \" << output << endl;\n        }\n        else if (g == XOR) {\n            auto start = clock();\n            s.xor_gate(ct_res, ct_res, ct);\n            avg_time += float(clock()-start)/CLOCKS_PER_SEC;\n            exp_out = (exp_out ^ in2); // exp_out = XOR(exp_out, in2)\n            //cout << \"XOR output: \" << output << endl;\n        }\n        else if (g == NOT) {\n            auto start = clock();\n            s.not_gate(ct_res, ct_res);\n            avg_time += float(clock()-start)/CLOCKS_PER_SEC;\n            exp_out = (1 - exp_out); // exp_out = NOT(exp_out)\n        }\n\n        int output = s.decrypt(ct_res);\n        assert(output == exp_out);\n    }\n    cout << \"Avg. time: \" << avg_time/N_TESTS << endl;\n}\n\nvoid test_lwehe_composition_of_gates(SchemeLWE& s)\n{\n    test_lwehe_gate_composition_helper(s, NAND);\n    cout << \"COMPOSING NAND IS OK\" << endl;\n\n    test_lwehe_gate_composition_helper(s, AND);\n    cout << \"COMPOSING AND IS OK\" << endl;\n\n    test_lwehe_gate_composition_helper(s, OR);\n    cout << \"COMPOSING OR IS OK\" << endl;\n\n    test_lwehe_gate_composition_helper(s, XOR);\n    cout << \"COMPOSING XOR IS OK\" << endl;\n\n    test_lwehe_gate_composition_helper(s, NOT);\n    cout << \"COMPOSING NOT GATE IS OK\" << endl;\n}\n\n\n\nint main()\n{\n    test_params();\n    test_sampler();\n\n    cout << endl;\n    cout << \"-------------------------\" << endl;\n    cout << \"NTRU tests\" << endl;\n    SchemeNTRU s_ntru;\n    test_ntruhe_nand(s_ntru);\n    test_ntruhe_and(s_ntru);\n    test_ntruhe_or(s_ntru);\n    test_ntruhe_xor(s_ntru);\n    test_ntruhe_not(s_ntru);\n    test_ntruhe_composition_of_gates(s_ntru);\n    cout << \"NTRU tests PASSED\" << endl;\n\n    cout << endl;\n    cout << \"-------------------------\" << endl;\n    cout << \"LWE tests\" << endl;\n    SchemeLWE s_lwe;\n    test_lwehe_not(s_lwe);\n    test_lwehe_nand(s_lwe);\n    test_lwehe_and(s_lwe);\n    test_lwehe_or(s_lwe);\n    test_lwehe_xor(s_lwe);\n    test_lwehe_not(s_lwe);\n    test_lwehe_composition_of_gates(s_lwe);\n    cout << \"LWE tests PASSED\" << endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "fc635931824dd89efaeb9edd074a65784447e393", "size": 19968, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test.cpp", "max_stars_repo_name": "KULeuven-COSIC/FINAL", "max_stars_repo_head_hexsha": "c6296ae5457ae6e61a9466a1497c6b0130460343", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2022-01-21T13:15:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T11:46:19.000Z", "max_issues_repo_path": "test.cpp", "max_issues_repo_name": "KULeuven-COSIC/FINAL", "max_issues_repo_head_hexsha": "c6296ae5457ae6e61a9466a1497c6b0130460343", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-03-24T21:09:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-24T21:09:18.000Z", "max_forks_repo_path": "test.cpp", "max_forks_repo_name": "KULeuven-COSIC/FINAL", "max_forks_repo_head_hexsha": "c6296ae5457ae6e61a9466a1497c6b0130460343", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-24T07:27:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-24T07:27:50.000Z", "avg_line_length": 29.2357247438, "max_line_length": 97, "alphanum_fraction": 0.4924879808, "num_tokens": 5738, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4607544475092444}}
{"text": "// Boost.Geometry\n// Unit Test\n\n// Copyright (c) 2019 Oracle and/or its affiliates.\n\n// Contributed and/or modified by Vissarion Fysikopoulos, 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#include <geometry_test_common.hpp>\n\n#include <boost/geometry/formulas/karney_direct.hpp>\n#include <boost/geometry/srs/srs.hpp>\n\n#ifdef BOOST_GEOEMTRY_TEST_WITH_GEOGRAPHICLIB\n#include <GeographicLib/Geodesic.hpp>\n#include <GeographicLib/Constants.hpp>\n#endif // BOOST_GEOEMTRY_TEST_WITH_GEOGRAPHICLIB\n\nint test_main(int, char*[])\n{\n\n#ifdef BOOST_GEOEMTRY_TEST_WITH_GEOGRAPHICLIB\n    // accuracy test from https://github.com/boostorg/geometry/issues/560\n    using namespace GeographicLib;\n\n    const long double wgs84_a = 6378137.0L;\n    const long double wgs84_f = 1.0L / 298.257223563L;\n    const long double one_minus_f = 1.0L - wgs84_f;\n    const long double wgs84_b = wgs84_a * one_minus_f;\n\n    const boost::geometry::srs::spheroid<long double> BoostWGS84(wgs84_a, wgs84_b);\n\n    // boost karney_direct function class with azimuth output and SeriesOrder = 6\n    typedef boost::geometry::formula::karney_direct <double, true, true, false, false, 6u>\n            BoostKarneyDirect_6;\n\n    // boost karney_direct function class with azimuth output and SeriesOrder = 8\n    typedef boost::geometry::formula::karney_direct <double, true, true, false, false, 8u>\n            BoostKarneyDirect_8;\n\n    // boost test BOOST_CHECK_CLOSE macro takes a percentage accuracy parameter\n    const double EPSILON = std::numeric_limits<double>::epsilon();\n    const double CALCULATION_TOLERANCE = 100 * EPSILON;\n\n    const Geodesic GeographicLibWGS84(Geodesic::WGS84());\n\n    // Loop around latitudes: 0 to 89 degrees\n    for (int i=0; i < 90; ++i)\n    {\n        // The latitude in degrees.\n        double latitude(1.0 * i);\n\n        // Loop around longitudes: 1 to 179 degrees\n        for (int j=1; j < 180; ++j)\n        {\n            // The longitude in degrees.\n            double longitude(1.0 * j);\n\n            // The Geodesic: distance in metres, start azimuth and finish azimuth in degrees.\n            double distance_m, azimuth, azi2;\n            GeographicLibWGS84.Inverse(0.0, 0.0, latitude, longitude, distance_m, azimuth, azi2);\n\n            // The GeographicLib position and azimuth at the distance in metres\n            double lat2k, lon2k, azi2k;\n            GeographicLibWGS84.Direct(0.0, 0.0, azimuth, distance_m, lat2k, lon2k, azi2k);\n            BOOST_CHECK_CLOSE(latitude, lat2k, 140 * CALCULATION_TOLERANCE);\n            BOOST_CHECK_CLOSE(longitude, lon2k, 120 * CALCULATION_TOLERANCE);\n\n            // The boost karney_direct order 6 position at the azimuth and distance in metres.\n            boost::geometry::formula::result_direct<double> results_6\n                    = BoostKarneyDirect_6::apply(0.0, 0.0, distance_m, azimuth, BoostWGS84);\n            BOOST_CHECK_CLOSE(azi2, results_6.reverse_azimuth, 140 * CALCULATION_TOLERANCE);\n            BOOST_CHECK_CLOSE(latitude, results_6.lat2, 220 * CALCULATION_TOLERANCE);\n\n            /******** Test below only passes with >= 10172000 * CALCULATION_TOLERANCE !! ********/\n            BOOST_CHECK_CLOSE(longitude, results_6.lon2, 10171000 * CALCULATION_TOLERANCE);\n            /*****************************************************************************/\n\n            // The boost karney_direct order 8 position at the azimuth and distance in metres.\n            boost::geometry::formula::result_direct<double> results_8\n                    = BoostKarneyDirect_8::apply(0.0, 0.0, distance_m, azimuth, BoostWGS84);\n            BOOST_CHECK_CLOSE(azi2, results_8.reverse_azimuth, 140 * CALCULATION_TOLERANCE);\n            BOOST_CHECK_CLOSE(latitude, results_8.lat2, 220 * CALCULATION_TOLERANCE);\n\n            /******** Test below only passes with >= 10174000 * CALCULATION_TOLERANCE !! ********/\n            BOOST_CHECK_CLOSE(longitude, results_8.lon2, 10173000 * CALCULATION_TOLERANCE);\n            /*****************************************************************************/\n        }\n    }\n#endif // BOOST_GEOEMTRY_TEST_WITH_GEOGRAPHICLIB\n\n    return 0;\n}\n\n", "meta": {"hexsha": "e485caafb46a54fef2739515f6d797ff75d1fb26", "size": 4275, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/libs/geometry/test/formulas/direct_accuracy.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/geometry/test/formulas/direct_accuracy.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/geometry/test/formulas/direct_accuracy.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": 43.6224489796, "max_line_length": 98, "alphanum_fraction": 0.6598830409, "num_tokens": 1091, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4607544475092444}}
{"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    cholesky.cpp\n * @brief   Efficient incomplete Cholesky on rank-deficient matrices, todo: constrained Cholesky\n * @author  Richard Roberts\n * @author  Frank Dellaert\n * @date    Nov 5, 2010\n */\n\n#include <gtsam/base/cholesky.h>\n#include <gtsam/base/timing.h>\n\n#include <boost/format.hpp>\n#include <cmath>\n\nusing namespace std;\n\nnamespace gtsam {\n\nstatic const double negativePivotThreshold = -1e-1;\nstatic const double zeroPivotThreshold = 1e-6;\nstatic const double underconstrainedPrior = 1e-5;\nstatic const int underconstrainedExponentDifference = 12;\n\n/* ************************************************************************* */\nstatic inline int choleskyStep(Matrix& ATA, size_t k, size_t order) {\n  // Get pivot value\n  double alpha = ATA(k, k);\n\n  // Correct negative pivots from round-off error\n  if (alpha < negativePivotThreshold) {\n    return -1;\n  } else if (alpha < 0.0)\n    alpha = 0.0;\n\n  const double beta = sqrt(alpha);\n\n  if (beta > zeroPivotThreshold) {\n    const double betainv = 1.0 / beta;\n\n    // Update k,k\n    ATA(k, k) = beta;\n\n    if (k < (order - 1)) {\n      // Update A(k,k+1:end) <- A(k,k+1:end) / beta\n      typedef Matrix::RowXpr::SegmentReturnType BlockRow;\n      BlockRow V = ATA.row(k).segment(k + 1, order - (k + 1));\n      V *= betainv;\n\n      // Update A(k+1:end, k+1:end) <- A(k+1:end, k+1:end) - v*v' / alpha\n      ATA.block(k + 1, k + 1, order - (k + 1), order - (k + 1)) -= V.transpose() * V;\n      //      ATA.bottomRightCorner(order-(k+1), order-(k+1)).selfadjointView<Eigen::Upper>()\n      //          .rankUpdate(V.adjoint(), -1);\n    }\n    return 1;\n  } else {\n    // For zero pivots, add the underconstrained variable prior\n    ATA(k, k) = underconstrainedPrior;\n    for (size_t j = k + 1; j < order; ++j)\n      ATA(k, j) = 0.0;\n    return 0;\n  }\n}\n\n/* ************************************************************************* */\npair<size_t, bool> choleskyCareful(Matrix& ATA, int order) {\n  // Check that the matrix is square (we do not check for symmetry)\n  assert(ATA.rows() == ATA.cols());\n\n  // Number of rows/columns\n  const size_t n = ATA.rows();\n\n  // Negative order means factor the entire matrix\n  if (order < 0)\n    order = int(n);\n\n  assert(size_t(order) <= n);\n\n  // The index of the row after the last non-zero row of the square-root factor\n  size_t maxrank = 0;\n  bool success = true;\n\n  // Factor row-by-row\n  for (size_t k = 0; k < size_t(order); ++k) {\n    int stepResult = choleskyStep(ATA, k, size_t(order));\n    if (stepResult == 1) {\n      maxrank = k + 1;\n    } else if (stepResult == -1) {\n      success = false;\n      break;\n    } /* else if(stepResult == 0) Found zero pivot */\n  }\n\n  return make_pair(maxrank, success);\n}\n\n/* ************************************************************************* */\nbool choleskyPartial(Matrix& ABC, size_t nFrontal, size_t topleft) {\n\n  gttic(choleskyPartial);\n  if (nFrontal == 0)\n    return true;\n\n  assert(ABC.cols() == ABC.rows());\n  const Eigen::DenseIndex n = ABC.rows() - topleft;\n  assert(n >= 0 && nFrontal <= size_t(n));\n\n  // Create views on blocks\n  auto A = ABC.block(topleft, topleft, nFrontal, nFrontal);\n  auto B = ABC.block(topleft, topleft + nFrontal, nFrontal, n - nFrontal);\n  auto C = ABC.block(topleft + nFrontal, topleft + nFrontal, n - nFrontal, n - nFrontal);\n\n  // Compute Cholesky factorization A = R'*R, overwrites A.\n  gttic(LLT);\n  Eigen::LLT<Matrix, Eigen::Upper> llt(A);\n  Eigen::ComputationInfo lltResult = llt.info();\n\n  if (lltResult != Eigen::Success) {\n    return false;\n  }\n\n  auto R = A.triangularView<Eigen::Upper>();\n  R = llt.matrixU();\n  gttoc(LLT);\n\n  // Compute S = inv(R') * B\n  gttic(compute_S);\n  if (nFrontal < n)\n    R.transpose().solveInPlace(B);\n  gttoc(compute_S);\n\n  // Compute L = C - S' * S\n  gttic(compute_L);\n  if (nFrontal < n)\n    C.selfadjointView<Eigen::Upper>().rankUpdate(B.transpose(), -1.0);\n  gttoc(compute_L);\n\n  // Check last diagonal element - Eigen does not check it\n  if (nFrontal >= 2) {\n    int exp2, exp1;\n    (void)frexp(R(topleft + nFrontal - 2, topleft + nFrontal - 2), &exp2);\n    (void)frexp(R(topleft + nFrontal - 1, topleft + nFrontal - 1), &exp1);\n    return (exp2 - exp1 < underconstrainedExponentDifference);\n  } else if (nFrontal == 1) {\n    int exp1;\n    (void)frexp(R(0, 0), &exp1);\n    return (exp1 > -underconstrainedExponentDifference);\n  } else {\n    return true;\n  }\n\n} // END choleskyPartial()\n}  // namespace gtsam\n", "meta": {"hexsha": "b85402608c9fa9f18ec75560873a7b0b31b3b34b", "size": 4836, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/base/cholesky.cpp", "max_stars_repo_name": "ICRA-2019/MH-iSAM2_lib", "max_stars_repo_head_hexsha": "cf92b2b94f5dcae39b780273c613ca945599e0c0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-10T02:24:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T02:24:39.000Z", "max_issues_repo_path": "gtsam/base/cholesky.cpp", "max_issues_repo_name": "ICRA-2019/MH-iSAM2_lib", "max_issues_repo_head_hexsha": "cf92b2b94f5dcae39b780273c613ca945599e0c0", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/base/cholesky.cpp", "max_forks_repo_name": "ICRA-2019/MH-iSAM2_lib", "max_forks_repo_head_hexsha": "cf92b2b94f5dcae39b780273c613ca945599e0c0", "max_forks_repo_licenses": ["BSD-3-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.487804878, "max_line_length": 96, "alphanum_fraction": 0.5818858561, "num_tokens": 1436, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4607544475092444}}
{"text": "#include <geometry.h>\n#include <tiny_math_types.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n\ntypedef tiny::MathTypes<double>   MT;\ntypedef MT::vector3_type          V;\ntypedef MT::real_type             T;\ntypedef MT::value_traits          VT;\n\n\nBOOST_AUTO_TEST_SUITE(geometry);\n\nBOOST_AUTO_TEST_CASE(inside_dop_test)\n{\n  std::vector<V> corners(2u);\n\n  corners[0] = V::make(-1.0,-1.0,-1.0);\n  corners[1] = V::make( 1.0, 1.0, 1.0);\n\n  geometry::DOP<T, 6u> const dop = geometry::make_dop(corners.begin(), corners.end(), geometry::make3<V>() );\n\n  BOOST_CHECK(geometry::is_valid(dop));\n\n  {\n    V    const p    = V::make( 0.0, 0.0, 0.0);\n    bool const test = geometry::inside_dop(p, dop);\n    BOOST_CHECK( test );\n  }\n  {\n    V    const p    = V::make( 1.0, 1.0, 1.0);\n    bool const test = geometry::inside_dop(p, dop);\n    BOOST_CHECK( test );\n  }\n  {\n    V    const p    = V::make( 2.0, 0.0, 0.0);\n    bool const test = geometry::inside_dop(p, dop);\n    BOOST_CHECK( !test );\n  }\n\n}\n\nBOOST_AUTO_TEST_CASE(outside_dop_test)\n{\n  std::vector<V> corners(2u);\n\n  corners[0] = V::make(-1.0,-1.0,-1.0);\n  corners[1] = V::make( 1.0, 1.0, 1.0);\n\n  geometry::DOP<T, 6u> const dop = geometry::make_dop(corners.begin(), corners.end(), geometry::make3<V>() );\n\n  BOOST_CHECK(geometry::is_valid(dop));\n\n  {\n    V    const p    = V::make( 0.0, 0.0, 0.0);\n    bool const test = geometry::outside_dop(p, dop);\n    BOOST_CHECK( ! test );\n  }\n  {\n    V    const p    = V::make( 1.0, 1.0, 1.0);\n    bool const test = geometry::outside_dop(p, dop);\n    BOOST_CHECK( ! test );\n  }\n  {\n    V    const p    = V::make( 2.0, 0.0, 0.0);\n    bool const test = geometry::outside_dop(p, dop);\n    BOOST_CHECK( test );\n  }\n  \n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "4df7f91d68114ce4ac962afd63a8f7383b1c8985", "size": 1888, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/FOUNDATION/GEOMETRY/unit_tests/geometry_inside_dop/geometry_inside_dop.cpp", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-11-27T09:44:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-13T00:24:21.000Z", "max_issues_repo_path": "PROX/FOUNDATION/GEOMETRY/unit_tests/geometry_inside_dop/geometry_inside_dop.cpp", "max_issues_repo_name": "erleben/matchstick", "max_issues_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_issues_repo_licenses": ["MIT"], "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/FOUNDATION/GEOMETRY/unit_tests/geometry_inside_dop/geometry_inside_dop.cpp", "max_forks_repo_name": "erleben/matchstick", "max_forks_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_forks_repo_licenses": ["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.5194805195, "max_line_length": 109, "alphanum_fraction": 0.6117584746, "num_tokens": 631, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4607544475092444}}
{"text": "#include <stan/math/prim/scal.hpp>\n#include <gtest/gtest.h>\n#include <boost/random/mersenne_twister.hpp>\n#include <math/prim/scal/prob/util.hpp>\n#include <vector>\n\nTEST(ProbDistributionsBernoulli, error_check) {\n  boost::random::mt19937 rng;\n  EXPECT_NO_THROW(stan::math::bernoulli_rng(0.6, rng));\n\n  EXPECT_THROW(stan::math::bernoulli_rng(1.6, rng), std::domain_error);\n  EXPECT_THROW(stan::math::bernoulli_rng(-0.6, rng), std::domain_error);\n  EXPECT_THROW(stan::math::bernoulli_rng(stan::math::positive_infinity(), rng),\n               std::domain_error);\n}\n\nTEST(ProbDistributionsBernoulli, chiSquareGoodnessFitTest) {\n  boost::random::mt19937 rng;\n  int N = 10000;\n\n  std::vector<double> expected;\n  expected.push_back(N * (1 - 0.4));\n  expected.push_back(N * 0.4);\n\n  std::vector<int> counts(2);\n  for (int i = 0; i < N; ++i) {\n    ++counts[stan::math::bernoulli_rng(0.4, rng)];\n  }\n\n  assert_chi_squared(counts, expected, 1e-6);\n}\n", "meta": {"hexsha": "a62d4c2ad69fe5b213e91a269ca41aafd6205569", "size": 938, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/math_unit/math/prim/scal/prob/bernoulli_test.cpp", "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": "tests/math_unit/math/prim/scal/prob/bernoulli_test.cpp", "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": "tests/math_unit/math/prim/scal/prob/bernoulli_test.cpp", "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": 29.3125, "max_line_length": 79, "alphanum_fraction": 0.697228145, "num_tokens": 296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743735019595, "lm_q2_score": 0.6224593382055109, "lm_q1q2_score": 0.46072845068670837}}
{"text": "#include \"tensor.hpp\"\n\n#include <Eigen/Dense>\n\nusing namespace Eigen;\n\nTensorXd::TensorXd(int nrow, int ncol, int nslice)\n    : nrow_(nrow), ncol_(ncol), nslice_(nslice),\n      value_(MatrixXd::Zero(nrow_, ncol_ * nslice_)) {}\n\nBlock<MatrixXd> TensorXd::operator[](int slice) {\n  return value_.block(0, slice * ncol_, nrow_, ncol_);\n}", "meta": {"hexsha": "b6de34af6b14f13202798ed0da5f38b362ec810b", "size": 334, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/tensor.cc", "max_stars_repo_name": "pan3rock/InvBlockTridiagonalMatrice", "max_stars_repo_head_hexsha": "695d22cf990b9e66141c7d6b1acde5688f333724", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/tensor.cc", "max_issues_repo_name": "pan3rock/InvBlockTridiagonalMatrice", "max_issues_repo_head_hexsha": "695d22cf990b9e66141c7d6b1acde5688f333724", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tensor.cc", "max_forks_repo_name": "pan3rock/InvBlockTridiagonalMatrice", "max_forks_repo_head_hexsha": "695d22cf990b9e66141c7d6b1acde5688f333724", "max_forks_repo_licenses": ["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.6923076923, "max_line_length": 55, "alphanum_fraction": 0.6946107784, "num_tokens": 103, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7401743735019595, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4607284455027814}}
{"text": "/* Boost test/fmod.cpp\r\n * test the fmod with specially crafted integer intervals\r\n *\r\n * Copyright Guillaume Melquiond 2002-2003\r\n * Permission to use, copy, modify, sell, and distribute this software\r\n * is hereby granted without fee provided that the above copyright notice\r\n * appears in all copies and that both that copyright notice and this\r\n * permission notice appear in supporting documentation.\r\n *\r\n * None of the above authors nor Polytechnic University make any\r\n * representation about the suitability of this software for any\r\n * purpose. It is provided \"as is\" without express or implied warranty.\r\n *\r\n * $Id: fmod.cpp,v 1.3 2003/02/05 17:34:36 gmelquio Exp $\r\n */\r\n\r\n#include <boost/numeric/interval/interval.hpp>\r\n#include <boost/numeric/interval/arith.hpp>\r\n#include <boost/numeric/interval/arith2.hpp>\r\n#include <boost/numeric/interval/utility.hpp>\r\n#include <boost/numeric/interval/checking.hpp>\r\n#include <boost/numeric/interval/rounding.hpp>\r\n#include <boost/test/minimal.hpp>\r\n\r\nstruct my_rounded_arith {\r\n  int sub_down(int x, int y) { return x - y; }\r\n  int sub_up  (int x, int y) { return x - y; }\r\n  int mul_down(int x, int y) { return x * y; }\r\n  int mul_up  (int x, int y) { return x * y; }\r\n  int div_down(int x, int y) {\r\n    int q = x / y;\r\n    return (x % y < 0) ? (q - 1) : q;\r\n  }\r\n  int int_down(int x) { return x; }\r\n};\r\n\r\nusing namespace boost;\r\nusing namespace numeric;\r\nusing namespace interval_lib;\r\n\r\ntypedef change_rounding<interval<int>, save_state_nothing<my_rounded_arith> >::type I;\r\n\r\nint test_main(int, char *[]) {\r\n\r\n  BOOST_CHECK(equal(fmod(I(6,9), 7), I(6,9)));\r\n  BOOST_CHECK(equal(fmod(6, I(7,8)), I(6,6)));\r\n  BOOST_CHECK(equal(fmod(I(6,9), I(7,8)), I(6,9)));\r\n\r\n  BOOST_CHECK(equal(fmod(I(13,17), 7), I(6,10)));\r\n  BOOST_CHECK(equal(fmod(13, I(7,8)), I(5,6)));\r\n  BOOST_CHECK(equal(fmod(I(13,17), I(7,8)), I(5,10)));\r\n\r\n  BOOST_CHECK(equal(fmod(I(-17,-13), 7), I(4,8)));\r\n  BOOST_CHECK(equal(fmod(-17, I(7,8)), I(4,7)));\r\n  BOOST_CHECK(equal(fmod(I(-17,-13), I(7,8)), I(4,11)));\r\n\r\n  return 0;\r\n}\r\n", "meta": {"hexsha": "dc4d86d0a7c85c7e35a01e50112331bd9cf6f59e", "size": 2057, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sdk/boost_1_30_0/libs/numeric/interval/test/fmod.cpp", "max_stars_repo_name": "acidicMercury8/xray-1.0", "max_stars_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-01-30T12:51:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-31T08:36:49.000Z", "max_issues_repo_path": "sdk/boost_1_30_0/libs/numeric/interval/test/fmod.cpp", "max_issues_repo_name": "acidicMercury8/xray-1.0", "max_issues_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_issues_repo_licenses": ["Linux-OpenIB"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sdk/boost_1_30_0/libs/numeric/interval/test/fmod.cpp", "max_forks_repo_name": "acidicMercury8/xray-1.0", "max_forks_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.8644067797, "max_line_length": 87, "alphanum_fraction": 0.6655323286, "num_tokens": 620, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743735019594, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.46072844550278136}}
{"text": "#include \"kernel_test.hpp\"\n\n#include <boost/test/unit_test.hpp>\n#include <random>\n#include <iostream>\n\nnamespace GooBalls {\nnamespace d2 {\nnamespace Physics {\n/**\n * Properties a kernel should have:\n * C^0, C^1 continuous\n * evaluated at r = h, the value should be zero\n * Kernel must be normalized: int_X W(|x - x_i|) dx = 1\n */\n\n/// Create `samples` 2d points on unit disk\nCoordinates2d randomUnitDisk(int samples){\n    std::mt19937 rnd;\n    rnd.seed(23);\n    std::uniform_real_distribution<> dist(0.0, 1.0);\n    Coordinates2d Xs(samples, 2);\n    for(int i = 0; i < samples; ++i){\n        do {\n            Xs(i, 0) = dist(rnd);\n            Xs(i, 1) = dist(rnd);\n            // rejection sampling\n        } while (Xs.row(i).norm() > 1.0);\n    }\n    return Xs;\n}\n\nCoordinates1d increasingToOne(int n){\n    Coordinates1d Xorig(n);\n    for(int i = 0; i  < n; ++i){\n        Xorig[i] = double(i)/n;\n    }\n    assert(Xorig.maxCoeff() < 1.0);\n    return Xorig;\n}\n\nstd::vector<Float> getHs(){\n    std::vector<Float> hs;\n    hs.push_back(0.1);\n    hs.push_back(0.5);\n    hs.push_back(1.0);\n    hs.push_back(5.0);\n    hs.push_back(10.0);\n    hs.push_back(50.0);\n    hs.push_back(100.0);\n    return hs;\n}\n\n\nvoid testRadialSymmetry(Kernel& k, int experiments){\n    int radiusSamples = std::sqrt(experiments);\n    int angleSamples = radiusSamples;\n    auto hs = getHs();\n    for(auto h : hs){\n        k.setH(h);\n        Coordinates2d Xs(angleSamples, 2);\n        Coordinates1d w, wgradN, wlap;\n        Coordinates2d wgrad;\n        Coordinates2d dirs(angleSamples, 2);\n        for(int i = 1; i < radiusSamples; ++i){\n            Float radius = i/double(radiusSamples) * h;\n            for(int j = 0; j < angleSamples; ++j){\n                Float angle = i/double(angleSamples) * 2*M_PI;\n                dirs(j, 0) = std::sin(angle);\n                dirs(j, 1) = std::cos(angle);\n            }\n            Xs = dirs * radius;\n            k.compute(Xs, &w, &wgrad, &wlap);\n            wgradN = wgrad.rowwise().norm();\n            BOOST_TEST(w.maxCoeff() - w.minCoeff() < 0.0001);\n            BOOST_TEST(wlap.maxCoeff() - wlap.minCoeff() < 0.0001);\n            BOOST_TEST(wgradN.maxCoeff() - wgradN.minCoeff() < 0.0001);\n            // TODO: check gradient direction\n        }\n    }\n}\n\nvoid testZeroBorder1d(Kernel& k){\n    auto hs = getHs();\n    Coordinates1d ws(hs.size());\n    for(size_t i = 0; i < hs.size(); ++i){\n        Float h = hs[i];\n        k.setH(h);\n        Coordinates1d Xs(1);\n        Xs[0] = h;\n        Coordinates1d w;\n        k.compute1d(Xs.array()*Xs.array(), &w, nullptr, nullptr);\n        ws[i] = w[0];\n        // BOOST_TEST(w[0] == 0.0);\n    }\n    ws = ws.array().abs();\n    BOOST_TEST(ws.maxCoeff() == 0.0);\n}\n\nvoid testZeroBorder(Kernel& k, int experiments){\n    std::mt19937 rnd;\n    rnd.seed(17); // we use a fixed seed for repeatability\n    std::uniform_real_distribution<> dist(-10.0, 10.0);\n    Coordinates1d ws(experiments);\n    for(int i = 0; i < experiments; ++i){\n        Coordinates2d x(1,2);\n        x(0,0) = dist(rnd);\n        x(0,1) = dist(rnd);\n        auto h = x.norm();\n        k.setH(h);\n        Coordinates1d w;\n        k.compute(x, &w, nullptr, nullptr);\n        ws[i] = w[0];\n        //BOOST_TEST(w[0] == 0.0);\n    }\n    ws = ws.array().abs();\n    BOOST_TEST(ws.maxCoeff() == 0.0);\n}\n\nvoid testZeroBorderGradient1d(Kernel& k){\n    auto hs = getHs();\n    for(auto h : hs){\n        k.setH(h);\n        Coordinates1d Xs(1);\n        Xs[0] = h;\n        Coordinates1d w;\n        k.compute1d(Xs.array()*Xs.array(), nullptr, &w, nullptr);\n        BOOST_TEST(w[0] == 0.0);\n    }\n}\n\nvoid testZeroBorderGradient(Kernel& k, int experiments){\n    Coordinates2d Xorig = randomUnitDisk(experiments).rowwise().normalized();\n    auto hs = getHs();\n    for(auto h : hs){\n        Coordinates2d Xs = h*Xorig;\n        Coordinates2d Wgrad;\n        k.setH(h);\n        k.compute(Xs, nullptr, &Wgrad, nullptr);\n        int i;\n        auto extrema = Wgrad.rowwise().norm();\n        extrema.maxCoeff(&i);\n        BOOST_TEST(Wgrad.row(i).norm() == 0.0);\n        BOOST_TEST(Wgrad(i, 0) == 0.0);\n        BOOST_TEST(Wgrad(i, 1) == 0.0);\n    }\n}\n\nvoid testNonNegativity(Kernel& k, int experiments){\n    Coordinates2d Xs = randomUnitDisk(experiments);\n    Coordinates1d W;\n    k.setH(1.0);\n    k.compute(Xs, &W, nullptr, nullptr);\n    for(int i = 0; i < experiments; ++i){\n        BOOST_TEST(0 <= W[i]);\n    }\n}\n\n\nvoid testMonotonicity(Kernel& k, int experiments){\n    Coordinates2d Xs(experiments, 2);\n    Xs.setZero();\n    Float h = 1.0;\n    for(int i = 0; i < experiments; ++i){\n        Xs(i, 0) = i/double(experiments-1)*h;\n    }\n    k.setH(h);\n    Coordinates1d w;\n    k.compute(Xs, &w, nullptr, nullptr);\n    for(int i = 1; i < experiments; ++i){\n        BOOST_TEST(w[i-1] >= w[i], std::to_string(i) + \": \" + std::to_string(w[i-1]) + \" >=! \" + std::to_string(w[i]));\n    }\n}\n\nvoid testGradientFiniteDifference(Kernel& k, int experiments){\n    const Coordinates2d Xorig = randomUnitDisk(experiments);\n    auto hs = getHs();\n    for(auto h : hs){\n        Float dx = h * 0.00000001;\n        k.setH(h);\n        Coordinates2d Xs = 0.99 * h * Xorig.array();\n        Coordinates2d Xsx = Xs;\n        Xsx.col(0).array() += dx;\n        Coordinates2d Xsy = Xs;\n        Xsy.col(1).array() += dx;\n        Coordinates1d W0, Wx, Wy;\n        Coordinates2d WgradReceived;\n        k.compute(Xs, &W0, &WgradReceived, nullptr);\n        k.compute(Xsx, &Wx, nullptr, nullptr);\n        k.compute(Xsy, &Wy, nullptr, nullptr);\n        Coordinates2d gradExpected(Xs.rows(), 2);\n        gradExpected.col(0) = (Wx - W0)/dx;\n        gradExpected.col(1) = (Wy - W0)/dx;\n        auto diff = (gradExpected - WgradReceived).array().abs();\n        int i, j;\n        diff.maxCoeff(&i,&j);\n        BOOST_TEST(gradExpected(i, j) == WgradReceived(i, j));\n    }\n}\n\n\nvoid testGradientFiniteDifference1d(Kernel& k, int experiments){\n    auto hs = getHs();\n    Coordinates1d Xorig = increasingToOne(experiments);\n    for(auto h : hs){\n        Float dx = h * 0.000001;\n        k.setH(h);\n        Coordinates1d Xs = 0.99 * h * Xorig;\n        Coordinates1d Xsx = Xs.array() + dx;\n        Coordinates1d W0, Wx;\n        Coordinates1d WgradReceived;\n        k.compute1d(Xs.array()*Xs.array(), &W0, &WgradReceived, nullptr);\n        k.compute1d(Xsx.array()*Xsx.array(), &Wx, nullptr, nullptr);\n        Coordinates1d gradExpected = (Wx - W0)/dx;\n        auto diff = (gradExpected - WgradReceived).array().abs();\n        int i;\n        diff.maxCoeff(&i);\n        BOOST_TEST(gradExpected[i] == WgradReceived[i]);\n    }\n}\n\nvoid testLaplacianFromGradientFiniteDifferences1d(Kernel& k, int experiments){\n    const Coordinates1d Xorig = increasingToOne(experiments);\n    auto hs = getHs();\n    for(auto h : hs){\n        Float dx = h * 0.000001;\n        k.setH(h);\n        Coordinates1d Xs = 0.99*h*Xorig.array();\n        Coordinates1d Xsx = Xs.array() + dx;\n\n        Coordinates1d G0, Gx;\n        Coordinates1d Wlap;\n        k.compute1d(Xs.array()*Xs.array(), nullptr, &G0, &Wlap);\n        k.compute1d(Xsx.array()*Xsx.array(), nullptr, &Gx, nullptr);\n        Coordinates1d expectedLaplacian = (Gx - G0)/dx;\n        \n        auto diff = (expectedLaplacian - Wlap).array().abs();\n        int i;\n        diff.maxCoeff(&i);\n        BOOST_TEST(expectedLaplacian[i] == Wlap[i]);\n    }\n}\n\nvoid testLaplacianFromGradientFiniteDifferences(Kernel& k, int experiments){\n    const Coordinates2d Xorig = randomUnitDisk(experiments);\n    auto hs = getHs();\n    for(auto h : hs){\n        Float dx = h * 0.000001;\n        k.setH(h);\n        Coordinates2d Xs = 0.99*h*Xorig;\n        Coordinates2d Xsx, Xsy;\n        Xsx = Xs; Xsx.col(0).array() += dx;\n        Xsy = Xs; Xsy.col(1).array() += dx;\n\n        Coordinates2d G0, Gx, Gy;\n        Coordinates1d Wlap;\n        k.compute(Xs, nullptr, &G0, &Wlap);\n        k.compute(Xsx, nullptr, &Gx, nullptr);\n        k.compute(Xsy, nullptr, &Gy, nullptr);\n        Coordinates1d expectedLaplacian = (Gx - G0).col(0)/dx + (Gy - G0).col(1)/dx;\n        \n        auto diff = (expectedLaplacian - Wlap).array().abs();\n        int i;\n        diff.maxCoeff(&i);\n        BOOST_TEST(expectedLaplacian[i] == Wlap[i]);\n    }\n}\n\nvoid testLaplacianFiniteDifference1d(Kernel& k, int experiments){\n    const Coordinates1d Xorig = increasingToOne(experiments);\n    auto hs = getHs();\n    for(auto h : hs){\n        Float dx = h * 0.0001;\n        k.setH(h);\n        Coordinates1d Xs = 0.99 * h * Xorig.array() + dx;\n        Coordinates1d Xsx1 = Xs.array() - dx;\n        Coordinates1d Xsx2 = Xs.array() + dx;\n\n        Coordinates1d W0, Wx1, Wx2;\n        Coordinates1d Wlap;\n        k.compute1d(Xs.array()*Xs.array(), &W0, nullptr, &Wlap);\n        k.compute1d(Xsx1.array()*Xsx1.array(), &Wx1, nullptr, nullptr);\n        k.compute1d(Xsx2.array()*Xsx2.array(), &Wx2, nullptr, nullptr);\n        Coordinates1d expectedLaplacian = (Wx1 + Wx2 - 2*W0) / (dx*dx);\n        \n        auto diff = (expectedLaplacian - Wlap).array().abs();\n        int i;\n        diff.maxCoeff(&i);\n        BOOST_TEST(expectedLaplacian[i] == Wlap[i]);\n    }\n}\n\n\nvoid testLaplacianFiniteDifference(Kernel& k, int experiments){\n    const Coordinates2d Xorig = randomUnitDisk(experiments);\n    auto hs = getHs();\n    for(auto h : hs){\n        Float dx = h * 0.00001;\n        k.setH(h);\n        Coordinates2d Xs = 0.99 * h * Xorig.array() + dx;\n        Coordinates2d Xsx1, Xsx2, Xsy1, Xsy2;\n        Xsx1 = Xs; Xsx1.col(0).array() -= dx;\n        Xsx2 = Xs; Xsx2.col(0).array() += dx;\n        Xsy1 = Xs; Xsy1.col(1).array() -= dx;\n        Xsy2 = Xs; Xsy2.col(1).array() += dx;\n\n        Coordinates1d W0, Wx1, Wx2, Wy1, Wy2;\n        Coordinates1d Wlap;\n        k.compute(Xs, &W0, nullptr, &Wlap);\n        k.compute(Xsx1, &Wx1, nullptr, nullptr);\n        k.compute(Xsx2, &Wx2, nullptr, nullptr);\n        k.compute(Xsy1, &Wy1, nullptr, nullptr);\n        k.compute(Xsy2, &Wy2, nullptr, nullptr);\n        Coordinates1d expectedLaplacian = (Wx1 + Wx2 + Wy1 + Wy2 - 4*W0) / (dx*dx);\n        \n        auto diff = (expectedLaplacian - Wlap).array().abs();\n        int i;\n        diff.maxCoeff(&i);\n        BOOST_TEST(expectedLaplacian[i] == Wlap[i]);\n    }\n}\n\n\nvoid testNormalization1d(Kernel& k, int experiments){\n    auto hs = getHs();\n    Coordinates1d Xorig = increasingToOne(experiments);\n    // we integrate over [-h, h] with `experiments` steps of size (2*h/experiments)\n    for(auto h : hs){\n        Coordinates1d Xs = h*(Xorig.array()*2 - 1);\n        Float dA = h*2/experiments; // area of one test segment\n        Coordinates1d W;\n        k.setH(h);\n        k.compute1d(Xs.array()*Xs.array(), &W, nullptr, nullptr);\n        Float totalWeight = W.sum()*dA;\n        BOOST_TEST(totalWeight == 1.0);\n    }\n}\n\nvoid testNormalization(Kernel& k, int experiments){\n    auto hs = getHs();\n    int n = std::max(100.0, std::sqrt(experiments));\n    for(auto h : hs){\n        Coordinates2d Xs(n*n, 2);\n        int inserted = 0;\n        for(int i = 0; i < n; ++i){\n            for(int j = 0; j < n; ++j){\n                TranslationVector pos;\n                pos[0] = h*(2*i/double(n)-1);\n                pos[1] = h*(2*j/double(n)-1);\n                if(pos.norm() > h){\n                    continue;\n                }\n                Xs.row(inserted++) = pos;\n            }\n        }\n        Xs.conservativeResize(inserted, Eigen::NoChange);\n        Float dA;\n        dA = 2*h/n; // area of one test square\n        dA = dA*dA;\n        Coordinates1d W;\n        k.setH(h);\n        k.compute(Xs, &W, nullptr, nullptr);\n        Float totalWeight = W.sum()*dA;\n        BOOST_TEST(totalWeight == 1.0);\n    }\n}\n\n} // Physics\n} // d2\n} // GooBalls\n", "meta": {"hexsha": "609cd51cbf642911acd1252911ecd4cee359cb49", "size": 11639, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/lib/physics/2d/kernel_test.cc", "max_stars_repo_name": "Fluci/GooBalls", "max_stars_repo_head_hexsha": "4b68084303e66af368fd6bbf94aaec0950c9c6e3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/lib/physics/2d/kernel_test.cc", "max_issues_repo_name": "Fluci/GooBalls", "max_issues_repo_head_hexsha": "4b68084303e66af368fd6bbf94aaec0950c9c6e3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lib/physics/2d/kernel_test.cc", "max_forks_repo_name": "Fluci/GooBalls", "max_forks_repo_head_hexsha": "4b68084303e66af368fd6bbf94aaec0950c9c6e3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.371967655, "max_line_length": 119, "alphanum_fraction": 0.5589827305, "num_tokens": 3592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4607284383675655}}
{"text": "/* \n * benchmark_hogwild_regression.cpp\n * author: Abhijit Chowdhary (achowdh2@ncsu.edu)\n *\n * Benchmark HOGWILD! as applied to regression on to a simple random normal 50\n * x 50 matrix A and random normal vector b:\n *\n *  minimize (1/2)||Ax-b||_2^2\n *\n * Outputs to results.txt and stdout time taken to reach desired tolerance for\n * each core count possible in system.\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 <omp.h>\n#include <stdio.h>\n\n#include <algorithm>\n#include <array>\n#include <atomic>\n#include <iostream>\n#include <random>\n#include <vector>\n\n#include <Eigen/Dense>\n\n#include \"compute_variance.h\"\n\n#define N 1024\n#define ETA 0.001\n#define NUM_EPOCHS 20\n#define TRIALS_PER_BAND 100\n#define MAX_BAND_POW 10\n\nint \nmain(int argc, char **argv)\n{\n  // Initialize random state, and parallel parameters.\n  unsigned P = omp_get_max_threads();\n  Eigen::initParallel();\n  omp_set_dynamic(0);\n  std::mt19937 gen(0);\n\n  // Construct sampling w/ replacement vector.\n  std::uniform_int_distribution<std::mt19937::result_type> distN(0,N-1);\n  unsigned *rand_selection = new unsigned[N*NUM_EPOCHS];\n  for (unsigned k = 0; k < N*NUM_EPOCHS; k++)\n  {\n    rand_selection[k] = distN(gen);\n  }\n  \n  std::vector<double> computed_variances;\n  Eigen::MatrixXd X = Eigen::MatrixXd::Constant(N, 1, 1.0);\n  for (unsigned bp = 0; bp < MAX_BAND_POW; bp++)\n  {\n    unsigned band = 1 << bp;\n    Eigen::MatrixXd A = Eigen::MatrixXd::Zero(N, N);\n    A.diagonal(0) = Eigen::MatrixXd::Random(N,1);\n    for (int k = 1; k <= band; k++)\n    {\n      A.diagonal(k) = Eigen::MatrixXd::Random(N-k, 1);\n      A.diagonal(-k) = Eigen::MatrixXd::Random(N-k, 1);\n    }\n\n    Eigen::VectorXd b = A*X;\n\n    std::vector<double> computed_norms;\n    std::array<std::atomic<double>, N> x;\n    for (unsigned trial = 0; trial < TRIALS_PER_BAND; ++trial)\n    { // Begin SGD trial\n      for (unsigned k = 0; k < N; k++) { x[k] = 0.0; }\n\n      #pragma omp parallel for\n      for (unsigned k = 0; k < N*NUM_EPOCHS; k++)\n      { // Begin parallel SGD iterations\n        unsigned id = rand_selection[k];\n        double dg = 0;\n        for (unsigned i = 0; i < N; i++) { dg += A(id, i)*x[i].load(); }\n        dg -= b(id);\n        for (unsigned i = 0; i < N; i++)\n        {\n          double dgi = x[i].load() - ETA*( A(id,i)*dg );\n          x[i].exchange( dgi );\n        }\n      } // End parallel SGD iterations\n\n      Eigen::MatrixXd xx(N,1);\n      for (int k = 0; k < N; k++) { xx(k) = x[k].load(); }\n      computed_norms.push_back( 0.5*(A*xx-b).squaredNorm() );\n    } // End SGD trial\n\n    computed_variances.push_back( compute_variance(computed_norms) );\n  }\n  for (unsigned k = 0; k < computed_variances.size(); k++)\n  {\n    printf(\"%.9f\\n\", computed_variances[k]);\n  }\n  delete []rand_selection;\n  return 0;\n}\n", "meta": {"hexsha": "0dfdc0f3ad2f4693ae52b107a460d452804342f7", "size": 3016, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Tests/banded_regression/measure_banded_asyncnoise.cc", "max_stars_repo_name": "abhijit-c/HOGWILD", "max_stars_repo_head_hexsha": "1ae85888fb5c33f0cf01043064d30106e7a3de39", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tests/banded_regression/measure_banded_asyncnoise.cc", "max_issues_repo_name": "abhijit-c/HOGWILD", "max_issues_repo_head_hexsha": "1ae85888fb5c33f0cf01043064d30106e7a3de39", "max_issues_repo_licenses": ["MIT"], "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/banded_regression/measure_banded_asyncnoise.cc", "max_forks_repo_name": "abhijit-c/HOGWILD", "max_forks_repo_head_hexsha": "1ae85888fb5c33f0cf01043064d30106e7a3de39", "max_forks_repo_licenses": ["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.2815533981, "max_line_length": 79, "alphanum_fraction": 0.6061007958, "num_tokens": 879, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4607284383675655}}
{"text": "//\n// Copyright (c) 2015-2019 CNRS INRIA\n//\n\n/*\n * Validate the sparse Cholesky decomposition of the mass matrix.  The code\n * tests both the numerical value and the computation time. For a strong\n * computation benchmark, see benchmark/timings.\n *\n */\n\n#include \"pinocchio/spatial/se3.hpp\"\n#include \"pinocchio/multibody/model.hpp\"\n#include \"pinocchio/multibody/data.hpp\"\n#include \"pinocchio/algorithm/crba.hpp\"\n#include \"pinocchio/algorithm/cholesky.hpp\"\n#include \"pinocchio/parsers/sample-models.hpp\"\n#include \"pinocchio/utils/timer.hpp\"\n#include \"pinocchio/algorithm/joint-configuration.hpp\"\n\n#include <iostream>\n#ifdef NDEBUG\n#  include <Eigen/Cholesky>\n#endif\n\n#include <boost/test/unit_test.hpp>\n#include <boost/utility/binary.hpp>\n\n\nBOOST_AUTO_TEST_SUITE ( BOOST_TEST_MODULE )\n\nBOOST_AUTO_TEST_CASE ( test_cholesky )\n{\n  using namespace Eigen;\n  using namespace pinocchio;\n\n  pinocchio::Model model;\n  pinocchio::buildModels::humanoidRandom(model,true);\n  pinocchio::Data data(model);\n  \n  model.lowerPositionLimit.head<3>().fill(-1.);\n  model.upperPositionLimit.head<3>().fill(1.);\n  VectorXd q = randomConfiguration(model);\n  data.M.fill(0); // Only nonzero coeff of M are initialized by CRBA.\n  crba(model,data,q);\n \n  pinocchio::cholesky::decompose(model,data);\n  data.M.triangularView<Eigen::StrictlyLower>() = \n  data.M.triangularView<Eigen::StrictlyUpper>().transpose();\n  \n  const Eigen::MatrixXd & U = data.U;\n  const Eigen::VectorXd & D = data.D;\n  const Eigen::MatrixXd & M = data.M;\n\n  #ifndef NDEBUG\n    std::cout << \"M = [\\n\" << M << \"];\" << std::endl;\n    std::cout << \"U = [\\n\" << U << \"];\" << std::endl;\n    std::cout << \"D = [\\n\" << D.transpose() << \"];\" << std::endl;\n  #endif\n      \n  BOOST_CHECK(M.isApprox(U*D.asDiagonal()*U.transpose() , 1e-12));\n\n  Eigen::VectorXd v = Eigen::VectorXd::Random(model.nv);\n// std::cout << \"v = [\" << v.transpose() << \"]';\" << std::endl;\n\n  Eigen::VectorXd Uv = v; pinocchio::cholesky::Uv(model,data,Uv);\n  BOOST_CHECK(Uv.isApprox(U*v, 1e-12));\n\n  Eigen::VectorXd Utv = v; pinocchio::cholesky::Utv(model,data,Utv);\n  BOOST_CHECK(Utv.isApprox(U.transpose()*v, 1e-12));\n\n  Eigen::VectorXd Uiv = v; pinocchio::cholesky::Uiv(model,data,Uiv);\n  BOOST_CHECK(Uiv.isApprox(U.inverse()*v, 1e-12));\n\n\n  Eigen::VectorXd Utiv = v; pinocchio::cholesky::Utiv(model,data,Utiv);\n  BOOST_CHECK(Utiv.isApprox(U.transpose().inverse()*v, 1e-12));\n\n  Eigen::VectorXd Miv = v; pinocchio::cholesky::solve(model,data,Miv);\n  BOOST_CHECK(Miv.isApprox(M.inverse()*v, 1e-12));\n\n  Eigen::VectorXd Mv = v; Mv = pinocchio::cholesky::Mv(model,data,Mv);\n  BOOST_CHECK(Mv.isApprox(M*v, 1e-12));\n  Mv = v;                 pinocchio::cholesky::UDUtv(model,data,Mv);\n  BOOST_CHECK(Mv.isApprox(M*v, 1e-12));\n}\n\n\n/* The flag triger the following timers:\n * 000001: sparse UDUt cholesky\n * 000010: dense Eigen LDLt cholesky (with pivot)\n * 000100: sparse resolution \n * 001000: sparse U*v multiplication\n * 010000: sparse U\\v substitution\n * 100000: sparse M*v multiplication without Cholesky\n */\nBOOST_AUTO_TEST_CASE ( test_timings )\n{\n  using namespace Eigen;\n  using namespace pinocchio;\n\n  pinocchio::Model model;\n  pinocchio::buildModels::humanoidRandom(model,true);\n  pinocchio::Data data(model);\n  \n  model.lowerPositionLimit.head<3>().fill(-1.);\n  model.upperPositionLimit.head<3>().fill(1.);\n  VectorXd q = randomConfiguration(model);\n  data.M.fill(0); // Only nonzero coeff of M are initialized by CRBA.\n  crba(model,data,q);\n  \n\n  long flag = BOOST_BINARY(1111111);\n  PinocchioTicToc timer(PinocchioTicToc::US); \n  #ifdef NDEBUG\n    #ifdef _INTENSE_TESTING_\n      const size_t NBT = 1000*1000;\n    #else\n      const size_t NBT = 10;\n    #endif\n  #else \n    const size_t NBT = 1;\n    std::cout << \"(the time score in debug mode is not relevant)  \" ;\n  #endif\n\n  bool verbose = flag & (flag-1) ; // True is two or more binaries of the flag are 1.\n  if(verbose) std::cout <<\"--\" << std::endl;\n\n  if( flag >> 0 & 1 )\n    {\n      timer.tic();\n      SMOOTH(NBT)\n      {\n\tpinocchio::cholesky::decompose(model,data);\n      }\n      if(verbose) std::cout << \"Decompose =\\t\";\n      timer.toc(std::cout,NBT);\n    }\n\n  if( flag >> 1 & 1 )\n    {\n      timer.tic();\n      Eigen::VectorXd v = Eigen::VectorXd::Random(model.nv);\n      Eigen::VectorXd res(model.nv);\n      SMOOTH(NBT)\n      {\n\tEigen::LDLT <Eigen::MatrixXd> Mchol(data.M);\n\tres = Mchol.solve(v);\n      }\n      if(verbose) std::cout << \"Eigen::LDLt =\\t\";\n      timer.toc(std::cout,NBT);\n    }\n\n  if( flag >> 2 & 31 )\n    {\n      std::vector<Eigen::VectorXd> randvec(NBT);\n      for(size_t i=0;i<NBT;++i ) randvec[i] = Eigen::VectorXd::Random(model.nv);\n      Eigen::VectorXd zero = Eigen::VectorXd(model.nv);\n      Eigen::VectorXd res (model.nv);\n\n\n      if( flag >> 2 & 1 )\n\t{\n\t  timer.tic();\n\t  SMOOTH(NBT)\n\t  {\n\t    pinocchio::cholesky::solve(model,data,randvec[_smooth]);\n\t  }\n\t  if(verbose) std::cout << \"solve =\\t\\t\";\n\t  timer.toc(std::cout,NBT);\n\t}\n\n      if( flag >> 3 & 1 )\n\t{\n\t  timer.tic();\n\t  SMOOTH(NBT)\n\t  {\n\t    pinocchio::cholesky::Uv(model,data,randvec[_smooth]);\n\t  }\n\t  if(verbose) std::cout << \"Uv =\\t\\t\";\n\t  timer.toc(std::cout,NBT);\n\t}\n\n      if( flag >> 4 & 1 )\n\t{\n\t  timer.tic();\n\t  SMOOTH(NBT)\n\t  {\n\t    pinocchio::cholesky::Uiv(model,data,randvec[_smooth]);\n\t  }\n\t  if(verbose) std::cout << \"Uiv =\\t\\t\";\n\t  timer.toc(std::cout,NBT);\n\t}\n      if( flag >> 5 & 1 )\n\t{\n\t  timer.tic();\n\t  Eigen::VectorXd res;\n\t  SMOOTH(NBT)\n\t  {\n\t    res = pinocchio::cholesky::Mv(model,data,randvec[_smooth]);\n\t  }\n\t  if(verbose) std::cout << \"Mv =\\t\\t\";\n\t  timer.toc(std::cout,NBT);\n\t}\n      if( flag >> 6 & 1 )\n\t{\n    timer.tic();\n    SMOOTH(NBT)\n    {\n      pinocchio::cholesky::UDUtv(model,data,randvec[_smooth]);\n    }\n    if(verbose) std::cout << \"UDUtv =\\t\\t\";\n    timer.toc(std::cout,NBT);\n\t}\n    }\n}\n  \n  BOOST_AUTO_TEST_CASE(test_Minv_from_cholesky)\n  {\n    using namespace Eigen;\n    using namespace pinocchio;\n    \n    pinocchio::Model model;\n    pinocchio::buildModels::humanoidRandom(model,true);\n    pinocchio::Data data(model);\n    \n    model.lowerPositionLimit.head<3>().fill(-1.);\n    model.upperPositionLimit.head<3>().fill(1.);\n    VectorXd q = randomConfiguration(model);\n    crba(model,data,q);\n    data.M.triangularView<Eigen::StrictlyLower>() =\n    data.M.triangularView<Eigen::StrictlyUpper>().transpose();\n    MatrixXd Minv_ref(data.M.inverse());\n    \n    cholesky::decompose(model,data);\n    VectorXd v_unit(VectorXd::Unit(model.nv,0));\n\n    VectorXd Ui_v_unit(model.nv);\n    VectorXd Ui_v_unit_ref(model.nv);\n    \n    for(int k = 0; k < model.nv; ++k)\n    {\n      v_unit = VectorXd::Unit(model.nv,k);\n      Ui_v_unit.setZero();\n      cholesky::internal::Miunit(model,data,k,Ui_v_unit);\n      Ui_v_unit_ref = v_unit;\n      cholesky::Uiv(model,data,Ui_v_unit_ref);\n      Ui_v_unit_ref.array() *= data.Dinv.array();\n      cholesky::Utiv(model,data,Ui_v_unit_ref);\n\n      BOOST_CHECK(Ui_v_unit.isApprox(Ui_v_unit_ref));\n      \n      Ui_v_unit_ref = v_unit;\n      cholesky::solve(model,data,Ui_v_unit_ref);\n      BOOST_CHECK(Ui_v_unit.isApprox(Ui_v_unit_ref));\n      \n//      std::cout << \"Ui_v_unit : \" << Ui_v_unit.transpose() << std::endl;\n//      std::cout << \"Ui_v_unit_ref : \" << Ui_v_unit_ref.transpose() << std::endl << std::endl;\n    }\n    \n    MatrixXd Minv(model.nv,model.nv);\n    Minv.setZero();\n    cholesky::computeMinv(model,data,Minv);\n    \n    BOOST_CHECK(Minv.isApprox(Minv_ref));\n    \n    // Check second call to cholesky::computeMinv\n    cholesky::computeMinv(model,data,Minv);\n    BOOST_CHECK(Minv.isApprox(Minv_ref));\n    \n    // Call the second signature of cholesky::computeMinv\n    Data data_bis(model);\n    crba(model,data_bis,q);\n    cholesky::decompose(model,data_bis);\n    cholesky::computeMinv(model,data_bis);\n    BOOST_CHECK(data_bis.Minv.isApprox(Minv_ref));\n  }\n\nBOOST_AUTO_TEST_SUITE_END ()\n", "meta": {"hexsha": "448c9d696ceaa4d871571d1f31f6bfd303fb0f57", "size": 7835, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittest/cholesky.cpp", "max_stars_repo_name": "thanhndv212/pinocchio", "max_stars_repo_head_hexsha": "3b4d272bf4e8a231954b71201ee7e0963c944aef", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2020-05-10T08:06:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-22T14:26:57.000Z", "max_issues_repo_path": "unittest/cholesky.cpp", "max_issues_repo_name": "thanhndv212/pinocchio", "max_issues_repo_head_hexsha": "3b4d272bf4e8a231954b71201ee7e0963c944aef", "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": "unittest/cholesky.cpp", "max_forks_repo_name": "thanhndv212/pinocchio", "max_forks_repo_head_hexsha": "3b4d272bf4e8a231954b71201ee7e0963c944aef", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-09-21T01:20:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-12T18:59:35.000Z", "avg_line_length": 27.9821428571, "max_line_length": 95, "alphanum_fraction": 0.6427568602, "num_tokens": 2395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4607284383675655}}
{"text": "///////////////////////////////////////////////////////////////\n//  Copyright 2021 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// Simple test that cpp_int -> double conversion has less than 0.5ulp error\n// and rounds to even in case of ties.\n// See https://github.com/boostorg/multiprecision/issues/360.\n//\n#ifdef _MSC_VER\n#define _SCL_SECURE_NO_WARNINGS\n#endif\n\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_int.hpp>\n#include \"test.hpp\"\n\nusing namespace boost::multiprecision;\n\n#ifdef BOOST_MSVC\n#pragma warning(disable : 4127)\n#endif\n\ntemplate <class T>\nT generate_random(unsigned bits_wanted)\n{\n   static boost::random::mt19937               gen;\n   typedef boost::random::mt19937::result_type random_type;\n\n   T        max_val;\n   unsigned digits;\n   if (std::numeric_limits<T>::is_bounded && (bits_wanted == (unsigned)std::numeric_limits<T>::digits))\n   {\n      max_val = (std::numeric_limits<T>::max)();\n      digits  = std::numeric_limits<T>::digits;\n   }\n   else\n   {\n      max_val = T(1) << bits_wanted;\n      digits  = bits_wanted;\n   }\n\n   unsigned bits_per_r_val = std::numeric_limits<random_type>::digits - 1;\n   while ((random_type(1) << bits_per_r_val) > (gen.max)())\n      --bits_per_r_val;\n\n   unsigned terms_needed = digits / bits_per_r_val + 1;\n\n   T val = 0;\n   for (unsigned i = 0; i < terms_needed; ++i)\n   {\n      val *= (gen.max)();\n      val += gen();\n   }\n   val %= max_val;\n   return val;\n}\n\ntemplate <class From, class To>\nvoid test_convert()\n{\n   boost::random::mt19937 gen;\n   boost::random::uniform_int_distribution<> d(20, (std::min)(200, std::numeric_limits<To>::max_exponent - 2));\n\n   for (unsigned i = 0; i < 10000; ++i)\n   {\n      int  bits = d(gen);\n      From from = generate_random<From>(bits);\n      To   t1(from);\n      From b(t1);\n      std::size_t m = msb(from);\n      if (m >= std::numeric_limits<To>::digits)\n      {\n         // For error <= 1ulp\n         // Note msb(from) returns one less than the number of bits in from:\n         From max_error = (From(1) << (m - std::numeric_limits<To>::digits));\n         BOOST_TEST_GE(max_error, abs(b - from));\n         if (max_error < abs(b - from))\n            // debugging help:\n            std::cout << from << std::endl\n                      << b << std::endl\n                      << abs(b - from) << std::endl;\n         if (max_error == abs(b - from))\n         {\n            // Check we rounded to even in case of tie:\n            BOOST_TEST_GT(lsb(b), (1 + msb(from) - std::numeric_limits<To>::digits));\n            if (lsb(b) <= (1 + msb(from) - std::numeric_limits<To>::digits))\n            {\n               // debugging help:\n               std::cout << from << std::endl\n                         << b << std::endl\n                         << abs(b - from) << std::endl;\n            }\n         }\n      }\n      else\n      {\n         BOOST_TEST_EQ(b, from);\n      }\n   }\n}\n\nint main()\n{\n   test_convert<cpp_int, float>();\n   test_convert<cpp_int, double>();\n   return boost::report_errors();\n}\n", "meta": {"hexsha": "4c2b62c6f9a83804099aaf9c11828a018dbf3200", "size": 3192, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_convert_cpp_int_2_float.cpp", "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": "test/test_convert_cpp_int_2_float.cpp", "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": "test/test_convert_cpp_int_2_float.cpp", "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": 29.0181818182, "max_line_length": 111, "alphanum_fraction": 0.569235589, "num_tokens": 838, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390162, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.46072843836756544}}
{"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// Written by Simon Praetorius\n\n\n#ifndef ITL_GCR_INCLUDE\n#define ITL_GCR_INCLUDE\n\n#include <boost/numeric/mtl/concept/collection.hpp>\n\nnamespace itl\n{\n\n  template <typename Matrix, typename Vector, typename Preconditioner, typename Iteration>\n  int gcr_full(const Matrix& A, Vector& x, const Vector& b, const Preconditioner& P, Iteration& iter)\n  {\n    using math::reciprocal;\n    typedef typename mtl::Collection<Vector>::value_type Scalar;\n    typedef typename mtl::Collection<Vector>::size_type Size;\n\n    if (size(b) == 0)\n      throw mtl::logic_error(\"empty rhs vector\");\n\n    Scalar zero= math::zero(b[0]), dbl_tol= 1.e-16; // TODO: tolerance as parameter or otherwise generalized\n\n    Size k, kmax(std::min(size(x), Size(iter.max_iterations() - iter.iterations())));\n\n    Vector r(b - A * x);\n    Vector uk(size(x), zero), ck(size(x), zero);\n    mtl::matrix::multi_vector<Vector> C(Vector(resource(x), zero), kmax);\n    mtl::matrix::multi_vector<Vector> U(Vector(resource(x), zero), kmax);\n\n    Scalar res(two_norm(r));\n    Scalar alpha(zero), beta(zero), gamma(zero);\n\n    for (k= 0; k < kmax && !iter.finished(res); ++k, ++iter)\n    {\n      uk = solve(P, r);\n      // In order to avoid breakdown, use LSQR switch\n      // Cite: C. Vuik, Further experiences with GMRESR, 1993\n      //  if (two_norm(uk) < dbl_tol)\n      //    uk = trans(A) * r; // requires transposed multiplication\n\n      ck = A * uk;\n      for (size_t i = 0; i < k; i++)\n      {\n        alpha = dot(C.vector(i), ck);\n\n        ck -= alpha * C.vector(i);\n        uk -= alpha * U.vector(i);\n      }\n\n      beta = two_norm(ck);\n      if (beta < dbl_tol)\n        return iter.fail(2, \"search direction close to 0\");\n\n      C.vector(k) = ck * reciprocal(beta);\n      U.vector(k) = uk * reciprocal(beta);\n\n      gamma = dot(C.vector(k), r);\n      x += U.vector(k) * gamma;\n      r -= C.vector(k) * gamma;\n\n      res = two_norm(r);\n    }\n\n    return iter;\n  }\n\n#if 0\n  template <typename Matrix, typename Vector, typename LeftPreconditioner, typename RightPreconditioner, typename Iteration>\n  int gmresr_trunc(const Matrix& A, Vector& x, const Vector& b, const LeftPreconditioner& L, const RightPreconditioner& R,\n                   Iteration& iter, , typename mtl::Collection<Vector>::size_type nTrunc)\n  {\nTODO:\n    implement truncated GCR solver, instead of restarted version\nCite:\n    C. Vuik, Further experiences with GMRESR, 1993\n  }\n#endif\n\n  /// Generalized Conjugate Residual method with restart\n  /// Cite: S.C. Eisenstat, H.C. Elman, M.H. Schultz, Variational iterative methods for non symmetric systems of linear equations, 1983\n  /// Cite: C. Vuik, New insight in GMRES-like methods with variable preconditioners\n  template <typename Matrix, typename Vector, typename LeftPreconditioner,\n            typename RightPreconditioner, typename Iteration>\n  int gcr(const Matrix& A, Vector& x, const Vector& b, LeftPreconditioner& /*L*/, RightPreconditioner& R,\n          Iteration& iter, typename mtl::Collection<Vector>::size_type restart)\n  {\n    do\n    {\n      Iteration inner(iter);\n      inner.set_max_iterations(std::min(int(iter.iterations()+restart), iter.max_iterations()));\n      inner.suppress_resume(true);\n      gcr_full(A, x, b, R, inner);\n      iter.update_progress(inner);\n    }\n    while (!iter.finished());\n\n    return iter;\n  }\n} // namespace itl;\n\n#endif // ITL_GMR_INCLUDE\n\n", "meta": {"hexsha": "931cbf802d2a45dc7a7dce2c0f8a886b506dc47f", "size": 4069, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/solver/itl/gcr.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/solver/itl/gcr.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/solver/itl/gcr.hpp", "max_forks_repo_name": "spraetor/amdis2", "max_forks_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.814516129, "max_line_length": 135, "alphanum_fraction": 0.6365200295, "num_tokens": 1031, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.4607284383675654}}
{"text": "//\n// Created by Shiina Miyuki on 2019/1/30.\n//\n#include \"../core/transform.h\"\n#include \"../core/interaction.h\"\n#define BOOST_AUTO_TEST_MAIN\n#define  BOOST_TEST_MODULE TransformTest\n\n#include <boost/test/unit_test.hpp>\n#include <boost/test/unit_test_log.hpp>\n#include <boost/filesystem/fstream.hpp>\n\nnamespace utf = boost::unit_test;\nusing namespace Miyuki;\nBOOST_AUTO_TEST_CASE(TestIndentity, *utf::tolerance(float(0.0001))) {\n    std::random_device rd;\n    std::uniform_real_distribution<Float> dist(-1.0f, 1.f);\n    auto I = Matrix4x4::identity();\n    for (int i = 0; i < 10; i++) {\n        Vec3f v(dist(rd),dist(rd),dist(rd));\n        Vec3f v2 = v;\n        v = I.mult(v);\n        BOOST_TEST(v.x() == v2.x());\n        BOOST_TEST(v.y() == v2.y());\n        BOOST_TEST(v.z() == v2.z());\n    }\n}\nBOOST_AUTO_TEST_CASE(TestInverse, *utf::tolerance(float(0.001))) {\n    std::random_device rd;\n    std::uniform_real_distribution<Float> dist(-1.0f, 1.f);\n    for (int i = 0; i < 10; i++) {\n        Matrix4x4 m;\n        for(int k = 0;k<16;k++){\n            m[k] = dist(rd);\n        }\n        Matrix4x4 inv;\n        if(Matrix4x4::inverse(m, inv)){\n            Vec3f v(dist(rd),dist(rd),dist(rd));\n            Vec3f v2 = v;\n            auto I = inv.mult(m);\n            v = inv.mult(m.mult(v));\n            BOOST_TEST(v.x() == v2.x());\n            BOOST_TEST(v.y() == v2.y());\n            BOOST_TEST(v.z() == v2.z());\n        }\n    }\n}\n\nBOOST_AUTO_TEST_CASE(TestTranslation, *utf::tolerance(float(0.0001))) {\n    std::random_device rd;\n    std::uniform_real_distribution<Float> dist(-10000.0f, 10000.0f);\n    auto t = Transform();\n    auto m = Matrix4x4::identity();\n    for (int i = 0; i < 10; i++) {\n        Vec3f tr(dist(rd), dist(rd), dist(rd));\n        m = m.mult(Matrix4x4::translation(tr));\n        t.translation += tr;\n        Vec3f v(dist(rd), dist(rd), dist(rd));\n        v.w() = 1;\n        auto a = m.mult(v);\n        auto b = t.apply(v);\n        BOOST_TEST(a.x() == b.x());\n        BOOST_TEST(a.y() == b.y());\n        BOOST_TEST(a.z() == b.z());\n    }\n}\nBOOST_AUTO_TEST_CASE(TestWorldLocal, *utf::tolerance(float(0.001))) {\n    std::random_device rd;\n    std::uniform_real_distribution<Float> dist(-1.0f, 1.f);\n    Interaction interaction;\n    interaction.normal = Vec3f{dist(rd), dist(rd), dist(rd)};\n    interaction.normal.normalize();\n    interaction.computeLocalCoordinate();\n    Vec3f v(dist(rd), dist(rd), dist(rd));\n    v.normalize();\n    Vec3f v3 = interaction.worldToLocal(v);\n    Vec3f v2 = interaction.localToWorld(v3);\n    BOOST_TEST(v.x() == v2.x());\n    BOOST_TEST(v.y() == v2.y());\n    BOOST_TEST(v.z() == v2.z());\n}", "meta": {"hexsha": "22fb7ec47780dc1b6c0d042584fa3e162a9d22dc", "size": 2634, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/unittest/test_transform.cc", "max_stars_repo_name": "sylvainbouxin/MiyukiRenderer", "max_stars_repo_head_hexsha": "88242b9e18ca7eaa1c751ab07f585fac8b591b5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/unittest/test_transform.cc", "max_issues_repo_name": "sylvainbouxin/MiyukiRenderer", "max_issues_repo_head_hexsha": "88242b9e18ca7eaa1c751ab07f585fac8b591b5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/unittest/test_transform.cc", "max_forks_repo_name": "sylvainbouxin/MiyukiRenderer", "max_forks_repo_head_hexsha": "88242b9e18ca7eaa1c751ab07f585fac8b591b5a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-09-11T20:20:54.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-11T20:20:54.000Z", "avg_line_length": 32.5185185185, "max_line_length": 71, "alphanum_fraction": 0.5732725892, "num_tokens": 761, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.4607284312323493}}
{"text": "/**\n * \\file hungarian.hpp\n * \\brief\n *\n * \\author Andrew Price\n * \\date 2016-4-19\n *\n * \\copyright\n *\n * Copyright (c) 2020, Andrew Price\n * All rights reserved.\n *\n * This file is provided under the following \"BSD-style\" License:\n * Redistribution and use in source and binary forms, with or\n * without modification, are permitted provided that the following\n * conditions are met:\n * * Redistributions of source code must retain the above copyright\n *   notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n *   copyright notice, this list of conditions and the following\n *   disclaimer in the documentation and/or other materials provided\n *   with the distribution.\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND\n * CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\n * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef HUNGARIAN_HPP\n#define HUNGARIAN_HPP\n\n#include <Eigen/Core>\n#include <vector>\n\n// Implementation of the Hungarian Algorithm derived from https://www.topcoder.com/community/data-science/data-science-tutorials/assignment-problem-and-hungarian-algorithm/\n\nnamespace mps\n{\n\n// TODO: template for multiple cost matrix types\n\n/**\n * @brief The Hungarian class solves the optimal nxn assignment problem in O(n^3) time.\n * The results are reported as a mapping from x to y (row to column of cost matrix)\n *\n * Formally, the system is defined as follows:\n * Given two sets \\f$ X, Y \\in \\mathbb{R}^n \\f$ and a cost matrix \\f$ C:X \\times Y \\rightarrow \\mathbb{R} \\f$,\n * find a bijection \\f$ f:X \\rightarrow Y \\f$ that minimizes the cost function \\f$ \\sum_{x\\in X}C[x,f(x)] \\f$.\n */\nclass Hungarian\n{\npublic:\n\tHungarian(const Eigen::MatrixXd& cost);\n\n\t/**\n\t * @brief getSolutionCost returns the current linear cost of the assignment\n\t * @return Solution cost of the form C(x1,xToY(x1)) + C(x2,xToY(x2)) + ...\n\t */\n\tdouble getSolutionCost();\n\n\t/**\n\t * @brief getAssignment Returns the optimal choice of y for each x in sequence\n\t * @return y-index of optimal pairing for each x\n\t */\n\tconst std::vector<int>& getAssignment() { return xy; }\n\nprotected:\n\tEigen::MatrixXd C;            ///< Cost matrix (nxn)\n\tconst int N;                  ///< Number of pairings to find\n\tint maxMatch;                 ///< Number of pairings locked so far\n\tstd::vector<double> lx;\n\tstd::vector<double> ly;\n\tstd::vector<int> xy;          ///< Mapping from x to y index\n\tstd::vector<int> yx;          ///< Mapping from y to x index\n\tstd::vector<double> slack;\n\tstd::vector<double> slackx;\n\tstd::vector<int> prev;        ///< Alternating tree\n\tstd::vector<bool> S;          ///< Set of matched x indices\n\tstd::vector<bool> T;          ///< Set of matched y indices\n\n\tvoid augment();\n\tvoid relabel();\n\tvoid addToTree(int x, int prevx);\n\n};\n\ndouble Hungarian::getSolutionCost()\n{\n\tdouble cost = 0;\n\tfor (int x = 0; x < N; ++x)\n\t{\n\t\tcost += C(x, xy[x]);\n\t}\n\treturn -cost;\n}\n\nHungarian::Hungarian(const Eigen::MatrixXd& cost)\n    : C(-cost), // Negate cost, as this algorithm finds the maximum assignment\n      N(C.cols()),\n      maxMatch(0),\n      lx(N, 0),\n      ly(N, 0),\n      xy(N,-1),\n      yx(N,-1),\n      slack(N),\n      slackx(N),\n      prev(N),\n      S(N),\n      T(N)\n{\n\t// Initial labelling\n\tfor (int x = 0; x < N; ++x)\n\t\tfor (int y = 0; y < N; ++y)\n\t\t\tlx[x] = std::max(lx[x], C(x,y));\n\n\t// Solve\n\taugment();\n}\n\nvoid Hungarian::relabel()\n{\n\tdouble delta = std::numeric_limits<double>::infinity();\n\n\tfor (int y = 0; y < N; ++y) // compute delta with slack\n\t\tif (!T[y]) { delta = std::min(delta, slack[y]); }\n\tassert(std::isfinite(delta));\n\tfor (int x = 0; x < N; ++x) // update X labels\n\t\tif (S[x]) { lx[x] -= delta; }\n\tfor (int y = 0; y < N; ++y) // update Y labels\n\t\tif (T[y]) { ly[y] += delta; }\n\tfor (int y = 0; y < N; ++y) // update slack array\n\t\tif (!T[y]) { slack[y] -= delta; }\n}\n\nvoid Hungarian::addToTree(int x, int prevx)\n{\n\tS[x] = true;\n\tprev[x] = prevx;\n\tfor (int y = 0; y < N; ++y)\n\t{\n\t\tdouble newCost = lx[x] + ly[y] - C(x,y);\n\t\tif (newCost < slack[y])\n\t\t{\n\t\t\tslack[y] = newCost;\n\t\t\tslackx[y] = x;\n\t\t}\n\t}\n}\n\nvoid Hungarian::augment()\n{\n\tif (maxMatch == N) { return; }\n\tint x = -1, y = -1, root = -1;\n\tstd::vector<int> q(N);\n\tint wr = 0, rd = 0;\n\n\t// Initialize sets and tree\n\tstd::fill(S.begin(), S.end(), false);\n\tstd::fill(T.begin(), T.end(), false);\n\tstd::fill(prev.begin(), prev.end(), -1);\n\n\t// Find root of tree\n\tfor (x = 0; x < N; ++x)\n\t{\n\t\tif (-1 == xy[x])\n\t\t{\n\t\t\tq[wr++] = root = x;\n\t\t\tprev[x] = -2;\n\t\t\tS[x] = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t// Initialize slack array\n\tfor (y = 0; y < N; ++y)\n\t{\n\t\tslack[y] = lx[root] + ly[y] - C(root,y);\n\t\tslackx[y] = root;\n\t}\n\n\twhile (true)\n\t{\n\t\twhile (rd < wr) // build tree with bfs\n\t\t{\n\t\t\tx = q[rd++];\n\t\t\tfor (y = 0; y < N; ++y)\n\t\t\t{\n\t\t\t\tif (C(x,y) == lx[x] + ly[y] && !T[y])\n\t\t\t\t{\n\t\t\t\t\tif (-1 == yx[y]) { break; } // found an isolated Y vertex\n\t\t\t\t\tT[y] = true; // else y is in T\n\t\t\t\t\tq[wr++] = yx[y]; // add target of y to frontier of bfs\n\t\t\t\t\taddToTree(yx[y], x);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (y < N) { break; } // Breaking out from inmost loop\n\t\t}\n\t\tif (y < N) { break; } // Breaking out from inmost loop\n\n\t\trelabel();\n\t\twr = rd = 0;\n\n\t\tfor (y = 0; y < N; ++y)\n\t\t{\n\t\t\tif (!T[y] && 0 == slack[y])\n\t\t\t{\n\t\t\t\tif (-1 == yx[y])\n\t\t\t\t{\n\t\t\t\t\tx = slackx[y];\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tT[y] = true;\n\t\t\t\t\tif (!S[yx[y]])\n\t\t\t\t\t{\n\t\t\t\t\t\tq[wr++] = yx[y];\n\t\t\t\t\t\taddToTree(yx[y], slackx[y]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (y < N) { break; }\n\t}\n\n\tif (y < N)\n\t{\n\t\tmaxMatch++;\n\t\tfor (int cx = x, cy = y, ty; cx != -2; cx = prev[cx], cy = ty)\n\t\t{\n\t\t\tty = xy[cx];\n\t\t\tyx[cy] = cx;\n\t\t\txy[cx] = cy;\n\t\t}\n\t\taugment();\n\t}\n}\n\n\n/*\nvoid hungarian(Eigen::MatrixXd& C)\n{\n\tassert(C.rows() == C.cols());\n\tconst size_t N = C.cols();\n\n\t// Initialize\n\thungarianInit(C);\n\n}\n\nvoid hungarianInit(Eigen::MatrixXd& C)\n{\n\t// Subtract smallest element from each row\n\tfor (size_t i = 0; i < N; ++i)\n\t{\n\t\tdouble rowMin = C(i,0);\n\t\tfor (size_t j = 0; j < N; ++j)\n\t\t\tif (C(i,j) < rowMin) { rowMin = C(i,j); }\n\t\tfor (size_t j = 0; j < N; ++j)\n\t\t\tC(i,j) -= rowMin;\n\t}\n\t// Subtract smallest element from each column\n\tfor (size_t j = 0; j < N; ++j)\n\t{\n\t\tdouble colMin = C(0,j);\n\t\tfor (size_t i = 0; i < N; ++i)\n\t\t\tif (C(i,j) < colMin) { colMin = C(i,j); }\n\t\tfor (size_t i = 0; i < N; ++i)\n\t\t\tC(i,j) -= colMin;\n\t}\n}\n*/\n} // namespace gtri\n#endif // HUNGARIAN_HPP\n", "meta": {"hexsha": "4c67ff84a85e6f4759071c45554899f55faa8fcd", "size": 6984, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "mps_voxels/include/mps_voxels/util/hungarian.hpp", "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/include/mps_voxels/util/hungarian.hpp", "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/include/mps_voxels/util/hungarian.hpp", "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": 24.5915492958, "max_line_length": 172, "alphanum_fraction": 0.5932130584, "num_tokens": 2185, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390162, "lm_q2_score": 0.6224593171945417, "lm_q1q2_score": 0.46072842799971153}}
{"text": "#include \"CEGO/concurrentqueue.h\"\n#include \"CEGO/CEGO.hpp\"\n#include <Eigen/Dense>\n#if defined(PYBIND11)\n#include <pybind11/embed.h>\n#include <pybind11/pybind11.h>\n#include <pybind11/numpy.h>\n#include <pybind11/stl.h>\n#include <pybind11/eigen.h>\nnamespace py = pybind11;\n#include <atomic>\n#include <fstream>\n\nstd::atomic_size_t Ncalls(0);\n\ninline bool ValidNumber(double x)\n{\n    // Idea from http://www.johndcook.com/IEEE_exceptions_in_cpp.html\n    return (x <= DBL_MAX && x >= -DBL_MAX);\n};\n\nclass Antoine {\npublic:\n    double m_Tt, m_Tc, m_pc, m_Dc;\n    Eigen::ArrayXd m_LHS, m_T;\n    std::string m_name;\n    Antoine(const std::string &name) :  m_name(name)\n    {\n        py::module ct = py::module::import(\"ctREFPROP.ctREFPROP\"); // Import cytpes wrapper of REFPROP dll\n        std::string RPPREFIX(getenv(\"RPPREFIX\")); \n        auto R = ct.attr(\"REFPROPFunctionLibrary\")(RPPREFIX + \"/REFPRP64.DLL\");\n        auto version = R.attr(\"RPVersion\")().cast<std::string>();\n        auto setup_info = R.attr(\"SETUPdll\")(1, name+\".FLD\", \"HMX.BNC\",\"DEF\");\n        if (setup_info.attr(\"ierr\").cast<int>() != 0) {\n            throw std::invalid_argument( setup_info.attr(\"herr\").cast<std::string>() );\n        }\n        auto info = R.attr(\"INFOdll\")(1);\n        m_pc = info.attr(\"Pc\").cast<double>();\n        m_Tc = info.attr(\"Tc\").cast<double>();\n        m_Tt = info.attr(\"Ttrp\").cast<double>();\n        m_Dc = info.attr(\"Dc\").cast<double>();\n\n        std::size_t N = 300;\n        m_LHS.resize(N);\n        m_T.resize(N);\n        std::vector<double> z(1,1);\n        Eigen::ArrayXd Tvec = Eigen::ArrayXd::LinSpaced(N, m_Tc*0.999, 0.99*m_Tt);\n        Eigen::Index j = 0;\n\n        for (auto i = 0; i < Tvec.size(); ++i){\n            auto o = R.attr(\"TQFLSHdll\")(Tvec[i], 1, &z, 0);\n            int ierr = o.attr(\"ierr\").cast<int>();\n            \n            if (ierr <= 100){\n                double p = o.attr(\"P\").cast<double>();\n                if (!ValidNumber(p)){ continue; }\n                m_LHS(j) = p;\n            }\n            m_T(j) = Tvec(i);\n            j++;\n        }\n        m_LHS.conservativeResize(j);\n        m_T.conservativeResize(j);\n    }\n    void plot_curve(){\n        #if defined(PYBIND11)\n        py::module plt = py::module::import(\"matplotlib.pyplot\"); // Import matplotlib\n        plt.attr(\"plot\")(1/m_T, m_LHS);\n        plt.attr(\"show\")();\n        #else\n        std::cout << \"No pybind11 support, so no plots\\n\";\n        #endif\n    }\n    Eigen::ArrayXd eval_RHS(const Eigen::ArrayXd& T, const Eigen::ArrayXd &c) {\n        return c[3]*pow(10,c[0]-c[1]/(c[2]+T));\n    }\n    double objective(const CEGO::AbstractIndividual *pind) {\n        const std::vector<double> &c = static_cast<const CEGO::NumericalIndividual<double>*>(pind)->get_coefficients();\n        return objective(Eigen::Map<const Eigen::ArrayXd>(&(c[0]), c.size()) );\n    }\n    double objective(const Eigen::ArrayXd &c) {\n        Ncalls++;\n        double ssq = ((eval_RHS(m_T, c) - m_LHS)/m_LHS).square().sum();\n        return ssq;\n    }\n    void plot_trace(const std::vector<double> &best_costs) {\n        #if defined(PYBIND11)\n        py::module plt = py::module::import(\"matplotlib.pyplot\"); // Import matplotlib\n        plt.attr(\"plot\")(best_costs);\n        plt.attr(\"show\")();\n        #else\n        std::cout << \"No pybind11 support, so no plots\\n\";\n        #endif\n    }\n    const Eigen::ArrayXd &get_T(){ return m_T; }\n};\n\nint main()\n{\n    py::scoped_interpreter interp{};\n    std::srand((unsigned int)time(0));\n\n    // Construct the bounds\n    std::vector<CEGO::Bound> bounds;\n    for (auto i = 0; i < 3; ++i) { \n        bounds.push_back(CEGO::Bound(std::pair<double, double>(-10000, 10000)));\n    }\n    for (auto i = 0; i < 1; ++i) {\n        bounds.push_back(CEGO::Bound(std::pair<double, double>(0.1,100)));\n    }\n    Antoine rp(\"PROPANE\");\n    //rp.plot_curve();\n   \n    CEGO::CostFunction cost_wrapper = std::bind((double (Antoine::*)(const CEGO::AbstractIndividual *)) &Antoine::objective, &rp, std::placeholders::_1);\n    auto Nlayers = 5;\n    auto layers = CEGO::Layers<double>(cost_wrapper, bounds.size(), 2000, Nlayers, 3);\n    layers.parallel = false;\n    layers.set_bounds(bounds);\n\n    auto flags = layers.get_evolver_flags();\n    flags[\"Nelite\"] = 2;\n    flags[\"Fmin\"] = 0.5;\n    flags[\"Fmax\"] = 1.0;\n    flags[\"CR\"] = 0.7;\n    layers.set_evolver_flags(flags);\n\n    std::vector<double> best_costs; \n    std::vector<std::vector<double> > objs;\n    double VTR = 1e-6, best_cost = 999999.0;\n    auto startTime = std::chrono::system_clock::now();\n    for (auto counter = 0; counter < 3000; ++counter) {\n        layers.do_generation();\n\n        // Store the best objective function in each layer\n        std::vector<double> oo;\n        for (auto &&cost_coefficients : layers.get_best_per_layer()) {\n            oo.push_back(std::get<0>(cost_coefficients));\n        }\n        objs.push_back(oo);\n\n        // For the overall best result, print it, and write JSON to file\n        auto best_layer = layers.get_best();\n        best_cost = std::get<0>(best_layer); best_costs.push_back(best_cost);\n        if (counter % 50 == 0) {\n            std::cout << counter << \": best: \" << best_cost << \"\\n \";// << CEGO::vec2string(best_coeffs) << \"\\n\";\n        }\n        if (best_cost < VTR){ break; }\n    }\n    auto best_layer = layers.get_best();\n    auto c = std::get<1>(best_layer);\n    auto endTime = std::chrono::system_clock::now();\n    double elap = std::chrono::duration<double>(endTime - startTime).count();\n\n    // Get the results stored in the thread-safe queue\n    std::vector<CEGO::Result> results; Eigen::MatrixXd mat;\n    results = layers.get_results();\n\n    std::cout << \"cbest\" << Eigen::Map<Eigen::ArrayXd>(&(c[0]), c.size()) << std::endl;\n        \n    std::cout << \"run:\" << elap << \" s\\n\";\n    std::cout << \"NFE:\" << Ncalls << std::endl;\n}\n\n#else\n\nint main(){\n    std::cout << \"Due to lack of pybind11 support, this file cannot be run\\n\";\n}\n\n#endif", "meta": {"hexsha": "7bea64ba901ebba5e8c5e87b16b74917d062d688", "size": 5947, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/Antoine.cxx", "max_stars_repo_name": "jedbrown/CEGO", "max_stars_repo_head_hexsha": "60e39319e577cf63e844d0818387aa9e486878f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2018-12-27T23:16:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-01T02:23:40.000Z", "max_issues_repo_path": "src/Antoine.cxx", "max_issues_repo_name": "jedbrown/CEGO", "max_issues_repo_head_hexsha": "60e39319e577cf63e844d0818387aa9e486878f1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-03-17T19:27:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-17T15:27:44.000Z", "max_forks_repo_path": "src/Antoine.cxx", "max_forks_repo_name": "jedbrown/CEGO", "max_forks_repo_head_hexsha": "60e39319e577cf63e844d0818387aa9e486878f1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-02-27T18:01:58.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-29T19:44:15.000Z", "avg_line_length": 34.9823529412, "max_line_length": 153, "alphanum_fraction": 0.5811333445, "num_tokens": 1717, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925404, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4606796719822193}}
{"text": "\n\n#include <stdlib.h>\n#include <math.h>\n#include <stdio.h>\n\n#include <NTL/config.h>\n\n#ifdef NTL_GMP_HACK\n\n#include <gmp.h>\n#include <NTL/mach_desc.h>\n\n\nint gcd(int a, int b)\n{\n   int u, v, t, x;\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\nint pow2(int a)\n{\n   int m;\n   int k;\n\n   m = 1;\n   k = 0;\n\n   while (m < a) {\n      m = 2*m;\n      k++;\n   }\n\n   if (m == a) \n      return k;\n   else\n      return -1;\n}\n  \n   \n\nconst char *accum[2] = { \"\", \"yy | \" };\n\nvoid lip_to_gmp(int A, int B)\n{\n   int d, na, nb;\n   int i, j, r;\n   int xx, yy;\n   int shamt;\n\n   int iter, na2, nb2;\n\n   d = gcd(A, B);\n   na = B/d;\n   nb = A/d;\n\n   na2 = pow2(na);\n   nb2 = pow2(nb);\n\n   printf(\"static\\n\");\n   printf(\"void lip_to_gmp(const long *x, mp_limb_t *y, long n)\\n\");\n   printf(\"{\\n\");\n   printf(\"   long r, q, xx;\\n\");\n   printf(\"   mp_limb_t yy;\\n\\n\");\n\n   if (na2 != -1) {\n      printf(\"   r = n & %d;\\n\", na-1);\n      printf(\"   q = n >> %d;\\n\", na2);\n   }\n   else {\n      printf(\"   r = n % %d;\\n\", na);\n      printf(\"   q = n / %d;\\n\", na);\n   }\n\n   printf(\"\\n\");\n\n   printf(\"   if (q > 0) {\\n\");\n\n   if (na2 != -1) \n      printf(\"      x += (q << %d);\\n\", na2);\n   else \n      printf(\"      x += (q * %d);\\n\", na);\n\n   if (nb2 != -1) \n      printf(\"      y += (q << %d);\\n\", nb2);\n   else if (pow2(nb+1) != -1)\n      printf(\"      y += (q << %d) - q;\\n\", pow2(nb+1));\n   else\n      printf(\"      y += (q * %d);\\n\", nb);\n\n   printf(\"   }\\n\");\n\n   printf(\"\\n\");\n   printf(\"   if (r > 0) {\\n\");\n   printf(\"      yy = 0;\\n\");\n   printf(\"\\n\");\n\n   printf(\"      switch (r-1) {\\n\");\n      \n\n   xx = 0;\n   yy = 0;\n\n   for (i = 1; ; i++) {\n      j = (i*A)/B;\n      r = (i*A)%B;\n\n\n      if (xx) {\n         printf(\"         \");\n         printf(\"yy = %s (((mp_limb_t)(xx)) << %d);\\n\", accum[yy], B-r);\n         yy = 1;\n      }\n\n      printf(\"      \");\n      printf(\"case %d:\\n\", na-1-i);\n\n      shamt = A-B+r;\n\n      printf(\"         \");\n\n      if (shamt >= 0) {\n         printf(\"y[%d] = \", nb-1-j);\n      }\n      else {\n         printf(\"yy = \");\n      }\n\n      printf(\"%s\", accum[yy]);\n\n      if (shamt == 0) {\n         printf(\"x[0];\\n\");\n         break;\n      }\n      else if (shamt < 0) {\n         printf(\"(((mp_limb_t)(x[%d])) << %d);\\n\", na-1-i, -shamt);\n         xx = 0;\n         yy = 1;\n      }\n      else {\n         printf(\"((xx=x[%d]) >> %d);\\n\", na-1-i, shamt);\n         xx = 1;\n         yy = 0;\n      }\n   }\n\n   printf(\"      }\\n\\n\");\n   printf(\"      n -= r;\\n\");\n   printf(\"   }\\n\\n\");\n   printf(\"   while (n > 0) {\\n\");\n   printf(\"      x -= %d;\\n\", na);\n   printf(\"      n -= %d;\\n\", na);\n   printf(\"      y -= %d;\\n\", nb);\n   printf(\"\\n\");\n\n\n   xx = 0;\n   yy = 0;\n\n   for (i = 0; ; i++) {\n      j = (i*A)/B;\n      r = (i*A)%B;\n\n      \n      if (xx) {\n         printf(\"      \");\n         printf(\"yy = %s (((mp_limb_t)(xx)) << %d);\\n\", accum[yy], B-r);\n         yy = 1;\n      }\n\n      shamt = A-B+r;\n\n      printf(\"      \");\n\n      if (shamt >= 0) {\n         printf(\"y[%d] = \", nb-1-j);\n      }\n      else {\n         printf(\"yy = \");\n      }\n\n      printf(\"%s\", accum[yy]);\n\n      if (shamt == 0) {\n         printf(\"x[0];\\n\");\n         break;\n      }\n      else if (shamt < 0) {\n         printf(\"(((mp_limb_t)(x[%d])) << %d);\\n\", na-1-i, -shamt);\n         xx = 0;\n         yy = 1;\n      }\n      else {\n         printf(\"((xx=x[%d]) >> %d);\\n\", na-1-i, shamt);\n         xx = 1;\n         yy = 0;\n      }\n   }\n\n   printf(\"   }\\n\");\n   printf(\"}\\n\");\n}\n\n\nvoid gmp_to_lip(int A, int B, int alt)\n{\n   int d, na, nb;\n   int i, j, r;\n   int shamt;\n\n   int na2, nb2;\n\n   d = gcd(A, B);\n   na = B/d;\n   nb = A/d;\n\n   na2 = pow2(na);\n   nb2 = pow2(nb);\n\n   printf(\"static\\n\");\n   if (!alt)\n      printf(\"void gmp_to_lip(long *x, const mp_limb_t *y, long n)\\n\");\n   else\n      printf(\"void gmp_to_lip1(long *x, const mp_limb_t *y, long n)\\n\");\n   printf(\"{\\n\");\n   printf(\"   long r, q; unsigned long xx;\\n\");\n   printf(\"   mp_limb_t yy;\\n\\n\");\n\n   if (na2 != -1) {\n      printf(\"   r = n & %d;\\n\", na-1);\n      printf(\"   q = n >> %d;\\n\", na2);\n   }\n   else {\n      printf(\"   r = n % %d;\\n\", na);\n      printf(\"   q = n / %d;\\n\", na);\n   }\n\n   printf(\"\\n\");\n\n   printf(\"   if (q > 0) {\\n\");\n\n   if (na2 != -1)\n      printf(\"      x += (q << %d);\\n\", na2);\n   else\n      printf(\"      x += (q * %d);\\n\", na);\n\n   if (nb2 != -1)\n      printf(\"      y += (q << %d);\\n\", nb2);\n   else if (pow2(nb+1) != -1)\n      printf(\"      y += (q << %d) - q;\\n\", pow2(nb+1));\n   else\n      printf(\"      y += (q * %d);\\n\", nb);\n\n   printf(\"   }\\n\");\n\n   printf(\"\\n\");\n\n\n   printf(\"   if (r > 0) {\\n\");\n\n   if (!alt) {\n      if (na - nb == 1)\n         printf(\"      yy = y[r-1];\\n\");\n      else if (na2 != -1) \n         printf(\"      yy = y[((r*%d + %d) >> %d) - 1];\\n\", nb, na-1, na2);\n      else\n         printf(\"      yy = y[((r*%d + %d) / %d) - 1];\\n\", nb, na-1, na);\n   \n   }\n   else\n      printf(\"      yy = 0;\\n\");\n\n   printf(\"\\n\");\n\n   printf(\"      switch (r-1) {\\n\");\n      \n\n\n   for (i = 1; ; i++) {\n      j = (i*A)/B;\n      r = (i*A)%B;\n\n\n      printf(\"      \");\n      printf(\"case %d:\\n\", na-1-i);\n\n      shamt = A-B+r;\n\n\n      if (shamt > 0) {\n         printf(\"         \");\n         printf(\"xx = ((unsigned long)(yy)) << %d;\\n\", shamt);\n         printf(\"         \");\n         printf(\"x[%d] = (xx | ((unsigned long)((yy = y[%d]) >> %d))) & NTL_RADIXM;\\n\", \n                na-1-i, nb-2-j, 2*B-r-A);\n      }\n      else if (shamt == 0) {\n         printf(\"         \");\n         printf(\"x[0] = ((unsigned long)(yy)) & NTL_RADIXM;\\n\");\n         break;\n      }\n      else {\n         printf(\"         \");\n         printf(\"x[%d] = ((unsigned long)(yy >> %d)) & NTL_RADIXM;\\n\", na-1-i, -shamt);\n      }\n   }\n\n   printf(\"      }\\n\\n\");\n   printf(\"      n -= r;\\n\");\n   printf(\"   }\\n\\n\");\n   printf(\"   while (n > 0) {\\n\");\n   printf(\"      x -= %d;\\n\", na);\n   printf(\"      n -= %d;\\n\", na);\n   printf(\"      y -= %d;\\n\", nb);\n   printf(\"\\n\");\n\n   printf(\"      yy = y[%d];\\n\", nb-1);\n\n   for (i = 0; ; i++) {\n      j = (i*A)/B;\n      r = (i*A)%B;\n\n\n      shamt = A-B+r;\n\n      if (shamt > 0) {\n         printf(\"      \");\n         printf(\"xx = ((unsigned long)(yy)) << %d;\\n\", shamt);\n         printf(\"      \");\n         printf(\"x[%d] = (xx | ((unsigned long)((yy = y[%d]) >> %d))) & NTL_RADIXM;\\n\", \n                na-1-i, nb-2-j, 2*B-r-A);\n      }\n      else if (shamt == 0) {\n         printf(\"      \");\n         printf(\"x[0] = ((unsigned long)(yy)) & NTL_RADIXM;\\n\");\n         break;\n      }\n      else {\n         printf(\"      \");\n         printf(\"x[%d] = ((unsigned long)(yy >> %d)) & NTL_RADIXM;\\n\", na-1-i, -shamt);\n      }\n   }\n\n\n   printf(\"   }\\n\");\n   printf(\"}\\n\");\n\n}\n\nvoid rdup(int a, int b)\n{\n   printf(\"((\");\n   if (pow2(a) != -1) {\n      printf(\"(x << %d)\", pow2(a)); \n   }\n   else if (pow2(a+1) != -1) {\n      printf(\"((x << %d) - x)\", pow2(a+1));\n   }\n   else {\n      printf(\"(x*%d)\", a);\n   }\n   \n   printf(\" + %d)\", b-1);\n\n   if (pow2(b) != -1) {\n      printf(\" >> %d)\", pow2(b));\n   }\n   else {\n      printf(\" / %d)\", b);\n   }\n}\n\n\nvoid G_TO_L(int A, int B)\n{\n   int d, na, nb;\n\n   d = gcd(A, B);\n   na = B/d;\n   nb = A/d;\n\n   printf(\"#define G_TO_L(x) \");\n   \n   rdup(na, nb);\n\n   printf(\"\\n\");\n}\n\nvoid L_TO_G(int A, int B)\n{\n   int d, na, nb;\n\n   d = gcd(A, B);\n   na = B/d;\n   nb = A/d;\n\n   printf(\"#define L_TO_G(x) \");\n   \n   rdup(nb, na);\n\n   printf(\"\\n\");\n}\n\n\nvoid L_TO_G_CHECK(int BPL, int BPI)\n{\n   if (BPL != BPI) {\n      printf(\"#define L_TO_G_CHECK_LEN\\n\");\n   }\n      \n}\n\n\nvoid Error(const char *s)\n{\n   fprintf(stderr, \"%s\\n\", s);\n   abort();\n}\n\n\nint main()\n{\n   mpz_t tt;\n   int A, B, BPL, BPI;\n\n   A = NTL_NBITS_MAX;\n\n   /*\n    * We compute B as the number of bits of a gmp limb.\n    * We require that this quantity correspond to the number of bits\n    * of a long, or possibly a \"long long\" that is twice as\n    * wide as a long.  These restrictions may not be entirely \n    * necessary, but they are satisfied on all platforms that I know of.\n    */\n\n   if (sizeof(mp_limb_t)==sizeof(long) &&\n            mp_bits_per_limb == NTL_BITS_PER_LONG)\n\n      B = NTL_BITS_PER_LONG;\n\n   else if (sizeof(mp_limb_t) == 2*sizeof(long) &&\n            mp_bits_per_limb == 2*NTL_BITS_PER_LONG)\n\n      B = 2*NTL_BITS_PER_LONG;\n\n   else\n      Error(\"sorry...this is a funny gmp\");\n\n   /*\n    * The following test is a bit redundant, but it doesn't hurt.\n    */\n\n   if (A >= B) Error(\"sorry...this is a funny gmp\");\n\n\n\n   /*\n    * Next, we check if either the _mp_size field of an mpz struct\n    * or the type mp_size_t is narrower than type \"long\".\n    * This is done to enable some overflow checks.\n    * For simplicity, we require that the sizeof\n    * these types is that of an int or a long, and we also make\n    * the somewhat DIRTY assumption that this sizeof value implies\n    * a corresponding bit count.  Since this assumption is true\n    * on all platforms that I know of, and since this assumption\n    * only affects some overflow tests, it seems reasonable.\n    */\n\n   if (sizeof(tt->_mp_size) == sizeof(int))\n      BPI = NTL_BITS_PER_INT;\n   else if (sizeof(tt->_mp_size) == sizeof(long))\n      BPI = NTL_BITS_PER_LONG;\n   else\n      Error(\"sorry...this is a funny gmp\");\n\n   if (sizeof(mp_size_t) != sizeof(int) && sizeof(mp_size_t) != sizeof(long))\n      Error(\"sorry...this is a funny gmp\");\n\n   if (sizeof(mp_size_t) < sizeof(tt->_mp_size))\n      BPI = NTL_BITS_PER_INT;\n\n\n   BPL = NTL_BITS_PER_LONG;\n\n   fprintf(stderr, \"\\ngmp looks OK...%d, %d, %d, %d.\\n\", A, B, BPI, BPL);\n   fprintf(stderr, \"generating file lip_gmp_aux.c.\\n\");\n\n\n   lip_to_gmp(A, B);\n   printf(\"\\n\");\n\n   gmp_to_lip(A, B, 0);\n   printf(\"\\n\");\n   gmp_to_lip(A, B, 1);\n   printf(\"\\n\");\n\n   G_TO_L(A, B);\n   L_TO_G(A, B);\n   L_TO_G_CHECK(BPL, BPI);\n\n   printf(\"#define HAVE_LIP_GMP_AUX\\n\");\n\n   return 0;\n}\n\n#else\n\nint main()\n{\n   fprintf(stderr, \"NTL_GMP_HACK flag not set.\\n\");\n   return 0;\n}\n\n#endif\n", "meta": {"hexsha": "778c732c26cf3f9c569eafad200b4e9c59961b50", "size": 10026, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "RUNETag/WinNTL/misc/gen_lip_gmp_aux.cpp", "max_stars_repo_name": "vshesh/RUNEtag", "max_stars_repo_head_hexsha": "800e93fb7c0560ea5a6261ffc60c02638a8cc8c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2021-09-29T14:50:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:01:21.000Z", "max_issues_repo_path": "RUNETag/WinNTL/misc/gen_lip_gmp_aux.cpp", "max_issues_repo_name": "vshesh/RUNEtag", "max_issues_repo_head_hexsha": "800e93fb7c0560ea5a6261ffc60c02638a8cc8c9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 15.0, "max_issues_repo_issues_event_min_datetime": "2021-12-24T22:53:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-25T10:03:13.000Z", "max_forks_repo_path": "LibSource/ExtendedNTL/misc/gen_lip_gmp_aux.cpp", "max_forks_repo_name": "ekzyis/CrypTool-2", "max_forks_repo_head_hexsha": "1af234b4f74486fbfeb3b3c49228cc36533a8c89", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2021-10-17T19:46:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T02:57:57.000Z", "avg_line_length": 18.9169811321, "max_line_length": 88, "alphanum_fraction": 0.4233991622, "num_tokens": 3488, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.46067967198221926}}
{"text": "/*\n * MCSatSamplePerfectlyStrategy.cpp\n *\n *  Created on: Apr 23, 2012\n *      Author: selman.joe@gmail.com\n */\n\n#include <cstdlib>\n#include <boost/random/bernoulli_distribution.hpp>\n#include \"MCSatSamplePerfectlyStrategy.h\"\n#include \"../logic/Domain.h\"\n\nvoid MCSatSamplePerfectlyStrategy::sampleSentences(const Model& m, const Domain& d, boost::mt19937& rng, std::vector<ELSentence>& sampled) {\n    // sample on an interval basis for each formula\n    for (Domain::formula_const_iterator it = d.formulas_begin(); it != d.formulas_end(); it++) {\n        ELSentence curSentence = *it;\n\n        if (curSentence.hasInfWeight()) {\n            sampled.push_back(curSentence); // have to take it\n            continue;\n        }\n        SISet satisfied = curSentence.dSatisfied(m, d);\n\n        double prob = 1.0 - exp(-(double)(curSentence.weight()));   // probability to sample an interval\n        SISet where(false, d.maxInterval());\n        // iterate over each interval, sampling!\n        for (SISet::const_iterator sisetIt = satisfied.begin(); sisetIt != satisfied.end(); sisetIt++) {\n            SpanInterval si = *sisetIt;\n            for (SpanInterval::const_iterator siIt = si.begin(); siIt != si.end(); siIt++) {\n                Interval interval = *siIt;\n                // sample it with probability 1-exp(-w)\n                boost::bernoulli_distribution<double> flip(prob);\n                if (flip(rng)) {\n                    where.add(SpanInterval(interval.start(), interval.start(), interval.finish(), interval.finish()));\n                }\n            }\n        }\n        if (!where.empty()) {\n            curSentence.setQuantification(where);\n            sampled.push_back(curSentence);\n        }\n    }\n}\n", "meta": {"hexsha": "9fc338d66b56631998242a989927687cc0d237ea", "size": 1716, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/inference/MCSatSamplePerfectlyStrategy.cpp", "max_stars_repo_name": "JunLi-Galios/repel", "max_stars_repo_head_hexsha": "e4e7f4ffc95f8d65dd478861080c9c77bab9b797", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/inference/MCSatSamplePerfectlyStrategy.cpp", "max_issues_repo_name": "JunLi-Galios/repel", "max_issues_repo_head_hexsha": "e4e7f4ffc95f8d65dd478861080c9c77bab9b797", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/inference/MCSatSamplePerfectlyStrategy.cpp", "max_forks_repo_name": "JunLi-Galios/repel", "max_forks_repo_head_hexsha": "e4e7f4ffc95f8d65dd478861080c9c77bab9b797", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.0, "max_line_length": 140, "alphanum_fraction": 0.6066433566, "num_tokens": 394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4606796658671747}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2017 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_MAX_VAL_HPP_INCLUDED\n#define BOOST_SIMD_ALGORITHM_MAX_VAL_HPP_INCLUDED\n\n#include <boost/simd/range/segmented_aligned_range.hpp>\n#include <boost/simd/constant/minf.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/function/if_else.hpp>\n#include <boost/simd/function/max.hpp>\n#include <boost/simd/function/maximum.hpp>\n#include <boost/simd/pack.hpp>\n#include <boost/simd/detail/is_aligned.hpp>\n\nnamespace boost { namespace simd\n{\n  /*!\n    @ingroup group-algo\n\n    Returns the value of the element with the smallest value in the range [first,last),\n    The largest possible value for the order if the range is empty.\n\n    @param first  Beginning of the range of elements to max_val\n    @param last   End of the range of elements to max_val\n    @param comp   comparison function object that will be applied.\n\n    @par Requirement\n\n      - @c first and @c last must be pointer to Vectorizable type.\n\n      - @c comp must be a polymorphic unary function object, i.e callable on generic types.\n      - if @c comp is not present the function test is done with operator <\n\n    @par Example\n\n    The following code uses simd::max_val to find the greatest and smallest element\n    @c std::vector.\n    @snippet max_val.cpp max_val\n    @snippet max_val.txt max_val\n\n    @return the maximum value of the range elements.\n  **/\n  template<typename T, typename Comp>\n  T max_val(T const* first, T const* last, Comp comp)\n  {\n    if (first == last) return comp(T(0), T(1)) ? Inf<T>() : Minf<T>();\n    auto pr = segmented_aligned_range(first,last);\n\n    T m = *first;\n    for( T e : pr.head ) { if (comp(m, e))  m = e; }\n\n    // main SIMD part\n    pack<T> mm(m);\n    for(pack<T> e : pr.body ) mm =  if_else(comp(m, e), e, m);\n\n    m =  mm[0];\n    for(T v : mm) if(comp(m, v)) m = v;\n\n    for( T e : pr.tail ) { if(comp(m, e))  m = e; }\n\n    return m;\n  }\n\n  /*!\n    @ingroup group-algo\n\n    Returns the value of the element with the smallest value in the range [first,last),\n    The largest possible value for the order if the range is empty.\n\n    @param first  Beginning of the range of elements to max_val\n    @param last   End of the range of elements to max_val\n\n    @par Requirement\n\n      - @c first and @c last must be pointer to Vectorizable type.\n\n    @par Example\n\n    The following code uses simd::max_val to find the greatest and smallest element\n    @c std::vector.\n    @snippet max_val.cpp max_val\n    @snippet max_val.txt max_val\n\n    @return the maximum value of the range elements.\n  **/\n  template<typename T> T max_val(T const* first, T const* last)\n  {\n    if (first == last) return Minf<T>();\n    auto pr = segmented_aligned_range(first,last);\n\n    T m = *first;\n    for( T e : pr.head ) m = max(e, m);\n\n    pack<T> mm(m);\n    for(pack<T> e : pr.body ) mm = max(e, mm);\n\n    m =  maximum(mm);\n    for(T e : pr.tail ) m = max(e, m);\n\n    return m;\n  }\n} }\n\n#endif\n", "meta": {"hexsha": "d7a8e0e46685049e2e7700ce3ec7ac449187e79c", "size": 3303, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/algorithm/max_val.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/algorithm/max_val.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/algorithm/max_val.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": 29.2300884956, "max_line_length": 100, "alphanum_fraction": 0.625491977, "num_tokens": 832, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4606796658671747}}
{"text": "#ifndef MOCHIMOCHI_ADAM_HPP_\n#define MOCHIMOCHI_ADAM_HPP_\n\n#include <Eigen/Dense>\n#include <cassert>\n#include <boost/serialization/serialization.hpp>\n#include <boost/serialization/nvp.hpp>\n#include <boost/serialization/split_member.hpp>\n#include <boost/serialization/vector.hpp>\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/archive/text_iarchive.hpp>\n#include <fstream>\n#include \"../../functions/enumerate.hpp\"\n#include \"../factory/binary_oml.hpp\"\n\nclass ADAM : public BinaryOML {\nprivate :\n  const std::size_t kDim;\n\nprivate :\n  std::size_t _timestep;\n  Eigen::VectorXd _w;\n  Eigen::VectorXd _m;\n  Eigen::VectorXd _v;\n\npublic :\n  ADAM(const std::size_t dim)\n    : kDim(dim),\n      _timestep(0),\n      _w(Eigen::VectorXd::Zero(kDim)),\n      _m(Eigen::VectorXd::Zero(kDim)),\n      _v(Eigen::VectorXd::Zero(kDim)) {\n\n    assert(dim > 0);\n  }\n\n  virtual ~ADAM() { }\n\nprivate :\n\n  double suffer_loss(const Eigen::VectorXd& x, const int y) const {\n    return std::max(0.0, 1.0 - y * _w.dot(x));\n  }\n\n  double calculate_margin(const Eigen::VectorXd& x) const {\n    return _w.dot(x);\n  }\n\npublic :\n\n  std::string name() const override {\n    return std::string(\"ADAM\");\n  }\n\n  bool update(const Eigen::VectorXd& feature, const int label) override {\n    constexpr auto kAlpha = 0.001;\n    constexpr auto kBeta1 = 0.9;\n    constexpr auto kBeta2 = 0.999;\n    constexpr auto kEpsilon = 0.00000001;\n    constexpr auto kLambda = 0.99999999;\n\n    if (suffer_loss(feature, label) <= 0.0) { return false; }\n\n    const Eigen::VectorXd gradiant = -label * feature;\n    const auto beta1_t = std::pow(kLambda, _timestep) * kBeta1;\n\n    _timestep++;\n    functions::enumerate(gradiant.data(), gradiant.data() + gradiant.size(), 0,\n                       [&](const std::size_t index, const double value) {\n                         _m[index] = beta1_t * _m[index] + (1.0 - beta1_t) * value;\n                         _v[index] = kBeta2 * _v[index] + (1.0 - kBeta2) * value * value;\n                         const auto m_t = _m[index] / (1.0 - std::pow(kBeta1, _timestep));\n                         const auto v_t = _v[index] / (1.0 - std::pow(kBeta2, _timestep));\n                         _w[index] -= kAlpha * m_t / (std::sqrt(v_t) + kEpsilon);\n                       });\n\n    return true;\n  }\n\n  int predict(const Eigen::VectorXd& feature) const override {\n    return calculate_margin(feature) > 0.0 ? 1 : -1;\n  }\n\n  void save(const std::string& filename) override {\n    std::ofstream ofs(filename);\n    assert(ofs);\n    boost::archive::text_oarchive oa(ofs);\n    oa << *this;\n    ofs.close();\n  }\n\n  void load(const std::string& filename) override {\n    std::ifstream ifs(filename);\n    assert(ifs);\n    boost::archive::text_iarchive ia(ifs);\n    ia >> *this;\n    ifs.close();\n  }\n\nprivate :\n  friend class boost::serialization::access;\n  BOOST_SERIALIZATION_SPLIT_MEMBER();\n  template <class Archive>\n  void save(Archive& ar, const unsigned int version) const {\n    std::vector<double> w_vector(_w.data(), _w.data() + _w.size());\n    std::vector<double> m_vector(_m.data(), _m.data() + _m.size());\n    std::vector<double> v_vector(_v.data(), _v.data() + _v.size());\n\n    ar & boost::serialization::make_nvp(\"w\", w_vector);\n    ar & boost::serialization::make_nvp(\"m\", m_vector);\n    ar & boost::serialization::make_nvp(\"v\", v_vector);\n    ar & boost::serialization::make_nvp(\"dimension\", const_cast<std::size_t&>(kDim));\n  }\n\n  template <class Archive>\n  void load(Archive& ar, const unsigned int version) {\n    std::vector<double> w_vector;\n    std::vector<double> m_vector;\n    std::vector<double> v_vector;\n\n    ar & boost::serialization::make_nvp(\"w\", w_vector);\n    ar & boost::serialization::make_nvp(\"m\", m_vector);\n    ar & boost::serialization::make_nvp(\"v\", v_vector);\n    ar & boost::serialization::make_nvp(\"dimension\", const_cast<std::size_t&>(kDim));\n\n    _w = Eigen::Map<Eigen::VectorXd>(&w_vector[0], w_vector.size());\n    _m = Eigen::Map<Eigen::VectorXd>(&m_vector[0], m_vector.size());\n    _v = Eigen::Map<Eigen::VectorXd>(&v_vector[0], v_vector.size());\n  }\n\n};\n\n#endif //MOCHIMOCHI_ADAM_HPP_\n", "meta": {"hexsha": "711312c445e6c627c2c36e495ad963cd48994364", "size": 4104, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "mochimochi/classifier/binary/adam.hpp", "max_stars_repo_name": "georgeslabreche/MochiMochi", "max_stars_repo_head_hexsha": "6ed0e8e078504a068a812735567d196f5d88e69f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mochimochi/classifier/binary/adam.hpp", "max_issues_repo_name": "georgeslabreche/MochiMochi", "max_issues_repo_head_hexsha": "6ed0e8e078504a068a812735567d196f5d88e69f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mochimochi/classifier/binary/adam.hpp", "max_forks_repo_name": "georgeslabreche/MochiMochi", "max_forks_repo_head_hexsha": "6ed0e8e078504a068a812735567d196f5d88e69f", "max_forks_repo_licenses": ["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.6268656716, "max_line_length": 90, "alphanum_fraction": 0.6357212476, "num_tokens": 1145, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4606796658671747}}
{"text": "/**\n * @file   CamPose.hpp\n * @brief  Header of CamPose class for camera pose representation.\n * @author Charlie Li\n * @date   2019.08.23\n */\n\n#ifndef CAMPOSE_HPP\n#define CAMPOSE_HPP\n\n#include <iostream>\n\n#include <opencv2/core.hpp>\n#include <Eigen/Core>\n\nnamespace SLAM_demo {\n\n/**\n * @class CamPose\n * @brief Store camera pose of each frame.\n */\nclass CamPose {\npublic: // public members\n    /// Store default pose and its inverse \\f$[I|0]\\f$.\n    CamPose();\n    /** \n     * @brief Construct pose-related data using the camera pose itself.\n     * @param[in] Tcw \\f$3 \\times 4\\f$ camera pose \\f$[R_{cw}|t_{cw}]\\f$,\n     */\n    CamPose(const cv::Mat& Tcw);\n    /** \n     * @brief Construct pose-related data using camera rotation and \n     *        translation matrices.\n     * @param[in] Rcw \\f$3 \\times 3\\f$ camera rotation matrix.\n     * @param[in] tcw \\f$3 \\times 1\\f$ camera translation matrix.\n     */\n    CamPose(const cv::Mat& Rcw, const cv::Mat& tcw);\n    /// Copy constructor.\n    CamPose(const CamPose& pose);\n    /// Copy-assignment operator.\n    CamPose& operator=(const CamPose& pose);\n    /// Default destructor.\n    ~CamPose() = default;\n    /// Set camera pose \\f$[R|t]\\f$ of current frame using an input pose.\n    void setPose(const cv::Mat& Tcw);\n    /** \n     * @brief Set camera pose \\f$[R|t]\\f$ of current frame using input \n     *        rotation and translation matrices.\n     */\n    void setPose(const cv::Mat& Rcw, const cv::Mat& tcw);\n    /**\n     * @name Getters for Pose-related Data\n     * @brief A group of getters for retrieving pose-related data.\n     * @return Matrix representation of pose-related data of type cv::Mat.\n     */\n    ///@{\n    CamPose getCamPoseInv() const { return CamPose(getPoseInv()); }\n    cv::Mat getPose() const { return mTcw.clone(); }\n    cv::Mat getRotation() const { return mTcw.colRange(0, 3).clone(); }\n    cv::Mat getRotationAngleAxis() const;\n    cv::Mat getTranslation() const {\n        return mTcw.rowRange(0, 3).col(3).clone();\n    }\n    /** \n     * @brief Get \\f$3 \\times 3\\f$ skew-symmetric matrix \\f$[t]_x\\f$ based on \n     *        \\f$3 \\times 1\\f$ translation vector \\f$t = (t_1, t_2, t_3)^T\\f$.\n     * \n     * \\f[ [t]_x = \\begin{bmatrix} \n     *               0 & -t_3 & t_2 \\\\ t_3 & 0 & -t_1 \\\\ -t_2 & t_1 & 0\n     *             \\end{bmatrix}\n     * \\f]\n     */\n    cv::Mat getTranslationSS() const;\n    cv::Mat getPoseInv() const { return mTwc.clone(); }\n    cv::Mat getRotationInv() const {\n        return mTwc.rowRange(0, 3).colRange(0, 3).clone();\n    }\n    //cv::Mat getRotationInvAngleAxis() const;\n    /// Get \\f$t_{wc}\\f$, which is the camera origin in world coordinate system.\n    cv::Mat getCamOrigin() const { return mTwc.rowRange(0, 3).col(3).clone(); }\n    ///@}\n    /**\n     * @brief  Get Euler angle representation of rotation matrix \\f$R_{cw}\\f$\n     *         as \\f$3 \\times 1\\f$ vector \\f$(yaw, pitch, roll)^T\\f$. \n     *         Unit: degree.\n     */\n    Eigen::Matrix<float, 3, 1> getREulerAngleEigen() const;\n    /**\n     * @brief  Get quaternion representation of rotation matrix \\f$R_{cw}\\f$\n     *         as \\f$4 \\times 1\\f$ vector \\f$(qw, qx, qy, qz)^T\\f$. \n     */\n    Eigen::Quaternion<float> getRQuatEigen() const;\n    /// Get Quaternion representation of R^T.\n    Eigen::Quaternion<float> getRInvQuatEigen() const;\n    /// Pose multiplication & assignment.\n    CamPose& operator*=(const CamPose& rhs);\n    /// Pose multiplication.    \n    const CamPose operator*(const CamPose& rhs) const;\nprivate: // private data\n    /** \n     * @brief \\f$3 \\times 4\\f$ camera pose \\f$[R_{cw}|t_{cw}]\\f$, i.e., the\n     *        transformation from world to camera coordinate system.\n     */\n    cv::Mat mTcw;\n    /** \n     * @brief \\f$3 \\times 4\\f$ transformation matrix \\f$[R_{wc}|t_{wc}]\\f$\n     *        from camera to world coordinate system. \n     *        \\f$ T_{cw, 4 \\times 4} = T_{wc, 4 \\times 4}^{-1}\\f$.\n     */\n    cv::Mat mTwc;\nprivate: // private members\n    /** \n     * @brief Update rotation matrix within \\f$T_{cw}\\f$, and at the same \n     *        time update corresponding inverse transformation \\f$T_{wc}\\f$.\n     */\n    void setRotation(const cv::Mat& Rcw);\n    /** \n     * @brief Update translation matrix within \\f$T_{cw}\\f$, and at the same\n     *        time update corresponding inverse transformation \\f$T_{wc}\\f$.\n     */\n    void setTranslation(const cv::Mat& tcw);\n    /// Set inverse pose \\f$T_{wc} = [R_{cw}^T | -R_{cw}^T t_{cw}]\\f$.\n    void setPoseInv();\n};\n\n/// Display pose info.\nstd::ostream& operator<<(std::ostream& os, const CamPose& pose);\n\n} // namespace SLAM_demo\n\n#endif // CAMPOSE_HPP\n", "meta": {"hexsha": "879b8d221f6f227d6cb26f7e15380cf3ecdb5a9b", "size": 4622, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/CamPose.hpp", "max_stars_repo_name": "charlie-lee/slam_demo", "max_stars_repo_head_hexsha": "0bb6cc6d20c6a728eea502a61456f83881144e59", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/CamPose.hpp", "max_issues_repo_name": "charlie-lee/slam_demo", "max_issues_repo_head_hexsha": "0bb6cc6d20c6a728eea502a61456f83881144e59", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/CamPose.hpp", "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": 35.0151515152, "max_line_length": 80, "alphanum_fraction": 0.5928169624, "num_tokens": 1408, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4606796658671746}}
{"text": "#include \"Polyline.h\"\n#include \"Vertex.h\"\n#include <boost/math/constants/constants.hpp>\n#include <boost/optional.hpp>\n#include <fmt/format.h>\n#include <smartmet/macgyver/Exception.h>\n#include <algorithm>\n#include <stdexcept>\n\nusing boost::math::double_constants::radian;\n\nnamespace Trax\n{\n// Begin a new polyline\nPolyline::Polyline(std::initializer_list<double> init_list)\n{\n  if (init_list.size() == 0 || init_list.size() % 2 != 0)\n    throw Fmi::Exception(BCP, \"Invalid initialization of Polyline from elements\");\n  const auto* iter = init_list.begin();\n  while (iter != init_list.end())\n  {\n    double x = *iter++;\n    double y = *iter++;\n    m_points.emplace_back(x, y, false);\n  }\n  update_bbox();\n}\n\n// A polyline is closed if it contains at least 3 points and the end points are equal\nbool Polyline::closed() const\n{\n  if (size() < 3)\n    return false;\n  return (xbegin() == xend() && ybegin() == yend());\n}\n\n// A polyline is clockwise if it is closed and the signed area is positive.\nbool Polyline::clockwise() const\n{\n  if (!closed())\n    return false;\n\n  double area = 0;\n  auto n = size();\n  for (std::size_t i = 0; i < n - 1; i++)\n    area += (m_points[i + 1].x - m_points[i].x) * (m_points[i].y + m_points[i + 1].y);\n\n  // The true area is |area/2|, but we care only about the orientation\n\n  // Treating zero-size polygons as anti-clockwise lead to troubled code elsewhere,\n  // hence we use equality as well.\n  return area >= 0;\n}\n\nstd::vector<double> Polyline::xcoordinates() const\n{\n  std::vector<double> ret;\n  const auto n = m_points.size();\n  ret.reserve(n);\n  for (auto i = 0UL; i < n; i++)\n    ret.push_back(m_points[i].x);\n  return ret;\n}\n\nstd::vector<double> Polyline::ycoordinates() const\n{\n  std::vector<double> ret;\n  const auto n = m_points.size();\n  ret.reserve(n);\n  for (auto i = 0UL; i < n; i++)\n    ret.push_back(m_points[i].y);\n  return ret;\n}\n\n// Polygon exteriors and holes may share only singular vertices and not\n// whole edges. Hence any point along any edge should be inside an exterior\n// if the hole is inside it.\n\nstd::pair<double, double> Polyline::inside_point() const\n{\n  const auto x = 0.5 * (m_points[0].x + m_points[1].x);\n  const auto y = 0.5 * (m_points[0].y + m_points[1].y);\n  return std::make_pair(x, y);\n}\n\n// Polyline exit angle\ndouble Polyline::end_angle() const\n{\n  const auto n = m_points.size() - 2;\n  auto x1 = m_points[n].x;\n  auto y1 = m_points[n].y;\n  auto x2 = m_points[n + 1].x;\n  auto y2 = m_points[n + 1].y;\n  return atan2(y2 - y1, x2 - x1) * radian;\n}\n\n// Polyline start angle\ndouble Polyline::start_angle() const\n{\n  auto x1 = m_points[0].x;\n  auto y1 = m_points[0].y;\n  auto x2 = m_points[1].x;\n  auto y2 = m_points[1].y;\n  return atan2(y2 - y1, x2 - x1) * radian;\n}\n\nbool Polyline::bbox_contains(const Polyline& other) const\n{\n  return bbox().contains(other.bbox());\n}\n\n// Does the (closed) polyline contain the other (closed) polyline\nbool Polyline::contains(const Polyline& other) const\n{\n  // Quick exit based on bounding box containment\n  if (!bbox_contains(other))\n  {\n    return false;\n  }\n\n  // A hole may touch the exterior at a vertex, but may not share\n  // an edge with it. Hence choosing the middle of a vertex as a test\n  // point is safe provided there are no rounding errors, huge values\n  // causing problems, highly distorted grids or something similar\n  // making the calculations not robust.\n\n  const auto test_point = other.inside_point();\n  const auto x = test_point.first;\n  const auto y = test_point.second;\n\n  // Refs 1-2 are for clarity since ref 3 only provides an idea for optimization by Stuart MacMartin\n  //\n  // 1: http://www.faqs.org/faqs/graphics/algorithms-faq/ question 2.03\n  // 2: https://wrf.ecse.rpi.edu/Research/Short_Notes/pnpoly.html\n  // 3: http://www.realtimerendering.com/resources/RTNews/html//rtnv5n3.html#art3\n\n  const auto n = m_points.size();\n  bool inside = false;\n  for (std::size_t i = 1; i < n; i++)\n  {\n    // Skip continuously while below or above y\n    if (m_points[i - 1].y < y)\n    {\n      while (i < n && m_points[i].y < y)\n        i++;\n    }\n    else if (m_points[i - 1].y > y)\n    {\n      while (i < n && m_points[i].y > y)\n        i++;\n    }\n\n    if (i >= n)\n      break;  // reached end without crossing y\n\n    auto x1 = m_points[i - 1].x;\n    auto y1 = m_points[i - 1].y;\n    auto x2 = m_points[i].x;\n    auto y2 = m_points[i].y;\n    if ((y1 > y) != (y2 > y))\n      if (x < (x1 - x2) * (y - y2) / (y1 - y2) + x2)\n        inside = !inside;\n  }\n\n  return inside;\n}\n\n// Append a new coordinate. Discard duplicates which appear from apthological cases\n// such as an isoband range value appearing only in one corner of a grid cell.\nvoid Polyline::append(const Vertex& vertex)\n{\n  if (m_points.empty())\n  {\n    m_points.reserve(256);  // do not settle for a small initial allocation\n    m_points.emplace_back(vertex.x, vertex.y, vertex.ghost);\n  }\n  else if (m_points.back().x != vertex.x || m_points.back().y != vertex.y)  // ignore duplicates\n    m_points.emplace_back(vertex.x, vertex.y, vertex.ghost);\n}\n\n// Append another polyline directly\nvoid Polyline::append(const Polyline& other)\n{\n  m_points.insert(m_points.end(), ++other.m_points.begin(), other.m_points.end());\n}\n\n// Reverse the winding order\nvoid Polyline::reverse()\n{\n  const auto n = size();\n  for (auto i = 0UL, j = n - 1; i < j; i++, j--)\n    std::swap(m_points[i], m_points[j]);\n}\n\n// Export normal WKT\nstd::string Polyline::wkt() const\n{\n  std::string ret = \"LINESTRING \";\n  ret += wkt_body();\n  return ret;\n}\n\n// Export WKT body only for use in multilinestrings etc\nstd::string Polyline::wkt_body() const\n{\n  std::string ret = \"(\";\n\n  const auto n = size();\n  for (auto i = 0UL; i < n; i++)\n  {\n    if (i > 0)\n      ret += ',';\n    ret += fmt::format(\"{} {}\", m_points[i].x, m_points[i].y);\n  }\n  ret += ')';\n  return ret;\n}\n\n\n\nvoid Polyline::wkb(std::ostringstream& out) const\n{\n  unsigned char byteOrder = 1;\n  int n = 1;\n  if(*(char *)&n == 0)\n    byteOrder = 0;\n\n  out.write((const char*)&byteOrder,sizeof(byteOrder));\n  uint type = 2; // Line\n  out.write((const char*)&type,sizeof(type));\n  wkb_body(out);\n}\n\n\n\nvoid Polyline::wkb_body(std::ostringstream& out) const\n{\n  uint n = size();\n  out.write((const char*)&n,sizeof(n));\n\n  for (uint i = 0; i < n; i++)\n  {\n    double x = m_points[i].x;\n    double y = m_points[i].y;\n\n    //printf(\"Point %f,%f\\n\",x,y);\n    out.write((const char*)&x,8);\n    out.write((const char*)&y,8);\n  }\n}\n\n\n\n// Normalize coordinates to lexicographic order for testing purposes\nPolyline& Polyline::normalize()\n{\n  if (!closed())\n  {\n    const auto n = size() - 1;\n    // Lexicographically smallest end vertex first\n    if (m_points[0].x > m_points[n].x ||\n        (m_points[0].x == m_points[n].x && m_points[0].y > m_points[n].y))\n      reverse();\n    return *this;\n  }\n\n  // Find lexicographically smallest element\n\n  auto n = size() - 1;  // minus one since the last vertex is the same as the first one\n  auto best = 0UL;\n  for (auto i = 1UL; i < n; i++)\n  {\n    if ((m_points[i].x < m_points[best].x) ||\n        (m_points[i].x == m_points[best].x && m_points[i].y < m_points[best].y))\n      best = i;\n  }\n\n  // Rotate until it is the first element\n  if (best != 0)\n  {\n    auto pos = m_points.begin();\n    std::advance(pos, best);\n    std::rotate(m_points.begin(), pos, --m_points.end());\n\n    // Fix closing vertex\n    m_points[n] = m_points[0];\n  }\n  return *this;\n}\n\n// For normalizing collections of polylines\nbool Polyline::operator<(const Polyline& other) const\n{\n  if (this == &other)\n    return false;\n\n  const auto n = std::min(size(), other.size());\n  for (auto i = 0UL; i < n; i++)\n  {\n    if (m_points[i].x != other.m_points[i].x)\n      return m_points[i].x < other.m_points[i].x;\n    if (m_points[i].y != other.m_points[i].y)\n      return m_points[i].y < other.m_points[i].y;\n  }\n  return false;\n}\n\nvoid Polyline::update_bbox()\n{\n  m_bbox.init(m_points);\n}\n\nbool Polyline::has_ghosts() const\n{\n  return std::any_of(m_points.begin(), m_points.end(), [](const Point& p) { return p.ghost; });\n}\n\nstruct ValidRange\n{\n  std::size_t begin;\n  std::size_t end;\n};\n\nboost::optional<ValidRange> find_valid_range(const Points& points, std::size_t startpos)\n{\n  const auto n = points.size();\n  while (startpos < n && points[startpos].ghost)\n    ++startpos;\n  if (startpos >= n)\n    return {};\n\n  auto endpos = startpos;\n  while (endpos < n && !points[endpos].ghost)\n    ++endpos;\n\n  return ValidRange{startpos, endpos};\n}\n\n// precondition: has_ghosts is true, closed is true\nvoid Polyline::remove_ghosts(Polylines& new_polylines)\n{\n#if 0\n  std::cout << \"Removing ghosts from \" << wkt() << \"\\n\";\n  for (auto i = 0UL; i < m_points.size(); i++)\n    std::cout << fmt::format(\n        \"\\t{} : {},{} {}\\n\", i, m_points[i].x, m_points[i].y, m_points[i].ghost ? \"?\" : \"-\");\n#endif\n\n  // Extract valid ranges\n  std::vector<ValidRange> ranges;\n  const auto n = m_points.size();\n  auto startpos = 0UL;\n  while (startpos < n)\n  {\n    auto range = find_valid_range(m_points, startpos);\n    if (!range)\n      break;\n    if (range->end - range->begin > 1)\n      ranges.emplace_back(*range);\n    startpos = range->end;\n  }\n\n  // Detect whether there is a wraparound\n  const bool wraparound =\n      (ranges.size() > 1 && ranges.front().begin == 0 && ranges.back().end == n);\n\n  auto sz = ranges.size();\n  if (wraparound)  // if there is wraparound, the last range is handled along with the first one\n    --sz;\n\n  for (auto i = 0UL; i < sz; i++)\n  {\n    Polyline line;\n    const auto& range = ranges[i];\n    if (i == 0 && wraparound)\n    {\n      const auto& range2 = ranges.back();\n      // std::cout << \"Keeping wraparound range \" << range2.begin << \"...\" << range2.end << \"\\n\";\n      for (auto j = range2.begin; j < range2.end - 1; j++)\n        line.m_points.push_back(m_points[j]);\n    }\n    // std::cout << \"Keeping  range \" << range.begin << \"...\" << range.end << \"\\n\";\n    for (auto j = range.begin; j < range.end; j++)\n      line.m_points.push_back(m_points[j]);\n    new_polylines.emplace_back(std::move(line));\n  }\n}\n\n}  // namespace Trax\n", "meta": {"hexsha": "f51f083b6cf445efaa1d1338878e855b049250e3", "size": 10067, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "trax/Polyline.cpp", "max_stars_repo_name": "fmidev/smartmet-library-trax", "max_stars_repo_head_hexsha": "c817f87de83c5644ca3cec22d3d48441015ed5af", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "trax/Polyline.cpp", "max_issues_repo_name": "fmidev/smartmet-library-trax", "max_issues_repo_head_hexsha": "c817f87de83c5644ca3cec22d3d48441015ed5af", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "trax/Polyline.cpp", "max_forks_repo_name": "fmidev/smartmet-library-trax", "max_forks_repo_head_hexsha": "c817f87de83c5644ca3cec22d3d48441015ed5af", "max_forks_repo_licenses": ["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.8128205128, "max_line_length": 100, "alphanum_fraction": 0.6251117513, "num_tokens": 3023, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.5926665999540697, "lm_q1q2_score": 0.46067966586717457}}
{"text": "/* Name: Minimum Gradient Tests\n * Number: N0720144 (James Doyle)\n */\n\n// Includes:\n#include <boost/test/unit_test.hpp>\n\n#include \"logs.h\"\n#include \"route.h\"\n#include \"track.h\"\n\n// Using:\nusing namespace GPS;\n\nBOOST_AUTO_TEST_SUITE( Route_minGradient_N0720144 )\n\nconst bool isFileName = true;\n\n/* Test 1: Tests if function outputs the largest negative gradient in a set of points\n * that gives multiple negative gradient differences\n */\n\nBOOST_AUTO_TEST_CASE( LargestNegativeGradient )\n{\n    Route route = Route(LogFiles::GPXRoutesDir + \"LargestNegativeGradient.gpx\",isFileName);\n    BOOST_CHECK_CLOSE(route.minGradient(),-220513.18751,1);\n}\n\n/* Test 2: Tests if it throws the exception std::invalid_argument when there is a single point\n * in the track\n */\n\nBOOST_AUTO_TEST_CASE( Invalid_Amount_of_Points )\n{\n    BOOST_CHECK_THROW(Route route = Route(LogFiles::GPXRoutesDir + \"Invalid_Amount_of_Points.gpx\",isFileName),std::invalid_argument);\n}\n\n/* Test 3: Tests if the elevations are zero it outputs a minimum gradient of 0\n */\n\nBOOST_AUTO_TEST_CASE( Elevations_Eqaul_to_Zero )\n{\n    Route route = Route(LogFiles::GPXRoutesDir + \"Elevations_Equal_to_Zero.gpx\", isFileName);\n    BOOST_CHECK_EQUAL(route.minGradient(),0);\n}\n\n/* Test 4: Tests if the gradient is outputted if all the latitudes of the points within the track\n * the same\n */\n\nBOOST_AUTO_TEST_CASE( No_Change_Latitude )\n{\n    Route route = Route(LogFiles::GPXRoutesDir + \"No_Change_Latitude.gpx\",isFileName);\n    BOOST_CHECK_CLOSE(route.minGradient(),235274.33443,1);\n}\n\n/* Test 4: Tests if the gradient is outputted if all the longitudes of the points within the track\n * the same\n */\n\nBOOST_AUTO_TEST_CASE( No_Change_Longitude )\n{\n    Route route = Route(LogFiles::GPXRoutesDir + \"No_Change_Longitude.gpx\",isFileName);\n    BOOST_CHECK_CLOSE(route.minGradient(),235274.33443,1);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "6ec4c93ae26e66d30240fed5125b25c5f5e491a0", "size": 1874, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/gpx-tests/n0720144_mingradient_tests.cpp", "max_stars_repo_name": "EdwinLangley/GPX-Route-and-Track", "max_stars_repo_head_hexsha": "e4de303c62c7e9dc92724e8f257f7960ff77c992", "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/gpx-tests/n0720144_mingradient_tests.cpp", "max_issues_repo_name": "EdwinLangley/GPX-Route-and-Track", "max_issues_repo_head_hexsha": "e4de303c62c7e9dc92724e8f257f7960ff77c992", "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/gpx-tests/n0720144_mingradient_tests.cpp", "max_forks_repo_name": "EdwinLangley/GPX-Route-and-Track", "max_forks_repo_head_hexsha": "e4de303c62c7e9dc92724e8f257f7960ff77c992", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5588235294, "max_line_length": 133, "alphanum_fraction": 0.7588046958, "num_tokens": 474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.46067073597788794}}
{"text": "//==================================================================================================\n/*!\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#include <boost/simd/function/scalar/inrad.hpp>\n#include <scalar_test.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/minf.hpp>\n#include <boost/simd/constant/nan.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/mone.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/constant/mzero.hpp>\n#include <boost/simd/constant/pio_4.hpp>\n#include <boost/simd/constant/pio_2.hpp>\n#include <boost/simd/constant/pi.hpp>\n\nSTF_CASE_TPL (\" inrad\",  STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::inrad;\n\n  using r_t = decltype(inrad(T()));\n\n  // return type conformity test\n  STF_TYPE_IS(r_t, T);\n\n  // specific values tests\n#ifndef BOOST_SIMD_NO_INVALIDS\n  STF_ULP_EQUAL(inrad(bs::Inf<T>()), bs::Inf<r_t>(), 0.5);\n  STF_ULP_EQUAL(inrad(bs::Minf<T>()), bs::Minf<r_t>(), 0.5);\n  STF_ULP_EQUAL(inrad(bs::Nan<T>()), bs::Nan<r_t>(), 0.5);\n#endif\n  STF_ULP_EQUAL(inrad(T(-180)), -bs::Pi<r_t>(), 0.5);\n  STF_ULP_EQUAL(inrad(T(-45)), -bs::Pio_4<r_t>(), 0.5);\n  STF_ULP_EQUAL(inrad(T(-90)), -bs::Pio_2<r_t>(), 0.5);\n  STF_ULP_EQUAL(inrad(bs::Zero<T>()), bs::Zero<r_t>(), 0.5);\n  STF_ULP_EQUAL(inrad(T(180)), bs::Pi<r_t>(), 0.5);\n  STF_ULP_EQUAL(inrad(T(45)), bs::Pio_4<r_t>(), 0.5);\n  STF_ULP_EQUAL(inrad(T(90)), bs::Pio_2<r_t>(), 0.5);\n}\n", "meta": {"hexsha": "9d1bffad2190dc6acdb44404fc7c7c18b6d3ff48", "size": 1711, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/scalar/inrad.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": "test/function/scalar/inrad.cpp", "max_issues_repo_name": "remymuller/boost.simd", "max_issues_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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/function/scalar/inrad.cpp", "max_forks_repo_name": "remymuller/boost.simd", "max_forks_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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": 35.6458333333, "max_line_length": 100, "alphanum_fraction": 0.6049094097, "num_tokens": 525, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583376458152, "lm_q2_score": 0.6619228625116081, "lm_q1q2_score": 0.4606707350433383}}
{"text": "//\n// Copyright 2005-2007 Adobe Systems Incorporated\n// Copyright 2018 Mateusz Loskot <mateusz at loskot dot net>\n//\n// Distribtted 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 <boost/gil/channel.hpp>\n#include <boost/gil/channel_algorithm.hpp>\n#include <boost/gil/typedefs.hpp>\n#include <cstdint>\n#include <limits>\n\n#define BOOST_TEST_MODULE test_scoped_channel_value\n#include \"unit_test.hpp\"\n\nnamespace gil = boost::gil;\n\nstruct int_minus_value  { static std::int8_t apply() { return -64; } };\nstruct int_plus_value   { static std::int8_t apply() { return  64; } };\nusing fixture = gil::scoped_channel_value\n    <\n        std::uint8_t, int_minus_value, int_plus_value\n    >;\n\nBOOST_AUTO_TEST_CASE(scoped_channel_value_default_constructor)\n{\n    fixture f;\n    std::uint8_t v = f;\n    BOOST_TEST(v == std::uint8_t{0});\n}\n\nBOOST_AUTO_TEST_CASE(scoped_channel_value_user_defined_constructors)\n{\n    fixture f{1};\n    std::uint8_t v = f;\n    BOOST_TEST(v == std::uint8_t{1});\n}\n\nBOOST_AUTO_TEST_CASE(scoped_channel_value_copy_constructors)\n{\n    fixture f1{128};\n    fixture f2{f1};\n\n    BOOST_TEST(std::uint8_t{f1} == std::uint8_t{128});\n    BOOST_TEST(std::uint8_t{f1} == std::uint8_t{f2});\n}\n\nBOOST_AUTO_TEST_CASE(scoped_channel_value_assignment)\n{\n    fixture f;\n    f = 64;\n    std::uint8_t v = f;\n    BOOST_TEST(v == std::uint8_t{64});\n}\n\nBOOST_AUTO_TEST_CASE(scoped_channel_value_float32_t)\n{\n    auto const tolerance = btt::tolerance(std::numeric_limits<float>::epsilon());\n    // min\n    BOOST_TEST(gil::float_point_zero<float>::apply() == 0.0, tolerance);\n    BOOST_TEST(gil::channel_traits<gil::float32_t>::min_value() == 0.0);\n    // max\n    BOOST_TEST(gil::float_point_one<float>::apply() == 1.0, tolerance);\n    BOOST_TEST(gil::channel_traits<gil::float32_t>::max_value() == 1.0);\n}\n\nBOOST_AUTO_TEST_CASE(scoped_channel_value_float64_t)\n{\n    auto const tolerance = btt::tolerance(std::numeric_limits<double>::epsilon());\n    // min\n    BOOST_TEST(gil::float_point_zero<double>::apply() == 0.0, tolerance);\n    BOOST_TEST(gil::channel_traits<gil::float64_t>::min_value() == 0.0, tolerance);\n    // max\n    BOOST_TEST(gil::float_point_one<double>::apply() == 1.0, tolerance);\n    BOOST_TEST(gil::channel_traits<gil::float64_t>::max_value() == 1.0, tolerance);\n}\n\nBOOST_AUTO_TEST_CASE(scoped_channel_value_halfs)\n{\n    // Create a double channel with range [-0.5 .. 0.5]\n    struct minus_half { static double apply() { return -0.5; } };\n    struct plus_half { static double apply() { return 0.5; } };\n    using halfs = gil::scoped_channel_value<double, minus_half, plus_half>;\n\n    auto const tolerance = btt::tolerance(std::numeric_limits<double>::epsilon());\n    BOOST_TEST(gil::channel_traits<halfs>::min_value() == minus_half::apply(), tolerance);\n    BOOST_TEST(gil::channel_traits<halfs>::max_value() == plus_half::apply(), tolerance);\n    // scoped channel maximum should map to the maximum\n    BOOST_TEST(gil::channel_convert<std::uint16_t>(\n        gil::channel_traits<halfs>::max_value()) == 65535, tolerance);\n}\n", "meta": {"hexsha": "3cfd47d089925098da7610b112cbb8718c765ff7", "size": 3137, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/gil/test/core/channel/scoped_channel_value.cpp", "max_stars_repo_name": "btzy/boost-1.72.0-mirror", "max_stars_repo_head_hexsha": "defad0f34b0abc884032b57dd4eb93f18f679bf1", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-01T03:04:05.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-01T03:04:05.000Z", "max_issues_repo_path": "libs/gil/test/core/channel/scoped_channel_value.cpp", "max_issues_repo_name": "btzy/boost-1.72.0-mirror", "max_issues_repo_head_hexsha": "defad0f34b0abc884032b57dd4eb93f18f679bf1", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-06-05T12:48:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-05T14:41:14.000Z", "max_forks_repo_path": "test/core/channel/scoped_channel_value.cpp", "max_forks_repo_name": "BoostGSoC19/gil-olzhas", "max_forks_repo_head_hexsha": "0fe841f2bf3f8ba25891bc0b3d1fac25ac5cd050", "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.3723404255, "max_line_length": 90, "alphanum_fraction": 0.7064073956, "num_tokens": 873, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.661922862511608, "lm_q2_score": 0.6959583376458153, "lm_q1q2_score": 0.4606707350433383}}
{"text": "/*\n@copyright Louis Dionne 2015\nDistributed under the Boost Software License, Version 1.0.\n(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n */\n\n#include <boost/hana/assert.hpp>\n#include <boost/hana/orderable.hpp>\n#include <boost/hana/tuple.hpp>\n\n#include <test/auto/base.hpp>\n#include <test/auto/comparable.hpp>\n#include <test/auto/orderable.hpp>\n\n#include <string>\n#include <type_traits>\nusing namespace std::literals;\nusing namespace boost::hana;\n\n\n// Minimal LessThanComparable types\nstruct ord1 { int value; };\nstruct ord2 {\n    int value;\n    constexpr operator ord1() const { return {value}; }\n};\n\ntemplate <typename T, typename U, typename = std::enable_if_t<\n    (std::is_same<T, ord1>{} || std::is_same<T, ord2>{}) &&\n    (std::is_same<U, ord1>{} || std::is_same<U, ord2>{})\n>>\nconstexpr bool operator<(T a, U b)\n{ return a.value < b.value; }\n\nnamespace boost { namespace hana {\n    template <typename T, typename U>\n    struct equal_impl<T, U, when<\n        (std::is_same<T, ord1>{} || std::is_same<T, ord2>{}) &&\n        (std::is_same<U, ord1>{} || std::is_same<U, ord2>{})\n    >> {\n        static constexpr bool apply(T a, U b)\n        { return a.value == b.value; }\n    };\n}}\n\nnamespace boost { namespace hana { namespace test {\n    template <> auto objects<int> = make<Tuple>(0,1,2,3,4,5);\n    template <> auto objects<unsigned int> = make<Tuple>(0u,1u,2u,3u,4u,5u);\n    template <> auto objects<long> = make<Tuple>(0l,1l,2l,3l,4l,5l);\n    template <> auto objects<unsigned long> = make<Tuple>(0ul,1ul,2ul,3ul,4ul,5ul);\n    template <> auto objects<ord1> = make<Tuple>(ord1{0}, ord1{1}, ord1{2}, ord1{3}, ord1{4});\n}}}\n\n\nint main() {\n    // laws\n    test::laws<Orderable, int>();\n    test::laws<Orderable, unsigned int>();\n    test::laws<Orderable, long>();\n    test::laws<Orderable, unsigned long>();\n    test::laws<Orderable, ord1>();\n\n    // less\n    {\n        BOOST_HANA_CONSTEXPR_CHECK(less(5, 6));\n        BOOST_HANA_CONSTEXPR_CHECK(not_(less(6, 6)));\n        BOOST_HANA_CONSTEXPR_CHECK(not_(less(7, 6)));\n\n        // Provided model for LessThanComparable types\n        BOOST_HANA_CONSTEXPR_CHECK(less(ord1{0}, ord1{1}));\n        BOOST_HANA_CONSTEXPR_CHECK(not_(less(ord1{0}, ord1{0})));\n        BOOST_HANA_CONSTEXPR_CHECK(not_(less(ord1{1}, ord1{0})));\n\n        BOOST_HANA_CONSTEXPR_CHECK(less(ord1{0}, ord2{1}));\n        BOOST_HANA_CONSTEXPR_CHECK(not_(less(ord1{0}, ord2{0})));\n        BOOST_HANA_CONSTEXPR_CHECK(not_(less(ord1{1}, ord2{0})));\n\n        BOOST_HANA_CONSTEXPR_CHECK(less(ord2{0}, ord1{1}));\n        BOOST_HANA_CONSTEXPR_CHECK(not_(less(ord2{0}, ord1{0})));\n        BOOST_HANA_CONSTEXPR_CHECK(not_(less(ord2{1}, ord1{0})));\n\n        BOOST_HANA_RUNTIME_CHECK(less(\"ab\", \"abc\"s));\n        BOOST_HANA_RUNTIME_CHECK(less(\"abc\"s, \"abcde\"));\n    }\n\n    // greater\n    {\n        BOOST_HANA_CONSTEXPR_CHECK(not_(greater(5, 6)));\n        BOOST_HANA_CONSTEXPR_CHECK(not_(greater(6, 6)));\n        BOOST_HANA_CONSTEXPR_CHECK(greater(7, 6));\n\n        BOOST_HANA_RUNTIME_CHECK(greater(\"abcd\", \"ab\"s));\n        BOOST_HANA_RUNTIME_CHECK(greater(\"abc\"s, \"abb\"));\n    }\n\n    // less_equal\n    {\n        BOOST_HANA_CONSTEXPR_CHECK(less_equal(5, 6));\n        BOOST_HANA_CONSTEXPR_CHECK(less_equal(6, 6));\n        BOOST_HANA_CONSTEXPR_CHECK(not_(less_equal(7, 6)));\n\n        BOOST_HANA_RUNTIME_CHECK(less_equal(\"ab\", \"abcd\"s));\n        BOOST_HANA_RUNTIME_CHECK(less_equal(\"abc\"s, \"abc\"));\n    }\n\n    // greater_equal\n    {\n        BOOST_HANA_CONSTEXPR_CHECK(not_(greater_equal(5, 6)));\n        BOOST_HANA_CONSTEXPR_CHECK(greater_equal(6, 6));\n        BOOST_HANA_CONSTEXPR_CHECK(greater_equal(7, 6));\n\n        BOOST_HANA_RUNTIME_CHECK(greater_equal(\"abcd\", \"ab\"s));\n        BOOST_HANA_RUNTIME_CHECK(greater_equal(\"abc\"s, \"abc\"));\n    }\n\n    // min\n    {\n        BOOST_HANA_CONSTEXPR_CHECK(equal(min(5, 6), 5));\n        BOOST_HANA_CONSTEXPR_CHECK(equal(min(6, 5), 5));\n    }\n\n    // max\n    {\n        BOOST_HANA_CONSTEXPR_CHECK(equal(max(5, 6), 6));\n        BOOST_HANA_CONSTEXPR_CHECK(equal(max(6, 5), 6));\n    }\n}\n", "meta": {"hexsha": "90c3c89c146db66a0772afacbb62454e9cb77218", "size": 4059, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/orderable.cpp", "max_stars_repo_name": "josephwinston/hana", "max_stars_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/orderable.cpp", "max_issues_repo_name": "josephwinston/hana", "max_issues_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/orderable.cpp", "max_forks_repo_name": "josephwinston/hana", "max_forks_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.7109375, "max_line_length": 94, "alphanum_fraction": 0.642769155, "num_tokens": 1187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.4606707318036822}}
{"text": "// Copyright 2004 The Trustees of Indiana University.\n\n// Use, modification and distribution is subject to the Boost Software\n// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n//  Authors: Douglas Gregor\n//           Andrew Lumsdaine\n#include <boost/graph/betweenness_centrality.hpp>\n\n#include <boost/graph/adjacency_list.hpp>\n#include <vector>\n#include <stack>\n#include <queue>\n#include <boost/property_map/property_map.hpp>\n#include <boost/core/lightweight_test.hpp>\n#include <boost/random/uniform_01.hpp>\n#include <boost/random/linear_congruential.hpp>\n#include <boost/lexical_cast.hpp>\n\nusing namespace boost;\n\nconst double error_tolerance = 0.001;\n\ntypedef property< edge_weight_t, double, property< edge_index_t, std::size_t > >\n    EdgeProperties;\n\nstruct weighted_edge\n{\n    int source, target;\n    double weight;\n};\n\ntemplate < typename Graph >\nvoid run_weighted_test(Graph*, int V, weighted_edge edge_init[], int E,\n    double correct_centrality[])\n{\n    Graph g(V);\n    typedef typename graph_traits< Graph >::vertex_descriptor Vertex;\n    typedef typename graph_traits< Graph >::vertex_iterator vertex_iterator;\n    typedef typename graph_traits< Graph >::edge_descriptor Edge;\n\n    std::vector< Vertex > vertices(V);\n    {\n        vertex_iterator v, v_end;\n        int index = 0;\n        for (boost::tie(v, v_end) = boost::vertices(g); v != v_end;\n             ++v, ++index)\n        {\n            put(vertex_index, g, *v, index);\n            vertices[index] = *v;\n        }\n    }\n\n    std::vector< Edge > edges(E);\n    for (int e = 0; e < E; ++e)\n    {\n        edges[e] = add_edge(\n            vertices[edge_init[e].source], vertices[edge_init[e].target], g)\n                       .first;\n        put(edge_weight, g, edges[e], 1.0);\n    }\n\n    std::vector< double > centrality(V);\n    brandes_betweenness_centrality(g,\n        centrality_map(make_iterator_property_map(\n                           centrality.begin(), get(vertex_index, g), double()))\n            .vertex_index_map(get(vertex_index, g))\n            .weight_map(get(edge_weight, g)));\n\n    for (int v = 0; v < V; ++v)\n    {\n        BOOST_TEST(centrality[v] == correct_centrality[v]);\n    }\n}\n\nstruct unweighted_edge\n{\n    int source, target;\n};\n\ntemplate < typename Graph >\nvoid run_unweighted_test(Graph*, int V, unweighted_edge edge_init[], int E,\n    double correct_centrality[], double* correct_edge_centrality = 0)\n{\n    Graph g(V);\n    typedef typename graph_traits< Graph >::vertex_descriptor Vertex;\n    typedef typename graph_traits< Graph >::vertex_iterator vertex_iterator;\n    typedef typename graph_traits< Graph >::edge_descriptor Edge;\n\n    std::vector< Vertex > vertices(V);\n    {\n        vertex_iterator v, v_end;\n        int index = 0;\n        for (boost::tie(v, v_end) = boost::vertices(g); v != v_end;\n             ++v, ++index)\n        {\n            put(vertex_index, g, *v, index);\n            vertices[index] = *v;\n        }\n    }\n\n    std::vector< Edge > edges(E);\n    for (int e = 0; e < E; ++e)\n    {\n        edges[e] = add_edge(\n            vertices[edge_init[e].source], vertices[edge_init[e].target], g)\n                       .first;\n        put(edge_weight, g, edges[e], 1.0);\n        put(edge_index, g, edges[e], e);\n    }\n\n    std::vector< double > centrality(V);\n    std::vector< double > edge_centrality1(E);\n\n    brandes_betweenness_centrality(g,\n        centrality_map(make_iterator_property_map(\n                           centrality.begin(), get(vertex_index, g), double()))\n            .edge_centrality_map(make_iterator_property_map(\n                edge_centrality1.begin(), get(edge_index, g), double()))\n            .vertex_index_map(get(vertex_index, g)));\n\n    std::vector< double > centrality2(V);\n    std::vector< double > edge_centrality2(E);\n    brandes_betweenness_centrality(g,\n        vertex_index_map(get(vertex_index, g))\n            .weight_map(get(edge_weight, g))\n            .centrality_map(make_iterator_property_map(\n                centrality2.begin(), get(vertex_index, g), double()))\n            .edge_centrality_map(make_iterator_property_map(\n                edge_centrality2.begin(), get(edge_index, g), double())));\n\n    std::vector< double > edge_centrality3(E);\n    brandes_betweenness_centrality(g,\n        edge_centrality_map(make_iterator_property_map(\n            edge_centrality3.begin(), get(edge_index, g), double())));\n\n    for (int v = 0; v < V; ++v)\n    {\n        BOOST_TEST(centrality[v] == centrality2[v]);\n\n        double relative_error = correct_centrality[v] == 0.0\n            ? centrality[v]\n            : (centrality[v] - correct_centrality[v]) / correct_centrality[v];\n        if (relative_error < 0)\n            relative_error = -relative_error;\n        BOOST_TEST(relative_error < error_tolerance);\n    }\n\n    for (int e = 0; e < E; ++e)\n    {\n        BOOST_TEST(edge_centrality1[e] == edge_centrality2[e]);\n        BOOST_TEST(edge_centrality1[e] == edge_centrality3[e]);\n\n        if (correct_edge_centrality)\n        {\n            double relative_error = correct_edge_centrality[e] == 0.0\n                ? edge_centrality1[e]\n                : (edge_centrality1[e] - correct_edge_centrality[e])\n                    / correct_edge_centrality[e];\n            if (relative_error < 0)\n                relative_error = -relative_error;\n            BOOST_TEST(relative_error < error_tolerance);\n\n            if (relative_error >= error_tolerance)\n            {\n                std::cerr << \"Edge \" << e << \" has edge centrality \"\n                          << edge_centrality1[e] << \", should be \"\n                          << correct_edge_centrality[e] << std::endl;\n            }\n        }\n    }\n}\n\ntemplate < typename Graph > void run_wheel_test(Graph*, int V)\n{\n    typedef typename graph_traits< Graph >::vertex_descriptor Vertex;\n    typedef typename graph_traits< Graph >::vertex_iterator vertex_iterator;\n    typedef typename graph_traits< Graph >::edge_descriptor Edge;\n\n    Graph g(V);\n    Vertex center = *boost::vertices(g).first;\n\n    std::vector< Vertex > vertices(V);\n    {\n        vertex_iterator v, v_end;\n        int index = 0;\n        for (boost::tie(v, v_end) = boost::vertices(g); v != v_end;\n             ++v, ++index)\n        {\n            put(vertex_index, g, *v, index);\n            vertices[index] = *v;\n            if (*v != center)\n            {\n                Edge e = add_edge(*v, center, g).first;\n                put(edge_weight, g, e, 1.0);\n            }\n        }\n    }\n\n    std::vector< double > centrality(V);\n    brandes_betweenness_centrality(g,\n        make_iterator_property_map(\n            centrality.begin(), get(vertex_index, g), double()));\n\n    std::vector< double > centrality2(V);\n    brandes_betweenness_centrality(g,\n        centrality_map(make_iterator_property_map(\n                           centrality2.begin(), get(vertex_index, g), double()))\n            .vertex_index_map(get(vertex_index, g))\n            .weight_map(get(edge_weight, g)));\n\n    relative_betweenness_centrality(g,\n        make_iterator_property_map(\n            centrality.begin(), get(vertex_index, g), double()));\n\n    relative_betweenness_centrality(g,\n        make_iterator_property_map(\n            centrality2.begin(), get(vertex_index, g), double()));\n\n    for (int v = 0; v < V; ++v)\n    {\n        BOOST_TEST(centrality[v] == centrality2[v]);\n        BOOST_TEST(\n            (v == 0 && centrality[v] == 1) || (v != 0 && centrality[v] == 0));\n    }\n\n    double dominance = central_point_dominance(g,\n        make_iterator_property_map(\n            centrality2.begin(), get(vertex_index, g), double()));\n    BOOST_TEST(dominance == 1.0);\n}\n\ntemplate < typename MutableGraph >\nvoid randomly_add_edges(MutableGraph& g, double edge_probability)\n{\n    typedef typename graph_traits< MutableGraph >::directed_category\n        directed_category;\n\n    minstd_rand gen;\n    uniform_01< minstd_rand, double > rand_gen(gen);\n\n    typedef typename graph_traits< MutableGraph >::vertex_descriptor vertex;\n    typename graph_traits< MutableGraph >::vertex_iterator vi, vi_end;\n    for (boost::tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi)\n    {\n        vertex v = *vi;\n        typename graph_traits< MutableGraph >::vertex_iterator wi\n            = is_same< directed_category, undirected_tag >::value\n            ? vi\n            : vertices(g).first;\n        while (wi != vi_end)\n        {\n            vertex w = *wi++;\n            if (v != w)\n            {\n                if (rand_gen() < edge_probability)\n                    add_edge(v, w, g);\n            }\n        }\n    }\n}\n\ntemplate < typename Graph, typename VertexIndexMap, typename CentralityMap >\nvoid simple_unweighted_betweenness_centrality(\n    const Graph& g, VertexIndexMap index, CentralityMap centrality)\n{\n    typedef typename boost::graph_traits< Graph >::vertex_descriptor vertex;\n    typedef\n        typename boost::graph_traits< Graph >::vertex_iterator vertex_iterator;\n    typedef typename boost::graph_traits< Graph >::adjacency_iterator\n        adjacency_iterator;\n    typedef typename boost::graph_traits< Graph >::vertices_size_type\n        vertices_size_type;\n    typedef typename boost::property_traits< CentralityMap >::value_type\n        centrality_type;\n\n    vertex_iterator vi, vi_end;\n    for (boost::tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi)\n        put(centrality, *vi, 0);\n\n    vertex_iterator si, si_end;\n    for (boost::tie(si, si_end) = vertices(g); si != si_end; ++si)\n    {\n        vertex s = *si;\n\n        // S <-- empty stack\n        std::stack< vertex > S;\n\n        // P[w] <-- empty list, w \\in V\n        typedef std::vector< vertex > Predecessors;\n        std::vector< Predecessors > predecessors(num_vertices(g));\n\n        // sigma[t] <-- 0, t \\in V\n        std::vector< vertices_size_type > sigma(num_vertices(g), 0);\n\n        // sigma[s] <-- 1\n        sigma[get(index, s)] = 1;\n\n        // d[t] <-- -1, t \\in V\n        std::vector< int > d(num_vertices(g), -1);\n\n        // d[s] <-- 0\n        d[get(index, s)] = 0;\n\n        // Q <-- empty queue\n        std::queue< vertex > Q;\n\n        // enqueue s --> Q\n        Q.push(s);\n\n        while (!Q.empty())\n        {\n            // dequeue v <-- Q\n            vertex v = Q.front();\n            Q.pop();\n\n            // push v --> S\n            S.push(v);\n\n            adjacency_iterator wi, wi_end;\n            for (boost::tie(wi, wi_end) = adjacent_vertices(v, g); wi != wi_end;\n                 ++wi)\n            {\n                vertex w = *wi;\n\n                // w found for the first time?\n                if (d[get(index, w)] < 0)\n                {\n                    // enqueue w --> Q\n                    Q.push(w);\n\n                    // d[w] <-- d[v] + 1\n                    d[get(index, w)] = d[get(index, v)] + 1;\n                }\n\n                // shortest path to w via v?\n                if (d[get(index, w)] == d[get(index, v)] + 1)\n                {\n                    // sigma[w] = sigma[w] + sigma[v]\n                    sigma[get(index, w)] += sigma[get(index, v)];\n\n                    // append v --> P[w]\n                    predecessors[get(index, w)].push_back(v);\n                }\n            }\n        }\n\n        // delta[v] <-- 0, v \\in V\n        std::vector< centrality_type > delta(num_vertices(g), 0);\n\n        // S returns vertices in order of non-increasing distance from s\n        while (!S.empty())\n        {\n            // pop w <-- S\n            vertex w = S.top();\n            S.pop();\n\n            const Predecessors& w_preds = predecessors[get(index, w)];\n            for (typename Predecessors::const_iterator vi = w_preds.begin();\n                 vi != w_preds.end(); ++vi)\n            {\n                vertex v = *vi;\n                // delta[v] <-- delta[v] + (sigma[v]/sigma[w])*(1 + delta[w])\n                delta[get(index, v)] += ((centrality_type)sigma[get(index, v)]\n                                            / sigma[get(index, w)])\n                    * (1 + delta[get(index, w)]);\n            }\n\n            if (w != s)\n            {\n                // C_B[w] <-- C_B[w] + delta[w]\n                centrality[w] += delta[get(index, w)];\n            }\n        }\n    }\n\n    typedef typename graph_traits< Graph >::directed_category directed_category;\n    const bool is_undirected\n        = is_same< directed_category, undirected_tag >::value;\n    if (is_undirected)\n    {\n        vertex_iterator v, v_end;\n        for (boost::tie(v, v_end) = vertices(g); v != v_end; ++v)\n        {\n            put(centrality, *v, get(centrality, *v) / centrality_type(2));\n        }\n    }\n}\n\ntemplate < typename Graph > void random_unweighted_test(Graph*, int n)\n{\n    Graph g(n);\n\n    {\n        typename graph_traits< Graph >::vertex_iterator v, v_end;\n        int index = 0;\n        for (boost::tie(v, v_end) = boost::vertices(g); v != v_end;\n             ++v, ++index)\n        {\n            put(vertex_index, g, *v, index);\n        }\n    }\n\n    randomly_add_edges(g, 0.20);\n\n    std::cout << \"Random graph with \" << n << \" vertices and \" << num_edges(g)\n              << \" edges.\\n\";\n\n    std::cout << \"  Direct translation of Brandes' algorithm...\";\n    std::vector< double > centrality(n);\n    simple_unweighted_betweenness_centrality(g, get(vertex_index, g),\n        make_iterator_property_map(\n            centrality.begin(), get(vertex_index, g), double()));\n    std::cout << \"DONE.\\n\";\n\n    std::cout << \"  Real version, unweighted...\";\n    std::vector< double > centrality2(n);\n    brandes_betweenness_centrality(g,\n        make_iterator_property_map(\n            centrality2.begin(), get(vertex_index, g), double()));\n    std::cout << \"DONE.\\n\";\n\n    if (!std::equal(centrality.begin(), centrality.end(), centrality2.begin()))\n    {\n        for (std::size_t v = 0; v < centrality.size(); ++v)\n        {\n            double relative_error = centrality[v] == 0.0\n                ? centrality2[v]\n                : (centrality2[v] - centrality[v]) / centrality[v];\n            if (relative_error < 0)\n                relative_error = -relative_error;\n            BOOST_TEST(relative_error < error_tolerance);\n        }\n    }\n\n    std::cout << \"  Real version, weighted...\";\n    std::vector< double > centrality3(n);\n\n    for (typename graph_traits< Graph >::edge_iterator ei = edges(g).first;\n         ei != edges(g).second; ++ei)\n        put(edge_weight, g, *ei, 1);\n\n    brandes_betweenness_centrality(g,\n        weight_map(get(edge_weight, g))\n            .centrality_map(make_iterator_property_map(\n                centrality3.begin(), get(vertex_index, g), double())));\n    std::cout << \"DONE.\\n\";\n\n    if (!std::equal(centrality.begin(), centrality.end(), centrality3.begin()))\n    {\n        for (std::size_t v = 0; v < centrality.size(); ++v)\n        {\n            double relative_error = centrality[v] == 0.0\n                ? centrality3[v]\n                : (centrality3[v] - centrality[v]) / centrality[v];\n            if (relative_error < 0)\n                relative_error = -relative_error;\n            BOOST_TEST(relative_error < error_tolerance);\n        }\n    }\n}\n\nint main(int argc, char* argv[])\n{\n    int random_test_num_vertices = 300;\n    if (argc >= 2)\n        random_test_num_vertices = boost::lexical_cast< int >(argv[1]);\n    typedef adjacency_list< listS, listS, undirectedS,\n        property< vertex_index_t, int >, EdgeProperties >\n        Graph;\n    typedef adjacency_list< listS, listS, directedS,\n        property< vertex_index_t, int >, EdgeProperties >\n        Digraph;\n\n    struct unweighted_edge ud_edge_init1[5]\n        = { { 0, 1 }, { 0, 3 }, { 1, 2 }, { 3, 2 }, { 2, 4 } };\n    double ud_centrality1[5] = { 0.5, 1.0, 3.5, 1.0, 0.0 };\n    run_unweighted_test((Graph*)0, 5, ud_edge_init1, 5, ud_centrality1);\n\n    // Example borrowed from the JUNG test suite\n    struct unweighted_edge ud_edge_init2[10] = {\n        { 0, 1 },\n        { 0, 6 },\n        { 1, 2 },\n        { 1, 3 },\n        { 2, 4 },\n        { 3, 4 },\n        { 4, 5 },\n        { 5, 8 },\n        { 7, 8 },\n        { 6, 7 },\n    };\n    double ud_centrality2[9]\n        = { 0.2142 * 28, 0.2797 * 28, 0.0892 * 28, 0.0892 * 28, 0.2797 * 28,\n              0.2142 * 28, 0.1666 * 28, 0.1428 * 28, 0.1666 * 28 };\n    double ud_edge_centrality2[10] = { 10.66666, 9.33333, 6.5, 6.5, 6.5, 6.5,\n        10.66666, 9.33333, 8.0, 8.0 };\n\n    run_unweighted_test(\n        (Graph*)0, 9, ud_edge_init2, 10, ud_centrality2, ud_edge_centrality2);\n\n    weighted_edge dw_edge_init1[6] = { { 0, 1, 1.0 }, { 0, 3, 1.0 },\n        { 1, 2, 0.5 }, { 3, 1, 1.0 }, { 3, 4, 1.0 }, { 4, 2, 0.5 } };\n    double dw_centrality1[5] = { 0.0, 1.5, 0.0, 1.0, 0.5 };\n    run_weighted_test((Digraph*)0, 5, dw_edge_init1, 6, dw_centrality1);\n\n    run_wheel_test((Graph*)0, 15);\n\n    random_unweighted_test((Graph*)0, random_test_num_vertices);\n\n    return boost::report_errors();\n}\n", "meta": {"hexsha": "8a2a024530151a2a88de41faeb9a099a9e9a9103", "size": 16905, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/graph/test/betweenness_centrality_test.cpp", "max_stars_repo_name": "uosorio/heroku_face", "max_stars_repo_head_hexsha": "7d6465e71dba17a15d8edaef520adb2fcd09d91e", "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": "3rdparty/boost_1_73_0/libs/graph/test/betweenness_centrality_test.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 130.0, "max_issues_repo_issues_event_min_datetime": "2016-06-22T22:11:25.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-29T20:24:09.000Z", "max_forks_repo_path": "3rdparty/boost_1_73_0/libs/graph/test/betweenness_centrality_test.cpp", "max_forks_repo_name": "qingkouwei/mediaones", "max_forks_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2015-07-08T19:18:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-14T16:39:56.000Z", "avg_line_length": 32.8891050584, "max_line_length": 80, "alphanum_fraction": 0.5601892931, "num_tokens": 4388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583124210896, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.4606707276294764}}
{"text": "/**\n * @file sdms_vector.hpp\n * @author David Albert (david.albert@insa-lyon.fr)\n * @brief \n * @version 0.1\n * @date 07/01/2021\n * \n * @copyright Copyright (c) 2021\n * \n */\n#pragma once\n\n#include <vector>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/vector_sparse.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n#include <assert.h>\n\n#include <sdm/utils/linear_algebra/vector_interface.hpp>\n\nnamespace sdm\n{\n  /**\n   * @brief Create a SDMS Vector. A SMDS Vector is used to optimize the calculation, however, you have to be careful when using it because it's not possible to add element after the initialization\n   * \n   * @tparam I Type of index\n   * @tparam T Type of value\n   */\n  template <class I, class T, class TBaseVector>\n  class sdmsVector : public VectorInterface<I, T>\n  {\n  public:\n    // using array_type = typename TBaseVector::array_type;\n    // using value_type = typename array_type::value_type;\n\n    static double PRECISION;\n\n    sdmsVector();\n\n    /**\n     * @brief Create a SDMS Vector. In order to create a vector, it's necessary to provide a map that associated the I element with a specific index and a specific Value.\n     * \n     * @param std::shared_ptr<std::unordered_map<I, size_t>> : A map that associate the element I with a specific index\n     * @param std::shared_ptr<std::unordered_map<I, T>> : A map that associate the element I with a specific value\n     * @param double : the default value\n     * \n     */\n    sdmsVector(std::shared_ptr<std::unordered_map<I, size_t>>, std::shared_ptr<std::unordered_map<I, T>>, double = 0);\n\n    /**\n     * @brief Create a SDMS Vector. \n     * \n     * @param std::vector<I>> : A vector for each element I\n     * @param std::vector<T> : A vector for each value associate at the same position of the element I in vector\n     * @param double : the default value\n     * \n     */\n    sdmsVector(std::vector<I>, std::vector<T>, double = 0);\n\n    virtual ~sdmsVector() {}\n\n    T at(const I &) const;\n    T getValueAt(const I &) const;\n    void setValueAt(const I &, const T &value);\n    void addValueAt(const I &, const T &value); // ps: added by baris, not tested.\n\n    T sum() const;\n    T norm_1() const;\n    T norm_2() const;\n\n    T min();\n    I argmin();\n    T max();\n    I argmax();\n\n    // sdmsVector transpose() const;\n\n    const std::vector<I> &getIndexes() const;\n\n    /**\n     * @brief Compare two vectors. Return true if all values are lower or equal to the second vector.\n     * \n     * @return true \n     * @return false \n     */\n    bool operator<=(const sdmsVector &) const;\n    bool operator==(const sdmsVector &) const;\n    bool operator!=(const sdmsVector &) const;\n    bool isEqual(const sdmsVector &other, double precision) const;\n\n    // template <class AE>\n    T dot(const sdmsVector &v2) const;\n\n    // template <class AE>\n    T operator^(const sdmsVector &v2) const;\n\n    std::string str() const;\n\n    auto begin() const { return this->iterator_.begin(); }\n    auto end() const { return this->iterator_.end(); }\n\n    template <class Archive>\n    void serialize(Archive &archive, const unsigned int);\n\n    size_t size() const;\n    std::shared_ptr<std::unordered_map<I, size_t>> getMapElementToIndex() const;\n\n  protected:\n    std::vector<I> vector_element_;\n    // std::shared_ptr<std::unordered_map<I, size_t>> map_index_to_value_;\n    std::shared_ptr<std::unordered_map<I, size_t>> map_element_to_index_;\n\n    // std::map<I, T> iterator_;\n\n    TBaseVector tbasevector_;\n\n    std::pair<I, T> getMin() const;\n    std::pair<I, T> getMax() const;\n\n    // friend sdmsVector operator*(const T &arg1, const sdmsVector &arg2)\n    // {\n    //   sdmsVector vnew = arg1 * static_cast<TBaseVector>(arg2);\n    //   vnew.setIndexes(arg2.getIndexes());\n    //   return vnew;\n    // }\n  };\n\n  /**\n   * @brief Sparse vector are vectors that store only non-zero values.\n   * \n   * @tparam I Type of index\n   * @tparam T Type of value\n   */\n  template <typename I = size_t, typename T = double>\n  using SparseVector = sdmsVector<I, T, boost::numeric::ublas::mapped_vector<T>>;\n\n  /**\n   * @brief Dense vector are standard vector.\n   * \n   * @tparam I Type of index\n   * @tparam T Type of value\n   */\n  template <typename I = size_t, typename T = double>\n  using DenseVector = sdmsVector<I, T, boost::numeric::ublas::vector<T>>;\n\n} // namespace sdm\n\n#include <sdm/utils/linear_algebra/sdms_vector.tpp>\n", "meta": {"hexsha": "0f476e0582b262e8c45e26f1092172b0a8596fbd", "size": 4393, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/sdm/utils/linear_algebra/sdms_vector.hpp", "max_stars_repo_name": "SDMStudio/sdms", "max_stars_repo_head_hexsha": "43a86973081ffd86c091aed69b332f0087f59361", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/sdm/utils/linear_algebra/sdms_vector.hpp", "max_issues_repo_name": "SDMStudio/sdms", "max_issues_repo_head_hexsha": "43a86973081ffd86c091aed69b332f0087f59361", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sdm/utils/linear_algebra/sdms_vector.hpp", "max_forks_repo_name": "SDMStudio/sdms", "max_forks_repo_head_hexsha": "43a86973081ffd86c091aed69b332f0087f59361", "max_forks_repo_licenses": ["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.2866666667, "max_line_length": 196, "alphanum_fraction": 0.6533120874, "num_tokens": 1186, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.6619228625116081, "lm_q1q2_score": 0.4606707266949271}}
{"text": "/*\n * test_pose.cpp\n *\n *  Created on: Mar 15, 2012\n *      Author: Pablo I\u00f1igo Blasco\n */\n\n#include <mrpt/poses/CPosePDFGaussian.h>\n#include <mrpt/poses/CPose3DPDFGaussian.h>\n#include <mrpt/math/CQuaternion.h>\n#include <geometry_msgs/PoseWithCovariance.h>\n#include <geometry_msgs/Pose.h>\n#include <geometry_msgs/Quaternion.h>\n#include <tf/tf.h>\n#include <mrpt_bridge/pose.h>\n#include <gtest/gtest.h>\n#include <Eigen/Dense>\n\nusing namespace std;\n\n#if MRPT_VERSION >= 0x199\n#define getAsVectorVal asVectorVal\nusing mrpt::DEG2RAD;\n#else\nusing mrpt::utils::DEG2RAD;\n#endif\n\nvoid checkPoseMatrixFromRotationParameters(\n\tconst double roll, const double pitch, const double yaw)\n{\n\t// TF-BULLET ROTATION\n\ttf::Pose original_pose;\n\ttf::Quaternion rotation;\n\trotation.setRPY(roll, pitch, yaw);\n\toriginal_pose.setRotation(rotation);\n\ttf::Matrix3x3 basis = original_pose.getBasis();\n\n\t// MRPT-ROTATION\n\tmrpt::poses::CPose3D mrpt_original_pose;\n\tmrpt_original_pose.setYawPitchRoll(yaw, pitch, roll);\n\tmrpt::math::CMatrixDouble33 mrpt_basis =\n\t\tmrpt_original_pose.getRotationMatrix();\n\n\tfor (int i = 0; i < 3; i++)\n\t\tfor (int j = 0; j < 3; j++)\n\t\t\tEXPECT_NEAR(basis[i][j], mrpt_basis(i, j), 0.01);\n}\n\nTEST(PoseConversions, copyMatrix3x3ToCMatrixDouble33)\n{\n\ttf::Matrix3x3 src(0, 1, 2, 3, 4, 5, 6, 7, 8);\n\tmrpt::math::CMatrixDouble33 des;\n\tmrpt_bridge::convert(src, des);\n\tfor (int r = 0; r < 3; r++)\n\t\tfor (int c = 0; c < 3; c++) EXPECT_FLOAT_EQ(des(r, c), src[r][c]);\n}\nTEST(PoseConversions, copyCMatrixDouble33ToMatrix3x3)\n{\n\tmrpt::math::CMatrixDouble33 src;\n\tfor (int r = 0; r < 3; r++)\n\t\tfor (int c = 0; c < 3; c++) src(r, c) = 12.0 + r * 4 - c * 2 + r * c;\n\n\ttf::Matrix3x3 des;\n\tmrpt_bridge::convert(src, des);\n\tfor (int r = 0; r < 3; r++)\n\t\tfor (int c = 0; c < 3; c++) EXPECT_FLOAT_EQ(des[r][c], src(r, c));\n}\n\nTEST(PoseConversions, checkPoseMatrixFromRotationParameters)\n{\n\tcheckPoseMatrixFromRotationParameters(0, 0, 0);\n\tcheckPoseMatrixFromRotationParameters(0.2, 0, 0);\n\tcheckPoseMatrixFromRotationParameters(0, 0.2, 0);\n\tcheckPoseMatrixFromRotationParameters(0, 0, 0.2);\n\tcheckPoseMatrixFromRotationParameters(0.4, 0.3, 0.2);\n\tcheckPoseMatrixFromRotationParameters(M_PI, -M_PI / 2.0, 0);\n}\n\n// Declare a test\nTEST(PoseConversions, reference_frame_change_with_rotations)\n{\n\tgeometry_msgs::PoseWithCovariance ros_msg_original_pose;\n\n\tros_msg_original_pose.pose.position.x = 1;\n\tros_msg_original_pose.pose.position.y = 0;\n\tros_msg_original_pose.pose.position.z = 0;\n\tros_msg_original_pose.pose.orientation.x = 0;\n\tros_msg_original_pose.pose.orientation.y = 0;\n\tros_msg_original_pose.pose.orientation.z = 0;\n\tros_msg_original_pose.pose.orientation.w = 1;\n\n\t// to mrpt\n\tmrpt::poses::CPose3DPDFGaussian mrpt_original_pose;\n\tmrpt_bridge::convert(ros_msg_original_pose, mrpt_original_pose);\n\tEXPECT_EQ(\n\t\tros_msg_original_pose.pose.position.x, mrpt_original_pose.mean[0]);\n\n\t// to tf\n\ttf::Pose tf_original_pose;\n\ttf::poseMsgToTF(ros_msg_original_pose.pose, tf_original_pose);\n\n\t// rotate yaw pi in MRPT\n\tmrpt::poses::CPose3D rotation_mrpt;\n\tdouble yaw = M_PI / 2.0;\n\trotation_mrpt.setFromValues(0, 0, 0, yaw, 0, 0);\n\tmrpt::poses::CPose3D mrpt_result = rotation_mrpt + mrpt_original_pose.mean;\n\tEXPECT_NEAR(mrpt_result[1], 1.0, 0.01);\n\n\t// rotate yaw pi in TF\n\ttf::Quaternion rotation_tf;\n\trotation_tf.setRPY(0, 0, yaw);\n\ttf::Pose rotation_pose_tf;\n\trotation_pose_tf.setIdentity();\n\trotation_pose_tf.setRotation(rotation_tf);\n\ttf::Pose tf_result = rotation_pose_tf * tf_original_pose;\n\tEXPECT_NEAR(tf_result.getOrigin()[1], 1.0, 0.01);\n\n\tgeometry_msgs::Pose mrpt_ros_result;\n\tmrpt_bridge::convert(mrpt_result, mrpt_ros_result);\n\n\tEXPECT_NEAR(mrpt_ros_result.position.x, tf_result.getOrigin()[0], 0.01);\n\tEXPECT_NEAR(mrpt_ros_result.position.y, tf_result.getOrigin()[1], 0.01);\n\tEXPECT_NEAR(mrpt_ros_result.position.z, tf_result.getOrigin()[2], 0.01);\n}\n\nvoid check_CPose3D_tofrom_ROS(\n\tdouble x, double y, double z, double yaw, double pitch, double roll)\n{\n\tconst mrpt::poses::CPose3D p3D(x, y, z, yaw, pitch, roll);\n\n\t// Convert MRPT->ROS\n\tgeometry_msgs::Pose ros_p3D;\n\tmrpt_bridge::convert(p3D, ros_p3D);\n\n\t// Compare ROS quat vs. MRPT quat:\n\tmrpt::math::CQuaternionDouble q;\n\tp3D.getAsQuaternion(q);\n\n\tEXPECT_NEAR(ros_p3D.position.x, p3D.x(), 1e-4) << \"p: \" << p3D << endl;\n\tEXPECT_NEAR(ros_p3D.position.y, p3D.y(), 1e-4) << \"p: \" << p3D << endl;\n\tEXPECT_NEAR(ros_p3D.position.z, p3D.z(), 1e-4) << \"p: \" << p3D << endl;\n\n\tEXPECT_NEAR(ros_p3D.orientation.x, q.x(), 1e-4) << \"p: \" << p3D << endl;\n\tEXPECT_NEAR(ros_p3D.orientation.y, q.y(), 1e-4) << \"p: \" << p3D << endl;\n\tEXPECT_NEAR(ros_p3D.orientation.z, q.z(), 1e-4) << \"p: \" << p3D << endl;\n\tEXPECT_NEAR(ros_p3D.orientation.w, q.r(), 1e-4) << \"p: \" << p3D << endl;\n\n\t// Test the other path: ROS->MRPT\n\tmrpt::poses::CPose3D p_bis;\n\tmrpt_bridge::convert(ros_p3D, p_bis);\n\n\t// p_bis==p3D?\n\tEXPECT_NEAR(\n\t\t(p_bis.getAsVectorVal() - p3D.getAsVectorVal())\n\t\t\t.array()\n\t\t\t.abs()\n\t\t\t.maxCoeff(),\n\t\t0, 1e-4)\n\t\t<< \"p_bis: \" << p_bis << endl\n\t\t<< \"p3D: \" << p3D << endl;\n}\n\n// Declare a test\nTEST(PoseConversions, check_CPose3D_tofrom_ROS)\n{\n\tcheck_CPose3D_tofrom_ROS(0, 0, 0, DEG2RAD(0), DEG2RAD(0), DEG2RAD(0));\n\tcheck_CPose3D_tofrom_ROS(1, 2, 3, DEG2RAD(0), DEG2RAD(0), DEG2RAD(0));\n\n\tcheck_CPose3D_tofrom_ROS(1, 2, 3, DEG2RAD(30), DEG2RAD(0), DEG2RAD(0));\n\tcheck_CPose3D_tofrom_ROS(1, 2, 3, DEG2RAD(0), DEG2RAD(30), DEG2RAD(0));\n\tcheck_CPose3D_tofrom_ROS(1, 2, 3, DEG2RAD(0), DEG2RAD(0), DEG2RAD(30));\n\n\tcheck_CPose3D_tofrom_ROS(1, 2, 3, DEG2RAD(-5), DEG2RAD(15), DEG2RAD(-30));\n\n\tcheck_CPose3D_tofrom_ROS(0, 0, 0, DEG2RAD(0), DEG2RAD(90), DEG2RAD(0));\n\tcheck_CPose3D_tofrom_ROS(0, 0, 0, DEG2RAD(0), DEG2RAD(-90), DEG2RAD(0));\n}\n\n// Declare a test\nTEST(PoseConversions, check_CPose2D_to_ROS)\n{\n\tconst mrpt::poses::CPose2D p2D(1, 2, 0.56);\n\n\t// Convert MRPT->ROS\n\tgeometry_msgs::Pose ros_p2D;\n\tmrpt_bridge::convert(p2D, ros_p2D);\n\n\t// Compare vs. 3D pose:\n\tconst mrpt::poses::CPose3D p3D = mrpt::poses::CPose3D(p2D);\n\tmrpt::poses::CPose3D p3D_ros;\n\tmrpt_bridge::convert(ros_p2D, p3D_ros);\n\n\t// p3D_ros should equal p3D\n\tEXPECT_NEAR(\n\t\t(p3D_ros.getAsVectorVal() - p3D.getAsVectorVal())\n\t\t\t.array()\n\t\t\t.abs()\n\t\t\t.maxCoeff(),\n\t\t0, 1e-4)\n\t\t<< \"p3D_ros: \" << p3D_ros << endl\n\t\t<< \"p3D: \" << p3D << endl;\n}\n", "meta": {"hexsha": "ae615ed66047e89a42bd3bc3608ce591af488a39", "size": 6237, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "catkin_ws/src/mrpt_bridge/src/test/test_pose.cpp", "max_stars_repo_name": "attaoveisi/AttBot_Rasberry", "max_stars_repo_head_hexsha": "dadcd6e80e2f3c7bd78c7a48ef64799de7bfa17f", "max_stars_repo_licenses": ["BSD-2-Clause"], "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": "workspace/catkin_ws/src/mrpt_bridge/src/test/test_pose.cpp", "max_issues_repo_name": "attaoveisi/AttBot2_Localization", "max_issues_repo_head_hexsha": "6ce84e26cc55fc391fdbcee168aa04102d59d375", "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": "workspace/catkin_ws/src/mrpt_bridge/src/test/test_pose.cpp", "max_forks_repo_name": "attaoveisi/AttBot2_Localization", "max_forks_repo_head_hexsha": "6ce84e26cc55fc391fdbcee168aa04102d59d375", "max_forks_repo_licenses": ["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.724137931, "max_line_length": 76, "alphanum_fraction": 0.7075517076, "num_tokens": 2298, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228625116081, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.46067072252072144}}
{"text": "#ifndef CPPMATH_GEOMETROY_GEOMETRY_HPP_\n#define CPPMATH_GEOMETROY_GEOMETRY_HPP_\n\n#include <cmath>  // fabs()\n#include <limits>  // limits<double>\n\n#include <Eigen/Core>\n\nnamespace cppmath\n{\n    /**\n     * Helper functions for geometric computations.\n     *\n     * \\author cpieloth\n     * \\copyright Copyright 2014 Christof Pieloth, Licensed under the Apache License, Version 2.0\n     */\n    namespace geometry\n    {\n        typedef Eigen::Vector3d Vector3T;\n        typedef Eigen::Matrix3Xd PointsT;\n        typedef Eigen::Matrix3d Matrix3T;\n\n        Matrix3T getRotationXYZMatrix( double x, double y, double z );\n\n        /**\n         * Calculates an orthogonal vector to v.\n         *\n         * \\param o An orthogonal vector of v.\n         * \\param v Input vector.\n         * \\return True if o contains an orthogonal vector of v.\n         */\n        bool findOrthogonalVector( Vector3T* const o, const Vector3T& v );\n\n        /**\n         * Calculates an tangent plane for the normal vector n. u, v and n are orthogonal to each other.\n         *\n         * \\param u Plane vector 1 for parametrically description.\n         * \\param v Plane vector 2 for parametrically description.\n         * \\param n Normal vector.\n         * \\return True if u and v contain a plane vector.\n         */\n        bool findTangentPlane( Vector3T* const u, Vector3T* const v, const Vector3T& n );\n    }\n}\n\n#endif  // CPPMATH_GEOMETROY_GEOMETRY_HPP_\n", "meta": {"hexsha": "d3b69704de3aad1d5350624e59789f33140c6186", "size": 1431, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/cppmath/geometry/Geometry.hpp", "max_stars_repo_name": "cpieloth/CppMath", "max_stars_repo_head_hexsha": "58d1c7f0ea07dab9f913b946a251a01b0827bb39", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cppmath/geometry/Geometry.hpp", "max_issues_repo_name": "cpieloth/CppMath", "max_issues_repo_head_hexsha": "58d1c7f0ea07dab9f913b946a251a01b0827bb39", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cppmath/geometry/Geometry.hpp", "max_forks_repo_name": "cpieloth/CppMath", "max_forks_repo_head_hexsha": "58d1c7f0ea07dab9f913b946a251a01b0827bb39", "max_forks_repo_licenses": ["Apache-2.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.4468085106, "max_line_length": 104, "alphanum_fraction": 0.6366177498, "num_tokens": 347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583124210896, "lm_q2_score": 0.6619228625116081, "lm_q1q2_score": 0.46067071834651574}}
{"text": "/*    Copyright (c) 2010-2019, Delft University of Technology\n *    All rigths reserved\n *\n *    This file is part of the Tudat. Redistribution and use in source and\n *    binary forms, with or without modification, are permitted exclusively\n *    under the terms of the Modified BSD license. You should have received\n *    a copy of the license with this file. If not, please or visit:\n *    http://tudat.tudelft.nl/LICENSE.\n *\n */\n\n#include <cmath>\n#include <numeric>\n\n#include <boost/math/special_functions/erf.hpp>\n#include <boost/math/distributions/normal.hpp>\n#include <boost/math/distributions/lognormal.hpp>\n\n#include \"tudat/math/statistics/multiVariateGaussianProbabilityDistributions.h\"\nnamespace tudat\n{\nnamespace statistics\n{\n\n\n//! Function to evaluate pdf of Gaussian cupola distribution\ndouble GaussianCopulaDistributionXd::evaluatePdf(\n        const Eigen::VectorXd& independentVariables )\n{\n    double probabilityDensity = 0.0 ;\n\n    // Check if vector independentVariables is inside [0,1]\n    int inBound = 0 ;\n    for( int i = 0 ; i < dimension_ ; i++ )\n    {\n        if( independentVariables(i) > 0.0 && independentVariables(i) < 1.0 )\n        {\n            inBound++;\n        }\n    }\n\n    // If data is in bounds\n    if( inBound == dimension_ )\n    {\n        // Convert U[0,1] to N[0,1] using inverse CDF of standard normal distribution\n        Eigen::VectorXd gaussianQuantiles( dimension_ ) ;\n        boost::math::normal distribution( 0.0 , 1.0 );\n\n        for( int i = 0 ; i < dimension_ ; i++ )\n        {\n            gaussianQuantiles( i ) = boost::math::quantile( distribution , independentVariables( i ) ); // Inverse cdf\n        }\n\n        // Calculate probability density\n        Eigen::MatrixXd location = - 0.5 * ( gaussianQuantiles.transpose() *\n                       ( inverseCorrelationMatrix_ - Eigen::MatrixXd::Identity( dimension_ , dimension_ ) ) *\n                                             gaussianQuantiles );\n\n        probabilityDensity = ( ( 1.0 / ( std::sqrt( determinant_ ) ) ) * std::exp( location( 0, 0 ) ) ) ;\n    }\n\n    return probabilityDensity ;\n}\n\n} // namespace statistics\n} // namespace tudat\n", "meta": {"hexsha": "d50ee6489dde50e1a1bac2f4161515e3052b4305", "size": 2149, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/math/statistics/multiVariateGaussianProbabilityDistributions.cpp", "max_stars_repo_name": "kimonito98/tudat", "max_stars_repo_head_hexsha": "c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/math/statistics/multiVariateGaussianProbabilityDistributions.cpp", "max_issues_repo_name": "kimonito98/tudat", "max_issues_repo_head_hexsha": "c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/math/statistics/multiVariateGaussianProbabilityDistributions.cpp", "max_forks_repo_name": "kimonito98/tudat", "max_forks_repo_head_hexsha": "c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.0746268657, "max_line_length": 118, "alphanum_fraction": 0.6389018148, "num_tokens": 525, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094145755218, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.460608125058007}}
{"text": "#include <algorithm>\r\n#include <iostream>\r\n#include <math.h>\r\n#include <malloc.h>\r\n#include <NTL/ZZ.h>\r\n\r\ninline bool incstates (int *states,int fields,int avoid){\r\n    states[--fields]++;\r\n\tif(states[fields]==avoid)states[fields]++;\r\n\twhile (fields&&states[fields]>9){\r\n\t\tstates[fields]=0;\r\n\t\tstates[--fields]++;\r\n\t\tif(states[fields]==avoid)states[fields]++;\r\n\t}\r\n\treturn (states[0] > 9)?(states[0]=0,false):true;\r\n}\r\n\r\nint main()\r\n{\r\n\tZZ totalsum = ZZ::zero();\r\n\tZZ zzOne = to_ZZ(1);\r\n\tZZ mul;\r\n\tZZ num;\r\n\tZZ min = to_ZZ(1000000000);\r\n\tint a[] = {0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1};\r\n    int states[] = {0,0,0,0,0,0,0,0};\r\n\tint nxt;\r\n\tfor (int i = 0;i < 10;i++){\r\n\t\tbool found = false;\r\n\t\tfor(int rep=1;rep<4&&!found;replaced++){\r\n\t\t\tdo{\r\n\t\t\t\tdo{\r\n\t\t\t\t\tnxt = 0;\r\n\t\t\t\t\tnum = ZZ::zero();\r\n\t\t\t\t\tmul = min * 10;\r\n\t\t\t\t\tfor(int k = rep;k<rep+10;k++)num+=((mul/=10)*((a[k])?states[nxt++]:i));\r\n\t\t\t\t\tif(ProbPrime(num) && num>min)found = (totalsum+=num,true);\r\n\t\t\t\t}while(incstates(states,rep,i));\r\n\t\t\t}while (std::next_permutation(a+rep,a+10+rep));\r\n\t\t}\r\n\t}\r\n\tcout << totalsum << \"\\n\";\r\n\treturn free(a);\r\n}", "meta": {"hexsha": "8e658734061cb06651244b23b792e5dd652877c7", "size": 1106, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "100-200/111.cpp", "max_stars_repo_name": "Thomaw/Project-Euler", "max_stars_repo_head_hexsha": "bcad5d8a1fd3ebaa06fa52d92d286607e9372a8d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "100-200/111.cpp", "max_issues_repo_name": "Thomaw/Project-Euler", "max_issues_repo_head_hexsha": "bcad5d8a1fd3ebaa06fa52d92d286607e9372a8d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "100-200/111.cpp", "max_forks_repo_name": "Thomaw/Project-Euler", "max_forks_repo_head_hexsha": "bcad5d8a1fd3ebaa06fa52d92d286607e9372a8d", "max_forks_repo_licenses": ["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.1363636364, "max_line_length": 77, "alphanum_fraction": 0.5596745027, "num_tokens": 397, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021708, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.46057752265714985}}
{"text": "/*\n [auto_generated]\n boost/numeric/odeint/stepper/bulirsch_stoer_dense_out.hpp\n\n [begin_description]\n Implementaiton of the Burlish-Stoer method with dense output\n [end_description]\n\n Copyright 2009-2011 Karsten Ahnert\n Copyright 2009-2011 Mario Mulansky\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_BULIRSCH_STOER_DENSE_OUT_HPP_INCLUDED\n#define BOOST_NUMERIC_ODEINT_STEPPER_BULIRSCH_STOER_DENSE_OUT_HPP_INCLUDED\n\n\n#include <iostream>\n\n#include <algorithm>\n\n#include <boost/config.hpp> // for min/max guidelines\n\n#include <boost/numeric/odeint/util/bind.hpp>\n\n#include <boost/math/special_functions/binomial.hpp>\n\n#include <boost/numeric/odeint/stepper/controlled_runge_kutta.hpp>\n#include <boost/numeric/odeint/stepper/modified_midpoint.hpp>\n#include <boost/numeric/odeint/stepper/controlled_step_result.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#include <boost/numeric/odeint/util/unit_helper.hpp>\n\n#include <boost/type_traits.hpp>\n\n\nnamespace boost {\nnamespace numeric {\nnamespace odeint {\n\ntemplate<\n    class State ,\n    class Value = double ,\n    class Deriv = State ,\n    class Time = Value ,\n    class Algebra = typename algebra_dispatcher< State >::algebra_type ,\n    class Operations = typename operations_dispatcher< State >::operations_type ,\n    class Resizer = initially_resizer\n    >\nclass bulirsch_stoer_dense_out {\n\n\npublic:\n\n    typedef State state_type;\n    typedef Value value_type;\n    typedef Deriv deriv_type;\n    typedef Time time_type;\n    typedef Algebra algebra_type;\n    typedef Operations operations_type;\n    typedef Resizer resizer_type;\n    typedef dense_output_stepper_tag stepper_category;\n#ifndef DOXYGEN_SKIP\n    typedef state_wrapper< state_type > wrapped_state_type;\n    typedef state_wrapper< deriv_type > wrapped_deriv_type;\n\n    typedef bulirsch_stoer_dense_out< State , Value , Deriv , Time , Algebra , Operations , Resizer > controlled_error_bs_type;\n\n    typedef typename inverse_time< time_type >::type inv_time_type;\n\n    typedef std::vector< value_type > value_vector;\n    typedef std::vector< time_type > time_vector;\n    typedef std::vector< inv_time_type > inv_time_vector;  //should be 1/time_type for boost.units\n    typedef std::vector< value_vector > value_matrix;\n    typedef std::vector< size_t > int_vector;\n    typedef std::vector< wrapped_state_type > state_vector_type;\n    typedef std::vector< wrapped_deriv_type > deriv_vector_type;\n    typedef std::vector< deriv_vector_type > deriv_table_type;\n#endif //DOXYGEN_SKIP\n\n    const static size_t m_k_max = 8;\n\n\n\n    bulirsch_stoer_dense_out(\n        value_type eps_abs = 1E-6 , value_type eps_rel = 1E-6 ,\n        value_type factor_x = 1.0 , value_type factor_dxdt = 1.0 ,\n        bool control_interpolation = false )\n        : m_error_checker( eps_abs , eps_rel , factor_x, factor_dxdt ) , \n          m_control_interpolation( control_interpolation) ,\n          m_last_step_rejected( false ) , m_first( true ) ,\n          m_current_state_x1( true ) ,\n          m_error( m_k_max ) ,\n          m_interval_sequence( m_k_max+1 ) ,\n          m_coeff( m_k_max+1 ) ,\n          m_cost( m_k_max+1 ) ,\n          m_table( m_k_max ) ,\n          m_mp_states( m_k_max+1 ) ,\n          m_derivs( m_k_max+1 ) ,\n          m_diffs( 2*m_k_max+1 ) ,\n          STEPFAC1( 0.65 ) , STEPFAC2( 0.94 ) , STEPFAC3( 0.02 ) , STEPFAC4( 4.0 ) , KFAC1( 0.8 ) , KFAC2( 0.9 )\n    {\n        BOOST_USING_STD_MIN();\n        BOOST_USING_STD_MAX();\n\n        for( unsigned short i = 0; i < m_k_max+1; i++ )\n        {\n            /* only this specific sequence allows for dense output */\n            m_interval_sequence[i] = 2 + 4*i;  // 2 6 10 14 ...\n            m_derivs[i].resize( m_interval_sequence[i] );\n            if( i == 0 )\n                m_cost[i] = m_interval_sequence[i];\n            else\n                m_cost[i] = m_cost[i-1] + m_interval_sequence[i];\n            m_coeff[i].resize(i);\n            for( size_t k = 0 ; k < i ; ++k  )\n            {\n                const value_type r = static_cast< value_type >( m_interval_sequence[i] ) / static_cast< value_type >( m_interval_sequence[k] );\n                m_coeff[i][k] = 1.0 / ( r*r - static_cast< value_type >( 1.0 ) ); // coefficients for extrapolation\n            }\n            // crude estimate of optimal order\n\n            m_current_k_opt = 4;\n            /* no calculation because log10 might not exist for value_type!\n            const value_type logfact( -log10( max BOOST_PREVENT_MACRO_SUBSTITUTION( eps_rel , static_cast< value_type >( 1.0E-12 ) ) ) * 0.6 + 0.5 );\n            m_current_k_opt = max BOOST_PREVENT_MACRO_SUBSTITUTION( 1 , min BOOST_PREVENT_MACRO_SUBSTITUTION( static_cast<int>( m_k_max-1 ) , static_cast<int>( logfact ) ));\n            */\n        }\n        int num = 1;\n        for( int i = 2*(m_k_max) ; i >=0  ; i-- )\n        {\n            m_diffs[i].resize( num );\n            num += (i+1)%2;\n        }\n    }\n\n    template< class System , class StateIn , class DerivIn , class StateOut , class DerivOut >\n    controlled_step_result try_step( System system , const StateIn &in , const DerivIn &dxdt , time_type &t , StateOut &out , DerivOut &dxdt_new , time_type &dt )\n    {\n        BOOST_USING_STD_MIN();\n        BOOST_USING_STD_MAX();\n        using std::pow;\n        \n        static const value_type val1( 1.0 );\n\n        typename odeint::unwrap_reference< System >::type &sys = system;\n\n        bool reject( true );\n\n        time_vector h_opt( m_k_max+1 );\n        inv_time_vector work( m_k_max+1 );\n\n        m_k_final = 0;\n        time_type new_h = dt;\n\n        //std::cout << \"t=\" << t <<\", dt=\" << dt << \", k_opt=\" << m_current_k_opt << \", first: \" << m_first << std::endl;\n\n        for( size_t k = 0 ; k <= m_current_k_opt+1 ; k++ )\n        {\n            m_midpoint.set_steps( m_interval_sequence[k] );\n            if( k == 0 )\n            {\n                m_midpoint.do_step( sys , in , dxdt , t , out , dt , m_mp_states[k].m_v , m_derivs[k]);\n            }\n            else\n            {\n                m_midpoint.do_step( sys , in , dxdt , t , m_table[k-1].m_v , dt , m_mp_states[k].m_v , m_derivs[k] );\n                extrapolate( k , m_table , m_coeff , out );\n                // get error estimate\n                m_algebra.for_each3( m_err.m_v , out , m_table[0].m_v ,\n                                     typename operations_type::template scale_sum2< value_type , value_type >( val1 , -val1 ) );\n                const value_type error = m_error_checker.error( m_algebra , in , dxdt , m_err.m_v , dt );\n                h_opt[k] = calc_h_opt( dt , error , k );\n                work[k] = static_cast<value_type>( m_cost[k] ) / h_opt[k];\n\n                m_k_final = k;\n\n                if( (k == m_current_k_opt-1) || m_first )\n                { // convergence before k_opt ?\n                    if( error < 1.0 )\n                    {\n                        //convergence\n                        reject = false;\n                        if( (work[k] < KFAC2*work[k-1]) || (m_current_k_opt <= 2) )\n                        {\n                            // leave order as is (except we were in first round)\n                            m_current_k_opt = min BOOST_PREVENT_MACRO_SUBSTITUTION( static_cast<int>(m_k_max)-1 , max BOOST_PREVENT_MACRO_SUBSTITUTION( 2 , static_cast<int>(k)+1 ) );\n                            new_h = h_opt[k] * static_cast<value_type>( m_cost[k+1] ) / static_cast<value_type>( m_cost[k] );\n                        } else {\n                            m_current_k_opt = min BOOST_PREVENT_MACRO_SUBSTITUTION( static_cast<int>(m_k_max)-1 , max BOOST_PREVENT_MACRO_SUBSTITUTION( 2 , static_cast<int>(k) ) );\n                            new_h = h_opt[k];\n                        }\n                        break;\n                    }\n                    else if( should_reject( error , k ) && !m_first )\n                    {\n                        reject = true;\n                        new_h = h_opt[k];\n                        break;\n                    }\n                }\n                if( k == m_current_k_opt )\n                { // convergence at k_opt ?\n                    if( error < 1.0 )\n                    {\n                        //convergence\n                        reject = false;\n                        if( (work[k-1] < KFAC2*work[k]) )\n                        {\n                            m_current_k_opt = max BOOST_PREVENT_MACRO_SUBSTITUTION( 2 , static_cast<int>(m_current_k_opt)-1 );\n                            new_h = h_opt[m_current_k_opt];\n                        }\n                        else if( (work[k] < KFAC2*work[k-1]) && !m_last_step_rejected )\n                        {\n                            m_current_k_opt = min BOOST_PREVENT_MACRO_SUBSTITUTION( static_cast<int>(m_k_max)-1 , static_cast<int>(m_current_k_opt)+1 );\n                            new_h = h_opt[k]*static_cast<value_type>( m_cost[m_current_k_opt] ) / static_cast<value_type>( m_cost[k] );\n                        } else\n                            new_h = h_opt[m_current_k_opt];\n                        break;\n                    }\n                    else if( should_reject( error , k ) )\n                    {\n                        reject = true;\n                        new_h = h_opt[m_current_k_opt];\n                        break;\n                    }\n                }\n                if( k == m_current_k_opt+1 )\n                { // convergence at k_opt+1 ?\n                    if( error < 1.0 )\n                    {   //convergence\n                        reject = false;\n                        if( work[k-2] < KFAC2*work[k-1] )\n                            m_current_k_opt = max BOOST_PREVENT_MACRO_SUBSTITUTION( 2 , static_cast<int>(m_current_k_opt)-1 );\n                        if( (work[k] < KFAC2*work[m_current_k_opt]) && !m_last_step_rejected )\n                            m_current_k_opt = min BOOST_PREVENT_MACRO_SUBSTITUTION( static_cast<int>(m_k_max)-1 , static_cast<int>(k) );\n                        new_h = h_opt[m_current_k_opt];\n                    } else\n                    {\n                        reject = true;\n                        new_h = h_opt[m_current_k_opt];\n                    }\n                    break;\n                }\n            }\n        }\n\n        if( !reject )\n        {\n\n            //calculate dxdt for next step and dense output\n            sys( out , dxdt_new , t+dt );\n\n            //prepare dense output\n            value_type error = prepare_dense_output( m_k_final , in , dxdt , out , dxdt_new , dt );\n\n            if( error > static_cast<value_type>(10) ) // we are not as accurate for interpolation as for the steps\n            {\n                reject = true;\n                new_h = dt * pow BOOST_PREVENT_MACRO_SUBSTITUTION( error , static_cast<value_type>(-1)/(2*m_k_final+2) );\n            } else {\n                t += dt;\n            }\n        }\n        //set next stepsize\n        if( !m_last_step_rejected || (new_h < dt) )\n            dt = new_h;\n\n        m_last_step_rejected = reject;\n        if( reject )\n            return fail;\n        else\n            return success;\n    }\n\n    template< class StateType >\n    void initialize( const StateType &x0 , const time_type &t0 , const time_type &dt0 )\n    {\n        m_resizer.adjust_size( x0 , detail::bind( &controlled_error_bs_type::template resize_impl< StateType > , detail::ref( *this ) , detail::_1 ) );\n        boost::numeric::odeint::copy( x0 , get_current_state() );\n        m_t = t0;\n        m_dt = dt0;\n        reset();\n    }\n\n\n    /*  =======================================================\n     *  the actual step method that should be called from outside (maybe make try_step private?)\n     */\n    template< class System >\n    std::pair< time_type , time_type > do_step( System system )\n    {\n        const size_t max_count = 1000;\n\n        if( m_first )\n        {\n            typename odeint::unwrap_reference< System >::type &sys = system;\n            sys( get_current_state() , get_current_deriv() , m_t );\n        }\n\n        controlled_step_result res = fail;\n        m_t_last = m_t;\n        size_t count = 0;\n        while( res == fail )\n        {\n            res = try_step( system , get_current_state() , get_current_deriv() , m_t , get_old_state() , get_old_deriv() , m_dt );\n            m_first = false;\n            if( count++ == max_count )\n                throw std::overflow_error( \"bulirsch_stoer : too much iterations!\");\n        }\n        toggle_current_state();\n        return std::make_pair( m_t_last , m_t );\n    }\n\n    /* performs the interpolation from a calculated step */\n    template< class StateOut >\n    void calc_state( time_type t , StateOut &x ) const\n    {\n        do_interpolation( t , x );\n    }\n\n    const state_type& current_state( void ) const\n    {\n        return get_current_state();\n    }\n\n    time_type current_time( void ) const\n    {\n        return m_t;\n    }\n\n    const state_type& previous_state( void ) const\n    {\n        return get_old_state();\n    }\n\n    time_type previous_time( void ) const\n    {\n        return m_t_last;\n    }\n\n    time_type current_time_step( void ) const\n    {\n        return m_dt;\n    }\n\n    /** \\brief Resets the internal state of the stepper. */\n    void reset()\n    {\n        m_first = true;\n        m_last_step_rejected = false;\n    }\n\n    template< class StateIn >\n    void adjust_size( const StateIn &x )\n    {\n        resize_impl( x );\n        m_midpoint.adjust_size();\n    }\n\n\nprivate:\n\n    template< class StateInOut , class StateVector >\n    void extrapolate( size_t k , StateVector &table , const value_matrix &coeff , StateInOut &xest , size_t order_start_index = 0 )\n    //polynomial extrapolation, see http://www.nr.com/webnotes/nr3web21.pdf\n    {\n        static const value_type val1( 1.0 );\n        for( int j=k-1 ; j>0 ; --j )\n        {\n            m_algebra.for_each3( table[j-1].m_v , table[j].m_v , table[j-1].m_v ,\n                                 typename operations_type::template scale_sum2< value_type , value_type >( val1 + coeff[k + order_start_index][j + order_start_index] ,\n                                                                                                           -coeff[k + order_start_index][j + order_start_index] ) );\n        }\n        m_algebra.for_each3( xest , table[0].m_v , xest ,\n                             typename operations_type::template scale_sum2< value_type , value_type >( val1 + coeff[k + order_start_index][0 + order_start_index] ,\n                                                                                                       -coeff[k + order_start_index][0 + order_start_index]) );\n    }\n\n\n    template< class StateVector >\n    void extrapolate_dense_out( size_t k , StateVector &table , const value_matrix &coeff , size_t order_start_index = 0 )\n    //polynomial extrapolation, see http://www.nr.com/webnotes/nr3web21.pdf\n    {\n        // result is written into table[0]\n        static const value_type val1( 1.0 );\n        for( int j=k ; j>1 ; --j )\n        {\n            m_algebra.for_each3( table[j-1].m_v , table[j].m_v , table[j-1].m_v ,\n                                 typename operations_type::template scale_sum2< value_type , value_type >( val1 + coeff[k + order_start_index][j + order_start_index - 1] ,\n                                                                                                           -coeff[k + order_start_index][j + order_start_index - 1] ) );\n        }\n        m_algebra.for_each3( table[0].m_v , table[1].m_v , table[0].m_v ,\n                             typename operations_type::template scale_sum2< value_type , value_type >( val1 + coeff[k + order_start_index][order_start_index] ,\n                                                                                                       -coeff[k + order_start_index][order_start_index]) );\n    }\n\n    time_type calc_h_opt( time_type h , value_type error , size_t k ) const\n    {\n        BOOST_USING_STD_MIN();\n        BOOST_USING_STD_MAX();\n        using std::pow;\n\n        value_type expo=1.0/(m_interval_sequence[k-1]);\n        value_type facmin = pow BOOST_PREVENT_MACRO_SUBSTITUTION( STEPFAC3 , expo );\n        value_type fac;\n        if (error == 0.0)\n            fac=1.0/facmin;\n        else\n        {\n            fac = STEPFAC2 / pow BOOST_PREVENT_MACRO_SUBSTITUTION( error / STEPFAC1 , expo );\n            fac = max BOOST_PREVENT_MACRO_SUBSTITUTION( facmin/STEPFAC4 , min BOOST_PREVENT_MACRO_SUBSTITUTION( 1.0/facmin , fac ) );\n        }\n        return h*fac;\n    }\n\n    bool in_convergence_window( size_t k ) const\n    {\n        if( (k == m_current_k_opt-1) && !m_last_step_rejected )\n            return true; // decrease order only if last step was not rejected\n        return ( (k == m_current_k_opt) || (k == m_current_k_opt+1) );\n    }\n\n    bool should_reject( value_type error , size_t k ) const\n    {\n        if( k == m_current_k_opt-1 )\n        {\n            const value_type d = m_interval_sequence[m_current_k_opt] * m_interval_sequence[m_current_k_opt+1] /\n                (m_interval_sequence[0]*m_interval_sequence[0]);\n            //step will fail, criterion 17.3.17 in NR\n            return ( error > d*d );\n        }\n        else if( k == m_current_k_opt )\n        {\n            const value_type d = m_interval_sequence[m_current_k_opt+1] / m_interval_sequence[0];\n            return ( error > d*d );\n        } else\n            return error > 1.0;\n    }\n\n    template< class StateIn1 , class DerivIn1 , class StateIn2 , class DerivIn2 >\n    value_type prepare_dense_output( int k , const StateIn1 &x_start , const DerivIn1 &dxdt_start ,\n                                     const StateIn2 & /* x_end */ , const DerivIn2 & /*dxdt_end */ , time_type dt )  \n    /* k is the order to which the result was approximated */\n    {\n\n        /* compute the coefficients of the interpolation polynomial\n         * we parametrize the interval t .. t+dt by theta = -1 .. 1\n         * we use 2k+3 values at the interval center theta=0 to obtain the interpolation coefficients\n         * the values are x(t+dt/2) and the derivatives dx/dt , ... d^(2k+2) x / dt^(2k+2) at the midpoints\n         * the derivatives are approximated via finite differences\n         * all values are obtained from interpolation of the results from the increasing orders of the midpoint calls\n         */\n\n        // calculate finite difference approximations to derivatives at the midpoint\n        for( int j = 0 ; j<=k ; j++ )\n        {\n            /* not working with boost units... */\n            const value_type d = m_interval_sequence[j] / ( static_cast<value_type>(2) * dt );\n            value_type f = 1.0; //factor 1/2 here because our interpolation interval has length 2 !!!\n            for( int kappa = 0 ; kappa <= 2*j+1 ; ++kappa )\n            {\n                calculate_finite_difference( j , kappa , f , dxdt_start );\n                f *= d;\n            }\n\n            if( j > 0 )\n                extrapolate_dense_out( j , m_mp_states , m_coeff );\n        }\n\n        time_type d = dt/2;\n\n        // extrapolate finite differences\n        for( int kappa = 0 ; kappa<=2*k+1 ; kappa++ )\n        {\n            for( int j=1 ; j<=(k-kappa/2) ; ++j )\n                extrapolate_dense_out( j , m_diffs[kappa] , m_coeff , kappa/2 );\n\n            // extrapolation results are now stored in m_diffs[kappa][0]\n\n            // divide kappa-th derivative by kappa because we need these terms for dense output interpolation\n            m_algebra.for_each1( m_diffs[kappa][0].m_v , typename operations_type::template scale< time_type >( static_cast<time_type>(d) ) );\n\n            d *= dt/(2*(kappa+2));\n        }\n\n        // dense output coefficients a_0 is stored in m_mp_states[0], a_i for i = 1...2k are stored in m_diffs[i-1][0]\n\n        // the error is just the highest order coefficient of the interpolation polynomial\n        // this is because we use only the midpoint theta=0 as support for the interpolation (remember that theta = -1 .. 1)\n\n        value_type error = 0.0;\n        if( m_control_interpolation )\n        {\n            boost::numeric::odeint::copy( m_diffs[2*k+1][0].m_v , m_err.m_v );\n            error = m_error_checker.error( m_algebra , x_start , dxdt_start , m_err.m_v , dt );\n        }\n\n        return error;\n    }\n\n    template< class DerivIn >\n    void calculate_finite_difference( size_t j , size_t kappa , value_type fac , const DerivIn &dxdt )\n    {\n        const int m = m_interval_sequence[j]/2-1;\n        if( kappa == 0) // no calculation required for 0th derivative of f\n        {\n            m_algebra.for_each2( m_diffs[0][j].m_v , m_derivs[j][m].m_v ,\n                                 typename operations_type::template scale_sum1< value_type >( fac ) );\n        }\n        else\n        {\n            // calculate the index of m_diffs for this kappa-j-combination\n            const int j_diffs = j - kappa/2;\n\n            m_algebra.for_each2( m_diffs[kappa][j_diffs].m_v , m_derivs[j][m+kappa].m_v ,\n                                 typename operations_type::template scale_sum1< value_type >( fac ) );\n            value_type sign = -1.0;\n            int c = 1;\n            //computes the j-th order finite difference for the kappa-th derivative of f at t+dt/2 using function evaluations stored in m_derivs\n            for( int i = m+static_cast<int>(kappa)-2 ; i >= m-static_cast<int>(kappa) ; i -= 2 )\n            {\n                if( i >= 0 )\n                {\n                    m_algebra.for_each3( m_diffs[kappa][j_diffs].m_v , m_diffs[kappa][j_diffs].m_v , m_derivs[j][i].m_v ,\n                                         typename operations_type::template scale_sum2< value_type , value_type >( 1.0 ,\n                                                                                                                   sign * fac * boost::math::binomial_coefficient< value_type >( kappa , c ) ) );\n                }\n                else\n                {\n                    m_algebra.for_each3( m_diffs[kappa][j_diffs].m_v , m_diffs[kappa][j_diffs].m_v , dxdt ,\n                                         typename operations_type::template scale_sum2< value_type , value_type >( 1.0 , sign * fac ) );\n                }\n                sign *= -1;\n                ++c;\n            }\n        }\n    }\n\n    template< class StateOut >\n    void do_interpolation( time_type t , StateOut &out ) const\n    {\n        // interpolation polynomial is defined for theta = -1 ... 1\n        // m_k_final is the number of order-iterations done for the last step - it governs the order of the interpolation polynomial\n        const value_type theta = 2 * get_unit_value( (t - m_t_last) / (m_t - m_t_last) ) - 1;\n        // we use only values at interval center, that is theta=0, for interpolation\n        // our interpolation polynomial is thus of order 2k+2, hence we have 2k+3 terms\n\n        boost::numeric::odeint::copy( m_mp_states[0].m_v , out );\n        // add remaining terms: x += a_1 theta + a2 theta^2 + ... + a_{2k} theta^{2k}\n        value_type theta_pow( theta );\n        for( size_t i=0 ; i<=2*m_k_final+1 ; ++i )\n        {\n            m_algebra.for_each3( out , out , m_diffs[i][0].m_v ,\n                                 typename operations_type::template scale_sum2< value_type >( static_cast<value_type>(1) , theta_pow ) );\n            theta_pow *= theta;\n        }\n    }\n\n    /* Resizer methods */\n    template< class StateIn >\n    bool resize_impl( const StateIn &x )\n    {\n        bool resized( false );\n\n        resized |= adjust_size_by_resizeability( m_x1 , x , typename is_resizeable<state_type>::type() );\n        resized |= adjust_size_by_resizeability( m_x2 , x , typename is_resizeable<state_type>::type() );\n        resized |= adjust_size_by_resizeability( m_dxdt1 , x , typename is_resizeable<state_type>::type() );\n        resized |= adjust_size_by_resizeability( m_dxdt2 , x , typename is_resizeable<state_type>::type() );\n        resized |= adjust_size_by_resizeability( m_err , x , typename is_resizeable<state_type>::type() );\n\n        for( size_t i = 0 ; i < m_k_max ; ++i )\n            resized |= adjust_size_by_resizeability( m_table[i] , x , typename is_resizeable<state_type>::type() );\n        for( size_t i = 0 ; i < m_k_max+1 ; ++i )\n            resized |= adjust_size_by_resizeability( m_mp_states[i] , x , typename is_resizeable<state_type>::type() );\n        for( size_t i = 0 ; i < m_k_max+1 ; ++i )\n            for( size_t j = 0 ; j < m_derivs[i].size() ; ++j )\n                resized |= adjust_size_by_resizeability( m_derivs[i][j] , x , typename is_resizeable<deriv_type>::type() );\n        for( size_t i = 0 ; i < 2*m_k_max+1 ; ++i )\n            for( size_t j = 0 ; j < m_diffs[i].size() ; ++j )\n                resized |= adjust_size_by_resizeability( m_diffs[i][j] , x , typename is_resizeable<deriv_type>::type() );\n\n        return resized;\n    }\n\n\n    state_type& get_current_state( void )\n    {\n        return m_current_state_x1 ? m_x1.m_v : m_x2.m_v ;\n    }\n    \n    const state_type& get_current_state( void ) const\n    {\n        return m_current_state_x1 ? m_x1.m_v : m_x2.m_v ;\n    }\n    \n    state_type& get_old_state( void )\n    {\n        return m_current_state_x1 ? m_x2.m_v : m_x1.m_v ;\n    }\n    \n    const state_type& get_old_state( void ) const\n    {\n        return m_current_state_x1 ? m_x2.m_v : m_x1.m_v ;\n    }\n\n    deriv_type& get_current_deriv( void )\n    {\n        return m_current_state_x1 ? m_dxdt1.m_v : m_dxdt2.m_v ;\n    }\n    \n    const deriv_type& get_current_deriv( void ) const\n    {\n        return m_current_state_x1 ? m_dxdt1.m_v : m_dxdt2.m_v ;\n    }\n    \n    deriv_type& get_old_deriv( void )\n    {\n        return m_current_state_x1 ? m_dxdt2.m_v : m_dxdt1.m_v ;\n    }\n    \n    const deriv_type& get_old_deriv( void ) const\n    {\n        return m_current_state_x1 ? m_dxdt2.m_v : m_dxdt1.m_v ;\n    }\n\n    \n    void toggle_current_state( void )\n    {\n        m_current_state_x1 = ! m_current_state_x1;\n    }\n\n\n\n    default_error_checker< value_type, algebra_type , operations_type > m_error_checker;\n    modified_midpoint_dense_out< state_type , value_type , deriv_type , time_type , algebra_type , operations_type , resizer_type > m_midpoint;\n\n    bool m_control_interpolation;\n\n    bool m_last_step_rejected;\n    bool m_first;\n\n    time_type m_t;\n    time_type m_dt;\n    time_type m_dt_last;\n    time_type m_t_last;\n\n    size_t m_current_k_opt;\n    size_t m_k_final;\n\n    algebra_type m_algebra;\n\n    resizer_type m_resizer;\n\n    wrapped_state_type m_x1 , m_x2;\n    wrapped_deriv_type m_dxdt1 , m_dxdt2;\n    wrapped_state_type m_err;\n    bool m_current_state_x1;\n\n\n\n    value_vector m_error; // errors of repeated midpoint steps and extrapolations\n    int_vector m_interval_sequence; // stores the successive interval counts\n    value_matrix m_coeff;\n    int_vector m_cost; // costs for interval count\n\n    state_vector_type m_table; // sequence of states for extrapolation\n\n    //for dense output:\n    state_vector_type m_mp_states; // sequence of approximations of x at distance center\n    deriv_table_type m_derivs; // table of function values\n    deriv_table_type m_diffs; // table of function values\n\n    //wrapped_state_type m_a1 , m_a2 , m_a3 , m_a4;\n\n    const value_type STEPFAC1 , STEPFAC2 , STEPFAC3 , STEPFAC4 , KFAC1 , KFAC2;\n};\n\n\n\n/********** DOXYGEN **********/\n\n/**\n * \\class bulirsch_stoer_dense_out\n * \\brief The Bulirsch-Stoer algorithm.\n * \n * The Bulirsch-Stoer is a controlled stepper that adjusts both step size\n * and order of the method. The algorithm uses the modified midpoint and\n * a polynomial extrapolation compute the solution. This class also provides\n * dense output facility.\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 bulirsch_stoer_dense_out::bulirsch_stoer_dense_out( value_type eps_abs , value_type eps_rel , value_type factor_x , value_type factor_dxdt , bool control_interpolation )\n     * \\brief Constructs the bulirsch_stoer class, including initialization of \n     * the error bounds.\n     *\n     * \\param eps_abs Absolute tolerance level.\n     * \\param eps_rel Relative tolerance level.\n     * \\param factor_x Factor for the weight of the state.\n     * \\param factor_dxdt Factor for the weight of the derivative.\n     * \\param control_interpolation Set true to additionally control the error of \n     * the interpolation.\n     */\n\n    /**\n     * \\fn bulirsch_stoer_dense_out::try_step( System system , const StateIn &in , const DerivIn &dxdt , time_type &t , StateOut &out , DerivOut &dxdt_new , time_type &dt )\n     * \\brief Tries to perform one step.\n     *\n     * This method tries to do one step with step size dt. If the error estimate\n     * is to large, the step is rejected and the method returns fail and the \n     * step size dt is reduced. If the error estimate is acceptably small, the\n     * step is performed, success is returned and dt might be increased to make \n     * the steps as large as possible. This method also updates t if a step is\n     * performed. Also, the internal order of the stepper is adjusted if required.\n     *\n     * \\param system The system function to solve, hence the r.h.s. of the ODE. \n     * It must fulfill the Simple System concept.\n     * \\param in The state of the ODE which should be solved.\n     * \\param dxdt The derivative of state.\n     * \\param t The value of the time. Updated if the step is successful.\n     * \\param out Used to store the result of the step.\n     * \\param dt The step size. Updated.\n     * \\return success if the step was accepted, fail otherwise.\n     */\n\n    /**\n     * \\fn bulirsch_stoer_dense_out::initialize( const StateType &x0 , const time_type &t0 , const time_type &dt0 )\n     * \\brief Initializes the dense output stepper.\n     *\n     * \\param x0 The initial state.\n     * \\param t0 The initial time.\n     * \\param dt0 The initial time step.\n     */\n\n    /**\n     * \\fn bulirsch_stoer_dense_out::do_step( System system )\n     * \\brief Does one time step. This is the main method that should be used to \n     * integrate an ODE with this stepper.\n     * \\note initialize has to be called before using this method to set the\n     * initial conditions x,t and the stepsize.\n     * \\param system The system function to solve, hence the r.h.s. of the\n     * ordinary differential equation. It must fulfill the Simple System concept.\n     * \\return Pair with start and end time of the integration step.\n     */\n\n    /**\n     * \\fn bulirsch_stoer_dense_out::calc_state( time_type t , StateOut &x ) const\n     * \\brief Calculates the solution at an intermediate point within the last step\n     * \\param t The time at which the solution should be calculated, has to be\n     * in the current time interval.\n     * \\param x The output variable where the result is written into.\n     */\n\n    /**\n     * \\fn bulirsch_stoer_dense_out::current_state( void ) const\n     * \\brief Returns the current state of the solution.\n     * \\return The current state of the solution x(t).\n     */\n\n    /**\n     * \\fn bulirsch_stoer_dense_out::current_time( void ) const\n     * \\brief Returns the current time of the solution.\n     * \\return The current time of the solution t.\n     */\n\n    /**\n     * \\fn bulirsch_stoer_dense_out::previous_state( void ) const\n     * \\brief Returns the last state of the solution.\n     * \\return The last state of the solution x(t-dt).\n     */\n\n    /**\n     * \\fn bulirsch_stoer_dense_out::previous_time( void ) const\n     * \\brief Returns the last time of the solution.\n     * \\return The last time of the solution t-dt.\n     */\n\n    /**\n     * \\fn bulirsch_stoer_dense_out::current_time_step( void ) const\n     * \\brief Returns the current step size.\n     * \\return The current step size.\n     */\n\n    /**\n     * \\fn bulirsch_stoer_dense_out::adjust_size( const StateIn &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}\n}\n}\n\n#endif // BOOST_NUMERIC_ODEINT_STEPPER_BULIRSCH_STOER_HPP_INCLUDED\n", "meta": {"hexsha": "bae8e5970d9826aa15a0ba7f918aabb83ab9fa94", "size": 32803, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Externals/Boost/boost/numeric/odeint/stepper/bulirsch_stoer_dense_out.hpp", "max_stars_repo_name": "MINATILO/packing-generation", "max_stars_repo_head_hexsha": "4d4f5d037e0687b57178602b989431e82a5c8b96", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 79.0, "max_stars_repo_stars_event_min_datetime": "2015-08-23T12:05:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:39:56.000Z", "max_issues_repo_path": "Externals/Boost/boost/numeric/odeint/stepper/bulirsch_stoer_dense_out.hpp", "max_issues_repo_name": "MINATILO/packing-generation", "max_issues_repo_head_hexsha": "4d4f5d037e0687b57178602b989431e82a5c8b96", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 31.0, "max_issues_repo_issues_event_min_datetime": "2015-07-20T17:57:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-02T10:31:50.000Z", "max_forks_repo_path": "Externals/Boost/boost/numeric/odeint/stepper/bulirsch_stoer_dense_out.hpp", "max_forks_repo_name": "MINATILO/packing-generation", "max_forks_repo_head_hexsha": "4d4f5d037e0687b57178602b989431e82a5c8b96", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 36.0, "max_forks_repo_forks_event_min_datetime": "2015-10-14T02:43:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T12:51:03.000Z", "avg_line_length": 40.2490797546, "max_line_length": 193, "alphanum_fraction": 0.588909551, "num_tokens": 8109, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145998, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.46048373637808154}}
{"text": "#include <gurobi_c++.h>\n#include <iostream>\n#include <cassert>\n#include <boost/filesystem.hpp>\nusing namespace std;\nnamespace fs = boost::filesystem;\n\nint main() {\n  fs::remove(fs::path(\"example.log\"));\n\n  try {\n    GRBEnv env(\"example.log\");\n    GRBModel model(env);\n    model.set(GRB_StringAttr_ModelName, \"model1\");\n\n    auto x = model.addVar(0.0, 1.0, 0.0, GRB_BINARY, \"x\");\n    auto y = model.addVar(0.0, 1.0, 0.0, GRB_BINARY, \"y\");\n    auto z = model.addVar(0.0, 1.0, 0.0, GRB_BINARY, \"z\");\n    model.update();\n\n    model.setObjective(x + 2.0 * y + z, GRB_MINIMIZE);\n\n    model.addConstr(x + y + z <= 2.0, \"c0\");\n    model.addConstr(x + y == 1.0, \"c1\");\n\n    model.optimize();\n\n    assert(model.get(GRB_DoubleAttr_ObjVal) == 1.0);\n    assert(x.get(GRB_DoubleAttr_X) == 1);\n    assert(y.get(GRB_DoubleAttr_X) == 0);\n    assert(z.get(GRB_DoubleAttr_X) == 0);\n\n  } catch (GRBException e) {\n    cout << e.getErrorCode() << endl;\n    cout << e.getMessage() << endl;\n    return 1;\n  }\n\n  assert(fs::exists(fs::path(\"example.log\")));\n}\n", "meta": {"hexsha": "cf95d09586833b22c957e23e1bab7361342ab7e4", "size": 1035, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mingw-w64-gurobi/check/example.cpp", "max_stars_repo_name": "ys-nuem/msys2-devtools", "max_stars_repo_head_hexsha": "f124a7444e21dcce4f27994504dbee69bf7501b6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mingw-w64-gurobi/check/example.cpp", "max_issues_repo_name": "ys-nuem/msys2-devtools", "max_issues_repo_head_hexsha": "f124a7444e21dcce4f27994504dbee69bf7501b6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mingw-w64-gurobi/check/example.cpp", "max_forks_repo_name": "ys-nuem/msys2-devtools", "max_forks_repo_head_hexsha": "f124a7444e21dcce4f27994504dbee69bf7501b6", "max_forks_repo_licenses": ["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.243902439, "max_line_length": 58, "alphanum_fraction": 0.6096618357, "num_tokens": 344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746407, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.46048372973027135}}
{"text": "// Copyright (C) 2012  Davis E. King (davis@dlib.net)\n// License: Boost Software License   See LICENSE.txt for the full license.\n#include <sstream>\n#include <string>\n#include <cstdlib>\n#include <ctime>\n#include <dlib/graph_cuts.h>\n#include <dlib/graph_utils.h>\n#include <dlib/directed_graph.h>\n#include <dlib/graph.h>\n#include <dlib/rand.h>\n#include <dlib/hash.h>\n#include <dlib/image_transforms.h>\n\n#include \"tester.h\"\n\nnamespace  \n{\n\n    using namespace test;\n    using namespace dlib;\n    using namespace std;\n\n\n    logger dlog(\"test.graph_cuts\");\n\n// ----------------------------------------------------------------------------------------\n\n    class dense_potts_problem \n    {\n    public:\n        typedef double value_type;\n    private:\n\n        matrix<value_type,0,1> factors1;\n        matrix<value_type> factors2;\n        matrix<node_label,0,1> labels;\n    public:\n\n        dense_potts_problem (\n            unsigned long num_nodes,\n            dlib::rand& rnd\n        )\n        {\n            factors1 = -7*(randm(num_nodes, 1, rnd)-0.5);\n            factors2 = make_symmetric(randm(num_nodes, num_nodes, rnd) > 0.5);\n            labels.set_size(num_nodes);\n            labels = FREE_NODE;\n        }\n\n        unsigned long number_of_nodes (\n        ) const { return factors1.nr(); }\n\n        unsigned long number_of_neighbors (\n            unsigned long // idx\n        ) const { return number_of_nodes()-1; }\n\n        unsigned long get_neighbor_idx (\n            unsigned long node_id1,\n            unsigned long node_id2\n        ) const\n        {\n            if (node_id2 < node_id1)\n                return node_id2;\n            else\n                return node_id2-1;\n        }\n\n        unsigned long get_neighbor (\n            unsigned long node_id,\n            unsigned long idx\n        ) const\n        {\n            DLIB_TEST(node_id < number_of_nodes());\n            DLIB_TEST(idx < number_of_neighbors(node_id));\n            if (idx < node_id)\n                return idx;\n            else\n                return idx+1;\n        }\n\n        void set_label (\n            const unsigned long& idx,\n            node_label value\n        )\n        {\n            labels(idx) = value;\n        }\n\n        node_label get_label (\n            const unsigned long& idx\n        ) const\n        {\n            return labels(idx);\n        }\n\n\n        value_type factor_value (unsigned long idx) const\n        {\n            DLIB_TEST(idx < number_of_nodes());\n\n            return factors1(idx);\n        }\n\n        value_type factor_value_disagreement (unsigned long idx1, unsigned long idx2) const\n        {\n            DLIB_TEST(idx1 != idx2);\n            DLIB_TEST(idx1 < number_of_nodes());\n            DLIB_TEST(idx2 < number_of_nodes());\n            DLIB_TEST(get_neighbor_idx(idx1,idx2) < number_of_neighbors(idx1));\n            DLIB_TEST(get_neighbor_idx(idx2,idx1) < number_of_neighbors(idx2));\n\n            return factors2(idx1, idx2);\n        }\n\n    };\n\n// ----------------------------------------------------------------------------------------\n\n    class image_potts_problem \n    {\n    public:\n        typedef double value_type;\n        const static unsigned long max_number_of_neighbors = 4;\n    private:\n\n        matrix<value_type,0,1> factors1;\n        matrix<value_type> factors2;\n        matrix<node_label,0,1> labels;\n        long nr;\n        long nc;\n        rectangle rect, inner_rect;\n        mutable long count;\n    public:\n\n        image_potts_problem (\n            long nr_,\n            long nc_,\n            dlib::rand& rnd\n        ) : nr(nr_), nc(nc_)\n        {\n            rect = rectangle(0,0,nc-1,nr-1);\n            inner_rect = shrink_rect(rect,1);\n            const unsigned long num_nodes = nr*nc;\n            factors1 = -7*(randm(num_nodes, 1, rnd));\n            factors2 = randm(num_nodes, 4, rnd) > 0.5;\n\n            //factors1 = 0;\n            //set_rowm(factors1, range(0, factors1.nr()/2)) = -1;\n\n            labels.set_size(num_nodes);\n            labels = FREE_NODE;\n\n            count = 0;\n        }\n\n        ~image_potts_problem()\n        {\n            dlog << LTRACE << \"interface calls: \" << count;\n            dlog << LTRACE << \"labels hash: \"<< murmur_hash3_128bit(&labels(0), labels.size()*sizeof(labels(0)), 0).first;\n        }\n\n        unsigned long number_of_nodes (\n        ) const { return factors1.nr(); }\n\n        unsigned long number_of_neighbors (\n            unsigned long idx\n        ) const \n        { \n            ++count;\n            const point& p = get_loc(idx);\n            if (inner_rect.contains(p))\n                return 4;\n            else if (p == rect.tl_corner() ||\n                     p == rect.bl_corner() ||\n                     p == rect.tr_corner() ||\n                     p == rect.br_corner() )\n                return 2;\n            else\n                return 3;\n        }\n\n        unsigned long get_neighbor_idx (\n            long node_id1,\n            long node_id2\n        ) const\n        {\n            ++count;\n            const point& p = get_loc(node_id1);\n            long ret = 0;\n            if (rect.contains(p + point(1,0)))\n            {\n                if (node_id2-node_id1 == 1)\n                    return ret;\n                ++ret;\n            }\n\n            if (rect.contains(p - point(1,0)))\n            {\n                if (node_id2-node_id1 == -1)\n                    return ret;\n                ++ret;\n            }\n\n            if (rect.contains(p + point(0,1)))\n            {\n                if (node_id2-node_id1 == nc)\n                    return ret;\n                ++ret;\n            }\n\n            return ret;\n        }\n\n        unsigned long get_neighbor (\n            long node_id,\n            long idx\n        ) const\n        {\n            ++count;\n            const point& p = get_loc(node_id);\n            if (rect.contains(p + point(1,0)))\n            {\n                if (idx == 0)\n                    return node_id+1;\n                --idx;\n            }\n\n            if (rect.contains(p - point(1,0)))\n            {\n                if (idx == 0)\n                    return node_id-1;\n                --idx;\n            }\n\n            if (rect.contains(p + point(0,1)))\n            {\n                if (idx == 0)\n                    return node_id+nc;\n                --idx;\n            }\n\n            return node_id-nc;\n        }\n\n        void set_label (\n            const unsigned long& idx,\n            node_label value\n        )\n        {\n            ++count;\n            labels(idx) = value;\n        }\n\n        node_label get_label (\n            const unsigned long& idx\n        ) const\n        {\n            ++count;\n            return labels(idx);\n        }\n\n        value_type factor_value (unsigned long idx) const\n        {\n            ++count;\n            DLIB_TEST(idx < (unsigned long)number_of_nodes());\n\n            return factors1(idx);\n        }\n\n        value_type factor_value_disagreement (unsigned long idx1, unsigned long idx2) const\n        {\n            ++count;\n            DLIB_TEST(idx1 != idx2);\n            DLIB_TEST(idx1 < (unsigned long)number_of_nodes());\n            DLIB_TEST(idx2 < (unsigned long)number_of_nodes());\n\n            // make this function symmetric\n            if (idx1 > idx2)\n                swap(idx1,idx2);\n\n\n            DLIB_TEST(get_neighbor(idx1, get_neighbor_idx(idx1, idx2)) == idx2);\n            DLIB_TEST(get_neighbor(idx2, get_neighbor_idx(idx2, idx1)) == idx1);\n\n            // the neighbor relationship better be symmetric\n            DLIB_TEST(get_neighbor_idx(idx1,idx2) < number_of_neighbors(idx1));\n            DLIB_TEST_MSG(get_neighbor_idx(idx2,idx1) < number_of_neighbors(idx2),\n                         \"\\n idx1: \"<< idx1  <<\n                         \"\\n idx2: \"<< idx2  <<\n                         \"\\n get_neighbor_idx(idx2,idx1): \"<< get_neighbor_idx(idx2,idx1) <<\n                         \"\\n number_of_neighbors(idx2): \" << number_of_neighbors(idx2) <<\n                         \"\\n nr: \"<< nr << \n                         \"\\n nc: \"<< nc \n            );\n\n            return factors2(idx1, get_neighbor_idx(idx1,idx2));\n        }\n\n    private:\n        point get_loc (\n            const unsigned long& idx\n        ) const\n        {\n            return point(idx%nc, idx/nc);\n        }\n\n    };\n\n// ----------------------------------------------------------------------------------------\n\n    template <typename potts_model>\n    void brute_force_potts_model (\n        potts_model& g\n    )\n    {\n        potts_model m(g);\n\n        const unsigned long num = (unsigned long)std::pow(2.0, (double)m.number_of_nodes());\n\n        double best_score = -std::numeric_limits<double>::infinity();\n        for (unsigned long i = 0; i < num; ++i)\n        {\n            for (unsigned long j = 0; j < m.number_of_nodes(); ++j)\n            {\n                unsigned long T = (1)<<j;\n                T = (T&i);\n                if (T != 0)\n                    m.set_label(j,SINK_CUT);\n                else\n                    m.set_label(j,SOURCE_CUT);\n            }\n\n\n            double score = potts_model_score(m);\n            if (score > best_score)\n            {\n                best_score = score;\n                g = m;\n            }\n        }\n    }\n\n// ----------------------------------------------------------------------------------------\n\n    template <typename graph_type>\n    void brute_force_potts_model_on_graph (\n        const graph_type& g,\n        std::vector<node_label>& labels_\n    )\n    {\n        std::vector<node_label> labels;\n        labels.resize(g.number_of_nodes());\n\n        const unsigned long num = (unsigned long)std::pow(2.0, (double)g.number_of_nodes());\n\n        double best_score = -std::numeric_limits<double>::infinity();\n        for (unsigned long i = 0; i < num; ++i)\n        {\n            for (unsigned long j = 0; j < g.number_of_nodes(); ++j)\n            {\n                unsigned long T = (1)<<j;\n                T = (T&i);\n                if (T != 0)\n                    labels[j] = SINK_CUT;\n                else\n                    labels[j] = SOURCE_CUT;\n            }\n\n\n            double score = potts_model_score(g,labels);\n            if (score > best_score)\n            {\n                best_score = score;\n                labels_ = labels;\n            }\n        }\n    }\n\n// ----------------------------------------------------------------------------------------\n\n    template <typename graph_type>\n    void make_random_undirected_graph(\n        dlib::rand& rnd,\n        graph_type& g\n    )\n    {\n        typedef typename graph_type::edge_type edge_weight_type;\n        g.clear();\n        const unsigned int num_nodes = rnd.get_random_32bit_number()%8;\n        g.set_number_of_nodes(num_nodes);\n\n        const unsigned int num_edges = static_cast<unsigned int>(num_nodes*(num_nodes-1)/2*rnd.get_random_double() + 0.5);\n\n        // add the right number of randomly selected edges\n        unsigned int count = 0;\n        while (count < num_edges)\n        {\n            unsigned long i = rnd.get_random_32bit_number()%g.number_of_nodes();\n            unsigned long j = rnd.get_random_32bit_number()%g.number_of_nodes();\n            if (i != j && g.has_edge(i, j) == false)\n            {\n                ++count;\n                g.add_edge(i, j);\n                edge(g, i, j) = static_cast<edge_weight_type>(rnd.get_random_double()*50);\n            }\n        }\n\n        for (unsigned long i = 0; i < g.number_of_nodes(); ++i)\n        {\n            g.node(i).data = static_cast<edge_weight_type>(rnd.get_random_gaussian()*200);\n        }\n    }\n\n// ----------------------------------------------------------------------------------------\n\n    void test_graph_potts_model(\n        dlib::rand& rnd\n    )\n    {\n        using namespace std;\n        double brute_force_score;\n        double graph_cut_score;\n\n        graph<double,double>::kernel_1a_c temp;\n        make_random_undirected_graph(rnd,temp);\n\n        {\n            std::vector<node_label> labels;\n\n            brute_force_potts_model_on_graph(temp, labels);\n\n            for (unsigned long i = 0; i < temp.number_of_nodes(); ++i)\n            {\n                dlog << LTRACE << \"node \" << i << \": \"<< (int)labels[i];\n            }\n\n            brute_force_score = potts_model_score(temp, labels);\n            dlog << LTRACE << \"brute force score: \"<< brute_force_score;\n        }\n        dlog << LTRACE << \"******************\";\n\n        {\n            std::vector<node_label> labels;\n            find_max_factor_graph_potts(temp, labels);\n            DLIB_TEST(temp.number_of_nodes() == labels.size());\n\n            for (unsigned long i = 0; i < temp.number_of_nodes(); ++i)\n            {\n                dlog << LTRACE << \"node \" << i << \": \"<< (int)labels[i];\n            }\n            graph_cut_score = potts_model_score(temp, labels);\n            dlog << LTRACE << \"graph cut score: \"<< graph_cut_score;\n        }\n\n        DLIB_TEST_MSG(graph_cut_score == brute_force_score, std::abs(graph_cut_score - brute_force_score));\n\n        dlog << LTRACE << \"##################\";\n        dlog << LTRACE << \"##################\";\n        dlog << LTRACE << \"##################\";\n    }\n\n// ----------------------------------------------------------------------------------------\n\n    template <typename potts_prob>\n    void impl_test_potts_model (\n        potts_prob& p\n    )\n    {\n        using namespace std;\n        double brute_force_score;\n        double graph_cut_score;\n\n        {\n            potts_prob temp(p);\n            brute_force_potts_model(temp);\n\n            for (unsigned long i = 0; i < temp.number_of_nodes(); ++i)\n            {\n                dlog << LTRACE << \"node \" << i << \": \"<< (int)temp.get_label(i);\n            }\n            brute_force_score = potts_model_score(temp);\n            dlog << LTRACE << \"brute force score: \"<< brute_force_score;\n        }\n        dlog << LTRACE << \"******************\";\n\n        {\n            potts_prob temp(p);\n            find_max_factor_graph_potts(temp);\n\n            for (unsigned long i = 0; i < temp.number_of_nodes(); ++i)\n            {\n                dlog << LTRACE << \"node \" << i << \": \"<< (int)temp.get_label(i);\n            }\n            graph_cut_score = potts_model_score(temp);\n            dlog << LTRACE << \"graph cut score: \"<< graph_cut_score;\n        }\n\n        DLIB_TEST_MSG(graph_cut_score == brute_force_score, std::abs(graph_cut_score - brute_force_score));\n\n        dlog << LTRACE << \"##################\";\n        dlog << LTRACE << \"##################\";\n        dlog << LTRACE << \"##################\";\n    }\n\n// ----------------------------------------------------------------------------------------\n// ----------------------------------------------------------------------------------------\n// ----------------------------------------------------------------------------------------\n//                                   BASIC MIN CUT STUFF\n// ----------------------------------------------------------------------------------------\n// ----------------------------------------------------------------------------------------\n// ----------------------------------------------------------------------------------------\n\n    template <typename directed_graph>\n    void brute_force_min_cut (\n        directed_graph& g,\n        unsigned long source,\n        unsigned long sink\n    )\n    {\n        typedef typename directed_graph::edge_type edge_weight_type;\n        const unsigned long num = (unsigned long)std::pow(2.0, (double)g.number_of_nodes());\n\n        std::vector<node_label> best_cut(g.number_of_nodes(),FREE_NODE);\n\n        edge_weight_type best_score = std::numeric_limits<edge_weight_type>::max();\n        for (unsigned long i = 0; i < num; ++i)\n        {\n            for (unsigned long j = 0; j < g.number_of_nodes(); ++j)\n            {\n                unsigned long T = (1)<<j;\n                T = (T&i);\n                if (T != 0)\n                    g.node(j).data = SINK_CUT;\n                else\n                    g.node(j).data = SOURCE_CUT;\n            }\n\n            // ignore cuts that don't label the source or sink node the way we want.\n            if (g.node(source).data != SOURCE_CUT ||\n                g.node(sink).data != SINK_CUT)\n                continue;\n\n            edge_weight_type score = graph_cut_score(g);\n            if (score < best_score)\n            {\n                best_score = score;\n                for (unsigned long j = 0; j < g.number_of_nodes(); ++j)\n                    best_cut[j] = g.node(j).data;\n            }\n        }\n\n        for (unsigned long j = 0; j < g.number_of_nodes(); ++j)\n            g.node(j).data =  best_cut[j];\n    }\n\n// ----------------------------------------------------------------------------------------\n\n    template <typename directed_graph>\n    void print_graph(\n        const directed_graph& g\n    )\n    {\n        using namespace std;\n        dlog << LTRACE << \"number of nodes: \"<< g.number_of_nodes();\n        for (unsigned long i = 0; i < g.number_of_nodes(); ++i)\n        {\n            for (unsigned long n = 0; n < g.node(i).number_of_children(); ++n)\n                dlog << LTRACE << i << \" -(\" << g.node(i).child_edge(n) << \")-> \" << g.node(i).child(n).index();\n        }\n    }\n\n    template <typename directed_graph>\n    void copy_edge_weights (\n        directed_graph& dest,\n        const directed_graph& src\n    )\n    {\n        for (unsigned long i = 0; i < src.number_of_nodes(); ++i)\n        {\n            for (unsigned long n = 0; n < src.node(i).number_of_children(); ++n)\n            {\n                dest.node(i).child_edge(n) = src.node(i).child_edge(n);\n            }\n        }\n    }\n\n// ----------------------------------------------------------------------------------------\n\n    template <typename graph_type>\n    void pick_random_source_and_sink (\n        dlib::rand& rnd,\n        const graph_type& g,\n        unsigned long& source,\n        unsigned long& sink\n    )\n    {\n        source = rnd.get_random_32bit_number()%g.number_of_nodes();\n        sink = rnd.get_random_32bit_number()%g.number_of_nodes();\n        while (sink == source)\n            sink = rnd.get_random_32bit_number()%g.number_of_nodes();\n    }\n\n// ----------------------------------------------------------------------------------------\n\n    template <typename dgraph_type>\n    void make_random_graph(\n        dlib::rand& rnd,\n        dgraph_type& g,\n        unsigned long& source,\n        unsigned long& sink\n    )\n    {\n        typedef typename dgraph_type::edge_type edge_weight_type;\n        g.clear();\n        const unsigned int num_nodes = rnd.get_random_32bit_number()%7 + 2;\n        g.set_number_of_nodes(num_nodes);\n\n        const unsigned int num_edges = static_cast<unsigned int>(num_nodes*(num_nodes-1)/2*rnd.get_random_double() + 0.5);\n\n        // add the right number of randomly selected edges\n        unsigned int count = 0;\n        while (count < num_edges)\n        {\n            unsigned long parent = rnd.get_random_32bit_number()%g.number_of_nodes();\n            unsigned long child = rnd.get_random_32bit_number()%g.number_of_nodes();\n            if (parent != child && g.has_edge(parent, child) == false)\n            {\n                ++count;\n                g.add_edge(parent, child);\n                edge(g, parent, child) = static_cast<edge_weight_type>(rnd.get_random_double()*50);\n\n                // have to have edges both ways\n                swap(parent, child);\n                g.add_edge(parent, child);\n                edge(g, parent, child) = static_cast<edge_weight_type>(rnd.get_random_double()*50);\n            }\n        }\n\n        pick_random_source_and_sink(rnd, g, source, sink);\n    }\n\n// ----------------------------------------------------------------------------------------\n\n    template <typename dgraph_type>\n    void make_random_chain_graph(\n        dlib::rand& rnd,\n        dgraph_type& g,\n        unsigned long& source,\n        unsigned long& sink\n    )\n    {\n        typedef typename dgraph_type::edge_type edge_weight_type;\n        g.clear();\n        const unsigned int num_nodes = rnd.get_random_32bit_number()%7 + 2;\n        g.set_number_of_nodes(num_nodes);\n\n        for (unsigned long i = 1; i < g.number_of_nodes(); ++i)\n        {\n            g.add_edge(i,i-1);\n            g.add_edge(i-1,i);\n            edge(g, i, i-1) = static_cast<edge_weight_type>(rnd.get_random_double()*50);\n            edge(g, i-1, i) = static_cast<edge_weight_type>(rnd.get_random_double()*50);\n        }\n\n        pick_random_source_and_sink(rnd, g, source, sink);\n    }\n\n// ----------------------------------------------------------------------------------------\n\n    template <typename dgraph_type>\n    void make_random_grid_graph(\n        dlib::rand& rnd,\n        dgraph_type& g,\n        unsigned long& source,\n        unsigned long& sink\n    )\n    /*!\n        ensures\n            - makes a grid graph like the kind used for potts models.\n    !*/\n    {\n        typedef typename dgraph_type::edge_type edge_weight_type;\n        g.clear();\n        const long nr = rnd.get_random_32bit_number()%2 + 2;\n        const long nc = rnd.get_random_32bit_number()%2 + 2;\n        g.set_number_of_nodes(nr*nc+2);\n\n        const rectangle rect(0,0,nc-1,nr-1);\n        for (long r = 0; r < nr; ++r)\n        {\n            for (long c = 0; c < nc; ++c)\n            {\n                const point p(c,r);\n                const unsigned long i = p.y()*nc + p.x();\n\n                const point n2(c-1,r);\n                if (rect.contains(n2))\n                {\n                    const unsigned long j = n2.y()*nc + n2.x();\n                    g.add_edge(i,j);\n                    g.add_edge(j,i);\n                    edge(g,i,j) = static_cast<edge_weight_type>(rnd.get_random_double()*50);\n                    edge(g,j,i) = static_cast<edge_weight_type>(rnd.get_random_double()*50);\n                }\n\n                const point n4(c,r-1);\n                if (rect.contains(n4))\n                {\n                    const unsigned long j = n4.y()*nc + n4.x();\n                    g.add_edge(i,j);\n                    g.add_edge(j,i);\n                    edge(g,i,j) = static_cast<edge_weight_type>(rnd.get_random_double()*50);\n                    edge(g,j,i) = static_cast<edge_weight_type>(rnd.get_random_double()*50);\n                }\n            }\n        }\n\n        // use the last two nodes as source and sink.  Also connect them to all the other nodes.\n        source = g.number_of_nodes()-1;\n        sink = g.number_of_nodes()-2;\n        for (unsigned long i = 0; i < g.number_of_nodes()-2; ++i)\n        {\n            g.add_edge(i,source);\n            g.add_edge(source,i);\n            g.add_edge(i,sink);\n            g.add_edge(sink,i);\n\n            edge(g,i,source) = static_cast<edge_weight_type>(rnd.get_random_double()*50);\n            edge(g,source,i) = static_cast<edge_weight_type>(rnd.get_random_double()*50);\n            edge(g,i,sink) = static_cast<edge_weight_type>(rnd.get_random_double()*50);\n            edge(g,sink,i) = static_cast<edge_weight_type>(rnd.get_random_double()*50);\n        }\n    }\n\n// ----------------------------------------------------------------------------------------\n\n    template <typename min_cut, typename dgraph_type>\n    void run_test_on_graphs (\n        const min_cut& mc,\n        dgraph_type& g1,\n        dgraph_type& g2,\n        unsigned long source,\n        unsigned long sink\n    )\n    {\n        typedef typename dgraph_type::edge_type edge_weight_type;\n        using namespace std;\n\n\n        dlog << LTRACE << \"number of nodes: \"<< g1.number_of_nodes();\n        dlog << LTRACE << \"is graph connected: \"<< graph_is_connected(g1);\n        dlog << LTRACE << \"has self loops:     \"<< graph_contains_length_one_cycle(g1);\n        dlog << LTRACE << \"SOURCE_CUT: \" << source;\n        dlog << LTRACE << \"SINK_CUT:   \" << sink;\n        mc(g1, source, sink);\n        brute_force_min_cut(g2, source, sink);\n\n        print_graph(g1);\n\n        // make sure the flow residuals are 0 at the cut locations\n        for (unsigned long i = 0; i < g1.number_of_nodes(); ++i)\n        {\n            for (unsigned long j = 0; j < g1.node(i).number_of_children(); ++j)\n            {\n                if ((g1.node(i).data == SOURCE_CUT && g1.node(i).child(j).data != SOURCE_CUT) ||\n                    (g1.node(i).data != SINK_CUT && g1.node(i).child(j).data == SINK_CUT)\n                    )\n                {\n                    DLIB_TEST_MSG(g1.node(i).child_edge(j) == 0, g1.node(i).child_edge(j));\n                }\n            }\n        }\n\n        // copy the edge weights from g2 back to g1 so we can compute cut scores\n        copy_edge_weights(g1, g2);\n\n        DLIB_TEST(g1.number_of_nodes() == g2.number_of_nodes());\n        for (unsigned long i = 0; i < g1.number_of_nodes(); ++i)\n        {\n            dlog << LTRACE << \"node \" << i << \": \" << (int)g1.node(i).data << \", \" << (int)g2.node(i).data;\n            if (g1.node(i).data != g2.node(i).data)\n            {\n                edge_weight_type cut_score = graph_cut_score(g1);\n                edge_weight_type brute_force_score = graph_cut_score(g2);\n                dlog << LTRACE << \"graph cut score: \"<< cut_score;\n                dlog << LTRACE << \"brute force score: \"<< brute_force_score;\n\n                if (brute_force_score != cut_score)\n                    print_graph(g1);\n                DLIB_TEST_MSG(brute_force_score == cut_score,std::abs(brute_force_score-cut_score));\n            }\n        }\n\n    }\n\n// ----------------------------------------------------------------------------------------\n\n    template <typename min_cut, typename edge_weight_type>\n    void test_graph_cuts(dlib::rand& rnd)\n    {\n        typedef typename dlib::directed_graph<node_label, edge_weight_type>::kernel_1a_c dgraph_type;\n        // we will create two identical graphs.\n        dgraph_type g1, g2;\n        min_cut mc;\n\n        unsigned long source, sink;\n\n        dlib::rand rnd_copy(rnd);\n        make_random_graph(rnd,g1, source, sink);\n        make_random_graph(rnd_copy,g2, source, sink);\n        run_test_on_graphs(mc, g1, g2, source, sink);\n\n        rnd_copy = rnd;\n        make_random_grid_graph(rnd,g1, source, sink);\n        make_random_grid_graph(rnd_copy,g2, source, sink);\n        run_test_on_graphs(mc, g1, g2, source, sink);\n\n        rnd_copy = rnd;\n        make_random_chain_graph(rnd,g1, source, sink);\n        make_random_chain_graph(rnd_copy,g2, source, sink);\n        run_test_on_graphs(mc, g1, g2, source, sink);\n\n    }\n\n// ----------------------------------------------------------------------------------------\n\n    class test_potts_grid_problem\n    {\n    public:\n        test_potts_grid_problem(int seed_) :seed(seed_){}\n        int seed;\n\n        long nr() const { return 3;}\n        long nc() const { return 3;}\n\n        typedef double value_type;\n\n        value_type factor_value(unsigned long idx) const\n        {\n            // Copy idx into a char buffer to avoid warnings about violation of strict aliasing \n            // rules when murmur_hash3() gets inlined into this function.\n            char buf[sizeof(idx)];\n            memcpy(buf,&idx,sizeof(idx));\n            // now hash the buffer rather than idx.\n            return ((double)murmur_hash3(buf, sizeof(buf), seed) - std::numeric_limits<uint32>::max()/2.0)/1000.0;\n        }\n\n        value_type factor_value_disagreement(unsigned long idx1, unsigned long idx2) const\n        {\n            return std::abs(factor_value(idx1+idx2)/10.0);\n        }\n    };\n\n// ----------------------------------------------------------------------------------------\n\n    template <typename prob_type>\n    void brute_force_potts_grid_problem(\n        const prob_type& prob,\n        array2d<unsigned char>& labels\n    )\n    {\n        const unsigned long num = (unsigned long)std::pow(2.0, (double)prob.nr()*prob.nc());\n\n        array2d<unsigned char> temp(prob.nr(), prob.nc());\n        unsigned char* data = &temp[0][0];\n\n        double best_score = -std::numeric_limits<double>::infinity();\n        for (unsigned long i = 0; i < num; ++i)\n        {\n            for (unsigned long j = 0; j < temp.size(); ++j)\n            {\n                unsigned long T = (1)<<j;\n                T = (T&i);\n                if (T != 0)\n                    *(data + j) = SINK_CUT;\n                else\n                    *(data + j) = SOURCE_CUT;\n            }\n\n\n            double score = potts_model_score(prob, temp);\n            if (score > best_score)\n            {\n                best_score = score;\n                assign_image(labels, temp);\n            }\n        }\n    }\n\n    void test_inf()\n    {\n        graph<double,double>::kernel_1a_c g;\n        g.set_number_of_nodes(4);\n        g.add_edge(0,1);\n        g.add_edge(1,2);\n        g.add_edge(2,3);\n        g.add_edge(3,0);\n\n        g.node(0).data = std::numeric_limits<double>::infinity();\n        g.node(1).data = -std::numeric_limits<double>::infinity();\n        g.node(2).data = std::numeric_limits<double>::infinity();\n        g.node(3).data = -std::numeric_limits<double>::infinity();\n\n        edge(g,0,1) = 1;\n        edge(g,1,2) = 1;\n        edge(g,2,3) = 1;\n        edge(g,3,0) = 1;\n\n        std::vector<node_label> labels;\n        find_max_factor_graph_potts(g, labels);\n\n        DLIB_TEST(labels[0] != 0);\n        DLIB_TEST(labels[1] == 0);\n        DLIB_TEST(labels[2] != 0);\n        DLIB_TEST(labels[3] == 0);\n\n        // --------------------------\n\n        g.node(0).data = std::numeric_limits<double>::infinity();\n        g.node(1).data = 0;\n        g.node(2).data = 0;\n        g.node(3).data = -3;\n\n        edge(g,0,1) = 1;\n        edge(g,1,2) = 1;\n        edge(g,2,3) = 1;\n        edge(g,3,0) = 1;\n\n        find_max_factor_graph_potts(g, labels);\n\n        DLIB_TEST(labels[0] != 0);\n        DLIB_TEST(labels[1] != 0);\n        DLIB_TEST(labels[2] != 0);\n        DLIB_TEST(labels[3] == 0);\n\n        // --------------------------\n\n        g.node(0).data = std::numeric_limits<double>::infinity();\n        g.node(1).data = 0;\n        g.node(2).data = 0;\n        g.node(3).data = -0.1;\n\n        edge(g,0,1) = 1;\n        edge(g,1,2) = 1;\n        edge(g,2,3) = 1;\n        edge(g,3,0) = 1;\n\n        find_max_factor_graph_potts(g, labels);\n\n        DLIB_TEST(labels[0] != 0);\n        DLIB_TEST(labels[1] != 0);\n        DLIB_TEST(labels[2] != 0);\n        DLIB_TEST(labels[3] != 0);\n\n        // --------------------------\n\n        g.node(0).data = std::numeric_limits<double>::infinity();\n        g.node(1).data = 0;\n        g.node(2).data = 0;\n        g.node(3).data = -0.1;\n\n        edge(g,0,1) = 1;\n        edge(g,1,2) = 1;\n        edge(g,2,3) = 0;\n        edge(g,3,0) = 0;\n\n        find_max_factor_graph_potts(g, labels);\n\n        DLIB_TEST(labels[0] != 0);\n        DLIB_TEST(labels[1] != 0);\n        DLIB_TEST(labels[2] != 0);\n        DLIB_TEST(labels[3] == 0);\n\n        // --------------------------\n\n        g.node(0).data = -std::numeric_limits<double>::infinity();\n        g.node(1).data = 0;\n        g.node(2).data = 0;\n        g.node(3).data = 0.1;\n\n        edge(g,0,1) = 1;\n        edge(g,1,2) = 1;\n        edge(g,2,3) = 0;\n        edge(g,3,0) = 0;\n\n        find_max_factor_graph_potts(g, labels);\n\n        DLIB_TEST(labels[0] == 0);\n        DLIB_TEST(labels[1] == 0);\n        DLIB_TEST(labels[2] == 0);\n        DLIB_TEST(labels[3] != 0);\n\n        // --------------------------\n\n        g.node(0).data = -std::numeric_limits<double>::infinity();\n        g.node(1).data = std::numeric_limits<double>::infinity();\n        g.node(2).data = 0;\n        g.node(3).data = 0.1;\n\n        edge(g,0,1) = 1;\n        edge(g,1,2) = 1;\n        edge(g,2,3) = 0;\n        edge(g,3,0) = 0;\n\n        find_max_factor_graph_potts(g, labels);\n\n        DLIB_TEST(labels[0] == 0);\n        DLIB_TEST(labels[1] != 0);\n        DLIB_TEST(labels[2] != 0);\n        DLIB_TEST(labels[3] != 0);\n\n        // --------------------------\n\n        g.node(0).data = -10;\n        g.node(1).data = std::numeric_limits<double>::infinity();\n        g.node(2).data = 0;\n        g.node(3).data = 0.1;\n\n        edge(g,0,1) = std::numeric_limits<double>::infinity();\n        edge(g,1,2) = std::numeric_limits<double>::infinity();\n        edge(g,2,3) = std::numeric_limits<double>::infinity();\n        edge(g,3,0) = std::numeric_limits<double>::infinity();\n\n        find_max_factor_graph_potts(g, labels);\n\n        DLIB_TEST(labels[0] != 0);\n        DLIB_TEST(labels[1] != 0);\n        DLIB_TEST(labels[2] != 0);\n        DLIB_TEST(labels[3] != 0);\n\n        // --------------------------\n\n        g.node(0).data = 10;\n        g.node(1).data = -std::numeric_limits<double>::infinity();\n        g.node(2).data = 20.05;\n        g.node(3).data = -0.1;\n\n        edge(g,0,1) = std::numeric_limits<double>::infinity();\n        edge(g,1,2) = 10;\n        edge(g,2,3) = std::numeric_limits<double>::infinity();\n        edge(g,3,0) = 10;\n\n        find_max_factor_graph_potts(g, labels);\n\n        DLIB_TEST(labels[0] == 0);\n        DLIB_TEST(labels[1] == 0);\n        DLIB_TEST(labels[2] == 0);\n        DLIB_TEST(labels[3] == 0);\n\n        // --------------------------\n\n        g.node(0).data = 10;\n        g.node(1).data = -std::numeric_limits<double>::infinity();\n        g.node(2).data = 20.2;\n        g.node(3).data = -0.1;\n\n        edge(g,0,1) = std::numeric_limits<double>::infinity();\n        edge(g,1,2) = 10;\n        edge(g,2,3) = std::numeric_limits<double>::infinity();\n        edge(g,3,0) = 10;\n\n        find_max_factor_graph_potts(g, labels);\n\n        DLIB_TEST(labels[0] == 0);\n        DLIB_TEST(labels[1] == 0);\n        DLIB_TEST(labels[2] != 0);\n        DLIB_TEST(labels[3] != 0);\n    }\n\n    struct potts_pair_image_model \n    {\n        typedef double value_type;\n\n        template <typename pixel_type1, typename pixel_type2>\n        value_type factor_value (\n            const pixel_type1& ,\n            const pixel_type2& v2 \n        ) const\n        {\n            return v2;\n        }\n\n        template <typename pixel_type>\n        value_type factor_value_disagreement (\n            const pixel_type& v1,\n            const pixel_type& v2 \n        ) const\n        {\n            if (v1 == v2)\n                return 10;\n            else\n                return 0;\n        }\n    };\n\n    void test_potts_pair_grid()\n    {\n        array2d<int> img1(40,40);\n        array2d<double> img2(40,40);\n\n        assign_all_pixels(img1, -1);\n        assign_all_pixels(img2, -1);\n\n        img1[4][4] = 1000;\n\n        img2[4][3] = 1;\n        img2[4][4] = 1;\n        img2[4][5] = 1;\n        img2[3][3] = 1;\n        img2[3][4] = 1;\n        img2[3][5] = 1;\n        img2[5][3] = 1;\n        img2[5][4] = 1;\n        img2[5][5] = 1;\n\n        array2d<unsigned char> labels;\n        find_max_factor_graph_potts(make_potts_grid_problem(potts_pair_image_model(),img2,img1), labels);\n\n        dlog << LINFO << \"num true labels: \" << sum(matrix_cast<int>(mat(labels)!=0));\n        DLIB_TEST(sum(matrix_cast<int>(mat(labels)!=0)) == 9);\n        DLIB_TEST(sum(matrix_cast<int>(mat(labels)==0)) == (int)img1.size()-9);\n\n        DLIB_TEST(labels[4][3]);\n        DLIB_TEST(labels[4][4]);\n        DLIB_TEST(labels[4][5]);\n        DLIB_TEST(labels[3][3]);\n        DLIB_TEST(labels[3][4]);\n        DLIB_TEST(labels[3][5]);\n        DLIB_TEST(labels[5][3]);\n        DLIB_TEST(labels[5][4]);\n        DLIB_TEST(labels[5][5]);\n    }\n\n// ----------------------------------------------------------------------------------------\n// ----------------------------------------------------------------------------------------\n// ----------------------------------------------------------------------------------------\n// ----------------------------------------------------------------------------------------\n\n    class graph_cuts_tester : public tester\n    {\n    public:\n        graph_cuts_tester (\n        ) :\n            tester (\"test_graph_cuts\",\n                    \"Runs tests on the graph cuts tools.\")\n        {}\n\n        dlib::rand rnd;\n\n        void perform_test (\n        )\n        {\n            test_potts_pair_grid();\n            test_inf();\n\n            for (int i = 0; i < 500; ++i)\n            {\n                array2d<unsigned char> labels, brute_labels;\n                test_potts_grid_problem prob(i);\n                find_max_factor_graph_potts(prob, labels);\n                brute_force_potts_grid_problem(prob, brute_labels);\n\n                DLIB_TEST(labels.nr() == brute_labels.nr());\n                DLIB_TEST(labels.nc() == brute_labels.nc());\n                for (long r = 0; r < labels.nr(); ++r)\n                {\n                    for (long c = 0; c < labels.nc(); ++c)\n                    {\n                        bool normal = (labels[r][c] != 0);\n                        bool brute = (brute_labels[r][c] != 0);\n                        DLIB_TEST(normal == brute);\n                    }\n                }\n            }\n\n            for (int i = 0; i < 1000; ++i)\n            {\n                print_spinner();\n                dlog << LTRACE << \"test_grpah_cuts<short> iter: \" << i;\n                test_graph_cuts<min_cut,short>(rnd);\n                print_spinner();\n                dlog << LTRACE << \"test_grpah_cuts<double> iter: \" << i;\n                test_graph_cuts<min_cut,double>(rnd);\n            }\n\n\n            for (int k = 0; k < 300; ++k)\n            {\n                dlog << LTRACE << \"image_potts_problem iter \" << k;\n                print_spinner();\n                image_potts_problem p(3,3, rnd);\n                impl_test_potts_model(p);\n            }\n            for (int k = 0; k < 300; ++k)\n            {\n                dlog << LTRACE << \"dense_potts_problem iter \" << k;\n                print_spinner();\n                dense_potts_problem p(6, rnd);\n                impl_test_potts_model(p);\n            }\n\n            for (int k = 0; k < 300; ++k)\n            {\n                dlog << LTRACE << \"dense_potts_problem iter \" << k;\n                print_spinner();\n                test_graph_potts_model(rnd);\n            }\n        }\n    } a;\n\n\n}\n\n\n\n\n", "meta": {"hexsha": "edf66909a656a387ec278bd1863a27fb47727b2e", "size": 38005, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/dlib/test/graph_cuts.cpp", "max_stars_repo_name": "markovchainz/cppagent", "max_stars_repo_head_hexsha": "97314ec43786a90697ca7fda15db13f2973aee3e", "max_stars_repo_licenses": ["Apache-2.0"], "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": "lib/dlib/test/graph_cuts.cpp", "max_issues_repo_name": "markovchainz/cppagent", "max_issues_repo_head_hexsha": "97314ec43786a90697ca7fda15db13f2973aee3e", "max_issues_repo_licenses": ["Apache-2.0"], "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": "lib/dlib/test/graph_cuts.cpp", "max_forks_repo_name": "markovchainz/cppagent", "max_forks_repo_head_hexsha": "97314ec43786a90697ca7fda15db13f2973aee3e", "max_forks_repo_licenses": ["Apache-2.0"], "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": 31.2027914614, "max_line_length": 122, "alphanum_fraction": 0.4694382318, "num_tokens": 8935, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746407, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4604837297302713}}
{"text": "//\n// Created by christoph on 08.09.18.\n//\n\n#include <Utils/File/Logfile.hpp>\n#include <Utils/Convert.hpp>\n#include <Math/Math.hpp>\n#include <Graphics/Shader/ShaderManager.hpp>\n#include <Graphics/Renderer.hpp>\n\n#include <chrono>\n#include <iostream>\n#include <boost/algorithm/string.hpp>\n#include <boost/algorithm/string/split.hpp>\n#include <GL/glew.h>\n\n#include \"MeshSerializer.hpp\"\n#include \"TrajectoryFile.hpp\"\n#include \"TrajectoryLoader.hpp\"\n\nusing namespace sgl;\n\nstatic std::vector<glm::vec2> circlePoints2D;\n\nvoid getPointsOnCircle(std::vector<glm::vec2> &points, const glm::vec2 &center, float radius, int numSegments)\n{\n    float theta = 2.0f * 3.1415926f / (float)numSegments;\n    float tangetialFactor = tan(theta); // opposite / adjacent\n    float radialFactor = cos(theta); // adjacent / hypotenuse\n    glm::vec2 position(radius, 0.0f);\n\n    for (int i = 0; i < numSegments; i++) {\n        points.push_back(position + center);\n\n        // Add the tangent vector and correct the position using the radial factor.\n        glm::vec2 tangent(-position.y, position.x);\n        position += tangetialFactor * tangent;\n        position *= radialFactor;\n    }\n}\n\n\nvoid initializeCircleData(int numSegments, float radius)\n{\n    circlePoints2D.clear();\n    getPointsOnCircle(circlePoints2D, glm::vec2(0.0f, 0.0f), radius, numSegments);\n}\n\n/**\n * Returns a oriented and shifted copy of a 2D circle in 3D space.\n * The number\n * @param vertices The list to append the circle points to.\n * @param normals Normal array of the tube to append normals to.\n * @param center The center of the circle in 3D space.\n * @param normal The normal orthogonal to the circle plane.\n * @param lastTangent The tangent of the last circle.\n */\nvoid insertOrientedCirclePoints(std::vector<glm::vec3> &vertices, std::vector<glm::vec3> &normals,\n        const glm::vec3 &center, const glm::vec3 &normal, glm::vec3 &lastTangent)\n{\n    if (circlePoints2D.size() == 0) {\n        std::cerr << \"Fatal error: circlePoints2D.size() == 0\" << std::endl;\n        exit(1);\n    }\n\n    glm::vec3 tangent, binormal;\n    glm::vec3 helperAxis = lastTangent;\n    //if (std::abs(glm::dot(helperAxis, normal)) > 0.9f) {\n    if (glm::length(glm::cross(helperAxis, normal)) < 0.01f) {\n        // If normal == helperAxis\n        helperAxis = glm::vec3(0.0f, 1.0f, 0.0f);\n    }\n    tangent = glm::normalize(helperAxis - normal * glm::dot(helperAxis, normal)); // Gram-Schmidt\n    //glm::vec3 tangent = glm::normalize(glm::cross(normal, helperAxis));\n    binormal = glm::normalize(glm::cross(normal, tangent));\n    lastTangent = tangent;\n\n\n    // In column-major order\n    glm::mat4 tangentFrameMatrix(\n            tangent.x,  tangent.y,  tangent.z,  0.0f,\n            binormal.x, binormal.y, binormal.z, 0.0f,\n            normal.x,   normal.y,   normal.z,   0.0f,\n            0.0f,       0.0f,       0.0f,       1.0f);\n    glm::mat4 translation(\n            1.0f,     0.0f,   .0f,     0.0f,\n            0.0f,     1.0f,     0.0f,     0.0f,\n            0.0f,     0.0f,     1.0f,     0.0f,\n            center.x, center.y, center.z, 1.0f);\n    glm::mat4 transform = translation * tangentFrameMatrix;\n\n    for (const glm::vec2 &circlePoint : circlePoints2D) {\n        glm::vec4 transformedPoint = transform * glm::vec4(circlePoint.x, circlePoint.y, 0.0f, 1.0f);\n        vertices.push_back(glm::vec3(transformedPoint.x, transformedPoint.y, transformedPoint.z));\n        glm::vec3 normal = glm::vec3(transformedPoint.x, transformedPoint.y, transformedPoint.z) - center;\n        normal = glm::normalize(normal);\n        normals.push_back(normal);\n    }\n}\n\n\nstruct TubeNode\n{\n    /// Center vertex position\n    glm::vec3 center;\n\n    /// Tangent pointing in direction of next node (or negative direction of last node for the final node in the list).\n    glm::vec3 tangent;\n\n    /// Circle points (circle with center of tube node, in plane with normal vector of tube node)\n    std::vector<glm::vec3> circleVertices;\n\n    std::vector<uint32_t> circleIndices;\n};\n\n/**\n * @param pathLineCenters: The (input) path line points to create a tube from.\n * @param pathLineAttributes: The (input) path line point vertex attributes (belonging to pathLineCenters).\n * @param vertices: The (output) vertex points, which are a set of oriented circles around the centers (see above).\n * @param indices: The (output) indices specifying how tube triangles are built from the circle vertices.\n */\ntemplate<typename T>\nvoid createTubeRenderData(const std::vector<glm::vec3> &pathLineCenters,\n                          const std::vector<T> &pathLineAttributes,\n                          std::vector<glm::vec3> &vertices,\n                          std::vector<glm::vec3> &normals,\n                          std::vector<T> &vertexAttributes,\n                          std::vector<uint32_t> &indices)\n{\n    int n = (int)pathLineCenters.size();\n    if (n < 2) {\n        sgl::Logfile::get()->writeError(\"Error in createTube: n < 2\");\n        return;\n    }\n\n    /// Circle points (circle with center of tube node, in plane with normal vector of tube node)\n    vertices.reserve(n*circlePoints2D.size());\n    normals.reserve(n*circlePoints2D.size());\n    vertexAttributes.reserve(n*circlePoints2D.size());\n    indices.reserve((n-1)*circlePoints2D.size()*6);\n\n    std::vector<TubeNode> tubeNodes;\n    tubeNodes.reserve(n);\n    int numVertexPts = 0;\n\n    // Turbulence dataset: Remove fixed point whirls\n    glm::vec3 diffFirstLast = pathLineCenters.front() - pathLineCenters.back();\n    if (glm::length(diffFirstLast) < 0.01f) {\n        return;\n    }\n\n    // First, create a list of tube nodes\n    glm::vec3 lastNormal = glm::vec3(1.0f, 0.0f, 0.0f);\n    for (int i = 0; i < n; i++) {\n        glm::vec3 center = pathLineCenters.at(i);\n\n        // Remove invalid line points (used in many scientific datasets to indicate invalid lines).\n        const float MAX_VAL = 1e10;\n        if (std::fabs(center.x) > MAX_VAL || std::fabs(center.y) > MAX_VAL || std::fabs(center.z) > MAX_VAL) {\n            continue;\n        }\n\n        glm::vec3 tangent;\n        if (i == 0) {\n            // First node\n            tangent = pathLineCenters.at(i+1) - pathLineCenters.at(i);\n        } else if (i == n-1) {\n            // Last node\n            tangent = pathLineCenters.at(i) - pathLineCenters.at(i-1);\n        } else {\n            // Node with two neighbors - use both normals\n            tangent = pathLineCenters.at(i+1) - pathLineCenters.at(i);\n            //normal += pathLineCenters.at(i) - pathLineCenters.at(i-1);\n        }\n\n        if (glm::length(tangent) < 0.0001f) {\n            // In case the two vertices are almost identical, just skip this path line segment\n            continue;\n        }\n\n        TubeNode node;\n        node.center = pathLineCenters.at(i);\n        node.tangent = glm::normalize(tangent);\n        insertOrientedCirclePoints(vertices, normals, node.center, node.tangent, lastNormal);\n        node.circleIndices.reserve(circlePoints2D.size());\n        for (int j = 0; j < circlePoints2D.size(); j++) {\n            node.circleIndices.push_back(j + numVertexPts*circlePoints2D.size());\n            if (pathLineAttributes.size() > 0) {\n                vertexAttributes.push_back(pathLineAttributes.at(i));\n            }\n        }\n        tubeNodes.push_back(node);\n        numVertexPts++;\n    }\n\n\n    // Create tube triangles/indices for the vertex data\n    /*for (int i = 0; i < numVertexPts-1; i++) {\n        std::vector<uint32_t> &circleIndicesCurrent = tubeNodes.at(i).circleIndices;\n        std::vector<uint32_t> &circleIndicesNext = tubeNodes.at(i+1).circleIndices;\n        for (int j = 0; j < circlePoints2D.size(); j++) {\n            // Build two CCW triangles (one quad) for each side\n            // Triangle 1\n            indices.push_back(circleIndicesCurrent.at(j));\n            indices.push_back(circleIndicesCurrent.at((j+1)%circlePoints2D.size()));\n            indices.push_back(circleIndicesNext.at((j+1)%circlePoints2D.size()));\n\n            // Triangle 2\n            indices.push_back(circleIndicesCurrent.at(j));\n            indices.push_back(circleIndicesNext.at((j+1)%circlePoints2D.size()));\n            indices.push_back(circleIndicesNext.at(j));\n        }\n    }*/\n    for (int i = 0; i < numVertexPts-1; i++) {\n        for (int j = 0; j < circlePoints2D.size(); j++) {\n            // Build two CCW triangles (one quad) for each side\n            // Triangle 1\n            indices.push_back(j + i*circlePoints2D.size());\n            indices.push_back((j+1)%circlePoints2D.size() + i*circlePoints2D.size());\n            indices.push_back((j+1)%circlePoints2D.size() + (i+1)*circlePoints2D.size());\n\n            // Triangle 2\n            indices.push_back(j + i*circlePoints2D.size());\n            indices.push_back((j+1)%circlePoints2D.size() + (i+1)*circlePoints2D.size());\n            indices.push_back(j + (i+1)*circlePoints2D.size());\n        }\n    }\n\n    // Only one vertex left -> Output nothing (tube consisting only of one point)\n    if (numVertexPts <= 1) {\n        vertices.clear();\n        normals.clear();\n        vertexAttributes.clear();\n    }\n}\nvoid createTubeRenderData(const std::vector<glm::vec3> &pathLineCenters,\n                          std::vector<std::vector<float>> &importanceCriteriaLine,\n                          std::vector<glm::vec3> &vertices,\n                          std::vector<glm::vec3> &normals,\n                          std::vector<std::vector<float>> &importanceCriteriaVertex,\n                          std::vector<uint32_t> &indices)\n{\n    int n = (int)pathLineCenters.size();\n    int numImportanceCriteria = (int)importanceCriteriaLine.size();\n    if (n < 2) {\n        sgl::Logfile::get()->writeError(\"Error in createTube: n < 2\");\n        return;\n    }\n\n    /// Circle points (circle with center of tube node, in plane with normal vector of tube node)\n    vertices.reserve(n*circlePoints2D.size());\n    normals.reserve(n*circlePoints2D.size());\n    importanceCriteriaVertex.resize(numImportanceCriteria);\n    for (int i = 0; i < numImportanceCriteria; i++) {\n        importanceCriteriaVertex.at(i).reserve(n);\n    }\n    indices.reserve((n-1)*circlePoints2D.size()*6);\n\n    // List of all line nodes (points with data)\n    std::vector<TubeNode> tubeNodes;\n    tubeNodes.reserve(n);\n    int numVertexPts = 0;\n\n    // First, create a list of tube nodes\n    glm::vec3 lastNormal = glm::vec3(1.0f, 0.0f, 0.0f);\n    for (int i = 0; i < n; i++) {\n        glm::vec3 center = pathLineCenters.at(i);\n\n        // Remove invalid line points (used in many scientific datasets to indicate invalid lines).\n        const float MAX_VAL = 1e10;\n        if (std::fabs(center.x) > MAX_VAL || std::fabs(center.y) > MAX_VAL || std::fabs(center.z) > MAX_VAL) {\n            continue;\n        }\n\n        glm::vec3 tangent;\n        if (i == 0) {\n            // First node\n            tangent = pathLineCenters.at(i+1) - pathLineCenters.at(i);\n        } else if (i == n-1) {\n            // Last node\n            tangent = pathLineCenters.at(i) - pathLineCenters.at(i-1);\n        } else {\n            // Node with two neighbors - use both normals\n            tangent = pathLineCenters.at(i+1) - pathLineCenters.at(i);\n            //normal += pathLineCenters.at(i) - pathLineCenters.at(i-1);\n        }\n\n        float lineSegmentLength = glm::length(tangent);\n\n        if (lineSegmentLength < 0.0001f) {\n            //normal = glm::vec3(1.0f, 0.0f, 0.0f);\n            // In case the two vertices are almost identical, just skip this path line segment\n            continue;\n        }\n        tangent = glm::normalize(tangent);\n\n        TubeNode node;\n        node.center = pathLineCenters.at(i);\n        node.tangent = tangent;\n        insertOrientedCirclePoints(vertices, normals, node.center, node.tangent, lastNormal);\n        node.circleIndices.reserve(circlePoints2D.size());\n        for (int j = 0; j < circlePoints2D.size(); j++) {\n            node.circleIndices.push_back(j + numVertexPts*circlePoints2D.size());\n            for (int k = 0; k < numImportanceCriteria; k++) {\n                importanceCriteriaVertex.at(k).push_back(importanceCriteriaLine.at(k).at(i));\n            }\n        }\n        tubeNodes.push_back(node);\n        numVertexPts++;\n    }\n\n\n    // Create tube triangles/indices for the vertex data\n    /*for (int i = 0; i < numVertexPts-1; i++) {\n        std::vector<uint32_t> &circleIndicesCurrent = tubeNodes.at(i).circleIndices;\n        std::vector<uint32_t> &circleIndicesNext = tubeNodes.at(i+1).circleIndices;\n        for (int j = 0; j < circlePoints2D.size(); j++) {\n            // Build two CCW triangles (one quad) for each side\n            // Triangle 1\n            indices.push_back(circleIndicesCurrent.at(j));\n            indices.push_back(circleIndicesCurrent.at((j+1)%circlePoints2D.size()));\n            indices.push_back(circleIndicesNext.at((j+1)%circlePoints2D.size()));\n\n            // Triangle 2\n            indices.push_back(circleIndicesCurrent.at(j));\n            indices.push_back(circleIndicesNext.at((j+1)%circlePoints2D.size()));\n            indices.push_back(circleIndicesNext.at(j));\n        }\n    }*/\n    // Create tube triangles/indices for the vertex data\n    for (int i = 0; i < numVertexPts-1; i++) {\n        for (int j = 0; j < circlePoints2D.size(); j++) {\n            // Build two CCW triangles (one quad) for each side\n            // Triangle 1\n            indices.push_back(j + i*circlePoints2D.size());\n            indices.push_back((j+1)%circlePoints2D.size() + i*circlePoints2D.size());\n            indices.push_back((j+1)%circlePoints2D.size() + (i+1)*circlePoints2D.size());\n\n            // Triangle 2\n            indices.push_back(j + i*circlePoints2D.size());\n            indices.push_back((j+1)%circlePoints2D.size() + (i+1)*circlePoints2D.size());\n            indices.push_back(j + (i+1)*circlePoints2D.size());\n        }\n    }\n\n    // Only one vertex left -> Output nothing (tube consisting only of one point)\n    if (numVertexPts <= 1) {\n        vertices.clear();\n        normals.clear();\n        importanceCriteriaVertex.clear();\n    }\n}\n\ntemplate\nvoid createTubeRenderData<uint32_t>(const std::vector<glm::vec3> &pathLineCenters,\n                                    const std::vector<uint32_t> &pathLineAttributes,\n                                    std::vector<glm::vec3> &vertices,\n                                    std::vector<glm::vec3> &normals,\n                                    std::vector<uint32_t> &vertexAttributes,\n                                    std::vector<uint32_t> &indices);\n\n\n\n\n\nvoid convertTrajectoryDataToBinaryTriangleMesh(\n        TrajectoryType trajectoryType,\n        const std::string &trajectoriesFilename,\n        const std::string &binaryFilename,\n        float lineRadius)\n{\n    auto start = std::chrono::system_clock::now();\n\n    if (trajectoryType == TRAJECTORY_TYPE_RINGS) {\n        initializeCircleData(3, lineRadius);\n    } else if (trajectoryType == TRAJECTORY_TYPE_ANEURYSM) {\n        initializeCircleData(3, lineRadius);\n    } else {\n        initializeCircleData(3, lineRadius);\n    }\n\n    BinaryMesh binaryMesh;\n    binaryMesh.submeshes.push_back(BinarySubMesh());\n    BinarySubMesh &submesh = binaryMesh.submeshes.front();\n    submesh.vertexMode = VERTEX_MODE_TRIANGLES;\n\n    std::vector<glm::vec3> globalVertexPositions;\n    std::vector<glm::vec3> globalNormals;\n    std::vector<std::vector<float>> globalImportanceCriteria;\n    std::vector<uint32_t> globalIndices;\n\n    uint32_t numLines = 0;\n    uint32_t numLineSegments = 0;\n\n\n    Trajectories trajectories = loadTrajectoriesFromFile(trajectoriesFilename, trajectoryType);\n\n    for (size_t i = 0; i < trajectories.size(); i++) {\n        Trajectory &trajectory = trajectories.at(i);\n\n        numLines++;\n        numLineSegments += trajectory.positions.size() - 1;\n\n        // Create tube render data\n        std::vector<glm::vec3> localVertices;\n        std::vector<std::vector<float>> importanceCriteriaVertex;\n        std::vector<glm::vec3> localNormals;\n        std::vector<uint32_t> localIndices;\n        createTubeRenderData(trajectory.positions, trajectory.attributes, localVertices, localNormals,\n                             importanceCriteriaVertex, localIndices);\n\n        // Local -> global\n        if (localVertices.size() > 0) {\n            for (size_t i = 0; i < localIndices.size(); i++) {\n                globalIndices.push_back(localIndices.at(i) + globalVertexPositions.size());\n            }\n            globalVertexPositions.insert(globalVertexPositions.end(), localVertices.begin(), localVertices.end());\n            globalNormals.insert(globalNormals.end(), localNormals.begin(), localNormals.end());\n            if (globalImportanceCriteria.empty()) {\n                globalImportanceCriteria.insert(globalImportanceCriteria.end(), importanceCriteriaVertex.begin(),\n                                                importanceCriteriaVertex.end());\n            } else {\n                for (size_t i = 0; i < globalImportanceCriteria.size(); i++) {\n                    globalImportanceCriteria.at(i).insert(globalImportanceCriteria.at(i).end(),\n                                                          importanceCriteriaVertex.at(i).begin(), importanceCriteriaVertex.at(i).end());\n                }\n            }\n        }\n    }\n\n\n    submesh.material.diffuseColor = glm::vec3(165, 220, 84) / 255.0f;\n    submesh.material.opacity = 120 / 255.0f;\n    submesh.indices = globalIndices;\n\n    const size_t numIndices = globalIndices.size();\n    const size_t numVertices = globalVertexPositions.size();\n    const size_t numNormals = globalNormals.size();\n    // free memory\n    globalIndices.clear(); globalIndices.shrink_to_fit();\n\n    BinaryMeshAttribute positionAttribute;\n    positionAttribute.name = \"vertexPosition\";\n    positionAttribute.attributeFormat = ATTRIB_FLOAT;\n    positionAttribute.numComponents = 3;\n    positionAttribute.data.resize(numVertices * sizeof(glm::vec3));\n    memcpy(&positionAttribute.data.front(), &globalVertexPositions.front(), numVertices * sizeof(glm::vec3));\n    submesh.attributes.push_back(positionAttribute);\n\n    // free memory\n    globalVertexPositions.clear(); globalVertexPositions.shrink_to_fit();\n\n    BinaryMeshAttribute lineNormalsAttribute;\n    lineNormalsAttribute.name = \"vertexNormal\";\n    lineNormalsAttribute.attributeFormat = ATTRIB_FLOAT;\n    lineNormalsAttribute.numComponents = 3;\n    lineNormalsAttribute.data.resize(numNormals * sizeof(glm::vec3));\n    memcpy(&lineNormalsAttribute.data.front(), &globalNormals.front(), numNormals * sizeof(glm::vec3));\n    submesh.attributes.push_back(lineNormalsAttribute);\n\n    // free memory\n    globalNormals.clear(); globalNormals.shrink_to_fit();\n\n    std::vector<std::vector<uint16_t>> globalImportanceCriteriaUnorm;\n    packUnorm16ArrayOfArrays(globalImportanceCriteria, globalImportanceCriteriaUnorm);\n\n    for (size_t i = 0; i < globalImportanceCriteriaUnorm.size(); i++) {\n        std::vector<uint16_t> &currentAttr = globalImportanceCriteriaUnorm.at(i);\n        BinaryMeshAttribute vertexAttribute;\n        vertexAttribute.name = \"vertexAttribute\" + sgl::toString(i);\n        vertexAttribute.attributeFormat = ATTRIB_UNSIGNED_SHORT;\n        vertexAttribute.numComponents = 1;\n        vertexAttribute.data.resize(currentAttr.size() * sizeof(uint16_t));\n        memcpy(&vertexAttribute.data.front(), &currentAttr.front(), currentAttr.size() * sizeof(uint16_t));\n        submesh.attributes.push_back(vertexAttribute);\n    }\n\n    // free memory\n    globalImportanceCriteriaUnorm.clear(); globalImportanceCriteriaUnorm.shrink_to_fit();\n\n    auto end = std::chrono::system_clock::now();\n\n    Logfile::get()->writeInfo(std::string() + \"Summary: \"\n                              + sgl::toString(numVertices) + \" vertices, \"\n                              + sgl::toString(numIndices / 3) + \" faces, \"\n                              + sgl::toString(numIndices) + \" indices.\");\n    Logfile::get()->writeInfo(std::string() + \"Writing binary mesh...\");\n    writeMesh3D(binaryFilename, binaryMesh);\n\n    // compute size of renderable geometry;\n    float byteSize = positionAttribute.data.size() * sizeof(uint8_t) + lineNormalsAttribute.data.size() * sizeof(uint8_t)\n                     + submesh.attributes[0].data.size() * sizeof(uint8_t) + submesh.indices.size() * sizeof(uint32_t);\n\n    float MBSize = byteSize / 1024. / 1024.;\n\n    Logfile::get()->writeInfo(std::string() +  \"Byte Size Mesh Structure: \" + std::to_string(MBSize) + \" MB\");\n    Logfile::get()->writeInfo(std::string() +  \"Num Lines: \" + std::to_string(numLines / 1000.) + \" Tsd.\") ;\n    Logfile::get()->writeInfo(std::string() +  \"Num LineSegments: \" + std::to_string(numLineSegments / 1.0E6) + \" Mio\");\n\n    auto elapsed =\n            std::chrono::duration_cast<std::chrono::milliseconds>(end - start);\n    Logfile::get()->writeInfo(std::string() + \"Computational time to create binmesh: \"\n                              + std::to_string(elapsed.count()));\n\n}\n\n\n\n\nvoid computeLineNormal(const glm::vec3 &tangent, glm::vec3 &normal, const glm::vec3 &lastNormal)\n{\n    glm::vec3 helperAxis = lastNormal;\n    if (glm::length(glm::cross(helperAxis, tangent)) < 0.01f) {\n        // If tangent == helperAxis\n        helperAxis = glm::vec3(0.0f, 1.0f, 0.0f);\n    }\n    normal = glm::normalize(helperAxis - tangent * glm::dot(helperAxis, tangent)); // Gram-Schmidt\n    //glm::vec3 binormal = glm::normalize(glm::cross(tangent, normal));\n}\n\n/**\n * @param pathLineCenters: The (input) path line points to create a tube from.\n * @param pathLineAttributes: The (input) path line point vertex attributes (belonging to pathLineCenters).\n * @param vertices: The (output) vertex points, which are a set of oriented circles around the centers (see above).\n * @param indices: The (output) indices specifying how tube triangles are built from the circle vertices.\n */\nvoid createTangentAndNormalData(std::vector<glm::vec3> &pathLineCenters,\n                                std::vector<std::vector<float>> &importanceCriteriaIn,\n                                std::vector<glm::vec3> &vertices,\n                                std::vector<std::vector<float>> &importanceCriteriaOut,\n                                std::vector<glm::vec3> &tangents,\n                                std::vector<glm::vec3> &normals,\n                                std::vector<uint32_t> &indices)\n{\n    int n = (int)pathLineCenters.size();\n    int numImportanceCriteria = (int)importanceCriteriaIn.size();\n    if (n < 2) {\n        sgl::Logfile::get()->writeError(\"Error in createTube: n < 2\");\n        return;\n    }\n\n    vertices.reserve(n);\n    importanceCriteriaOut.resize(numImportanceCriteria);\n    for (int i = 0; i < numImportanceCriteria; i++) {\n        importanceCriteriaOut.at(i).reserve(n);\n    }\n    tangents.reserve(n);\n    normals.reserve(n);\n    indices.reserve(n);\n\n    // First, create a list of tube nodes\n    glm::vec3 lastNormal = glm::vec3(1.0f, 0.0f, 0.0f);\n    for (int i = 0; i < n; i++) {\n        glm::vec3 center = pathLineCenters.at(i);\n\n        // Remove invalid line points (used in many scientific datasets to indicate invalid lines).\n        const float MAX_VAL = 1e10;\n        if (std::fabs(center.x) > MAX_VAL || std::fabs(center.y) > MAX_VAL || std::fabs(center.z) > MAX_VAL) {\n            continue;\n        }\n\n        glm::vec3 tangent;\n        if (i == 0) {\n            // First node\n            tangent = pathLineCenters.at(i+1) - pathLineCenters.at(i);\n        } else if (i == n-1) {\n            // Last node\n            tangent = pathLineCenters.at(i) - pathLineCenters.at(i-1);\n        } else {\n            // Node with two neighbors - use both normals\n            tangent = pathLineCenters.at(i+1) - pathLineCenters.at(i);\n            //normal += pathLineCenters.at(i) - pathLineCenters.at(i-1);\n        }\n        if (glm::length(tangent) < 0.0001f) {\n            // In case the two vertices are almost identical, just skip this path line segment\n            continue;\n        }\n        tangent = glm::normalize(tangent);\n\n        glm::vec3 normal;\n        computeLineNormal(tangent, normal, lastNormal);\n        lastNormal = normal;\n\n        vertices.push_back(pathLineCenters.at(i));\n        for (int j = 0; j < numImportanceCriteria; j++) {\n            importanceCriteriaOut.at(j).push_back(importanceCriteriaIn.at(j).at(i));\n        }\n        tangents.push_back(tangent);\n        normals.push_back(normal);\n    }\n\n    // Create indices\n    for (int i = 0; i < (int)vertices.size() - 1; i++) {\n        indices.push_back(i);\n        indices.push_back(i+1);\n    }\n}\n\n\n\n\nstruct InputLinePoint {\n    glm::vec3 linePoint;\n    float lineAttribute;\n};\nstruct OutputLinePoint {\n    glm::vec3 linePoint;\n    float lineAttribute;\n    glm::vec3 lineTangent;\n    uint32_t valid; // 0 or 1\n    glm::vec3 lineNormal;\n    float padding2;\n};\nstruct PathLinePoint {\n    glm::vec3 linePointPosition;\n    float linePointAttribute;\n    glm::vec3 lineTangent;\n    float padding1;\n    glm::vec3 lineNormal;\n    float padding2;\n};\n\nstruct TubeVertex {\n    glm::vec3 vertexPosition;\n    float vertexAttribute;\n    glm::vec3 vertexNormal;\n    float padding;\n};\n\nvoid convertTrajectoryDataToBinaryTriangleMeshGPU(\n        TrajectoryType trajectoryType,\n        const std::string &trajectoriesFilename,\n        const std::string &binaryFilename,\n        float lineRadius)\n{\n    auto start = std::chrono::system_clock::now();\n    sgl::ShaderManager->invalidateShaderCache();\n\n    unsigned int NUM_CIRCLE_SEGMENTS = 3;\n    if (trajectoryType == TRAJECTORY_TYPE_RINGS) {\n        sgl::ShaderManager->addPreprocessorDefine(\"NUM_CIRCLE_SEGMENTS\", NUM_CIRCLE_SEGMENTS);\n        sgl::ShaderManager->addPreprocessorDefine(\"CIRCLE_RADIUS\", lineRadius);\n    } else if (trajectoryType == TRAJECTORY_TYPE_ANEURYSM) {\n        sgl::ShaderManager->addPreprocessorDefine(\"NUM_CIRCLE_SEGMENTS\", NUM_CIRCLE_SEGMENTS);\n        sgl::ShaderManager->addPreprocessorDefine(\"CIRCLE_RADIUS\", lineRadius);\n    } else {\n        sgl::ShaderManager->addPreprocessorDefine(\"NUM_CIRCLE_SEGMENTS\", NUM_CIRCLE_SEGMENTS);\n        sgl::ShaderManager->addPreprocessorDefine(\"CIRCLE_RADIUS\", lineRadius);\n    }\n\n    BinaryMesh binaryMesh;\n    binaryMesh.submeshes.push_back(BinarySubMesh());\n    BinarySubMesh &submesh = binaryMesh.submeshes.front();\n    submesh.vertexMode = VERTEX_MODE_TRIANGLES;\n\n    std::vector<uint32_t> lineOffsetsInput;\n    uint64_t numLinesInput = 0;\n    uint64_t numLinePointsInput = 0;\n\n    std::vector<uint32_t> lineOffsetsOutput;\n    uint64_t numLinesOutput = 0;\n    uint64_t numLinePointsOutput = 0;\n\n    std::vector<InputLinePoint> inputLinePoints;\n    std::vector<OutputLinePoint> outputLinePoints;\n    std::vector<PathLinePoint> pathLinePoints;\n\n    auto startLoad = std::chrono::system_clock::now();\n\n    Trajectories trajectories = loadTrajectoriesFromFile(trajectoriesFilename, trajectoryType);\n\n    lineOffsetsInput.push_back(0);\n    for (size_t i = 0; i < trajectories.size(); i++) {\n        Trajectory &trajectory = trajectories.at(i);\n\n        InputLinePoint inputLinePoint;\n        for (int j = 0; j < trajectory.positions.size(); j++) {\n            inputLinePoint.linePoint = trajectory.positions.at(j);\n            inputLinePoint.lineAttribute = trajectory.attributes.at(0).at(j);\n            inputLinePoints.push_back(inputLinePoint);\n        }\n\n        if (trajectory.positions.size() > 0) {\n            numLinePointsInput += trajectory.positions.size();\n            numLinesInput++;\n        } else {\n            continue;\n        }\n        lineOffsetsInput.push_back(numLinePointsInput);\n    }\n\n    auto endLoad = std::chrono::system_clock::now();\n    auto elapsedLoad = std::chrono::duration_cast<std::chrono::milliseconds>(endLoad - startLoad);\n    Logfile::get()->writeInfo(std::string() + \"Computational time to load: \" + std::to_string(elapsedLoad.count()));\n\n    const unsigned int WORK_GROUP_SIZE_1D = 256;\n    sgl::ShaderManager->addPreprocessorDefine(\"WORK_GROUP_SIZE_1D\", WORK_GROUP_SIZE_1D);\n    unsigned int numWorkGroupsOld;\n    uint32_t numWorkGroups;\n    void *bufferMemory;\n\n    // PART 1: Create line normals & mask invalid line points\n    auto startNormals = std::chrono::system_clock::now();\n    sgl::GeometryBufferPtr lineOffsetBufferInput = sgl::Renderer->createGeometryBuffer(\n            (numLinesInput+1) * sizeof(uint32_t), &lineOffsetsInput.front(),\n            SHADER_STORAGE_BUFFER, BUFFER_STATIC);\n    sgl::GeometryBufferPtr inputLinePointBuffer = sgl::Renderer->createGeometryBuffer(\n            inputLinePoints.size() * sizeof(InputLinePoint), &inputLinePoints.front(),\n            SHADER_STORAGE_BUFFER, BUFFER_STATIC);\n    sgl::GeometryBufferPtr outputLinePointBuffer = sgl::Renderer->createGeometryBuffer(\n            inputLinePoints.size() * sizeof(OutputLinePoint),\n            SHADER_STORAGE_BUFFER, BUFFER_STATIC);\n\n    sgl::ShaderProgramPtr createLineNormalsShader = sgl::ShaderManager->getShaderProgram({\"CreateLineNormals.Compute\"});\n    sgl::ShaderManager->bindShaderStorageBuffer(2, lineOffsetBufferInput);\n    sgl::ShaderManager->bindShaderStorageBuffer(3, inputLinePointBuffer);\n    sgl::ShaderManager->bindShaderStorageBuffer(4, outputLinePointBuffer);\n    createLineNormalsShader->setUniform(\"numLines\", static_cast<uint32_t>(numLinesInput));\n    numWorkGroupsOld = iceil(numLinesInput, WORK_GROUP_SIZE_1D); // last vector: local work group size\n    numWorkGroups = (numLinesInput - 1) / WORK_GROUP_SIZE_1D + 1;\n\n    createLineNormalsShader->dispatchCompute(numWorkGroups);\n    glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT);\n\n    bufferMemory = outputLinePointBuffer->mapBuffer(BUFFER_MAP_READ_ONLY);\n    outputLinePoints.resize(inputLinePoints.size());\n    memcpy(&outputLinePoints.front(), bufferMemory, outputLinePoints.size() * sizeof(OutputLinePoint));\n    outputLinePointBuffer->unmapBuffer();\n    auto endNormals = std::chrono::system_clock::now();\n    auto elapsedNormals = std::chrono::duration_cast<std::chrono::milliseconds>(endNormals - startNormals);\n    Logfile::get()->writeInfo(std::string() + \"Computational time to create normals: \"\n            + std::to_string(elapsedNormals.count()));\n\n\n    // PART 1.2: OutputLinePoint -> PathLinePoint (while removing invalid points)\n    auto startCompact = std::chrono::system_clock::now();\n    pathLinePoints.reserve(outputLinePoints.size());\n    lineOffsetsOutput.push_back(0);\n    for (size_t lineID = 0; lineID < numLinesInput; lineID++) {\n        size_t linePointsOffset = lineOffsetsInput.at(lineID);\n        size_t numLinePoints = lineOffsetsInput.at(lineID+1)-linePointsOffset;\n\n        size_t currentLineNumPointsOutput = 0;\n\n        for (size_t linePointID = 0; linePointID < numLinePoints; linePointID++) {\n            OutputLinePoint &outputLinePoint = outputLinePoints.at(linePointsOffset+linePointID);\n            if (outputLinePoint.valid == 1) {\n                PathLinePoint pathLinePoint;\n                pathLinePoint.linePointPosition = outputLinePoint.linePoint;\n                pathLinePoint.linePointAttribute = outputLinePoint.lineAttribute;\n                pathLinePoint.lineTangent = outputLinePoint.lineTangent;\n                pathLinePoint.lineNormal = outputLinePoint.lineNormal;\n                pathLinePoints.push_back(pathLinePoint);\n                currentLineNumPointsOutput++;\n                numLinePointsOutput++;\n            }\n        }\n\n        if (currentLineNumPointsOutput > 0) {\n            numLinesOutput++;\n            lineOffsetsOutput.push_back(numLinePointsOutput);\n        }\n    }\n    auto endCompact = std::chrono::system_clock::now();\n    auto elapsedCompact = std::chrono::duration_cast<std::chrono::milliseconds>(endCompact - startCompact);\n    Logfile::get()->writeInfo(std::string() + \"Computational time to compact: \"\n            + std::to_string(elapsedCompact.count()));\n\n\n    // PART 2: CreateTubePoints.Compute\n    auto startTube = std::chrono::system_clock::now();\n    std::vector<TubeVertex> tubeVertices;\n    tubeVertices.resize(NUM_CIRCLE_SEGMENTS * pathLinePoints.size());\n\n    sgl::GeometryBufferPtr pathLinePointsBuffer = sgl::Renderer->createGeometryBuffer(\n            pathLinePoints.size() * sizeof(PathLinePoint), &pathLinePoints.front(),\n            SHADER_STORAGE_BUFFER, BUFFER_STATIC);\n    sgl::GeometryBufferPtr tubeVertexBuffer = sgl::Renderer->createGeometryBuffer(\n            NUM_CIRCLE_SEGMENTS * pathLinePoints.size() * sizeof(TubeVertex),\n            SHADER_STORAGE_BUFFER, BUFFER_STATIC);\n\n    int maxNumWorkGroupsSupported = 0;\n    glGetIntegeri_v(GL_MAX_COMPUTE_WORK_GROUP_COUNT, 0, &maxNumWorkGroupsSupported);\n\n    sgl::ShaderProgramPtr createTubePointsShader = sgl::ShaderManager->getShaderProgram({\"CreateTubePoints.Compute\"});\n    sgl::ShaderManager->bindShaderStorageBuffer(2, pathLinePointsBuffer);\n    sgl::ShaderManager->bindShaderStorageBuffer(3, tubeVertexBuffer);\n    createTubePointsShader->setUniform(\"numLinePoints\", static_cast<uint32_t>(numLinePointsOutput));\n    numWorkGroups = iceil(pathLinePoints.size(), WORK_GROUP_SIZE_1D);\n    if (numWorkGroups > maxNumWorkGroupsSupported) {\n        sgl::Logfile::get()->writeInfo(\"Info: numWorkGroups > MAX_COMPUTE_WORK_GROUP_COUNT. Switching to CPU fallback.\");\n        convertTrajectoryDataToBinaryTriangleMesh(trajectoryType, trajectoriesFilename, binaryFilename, lineRadius);\n        return;\n    }\n    createTubePointsShader->dispatchCompute(numWorkGroups);\n    glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT);\n\n    bufferMemory = tubeVertexBuffer->mapBuffer(BUFFER_MAP_READ_ONLY);\n    memcpy(&tubeVertices.front(), bufferMemory, NUM_CIRCLE_SEGMENTS * pathLinePoints.size() * sizeof(TubeVertex));\n    tubeVertexBuffer->unmapBuffer();\n\n    std::vector<glm::vec3> globalVertexPositions;\n    std::vector<glm::vec3> globalNormals;\n    std::vector<std::vector<float>> globalImportanceCriteria;\n    globalVertexPositions.reserve(tubeVertices.size());\n    globalNormals.reserve(tubeVertices.size());\n    globalImportanceCriteria.resize(1);\n    globalImportanceCriteria.at(0).reserve(tubeVertices.size());\n    for (TubeVertex &tubeVertex : tubeVertices) {\n        globalVertexPositions.push_back(tubeVertex.vertexPosition);\n        globalNormals.push_back(tubeVertex.vertexNormal);\n        globalImportanceCriteria.at(0).push_back(tubeVertex.vertexAttribute);\n    }\n    auto endTube = std::chrono::system_clock::now();\n    auto elapsedTube = std::chrono::duration_cast<std::chrono::milliseconds>(endTube - startTube);\n    Logfile::get()->writeInfo(std::string() + \"Computational time to create tube vertices: \"\n                              + std::to_string(elapsedTube.count()));\n\n\n\n\n    // PART 3: CreateTubeIndices.Compute\n    auto startIndices = std::chrono::system_clock::now();\n    std::vector<uint32_t> tubeIndices;\n    size_t numLineSegments = numLinePointsOutput - numLinesOutput;\n    size_t numIndices = numLineSegments*NUM_CIRCLE_SEGMENTS*6;\n    tubeIndices.resize(numIndices);\n\n    sgl::GeometryBufferPtr lineOffsetBufferOutput = sgl::Renderer->createGeometryBuffer(\n            (numLinesOutput+1) * sizeof(uint32_t), &lineOffsetsOutput.front(),\n            SHADER_STORAGE_BUFFER, BUFFER_STATIC);\n    sgl::GeometryBufferPtr tubeIndexBuffer = sgl::Renderer->createGeometryBuffer(\n            numIndices * sizeof(uint32_t),\n            SHADER_STORAGE_BUFFER, BUFFER_STATIC);\n\n    sgl::ShaderProgramPtr createTubeIndicesShader = sgl::ShaderManager->getShaderProgram({\"CreateTubeIndices.Compute\"});\n    sgl::ShaderManager->bindShaderStorageBuffer(2, lineOffsetBufferOutput);\n    sgl::ShaderManager->bindShaderStorageBuffer(3, tubeIndexBuffer);\n    createTubeIndicesShader->setUniform(\"numLines\", static_cast<uint32_t>(numLinesOutput));\n    numWorkGroups = iceil(numLinesOutput, WORK_GROUP_SIZE_1D); // last vector: local work group size\n    createTubeIndicesShader->dispatchCompute(numWorkGroups);\n    glMemoryBarrier(GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);\n\n    bufferMemory = tubeIndexBuffer->mapBuffer(BUFFER_MAP_READ_ONLY);\n    memcpy(&tubeIndices.front(), bufferMemory, numIndices * sizeof(uint32_t));\n    tubeIndexBuffer->unmapBuffer();\n    auto endIndices = std::chrono::system_clock::now();\n    auto elapsedIndices = std::chrono::duration_cast<std::chrono::milliseconds>(endIndices - startIndices);\n    Logfile::get()->writeInfo(std::string() + \"Computational time to create tube indices: \"\n            + std::to_string(elapsedIndices.count()));\n\n    sgl::ShaderManager->removePreprocessorDefine(\"WORK_GROUP_SIZE_1D\");\n    sgl::ShaderManager->removePreprocessorDefine(\"NUM_CIRCLE_SEGMENTS\");\n    sgl::ShaderManager->removePreprocessorDefine(\"CIRCLE_RADIUS\");\n    sgl::ShaderManager->unbindShader();\n\n\n\n    // Normalize data for rings\n    auto startPost = std::chrono::system_clock::now();\n\n    submesh.material.diffuseColor = glm::vec3(165, 220, 84) / 255.0f;\n    submesh.material.opacity = 120 / 255.0f;\n    submesh.indices = tubeIndices;\n\n    const size_t numIndicesTubes = tubeIndices.size();\n    const size_t numVertices = globalVertexPositions.size();\n    const size_t numNormals = globalNormals.size();\n    // free memory\n    tubeIndices.clear(); tubeIndices.shrink_to_fit();\n\n    BinaryMeshAttribute positionAttribute;\n    positionAttribute.name = \"vertexPosition\";\n    positionAttribute.attributeFormat = ATTRIB_FLOAT;\n    positionAttribute.numComponents = 3;\n    positionAttribute.data.resize(numVertices * sizeof(glm::vec3));\n    memcpy(&positionAttribute.data.front(), &globalVertexPositions.front(), numVertices * sizeof(glm::vec3));\n    submesh.attributes.push_back(positionAttribute);\n\n    // free memory\n    globalVertexPositions.clear(); globalVertexPositions.shrink_to_fit();\n\n    BinaryMeshAttribute lineNormalsAttribute;\n    lineNormalsAttribute.name = \"vertexNormal\";\n    lineNormalsAttribute.attributeFormat = ATTRIB_FLOAT;\n    lineNormalsAttribute.numComponents = 3;\n    lineNormalsAttribute.data.resize(numNormals * sizeof(glm::vec3));\n    memcpy(&lineNormalsAttribute.data.front(), &globalNormals.front(), numNormals * sizeof(glm::vec3));\n    submesh.attributes.push_back(lineNormalsAttribute);\n\n    // free memory\n    globalNormals.clear(); globalNormals.shrink_to_fit();\n\n    std::vector<std::vector<uint16_t>> globalImportanceCriteriaUnorm;\n    packUnorm16ArrayOfArrays(globalImportanceCriteria, globalImportanceCriteriaUnorm);\n\n    for (size_t i = 0; i < globalImportanceCriteriaUnorm.size(); i++) {\n        std::vector<uint16_t> &currentAttr = globalImportanceCriteriaUnorm.at(i);\n        BinaryMeshAttribute vertexAttribute;\n        vertexAttribute.name = \"vertexAttribute\" + sgl::toString(i);\n        vertexAttribute.attributeFormat = ATTRIB_UNSIGNED_SHORT;\n        vertexAttribute.numComponents = 1;\n        vertexAttribute.data.resize(currentAttr.size() * sizeof(uint16_t));\n        memcpy(&vertexAttribute.data.front(), &currentAttr.front(), currentAttr.size() * sizeof(uint16_t));\n        submesh.attributes.push_back(vertexAttribute);\n    }\n    auto endPost = std::chrono::system_clock::now();\n    auto elapsedPost = std::chrono::duration_cast<std::chrono::milliseconds>(endPost - startPost);\n    Logfile::get()->writeInfo(std::string() + \"Computational time post-process: \" + std::to_string(elapsedPost.count()));\n\n    auto end = std::chrono::system_clock::now();\n\n    Logfile::get()->writeInfo(std::string() + \"Summary: \"\n                              + sgl::toString(numVertices) + \" vertices, \"\n                              + sgl::toString(numIndicesTubes / 3) + \" faces, \"\n                              + sgl::toString(numIndicesTubes) + \" indices.\");\n    Logfile::get()->writeInfo(std::string() + \"Writing binary mesh...\");\n    writeMesh3D(binaryFilename, binaryMesh);\n\n    // compute size of renderable geometry;\n    float byteSize = positionAttribute.data.size() * sizeof(uint8_t) + lineNormalsAttribute.data.size() * sizeof(uint8_t)\n                     + submesh.attributes[0].data.size() * sizeof(uint8_t) + submesh.indices.size() * sizeof(uint32_t);\n\n    float MBSize = byteSize / 1024. / 1024.;\n\n    // free memory\n    submesh.attributes.clear(); submesh.attributes.shrink_to_fit();\n\n    Logfile::get()->writeInfo(std::string() +  \"Byte Size Mesh Structure: \" + std::to_string(MBSize) + \" MB\");\n    Logfile::get()->writeInfo(std::string() +  \"Num Lines: \" + std::to_string(numLinesOutput / 1000.) + \" Tsd.\") ;\n    Logfile::get()->writeInfo(std::string() +  \"Num Line Points: \" + std::to_string(numLinePointsOutput / 1.0E6) + \" Mio\");\n\n    auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);\n    Logfile::get()->writeInfo(std::string() + \"Computational time to create binmesh: \"\n                              + std::to_string(elapsed.count()));\n}\n\n\n\nvoid convertTrajectoryDataToBinaryLineMesh(\n        TrajectoryType trajectoryType,\n        const std::string &trajectoriesFilename,\n        const std::string &binaryFilename)\n{\n    auto start = std::chrono::system_clock::now();\n\n    BinaryMesh binaryMesh;\n    binaryMesh.submeshes.push_back(BinarySubMesh());\n    BinarySubMesh &submesh = binaryMesh.submeshes.front();\n    submesh.vertexMode = VERTEX_MODE_LINES;\n\n    std::vector<glm::vec3> globalVertexPositions;\n    std::vector<glm::vec3> globalNormals;\n    std::vector<glm::vec3> globalTangents;\n    std::vector<std::vector<float>> globalImportanceCriteria;\n    std::vector<uint32_t> globalIndices;\n\n\n    Trajectories trajectories = loadTrajectoriesFromFile(trajectoriesFilename, trajectoryType);\n\n    for (size_t i = 0; i < trajectories.size(); i++) {\n        Trajectory &trajectory = trajectories.at(i);\n\n        // Create tube render data\n        std::vector<glm::vec3> localVertices;\n        std::vector<glm::vec3> localTangents;\n        std::vector<glm::vec3> localNormals;\n        std::vector<uint32_t> localIndices;\n        std::vector<std::vector<float>> importanceCriteriaOut;\n        createTangentAndNormalData(trajectory.positions, trajectory.attributes, localVertices,\n                                   importanceCriteriaOut, localTangents, localNormals, localIndices);\n\n        // Local -> global\n        if (localVertices.size() > 0) {\n            for (size_t i = 0; i < localIndices.size(); i++) {\n                globalIndices.push_back(localIndices.at(i) + globalVertexPositions.size());\n            }\n            globalVertexPositions.insert(globalVertexPositions.end(), localVertices.begin(), localVertices.end());\n            globalTangents.insert(globalTangents.end(), localTangents.begin(), localTangents.end());\n            globalNormals.insert(globalNormals.end(), localNormals.begin(), localNormals.end());\n            if (globalImportanceCriteria.empty()) {\n                globalImportanceCriteria.insert(globalImportanceCriteria.end(), importanceCriteriaOut.begin(),\n                                                importanceCriteriaOut.end());\n            } else {\n                for (size_t i = 0; i < globalImportanceCriteria.size(); i++) {\n                    globalImportanceCriteria.at(i).insert(globalImportanceCriteria.at(i).end(),\n                                                          importanceCriteriaOut.at(i).begin(),\n                                                          importanceCriteriaOut.at(i).end());\n                }\n            }\n        }\n    }\n\n\n    submesh.material.diffuseColor = glm::vec3(165, 220, 84) / 255.0f;\n    submesh.material.opacity = 120 / 255.0f;\n    submesh.indices = globalIndices;\n\n    const size_t numIndices = globalIndices.size();\n    const size_t numVertices = globalVertexPositions.size();\n    const size_t numNormals = globalNormals.size();\n    const size_t numTangents = globalTangents.size();\n    // free memory\n    globalIndices.clear(); globalIndices.shrink_to_fit();\n\n    BinaryMeshAttribute positionAttribute;\n    positionAttribute.name = \"vertexPosition\";\n    positionAttribute.attributeFormat = ATTRIB_FLOAT;\n    positionAttribute.numComponents = 3;\n    positionAttribute.data.resize(numVertices * sizeof(glm::vec3));\n    memcpy(&positionAttribute.data.front(), &globalVertexPositions.front(), numVertices * sizeof(glm::vec3));\n    submesh.attributes.push_back(positionAttribute);\n\n    // free memory\n    globalVertexPositions.clear(); globalVertexPositions.shrink_to_fit();\n\n    BinaryMeshAttribute lineNormalsAttribute;\n    lineNormalsAttribute.name = \"vertexLineNormal\";\n    lineNormalsAttribute.attributeFormat = ATTRIB_FLOAT;\n    lineNormalsAttribute.numComponents = 3;\n    lineNormalsAttribute.data.resize(numNormals * sizeof(glm::vec3));\n    memcpy(&lineNormalsAttribute.data.front(), &globalNormals.front(), numNormals * sizeof(glm::vec3));\n    submesh.attributes.push_back(lineNormalsAttribute);\n\n    // free memory\n    globalNormals.clear(); globalNormals.shrink_to_fit();\n\n    BinaryMeshAttribute lineTangentAttribute;\n    lineTangentAttribute.name = \"vertexLineTangent\";\n    lineTangentAttribute.attributeFormat = ATTRIB_FLOAT;\n    lineTangentAttribute.numComponents = 3;\n    lineTangentAttribute.data.resize(numTangents * sizeof(glm::vec3));\n    memcpy(&lineTangentAttribute.data.front(), &globalTangents.front(), numTangents * sizeof(glm::vec3));\n    submesh.attributes.push_back(lineTangentAttribute);\n\n    // free memory\n    globalTangents.clear(); globalTangents.shrink_to_fit();\n\n    std::vector<std::vector<uint16_t>> globalImportanceCriteriaUnorm;\n    packUnorm16ArrayOfArrays(globalImportanceCriteria, globalImportanceCriteriaUnorm);\n\n    for (size_t i = 0; i < globalImportanceCriteriaUnorm.size(); i++) {\n        std::vector<uint16_t> &currentAttr = globalImportanceCriteriaUnorm.at(i);\n        BinaryMeshAttribute vertexAttribute;\n        vertexAttribute.name = \"vertexAttribute\" + sgl::toString(i);\n        vertexAttribute.attributeFormat = ATTRIB_UNSIGNED_SHORT;\n        vertexAttribute.numComponents = 1;\n        vertexAttribute.data.resize(currentAttr.size() * sizeof(uint16_t));\n        memcpy(&vertexAttribute.data.front(), &currentAttr.front(), currentAttr.size() * sizeof(uint16_t));\n        submesh.attributes.push_back(vertexAttribute);\n    }\n\n    // free memory\n    globalImportanceCriteriaUnorm.clear(); globalImportanceCriteriaUnorm.shrink_to_fit();\n\n    auto end = std::chrono::system_clock::now();\n\n    Logfile::get()->writeInfo(std::string() + \"Summary: \"\n                              + sgl::toString(numVertices) + \" vertices, \"\n                              + sgl::toString(numIndices / 3) + \" faces, \"\n                              + sgl::toString(numIndices) + \" indices.\");\n    Logfile::get()->writeInfo(std::string() + \"Writing binary mesh...\");\n    writeMesh3D(binaryFilename, binaryMesh);\n\n\n    auto elapsed =\n            std::chrono::duration_cast<std::chrono::milliseconds>(end - start);\n    Logfile::get()->writeInfo(std::string() + \"Computational time to create binmesh: \"\n                        + std::to_string(elapsed.count()));\n}\n\n", "meta": {"hexsha": "253ce7e1d8ad48af47117741e1f5ebc8e40b69c2", "size": 46828, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Utils/TrajectoryLoader.cpp", "max_stars_repo_name": "chrismile/PixelSyncOIT", "max_stars_repo_head_hexsha": "a90353c5a19f911fc470f065cdc91b7b41299c43", "max_stars_repo_licenses": ["Apache-2.0", "BSD-2-Clause"], "max_stars_count": 44.0, "max_stars_repo_stars_event_min_datetime": "2019-01-15T09:53:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T08:37:22.000Z", "max_issues_repo_path": "src/Utils/TrajectoryLoader.cpp", "max_issues_repo_name": "chrismile/PixelSyncOIT", "max_issues_repo_head_hexsha": "a90353c5a19f911fc470f065cdc91b7b41299c43", "max_issues_repo_licenses": ["Apache-2.0", "BSD-2-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-07-25T11:17:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-06T09:51:39.000Z", "max_forks_repo_path": "src/Utils/TrajectoryLoader.cpp", "max_forks_repo_name": "chrismile/PixelSyncOIT", "max_forks_repo_head_hexsha": "a90353c5a19f911fc470f065cdc91b7b41299c43", "max_forks_repo_licenses": ["Apache-2.0", "BSD-2-Clause"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2020-04-13T10:02:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-10T09:34:23.000Z", "avg_line_length": 43.6828358209, "max_line_length": 136, "alphanum_fraction": 0.6583667891, "num_tokens": 11285, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4604837297302712}}
{"text": "\n#include \"Generic/common/leak_detection.h\"\n\n#include <string>\n#include <vector>\n\n#include <boost/algorithm/string/predicate.hpp>\n#include \"Generic/common/Symbol.h\"\n\n#include \"DistributionalUtil.h\"\n\n\nfloat DistributionalUtil::calculateAvgScore(const float& s1, const float& s2) {\n\tfloat avgS = -1;\n\n\tif( s1!=-1 && s2!=-1 ) \n\t\tavgS = (s1 + s2)/2;\n\t\t\n\treturn avgS;\n}\n\nint DistributionalUtil::scoreToBin(const float& score) {\n\tint bin;\n\n        if(score<0.5) {\n        \tbin = 5;\n        }\n        else if( (0.5<=score) && (score<0.6) ) {\n                bin = 6;\n        }\n        else if( (0.6<=score) && (score<0.7) ) {\n                bin = 7;\n        }\n        else if( (0.7<=score) && (score<0.8) ) {\n                bin = 8;\n        }\n        else if( (0.8<=score) && (score<0.9) ) {\n                bin = 9;\n                }\n        else if(0.9<=score) {\n                bin = 10;\n        }\n\n\treturn bin;\n}\n\n/*\n  10/15/2013 : Yee Seng Chan\n  The scoreToBins is temporarily there for an alternative way of representing scores, as a set of inequalities,\n  instead of as a single bin as currently represented by the scoreToBin function.\n\nstd::vector<std::wstring> DistributionalUtil::scoreToBins(const float& score) {\n\tstd::vector<std::wstring> bins;\n\n        if(score<0.5) {\n        \tbins.push_back(L\"<=0\");\n        }\n        else if( (0.5<=score) && (score<0.6) ) {\n                bins.push_back(L\">0\");\n                bins.push_back(L\"<=5\");\n        }\n        else if( (0.6<=score) && (score<0.7) ) {\n                bins.push_back(L\">0\");\n                bins.push_back(L\">5\");\n                bins.push_back(L\"<=6\");\n        }\n        else if( (0.7<=score) && (score<0.8) ) {\n                bins.push_back(L\">0\");\n                bins.push_back(L\">5\");\n                bins.push_back(L\">6\");\n                bins.push_back(L\"<=7\");\n        }\n        else if( (0.8<=score) && (score<0.9) ) {\n                bins.push_back(L\">0\");\n                bins.push_back(L\">5\");\n                bins.push_back(L\">6\");\n                bins.push_back(L\">7\");\n                bins.push_back(L\"<=8\");\n        }\n        else if(0.9<=score) {\n                bins.push_back(L\">0\");\n                bins.push_back(L\">5\");\n                bins.push_back(L\">6\");\n                bins.push_back(L\">7\");\n                bins.push_back(L\">8\");\n        }\n\n\treturn bins;\n}\n*/\n\nSymbol DistributionalUtil::determinePosType(const Symbol& posTag) {\n\tif(boost::algorithm::starts_with(posTag.to_string(), L\"NN\"))\n\t\treturn Symbol(L\"N\");\n\telse if(boost::algorithm::starts_with(posTag.to_string(), L\"JJ\"))\n\t\treturn Symbol(L\"J\");\n\telse if(boost::algorithm::starts_with(posTag.to_string(), L\"VB\"))\n\t\treturn Symbol(L\"V\");\n\telse\n\t\treturn Symbol();\n\n\treturn Symbol();\n}\n\n", "meta": {"hexsha": "60d9c1b48d5db24b544be8a3593df1a7b28c60db", "size": 2743, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Generic/distributionalKnowledge/DistributionalUtil.cpp", "max_stars_repo_name": "BBN-E/serif", "max_stars_repo_head_hexsha": "1e2662d82fb1c377ec3c79355a5a9b0644606cb4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-24T19:57:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T19:57:00.000Z", "max_issues_repo_path": "src/Generic/distributionalKnowledge/DistributionalUtil.cpp", "max_issues_repo_name": "BBN-E/serif", "max_issues_repo_head_hexsha": "1e2662d82fb1c377ec3c79355a5a9b0644606cb4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Generic/distributionalKnowledge/DistributionalUtil.cpp", "max_forks_repo_name": "BBN-E/serif", "max_forks_repo_head_hexsha": "1e2662d82fb1c377ec3c79355a5a9b0644606cb4", "max_forks_repo_licenses": ["Apache-2.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.1238095238, "max_line_length": 111, "alphanum_fraction": 0.505286183, "num_tokens": 746, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4604837297302712}}
{"text": "\n/*\n * Copyright 2015 Christoph Jud (christoph.jud@unibas.ch)\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 <memory>\n#include <ctime>\n#include <cmath>\n\n#include <boost/random.hpp>\n\n#include \"GaussianProcess.h\"\n#include \"Kernel.h\"\n#include \"KernelUtils.h\"\n#include \"MatrixIO.h\"\n\nusing namespace gpr;\n\ntypedef Kernel<double>                      KernelType;\ntypedef std::shared_ptr<KernelType>         KernelTypePointer;\ntypedef WhiteKernel<double>                 WhiteKernelType;\ntypedef std::shared_ptr<WhiteKernelType>    WhiteKernelTypePointer;\ntypedef GaussianProcess<double> GaussianProcessType;\ntypedef std::shared_ptr<GaussianProcessType> GaussianProcessTypePointer;\ntypedef GaussianProcessType::VectorType VectorType;\ntypedef GaussianProcessType::MatrixType MatrixType;\n\nvoid Test1(){\n    /*\n     * Test 1: construct, regress, io of highly general kernel\n     */\n    std::cout << \"Test 1.1: construct, regress, of highly general kernel...\" << std::flush;\n\n    // ground truth periodic variable\n    auto f = [](double x)->double { return std::sin(x)*std::cos(2.2*std::sin(x)); };\n\n    double interval_start = 0;\n    double interval_end = 5 * 2*M_PI; // full interval\n    double interval_step = 0.1;\n\n    //--------------------------------------------------------------------------------\n    // generating ground truth\n    unsigned gt_size = (interval_end-interval_start) / interval_step;\n    VectorType y(gt_size);\n    for(unsigned i=0; i<gt_size; i++){\n        y[i] = f(interval_start + i*interval_step);\n    }\n\n    //--------------------------------------------------------------------------------\n    // perform training\n    double noise = 0.01;\n    static boost::minstd_rand randgen(static_cast<unsigned>(time(0)));\n    static boost::normal_distribution<> dist(0, noise);\n    static boost::variate_generator<boost::minstd_rand, boost::normal_distribution<> > r(randgen, dist);\n\n    double interval_training_end = 2 * 2*M_PI; // interval to train\n    unsigned number_of_samples = 50;\n\n    std::vector<double> params;\n    params.push_back(1);\n    params.push_back(2);\n    params.push_back(3);\n    params.push_back(4);\n    params.push_back(5);\n    params.push_back(6);\n    params.push_back(7);\n    params.push_back(8);\n    params.push_back(9);\n    params.push_back(101);\n    params.push_back(202);\n    params.push_back(303);\n    params.push_back(404);\n\n    KernelTypePointer k = GetGeneralKernel(params);\n    std::string k_string = k->ToString();\n\n    GaussianProcessTypePointer gp(new GaussianProcessType(k));\n    gp->SetSigma(0); // noise\n\n    // add samples\n    double training_step_size = (interval_training_end - interval_start) / number_of_samples;\n    for(unsigned i=0; i<number_of_samples; i++){\n        VectorType x(1);\n        x(0) = interval_start + i*training_step_size;\n\n        VectorType y(1);\n        y(0) = f(x(0)) + r();\n\n        gp->AddSample(x, y);\n    }\n    gp->Initialize();\n\n    //--------------------------------------------------------------------------------\n    // predict full intervall\n    VectorType y_predict(gt_size);\n    for(unsigned i=0; i<gt_size; i++){\n        VectorType x(1);\n        x(0) = interval_start + i*interval_step;\n        y_predict[i] = gp->Predict(x)(0);\n    }\n\n    double err = (y-y_predict).norm(); // here we are not interested in an accurate regression\n    if(err>6){\n        std::stringstream ss; ss<<err; throw ss.str();\n    }\n    else{\n        std::cout << \"\\t[passed].\" << std::endl;\n    }\n\n    std::cout << \"Test 1.2: save/load of highly general kernel...\" << std::flush;\n\n    gp->Save(\"/tmp/gp_io_test-\");\n\n\n    WhiteKernelTypePointer k_dummy(new WhiteKernelType(1));\n    GaussianProcessTypePointer gp_read(new GaussianProcessType(k_dummy));\n\n\n    try{\n        gp_read->Load(\"/tmp/gp_io_test-\");\n    }\n    catch(std::string& s){\n        std::cout << s << std::endl;\n    }\n\n\n    std::string k_string_read = gp_read->GetKernel()->ToString();\n\n    if(*gp.get() == *gp_read.get() && k_string_read.compare(k_string)==0){\n        std::cout << \"\\t\\t\\t[passed].\" << std::endl;\n    }\n    else{\n        throw std::string(\"comparison\");\n    }\n}\n\n\n\n\nint main (int argc, char *argv[]){\n    std::cout << \"Highly general kernel test: \" << std::endl;\n    try{\n        Test1();\n    }\n    catch(std::string& s){\n        std::cout << \"[failed] Error: \" << s << std::endl;\n        return -1;\n    }\n\n    return 0;\n}\n\n", "meta": {"hexsha": "eb17edb9b8c776ee3bc48eba25f15297e20aa4c7", "size": 4913, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/HighlyGeneralKernelTest.cpp", "max_stars_repo_name": "ChristophJud/GPR", "max_stars_repo_head_hexsha": "62c60aca697ae7614356b1f6db06568f0c4085d2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2015-04-20T14:30:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-18T21:44:06.000Z", "max_issues_repo_path": "tests/HighlyGeneralKernelTest.cpp", "max_issues_repo_name": "ChristophJud/GPR", "max_issues_repo_head_hexsha": "62c60aca697ae7614356b1f6db06568f0c4085d2", "max_issues_repo_licenses": ["Apache-2.0"], "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/HighlyGeneralKernelTest.cpp", "max_forks_repo_name": "ChristophJud/GPR", "max_forks_repo_head_hexsha": "62c60aca697ae7614356b1f6db06568f0c4085d2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2015-11-16T00:50:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-23T02:00:18.000Z", "avg_line_length": 29.4191616766, "max_line_length": 104, "alphanum_fraction": 0.6155098718, "num_tokens": 1195, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4604837297302712}}
{"text": "#include \"lola/Robot.h\"\n#include \"lepp3/models/Coordinate.h\"\n#include \"lepp3/models/SurfaceModel.h\"\n\n#include <Eigen/Geometry>\n#include <limits>\n\nusing namespace lepp;\n\nbool Robot::isInRobotBoundary(ObjectModel const& model) const {\n  int obj_id = model.id();\n  Coordinate model_center = model.center_point();\n  Coordinate robot_position = this->robot_position();\n  // Now find the distance between the two coordinates, giving the\n  // (rough) distance between the robot and the object.\n  double const squared_dist = (model_center - robot_position).square_norm();\n\n  // The object is considered to be in the robot's boundary if closer\n  // than a particular threshold.\n  return squared_dist < inner_zone_square_radius_;\n}\n\n// checks to see if the robot is near or on a given surface\n// If the robot's center is within the surface's convex hull or near\n// to one of the edges which forms the convex hull, this returns TRUE.\nbool Robot::isInRobotBoundary(SurfaceModel const& model) const {\n  int obj_id = model.id();\n\n  Coordinate robot_position = this->robot_position();\n  PointT robot_center;\n  robot_center.x = robot_position.x;\n  robot_center.y = robot_position.y;\n  robot_center.z = robot_position.z;\n\n  // check if robot is inside (or standing on) the surface\n  bool isInside = pcl::isPointIn2DPolygon(robot_center, *(model.get_hull()));\n  if (isInside) {\n    return true;\n  }\n\n  // check if robot is close to the edge of the surface\n  double sq_min_dist_to_poly = std::numeric_limits<double>::max();\n\n  const size_t hull_point_count = model.get_hull()->points.size();\n  for (size_t i = 1; i <= hull_point_count; ++i) {\n    PointT const& point1 = model.get_hull()->points[i % hull_point_count];\n    PointT const& point2 = model.get_hull()->points[i - 1];\n\n    Eigen::Vector3d p1_to_p2 = {(point2 - point1).x, (point2 - point1).y, (point2 - point1).z};\n    Eigen::Vector3d p1_to_robot = {(robot_center - point1).x, (robot_center - point1).y, (robot_center - point1).z}; // I hate myself\n    Eigen::Vector3d p2_to_robot = {(robot_center - point2).x, (robot_center - point2).y, (robot_center - point2).z}; // I hate myself\n\n    auto r = p1_to_robot.dot(p1_to_p2 / p1_to_p2.norm()); //scalar projection of p1_to_robot into p1_to_p2\n    r /= p1_to_p2.norm(); //this checks if the projection of p1_to_robot into p1_to_p2 lies inside or outside the segment\n\n    double sq_dist_to_poly = 0; // distance to this edge\n    if (r < 0) { // robot lies outside of the segment, closer to p1\n      sq_dist_to_poly = p1_to_robot.squaredNorm();\n    } else if (r > 1) { // robot lies outside of the segment, closer to p2\n      sq_dist_to_poly = p2_to_robot.squaredNorm();\n    } else { // robot lies inside the segment\n      sq_dist_to_poly = p1_to_robot.squaredNorm() - r * p1_to_p2.squaredNorm();\n    }\n\n    sq_min_dist_to_poly = std::min(sq_dist_to_poly, sq_min_dist_to_poly);\n  }\n\n  // The surface is considered to be in the robot's boundary if closer\n  // than a particular threshold or the robot's position is within the\n  // bounds of the surface's convex hull.\n  return sq_min_dist_to_poly < inner_zone_square_radius_;\n}\n\nlepp::Coordinate Robot::robot_position() const {\n  lepp::LolaKinematicsParams params = pose_service_.getParams();\n  return lepp::PoseService::getRobotPosition(params);\n}\n", "meta": {"hexsha": "7f82f99c2448aa5450a0b2f8ba19718214b986f1", "size": 3284, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/lola/Robot.cpp", "max_stars_repo_name": "am-lola/lepp3", "max_stars_repo_head_hexsha": "7f92ce61bccad984e18ce86da0d8a1b9c48feb65", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2017-01-16T10:41:56.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-09T09:13:30.000Z", "max_issues_repo_path": "src/lola/Robot.cpp", "max_issues_repo_name": "am-lola/lepp3", "max_issues_repo_head_hexsha": "7f92ce61bccad984e18ce86da0d8a1b9c48feb65", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lola/Robot.cpp", "max_forks_repo_name": "am-lola/lepp3", "max_forks_repo_head_hexsha": "7f92ce61bccad984e18ce86da0d8a1b9c48feb65", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2015-08-07T13:07:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T03:18:33.000Z", "avg_line_length": 42.1025641026, "max_line_length": 133, "alphanum_fraction": 0.7222898904, "num_tokens": 877, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.757794360334681, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.46048372308246066}}
{"text": "#include <boost/math/distributions/extreme_value.hpp>\n", "meta": {"hexsha": "746d4bc6f357c084baf7e1fa3e457b98597cf55e", "size": 54, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_distributions_extreme_value.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_distributions_extreme_value.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_distributions_extreme_value.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 27.0, "max_line_length": 53, "alphanum_fraction": 0.8333333333, "num_tokens": 11, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672320414786, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4604792546997355}}
{"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_TANH_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_TANH_HPP_INCLUDED\n\n#include <boost/simd/arch/common/detail/generic/tanh_kernel.hpp>\n#include <boost/simd/constant/mtwo.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/ratio.hpp>\n#include <boost/simd/constant/two.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/fma.hpp>\n#include <boost/simd/function/inc.hpp>\n#include <boost/simd/function/rec.hpp>\n#include <boost/simd/function/sqr.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 ( tanh_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_<bd::floating_<A0> >\n                          )\n  {\n\n    BOOST_FORCEINLINE A0 operator() ( A0  a0) const BOOST_NOEXCEPT\n    {\n      //////////////////////////////////////////////////////////////////////////////\n      // if x = abs(a0) is less than 5/8 sinh is computed using a polynomial(float)\n      // (respectively rational(double)) approx from cephes.\n      // else\n      // tanh(a0) is  sign(a0)*(2/(exp(2*x)+1)+1)\n      //////////////////////////////////////////////////////////////////////////////\n      A0 x = bs::abs(a0);\n      if( x < Ratio<A0, 5, 8>())\n      {\n       return detail::tanh_kernel<A0>::tanh(a0, sqr(x));\n      }\n      else\n      {\n       A0 r = fma(Mtwo<A0>(), rec(inc(exp(x+x))), One<A0>());\n       return bitwise_xor(r, bitofsign(a0));\n      }\n    }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "9105d3e26dcdc84fcac78cd5694a96e3107f293f", "size": 2227, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/scalar/function/tanh.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/scalar/function/tanh.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/tanh.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": 34.2615384615, "max_line_length": 100, "alphanum_fraction": 0.5419847328, "num_tokens": 507, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.460479244163892}}
{"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 \"FluidAdvection.h\"\n#include \"../Math/RegularNumberField.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\nnamespace SceneEngine\n{\n    using ScalarField2D = XLEMath::ScalarField2D<Eigen::VectorXf>;\n    using VectorField2D = VectorField2DSeparate<Eigen::VectorXf>;\n    using ScalarField3D = XLEMath::ScalarField3D<Eigen::VectorXf>;\n    using VectorField3D = VectorField3DSeparate<Eigen::VectorXf>;\n\n    UInt3 As3DDims(UInt2 input)     { return Expand(input, 1u); }\n    UInt3 As3DBorder(UInt2 input)   { return UInt3(1,1,0); }\n    UInt3 As3DDims(UInt3 input)     { return input; }\n    UInt3 As3DBorder(UInt3 input)   { return UInt3(1,1,1); }\n\n    template<typename OutType, typename InType>\n        OutType ConvertVector(const InType& in)\n        {\n            OutType result; \n            unsigned i=0u; \n            for (; i<std::min((unsigned)InType::dimension, (unsigned)OutType::dimension); ++i)\n                result[i] = (OutType::value_type)in[i];\n            for (; i<(unsigned)OutType::dimension; ++i)\n                result[i] = (OutType::value_type)0;\n            return result;\n        }\n\n    template<unsigned SamplingFlags, typename Field>\n        static typename Field::ValueType AdvectRK4(\n            const Field& velFieldT0, const Field& velFieldT1,\n            typename Field::Coord pt, typename Field::FloatCoord velScale)\n        {\n            const auto s = velScale;\n            const auto halfS = decltype(s)(s / 2);\n    \n            auto startTap = ConvertVector<typename Field::FloatCoord>(pt);\n            auto k1 = velFieldT0.Load(pt);\n            auto k2 = .5f * velFieldT0.Sample<SamplingFlags>(startTap + MultiplyAcross(halfS, k1))\n                    + .5f * velFieldT1.Sample<SamplingFlags>(startTap + MultiplyAcross(halfS, k1))\n                    ;\n            auto k3 = .5f * velFieldT0.Sample<SamplingFlags>(startTap + MultiplyAcross(halfS, k2))\n                    + .5f * velFieldT1.Sample<SamplingFlags>(startTap + MultiplyAcross(halfS, k2))\n                    ;\n            auto k4 = velFieldT1.Sample<SamplingFlags>(startTap + MultiplyAcross(s, k3));\n    \n            auto finalVel = (1.f / 6.f) * (k1 + 2.f * k2 + 2.f * k3 + k4);\n            return startTap + MultiplyAcross(s, finalVel);\n        }\n\n    template<unsigned SamplingFlags, typename Field>\n        static typename Field::ValueType AdvectRK4(\n            const Field& velFieldT0, const Field& velFieldT1,\n            typename Field::FloatCoord pt, typename Field::FloatCoord velScale)\n        {\n            const auto s = velScale;\n            const auto halfS = decltype(s)(s / 2);\n\n                // when using a float point input, we need bilinear interpolation\n            auto k1 = velFieldT0.Sample<SamplingFlags>(pt);\n            auto k2 = .5f * velFieldT0.Sample<SamplingFlags>(pt + MultiplyAcross(halfS, k1))\n                    + .5f * velFieldT1.Sample<SamplingFlags>(pt + MultiplyAcross(halfS, k1))\n                    ;\n            auto k3 = .5f * velFieldT0.Sample<SamplingFlags>(pt + MultiplyAcross(halfS, k2))\n                    + .5f * velFieldT1.Sample<SamplingFlags>(pt + MultiplyAcross(halfS, k2))\n                    ;\n            auto k4 = velFieldT1.Sample<SamplingFlags>(pt + MultiplyAcross(s, k3));\n\n            auto finalVel = (1.f / 6.f) * (k1 + 2.f * k2 + 2.f * k3 + k4);\n            return pt + MultiplyAcross(s, finalVel);\n        }\n\n    template<typename Type> static Type MaxValue();\n    template<> static float MaxValue()         { return FLT_MAX; }\n    template<> static Float2 MaxValue()        { return Float2(FLT_MAX, FLT_MAX); }\n    template<> static Float3 MaxValue()        { return Float3(FLT_MAX, FLT_MAX, FLT_MAX); }\n    static float   MinAcross(float lhs, float rhs)   { return std::min(lhs, rhs); }\n    static Float2  MinAcross(Float2 lhs, Float2 rhs) { return Float2(std::min(lhs[0], rhs[0]), std::min(lhs[1], rhs[1])); }\n    static Float3  MinAcross(Float3 lhs, Float3 rhs) { return Float3(std::min(lhs[0], rhs[0]), std::min(lhs[1], rhs[1]), std::min(lhs[2], rhs[2])); }\n    static float   MaxAcross(float lhs, float rhs)   { return std::max(lhs, rhs); }\n    static Float2  MaxAcross(Float2 lhs, Float2 rhs) { return Float2(std::max(lhs[0], rhs[0]), std::max(lhs[1], rhs[1])); }\n    static Float3  MaxAcross(Float3 lhs, Float3 rhs) { return Float3(std::max(lhs[0], rhs[0]), std::max(lhs[1], rhs[1]), std::max(lhs[2], rhs[2])); }\n\n    // static Float2 ClampAcross(const Float2& input, const Float2& mins, const Float2& maxs)\n    // {\n    //     return Float2(Clamp(input[0], mins[0], maxs[0]), Clamp(input[1], mins[1], maxs[1]));\n    // }\n    // \n    // static Float3 ClampAcross(const Float3& input, const Float3& mins, const Float3& maxs)\n    // {\n    //     return Float3(Clamp(input[0], mins[0], maxs[0]), Clamp(input[1], mins[1], maxs[1]), Clamp(input[2], mins[2], maxs[2]));\n    // }\n\n    template<unsigned WrappingFlags, typename VectorType>\n        static VectorType ApplyBoundary(\n            const VectorType& input, \n            const VectorType& dims)\n    {\n        VectorType result;\n        static_assert(RNFSample::WrapY == (RNFSample::WrapX<<1), \"Expecting wrapping flags to be sequential bits\");\n        static_assert(RNFSample::WrapZ == (RNFSample::WrapX<<2), \"Expecting wrapping flags to be sequential bits\");\n        for (unsigned c=0; c<VectorType::dimension; ++c) {\n            if (WrappingFlags & (RNFSample::WrapX<<c)) {\n                result[c] = XlFMod(input[c]+dims[c], dims[c]);\n            } else {\n                result[c] = Clamp(input[c], 0.f, dims[c]-1.f-1e-5f);\n            }\n        }\n        return result;\n    }\n\n    template<unsigned SamplingFlags, typename Field>\n        typename Field::ValueType LoadWithNearbyRange(\n            typename Field::ValueType& minNeighbour, \n            typename Field::ValueType& maxNeighbour, const Field& field, typename Field::FloatCoord pt)\n        {\n            typename Field::ValueType predictorParts[Field::NeighborCount];\n            float predictorWeights[Field::BilinearWeightCount];\n            field.GatherNeighbors(predictorParts, predictorWeights, pt, SamplingFlags);\n            \n            minNeighbour =  MaxValue<typename Field::ValueType>();\n            maxNeighbour = -MaxValue<typename Field::ValueType>();\n            for (unsigned c=0; c<Field::NeighborCount; ++c) {\n                minNeighbour = MinAcross(predictorParts[c], minNeighbour);\n                maxNeighbour = MaxAcross(predictorParts[c], maxNeighbour);\n            }\n\n            if (constant_expression<(SamplingFlags & RNFSample::Cubic)==0>::result()) {\n                Field::ValueType result =  predictorWeights[0] * predictorParts[0];\n                for (unsigned i=1; i<Field::BilinearWeightCount; ++i)   // hopefully the compiler should unroll this loop (which is short, there are only 4 or 8 weights)\n                    result += predictorWeights[i] * predictorParts[i];\n                return result;\n            } else {\n                return field.Sample<SamplingFlags>(pt);\n            }\n        }\n    \n    template<unsigned WrappingFlags, typename Field, typename VelField>\n        static void PerformAdvection_Internal(\n            Field dstValues, Field srcValues, \n            VelField velFieldT0, VelField velFieldT1,\n            float deltaTime, const AdvectionSettings& settings)\n    {\n        //\n        // This is the advection step. We will use the method of characteristics.\n        //\n        // We have a few different options for the stepping method:\n        //  * basic euler forward integration (ie, just step forward in time)\n        //  * forward integration method divided into smaller time steps\n        //  * Runge-Kutta integration\n        //  * Modified MacCormack methods\n        //  * Back and Forth Error Compensation and Correction (BFECC)\n        //\n        // Let's start without any complex boundary conditions.\n        //\n        // We have to be careful about how the velocity sample is aligned with\n        // the grid cell. Incorrect alignment will produce a bias in the way that\n        // we interpolate the field.\n        //\n        // We could consider offsetting the velocity field by half a cell (see\n        // Visual Simulation of Smoke, Fedkiw, et al)\n        //\n        // Also consider Semi-Lagrangian methods for large timesteps (when the CFL\n        // number is larger than 1)\n        //\n\n        const auto advectionMethod = settings._method;\n        const auto adjvectionSteps = settings._subSteps;\n\n        assert(dstValues.Dimensions() == srcValues.Dimensions());\n        assert(dstValues.Dimensions() == velFieldT0.Dimensions());\n        assert(dstValues.Dimensions() == velFieldT1.Dimensions());\n        const UInt3 dims = As3DDims(dstValues.Dimensions());\n\n            // when the border condition is \"margin\" we create a 1 cell margin on that\n            // edge that will be read from, but not written to\n        UInt3 margin = As3DBorder(dstValues.Dimensions());\n        if (settings._borderX != AdvectionBorder::Margin) margin[0] = 0;\n        if (settings._borderY != AdvectionBorder::Margin) margin[1] = 0;\n        if (settings._borderZ != AdvectionBorder::Margin) margin[2] = 0;\n\n        using FloatCoord = typename VelField::FloatCoord;\n        using Coord = typename VelField::Coord;\n        const auto velFieldScale = ConvertVector<FloatCoord>(\n            Float3(\n                float(dims[0]-2*margin[0]),\n                float(dims[1]-2*margin[1]),\n                float(dims[2]-2*margin[2])));   // (grid size without borders)\n        const auto clampMax = ConvertVector<FloatCoord>(dims);\n\n        if (advectionMethod == AdvectionMethod::ForwardEuler) {\n\n                //  For each cell in the grid, trace backwards\n                //  through the velocity field to find an approximation\n                //  of where the point was in the previous frame.\n\n            for (unsigned z=margin[2]; z<dims[2]-margin[2]; ++z)\n                for (unsigned y=margin[1]; y<dims[1]-margin[1]; ++y)\n                    for (unsigned x=margin[0]; x<dims[0]-margin[0]; ++x) {\n                        auto coord = ConvertVector<Coord>(UInt3(x, y, z));\n                        auto startVel = velFieldT1.Load(coord);\n                        FloatCoord tap = ConvertVector<FloatCoord>(coord) - MultiplyAcross(deltaTime * velFieldScale, startVel);\n                        tap = ApplyBoundary<WrappingFlags>(tap, clampMax);\n                        dstValues.Write(coord, srcValues.Sample<0>(tap));\n                    }\n\n        } else if (advectionMethod == AdvectionMethod::ForwardEulerDiv) {\n\n            auto stepScale = decltype(velFieldScale)(deltaTime * velFieldScale / float(adjvectionSteps));\n            for (unsigned z=margin[2]; z<dims[2]-margin[2]; ++z)\n                for (unsigned y=margin[1]; y<dims[1]-margin[1]; ++y)\n                    for (unsigned x=margin[0]; x<dims[0]-margin[0]; ++x) {\n\n                        auto coord = ConvertVector<Coord>(UInt3(x, y, z));\n                        auto tap = ConvertVector<FloatCoord>(UInt3(x, y, z));\n                        auto vel = velFieldT0.Load(coord);\n                        for (unsigned s=1; ; ++s) {\n                            tap -= MultiplyAcross(stepScale, vel);\n                            tap = ApplyBoundary<WrappingFlags>(tap, clampMax);\n                            if (s>=adjvectionSteps) break;\n\n                            vel = LinearInterpolate(\n                                velFieldT0.Sample<0>(tap),\n                                velFieldT1.Sample<0>(tap),\n                                s / float(adjvectionSteps-1));\n                        }\n\n                        dstValues.Write(coord, srcValues.Sample<WrappingFlags>(tap));\n                    }\n\n        } else if (advectionMethod == AdvectionMethod::RungeKutta) {\n\n            if (settings._interpolation == AdvectionInterp::Bilinear) {\n\n                const auto SamplingFlags = WrappingFlags;\n                for (unsigned z=margin[2]; z<dims[2]-margin[2]; ++z)\n                    for (unsigned y=margin[1]; y<dims[1]-margin[1]; ++y)\n                        for (unsigned x=margin[0]; x<dims[0]-margin[0]; ++x) {\n\n                                // This is the RK4 version\n                                // We'll use the average of the velocity field at t and\n                                // the velocity field at t+dt as an estimate of the field\n                                // at t+.5*dt\n\n                                // Note that we're tracing the velocity field backwards.\n                                // So doing k1 on velField1, and k4 on velFieldT0\n                                //      -- hoping this will interact with the velocity diffusion more sensibly\n                            auto coord = ConvertVector<Coord>(UInt3(x, y, z));\n                            const auto tap = AdvectRK4<SamplingFlags>(velFieldT1, velFieldT0, coord, -deltaTime * velFieldScale);\n                            dstValues.Write(coord, srcValues.Sample<SamplingFlags>(tap));\n\n                        }\n\n            } else {\n\n                const auto SamplingFlags = RNFSample::Cubic|WrappingFlags;\n                for (unsigned z=margin[2]; z<dims[2]-margin[2]; ++z)\n                    for (unsigned y=margin[1]; y<dims[1]-margin[1]; ++y)\n                        for (unsigned x=margin[0]; x<dims[0]-margin[0]; ++x) {\n                            auto coord = ConvertVector<Coord>(UInt3(x, y, z));\n                            const auto tap = AdvectRK4<SamplingFlags>(velFieldT1, velFieldT0, coord, -deltaTime * velFieldScale);\n                            dstValues.Write(coord, srcValues.Sample<SamplingFlags>(tap));\n                        }\n\n            }\n\n        } else if (advectionMethod == AdvectionMethod::MacCormackRK4) {\n\n                //\n                // This is a modified MacCormack scheme, as described in An Unconditionally\n                // Stable MacCormack Method -- Selle & Fedkiw, et al.\n                //  http://physbam.stanford.edu/~fedkiw/papers/stanford2006-09.pdf\n                //\n                // It's also similar to the (oddly long nammed) Back And Forth Error Compensation \n                // and Correction (BFECC).\n                //\n                // Basically, we want to run an initial predictor step, then run a backwards\n                // advection to find an intermediate point. The difference between the value at\n                // the initial point and the intermediate point is used as a error term.\n                //\n                // This way, we get an improved estimate, but with only 2 advection steps.\n                //\n                // We need to use some advection method for the forward and advection steps. Often\n                // a semi-lagrangian method is used (particularly velocities and timesteps are large\n                // with respect to the grid size). \n                //\n                // But here, we'll use RK4.\n                //\n                // We also need a way to check for overruns and oscillation cases. Selle & Fedkiw\n                // suggest using a normal semi-Lagrangian method in these cases. We'll try a simplier\n                // method and just clamp.\n                //\n\n            if (settings._interpolation == AdvectionInterp::Bilinear) {\n\n                const auto SamplingFlags = WrappingFlags;\n                for (unsigned z=margin[2]; z<dims[2]-margin[2]; ++z)\n                    for (unsigned y=margin[1]; y<dims[1]-margin[1]; ++y)\n                        for (unsigned x=margin[0]; x<dims[0]-margin[0]; ++x) {\n\n                            auto coord = ConvertVector<Coord>(UInt3(x, y, z));\n\n                                // advect backwards in time first, to find the predictor\n                            const auto predictor = AdvectRK4<SamplingFlags>(velFieldT1, velFieldT0, coord, -deltaTime * velFieldScale);\n                                // advect forward again to find the error tap\n                            const auto reversedTap = AdvectRK4<SamplingFlags>(velFieldT0, velFieldT1, predictor, deltaTime * velFieldScale);\n\n                            auto originalValue = srcValues.Load(coord);\n                            auto reversedValue = srcValues.Sample<SamplingFlags>(reversedTap);\n                            Field::ValueType finalValue;\n\n                                // Here we clamp the final result within the range of the neighbour cells of the \n                                // original predictor. This prevents the scheme from becoming unstable (by avoiding\n                                // irrational values for 0.5f * (originalValue - reversedValue)\n                            const bool doRangeClamping = true;\n                            if (constant_expression<doRangeClamping>::result()) {\n                                typename Field::ValueType minNeighbour, maxNeighbour;\n                                auto predictorValue = LoadWithNearbyRange<SamplingFlags>(minNeighbour, maxNeighbour, srcValues, predictor);\n                                finalValue = typename Field::ValueType(predictorValue + .5f * (originalValue - reversedValue));\n                                finalValue = MaxAcross(finalValue, minNeighbour);\n                                finalValue = MinAcross(finalValue, maxNeighbour);\n                            } else {\n                                auto predictorValue = srcValues.Sample<SamplingFlags>(predictor);\n                                finalValue = typename Field::ValueType(predictorValue + .5f * (originalValue - reversedValue));\n                            }\n\n                            dstValues.Write(coord, finalValue);\n\n                        }   \n\n            } else {\n\n                const auto SamplingFlags = RNFSample::Cubic|WrappingFlags;\n                for (unsigned z=margin[2]; z<dims[2]-margin[2]; ++z)\n                    for (unsigned y=margin[1]; y<dims[1]-margin[1]; ++y)\n                        for (unsigned x=margin[0]; x<dims[0]-margin[0]; ++x) {\n\n                            auto coord = ConvertVector<Coord>(UInt3(x, y, z));\n                            const auto predictor = AdvectRK4<SamplingFlags>(velFieldT1, velFieldT0, coord, -deltaTime * velFieldScale);\n                            const auto reversedTap = AdvectRK4<SamplingFlags>(velFieldT0, velFieldT1, predictor, deltaTime * velFieldScale);\n\n                            auto originalValue = srcValues.Load(coord);\n                            auto reversedValue = srcValues.Sample<SamplingFlags>(reversedTap);\n\n                            Field::ValueType minNeighbour, maxNeighbour;\n                            auto predictorValue = LoadWithNearbyRange<SamplingFlags>(minNeighbour, maxNeighbour, srcValues, predictor);\n                            auto finalValue = Field::ValueType(predictorValue + .5f * (originalValue - reversedValue));\n                            finalValue = MaxAcross(finalValue, minNeighbour);\n                            finalValue = MinAcross(finalValue, maxNeighbour);\n\n                            dstValues.Write(coord, finalValue);\n\n                        }\n\n            }\n\n        }\n\n    }\n\n    template<typename Field, typename VelField>\n        void PerformAdvection(\n            Field dstValues, Field srcValues, \n            VelField velFieldT0, VelField velFieldT1,\n            float deltaTime, const AdvectionSettings& settings)\n    {\n            // it's awkward, but we need to convertion between the\n            // variables \"settings._border...\" and the compile time\n            // static RNFSample flags. Only a fixed number of variations\n            // are supported... others will fall back to clamping in all\n            // directions.\n        if (    settings._borderX == AdvectionBorder::Wrap \n            &&  settings._borderY != AdvectionBorder::Wrap \n            &&  settings._borderZ != AdvectionBorder::Wrap) {\n\n            PerformAdvection_Internal<RNFSample::WrapX|RNFSample::ClampY|RNFSample::ClampZ>(\n                dstValues, srcValues, velFieldT0, velFieldT1, deltaTime, settings);\n\n        } else if ( settings._borderX != AdvectionBorder::Wrap \n            &&      settings._borderY == AdvectionBorder::Wrap \n            &&      settings._borderZ != AdvectionBorder::Wrap) {\n\n            PerformAdvection_Internal<RNFSample::ClampX|RNFSample::WrapY|RNFSample::ClampZ>(\n                dstValues, srcValues, velFieldT0, velFieldT1, deltaTime, settings);\n\n        } else if ( settings._borderX != AdvectionBorder::Wrap \n            &&      settings._borderY != AdvectionBorder::Wrap \n            &&      settings._borderZ == AdvectionBorder::Wrap) {\n\n            PerformAdvection_Internal<RNFSample::ClampX|RNFSample::ClampY|RNFSample::WrapZ>(\n                dstValues, srcValues, velFieldT0, velFieldT1, deltaTime, settings);\n\n        } else if ( settings._borderX == AdvectionBorder::Wrap \n            &&      settings._borderY == AdvectionBorder::Wrap \n            &&      settings._borderZ == AdvectionBorder::Wrap) {\n\n            PerformAdvection_Internal<RNFSample::WrapX|RNFSample::WrapY|RNFSample::WrapZ>(\n                dstValues, srcValues, velFieldT0, velFieldT1, deltaTime, settings);\n\n        } else if ( settings._borderX == AdvectionBorder::Wrap \n            &&      settings._borderY == AdvectionBorder::Wrap \n            &&      settings._borderZ != AdvectionBorder::Wrap) {\n\n            PerformAdvection_Internal<RNFSample::WrapX|RNFSample::WrapY|RNFSample::ClampZ>(\n                dstValues, srcValues, velFieldT0, velFieldT1, deltaTime, settings);\n\n        } else {\n\n            assert(settings._borderX != AdvectionBorder::Wrap && settings._borderY != AdvectionBorder::Wrap && settings._borderZ != AdvectionBorder::Wrap);\n            PerformAdvection_Internal<RNFSample::ClampX|RNFSample::ClampY|RNFSample::ClampZ>(\n                dstValues, srcValues, velFieldT0, velFieldT1, deltaTime, settings);\n\n        }\n    }\n\n    AdvectionSettings::AdvectionSettings()\n    {\n        _method = AdvectionMethod::MacCormackRK4;\n        _interpolation = AdvectionInterp::Bilinear;\n        _subSteps = 4;\n        _borderX = AdvectionBorder::Margin; \n        _borderY = AdvectionBorder::Margin; \n        _borderZ = AdvectionBorder::Margin;\n    }\n\n    AdvectionSettings::AdvectionSettings(\n        AdvectionMethod method,\n        AdvectionInterp interpolation,\n        unsigned        subSteps,\n        AdvectionBorder borderX, AdvectionBorder borderY, AdvectionBorder borderZ)\n    {\n        _method = method;\n        _interpolation = interpolation;\n        _subSteps = subSteps;\n        _borderX = borderX;\n        _borderY = borderY;\n        _borderZ = borderZ;\n    }\n\n    template void PerformAdvection(\n        ScalarField2D, ScalarField2D, \n        VectorField2D, VectorField2D,\n        float, const AdvectionSettings&);\n\n    template void PerformAdvection(\n        VectorField2D, VectorField2D, \n        VectorField2D, VectorField2D,\n        float, const AdvectionSettings&);\n\n    template void PerformAdvection(\n        ScalarField3D, ScalarField3D, \n        VectorField3D, VectorField3D,\n        float, const AdvectionSettings&);\n\n    template void PerformAdvection(\n        VectorField3D, VectorField3D, \n        VectorField3D, VectorField3D,\n        float, const AdvectionSettings&);\n}\n\n", "meta": {"hexsha": "4ff742353a538faf7d6e846ef06c17455cfff592", "size": 23567, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SceneEngine/FluidAdvection.cpp", "max_stars_repo_name": "alexgithubber/XLE-Another-Fork", "max_stars_repo_head_hexsha": "cdd8682367d9e9fdbdda9f79d72bb5b1499cec46", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SceneEngine/FluidAdvection.cpp", "max_issues_repo_name": "alexgithubber/XLE-Another-Fork", "max_issues_repo_head_hexsha": "cdd8682367d9e9fdbdda9f79d72bb5b1499cec46", "max_issues_repo_licenses": ["MIT"], "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/FluidAdvection.cpp", "max_forks_repo_name": "alexgithubber/XLE-Another-Fork", "max_forks_repo_head_hexsha": "cdd8682367d9e9fdbdda9f79d72bb5b1499cec46", "max_forks_repo_licenses": ["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.9300847458, "max_line_length": 169, "alphanum_fraction": 0.5772902788, "num_tokens": 5501, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527631, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.46047924416389197}}
{"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/**\n * \\file\n * \\brief test core essential matrix class\n */\n\n#include <test_eigen.h>\n\n#include <vital/types/fundamental_matrix.h>\n\n#include <Eigen/SVD>\n\nusing namespace kwiver::vital;\n\n// ----------------------------------------------------------------------------\nint main(int argc, char** argv)\n{\n  ::testing::InitGoogleTest( &argc, argv );\n  return RUN_ALL_TESTS();\n}\n\n// ----------------------------------------------------------------------------\nTEST(fundamental_matrix, rank)\n{\n  matrix_3x3d mat_rand = matrix_3x3d::Random();\n  fundamental_matrix_d fm{ mat_rand };\n\n  matrix_3x3d mat = fm.matrix();\n\n  Eigen::JacobiSVD<matrix_3x3d> svd{ mat, Eigen::ComputeFullV |\n                                          Eigen::ComputeFullU };\n  auto const& S = svd.singularValues();\n\n  EXPECT_GE( S[0], 0.0 ) << \"Singular values should be non-negative\";\n  EXPECT_GE( S[1], 0.0 ) << \"Singular values should be non-negative\";\n  EXPECT_NEAR( 0.0, S[2], 1e-14 ) << \"Last singular value should be zero\";\n\n  EXPECT_MATRIX_NEAR( mat, fundamental_matrix_d{ mat }.matrix(), 1e-14 )\n    << \"Constructor from matrix not consistent with matrix accessor\";\n}\n", "meta": {"hexsha": "0ef5231ab36dcd2f288f854beaa3de534ff8001e", "size": 1338, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "vital/tests/test_fundamental_matrix.cxx", "max_stars_repo_name": "mwoehlke-kitware/kwiver", "max_stars_repo_head_hexsha": "614a488bd2b7fe551ac75eec979766d882709791", "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": "vital/tests/test_fundamental_matrix.cxx", "max_issues_repo_name": "mwoehlke-kitware/kwiver", "max_issues_repo_head_hexsha": "614a488bd2b7fe551ac75eec979766d882709791", "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": "vital/tests/test_fundamental_matrix.cxx", "max_forks_repo_name": "mwoehlke-kitware/kwiver", "max_forks_repo_head_hexsha": "614a488bd2b7fe551ac75eec979766d882709791", "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": 30.4090909091, "max_line_length": 79, "alphanum_fraction": 0.6016442451, "num_tokens": 331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7310585903489892, "lm_q2_score": 0.6297746143530796, "lm_q1q2_score": 0.46040214180654065}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// statistics::survival::data::data::event.hpp                               //\n//                                                                           //\n//  Copyright 2009 Erwann Rogard. Distributed under the Boost                //\n//  Software License, Version 1.0. (See accompanying file                    //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)         //\n///////////////////////////////////////////////////////////////////////////////\n#ifndef BOOST_STATISTICS_SURVIVAL_DATA_DATA_EVENT_HPP_ER_2009\n#define BOOST_STATISTICS_SURVIVAL_DATA_DATA_EVENT_HPP_ER_2009\n#include <limits>\n#include <ostream>\n#include <boost/format.hpp>\n#include <boost/operators.hpp>\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/archive/text_iarchive.hpp>\n#include <boost/statistics/survival/constant.hpp>\n#include <boost/arithmetic/equal.hpp>\n\nnamespace boost {\nnamespace statistics{\nnamespace survival {\nnamespace data {\n\n    // Abstraction for failure indicator and event time.\n    //\n    // B == T can be useful to represent a proportion of failures (see\n    // mean_event)\n    template<typename T,typename B = bool>\n    class event : equality_comparable<event<T,B> >{\n        typedef constant<T> const_;\n        public:\n        typedef T value_type;\n        typedef B failure_type;\n        // Construction \n        event(); //  (f = false, t = infinity)\n        explicit event(B isf,value_type rt);\n        event(const event&);\n        event& operator=(const event&);\n\n        // Access \n        B failure()const;\n        value_type time()const;\n    \n        // Operators \n        bool operator==(const event&);\n        \n        protected:\n        friend class boost::serialization::access;\n        \n        template<class Archive>\n        void serialize(Archive & ar, const unsigned int version);\n                \n        B failure_;         //!censored\n        value_type time_;   //since entry time\n    };\n\n\n    template<typename T,typename B>\n    std::ostream& operator<<(std::ostream& out,const event<T,B>& e);\n    \n    // Implementation //\n    \n    \n    //Construct\n    template<typename T,typename B>\n    event<T,B>::event():failure_(false),time_(const_::inf_){}\n    \n    template<typename T,typename B>\n    event<T,B>::event(B isf,value_type rt)\n    :failure_(isf),time_(rt){}\n\n    template<typename T,typename B>\n    event<T,B>::event(const event& that)\n    :failure_(that.failure_),time_(that.time_){}\n\n    template<typename T,typename B>\n    event<T,B>& \n    event<T,B>::operator=(const event& that){\n        if(&that!=this){\n            failure_ = (that.failure_);\n            time_ = (that.time_);            \n        }\n        return *this;\n    }\n\n    template<typename T,typename B>\n    std::ostream& operator<<(std::ostream& out,const event<T,B>& e){\n        static const char* str = \"(%1%,%2%)\";\n        format f(str);\n        f % e.failure() % e.time();\n        out << f.str();\n        return out;\n    }\n            \n    template<typename T,typename B>\n    B event<T,B>::failure()const{ return failure_; }\n\n    template<typename T,typename B>\n    typename event<T,B>::value_type event<T,B>::time()const{ \n        return time_;\n    }\n\n    template<typename T,typename B>\n    template<class Archive>\n    void event<T,B>::serialize(Archive & ar, const unsigned int version)\n    {\n        ar & failure_;\n        ar & time_;\n    }\n\n    // Operators\n    template<typename T,typename B>\n    bool event<T,B>::operator==(const event& e){\n        bool eq_1 = arithmetic_tools::equal(\n            e.time(),\n            (this->time())\n        );\n        bool eq_2 = arithmetic_tools::equal(\n            (this->failure_) , (e.failure())\n        );\n        return  (eq_1 && eq_2);    \n    }\n\n}// data\n}// survival\n}// statistics\n}// boost\n\n#endif", "meta": {"hexsha": "085cc668b9bd8b55f1d1871e0215e38e25e8687e", "size": 3865, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "survival_data copy/boost/statistics/survival/data/data/event.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": "survival_data copy/boost/statistics/survival/data/data/event.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": "survival_data copy/boost/statistics/survival/data/data/event.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": 29.9612403101, "max_line_length": 79, "alphanum_fraction": 0.5547218629, "num_tokens": 847, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.4604021395061039}}
{"text": "#include <Eigen/Dense>\n#include <vector>\n#include <algorithm>\n#include \"geometryUtil.hpp\"\n#include \"privdef.hpp\"\n\n\nstd::vector<Eigen::Vector3f> cornersWorkspaceAll(const Eigen::Vector3f& corner0, const Eigen::Vector3f& corner1) {\n\tstd::vector<Eigen::Vector3f> corners;\n\tint index[3];\n\tfor (int i = 0; i < 8; i++) { // for the number of the corners\n\t\tint res = i;\n\t\tfor (int j = 0; j < 3; j++) { // for x, y, z\n\t\t\tindex[j] = res % 2;\n\t\t\tres /= 2;\n\t\t}\n\t\tfloat x = (index[0] == 0 ? corner0.x() : corner1.x());\n\t\tfloat y = (index[1] == 0 ? corner0.y() : corner1.y());\n\t\tfloat z = (index[2] == 0 ? corner0.z() : corner1.z());\n\t\tcorners.push_back(Eigen::Vector3f(x, y, z));\n\t}\n\treturn corners;\n}\n\nstd::vector<float> range2Points(const Eigen::Vector3f& pos_self, const Eigen::Quaternionf& quo_self, std::vector<Eigen::Vector3f> const& points) {\n\tstd::vector<float> ranges;\n\tstd::for_each(points.begin(), points.end(), [&ranges, &pos_self, &quo_self](Eigen::Vector3f point) {\n\t\tranges.push_back((point - pos_self).dot(quo_self * Eigen::Vector3f::UnitZ()));\n\t\t});\n\treturn ranges;\n}\n\nnamespace dynaman {\n\tbool isInsideWorkspace(const Eigen::Vector3f& pos, const Eigen::Vector3f& lowerbound, const Eigen::Vector3f& upperbound) {\n\t\tEigen::Vector3f v0 = pos - lowerbound;\n\t\tEigen::Vector3f v1 = pos - upperbound;\n\t\treturn (v0.x() * v1.x() <= 0) && (v0.y() * v1.y() <= 0) && (v0.z() * v1.z() <= 0);\n\t}\n\n\tEigen::Matrix3f RotForDeviceId(int device_id, autd::GeometryPtr geo) {\n\t\tEigen::Vector3f pos_origin = geo->position(device_id * NUM_TRANS_IN_UNIT);\n\t\tEigen::Vector3f pos_trans_on_xaxis = geo->position(device_id * NUM_TRANS_IN_UNIT + NUM_TRANS_X - 1);\n\t\tEigen::Vector3f pos_trans_on_yaxis = geo->position((device_id + 1) * NUM_TRANS_IN_UNIT - NUM_TRANS_X);\n\t\tEigen::Vector3f unitX_device = (pos_trans_on_xaxis - pos_origin).normalized();\n\t\tEigen::Vector3f unitY_device = (pos_trans_on_yaxis - pos_origin).normalized();\n\t\tEigen::Vector3f unitZ_device = geo->direction(device_id * NUM_TRANS_IN_UNIT);\n\t\tEigen::Matrix3f rot;\n\t\trot << unitX_device, unitY_device, unitZ_device;\n\t\treturn rot;\n\t}\n\n\tstd::vector<Eigen::Matrix3f> RotsAutd(autd::GeometryPtr geo) {\n\t\tstd::vector<Eigen::Matrix3f> rots(geo->numDevices());\n\t\tfor (auto itr_device = rots.begin(); itr_device != rots.end(); itr_device++) {\n\t\t\t*itr_device = RotForDeviceId(std::distance(rots.begin(), itr_device), geo);\n\t\t}\n\t\treturn rots;\n\t}\n\n\tstd::vector<Eigen::Matrix3f> RotsAutd(std::shared_ptr<autd::Controller> pAupa) {\n\t\treturn RotsAutd(pAupa->geometry());\n\t}\n\n\tEigen::Vector3f CenterForDeviceId(int deviceId, autd::GeometryPtr geo) {\n\t\tEigen::Vector3f center_local(TRANS_SIZE_MM * (NUM_TRANS_X / 2 - 0.5f), TRANS_SIZE_MM * (NUM_TRANS_Y / 2 - 0.5f), 0.f);\n\t\treturn  RotForDeviceId(deviceId, geo) * center_local + geo->position(NUM_TRANS_IN_UNIT * deviceId);\n\t}\n\n\tEigen::Matrix3Xf CentersAutd(autd::GeometryPtr geo) {\n\t\tEigen::Matrix3Xf centers(3, geo->numDevices());\n\t\tfor (int i_autd = 0; i_autd < geo->numDevices(); i_autd++) {\n\t\t\tcenters.col(i_autd) = CenterForDeviceId(i_autd, geo);\n\t\t}\n\t\treturn centers;\n\t}\n\n\tEigen::Matrix3Xf DirectionsAutd(autd::GeometryPtr geo) {\n\t\tEigen::Matrix3Xf directions;\n\t\tdirections.resize(3, geo->numDevices());\n\t\tfor (int i_col = 0; i_col < directions.cols(); i_col++) {\n\t\t\tdirections.col(i_col) = geo->direction(i_col * NUM_TRANS_IN_UNIT);\n\t\t}\n\t\treturn directions;\n\t}\n}", "meta": {"hexsha": "c36c1fdf4be06c8e239bc9c424411ac773b3e4f6", "size": 3350, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/geometryUtil.cpp", "max_stars_repo_name": "shinolab/dynamic-manipulation", "max_stars_repo_head_hexsha": "d43bae688cecf87e15605ed6a9dbc80a782d72fc", "max_stars_repo_licenses": ["MIT"], "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/geometryUtil.cpp", "max_issues_repo_name": "shinolab/dynamic-manipulation", "max_issues_repo_head_hexsha": "d43bae688cecf87e15605ed6a9dbc80a782d72fc", "max_issues_repo_licenses": ["MIT"], "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/geometryUtil.cpp", "max_forks_repo_name": "shinolab/dynamic-manipulation", "max_forks_repo_head_hexsha": "d43bae688cecf87e15605ed6a9dbc80a782d72fc", "max_forks_repo_licenses": ["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.4117647059, "max_line_length": 146, "alphanum_fraction": 0.6901492537, "num_tokens": 1089, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.731058578630005, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.4604021293463399}}
{"text": "/*\nBSD 3-Clause License\n\nCopyright (c) 2020, Mihai Francu\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\n   list of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright notice,\n   this list of conditions and the following disclaimer in the documentation\n   and/or other materials provided with the distribution.\n\n3. 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#include \"FemPhysicsMatrixFree.h\"\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <Eigen/Eigenvalues>\n#include <Engine/Profiler.h>\n#include \"PolarDecomposition.h\"\n#include \"ElasticEnergy.h\"\n#include \"LinearSolver.h\"\n#include \"NewtonSolver.h\"\n#include \"NonlinearCG.h\"\n#include <iostream>\n\n#pragma warning( disable : 4267) // for size_t-uint conversions\n\n// Bibliography:\n// [Sifakis] Sifakis, E., The classical FEM method and discretization methodology, Siggraph course, 2012\n// [Teran03] Teran, J. et al., Finite Volume Method for the Simulation of Skeletal Muscle, Eurographics, 2003\n// [Teran03] Teran, J. et al., Robust Quasistatic Finite Elements and Flesh Simulation, Eurographics, 2005\n// [Mueller] Mueller, M. et al., Real Time Physics Class Notes, Chapter 4 - The finite element method, Siggraph course, 2008\n// [Bonet] Bonet, J., Wood, R.D., Nonlinear Continuum Mechanics for Finite Element Analysis\n// [Erleben] Erleben, K. et al., Physics-based animation\n\n// We are using explicit FEM: lumped masses (particle masses) and lumped body forces (particle forces)\n// Also, it is geometrically linear FEM: all elements are linear displacement/constant strain tetrahedra\n// P or PK1 is the first Piola-Kirchoff tensor\n// S or PK2 is the second Piola-Kirchoff tensor\n\n//#define CACHED_STIFFNESS_MATRIX\n\nnamespace FEM_SYSTEM\n{\n\t// node indices for each face\n\tint faces[4][3] = {\n\t\t\t{ 1, 2, 3 },\n\t\t\t{ 0, 2, 3 },\n\t\t\t{ 0, 1, 3 },\n\t\t\t{ 0, 1, 2 } };\n\n\tFemPhysicsMatrixFree::FemPhysicsMatrixFree(const std::vector<Tet>& tetrahedra,\n\t\tconst std::vector<Node>& allNodes, const FemConfig& config)\n\t\t: FemPhysicsBase(config)\n\t\t, nodes(allNodes)\n\t\t, hasCollisions(false)\n\t{\n\t\ttets.resize(tetrahedra.size());\n\t\tfor (size_t i = 0; i < tets.size(); i++)\n\t\t{\n\t\t\tTetrahedron& tet = tets.at(i);\n\n\t\t\ttet.i[0] = tetrahedra[i].idx[0];\n\t\t\ttet.i[1] = tetrahedra[i].idx[1];\n\t\t\ttet.i[2] = tetrahedra[i].idx[2];\n\t\t\ttet.i[3] = tetrahedra[i].idx[3];\n\t\t}\n\n#ifndef USE_CONSTRAINT_BCS\n\t\tReshuffleFixedNodes();\n#else\n\t\tmNumBCs = 0;\n\t\tmReshuffleMap.resize(nodes.size());\n\t\tfor (uint32 i = 0; i < nodes.size(); i++)\n\t\t{\n\t\t\tmReshuffleMap[i] = i;\n\t\t\tif (nodes[i].invMass == 0)\n\t\t\t{\n\t\t\t\tnodes[i].invMass = 1;\n\t\t\t\tAddDirichletBC(i, AXIS_X | AXIS_Y | AXIS_Z);\n\t\t\t}\n\t\t}\n#endif\n\n\t\tif (config.mCustomConfig != nullptr)\n\t\t{\n\t\t\tconst Config* cfg = (Config*)config.mCustomConfig;\n\t\t\tmConfig = *cfg;\n\t\t}\n\n\t\t// damping params (partial Rayleigh damping: we reuse the matrix structure from the stiffness matrix)\n\t\t// TODO: use Rayleigh damping params instead\n\t\ted = config.mDampingYoungsModulus;\n\t\tnud = config.mDampingPoissonRatio;\n\t\treal omnd = 1.f - nud;\n\t\treal om2nd = 1.f - 2 * nud;\n\t\treal fd = ed / (1.f + nud) / om2nd;\n\t\tEd = fd * Matrix3R(omnd, nud, nud,\n\t\t\tnud, omnd, nud,\n\t\t\tnud, nud, omnd);\n\n\t\t// prepare the vector of lumped masses\n\t\tstd::vector<real> masses(nodes.size(), 0.f);\n\n\t\t// init the test and shape matrices\n\t\tmTotalInitialVol = 0;\n\t\tfor (size_t i = 0; i < tets.size(); i++)\n\t\t{\n\t\t\tTetrahedron& tet = tets.at(i);\n\t\t\tconst Vector3R& x0 = nodes.at(tet.i[0]).pos0;\n\t\t\tconst Vector3R& x1 = nodes.at(tet.i[1]).pos0;\n\t\t\tconst Vector3R& x2 = nodes.at(tet.i[2]).pos0;\n\t\t\tconst Vector3R& x3 = nodes.at(tet.i[3]).pos0;\n\t\t\tVector3R d1 = x1 - x0;\n\t\t\tVector3R d2 = x2 - x0;\n\t\t\tVector3R d3 = x3 - x0;\n\t\t\tMatrix3R mat(d1, d2, d3); // this is the reference shape matrix Dm [Sifakis][Teran03]\n\t\t\ttet.X = mat.GetInverse(); // Dm^-1\n\t\t\ttet.Xtr = !tet.X; // Dm^-T; pre-stored but could not be for saving memory\n\t\t\ttet.vol = (mat.Determinant()) / 6.f; // signed volume of the tet\n\t\t\tmTotalInitialVol += tet.vol;\n\n\t\t\treal lumpedMass = 0.25f * tet.vol * config.mDensity;\n\t\t\tmasses[tet.i[0]] += lumpedMass;\n\t\t\tmasses[tet.i[1]] += lumpedMass;\n\t\t\tmasses[tet.i[2]] += lumpedMass;\n\t\t\tmasses[tet.i[3]] += lumpedMass;\n\n\t\t\t// compute face areas\n\t\t\tVector3R b[4];\n\t\t\tfor (int j = 0; j < 4; j++)\n\t\t\t{\n\t\t\t\tint i1 = faces[j][0];\n\t\t\t\tint i2 = faces[j][1];\n\t\t\t\tint i3 = faces[j][2];\n\n\t\t\t\tint j1 = tet.i[i1];\n\t\t\t\tint j2 = tet.i[i2];\n\t\t\t\tint j3 = tet.i[i3];\n\t\t\t\tint j4 = tet.i[j];\n\n\t\t\t\ttet.NA[j] = cross(nodes[j2].pos - nodes[j1].pos, nodes[j3].pos - nodes[j1].pos);\n\t\t\t\tif (dot(tet.NA[j], nodes[j4].pos - nodes[j1].pos) > 0)\n\t\t\t\t\ttet.NA[j].Flip();\n\n\t\t\t\tVector3R splitFaceForce = (-1.f / 6.f) * tet.NA[j];\n\t\t\t\tb[i1] += splitFaceForce;\n\t\t\t\tb[i2] += splitFaceForce;\n\t\t\t\tb[i3] += splitFaceForce;\n\t\t\t}\n\t\t\t//tet.Bm = Matrix3R(b[1], b[2], b[3]);\n\t\t\t\n\t\t\t// compute the gradient of the shape functions [Erleben]\n\t\t\tVector3R y[4];\n\t\t\ty[1] = tet.X[0];\n\t\t\ty[2] = tet.X[1];\n\t\t\ty[3] = tet.X[2];\n\t\t\ty[0] = y[1] + y[2] + y[3];\n\t\t\ty[0].Flip();\n\n\t\t\t// compute the Cauchy strain Jacobian matrix according to [Mueller]: H = de/dx\n\t\t\tfor (int j = 0; j < 4; j++)\n\t\t\t{\n\t\t\t\ttet.Hn[j] = Matrix3R(y[j]);\n\t\t\t\ttet.Hs[j] = Matrix3R(0, y[j].Z(), y[j].Y(),\n\t\t\t\t\ty[j].Z(), 0, y[j].X(),\n\t\t\t\t\ty[j].Y(), y[j].X(), 0);\n\t\t\t}\n\t\t\t\n\t\t\t// for linear FEM we can actually precompute the tangent stiffness matrix\n\t\t\treal s = mYoungsModulus / (1.f + mPoissonRatio);\n\t\t\tfor (int j = 0; j < 4; j++)\n\t\t\t{\n\t\t\t\tfor (int k = 0; k < 4; k++)\n\t\t\t\t{\n\t\t\t\t\ttet.K[j][k] = tet.vol * (tet.Hn[j] * mNormalElasticityMatrix * tet.Hn[k] + s * tet.Hs[j] * (!tet.Hs[k]));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// set masses\n\t\tfor (size_t i = 0; i < nodes.size(); i++)\n\t\t{\n\t\t\tif (nodes[i].invMass != 0 && masses[i] != 0)\n\t\t\t\tnodes[i].invMass = 1.f / masses[i];\n\t\t}\n\n\t\tlambdaAcc.resize(tets.size());\n\t\tdH.resize(tets.size());\n\n\t\tmForces.resize(nodes.size());\n\n\t\tBuildMassMatrix();\n\t}\n\n\tvoid FemPhysicsMatrixFree::BuildMassMatrix()\n\t{\n\t\t// build lumped mass matrix\n\t\tuint32 numDofs = GetNumFreeNodes() * 3;\n\t\tmMassMatrix.resize(numDofs, numDofs);\n\t\tfor (uint32 i = 0; i < GetNumFreeNodes(); i++)\n\t\t{\n\t\t\treal mass = 1.f / nodes[i + mNumBCs].invMass;\n\t\t\tmMassMatrix.coeffRef(i * 3, i * 3) = mass;\n\t\t\tmMassMatrix.coeffRef(i * 3 + 1, i * 3 + 1) = mass;\n\t\t\tmMassMatrix.coeffRef(i * 3 + 2, i * 3 + 2) = mass;\n\t\t}\n\t}\n\n\tvoid FemPhysicsMatrixFree::ReshuffleFixedNodes()\n\t{\n\t\tstd::vector<Node> newNodes;\n\t\tmReshuffleMap.resize(nodes.size()); // map from old indices to new ones\n\t\t// add fixed nodes first\n\t\tmNumBCs = 0;\n\t\tfor (size_t i = 0; i < nodes.size(); i++)\n\t\t{\n\t\t\tif (nodes[i].invMass == 0)\n\t\t\t{\n\t\t\t\tmReshuffleMap[i] = newNodes.size();\n\t\t\t\tnewNodes.push_back(nodes[i]);\n\t\t\t\tmNumBCs++;\n\t\t\t}\n\t\t}\n\t\t// then the other nodes\n\t\tfor (size_t i = 0; i < nodes.size(); i++)\n\t\t{\n\t\t\tif (nodes[i].invMass != 0)\n\t\t\t{\n\t\t\t\tmReshuffleMap[i] = newNodes.size();\n\t\t\t\tnewNodes.push_back(nodes[i]);\n\t\t\t}\n\t\t}\n\t\tnodes = newNodes; // replace old nodes with shuffled ones\n\t\t// remap tets\n\t\toriginalTets = tets;\n\t\tfor (size_t i = 0; i < tets.size(); i++)\n\t\t{\n\t\t\tfor (int j = 0; j < 4; j++)\n\t\t\t{\n\t\t\t\ttets[i].i[j] = mReshuffleMap[tets[i].i[j]];\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid FemPhysicsMatrixFree::AddCable(const Cable& cable)\n\t{\n\t\tFemPhysicsBase::AddCable(cable);\n\t\t// add new DOF nodes for the unattached spring nodes\n\t\tCable& currCable = mCables[mCables.size() - 1];\n\t\tmNumSpringNodes = 0;\n\t\tfor (uint32 i = 0; i < cable.mCableNodes.size(); i++)\n\t\t{\n\t\t\tint elem = cable.mCableNodes[i].elem;\n\t\t\tif (elem < 0)\n\t\t\t{\n\t\t\t\tconst Tetrahedron& tet = tets[-elem];\n\t\t\t\treal w0 = currCable.mCableNodes[i].bary.x;\n\t\t\t\treal w1 = currCable.mCableNodes[i].bary.y;\n\t\t\t\treal w2 = currCable.mCableNodes[i].bary.z;\n\t\t\t\treal w3 = 1 - w0 - w1 - w2;\n\t\t\t\treal invMass = w0 * nodes[tet.i[0]].invMass + w1 * nodes[tet.i[1]].invMass + w1 * nodes[tet.i[1]].invMass + w3 * nodes[tet.i[3]].invMass;\n\n\t\t\t\tcurrCable.mCableNodes[i].elem = -((int)nodes.size());\n\t\t\t\tNode node;\n\t\t\t\tnode.invMass = invMass; // TODO: average node mass\n\t\t\t\tnode.pos = currCable.mCablePositions[i];\n\t\t\t\tmReshuffleMap.push_back(nodes.size());\n\t\t\t\tnodes.push_back(node);\n\t\t\t\tmNumSpringNodes++;\n\t\t\t}\n\t\t}\n\t\t// rebuild the mass matrix\n\t\tBuildMassMatrix();\n\t\tmForces.resize(nodes.size());\n\t}\n\n\tvoid FemPhysicsMatrixFree::Step(real dt)\n\t{\n\t\tif (mSimType == ST_IMPLICIT)\n\t\t{\n\t\t\t// save positions before step - breaks dynamic Dirichlet BCs!\n\t\t\tfor (size_t i = 0; i < GetNumNodes(); i++)\n\t\t\t{\n\t\t\t\tnodes[i].pos0 = nodes[i].pos;\n\t\t\t}\n\t\t\t\n\t\t\treal h = dt / mNumSteps;\n\t\t\tfor (int i = 0; i < mNumSteps; i++)\n\t\t\t{\n\t\t\t\tmTimeStep = h;\n\t\t\t\tmForceFraction = 1;\n\t\t\t\tSolve();\n\t\t\t\tHandleCollisions(h);\n\t\t\t}\n\t\t}\n\t\telse if (mSimType == ST_EXPLICIT)\n\t\t{\n\t\t\treal h = dt / mNumSteps;\n\t\t\tmForceFraction = 1;\n\t\t\tfor (int i = 0; i < mNumSteps; i++)\n\t\t\t{\n\t\t\t\tSubStep(h);\n\t\t\t}\n\t\t}\n\t\telse if (mSimType == ST_STATIC)\n\t\t{\n\t\t\tif (mForceFraction == 0)\n\t\t\t{\n\t\t\t\tmForceFraction = 1;\n\t\t\t\tSolve();\t\t\t\t\n\t\t\t}\n\t\t}\n\t\telse if (mSimType == ST_QUASI_STATIC)\n\t\t{\n\t\t\tif (mForceFraction < 1)\n\t\t\t{\t\n\t\t\t\tmForceFraction = std::min(real(1), mForceFraction + mForceStep);\n\t\t\t\tSolve();\n\t\t\t}\n\t\t}\n\n\t}\n\n\tvoid FemPhysicsMatrixFree::UpdatePositions(std::vector<Node>& newNodes)\n\t{\n\t\t// TODO: use mNumBCs and mReshuffleMapInv\n\t\tfor (size_t i = 0; i < newNodes.size(); i++)\n\t\t{\n\t\t\tif (newNodes[i].invMass == 0)\n\t\t\t\tnodes[mReshuffleMap[i]].pos = newNodes[i].pos;\n\t\t}\n\t}\n\n\tvoid FemPhysicsMatrixFree::ComputeDeformationGradient(uint32 e, Matrix3R& F) const\n\t{\n\t\tconst Tetrahedron& tet = tets[e];\n\t\t// compute deformed/spatial shape matrix Ds [Sifakis]\n\t\tconst Vector3R& x0 = nodes.at(tet.i[0]).pos;\n\t\tconst Vector3R& x1 = nodes.at(tet.i[1]).pos;\n\t\tconst Vector3R& x2 = nodes.at(tet.i[2]).pos;\n\t\tconst Vector3R& x3 = nodes.at(tet.i[3]).pos;\n\t\tVector3R d1 = x1 - x0;\n\t\tVector3R d2 = x2 - x0;\n\t\tVector3R d3 = x3 - x0;\n\t\tMatrix3R Ds(d1, d2, d3);\n\t\t// compute deformation gradient\n\t\tF = Ds * tet.X;\n\t}\n\n\t// simplest way of doing time dependent FEM - explicit integration of the discretized system\n\tvoid FemPhysicsMatrixFree::SubStep(real h)\n\t{\n\t\tfor (uint32 i = 0; i < mForces.size(); i++)\n\t\t\tmForces[i].SetZero();\n\t\tElasticEnergy::ComputeForces(this, mForces);\n\n\t\tComputeSpringForces(mForces);\n\n\t\t// integrate node velocities and positions using Symplectic Euler\n\t\tfor (size_t i = 0; i < nodes.size(); i++)\n\t\t{\n\t\t\tif (nodes[i].invMass == 0)\n\t\t\t\tcontinue;\n\t\t\tnodes[i].vel += (h * nodes[i].invMass) * mForces[i] + h * mGravity;\n\t\t\tnodes[i].pos += h * nodes[i].vel;\n\t\t}\n\t}\n\n\tinline void AddMatrix3(EigenMatrix& K, int n, int m, const Matrix3R& Ke, real h2)\n\t{\n\t\tint nn = 3 * n;\n\t\tint mm = 3 * m;\n\t\tfor (int i = 0; i < 3; i++)\n\t\t{\n\t\t\tfor (int j = 0; j < 3; j++)\n\t\t\t{\n#ifdef SPARSE\n\t\t\t\tK.coeffRef(nn + i, mm + j) -= h2 * Ke.m[i][j];\n#else\n\t\t\t\tK(nn + i, mm + j) -= h2 * Ke.m[i][j];\n#endif\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid FemPhysicsMatrixFree::ComputeForceDifferential(const std::vector<Vector3R>& dx, std::vector<Vector3R>& df) const\n\t{\n\t\tPROFILE_SCOPE(\"Differential\");\n\t\tmemset(&df[0], 0, df.size() * sizeof(Vector3R));\n\n\t\t// Lame coefficients\n\t\tconst real mu = GetShearModulus();\n\t\tconst real lambda = GetLameFirstParam();\n\n\t\tMatrix3R id;\n\t\tVector3R zero;\n\t\t#pragma omp parallel for\n\t\tfor (int i = 0; i < (int)tets.size(); i++)\n\t\t{\n\t\t\tconst Tetrahedron& tet = tets.at(i);\n\t\t\t// compute deformation gradient increment dF\n\t\t\tconst Vector3R& x0 = tet.i[0] < mNumBCs ? zero : dx[tet.i[0] - mNumBCs];\n\t\t\tconst Vector3R& x1 = tet.i[1] < mNumBCs ? zero : dx[tet.i[1] - mNumBCs];\n\t\t\tconst Vector3R& x2 = tet.i[2] < mNumBCs ? zero : dx[tet.i[2] - mNumBCs];\n\t\t\tconst Vector3R& x3 = tet.i[3] < mNumBCs ? zero : dx[tet.i[3] - mNumBCs];\n\t\t\tVector3R d1 = x1 - x0;\n\t\t\tVector3R d2 = x2 - x0;\n\t\t\tVector3R d3 = x3 - x0;\n\t\t\tMatrix3R mat(d1, d2, d3);\n\t\t\tMatrix3R dF = mat * tet.X;\n\n\t\t\tMatrix3R F;\n\t\t\tComputeDeformationGradient(i, F); // we don't need it for linear, but never mind\n\n\t\t\tMatrix3R dP;\n\t\t\tif (mMaterial == MMT_LINEAR || mMaterial == MMT_DISTORTIONAL_LINEAR)\n\t\t\t{\n\t\t\t\t// stress differential - linear elasticity\n\t\t\t\tdP = mu * (dF + !dF) + lambda * dF.Trace() * id;\n\t\t\t}\n\t\t\telse if (mMaterial == MMT_COROTATIONAL)\n\t\t\t{\n\t\t\t\t// corotational\n\t\t\t\tMatrix3R R, S;\n\t\t\t\tComputePolarDecomposition(F, R, S);\n\t\t\t\tMatrix3R dS = !R * dF;\n\t\t\t\tdP = 2 * mu * dF + lambda * dS.Trace() * R;\n\t\t\t\t// nonlinear correction term - comment below to obtain the implicit corotational method in [Mueller]\n\t\t\t\treal trS = S.Trace();\n\t\t\t\tMatrix3R A = S - trS * id;\n\t\t\t\tVector3R w(dS(1, 2) - dS(2, 1), dS(0, 2) - dS(2, 0), dS(0, 1) - dS(1, 0));\n\t\t\t\tVector3R r = A.GetInverse() * w;\n\t\t\t\tMatrix3R X = Matrix3R::Skew(r);\n\t\t\t\tMatrix3R dR = R * X;\n\t\t\t\tdP = dP + (lambda * (trS - 3) - 2 * mu) * dR;\n\t\t\t}\n\t\t\telse if (mMaterial == MMT_STVK)\n\t\t\t{\n\t\t\t\tMatrix3R E = 0.5f * (!F * F - id);\n\t\t\t\tMatrix3R dE = 0.5f * (!dF * F + !F * dF);\n\t\t\t\tdP = dF * (2 * mu * E + lambda * E.Trace() * id)\n\t\t\t\t\t+ F * (2 * mu * dE + lambda * dE.Trace() * id);\n\t\t\t}\n\t\t\telse if (mMaterial == MMT_NEO_HOOKEAN)\n\t\t\t{\n\t\t\t\tMatrix3R Finv = F.GetInverse();\n\t\t\t\tMatrix3R Finvtr = !Finv;\n\t\t\t\treal J = F.Determinant();\n\t\t\t\tdP = mu * dF + (mu - lambda * log(J)) * Finvtr * !dF * Finvtr + lambda * (Finv * dF).Trace() * Finvtr;\n\t\t\t}\n\n\t\t\t// compute the double contraction of dF and dP to check PD\n\t\t\t//real indicator = Matrix3R::DoubleContraction(dF, dP);\n\t\t\t//if (indicator < 0)\n\t\t\t//{\n\t\t\t//\tPrintf(\"Stiffness matrix is not PD (dF:dP = %g).\\n\", indicator);\n\t\t\t//}\n\n\t\t\tdH[i] = -tet.vol * dP * tet.Xtr;\n\t\t}\n\n\t\tfor (size_t i = 0; i < tets.size(); i++)\n\t\t{\n\t\t\tconst Tetrahedron& tet = tets.at(i);\n\t\t\tVector3R f3;\n\t\t\tfor (int j = 1; j < 4; j++)\n\t\t\t{\n\t\t\t\tVector3R f = dH[i](j - 1);\n\t\t\t\tif (tet.i[j] >= mNumBCs)\n\t\t\t\t\tdf[tet.i[j] - mNumBCs] += f;\n\t\t\t\tf3 -= f;\n\t\t\t}\n\t\t\tif (tet.i[0] >= mNumBCs)\n\t\t\t\tdf[tet.i[0]- mNumBCs] += f3;\n\t\t}\n\t}\n\n\treal FemPhysicsMatrixFree::GetTotalVolume() const\n\t{\n\t\treal totalVol = 0;\n\t\tfor (size_t e = 0; e < tets.size(); e++)\n\t\t{\n\t\t\t// compute current volume\n\t\t\tconst Tetrahedron& tet = tets.at(e);\n\t\t\tint i0 = tet.i[0];\n\t\t\tint i1 = tet.i[1];\n\t\t\tint i2 = tet.i[2];\n\t\t\tint i3 = tet.i[3];\n\t\t\tconst Vector3R& x0 = nodes.at(i0).pos;\n\t\t\tconst Vector3R& x1 = nodes.at(i1).pos;\n\t\t\tconst Vector3R& x2 = nodes.at(i2).pos;\n\t\t\tconst Vector3R& x3 = nodes.at(i3).pos;\n\t\t\tVector3R d1 = x1 - x0;\n\t\t\tVector3R d2 = x2 - x0;\n\t\t\tVector3R d3 = x3 - x0;\n\t\t\tMatrix3R mat(d1, d2, d3); // this is the spatial shape matrix Dm [Sifakis][Teran03]\n\t\t\treal vol = (mat.Determinant()) / 6.f; // signed volume of the tet\n\t\t\ttotalVol += vol;\n\t\t}\n\t\treturn totalVol;\n\t}\n\n\tvoid FemPhysicsMatrixFree::MatrixVectorMultiply(const std::vector<Vector3R>& d, std::vector<Vector3R>& df) const\n\t{\n\t\tPROFILE_SCOPE(\"Matrix mult\");\n\t\t// compute M * d / h^2 - K * d (only the second term for quasi-static, identified by mTimeStep = 0)\n\t\tComputeForceDifferential(d, df);\n\t\tconst real invHSqr = mTimeStep == 0 ? 0 : 1.f / (mTimeStep * mTimeStep);\n\t\tfor (size_t i = 0; i < GetNumFreeNodes(); i++)\n\t\t{\n\t\t\treal mass = 1.f / nodes[i + mNumBCs].invMass;\n\t\t\tdf[i] = invHSqr * mass * d[i] - df[i];\n\t\t}\n\t}\n\n\tvoid FemPhysicsMatrixFree::ComputeGradients(std::vector<Vector3R>& r)\n\t{\n\t\tPROFILE_SCOPE(\"Gradients\");\n\t\t// compute negative gradient r = f(x, v) + M * g\n\t\tfor (uint32 i = 0; i < mForces.size(); i++)\n\t\t\tmForces[i].SetZero();\n\t\tComputePressureForces(mForces, mTractionStiffnessMatrix);\n\t\tElasticEnergy::ComputeForces(this, mForces);\n\t\tComputeSpringForces(mForces);\n\t\tconst real invH = mTimeStep == 0 ? 0 : 1.f / mTimeStep;\n\t\tconst real invHSqr = mTimeStep == 0 ? 0 : 1.f / (mTimeStep * mTimeStep);\n\t\tfor (size_t i = 0; i < GetNumFreeNodes(); i++)\n\t\t{\n\t\t\tif (nodes[i + mNumBCs].invMass == 0)\n\t\t\t\tcontinue; // this is for USE_CONSTRAINT_BCS but does no harm\n\t\t\treal mass = 1.f / nodes[i + mNumBCs].invMass;\n\t\t\tr[i] = mForces[i + mNumBCs];\n\t\t\tr[i] += mass * mForceFraction * mGravity;\n\t\t\tif (i < GetNumFreeNodes() - mNumSpringNodes) // do not apply gravity or inertia to free cable nodes\n\t\t\t{\n\t\t\t\tr[i] += mass * invH * nodes[i + mNumBCs].vel;\n\t\t\t\tr[i] -= mass * invHSqr * (nodes[i + mNumBCs].pos - nodes[i + mNumBCs].pos0);\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid FemPhysicsMatrixFree::UpdatePosAndComputeGradients(const std::vector<Vector3R>& pos, std::vector<Vector3R>& r)\n\t{\n\t\tfor (size_t i = 0; i < GetNumFreeNodes(); i++)\n\t\t\tnodes[i + mNumBCs].pos = pos[i];\n\n\t\tComputeGradients(r);\n\t}\n\n\tbool FemPhysicsMatrixFree::Solve()\n\t{\n\t\tMEASURE_TIME(\"Nonlinear FEM solve\");\n\t\tPROFILE_SCOPE(\"Solve\");\n\n\t\tbool ret = true;\n\t\tif (mConfig.mSolver == NST_NEWTON)\n\t\t\tSolveNewton();\n\t\telse if (mConfig.mSolver == NST_NEWTON_LS)\n\t\t\tSolveNewtonLS();\n\t\telse if (mConfig.mSolver == NST_NEWTON_CG)\n\t\t\tSolveNewtonCG();\n\t\telse if (mConfig.mSolver == NST_NONLINEAR_CG)\n\t\t\tSolveNonlinearConjugateGradient();\n\t\telse if (mConfig.mSolver == NST_STEEPEST_DESCENT)\n\t\t\tSolveNonlinearSteepestDescent();\n\t\telse if (mConfig.mSolver == NST_GRADIENT_DESCENT)\n\t\t\tSolveGradientDescent(mConfig.mDescentRate);\n\n\t\tif (mTimeStep != 0 && mSimType == ST_IMPLICIT)\n\t\t{\n\t\t\t// compute new velocities\n\t\t\tconst real invH = 1.f / mTimeStep;\n\t\t\tfor (size_t i = 0; i < GetNumFreeNodes(); i++)\n\t\t\t{\n\t\t\t\tnodes.at(i + mNumBCs).vel = invH * (nodes[i + mNumBCs].pos - nodes[i + mNumBCs].pos0);\n\t\t\t}\n\t\t}\n\n\t\t//Printf(\"final energy: %g\\n\", ComputeEnergy());\n\n\t\treturn ret;\n\t}\n\n\tvoid FemPhysicsMatrixFree::SolveNewtonCG()\n\t{\n\t\tstd::vector<Vector3R> delta(GetNumFreeNodes()); // allocation!\n\t\tstd::vector<Vector3R> b(GetNumFreeNodes()); // allocation!\n\n\t\t// no need for Newton for linear elasticity\n\t\tint numIters = /*mMaterial == MMT_LINEAR ? 1 : */mOuterIterations;\n\n\t\t// Newton steps (outer loop)\n\t\tfor (int iter = 0; iter < numIters; iter++)\n\t\t{\n\t\t\tComputeGradients(b);\n\n\t\t\t// solve K * dx = b by Conjugate Gradient\n\t\t\tstd::fill(delta.begin(), delta.end(), Vector3R()); // reset the guess to zero; TODO: warm start\n\t\t\tSolveConjugateGradientMF<real, Vector3R, FemPhysicsMatrixFree>(*this, b, delta, mInnerIterations);\n\n\t\t\t// add dx\n\t\t\tfor (size_t i = 0; i < GetNumFreeNodes(); i++)\n\t\t\t{\n\t\t\t\t//mTotalDisplacements[i] += delta[i];\n\t\t\t\tnodes.at(i + mNumBCs).pos += delta[i];\n\t\t\t}\n\t\t}\n\t}\n\n\treal FemPhysicsMatrixFree::MeritResidual(const EigenVector& rhs)\n\t{\n\t\tif (mConfig.mOptimizer)\n\t\t\treturn ComputeEnergy();\n\t\telse\n\t\t\treturn 0.5 * rhs.squaredNorm();\n\t}\n\n\tEigenVector FemPhysicsMatrixFree::ComputeRhs(const EigenVector& sol)\n\t{\n\t\t// set node positions\n\t\tauto solVecs = GetStdVector(sol);\n\t\tASSERT(solVecs.size() == GetNumFreeNodes());\n\t\tfor (uint32 i = 0; i < GetNumFreeNodes(); i++)\n\t\t{\n\t\t\tnodes[i + mNumBCs].pos = solVecs[i];\n\t\t}\n\n\t\tstd::vector<Vector3R> b(GetNumFreeNodes()); // allocation!\n\t\tComputeGradients(b);\n\t\tEigenVector rhs = GetEigenVector(b);\n\n\t\t// add penalty Dirichlet BC forces\n\t\tif (!mDirichletIndices.empty())\n\t\t{\n\t\t\t// count the constraints\n\t\t\tint count = 0;\n\t\t\tfor (size_t i = 0; i < mDirichletIndices.size(); i++)\n\t\t\t{\n\t\t\t\tif (mDirichletAxes[i] & AXIS_X) count++;\n\t\t\t\tif (mDirichletAxes[i] & AXIS_Y) count++;\n\t\t\t\tif (mDirichletAxes[i] & AXIS_Z) count++;\n\t\t\t}\n\n\t\t\tEigenVector dirichletErrors(count);\n\t\t\tcount = 0;\n\t\t\tfor (uint32 i = 0; i < mDirichletIndices.size(); i++)\n\t\t\t{\n\t\t\t\t// the i'th BC\t\t\t\t\n\t\t\t\tuint32 flags = mDirichletAxes[i];\n\t\t\t\tuint32 idx0 = mDirichletIndices[i];\n\t\t\t\tuint32 idx = idx0 - mNumBCs; // affecting node idx\n\t\t\t\t// compute the BC error\n\t\t\t\tif (flags & AXIS_X)\n\t\t\t\t{\n\t\t\t\t\tdirichletErrors(count++) = nodes[idx].pos.x - nodes[idx].pos0.x;\n\t\t\t\t}\n\t\t\t\tif (flags & AXIS_Y)\n\t\t\t\t{\n\t\t\t\t\tdirichletErrors(count++) = nodes[idx].pos.y - nodes[idx].pos0.y;\n\t\t\t\t}\n\t\t\t\tif (flags & AXIS_Z)\n\t\t\t\t{\n\t\t\t\t\tdirichletErrors(count++) = nodes[idx].pos.z - nodes[idx].pos0.z;\n\t\t\t\t}\n\t\t\t}\n\t\t\t//Printf(\"Dirichlet BCs error: %g\\n\", dirichletErrors.lpNorm<Eigen::Infinity>());\n\t\t\trhs -= mDirichletStiffness * mDirichletJacobian.transpose() * dirichletErrors;\n\t\t\t// TODO: we can build the rhs term directly without the Jacobian\n\t\t}\n\n\t\t//Printf(\"E=%g\\n\", ComputeEnergy());\n\t\treturn rhs;\n\t}\n\n\ttemplate<class MATRIX>\n\tvoid FemPhysicsMatrixFree::ComputeSystemMatrix(const EigenVector& s, const EigenVector& y, MATRIX& K)\n\t{\t\t\n\t\tElasticEnergy::AssembleStiffnessMatrix(this, K);\n\t\t//K -= mTractionStiffnessMatrix;\n\t\tif (mTimeStep != 0 && mSimType == ST_IMPLICIT)\n\t\t\tK += (1.f / mTimeStep / mTimeStep) * mMassMatrix;\n\n\t\tif (!mDirichletIndices.empty())\n\t\t{\n\t\t\tK += mDirichletStiffness * mDirichletJacobian.transpose() * mDirichletJacobian;\n\t\t}\n\t\tif (!mCables.empty())\n\t\t{\n\t\t\tMATRIX Ks;\n\t\t\tComputeSpringStiffnessMatrix(Ks);\n\t\t\tK -= Ks;\n\t\t}\n\t\tif (mConfig.mOptimizer)\n\t\t\tPrintf(\"energy: %g\\n\", ComputeEnergy());\n\t}\n\n\tEigenVector FemPhysicsMatrixFree::SolveLinearSystem(EigenMatrix& K, const EigenVector& rhs, const EigenVector& s, const EigenVector& y)\n\t{\n\t\tLinearSolver solver;\n\t\tsolver.Init(K, LST_LU_PARDISO);\n\t\t//solver.SetTolerance(0.1);\n\t\t//solver.Init(K, LST_CG);\n\t\treturn solver.Solve(rhs);\n\t}\n\n\tEigenVector FemPhysicsMatrixFree::SolveLinearSystem(SparseMatrix& K, const EigenVector& rhs, const EigenVector& s, const EigenVector& y)\n\t{\n\t\tLinearSolver solver;\n\t\tsolver.Init(K, LST_LU_PARDISO);\n\t\treturn solver.Solve(rhs);\n\t}\n\n\tbool FemPhysicsMatrixFree::SolveNewtonLS()\n\t{\n\t\tAssembleDynamicContributions();\n\t\t\n\t\tNewtonSolverBackTrack<FemPhysicsMatrixFree, SparseMatrix> solver;\n\t\tsolver.mNumIterations = mOuterIterations;\n\t\tsolver.mVerbose = mVerbose ? VL_MINIMUM : VL_NONE;\n\t\tsolver.mResidualThreshold = mAbsNewtonResidualThreshold;\n\t\tsolver.mUseProblemSolver = true;\n\t\tif (mConfig.mOptimizer)\n\t\t{\n\t\t\tsolver.mLSCondition = LSC_ARMIJO;\n\t\t\t//solver.mAlpha = 1e-3;\n\t\t}\n\t\t//solver.mUseBFGS = false;\n\n\t\t// prepare the initial guess with the current configuration\n\t\tuint32 size = GetNumFreeNodes() * NUM_POS_COMPONENTS;\n\t\tEigenVector solution(size);\n\t\tfor (uint32 i = 0; i < GetNumFreeNodes(); i++)\n\t\t{\n\t\t\tconst Vector3R& p = nodes[i + mNumBCs].pos;\n\t\t\tsolution(i * NUM_POS_COMPONENTS) = p.x;\n\t\t\tsolution(i * NUM_POS_COMPONENTS + 1) = p.y;\n\t\t\tsolution(i * NUM_POS_COMPONENTS + 2) = p.z;\n\t\t}\n\n\t\tsolver.Solve(*this, size, solution);\n\t\tif (mVerbose)\n\t\t{\n\t\t\treal vol = GetTotalVolume();\n\t\t\tPrintf(\"vol err: %.2f%%\\n\", abs(vol - mTotalInitialVol) / mTotalInitialVol * 100);\n\t\t}\n\n\t\t// set node positions\n\t\tauto solVecs = GetStdVector(solution);\n\t\tASSERT(solVecs.size() == GetNumFreeNodes());\n\t\tfor (uint32 i = 0; i < GetNumFreeNodes(); i++)\n\t\t{\n\t\t\tnodes[i + mNumBCs].pos = solVecs[i];\n\t\t}\n\n\t\tCheckForInversion(true);\n\n\t\t// store Hessian\n\t\tmHessian = solver.mB;\n\n\t\treturn true;\n\t}\n\n\tbool FemPhysicsMatrixFree::SolveNewton()\n\t{\n\t\tAssembleDynamicContributions();\n\n\t\tNewtonSolver<FemPhysicsMatrixFree, SparseMatrix> solver;\n\t\tsolver.mNumIterations = mOuterIterations;\n\t\tsolver.mVerbose = mVerbose ? VL_MINIMUM : VL_NONE;\n\t\tsolver.mResidualThreshold = mAbsNewtonResidualThreshold;\n\t\tsolver.mSolverType = LST_LU_PARDISO;\n\t\t//solver.mUseFiniteDiff = true;\n\n\t\t// prepare the initial guess with the current configuration\n\t\tuint32 size = GetNumFreeNodes() * NUM_POS_COMPONENTS;\n\t\t//Printf(\"#dofs: %d\\n\", size);\n\t\tEigenVector solution(size);\n\t\tfor (uint32 i = 0; i < GetNumFreeNodes(); i++)\n\t\t{\n\t\t\tconst Vector3R& p = nodes[i + mNumBCs].pos;\n\t\t\tsolution(i * NUM_POS_COMPONENTS) = p.x;\n\t\t\tsolution(i * NUM_POS_COMPONENTS + 1) = p.y;\n\t\t\tsolution(i * NUM_POS_COMPONENTS + 2) = p.z;\n\t\t}\n\n\t\tsolver.Solve(*this, size, solution);\n\t\tif (mVerbose)\n\t\t{\n\t\t\treal vol = GetTotalVolume();\n\t\t\tPrintf(\"vol err: %.2f%%\\n\", abs(vol - mTotalInitialVol) / mTotalInitialVol * 100);\n\t\t}\n\n\t\t// set node positions\n\t\tauto solVecs = GetStdVector(solution);\n\t\tASSERT(solVecs.size() == GetNumFreeNodes());\n\t\tfor (uint32 i = 0; i < GetNumFreeNodes(); i++)\n\t\t{\n\t\t\tnodes[i + mNumBCs].pos = solVecs[i];\n\t\t}\n\n\t\tCheckForInversion(true);\n\n\t\treturn true;\n\t}\n\n\tvoid FemPhysicsMatrixFree::SolveGradientDescent(real alpha)\n\t{\n\t\tstd::vector<Vector3R> b(GetNumFreeNodes()); // allocation!\n\t\tfor (uint32 iter = 0; iter < mOuterIterations; iter++)\n\t\t{\n\t\t\tComputeGradients(b);\n\n\t\t\t// perform the gradient descent step (very similar to explicit integration)\n\t\t\tfor (size_t i = 0; i < GetNumFreeNodes(); i++)\n\t\t\t{\n\t\t\t\tVector3R delta = alpha * b[i];\n\t\t\t\tnodes[i + mNumBCs].pos += delta;\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid FemPhysicsMatrixFree::SolveNonlinearSteepestDescent()\n\t{\n\t\t// the residual vector\n\t\tstd::vector<Vector3R> r(GetNumFreeNodes()); // allocation!\n\t\t// the differential vector\n\t\tstd::vector<Vector3R> df(GetNumFreeNodes()); // allocation!\n\n\t\tfor (uint32 iter = 0; iter < mOuterIterations; iter++)\n\t\t{\n\t\t\tComputeGradients(r);\n\t\t\tMatrixVectorMultiply(r, df);\n\t\t\treal delta = InnerProduct<Vector3R, real>(r, r);\n\t\t\tif (delta == 0)\n\t\t\t\tbreak;\n\t\t\treal alpha = delta / InnerProduct<Vector3R, real>(r, df);\n\t\t\tif (alpha == 0)\n\t\t\t\tbreak;\n\n\t\t\t// perform the gradient descent step (very similar to explicit integration)\n\t\t\tfor (size_t i = 0; i < GetNumFreeNodes(); i++)\n\t\t\t{\n\t\t\t\tVector3R delta = alpha * r[i];\n\t\t\t\tnodes[i + mNumBCs].pos += delta;\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid FemPhysicsMatrixFree::SolveNonlinearConjugateGradient()\n\t{\n\t\tstd::vector<Vector3R> pos(GetNumFreeNodes()); // allocation!\n\t\tfor (uint32 i = 0; i < GetNumFreeNodes(); i++)\n\t\t\tpos[i] = nodes[i + mNumBCs].pos;\n\n\t\tNonlinearConjugateGradientMinimizer<FemPhysicsMatrixFree, std::vector<Vector3R>> minimizer;\n\t\tminimizer.mOuterIterations = mOuterIterations;\n\t\tminimizer.mInnerIterations = mInnerIterations;\n\t\tminimizer.mAbsResidualThreshold = mAbsNewtonResidualThreshold;\n\t\tminimizer.Solve(*this, GetNumFreeNodes(), pos);\n\t}\n\n\treal FemPhysicsMatrixFree::ComputeEnergy()\n\t{\n\t\treal val = ComputeElasticEnergy();\n\t\t// add the gravitational and kinetic part\n\t\treal invHSqr = mTimeStep != 0 ? 0.5f / mTimeStep / mTimeStep : 0;\n\t\tfor (size_t i = 0; i < GetNumFreeNodes(); i++)\n\t\t{\n\t\t\treal mass = 1.f / nodes[i + mNumBCs].invMass;\n\t\t\tval -= mass * mForceFraction * mGravity.y * nodes[i + mNumBCs].pos.y; // gravitational\n\t\t\tval -= invHSqr * mass * GetTotalDisplacement(i).LengthSquared(); // kinetic (delta)\n\t\t}\n\t\t// add the pressure part (WIP)\n\t\tfor (size_t i = 0; i < mTractionSurface.size() / 3; i += 3)\n\t\t{\n\t\t\tint base = i * 3;\n\t\t\t// global (shuffled) indices of nodes\n\t\t\tuint32 i1 = mTractionSurface[base];\n\t\t\tuint32 i2 = mTractionSurface[base + 1];\n\t\t\tuint32 i3 = mTractionSurface[base + 2];\n\n\t\t\t// compute triangle area and normal\n\t\t\tconst Vector3R& p1 = GetDeformedPosition(i1);\n\t\t\tconst Vector3R& p2 = GetDeformedPosition(i2);\n\t\t\tconst Vector3R& p3 = GetDeformedPosition(i3);\n\n\t\t\t// compute volume formed with the origin\n\t\t\treal vol = (1.f / 6.f) * triple(p1, p2, p3);\n\t\t\tval += abs(vol) * mAppliedPressure;\n\t\t}\n\t\t// add the springs\n\t\tval += ComputeSpringEnergy();\n\n\t\t//Printf(\"energy: %g\\n\", val);\n\t\treturn val;\n\t}\n\n\treal FemPhysicsMatrixFree::ComputeEnergy(int level)\n\t{\n\t\t// level 0 -> elastic\n\t\t// level 1 -> gravitational\n\t\t// level 2 -> vol\n\t\t// level 3 -> kinetic\n\n\t\treal val = 0;\n\t\t\n\t\tif (level == 0)\n\t\t\tval += ComputeElasticEnergy();\n\t\t\n\t\t// add the gravitational and kinetic part\n\t\treal invHSqr = mTimeStep != 0 ? 0.5f / mTimeStep / mTimeStep : 0;\n\t\t\n\t\tfor (size_t i = 0; i < GetNumFreeNodes(); i++)\n\t\t{\n\t\t\treal mass = 1.f / nodes[i + mNumBCs].invMass;\n\t\t\tif (level == 1)\n\t\t\t\tval += mass * mForceFraction * mGravity.y * nodes[i + mNumBCs].pos.y; // gravitational\n\t\t\t\n\t\t\tif (level == 3)\n\t\t\t\tval += invHSqr * mass * GetTotalDisplacement(i).LengthSquared(); // kinetic\n\t\t}\n\n\n\t\t//// add the pressure part (WIP)\n\t\t//for (size_t i = 0; i < mTractionSurface.size() / 3; i += 3)\n\t\t//{\n\t\t//\tint base = i * 3;\n\t\t//\t// global (shuffled) indices of nodes\n\t\t//\tuint32 i1 = mTractionSurface[base];\n\t\t//\tuint32 i2 = mTractionSurface[base + 1];\n\t\t//\tuint32 i3 = mTractionSurface[base + 2];\n\n\t\t//\t// compute triangle area and normal\n\t\t//\tconst Vector3R& p1 = GetDeformedPosition(i1);\n\t\t//\tconst Vector3R& p2 = GetDeformedPosition(i2);\n\t\t//\tconst Vector3R& p3 = GetDeformedPosition(i3);\n\n\t\t//\t// compute volume formed with the origin\n\t\t//\treal vol = (1.f / 6.f) * triple(p1, p2, p3);\n\t\t//\tval += abs(vol) * mAppliedPressure;\n\t\t//}\n\n\t\t//Printf(\"energy: %f\\n\", val);\n\t\treturn val;\n\t}\n\n\tvoid FemPhysicsMatrixFree::ComputePressureForces(Vector3Array& fout, EigenMatrix& Kout) const\n\t{\n\t\tif (mTractionSurface.empty())\n\t\t\treturn;\n\n\t\tif (mUseImplicitPressureForces)\n\t\t{\n\t\t\tuint32 numDofs = GetNumFreeNodes() * NUM_POS_COMPONENTS;\n\t\t\tKout.resize(numDofs, numDofs);\n\t\t\tKout.setZero();\n\t\t}\n\n\t\tauto computeForce = [&](const Vector3R& p1, const Vector3R& p2, const Vector3R& p3)->Vector3R\n\t\t{\n\t\t\tVector3R a = p2 - p1;\n\t\t\tVector3R b = p3 - p1;\n\t\t\tVector3R normal = cross(a, b);\n\t\t\treal area = 0.5f * normal.Length();\n\t\t\tnormal.Normalize();\n\n\t\t\tVector3R traction = mAppliedPressure * normal;\n\t\t\tVector3R force = (area / 3.0f) * traction;\n\t\t\treturn force;\n\t\t};\n\n\t\t// go through all inner boundary triangles\n\t\tfor (uint32 t = 0; t < mTractionSurface.size() / 3; t++)\n\t\t{\n\t\t\tint base = t * 3;\n\t\t\t// global (shuffled) indices of nodes\n\t\t\tuint32 i1 = mTractionSurface[base];\n\t\t\tuint32 i2 = mTractionSurface[base + 1];\n\t\t\tuint32 i3 = mTractionSurface[base + 2];\n\n\t\t\t// compute triangle area and normal\n\t\t\tconst Vector3R& p1 = GetDeformedPosition(i1);\n\t\t\tconst Vector3R& p2 = GetDeformedPosition(i2);\n\t\t\tconst Vector3R& p3 = GetDeformedPosition(i3);\n\n\t\t\t// apply traction to triangle nodes\n\t\t\tVector3R force = mForceFraction * computeForce(p1, p2, p3);\n\t\t\ti1 = mReshuffleMap[i1];\n\t\t\ti2 = mReshuffleMap[i2];\n\t\t\ti3 = mReshuffleMap[i3];\n\t\t\tfout[i1] += force;\n\t\t\tfout[i2] += force;\n\t\t\tfout[i3] += force;\n\n\t\t\tif (mUseImplicitPressureForces)\n\t\t\t{\n\t\t\t\t// compute local stiffness matrix\n\t\t\t\tMatrix3R K[3];\n\t\t\t\tVector3R a = p2 - p1;\n\t\t\t\tVector3R b = p3 - p1;\n\t\t\t\ta.Scale(mAppliedPressure / 6.0f);\n\t\t\t\tb.Scale(mAppliedPressure / 6.0f);\n\t\t\t\tK[2] = Matrix3R::Skew(a);\n\t\t\t\tK[1] = Matrix3R::Skew(-b);\n\t\t\t\tK[0] = -K[1] - K[2];\n\n\t\t\t\ti1 -= mNumBCs;\n\t\t\t\ti2 -= mNumBCs;\n\t\t\t\ti3 -= mNumBCs;\n\n\t\t\t\t// assemble global stiffness matrix\n\t\t\t\tfor (uint32 x = 0; x < 3; x++)\n\t\t\t\t{\n\t\t\t\t\tfor (uint32 y = 0; y < 3; y++)\n\t\t\t\t\t{\n\t\t\t\t\t\tKout(i1 * 3 + x, i1 * 3 + y) += K[0](x, y);\n\t\t\t\t\t\tKout(i1 * 3 + x, i2 * 3 + y) += K[1](x, y);\n\t\t\t\t\t\tKout(i1 * 3 + x, i3 * 3 + y) += K[2](x, y);\n\t\t\t\t\t\tKout(i2 * 3 + x, i1 * 3 + y) += K[0](x, y);\n\t\t\t\t\t\tKout(i2 * 3 + x, i2 * 3 + y) += K[1](x, y);\n\t\t\t\t\t\tKout(i2 * 3 + x, i3 * 3 + y) += K[2](x, y);\n\t\t\t\t\t\tKout(i3 * 3 + x, i1 * 3 + y) += K[0](x, y);\n\t\t\t\t\t\tKout(i3 * 3 + x, i2 * 3 + y) += K[1](x, y);\n\t\t\t\t\t\tKout(i3 * 3 + x, i3 * 3 + y) += K[2](x, y);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid FemPhysicsMatrixFree::SetBoundaryConditionsSurface(const std::vector<uint32>& triangleList, real pressure)\n\t{\n\t\tmAppliedPressure = pressure;\n\t\tmTractionSurface.resize(triangleList.size());\n\n\t\tfor (uint32 i = 0; i < triangleList.size(); i++)\n\t\t{\n\t\t\tmTractionSurface[i] = triangleList[i];\n\t\t}\n\t}\n\n\treal FemPhysicsMatrixFree::ComputeSpringEnergy(Cable& cable)\n\t{\n\t\tif (cable.mCableNodes.empty() || cable.mActuation == 0)\n\t\t\treturn 0;\n\t\tuint32 numNodes = cable.mCableNodes.size();\n\t\tuint32 numSprings = numNodes - 1;\n\t\t// compute interpolated spring nodes\n\t\tcable.mCablePositions.resize(numNodes);\n\t\tVector3Array vels(numNodes);\n\t\tfor (uint32 i = 0; i < numNodes; i++)\n\t\t{\n\t\t\tint elem = cable.mCableNodes[i].elem;\n\t\t\tif (elem < 0)\n\t\t\t{\n\t\t\t\tcable.mCablePositions[i] = nodes[-elem].pos;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst Tetrahedron& tet = tets[elem];\n\t\t\tconst Vector3R& x0 = nodes[tet.i[0]].pos;\n\t\t\tconst Vector3R& x1 = nodes[tet.i[1]].pos;\n\t\t\tconst Vector3R& x2 = nodes[tet.i[2]].pos;\n\t\t\tconst Vector3R& x3 = nodes[tet.i[3]].pos;\n\t\t\treal w0 = cable.mCableNodes[i].bary.x;\n\t\t\treal w1 = cable.mCableNodes[i].bary.y;\n\t\t\treal w2 = cable.mCableNodes[i].bary.z;\n\t\t\treal w3 = 1 - w0 - w1 - w2;\n\t\t\tcable.mCablePositions[i] = w0 * x0 + w1 * x1 + w2 * x2 + w3 * x3;\n\t\t\tvels[i] = w0 * nodes[tet.i[0]].vel + w1 * nodes[tet.i[1]].vel + w2 * nodes[tet.i[2]].vel + w3 * nodes[tet.i[3]].vel;\n\t\t}\n\t\t// TODO: reuse cable positions\n\t\t// 1. Compute spring errors and potentials\n\t\tstd::vector<Vector3R> springForces(numSprings);\n\t\tconst real eps = cable.mCableRestLength * 0.01;\n\t\treal energy = 0;\n\t\tfor (uint32 i = 0; i < numSprings; i++)\n\t\t{\n\t\t\tVector3R y = cable.mCablePositions[i + 1] - cable.mCablePositions[i];\n\t\t\treal len = y.Length();\n\t\t\tVector3R dir = (1.0 / len) * y;\n\t\t\treal err = len - cable.mCableRestLength * cable.mActuation;\n\t\t\treal potential = cable.mCableStiffness * (err * err + eps * eps / 3);\n\t\t\t// Bern tension model (unilateral spring + twice differentiable)\n\t\t\tif (err < -eps)\n\t\t\t\tpotential = 0;\n\t\t\telse if (err >= -eps && err <= eps)\n\t\t\t\tpotential = 0.5 * cable.mCableStiffness * (err * err * err / 3 / eps + err * err + eps * err + eps * eps / 3);\n\t\t\tenergy += potential;\n\t\t}\n\t\treturn energy;\n\t}\n\n\treal FemPhysicsMatrixFree::ComputeSpringEnergy()\n\t{\n\t\treal energy = 0;\n\t\tfor (Cable& cable : mCables)\n\t\t{\n\t\t\tenergy += ComputeSpringEnergy(cable);\n\t\t}\n\t\treturn energy;\n\t}\n\n} // namespace FEM_SYSTEM", "meta": {"hexsha": "e89d4e093ad6c6dc702113db500249d7d01634a7", "size": 33524, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Source/FemPhysicsMatrixFree.cpp", "max_stars_repo_name": "MihaiF/SolidFEM", "max_stars_repo_head_hexsha": "58e08130e2f31be3b056c387ed03aab3b0b3db38", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-05-19T10:59:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-04T08:59:32.000Z", "max_issues_repo_path": "Source/FemPhysicsMatrixFree.cpp", "max_issues_repo_name": "MihaiF/SolidFEM", "max_issues_repo_head_hexsha": "58e08130e2f31be3b056c387ed03aab3b0b3db38", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/FemPhysicsMatrixFree.cpp", "max_forks_repo_name": "MihaiF/SolidFEM", "max_forks_repo_head_hexsha": "58e08130e2f31be3b056c387ed03aab3b0b3db38", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-11-08T16:14:53.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-08T16:14:53.000Z", "avg_line_length": 29.8521816563, "max_line_length": 141, "alphanum_fraction": 0.6378713757, "num_tokens": 11530, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.4604021293463398}}
{"text": "/**\n# Copyright 2018 D-Wave Systems Inc.\n#\n#    Licensed under the Apache License, Version 2.0 (the \"License\");\n#    you may not use this file except in compliance with the License.\n#    You may obtain a copy of the License at\n#\n#        http://www.apache.org/licenses/LICENSE-2.0\n#\n#    Unless required by applicable law or agreed to in writing, software\n#    distributed under the License is distributed on an \"AS IS\" BASIS,\n#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n#    See the License for the specific language governing permissions and\n#    limitations under the License.\n#\n# ================================================================================================\n*/\n#include \"fix_variables.hpp\"\n#include \"compressed_matrix.hpp\"\n\n#include <algorithm>\n#include <cmath>\n#include <limits>\n#include <map>\n#include <queue>\n#include <set>\n#include <string>\n\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/push_relabel_max_flow.hpp>\n#include <boost/graph/strong_components.hpp>\n\n//for debugging only\n#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <time.h>\n\nnamespace\n{\n\nclass compClass\n{\npublic:\n\tbool operator()(const std::pair<int, int>& a, const std::pair<int, int>& b)\n\t{\n\t\tif (a.second != b.second)\n\t\t\treturn !(a.second < b.second);\n\t\telse\n\t\t\treturn a.first < b.first;\n\t}\n};\n\nbool compareAbs(double a, double b)\n{\n\treturn std::abs(a) < std::abs(b);\n}\n\n\n//the index is 1-based, according to the paper\nstruct Posiform\n{\n\tstd::vector<std::pair<std::pair<int, int>, long long int> > quadratic;\n\tstd::vector<std::pair<int, long long int> > linear;\n\tlong long int cst;\n\tint numVars;\n};\n\nstruct SC\n{\n\tstd::vector<int> original;\n\tstd::vector<int> positive;\n\tstd::vector<int> negative;\n};\n\nstruct SCRet\n{\n\tstd::vector<SC> S;\n\tcompressed_matrix::CompressedMatrix<long long int> G;\n};\n\nPosiform BQPToPosiform(const compressed_matrix::CompressedMatrix<long long int>& Q, bool makeRandom = false)\n{\n\tint numVariables = Q.numRows();\n\tPosiform ret;\n\tret.numVars = numVariables;\n\tstd::vector<long long int> q(numVariables);\n\n\t//q = diag(Q);\n\tfor (int i = 0; i < numVariables; i++)\n\t\tq[i] = Q.get(i, i);\n\n\t//tmpQ = triu(Q,1);\n\tstd::vector<int> tmpQRowOffsets(numVariables + 1);\n\tstd::vector<int> tmpQColIndices; tmpQColIndices.reserve(Q.nnz());\n\tstd::vector<long long int> tmpQValues; tmpQValues.reserve(Q.nnz());\n\tint index = 0;\n\tfor (int i = 0; i < Q.numRows(); i++)\n\t{\n\t\tint start = Q.rowOffsets()[i];\n\t\tint end = Q.rowOffsets()[i + 1];\n\t\ttmpQRowOffsets[i] = index;\n\t\tfor (int j = start; j < end; j++)\n\t\t{\n\t\t\tint r = i;\n\t\t\tint c = Q.colIndices()[j];\n\t\t\tif (r != c)\n\t\t\t{\n\t\t\t\ttmpQColIndices.push_back(c);\n\t\t\t\ttmpQValues.push_back(Q.values()[j]); //Q.values()[j] is Q(r, c)\n\t\t\t\t++index;\n\t\t\t}\n\t\t}\n\t}\n\ttmpQRowOffsets.back() = index; //number of non-zero elements\n\n\tcompressed_matrix::CompressedMatrix<long long int> tmpQ(numVariables, numVariables, tmpQRowOffsets, tmpQColIndices, tmpQValues);\n\n\n\tif (!makeRandom) //make a deterministic posiform from Q\n\t{\n\t\t//cPrime = q + sum(tmpQ.*(tmpQ<0),2); and quadratic term\n\t\tstd::vector<long long int> cPrime = q;\n\t\tfor (int i = 0; i < tmpQ.numRows(); i++)\n\t\t{\n\t\t\tint start = tmpQ.rowOffsets()[i];\n\t\t\tint end = tmpQ.rowOffsets()[i + 1];\n\t\t\tfor (int j = start; j < end; j++)\n\t\t\t{\n\t\t\t\tint r = i;\n\t\t\t\tint c = tmpQ.colIndices()[j];\n\t\t\t\tif (tmpQ.values()[j] < 0)\n\t\t\t\t{\n\t\t\t\t\tcPrime[i] += tmpQ.values()[j];\n\t\t\t\t\tret.quadratic.push_back(std::make_pair(std::make_pair(r + 1, -(c + 1)), -tmpQ.values()[j])); //+1 makes it 1-based\n\t\t\t\t}\n\t\t\t\telse if (tmpQ.values()[j] > 0)\n\t\t\t\t\tret.quadratic.push_back(std::make_pair(std::make_pair(r + 1, c + 1), tmpQ.values()[j])); //+1 makes it 1-based\n\t\t\t}\n\t\t}\n\n\t\t//constant term and linear term\n\t\tret.cst = 0;\n\t\tfor (int i = 0; i < numVariables; i++)\n\t\t{\n\t\t\tif (cPrime[i] < 0)\n\t\t\t{\n\t\t\t\tret.cst += cPrime[i]; //constant term\n\t\t\t\tret.linear.push_back(std::make_pair(-(i + 1), -cPrime[i])); //+1 makes it 1-based\n\t\t\t}\n\t\t\telse if (cPrime[i] > 0)\n\t\t\t\tret.linear.push_back(std::make_pair(i + 1, cPrime[i])); //+1 makes it 1-based\n\t\t}\n\t}\n\telse\n\t{\n\t\tstd::vector<long long int> linear = q;\n\t\tstd::set<std::pair<int, int> > negPairs;\n\t\tfor (int i = 0; i < tmpQ.numRows(); i++)\n\t\t{\n\t\t\tint start = tmpQ.rowOffsets()[i];\n\t\t\tint end = tmpQ.rowOffsets()[i + 1];\n\t\t\tfor (int j = start; j < end; j++)\n\t\t\t{\n\t\t\t\tint r = i;\n\t\t\t\tint c = tmpQ.colIndices()[j];\n\t\t\t\tif (tmpQ.values()[j] < 0)\n\t\t\t\t{\n\t\t\t\t\tif (rand() % 2 == 0)\n\t\t\t\t\t\tnegPairs.insert(std::make_pair(-(r + 1), c + 1)); //+1 makes it 1-based\n\t\t\t\t\telse\n\t\t\t\t\t\tnegPairs.insert(std::make_pair(r + 1, -(c + 1))); //+1 makes it 1-based\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor (int i = 0; i < tmpQ.numRows(); i++)\n\t\t{\n\t\t\tint start = tmpQ.rowOffsets()[i];\n\t\t\tint end = tmpQ.rowOffsets()[i + 1];\n\t\t\tfor (int j = start; j < end; j++)\n\t\t\t{\n\t\t\t\tint r = i;\n\t\t\t\tint c = tmpQ.colIndices()[j];\n\t\t\t\tif (tmpQ.values()[j] > 0)\n\t\t\t\t\tret.quadratic.push_back(std::make_pair(std::make_pair(r + 1, c + 1), tmpQ.values()[j]));\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif (negPairs.find(std::make_pair(r + 1, -(c + 1)))!=negPairs.end())\n\t\t\t\t\t\tret.quadratic.push_back(std::make_pair(std::make_pair(r + 1, -(c + 1)), -tmpQ.values()[j]));\n\t\t\t\t\telse\n\t\t\t\t\t\tret.quadratic.push_back(std::make_pair(std::make_pair(-(r + 1), c + 1), -tmpQ.values()[j]));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor (std::set<std::pair<int, int> >::iterator it = negPairs.begin(); it != negPairs.end(); ++it)\n\t\t{\n\t\t\tif (it->first > 0)\n\t\t\t\tlinear[it->first - 1] += tmpQ(it->first - 1, -it->second - 1);\n\t\t\telse\n\t\t\t\tlinear[it->second - 1] += tmpQ(-it->first - 1, it->second - 1);\n\t\t}\n\n\t\tret.cst = 0;\n\n\t\tfor (int i = 0; i < numVariables; i++)\n\t\t{\n\t\t\tif (linear[i] < 0)\n\t\t\t{\n\t\t\t\tret.cst += linear[i];\n\t\t\t\tret.linear.push_back(std::make_pair(-(i + 1), -linear[i]));\n\t\t\t}\n\t\t\telse if (linear[i] > 0)\n\t\t\t\tret.linear.push_back(std::make_pair(i + 1, linear[i]));\n\t\t}\n\t}\n\n\treturn ret;\n}\n\ncompressed_matrix::CompressedMatrix<long long int> posiformToImplicationNetwork_1(const Posiform& p)\n{\n\tint n = p.numVars;\n\tint numVertices = 2 * n + 2;\n\tint source = 0;\n\tint sink = n + 1;\n\n\t//n = p.numVars\n\t//0: source;\n\t//1 to n: x_1 to x_n\n\t//n+1: sink\n\t//n+2 to 2*n+1: \\overline_x_1 to \\overline_x_n\n\tstd::map<std::pair<int, int>, long long int> m;\n\tfor (int i = 0; i < p.linear.size(); i++)\n\t{\n\t\tint v = p.linear[i].first;\n\n\t\tlong long int capacity = p.linear[i].second; // originally p.linear[i].second/2\n\t\tif (v > 0)\n\t\t{\n\t\t\tm[std::make_pair(source, v + n + 1)] = capacity;\n\t\t\tm[std::make_pair(v, sink)] = capacity;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tv = std::abs(v);\n\t\t\tm[std::make_pair(source, v)] = capacity;\n\t\t\tm[std::make_pair(v + n + 1, sink)] = capacity;\n\t\t}\n\t}\n\n\tfor (int i = 0; i < p.quadratic.size(); i++)\n\t{\n\t\tint v_1 = p.quadratic[i].first.first;\n\t\tint v_2 = p.quadratic[i].first.second;\n\n\t\tlong long int capacity = p.quadratic[i].second; // originally p.quadratic[i].second/2\n\t\tif (v_1 < 0)\n\t\t{\n\t\t\tv_1 = std::abs(v_1);\n\t\t\tm[std::make_pair(v_1 + n + 1, v_2 + n + 1)] = capacity;\n\t\t\tm[std::make_pair(v_2, v_1)] = capacity;\n\t\t}\n\t\telse if (v_2 < 0)\n\t\t{\n\t\t\tv_2 = std::abs(v_2);\n\t\t\tm[std::make_pair(v_1, v_2)] = capacity;\n\t\t\tm[std::make_pair(v_2 + n + 1, v_1 + n + 1)] = capacity;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tm[std::make_pair(v_1, v_2 + n + 1)] = capacity;\n\t\t\tm[std::make_pair(v_2, v_1 + n + 1)] = capacity;\n\t\t}\n\t}\n\n\treturn compressed_matrix::CompressedMatrix<long long int>(numVertices, numVertices, m);\n}\n\ncompressed_matrix::CompressedMatrix<long long int> posiformToImplicationNetwork_2(const Posiform& p)\n{\n\tint n = p.numVars;\n\tint numVertices = 2 * n + 2;\n\tint source = n;\n\tint sink = 2 * n + 1;\n\n\t//n = p.numVars\n\t//0 to n-1: x_1 to x_n\n\t//n: source;\n\t//n+1 to 2*n: \\overline_x_1 to \\overline_x_n\n\t//2*n+1: sink\n\tstd::map<std::pair<int, int>, long long int> m;\n\tfor (int i = 0; i < p.linear.size(); i++)\n\t{\n\t\tint v = p.linear[i].first;\n\t\tlong long int capacity = p.linear[i].second; // originally p.linear[i].second/2\n\t\tif (v > 0)\n\t\t{\n\t\t\tm[std::make_pair(source, v + n)] = capacity;\n\t\t\tm[std::make_pair(v - 1, sink)] = capacity;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tv = std::abs(v);\n\t\t\tm[std::make_pair(source, v - 1)] = capacity;\n\t\t\tm[std::make_pair(v + n, sink)] = capacity;\n\t\t}\n\t}\n\n\tfor (int i = 0; i < p.quadratic.size(); i++)\n\t{\n\t\tint v_1 = p.quadratic[i].first.first;\n\t\tint v_2 = p.quadratic[i].first.second;\n\t\tlong long int capacity = p.quadratic[i].second; // originally p.quadratic[i].second/2\n\t\tif (v_1 < 0)\n\t\t{\n\t\t\tv_1 = std::abs(v_1);\n\t\t\tm[std::make_pair(v_1 + n, v_2 + n)] = capacity;\n\t\t\tm[std::make_pair(v_2 - 1, v_1 - 1)] = capacity;\n\t\t}\n\t\telse if (v_2 < 0)\n\t\t{\n\t\t\tv_2 = std::abs(v_2);\n\t\t\tm[std::make_pair(v_1 - 1, v_2 - 1)] = capacity;\n\t\t\tm[std::make_pair(v_2 + n, v_1 + n)] = capacity;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tm[std::make_pair(v_1 - 1, v_2 + n)] = capacity;\n\t\t\tm[std::make_pair(v_2 - 1, v_1 + n)] = capacity;\n\t\t}\n\t}\n\n\treturn compressed_matrix::CompressedMatrix<long long int>(numVertices, numVertices, m);\n}\n\n//this version returns R instead of F\ncompressed_matrix::CompressedMatrix<long long int> maxFlow(const compressed_matrix::CompressedMatrix<long long int>& A)\n{\n\tint numVertices = A.numRows();\n\tint numVariables = numVertices / 2 - 1;\n\n\t//clock_t curr_1 = clock();\n\t//clock_t curr_2;\n\n\tusing namespace boost;\n\n\ttypedef adjacency_list_traits<vecS, vecS, directedS> Traits;\n\ttypedef adjacency_list<vecS, vecS, directedS, property<vertex_name_t, std::string>, property<edge_capacity_t, long long int, property<edge_residual_capacity_t, long long int, property<edge_reverse_t, Traits::edge_descriptor> > > > Graph; //for edge capacity is long long int\n\t//typedef adjacency_list<vecS, vecS, directedS, property<vertex_name_t, std::string>, property<edge_capacity_t, double, property<edge_residual_capacity_t, double, property<edge_reverse_t, Traits::edge_descriptor> > > > Graph; //for edge capacity is double\n\n\tGraph g;\n\n\tproperty_map<Graph, edge_capacity_t>::type capacity = get(edge_capacity, g);\n\tproperty_map<Graph, edge_reverse_t>::type reverse_edge = get(edge_reverse, g);\n\tproperty_map<Graph, edge_residual_capacity_t>::type residual_capacity = get(edge_residual_capacity, g);\n\n\tstd::vector<Traits::vertex_descriptor> verts(numVertices);\n\tfor (int i = 0; i < numVertices; ++i)\n\t\tverts[i] = add_vertex(g);\n\n\tTraits::vertex_descriptor s = verts[0];\n\tTraits::vertex_descriptor t = verts[numVariables + 1];\n\n\tfor (int i = 0; i < A.numRows(); i++)\n\t{\n\t\tint start = A.rowOffsets()[i];\n\t\tint end = A.rowOffsets()[i + 1];\n\t\tfor (int j = start; j < end; j++)\n\t\t{\n\t\t\tint r = i;\n\t\t\tint c = A.colIndices()[j];\n\t\t\tlong long int cap = A.values()[j];\n\n\t\t\tTraits::edge_descriptor e1, e2;\n\t\t\tbool in1, in2;\n\t\t\tboost::tie(e1, in1) = add_edge(verts[r], verts[c], g);\n\t\t\tboost::tie(e2, in2) = add_edge(verts[c], verts[r], g);\n\n\t\t\tcapacity[e1] = cap;\n\t\t\tcapacity[e2] = 0;\n\t\t\treverse_edge[e1] = e2;\n\t\t\treverse_edge[e2] = e1;\n\t\t}\n\t}\n\n\n\t//curr_2 = clock();\n\t//mexPrintf(\"inside maxFlow int version: Time elapsed_constructing_graph_for_max_flow: %f\\n\", ((double)curr_2 - curr_1) / CLOCKS_PER_SEC);\n\t//curr_1 = curr_2;\n\n\tpush_relabel_max_flow(g, s, t);\n\n\t//curr_2 = clock();\n\t//mexPrintf(\"inside maxFlow int version: Time elapsed_for_boost_max_flow: %f\\n\", ((double)curr_2 - curr_1) / CLOCKS_PER_SEC);\n\t//curr_1 = curr_2;\n\n\tstd::vector<int> RRowOffsets(numVertices+1);\n\tstd::vector<int> RColIndices;\n\tstd::vector<long long int> RValues;\n\tint offset = 0;\n\tint currRow = 0;\n\tgraph_traits<Graph>::vertex_iterator u_iter, u_end;\n\tgraph_traits<Graph>::out_edge_iterator ei, e_end;\n\tfor (boost::tie(u_iter, u_end) = vertices(g); u_iter != u_end; ++u_iter)\n\t\tfor (boost::tie(ei, e_end) = out_edges(*u_iter, g); ei != e_end; ++ei)\n\t\t{\n\t\t\tif (capacity[*ei] > 0)\n\t\t\t{\n\t\t\t\tif (currRow <= *u_iter)\n\t\t\t\t{\n\t\t\t\t\tfor (int i = currRow; i <= *u_iter; i++)\n\t\t\t\t\t\tRRowOffsets[i] = offset;\n\t\t\t\t\tcurrRow = static_cast<int>((*u_iter) + 1);\n\t\t\t\t}\n\n\t\t\t\tRColIndices.push_back(static_cast<int>(target(*ei, g)));\n\t\t\t\tRValues.push_back(residual_capacity[*ei]);\n\t\t\t\t++offset;\n\t\t\t}\n\t\t}\n\tfor (int i = currRow; i < RRowOffsets.size(); i++)\n\t\tRRowOffsets[i] = offset;\n\n\tcompressed_matrix::CompressedMatrix<long long int> R(numVertices, numVertices, RRowOffsets, RColIndices, RValues); //residual\n\n\t//curr_2 = clock();\n\t//mexPrintf(\"inside maxFlow int version: Time elapsed_get_R: %f\\n\", ((double)curr_2 - curr_1) / CLOCKS_PER_SEC);\n\t//curr_1 = curr_2;\n\n\tstd::map<std::pair<int, int>, long long int> rm = compressed_matrix::compressedMatrixToMap(R);\n\tstd::map<std::pair<int, int>, long long int> rmMissing;\n\n\t//curr_2 = clock();\n\t//mexPrintf(\"inside maxFlow int version: Time elapsed_copy_R_to_map: %f\\n\", ((double)curr_2 - curr_1) / CLOCKS_PER_SEC);\n\t//curr_1 = curr_2;\n\n\tfor (int i = 0; i < R.numRows(); i++)\n\t{\n\t\tint start = R.rowOffsets()[i];\n\t\tint end = R.rowOffsets()[i + 1];\n\t\tfor (int j = start; j < end; j++)\n\t\t{\n\t\t\tint r = i;\n\t\t\tint c = R.colIndices()[j];\n\t\t\tlong long int Arc = A.get(r, c);\n\t\t\tlong long int Rcr = R.get(c, r);\n\t\t\tif (Arc != 0 && R.values()[j] + Rcr - Arc != 0) //it->second is: R(r, c); here it means R(r, c)+R(c, r)!=A(r, c), so R(c, r) is missing\n\t\t\t\trmMissing.insert(std::make_pair(std::make_pair(c, r), Arc - R.values()[j]));\n\t\t}\n\t}\n\n\tfor (std::map<std::pair<int, int>, long long int>::iterator it = rmMissing.begin(), end = rmMissing.end(); it != end; ++it)\n\t\trm.insert(*it);\n\n\t//curr_2 = clock();\n\t//mexPrintf(\"inside maxFlow int version: Time elapsed_get_missing_elements_in_R: %f\\n\", ((double)curr_2 - curr_1) / CLOCKS_PER_SEC);\n\t//curr_1 = curr_2;\n\n\treturn compressed_matrix::CompressedMatrix<long long int>(numVertices, numVertices, rm);\n}\n\nstd::vector<int> bfs_for_method_2(const compressed_matrix::CompressedMatrix<long long int>& g, int s)\n{\n\tstd::queue<int> q;\n\tq.push(s);\n\tint numVertices = g.numRows();\n\tstd::vector<int> visited(numVertices, -1);\n\tvisited[s] = 1;\n\n\twhile (!q.empty())\n\t{\n\t\tint curr = q.front(); q.pop();\n\t\tint start = g.rowOffsets()[curr];\n\t\tint end = g.rowOffsets()[curr + 1];\n\t\tfor (int j = start; j < end; j++)\n\t\t{\n\t\t\tint c = g.colIndices()[j];\n\t\t\tif (g.values()[j] != 0 && visited[c] == -1)\n\t\t\t{\n\t\t\t\tvisited[c] = 1;\n\t\t\t\tq.push(c);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn visited;\n}\n\ncompressed_matrix::CompressedMatrix<long long int> makeResidualSymmetric(const compressed_matrix::CompressedMatrix<long long int>& R)\n{\n\t//clock_t curr_1 = clock();\n\t//clock_t curr_2;\n\n\tint numVertices = R.numRows();\n\tint numVariables = numVertices / 2 - 1;\n\tstd::map<std::pair<int, int>, long long int> MsymR;\n\tfor (int i = 0; i < R.numRows(); i++)\n\t{\n\t\tint start = R.rowOffsets()[i];\n\t\tint end = R.rowOffsets()[i + 1];\n\t\tfor (int j = start; j < end; j++)\n\t\t{\n\t\t\tint r = i;\n\t\t\tint c = R.colIndices()[j];\n\t\t\tif (r != c)\n\t\t\t{\n\t\t\t\tMsymR[std::make_pair(r, c)] += R.values()[j];\n\t\t\t\tint compR;\n\t\t\t\tif (r <= numVariables)\n\t\t\t\t\tcompR = r + (numVariables + 1);\n\t\t\t\telse\n\t\t\t\t\tcompR = r - (numVariables + 1);\n\t\t\t\tint compC;\n\t\t\t\tif (c <= numVariables)\n\t\t\t\t\tcompC = c + (numVariables + 1);\n\t\t\t\telse\n\t\t\t\t\tcompC = c - (numVariables + 1);\n\t\t\t\tMsymR[std::make_pair(compC, compR)] += R.values()[j];\n\t\t\t}\n\t\t}\n\t}\n\n\t//curr_2 = clock();\n\t//mexPrintf(\"inside makeResidualSym: Time elapsed_get_MsymR: %f\\n\", ((double)curr_2 - curr_1) / CLOCKS_PER_SEC);\n\t//curr_1 = curr_2;\n\n\t//remove extra 0s in MsymR, required because there will possibly be 0 in MsymR and the 0 will add non-exist edges in stronglyConnectedComponents()\n\t//cause the connected components results incorrct !!!\n\tstd::map<std::pair<int, int>, long long int> MsymRWithoutZero;\n\tfor (std::map<std::pair<int, int>, long long int>::const_iterator it = MsymR.begin(), end = MsymR.end(); it != end; ++it)\n\t{\n\t\tif (it->second != 0 && it->first.first != numVariables + 1 && it->first.second != 0) //add clearing R here !!!\n\t\t\tMsymRWithoutZero.insert(*it);\n\t}\n\n\t//curr_2 = clock();\n\t//mexPrintf(\"inside makeResidualSym: Time elapsed_remove_zero_in_MsymR: %f\\n\", ((double)curr_2 - curr_1) / CLOCKS_PER_SEC);\n\t//curr_1 = curr_2;\n\n\treturn compressed_matrix::CompressedMatrix<long long int>(numVertices, numVertices, MsymRWithoutZero);\n}\n\nSCRet stronglyConnectedComponents(const compressed_matrix::CompressedMatrix<long long int>& R)\n{\n\t//clock_t curr_1 = clock();\n\t//clock_t curr_2;\n\n\tint numVertices = R.numRows();\n\tint numVariables = numVertices / 2 - 1;\n\n\tusing namespace boost;\n\n\ttypedef adjacency_list_traits < vecS, vecS, directedS > Traits;\n\ttypedef adjacency_list < vecS, vecS, directedS,\n\t\tproperty < vertex_name_t, std::string,\n\t\tproperty < vertex_index_t, long,\n\t\tproperty < vertex_color_t, boost::default_color_type,\n\t\tproperty < vertex_distance_t, long,\n\t\tproperty < vertex_predecessor_t, Traits::edge_descriptor > > > > >\n\t> Graph;\n\n\ttypedef graph_traits<Graph>::vertex_descriptor Vertex;\n\n\tGraph G;\n\n\tstd::vector<Traits::vertex_descriptor> root(numVertices);\n\tfor (int i = 0; i < numVertices; ++i)\n\t\troot[i] = add_vertex(G);\n\n\tstd::vector<int> component(num_vertices(G)), discover_time(num_vertices(G));\n\tstd::vector<default_color_type> color(num_vertices(G));\n\n\tfor (int i = 0; i < R.numRows(); i++)\n\t{\n\t\tint start = R.rowOffsets()[i];\n\t\tint end = R.rowOffsets()[i + 1];\n\t\tfor (int j = start; j < end; j++)\n\t\t{\n\t\t\tint r = i;\n\t\t\tint c = R.colIndices()[j];\n\t\t\tadd_edge(root[r], root[c], G);\n\t\t}\n\t}\n\n\t//curr_2 = clock();\n\t//mexPrintf(\"Time elapsed_constructing_graph_for_strongly_connected_components_graph: %f\\n\", ((double)curr_2 - curr_1) / CLOCKS_PER_SEC);\n\t//curr_1 = curr_2;\n\n\t//int num = strong_components(G, &component[0], root_map(&root[0]).color_map(&color[0]).discover_time_map(&discover_time[0]));\n\tint num = strong_components(G, boost::make_iterator_property_map(component.begin(), boost::get(boost::vertex_index, G)),\n\t\t\t                                root_map(boost::make_iterator_property_map(root.begin(), boost::get(boost::vertex_index, G))).color_map(boost::make_iterator_property_map(color.begin(), boost::get(boost::vertex_index, G))).discover_time_map(boost::make_iterator_property_map(discover_time.begin(), boost::get(boost::vertex_index, G))));\n\n\t//curr_2 = clock();\n\t//mexPrintf(\"Time elapsed_boost_strongly_connected_components_graph: %f\\n\", ((double)curr_2 - curr_1) / CLOCKS_PER_SEC);\n\t//curr_1 = curr_2;\n\n\t//here original's content is from 0 to 2*n+1, 0: source, 1 to n, variables, n+1: sink, n+2 to 2*n+1: bar variables\n\t//positive: from 1 to n (1-based variables index)\n\t//negative: from 1 to n (1-based variables index)\n\tstd::vector<SC> vsc(num);\n\tfor (int i = 0; i < component.size(); i++)\n\t{\n\t\tint whichComponent = component[i];\n\t\tvsc[whichComponent].original.push_back(i);\n\t\tif (vsc[whichComponent].original.back() <= numVariables)\n\t\t\tvsc[whichComponent].positive.push_back(vsc[whichComponent].original.back());\n\t\telse\n\t\t\tvsc[whichComponent].negative.push_back(vsc[whichComponent].original.back() - (numVariables + 1));\n\t}\n\n\tstd::map<std::pair<int, int>, long long int> M;\n\n\t//speed up the program a lot !!!\n\t//build the graph G for strongly connected components\n\tfor (int i = 0; i < R.numRows(); i++)\n\t{\n\t\tint start = R.rowOffsets()[i];\n\t\tint end = R.rowOffsets()[i + 1];\n\t\tfor (int j = start; j < end; j++)\n\t\t{\n\t\t\tint r = i;\n\t\t\tint c = R.colIndices()[j];\n\t\t\tint sc1 = component[r];\n\t\t\tint sc2 = component[c];\n\t\t\tif (sc1 != sc2 && R.values()[j] > 0 && M.find(std::make_pair(sc1, sc2)) == M.end())\n\t\t\t\tM.insert(std::make_pair(std::make_pair(sc1, sc2), 1));\n\t\t}\n\t}\n\n\t//curr_2 = clock();\n\t//mexPrintf(\"Time elapsed_after_boost_scc: %f\\n\", ((double)curr_2 - curr_1) / CLOCKS_PER_SEC);\n\t//curr_1 = curr_2;\n\n\tSCRet ret;\n\tret.S = vsc;\n\tret.G = compressed_matrix::CompressedMatrix<long long int>(num, num, M);\n\n\treturn ret;\n}\n\nstd::vector<int> classifyStronglyConnectedComponents(const std::vector<SC>& S)\n{\n\tstd::vector<int> ret(S.size()); //0: self-complement, 1: non-self-complement\n\n\tfor (int i = 0; i < S.size(); i++)\n\t{\n\t\tbool flag = true;\n\t\tstd::set<int> pos(S[i].positive.begin(), S[i].positive.end());\n\t\tfor (int j = 0; j < S[i].negative.size(); j++)\n\t\t{\n\t\t\tif (pos.find(S[i].negative[j]) != pos.end())\n\t\t\t{\n\t\t\t\tflag = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (flag)\n\t\t\tret[i] = 1;\n\t\telse\n\t\t\tret[i] = 0;\n\t}\n\n\treturn ret;\n}\n\nvoid shortestPath(int src, const compressed_matrix::CompressedMatrix<long long int>& g, std::vector<int>& visited)\n{\n\tstd::queue<int> q;\n\tq.push(src);\n\tvisited.resize(g.numRows(), 0);\n\tvisited[src] = 1;\n\n\twhile (!q.empty())\n\t{\n\t\tint curr = q.front(); q.pop();\n\n\t\tint start = g.rowOffsets()[curr];\n\t\tint end = g.rowOffsets()[curr + 1];\n\t\tfor (int j = start; j < end; j++)\n\t\t{\n\t\t\tint c = g.colIndices()[j];\n\t\t\tif (g.values()[j] != 0 && !visited[c])\n\t\t\t{\n\t\t\t\tvisited[c] = 2;\n\t\t\t\tq.push(c);\n\t\t\t}\n\t\t}\n\t}\n}\n\nstd::vector<std::pair<int, int> > fixVariables(const std::vector<int>& classifiedSC, const SCRet& scRet, int numVariables)\n{\n\tstd::vector<std::pair<int, int> > ret;\n\n\tint x0Location;\n\tint x0BarLocation;\n\tstd::vector<int> I;\n\n\tfor (int i = 0; i < classifiedSC.size(); i++)\n\t{\n\t\tif (classifiedSC[i] == 1) //1: non self-complement\n\t\t{\n\t\t\tif (scRet.S[i].original[0] == 0)\n\t\t\t\tx0Location = i;\n\t\t\telse if (scRet.S[i].original[0] == numVariables + 1)\n\t\t\t\tx0BarLocation = i;\n\t\t\telse\n\t\t\t\tI.push_back(i);\n\t\t}\n\t}\n\n\t//calculate if there is a path from x0 to other nodes\n\tstd::vector<int> visited;\n\tshortestPath(x0Location, scRet.G, visited); //speed up the program\n\n\t//find complement pairs\n\tstd::vector<int> positive(numVariables + 1, -1);\n\tstd::vector<int> negative(numVariables + 1, -1);\n\tfor (int i = 0; i < I.size(); i++)\n\t{\n\t\tfor (int k = 0; k < scRet.S[I[i]].positive.size(); k++)\n\t\t\tpositive[scRet.S[I[i]].positive[k]] = I[i];\n\t\tfor (int k = 0; k < scRet.S[I[i]].negative.size(); k++)\n\t\t\tnegative[scRet.S[I[i]].negative[k]] = I[i];\n\t}\n\n\tstd::map<int, int> complementPairs;\n\tfor (int i = 0; i < positive.size(); i++)\n\t{\n\t\tif (positive[i] != -1 && negative[i] != -1)\n\t\t{\n\t\t\tcomplementPairs[positive[i]] = negative[i];\n\t\t\tcomplementPairs[negative[i]] = positive[i];\n\t\t}\n\t}\n\n\tstd::queue<int> q;\n\n\tstd::map<std::pair<int, int>, long long int> GTransMap;\n\tfor (int i = 0; i < scRet.G.numRows(); i++)\n\t{\n\t\tint start = scRet.G.rowOffsets()[i];\n\t\tint end = scRet.G.rowOffsets()[i + 1];\n\t\tfor (int j = start; j < end; j++)\n\t\t\tGTransMap.insert(std::make_pair(std::make_pair(scRet.G.colIndices()[j], i), scRet.G.values()[j]));\n\t}\n\tcompressed_matrix::CompressedMatrix<long long int> GTrans(scRet.G.numRows(), scRet.G.numRows(), GTransMap);\n\n\tstd::vector<int> outDegrees(scRet.G.numRows(), -1);\n\tfor (int i = 0; i < classifiedSC.size(); i++)\n\t{\n\t\tif (classifiedSC[i] == 1) //non self-complement components\n\t\t{\n\t\t\toutDegrees[i] = scRet.G.rowOffsets()[i + 1] - scRet.G.rowOffsets()[i];\n\t\t\tif (outDegrees[i] == 0 && i != x0Location && i != x0BarLocation) //need to push the original outdegree 0 nodes into q !!!\n\t\t\t\tq.push(i);\n\t\t}\n\t}\n\toutDegrees[x0Location] = -1;\n\toutDegrees[x0BarLocation] = -1;\n\n\tfor (int i = 0; i < visited.size(); i++)\n\t{\n\t\tif (visited[i] == 2) //exclude x0\n\t\t{\n\t\t\tfor (int k = 0; k < scRet.S[i].positive.size(); k++)\n\t\t\t\tret.push_back(std::make_pair(scRet.S[i].positive[k], 1));\n\n\t\t\tfor (int k = 0; k < scRet.S[i].negative.size(); k++)\n\t\t\t\tret.push_back(std::make_pair(scRet.S[i].negative[k], 0));\n\n\t\t\tint complement = complementPairs[i];\n\n\t\t\toutDegrees[i] = -1;\n\t\t\toutDegrees[complement] = -1;\n\t\t}\n\t}\n\n\n\t//decrease the outdegrees of node which has outgoing edges to i and to complement\n\t//push node which has 0 outdegrees into the queue\n\tfor (int i = 0; i < visited.size(); i++)\n\t{\n\t\tif (visited[i] == 2) //exclude x0\n\t\t{\n\t\t\tint start = GTrans.rowOffsets()[i];\n\t\t\tint end = GTrans.rowOffsets()[i + 1];\n\t\t\tfor (int k = start; k < end; k++)\n\t\t\t{\n\t\t\t\tif (outDegrees[GTrans.colIndices()[k]] > 0)\n\t\t\t\t{\n\t\t\t\t\t--outDegrees[GTrans.colIndices()[k]];\n\t\t\t\t\tif (outDegrees[GTrans.colIndices()[k]] == 0)\n\t\t\t\t\t\tq.push(GTrans.colIndices()[k]);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tint complement = complementPairs[i];\n\t\t\tstart = GTrans.rowOffsets()[complement];\n\t\t\tend = GTrans.rowOffsets()[complement + 1];\n\t\t\tfor (int k = start; k < end; k++)\n\t\t\t{\n\t\t\t\tif (outDegrees[GTrans.colIndices()[k]] > 0)\n\t\t\t\t{\n\t\t\t\t\t--outDegrees[GTrans.colIndices()[k]];\n\t\t\t\t\tif (outDegrees[GTrans.colIndices()[k]] == 0)\n\t\t\t\t\t\tq.push(GTrans.colIndices()[k]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\n\twhile (!q.empty())\n\t{\n\t\tint curr = q.front(); q.pop();\n\t\tif (outDegrees[curr] == 0)\n\t\t{\n\t\t\toutDegrees[curr] = -1;\n\t\t\tint complement = complementPairs[curr];\n\t\t\toutDegrees[complement] = -1;\n\n\t\t\t//fixed all variables in component curr\n\t\t\tfor (int k = 0; k < scRet.S[curr].positive.size(); k++)\n\t\t\t\tret.push_back(std::make_pair(scRet.S[curr].positive[k], 1));\n\n\t\t\tfor (int k = 0; k < scRet.S[curr].negative.size(); k++)\n\t\t\t\tret.push_back(std::make_pair(scRet.S[curr].negative[k], 0));\n\n\t\t\t//decrease the outdegrees of node which has outgoing edges to i and to complement\n\t\t\t//push node which has 0 outdegrees into the queue\n\t\t\tint start = GTrans.rowOffsets()[curr];\n\t\t\tint end = GTrans.rowOffsets()[curr + 1];\n\t\t\tfor (int k = start; k < end; k++)\n\t\t\t{\n\t\t\t\tif (outDegrees[GTrans.colIndices()[k]] > 0)\n\t\t\t\t{\n\t\t\t\t\t--outDegrees[GTrans.colIndices()[k]];\n\t\t\t\t\tif (outDegrees[GTrans.colIndices()[k]] == 0)\n\t\t\t\t\t\tq.push(GTrans.colIndices()[k]);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tstart = GTrans.rowOffsets()[complement];\n\t\t\tend = GTrans.rowOffsets()[complement + 1];\n\t\t\tfor (int k = start; k < end; k++)\n\t\t\t{\n\t\t\t\tif (outDegrees[GTrans.colIndices()[k]] > 0)\n\t\t\t\t{\n\t\t\t\t\t--outDegrees[GTrans.colIndices()[k]];\n\t\t\t\t\tif (outDegrees[GTrans.colIndices()[k]] == 0)\n\t\t\t\t\t\tq.push(GTrans.colIndices()[k]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tstd::sort(ret.begin(), ret.end(), compClass());\n\n\treturn ret;\n}\n\ncompressed_matrix::CompressedMatrix<double> computeNewQAndOffset(const compressed_matrix::CompressedMatrix<double>& Q, const std::vector<std::pair<int, int> >& fixed, double& offset)\n{\n\t//fixed now is 1-based\n\tif (!fixed.empty())\n\t{\n\t\tint numVariables = Q.numRows();\n\n\t\tstd::map<int, int> mI;\n\t\tfor (int i = 0; i < fixed.size(); i++)\n\t\t\tmI[fixed[i].first - 1] = i; //-1 to make it 0-based\n\n\t\tstd::vector<int> J;\n\t\tstd::map<int, int> mJ;\n\t\tint cnt = 0;\n\t\tfor (int i = 0; i < numVariables; i++)\n\t\t{\n\t\t\tif (mI.find(i) == mI.end())\n\t\t\t{\n\t\t\t\tJ.push_back(i);\n\t\t\t\tmJ[i] = cnt++;\n\t\t\t}\n\t\t}\n\n\t\tstd::map<std::pair<int, int>, double> QII;\n\t\tstd::map<std::pair<int, int>, double> QJJ;\n\t\tstd::map<std::pair<int, int>, double> QIJ;\n\t\tstd::map<std::pair<int, int>, double> QJI;\n\n\t\tfor (int i = 0; i < Q.numRows(); i++)\n\t\t{\n\t\t\tint start = Q.rowOffsets()[i];\n\t\t\tint end = Q.rowOffsets()[i + 1];\n\t\t\tfor (int j = start; j < end; j++)\n\t\t\t{\n\t\t\t\tint r = i;\n\t\t\t\tint c = Q.colIndices()[j];\n\t\t\t\tif (mI.find(r) != mI.end() && mI.find(c) != mI.end())\n\t\t\t\t\tQII[std::make_pair(mI[r], mI[c])] = Q.values()[j];\n\t\t\t\tif (mJ.find(r) != mJ.end() && mJ.find(c) != mJ.end())\n\t\t\t\t\tQJJ[std::make_pair(mJ[r], mJ[c])] = Q.values()[j];\n\t\t\t\tif (mI.find(r) != mI.end() && mJ.find(c) != mJ.end())\n\t\t\t\t\tQIJ[std::make_pair(mI[r], mJ[c])] = Q.values()[j];\n\t\t\t\tif (mJ.find(r) != mJ.end() && mI.find(c) != mI.end())\n\t\t\t\t\tQJI[std::make_pair(mJ[r], mI[c])] = Q.values()[j];\n\t\t\t}\n\t\t}\n\n\t\t//off_set = x0'*Q_II*x0;\n\t\toffset = 0;\n\t\tfor (std::map<std::pair<int, int>, double>::const_iterator it = QII.begin(), end = QII.end(); it != end; ++it)\n\t\t{\n\t\t\tint r = it->first.first;\n\t\t\tint c = it->first.second;\n\t\t\toffset += fixed[r].second * it->second * fixed[c].second;\n\t\t}\n\n\t\t//x0'*Q_IJ\n\t\tstd::vector<double> tmp2(numVariables - fixed.size(), 0);\n\t\tfor (std::map<std::pair<int, int>, double>::const_iterator it = QIJ.begin(), end = QIJ.end(); it != end; ++it)\n\t\t{\n\t\t\tint r = it->first.first;\n\t\t\tint c = it->first.second;\n\t\t\ttmp2[c] += it->second * fixed[r].second;\n\t\t}\n\n\t\t//Q_JI*x0\n\t\tstd::vector<double> tmp3(numVariables - fixed.size(), 0);\n\t\tfor (std::map<std::pair<int, int>, double>::const_iterator it = QJI.begin(), end = QJI.end(); it != end; ++it)\n\t\t{\n\t\t\tint r = it->first.first;\n\t\t\tint c = it->first.second;\n\t\t\ttmp3[r] += it->second * fixed[c].second;\n\t\t}\n\n\t\tfor (int i = 0; i < (int)tmp3.size(); i++)\n\t\t\ttmp2[i] += tmp3[i];\n\n\t\tcnt = 0;\n\t\tfor (int i = 0; i < (int)mJ.size() * (int)mJ.size(); i += numVariables - static_cast<int>(fixed.size()) + 1)\n\t\t{\n\t\t\tint r = i / static_cast<int>(mJ.size());\n\t\t\tint c = i % mJ.size();\n\t\t\tQJJ[std::make_pair(r, c)] += tmp2[cnt++];\n\t\t}\n\n\t\tstd::map<std::pair<int, int>, double> mfixedQ;\n\t\tfor (std::map<std::pair<int, int>, double>::const_iterator it = QJJ.begin(), end = QJJ.end(); it != end; ++it)\n\t\t{\n\t\t\tint r = it->first.first;\n\t\t\tint c = it->first.second;\n\t\t\tif (it->second != 0)\n\t\t\t\tmfixedQ[std::make_pair(J[r], J[c])] = it->second;\n\t\t}\n\n\t\treturn compressed_matrix::CompressedMatrix<double>(numVariables, numVariables, mfixedQ);\n\t}\n\telse\n\t{\n\t\toffset = 0;\n\t\treturn Q;\n\t}\n}\n\nstd::vector<std::pair<int, int> > applyImplication(const compressed_matrix::CompressedMatrix<long long int>& A)\n{\n\tint numVertices = A.numRows();\n\tint numVariables = numVertices / 2 - 1;\n\n\t//debuging only\n\t//clock_t curr_1 = clock();\n\t//clock_t curr_2;\n\n\tusing namespace boost;\n\n\ttypedef adjacency_list_traits<vecS, vecS, directedS> Traits;\n\ttypedef adjacency_list<vecS, vecS, directedS, property<vertex_name_t, std::string>, property<edge_capacity_t, long long int, property<edge_residual_capacity_t, long long int, property<edge_reverse_t, Traits::edge_descriptor> > > > Graph; //for edge capacity is long long int\n\t//typedef adjacency_list<vecS, vecS, directedS, property<vertex_name_t, std::string>, property<edge_capacity_t, double, property<edge_residual_capacity_t, double, property<edge_reverse_t, Traits::edge_descriptor> > > > Graph; //for edge capacity is double\n\n\tGraph g;\n\n\tproperty_map<Graph, edge_capacity_t>::type capacity = get(edge_capacity, g);\n\tproperty_map<Graph, edge_reverse_t>::type reverse_edge = get(edge_reverse, g);\n\tproperty_map<Graph, edge_residual_capacity_t>::type residual_capacity = get(edge_residual_capacity, g);\n\n\tstd::vector<Traits::vertex_descriptor> verts(numVertices);\n\tfor (int i = 0; i < numVertices; ++i)\n\t\tverts[i] = add_vertex(g);\n\n\tTraits::vertex_descriptor s = verts[numVariables];\n\tTraits::vertex_descriptor t = verts[2 * numVariables + 1];\n\n\tfor (int i = 0; i < A.numRows(); i++)\n\t{\n\t\tint start = A.rowOffsets()[i];\n\t\tint end = A.rowOffsets()[i + 1];\n\t\tfor (int j = start; j < end; j++)\n\t\t{\n\t\t\tint r = i;\n\t\t\tint c = A.colIndices()[j];\n\t\t\tlong long int cap = A.values()[j];\n\n\t\t\tTraits::edge_descriptor e1, e2;\n\t\t\tbool in1, in2;\n\t\t\tboost::tie(e1, in1) = add_edge(verts[r], verts[c], g);\n\t\t\tboost::tie(e2, in2) = add_edge(verts[c], verts[r], g);\n\n\t\t\tcapacity[e1] = cap;\n\t\t\tcapacity[e2] = 0;\n\t\t\treverse_edge[e1] = e2;\n\t\t\treverse_edge[e2] = e1;\n\t\t}\n\t}\n\n\t//curr_2 = clock();\n\t//mexPrintf(\"inside applyImplication int version: Time elapsed_building_graph: %f\\n\", ((double)curr_2 - curr_1) / CLOCKS_PER_SEC);\n\t//curr_1 = curr_2;\n\n\tpush_relabel_max_flow(g, s, t);\n\n\t//curr_2 = clock();\n\t//mexPrintf(\"inside applyImplication int version: Time elapsed_max_flow: %f\\n\", ((double)curr_2 - curr_1) / CLOCKS_PER_SEC);\n\t//curr_1 = curr_2;\n\n\t//residual\n\tstd::vector<int> RRowOffsets(numVertices+1);\n\tstd::vector<int> RColIndices;\n\tstd::vector<long long int> RValues;\n\t//flow\n\tstd::vector<int> FRowOffsets(numVertices+1);\n\tstd::vector<int> FColIndices;\n\tstd::vector<long long int> FValues;\n\n\tint offset = 0;\n\tint currRow = 0;\n\tgraph_traits<Graph>::vertex_iterator u_iter, u_end;\n\tgraph_traits<Graph>::out_edge_iterator ei, e_end;\n\tfor (boost::tie(u_iter, u_end) = vertices(g); u_iter != u_end; ++u_iter)\n\t\tfor (boost::tie(ei, e_end) = out_edges(*u_iter, g); ei != e_end; ++ei)\n\t\t{\n\t\t\tif (capacity[*ei] > 0)\n\t\t\t{\n\t\t\t\tif (currRow <= *u_iter)\n\t\t\t\t{\n\t\t\t\t\tfor (int i = currRow; i <= *u_iter; i++)\n\t\t\t\t\t{\n\t\t\t\t\t\tRRowOffsets[i] = offset;\n\t\t\t\t\t\tFRowOffsets[i] = offset;\n\t\t\t\t\t}\n\t\t\t\t\tcurrRow = static_cast<int>((*u_iter) + 1);\n\t\t\t\t}\n\t\t\t\tRColIndices.push_back(static_cast<int>(target(*ei, g)));\n\t\t\t\tRValues.push_back(residual_capacity[*ei]);\n\t\t\t\tFColIndices.push_back(static_cast<int>(target(*ei, g)));\n\t\t\t\tFValues.push_back(capacity[*ei] - residual_capacity[*ei]);\n\t\t\t\t++offset;\n\t\t\t}\n\t\t}\n\tfor (int i = currRow; i < RRowOffsets.size(); i++)\n\t\tRRowOffsets[i] = offset;\n\tfor (int i = currRow; i < FRowOffsets.size(); i++)\n\t\tFRowOffsets[i] = offset;\n\n\tcompressed_matrix::CompressedMatrix<long long int> R(numVertices, numVertices, RRowOffsets, RColIndices, RValues); //residual\n\tcompressed_matrix::CompressedMatrix<long long int> F(numVertices, numVertices, FRowOffsets, FColIndices, FValues); //flow\n\n\t//curr_2 = clock();\n\t//mexPrintf(\"inside applyImplication int version: Time elapsed_get_RF: %f\\n\", ((double)curr_2 - curr_1) / CLOCKS_PER_SEC);\n\t//curr_1 = curr_2;\n\n\t//resid = (A>0).*R + F'.*(A'>0);\n\tstd::map<std::pair<int, int>, long long int> residM;\n\tfor (int i = 0; i < A.numRows(); i++)\n\t{\n\t\tint start = A.rowOffsets()[i];\n\t\tint end = A.rowOffsets()[i + 1];\n\t\tfor (int j = start; j < end; j++)\n\t\t{\n\t\t\tint r = i;\n\t\t\tint c = A.colIndices()[j];\n\t\t\tlong long int RValue = R.get(r, c);\n\t\t\tif (A.values()[j] > 0 && RValue != 0 && r != 2 * numVariables + 1 && c != numVariables)\n\t\t\t\tresidM[std::make_pair(r, c)] += RValue;\n\n\t\t\tlong long int FTValue = F.get(r, c); //not F(c, r) !!!\n\t\t\tif (A.values()[j] > 0 && FTValue != 0 && c != 2 * numVariables + 1 && r != numVariables)\n\t\t\t\tresidM[std::make_pair(c, r)] += FTValue;\n\t\t}\n\t}\n\n\tcompressed_matrix::CompressedMatrix<long long int> resid(numVertices, numVertices, residM);\n\n\t//curr_2 = clock();\n\t//mexPrintf(\"inside applyImplication int version: Time elapsed_finally_get_resid: %f\\n\", ((double)curr_2 - curr_1) / CLOCKS_PER_SEC);\n\t//curr_1 = curr_2;\n\n\tstd::vector<int> forced = bfs_for_method_2(resid, numVariables);\n\n\t//curr_2 = clock();\n\t//mexPrintf(\"inside applyImplication int version: Time elapsed_bfs_for_method_2: %f\\n\", ((double)curr_2 - curr_1) / CLOCKS_PER_SEC);\n\t//curr_1 = curr_2;\n\n\tstd::vector<std::pair<int, int> > fixed;\n\tfor (int i = 0; i < forced.size(); i++)\n\t{\n\t\tif (forced[i] > 0)\n\t\t{\n\t\t\tif (i <= numVariables - 1)\n\t\t\t\tfixed.push_back(std::make_pair(i + 1, 1)); //1-based\n\t\t\telse if (i >= numVariables + 1 && i <= 2 * numVariables)\n\t\t\t\tfixed.push_back(std::make_pair(i - numVariables, 0)); //1-based\n\t\t}\n\t}\n\n\tstd::sort(fixed.begin(), fixed.end(), compClass());\n\n\t//curr_2 = clock();\n\t//mexPrintf(\"inside applyImplication int version: Time elapsed_fix_vars_and_sorting: %f\\n\", ((double)curr_2 - curr_1) / CLOCKS_PER_SEC);\n\t//curr_1 = curr_2;\n\n\treturn fixed;\n}\n\n} // anonymous namespace\n\nnamespace fix_variables_\n{\n\nFixVariablesResult fixQuboVariables(const compressed_matrix::CompressedMatrix<double>& Q, int method)\n{\n\t//Q needs to be a square matrix\n\tif (Q.numRows() != Q.numCols())\n\t\tthrow FixVariablesException(\"Q's size is not correct.\");\n\n\tif (!(method == 1 || method == 2))\n\t\tthrow FixVariablesException(\"method must be an integer of 1 or 2.\");\n\n\tFixVariablesResult ret;\n\n\t//check if Q is empty\n\tif (Q.numRows() == 0 || Q.numCols() == 0)\n\t{\n\t\tret.offset = 0;\n\t\treturn ret;\n\t}\n\n\tint numVariables = Q.numRows();\n\n\t//clock_t curr_1 = clock();\n\t//clock_t curr_2;\n\n\t//uTriQ = triu(Q) + tril(Q,-1)'; //make upper triangular\n\tstd::map<std::pair<int, int>, double> uTriQMap;\n\tstd::set<int> usedVariables;\n\tfor (int i = 0; i < Q.numRows(); i++)\n\t{\n\t\tint start = Q.rowOffsets()[i];\n\t\tint end = Q.rowOffsets()[i + 1];\n\t\tfor (int j = start; j < end; j++)\n\t\t{\n\t\t\tint r = i;\n\t\t\tint c = Q.colIndices()[j];\n\t\t\tuTriQMap[std::make_pair(std::min(r, c), std::max(r, c))] += Q.values()[j];\n\t\t\tusedVariables.insert(r);\n\t\t\tusedVariables.insert(c);\n\t\t}\n\t}\n\n\tcompressed_matrix::CompressedMatrix<double> uTriQ(numVariables, numVariables, uTriQMap);\n\n\tdouble maxAbsValue = 0;\n\n\tif (!uTriQ.values().empty())\n\t\tmaxAbsValue = std::fabs(*std::max_element(uTriQ.values().begin(), uTriQ.values().end(), compareAbs));\n\n\tdouble ratio = 1;\n\n\tif (maxAbsValue != 0)\n\t\tratio = static_cast<double>(std::numeric_limits<long long int>::max()) / maxAbsValue;\n\n\tratio /= static_cast<double>(1LL << 10);\n\n\tif (ratio < 1)\n\t\tratio = 1;\n\n\tstd::map<std::pair<int, int>, long long int> uTriQMapLLI;\n\n\tfor (std::map<std::pair<int, int>, double>::iterator it = uTriQMap.begin(), end = uTriQMap.end(); it != end; ++it)\n\t\tuTriQMapLLI[it->first] = static_cast<long long int>(it->second * ratio);\n\n\tcompressed_matrix::CompressedMatrix<long long int> uTriQLLI(numVariables, numVariables, uTriQMapLLI);\n\n\t//curr_2 = clock();\n\t//mexPrintf(\"Time elapsed_make upper triangular: %f\\n\", ((double)curr_2 - curr_1) / CLOCKS_PER_SEC);\n\t//curr_1 = curr_2;\n\n\tPosiform p = BQPToPosiform(uTriQLLI);\n\n\t//curr_2 = clock();\n\t//mexPrintf(\"Time elapsed_BQPToPosiform: %f\\n\", ((double)curr_2 - curr_1) / CLOCKS_PER_SEC);\n\t//curr_1 = curr_2;\n\n\tif (method == 1)\n\t{\n\t\tcompressed_matrix::CompressedMatrix<long long int> A = posiformToImplicationNetwork_1(p);\n\n\t\t//curr_2 = clock();\n\t    //mexPrintf(\"Time elapsed_posiformToImplicationNetwork_1: %f\\n\", ((double)curr_2 - curr_1) / CLOCKS_PER_SEC);\n\t    //curr_1 = curr_2;\n\n\t\tcompressed_matrix::CompressedMatrix<long long int> R = maxFlow(A);  //use this\n\n\t\t//curr_2 = clock();\n\t    //mexPrintf(\"Time elapsed_maxFlow: %f\\n\", ((double)curr_2 - curr_1) / CLOCKS_PER_SEC);\n\t    //curr_1 = curr_2;\n\n\t\tcompressed_matrix::CompressedMatrix<long long int> symR = makeResidualSymmetric(R); //use this\n\n\t\t//curr_2 = clock();\n\t    //mexPrintf(\"Time elapsed_makeRSym: %f\\n\", ((double)curr_2 - curr_1) / CLOCKS_PER_SEC);\n\t    //curr_1 = curr_2;\n\n\t\t//add clearing R in makeResidualSym, so here just use symR directly !!!\n\t\tSCRet scRet = stronglyConnectedComponents(symR);\n\n\n\t\t//curr_2 = clock();\n\t    //mexPrintf(\"Time elapsed_stronglyConnectedComponents: %f\\n\", ((double)curr_2 - curr_1) / CLOCKS_PER_SEC);\n\t    //curr_1 = curr_2;\n\n\t\tstd::vector<int> classifiedSC = classifyStronglyConnectedComponents(scRet.S);\n\n\t\t//curr_2 = clock();\n\t    //mexPrintf(\"Time elapsed_classifyStrongComponents: %f\\n\", ((double)curr_2 - curr_1) / CLOCKS_PER_SEC);\n\t    //curr_1 = curr_2;\n\n\t\tret.fixedVars = fixVariables(classifiedSC, scRet, numVariables);\n\n\t\t//curr_2 = clock();\n\t    //mexPrintf(\"Time elapsed_fixVarsUsingOutDegree: %f\\n\", ((double)curr_2 - curr_1) / CLOCKS_PER_SEC);\n\t    //curr_1 = curr_2;\n\t}\n\telse if (method == 2)\n\t{\n\t\tcompressed_matrix::CompressedMatrix<long long int> A = posiformToImplicationNetwork_2(p);\n\n\t\t//curr_2 = clock();\n\t    //mexPrintf(\"Time elapsed_posiformToImplicationNetwork_2: %f\\n\", ((double)curr_2 - curr_1) / CLOCKS_PER_SEC);\n\t    //curr_1 = curr_2;\n\n\t\tret.fixedVars = applyImplication(A);\n\n\t\t//curr_2 = clock();\n\t    //mexPrintf(\"Time elapsed_applyImplication: %f\\n\", ((double)curr_2 - curr_1) / CLOCKS_PER_SEC);\n\t    //curr_1 = curr_2;\n\t}\n\n\tif (ret.fixedVars.size() > numVariables)\n\t\tthrow FixVariablesException(\"ret.fixedVars has wrong size.\");\n\n\t// remove unused variables from ret.fixedVars\n\tstd::vector<std::pair<int, int> > updatedFixedVars;\n\tfor (int i = 0; i < ret.fixedVars.size(); ++i)\n\t{\n\t\tif (usedVariables.find(ret.fixedVars[i].first - 1) != usedVariables.end()) // -1 to make it 0-based since usedVariables is 0-based\n\t\t\tupdatedFixedVars.push_back(ret.fixedVars[i]);\n\t}\n\n\tret.fixedVars = updatedFixedVars;\n\n\tret.newQ = computeNewQAndOffset(uTriQ, ret.fixedVars, ret.offset);\n\n\t//curr_2 = clock();\n\t//mexPrintf(\"Time elapsed_computeNewQAndOffset: %f\\n\", ((double)curr_2 - curr_1) / CLOCKS_PER_SEC);\n\t//curr_1 = curr_2;\n\n\treturn ret;\n}\n\n\nstd::vector<std::pair<int,  int> > fixQuboVariablesMap(std::map<std::pair<int, int>, double> QMap, int QSize, int mtd)\n{\n    compressed_matrix::CompressedMatrix<double> QInput(QSize, QSize, QMap);\n\n    FixVariablesResult ret = fixQuboVariables(QInput, mtd);\n\n    return ret.fixedVars;\n}\n\n\n} // namespace fix_variables_\n", "meta": {"hexsha": "a77987e3c3055b92132dd97c5289e42dc7463faf", "size": 39201, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dimod/roof_duality/src/fix_variables.cpp", "max_stars_repo_name": "joseppinilla/dimod", "max_stars_repo_head_hexsha": "e33ca5045e31ee2d9d58515f017fb6be5276cd8e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-03T16:42:26.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-03T16:42:26.000Z", "max_issues_repo_path": "dimod/roof_duality/src/fix_variables.cpp", "max_issues_repo_name": "xpin/dimod", "max_issues_repo_head_hexsha": "5e399317b0bfaae6ed20e22b9f2ef242f5fa5e6c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dimod/roof_duality/src/fix_variables.cpp", "max_forks_repo_name": "xpin/dimod", "max_forks_repo_head_hexsha": "5e399317b0bfaae6ed20e22b9f2ef242f5fa5e6c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-08-15T17:16:46.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-15T17:16:46.000Z", "avg_line_length": 30.2243639167, "max_line_length": 338, "alphanum_fraction": 0.6355960307, "num_tokens": 12702, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300048, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.46040212934633973}}
{"text": "#pragma once\n\n#include \"optimizationtools/indexed_set.hpp\"\n#include \"optimizationtools/utils.hpp\"\n\n#include <iostream>\n#include <fstream>\n\n#include <boost/filesystem.hpp>\n#include <boost/regex.hpp>\n\n/**\n * Time-dependent orienteering problem.\n *\n * Input:\n * - n locations; for each location j = 1..n, a profit p\u2c7c\n * - a function t(j\u2081, j\u2082, s) which returns the time to travel from location j\u2081\n *   to location j\u2082 starting at time s\n * - a time limit t\u2098\u2090\u2093\n * Problem:\n * - Find a path starting at location 1 and ending at location n such that:\n *   - each location is visited at most once\n *   - the arrival at location n is before t\u2098\u2090\u2093\n * Objective:\n * - Maximize the total profit of the visited locations\n *\n */\n\nnamespace orproblems\n{\n\nnamespace timedependentorienteering\n{\n\nusing LocationId = int64_t;\nusing LocationPos = int64_t;\nusing ArcCategory = int64_t;\nusing TimePeriod = int64_t;\nusing Time = double;\nusing Length = double;\nusing Profit = double;\n\nstruct Location\n{\n    Length x;\n    Length y;\n    Profit profit;\n};\n\nstruct Arc\n{\n    ArcCategory category;\n    Length length;\n};\n\nclass Instance\n{\n\npublic:\n\n    Instance(LocationId n):\n        locations_(n),\n        arcs_(n, std::vector<Arc>(n)) { }\n    void set_maximum_duration(Time maximum_duration) { maximum_duration_ = maximum_duration; }\n\n    Instance(std::string instance_path, std::string format = \"\")\n    {\n        std::ifstream file(instance_path);\n        if (!file.good())\n            throw std::runtime_error(\n                    \"Unable to open file \\\"\" + instance_path + \"\\\".\");\n        if (format == \"\" || format == \"verbeeck2014\") {\n            read_verbeeck2014(file, instance_path);\n        } else {\n            throw std::invalid_argument(\n                    \"Unknown instance format \\\"\" + format + \"\\\".\");\n        }\n        file.close();\n    }\n\n    virtual ~Instance() { }\n\n    inline LocationId number_of_locations() const { return locations_.size(); }\n    inline const Location& location(LocationId j) const { return locations_[j]; }\n    inline Time maximum_duration() const { return maximum_duration_; }\n    inline Time arrival_time(LocationId j1, LocationId j2, Time start) const\n    {\n        Time current_time = start;\n        Length remaining_length = arcs_[j1][j2].length;\n        ArcCategory arc_category = arcs_[j1][j2].category;\n        TimePeriod time_period =\n            (current_time < 9 - 7)? 0:\n            (current_time < 17 - 7)? 1:\n            (current_time < 19 - 7)? 2:\n            3;\n        for (;;) {\n            Time time_period_end =\n                (time_period == 0)? 9 - 7:\n                (time_period == 1)? 17 - 7:\n                (time_period == 2)? 19 - 7:\n                std::numeric_limits<Time>::max();\n            double speed = speed_matrix_[arc_category][time_period];\n            Time at = current_time + remaining_length / speed;\n            if (at <= time_period_end) {\n                //std::cout << \"j1 \" << j1\n                //    << \" j2 \" << j2\n                //    << \" x1 \" << locations_[j1].x\n                //    << \" y1 \" << locations_[j1].y\n                //    << \" x2 \" << locations_[j2].x\n                //    << \" y2 \" << locations_[j2].y\n                //    << \" length \" << arcs_[j1][j2].length\n                //    << \" cat \" << arc_category\n                //    << \" start \" << start\n                //    << \" dur \" << at - start\n                //    << \" arrival \" << at << \" / \" << time_period_end\n                //    << std::endl;\n                return at;\n            }\n            remaining_length -= (time_period_end - current_time) * speed;\n            //std::cout << \"remaining_length \" << remaining_length << std::endl;\n            current_time = time_period_end;\n            time_period++;\n        }\n        return -1;\n    }\n\n    std::pair<bool, Time> check(\n            std::string certificate_path,\n            int verbose = 1) const\n    {\n        // Initial display.\n        if (verbose >= 1) {\n            std::cout\n                << \"Checker\" << std::endl\n                << \"-------\" << std::endl;\n        }\n\n        std::ifstream file(certificate_path);\n        if (!file.good())\n            throw std::runtime_error(\n                    \"Unable to open file \\\"\" + certificate_path + \"\\\".\");\n\n        LocationId n = number_of_locations();\n        LocationId j = -1;\n        LocationId j_prec = 0;\n        optimizationtools::IndexedSet locations(n);\n        locations.add(0);\n        locations.add(n - 1);\n        LocationPos number_of_duplicates = 0;\n        Time current_time = 0;\n        Profit profit = location(0).profit;\n        while (file >> j) {\n            if (locations.contains(j)) {\n                number_of_duplicates++;\n                if (verbose == 2)\n                    std::cout << \"Location \" << j << \" is already scheduled.\" << std::endl;\n            }\n            locations.add(j);\n            current_time = arrival_time(j_prec, j, current_time);\n            profit += location(j).profit;\n            if (verbose == 2)\n                std::cout << \"Location: \" << j\n                    << \"; Time: \" << current_time\n                    << \"; Profit: \" << profit << \" (\" << location(j).profit << \")\"\n                    << std::endl;\n            j_prec = j;\n        }\n        current_time = arrival_time(j_prec, n - 1, current_time);\n        profit += location(n - 1).profit;\n\n        bool feasible\n            = (current_time <= maximum_duration())\n            && (number_of_duplicates == 0);\n        if (verbose == 2)\n            std::cout << \"---\" << std::endl;\n        if (verbose >= 1) {\n            std::cout << \"Number of locations:       \" << locations.size() << \" / \" << n  << std::endl;\n            std::cout << \"Number of duplicates:      \" << number_of_duplicates << std::endl;\n            std::cout << \"Duraction:                 \" << current_time << \" / \" << maximum_duration() << std::endl;\n            std::cout << \"Feasible:                  \" << feasible << std::endl;\n            std::cout << \"Profit:                    \" << profit << std::endl;\n        }\n        return {feasible, profit};\n    }\n\nprivate:\n\n    void read_verbeeck2014(\n            std::ifstream& file,\n            std::string instance_path)\n    {\n        std::string tmp;\n        LocationId n = -1;\n        file\n            >> tmp >> n\n            >> tmp >> tmp\n            >> tmp >> maximum_duration_\n            ;\n        locations_ = std::vector<Location>(n);\n        for (LocationId j = 0; j < n; ++j)\n            file >> locations_[j].x >> locations_[j].y >> locations_[j].profit;\n        arcs_ = std::vector<std::vector<Arc>>(n, std::vector<Arc>(n));\n        for (LocationId j1 = 0; j1 < n; ++j1) {\n            for (LocationId j2 = 0; j2 < n; ++j2) {\n                Length dx = locations_[j1].x - locations_[j2].x;\n                Length dy = locations_[j1].y - locations_[j2].y;\n                Length dxy = std::sqrt(dx * dx + dy * dy);\n                dxy /= 5;\n                arcs_[j1][j2].length = dxy;\n            }\n        }\n\n        // Read speed matrix.\n        auto speed_matrix_path = boost::filesystem::path(instance_path)\n            .parent_path().parent_path().parent_path() /= \"speedmatrix.txt\";\n        std::ifstream speed_matrix_file(speed_matrix_path.string());\n        speed_matrix_ = std::vector<std::vector<double>>(\n                5, std::vector<double>(4, 0.0));\n        for (ArcCategory arc_category = 0; arc_category < 5; ++arc_category)\n            for (TimePeriod time_period = 0; time_period < 4; ++time_period)\n                speed_matrix_file >> speed_matrix_[arc_category][time_period];\n\n        // Read arc category matrix.\n        boost::filesystem::directory_iterator it_end;\n        auto arc_category_directory = boost::filesystem::path(instance_path)\n            .parent_path().parent_path();\n        const boost::regex filter(\"arc_cat_.*\\\\.txt\");\n        for (boost::filesystem::directory_iterator it(arc_category_directory); it != it_end; ++it) {\n            if (!boost::filesystem::is_regular_file(it->status()))\n                continue;\n            boost::smatch what;\n            // For V2:\n            //if(!boost::regex_match(it->leaf(), what, filter))\n            //    continue;\n            // For V3:\n            if (!boost::regex_match(it->path().filename().string(), what, filter))\n                continue;\n            // File matches, store it\n            std::ifstream arc_category_file(it->path().string());\n            for (LocationId location_id_1 = 0; location_id_1 < number_of_locations(); ++location_id_1)\n                for (LocationId location_id_2 = 0; location_id_2 < number_of_locations(); ++location_id_2)\n                    arc_category_file >> arcs_[location_id_1][location_id_2].category;\n        }\n    }\n\n    std::vector<Location> locations_;\n    std::vector<std::vector<Arc>> arcs_;\n    std::vector<std::vector<double>> speed_matrix_;\n    Time maximum_duration_ = 0;\n\n};\n\nstatic inline std::ostream& operator<<(\n        std::ostream &os, const Instance& instance)\n{\n    os << \"number of locations: \" << instance.number_of_locations() << std::endl;\n    for (LocationId j = 0; j < instance.number_of_locations(); ++j) {\n        os << \"location \" << j\n            << \" profit \" << instance.location(j).profit;\n        os << std::endl;\n    }\n    return os;\n}\n\n}\n\n}\n\n", "meta": {"hexsha": "29b8adcdf1d4d90593d1be7eb8ad71b6761cb64b", "size": 9333, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "orproblems/timedependentorienteering.hpp", "max_stars_repo_name": "fontanf/orproblems", "max_stars_repo_head_hexsha": "abcdd0f271bd86eefe1e6af00b052583e44721c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-23T15:53:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T15:53:58.000Z", "max_issues_repo_path": "orproblems/timedependentorienteering.hpp", "max_issues_repo_name": "fontanf/orproblems", "max_issues_repo_head_hexsha": "abcdd0f271bd86eefe1e6af00b052583e44721c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "orproblems/timedependentorienteering.hpp", "max_forks_repo_name": "fontanf/orproblems", "max_forks_repo_head_hexsha": "abcdd0f271bd86eefe1e6af00b052583e44721c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-19T11:46:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-19T11:46:55.000Z", "avg_line_length": 34.6951672862, "max_line_length": 115, "alphanum_fraction": 0.5287688846, "num_tokens": 2247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585903489892, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.4604021265668941}}
{"text": "/**\n * @file yaml_eigen.h\n * @author Alexander Herzog\n * @license License BSD-3-Clause\n * @copyright Copyright (c) 2019, New York University and Max Planck Gesellschaft.\n * @date 2015-02-27\n * \n * @brief Add support for eigen frm the yaml-cpp standard package.\n */\n\n#pragma once\n\n#include <type_traits>\n#include <iomanip>\n#include <Eigen/Eigen>\n#include <yaml-cpp/yaml.h>\n\nnamespace robot_math{\ntemplate<class T>\nstruct MovableEigenVector;\ntemplate<class T>\nstruct MovableEigenMatrix;\n}\n\nnamespace YAML {\n\ntemplate<class Scalar, int Rows, int Cols, int Align, int RowsAtCompileTime, int ColsAtCompileTime>\nstruct EigenVectorConverter{\n  typedef Eigen::Matrix<Scalar,  Rows,  Cols,  Align,  RowsAtCompileTime,  ColsAtCompileTime> VectorType;\n\n  static void resize_if_needed(int rows, int cols, VectorType& rhs){\n    if(rhs.size() != rows*cols)\n    {\n      if (VectorType::SizeAtCompileTime == Eigen::Dynamic &&\n          VectorType::MaxSizeAtCompileTime == Eigen::Dynamic)\n      {\n        rhs.resize(rows*cols);\n      }else\n      {\n        std::ostringstream error;\n        error << \"ERROR: The fixed sized vector of size (\" << rhs.size()\n              << \") is of different size than the input yaml data vector of \"\n              << \"size (\" << rows * cols << \").\" ;\n        throw(std::runtime_error(error.str()));\n      }\n    }\n  }\n\n  static Scalar& access_element(int r, int c, VectorType& rhs)\n  {\n    return rhs(r+c);\n  }\n};\n\ntemplate<class Scalar, int Rows, int Cols, int Align, int RowsAtCompileTime, int ColsAtCompileTime>\nstruct EigenMatrixConverter{\n  typedef Eigen::Matrix<Scalar,  Rows,  Cols,  Align,  RowsAtCompileTime,  ColsAtCompileTime> MatrixType;\n\n  static void resize_if_needed(int rows, int cols, MatrixType& rhs){\n    if(rhs.rows() != rows || rhs.cols() != cols)\n    {\n      if (MatrixType::SizeAtCompileTime == Eigen::Dynamic &&\n          MatrixType::MaxSizeAtCompileTime == Eigen::Dynamic)\n      {\n        rhs.resize(rows, cols);\n      }else\n      {\n        std::ostringstream error;\n        error << \"ERROR: The fixed sized matrix of dim (\" << rhs.rows() << \",\"\n              << rhs.cols() << \") is of different dim than the input yaml \"\n              << \"data matrix of dim (\" << rows << \",\" << cols << \").\" ;\n        throw(std::runtime_error(error.str()));\n      }\n    }\n  }\n\n\n  static Scalar& access_element(int r, int c, MatrixType& rhs){\n    return rhs(r, c);\n  }\n};\n\ntemplate<class Scalar, int Rows, int Cols, int Align, int RowsAtCompileTime, int ColsAtCompileTime>\nstruct convert<Eigen::Matrix<Scalar,  Rows,  Cols,  Align,  RowsAtCompileTime,  ColsAtCompileTime> >{\n  typedef Eigen::Matrix<Scalar,  Rows,  Cols,  Align,  RowsAtCompileTime,  ColsAtCompileTime> Eigen_Type_;\n  const static bool is_vector_type_ = Rows == 1 || Cols == 1;\n  typedef typename std::conditional<is_vector_type_,\n      EigenVectorConverter<Scalar, Rows, Cols, Align, RowsAtCompileTime, ColsAtCompileTime>,\n      EigenMatrixConverter<Scalar, Rows, Cols, Align, RowsAtCompileTime, ColsAtCompileTime>>::type Converter_;\n\n  static Node encode(const Eigen_Type_& rhs) {\n    Eigen::IOFormat yaml_format(Eigen::FullPrecision, Eigen::DontAlignCols, \", \", \", \", \"[\", \"]\", \"[\", \"]\");\n    std::stringstream ss;\n    ss << std::setprecision (std::numeric_limits<double>::digits10 + 1) << rhs.format(yaml_format);\n    return Load(ss.str());\n  }\n\n  static bool decode_2d(const Node& node, Eigen_Type_& rhs){\n    const size_t n_rows = node.size();\n    const size_t n_cols = node[0].size();\n    Converter_::resize_if_needed(n_rows, n_cols, rhs);\n\n    for (size_t r=0;r<n_rows;++r){\n      const Node& yaml_row = node[r];\n      if(yaml_row.size() != n_cols)\n        return false;\n      for (size_t c=0;c<n_cols;++c)\n        Converter_::access_element(r, c, rhs) = yaml_row[c].as<Scalar>();\n    }\n\n    return true;\n  }\n\n  static bool decode_1d(const Node& node, Eigen_Type_& rhs){\n    const size_t n_size = node.size();\n    Converter_::resize_if_needed(n_size, 1, rhs);\n    for (size_t r=0;r<n_size;++r)\n      Converter_::access_element(r, 0, rhs) = node[r].as<Scalar>();\n    return true;\n  };\n\n  static bool decode(const Node& node, Eigen_Type_& rhs){\n    if(!node.IsSequence())\n      return false;\n    if(node.size() > 0)\n    {\n      if(!node[0].IsSequence())\n        return decode_1d(node, rhs);\n      else\n        return decode_2d(node, rhs);\n    }\n    else\n    {\n      Converter_::resize_if_needed(0, 0, rhs);\n      return true;\n    }    \n  }\n};\n\n\ntemplate<class T>\nstruct convert<robot_math::MovableEigenVector<T>> {\n  static Node encode(const robot_math::MovableEigenVector<T>& mp){\n    return convert<T>::encode(static_cast<const T&>(mp));\n  }\n  static bool decode(const Node& node, robot_math::MovableEigenVector<T>& mp){\n    return convert<T>::decode(node, static_cast<T&>(mp));\n  }\n};\n\ntemplate<>\nstruct convert<Eigen::Quaterniond> {\n  static Node encode(const Eigen::Quaterniond& mp){\n    return convert<Eigen::Vector4d>::encode(Eigen::Vector4d(mp.w(), mp.x(), mp.y(), mp.z()));\n  }\n  static bool decode(const Node& node, Eigen::Quaterniond& mp){\n    Eigen::Vector4d v4;\n    if(!convert<Eigen::Vector4d>::decode(node, v4)) return false;\n    mp.w() = v4[0];\n    mp.x() = v4[1];\n    mp.y() = v4[2];\n    mp.z() = v4[3];\n    return true;\n  }\n};\n\n} // namespace YAML\n\n\n", "meta": {"hexsha": "9bb8a0bfaf669887dbb23f2bbc89d1fff7f19d2f", "size": 5264, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/yaml_utils/yaml_eigen.hpp", "max_stars_repo_name": "machines-in-motion/yaml_utils", "max_stars_repo_head_hexsha": "53712e32aa5f530b420be9cf1ab648e7091b8822", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/yaml_utils/yaml_eigen.hpp", "max_issues_repo_name": "machines-in-motion/yaml_utils", "max_issues_repo_head_hexsha": "53712e32aa5f530b420be9cf1ab648e7091b8822", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2019-11-27T12:45:25.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-10T07:38:04.000Z", "max_forks_repo_path": "include/yaml_utils/yaml_eigen.hpp", "max_forks_repo_name": "machines-in-motion/yaml_utils", "max_forks_repo_head_hexsha": "53712e32aa5f530b420be9cf1ab648e7091b8822", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-11-24T00:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-24T00:31:16.000Z", "avg_line_length": 30.9647058824, "max_line_length": 110, "alphanum_fraction": 0.6436170213, "num_tokens": 1424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.4604021191865755}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n// Unit Test\r\n\r\n// Copyright (c) 2010 Barend Gehrels, Amsterdam, the Netherlands.\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#include <geometry_test_common.hpp>\r\n\r\n\r\n#include <boost/geometry/geometry.hpp>\r\n\r\n#include <boost/geometry/geometries/box.hpp>\r\n#include <boost/geometry/geometries/point.hpp>\r\n#include <boost/geometry/geometries/polygon.hpp>\r\n#include <boost/geometry/geometries/ring.hpp>\r\n\r\n#include <boost/geometry/geometries/adapted/boost_polygon/point.hpp>\r\n#include <boost/geometry/geometries/adapted/boost_polygon/box.hpp>\r\n#include <boost/geometry/geometries/adapted/boost_polygon/ring.hpp>\r\n#include <boost/geometry/geometries/adapted/boost_polygon/polygon.hpp>\r\n\r\n#include <boost/geometry/domains/gis/io/wkt/wkt.hpp>\r\n\r\n#include <iostream>\r\n\r\ntemplate <typename T>\r\nvoid fill_polygon_with_two_holes(boost::polygon::polygon_with_holes_data<T>& boost_polygon_polygon)\r\n{\r\n    std::vector<boost::polygon::point_data<T> > point_vector;\r\n    point_vector.push_back(boost::polygon::point_data<T>(0, 0));\r\n    point_vector.push_back(boost::polygon::point_data<T>(0, 10));\r\n    point_vector.push_back(boost::polygon::point_data<T>(10, 10));\r\n    point_vector.push_back(boost::polygon::point_data<T>(10, 0));\r\n    point_vector.push_back(boost::polygon::point_data<T>(0, 0));\r\n    boost_polygon_polygon.set(point_vector.begin(), point_vector.end());\r\n\r\n\r\n    std::vector<boost::polygon::polygon_data<T> > holes;\r\n    holes.resize(2);\r\n\r\n    {\r\n        std::vector<boost::polygon::point_data<T> > point_vector;\r\n        point_vector.push_back(boost::polygon::point_data<T>(1, 1));\r\n        point_vector.push_back(boost::polygon::point_data<T>(2, 1));\r\n        point_vector.push_back(boost::polygon::point_data<T>(2, 2));\r\n        point_vector.push_back(boost::polygon::point_data<T>(1, 2));\r\n        point_vector.push_back(boost::polygon::point_data<T>(1, 1));\r\n        holes[0].set(point_vector.begin(), point_vector.end());\r\n    }\r\n\r\n    {\r\n        std::vector<boost::polygon::point_data<T> > point_vector;\r\n        point_vector.push_back(boost::polygon::point_data<T>(3, 3));\r\n        point_vector.push_back(boost::polygon::point_data<T>(4, 3));\r\n        point_vector.push_back(boost::polygon::point_data<T>(4, 4));\r\n        point_vector.push_back(boost::polygon::point_data<T>(3, 4));\r\n        point_vector.push_back(boost::polygon::point_data<T>(3, 3));\r\n        holes[1].set(point_vector.begin(), point_vector.end());\r\n    }\r\n    boost_polygon_polygon.set_holes(holes.begin(), holes.end());\r\n}\r\n\r\n\r\ntemplate <typename T>\r\nvoid test_coordinate_type()\r\n{\r\n    // 1a: Check if Boost.Polygon's point fulfills Boost.Geometry's point concept\r\n    bg::concept::check<boost::polygon::point_data<T> >();\r\n\r\n    // 1b: use a Boost.Polygon point in Boost.Geometry, calc. distance with two point types\r\n    boost::polygon::point_data<T> boost_polygon_point(1, 2);\r\n\r\n    typedef bg::model::point<T, 2, bg::cs::cartesian> bg_point_type;\r\n    bg_point_type boost_geometry_point(3, 4);\r\n    BOOST_CHECK_EQUAL(bg::distance(boost_polygon_point, boost_geometry_point),\r\n                    2 * std::sqrt(2.0));\r\n\r\n    // 2a: Check if Boost.Polygon's box fulfills Boost.Geometry's box concept\r\n    bg::concept::check<boost::polygon::rectangle_data<T> >();\r\n\r\n    // 2b: use a Boost.Polygon rectangle in Boost.Geometry, compare with boxes\r\n    boost::polygon::rectangle_data<T> boost_polygon_box;\r\n    bg::model::box<bg_point_type> boost_geometry_box;\r\n\r\n    bg::assign_values(boost_polygon_box, 0, 1, 5, 6);\r\n    bg::assign_values(boost_geometry_box, 0, 1, 5, 6);\r\n    T boost_polygon_area = bg::area(boost_polygon_box);\r\n    T boost_geometry_area = bg::area(boost_geometry_box);\r\n    T boost_polygon_area_by_boost_polygon = boost::polygon::area(boost_polygon_box);\r\n    BOOST_CHECK_EQUAL(boost_polygon_area, boost_geometry_area);\r\n    BOOST_CHECK_EQUAL(boost_polygon_area, boost_polygon_area_by_boost_polygon);\r\n\r\n    // 3a: Check if Boost.Polygon's polygon fulfills Boost.Geometry's ring concept\r\n    bg::concept::check<boost::polygon::polygon_data<T> >();\r\n\r\n    // 3b: use a Boost.Polygon polygon (ring)\r\n    boost::polygon::polygon_data<T> boost_polygon_ring;\r\n    {\r\n        // Filling it is a two-step process using Boost.Polygon\r\n        std::vector<boost::polygon::point_data<T> > point_vector;\r\n        point_vector.push_back(boost::polygon::point_data<T>(0, 0));\r\n        point_vector.push_back(boost::polygon::point_data<T>(0, 3));\r\n        point_vector.push_back(boost::polygon::point_data<T>(4, 0));\r\n        point_vector.push_back(boost::polygon::point_data<T>(0, 0));\r\n        boost_polygon_ring.set(point_vector.begin(), point_vector.end());\r\n    }\r\n\r\n    // Boost-geometry ring\r\n    bg::model::ring<bg_point_type> boost_geometry_ring;\r\n    {\r\n        boost_geometry_ring.push_back(bg_point_type(0, 0));\r\n        boost_geometry_ring.push_back(bg_point_type(0, 3));\r\n        boost_geometry_ring.push_back(bg_point_type(4, 0));\r\n        boost_geometry_ring.push_back(bg_point_type(0, 0));\r\n    }\r\n    boost_polygon_area = bg::area(boost_polygon_ring);\r\n    boost_geometry_area = bg::area(boost_geometry_ring);\r\n    boost_polygon_area_by_boost_polygon = boost::polygon::area(boost_polygon_ring);\r\n    BOOST_CHECK_EQUAL(boost_polygon_area, boost_geometry_area);\r\n    BOOST_CHECK_EQUAL(boost_polygon_area, boost_polygon_area_by_boost_polygon);\r\n\r\n    // Check mutable ring\r\n    std::string wkt = \"POLYGON((0 0,0 10,10 10,10 0,0 0))\";\r\n    bg::read_wkt(wkt, boost_polygon_ring);\r\n    bg::read_wkt(wkt, boost_geometry_ring);\r\n    boost_polygon_area = bg::area(boost_polygon_ring);\r\n    boost_geometry_area = bg::area(boost_geometry_ring);\r\n    boost_polygon_area_by_boost_polygon = boost::polygon::area(boost_polygon_ring);\r\n    BOOST_CHECK_EQUAL(boost_polygon_area, boost_geometry_area);\r\n    BOOST_CHECK_EQUAL(boost_polygon_area, boost_polygon_area_by_boost_polygon);\r\n\r\n    // 4a: Boost.Polygon's polygon with holes\r\n    boost::polygon::polygon_with_holes_data<T> boost_polygon_polygon;\r\n    fill_polygon_with_two_holes(boost_polygon_polygon);\r\n\r\n    // Using Boost.Polygon\r\n    boost_polygon_area = bg::area(boost_polygon_polygon);\r\n    boost_polygon_area_by_boost_polygon = boost::polygon::area(boost_polygon_polygon);\r\n    BOOST_CHECK_EQUAL(boost_polygon_area, boost_polygon_area_by_boost_polygon);\r\n\r\n    wkt = \"POLYGON((0 0,0 10,10 10,10 0,0 0),(1 1,2 1,2 2,1 2,1 1),(3 3,4 3,4 4,3 4,3 3))\";\r\n\r\n    bg::model::polygon<bg_point_type> boost_geometry_polygon;\r\n    bg::read_wkt(wkt, boost_geometry_polygon);\r\n\r\n    boost_geometry_area = bg::area(boost_geometry_polygon);\r\n    BOOST_CHECK_EQUAL(boost_polygon_area, boost_geometry_area);\r\n\r\n    bg::clear(boost_polygon_polygon);\r\n    bg::read_wkt(wkt, boost_polygon_polygon);\r\n    boost_geometry_area = bg::area(boost_polygon_polygon);\r\n    BOOST_CHECK_EQUAL(boost_polygon_area, boost_geometry_area);\r\n\r\n    std::ostringstream out;\r\n    out << bg::wkt(boost_polygon_polygon);\r\n    BOOST_CHECK_EQUAL(wkt, out.str());\r\n\r\n}\r\n\r\nint test_main(int, char* [])\r\n{\r\n    test_coordinate_type<int>();\r\n    //test_coordinate_type<float>(); // compiles, but \"BOOST_CHECK_EQUAL\" fails\r\n    test_coordinate_type<double>();\r\n    return 0;\r\n}", "meta": {"hexsha": "58cf31172ca3ccaa7ef82a2533f1e6fc82c6805e", "size": 7389, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/test/geometries/boost_polygon.cpp", "max_stars_repo_name": "Ron2014/boost_1_48_0", "max_stars_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "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/geometry/test/geometries/boost_polygon.cpp", "max_issues_repo_name": "Ron2014/boost_1_48_0", "max_issues_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "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/geometry/test/geometries/boost_polygon.cpp", "max_forks_repo_name": "Ron2014/boost_1_48_0", "max_forks_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "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.7218934911, "max_line_length": 100, "alphanum_fraction": 0.7101096224, "num_tokens": 1825, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585669110203, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.46040211180625673}}
{"text": "/// @file metropolis_hastings.hpp A generic templated Metropolis-Hastings sampler implementation\n\n#ifndef BIGGLES_SAMPLING_METROPOLIS_HASTINGS_HPP\n#define BIGGLES_SAMPLING_METROPOLIS_HASTINGS_HPP\n\n#include <cmath>\n#include <boost/tuple/tuple.hpp>\n\n#include \"../partition_sampler_items.hpp\"\n#include \"../detail/random.hpp\"\n#include \"../detail/fun.hpp\"\n#include \"../mh_moves/mh_moves.hpp\"\n\nnamespace biggles { namespace sampling {\n\n/// \\brief attributes of the current sampling state\nstruct mh_state_observer {\n    /// @brief The log probability density of the current sample.\n    ///\n    /// this is either last_sample_log_density (if proposal was rejected)\n    /// or last_proposal_log_density (if proposal was accepted)\n    float sample_log_density;\n\n    /// @brief last log(alpha) where alpha is uniformly distributed between 0 and 1\n    float last_log_alpha;\n\n    /// @brief log density of the last proposed move\n    float last_proposal_log_density;\n\n    /// \\brief the density of the last sample p(T|theta, y)\n    float last_sample_log_density;\n\n    /// @brief the last proposal density ratio Q(T|T*)/Q(T*|T)\n    float last_pdr;\n\n    /// @brief The number of samples which have been accepted during the lifetime of this sampler. This will always be\n    /// less than or equal to \\c n_proposed_.\n    size_t n_accepted;\n\n    /// @brief The number of samples which have been proposed during the lifetime of this sampler.\n    size_t n_proposed;\n\n    /// @brief was the last proposal accepted?\n    bool accepted;\n\n    mh_state_observer() :\n        sample_log_density(-std::numeric_limits<float>::max()),\n        last_log_alpha(-std::numeric_limits<float>::max()),\n        last_proposal_log_density(-std::numeric_limits<float>::max()),\n        last_sample_log_density(-std::numeric_limits<float>::max()),\n        last_pdr(-std::numeric_limits<float>::max()),\n        n_accepted(1),\n        n_proposed(1),\n        accepted(false) {}\n\n    mh_state_observer(const mh_state_observer& o) :\n        sample_log_density(o.sample_log_density),\n        last_log_alpha(o.last_log_alpha),\n        last_proposal_log_density(o.last_proposal_log_density),\n        last_sample_log_density(o.last_sample_log_density),\n        last_pdr(o.last_pdr),\n        n_accepted(o.n_accepted),\n        n_proposed(o.n_proposed),\n        accepted(o.accepted) {}\n\n    const mh_state_observer& operator = (const mh_state_observer& o) {\n        if (&o == this) return *this;\n        sample_log_density = o.sample_log_density;\n        last_log_alpha = o.last_log_alpha;\n        last_proposal_log_density = o.last_proposal_log_density;\n        last_sample_log_density = o.last_sample_log_density;\n        last_pdr = o.last_pdr;\n        n_accepted = o.n_accepted;\n        n_proposed = o.n_proposed;\n        accepted = o.accepted;\n        return *this;\n    }\n\n    /// \\brief the total accptance rate\n    float acceptance_rate() const { return static_cast<float>(n_accepted) / static_cast<float>(n_proposed); }\n\n};\n\n/// @brief A Metropolis-Hastings sampler.\n///\n/// Metropolis-Hastings is an algorithm which can sample from an arbitrary probability density function, \\f$ P(x) \\f$,\n/// given only that the PDF can be evaluated. In fact it is even more general: the function may return some constant\n/// multiple of the true PDF meaning that M-H is exceptionally useful when the PDF is known up to some normalisation\n/// factor. The PDF \\f$ P(x) \\f$ is termed the <em>target</em> distribution.\n///\n/// In addition to being able to evaluate the target distribution, one must be able to draw samples from a proposal\n/// distribution, \\f$ Q(x' | x) \\f$. In this case \\f$ x' \\f$ is a new sample and \\f$ x \\f$ is the sample we currently\n/// are at.\n///\n/// To use the sampler you must provide at a minimum a functor which can evaluate the logarithm of the target PDF at a\n/// given sample and a proposal functor. The proposal functor takes a current sample, \\f$ x \\f$, and returns a new\n/// sample, \\f$ x' \\f$, conditioned on it. In addition, it returns\n///\n/// \\f[\n/// \\log\\left(\\frac{Q(x|x')}{Q(x'|x)}\\right) = \\log(Q(x|x')) - \\log(Q(x'|x)).\n/// \\f]\n///\n/// This logarithm may of course be zero to indicate a symmetric proposal distribution.\n///\n/// In addition you may optionally provide the C++ type of the sample and a functor which can sample uniformly from the\n/// interval [0,1]. The boost library is used to provide a Mersenne twister-based uniform sampler if you do not specify\n/// an alternative.\n///\n/// As an example of use, consider sampling the Rosenbrock function:\n///\n/// @code\n/// typedef boost::tuples::tuple<float, float> point;\n///\n/// inline float rosenbrock(const point& p)\n/// {\n///     float x, y;\n///     boost::tuples::tie(x,y) = p;\n///     return (1.f-x)*(1.f-x) + 100.f*(y-x*x)*(y-x*x);\n/// }\n/// @endcode\n///\n/// Firstly, we need to convert this function which has a minimum at (1,1) to a log-PDF with a maximum at (1,1). Since\n/// we do not need to worry about normalisation, this is quite easy:\n///\n/// @code\n/// // a cooked-up PDF which has a maximum where the Rosenbrock function has a minimum.\n/// inline float rosenbrock_log_pdf(const point& p)\n/// {\n///     return -rosenbrock(p);\n/// }\n/// @endcode\n///\n/// We also need a proposal function. The proposal function should accept a sample, in this case a \\c point, and return\n/// a tuple containing a new sample and the log proposal density ration outlined above. We shall use a simple Guassian\n/// proposal function which moves the sample according to a Gaussian distribution centred on the current sample with a\n/// standard deviation of 0.2. Since this proposal distribution is symmetric, we can return 0 as the log proposal ratio:\n///\n/// @code\n/// typedef boost::tuples::tuple<point, float> proposal_result_t;\n///\n/// inline proposal_result_t propose_gaussian(const point& p)\n/// {\n///     static boost::mt19937 rng;\n///     static boost::normal_distribution<float> norm(0.f, 0.2f);\n///     static boost::variate_generator<boost::mt19937&, boost::normal_distribution<float> > variate(rng, norm);\n///\n///     point new_p(p.get<0>() + variate(), p.get<1>() + variate());\n///\n///     return proposal_result_t(new_p, 0.f);\n/// }\n/// @endcode\n///\n/// Since these functions are plain C++ functions, we shall wrap them in the functor classes available in the standard\n/// library's \\c functor header. We firstly need to define a type for them:\n///\n/// @code\n/// typedef std::pointer_to_unary_function<const point&, float> pdf_t;\n/// typedef std::pointer_to_unary_function<const point&, proposal_result_t> proposal_func_t;\n/// @endcode\n///\n/// Using the standard library \\c std::ptr_fun function, we can now declare our sampler.\n///\n/// @code\n/// // MH sampler for Rosenbrock function. An example of using a function pointer directly.\n/// sampler<pdf_t, proposal_func_t> s(std::ptr_fun(rosenbrock_log_pdf),\n///                                   std::ptr_fun(propose_gaussian));\n/// @endcode\n///\n/// In this case, the sample type has been inferred directly from the types of the proposal and target functions. You\n/// may also specify it directly if necessary.\n///\n/// Calling draw() on \\c s will now draw point locations from the Rosenbrock PDF we defined earlier. In real-world use,\n/// you should keep an eye on the value returned from acceptance_rate() to check it is around 0.25.\n///\n/// @sa http://en.wikipedia.org/wiki/Metropolis%E2%80%93Hastings_algorithm\n///\nclass metropolis_hastings_sampler {\npublic:\n    /// @brief Initialise the sampler.\n    ///\n    /// @param target A functor representing the target distribution. This is copied internally.\n    /// @param propose A functor for proposing new samples. This is copied internally.\n    /// @param initial_sample An initial starting sample.\n    /// @param uniform A functor for generating uniform reals on the interval [0,1].\n    metropolis_hastings_sampler(const partition_distribution& target, const partition_proposal& propose,\n            const partition_sampler_sample& initial_sample )\n        : target_(target)\n        , propose_(propose)\n        , sample_(initial_sample)\n        , last_proposal_(partition_proposal::result_type(initial_sample, -std::numeric_limits<float>::max()))\n        , temperature_(1.0f)\n        , acceptance_seq_(5000)\n        , internal_records_ptr_(new capability_recorder(initial_sample.partition_sample_ptr->first_time_stamp(),\n                            initial_sample.partition_sample_ptr->last_time_stamp(),\n                            initial_sample.partition_sample_ptr->tracks()))\n    {\n        //state_.sample_log_density = target(initial_sample);\n    }\n\n    /// @brief Draw the next sample from the sampler.\n    ///\n    /// @return A reference to the new sample. This can be retrieved before the next call to draw() via last_sample().\n    const partition_sampler_sample& draw();\n\n    /// @brief Obtain a reference to the last sample drawn from the sampler.\n    const partition_sampler_sample& last_sample() const { return sample_; }\n\n    /// @brief Obtain the log probability density of the last sample drawn from the sampler. log(P(x| theta, D)\n    float current_sample_log_density() const { return state_.sample_log_density; }\n\n    /// @brief Obtain the current acceptance rate of the sampler.\n    ///\n    /// The acceptance rate is defined as the ratio of accepted proposals to total number of proposals. The usual rule\n    /// of thumb for Metropolis-Hastings is that this value, often termed \\f$ \\alpha \\f$, should be around 0.25.\n    float acceptance_rate() const { return state_.acceptance_rate(); }\n\n    /// @brief Obtain the recent acceptance rate of the sampler.\n    ///\n    /// This acceptance rate only takes the last samples into account instead of the whole sampling history\n    float recent_acceptance_rate() const {\n        return std::accumulate(acceptance_seq_.begin(), acceptance_seq_.end(), 0.f)/float(acceptance_seq_.size());\n    }\n\n    /// @brief The last proposed sample\n    partition_sampler_sample proposed_sample() const { return last_proposal_.partition_sample; }\n\n    /*\n    /// @brief The last proposed move\n    mh_moves::move_type proposed_move() const { return proposed_sample().executed_move; }\n    */\n\n    /// @brief last log alpha\n    float last_log_alpha() const { return state_.last_log_alpha; }\n\n    /// @brief log density of the last proposed partition log(P(x'|theta, D))\n    float last_log_density() const { return state_.last_proposal_log_density; }\n\n    /// @brief last proposal density ratio Q(T|T*)/Q(T*|T)\n    float last_pdr() const {return state_.last_pdr; }\n\n    bool last_proposal_accepted() const { return state_.accepted; }\n\n    mh_state_observer current_state() const { return state_; }\n    internal_containers_observer current_internals() const { return intern_; }\n\n    void set_temperature(float temperature) {\n        if (temperature > 1.f or temperature <= 0.f) {\n            throw std::runtime_error(\"temperature must be in (0, 1].\");\n        }\n        temperature_ = temperature;\n    }\n\nprotected:\n    /// @brief The target distribution functor.\n    partition_distribution target_;\n\n    /// @brief The proposal function and PDF. See class documentation.\n    partition_proposal propose_;\n\n    /// @brief The current sample.\n    partition_sampler_sample sample_;\n\n    /// @brief The last (possibly not accepted) proposal\n    partition_proposal::result_type last_proposal_;\n\n    mh_state_observer state_;\n    internal_containers_observer intern_;\n\n    float temperature_;\n\n    fqueue<int> acceptance_seq_;\n\n    capability_recorder_ptr internal_records_ptr_;\n\n};\n\n\n} }\n\n#endif // BIGGLES_SAMPLING_METROPOLIS_HASTINGS_HPP\n", "meta": {"hexsha": "18d6939c47774cb8ece8989412ee2054dff3f98a", "size": 11612, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/biggles/sampling/metropolis_hastings.hpp", "max_stars_repo_name": "fbi-octopus/biggles", "max_stars_repo_head_hexsha": "2dac4f1748ab87242951239caf274f302be1143a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-15T14:01:59.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-15T14:01:59.000Z", "max_issues_repo_path": "include/biggles/sampling/metropolis_hastings.hpp", "max_issues_repo_name": "fbi-octopus/biggles", "max_issues_repo_head_hexsha": "2dac4f1748ab87242951239caf274f302be1143a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/biggles/sampling/metropolis_hastings.hpp", "max_forks_repo_name": "fbi-octopus/biggles", "max_forks_repo_head_hexsha": "2dac4f1748ab87242951239caf274f302be1143a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.3238434164, "max_line_length": 120, "alphanum_fraction": 0.6986737857, "num_tokens": 2687, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585669110202, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.4604021118062567}}
{"text": "//=======================================================================\n// Copyright 2001 Jeremy G. Siek, Andrew Lumsdaine, Lie-Quan Lee,\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n#include <vector>\n#include <string>\n#include <iostream>\n#include <boost/graph/stanford_graph.hpp>\n#include <boost/graph/topological_sort.hpp>\n\nint main()\n{\n    using namespace boost;\n    const int n_vertices = 7;\n    Graph* sgb_g = gb_new_graph(n_vertices);\n\n    const char* tasks[]\n        = { \"pick up kids from school\", \"buy groceries (and snacks)\",\n              \"get cash at ATM\", \"drop off kids at soccer practice\",\n              \"cook dinner\", \"pick up kids from soccer\", \"eat dinner\" };\n    const int n_tasks = sizeof(tasks) / sizeof(char*);\n\n    gb_new_arc(sgb_g->vertices + 0, sgb_g->vertices + 3, 0);\n    gb_new_arc(sgb_g->vertices + 1, sgb_g->vertices + 3, 0);\n    gb_new_arc(sgb_g->vertices + 1, sgb_g->vertices + 4, 0);\n    gb_new_arc(sgb_g->vertices + 2, sgb_g->vertices + 1, 0);\n    gb_new_arc(sgb_g->vertices + 3, sgb_g->vertices + 5, 0);\n    gb_new_arc(sgb_g->vertices + 4, sgb_g->vertices + 6, 0);\n    gb_new_arc(sgb_g->vertices + 5, sgb_g->vertices + 6, 0);\n\n    typedef graph_traits< Graph* >::vertex_descriptor vertex_t;\n    std::vector< vertex_t > topo_order;\n    topological_sort(sgb_g, std::back_inserter(topo_order),\n        vertex_index_map(get(vertex_index, sgb_g)));\n    int n = 1;\n    for (std::vector< vertex_t >::reverse_iterator i = topo_order.rbegin();\n         i != topo_order.rend(); ++i, ++n)\n        std::cout << n << \": \" << tasks[get(vertex_index, sgb_g)[*i]]\n                  << std::endl;\n\n    gb_recycle(sgb_g);\n    return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "7453c3d3bbc0c7f31dfb90af22c27dfa0c3171c1", "size": 1856, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/graph/example/topo-sort-with-sgb.cpp", "max_stars_repo_name": "uosorio/heroku_face", "max_stars_repo_head_hexsha": "7d6465e71dba17a15d8edaef520adb2fcd09d91e", "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": "3rdparty/boost_1_73_0/libs/graph/example/topo-sort-with-sgb.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 130.0, "max_issues_repo_issues_event_min_datetime": "2016-06-22T22:11:25.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-29T20:24:09.000Z", "max_forks_repo_path": "3rdparty/boost_1_73_0/libs/graph/example/topo-sort-with-sgb.cpp", "max_forks_repo_name": "qingkouwei/mediaones", "max_forks_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2015-07-08T19:18:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-14T16:39:56.000Z", "avg_line_length": 39.4893617021, "max_line_length": 75, "alphanum_fraction": 0.5953663793, "num_tokens": 511, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.6992544335934766, "lm_q1q2_score": 0.4604013564232922}}
{"text": "/*\n * Imu.hpp\n *\n *  Created on: Apr 30, 2021\n *      Author: jelavice\n */\n\n#pragma once\n#include <Eigen/Dense>\n#include \"icp_localization/common/time.hpp\"\n\n#include <sensor_msgs/Imu.h>\n\nnamespace icp_loco {\n\ntemplate<typename FloatType>\nclass ImuReading\n{\n public:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n  using Vector = Eigen::Matrix<FloatType, 3, 1>;\n  using Quaternion = Eigen::Quaternion<FloatType>;\n  ImuReading()\n      : ImuReading(Vector::Zero(), Vector::Zero(), Quaternion::Identity())\n  {\n  }\n  ImuReading(const Vector& lin, const Vector& ang)\n      : ImuReading(lin, ang, Quaternion::Identity())\n  {\n  }\n\n  ImuReading(const Vector& lin, const Vector& ang, const Quaternion &q)\n      : acc_(lin),\n        angVel_(ang),\n        q_(q)\n  {\n  }\n\n  template<typename OtherType>\n  ImuReading<OtherType> cast() const\n  {\n    return ImuReading<OtherType>(acc_.template cast<OtherType>(),\n                                 angVel_.template cast<OtherType>(), q_.template cast<OtherType>());\n  }\n\n  const Vector& acceleration() const\n  {\n    return acc_;\n  }\n  const Vector& angularVelocity() const\n  {\n    return angVel_;\n  }\n  const Quaternion& rotation() const\n  {\n    return q_;\n  }\n\n  Vector& acceleration()\n  {\n    return acc_;\n  }\n  Vector& angularVelocity()\n  {\n    return angVel_;\n  }\n  Quaternion& rotation()\n  {\n    return q_;\n  }\n\n  std::string asString() const{\n    const double kRadToDeg = 180.0 / M_PI;\n\n    const std::string acc  =  string_format(\"acc:[%f, %f, %f]\", acc_.x(), acc_.y(), acc_.z());\n    const std::string angVel  =  string_format(\"angVel:[%f, %f, %f]\", angVel_.x(), angVel_.y(), angVel_.z());\n    const std::string rot = string_format(\"q:[%f, %f, %f, %f]\",q_.x(), q_.y(), q_.z(), q_.w());\n    const auto rpy = toRPY(q_) * kRadToDeg;\n    const std::string rpyString = string_format(\"rpy (deg):[%f, %f, %f]\",rpy.x(), rpy.y(),rpy.z());\n    return acc + \" ; \" +angVel + \" ; \" + rot + \" ; \" + rpyString;\n  }\n\n private:\n  Vector acc_;\n  Vector angVel_;\n  Quaternion q_;\n};\n\nusing ImuReadingd = ImuReading<double>;\nusing ImuReadingf = ImuReading<float>;\n\nstruct TimestampedImuReading\n{\n  Time time_;\n  ImuReadingd imu_;\n};\n\nTimestampedImuReading interpolate(const TimestampedImuReading& start, const TimestampedImuReading& end,\n                             const Time &time);\n\nTimestampedImuReading fromRos(const sensor_msgs::Imu &msg);\n\n} // namespace icp_loco\n", "meta": {"hexsha": "e0644d0c1a83b9f34b8318e870915052f851cd4f", "size": 2380, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/icp_localization/transform/ImuReading.hpp", "max_stars_repo_name": "ibrahimhroob/icp_localization", "max_stars_repo_head_hexsha": "271d99c59141fcd293190ec935020213783745e5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 72.0, "max_stars_repo_stars_event_min_datetime": "2021-07-06T09:05:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T08:21:07.000Z", "max_issues_repo_path": "include/icp_localization/transform/ImuReading.hpp", "max_issues_repo_name": "ibrahimhroob/icp_localization", "max_issues_repo_head_hexsha": "271d99c59141fcd293190ec935020213783745e5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-06-09T20:06:41.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T09:54:42.000Z", "max_forks_repo_path": "include/icp_localization/transform/ImuReading.hpp", "max_forks_repo_name": "ibrahimhroob/icp_localization", "max_forks_repo_head_hexsha": "271d99c59141fcd293190ec935020213783745e5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2021-06-23T09:18:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T03:14:10.000Z", "avg_line_length": 22.8846153846, "max_line_length": 109, "alphanum_fraction": 0.6331932773, "num_tokens": 692, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544335934766, "lm_q2_score": 0.6584174871563662, "lm_q1q2_score": 0.460401347049565}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n// QuickBook Example\r\n\r\n// Copyright (c) 2011-2012 Barend Gehrels, Amsterdam, the Netherlands.\r\n// Copyright (c) 2014 Adam Wulkiewicz, Lodz, Poland.\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n//[boost_polygon_ring\r\n//`Shows how to use Boost.Polygon polygon_data within Boost.Geometry\r\n\r\n#include <iostream>\r\n#include <boost/geometry.hpp>\r\n#include <boost/geometry/geometries/adapted/boost_polygon.hpp>\r\n\r\nint main()\r\n{\r\n    typedef boost::polygon::polygon_data<int> polygon;\r\n    typedef boost::polygon::polygon_traits<polygon>::point_type point;\r\n\r\n    point pts[5] = {\r\n        boost::polygon::construct<point>(0, 0),\r\n        boost::polygon::construct<point>(0, 10),\r\n        boost::polygon::construct<point>(10, 10),\r\n        boost::polygon::construct<point>(10, 0),\r\n        boost::polygon::construct<point>(0, 0)\r\n    };\r\n\r\n    polygon poly;\r\n    boost::polygon::set_points(poly, pts, pts+5);\r\n    \r\n    std::cout << \"Area (using Boost.Geometry): \"\r\n        << boost::geometry::area(poly) << std::endl;\r\n    std::cout << \"Area (using Boost.Polygon): \"\r\n        << boost::polygon::area(poly) << std::endl;\r\n\r\n    return 0;\r\n}\r\n\r\n//]\r\n\r\n//[boost_polygon_ring_output\r\n/*`\r\nOutput:\r\n[pre\r\nArea (using Boost.Geometry): 100\r\nArea (using Boost.Polygon): 100\r\n]\r\n*/\r\n//]\r\n", "meta": {"hexsha": "054b7911c9c7ff69252f518bb7b8b47cc2bd87b7", "size": 1477, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/geometry/doc/src/examples/geometries/adapted/boost_polygon_ring.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": 85.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T20:36:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T20:38:31.000Z", "max_issues_repo_path": "libs/boost/libs/geometry/doc/src/examples/geometries/adapted/boost_polygon_ring.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/src/examples/geometries/adapted/boost_polygon_ring.cpp", "max_forks_repo_name": "flingone/frameworks_base_cmds_remoted", "max_forks_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2015-01-28T16:33:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-12T05:04:39.000Z", "avg_line_length": 27.8679245283, "max_line_length": 80, "alphanum_fraction": 0.6492890995, "num_tokens": 382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.6992544085240401, "lm_q1q2_score": 0.4604013399171365}}
{"text": "// vi: set et ts=4 sw=2 sts=2:\n\n#ifndef HMAT_HMATRIX_LOW_RANK_DATA_HPP\n#define HMAT_HMATRIX_LOW_RANK_DATA_HPP\n\n#include \"common.hpp\"\n#include \"hmatrix_data.hpp\"\n#include <armadillo>\n\nnamespace hmat {\n\ntemplate <typename ValueType>\nclass HMatrixLowRankData : public HMatrixData<ValueType> {\n\npublic:\n  void apply(const arma::Mat<ValueType> &X, arma::Mat<ValueType> &Y,\n             TransposeMode trans, ValueType alpha, ValueType beta) const\n      override;\n\n  void apply(const arma::subview<ValueType> &X, arma::subview<ValueType> &Y,\n             TransposeMode trans, ValueType alpha, ValueType beta) const\n      override;\n\n  const arma::Mat<ValueType> &A() const;\n  arma::Mat<ValueType> &A();\n\n  const arma::Mat<ValueType> &B() const;\n  arma::Mat<ValueType> &B();\n\n  int rows() const override;\n  int cols() const override;\n  int rank() const override;\n\n  typename ScalarTraits<ValueType>::RealType frobeniusNorm() const override;\n\n  double memSizeKb() const override;\n\nprivate:\n  arma::Mat<ValueType> m_A;\n  arma::Mat<ValueType> m_B;\n};\n}\n\n#include \"hmatrix_low_rank_data_impl.hpp\"\n\n#endif\n", "meta": {"hexsha": "1430c07ee9bcf07821674aad1233525c7a9ff737", "size": 1092, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/hmat/hmatrix_low_rank_data.hpp", "max_stars_repo_name": "mdavezac/bempp", "max_stars_repo_head_hexsha": "bc573062405bda107d1514e40b6153a8350d5ab5", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib/hmat/hmatrix_low_rank_data.hpp", "max_issues_repo_name": "mdavezac/bempp", "max_issues_repo_head_hexsha": "bc573062405bda107d1514e40b6153a8350d5ab5", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/hmat/hmatrix_low_rank_data.hpp", "max_forks_repo_name": "mdavezac/bempp", "max_forks_repo_head_hexsha": "bc573062405bda107d1514e40b6153a8350d5ab5", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.2340425532, "max_line_length": 76, "alphanum_fraction": 0.7152014652, "num_tokens": 289, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708562, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.4603573428285369}}
{"text": "/* -*-C++-*-\n   (c) Copyright 2005-2008, Hewlett-Packard Development Company, LP\n\n   See the file named COPYING for license details\n*/\n\n/** @file\n    StatsQuantile implementation\n*/\n\n#include <algorithm>\n#include <sstream>\n#include <cstring>\n\n#include <boost/format.hpp>\n\n#include <Lintel/AssertBoost.hpp>\n#include <Lintel/Double.hpp>\n#include <Lintel/HashMap.hpp>\n#include <Lintel/LintelLog.hpp>\n#include <Lintel/StatsQuantile.hpp>\n\nusing namespace std;\nusing boost::format;\n\nnamespace {\n    struct ErrorNbound {\n\tdouble quantile_error;\n\tint64_t nbound;\n\tErrorNbound() : quantile_error(0), nbound(0) { }\n\tErrorNbound(double a, int64_t b) : quantile_error(a), nbound(b) { }\n\t\n\tuint32_t hash() const {\n\t    uint32_t a = static_cast<uint32_t>(quantile_error * 1e9);\n\t    uint32_t b = nbound >> 32;\n\t    uint32_t c = nbound & 0xFFFFFFFFU;\n\t    return lintel::BobJenkinsHashMix3(a, b, c);\n\t}\n\n\tbool operator == (const ErrorNbound &rhs) const {\n\t    return quantile_error == rhs.quantile_error && nbound == rhs.nbound;\n\t}\n    };\n\n    struct BK {\n\tuint32_t b, k;\n\tBK() : b(0), k(0) { }\n\tBK(uint32_t in_b, uint32_t in_k) : b(in_b), k(in_k) { }\n    };\n\n    HashMap<ErrorNbound, BK> bk_cache;\n\n    double fact(double a) {\n\tdouble ret = 1.0;\n\tfor(double i = 2;i<=a;i++) {\n\t    ret *= i;\n\t}\n\treturn ret;\n    }\n\n    double choose(int b, int a) { // b choose a \n\tdouble ret = fact(b) / (fact(b-a) * fact(a));\n\treturn ret;\n    }\n\n    class doubleOrder {\n    public:\n\tinline bool operator() (double a, double b) const {\n\t    return a < b;\n\t}\n    };\n    \n}\n\nStatsQuantile::StatsQuantile(double _quantile_error, int64_t in_nbound, int _print_nrange, bool lazy)\n    : quantile_error(_quantile_error), Nbound(in_nbound < 100 ? 100 : in_nbound), \n      print_nrange(_print_nrange), lazy(lazy)\n{\n    // sanity check that we haven't been called in a weird/wrong way.\n    INVARIANT(quantile_error < 0.2, format(\"whoa, quantile_error %.3g >= 0.2??\") % quantile_error);\n    double tmp_nbound = Nbound; // easy for calculations\n    INVARIANT(in_nbound > 1, format(\"Usage error? StatsQuantile nbound set to %d?\") % in_nbound);\n\t      \n    int32_t best_b = -1, best_k = -1;\n\n    // If we are making lots of smallish StatsQuantiles, we can spend\n    // too much of our time doing this, so cache the sizes.\n    BK *cache = bk_cache.lookup(ErrorNbound(quantile_error, Nbound));\n\n    if (cache != NULL) {\n\tbest_b = cache->b;\n\tbest_k = cache->k;\n    } else {\n\t// The hunt for b = nbuffers, and k = buffer_size is on, following \n\t// section 4.5 in the paper\n\n\tconst int32_t max_b = 30;\n\tconst int32_t max_h = 40;\n\tfor(int32_t b=2;b<max_b;b++) {\n\t    int32_t h = 3;\n\t    for(;h < max_h;h++) {\n\t\tdouble v = (h-2) * choose(b+h-2,h-1) - choose(b+h-3,h-3) + choose(b+h-3,h-2);\n\t\tif (v > 2 * quantile_error * tmp_nbound) {\n\t\t    --h; // this one is too high\n\t\t    break;\n\t\t}\n\t    }\n\t    double k = ceil(tmp_nbound / choose(b+h-2,h-1));\n\t    if (b * k < 1.0e9) {\n\t\tif (best_b == -1 || b * k < best_b * best_k) {\n\t\t    best_b = b;\n\t\t    best_k = (int)k;\n\t\t} \n\t    }\n\t}\n\tif (bk_cache.size() > 1000) { // keep the cache small\n\t    bk_cache.clear();\n\t}\n\tbk_cache[ErrorNbound(quantile_error, Nbound)] = BK(best_b, best_k);\n    }    \n    INVARIANT(best_b > 0 && best_k > 0,\n\t      format(\"unable to find b/k for %.8g %.8g\") % quantile_error % tmp_nbound);\n\n    // lower bound sanity value\n    if (best_k < 10) best_k = 10;\n    // First requirement makes the logic setting the buffer_level faster\n    // second one just seems sane.\n    init(best_b, best_k);\n}\n\n// fake Nbound, big enough for tests\nStatsQuantile::StatsQuantile(const string &,\n\t\t\t     int _nbuffers, int _buffer_size, int _print_nrange)\n    : quantile_error(Double::NaN), Nbound(5000000), print_nrange(_print_nrange), lazy(true)\n{\n    init(_nbuffers, _buffer_size);\n}\n\nvoid StatsQuantile::init(int _nbuffers, int _buffer_size) {\n    nbuffers = _nbuffers;\n    buffer_size = _buffer_size;\n    INVARIANT(nbuffers > 1,\n\t      \"need at least two buffers for code to work correctly\");\n    INVARIANT(buffer_size >= 10,\n\t      \"buffers smaller than 10 don't make sense.\");\n    all_buffers = new one_buffer[nbuffers];\n    for(int i = 0; i < nbuffers; ++i) {\n\tall_buffers[i] = NULL;\n    }\n    buffer_weight = new int64_t[nbuffers];\n    buffer_level = new int[nbuffers];\n    buffer_sorted = new bool[nbuffers];\n    if (!lazy) {\n\ttmp_buffer = new double[buffer_size];\n    } else {\n\ttmp_buffer = NULL;\n    }\n    collapse_pos = new int[buffer_size];\n    init_buffers();\n}\n\nvoid StatsQuantile::init_buffers() {\n    for(int i=0;i<nbuffers;i++) {\n\tif (all_buffers[i] == NULL && ! lazy) {\n\t    all_buffers[i] = new double[buffer_size];\n\t}\n\t// touch all the space to make sure it is allocated; necessary\n\t// to avoid demand allocation (which can create long delays\n\t// when used in Buttress2)\n\tif (all_buffers[i] != NULL) {\n\t    for(int j=0;j<buffer_size;j+=32) {\n\t\tall_buffers[i][j] = 0.0;\n\t    }\n\t}\n\tbuffer_weight[i] = -1;\n\tbuffer_level[i] = -1;\n\tbuffer_sorted[i] = false;\n    }\n\n    cur_buffer = 0;\n    cur_buffer_pos = 0;\n    buffer_weight[cur_buffer] = 1;\n    buffer_level[cur_buffer] = 0;\n    collapse_even_low = true;\n    if (lazy) {\n\tcur_buffer = -1;\n\tcur_buffer_pos = buffer_size+1;\n    }\n}\n\nStatsQuantile::~StatsQuantile() {\n    for(int i=0;i<nbuffers;i++) {\n\tdelete[] all_buffers[i];\n    }\n    delete[] all_buffers;\n    delete[] buffer_weight;\n    delete[] buffer_level;\n    delete[] buffer_sorted;\n    delete[] tmp_buffer;\n    delete[] collapse_pos;\n}\n\nvoid StatsQuantile::reset() {\n    Stats::reset();\n    init_buffers();\n}\n\nvoid StatsQuantile::addQuantile(const double value) {\n    if (cur_buffer_pos >= buffer_size) {\n\tcur_buffer += 1;\n\tcur_buffer_pos = 0;\n\tif (cur_buffer == nbuffers) {\n\t    collapse();\n\t} else if (cur_buffer>0) {\n#if 1\n\t    // do the sort here to amortize the work\n\t    sort(all_buffers[cur_buffer - 1],\n\t\t      all_buffers[cur_buffer - 1]+buffer_size,\n\t\t      doubleOrder());\n\t    buffer_sorted[cur_buffer-1] = true;\n#endif\n\t}\n        SINVARIANT(cur_buffer < nbuffers);\n\tif (lazy && all_buffers[cur_buffer] == NULL) {\n\t    all_buffers[cur_buffer] = new double[buffer_size];\n\t}\n\tbuffer_weight[cur_buffer] = 1;\n\tbuffer_level[cur_buffer] = 0;\n\tif (cur_buffer == nbuffers - 1) {\n\t    buffer_level[cur_buffer] = buffer_level[cur_buffer - 1];\n\t}\n    }\n    buffer_sorted[cur_buffer] = false;\n    all_buffers[cur_buffer][cur_buffer_pos] = value;\n    cur_buffer_pos += 1;\n}\n\nvoid StatsQuantile::add(const double value) {\n    Stats::add(value);\n    addQuantile(value);\n}\n\nvoid StatsQuantile::add(const Stats &_stat) {\n    const StatsQuantile *stat = dynamic_cast<const StatsQuantile *>(&_stat);\n    INVARIANT(stat != NULL, \"need another StatsQuantile for add(Stats) to work\");\n\n    Stats::add(_stat); \n\n    if ((cur_buffer == -1 || \n\t (cur_buffer == 0 && cur_buffer_pos == 0)) && // we are empty\n\tbuffer_size == stat->buffer_size && // we are compatible\n\tnbuffers == stat->nbuffers) {\n\tINVARIANT(countll() == _stat.countll(), \"??\");\n\tINVARIANT(stat->cur_buffer < nbuffers, \"??\");\n\tfor(int i=0; i <= stat->cur_buffer; ++i) {\n\t    // Will copy some useless stuff in last buffer.\n\t    if (all_buffers[i] == NULL) {\n\t\tall_buffers[i] = new double[buffer_size];\n\t    }\n\t    memcpy(all_buffers[i], stat->all_buffers[i],\n\t\t   sizeof(double) * buffer_size);\n\t    buffer_weight[i] = stat->buffer_weight[i];\n\t    buffer_level[i] = stat->buffer_level[i];\n\t    buffer_sorted[i] = stat->buffer_sorted[i];\n\t}\n\tcur_buffer = stat->cur_buffer;\n\tcur_buffer_pos = stat->cur_buffer_pos;\n\t// TODO: determine if we really have to copy collapse_pos\n\tmemcpy(collapse_pos, stat->collapse_pos, sizeof(int) * buffer_size);\n\tcollapse_even_low = stat->collapse_even_low;\n\treturn;\n    }\n\n    // There should be a faster way to do this, but this should work\n    // correctly.  The faster way should be possible if for no other\n    // reason we are inserting the values in order.  In essence we\n    // pretent that stat was made up of repeated insertions of the\n    // values kept.  Since it's contents are indistinguishable from\n    // that actually happening, the merge should be pretty close to\n    // correct; this is of course not a formal proof, and I suspect\n    // that it is wrong in some special case.\n\n    // TODO: special case bulk loading of lots of the same values;\n    // should be able to greatly simplify the addQuantile code to just\n    // copy a swath of values in.  Probably can even sort the buffer\n    // first, and if we are in order, then just drop everything in and\n    // leave the buffer marked sorted.\n\n    for(int i=0; i < stat->cur_buffer; ++i) {\n\t// cur_buffer is the one we are filling, so all previous ones are full\n\tdouble *abuf = stat->all_buffers[i];\n\tfor(int j=0; j < stat->buffer_size; ++j) {\n\t    double v = abuf[j];\n\t    for(int64_t k=0; k < stat->buffer_weight[i]; ++k) {\n\t\taddQuantile(v);\n\t    }\n\t}\n    }\n    double *abuf = stat->all_buffers[stat->cur_buffer];\n    for (int j=0; j < stat->cur_buffer_pos; ++j) {\n\tdouble v = abuf[j];\n\tfor(int64_t k=0; k < stat->buffer_weight[stat->cur_buffer]; ++k) {\n\t    addQuantile(v);\n\t}\n    }\n}\n\n// getQuantile is quite expensive for the upper quantiles; in theory\n// we ought to be able to do some sort of binary-like search in that case,\n// skipping by a lot of the lower quantiles in a batch rather than \n// ratcheting through them one by one as in the paper, and the current\n// implementation\n\n// const because the only operation on class variables is a sort of buffers\ndouble StatsQuantile::getQuantile(double quantile, bool allow_invalid_nbound) const {\n    int64_t count = countll();\n    if (count == 0) {\n\treturn Double::NaN;\n    }\n    INVARIANT(count <= Nbound || allow_invalid_nbound,\n\t      format(\"Error: %d (# entries in quantile) > %d (Nbound on quantile)\")\n\t      % count % Nbound);\n    INVARIANT(quantile >= 0.0 && quantile <= 1.0, \"quantile out of bounds\");\n    // this is slightly different than the algorithm in the paper; the \n    // goal is to allow people to calculate quantiles while the algorithm\n    // is running without having to add in and remove the +-\\Inf entries\n    // that would be needed to make the last buffer have integral size\n    // I think this change is correct\n\n    for(int i = 0; i <= cur_buffer; i++) {\n\tcollapse_pos[i] = 0;\n\t// TODO: add a check that the total weight covered by all the\n\t// current buffers is exactly the number of elements that we\n\t// have.  Have to be a little careful on the last buffer to\n\t// only count the values that we have actually inserted.\n\tif (!buffer_sorted[i]) {\n\t    if (i < cur_buffer) {\n\t\tsort(all_buffers[i],all_buffers[i] + buffer_size,\n\t\t\t  doubleOrder());\n\t    } else {\n\t\t// only sort part that has values in it.\n\t\tsort(all_buffers[i],all_buffers[i] + cur_buffer_pos,\n\t\t\t  doubleOrder());\n\t\t// Fill the rest with Inf's so that we don't have to\n\t\t// do any special logic when choosing the \"smallest\"\n\t\t// next value, all of the Inf's will come at the end, and\n\t\t// if we get to an Inf, then we are done anyway and it\n\t\t// doesn't matter if we take one that doesn't actually exist.\n\t\tfor(int j=cur_buffer_pos;j<buffer_size;j++) {\n\t\t    all_buffers[i][j] = Double::Inf;\n\t\t}\n\t    }\n\t    buffer_sorted[i] = true;\n\t}\n    }\n    // the 1e-15 accounts for a minor rounding error that seems to occur\n    // when doing division, e.g. ceil(150000.0 * (131058.0 / 150000.0)) on\n    // linux = 131059.0; I'd imagine we'll never see 1e+15 values\n    // wherein this adjustment would make a difference\n    double nentries = countll();\n    INVARIANT(nentries < 1e+14,\n\t      \"Rounding error adjustment may start to do something wrong around 1e+14 entries.\\n\"\n\t      \"May be safe to decrease rounding adjustment to 0.5e-15, but will be getting very\\n\"\n\t      \"close to the limit of precision in floating point.  How did you get this many\\n\"\n\t      \"entries into the table??\");\n    // Subtract 1 because the quantile positions count from 1..n, but\n    // C++ arrays index from 0..n-1\n    int64_t target_index \n\t= static_cast<int64_t>(ceil(nentries * (quantile - 1e-15))) - 1;\n    if (target_index < 0) target_index = 0;\n    if (target_index == nentries) {\n\ttarget_index = (long long)(nentries - 1);\n    }\n    // can be switched back to getQuantileByIndex() if there are difficulties.\n    return getQuantileByBinSearchIndex(target_index);\n}\n\nint StatsQuantile::collapseFindFirstBuffer() {\n    double nentries = countll();\n    INVARIANT(nentries < 1e+14, \"getQuantile will fail now.\");\n\t\t \n    int first_buffer;\n    for(first_buffer = nbuffers - 1;first_buffer > 0; --first_buffer) {\n\tif (buffer_level[first_buffer - 1] != buffer_level[first_buffer]) {\n\t    break;\n\t}\n    }\n    INVARIANT(first_buffer < nbuffers - 1,\n\t      \"Whoa, collapse should always operate on at least two buffers\");\n    INVARIANT(buffer_level[first_buffer] >= 0,\n\t      \"Whoa, buffer level should be positive\");\n    return first_buffer;\n}\n\n// TODO-2010-04-26: remove this and the associated test case; if it's\n// lasted this long, then we're not having problems with the new\n// binary search version.\ndouble StatsQuantile::getQuantileByIndex(uint64_t target_index) const {\n    uint64_t cur_index = 0;\n\n    PriorityQueue<std::pair<double, int>, pairCmp> tmp_pq(nbuffers);\n    for(int i=0; i < cur_buffer; ++i) {\n\tcollapse_pos[i] = 0;\n\ttmp_pq.push(make_pair(collapseVal(i), i));\n    }\n    if (cur_buffer_pos > 0) {\n\tcollapse_pos[cur_buffer] = 0;\n\ttmp_pq.push(make_pair(collapseVal(cur_buffer), cur_buffer));\n    }\n\n#if LINTEL_DEBUG\n    double prev_val = -Double::Inf;\n#endif\n    while(!tmp_pq.empty()) {\n\tdouble min_val = tmp_pq.top().first;\n\tint min_buffer = tmp_pq.top().second;\n\n#if LINTEL_DEBUG\n\tSINVARIANT(collapse_pos[min_buffer] < buffer_size && \n\t\t   (min_buffer < cur_buffer || collapse_pos[min_buffer] < cur_buffer_pos));\n\tINVARIANT(min_val >= prev_val, \"Whoa, sort order error?!\");\n\tprev_val = min_val;\n#endif\n\n\tcollapse_pos[min_buffer] += 1;\n\n\t// this entry occupies sorted order positions\n\t// [cur_index .. cur_index + buffer_weight[min_buffer] - 1]\n\t// so the check is for cur_index > target_index\n\t// need to think about the logic for this in collapse()\n\tcur_index += buffer_weight[min_buffer];\n\tif (cur_index > target_index) {\n\t    return min_val;\n\t}\n\tint max_pos = min_buffer < cur_buffer ? buffer_size : cur_buffer_pos;\n\tif (collapse_pos[min_buffer] < max_pos) {\n\t    tmp_pq.replaceTop(make_pair(collapseVal(min_buffer), min_buffer));\n\t} else {\n\t    tmp_pq.pop();\n\t}\n    }\n    return Double::NaN;\n}\n\nnamespace {\n    struct BinSearchState {\n\tuint32_t min, max, orig_max, split_lower, split_upper;\n\texplicit BinSearchState(uint32_t b) \n\t    : min(0), max(b), orig_max(b)\n\t{ }\n\tuint32_t mid() const { return (max + min) / 2; }\n\tuint32_t remain() const { return max - min; }\n\n\tvoid calculateBounds(double target, double *buffer) {\n\t    double *lower = lower_bound(buffer + min, buffer + max, target);\n\t    split_lower = lower - buffer;\n\t    double *upper = upper_bound(buffer + min, buffer + max, target);\n\t    split_upper = upper - buffer;\n\t}\n    };\n\n    uint32_t biggestRemaining(const vector<BinSearchState> &state) {\n\tuint32_t biggest = 0;\n\tuint32_t remain = state[0].remain();\n\tfor(uint32_t i = 1; i < state.size(); ++i) {\n\t    if (state[i].remain() > remain) {\n\t\tbiggest = i;\n\t\tremain = state[i].remain();\n\t    }\n\t}\n\treturn biggest;\n    }\n}\n\n\n\ndouble StatsQuantile::getQuantileByBinSearchIndex(uint64_t target_index) const {\n    vector<BinSearchState> state;\n\n    // one last buffer if the last one is present\n    state.resize(cur_buffer + (cur_buffer_pos > 0 ? 1 : 0), BinSearchState(buffer_size)); \n    if (cur_buffer_pos > 0) {\n\tstate[cur_buffer].max = state[cur_buffer].orig_max = cur_buffer_pos;\n    }\n\n    uint64_t entry_count = 0;\n    for(uint32_t i = 0; i < static_cast<uint32_t>(cur_buffer); ++i) {\n\tentry_count += static_cast<uint64_t>(buffer_weight[i]) * buffer_size;\n    }\n    entry_count += cur_buffer_pos;\n    SINVARIANT(entry_count == countll());\n    \n    LintelLogDebug(\"StatsQuantile::getQuantile\", format(\"entries %d\") % entry_count);\n    while(true) {\n\tuint32_t biggest = biggestRemaining(state);\n\tdouble split_val = all_buffers[biggest][state[biggest].mid()];\n\tLintelLogDebug(\"StatsQuantile::getQuantile\", format(\"biggest %d, split @%.12g\") \n\t\t       % biggest % split_val);\n\n\tuint64_t count_lower = 0;\n\tuint64_t count_match = 0;\n\tuint64_t count_upper = 0;\n\tfor(uint32_t i = 0; i < state.size(); ++i) {\n\t    state[i].calculateBounds(split_val, all_buffers[i]);\n\t    LintelLogDebug(\"StatsQuantile::getQuantile\", \n\t\t\t   format(\"  buffer %d wt=%d min=%d, sl=%d, su=%d, max=%d\") \n\t\t\t   % i % buffer_weight[i] % state[i].min \n\t\t\t   % state[i].split_lower % state[i].split_upper % state[i].max);\n\t    count_lower += buffer_weight[i] * state[i].split_lower; // 0 .. split_lower - 1\n\t    count_match += buffer_weight[i] \n\t\t* (state[i].split_upper - state[i].split_lower); // split_lower .. split_upper -1\n\t    count_upper += buffer_weight[i] \n\t\t* (state[i].orig_max - state[i].split_upper); // split_upper .. buffer_size - 1\n\t}\n\tLintelLogDebug(\"StatsQuantile::getQuantile\", format(\"cl=%d, cm=%d, cu=%d\")\n\t\t       % count_lower % count_match % count_upper);\n\tSINVARIANT(count_lower + count_match + count_upper == entry_count);\n\n\tif (target_index < count_lower) {\n\t    LintelLogDebug(\"StatsQuantile::getQuantile\", \"in-lower\");\n\t    bool any_changed = false;\n\t    for(uint32_t i = 0; i < state.size(); ++i) {\n\t\tif (state[i].max != state[i].split_lower) any_changed = true;\n\t\tstate[i].max = state[i].split_lower;\n\t\tSINVARIANT(state[i].min <= state[i].max);\n\t    }\n\t    SINVARIANT(any_changed);\n\t} else if (target_index < count_lower + count_match) {\n\t    LintelLogDebug(\"StatsQuantile::getQuantile\", \"***match\");\n\t    return split_val; // even if we didn't find the exact match, we're good enough\n\t} else if (target_index < count_lower + count_match + count_upper) {\n\t    LintelLogDebug(\"StatsQuantile::getQuantile\", \"in-upper\");\n\t    bool any_changed = false;\n\t    for(uint32_t i = 0; i < state.size(); ++i) {\n\t\tif (state[i].min != state[i].split_upper) any_changed = true;\n\t\tstate[i].min = state[i].split_upper;\n\t\tSINVARIANT(state[i].min <= state[i].max);\n\t    }\n\t    SINVARIANT(any_changed);\n\t}\n    }\n    FATAL_ERROR(\"unimplemented\");\n}\n  \n\nint64_t StatsQuantile::collapseSortBuffers(int first_buffer) {\n    int64_t total_weight = 0;\n    for(int i=first_buffer;i<nbuffers;i++) {\n\ttotal_weight += buffer_weight[i];\n\tINVARIANT(buffer_weight[i] > 0, \"Whoa, buffer_weight should be at least 1\");\n\tcollapse_pos[i] = 0;\n\tif (buffer_sorted[i]) {\n\t    // could re-verify sortedness here, but we'll probably catch it later\n\t} else {\n\t    INVARIANT(i == (nbuffers - 1) || buffer_weight[i] == 1,\n\t\t      format(\"Huh %d != %d // %d\") % i % (nbuffers - 1) % buffer_weight[i]);\n\t    // sort the buffer\n\t    sort(all_buffers[i], all_buffers[i] + buffer_size, doubleOrder());\n\t    buffer_sorted[i] = true;\n\t} \n    }\n    return total_weight;\n}\n\nint64_t StatsQuantile::collapseNextQuantileOffset(int64_t total_weight) {\n    int64_t next_quantile_offset = 0;\n    if ((total_weight % 2) == 0) {\n\tif (collapse_even_low) {\n\t    next_quantile_offset = total_weight / 2;\n\t    collapse_even_low = false;\n\t} else {\n\t    next_quantile_offset = (total_weight + 2) / 2;\n\t    collapse_even_low = true;\n\t}\n    } else if ((total_weight % 2) == 1) {\n\tnext_quantile_offset = (total_weight + 1) / 2;\n    } else {\n\tFATAL_ERROR(\"Huh?\");\n    }\n    return next_quantile_offset;\n}\n\nvoid StatsQuantile::collapse() {\n    // could do a more \"in-place\" collapse by first doing the walk, and\n    // for every entry which is not going to go into the final collation,\n    // replace it with a NaN; then move all the entries in the output \n    // bucket which are not NaN's to the end, then collate again in order\n    // filling into the output location; this does in-place, but requires\n    // two walks over the larger data, and so may very well be slower\n    // it's also a lot more complex\n\n    int first_buffer = collapseFindFirstBuffer();\n\n    // first, sort each of the unsorted input buffers \n    int64_t total_weight = collapseSortBuffers(first_buffer);\n    \n    int64_t next_quantile_offset = collapseNextQuantileOffset(total_weight);\n\n    // Since we start counting at offset 0 (the paper starts at 1), we \n    // subtract one from the starting offset\n    next_quantile_offset -= 1;\n    DEBUG_SINVARIANT(next_quantile_offset >= 0);\n\n    int64_t cur_quantile_offset = 0;\n    int64_t next_output_pos = 0;\n    IF_LINTEL_DEBUG(double prev_val = -Double::Inf;)\n\n    // Because a double and int are small, it's faster to store the\n    // pair rather than do the double dereference each time to\n    // translate a buffer number into its value.\n    PriorityQueue<pair<double, int>, pairCmp> pq(nbuffers);\n    for(int i=first_buffer; i < nbuffers; ++i) {\n\tpq.push(make_pair(collapseVal(i), i));\n    }\n    if (tmp_buffer == NULL) {\n\ttmp_buffer = new double[buffer_size];\n    }\n    while(next_output_pos < buffer_size) {\n\tint min_buffer = pq.top().second;\n\tdouble min_val = pq.top().first;\n\n\tDEBUG_INVARIANT(min_val >= prev_val, \"Whoa, sort order error?!\");\n\tIF_LINTEL_DEBUG(prev_val = min_val;)\n\tcollapse_pos[min_buffer] += 1;\n\t// same logic as for output(), this entry is in positions\n\t// [cur_quantile_offset .. cur_quantile_offset + bw[mb] - 1]\n\t// so if after adding in bw[mb], cqo > nqo then we just passed\n\t// nqo, so it should be used as the value to fit into the\n\t// new list\n\tcur_quantile_offset += buffer_weight[min_buffer];\n\tif (cur_quantile_offset > next_quantile_offset) {\n\t    tmp_buffer[next_output_pos] = min_val;\n\t    next_output_pos += 1;\n\t    next_quantile_offset += total_weight;\n\t}\n\n\tif (collapse_pos[min_buffer] < buffer_size) {\n\t    pq.replaceTop(make_pair(collapseVal(min_buffer), min_buffer));\n\t} else {\n\t    pq.pop();\n\t    DEBUG_SINVARIANT(next_output_pos == buffer_size || !pq.empty());\n\t}\n    }\n    INVARIANT(next_quantile_offset / total_weight == buffer_size,\n\t      format(\"Huh, didn't get to correct quantile offset %lld/%d != %d?!\")\n\t      % next_quantile_offset % total_weight % buffer_size);\n\n    // update all_buffers[first_buffer]\n    memcpy(all_buffers[first_buffer],tmp_buffer, buffer_size * sizeof(double));\n    buffer_level[first_buffer] = buffer_level[first_buffer] + 1;\n    buffer_weight[first_buffer] = total_weight;\n    buffer_sorted[first_buffer] = true;\n\n    // clean up buffer weights\n    for(int i=first_buffer + 1;i<nbuffers;i++) {\n\tbuffer_weight[i] = -1;\n\tbuffer_level[i] = -1;\n\tbuffer_sorted[i] = false;\n    }\n    cur_buffer = first_buffer + 1;\n}\n\nvoid StatsQuantile::dumpState() {\n    printf(\"%d buffers, each containing %d entries\\n\",\n\t   nbuffers,buffer_size);\n    printf(\"cur buffer is %d, cur buffer pos is %d\\n\",\n\t   cur_buffer,cur_buffer_pos);\n\n    for(int i=0;i<=cur_buffer;i++) {\n\tcout << format(\"  buffer %d, level %d, weight %d:\\n    \")\n\t    % i % buffer_level[i] % buffer_weight[i];\n\tint max = i == cur_buffer ? cur_buffer_pos : buffer_size;\n\tfor(int j=0;j<max;j++) {\n\t    printf(\"%.4g, \",all_buffers[i][j]);\n\t    if ((j%10) == 9) {\n\t\tprintf(\"\\n    \");\n\t    }\n\t}\n\tprintf(\"\\n\");\n    }\n}\n\nvoid StatsQuantile::printRome(int depth, ostream &out) const {\n    Stats::printRome(depth,out);\n    string spaces;\n    for(int i = 0; i < depth; i++) {\n\tspaces += \" \";\n    }\n    double nentries = countll();\n    if (nentries > 0) {\n\tout << spaces << \"{ quantiles (\\n\";\n\tdouble step = 1.0 / (double)print_nrange;\n\tint nquantiles = 0;\n\tfor(double quantile = step;Double::lt(quantile,1.0);quantile += step) {\n\t    double quantile_value = getQuantile(quantile);\n\t    out << spaces << \"  { \" << quantile*100 << \" \" << quantile_value << \" }\\n\";\n\t    ++nquantiles;\n\t}\n\tfor(double tail_frac = 0.1; (tail_frac * nentries) >= 1.0;) {\n\t    double quantile_value = getQuantile(1-tail_frac);\n\t    out << spaces << \"  { \" << 100*(1-tail_frac) << \" \" << quantile_value << \" }\\n\";\n\t    tail_frac /= 2.0;\n\t    quantile_value = getQuantile(1-tail_frac);\n\t    out << spaces << \"  { \" << 100*(1-tail_frac) << \" \" << quantile_value << \" }\\n\";\n\t    tail_frac /= 5.0;\n\t}\n\tout << spaces << \") }\\n\";\n    }\n}\n\nvoid StatsQuantile::printFile(FILE *out, int nranges) {\n    ostringstream tmp;\n    printTextRanges(tmp, nranges);\n    fwrite(tmp.str().data(), tmp.str().size(), 1, out);\n}\n\nvoid StatsQuantile::printTextRanges(ostream &out, int nranges, double multiplier) const {\n    nranges = (nranges == -1 ? print_nrange : nranges);\n    out << format(\"%lld data points, mean %.6g +- %.6g [%.6g,%.6g]\\n\")\n\t% countll() % (multiplier * mean()) % (multiplier * stddev()) \n\t% (multiplier * min()) % (multiplier * max());\n    if (countll() == 0) return;\n    out << format(\"    quantiles about every %.0f data points:\")\n\t% ((double)countll()/(double)nranges);\n    double step = 1.0 / (double)nranges;\n    int nquantiles = 0;\n    for(double quantile = step;Double::lt(quantile,1.0);quantile += step) {\n\tif ((nquantiles % 10) == 0) {\n\t    out << format(\"\\n    %.4g%%: \") % (quantile * 100);\n\t} else {\n\t    out << \", \";\n\t}\n\n\tout << format(\"%.8g\") % (multiplier * getQuantile(quantile));\n\t++nquantiles;\n    }\n    out << \"\\n\";\n}\n\nvoid StatsQuantile::printTail(FILE *out) {\n    ostringstream tmp;\n    printTextTail(tmp);\n    fwrite(tmp.str().data(), tmp.str().size(), 1, out);\n}\n\n// TODO: should this print tails if we have very few data points,\n// e.g. 22 data points, should we get the 90%,95% tails?  This happens\n// in the dataseries groupby regression test, but may be otherwise\n// irrelevant.\nvoid StatsQuantile::printTextTail(ostream &out, double multiplier) const {\n    double nentries = countll();\n    out << \"  tails: \";\n    for(double tail_frac = 0.1; (tail_frac * nentries) >= 10.0;) {\n\tif (tail_frac < 0.05) {\n\t    out << \", \";\n\t}\n\tout << format(\"%.12g%%: %.8g\")\n\t    % (100*(1-tail_frac)) % (multiplier * getQuantile(1-tail_frac));\n\ttail_frac /= 2.0;\n\tout << format(\", %.12g%%: %.8g\")\n\t    % (100*(1-tail_frac)) % (multiplier * getQuantile(1-tail_frac));\n\ttail_frac /= 5.0;\n    }\n    out << \"\\n\";\n}\n\nvoid StatsQuantile::printText(ostream &out) const {\n    printTextRanges(out);\n    printTextTail(out);\n}\n\nsize_t StatsQuantile::memoryUsage() const {\n    // primary data (init_buffers) + secondary metadata (init)\n    return nbuffers * buffer_size * sizeof(double) // primary\n\t+ nbuffers * (sizeof(int64_t) + sizeof(int) + sizeof(bool)\n\t\t      + sizeof(double) + sizeof(int)) // secondary\n\t+ sizeof(StatsQuantile);\n}\n", "meta": {"hexsha": "6d155a4b1875e7296f4ba2e989ed8b477ca593b1", "size": 26324, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/StatsQuantile.cpp", "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": "src/StatsQuantile.cpp", "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": "src/StatsQuantile.cpp", "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": 33.7920410783, "max_line_length": 101, "alphanum_fraction": 0.6570809907, "num_tokens": 7480, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185944046238981, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.46035734068939854}}
{"text": "/*\n * LineIterator.hpp\n *\n *  Created on: Nov 13, 2014\n *      Author: P\u00e9ter Fankhauser\n *   Institute: ETH Zurich, Autonomous Systems Lab\n */\n\n#pragma once\n\n#include \"grid_map_core/GridMap.hpp\"\n#include \"grid_map_core/iterators/SubmapIterator.hpp\"\n\n// Eigen\n#include <Eigen/Core>\n\nnamespace grid_map {\n\n/*!\n * Iterator class to iterate over a line in the map.\n * Based on Bresenham Line Drawing algorithm.\n */\nclass LineIterator\n{\npublic:\n\n  /*!\n   * Constructor.\n   * @param gridMap the grid map to iterate on.\n   * @param start the starting index of the line.\n   * @param end the ending index of the line.\n   */\n  LineIterator(const grid_map::GridMap& gridMap, const Eigen::Array2i& start, const Eigen::Array2i& end);\n\n  /*!\n   * Constructor.\n   * @param gridMap the grid map to iterate on.\n   * @param start the starting point of the line.\n   * @param end the ending point of the line.\n   */\n  LineIterator(const grid_map::GridMap& gridMap, const Eigen::Vector2d& start, const Eigen::Vector2d& end);\n\n  /*!\n   * Assignment operator.\n   * @param iterator the iterator to copy data from.\n   * @return a reference to *this.\n   */\n  LineIterator& operator =(const LineIterator& other);\n\n  /*!\n   * Compare to another iterator.\n   * @return whether the current iterator points to a different address than the other one.\n   */\n  bool operator !=(const LineIterator& other) const;\n\n  /*!\n   * Dereference the iterator with const.\n   * @return the value to which the iterator is pointing.\n   */\n  const Eigen::Array2i& operator *() const;\n\n  /*!\n   * Increase the iterator to the next element.\n   * @return a reference to the updated iterator.\n   */\n  LineIterator& operator ++();\n\n  /*!\n   * Indicates if iterator is past end.\n   * @return true if iterator is out of scope, false if end has not been reached.\n   */\n  bool isPastEnd() const;\n\nprivate:\n\n  // TODO\n  void initializeParameters();\n\n  //! Current index.\n  Eigen::Array2i index_;\n\n  //! Starting index of the line.\n  Eigen::Array2i start_;\n\n  //! Ending index of the line.\n  Eigen::Array2i end_;\n\n  //! Current cell number.\n  unsigned int iCell_;\n\n  //! Number of cells in the line.\n  unsigned int nCells_;\n\n  //! Helper variables for Bresenham Line Drawing algorithm.\n  Eigen::Array2i increment1_, increment2_;\n  int denominator_, numerator_, numeratorAdd_;\n\n  //! Map information needed to get position from iterator.\n  Eigen::Array2d mapLength_;\n  Eigen::Vector2d mapPosition_;\n  double resolution_;\n  Eigen::Array2i bufferSize_;\n  Eigen::Array2i bufferStartIndex_;\n};\n\n} /* namespace */\n", "meta": {"hexsha": "675bb4d39eaef85d5b823c9dd62f3ad58ecf56a1", "size": 2548, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "grid_map_core/include/grid_map_core/iterators/LineIterator.hpp", "max_stars_repo_name": "EricLYang/grid_map", "max_stars_repo_head_hexsha": "4c0defae8b2860060679d914bce969a38a478e9b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-08-29T01:29:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-17T08:29:27.000Z", "max_issues_repo_path": "grid_map_core/include/grid_map_core/iterators/LineIterator.hpp", "max_issues_repo_name": "ycb88/grid_map", "max_issues_repo_head_hexsha": "93ca546f48012b7b0c500c730bd7d878c9a4e47e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "grid_map_core/include/grid_map_core/iterators/LineIterator.hpp", "max_forks_repo_name": "ycb88/grid_map", "max_forks_repo_head_hexsha": "93ca546f48012b7b0c500c730bd7d878c9a4e47e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-17T08:29:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-17T08:29:30.000Z", "avg_line_length": 23.8130841121, "max_line_length": 107, "alphanum_fraction": 0.6887755102, "num_tokens": 634, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708562, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.46035733296778775}}
{"text": "// Copyright 2015-2018 Hans Dembinski\n//\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include <boost/core/is_same.hpp>\n#include <boost/core/lightweight_test.hpp>\n#include <boost/core/lightweight_test_trait.hpp>\n#include <boost/histogram/axis.hpp>\n#include <boost/histogram/axis/ostream.hpp>\n#include <boost/histogram/histogram.hpp>\n#include <boost/histogram/ostream.hpp>\n#include <boost/throw_exception.hpp>\n#include <string>\n#include <vector>\n#include \"std_ostream.hpp\"\n#include \"throw_exception.hpp\"\n#include \"utility_histogram.hpp\"\n\nusing namespace boost::histogram;\n\ntemplate <typename Tag>\nvoid run_tests() {\n  // arithmetic operators\n  {\n    auto a = make(Tag(), axis::integer<int, use_default, axis::option::none_t>(0, 2));\n    auto b = a;\n    a(0);\n    b(1);\n    auto c = a + b;\n    BOOST_TEST_EQ(c.at(0), 1);\n    BOOST_TEST_EQ(c.at(1), 1);\n    c += b;\n    BOOST_TEST_EQ(c.at(0), 1);\n    BOOST_TEST_EQ(c.at(1), 2);\n    auto d = a + b + c;\n    BOOST_TEST_TRAIT_SAME(decltype(d), decltype(a));\n    BOOST_TEST_EQ(d.at(0), 2);\n    BOOST_TEST_EQ(d.at(1), 3);\n\n    auto d2 = d - a - b - c;\n    BOOST_TEST_TRAIT_SAME(decltype(d2), decltype(a));\n    BOOST_TEST_EQ(d2.at(0), 0);\n    BOOST_TEST_EQ(d2.at(1), 0);\n    d2 -= a;\n    BOOST_TEST_EQ(d2.at(0), -1);\n    BOOST_TEST_EQ(d2.at(1), 0);\n\n    auto d3 = d;\n    d3 *= d;\n    BOOST_TEST_EQ(d3.at(0), 4);\n    BOOST_TEST_EQ(d3.at(1), 9);\n    auto d4 = d3 * (1 * d); // converted return type\n    BOOST_TEST_TRAIT_FALSE((boost::core::is_same<decltype(d4), decltype(d3)>));\n    BOOST_TEST_EQ(d4.at(0), 8);\n    BOOST_TEST_EQ(d4.at(1), 27);\n    d4 /= d;\n    BOOST_TEST_EQ(d4.at(0), 4);\n    BOOST_TEST_EQ(d4.at(1), 9);\n    auto d5 = d4 / d;\n    BOOST_TEST_EQ(d5.at(0), 2);\n    BOOST_TEST_EQ(d5.at(1), 3);\n\n    auto e = 3 * a; // converted return type\n    auto f = b * 2; // converted return type\n    BOOST_TEST_TRAIT_FALSE((boost::core::is_same<decltype(e), decltype(a)>));\n    BOOST_TEST_TRAIT_FALSE((boost::core::is_same<decltype(f), decltype(a)>));\n    BOOST_TEST_EQ(e.at(0), 3);\n    BOOST_TEST_EQ(e.at(1), 0);\n    BOOST_TEST_EQ(f.at(0), 0);\n    BOOST_TEST_EQ(f.at(1), 2);\n    auto r = 1.0 * a;\n    r += b;\n    r += e;\n    BOOST_TEST_EQ(r.at(0), 4);\n    BOOST_TEST_EQ(r.at(1), 1);\n    BOOST_TEST_EQ(r, a + b + 3 * a);\n    auto s = r / 4;\n    r /= 4;\n    BOOST_TEST_EQ(r.at(0), 1);\n    BOOST_TEST_EQ(r.at(1), 0.25);\n    BOOST_TEST_EQ(r, s);\n  }\n\n  // arithmetic operators with mixed storage: unlimited vs. vector<unsigned>\n  {\n    auto ia = axis::integer<int, axis::null_type, axis::option::none_t>(0, 2);\n    auto a = make(Tag(), ia);\n    a(0, weight(2));\n    a(1, weight(2));\n    auto b = a;\n    auto c = make_s(Tag(), std::vector<int>(), ia);\n    c(0, weight(2));\n    c(1, weight(2));\n    auto a2 = a;\n    a2 += c;\n    BOOST_TEST_EQ(a2, (a + b));\n    auto a3 = a;\n    a3 *= c;\n    BOOST_TEST_EQ(a3, (a * b));\n    auto a4 = a;\n    a4 -= c;\n    BOOST_TEST_EQ(a4, (a - b));\n    auto a5 = a;\n    a5 /= c;\n    BOOST_TEST_EQ(a5, (a / b));\n  }\n\n  // arithmetic operators with mixed storage: vector<unsigned char> vs. vector<unsigned>\n  {\n    auto ia = axis::integer<int, axis::null_type, axis::option::none_t>(0, 2);\n    auto a = make_s(Tag(), std::vector<unsigned long>{}, ia);\n    auto c = make_s(Tag(), std::vector<unsigned>(), ia);\n    a(0, weight(2u));\n    a(1, weight(2u));\n    auto b = a;\n    c(0, weight(2u));\n    c(1, weight(2u));\n    auto a2 = a;\n    a2 += c;\n    BOOST_TEST_EQ(a2, (a + b));\n    auto a3 = a;\n    a3 *= c;\n    BOOST_TEST_EQ(a3, (a * b));\n    auto a4 = a;\n    a4 -= c;\n    BOOST_TEST_EQ(a4, (a - b));\n    auto a5 = a;\n    a5 /= c;\n    BOOST_TEST_EQ(a5, (a / b));\n  }\n\n  // add operators with weighted storage\n  {\n    auto ia = axis::integer<int, axis::null_type, axis::option::none_t>(0, 2);\n    auto a = make_s(Tag(), std::vector<accumulators::weighted_sum<>>(), ia);\n    auto b = make_s(Tag(), std::vector<accumulators::weighted_sum<>>(), ia);\n\n    a(0);\n    BOOST_TEST_EQ(a.at(0).variance(), 1);\n    b(weight(3), 1);\n    BOOST_TEST_EQ(b.at(1).variance(), 9);\n    auto c = a;\n    c += b;\n    BOOST_TEST_EQ(c.at(0).value(), 1);\n    BOOST_TEST_EQ(c.at(0).variance(), 1);\n    BOOST_TEST_EQ(c.at(1).value(), 3);\n    BOOST_TEST_EQ(c.at(1).variance(), 9);\n    auto d = a;\n    d += b;\n    BOOST_TEST_EQ(d.at(0).value(), 1);\n    BOOST_TEST_EQ(d.at(0).variance(), 1);\n    BOOST_TEST_EQ(d.at(1).value(), 3);\n    BOOST_TEST_EQ(d.at(1).variance(), 9);\n\n    // add unweighted histogram\n    auto e = make_s(Tag(), std::vector<int>(), ia);\n    std::fill(e.begin(), e.end(), 2);\n\n    d += e;\n    BOOST_TEST_EQ(d.at(0).value(), 3);\n    BOOST_TEST_EQ(d.at(0).variance(), 3);\n    BOOST_TEST_EQ(d.at(1).value(), 5);\n    BOOST_TEST_EQ(d.at(1).variance(), 11);\n  }\n\n  // bad operations\n  {\n    auto a = make(Tag(), axis::integer<>(0, 2));\n    auto b = make(Tag(), axis::integer<>(0, 3));\n    BOOST_TEST_THROWS(a += b, std::invalid_argument);\n    BOOST_TEST_THROWS(a -= b, std::invalid_argument);\n    BOOST_TEST_THROWS(a *= b, std::invalid_argument);\n    BOOST_TEST_THROWS(a /= b, std::invalid_argument);\n  }\n}\n\nint main() {\n  run_tests<static_tag>();\n  run_tests<dynamic_tag>();\n\n  return boost::report_errors();\n}\n", "meta": {"hexsha": "8838578990658a15b62e1dbf0d33504747a84e1f", "size": 5270, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/histogram_operators_test.cpp", "max_stars_repo_name": "jbuonagurio/histogram", "max_stars_repo_head_hexsha": "a872c6e1c32e3c6000317b07aec7e416c8939c75", "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": "test/histogram_operators_test.cpp", "max_issues_repo_name": "jbuonagurio/histogram", "max_issues_repo_head_hexsha": "a872c6e1c32e3c6000317b07aec7e416c8939c75", "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/histogram_operators_test.cpp", "max_forks_repo_name": "jbuonagurio/histogram", "max_forks_repo_head_hexsha": "a872c6e1c32e3c6000317b07aec7e416c8939c75", "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.4864864865, "max_line_length": 88, "alphanum_fraction": 0.5929791271, "num_tokens": 1738, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708562, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.46035733296778775}}
{"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#define NT2_UNIT_MODULE \"nt2 complex.operator toolbox - sqrti/scalar Mode\"\n\n//////////////////////////////////////////////////////////////////////////////\n// unit test behavior of boost.simd.operator components in scalar mode\n//////////////////////////////////////////////////////////////////////////////\n/// created  by jt the 18/02/2011\n///\n#include <nt2/include/constants/sqrti.hpp>\n#include <nt2/include/constants/sqrt_2o_2.hpp>\n#include <boost/simd/sdk/simd/logical.hpp>\n#include <boost/type_traits/is_same.hpp>\n#include <boost/dispatch/functor/meta/call.hpp>\n#include <nt2/sdk/unit/tests.hpp>\n#include <nt2/sdk/unit/module.hpp>\n#include <nt2/toolbox/constant/constant.hpp>\n\nNT2_TEST_CASE_TPL ( sqrti_real__2_0,  BOOST_SIMD_REAL_TYPES)\n{\n\n  typedef std::complex<T> cT;\n\n  // specific values tests\n  NT2_TEST_EQUAL(nt2::Sqrti<cT>(),  cT(nt2::Sqrt_2o_2<T>(),nt2::Sqrt_2o_2<T>()));\n\n} // end of test for floating_\n", "meta": {"hexsha": "dc6abb7146d7f0cec980dedce3e47a0e2096da4d", "size": 1424, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/type/complex/operator/unit/scalar/sqrti.cpp", "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/type/complex/operator/unit/scalar/sqrti.cpp", "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/type/complex/operator/unit/scalar/sqrti.cpp", "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.8823529412, "max_line_length": 81, "alphanum_fraction": 0.544241573, "num_tokens": 331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7185943925708562, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.46035733296778775}}
{"text": "// Sampling code\n\n#include <ctime>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <string>\n#include <Eigen/Dense>\n#include \"state.hpp\"\n\n#define USAGE \"./infer directory [samples [burn [thin [proposals]]]]\"\n\n// Default params\n#define SAMPLES 24000\n#define BURN 6000\n#define THIN 6\n#define PROPOSALS 6\n\nusing namespace Eigen;\nusing namespace std;\n\n///////////////////////\n// Sampling function //\n///////////////////////\n\n// Given the specified sampling parameters, performs MCMC updates and\n// computes the posterior mean of object coocurrence/strengths\nvoid infer(State &state, int samples, int burn, int thin, int proposals,\n            ArrayXXd &avg_cooc, ArrayXXd &avg_strengths)\n{\n    int N = state.strengths.cols();\n    int A = state.strengths.rows();\n    avg_cooc = MatrixXd::Identity(N,N); // Only matrix class has Identity\n    avg_strengths = ArrayXXd::Zero(A,N);\n\n    // Burn-in\n    for (int i=0;i<burn;i++){\n        state.update(proposals);\n    }\n\n    // Thinned samples from posterior\n    for (int i=0;i<samples-burn;i++){\n        state.update(proposals);\n        if (i % thin == 0){\n            // Update avg_cooc\n            for (int j=0;j<N;j++) {\n            for (int k=j+1;k<N;k++) {\n                bool same = state.z(j) == state.z(k);\n                avg_cooc(k,j) += (same - avg_cooc(k,j))/(i+1);\n            }\n            }\n            \n            // Update avg_strengths\n            ArrayXXd diff = state.strengths - avg_strengths;\n            avg_strengths += diff/(i+1);\n        }\n    }\n\n    // Fill in other side of cooc\n    for (int j=0;j<N;j++) {\n    for (int k=j+1;k<N;k++) {\n        avg_cooc(j,k) = avg_cooc(k,j);\n    }\n    }\n}\n\n//////////////////\n// IO Functions //\n//////////////////\n\nvoid events_from_file(string file, ArrayXXi &pos, ArrayXXi &neg)\n{\n    // First we compute the size of the file (we assume correct formatting)\n    ifstream in(file.c_str());\n    string line,field;\n    getline(in,line);\n\n    // Get the first line to determine the number of cols\n    int cols = 0;\n    stringstream firstrow(line);\n    while (getline(firstrow,field,',')){\n        cols++;\n    }\n\n    // Get the rest of the lines to determine the number of rows\n    int rows = 1;\n    while (getline(in,line)){\n        rows++;\n    }\n    in.close();\n\n    // Now we rescan the file, and split the data into pos/neg event counts\n    // (Note that data is stored tranposed relative to CSV layout).\n    in.open(file.c_str());\n    pos.resize(cols/2,rows);\n    neg.resize(cols/2,rows);\n    for (int r=0;r<rows;r++){\n        getline(in,line);\n        stringstream stream(line);\n        bool even = true;\n\n        for (int c=0;c<cols;c++){\n            getline(stream,field,',');\n            if (even){\n                pos(c/2,r) = atoi(field.c_str());\n            } else {\n                neg(c/2,r) = atoi(field.c_str());\n            }\n            even = !even;\n        }\n    }\n    in.close();\n}\n\n// Writes an coccurence array to standard error\nvoid array_to_file(string file, const Ref<const ArrayXXd> &arr)\n{\n    ofstream out(file.c_str());\n    int C = arr.cols();\n    int R = arr.rows();\n\n    for (int c=0;c<C;c++){\n        for (int r=0;r<R;r++){\n            out << arr(r,c);\n            if ( R-r > 1 ){\n                out << ',';\n            }\n        }\n        out << endl;\n    }\n}\n\n///////////////////\n// Main function //\n///////////////////\n\nint main(int argc, char *argv[])\n{\n    // Parse the options\n    if (argc < 2 || argc > 6) {\n        cout << USAGE << endl;\n        return 1;\n    }\n\n    // Sampling parameters\n    int samples = SAMPLES;\n    int burn = BURN;\n    int thin = THIN;\n    int proposals = PROPOSALS;\n    if (argc > 2){\n        samples = atoi(argv[2]);\n    if (argc > 3){\n        burn = atoi(argv[3]);\n    if (argc > 4){\n        thin = atoi(argv[4]);\n    if (argc > 5){\n        proposals = atoi(argv[5]);\n    }}}}\n\n    // Directory location\n    string dir = argv[1];\n    if (dir[dir.length()] != '/'){ // Kind of a hack...\n        dir += '/';\n    }\n    string events_file = dir + \"events.csv\";\n    \n    // Import the data\n    ArrayXXi pos,neg;\n    events_from_file(events_file,pos,neg);\n\n    // Create the particle\n    gsl_rng *rng = gsl_rng_alloc(gsl_rng_default);\n    State particle(rng,pos,neg);\n\n    // Sample and compute the posterior co-occurence/strengths\n    ArrayXXd avg_cooc,avg_strengths;\n    clock_t begin = clock();\n    infer(particle,samples,burn,thin,proposals,avg_cooc,avg_strengths);\n    double duration = float(clock() - begin) / CLOCKS_PER_SEC;\n    cout << \"Took : \" << duration << \" seconds\" << endl;\n    cout << \"Final state: \" << endl;\n    particle.print_vars(true);\n\n    // Write the posterior averages to disk\n    string cooc_file = dir + \"cooc.csv\";\n    array_to_file(cooc_file,avg_cooc);\n\n    string strengths_file = dir + \"strengths.csv\";\n    array_to_file(strengths_file,avg_strengths);\n\n    gsl_rng_free(rng);\n    return 0;\n}\n", "meta": {"hexsha": "f38daf13b131023287338fd3408667a728212b68", "size": 4902, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bench/clustering/main.cpp", "max_stars_repo_name": "crafthpc/fphpc", "max_stars_repo_head_hexsha": "6911fd7d3961feec92c8a4c2812b83e7b98ca9d6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-02-23T22:38:32.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-21T13:08:53.000Z", "max_issues_repo_path": "bench/clustering/main.cpp", "max_issues_repo_name": "crafthpc/fphpc", "max_issues_repo_head_hexsha": "6911fd7d3961feec92c8a4c2812b83e7b98ca9d6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2018-11-11T20:38:00.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-15T20:50:37.000Z", "max_forks_repo_path": "bench/clustering/main.cpp", "max_forks_repo_name": "crafthpc/fphpc", "max_forks_repo_head_hexsha": "6911fd7d3961feec92c8a4c2812b83e7b98ca9d6", "max_forks_repo_licenses": ["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.2680412371, "max_line_length": 75, "alphanum_fraction": 0.5518155855, "num_tokens": 1281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.4603573329677877}}
{"text": "#include <cmath>\n#include <ctime>\n#include <iostream>\n#include <iterator>\n#include <deque>\n#include <fstream>\n#include <sstream>\nusing namespace std;\n\n#include <boost/random.hpp>\n\n#define BOOST_TEST_MAIN\n// #define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE TestFFTLibs\n#include <boost/test/unit_test.hpp>\n\n#include <fftscarf.h>\nusing namespace fftscarf;\n\n#include \"../benchmark/stream.h\"\n\n#include <boost/program_options.hpp>\nnamespace po = boost::program_options;\n\ntemplate<typename FFTPlanType>\nstatic void test_lib(){\n\n    // Default argument\n    int N = 4096;\n\n    // Arguments parsing\n    po::options_description desc(\"Options\");\n    desc.add_options()\n        (\"size\", po::value<uint32_t>(), \"The FFT size\")\n        (\"specverif\", \"Verify the spectrum by comparison with a reference\")\n        (\"specprint\", \"If verification fails, print the erroneous vectors\")\n    ;\n    //    po::positional_options_description posopt;\n    //    posopt.add(\"size\", 1);\n    po::variables_map vm;\n//    po::store(po::command_line_parser(boost::unit_test::framework::master_test_suite().argc, boost::unit_test::framework::master_test_suite().argv).options(desc).positional(posopt).run(), vm);\n    po::store(po::parse_command_line(boost::unit_test::framework::master_test_suite().argc, boost::unit_test::framework::master_test_suite().argv, desc), vm);\n    po::notify(vm);\n    if (vm.count(\"size\"))\n        N = vm[\"size\"].as<uint32_t>();\n\n    std::cout << \"Testing \" << FFTPlanType::libraryName() << \"  N=\" << N << \" ...\" << std::endl;\n\n    boost::mt19937 rnd_engine((uint32_t)std::time(0));\n    std::vector<std::complex<typename FFTPlanType::FloatType> > spec;\n    std::vector<std::complex<typename FFTPlanType::FloatType> > spec_ref;\n    std::vector<typename FFTPlanType::FloatType> inframe, outframe;\n\n    long double accthresh = 100*fftscarf::eps<typename FFTPlanType::FloatType>();\n\n    #ifdef FFTSCARF_PRECISION_LONGDOUBLE\n        FFTPlanLongDoubleFFTReal fft_ref(true);\n    #else\n        #ifdef FFTSCARF_PRECISION_DOUBLE\n            FFTPlanDoubleFFTReal fft_ref(true);\n        #else\n            FFTPlanSingleFFTReal fft_ref(true);\n        #endif\n    #endif\n    FFTPlanType fft(true);\n    FFTPlanType ifft(false);\n\n    // Test transforms of sinusoids --------------------------------------------\n    boost::random::uniform_int_distribution<> binrnd(0,N/2); // For random frequency\n    boost::random::uniform_real_distribution<typename FFTPlanType::FloatType> phirnd(0.0, 2*fftscarf::pi); // For random phase\n    for(size_t b=0; b<10; ++b){\n        int binref = binrnd(rnd_engine); // Frequency\n        int ampref = N/2;            // Amplitude // TODO Randomize!\n        if(binref==0 || binref==N/2) ampref *= 2;\n        long double phiref = phirnd(rnd_engine); // Phase\n\n        // Fill an input frame\n        // Test with a simple sinusoid centered on an exact bin\n        inframe.resize(N);\n        for(int n=0; n<N; ++n)\n            inframe[n] = cosl(binref*2*fftscarf::pi*n/((long double)N) + phiref);\n        \n        // Run the tested implementation\n        fft.rfft(inframe, spec, N);\n\n        // Check the amplitude\n        long double ampmeas = std::abs(spec[binref]);\n        if(abs(ampref-ampmeas)>10*N*accthresh)\n            std::cout << \"    spec err=\" << abs(ampref-ampmeas) << \" (threshold=\" << 10*N*accthresh << \")\" << std::endl;\n        BOOST_CHECK(abs(ampref-ampmeas)<10*N*accthresh);\n\n        // Check the phase\n        long double phimeas = std::arg(spec[binref]);\n        if(abs(wrap(phiref-phimeas))>10*N*accthresh)\n            std::cout << \"    spec err=\" << abs(wrap(phiref-phimeas)) << \" (threshold=\" << 10*N*accthresh << \")\" << std::endl;\n        BOOST_CHECK(abs(wrap(phiref-phimeas))<10*N*accthresh);\n\n         // Check the zeros\n         long double spec_err = 0.0;\n         for(size_t k=0; k<=N/2; ++k)\n             if(k!=binref)\n                 spec_err += abs(spec[k])*abs(spec[k]);\n          spec_err = sqrt(spec_err/spec.size());\n          if(spec_err>10*N*accthresh)\n              std::cout << \"    spec err=\" << spec_err << \" (threshold=\" << 10*N*accthresh << \")\" << std::endl;\n          BOOST_CHECK(spec_err<10*N*accthresh);\n    }\n\n    // Test transforms of Gaussian noise ---------------------------------------\n    boost::normal_distribution<typename FFTPlanType::FloatType> rnd_normal_distrib;\n    boost::variate_generator<boost::mt19937&, \n        boost::normal_distribution<typename FFTPlanType::FloatType> > generator(rnd_engine, rnd_normal_distrib);\n\n    for(size_t b=0; b<100; ++b){\n        // Fill an input frame\n        inframe.resize(N);\n        for(int n=0; n<N; ++n)\n            inframe[n] = generator();\n\n        // Run the tested implementation\n        fft.rfft(inframe, spec, N);\n\n        if(vm.count(\"specverif\")){\n            // Run the \"reference\" implementation\n            fft_ref.rfft(inframe, spec_ref, N);\n\n            // Verify: sig->spec == specref\n            long double spec_err = 0.0;\n            for(size_t i=0; i<spec.size(); ++i)\n                spec_err += std::abs(spec_ref[i]-spec[i])*std::abs(spec_ref[i]-spec[i]);\n            spec_err = sqrt(spec_err/spec_ref.size());\n            if(spec_err>accthresh){\n                std::cout << \"    spec err=\" << spec_err << \" (threshold=\" << accthresh << \"; ref implementation: \" << fft_ref.libraryName() << \")\" << std::endl;\n                if(vm.count(\"specprint\")){\n                    std::cout << \"spec_ref=\" << spec_ref << endl;\n                    std::cout << \"spec=\" << spec << endl;\n                }\n            }\n            BOOST_CHECK(spec_err<accthresh);\n        }\n\n        // Verify: sig->spec->sig' == sig\n\n        // First reverse the spec\n        ifft.irfft(spec, outframe, N);\n\n        // Then measure relative RMS\n        long double sqerr = 0.0;\n        long double sqin = 0.0;\n        for(size_t i=0; i<inframe.size(); ++i){\n            sqerr += (inframe[i]-outframe[i])*(inframe[i]-outframe[i]);\n            sqin += inframe[i]*inframe[i];\n        }\n        long double sig_rerr = sqrt(sqerr/sqin);\n        if(sig_rerr>accthresh)\n            std::cout << \"    sig err=\" << sig_rerr << \" (threshold=\" << accthresh << \")\" << std::endl;\n        BOOST_CHECK(sig_rerr<accthresh);\n    }\n}\n\n//#ifdef FFTSCARF_FFT_DJBFFT\n//BOOST_AUTO_TEST_CASE( test_fftlibs_djbfft )\n//{\n//    test_lib<fftscarf::FFTPlanDJBFFT>();\n//}\n//#endif\n\n#ifdef FFTSCARF_FFT_OOURA\nBOOST_AUTO_TEST_CASE( test_fftlibs_ooura )\n{\n    test_lib<fftscarf::FFTPlanOoura>();\n}\n#endif\n\n#ifdef FFTSCARF_FFT_FFTREAL\n    #ifdef FFTSCARF_PRECISION_SINGLE\n    BOOST_AUTO_TEST_CASE( test_fftlibs_fftreal_single )\n    {\n        test_lib<fftscarf::FFTPlanSingleFFTReal>();\n    }\n    #endif\n    #ifdef FFTSCARF_PRECISION_DOUBLE\n    BOOST_AUTO_TEST_CASE( test_fftlibs_fftreal_double )\n    {\n        test_lib<fftscarf::FFTPlanDoubleFFTReal>();\n    }\n    #endif\n    #ifdef FFTSCARF_PRECISION_LONGDOUBLE\n    BOOST_AUTO_TEST_CASE( test_fftlibs_fftreal_longdouble )\n    {\n        test_lib<fftscarf::FFTPlanLongDoubleFFTReal>();\n    }\n    #endif\n#endif\n\n#ifdef FFTSCARF_FFT_PFFFT\n    #ifdef FFTSCARF_PRECISION_SINGLE\n    BOOST_AUTO_TEST_CASE( test_fftlibs_pffft )\n    {\n        test_lib<fftscarf::FFTPlanPFFFT>();\n    }\n    #endif\n#endif\n\n#ifdef FFTSCARF_FFT_FFTS\n    #ifdef FFTSCARF_PRECISION_SINGLE\n    BOOST_AUTO_TEST_CASE( test_fftlibs_ffts )\n    {\n        test_lib<fftscarf::FFTPlanFFTS>();\n    }\n    #endif\n#endif\n\n#ifdef FFTSCARF_FFT_FFTW3\n    #ifdef FFTSCARF_PRECISION_SINGLE\n    BOOST_AUTO_TEST_CASE( test_fftlibs_fftw3_single )\n    {\n        test_lib<fftscarf::FFTPlanSingleFFTW3>();\n    }\n    #endif\n    #ifdef FFTSCARF_PRECISION_DOUBLE\n    BOOST_AUTO_TEST_CASE( test_fftlibs_fftw3_double )\n    {\n        test_lib<fftscarf::FFTPlanDoubleFFTW3>();\n    }\n    #endif\n    #ifdef FFTSCARF_PRECISION_LONGDOUBLE\n    BOOST_AUTO_TEST_CASE( test_fftlibs_fftw3_longdouble )\n    {\n        test_lib<fftscarf::FFTPlanLongDoubleFFTW3>();\n    }\n    #endif\n#endif\n\n#ifdef FFTSCARF_FFT_IPP\n    #ifdef FFTSCARF_PRECISION_SINGLE\n    BOOST_AUTO_TEST_CASE( test_fftlibs_ipp_single)\n    {\n        test_lib<fftscarf::FFTPlanSingleIPP>();\n    }\n    #endif\n    #ifdef FFTSCARF_PRECISION_DOUBLE\n    BOOST_AUTO_TEST_CASE( test_fftlibs_ipp_double)\n    {\n        test_lib<fftscarf::FFTPlanDoubleIPP>();\n    }\n    #endif\n#endif\n\n#ifdef FFTSCARF_FFT_DFT\n    #ifdef FFTSCARF_PRECISION_SINGLE\n    BOOST_AUTO_TEST_CASE( test_fftlibs_dft_single)\n    {\n        test_lib<fftscarf::FFTPlanSingleDFT>();\n    }\n    #endif\n    #ifdef FFTSCARF_PRECISION_DOUBLE\n    BOOST_AUTO_TEST_CASE( test_fftlibs_dft_double)\n    {\n        test_lib<fftscarf::FFTPlanDoubleDFT>();\n    }\n    #endif\n    #ifdef FFTSCARF_PRECISION_LONGDOUBLE\n    BOOST_AUTO_TEST_CASE( test_fftlibs_dft_longdouble)\n    {\n        test_lib<fftscarf::FFTPlanLongDoubleDFT>();\n    }\n    #endif\n#endif\n", "meta": {"hexsha": "ef9cf26d665576169e9a42adbe11fa8982333573", "size": 8803, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_fftlibs.cpp", "max_stars_repo_name": "entn-at/gillesdegottex_fttscarf", "max_stars_repo_head_hexsha": "91251689107f53e21bf3dc4c5afae066a0bc48d7", "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": "test/test_fftlibs.cpp", "max_issues_repo_name": "entn-at/gillesdegottex_fttscarf", "max_issues_repo_head_hexsha": "91251689107f53e21bf3dc4c5afae066a0bc48d7", "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": "test/test_fftlibs.cpp", "max_forks_repo_name": "entn-at/gillesdegottex_fttscarf", "max_forks_repo_head_hexsha": "91251689107f53e21bf3dc4c5afae066a0bc48d7", "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": 32.6037037037, "max_line_length": 194, "alphanum_fraction": 0.6258093832, "num_tokens": 2412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.640635847978761, "lm_q1q2_score": 0.46035732803741314}}
{"text": "\r\n// Copyright 2006-2009 Daniel James.\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#include <boost/unordered_set.hpp>\r\n#include <boost/detail/lightweight_test.hpp>\r\n\r\n//[point_example1\r\n    struct point {\r\n        int x;\r\n        int y;\r\n    };\r\n\r\n    bool operator==(point const& p1, point const& p2)\r\n    {\r\n        return p1.x == p2.x && p1.y == p2.y;\r\n    }\r\n\r\n    struct point_hash\r\n        : std::unary_function<point, std::size_t>\r\n    {\r\n        std::size_t operator()(point const& p) const\r\n        {\r\n            std::size_t seed = 0;\r\n            boost::hash_combine(seed, p.x);\r\n            boost::hash_combine(seed, p.y);\r\n            return seed;\r\n        }\r\n    };\r\n\r\n    boost::unordered_multiset<point, point_hash> points;\r\n//]\r\n\r\nint main() {\r\n    point x[] = {{1,2}, {3,4}, {1,5}, {1,2}};\r\n    for(int i = 0; i < sizeof(x) / sizeof(point); ++i)\r\n        points.insert(x[i]);\r\n    BOOST_TEST(points.count(x[0]) == 2);\r\n    BOOST_TEST(points.count(x[1]) == 1);\r\n    point y = {10, 2};\r\n    BOOST_TEST(points.count(y) == 0);\r\n\r\n    return boost::report_errors();\r\n}\r\n", "meta": {"hexsha": "80c161631b024cb37be743deaabd1f6a4aa53e1c", "size": 1197, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/unordered/doc/src_code/point1.cpp", "max_stars_repo_name": "zyiacas/boost-doc-zh", "max_stars_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 198.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T05:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:46:46.000Z", "max_issues_repo_path": "libs/unordered/doc/src_code/point1.cpp", "max_issues_repo_name": "sdfict/boost-doc-zh", "max_issues_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/unordered/doc/src_code/point1.cpp", "max_forks_repo_name": "sdfict/boost-doc-zh", "max_forks_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 26.0217391304, "max_line_length": 80, "alphanum_fraction": 0.5505430242, "num_tokens": 330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6406358411176238, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.46035732310703836}}
{"text": "#pragma once\n#include <boost/regex/v4/regex.hpp>\n#include \"ArithmeticExpression.hpp\"\n\nnamespace string_util\n{\n\tbool is_number(std::string str)\n\t{\n\t\treturn boost::regex_match(str, ArithmeticExpression::match_info, ArithmeticExpression::is_number_regex);\n\t}\n\n\tbool is_digit(char c)\n\t{\n\t\treturn c >= '0' && c <= '9';\n\t}\n\n\tbool is_number_char(char c)\n\t{\n\t\treturn (c >= '0' && c <= '9') || c == '.';\n\t}\n\n\tint is_letter(char c)\n\t{\n\t\treturn (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');\n\t}\n\n\tint is_text_operator(std::string str)\n\t{\n\t\tfor (unsigned i = 0; i < ArithmeticExpression::text_operator_dictionary.size(); i++)\n\t\t{\n\t\t\tfor (unsigned j = 0; j < ArithmeticExpression::text_operator_dictionary[i].size(); j++)\n\t\t\t{\n\t\t\t\tif (ArithmeticExpression::text_operator_dictionary[i][j] == str)\n\t\t\t\t{\n\t\t\t\t\treturn i + 1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn 0;\n\t}\n\n\tint is_operator(char c)\n\t{\n\t\tfor (unsigned i = 0; i < ArithmeticExpression::char_operator.size(); i++)\n\t\t{\n\t\t\tif (c == ArithmeticExpression::char_operator[i]) return 1;\n\t\t}\n\t\treturn 0;\n\t}\n\n\tvoid to_lower_case(std::string& str)\n\t{\n\t\tfor (unsigned i = 0; i < str.size(); i++)\n\t\t{\n\t\t\tif (str[i] >= 'A' && str[i] < 'Z')\n\t\t\t{\n\t\t\t\tstr[i] += 32;\n\t\t\t}\n\t\t}\n\t}\n\tint is_parenthesis(char c)\n\t{\n\t\treturn c == '(' || c == ')';\n\t}\n\tint arity(std::string str)\n\t{\n\t\tint is_t_operator = is_text_operator(str);\n\t\tif (is_t_operator != 0)\n\t\t\treturn is_t_operator;\n\t\tif (is_operator(str[0]))\n\t\t\treturn 1;\n\t\treturn 0;\n\t}\n\n\tint precedence(std::string& str)\n\t{\n\t\tif (str == \"^\") return 5;\n\t\telse if (str == \"*\" || str == \"/\" || str == \"%\") return 4;\n\t\telse if (str == \"+\" || str == \"-\") return 3;\n\t\telse if (str == \"&\") return 2;\n\t\telse if (str == \"|\") return 1;\n\t\treturn 0;\n\t}\n}", "meta": {"hexsha": "0577cc0f3711afdc2a258b9ee3f202a7d2c2ef34", "size": 1697, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ArithmeticEvalulator/HedronLoggerTestBranch/string_util.hpp", "max_stars_repo_name": "Gabriel-Baril/arithmetic-evaluator", "max_stars_repo_head_hexsha": "171acdbf5ebde61b486833f64c8e1d48e5816540", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ArithmeticEvalulator/HedronLoggerTestBranch/string_util.hpp", "max_issues_repo_name": "Gabriel-Baril/arithmetic-evaluator", "max_issues_repo_head_hexsha": "171acdbf5ebde61b486833f64c8e1d48e5816540", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ArithmeticEvalulator/HedronLoggerTestBranch/string_util.hpp", "max_forks_repo_name": "Gabriel-Baril/arithmetic-evaluator", "max_forks_repo_head_hexsha": "171acdbf5ebde61b486833f64c8e1d48e5816540", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.2023809524, "max_line_length": 106, "alphanum_fraction": 0.5757218621, "num_tokens": 544, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.46035732310703836}}
{"text": "/*\n * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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#define BOOST_TEST_MAIN\n\n#define BOOST_TEST_MODULE bse_test\n\n// Third party includes\n#include <boost/test/unit_test.hpp>\n\n// VOTCA includes\n#include <votca/tools/eigenio_matrixmarket.h>\n\n// Local VOTCA includes\n#include \"votca/xtp/bse.h\"\n#include \"votca/xtp/convergenceacc.h\"\n#include \"votca/xtp/qmfragment.h\"\n#include <libint2/initialize.h>\n#include <votca/tools/eigenio_matrixmarket.h>\nusing namespace votca::xtp;\nusing namespace std;\n\nBOOST_AUTO_TEST_SUITE(bse_test)\n\nBOOST_AUTO_TEST_CASE(bse_hamiltonian) {\n  libint2::initialize();\n  Orbitals orbitals;\n  orbitals.QMAtoms().LoadFromFile(std::string(XTP_TEST_DATA_FOLDER) +\n                                  \"/bse/molecule.xyz\");\n  BasisSet basis;\n  basis.Load(std::string(XTP_TEST_DATA_FOLDER) + \"/bse/3-21G.xml\");\n  orbitals.SetupDftBasis(std::string(XTP_TEST_DATA_FOLDER) + \"/bse/3-21G.xml\");\n  AOBasis aobasis;\n  aobasis.Fill(basis, orbitals.QMAtoms());\n\n  orbitals.setNumberOfOccupiedLevels(4);\n  Eigen::MatrixXd& MOs = orbitals.MOs().eigenvectors();\n  MOs = votca::tools::EigenIO_MatrixMarket::ReadMatrix(\n      std::string(XTP_TEST_DATA_FOLDER) + \"/bse/MOs.mm\");\n\n  Eigen::MatrixXd Hqp = votca::tools::EigenIO_MatrixMarket::ReadMatrix(\n      std::string(XTP_TEST_DATA_FOLDER) + \"/bse/Hqp.mm\");\n\n  Eigen::VectorXd& mo_energy = orbitals.MOs().eigenvalues();\n  mo_energy = votca::tools::EigenIO_MatrixMarket::ReadVector(\n      std::string(XTP_TEST_DATA_FOLDER) + \"/bse/MO_energies.mm\");\n\n  Logger log;\n  TCMatrix_gwbse Mmn;\n  Mmn.Initialize(aobasis.AOBasisSize(), 0, 16, 0, 16);\n  Mmn.Fill(aobasis, aobasis, MOs);\n\n  BSE::options opt;\n  opt.cmax = 16;\n  opt.rpamax = 16;\n  opt.rpamin = 0;\n  opt.vmin = 0;\n  opt.nmax = 3;\n  opt.min_print_weight = 0.1;\n  opt.useTDA = true;\n  opt.homo = 4;\n  opt.qpmin = 0;\n  opt.qpmax = 16;\n  opt.max_dyn_iter = 10;\n  opt.dyn_tolerance = 1e-5;\n  opt.davidson_correction = \"DPR\";\n  opt.davidson_tolerance = \"lapack\";\n  opt.davidson_update = \"safe\";\n  opt.davidson_maxiter = 50;\n\n  orbitals.setBSEindices(0, 16);\n\n  BSE bse = BSE(log, Mmn);\n  orbitals.setTDAApprox(true);\n  orbitals.RPAInputEnergies() = Hqp.diagonal();\n\n  ////////////////////////////////////////////////////////\n  // TDA Singlet davidson\n  ////////////////////////////////////////////////////////\n\n  // reference energy singlet, no offdiagonals in Hqp\n  Eigen::VectorXd se_nooffdiag_ref =\n      votca::tools::EigenIO_MatrixMarket::ReadVector(\n          std::string(XTP_TEST_DATA_FOLDER) + \"/bse/singlets_nooffdiag_tda.mm\");\n\n  // reference singlet coefficients, no offdiagonals in Hqp\n  Eigen::MatrixXd spsi_nooffdiag_ref =\n      votca::tools::EigenIO_MatrixMarket::ReadMatrix(\n          std::string(XTP_TEST_DATA_FOLDER) +\n          \"/bse/singlets_psi_nooffdiag_tda.mm\");\n\n  // no offdiagonals\n  opt.use_Hqp_offdiag = false;\n  bse.configure(opt, orbitals.RPAInputEnergies(), Hqp);\n\n  bse.Solve_singlets(orbitals);\n  std::vector<QMFragment<BSE_Population> > fragments;\n  bse.Analyze_singlets(fragments, orbitals);\n  bool check_se_nooffdiag =\n      se_nooffdiag_ref.isApprox(orbitals.BSESinglets().eigenvalues(), 0.001);\n  if (!check_se_nooffdiag) {\n    cout << \"Singlets energy without Hqp offdiag\" << endl;\n    cout << orbitals.BSESinglets().eigenvalues() << endl;\n    cout << \"Singlets energy without Hqp offdiag ref\" << endl;\n    cout << se_nooffdiag_ref << endl;\n  }\n  BOOST_CHECK_EQUAL(check_se_nooffdiag, true);\n  Eigen::MatrixXd projection_nooffdiag =\n      spsi_nooffdiag_ref.transpose() * orbitals.BSESinglets().eigenvectors();\n  Eigen::VectorXd norms_nooffdiag = projection_nooffdiag.colwise().norm();\n  bool check_spsi_nooffdiag = norms_nooffdiag.isApproxToConstant(1, 1e-5);\n  if (!check_spsi_nooffdiag) {\n    cout << \"Norms\" << norms_nooffdiag << endl;\n    cout << \"Singlets psi without Hqp offdiag\" << endl;\n    cout << orbitals.BSESinglets().eigenvectors() << endl;\n    cout << \"Singlets psi without Hqp offdiag ref\" << endl;\n    cout << spsi_nooffdiag_ref << endl;\n  }\n  BOOST_CHECK_EQUAL(check_spsi_nooffdiag, true);\n\n  // with Hqp offdiags\n  opt.use_Hqp_offdiag = true;\n  bse.configure(opt, orbitals.RPAInputEnergies(), Hqp);\n\n  // reference energy\n  Eigen::VectorXd se_ref = votca::tools::EigenIO_MatrixMarket::ReadVector(\n      std::string(XTP_TEST_DATA_FOLDER) + \"/bse/singlets_tda.mm\");\n  // reference coefficients\n  Eigen::MatrixXd spsi_ref = votca::tools::EigenIO_MatrixMarket::ReadMatrix(\n      std::string(XTP_TEST_DATA_FOLDER) + \"/bse/singlets_psi_tda.mm\");\n\n  // Hqp unchanged\n  bool check_hqp_unchanged = Hqp.isApprox(bse.getHqp(), 0.001);\n  if (!check_hqp_unchanged) {\n    cout << \"unchanged Hqp\" << endl;\n    cout << bse.getHqp() << endl;\n    cout << \"unchanged Hqp ref\" << endl;\n    cout << Hqp << endl;\n  }\n  BOOST_CHECK_EQUAL(check_hqp_unchanged, true);\n\n  bse.Solve_singlets(orbitals);\n  bool check_se = se_ref.isApprox(orbitals.BSESinglets().eigenvalues(), 0.001);\n  if (!check_se) {\n    cout << \"Singlets energy\" << endl;\n    cout << orbitals.BSESinglets().eigenvalues() << endl;\n    cout << \"Singlets energy ref\" << endl;\n    cout << se_ref << endl;\n  }\n  BOOST_CHECK_EQUAL(check_se, true);\n  Eigen::MatrixXd projection =\n      spsi_ref.transpose() * orbitals.BSESinglets().eigenvectors();\n  Eigen::VectorXd norms = projection.colwise().norm();\n  bool check_spsi = norms.isApproxToConstant(1, 1e-5);\n  if (!check_spsi) {\n    cout << \"Norms\" << norms << endl;\n    cout << \"Singlets psi\" << endl;\n    cout << orbitals.BSESinglets().eigenvectors() << endl;\n    cout << \"Singlets psi ref\" << endl;\n    cout << spsi_ref << endl;\n  }\n  BOOST_CHECK_EQUAL(check_spsi, true);\n\n  // singlets dynamical screening TDA\n  bse.Perturbative_DynamicalScreening(QMStateType(QMStateType::Singlet),\n                                      orbitals);\n\n  Eigen::VectorXd se_dyn_tda_ref =\n      votca::tools::EigenIO_MatrixMarket::ReadVector(\n          std::string(XTP_TEST_DATA_FOLDER) + \"/bse/singlets_dynamic_TDA.mm\");\n  bool check_se_dyn_tda =\n      se_dyn_tda_ref.isApprox(orbitals.BSESinglets_dynamic(), 0.005);\n  if (!check_se_dyn_tda) {\n    cout << \"Singlet energies dyn TDA\" << endl;\n    cout << orbitals.BSESinglets_dynamic() << endl;\n    cout << \"Singlet energies dyn TDA ref\" << endl;\n    cout << se_dyn_tda_ref << endl;\n  }\n  BOOST_CHECK_EQUAL(check_se_dyn_tda, true);\n\n  ////////////////////////////////////////////////////////\n  // BTDA Singlet Davidson\n  ////////////////////////////////////////////////////////\n\n  // reference energy\n  Eigen::VectorXd se_ref_btda = votca::tools::EigenIO_MatrixMarket::ReadVector(\n      std::string(XTP_TEST_DATA_FOLDER) + \"/bse/singlets_btda.mm\");\n\n  // reference coefficients\n  Eigen::MatrixXd spsi_ref_btda =\n      votca::tools::EigenIO_MatrixMarket::ReadMatrix(\n          std::string(XTP_TEST_DATA_FOLDER) + \"/bse/singlets_psi_btda.mm\");\n\n  // // reference coefficients AR\n  Eigen::MatrixXd spsi_ref_btda_AR =\n      votca::tools::EigenIO_MatrixMarket::ReadMatrix(\n          std::string(XTP_TEST_DATA_FOLDER) + \"/bse/singlets_psi_AR_btda.mm\");\n\n  opt.nmax = 3;\n  opt.useTDA = false;\n  bse.configure(opt, orbitals.RPAInputEnergies(), Hqp);\n  orbitals.setTDAApprox(false);\n  bse.Solve_singlets(orbitals);\n  bse.Analyze_singlets(fragments, orbitals);\n  // std::cout<<log;\n\n  orbitals.BSESinglets().eigenvectors().colwise().normalize();\n  orbitals.BSESinglets().eigenvectors2().colwise().normalize();\n\n  Eigen::MatrixXd spsi_ref_btda_normalized = spsi_ref_btda;\n  Eigen::MatrixXd spsi_ref_btda_AR_normalized = spsi_ref_btda_AR;\n  spsi_ref_btda_normalized.colwise().normalize();\n  spsi_ref_btda_AR_normalized.colwise().normalize();\n\n  bool check_se_btda =\n      se_ref_btda.isApprox(orbitals.BSESinglets().eigenvalues(), 0.001);\n  if (!check_se_btda) {\n    cout << \"Singlets energy BTDA\" << endl;\n    cout << orbitals.BSESinglets().eigenvalues() << endl;\n    cout << \"Singlets energy BTDA ref\" << endl;\n    cout << se_ref_btda << endl;\n  }\n  BOOST_CHECK_EQUAL(check_se_btda, true);\n\n  projection = spsi_ref_btda_normalized.transpose() *\n               orbitals.BSESinglets().eigenvectors();\n  norms = projection.colwise().norm();\n  bool check_spsi_btda = norms.isApproxToConstant(1, 1e-5);\n\n  if (!check_spsi_btda) {\n    cout << \"Norms\" << norms << endl;\n    cout << \"Singlets psi BTDA\" << endl;\n    cout << orbitals.BSESinglets().eigenvectors() << endl;\n    cout << \"Singlets psi BTDA ref\" << endl;\n    cout << spsi_ref_btda << endl;\n  }\n  BOOST_CHECK_EQUAL(check_spsi_btda, true);\n\n  orbitals.BSESinglets().eigenvectors2().colwise().normalize();\n  projection = spsi_ref_btda_AR_normalized.transpose() *\n               orbitals.BSESinglets().eigenvectors2();\n  norms = projection.colwise().norm();\n  bool check_spsi_btda_AR = norms.isApproxToConstant(1, 1e-5);\n\n  // check_spsi_AR = true;\n  if (!check_spsi_btda_AR) {\n    cout << \"Norms\" << norms << endl;\n    cout << \"Singlets psi BTDA AR\" << endl;\n    cout << orbitals.BSESinglets().eigenvectors2() << endl;\n    cout << \"Singlets psi BTDA AR ref\" << endl;\n    cout << spsi_ref_btda_AR << endl;\n  }\n  BOOST_CHECK_EQUAL(check_spsi_btda_AR, true);\n\n  // singlets full BSE dynamical screening\n  bse.Perturbative_DynamicalScreening(QMStateType(QMStateType::Singlet),\n                                      orbitals);\n\n  Eigen::VectorXd se_dyn_full_ref =\n      votca::tools::EigenIO_MatrixMarket::ReadVector(\n          std::string(XTP_TEST_DATA_FOLDER) + \"/bse/singlets_dynamic_full.mm\");\n  bool check_se_dyn_full =\n      se_dyn_full_ref.isApprox(orbitals.BSESinglets_dynamic(), 0.05);\n  if (!check_se_dyn_full) {\n    cout << \"Singlet energies dyn full BSE\" << endl;\n    cout << orbitals.BSESinglets_dynamic() << endl;\n    cout << \"Singlet energies dyn full BSE ref\" << endl;\n    cout << se_dyn_full_ref << endl;\n  }\n  BOOST_CHECK_EQUAL(check_se_dyn_full, true);\n\n  ////////////////////////////////////////////////////////\n  // TDA Triplet davidson\n  ////////////////////////////////////////////////////////\n\n  // reference energy\n  opt.nmax = 1;\n  Eigen::VectorXd te_ref = votca::tools::EigenIO_MatrixMarket::ReadVector(\n      std::string(XTP_TEST_DATA_FOLDER) + \"/bse/triplets_tda.mm\");\n\n  // reference coefficients\n  Eigen::MatrixXd tpsi_ref = votca::tools::EigenIO_MatrixMarket::ReadMatrix(\n      std::string(XTP_TEST_DATA_FOLDER) + \"/bse/triplets_psi_tda.mm\");\n\n  orbitals.setTDAApprox(true);\n  opt.useTDA = true;\n\n  bse.configure(opt, orbitals.RPAInputEnergies(), Hqp);\n  bse.Solve_triplets(orbitals);\n  std::vector<QMFragment<BSE_Population> > triplets;\n  bse.Analyze_triplets(triplets, orbitals);\n\n  bool check_te = te_ref.isApprox(orbitals.BSETriplets().eigenvalues(), 0.001);\n  if (!check_te) {\n    cout << \"Triplet energy\" << endl;\n    cout << orbitals.BSETriplets().eigenvalues() << endl;\n    cout << \"Triplet energy ref\" << endl;\n    cout << te_ref << endl;\n  }\n  BOOST_CHECK_EQUAL(check_te, true);\n\n  bool check_tpsi = tpsi_ref.cwiseAbs2().isApprox(\n      orbitals.BSETriplets().eigenvectors().cwiseAbs2(), 0.1);\n  check_tpsi = true;\n  if (!check_tpsi) {\n    cout << \"Triplet psi\" << endl;\n    cout << orbitals.BSETriplets().eigenvectors() << endl;\n    cout << \"Triplet ref\" << endl;\n    cout << tpsi_ref << endl;\n  }\n  BOOST_CHECK_EQUAL(check_tpsi, true);\n\n  // triplets dynamical screening TDA\n  bse.Perturbative_DynamicalScreening(QMStateType(QMStateType::Triplet),\n                                      orbitals);\n\n  Eigen::VectorXd te_dyn_tda_ref =\n      votca::tools::EigenIO_MatrixMarket::ReadVector(\n          std::string(XTP_TEST_DATA_FOLDER) + \"/bse/triplets_dynamic_TDA.mm\");\n  bool check_te_dyn_tda =\n      te_dyn_tda_ref.isApprox(orbitals.BSETriplets_dynamic(), 0.001);\n  if (!check_te_dyn_tda) {\n    cout << \"Triplet energies dyn TDA\" << endl;\n    cout << orbitals.BSETriplets_dynamic() << endl;\n    cout << \"Triplet energies dyn TDA ref\" << endl;\n    cout << te_dyn_tda_ref << endl;\n  }\n  BOOST_CHECK_EQUAL(check_te_dyn_tda, true);\n\n  // Cutout Hamiltonian\n  Eigen::MatrixXd Hqp_cut_ref = votca::tools::EigenIO_MatrixMarket::ReadMatrix(\n      std::string(XTP_TEST_DATA_FOLDER) + \"/bse/Hqp_cut.mm\");\n  // Hqp cut\n  opt.cmax = 15;\n  opt.vmin = 1;\n  bse.configure(opt, orbitals.RPAInputEnergies(), Hqp);\n  bool check_hqp_cut = Hqp_cut_ref.isApprox(bse.getHqp(), 0.001);\n  if (!check_hqp_cut) {\n    cout << \"cut Hqp\" << endl;\n    cout << bse.getHqp() << endl;\n    cout << \"cut Hqp ref\" << endl;\n    cout << Hqp_cut_ref << endl;\n  }\n  BOOST_CHECK_EQUAL(check_hqp_cut, true);\n\n  // Hqp extend\n  opt.cmax = 16;\n  opt.vmin = 0;\n  opt.qpmin = 1;\n  opt.qpmax = 15;\n  BSE bse2 = BSE(log, Mmn);\n  bse2.configure(opt, orbitals.RPAInputEnergies(), Hqp_cut_ref);\n  Eigen::MatrixXd Hqp_extended_ref =\n      votca::tools::EigenIO_MatrixMarket::ReadMatrix(\n          std::string(XTP_TEST_DATA_FOLDER) + \"/bse/Hqp_extended.mm\");\n  bool check_hqp_extended = Hqp_extended_ref.isApprox(bse2.getHqp(), 0.001);\n  if (!check_hqp_extended) {\n    cout << \"extended Hqp\" << endl;\n    cout << bse2.getHqp() << endl;\n    cout << \"extended Hqp ref\" << endl;\n    cout << Hqp_extended_ref << endl;\n  }\n  BOOST_CHECK_EQUAL(check_hqp_extended, true);\n  libint2::finalize();\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "b190a4ac1d50475eaf3fe02e0dbc52d4290e5648", "size": 13659, "ext": "cc", "lang": "C++", "max_stars_repo_path": "xtp/src/tests/test_bse.cc", "max_stars_repo_name": "ipelupessy/votca", "max_stars_repo_head_hexsha": "b0daafb6f503e6a55c878172ef9d68c6639da9e0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "xtp/src/tests/test_bse.cc", "max_issues_repo_name": "ipelupessy/votca", "max_issues_repo_head_hexsha": "b0daafb6f503e6a55c878172ef9d68c6639da9e0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "xtp/src/tests/test_bse.cc", "max_forks_repo_name": "ipelupessy/votca", "max_forks_repo_head_hexsha": "b0daafb6f503e6a55c878172ef9d68c6639da9e0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.9447368421, "max_line_length": 80, "alphanum_fraction": 0.6752324475, "num_tokens": 4006, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435083355187, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.46035305210048005}}
{"text": "#include \"msl_raptor_backend.h\"\n#include \"opencv2/highgui/highgui.hpp\"\n#include \"opencv2/imgproc/imgproc.hpp\"\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <chrono>\n#include <iostream>\n#include <opencv2/core/eigen.hpp>\n#include <type_traits>\n\nint main(int argc, char **argv)\n{\n    // Define if we want to used an aligned bb (4 parameters) or an angled one (5 parameters).\n    const bool aligned_bb = false;\n\n    // Define camera parameters (camera matrix, extrinsics, distorsion coefficients) and create camera params object.\n    std::vector<float> cam_mat{304.7262878417969, 0.0, 214.2415313720703,\n                               0.0, 304.7262878417969, 121.70726013183594,\n                               0.0, 0.0, 1.0};\n    std::vector<float> rvec(3, 0.0);\n    std::vector<float> tvec(3, 0.0);\n    std::vector<float> dist_coeffs(4, 0);\n    msl_raptor_backend::CameraParams cam_params(cam_mat, rvec, tvec, dist_coeffs);\n\n    // Define object parameters (UKF initial covariances, process noise, and measurement noise, dimensions) and create object params object.\n    std::vector<double> sigma{0.0000000000001, 0.000001, 0.000001,  // position\n                              0.00000000000005, 0.000005, 0.000005, //  linear velocity\n                              0.000003, 0.000003, 0.000003,         // angular velocity\n                              0.000005, 0.000005, 0.00005};         // orientation\n\n    std::vector<double> process_noise{0.002, 0.0002, 0.0002,     // position\n                                      0.0001, 0.0000001, 0.0001, // linear velocity\n                                      0.0006, 0.000006, 0.00006, // angular velocity\n                                      0.00001, 0.0001, 0.00001}; // orientation\n\n    // measurement vector for angle bb is center x, center y, width, height, angle.\n    std::vector<double> meas_noise{1, 1, 2, 1, 0.5};\n\n    // Parameters for optimisation-based pose estimation from bb\n    double momentum = 0.9;                                         // Momentum parameter\n    int max_steps = 500;                                           // Maximum number of steps\n    int conv_steps = 4;                                            // Steps to check convergence\n    int period_lower_lr = 20;                                      // How often to reduce learning rate\n    std::vector<msl_raptor_backend::PoseVec> bb_init_pose_guesses; // Contains position vector and quaternion for orientation\n    // Add a grid of initial guesses\n    for (double i = -2; i < 2; i += 1)\n    {\n        for (double j = -2; j < 2; j += 1)\n        {\n            for (double k = 2; k < 8; k += 1)\n            {\n                bb_init_pose_guesses.push_back(msl_raptor_backend::PoseVec(i, j, k, 0, 0, 0, 1)); // Position vector and orientation quaternion\n                // std::cout << msl_raptor_backend::PoseVec(i, j, k, 0, 0, 0, 1) << std::endl;\n            }\n        }\n    }\n    std::vector<double> bb_init_step_size{0.001, 0.001, 0.01, 0.001, 0.001, 0.001};    // Step sizes along position and Euler axis for orientation\n    std::vector<double> bb_init_lr{0.0005, 0.0005, 0.0001, 0.00005, 0.00005, 0.00005}; // Step sizes for gradient approximation along position and Euler axis for orientation\n    msl_raptor_backend::ObjPoseInitParams obj_pose_init_params(bb_init_step_size, bb_init_lr, bb_init_pose_guesses, momentum, max_steps, conv_steps, period_lower_lr);\n\n    // Provides width, height and length of object in meters, from which corners of a 3D box are used to approximate the object's shape.\n    msl_raptor_backend::ObjParams obj_params(0.3, 0.2, 0.5, sigma, process_noise, meas_noise, obj_pose_init_params);\n\n    // Initial state, here places the object 5 meters away in front with no velocity.\n    MSLRaptorUKF<aligned_bb>::StateVec true_state, state_approx_heuristic, state_approx_optim;\n    true_state << 0, 0, 5.2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0;\n    true_state.quat(0).setIdentity();\n\n    // Initialize MSL-RAPTOR back-end UKF using set object parameters, camera parameters, and true state.\n    MSLRaptorUKF<aligned_bb> msl_raptor_ukf(obj_params, cam_params, true_state);\n    std::cout << \"True pose is \" << std::endl\n              << msl_raptor_ukf.stateToPose(true_state) << std::endl\n              << std::endl;\n\n    // Check the measurement process applied to the current UKF state with no input, which returns a bounding box prediction.\n    MSLRaptorUKF<aligned_bb>::MeasureVec m = msl_raptor_ukf.H(true_state, Eigen::Affine3d());\n\n    std::cout << \"Measurement at true state\" << std::endl\n              << m << std::endl\n              << std::endl;\n\n    // Example of approximating a state from a 2D bounding box with heuristics\n    state_approx_heuristic = msl_raptor_ukf.approxStateFromBbHeuristic(m);\n    std::cout << \"Pose approximated only from 2D bounding box with a heuristic \" << std::endl\n              << msl_raptor_ukf.stateToPose(state_approx_heuristic) << std::endl\n              << std::endl;\n\n    // Example of approximating a state from a 2D bounding box with optimisation\n    double optim_error;\n    std::tie(optim_error, state_approx_optim) = msl_raptor_ukf.approxStatePoseOptim(m);\n    std::cout << \"Pose approximated only from 2D bounding box with optimisation (err \" << optim_error << \") \"\n              << std::endl\n              << msl_raptor_ukf.stateToPose(state_approx_optim) << std::endl\n              << std::endl;\n\n    // Modify the measurement width to make it appear closer\n    m(2) *= 4;\n    m(3) *= 4;\n    std::cout << \"What if we observed a bounding box with a larger size. This should indicate a closer object.\" << std::endl\n              << m << std::endl\n              << std::endl;\n\n    // Update the UKF with the modified measurement, which should make the pose appear ...\n    msl_raptor_ukf.update(0.03, m);\n\n    // Check the new state\n    std::cout << \"Predicted pose after measurement update is \" << std::endl\n              << msl_raptor_ukf.stateToPose(msl_raptor_ukf.getState()) << \"\\n\\n\";\n\n    // Create a fake input (could be from odometry in practice) \n    Eigen::Affine3d input = Eigen::AngleAxisd(0.05, Eigen::Vector3d::UnitZ()) *\n                            Eigen::Translation3d(0.0, 0.0, 0.2);\n    std::cout << \"What if we apply a translation and orientation input with the measurement \\n \\n\";\n\n    // Update the UKF with the modified measurement and fake input\n    msl_raptor_ukf.update(0.03, m, input);\n\n    // Check the new state\n    std::cout << \"The new pose is \" << std::endl\n              << msl_raptor_ukf.stateToPose(msl_raptor_ukf.getState()) << \"\\n\\n\";\n}\n", "meta": {"hexsha": "3fa39cc2e5f0e9dcd5a542cf5162bbcc9a6beb61", "size": 6576, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "msl-raptor-example.cpp", "max_stars_repo_name": "bramtoula/MSL-RAPTOR-Backend", "max_stars_repo_head_hexsha": "3014a6681119f9e48bc7c591d2ed7c53a00c65fd", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "msl-raptor-example.cpp", "max_issues_repo_name": "bramtoula/MSL-RAPTOR-Backend", "max_issues_repo_head_hexsha": "3014a6681119f9e48bc7c591d2ed7c53a00c65fd", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "msl-raptor-example.cpp", "max_forks_repo_name": "bramtoula/MSL-RAPTOR-Backend", "max_forks_repo_head_hexsha": "3014a6681119f9e48bc7c591d2ed7c53a00c65fd", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 53.9016393443, "max_line_length": 173, "alphanum_fraction": 0.6269768856, "num_tokens": 1847, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.460353045840053}}
{"text": "/*\n * Copyright 2012-2019 CNRS-UM LIRMM, CNRS-AIST JRL\n */\n\n// check memory allocation in some method\n#define EIGEN_RUNTIME_NO_MALLOC\n\n// includes\n// std\n#include <iostream>\n\n// boost\n#define BOOST_TEST_MODULE Dynamics\n#include <boost/math/constants/constants.hpp>\n#include <boost/test/unit_test.hpp>\n\n// SpaceVecAlg\n#include <SpaceVecAlg/SpaceVecAlg>\n\n// RBDyn\n#include \"RBDyn/Body.h\"\n#include \"RBDyn/FD.h\"\n#include \"RBDyn/FK.h\"\n#include \"RBDyn/FV.h\"\n#include \"RBDyn/ID.h\"\n#include \"RBDyn/Joint.h\"\n#include \"RBDyn/MultiBody.h\"\n#include \"RBDyn/MultiBodyConfig.h\"\n#include \"RBDyn/MultiBodyGraph.h\"\n\n// arm\n#include \"XYZSarm.h\"\n\nconst double TOL = 0.0000001;\n\nBOOST_AUTO_TEST_CASE(OneBody)\n{\n  using namespace Eigen;\n  using namespace sva;\n  using namespace rbd;\n  namespace cst = boost::math::constants;\n\n  double mass = 1.;\n  Matrix3d I = Matrix3d::Identity();\n  Vector3d h = Vector3d(0., 0.5, 0.);\n\n  RBInertiad rbi(mass, h, I);\n\n  Body b0(rbi, \"b0\");\n  Body b1(rbi, \"b1\");\n\n  Joint j0(Joint::RevX, true, \"j0\");\n\n  MultiBodyGraph mbg;\n\n  mbg.addBody(b0);\n  mbg.addBody(b1);\n\n  mbg.addJoint(j0);\n\n  mbg.linkBodies(\"b0\", PTransformd::Identity(), \"b1\", PTransformd::Identity(), \"j0\");\n\n  MultiBody mb = mbg.makeMultiBody(\"b0\", true);\n\n  MultiBodyConfig mbc(mb);\n  mbc.zero(mb);\n\n  forwardKinematics(mb, mbc);\n  forwardVelocity(mb, mbc);\n\n  InverseDynamics id(mb);\n  id.inverseDynamics(mb, mbc);\n\n  BOOST_CHECK_EQUAL(int(id.f().size()), mb.nrBodies());\n  BOOST_CHECK_SMALL(mbc.jointTorque[1][0], TOL);\n\n  mbc.q = {{}, {cst::pi<double>()}};\n  forwardKinematics(mb, mbc);\n  forwardVelocity(mb, mbc);\n  id.inverseDynamics(mb, mbc);\n\n  std::cout << std::endl;\n  BOOST_CHECK_SMALL(mbc.jointTorque[1][0], TOL);\n\n  mbc.q = {{}, {cst::pi<double>() / 2.}};\n  forwardKinematics(mb, mbc);\n  forwardVelocity(mb, mbc);\n  id.inverseDynamics(mb, mbc);\n\n  double torque = Vector3d(0., 0., 0.5).cross(Vector3d(0., 9.81, 0.))(0);\n  BOOST_CHECK_SMALL(std::abs(torque - mbc.jointTorque[1][0]), TOL);\n\n  MultiBodyConfig mbc2 = mbc;\n  mbc2.gravity = Vector3d::Zero();\n  MotionVecd gravity(Vector3d::Zero(), Vector3d(0., 9.81, 0.));\n  ForceVecd gravityB1 = mb.body(0).inertia() * (mbc2.bodyPosW[0] * gravity);\n  ForceVecd gravityB2 = mb.body(1).inertia() * (mbc2.bodyPosW[1] * gravity);\n  mbc2.force = {gravityB1, gravityB2};\n  id.inverseDynamics(mb, mbc2);\n\n  torque = Vector3d(0., 0., 0.5).cross(Vector3d(0., -9.81, 0.))(0);\n  BOOST_CHECK_SMALL(std::abs(torque - mbc2.jointTorque[1][0]), TOL);\n}\n\nvoid makeRandomVecVec(std::vector<std::vector<double>> & vec)\n{\n  typedef Eigen::Matrix<double, 1, 1> EScalar;\n  for(auto & v1 : vec)\n    for(auto & v2 : v1) v2 = EScalar::Random()(0) * 10.;\n}\n\nvoid normalizeQuat(std::vector<double> & q)\n{\n  Eigen::Vector4d qv(q[0], q[1], q[2], q[3]);\n  double norm = qv.norm();\n  for(int i = 0; i < 4; ++i) q[i] /= norm;\n}\n\nvoid makeRandomConfig(rbd::MultiBodyConfig & mbc)\n{\n  makeRandomVecVec(mbc.q);\n  makeRandomVecVec(mbc.alpha);\n  makeRandomVecVec(mbc.alphaD);\n  makeRandomVecVec(mbc.jointTorque);\n\n  for(std::size_t i = 0; i < mbc.q.size(); ++i)\n  {\n    if(mbc.q[i].size() == 4 || mbc.q[i].size() == 7)\n    {\n      normalizeQuat(mbc.q[i]);\n    }\n  }\n}\n\nEigen::MatrixXd makeHFromID(const rbd::MultiBody & mb,\n                            const rbd::MultiBodyConfig & mbc,\n                            rbd::InverseDynamics & id,\n                            const Eigen::VectorXd & C)\n{\n  using namespace Eigen;\n  using namespace sva;\n  using namespace rbd;\n\n  Eigen::MatrixXd H(mb.nrDof(), mb.nrDof());\n  VectorXd Hd(mb.nrDof());\n\n  MultiBodyConfig mbcd(mbc);\n  for(auto & v1 : mbcd.alphaD)\n  {\n    for(auto & v2 : v1)\n    {\n      v2 = 0.;\n    }\n  }\n\n  int col = 0;\n  for(int i = 0; i < mb.nrJoints(); ++i)\n  {\n    for(int j = 0; j < mb.joint(i).dof(); ++j)\n    {\n      mbcd.alphaD[i][j] = 1.;\n\n      id.inverseDynamics(mb, mbcd);\n\n      int dof = 0;\n      for(auto & v1 : mbcd.jointTorque)\n      {\n        for(auto & v2 : v1)\n        {\n          Hd(dof) = v2;\n          ++dof;\n        }\n      }\n\n      H.col(col) = Hd - C;\n\n      mbcd.alphaD[i][j] = 0.;\n      ++col;\n    }\n  }\n\n  return H;\n}\n\nBOOST_AUTO_TEST_CASE(IDvsFDFixed)\n{\n  using namespace Eigen;\n  using namespace sva;\n  using namespace rbd;\n  namespace cst = boost::math::constants;\n\n  typedef Matrix<double, 1, 1> EScalar;\n\n  RBInertiad I0(EScalar::Random()(0) * 10., Vector3d::Random() * 10., Matrix3d::Random().triangularView<Lower>());\n  RBInertiad I1(EScalar::Random()(0) * 10., Vector3d::Random() * 10., Matrix3d::Random().triangularView<Lower>());\n  RBInertiad I2(EScalar::Random()(0) * 10., Vector3d::Random() * 10., Matrix3d::Random().triangularView<Lower>());\n  RBInertiad I3(EScalar::Random()(0) * 10., Vector3d::Random() * 10., Matrix3d::Random().triangularView<Lower>());\n\n  Body b0(I0, \"b0\");\n  Body b1(I1, \"b1\");\n  Body b2(I2, \"b2\");\n  Body b3(I3, \"b3\");\n\n  Joint j0 = Joint(Joint::Spherical, true, \"j0\");\n  Joint j1 = Joint(Joint::RevX, true, \"j1\");\n  Joint j2 = Joint(Joint::RevZ, true, \"j2\");\n\n  MultiBodyGraph mbg;\n\n  mbg.addBody(b0);\n  mbg.addBody(b1);\n  mbg.addBody(b2);\n  mbg.addBody(b3);\n\n  mbg.addJoint(j0);\n  mbg.addJoint(j1);\n  mbg.addJoint(j2);\n\n  mbg.linkBodies(\"b0\", PTransformd(Vector3d(0., 0.5, 0.)), \"b1\", PTransformd(Vector3d(0., -0.5, 0.)), \"j0\");\n  mbg.linkBodies(\"b1\", PTransformd(Vector3d(0.5, 0., 0.)), \"b2\", PTransformd(Vector3d(0., 0., 0.)), \"j1\");\n  mbg.linkBodies(\"b1\", PTransformd(Vector3d(-0.5, 0., 0.)), \"b3\", PTransformd(Vector3d(0., 0., 0.)), \"j2\");\n\n  MultiBody mb = mbg.makeMultiBody(\"b0\", true);\n\n  MultiBodyConfig mbc(mb);\n\n  mbc.q = {{}, {1., 0., 0., 0.}, {0.}, {0.}};\n  mbc.alpha = {{}, {0., 0., 0.}, {0.}, {0.}};\n  mbc.alphaD = {{}, {0., 0., 0.}, {0.}, {0.}};\n  mbc.force = {ForceVecd(Vector6d::Zero()), ForceVecd(Vector6d::Zero()), ForceVecd(Vector6d::Zero()),\n               ForceVecd(Vector6d::Zero())};\n\n  forwardKinematics(mb, mbc);\n  forwardVelocity(mb, mbc);\n\n  InverseDynamics id(mb);\n  ForwardDynamics fd(mb);\n\n  // check non linear is null\n  mbc.gravity = Vector3d::Zero();\n  fd.computeC(mb, mbc);\n\n  BOOST_CHECK(fd.C().isZero());\n\n  // check FD C against ID C\n  mbc.gravity = Vector3d(0., -9.81, 0.);\n  makeRandomConfig(mbc);\n\n  forwardKinematics(mb, mbc);\n  forwardVelocity(mb, mbc);\n\n  fd.computeC(mb, mbc);\n\n  mbc.alphaD = {{}, {0., 0., 0.}, {0.}, {0.}};\n  id.inverseDynamics(mb, mbc);\n\n  VectorXd ID_C(mb.nrDof());\n  int dof = 0;\n  for(auto & v1 : mbc.jointTorque)\n  {\n    for(auto & v2 : v1)\n    {\n      ID_C(dof) = v2;\n      ++dof;\n    }\n  }\n\n#ifdef __i386__\n  BOOST_CHECK_SMALL((fd.C() - ID_C).array().abs().sum(), TOL);\n#else\n  BOOST_CHECK_EQUAL(fd.C(), ID_C);\n#endif\n\n  // check FD H against ID H\n  makeRandomConfig(mbc);\n\n  forwardKinematics(mb, mbc);\n  forwardVelocity(mb, mbc);\n\n  fd.forwardDynamics(mb, mbc);\n  MatrixXd ID_H = makeHFromID(mb, mbc, id, fd.C());\n\n  BOOST_CHECK_SMALL((fd.H() - ID_H).norm(), 1e-10);\n\n  // check symmetry\n\n  MatrixXd L = fd.H().triangularView<Lower>();\n  MatrixXd U = fd.H().triangularView<Upper>().transpose();\n\n  BOOST_CHECK_SMALL((L - U).norm(), 1e-10);\n\n  // check torque and acceleration output\n\n  // torque -> FD -> alphaD -> ID -> torque\n  makeRandomConfig(mbc);\n\n  VectorXd vT1(mb.nrDof()), vT2(mb.nrDof());\n\n  forwardKinematics(mb, mbc);\n  forwardVelocity(mb, mbc);\n\n  paramToVector(mbc.jointTorque, vT1);\n\n  fd.forwardDynamics(mb, mbc);\n  id.inverseDynamics(mb, mbc);\n\n  paramToVector(mbc.jointTorque, vT2);\n\n  BOOST_CHECK_SMALL((vT1 - vT2).norm(), 1e-10);\n\n  // alphaD -> ID -> torque -> FD -> alphaD\n  makeRandomConfig(mbc);\n\n  VectorXd vA1(mb.nrDof()), vA2(mb.nrDof());\n\n  forwardKinematics(mb, mbc);\n  forwardVelocity(mb, mbc);\n\n  paramToVector(mbc.alphaD, vA1);\n\n  id.inverseDynamics(mb, mbc);\n  fd.forwardDynamics(mb, mbc);\n\n  paramToVector(mbc.alphaD, vA2);\n\n  BOOST_CHECK_SMALL((vA1 - vA2).norm(), 1e-10);\n}\n\nBOOST_AUTO_TEST_CASE(IDvsFDFree)\n{\n  using namespace Eigen;\n  using namespace sva;\n  using namespace rbd;\n  namespace cst = boost::math::constants;\n\n  typedef Matrix<double, 1, 1> EScalar;\n\n  RBInertiad I0(EScalar::Random()(0) * 10., Vector3d::Random() * 10., Matrix3d::Random().triangularView<Lower>());\n  RBInertiad I1(EScalar::Random()(0) * 10., Vector3d::Random() * 10., Matrix3d::Random().triangularView<Lower>());\n  RBInertiad I2(EScalar::Random()(0) * 10., Vector3d::Random() * 10., Matrix3d::Random().triangularView<Lower>());\n  RBInertiad I3(EScalar::Random()(0) * 10., Vector3d::Random() * 10., Matrix3d::Random().triangularView<Lower>());\n\n  Body b0(I0, \"b0\");\n  Body b1(I1, \"b1\");\n  Body b2(I2, \"b2\");\n  Body b3(I3, \"b3\");\n\n  Joint j0 = Joint(Joint::Spherical, true, \"j0\");\n  Joint j1 = Joint(Joint::RevX, true, \"j1\");\n  Joint j2 = Joint(Joint::RevZ, true, \"j2\");\n\n  MultiBodyGraph mbg;\n\n  mbg.addBody(b0);\n  mbg.addBody(b1);\n  mbg.addBody(b2);\n  mbg.addBody(b3);\n\n  mbg.addJoint(j0);\n  mbg.addJoint(j1);\n  mbg.addJoint(j2);\n\n  mbg.linkBodies(\"b0\", PTransformd(Vector3d(0., 0.5, 0.)), \"b1\", PTransformd(Vector3d(0., -0.5, 0.)), \"j0\");\n  mbg.linkBodies(\"b1\", PTransformd(Vector3d(0.5, 0., 0.)), \"b2\", PTransformd(Vector3d(0., 0., 0.)), \"j1\");\n  mbg.linkBodies(\"b1\", PTransformd(Vector3d(-0.5, 0., 0.)), \"b3\", PTransformd(Vector3d(0., 0., 0.)), \"j2\");\n\n  MultiBody mb = mbg.makeMultiBody(\"b0\", false);\n\n  MultiBodyConfig mbc(mb);\n\n  mbc.q = {{1., 0., 0., 0., 0., 0., 0.}, {1., 0., 0., 0.}, {0.}, {0.}};\n  mbc.alpha = {{0., 0., 0., 0., 0., 0.}, {0., 0., 0.}, {0.}, {0.}};\n  mbc.alphaD = {{0., 0., 0., 0., 0., 0.}, {0., 0., 0.}, {0.}, {0.}};\n  mbc.force = {ForceVecd(Vector6d::Zero()), ForceVecd(Vector6d::Zero()), ForceVecd(Vector6d::Zero()),\n               ForceVecd(Vector6d::Zero())};\n\n  forwardKinematics(mb, mbc);\n  forwardVelocity(mb, mbc);\n\n  InverseDynamics id(mb);\n  ForwardDynamics fd(mb);\n\n  // check non linear is null\n  mbc.gravity = Vector3d::Zero();\n  fd.computeC(mb, mbc);\n\n  BOOST_CHECK(fd.C().isZero());\n\n  // check FD C against ID C\n  mbc.gravity = Vector3d(0., -9.81, 0.);\n  makeRandomConfig(mbc);\n\n  forwardKinematics(mb, mbc);\n  forwardVelocity(mb, mbc);\n\n  fd.computeC(mb, mbc);\n\n  mbc.alphaD = {{0., 0., 0., 0., 0., 0.}, {0., 0., 0.}, {0.}, {0.}};\n  id.inverseDynamics(mb, mbc);\n\n  VectorXd ID_C(mb.nrDof());\n  int dof = 0;\n  for(auto & v1 : mbc.jointTorque)\n  {\n    for(auto & v2 : v1)\n    {\n      ID_C(dof) = v2;\n      ++dof;\n    }\n  }\n\n#ifdef __i386__\n  BOOST_CHECK_SMALL((fd.C() - ID_C).array().abs().sum(), TOL);\n#else\n  BOOST_CHECK_EQUAL(fd.C(), ID_C);\n#endif\n\n  // check FD H against ID H\n  makeRandomConfig(mbc);\n\n  forwardKinematics(mb, mbc);\n  forwardVelocity(mb, mbc);\n\n  fd.forwardDynamics(mb, mbc);\n  MatrixXd ID_H = makeHFromID(mb, mbc, id, fd.C());\n\n  BOOST_CHECK_SMALL((fd.H() - ID_H).norm(), 1e-10);\n\n  // check symmetry\n\n  MatrixXd L = fd.H().triangularView<Lower>();\n  MatrixXd U = fd.H().triangularView<Upper>().transpose();\n\n  BOOST_CHECK_SMALL((L - U).norm(), 1e-10);\n\n  // check torque and acceleration output\n\n  // torque -> FD -> alphaD -> ID -> torque\n  makeRandomConfig(mbc);\n\n  VectorXd vT1(mb.nrDof()), vT2(mb.nrDof());\n\n  forwardKinematics(mb, mbc);\n  forwardVelocity(mb, mbc);\n\n  paramToVector(mbc.jointTorque, vT1);\n\n  internal::set_is_malloc_allowed(false);\n  fd.forwardDynamics(mb, mbc);\n  id.inverseDynamics(mb, mbc);\n  internal::set_is_malloc_allowed(true);\n\n  paramToVector(mbc.jointTorque, vT2);\n\n#ifndef WIN32\n  BOOST_CHECK_SMALL((vT1 - vT2).norm(), 1e-9);\n#else\n  BOOST_CHECK_SMALL((vT1 - vT2).norm(), 1e-8);\n#endif\n\n  // alphaD -> ID -> torque -> FD -> alphaD\n  makeRandomConfig(mbc);\n\n  VectorXd vA1(mb.nrDof()), vA2(mb.nrDof());\n\n  forwardKinematics(mb, mbc);\n  forwardVelocity(mb, mbc);\n\n  paramToVector(mbc.alphaD, vA1);\n\n  id.inverseDynamics(mb, mbc);\n  fd.forwardDynamics(mb, mbc);\n\n  paramToVector(mbc.alphaD, vA2);\n\n  BOOST_CHECK_SMALL((vA1 - vA2).norm(), 1e-10);\n}\n\nBOOST_AUTO_TEST_CASE(MultiBodyGraphMerge)\n{\n  rbd::MultiBody mb;\n  rbd::MultiBodyConfig mbc;\n  rbd::MultiBodyGraph mbg;\n  std::tie(mb, mbc, mbg) = makeXYZSarm();\n\n  BOOST_CHECK_EQUAL(mbg.nrNodes(), 5);\n  BOOST_CHECK_EQUAL(mbg.nrJoints(), 4);\n  BOOST_CHECK_EQUAL(mb.nrBodies(), 5);\n  BOOST_CHECK_EQUAL(mb.nrJoints(), 5);\n\n  forwardKinematics(mb, mbc);\n  forwardVelocity(mb, mbc);\n\n  std::map<std::string, std::vector<double>> configByName;\n  configByName[\"j0\"] = {0.};\n  configByName[\"j1\"] = {0.};\n  configByName[\"j2\"] = {0.};\n  configByName[\"j3\"] = {1., 0., 0., 0.};\n\n  // merge b2, b3 and b4 in b1\n  mbg.mergeSubBodies(\"b0\", \"j1\", configByName);\n  mbg.mergeSubBodies(\"b0\", \"j3\", configByName);\n\n  rbd::MultiBody mbMerged = mbg.makeMultiBody(\"b0\", true);\n\n  BOOST_CHECK_EQUAL(mbg.nrNodes(), 2);\n  BOOST_CHECK_EQUAL(mbg.nrJoints(), 1);\n  BOOST_CHECK_EQUAL(mbMerged.nrBodies(), 2);\n  BOOST_CHECK_EQUAL(mbMerged.nrJoints(), 2);\n\n  rbd::ForwardDynamics fd(mb);\n  fd.forwardDynamics(mb, mbc);\n  double error = (fd.inertiaSubTree()[1].matrix() - mbMerged.body(1).inertia().matrix()).norm();\n\n  BOOST_CHECK_SMALL(error, TOL);\n}\n", "meta": {"hexsha": "dec0b6f2455c9695c4eeeae209d636ba05706955", "size": 12875, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/DynamicsTest.cpp", "max_stars_repo_name": "dbdxnuliba/RBDyn-provides-a-set-of-classes-and-functions-to-model-the-dynamics-of-rigid-body-systems.", "max_stars_repo_head_hexsha": "c3f498f8330e06be7dae55570d00931702b920d6", "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": "tests/DynamicsTest.cpp", "max_issues_repo_name": "dbdxnuliba/RBDyn-provides-a-set-of-classes-and-functions-to-model-the-dynamics-of-rigid-body-systems.", "max_issues_repo_head_hexsha": "c3f498f8330e06be7dae55570d00931702b920d6", "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": "tests/DynamicsTest.cpp", "max_forks_repo_name": "dbdxnuliba/RBDyn-provides-a-set-of-classes-and-functions-to-model-the-dynamics-of-rigid-body-systems.", "max_forks_repo_head_hexsha": "c3f498f8330e06be7dae55570d00931702b920d6", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.9032882012, "max_line_length": 114, "alphanum_fraction": 0.6246990291, "num_tokens": 4605, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.46035304584005293}}
{"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// Internal functions\nAnyType mLogstateToResult(\n    const Allocator &inAllocator,\n    int ref_category, \n    const HandleMap<const ColumnVector, TransparentHandle<double> >& inCoef,\n    const ColumnVector &diagonal_of_heissian,\n    double logLikelihood,\n    double conditionNo);\n\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 \u00a714.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        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> 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 5 + inWidthOfX * inWidthOfX * inNumCategories * inNumCategories\n                                 + 2 * 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: coef (vector of coefficients)\n     *\n     * Intra-iteration components (updated in transition step):\n     * - 2 + widthOfX*numCategories: numRows (number of rows already processed in this iteration)\n     * - 3 + widthOfX*numCategories: gradient (X^T A z)\n     * - 3 + 2 * widthOfX * inNumCategories: X_transp_AX (X^T A X)\n     * - 3 + widthOfX^2*numCategories^2\n                         + 2 * widthOfX*numCategories: logLikelihood ( ln(l(c)) )\n     * - 4 + widthOfX^2*numCategories^2\n                         + 2 * widthOfX*numCategories: ref_category\n     */\n    void rebind(uint16_t inWidthOfX = 0, uint16_t inNumCategories = 0) {\n        widthOfX.rebind(&mStorage[0]);\n        numCategories.rebind(&mStorage[1]);\n        coef.rebind(&mStorage[2], inWidthOfX*inNumCategories);\n\n        numRows.rebind(&mStorage[2 + inWidthOfX*inNumCategories]);\n\n        gradient.rebind(&mStorage[3 + inWidthOfX*inNumCategories],inWidthOfX*inNumCategories);\n        X_transp_AX.rebind(&mStorage[3 + 2 * inWidthOfX*inNumCategories],\n            inNumCategories*inWidthOfX, inWidthOfX*inNumCategories);\n        logLikelihood.rebind(&mStorage[3 +\n             inNumCategories*inNumCategories*inWidthOfX*inWidthOfX\n             + 2 * inWidthOfX*inNumCategories]);\n        ref_category.rebind(&mStorage[4 +\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\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 \u00a714.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\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    typename HandleTraits<Handle>::ReferenceToUInt16 ref_category;\n};\n\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    // Get x as a vector of double\n    MappedColumnVector x = args[4].getAs<MappedColumnVector>();\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     * 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            \"calulation. 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 heissianInver = -1 * decomposition.pseudoInverse();\n\n    state.coef.noalias() += heissianInver * 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.gradient = -1 * heissianInver.diagonal();\n    state.X_transp_AX(0,0) = decomposition.conditionNo();\n\n    return state;\n}\n\nAnyType\nmlogregr_robust_step_transition::run(AnyType &args) {\n    using std::endl;\n\n\tMLogRegrRobustTransitionState<MutableArrayHandle<double> > state = args[0];\n    // Get x as a vector of double\n    MappedColumnVector x = args[4].getAs<MappedColumnVector>();\n    // Get the category & numCategories as integer\n    int16_t category = args[1].getAs<int>();\n    // Number of categories after pivoting (We pivot around the first category)\n    int16_t numCategories = (args[2].getAs<int>() - 1);\n    int32_t ref_category = args[3].getAs<int32_t>();\n\tMappedColumnVector coefVec = args[5].getAs<MappedColumnVector>();\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        state.coef = coefVec;\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            \"calulation. Input data is likely of poor numerical condition.\");\n\n\n    SymmetricPositiveDefiniteEigenDecomposition<Matrix> decomposition(\n        -1 * state.X_transp_AX, EigenvaluesOnly, ComputePseudoInverse);\n\n\tfor(int i = 0; i < state.X_transp_AX.rows(); i++)\n\t{\n\t\tfor(int j = 0; j < state.X_transp_AX.cols(); j++)\n\t\t{\n\t\t\telog(INFO, \"Bread %i, %i, %f\",  i,j, static_cast<float>(state.X_transp_AX(i,j)));\n\t\t}\n\t}\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\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.ref_category, state.coef,\n        state.gradient, state.logLikelihood, state.X_transp_AX(0,0));\n}\n\n\n/**\n * @brief Compute the diagnostic statistics\n *\n * This function wraps the common parts of computing the results for IRLS.\n */\nAnyType mLogstateToResult(\n    const Allocator &inAllocator,\n    int ref_category,\n    const HandleMap<const ColumnVector, TransparentHandle<double> > &inCoef,\n    const ColumnVector &diagonal_of_heissian,\n    double logLikelihood,\n    double conditionNo) {\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_heissian(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 << ref_category << inCoef << logLikelihood << stdErr << waldZStats << waldPValues\n        << oddsRatios << conditionNo;\n    return tuple;\n}\n\n\n\n// ---------------------------------------------------------------------------\n//             Marginal Effects Multi-Logistic Regression States\n// ---------------------------------------------------------------------------\n/**\n * @brief State for marginal effects calculation for logistic regression\n *\n * TransitionState encapsualtes the transition state during the\n * marginal effects calculation for the logistic-regression aggregate function.\n * To the database, the state is exposed as a single DOUBLE PRECISION array,\n * to the C++ code it is a proper 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 */\n\ntemplate <class Handle>\nclass mlogregrMarginalTransitionState {\n\n    // By \u00a714.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 mlogregrMarginalTransitionState;\n\npublic:\n    mlogregrMarginalTransitionState(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> mlogregrMarginalTransitionState &operator=(\n        const mlogregrMarginalTransitionState<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> mlogregrMarginalTransitionState &operator+=(\n        const mlogregrMarginalTransitionState<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        margins_matrix += inOtherState.margins_matrix;\n        X_bar += inOtherState.X_bar;\n        X_transp_AX += inOtherState.X_transp_AX;\n        reference_margins+= inOtherState.reference_margins;\n        return *this;\n    }\n\n    /**\n     * @brief Reset the inter-iteration fields.\n     */\n    inline void reset() {\n        numRows = 0;\n        margins_matrix.fill(0);\n        X_bar.fill(0);\n        X_transp_AX.fill(0);\n        reference_margins.fill(0);\n    }\n\nprivate:\n    static inline uint32_t arraySize(const uint16_t inWidthOfX,\n        const uint16_t inNumCategories) {\n        return 4 + 3*inWidthOfX * inNumCategories + 1*inWidthOfX + \n           inNumCategories * inWidthOfX * 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: margins_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        margins_matrix.rebind(&mStorage[4 + inWidthOfX * inNumCategories],\n            inNumCategories , inWidthOfX );\n        X_bar.rebind(&mStorage[4 + 2*inWidthOfX * inNumCategories], inWidthOfX);\n        reference_margins.rebind(&mStorage[4 + 2*inWidthOfX + 2*inWidthOfX*inNumCategories],\n            inWidthOfX);\n        X_transp_AX.rebind(&mStorage[4 + 3*inWidthOfX * inNumCategories + 1*inWidthOfX],\n            inNumCategories*inWidthOfX, inWidthOfX*inNumCategories);\n    }\n\n    Handle mStorage;\n\npublic:\n    typename HandleTraits<Handle>::ReferenceToUInt16 widthOfX;\n    typename HandleTraits<Handle>::ReferenceToUInt16 numCategories;\n\n    typename HandleTraits<Handle>::ColumnVectorTransparentHandleMap coef;\n    typename HandleTraits<Handle>::ReferenceToUInt64 numRows;\n    typename HandleTraits<Handle>::MatrixTransparentHandleMap margins_matrix;\n    typename HandleTraits<Handle>::MatrixTransparentHandleMap X_transp_AX;\n    typename HandleTraits<Handle>::ColumnVectorTransparentHandleMap reference_margins;\n    typename HandleTraits<Handle>::ReferenceToUInt16 ref_category;\n    typename HandleTraits<Handle>::ColumnVectorTransparentHandleMap X_bar;\n};\n\n\nAnyType\nmlogregr_marginal_step_transition::run(AnyType &args) {\n    using std::endl;\n\n\t  mlogregrMarginalTransitionState<MutableArrayHandle<double> > state = args[0];\n    // Get x as a vector of double\n    MappedColumnVector x = args[4].getAs<MappedColumnVector>();\n    // Get the category & numCategories as integer\n    int16_t category = args[1].getAs<int>();\n    // Number of categories after pivoting (We pivot around the first category)\n    int16_t numCategories = (args[2].getAs<int>() - 1);\n    int32_t ref_category = args[3].getAs<int32_t>();\n\t  MappedColumnVector coefVec = args[5].getAs<MappedColumnVector>();\n\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        state.coef = coefVec;\n        state.numCategories = numCategories;\n        state.ref_category = ref_category;\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    //    Marginal Effect calculations\n    // ----------------------------------------------------------------------\n    Matrix coef = state.coef;\n    coef.resize(numCategories, state.widthOfX);\n\n    // prob is vector of size # categories\n    /* \n        Note: The above 2 lines could have been written as:\n        ColumnVector prob = -coef*x; but this creates warnings. \n        See multilog for details. \n    */\n    ColumnVector prob(numCategories); \n    prob = coef*x;\n\n    // Calculate the odds ratio\n    prob = prob.array().exp();\n    double prob_sum = prob.sum();\n\n    prob = prob / (1 + prob_sum);\n    \n    // Reference category computations. They have been taken out of \n    // the output but left in the infrastructure\n    double ref_prob = 1 / (1 + prob_sum);\n    \n    Matrix probDiag = prob.asDiagonal();\n\n\n    // Marginal effects (reference calculated separately)\n    ColumnVector coef_trans_prob;\n    coef_trans_prob = coef.transpose() * prob;\n    Matrix margins_matrix = coef;\n    margins_matrix.rowwise() -= coef_trans_prob.transpose();\n    margins_matrix = probDiag * margins_matrix;\n\n\n    //    Variance Calculations\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    a = prob * prob.transpose() - probDiag;\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    state.margins_matrix += margins_matrix;\n    state.reference_margins += -coef_trans_prob * ref_prob; \n    state.X_bar += x; // It is called X_bar but it really is the sum\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_marginal_step_merge_states::run(AnyType &args) {\n    mlogregrMarginalTransitionState<MutableArrayHandle<double> > stateLeft = args[0];\n    mlogregrMarginalTransitionState<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 mlogregr_marginalstateToResult(\n    const Allocator &inAllocator,\n    const int numRows,\n    const ColumnVector &inCoef,\n    const ColumnVector &inMargins,\n    const ColumnVector &inVariance\n    ) {\n\n    \n    MutableNativeColumnVector margins(\n        inAllocator.allocateArray<double>(inMargins.size()));\n    MutableNativeColumnVector coef(\n        inAllocator.allocateArray<double>(inMargins.size()));\n    MutableNativeColumnVector stdErr(\n        inAllocator.allocateArray<double>(inMargins.size()));\n    MutableNativeColumnVector tStats(\n        inAllocator.allocateArray<double>(inMargins.size()));\n    MutableNativeColumnVector pValues(\n        inAllocator.allocateArray<double>(inMargins.size()));\n\n    for (Index i = 0; i < inMargins.size(); ++i) {\n        margins(i) = inMargins(i);\n        coef(i) = inCoef(i);\n        stdErr(i) = std::sqrt(inVariance(i));\n        tStats(i) = margins(i) / stdErr(i);\n\n        // P-values only make sense if numRows > coef.size()\n        if (numRows > inCoef.size())\n          pValues(i) = 2. * prob::cdf(\n              boost::math::complement(\n                  prob::students_t(\n                      static_cast<double>(numRows - inCoef.size())\n                  ),\n                  std::fabs(tStats(i))\n              ));\n    }\n\n    // Return all coefficients, standard errors, etc. in a tuple\n    // Note: PValues will return NULL if numRows <= coef.size\n    AnyType tuple;\n    tuple << margins\n          << coef\n          << stdErr\n          << tStats\n        \t<< (numRows > inCoef.size()? pValues: Null());\n    return tuple;\n}\n\n\n/**\n * @brief Perform the logistic-regression final step\n */\nAnyType\nmlogregr_marginal_step_final::run(AnyType &args) {\n    // We request a mutable object. Depending on the backend, this might perform\n    // a deep copy.\n    mlogregrMarginalTransitionState<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    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    // 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            \"calulation. Input data is likely of poor numerical condition.\");\n\n    // Include marginal effects of reference variable: \n    // FIXME: They have been taken out of the output for now\n    //const int size = state.coef.size() + numIndepVars;\n    const int size = state.coef.size();\n    \n    // Variance-covariance calculation\n    // ----------------------------------------------------------\n    SymmetricPositiveDefiniteEigenDecomposition<Matrix> decomposition(\n        -1 * state.X_transp_AX, EigenvaluesOnly, ComputePseudoInverse);\n\n    // Precompute -(X^T * A * X)^-1\n    Matrix V = decomposition.pseudoInverse();\n\n\n\n    // Marginal Effect calculation\n    // ---------------------------------------------------------\n    Matrix margins_matrix;\n    margins_matrix = state.margins_matrix / state.numRows;\n\n\n    // Standard error calculation\n    // ----------------------------------------------------------\n    ColumnVector x_bar = state.X_bar / state.numRows;\n    int numIndepVars = state.coef.size() / state.numCategories;\n    int numCategories = state.numCategories;\n    \n    Matrix coef = state.coef;\n    coef.resize(state.numCategories, state.widthOfX);\n    \n    // Variance & Marginal gradient\n    ColumnVector marginal_gradient(size);\n    ColumnVector variance(size);\n    variance.setOnes();\n\n    // Probibility vector at the mean\n    ColumnVector p_bar(state.numCategories); \n    ColumnVector coef_x_bar(state.numCategories);\n    ColumnVector coef_trans_p_bar(state.widthOfX);\n    \n    coef_x_bar = coef*x_bar;\n    coef_trans_p_bar = coef.transpose() * p_bar;\n\n    p_bar = coef_x_bar;\n    p_bar = p_bar.array().exp();\n    p_bar = p_bar / (1 + p_bar.sum());\n\n    // Marginal effects at the mean\n    Matrix margins_mean_matrix(numCategories, numIndepVars);\n    margins_mean_matrix.rowwise() -= coef_trans_p_bar.transpose();\n    margins_mean_matrix = p_bar.asDiagonal() * margins_matrix;\n\n    // Compute the variance for each marginal effect\n    int index, e_j_J, e_k_K, e_k_K_j_J;\n    for (int K=0; K < numIndepVars; K++){\n      for (int J=0; J < numCategories; J++){\n\n        for (int k=0; k < numIndepVars; k++){\n          for (int j=0; j < numCategories; j++){\n            \n            e_j_J = (j==J) ? 1: 0;\n            e_k_K = (k==K) ? 1: 0;\n            e_k_K_j_J = (j==J && k==K) ? 1: 0;\n\n            index = k*numCategories + j;\n\n            marginal_gradient(index) = \n                x_bar(k) * (e_j_J  - p_bar(j)) * margins_mean_matrix(J,K);\n\n            marginal_gradient(index) += p_bar(J) * \n                ( e_k_K_j_J - p_bar(j) * e_k_K - x_bar(k) * margins_mean_matrix(j,K));\n          }\n        }\n\n        // NOTE: Since the earlier Variance calculations are being done by\n        // stacking up the indepdent variables for each category separtely\n        variance(K + numIndepVars * J) = \n                          marginal_gradient.transpose() * V * marginal_gradient;\n\n      }\n    }\n\n    \n\n    // Add in reference variables to all the calculations\n    // ----------------------------------------------------------\n    ColumnVector coef_with_ref(size);\n    ColumnVector margins_with_ref(size);\n\n    // Vectorize the margins_matrix and add the reference variable\n    for (int j=0; j < numCategories; j++){\n      for (int k=0; k < numIndepVars; k++){\n        \n        index = k + numIndepVars *j;\n        coef_with_ref(index) = coef(j,k);\n\n        index = k + numIndepVars*j;\n        margins_with_ref(index) = margins_matrix(j,k);\n      }\n    }\n\n    return mlogregr_marginalstateToResult(*this, \n                                          state.numRows,\n                                          coef_with_ref, \n                                          margins_with_ref,\n                                          variance);\n}\n\n\n// ------------------------ End of Marginal ------------------------------------\n\n\n} // namespace regress\n\n} // namespace modules\n\n} // namespace madlib\n", "meta": {"hexsha": "ba3b1c98e7d5b93dee1f84475670b0cef1961509", "size": 48340, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "madlib/src/modules/regress/multilogistic.cpp", "max_stars_repo_name": "cloudera/madlibport", "max_stars_repo_head_hexsha": "e1a47822fbb69899fe602ef71c56f6c6dacc1340", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2015-01-01T09:13:57.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-30T02:55:46.000Z", "max_issues_repo_path": "madlib/src/modules/regress/multilogistic.cpp", "max_issues_repo_name": "cloudera/madlibport", "max_issues_repo_head_hexsha": "e1a47822fbb69899fe602ef71c56f6c6dacc1340", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "madlib/src/modules/regress/multilogistic.cpp", "max_forks_repo_name": "cloudera/madlibport", "max_forks_repo_head_hexsha": "e1a47822fbb69899fe602ef71c56f6c6dacc1340", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2015-10-16T12:17:55.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-12T10:33:18.000Z", "avg_line_length": 35.9940431869, "max_line_length": 106, "alphanum_fraction": 0.6491311543, "num_tokens": 11865, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4603530395796255}}
{"text": "/**\n * @author     : Zhao Chonyyao (cyzhao@zju.edu.cn)\n * @date       : 2021-04-30\n * @description: elasticity finite element method problem\n * @version    : 1.0\n */\n#include <memory>\n#include <iomanip>\n#include <boost/property_tree/ptree.hpp>\n\n#include \"Common/DEFINE_TYPE.h\"\n#include \"Common/error.h\"\n\n// TODO: possible bad idea of having dependence to model in problem module\n#include \"Model/fem/elas_energy.h\"\n#include \"Model/fem/mass_matrix.h\"\n\n#include \"Problem/energy/basic_energy.h\"\n#include \"Io/io.h\"\n#include \"Geometry/extract_surface.imp\"\n\n#include \"elas_fem_problem.h\"\n\nnamespace PhysIKA {\nusing namespace std;\nusing namespace Eigen;\n\ntemplate <typename T>\nint read_elas_mtr(const char* file, VEC<T>& Young, VEC<T>& Poi, const size_t num_cells)\n{\n    cout << \"read_elas_mtr\" << endl;\n    Young.resize(num_cells);\n    Poi.resize(num_cells);\n    ifstream ifs(file);\n    if (ifs.fail())\n    {\n        std::cerr << \"[info] \"\n                  << \"can not open file\" << file << std::endl;\n        return __LINE__;\n    }\n    size_t cell_id = 0;\n    while (!ifs.eof())\n    {\n        if (cell_id == num_cells)\n            break;\n        ifs >> Young(cell_id) >> Poi(cell_id);\n        ++cell_id;\n    }\n    ifs.close();\n    return 0;\n}\n\ntemplate <typename T>\nelas_problem_builder<T>::elas_problem_builder(const T* x, const boost::property_tree::ptree& pt)\n    : pt_(pt)\n{\n    if (pt.get<string>(\"solver_type\") == \"explicit\")\n    {\n#define SEMI_IMPLICIT\n    }\n\n    //TODO: need to check exception\n    const string filename = pt.get<string>(\"filename\");\n    MAT<T>       nods(1, 1);\n    MatrixXi     cells(1, 1);\n\n    const string type = pt.get<string>(\"type\", \"tet\");\n\n    if (type == \"tet\")\n    {\n        IF_ERR(exit, mesh_read_from_vtk<T, 4>(filename.c_str(), nods, cells));\n    }\n    else if (type == \"hex\")\n        exit_if(mesh_read_from_vtk<T, 8>(filename.c_str(), nods, cells));\n    else\n    {\n        // error_msg(\"type:<%s> is not supported.\", type.c_str());\n    }\n\n    const size_t num_nods = nods.cols(), num_cells = cells.cols();\n    cout << \"V\" << nods.rows() << \" \" << nods.cols() << endl\n         << \"T \" << cells.rows() << \" \" << cells.cols() << endl;\n    if (x != nullptr)\n        nods = Map<const MAT<T>>(x, nods.rows(), nods.cols());\n    cout << \"Boundary Box :\\n\"\n         << nods.rowwise().minCoeff() << endl\n         << nods.rowwise().maxCoeff() << endl;\n\n    REST_  = nods;\n    cells_ = cells;\n\n    Matrix<T, 3, 3> rot;\n    rot << 0, 0, 1, 0, 1, 0, -1, 0, 0;\n    cout << \"rotatoin matrix is \" << rot << endl;\n    MAT<T> rotated_nods = rot * nods;\n\n    // const string outdir = argv[3];\n    auto phy_paras = pt.get_child(\"physics\");\n    //set mtr\n    const T      rho       = phy_paras.get<T>(\"rho\", 20);\n    const T      Young     = phy_paras.get<T>(\"Young\", 2000.0);\n    const T      poi       = phy_paras.get<T>(\"poi\", 0.3);\n    const T      gravity   = phy_paras.get<T>(\"gravity\", 9.8);\n    const T      dt        = phy_paras.get<T>(\"dt\", 0.01);\n    const T      w_pos     = phy_paras.get<T>(\"w_pos\", 1e6);\n    const size_t num_frame = phy_paras.get<size_t>(\"num_frames\", 100);\n\n    //set mtr\n    VEC<T>       Young_vec(num_cells), Poi_vec(num_cells);\n    const string mtr_file = pt.get<string>(\"mtr_file\", \"\");\n    if (mtr_file != \"\")\n        read_elas_mtr(mtr_file.c_str(), Young_vec, Poi_vec, num_cells);\n\n    //read fixed points\n    vector<size_t> cons(0);\n    const string   cons_file_path = pt.get<string>(\"cons\", \"\");\n    if (cons_file_path != \"\")\n        IF_ERR(exit, read_fixed_verts_from_csv(cons_file_path.c_str(), cons));\n    cout << \"constrint \" << cons.size() << \" points\" << endl;\n\n    //calc mass vector\n    Matrix<T, -1, 1> mass_vec(num_nods);\n    // calc_mass_vector<T>(nods, cells, rho, mass_vec);\n    if (type == \"tet\")\n        mass_calculator<T, 3, 4, 1, 1, basis_func, quadrature>(nods, cells, rho, mass_vec);\n    else if (type == \"hex\")\n        mass_calculator<T, 3, 8, 1, 2, basis_func, quadrature>(nods, cells, rho, mass_vec);\n\n    cout << \"build energy\" << endl;\n    int ELAS = 0;\n    int GRAV = 1;\n    int KIN  = 2;\n    int POS  = 3;\n    if (pt_.get<string>(\"solver_type\") == \"explicit\")\n        POS = 2;\n\n    ebf_.resize(POS + 1);\n    {\n        const string csttt_type = phy_paras.get<string>(\"csttt\", \"linear\");\n        if (pt.get<bool>(\"rotate\", false))\n            nods = rotated_nods;\n        if (mtr_file != \"\")\n            gen_elas_energy_intf<T>(type, csttt_type, nods, cells, Young_vec, Poi_vec, ebf_[ELAS], &elas_intf_);\n        else\n            gen_elas_energy_intf<T>(type, csttt_type, nods, cells, Young, poi, ebf_[ELAS], &elas_intf_);\n        nods = REST_;\n        // to lowercase.\n        char axis = pt.get<char>(\"grav_axis\", 'y') | 0x20;\n        if (axis > 'z' || axis < 'x')\n        {\n            // error_msg(\"grav_axis should be one of x(X), y(Y) or z(Z).\");\n        }\n        ebf_[GRAV] = make_shared<gravity_energy<T, 3>>(num_nods, 1, gravity, mass_vec, axis);\n\n        kinetic_ = pt.get<bool>(\"dynamics\", true) ? make_shared<momentum<T, 3>>(nods.data(), num_nods, mass_vec, dt)\n                                                  : nullptr;\n\n        if (pt_.get<string>(\"solver_type\") == \"implicit\")\n            ebf_[KIN] = kinetic_;\n\n        ebf_[POS] = make_shared<position_constraint<T, 3>>(nods.data(), num_nods, w_pos, cons);\n    }\n\n    //set constraint\n\n    enum constraint_type\n    {\n        COLL\n    };\n    cbf_.resize(COLL + 1);\n    collider_  = nullptr;\n    cbf_[COLL] = collider_;\n\n    if (pt_.get<string>(\"solver_type\") == \"explicit\")\n    {\n        Map<Matrix<T, -1, 1>> position(REST_.data(), REST_.size());\n        semi_implicit_ = make_shared<semi_implicit<T>>(dt, mass_vec, position);\n    }\n}\n\ntemplate <typename T>\nstd::shared_ptr<Problem<T, 3>> elas_problem_builder<T>::build_problem() const\n{\n    cout << \"assemble energy\" << endl;\n    shared_ptr<Functional<T, 3>> energy;\n    try\n    {\n        energy = build_energy_t<T, 3>(ebf_);\n    }\n    catch (std::exception& e)\n    {\n        cerr << e.what() << endl;\n        exit(EXIT_FAILURE);\n    }\n\n    shared_ptr<Constraint<T>> constraint;\n    cout << \"assemble constraint\" << endl;\n    bool all_null = true;\n    for (auto& c : cbf_)\n        if (c != nullptr)\n            all_null = false;\n    if (all_null)\n    {\n        constraint = nullptr;\n        cout << \"WARNGING: No hard constraints.\" << endl;\n    }\n    else\n    {\n        try\n        {\n            constraint = build_constraint_t<T>(cbf_);\n        }\n        catch (std::exception& e)\n        {\n            cerr << e.what() << endl;\n            exit(EXIT_FAILURE);\n        }\n    }\n    exit_if(constraint != nullptr && energy->Nx() != constraint->Nx(), \"energy and constraint has different dimension.\");\n    return make_shared<Problem<T, 3>>(energy, constraint);\n}\n\ntemplate <typename T>\nint elas_problem_builder<T>::update_problem(const T* x, const T* v)\n{\n    if (kinetic_ != nullptr)\n        IF_ERR(return, kinetic_->update_location_and_velocity(x, v));\n    if (collider_ != nullptr)\n        IF_ERR(return, collider_->update(x));\n    return 0;\n}\n\ntemplate class elas_problem_builder<double>;\n\ntemplate class elas_problem_builder<float>;\n\n}  // namespace PhysIKA\n", "meta": {"hexsha": "f379e2ccc8b92f687a716cb04e5b1726b1d69aee", "size": 7160, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Source/Dynamics/FiniteElementMethod/Source/Problem/integrated_problem/elas_fem_problem.cc", "max_stars_repo_name": "weikm/sandcarSimulation2", "max_stars_repo_head_hexsha": "fe499d0a3289c0ac1acce69c7dc78d8ce1b2708a", "max_stars_repo_licenses": ["Apache-2.0"], "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/Dynamics/FiniteElementMethod/Source/Problem/integrated_problem/elas_fem_problem.cc", "max_issues_repo_name": "weikm/sandcarSimulation2", "max_issues_repo_head_hexsha": "fe499d0a3289c0ac1acce69c7dc78d8ce1b2708a", "max_issues_repo_licenses": ["Apache-2.0"], "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/Dynamics/FiniteElementMethod/Source/Problem/integrated_problem/elas_fem_problem.cc", "max_forks_repo_name": "weikm/sandcarSimulation2", "max_forks_repo_head_hexsha": "fe499d0a3289c0ac1acce69c7dc78d8ce1b2708a", "max_forks_repo_licenses": ["Apache-2.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.0840336134, "max_line_length": 121, "alphanum_fraction": 0.5762569832, "num_tokens": 2040, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4603530395796255}}
{"text": "/* ----------------------------------------------------------------------\n *\n *                    *** Smooth Mach Dynamics ***\n *\n * This file is part of the USER-SMD package for LAMMPS.\n * Copyright (2014) Georg C. Ganzenmueller, georg.ganzenmueller@emi.fhg.de\n * Fraunhofer Ernst-Mach Institute for High-Speed Dynamics, EMI,\n * Eckerstrasse 4, D-79104 Freiburg i.Br, Germany.\n *\n * ----------------------------------------------------------------------- */\n\n/* ----------------------------------------------------------------------\n LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator\n http://lammps.sandia.gov, Sandia National Laboratories\n Steve Plimpton, sjplimp@sandia.gov\n\n Copyright (2003) Sandia Corporation.  Under the terms of Contract\n DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains\n certain rights in this software.  This software is distributed under\n the GNU General Public License.\n\n See the README file in the top-level LAMMPS directory.\n ------------------------------------------------------------------------- */\n\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <iostream>\n#include <Eigen/Eigen>\n#include <Eigen/Geometry>\n#include \"compute_smd_tlsph_shape.h\"\n#include \"atom.h\"\n#include \"update.h\"\n#include \"modify.h\"\n#include \"comm.h\"\n#include \"force.h\"\n#include \"memory.h\"\n#include \"error.h\"\n#include \"pair.h\"\n\nusing namespace Eigen;\nusing namespace std;\nusing namespace LAMMPS_NS;\n\n/* ---------------------------------------------------------------------- */\n\nComputeSmdTlsphShape::ComputeSmdTlsphShape(LAMMPS *lmp, int narg, char **arg) :\n                Compute(lmp, narg, arg) {\n        if (narg != 3)\n                error->all(FLERR, \"Illegal compute smd/tlsph_strain command\");\n\n        peratom_flag = 1;\n        size_peratom_cols = 7;\n\n        nmax = 0;\n        strainVector = NULL;\n}\n\n/* ---------------------------------------------------------------------- */\n\nComputeSmdTlsphShape::~ComputeSmdTlsphShape() {\n        memory->sfree(strainVector);\n}\n\n/* ---------------------------------------------------------------------- */\n\nvoid ComputeSmdTlsphShape::init() {\n\n        int count = 0;\n        for (int i = 0; i < modify->ncompute; i++)\n                if (strcmp(modify->compute[i]->style, \"smd/tlsph_strain\") == 0)\n                        count++;\n        if (count > 1 && comm->me == 0)\n                error->warning(FLERR, \"More than one compute smd/tlsph_strain\");\n}\n\n/* ---------------------------------------------------------------------- */\n\nvoid ComputeSmdTlsphShape::compute_peratom() {\n        double *contact_radius = atom->contact_radius;\n        invoked_peratom = update->ntimestep;\n\n        // grow vector array if necessary\n\n        if (atom->nmax > nmax) {\n                memory->destroy(strainVector);\n                nmax = atom->nmax;\n                memory->create(strainVector, nmax, size_peratom_cols, \"strainVector\");\n                array_atom = strainVector;\n        }\n\n        int itmp = 0;\n        Matrix3d *R = (Matrix3d *) force->pair->extract(\"smd/tlsph/rotation_ptr\", itmp);\n        if (R == NULL) {\n                error->all(FLERR, \"compute smd/tlsph_shape failed to access rotation array\");\n        }\n\n        Matrix3d *F = (Matrix3d *) force->pair->extract(\"smd/tlsph/Fincr_ptr\", itmp);\n        if (F == NULL) {\n                error->all(FLERR, \"compute smd/tlsph_shape failed to access deformation gradient array\");\n        }\n\n        int *mask = atom->mask;\n        int nlocal = atom->nlocal;\n        Matrix3d E, eye;\n        eye.setIdentity();\n        Quaterniond q;\n\n        for (int i = 0; i < nlocal; i++) {\n                if (mask[i] & groupbit) {\n\n                        E = 0.5 * (F[i].transpose() * F[i] - eye); // Green-Lagrange strain\n                        strainVector[i][0] = contact_radius[i] * (1.0 + E(0, 0));\n                        strainVector[i][1] = contact_radius[i] * (1.0 + E(1, 1));\n                        strainVector[i][2] = contact_radius[i] * (1.0 + E(2, 2));\n\n                        q = R[i]; // convert pure rotation matrix to quaternion\n                        strainVector[i][3] = q.w();\n                        strainVector[i][4] = q.x();\n                        strainVector[i][5] = q.y();\n                        strainVector[i][6] = q.z();\n                } else {\n                        for (int j = 0; j < size_peratom_cols; j++) {\n                                strainVector[i][j] = 0.0;\n                        }\n                }\n        }\n}\n\n/* ----------------------------------------------------------------------\n memory usage of local atom-based array\n ------------------------------------------------------------------------- */\n\ndouble ComputeSmdTlsphShape::memory_usage() {\n        double bytes = size_peratom_cols * nmax * sizeof(double);\n        return bytes;\n}\n", "meta": {"hexsha": "bbab274b5cca0dd4d785ea0be2044df1e6c2cef9", "size": 4853, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lammps-master/src/USER-SMD/compute_smd_tlsph_shape.cpp", "max_stars_repo_name": "rajkubp020/helloword", "max_stars_repo_head_hexsha": "4bd22691de24b30a0f5b73821c35a7ac0666b034", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lammps-master/src/USER-SMD/compute_smd_tlsph_shape.cpp", "max_issues_repo_name": "rajkubp020/helloword", "max_issues_repo_head_hexsha": "4bd22691de24b30a0f5b73821c35a7ac0666b034", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lammps-master/src/USER-SMD/compute_smd_tlsph_shape.cpp", "max_forks_repo_name": "rajkubp020/helloword", "max_forks_repo_head_hexsha": "4bd22691de24b30a0f5b73821c35a7ac0666b034", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1666666667, "max_line_length": 105, "alphanum_fraction": 0.4811456831, "num_tokens": 1103, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.4603305613374161}}
{"text": "#include <iostream>\n#include <cmath>\n#include <NTL/ZZ.h>\n\n\nusing namespace std;\nusing namespace NTL;\n\n#include \"iterative.h\"\n#include \"recursive.h\"\n\nusing namespace std;\nusing namespace NTL;\nusing namespace chrono;\n\n//#define ITERATIVE\n\nvoid usage_example_zp(){\n    long degree = pow(2,20)-1;\n\n    ZZ prime;\n    GenPrime(prime, 128);\n    ZZ_p::init(prime);\n\n//  interpolation points:\n    ZZ_p* X = new ZZ_p[degree+1];\n    ZZ_p* Y = new ZZ_p[degree+1];\n    for(unsigned int i=0;i<=degree; i++) {\n        random(X[i]);\n        random(Y[i]);\n    }\n\n    ZZ_pX P;\n#ifdef ITERATIVE\n    poly_interpolate_zp_iterative(degree, X, Y, P);\n#else\n    poly_interpolate_zp_recursive(degree, X, Y, P);\n#endif\n\n    // EVALUATE\n    ZZ_p* X2 = new ZZ_p[degree+1];\n    ZZ_p* Y2 = new ZZ_p[degree+1];\n    for(unsigned int i=0;i<=degree; i++) {\n        random(X[i]);\n    }\n#ifdef ITERATIVE\n    poly_evaluate_zp_iterative(degree, P, X2, Y2);\n#else\n    poly_evaluate_zp_recursive(degree, P, X2, Y2);\n#endif\n\n    delete[] X;\n    delete[] Y;\n    delete[] X2;\n    delete[] Y2;\n}\n\n\nint main() {\n\n    usage_example_zp();\n\n}\n", "meta": {"hexsha": "f89f5455af4668c75b5835ae70627c1620a8b858", "size": 1095, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "schoppmp/FastPolynomial", "max_stars_repo_head_hexsha": "19f5c2ac8a6a70942e81715276ce1b04f028e9dd", "max_stars_repo_licenses": ["MIT"], "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": "schoppmp/FastPolynomial", "max_issues_repo_head_hexsha": "19f5c2ac8a6a70942e81715276ce1b04f028e9dd", "max_issues_repo_licenses": ["MIT"], "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": "schoppmp/FastPolynomial", "max_forks_repo_head_hexsha": "19f5c2ac8a6a70942e81715276ce1b04f028e9dd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-01T07:05:53.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-01T07:05:53.000Z", "avg_line_length": 17.109375, "max_line_length": 51, "alphanum_fraction": 0.6228310502, "num_tokens": 335, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.82446190912407, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.4603193396652467}}
{"text": "#define BOOST_TEST_MODULE \"test_dihedral_angle_interaction\"\n\n#ifdef BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n#else\n#include <boost/test/included/unit_test.hpp>\n#endif\n\n#include <mjolnir/core/BoundaryCondition.hpp>\n#include <mjolnir/core/SimulatorTraits.hpp>\n#include <mjolnir/forcefield/local/DihedralAngleInteraction.hpp>\n#include <mjolnir/math/constants.hpp>\n#include <mjolnir/forcefield/local/ClementiDihedralPotential.hpp>\n#include <mjolnir/util/make_unique.hpp>\n\n#include <random>\n\nBOOST_AUTO_TEST_CASE(DihedralAngle_force)\n{\n    using traits_type         = mjolnir::SimulatorTraits<double, mjolnir::UnlimitedBoundary>;\n    using real_type           = traits_type::real_type;\n    using coord_type          = traits_type::coordinate_type;\n    using boundary_type       = traits_type::boundary_type;\n    using system_type         = mjolnir::System<traits_type>;\n    using potential_type      = mjolnir::ClementiDihedralPotential<real_type>;\n    using dihedral_angle_type = mjolnir::DihedralAngleInteraction<traits_type, potential_type>;\n\n    constexpr real_type tol = 1e-7;\n\n    const real_type k1(1e0);\n    const real_type k3(1e0);\n    const real_type native(mjolnir::math::constants<real_type>::pi() * 2.0 / 3.0);\n\n    potential_type potential{k1, k3, native};\n    dihedral_angle_type interaction(\"none\", {{ {{0,1,2,3}}, potential}});\n\n    const coord_type pos1(1e0, 0e0, 1e0);\n    const coord_type pos2(0e0, 0e0, 1e0);\n    const coord_type pos3(0e0, 0e0, 0e0);\n\n    system_type sys(4, boundary_type{});\n\n    sys.at(0).mass = 1.0;\n    sys.at(1).mass = 1.0;\n    sys.at(2).mass = 1.0;\n    sys.at(3).mass = 1.0;\n    sys.at(0).rmass = 1.0;\n    sys.at(1).rmass = 1.0;\n    sys.at(2).rmass = 1.0;\n    sys.at(3).rmass = 1.0;\n\n    sys.at(0).position = pos1;\n    sys.at(1).position = pos2;\n    sys.at(2).position = pos3;\n    sys.at(3).position = coord_type(0,0,0);\n    sys.at(0).velocity = coord_type(0,0,0);\n    sys.at(1).velocity = coord_type(0,0,0);\n    sys.at(2).velocity = coord_type(0,0,0);\n    sys.at(3).velocity = coord_type(0,0,0);\n    sys.at(0).force    = coord_type(0,0,0);\n    sys.at(1).force    = coord_type(0,0,0);\n    sys.at(2).force    = coord_type(0,0,0);\n    sys.at(3).force    = coord_type(0,0,0);\n\n    sys.at(0).name  = \"X\";\n    sys.at(1).name  = \"X\";\n    sys.at(2).name  = \"X\";\n    sys.at(3).name  = \"X\";\n    sys.at(0).group = \"NONE\";\n    sys.at(1).group = \"NONE\";\n    sys.at(2).group = \"NONE\";\n    sys.at(3).group = \"NONE\";\n\n    const real_type dtheta = mjolnir::math::constants<real_type>::pi() / 1800.0;\n    for(int i = -1800; i < 1800; ++i)\n    {\n        BOOST_TEST(mjolnir::math::length(sys[0].position - pos1) == 0.0, boost::test_tools::tolerance(tol));\n        BOOST_TEST(mjolnir::math::length(sys[1].position - pos2) == 0.0, boost::test_tools::tolerance(tol));\n        BOOST_TEST(mjolnir::math::length(sys[2].position - pos3) == 0.0, boost::test_tools::tolerance(tol));\n\n        BOOST_TEST(mjolnir::math::length(sys[0].velocity) == 0.0, boost::test_tools::tolerance(tol));\n        BOOST_TEST(mjolnir::math::length(sys[1].velocity) == 0.0, boost::test_tools::tolerance(tol));\n        BOOST_TEST(mjolnir::math::length(sys[2].velocity) == 0.0, boost::test_tools::tolerance(tol));\n\n        sys[0].force = coord_type(0,0,0);\n        sys[1].force = coord_type(0,0,0);\n        sys[2].force = coord_type(0,0,0);\n        sys[3].force = coord_type(0,0,0);\n\n        const real_type theta = i * dtheta;\n        const coord_type pos4(std::cos(theta), -std::sin(theta), 0e0);\n        sys[3].position = pos4;\n\n        const real_type deriv = potential.derivative(theta);\n        const real_type coef = std::abs(deriv);\n\n        interaction.calc_force(sys);\n\n        // magnitude\n        // if radius == 1e0, then force strength is equal to dV.\n        BOOST_TEST(mjolnir::math::length(sys[1].position - sys[0].position) == 1e0, boost::test_tools::tolerance(tol));\n        BOOST_TEST(mjolnir::math::length(sys[2].position - sys[1].position) == 1e0, boost::test_tools::tolerance(tol));\n        BOOST_TEST(mjolnir::math::length(sys[3].position - sys[2].position) == 1e0, boost::test_tools::tolerance(tol));\n\n        const real_type force_strength1 = mjolnir::math::length(sys[0].force);\n        const real_type force_strength3 = mjolnir::math::length(sys[3].force);\n        if(i == 1200)\n        {\n            BOOST_TEST(coef            == 0.0, boost::test_tools::tolerance(tol));\n            BOOST_TEST(force_strength1 == 0.0, boost::test_tools::tolerance(tol));\n            BOOST_TEST(force_strength3 == 0.0, boost::test_tools::tolerance(tol));\n        }\n        else\n        {\n            BOOST_TEST(coef == force_strength1, boost::test_tools::tolerance(tol));\n            BOOST_TEST(coef == force_strength3, boost::test_tools::tolerance(tol));\n        }\n\n        // force applied to center particle is equal to sum of others\n        const coord_type sum = sys[0].force + sys[1].force + sys[2].force + sys[3].force;\n        BOOST_TEST(mjolnir::math::length(sum) == 0.0, boost::test_tools::tolerance(tol));\n\n        // direction\n        if(i == 1200) // most stable point\n        {\n            BOOST_TEST(mjolnir::math::length(sys[0].force) == 0.0, boost::test_tools::tolerance(tol));\n            BOOST_TEST(mjolnir::math::length(sys[1].force) == 0.0, boost::test_tools::tolerance(tol));\n            BOOST_TEST(mjolnir::math::length(sys[2].force) == 0.0, boost::test_tools::tolerance(tol));\n            BOOST_TEST(mjolnir::math::length(sys[3].force) == 0.0, boost::test_tools::tolerance(tol));\n        }\n        else\n        {\n            // perpendicular to radius vector\n            const real_type normal1 = mjolnir::math::dot_product(sys[0].force, sys[0].position - sys[1].position);\n            const real_type normal4 = mjolnir::math::dot_product(sys[3].force, sys[2].position - sys[3].position);\n            BOOST_TEST(normal1 == 0.0, boost::test_tools::tolerance(tol));\n            BOOST_TEST(normal4 == 0.0, boost::test_tools::tolerance(tol));\n        }\n\n        // perpendicular to z axis\n        BOOST_TEST(sys[0].force[2] == 0.0, boost::test_tools::tolerance(tol));\n        BOOST_TEST(sys[1].force[2] == 0.0, boost::test_tools::tolerance(tol));\n        BOOST_TEST(sys[2].force[2] == 0.0, boost::test_tools::tolerance(tol));\n        BOOST_TEST(sys[3].force[2] == 0.0, boost::test_tools::tolerance(tol));\n    }\n}\n\nBOOST_AUTO_TEST_CASE(DihedralAngleInteraction_numerical_diff)\n{\n    using traits_type         = mjolnir::SimulatorTraits<double, mjolnir::UnlimitedBoundary>;\n    using real_type           = traits_type::real_type;\n    using coord_type          = traits_type::coordinate_type;\n    using boundary_type       = traits_type::boundary_type;\n    using system_type         = mjolnir::System<traits_type>;\n    using potential_type       = mjolnir::ClementiDihedralPotential<real_type>;\n    using dihedral_angle_type = mjolnir::DihedralAngleInteraction<traits_type, potential_type>;\n\n    const real_type k1(1e0);\n    const real_type k3(1e0);\n    const real_type native(mjolnir::math::constants<real_type>::pi() / 2.0);\n\n    std::mt19937 mt(123456789);\n    std::uniform_real_distribution<real_type> uni(-1.0, 1.0);\n\n    potential_type potential{k1, k3, native};\n    dihedral_angle_type interaction(\"none\", {{ {{0,1,2,3}}, potential}});\n\n    for(std::size_t i=0; i<100; ++i)\n    {\n        system_type sys(4, boundary_type{});\n\n        sys.mass (0) = 1.0;\n        sys.mass (1) = 1.0;\n        sys.mass (2) = 1.0;\n        sys.mass (3) = 1.0;\n        sys.rmass(0) = 1.0;\n        sys.rmass(1) = 1.0;\n        sys.rmass(2) = 1.0;\n        sys.rmass(3) = 1.0;\n\n        sys.position(0) = coord_type(2.0 + 1e-2 * uni(mt), 0.0 + 1e-2 * uni(mt),  1.0 + 1e-2 * uni(mt));\n        sys.position(1) = coord_type(1.0 + 1e-2 * uni(mt), 1.0 + 1e-2 * uni(mt),  0.0 + 1e-2 * uni(mt));\n        sys.position(2) = coord_type(0.0 + 1e-2 * uni(mt), 0.0 + 1e-2 * uni(mt),  0.0 + 1e-2 * uni(mt));\n        sys.position(3) = coord_type(1.0 + 1e-2 * uni(mt), 1.0 + 1e-2 * uni(mt), -1.0 + 1e-2 * uni(mt));\n        sys.velocity(0) = coord_type(0.0, 0.0,  0.0);\n        sys.velocity(1) = coord_type(0.0, 0.0,  0.0);\n        sys.velocity(2) = coord_type(0.0, 0.0,  0.0);\n        sys.velocity(3) = coord_type(0.0, 0.0,  0.0);\n        sys.force   (0) = coord_type(0.0, 0.0,  0.0);\n        sys.force   (1) = coord_type(0.0, 0.0,  0.0);\n        sys.force   (2) = coord_type(0.0, 0.0,  0.0);\n        sys.force   (3) = coord_type(0.0, 0.0,  0.0);\n\n        const auto init = sys;\n\n        sys.at(0).name  = \"X\";\n        sys.at(1).name  = \"X\";\n        sys.at(2).name  = \"X\";\n        sys.at(3).name  = \"X\";\n        sys.at(0).group = \"NONE\";\n        sys.at(1).group = \"NONE\";\n        sys.at(2).group = \"NONE\";\n        sys.at(3).group = \"NONE\";\n\n        constexpr real_type tol = 1e-4;\n        constexpr real_type dr  = 1e-4;\n        for(std::size_t idx=0; idx<4; ++idx)\n        {\n            {\n                // ----------------------------------------------------------------\n                // reset positions\n                sys = init;\n\n                // calc U(x-dx)\n                const auto E0 = interaction.calc_energy(sys);\n\n                mjolnir::math::X(sys.position(idx)) += dr;\n\n                // calc F(x)\n                interaction.calc_force(sys);\n\n                mjolnir::math::X(sys.position(idx)) += dr;\n\n                // calc U(x+dx)\n                const auto E1 = interaction.calc_energy(sys);\n\n                // central difference\n                const auto dE = (E1 - E0) * 0.5;\n\n                BOOST_TEST(-dE == dr * mjolnir::math::X(sys.force(idx)),\n                           boost::test_tools::tolerance(tol));\n            }\n            {\n                // ----------------------------------------------------------------\n                // reset positions\n                sys = init;\n\n                // calc U(x-dx)\n                const auto E0 = interaction.calc_energy(sys);\n\n                mjolnir::math::Y(sys.position(idx)) += dr;\n\n                // calc F(x)\n                interaction.calc_force(sys);\n\n                mjolnir::math::Y(sys.position(idx)) += dr;\n\n                // calc U(x+dx)\n                const auto E1 = interaction.calc_energy(sys);\n\n                // central difference\n                const auto dE = (E1 - E0) * 0.5;\n\n                BOOST_TEST(-dE == dr * mjolnir::math::Y(sys.force(idx)),\n                           boost::test_tools::tolerance(tol));\n            }\n            {\n                // ----------------------------------------------------------------\n                // reset positions\n                sys = init;\n\n                // calc U(x-dx)\n                const auto E0 = interaction.calc_energy(sys);\n\n                mjolnir::math::Z(sys.position(idx)) += dr;\n\n                // calc F(x)\n                interaction.calc_force(sys);\n\n                mjolnir::math::Z(sys.position(idx)) += dr;\n\n                // calc U(x+dx)\n                const auto E1 = interaction.calc_energy(sys);\n\n                // central difference\n                const auto dE = (E1 - E0) * 0.5;\n\n                BOOST_TEST(-dE == dr * mjolnir::math::Z(sys.force(idx)),\n                           boost::test_tools::tolerance(tol));\n            }\n        }\n    }\n}\n\nBOOST_AUTO_TEST_CASE(DihedralAngleInteraction_calc_force_and_energy)\n{\n    using traits_type         = mjolnir::SimulatorTraits<double, mjolnir::UnlimitedBoundary>;\n    using real_type           = traits_type::real_type;\n    using coord_type          = traits_type::coordinate_type;\n    using boundary_type       = traits_type::boundary_type;\n    using system_type         = mjolnir::System<traits_type>;\n    using potential_type       = mjolnir::ClementiDihedralPotential<real_type>;\n    using dihedral_angle_type = mjolnir::DihedralAngleInteraction<traits_type, potential_type>;\n\n    const real_type k1(1e0);\n    const real_type k3(1e0);\n    const real_type native(mjolnir::math::constants<real_type>::pi() / 2.0);\n\n    std::mt19937 mt(123456789);\n    std::uniform_real_distribution<real_type> uni(-1.0, 1.0);\n\n    potential_type potential{k1, k3, native};\n    dihedral_angle_type interaction(\"none\", {{ {{0,1,2,3}}, potential}});\n\n    for(std::size_t i=0; i<100; ++i)\n    {\n        system_type sys(4, boundary_type{});\n\n        sys.mass (0) = 1.0;\n        sys.mass (1) = 1.0;\n        sys.mass (2) = 1.0;\n        sys.mass (3) = 1.0;\n        sys.rmass(0) = 1.0;\n        sys.rmass(1) = 1.0;\n        sys.rmass(2) = 1.0;\n        sys.rmass(3) = 1.0;\n\n        sys.position(0) = coord_type(2.0 + 1e-2 * uni(mt), 0.0 + 1e-2 * uni(mt),  1.0 + 1e-2 * uni(mt));\n        sys.position(1) = coord_type(1.0 + 1e-2 * uni(mt), 1.0 + 1e-2 * uni(mt),  0.0 + 1e-2 * uni(mt));\n        sys.position(2) = coord_type(0.0 + 1e-2 * uni(mt), 0.0 + 1e-2 * uni(mt),  0.0 + 1e-2 * uni(mt));\n        sys.position(3) = coord_type(1.0 + 1e-2 * uni(mt), 1.0 + 1e-2 * uni(mt), -1.0 + 1e-2 * uni(mt));\n        sys.velocity(0) = coord_type(0.0, 0.0,  0.0);\n        sys.velocity(1) = coord_type(0.0, 0.0,  0.0);\n        sys.velocity(2) = coord_type(0.0, 0.0,  0.0);\n        sys.velocity(3) = coord_type(0.0, 0.0,  0.0);\n        sys.force   (0) = coord_type(0.0, 0.0,  0.0);\n        sys.force   (1) = coord_type(0.0, 0.0,  0.0);\n        sys.force   (2) = coord_type(0.0, 0.0,  0.0);\n        sys.force   (3) = coord_type(0.0, 0.0,  0.0);\n\n        sys.at(0).name  = \"X\";\n        sys.at(1).name  = \"X\";\n        sys.at(2).name  = \"X\";\n        sys.at(3).name  = \"X\";\n        sys.at(0).group = \"NONE\";\n        sys.at(1).group = \"NONE\";\n        sys.at(2).group = \"NONE\";\n        sys.at(3).group = \"NONE\";\n\n        constexpr real_type tol = 1e-4;\n        auto ref_sys = sys;\n\n        const auto energy = interaction.calc_force_and_energy(sys);\n        const auto ref_energy = interaction.calc_energy(ref_sys);\n        interaction.calc_force(ref_sys);\n        BOOST_TEST(ref_energy == energy, boost::test_tools::tolerance(tol));\n\n        for(std::size_t idx=0; idx<sys.size(); ++idx)\n        {\n            BOOST_TEST(mjolnir::math::X(sys.force(idx)) == mjolnir::math::X(ref_sys.force(idx)), boost::test_tools::tolerance(tol));\n            BOOST_TEST(mjolnir::math::Y(sys.force(idx)) == mjolnir::math::Y(ref_sys.force(idx)), boost::test_tools::tolerance(tol));\n            BOOST_TEST(mjolnir::math::Z(sys.force(idx)) == mjolnir::math::Z(ref_sys.force(idx)), boost::test_tools::tolerance(tol));\n        }\n    }\n}\n", "meta": {"hexsha": "a5f44e34996d7cc67e06848c28bb13304d3e6955", "size": 14408, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/core/test_dihedral_angle_interaction.cpp", "max_stars_repo_name": "yutakasi634/Mjolnir", "max_stars_repo_head_hexsha": "ab7a29a47f994111e8b889311c44487463f02116", "max_stars_repo_licenses": ["MIT"], "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/core/test_dihedral_angle_interaction.cpp", "max_issues_repo_name": "yutakasi634/Mjolnir", "max_issues_repo_head_hexsha": "ab7a29a47f994111e8b889311c44487463f02116", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-07T11:41:45.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-08T10:01:38.000Z", "max_forks_repo_path": "test/core/test_dihedral_angle_interaction.cpp", "max_forks_repo_name": "yutakasi634/Mjolnir", "max_forks_repo_head_hexsha": "ab7a29a47f994111e8b889311c44487463f02116", "max_forks_repo_licenses": ["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.4719101124, "max_line_length": 132, "alphanum_fraction": 0.5625347029, "num_tokens": 4520, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.46025819867157386}}
{"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_MOD_HPP_INCLUDED\n#define BOOST_SIMD_TOOLBOX_ARITHMETIC_FUNCTIONS_SCALAR_MOD_HPP_INCLUDED\n#include <boost/simd/toolbox/arithmetic/functions/mod.hpp>\n#include <boost/simd/include/functions/scalar/idivfloor.hpp>\n/////////////////////////////////////////////////////////////////////////////\n// The mod function computes the remainder of dividing x by y.  The\n// return value is x-n*y, where n is the value x / y, rounded to -inf.\n/////////////////////////////////////////////////////////////////////////////\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::mod_, tag::cpu_\n                            , (A0)\n                            , (scalar_< arithmetic_<A0> >)\n                              (scalar_< arithmetic_<A0> >)\n                            )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    {\n      return a1 ? a0-a1*boost::simd::idivfloor(a0,a1) : a0;\n    }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "9825f2dbd0940e0d6cc81826cf17a4719bba765d", "size": 1531, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/arithmetic/include/boost/simd/toolbox/arithmetic/functions/scalar/mod.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/mod.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/mod.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.5277777778, "max_line_length": 80, "alphanum_fraction": 0.5022860875, "num_tokens": 320, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375735, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.46009796855120716}}
{"text": "#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <boost/bind.hpp>\n#include \"../library/MPC.h\"\n#include \"../library/Consensus.h\"\n#include \"../library/IOEigen.h\"\n/**************************** ROS libraries****************************/\n#include <ros/ros.h>\n#include <trajectory_msgs/MultiDOFJointTrajectory.h>\n#include <mav_msgs/conversions.h>\n#include <geometry_msgs/PointStamped.h>\n#include <geometry_msgs/Twist.h>\n#include <gazebo_msgs/GetModelState.h>\n#include <gazebo_msgs/GetWorldProperties.h>\n\n/************************** C++ libraries *****************************/\n#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <string>\n#include <fstream>\n\n//using namespace Foap;\n//using namespace IOeigen;\n\n/**************************Functions declarations *********************/\nvoid positionCallback(const geometry_msgs::PointStamped::ConstPtr& msg, int index);\nvoid getCurrentPose(Eigen::MatrixXd &q);\nvoid controlsCallback(const geometry_msgs::Twist::ConstPtr& msg, int index);\nvoid getComputedControls(Eigen::MatrixXd &q);\nbool readMatrix(std::string filename, Eigen::MatrixXd &M);\n\n/*************************** Global variables *************************/\n#define DEBUG 0\n\nint agent = 3;\n\nbool leader = false;\n\nEigen::IOFormat OctaveFmt(Eigen::StreamPrecision, 0, \", \", \";\\n\", \"\", \"\", \"[\", \"]\");\nstd::string sep = \"\\n----------------------------------------\\n\";\n\n// path and gazebo envoronment input names\nstd::string path = \"resource/\";\nstd::string A_filename = path+\"A.dat\";\nstd::string d_filename = path+\"d.dat\";\nstd::string simulation_filename = path+\"sim.dat\";\nstd::string MPC_filename = path+\"MPC.dat\";\nstd::string consensus_filename = path+\"consensus.dat\";\nbool status_file;\nstd::string robot_name = \"hummingbird_\"; // same as mav_name in launchfile\nstd::string obstacle_name = \"obstacle\";\nstd::string relativeEntityName = \"world\" ;\n\n// output filename\nstd::string output_path = \"output/data/\";\nstd::string q_test_filename = output_path+\"q_test.dat\";//agents position\nstd::string q_odom_filename = output_path+\"q_odom.dat\";\nstd::string adjacency_mat_filename = output_path+\"adjacency_mat.dat\";\nstd::string laplacian_mat_filename = output_path+\"laplacian_mat.dat\";\nstd::string q0_mat_filename = output_path+\"q0_mat.dat\";\nstd::string z_mat_filename = output_path+\"z_mat.dat\";\nstd::string q_obst_filename = output_path+\"q_obst.dat\";// obstacles' position\nstd::string qp_agent_filename = output_path+\"qp_agent_\"+std::to_string(agent)+\".dat\";//agents' velocities\nstd::string e_consensus_filename = output_path+\"e_consensus.dat\";//agents' velocities\nstd::string e_consensus_agents_filename = output_path+\"e_consensus_agents.dat\";//agents' velocities\nstd::string qz_agents_filename = output_path+\"qz_agents.dat\";\nstd::string qp_computed_controls_filename = output_path+\"qp_computed_controls.dat\";\n\n// pub & suv variables name\nstd::string slash(\"/\");\nstd::string publisher_name = \"/command/trajectory\";\nstd::string subscriber_name = \"/ground_truth/position/\";\nstd::string topic_controls = \"/controls/computed_u\";\n\n// ros msg's\nstd::vector<geometry_msgs::PointStamped> pos_msg;\nstd::vector<geometry_msgs::Twist> controls_msg;\n\n// system dimentions\nint n_robots = 0, dim = 3, n_models = 0, n_obstacles = 0;\n\n// Gains of predefined consensus\ndouble kf=20;\n\nint main(int argc, char **argv){\n  ros::init(argc,argv,\"uav_\"+std::to_string(agent)+\"_control\");\n  ros::NodeHandle nh(\"~\");\n  std::string multi_uav_control_path;\n  nh.getParam(\"resources_path\", multi_uav_control_path);\n  std::cout << multi_uav_control_path << std::endl;\n    /************************ Read input paramaters *****************/\n    Eigen::MatrixXd A, d_matrix;\n\n    status_file = readMatrix(multi_uav_control_path+A_filename, A);\n    std::cout<<A<<std::endl;\n    if(!status_file){\n        std::cout << \"[ERR] Could not read adjacency matrix file \" << std::endl;\n        std::cout << multi_uav_control_path+A_filename << std::endl;\n        return 1;\n    }\n\n    status_file =  readMatrix(multi_uav_control_path+d_filename, d_matrix);\n    if(!status_file){\n        std::cout << \"[ERR] Could not read displacements file \" << std::endl;\n        return 1;\n    }\n\n    if(A.cols() != d_matrix.cols()){\n      std::cout << \"[ERR] Sizes do not match \" << std::endl;\n        return 1;\n    }\n\n    /************************** Get World Properties ******************/\n    /*** Get initial position of robots and obstacles from world properties ***/\n    // resize q0 & qobs\n    Eigen::MatrixXd q0, qobs, qz;\n    n_robots = A.cols();\n    q0.resize(dim, n_robots);\n    qz.resize(dim,n_robots);\n\n    gazebo_msgs::GetModelState getModelState;\n    geometry_msgs::Point pp;\n    ros::ServiceClient gms_c = nh.serviceClient<gazebo_msgs::GetModelState>(\"/gazebo/get_model_state\") ;\n    ros::ServiceClient gwp_c = nh.serviceClient<gazebo_msgs::GetWorldProperties>(\"/gazebo/get_world_properties\");\n    gazebo_msgs::GetWorldProperties gwp_s;\n    if (gwp_c.call(gwp_s)){\n        std::vector<std::string> models = gwp_s.response.model_names;\n        n_models = (int)models.size();\n        ROS_INFO(\"Number of models: %i\", n_models);\n        if(n_models==1){ // only and empty world has been loaded\n            ROS_ERROR(\"An empty world as been loaded\");\n            return 1;\n        }\n        // compare if the Adjancency matrix size is equal to the number of robots\n        if(n_robots > (n_models-1)){\n            ROS_ERROR(\"Number of robots don't match with the Adjancency matrix\");\n            return 1;\n        }\n\n        // resize qobs\n        n_obstacles = n_models-n_robots-1;\n        if(n_obstacles>0){\n            qobs.resize(dim, n_obstacles);\n        }\n\n        //sort the name models to find the robots & obstacles initial positions:\n        // models[0] = ground_plane, models[1, n_robots+1] = robots, models[n_robots+2, end] = obstacles\n        std::sort(models.begin(), models.end());\n        Eigen::VectorXd current_pose(dim); // assume a 3D pose, change dim to add more dimension: e.x: [x, y, z, yaw]\n        // get robots position\n        for(int i=0; i<n_robots; i++){\n            getModelState.request.model_name = models[i+1];\n            getModelState.request.relative_entity_name = relativeEntityName ;\n            gms_c.call(getModelState);\n            pp = getModelState.response.pose.position;\n            current_pose << pp.x, pp.y, pp.z;\n            q0.col(i) = current_pose;\n\n        }\n\n        // get obstacles positions\n        if(n_obstacles>0){\n            for(int i=0; i<n_obstacles; i++){\n                getModelState.request.model_name = models[n_robots+i+1];\n                getModelState.request.relative_entity_name = relativeEntityName ;\n                gms_c.call(getModelState);\n                pp = getModelState.response.pose.position;\n                current_pose << pp.x, pp.y, 1.0; // the obstacles are fixed in z = 1.0\n                qobs.col(i) = current_pose;\n            }\n         // save data to files\n    \t//IOEigen::writeMatrix(q_obst_filename, qobs);\n\t}\n\n        ROS_INFO(\"Number of robots: %i\", n_robots);\n        ROS_INFO(\"Number of obstacles: %i\", n_obstacles);\n\n        ROS_INFO(\"Number of current agent: %i\", agent);\n\n        std::cout << \"Init robot positions: \\n\" << q0.format(OctaveFmt) << sep;\n\n        if(n_obstacles > 0)\n            std::cout << \"Init obstacles positions: \\n\" << qobs.format(OctaveFmt) << sep;\n    }\n    else{\n        ROS_ERROR(\"Failed to call service get_world_properties\");\n        return 1;\n    }\n\n\n    /***************************** Pub's & Sub's *********************/\n    pos_msg.resize(n_robots);\n    std::string topic_pub;\n    ros::Publisher pose_pub;\n    std::vector<std::string> topic_sub(n_robots);\n    std::vector<ros::Subscriber> pose_sub(n_robots);\n    trajectory_msgs::MultiDOFJointTrajectory MultiDOF_msg;\n    ros::Rate rate(10);\n    for(int i=0; i<n_robots; i++){\n        topic_sub[i] = slash + robot_name + std::to_string(i) + subscriber_name;\n        pose_sub[i] = nh.subscribe<geometry_msgs::PointStamped>(topic_sub[i],1,boost::bind(positionCallback, _1, i));\n    }\n\n    topic_pub = slash + robot_name + std::to_string(agent) + publisher_name;\n    pose_pub = nh.advertise<trajectory_msgs::MultiDOFJointTrajectory>(topic_pub,1);\n\n    //Distributed topics\n    controls_msg.resize(n_robots);\n    std::string topic_control_pub;\n    ros::Publisher controls_pub;\n    std::vector<std::string> controls_topic_sub(n_robots);\n    std::vector<ros::Subscriber> controls_sub(n_robots);\n\n    for(int i=0; i<n_robots; i++){\n        controls_topic_sub[i] = slash + robot_name + std::to_string(i) + topic_controls;\n        controls_sub[i] = nh.subscribe<geometry_msgs::Twist>(controls_topic_sub[i],1,boost::bind(controlsCallback, _1, i));\n    }\n\n    topic_control_pub = slash + robot_name + std::to_string(agent) + topic_controls;\n    controls_pub = nh.advertise<geometry_msgs::Twist>(topic_control_pub, 1);\n\n\n\n    /********************** Compute L, D, qz ******************************/\n    Eigen::MatrixXd L, eta, etaA;\n    L = Consensus::laplacian(A);\n    /******************** System inicialization ***************************/\n    Eigen::VectorXd qpz_e = Eigen::VectorXd::Zero(n_robots*dim);\n    Eigen::VectorXd e_qz = Eigen::VectorXd::Zero(n_robots*dim);\n    Eigen::MatrixXd q_odom(dim, n_robots);\n    Eigen::MatrixXd q_controls(dim, n_robots);\n\n    Eigen::MatrixXd qz_centroid;\n    Eigen::VectorXd robot_new_pose;\n    Eigen::VectorXd q_test, e_c, e_c_L2, e_cons, p_ia, q_c, e_0;\n\n    qz = q0 - d_matrix;\n\n    /************************ Read data parameters *************************/\n    Eigen::MatrixXd tmp; // tmp matrix to read paraneters\n\n    int updated = 0, steps = 0, counter = 0, Hp = 0, Hu = 0, Hw = 0;\n    //Simulation\n    double epsilon, t_old, t_new, dt, t = 0, tf, d, k1, p_gain, lambda;\n    //MPC\n    double cost_x, cost_u, D, k_d, E, k_e, min_u, max_u, minx, maxx, miny, maxy, minz, maxz;\n\n    double tf2=4;\n    Eigen::VectorXd ratios(2);\n    Eigen::VectorXd system_params;\n    readMatrix(simulation_filename, tmp);\n    if(tmp.rows() < 3){\n        std::cout << \"Default system simulations params inicialization\" << std::endl;\n        epsilon = 0.05; dt = d = 0.01; tf = 10.0;\n    }\n    else{\n        epsilon = tmp(0,0); dt = d = tmp(1,0); tf = tmp(2,0);\n    }\n\n    readMatrix(MPC_filename, tmp);\n    if(tmp.rows() < 17){\n        std::cout << \"Default system MPC params inicialization\" << std::endl;\n        Hp = 15; Hu = 10; Hw = 1; cost_x = 1000.0; cost_u = 1.0;\n        D = 0.5; k_d = 10.0; E = 2.25; k_e = 1.0;\n        min_u = -10.0; max_u = 10.0;\n        minx = -3.0; maxx = 4.0; miny = -3.0; maxy = 4.0; minz = 0.3; maxz = 2.5;\n    }\n    else{\n        Hp = int(tmp(0,0)); Hu = int(tmp(1,0)); Hw = int(tmp(2,0)); cost_x = tmp(3,0); cost_u = tmp(4,0);\n        D = tmp(5,0); k_d = tmp(6,0); E = tmp(7,0); k_e = tmp(8,0);\n        min_u = tmp(9,0); max_u = tmp(10,0);\n        minx = tmp(11,0); maxx = tmp(12,0); miny = tmp(13,0); maxy = tmp(14,0); minz = tmp(15,0); maxz = tmp(16,0);\n    }\n\n    std::cout << \"Simulation inicialization\" << sep;\n\n    steps = tf/dt;\n\n\n    /************************ Data storage variables ***********************/\n    Eigen::MatrixXd q_odom_data(dim*n_robots, steps+1);\n    Eigen::MatrixXd qp_agent_data(dim, steps+1); //Velocities of agent\n    Eigen::MatrixXd qp_computed_controls_data(dim*n_robots, steps+1);\n    Eigen::MatrixXd e_consensus_data(dim*n_robots, steps+1);// Consensus of virtual system\n \tEigen::MatrixXd qz_data_agents(dim*n_robots, steps+1);\n    /*************************** Start simulation ***********************/\n    bool trajectory = false;\n\n    /************************************* START SIMULATION ************************************/\n    while(ros::ok()){\n        if(counter > steps)\n            break;\n\n        // hold for updates\n        if(updated < 2){\n            rate.sleep();\n            updated+=1;\n            continue;\n        }\n\n\n        ros::spinOnce();\n\n        getCurrentPose(q_odom);\n\n        qz = q_odom - d_matrix;\n        e_qz = Consensus::consensus_error(L, qz);\n        e_c_L2 = Consensus::norm_consensus_error(e_qz, n_robots);\n\n        q_odom_data.col(counter) = Consensus::matrix2vector(q_odom);\n\t\te_consensus_data.col(counter)=e_qz;\n\t\tqz_data_agents.col(counter)=Consensus::matrix2vector(qz);\n\n        if(e_c_L2.maxCoeff()<epsilon)\n        {\n           ROS_INFO(\"Consensus reached\");\n            break;\n        }\n\n        MPC mpc_control(dim, Hp, Hu, Hw, dt, cost_x, cost_u, min_u, max_u);\n\n        mpc_control.set_reference(qz, A.col(agent), n_robots, agent);\n\n        for (int i = 0; i < n_robots; i++)\n        {\n            if (A(i,agent) == 1)\n            {\n                mpc_control.add_obstacle_constraint_column(q_odom.col(i), q_odom.col(agent), D);\n                mpc_control.add_obstacle_penalty_column(q_odom.col(i), q_odom.col(agent), D, k_d);\n                mpc_control.add_connectivity_constraint(q_odom.col(i), q_odom.col(agent), E);\n                mpc_control.add_connectivity_penalty(q_odom.col(i), q_odom.col(agent), E, k_e);\n            }\n        }\n\n        for (int i = 0; i < n_obstacles; i++)\n        {\n            mpc_control.add_obstacle_constraint_column(qobs.col(i), q_odom.col(agent), D);\n            mpc_control.add_obstacle_penalty_column(qobs.col(i), q_odom.col(agent), D, k_d);\n        }\n\n        //mpc_control.set_lower_constraint(q_odom.col(agent), minz);\n        mpc_control.set_box_constraints(q_odom.col(agent), minx, maxx, miny, maxy, minz, maxz);\n\n        Eigen::VectorXd solMPC(dim*Hu);\n\n        int success_mpc;\n\n        success_mpc = mpc_control.compute_control(solMPC);\n\n        Eigen::VectorXd vel(dim);\n        for (int i=0; i < dim; i++)\n            vel(i) = solMPC[i];\n\n        //Publish computed controls\n        geometry_msgs::Twist c_msg;\n        c_msg.linear.x = vel(0); c_msg.linear.y = vel(1); c_msg.linear.z = vel(2);\n        controls_pub.publish(c_msg);\n\n        //Read published controls\n        getComputedControls(q_controls);\n\n        qp_computed_controls_data.col(counter) = Consensus::matrix2vector(q_controls);\n\n        //Distributed control\n        MPC mpc_control2(dim, Hp, Hu, Hw, dt, cost_x, cost_u, min_u, max_u);\n\n        mpc_control2.set_reference(qz, A.col(agent), n_robots, agent, q_controls);\n\n        for (int i = 0; i < n_robots; i++)\n        {\n            if (A(i,agent) == 1)\n            {\n                mpc_control2.add_obstacle_constraint_column(q_odom.col(i), q_odom.col(agent), q_controls.col(i), D);\n                mpc_control2.add_obstacle_penalty_column(q_odom.col(i), q_odom.col(agent), q_controls.col(i), D, k_d);\n                mpc_control2.add_connectivity_constraint(q_odom.col(i), q_odom.col(agent), q_controls.col(i), E);\n                mpc_control2.add_connectivity_penalty(q_odom.col(i), q_odom.col(agent), q_controls.col(i), E, k_e);\n            }\n        }\n\n        for (int i = 0; i < n_obstacles; i++)\n        {\n            mpc_control2.add_obstacle_constraint_column(qobs.col(i), q_odom.col(agent), D);\n            mpc_control2.add_obstacle_penalty_column(qobs.col(i), q_odom.col(agent), D, k_d);\n        }\n\n        //mpc_control2.set_lower_constraint(q_odom.col(agent), minz);\n        mpc_control2.set_box_constraints(q_odom.col(agent), minx, maxx, miny, maxy, minz, maxz);\n\n        success_mpc = mpc_control2.compute_control(solMPC);\n\n        for (int i=0; i < dim; i++)\n            vel(i) = solMPC[i];\n\n        qp_agent_data.col(counter) = vel;\n\n        robot_new_pose = q_odom.col(agent) + dt*vel;\n\n        //std::cout << robot_new_pose(0) << \" \" << robot_new_pose(1) << \" \" << robot_new_pose(2) << sep;\n\n        // set MultiDOF msg\n        trajectory_msgs::MultiDOFJointTrajectory msg;\n        msg.header.stamp=ros::Time::now();\n        mav_msgs::msgMultiDofJointTrajectoryFromPositionYaw(robot_new_pose, 1 , &msg);\n        pose_pub.publish(msg);\n\n        counter++;\n        t+=dt;\n        rate.sleep();\n    }\n\n    std::cout << \"Consensus reached in \" << counter << \" steps \" << sep;\n\n    std::cout << \"Final error = \" << e_c_L2.maxCoeff() << std::endl;\n    std::cout << \"Error vector\" << std::endl << e_c_L2 << sep;\n\n    // save data to files\n    if (leader)\n    {\n        IOEigen::writeMatrix(q_odom_filename, q_odom_data.block(0, 0, dim*n_robots, counter), true);\n        IOEigen::writeMatrix(qp_agent_filename, qp_agent_data.block(0, 0, dim, counter), true);\n        IOEigen::writeMatrix(e_consensus_filename, e_consensus_data.block(0, 0, dim*n_robots, counter), true);\n        IOEigen::writeMatrix(qp_computed_controls_filename, qp_computed_controls_data.block(0, 0, dim*n_robots, counter), true);\n    \tIOEigen::writeMatrix(qz_agents_filename, qz_data_agents.block(0, 0, dim*n_robots, counter), true);\n\n        system(\"python /home/cimat/bebop_ws/src/multi_uav_control/src/library/plots.py\");\n    }\n    else\n    {\n        IOEigen::writeMatrix(qp_agent_filename, qp_agent_data.block(0, 0, dim, counter), true);\n    }\n\n    return 0;\n}\n\n\n/*\nMultiple pose callback.\nReturn the pose of the i-robot\n*/\nvoid positionCallback(const geometry_msgs::PointStamped::ConstPtr& msg, int index){\n        pos_msg[index].point.x = msg->point.x;\n        pos_msg[index].point.y = msg->point.y;\n        pos_msg[index].point.z = msg->point.z;\n}\n\n/*\nGet current pose from odometry for each robot\n*/\nvoid getCurrentPose(Eigen::MatrixXd &q){\n    Eigen::VectorXd current_pose(3);\n    for(int i=0; i<n_robots; i++){\n        current_pose(0) = pos_msg[i].point.x; current_pose(1) = pos_msg[i].point.y; current_pose(2) = pos_msg[i].point.z;\n        q.col(i) = current_pose;\n    }\n}\n\n/*\nMultiple controls callback.\nReturn the controls of the i-robot\n*/\nvoid controlsCallback(const geometry_msgs::Twist::ConstPtr& msg, int index){\n        controls_msg[index].linear.x = msg->linear.x;\n        controls_msg[index].linear.y = msg->linear.y;\n        controls_msg[index].linear.z = msg->linear.z;\n}\n\n/*\nGet computed controls for each robot\n*/\nvoid getComputedControls(Eigen::MatrixXd &q){\n    Eigen::VectorXd computed_controls(3);\n    for(int i=0; i<n_robots; i++){\n        computed_controls(0) = controls_msg[i].linear.x; computed_controls(1) = controls_msg[i].linear.y; computed_controls(2) = controls_msg[i].linear.z;\n        q.col(i) = computed_controls;\n    }\n}\n\nbool readMatrix(std::string filename, Eigen::MatrixXd &M){\n    std::ifstream fin(filename.c_str());\n    if(!fin.good()){\n            return false;\n    }\n    int rows, cols;\n    //read header matrix Name rows cols\n    fin >> rows; fin >> cols;\n    M.resize(rows,cols);\n    for(int i=0; i<rows; i++){\n        for(int j=0; j<cols; j++){\n            fin >> M(i,j);\n        }\n    }\n\n    return true;\n}\n", "meta": {"hexsha": "1007795a904b07ed0bc61b2aff3980a969556d06", "size": 18599, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/multi_uav_control/src/nodes/distributed_control_node_uav_3.cpp", "max_stars_repo_name": "cimat-ris/quadrotor-simulation-gazebo", "max_stars_repo_head_hexsha": "e3917870f4ab28a0278588676359571201e77451", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/multi_uav_control/src/nodes/distributed_control_node_uav_3.cpp", "max_issues_repo_name": "cimat-ris/quadrotor-simulation-gazebo", "max_issues_repo_head_hexsha": "e3917870f4ab28a0278588676359571201e77451", "max_issues_repo_licenses": ["Apache-2.0"], "max_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_uav_control/src/nodes/distributed_control_node_uav_3.cpp", "max_forks_repo_name": "cimat-ris/quadrotor-simulation-gazebo", "max_forks_repo_head_hexsha": "e3917870f4ab28a0278588676359571201e77451", "max_forks_repo_licenses": ["Apache-2.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.497983871, "max_line_length": 154, "alphanum_fraction": 0.6172912522, "num_tokens": 4940, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4600979685512071}}
{"text": "#include <cctbx/boost_python/flex_fwd.h>\n#include <boost/python/module.hpp>\n#include <boost/python/def.hpp>\n#include <cfloat>\n#include <cctbx/uctbx/determine_unit_cell/NCDist.h>\n#include <scitbx/array_family/tiny.h>\n#include <scitbx/array_family/flex_types.h>\n#include <scitbx/array_family/versa.h>\n#include <scitbx/array_family/shared.h>\n#include <scitbx/array_family/accessors/c_grid.h>\n#include <omptbx/omp_or_stubs.h>\nnamespace af = scitbx::af;\n\nusing namespace boost::python;\n\nnamespace cctbx { namespace uctbx {\n\n  double NCDist_wrapper(af::tiny<double,6> mm1,af::tiny<double,6> mm2){\n    return NCDist(&mm1[0],&mm2[0]);\n  }\n\n  scitbx::af::versa<double, scitbx::af::c_grid<2> > NCDist_matrix(scitbx::af::shared<double> MM){\n    int NN = MM.size()/6;\n    af::versa<double, af::c_grid<2> > result( af::c_grid<2> (NN,NN));\n    double* MM_ptr = MM.begin();\n    double* result_ptr = result.begin();\n\n    # pragma omp parallel\n    {\n    # pragma omp for\n    for (int i = 0; i < NN; ++i) {\n      af::tiny<double,6> mm1(&(MM_ptr[i*6]), &(MM_ptr[(i+1)*6]));\n      for (int j = i+1; j < NN; ++j) {\n        af::tiny<double,6> mm2(&(MM_ptr[j*6]), &(MM_ptr[(j+1)*6]));\n        double metric = NCDist(&mm1[0],&mm2[0]);\n        result_ptr[i*NN + j] = metric;\n        result_ptr[j*NN + i] = metric;\n      }\n    }\n    }\n    return result;\n  }\n\n  scitbx::af::versa<double, scitbx::af::c_grid<2> > NCDist_flatten(scitbx::af::shared<double> MM){\n    int NN = MM.size()/6;\n    af::versa<double, af::c_grid<2> > result( af::c_grid<2> (NN,NN));\n    double* MM_ptr = MM.begin();\n    double* result_ptr = result.begin();\n    // figure out the number of non-diagonal elements in an NN x NN square matrix\n    int n_elements = (NN*NN-NN)/2;\n    # pragma omp parallel\n    {\n    # pragma omp for\n    for (int idx = 0; idx < n_elements; ++idx) {\n      // Given idx, can we deduce the i and j upper-triangular coordinates?\n      double quad_a = -0.5;\n      double quad_b = (NN-0.5);\n      double quad_c = -(double)(idx);\n      double radical = std::sqrt(quad_b*quad_b - 4.*quad_a*quad_c);\n      int i = (int)( (-quad_b + radical)/ (2.*quad_a) );\n      int total_count_above_row_i=(NN*i)-((i*i-i)/2)-i;\n      int j = idx - total_count_above_row_i + (i+1);\n      // for the NCDist metric, pass in pointers to the two metrical matrices\n      double metric = NCDist(&(MM_ptr[i*6]),&(MM_ptr[j*6]));\n      result_ptr[i*NN + j] = metric;\n      result_ptr[j*NN + i] = metric;\n      }\n    }\n    return result;\n  }\n\n}}\n\n// Contingent upon Andrews-Bernstein NCDist repository\n# if HAVE_NCDIST\nnamespace ncdist2017 {\n#include <NCDist.h>\n#include <CS6Dist.h>\n}\n\nnamespace cctbx { namespace uctbx {\n\n  double NCDist2017_wrapper(af::tiny<double,6> mm1,af::tiny<double,6> mm2){\n    return ncdist2017::NCDist(&mm1[0],&mm2[0]);\n  }\n\n  double CS6Dist_wrapper(af::tiny<double,6> mm1,af::tiny<double,6> mm2){\n    return ncdist2017::CS6Dist(&mm1[0],&mm2[0]);\n  }\n\n  double CS6Dist_in_G6_wrapper(af::tiny<double,6> mm1,af::tiny<double,6> mm2){\n    return ncdist2017::CS6Dist_in_G6(&mm1[0],&mm2[0]);\n  }\n\n  scitbx::af::versa<double, scitbx::af::c_grid<2> > NCDist2017_flatten(scitbx::af::shared<double> MM){\n    int NN = MM.size()/6;\n    af::versa<double, af::c_grid<2> > result( af::c_grid<2> (NN,NN));\n    double* MM_ptr = MM.begin();\n    double* result_ptr = result.begin();\n    // figure out the number of non-diagonal elements in an NN x NN square matrix\n    int n_elements = (NN*NN-NN)/2;\n    # pragma omp parallel\n    {\n    # pragma omp for\n    for (int idx = 0; idx < n_elements; ++idx) {\n      // Given idx, can we deduce the i and j upper-triangular coordinates?\n      double quad_a = -0.5;\n      double quad_b = (NN-0.5);\n      double quad_c = -(double)(idx);\n      double radical = std::sqrt(quad_b*quad_b - 4.*quad_a*quad_c);\n      int i = (int)( (-quad_b + radical)/ (2.*quad_a) );\n      int total_count_above_row_i=(NN*i)-((i*i-i)/2)-i;\n      int j = idx - total_count_above_row_i + (i+1);\n      // for the NCDist metric, pass in pointers to the two metrical matrices\n      double metric = ncdist2017::NCDist(&(MM_ptr[i*6]),&(MM_ptr[j*6]));\n      result_ptr[i*NN + j] = metric;\n      result_ptr[j*NN + i] = metric;\n      }\n    }\n    return result;\n  }\n\n  scitbx::af::versa<double, scitbx::af::c_grid<2> > CS6Dist_in_G6_flatten(scitbx::af::shared<double> MM){\n    int NN = MM.size()/6;\n    scitbx::af::shared<double> MM_S6(MM.size());\n    af::versa<double, af::c_grid<2> > result( af::c_grid<2> (NN,NN));\n    double* MM_ptr = MM.begin();\n    double* MM_S6_ptr = MM_S6.begin();\n    double* result_ptr = result.begin();\n    // Convert NN primitive Niggli-reduced G6 cells to Selling-reduced S6 cells\n    # pragma omp parallel\n    {\n    # pragma omp for\n    for (int idx = 0; idx < NN; ++idx){\n         ncdist2017::G6toS6Reduce(&MM_ptr[idx*6],&MM_S6_ptr[idx*6]);\n      }\n    }\n    // figure out the number of non-diagonal elements in an NN x NN square matrix\n    int n_elements = (NN*NN-NN)/2;\n    # pragma omp parallel\n    {\n    # pragma omp for\n    for (int idx = 0; idx < n_elements; ++idx) {\n      // Given idx, can we deduce the i and j upper-triangular coordinates?\n      double quad_a = -0.5;\n      double quad_b = (NN-0.5);\n      double quad_c = -(double)(idx);\n      double radical = std::sqrt(quad_b*quad_b - 4.*quad_a*quad_c);\n      int i = (int)( (-quad_b + radical)/ (2.*quad_a) );\n      int total_count_above_row_i=(NN*i)-((i*i-i)/2)-i;\n      int j = idx - total_count_above_row_i + (i+1);\n      //\n      double metric = ncdist2017::CS6Dist(&(MM_ptr[i*6]),&(MM_ptr[j*6]));\n      result_ptr[i*NN + j] = metric;\n      result_ptr[j*NN + i] = metric;\n      }\n    }\n    return result;\n  }\n  scitbx::af::versa<double, scitbx::af::c_grid<2> > Euclidean_L2norm_flatten(scitbx::af::shared<double> MM){\n    int NN = MM.size()/6;\n    af::versa<double, af::c_grid<2> > result( af::c_grid<2> (NN,NN));\n    double* MM_ptr = MM.begin();\n    double* result_ptr = result.begin();\n    // figure out the number of non-diagonal elements in an NN x NN square matrix\n    int n_elements = (NN*NN-NN)/2;\n    # pragma omp parallel\n    {\n    # pragma omp for\n    for (int idx = 0; idx < n_elements; ++idx) {\n      // Given idx, can we deduce the i and j upper-triangular coordinates?\n      double quad_a = -0.5;\n      double quad_b = (NN-0.5);\n      double quad_c = -(double)(idx);\n      double radical = std::sqrt(quad_b*quad_b - 4.*quad_a*quad_c);\n      int i = (int)( (-quad_b + radical)/ (2.*quad_a) );\n      int total_count_above_row_i=(NN*i)-((i*i-i)/2)-i;\n      int j = idx - total_count_above_row_i + (i+1);\n      double a1 = std::sqrt(MM_ptr[i*6]);\n      double a2 = std::sqrt(MM_ptr[j*6]);\n      double d_a = a1-a2;\n      double b1 = std::sqrt(MM_ptr[i*6+1]);\n      double b2 = std::sqrt(MM_ptr[j*6+1]);\n      double d_b = b1-b2;\n      double c1 = std::sqrt(MM_ptr[i*6+2]);\n      double c2 = std::sqrt(MM_ptr[j*6+2]);\n      double d_c = c1-c2;\n\n      double metric = std::sqrt(d_a*d_a + d_b*d_b + d_c*d_c);\n\n      result_ptr[i*NN + j] = metric;\n      result_ptr[j*NN + i] = metric;\n      }\n    }\n    return result;\n  }\n\n}}\n# endif // HAVE_NCDIST\n\nBOOST_PYTHON_MODULE(determine_unit_cell_ext)\n{\n  def (\"NCDist\",&cctbx::uctbx::NCDist_wrapper);\n  def (\"NCDist_matrix\",&cctbx::uctbx::NCDist_matrix);\n  def (\"NCDist_flatten\",&cctbx::uctbx::NCDist_flatten,\n      \"Obtain an NxN flex versa <double> containing NCDist metrics from a list of N G6 vectors.\\n\"\n      \"The resulting matrix is symmetric.\\n\"\n      \"The G6 vectors [a.a, b.b, c.c, 2*b.c, 2*a.c, 2*a.b]\\n\"\n      \"are to be passed in as a flex.double containing 6*N elements.\\n\"\n      \"It is assumed the a,b,c vectors are primitive, Niggli reduced\\n\"\n      \"Uses 2014 library with FAST=true, skips some of the tests for smaller differences\\n\"\n      );\n# if HAVE_NCDIST\n  def (\"NCDist2017\",&cctbx::uctbx::NCDist2017_wrapper);\n  def (\"CS6Dist\",&cctbx::uctbx::CS6Dist_wrapper);\n  def (\"CS6Dist_in_G6\",&cctbx::uctbx::CS6Dist_in_G6_wrapper,(arg(\"G6cell1\"),arg(\"G6cell2\")),\n      \"Use this in place of the NCDist wrapper when working with G6 arguments\\n\"\n      \"A G6 argument is [a.a, b.b, c.c, 2*b.c, 2*a.c, 2*a.b]\\n\"\n      \"It is assumed the arguments are primitive, Niggli reduced\\n\");\n  def (\"NCDist2017_flatten\",&cctbx::uctbx::NCDist2017_flatten,(arg(\"G6\")),\n      \"Obtain an NxN flex versa <double> containing NCDist metrics from a list of N G6 vectors.\\n\"\n      \"The resulting matrix is symmetric.\\n\"\n      \"The G6 vectors [a.a, b.b, c.c, 2*b.c, 2*a.c, 2*a.b]\\n\"\n      \"are to be passed in as a flex.double containing 6*N elements.\\n\"\n      \"It is assumed the a,b,c vectors are primitive, Niggli reduced\\n\"\n      \"Uses live library with FAST=false, includes the tests for smaller differences\\n\"\n      );\n  def (\"CS6Dist_in_G6_flatten\",&cctbx::uctbx::CS6Dist_in_G6_flatten,(arg(\"G6\")),\n      \"Obtain an NxN flex versa <double> containing S6 metrics from a list of N G6 vectors.\\n\"\n      \"The resulting matrix is symmetric.\\n\"\n      \"The G6 vectors [a.a, b.b, c.c, 2*b.c, 2*a.c, 2*a.b]\\n\"\n      \"are to be passed in as a flex.double containing 6*N elements.\\n\"\n      \"It is assumed the a,b,c vectors are primitive, Niggli reduced\\n\"\n      \"Uses live library with FAST=false, includes the tests for smaller differences\\n\"\n      );\n  def (\"Euclidean_L2norm_flatten\",&cctbx::uctbx::Euclidean_L2norm_flatten,(arg(\"G6\")),\n      \"Obtain an NxN flex versa <double> containing 3-space L2 norm from a list of N G6 vectors.\\n\"\n      \"Note as currently implemented it is NOT a full 6-space distance, only 3-space.\\n\"\n      \"The resulting matrix is symmetric.\\n\"\n      \"The G6 vectors [a.a, b.b, c.c, 2*b.c, 2*a.c, 2*a.b]\\n\"\n      \"are to be passed in as a flex.double containing 6*N elements.\\n\"\n      );\n# endif // HAVE_NCDIST\n}\n", "meta": {"hexsha": "4e6dceef886ab124ada15084b7fad219ffcff687", "size": 9727, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cctbx/uctbx/determine_unit_cell/ext.cpp", "max_stars_repo_name": "dperl-sol/cctbx_project", "max_stars_repo_head_hexsha": "b9e390221a2bc4fd00b9122e97c3b79c632c6664", "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/uctbx/determine_unit_cell/ext.cpp", "max_issues_repo_name": "dperl-sol/cctbx_project", "max_issues_repo_head_hexsha": "b9e390221a2bc4fd00b9122e97c3b79c632c6664", "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/uctbx/determine_unit_cell/ext.cpp", "max_forks_repo_name": "dperl-sol/cctbx_project", "max_forks_repo_head_hexsha": "b9e390221a2bc4fd00b9122e97c3b79c632c6664", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 115.0, "max_forks_repo_forks_event_min_datetime": "2016-11-15T08:17:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T15:30:14.000Z", "avg_line_length": 39.7020408163, "max_line_length": 108, "alphanum_fraction": 0.6273259998, "num_tokens": 3187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673133042217, "lm_q2_score": 0.5660185351961016, "lm_q1q2_score": 0.4600979659852461}}
{"text": "#include <mpl_traj_solver/traj_solver.h>\n#include <fstream>\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n\n// Pass the data into a VoxelMapUtil class for collision checking\n// Plot the result in svg image\ntypedef boost::geometry::model::d2::point_xy<double> point_2d;\nstd::ofstream svg(\"output.svg\");\n// Declare a stream and an SVG mapper\nboost::geometry::svg_mapper<point_2d> mapper(svg, 1000, 1000);\n\nvoid drawTraj(const Trajectory2D& traj, std::string traj_name, std::string traj_color) {\n  // Draw the trajectory\n  double total_t = traj.getTotalTime();\n  printf(\"%s: \\n\", traj_name.c_str());\n  printf(\"   T: %f\\n\", total_t);\n  printf(\"   J(VEL) = %f, J(ACC) = %f, J(JRK) = %f, J(SNP) = %f\\n\",\n         traj.J(Control::VEL), traj.J(Control::ACC), traj.J(Control::JRK), traj.J(Control::SNP));\n  int num = 200; // number of points on trajectory to draw\n  const auto ws = traj.sample(num);\n  boost::geometry::model::linestring<point_2d> line;\n  for (const auto& w: ws)\n    line.push_back(point_2d(w.pos(0), w.pos(1)));\n  mapper.add(line);\n  mapper.map(line, traj_color);\n}\n\nint main(int argc, char **argv) {\n  // Draw the canvas\n  boost::geometry::model::polygon<point_2d> bound;\n  const double origin_x = -1;\n  const double origin_y = -1;\n  const double range_x = 7;\n  const double range_y = 3;\n  std::vector<point_2d> points;\n  points.push_back(point_2d(origin_x, origin_y));\n  points.push_back(point_2d(origin_x, origin_y + range_y));\n  points.push_back(point_2d(origin_x + range_x, origin_y + range_y));\n  points.push_back(point_2d(origin_x + range_x, origin_y));\n  points.push_back(point_2d(origin_x, origin_y));\n  boost::geometry::assign_points(bound, points);\n  boost::geometry::correct(bound);\n\n  mapper.add(bound);\n  mapper.map(bound, \"fill-opacity:1.0;fill:rgb(255,255,255);stroke:rgb(0,0,0);\"\n                    \"stroke-width:2\"); // White\n\n  // Draw path and trajectories\n\tvec_Vec2f path;\n\tpath.push_back(Vec2f(0, 0));\n  path.push_back(Vec2f(1, 0));\n  path.push_back(Vec2f(2, 1));\n  path.push_back(Vec2f(5, 1));\n\n  // Min Vel Traj\n  {\n    std::string color = \"opacity:0.4;fill:none;stroke:rgb(237,10,63);stroke-width:5\"; // Red\n    TrajSolver2D traj_solver(Control::VEL);\n    traj_solver.setPath(path);\n    traj_solver.setV(1); // set velocity for time allocation\n    drawTraj(traj_solver.solve(), \"min_vel_traj\", color);\n  }\n  // Min Acc Traj\n  {\n    std::string color = \"opacity:0.4;fill:none;stroke:rgb(94,140,49);stroke-width:5\"; // Green\n    TrajSolver2D traj_solver(Control::ACC);\n    traj_solver.setPath(path);\n    traj_solver.setV(1); // set velocity for time allocation\n    drawTraj(traj_solver.solve(), \"min_acc_traj\", color);\n  }\n  // Min Jrk Traj\n  {\n    std::string color = \"opacity:0.4;fill:none;stroke:rgb(118,215,234);stroke-width:5\"; // Blue\n    TrajSolver2D traj_solver(Control::JRK);\n    traj_solver.setPath(path);\n    traj_solver.setV(1); // set velocity for time allocation\n    drawTraj(traj_solver.solve(), \"min_jrk_traj\", color);\n  }\n\n  // Draw keyframes\n  for(const auto& it: path) {\n    point_2d pt;\n    boost::geometry::assign_values(pt, it(0), it(1));\n    mapper.add(pt);\n    mapper.map(pt, \"fill-opacity:1.0;fill:rgb(255,0,0);\", 10); // Red\n  }\n\n  // Write title at the lower right corner on canvas\n  mapper.text(point_2d(4.0, -0.2), \"test_traj_solver\",\n              \"fill-opacity:1.0;fill:rgb(10,10,250);\");\n\n  mapper.text(point_2d(3.5, -0.4), \"Red: \",\n              \"fill-opacity:1.0;fill:rgb(237,10,63);\");\n  mapper.text(point_2d(4.0, -0.4), \"minimum velocity trajectory\",\n              \"fill-opacity:1.0;fill:rgb(0,0,0);\");\n\n  mapper.text(point_2d(3.5, -0.6), \"Green: \",\n              \"fill-opacity:1.0;fill:rgb(94,140,49);\");\n  mapper.text(point_2d(4.0, -0.6), \"minimum acceleration trajectory\",\n              \"fill-opacity:1.0;fill:rgb(0,0,0);\");\n\n  mapper.text(point_2d(3.5, -0.8), \"Blue: \",\n              \"fill-opacity:1.0;fill:rgb(118,215,234);\");\n  mapper.text(point_2d(4.0, -0.8), \"minimum jerk trajectory\",\n              \"fill-opacity:1.0;fill:rgb(0,0,0);\");\n\n\n\n  return 0;\n}\n", "meta": {"hexsha": "15be85724d1d81eba828f6f076f9437d63b9b0fa", "size": 4113, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_traj_solver.cpp", "max_stars_repo_name": "yugo1103/motion_primitive_library", "max_stars_repo_head_hexsha": "393a3d5fb1cac744bfb7dbd078f76841eb2d61cd", "max_stars_repo_licenses": ["Apache-2.0"], "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_traj_solver.cpp", "max_issues_repo_name": "yugo1103/motion_primitive_library", "max_issues_repo_head_hexsha": "393a3d5fb1cac744bfb7dbd078f76841eb2d61cd", "max_issues_repo_licenses": ["Apache-2.0"], "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_traj_solver.cpp", "max_forks_repo_name": "yugo1103/motion_primitive_library", "max_forks_repo_head_hexsha": "393a3d5fb1cac744bfb7dbd078f76841eb2d61cd", "max_forks_repo_licenses": ["Apache-2.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.3982300885, "max_line_length": 97, "alphanum_fraction": 0.6601021152, "num_tokens": 1316, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300698514777, "lm_q2_score": 0.6548947425132314, "lm_q1q2_score": 0.460083249203186}}
{"text": "//////////////////////////////////////////////////////////////////////////////\n//   Copyright 2003 and onward LASMEA UMR 6602 CNRS/U.B.P Clermont-Ferrand\n//   Copyright 2009 and onward LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//////////////////////////////////////////////////////////////////////////////\n#define NT2_UNIT_MODULE \"nt2 boost.simd.ieee toolbox - saturate_at/simd Mode\"\n\n//////////////////////////////////////////////////////////////////////////////\n// unit test behavior of boost.simd.ieee components in simd mode\n//////////////////////////////////////////////////////////////////////////////\n\n#include <boost/simd/ieee/include/functions/saturate_at.hpp>\n#include <boost/simd/sdk/simd/native.hpp>\n#include <boost/simd/sdk/simd/io.hpp>\n#include <boost/type_traits/is_same.hpp>\n#include <nt2/sdk/unit/tests.hpp>\n#include <nt2/sdk/unit/module.hpp>\n#include <boost/dispatch/functor/meta/call.hpp>\n#include <boost/simd/include/constants/zero.hpp>\n#include <boost/simd/include/constants/one.hpp>\n#include <boost/simd/include/constants/mone.hpp>\n#include <boost/simd/include/constants/pi.hpp>\n#include <boost/simd/include/constants/four.hpp>\n#include <boost/simd/include/constants/mten.hpp>\n#include <boost/simd/include/constants/ten.hpp>\n\nNT2_TEST_CASE_TPL ( saturate_at_real__1_0,  BOOST_SIMD_SIMD_REAL_TYPES)\n{\n  using boost::simd::native;\n  using boost::simd::saturate_at;\n  using boost::simd::tag::saturate_at_;\n  typedef BOOST_SIMD_DEFAULT_EXTENSION  ext_t;\n  typedef native<T,ext_t>                        n_t;\n  typedef typename boost::dispatch::meta::call<saturate_at_<boost::simd::tag::Pi>(n_t)>::type r_t;\n  typedef typename boost::simd::meta::scalar_of<r_t>::type sr_t;\n\n  NT2_TEST_TYPE_IS( r_t, (native<T,ext_t>) );\n\n  NT2_TEST_ULP_EQUAL(saturate_at<boost::simd::tag::Pi>(boost::simd::Nan<n_t>())[0] , boost::simd::Nan<sr_t>(), 0);\n  NT2_TEST_ULP_EQUAL(saturate_at<boost::simd::tag::Pi>(boost::simd::Minf<n_t>())[0], -boost::simd::Pi<sr_t>(), 0);\n  NT2_TEST_ULP_EQUAL(saturate_at<boost::simd::tag::Pi>(boost::simd::Mten<n_t>())[0], -boost::simd::Pi<sr_t>(), 0);\n  NT2_TEST_ULP_EQUAL(saturate_at<boost::simd::tag::Pi>(boost::simd::Mone<n_t>())[0], boost::simd::Mone<sr_t>(), 0);\n  NT2_TEST_ULP_EQUAL(saturate_at<boost::simd::tag::Pi>(boost::simd::Zero<n_t>())[0], boost::simd::Zero<sr_t>(), 0);\n  NT2_TEST_ULP_EQUAL(saturate_at<boost::simd::tag::Pi>(boost::simd::One<n_t>())[0] , boost::simd::One<sr_t>(), 0);\n  NT2_TEST_ULP_EQUAL(saturate_at<boost::simd::tag::Pi>(boost::simd::Ten<n_t>())[0] , boost::simd::Pi<sr_t>(), 0);\n  NT2_TEST_ULP_EQUAL(saturate_at<boost::simd::tag::Pi>(boost::simd::Inf<n_t>())[0] , boost::simd::Pi<sr_t>(), 0);\n}\n\nNT2_TEST_CASE_TPL ( saturate_at_signed,  BOOST_SIMD_SIMD_INTEGRAL_SIGNED_TYPES)\n{\n  using boost::simd::native;\n  using boost::simd::saturate_at;\n  using boost::simd::tag::saturate_at_;\n  typedef BOOST_SIMD_DEFAULT_EXTENSION  ext_t;\n  typedef native<T,ext_t>                        n_t;\n  typedef typename boost::dispatch::meta::call<saturate_at_<boost::simd::tag::Pi>(n_t)>::type r_t;\n  typedef typename boost::simd::meta::scalar_of<r_t>::type sr_t;\n\n  NT2_TEST_TYPE_IS( r_t, (native<T,ext_t>) );\n\n  NT2_TEST_EQUAL(saturate_at<boost::simd::tag::Four>(boost::simd::Mten<n_t>()), -boost::simd::Four<r_t>() );\n  NT2_TEST_EQUAL(saturate_at<boost::simd::tag::Four>(boost::simd::Mone<n_t>()), boost::simd::Mone<r_t>() );\n  NT2_TEST_EQUAL(saturate_at<boost::simd::tag::Four>(boost::simd::Zero<n_t>()), boost::simd::Zero<r_t>() );\n  NT2_TEST_EQUAL(saturate_at<boost::simd::tag::Four>(boost::simd::One<n_t>()), boost::simd::One<r_t>() );\n  NT2_TEST_EQUAL(saturate_at<boost::simd::tag::Four>(boost::simd::Ten<n_t>()), boost::simd::Four<r_t>() );\n}\n\nNT2_TEST_CASE_TPL ( saturate_at_unsigned,  BOOST_SIMD_SIMD_INTEGRAL_UNSIGNED_TYPES)\n{\n  using boost::simd::native;\n  using boost::simd::saturate_at;\n  using boost::simd::tag::saturate_at_;\n  typedef BOOST_SIMD_DEFAULT_EXTENSION  ext_t;\n  typedef native<T,ext_t>                        n_t;\n  typedef typename boost::dispatch::meta::call<saturate_at_<boost::simd::tag::Pi>(n_t)>::type r_t;\n  typedef typename boost::simd::meta::scalar_of<r_t>::type sr_t;\n\n  NT2_TEST_TYPE_IS( r_t, (native<T,ext_t>) );\n\n  NT2_TEST_EQUAL(saturate_at<boost::simd::tag::Four>(boost::simd::Zero<n_t>()), boost::simd::Zero<r_t>() );\n  NT2_TEST_EQUAL(saturate_at<boost::simd::tag::Four>(boost::simd::One<n_t>()) , boost::simd::One<r_t>() );\n  NT2_TEST_EQUAL(saturate_at<boost::simd::tag::Four>(boost::simd::Ten<n_t>()) , boost::simd::Four<r_t>() );\n}\n", "meta": {"hexsha": "9e0b58cec4e0520d0cd1c2a02a4786616e5b7df3", "size": 4721, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/ieee/unit/simd/saturate_at.cpp", "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/ieee/unit/simd/saturate_at.cpp", "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/ieee/unit/simd/saturate_at.cpp", "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": 54.2643678161, "max_line_length": 115, "alphanum_fraction": 0.6560050837, "num_tokens": 1368, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.4600832410456388}}
{"text": "// (C) Copyright Andrew Sutton 2007\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//[code_bron_kerbosch_print_cliques\n#include <iostream>\n\n#include <boost/graph/undirected_graph.hpp>\n#include <boost/graph/bron_kerbosch_all_cliques.hpp>\n\n#include \"helper.hpp\"\n\nusing namespace std;\nusing namespace boost;\n\n// The clique_printer is a visitor that will print the vertices that comprise\n// a clique. Note that the vertices are not given in any specific order.\ntemplate <typename OutputStream>\nstruct clique_printer\n{\n    clique_printer(OutputStream& stream)\n        : os(stream)\n    { }\n\n    template <typename Clique, typename Graph>\n    void clique(const Clique& c, const Graph& g)\n    {\n        // Iterate over the clique and print each vertex within it.\n        typename Clique::const_iterator i, end = c.end();\n        for(i = c.begin(); i != end; ++i) {\n            os << g[*i].name << \" \";\n        }\n        os << endl;\n    }\n    OutputStream& os;\n};\n\n// The Actor type stores the name of each vertex in the graph.\nstruct Actor\n{\n    string name;\n};\n\n// Declare the graph type and its vertex and edge types.\ntypedef undirected_graph<Actor> Graph;\ntypedef graph_traits<Graph>::vertex_descriptor Vertex;\ntypedef graph_traits<Graph>::edge_descriptor Edge;\n\n// The name map provides an abstract accessor for the names of\n// each vertex. This is used during graph creation.\ntypedef property_map<Graph, string Actor::*>::type NameMap;\n\nint\nmain(int argc, char *argv[])\n{\n    // Create the graph and and its name map accessor.\n    Graph g;\n    NameMap nm(get(&Actor::name, g));\n\n    // Read the graph from standard input.\n    read_graph(g, nm, cin);\n\n    // Instantiate the visitor for printing cliques\n    clique_printer<ostream> vis(cout);\n\n    // Use the Bron-Kerbosch algorithm to find all cliques, printing them\n    // as they are found.\n    bron_kerbosch_all_cliques(g, vis);\n\n    return 0;\n}\n//]\n", "meta": {"hexsha": "93030edd1522fa3350c848377b28975007a5bc95", "size": 2036, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/graph/example/bron_kerbosch_print_cliques.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "boost/libs/graph/example/bron_kerbosch_print_cliques.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "boost/libs/graph/example/bron_kerbosch_print_cliques.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 27.1466666667, "max_line_length": 77, "alphanum_fraction": 0.695481336, "num_tokens": 489, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947425132315, "lm_q2_score": 0.7025300573952052, "lm_q1q2_score": 0.4600832410456387}}
{"text": "#include <boost/test/unit_test.hpp>\n\n#include <stdexcept>\n\n#include \"Variable.hpp\"\n#include \"it/BitsetCounter.hpp\"\n#include \"it/Distribution.hpp\"\n\nusing namespace mist;\n\n// test data\nint num_vars = 10;\n\nauto* data_a{ new Variable::data_t[6]{ 0, 1, 1, 0, 0, 1 } };\n;\nauto* data_b{ new Variable::data_t[6]{ 1, 1, 0, 0, 1, 0 } };\n;\n\nVariable::data_ptr da(data_a);\nVariable::data_ptr db(data_b);\n\nVariable variable_a(da, 6, 0, 2);\nVariable variable_b(db, 6, 1, 2);\nVariable variable_num_vars(db, 6, num_vars - 1, 2);\nVariable variable_index_oor(db, 6, num_vars, 2);\n\nBOOST_AUTO_TEST_CASE(BitsetCounter_default_constructor)\n{\n  it::BitsetCounter pdb1({ variable_a, variable_b });\n}\n\nBOOST_AUTO_TEST_CASE(BitsetCounter_count_1)\n{\n\n  Variable::tuple vars;\n  vars.push_back(variable_a);\n  it::BitsetCounter pdb(vars);\n\n  it::Distribution pd0;\n  it::Distribution pd1;\n  it::Distribution pd2;\n  pdb.count(vars, { 0 }, pd0);\n  pdb.count(vars, pd1);\n  pdb.count(variable_a, pd2);\n\n  BOOST_TEST(pd0(std::vector<Variable::data_t>{ 0 }) == 3);\n  BOOST_TEST(pd0(std::vector<Variable::data_t>{ 1 }) == 3);\n  BOOST_TEST(pd1(std::vector<Variable::data_t>{ 0 }) == 3);\n  BOOST_TEST(pd1(std::vector<Variable::data_t>{ 1 }) == 3);\n  BOOST_TEST(pd2(std::vector<Variable::data_t>{ 0 }) == 3);\n  BOOST_TEST(pd2(std::vector<Variable::data_t>{ 1 }) == 3);\n\n  BOOST_TEST(pd0 == pd2);\n  BOOST_TEST(pd1 == pd2);\n}\n\nBOOST_AUTO_TEST_CASE(BitsetCounter_count)\n{\n\n  Variable::tuple vars;\n  vars.push_back(variable_a);\n  vars.push_back(variable_b);\n  it::BitsetCounter pdb(vars);\n\n  it::Distribution pd;\n  pdb.count(vars, pd);\n\n  BOOST_TEST(pd(std::vector<Variable::data_t>{ 0, 0 }) == 1);\n  BOOST_TEST(pd(std::vector<Variable::data_t>{ 0, 1 }) == 2);\n  BOOST_TEST(pd(std::vector<Variable::data_t>{ 1, 0 }) == 2);\n  BOOST_TEST(pd(std::vector<Variable::data_t>{ 1, 1 }) == 1);\n\n  vars.push_back(variable_b);\n  pdb.count(vars, pd);\n\n  BOOST_TEST(pd(std::vector<Variable::data_t>{ 0, 0, 0 }) == 1);\n  BOOST_TEST(pd(std::vector<Variable::data_t>{ 0, 0, 1 }) == 0);\n  BOOST_TEST(pd(std::vector<Variable::data_t>{ 0, 1, 0 }) == 0);\n  BOOST_TEST(pd(std::vector<Variable::data_t>{ 0, 1, 1 }) == 2);\n}\n\nBOOST_AUTO_TEST_CASE(BitsetCounter_index_oor)\n{\n\n  Variable::tuple vars;\n  // variable has index larger than the number of variables in the set, i.e.\n  // out of range\n  vars.push_back(variable_num_vars);\n  BOOST_CHECK_THROW(it::BitsetCounter pdb(vars), it::BitsetCounterOutOfRange);\n}\n\nstatic it::Distribution\npolymorphCount(it::Counter& pdc, Variable::tuple const& vars)\n{\n  it::Distribution dist;\n  pdc.count(vars, dist);\n  return dist;\n}\n\nBOOST_AUTO_TEST_CASE(BitsetCounter_polymorph)\n{\n\n  Variable::tuple vars;\n  vars.push_back(variable_b);\n  vars.push_back(variable_a);\n  it::BitsetCounter pdb(vars);\n\n  it::Distribution pd = polymorphCount(pdb, vars);\n\n  BOOST_TEST(pd(std::vector<Variable::data_t>{ 0, 0 }) == 1);\n  BOOST_TEST(pd(std::vector<Variable::data_t>{ 0, 1 }) == 2);\n  BOOST_TEST(pd(std::vector<Variable::data_t>{ 1, 0 }) == 2);\n  BOOST_TEST(pd(std::vector<Variable::data_t>{ 1, 1 }) == 1);\n}\n", "meta": {"hexsha": "a4386a4e20ac95d2b021acbe504ed2676a7de03f", "size": 3069, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mist/it/BitsetCounter.test.cpp", "max_stars_repo_name": "andbanman/mist", "max_stars_repo_head_hexsha": "2546fb41bccea1f89a43dbdbed7ce3a257926b54", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/mist/it/BitsetCounter.test.cpp", "max_issues_repo_name": "andbanman/mist", "max_issues_repo_head_hexsha": "2546fb41bccea1f89a43dbdbed7ce3a257926b54", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-03-30T21:40:44.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-08T18:54:34.000Z", "max_forks_repo_path": "src/mist/it/BitsetCounter.test.cpp", "max_forks_repo_name": "andbanman/mist", "max_forks_repo_head_hexsha": "2546fb41bccea1f89a43dbdbed7ce3a257926b54", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6869565217, "max_line_length": 78, "alphanum_fraction": 0.6823069404, "num_tokens": 972, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300698514778, "lm_q2_score": 0.6548947290421276, "lm_q1q2_score": 0.4600832397393306}}
{"text": "#include <memory>\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n#include <igl/jet.h>\n#include <igl/gaussian_curvature.h>\n#include <igl/principal_curvature.h>\n#include <igl/per_face_normals.h>\n#include <igl/massmatrix.h>\n#include <igl/readOBJ.h>\n#include <igl/invert_diag.h>\n#include <igl/hsv_to_rgb.h>\n#include <igl/boundary_loop.h>\n#include <igl/boundary_facets.h>\n#include <igl/hsv_to_rgb.h>\n#include <igl/adjacency_list.h>\n\n\n#include \"../../include/Visualization/PaintGeometry.h\"\n\n\n\nEigen::MatrixXd PaintGeometry::paintPhi(const Eigen::VectorXd& phi, Eigen::VectorXd* brightness)      // brightness should between 0 and 1\n{\n    int nverts = phi.size();\n    // std::cout << phi.minCoeff() << \" \" << phi.maxCoeff() << std::endl;\n    Eigen::MatrixXd color(nverts, 3);\n    if (isNormalize)\n    {\n        igl::jet(phi, true, color);\n    }\n    else\n    {\n        for (int i = 0; i < nverts; i++)\n        {\n            double r, g, b;\n            double h = 360.0 * phi[i] / 2.0 / M_PI + 120;\n            h = 360 + ((int)h % 360); // fix for libigl bug\n            double s = 1.0;\n            double v = 0.5;\n            if(brightness)\n            {\n                double r = (*brightness)(i);\n                v = r * r / (r * r + 1);\n            }\n//                v = (*brightness)(i);\n            igl::hsv_to_rgb(h, s, v, r, g, b);\n            color(i, 0) = r;\n            color(i, 1) = g;\n            color(i, 2) = b;\n        }\n    }\n\n    return color;\n\n\n}\n\nEigen::MatrixXd PaintGeometry::paintAmplitude(const Eigen::VectorXd& amplitude)\n{\n    int nverts = amplitude.size();\n    Eigen::VectorXd trueAmp = amplitude;\n\n    // std::cout << \"amplitude: \" << trueAmp.minCoeff() << \" \" << trueAmp.maxCoeff() << std::endl;\n\n    Eigen::MatrixXd color(nverts, 3);\n    igl::jet(trueAmp, isNormalize, color);\n\n    return color;\n}", "meta": {"hexsha": "32249c60b2878b013e67ddd012eda0b91c60a28e", "size": 1826, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Visualization/PaintGeometry.cpp", "max_stars_repo_name": "csyzzkdcz/PhaseInterpolation_polyscope", "max_stars_repo_head_hexsha": "4833a569f9eca1c222f7cdfd8e4aae3f03d8ad0b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Visualization/PaintGeometry.cpp", "max_issues_repo_name": "csyzzkdcz/PhaseInterpolation_polyscope", "max_issues_repo_head_hexsha": "4833a569f9eca1c222f7cdfd8e4aae3f03d8ad0b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Visualization/PaintGeometry.cpp", "max_forks_repo_name": "csyzzkdcz/PhaseInterpolation_polyscope", "max_forks_repo_head_hexsha": "4833a569f9eca1c222f7cdfd8e4aae3f03d8ad0b", "max_forks_repo_licenses": ["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.4637681159, "max_line_length": 138, "alphanum_fraction": 0.5591456736, "num_tokens": 529, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300698514778, "lm_q2_score": 0.6548947155710233, "lm_q1q2_score": 0.4600832302754747}}
{"text": "// Negative test for BOOST_TEST_WITH\n//\n// Copyright 2020 Bjorn Reese\n// Copyright 2020 Peter Dimov\n//\n// Distributed under the Boost Software License, Version 1.0.\n// https://www.boost.org/LICENSE_1_0.txt\n\n#include <boost/core/lightweight_test.hpp>\n#include <cmath>\n\ntemplate <typename T>\nstruct with_tolerance\n{\n    with_tolerance( T tolerance ): tolerance( tolerance )\n    {\n    }\n\n    bool operator()( T lhs, T rhs ) const\n    {\n        return std::abs( lhs - rhs ) <= tolerance;\n    }\n\nprivate:\n\n    T tolerance;\n};\n\nvoid test_tolerance_predicate()\n{\n    BOOST_TEST_WITH( 1.0, 1.0 - 1e-6, with_tolerance<double>(1e-7) );\n    BOOST_TEST_WITH( 1.0, 1.0 + 1e-6, with_tolerance<double>(1e-7) );\n}\n\nint main()\n{\n    test_tolerance_predicate();\n    return boost::report_errors() == 2;\n}\n", "meta": {"hexsha": "4583c2cce05a9ac0e862842b06dea4228047b0a1", "size": 786, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "console/src/boost_1_78_0/libs/core/test/lightweight_test_with_fail.cpp", "max_stars_repo_name": "vany152/FilesHash", "max_stars_repo_head_hexsha": "39f282807b7f1abc56dac389e8259ee3bb557a8d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 106.0, "max_stars_repo_stars_event_min_datetime": "2015-08-07T04:23:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-27T18:25:15.000Z", "max_issues_repo_path": "console/src/boost_1_78_0/libs/core/test/lightweight_test_with_fail.cpp", "max_issues_repo_name": "vany152/FilesHash", "max_issues_repo_head_hexsha": "39f282807b7f1abc56dac389e8259ee3bb557a8d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 130.0, "max_issues_repo_issues_event_min_datetime": "2016-06-22T22:11:25.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-29T20:24:09.000Z", "max_forks_repo_path": "Libs/boost_1_76_0/libs/core/test/lightweight_test_with_fail.cpp", "max_forks_repo_name": "Antd23rus/S2DE", "max_forks_repo_head_hexsha": "47cc7151c2934cd8f0399a9856c1e54894571553", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2015-07-08T19:18:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-14T16:39:56.000Z", "avg_line_length": 19.65, "max_line_length": 69, "alphanum_fraction": 0.665394402, "num_tokens": 219, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947155710233, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.46008322619670117}}
{"text": "//\n// Copyright \u00a9 2017 Arm Ltd. All rights reserved.\n// SPDX-License-Identifier: MIT\n//\n\n#include <boost/test/unit_test.hpp>\n#include \"ParserFlatbuffersFixture.hpp\"\n#include \"../TfLiteParser.hpp\"\n\n#include <string>\n#include <iostream>\n\nBOOST_AUTO_TEST_SUITE(TensorflowLiteParser)\n\nstruct FullyConnectedFixture : public ParserFlatbuffersFixture\n{\n    explicit FullyConnectedFixture(const std::string& inputShape,\n                                           const std::string& outputShape,\n                                           const std::string& filterShape,\n                                           const std::string& filterData,\n                                           const std::string biasShape = \"\",\n                                           const std::string biasData = \"\")\n    {\n        std::string inputTensors = \"[ 0, 2 ]\";\n        std::string biasTensor = \"\";\n        std::string biasBuffer = \"\";\n        if (biasShape.size() > 0 && biasData.size() > 0)\n        {\n            inputTensors = \"[ 0, 2, 3 ]\";\n            biasTensor = R\"(\n                        {\n                            \"shape\": )\" + biasShape + R\"( ,\n                            \"type\": \"INT32\",\n                            \"buffer\": 3,\n                            \"name\": \"biasTensor\",\n                            \"quantization\": {\n                                \"min\": [ 0.0 ],\n                                \"max\": [ 255.0 ],\n                                \"scale\": [ 1.0 ],\n                                \"zero_point\": [ 0 ],\n                            }\n                        } )\";\n            biasBuffer = R\"(\n                    { \"data\": )\" + biasData + R\"(, }, )\";\n        }\n        m_JsonString = R\"(\n            {\n                \"version\": 3,\n                \"operator_codes\": [ { \"builtin_code\": \"FULLY_CONNECTED\" } ],\n                \"subgraphs\": [ {\n                    \"tensors\": [\n                        {\n                            \"shape\": )\" + inputShape + R\"(,\n                            \"type\": \"UINT8\",\n                            \"buffer\": 0,\n                            \"name\": \"inputTensor\",\n                            \"quantization\": {\n                                \"min\": [ 0.0 ],\n                                \"max\": [ 255.0 ],\n                                \"scale\": [ 1.0 ],\n                                \"zero_point\": [ 0 ],\n                            }\n                        },\n                        {\n                            \"shape\": )\" + outputShape + R\"(,\n                            \"type\": \"UINT8\",\n                            \"buffer\": 1,\n                            \"name\": \"outputTensor\",\n                            \"quantization\": {\n                                \"min\": [ 0.0 ],\n                                \"max\": [ 511.0 ],\n                                \"scale\": [ 2.0 ],\n                                \"zero_point\": [ 0 ],\n                            }\n                        },\n                        {\n                            \"shape\": )\" + filterShape + R\"(,\n                            \"type\": \"UINT8\",\n                            \"buffer\": 2,\n                            \"name\": \"filterTensor\",\n                            \"quantization\": {\n                                \"min\": [ 0.0 ],\n                                \"max\": [ 255.0 ],\n                                \"scale\": [ 1.0 ],\n                                \"zero_point\": [ 0 ],\n                            }\n                        }, )\" + biasTensor + R\"(\n                    ],\n                    \"inputs\": [ 0 ],\n                    \"outputs\": [ 1 ],\n                    \"operators\": [\n                        {\n                            \"opcode_index\": 0,\n                            \"inputs\": )\" + inputTensors + R\"(,\n                            \"outputs\": [ 1 ],\n                            \"builtin_options_type\": \"FullyConnectedOptions\",\n                            \"builtin_options\": {\n                                \"fused_activation_function\": \"NONE\"\n                            },\n                            \"custom_options_format\": \"FLEXBUFFERS\"\n                        }\n                    ],\n                } ],\n                \"buffers\" : [\n                    { },\n                    { },\n                    { \"data\": )\" + filterData + R\"(, }, )\"\n                       + biasBuffer + R\"(\n                ]\n            }\n        )\";\n        SetupSingleInputSingleOutput(\"inputTensor\", \"outputTensor\");\n    }\n};\n\nstruct FullyConnectedWithNoBiasFixture : FullyConnectedFixture\n{\n    FullyConnectedWithNoBiasFixture()\n        : FullyConnectedFixture(\"[ 1, 4, 1, 1 ]\",     // inputShape\n                                \"[ 1, 1 ]\",           // outputShape\n                                \"[ 1, 4 ]\",           // filterShape\n                                \"[ 2, 3, 4, 5 ]\")     // filterData\n    {}\n};\n\nBOOST_FIXTURE_TEST_CASE(FullyConnectedWithNoBias, FullyConnectedWithNoBiasFixture)\n{\n    RunTest<2, armnn::DataType::QAsymmU8>(\n        0,\n        { 10, 20, 30, 40 },\n        { 400/2 });\n}\n\nstruct FullyConnectedWithBiasFixture : FullyConnectedFixture\n{\n    FullyConnectedWithBiasFixture()\n        : FullyConnectedFixture(\"[ 1, 4, 1, 1 ]\",     // inputShape\n                                \"[ 1, 1 ]\",           // outputShape\n                                \"[ 1, 4 ]\",           // filterShape\n                                \"[ 2, 3, 4, 5 ]\",     // filterData\n                                \"[ 1 ]\",              // biasShape\n                                \"[ 10, 0, 0, 0 ]\" )   // biasData\n    {}\n};\n\nBOOST_FIXTURE_TEST_CASE(ParseFullyConnectedWithBias, FullyConnectedWithBiasFixture)\n{\n    RunTest<2, armnn::DataType::QAsymmU8>(\n        0,\n        { 10, 20, 30, 40 },\n        { (400+10)/2 });\n}\n\nstruct FullyConnectedWithBiasMultipleOutputsFixture : FullyConnectedFixture\n{\n    FullyConnectedWithBiasMultipleOutputsFixture()\n            : FullyConnectedFixture(\"[ 1, 4, 2, 1 ]\",     // inputShape\n                                    \"[ 2, 1 ]\",           // outputShape\n                                    \"[ 1, 4 ]\",           // filterShape\n                                    \"[ 2, 3, 4, 5 ]\",     // filterData\n                                    \"[ 1 ]\",              // biasShape\n                                    \"[ 10, 0, 0, 0 ]\" )   // biasData\n    {}\n};\n\nBOOST_FIXTURE_TEST_CASE(FullyConnectedWithBiasMultipleOutputs, FullyConnectedWithBiasMultipleOutputsFixture)\n{\n    RunTest<2, armnn::DataType::QAsymmU8>(\n            0,\n            { 1, 2, 3, 4, 10, 20, 30, 40 },\n            { (40+10)/2, (400+10)/2 });\n}\n\nstruct DynamicFullyConnectedWithBiasMultipleOutputsFixture : FullyConnectedFixture\n{\n    DynamicFullyConnectedWithBiasMultipleOutputsFixture()\n        : FullyConnectedFixture(\"[ 1, 4, 2, 1 ]\",     // inputShape\n                                \"[ ]\",               // outputShape\n                                \"[ 1, 4 ]\",           // filterShape\n                                \"[ 2, 3, 4, 5 ]\",     // filterData\n                                \"[ 1 ]\",              // biasShape\n                                \"[ 10, 0, 0, 0 ]\" )   // biasData\n    { }\n};\n\nBOOST_FIXTURE_TEST_CASE(\n    DynamicFullyConnectedWithBiasMultipleOutputs,\n    DynamicFullyConnectedWithBiasMultipleOutputsFixture)\n{\n    RunTest<2,\n            armnn::DataType::QAsymmU8,\n            armnn::DataType::QAsymmU8>(0,\n                                      { { \"inputTensor\", { 1, 2, 3, 4, 10, 20, 30, 40} } },\n                                      { { \"outputTensor\", { (40+10)/2, (400+10)/2 } } },\n                                      true);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "e7aa9082e237e96cd54f9221670fbdb15e7e46d2", "size": 7648, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/armnnTfLiteParser/test/FullyConnected.cpp", "max_stars_repo_name": "Project-Xtended/external_armnn", "max_stars_repo_head_hexsha": "c5e1bbf9fc8ecbb8c9eb073a1550d4c8c15fce94", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-12-09T15:14:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-10T01:37:53.000Z", "max_issues_repo_path": "src/armnnTfLiteParser/test/FullyConnected.cpp", "max_issues_repo_name": "Project-Xtended/external_armnn", "max_issues_repo_head_hexsha": "c5e1bbf9fc8ecbb8c9eb073a1550d4c8c15fce94", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/armnnTfLiteParser/test/FullyConnected.cpp", "max_forks_repo_name": "Project-Xtended/external_armnn", "max_forks_repo_head_hexsha": "c5e1bbf9fc8ecbb8c9eb073a1550d4c8c15fce94", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2022-01-23T11:34:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-12T15:51:37.000Z", "avg_line_length": 38.432160804, "max_line_length": 108, "alphanum_fraction": 0.356040795, "num_tokens": 1620, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300449389326, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.4600832234242359}}
{"text": "/*\n * GraphBLAS Template Library (GBTL), Version 3.0\n *\n * Copyright 2020 Carnegie Mellon University, Battelle Memorial Institute, and\n * Authors.\n *\n * THIS MATERIAL WAS PREPARED AS AN ACCOUNT OF WORK SPONSORED BY AN AGENCY OF\n * THE UNITED STATES GOVERNMENT.  NEITHER THE UNITED STATES GOVERNMENT NOR THE\n * UNITED STATES DEPARTMENT OF ENERGY, NOR THE UNITED STATES DEPARTMENT OF\n * DEFENSE, NOR CARNEGIE MELLON UNIVERSITY, NOR BATTELLE, NOR ANY OF THEIR\n * EMPLOYEES, NOR ANY JURISDICTION OR ORGANIZATION THAT HAS COOPERATED IN THE\n * DEVELOPMENT OF THESE MATERIALS, MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR\n * ASSUMES ANY LEGAL LIABILITY OR RESPONSIBILITY FOR THE ACCURACY, COMPLETENESS,\n * OR USEFULNESS OR ANY INFORMATION, APPARATUS, PRODUCT, SOFTWARE, OR PROCESS\n * DISCLOSED, OR REPRESENTS THAT ITS USE WOULD NOT INFRINGE PRIVATELY OWNED\n * RIGHTS.\n *\n * Released under a BSD-style license, please see LICENSE file or contact\n * permission@sei.cmu.edu for full terms.\n *\n * [DISTRIBUTION STATEMENT A] This material has been approved for public release\n * and unlimited distribution.  Please see Copyright notice for non-US\n * Government use and distribution.\n *\n * This Software includes and/or makes use of the following Third-Party Software\n * subject to its own license:\n *\n * 1. Boost Unit Test Framework\n * (https://www.boost.org/doc/libs/1_45_0/libs/test/doc/html/utf.html)\n * Copyright 2001 Boost software license, Gennadiy Rozental.\n *\n * DM20-0442\n */\n\n#include <iostream>\n\n#include <algorithms/maxflow.hpp>\n#include <graphblas/graphblas.hpp>\n\nusing namespace grb;\n\n#define BOOST_TEST_MAIN\n#define BOOST_TEST_MODULE maxflow_test_suite\n\n#include <boost/test/included/unit_test.hpp>\n\nBOOST_AUTO_TEST_SUITE(BOOST_TEST_MODULE)\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(maxflow_push_relabel_test)\n{\n    IndexArrayType i = {0, 0, 1, 2, 2, 3, 4, 4};\n    IndexArrayType j = {1, 3, 2, 3, 5, 4, 1, 5};\n    std::vector<double>       v = {15, 4, 12, 3, 7, 10, 5, 10};\n    Matrix<double, DirectedMatrixTag> m1(6, 6);\n    m1.build(i, j, v);\n\n    //grb::print_matrix(std::cerr, m1, \"\\nGraph\");\n    auto result = algorithms::maxflow_push_relabel(m1, 0, 5);\n    BOOST_CHECK_EQUAL(result, 14);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(maxflow_push_relabel_test2)\n{\n    //       s   1  2  3  4  5  6  t\n    //  m1({{-, 10, 5,15, -, -, -, -},   // s = 0\n    //      {-,  -, 4, -, 9,15, -, -},   // 1\n    //      {-,  -, -, 4, -, 8, -, -},   // 2\n    //      {-,  -, -, -, -, -,30, -},   // 3\n    //      {-,  -, -, -, -,15, -,10},   // 4\n    //      {-,  -, -, -, -, -,15,10},   // 5\n    //      {-,  -, 6, -, -, -, -,10},   // 6\n    //      {-,  -, -, -, -, -, -, -}}); // t = 7\n\n    IndexArrayType i =      {0, 0, 0, 1, 1, 1, 2, 2, 3, 4, 4, 5, 5, 6, 6};\n    IndexArrayType j =      {1, 2, 3, 2, 4, 5, 3, 5, 6, 5, 7, 6, 7, 2, 7};\n    std::vector<double> v = {10,5,15, 4, 9,15, 4, 8,30,15,10,15,10, 6,10};\n    Matrix<double, DirectedMatrixTag> m1(8, 8);\n    m1.build(i, j, v);\n\n    //grb::print_matrix(std::cerr, m1, \"\\nGraph\");\n    auto result = algorithms::maxflow_push_relabel(m1, 0, 7);\n    BOOST_CHECK_EQUAL(result, 28);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(maxflow_ford_fulk_test)\n{\n    IndexArrayType i = {0, 0, 1, 2, 2, 3, 4, 4};\n    IndexArrayType j = {1, 3, 2, 3, 5, 4, 1, 5};\n    std::vector<double>       v = {15, 4, 12, 3, 7, 10, 5, 10};\n    Matrix<double, DirectedMatrixTag> m1(6, 6);\n    m1.build(i, j, v);\n\n    //grb::print_matrix(std::cerr, m1, \"\\nGraph\");\n    auto result = algorithms::maxflow_ford_fulk(m1, 0, 5);\n    BOOST_CHECK_EQUAL(result, 14);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(maxflow_ford_fulk_test_counter_example)\n{\n    /*       2  2\n     *      1--6--3\n     *  2  /     / \\  10\n     *    /     /                               \\\n     *   0     /     5\n     *    \\   / 9   /\n     *  9  \\ /     /  2\n     *      2-----4\n     *         7\n     */\n    IndexArrayType      i = {0, 0, 1, 2, 2, 3, 4, 6};\n    IndexArrayType      j = {1, 2, 6, 3, 4, 5, 5, 3};\n    std::vector<double> v = {2, 9, 2, 9, 7,10, 2, 2};\n    Matrix<double, DirectedMatrixTag> m1(7, 7);\n    m1.build(i, j, v);\n\n    //grb::print_matrix(std::cerr, m1, \"\\nGraph\");\n    auto result = algorithms::maxflow_ford_fulk(m1, 0, 5);\n    BOOST_CHECK_EQUAL(result, 11);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(maxflow_ford_fulk_test2)\n{\n    //       s   1  2  3  4  5  6  t\n    //  m1({{-, 10, 5,15, -, -, -, -},   // s = 0\n    //      {-,  -, 4, -, 9,15, -, -},   // 1\n    //      {-,  4, -, 4, -, 8, -, -},   // 2\n    //      {-,  -, -, -, -, -,30, -},   // 3\n    //      {-,  -, -, -, -,15, -,10},   // 4\n    //      {-,  -, -, -, -, -,15,10},   // 5\n    //      {-,  -, 6, -, -, -, -,10},   // 6\n    //      {-,  -, -, -, -, -, -, -}}); // t = 7\n\n    IndexArrayType i =      {0, 0, 0, 1, 1, 1, 2, 2, 3, 4, 4, 5, 5, 6, 6};\n    IndexArrayType j =      {1, 2, 3, 2, 4, 5, 3, 5, 6, 5, 7, 6, 7, 2, 7};\n    std::vector<double> v = {10,5,15, 4, 9,15, 4, 8,30,15,10,15,10, 6,10};\n    Matrix<double, DirectedMatrixTag> m1(8, 8);\n    m1.build(i, j, v);\n\n    //grb::print_matrix(std::cerr, m1, \"\\nGraph\");\n    auto result = algorithms::maxflow_ford_fulk(m1, 0, 7);\n    BOOST_CHECK_EQUAL(result, 28);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(maxflow_ford_fulk_test2_bidirectional)\n{\n    //       s   1  2  3  4  5  6  t\n    //  m1({{-, 10, 5,15, -, -, -, -},   // s = 0\n    //      {-,  -, 4, -, 9,15, -, -},   // 1\n    //      {-,  4, -, 4, -, 8, -, -},   // 2\n    //      {-,  -, -, -, -, -,30, -},   // 3\n    //      {-,  -, -, -, -,15, -,10},   // 4\n    //      {-,  -, -, -, 5, -,15,10},   // 5\n    //      {-,  -, 6, -, -, -, -,10},   // 6\n    //      {-,  -, -, -, -, -, -, -}}); // t = 7\n\n    IndexArrayType i =      {0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 4, 4, 5, 5, 5, 6, 6};\n    IndexArrayType j =      {1, 2, 3, 2, 4, 5, 1, 3, 5, 6, 5, 7, 4, 6, 7, 2, 7};\n    std::vector<double> v = {10,5,15, 4, 9,15, 4, 4, 8,30,15,10, 5,15,10, 6,10};\n    Matrix<double, DirectedMatrixTag> m1(8, 8);\n    m1.build(i, j, v);\n\n    //grb::print_matrix(std::cerr, m1, \"\\nGraph\");\n    auto result = algorithms::maxflow_ford_fulk(m1, 0, 7);\n    BOOST_CHECK_EQUAL(result, 30);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "e81458f38a16b30bea024827d36ffd3f8c781db1", "size": 6540, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/test_maxflow.cpp", "max_stars_repo_name": "KIwabuchi/gbtl", "max_stars_repo_head_hexsha": "62c6b1e3262f3623359e793edb5ec4fa7bb471f0", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 112.0, "max_stars_repo_stars_event_min_datetime": "2016-04-26T05:54:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T05:56:16.000Z", "max_issues_repo_path": "src/test/test_maxflow.cpp", "max_issues_repo_name": "KIwabuchi/gbtl", "max_issues_repo_head_hexsha": "62c6b1e3262f3623359e793edb5ec4fa7bb471f0", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 21.0, "max_issues_repo_issues_event_min_datetime": "2016-03-22T19:06:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-07T15:40:18.000Z", "max_forks_repo_path": "src/test/test_maxflow.cpp", "max_forks_repo_name": "KIwabuchi/gbtl", "max_forks_repo_head_hexsha": "62c6b1e3262f3623359e793edb5ec4fa7bb471f0", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2016-04-26T05:54:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-21T03:33:20.000Z", "avg_line_length": 37.5862068966, "max_line_length": 80, "alphanum_fraction": 0.4862385321, "num_tokens": 2418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.6548947155710234, "lm_q1q2_score": 0.46008322211792774}}
{"text": "//=======================================================================\r\n// Copyright (c) 2005 Aaron Windsor\r\n//\r\n// Distributed under the Boost Software License, Version 1.0. \r\n// (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n//\r\n//=======================================================================\r\n\r\n#ifndef BOOST_GRAPH_MAXIMUM_CARDINALITY_MATCHING_HPP\r\n#define BOOST_GRAPH_MAXIMUM_CARDINALITY_MATCHING_HPP\r\n\r\n#include <vector>\r\n#include <list>\r\n#include <deque>\r\n#include <algorithm>                     // for std::sort and std::stable_sort\r\n#include <utility>                       // for std::pair\r\n#include <boost/property_map.hpp>\r\n#include <boost/utility.hpp>             // for boost::tie\r\n#include <boost/graph/graph_traits.hpp>  \r\n#include <boost/graph/visitors.hpp>\r\n#include <boost/graph/depth_first_search.hpp>\r\n#include <boost/graph/filtered_graph.hpp>\r\n#include <boost/pending/disjoint_sets.hpp>\r\n#include <boost/assert.hpp>\r\n\r\n\r\nnamespace boost\r\n{\r\n  namespace graph { namespace detail {\r\n    enum { V_EVEN, V_ODD, V_UNREACHED };\r\n  } } // end namespace graph::detail\r\n\r\n  template <typename Graph, typename MateMap, typename VertexIndexMap>\r\n  typename graph_traits<Graph>::vertices_size_type \r\n  matching_size(const Graph& g, MateMap mate, VertexIndexMap vm)\r\n  {\r\n    typedef typename graph_traits<Graph>::vertex_iterator vertex_iterator_t;\r\n    typedef typename graph_traits<Graph>::vertex_descriptor\r\n      vertex_descriptor_t;\r\n    typedef typename graph_traits<Graph>::vertices_size_type v_size_t;\r\n\r\n    v_size_t size_of_matching = 0;\r\n    vertex_iterator_t vi, vi_end;\r\n\r\n    for(tie(vi,vi_end) = vertices(g); vi != vi_end; ++vi)\r\n      {\r\n        vertex_descriptor_t v = *vi;\r\n        if (get(mate,v) != graph_traits<Graph>::null_vertex() \r\n            && get(vm,v) < get(vm,get(mate,v)))\r\n        ++size_of_matching;\r\n      }\r\n    return size_of_matching;\r\n  }\r\n\r\n\r\n\r\n\r\n  template <typename Graph, typename MateMap>\r\n  inline typename graph_traits<Graph>::vertices_size_type\r\n  matching_size(const Graph& g, MateMap mate)\r\n  {\r\n    return matching_size(g, mate, get(vertex_index,g));\r\n  }\r\n\r\n\r\n\r\n\r\n  template <typename Graph, typename MateMap, typename VertexIndexMap>\r\n  bool is_a_matching(const Graph& g, MateMap mate, VertexIndexMap vm)\r\n  {\r\n    typedef typename graph_traits<Graph>::vertex_descriptor\r\n      vertex_descriptor_t;\r\n    typedef typename graph_traits<Graph>::vertex_iterator vertex_iterator_t;\r\n\r\n    vertex_iterator_t vi, vi_end;\r\n    for( tie(vi,vi_end) = vertices(g); vi != vi_end; ++vi)\r\n      {\r\n        vertex_descriptor_t v = *vi;\r\n        if (get(mate,v) != graph_traits<Graph>::null_vertex() \r\n            && v != get(mate,get(mate,v)))\r\n        return false;\r\n      }    \r\n    return true;\r\n  }\r\n\r\n\r\n\r\n\r\n  template <typename Graph, typename MateMap>\r\n  inline bool is_a_matching(const Graph& g, MateMap mate)\r\n  {\r\n    return is_a_matching(g, mate, get(vertex_index,g));\r\n  }\r\n\r\n\r\n\r\n\r\n  //***************************************************************************\r\n  //***************************************************************************\r\n  //               Maximum Cardinality Matching Functors \r\n  //***************************************************************************\r\n  //***************************************************************************\r\n  \r\n  template <typename Graph, typename MateMap, \r\n            typename VertexIndexMap = dummy_property_map>\r\n  struct no_augmenting_path_finder\r\n  {\r\n    no_augmenting_path_finder(const Graph& g, MateMap mate, VertexIndexMap vm)\r\n    { }\r\n\r\n    inline bool augment_matching() { return false; }\r\n\r\n    template <typename PropertyMap>\r\n    void get_current_matching(PropertyMap p) {}\r\n  };\r\n\r\n\r\n\r\n\r\n  template <typename Graph, typename MateMap, typename VertexIndexMap>\r\n  class edmonds_augmenting_path_finder\r\n  {\r\n    // This implementation of Edmonds' matching algorithm closely\r\n    // follows Tarjan's description of the algorithm in \"Data\r\n    // Structures and Network Algorithms.\"\r\n\r\n  public:\r\n\r\n    //generates the type of an iterator property map from vertices to type X\r\n    template <typename X>\r\n    struct map_vertex_to_ \r\n    { \r\n      typedef boost::iterator_property_map<typename std::vector<X>::iterator,\r\n                                           VertexIndexMap> type; \r\n    };\r\n    \r\n    typedef typename graph_traits<Graph>::vertex_descriptor\r\n      vertex_descriptor_t;\r\n    typedef typename std::pair< vertex_descriptor_t, vertex_descriptor_t >\r\n      vertex_pair_t;\r\n    typedef typename graph_traits<Graph>::edge_descriptor edge_descriptor_t; \r\n    typedef typename graph_traits<Graph>::vertices_size_type v_size_t;\r\n    typedef typename graph_traits<Graph>::edges_size_type e_size_t;\r\n    typedef typename graph_traits<Graph>::vertex_iterator vertex_iterator_t;\r\n    typedef typename graph_traits<Graph>::out_edge_iterator \r\n      out_edge_iterator_t;\r\n    typedef typename std::deque<vertex_descriptor_t> vertex_list_t;\r\n    typedef typename std::vector<edge_descriptor_t> edge_list_t;\r\n    typedef typename map_vertex_to_<vertex_descriptor_t>::type \r\n      vertex_to_vertex_map_t;\r\n    typedef typename map_vertex_to_<int>::type vertex_to_int_map_t;\r\n    typedef typename map_vertex_to_<vertex_pair_t>::type \r\n      vertex_to_vertex_pair_map_t;\r\n    typedef typename map_vertex_to_<v_size_t>::type vertex_to_vsize_map_t;\r\n    typedef typename map_vertex_to_<e_size_t>::type vertex_to_esize_map_t;\r\n\r\n\r\n\r\n    \r\n    edmonds_augmenting_path_finder(const Graph& arg_g, MateMap arg_mate, \r\n                                   VertexIndexMap arg_vm) : \r\n      g(arg_g),\r\n      vm(arg_vm),\r\n      n_vertices(num_vertices(arg_g)),\r\n\r\n      mate_vector(n_vertices),\r\n      ancestor_of_v_vector(n_vertices),\r\n      ancestor_of_w_vector(n_vertices),\r\n      vertex_state_vector(n_vertices),\r\n      origin_vector(n_vertices),\r\n      pred_vector(n_vertices),\r\n      bridge_vector(n_vertices),\r\n      ds_parent_vector(n_vertices),\r\n      ds_rank_vector(n_vertices),\r\n\r\n      mate(mate_vector.begin(), vm),\r\n      ancestor_of_v(ancestor_of_v_vector.begin(), vm),\r\n      ancestor_of_w(ancestor_of_w_vector.begin(), vm),\r\n      vertex_state(vertex_state_vector.begin(), vm),\r\n      origin(origin_vector.begin(), vm),\r\n      pred(pred_vector.begin(), vm),\r\n      bridge(bridge_vector.begin(), vm),\r\n      ds_parent_map(ds_parent_vector.begin(), vm),\r\n      ds_rank_map(ds_rank_vector.begin(), vm),\r\n\r\n      ds(ds_rank_map, ds_parent_map)\r\n    {\r\n      vertex_iterator_t vi, vi_end;\r\n      for(tie(vi,vi_end) = vertices(g); vi != vi_end; ++vi)\r\n        mate[*vi] = get(arg_mate, *vi);\r\n    }\r\n\r\n\r\n    \r\n\r\n    bool augment_matching()\r\n    {\r\n      //As an optimization, some of these values can be saved from one\r\n      //iteration to the next instead of being re-initialized each\r\n      //iteration, allowing for \"lazy blossom expansion.\" This is not\r\n      //currently implemented.\r\n      \r\n      e_size_t timestamp = 0;\r\n      even_edges.clear();\r\n      \r\n      vertex_iterator_t vi, vi_end;\r\n      for(tie(vi,vi_end) = vertices(g); vi != vi_end; ++vi)\r\n      {\r\n        vertex_descriptor_t u = *vi;\r\n      \r\n        origin[u] = u;\r\n        pred[u] = u;\r\n        ancestor_of_v[u] = 0;\r\n        ancestor_of_w[u] = 0;\r\n        ds.make_set(u);\r\n      \r\n        if (mate[u] == graph_traits<Graph>::null_vertex())\r\n        {\r\n          vertex_state[u] = graph::detail::V_EVEN;\r\n          out_edge_iterator_t ei, ei_end;\r\n          for(tie(ei,ei_end) = out_edges(u,g); ei != ei_end; ++ei)\r\n            even_edges.push_back( *ei );\r\n        }\r\n        else\r\n          vertex_state[u] = graph::detail::V_UNREACHED;      \r\n      }\r\n    \r\n      //end initializations\r\n    \r\n      vertex_descriptor_t v,w,w_free_ancestor,v_free_ancestor;\r\n      w_free_ancestor = graph_traits<Graph>::null_vertex();\r\n      v_free_ancestor = graph_traits<Graph>::null_vertex(); \r\n      bool found_alternating_path = false;\r\n      \r\n      while(!even_edges.empty() && !found_alternating_path)\r\n      {\r\n        // since we push even edges onto the back of the list as\r\n        // they're discovered, taking them off the back will search\r\n        // for augmenting paths depth-first.\r\n        edge_descriptor_t current_edge = even_edges.back();\r\n        even_edges.pop_back();\r\n\r\n        v = source(current_edge,g);\r\n        w = target(current_edge,g);\r\n      \r\n        vertex_descriptor_t v_prime = origin[ds.find_set(v)];\r\n        vertex_descriptor_t w_prime = origin[ds.find_set(w)];\r\n      \r\n        // because of the way we put all of the edges on the queue,\r\n        // v_prime should be labeled V_EVEN; the following is a\r\n        // little paranoid but it could happen...\r\n        if (vertex_state[v_prime] != graph::detail::V_EVEN)\r\n        {\r\n          std::swap(v_prime,w_prime);\r\n          std::swap(v,w);\r\n        }\r\n\r\n        if (vertex_state[w_prime] == graph::detail::V_UNREACHED)\r\n        {\r\n          vertex_state[w_prime] = graph::detail::V_ODD;\r\n          vertex_state[mate[w_prime]] = graph::detail::V_EVEN;\r\n          out_edge_iterator_t ei, ei_end;\r\n          for( tie(ei,ei_end) = out_edges(mate[w_prime], g); ei != ei_end; ++ei)\r\n            even_edges.push_back(*ei);\r\n          pred[w_prime] = v;\r\n        }\r\n        \r\n\t\t//w_prime == v_prime can happen below if we get an edge that has been\r\n        //shrunk into a blossom\r\n        else if (vertex_state[w_prime] == graph::detail::V_EVEN && w_prime != v_prime) \r\n        {                                                             \r\n          vertex_descriptor_t w_up = w_prime;\r\n          vertex_descriptor_t v_up = v_prime;\r\n          vertex_descriptor_t nearest_common_ancestor \r\n                = graph_traits<Graph>::null_vertex();\r\n          w_free_ancestor = graph_traits<Graph>::null_vertex();\r\n          v_free_ancestor = graph_traits<Graph>::null_vertex();\r\n          \r\n          // We now need to distinguish between the case that\r\n          // w_prime and v_prime share an ancestor under the\r\n          // \"parent\" relation, in which case we've found a\r\n          // blossom and should shrink it, or the case that\r\n          // w_prime and v_prime both have distinct ancestors that\r\n          // are free, in which case we've found an alternating\r\n          // path between those two ancestors.\r\n\r\n          ++timestamp;\r\n\r\n          while (nearest_common_ancestor == graph_traits<Graph>::null_vertex() && \r\n             (v_free_ancestor == graph_traits<Graph>::null_vertex() || \r\n              w_free_ancestor == graph_traits<Graph>::null_vertex()\r\n              )\r\n             )\r\n          {\r\n            ancestor_of_w[w_up] = timestamp;\r\n            ancestor_of_v[v_up] = timestamp;\r\n\r\n            if (w_free_ancestor == graph_traits<Graph>::null_vertex())\r\n              w_up = parent(w_up);\r\n            if (v_free_ancestor == graph_traits<Graph>::null_vertex())\r\n              v_up = parent(v_up);\r\n          \r\n            if (mate[v_up] == graph_traits<Graph>::null_vertex())\r\n              v_free_ancestor = v_up;\r\n            if (mate[w_up] == graph_traits<Graph>::null_vertex())\r\n              w_free_ancestor = w_up;\r\n          \r\n            if (ancestor_of_w[v_up] == timestamp)\r\n              nearest_common_ancestor = v_up;\r\n            else if (ancestor_of_v[w_up] == timestamp)\r\n              nearest_common_ancestor = w_up;\r\n            else if (v_free_ancestor == w_free_ancestor && \r\n              v_free_ancestor != graph_traits<Graph>::null_vertex())\r\n            nearest_common_ancestor = v_up;\r\n          }\r\n          \r\n          if (nearest_common_ancestor == graph_traits<Graph>::null_vertex())\r\n            found_alternating_path = true; //to break out of the loop\r\n          else\r\n          {\r\n            //shrink the blossom\r\n            link_and_set_bridges(w_prime, nearest_common_ancestor, std::make_pair(w,v));\r\n            link_and_set_bridges(v_prime, nearest_common_ancestor, std::make_pair(v,w));\r\n          }\r\n        }      \r\n      }\r\n      \r\n      if (!found_alternating_path)\r\n        return false;\r\n\r\n      // retrieve the augmenting path and put it in aug_path\r\n      reversed_retrieve_augmenting_path(v, v_free_ancestor);\r\n      retrieve_augmenting_path(w, w_free_ancestor);\r\n\r\n      // augment the matching along aug_path\r\n      vertex_descriptor_t a,b;\r\n      while (!aug_path.empty())\r\n      {\r\n        a = aug_path.front();\r\n        aug_path.pop_front();\r\n        b = aug_path.front();\r\n        aug_path.pop_front();\r\n        mate[a] = b;\r\n        mate[b] = a;\r\n      }\r\n      \r\n      return true;\r\n      \r\n    }\r\n\r\n\r\n\r\n\r\n    template <typename PropertyMap>\r\n    void get_current_matching(PropertyMap pm)\r\n    {\r\n      vertex_iterator_t vi,vi_end;\r\n      for(tie(vi,vi_end) = vertices(g); vi != vi_end; ++vi)\r\n        put(pm, *vi, mate[*vi]);\r\n    }\r\n\r\n\r\n\r\n\r\n    template <typename PropertyMap>\r\n    void get_vertex_state_map(PropertyMap pm)\r\n    {\r\n      vertex_iterator_t vi,vi_end;\r\n      for(tie(vi,vi_end) = vertices(g); vi != vi_end; ++vi)\r\n        put(pm, *vi, vertex_state[origin[ds.find_set(*vi)]]);\r\n    }\r\n\r\n\r\n\r\n\r\n  private:    \r\n\r\n    vertex_descriptor_t parent(vertex_descriptor_t x)\r\n    {\r\n      if (vertex_state[x] == graph::detail::V_EVEN \r\n          && mate[x] != graph_traits<Graph>::null_vertex())\r\n        return mate[x];\r\n      else if (vertex_state[x] == graph::detail::V_ODD)\r\n        return origin[ds.find_set(pred[x])];\r\n      else\r\n        return x;\r\n    }\r\n    \r\n    \r\n\r\n\r\n    void link_and_set_bridges(vertex_descriptor_t x, \r\n                              vertex_descriptor_t stop_vertex, \r\n                  vertex_pair_t the_bridge)\r\n    {\r\n      for(vertex_descriptor_t v = x; v != stop_vertex; v = parent(v))\r\n      {\r\n        ds.union_set(v, stop_vertex);\r\n        origin[ds.find_set(stop_vertex)] = stop_vertex;\r\n\r\n        if (vertex_state[v] == graph::detail::V_ODD)\r\n        {\r\n          bridge[v] = the_bridge;\r\n          out_edge_iterator_t oei, oei_end;\r\n          for(tie(oei, oei_end) = out_edges(v,g); oei != oei_end; ++oei)\r\n            even_edges.push_back(*oei);\r\n        }\r\n      }\r\n    }\r\n    \r\n\r\n    // Since none of the STL containers support both constant-time\r\n    // concatenation and reversal, the process of expanding an\r\n    // augmenting path once we know one exists is a little more\r\n    // complicated than it has to be. If we know the path is from v to\r\n    // w, then the augmenting path is recursively defined as:\r\n    //\r\n    // path(v,w) = [v], if v = w\r\n    //           = concat([v, mate[v]], path(pred[mate[v]], w), \r\n    //                if v != w and vertex_state[v] == graph::detail::V_EVEN\r\n    //           = concat([v], reverse(path(x,mate[v])), path(y,w)),\r\n    //                if v != w, vertex_state[v] == graph::detail::V_ODD, and bridge[v] = (x,y)\r\n    //\r\n    // These next two mutually recursive functions implement this definition.\r\n    \r\n    void retrieve_augmenting_path(vertex_descriptor_t v, vertex_descriptor_t w)  \r\n    {\r\n      if (v == w)\r\n        aug_path.push_back(v);\r\n      else if (vertex_state[v] == graph::detail::V_EVEN)\r\n      {\r\n        aug_path.push_back(v);\r\n        aug_path.push_back(mate[v]);\r\n        retrieve_augmenting_path(pred[mate[v]], w);\r\n      }\r\n      else //vertex_state[v] == graph::detail::V_ODD \r\n      {\r\n        aug_path.push_back(v);\r\n        reversed_retrieve_augmenting_path(bridge[v].first, mate[v]);\r\n        retrieve_augmenting_path(bridge[v].second, w);\r\n      }\r\n    }\r\n\r\n\r\n    void reversed_retrieve_augmenting_path(vertex_descriptor_t v,\r\n                                           vertex_descriptor_t w)  \r\n    {\r\n\r\n      if (v == w)\r\n        aug_path.push_back(v);\r\n      else if (vertex_state[v] == graph::detail::V_EVEN)\r\n      {\r\n        reversed_retrieve_augmenting_path(pred[mate[v]], w);\r\n        aug_path.push_back(mate[v]);\r\n        aug_path.push_back(v);\r\n      }\r\n      else //vertex_state[v] == graph::detail::V_ODD \r\n      {\r\n        reversed_retrieve_augmenting_path(bridge[v].second, w);\r\n        retrieve_augmenting_path(bridge[v].first, mate[v]);\r\n        aug_path.push_back(v);\r\n      }\r\n    }\r\n\r\n    \r\n\r\n\r\n    //private data members\r\n    \r\n    const Graph& g;\r\n    VertexIndexMap vm;\r\n    v_size_t n_vertices;\r\n    \r\n    //storage for the property maps below\r\n    std::vector<vertex_descriptor_t> mate_vector;\r\n    std::vector<e_size_t> ancestor_of_v_vector;\r\n    std::vector<e_size_t> ancestor_of_w_vector;\r\n    std::vector<int> vertex_state_vector;\r\n    std::vector<vertex_descriptor_t> origin_vector;\r\n    std::vector<vertex_descriptor_t> pred_vector;\r\n    std::vector<vertex_pair_t> bridge_vector;\r\n    std::vector<vertex_descriptor_t> ds_parent_vector;\r\n    std::vector<v_size_t> ds_rank_vector;\r\n\r\n    //iterator property maps\r\n    vertex_to_vertex_map_t mate;\r\n    vertex_to_esize_map_t ancestor_of_v;\r\n    vertex_to_esize_map_t ancestor_of_w;\r\n    vertex_to_int_map_t vertex_state;\r\n    vertex_to_vertex_map_t origin;\r\n    vertex_to_vertex_map_t pred;\r\n    vertex_to_vertex_pair_map_t bridge;\r\n    vertex_to_vertex_map_t ds_parent_map;\r\n    vertex_to_vsize_map_t ds_rank_map;\r\n\r\n    vertex_list_t aug_path;\r\n    edge_list_t even_edges;\r\n    disjoint_sets< vertex_to_vsize_map_t, vertex_to_vertex_map_t > ds;\r\n\r\n  };\r\n\r\n\r\n\r\n\r\n  //***************************************************************************\r\n  //***************************************************************************\r\n  //               Initial Matching Functors\r\n  //***************************************************************************\r\n  //***************************************************************************\r\n  \r\n  template <typename Graph, typename MateMap>\r\n  struct greedy_matching\r\n  {\r\n    typedef typename graph_traits< Graph >::vertex_descriptor vertex_descriptor_t;\r\n    typedef typename graph_traits< Graph >::vertex_iterator vertex_iterator_t;\r\n    typedef typename graph_traits< Graph >::edge_descriptor edge_descriptor_t; \r\n    typedef typename graph_traits< Graph >::edge_iterator edge_iterator_t;\r\n\r\n    static void find_matching(const Graph& g, MateMap mate)\r\n    {\r\n      vertex_iterator_t vi, vi_end;\r\n      for(tie(vi,vi_end) = vertices(g); vi != vi_end; ++vi)\r\n        put(mate, *vi, graph_traits<Graph>::null_vertex());\r\n            \r\n      edge_iterator_t ei, ei_end;\r\n      for( tie(ei, ei_end) = edges(g); ei != ei_end; ++ei)\r\n      {\r\n        edge_descriptor_t e = *ei;\r\n        vertex_descriptor_t u = source(e,g);\r\n        vertex_descriptor_t v = target(e,g);\r\n      \r\n        if (get(mate,u) == get(mate,v))  \r\n        //only way equality can hold is if\r\n        //   mate[u] == mate[v] == null_vertex\r\n        {\r\n          put(mate,u,v);\r\n          put(mate,v,u);\r\n        }\r\n      }    \r\n    }\r\n  };\r\n  \r\n\r\n\r\n  \r\n  template <typename Graph, typename MateMap>\r\n  struct extra_greedy_matching\r\n  {\r\n    // The \"extra greedy matching\" is formed by repeating the\r\n    // following procedure as many times as possible: Choose the\r\n    // unmatched vertex v of minimum non-zero degree.  Choose the\r\n    // neighbor w of v which is unmatched and has minimum degree over\r\n    // all of v's neighbors. Add (u,v) to the matching. Ties for\r\n    // either choice are broken arbitrarily. This procedure takes time\r\n    // O(m log n), where m is the number of edges in the graph and n\r\n    // is the number of vertices.\r\n    \r\n    typedef typename graph_traits< Graph >::vertex_descriptor\r\n      vertex_descriptor_t;\r\n    typedef typename graph_traits< Graph >::vertex_iterator vertex_iterator_t;\r\n    typedef typename graph_traits< Graph >::edge_descriptor edge_descriptor_t; \r\n    typedef typename graph_traits< Graph >::edge_iterator edge_iterator_t;\r\n    typedef std::pair<vertex_descriptor_t, vertex_descriptor_t> vertex_pair_t;\r\n    \r\n    struct select_first\r\n    {\r\n      inline static vertex_descriptor_t select_vertex(const vertex_pair_t p) \r\n      {return p.first;}\r\n    };\r\n\r\n    struct select_second\r\n    {\r\n      inline static vertex_descriptor_t select_vertex(const vertex_pair_t p) \r\n      {return p.second;}\r\n    };\r\n\r\n    template <class PairSelector>\r\n    class less_than_by_degree\r\n    {\r\n    public:\r\n      less_than_by_degree(const Graph& g): m_g(g) {}\r\n      bool operator() (const vertex_pair_t x, const vertex_pair_t y)\r\n      {\r\n        return \r\n          out_degree(PairSelector::select_vertex(x), m_g) \r\n          < out_degree(PairSelector::select_vertex(y), m_g);\r\n      }\r\n    private:\r\n      const Graph& m_g;\r\n    };\r\n\r\n\r\n    static void find_matching(const Graph& g, MateMap mate)\r\n    {\r\n      typedef std::vector<std::pair<vertex_descriptor_t, vertex_descriptor_t> >\r\n        directed_edges_vector_t;\r\n      \r\n      directed_edges_vector_t edge_list;\r\n      vertex_iterator_t vi, vi_end;\r\n      for(tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi)\r\n        put(mate, *vi, graph_traits<Graph>::null_vertex());\r\n\r\n      edge_iterator_t ei, ei_end;\r\n      for(tie(ei, ei_end) = edges(g); ei != ei_end; ++ei)\r\n      {\r\n        edge_descriptor_t e = *ei;\r\n        vertex_descriptor_t u = source(e,g);\r\n        vertex_descriptor_t v = target(e,g);\r\n        edge_list.push_back(std::make_pair(u,v));\r\n        edge_list.push_back(std::make_pair(v,u));\r\n      }\r\n      \r\n      //sort the edges by the degree of the target, then (using a\r\n      //stable sort) by degree of the source\r\n      std::sort(edge_list.begin(), edge_list.end(), \r\n                less_than_by_degree<select_second>(g));\r\n      std::stable_sort(edge_list.begin(), edge_list.end(), \r\n                       less_than_by_degree<select_first>(g));\r\n      \r\n      //construct the extra greedy matching\r\n      for(typename directed_edges_vector_t::const_iterator itr = edge_list.begin(); itr != edge_list.end(); ++itr)\r\n      {\r\n        if (get(mate,itr->first) == get(mate,itr->second)) \r\n        //only way equality can hold is if mate[itr->first] == mate[itr->second] == null_vertex\r\n        {\r\n          put(mate, itr->first, itr->second);\r\n          put(mate, itr->second, itr->first);\r\n        }\r\n      }    \r\n    }\r\n  };\r\n\r\n\r\n  \r\n\r\n  template <typename Graph, typename MateMap>\r\n  struct empty_matching\r\n  { \r\n    typedef typename graph_traits< Graph >::vertex_iterator vertex_iterator_t;\r\n    \r\n    static void find_matching(const Graph& g, MateMap mate)\r\n    {\r\n      vertex_iterator_t vi, vi_end;\r\n      for(tie(vi,vi_end) = vertices(g); vi != vi_end; ++vi)\r\n        put(mate, *vi, graph_traits<Graph>::null_vertex());\r\n    }\r\n  };\r\n  \r\n\r\n\r\n\r\n  //***************************************************************************\r\n  //***************************************************************************\r\n  //               Matching Verifiers\r\n  //***************************************************************************\r\n  //***************************************************************************\r\n\r\n  namespace detail\r\n  {\r\n\r\n    template <typename SizeType>\r\n    class odd_components_counter : public dfs_visitor<>\r\n    // This depth-first search visitor will count the number of connected \r\n    // components with an odd number of vertices. It's used by \r\n    // maximum_matching_verifier.\r\n    {\r\n    public:\r\n      odd_components_counter(SizeType& c_count):\r\n        m_count(c_count)\r\n      {\r\n        m_count = 0;\r\n      }\r\n      \r\n      template <class Vertex, class Graph>\r\n      void start_vertex(Vertex v, Graph&) \r\n      {\r\n        m_parity = false; \r\n      }\r\n      \r\n      template <class Vertex, class Graph>\r\n      void discover_vertex(Vertex u, Graph&) \r\n      {\r\n        m_parity = !m_parity;\r\n\t\tm_parity ? ++m_count : --m_count;\r\n      }\r\n      \r\n    protected:\r\n      SizeType& m_count;\r\n      \r\n    private:\r\n      bool m_parity;\r\n      \r\n    };\r\n\r\n  }//namespace detail\r\n\r\n\r\n\r\n\r\n  template <typename Graph, typename MateMap, \r\n            typename VertexIndexMap = dummy_property_map>\r\n  struct no_matching_verifier\r\n  {\r\n    inline static bool \r\n    verify_matching(const Graph& g, MateMap mate, VertexIndexMap vm) \r\n    { return true;}\r\n  };\r\n  \r\n  \r\n\r\n\r\n  template <typename Graph, typename MateMap, typename VertexIndexMap>\r\n  struct maximum_cardinality_matching_verifier\r\n  {\r\n\r\n    template <typename X>\r\n    struct map_vertex_to_\r\n    { \r\n      typedef boost::iterator_property_map<typename std::vector<X>::iterator,\r\n                                           VertexIndexMap> type; \r\n    };\r\n\r\n    typedef typename graph_traits<Graph>::vertex_descriptor \r\n      vertex_descriptor_t;\r\n    typedef typename graph_traits<Graph>::vertices_size_type v_size_t;\r\n    typedef typename graph_traits<Graph>::vertex_iterator vertex_iterator_t;\r\n    typedef typename map_vertex_to_<int>::type vertex_to_int_map_t;\r\n    typedef typename map_vertex_to_<vertex_descriptor_t>::type \r\n      vertex_to_vertex_map_t;\r\n\r\n\r\n    template <typename VertexStateMap>\r\n    struct non_odd_vertex {\r\n      //this predicate is used to create a filtered graph that\r\n      //excludes vertices labeled \"graph::detail::V_ODD\"\r\n      non_odd_vertex() : vertex_state(0) { }\r\n  \r\n\t  non_odd_vertex(VertexStateMap* arg_vertex_state) \r\n        : vertex_state(arg_vertex_state) { }\r\n\r\n\t  template <typename Vertex>\r\n      bool operator()(const Vertex& v) const \r\n\t  {\r\n        BOOST_ASSERT(vertex_state);\r\n        return get(*vertex_state, v) != graph::detail::V_ODD;\r\n      }\r\n\r\n      VertexStateMap* vertex_state;\r\n    };\r\n\r\n\r\n    static bool verify_matching(const Graph& g, MateMap mate, VertexIndexMap vm)\r\n    {\r\n      //For any graph G, let o(G) be the number of connected\r\n      //components in G of odd size. For a subset S of G's vertex set\r\n      //V(G), let (G - S) represent the subgraph of G induced by\r\n      //removing all vertices in S from G. Let M(G) be the size of the\r\n      //maximum cardinality matching in G. Then the Tutte-Berge\r\n      //formula guarantees that\r\n      //\r\n      //           2 * M(G) = min ( |V(G)| + |U| + o(G - U) )\r\n      //\r\n      //where the minimum is taken over all subsets U of\r\n      //V(G). Edmonds' algorithm finds a set U that achieves the\r\n      //minimum in the above formula, namely the vertices labeled\r\n      //\"ODD.\" This function runs one iteration of Edmonds' algorithm\r\n      //to find U, then verifies that the size of the matching given\r\n      //by mate satisfies the Tutte-Berge formula.\r\n\r\n      //first, make sure it's a valid matching\r\n      if (!is_a_matching(g,mate,vm))\r\n        return false;\r\n\r\n      //We'll try to augment the matching once. This serves two\r\n      //purposes: first, if we find some augmenting path, the matching\r\n      //is obviously non-maximum. Second, running edmonds' algorithm\r\n      //on a graph with no augmenting path will create the\r\n      //Edmonds-Gallai decomposition that we need as a certificate of\r\n      //maximality - we can get it by looking at the vertex_state map\r\n      //that results.\r\n      edmonds_augmenting_path_finder<Graph,MateMap,VertexIndexMap>\r\n        augmentor(g,mate,vm);\r\n      if (augmentor.augment_matching())\r\n        return false;\r\n\r\n      std::vector<int> vertex_state_vector(num_vertices(g));\r\n      vertex_to_int_map_t vertex_state(vertex_state_vector.begin(), vm);\r\n      augmentor.get_vertex_state_map(vertex_state);\r\n      \r\n      //count the number of graph::detail::V_ODD vertices\r\n      v_size_t num_odd_vertices = 0;\r\n      vertex_iterator_t vi, vi_end;\r\n      for(tie(vi,vi_end) = vertices(g); vi != vi_end; ++vi)\r\n        if (vertex_state[*vi] == graph::detail::V_ODD)\r\n          ++num_odd_vertices;\r\n\r\n      //count the number of connected components with odd cardinality\r\n      //in the graph without graph::detail::V_ODD vertices\r\n      non_odd_vertex<vertex_to_int_map_t> filter(&vertex_state);\r\n      filtered_graph<Graph, keep_all, non_odd_vertex<vertex_to_int_map_t> > fg(g, keep_all(), filter);\r\n\r\n      v_size_t num_odd_components;\r\n      detail::odd_components_counter<v_size_t> occ(num_odd_components);\r\n      depth_first_search(fg, visitor(occ).vertex_index_map(vm));\r\n\r\n      if (2 * matching_size(g,mate,vm) == num_vertices(g) + num_odd_vertices - num_odd_components)\r\n        return true;\r\n      else\r\n        return false;\r\n    }\r\n  };\r\n\r\n\r\n\r\n\r\n  template <typename Graph, \r\n        typename MateMap,\r\n        typename VertexIndexMap,\r\n        template <typename, typename, typename> class AugmentingPathFinder, \r\n        template <typename, typename> class InitialMatchingFinder,\r\n        template <typename, typename, typename> class MatchingVerifier>\r\n  bool matching(const Graph& g, MateMap mate, VertexIndexMap vm)\r\n  {\r\n    \r\n    InitialMatchingFinder<Graph,MateMap>::find_matching(g,mate);\r\n\r\n    AugmentingPathFinder<Graph,MateMap,VertexIndexMap> augmentor(g,mate,vm);\r\n    bool not_maximum_yet = true;\r\n    while(not_maximum_yet)\r\n      {\r\n        not_maximum_yet = augmentor.augment_matching();\r\n      }\r\n    augmentor.get_current_matching(mate);\r\n\r\n    return MatchingVerifier<Graph,MateMap,VertexIndexMap>::verify_matching(g,mate,vm);    \r\n    \r\n  }\r\n\r\n\r\n\r\n\r\n  template <typename Graph, typename MateMap, typename VertexIndexMap>\r\n  inline bool checked_edmonds_maximum_cardinality_matching(const Graph& g, MateMap mate, VertexIndexMap vm)\r\n  {\r\n    return matching \r\n      < Graph, MateMap, VertexIndexMap,\r\n        edmonds_augmenting_path_finder, extra_greedy_matching, maximum_cardinality_matching_verifier>\r\n      (g, mate, vm);\r\n  }\r\n\r\n\r\n\r\n\r\n  template <typename Graph, typename MateMap>\r\n  inline bool checked_edmonds_maximum_cardinality_matching(const Graph& g, MateMap mate)\r\n  {\r\n    return checked_edmonds_maximum_cardinality_matching(g, mate, get(vertex_index,g));\r\n  }\r\n\r\n\r\n\r\n\r\n  template <typename Graph, typename MateMap, typename VertexIndexMap>\r\n  inline void edmonds_maximum_cardinality_matching(const Graph& g, MateMap mate, VertexIndexMap vm)\r\n  {\r\n    matching < Graph, MateMap, VertexIndexMap,\r\n               edmonds_augmenting_path_finder, extra_greedy_matching, no_matching_verifier>\r\n      (g, mate, vm);\r\n  }\r\n\r\n\r\n\r\n\r\n  template <typename Graph, typename MateMap>\r\n  inline void edmonds_maximum_cardinality_matching(const Graph& g, MateMap mate)\r\n  {\r\n    edmonds_maximum_cardinality_matching(g, mate, get(vertex_index,g));\r\n  }\r\n\r\n}//namespace boost\r\n\r\n#endif //BOOST_GRAPH_MAXIMUM_CARDINALITY_MATCHING_HPP\r\n", "meta": {"hexsha": "2405d599586a94939f37ea160638de9a020ee257", "size": 30271, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "windows/include/boost/graph/max_cardinality_matching.hpp", "max_stars_repo_name": "jaredhoberock/gotham", "max_stars_repo_head_hexsha": "e3551cc355646530574d086d7cc2b82e41e8f798", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-12-29T07:21:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-29T10:47:38.000Z", "max_issues_repo_path": "external/windows/boost/include/boost/graph/max_cardinality_matching.hpp", "max_issues_repo_name": "foxostro/CheeseTesseract", "max_issues_repo_head_hexsha": "737ebbd19cee8f5a196bf39a11ca793c561e56cb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "external/windows/boost/include/boost/graph/max_cardinality_matching.hpp", "max_forks_repo_name": "foxostro/CheeseTesseract", "max_forks_repo_head_hexsha": "737ebbd19cee8f5a196bf39a11ca793c561e56cb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.2432126697, "max_line_length": 115, "alphanum_fraction": 0.6042747184, "num_tokens": 6778, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.6548947155710233, "lm_q1q2_score": 0.4600832221179277}}
{"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 \"metro/likelihood/Multinomial.hpp\"\n#include \"components/SNPSummaryComponent/SNPHWE.hpp\"\n#include \"components/SNPSummaryComponent/HWEComputation.hpp\"\n#include \"metro/likelihood/Multinomial.hpp\"\n#include \"metro/likelihood/ProductOfMultinomials.hpp\"\n#include \"metro/FishersExactTest.hpp\"\n\n// #define DEBUG_HWE_COMPUTATION 1\n\nnamespace stats {\n\tHWEComputation::HWEComputation():\n\t\tm_threshhold( 0.9 ),\n\t\tm_chi_squared_1df( 1.0 ),\n\t\tm_chi_squared_2df( 2.0 )\n\t{}\n\t\n\tvoid HWEComputation::operator()(\n\t\tVariantIdentifyingData const& snp,\n\t\tGenotypes const& genotypes,\n\t\tPloidy const& ploidy,\n\t\tgenfile::VariantDataReader&,\n\t\tResultCallback callback\n\t) {\n\t\tgenfile::Chromosome const& chromosome = snp.get_position().chromosome() ;\n\t\tif( snp.number_of_alleles() == 2 ) {\n\t\t\tif( chromosome.is_sex_determining() ) {\n\t\t\t\tX_chromosome_test( snp, genotypes, ploidy, callback ) ;\n\t\t\t} else {\n\t\t\t\tautosomal_test( snp, genotypes, callback ) ;\n\t\t\t}\n\t\t}\n\t}\n\n\tstd::string HWEComputation::get_summary( std::string const& prefix, std::size_t column_width ) const { return prefix + \"HWEComputation\" ; }\n\n\tvoid HWEComputation::autosomal_test( VariantIdentifyingData const& snp, Genotypes const& genotypes, ResultCallback callback ) {\n\t\tEigen::VectorXd genotype_counts = Eigen::VectorXd::Zero( 3 ) ;\n\t\tfor( int g = 0; g < 3; ++g ) {\n\t\t\tgenotype_counts( g ) = std::floor( genotypes.col(g).sum() + 0.5 ) ;\n\t\t}\n\t\tautosomal_exact_test( snp, genotype_counts, callback ) ;\n\t\tautosomal_multinomial_test( snp, genotype_counts, callback ) ;\n\t}\n\n\tvoid HWEComputation::autosomal_exact_test( VariantIdentifyingData const& snp, Eigen::VectorXd const& genotype_counts, ResultCallback callback ) {\n\t\tif( genotype_counts.array().maxCoeff() > 0.5 ) {\n\t\t\tdouble HWE_pvalue = SNPHWE( genotype_counts(1), genotype_counts(0), genotype_counts(2) ) ;\n\t\t\tcallback( \"HW_exact_p_value\", HWE_pvalue ) ;\n\t\t}\n\t\telse {\n\t\t\tcallback( \"HW_exact_p_value\", genfile::MissingValue() ) ;\n\t\t}\n\t}\n\n\tvoid HWEComputation::autosomal_multinomial_test( VariantIdentifyingData const& snp, Eigen::VectorXd const& genotype_counts, ResultCallback callback ) {\n\t\tmetro::likelihood::Multinomial< double, Eigen::VectorXd, Eigen::MatrixXd > hw_model( genotype_counts ) ;\n\t\t{\n\t\t\t// compute MLE under assumption of hardy-weinberg.\n\t\t\tdouble p = 2.0 * genotype_counts( 2 ) + genotype_counts( 1 ) ;\n\t\t\tp /= 2.0 * genotype_counts.sum() ;\n\t\t\tEigen::VectorXd a = Eigen::VectorXd::Zero( 3 ) ;\n\t\t\ta( 0 ) = ( 1 - p ) * ( 1 - p ) ;\n\t\t\ta( 1 ) = 2.0 * p * ( 1 - p ) ;\n\t\t\ta( 2 ) = p * p ;\n\t\t\thw_model.evaluate_at( a ) ;\n\t\t}\n\n\t\tmetro::likelihood::Multinomial< double, Eigen::VectorXd, Eigen::MatrixXd > full_model( genotype_counts ) ;\n\t\tfull_model.evaluate_at( full_model.get_MLE() ) ;\n\t\t\n#if DEBUG_HWE_COMPUTATION\n\t\tstd::cerr << std::fixed << std::setprecision( 5 );\n\t\tstd::cerr << \"table = \" << genotype_counts.transpose() << \"...\\n\" ;\n\t\tstd::cerr << std::resetiosflags( std::ios::floatfield ) ;\n\t\tstd::cerr << \"hw_model.MLE = \" << hw_model.get_parameters().transpose() << \", loglikelihood = \" << hw_model.get_value_of_function() << \"...\\n\" ;\n\t\tstd::cerr << \"full_model.MLE = \" << full_model.get_parameters().transpose() << \", loglikelihood = \" << full_model.get_value_of_function() << \"...\\n\" ;\n#endif\n\t\t\n\t\tdouble likelihood_ratio_statistic = 2.0 * ( full_model.get_value_of_function() - hw_model.get_value_of_function() ) ;\n\t\tdouble p_value = std::numeric_limits< double >::quiet_NaN() ;\n\t\tif( likelihood_ratio_statistic != likelihood_ratio_statistic || likelihood_ratio_statistic < 0.0 ) {\n\t\t\tlikelihood_ratio_statistic = std::numeric_limits< double >::quiet_NaN() ;\n\t\t}\n\t\telse {\n\t\t\tp_value = boost::math::cdf(\n\t\t\t\tboost::math::complement(\n\t\t\t\t\tm_chi_squared_1df,\n\t\t\t\t\tlikelihood_ratio_statistic\n\t\t\t\t)\n\t\t\t) ;\n\t\t}\n\t\t\n\t\tcallback( \"HW_lrt_p_value\", p_value ) ;\n\t}\n\n\tvoid HWEComputation::X_chromosome_test( VariantIdentifyingData const& snp, Genotypes const& genotypes, Ploidy const& ploidy, ResultCallback callback ) {\n\t\t// We look at three models and perform two LR tests.\n\t\t// model1: full model, males and females may have different frequencies and no assumption of HW in females.  (3 parameters)\n\t\t// model2: HWE holds in females, but males and females may have different frequencies. (2 parameters)\n\t\t// model3: HWE holds in females and males and females have the same frequency. (1 parameter)\n\t\t//\n\t\t// test1: test that males and females have the same allele frequency\n\t\t// test2: test HWE in females.\n\t\t//\n\t\t// Note: males will be called as 0/1 on the X and Y chromosomes.\n\t\tEigen::MatrixXd genotype_counts = Eigen::MatrixXd::Zero( 2, 3 ) ; // first row is males, second row is females.  Last column will be zero for males.\n\t\tEigen::MatrixXd allele_counts = Eigen::MatrixXd::Zero( 2, 2 ) ; // first row is males, second row is females.\n\n\t\ttypedef Eigen::VectorXd Vector ;\n\n\t\tint const HAPLOID = 0 ;\n\t\tint const DIPLOID = 1 ;\n\n\t\tfor( int i = 0; i < genotypes.rows(); ++i ) {\n\t\t\tif( ploidy(i) == 1 || ploidy(i) == 2 ) {\n\t\t\t\tint const index = ploidy(i) - 1 ;\n\t\t\t\tfor( int g = 0; g < 3; ++g ) {\n\t\t\t\t\tif( genotypes( i, g ) > m_threshhold ) {\n\t\t\t\t\t\t++genotype_counts( index, g ) ;\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}\n\t\tfor( int g = 0; g < 2; ++g ) {\n\t\t\tallele_counts( 0, g ) = genotype_counts( 0, g ) ;\n\t\t\tallele_counts( 1, g ) = genotype_counts( 1, 1 ) + 2.0 * genotype_counts( 1, 2.0 * g ) ;\n\t\t}\n\n\t\tif( genotype_counts.maxCoeff() == 0 ) {\n\t\t\t\tcallback( \"HW_females_exact_pvalue\", genfile::MissingValue() ) ;\n\t\t\t\tcallback( \"HW_females_lrt_pvalue\", genfile::MissingValue()) ;\n\t\t\t\tcallback( \"male_female_exact_pvalue\", genfile::MissingValue() ) ;\n\t\t\t\tcallback( \"male_female_lrt_pvalue\", genfile::MissingValue() ) ;\n\t\t\t\tcallback( \"male_female_and_HW_lrt_pvalue\", genfile::MissingValue() ) ;\n\n\t\t} else {\n\t\t\ttypedef metro::likelihood::Multinomial< double, Eigen::VectorXd, Eigen::MatrixXd > Multinomial ;\n\t\t\ttypedef metro::likelihood::ProductOfMultinomials< double, Eigen::VectorXd, Eigen::MatrixXd > ProductOfIndependentMultinomials ;\n\t\t\t// In model 1 each genotype is allowed to have its own frequency.\n\t\t\t// Morever males and females may have different frequencies\n\t\t\tProductOfIndependentMultinomials full_model( genotype_counts ) ;\n\t\t\tfull_model.evaluate_at( full_model.get_MLE() ) ;\n\n\t\t\t// In model2 alleles are independent (HWE) in females, but males and females may differ.\n\t\t\tProductOfIndependentMultinomials model2( genotype_counts ) ;\n\t\t\t{\n\t\t\t\tdouble const p_females = ( 2 * genotype_counts( DIPLOID, 0 ) + genotype_counts( DIPLOID, 1 ) ) / (2 * genotype_counts.row( DIPLOID ).sum() ) ;\n\t\t\t\tdouble const p_males = genotype_counts( HAPLOID, 0 ) / genotype_counts.row( HAPLOID ).sum() ;\n\t\t\t\tVector params( 6 ) ;\n\t\t\t\tparams( 0 ) = p_males ;\n\t\t\t\tparams( 1 ) = 1-p_males ;\n\t\t\t\tparams( 2 ) = 0 ;\n\t\t\t\tparams( 3 ) = p_females * p_females ;\n\t\t\t\tparams( 4 ) = 2 * p_females * (1-p_females) ;\n\t\t\t\tparams( 5 ) = (1-p_females) * (1-p_females) ;\n\t\t\t\tmodel2.evaluate_at( params ) ;\n\t\t\t}\n\n\t\t\t// In model3, the NULL model, alleles are independent (HWE) and males and females must agree.\n\t\t\tProductOfIndependentMultinomials model3( genotype_counts ) ;\n\t\t\t{\n\t\t\t\tdouble const p = ( 2 * genotype_counts( DIPLOID, 0 ) + genotype_counts( HAPLOID, 0 ) + genotype_counts( DIPLOID, 1 ) )\n\t\t\t\t\t/ ( 2 * genotype_counts.row( DIPLOID ).sum() + genotype_counts.row( HAPLOID ).sum() ) ;\n\t\t\t\t\n\t\t\t\tVector params( 6 ) ;\n\t\t\t\tparams( 0 ) = p ;\n\t\t\t\tparams( 1 ) = (1-p) ;\n\t\t\t\tparams( 2 ) = 0 ;\n\t\t\t\tparams( 3 ) = p * p ;\n\t\t\t\tparams( 4 ) = 2 * p * (1-p) ;\n\t\t\t\tparams( 5 ) = (1-p) * (1-p) ;\n\t\t\t\tmodel3.evaluate_at( params ) ;\n\t\t\t}\n\n#if DEBUG_HWE_COMPUTATION\n\t\t\tstd::cerr << \"Genotype counts:\\n\" << genotype_counts << \"\\n\" ;\n\t\t\tstd::cerr << \"Allele counts:\\n\" << allele_counts << \"\\n\" ;\n\t\t\tstd::cerr << \"Model 1 params: \" << full_model.get_parameters().transpose() << \".\\n\" ;\n\t\t\tstd::cerr << \"Model 2 params: \" << model2.get_parameters().transpose() << \".\\n\" ;\n\t\t\tstd::cerr << \"Model 3 params: \" << model3.get_parameters().transpose() << \".\\n\" ;\n#endif\n\t\t\tdouble const NaN = std::numeric_limits< double >::quiet_NaN() ;\n\n\t\t\tusing boost::math::cdf ;\n\t\t\tusing boost::math::complement ;\n\n\t\t\tif( genotype_counts.row( DIPLOID ).array().maxCoeff() > 0.5 ) {\n\t\t\t\tdouble exact_HWE_pvalue = SNPHWE( genotype_counts( DIPLOID, 1 ), genotype_counts( DIPLOID, 0 ), genotype_counts( DIPLOID, 2 ) ) ;\n\t\t\t\tcallback( \"HW_females_exact_pvalue\", exact_HWE_pvalue ) ;\n\t\t\t} else {\n\t\t\t\tcallback( \"HW_females_exact_pvalue\", genfile::MissingValue() ) ;\n\t\t\t}\n\t\t\t\n\t\t\tdouble const lr_stat_12 = 2.0 * ( full_model.get_value_of_function() - model2.get_value_of_function() ) ;\n\t\t\tdouble p_value_12 = NaN ;\n\t\t\tif( lr_stat_12 == lr_stat_12 && lr_stat_12 > 0 && lr_stat_12 != std::numeric_limits< double >::infinity() ) {\n\t\t\t\tp_value_12 = cdf( complement( m_chi_squared_1df, lr_stat_12 ) ) ;\n\t\t\t\tcallback( \"HW_females_lrt_pvalue\", p_value_12 ) ;\n\t\t\t} else {\n\t\t\t\tcallback( \"HW_females_lrt_pvalue\", genfile::MissingValue()) ;\n\t\t\t}\n\n\t\t\t// Also get exact male/female p-value\n\t\t\t{\n\t\t\t\tEigen::Matrix2d A = allele_counts ;\n\t\t\t\tA(0,0) = std::floor( A(0,0) + 0.5 ) ;\n\t\t\t\tA(0,1) = std::floor( A(0,1) + 0.5 ) ;\n\t\t\t\tA(1,0) = std::floor( A(1,0) + 0.5 ) ;\n\t\t\t\tA(1,1) = std::floor( A(1,1) + 0.5 ) ;\n\t\t\t\tdouble const male_female_pvalue = metro::FishersExactTest( A ).get_pvalue( metro::FishersExactTest::eTwoSided ) ;\n\t\t\t\tif( male_female_pvalue == male_female_pvalue ) {\n\t\t\t\t\tcallback( \"male_female_exact_pvalue\", male_female_pvalue ) ;\n\t\t\t\t} else {\n\t\t\t\t\tcallback( \"male_female_exact_pvalue\", genfile::MissingValue() ) ;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tdouble const lr_stat_23 = 2.0 * ( model2.get_value_of_function() - model3.get_value_of_function() ) ;\n\t\t\tdouble p_value_23 = NaN ;\n\t\t\tif( lr_stat_23 == lr_stat_23 && lr_stat_23 > 0 && lr_stat_23 != std::numeric_limits< double >::infinity() ) {\n\t\t\t\tp_value_23 = cdf( complement( m_chi_squared_1df, lr_stat_23 ) ) ;\n\t\t\t\tcallback( \"male_female_lrt_pvalue\", p_value_23 ) ;\n\t\t\t} else {\n\t\t\t\tcallback( \"male_female_lrt_pvalue\", genfile::MissingValue() ) ;\n\t\t\t}\n\n\t\t\tdouble const lr_stat_13 = 2.0 * ( full_model.get_value_of_function() - model3.get_value_of_function() ) ;\n\t\t\tdouble p_value_13 = NaN ;\n\t\t\tif( lr_stat_13 == lr_stat_13 && lr_stat_13 > 0 && lr_stat_13 != std::numeric_limits< double >::infinity() ) {\n\t\t\t\tp_value_13 = cdf( complement( m_chi_squared_2df, lr_stat_13 ) ) ;\n\t\t\t\tcallback( \"male_female_and_HW_lrt_pvalue\", p_value_13 ) ;\n\t\t\t} else {\n\t\t\t\tcallback( \"male_female_and_HW_lrt_pvalue\", genfile::MissingValue() ) ;\n\t\t\t}\n\t\t}\n\t}\n}\n\n", "meta": {"hexsha": "8c5131f7fe2b910220d18ff0228a40825320e866", "size": 10797, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "components/SNPSummaryComponent/src/HWEComputation.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/HWEComputation.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/HWEComputation.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": 42.8452380952, "max_line_length": 153, "alphanum_fraction": 0.6720385292, "num_tokens": 3337, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961425, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.46002339382355173}}
{"text": "#include <frovedis.hpp>\n#include <frovedis/ml/clustering/kmeans.hpp>\n#include <boost/lexical_cast.hpp>\n\nint main(int argc, char* argv[]){\n  frovedis::use_frovedis use(argc, argv);\n\n  set_loglevel(DEBUG);\n  auto samples = frovedis::make_crs_matrix_load<double>(\"./train.mat\");\n  int num_iteration = 100;\n  double eps = 0.01;\n  int k = 3;\n  auto centroids = frovedis::kmeans(samples, k, num_iteration, eps);\n\n  centroids.transpose().save(\"./model\");\n\n  auto c = frovedis::make_rowmajor_matrix_local_load<double>(\"./model\");\n  auto ct = c.transpose();\n  auto mat = frovedis::make_crs_matrix_local_load<double>(\"./test.mat\");\n  auto r = kmeans_assign_cluster(mat, ct);\n  for(auto i: r) std::cout << i << std::endl;\n}\n", "meta": {"hexsha": "c3ab0ce9de7dc26c7f4e42cc6d6256782391f9ef", "size": 713, "ext": "cc", "lang": "C++", "max_stars_repo_path": "doc/tutorial/src/tut4.3-1/tut.cc", "max_stars_repo_name": "XpressAI/frovedis", "max_stars_repo_head_hexsha": "bda0f2c688fb832671c5b542dd8df1c9657642ff", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 63.0, "max_stars_repo_stars_event_min_datetime": "2018-06-21T14:11:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T11:24:36.000Z", "max_issues_repo_path": "doc/tutorial/src/tut4.3-1/tut.cc", "max_issues_repo_name": "XpressAI/frovedis", "max_issues_repo_head_hexsha": "bda0f2c688fb832671c5b542dd8df1c9657642ff", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2018-09-22T14:01:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-27T16:11:05.000Z", "max_forks_repo_path": "doc/tutorial/src/tut4.3-1/tut.cc", "max_forks_repo_name": "XpressAI/frovedis", "max_forks_repo_head_hexsha": "bda0f2c688fb832671c5b542dd8df1c9657642ff", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2018-08-23T15:59:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T06:47:22.000Z", "avg_line_length": 31.0, "max_line_length": 72, "alphanum_fraction": 0.698457223, "num_tokens": 205, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.46002338931258757}}
{"text": "#include \"relative_rme.h\"\n\n#include <Eigen/Dense>\n#include <cmath>\n#include <vector>\n\n#include \"basis_func/ho.h\"\n#include \"chime.h\"\n#include \"constants.h\"\n#include \"quadpp/quadpp.h\"\n#include \"quadpp/spline.h\"\n#include \"tprme.h\"\n\nnamespace chime {\nnamespace relative {\n\nconstexpr double mPi = constants::pion_mass_fm;\nconstexpr double mN = constants::nucleon_mass_fm;\nconstexpr double FPi = constants::pion_decay_constant_fm;\nconstexpr double gA = constants::gA;\n\n///////////////////////////////////////////////////////////////////////////\n//////////////// Magnetic moment (2n NLO) matrix element //////////////////\n///////////////////////////////////////////////////////////////////////////\n\nvoid ConstructMu2nNLOOperator(\n    const basis::RelativeOperatorParametersLSJT& op_params,\n    const basis::RelativeSpaceLSJT& rel_space,\n    std::array<basis::RelativeSectorsLSJT, 3>& rel_sectors,\n    std::array<basis::OperatorBlocks<double>, 3>& rel_matrices,\n    const double& oscillator_energy, const double& R)\n{\n  std::cout << \" Constructing M1 operator...\\n\";\n  assert(op_params.J0 == 1);\n  assert(op_params.g0 == 0);\n  assert((op_params.T0_min == 1) && (op_params.T0_max == 1));\n\n  // Alias isospin rank.\n  int T0 = op_params.T0_min;\n\n  // Generate required harmonic oscillator basis functions, and radial\n  // integral weights.\n  int Nmax = op_params.Nmax;\n\n  int npts = 3001;\n  const double low = 0, high = 1;\n  Eigen::ArrayXd x, r, jac, wt;\n  quadpp::SemiInfiniteIntegralMesh(npts, low, high, x, r, jac);\n  wt = r * r * jac;  // weights for radial integral with transformed variable\n\n  std::cout << \"  Generating basis functions...\\n\";\n  std::vector<Eigen::ArrayXXd> ho_wfs;\n  double brel = chime::RelativeOscillatorLength(oscillator_energy);\n  basis_func::ho::WaveFunctionsUptoMaxL(ho_wfs, r, Nmax, Nmax, brel,\n                                        basis_func::Space::coordinate);\n\n  // Radial integral kernels.\n  std::cout << \"  Generating integral kernels...\\n\";\n  Eigen::ArrayXd mpir = mPi * r;\n  Eigen::ArrayXd expmpir = Eigen::exp(-mpir);\n  Eigen::ArrayXd ypir = expmpir / mpir;\n  Eigen::ArrayXd zpir = (1. + mpir);\n  Eigen::ArrayXd tpir = (-1. + 2 * mpir);\n\n  // Semilocal coordinate space regulator.\n  Eigen::ArrayXd scs_reg =\n      r.unaryExpr([&R](double rs) { return chime::SCSRegulator(rs, R); });\n\n  // Zero initialize operator.\n  std::cout << \"  Zero initializing operator...\\n\";\n  basis::ConstructZeroOperatorRelativeLSJT(op_params, rel_space, rel_sectors,\n                                           rel_matrices);\n\n  // Select T0 component.\n  const basis::RelativeSectorsLSJT& sectors = rel_sectors[T0];\n  basis::OperatorBlocks<double>& matrices = rel_matrices[T0];\n\n  // Reduced matrix element calculation.\n  std::cout << \"  Starting matrix element calculation...\\n\";\n  for (std::size_t sector_index = 0; sector_index < sectors.size();\n       ++sector_index) {\n    const basis::RelativeSectorsLSJT::SectorType& sector =\n        sectors.GetSector(sector_index);\n    const basis::RelativeSubspaceLSJT& bra_subspace = sector.bra_subspace();\n    const basis::RelativeSubspaceLSJT& ket_subspace = sector.ket_subspace();\n\n    // Alias for matrix.\n    basis::OperatorBlock<double>& matrix = matrices[sector_index];\n\n    // Extract subspace labels.\n    int bra_L = bra_subspace.L();\n    int bra_S = bra_subspace.S();\n    int bra_J = bra_subspace.J();\n    int bra_T = bra_subspace.T();\n    int ket_L = ket_subspace.L();\n    int ket_S = ket_subspace.S();\n    int ket_J = ket_subspace.J();\n    int ket_T = ket_subspace.T();\n\n    if ((bra_T == ket_T) || (bra_S == ket_S)) {\n      continue;\n    }\n\n    // Loop over bra and ket states.\n    const std::size_t bra_subspace_size = bra_subspace.size();\n    const std::size_t ket_subspace_size = ket_subspace.size();\n#pragma omp parallel for collapse(2)\n    for (std::size_t bra_index = 0; bra_index < bra_subspace_size;\n         ++bra_index) {\n      for (std::size_t ket_index = 0; ket_index < ket_subspace_size;\n           ++ket_index) {\n        const basis::RelativeStateLSJT bra_state(bra_subspace, bra_index);\n        const basis::RelativeStateLSJT ket_state(ket_subspace, ket_index);\n\n        // Extract state labels.\n        int bra_n = bra_state.n();\n        int ket_n = ket_state.n();\n\n        // Common part of all radial integrals.\n        Eigen::ArrayXd common_integrand = wt * scs_reg;\n        common_integrand *=\n            (ho_wfs.at(bra_L).row(bra_n) * ho_wfs.at(ket_L).row(ket_n));\n\n        // Reduced matrix element calculation.\n        double rme = 0;\n\n        double tp_f =\n            tp::CSpinTensorProductRME(bra_subspace, ket_subspace, 2, 1, 1);\n        tp_f *= std::sqrt(10.);\n\n        Eigen::ArrayXd y = common_integrand * zpir * ypir;\n        y.head(1) = 0;  // Required to avoid divide by 0.\n        y.tail(1) = 0;  // Required to avoid divide by 0.\n        double integ_zpir_ypir = quadpp::spline::Integrate(x, y);\n\n        rme = tp_f * integ_zpir_ypir;\n\n        if (bra_L == ket_L) {\n          double tp_g =\n              tp::CSpinTensorProductRME(bra_subspace, ket_subspace, 0, 1, 1);\n\n          y = common_integrand * tpir * ypir;\n          y.head(1) = 0;  // Required to avoid divide by 0.\n          y.tail(1) = 0;  // Required to avoid divide by 0.\n          double integ_tpir_ypir = quadpp::spline::Integrate(x, y);\n\n          rme += tp_g * integ_tpir_ypir;\n        }\n\n        rme *= tp::SpinTensorProductRME(bra_T, ket_T, 1);  // Isospin.\n        rme *= -(mN * mPi * gA * gA) / (24 * constants::pi * FPi * FPi);\n\n        matrix(bra_n, ket_n) = rme;\n      }\n    }\n  }\n}\n\n}  // namespace relative\n}  // namespace chime\n", "meta": {"hexsha": "f8e23c9490f6984585720541d4ce31afeaded913", "size": 5607, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "programs/relative_rme.cpp", "max_stars_repo_name": "kc9jud/chime", "max_stars_repo_head_hexsha": "274f300d38f7806cef23c14f529784370cb0f91b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-09-18T20:31:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T14:47:07.000Z", "max_issues_repo_path": "programs/relative_rme.cpp", "max_issues_repo_name": "kc9jud/chime", "max_issues_repo_head_hexsha": "274f300d38f7806cef23c14f529784370cb0f91b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2019-04-08T22:42:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T15:10:53.000Z", "max_forks_repo_path": "programs/relative_rme.cpp", "max_forks_repo_name": "kc9jud/chime", "max_forks_repo_head_hexsha": "274f300d38f7806cef23c14f529784370cb0f91b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-03T17:25:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-03T17:25:01.000Z", "avg_line_length": 34.8260869565, "max_line_length": 77, "alphanum_fraction": 0.6258248618, "num_tokens": 1542, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637397236823, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.4600047162734187}}
{"text": "#include <vector>\n#include <iostream>\n#include <memory>\n#define _USE_MATH_DEFINES\n#include <math.h>\n#include \"Trajectory.hpp\"\n#include <Eigen/Dense>\n#define NOMINMAX\n#include <Windows.h>\n\nusing namespace dynaman;\n\nTrajectoryConstantState::TrajectoryConstantState(\n\tEigen::Vector3f const &positionTarget,\n\tEigen::Vector3f const &velocityTarget,\n\tEigen::Vector3f const &accelTarget)\n\t:\n\tposTgt(positionTarget),\n\tvelTgt(velocityTarget),\n\taccelTgt(accelTarget)\n{}\n\nEigen::Vector3f TrajectoryConstantState::pos(DWORD sys_time_ms) {\n\treturn posTgt;\n}\n\nEigen::Vector3f TrajectoryConstantState::vel(DWORD sys_time_ms) {\n\treturn velTgt;\n}\n\nEigen::Vector3f TrajectoryConstantState::accel(DWORD sys_time_ms) {\n\treturn accelTgt;\n}\n\nstd::shared_ptr<Trajectory> TrajectoryConstantState::Create(\n\tconst Eigen::Vector3f &positionTarget,\n\tconst Eigen::Vector3f &velocityTarget,\n\tconst Eigen::Vector3f &accelTarget\n) {\n\treturn std::make_shared<TrajectoryConstantState>(\n\t\tpositionTarget,\n\t\tvelocityTarget,\n\t\taccelTarget\n\t\t);\n}\n\nTrajectoryStep::TrajectoryStep(\n\tconst Eigen::Vector3f& posInit,\n\tconst Eigen::Vector3f& posEnd,\n\tDWORD switch_time_ms\n) :\n\tm_posInit(posInit),\n\tm_posEnd(posEnd),\n\tm_switch_time_ms(switch_time_ms)\n{}\n\nstd::shared_ptr<Trajectory> TrajectoryStep::Create(\n\tconst Eigen::Vector3f& posInit,\n\tconst Eigen::Vector3f& posEnd,\n\tDWORD switch_time_ms\n) {\n\treturn std::make_shared<TrajectoryStep>(posInit, posEnd, switch_time_ms);\n}\n\nEigen::Vector3f TrajectoryStep::pos(DWORD sys_time_ms) {\n\treturn sys_time_ms < m_switch_time_ms ? m_posInit : m_posEnd;\n}\n\nEigen::Vector3f TrajectoryStep::vel(DWORD sys_time_ms) {\n\treturn Eigen::Vector3f::Zero();\n}\n\nEigen::Vector3f TrajectoryStep::accel(DWORD sys_time_ms) {\n\treturn Eigen::Vector3f::Zero();\n}\n\nEigen::Vector3f TrajectoryBangBang::pos(DWORD sys_time_ms)\n{\n\tif (sys_time_ms < _sys_time_init)\n\t\treturn _posInit;\n\tif (sys_time_ms > _sys_time_init + _timeTotal * 1000)\n\t\treturn _posEnd;\n\tfloat dt = (sys_time_ms - _sys_time_init) / 1000.f;\n\treturn (2.0f * dt < _timeTotal) ? 0.5f * dt * dt * accel(sys_time_ms) + _posInit : 0.5f * (dt - _timeTotal) * (dt - _timeTotal) * accel(sys_time_ms) + _posEnd;\n}\n\nEigen::Vector3f TrajectoryBangBang::vel(DWORD sys_time_ms)\n{\n\tif (sys_time_ms < _sys_time_init || sys_time_ms > (_sys_time_init + _timeTotal*1000)) return Eigen::Vector3f::Zero();\n\tfloat dt = (sys_time_ms - _sys_time_init) / 1000.f;\n\treturn 2.0f * dt < _timeTotal ? accel(sys_time_ms) * dt : accel(sys_time_ms) * (dt - _timeTotal);\n}\n\nEigen::Vector3f TrajectoryBangBang::accel(DWORD sys_time_ms)\n{\n\tif (sys_time_ms < _sys_time_init || sys_time_ms > (_sys_time_init + _timeTotal * 1000)) return Eigen::Vector3f::Zero();\n\tfloat dt = (sys_time_ms - _sys_time_init) / 1000.f;\n\treturn \t2.0f * dt < _timeTotal ? 4.0f * (_posEnd - _posInit) / _timeTotal / _timeTotal : 4.0f * (_posInit - _posEnd) / _timeTotal / _timeTotal;\n}\n\nstd::shared_ptr<Trajectory> TrajectoryBangBang::Create(float timeTotal,\n\tDWORD sys_time_init,\n\tEigen::Vector3f const &posInit,\n\tEigen::Vector3f const &posEnd) {\n\treturn std::make_shared<TrajectoryBangBang>(\n\t\ttimeTotal,\n\t\tsys_time_init,\n\t\tposInit,\n\t\tposEnd\n\t\t);\n}\n\nTrajectoryCircle::TrajectoryCircle(\n\tconst Eigen::Vector3f& center,\n\tfloat radius,\n\tfloat inclination,\n\tfloat raan,\n\tfloat period_sec,\n\tfloat phaseInit,\n\tDWORD sys_time_init)\n\t:_center(center),\n\t_radius(radius),\n\t_inclination(inclination),\n\t_raan(raan),\n\t_omega(2 * M_PI / period_sec),\n\t_phaseInit(phaseInit),\n\t_sys_time_init(sys_time_init) {}\n\nstd::shared_ptr<Trajectory> TrajectoryCircle::Create(\n\tconst Eigen::Vector3f& center,\n\tfloat radius,\n\tfloat inclination,\n\tfloat raan,\n\tfloat period_sec,\n\tfloat phaseInit,\n\tDWORD sys_time_init) {\n\treturn std::make_shared<TrajectoryCircle>(center, radius, inclination, raan, period_sec, phaseInit, sys_time_init);\n}\n\nfloat TrajectoryCircle::Radius() {\n\treturn _radius;\n}\n\nfloat TrajectoryCircle::Phase(DWORD sys_time_ms) {\n\treturn _phaseInit + (sys_time_ms - _sys_time_init) / 1000.f * _omega;\n}\n\nEigen::Vector3f TrajectoryCircle::pos(DWORD sys_time_ms) {\n\treturn Eigen::AngleAxisf(_raan, Eigen::Vector3f::UnitZ())\n\t\t* Eigen::AngleAxisf(_inclination, Eigen::Vector3f::UnitX())\n\t\t* Eigen::AngleAxisf(Phase(sys_time_ms), Eigen::Vector3f::UnitZ())\n\t\t* (_radius * Eigen::Vector3f::UnitX())\n\t\t+ _center;\n}\n\nEigen::Vector3f TrajectoryCircle::vel(DWORD sys_time_ms) {\n\treturn Eigen::AngleAxisf(_raan, Eigen::Vector3f::UnitZ())\n\t\t* Eigen::AngleAxisf(_inclination, Eigen::Vector3f::UnitX())\n\t\t* Eigen::AngleAxisf(Phase(sys_time_ms), Eigen::Vector3f::UnitZ())\n\t\t* (_omega * _radius * Eigen::Vector3f::UnitY());\n}\n\nEigen::Vector3f TrajectoryCircle::accel(DWORD sys_time_ms) {\n\treturn Eigen::AngleAxisf(_raan, Eigen::Vector3f::UnitZ())\n\t\t* Eigen::AngleAxisf(_inclination, Eigen::Vector3f::UnitX())\n\t\t* Eigen::AngleAxisf(Phase(sys_time_ms), Eigen::Vector3f::UnitZ())\n\t\t* (- _omega * _omega * _radius * Eigen::Vector3f::UnitX());\n}\n\nTrajectorySinusoid::TrajectorySinusoid(\n\tconst Eigen::Vector3f& direction,\n\tfloat amplitude,\n\tfloat period,\n\tconst Eigen::Vector3f& center,\n\tDWORD sys_time_init)\n\t:_direction(direction),\n\t_amplitude(amplitude),\n\t_period(period),\n\t_center(center),\n\t_sys_time_init(sys_time_init) {}\n\nstd::shared_ptr<Trajectory> TrajectorySinusoid::Create(\n\tconst Eigen::Vector3f& direction,\n\tfloat amplitude,\n\tfloat period,\n\tconst Eigen::Vector3f& center,\n\tDWORD sys_time_init\n) {\n\treturn std::make_shared<TrajectorySinusoid>(direction, amplitude, period, center, sys_time_init);\n}\n\nEigen::Vector3f TrajectorySinusoid::pos(DWORD sys_time) {\n\treturn _center + _direction * _amplitude * sinf((Phase(sys_time)));\n}\n\nEigen::Vector3f TrajectorySinusoid::vel(DWORD sys_time) {\n\treturn (sys_time < _sys_time_init) ? Eigen::Vector3f(0, 0, 0) : _direction * _amplitude * Omega(sys_time) * cosf(Phase(sys_time));\n}\n\nEigen::Vector3f TrajectorySinusoid::accel(DWORD sys_time) {\n\treturn -_direction * _amplitude * Omega(sys_time) * Omega(sys_time) * sinf(Phase(sys_time));\n}\n\nfloat TrajectorySinusoid::Phase(DWORD sys_time) {\n\treturn (sys_time < _sys_time_init) ? 0.f : fmodf((sys_time - _sys_time_init)/1000.f, _period) / _period * M_PI * 2.0f;\n}\n\nfloat TrajectorySinusoid::Omega(DWORD sys_time) {\n\treturn 2.0f * M_PI / _period;\n}\n\nTrajectoryInfShape::TrajectoryInfShape(\n\tconst Eigen::Vector3f& center,\n\tfloat height,\n\tfloat width,\n\tfloat period_sec,\n\tDWORD sys_time_init)\n\t:_center(center),\n\t_omega(4.0f * M_PI / period_sec),\n\t_height(height),\n\t_width(width),\n\t_sys_time_init(sys_time_init) {\n}\n\nstd::shared_ptr<Trajectory> TrajectoryInfShape::Create(\n\tconst Eigen::Vector3f& center,\n\tfloat period_sec,\n\tfloat height,\n\tfloat width,\n\tDWORD sys_time_init) {\n\treturn std::make_shared<TrajectoryInfShape>(\n\t\tcenter,\n\t\tperiod_sec,\n\t\theight,\n\t\twidth,\n\t\tsys_time_init);\n}\n\nfloat TrajectoryInfShape::Phase(DWORD sys_time_ms) {\n\treturn (sys_time_ms - _sys_time_init) / 1000.f * _omega;\n}\n\nEigen::Vector3f TrajectoryInfShape::pos(DWORD sys_time_ms) {\n\tif (fmodf(Phase(sys_time_ms), 4.f * M_PI) < 2.f * M_PI) {\n\t\treturn Eigen::Vector3f(\n\t\t\t0.25f * _width * (1 - cosf(Phase(sys_time_ms))),\n\t\t\t0.f,\n\t\t\t0.5f * _height * sinf(Phase(sys_time_ms))\n\t\t) + _center;\n\t}\n\telse {\n\t\treturn Eigen::Vector3f(\n\t\t\t0.25f * _width * (-1 + cosf(Phase(sys_time_ms))),\n\t\t\t0.f,\n\t\t\t0.5f * _height * sinf(Phase(sys_time_ms))\n\t\t) + _center;\n\t}\n}\n\nEigen::Vector3f TrajectoryInfShape::vel(DWORD sys_time_ms) {\n\tif (fmodf(Phase(sys_time_ms), 4.f * M_PI) < 2.f * M_PI) {\n\t\treturn _omega * Eigen::Vector3f(\n\t\t\t0.25f * _width * (sinf(Phase(sys_time_ms))),\n\t\t\t0.f,\n\t\t\t0.5f * _height * cosf(Phase(sys_time_ms))\n\t\t);\n\t}\n\telse {\n\t\treturn _omega * Eigen::Vector3f(\n\t\t\t-0.25f * _width * (sinf(Phase(sys_time_ms))),\n\t\t\t0.f,\n\t\t\t0.5f * _height * cosf(Phase(sys_time_ms))\n\t\t);\n\t}\n}\n\nEigen::Vector3f TrajectoryInfShape::accel(DWORD sys_time_ms) {\n\tif (fmodf(Phase(sys_time_ms), 4.f * M_PI) < 2.f * M_PI) {\n\t\treturn _omega * _omega * Eigen::Vector3f(\n\t\t\t0.25f * _width * (cosf(Phase(sys_time_ms))),\n\t\t\t0.f,\n\t\t\t-0.5f * _height * sinf(Phase(sys_time_ms))\n\t\t);\n\t}\n\telse {\n\t\treturn _omega * _omega * Eigen::Vector3f(\n\t\t\t-0.25f * _width * (cosf(Phase(sys_time_ms))),\n\t\t\t0.f,\n\t\t\t-0.5f * _height * sinf(Phase(sys_time_ms))\n\t\t);\n\t}\n}\n\nTrajectoryHeart::TrajectoryHeart(\n\tconst Eigen::Vector3f& center,\n\tfloat height,\n\tfloat width,\n\tfloat period_sec,\n\tDWORD sys_time_init)\n\t:_center(center),\n\t_height(height),\n\t_width(width),\n\t_omega(2.f * M_PI / period_sec),\n\t_sys_time_init(sys_time_init) {}\n\nstd::shared_ptr<Trajectory> TrajectoryHeart::Create(\n\tconst Eigen::Vector3f& center,\n\tfloat height,\n\tfloat width,\n\tfloat period_sec,\n\tDWORD sys_time_init)\n{\n\treturn std::make_shared<TrajectoryHeart>(center, height, width, period_sec, sys_time_init);\n}\n\nfloat TrajectoryHeart::Phase(DWORD sys_time_ms) {\n\treturn _omega * (sys_time_ms - _sys_time_init) / 1000.f;\n}\n\nEigen::Vector3f TrajectoryHeart::pos(DWORD sys_time_ms) {\n\treturn Eigen::Vector3f(\n\t\t0.5f * _width * sinf(Phase(sys_time_ms)) * sinf(Phase(sys_time_ms)) * sinf(Phase(sys_time_ms)),\n\t\t0.f,\n\t\t0.5f * _height\n\t\t* (2.6f * cosf(Phase(sys_time_ms))\n\t\t\t- cosf(2.f * Phase(sys_time_ms))\n\t\t\t- 0.4f * cosf(3.f * Phase(sys_time_ms))\n\t\t\t- 0.2f * cosf(4.f * Phase(sys_time_ms))\n\t\t\t+ 0.508f)\n\t) + _center;\n}\n\nEigen::Vector3f TrajectoryHeart::vel(DWORD sys_time_ms) {\n\treturn _omega * Eigen::Vector3f(\n\t\t1.5f * _width * sinf(Phase(sys_time_ms)) * sinf(Phase(sys_time_ms)) * cosf(Phase(sys_time_ms)),\n\t\t0.f,\n\t\t0.5f * _height * (\n\t\t\t- 2.6f * sinf(Phase(sys_time_ms))\n\t\t\t+ 2.f * sinf(2.f * Phase(sys_time_ms))\n\t\t\t+ 1.2f * sinf(3.f * Phase(sys_time_ms))\n\t\t\t+ 0.8f * sinf(4.f * Phase(sys_time_ms))\n\t\t\t)\n\t);\n}\n\nEigen::Vector3f TrajectoryHeart::accel(DWORD sys_time_ms) {\n\treturn _omega * _omega * Eigen::Vector3f(\n\t\t1.5f * _width * (\n\t\t\t2.f * sinf(Phase(sys_time_ms)) * cosf(Phase(sys_time_ms)) * cosf(Phase(sys_time_ms))\n\t\t\t- sinf(Phase(sys_time_ms)) * sinf(Phase(sys_time_ms)) * sinf(Phase(sys_time_ms))\n\t\t\t),\n\t\t0.f,\n\t\t0.5f * _height * (\n\t\t\t-2.6f * cosf(Phase(sys_time_ms))\n\t\t\t+ 4.f * cosf(2.f * Phase(sys_time_ms))\n\t\t\t+ 3.6f * cosf(3.f * Phase(sys_time_ms))\n\t\t\t+ 3.2f * cosf(4.f * Phase(sys_time_ms))\n\t\t\t)\n\t);\n}\n\nstd::shared_ptr<Trajectory> TrajectoryBangbangWithDrag::Create(\n\tfloat force,\n\tfloat radius,\n\tDWORD sys_time_init,\n\tconst Eigen::Vector3f& posInit,\n\tconst Eigen::Vector3f& posEnd\n) {\n\treturn std::make_shared<TrajectoryBangbangWithDrag>(force, radius, sys_time_init, posInit, posEnd);\n}\n\nfloat TrajectoryBangbangWithDrag::terminal_velocity() {\n\treturn 36914.f * std::sqrt(_force) / _radius;\n}\n\nfloat TrajectoryBangbangWithDrag::mu() {\n\treturn 0.15f / _radius;\n}\n\nfloat TrajectoryBangbangWithDrag::beta() {\n\tfloat dist = (_posEnd - _posInit).norm();\n\treturn std::sqrtf((std::expf(2 * mu() * dist) - 1 )/(std::expf(2 * mu() * dist) + 1));\n}\n\nfloat TrajectoryBangbangWithDrag::time_to_accel() {\n\treturn std::logf((1 + beta()) / (1 - beta())) / 2.0f / mu() / terminal_velocity();\n}\n\nfloat TrajectoryBangbangWithDrag::time_to_decel() {\n\treturn std::atan(beta()) / mu() / terminal_velocity();\n}\n\nfloat TrajectoryBangbangWithDrag::dist_to_accel() {\n\tauto dist = (_posEnd - _posInit).norm();\n\treturn 0.5f / mu() * std::logf(0.5f * (std::expf(2.f * mu() * dist) + 1.f));\n}\n\nEigen::Vector3f TrajectoryBangbangWithDrag::pos(DWORD time_ms) {\n\tauto vt = terminal_velocity();\n\tif (time_ms < _sys_time_init) {\n\t\treturn _posInit;\n\t}\n\tfloat dt = (time_ms - _sys_time_init) / 1000.f;\n\tfloat dist = 0;\n\tif (dt < time_to_accel()) {\n\t\tdist = -vt * dt + 1.0f / mu() * std::logf((std::expf(2.f * mu() * vt * dt) + 1) / 2.0f);\n\t}\n\telse if (dt <= time_to_accel() + time_to_decel()) {\n\t\tfloat time_to_go = time_to_accel() + time_to_decel() - dt;\n\t\tdist = (_posEnd - _posInit).norm() + std::logf(std::abs(std::cosf(mu() * vt * time_to_go))) / mu();\n\t}\n\telse {\n\t\tdist = (_posEnd - _posInit).norm();\n\t}\n\treturn dist * (_posEnd - _posInit).normalized() + _posInit;\n}\n\nEigen::Vector3f TrajectoryBangbangWithDrag::vel(DWORD time_ms) {\n\tif (time_ms < _sys_time_init) {\n\t\treturn Eigen::Vector3f::Zero();\n\t}\n\tfloat dt = (time_ms - _sys_time_init) / 1000.f;\n\tfloat speed = 0;\n\tif (dt < time_to_accel()) {\n\t\tspeed = terminal_velocity() * (1 - 2.f / (expf(2 * mu() * terminal_velocity() * dt) + 1.f));\n\t}\n\telse if (dt < time_to_accel() + time_to_decel()) {\n\t\tauto time_to_go = time_to_accel() + time_to_decel() - dt;\n\t\tspeed = terminal_velocity() * std::tanf(mu() * terminal_velocity() * time_to_go);\n\t}\n\treturn speed * (_posEnd - _posInit).normalized();\n}\n\nEigen::Vector3f TrajectoryBangbangWithDrag::accel(DWORD time_ms) {\n\tauto dt = (time_ms - _sys_time_init) / 1000.f;\n\tif (dt >= time_to_accel() + time_to_decel()) {\n\t\treturn Eigen::Vector3f::Zero();\n\t}\n\tauto mass = static_cast<float>(1.168e-9f * 4.0f * float(M_PI) * _radius * _radius * _radius / 3.0f);\n\tauto a = _force / mass;\n\tif (dt > time_to_accel()) {\n\t\ta *= -1;\n\t}\n\treturn a * (_posEnd - _posInit).normalized();\n}", "meta": {"hexsha": "581be4a8b99753bb9769b1c162605e113996e4f3", "size": 12792, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/Trajectory.cpp", "max_stars_repo_name": "shinolab/dynamic-manipulation", "max_stars_repo_head_hexsha": "d43bae688cecf87e15605ed6a9dbc80a782d72fc", "max_stars_repo_licenses": ["MIT"], "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/Trajectory.cpp", "max_issues_repo_name": "shinolab/dynamic-manipulation", "max_issues_repo_head_hexsha": "d43bae688cecf87e15605ed6a9dbc80a782d72fc", "max_issues_repo_licenses": ["MIT"], "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/Trajectory.cpp", "max_forks_repo_name": "shinolab/dynamic-manipulation", "max_forks_repo_head_hexsha": "d43bae688cecf87e15605ed6a9dbc80a782d72fc", "max_forks_repo_licenses": ["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.7460674157, "max_line_length": 160, "alphanum_fraction": 0.7084115072, "num_tokens": 4080, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.766293653760418, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.45992053076197287}}
{"text": "\n#include <iostream>\n\n#include <ignition/math/eigen3/Conversions.hh>\n#include <Eigen/Geometry>\n\nint main()\n{\n  Eigen::Vector3d vecE = Eigen::Vector3d(1.0, 2.0, 3.0);\n  ignition::math::Vector3d vecI = ignition::math::eigen3::convert(vecE);\n\n  std::cout << vecI << std::endl;\n}\n", "meta": {"hexsha": "3d95f15f805edb1dce2ec1c6f4006dce0703cc00", "size": 276, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ign-common/dummy.cpp", "max_stars_repo_name": "mxgrey/sandbox", "max_stars_repo_head_hexsha": "6f3c316702a47053499222dbf293efe6c1f43f0c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ign-common/dummy.cpp", "max_issues_repo_name": "mxgrey/sandbox", "max_issues_repo_head_hexsha": "6f3c316702a47053499222dbf293efe6c1f43f0c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ign-common/dummy.cpp", "max_forks_repo_name": "mxgrey/sandbox", "max_forks_repo_head_hexsha": "6f3c316702a47053499222dbf293efe6c1f43f0c", "max_forks_repo_licenses": ["BSD-3-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.7142857143, "max_line_length": 72, "alphanum_fraction": 0.6775362319, "num_tokens": 93, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.766293653760418, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.45992053076197287}}
{"text": "#include \"util.hpp\"\n\n#include <Eigen/Geometry>\n#include <vector>\n#include <map>\n#include <fstream>\n\n#include <float.h>\n\n\n#include <cvx/util/math/rng.hpp>\n#include <cvx/util/geometry/kdtree.hpp>\n\nusing namespace Eigen ;\nusing namespace std ;\nusing namespace cvx::util ;\n\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nstatic uint closest_center(const Vector3f &p, const vector<Vector3f> &c, float &closest_dist)\n{\n    float min_dist = FLT_MAX ;\n    uint best_idx ;\n\n    for(uint i=0 ; i<c.size() ; i++ )\n    {\n        float dist = (c[i] - p).norm() ;\n        if ( dist < min_dist ) {\n            min_dist = dist ;\n            best_idx = i ;\n        }\n    }\n\n    closest_dist = min_dist ;\n\n    return best_idx ;\n\n}\n\nstatic void pruneModes(vector<Vector3f> &centers, vector<float> &cweights, float threshold, vector<uint> &cassign )\n{\n    uint n = centers.size() ;\n\n    if ( n == 0 ) return ;\n\n    vector<Vector3f> prunned ;\n    vector<uint> idxs ;\n    vector<float> cwassign ;\n\n    idxs.resize(n) ;\n\n    prunned.push_back(centers[0]) ;\n    cassign.push_back(1) ;\n    cwassign.push_back(cweights[0]) ;\n    idxs[0] = 0 ;\n\n    for( uint j=1 ; j<n ; j++ )\n    {\n        float closest_dist ;\n        uint closest = closest_center(centers[j], prunned, closest_dist) ;\n\n        if ( closest_dist < threshold )\n        {\n            assert(closest < cwassign.size()) ;\n\n            cassign[closest] ++ ;\n            cwassign[closest] += cweights[j] ;\n            idxs[j] = closest ;\n        }\n        else {\n            prunned.push_back(centers[j]) ;\n            cassign.push_back(1) ;\n            cwassign.push_back(cweights[j]) ;\n            idxs[j] = cassign.size() - 1 ;\n        }\n    }\n\n    centers = prunned ;\n    cweights = cwassign ;\n}\n\nstruct WeightSorter\n{\n    WeightSorter(const vector<float> &weights): weights_(weights) {}\n\n    bool operator () (const int a, const int b) { return weights_[a] >= weights_[b] ; }\n    const vector<float> weights_ ;\n};\n\n\n\nvoid mean_shift(RNG &g, const std::vector<Vector3f> &pts, Vector3f &mode,  float &weight, float sigma,\n                    unsigned int maxIter, float seed_perc, uint min_seeds)\n{\n    uint n = pts.size() ;\n\n    uint n_seed = std::max((uint)(n * seed_perc), std::min(n, min_seeds)) ;\n\n    vector<uint> seed_idx ;\n\n    for( uint i=0 ; i<n ; i++ )\n        seed_idx.push_back(i) ;\n\n    g.shuffle(seed_idx) ;\n\n    Vector3f best_center ;\n    float max_weight = -FLT_MAX ;\n\n    for(uint r=0 ; r<n_seed ; r++)\n    {\n        const Vector3f &seed = pts[seed_idx[r]] ;\n\n        Vector3f center = seed ;\n        double center_dist ;\n        uint iter = 0 ;\n        float weight ;\n\n        // shift center until convergence\n\n        do {\n\n            Vector3f new_center(0, 0, 0) ;\n            double denom = 0.0 ;\n\n            for(uint i=0 ; i<n ; i++ )\n            {\n                float sqd = (center - pts[i]).squaredNorm() ;\n                double ep = exp(-sqd/ (2.0 * sigma * sigma));\n\n                denom += ep ;\n\n                new_center += ep * pts[i] ;\n            }\n\n            new_center /= denom ;\n\n            center_dist = (new_center - center).norm() ;\n\n            ++iter ;\n\n            center = new_center ;\n\n            weight = denom ;\n\n        } while ( center_dist > 1.0e-7  && iter < maxIter ) ;\n\n        if ( weight > max_weight ) {\n            max_weight = weight ;\n            best_center = center ;\n        }\n    }\n\n    mode = best_center ;\n    weight = max_weight ;\n}\n\n/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n\n// rigid pose estimation\n\nIsometry3f find_rigid(const Matrix3Xf &P, const Matrix3Xf &Q) {\n\n    // Default output\n    Isometry3f A;\n    A.linear() = Matrix3f::Identity(3, 3);\n    A.translation() = Vector3f::Zero();\n\n    if (P.cols() != Q.cols())\n        throw \"Find3DAffineTransform(): input data mis-match\";\n\n    // Center the data\n    Vector3f p = P.rowwise().mean();\n    Vector3f q = Q.rowwise().mean();\n\n    Matrix3Xf X = P.colwise() - p;\n    Matrix3Xf Y = Q.colwise() - q;\n\n    // SVD\n    MatrixXf Cov = X*Y.transpose();\n    JacobiSVD<MatrixXf> svd(Cov, ComputeThinU | ComputeThinV);\n\n    // Find the rotation, and prevent reflections\n    Matrix3f I = Matrix3f::Identity(3, 3);\n    double d = (svd.matrixV()*svd.matrixU().transpose()).determinant();\n    (d > 0.0) ? d = 1.0 : d = -1.0;\n    I(2, 2) = d;\n\n    Matrix3f R = svd.matrixV()*I*svd.matrixU().transpose();\n\n    // The final transform\n    A.linear() = R;\n    A.translation() = q - R*p;\n\n    return A;\n}\n\nIsometry3f find_rigid(const vector<Vector3f> &src, const vector<Vector3f> &dst) {\n\n    assert( src.size() == dst.size() ) ;\n\n    Eigen::Map<Matrix3Xf> m_src((float *)src.data(), 3, src.size())  ;\n    Eigen::Map<Matrix3Xf> m_dst((float *)dst.data(), 3, dst.size())  ;\n\n    return find_rigid(m_src, m_dst) ;\n}\n\n//////////////////////////////////////////////////////////////\n\n\nVector3f back_project(const cv::Mat &depth, const PinholeCamera &cam, const cv::Point &pt) {\n    float z = depth.at<ushort>(pt)/1000.0 ;\n    return cam.backProject(pt.x, pt.y, z) ;\n}\n\n\nvoid save_cloud_obj(const string &file_name, const std::vector<Vector3f> &cloud)\n{\n    ofstream strm(file_name.c_str()) ;\n\n    for( uint i=0 ; i<cloud.size() ; i++ )\n        strm << \"v \" << cloud[i].adjoint() << endl ;\n}\n", "meta": {"hexsha": "7bb2392444bb483382cddfa3319ebb80185e6d33", "size": 5382, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/util.cpp", "max_stars_repo_name": "malasiot/crf", "max_stars_repo_head_hexsha": "1bd7c3f8c06604e13fb30c5873132619228713e4", "max_stars_repo_licenses": ["MIT"], "max_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.cpp", "max_issues_repo_name": "malasiot/crf", "max_issues_repo_head_hexsha": "1bd7c3f8c06604e13fb30c5873132619228713e4", "max_issues_repo_licenses": ["MIT"], "max_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.cpp", "max_forks_repo_name": "malasiot/crf", "max_forks_repo_head_hexsha": "1bd7c3f8c06604e13fb30c5873132619228713e4", "max_forks_repo_licenses": ["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.0267857143, "max_line_length": 117, "alphanum_fraction": 0.5297287254, "num_tokens": 1439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4599205243552873}}
{"text": "#pragma once\n\n#include <Eigen/Geometry>\n\nnamespace iNav {\n\nclass IMUData {\npublic:\n  double timestamp;\n  Eigen::Vector3d gyro;\n  Eigen::Vector3d acc;\n};\n\nclass IMUParam {\npublic:\n  double ARW;\n  double VRW;\n  double gyro_bias_std;\n  double T_gyro_bias;\n  double acc_bias_std;\n  double T_acc_bias;\n  double gyro_scalar_std;\n  double T_gyro_scalar;\n  double acc_scalar_std;\n  double T_acc_scalar;\n};\n\nclass GnssData {\npublic:\n  double timestamp;\n  Eigen::Vector3d pos;\n  Eigen::Vector3d pos_std;\n};\n\nclass NavData {\npublic:\n  double timestamp;\n  Eigen::Vector3d pos;\n  Eigen::Vector3d pos_std;\n  Eigen::Vector3d vel;\n  Eigen::Vector3d vel_std;\n  Eigen::Vector3d att;\n  Eigen::Vector3d att_std;\n};\n\n}  // namespace iNav\n", "meta": {"hexsha": "a2730c0204587df3f27b7b7169de2735c72e2e0e", "size": 717, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/DataStorage.hpp", "max_stars_repo_name": "LauZanMo/INS", "max_stars_repo_head_hexsha": "13bd9427c98ba551318f76c94dc793273d2dd070", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-13T02:29:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-13T02:29:54.000Z", "max_issues_repo_path": "include/DataStorage.hpp", "max_issues_repo_name": "LauZanMo/INS", "max_issues_repo_head_hexsha": "13bd9427c98ba551318f76c94dc793273d2dd070", "max_issues_repo_licenses": ["MIT"], "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/DataStorage.hpp", "max_forks_repo_name": "LauZanMo/INS", "max_forks_repo_head_hexsha": "13bd9427c98ba551318f76c94dc793273d2dd070", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-28T01:05:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T01:05:16.000Z", "avg_line_length": 15.2553191489, "max_line_length": 26, "alphanum_fraction": 0.7224546722, "num_tokens": 207, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115012, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4599205179486015}}
{"text": "/* \n* This file is part of Fieldosophy, a toolkit for random fields.\n*\n* Copyright (C) 2021 Anders Gunnar Felix Hildeman <fieldosophySPDEC@gmail.com>\n*\n* This Source Code is subject to the terms of the BSD 3-Clause License.\n* If a copy of the license was not distributed with this file, you can obtain one at https://opensource.org/licenses/BSD-3-Clause.\n*\n*/\n\n\n#ifndef MESH_HXX\n#define MESH_HXX\n\n#include <Eigen/Dense>\n\n#include <set>\n#include <vector>\n#include <list>\n\n\n// Forward declaration\nclass MeshGraph;\n\n// Class representing a mesh initiated from pointers to triangles and nodes\nclass ConstMesh\n{\n    public:\n\n        ConstMesh( const double * const pNodes, const unsigned int pD, const unsigned int pNumNodes, \n            const unsigned int * const pSimplices, const unsigned int pNumSimplices, const unsigned int pTopD, \n            const unsigned int * const pNeighs = NULL ) : \n            mNodes(pNodes), mD(pD), mNumNodes(pNumNodes), mSimplices(pSimplices), mNumSimplices(pNumSimplices), mTopD(pTopD), mNeighs(pNeighs) {}\n            \n        ConstMesh( const ConstMesh & pMesh ) \n        {\n            mNodes = pMesh.getNodes();\n            mD = pMesh.getD();\n            mNumNodes = pMesh.getNN();\n            mSimplices = pMesh.getSimplices();\n            mNumSimplices = pMesh.getNT();\n            mTopD = pMesh.getTopD();\n            mNeighs = pMesh.mNeighs;\n        }\n        \n        ConstMesh & operator=(const ConstMesh & pMesh)\n        {\n            if (&pMesh != this)\n                *this = ConstMesh(pMesh);\n            \n            return *this;\n        }\n        \n            \n        ~ConstMesh();\n            \n        // Get variables\n        inline const double * getNodes() const {return mNodes;}\n        inline const unsigned int * getSimplices() const {return mSimplices;}\n        inline const unsigned int * getNeighs() const {return mNeighs;}\n        inline const unsigned int getNN() const {return mNumNodes;}\n        inline const unsigned int getNT() const {return mNumSimplices;}\n        inline const unsigned int getD() const {return mD;}\n        inline const unsigned int getTopD() const {return mTopD;}\n        inline const bool hasNeighs() const {return (mNeighs != NULL);}\n        \n        \n        // Get diameter of simplex\n        double getDiameter( const unsigned int pSimplexInd ) const;\n        // Get a simplex index for a simplex where points are part\n        int getASimplexForPoint( const double * const pPoints, const unsigned int pNumPoints, \n            unsigned int * const pSimplexIds, double * const pBarycentricCoords, \n            const double pEmbTol, const double * const pCenterOfCurvature, const unsigned int pNumCentersOfCurvature) const;\n        // Get a set of all simplices for which the given point is a member.\n        int getAllSimplicesForPoint( const double * const pPoint, unsigned int pSimplexId, \n            std::set<unsigned int> & pOutput,\n            const double pEmbTol, const double * const pCenterOfCurvature ) const;\n        // Get a simplex index for a simplex where node is a part\n        int getASimplexForNode( const unsigned int * const pNodes, const unsigned int pNumNodes, unsigned int * const pSimplexIds) const;\n        // Get a simplex index for a simplex where set is a part\n        int getASimplexForSet( const std::set<unsigned int> & pSet, unsigned int & pSimplexId) const;\n        // Get a set of all simplices for which the given node is a member.\n        int getAllSimplicesForNode( const unsigned int pNode, unsigned int pSimplexId,\n            std::set<unsigned int> & pOutput ) const\n        {\n            std::set<unsigned int> lSet;\n            lSet.insert(pNode);\n            return getAllSimplicesForSet( lSet, pSimplexId, pOutput );\n        }\n        // Get a set of all simplices for which the given set is a member.\n        int getAllSimplicesForSet( const std::set<unsigned int> & pSet, unsigned int pSimplexId,\n            std::set<unsigned int> & pOutput ) const;\n        // Get coefficients of gradient of linear function on face\n        int getGradientChainCoefficientsOfSimplex( double * const pGradientCoefficients, const unsigned int pNumRows, const unsigned int pNumCols, \n            const unsigned int pSimplexInd, double * const pArea = NULL ) const;\n        \n        // Get standard- and/or barycentric coordinates for points given simplex\n        int getCoordinatesGivenSimplex( const double * const pPoints, const unsigned int pNumPoints, const unsigned int pSimplexId,\n            double * const pStandardCoords, double * const pBarycentricCoords, \n            const double pEmbTol, const double * const pCenterOfCurvature, const unsigned int pNumCentersOfCurvature, double * const pBaryOutsidedness) const;\n        // Get a set of all node indices part of a collection of simplices\n        std::set<unsigned int> getUniqueNodesOfSimplexCollection( const unsigned int * const pSimplices, const unsigned int pNumSimplices ) const;\n        // Populate arrays with corresponding mesh\n        int populateArrays( double * const pNodes, const unsigned int pD, const unsigned int pNumNodes, \n            unsigned int * const pSimplices, const unsigned int pNumSimplices, const unsigned int pTopD,\n            unsigned int * const pNeighs = NULL ) const;\n        // Computes a mesh graph of mesh\n        int computeMeshGraph( const unsigned int pMaxNumNodes, const double pMinDiam, const unsigned int pMinNumTriangles,\n            const double * const pPoints = NULL, const unsigned int * const pNumPoints = NULL );\n        // See if two simplices are neighbors\n        bool areSimplicesNeighbors( const unsigned int pSimpInd1, const unsigned int pSimpInd2 ) const;\n        // See if node is part of simplex\n        inline bool isNodePartOfSimplex( const unsigned int pNode, const unsigned int pSimplex ) const\n        {\n            if (pSimplex > getNT())\n                return false;\n            for (unsigned int lIter = 0; lIter < (getTopD()+1); lIter++ )\n            {\n                if ( pNode == getSimplices()[pSimplex * (getTopD()+1) + lIter] )\n                    return true;\n            }\n            return false;\n        }\n        \n        // See if node is part of simplex\n        inline bool isSetPartOfSimplex( const std::set<unsigned int> & pSet, const unsigned int pSimplex ) const\n        {\n            if (pSimplex > getNT())\n                return false;                \n            unsigned int lNumMatches = 0;\n            // Loop through simplex\n            for (unsigned int lIter = 0; lIter < (getTopD()+1); lIter++ )\n            {\n                const unsigned int lCurNode = getSimplices()[pSimplex * (getTopD()+1) + lIter];\n                if ( pSet.count(lCurNode) > 0 )\n                    ++lNumMatches;\n            }\n            if (lNumMatches == pSet.size() )\n                return true;\n            \n            return false;\n        }\n        \n        \n    \n        \n        \n    protected:\n    \n        const double * mNodes;    \n        unsigned int mD;\n        unsigned int mNumNodes;\n        \n        const unsigned int * mSimplices;\n        unsigned int mNumSimplices;\n        unsigned int mTopD;\n        \n        const unsigned int * mNeighs;\n        \n        // Pointer to storage of mesh graph for node\n        MeshGraph * mMeshGraph = NULL;\n        // Compute the standard simplex coordinates of chosen point\n        Eigen::VectorXd getSimplexStandardCoords( const double * const pPoint, const unsigned int pSimplexId, std::vector< double > & pCurNodeCoords,\n            double * const pDivergence = NULL, const double * const pCenterOfCurvature = NULL ) const;\n\n};\n\n// Class representing a full mesh (saving nodes and triangles inside)\nclass FullMesh : public ConstMesh\n{\n    public:\n\n        FullMesh( const double * const pNodes, const unsigned int pD, const unsigned int pNumNodes, \n                const unsigned int * const pSimplices, const unsigned int pNumSimplices, const unsigned int pTopD,\n                const unsigned int * const pNeighs = NULL );\n        \n        // Method refining all simplices accordingly\n        int refine( const unsigned int pMaxNumNodes, std::vector<double> & pMaxDiam, const unsigned int * const pNumLevels, int (* transformationPtr)(double *, unsigned int) );\n        // Method refining a simplex\n        int refineSimplex( const unsigned int pChosenSimplex, const double pMaxDiam, const unsigned int pMaxNewSimplices = 1);\n        // Overloaded member function for populating arrays from mesh\n        int populateArrays( double * const pNodes, const unsigned int pD, const unsigned int pNumNodes, \n            unsigned int * const pSimplices, const unsigned int pNumSimplices, const unsigned int pTopD,\n            unsigned int * const pNeighs = NULL );    \n\n    private:\n    \n        // Function for updating ConstMesh pointers when FullMesh is changing\n        inline void updateConstMeshPointers()\n        {\n            // Set pointers to data\n            mNodes = (mFullNodes.size() == 0) ? NULL : mFullNodes.data();\n            mSimplices = (mFullSimplices.size() == 0) ? NULL : mFullSimplices.data();\n            mNeighs = (mFullNeighs.size() == 0) ? NULL : mFullNeighs.data();\n            return;\n        }\n    \n        // Stores simplices\n        std::vector< unsigned int > mFullSimplices;\n        // Store nodes\n        std::vector< double > mFullNodes;\n        // Store neigbors\n        std::vector< unsigned int > mFullNeighs;\n\n};\n\n\n\n\n\n\n// Functor for comparison of sets of node indices to give a weak ordering\nclass CompareNodeSets\n{\n    public:\n        CompareNodeSets( const unsigned int pD = 0 ) : mD(pD) {}\n        \n        bool operator() ( const std::set<unsigned int> pLhs, const std::set<unsigned int> pRhs )\n        {\n            // Initialize comparison as less than\n            bool lLhsLessThanRhs = false;\n            // Loop through set\n            std::set<unsigned int>::const_iterator lIterRhs = pRhs.begin();\n            for ( std::set<unsigned int>::const_iterator lIterLhs = pLhs.begin(); lIterLhs !=  pLhs.end();  )\n            {\n                // If current \n                if ( *lIterLhs < *lIterRhs )\n                {\n                    // Set that Lhs is smaller than Rhs\n                    lLhsLessThanRhs = true;\n                    // Stop looping\n                    break;\n                }\n                else \n                    if ( *lIterLhs > *lIterRhs )\n                        // Stop looping since rhs is apparently smaller\n                        break;\n                \n                // Advance iterators\n                ++lIterLhs;\n                ++lIterRhs;\n            }\n            // Return result\n            return lLhsLessThanRhs;\n        }\n        bool operator() ( const unsigned int * const pLhs, const unsigned int * const pRhs )\n        {\n            // Initialize comparison as less than\n            bool lLhsLessThanRhs = false;\n            // Loop through arrays\n            for ( unsigned int lIter = 0; lIter < mD; lIter++  )\n            {\n                // If current \n                if ( pLhs[lIter] < pRhs[lIter] )\n                {\n                    // Set that Lhs is smaller than Rhs\n                    lLhsLessThanRhs = true;\n                    // Stop looping\n                    break;\n                }\n                else \n                    if ( pLhs[lIter] > pRhs[lIter] )\n                        // Stop looping since rhs is apparently smaller\n                        break;\n            }\n            // Return result\n            return lLhsLessThanRhs;\n        }\n    \n    private:\n        const unsigned int mD;\n};\n\n\n// Class representing boundaries of all simplices in a mesh\nclass SimplexEdges\n{\n    public:\n\n        SimplexEdges() {}\n    \n        // Compute all simplex boundaries and which simplices they are boundaries of.\n        int computeEdges( \n            const unsigned int * const pSimplices, const unsigned int pTopD, \n            const unsigned int pNumSimplices, const unsigned int pEdgeDim );\n        // Populate edges array\n        int populateEdges( unsigned int * pEdges, const unsigned int pNumEdges, const unsigned pNumNodes ) const;\n        // Populate simplex array associated with edges array\n        int populateEdgesSimplexList( unsigned int * const pSimplexList, const unsigned int pNumEdges, \n            const unsigned pMaxNumSimplicesPerEdge, const unsigned int pNumSimplices ) const;\n        // Populate map of all edges to each simplex\n        int populateSimplexEdgesList( unsigned int * const pEdgeList, const unsigned int pNumSimplices, \n            const unsigned int pNumEdgesPerSimplex ) const;\n            \n        // Acquire number of maximum simplices per edge\n        inline const unsigned int & getMaxSimplicesPerEdge() const { return mMaxSimplicesPerEdge; }\n        // Get number of edges\n        inline unsigned int getNumEdges() const { return mEdges.size(); }\n        // Get number of edges for each simplex\n        inline const unsigned int & getNumEdgesPerSimplex() const { return mNumEdgesPerSimplex; }\n        \n        // Function for finding edge index from edge definition in logarithmic time\n        static unsigned int findEdgeIndexGivenEdge( const unsigned int * const pEdge,\n            const unsigned int * pEdges, const unsigned int pNumEdges, const unsigned int pEdgeDim );\n    \n        // Typedef of the pair of boundary node indices and simplices associated with boundary\n        typedef std::pair< std::set<unsigned int>, std::set<unsigned int> > EdgeElement;\n\n    private:\n\n        // Functor for comparison of EdgeElements\n        class CompareEdges\n        {\n            public:\n            bool operator() ( const EdgeElement & pLhs, const EdgeElement & pRhs )\n            { \n                CompareNodeSets lTemp;\n                return lTemp(pLhs.first, pRhs.first); \n            }\n        };\n        \n        // Store the maximum number of simplices for any edge\n        unsigned int mMaxSimplicesPerEdge = 1;\n        // Store the number of nodes in edges\n        unsigned int mEdgeDim = 0;\n        // Store number of edges per simplex\n        unsigned int mNumEdgesPerSimplex = 0;\n        // Store simplex boundaries\n        std::set< EdgeElement, CompareEdges > mEdges;\n};\n\n\n// Class representing a mapping from original simplices on a manifold (embedded or not) to standard simplex coordinates\nclass MapToSimp\n{\n    public:\n        // Constructor\n        MapToSimp( const double * const pPoints, const unsigned int pD, const unsigned int pTopD );\n        // Acquire determinant (of R1 if pTopD < pD)\n        double getAbsDeterminant() const {return std::abs(mDeterminant);}\n        // Solve \n        Eigen::MatrixXd solve( const Eigen::MatrixXd & pVector ) const;\n        // Solve transposed\n        Eigen::MatrixXd solveTransposed( const Eigen::MatrixXd & pVector ) const;\n        // Get length between hyperplane of simplex and vector\n        double getOrthogonalLength( const Eigen::VectorXd & pVector ) const;\n        // Get parameter value 't' of line parameterized as 'pLinePoint' + t*'pLineVector', for the point where line cuts hyperplane of simplex.\n        double getLineIntersection( const Eigen::VectorXd & pLinePoint, const Eigen::VectorXd & pLineVector ) const;\n        // Get standard coordinates of vector\n        Eigen::MatrixXd getStandardCoord( const Eigen::MatrixXd & pVector ) const {return solve(pVector.colwise() - mPoint0);}\n        // right multiplication of F with vector\n        Eigen::MatrixXd multiplyWithF( const Eigen::MatrixXd & pVector ) const;        \n        // Map point from standard simplex space to original space\n        Eigen::MatrixXd getOriginalCoord( const Eigen::MatrixXd & pVector ) const { return ( multiplyWithF( pVector ).colwise() + mPoint0 );  }\n    \n    private:\n    \n        const unsigned int mD;\n        const unsigned int mTopD;\n        double mDeterminant;\n        Eigen::VectorXd mPoint0;\n        Eigen::ColPivHouseholderQR< Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor> > mQR;\n\n};\n\n\n// Class aiding in extending mesh to new dimension\nclass ExtendMesh\n{\n\n    public:\n        \n        ExtendMesh( const std::vector<unsigned int> * const pEdges,\n            const std::vector<unsigned int> * const pSimplexIdentity,\n            const std::vector<unsigned int> * const pEdgeIdentity,\n            const unsigned int * const pSimplices, \n            const unsigned int pNumSimplices, const unsigned int pTopD, \n            const unsigned int pNumNodes, const unsigned int pNumEdgesSimp ) : \n            mEdges(pEdges), mSimplexIdentity(pSimplexIdentity), mEdgeIdentity(pEdgeIdentity),\n            mOldSimplices(pSimplices), mNumSimplices(pNumSimplices), mTopD(pTopD), mNumNodes(pNumNodes), mNumEdgesSimp(pNumEdgesSimp) \n            {\n                // Create vector of which simplices that have been placed\n                mPlacedSimplices = std::vector<bool>(mNumSimplices, false);\n            }\n            \n        // Mark that simplices has been placed covering old simplex\n        inline int markPlacement( const unsigned int pSimplexId, const bool pMarker = true )\n        {\n            if ( pSimplexId > mNumSimplices )\n                return 1;\n            mPlacedSimplices.at(pSimplexId) = pMarker;\n            return 0;\n        }\n        // Get if simplex is placed\n        inline bool isSimplexPlaced( const unsigned int pSimplexId ) const\n        {\n            if ( pSimplexId > mNumSimplices )\n                return true;\n            return mPlacedSimplices.at(pSimplexId);\n        }\n        // get all node index values to choose from for extensions of specific simplex\n        inline std::set<unsigned int> allPossibleNodeInds( const unsigned int pSimplexInd ) const\n        {\n            // Get all nodes possible for sub simplices\n            std::set<unsigned int> lPossibleNodeInds;\n            for ( unsigned int lIterNodes = 0; lIterNodes < ( mTopD + 1 ); lIterNodes++ )\n            {\n                lPossibleNodeInds.insert( mOldSimplices[ pSimplexInd * (mTopD+1) + lIterNodes ] );\n                lPossibleNodeInds.insert( mOldSimplices[ pSimplexInd * (mTopD+1) + lIterNodes ] + mNumNodes );\n            }\n        \n            return lPossibleNodeInds;\n        }\n        // Get all edge indices of current simplex\n        inline std::vector<unsigned int> edgesOfOldSimplex( const unsigned int pSimplexInd ) const\n        {\n            return std::vector< unsigned int >(\n                mSimplexIdentity->begin() + pSimplexInd * mNumEdgesSimp, \n                mSimplexIdentity->begin() + (pSimplexInd + 1) * mNumEdgesSimp );\n        }\n        // Is simplex on the border\n        bool isSimplexOnBorder( const unsigned int pSimplexId ) const;\n        // Get all old simplices sharing an edge with current simplex, as well as which edge are shared between them\n        std::vector< std::pair< unsigned int, unsigned int> > neighSimps( \n            const unsigned int pSimplexInd, const char pPlaced = 0 ) const;\n        // Computes all new edges of old simplex that are fixed due to already placed new simplices\n        std::list< std::set<unsigned int> > computeComplyEdgesFromPlaced( \n            const unsigned int pSimplexInd, const std::vector<std::pair<unsigned int, unsigned int>> & pNeighs, \n            const unsigned int * const pNewSimplices ) const;\n        // Computes the simplex when projected onto old dimensionality\n        std::set<unsigned int> projectNewOntoOldSimplex( std::set<unsigned int> & pNewSimplex ) const;\n        // See if simplex is on edge of prism\n        bool onPrismEdge( std::set<unsigned int> & pNewSimplex ) const;\n            \n        // Acquire vector of new simplices from an old simplex (taking into account placed neighbors)\n        int computeNewSubSimplices( \n            const unsigned int pSimplexInd, const unsigned int * const pNewSimplices, std::vector< std::set<unsigned int> > & pOut  ) const;\n        // Acquire list of simplices which mark the path from given simplex to closest simplex that is not placed (or is an edge)\n        unsigned int shortestPathToFreedom( const unsigned int pSimplexId, const unsigned int pPrevSimplexId, std::list<unsigned int> & pPath ) const;\n        \n        \n\n    protected:\n    \n        const std::vector<unsigned int> * const mEdges;\n        const std::vector<unsigned int> * const mSimplexIdentity;\n        const std::vector<unsigned int> * const mEdgeIdentity;\n        std::vector<bool> mPlacedSimplices;\n        const unsigned int mTopD;\n        const unsigned int mNumNodes;\n        const unsigned int mNumSimplices;\n        const unsigned int mNumEdgesSimp;\n        const unsigned int * const mOldSimplices;\n\n};\n\n\n// Get edges of simplex\nint mesh_getEdgesOfSimplex( std::vector< std::set<unsigned int> > & pOut, const unsigned int pNumCombinations,\n    const unsigned int pEdgeDim, const unsigned int pTopologicalD, const unsigned int * const pSimplex );\n// Acquire edges and edge identities from simplex mapping    \nint mesh_getEdgesAndRelations( std::vector<unsigned int> &pEdges, std::vector<unsigned int> &pSimplexIdentity, std::vector<unsigned int> &pEdgeIdentity,\n    const unsigned int * const pSimplices, const unsigned int pNumSimplices, const unsigned int pTopD, const unsigned int pNumEdgesSimp = 0 );    \n        \n\nextern \"C\"\n{    \n\n    // Get observation matrix (only works in R^d, no embedded manifolds)\n    int mesh_getObservationMatrix( double * const pData, unsigned int * const pRow, unsigned int * const pCol, const unsigned int pNumNonZeros,\n        const double * const pPoints, const unsigned int pNumPoints,\n        const double * const pNodes, const unsigned int pNumNodes,\n        const unsigned int * const pMesh, const unsigned int pNumSimplices,\n        const unsigned int pD, const unsigned int pTopD, const double pEmbTol = 0.0d,\n        const double * const pCenterOfCurvature = NULL, const unsigned int pNumCentersOfCurvature = 0);\n        \n    // Maps triangle values to matrices\n    int mesh_getGradientCoefficientMatrix( const unsigned int pNonNulls, double * const pData, \n        unsigned int * const pRow, unsigned int * const pCol, unsigned int * const pDataIndex,\n        const double * const pNodes, const unsigned int pNumNodes,\n        const unsigned int * const pMesh, const unsigned int pNumSimplices,\n        const unsigned int pD, const unsigned int pTopD,\n        double * const pAreas = NULL );\n    \n    // Recurrent investigation of all edges (or sub-edges) [thread safe]\n    int mesh_recurrentEdgeFinder( unsigned int * const pEdgeList, const unsigned int pAllocateSpace,\n        const unsigned int pD, const unsigned int * const pCurPointConfig, const unsigned int pNumPointConfig );\n    \n    // Get edges of simplices\n    int mesh_getEdgesOfSimplices( unsigned int * const pEdges, unsigned int * pEdgeIndex, unsigned int * const pSimplexIdentity, const unsigned int pEdgeDim, \n        const unsigned int pTopologicalD, const unsigned int * const pSimplex, const unsigned int pNumSimplices ); \n    // Compute edges of chosen dimensionality and which simplices that are associated to them\n    int mesh_computeEdges( const unsigned int pEdgeDim, const unsigned int * const pSimplices,\n        const unsigned int pNumSimplices, const unsigned int pTopD,\n        unsigned int * const pNumEdges, unsigned int * const pEdgeId, unsigned int * const pMaxSimplicesPerEdge );\n    // Populate arrays of edges, associated simplices, and associated edges to each simplex\n    int mesh_populateEdges( unsigned int * const pEdges, const unsigned int pEdgeDim, const unsigned int pNumEdges, \n        const unsigned int pEdgeId,\n        unsigned int * const pSimplicesForEdges, const unsigned int pMaxSimplicesPerEdge, const unsigned int pNumSimplices, \n        unsigned int * const pEdgesForSimplices, const unsigned int pNumEdgesPerSimplex );\n    // Clear saved edges\n    int mesh_clearEdges( const unsigned int pEdgeId );\n    \n    // Get neighborhood of each simplex\n    int mesh_getSimplexNeighborhood( const unsigned int pNumEdges, const unsigned int pNumSimplices,\n        const unsigned int * const pSimplicesForEdges, const unsigned int pMaxSimplicesPerEdge,\n        const unsigned int * const pEdgesForSimplices, const unsigned int pNumEdgesPerSimplex,\n        unsigned int * const pNeighborhood\n      );\n    \n    // Refines chosen simplices\n    int mesh_refineMesh( const double * const pNodes, const unsigned int pNumNodes, const unsigned int pD,\n        const unsigned int * const pSimplices, const unsigned int pNumSimplices, const unsigned int pTopD,\n        unsigned int * const pNewNumNodes, unsigned int * const pNewNumSimplices, unsigned int * const pId,\n        const unsigned int pMaxNumNodes, const double * const pMaxDiam, const unsigned int pNumMaxDiam,\n        const unsigned int * const pNumLevels, int (* transformationPtr)(double *, unsigned int) );\n        \n    // Populate new mesh\n    int mesh_acquireMesh( const unsigned int pId, \n        double * const pNodes, const unsigned int pNumNodes, const unsigned int pD,\n        unsigned int * const pSimplices, const unsigned int pNumSimplices, const unsigned int pTopD,\n        unsigned int * const pNeighs = NULL );\n        \n    // Binomial coefficient\n    inline unsigned int mesh_nchoosek( unsigned int n, unsigned int k );\n    \n    // Extend mesh\n    int mesh_extendMesh( unsigned int * const pNewSimplices, const unsigned int pNewNumSimplices,\n        const unsigned int * const pSimplices, const unsigned int pNumSimplices, const unsigned int pTopD, const unsigned int pNumNodes );\n        \n        \n        \n}\n\n\n\n\n\n#endif // MESH_HXX", "meta": {"hexsha": "5c844dcd106b7da364d16172149f1289e75a8825", "size": 25649, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "fieldosophy/Includes/mesh.hxx", "max_stars_repo_name": "andyGFHill/fieldosophy", "max_stars_repo_head_hexsha": "8677048d56b382a45a80383fe8ff84d75a5f9760", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-05-03T10:07:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T19:24:28.000Z", "max_issues_repo_path": "fieldosophy/Includes/mesh.hxx", "max_issues_repo_name": "andyGFHill/fieldosophy", "max_issues_repo_head_hexsha": "8677048d56b382a45a80383fe8ff84d75a5f9760", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fieldosophy/Includes/mesh.hxx", "max_forks_repo_name": "andyGFHill/fieldosophy", "max_forks_repo_head_hexsha": "8677048d56b382a45a80383fe8ff84d75a5f9760", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-27T11:49:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-27T11:49:02.000Z", "avg_line_length": 47.586270872, "max_line_length": 176, "alphanum_fraction": 0.6423252369, "num_tokens": 6066, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743168019989179, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.45985782975346245}}
{"text": "/** \\file mean_atomic.hpp \\brief Atomic (simple) parametric functions */\n/*\n-------------------------------------------------------------------------\n   This file is part of BayesOpt, an efficient C++ library for \n   Bayesian optimization.\n\n   Copyright (C) 2011-2015 Ruben Martinez-Cantin <rmcantin@unizar.es>\n \n   BayesOpt is free software: you can redistribute it and/or modify it \n   under the terms of the GNU Affero General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   BayesOpt is distributed in the hope that it will be useful, but \n   WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU Affero General Public License for more details.\n\n   You should have received a copy of the GNU Affero General Public License\n   along with BayesOpt.  If not, see <http://www.gnu.org/licenses/>.\n------------------------------------------------------------------------\n*/\n\n#ifndef  _MEAN_ATOMIC_HPP_\n#define  _MEAN_ATOMIC_HPP__\n\n#include <boost/numeric/ublas/vector_proxy.hpp>\n#include \"mean_functors.hpp\"\n\nnamespace bayesopt\n{\n\n  /**\\addtogroup ParametricFunctions\n   * @{\n   */\n\n  /** \\brief Abstract class for an atomic kernel */\n  class AtomicFunction : public ParametricFunction\n  {\n  public:\n    virtual int init(size_t input_dim)\n    {\n      n_inputs = input_dim;\n      return 0;\n    };\n    void setParameters(const vectord &theta) \n    {\n      if(theta.size() != n_params)\n\t{\n\t  throw std::invalid_argument(\"Wrong number of mean function parameters\"); \n\t}\n   \n      mParameters = theta;\n    };\n    vectord getParameters() {return mParameters;};\n    size_t nParameters() {return n_params;};\n    size_t nFeatures() {return n_features;};\n\n    virtual ~AtomicFunction(){};\n\n  protected:\n    size_t n_params;\n    size_t n_features;\n    vectord mParameters;\n  };\n\n\n  /** \\brief Constant zero function */\n  class ZeroFunction: public AtomicFunction\n  {\n  public:\n    int init(size_t input_dim)\n    {\n      n_inputs = input_dim;\n      n_params = 1;\n      n_features = 1;\n      return 0;\n    };\n    double getMean (const vectord& x) { return 0.0; };\n    vectord getFeatures(const vectord& x) { return zvectord(1); };  \n  };\n\n  /** \\brief Constant one function */\n  class OneFunction: public AtomicFunction\n  {\n  public:\n    int init(size_t input_dim)\n    {\n      n_inputs = input_dim;\n      n_params = 1;\n      n_features = 1;\n      return 0;\n    };\n    double getMean (const vectord& x) { return 1.0; };\n    vectord getFeatures(const vectord& x) { return svectord(1,1.0); };  \n  };\n\n\n  /** \\brief Constant function. \n      The first parameter indicates the constant value. */\n  class ConstantFunction: public AtomicFunction\n  {\n  public:\n    int init(size_t input_dim)\n    {\n      n_inputs = input_dim;\n      n_params = 1;\n      n_features = 1;\n      return 0;\n    };\n    double getMean (const vectord& x) { return mParameters(0); };\n    vectord getFeatures(const vectord& x) { return svectord(1,1.0); };  \n  };\n\n\n  /** \\brief Linear combination function. \n      Each parameter indicates the coefficient of each dimension. */\n  class LinearFunction: public AtomicFunction\n  {\n  public:\n    int init(size_t input_dim)\n    {\n      n_inputs = input_dim;\n      n_params = input_dim;\n      n_features = input_dim;\n      return 0;\n    };\n    double getMean (const vectord& x)\n    { return boost::numeric::ublas::inner_prod(x,mParameters);  };\n    vectord getFeatures(const vectord& x) { return x; };  \n  };\n\n\n  /** \\brief Linear combination plus constant function. \n      The first parameter indicates the constant value. */\n  class LinearPlusConstantFunction: public AtomicFunction\n  {\n  public:\n    int init(size_t input_dim)\n    {\n      n_inputs = input_dim;\n      n_params = input_dim + 1;\n      n_features = input_dim + 1;\n      return 0;\n    };\n    void setParameters(const vectord& params)\n    { \n      if(params.size() != n_params)\n\t{\n\t  throw std::invalid_argument(\"Wrong number of mean function parameters\"); \n\t}\n\n      mConstParam = params(0);\n      mParameters = boost::numeric::ublas::project(params, \n\t\t\t\t\t\t   boost::numeric::ublas::range(1, params.size())); \n    };\n  \n    double getMean (const vectord& x)\n    { return boost::numeric::ublas::inner_prod(x,mParameters) + mConstParam;  };\n\n    vectord getFeatures(const vectord& x) \n    {\n      using boost::numeric::ublas::range;\n      using boost::numeric::ublas::project;\n      vectord res(x.size()+1);\n      res(0) = 1;\n      project(res,range(1,res.size())) = x;\n      return res; \n    };  \n\n  protected:\n    double mConstParam;\n  };\n\n  //@}\n\n} //namespace bayesopt\n\n#endif\n", "meta": {"hexsha": "3d67a29ed8c5790a3f450a2ca79739a8ee52cd44", "size": 4707, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "external/bayesopt/include/mean_atomic.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/mean_atomic.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/mean_atomic.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": 26.15, "max_line_length": 80, "alphanum_fraction": 0.6330996388, "num_tokens": 1175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743168019989179, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.45985782975346245}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// statistics::survival::model::exponential::model.hpp                       //\n//                                                                           //\n//  Copyright 2009 Erwann Rogard. Distributed under the Boost                //\n//  Software License, Version 1.0. (See accompanying file                    //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)         //\n///////////////////////////////////////////////////////////////////////////////\n#ifndef BOOST_STATISTICS_SURVIVAL_MODEL_MODELS_EXPONENTIAL_MODEL_HPP_ER_2009\n#define BOOST_STATISTICS_SURVIVAL_MODEL_MODELS_EXPONENTIAL_MODEL_HPP_ER_2009\n#include <numeric>\n#include <boost/mpl/assert.hpp>\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/archive/text_iarchive.hpp>\n#include <boost/type_traits/is_scalar.hpp>\n#include <boost/utility/enable_if.hpp>\n#include <boost/range.hpp>\n\nnamespace boost{\nnamespace statistics{\n\nnamespace survival{\nnamespace model{\nnamespace exponential{\n\n    template<typename T>\n    class model{\n        public:\n        typedef T value_type;\n    \n        model();\n                \n        template<typename X,typename B>\n        static typename boost::enable_if<boost::is_scalar<X>,T>::type\n        log_rate(const X& x,const B& b);\n\n        template<typename X,typename B>\n        static typename boost::disable_if<boost::is_scalar<X>,T>::type\n        log_rate(const X& x,const B& b);\n\n        protected:\n        friend class boost::serialization::access;\n        template<class Archive>\n        void serialize(Archive & ar, const unsigned int version){\n            // no member variables\n        }\n\n    };\n\n    // Implementation //\n    \n    template<typename T>\n    model<T>::model(){}\n\n    template<typename T>\n    template<typename X,typename B>\n    typename boost::enable_if<boost::is_scalar<X>,T>::type\n    model<T>::log_rate(const X& x,const B& b){\n        BOOST_MPL_ASSERT((\n            is_scalar<B>\n        ));\n        return ( static_cast<T>( x ) * static_cast<T>( b ) );\n    }\n\n    template<typename T>\n    template<typename X,typename B>\n    typename boost::disable_if<is_scalar<X>,T>::type\n    model<T>::log_rate(const X& x,const B& b){\n        BOOST_ASSERT(size(x) == size(b));\n        return std::inner_product( \n            boost::begin(x), \n            boost::end(x),\n            boost::begin(b),\n            static_cast<T>(0)\n        );\n    }\n\n}// exponential\n}// model    \n}// survival\n}// statistics\n}// boost\n\n#endif \n", "meta": {"hexsha": "e90c5558941674856d679dfcde317eeedf779aa3", "size": 2546, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "survival_model copy/boost/statistics/survival/model/models/exponential/model.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": "survival_model copy/boost/statistics/survival/model/models/exponential/model.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": "survival_model copy/boost/statistics/survival/model/models/exponential/model.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": 30.3095238095, "max_line_length": 79, "alphanum_fraction": 0.5655930872, "num_tokens": 528, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743168019989179, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.45985782975346245}}
{"text": "#ifndef ALEPH_CONTAINERS_DIMENSIONALITY_ESTIMATORS_HH__\n#define ALEPH_CONTAINERS_DIMENSIONALITY_ESTIMATORS_HH__\n\n#include <aleph/math/KahanSummation.hh>\n#include <aleph/math/PrincipalComponentAnalysis.hh>\n\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/kruskal_min_spanning_tree.hpp>\n\n#include <iterator>\n#include <limits>\n#include <stdexcept>\n#include <vector>\n\n#include <cmath>\n\nnamespace aleph\n{\n\nnamespace containers\n{\n\n/**\n  Estimates local intrinsic dimensionality of a container using its\n  nearest neighbours. The underlying assumption of the estimator is\n  that points are locally uniformly distributed uniformly. Use this\n  estimator with care when analysing unknown data.\n\n  @param container Container to use for dimensionality estimation\n  @param k         Number of nearest neighbours\n  @param distance  Distance measure\n\n  @returns Vector of local intrinsic dimensionality estimates. Note\n           that the numbers are reported *without* rounding.\n*/\n\ntemplate <\n  class Distance,\n  class Container,\n  class Wrapper\n> std::vector<double> estimateLocalDimensionalityNearestNeighbours( const Container& container,\n                                                                    unsigned k,\n                                                                    Distance /* distance */ = Distance() )\n{\n  using IndexType   = typename Wrapper::IndexType;\n  using ElementType = typename Wrapper::ElementType;\n\n  std::vector< std::vector<IndexType> > indices;\n  std::vector< std::vector<ElementType> > distances;\n\n  Wrapper nnWrapper( container );\n  nnWrapper.neighbourSearch( k+1, indices, distances );\n\n  auto n = container.size();\n\n  std::vector<double> estimates;\n  estimates.reserve( n );\n\n  for( decltype(n) i = 0; i < n; i++ )\n  {\n    auto&& nnDistances = distances.at(i);\n    auto r1            = aleph::math::accumulate_kahan( nnDistances.begin(), nnDistances.begin() + k,     0.0 ) / static_cast<double>(k  );\n    auto r2            = aleph::math::accumulate_kahan( nnDistances.begin(), nnDistances.begin() + k + 1, 0.0 ) / static_cast<double>(k+1);\n\n    estimates.push_back( r1 / ( (r2-r1)*k ) );\n  }\n\n  return estimates;\n}\n\n/**\n  Estimates local intrinsic dimensionality of a container using its\n  nearest neighbours. No assumptions about the distribution of data\n  points are made. The function uses an iteration over a *range* of\n  nearest neighbours and solves a regression problem.\n\n  Please see the publication\n\n    > An evaluation of intrinsic dimensionality estimators\\n\n    > Peter J. Verveer and Robert P. W. Duin\\n\n    > IEEE Transactions on Pattern Analysis and Machine Intelligence 17.1, pp. 81-86, 1985\n\n  for more details.\n\n  @param container Container to use for dimensionality estimation\n\n  @param kMin      Minimum number of nearest neighbours to use in\n                   computing local dimensionality estimates.\n\n  @param kMax      Maximum number of nearest neighbours to use in\n                   computing local dimensionality estimates. This\n                   parameter influences performance.\n\n  @param distance  Distance measure\n\n  @returns Vector of local intrinsic dimensionality estimates. Note that\n           the numbers are reported *without* rounding.\n*/\n\ntemplate <\n  class Distance,\n  class Container,\n  class Wrapper\n> std::vector<double> estimateLocalDimensionalityNearestNeighbours( const Container& container,\n                                                                    unsigned kMin,\n                                                                    unsigned kMax,\n                                                                    Distance /* distance */ = Distance() )\n\n{\n  if( kMin > kMax )\n    std::swap( kMin, kMax );\n\n  if( kMax == 0 || kMin == 0 )\n    throw std::runtime_error( \"Expecting non-zero number of nearest neighbours\" );\n\n  using IndexType   = typename Wrapper::IndexType;\n  using ElementType = typename Wrapper::ElementType;\n\n  std::vector< std::vector<IndexType> > indices;\n  std::vector< std::vector<ElementType> > distances;\n\n  Wrapper nnWrapper( container );\n  nnWrapper.neighbourSearch( kMax, indices, distances );\n\n  auto n = container.size();\n\n  std::vector<double> estimates;\n  estimates.reserve( n );\n\n  for( decltype(n) i = 0; i < n; i++ )\n  {\n    auto&& nnDistances = distances.at(i);\n\n    std::vector<double> localEstimates;\n    localEstimates.reserve( kMax );\n\n    for( unsigned k = kMin; k < kMax; k++ )\n    {\n      auto r = aleph::math::accumulate_kahan( nnDistances.begin(), nnDistances.begin() + k, 0.0 ) / static_cast<double>(k);\n      localEstimates.emplace_back( r );\n    }\n\n    // The dimensionality estimates consist of two terms. The first term\n    // is similar to the local biased dimensionality estimate.\n\n    std::vector<double> firstTerms;\n    firstTerms.reserve( kMax );\n\n    std::vector<double> secondTerms;\n    secondTerms.reserve( kMax );\n\n    for( unsigned k = kMin; k < kMax - 1; k++ )\n    {\n      auto index = k - kMin;\n      auto r1    = localEstimates.at(index);\n      auto r2    = localEstimates.at(index+1);\n\n      firstTerms.emplace_back ( ( (r2-r1) * r1 ) / k );\n      secondTerms.emplace_back( ( (r2-r1) * (r2-r1) ) );\n    }\n\n    auto s = aleph::math::accumulate_kahan( firstTerms.begin() , firstTerms.end() , 0.0 );\n    auto t = aleph::math::accumulate_kahan( secondTerms.begin(), secondTerms.end(), 0.0 );\n\n    estimates.push_back( s / t );\n  }\n\n  return estimates;\n\n}\n\n/**\n  Estimates local intrinsic dimensionality of a container using its\n  nearest neighbours. No assumptions about the distribution of data\n  points are made. The function uses *maximum likelihood estimates*\n  for the dimensionality estimates.\n\n  Please see the publication\n\n    > Maximum Likelihood Estimation of Intrinsic Dimension\\n\n    > Elizaveta Levina and Peter J. Bickel\\n\n    > Advances in Neural Information Processing Systems, 2005\n\n  for more details.\n\n  @param container Container to use for dimensionality estimation\n\n  @param kMin      Minimum number of nearest neighbours to use in\n                   computing local dimensionality estimates.\n\n  @param kMax      Maximum number of nearest neighbours to use in\n                   computing local dimensionality estimates. This\n                   parameter influences performance.\n\n  @param distance  Distance measure\n\n  @returns Vector of local intrinsic dimensionality estimates. Note that\n           the numbers are reported *without* rounding.\n*/\n\ntemplate <\n  class Distance,\n  class Container,\n  class Wrapper\n> std::vector<double> estimateLocalDimensionalityNearestNeighboursMLE( const Container& container,\n                                                                       unsigned kMin,\n                                                                       unsigned kMax,\n                                                                       Distance /* distance */ = Distance() )\n{\n  if( kMin > kMax )\n    std::swap( kMin, kMax );\n\n  if( kMax == 0 || kMin == 0 )\n    throw std::runtime_error( \"Expecting non-zero number of nearest neighbours\" );\n\n  using IndexType   = typename Wrapper::IndexType;\n  using ElementType = typename Wrapper::ElementType;\n\n  std::vector< std::vector<IndexType> > indices;\n  std::vector< std::vector<ElementType> > distances;\n\n  Wrapper nnWrapper( container );\n  nnWrapper.neighbourSearch( kMax, indices, distances );\n\n  auto n = container.size();\n\n  std::vector<double> estimates;\n  estimates.reserve( n );\n\n  for( decltype(n) i = 0; i < n; i++ )\n  {\n    auto&& nnDistances = distances.at(i);\n\n    std::vector<double> localEstimates;\n    localEstimates.reserve( kMax );\n\n    // This follows the notation in the original paper. I dislike using\n    // $T_k$ to denote distances, though.\n    for( unsigned k = kMin - 1; k < kMax; k++ )\n    {\n      // Nothing to do here...\n      if( k == 0 )\n        continue;\n\n      std::vector<double> logEstimates;\n      logEstimates.reserve( k-1 );\n\n      for( auto it = nnDistances.begin(); it != nnDistances.begin() + k; ++it )\n      {\n        if( *it > 0.0 && nnDistances.at(k) > 0.0 )\n          logEstimates.push_back( std::log( nnDistances.at(k) / *it ) );\n\n        // This defines log(0) = 0, as usually done in information\n        // theory. The original paper does not handle this.\n        else\n          logEstimates.push_back( 0.0 );\n      }\n\n      auto mk = k > 1 ? 1.0 / (k-1) * aleph::math::accumulate_kahan( logEstimates.begin(), logEstimates.end(), 0.0 )\n                      : 0.0;\n\n      if( mk > 0.0 )\n        mk = 1.0 / mk;\n      else\n        mk = 0.0;\n\n      localEstimates.push_back( mk );\n    }\n\n    estimates.push_back( aleph::math::accumulate_kahan( localEstimates.begin(), localEstimates.end(), 0.0 ) / (kMax - kMin + 1) );\n  }\n\n  return estimates;\n}\n\n/**\n  Estimates local intrinsic dimensionality of a container using its\n  minimum spanning tree.\n\n  @param container Container to use for dimensionality estimation\n  @param distance  Distance measure\n\n  @returns Vector of local intrinsic dimensionality estimates. Note\n           that the numbers are reported *without* rounding.\n*/\n\ntemplate <\n  class Distance,\n  class Container\n> std::vector<double> estimateLocalDimensionalityNearestNeighbours( const Container& container,\n                                                                    Distance distance = Distance() )\n{\n  using WeightedGraph\n    = boost::adjacency_list<\n        boost::vecS,\n        boost::vecS,\n        boost::undirectedS,\n        boost::no_property,\n        boost::property<boost::edge_weight_t, double> >;\n\n  using VertexDescriptor = boost::graph_traits<WeightedGraph>::vertex_descriptor;\n  using EdgeDescriptor   = boost::graph_traits<WeightedGraph>::edge_descriptor;\n\n  auto n = container.size();\n  auto d = container.dimension();\n\n  WeightedGraph G( n );\n\n  for( std::size_t i = 0; i < n; i++ )\n  {\n    auto&& p = container[i];\n\n    for( std::size_t j = i+1; j < n; j++ )\n    {\n      auto&& q  = container[j];\n      auto dist = distance( p.begin(), q.begin(), d );\n\n      boost::add_edge( VertexDescriptor(i),\n                       VertexDescriptor(j),\n                       dist,\n                       G );\n    }\n  }\n\n  std::vector<EdgeDescriptor> mstEdges;\n  boost::kruskal_minimum_spanning_tree( G,\n                                        std::back_inserter( mstEdges ) );\n\n  WeightedGraph MST( n );\n\n  for( auto&& edge : mstEdges )\n  {\n    boost::add_edge( boost::source( edge, G ),\n                     boost::target( edge, G ),\n                     MST );\n  }\n\n  for( auto pair = boost::vertices( MST ); pair.first != pair.second; ++pair.first )\n  {\n  }\n\n  return {};\n}\n\n/**\n  Estimates local intrinsic dimensionality of a container using its\n  local principal components. The basic premise is that the largest\n  spectral gap in the eigenspectrum of a local PCA gives a suitable\n  hint about the local dimensionality at the given set of points.\n\n  @param container Container to use for dimensionality estimation\n  @param distance  Distance measure\n\n  @returns Vector of local intrinsic dimensionality estimates. The numbers are\n           not rounded but taken directly from the estimation procedure.\n*/\n\ntemplate <\n  class Distance,\n  class Container,\n  class Wrapper\n> std::vector<unsigned> estimateLocalDimensionalityPCA( const Container& container,\n                                                        unsigned k,\n                                                        Distance /* distance */ = Distance() )\n{\n  using IndexType   = typename Wrapper::IndexType;\n  using ElementType = typename Wrapper::ElementType;\n\n  std::vector< std::vector<IndexType> > indices;\n  std::vector< std::vector<ElementType> > distances;\n\n  Wrapper nnWrapper( container );\n  nnWrapper.neighbourSearch( k+1, indices, distances );\n\n  std::vector<unsigned> estimates;\n  estimates.reserve( container.size() );\n\n  for( auto&& localIndices : indices )\n  {\n    std::vector< std::vector<ElementType> > data( localIndices.size(), std::vector<ElementType>() );\n\n    {\n      std::size_t i = 0;\n      for( auto&& index : localIndices )\n      {\n        auto&& p = container[index];\n\n        data[i].assign( p.begin(), p.end() );\n\n        i++;\n      }\n    }\n\n    // Calculate a (local) principal component analysis and analyse the\n    // resulting spectrum. The largest spectral gap is used to estimate\n    // the local intrinsic dimensionality.\n    aleph::math::PrincipalComponentAnalysis pca;\n    auto result           = pca( data );\n    auto&& singularValues = result.singularValues;\n\n    if( singularValues.size() >= 2 )\n    {\n      ElementType spectralGap = std::numeric_limits<ElementType>::lowest();\n      unsigned spectralIndex  = 0;\n\n      auto prev = singularValues.begin();\n      auto curr = std::next( prev );\n\n      for( ; curr != singularValues.end(); ++prev, ++curr)\n      {\n        auto gap = std::abs( *prev - *curr );\n\n        if( gap > spectralGap )\n        {\n          // Notice that I am using the *lower* bound of the index here\n          // by specifying `prev` instead of current. This makes sense,\n          // as a jumping between $i-1$ and $i$ indicates that $i-1$ is\n          // sufficient to describe the data adequately.\n          //\n          // The additional offset of 1 is used because `std::distance`\n          // uses zero-based indices.\n          spectralGap   = gap;\n          spectralIndex = static_cast<unsigned>( std::distance( singularValues.begin(), prev ) ) + 1;\n        }\n      }\n\n      estimates.push_back( spectralIndex );\n    }\n  }\n\n  return estimates;\n}\n\n} // namespace containers\n\n} // namespace aleph\n\n#endif\n", "meta": {"hexsha": "67a0c9387dfcbf49484de7caa9145b2ab5098fe4", "size": 13571, "ext": "hh", "lang": "C++", "max_stars_repo_path": "include/aleph/containers/DimensionalityEstimators.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/containers/DimensionalityEstimators.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/containers/DimensionalityEstimators.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": 30.9134396355, "max_line_length": 139, "alphanum_fraction": 0.6268513743, "num_tokens": 3117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.45985782271378445}}
{"text": "// Copyright (C) 2017 Vicente J. Botet Escriba\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// <experimental/strong_type.hpp>\n\n/// This example tries to see how close we can define money using strong_type\n/// money should be close to strong_counter as it is close to duration.\n/// However, there are some issues.\n///     There is not a common currency (until we decide to have it)\n///         Adding money with different currencies needs the currency result, and so needs to be lazy\n///     Having a common currency means to do two operations to convert from two currencies.\n///         The compiler could optimize it if the currency is know at compile time, but in general this is not the case.\n///     Should we have implicit or explicit conversions between currencies?\n\n#include <iostream>\n#include <functional>\n#include <type_traits>\n#include \"currency.hpp\"\n#include <experimental/strong_counter.hpp>\n#include <experimental/fundamental/v2/config.hpp>\n\nnamespace stdex = std::experimental;\n\ntemplate <class M>\nusing currency_t = typename M::domain::currency_type;\n\ntemplate<class Currency>\nstruct money_domain\n{\n    using currency_type =  Currency;\n    template <class T, class C, class U\n          , typename std::enable_if <\n              std::conjunction <\n                std::is_convertible<U, T>, // no overflow\n                std::disjunction<\n                      std::is_floating_point<T>,\n                      std::conjunction<\n                          //std::integral_constant<bool, std::ratio_divide<P, Period>::den == 1>,\n                          std::true_type,\n                          std::negation< std::is_floating_point<U> >\n                      >\n                  >\n              >::value\n          >::type* = nullptr\n    >\n    static T inter_domain_convert(money_domain<C>, U const& u)\n    {\n        return T(currency::convert<C,Currency>(u));\n    }\n\n    template <class T, class C, class U>\n    static T inter_domain_cast(money_domain<C>, U const& u)\n    {\n        return T(currency::convert<C,Currency>(u));\n    }\n\n    template <class T, class U\n          , typename std::enable_if <\n              std::conjunction <\n                std::is_convertible<U, T>,\n                std::disjunction<\n                      std::is_floating_point<T>,\n                      std::negation< std::is_floating_point<U> >\n                >\n              >::value\n          >::type* = nullptr\n          >\n    static T intra_domain_convert(U const& u)\n    {\n        return T(u);\n    }\n};\n\nnamespace std\n{\n\nnamespace experimental\n{\ninline  namespace fundamental_v3 {\nnamespace mixin {\n  template <class Currency>\n  struct is_compatible_with<money_domain<Currency>, money_domain<Currency>> : std::true_type {};\n}\n}\n\ntemplate <class Currency>\nstruct domain_converter<money_domain<Currency>> : money_domain<Currency>  {  };\n}\n\n}\n\n// fixme: Should be Rep, Currency?\n// fixme: Should we add a Period parameter to count in Million Dollars, or in cents?\n//      Don't having a period, forces almost to work with double.\n//      Having a period allows to work with integers most of the time\n\ntemplate <class Currency, class Rep=double>\nusing money = stdex::strong_counter<money_domain<Currency>, Rep>;\n\nnamespace money_expr\n{\n/// helper function that converts a money to a specific currency using the conversion_factor customization point\ntemplate <class Currency, class C, class R>\ndouble to_currency(money<C, R> const& m)\n{\n    return currency::convert<C, Currency>(m.count());\n}\n\ntemplate <class M1, class M2, class Op>\nstruct binary\n{\n    M1 m1;\n    M2 m2;\n\n    // fixme:: shouldn't this require that the representation is convertible from the common_type?\n    template <class C, class R>\n    JASEL_CXX14_CONSTEXPR operator money<C,R>() {\n        return money<C,R>( Op{}(to_currency<C>(m1), to_currency<C>(m2)));\n    }\n};\n\ntemplate <class M1, class M2>\nstruct add\n{\n    M1 m1;\n    M2 m2;\n\n    // fixme:: shouldn't this requires that the representation is convertible from the common_type?\n    template <class C, class R>\n    JASEL_CXX14_CONSTEXPR operator money<C,R>()\n    {\n        return money<C,R>( to_currency<C>(m1) + to_currency<C>(m2));\n    }\n};\ntemplate <class M1, class M2>\nstruct substract\n{\n    M1 m1;\n    M2 m2;\n\n    template <class C, class R>\n    JASEL_CXX14_CONSTEXPR operator money<C,R>()\n    {\n        return money<C,R>( to_currency<C>(m1) - to_currency<C>(m2));\n    }\n};\n\ntemplate <class C, class M1, class M2>\nstruct divide\n{\n    M1 m1;\n    M2 m2;\n\n    template <class R>\n    JASEL_CXX14_CONSTEXPR operator R()\n    {\n        return money<C,R>( to_currency<C>(m1) / to_currency<C>(m2));\n    }\n};\n\ntemplate <class M1, class M2>\nstruct modulo\n{\n    M1 m1;\n    M2 m2;\n\n    template <class C, class R>\n    JASEL_CXX14_CONSTEXPR operator money<C,R>()\n    {\n        return money<C,R>( to_currency<C>(m1) % to_currency<C>(m2));\n    }\n};\n\n}\n\n\ntemplate <class C1, class R1, class C2, class R2, typename = std::enable_if_t< ! std::is_same<C1, C2>::value>>\nconstexpr auto operator+(money<C1,R1> m1, money<C2,R2> m2) noexcept\n-> money_expr::add<money<C1,R1>, money<C2,R2>>\n{\n    return money_expr::add<money<C1,R1>, money<C2,R2>>{m1, m2} ;\n    //return money_expr::binary<money<C1,R1>, money<C2,R2>, std::plus>{m1, m2} ;\n}\n\ntemplate <class C1, class R1, class C2, class R2, typename = std::enable_if_t< ! std::is_same<C1, C2>::value>>\nconstexpr auto operator-(money<C1,R1> m1, money<C2,R2> m2) noexcept\n-> money_expr::substract<money<C1,R1>, money<C2,R2>>\n{\n    return money_expr::substract<money<C1,R1>, money<C2,R2>>{m1, m2} ;\n}\n\ntemplate <class OSTREAM, class C, class R>\nOSTREAM& operator<<(OSTREAM& os, money<C, R> m)\n{\n    os<< m.count() << C{}.symbol();\n    return os;\n}\n\nusing dollars = money<currency::dollar>;\nusing euros = money<currency::euro>;\n\n\n#include <boost/detail/lightweight_test.hpp>\n#include <iostream>\n\nint main()\n{\n    {\n        dollars d(5);\n        BOOST_TEST(long(d.count()) == 5);\n    }\n    {\n        dollars d;\n        d = dollars(5);\n        BOOST_TEST(long(d.count()) == 5);\n    }\n    {\n        dollars d;\n        d = dollars(5);\n        BOOST_TEST(d == dollars(5));\n    }\n    {\n        dollars d1(5), d2(10);\n        BOOST_TEST(d1+d2 == dollars(15));\n    }\n    {\n        dollars d(5);\n        BOOST_TEST(+d  == d);\n    }\n    {\n        dollars d1(5), d2(10);\n        BOOST_TEST(d1-d2 == dollars(-5));\n    }\n    {\n        dollars d(5);\n        BOOST_TEST(-d  == dollars(-5));\n    }\n    {\n        dollars d(5);\n        BOOST_TEST(d * 3  == dollars(15));\n    }\n    {\n        dollars d(5);\n        BOOST_TEST(3 * d  == dollars(15));\n    }\n    {\n        dollars d(15);\n        BOOST_TEST(d / 3  == dollars(5));\n    }\n    {\n        using idollars = money<currency::dollar, int>;\n        idollars d(16);\n        BOOST_TEST(d % 3  == idollars(1));\n    }\n//    {\n//        using CR = std::common_type_t<double,int>;\n//        double d(16);\n//        BOOST_TEST(CR(d) % 3  == 1);\n//    }\n    {\n        dollars d(10);\n        euros e(5);\n        euros x = d + e;\n        std::cout <<x << std::endl;\n        BOOST_TEST(x == euros(25));\n    }\n    {\n        euros e1(5);\n        dollars d(10);\n        euros e2(5);\n        euros x = e1 + d + e2;\n        std::cout <<x << std::endl;\n        BOOST_TEST(x == euros(30));\n    }\n    {\n        dollars d(10);\n        euros e(5);\n        e =  d;\n        BOOST_TEST(e == euros(20));\n    }\n    {\n        dollars d(10);\n        euros e(5);\n        euros x = d - e;\n        std::cout <<x << std::endl;\n        BOOST_TEST(x == euros(15));\n    }\n    {\n        dollars d(10);\n        euros e(5);\n        euros x = d - e;\n        std::cout <<x << std::endl;\n        BOOST_TEST(x == euros(15));\n    }\n    {\n        euros e1(5);\n        dollars d(10);\n        euros e2(5);\n        euros x = e1 - d - e2;\n        std::cout <<x << std::endl;\n        BOOST_TEST(x == euros(-20));\n    }\n    return ::boost::report_errors();\n}\n\n", "meta": {"hexsha": "3522f0ba35c53c0b078e5a63183e96d3784f972b", "size": 8005, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/strong/money3.cpp", "max_stars_repo_name": "jwakely/std-make", "max_stars_repo_head_hexsha": "f09d052983ace70cf371bb8ddf78d4f00330bccd", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 105.0, "max_stars_repo_stars_event_min_datetime": "2015-01-24T13:26:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T15:36:53.000Z", "max_issues_repo_path": "example/strong/money3.cpp", "max_issues_repo_name": "jwakely/std-make", "max_issues_repo_head_hexsha": "f09d052983ace70cf371bb8ddf78d4f00330bccd", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 37.0, "max_issues_repo_issues_event_min_datetime": "2015-09-04T06:57:10.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-09T18:01:44.000Z", "max_forks_repo_path": "example/strong/money3.cpp", "max_forks_repo_name": "jwakely/std-make", "max_forks_repo_head_hexsha": "f09d052983ace70cf371bb8ddf78d4f00330bccd", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 23.0, "max_forks_repo_forks_event_min_datetime": "2015-01-27T11:09:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-04T02:23:30.000Z", "avg_line_length": 25.9902597403, "max_line_length": 120, "alphanum_fraction": 0.580262336, "num_tokens": 2153, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.45985782271378445}}
{"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_long_test.cpp\n * @brief\n * @author Robert Rosolek\n * @version 1.0\n * @date 2013-11-19\n */\n#include \"test_utils/scheduling.hpp\"\n#include \"test_utils/logger.hpp\"\n#include \"test_utils/test_result_check.hpp\"\n\n#include \"paal/utils/irange.hpp\"\n#include \"paal/greedy/scheduling_jobs/scheduling_jobs.hpp\"\n\n#include <boost/test/unit_test.hpp>\n\n#include <vector>\n#include <utility>\n\nBOOST_AUTO_TEST_CASE(testSchedulingJobs) {\n    typedef long long Time;\n    typedef std::pair<int, long long> Machine;\n    typedef Time Job;\n\n    const unsigned seed = 68;\n    const Time optTime = 10000;\n    const long min_machines = 10;\n    const long max_machines = 100000;\n    const long step_machines = 10;\n    const long maxMachineSpeed = 100;\n    const double min_jobs_on_machine_start = 1.0;\n    const double min_jobs_on_machine_end = 5.0;\n    const double min_jobs_on_machine_step = 0.33;\n\n    std::srand(seed);\n    for (int numberOfMachines = min_machines; numberOfMachines <= max_machines;\n         numberOfMachines *= step_machines) {\n        for (double minJobsOnMachine = min_jobs_on_machine_start;\n             minJobsOnMachine < min_jobs_on_machine_end;\n             minJobsOnMachine += min_jobs_on_machine_step) {\n            LOGLN(\"machines: \" << numberOfMachines);\n            std::vector<Machine> machines(numberOfMachines);\n            for (auto machineID : paal::irange(numberOfMachines)) {\n                machines[machineID] =\n                    std::make_pair(machineID, rand() % maxMachineSpeed + 1);\n            }\n            auto getSpeed = [](Machine machine) { return machine.second; };\n\n            std::vector<Job> jobs = generate_job_loads(\n                machines, minJobsOnMachine, optTime, getSpeed);\n            LOGLN(\"jobs: \" << jobs.size());\n\n            typedef std::vector<std::pair<decltype(machines) ::iterator,\n                                          decltype(jobs) ::iterator>> Result;\n            Result resultRandomized, resultDeterministic;\n\n            paal::greedy::schedule_randomized(\n                machines.begin(), machines.end(), jobs.begin(), jobs.end(),\n                back_inserter(resultRandomized), getSpeed,\n                paal::utils::identity_functor());\n            paal::greedy::schedule_deterministic(\n                machines.begin(), machines.end(), jobs.begin(), jobs.end(),\n                back_inserter(resultDeterministic), getSpeed,\n                paal::utils::identity_functor());\n\n            auto checkAndPrint = [&](const Result & result) {\n                check_jobs(result, jobs);\n                double max_time = get_max_time(result, getSpeed);\n                check_result(max_time, double(optTime), 2);\n            };\n\n            checkAndPrint(resultRandomized);\n            checkAndPrint(resultDeterministic);\n        }\n    }\n}\n", "meta": {"hexsha": "278017d54f7c588ec006684222cb981df055f647", "size": 3146, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/greedy/scheduling_jobs_long_test.cpp", "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": "test/greedy/scheduling_jobs_long_test.cpp", "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": "test/greedy/scheduling_jobs_long_test.cpp", "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.4523809524, "max_line_length": 79, "alphanum_fraction": 0.6010807374, "num_tokens": 693, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.45985782271378434}}
{"text": "/*\n *  Distributed under the MIT License (See accompanying file /LICENSE )\n */\n#include \"pgcpp/common_concepts.h\"\n#include \"pgcpp/fractions.hpp\"\n#include <boost/multiprecision/cpp_int.hpp>\n#include <doctest/doctest.h>\n// #include <iostream>\n\nusing namespace fun;\n\nTEST_CASE(\"undefined behavior\")\n{\n    int a = 125;\n    int c = 32;\n    [[maybe_unused]] int b = a >> c; // see if your tool can catch the problem\n    // std::cout << \"125 >> 32 = \" << b << \"\\n\";\n}\n\nTEST_CASE(\"Fraction\")\n{\n    using boost::multiprecision::cpp_int;\n    static_assert(Integral<cpp_int>);\n\n    const auto a = cpp_int {3};\n    const auto b = cpp_int {4};\n    const auto c = cpp_int {5};\n    const auto d = cpp_int {6};\n    const auto f = cpp_int {-30};\n    const auto g = cpp_int {40};\n    const auto z = cpp_int {0};\n    const auto h = cpp_int {-g};\n\n    const auto p = Fraction {a, b};\n    // std::cout << p << '\\n';\n    const auto q = Fraction {c, d};\n\n    CHECK(p == Fraction(30, 40));\n    CHECK(p + q == Fraction(19, 12));\n    CHECK(p - q == Fraction(-1, 12));\n    CHECK(p != 0);\n}\n\nTEST_CASE(\"Fraction Special Cases\")\n{\n    const auto p = Fraction {3, 4};\n    const auto inf = Fraction {1, 0};\n    const auto nan = Fraction {0, 0};\n    const auto zero = Fraction {0, 1};\n\n    CHECK(-inf < zero);\n    CHECK(zero < inf);\n    CHECK(-inf < p);\n    CHECK(p < inf);\n    CHECK(inf == inf);\n    CHECK(-inf < inf);\n    CHECK(inf == inf * p);\n    CHECK(inf == inf * inf);\n    CHECK(inf == p / zero);\n    CHECK(inf == inf / zero);\n    CHECK(nan == nan);\n    CHECK(nan == inf * zero);\n    CHECK(nan == -inf * zero);\n    CHECK(nan == inf / inf);\n    CHECK(nan == nan * zero);\n    CHECK(nan == nan * nan);\n    CHECK(inf == inf + inf);\n    CHECK(nan == inf - inf);\n    // CHECK( inf + p == nan ); // ???\n    // CHECK( -inf + p == nan ); // ???\n}\n", "meta": {"hexsha": "d1900aa153954e8ad37b8237d9c68c866f7a001f", "size": 1813, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/test/src/test_frac.cpp", "max_stars_repo_name": "luk036/pgcpp", "max_stars_repo_head_hexsha": "acef09303ebaa1334b5d30b727d975495e488d4f", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-21T09:08:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T09:08:51.000Z", "max_issues_repo_path": "lib/test/src/test_frac.cpp", "max_issues_repo_name": "luk036/pgcpp", "max_issues_repo_head_hexsha": "acef09303ebaa1334b5d30b727d975495e488d4f", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-07-25T11:01:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-10T13:23:34.000Z", "max_forks_repo_path": "lib/test/src/test_frac.cpp", "max_forks_repo_name": "luk036/pgcpp", "max_forks_repo_head_hexsha": "acef09303ebaa1334b5d30b727d975495e488d4f", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-06-03T08:58:05.000Z", "max_forks_repo_forks_event_max_datetime": "2018-06-03T08:58:05.000Z", "avg_line_length": 25.1805555556, "max_line_length": 78, "alphanum_fraction": 0.5526751241, "num_tokens": 541, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.45985782271378434}}
{"text": "//==================================================================================================\n/*!\n\n  Copyright 2015 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#include <boost/simd/constant/cgold.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/five.hpp>\n#include <boost/simd/as.hpp>\n#include <simd_test.hpp>\n\nSTF_CASE_TPL( \"Check cgold behavior for integral types\"\n            , (std::uint8_t)(std::uint16_t)(std::uint32_t)(std::uint64_t)\n              (std::int8_t)(std::int16_t)(std::int32_t)(std::int64_t)\n            )\n{\n  using boost::simd::as;\n  using boost::simd::detail::cgold;\n  using boost::simd::Cgold;\n\n  STF_TYPE_IS(decltype(Cgold<T>()), T);\n  STF_EQUAL(Cgold<T>(), T(0));\n  STF_EQUAL(cgold( as(T{}) ),T(0));\n}\n\nSTF_CASE_TPL( \"Check cgold behavior for floating types\"\n            , (double)(float)\n            )\n{\n  using boost::simd::as;\n  using boost::simd::detail::cgold;\n  using boost::simd::Cgold;\n\n  STF_TYPE_IS(decltype(Cgold<T>()), T);\n  STF_ULP_EQUAL(Cgold<T>()+T(1), Cgold<T>()*Cgold<T>(), 1);\n  STF_LESS(  Cgold<T>(), T(1));\n  auto z = cgold( as(T{}));\n  STF_ULP_EQUAL((z+T(1)),z*z, 1);\n                                              }\n", "meta": {"hexsha": "ed9b88284772f42976c34175f9348277b6299c97", "size": 1408, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/constant/scalar/cgold.cpp", "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": "test/constant/scalar/cgold.cpp", "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": "test/constant/scalar/cgold.cpp", "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": 32.0, "max_line_length": 100, "alphanum_fraction": 0.5269886364, "num_tokens": 381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.45985782271378434}}
{"text": "/*\n * ConstantNode.cpp\n *\n *  Created on: 2013/06/23\n *      Author: kryozahiro\n */\n\n#include \"ConstantNode.h\"\n\n#include <boost/lexical_cast.hpp>\nusing namespace std;\n\nConstantNode::ConstantNode(pair<double, double> minmax) : minmax(minmax), constant(minmax.first) {\n}\n\nvoid ConstantNode::randomize(const ProgramType& programType, mt19937_64& randomEngine) {\n\tuniform_real_distribution<double> dist(minmax.first, minmax.second);\n\tconstant = dist(randomEngine);\n}\n\ndouble ConstantNode::operator()(const vector<double>& input) {\n\treturn constant;\n}\n\nint ConstantNode::getArity() const {\n\treturn 0;\n}\n\nstring ConstantNode::getName() const {\n\treturn boost::lexical_cast<string>(constant);\n}\n", "meta": {"hexsha": "8033f00acb171fb47512d2d665df473b38603e31", "size": 687, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gamesolver/program/ExpressionTree/ConstantNode.cpp", "max_stars_repo_name": "kryozahiro/gamesolver", "max_stars_repo_head_hexsha": "e5367c292cd9791c1758ac02df226efcb748cd67", "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": "gamesolver/program/ExpressionTree/ConstantNode.cpp", "max_issues_repo_name": "kryozahiro/gamesolver", "max_issues_repo_head_hexsha": "e5367c292cd9791c1758ac02df226efcb748cd67", "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": "gamesolver/program/ExpressionTree/ConstantNode.cpp", "max_forks_repo_name": "kryozahiro/gamesolver", "max_forks_repo_head_hexsha": "e5367c292cd9791c1758ac02df226efcb748cd67", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-10-06T16:06:10.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-06T16:06:10.000Z", "avg_line_length": 21.46875, "max_line_length": 98, "alphanum_fraction": 0.7409024745, "num_tokens": 171, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.45985782271378434}}
{"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#include <iostream>\n\n#include <boost/timer/timer.hpp>\n\n#include \"dune/grid/config.h\"\n#include \"dune/grid/uggrid.hh\"\n\n#include \"fem/gridmanager.hh\"\n#include \"fem/lagrangespace.hh\"\n#include \"timestepping/limexWithoutJens.hh\"\n#include \"utilities/gridGeneration.hh\" //  createUnitSquare\n\nusing namespace Kaskade;\n\n#include \"mygrid.hh\"\n#include \"integrate.hh\"\n#include \"movingsource.hh\"\n\nstruct InitialValue \n{\n  using Scalar = double;\n  static int const components = 1;\n  using ValueType = Dune::FieldVector<Scalar,components>;\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    Dune::FieldVector<typename Cell::ctype,Cell::dimensionworld> x = cell.geometry().global(localCoordinate);\n    x -= 0.5;\n    return 0.0;\n  }\n\nprivate:\n  int component;\n};\n\nint main(int argc, char *argv[])\n  {\n    int const dim = 2;\n    int refinements = 5, order = 2, extrapolOrder = 2, maxSteps = 100,\n      verbosity=1;\n    double dt = 0.1, maxDT = 1.0, T = 1.0, rTolT = 1.0e-3, aTolT = 1.0e-3, rTolX = 2.0e-5, aTolX = 2.0e-5, writeInterval = 1.0;\n\n    std::cout << \"Start moving source tutorial program\" << std::endl;\n\n    using Grid = Dune::UGGrid<dim>;\n    using H1Space = FEFunctionSpace<ContinuousLagrangeMapper<double,Grid::LeafGridView> >;\n    using Spaces = boost::fusion::vector<H1Space const*>;\n    using VariableDescriptions = boost::fusion::vector<VariableDescription<0,1,0> >;\n    using VariableSet = VariableSetDescription<Spaces,VariableDescriptions>;\n    using Equation = MovingSourceEquation<double,VariableSet>;\n\n    GridManager<Grid> gridManager(RefineGrid<Grid>(refinements));\n    std::cout << \"Grid: \" << gridManager.grid().size(0) << \" \" << gridManager.grid().size(1) << \" \" \n              << gridManager.grid().size(2) << std::endl;\n\n  \n// construct involved spaces.\n\n  H1Space temperatureSpace(gridManager,gridManager.grid().leafView(),order);\n\n    Spaces spaces(&temperatureSpace);\n\n    std::string varNames[1] = { \"u\" };\n  \n    VariableSet variableSet(spaces,varNames);\n\n    Equation Eq;\n\n  std::vector<VariableSet::VariableSet> solutions;\n  // std::vector<VariableSet::VariableSet> devnull;\n\n  Eq.time(0);\n  VariableSet::VariableSet x(variableSet);\n  Eq.scaleInitialValue<0>(InitialValue(0),x);\n  \n  x = integrate(gridManager,Eq,variableSet,spaces,\n          dt,maxDT,T,maxSteps,rTolT,aTolT,rTolX,aTolX,extrapolOrder,\n          std::back_inserter(solutions),writeInterval,x,DirectType::SUPERLU,verbosity);\n\n    std::cout << \"End moving source tutorial program\" << std::endl;\n\n  }\n", "meta": {"hexsha": "00c3a52d24e28181c66986bd4a041f7d5edb330a", "size": 3626, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Kaskade/tutorial/instationary_heattransfer/knownsol.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/instationary_heattransfer/knownsol.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:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-09T22:02:36.000Z", "max_forks_repo_path": "Kaskade/tutorial/instationary_heattransfer/knownsol.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": 36.26, "max_line_length": 127, "alphanum_fraction": 0.5785990072, "num_tokens": 953, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.4597726580655984}}
{"text": "// This file is part of Eigen, a lightweight C++ template library\n// for linear algebra.\n//\n// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>\n// Copyright (C) 2009 Benoit Jacob <jacob.benoit.1@gmail.com>\n//\n// Eigen 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 3 of the License, or (at your option) any later version.\n//\n// Alternatively, 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 2 of\n// the License, or (at your option) any later version.\n//\n// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY\n// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License and a copy of the GNU General Public License along with\n// Eigen. If not, see <http://www.gnu.org/licenses/>.\n\n#include \"main.h\"\n#include <Eigen/SVD>\n#include <Eigen/LU>\n\ntemplate<typename MatrixType, unsigned int Options> void svd(const MatrixType& m = MatrixType(), bool pickrandom = true)\n{\n  typedef typename MatrixType::Index Index;\n  Index rows = m.rows();\n  Index cols = m.cols();\n\n  enum {\n    RowsAtCompileTime = MatrixType::RowsAtCompileTime,\n    ColsAtCompileTime = MatrixType::ColsAtCompileTime\n  };\n\n  typedef typename MatrixType::Scalar Scalar;\n  typedef typename NumTraits<Scalar>::Real RealScalar;\n  typedef Matrix<Scalar, RowsAtCompileTime, RowsAtCompileTime> MatrixUType;\n  typedef Matrix<Scalar, ColsAtCompileTime, ColsAtCompileTime> MatrixVType;\n  typedef Matrix<Scalar, RowsAtCompileTime, 1> ColVectorType;\n  typedef Matrix<Scalar, ColsAtCompileTime, 1> InputVectorType;\n\n  MatrixType a;\n  if(pickrandom) a = MatrixType::Random(rows,cols);\n  else a = m;\n\n  JacobiSVD<MatrixType,Options> svd(a);\n  MatrixType sigma = MatrixType::Zero(rows,cols);\n  sigma.diagonal() = svd.singularValues().template cast<Scalar>();\n  MatrixUType u = svd.matrixU();\n  MatrixVType v = svd.matrixV();\n\n  //std::cout << \"a\\n\" << a << std::endl;\n  //std::cout << \"b\\n\" << u * sigma * v.adjoint() << std::endl;\n  \n  VERIFY_IS_APPROX(a, u * sigma * v.adjoint());\n  VERIFY_IS_UNITARY(u);\n  VERIFY_IS_UNITARY(v);\n}\n\ntemplate<typename MatrixType> void svd_verify_assert()\n{\n  MatrixType tmp;\n\n  SVD<MatrixType> svd;\n  //VERIFY_RAISES_ASSERT(svd.solve(tmp, &tmp))\n  VERIFY_RAISES_ASSERT(svd.matrixU())\n  VERIFY_RAISES_ASSERT(svd.singularValues())\n  VERIFY_RAISES_ASSERT(svd.matrixV())\n  /*VERIFY_RAISES_ASSERT(svd.computeUnitaryPositive(&tmp,&tmp))\n  VERIFY_RAISES_ASSERT(svd.computePositiveUnitary(&tmp,&tmp))\n  VERIFY_RAISES_ASSERT(svd.computeRotationScaling(&tmp,&tmp))\n  VERIFY_RAISES_ASSERT(svd.computeScalingRotation(&tmp,&tmp))*/\n}\n\nvoid test_jacobisvd()\n{\n  for(int i = 0; i < g_repeat; i++) {\n    Matrix2cd m;\n    m << 0, 1,\n         0, 1;\n    CALL_SUBTEST_1(( svd<Matrix2cd,0>(m, false) ));\n    m << 1, 0,\n         1, 0;\n    CALL_SUBTEST_1(( svd<Matrix2cd,0>(m, false) ));\n    Matrix2d n;\n    n << 1, 1,\n         1, -1;\n    CALL_SUBTEST_2(( svd<Matrix2d,0>(n, false) ));\n    CALL_SUBTEST_3(( svd<Matrix3f,0>() ));\n    CALL_SUBTEST_4(( svd<Matrix4d,Square>() ));\n    CALL_SUBTEST_5(( svd<Matrix<float,3,5> , AtLeastAsManyColsAsRows>() ));\n    CALL_SUBTEST_6(( svd<Matrix<double,Dynamic,2> , AtLeastAsManyRowsAsCols>(Matrix<double,Dynamic,2>(10,2)) ));\n\n    CALL_SUBTEST_7(( svd<MatrixXf,Square>(MatrixXf(50,50)) ));\n    CALL_SUBTEST_8(( svd<MatrixXcd,AtLeastAsManyRowsAsCols>(MatrixXcd(14,7)) ));\n  }\n  CALL_SUBTEST_9(( svd<MatrixXf,0>(MatrixXf(300,200)) ));\n  CALL_SUBTEST_10(( svd<MatrixXcd,AtLeastAsManyColsAsRows>(MatrixXcd(100,150)) ));\n\n  CALL_SUBTEST_3(( svd_verify_assert<Matrix3f>() ));\n  CALL_SUBTEST_3(( svd_verify_assert<Matrix3d>() ));\n  CALL_SUBTEST_9(( svd_verify_assert<MatrixXf>() ));\n  CALL_SUBTEST_11(( svd_verify_assert<MatrixXd>() ));\n\n  // Test problem size constructors\n  CALL_SUBTEST_12( JacobiSVD<MatrixXf>(10, 20) );\n}\n", "meta": {"hexsha": "24dbc22a503bb8cbda6bb4b8df52dcd6a60e961b", "size": 4221, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "t1m1/include/eigen/test/jacobisvd.cpp", "max_stars_repo_name": "dailysoap/CSMM.104x", "max_stars_repo_head_hexsha": "4515b30ab5f60827a9011b23ef155a3063584a9d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2017-04-01T17:18:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T05:23:23.000Z", "max_issues_repo_path": "t1m1/include/eigen/test/jacobisvd.cpp", "max_issues_repo_name": "dailysoap/CSMM.104x", "max_issues_repo_head_hexsha": "4515b30ab5f60827a9011b23ef155a3063584a9d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-05-24T13:36:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-15T06:44:20.000Z", "max_forks_repo_path": "t1m1/include/eigen/test/jacobisvd.cpp", "max_forks_repo_name": "dailysoap/CSMM.104x", "max_forks_repo_head_hexsha": "4515b30ab5f60827a9011b23ef155a3063584a9d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-09-20T01:07:39.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-22T14:55:38.000Z", "avg_line_length": 37.0263157895, "max_line_length": 120, "alphanum_fraction": 0.715233357, "num_tokens": 1242, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.7217432122827967, "lm_q1q2_score": 0.4597726519313339}}
{"text": "/*\n * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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#define BOOST_TEST_MAIN\n\n#define BOOST_TEST_MODULE fourcenter_test\n\n// Third party includes\n#include <boost/test/unit_test.hpp>\n\n#include <votca/tools/eigenio_matrixmarket.h>\n\n// Local VOTCA includes\n#include \"votca/xtp/aobasis.h\"\n#include \"votca/xtp/fourcenter.h\"\n#include \"votca/xtp/qmmolecule.h\"\n\nusing namespace votca::xtp;\nusing namespace votca;\nusing namespace std;\n\nBOOST_AUTO_TEST_SUITE(fourcenter_test)\n\nBOOST_AUTO_TEST_CASE(small_l_test) {\n\n  QMMolecule mol(\" \", 0);\n  mol.LoadFromFile(std::string(XTP_TEST_DATA_FOLDER) +\n                   \"/fourcenter/molecule.xyz\");\n\n  BasisSet basis;\n  basis.Load(std::string(XTP_TEST_DATA_FOLDER) + \"/fourcenter/3-21G.xml\");\n  AOBasis aobasis;\n  aobasis.Fill(basis, mol);\n\n  const AOShell& shell0 = aobasis.getShell(2);\n  const AOShell& shell1 = aobasis.getShell(3);\n  const AOShell& shell2 = aobasis.getShell(4);\n  const AOShell& shell4 = aobasis.getShell(5);\n  FCMatrix fcenter;\n  Eigen::Tensor<double, 4> block(shell0.getNumFunc(), shell4.getNumFunc(),\n                                 shell2.getNumFunc(), shell1.getNumFunc());\n  block.setZero();\n  fcenter.FillFourCenterRepBlock(block, shell0, shell4, shell2, shell1);\n\n  Eigen::Map<Eigen::VectorXd> mapped_result(block.data(), block.size());\n  Eigen::VectorXd ref = Eigen::VectorXd::Zero(block.size());\n  ref << 0.021578, 0.0112696, 0.0112696, 0.0112696, 0.021578, 0.0112696,\n      0.0112696, 0.0112696, 0.021578;\n  Eigen::TensorMap<Eigen::Tensor<double, 4> > ref_block(\n      ref.data(), shell0.getNumFunc(), shell4.getNumFunc(), shell2.getNumFunc(),\n      shell1.getNumFunc());\n\n  bool check = mapped_result.isApprox(ref, 0.0001);\n  BOOST_CHECK_EQUAL(check, 1);\n  if (!check) {\n    cout << \"ref\" << endl;\n    cout << ref_block << endl;\n    cout << \"result\" << endl;\n    cout << block << endl;\n  }\n}\n\nBOOST_AUTO_TEST_CASE(large_l_test) {\n\n  QMMolecule mol(\"C\", 0);\n  mol.LoadFromFile(std::string(XTP_TEST_DATA_FOLDER) + \"/fourcenter/C2.xyz\");\n\n  BasisSet basisset;\n  basisset.Load(std::string(XTP_TEST_DATA_FOLDER) + \"/fourcenter/G.xml\");\n\n  AOBasis dftbasis;\n  dftbasis.Fill(basisset, mol);\n\n  FCMatrix fcenter;\n  Eigen::Tensor<double, 4> block(\n      dftbasis.getShell(0).getNumFunc(), dftbasis.getShell(1).getNumFunc(),\n      dftbasis.getShell(0).getNumFunc(), dftbasis.getShell(1).getNumFunc());\n  block.setZero();\n  fcenter.FillFourCenterRepBlock(block, dftbasis.getShell(0),\n                                 dftbasis.getShell(1), dftbasis.getShell(0),\n                                 dftbasis.getShell(1));\n  // we only check the first and last 600 values because this gets silly quite\n  // quickly\n  Eigen::Map<Eigen::VectorXd> mapped_result(block.data(), block.size());\n  Eigen::VectorXd ref_head = votca::tools::EigenIO_MatrixMarket::ReadVector(\n      std::string(XTP_TEST_DATA_FOLDER) + \"/fourcenter/largeLbegin.mm\");\n\n  Eigen::VectorXd ref_tail = votca::tools::EigenIO_MatrixMarket::ReadVector(\n      std::string(XTP_TEST_DATA_FOLDER) + \"/fourcenter/largeLend.mm\");\n\n  bool check_head = mapped_result.head<600>().isApprox(ref_head, 0.0001);\n  BOOST_CHECK_EQUAL(check_head, 1);\n  if (!check_head) {\n    cout << \"ref\" << endl;\n    cout << ref_head.transpose() << endl;\n    cout << \"result\" << endl;\n    cout << mapped_result.head<600>().transpose() << endl;\n  }\n\n  bool check_tail = mapped_result.tail<600>().isApprox(ref_tail, 0.0001);\n  BOOST_CHECK_EQUAL(check_tail, 1);\n  if (!check_tail) {\n    cout << \"ref\" << endl;\n    cout << ref_tail.transpose() << endl;\n    cout << \"result\" << endl;\n    cout << mapped_result.tail<600>().transpose() << endl;\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "6b17cc122147f60cc020310c3574872aef7425e4", "size": 4201, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/tests/test_fourcenter.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/tests/test_fourcenter.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/tests/test_fourcenter.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.1544715447, "max_line_length": 80, "alphanum_fraction": 0.6898357534, "num_tokens": 1155, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432182679957, "lm_q2_score": 0.6370307875894139, "lm_q1q2_score": 0.45977265077057955}}
{"text": "/*\n@copyright Louis Dionne 2014\nDistributed under the Boost Software License, Version 1.0.\n(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n */\n\n#include <boost/hana/detail/assert.hpp>\n#include <boost/hana/detail/constexpr.hpp>\n#include <boost/hana/ext/std/integral_constant.hpp>\n#include <boost/hana/functional.hpp>\n#include <boost/hana/integer_list.hpp>\n#include <boost/hana/integral.hpp>\n#include <boost/hana/type.hpp>\n#include <boost/hana/type_list.hpp>\n\n#include <type_traits>\nusing namespace boost::hana;\nusing namespace literals;\n\n\nint main() {\n    //! [main]\n    BOOST_HANA_CONSTEXPR_LAMBDA auto odd = [](auto x) {\n        return x % 2_c != 0_c;\n    };\n\n    constexpr auto types = type_list<int, char, long, short, char, double>;\n    constexpr auto ints = integer_list<int, 1, 2, 3>;\n\n    BOOST_HANA_CONSTANT_ASSERT(count(ints, odd) == 2_c);\n\n    BOOST_HANA_CONSTANT_ASSERT(count(types, trait<std::is_floating_point>) == 1_c);\n    BOOST_HANA_CONSTANT_ASSERT(count(types, _ == type<char>) == 2_c);\n    BOOST_HANA_CONSTANT_ASSERT(count(types, _ == type<void>) == 0_c);\n    //! [main]\n}\n", "meta": {"hexsha": "5b9053ec250ff6556eef8bb17921a2f0bc1a8ca1", "size": 1122, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/foldable/count.cpp", "max_stars_repo_name": "rbock/hana", "max_stars_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-05-07T14:29:13.000Z", "max_stars_repo_stars_event_max_datetime": "2015-07-04T10:59:46.000Z", "max_issues_repo_path": "example/foldable/count.cpp", "max_issues_repo_name": "rbock/hana", "max_issues_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/foldable/count.cpp", "max_forks_repo_name": "rbock/hana", "max_forks_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3243243243, "max_line_length": 83, "alphanum_fraction": 0.7112299465, "num_tokens": 296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7217432182679956, "lm_q2_score": 0.6370307875894139, "lm_q1q2_score": 0.4597726507705795}}
{"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 *      130301    D. Dirkx          Migrated from personal code.\n *      130308    E.D. Brandon      Minor changes.\n *\n *    References\n *      Montebruck O, Gill E. Satellite Orbits, Springer, 2000.\n *\n *    Notes\n *\n */\n\n#define BOOST_TEST_MAIN\n\n#include <boost/format.hpp>\n#include <boost/test/unit_test.hpp>\n\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/unitConversions.h\"\n#include \"Tudat/Basics/testMacros.h\"\n\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/geodeticCoordinateConversions.h\"\n\nnamespace tudat\n{\nnamespace unit_tests\n{\n\nBOOST_AUTO_TEST_SUITE( test_geodetic_coordinate_conversions )\n\nBOOST_AUTO_TEST_CASE( testGeodeticCoordinateConversions )\n{\n    using namespace coordinate_conversions;\n    using namespace unit_conversions;\n\n    // Expected Cartesian state, Montenbruck & Gill (2000) Exercise 5.3.\n    const Eigen::Vector3d testCartesianPosition( 1917032.190, 6029782.349, -801376.113 );\n\n    // Expected Cartesian state, Montenbruck & Gill (2000) Exercise 5.3.\n    const Eigen::Vector3d testGeodeticPosition( -63.667,\n                                                convertDegreesToRadians( -7.26654999 ),\n                                                convertDegreesToRadians( 72.36312094 ) );\n\n    // Central body characteristics (WGS84 Earth ellipsoid).\n    const double flattening = 1.0 / 298.257223563;\n    const double equatorialRadius = 6378137.0;\n\n    // Test conversion to geodetic coordinates.\n    {\n        // Calculate geodetic position.\n        const Eigen::Vector3d calculatedGeodeticPosition =\n                convertCartesianToGeodeticCoordinates(\n                    testCartesianPosition, equatorialRadius, flattening, 1.0E-4 );\n\n        // Compare per coefficients (different tolerances).\n        BOOST_CHECK_SMALL( calculatedGeodeticPosition.x( ) - testGeodeticPosition.x( ), 1.0E-4 );\n        BOOST_CHECK_SMALL( calculatedGeodeticPosition.y( ) - testGeodeticPosition.y( ), 1.0E-10 );\n        BOOST_CHECK_SMALL( calculatedGeodeticPosition.z( ) - testGeodeticPosition.z( ), 1.0E-10 );\n    }\n\n    // Test separate functions for altitude and geodetic latitude.\n    {\n        // Calculate altitude and geodetic latitude using dedicated functions.\n        const double directAltitude = calculateAltitudeOverOblateSpheroid(\n                    testCartesianPosition, equatorialRadius, flattening, 1.0E-4 );\n        const double directGeodeticLatitude = calculateGeodeticLatitude(\n                    testCartesianPosition, equatorialRadius, flattening, 1.0E-4 );\n\n        // Compare values.\n        BOOST_CHECK_SMALL( directAltitude - testGeodeticPosition.x( ), 1.0E-4 );\n        BOOST_CHECK_SMALL( directGeodeticLatitude - testGeodeticPosition.y( ), 1.0E-10 );\n    }\n\n    // Test conversions from geodetic coordinates to cartesian position.\n    {\n        const Eigen::Vector3d calculateCartesianPosition =\n                convertGeodeticToCartesianCoordinates(\n                    testGeodeticPosition, equatorialRadius, flattening  );\n\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION(\n                    calculateCartesianPosition, testCartesianPosition, 1.0E-9 );\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END( )\n\n} // namespace unit_tests\n} // namespace tudat\n", "meta": {"hexsha": "0ff9673909b5a9acc5b6a2206737aef387f99dc9", "size": 4922, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/BasicAstrodynamics/UnitTests/unitTestGeodeticCoordinateConversions.cpp", "max_stars_repo_name": "JPelamatti/ThesisTUDAT", "max_stars_repo_head_hexsha": "b94ce35fb7c8fa44ae83238e296a979dfa3adfe8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tudat/Astrodynamics/BasicAstrodynamics/UnitTests/unitTestGeodeticCoordinateConversions.cpp", "max_issues_repo_name": "JPelamatti/ThesisTUDAT", "max_issues_repo_head_hexsha": "b94ce35fb7c8fa44ae83238e296a979dfa3adfe8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tudat/Astrodynamics/BasicAstrodynamics/UnitTests/unitTestGeodeticCoordinateConversions.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.9464285714, "max_line_length": 99, "alphanum_fraction": 0.7019504267, "num_tokens": 1134, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.4597726381715572}}
{"text": "#ifndef __FOLDING_UTILS__\n#define __FOLDING_UTILS__\n\n#include <math.h>\n#include <ros/ros.h>\n#include <Eigen/Dense>\n#include <stdexcept>\n\nnamespace generic_control_toolbox\n{\nclass MatrixParser\n{\n public:\n  MatrixParser();\n  ~MatrixParser();\n\n  /**\n    Initialize a nxn matrix with values obtained from the ros parameter\n    server.\n\n    @param M The matrix to be initialized\n    @param param_name The parameter server location\n    @param n The ros nodehandle used to query the parameter server\n\n    @throw logic_error in case vals does not have square dimensions.\n    @return True for success, False if parameter is not available.\n  **/\n  static bool parseMatrixData(Eigen::MatrixXd &M, const std::string param_name,\n                              const ros::NodeHandle &n);\n\n  /**\n    Computed the skew-symmetric matrix of a 3-dimensional vector.\n\n    @param v The 3-dimensional vector\n    @return The skew-symmetric matrix\n  **/\n  static Eigen::Matrix3d computeSkewSymmetric(const Eigen::Vector3d &v);\n\n private:\n  /**\n    Fill in a nxn matrix with the given values.\n\n    @param M The matrix to be filled in. Will be set to the size nxn.\n    @param vals A vector with the values to fill in\n    @throw logic_error in case vals does not have square dimensions.\n  **/\n  static void initializeEigenMatrix(Eigen::MatrixXd &M,\n                                    const std::vector<double> &vals);\n};\n}  // namespace generic_control_toolbox\n\n#endif\n", "meta": {"hexsha": "b428c4138ff27a774861f563c3cc5cb81162a52a", "size": 1442, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/generic_control_toolbox/matrix_parser.hpp", "max_stars_repo_name": "RaduCorcodel/generic_control_toolbox", "max_stars_repo_head_hexsha": "7702521c2a4452e9d7207642e95f21dbcbf76e00", "max_stars_repo_licenses": ["MIT"], "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/generic_control_toolbox/matrix_parser.hpp", "max_issues_repo_name": "RaduCorcodel/generic_control_toolbox", "max_issues_repo_head_hexsha": "7702521c2a4452e9d7207642e95f21dbcbf76e00", "max_issues_repo_licenses": ["MIT"], "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/generic_control_toolbox/matrix_parser.hpp", "max_forks_repo_name": "RaduCorcodel/generic_control_toolbox", "max_forks_repo_head_hexsha": "7702521c2a4452e9d7207642e95f21dbcbf76e00", "max_forks_repo_licenses": ["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.2075471698, "max_line_length": 79, "alphanum_fraction": 0.6955617198, "num_tokens": 330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.4597726381715572}}
{"text": "#include <limits>\n#include <vector>\n#include <unordered_map>\n\n#include \"controllers/sfm_aligner.h\"\n#include \"estimators/similarity_transform.h\"\n#include \"estimators/ransac_similarity.h\"\n#include \"estimators/sim3.h\"\n#include \"optim/bundle_adjustment.h\"\n#include \"util/timer.h\"\n#include \"math/util.h\"\n\n#include <glog/logging.h>\n#include <Eigen/Geometry>\n#include <ceres/rotation.h>\n\nnamespace GraphSfM {\n\ndouble MeanReprojectionResiduals(const std::vector<double>& residuals)\n{\n    double mean_residual = 0.0;\n    for (auto residual : residuals) {\n        mean_residual += residual;\n    }\n    return mean_residual / residuals.size();\n}\n\nstd::vector<double> ComputeReprojectionResiduals(const std::vector<Eigen::Vector3d>& src_points,\n                                    const std::vector<Eigen::Vector3d>& ref_points,\n                                    const Eigen::Matrix3x4d& alignment)\n{\n    std::vector<double> residuals;\n    for (uint i = 0; i < src_points.size(); i++) {\n        const Eigen::Vector3d& tsrc_point = alignment * src_points[i].homogeneous();\n        const Eigen::Vector3d& ref_point = ref_points[i];\n\n        double residual = (tsrc_point - ref_point).norm();\n        residuals.push_back(residual);\n    }\n    return residuals;\n}\n\nSfMAligner::SfMAligner(const std::vector<Reconstruction*>& reconstructions,\n                       const BundleAdjustmentOptions& ba_options)\n     : reconstructions_(reconstructions),\n       ba_options_(ba_options)\n{\n    // some logic or parameters check\n    CHECK_GT(reconstructions.size(), 0);\n    CHECK_GT(reconstructions_.size(), 0);\n\n    for (uint i = 0; i < reconstructions_.size(); i++) {\n        LOG(INFO) << \"Node id: \" << i;\n        CHECK_NOTNULL(reconstructions_[i]);\n        LOG(INFO) << \"Total images number: \" << reconstructions_[i]->NumImages();\n    }\n}\n\nbool SfMAligner::Align()\n{\n    // 1. Constructing a graph from reconstructions,\n    // each node is a reconstruction, edges represents the connections between \n    // reconstructions (by the means of common images or common 3D points), the weight\n    // of edge represents the mean reprojection error.\n    LOG(INFO) << \"Constructing Reconstructions Graph...\";\n    ConstructReconsGraph();\n    recons_graph_.ShowInfo();\n    CHECK_EQ(recons_graph_.GetNodesNum(), reconstructions_.size());\n\n    // The reconstruction graph should be at least a spanning tree,\n    // or we couldn't stitch all reconstructions together due to \n    // too large alignment error or disconnected components.\n    if (recons_graph_.GetEdgesNum() < recons_graph_.GetNodesNum() - 1) {\n        LOG(ERROR) << \"Can't align all reconstructions together due to \"\n                   << \"too large alignment error or disconnected components\";\n        return false;\n    }\n\n    // 2. Constructing a minimum spanning tree, thus we can select the\n    // most accurate n - 1 edges for accurate alignment.\n    LOG(INFO) << \"Finding Minimum Spanning Tree...\";\n    std::vector<Edge> mst_edges = recons_graph_.Kruskal();\n    if (mst_edges.size() < recons_graph_.GetNodesNum() - 1) {\n        return false;\n    }\n\n    Graph<Node, Edge> mst;\n    for (auto node : recons_graph_.GetNodes()) {\n        mst.AddNode(node.second);\n    }\n    for (const auto edge : mst_edges) {\n        mst.AddEdge(edge);\n    }\n    mst.ShowInfo();\n\n    // 3. Finding an anchor node, an anchor node is a reference reconstruction \n    // that all other reconstructions should be aligned to.\n    LOG(INFO) << \"Finding Anchor Node...\";\n    FindAnchorNode(&mst);\n\n    // 4. Compute the final transformation to anchor node for each cluster\n    LOG(INFO) << \"Computing Final Similarity Transformations...\";\n    for (uint i = 0; i < reconstructions_.size(); i++) {\n        if (i != anchor_node_.id) {\n            this->ComputePath(i, anchor_node_.id);\n        }\n    }\n    sim3_to_anchor_[anchor_node_.id] = Sim3();\n\n    // 5. Merging all other reconstructions to anchor node\n    LOG(INFO) << \"Merging Reconstructions...\";\n    this->MergeReconstructions();\n\n    // 6. Final Bundle Adjustment\n    LOG(INFO) << \"Final Global Bundle Adjustment\";\n    this->AdjustGlobalBundle();\n\n    return true;\n}\n\nNode SfMAligner::GetAnchorNode() const\n{\n    return anchor_node_;\n}\n\nstd::vector<Sim3> SfMAligner::GetSim3ToAnchor() const\n{\n    return sim3_to_anchor_;\n}\n\nvoid SfMAligner::ConstructReconsGraph()\n{\n    // 1. Add nodes\n    for (size_t i = 0; i < reconstructions_.size(); i++) {\n        Node node(i);\n        // node.recon = reconstructions_[i];\n        recons_graph_.AddNode(node);\n    }\n\n    // 2. Add edges\n    for (uint i = 0; i < reconstructions_.size(); i++) {\n        for (uint j = i + 1; j < reconstructions_.size(); j++) {\n            const double weight = ComputeEdgeWeight(i, j);\n            LOG(INFO) << \"weight: \" << weight;\n            if (weight != std::numeric_limits<double>::max()) {\n                recons_graph_.AddEdge(Edge(i, j, (float)weight));\n            }\n        }\n    }\n}\n\ndouble SfMAligner::ComputeEdgeWeight(const uint i, const uint j)\n{\n    const Reconstruction& recon1 = *reconstructions_[i];\n    const Reconstruction& recon2 = *reconstructions_[j];\n    double weight = std::numeric_limits<double>::max();\n\n    Eigen::Matrix3d R1 = Eigen::Matrix3d::Identity(3, 3), \n                    R2 = Eigen::Matrix3d::Identity(3, 3);\n    Eigen::Vector3d t1 = Eigen::Vector3d::Zero(),\n                    t2 = Eigen::Vector3d::Zero();\n    double s1 = 1.0, s2 = 1.0;\n\n    // Find common registered images\n    std::vector<image_t> common_reg_images = recon1.FindCommonRegImageIds(recon2);\n    std::vector<Eigen::Vector3d> src_points, ref_points;\n    std::vector<Eigen::Matrix3d> src_rotations, ref_rotations;\n    for (const auto common_id : common_reg_images) {\n        src_points.push_back(recon1.Image(common_id).ProjectionCenter());\n        src_rotations.push_back(recon1.Image(common_id).RotationMatrix());\n        ref_points.push_back(recon2.Image(common_id).ProjectionCenter());\n        ref_rotations.push_back(recon2.Image(common_id).RotationMatrix());\n    }\n    LOG(INFO) << \"Common registerd images number: \" << common_reg_images.size();\n\n    if (common_reg_images.size() < 2) {\n        LOG(WARNING) << \"Not found enough common registered images.\";\n        return std::numeric_limits<double>::max();\n    } else if (common_reg_images.size() < 5) {\n        ComputeSimilarityByCameraMotions(src_points, ref_points, \n                                         src_rotations, ref_rotations, R1, t1, s1);\n        ComputeSimilarityByCameraMotions(ref_points, src_points, \n                                         ref_rotations, src_rotations, R2, t2, s2);\n            \n        double msd1 = CheckReprojError(src_points, ref_points, s1, R1, t1),\n               msd2 = CheckReprojError(ref_points, src_points, s2, R2, t2);\n\n        // angular residual should be considered\n        const double angular_residual1 = \n            CheckAngularResidual(src_rotations, ref_rotations, R1);\n        const double angular_residual2 = \n            CheckAngularResidual(ref_rotations, src_rotations, R2);\n\n        weight = std::max(std::max(msd1, msd2), \n                          std::max(angular_residual1, angular_residual2));\n\n        if (weight != numeric_limits<double>::max()) {\n            sim3_graph_[i][j] = Sim3(R1, t1, s1);\n            sim3_graph_[j][i] = Sim3(R2, t2, s2);\n        }\n    } else {\n        double msd1 = 0.0, msd2 = 0.0;\n        FindSimilarityTransform(src_points, ref_points, R1, t1, s1, msd1);\n        FindSimilarityTransform(ref_points, src_points, R2, t2, s2, msd2);\n\n        // angular residual should be considered\n        const double angular_residual1 = \n            CheckAngularResidual(src_rotations, ref_rotations, R1);\n        const double angular_residual2 = \n            CheckAngularResidual(ref_rotations, src_rotations, R2);\n\n        weight = std::max(std::max(msd1, msd2), \n                          std::max(angular_residual1, angular_residual2));\n\n        if (weight != numeric_limits<double>::max()) {\n            sim3_graph_[i][j] = Sim3(R1, t1, s1);\n            sim3_graph_[j][i] = Sim3(R2, t2, s2);\n        }\n    }\n\n    return weight;\n}\n\nvoid SfMAligner::FindAnchorNode(Graph<Node, Edge>* graph)\n{\n    paths_.resize(recons_graph_.GetNodesNum());\n    sim3_to_anchor_.resize(recons_graph_.GetNodesNum());\n\n    // The anchor is found by merging all leaf nodes to their adjacent nodes, \n    // until one node or two nodes left. If two nodes left, we choose the reconstruction \n    // that has the largest size as the anchor.\n    int layer = 1;\n    uint anchor_index = 0;\n\n    while (graph->GetNodesNum() > 1) {\n        LOG(INFO) << \"Merging the \" << layer++ << \"-th layer leaf nodes\";\n\n        graph->CountOutDegrees();\n        graph->CountInDegrees();\n        graph->CountDegrees();\n        std::unordered_map<size_t, size_t> degrees = graph->GetDegrees();\n\n        // Finding all leaf nodes. Leaf node in graph has degree equals to 1.\n        std::vector<int> indexes;\n        if (graph->GetNodesNum() == 2) {\n            indexes.push_back(degrees.begin()->first);\n        } else {\n            for (auto it = degrees.begin(); it != degrees.end(); ++it) {\n                LOG(INFO) << \"node: \" << it->first << \", \"\n                          << \"degree: \" << it->second;\n                if (it->second == 1) indexes.push_back(it->first);\n            }\n        }\n        if (indexes.empty()) break;\n\n        for (auto idx : indexes) {\n            if (idx == -1) break;\n            const Edge& edge = graph->FindConnectedEdge(idx);\n\n            LOG(INFO) << \"Find node [degree = 1]: \" << idx;\n            LOG(INFO) << edge.src << \"->\" << edge.dst << \": \" << edge.weight;\n\n            // src is the node with degree = 1\n            uint src = (idx == edge.src) ? edge.src : edge.dst;\n            uint dst = (idx == edge.src) ? edge.dst : edge.src;\n            Reconstruction* src_recon = reconstructions_[src];\n            Reconstruction* dst_recon = reconstructions_[dst];\n\n            LOG(INFO) << \"Merge Clusters: \" << src << \"->\" << dst << \": \" << edge.weight;\n            anchor_index = dst;\n            const Sim3 sim = sim3_graph_[src][dst];\n            paths_[src].insert(std::make_pair(dst, sim));\n\n            graph->DeleteNode(src);\n            graph->DeleteEdge(src, dst);\n            graph->DeleteEdge(dst, src);\n            graph->ShowInfo();\n        }\n    }\n\n    anchor_node_.id = anchor_index;\n}\n\nvoid SfMAligner::ComputePath(int src, int dst)\n{\n    LOG(INFO) << \"Computing Path: \" << src << \"->\" << dst;\n    std::queue<int> qu;\n    qu.push(src);\n\n    Eigen::Matrix3d r = Eigen::Matrix3d::Identity();\n    Eigen::Vector3d t = Eigen::Vector3d::Zero();\n    double s = 1.0;\n\n    Sim3 sim(Eigen::Matrix3d::Identity(), Eigen::Vector3d::Identity(), 1.0);\n    LOG(INFO) << \"v: \" << src;\n    while (!qu.empty()) {\n        int u = qu.front(); qu.pop();\n        auto it = paths_[u].begin();\n        int v = it->first;\n        LOG(INFO) << \"v: \" << v;\n        s = it->second.s * s;\n        r = it->second.R * r.eval();\n        t = it->second.s * it->second.R * t.eval() + it->second.t;\n        if (v == dst) {\n            sim.s = s; sim.R = r; sim.t = t;\n            sim3_to_anchor_[src] = sim;\n            return;\n        }\n        else qu.push(v);\n    }\n    LOG(INFO) << \"\\n\";\n}\n\nvoid SfMAligner::MergeReconstructions()\n{\n    for (uint i = 0; i < reconstructions_.size(); i++) {\n        if (i == anchor_node_.id) { continue; }\n\n        Sim3 sim3 = sim3_to_anchor_[i];\n        Eigen::Matrix3x4d alignment;\n        alignment.block(0, 0, 3, 3) = sim3.s * sim3.R;\n        alignment.block(0, 3, 3, 1) = sim3.t;\n\n        reconstructions_[anchor_node_.id]->Merge(*reconstructions_[i],\n                                                 alignment);\n    }\n}\n\nbool SfMAligner::AdjustGlobalBundle()\n{\n    Reconstruction* final_recon = reconstructions_[anchor_node_.id];\n    CHECK_NOTNULL(final_recon);\n\n    const std::vector<image_t>& reg_image_ids = final_recon->RegImageIds();\n\n    CHECK_GE(reg_image_ids.size(), 2) << \"At least two images must be \"\n                                         \"registered for global bundle-adjustment\";\n    \n    // Avoid degeneracies in bundle adjustment.\n    final_recon->FilterObservationsWithNegativeDepth();\n\n    // Configure bundle adjustment\n    BundleAdjustmentConfig ba_config;\n    for (const image_t image_id : reg_image_ids) {\n        ba_config.AddImage(image_id);\n    }\n\n    // Fix 7-DOFs of the bundle adjustment problem.\n    ba_config.SetConstantPose(reg_image_ids[0]);\n    ba_config.SetConstantTvec(reg_image_ids[1], {0});\n\n    // Run bundle adjustment.\n    BundleAdjuster bundle_adjuster(ba_options_, ba_config);\n    if (!bundle_adjuster.Solve(final_recon)) {\n        return false;\n    }\n\n    // Normalize scene for numerical stability and\n    // to avoid large scale changes in viewer.\n    final_recon->Normalize();\n\n    return true;\n}\n\nvoid FindSimilarityTransform(const std::vector<Eigen::Vector3d>& observations1,\n                             const std::vector<Eigen::Vector3d>& observations2,\n                             Eigen::Matrix3d& R,\n                             Eigen::Vector3d& t,\n                             double& scale,\n                             double& msd)\n{\n    std::vector<Eigen::Vector3d> inliers1, inliers2;\n    double threshold = 0.1; // TODO: (chenyu) make this parameter an user option\n    double p = 0.99;\n\n    if (observations1.size() > 5) {\n        LOG(INFO) << \"Finding Similarity by RANSAC\";\n        RansacSimilarity(observations1, observations2, inliers1, inliers2, R, t, scale, threshold, p);\n        VLOG(2) << \"inliers size: \" << inliers1.size();\n        // Re-compute similarity by inliers\n        Eigen::MatrixXd x1 = Eigen::MatrixXd::Zero(3, inliers1.size()),\n                        x2 = Eigen::MatrixXd::Zero(3, inliers2.size());\n        for(int i = 0; i < inliers1.size(); i++) {\n            x1.col(i) = inliers1[i];\n            x2.col(i) = inliers2[i];\n        }\n        GraphSfM::FindRTS(x1, x2, &scale, &t, &R);\n        // Optional non-linear refinement of the found parameters\n        GraphSfM::Refine_RTS(x1, x2, &scale, &t, &R);\n\n        if (inliers1.size() < 4) { msd = numeric_limits<double>::max(); return; }\n        // else msd = CheckReprojError(inliers1, inliers2, scale, R, t);\n    }\n\n    if (observations1.size() <= 5 || inliers1.size() <= 5) {\n        Eigen::MatrixXd x1 = Eigen::MatrixXd::Zero(3, observations1.size()),\n                        x2 = Eigen::MatrixXd::Zero(3, observations2.size());\n        for (int i = 0; i < observations1.size(); i++) {\n            x1.col(i) = observations1[i];\n            x2.col(i) = observations2[i];\n        }\n        GraphSfM::FindRTS(x1, x2, &scale, &t, &R);\n        GraphSfM::Refine_RTS(x1, x2, &scale, &t, &R);\n        \n        // msd = CheckReprojError(observations1, observations2, scale, R, t);\n    }\n\n    msd = CheckReprojError(observations1, observations2, scale, R, t);\n\n    // LOG(INFO) << \"scale: \" << scale;\n    // LOG(INFO) << \"rotation: \";\n    // LOG(INFO) << R(0, 0) << \" \" << R(0, 1) << \" \" << R(0, 2);\n    // LOG(INFO) << R(1, 0) << \" \" << R(1, 1) << \" \" << R(1, 2);\n    // LOG(INFO) << R(2, 0) << \" \" << R(2, 1) << \" \" << R(2, 2);\n    // LOG(INFO) << \"translation: \" << t[0] << \", \" << t[1] << \", \" << t[2];\n}\n\ndouble CheckReprojError(const vector<Eigen::Vector3d>& src_observations,\n                        const vector<Eigen::Vector3d>& dst_observations,\n                        const double& scale,\n                        const Eigen::Matrix3d& R,\n                        const Eigen::Vector3d& t)\n{\n    double reproj_err = 0.0;\n    const int size = src_observations.size();\n    for (int i = 0; i < size; i++) {\n        Eigen::Vector3d reproj_obv = scale * R * src_observations[i] + t;\n        reproj_err += (reproj_obv - dst_observations[i]).norm();\n    }\n\n    LOG(INFO) << \"Mean Reprojection Error: \" << reproj_err / size\n              << \" (\" << reproj_err << \"/\" \n              << size << \")\";\n    return reproj_err / size;\n}\n\ndouble CheckAngularResidual(const std::vector<Eigen::Matrix3d>& src_rotations,\n                           const std::vector<Eigen::Matrix3d>& dst_rotations,\n                           const Eigen::Matrix3d& R)\n{\n    double angular_residual = 0.0;\n    const int n = src_rotations.size();\n    for (uint i = 0; i < n; i++) {\n        Eigen::Matrix3d rel_rotation = \n            dst_rotations[i].transpose() * src_rotations[i] * R.transpose();\n        Eigen::Vector3d angle_axis;\n        ceres::RotationMatrixToAngleAxis(rel_rotation.data(), angle_axis.data());\n        angular_residual += RadToDeg(angle_axis.norm());\n    }\n\n    angular_residual /= n;\n    LOG(INFO) << \"Average Angular Residual: \" << angular_residual << \" degree.\";\n    return angular_residual;\n}\n\nbool ComputeSimilarityByCameraMotions(\n    std::vector<Eigen::Vector3d>& camera_centers1,\n    std::vector<Eigen::Vector3d>& camera_centers2,\n    std::vector<Eigen::Matrix3d>& camera_rotations1,\n    std::vector<Eigen::Matrix3d>& camera_rotations2,\n    Eigen::Matrix3d& relative_r,\n    Eigen::Vector3d& relative_t,\n    double& scale)\n{\n    // my hybrid approach by combining \"Divide and Conquer: Efficient Large-Scale\n    // Structure from Motion Using Graph Partitioning\" and RANSAC\n\n    const int n = camera_centers1.size();\n    std::vector<Eigen::Vector3d> ts1(n);\n    std::vector<Eigen::Vector3d> ts2(n);\n\n    for (uint i = 0; i < n; i++) {\n        ts1[i] = -camera_rotations1[i] * camera_centers1[i];\n        ts2[i] = -camera_rotations2[i] * camera_centers2[i];\n    }\n\n    // compute relative scale from a->b\n    std::vector<double> scales;\n    for (int i = 0; i < n; i++) {\n        Eigen::Vector3d center_a1 = camera_centers1[i];\n        Eigen::Vector3d center_b1 = camera_centers2[i];\n        for (int j = i + 1; j < n; j++) {\n            Eigen::Vector3d center_a2 = camera_centers1[j];\n            Eigen::Vector3d center_b2 = camera_centers2[j];\n            double scale_ab = (center_b1 - center_b2).norm() / \n                             (center_a1 - center_a2).norm();\n            scales.push_back(scale_ab);\n        }\n    }\n    // retrieve the median of scales, according to \n    // the equation (5) of the paper \"Divide and Conquer: Efficient Large-Scale\n    // Structure from Motion Using Graph Partitioning\" \n    std::sort(scales.begin(), scales.end());\n    scale = scales[scales.size() / 2];\n\n    // compute relative rotation & relative translation from a->b\n    std::vector<Correspondence3D> corres3d;\n    std::vector<CorrespondenceEuc> input_datas;\n    for (int i = 0; i < camera_centers1.size() ;i++) {\n        corres3d.emplace_back(camera_centers1[i], camera_centers2[i]);\n        input_datas.push_back(make_pair(Euclidean3D(camera_rotations1[i], ts1[i]),\n                                        Euclidean3D(camera_rotations2[i], ts2[i])));\n    }\n    EuclideanEstimator euc_estimator(scale, corres3d);\n    \n    Euclidean3D euc3d;\n    RansacParameters params;\n    params.rng = std::make_shared<RandomNumberGenerator>((unsigned int)time(NULL));\n    params.error_thresh = 0.002;\n    params.max_iterations = 1000;\n    \n    Prosac<EuclideanEstimator> prosac_euc3(params, euc_estimator);\n    prosac_euc3.Initialize();\n    RansacSummary summary;\n    prosac_euc3.Estimate(input_datas, &euc3d, &summary);\n\n    relative_r = euc3d.R;\n    relative_t = euc3d.t;\n    \n    // LOG(INFO) << \"scale: \" << scale;\n    // LOG(INFO) << \"rotation: \\n\";\n    // LOG(INFO) << relative_r(0, 0) << \" \" << relative_r(0, 1) << \" \" << relative_r(0, 2);\n    // LOG(INFO) << relative_r(1, 0) << \" \" << relative_r(1, 1) << \" \" << relative_r(1, 2);\n    // LOG(INFO) << relative_r(2, 0) << \" \" << relative_r(2, 1) << \" \" << relative_r(2, 2);\n    // LOG(INFO) << \"translation: \" \n            //   << relative_t[0] << \", \" << relative_t[1] << \", \" << relative_t[2];\n\n    return true;\n}\n\n} // namespace GraphSfM", "meta": {"hexsha": "e787bc7903853ba86a7854cc00657965374fd950", "size": 19825, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/controllers/sfm_aligner.cpp", "max_stars_repo_name": "LumanYang/GraphSfM", "max_stars_repo_head_hexsha": "c04a63578ce63065eb76278f358812c099d4eeef", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-17T06:18:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-17T06:18:43.000Z", "max_issues_repo_path": "src/controllers/sfm_aligner.cpp", "max_issues_repo_name": "LumanYang/GraphSfM", "max_issues_repo_head_hexsha": "c04a63578ce63065eb76278f358812c099d4eeef", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/controllers/sfm_aligner.cpp", "max_forks_repo_name": "LumanYang/GraphSfM", "max_forks_repo_head_hexsha": "c04a63578ce63065eb76278f358812c099d4eeef", "max_forks_repo_licenses": ["BSD-3-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.3352165725, "max_line_length": 102, "alphanum_fraction": 0.5953089533, "num_tokens": 5302, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217431943271999, "lm_q2_score": 0.6370307806984445, "lm_q1q2_score": 0.45977263054604534}}
{"text": "// Boost.Geometry\n\n// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.\n\n// This file was modified by Oracle on 2015.\n// Modifications copyright (c) 2015 Oracle and/or its affiliates.\n\n// Contributed and/or modified by 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_THOMAS_HPP\n#define BOOST_GEOMETRY_STRATEGIES_GEOGRAPHIC_THOMAS_HPP\n\n\n#include <boost/geometry/core/coordinate_type.hpp>\n#include <boost/geometry/core/radian_access.hpp>\n\n#include <boost/geometry/strategies/distance.hpp>\n\n#include <boost/geometry/util/promote_floating_point.hpp>\n#include <boost/geometry/util/select_calculation_type.hpp>\n\n#include <boost/geometry/algorithms/detail/thomas_inverse.hpp>\n\nnamespace geofeatures_boost {} namespace boost = geofeatures_boost; namespace geofeatures_boost { namespace geometry\n{\n\nnamespace strategy { namespace distance\n{\n\n/*!\n\\brief The solution of the inverse problem of geodesics on latlong coordinates,\n       Forsyth-Andoyer-Lambert type approximation with second order terms.\n\\ingroup distance\n\\tparam Spheroid The reference spheroid model\n\\tparam CalculationType \\tparam_calculation\n\\author See\n    - Technical Report: PAUL D. THOMAS, MATHEMATICAL MODELS FOR NAVIGATION SYSTEMS, 1965\n      http://www.dtic.mil/docs/citations/AD0627893\n    - Technical Report: PAUL D. THOMAS, SPHEROIDAL GEODESICS, REFERENCE SYSTEMS, AND LOCAL GEOMETRY, 1970\n      http://www.dtic.mil/docs/citations/AD703541\n*/\ntemplate\n<\n    typename Spheroid,\n    typename CalculationType = void\n>\nclass thomas\n{\npublic :\n    template <typename Point1, typename Point2>\n    struct calculation_type\n        : promote_floating_point\n          <\n              typename select_calculation_type\n                  <\n                      Point1,\n                      Point2,\n                      CalculationType\n                  >::type\n          >\n    {};\n\n    typedef Spheroid model_type;\n\n    inline thomas()\n        : m_spheroid()\n    {}\n\n    explicit inline thomas(Spheroid const& spheroid)\n        : m_spheroid(spheroid)\n    {}\n\n    template <typename Point1, typename Point2>\n    inline typename calculation_type<Point1, Point2>::type\n    apply(Point1 const& point1, Point2 const& point2) const\n    {\n        return geometry::detail::thomas_inverse\n                <\n                    typename calculation_type<Point1, Point2>::type,\n                    true, false\n                >::apply(get_as_radian<0>(point1),\n                         get_as_radian<1>(point1),\n                         get_as_radian<0>(point2),\n                         get_as_radian<1>(point2),\n                         m_spheroid).distance;\n    }\n\n    inline Spheroid const& model() const\n    {\n        return m_spheroid;\n    }\n\nprivate :\n    Spheroid m_spheroid;\n};\n\n#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\nnamespace services\n{\n\ntemplate <typename Spheroid, typename CalculationType>\nstruct tag<thomas<Spheroid, CalculationType> >\n{\n    typedef strategy_tag_distance_point_point type;\n};\n\n\ntemplate <typename Spheroid, typename CalculationType, typename P1, typename P2>\nstruct return_type<thomas<Spheroid, CalculationType>, P1, P2>\n    : thomas<Spheroid, CalculationType>::template calculation_type<P1, P2>\n{};\n\n\ntemplate <typename Spheroid, typename CalculationType>\nstruct comparable_type<thomas<Spheroid, CalculationType> >\n{\n    typedef thomas<Spheroid, CalculationType> type;\n};\n\n\ntemplate <typename Spheroid, typename CalculationType>\nstruct get_comparable<thomas<Spheroid, CalculationType> >\n{\n    static inline thomas<Spheroid, CalculationType> apply(thomas<Spheroid, CalculationType> const& input)\n    {\n        return input;\n    }\n};\n\ntemplate <typename Spheroid, typename CalculationType, typename P1, typename P2>\nstruct result_from_distance<thomas<Spheroid, CalculationType>, P1, P2 >\n{\n    template <typename T>\n    static inline typename return_type<thomas<Spheroid, CalculationType>, P1, P2>::type\n        apply(thomas<Spheroid, CalculationType> const& , T const& value)\n    {\n        return value;\n    }\n};\n\n\n} // namespace services\n#endif // DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\n\n\n}} // namespace strategy::distance\n\n\n}} // namespace geofeatures_boost::geometry\n\n\n#endif // BOOST_GEOMETRY_STRATEGIES_GEOGRAPHIC_THOMAS_HPP\n", "meta": {"hexsha": "d478f86d97e3c4aab9a56926e20d1e5f613fe00c", "size": 4453, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Pods/GeoFeatures/GeoFeatures/boost/geometry/strategies/geographic/distance_thomas.hpp", "max_stars_repo_name": "xarvey/Yuuuuuge", "max_stars_repo_head_hexsha": "9f4ec32f81cf813ea630ba2c44eb03970c56dad3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2015-08-25T05:35:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-24T14:21:59.000Z", "max_issues_repo_path": "Pods/GeoFeatures/GeoFeatures/boost/geometry/strategies/geographic/distance_thomas.hpp", "max_issues_repo_name": "xarvey/Yuuuuuge", "max_issues_repo_head_hexsha": "9f4ec32f81cf813ea630ba2c44eb03970c56dad3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 97.0, "max_issues_repo_issues_event_min_datetime": "2015-08-25T16:11:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-17T00:54:32.000Z", "max_forks_repo_path": "Pods/GeoFeatures/GeoFeatures/boost/geometry/strategies/geographic/distance_thomas.hpp", "max_forks_repo_name": "xarvey/Yuuuuuge", "max_forks_repo_head_hexsha": "9f4ec32f81cf813ea630ba2c44eb03970c56dad3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-08-26T03:11:38.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-21T07:16:29.000Z", "avg_line_length": 28.3630573248, "max_line_length": 116, "alphanum_fraction": 0.7049180328, "num_tokens": 1058, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4597669312872782}}
{"text": "//Source: The LLVM Compiler Infrastructure - lib/addsf3.c\n//Modified to truncate result of addition\n\n#include <limits.h>\n#include <boost/cstdint.hpp>\n#include \"FpAddTruncate.h\"\n#include \"BitManip.h\"\n\ntypedef uint32 rep_t;\ntypedef int32 srep_t;\ntypedef float fp_t;\n#define REP_C UINT32_C\n#define significandBits 23\n\n#define typeWidth       (sizeof(rep_t)*CHAR_BIT)\n#define exponentBits    (typeWidth - significandBits - 1)\n#define maxExponent     ((1 << exponentBits) - 1)\n#define exponentBias    (maxExponent >> 1)\n\n#define implicitBit     (REP_C(1) << significandBits)\n#define significandMask (implicitBit - 1U)\n#define signBit         (REP_C(1) << (significandBits + exponentBits))\n#define absMask         (signBit - 1U)\n#define exponentMask    (absMask ^ significandMask)\n#define oneRep          ((rep_t)exponentBias << significandBits)\n#define infRep          exponentMask\n#define quietBit        (implicitBit >> 1)\n#define qnanRep         (exponentMask | quietBit)\n\nstatic inline int rep_clz(rep_t a) {\n\treturn __builtin_clz(a);\n}\n\nuint32 FpAddTruncate(uint32 a, uint32 b) \n{\n    const rep_t aAbs = a & absMask;\n    const rep_t bAbs = b & absMask;\n    \n    // Detect if a or b is zero, infinity, or NaN.\n    if (aAbs - 1U >= infRep - 1U || bAbs - 1U >= infRep - 1U) {\n        \n        // NaN + anything = qNaN\n        if (aAbs > infRep) return (a | quietBit);\n        // anything + NaN = qNaN\n        if (bAbs > infRep) return (b | quietBit);\n        \n        if (aAbs == infRep) {\n            // +/-infinity + -/+infinity = qNaN\n            if ((a ^ b) == signBit) return qnanRep;\n            // +/-infinity + anything remaining = +/- infinity\n            else return a;\n        }\n        \n        // anything remaining + +/-infinity = +/-infinity\n        if (bAbs == infRep) return b;\n        \n        // zero + anything = anything\n        if (!aAbs) {\n            // but we need to get the sign right for zero + zero\n            if (!bAbs) return (a & b);\n            else return b;\n        }\n        \n        // anything + zero = anything\n        if (!bAbs) return a;\n    }\n    \n    // Swap a and b if necessary so that a has the larger absolute value.\n    if (bAbs > aAbs) {\n        const uint32 temp = a;\n        a = b;\n        b = temp;\n    }\n    \n    // Extract the exponent and significand from the (possibly swapped) a and b.\n    int aExponent = a >> significandBits & maxExponent;\n    int bExponent = b >> significandBits & maxExponent;\n    rep_t aSignificand = a & significandMask;\n    rep_t bSignificand = b & significandMask;\n    \n    // Normalize any denormals, and adjust the exponent accordingly.\n    //if (aExponent == 0) aExponent = normalize(&aSignificand);\n    //if (bExponent == 0) bExponent = normalize(&bSignificand);\n    \n    // The sign of the result is the sign of the larger operand, a.  If they\n    // have opposite signs, we are performing a subtraction; otherwise addition.\n    const rep_t resultSign = a & signBit;\n    const bool subtraction = (a ^ b) & signBit;\n    \n    // Shift the significands to give us round, guard and sticky, and or in the\n    // implicit significand bit.  (If we fell through from the denormal path it\n    // was already set by normalize( ), but setting it twice won't hurt\n    // anything.)\n    aSignificand = (aSignificand | implicitBit) << 3;\n    bSignificand = (bSignificand | implicitBit) << 3;\n    \n    // Shift the significand of b by the difference in exponents, with a sticky\n    // bottom bit to get rounding correct.\n    const unsigned int align = aExponent - bExponent;\n    if (align) {\n        if (align < typeWidth) {\n            //const bool sticky = bSignificand << (typeWidth - align);\n            bSignificand = bSignificand >> align;\n        } else {\n            bSignificand = 0; // sticky; b is known to be non-zero.\n        }\n    }\n    \n    if (subtraction) {\n        aSignificand -= bSignificand;\n        \n        // If a == -b, return +zero.\n        if (aSignificand == 0) return 0;\n        \n        // If partial cancellation occured, we need to left-shift the result\n        // and adjust the exponent:\n        if (aSignificand < implicitBit << 3) {\n            const int shift = rep_clz(aSignificand) - rep_clz(implicitBit << 3);\n            aSignificand <<= shift;\n            aExponent -= shift;\n        }\n    }\n    \n    else /* addition */ {\n        aSignificand += bSignificand;\n        \n        // If the addition carried up, we need to right-shift the result and\n        // adjust the exponent:\n        if (aSignificand & implicitBit << 4) {\n            const bool sticky = aSignificand & 1;\n            aSignificand = aSignificand >> 1 | sticky;\n            aExponent += 1;\n        }\n    }\n    \n    // If we have overflowed the type, return +/- infinity:\n    if (aExponent >= maxExponent) return infRep | resultSign;\n    \n    if (aExponent <= 0) {\n        // Result is denormal before rounding; the exponent is zero and we\n        // need to shift the significand.\n        const int shift = 1 - aExponent;\n        const bool sticky = aSignificand << (typeWidth - shift);\n        aSignificand = aSignificand >> shift | sticky;\n        aExponent = 0;\n    }\n    \n    // Low three bits are round, guard, and sticky.\n    const int roundGuardSticky = aSignificand & 0x7;\n    \n    // Shift the significand into place, and mask off the implicit bit.\n    rep_t result = aSignificand >> 3 & significandMask;\n    \n    // Insert the exponent and sign.\n    result |= (rep_t)aExponent << significandBits;\n    result |= resultSign;\n    \n    return result;\n}\n", "meta": {"hexsha": "0534002445683cbe67fa3d01df8b62ebac871829", "size": 5540, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Source/ee/FpAddTruncate.cpp", "max_stars_repo_name": "maximu/Play-", "max_stars_repo_head_hexsha": "c9ea635c66a5cc939b8719b634bc8135ec0d67ce", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-30T16:23:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-30T16:23:17.000Z", "max_issues_repo_path": "Source/ee/FpAddTruncate.cpp", "max_issues_repo_name": "maximu/Play-", "max_issues_repo_head_hexsha": "c9ea635c66a5cc939b8719b634bc8135ec0d67ce", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Source/ee/FpAddTruncate.cpp", "max_forks_repo_name": "maximu/Play-", "max_forks_repo_head_hexsha": "c9ea635c66a5cc939b8719b634bc8135ec0d67ce", "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.625, "max_line_length": 80, "alphanum_fraction": 0.5994584838, "num_tokens": 1478, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4597669312872782}}
{"text": "#include \"timetable/departure_table.hpp\"\n\n#include <algorithm>\n\n#include <boost/assert.hpp>\n\nnamespace nepomuk\n{\nnamespace timetable\n{\n\nbool Departure::operator<(Departure const &other) const { return end < other.end; }\n\ndate::Time Departure::get_next_departure(date::Time const starting_at) const\n{\n    // the next departue for a given starting time is defined by T = begin + x * headway with T >=\n    // starting_at and x minimal among all x that fulfill T >= starting_at\n\n    BOOST_ASSERT(starting_at <= end);\n\n    // in case the trip is only serviced after the starting time, the very first service can be\n    // reached. After this check starting_at is within the range [begin,end)\n    if (starting_at <= begin)\n        return begin;\n\n    // compute the xth train that can be reached (ceil(delta_t/headway))\n    const auto x = (starting_at - begin + headway - 1) / headway;\n\n    return begin + x * headway;\n}\n\nDepartureTable::const_iterator_range DepartureTable::list(date::Time starting_at) const\n{\n    return {std::lower_bound(departures.begin(),\n                             departures.end(),\n                             starting_at,\n                             [](auto const &departure, auto const &time) {\n                                 return departure.end < time + (departure.headway);\n                             }),\n            departures.end()};\n}\n\n} // namespace timetable\n} // namespace nepomuk\n", "meta": {"hexsha": "6b8a7aef1bd2e6855383d70768d25adb21e890f9", "size": 1417, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/timetable/departure_table.cpp", "max_stars_repo_name": "mapbox/nepomuk", "max_stars_repo_head_hexsha": "8771482edb9b16bb0f5a152c15681c57eb3bb6b6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2017-05-12T11:52:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-06T06:05:08.000Z", "max_issues_repo_path": "src/timetable/departure_table.cpp", "max_issues_repo_name": "mapbox/nepomuk", "max_issues_repo_head_hexsha": "8771482edb9b16bb0f5a152c15681c57eb3bb6b6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 49.0, "max_issues_repo_issues_event_min_datetime": "2017-05-11T16:13:58.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-13T11:19:17.000Z", "max_forks_repo_path": "src/timetable/departure_table.cpp", "max_forks_repo_name": "mapbox/nepomuk", "max_forks_repo_head_hexsha": "8771482edb9b16bb0f5a152c15681c57eb3bb6b6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-11-19T12:04:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-06T06:14:25.000Z", "avg_line_length": 31.4888888889, "max_line_length": 98, "alphanum_fraction": 0.6323218066, "num_tokens": 309, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.45976693128727814}}
{"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 <fstream>\n#include <vector>\n#include <iterator>\n#include <algorithm>\n#include <boost/program_options.hpp>\n#include <dai/factorgraph.h>\n#include <dai/weightedgraph.h>\n#include <dai/util.h>\n#include <dai/graph.h>\n#include <dai/enum.h>\n#include <dai/properties.h>\n\n\nusing namespace std;\nusing namespace dai;\nnamespace po = boost::program_options;\n\n\n/// Possible factor types\nDAI_ENUM(FactorType,ISINGGAUSS,ISINGUNIFORM,EXPGAUSS,POTTS);\n\n\n/// Creates a factor graph from a pairwise interactions graph\n/** \\param G  Graph describing interactions between variables\n *  \\param ft Type of factors to use for interactions\n *  \\param states Number of states of the variables\n *  \\param props Additional properties for generating the interactions\n */\nFactorGraph createFG( const GraphAL &G, FactorType ft, size_t states, const PropertySet &props ) {\n    size_t N = G.nrNodes();\n\n    DAI_ASSERT(states <= 2 || ft != FactorType::ISINGGAUSS && ft != FactorType::ISINGUNIFORM );\n\n    // Get inverse temperature\n    Real beta = 1.0;\n    if( ft != FactorType::ISINGGAUSS && ft != FactorType::ISINGUNIFORM )\n        beta = props.getAs<Real>(\"beta\");\n\n    // Get properties for Ising factors\n    Real mean_h = 0.0;\n    Real sigma_h = 0.0;\n    Real mean_J = 0.0;\n    Real sigma_J = 0.0;\n    if( ft == FactorType::ISINGGAUSS ) {\n        mean_h = props.getAs<Real>(\"mean_th\");\n        sigma_h = props.getAs<Real>(\"sigma_th\");\n        mean_J = props.getAs<Real>(\"mean_w\");\n        sigma_J = props.getAs<Real>(\"sigma_w\");\n    }\n    Real min_h = 0.0;\n    Real min_J = 0.0;\n    Real max_h = 0.0;\n    Real max_J = 0.0;\n    if( ft == FactorType::ISINGUNIFORM ) {\n        min_h = props.getAs<Real>(\"min_th\");\n        min_J = props.getAs<Real>(\"min_w\");\n        max_h = props.getAs<Real>(\"max_th\");\n        max_J = props.getAs<Real>(\"max_w\");\n    }\n\n    // Create variables\n    vector<Var> vars;\n    vars.reserve( N );\n    for( size_t i = 0; i < N; i++ )\n        vars.push_back( Var( i, states ) );\n\n    // Create factors\n    vector<Factor> factors;\n    factors.reserve( G.nrEdges() + N );\n    // Pairwise factors\n    for( size_t i = 0; i < N; i++ )\n        for( const Neighbor &j : G.nb(i) )\n            if( i < j ) {\n                if( ft == FactorType::POTTS )\n                    factors.push_back( createFactorPotts( vars[i], vars[j], beta ) );\n                else if( ft == FactorType::EXPGAUSS )\n                    factors.push_back( createFactorExpGauss( VarSet( vars[i], vars[j] ), beta ) );\n                else if( ft == FactorType::ISINGGAUSS ) {\n                    Real J = rnd_stdnormal() * sigma_J + mean_J;\n                    factors.push_back( createFactorIsing( vars[i], vars[j], J ) );\n                } else if( ft == FactorType::ISINGUNIFORM ) {\n                    Real J = min_J + rnd_uniform() * (max_J - min_J);\n                    factors.push_back( createFactorIsing( vars[i], vars[j], J ) );\n                }\n            }\n    // Unary factors\n    if( ft == FactorType::ISINGGAUSS )\n        for( size_t i = 0; i < N; i++ ) {\n            Real h = rnd_stdnormal() * sigma_h + mean_h;\n            factors.push_back( createFactorIsing( vars[i], h ) );\n        }\n    else if( ft == FactorType::ISINGUNIFORM )\n        for( size_t i = 0; i < N; i++ ) {\n            Real h = min_h + rnd_uniform() * (max_h - min_h);\n            factors.push_back( createFactorIsing( vars[i], h ) );\n        }\n\n    return FactorGraph( factors.begin(), factors.end(), vars.begin(), vars.end(), factors.size(), vars.size() );\n}\n\n\n/// Return a random factor graph with higher-order interactions\n/** \\param N number of variables\n *  \\param M number of factors\n *  \\param k number of variables that each factor depends on\n *  \\param beta standard-deviation of Gaussian log-factor entries\n */\nFactorGraph createHOIFG( size_t N, size_t M, size_t k, Real beta ) {\n    vector<Var> vars;\n    vector<Factor> factors;\n\n    vars.reserve(N);\n    for( size_t i = 0; i < N; i++ )\n        vars.push_back(Var(i,2));\n\n    for( size_t I = 0; I < M; I++ ) {\n        VarSet vars;\n        while( vars.size() < k ) {\n            do {\n                size_t newind = (size_t)(N * rnd_uniform());\n                Var newvar = Var(newind, 2);\n                if( !vars.contains( newvar ) ) {\n                    vars |= newvar;\n                    break;\n                }\n            } while( 1 );\n        }\n        factors.push_back( createFactorExpGauss( vars, beta ) );\n    }\n\n    return FactorGraph( factors.begin(), factors.end(), vars.begin(), vars.end(), factors.size(), vars.size() );\n}\n\n\n/// Creates a regular random bipartite graph\n/** \\param N1 = number of nodes of type 1\n *  \\param d1 = size of neighborhoods of nodes of type 1\n *  \\param N2 = number of nodes of type 2\n *  \\param d2 = size of neighborhoods of nodes of type 2\n *  \\note asserts that N1 * d1 == N2 * d2\n */\nBipartiteGraph createRandomBipartiteGraph( size_t N1, size_t N2, size_t d1, size_t d2 ) {\n    BipartiteGraph G;\n\n    DAI_ASSERT( N1 * d1 == N2 * d2 );\n\n    // build lists of degree-repeated vertex numbers\n    std::vector<size_t> stubs1( N1*d1, 0 );\n    for( size_t n1 = 0; n1 < N1; n1++ )\n        for( size_t t = 0; t < d1; t++ )\n            stubs1[n1*d1 + t] = n1;\n\n    // build lists of degree-repeated vertex numbers\n    std::vector<size_t> stubs2( N2*d2, 0 );\n    for( size_t n2 = 0; n2 < N2; n2++ )\n        for( size_t t = 0; t < d2; t++ )\n            stubs2[n2*d2 + t] = n2;\n\n    // shuffle lists\n    random_shuffle( stubs1.begin(), stubs1.end(), rnd );\n    random_shuffle( stubs2.begin(), stubs2.end(), rnd );\n\n    // add edges\n    vector<Edge> edges;\n    edges.reserve( N1*d1 );\n    for( size_t e = 0; e < N1*d1; e++ )\n        edges.push_back( Edge(stubs1[e], stubs2[e]) );\n\n    // finish construction\n    G.construct( N1, N2, edges.begin(), edges.end() );\n\n    return G;\n}\n\n\n/// Returns x**n % p, assuming p is prime\nint powmod (int x, int n, int p) {\n    int y = 1;\n    for( int m = 0; m < n; m++ )\n        y = (x * y) % p;\n    return y;\n}\n\n\n/// Returns order of x in GF(p) with p prime\nsize_t order (int x, int p) {\n    x = x % p;\n    DAI_ASSERT( x != 0 );\n    size_t n = 0;\n    size_t prod = 1;\n    do {\n        prod = (prod * x) % p;\n        n++;\n    } while( prod != 1 );\n    return n;\n}\n\n\n/// Returns whether n is a prime number\nbool isPrime (size_t n) {\n    bool result = true;\n    for( size_t k = 2; (k < n) && result; k++ )\n        if( n % k == 0 )\n            result = false;\n    return result;\n}\n\n\n/// Constructs a regular LDPC graph with N=6, j=2, K=4, k=3\nBipartiteGraph createSmallLDPCGraph() {\n    BipartiteGraph G;\n    size_t N=4, j=3, K=4; // k=3;\n\n    vector<Edge> edges;\n    edges.reserve( N*j );\n    edges.push_back( Edge(0,0) ); edges.push_back( Edge(1,0) ); edges.push_back( Edge(2,0) );\n    edges.push_back( Edge(0,1) ); edges.push_back( Edge(1,1) ); edges.push_back( Edge(3,1) );\n    edges.push_back( Edge(0,2) ); edges.push_back( Edge(2,2) ); edges.push_back( Edge(3,2) );\n    edges.push_back( Edge(1,3) ); edges.push_back( Edge(2,3) ); edges.push_back( Edge(3,3) );\n\n    // finish construction\n    G.construct( N, K, edges.begin(), edges.end() );\n\n    return G;\n}\n\n\n/// Creates group-structured LDPC code\n/** Use construction described in \"A Class of Group-Structured LDPC Codes\"\n *  by R. M. Tanner, D. Sridhara and T. Fuja\n *  Proceedings of ICSTA, 2001\n *\n *  Example parameters: (p,j,k) = (31,3,5)\n *                      (p,j,k) = (37,3,4)\n *                      (p,j,k) = (7,2,4)\n *                      (p,j,k) = (29,2,4)\n *\n *  j and k must be divisors of p-1\n */\nBipartiteGraph createGroupStructuredLDPCGraph( size_t p, size_t j, size_t k ) {\n    BipartiteGraph G;\n\n    size_t n = j;\n    size_t N = p * k;\n    size_t K = p * j;\n\n    size_t a, b;\n    for( a = 2; a < p; a++ )\n        if( order(a,p) == k )\n            break;\n    DAI_ASSERT( a != p );\n    for( b = 2; b < p; b++ )\n        if( order(b,p) == j )\n            break;\n    DAI_ASSERT( b != p );\n    // cout << \"# order(a=\" << a << \") = \" << order(a,p) << endl;\n    // cout << \"# order(b=\" << b << \") = \" << order(b,p) << endl;\n\n    DAI_ASSERT( N * n == K * k );\n\n    vector<Edge> edges;\n    edges.reserve( N * n );\n\n    for( size_t s = 0; s < j; s++ )\n        for( size_t t = 0; t < k; t++ ) {\n            size_t P = (powmod(b,s,p) * powmod(a,t,p)) % p;\n            for( size_t m = 0; m < p; m++ )\n                edges.push_back( Edge(t*p + m, s*p + ((m + P) % p)) );\n        }\n\n    // finish construction\n    G.construct( N, K, edges.begin(), edges.end() );\n\n    return G;\n}\n\n\n// Constructs a parity check table\nvoid createParityCheck( Real *result, size_t n, Real eps ) {\n    size_t N = 1 << n;\n    for( size_t i = 0; i < N; i++ ) {\n        size_t c = 0;\n        for( size_t t = 0; t < n; t++ )\n            if( i & (1 << t) )\n                c ^= 1;\n        if( c )\n            result[i] = eps;\n        else\n            result[i] = 1.0 - eps;\n    }\n    return;\n}\n\n\n/// Predefined names of various factor graph types\nconst char *FULL_TYPE        = \"FULL\";\nconst char *DREG_TYPE        = \"DREG\";\nconst char *LOOP_TYPE        = \"LOOP\";\nconst char *TREE_TYPE        = \"TREE\";\nconst char *GRID_TYPE        = \"GRID\";\nconst char *GRID3D_TYPE      = \"GRID3D\";\nconst char *HOI_TYPE         = \"HOI\";\nconst char *LDPC_TYPE        = \"LDPC\";\n\n\n/// Possible LDPC structures\nDAI_ENUM(LDPCType,SMALL,GROUP,RANDOM);\n\n\n/// Main function\nint main( int argc, char *argv[] ) {\n    try {\n        // Variables for storing command line arguments\n        size_t seed;\n        size_t states = 2;\n        string type;\n        size_t d, N, K, k, j, n1, n2, n3, prime;\n        bool periodic = false;\n        FactorType ft;\n        LDPCType ldpc;\n        Real beta, sigma_w, sigma_th, mean_w, mean_th, min_w, min_th, max_w, max_th, noise;\n\n        // Declare the supported options.\n        po::options_description opts(\"General command line options\");\n        opts.add_options()\n            (\"help\",     \"produce help message\")\n            (\"seed\",     po::value<size_t>(&seed),   \"random number seed (tries to read from /dev/urandom if not specified)\")\n            (\"states\",   po::value<size_t>(&states), \"number of states of each variable (default=2 for binary variables)\")\n        ;\n\n        // Graph structure options\n        po::options_description opts_graph(\"Options for specifying graph structure\");\n        opts_graph.add_options()\n            (\"type\",     po::value<string>(&type),   \"factor graph type (one of 'FULL', 'DREG', 'LOOP', 'TREE', 'GRID', 'GRID3D', 'HOI', 'LDPC')\")\n            (\"d\",        po::value<size_t>(&d),      \"variable connectivity (only for type=='DREG');\\n\\t<d><N> should be even\")\n            (\"N\",        po::value<size_t>(&N),      \"number of variables (not for type=='GRID','GRID3D')\")\n            (\"n1\",       po::value<size_t>(&n1),     \"width of grid (only for type=='GRID','GRID3D')\")\n            (\"n2\",       po::value<size_t>(&n2),     \"height of grid (only for type=='GRID','GRID3D')\")\n            (\"n3\",       po::value<size_t>(&n3),     \"length of grid (only for type=='GRID3D')\")\n            (\"periodic\", po::value<bool>(&periodic), \"periodic grid? (only for type=='GRID','GRID3D'; default=0)\")\n            (\"K\",        po::value<size_t>(&K),      \"number of factors (only for type=='HOI','LDPC')\")\n            (\"k\",        po::value<size_t>(&k),      \"number of variables per factor (only for type=='HOI','LDPC')\")\n        ;\n\n        // Factor options\n        po::options_description opts_factors(\"Options for specifying factors\");\n        opts_factors.add_options()\n            (\"factors\",  po::value<FactorType>(&ft), \"factor type (one of 'EXPGAUSS','POTTS','ISINGGAUSS','ISINGUNIFORM')\")\n            (\"beta\",     po::value<Real>(&beta),     \"inverse temperature (ignored for factors=='ISINGGAUSS','ISINGUNIFORM')\")\n            (\"mean_w\",   po::value<Real>(&mean_w),   \"mean of pairwise interactions w_{ij} (only for factors=='ISINGGAUSS')\")\n            (\"mean_th\",  po::value<Real>(&mean_th),  \"mean of unary interactions th_i (only for factors=='ISINGGAUSS')\")\n            (\"sigma_w\",  po::value<Real>(&sigma_w),  \"stddev of pairwise interactions w_{ij} (only for factors=='ISINGGAUSS')\")\n            (\"sigma_th\", po::value<Real>(&sigma_th), \"stddev of unary interactions th_i (only for factors=='ISINGGAUSS'\")\n            (\"min_w\",    po::value<Real>(&min_w),    \"minimum of pairwise interactions w_{ij} (only for factors=='ISINGUNIFORM')\")\n            (\"min_th\",   po::value<Real>(&min_th),   \"minimum of unary interactions th_i (only for factors=='ISINGUNIFORM')\")\n            (\"max_w\",    po::value<Real>(&max_w),    \"maximum of pairwise interactions w_{ij} (only for factors=='ISINGUNIFORM')\")\n            (\"max_th\",   po::value<Real>(&max_th),   \"maximum of unary interactions th_i (only for factors=='ISINGUNIFORM')\")\n        ;\n\n        // LDPC options\n        po::options_description opts_ldpc(\"Options for specifying LDPC code factor graphs\");\n        opts_ldpc.add_options()\n            (\"ldpc\",     po::value<LDPCType>(&ldpc), \"type of LDPC code (one of 'SMALL','GROUP','RANDOM')\")\n            (\"j\",        po::value<size_t>(&j),      \"number of parity checks per bit (only for type=='LDPC')\")\n            (\"noise\",    po::value<Real>(&noise),    \"bitflip probability for binary symmetric channel (only for type=='LDPC')\")\n            (\"prime\",    po::value<size_t>(&prime),  \"prime number for construction of LDPC code (only for type=='LDPC' with ldpc='GROUP'))\")\n        ;\n\n        // All options\n        opts.add(opts_graph).add(opts_factors).add(opts_ldpc);\n\n        // Parse command line arguments\n        po::variables_map vm;\n        po::store(po::parse_command_line(argc, argv, opts), vm);\n        po::notify(vm);\n\n        // Display help message if necessary\n        if( vm.count(\"help\") || !vm.count(\"type\") ) {\n            cout << \"This program is part of libDAI - http://www.libdai.org/\" << endl << endl;\n            cout << \"Usage: ./createfg [options]\" << endl << endl;\n            cout << \"Creates a factor graph according to the specified options.\" << endl << endl;\n\n            cout << endl << opts << endl;\n\n            cout << \"The following factor graph types with pairwise interactions can be created:\" << endl;\n            cout << \"\\t'FULL':   fully connected graph of <N> variables\" << endl;\n            cout << \"\\t'DREG':   random regular graph of <N> variables where each variable is connected with <d> others\" << endl;\n            cout << \"\\t'LOOP':   a single loop of <N> variables\" << endl;\n            cout << \"\\t'TREE':   random tree-structured (acyclic, connected) graph of <N> variables\" << endl;\n            cout << \"\\t'GRID':   2D grid of <n1>x<n2> variables\" << endl;\n            cout << \"\\t'GRID3D': 3D grid of <n1>x<n2>x<n3> variables\" << endl;\n            cout << \"The following higher-order interactions factor graphs can be created:\" << endl;\n            cout << \"\\t'HOI':    random factor graph consisting of <N> variables and <K> factors,\" << endl;\n            cout << \"\\t          each factor being an interaction of <k> variables.\" << endl;\n            cout << \"The following LDPC code factor graphs can be created:\" << endl;\n            cout << \"\\t'LDPC':   simulates LDPC decoding problem, using an LDPC code of <N> bits and <K>\" << endl;\n            cout << \"\\t          parity checks, with <k> bits per check and <j> checks per bit, transmitted\" << endl;\n            cout << \"\\t          on a binary symmetric channel with probability <noise> of flipping a bit.\" << endl;\n            cout << \"\\t          The transmitted codeword has all bits set to zero. The argument 'ldpc'\" << endl;\n            cout << \"\\t          determines how the LDPC code is constructed: either using a group structure,\" << endl;\n            cout << \"\\t          or randomly, or a fixed small code with (N,K,k,j) = (4,4,3,3).\" << endl << endl;\n\n            cout << \"For all types except type=='LDPC', the factors have to be specified as well.\" << endl << endl;\n\n            cout << \"EXPGAUSS factors (the default) are created by drawing all log-factor entries\" << endl;\n            cout << \"independently from a Gaussian with mean 0 and standard deviation <beta>.\" << endl << endl;\n\n            cout << \"In case of pairwise interactions, one can also choose POTTS factors, for which\" << endl;\n            cout << \"the log-factors are simply delta functions multiplied by the strength <beta>.\" << endl << endl;\n\n            cout << \"For pairwise interactions and binary variables, one can also use ISINGGAUSS factors.\" << endl;\n            cout << \"Here variables x1...xN are assumed to be +1/-1--valued, and unary interactions\" << endl;\n            cout << \"are of the form exp(th*xi) with th drawn from a Gaussian distribution with mean\" << endl;\n            cout << \"<mean_th> and standard deviation <sigma_th>, and pairwise interactions are of the\" << endl;\n            cout << \"form exp(w*xi*xj) with w drawn from a Gaussian distribution with mean <mean_w>\" << endl;\n            cout << \"and standard deviation <sigma_w>.\" << endl;\n            cout << \"Alternatively, one can use ISINGUNIFORM factors: here th is drawn from a uniform\" << endl;\n            cout << \"distribution on [<min_th>, <max_th>), and w is drawn from a uniform distribution\" << endl;\n            cout << \"on [<min_w>, <max_w>).\" << endl;\n            return 1;\n        }\n\n        // Set default number of states\n        if( !vm.count(\"states\") )\n            states = 2;\n\n        // Set default factor type\n        if( !vm.count(\"factors\") )\n            ft = FactorType::EXPGAUSS;\n        // Check validness of factor type\n        if( ft == FactorType::POTTS )\n            if( type == HOI_TYPE )\n                throw \"For factors=='POTTS', interactions should be pairwise (type!='HOI')\";\n        if( ft == FactorType::ISINGGAUSS )\n            if( ((states != 2) || (type == HOI_TYPE)) )\n                throw \"For factors=='ISINGGAUSS', variables should be binary (states==2) and interactions should be pairwise (type!='HOI')\";\n        if( ft == FactorType::ISINGUNIFORM )\n            if( ((states != 2) || (type == HOI_TYPE)) )\n                throw \"For factors=='ISINGUNIFORM', variables should be binary (states==2) and interactions should be pairwise (type!='HOI')\";\n\n        // Read random seed\n        if( !vm.count(\"seed\") ) {\n            ifstream infile;\n            bool success;\n            infile.open( \"/dev/urandom\" );\n            success = infile.is_open();\n            if( success ) {\n                infile.read( (char *)&seed, sizeof(size_t) / sizeof(char) );\n                success = infile.good();\n                infile.close();\n            }\n            if( !success )\n                throw \"Please specify random number seed.\";\n        }\n        rnd_seed( seed );\n\n        // Set default periodicity\n        if( !vm.count(\"periodic\") )\n            periodic = false;\n\n        // Store some options in a PropertySet object\n        PropertySet options;\n        if( vm.count(\"mean_th\") )\n            options.set(\"mean_th\", mean_th);\n        if( vm.count(\"sigma_th\") )\n            options.set(\"sigma_th\", sigma_th);\n        if( vm.count(\"mean_w\") )\n            options.set(\"mean_w\", mean_w);\n        if( vm.count(\"sigma_w\") )\n            options.set(\"sigma_w\", sigma_w);\n        if( vm.count(\"beta\") )\n            options.set(\"beta\", beta);\n        if( vm.count(\"min_w\") )\n            options.set(\"min_w\", min_w);\n        if( vm.count(\"min_th\") )\n            options.set(\"min_th\", min_th);\n        if( vm.count(\"max_w\") )\n            options.set(\"max_w\", max_w);\n        if( vm.count(\"max_th\") )\n            options.set(\"max_th\", max_th);\n\n        // Output some comments\n        cout << \"# Factor graph made by \" << argv[0] << endl;\n        cout << \"# type = \" << type << endl;\n        cout << \"# states = \" << states << endl;\n        cout << \"# factor type = \" << ft << endl;\n\n        // The factor graph to be constructed\n        FactorGraph fg;\n\n#define NEED_ARG(name, desc) do { if(!vm.count(name)) throw \"Please specify \" desc \" with --\" name; } while(0);\n\n        if( type == FULL_TYPE || type == DREG_TYPE || type == LOOP_TYPE || type == TREE_TYPE || type == GRID_TYPE || type == GRID3D_TYPE ) {\n            // Pairwise interactions\n\n            // Check command line options\n            if( type == GRID_TYPE ) {\n                NEED_ARG(\"n1\", \"width of grid\");\n                NEED_ARG(\"n2\", \"height of grid\");\n                N = n1 * n2;\n            } else if( type == GRID3D_TYPE ) {\n                NEED_ARG(\"n1\", \"width of grid\");\n                NEED_ARG(\"n2\", \"height of grid\");\n                NEED_ARG(\"n3\", \"depth of grid\");\n                N = n1 * n2 * n3;\n            } else\n                NEED_ARG(\"N\", \"number of variables\");\n\n            if( ft == FactorType::ISINGGAUSS ) {\n                NEED_ARG(\"mean_w\", \"mean of pairwise interactions\");\n                NEED_ARG(\"mean_th\", \"mean of unary interactions\");\n                NEED_ARG(\"sigma_w\", \"stddev of pairwise interactions\");\n                NEED_ARG(\"sigma_th\", \"stddev of unary interactions\");\n            } else if( ft == FactorType::ISINGUNIFORM ) {\n                NEED_ARG(\"min_w\", \"minimum of pairwise interactions\");\n                NEED_ARG(\"min_th\", \"minimum of unary interactions\");\n                NEED_ARG(\"max_w\", \"maximum of pairwise interactions\");\n                NEED_ARG(\"max_th\", \"maximum of unary interactions\");\n            } else\n                NEED_ARG(\"beta\", \"stddev of log-factor entries\");\n\n            if( type == DREG_TYPE )\n                NEED_ARG(\"d\", \"connectivity (number of neighboring variables of each variable)\");\n\n            // Build pairwise interaction graph\n            GraphAL G;\n            if( type == FULL_TYPE )\n                G = createGraphFull( N );\n            else if( type == DREG_TYPE )\n                G = createGraphRegular( N, d );\n            else if( type == LOOP_TYPE )\n                G = createGraphLoop( N );\n            else if( type == TREE_TYPE )\n                G = createGraphTree( N );\n            else if( type == GRID_TYPE )\n                G = createGraphGrid( n1, n2, periodic );\n            else if( type == GRID3D_TYPE )\n                G = createGraphGrid3D( n1, n2, n3, periodic );\n\n            // Construct factor graph from pairwise interaction graph\n            fg = createFG( G, ft, states, options );\n\n            // Output some additional comments\n            if( type == GRID_TYPE || type == GRID3D_TYPE ) {\n                cout << \"# n1 = \" << n1 << endl;\n                cout << \"# n2 = \" << n2 << endl;\n                if( type == GRID3D_TYPE )\n                    cout << \"# n3 = \" << n3 << endl;\n            }\n            if( type == DREG_TYPE )\n                cout << \"# d = \" << d << endl;\n            cout << \"# options = \" << options << endl;\n        } else if( type == HOI_TYPE ) {\n            // Higher order interactions\n\n            // Check command line arguments\n            NEED_ARG(\"N\", \"number of variables\");\n            NEED_ARG(\"K\", \"number of factors\");\n            NEED_ARG(\"k\", \"number of variables per factor\");\n            NEED_ARG(\"beta\", \"stddev of log-factor entries\");\n\n            // Create higher-order interactions factor graph\n            do {\n                fg = createHOIFG( N, K, k, beta );\n            } while( !fg.isConnected() );\n\n            // Output some additional comments\n            cout << \"# K = \" << K << endl;\n            cout << \"# k = \" << k << endl;\n            cout << \"# beta = \" << beta << endl;\n        } else if( type == LDPC_TYPE ) {\n            // LDPC codes\n\n            // Check command line arguments\n            NEED_ARG(\"ldpc\", \"type of LDPC code\");\n            NEED_ARG(\"noise\", \"bitflip probability for binary symmetric channel\");\n\n            // Check more command line arguments (seperately for each LDPC type)\n            if( ldpc == LDPCType::RANDOM ) {\n                NEED_ARG(\"N\", \"number of variables\");\n                NEED_ARG(\"K\", \"number of factors\");\n                NEED_ARG(\"k\", \"number of variables per factor\");\n                NEED_ARG(\"j\", \"number of parity checks per bit\");\n                if( N * j != K * k )\n                    throw \"Parameters should satisfy N * j == K * k\";\n            } else if( ldpc == LDPCType::GROUP ) {\n                NEED_ARG(\"prime\", \"prime number\");\n                NEED_ARG(\"k\", \"number of variables per factor\");\n                NEED_ARG(\"j\", \"number of parity checks per bit\");\n\n                if( !isPrime(prime) )\n                    throw \"Parameter <prime> should be prime\";\n                if( !((prime-1) % j == 0 ) )\n                    throw \"Parameters should satisfy (prime-1) % j == 0\";\n                if( !((prime-1) % k == 0 ) )\n                    throw \"Parameters should satisfy (prime-1) % k == 0\";\n\n                N = prime * k;\n                K = prime * j;\n            } else if( ldpc == LDPCType::SMALL ) {\n                N = 4;\n                K = 4;\n                j = 3;\n                k = 3;\n            }\n\n            // Output some additional comments\n            cout << \"# N = \" << N << endl;\n            cout << \"# K = \" << K << endl;\n            cout << \"# j = \" << j << endl;\n            cout << \"# k = \" << k << endl;\n            if( ldpc == LDPCType::GROUP )\n                cout << \"# prime = \" << prime << endl;\n            cout << \"# noise = \" << noise << endl;\n\n            // Construct likelihood and paritycheck factors\n            Real likelihood[4] = {1.f - noise, noise, noise, 1.f - noise};\n            Real *paritycheck = new Real[1 << k];\n            createParityCheck(paritycheck, k, 0.0);\n\n            // Create LDPC structure\n            BipartiteGraph ldpcG;\n            bool regular;\n            do {\n                if( ldpc == LDPCType::GROUP )\n                    ldpcG = createGroupStructuredLDPCGraph( prime, j, k );\n                else if( ldpc == LDPCType::RANDOM )\n                    ldpcG = createRandomBipartiteGraph( N, K, j, k );\n                else if( ldpc == LDPCType::SMALL )\n                    ldpcG = createSmallLDPCGraph();\n\n                regular = true;\n                for( size_t i = 0; i < N; i++ )\n                    if( ldpcG.nb1(i).size() != j )\n                        regular = false;\n                for( size_t I = 0; I < K; I++ )\n                    if( ldpcG.nb2(I).size() != k )\n                        regular = false;\n            } while( !regular && !ldpcG.isConnected() );\n\n            // Convert to FactorGraph\n            vector<Factor> factors;\n            for( size_t I = 0; I < K; I++ ) {\n                VarSet vs;\n                for( size_t _i = 0; _i < k; _i++ ) {\n                    size_t i = ldpcG.nb2(I)[_i];\n                    vs |= Var( i, 2 );\n                }\n                factors.push_back( Factor( vs, paritycheck ) );\n            }\n            delete paritycheck;\n\n            // Generate noise vector\n            vector<char> noisebits(N,0);\n            size_t bitflips = 0;\n            for( size_t i = 0; i < N; i++ ) {\n                if( rnd_uniform() < noise ) {\n                    noisebits[i] = 1;\n                    bitflips++;\n                }\n            }\n            cout << \"# bitflips = \" << bitflips << endl;\n\n            // Simulate transmission of all-zero codeword\n            vector<char> input(N,0);\n            vector<char> output(N,0);\n            for( size_t i = 0; i < N; i++ )\n                output[i] = (input[i] + noisebits[i]) & 1;\n\n            // Add likelihoods\n            for( size_t i = 0; i < N; i++ )\n               factors.push_back( Factor(Var(i,2), likelihood + output[i]*2) );\n\n            // Construct Factor Graph\n            fg = FactorGraph( factors );\n        } else\n            throw \"Invalid type\";\n\n        // Output additional comments\n        cout << \"# N = \" << fg.nrVars() << endl;\n        cout << \"# seed = \" << seed << endl;\n\n        // Output factor graph\n        cout << fg;\n    } catch( const char *e ) {\n        /// Display error message\n        cerr << \"Error: \" << e << endl;\n        return 1;\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "70abea9a9042ca2d28a7d1159e6aa81557ef5c0d", "size": 28375, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "utils/createfg.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": "utils/createfg.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": "utils/createfg.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": 40.4202279202, "max_line_length": 146, "alphanum_fraction": 0.5273303965, "num_tokens": 7439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.752012562644147, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.45976692449137}}
{"text": "#ifndef SKYLARK_LIBSVM_IO_HPP\n#define SKYLARK_LIBSVM_IO_HPP\n\n#include <memory>\n\n#if SKYLARK_HAVE_BOOST_FILESYSTEM\n#include \"boost/filesystem/operations.hpp\"\n#include \"boost/filesystem/path.hpp\"\nnamespace boostfs = boost::filesystem;\n#endif\n\n#include <unordered_map>\n#include <boost/serialization/list.hpp>\n\n#include \"../types.hpp\"\n#include \"../get_communicator.hpp\"\n\nnamespace skylark { namespace utility { namespace io {\n\n/**\n * Reads X and Y from a file in libsvm format.\n * X and Y are Elemental dense matrices.\n *\n * @param fname input file name.\n * @param X output X\n * @param Y output Y\n * @param direction whether the examples are to be put in rows or columns\n * @param min_d minimum number of rows in the matrix.\n * @param max_n maximum number of columns in the matrix.\n * @param blocksize blocksize for reading for distributed outputs.\n */\ntemplate<typename T, typename R>\nvoid ReadLIBSVM(const std::string& fname,\n    El::Matrix<T>& X, El::Matrix<R>& Y,\n    base::direction_t direction, int min_d = 0, int max_n = -1,\n    int blocksize=10000) {\n\n    std::string line;\n    std::string token, val, ind;\n    R label;\n    unsigned int start = 0;\n    unsigned int t;\n    int n = 0, nt = 0;\n    int d = 0;\n    int i, j, last;\n    char c;\n\n    std::ifstream in(fname);\n\n    if ((in.rdstate() & std::ifstream::failbit) != 0)\n        SKYLARK_THROW_EXCEPTION (\n           base::io_exception()\n               << base::error_msg(\n                \"Failed to open file \" + fname));\n\n    // make one pass over the data to figure out dimensions -\n    // will pay in terms of preallocated storage.\n    while(!in.eof() && n != max_n) {\n        getline(in, line);\n\n        // Ignore empty lines and comment lines (begin with #)\n        if(line.length() == 0 || line[0] == '#')\n            break;\n\n        n++;\n\n        // Figure out number of targets (only first line)\n        if (n == 1) {\n            std::string tstr;\n            std::istringstream tokenstream (line);\n            tokenstream >> tstr;\n            while (tstr.find(\":\") == std::string::npos) {\n                nt++;\n                if (tokenstream.eof())\n                    break;\n                tokenstream >> tstr;\n            }\n        }\n\n        size_t delim = line.find_last_of(\":\");\n        if(delim == std::string::npos)\n            continue;\n\n        t = delim;\n        while(line[t]!=' ') {\n            t--;\n        }\n        val = line.substr(t+1, delim - t);\n        last = atoi(val.c_str());\n        if (last>d)\n            d = last;\n    }\n    if (min_d > 0)\n        d = std::max(d, min_d);\n\n    // prepare for second pass\n    in.clear();\n    in.seekg(0, std::ios::beg);\n\n    if (direction == base::COLUMNS) {\n        X.Resize(d, n);\n        Y.Resize(nt, n);\n    } else {\n        X.Resize(n, d);\n        Y.Resize(n, nt);\n    }\n\n    T *Xdata = X.Buffer();\n    R *Ydata = Y.Buffer();\n    int ldX = X.LDim();\n    int ldY = Y.LDim();\n\n    for (t = 0; t < n; t++) {\n        getline(in, line);\n\n        // Ignore empty lines and comment lines (begin with #)\n        if(line.length() == 0 || line[0] == '#')\n            break;\n\n        std::istringstream tokenstream(line);\n\n        for(int r = 0; r < nt; r++) {\n            tokenstream >> label;\n            if (direction == base::COLUMNS)\n                Ydata[t * ldY + r] = label;\n            else\n                Ydata[r * ldY + t] = label;\n        }\n\n        while (tokenstream >> token) {\n            size_t delim  = token.find(':');\n            ind = token.substr(0, delim);\n            val = token.substr(delim+1); //.substr(delim+1);\n            j = atoi(ind.c_str()) - 1;\n            if (direction == base::COLUMNS)\n                Xdata[t * ldX + j] = atof(val.c_str());\n            else\n                Xdata[j * ldX + t] = atof(val.c_str());\n        }\n    }\n}\n\n/**\n * Reads X and Y from a file in libsvm format.\n * X and Y are Elemental distributed matrices.\n *\n * @param fname input file name.\n * @param X output X\n * @param Y output Y\n * @param direction whether the examples are to be put in rows or columns\n * @param max_n stop reading after n rows. If -1 then will read all rows.\n * @param min_d minimum number of rows in the matrix.\n * @param blocksize blocksize for blocking of read.\n */\ntemplate<typename T, El::Distribution UX, El::Distribution VX,\n         typename R, El::Distribution UY, El::Distribution VY>\nvoid ReadLIBSVM(const std::string& fname,\n    El::DistMatrix<T, UX, VX>& X, El::DistMatrix<R, UY, VY>& Y,\n    base::direction_t direction, int min_d = 0, int max_n = -1,\n    int blocksize = 10000) {\n\n    std::string line;\n    std::string token, val, ind;\n    R label;\n    unsigned int start = 0;\n    size_t delim;\n    unsigned int t;\n    int n = 0, nt = 0;\n    int d = 0;\n    int i, j, last;\n    char c;\n\n    std::ifstream in(fname);\n\n    // TODO check that X and Y have the same grid.\n    boost::mpi::communicator comm = skylark::utility::get_communicator(X);\n    int rank = X.Grid().Rank();\n\n    // make one pass over the data to figure out dimensions -\n    // will pay in terms of preallocated storage.\n    if (rank==0) {\n        while(!in.eof() && n != max_n) {\n            getline(in, line);\n\n            // Ignore empty lines and comment lines (begin with #)\n            if(line.length() == 0 || line[0] == '#')\n                break;\n\n            n++;\n\n            // Figure out number of targets (only first line)\n            if (n == 1) {\n                std::string tstr;\n                std::istringstream tokenstream (line);\n                tokenstream >> tstr;\n                while (tstr.find(\":\") == std::string::npos) {\n                    nt++;\n                    if (tokenstream.eof())\n                        break;\n                    tokenstream >> tstr;\n                }\n            }\n\n            size_t delim = line.find_last_of(\":\");\n            if(delim == std::string::npos)\n                continue;\n\n            t = delim;\n            while(line[t]!=' ')\n                t--;\n\n            val = line.substr(t+1, delim - t);\n            last = atoi(val.c_str());\n            if (last>d)\n                d = last;\n        }\n        if (min_d > 0)\n            d = std::max(d, min_d);\n\n        // prepare for second pass\n        in.clear();\n        in.seekg(0, std::ios::beg);\n    }\n\n    boost::mpi::broadcast(comm, n, 0);\n    boost::mpi::broadcast(comm, d, 0);\n    boost::mpi::broadcast(comm, nt, 0);\n\n    int numblocks = ((int) n/ (int) blocksize); // of size blocksize\n    int leftover = n % blocksize;\n    int block = blocksize;\n\n    if (direction == base::COLUMNS) {\n        X.Resize(d, n);\n        Y.Resize(nt, n);\n    } else {\n        X.Resize(n, d);\n        Y.Resize(n, nt);\n    }\n\n    El::DistMatrix<T, El::CIRC, El::CIRC> XB(X.Grid());\n    El::DistMatrix<R, El::CIRC, El::CIRC> YB(Y.Grid());\n    El::DistMatrix<T, UX, VX> Xv(X.Grid());\n    El::DistMatrix<R, UY, VY> Yv(Y.Grid());\n    for(int i=0; i<numblocks+1; i++) {\n        if (i==numblocks)\n            block = leftover;\n        if (block==0)\n            break;\n\n        if (direction == base::COLUMNS) {\n            El::Zeros(XB, d, block);\n            El::Zeros(YB, nt, block);\n        } else {\n            El::Zeros(XB, block, d);\n            El::Zeros(YB, block, nt);\n        }\n\n        if(rank==0) {\n            T *Xdata = XB.Matrix().Buffer();\n            R *Ydata = YB.Matrix().Buffer();\n            int ldX = XB.Matrix().LDim();\n            int ldY = YB.Matrix().LDim();\n\n            t = 0;\n            while(!in.eof() && t<block) {\n                getline(in, line);\n\n                // Ignore empty lines and comment lines (begin with #)\n                if(line.length() == 0 || line[0] == '#')\n                    break;\n\n                std::istringstream tokenstream(line);\n\n                for(int r = 0; r < nt; r++) {\n                    tokenstream >> label;\n                    if (direction == base::COLUMNS)\n                        Ydata[t * ldY + r] = label;\n                    else\n                        Ydata[r * ldY + t] = label;\n                }\n\n                while (tokenstream >> token) {\n                    size_t delim  = token.find(':');\n                    ind = token.substr(0, delim);\n                    val = token.substr(delim+1); //.substr(delim+1);\n                    j = atoi(ind.c_str()) - 1;\n                    if (direction == base::COLUMNS)\n                        Xdata[t * ldX + j] = atof(val.c_str());\n                    else\n                        Xdata[j * ldX + t] = atof(val.c_str());\n                }\n\n                t++;\n            }\n        }\n\n        // The calls below should distribute the data to all the nodes.\n        if (direction == base::COLUMNS) {\n            int ldX = XB.Matrix().LDim();\n            El::View(Xv, X, 0, i*blocksize, d, block);\n            El::View(Yv, Y, 0, i*blocksize, nt, block);\n        } else {\n            El::View(Xv, X, i*blocksize, 0, block, d);\n            El::View(Yv, Y, i*blocksize, 0, block, nt);\n        }\n\n        Xv = XB;\n        Yv = YB;\n    }\n}\n\n/**\n * Reads X and Y from a file in libsvm format.\n * X is a Skylark local sparse matrix, and Y is Elemental dense matrices.\n *\n * @param fname input file name\n * @param X output X\n * @param Y output Y\n * @param direction whether the examples are to be put in rows or columns\n * @param min_d minimum number of rows in the matrix.\n * @param max_n maximum number of cols in the matrix.\n * @param blocksize blocksize for reading for distributed outputs.\n */\ntemplate<typename T, typename R>\nvoid ReadLIBSVM(const std::string& fname,\n    base::sparse_matrix_t<T>& X, El::Matrix<R>& Y,\n    base::direction_t direction, int min_d = 0, int max_n = -1,\n    int blocksize = 10000) {\n\n    std::string line;\n    std::string token;\n    R label;\n    unsigned int start = 0;\n    unsigned int t;\n    int n = 0, nt = 0;\n    int d = 0;\n    int i, j, last;\n    char c;\n    int nnz=0;\n    int nz;\n\n    std::ifstream in(fname);\n\n    // make one pass over the data to figure out dimensions and nnz\n    // will pay in terms of preallocated storage.\n    // Also find number of non-zeros per column.\n    std::unordered_map<int, int> colsize;\n\n    while(!in.eof() && n != max_n) {\n        getline(in, line);\n\n        // Ignore empty lines and comment lines (begin with #)\n        if(line.length() == 0 || line[0] == '#')\n            break;\n\n        n++;\n\n        // Figure out number of targets (only first line)\n        if (n == 1) {\n            std::string tstr;\n            std::istringstream tokenstream (line);\n            tokenstream >> tstr;\n            while (tstr.find(\":\") == std::string::npos) {\n                nt++;\n                if (tokenstream.eof())\n                    break;\n                tokenstream >> tstr;\n            }\n        }\n\n        if (direction == base::COLUMNS) {\n            size_t delim = line.find_last_of(\":\");\n            if(delim == std::string::npos)\n                continue;\n\n            t = delim;\n            while(line[t]!=' ')\n                t--;\n\n            std::string val = line.substr(t+1, delim - t);\n            last = atoi(val.c_str());\n            if (last>d)\n                d = last;\n\n\n            std::istringstream tokenstream (line);\n            tokenstream >> label;\n            while (tokenstream >> token)\n                nnz++;\n        } else {\n            std::istringstream tokenstream (line);\n            tokenstream >> label;\n\n            while (tokenstream >> token) {\n                nnz++;\n                size_t delim  = token.find(':');\n                int ind = atoi(token.substr(0, delim).c_str());\n\n                colsize[ind-1]++;\n\n                if (ind > d)\n                    d = ind;\n            }\n        }\n    }\n\n    if (min_d > 0)\n        d = std::max(d, min_d);\n\n    T *values = new T[nnz];\n    int *rowind = new int[nnz];\n    int *col_ptr = new int[direction == base::COLUMNS ? n + 1 : d + 1];\n\n    if (direction == base::ROWS) {\n        col_ptr[0] = 0;\n        for(int i = 1; i <= d; i++)\n            col_ptr[i] = col_ptr[i-1] + colsize[i-1];\n        Y.Resize(n, nt);\n    } else\n        Y.Resize(nt, n);\n    R *Ydata = Y.Buffer();\n    int ldY = Y.LDim();\n\n    // prepare for second pass\n    in.clear();\n    in.seekg(0, std::ios::beg);\n    if (direction == base::COLUMNS)\n        nnz = 0;\n\n    colsize.clear();\n    for (t = 0; t < n; t++) {\n        getline(in, line);\n\n        // Ignore empty lines and comment lines (begin with #)\n        if(line.length() == 0 || line[0] == '#')\n            break;\n\n        std::istringstream tokenstream (line);\n\n        for(int r = 0; r < nt; r++) {\n            tokenstream >> label;\n            if (direction == base::COLUMNS)\n                Ydata[t * ldY + r] = label;\n            else\n                Ydata[r * ldY + t] = label;\n        }\n\n        if (direction == base::COLUMNS)\n            col_ptr[t] = nnz;\n\n        while (tokenstream >> token) {\n            size_t delim  = token.find(':');\n            std::string ind = token.substr(0, delim);\n            std::string val = token.substr(delim+1); //.substr(delim+1);\n            j = atoi(ind.c_str()) - 1;\n\n            if (direction == base::COLUMNS) {\n                rowind[nnz] = j;\n                values[nnz] = atof(val.c_str());\n                nnz++;\n            } else {\n                rowind[col_ptr[j] + colsize[j]] = t;\n                values[col_ptr[j] + colsize[j]] = atof(val.c_str());\n                colsize[j]++;\n            }\n        }\n    }\n\n    if (min_d > 0)\n        d = std::max(d, min_d);\n\n    if (direction == base::COLUMNS) {\n        col_ptr[n] = nnz; // last entry (total number of nnz)\n        X.attach(col_ptr, rowind, values, nnz, d, n, true);\n    } else\n        X.attach(col_ptr, rowind, values, nnz, n, d, true);\n}\n\n/**\n * Reads X and Y from a file in libsvm format.\n * X is a sparse distributed VC/STAR matrix and Y is a dense distributed\n * VC/STAR matrix.\n *\n * IMPORTANT: output is in column-major format (the rows are features).\n *\n * @param fname input file name.\n * @param X output X\n * @param Y output Y\n * @param direction whether the examples are to be put in rows or columns\n * @param min_d minimum number of rows in the matrix.\n * @param blocksize blocksize for blocking of read.\n */\ntemplate<typename T,\n         typename R, El::Distribution UY, El::Distribution VY>\nvoid ReadLIBSVM(const std::string& fname,\n    base::sparse_vc_star_matrix_t<T>& X, El::DistMatrix<R, UY, VY>& Y,\n    base::direction_t direction, int min_d = 0, int max_n = -1,\n    int blocksize = 10000) {\n\n\n    std::string line;\n    std::string token, val, ind;\n    T label;\n    unsigned int start = 0;\n    unsigned int delim, t;\n    int n = 0, nt = 0;\n    int d = 0;\n    int i, j, last;\n    char c;\n\n    std::ifstream in(fname);\n\n    boost::mpi::communicator comm = skylark::utility::get_communicator(Y);\n    int rank = comm.rank();\n    int size = comm.size();\n\n    std::vector< std::list<int> > non_local_updates_j(size);\n    std::vector< std::list<int> > non_local_updates_row(size);\n    std::vector< std::list<T> > non_local_updates_v(size);\n\n    // make one pass over the data to figure out dimensions -\n    // will pay in terms of preallocated storage.\n    if (rank==0) {\n        while(!in.eof() && n != max_n) {\n            getline(in, line);\n            if(line.length()==0)\n                break;\n            delim = line.find_last_of(\":\");\n            if(delim > line.length())\n                continue;\n            n++;\n\n            // Figure out number of targets\n            if (n == 1) {\n                std::string tstr;\n                std::istringstream tokenstream (line);\n                tokenstream >> tstr;\n                while (tstr.find(\":\") == std::string::npos) {\n                    nt++;\n                    tokenstream >> tstr;\n                }\n            }\n\n            t = delim;\n            while(line[t]!=' ') {\n                t--;\n            }\n            val = line.substr(t+1, delim - t);\n            last = atoi(val.c_str());\n            if (last>d)\n                d = last;\n        }\n        if (min_d > 0)\n            d = std::max(d, min_d);\n\n        // prepare for second pass\n        in.clear();\n        in.seekg(0, std::ios::beg);\n    }\n\n    boost::mpi::broadcast(comm, n, 0);\n    boost::mpi::broadcast(comm, d, 0);\n    boost::mpi::broadcast(comm, nt, 0);\n\n    int numblocks = ((int) n/ (int) blocksize); // of size blocksize\n    int leftover = n % blocksize;\n    int block = blocksize;\n\n    if (direction == base::COLUMNS) {\n        X.resize(d, n);\n        Y.Resize(nt, n);\n    } else {\n        X.resize(n, d);\n        Y.Resize(n, nt);\n    }\n\n    El::DistMatrix<T, El::CIRC, El::CIRC> YB(Y.Grid());\n    El::DistMatrix<T, El::VC, El::STAR> Yv(Y.Grid());\n\n    int row = 0;\n    for(int i=0; i<numblocks+1; i++) {\n        if (i==numblocks)\n            block = leftover;\n        if (block==0)\n            break;\n\n        if (direction == base::COLUMNS) {\n            El::Zeros(YB, nt, block);\n        } else {\n            El::Zeros(YB, block, nt);\n        }\n\n        if(rank==0) {\n            T *Ydata = YB.Matrix().Buffer();\n            int ldY = YB.Matrix().LDim();\n\n            t = 0;\n            while(!in.eof() && t<block) {\n                getline(in, line);\n                if( line.length()==0)\n                    break;\n\n                std::istringstream tokenstream (line);\n                for(int r = 0; r < nt; r++) {\n                    tokenstream >> label;\n                    if (direction == base::COLUMNS)\n                        Ydata[t * ldY + r] = label;\n                    else\n                        Ydata[r * ldY + t] = label;\n                }\n\n                while (tokenstream >> token) {\n                    delim  = token.find(':');\n                    ind = token.substr(0, delim);\n                    val = token.substr(delim+1); //.substr(delim+1);\n                    j = atoi(ind.c_str()) - 1;\n                    int owner = (direction == base::COLUMNS) ?\n                        X.owner(j, row) : X.owner(row, j);\n                    if (owner == 0) {\n                        if (direction == base::COLUMNS)\n                            X.queue_update(j, row, atof(val.c_str()));\n                        else\n                            X.queue_update(row, j, atof(val.c_str()));\n                    } else {\n                        non_local_updates_j[owner].push_back(j);\n                        non_local_updates_row[owner].push_back(row);\n                        non_local_updates_v[owner].push_back(atof(val.c_str()));\n                    }\n                }\n\n                row++;\n                t++;\n            }\n\n            for (int rk = 1; rk < size; rk++) {\n                comm.send(rk, 0, non_local_updates_j[rk]);\n                comm.send(rk, 0, non_local_updates_row[rk]);\n                comm.send(rk, 0, non_local_updates_v[rk]);\n\n                non_local_updates_j[rk].clear();\n                non_local_updates_row[rk].clear();\n                non_local_updates_v[rk].clear();\n            }\n        } else {\n                comm.recv(0, 0, non_local_updates_j[rank]);\n                comm.recv(0, 0, non_local_updates_row[rank]);\n                comm.recv(0, 0, non_local_updates_v[rank]);\n\n                auto it_j = non_local_updates_j[rank].begin();\n                auto it_row = non_local_updates_row[rank].begin();\n                auto it_v = non_local_updates_v[rank].begin();\n\n                for(; it_j != non_local_updates_j[rank].end();) {\n\n                    int j = *it_j, row = *it_row;\n                    T val = *it_v;\n\n                    if (direction == base::COLUMNS)\n                        X.queue_update(j, row, val);\n                    else\n                        X.queue_update(row, j, val);\n\n                    it_j++; it_row++; it_v++;\n                }\n\n                non_local_updates_j[rank].clear();\n                non_local_updates_row[rank].clear();\n                non_local_updates_v[rank].clear();\n        }\n\n        // The calls below should distribute the data to all the nodes.\n        if (direction == base::COLUMNS) {\n            El::View(Yv, Y, 0, i*blocksize, nt, block);\n        } else {\n            El::View(Yv, Y, i*blocksize, 0, block, nt);\n        }\n\n        Yv = YB;\n    }\n\n    X.finalize();\n}\n\nvoid ReadLIBSVM(const std::string& fname,\n    boost::any X, boost::any Y,\n    base::direction_t direction, int min_d = 0, int max_n = -1,\n    int blocksize = 10000) {\n\n#define SKYLARK_READLIBSVM_APPLY_DISPATCH(XT, YT)                   \\\n    if (X.type() == typeid(XT*) && Y.type() == typeid(YT*))  {      \\\n        ReadLIBSVM(fname, *boost::any_cast<XT*>(X),                 \\\n            *boost::any_cast<YT*>(Y), direction,                    \\\n            min_d, max_n, blocksize);                               \\\n            return;                                                 \\\n    }                                       \\\n\n#if !(defined SKYLARK_NO_ANY)\n    SKYLARK_READLIBSVM_APPLY_DISPATCH(mdtypes::matrix_t, mdtypes::matrix_t);\n    SKYLARK_READLIBSVM_APPLY_DISPATCH(mdtypes::matrix_t, mftypes::matrix_t);\n    SKYLARK_READLIBSVM_APPLY_DISPATCH(mftypes::matrix_t, mdtypes::matrix_t);\n    SKYLARK_READLIBSVM_APPLY_DISPATCH(mftypes::matrix_t, mftypes::matrix_t);\n\n    SKYLARK_READLIBSVM_APPLY_DISPATCH(mdtypes::shared_matrix_t,\n        mdtypes::shared_matrix_t);\n    SKYLARK_READLIBSVM_APPLY_DISPATCH(mdtypes::shared_matrix_t,\n        mftypes::shared_matrix_t);\n    SKYLARK_READLIBSVM_APPLY_DISPATCH(mftypes::shared_matrix_t,\n        mdtypes::shared_matrix_t);\n    SKYLARK_READLIBSVM_APPLY_DISPATCH(mftypes::shared_matrix_t,\n        mftypes::shared_matrix_t);\n\n    SKYLARK_READLIBSVM_APPLY_DISPATCH(mdtypes::root_matrix_t,\n        mdtypes::root_matrix_t);\n    SKYLARK_READLIBSVM_APPLY_DISPATCH(mdtypes::root_matrix_t,\n        mftypes::root_matrix_t);\n    SKYLARK_READLIBSVM_APPLY_DISPATCH(mftypes::root_matrix_t,\n        mdtypes::root_matrix_t);\n    SKYLARK_READLIBSVM_APPLY_DISPATCH(mftypes::root_matrix_t,\n        mftypes::root_matrix_t);\n\n    SKYLARK_READLIBSVM_APPLY_DISPATCH(mdtypes::sparse_matrix_t,\n        mdtypes::matrix_t);\n    SKYLARK_READLIBSVM_APPLY_DISPATCH(mdtypes::sparse_matrix_t,\n        mftypes::matrix_t);\n    SKYLARK_READLIBSVM_APPLY_DISPATCH(mftypes::sparse_matrix_t,\n        mdtypes::matrix_t);\n    SKYLARK_READLIBSVM_APPLY_DISPATCH(mftypes::sparse_matrix_t,\n        mftypes::matrix_t);\n\n    SKYLARK_READLIBSVM_APPLY_DISPATCH(mdtypes::dist_matrix_t,\n        mdtypes::dist_matrix_t);\n    SKYLARK_READLIBSVM_APPLY_DISPATCH(mdtypes::dist_matrix_t,\n        mftypes::dist_matrix_t);\n    SKYLARK_READLIBSVM_APPLY_DISPATCH(mftypes::dist_matrix_t,\n        mdtypes::dist_matrix_t);\n    SKYLARK_READLIBSVM_APPLY_DISPATCH(mftypes::dist_matrix_t,\n        mftypes::dist_matrix_t);\n\n    SKYLARK_READLIBSVM_APPLY_DISPATCH(mdtypes::dist_matrix_vc_star_t,\n        mdtypes::dist_matrix_vc_star_t);\n    SKYLARK_READLIBSVM_APPLY_DISPATCH(mdtypes::dist_matrix_vc_star_t,\n        mftypes::dist_matrix_vc_star_t);\n    SKYLARK_READLIBSVM_APPLY_DISPATCH(mftypes::dist_matrix_vc_star_t,\n        mdtypes::dist_matrix_vc_star_t);\n    SKYLARK_READLIBSVM_APPLY_DISPATCH(mftypes::dist_matrix_vc_star_t,\n        mftypes::dist_matrix_vc_star_t);\n\n    SKYLARK_READLIBSVM_APPLY_DISPATCH(mdtypes::dist_matrix_vr_star_t,\n        mdtypes::dist_matrix_vr_star_t);\n    SKYLARK_READLIBSVM_APPLY_DISPATCH(mdtypes::dist_matrix_vr_star_t,\n        mftypes::dist_matrix_vr_star_t);\n    SKYLARK_READLIBSVM_APPLY_DISPATCH(mftypes::dist_matrix_vr_star_t,\n        mdtypes::dist_matrix_vr_star_t);\n    SKYLARK_READLIBSVM_APPLY_DISPATCH(mftypes::dist_matrix_vr_star_t,\n        mftypes::dist_matrix_vr_star_t);\n\n    SKYLARK_READLIBSVM_APPLY_DISPATCH(mdtypes::dist_matrix_star_vc_t,\n        mdtypes::dist_matrix_star_vc_t);\n    SKYLARK_READLIBSVM_APPLY_DISPATCH(mdtypes::dist_matrix_star_vc_t,\n        mftypes::dist_matrix_star_vc_t);\n    SKYLARK_READLIBSVM_APPLY_DISPATCH(mftypes::dist_matrix_star_vc_t,\n        mdtypes::dist_matrix_star_vc_t);\n    SKYLARK_READLIBSVM_APPLY_DISPATCH(mftypes::dist_matrix_star_vc_t,\n        mftypes::dist_matrix_star_vc_t);\n\n    SKYLARK_READLIBSVM_APPLY_DISPATCH(mdtypes::dist_matrix_star_vr_t,\n        mdtypes::dist_matrix_star_vr_t);\n    SKYLARK_READLIBSVM_APPLY_DISPATCH(mdtypes::dist_matrix_star_vr_t,\n        mftypes::dist_matrix_star_vr_t);\n    SKYLARK_READLIBSVM_APPLY_DISPATCH(mftypes::dist_matrix_star_vr_t,\n        mdtypes::dist_matrix_star_vr_t);\n    SKYLARK_READLIBSVM_APPLY_DISPATCH(mftypes::dist_matrix_star_vr_t,\n        mftypes::dist_matrix_star_vr_t);\n\n#endif\n\n    SKYLARK_THROW_EXCEPTION (\n        base::io_exception()\n          << base::error_msg(\n           \"This combination has not yet been implemented for ReadLIBSVM\"));\n\n#undef SKYLARK_READLIBSVM_APPLY_DISPATCH\n}\n\n/**\n * Write X and Y from a file in libsvm format.\n * X and Y are Elemental dense matrices.\n *\n * @param fname output file name.\n * @param X input X\n * @param Y output Y\n * @param direction whether the examples are in the rows or columns of X and Y\n */\ntemplate<typename T, typename R>\nvoid WriteLIBSVM(const std::string& fname,\n    El::Matrix<T>& X, El::Matrix<R>& Y,\n    base::direction_t direction) {\n\n    std::ofstream out(fname);\n    El::Int n, d;\n\n    if (direction == base::COLUMNS) {\n        n = X.Width();\n        d = X.Height();\n    } else {\n        n = X.Height();\n        d = X.Width();\n    }\n\n    for(El::Int j = 0; j < n; j++) {\n        if (direction == base::COLUMNS) {\n            out << Y.Get(0, j) << \" \";\n            for(El::Int r = 0; r < d; r++) {\n                T val = X.Get(r, j);\n                if (val != 0.0)\n                    out << (r+1) << \":\" << val << \" \";\n            }\n            out << std::endl;\n        } else {\n            out << Y.Get(j, 0) << \" \";\n            for(El::Int r = 0; r < d; r++) {\n                T val = X.Get(j, r);\n                if (val != 0.0)\n                    out << (r+1) << \":\" << val << \" \";\n            }\n            out << std::endl;\n        }\n    }\n\n    out.close();\n}\n\n/**\n * Write X and Y from a file in libsvm format.\n * X and Y are Elemental distributed matrices.\n *\n * @param fname output file name.\n * @param X input X\n * @param Y output Y\n * @param direction whether the examples are in the rows or columns of X and Y\n * @param blocksize blocksize for blocking of read.\n */\ntemplate<typename T, El::Distribution UX, El::Distribution VX,\n         typename R, El::Distribution UY, El::Distribution VY>\nvoid WriteLIBSVM(const std::string& fname,\n    El::DistMatrix<T, UX, VX>& X, El::DistMatrix<R, UY, VY>& Y,\n    base::direction_t direction, int blocksize = 10000) {\n\n    int rank = X.Grid().Rank();\n\n    std::ofstream out(fname);\n    El::Int n, d;\n\n    if (direction == base::COLUMNS) {\n        n = X.Width();\n        d = X.Height();\n    } else {\n        n = X.Height();\n        d = X.Width();\n    }\n\n    El::Int numblocks = ((int) n/ (int) blocksize);\n    El::Int leftover = n % blocksize;\n    El::Int block = blocksize;\n\n    El::DistMatrix<T, El::CIRC, El::CIRC> XB(X.Grid());\n    El::DistMatrix<R, El::CIRC, El::CIRC> YB(Y.Grid());\n    El::DistMatrix<T, UX, VX> Xv(X.Grid());\n    El::DistMatrix<R, UY, VY> Yv(Y.Grid());\n    for(El::Int i = 0; i < numblocks + 1; i++) {\n        if (i == numblocks)\n            block = leftover;\n        if (block == 0)\n            break;\n\n        // The calls below should distribute the data to all the nodes.\n        if (direction == base::COLUMNS) {\n            El::View(Xv, X, 0, i*blocksize, d, block);\n            El::View(Yv, Y, 0, i*blocksize, 1, block);\n        } else {\n            El::View(Xv, X, i*blocksize, 0, block, d);\n            El::View(Yv, Y, i*blocksize, 0, block, 1);\n        }\n\n        XB = Xv;\n        YB = Yv;\n\n        if(rank==0)\n            for(El::Int j = 0; j < block; j++) {\n                if (direction == base::COLUMNS) {\n                    out << YB.Get(0, j) << \" \";\n                    for(El::Int r = 0; r < d; r++) {\n                        T val = XB.Get(r, j);\n                        if (val != 0.0)\n                            out << (r+1) << \":\" << val << \" \";\n                    }\n                    out << std::endl;\n                } else {\n                        out << YB.Get(j, 0) << \" \";\n                        for(El::Int r = 0; r < d; r++) {\n                            T val = XB.Get(j, r);\n                            if (val != 0.0)\n                                out << (r+1) << \":\" << val << \" \";\n                        }\n                        out << std::endl;\n                }\n            }\n    }\n    out.close();\n}\n\n#if SKYLARK_HAVE_BOOST_FILESYSTEM\n\n/**\n * Reads X and Y from a directory of files in libsvm format.\n * X and Y are Elemental dense matrices.\n *\n * @param fname input file name\n * @param X output X\n * @param Y output Y\n * @param direction whether the examples are to be put in rows or columns\n * @param min_d minimum number of rows in the matrix.\n */\ntemplate<typename T, typename R>\nvoid ReadDirLIBSVM(const std::string& dname,\n    El::Matrix<T>& X, El::Matrix<R>& Y,\n    base::direction_t direction, int min_d = 0) {\n\n    std::string line;\n    std::string token;\n    R label;\n    unsigned int start = 0;\n    unsigned int t;\n    int n = 0, nt = 0;\n    int d = 0;\n    int i, j, last;\n    char c;\n    int nnz=0;\n    int nz;\n\n    boostfs::path full_path(boostfs::system_complete(boostfs::path(dname)));\n    boostfs::directory_iterator end_iter;\n\n    for(boostfs::directory_iterator dirit(full_path); dirit != end_iter;\n        dirit++) {\n\n        std::string fname = dirit->path().filename().string();\n        if (fname == \".\" || fname == \"..\" || fname[0] == '.')\n            continue;\n\n        std::ifstream in(dirit->path().string());\n\n        while(!in.eof()) {\n            getline(in, line);\n\n            // Ignore empty lines and comment lines (begin with #)\n            if(line.length() == 0 || line[0] == '#')\n                break;\n\n            n++;\n\n            // Figure out number of targets (only first line)\n            if (n == 1) {\n                std::string tstr;\n                std::istringstream tokenstream (line);\n                tokenstream >> tstr;\n                while (tstr.find(\":\") == std::string::npos) {\n                    nt++;\n                    if (tokenstream.eof())\n                        break;\n                    tokenstream >> tstr;\n                }\n            }\n\n            if (direction == base::COLUMNS) {\n                size_t delim = line.find_last_of(\":\");\n                if(delim == std::string::npos)\n                    continue;\n\n                t = delim;\n                while(line[t]!=' ')\n                    t--;\n                std::string val = line.substr(t+1, delim - t);\n                last = atoi(val.c_str());\n                if (last>d)\n                    d = last;\n\n\n                std::istringstream tokenstream (line);\n                tokenstream >> label;\n                while (tokenstream >> token)\n                    nnz++;\n            } else {\n                std::istringstream tokenstream (line);\n                tokenstream >> label;\n\n                while (tokenstream >> token) {\n                    nnz++;\n                    size_t delim  = token.find(':');\n                    int ind = atoi(token.substr(0, delim).c_str());\n\n                    if (ind > d)\n                        d = ind;\n                }\n            }\n        }\n\n        in.close();\n    }\n\n    if (min_d > 0)\n        d = std::max(d, min_d);\n\n\n    if (direction == base::ROWS) {\n        X.Resize(n, d);\n        Y.Resize(n, nt);\n    } else {\n        X.Resize(d, n);\n        Y.Resize(nt, n);\n    }\n\n    T *Xdata = X.Buffer();\n    El::Int ldX = X.LDim();\n    R *Ydata = Y.Buffer();\n    El::Int ldY = Y.LDim();\n\n    // prepare for second pass\n    t = 0;\n\n    for(boostfs::directory_iterator dirit(full_path); dirit != end_iter;\n        dirit++) {\n\n        std::string fname = dirit->path().filename().string();\n        if (fname == \".\" || fname == \"..\" || fname[0] == '.')\n            continue;\n\n        std::ifstream in(dirit->path().string());\n        while(!in.eof()) {\n            getline(in, line);\n\n            // Ignore empty lines and comment lines (begin with #)\n            if(line.length() == 0 || line[0] == '#')\n                break;\n            t++;\n\n            std::istringstream tokenstream (line);\n\n            for(int r = 0; r < nt; r++) {\n                tokenstream >> label;\n                if (direction == base::COLUMNS)\n                    Ydata[t * ldY + r] = label;\n                else\n                    Ydata[r * ldY + t] = label;\n            }\n\n            while (tokenstream >> token) {\n                size_t delim  = token.find(':');\n                std::string ind = token.substr(0, delim);\n                std::string val = token.substr(delim+1); //.substr(delim+1);\n                j = atoi(ind.c_str()) - 1;\n\n                if (direction == base::COLUMNS)\n                    Xdata[t * ldX + j] = atof(val.c_str());\n                else\n                    Xdata[j * ldX + t] = atof(val.c_str());\n\n            }\n        }\n    }\n}\n\n/**\n * Reads X and Y from a directory of files in libsvm format.\n * X is a Skylark local sparse matrix, and Y is Elemental dense matrices.\n *\n * @param fname input file name\n * @param X output X\n * @param Y output Y\n * @param direction whether the examples are to be put in rows or columns\n * @param min_d minimum number of rows in the matrix.\n */\ntemplate<typename T, typename R>\nvoid ReadDirLIBSVM(const std::string& dname,\n    base::sparse_matrix_t<T>& X, El::Matrix<R>& Y,\n    base::direction_t direction, int min_d = 0) {\n\n    std::string line;\n    std::string token;\n    R label;\n    unsigned int start = 0;\n    unsigned int t;\n    int n = 0, nt = 0;\n    int d = 0;\n    int i, j, last;\n    char c;\n    int nnz=0;\n    int nz;\n\n    boostfs::path full_path(boostfs::system_complete(boostfs::path(dname)));\n    boostfs::directory_iterator end_iter;\n\n    // make one pass over the data to figure out dimensions and nnz\n    // will pay in terms of preallocated storage.\n    // Also find number of non-zeros per column.\n    std::unordered_map<int, int> colsize;\n\n    for(boostfs::directory_iterator dirit(full_path); dirit != end_iter;\n        dirit++) {\n\n        std::string fname = dirit->path().filename().string();\n        if (fname == \".\" || fname == \"..\" || fname[0] == '.')\n            continue;\n\n        std::ifstream in(dirit->path().string());\n\n        while(!in.eof()) {\n            getline(in, line);\n\n            // Ignore empty lines and comment lines (begin with #)\n            if(line.length() == 0 || line[0] == '#')\n                break;\n\n            n++;\n\n            // Figure out number of targets (only first line)\n            if (n == 1) {\n                std::string tstr;\n                std::istringstream tokenstream (line);\n                tokenstream >> tstr;\n                while (tstr.find(\":\") == std::string::npos) {\n                    nt++;\n                    if (tokenstream.eof())\n                        break;\n                    tokenstream >> tstr;\n                }\n            }\n\n            if (direction == base::COLUMNS) {\n                size_t delim = line.find_last_of(\":\");\n                if(delim == std::string::npos)\n                    continue;\n\n                t = delim;\n                while(line[t]!=' ')\n                    t--;\n                std::string val = line.substr(t+1, delim - t);\n                last = atoi(val.c_str());\n                if (last>d)\n                    d = last;\n\n\n                std::istringstream tokenstream (line);\n                tokenstream >> label;\n                while (tokenstream >> token)\n                    nnz++;\n            } else {\n                std::istringstream tokenstream (line);\n                tokenstream >> label;\n\n                while (tokenstream >> token) {\n                    nnz++;\n                    size_t delim  = token.find(':');\n                    int ind = atoi(token.substr(0, delim).c_str());\n\n                    colsize[ind-1]++;\n                    if (ind > d)\n                        d = ind;\n                }\n            }\n        }\n\n        in.close();\n    }\n\n    if (min_d > 0)\n        d = std::max(d, min_d);\n\n    T *values = new T[nnz];\n    int *rowind = new int[nnz];\n    int *col_ptr = new int[direction == base::COLUMNS ? n + 1 : d + 1];\n\n    if (direction == base::ROWS) {\n        col_ptr[0] = 0;\n        for(int i = 1; i <= d; i++)\n            col_ptr[i] = col_ptr[i-1] + colsize[i-1];\n        Y.Resize(n, nt);\n    } else\n        Y.Resize(nt, n);\n\n    R *Ydata = Y.Buffer();\n    int ldY = Y.LDim();\n\n    // prepare for second pass\n    colsize.clear();\n    t = 0;\n\n    for(boostfs::directory_iterator dirit(full_path); dirit != end_iter;\n        dirit++) {\n\n        std::string fname = dirit->path().filename().string();\n        if (fname == \".\" || fname == \"..\" || fname[0] == '.')\n            continue;\n\n        std::ifstream in(dirit->path().string());\n        while(!in.eof()) {\n            getline(in, line);\n\n            // Ignore empty lines and comment lines (begin with #)\n            if(line.length() == 0 || line[0] == '#')\n                break;\n            t++;\n\n            std::istringstream tokenstream (line);\n\n            for(int r = 0; r < nt; r++) {\n                tokenstream >> label;\n                if (direction == base::COLUMNS)\n                    Ydata[t * ldY + r] = label;\n                else\n                    Ydata[r * ldY + t] = label;\n            }\n            if (direction == base::COLUMNS)\n                col_ptr[t] = nnz;\n\n            while (tokenstream >> token) {\n                size_t delim  = token.find(':');\n                std::string ind = token.substr(0, delim);\n                std::string val = token.substr(delim+1); //.substr(delim+1);\n                j = atoi(ind.c_str()) - 1;\n\n                if (direction == base::COLUMNS) {\n                    rowind[nnz] = j;\n                    values[nnz] = atof(val.c_str());\n                    nnz++;\n                } else {\n                    rowind[col_ptr[j] + colsize[j]] = t;\n                    values[col_ptr[j] + colsize[j]] = atof(val.c_str());\n                    colsize[j]++;\n                }\n            }\n        }\n    }\n\n    if (direction == base::COLUMNS) {\n        col_ptr[n] = nnz; // last entry (total number of nnz)\n        X.attach(col_ptr, rowind, values, nnz, d, n, true);\n    } else\n        X.attach(col_ptr, rowind, values, nnz, n, d, true);\n}\n\n/**\n * reads x and y from a directory of files in libsvm format.\n * x and y are elemental distributed matrices.\n *\n * @param fname input file name.\n * @param x output x\n * @param y output y\n * @param direction whether the examples are to be put in rows or columns\n * @param min_d minimum number of rows in the matrix.\n * @param blocksize blocksize for blocking of read.\n */\ntemplate<typename T, El::Distribution UX, El::Distribution VX,\n         typename R, El::Distribution UY, El::Distribution VY>\nvoid ReadDirLIBSVM(const std::string& dname,\n    El::DistMatrix<T, UX, VX>& X, El::DistMatrix<R, UY, VY>& Y,\n    base::direction_t direction, int min_d = 0, int blocksize = 10000) {\n\n\n    std::string line;\n    std::string token, val, ind;\n    R label;\n    unsigned int start = 0;\n    unsigned int t;\n    int n = 0, nt = 0;\n    int d = 0;\n    int i, j, last;\n    char c;\n\n    // TODO check that X and Y have the same grid.\n    boost::mpi::communicator comm = skylark::utility::get_communicator(X);\n    int rank = X.Grid().Rank();\n\n    boostfs::path full_path(boostfs::system_complete(boostfs::path(dname)));\n    boostfs::directory_iterator end_iter;\n\n    // make one pass over the data to figure out dimensions -\n    // will pay in terms of preallocated storage.\n    if (rank==0) {\n        for(boostfs::directory_iterator dirit(full_path); dirit != end_iter;\n            dirit++) {\n\n            std::string fname = dirit->path().filename().string();\n            if (fname == \".\" || fname == \"..\" || fname[0] == '.')\n                continue;\n\n            std::ifstream in(dirit->path().string());\n\n            while(!in.eof()) {\n                getline(in, line);\n\n                // Ignore empty lines and comment lines (begin with #)\n                if(line.length() == 0 || line[0] == '#')\n                    break;\n\n                n++;\n\n                // Figure out number of targets (only first line)\n                if (n == 1) {\n                    std::string tstr;\n                    std::istringstream tokenstream (line);\n                    tokenstream >> tstr;\n                    while (tstr.find(\":\") == std::string::npos) {\n                        nt++;\n                        if (tokenstream.eof())\n                            break;\n                        tokenstream >> tstr;\n                    }\n                }\n\n                size_t delim = line.find_last_of(\":\");\n                if(delim == std::string::npos)\n                    continue;\n\n                t = delim;\n                while(line[t]!=' ') {\n                    t--;\n                }\n                val = line.substr(t+1, delim - t);\n                last = atoi(val.c_str());\n                if (last>d)\n                    d = last;\n            }\n\n            in.close();\n        }\n\n        if (min_d > 0)\n            d = std::max(d, min_d);\n    }\n\n    boost::mpi::broadcast(comm, n, 0);\n    boost::mpi::broadcast(comm, d, 0);\n    boost::mpi::broadcast(comm, nt, 0);\n\n    int numblocks = ((int) n/ (int) blocksize); // of size blocksize\n    int leftover = n % blocksize;\n    int block = blocksize;\n\n    if (direction == base::COLUMNS) {\n        X.Resize(d, n);\n        Y.Resize(nt, n);\n    } else {\n        X.Resize(n, d);\n        Y.Resize(n, nt);\n    }\n\n    El::DistMatrix<T, El::CIRC, El::CIRC> XB(X.Grid()), YB(Y.Grid());\n    El::DistMatrix<T, UX, VX> Xv(X.Grid());\n    El::DistMatrix<R, UY, VY> Yv(Y.Grid());\n    boostfs::directory_iterator dirit(full_path);\n\n    std::ifstream in;\n    if (rank == 0) {\n        std::string fname = dirit->path().filename().string();\n        while (fname == \".\" || fname == \"..\" || fname[0] == '.') {\n            dirit++;\n            if (dirit == end_iter)\n                break;\n            fname = dirit->path().filename().string();\n        }\n\n        in.open(dirit->path().string());\n\n        dirit++;\n    }\n\n    for(int i=0; i<numblocks+1; i++) {\n        if (i==numblocks)\n            block = leftover;\n        if (block==0)\n            break;\n\n        if (direction == base::COLUMNS) {\n            El::Zeros(XB, d, block);\n            El::Zeros(YB, nt, block);\n        } else {\n            El::Zeros(XB, block, d);\n            El::Zeros(YB, block, nt);\n        }\n\n        if(rank==0) {\n            T *Xdata = XB.Matrix().Buffer();\n            R *Ydata = YB.Matrix().Buffer();\n            int ldX = XB.Matrix().LDim();\n            int ldY = YB.Matrix().LDim();\n\n            t = 0;\n            while(t<block) {\n                if (in.eof()) {\n                    if (dirit == end_iter)\n                        break;\n\n                    in.close();\n\n                    std::string fname = dirit->path().filename().string();\n                    while (fname == \".\" || fname == \"..\" || fname[0] == '.') {\n                        dirit++;\n                        if (dirit == end_iter)\n                            break;\n\n                        fname = dirit->path().filename().string();\n                    }\n\n                    if (dirit == end_iter)\n                        break;\n\n                    in.open(dirit->path().string());\n                    dirit++;\n                }\n\n                getline(in, line);\n\n                // Ignore empty lines and comment lines (begin with #)\n                if(line.length() == 0 || line[0] == '#')\n                    break;\n\n                std::istringstream tokenstream (line);\n                for(int r = 0; r < nt; r++) {\n                    tokenstream >> label;\n                    if (direction == base::COLUMNS)\n                        Ydata[t * ldY + r] = label;\n                    else\n                        Ydata[r * ldY + t] = label;\n                }\n\n                while (tokenstream >> token) {\n                    size_t delim  = token.find(':');\n                    ind = token.substr(0, delim);\n                    val = token.substr(delim+1); //.substr(delim+1);\n                    j = atoi(ind.c_str()) - 1;\n                    if (direction == base::COLUMNS)\n                        Xdata[t * ldX + j] = atof(val.c_str());\n                    else\n                        Xdata[j * ldX + t] = atof(val.c_str());\n                }\n\n                t++;\n            }\n        }\n\n        // The calls below should distribute the data to all the nodes.\n        if (direction == base::COLUMNS) {\n            int ldX = XB.Matrix().LDim();\n            El::View(Xv, X, 0, i*blocksize, d, block);\n            El::View(Yv, Y, 0, i*blocksize, nt, block);\n        } else {\n            El::View(Xv, X, i*blocksize, 0, block, d);\n            El::View(Yv, Y, i*blocksize, 0, block, nt);\n        }\n\n        Xv = XB;\n        Yv = YB;\n    }\n\n    if (rank == 0)\n        in.close();\n}\n\ntemplate<typename T,\n         typename R, El::Distribution UY, El::Distribution VY>\nvoid ReadDirLIBSVM(const std::string& dname,\n    base::sparse_vc_star_matrix_t<T>& X, El::DistMatrix<R, UY, VY>& Y,\n    base::direction_t direction, int min_d = 0, int blocksize = 10000) {\n\n    SKYLARK_THROW_EXCEPTION(skylark::base::io_exception() <<\n        skylark::base::error_msg(\n            \"readdirlibsvm not implemented for sparse_vc_star_matrix_t!\"));\n}\n\n#else\n\ntemplate<typename XType, typename YType>\nvoid ReadDirLIBSVM(const std::string& dname, XType& X, YType& Y,\n    base::direction_t direction, int min_d = 0, int blocksize = 10000) {\n\n    SKYLARK_THROW_EXCEPTION(base::io_exception() <<\n        base::error_msg(\"Install Boost Filesystem for ReadDir support!\"));\n\n}\n\n#endif\n\n#if SKYLARK_HAVE_LIBHDFS\n\n/**\n * Reads X and Y from a file in libsvm format (from HDFS filesystem).\n * X and Y are Elemental dense matrices.\n *\n * @param fs hdfs filesystem\n * @param fname input file name.\n * @param X output X\n * @param Y output Y\n * @param direction whether the examples are to be put in rows or columns\n * @param min_d minimum number of rows in the matrix.\n */\ntemplate<typename T, typename R>\nvoid ReadLIBSVM(const hdfsFS &fs, const std::string& fname,\n    El::Matrix<T>& X, El::Matrix<R>& Y,\n    base::direction_t direction, int min_d = 0) {\n\n    std::string line;\n    std::string token, val, ind;\n    R label;\n    unsigned int start = 0;\n    unsigned int t;\n    int n = 0, nt = 0;\n    int d = 0;\n    int i, j, last;\n    char c;\n\n    hdfs_line_streamer_iterator_t itr(fs, fname, 1000);\n    auto in = itr.next();\n\n    // make one pass over the data to figure out dimensions -\n    // will pay in terms of preallocated storage.\n    while(in != nullptr) {\n        while(!in->eof()) {\n            in->getline(line);\n\n            // Ignore empty lines and comment lines (begin with #)\n            if(line.length() == 0 || line[0] == '#')\n                break;\n\n            n++;\n\n            // Figure out number of targets (only first line)\n            if (n == 1) {\n                std::string tstr;\n                std::istringstream tokenstream (line);\n                tokenstream >> tstr;\n                while (tstr.find(\":\") == std::string::npos) {\n                    nt++;\n                    if (tokenstream.eof())\n                        break;\n                    tokenstream >> tstr;\n                }\n            }\n\n            size_t delim = line.find_last_of(\":\");\n            if(delim == std::string::npos)\n                continue;\n\n            t = delim;\n            while(line[t]!=' ') {\n                t--;\n            }\n            val = line.substr(t+1, delim - t);\n            last = atoi(val.c_str());\n            if (last>d)\n                d = last;\n        }\n\n        in = itr.next();\n    }\n\n    if (min_d > 0)\n        d = std::max(d, min_d);\n\n    // prepare for second pass\n    itr.reset();\n    in = itr.next();\n\n    if (direction == base::COLUMNS) {\n        X.Resize(d, n);\n        Y.Resize(nt, n);\n    } else {\n        X.Resize(n, d);\n        Y.Resize(n, nt);\n    }\n\n    T *Xdata = X.Buffer();\n    R *Ydata = Y.Buffer();\n    int ldX = X.LDim();\n    int ldY = Y.LDim();\n\n    t = 0;\n    while(in != nullptr) {\n\n        in->rewind();\n        while(!in->eof()) {\n            in->getline(line);\n\n            // Ignore empty lines and comment lines (begin with #)\n            if(line.length() == 0 || line[0] == '#')\n                break;\n\n            std::istringstream tokenstream (line);\n\n            for(int r = 0; r < nt; r++) {\n                tokenstream >> label;\n                if (direction == base::COLUMNS)\n                    Ydata[t * ldY + r] = label;\n                else\n                    Ydata[r * ldY + t] = label;\n            }\n\n            while (tokenstream >> token) {\n                size_t delim  = token.find(':');\n                ind = token.substr(0, delim);\n                val = token.substr(delim+1); //.substr(delim+1);\n                j = atoi(ind.c_str()) - 1;\n                if (direction == base::COLUMNS)\n                    Xdata[t * ldX + j] = atof(val.c_str());\n                else\n                    Xdata[j * ldX + t] = atof(val.c_str());\n            }\n\n            t++;\n        }\n\n        in = itr.next();\n    }\n}\n\n/**\n * Reads X and Y from a file in libsvm format (from HDFS filesystem).\n * X is a Skylark local sparse matrix, and Y is Elemental dense matrices.\n *\n * @param fname input file name\n * @param X output X\n * @param Y output Y\n * @param direction whether the examples are to be put in rows or columns\n * @param min_d minimum number of rows in the matrix.\n */\ntemplate<typename T, typename R>\nvoid ReadLIBSVM(hdfsFS &fs, const std::string& fname,\n    base::sparse_matrix_t<T>& X, El::Matrix<R>& Y,\n    base::direction_t direction, int min_d = 0) {\n\n    std::string line;\n    std::string token;\n    R label;\n    unsigned int start = 0;\n    unsigned int t;\n    int n = 0, nt = 0;\n    int d = 0;\n    int i, j, last;\n    char c;\n    int nnz=0;\n    int nz;\n\n    hdfs_line_streamer_iterator_t itr(fs, fname, 1000);\n    auto in = itr.next();\n\n    // make one pass over the data to figure out dimensions and nnz\n    // will pay in terms of preallocated storage.\n    // Also find number of non-zeros per column.\n    std::unordered_map<int, int> colsize;\n\n    while(in != nullptr) {\n\n        while(!in->eof()) {\n            in->getline(line);\n\n            // Ignore empty lines and comment lines (begin with #)\n            if(line.length() == 0 || line[0] == '#')\n                break;\n\n            n++;\n\n            // Figure out number of targets (only first line)\n            if (n == 1) {\n                std::string tstr;\n                std::istringstream tokenstream (line);\n                tokenstream >> tstr;\n                while (tstr.find(\":\") == std::string::npos) {\n                    nt++;\n                    if (tokenstream.eof())\n                        break;\n                    tokenstream >> tstr;\n                }\n            }\n\n            if (direction == base::COLUMNS) {\n                size_t delim = line.find_last_of(\":\");\n                if(delim == line.length())\n                    continue;\n\n                t = delim;\n                while(line[t]!=' ')\n                    t--;\n                std::string val = line.substr(t+1, delim - t);\n                last = atoi(val.c_str());\n                if (last>d)\n                    d = last;\n\n\n                std::istringstream tokenstream (line);\n                tokenstream >> label;\n                while (tokenstream >> token)\n                    nnz++;\n            } else {\n                std::istringstream tokenstream (line);\n                tokenstream >> label;\n\n                while (tokenstream >> token) {\n                    nnz++;\n                    size_t delim  = token.find(':');\n                    int ind = atoi(token.substr(0, delim).c_str());\n\n                    colsize[ind-1]++;\n\n                    if (ind > d)\n                        d = ind;\n                }\n            }\n        }\n\n        in = itr.next();\n    }\n\n    if (min_d > 0)\n        d = std::max(d, min_d);\n\n    T *values = new T[nnz];\n    int *rowind = new int[nnz];\n    int *col_ptr = new int[direction == base::COLUMNS ? n + 1 : d + 1];\n\n    if (direction == base::ROWS) {\n        col_ptr[0] = 0;\n        for(int i = 1; i <= d; i++)\n            col_ptr[i] = col_ptr[i-1] + colsize[i-1];\n        Y.Resize(n, nt);\n    } else\n        Y.Resize(1, nt);\n\n    R *Ydata = Y.Buffer();\n    int ldY = Y.LDim();\n\n    // prepare for second pass\n    itr.reset();\n    in = itr.next();\n\n    if (direction == base::COLUMNS)\n        nnz = 0;\n\n    colsize.clear();\n\n    t = 0;\n    while(in != nullptr) {\n        in->rewind();\n\n        while(!in->eof()) {\n            in->getline(line);\n\n            // Ignore empty lines and comment lines (begin with #)\n            if(line.length() == 0 || line[0] == '#')\n                break;\n\n            std::istringstream tokenstream (line);\n\n            for(int r = 0; r < nt; r++) {\n                tokenstream >> label;\n                if (direction == base::COLUMNS)\n                    Ydata[t * ldY + r] = label;\n                else\n                    Ydata[r * ldY + t] = label;\n            }\n\n            if (direction == base::COLUMNS)\n                col_ptr[t] = nnz;\n\n            while (tokenstream >> token) {\n                size_t delim  = token.find(':');\n                std::string ind = token.substr(0, delim);\n                std::string val = token.substr(delim+1); //.substr(delim+1);\n                j = atoi(ind.c_str()) - 1;\n\n                if (direction == base::COLUMNS) {\n                    rowind[nnz] = j;\n                    values[nnz] = atof(val.c_str());\n                    nnz++;\n                } else {\n                    rowind[col_ptr[j] + colsize[j]] = t;\n                    values[col_ptr[j] + colsize[j]] = atof(val.c_str());\n                    colsize[j]++;\n                }\n            }\n\n            t++;\n        }\n\n        in->close();\n        in = itr.next();\n    }\n\n    if (direction == base::COLUMNS) {\n        col_ptr[n] = nnz; // last entry (total number of nnz)\n        X.attach(col_ptr, rowind, values, nnz, d, n, true);\n    } else\n        X.attach(col_ptr, rowind, values, nnz, n, d, true);\n}\n\n/**\n * Reads X and Y from a file in libsvm format (from HDFS filesystem).\n * X and Y are Elemental distributed matrices.\n * Note that all the data is read on rank 0 (WHY??).\n *\n *\n * @param fname input file name.\n * @param X output X\n * @param Y output Y\n * @param direction whether the examples are to be put in rows or columns\n * @param min_d minimum number of rows in the matrix.\n * @param blocksize blocksize for blocking of read.\n */\ntemplate<typename T, El::Distribution UX, El::Distribution VX,\n         typename R, El::Distribution UY, El::Distribution VY>\nvoid ReadLIBSVM(hdfsFS &fs, const std::string& fname,\n    El::DistMatrix<T, UX, VX>& X, El::DistMatrix<R, UY, VY>& Y,\n    base::direction_t direction, int min_d = 0, int blocksize = 10000) {\n\n    std::string line;\n    std::string token, val, ind;\n    R label;\n    unsigned int start = 0;\n    unsigned int t;\n    int n = 0, nt = 0;\n    int d = 0;\n    int i, j, last;\n    char c;\n\n    // TODO check that X and Y have the same grid.\n    boost::mpi::communicator comm = skylark::utility::get_communicator(X);\n    int rank = X.Grid().Rank();\n\n    //FIXME: only required on rank 0\n    //detail::hdfs_line_streamer_iterator_t itr(fs, fname, 1000);\n    std::unique_ptr<hdfs_line_streamer_iterator_t> itr(nullptr);\n\n    // make one pass over the data to figure out dimensions -\n    // will pay in terms of preallocated storage.\n    if (rank==0) {\n\n        itr.reset(new hdfs_line_streamer_iterator_t (fs, fname, 1000));\n        auto in = itr->next();\n\n        while(in != nullptr) {\n            while(!in->eof()) {\n                in->getline(line);\n\n                // Ignore empty lines and comment lines (begin with #)\n                if(line.length() == 0 || line[0] == '#')\n                    break;\n\n                n++;\n\n                // Figure out number of targets\n                if (n == 1) {\n                    std::string tstr;\n                    std::istringstream tokenstream (line);\n                    tokenstream >> tstr;\n                    while (tstr.find(\":\") == std::string::npos) {\n                        nt++;\n                        if (tokenstream.eof())\n                            break;\n                        tokenstream >> tstr;\n                    }\n                }\n\n                size_t delim = line.find_last_of(\":\");\n                if(delim == std::string::npos)\n                    continue;\n\n                t = delim;\n                while(line[t]!=' ') {\n                    t--;\n                }\n                val = line.substr(t+1, delim - t);\n                last = atoi(val.c_str());\n                if (last>d)\n                    d = last;\n            }\n\n            in = itr->next();\n        }\n\n        if (min_d > 0)\n            d = std::max(d, min_d);\n    }\n\n    boost::mpi::broadcast(comm, n, 0);\n    boost::mpi::broadcast(comm, d, 0);\n    boost::mpi::broadcast(comm, nt, 0);\n\n    int numblocks = ((int) n/ (int) blocksize); // of size blocksize\n    int leftover = n % blocksize;\n    int block = blocksize;\n\n    if (direction == base::COLUMNS) {\n        X.Resize(d, n);\n        Y.Resize(nt, n);\n    } else {\n        X.Resize(n, d);\n        Y.Resize(n, nt);\n    }\n\n    El::DistMatrix<T, El::CIRC, El::CIRC> XB(X.Grid()), YB(Y.Grid());\n    El::DistMatrix<T, UX, VX> Xv(X.Grid());\n    El::DistMatrix<R, UY, VY> Yv(Y.Grid());\n    for(int i=0; i<numblocks+1; i++) {\n        if (i==numblocks)\n            block = leftover;\n        if (block==0)\n            break;\n\n        if (direction == base::COLUMNS) {\n            El::Zeros(XB, d, block);\n            El::Zeros(YB, nt, block);\n        } else {\n            El::Zeros(XB, block, d);\n            El::Zeros(YB, block, nt);\n        }\n\n        if(rank==0) {\n            T *Xdata = XB.Matrix().Buffer();\n            R *Ydata = YB.Matrix().Buffer();\n            int ldX = XB.Matrix().LDim();\n            int ldY = YB.Matrix().LDim();\n\n            itr->reset();\n            auto in = itr->next();\n\n            t = 0;\n            while(in != nullptr) {\n\n                in->rewind();\n                while(!in->eof() && t<block) {\n                    in->getline(line);\n\n                    // Ignore empty lines and comment lines (begin with #)\n                    if(line.length() == 0 || line[0] == '#')\n                        break;\n                    std::istringstream tokenstream (line);\n                    for(int r = 0; r < nt; r++) {\n                        tokenstream >> label;\n                        if (direction == base::COLUMNS)\n                            Ydata[t * ldY + r] = label;\n                        else\n                            Ydata[r * ldY + t] = label;\n                    }\n\n                    while (tokenstream >> token) {\n                        size_t delim  = token.find(':');\n                        ind = token.substr(0, delim);\n                        val = token.substr(delim+1); //.substr(delim+1);\n                        j = atoi(ind.c_str()) - 1;\n                        if (direction == base::COLUMNS)\n                            Xdata[t * ldX + j] = atof(val.c_str());\n                        else\n                            Xdata[j * ldX + t] = atof(val.c_str());\n                    }\n\n                    t++;\n                }\n\n                in = itr->next();\n            }\n        }\n\n        // The calls below should distribute the data to all the nodes.\n        if (direction == base::COLUMNS) {\n            int ldX = XB.Matrix().LDim();\n            El::View(Xv, X, 0, i*blocksize, d, block);\n            El::View(Yv, Y, 0, i*blocksize, nt, block);\n        } else {\n            El::View(Xv, X, i*blocksize, 0, block, d);\n            El::View(Yv, Y, i*blocksize, 0, block, nt);\n        }\n\n        Xv = XB;\n        Yv = YB;\n    }\n}\n\ntemplate<typename T,\n         typename R, El::Distribution UY, El::Distribution VY>\nvoid ReadLIBSVM(const hdfsFS &fs, const std::string& fname,\n    base::sparse_vc_star_matrix_t<T>& X, El::DistMatrix<R, UY, VY>& Y,\n    base::direction_t direction, int min_d = 0, int blocksize = 10000) {\n\n    //TODO: implement\n    SKYLARK_THROW_EXCEPTION(skylark::base::io_exception() <<\n        skylark::base::error_msg(\n            \"ReadLIBSVM from HDFS not implemented for sparse_vc_star_matrix_t!\"));\n}\n\n\n\n#endif\n\n} } } // namespace skylark::utility::io\n\n#endif\n", "meta": {"hexsha": "4d2c41e48a3293cebc2fd49e7207a8169860f145", "size": 60819, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "utility/io/libsvm_io.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": "utility/io/libsvm_io.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": "utility/io/libsvm_io.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": 30.3034379671, "max_line_length": 82, "alphanum_fraction": 0.4855226163, "num_tokens": 15352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.45971652084341247}}
{"text": "// Copyright (c) 2017-2018, CNRS\n// Authors: Joseph Mirabel (joseph.mirabel@laas.fr)\n//\n\n#include \"pinocchio/multibody/liegroup/liegroup.hpp\"\n#include \"pinocchio/multibody/liegroup/liegroup-collection.hpp\"\n#include \"pinocchio/multibody/liegroup/liegroup-generic.hpp\"\n\n#include \"pinocchio/multibody/joint/joint-generic.hpp\"\n\n#include <boost/test/unit_test.hpp>\n#include <boost/utility/binary.hpp>\n#include <boost/algorithm/string.hpp>\n\n#define EIGEN_VECTOR_IS_APPROX(Va, Vb, precision)                              \\\n  BOOST_CHECK_MESSAGE((Va).isApprox(Vb, precision),                            \\\n      \"check \" #Va \".isApprox(\" #Vb \") failed \"                                \\\n      \"[\\n\" << (Va).transpose() << \"\\n!=\\n\" << (Vb).transpose() << \"\\n]\")\n#define EIGEN_MATRIX_IS_APPROX(Va, Vb, precision)                              \\\n  BOOST_CHECK_MESSAGE((Va).isApprox(Vb, precision),                            \\\n      \"check \" #Va \".isApprox(\" #Vb \") failed \"                                \\\n      \"[\\n\" << (Va) << \"\\n!=\\n\" << (Vb) << \"\\n]\")\n\nusing namespace pinocchio;\n\n#define VERBOSE false\n#define IFVERBOSE if(VERBOSE)\n\ntemplate <typename T>\nvoid test_lie_group_methods (T & jmodel, typename T::JointDataDerived &)\n{\n  typedef double Scalar;\n  \n  const Scalar prec = Eigen::NumTraits<Scalar>::dummy_precision();\n  BOOST_TEST_MESSAGE (\"Testing Joint over \" << jmodel.shortname());\n  typedef typename T::ConfigVector_t  ConfigVector_t;\n  typedef typename T::TangentVector_t TangentVector_t;\n  \n  ConfigVector_t  q1(ConfigVector_t::Random (jmodel.nq()));\n  TangentVector_t q1_dot(TangentVector_t::Random (jmodel.nv()));\n  ConfigVector_t  q2(ConfigVector_t::Random (jmodel.nq()));\n  \n  typedef typename LieGroup<T>::type LieGroupType;\n  static ConfigVector_t Ones(ConfigVector_t::Ones(jmodel.nq()));\n  const Scalar u = 0.3;\n  // pinocchio::Inertia::Matrix6 Ia(pinocchio::Inertia::Random().matrix());\n  // bool update_I = false;\n  \n  q1 = LieGroupType().randomConfiguration(-Ones, Ones);\n  \n  typename T::JointDataDerived jdata = jmodel.createData();\n  \n  // Check integrate\n  jmodel.calc(jdata, q1, q1_dot);\n  SE3 M1 = jdata.M;\n  Motion v1(jdata.v);\n  \n  q2 = LieGroupType().integrate(q1,q1_dot);\n  jmodel.calc(jdata,q2);\n  SE3 M2 = jdata.M;\n  \n  SE3 M2_exp = M1*exp6(v1);\n  \n  if(jmodel.shortname() != \"JointModelSphericalZYX\")\n  {\n    BOOST_CHECK_MESSAGE(M2.isApprox(M2_exp), std::string(\"Error when integrating1 \" + jmodel.shortname()));\n  }\n  \n  // Check the reversability of integrate\n  ConfigVector_t q3 = LieGroupType().integrate(q2,-q1_dot);\n  jmodel.calc(jdata,q3);\n  SE3 M3 = jdata.M;\n  \n  BOOST_CHECK_MESSAGE(M3.isApprox(M1), std::string(\"Error when integrating back \" + jmodel.shortname()));\n  \n  // Check interpolate\n  ConfigVector_t q_interpolate = LieGroupType().interpolate(q1,q2,0.);\n  BOOST_CHECK_MESSAGE(q_interpolate.isApprox(q1), std::string(\"Error when interpolating \" + jmodel.shortname()));\n  \n  q_interpolate = LieGroupType().interpolate(q1,q2,1.);\n  BOOST_CHECK_MESSAGE(q_interpolate.isApprox(q2), std::string(\"Error when interpolating \" + jmodel.shortname()));\n  \n  if(jmodel.shortname() != \"JointModelSphericalZYX\")\n  {\n    q_interpolate = LieGroupType().interpolate(q1,q2,u);\n    jmodel.calc(jdata,q_interpolate);\n    SE3 M_interpolate = jdata.M;\n    \n    SE3 M_interpolate_expected = M1*exp6(u*v1);\n    BOOST_CHECK_MESSAGE(M_interpolate_expected.isApprox(M_interpolate,1e2*prec), std::string(\"Error when interpolating \" + jmodel.shortname()));\n  }\n\n  // Check that difference between two equal configuration is exactly 0\n  TangentVector_t zero = LieGroupType().difference(q1,q1);\n  BOOST_CHECK_MESSAGE (zero.isZero (0), std::string (\"Error: difference between two equal configurations is not 0.\"));\n  zero = LieGroupType().difference(q2,q2);\n  BOOST_CHECK_MESSAGE (zero.isZero (0), std::string (\"Error: difference between two equal configurations is not 0.\"));\n\n  // Check difference\n  TangentVector_t vdiff = LieGroupType().difference(q1,q2);\n  BOOST_CHECK_MESSAGE(vdiff.isApprox(q1_dot,1e2*prec), std::string(\"Error when differentiating \" + jmodel.shortname()));\n  \n  // Check distance\n  Scalar dist = LieGroupType().distance(q1,q2);\n  BOOST_CHECK_MESSAGE(dist > 0., \"distance - wrong results\");\n  BOOST_CHECK_SMALL(math::fabs(dist-q1_dot.norm()), 10*prec);\n  \n  std::string error_prefix(\"LieGroup\");\n  error_prefix += \" on joint \" + jmodel.shortname();\n  \n  BOOST_CHECK_MESSAGE(jmodel.nq() == LieGroupType::NQ, std::string(error_prefix + \" - nq \"));\n  BOOST_CHECK_MESSAGE(jmodel.nv() == LieGroupType::NV, std::string(error_prefix + \" - nv \"));\n  \n  BOOST_CHECK_MESSAGE\n  (jmodel.nq() ==\n   LieGroupType().randomConfiguration(-1 * Ones, Ones).size(),\n   std::string(error_prefix + \" - RandomConfiguration dimensions \"));\n\n  ConfigVector_t q_normalize(ConfigVector_t::Random());\n  Eigen::VectorXd q_normalize_ref(q_normalize);\n  if(jmodel.shortname() == \"JointModelSpherical\")\n  {\n    q_normalize_ref /= q_normalize_ref.norm();\n  }\n  else if(jmodel.shortname() == \"JointModelFreeFlyer\")\n  {\n    q_normalize_ref.template tail<4>() /= q_normalize_ref.template tail<4>().norm();\n  }\n  else if(boost::algorithm::istarts_with(jmodel.shortname(),\"JointModelRUB\"))\n  {\n    q_normalize_ref /= q_normalize_ref.norm();\n  }\n  else if(jmodel.shortname() == \"JointModelPlanar\")\n  {\n    q_normalize_ref.template tail<2>() /= q_normalize_ref.template tail<2>().norm();\n  }\n  LieGroupType().normalize(q_normalize);\n  BOOST_CHECK_MESSAGE(q_normalize.isApprox(q_normalize_ref), std::string(error_prefix + \" - normalize \"));\n}\n\nstruct TestJoint{\n\n  template <typename T>\n  void operator()(const T ) const\n  {\n    T jmodel;\n    jmodel.setIndexes(0,0,0);\n    typename T::JointDataDerived jdata = jmodel.createData();\n\n    test_lie_group_methods(jmodel, jdata);    \n  }\n\n  void operator()(const pinocchio::JointModelRevoluteUnaligned & ) const\n  {\n    pinocchio::JointModelRevoluteUnaligned jmodel(1.5, 1., 0.);\n    jmodel.setIndexes(0,0,0);\n    pinocchio::JointModelRevoluteUnaligned::JointDataDerived jdata = jmodel.createData();\n\n    test_lie_group_methods(jmodel, jdata);\n  }\n\n  void operator()(const pinocchio::JointModelPrismaticUnaligned & ) const\n  {\n    pinocchio::JointModelPrismaticUnaligned jmodel(1.5, 1., 0.);\n    jmodel.setIndexes(0,0,0);\n    pinocchio::JointModelPrismaticUnaligned::JointDataDerived jdata = jmodel.createData();\n\n    test_lie_group_methods(jmodel, jdata);\n  }\n\n};\n\nstruct LieGroup_Jdifference{\n  template <typename T>\n  void operator()(const T ) const\n  {\n    typedef typename T::ConfigVector_t ConfigVector_t;\n    typedef typename T::TangentVector_t TangentVector_t;\n    typedef typename T::JacobianMatrix_t JacobianMatrix_t;\n    typedef typename T::Scalar Scalar;\n\n    T lg;\n    BOOST_TEST_MESSAGE (lg.name());\n    ConfigVector_t q[2], q_dv[2];\n    q[0] = lg.random();\n    q[1] = lg.random();\n    TangentVector_t va, vb, dv;\n    JacobianMatrix_t J[2];\n    dv.setZero();\n\n    lg.difference (q[0], q[1], va);\n    lg.template dDifference<ARG0> (q[0], q[1], J[0]);\n    lg.template dDifference<ARG1> (q[0], q[1], J[1]);\n\n    const Scalar eps = 1e-6;\n    for (int k = 0; k < 2; ++k) {\n      BOOST_TEST_MESSAGE (\"Checking J\" << k << '\\n' << J[k]);\n      q_dv[0] = q[0];\n      q_dv[1] = q[1];\n      // Check J[k]\n      for (int i = 0; i < dv.size(); ++i)\n      {\n        dv[i] = eps;\n        lg.integrate (q[k], dv, q_dv[k]);\n        lg.difference (q_dv[0], q_dv[1], vb);\n\n        // vb - va ~ J[k] * dv\n        TangentVector_t J_dv = J[k].col(i);\n        TangentVector_t vb_va = (vb - va) / eps;\n        EIGEN_VECTOR_IS_APPROX (vb_va, J_dv, 1e-2);\n        dv[i] = 0;\n      }\n    }\n\n    specificTests(lg);\n  }\n\n  template <typename T>\n  void specificTests(const T ) const\n  {}\n\n  template <typename Scalar, int Options>\n  void specificTests(const SpecialEuclideanOperationTpl<3,Scalar,Options>) const\n  {\n    typedef SE3Tpl<Scalar> SE3;\n    typedef SpecialEuclideanOperationTpl<3,Scalar,Options> LG_t;\n    typedef typename LG_t::ConfigVector_t ConfigVector_t;\n    typedef typename LG_t::JacobianMatrix_t JacobianMatrix_t;\n\n    LG_t lg;\n\n    ConfigVector_t q[2];\n    q[0] = lg.random();\n    q[1] = lg.random();\n    JacobianMatrix_t J[2];\n\n    lg.template dDifference<ARG0> (q[0], q[1], J[0]);\n    lg.template dDifference<ARG1> (q[0], q[1], J[1]);\n\n    SE3 om0 (typename SE3::Quaternion (q[0].template tail<4>()).matrix(), q[0].template head<3>()),\n        om1 (typename SE3::Quaternion (q[1].template tail<4>()).matrix(), q[1].template head<3>()),\n        _1m2 (om1.actInv (om0)) ;\n    EIGEN_MATRIX_IS_APPROX (J[1] * _1m2.toActionMatrix(), - J[0], 1e-8);\n  }\n\n  template <typename Scalar, int Options>\n    void specificTests(const CartesianProductOperation<\n        VectorSpaceOperationTpl<3,Scalar,Options>,\n        SpecialOrthogonalOperationTpl<3,Scalar,Options>\n        >) const\n  {\n    typedef SE3Tpl<Scalar> SE3;\n    typedef CartesianProductOperation<\n      VectorSpaceOperationTpl<3,Scalar,Options>,\n      SpecialOrthogonalOperationTpl<3,Scalar,Options>\n        > LG_t;\n    typedef typename LG_t::ConfigVector_t ConfigVector_t;\n    typedef typename LG_t::JacobianMatrix_t JacobianMatrix_t;\n\n    LG_t lg;\n\n    ConfigVector_t q[2];\n    q[0] = lg.random();\n    q[1] = lg.random();\n    JacobianMatrix_t J[2];\n\n    lg.template dDifference<ARG0> (q[0], q[1], J[0]);\n    lg.template dDifference<ARG1> (q[0], q[1], J[1]);\n\n    typename SE3::Matrix3\n      oR0 (typename SE3::Quaternion (q[0].template tail<4>()).matrix()),\n      oR1 (typename SE3::Quaternion (q[1].template tail<4>()).matrix());\n    JacobianMatrix_t X (JacobianMatrix_t::Identity());\n    X.template bottomRightCorner<3,3>() = oR1.transpose() * oR0;\n    EIGEN_MATRIX_IS_APPROX (J[1] * X, - J[0], 1e-8);\n  }\n};\n\ntemplate<bool around_identity>\nstruct LieGroup_Jintegrate{\n  template <typename T>\n  void operator()(const T ) const\n  {\n    typedef typename T::ConfigVector_t ConfigVector_t;\n    typedef typename T::TangentVector_t TangentVector_t;\n    typedef typename T::JacobianMatrix_t JacobianMatrix_t;\n    typedef typename T::Scalar Scalar;\n\n    T lg;\n    ConfigVector_t q = lg.random();\n    TangentVector_t v, dq, dv;\n    if(around_identity)\n      v.setZero();\n    else\n      v.setRandom();\n    \n    dq.setZero();\n    dv.setZero();\n\n    ConfigVector_t q_v = lg.integrate (q, v);\n\n    JacobianMatrix_t Jq, Jv;\n    lg.dIntegrate_dq (q, v, Jq);\n    lg.dIntegrate_dv (q, v, Jv);\n\n    const Scalar eps = 1e-6;\n    for (int i = 0; i < v.size(); ++i)\n    {\n      dq[i] = dv[i] = eps;\n      ConfigVector_t q_dq = lg.integrate (q, dq);\n\n      ConfigVector_t q_dq_v = lg.integrate (q_dq, v);\n      TangentVector_t Jq_dq = Jq.col(i);\n      // q_dv_v - q_v ~ Jq dv\n      TangentVector_t dI_dq = lg.difference (q_v, q_dq_v) / eps;\n      EIGEN_VECTOR_IS_APPROX (dI_dq, Jq_dq, 1e-2);\n\n      ConfigVector_t q_v_dv = lg.integrate (q, (v+dv).eval());\n      TangentVector_t Jv_dv = Jv.col(i);\n      // q_v_dv - q_v ~ Jv dv\n      TangentVector_t dI_dv = lg.difference (q_v, q_v_dv) / eps;\n      EIGEN_VECTOR_IS_APPROX (dI_dv, Jv_dv, 1e-2);\n\n      dq[i] = dv[i] = 0;\n    }\n  }\n};\n\nstruct LieGroup_JintegrateJdifference{\n  template <typename T>\n  void operator()(const T ) const\n  {\n    typedef typename T::ConfigVector_t ConfigVector_t;\n    typedef typename T::TangentVector_t TangentVector_t;\n    typedef typename T::JacobianMatrix_t JacobianMatrix_t;\n\n    T lg;\n    BOOST_TEST_MESSAGE (lg.name());\n    ConfigVector_t qa, qb (lg.nq());\n    qa = lg.random();\n    TangentVector_t v (lg.nv());\n    v.setRandom ();\n    lg.integrate(qa, v, qb);\n\n    JacobianMatrix_t Jd_qb, Ji_v;\n\n    lg.template dDifference<ARG1> (qa, qb, Jd_qb);\n    lg.template dIntegrate <ARG1> (qa, v , Ji_v );\n\n    BOOST_CHECK_MESSAGE ((Jd_qb * Ji_v).isIdentity(),\n        \"Jd_qb\\n\" <<\n        Jd_qb << '\\n' <<\n        \"* Ji_v\\n\" <<\n        Ji_v << '\\n' <<\n        \"!= Identity\\n\" <<\n        Jd_qb * Ji_v << '\\n');\n  }\n};\n\nstruct LieGroup_JintegrateCoeffWise\n{\n  template <typename T>\n  void operator()(const T ) const\n  {\n    typedef typename T::ConfigVector_t ConfigVector_t;\n    typedef typename T::TangentVector_t TangentVector_t;\n    typedef typename T::Scalar Scalar;\n    \n    T lg;\n    ConfigVector_t q = lg.random();\n    TangentVector_t dv(TangentVector_t::Zero(lg.nv()));\n    \n    BOOST_TEST_MESSAGE (lg.name());\n    typedef Eigen::Matrix<Scalar,T::NQ,T::NV> JacobianCoeffs;\n    JacobianCoeffs Jintegrate(JacobianCoeffs::Zero(lg.nq(),lg.nv()));\n    lg.integrateCoeffWiseJacobian(q,Jintegrate);\n    JacobianCoeffs Jintegrate_fd(JacobianCoeffs::Zero(lg.nq(),lg.nv()));\n\n    const Scalar eps = 1e-8;\n    for (int i = 0; i < lg.nv(); ++i)\n    {\n      dv[i] = eps;\n      ConfigVector_t q_next(ConfigVector_t::Zero(lg.nq()));\n      lg.integrate(q, dv,q_next);\n      Jintegrate_fd.col(i) = (q_next - q)/eps;\n      \n      dv[i] = 0;\n    }\n\n    EIGEN_MATRIX_IS_APPROX(Jintegrate, Jintegrate_fd, sqrt(eps));\n  }\n};\n\nBOOST_AUTO_TEST_SUITE ( BOOST_TEST_MODULE )\n\nBOOST_AUTO_TEST_CASE ( test_all )\n{\n  typedef boost::variant< JointModelRX, JointModelRY, JointModelRZ, JointModelRevoluteUnaligned\n                          , JointModelSpherical, JointModelSphericalZYX\n                          , JointModelPX, JointModelPY, JointModelPZ\n                          , JointModelPrismaticUnaligned\n                          , JointModelFreeFlyer\n                          , JointModelPlanar\n                          , JointModelTranslation\n                          , JointModelRUBX, JointModelRUBY, JointModelRUBZ\n                          > Variant;\n  for (int i = 0; i < 20; ++i)\n    boost::mpl::for_each<Variant::types>(TestJoint());\n  \n  // FIXME JointModelComposite does not work.\n  // boost::mpl::for_each<JointModelVariant::types>(TestJoint());\n  \n}\n\nBOOST_AUTO_TEST_CASE ( Jdifference )\n{\n  typedef double Scalar;\n  enum { Options = 0 };\n  \n  typedef boost::mpl::vector<  VectorSpaceOperationTpl<1,Scalar,Options>\n                             , VectorSpaceOperationTpl<2,Scalar,Options>\n                             , SpecialOrthogonalOperationTpl<2,Scalar,Options>\n                             , SpecialOrthogonalOperationTpl<3,Scalar,Options>\n                             , SpecialEuclideanOperationTpl<2,Scalar,Options>\n                             , SpecialEuclideanOperationTpl<3,Scalar,Options>\n                             , CartesianProductOperation<\n                                 VectorSpaceOperationTpl<2,Scalar,Options>,\n                                 SpecialOrthogonalOperationTpl<2,Scalar,Options>\n                               >\n                             , CartesianProductOperation<\n                                 VectorSpaceOperationTpl<3,Scalar,Options>,\n                                 SpecialOrthogonalOperationTpl<3,Scalar,Options>\n                               >\n                             > Types;\n  for (int i = 0; i < 20; ++i)\n    boost::mpl::for_each<Types>(LieGroup_Jdifference());\n}\n\nBOOST_AUTO_TEST_CASE ( Jintegrate )\n{\n  typedef double Scalar;\n  enum { Options = 0 };\n  \n  typedef boost::mpl::vector<  VectorSpaceOperationTpl<1,Scalar,Options>\n                             , VectorSpaceOperationTpl<2,Scalar,Options>\n                             , SpecialOrthogonalOperationTpl<2,Scalar,Options>\n                             , SpecialOrthogonalOperationTpl<3,Scalar,Options>\n                             , SpecialEuclideanOperationTpl<2,Scalar,Options>\n                             , SpecialEuclideanOperationTpl<3,Scalar,Options>\n                             , CartesianProductOperation<\n                                 VectorSpaceOperationTpl<2,Scalar,Options>,\n                                 SpecialOrthogonalOperationTpl<2,Scalar,Options>\n                               >\n                             , CartesianProductOperation<\n                                 VectorSpaceOperationTpl<3,Scalar,Options>,\n                                 SpecialOrthogonalOperationTpl<3,Scalar,Options>\n                               >\n                             > Types;\n  for (int i = 0; i < 20; ++i)\n    boost::mpl::for_each<Types>(LieGroup_Jintegrate<false>());\n  \n  // Around identity\n  boost::mpl::for_each<Types>(LieGroup_Jintegrate<true>());\n}\n\nBOOST_AUTO_TEST_CASE ( Jintegrate_Jdifference )\n{\n  typedef double Scalar;\n  enum { Options = 0 };\n  \n  typedef boost::mpl::vector<  VectorSpaceOperationTpl<1,Scalar,Options>\n                             , VectorSpaceOperationTpl<2,Scalar,Options>\n                             , SpecialOrthogonalOperationTpl<2,Scalar,Options>\n                             , SpecialOrthogonalOperationTpl<3,Scalar,Options>\n                             , SpecialEuclideanOperationTpl<2,Scalar,Options>\n                             , SpecialEuclideanOperationTpl<3,Scalar,Options>\n                             , CartesianProductOperation<\n                                 VectorSpaceOperationTpl<2,Scalar,Options>,\n                                 SpecialOrthogonalOperationTpl<2,Scalar,Options>\n                               >\n                             , CartesianProductOperation<\n                                 VectorSpaceOperationTpl<3,Scalar,Options>,\n                                 SpecialOrthogonalOperationTpl<3,Scalar,Options>\n                               >\n                             > Types;\n  for (int i = 0; i < 20; ++i)\n    boost::mpl::for_each<Types>(LieGroup_JintegrateJdifference());\n}\n\nBOOST_AUTO_TEST_CASE(JintegrateCoeffWise)\n{\n  typedef double Scalar;\n  enum { Options = 0 };\n  \n  typedef boost::mpl::vector<  VectorSpaceOperationTpl<1,Scalar,Options>\n  , VectorSpaceOperationTpl<2,Scalar,Options>\n  , SpecialOrthogonalOperationTpl<2,Scalar,Options>\n  , SpecialOrthogonalOperationTpl<3,Scalar,Options>\n  , SpecialEuclideanOperationTpl<2,Scalar,Options>\n  , SpecialEuclideanOperationTpl<3,Scalar,Options>\n  , CartesianProductOperation<\n  VectorSpaceOperationTpl<2,Scalar,Options>,\n  SpecialOrthogonalOperationTpl<2,Scalar,Options>\n  >\n  , CartesianProductOperation<\n  VectorSpaceOperationTpl<3,Scalar,Options>,\n  SpecialOrthogonalOperationTpl<3,Scalar,Options>\n  >\n  > Types;\n  for (int i = 0; i < 20; ++i)\n    boost::mpl::for_each<Types>(LieGroup_JintegrateCoeffWise());\n  \n  {\n    typedef SpecialEuclideanOperationTpl<3,Scalar,Options> LieGroup;\n    typedef LieGroup::ConfigVector_t ConfigVector_t;\n    LieGroup lg;\n    \n    ConfigVector_t q = lg.random();\n//    TangentVector_t dv(TangentVector_t::Zero(lg.nv()));\n    \n    typedef Eigen::Matrix<Scalar,LieGroup::NQ,LieGroup::NV> JacobianCoeffs;\n    JacobianCoeffs Jintegrate(JacobianCoeffs::Zero(lg.nq(),lg.nv()));\n    lg.integrateCoeffWiseJacobian(q,Jintegrate);\n    \n    \n   \n  }\n}\n\nBOOST_AUTO_TEST_CASE ( test_vector_space )\n{\n  typedef VectorSpaceOperationTpl<3,double> VSO_t;\n  VSO_t::ConfigVector_t q,\n    lo(VSO_t::ConfigVector_t::Constant(-std::numeric_limits<double>::infinity())),\n    // lo(VSO_t::ConfigVector_t::Constant(                                       0)),\n    // up(VSO_t::ConfigVector_t::Constant( std::numeric_limits<double>::infinity()));\n    up(VSO_t::ConfigVector_t::Constant(                                       0));\n\n  bool error = false;\n  try {\n    VSO_t ().randomConfiguration(lo, up, q);\n  } catch (const std::runtime_error&) {\n    error = true;\n  }\n  BOOST_CHECK_MESSAGE(error, \"Random configuration between infinite bounds should return an error\");\n}\n\nBOOST_AUTO_TEST_CASE ( test_size )\n{\n  // R^1: neutral = [0]\n  VectorSpaceOperationTpl <1,double> vs1;\n  Eigen::VectorXd neutral;\n  neutral.resize (1);\n  neutral.setZero ();\n  BOOST_CHECK (vs1.nq () == 1);\n  BOOST_CHECK (vs1.nv () == 1);\n  BOOST_CHECK (vs1.name () == \"R^1\");\n  BOOST_CHECK (vs1.neutral () == neutral);\n  // R^2: neutral = [0, 0]\n  VectorSpaceOperationTpl <2,double> vs2;\n  neutral.resize (2);\n  neutral.setZero ();\n  BOOST_CHECK (vs2.nq () == 2);\n  BOOST_CHECK (vs2.nv () == 2);\n  BOOST_CHECK (vs2.name () == \"R^2\");\n  BOOST_CHECK (vs2.neutral () == neutral);\n  // R^3: neutral = [0, 0, 0]\n  VectorSpaceOperationTpl <3,double> vs3;\n  neutral.resize (3);\n  neutral.setZero ();\n  BOOST_CHECK (vs3.nq () == 3);\n  BOOST_CHECK (vs3.nv () == 3);\n  BOOST_CHECK (vs3.name () == \"R^3\");\n  BOOST_CHECK (vs3.neutral () == neutral);\n  // SO(2): neutral = [1, 0]\n  SpecialOrthogonalOperationTpl<2,double> so2;\n  neutral.resize (2); neutral [0] = 1; neutral [1] = 0;\n  BOOST_CHECK (so2.nq () == 2);\n  BOOST_CHECK (so2.nv () == 1);\n  BOOST_CHECK (so2.name () == \"SO(2)\");\n  BOOST_CHECK (so2.neutral () == neutral);\n  // SO(3): neutral = [0, 0, 0, 1]\n  SpecialOrthogonalOperationTpl<3,double> so3;\n  neutral.resize (4); neutral.setZero ();\n  neutral [3] = 1;\n  BOOST_CHECK (so3.nq () == 4);\n  BOOST_CHECK (so3.nv () == 3);\n  BOOST_CHECK (so3.name () == \"SO(3)\");\n  BOOST_CHECK (so3.neutral () == neutral);\n  // SE(2): neutral = [0, 0, 1, 0]\n  SpecialEuclideanOperationTpl <2,double> se2;\n  neutral.resize (4); neutral.setZero ();\n  neutral [2] = 1;\n  BOOST_CHECK (se2.nq () == 4);\n  BOOST_CHECK (se2.nv () == 3);\n  BOOST_CHECK (se2.name () == \"SE(2)\");\n  BOOST_CHECK (se2.neutral () == neutral);\n  // SE(3): neutral = [0, 0, 0, 0, 0, 0, 1]\n  SpecialEuclideanOperationTpl <3,double> se3;\n  neutral.resize (7); neutral.setZero ();\n  neutral [6] = 1;\n  BOOST_CHECK (se3.nq () == 7);\n  BOOST_CHECK (se3.nv () == 6);\n  BOOST_CHECK (se3.name () == \"SE(3)\");\n  BOOST_CHECK (se3.neutral () == neutral);\n  // R^2 x SO(2): neutral = [0, 0, 1, 0]\n  CartesianProductOperation <VectorSpaceOperationTpl <2,double>,\n                             SpecialOrthogonalOperationTpl <2,double> > r2xso2;\n  neutral.resize (4); neutral.setZero ();\n  neutral [2] = 1;\n  BOOST_CHECK (r2xso2.nq () == 4);\n  BOOST_CHECK (r2xso2.nv () == 3);\n  BOOST_CHECK (r2xso2.name () == \"R^2*SO(2)\");\n  BOOST_CHECK (r2xso2.neutral () == neutral);\n  // R^3 x SO(3): neutral = [0, 0, 0, 0, 0, 0, 1]\n  CartesianProductOperation <VectorSpaceOperationTpl <3,double>,\n                             SpecialOrthogonalOperationTpl <3,double> > r3xso3;\n  neutral.resize (7); neutral.setZero ();\n  neutral [6] = 1;\n  BOOST_CHECK (r3xso3.nq () == 7);\n  BOOST_CHECK (r3xso3.nv () == 6);\n  BOOST_CHECK (r3xso3.name () == \"R^3*SO(3)\");\n  BOOST_CHECK (r3xso3.neutral () == neutral);\n}\n\nBOOST_AUTO_TEST_CASE(test_dim_computation)\n{\n  int dim = eval_set_dim<1,1>::value ;\n  BOOST_CHECK(dim == 2);\n  dim = eval_set_dim<Eigen::Dynamic,1>::value;\n  BOOST_CHECK(dim == Eigen::Dynamic);\n  dim = eval_set_dim<1,Eigen::Dynamic>::value;\n  BOOST_CHECK(dim == Eigen::Dynamic);\n}\n\ntemplate<typename LieGroupCollection>\nstruct TestLieGroupVariantVisitor\n{\n  \n  typedef LieGroupGenericTpl<LieGroupCollection> LieGroupGeneric;\n\n  \n  template<typename Derived>\n  void operator() (const LieGroupBase<Derived> & lg) const\n  {\n    LieGroupGenericTpl<LieGroupCollection> lg_generic(lg.derived());\n    test(lg,lg_generic);\n  }\n  \n  template<typename Derived>\n  static void test(const LieGroupBase<Derived> & lg,\n                   const LieGroupGenericTpl<LieGroupCollection> & lg_generic)\n  {\n    typedef typename Derived::ConfigVector_t ConfigVector_t;\n    typedef typename Derived::TangentVector_t TangentVector_t;\n    BOOST_CHECK(lg.nq() == nq(lg_generic));\n    BOOST_CHECK(lg.nv() == nv(lg_generic));\n    \n    BOOST_CHECK(lg.name() == name(lg_generic));\n    \n    BOOST_CHECK(lg.neutral() == neutral(lg_generic));\n    \n    typedef typename LieGroupGeneric::ConfigVector_t ConfigVectorGeneric;\n    typedef typename LieGroupGeneric::TangentVector_t TangentVectorGeneric;\n    \n    ConfigVector_t q0 = lg.random();\n    TangentVector_t v = TangentVector_t::Random(lg.nv());\n    ConfigVector_t qout_ref(lg.nq());\n    lg.integrate(q0, v, qout_ref);\n    \n    ConfigVectorGeneric qout(lg.nq());\n    integrate(lg_generic, ConfigVectorGeneric(q0), TangentVectorGeneric(v), qout);\n    BOOST_CHECK(qout.isApprox(qout_ref));\n  }\n};\n\nBOOST_AUTO_TEST_CASE(test_liegroup_variant)\n{\n  boost::mpl::for_each<LieGroupCollectionDefault::LieGroupVariant::types>(TestLieGroupVariantVisitor<LieGroupCollectionDefault>());\n}\n\nBOOST_AUTO_TEST_SUITE_END ()\n", "meta": {"hexsha": "a377510273655150e4b790c10de6584df794e6af", "size": 23951, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittest/liegroups.cpp", "max_stars_repo_name": "andreadelprete/pinocchio", "max_stars_repo_head_hexsha": "6fa1c7d5502629ee126f84f1a05471815fba30f4", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "unittest/liegroups.cpp", "max_issues_repo_name": "andreadelprete/pinocchio", "max_issues_repo_head_hexsha": "6fa1c7d5502629ee126f84f1a05471815fba30f4", "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": "unittest/liegroups.cpp", "max_forks_repo_name": "andreadelprete/pinocchio", "max_forks_repo_head_hexsha": "6fa1c7d5502629ee126f84f1a05471815fba30f4", "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": 35.0673499268, "max_line_length": 144, "alphanum_fraction": 0.6359650954, "num_tokens": 6663, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.705785040214066, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.4597165145753041}}
{"text": "#ifndef MATMATALL_HPP\n#define MATMATALL_HPP\n\n#include <vector>\n#include <boost/align/aligned_allocator.hpp>\n\ntemplate <typename T>\nusing aligned_allocator = boost::alignment::aligned_allocator<T, 64>;\ntemplate <typename T>\nusing aligned_vector = std::vector<T, aligned_allocator<T>>;\n\nvoid matmatall(double alpha, double const* a, int m, int n, double const* b, int k, double beta, double * c);\n\n#endif // MATMATALL_HPP", "meta": {"hexsha": "f2c04a594578557a3ddede08a6eacd3167e29013", "size": 419, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "matmatall.hpp", "max_stars_repo_name": "mindpad/matrix-matrix-multiplication", "max_stars_repo_head_hexsha": "0c0626da5037dfa0f8b43db2b9cb90272a02dc8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "matmatall.hpp", "max_issues_repo_name": "mindpad/matrix-matrix-multiplication", "max_issues_repo_head_hexsha": "0c0626da5037dfa0f8b43db2b9cb90272a02dc8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "matmatall.hpp", "max_forks_repo_name": "mindpad/matrix-matrix-multiplication", "max_forks_repo_head_hexsha": "0c0626da5037dfa0f8b43db2b9cb90272a02dc8a", "max_forks_repo_licenses": ["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.9285714286, "max_line_length": 109, "alphanum_fraction": 0.7637231504, "num_tokens": 104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548646660542, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.45971651129010377}}
{"text": "// On-the-Fly Algorithm for Emptyness of NBAs [Yannakakis et. al].\r\n// Model Checking, Institute of Computer Science, University of Innsbruck.\r\n// Written by Daniel Strigl.\r\n\r\n//          Copyright Daniel Strigl 2008.\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#include <boost/graph/adjacency_list.hpp>\r\n#include <iostream>\r\n#include <vector>\r\n#include <string>\r\n#include <sstream>\r\nusing namespace boost;\r\n\r\n// Typedefs and defines\r\ntypedef adjacency_list<vecS, vecS, directedS> graph_t;\r\ntypedef graph_traits<graph_t>::vertex_descriptor vertex_t;\r\n#define _countof(array) (sizeof(array) / sizeof(array[0]))\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n\r\n#if 1\r\n\r\n// ----------------------------------------------------------------------------\r\n//  Sample 1 \r\n//    [http://cl-informatik.uibk.ac.at/teaching/ss08/mc/exercises.pdf, Ex. 1]  \r\n// ----------------------------------------------------------------------------\r\n\r\n// Set up the vertex names\r\nenum { _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, N };\r\nchar* name[] = { \r\n    \"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"11\" };\r\n\r\n// Specify the edges in the graph\r\ntypedef std::pair<int, int> E;\r\nE edge_array[] = { \r\n    E( _0,  _1), E( _0,  _2), E( _0,  _3),\r\n    E( _1,  _0),\r\n    E( _2,  _3), E( _2,  _8),\r\n    E( _3,  _4),\r\n    E( _4,  _5), E( _4,  _6), E( _4,  _7),\r\n    E( _5,  _7),\r\n    E( _6,  _2), E( _6,  _7),\r\n    E( _7, _11),\r\n    E( _8,  _9),\r\n    E( _9,  _3), E( _9,  _6), E( _9, _10),\r\n    E(_10,  _6), E(_10,  _7), E(_10,  _9), E(_10, _11),\r\n    E(_11,  _7)\r\n};\r\n\r\n// Specify the final (accepting) states\r\nvertex_t F[] = { _0, _4, _5, _9, _10 };\r\n\r\n// Specify the initial state\r\nvertex_t S = _0;\r\n\r\n#else /////////////////////////////////////////////////////////////////////////\r\n\r\n// ----------------------------------------------------------------------------\r\n//  Sample 2 \r\n//    [http://cl-informatik.uibk.ac.at/teaching/ss08/mc/ohp/1x1.pdf, Slide 23]  \r\n// ----------------------------------------------------------------------------\r\n\r\n// Set up the vertex names\r\nenum { _q0, _q1, _q2, _q3, N };\r\nchar* name[] = { \"q0\", \"q1\", \"q2\", \"q3\" };\r\n\r\n// Specify the edges in the graph\r\ntypedef std::pair<int, int> E;\r\nE edge_array[] = { \r\n    E(_q0, _q1), E(_q0, _q2),\r\n    E(_q1, _q2), E(_q1, _q3),\r\n    E(_q2, _q3),\r\n    E(_q3, _q2),\r\n};\r\n\r\n// Specify the final (accepting) states\r\nvertex_t F[] = { _q1, _q2 };\r\n\r\n// Specify the initial state\r\nvertex_t S = _q0;\r\n\r\n#endif\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n\r\nstatic std::vector<vertex_t> finalStates(F, F + _countof(F));\r\nstatic graph_t g(edge_array, edge_array + sizeof(edge_array) / sizeof(E), N);\r\nstatic std::vector<bool> marked(num_vertices(g), false);\r\nstatic std::vector<bool> flagged(num_vertices(g), false);\r\nstatic std::vector<vertex_t> outer_dfs_stack;\r\nstatic std::vector<vertex_t> inner_dfs_stack;\r\nstatic std::basic_ostringstream<char> word;\r\n\r\nstatic void plot_list(std::vector<bool>& l)\r\n{\r\n    std::vector<vertex_t> tmp;\r\n    for (size_t i = 0; i < l.size(); ++i)\r\n        if (l[i])\r\n            tmp.push_back(i);\r\n\r\n    if (tmp.empty())\r\n    {\r\n        std::cout << \"$\\\\varnothing$\";\r\n        return;\r\n    }\r\n\r\n    std::cout << \"\\\\{\";\r\n\r\n    for (size_t i = 0; i < tmp.size(); ++i)\r\n    {\r\n        std::cout << name[tmp[i]];\r\n        if (i < tmp.size() - 1)\r\n            std::cout << \", \";\r\n    }\r\n\r\n    std::cout << \"\\\\}\";\r\n}\r\n\r\nstatic void plot_stack(std::vector<vertex_t>& s)\r\n{\r\n    if (s.empty())\r\n    {\r\n        std::cout << \"$\\\\varepsilon$\";\r\n        return;\r\n    }\r\n\r\n    for (size_t i = s.size(); i > 0; --i)\r\n    {\r\n        std::cout << name[s[i-1]];\r\n        if (i > 1)\r\n            std::cout << \", \";\r\n    }\r\n}\r\n\r\nstatic void plot_stat()\r\n{\r\n    plot_stack(outer_dfs_stack);\r\n    std::cout << \" & \";\r\n    plot_stack(inner_dfs_stack); \r\n    std::cout << \" & \";\r\n    plot_list(marked);\r\n    std::cout << \" & \";\r\n    plot_list(flagged);\r\n    std::cout << \" \\\\\\\\\" << std::endl;\r\n}\r\n\r\nstatic bool inner_dfs(const graph_t& g, vertex_t q)\r\n{\r\n    inner_dfs_stack.push_back(q);\r\n\r\n    flagged[q] = true;\r\n\r\n    plot_stat();\r\n\r\n    graph_traits<graph_t>::adjacency_iterator vi, vi_end;\r\n\r\n    for (tie(vi, vi_end) = adjacent_vertices(q, g); vi != vi_end; ++vi)\r\n    {\r\n        std::vector<vertex_t>::const_iterator res;\r\n\r\n        if ((res = find(outer_dfs_stack.begin(), outer_dfs_stack.end(), *vi)) \r\n            != outer_dfs_stack.end())\r\n        {\r\n            for (std::vector<vertex_t>::const_iterator \r\n                itr = outer_dfs_stack.begin();\r\n                itr != outer_dfs_stack.end(); ++itr)\r\n            {\r\n                word << name[*itr] << \"\\\\:\";\r\n            }\r\n\r\n            word << \"\\\\left(\\\\:\";\r\n\r\n            for (std::vector<vertex_t>::const_iterator \r\n                itr = inner_dfs_stack.begin() + 1;\r\n                itr != inner_dfs_stack.end(); ++itr)\r\n            {\r\n                word << name[*itr] << \"\\\\:\";\r\n            }\r\n\r\n            for (std::vector<vertex_t>::const_iterator itr = res;\r\n                itr != outer_dfs_stack.end(); ++itr)\r\n            {\r\n                word << name[*itr] << \"\\\\:\";\r\n            }\r\n\r\n            word << \"\\\\right)\" << \"^{\\\\omega}\";\r\n\r\n            return false;\r\n        }\r\n        else if (!flagged[*vi])\r\n        {\r\n            if (!inner_dfs(g, *vi))\r\n                return false;\r\n        }\r\n    }\r\n\r\n    inner_dfs_stack.pop_back();\r\n\r\n    return true;\r\n}\r\n\r\nstatic bool outer_dfs(const graph_t& g, vertex_t q)\r\n{\r\n    outer_dfs_stack.push_back(q);\r\n\r\n    marked[q] = true;\r\n\r\n    plot_stat();\r\n\r\n    graph_traits<graph_t>::adjacency_iterator vi, vi_end;\r\n\r\n    for (tie(vi, vi_end) = adjacent_vertices(q, g); vi != vi_end; ++vi)\r\n    {\r\n        if (!marked[*vi])\r\n        {\r\n            if (!outer_dfs(g, *vi))\r\n                return false;\r\n        }\r\n    }\r\n\r\n    if (find(finalStates.begin(), finalStates.end(), q) != finalStates.end())\r\n        if (!inner_dfs(g, q))\r\n            return false;\r\n\r\n    outer_dfs_stack.pop_back();\r\n\r\n    return true;\r\n}\r\n\r\nint main(int argc, char* argv[])\r\n{\r\n    std::cout << \"\\\\documentclass[landscape]{article}\" << std::endl;\r\n    std::cout << \"\\\\usepackage{lscape}\" << std::endl;\r\n    std::cout << \"\\\\usepackage[latin1]{inputenc}\" << std::endl;\r\n    std::cout << \"\\\\usepackage{amssymb}\" << std::endl;\r\n    std::cout << std::endl;\r\n    std::cout << \"\\\\begin{document}\" << std::endl;\r\n    std::cout << std::endl;\r\n    std::cout << \"\\\\begin{table}[htb]\" << std::endl;\r\n    std::cout << \"\\\\begin{center}\" << std::endl;\r\n    std::cout << \"\\\\begin{tabular}{cccc}\" << std::endl;\r\n    std::cout << \"\\\\textbf{outer\\\\_dfs-stack} & \\\\textbf{inner\\\\_dfs-stack} &\"\\\r\n        \" \\\\textbf{marked} & \\\\textbf{flagged} \\\\\\\\\" << std::endl;\r\n    std::cout << \"\\\\hline\" << std::endl;\r\n    std::cout << \"$\\\\varepsilon$ & $\\\\varepsilon$ & $\\\\varnothing$ &\"\\\r\n        \" $\\\\varnothing$ \\\\\\\\\" << std::endl;\r\n\r\n    const bool result = outer_dfs(g, S);\r\n\r\n    std::cout << \"\\\\end{tabular}\" << std::endl;\r\n    std::cout << \"\\\\end{center}\" << std::endl;\r\n    std::cout << \"\\\\end{table}\" << std::endl;\r\n    std::cout << std::endl;\r\n\r\n    std::cout << \"\\\\begin{center}\" << std::endl;\r\n    if (result)\r\n        std::cout << \"\\\\textbf{terminate}(true)\" << std::endl;\r\n    else\r\n        std::cout << \"\\\\textbf{terminate}(false)\" << std::endl;\r\n    std::cout << \"\\\\end{center}\" << std::endl;\r\n\r\n    if (!result)\r\n    {\r\n        std::cout << std::endl;\r\n        std::cout << \"\\\\begin{center}\" << std::endl;\r\n        std::cout << \"$word = \" << word.str() << \"$\" << std::endl;\r\n        std::cout << \"\\\\end{center}\" << std::endl;\r\n    }\r\n\r\n    std::cout << std::endl;\r\n    std::cout << \"\\\\end{document}\" << std::endl;\r\n\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "c0209ba99cef95b0806b6ab04482d11e6fbeafa7", "size": 7912, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mcotf.cpp", "max_stars_repo_name": "dstrigl/mcotf", "max_stars_repo_head_hexsha": "92a9caf6173b1241a2f9ed45cd379469762b7178", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mcotf.cpp", "max_issues_repo_name": "dstrigl/mcotf", "max_issues_repo_head_hexsha": "92a9caf6173b1241a2f9ed45cd379469762b7178", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mcotf.cpp", "max_forks_repo_name": "dstrigl/mcotf", "max_forks_repo_head_hexsha": "92a9caf6173b1241a2f9ed45cd379469762b7178", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4604316547, "max_line_length": 81, "alphanum_fraction": 0.4753538928, "num_tokens": 2247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548646660542, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.4597165072591763}}
{"text": "//==================================================================================================\n/*!\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#include <boost/simd/constant/thirdrooteps.hpp>\n#include <boost/simd/constant/eps.hpp>\n#include <boost/simd/as.hpp>\n#include <scalar_test.hpp>\n\nSTF_CASE_TPL( \"Check thirdrooteps behavior for integral types\"\n            , (std::uint8_t)(std::uint16_t)(std::uint32_t)(std::uint64_t)\n              (std::int8_t)(std::int16_t)(std::int32_t)(std::int64_t)\n            )\n{\n  using boost::simd::as;\n  using boost::simd::detail::thirdrooteps;\n  using boost::simd::Thirdrooteps;\n\n  STF_TYPE_IS(decltype(Thirdrooteps<T>()), T);\n  STF_EQUAL(Thirdrooteps<T>(), T(1));\n  STF_EQUAL(thirdrooteps( as(T{}) ),T(1));\n}\n\nSTF_CASE_TPL( \"Check thirdrooteps behavior for floating types\"\n            , (double)(float)\n            )\n{\n  using boost::simd::as;\n  using boost::simd::detail::thirdrooteps;\n  using boost::simd::Thirdrooteps;\n  using boost::simd::Eps;\n\n  STF_TYPE_IS(decltype(Thirdrooteps<T>()), T);\n  auto z1 = Thirdrooteps<T>();\n  STF_ULP_EQUAL(z1*z1*z1, Eps<T>(), 0.5);\n  auto z2 = thirdrooteps( as(T{}));\n  STF_ULP_EQUAL(z2*z2*z2, Eps<T>(), 0.5);\n}\n", "meta": {"hexsha": "88348017d26299ce6b81da1f0a1e558b584c7ddb", "size": 1424, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/constant/scalar/thirdrooteps.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": "test/constant/scalar/thirdrooteps.cpp", "max_issues_repo_name": "remymuller/boost.simd", "max_issues_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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/constant/scalar/thirdrooteps.cpp", "max_forks_repo_name": "remymuller/boost.simd", "max_forks_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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": 32.3636363636, "max_line_length": 100, "alphanum_fraction": 0.5723314607, "num_tokens": 390, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850154599563, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.4597165032282488}}
{"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// This define to disable bounds checking in boost::multi_array\n#define BOOST_DISABLE_ASSERTS\n\n#include <cfloat>\n#include <algorithm>\n#include <iostream>\n#include <fstream>\n\n#include <boost/multi_array.hpp>\n#include <boost/array.hpp>\n#include <boost/iterator/zip_iterator.hpp>\n#include <boost/tuple/tuple.hpp>\n\n#include \"confint.hpp\"\n\nusing namespace std;\n\n#define TIMER 1\n\n////////////////////////////////////////////////////////////////////////////////\ninline double euclid_dist_sq(double x, double y)\n{\n  const double temp = x - y;\n  return temp * temp;\n}\n\n\n////////////////////////////////////////////////////////////////////////////////\n// read in the data points\n// select initial cluster centroids\n////////////////////////////////////////////////////////////////////////////////\ntemplate<typename Stream, typename Points, typename Centroids>\nvoid kmeans_input(Stream& in_str, Points& points, Centroids& centroids)\n{\n  typedef decltype(*points.begin()) point_ref;\n\n  std::for_each(points.begin(), points.end(), [&](point_ref&& point) {\n    in_str.read((char*) &point[0], sizeof(double) * point.size());\n\n    if (in_str.fail())\n    {\n      cerr << \"Incomplete file read\" << endl;\n      exit(1);\n    }\n  });\n\n  std::copy(points.begin(), points.begin() + centroids.size(),\n            centroids.begin());\n}\n\n\n////////////////////////////////////////////////////////////////////////////////\n// display results to standard output\n////////////////////////////////////////////////////////////////////////////////\ntemplate<typename Centroids>\nvoid kmeans_output(int k_clusters, int point_count, int dimensions,\n                   Centroids& centroids)\n{\n  cout << \"k= \" << k_clusters << \", n= \" << point_count << \", \";\n  cout << \"d= \" << dimensions << endl;\n  cout << \"CENTROIDS\" << endl;\n\n  typedef decltype(*centroids.begin()) centroid_ref;\n\n  std::for_each(centroids.begin(), centroids.end(),[&](centroid_ref&& centroid){\n    std::for_each(centroid.begin(), centroid.end(),\n                  [&](double const& dimension) { cout << dimension << \" \"; });\n    cout << endl; });\n}\n\n\n////////////////////////////////////////////////////////////////////////////////\n// k-means computation\n////////////////////////////////////////////////////////////////////////////////\ntemplate<typename Points, typename Centroids, typename Counts>\nvoid kmeans_seq(Counts& old_assign_counts, Centroids& old_centroids,\n                Counts& new_assign_counts, Centroids& new_centroids,\n                Points& points, double& mean_sq_err, int& iterations) {\n\n  std::vector<double> distance(old_centroids.size());\n  double              old_mean_sq_err;\n  double              new_mean_sq_err;\n  std::plus<double>   plus_wf;\n\n  typedef decltype(*(old_centroids.begin())) point_ref;\n\n  do {\n    old_mean_sq_err = mean_sq_err;\n    new_mean_sq_err = 0.0;\n\n    // initialize for another iteration\n    std::fill(new_assign_counts.begin(), new_assign_counts.end(), 0);\n\n    for_each(new_centroids.begin(), new_centroids.end(),\n             [](point_ref&& centroid) {\n               std::fill(centroid.begin(), centroid.end(), 0.0); });\n\n    // for all points\n    for_each(points.begin(), points.end(), [&](point_ref&& point) {\n      // compute squared Euclidean distance from all centroids to this point\n      std::transform(\n        old_centroids.begin(), old_centroids.end(), distance.begin(),\n        [&](point_ref&& centroid) {\n          return std::inner_product(point.begin(),point.end(),centroid.begin(),\n                                    0, plus_wf, euclid_dist_sq); });\n\n      // find the nearest centroid to this point\n      auto iter         = std::min_element(distance.begin(), distance.end());\n      const int nearest = std::distance(distance.begin(), iter);\n\n      // update the new owner centroid to include this point\n      std::transform(new_centroids[nearest].begin(),\n                     new_centroids[nearest].end(), point.begin(),\n                     new_centroids[nearest].begin(), plus_wf);\n\n      ++new_assign_counts[nearest];\n\n      new_mean_sq_err += std::inner_product(point.begin(), point.end(),\n                                            old_centroids[nearest].begin(), 0,\n                                            plus_wf, euclid_dist_sq);\n    });\n\n    // re-estimate the centroids as the average of the assigned points\n    std::transform(new_assign_counts.begin(), new_assign_counts.end(),\n                   old_assign_counts.begin(),\n                   [](int& new_count) { return std::max(new_count, 1); });\n\n    auto beg_iter = boost::make_zip_iterator(boost::make_tuple(\n      old_centroids.begin(), new_centroids.begin(), old_assign_counts.begin()));\n\n    auto end_iter = boost::make_zip_iterator(boost::make_tuple(\n      old_centroids.end(), new_centroids.end(), old_assign_counts.end()));\n\n    typedef decltype(*beg_iter) tuple_ref;\n\n    std::for_each(beg_iter, end_iter, [](tuple_ref&& t) {\n      std::transform(boost::get<1>(t).begin(), boost::get<1>(t).end(),\n                     boost::get<0>(t).begin(), [&](double const& dimension) {\n                       return dimension / boost::get<2>(t); }); });\n\n    ++iterations;\n\n    mean_sq_err = new_mean_sq_err;\n  } while (mean_sq_err < old_mean_sq_err);\n}\n\n\n////////////////////////////////////////////////////////////////////////////////\n// driver\n////////////////////////////////////////////////////////////////////////////////\nvoid kmeans(int k_clusters, int point_count, int dimensions, ifstream& in_str)\n{\n#ifdef TIMER\n  counter_t timer;\n  timer.reset();\n  timer.start();\n#endif\n\n  typedef boost::multi_array<double, 2> points_ct_t;\n  typedef std::vector<int>              counts_ct_t;\n\n  const auto points_extents    = boost::extents[point_count][dimensions];\n  const auto centroids_extents = boost::extents[ k_clusters][dimensions];\n\n  points_ct_t points(points_extents);\n\n#ifdef TIMER\n  points_ct_t initial_centroids(centroids_extents);\n#endif\n\n  points_ct_t old_centroids(centroids_extents);\n  points_ct_t new_centroids(centroids_extents);\n\n  counts_ct_t old_assign_counts(k_clusters);\n  counts_ct_t new_assign_counts(k_clusters);\n\n  double mean_sq_err = DBL_MAX;\n  int iterations     = 0;\n\n  kmeans_input(in_str, points, old_centroids);\n\n  initial_centroids = old_centroids;\n\n#ifdef TIMER\n  double io_time = timer.stop();\n\n  confidence_interval_controller iter_control(32, 100, 0.05);\n\n  while (iter_control.iterate())\n  {\n    old_centroids = initial_centroids;\n\n    timer.reset();\n    timer.start();\n#endif\n\n  kmeans_seq(old_assign_counts, old_centroids, new_assign_counts, new_centroids,\n             points, mean_sq_err, iterations);\n\n#ifdef TIMER\n    iter_control.push_back(timer.stop());\n  }\n#endif\n\n  kmeans_output(k_clusters, point_count, dimensions, old_centroids);\n\n#ifdef TIMER\n iter_control.report(\"km_seq\");\n cout << \"io= \" << io_time << \",\";\n cout << \"mse= \" << mean_sq_err << \", iter= \" << iterations << endl;\n#endif\n}\n\n\n////////////////////////////////////////////////////////////////////////////////\nint main(int argc, char **argv)\n{\n  if ( argc < 2 ) {\n    cerr << \"Cluster count must be specified on command line\" << endl;\n    exit(1);\n  }\n\n  int k_clusters = atoi( argv[1] );\n\n  if ( k_clusters < 2 ) {\n    cerr << \"Cluster count must be greater than 1\" << endl;\n    exit(1);\n  }\n\n  if ( argc < 3 ) {\n    cerr << \"Point count must be specified on command line\" << endl;\n    exit(1);\n  }\n\n  int point_count = atoi( argv[2] );\n\n  if ( point_count < 1 ) {\n    cerr << \"Point count must be greater than 0\" << endl;\n    exit(1);\n  }\n\n  if ( argc < 4 ) {\n    cerr << \"Dimension count must be specified on command line\" << endl;\n    exit(1);\n  }\n\n  int dimensions = atoi( argv[3] );\n\n  if ( point_count < 2 ) {\n    cerr << \"Dimensions must be greater than 1\" << endl;\n    exit(1);\n  }\n\n  if ( argc < 5 ) {\n    cerr << \"Input file must be specified on command line\" << endl;\n    exit(1);\n  }\n\n  ifstream in_str;\n  in_str.open(argv[4], ios::binary|ios::in );\n\n  if ( !in_str.is_open() ) {\n    cerr << \"Input file must be specified on command line\" << endl;\n    exit(1);\n  }\n\n  kmeans(k_clusters, point_count, dimensions, in_str);\n\n  in_str.close();\n}\n", "meta": {"hexsha": "c05c3d9f8bdaeace9abfc24a08c647da9df880e4", "size": 8509, "ext": "cc", "lang": "C++", "max_stars_repo_path": "stapl_release/benchmarks/data_mining/k_means_cluster/km_stl.cc", "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/benchmarks/data_mining/k_means_cluster/km_stl.cc", "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/benchmarks/data_mining/k_means_cluster/km_stl.cc", "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": 30.1737588652, "max_line_length": 80, "alphanum_fraction": 0.5847925726, "num_tokens": 1862, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195152660687, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.4596499774832081}}
{"text": "#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <unordered_map>\n#include <boost/format.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/variance.hpp>\n#include <boost/spirit/include/qi.hpp>\n#include <boost/progress.hpp>\n#include <boost/program_options.hpp>\n#include <boost/log/trivial.hpp>\n#include <boost/log/utility/setup/console.hpp>\n#define LOG(x) BOOST_LOG_TRIVIAL(x)\n#include \"csvlint.h\"\n#define USE_OPENMP 1\n#include \"bigtext.h\"\n\nusing namespace std;\nusing namespace boost;\nnamespace po = boost::program_options; \nnamespace ba = boost::accumulators;\nnamespace qi = boost::spirit::qi;\ntypedef ba::accumulator_set<double, ba::stats<ba::tag::mean, ba::tag::variance>> Acc;\n\nsize_t topk = 20;\n\nstruct Column {\n    vector<csvlint::crange> strings;\n    vector<float> floats;\n    size_t missing;\n};\n\nstruct Chunk {\n    vector<string> lines;\n    vector<csvlint::crange> cols;\n    vector<Column> data;\n    size_t total;\n};\n\nsize_t total (vector<Chunk> const &chunks) {\n    size_t v = 0;\n    for (auto const &ch: chunks) {\n        v += ch.total;\n    }\n    return v;\n}\n\nsize_t good (vector<Chunk> const &chunks) {\n    size_t v = 0;\n    for (auto const &ch: chunks) {\n        v += ch.data.size();\n    }\n    return v;\n}\n\n// percentiles must be previously sorted\nvoid percentiles (vector<float> &all, vector<float> &ps) {\n    vector<size_t> offs(ps.size());\n    for (unsigned i = 0; i < offs.size(); ++i) {\n        offs[i] = round(ps[i] * all.size());\n        if (offs[i] >= all.size()) {\n            offs[i] = all.size() - 1;\n        }\n        if (i) {\n            BOOST_VERIFY(offs[i] > offs[i-1]);\n        }\n    }\n    size_t last = 0;\n    for (unsigned i = 0; i < offs.size(); ++i) {\n        nth_element(all.begin() + last, all.begin() + offs[i], all.end());\n        ps[i] = all[offs[i]];\n        last = offs[i];\n    }\n}\n\nvoid stat_number (csvlint::Field const &f,  vector<Chunk> const &chunks, string *out) {\n    vector<float> all(good(chunks));\n    unsigned col = f.column;\n    unsigned off = 0;\n    size_t missing = 0;\n    Acc acc;\n    for (auto const &ch: chunks) {\n        for (float e: ch.data[col].floats) {\n            all[off++] = e;\n            acc(e);\n        }\n        missing += ch.data[col].missing;\n    }\n    all.resize(off);\n    vector<float> ps{0, 0.25, 0.5, 0.75, 1.0};\n    percentiles(all, ps);\n    ostringstream ss;\n    ss << 'N' << f.column <<':' << f.name \n        << ',' << missing\n        << ',' << all.size()\n        << ',' << ba::mean(acc)\n        << ',' << sqrt(ba::variance(acc));\n    for (auto v: ps) {\n        ss << ',' << v;\n    }\n    *out = ss.str();\n}\n\nvoid stat_string (csvlint::Field const &f, vector<Chunk> const &chunks, string *out, char C='S') {\n    unordered_map<string, size_t> cnts;\n    unsigned col = f.column;\n    size_t missing = 0;\n    for (auto const &ch: chunks) {\n        for (auto e: ch.data[col].strings) {\n            ++cnts[string(e.begin(), e.end())];\n        }\n        missing += ch.data[col].missing;\n    }\n    vector<pair<size_t,string>> sz(cnts.size());\n    {\n        size_t o = 0;\n        for (auto const &p: cnts) {\n            sz[o].first = p.second;\n            sz[o].second = p.first;\n            ++o;\n        }\n    }\n    sort(sz.begin(), sz.end());\n    reverse(sz.begin(), sz.end());\n    ostringstream ss;\n    ss << C << f.column << ':' << f.name << \",NA:\" << missing << \",VALUES:\" << sz.size();\n    if (sz.size() > topk) sz.resize(topk);\n    for (auto const &e: sz) {\n        ss << \",'\" << e.second << \"':\" << e.first;\n    }\n    if (cnts.size() > sz.size()) {\n        ss << \",...\";\n    }\n    *out = ss.str();\n}\n\nvoid stat_column (csvlint::Field const &f, vector<Chunk> const &chunks, string *out) {\n    if (f.type == csvlint::TYPE_NUMERIC) {\n        string o1, o2;\n        stat_number(f, chunks, &o1);\n        stat_string(f, chunks, &o2, 'I');\n        o1.push_back('\\n');\n        *out = o1 + o2;\n    }\n    else if (f.type == csvlint::TYPE_STRING) {\n        stat_string(f, chunks, out);\n    }\n    else BOOST_VERIFY(0);\n}\n\nint main (int argc, char *argv[]) {\n    unsigned guess_size;\n    \n    string input_path;\n    string output_path;\n    po::options_description desc_visible(\"General options\");\n    desc_visible.add_options()\n    (\"help,h\", \"produce help message.\")\n    (\"input,I\", po::value(&input_path), \"input path\")\n    (\",M\", po::value(&guess_size)->default_value(10), \"\")\n    (\"topk\", po::value(&topk)->default_value(topk), \"\")\n    ;\n    po::options_description desc(\"Allowed options\");\n    desc.add(desc_visible);\n\n    po::positional_options_description p;\n    p.add(\"input\", 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\") || vm.count(\"input\") == 0) {\n        cout << \"Usage: csvlint-stat [OTHER OPTIONS]... <data>\" << endl;\n        cout << desc_visible << endl;\n        return 0;\n    }\n\n    boost::log::add_console_log(cerr);\n\n    csvlint::Format fmt;\n    fmt.train(input_path, guess_size * 1024 * 1024);\n\n    cerr << \"Parsing text...\" << endl;\n    BigText<Chunk> text(input_path, fmt.data_offset, '\\n', fmt.max_line, 10 * 1024*1024);\n\n    for (auto &ch: text) {\n        ch.total = 0;\n        ch.data.resize(fmt.fields.size());\n        for (auto &v: ch.data) {\n            v.missing = 0;\n        }\n    }\n    text.lines ([&fmt](char const *begin, char const *end, Chunk *ch, size_t i_in_block) {\n        auto &cols = ch->cols;\n        ch->lines.emplace_back(begin, end);\n        bool r = fmt.parse(csvlint::crange(std::ref(ch->lines.back())), &cols);\n        if (r) {\n            for (unsigned i = 0; i < fmt.fields.size(); ++i) {\n                Column &data = ch->data[i];\n                auto const &field = fmt.fields[i];\n                csvlint::crange e = cols[i];\n                if (e.missing()) {\n                    ++data.missing;\n                }\n                else {\n                    if (field.type == csvlint::TYPE_NUMERIC) {\n                        float v;\n                        qi::parse(e.begin(), e.end(), qi::float_, v);\n                        data.floats.push_back(v);\n                    }\n                    data.strings.push_back(e);\n                }\n            }\n        }\n        ++ch->total;\n    });\n\n    cerr << total(text) << \" total lines.\" << endl;\n    cerr << good(text) << \" good lines.\" << endl;\n\n    vector<string> stats(fmt.fields.size());\n\n    cerr << \"Counting numbers...\" << endl;\n    progress_display progress(fmt.fields.size(), cerr);\n#pragma omp parallel for\n    for (unsigned i = 0; i < fmt.fields.size(); ++i) {\n        stat_column(fmt.fields[i], text, &stats[i]);\n#pragma omp critical\n        ++progress;\n    }\n\n\n    for (auto &st: stats) {\n        if (st.empty()) continue;\n        cout << st << endl;\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "818a6e461e1a622198f9a652e587030e832c2fe3", "size": 6935, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "csvlint-stat.cpp", "max_stars_repo_name": "aaalgo/csvlint", "max_stars_repo_head_hexsha": "14ded6b8638aff10582a62e7e458f881309dbe30", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "csvlint-stat.cpp", "max_issues_repo_name": "aaalgo/csvlint", "max_issues_repo_head_hexsha": "14ded6b8638aff10582a62e7e458f881309dbe30", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "csvlint-stat.cpp", "max_forks_repo_name": "aaalgo/csvlint", "max_forks_repo_head_hexsha": "14ded6b8638aff10582a62e7e458f881309dbe30", "max_forks_repo_licenses": ["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.5390946502, "max_line_length": 98, "alphanum_fraction": 0.5421773612, "num_tokens": 1879, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.734119526900183, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.45964997452442996}}
{"text": "#include <Engine/MeshEdit/Paramaterize.h>\n#include <Engine/MeshEdit/MinSurf.h>\n#include <Engine/Primitive/TriMesh.h>\n#include <Eigen/Sparse>\n#include <Eigen/SparseQR>\n\nusing namespace Ubpa;\nusing namespace Eigen;\nusing namespace std;\n\nParamaterize::Paramaterize(Ptr<TriMesh> triMesh, bool uSquare, bool uUniform) \t\n    : heMesh(make_shared<HEMesh<V>>()), useSquare(uSquare), useUniform(uUniform) {\n\tInit(triMesh);\n}\n\nvoid Paramaterize::Clear() {\n\theMesh->Clear();\n\ttriMesh = nullptr;\n}\n\nbool Paramaterize::Init(Ptr<TriMesh> triMesh) {\n\tClear();\n\n\tif (triMesh == nullptr)\n\t\treturn true;\n\n\tif (triMesh->GetType() == TriMesh::INVALID) {\n\t\tprintf(\"ERROR::Parameterize::Init:\\n\"\n\t\t\t\"\\t\"\"trimesh is invalid\\n\");\n\t\treturn false;\n\t}\n\n\t// init half-edge structure\n\tsize_t nV = triMesh->GetPositions().size();\n\tvector<vector<size_t>> triangles;\n\ttriangles.reserve(triMesh->GetTriangles().size());\n\tfor (auto triangle : triMesh->GetTriangles())\n\t\ttriangles.push_back({ triangle->idx[0], triangle->idx[1], triangle->idx[2] });\n\theMesh->Reserve(nV);\n\theMesh->Init(triangles);\n\n\tif (!heMesh->IsTriMesh() || !heMesh->HaveBoundary()) {\n\t\tprintf(\"ERROR::Parameterize::Init:\\n\"\n\t\t\t\"\\t\"\"trimesh is not a triangle mesh or hasn't a boundaries\\n\");\n\t\theMesh->Clear();\n\t\treturn false;\n\t}\n\n\t// triangle mesh's positions ->  half-edge structure's positions\n\tfor (int i = 0; i < nV; i++) {\n\t\tauto v = heMesh->Vertices().at(i);\n\t\tv->pos = triMesh->GetPositions()[i].cast_to<vecf3>();\n\t}\n\n\tthis->triMesh = triMesh;\n\treturn true;\n}\n\nvoid Paramaterize::DoPara() {\n\t// First, detect and fix boundary\n\trandom_set<V*> boundary_points;\n\trandom_set<V*> inner_points;\n\n\tauto boundaries = this->heMesh->Boundaries();\n\tif (boundaries.size() != 1) {\n\t\tcout << \"ERROR::Parameterize::DoPara:\" << endl\n\t\t\t << \"\\t\" << \"got boundaries = \" << boundaries.size()\n\t\t\t << \" (expect 1)\" << endl;\n\t\treturn;\n\t}\n\n\tfor (auto v: boundaries[0]) {\n\t\tboundary_points.insert(v->Origin());\n\t}\n\n\tfor (auto v: heMesh->Vertices()) {\n\t\tif (!boundary_points.contains(v)) {\n\t\t\tinner_points.insert(v);\n\t\t}\n\t}\n\n\t//const float boost_factor = 100;\n\tconst float boost_factor = 1;\n\t// Fix our boundary\n\tif (useSquare) {\n\t\tint points_total = boundary_points.size();\n\t\tfloat step = 4.0f / points_total;\n\n\t\tfloat curr = 0;\n\t\tfor (auto v: boundary_points) {\n\t\t\tvecf3 new_pos;\n\t\t\tif (curr >= 0 && curr < 1) {\n\t\t\t\tnew_pos[0] = curr;\n\t\t\t\tnew_pos[1] = new_pos[2] = 0;\n\t\t\t} else if (curr >= 1 && curr < 2) {\n\t\t\t\tnew_pos[0] = 1;\n\t\t\t\tnew_pos[1] = curr - 1;\n\t\t\t\tnew_pos[2] = 0;\n\t\t\t} else if (curr >= 2 && curr < 3) {\n\t\t\t\tnew_pos[0] = 1 - (curr - 2);\n\t\t\t\tnew_pos[1] = 1;\n\t\t\t\tnew_pos[2] = 0;\n\t\t\t} else { // curr >= 3; remember to cut off as fp precision is an issue\n\t\t\t\tnew_pos[0] = 0;\n\t\t\t\tnew_pos[1] = curr > 4 ? 4 : 4 - curr;\n\t\t\t\tnew_pos[2] = 0;\n\t\t\t}\n\t\t\tv->pos = new_pos * boost_factor;\n\t\t\tcurr += step;\n\t\t}\n\n\t} else {\n\t\tint points_total = boundary_points.size();\n\t\tfloat step = 2 * 3.1415926f / points_total;\n\n\t\tfloat curr = 0;\n\t\tfor (auto v: boundary_points) {\n\t\t\tvecf3 new_pos;\n\t\t\tnew_pos[0] = cosf(curr);\n\t\t\tnew_pos[1] = sinf(curr);\n\t\t\tnew_pos[2] = 0;\n\n\t\t\tv->pos = new_pos * boost_factor;\n\t\t\tcurr += step;\n\t\t}\n\t}\n\n\t// Build sparse matrix\n\tsize_t n = inner_points.size();\n\tSparseMatrix<float> coeff_mat(n, n);\n\tcoeff_mat.setZero();\n\tVectorXf b_vec_x = VectorXf::Zero(n);\n\tVectorXf b_vec_y = VectorXf::Zero(n);\n\tVectorXf b_vec_z = VectorXf::Zero(n);\n\n\tcout << \"coeff mat build start\" << endl;\n\n\tif (useUniform) {\n\t\tint current_row = 0;\n\t\tfor (auto v: inner_points) {\n\t\t\t// vidx CERTAINLY follows order (and it's redundant)\n\t\t\tsize_t vidx = inner_points.idx(v);\n\t\t\tauto adj = v->AdjVertices();\n\t\t\tsize_t degree = v->Degree();\n\t\t\tfor (auto adjv : adj) {\n\t\t\t\t// check type\n\t\t\t\tif (boundary_points.contains(adjv)) { // this set is usually smaller\n\t\t\t\t\tb_vec_x(current_row) += (1.0f / degree) * adjv->pos[0];\n\t\t\t\t\tb_vec_y(current_row) += (1.0f / degree) * adjv->pos[1];\n\t\t\t\t\tb_vec_z(current_row) += (1.0f / degree) * adjv->pos[2];\n\t\t\t\t} else { // inner\n\t\t\t\t\tassert(inner_points.contains(adjv));\n\t\t\t\t\tsize_t adjidx = inner_points.idx(adjv);\n\t\t\t\t\t// todo add assert = 0\n\t\t\t\t\tcoeff_mat.insert(current_row, adjidx) = - 1.0f / degree;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// add itself\n\t\t\t// todo add assert\n\t\t\tcoeff_mat.insert(current_row, vidx) = 1;\n\t\t\tcurrent_row++;\n\t\t}\n\t} else { // use cotangent weight\n\n\t\tint fallback_met = 0;\n\t\tint current_row = 0;\n\t\tfor (auto v: inner_points) {\n\t\t\t// vidx CERTAINLY follows order (and it's redundant)\n\t\t\tsize_t vidx = inner_points.idx(v);\n\t\t\tauto adj = v->AdjVertices();\n\t\t\tsize_t degree = v->Degree();\n\n\t\t\tfloat weight_sum = 0;\n\t\t\tbool needFallback = false;\n\t\t\tfor (auto adjv : adj) {\n\t\t\t\t// check type\n\n\t\t\t\tfloat weight = 0;  // this is required to be positive\n\t\t\t\tauto adjadjv = adjv->AdjVertices();\n\n\t\t\t\tdecltype(adjadjv) intersect;\n\t\t\t\tfor (auto vv : adjadjv) {\n\t\t\t\t\tfor (auto vvv : adj) {\n\t\t\t\t\t\tif (vv == vvv && vv != v) {\n\t\t\t\t\t\t\tintersect.push_back(vv);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tassert(intersect.size() == 2);\n\t\t\t\t\t\n\t\t\t\t// calculate angels of two\n\t\t\t\t// (v_i - adjadjv[0]) & (adjadjv[0] - adjv)\n\t\t\t\t// float cos_alpha = (v->pos - adjadjv[0]->pos).cos_theta(adjadjv[0]->pos - adjv->pos) \n\t\t\t\t// \t\t\t\t/ (v->pos - adjadjv[0]->pos).sin_theta(adjadjv[0]->pos - adjv->pos);\n\t\t\t\tfloat ctheta_alpha = -1 * (v->pos - intersect[0]->pos).cos_theta(intersect[0]->pos - adjv->pos);\n\t\t\t\tfloat ctg_alpha = ctheta_alpha / (sqrtf(1 - ctheta_alpha * ctheta_alpha) + 1e-5);\n\t\t\t\t\n\t\t\t\tfloat ctheta_beta = -1 * (v->pos - intersect[1]->pos).cos_theta(intersect[1]->pos - adjv->pos);\n\t\t\t\tfloat ctg_beta = ctheta_beta / (sqrtf(1 - ctheta_beta * ctheta_beta) + 1e-5);\n\n\t\t\t\t// needFallback = true;\n\t\t\t\t// break;\n\t\t\t\tif (ctg_alpha + ctg_beta <= 0) {\n\t\t\t\t\tneedFallback = true;\n\t\t\t\t\tbreak;\n\t\t\t\t} else {\n\t\t\t\t\tweight = ctg_alpha + ctg_beta;\n\t\t\t\t\tweight_sum += weight;\n\t\t\t\t}\n\n\t\t\t\tif (boundary_points.contains(adjv)) { // this set is usually smaller\n\t\t\t\t\tb_vec_x(current_row) += weight * adjv->pos[0];\n\t\t\t\t\tb_vec_y(current_row) += weight * adjv->pos[1];\n\t\t\t\t\tb_vec_z(current_row) += weight * adjv->pos[2];\n\t\t\t\t} else {\n\t\t\t\t\tassert(inner_points.contains(adjv));\n\t\t\t\t\tsize_t adjidx = inner_points.idx(adjv);\n\n\t\t\t\t\tcoeff_mat.insert(current_row, adjidx) = - weight;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (needFallback) {\n\t\t\t\t// update all b_vec, reassign coeff_mat and update weight_sum\n\t\t\t\tb_vec_x(current_row) = 0;\n\t\t\t\tb_vec_y(current_row) = 0;\n\t\t\t\tb_vec_z(current_row) = 0;\n\n\t\t\t\tfor (auto adjv : adj) {\n\t\t\t\t\t// check type\n\t\t\t\t\tif (boundary_points.contains(adjv)) { // this set is usually smaller\n\t\t\t\t\t\tb_vec_x(current_row) += (1.0f / degree) * adjv->pos[0];\n\t\t\t\t\t\tb_vec_y(current_row) += (1.0f / degree) * adjv->pos[1];\n\t\t\t\t\t\tb_vec_z(current_row) += (1.0f / degree) * adjv->pos[2];\n\t\t\t\t\t} else { // inner\n\t\t\t\t\t\tassert(inner_points.contains(adjv));\n\t\t\t\t\t\tsize_t adjidx = inner_points.idx(adjv);\n\t\t\t\t\t\t// todo add assert = 0\n\t\t\t\t\t\tcoeff_mat.coeffRef(current_row, adjidx) = - 1.0f / degree; // since no one knows whether it's inserted or not\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tweight_sum = 1;\n\t\t\t\tfallback_met++;\n\t\t\t}\n\n\t\t\t// add itself\n\t\t\t// todo add assert\n\t\t\tcoeff_mat.insert(current_row, vidx) = weight_sum;\n\t\t\tcurrent_row++;\n\t\t}\n\t\tcout << \"met \" << fallback_met << \" fallback(s).\" << endl;\n\t}\n\n\tcout << \"coeff mat build complete\" << endl;\n\n\t// Solve\n\tSparseQR<SparseMatrix<float>, COLAMDOrdering<int>> solver;\n\n\tcout << \"begin makeCompressed()\" << endl;\n\tcoeff_mat.makeCompressed();\n\n\tcout << \"begin compute()\" << endl;\n\tsolver.compute(coeff_mat);\n\tif (solver.info() != Eigen::Success) {\n\t\tcout << \"solver: decomposition was not successful.\" << endl;\n\t\treturn;\n\t}\n\n\tcout << \"begin solve() for x\" << endl;\n\tVectorXf res_x = solver.solve(b_vec_x);\n\n\tcout << \"begin solve() for y\" << endl;\n\tVectorXf res_y = solver.solve(b_vec_y);\n\n\tcout << \"begin solve() for z\" << endl;\n\tVectorXf res_z = solver.solve(b_vec_z);\n\n\t// Update vertex coordinates\n\tfor (int i = 0; i < n; i++) {\n\t\t// find the corresponding point\n\t\tauto v = inner_points[i];\n\t\tvecf3 new_pos = { res_x(i), res_y(i), res_z(i) }; // works?\n\n\t\t//cout << new_pos << endl;\n\t\tv->pos = new_pos;\n\t}\n\n}\n\nbool Paramaterize::Run() {\n\tif (heMesh->IsEmpty() || !triMesh) {\n\t\tprintf(\"ERROR::Parameterize::Run\\n\"\n\t\t\t\"\\t\"\"heMesh->IsEmpty() || !triMesh\\n\");\n\t\treturn false;\n\t}\n\n\tDoPara();\n\n\t// half-edge structure -> triangle mesh\n\tsize_t nV = heMesh->NumVertices();\n\tsize_t nF = heMesh->NumPolygons();\n\tvector<pointf3> positions;\n\tvector<unsigned> indice;\n\tpositions.reserve(nV);\n\tindice.reserve(3 * nF);\n\tfor (auto v : heMesh->Vertices())\n\t\tpositions.push_back(v->pos.cast_to<pointf3>());\n\tfor (auto f : heMesh->Polygons()) { // f is triangle\n\t\tfor (auto v : f->BoundaryVertice()) // vertices of the triangle\n\t\t\tindice.push_back(static_cast<unsigned>(heMesh->Index(v)));\n\t}\n\n\ttriMesh->Init(indice, positions);\n\n\treturn true;\n}\n", "meta": {"hexsha": "195f308392d945e62b36d653aa4a61e7d26ff5c2", "size": 8733, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Homeworks/4_MinSurfMeshPara/project/src/Engine/MeshEdit/Paramaterize.cpp", "max_stars_repo_name": "libreliu/USTC-CG", "max_stars_repo_head_hexsha": "7064e6c72028187453375fdd6cb66c6ac0182ed2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2020-05-22T00:21:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-18T03:07:04.000Z", "max_issues_repo_path": "Homeworks/4_MinSurfMeshPara/project/src/Engine/MeshEdit/Paramaterize.cpp", "max_issues_repo_name": "libreliu/USTC-CG", "max_issues_repo_head_hexsha": "7064e6c72028187453375fdd6cb66c6ac0182ed2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Homeworks/4_MinSurfMeshPara/project/src/Engine/MeshEdit/Paramaterize.cpp", "max_forks_repo_name": "libreliu/USTC-CG", "max_forks_repo_head_hexsha": "7064e6c72028187453375fdd6cb66c6ac0182ed2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-10-17T15:59:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-17T15:59:09.000Z", "avg_line_length": 27.3761755486, "max_line_length": 115, "alphanum_fraction": 0.6252147029, "num_tokens": 2754, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.734119526900183, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.45964997452442996}}
{"text": "//==================================================================================================\n/*!\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#include <boost/simd/function/scalar/csc.hpp>\n#include <boost/simd/function/restricted.hpp>\n#include <scalar_test.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/minf.hpp>\n#include <boost/simd/constant/nan.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/mone.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/constant/mzero.hpp>\n#include <boost/simd/constant/sqrt_2.hpp>\n#include <boost/simd/constant/pio_2.hpp>\n#include <boost/simd/constant/pio_4.hpp>\n\nSTF_CASE_TPL (\" csc\",  STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::csc;\n\n  using r_t = decltype(csc(T()));\n\n  // return type conformity test\n  STF_TYPE_IS(r_t, T);\n\n  // specific values tests\n#ifndef BOOST_SIMD_NO_INVALIDS\n  STF_ULP_EQUAL(csc(-bs::Zero<T>()), bs::Minf<r_t>(), 0.5);\n  STF_ULP_EQUAL(csc(bs::Inf<T>()), bs::Nan<r_t>(), 0.5);\n  STF_ULP_EQUAL(csc(bs::Minf<T>()), bs::Nan<r_t>(), 0.5);\n  STF_ULP_EQUAL(csc(bs::Nan<T>()), bs::Nan<r_t>(), 0.5);\n  STF_ULP_EQUAL(csc(bs::Zero<T>()), bs::Inf<r_t>(), 0.5);\n#endif\n  STF_ULP_EQUAL(csc(-bs::Pio_2<T>()), bs::Mone<r_t>(), 0.5);\n  STF_ULP_EQUAL(csc(-bs::Pio_4<T>()), -bs::Sqrt_2<r_t>(), 0.5);\n  STF_ULP_EQUAL(csc(bs::Pio_2<T>()), bs::One<r_t>(), 0.5);\n  STF_ULP_EQUAL(csc(bs::Pio_4<T>()), bs::Sqrt_2<r_t>(), 0.5);\n}\n\nSTF_CASE_TPL (\" csc restricted_\",  STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::csc;\n\n  using r_t = decltype(csc(T()));\n\n  // return type conformity test\n  STF_TYPE_IS(r_t, T);\n\n  // specific values tests\n#ifndef BOOST_SIMD_NO_INVALIDS\n  STF_ULP_EQUAL(bs::restricted_(csc)(-bs::Zero<T>()), bs::Minf<r_t>(), 0.5);\n  STF_ULP_EQUAL(bs::restricted_(csc)(bs::Inf<T>()), bs::Nan<r_t>(), 0.5);\n  STF_ULP_EQUAL(bs::restricted_(csc)(bs::Minf<T>()), bs::Nan<r_t>(), 0.5);\n  STF_ULP_EQUAL(bs::restricted_(csc)(bs::Nan<T>()), bs::Nan<r_t>(), 0.5);\n  STF_ULP_EQUAL(bs::restricted_(csc)(bs::Zero<T>()), bs::Inf<r_t>(), 0.5);\n#endif\n  STF_ULP_EQUAL(bs::restricted_(csc)(-bs::Pio_2<T>()), bs::Nan<r_t>(), 0.5);\n  STF_ULP_EQUAL(bs::restricted_(csc)(-bs::Pio_4<T>()), -bs::Sqrt_2<r_t>(), 0.5);\n  STF_ULP_EQUAL(bs::restricted_(csc)(bs::Pio_2<T>()), bs::Nan<r_t>(), 0.5);\n  STF_ULP_EQUAL(bs::restricted_(csc)(bs::Pio_4<T>()), bs::Sqrt_2<r_t>(), 0.5);\n}\n\nSTF_CASE_TPL (\" csc clipped_small_\",  STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bst = bs::tag;\n  namespace bd = boost::dispatch;\n  using bs::csc;\n\n  using r_t = decltype(csc(T()));\n\n  // return type conformity test\n  STF_TYPE_IS(r_t, T);\n\n  // specific values tests\n#ifndef BOOST_SIMD_NO_INVALIDS\n  STF_ULP_EQUAL(csc(-bs::Zero<T>(), bst::clipped_small_), bs::Minf<r_t>(), 0.5);\n  STF_ULP_EQUAL(csc(bs::Inf<T>(), bst::clipped_small_), bs::Nan<r_t>(), 0.5);\n  STF_ULP_EQUAL(csc(bs::Minf<T>(), bst::clipped_small_), bs::Nan<r_t>(), 0.5);\n  STF_ULP_EQUAL(csc(bs::Nan<T>(), bst::clipped_small_), bs::Nan<r_t>(), 0.5);\n  STF_ULP_EQUAL(csc(bs::Zero<T>(), bst::clipped_small_), bs::Inf<r_t>(), 0.5);\n#endif\n  STF_ULP_EQUAL(csc(-bs::Pio_2<T>(), bst::clipped_small_), bs::Mone<r_t>(), 0.5);\n  STF_ULP_EQUAL(csc(-bs::Pio_4<T>(), bst::clipped_small_), -bs::Sqrt_2<r_t>(), 0.5);\n  STF_ULP_EQUAL(csc(bs::Pio_2<T>(), bst::clipped_small_), bs::One<r_t>(), 0.5);\n  STF_ULP_EQUAL(csc(bs::Pio_4<T>(), bst::clipped_small_), bs::Sqrt_2<r_t>(), 0.5);\n}\n", "meta": {"hexsha": "159fa3df61b6983942c44fa9f5b538b93f087215", "size": 3756, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/scalar/csc.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": "test/function/scalar/csc.cpp", "max_issues_repo_name": "remymuller/boost.simd", "max_issues_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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/function/scalar/csc.cpp", "max_forks_repo_name": "remymuller/boost.simd", "max_forks_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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": 37.9393939394, "max_line_length": 100, "alphanum_fraction": 0.6267305644, "num_tokens": 1313, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195152660687, "lm_q2_score": 0.6261241632752914, "lm_q1q2_score": 0.45964996724002977}}
{"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 sigma_point_additive_uncorrelated_update_policy.hpp\n * \\date July 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/traits.hpp>\n#include <fl/util/descriptor.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 SigmaPointUpdatePolicy;\n\ntemplate <\n    typename SigmaPointQuadrature,\n    typename AdditiveUncorrelatedObsrvFunction\n>\nclass SigmaPointUpdatePolicy<\n          SigmaPointQuadrature,\n          AdditiveUncorrelated<AdditiveUncorrelatedObsrvFunction>>\n    : public Descriptor\n{\npublic:\n    typedef typename AdditiveUncorrelatedObsrvFunction::State State;\n    typedef typename AdditiveUncorrelatedObsrvFunction::Obsrv Obsrv;\n\n    enum : signed int\n    {\n        NumberOfPoints =\n            SigmaPointQuadrature::number_of_points(SizeOf<State>::Value)\n    };\n\n    // static_assert(false, \"Just implementing this ........\");\n\n    typedef PointSet<State, NumberOfPoints> StatePointSet;\n    typedef PointSet<Obsrv, NumberOfPoints> ObsrvPointSet;\n\n    template <\n        typename Belief\n    >\n    void operator()(const AdditiveUncorrelatedObsrvFunction& obsrv_function,\n                    const SigmaPointQuadrature& quadrature,\n                    const Belief& prior_belief,\n                    const Obsrv& obsrv,\n                    Belief& posterior_belief)\n    {\n        auto&& h = [&](const State& x)\n        {\n           return obsrv_function.expected_observation(x);\n        };\n\n        quadrature.propergate_gaussian(h, prior_belief, X, Z);\n\n        auto R_inv =\n            obsrv_function\n                .noise_diagonal_covariance()\n                .diagonal()\n                .cwiseInverse()\n                .eval();\n\n        auto W_inv =\n            X.covariance_weights_vector()\n                .cwiseInverse()\n                .eval();\n\n        auto&& prediction = Z.center();\n        auto&& Y_c = Z.points();\n        auto&& X_c = X.centered_points();\n\n        auto innovation = (obsrv - prediction).eval();\n\n        auto C = (Y_c.transpose() * R_inv.asDiagonal() * Y_c).eval();\n        C += W_inv.asDiagonal();\n        C = C.inverse();\n\n        auto correction = (\n           X_c * C * Y_c.transpose() *  R_inv.asDiagonal() * innovation).eval();\n\n        posterior_belief.dimension(prior_belief.dimension());\n        posterior_belief.mean(X.mean() + correction);\n        posterior_belief.covariance(X_c * C * X_c.transpose());\n    }\n\n    virtual std::string name() const\n    {\n        return \"SigmaPointUpdatePolicy<\"\n            + this->list_arguments(\n                 \"SigmaPointQuadrature\",\n                 \"AdditiveUncorrelated<AdditiveUncorrelatedSensorFunction>\")\n            + \">\";\n    }\n\n    virtual std::string description() const\n    {\n        return \"Sigma Point based filter update policy for observation model\"\n               \" with additive uncorrelated noise\";\n    }\n\nprotected:\n    StatePointSet X;\n    ObsrvPointSet Z;\n};\n\n}\n\n\n\n", "meta": {"hexsha": "24791ccfbc01be90c6bf07c9c0ef3270f1ec2ebc", "size": 3531, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/fl/filter/gaussian/update_policy/sigma_point_additive_uncorrelated_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/sigma_point_additive_uncorrelated_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/sigma_point_additive_uncorrelated_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": 26.9541984733, "max_line_length": 80, "alphanum_fraction": 0.6309827244, "num_tokens": 796, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.82893881677331, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.45962209116004366}}
{"text": "#include \"kinematics.h\"\n#include \"motor_control.h\"\n#include <armadillo>\n\nusing namespace arma;\nusing namespace std;\n\nint main()\n{\n\tdouble x,y,z;\n\twhile(1)\n\t{\n\t\tcout<<\"Enter x,y,z values: \";\n\t\tcin>>x>>y>>z;\n\t\tmat target;\n\t\ttarget<<x<<y<<z;\n\t\ttarget.print();\n\t\tmat theta_default;\n\t\ttheta_default<<0<<1.5707<<1.5707<<0;\n\t\ttheta_default.print();\n\t\tmat calc = calculate_ccd(theta_default, target);\t\t\t\n\t\tcalc.print(\"CALC\");\n\t}\n\treturn 0;\n}\n", "meta": {"hexsha": "ae5bbd65d06161b1ea53673d4dc978ba7e7050e1", "size": 434, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/ccd_inverse.cpp", "max_stars_repo_name": "ardop/Kinematics-", "max_stars_repo_head_hexsha": "4f7b727edce3ff6cfdd54422bb72f5a72479497e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2016-11-19T07:29:07.000Z", "max_stars_repo_stars_event_max_datetime": "2017-05-27T02:50:48.000Z", "max_issues_repo_path": "code/ccd_inverse.cpp", "max_issues_repo_name": "ardop/Kinematics-", "max_issues_repo_head_hexsha": "4f7b727edce3ff6cfdd54422bb72f5a72479497e", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/ccd_inverse.cpp", "max_forks_repo_name": "ardop/Kinematics-", "max_forks_repo_head_hexsha": "4f7b727edce3ff6cfdd54422bb72f5a72479497e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-11-19T14:14:09.000Z", "max_forks_repo_forks_event_max_datetime": "2016-11-19T14:14:09.000Z", "avg_line_length": 16.6923076923, "max_line_length": 53, "alphanum_fraction": 0.6520737327, "num_tokens": 135, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8175744939732856, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.4596211682353788}}
{"text": "#include <boost/math/special_functions/gamma.hpp>\n", "meta": {"hexsha": "dd249fbcc89ef661472cd06c05abb35a7eea669f", "size": 50, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_special_functions_gamma.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_special_functions_gamma.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_special_functions_gamma.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 25.0, "max_line_length": 49, "alphanum_fraction": 0.82, "num_tokens": 11, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744939732856, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.45962116823537874}}
{"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\u2019s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n#pragma once\n\n#include \"../util/FluidEigenMappings.hpp\"\n#include \"../util/OutlierDetection.hpp\"\n#include \"../util/Stats.hpp\"\n#include \"../util/WeightedStats.hpp\"\n#include \"../../data/FluidIndex.hpp\"\n#include \"../../data/TensorTypes.hpp\"\n#include <Eigen/Core>\n#include <cassert>\n#include <cmath>\n\nnamespace fluid {\nnamespace algorithm {\n\nclass MultiStats\n{\npublic:\n  using ArrayXd = Eigen::ArrayXd;\n  using ArrayXi = Eigen::ArrayXi;\n\n  void init(index numDerivatives, double low, double mid, double high)\n  {\n    assert(numDerivatives <= 2);\n    mNumDerivatives = numDerivatives;\n    mLow = low / 100.0;\n    mMiddle = mid / 100.0;\n    mHigh = high / 100.0;\n  }\n\n  index numStats() { return 7; }\n\n  ArrayXd diff(Eigen::Ref<ArrayXd> in)\n  {\n    return in.segment(1, in.size() - 1) - in.segment(0, in.size() - 1);\n  }\n\n  void process(const RealMatrixView in, RealMatrixView out, double cutoff = -1,\n               RealVectorView w = RealVectorView(nullptr, 0, 0))\n  {\n    using namespace Eigen;\n    using namespace _impl;\n    using fluid::Slice;\n    assert(out.size() == in.rows() * numStats() * (mNumDerivatives + 1));\n    bool     weighted = w.size() > 0;\n    ArrayXXd input = asEigen<Array>(in);\n    ArrayXd  weights = asEigen<Array>(w);\n    index    numChannels = input.rows();\n    index    numFrames = input.cols();\n    ArrayXi  mask = ArrayXi::Ones(numFrames);\n\n    if (cutoff >= 0)\n    {\n      for (index i = 0; i < numChannels; i++)\n      { OutlierDetection().process(input.row(i), mask, cutoff); }\n    }\n    index numCleanFrames = mask.sum();\n    if (numCleanFrames <= 0) return;\n    if (weighted && weights.sum() <= 0) return;\n    ArrayXXd filtered = ArrayXXd::Zero(numChannels, numCleanFrames);\n    ArrayXd  filteredWeights;\n    if (weighted) filteredWeights = ArrayXd::Zero(numCleanFrames);\n    index k = 0;\n    for (index j = 0; j < mask.size(); j++)\n    {\n      if (mask(j) > 0)\n      {\n        filtered.col(k) = input.col(j);\n        if (weighted) filteredWeights(k) = weights(j);\n        k++;\n      }\n    }\n    filteredWeights = (filteredWeights >= 0).select(filteredWeights, 0);\n    if (weighted && filteredWeights.size() > 0)\n    {\n      double sum = filteredWeights.sum();\n      if (sum > 0) filteredWeights = filteredWeights / filteredWeights.sum();\n    }\n    ArrayXXd result =\n        ArrayXXd::Zero(numChannels, numStats() * (mNumDerivatives + 1));\n    for (index i = 0; i < numChannels; i++)\n    {\n      ArrayXd d1, d2, d1Weights, d2Weights;\n      ArrayXd channel = filtered.row(i);\n      result.block(i, 0, 1, numStats()) =\n          weighted\n              ? WeightedStats()\n                    .process(channel, filteredWeights, mLow, mMiddle, mHigh)\n                    .matrix()\n                    .transpose()\n              : Stats()\n                    .process(channel, mLow, mMiddle, mHigh)\n                    .matrix()\n                    .transpose();\n      if (mNumDerivatives > 0 && numCleanFrames >= 2)\n      {\n        d1 = diff(channel);\n        if (weighted)\n          d1Weights = filteredWeights.segment(1, numCleanFrames - 1);\n        result.block(i, numStats(), 1, numStats()) =\n            weighted ? WeightedStats()\n                           .process(d1, d1Weights, mLow, mMiddle, mHigh)\n                           .matrix()\n                           .transpose()\n                     : Stats()\n                           .process(d1, mLow, mMiddle, mHigh)\n                           .matrix()\n                           .transpose();\n      }\n      if (mNumDerivatives > 1 && numCleanFrames >= 3)\n      {\n        d2 = diff(d1);\n        if (weighted)\n          d2Weights = filteredWeights.segment(2, numCleanFrames - 2);\n        result.block(i, 2 * numStats(), 1, numStats()) =\n            weighted ? WeightedStats()\n                           .process(d2, d2Weights, mLow, mMiddle, mHigh)\n                           .matrix()\n                           .transpose()\n                     : Stats()\n                           .process(d2, mLow, mMiddle, mHigh)\n                           .matrix()\n                           .transpose();\n      }\n    }\n    out = asFluid(result);\n  }\n  index  mNumDerivatives{0};\n  double mLow{0};\n  double mMiddle{0.5};\n  double mHigh{1};\n};\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "6d500c97a76e78efed584e2fea38bb8d00ad610b", "size": 4672, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/public/MultiStats.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/MultiStats.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/MultiStats.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": 32.2206896552, "max_line_length": 79, "alphanum_fraction": 0.5639982877, "num_tokens": 1183, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744939732856, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.45962116823537874}}
{"text": "#pragma once\n#include <algorithm>\n#include <array>\n#include <boost/assert.hpp>\n#include <boost/intrusive/list.hpp>\n#include <boost/intrusive/set.hpp>\n#include <memory>\n\nnamespace sssp {\n\ninline int ceil_log2(size_t n) {\n    size_t result = 1;\n    int bit = 0;\n    while (result < n) {\n        result *= 2;\n        bit += 1;\n    }\n    return bit;\n}\n\n// 128 MiB chunks with 256 byte minimum allocation\nstatic constexpr int buddy_allocator_layers = 19;\nstatic constexpr int buddy_allocator_missing_layers = 8;\nstatic constexpr size_t buddy_allocator_chunk_bytes = 1 << (buddy_allocator_layers + buddy_allocator_missing_layers);\nstatic constexpr size_t buddy_allocator_min_bytes = 1 << buddy_allocator_missing_layers;\n\n// buddy_allocator_nodes form a doubly-linked list and contain a free flag.\nstruct buddy_allocator_node : boost::intrusive::list_base_hook<> {\n    int free_in_layer = buddy_allocator_layers;\n};\n\n// A chunk of memory.\nstruct buddy_allocator_chunk : boost::intrusive::set_base_hook<> {\n  public:\n    buddy_allocator_chunk() { m_layers.back().push_front(m_nodes[0]); }\n    buddy_allocator_chunk(const buddy_allocator_chunk& other) = delete;\n    buddy_allocator_chunk(buddy_allocator_chunk&& other) = delete;\n    buddy_allocator_chunk& operator=(const buddy_allocator_chunk& other) = delete;\n    buddy_allocator_chunk& operator=(buddy_allocator_chunk&& other) = delete;\n\n    size_t alloc_node(int layer);\n    void free_node(int layer, size_t offset);\n    char* base_pointer() { return &m_memory[0]; }\n    const char* base_pointer() const { return &m_memory[0]; }\n\n  private:\n    // Preallocate all possibly required nodes\n    std::array<buddy_allocator_node, 1 << buddy_allocator_layers> m_nodes;\n    // Free list for each layer. The extra layer is the indivisible root layer\n    std::array<boost::intrusive::list<buddy_allocator_node>, buddy_allocator_layers + 1> m_layers;\n    // The memory\n    alignas(max_align_t) char m_memory[buddy_allocator_chunk_bytes];\n};\n\ninline bool operator<(const buddy_allocator_chunk& a, const buddy_allocator_chunk& b) {\n    return a.base_pointer() < b.base_pointer();\n}\ninline bool operator==(const buddy_allocator_chunk& a, const buddy_allocator_chunk& b) {\n    return a.base_pointer() == b.base_pointer();\n}\n\n// This holds all the resources needed by an buddy_allocator. Only\n// free this once no more allocators use it!\nclass buddy_allocator_memory {\n  public:\n    buddy_allocator_memory() = default;\n    buddy_allocator_memory(const buddy_allocator_memory& other) = delete;\n    buddy_allocator_memory(buddy_allocator_memory&& other) = delete;\n    buddy_allocator_memory& operator=(const buddy_allocator_memory& other) = delete;\n    buddy_allocator_memory& operator=(buddy_allocator_memory&& other) = delete;\n    ~buddy_allocator_memory() {\n        m_chunks.clear_and_dispose([](buddy_allocator_chunk* chunk) { delete chunk; });\n    }\n\n    char* alloc(int layer);\n    void free(int layer, char* address);\n\n  private:\n    boost::intrusive::set<buddy_allocator_chunk> m_chunks;\n    buddy_allocator_chunk* m_last_success = nullptr;\n};\n\n// This is a *none* thread safe buddy allocator.\ntemplate <typename T> class buddy_allocator {\n  public:\n    template <typename OtherT> friend class buddy_allocator;\n\n    using pointer = T*;\n    using const_pointer = const T*;\n    using reference = T&;\n    using const_reference = const T&;\n    using void_pointer = void*;\n    using const_void_pointer = const void*;\n    using value_type = T;\n    using size_type = size_t;\n    using difference_type = ptrdiff_t;\n    template <typename OtherT> struct rebind { using other = buddy_allocator<OtherT>; };\n\n    // Creates a buddy allocator with the given state. Once the state is\n    // destroyed, the allocator becomes invalid and all memory is lost.\n    // Therefore only free the state once all allocator instances are free'd as well.\n    buddy_allocator(buddy_allocator_memory* state) : m_state(state) {}\n    // This is the type converting constructor.\n    template <typename OtherT> buddy_allocator(const buddy_allocator<OtherT>& other) : m_state(other.m_state) {}\n    // Appropriate copy and move semantics.\n    buddy_allocator(const buddy_allocator<T>& other) : m_state(other.m_state) {}\n    buddy_allocator(const buddy_allocator<T>&& other) : m_state(other.m_state) {}\n    buddy_allocator& operator=(const buddy_allocator<T>& other) {\n        m_state = other.m_state;\n        return *this;\n    }\n    buddy_allocator& operator=(const buddy_allocator<T>&& other) {\n        m_state = other.m_state;\n        return *this;\n    }\n\n    // Equality operators\n    template <typename OtherT> bool operator==(const buddy_allocator<OtherT>& other) {\n        return m_state == other.m_state;\n    }\n    template <typename OtherT> bool operator!=(const buddy_allocator<OtherT>& other) {\n        return m_state != other.m_state;\n    }\n\n    // Allocate memory.\n    T* allocate(size_t n) {\n        int layer = std::max(0, ceil_log2(sizeof(T) * n) - buddy_allocator_missing_layers);\n        if (layer < buddy_allocator_layers) {\n            return reinterpret_cast<T*>(m_state->alloc(layer));\n        } else {\n            return static_cast<T*>(malloc(sizeof(T) * n));\n        }\n    }\n\n    // Free memory.\n    void deallocate(T* ptr, size_t n) {\n        int layer = std::max(0, ceil_log2(sizeof(T) * n) - buddy_allocator_missing_layers);\n        if (layer < buddy_allocator_layers) {\n            m_state->free(layer, reinterpret_cast<char*>(ptr));\n        } else {\n            free(ptr);\n        }\n    }\n\n    void destroy(T* ptr) { ptr->~T(); }\n\n  private:\n    buddy_allocator_memory* m_state;\n};\n\n} // namespace sssp", "meta": {"hexsha": "e4eab6872f379800d86a573461d0ce9f954e3b1c", "size": 5632, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "buddy_allocator.hpp", "max_stars_repo_name": "kaini/sssp-shm", "max_stars_repo_head_hexsha": "42fe049211a17177b10159f404a64842a7ba6076", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-02-28T03:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-19T17:30:01.000Z", "max_issues_repo_path": "buddy_allocator.hpp", "max_issues_repo_name": "kaini/sssp-shm", "max_issues_repo_head_hexsha": "42fe049211a17177b10159f404a64842a7ba6076", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "buddy_allocator.hpp", "max_forks_repo_name": "kaini/sssp-shm", "max_forks_repo_head_hexsha": "42fe049211a17177b10159f404a64842a7ba6076", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-17T09:23:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-17T09:23:17.000Z", "avg_line_length": 37.298013245, "max_line_length": 117, "alphanum_fraction": 0.7056107955, "num_tokens": 1296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038221, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.459621153242433}}
{"text": "#include \"rlbot/rlbot_generated.h\"\n#include \"rlbot/bot.h\"\n#include \"rlbot/scopedrenderer.h\"\n\n#include \"../badbot.h\"\n\n#include \"path.h\"\n\n#include <vector>\n#include <algorithm>\n#include <iostream>\n\n#include <Eigen/Dense>\n\n\n\nusing namespace Eigen;\n\n\n\nnamespace badbot {\n\n\tnamespace paths {\n\t\tBezier::Bezier(const util::Car car, const Vector3f t, const util::BallPrediction& bp) :\n\t\t\ttarget(t),\n\t\t\tcar(car),\n\t\t\tbp(bp){\n\n\t\t\tfloat t_approx = (car.physics.location - target).norm() / car.physics.velocity.norm() + bp.predictionSlices[0].gameSeconds;\n\n\t\t\tint intercept = 0;\n\t\t\tfor (; intercept < bp.predictionSlices.size(); ++intercept) {\n\n\t\t\t\tif (bp.predictionSlices[intercept].gameSeconds > t_approx) break;\n\n\t\t\t}\n\n\t\t\tif (intercept != 0) --intercept;\n\n\t\t\tVector3f target = bp.predictionSlices[intercept].physics.location;\n\n\t\t\tfloat dist = (car.physics.location - target).norm();\n\n\n\n\t\t\tVector3f p0 = car.physics.location;\n\t\t\tVector3f p1 = car.physics.location + car.physics.forward() * std::min(dist, 100.0f);\n\t\t\tVector3f goalVector = car.other_goal() - target;\n\t\t\tgoalVector.z() = 0;\n\t\t\tgoalVector.normalize();\n\t\t\tVector3f p2 = target - goalVector*dist/2;\n\t\t\tVector3f p3 = target;\n\n\t\t\tbool debug = true;\n\t\t\tif (debug && car.team == 0) {\n\t\t\t\trlbot::ScopedRenderer renderer(\"BezierDebug\" + car.name);\n\t\t\t\trenderer.DrawRect3D(rlbot::Color::magenta, util::convert(p0), 20, 20, 1, 1);\n\t\t\t\trenderer.DrawRect3D(rlbot::Color::magenta, util::convert(p1), 20, 20, 1, 1);\n\t\t\t\trenderer.DrawRect3D(rlbot::Color::magenta, util::convert(p2), 20, 20, 1, 1);\n\t\t\t\trenderer.DrawRect3D(rlbot::Color::magenta, util::convert(p3), 20, 20, 1, 1);\n\t\t\t}\n\n\t\t\t//p1 = { 0, 0, 0 };\n\t\t\t//p2 = { 500, 1000, 0 };\n\t\t\t//p3 = {-500, 1000, 0 };\n\n\t\t\t//p1 = (p0 + p3) / 2;\n\t\t\t//p2 = p1;\n\n\t\t\tcurve = [=](float t) -> Vector3f{\treturn\tstd::pow(1 - t, 3) * p0\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ 3 * std::pow(1 - t, 2) * t * p1\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ 3 * (1 - t) * t * t * p2\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ std::pow(t, 3) * p3; };\n\n\t\t\tfor (size_t i = 1; i <= util::NUM_POINTS; ++i) {\n\t\t\t\tpath.push_back(curve(i * 1.0f / util::NUM_POINTS));\n\t\t\t}\n\t\t\t//rlbot::ScopedRenderer renderer(\"Renderer\" + std::to_string(car.team));\n\n\t\t\t//std::vector <const rlbot::flat::Vector3*> points;\n\n\t\t\t//points.push_back(new rlbot::flat::Vector3{ p0[0], p0[1], p0[2] });\n\t\t\t//points.push_back(new rlbot::flat::Vector3{ p1[0], p1[1], p1[2] });\n\t\t\t//points.push_back(new rlbot::flat::Vector3{ p2[0], p2[1], p2[2] });\n\t\t\t//points.push_back(new rlbot::flat::Vector3{ p3[0], p3[1], p3[2] });\n\t\t\t\n\t\t\t//renderer.DrawPolyLine3D(rlbot::Color::yellow, points);\n\t\t}\n\n\t\t\n\t\tvoid Bezier::getPath(std::vector<const rlbot::flat::Vector3*>& points) const {\n\n\t\t\tfor (auto point : points) delete point;\n\t\t\tpoints.clear();\n\n\t\t\t//TODO IMPLEMENT ACTUAL THINGY\n\t\t\t//unsigned len = std::min(path.size(), util::NUM_POINTS);\n\t\t\tfor (unsigned i = 0; i < util::NUM_POINTS; ++i) {\n\t\t\t\tpoints.push_back(new rlbot::flat::Vector3{ path[i][0], path[i][1], path[i][2] });\n\t\t\t}\n\n\t\t}\n\n\t\trlbot::Controller Bezier::getControl() const {\n\t\t\treturn util::optimalGroundControl(car, path);\n\t\t}\n\t\t\n\n\t\t\n\t}//namespace paths\n}//namespace badbot", "meta": {"hexsha": "aed343f3ca712f8e29e8df99143bab8b04b9e9ea", "size": 3085, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "brain/path.cpp", "max_stars_repo_name": "steinraf/badbotcpp", "max_stars_repo_head_hexsha": "6b517bd0c9ce1f1b717dbfdd790e627434259219", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-09T23:13:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-09T23:13:03.000Z", "max_issues_repo_path": "brain/path.cpp", "max_issues_repo_name": "steinraf/badbotcpp", "max_issues_repo_head_hexsha": "6b517bd0c9ce1f1b717dbfdd790e627434259219", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "brain/path.cpp", "max_forks_repo_name": "steinraf/badbotcpp", "max_forks_repo_head_hexsha": "6b517bd0c9ce1f1b717dbfdd790e627434259219", "max_forks_repo_licenses": ["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.7927927928, "max_line_length": 126, "alphanum_fraction": 0.6200972447, "num_tokens": 1044, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.45961514642584705}}
{"text": "#include \"../../include/IntrinsicFormula/WrinkleEditingProcess.h\"\n#include \"../../include/Optimization/NewtonDescent.h\"\n#include \"../../include/IntrinsicFormula/KnoppelStripePattern.h\"\n#include <igl/cotmatrix_entries.h>\n#include <igl/cotmatrix.h>\n#include <igl/doublearea.h>\n#include <igl/boundary_loop.h>\n#include <Eigen/SPQRSupport>\n\nusing namespace IntrinsicFormula;\n\nWrinkleEditingProcess::WrinkleEditingProcess(const Eigen::MatrixXd& pos, const MeshConnectivity& mesh, const std::vector<int>& selectedVids, const Eigen::VectorXi& faceFlag, int quadOrd, double spatialRatio)\n{\n\t_pos = pos;\n\t_mesh = mesh;\n\t_faceFlag = faceFlag;\n\tigl::cotmatrix_entries(pos, mesh.faces(), _cotMatrixEntries);\n\tigl::doublearea(pos, mesh.faces(), _faceArea);\n\t_faceArea /= 2.0;\n\t_quadOrd = quadOrd;\n\t_spatialRatio = spatialRatio;\n\t_selectedVids = selectedVids;\n\n\tint nverts = pos.rows();\n\tint nfaces = mesh.nFaces();\n\tint nedges = mesh.nEdges();\n\n\t_vertFlag.resize(nverts);\n\t_vertFlag.setConstant(-1);\n\n\t_edgeFlag.resize(nedges);\n\t_edgeFlag.setConstant(-1);\n\n\t_vertArea.setZero(nverts);\n\tbuildVertexNeighboringInfo(_mesh, _pos.rows(), _vertNeiEdges, _vertNeiFaces);\n\n\t_edgeCotCoeffs.setZero(nedges);\n\n\t_effectiveVids.clear();\n\t_effectiveEids.clear();\n\t_effectiveVids.clear();\n\n\tstd::vector<int> bnds;\n\tigl::boundary_loop(_mesh.faces(), bnds);\n\n\tstd::set<int> edgeset;\n\tstd::set<int> vertset;\n\t_nInterfaces = 0;\n\n\tfor (int i = 0; i < nfaces; i++)\n\t{\n\t\tfor (int j = 0; j < 3; j++)\n\t\t{\n\t\t\tint vid = _mesh.faceVertex(i, j);\n\t\t\tint eid = _mesh.faceEdge(i, j);\n\n\t\t\t_vertArea(vid) += _faceArea(i) / _vertNeiFaces.size() / 3.0;\n\t\t\t_edgeCotCoeffs(eid) += _cotMatrixEntries(i, j);\n\n\t\t\tif (faceFlag(i) != -1)\n\t\t\t{\n\t\t\t\t_vertFlag(vid) = faceFlag(i);\n\t\t\t\t_edgeFlag(eid) = faceFlag(i);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t_effectiveFids.push_back(i);\n\t\t\t\t//                if(std::find(bnds.begin(), bnds.end(), vid) == bnds.end() && vertset.count(vid) == 0)     // not on boundary\n\t\t\t\tif (vertset.count(vid) == 0)\n\t\t\t\t\tvertset.insert(vid);\n\t\t\t\tif (edgeset.count(eid) == 0)\n\t\t\t\t\tedgeset.insert(eid);\n\t\t\t\t_nInterfaces++;\n\t\t\t}\n\t\t}\n\t}\n\tstd::copy(vertset.begin(), vertset.end(), std::back_inserter(_effectiveVids));\n\tstd::copy(edgeset.begin(), edgeset.end(), std::back_inserter(_effectiveEids));\n\n\t_faceVertMetrics.resize(nfaces);\n\tfor (int i = 0; i < nfaces; i++)\n\t{\n\t\t_faceVertMetrics[i].resize(3);\n\t\tfor (int j = 0; j < 3; j++)\n\t\t{\n\t\t\tint vid = _mesh.faceVertex(i, j);\n\t\t\tint vidj = _mesh.faceVertex(i, (j + 1) % 3);\n\t\t\tint vidk = _mesh.faceVertex(i, (j + 2) % 3);\n\n\t\t\tEigen::Vector3d e0 = _pos.row(vidj) - _pos.row(vid);\n\t\t\tEigen::Vector3d e1 = _pos.row(vidk) - _pos.row(vid);\n\n\t\t\tEigen::Matrix2d I;\n\t\t\tI << e0.dot(e0), e0.dot(e1), e1.dot(e0), e1.dot(e1);\n\t\t\t_faceVertMetrics[i][j] = I.inverse();\n\t\t}\n\t}\n\tstd::cout << \"number of interfaces: \" << _nInterfaces << std::endl;\n\n\n}\n\nvoid WrinkleEditingProcess::initialization(const std::vector<Eigen::VectorXd>& initRefAmpList, const std::vector<Eigen::MatrixXd>& initRefOmegaList, const std::vector<Eigen::VectorXd>& refAmpList, const std::vector<Eigen::MatrixXd>& refOmegaList)\n{\n\t\n\tstd::vector<std::complex<double>> initZvals, initZvalsBeforeEdition;\n\tstd::vector<std::complex<double>> tarZvals, tarZvalsBeforeEdition;\n\n\tint nFrames = refAmpList.size() - 2;\n\n\tEigen::VectorXi bndVertsFlag = _vertFlag;\n\tfor (int i = 0; i < bndVertsFlag.rows(); i++)\n\t{\n\t\tif (bndVertsFlag(i) != -1)\n\t\t\tbndVertsFlag(i) = 1;\n\t\telse\n\t\t\tbndVertsFlag(i) = 0;\n\t}\n\n\tEigen::VectorXi firstStepFlags = Eigen::VectorXi::Ones(_vertFlag.rows());\n\tfor (int i = 0; i < firstStepFlags.rows(); i++)\n\t{\n\t\tif (bndVertsFlag(i) != -1)\n\t\t\tfirstStepFlags(i) = 1;\n\t\telse\n\t\t\tfirstStepFlags(i) = 0;\n\t}\n\n\tfor (int i = 0; i < _selectedVids.size(); i++)\n\t{\n\t\tfirstStepFlags(_selectedVids[i]) = 0;\n\t}\n\n\tstd::cout << \"initialize bnd zvals. \" << std::endl;\n\n\troundVertexZvalsFromHalfEdgeOmegaVertexMag(_mesh, initRefOmegaList[0], initRefAmpList[0], _faceArea, _cotMatrixEntries, _pos.rows(), initZvalsBeforeEdition);\n\troundVertexZvalsFromHalfEdgeOmegaVertexMag(_mesh, initRefOmegaList[nFrames + 1], initRefAmpList[nFrames + 1], _faceArea, _cotMatrixEntries, _pos.rows(), tarZvalsBeforeEdition);\n\n\tif (!_nInterfaces)\n\t{\n\t\t_combinedRefOmegaList = initRefOmegaList;\n\t\t_combinedRefAmpList = initRefAmpList;\n\t\tinitZvals = initZvalsBeforeEdition;\n\t\ttarZvals = tarZvalsBeforeEdition;\n\t}\n\telse\n\t{\n\t\tstd::cout << \"compute reference omega.\" << std::endl;\n\t\tcomputeCombinedRefOmegaList(refOmegaList);\n\t\tstd::cout << \"compute reference amplitude.\" << std::endl;\n\t\tcomputeCombinedRefAmpList(refAmpList, &_combinedRefOmegaList);\n\n\t\tinitZvals = initZvalsBeforeEdition;\n\t\ttarZvals = tarZvalsBeforeEdition;\n\n\t\troundZvalsForSpecificDomainWithGivenMag(_mesh, _combinedRefOmegaList[0], _combinedRefAmpList[0], bndVertsFlag, _faceArea, _cotMatrixEntries, _pos.rows(), initZvals);\n\t\troundZvalsForSpecificDomainWithBndValues(_pos, _mesh, _combinedRefOmegaList[0], bndVertsFlag, _faceArea, _cotMatrixEntries, _pos.rows(), initZvals);\n\n\t\troundZvalsForSpecificDomainWithGivenMag(_mesh, _combinedRefOmegaList[nFrames + 1], _combinedRefAmpList[nFrames + 1], bndVertsFlag, _faceArea, _cotMatrixEntries, _pos.rows(), tarZvals);\n\t\troundZvalsForSpecificDomainWithBndValues(_pos, _mesh, _combinedRefOmegaList[nFrames + 1], bndVertsFlag, _faceArea, _cotMatrixEntries, _pos.rows(), tarZvals);\n\n\t\t\n\t\t/*roundZvalsForSpecificDomainWithBndValues(_pos, _mesh, _combinedRefOmegaList[0], firstStepFlags, _faceArea, _cotMatrixEntries, _pos.rows(), initZvals);\n\n\t\tfor (int i = 0; i < initZvals.size(); i++)\n\t\t{\n\t\t\tif (firstStepFlags[i] == 0)\n\t\t\t{\n\t\t\t\tdouble arg = std::arg(initZvals[i]);\n\t\t\t\tinitZvals[i] = refAmpList[0][i] * std::complex<double>(std::cos(arg), std::sin(arg));\n\t\t\t}\n\t\t\t\t\n\t\t}\n\n\t\troundZvalsForSpecificDomainWithBndValues(_pos, _mesh, _combinedRefOmegaList[0], bndVertsFlag, _faceArea, _cotMatrixEntries, _pos.rows(), initZvals);\n\n\t\troundZvalsForSpecificDomainWithBndValues(_pos, _mesh, _combinedRefOmegaList[nFrames + 1], firstStepFlags, _faceArea, _cotMatrixEntries, _pos.rows(), tarZvals);\n\n\t\tfor (int i = 0; i < tarZvals.size(); i++)\n\t\t{\n\t\t\tif (firstStepFlags[i] == 0)\n\t\t\t{\n\t\t\t\tdouble arg = std::arg(tarZvals[i]);\n\t\t\t\ttarZvals[i] = refAmpList[nFrames + 1][i] * std::complex<double>(std::cos(arg), std::sin(arg));\n\t\t\t}\n\n\t\t}\n\n\t\troundZvalsForSpecificDomainWithBndValues(_pos, _mesh, _combinedRefOmegaList[nFrames + 1], bndVertsFlag, _faceArea, _cotMatrixEntries, _pos.rows(), tarZvals);*/\n\t}\n\n\t/*if (_nInterfaces)\n\t{\n\t\troundZvalsForSpecificDomainWithGivenMag(_mesh, _combinedRefOmegaList[0], _combinedRefAmpList[0], bndVertsFlag, _faceArea, _cotMatrixEntries, _pos.rows(), initZvals);\n\t\troundZvalsForSpecificDomainWithBndValues(_pos, _mesh, _combinedRefOmegaList[0], bndVertsFlag, _faceArea, _cotMatrixEntries, _pos.rows(), initZvals);\n\n\t\troundZvalsForSpecificDomainWithGivenMag(_mesh, _combinedRefOmegaList[nFrames + 1], _combinedRefAmpList[nFrames + 1], bndVertsFlag, _faceArea, _cotMatrixEntries, _pos.rows(), tarZvals);\n\t\troundZvalsForSpecificDomainWithBndValues(_pos, _mesh, _combinedRefOmegaList[nFrames + 1], bndVertsFlag, _faceArea, _cotMatrixEntries, _pos.rows(), tarZvals);\n\t}*/\n\n\n\n\t_edgeOmegaList = _combinedRefOmegaList;\n\t_zvalsList.resize(nFrames + 2);\n\n\t_zvalsList[0] = initZvals;\n\t_zvalsList[nFrames + 1] = tarZvals;\n\n\tdouble dt = 1.0 / (nFrames + 1);\n\n\tstd::cout << \"initialize the intermediate frames.\" << std::endl;\n\tfor (int i = 1; i <= nFrames; i++)\n\t{\n\t\t double t = i * dt;\n\n\t\t _zvalsList[i] = tarZvals;\n\n\t\t for(int j = 0; j < tarZvals.size(); j++)\n\t\t {\n\t\t\t _zvalsList[i][j] = (1 - t) * initZvals[j] + t * tarZvals[j];\n\t\t }\n\n//\t\tif (_nInterfaces)\n//\t\t{\n//\t\t\troundZvalsForSpecificDomainWithGivenMag(_mesh, _combinedRefOmegaList[i], _combinedRefAmpList[i], bndVertsFlag, _faceArea, _cotMatrixEntries, _pos.rows(), _zvalsList[i]);\n//\t\t\troundZvalsForSpecificDomainWithBndValues(_pos, _mesh, _combinedRefOmegaList[i], bndVertsFlag, _faceArea, _cotMatrixEntries, _pos.rows(), _zvalsList[i]);\n//\t\t}\n//\t\telse\n//\t\t{\n//\t\t\troundVertexZvalsFromHalfEdgeOmegaVertexMag(_mesh, _combinedRefOmegaList[i], _combinedRefAmpList[i], _faceArea, _cotMatrixEntries, _pos.rows(), _zvalsList[i]);\n//\t\t}\n\n\t}\n\n//\tfor (int i = 0; i <= nFrames + 1; i++)\n//\t{\n//\t\tfor (int j = 0; j < _zvalsList[i].size(); j++)\n//\t\t{\n//\t\t\t_combinedRefAmpList[i][j] = std::abs(_zvalsList[i][j]);\n//\t\t}\n//\t}\n\n\t_zdotModel = ComputeZdotFromHalfEdgeOmega(_mesh, _faceArea, _quadOrd, dt);\n\n\t//\t_model = IntrinsicKnoppelDrivenFormula(_mesh, _faceArea, _cotMatrixEntries, _combinedRefOmegaList, _combinedRefAmpList, initZvals, tarZvals, _combinedRefOmegaList[0], _combinedRefOmegaList[nFrames + 1], nFrames, 1.0, _quadOrd,true);\n\n\n}\n\nvoid WrinkleEditingProcess::convertList2Variable(Eigen::VectorXd& x)\n{\n\tint nverts = _zvalsList[0].size();\n\tint nedges = _edgeOmegaList[0].rows();\n\n\tint numFrames = _zvalsList.size() - 2;\n\n\tint DOFsPerframe = (2 * nverts + 2 * nedges);\n\n\tint DOFs = numFrames * DOFsPerframe;\n\n\tx.setZero(DOFs);\n\n\tfor (int i = 0; i < numFrames; i++)\n\t{\n\t\tfor (int j = 0; j < nverts; j++)\n\t\t{\n\t\t\tx(i * DOFsPerframe + 2 * j) = _zvalsList[i + 1][j].real();\n\t\t\tx(i * DOFsPerframe + 2 * j + 1) = _zvalsList[i + 1][j].imag();\n\t\t}\n\n\t\tfor (int j = 0; j < nedges; j++)\n\t\t{\n\t\t\tx(i * DOFsPerframe + 2 * nverts + 2 * j) = _edgeOmegaList[i + 1](j, 0);\n\t\t\tx(i * DOFsPerframe + 2 * nverts + 2 * j + 1) = _edgeOmegaList[i + 1](j, 1);\n\t\t}\n\t}\n}\n\nvoid WrinkleEditingProcess::convertVariable2List(const Eigen::VectorXd& x)\n{\n\tint nverts = _zvalsList[0].size();\n\tint nedges = _edgeOmegaList[0].rows();\n\n\tint numFrames = _zvalsList.size() - 2;\n\n\tint DOFsPerframe = (2 * nverts + 2 * nedges);\n\n\tfor (int i = 0; i < numFrames; i++)\n\t{\n\t\tfor (int j = 0; j < nverts; j++)\n\t\t{\n\t\t\t_zvalsList[i + 1][j] = std::complex<double>(x(i * DOFsPerframe + 2 * j), x(i * DOFsPerframe + 2 * j + 1));\n\t\t}\n\n\t\tfor (int j = 0; j < nedges; j++)\n\t\t{\n\t\t\t_edgeOmegaList[i + 1](j, 0) = x(i * DOFsPerframe + 2 * nverts + 2 * j);\n\t\t\t_edgeOmegaList[i + 1](j, 1) = x(i * DOFsPerframe + 2 * nverts + 2 * j + 1);\n\t\t}\n\t}\n}\n\ndouble WrinkleEditingProcess::amplitudeEnergyWithGivenOmegaPerface(const Eigen::VectorXd& amp, const Eigen::MatrixXd& w,\n\tint fid, Eigen::Vector3d* deriv,\n\tEigen::Matrix3d* hess)\n{\n\tdouble energy = 0;\n\n\tdouble curlSq = curlFreeEnergyPerface(w, fid, NULL, NULL);\n\tEigen::Vector3d wSq;\n\twSq.setZero();\n\n\t/*for(int i = 0; i < 3; i++)\n\t{\n\t\tEigen::Vector2d dtheta;\n\n\t\tint eidij = _mesh.faceEdge(fid, (i + 2) % 3);\n\t\tint eidik = _mesh.faceEdge(fid, (i + 1) % 3);\n\t\tint vid = _mesh.faceVertex(fid, i);\n\n\n\t\tif (vid == _mesh.edgeVertex(eidij, 0))\n\t\t{\n\t\t\tdtheta(0) = w(eidij, 0);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdtheta(0) = w(eidij, 1);\n\t\t}\n\n\t\tif (vid == _mesh.edgeVertex(eidik, 0))\n\t\t{\n\t\t\tdtheta(1) = w(eidik, 0);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdtheta(1) = w(eidik, 1);\n\t\t}\n\n\t\twSq(i) = dtheta.dot(_faceVertMetrics[fid][i] * dtheta);\n\t}*/\n\n\tif (deriv)\n\t\tderiv->setZero();\n\tif (hess)\n\t\thess->setZero();\n\n\tfor (int i = 0; i < 3; i++)\n\t{\n\t\tint vid = _mesh.faceVertex(fid, i);\n\t\tenergy += 0.5 * amp(vid) * amp(vid) / 3 * (wSq(i) * _faceArea(fid) + curlSq);\n\n\t\tif (deriv)\n\t\t\t(*deriv)(i) += amp(vid) * (wSq(i) * _faceArea(fid) + curlSq) / 3;\n\t\tif (hess)\n\t\t\t(*hess)(i, i) += (wSq(i) * _faceArea(fid) + curlSq) / 3;\n\t}\n\n\treturn energy;\n}\n\ndouble WrinkleEditingProcess::amplitudeEnergyWithGivenOmega(const Eigen::VectorXd& amp, const Eigen::MatrixXd& w,\n\tEigen::VectorXd* deriv,\n\tstd::vector<Eigen::Triplet<double>>* hessT)\n{\n\tdouble energy = 0;\n\n\tint nverts = _pos.rows();\n\tint nEffectiveFaces = _effectiveFids.size();\n\n\tstd::vector<double> energyList(nEffectiveFaces);\n\tstd::vector<Eigen::Vector3d> derivList(nEffectiveFaces);\n\tstd::vector<Eigen::Matrix3d> hessList(nEffectiveFaces);\n\n\tauto computeEnergy = [&](const tbb::blocked_range<uint32_t>& range) {\n\t\tfor (uint32_t i = range.begin(); i < range.end(); ++i)\n\t\t{\n\t\t\tint fid = _effectiveFids[i];\n\t\t\tenergyList[i] = amplitudeEnergyWithGivenOmegaPerface(amp, w, fid, deriv ? &derivList[i] : NULL, hessT ? &hessList[i] : NULL);\n\t\t}\n\t};\n\n\ttbb::blocked_range<uint32_t> rangex(0u, (uint32_t)nEffectiveFaces, GRAIN_SIZE);\n\ttbb::parallel_for(rangex, computeEnergy);\n\n\tif (deriv)\n\t\tderiv->setZero(nverts);\n\tif (hessT)\n\t\thessT->clear();\n\n\tfor (int efid = 0; efid < nEffectiveFaces; efid++)\n\t{\n\t\tenergy += energyList[efid];\n\t\tint fid = _effectiveFids[efid];\n\n\t\tif (deriv)\n\t\t{\n\t\t\tfor (int j = 0; j < 3; j++)\n\t\t\t{\n\t\t\t\tint vid = _mesh.faceVertex(fid, j);\n\t\t\t\t(*deriv)(vid) += derivList[efid](j);\n\t\t\t}\n\t\t}\n\n\t\tif (hessT)\n\t\t{\n\t\t\tfor (int j = 0; j < 3; j++)\n\t\t\t{\n\t\t\t\tint vid = _mesh.faceVertex(fid, j);\n\t\t\t\tfor (int k = 0; k < 3; k++)\n\t\t\t\t{\n\t\t\t\t\tint vid1 = _mesh.faceVertex(fid, k);\n\t\t\t\t\thessT->push_back({ vid, vid1, hessList[efid](j, k) });\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn energy;\n}\n\nvoid WrinkleEditingProcess::computeCombinedRefAmpList(const std::vector<Eigen::VectorXd>& refAmpList, std::vector<Eigen::MatrixXd>* combinedOmegaList)\n{\n\tint nverts = _pos.rows();\n\tint nfaces = _mesh.nFaces();\n\tint nFrames = refAmpList.size();\n\n\t_combinedRefAmpList.resize(nFrames);\n\n\tdouble c = std::min(1.0 / (nFrames * nFrames), 1e-3);\n\n\tstd::vector<Eigen::Triplet<double>> T;\n\t// projection matrix\n\tstd::vector<int> freeVid;\n\tfor (int i = 0; i < nverts; i++)\n\t{\n\t\tif (_vertFlag(i) == -1)\n\t\t{\n\t\t\tfreeVid.push_back(i);\n\t\t}\n\t}\n\n\tfor (int i = 0; i < freeVid.size(); i++)\n\t{\n\t\tT.push_back(Eigen::Triplet<double>(i, freeVid[i], 1.0));\n\t}\n\n\tEigen::SparseMatrix<double> projM(freeVid.size(), nverts);\n\tprojM.setFromTriplets(T.begin(), T.end());\n\n\tEigen::SparseMatrix<double> unProjM = projM.transpose();\n\n\tauto projVar = [&](const int frameId)\n\t{\n\t\tEigen::MatrixXd fullX = Eigen::VectorXd::Zero(nverts);\n\t\tfor (int i = 0; i < nverts; i++)\n\t\t{\n\t\t\tif (_vertFlag(i) != -1)\n\t\t\t{\n\t\t\t\tfullX(i) = refAmpList[frameId](i);\n\t\t\t}\n\t\t}\n\t\tEigen::VectorXd x0 = projM * fullX;\n\t\treturn x0;\n\t};\n\n\tauto unProjVar = [&](const Eigen::VectorXd& x, const int frameId)\n\t{\n\t\tEigen::VectorXd fullX = unProjM * x;\n\n\t\tfor (int i = 0; i < nverts; i++)\n\t\t{\n\t\t\tif (_vertFlag(i) != -1)\n\t\t\t{\n\t\t\t\tfullX(i) = refAmpList[frameId](i);\n\t\t\t}\n\t\t}\n\t\treturn fullX;\n\t};\n\n\tEigen::SparseMatrix<double> L;\n\tigl::cotmatrix(_pos, _mesh.faces(), L);\n\n\n\tfor (int i = 0; i < nFrames; i++)\n\t{\n\t\tstd::cout << \"Frame \" << std::to_string(i) << \": free vertices: \" << freeVid.size() << std::endl;;\n\t\tauto funVal = [&](const Eigen::VectorXd& x, Eigen::VectorXd* grad, Eigen::SparseMatrix<double>* hess, bool isProj) {\n\t\t\tEigen::VectorXd deriv, deriv1;\n\t\t\tstd::vector<Eigen::Triplet<double>> T;\n\t\t\tEigen::SparseMatrix<double> H;\n\n\t\t\tEigen::VectorXd fullx = unProjVar(x, i);\n\t\t\tdouble E = -0.5 * fullx.dot(L * fullx);\n\n\t\t\tif (combinedOmegaList)\n\t\t\t{\n\t\t\t\tE += amplitudeEnergyWithGivenOmega(fullx, (*combinedOmegaList)[i], grad ? &deriv1 : NULL, hess ? &T : NULL);\n\t\t\t}\n\n\t\t\tif (grad)\n\t\t\t{\n\t\t\t\tderiv = -L * fullx;\n\t\t\t\tif (combinedOmegaList)\n\t\t\t\t\tderiv += deriv1;\n\t\t\t\t(*grad) = projM * deriv;\n\t\t\t}\n\n\t\t\tif (hess)\n\t\t\t{\n\t\t\t\tif (combinedOmegaList)\n\t\t\t\t{\n\t\t\t\t\tH.resize(fullx.rows(), fullx.rows());\n\t\t\t\t\tH.setFromTriplets(T.begin(), T.end());\n\t\t\t\t\t(*hess) = projM * (H - L) * unProjM;\n\t\t\t\t}\n\n\t\t\t\telse\n\t\t\t\t\t(*hess) = projM * (-L) * unProjM;\n\n\t\t\t}\n\n\t\t\treturn E;\n\t\t};\n\t\tauto maxStep = [&](const Eigen::VectorXd& x, const Eigen::VectorXd& dir) {\n\t\t\treturn 1.0;\n\t\t};\n\n\t\tEigen::VectorXd x0 = projVar(i);\n\t\tif (_nInterfaces && freeVid.size())\n\t\t{\n\t\t\tOptSolver::newtonSolver(funVal, maxStep, x0, 1000, 1e-6, 1e-10, 1e-15, false);\n\n\t\t\tEigen::VectorXd deriv;\n\t\t\tdouble E = funVal(x0, &deriv, NULL, false);\n\t\t\tstd::cout << \"terminated with energy : \" << E << \", gradient norm : \" << deriv.norm() << std::endl << std::endl;\n\t\t}\n\t\t\t\n\t\t_combinedRefAmpList[i] = unProjVar(x0, i);\n\t}\n}\n\ndouble WrinkleEditingProcess::curlFreeEnergyPerface(const Eigen::MatrixXd& w, int faceId, Eigen::Matrix<double, 6, 1>* deriv, Eigen::Matrix<double, 6, 6>* hess)\n{\n\tdouble E = 0;\n\n\tdouble diff0, diff1;\n\tEigen::Matrix<double, 6, 1> select0, select1;\n\tselect0.setZero();\n\tselect1.setZero();\n\n\tEigen::Matrix<double, 6, 1> edgews;\n\n\tfor (int i = 0; i < 3; i++)\n\t{\n\t\tint eid = _mesh.faceEdge(faceId, i);\n\t\tedgews(2 * i) = w(eid, 0);\n\t\tedgews(2 * i + 1) = w(eid, 1);\n\n\t\tif (_mesh.faceVertex(faceId, (i + 1) % 3) == _mesh.edgeVertex(eid, 0))\n\t\t{\n\t\t\tselect0(2 * i) = 1;\n\t\t\tselect1(2 * i + 1) = 1;\n\t\t}\n\n\t\telse\n\t\t{\n\t\t\tselect0(2 * i + 1) = 1;\n\t\t\tselect1(2 * i) = 1;\n\t\t}\n\t}\n\tdiff0 = select0.dot(edgews);\n\tdiff1 = select1.dot(edgews);\n\n\tE = 0.5 * (diff0 * diff0 + diff1 * diff1);\n\tif (deriv)\n\t{\n\t\t*deriv = select0 * diff0 + select1 * diff1;\n\t}\n\tif (hess)\n\t{\n\t\t*hess = select0 * select0.transpose() + select1 * select1.transpose();\n\t}\n\n\treturn E;\n}\n\n\ndouble WrinkleEditingProcess::curlFreeEnergy(const Eigen::MatrixXd& w, Eigen::VectorXd* deriv, std::vector<Eigen::Triplet<double>>* hessT)\n{\n\tdouble E = 0;\n\tint nedges = _mesh.nEdges();\n\tint nEffectiveFaces = _effectiveFids.size();\n\n\tstd::vector<double> energyList(nEffectiveFaces);\n\tstd::vector<Eigen::Matrix<double, 6, 1>> derivList(nEffectiveFaces);\n\tstd::vector<Eigen::Matrix<double, 6, 6>> hessList(nEffectiveFaces);\n\n\tauto computeEnergy = [&](const tbb::blocked_range<uint32_t>& range) {\n\t\tfor (uint32_t i = range.begin(); i < range.end(); ++i)\n\t\t{\n\t\t\tint fid = _effectiveFids[i];\n\t\t\tenergyList[i] = curlFreeEnergyPerface(w, fid, deriv ? &derivList[i] : NULL, hessT ? &hessList[i] : NULL);\n\t\t}\n\t};\n\n\ttbb::blocked_range<uint32_t> rangex(0u, (uint32_t)nEffectiveFaces, GRAIN_SIZE);\n\ttbb::parallel_for(rangex, computeEnergy);\n\n\tif (deriv)\n\t\tderiv->setZero(2 * nedges);\n\tif (hessT)\n\t\thessT->clear();\n\n\tfor (int efid = 0; efid < nEffectiveFaces; efid++)\n\t{\n\t\tE += energyList[efid];\n\t\tint fid = _effectiveFids[efid];\n\n\t\tif (deriv)\n\t\t{\n\t\t\tfor (int j = 0; j < 3; j++)\n\t\t\t{\n\t\t\t\tint eid = _mesh.faceEdge(fid, j);\n\t\t\t\t(*deriv)(2 * eid) += derivList[efid](2 * j);\n\t\t\t\t(*deriv)(2 * eid + 1) += derivList[efid](2 * j + 1);\n\t\t\t}\n\t\t}\n\n\t\tif (hessT)\n\t\t{\n\t\t\tfor (int j = 0; j < 3; j++)\n\t\t\t{\n\t\t\t\tint eid = _mesh.faceEdge(fid, j);\n\t\t\t\tfor (int k = 0; k < 3; k++)\n\t\t\t\t{\n\t\t\t\t\tint eid1 = _mesh.faceEdge(fid, k);\n\t\t\t\t\thessT->push_back({ 2 * eid, 2 * eid1, hessList[efid](2 * j, 2 * k) });\n\t\t\t\t\thessT->push_back({ 2 * eid, 2 * eid1 + 1, hessList[efid](2 * j, 2 * k + 1) });\n\t\t\t\t\thessT->push_back({ 2 * eid + 1, 2 * eid1, hessList[efid](2 * j + 1, 2 * k) });\n\t\t\t\t\thessT->push_back({ 2 * eid + 1, 2 * eid1 + 1, hessList[efid](2 * j + 1, 2 * k + 1) });\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn E;\n}\n\n\ndouble WrinkleEditingProcess::divFreeEnergyPervertex(const Eigen::MatrixXd& w, int vertId, Eigen::VectorXd* deriv,\n\tEigen::MatrixXd* hess)\n{\n\tdouble energy = 0;\n\tint neiEdges = _vertNeiEdges[vertId].size();\n\n\n\tEigen::VectorXd selectedVec0, selectedVec1;\n\tselectedVec0.setZero(2 * neiEdges);\n\tselectedVec1.setZero(2 * neiEdges);\n\n\tEigen::VectorXd edgew;\n\tedgew.setZero(2 * neiEdges);\n\n\tfor (int i = 0; i < neiEdges; i++)\n\t{\n\t\tint eid = _vertNeiEdges[vertId][i];\n\t\tif (_mesh.edgeVertex(eid, 0) == vertId)\n\t\t{\n\t\t\tselectedVec0(2 * i) = _edgeCotCoeffs(eid);\n\t\t\tselectedVec1(2 * i + 1) = _edgeCotCoeffs(eid);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tselectedVec0(2 * i + 1) = _edgeCotCoeffs(eid);\n\t\t\tselectedVec1(2 * i) = _edgeCotCoeffs(eid);\n\t\t}\n\n\t\tedgew(2 * i) = w(eid, 0);\n\t\tedgew(2 * i + 1) = w(eid, 1);\n\t}\n\tdouble diff0 = selectedVec0.dot(edgew);\n\tdouble diff1 = selectedVec1.dot(edgew);\n\n\tenergy = 0.5 * (diff0 * diff0 + diff1 * diff1);\n\tif (deriv)\n\t{\n\t\t(*deriv) = (diff0 * selectedVec0 + diff1 * selectedVec1);\n\t}\n\tif (hess)\n\t{\n\t\t(*hess) = (selectedVec0 * selectedVec0.transpose() + selectedVec1 * selectedVec1.transpose());\n\t}\n\n\treturn energy;\n}\n\ndouble WrinkleEditingProcess::divFreeEnergy(const Eigen::MatrixXd& w, Eigen::VectorXd* deriv,\n\tstd::vector<Eigen::Triplet<double>>* hessT)\n{\n\tdouble energy = 0;\n\tint nedges = _mesh.nEdges();\n\tint nEffectiveVerts = _effectiveVids.size();\n\n\tstd::vector<double> energyList(nEffectiveVerts);\n\tstd::vector<Eigen::VectorXd> derivList(nEffectiveVerts);\n\tstd::vector<Eigen::MatrixXd> hessList(nEffectiveVerts);\n\n\tauto computeEnergy = [&](const tbb::blocked_range<uint32_t>& range) {\n\t\tfor (uint32_t i = range.begin(); i < range.end(); ++i)\n\t\t{\n\t\t\tint vid = _effectiveVids[i];\n\t\t\tenergyList[i] = divFreeEnergyPervertex(w, vid, deriv ? &derivList[i] : NULL, hessT ? &hessList[i] : NULL);\n\t\t}\n\t};\n\n\ttbb::blocked_range<uint32_t> rangex(0u, (uint32_t)nEffectiveVerts, GRAIN_SIZE);\n\ttbb::parallel_for(rangex, computeEnergy);\n\n\tif (deriv)\n\t\tderiv->setZero(2 * nedges);\n\tif (hessT)\n\t\thessT->clear();\n\n\tfor (int efid = 0; efid < nEffectiveVerts; efid++)\n\t{\n\t\tint vid = _effectiveVids[efid];\n\t\tenergy += energyList[efid];\n\n\t\tif (deriv)\n\t\t{\n\t\t\tfor (int j = 0; j < _vertNeiEdges[vid].size(); j++)\n\t\t\t{\n\t\t\t\tint eid = _vertNeiEdges[vid][j];\n\t\t\t\t(*deriv)(2 * eid) += derivList[efid](2 * j);\n\t\t\t\t(*deriv)(2 * eid + 1) += derivList[efid](2 * j + 1);\n\t\t\t}\n\t\t}\n\n\t\tif (hessT)\n\t\t{\n\t\t\tfor (int j = 0; j < _vertNeiEdges[vid].size(); j++)\n\t\t\t{\n\t\t\t\tint eid = _vertNeiEdges[vid][j];\n\t\t\t\tfor (int k = 0; k < _vertNeiEdges[vid].size(); k++)\n\t\t\t\t{\n\t\t\t\t\tint eid1 = _vertNeiEdges[vid][k];\n\t\t\t\t\thessT->push_back({ 2 * eid, 2 * eid1, hessList[efid](2 * j, 2 * k) });\n\t\t\t\t\thessT->push_back({ 2 * eid, 2 * eid1 + 1, hessList[efid](2 * j, 2 * k + 1) });\n\t\t\t\t\thessT->push_back({ 2 * eid + 1, 2 * eid1, hessList[efid](2 * j + 1, 2 * k) });\n\t\t\t\t\thessT->push_back({ 2 * eid + 1, 2 * eid1 + 1, hessList[efid](2 * j + 1, 2 * k + 1) });\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn energy;\n}\n\nvoid WrinkleEditingProcess::computeCombinedRefOmegaList(const std::vector<Eigen::MatrixXd>& refOmegaList)\n{\n\tint nedges = _mesh.nEdges();\n\tint nFrames = refOmegaList.size();\n\n\t_combinedRefOmegaList.resize(nFrames);\n\n\tstd::vector<Eigen::Triplet<double>> T;\n\t// projection matrix\n\tstd::vector<int> freeEid;\n\tfor (int i = 0; i < nedges; i++)\n\t{\n\t\tif (_edgeFlag(i) == -1)\n\t\t{\n\t\t\tfreeEid.push_back(i);\n\t\t}\n\t}\n\n\tfor (int i = 0; i < freeEid.size(); i++)\n\t{\n\t\tT.push_back(Eigen::Triplet<double>(2 * i, 2 * freeEid[i], 1.0));\n\t\tT.push_back(Eigen::Triplet<double>(2 * i + 1, 2 * freeEid[i] + 1, 1.0));\n\t}\n\n\tEigen::SparseMatrix<double> projM(2 * freeEid.size(), 2 * nedges);\n\tprojM.setFromTriplets(T.begin(), T.end());\n\n\tEigen::SparseMatrix<double> unProjM = projM.transpose();\n\n\tauto projVar = [&](const int frameId)\n\t{\n\t\tEigen::MatrixXd fullX = Eigen::VectorXd::Zero(nedges * 2);\n\t\tfor (int i = 0; i < nedges; i++)\n\t\t{\n\t\t\tif (_edgeFlag(i) != -1)\n\t\t\t{\n\t\t\t\tfullX(2 * i) = refOmegaList[frameId](i, 0);\n\t\t\t\tfullX(2 * i + 1) = refOmegaList[frameId](i, 1);\n\t\t\t}\n\t\t}\n\t\tEigen::VectorXd x0 = projM * fullX;\n\t\treturn x0;\n\t};\n\n\tauto unProjVar = [&](const Eigen::VectorXd& x, const int frameId)\n\t{\n\t\tEigen::VectorXd fullX = unProjM * x;\n\n\t\tEigen::MatrixXd w(nedges, 2);\n\n\t\tfor (int i = 0; i < nedges; i++)\n\t\t{\n\t\t\tif (_edgeFlag(i) != -1)\n\t\t\t{\n\t\t\t\tfullX(2 * i) = refOmegaList[frameId](i, 0);\n\t\t\t\tfullX(2 * i + 1) = refOmegaList[frameId](i, 1);\n\t\t\t}\n\t\t\tw(i, 0) = fullX(2 * i);\n\t\t\tw(i, 1) = fullX(2 * i + 1);\n\t\t}\n\t\treturn w;\n\t};\n\tauto mat2vec = [&](const Eigen::MatrixXd& w)\n\t{\n\t\tEigen::VectorXd x(2 * w.rows());\n\t\tfor (int i = 0; i < w.rows(); i++)\n\t\t{\n\t\t\tx(2 * i) = w(i, 0);\n\t\t\tx(2 * i + 1) = w(i, 1);\n\t\t}\n\t\treturn x;\n\t};\n\n\tEigen::MatrixXd prevw(nedges, 2);\n\tprevw.setZero();\n\tfor (int i = 0; i < nedges; i++)\n\t{\n\t\tif (_edgeFlag(i) != -1)\n\t\t{\n\t\t\tprevw(i, 0) = refOmegaList[0](i, 0);\n\t\t\tprevw(2 * i + 1) = refOmegaList[0](i, 1);\n\t\t}\n\t}\n\tEigen::VectorXd prefullx = mat2vec(prevw);\n\n\n\tfor (int k = 0; k < nFrames; k++)\n\t{\n\t\tstd::cout << \"Frame \" << std::to_string(k) << \": free edges: \" << freeEid.size() << std::endl;\n\t\tauto funVal = [&](const Eigen::VectorXd& x, Eigen::VectorXd* grad, Eigen::SparseMatrix<double>* hess, bool isProj) {\n\t\t\tEigen::VectorXd deriv, deriv1;\n\t\t\tstd::vector<Eigen::Triplet<double>> T, T1;\n\t\t\tEigen::SparseMatrix<double> H;\n\t\t\tEigen::MatrixXd w = unProjVar(x, k);\n\n\t\t\tdouble E = curlFreeEnergy(w, grad ? &deriv : NULL, hess ? &T : NULL);\n\t\t\tE += divFreeEnergy(w, grad ? &deriv1 : NULL, hess ? &T1 : NULL);\n\n\t\t\tif (grad)\n\t\t\t\tderiv += deriv1;\n\t\t\tif (hess)\n\t\t\t{\n\t\t\t\tstd::copy(T1.begin(), T1.end(), std::back_inserter(T));\n\t\t\t\tH.resize(2 * w.rows(), 2 * w.rows());\n\t\t\t\tH.setFromTriplets(T.begin(), T.end());\n\t\t\t}\n\n\n\t\t\t// we need some reg to remove the singularity, where we choose some kinetic energy (||w - prevw||^2), which coeff = 1e-3\n\t\t\tdouble c = std::min(1.0 / (nFrames * nFrames), 1e-3);\n\t\t\tE += c / 2.0 * (w - prevw).squaredNorm();\n\n\t\t\tif (grad)\n\t\t\t{\n\t\t\t\tEigen::VectorXd fullx = mat2vec(w);\n\t\t\t\t(*grad) = projM * (deriv + c * (fullx - prefullx));\n\t\t\t}\n\n\t\t\tif (hess)\n\t\t\t{\n\t\t\t\tEigen::SparseMatrix<double> idMat(2 * w.rows(), 2 * w.rows());\n\t\t\t\tidMat.setIdentity();\n\t\t\t\t(*hess) = projM * (H + c * idMat) * unProjM;\n\t\t\t}\n\n\t\t\treturn E;\n\t\t};\n\t\tauto maxStep = [&](const Eigen::VectorXd& x, const Eigen::VectorXd& dir) {\n\t\t\treturn 1.0;\n\t\t};\n\n\t\tEigen::VectorXd x0 = projVar(k);\n\n\t\tif (_nInterfaces && freeEid.size())\n\t\t{\n\t\t\tOptSolver::newtonSolver(funVal, maxStep, x0, 1000, 1e-6, 1e-10, 1e-15, false);\n\n\t\t\tEigen::VectorXd deriv;\n\t\t\tdouble E = funVal(x0, &deriv, NULL, false);\n\t\t\tstd::cout << \"terminated with energy : \" << E << \", gradient norm : \" << deriv.norm() << std::endl << std::endl;\n\t\t}\n\t\t\t\n\t\tprevw = unProjVar(x0, k);\n\t\t_combinedRefOmegaList[k] = prevw;\n\t\tprefullx = mat2vec(prevw);\n\t}\n}\n\n\ndouble WrinkleEditingProcess::computeEnergy(const Eigen::VectorXd& x, Eigen::VectorXd* deriv, Eigen::SparseMatrix<double>* hess, bool isProj)\n{\n\tint nverts = _zvalsList[0].size();\n\tint nedges = _edgeOmegaList[0].rows();\n\n\tint numFrames = _zvalsList.size() - 2;\n\n\tint DOFsPerframe = (2 * nverts + 2 * nedges);\n\tint DOFs = numFrames * DOFsPerframe;\n\n\tconvertVariable2List(x);\n\n\tEigen::VectorXd curDeriv;\n\tstd::vector<Eigen::Triplet<double>> T, curT;\n\n\tdouble energy = 0;\n\tif (deriv)\n\t{\n\t\tderiv->setZero(DOFs);\n\t}\n\n\tfor (int i = 0; i < _zvalsList.size() - 1; i++)\n\t{\n\t\tenergy += _zdotModel.computeZdotIntegration(_zvalsList[i], _edgeOmegaList[i], _zvalsList[i + 1], _edgeOmegaList[i + 1], deriv ? &curDeriv : NULL, hess ? &curT : NULL, isProj);\n\n\n\t\tif (deriv)\n\t\t{\n\n\t\t\tif (i == 0)\n\t\t\t\tderiv->segment(0, DOFsPerframe) += curDeriv.segment(DOFsPerframe, DOFsPerframe);\n\t\t\telse if (i == _zvalsList.size() - 2)\n\t\t\t\tderiv->segment((i - 1) * DOFsPerframe, DOFsPerframe) += curDeriv.segment(0, DOFsPerframe);\n\t\t\telse\n\t\t\t{\n\t\t\t\tderiv->segment((i - 1) * DOFsPerframe, 2 * DOFsPerframe) += curDeriv;\n\t\t\t}\n\n\n\t\t}\n\n\t\tif (hess)\n\t\t{\n\t\t\tfor (auto& it : curT)\n\t\t\t{\n\n\t\t\t\tif (i == 0)\n\t\t\t\t{\n\t\t\t\t\tif (it.row() >= DOFsPerframe && it.col() >= DOFsPerframe)\n\t\t\t\t\t\tT.push_back({ it.row() - DOFsPerframe, it.col() - DOFsPerframe, it.value() });\n\t\t\t\t}\n\t\t\t\telse if (i == _zvalsList.size() - 2)\n\t\t\t\t{\n\t\t\t\t\tif (it.row() < DOFsPerframe && it.col() < DOFsPerframe)\n\t\t\t\t\t\tT.push_back({ it.row() + (i - 1) * DOFsPerframe, it.col() + (i - 1) * DOFsPerframe, it.value() });\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tT.push_back({ it.row() + (i - 1) * DOFsPerframe, it.col() + (i - 1) * DOFsPerframe, it.value() });\n\t\t\t\t}\n\n\n\t\t\t}\n\t\t\tcurT.clear();\n\t\t}\n\t}\n\n\tfor (int i = 0; i < numFrames; i++) {\n\t\tint id = i + 1;\n\n\t\t// vertex amp diff\n\t\tdouble aveAmp = 0;\n\t\tfor (int j = 0; j < nverts; j++)\n\t\t{\n\t\t\taveAmp += _combinedRefAmpList[id][j] / nverts;\n\t\t}\n\t\tfor (int j = 0; j < nverts; j++) {\n\t\t\tdouble ampSq = _zvalsList[id][j].real() * _zvalsList[id][j].real() +\n\t\t\t\t_zvalsList[id][j].imag() * _zvalsList[id][j].imag();\n\t\t\tdouble refAmpSq = _combinedRefAmpList[id][j] * _combinedRefAmpList[id][j];\n\n\t\t\tenergy += _spatialRatio * (ampSq - refAmpSq) * (ampSq - refAmpSq) / (aveAmp * aveAmp);\n\n\t\t\tif (deriv) {\n\t\t\t\t(*deriv)(i * DOFsPerframe + 2 * j) += 2.0 * _spatialRatio / (aveAmp * aveAmp) * (ampSq - refAmpSq) *\n\t\t\t\t\t(2.0 * _zvalsList[id][j].real());\n\t\t\t\t(*deriv)(i * DOFsPerframe + 2 * j + 1) += 2.0 * _spatialRatio / (aveAmp * aveAmp) * (ampSq - refAmpSq) *\n\t\t\t\t\t(2.0 * _zvalsList[id][j].imag());\n\t\t\t}\n\n\t\t\tif (hess) {\n\t\t\t\tEigen::Matrix2d tmpHess;\n\t\t\t\ttmpHess << 2.0 * _zvalsList[id][j].real() * 2.0 * _zvalsList[id][j].real(), 2.0 * _zvalsList[id][j].real() * 2.0 * _zvalsList[id][j].imag(),\n\t\t\t\t\t2.0 * _zvalsList[id][j].real() * 2.0 * _zvalsList[id][j].imag(), 2.0 * _zvalsList[id][j].imag() * 2.0 * _zvalsList[id][j].imag();\n\n\t\t\t\ttmpHess *= 2.0 * _spatialRatio / (aveAmp * aveAmp);\n\t\t\t\ttmpHess += 2.0 * _spatialRatio / (aveAmp * aveAmp) * (ampSq - refAmpSq) * (2.0 * Eigen::Matrix2d::Identity());\n\n\t\t\t\tif (isProj)\n\t\t\t\t\ttmpHess = SPDProjection(tmpHess);\n\n\t\t\t\tfor (int k = 0; k < 2; k++)\n\t\t\t\t\tfor (int l = 0; l < 2; l++)\n\t\t\t\t\t\tT.push_back({ i * DOFsPerframe + 2 * j + k, i * DOFsPerframe + 2 * j + l, tmpHess(k, l) });\n\n\t\t\t}\n\t\t}\n\n\t\t// edge omega difference\n\t\tfor (int j = 0; j < nedges; j++) {\n\t\t\tenergy += _spatialRatio * (aveAmp * aveAmp) * (_edgeOmegaList[id] - _combinedRefOmegaList[id]).row(j).dot(\n\t\t\t\t(_edgeOmegaList[id] - _combinedRefOmegaList[id]).row(j));\n\n\t\t\tif (deriv) {\n\t\t\t\t(*deriv)(i * DOFsPerframe + 2 * nverts + 2 * j) += 2 * _spatialRatio * (aveAmp * aveAmp) *\n\t\t\t\t\t(_edgeOmegaList[id] - _combinedRefOmegaList[id])(j,\n\t\t\t\t\t\t0);\n\t\t\t\t(*deriv)(i * DOFsPerframe + 2 * nverts + 2 * j + 1) += 2 * _spatialRatio * (aveAmp * aveAmp) *\n\t\t\t\t\t(_edgeOmegaList[id] -\n\t\t\t\t\t\t_combinedRefOmegaList[id])(j, 1);\n\t\t\t}\n\n\t\t\tif (hess) {\n\t\t\t\tT.push_back({ i * DOFsPerframe + 2 * nverts + 2 * j, i * DOFsPerframe + 2 * nverts + 2 * j,\n\t\t\t\t\t\t\t 2 * _spatialRatio * (aveAmp * aveAmp) });\n\t\t\t\tT.push_back({ i * DOFsPerframe + 2 * nverts + 2 * j + 1, i * DOFsPerframe + 2 * nverts + 2 * j + 1,\n\t\t\t\t\t\t\t 2 * _spatialRatio * (aveAmp * aveAmp) });\n\t\t\t}\n\t\t}\n\n\t\t// knoppel part\n\t\tEigen::VectorXd kDeriv;\n\t\tstd::vector<Eigen::Triplet<double>> kT;\n\n\t\tdouble knoppel = IntrinsicFormula::KnoppelEnergyGivenMag(_mesh, _combinedRefOmegaList[id],\n\t\t\t_combinedRefAmpList[id] / aveAmp, _faceArea, _cotMatrixEntries,\n\t\t\t_zvalsList[id], deriv ? &kDeriv : NULL,\n\t\t\thess ? &kT : NULL);\n\t\tenergy += _spatialRatio * knoppel;\n\n\t\tif (deriv) {\n\t\t\tderiv->segment(i * DOFsPerframe, kDeriv.rows()) += _spatialRatio * kDeriv;\n\t\t}\n\n\t\tif (hess) {\n\t\t\tfor (auto& it : kT) {\n\t\t\t\tT.push_back({ i * DOFsPerframe + it.row(), i * DOFsPerframe + it.col(), _spatialRatio * it.value() });\n\t\t\t}\n\t\t}\n\t}\n\n\n\tif (hess)\n\t{\n\t\t//std::cout << \"num of triplets: \" << T.size() << std::endl;\n\t\thess->resize(DOFs, DOFs);\n\t\thess->setFromTriplets(T.begin(), T.end());\n\t}\n\treturn energy;\n}\n\n////////////////////////////////////////////// test functions ///////////////////////////////////////////////////////////////////////////\nvoid WrinkleEditingProcess::testCurlFreeEnergy(const Eigen::MatrixXd& w)\n{\n\tEigen::VectorXd deriv;\n\tstd::vector<Eigen::Triplet<double>> T;\n\tEigen::SparseMatrix<double> hess;\n\tdouble E = curlFreeEnergy(w, &deriv, &T);\n\thess.resize(2 * w.rows(), 2 * w.rows());\n\thess.setFromTriplets(T.begin(), T.end());\n\n\tstd::cout << \"tested curl free energy: \" << E << \", gradient norm: \" << deriv.norm() << std::endl;\n\n\tEigen::VectorXd dir = deriv;\n\tdir.setRandom();\n\n\tEigen::VectorXd x(2 * w.rows());\n\tfor (int i = 0; i < w.rows(); i++)\n\t{\n\t\tx(2 * i) = w(i, 0);\n\t\tx(2 * i + 1) = w(i, 1);\n\t}\n\tfor (int i = 3; i < 10; i++)\n\t{\n\t\tdouble eps = std::pow(0.1, i);\n\t\tEigen::VectorXd deriv1;\n\t\tEigen::MatrixXd w1 = w;\n\t\tfor (int j = 0; j < w.rows(); j++)\n\t\t{\n\t\t\tw1(j, 0) += eps * dir(2 * j);\n\t\t\tw1(j, 1) += eps * dir(2 * j + 1);\n\t\t}\n\t\tdouble E1 = curlFreeEnergy(w1, &deriv1, NULL);\n\n\t\tstd::cout << \"\\neps: \" << eps << std::endl;\n\t\tstd::cout << \"gradient check: \" << std::abs((E1 - E) / eps - dir.dot(deriv)) << std::endl;\n\t\tstd::cout << \"hess check: \" << ((deriv1 - deriv) / eps - hess * dir).norm() << std::endl;\n\t}\n}\n\nvoid WrinkleEditingProcess::testCurlFreeEnergyPerface(const Eigen::MatrixXd& w, int faceId)\n{\n\tEigen::Matrix<double, 6, 1> deriv;\n\tEigen::Matrix<double, 6, 6> hess;\n\tdouble E = curlFreeEnergyPerface(w, faceId, &deriv, &hess);\n\tEigen::Matrix<double, 6, 1> dir = deriv;\n\tdir.setRandom();\n\n\tstd::cout << \"tested curl free energy for face: \" << faceId << \", energy: \" << E << \", gradient norm: \" << deriv.norm() << std::endl;\n\n\tfor (int i = 3; i < 10; i++)\n\t{\n\t\tdouble eps = std::pow(0.1, i);\n\t\tEigen::MatrixXd w1 = w;\n\t\tfor (int j = 0; j < 3; j++)\n\t\t{\n\t\t\tint eid = _mesh.faceEdge(faceId, j);\n\t\t\tw1(eid, 0) += eps * dir(2 * j);\n\t\t\tw1(eid, 1) += eps * dir(2 * j + 1);\n\t\t}\n\t\tEigen::Matrix<double, 6, 1> deriv1;\n\t\tdouble E1 = curlFreeEnergyPerface(w1, faceId, &deriv1, NULL);\n\n\t\tstd::cout << \"\\neps: \" << eps << std::endl;\n\t\tstd::cout << \"gradient check: \" << std::abs((E1 - E) / eps - dir.dot(deriv)) << std::endl;\n\t\tstd::cout << \"hess check: \" << ((deriv1 - deriv) / eps - hess * dir).norm() << std::endl;\n\t}\n\n}\n\nvoid WrinkleEditingProcess::testDivFreeEnergy(const Eigen::MatrixXd& w)\n{\n\tEigen::VectorXd deriv;\n\tstd::vector<Eigen::Triplet<double>> T;\n\tEigen::SparseMatrix<double> hess;\n\tdouble E = divFreeEnergy(w, &deriv, &T);\n\thess.resize(2 * w.rows(), 2 * w.rows());\n\thess.setFromTriplets(T.begin(), T.end());\n\n\tstd::cout << \"tested div free energy: \" << E << \", gradient norm: \" << deriv.norm() << std::endl;\n\n\tEigen::VectorXd dir = deriv;\n\tdir.setRandom();\n\n\tfor (int i = 3; i < 10; i++)\n\t{\n\t\tdouble eps = std::pow(0.1, i);\n\t\tEigen::VectorXd deriv1;\n\t\tEigen::MatrixXd w1 = w;\n\t\tfor (int j = 0; j < w.rows(); j++)\n\t\t{\n\t\t\tw1(j, 0) += eps * dir(2 * j);\n\t\t\tw1(j, 1) += eps * dir(2 * j + 1);\n\t\t}\n\t\tdouble E1 = divFreeEnergy(w1, &deriv1, NULL);\n\n\t\tstd::cout << \"\\neps: \" << eps << std::endl;\n\t\tstd::cout << \"gradient check: \" << std::abs((E1 - E) / eps - dir.dot(deriv)) << std::endl;\n\t\tstd::cout << \"hess check: \" << ((deriv1 - deriv) / eps - hess * dir).norm() << std::endl;\n\t}\n}\n\nvoid WrinkleEditingProcess::testDivFreeEnergyPervertex(const Eigen::MatrixXd& w, int vertId)\n{\n\tEigen::VectorXd deriv;\n\tEigen::MatrixXd hess;\n\tdouble E = divFreeEnergyPervertex(w, vertId, &deriv, &hess);\n\tEigen::VectorXd dir = deriv;\n\tdir.setRandom();\n\n\tstd::cout << \"tested div free energy for vertex: \" << vertId << \", energy: \" << E << \", gradient norm: \" << deriv.norm() << std::endl;\n\n\tfor (int i = 3; i < 10; i++)\n\t{\n\t\tdouble eps = std::pow(0.1, i);\n\t\tEigen::MatrixXd w1 = w;\n\t\tfor (int j = 0; j < _vertNeiEdges[vertId].size(); j++)\n\t\t{\n\t\t\tint eid = _vertNeiEdges[vertId][j];\n\t\t\tw1(eid, 0) += eps * dir(2 * j);\n\t\t\tw1(eid, 1) += eps * dir(2 * j + 1);\n\t\t}\n\t\tEigen::VectorXd deriv1;\n\t\tdouble E1 = divFreeEnergyPervertex(w1, vertId, &deriv1, NULL);\n\n\t\tstd::cout << \"\\neps: \" << eps << std::endl;\n\t\tstd::cout << \"gradient check: \" << std::abs((E1 - E) / eps - dir.dot(deriv)) << std::endl;\n\t\tstd::cout << \"hess check: \" << ((deriv1 - deriv) / eps - hess * dir).norm() << std::endl;\n\t}\n\n}\n\n\nvoid WrinkleEditingProcess::testAmpEnergyWithGivenOmega(const Eigen::VectorXd& amp, const Eigen::MatrixXd& w)\n{\n\tEigen::VectorXd deriv;\n\tstd::vector<Eigen::Triplet<double>> T;\n\tEigen::SparseMatrix<double> hess;\n\tdouble E = amplitudeEnergyWithGivenOmega(amp, w, &deriv, &T);\n\thess.resize(amp.rows(), amp.rows());\n\thess.setFromTriplets(T.begin(), T.end());\n\n\tstd::cout << \"tested amp energy: \" << E << \", gradient norm: \" << deriv.norm() << std::endl;\n\n\tEigen::VectorXd dir = deriv;\n\tdir.setRandom();\n\n\n\tfor (int i = 3; i < 10; i++)\n\t{\n\t\tdouble eps = std::pow(0.1, i);\n\t\tEigen::VectorXd deriv1;\n\t\tEigen::VectorXd amp1 = amp;\n\t\tfor (int j = 0; j < amp.rows(); j++)\n\t\t{\n\t\t\tamp1(j) += eps * dir(j);\n\t\t}\n\t\tdouble E1 = amplitudeEnergyWithGivenOmega(amp1, w, &deriv1, NULL);\n\n\t\tstd::cout << \"\\neps: \" << eps << std::endl;\n\t\tstd::cout << \"gradient check: \" << std::abs((E1 - E) / eps - dir.dot(deriv)) << std::endl;\n\t\tstd::cout << \"hess check: \" << ((deriv1 - deriv) / eps - hess * dir).norm() << std::endl;\n\t}\n}\n\nvoid WrinkleEditingProcess::testAmpEnergyWithGivenOmegaPerface(const Eigen::VectorXd& amp, const Eigen::MatrixXd& w, int faceId)\n{\n\tEigen::Vector3d deriv;\n\tEigen::Matrix3d hess;\n\tdouble E = amplitudeEnergyWithGivenOmegaPerface(amp, w, faceId, &deriv, &hess);\n\tEigen::Vector3d dir = deriv;\n\tdir.setRandom();\n\n\tstd::cout << \"tested amp energy for face: \" << faceId << \", energy: \" << E << \", gradient norm: \" << deriv.norm() << std::endl;\n\n\tfor (int i = 3; i < 10; i++)\n\t{\n\t\tdouble eps = std::pow(0.1, i);\n\t\tEigen::VectorXd amp1 = amp;\n\t\tfor (int j = 0; j < 3; j++)\n\t\t{\n\t\t\tint vid = _mesh.faceVertex(faceId, j);\n\t\t\tamp1(vid) += eps * dir(j);\n\t\t}\n\t\tEigen::Vector3d deriv1;\n\t\tdouble E1 = amplitudeEnergyWithGivenOmegaPerface(amp1, w, faceId, &deriv1, NULL);\n\n\t\tstd::cout << \"\\neps: \" << eps << std::endl;\n\t\tstd::cout << \"gradient check: \" << std::abs((E1 - E) / eps - dir.dot(deriv)) << std::endl;\n\t\tstd::cout << \"hess check: \" << ((deriv1 - deriv) / eps - hess * dir).norm() << std::endl;\n\t}\n\n}\n\nvoid WrinkleEditingProcess::testEnergy(Eigen::VectorXd x)\n{\n\tEigen::VectorXd deriv;\n\tEigen::SparseMatrix<double> hess;\n\n\tdouble e = computeEnergy(x, &deriv, &hess, false);\n\tstd::cout << \"energy: \" << e << std::endl;\n\n\tEigen::VectorXd dir = deriv;\n\tdir.setRandom();\n\n\tfor (int i = 3; i < 9; i++)\n\t{\n\t\tdouble eps = std::pow(0.1, i);\n\n\t\tEigen::VectorXd deriv1;\n\t\tdouble e1 = computeEnergy(x + eps * dir, &deriv1, NULL, false);\n\n\t\tstd::cout << \"eps: \" << eps << std::endl;\n\t\tstd::cout << \"value-gradient check: \" << (e1 - e) / eps - dir.dot(deriv) << std::endl;\n\t\tstd::cout << \"gradient-hessian check: \" << ((deriv1 - deriv) / eps - hess * dir).norm() << std::endl;\n\t}\n}", "meta": {"hexsha": "e4d1ff63607a627164935a04c859db540b9ed401", "size": 36817, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/IntrinsicFormula/WrinkleEditingProcess.cpp", "max_stars_repo_name": "csyzzkdcz/PhaseInterpolation_polyscope", "max_stars_repo_head_hexsha": "4833a569f9eca1c222f7cdfd8e4aae3f03d8ad0b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/IntrinsicFormula/WrinkleEditingProcess.cpp", "max_issues_repo_name": "csyzzkdcz/PhaseInterpolation_polyscope", "max_issues_repo_head_hexsha": "4833a569f9eca1c222f7cdfd8e4aae3f03d8ad0b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/IntrinsicFormula/WrinkleEditingProcess.cpp", "max_forks_repo_name": "csyzzkdcz/PhaseInterpolation_polyscope", "max_forks_repo_head_hexsha": "4833a569f9eca1c222f7cdfd8e4aae3f03d8ad0b", "max_forks_repo_licenses": ["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.6736760125, "max_line_length": 246, "alphanum_fraction": 0.6202026238, "num_tokens": 13162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397348, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.45953772322821224}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// 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_NON_PARAMETRIC_CONTINGENCY_TABLE_PEARSON_CHISQ_INDEPENDENCE_STATISTIC_HPP_ER_2010\n#define BOOST_STATISTICS_DETAIL_NON_PARAMETRIC_CONTINGENCY_TABLE_PEARSON_CHISQ_INDEPENDENCE_STATISTIC_HPP_ER_2010\n#include <cmath>\n#include <boost/mpl/size.hpp>\n#include <boost/mpl/fold.hpp>\n#include <boost/mpl/for_each.hpp>\n#include <boost/mpl/push_back.hpp>\n#include <boost/mpl/placeholders.hpp>\n#include <boost/mpl/vector/vector10.hpp>\n#include <boost/mpl/detail/wrapper.hpp>\n#include <boost/lambda/lambda.hpp>\n#include <boost/lambda/bind.hpp>\n#include <boost/numeric/conversion/converter.hpp>\n#include <boost/type_traits/add_const.hpp>\n#include <boost/type_traits/remove_reference.hpp>\n#include <boost/foreach.hpp>\n#include <boost/range.hpp>\n#include <boost/accumulators/statistics/detail/weighted_count.hpp>\n#include <boost/statistics/detail/non_parametric/contingency_table/pearson_chisq/common/chisq_summand_formula.hpp>\n#include <boost/statistics/detail/non_parametric/contingency_table/cells/cells.hpp>\n#include <boost/statistics/detail/non_parametric/contingency_table/cells/count_matching.hpp>\n\n// Under independence, in dimension = 2\n// p_{j1,j2} = p_{j1} * p{j2}\n\n// Warning : this is incomplete / Wrong.\n\nnamespace boost { \nnamespace statistics{\nnamespace detail{\nnamespace contingency_table{\nnamespace pearson_chisq_statistic{\nnamespace independence_between_aux{\n\n    template<typename T1,typename Keys,typename AccSet>\n    struct chisq_summand\n    {\n\n        typedef std::size_t size_;\n        typedef typename boost::mpl::size<Keys>::type keys_count_;\n        \n        template<typename N> \n        chisq_summand(const AccSet& a, const N& total_count) \n            : acc( a ) , denom( \n                pow( total_count, keys_count_::value - 1)\n            ){}\n\n        template<typename C>        \n        T1 operator()(const C& cell)const\n        {\n            namespace ct = contingency_table;\n            typedef boost::mpl::detail::wrapper< \n                 boost::mpl::vector1< boost::mpl::_ >\n            > op_;\n            typedef boost::numeric::converter<T1,size_> conv_;\n            size_ n = 1;\n        \tboost::mpl::for_each<Keys,op_>( \n                ct::make_fun_count_matcher(acc, cell.first, prod_fun( n ) )\n            );\n            return pearson_chisq_statistic::chisq_summand_formula<T1>( \n                conv_::convert( n ) / conv_::convert( denom ), \n                cell.second \n            );\n        }\n    \n        struct prod_fun{\n            \n            prod_fun(size_& n) : n_( n ){}\n            \n            template<typename T> \n            void operator()(const T& k)const{ \n                this->n_ *= k; \n            }\n            \n            mutable size_& n_;\n        };\n    \n        const AccSet& acc;\n        size_ denom;\n\n    };\n\n}// independence_between_aux\n\n\n    template<typename T1,typename Keys,typename AccSet>\n    T1 value(\n        const boost::mpl::detail::wrapper<\n            pearson_chisq_statistic::tag::independence_between<Keys>\n        >& hypothesis,\n        const AccSet& acc\n    )\n    {\n        namespace ct = contingency_table;\n        namespace ns = ct::pearson_chisq_statistic::independence_between_aux;\n        typedef typename ct::result_of::extract::cells<\n            Keys,AccSet>::type ref_cells_;\n        typedef typename boost::remove_reference<ref_cells_>::type cells_;\n        typedef typename boost::range_reference<cells_>::type ref_cell_;\n        typedef ns::chisq_summand<T1,Keys,AccSet> summand_;\n        typedef std::size_t size_;\n        \n        ref_cells_ ref_cells = ct::extract::cells<Keys>( acc );\n        size_ n_obs = boost::accumulators::extract::weighted_count( acc );       \n        \n        summand_ summand(acc, n_obs);\n        typedef boost::numeric::converter<T1,size_> conv_;\n        \n        T1 result = conv_::convert( 0 );\n        BOOST_FOREACH(ref_cell_ ref_cell, ref_cells )\n        {\n            result += summand( ref_cell );\n        }\n        \n        return result;        \n    }\n\n}// pearson_chisq_statistic\n}// contingency_table\n}// detail\n}// statistics\n}// boost\n\n#endif\n", "meta": {"hexsha": "ca8adb503adce096955b9de978bd6eddfbef2e65", "size": 4669, "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/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/contingency_table/pearson_chisq/independence/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/contingency_table/pearson_chisq/independence/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": 35.3712121212, "max_line_length": 114, "alphanum_fraction": 0.5999143286, "num_tokens": 1044, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.5813030906443134, "lm_q1q2_score": 0.45953771749071587}}
{"text": "/*\n   bern_modp.cpp:  computing isolated Bernoulli numbers modulo p\n\n   Copyright (C) 2008, 2009, David Harvey\n\n   This file is part of the bernmm package (version 1.1).\n\n   bernmm is released under a BSD-style license. See the README file in\n   the source distribution for details.\n*/\n\n\n#include <limits.h>\n#include <signal.h>\n#include <cstring>\n#include <gmp.h>\n#include <NTL/ZZ.h>\n#include \"bern_modp_util.h\"\n#include \"bern_modp.h\"\n\n\nNTL_CLIENT;\n\n\nusing namespace std;\n\n\nnamespace bernmm {\n\n\n/******************************************************************************\n\n   Computing the main sum (general case)\n\n******************************************************************************/\n\n/*\n   Returns (1 - g^k) B_k / 2k mod p.\n\n   PRECONDITIONS:\n      5 <= p < NTL_SP_BOUND, p prime\n      2 <= k <= p-3, k even\n      pinv = PrepMulMod(p)\n      g = a multiplicative generator of GF(p), in [0, p)\n*/\nlong bernsum_powg(long p, mulmod_t pinv, long k, long g)\n{\n   long half_gm1 = (g + ((g & 1) ? 0 : p) - 1) / 2;    // (g-1)/2 mod p\n   long g_to_jm1 = 1;\n   long g_to_km1 = PowerMod(g, k-1, p, pinv);\n   long g_to_km1_to_j = g_to_km1;\n   long sum = 0;\n   muldivrem_t g_pinv = PrepMulDivRem(g, p);\n   mulmod_precon_t g_to_km1_pinv = PrepMulModPrecon(g_to_km1, p, pinv);\n\n   for (long j = 1; j <= (p-1)/2; j++)\n   {\n      // at this point,\n      //    g_to_jm1 holds g^(j-1) mod p\n      //    g_to_km1_to_j holds (g^(k-1))^j mod p\n\n      // update g_to_jm1 and compute q = (g*(g^(j-1) mod p) - (g^j mod p)) / p\n      long q;\n      g_to_jm1 = MulDivRem(q, g_to_jm1, g, p, g_pinv);\n\n      // compute h = -h_g(g^j) = q - (g-1)/2\n      long h = SubMod(q, half_gm1, p);\n\n      // add h_g(g^j) * (g^(k-1))^j to running total\n      sum = SubMod(sum, MulMod(h, g_to_km1_to_j, p, pinv), p);\n\n      // update g_to_km1_to_j\n      g_to_km1_to_j = MulModPrecon(g_to_km1_to_j, g_to_km1, p, g_to_km1_pinv);\n   }\n\n   return sum;\n}\n\n\n\n/******************************************************************************\n\n   Computing the main sum (c = 1/2 case)\n\n******************************************************************************/\n\n\n/*\n   The Expander class stores precomputed information for a fixed integer p,\n   that subsequently permits fast computation of the binary expansion of s/p\n   for any 0 < s < p.\n\n   The constructor takes p and max_words as input. Must have 1 <= max_words <=\n   MAX_INV. It computes an approximation to 1/p.\n\n   The function expand(word_t* res, long s, long n) computes n words of s/p.\n   Must have 0 < s < p and 1 <= n <= max_words. The output is written to res.\n   The first word of output is junk. The next n words are the digits of s/p,\n   from least to most significant. The buffer must be at least n+2 words long\n   (even though the first and last words are never used for output).\n\n   A \"word\" is a word_t, and contains WORD_BITS bits. On most systems this\n   will be an mp_limb_t.\n*/\n\n#define MAX_INV 256\n\n#if (GMP_NAIL_BITS == 0) && (GMP_LIMB_BITS >= ULONG_BITS)\n// fast mpn-based version\n\ntypedef mp_limb_t word_t;\n#define WORD_BITS GMP_LIMB_BITS\n\nclass Expander\n{\nprivate:\n   // Approximation to 1/p. We store (max_words + 1) limbs.\n   mp_limb_t pinv[MAX_INV + 2];\n   mp_limb_t p;\n   int max_words;\n\npublic:\n   Expander(long p, int max_words)\n   {\n      assert(max_words >= 1);\n      assert(max_words <= MAX_INV);\n\n      this->max_words = max_words;\n      this->p = p;\n      mp_limb_t one = 1;\n      mpn_divrem_1(pinv, max_words + 1, &one, 1, p);\n   }\n\n   void expand(word_t* res, long s, int n)\n   {\n      assert(s > 0 && s < p);\n      assert(n >= 1);\n      assert(n <= max_words);\n\n      if (s == 1)\n      {\n         // already have 1/p; just copy it\n         for (int i = 1; i <= n; i++)\n            res[i] = pinv[max_words - n + i];\n      }\n      else\n      {\n         mpn_mul_1(res, pinv + max_words - n, n + 1, (mp_limb_t) s);\n\n         // If the first output limb is really close to 0xFFFF..., then there's\n         // a possibility of overflow, so fall back on doing division directly.\n         // This should happen extremely rarely --- essentially never on a\n         // 64-bit system, and very occasionally on a 32-bit system.\n         if (res[0] > -((mp_limb_t) s))\n         {\n            mp_limb_t ss = s;\n            mpn_divrem_1(res, n + 1, &ss, 1, p);\n         }\n      }\n   }\n};\n\n\n#else\n// slow mpz-based version, since GMP is using nails, or mp_limb_t is\n// absurdly narrow\n\ntypedef unsigned long word_t;\n#define WORD_BITS ULONG_BITS\n\nclass Expander\n{\nprivate:\n   mp_limb_t p;\n   mpz_t temp;\n\npublic:\n   Expander(long p, int max_words)\n   {\n      this->p = p;\n      mpz_init(temp);\n   }\n\n   ~Expander()\n   {\n      mpz_clear(temp);\n   }\n\n   void expand(word_t* res, long s, int n)\n   {\n      assert(s > 0 && s < p);\n      assert(n >= 1);\n\n      mpz_set_ui(temp, s);\n      mpz_mul_2exp(temp, temp, WORD_BITS * n);\n      mpz_fdiv_q_ui(temp, temp, p);\n      mpz_export(res + 1, NULL, -1, sizeof(word_t), 0, 0, temp);\n   }\n};\n\n#endif\n\n\n\n/*\n   Returns (2^(-k) - 1) 2 B_k / k  mod p.\n\n   (Note: this is useless if 2^k = 1 mod p.)\n\n   PRECONDITIONS:\n      5 <= p < NTL_SP_BOUND, p prime\n      2 <= k <= p-3, k even\n      pinv = PrepMulMod(p)\n      g = a multiplicative generator of GF(p), in [0, p)\n      n = multiplicative order of 2 in GF(p)\n*/\n\n#define TABLE_LG_SIZE 8\n#define TABLE_SIZE (((word_t) 1) << TABLE_LG_SIZE)\n#define TABLE_MASK (TABLE_SIZE - 1)\n#define NUM_TABLES (WORD_BITS / TABLE_LG_SIZE)\n\n#if WORD_BITS % TABLE_LG_SIZE != 0\n#error Number of bits in a long must be divisible by TABLE_LG_SIZE\n#endif\n\nlong bernsum_pow2(long p, mulmod_t pinv, long k, long g, long n)\n{\n   // In the main summation loop we accumulate data into the _tables_ array;\n   // tables[y][z] contributes to the final answer with a weight of\n   //\n   // sum(-(-1)^z[t] * (2^(k-1))^(WORD_BITS - 1 - y * TABLE_LG_SIZE - t) :\n   //                                                  0 <= t < TABLE_LG_SIZE),\n   //\n   // where z[t] denotes the t-th binary digit of z (LSB is t = 0).\n   // The memory footprint for _tables_ is 4KB on a 32-bit machine, or 16KB\n   // on a 64-bit machine, so should fit easily into L1 cache.\n   long tables[NUM_TABLES][TABLE_SIZE];\n   memset(tables, 0, sizeof(long) * NUM_TABLES * TABLE_SIZE);\n\n   long m = (p-1) / n;\n\n   // take advantage of symmetry (n' and m' from the paper)\n   if (n & 1)\n      m >>= 1;\n   else\n      n >>= 1;\n\n   // g^(k-1)\n   long g_to_km1 = PowerMod(g, k-1, p, pinv);\n   // 2^(k-1)\n   long two_to_km1 = PowerMod(2, k-1, p, pinv);\n   // B^(k-1), where B = 2^WORD_BITS\n   long B_to_km1 = PowerMod(two_to_km1, WORD_BITS, p, pinv);\n   // B^(MAX_INV)\n   long s_jump = PowerMod(2, MAX_INV * WORD_BITS, p, pinv);\n\n   // help speed up modmuls\n   mulmod_precon_t g_pinv = PrepMulModPrecon(g, p, pinv);\n   mulmod_precon_t g_to_km1_pinv = PrepMulModPrecon(g_to_km1, p, pinv);\n   mulmod_precon_t two_to_km1_pinv = PrepMulModPrecon(two_to_km1, p, pinv);\n   mulmod_precon_t B_to_km1_pinv = PrepMulModPrecon(B_to_km1, p, pinv);\n   mulmod_precon_t s_jump_pinv = PrepMulModPrecon(s_jump, p, pinv);\n\n   long g_to_km1_to_i = 1;\n   long g_to_i = 1;\n   long sum = 0;\n\n   // Precompute some of the binary expansion of 1/p; at most MAX_INV words,\n   // or possibly less if n is sufficiently small\n   Expander expander(p, (n >= MAX_INV * WORD_BITS)\n                                       ? MAX_INV : ((n - 1) / WORD_BITS + 1));\n\n   // =========== phase 1: main summation loop\n\n   // loop over outer sum\n   for (long i = 0; i < m; i++)\n   {\n      // s keeps track of g^i*2^j mod p\n      long s = g_to_i;\n      // x keeps track of (g^i*2^j)^(k-1) mod p\n      long x = g_to_km1_to_i;\n\n      // loop over inner sum; break it up into chunks of length at most\n      // MAX_INV * WORD_BITS. If n is large, this allows us to do most of\n      // the work with mpn_mul_1 instead of mpn_divrem_1, and also improves\n      // memory locality.\n      for (long nn = n; nn > 0; nn -= MAX_INV * WORD_BITS)\n      {\n         word_t s_over_p[MAX_INV + 2];\n         long bits, words;\n\n         if (nn >= MAX_INV * WORD_BITS)\n         {\n            // do one chunk of length exactly MAX_INV * WORD_BITS\n            bits = MAX_INV * WORD_BITS;\n            words = MAX_INV;\n         }\n         else\n         {\n            // last chunk of length less than MAX_INV * WORD_BITS\n            bits = nn;\n            words = (nn - 1) / WORD_BITS + 1;\n         }\n\n         // compute some bits of the binary expansion of s/p\n         expander.expand(s_over_p, s, words);\n         word_t* next = s_over_p + words;\n\n         // loop over whole words\n         for (; bits >= WORD_BITS; bits -= WORD_BITS, next--)\n         {\n            word_t y = *next;\n\n#if NUM_TABLES != 8 && NUM_TABLES != 4\n            // generic version\n            for (long h = 0; h < NUM_TABLES; h++)\n            {\n               long& target = tables[h][y & TABLE_MASK];\n               target = SubMod(target, x, p);\n               y >>= TABLE_LG_SIZE;\n            }\n#else\n            // unrolled versions for 32-bit/64-bit machines\n            long& target0 = tables[0][y & TABLE_MASK];\n            target0 = SubMod(target0, x, p);\n\n            long& target1 = tables[1][(y >> TABLE_LG_SIZE) & TABLE_MASK];\n            target1 = SubMod(target1, x, p);\n\n            long& target2 = tables[2][(y >> (2*TABLE_LG_SIZE)) & TABLE_MASK];\n            target2 = SubMod(target2, x, p);\n\n            long& target3 = tables[3][(y >> (3*TABLE_LG_SIZE)) & TABLE_MASK];\n            target3 = SubMod(target3, x, p);\n#if NUM_TABLES == 8\n            long& target4 = tables[4][(y >> (4*TABLE_LG_SIZE)) & TABLE_MASK];\n            target4 = SubMod(target4, x, p);\n\n            long& target5 = tables[5][(y >> (5*TABLE_LG_SIZE)) & TABLE_MASK];\n            target5 = SubMod(target5, x, p);\n\n            long& target6 = tables[6][(y >> (6*TABLE_LG_SIZE)) & TABLE_MASK];\n            target6 = SubMod(target6, x, p);\n\n            long& target7 = tables[7][(y >> (7*TABLE_LG_SIZE)) & TABLE_MASK];\n            target7 = SubMod(target7, x, p);\n#endif\n#endif\n\n            x = MulModPrecon(x, B_to_km1, p, B_to_km1_pinv);\n         }\n\n         // loop over remaining bits in the last word\n         word_t y = *next;\n         for (; bits > 0; bits--)\n         {\n            if (y & (((word_t) 1) << (WORD_BITS - 1)))\n               sum = SubMod(sum, x, p);\n            else\n               sum = AddMod(sum, x, p);\n\n            x = MulModPrecon(x, two_to_km1, p, two_to_km1_pinv);\n            y <<= 1;\n         }\n\n         // update s\n         s = MulModPrecon(s, s_jump, p, s_jump_pinv);\n      }\n\n      // update g^i and (g^(k-1))^i\n      g_to_i = MulModPrecon(g_to_i, g, p, g_pinv);\n      g_to_km1_to_i = MulModPrecon(g_to_km1_to_i, g_to_km1, p, g_to_km1_pinv);\n   }\n\n   // =========== phase 2: consolidate table data\n\n   // compute weights[z] = sum((-1)^z[t] * (2^(k-1))^(TABLE_LG_SIZE - 1 - t) :\n   //                                                  0 <= t < TABLE_LG_SIZE).\n\n   long weights[TABLE_SIZE];\n   weights[0] = 0;\n   for (long h = 0, x = 1; h < TABLE_LG_SIZE;\n        h++, x = MulModPrecon(x, two_to_km1, p, two_to_km1_pinv))\n   {\n      for (long i = (1L << h) - 1; i >= 0; i--)\n      {\n         weights[2*i+1] = SubMod(weights[i], x, p);\n         weights[2*i]   = AddMod(weights[i], x, p);\n      }\n   }\n\n   // combine table data with weights\n\n   long x_jump = PowerMod(two_to_km1, TABLE_LG_SIZE, p, pinv);\n\n   for (long h = NUM_TABLES - 1, x = 1; h >= 0; h--)\n   {\n      mulmod_precon_t x_pinv = PrepMulModPrecon(x, p, pinv);\n\n      for (long i = 0; i < TABLE_SIZE; i++)\n      {\n         long y = MulMod(tables[h][i], weights[i], p, pinv);\n         y = MulModPrecon(y, x, p, x_pinv);\n         sum = SubMod(sum, y, p);\n      }\n\n      x = MulModPrecon(x_jump, x, p, x_pinv);\n   }\n\n   return sum;\n}\n\n\n/******************************************************************************\n\n   Computing the main sum (c = 1/2 case, with REDC arithmetic)\n\n   Throughout this section F denotes 2^(ULONG_BITS / 2).\n\n******************************************************************************/\n\n\n/*\n   Returns x/F mod n. Output is in [0, 2n), i.e. *not* reduced completely\n   into [0, n).\n\n   PRECONDITIONS:\n      3 <= n < F, n odd\n      0 <= x < nF    (if n < F/2)\n      0 <= x < nF/2  (if n > F/2)\n      ninv2 = -1/n mod F\n*/\n#define LOW_MASK ((1L << (ULONG_BITS / 2)) - 1)\nstatic inline long RedcFast(long x, long n, long ninv2)\n{\n   unsigned long y = (x * ninv2) & LOW_MASK;\n   unsigned long z = x + (n * y);\n   return z >> (ULONG_BITS / 2);\n}\n\n\n/*\n   Same as RedcFast(), but reduces output into [0, n).\n*/\nstatic inline long Redc(long x, long n, long ninv2)\n{\n   long y = RedcFast(x, n, ninv2);\n   if (y >= n)\n      y -= n;\n   return y;\n}\n\n\n/*\n   Computes -1/n mod F, in [0, F).\n\n   PRECONDITIONS:\n      3 <= n < F, n odd\n*/\nlong PrepRedc(long n)\n{\n   long ninv2 = -n;   // already correct mod 8\n\n   // newton's method for 2-adic inversion\n   for (long bits = 3; bits < ULONG_BITS/2; bits *= 2)\n      ninv2 = 2*ninv2 + n * ninv2 * ninv2;\n\n   return ninv2 & LOW_MASK;\n}\n\n\n/*\n   Same as bernsum_pow2(), but uses REDC arithmetic, and various delayed\n   reduction strategies.\n\n   PRECONDITIONS:\n      Same as bernsum_pow2(), and in addition:\n      p < 2^(ULONG_BITS/2 - 1)\n\n   (See bernsum_pow2() for code comments; we only add comments here where\n   something is different from bernsum_pow2())\n*/\nlong bernsum_pow2_redc(long p, mulmod_t pinv, long k, long g, long n)\n{\n   long pinv2 = PrepRedc(p);\n   long F = (1L << (ULONG_BITS/2)) % p;\n\n   long tables[NUM_TABLES][TABLE_SIZE];\n   memset(tables, 0, sizeof(long) * NUM_TABLES * TABLE_SIZE);\n\n   long m = (p-1) / n;\n\n   if (n & 1)\n      m >>= 1;\n   else\n      n >>= 1;\n\n   long g_to_km1 = PowerMod(g, k-1, p, pinv);\n   long two_to_km1 = PowerMod(2, k-1, p, pinv);\n   long B_to_km1 = PowerMod(two_to_km1, WORD_BITS, p, pinv);\n   long s_jump = PowerMod(2, MAX_INV * WORD_BITS, p, pinv);\n\n   long g_redc = MulMod(g, F, p, pinv);\n   long g_to_km1_redc = MulMod(g_to_km1, F, p, pinv);\n   long two_to_km1_redc = MulMod(two_to_km1, F, p, pinv);\n   long B_to_km1_redc = MulMod(B_to_km1, F, p, pinv);\n   long s_jump_redc = MulMod(s_jump, F, p, pinv);\n\n   long g_to_km1_to_i = 1;    // always in [0, 2p)\n   long g_to_i = 1;           // always in [0, 2p)\n   long sum = 0;\n\n   Expander expander(p, (n >= MAX_INV * WORD_BITS)\n                                       ? MAX_INV : ((n - 1) / WORD_BITS + 1));\n\n   // =========== phase 1: main summation loop\n\n   for (long i = 0; i < m; i++)\n   {\n      long s = g_to_i;           // always in [0, p)\n      if (s >= p)\n         s -= p;\n\n      long x = g_to_km1_to_i;    // always in [0, 2p)\n\n      for (long nn = n; nn > 0; nn -= MAX_INV * WORD_BITS)\n      {\n         word_t s_over_p[MAX_INV + 2];\n         long bits, words;\n\n         if (nn >= MAX_INV * WORD_BITS)\n         {\n            bits = MAX_INV * WORD_BITS;\n            words = MAX_INV;\n         }\n         else\n         {\n            bits = nn;\n            words = (nn - 1) / WORD_BITS + 1;\n         }\n\n         expander.expand(s_over_p, s, words);\n         word_t* next = s_over_p + words;\n\n         for (; bits >= WORD_BITS; bits -= WORD_BITS, next--)\n         {\n            word_t y = *next;\n\n            // note: we add the values into tables *without* reduction mod p\n\n#if NUM_TABLES != 8 && NUM_TABLES != 4\n            // generic version\n            for (long h = 0; h < NUM_TABLES; h++)\n            {\n               tables[h][y & TABLE_MASK] += x;\n               y >>= TABLE_LG_SIZE;\n            }\n#else\n            // unrolled versions for 32-bit/64-bit machines\n            tables[0][ y                       & TABLE_MASK] += x;\n            tables[1][(y >>    TABLE_LG_SIZE ) & TABLE_MASK] += x;\n            tables[2][(y >> (2*TABLE_LG_SIZE)) & TABLE_MASK] += x;\n            tables[3][(y >> (3*TABLE_LG_SIZE)) & TABLE_MASK] += x;\n#if NUM_TABLES == 8\n            tables[4][(y >> (4*TABLE_LG_SIZE)) & TABLE_MASK] += x;\n            tables[5][(y >> (5*TABLE_LG_SIZE)) & TABLE_MASK] += x;\n            tables[6][(y >> (6*TABLE_LG_SIZE)) & TABLE_MASK] += x;\n            tables[7][(y >> (7*TABLE_LG_SIZE)) & TABLE_MASK] += x;\n#endif\n#endif\n\n            x = RedcFast(x * B_to_km1_redc, p, pinv2);\n         }\n\n         // bring x into [0, p) for next loop\n         if (x >= p)\n            x -= p;\n\n         word_t y = *next;\n         for (; bits > 0; bits--)\n         {\n            if (y & (((word_t) 1) << (WORD_BITS - 1)))\n               sum = SubMod(sum, x, p);\n            else\n               sum = AddMod(sum, x, p);\n\n            x = Redc(x * two_to_km1_redc, p, pinv2);\n            y <<= 1;\n         }\n\n         s = Redc(s * s_jump_redc, p, pinv2);\n      }\n\n      g_to_i = RedcFast(g_to_i * g_redc, p, pinv2);\n      g_to_km1_to_i = RedcFast(g_to_km1_to_i * g_to_km1_redc, p, pinv2);\n   }\n\n   // At this point, each table entry is at most p^2 (since x was always\n   // in [0, 2p), and the inner loop was called at most (p/2) / WORD_BITS\n   // times, and 2p * p/2 / WORD_BITS * TABLE_LG_SIZE <= p^2).\n\n   // =========== phase 2: consolidate table data\n\n   long weights[TABLE_SIZE];\n   weights[0] = 0;\n   // we store the weights multiplied by a factor of 2^(3*ULONG_BITS/2) to\n   // compensate for the three rounds of REDC reduction in the loop below\n   for (long h = 0, x = PowerMod(2, 3*ULONG_BITS/2, p, pinv);\n        h < TABLE_LG_SIZE; h++, x = Redc(x * two_to_km1_redc, p, pinv2))\n   {\n      for (long i = (1L << h) - 1; i >= 0; i--)\n      {\n         weights[2*i+1] = SubMod(weights[i], x, p);\n         weights[2*i]   = AddMod(weights[i], x, p);\n      }\n   }\n\n   long x_jump = PowerMod(two_to_km1, TABLE_LG_SIZE, p, pinv);\n   long x_jump_redc = MulMod(x_jump, F, p, pinv);\n\n   for (long h = NUM_TABLES - 1, x = 1; h >= 0; h--)\n   {\n      for (long i = 0; i < TABLE_SIZE; i++)\n      {\n         long y;\n         y = RedcFast(tables[h][i], p, pinv2);\n         y = RedcFast(y * weights[i], p, pinv2);\n         y = RedcFast(y * x, p, pinv2);\n         sum += y;\n      }\n\n      x = Redc(x * x_jump_redc, p, pinv2);\n   }\n\n   return sum % p;\n}\n\n\n\n/******************************************************************************\n\n   Wrappers for bernsum_*\n\n******************************************************************************/\n\n\n/*\n   Returns B_k/k mod p, in the range [0, p).\n\n   PRECONDITIONS:\n      5 <= p < NTL_SP_BOUND, p prime\n      2 <= k <= p-3, k even\n      pinv = PrepMulMod(p)\n\n   Algorithm: uses bernsum_powg() to compute the main sum.\n*/\nlong _bern_modp_powg(long p, mulmod_t pinv, long k)\n{\n   Factorisation F(p-1);\n   long g = primitive_root(p, pinv, F);\n\n   // compute main sum\n   long x = bernsum_powg(p, pinv, k, g);\n\n   // divide by (1 - g^k) and multiply by 2\n   long g_to_k = PowerMod(g, k, p, pinv);\n   long t = InvMod(p + 1 - g_to_k, p);\n   x = MulMod(x, t, p, pinv);\n   x = AddMod(x, x, p);\n\n   return x;\n}\n\n\n/*\n   Returns B_k/k mod p, in the range [0, p).\n\n   PRECONDITIONS:\n      5 <= p < NTL_SP_BOUND, p prime\n      2 <= k <= p-3, k even\n      pinv = PrepMulMod(p)\n      2^k != 1 mod p\n\n   Algorithm: uses bernsum_pow2() (or bernsum_pow2_redc() if p is small\n   enough) to compute the main sum.\n*/\nlong _bern_modp_pow2(long p, mulmod_t pinv, long k)\n{\n   Factorisation F(p-1);\n   long g = primitive_root(p, pinv, F);\n   long n = order(2, p, pinv, F);\n\n   // compute main sum\n   long x;\n   if (p < (1L << (ULONG_BITS/2 - 1)))\n      x = bernsum_pow2_redc(p, pinv, k, g, n);\n   else\n      x = bernsum_pow2(p, pinv, k, g, n);\n\n   // divide by 2*(2^(-k) - 1)\n   long t = PowerMod(2, -k, p, pinv) - 1;\n   t = AddMod(t, t, p);\n   t = InvMod(t, p);\n   x = MulMod(x, t, p, pinv);\n\n   return x;\n}\n\n\n\n/*\n   Returns B_k/k mod p, in the range [0, p).\n\n   PRECONDITIONS:\n      5 <= p < NTL_SP_BOUND, p prime\n      2 <= k <= p-3, k even\n      pinv = PrepMulMod(p)\n*/\nlong _bern_modp(long p, mulmod_t pinv, long k)\n{\n   if (PowerMod(2, k, p, pinv) != 1)\n      // 2^k != 1 mod p, so we use the faster version\n      return _bern_modp_pow2(p, pinv, k);\n   else\n      // forced to use slower version\n      return _bern_modp_powg(p, pinv, k);\n}\n\n\n\n/******************************************************************************\n\n   Main bern_modp() routine\n\n******************************************************************************/\n\nlong bern_modp(long p, long k)\n{\n   assert(k >= 0);\n   assert(2 <= p && p < NTL_SP_BOUND);\n\n   // B_0 = 1\n   if (k == 0)\n      return 1;\n\n   // B_1 = -1/2 mod p\n   if (k == 1)\n   {\n      if (p == 2)\n         return -1;\n      return (p-1)/2;\n   }\n\n   // B_k = 0 for odd k >= 3\n   if (k & 1)\n      return 0;\n\n   // denominator of B_k is always divisible by 6 for k >= 2\n   if (p <= 3)\n      return -1;\n\n   // use Kummer's congruence (k = m mod p-1  =>  B_k/k = B_m/m mod p)\n   long m = k % (p-1);\n   if (m == 0)\n      return -1;\n\n   mulmod_t pinv = PrepMulMod(p);\n   long x = _bern_modp(p, pinv, m);    // = B_m/m mod p\n   return MulMod(x, k%p, p, pinv);\n}\n\n\n};    // end namespace\n\n\n\n// end of file ================================================================\n", "meta": {"hexsha": "b46a7de18bcb27564b848502880439f8e3745d86", "size": 21026, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sage/rings/bernmm/bern_modp.cpp", "max_stars_repo_name": "bopopescu/sage", "max_stars_repo_head_hexsha": "2d495be78e0bdc7a0a635454290b27bb4f5f70f0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1742.0, "max_stars_repo_stars_event_min_datetime": "2015-01-04T07:06:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T11:32:52.000Z", "max_issues_repo_path": "src/sage/rings/bernmm/bern_modp.cpp", "max_issues_repo_name": "Ivo-Maffei/sage", "max_issues_repo_head_hexsha": "467fbc70a08b552b3de33d9065204ee9cbfb02c7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 66.0, "max_issues_repo_issues_event_min_datetime": "2015-03-19T19:17:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T11:59:30.000Z", "max_forks_repo_path": "src/sage/rings/bernmm/bern_modp.cpp", "max_forks_repo_name": "dimpase/sage", "max_forks_repo_head_hexsha": "468f23815ade42a2192b0a9cd378de8fdc594dcd", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 495.0, "max_forks_repo_forks_event_min_datetime": "2015-01-10T10:23:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T22:06:11.000Z", "avg_line_length": 26.9910141207, "max_line_length": 79, "alphanum_fraction": 0.5267763721, "num_tokens": 6661, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4595377174907158}}
{"text": "// Copyright (c) Dewetron 2017\n#include \"otfft.h\"\n\n#include <boost/test/unit_test.hpp>\n\n#include <algorithm>\n#include <cmath>\n#include <cstdint>\n#include <functional>\n#include <iterator>\n#include <random>\n#include <vector>\n\nnamespace\n{\n    template <OTFFT::TransformationType TR_TYPE, OTFFT::OptimizationType OPT_TYPE>\n    void testComplexFFT(const std::size_t SIZE)\n    {\n        std::random_device rnd_device;\n        std::mt19937 mersenne_engine(rnd_device());\n        std::uniform_real_distribution<double> dist(-99.0, 99.0);\n        auto gen = std::bind(dist, mersenne_engine);\n\n        std::vector<OTFFT::complex_t> expected;\n\n        for (auto n = 0; n < SIZE; ++n)\n        {\n            expected.emplace_back(gen(), gen());\n        }\n\n        std::vector<OTFFT::complex_t> spectrum = expected;\n\n        auto fft = TR_TYPE == OTFFT::TransformationType::TRANSFORM_BLUESTEIN ?\n                       OTFFT::Factory::createBluesteinFFT(static_cast<int>(SIZE), OPT_TYPE) :\n                       OTFFT::Factory::createComplexFFT(static_cast<int>(SIZE), OPT_TYPE);\n        {\n            OTFFT::complex_vector spectrum_pointer{spectrum.data()};\n            fft->fwd0(spectrum_pointer);\n            fft->invn(spectrum_pointer);\n        }\n\n        for (std::size_t idx{0}; idx < SIZE / 2; ++idx)\n        {\n            if (std::fabs(expected[idx].Re) < 1e-10)\n            {\n                BOOST_CHECK_SMALL(spectrum[idx].Re, 1e-8);\n            }\n            else\n            {\n                BOOST_CHECK_CLOSE(expected[idx].Re, spectrum[idx].Re, .1);\n            }\n\n            if (std::fabs(expected[idx].Im) < 1e-10)\n            {\n                BOOST_CHECK_SMALL(spectrum[idx].Im, 1e-8);\n            }\n            else\n            {\n                BOOST_CHECK_CLOSE(expected[idx].Im, spectrum[idx].Im, .1);\n            }\n        }\n    }\n\n    template <OTFFT::OptimizationType OPT_TYPE>\n    void testRealFFT(const std::size_t SIZE)\n    {\n        std::random_device rnd_device;\n        std::mt19937 mersenne_engine(rnd_device());\n        std::uniform_real_distribution<double> dist(-99.0, 99.0);\n        auto gen = std::bind(dist, mersenne_engine);\n\n        std::vector<double> expected;\n\n        for (auto n = 0; n < SIZE; ++n)\n        {\n            expected.emplace_back(gen());\n        }\n\n        std::vector<double> spectrum = expected;\n\n        auto fft = OTFFT::Factory::createRealFFT(static_cast<int>(SIZE), OPT_TYPE);\n        {\n            std::vector<OTFFT::complex_t> workspace(SIZE);\n            OTFFT::double_vector spectrum_pointer{spectrum.data()};\n            OTFFT::complex_vector workspace_pointer{workspace.data()};\n            fft->fwd0(spectrum_pointer, workspace_pointer);\n            fft->invn(workspace_pointer, spectrum_pointer);\n        }\n\n        for (std::size_t idx{0}; idx < SIZE / 2; ++idx)\n        {\n            if (std::fabs(expected[idx]) < 1e-10)\n            {\n                BOOST_CHECK_SMALL(spectrum[idx], 1e-8);\n            }\n            else\n            {\n                BOOST_CHECK_CLOSE(expected[idx], spectrum[idx], .1);\n            }\n        }\n    }\n\n    template <OTFFT::OptimizationType OPT_TYPE>\n    void testDCT(const std::size_t SIZE)\n    {\n        std::random_device rnd_device;\n        std::mt19937 mersenne_engine(rnd_device());\n        std::uniform_real_distribution<double> dist(-99.0, 99.0);\n        auto gen = std::bind(dist, mersenne_engine);\n\n        std::vector<double> expected;\n\n        for (auto n = 0; n < SIZE; ++n)\n        {\n            expected.emplace_back(gen());\n        }\n\n        std::vector<double> spectrum = expected;\n\n        auto fft = OTFFT::Factory::createDCT(static_cast<int>(SIZE), OPT_TYPE);\n        {\n            OTFFT::double_vector spectrum_pointer{spectrum.data()};\n            fft->fwd0(spectrum_pointer);\n            fft->invn(spectrum_pointer);\n        }\n\n        for (std::size_t idx{0}; idx < SIZE / 2; ++idx)\n        {\n            if (std::fabs(expected[idx]) < 1e-10)\n            {\n                BOOST_CHECK_SMALL(spectrum[idx], 1e-8);\n            }\n            else\n            {\n                BOOST_CHECK_CLOSE(expected[idx], spectrum[idx], .1);\n            }\n        }\n    }\n}\n\nBOOST_AUTO_TEST_SUITE(otfft_optimization_test)\n\nBOOST_AUTO_TEST_CASE(TestBluestein)\n{\n    const std::vector<std::size_t> N{\n      8, 13, 27, 32, 172, 347, 512, 3247, 4096, 12312, 16384,\n      32411, 32768, 53743, 65536, 83476, 131072, 234643, 262144,\n      463272, 524288\n    };\n#ifdef OTFFT_WITH_SSE2\n    for (auto n : N)\n    {\n        testComplexFFT<OTFFT::TransformationType::TRANSFORM_BLUESTEIN, OTFFT::OptimizationType::OPTIMIZED_FFT_SSE2>(n);\n    }\n#endif\n#ifdef OTFFT_WITH_AVX\n    for (auto n : N)\n    {\n        testComplexFFT<OTFFT::TransformationType::TRANSFORM_BLUESTEIN, OTFFT::OptimizationType::OPTIMIZED_FFT_AVX>(n);\n    }\n#endif\n#ifdef OTFFT_WITH_AVX2\n    for (auto n : N)\n    {\n        testComplexFFT<OTFFT::TransformationType::TRANSFORM_BLUESTEIN, OTFFT::OptimizationType::OPTIMIZED_FFT_AVX2>(n);\n    }\n#endif\n}\n\nBOOST_AUTO_TEST_CASE(TestComplex)\n{\n    const std::vector<std::size_t> N{\n      8, 13, 27, 32, 172, 347, 512, 3247, 4096, 12312, 16384,\n      32411, 32768, 53743, 65536, 83476, 131072, 234643, 262144,\n      463272, 524288\n    };\n#ifdef OTFFT_WITH_SSE2\n    for (auto n : N)\n    {\n        testComplexFFT<OTFFT::TransformationType::TRANSFORM_FFT_COMPLEX, OTFFT::OptimizationType::OPTIMIZED_FFT_SSE2>(n);\n    }\n#endif\n#ifdef OTFFT_WITH_AVX\n    for (auto n : N)\n    {\n        testComplexFFT<OTFFT::TransformationType::TRANSFORM_FFT_COMPLEX, OTFFT::OptimizationType::OPTIMIZED_FFT_AVX>(n);\n    }\n#endif\n#ifdef OTFFT_WITH_AVX2\n    for (auto n : N)\n    {\n        testComplexFFT<OTFFT::TransformationType::TRANSFORM_FFT_COMPLEX, OTFFT::OptimizationType::OPTIMIZED_FFT_AVX2>(n);\n    }\n#endif\n}\n\nBOOST_AUTO_TEST_CASE(TestReal)\n{\n    const std::vector<std::size_t> N{\n      8, 32, 512, 4096, 16384, 32768, 65536, 131072,\n      262144, 463272, 524288\n    };\n#ifdef OTFFT_WITH_SSE2\n    for (auto n : N)\n    {\n        testRealFFT<OTFFT::OptimizationType::OPTIMIZED_FFT_SSE2>(n);\n    }\n#endif\n#ifdef OTFFT_WITH_AVX\n    for (auto n : N)\n    {\n        testRealFFT<OTFFT::OptimizationType::OPTIMIZED_FFT_AVX>(n);\n    }\n#endif\n#ifdef OTFFT_WITH_AVX2\n    for (auto n : N)\n    {\n        testRealFFT<OTFFT::OptimizationType::OPTIMIZED_FFT_AVX2>(n);\n    }\n#endif\n}\n\nBOOST_AUTO_TEST_CASE(TestDCT)\n{\n    const std::vector<std::size_t> N{\n      8, 32, 512, 4096, 16384, 32768, 65536, 131072,\n      262144, 463272, 524288\n    };\n#ifdef OTFFT_WITH_SSE2\n    for (auto n : N)\n    {\n        testDCT<OTFFT::OptimizationType::OPTIMIZED_FFT_SSE2>(n);\n    }\n#endif\n#ifdef OTFFT_WITH_AVX\n    for (auto n : N)\n    {\n        testDCT<OTFFT::OptimizationType::OPTIMIZED_FFT_AVX>(n);\n    }\n#endif\n#ifdef OTFFT_WITH_AVX2\n    for (auto n : N)\n    {\n        testDCT<OTFFT::OptimizationType::OPTIMIZED_FFT_AVX2>(n);\n    }\n#endif\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "a1c6b5fce2c5caa44d78d727a589f0c022a65a1d", "size": 6924, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/otfft_optimization_test.cpp", "max_stars_repo_name": "24icewolf42/otfft", "max_stars_repo_head_hexsha": "6069f7017043af06f556a275662a465a56111c42", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2018-10-24T22:46:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-04T00:57:59.000Z", "max_issues_repo_path": "unit_tests/otfft_optimization_test.cpp", "max_issues_repo_name": "24icewolf42/otfft", "max_issues_repo_head_hexsha": "6069f7017043af06f556a275662a465a56111c42", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-01-16T10:39:16.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-16T15:42:37.000Z", "max_forks_repo_path": "unit_tests/otfft_optimization_test.cpp", "max_forks_repo_name": "24icewolf42/otfft", "max_forks_repo_head_hexsha": "6069f7017043af06f556a275662a465a56111c42", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2018-01-16T15:52:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-02T00:21:50.000Z", "avg_line_length": 27.696, "max_line_length": 121, "alphanum_fraction": 0.5954650491, "num_tokens": 1965, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.45948887065546884}}
{"text": "#include <boost/histogram.hpp>\n#include <iostream>\n#include <sens_loc/analysis/keypoints.h>\n#include <sens_loc/math/rounding.h>\n#include <sens_loc/util/console.h>\n#include <stdexcept>\n\nnamespace sens_loc::analysis {\n\nvoid keypoints::analyze(gsl::span<const cv::KeyPoint> points,\n                        const bool                    distribution,\n                        const bool                    size,\n                        const bool                    response) noexcept {\n    _size_histo.reset();\n    _size.reset();\n    _response_histo.reset();\n    _response_histo.reset();\n    _distribution.reset();\n\n    if (points.empty())\n        return;\n\n    try {\n        std::vector<float> responses;\n        std::vector<float> sizes;\n        std::for_each(points.begin(), points.end(),\n                      [&](const cv::KeyPoint& kp) {\n                          if (size)\n                              sizes.emplace_back(kp.size);\n                          if (response)\n                              responses.emplace_back(kp.response);\n                      });\n        if (size) {\n            std::sort(std::begin(sizes), std::end(sizes));\n            _size = statistic::make(sizes);\n        }\n        if (response) {\n            std::sort(std::begin(responses), std::end(responses));\n            _response = statistic::make(responses);\n        }\n    } catch (const std::exception& e) {\n        std::cerr << sens_loc::util::err{}\n                  << \"Could not create statistics for size and response.\\n\"\n                  << \"Message: \" << e.what() << \"\\n\";\n        return;\n    }\n\n    using namespace boost::histogram;\n\n    // Shortcut if no histogram will be created.\n    if (!distribution && !response && !size)\n        return;\n\n    if (distribution)\n        try {\n            _distribution = make_histogram(\n                axis_t{_dist_width_bins, 0.0F, 1.0F, _dist_w_title},\n                axis_t{_dist_height_bins, 0.0F, 1.0F, _dist_h_title});\n        } catch (const std::invalid_argument& e) {\n            std::cerr << sens_loc::util::err{}\n                      << \"Bad distribution histogram configuration!\\n\"\n                      << \"Message: \" << e.what() << \"\\n\";\n            return;\n        }\n\n    const float delta = 5.0F * std::numeric_limits<float>::epsilon();\n    if (size && _size_histo_enabled) {\n        try {\n            const auto [s_min, s_max] = [&]() -> std::pair<float, float> {\n                if (std::abs(_size.min - _size.max) < 0.0001F)\n                    return {_size.min - 1.0F, _size.max + 1.0F};\n                return {_size.min - delta, _size.max + delta};\n            }();\n            _size_histo =\n                make_histogram(axis_t{_size_bins, s_min, s_max, _size_title});\n        } catch (const std::invalid_argument& e) {\n            std::cerr << sens_loc::util::err{}\n                      << \"Could not create size histogram configuration!\\n\"\n                      << \"Message: \" << e.what() << \"\\n\";\n            return;\n        }\n    }\n\n    if (response && _response_histo_enabled) {\n        try {\n            const float r_min = _response.min - delta;\n            const float r_max = _response.max + delta;\n            _response_histo   = make_histogram(\n                axis_t{_response_bins, r_min, r_max, _response_title});\n        } catch (const std::invalid_argument& e) {\n            std::cerr << sens_loc::util::err{}\n                      << \"Could not create response histogram configuration!\\n\"\n                      << \"Message: \" << e.what() << \"\\n\";\n            return;\n        }\n    }\n\n    try {\n        auto iw = static_cast<float>(_img_width);\n        auto ih = static_cast<float>(_img_height);\n        std::for_each(points.begin(), points.end(),\n                      [&](const cv::KeyPoint& kp) {\n                          if (distribution)\n                              _distribution(kp.pt.x / iw, kp.pt.y / ih);\n                          if (response && _response_histo_enabled)\n                              _response_histo(kp.response);\n                          if (size && _size_histo_enabled)\n                              _size_histo(kp.size);\n                      });\n    } catch (const std::exception& e) {\n        std::cerr << sens_loc::util::err{}\n                  << \"Could not create histograms for size and/or response \"\n                     \"and/or keypoint-distribution.\\n\"\n                  << \"Message: \" << e.what() << \"\\n\";\n        return;\n    }\n}\n\nvoid write(cv::FileStorage& fs, const std::string& name, const keypoints& kp) {\n    fs << name << \"{\";\n    write(fs, \"response\", kp.response());\n    write(fs, \"size\", kp.size());\n    fs << \"}\";\n}\n\n}  // namespace sens_loc::analysis\n", "meta": {"hexsha": "4ae625ac9c434be88c0c070789cec4a43cd6211b", "size": 4683, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/lib/analysis/keypoints.cpp", "max_stars_repo_name": "JonasToth/depth-conversions", "max_stars_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-09-30T07:09:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T09:14:35.000Z", "max_issues_repo_path": "src/lib/analysis/keypoints.cpp", "max_issues_repo_name": "JonasToth/depth-conversions", "max_issues_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/analysis/keypoints.cpp", "max_forks_repo_name": "JonasToth/depth-conversions", "max_forks_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b", "max_forks_repo_licenses": ["BSD-3-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.874015748, "max_line_length": 79, "alphanum_fraction": 0.4926329276, "num_tokens": 1038, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4594888650590204}}
{"text": "#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/connected_components.hpp>\n\n#include <bitset>\n#include <vector>\n#include <array>\n#include <numeric>\n#include <iostream>\n#include <fstream>\n#include <iomanip>\n\nstd::array<uint8_t,256> run_rounds(const std::vector<uint8_t> inputs,\n                                   const size_t &hash_length,\n                                   const size_t &num_rounds)\n{\n  std::array<uint8_t,256> ring;\n  std::iota(ring.begin(), ring.end(), 0);\n\n  size_t skip(0), current(0);\n  for (size_t round=0; round<num_rounds; ++round)\n    {\n      for (auto &input: inputs)\n        {\n          uint8_t start (current + (input-1));\n          uint8_t finish(current);\n\n          const uint8_t stop (input/2);\n          for (uint8_t ix=0; ix != stop; ++ix)\n            {\n              std::swap(ring[start], ring[finish]);\n              --start;\n              ++finish;\n            }\n          current += input + skip;\n          ++skip;\n        }\n    }\n  return ring;\n}\nstd::vector<uint8_t> compute_dense_hash(const size_t &hash_length,\n                                        const std::vector<uint8_t> &inputs)\n{\n  auto inputs_copy(inputs);\n  for (auto &c: {17, 31, 73, 47, 23})\n    { inputs_copy.push_back(c); }\n  auto ring(run_rounds(inputs_copy,hash_length,64));\n\n  std::vector<uint8_t> dense_hash(hash_length/16);\n  for (size_t ix=0; ix<hash_length; ix+=16)\n    { for(size_t jx=0; jx<16; ++jx)\n        { dense_hash[ix/16]^=ring[ix+jx]; } }\n\n  return dense_hash;\n}\n\nint main(int, char *argv[])\n{\n  const size_t hash_length(256);\n\n  size_t total_memory(0);\n  std::vector<std::vector<size_t>> bit_array(128);\n  for(auto &b: bit_array)\n    { b.resize(128,-1); }\n\n  boost::adjacency_list <boost::vecS, boost::vecS, boost::undirectedS> graph;\n  size_t memory_id(0);\n  for (size_t row=0; row<128; ++row)\n    {\n      std::vector<uint8_t> inputs;\n      for (auto &c: argv[1] + (\"-\" + std::to_string(row)))\n        { inputs.push_back(c); }\n\n      auto dense_hash(compute_dense_hash(hash_length,inputs));\n      for (auto &h: dense_hash)\n        { total_memory+=std::bitset<8>(h).count(); }\n\n      for(size_t b=0; b<128/8; ++b)\n        {\n          std::bitset<8> b8(dense_hash[b]);\n          for(size_t c=0; c<8; ++c)\n            {\n              auto is_on (b8[7-c]);\n              if(is_on)\n                {\n                  bit_array[row][b*8 + c]=memory_id;\n                  if(row!=0 && bit_array[row-1][b*8 + c]!=-1)\n                    { add_edge(memory_id, bit_array[row-1][b*8 + c], graph); }\n\n                  if((b!=0 || c!=0) && bit_array[row][b*8 + c-1]!=-1)\n                    { add_edge(memory_id, bit_array[row][b*8 + c-1], graph); }\n                  ++memory_id;\n                }\n            }\n        }\n    }\n  std::cout << \"Part 1: \" << total_memory << \"\\n\";\n\n  std::vector<int> component(boost::num_vertices(graph));\n  std::cout << \"Part 2: \"\n            << connected_components(graph, &component[0])\n            << \"\\n\";\n\n\n}", "meta": {"hexsha": "7775e3a7b3007c2d961e610f1af0e518a4dc7b58", "size": 2978, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Advent_of_Code/2017/Day14/Day14b.cpp", "max_stars_repo_name": "Elzei/show-off", "max_stars_repo_head_hexsha": "fd6c46480160d795a7c1c833a798f3d49eddf144", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Advent_of_Code/2017/Day14/Day14b.cpp", "max_issues_repo_name": "Elzei/show-off", "max_issues_repo_head_hexsha": "fd6c46480160d795a7c1c833a798f3d49eddf144", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Advent_of_Code/2017/Day14/Day14b.cpp", "max_forks_repo_name": "Elzei/show-off", "max_forks_repo_head_hexsha": "fd6c46480160d795a7c1c833a798f3d49eddf144", "max_forks_repo_licenses": ["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.6346153846, "max_line_length": 78, "alphanum_fraction": 0.5295500336, "num_tokens": 837, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.795658090372256, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4594888594625716}}
{"text": "// Copyright (c) 2016\n// Author: Chrono Law\n#include <forward_list>\n\n#include <std.hpp>\nusing namespace std;\n\n#include <boost/concept_check.hpp>\nusing namespace boost;\n\n///////////////////////////////////////\n\n//template<typename T>\n//T my_min(const T& l,const T& r)\n//{\n//    BOOST_CONCEPT_ASSERT((LessThanComparable<T>));\n//    //BOOST_CONCEPT_ASSERT((SGIAssignable<T>));\n//\n//    return (l < r) ? l : r;\n//}\n\n#include <boost/concept/requires.hpp>\n\ntemplate<typename T>\nBOOST_CONCEPT_REQUIRES(\n((LessThanComparable<T>)),\n (T)                       )\nmy_min(const T& l,const T& r)\n{\n    return (l < r) ? l : r;\n}\n\n//template <typename I>\n//BOOST_CONCEPT_REQUIRES(\n//((Mutable_RandomAccessIterator<I>))\n//((LessThanComparable<typename RandomAccessIterator<I>::value_type>)),\n//(void)                     )\n//_sort(I first, I last)\n//{\n//    std::stable_sort(first, last);\n//}\n\n///////////////////////////////////////\n\nvoid case1()\n{\n    //complex<double> cp1, cp2;\n    //my_min(cp1, cp2);\n\n}\n\n///////////////////////////////////////\n\nvoid case2()\n{\n    BOOST_CONCEPT_ASSERT((UnaryFunction< negate<int>, int, int>));\n    BOOST_CONCEPT_ASSERT((AdaptableUnaryFunction< negate<int>, int, int>));\n    BOOST_CONCEPT_ASSERT((BinaryFunction< plus<int>,int, int, int>));\n\n}\n\n///////////////////////////////////////\n\ntemplate <typename I> \nvoid _sort(I first, I last)\n{\n    BOOST_CONCEPT_ASSERT((RandomAccessIterator<I>));\n    std::stable_sort(first, last);\n}\n\nvoid case3()\n{\n    BOOST_CONCEPT_ASSERT((InputIterator<int*>));\n    BOOST_CONCEPT_ASSERT((OutputIterator<int*, int>));\n    BOOST_CONCEPT_ASSERT((RandomAccessIterator<int*>));\n\n    assert((std::is_same<InputIterator<int*>::pointer,\n                iterator_traits<int*>::pointer>::value));\n\n    BOOST_CONCEPT_ASSERT((ForwardIterator<forward_list<int>::iterator>));\n    BOOST_CONCEPT_ASSERT((Mutable_ForwardIterator<\n                forward_list<int>::iterator>));\n\n    typedef vector<int>::iterator I;\n    BOOST_CONCEPT_ASSERT((BidirectionalIterator<I>));\n    BOOST_CONCEPT_ASSERT((RandomAccessIterator<I>));\n\n}\n\n///////////////////////////////////////\n\n#include <boost/iterator/iterator_concepts.hpp>\n\n#include <boost/iterator/iterator_facade.hpp>\n\n///////////////////////////////////////\n\ntemplate<typename T>\nclass vs_iterator :\n        public boost::iterator_facade<\n        vs_iterator<T>, T,\n        boost::single_pass_traversal_tag>\n{\npublic:\n    typedef boost::iterator_facade<\n        vs_iterator<T>, T,boost::single_pass_traversal_tag> super_type;\n    typedef vs_iterator this_type;\n\n    typedef typename super_type::reference reference;\n    // using typename super_type::reference ;\n\nprivate:\n    std::vector<T> &v;\n    size_t current_pos;\npublic:\n    vs_iterator(vector<T> &_v, size_t pos = 0):\n      v(_v), current_pos(pos)\n    {}\n    vs_iterator(this_type const& other):\n        v(other.v), current_pos(other.current_pos)\n    {}\n    void operator=(this_type const& other)\n    {\n        this->v = other.v;\n        this->current_pos = other.current_pos;\n    }\nprivate:\n    friend class boost::iterator_core_access;\n\n    reference dereference() const\n    {   return v[current_pos]; }\n\n    void increment()\n    {   ++current_pos;  }\n\n    bool equal(this_type const& other) const\n    {   return this->current_pos == other.current_pos;}\n};\n\nvoid case4()\n{\n    using namespace boost_concepts;\n\n    typedef vector<bool>::iterator I;\n\n    BOOST_CONCEPT_ASSERT((ReadableIterator<I>));\n    BOOST_CONCEPT_ASSERT((WritableIterator<I>));\n    BOOST_CONCEPT_ASSERT((SwappableIteratorConcept<I>));\n    BOOST_CONCEPT_ASSERT((RandomAccessTraversalConcept<I>));\n\n    BOOST_CONCEPT_ASSERT((ReadableIterator<vs_iterator<int> >));\n    BOOST_CONCEPT_ASSERT((WritableIterator<vs_iterator<int> >));\n    BOOST_CONCEPT_ASSERT((SwappableIterator<vs_iterator<int>>));\n    BOOST_CONCEPT_ASSERT((SinglePassIterator<vs_iterator<int> >));\n\n    //BOOST_CONCEPT_ASSERT((LvalueIteratorConcept<I>));\n\n}\n\n///////////////////////////////////////\n\n#include <boost/array.hpp>\n#include <boost/circular_buffer.hpp>\n\nvoid case5()\n{\n    BOOST_CONCEPT_ASSERT((Container<vector<int>>));\n    BOOST_CONCEPT_ASSERT((RandomAccessContainer<vector<int>>));\n\n    assert((std::is_same<vector<int>::value_type,\n                Container<vector<int>>::value_type>::value));\n\n    //BOOST_CONCEPT_ASSERT((Container<forward_list<int>>));\n    //BOOST_CONCEPT_ASSERT((ForwardContainer<forward_list<int>>));\n\n    //BOOST_CONCEPT_ASSERT((ReversibleContainer<forward_list<int>>));\n\n    BOOST_CONCEPT_ASSERT((Container<boost::circular_buffer<int> >));\n\n    //BOOST_CONCEPT_ASSERT((Container<boost::array<int> >));\n\n    BOOST_CONCEPT_ASSERT((Sequence<vector<int>>));\n    BOOST_CONCEPT_ASSERT((Sequence<deque<int>>));\n    BOOST_CONCEPT_ASSERT((Sequence<list<int>>));\n\n    BOOST_CONCEPT_ASSERT((FrontInsertionSequence<deque<int>>));\n    BOOST_CONCEPT_ASSERT((BackInsertionSequence<list<int>>));\n\n    BOOST_CONCEPT_ASSERT((AssociativeContainer<set<int>>));\n    BOOST_CONCEPT_ASSERT((AssociativeContainer<map<int,int>>));\n    BOOST_CONCEPT_ASSERT((MultipleAssociativeContainer<multimap<int,int>>));\n\n    BOOST_CONCEPT_ASSERT((SimpleAssociativeContainer<set<int>>));\n    BOOST_CONCEPT_ASSERT((SortedAssociativeContainer<set<int>>));\n\n}\n\n///////////////////////////////////////\n\n#include <boost/range/concepts.hpp>\n\nvoid case6()\n{\n    BOOST_CONCEPT_ASSERT((SinglePassRangeConcept<std::forward_list<int>>));\n    BOOST_CONCEPT_ASSERT((ForwardRangeConcept<std::forward_list<int>>));\n\n    BOOST_CONCEPT_ASSERT((BidirectionalRangeConcept<std::list<int>>));\n    BOOST_CONCEPT_ASSERT((RandomAccessRangeConcept<std::vector<int>>));\n\n    char a[] = \"range\";\n    BOOST_CONCEPT_ASSERT((RandomAccessRangeConcept<decltype(a)>));\n\n}\n\n///////////////////////////////////////\n#include <boost/concept_archetype.hpp>\n\nvoid case7()\n{\n    typedef null_archetype<> T;\n    typedef assignable_archetype<T> at;\n    typedef copy_constructible_archetype<at> cat;\n    //typedef sgi_assignable_archetype<T> at;\n    typedef less_than_comparable_archetype<cat> vt;\n\n    boost::detail::dummy_constructor dummy_cons;\n    vt v1(dummy_cons), v2(dummy_cons);\n\n    my_min(v1, v2);\n\n    typedef mutable_random_access_iterator_archetype<vt> rt;\n    rt begin, end;\n    _sort(begin, end);\n\n}\n\n///////////////////////////////////////\n\n#include <boost/iterator/iterator_archetypes.hpp>\n\nvoid case8()\n{\n    using namespace boost_concepts;\n    typedef copy_constructible_archetype<assignable_archetype<>> T;\n    //typedef sgi_assignable_archetype<> T;\n\n    typedef input_iterator_archetype<T > I;\n\n    BOOST_CONCEPT_ASSERT((ReadableIterator<I>));\n    BOOST_CONCEPT_ASSERT((SinglePassIterator<I>));\n    BOOST_CONCEPT_ASSERT((InputIterator<I>));\n\n    typedef boost::iterator_archetype<T,\n            boost::iterator_archetypes::readable_iterator_t,\n            boost::single_pass_traversal_tag > II;\n\n    BOOST_CONCEPT_ASSERT((ReadableIterator<II>));\n    BOOST_CONCEPT_ASSERT((SinglePassIterator<II>));\n    BOOST_CONCEPT_ASSERT((InputIterator<II>));\n\n}\n\n///////////////////////////////////////\n\nint main()\n{\n    std::cout << \"hello concept_check\" << std::endl;\n\n    case1();\n    case2();\n    case3();\n    case4();\n    case5();\n    case6();\n    case7();\n    case8();\n}\n", "meta": {"hexsha": "881b8245fec8d4432206609c037a2d0c11453db1", "size": 7212, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "generic/concept_check.cpp", "max_stars_repo_name": "MaxHonggg/professional_boost", "max_stars_repo_head_hexsha": "6fff73d3b9832644068dc8fe0443be813c7237b4", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 47.0, "max_stars_repo_stars_event_min_datetime": "2016-05-20T08:49:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-03T01:17:07.000Z", "max_issues_repo_path": "generic/concept_check.cpp", "max_issues_repo_name": "MaxHonggg/professional_boost", "max_issues_repo_head_hexsha": "6fff73d3b9832644068dc8fe0443be813c7237b4", "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": "generic/concept_check.cpp", "max_forks_repo_name": "MaxHonggg/professional_boost", "max_forks_repo_head_hexsha": "6fff73d3b9832644068dc8fe0443be813c7237b4", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 37.0, "max_forks_repo_forks_event_min_datetime": "2016-07-25T04:52:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T03:55:08.000Z", "avg_line_length": 25.9424460432, "max_line_length": 76, "alphanum_fraction": 0.65640599, "num_tokens": 1661, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011686727232, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.459484971386069}}
{"text": "// Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n// not use this file except in compliance with the License.  You may obtain\n// a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS, 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// cvlm.cc -- A linear model estimator that uses a variety of loss functions.\n//            It sets the regularizer parameters using cross-validation.\n//\n// Mark Johnson, 11th April 2005, last modified 21st Nov 2007\n//\n// This is a version of wlle.cc reworked to use the tao-optimizer.h\n// routines (so most of the Petsc/Tao junk is now moved out of this\n// file).  It also sets regularizer factors by cross-validation.\n// It writes out the weights file after each cross-validation estimation.\n//\n// This optimizier uses the TAO constrained optimization method tao_blmvm\n// to avoid the variable discontinuity at zero if the -cv flag is set.\n//\n// For each variable x[i] in the original problem we introduce a pair of\n// variables xp[i] and xn[i] and a pair of constraints xp[i] >= 0, xn[i] <= 0.\n// Then x[i] = xp[i] + xn[i].\n//\n// The regularized function Q that is optimized is:\n//\n//  Q(xp,xn) = s * ( L(xp+xn) + R(xp,xn) )\n//\n// where s is a user-specified parameter, L is the unregularized loss \n// function and R is the regularizer:\n//\n//  R(xp,xn) = c * sum_i (pow(fabs(xp[i]),p) + pow(fabs(xn[i]),p))\n//\n// where c and p are user-specifier adjustable parameters.  (The fabs()\n// is there just in case the optimization routine temporarily proposes an\n// infeasible solution).\n//\n// Note that\n//\n//  d Q/d xp[i] = s * d L/ d xp[i] + s * c * p * sum_i pow(fabs(xp[i]),p-1) * sign(xp[i])\n//\n// where sign(xp[i]) is +1 if xp[i] is non-negative and -1 otherwise.\n//\n// Change log:\n//\n// 20th April, 2004: the regularizer weights disjunctive features proportial\n// to the number of disjuncts they contain\n//\nconst char usage[] =\n\"cvlm version of 21st November 2007\\n\"\n\"\\n\"\n\"\tA constrained-variable weighted linear model estimator\\n\"\n\"\twith regularizer factors set by cross-validation.\\n\"\n\"\\n\"\n\"cvlm estimates feature weights that estimate the parameters of a\\n\"\n\"linear model by minimizing a regularized loss of the feature\\n\"\n\"weights using the LVLM or BLVLM optimizer from the Petsc/Tao\\n\"\n\"optimization package (see http://www-fp.mcs.anl.gov/tao/ for details).\\n\"\n\"It can deal with partially labeled data (i.e., training instances\\n\"\n\"consist of one or more \\\"winners\\\" and one or more \\\"losers\\\").\\n\"\n\"\\n\"\n\"Usage: cvlm [-help] [-debug debug_level] [-c0 c0] [-c00 c00] [-p p] [-r r] [-s s] [-cv] \\n\"\n\"              [-l ltype] [-Pyx_factor f] [-Px_propto_g] [-max-nrounds maxnrounds] \\n\"\n\"              [-o weights-file]  [-e eval-file] [-x eval-file2]\\n\"\n\"              [-ns ns] [-f feat-file]\\n\"\n\"              tao-options*\\n\"\n\"\t       < train-file\\n\"\n\"\\n\"\n\"where:\\n\"\n\"\\n\"\n\" debug_level > 0 controls the amount of output produced\\n\"\n\"\\n\"\n\" c0 is the initial value for the regularizer constant, and the weight of the regularizer\\n\"\n\" constant for the first feature class is multiplied by c00\\n\"\n\"\\n\"\n\" train-file, eval-file and eval-file2 are files from which training and evaluation\\n\"\n\" data are read (if eval-file ends in the suffix .bz2 then bzcat is used\\n\"\n\" to read it; if no eval-file is specified, then the program tests on the\\n\"\n\" training data),\\n\"\n\"\\n\"\n\" weights-file is a file to which the estimated weights are written,\\n\"\n\"\\n\"\n\" feat-file is a file of <featclass> <featuredetails> lines, used for\\n\"\n\" cross-validating regularizer weights,\\n\"\n\"\\n\"\n\" ns is the number of ':' characters to use to define the cross-validation\\n\"\n\" classes,\\n\" \n\"\\n\"\n\" ltype identifies the type of loss function used:\\n\"\n\"\\n\"\n\"    -l 0 - log loss (c0 ~ 5)\\n\"\n\"    -l 1 - EM-style log loss (c0 ~ 5)\\n\"\n\"    -l 2 - pairwise log loss \\n\"\n\"    -l 3 - exp loss (c0 ~ 25, s ~ 1e-5)\\n\"\n\"    -l 4 - log exp loss (c0 ~ 1e-4)\\n\"\n\"    -l 5 - maximize expected F-score (c ~ ?)\\n\"\n\"\\n\"\n\" ns is the maximum number of ':' characters in a <featclass>, used to\\n\"\n\" determine how features are binned into feature classes (ns = -1 bins\\n\"\n\" all features into the same class)\\n\"\n\"\\n\"\n\" r specifies that the weights are initialized to random values in\\n\"\n\"   [-r ... +r],\\n\"\n\"\\n\"\n\" -Pyx_factor f indicates that a parse should be taken as correct\\n\"\n\"   proportional to f raised to its f-score, and\\n\"\n\"\\n\"\n\" -Px_propto_g indicates that each sentence is weighted by the number of\\n\"\n\"   edges in its gold parse.\\n\"\n\"\\n\"\n\" -max-nrounds maxnrounds specifies that at most maxnrounds of cross-validation\\n\"\n\"   is to be performed.\\n\"\n\"\\n\"\n\"The function that the program minimizes is:\\n\"\n\"\\n\"\n\"   Q(w) = s * (- L(w) + c * sum_j pow(fabs(w[j]), p) ), where:\\n\"\n\"\\n\"\n\"   L(w) is the loss function to be optimized.\\n\"\n\"\\n\"\n\"The -cv option instructs the program to optimize a function defined in\\n\"\n\"terms of vectors of variables u[] and v[], where w[j] = u[j] + v[j]\\n\"\n\"and v[j] <= 0 <= u[j], otherwise it optimizes the w[j] directly.\\n\"\n\"\\n\"\n\"With debug = 0, the program writes a single line to stdout:\\n\"\n\"\\n\"\n\"c p r s it nzeroweights/nweights neglogP/nsentence ncorrect/nsentences\\n\"\n\"\\n\"\n\"With debug >= 10, the program writes out a histogram of weights as well\\n\"\n\"\\n\"\n\"Data format:\\n\"\n\"-----------\\n\"\n\"\\n\"\n\"<Data>     --> [S=<NS>] <Sentence>*\\n\"\n\"<Sentence> --> [G=<G>] N=<N> <Parse>*\\n\"\n\"<Parse>    --> [P=<P>] [W=<W>] <FC>*,\\n\"\n\"<FC>       --> <F>[=<C>]\\n\"\n\"\\n\"\n\"NS is the number of sentences.\\n\"\n\"\\n\"\n\"Each <Sentence> consists of N <Parse>s.  <G> is the gold standard\\n\"\n\"score.  To get parsing precision and recall results, set <G> to the\\n\"\n\"number of edges in the gold standard parse.  To get accuracy results,\\n\"\n\"set <G> to 1 (the default).\\n\"\n\"\\n\"\n\"A <Parse> consists of <FC> pairs.  <P> is the parse's possible highest\\n\"\n\"score and <W> is the parse's actual score.  To get parsing precision and\\n\"\n\"recall results, set <P> to the number of edges in the parse and <W> to\\n\"\n\"the number of edges in common between the gold and parse trees.\\n\"\n\"\\n\"\n\"A <FC> consists of a feature (a non-negative integer) and an optional\\n\"\n\"count (a real).\\n\"\n\"\\n\"\n\"The default for all numbers except <W> is 1.  The default for <W> is 0.\\n\";\n\n#include \"custom_allocator.h\"    // must come first\n#define _GLIBCPP_CONCEPT_CHECKS  // uncomment this for checking\n\n#include <boost/lexical_cast.hpp>\n#include <cassert>\n#include <cctype>\n#include <cerrno>\n#include <cmath>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <iostream>\n#include <vector>\n\n#include \"lmdata.h\"\n#include \"powell.h\"\n#include \"utility.h\"\n#include \"tao-optimizer.h\"\n\ntypedef std::vector<double> doubles;\ntypedef std::vector<size_t> size_ts;\n\nint debug_level = 0;\n\nenum loss_type { log_loss, em_log_loss, em_log_loss_noomp, pairwise_log_loss, exp_loss, log_exp_loss, \n\t\t expected_fscore_loss };\n\nconst char* loss_type_name[] = { \"log_loss\", \"em_log_loss\", \"em_log_loss_noomp\", \"pairwise_log_loss\", \"exp_loss\", \n\t\t\t\t \"log_exp_loss\", \"expected_fscore_loss\" };\n\nvoid print_histogram(int nx, const double x[], int nbins=20) {\n  int nx_nonzero = 0;\n  for (int i = 0; i < nx; ++i)\n    if (x[i] != 0)\n      ++nx_nonzero;\n\n  std::cout << \"#   There are \" << nx_nonzero << \" non-zero values and \" \n\t    << nx-nx_nonzero << \" zero values.\" << std::endl;\n\n  if (nx_nonzero > 0) {\n    std::vector<double> s;\n    s.reserve(nx_nonzero);\n    for (int i = 0; i < nx; ++i)\n      if (x[i] != 0)\n\ts.push_back(x[i]);\n    std::sort(s.begin(), s.end());\n    for (int i = 0; i <= nbins; ++i) {\n      int j = i*(nx_nonzero-1);\n      j /= nbins;\n      std::cout << float(i)/float(nbins) << '\\t' << s[j] << std::endl;\n    }\n  }\n}  // print_histogram()\n\n// f_df() evaluates the statistics of the corpus, and prints the f-score\n//  if required\n//\ndouble f_df(loss_type ltype, corpus_type* corpus, double x[], double df_dx[]) {\n  Float sum_g = 0, sum_p = 0, sum_w = 0, L = 0;\n  \n  switch (ltype) {\n  case log_loss:\n    L = corpus_stats(corpus, &x[0], &df_dx[0], &sum_g, &sum_p, &sum_w);\n    break;\n  case em_log_loss:\n    L = emll_corpus_stats(corpus, &x[0], &df_dx[0], &sum_g, &sum_p, &sum_w);\n    break;\n  case em_log_loss_noomp:\n    L = emll_corpus_stats_noomp(corpus, &x[0], &df_dx[0], &sum_g, &sum_p, &sum_w);\n    break;\n  case pairwise_log_loss:\n    L = pwlog_corpus_stats(corpus, &x[0], &df_dx[0], &sum_g, &sum_p, &sum_w);\n    break;\n  case exp_loss:\n    L = exp_corpus_stats(corpus, &x[0], &df_dx[0], &sum_g, &sum_p, &sum_w);\n    break;\n  case log_exp_loss:\n    L = log_exp_corpus_stats(corpus, &x[0], &df_dx[0], &sum_g, &sum_p, &sum_w);\n    break;\n  case expected_fscore_loss:\n    L = 1 - fscore_corpus_stats(corpus, &x[0], &df_dx[0], &sum_g, &sum_p, &sum_w);\n    for (size_type j = 0; j < corpus->nfeatures; ++j)\n      df_dx[j] = -df_dx[j];\n    break;\n  default:\n    L = 0;\n    std::cerr << \"## Error: unrecognized loss_type loss = \" << int(ltype) \n\t      << std::endl;\n  }\n  \n  if (debug_level >= 1000)\n    std::cerr << \"f score = \" << 2*sum_w/(sum_g+sum_p) << \", \" << std::flush;\n  \n  assert(finite(L));\n  return L;\n}\n\n\n// Unconstrained is for unconstrained optimization\n//\nstruct Unconstrained {\n  const loss_type ltype;\n  corpus_type* corpus;\n  const size_ts& f_c;\t//!< feature -> cross-validation class\n  const doubles& cs;\t//!< cross-validation class -> regularizer factor\n  double p, s;\n  int it;\n  double L, R, Q;\n\n  Unconstrained(loss_type ltype, corpus_type* corpus, const size_ts& f_c, \n\t\tconst doubles& cs, double p, double s) \n    : ltype(ltype), corpus(corpus), f_c(f_c), cs(cs), p(p), s(s), it(0) \n  { \n    assert(f_c.size() == corpus->nfeatures);\n    for (size_type f = 0; f < f_c.size(); ++f)\n      assert(f_c[f] < cs.size());\n  }\n\n  double operator() (int nx, double x[], double df_dx[]) {\n    it++;\n    if (debug_level >= 1000)      \n      std::cerr << \"it = \" << it << \", \" << std::flush;\n\n    L = f_df(ltype, corpus, x, df_dx);\n\n    if (s != 1) {\n      L *= s;\n\n      for (int i = 0; i < nx; ++i) {\n\tassert(finite(df_dx[i]));\n\tdf_dx[i] *= s;\n      }\n    }\n\n    assert(size_t(nx) == corpus->nfeatures);\n    assert(f_c.size() == corpus->nfeatures);\n\n    R = 0;\n    for (int i = 0; i < nx; ++i) \n      R +=  cs[f_c[i]] * pow(fabs(x[i]), p);\n    R *= s;\n\n    Q = L + R;\n    \n    if (debug_level >= 1000)\n      std::cerr << \"Q = \" << Q << \" = L = \" << L << \" + R = \" << R << std::endl;\n\n    assert(finite(Q));\n    \n    double sp = s * p;\n    for (int i = 0; i < nx; ++i) \n      df_dx[i] += sp * cs[f_c[i]] * pow(fabs(x[i]), p-1) \n\t* (x[i] >= 0 ? (x[i] == 0 ? 0 : 1) : -1);\n\n    if (debug_level >= 10000) {\n      std::cerr << \"Histogram of derivatives:\" << std::endl;\n      print_histogram(nx, &df_dx[0]);\n      std::cerr << \"--------------------------\" << std::endl;\n    }\n\n    for (int i = 0; i < nx; ++i)\n      assert(finite(df_dx[i]));\n    return Q;\n  }   // Unconstrained::operator()\n\n};  // Unconstrained{}\n\n\n// Constrained{} for the constrained optimization.\n//\nstruct Constrained {\n  const loss_type ltype;\n  corpus_type* corpus;\n  const size_ts& f_c;\t//!< feature -> cross-validation class\n  const doubles& cs;\t//!< cross-validation class -> regularizer factor\n  double p, s;\n  int it;\n  doubles x, df_dx;\n  double L, R, Q;\n\n  Constrained(loss_type ltype, corpus_type* corpus, const size_ts& f_c, \n\t      const doubles& cs, double p, double s) \n    : ltype(ltype), corpus(corpus), f_c(f_c), cs(cs), p(p), s(s), it(0),\n      x(corpus->nfeatures, 0), df_dx(corpus->nfeatures) { \n    assert(f_c.size() == corpus->nfeatures);\n    for (size_type f = 0; f < f_c.size(); ++f)\n      assert(f_c[f] < cs.size());\n  }\n\n  double operator() (int nx2, double x2[], double df_dx2[]) {\n    it++;\n    if (debug_level >= 1000)      std::cerr << \"it = \" << it << \", \" << std::flush;\n    \n    size_type nx = corpus->nfeatures;\n    assert(nx2 = 2 * nx);\n    assert(x.size() == nx);\n    for (size_type i = 0; i < nx; ++i) {\n      assert(finite(x2[i]));\n      assert(finite(x2[i+nx]));\n      x[i] = x2[i] + x2[i+nx];\n      assert(finite(x[i]));\n    }\n\n    L = f_df(ltype, corpus, &x[0], &df_dx[0]);\n    \n    L *= s;\n\n    for (size_type i = 0; i < nx; ++i) {\n      assert(finite(df_dx[i]));\n      df_dx2[i] = df_dx2[i+nx] = s * df_dx[i];\n    }\n\n    R = 0;\n    for (size_type i = 0; i < nx; ++i)\n      R += cs[f_c[i]] * pow(fabs(x2[i]), p) + pow(fabs(x2[i+nx]), p);\n    R *= s;\n\n    Q = L + R;\n    \n    if (debug_level >= 1000)\n      std::cerr << \"Q = \" << Q << \" = L = \" << L << \" + R = \" << R << std::endl;\n\n    assert(finite(Q));\n    \n    double sp = s * p;\n    for (size_type i = 0; i < nx; ++i) {\n      df_dx2[i] += sp * cs[f_c[i]] * pow(fabs(x2[i]), p-1) * (x2[i] >= 0 ? 1 : -1);\n      df_dx2[i+nx] += sp * cs[f_c[i]] * pow(fabs(x2[i+nx]), p-1) * (x2[i+nx] > 0 ? 1 : -1);\n    }\n\n    if (debug_level >= 10000) {\n      std::cerr << \"Histogram of derivatives:\" << std::endl;\n      print_histogram(nx, &df_dx[0]);\n      std::cerr << \"--------------------------\" << std::endl;\n    }\n\n    for (int i = 0; i < nx2; ++i)\n      assert(finite(df_dx2[i]));\n    return Q;\n  }   // Constrained::operator()\n\n};  // Constrained{}\n\n\n// The Estimator1 does one round of estimation\n//\nstruct Estimator1 {\n  typedef std::vector<size_t> size_ts;\n  typedef std::vector<double> doubles;\n  \n  corpus_type* train;\t//!< training data\n  size_type nx;\t\t//!< number of features\n  corpus_type* eval;\t//!< evaluation data\n  corpus_type* eval2;\t//!< 2nd evaluation data\n  loss_type ltype;\t//!< type of loss function\n  double c0;\t\t//!< default regularizer factor\n  double c00;           //!< multiply default regularizer factor for first feature class\n  double p;\t\t//!< regularizer power\n  double r;\t\t//!< random initialization\n  double s;\t\t//!< scale factor\n  bool cv;\t\t//!< use constrained variables\n  bool opt_fscore;\t//!< optimize f-score or - log likelihood\n\n  doubles x;\t\t//!< feature -> weight\n  size_ts f_c;\t\t//!< feature -> cross-validation class\n  doubles lcs;\t\t//!< cross-validation class -> log factor\n  size_type nc;\t\t//!< number of cross-validation classes\n\n  size_type nits;\t//!< number of iterations of last round\n  size_type sum_nits;\t//!< total number of iterations\n  size_type nrounds;\t//!< number of cross-validation rounds so far\n  size_type max_nrounds; //!< number of cross-validation rounds to perform\n  double best_score;    //!< best score seen so far\n  std::string weightsfile; //!< name of weights file\n\n  typedef std::map<std::string,size_t> S_C;\n  S_C identifier_regclass; //!< map from feature class identifiers to regularization class\n  typedef std::vector<std::string> Ss;\n  Ss regclass_identifiers; //!< vector of class identifiers\n\n  Estimator1(loss_type ltype, double c0, double c00, double p, double r, double s, bool cv, \n\t     bool opt_fscore = true, size_type max_nrounds = 0, const char* weightsfile = NULL) \n    : train(NULL), nx(0), eval(NULL), eval2(NULL),\n      ltype(ltype), c0(c0), c00(c00), p(p), r(r), s(s), cv(cv), \n      opt_fscore(opt_fscore), x(nx), f_c(nx), lcs(1, log(c0)), nc(1), \n      nits(0), sum_nits(0), nrounds(0), max_nrounds(max_nrounds), best_score(0),\n      weightsfile(weightsfile == NULL ? \"\" : weightsfile)\n  { }  // Estimator1::Estimator1()\n\n  //! set_data() sets the training and evaluation data\n  //\n  void set_data(corpus_type* t, corpus_type* e, corpus_type* e2) {\n    train = t;\n    eval = e;\n    eval2 = e2;\n    nx = train->nfeatures;\n    x.resize(nx);\n    assert(f_c.size() <= nx);\n    assert(eval == NULL || eval->nfeatures <= train->nfeatures);\n    assert(eval2 == NULL || eval2->nfeatures <= train->nfeatures);\n  } // Estimator1::set_data()\n\n  // operator() actually runs one round of estimation\n  //\n  double operator() (const doubles& lccs) {\n    assert(lccs.size() == nc);\n    doubles ccs(nc);\n    double L, R, Q;\n\n    for (size_type i = 0; i < nc; ++i)\n      ccs[i] = exp(lccs[i]);\n\n    assert(x.size() == nx);\n    nits = 0;\n    nrounds++;\n\n    if (debug_level >= 10) {\n      if (nrounds == 1) \n\tstd::cerr << \"# round\tnfeval\tL\tR\tQ\tneglogP\tf-score\tcss\" << std::endl;\n      std::cerr << nrounds << std::flush;\n    }\n    if (cv) {\n\n      // Constrained variable optimization\n\n      Constrained fn(ltype, train, f_c, ccs, p, s);\n      tao_constrained_optimizer<Constrained> tao_opt(2*nx, fn);\n\n      if (r != 0) \n\tfor (size_type i = 0; i < 2*nx; ++i)\n\t  tao_opt[i] = r*double(random()-RAND_MAX/2)/double(RAND_MAX/2);\n    \n      for (size_type i = 0; i < nx; ++i) {\n\ttao_opt.lower_bound[i] = 0;\n\ttao_opt.lower_bound[i+nx] = TAO_NINFINITY;\n\ttao_opt.upper_bound[i] = TAO_INFINITY;\n\ttao_opt.upper_bound[i+nx] = 0;\n      }\n      \n      tao_opt.optimize();\n    \n      nits = fn.it;\n      L = fn.L;\n      R = fn.R;\n      Q = fn.Q;\n\n      for (size_type i = 0; i < nx; ++i)\n\tx[i] = tao_opt[i] + tao_opt[i+nx];\n    }\n    else {\n      \n      // Unconstrained optimization\n      \n      Unconstrained fn(ltype, train, f_c, ccs, p, s);\n      tao_optimizer<Unconstrained> tao_opt(nx, fn);\n\n      if (r != 0) \n\tfor (size_type i = 0; i < nx; ++i)\n\t  tao_opt[i] = r*double(random()-RAND_MAX/2)/double(RAND_MAX/2);\n      \n      tao_opt.optimize();\n      \n      nits = fn.it;\n      L = fn.L;\n      R = fn.R;\n      Q = fn.Q;\n\n      for (size_type i = 0; i < nx; ++i)\n\tx[i] = tao_opt[i];\n    }\n\n    // Clean up, collect stats\n\n    sum_nits += nits;\n\n    if (debug_level >= 10)\n      std::cerr << '\\t' << nits << '\\t' << L << '\\t' << R << '\\t' << Q;\n\n    double score = evaluate(opt_fscore, true);\n\n    if (debug_level >= 10)\n      std::cerr << '\\t' << ccs << std::endl;\n\n    return score;\n\n  }  // Estimator1::operator()\n\n  // evaluate() evaluates the current model on the eval data, prints\n  // out debugging information if appropriate, and returns either\n  // the - log likelihood or 1 - f-score.\n  //\n  double evaluate(bool opt_fscore = false, bool internal = false) {\n\n    std::vector<double> df_dx(nx);\n    Float sum_g = 0, sum_p = 0, sum_w = 0;\n    Float neglogP = corpus_stats(eval, &x[0], &df_dx[0], \n\t\t\t\t &sum_g, &sum_p, &sum_w);\n    Float fscore = 2*sum_w/(sum_g+sum_p);\n    \n    if (internal) {  // internal evaluation, use a short print-out\n      if (debug_level >= 10) {\n\tstd::cerr << '\\t' << neglogP << '\\t' << fscore; \n\tif (eval2 != NULL) {\n\t  Float sum_g2 = 0, sum_p2 = 0, sum_w2 = 0;\n\t  Float neglogP2 = corpus_stats(eval2, &x[0], &df_dx[0], \n\t\t\t\t\t&sum_g2, &sum_p2, &sum_w2);\n\t  Float fscore2 = 2*sum_w2/(sum_g2+sum_p2);\n\t  std::cerr << '\\t' << neglogP2 << '\\t' << fscore2;\n\t}\n      }\n    }\n    else { // final evaluation, print out more info\n    \n      int nzeros = 0;\n      for (size_type i = 0; i < nx; ++i) \n\tif (x[i] == 0)\n\t  ++nzeros;\n  \n      std::cerr << \"# Regularizer power p = \" << p << std::endl;\n      std::cerr << \"# \" << nx-nzeros << \" non-zero feature weights of \" \n\t\t<< nx << \" features.\" << std::endl;\n      std::cerr << \"# Eval neglogP = \" << neglogP \n\t\t<< \", neglogP/nsentences = \" << neglogP/eval->nsentences\n\t\t<< std::endl;\n      std::cerr << \"# Eval precision = \" << sum_w/sum_p \n\t\t<< \", recall = \" << sum_w/sum_g\n\t\t<< \", f-score = \" << 2*sum_w/(sum_g+sum_p)\n\t\t<< std::endl;\n      if (eval2 != NULL) {\n\tFloat sum_g = 0, sum_p = 0, sum_w = 0;\n\tFloat neglogP = corpus_stats(eval2, &x[0], &df_dx[0], \n\t\t\t\t     &sum_g, &sum_p, &sum_w);\n\tstd::cerr << \"# Eval2 neglogP = \" << neglogP \n\t\t  << \", neglogP/nsentences = \" << neglogP/train->nsentences\n\t\t  << std::endl;\n\tstd::cerr << \"# Eval2 precision = \" << sum_w/sum_p \n\t\t  << \", recall = \" << sum_w/sum_g\n\t\t  << \", f-score = \" << 2*sum_w/(sum_g+sum_p)\n\t\t  << std::endl;\n      }\n      {\n\tFloat sum_g = 0, sum_p = 0, sum_w = 0;\n\tFloat neglogP = corpus_stats(train, &x[0], &df_dx[0], \n\t\t\t\t     &sum_g, &sum_p, &sum_w);\n\tstd::cerr << \"# Train neglogP = \" << neglogP \n\t\t  << \", neglogP/nsentences = \" << neglogP/train->nsentences\n\t\t  << std::endl;\n\tstd::cerr << \"# Train precision = \" << sum_w/sum_p \n\t\t  << \", recall = \" << sum_w/sum_g\n\t\t  << \", f-score = \" << 2*sum_w/(sum_g+sum_p)\n\t\t  << std::endl;\n      }\n\n      std::cerr << \"# regclass_identifiers = \" << regclass_identifiers << std::endl;\n      std::cerr << \"# lcs = \" << lcs << std::endl;\n      {\n\tdoubles cs(nc);\n\tfor (size_type i = 0; i < nc; ++i)\n\t  cs[i] = exp(lcs[i]);\n\tstd::cerr << \"# cs = \" << cs << std::endl;\n      }\n      if (debug_level >= 100) {\n\tstd::cerr << \"# Cumulative distribution of feature weights:\" << std::endl;\n\tprint_histogram(nx, &x[0]);\n      }\n    }\n\n    double score = (opt_fscore ? 1 - fscore : neglogP);\n\n    if (nrounds == 1 || score < best_score) {\n      best_score = score;\n\n      // Write out weights file\n    \n      if (!weightsfile.empty()) {\n\tFILE* out = fopen(weightsfile.c_str(), \"w\");\n\t// fprintf(out, \"%d@\", nx-nzeros);\n\tfor (size_type i = 0; i < x.size(); ++i) \n\t  if (x[i] != 0) {\n\t    fprintf(out, \"%d\", i);\n\t    if (x[i] != 1)\n\t      fprintf(out, \"=%g\", x[i]);\n\t    fprintf(out, \"\\n\");\n\t  }\n\tfclose(out);\n      }      \n    }\n    return score;\n  } // Estimator1::evaluate()\n\n  //! fc_bin() maps a feature count to its corresponding bin\n  //\n  static int fc_bin(double feature_count_base, int feature_count) {\n    if (feature_count <= 4)\n      return feature_count;\n    else\n      return lrint(4.0 + pow(feature_count_base, \n\t\t\t     lrint(log(feature_count-4)/log(feature_count_base))));\n  }  // Estimator1::fc_bin()\n\n  // read_featureclasses() reads the feature classes from a feature file\n  //\n  void read_featureclasses(const char* filename, \n\t\t\t   int nseparators = 1,\n\t\t\t   const char* separators = \":\") {\n    \n    const char* filesuffix = strrchr(filename, '.');\n    bool popen_flag = false;\n    FILE *in;\n    if (strcasecmp(filesuffix, \".bz2\") == 0) {\n      std::string command(\"bzcat \");\n      command += filename;\n      in = popen(command.c_str(), \"r\");\n      if (in == NULL) {\n\tperror(\"## Error in lm-owlqn: \");\n\tstd::cerr << \"## popen(\\\"\" << command << \"\\\", \\\"r\\\") failed, usage = \" << resource_usage() << std::endl;\n      }\n      popen_flag = true;\n    }\n    else if (strcasecmp(filesuffix, \".gz\") == 0) {\n      std::string command(\"gunzip -c \");\n      command += filename;\n      errno = 0;\n      in = popen(command.c_str(), \"r\");\n      if (in == NULL) {\n\tperror(\"## Error in lm-owlqn: \");\n\tstd::cerr << \"## popen(\\\"\" << command << \"\\\", \\\"r\\\") failed, usage = \" << resource_usage() << std::endl;\n      }\n      popen_flag = true;\n    }\n    else\n      in = fopen(filename, \"r\");\n    if (in == NULL) {\n      std::cerr << \"## Couldn't open evalfile \" << filename\n\t\t<< \", errno = \" << errno << \"\\n\" \n\t\t<< usage << std::endl;\n      exit(EXIT_FAILURE);\n    }\n\n    size_type featno;\n\n    // read feature number \n\n    while (fscanf(in, \" %u \", &featno) == 1) {\n      int c = ':';\n      \n      // read the prefix of the feature class identifier\n      \n      std::string identifier;\n      int iseparators = 0;\n      if (nseparators >= 0)\n\twhile ((c = getc(in)) != EOF && !isspace(c)) {\n\t  if (index(separators, c) != NULL)\n\t    if (++iseparators > nseparators)\n\t      break;\n\t  identifier.push_back(c);\n\t}\n      \n      // skip the rest of the line\n\n      while ((c = getc(in)) != EOF && c != '\\n')\n\t;\n\n      // insert the prefix into the prefix -> regularization class map\n      \n      S_C::iterator it \n\t= identifier_regclass.insert(S_C::value_type(identifier, \n\t\t\t\t\t\t     identifier_regclass.size())).first;\n      \n      size_type cl = it->second;    // regularization class\n\n      f_c.resize(featno+1);\n      f_c[featno] = cl;          // set feature's regularization class\n    }\n      \n    nc = identifier_regclass.size();   // set nc\n    lcs.resize(nc, log(c0));           // set each regularizer class' factor to c0\n    lcs[0] += log(c00);                // increment first regularizer class' factor by c00\n\n    // construct regclass_identifiers\n    \n    regclass_identifiers.resize(nc);\n    cforeach (S_C, it, identifier_regclass) {\n      assert(it->second < regclass_identifiers.size());\n      regclass_identifiers[it->second] = it->first;\n    }\n\n    if (debug_level >= 0) \n      std::cerr << \"# Regularization classes: \" << regclass_identifiers << std::endl;\n\n    if (popen_flag)\n      pclose(in);\n    else\n      fclose(in);\n  }  // Estimator1::read_featureclasses() \n    \n  void estimate()\n  {\n    if (max_nrounds == 1) \n      operator()(lcs);\n    else {\n      if(max_nrounds == 0)\n\tmax_nrounds = (lcs.size() > 1) ? 11 : 51;\n      powell::control cntrl(1e-4, 1e-2, 0, max_nrounds);\n      powell::minimize(lcs, *this, log(2), cntrl);\n    }\n\n    if (debug_level > 0) {\n      std::cerr << \"# Regularizer class weights = (\";\n      for (size_type i = 0; i < lcs.size(); ++i) {\n\tif (i > 0)\n\t  std::cerr << ' ';\n\tstd::cerr << exp(lcs[i]);\n      }\n      std::cerr << ')' << std::endl;\n    }\n\n  }  // Estimator1::estimate()\n\n};  // Estimator1{}\n\n\nint main(int argc, char** argv) \n{\n  errno = 0;\n\n  std::ios::sync_with_stdio(false);\n\n  // Initialize TAO and PETSc\n\n  tao_environment tao_env(argc, argv);\n\n  if (tao_env.get_bool_option(\"-help\") || tao_env.get_bool_option(\"--help\")) {\n    std::cerr << \"-help\\n\" << usage << std::endl;\n    exit(EXIT_SUCCESS);\n  }\n\n  debug_level = tao_env.get_int_option(\"-debug\", debug_level);\n  loss_type ltype = loss_type(tao_env.get_int_option(\"-l\", 0));\n  double c0 = tao_env.get_double_option(\"-c0\", 2.0);\n  double c00 = tao_env.get_double_option(\"-c00\", 1.0);\n  double p = tao_env.get_double_option(\"-p\", 2.0);\n  double r = tao_env.get_double_option(\"-r\", 0.0);\n  double s = tao_env.get_double_option(\"-s\", 1.0);\n  bool cv = tao_env.get_bool_option(\"-cv\");\n  double Pyx_factor = tao_env.get_double_option(\"-Pyx_factor\", 0.0);\n  bool Px_propto_g = tao_env.get_bool_option(\"-Px_propto_g\");\n  size_type max_nrounds = tao_env.get_int_option(\"-max-nrounds\", 0);\n\n  if (debug_level >= 10)\n    std::cerr << \"#  ltype = \" << ltype\n\t      << \" (\" << loss_type_name[ltype] << \")\"\n\t      << \", regularization c0 = \" << c0\n\t      << \", c00 = \" << c00\n\t      << \", power p = \" << p \n\t      << \", scale s = \" << s\n\t      << \"; random init r = \" << r \n\t      << \", constrained var optimization cv = \" << cv\n\t      << \", Pyx_factor = \" << Pyx_factor\n\t      << \", Px_propto_g = \" << Px_propto_g\n\t      << \", max_nrounds = \" << max_nrounds\n\t      << std::endl;\n\n  // I discovered a couple of years after I wrote this program that popen\n  // uses fork, which doubles your virtual memory for a short instant!\n\n  Estimator1 e(ltype, c0, c00, p, r, s, cv, true,\n\t       max_nrounds, tao_env.get_cstr_option(\"-o\"));\n\n  int nseparators = tao_env.get_int_option(\"-ns\", 1);\n  const char* filename = tao_env.get_cstr_option(\"-f\");\n  if (filename != NULL)\n    e.read_featureclasses(filename, nseparators, \":\");  \n\n  // Read in eval data first, as that way we may squeeze everything into 4GB\n\n  corpusflags_type corpusflags = { Pyx_factor, Px_propto_g };\n  \n  corpus_type* evaldata = NULL;\n  const char* evalfile = tao_env.get_cstr_option(\"-e\");\n  if (evalfile != NULL) {\n    evaldata = read_corpus_file(&corpusflags, evalfile);\n    if (debug_level >= 10)\n      std::cerr << \"# read evalfile = \" << evalfile \n\t\t<< \", nsentences = \" << evaldata->nsentences\n\t\t<< std::endl;\n  }\n\n  corpus_type* evaldata2 = NULL;\n  const char* evalfile2 = tao_env.get_cstr_option(\"-x\");\n  if (evalfile2 != NULL) {\n    evaldata2 = read_corpus_file(&corpusflags, evalfile2);\n    if (debug_level >= 10)\n      std::cerr << \"# read evalfile2 = \" << evalfile2 \n\t\t<< \", nsentences = \" << evaldata2->nsentences\n\t\t<< std::endl;\n  }\n\n  corpus_type* traindata = read_corpus(&corpusflags, stdin);\n  int nx = traindata->nfeatures;\n\n  if (errno != 0) {\n    perror(\"## cvlm, after reading main corpus, nonzero errno  \");\n    errno = 0;\n  }\n\n  std::cerr << \"# \" << nx << \" features in training data, \" << resource_usage() << std::endl;\n\n  if (evaldata == NULL)\n    evaldata = traindata;\n\n  e.set_data(traindata, evaldata, evaldata2);\n  e.estimate();\n\n}  // main()\n", "meta": {"hexsha": "0443e6476e0e17e49099abe94c99950ee041ac6d", "size": 27938, "ext": "cc", "lang": "C++", "max_stars_repo_path": "scripts/CPI-corpora-preparing/bllip-parser/second-stage/programs/wlle/cvlm.cc", "max_stars_repo_name": "AmmarQaseem/CPI-Pipeline-test", "max_stars_repo_head_hexsha": "3866883c54d7bd77753ee4b72997949bdcf76359", "max_stars_repo_licenses": ["PostgreSQL", "ISC", "Intel"], "max_stars_count": 189.0, "max_stars_repo_stars_event_min_datetime": "2015-01-19T14:22:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-15T21:36:52.000Z", "max_issues_repo_path": "scripts/CPI-corpora-preparing/bllip-parser/second-stage/programs/wlle/cvlm.cc", "max_issues_repo_name": "AmmarQaseem/CPI-Pipeline-test", "max_issues_repo_head_hexsha": "3866883c54d7bd77753ee4b72997949bdcf76359", "max_issues_repo_licenses": ["PostgreSQL", "ISC", "Intel"], "max_issues_count": 48.0, "max_issues_repo_issues_event_min_datetime": "2015-01-20T10:26:00.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-07T19:53:26.000Z", "max_forks_repo_path": "scripts/CPI-corpora-preparing/bllip-parser/second-stage/programs/wlle/cvlm.cc", "max_forks_repo_name": "AmmarQaseem/CPI-Pipeline-test", "max_forks_repo_head_hexsha": "3866883c54d7bd77753ee4b72997949bdcf76359", "max_forks_repo_licenses": ["PostgreSQL", "ISC", "Intel"], "max_forks_count": 55.0, "max_forks_repo_forks_event_min_datetime": "2015-01-31T17:32:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T09:17:44.000Z", "avg_line_length": 31.9291428571, "max_line_length": 114, "alphanum_fraction": 0.5927768631, "num_tokens": 8786, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370421, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4594849629629764}}
{"text": "/**\n * @file AdaBoost_test.cpp\n * @author Udit Saxena\n *\n * Tests for AdaBoost class.\n */\n\n#include <mlpack/core.hpp>\n#include <mlpack/methods/adaboost/adaboost.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"old_boost_test_definitions.hpp\"\n\nusing namespace mlpack;\nusing namespace arma;\nusing namespace mlpack::adaboost;\n\nBOOST_AUTO_TEST_SUITE(AdaBoostTest);\n\n/**\n *  This test case runs the AdaBoost.mh algorithm on the UCI Iris dataset.\n *  It checks whether the hamming loss breaches the upperbound, which\n *  is provided by ztAccumulator.\n */\nBOOST_AUTO_TEST_CASE(HammingLossBoundIris)\n{\n  arma::mat inputData;\n\n  if (!data::Load(\"iris.txt\", inputData))\n    BOOST_FAIL(\"Cannot load test dataset iris.txt!\");\n\n  arma::Mat<size_t> labels;\n\n  if (!data::Load(\"iris_labels.txt\",labels))\n    BOOST_FAIL(\"Cannot load labels for iris iris_labels.txt\");\n\n  // no need to map the labels here\n\n  // Define your own weak learner, perceptron in this case.\n  // Run the perceptron for perceptron_iter iterations.\n  int perceptronIter = 400;\n\n  perceptron::Perceptron<> p(inputData, labels.row(0), max(labels.row(0)) + 1,\n      perceptronIter);\n\n  // Define parameters for the adaboost\n  int iterations = 100;\n  double tolerance = 1e-10;\n  AdaBoost<> a(inputData, labels.row(0), iterations, tolerance, p);\n\n  int countError = 0;\n  for (size_t i = 0; i < labels.n_cols; i++)\n    if(labels(i) != a.finalHypothesis(i))\n      countError++;\n  double hammingLoss = (double) countError / labels.n_cols;\n\n  double ztP = a.GetztProduct();\n  BOOST_REQUIRE(hammingLoss <= ztP);\n}\n\n/**\n *  This test case runs the AdaBoost.mh algorithm on the UCI Iris dataset.\n *  It checks if the error returned by running a single instance of the\n *  weak learner is worse than running the boosted weak learner using\n *  adaboost.\n */\nBOOST_AUTO_TEST_CASE(WeakLearnerErrorIris)\n{\n  arma::mat inputData;\n\n  if (!data::Load(\"iris.txt\", inputData))\n    BOOST_FAIL(\"Cannot load test dataset iris.txt!\");\n\n  arma::Mat<size_t> labels;\n\n  if (!data::Load(\"iris_labels.txt\",labels))\n    BOOST_FAIL(\"Cannot load labels for iris iris_labels.txt\");\n\n  // no need to map the labels here\n\n  // Define your own weak learner, perceptron in this case.\n  // Run the perceptron for perceptron_iter iterations.\n  int perceptronIter = 400;\n\n  arma::Row<size_t> perceptronPrediction(labels.n_cols);\n  perceptron::Perceptron<> p(inputData, labels.row(0), max(labels.row(0)) + 1,\n      perceptronIter);\n  p.Classify(inputData, perceptronPrediction);\n\n  int countWeakLearnerError = 0;\n  for (size_t i = 0; i < labels.n_cols; i++)\n    if(labels(i) != perceptronPrediction(i))\n      countWeakLearnerError++;\n  double weakLearnerErrorRate = (double) countWeakLearnerError / labels.n_cols;\n\n  // Define parameters for the adaboost\n  int iterations = 100;\n  double tolerance = 1e-10;\n  AdaBoost<> a(inputData, labels.row(0), iterations, tolerance, p);\n  int countError = 0;\n  for (size_t i = 0; i < labels.n_cols; i++)\n    if(labels(i) != a.finalHypothesis(i))\n      countError++;\n  double error = (double) countError / labels.n_cols;\n\n  BOOST_REQUIRE(error <= weakLearnerErrorRate);\n}\n\n/**\n *  This test case runs the AdaBoost.mh algorithm on the UCI Vertebral\n *  Column dataset.\n *  It checks whether the hamming loss breaches the upperbound, which\n *  is provided by ztAccumulator.\n */\nBOOST_AUTO_TEST_CASE(HammingLossBoundVertebralColumn)\n{\n  arma::mat inputData;\n\n  if (!data::Load(\"vc2.txt\", inputData))\n    BOOST_FAIL(\"Cannot load test dataset vc2.txt!\");\n\n  arma::Mat<size_t> labels;\n\n  if (!data::Load(\"vc2_labels.txt\",labels))\n    BOOST_FAIL(\"Cannot load labels for vc2_labels.txt\");\n\n  // no need to map the labels here\n\n  // Define your own weak learner, perceptron in this case.\n  // Run the perceptron for perceptron_iter iterations.\n  int perceptronIter = 800;\n\n  perceptron::Perceptron<> p(inputData, labels.row(0), max(labels.row(0)) + 1,\n      perceptronIter);\n\n  // Define parameters for the adaboost\n  int iterations = 50;\n  double tolerance = 1e-10;\n  AdaBoost<> a(inputData, labels.row(0), iterations, tolerance, p);\n  int countError = 0;\n  for (size_t i = 0; i < labels.n_cols; i++)\n    if(labels(i) != a.finalHypothesis(i))\n      countError++;\n  double hammingLoss = (double) countError / labels.n_cols;\n\n  double ztP = a.GetztProduct();\n  BOOST_REQUIRE(hammingLoss <= ztP);\n}\n\n/**\n *  This test case runs the AdaBoost.mh algorithm on the UCI Vertebral\n *  Column dataset.\n *  It checks if the error returned by running a single instance of the\n *  weak learner is worse than running the boosted weak learner using\n *  adaboost.\n */\nBOOST_AUTO_TEST_CASE(WeakLearnerErrorVertebralColumn)\n{\n  arma::mat inputData;\n\n  if (!data::Load(\"vc2.txt\", inputData))\n    BOOST_FAIL(\"Cannot load test dataset vc2.txt!\");\n\n  arma::Mat<size_t> labels;\n\n  if (!data::Load(\"vc2_labels.txt\",labels))\n    BOOST_FAIL(\"Cannot load labels for vc2_labels.txt\");\n\n  // no need to map the labels here\n\n  // Define your own weak learner, perceptron in this case.\n  // Run the perceptron for perceptron_iter iterations.\n  int perceptronIter = 800;\n\n  arma::Row<size_t> perceptronPrediction(labels.n_cols);\n  perceptron::Perceptron<> p(inputData, labels.row(0), max(labels.row(0)) + 1,\n      perceptronIter);\n  p.Classify(inputData, perceptronPrediction);\n\n  int countWeakLearnerError = 0;\n  for (size_t i = 0; i < labels.n_cols; i++)\n    if(labels(i) != perceptronPrediction(i))\n      countWeakLearnerError++;\n  double weakLearnerErrorRate = (double) countWeakLearnerError / labels.n_cols;\n\n  // Define parameters for the adaboost\n  int iterations = 50;\n  double tolerance = 1e-10;\n  AdaBoost<> a(inputData, labels.row(0), iterations, tolerance, p);\n  int countError = 0;\n  for (size_t i = 0; i < labels.n_cols; i++)\n    if(labels(i) != a.finalHypothesis(i))\n      countError++;\n  double error = (double) countError / labels.n_cols;\n\n  BOOST_REQUIRE(error <= weakLearnerErrorRate);\n}\n\n/**\n *  This test case runs the AdaBoost.mh algorithm on non-linearly\n *  separable dataset.\n *  It checks whether the hamming loss breaches the upperbound, which\n *  is provided by ztAccumulator.\n */\nBOOST_AUTO_TEST_CASE(HammingLossBoundNonLinearSepData)\n{\n  arma::mat inputData;\n\n  if (!data::Load(\"train_nonlinsep.txt\", inputData))\n    BOOST_FAIL(\"Cannot load test dataset train_nonlinsep.txt!\");\n\n  arma::Mat<size_t> labels;\n\n\n  if (!data::Load(\"train_labels_nonlinsep.txt\",labels))\n    BOOST_FAIL(\"Cannot load labels for train_labels_nonlinsep.txt\");\n\n  // no need to map the labels here\n\n  // Define your own weak learner, perceptron in this case.\n  // Run the perceptron for perceptron_iter iterations.\n  int perceptronIter = 800;\n\n  perceptron::Perceptron<> p(inputData, labels.row(0), max(labels.row(0)) + 1,\n      perceptronIter);\n\n  // Define parameters for the adaboost\n  int iterations = 50;\n  double tolerance = 1e-10;\n  AdaBoost<> a(inputData, labels.row(0), iterations, tolerance, p);\n  int countError = 0;\n  for (size_t i = 0; i < labels.n_cols; i++)\n    if(labels(i) != a.finalHypothesis(i))\n      countError++;\n  double hammingLoss = (double) countError / labels.n_cols;\n\n  double ztP = a.GetztProduct();\n  BOOST_REQUIRE(hammingLoss <= ztP);\n}\n\n/**\n *  This test case runs the AdaBoost.mh algorithm on a non-linearly\n *  separable dataset.\n *  It checks if the error returned by running a single instance of the\n *  weak learner is worse than running the boosted weak learner using\n *  adaboost.\n */\nBOOST_AUTO_TEST_CASE(WeakLearnerErrorNonLinearSepData)\n{\n  arma::mat inputData;\n\n  if (!data::Load(\"train_nonlinsep.txt\", inputData))\n    BOOST_FAIL(\"Cannot load test dataset train_nonlinsep.txt!\");\n\n  arma::Mat<size_t> labels;\n\n  if (!data::Load(\"train_labels_nonlinsep.txt\",labels))\n    BOOST_FAIL(\"Cannot load labels for train_labels_nonlinsep.txt\");\n\n  // no need to map the labels here\n\n  // Define your own weak learner, perceptron in this case.\n  // Run the perceptron for perceptron_iter iterations.\n  int perceptronIter = 800;\n\n  arma::Row<size_t> perceptronPrediction(labels.n_cols);\n  perceptron::Perceptron<> p(inputData, labels.row(0), max(labels.row(0)) + 1,\n      perceptronIter);\n  p.Classify(inputData, perceptronPrediction);\n\n  int countWeakLearnerError = 0;\n  for (size_t i = 0; i < labels.n_cols; i++)\n    if(labels(i) != perceptronPrediction(i))\n      countWeakLearnerError++;\n  double weakLearnerErrorRate = (double) countWeakLearnerError / labels.n_cols;\n\n  // Define parameters for the adaboost\n  int iterations = 50;\n  double tolerance = 1e-10;\n  AdaBoost<> a(inputData, labels.row(0), iterations, tolerance, p);\n  int countError = 0;\n  for (size_t i = 0; i < labels.n_cols; i++)\n    if(labels(i) != a.finalHypothesis(i))\n      countError++;\n  double error = (double) countError / labels.n_cols;\n\n  BOOST_REQUIRE(error <= weakLearnerErrorRate);\n}\n\n/**\n *  This test case runs the AdaBoost.mh algorithm on the UCI Iris dataset.\n *  It checks whether the hamming loss breaches the upperbound, which\n *  is provided by ztAccumulator.\n *  This is for the weak learner: Decision Stumps.\n */\nBOOST_AUTO_TEST_CASE(HammingLossIris_DS)\n{\n  arma::mat inputData;\n\n  if (!data::Load(\"iris.txt\", inputData))\n    BOOST_FAIL(\"Cannot load test dataset iris.txt!\");\n\n  arma::Mat<size_t> labels;\n\n  if (!data::Load(\"iris_labels.txt\",labels))\n    BOOST_FAIL(\"Cannot load labels for iris_labels.txt\");\n\n  // no need to map the labels here\n\n  // Define your own weak learner, Decision Stumps in this case.\n\n  // Define parameters for the adaboost\n  const size_t numClasses = 3;\n  const size_t inpBucketSize = 6;\n\n  decision_stump::DecisionStump<> ds(inputData, labels.row(0),\n                                     numClasses, inpBucketSize);\n  int iterations = 50;\n  double tolerance = 1e-10;\n\n  AdaBoost<arma::mat, mlpack::decision_stump::DecisionStump<> > a(inputData,\n          labels.row(0), iterations, tolerance, ds);\n  int countError = 0;\n  for (size_t i = 0; i < labels.n_cols; i++)\n    if(labels(i) != a.finalHypothesis(i))\n      countError++;\n  double hammingLoss = (double) countError / labels.n_cols;\n\n  double ztP = a.GetztProduct();\n  BOOST_REQUIRE(hammingLoss <= ztP);\n}\n\n/**\n *  This test case runs the AdaBoost.mh algorithm on a non-linearly\n *  separable dataset.\n *  It checks if the error returned by running a single instance of the\n *  weak learner is worse than running the boosted weak learner using\n *  adaboost.\n *  This is for the weak learner: Decision Stumps.\n */\nBOOST_AUTO_TEST_CASE(WeakLearnerErrorIris_DS)\n{\n  arma::mat inputData;\n\n  if (!data::Load(\"iris.txt\", inputData))\n    BOOST_FAIL(\"Cannot load test dataset iris.txt!\");\n\n  arma::Mat<size_t> labels;\n\n  if (!data::Load(\"iris_labels.txt\",labels))\n    BOOST_FAIL(\"Cannot load labels for iris_labels.txt\");\n\n  // no need to map the labels here\n\n  // Define your own weak learner, Decision Stump in this case.\n\n  const size_t numClasses = 3;\n  const size_t inpBucketSize = 6;\n\n  arma::Row<size_t> dsPrediction(labels.n_cols);\n\n  decision_stump::DecisionStump<> ds(inputData, labels.row(0),\n                                     numClasses, inpBucketSize);\n  ds.Classify(inputData, dsPrediction);\n\n  int countWeakLearnerError = 0;\n  for (size_t i = 0; i < labels.n_cols; i++)\n    if(labels(i) != dsPrediction(i))\n      countWeakLearnerError++;\n  double weakLearnerErrorRate = (double) countWeakLearnerError / labels.n_cols;\n\n  // Define parameters for the adaboost\n  int iterations = 50;\n  double tolerance = 1e-10;\n\n  AdaBoost<arma::mat, mlpack::decision_stump::DecisionStump<> > a(inputData,\n           labels.row(0), iterations, tolerance, ds);\n  int countError = 0;\n  for (size_t i = 0; i < labels.n_cols; i++)\n    if(labels(i) != a.finalHypothesis(i))\n      countError++;\n  double error = (double) countError / labels.n_cols;\n\n  BOOST_REQUIRE(error <= weakLearnerErrorRate);\n}\n/**\n *  This test case runs the AdaBoost.mh algorithm on the UCI Vertebral\n *  Column dataset.\n *  It checks if the error returned by running a single instance of the\n *  weak learner is worse than running the boosted weak learner using\n *  adaboost.\n *  This is for the weak learner: Decision Stumps.\n */\nBOOST_AUTO_TEST_CASE(HammingLossBoundVertebralColumn_DS)\n{\n  arma::mat inputData;\n\n  if (!data::Load(\"vc2.txt\", inputData))\n    BOOST_FAIL(\"Cannot load test dataset vc2.txt!\");\n\n  arma::Mat<size_t> labels;\n\n  if (!data::Load(\"vc2_labels.txt\",labels))\n    BOOST_FAIL(\"Cannot load labels for vc2_labels.txt\");\n\n  // no need to map the labels here\n\n  // Define your own weak learner, Decision Stump in this case.\n\n  // Define parameters for the adaboost\n  const size_t numClasses = 3;\n  const size_t inpBucketSize = 6;\n\n  decision_stump::DecisionStump<> ds(inputData, labels.row(0),\n                                     numClasses, inpBucketSize);\n\n  int iterations = 50;\n  double tolerance = 1e-10;\n\n  AdaBoost<arma::mat, mlpack::decision_stump::DecisionStump<> > a(inputData,\n           labels.row(0), iterations, tolerance, ds);\n  int countError = 0;\n  for (size_t i = 0; i < labels.n_cols; i++)\n    if(labels(i) != a.finalHypothesis(i))\n      countError++;\n  double hammingLoss = (double) countError / labels.n_cols;\n\n  double ztP = a.GetztProduct();\n  BOOST_REQUIRE(hammingLoss <= ztP);\n}\n\n/**\n *  This test case runs the AdaBoost.mh algorithm on the UCI Vertebral\n *  Column dataset.\n *  It checks if the error returned by running a single instance of the\n *  weak learner is worse than running the boosted weak learner using\n *  adaboost.\n *  This is for the weak learner: Decision Stumps.\n */\nBOOST_AUTO_TEST_CASE(WeakLearnerErrorVertebralColumn_DS)\n{\n  arma::mat inputData;\n\n  if (!data::Load(\"vc2.txt\", inputData))\n    BOOST_FAIL(\"Cannot load test dataset vc2.txt!\");\n\n  arma::Mat<size_t> labels;\n\n  if (!data::Load(\"vc2_labels.txt\",labels))\n    BOOST_FAIL(\"Cannot load labels for vc2_labels.txt\");\n\n  // no need to map the labels here\n\n  // Define your own weak learner, Decision Stump in this case.\n\n  const size_t numClasses = 3;\n  const size_t inpBucketSize = 6;\n\n  arma::Row<size_t> dsPrediction(labels.n_cols);\n\n  decision_stump::DecisionStump<> ds(inputData, labels.row(0),\n                                     numClasses, inpBucketSize);\n\n  int countWeakLearnerError = 0;\n  for (size_t i = 0; i < labels.n_cols; i++)\n    if(labels(i) != dsPrediction(i))\n      countWeakLearnerError++;\n  double weakLearnerErrorRate = (double) countWeakLearnerError / labels.n_cols;\n\n  // Define parameters for the adaboost\n  int iterations = 50;\n  double tolerance = 1e-10;\n  AdaBoost<arma::mat, mlpack::decision_stump::DecisionStump<> > a(inputData,\n           labels.row(0), iterations, tolerance, ds);\n  int countError = 0;\n  for (size_t i = 0; i < labels.n_cols; i++)\n    if(labels(i) != a.finalHypothesis(i))\n      countError++;\n  double error = (double) countError / labels.n_cols;\n\n  BOOST_REQUIRE(error <= weakLearnerErrorRate);\n}\n/**\n *  This test case runs the AdaBoost.mh algorithm on non-linearly\n *  separable dataset.\n *  It checks whether the hamming loss breaches the upperbound, which\n *  is provided by ztAccumulator.\n *  This is for the weak learner: Decision Stumps.\n */\nBOOST_AUTO_TEST_CASE(HammingLossBoundNonLinearSepData_DS)\n{\n  arma::mat inputData;\n\n  if (!data::Load(\"train_nonlinsep.txt\", inputData))\n    BOOST_FAIL(\"Cannot load test dataset train_nonlinsep.txt!\");\n\n  arma::Mat<size_t> labels;\n\n  if (!data::Load(\"train_labels_nonlinsep.txt\",labels))\n    BOOST_FAIL(\"Cannot load labels for train_labels_nonlinsep.txt\");\n\n\n  // no need to map the labels here\n\n  // Define your own weak learner, Decision Stump in this case.\n\n  // Define parameters for the adaboost\n  const size_t numClasses = 2;\n  const size_t inpBucketSize = 6;\n\n  decision_stump::DecisionStump<> ds(inputData, labels.row(0),\n                                     numClasses, inpBucketSize);\n\n  int iterations = 50;\n  double tolerance = 1e-10;\n\n  AdaBoost<arma::mat, mlpack::decision_stump::DecisionStump<> > a(inputData,\n           labels.row(0), iterations, tolerance, ds);\n  int countError = 0;\n  for (size_t i = 0; i < labels.n_cols; i++)\n    if(labels(i) != a.finalHypothesis(i))\n      countError++;\n  double hammingLoss = (double) countError / labels.n_cols;\n\n  double ztP = a.GetztProduct();\n  BOOST_REQUIRE(hammingLoss <= ztP);\n}\n\n/**\n *  This test case runs the AdaBoost.mh algorithm on a non-linearly\n *  separable dataset.\n *  It checks if the error returned by running a single instance of the\n *  weak learner is worse than running the boosted weak learner using\n *  adaboost.\n *  This for the weak learner: Decision Stumps.\n */\nBOOST_AUTO_TEST_CASE(WeakLearnerErrorNonLinearSepData_DS)\n{\n  arma::mat inputData;\n\n  if (!data::Load(\"train_nonlinsep.txt\", inputData))\n    BOOST_FAIL(\"Cannot load test dataset train_nonlinsep.txt!\");\n\n  arma::Mat<size_t> labels;\n\n  if (!data::Load(\"train_labels_nonlinsep.txt\",labels))\n    BOOST_FAIL(\"Cannot load labels for train_labels_nonlinsep.txt\");\n\n  // no need to map the labels here\n\n  // Define your own weak learner, Decision Stump in this case.\n\n  const size_t numClasses = 2;\n  const size_t inpBucketSize = 3;\n\n  arma::Row<size_t> dsPrediction(labels.n_cols);\n\n  decision_stump::DecisionStump<> ds(inputData, labels.row(0),\n                                     numClasses, inpBucketSize);\n\n  int countWeakLearnerError = 0;\n  for (size_t i = 0; i < labels.n_cols; i++)\n    if(labels(i) != dsPrediction(i))\n      countWeakLearnerError++;\n  double weakLearnerErrorRate = (double) countWeakLearnerError / labels.n_cols;\n\n  // Define parameters for the adaboost\n  int iterations = 500;\n  double tolerance = 1e-23;\n\n  AdaBoost<arma::mat, mlpack::decision_stump::DecisionStump<> > a(inputData,\n           labels.row(0), iterations, tolerance, ds);\n  int countError = 0;\n  for (size_t i = 0; i < labels.n_cols; i++)\n    if(labels(i) != a.finalHypothesis(i))\n      countError++;\n  double error = (double) countError / labels.n_cols;\n\n  BOOST_REQUIRE(error <= weakLearnerErrorRate);\n}\n\n/**\n *  This test case runs the AdaBoost.mh algorithm on the UCI Vertebral\n *  Column dataset.\n *  It tests the Classify function and checks for a satisfiable error rate.\n */\nBOOST_AUTO_TEST_CASE(ClassifyTest_VERTEBRALCOL)\n{\n  mlpack::math::RandomSeed(std::time(NULL));\n  arma::mat inputData;\n\n  if (!data::Load(\"vc2.txt\", inputData))\n    BOOST_FAIL(\"Cannot load test dataset vc2.txt!\");\n\n  arma::Mat<size_t> labels;\n\n  if (!data::Load(\"vc2_labels.txt\",labels))\n    BOOST_FAIL(\"Cannot load labels for vc2_labels.txt\");\n\n  // no need to map the labels here\n\n  // Define your own weak learner, perceptron in this case.\n  // Run the perceptron for perceptron_iter iterations.\n\n  int perceptronIter = 1000;\n\n  arma::mat testData;\n\n  if (!data::Load(\"vc2_test.txt\", testData))\n    BOOST_FAIL(\"Cannot load test dataset vc2_test.txt!\");\n\n  arma::Mat<size_t> trueTestLabels;\n\n  if (!data::Load(\"vc2_test_labels.txt\",trueTestLabels))\n    BOOST_FAIL(\"Cannot load labels for vc2_test_labels.txt\");\n\n  arma::Row<size_t> perceptronPrediction(labels.n_cols);\n  perceptron::Perceptron<> p(inputData, labels.row(0), max(labels.row(0)) + 1,\n      perceptronIter);\n  p.Classify(inputData, perceptronPrediction);\n\n  // Define parameters for the adaboost\n\n  int iterations = 100;\n  double tolerance = 1e-10;\n  AdaBoost<> a(inputData, labels.row(0), iterations, tolerance, p);\n\n  arma::Row<size_t> predictedLabels(testData.n_cols);\n  a.Classify(testData, predictedLabels);\n\n  int localError = 0;\n\n  for (size_t i = 0; i < trueTestLabels.n_cols; i++)\n    if(trueTestLabels(i) != predictedLabels(i))\n      localError++;\n\n  double lError = (double) localError / trueTestLabels.n_cols;\n\n  BOOST_REQUIRE(lError <= 0.30);\n\n}\n\n/**\n *  This test case runs the AdaBoost.mh algorithm on a non linearly\n *  separable dataset.\n *  It tests the Classify function and checks for a satisfiable error rate.\n */\nBOOST_AUTO_TEST_CASE(ClassifyTest_NONLINSEP)\n{\n  arma::mat inputData;\n\n  if (!data::Load(\"train_nonlinsep.txt\", inputData))\n    BOOST_FAIL(\"Cannot load test dataset train_nonlinsep.txt!\");\n\n  arma::Mat<size_t> labels;\n\n  if (!data::Load(\"train_labels_nonlinsep.txt\",labels))\n    BOOST_FAIL(\"Cannot load labels for train_labels_nonlinsep.txt\");\n\n  // no need to map the labels here\n\n  // Define your own weak learner, perceptron in this case.\n  // Run the perceptron for perceptron_iter iterations.\n\n  const size_t numClasses = 2;\n  const size_t inpBucketSize = 3;\n\n  arma::mat testData;\n\n  if (!data::Load(\"test_nonlinsep.txt\", testData))\n    BOOST_FAIL(\"Cannot load test dataset test_nonlinsep.txt!\");\n\n  arma::Mat<size_t> trueTestLabels;\n\n  if (!data::Load(\"test_labels_nonlinsep.txt\",trueTestLabels))\n    BOOST_FAIL(\"Cannot load labels for test_labels_nonlinsep.txt\");\n\n  arma::Row<size_t> dsPrediction(labels.n_cols);\n\n  decision_stump::DecisionStump<> ds(inputData, labels.row(0),\n                                     numClasses, inpBucketSize);\n\n  // Define parameters for the adaboost\n  int iterations = 50;\n  double tolerance = 1e-10;\n  AdaBoost<arma::mat, mlpack::decision_stump::DecisionStump<> > a(\n           inputData, labels.row(0), iterations, tolerance, ds);\n\n  arma::Row<size_t> predictedLabels(testData.n_cols);\n  a.Classify(testData, predictedLabels);\n\n  int localError = 0;\n  for (size_t i = 0; i < trueTestLabels.n_cols; i++)\n    if(trueTestLabels(i) != predictedLabels(i))\n      localError++;\n\n  double lError = (double) localError / trueTestLabels.n_cols;\n\n  BOOST_REQUIRE(lError <= 0.30);\n}\n\n/**\n *  This test case runs the AdaBoost.mh algorithm on the UCI Iris Dataset.\n *  It trains it on two thirds of the Iris dataset (iris_train.csv),\n *  and tests on the remaining third of the dataset (iris_test.csv).\n *  It tests the Classify function and checks for a satisfiable error rate.\n */\nBOOST_AUTO_TEST_CASE(ClassifyTest_IRIS)\n{\n  arma::mat inputData;\n\n  if (!data::Load(\"iris_train.csv\", inputData))\n    BOOST_FAIL(\"Cannot load test dataset iris_train.csv!\");\n\n  arma::Mat<size_t> labels;\n\n  if (!data::Load(\"iris_train_labels.csv\",labels))\n    BOOST_FAIL(\"Cannot load labels for iris_train_labels.csv\");\n\n  // no need to map the labels here\n\n  // Define your own weak learner, perceptron in this case.\n  // Run the perceptron for perceptron_iter iterations.\n  int perceptronIter = 800;\n\n  perceptron::Perceptron<> p(inputData, labels.row(0), max(labels.row(0)) + 1,\n      perceptronIter);\n\n  // Define parameters for the adaboost\n  int iterations = 50;\n  double tolerance = 1e-10;\n  AdaBoost<> a(inputData, labels.row(0), iterations, tolerance, p);\n\n  arma::mat testData;\n  if (!data::Load(\"iris_test.csv\", inputData))\n    BOOST_FAIL(\"Cannot load test dataset iris_test.csv!\");\n\n  arma::Row<size_t> predictedLabels(testData.n_cols);\n\n  a.Classify(testData, predictedLabels);\n\n  arma::Row<size_t> trueTestLabels;\n  if (!data::Load(\"iris_test_labels.csv\", inputData))\n    BOOST_FAIL(\"Cannot load test dataset iris_test_labels.csv!\");\n\n  int localError = 0;\n  for (size_t i = 0; i < trueTestLabels.n_cols; i++)\n    if(trueTestLabels(i) != predictedLabels(i))\n      localError++;\n  double lError = (double) localError / labels.n_cols;\n\n  BOOST_REQUIRE(lError <= 0.30);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "ef8269cc861c27b1ad13d298c3c8d6112f6bf074", "size": 23140, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/adaboost_test.cpp", "max_stars_repo_name": "vj-ug/Contribution-to-mlpack", "max_stars_repo_head_hexsha": "0ddb5ed463861f459ff2829712bdc59ba9d810b0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/mlpack/tests/adaboost_test.cpp", "max_issues_repo_name": "vj-ug/Contribution-to-mlpack", "max_issues_repo_head_hexsha": "0ddb5ed463861f459ff2829712bdc59ba9d810b0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/tests/adaboost_test.cpp", "max_forks_repo_name": "vj-ug/Contribution-to-mlpack", "max_forks_repo_head_hexsha": "0ddb5ed463861f459ff2829712bdc59ba9d810b0", "max_forks_repo_licenses": ["BSD-3-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.6084656085, "max_line_length": 79, "alphanum_fraction": 0.7012100259, "num_tokens": 6243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4594849570831288}}
{"text": "#pragma once\n#include <algorithm>\n#include <vector>\n#include <cmath>\n#include <Eigen/Dense>\n\n\nusing std::vector;\nusing std::pair;\n// using falkolib::Keypoint;\nusing Eigen::Vector3f;\nusing Eigen::MatrixXf;\n// using isam::Pose2d;\n\n\n/*\nY.T.\nThis class implements a family of pairwise data assoication algorithms. \nCurrently supports:\n- nearest neighbor (NN) matching \n- correspondence graph (CG) matching\n*/\nclass PairwiseMatcher\n{\npublic:\n\tPairwiseMatcher(double& dist_tol_inp);\n\t~PairwiseMatcher();\n\tvoid reset();\n\n\t// nearest neighbor (NN) matching\n\tvoid set_nn_dist_tol(double dist_tol);\n\t// NN matching assumes that pc1 and pc2 are in the same coordinate frame!\n\tbool nn_match(vector<Eigen::Vector3f> pc1, vector<Eigen::Vector3f> pc2);\n\n\t\n\tunsigned get_num_matches();\n\tvoid get_matches(vector<pair<int, int>>& matches);\n\t\n\t// Convert resulting pairwise matches into a partial permutation matrix\n\tvoid get_permutation_matrix(Eigen::MatrixXf& P);\n\nprivate:\n\t// NN matching parameters\n\tdouble nn_dist_tol_ = 0; \n\tvector<pair<int, int>> matches_;\n\tvector<Vector3f> pc1_;\n\tvector<Vector3f> pc2_;\n};", "meta": {"hexsha": "64d841f846ec93530da9e13dd59fe6c453aa845a", "size": 1095, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/clear/PairwiseMatcher.hpp", "max_stars_repo_name": "NamDinhRobotics/clear-fusion", "max_stars_repo_head_hexsha": "bde1af066db655f2c308f7afdf143287e634dca5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-29T10:28:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T10:28:53.000Z", "max_issues_repo_path": "include/clear/PairwiseMatcher.hpp", "max_issues_repo_name": "NamDinhRobotics/clear-fusion", "max_issues_repo_head_hexsha": "bde1af066db655f2c308f7afdf143287e634dca5", "max_issues_repo_licenses": ["MIT"], "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/clear/PairwiseMatcher.hpp", "max_forks_repo_name": "NamDinhRobotics/clear-fusion", "max_forks_repo_head_hexsha": "bde1af066db655f2c308f7afdf143287e634dca5", "max_forks_repo_licenses": ["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.8125, "max_line_length": 74, "alphanum_fraction": 0.7497716895, "num_tokens": 277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4594849570831288}}
{"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// Author: Fran\u00e7ois Faure, INRIA-UJF, (C) 2011\n//\n// Copyright: See COPYING file that comes with this distribution\n#include <SofaEigen2Solver/SVDLinearSolver.h>\n#include <sofa/core/visual/VisualParams.h>\n#include <SofaBaseLinearSolver/FullMatrix.h>\n#include <SofaBaseLinearSolver/SparseMatrix.h>\n#include <SofaBaseLinearSolver/CompressedRowSparseMatrix.h>\n#include <sofa/simulation/MechanicalVisitor.h>\n#include <sofa/helper/system/thread/CTime.h>\n#include <sofa/helper/AdvancedTimer.h>\n#include <sofa/core/ObjectFactory.h>\n#include <iostream>\n#include <Eigen/Dense>\n#include <Eigen/Core>\n\nnamespace sofa\n{\nnamespace component\n{\nnamespace linearsolver\n{\nusing core::VecId;\nusing namespace sofa::defaulttype;\nusing namespace sofa::core::behavior;\nusing namespace sofa::simulation;\n#ifdef DISPLAY_TIME\nusing sofa::helper::system::thread::CTime;\n#endif\n\ntemplate<class TMatrix, class TVector>\nSVDLinearSolver<TMatrix,TVector>::SVDLinearSolver()\n    : f_verbose( initData(&f_verbose,false,\"verbose\",\"Dump system state at each iteration\") )\n    , f_minSingularValue( initData(&f_minSingularValue,(Real)1.0e-6,\"minSingularValue\",\"Thershold under which a singular value is set to 0, for the stabilization of ill-conditioned system.\") )\n    , f_conditionNumber( initData(&f_conditionNumber,(Real)0.0,\"conditionNumber\",\"Condition number of the matrix: ratio between the largest and smallest singular values. Computed in method solve.\") )\n{\n#ifdef DISPLAY_TIME\n    timeStamp = 1.0 / (double)CTime::getRefTicksPerSec();\n#endif\n}\n\n\n/// Solve Mx=b\ntemplate<class TMatrix, class TVector>\nvoid SVDLinearSolver<TMatrix,TVector>::solve(Matrix& M, Vector& x, Vector& b)\n{\n#ifdef SOFA_DUMP_VISITOR_INFO\n    simulation::Visitor::printComment(\"SVD\");\n#endif\n#ifdef DISPLAY_TIME\n    CTime timer;\n    double time1 = (double) timer.getTime();\n#endif\n    const bool printLog = this->f_printLog.getValue();\n    const bool verbose  = f_verbose.getValue();\n\n    /// Convert the matrix and the right-hand vector to Eigen objects\n    Eigen::MatrixXd m(M.rowSize(),M.colSize());\n    Eigen::VectorXd rhs(M.rowSize());\n    for(unsigned i=0; i<(unsigned)M.rowSize(); i++ )\n    {\n        for( unsigned j=0; j<(unsigned)M.colSize(); j++ )\n            m(i,j) = M[i][j];\n        rhs(i) = b[i];\n    }\n    if(verbose)\n    {\n        serr << \"SVDLinearSolver<TMatrix,TVector>::solve, Here is the matrix m:\" << sendl << m << sendl;\n    }\n\n    /// Compute the SVD decomposition and the condition number\n    Eigen::JacobiSVD<Eigen::MatrixXd> svd(m, Eigen::ComputeThinU | Eigen::ComputeThinV);\n    f_conditionNumber.setValue( (Real)(svd.singularValues()(0) / svd.singularValues()(M.rowSize()-1)) );\n    if(printLog)\n    {\n        serr << \"SVDLinearSolver<TMatrix,TVector>::solve, the singular values are:\" << sendl << svd.singularValues() << sendl;\n    }\n    if(verbose)\n    {\n        serr << \"Its left singular vectors are the columns of the thin U matrix:\" << sendl << svd.matrixU() << sendl;\n        serr << \"Its right singular vectors are the columns of the thin V matrix:\" << sendl << svd.matrixV() << sendl;\n    }\n\n    /// Solve the equation system and copy the solution to the SOFA vector\n//    Eigen::VectorXd solution = svd.solve(rhs);\n//    for(unsigned i=0; i<M.rowSize(); i++ ){\n//        x[i] = solution(i);\n//    }\n    Eigen::VectorXd Ut_b = svd.matrixU().transpose() *  rhs;\n    Eigen::VectorXd S_Ut_b(M.colSize());\n    for( unsigned i=0; i<(unsigned)M.colSize(); i++ )   /// product with the diagonal matrix, using the threshold for near-null values\n    {\n        if( svd.singularValues()[i] > f_minSingularValue.getValue() )\n            S_Ut_b[i] = Ut_b[i]/svd.singularValues()[i];\n        else\n            S_Ut_b[i] = (Real)0.0 ;\n    }\n    Eigen::VectorXd solution = svd.matrixV() * S_Ut_b;\n    for(unsigned i=0; i<(unsigned)M.rowSize(); i++ )\n    {\n        x[i] = (Real) solution(i);\n    }\n\n    if( printLog )\n    {\n#ifdef DISPLAY_TIME\n        time1 = (double)(((double) timer.getTime() - time1) * timeStamp / (nb_iter-1));\n        std::cerr<<\"SVDLinearSolver::solve, SVD = \"<<time1<<std::endl;\n#endif\n        serr << \"SVDLinearSolver<TMatrix,TVector>::solve, rhs vector = \" << sendl << rhs.transpose() << sendl;\n        serr << \"SVDLinearSolver<TMatrix,TVector>::solve, solution = \" << sendl << x << sendl;\n        serr << \"SVDLinearSolver<TMatrix,TVector>::solve, verification, mx - b = \" << sendl << (m * solution - rhs ).transpose() << sendl;\n    }\n}\n\n\nSOFA_DECL_CLASS(SVDLinearSolver)\n\nint SVDLinearSolverClass = core::RegisterObject(\"Linear system solver using the conjugate gradient iterative algorithm\")\n        .add< SVDLinearSolver< FullMatrix<double>, FullVector<double> > >()\n        .add< SVDLinearSolver< FullMatrix<float>, FullVector<float> > >()\n        .addAlias(\"SVDLinear\")\n        .addAlias(\"SVD\")\n        ;\n\n} // namespace linearsolver\n\n} // namespace component\n\n} // namespace sofa\n\n", "meta": {"hexsha": "c49d77587c3cc1f8db4fd4a007be9b50551086ab", "size": 6558, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SofaKernel/modules/SofaEigen2Solver/SVDLinearSolver.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": "SofaKernel/modules/SofaEigen2Solver/SVDLinearSolver.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": "SofaKernel/modules/SofaEigen2Solver/SVDLinearSolver.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.862745098, "max_line_length": 199, "alphanum_fraction": 0.604452577, "num_tokens": 1553, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.45948495708312875}}
{"text": "#include \"Random.hpp\"\n\n#include <boost/random.hpp>\n#include <boost/random/random_device.hpp>\n\n//\n// class Random\n//\n\ntemplate <class T>\nRandom<T>::Random() {\n\n    boost::random::random_device seed_gen;\n    this->engine = new boost::random::mt19937_64(seed_gen());\n\n}\n\ntemplate <class T>\nRandom<T>::~Random() {\n\n    delete(this->engine);\n\n}\n\ntemplate <class T>\nT Random<T>::operator()() const {\n\n    return get();\n\n}\n\n//\n// class Poison\n//\n\nPoisson::Poisson(double arg) {\n\n    this->poisson = new boost::random::poisson_distribution<int, double>(arg);\n\n}\n\nPoisson::~Poisson() {\n\n    delete(this->poisson);\n\n}\n\nint Poisson::get() const {\n\n    return (*poisson)(*engine);\n\n}\n\n\n//\n// class Exponential\n//\n\nExponential::Exponential(double arg) {\n\n    this->exponential = new boost::random::exponential_distribution<double>(arg);\n\n}\n\nExponential::~Exponential() {\n\n    delete(this->exponential);\n\n}\n\ndouble Exponential::get() const {\n\n    return (*exponential)(*engine);\n\n}", "meta": {"hexsha": "1ce1bf9d9d5cbbed6237297d0d04ccdf3a935a12", "size": 967, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/Random.cpp", "max_stars_repo_name": "grncbg/ANSL-NetworkSimulator", "max_stars_repo_head_hexsha": "6a49390218518559e1ffaed6c91468e8873d90c0", "max_stars_repo_licenses": ["MIT"], "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/Random.cpp", "max_issues_repo_name": "grncbg/ANSL-NetworkSimulator", "max_issues_repo_head_hexsha": "6a49390218518559e1ffaed6c91468e8873d90c0", "max_issues_repo_licenses": ["MIT"], "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/Random.cpp", "max_forks_repo_name": "grncbg/ANSL-NetworkSimulator", "max_forks_repo_head_hexsha": "6a49390218518559e1ffaed6c91468e8873d90c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 12.8933333333, "max_line_length": 81, "alphanum_fraction": 0.6504653568, "num_tokens": 242, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.45948495708312875}}
{"text": "/*=========================================================================\n *\n * Copyright Universitat Pompeu Fabra, Department of Information and\n * Comunication Technologies.\n *  \n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *         http://www.apache.org/licenses/LICENSE-2.0.txt\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS,\n *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *=========================================================================*/\n\n#ifndef itkRWSegmentationFilter_hxx\n#define itkRWSegmentationFilter_hxx\n\n#include <itkImageRegionIterator.h>\n#include <itkImageRegionConstIterator.h>\n\n#include <vector>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n\nnamespace itk\n{\ntemplate <typename TInputImage, typename TOutputImage>\nvoid RWSegmentationFilter<TInputImage, TOutputImage>::GenerateData()\n{\n  if (m_LabelImage == nullptr) // Exit if SetLabelImage has not been called\n  {\n    std::cout << \"Label image has not been set\" << std::endl;\n    return;\n  }\n  if (OutputImageType::ImageDimension != 2 && OutputImageType::ImageDimension != 3)\n  {\n    std::cout << \"Exit segmentation. Image dimension must be 2 or 3 but is \" << OutputImageType::ImageDimension << std::endl;\n    return;\n  }\n\n  // Get regions to iterate for original and label images\n  typename OutputImageType::RegionType regionLabel = m_LabelImage->GetLargestPossibleRegion();\n\n  // Set label image iterator to get the bounding box size and the quantity of marked nodes\n  typedef itk::ImageRegionIterator<OutputImageType> IteratorLabelType;\n  IteratorLabelType itLabel(m_LabelImage, regionLabel);\n\n  // Crop image to bounds containin labels\n  typename OutputImageType::RegionType regionLabelCrop;\n  typename InputImageType::RegionType regionCrop;\n\n  for (int i = 0; i != OutputImageType::ImageDimension; ++i)\n  {\n    regionLabelCrop.SetSize(i, regionLabel.GetIndex()[i]);\n    regionLabelCrop.SetIndex(i, regionLabel.GetSize()[i]);\n  }\n\n  int markedLength = 0;\n\n  itLabel.GoToBegin();\n  while (!itLabel.IsAtEnd())\n  {\n    // Get image boundaries to crop image\n    if (itLabel.Get() != 0)\n    {\n      ++markedLength;\n      // Get bounding region\n      for (int i = 0; i != OutputImageType::ImageDimension; ++i)\n      {\n        if (itLabel.GetIndex()[i] < regionLabelCrop.GetIndex()[i])\n        {\n          regionCrop.SetIndex(i, itLabel.GetIndex()[i]);\n          regionLabelCrop.SetIndex(i, itLabel.GetIndex()[i]);\n        }\n        else if (itLabel.GetIndex()[i] > regionLabelCrop.GetSize()[i])\n        {\n          regionCrop.SetSize(i, itLabel.GetIndex()[i]);\n          regionLabelCrop.SetSize(i, itLabel.GetIndex()[i]);\n        }\n      }\n    }\n    ++itLabel;\n  }\n\n  int totalNodes = 1;\n  for (int i = 0; i != OutputImageType::ImageDimension; ++i)\n  {\n    regionCrop.SetIndex(i, regionCrop.GetIndex()[i]);\n    regionLabelCrop.SetIndex(i, regionLabelCrop.GetIndex()[i]);\n    regionCrop.SetSize(i, regionCrop.GetSize()[i] - regionCrop.GetIndex()[i] + 1);\n    regionLabelCrop.SetSize(i, regionLabelCrop.GetSize()[i] - regionLabelCrop.GetIndex()[i] + 1);\n\n    totalNodes *= regionCrop.GetSize()[i];\n  }\n\n  /////////////////////// Build Graph /////////////////////////////\n  /*\n    // Create graph. Each node will correspond to a pixel connected to its neighbors by an edge.\n    // Neighbors are those nodes which distance is 1 ( d = sqrt((x-xi)\u00b2 + (y-yi)\u00b2 + (z-zi)\u00b2) = 1 ), \n    // where x, y, and z are the indices of a pixel and xi, yi, and zi are the indeces of a neighboring pixel\n    // Iterate through all pixels of input and label images\n    */\n\n  int unmarkedLength = totalNodes - markedLength; /* Quantity of unmarked nodes */\n\n  // Define vectors to store graph data\n  std::vector<float> *nodes = new std::vector<float>(totalNodes);  /* Pixel intensity for all nodes/pixels */\n  std::vector<float> *labels = new std::vector<float>(totalNodes); /* Label of each node/pixel */\n  /*  For node 'i'. If 'i' is a marked node, previousFound->at(i) is how many unmarked nodes there are before node 'i'.\n        If 'i' is an unmarked node, previousFound->at(i) is how many marked nodes there are before node 'i'.\n        This values are needed to build ordered Lu and BT matrices.\n    */\n  std::vector<int> *previousFound = new std::vector<int>(totalNodes);\n  std::vector<int> *unmarked = new std::vector<int>(unmarkedLength); /* Indices of unmarked nodes ordered */\n  std::vector<int> *marked = new std::vector<int>(markedLength);     /* Store labels of marked nodes */\n  std::vector<int> *markedIdx = new std::vector<int>(markedLength);  /* Indices of marked nodes ordered */\n  std::vector<int> *nameLabels = new std::vector<int>();             /* Values of the different labels of the prior */\n\n  // Set bounding box image iterators\n  typedef itk::ImageRegionConstIterator<InputImageType> ConstIteratorImageType;\n  ConstIteratorImageType itImageCrop(this->GetInput(), regionCrop);\n  IteratorLabelType itLabelCrop(m_LabelImage, regionLabelCrop);\n\n  int foundMarked = 0;\n  int foundUnmarked = 0;\n  int NodeIdx = 0;\n\n  itImageCrop.GoToBegin();\n  itLabelCrop.GoToBegin();\n  while (!itImageCrop.IsAtEnd())\n  {\n    // Store intensity in a std::vector\n    nodes->at(NodeIdx) = itImageCrop.Get();\n    // Store labels in a std::vector. Each index of 'nodes' and 'labels' correspond to the same pixel\n    labels->at(NodeIdx) = itLabelCrop.Get();\n\n    if (itLabelCrop.Get() == 0)\n    {\n      // Get the index of each node that is unmarked\n      unmarked->at(foundUnmarked) = NodeIdx;\n      // Store how many marked points have been found before this unmarked node\n      previousFound->at(NodeIdx) = foundMarked;\n      ++foundUnmarked;\n    }\n    else\n    {\n      // Set to label value if label != 0\n      marked->at(foundMarked) = itLabelCrop.Get();\n      // Get the index of each node that is marked\n      markedIdx->at(foundMarked) = NodeIdx;\n      // Store how many unmarked points have been found before this marked node\n      previousFound->at(NodeIdx) = foundUnmarked;\n      ++foundMarked;\n      bool found;\n\n      // Store the different labels in a std::vector\n      found = std::find(nameLabels->begin(), nameLabels->end(), itLabelCrop.Get()) != nameLabels->end();\n      if (!found)\n      {\n        nameLabels->push_back(itLabelCrop.Get());\n      }\n    }\n    ++itImageCrop;\n    ++itLabelCrop;\n    ++NodeIdx;\n  }\n\n  // Sort labels\n  std::sort(nameLabels->begin(), nameLabels->end());\n\n  int totalLabels = nameLabels->size();\n\n  if (m_SolveForAllLabels)\n  {\n    totalLabels += 1;\n  }\n\n  // Linear system: Lu * X = -BT * M\n  // Convert marked (M) into a Eigen::Sparse matrix markedRHS. Needed for the computation of -BT * M (Eigen::SparseMatrix * Eigen::SparseMatrix)\n  Eigen::SparseMatrix<float, Eigen::ColMajor> *markedRHS = new Eigen::SparseMatrix<float, Eigen::ColMajor>(markedLength, totalLabels - 1);\n  for (int i = 0; i != totalLabels - 1; ++i)\n  {\n    int pos = 0;\n    for (auto itMarked = marked->begin(); itMarked != marked->end(); ++itMarked)\n    {\n      if (*itMarked == nameLabels->at(i))\n        markedRHS->insert(pos, i) = 1;\n      ++pos;\n    }\n  }\n\n  marked->clear();\n  delete marked;\n\n  /////////////////////// Build Laplacian matrix /////////////////////////////\n  // Normalize intensity gradient over image spacing\n  std::vector<float> spacing;\n  typename InputImageType::SpacingType space = this->GetInput()->GetSpacing();\n  if (OutputImageType::ImageDimension == 2)\n    spacing = {space[1], space[0], space[0], space[1]};\n  else if (OutputImageType::ImageDimension == 3)\n    spacing = {space[2], space[1], space[0], space[0], space[1], space[2]};\n\n  std::vector<int> neighbors;\n  int x = regionCrop.GetSize()[0];\n  int y = regionCrop.GetSize()[1];\n  //  Right hand of the equation: -BT * M\n  Eigen::SparseMatrix<float, Eigen::ColMajor> *BTxM = new Eigen::SparseMatrix<float, Eigen::ColMajor>(markedLength, totalLabels - 1);\n\n  // Build BT\n  // Compare whether NumCols < NumRows for less iterations during BT building\n  if (markedIdx->size() < unmarked->size())\n  {\n    Eigen::SparseMatrix<float, Eigen::ColMajor> *BT = new Eigen::SparseMatrix<float, Eigen::ColMajor>(unmarkedLength, markedLength);\n    BT->reserve(Eigen::VectorXi::Constant(markedLength, 6));\n\n    int node;\n    float valNode, valNeighbor, w;\n\n    // Iterate through marked nodes to build BT. Rows correspond to unmarked nodes, columns to marked nodes\n    for (auto itMarked = markedIdx->begin(); itMarked != markedIdx->end(); ++itMarked)\n    {\n      valNode = nodes->at(*itMarked); // Intensity of node\n      // Obtain neighbors indexes. right and left, top and bottom, front and back.\n      node = *itMarked;\n      if (OutputImageType::ImageDimension == 2)\n        neighbors = {node - x, node - 1, node + 1, node + x};\n      else if (OutputImageType::ImageDimension == 3)\n        neighbors = {node - x * y, node - x, node - 1, node + 1, node + x, node + x * y};\n      for (int i = 0; i != neighbors.size(); ++i)\n      {\n        // Make sure all the neighbors computed fall within the bounding box dimension\n        if (neighbors.at(i) >= 0 && neighbors.at(i) < totalNodes && labels->at(neighbors.at(i)) == 0)\n        {\n          valNeighbor = nodes->at(neighbors.at(i));                                    // Intensity of neighbor pixel\n          w = (exp(-m_Beta * pow((valNode - valNeighbor) / spacing.at(i), 2)) + 1e-6); // Intensity gradient following a Gaussian function\n          //  Columns of BT correspond to marked nodes, rows to unmarked\n          BT->insert(neighbors.at(i) - previousFound->at(neighbors.at(i)), node - previousFound->at(node)) = -w;\n        }\n      }\n    }\n    markedIdx->clear();\n    //  Right hand of the equation: -BT * M\n    *BTxM = -*BT * *markedRHS;\n    BT->resize(0, 0);\n    BT->data().squeeze();\n    markedRHS->resize(0, 0);\n    markedRHS->data().squeeze();\n    delete markedIdx, markedRHS, BT;\n  }\n  else\n  {\n    markedIdx->clear();\n    delete markedIdx;\n\n    Eigen::SparseMatrix<float, Eigen::RowMajor> *BT = new Eigen::SparseMatrix<float, Eigen::RowMajor>(unmarkedLength, markedLength);\n    BT->reserve(Eigen::VectorXi::Constant(markedLength, 6));\n\n    int node;\n    float valNode, valNeighbor, w;\n\n    // Iterate through unmarked nodes to build BT. Rows correspond to unmarked nodes, columns to marked nodes\n    for (auto itUnmarked = unmarked->begin(); itUnmarked != unmarked->end(); ++itUnmarked)\n    {\n      valNode = nodes->at(*itUnmarked); // Intensity of node\n      // Obtain neighbors indexes. right and left, top and bottom, front and back.\n      node = *itUnmarked;\n      if (OutputImageType::ImageDimension == 2)\n        neighbors = {node - x, node - 1, node + 1, node + x};\n      else if (OutputImageType::ImageDimension == 3)\n        neighbors = {node - x * y, node - x, node - 1, node + 1, node + x, node + x * y};\n      for (int i = 0; i != neighbors.size(); ++i)\n      {\n        // Make sure all the neighbors computed fall within the bounding box dimension\n        if (neighbors.at(i) >= 0 && neighbors.at(i) < totalNodes && labels->at(neighbors.at(i)) != 0)\n        {\n          valNeighbor = nodes->at(neighbors.at(i));                                    // Intensity of neighbor pixel\n          w = (exp(-m_Beta * pow((valNode - valNeighbor) / spacing.at(i), 2)) + 1e-6); // Intensity gradient following a Gaussian function\n          //  Columns of BT correspond to marked nodes, rows to unmarked\n          BT->insert(node - previousFound->at(node), neighbors.at(i) - previousFound->at(neighbors.at(i))) = -w;\n        }\n      }\n    }\n    //  Right hand of the equation: -BT * M\n    *BTxM = -*BT * *markedRHS;\n    BT->resize(0, 0);\n    BT->data().squeeze();\n    markedRHS->resize(0, 0);\n    markedRHS->data().squeeze();\n    delete markedRHS, BT;\n  }\n\n  // Build Lu. LHS of the equation\n  Eigen::SparseMatrix<float, Eigen::RowMajor> *Lu = new Eigen::SparseMatrix<float, Eigen::RowMajor>(unmarkedLength, unmarkedLength);\n  Lu->reserve(Eigen::VectorXi::Constant(unmarkedLength, 7));\n\n  // Iterate through unmarked nodes to build Lu. Rows correspond to unmarked nodes, columns to unmarked nodes\n  for (auto itUnmarked = unmarked->begin(); itUnmarked != unmarked->end(); ++itUnmarked)\n  {\n    int node;\n    float valNode, valNeighbor, w, degree;\n\n    valNode = nodes->at(*itUnmarked); // Intensity of node\n    // Obtain neighbors indexes. right and left, top and bottom, front and back.\n    node = *itUnmarked;\n    if (OutputImageType::ImageDimension == 2)\n      neighbors = {node - x, node - 1, node + 1, node + x};\n    else if (OutputImageType::ImageDimension == 3)\n      neighbors = {node - x * y, node - x, node - 1, node + 1, node + x, node + x * y};\n    degree = 0.0;\n    for (int i = 0; i != neighbors.size(); ++i)\n    {\n      // Make sure all the neighbors computed fall within the bounding box dimension\n      if (neighbors.at(i) >= 0 && neighbors.at(i) < totalNodes)\n      {\n        valNeighbor = nodes->at(neighbors.at(i));                                    // Intensity of neighbor pixel\n        w = (exp(-m_Beta * pow((valNode - valNeighbor) / spacing.at(i), 2)) + 1e-6); // Intensity gradient following a Gaussian function\n        degree += w;                                                                 // Sum of the weights\n        //  Columns of Lu correspond to unmarked nodes\n        if (labels->at(neighbors.at(i)) == 0) // If neighbor is an unmarked node, build Lu\n        {\n          Lu->insert(node - previousFound->at(node), neighbors.at(i) - previousFound->at(neighbors.at(i))) = -w;\n        }\n      }\n    }\n    // Add node degree to diagonal of Lu\n    Lu->insert(node - previousFound->at(node), node - previousFound->at(node)) = degree;\n  }\n  Lu->makeCompressed();\n\n  nodes->clear();\n  unmarked->clear();\n  previousFound->clear();\n  neighbors.clear();\n  delete nodes, unmarked, previousFound;\n\n  /////////////////////// Solve linear system /////////////////////////////\n  // Lu * X = -BT * M\n  // Set vector to store the result of the solver\n  Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> *probabilities = new Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic>(unmarkedLength, totalLabels - 1);\n\n  // Allow multithreading. For the moment limited to 8 threads.\n  if (m_NumberOfThreads > 0 && m_NumberOfThreads < 9)\n  {\n    omp_set_num_threads(m_NumberOfThreads);\n    Eigen::setNbThreads(m_NumberOfThreads);\n  }\n  else\n  {\n    omp_set_num_threads(1);\n    Eigen::setNbThreads(1);\n  }\n\n  // Set the solver for the problem with LHS Lu. BiCGStab.\n  // Select either Eigen BiCGSTAB or ConjugateGradient\n  Eigen::BiCGSTAB<Eigen::SparseMatrix<float, Eigen::RowMajor>, Eigen::DiagonalPreconditioner<float>> *solver = new Eigen::BiCGSTAB<Eigen::SparseMatrix<float, Eigen::RowMajor>, Eigen::DiagonalPreconditioner<float>>(*Lu); // Usually faster\n  // Eigen::ConjugateGradient< Eigen::SparseMatrix< float ,Eigen::RowMajor> , Eigen::Lower|Eigen::Upper , Eigen::DiagonalPreconditioner<float> > solver(Lu);\n\n  // Set solver parameters\n  solver->setTolerance(m_Tolerance);\n  solver->setMaxIterations(m_MaximumNumberOfIterations);\n  // Compute probabilities with RHS BTxM\n  *probabilities = solver->solve(*BTxM);\n\n  m_SolverIterations = solver->iterations();\n  m_SolverError = solver->error();\n\n  Lu->resize(0, 0);\n  Lu->data().squeeze();\n  BTxM->resize(0, 0);\n  BTxM->data().squeeze();\n  delete Lu, BTxM;\n\n  std::vector<int> *RWLabels = new std::vector<int>(unmarkedLength);\n\n  /*  Assign a label to each unmarked node according to the result of the solver. \n        The label that is assigned is that one corresponding to the highest probability.\n        Since we solver for S-1 systems, last label probability is computed by subtraction */\n  for (int i = 0; i != unmarkedLength; ++i)\n  {\n    float maxProbability = probabilities->coeffRef(i, 0);\n    int maxLabelPos = 0;\n    float accumulatedProbability = maxProbability;\n    for (int j = 1; j != totalLabels - 1; ++j)\n    {\n      accumulatedProbability += probabilities->coeffRef(i, j);\n      if (probabilities->coeffRef(i, j) > maxProbability)\n      {\n        maxProbability = probabilities->coeffRef(i, j);\n        maxLabelPos = j;\n      }\n    }\n    RWLabels->at(i) = 0.95 - accumulatedProbability > maxProbability ? nameLabels->back() : nameLabels->at(maxLabelPos);\n  }\n  probabilities->resize(0, 0);\n  delete probabilities;\n\n  int valBackground;\n  if (!m_WriteBackground)\n    valBackground = 0;\n  else\n    valBackground = nameLabels->back();\n\n  typename OutputImageType::Pointer outputLabels = this->GetOutput();\n  outputLabels->Graft(m_LabelImage);\n  outputLabels->FillBuffer(valBackground);\n\n  // Iterate through original label image to create segmentation image\n  // Assign labels known from label image to their original value. Assign unmarked labels\n  // according to the result from the solver\n\n  IteratorLabelType itOut1(outputLabels, regionLabelCrop);\n\n  // Set computed labels to segmentation image\n  int unmarkedIdx = 0;\n  int idxOutput = 0;\n\n  itOut1.GoToBegin();\n  while (!itOut1.IsAtEnd())\n  {\n    if (labels->at(idxOutput) == 0)\n    {\n      if (RWLabels->at(unmarkedIdx) != nameLabels->back())\n        itOut1.Set(RWLabels->at(unmarkedIdx));\n      else\n        itOut1.Set(valBackground);\n      ++unmarkedIdx;\n    }\n    else if (labels->at(idxOutput) != nameLabels->back())\n      itOut1.Set(labels->at(idxOutput));\n\n    ++idxOutput;\n    ++itOut1;\n  }\n\n  labels->clear();\n  RWLabels->clear();\n  nameLabels->clear();\n  delete labels, RWLabels, nameLabels;\n\n  return;\n}\n\ntemplate <typename TInputImage, typename TOutputImage>\nvoid RWSegmentationFilter<TInputImage, TOutputImage>::PrintSelf(std::ostream &os, Indent indent) const\n{\n  Superclass::PrintSelf(os, indent);\n  os << indent << \"Beta: \" << m_Beta << std::endl;\n  os << indent << \"NumberOfThreads: \" << m_NumberOfThreads << std::endl;\n  os << indent << \"Tolerance: \" << m_Tolerance << std::endl;\n  os << indent << \"MaximumNumberOfIterations: \" << m_MaximumNumberOfIterations << std::endl;\n  os << indent << \"WriteBackground: \" << m_WriteBackground << std::endl;\n}\n\n} // namespace itk\n#endif", "meta": {"hexsha": "639d7938693baa03eba99ea599c69505ce4aed0d", "size": 18332, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "itkRWSegmentationFilter/itkRWSegmentationFilter.hxx", "max_stars_repo_name": "enricperera/itkRWSegmentationFilter", "max_stars_repo_head_hexsha": "0188a4cfa31c8798301af58c37b28d430efdef06", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-20T13:29:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-20T13:29:02.000Z", "max_issues_repo_path": "itkRWSegmentationFilter/itkRWSegmentationFilter.hxx", "max_issues_repo_name": "enricperera/itkRWSegmentationFilter", "max_issues_repo_head_hexsha": "0188a4cfa31c8798301af58c37b28d430efdef06", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-04-10T09:48:45.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-10T09:48:45.000Z", "max_forks_repo_path": "Plugins/org.upf.rwSegmentationPlugin/src/internal/itkRWSegmentationFilter/itkRWSegmentationFilter.hxx", "max_forks_repo_name": "enricperera/mitkRWSegmentationPlugin", "max_forks_repo_head_hexsha": "20e4bbb7bd977fdc929e694a233410af1aa67cab", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.7657266811, "max_line_length": 237, "alphanum_fraction": 0.6446650666, "num_tokens": 4851, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384736, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4594849512032808}}
{"text": "// Copyright (C) 2011  Davis E. King (davis@dlib.net)\r\n// License: Boost Software License   See LICENSE.txt for the full license.\r\n\r\n\r\n#include <sstream>\r\n#include <string>\r\n#include <cstdlib>\r\n#include <ctime>\r\n#include \"tester.h\"\r\n#include <dlib/svm_threaded.h>\r\n#include <dlib/rand.h>\r\n\r\n\r\ntypedef dlib::matrix<double,3,1> lhs_element;\r\ntypedef dlib::matrix<double,3,1> rhs_element;\r\n\r\nnamespace  \r\n{\r\n    using namespace test;\r\n    using namespace dlib;\r\n    using namespace std;\r\n\r\n    logger dlog(\"test.assignment_learning\");\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\n    struct feature_extractor_dense\r\n    {\r\n        typedef matrix<double,3,1> feature_vector_type;\r\n\r\n        typedef ::lhs_element lhs_element;\r\n        typedef ::rhs_element rhs_element;\r\n\r\n        unsigned long num_features() const\r\n        {\r\n            return 3;\r\n        }\r\n\r\n        void get_features (\r\n            const lhs_element& left,\r\n            const rhs_element& right,\r\n            feature_vector_type& feats\r\n        ) const\r\n        {\r\n            feats = squared(left - right);\r\n        }\r\n\r\n    };\r\n\r\n    void serialize   (const feature_extractor_dense& , std::ostream& ) {}\r\n    void deserialize (feature_extractor_dense&       , std::istream& ) {}\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\n    struct feature_extractor_sparse\r\n    {\r\n        typedef std::vector<std::pair<unsigned long,double> > feature_vector_type;\r\n\r\n        typedef ::lhs_element lhs_element;\r\n        typedef ::rhs_element rhs_element;\r\n\r\n        unsigned long num_features() const\r\n        {\r\n            return 3;\r\n        }\r\n\r\n        void get_features (\r\n            const lhs_element& left,\r\n            const rhs_element& right,\r\n            feature_vector_type& feats\r\n        ) const\r\n        {\r\n            feats.clear();\r\n            feats.push_back(make_pair(0,squared(left-right)(0)));\r\n            feats.push_back(make_pair(1,squared(left-right)(1)));\r\n            feats.push_back(make_pair(2,squared(left-right)(2)));\r\n        }\r\n\r\n    };\r\n\r\n    void serialize   (const feature_extractor_sparse& , std::ostream& ) {}\r\n    void deserialize (feature_extractor_sparse&       , std::istream& ) {}\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\n    typedef std::pair<std::vector<lhs_element>, std::vector<rhs_element> > sample_type;\r\n    typedef std::vector<long> label_type;\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\n    void make_data (\r\n        std::vector<sample_type>& samples,\r\n        std::vector<label_type>& labels\r\n    )\r\n    {\r\n        lhs_element a, b, c, d;\r\n        a = 1,0,0;\r\n        b = 0,1,0;\r\n        c = 0,0,1;\r\n        d = 0,1,1;\r\n\r\n        std::vector<lhs_element> lhs;\r\n        std::vector<rhs_element> rhs;\r\n        label_type label;\r\n\r\n        lhs.push_back(a);\r\n        lhs.push_back(b);\r\n        lhs.push_back(c);\r\n\r\n        rhs.push_back(b);\r\n        rhs.push_back(a);\r\n        rhs.push_back(c);\r\n\r\n        label.push_back(1);\r\n        label.push_back(0);\r\n        label.push_back(2);\r\n\r\n        samples.push_back(make_pair(lhs,rhs));\r\n        labels.push_back(label);\r\n\r\n\r\n\r\n\r\n        lhs.clear();\r\n        rhs.clear();\r\n        label.clear();\r\n\r\n        lhs.push_back(a);\r\n        lhs.push_back(b);\r\n        lhs.push_back(c);\r\n\r\n        rhs.push_back(c);\r\n        rhs.push_back(b);\r\n        rhs.push_back(a);\r\n        rhs.push_back(d);\r\n\r\n        label.push_back(2);\r\n        label.push_back(1);\r\n        label.push_back(0);\r\n\r\n        samples.push_back(make_pair(lhs,rhs));\r\n        labels.push_back(label);\r\n\r\n\r\n        lhs.clear();\r\n        rhs.clear();\r\n        label.clear();\r\n\r\n        lhs.push_back(a);\r\n        lhs.push_back(b);\r\n        lhs.push_back(c);\r\n\r\n        rhs.push_back(c);\r\n        rhs.push_back(a);\r\n        rhs.push_back(d);\r\n\r\n        label.push_back(1);\r\n        label.push_back(-1);\r\n        label.push_back(0);\r\n\r\n        samples.push_back(make_pair(lhs,rhs));\r\n        labels.push_back(label);\r\n\r\n\r\n\r\n        lhs.clear();\r\n        rhs.clear();\r\n        label.clear();\r\n\r\n        lhs.push_back(d);\r\n        lhs.push_back(b);\r\n        lhs.push_back(c);\r\n\r\n        label.push_back(-1);\r\n        label.push_back(-1);\r\n        label.push_back(-1);\r\n\r\n        samples.push_back(make_pair(lhs,rhs));\r\n        labels.push_back(label);\r\n\r\n\r\n\r\n        lhs.clear();\r\n        rhs.clear();\r\n        label.clear();\r\n\r\n        samples.push_back(make_pair(lhs,rhs));\r\n        labels.push_back(label);\r\n\r\n    }\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\n    void make_data_force (\r\n        std::vector<sample_type>& samples,\r\n        std::vector<label_type>& labels\r\n    )\r\n    {\r\n        lhs_element a, b, c, d;\r\n        a = 1,0,0;\r\n        b = 0,1,0;\r\n        c = 0,0,1;\r\n        d = 0,1,1;\r\n\r\n        std::vector<lhs_element> lhs;\r\n        std::vector<rhs_element> rhs;\r\n        label_type label;\r\n\r\n        lhs.push_back(a);\r\n        lhs.push_back(b);\r\n        lhs.push_back(c);\r\n\r\n        rhs.push_back(b);\r\n        rhs.push_back(a);\r\n        rhs.push_back(c);\r\n\r\n        label.push_back(1);\r\n        label.push_back(0);\r\n        label.push_back(2);\r\n\r\n        samples.push_back(make_pair(lhs,rhs));\r\n        labels.push_back(label);\r\n\r\n\r\n\r\n\r\n        lhs.clear();\r\n        rhs.clear();\r\n        label.clear();\r\n\r\n        lhs.push_back(a);\r\n        lhs.push_back(b);\r\n        lhs.push_back(c);\r\n\r\n        rhs.push_back(c);\r\n        rhs.push_back(b);\r\n        rhs.push_back(a);\r\n        rhs.push_back(d);\r\n\r\n        label.push_back(2);\r\n        label.push_back(1);\r\n        label.push_back(0);\r\n\r\n        samples.push_back(make_pair(lhs,rhs));\r\n        labels.push_back(label);\r\n\r\n\r\n        lhs.clear();\r\n        rhs.clear();\r\n        label.clear();\r\n\r\n        lhs.push_back(a);\r\n        lhs.push_back(c);\r\n\r\n        rhs.push_back(c);\r\n        rhs.push_back(a);\r\n\r\n        label.push_back(1);\r\n        label.push_back(0);\r\n\r\n        samples.push_back(make_pair(lhs,rhs));\r\n        labels.push_back(label);\r\n\r\n\r\n\r\n\r\n\r\n        lhs.clear();\r\n        rhs.clear();\r\n        label.clear();\r\n\r\n        samples.push_back(make_pair(lhs,rhs));\r\n        labels.push_back(label);\r\n\r\n    }\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\n    template <typename fe_type, typename F>\r\n    void test1(F make_data, bool force_assignment)\r\n    {\r\n        print_spinner();\r\n\r\n        std::vector<sample_type> samples;\r\n        std::vector<label_type> labels;\r\n\r\n        make_data(samples, labels);\r\n        make_data(samples, labels);\r\n        make_data(samples, labels);\r\n\r\n        randomize_samples(samples, labels);\r\n\r\n        structural_assignment_trainer<fe_type> trainer;\r\n\r\n        DLIB_TEST(trainer.forces_assignment() == false);\r\n        DLIB_TEST(trainer.get_c() == 100);\r\n        DLIB_TEST(trainer.get_num_threads() == 2);\r\n        DLIB_TEST(trainer.get_max_cache_size() == 5);\r\n\r\n\r\n        trainer.set_forces_assignment(force_assignment);\r\n        trainer.set_num_threads(3);\r\n        trainer.set_c(50);\r\n\r\n        DLIB_TEST(trainer.get_c() == 50);\r\n        DLIB_TEST(trainer.get_num_threads() == 3);\r\n        DLIB_TEST(trainer.forces_assignment() == force_assignment);\r\n\r\n        assignment_function<fe_type> ass = trainer.train(samples, labels);\r\n\r\n        for (unsigned long i = 0; i < samples.size(); ++i)\r\n        {\r\n            std::vector<long> out = ass(samples[i]);\r\n            dlog << LINFO << \"true labels: \" << trans(mat(labels[i]));\r\n            dlog << LINFO << \"pred labels: \" << trans(mat(out));\r\n            DLIB_TEST(trans(mat(labels[i])) == trans(mat(out)));\r\n        }\r\n\r\n        double accuracy;\r\n\r\n        dlog << LINFO << \"samples.size(): \"<< samples.size();\r\n        accuracy = test_assignment_function(ass, samples, labels);\r\n        dlog << LINFO << \"accuracy: \"<< accuracy;\r\n        DLIB_TEST(accuracy == 1);\r\n\r\n        accuracy = cross_validate_assignment_trainer(trainer, samples, labels, 3);\r\n        dlog << LINFO << \"cv accuracy: \"<< accuracy;\r\n        DLIB_TEST(accuracy == 1);\r\n\r\n        ostringstream sout;\r\n        serialize(ass, sout);\r\n        istringstream sin(sout.str());\r\n        assignment_function<fe_type> ass2;\r\n        deserialize(ass2, sin);\r\n\r\n        DLIB_TEST(ass2.forces_assignment() == ass.forces_assignment());\r\n        DLIB_TEST(length(ass2.get_weights() - ass.get_weights()) < 1e-10);\r\n\r\n        for (unsigned long i = 0; i < samples.size(); ++i)\r\n        {\r\n            std::vector<long> out = ass2(samples[i]);\r\n            dlog << LINFO << \"true labels: \" << trans(mat(labels[i]));\r\n            dlog << LINFO << \"pred labels: \" << trans(mat(out));\r\n            DLIB_TEST(trans(mat(labels[i])) == trans(mat(out)));\r\n        }\r\n    }\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\n    class test_assignment_learning : public tester\r\n    {\r\n    public:\r\n        test_assignment_learning (\r\n        ) :\r\n            tester (\"test_assignment_learning\",\r\n                    \"Runs tests on the assignment learning code.\")\r\n        {}\r\n\r\n        void perform_test (\r\n        )\r\n        {\r\n            test1<feature_extractor_dense>(make_data, false);\r\n            test1<feature_extractor_sparse>(make_data, false);\r\n\r\n            test1<feature_extractor_dense>(make_data_force, false);\r\n            test1<feature_extractor_sparse>(make_data_force, false);\r\n            test1<feature_extractor_dense>(make_data_force, true);\r\n            test1<feature_extractor_sparse>(make_data_force, true);\r\n        }\r\n    } a;\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\n}\r\n\r\n\r\n", "meta": {"hexsha": "70c4874a1dc2b7c64ff1cb164a5df947947dab27", "size": 9959, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dlib/test/assignment_learning.cpp", "max_stars_repo_name": "ckproc/dlib-19.7", "max_stars_repo_head_hexsha": "0ca40f5e85de2436e557bee9a805d3987d2d9507", "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": "dlib/test/assignment_learning.cpp", "max_issues_repo_name": "ckproc/dlib-19.7", "max_issues_repo_head_hexsha": "0ca40f5e85de2436e557bee9a805d3987d2d9507", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2018-02-27T15:44:25.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-28T01:26:03.000Z", "max_forks_repo_path": "dlib/test/assignment_learning.cpp", "max_forks_repo_name": "ckproc/dlib-19.7", "max_forks_repo_head_hexsha": "0ca40f5e85de2436e557bee9a805d3987d2d9507", "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.2078947368, "max_line_length": 92, "alphanum_fraction": 0.4955316799, "num_tokens": 2031, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289836, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.45938115004992597}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   tstWattDistribution.cpp\n//! \\author Aaron Tumulak\n//! \\brief  Watt distribution unit tests.\n//!\n//---------------------------------------------------------------------------//\n\n// Std Lib Includes\n#include <iostream>\n\n// Boost Includes\n#include <boost/units/systems/si.hpp>\n#include <boost/units/systems/cgs.hpp>\n#include <boost/units/io.hpp>\n\n// Trilinos Includes\n#include <Teuchos_UnitTestHarness.hpp>\n#include <Teuchos_RCP.hpp>\n#include <Teuchos_Array.hpp>\n#include <Teuchos_ParameterList.hpp>\n#include <Teuchos_XMLParameterListCoreHelpers.hpp>\n#include <Teuchos_VerboseObject.hpp>\n\n// FRENSIE Includes\n#include \"Utility_UnitTestHarnessExtensions.hpp\"\n#include \"Utility_OneDDistribution.hpp\"\n#include \"Utility_WattDistribution.hpp\"\n#include \"Utility_PhysicalConstants.hpp\"\n#include \"Utility_RandomNumberGenerator.hpp\"\n#include \"Utility_UnitTraits.hpp\"\n#include \"Utility_QuantityTraits.hpp\"\n#include \"Utility_ElectronVoltUnit.hpp\"\n\nusing boost::units::quantity;\nusing namespace Utility::Units;\nnamespace si = boost::units::si;\nnamespace cgs = boost::units::cgs;\n\n//---------------------------------------------------------------------------//\n// Testing Variables\n//---------------------------------------------------------------------------//\n\nTeuchos::RCP<Teuchos::ParameterList> test_dists_list;\n\nTeuchos::RCP<Utility::OneDDistribution> distribution(\n\t\t\t\t new Utility::WattDistribution( 1.0, 1.0, 1.0, 0.1 ) );\n\nTeuchos::RCP<Utility::UnitAwareOneDDistribution<MegaElectronVolt,si::amount> >\nunit_aware_distribution( new Utility::UnitAwareWattDistribution<MegaElectronVolt,si::amount>( 1e6*eV, 1e3*keV, 1e-6/eV, 0.1*MeV ) );\n\n//---------------------------------------------------------------------------//\n// Tests.\n//---------------------------------------------------------------------------//\n// Check that the distribution can be evaluated\nTEUCHOS_UNIT_TEST( WattDistribution, evaluate )\n{\n  double test_value_1 = 0.0 ;\n  double test_value_2 = exp( -1.0 ) * sinh( 1.0 );\n  \n  TEST_EQUALITY_CONST( distribution->evaluate( 0.0 ), test_value_1 );\n  TEST_EQUALITY_CONST( distribution->evaluate( 1.0 ), test_value_2 );\n}\n\n//---------------------------------------------------------------------------//\n// Check that the unit-aware distribution can be evaluated\nTEUCHOS_UNIT_TEST( UnitAwareWattDistribution, evaluate )\n{\n  double scale_factor = exp( -1.0 )*sinh( 1.0 );\n\n  TEST_EQUALITY_CONST( unit_aware_distribution->evaluate( 0.0*MeV ),\n\t\t       0.0*si::mole );\n  TEST_EQUALITY_CONST( unit_aware_distribution->evaluate( 1.0*MeV ),\n\t\t       scale_factor*si::mole );\n}\n\n//---------------------------------------------------------------------------//\n// Check that the PDF can be evaluated\nTEUCHOS_UNIT_TEST( WattDistribution, evaluatePDF )\n{\n  double test_value_1 = 0.0 ;\n  double test_value_2 = 0.25 * sqrt( Utility::PhysicalConstants::pi ) * exp( 0.25 ) * ( erf( sqrt(0.9) - sqrt(0.25) ) + erf( sqrt(0.9) + sqrt(0.25) ) ) - exp( -0.9 ) * sinh( sqrt(0.9) );\n  test_value_2 = pow( test_value_2, -1.0 ) * exp( -1.0 ) * sinh( 1.0 );\n\n  TEST_EQUALITY_CONST( distribution->evaluatePDF( 0.0 ), test_value_1 );\n  TEST_EQUALITY_CONST( distribution->evaluatePDF( 1.0 ), test_value_2 );\n}\n\n//---------------------------------------------------------------------------//\n// Check that the unit-aware PDF can be evaluated\nTEUCHOS_UNIT_TEST( UnitAwareWattDistribution, evaluatePDF )\n{\n  double scale_factor = exp( -1.0 )*sinh( 1.0 );\n  scale_factor /= 0.25 * sqrt( Utility::PhysicalConstants::pi ) * exp( 0.25 ) * ( erf( sqrt(0.9) - sqrt(0.25) ) + erf( sqrt(0.9) + sqrt(0.25) ) ) - exp( -0.9 ) * sinh( sqrt(0.9) );\n\n  TEST_EQUALITY_CONST( unit_aware_distribution->evaluatePDF( 0.0*MeV ),\n\t\t       0.0/MeV );\n  TEST_EQUALITY_CONST( unit_aware_distribution->evaluatePDF( 1.0*MeV ),\n\t\t       scale_factor/MeV );\n}\n\n//---------------------------------------------------------------------------//\n// Check that the distribution can be sampled using OpenMC method\nTEUCHOS_UNIT_TEST( WattDistribution, sample )\n{\n  std::vector<double> fake_stream( 15 );\n  fake_stream[0] = 0.8110855833521807; // Maxwellian Distribution\n  fake_stream[1] = 0.9603231091455754; // Sample Accepted. Sample is:\n  fake_stream[2] = 0.3888878000049402; // 0.23654793157394\n  fake_stream[3] = 0.1790067705163392; // Watt Distribution Sample Accepted. Sample is: 0.17431015530718\n  fake_stream[4] = 0.7971990719536760; // Maxwellian Distribution\n  fake_stream[5] = 0.0448247918373053; // Sample Rejected. Sample is:\n  fake_stream[6] = 0.0375590391821071; // 3.32084968701263\n  fake_stream[7] = 0.9522705508082248; // Maxwellian Distribution\n  fake_stream[8] = 0.5691586660769004; // Sample Accepted. Sample is:\n  fake_stream[9] = 0.0083308067369354; // 0.61240561891848\n  fake_stream[10] = 0.6415677450291360; // Watt Distribution Sample Rejected. Sample is: 1.08397711671084\n  fake_stream[11] = 0.8589987123720327; // Maxwellian Distribution\n  fake_stream[12] = 0.4981431293148418; // Sample Accepted. Sample is:\n  fake_stream[13] = 0.5932835342621010; // 0.39976547875177\n  fake_stream[14] = 0.6731968005067009; // Watt Distribution Sample Accepted. Sample is: 0.86877979533891\n\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  double sample = distribution->sample();\n  TEST_FLOATING_EQUALITY( sample, 0.17431015530718, 1e-13 );\n\n  sample = distribution->sample();\n  TEST_FLOATING_EQUALITY( sample, 0.86877979533891, 1e-13 );\n\n  Utility::RandomNumberGenerator::unsetFakeStream();\n}\n\n//---------------------------------------------------------------------------//\n// Check that the unit-aware distribution can be sampled using OpenMC method\nTEUCHOS_UNIT_TEST( UnitAwareWattDistribution, sample )\n{\n  std::vector<double> fake_stream( 15 );\n  fake_stream[0] = 0.8110855833521807; // Maxwellian Distribution\n  fake_stream[1] = 0.9603231091455754; // Sample Accepted. Sample is:\n  fake_stream[2] = 0.3888878000049402; // 0.23654793157394\n  fake_stream[3] = 0.1790067705163392; // Watt Distribution Sample Accepted. Sample is: 0.17431015530718\n  fake_stream[4] = 0.7971990719536760; // Maxwellian Distribution\n  fake_stream[5] = 0.0448247918373053; // Sample Rejected. Sample is:\n  fake_stream[6] = 0.0375590391821071; // 3.32084968701263\n  fake_stream[7] = 0.9522705508082248; // Maxwellian Distribution\n  fake_stream[8] = 0.5691586660769004; // Sample Accepted. Sample is:\n  fake_stream[9] = 0.0083308067369354; // 0.61240561891848\n  fake_stream[10] = 0.6415677450291360; // Watt Distribution Sample Rejected. Sample is: 1.08397711671084\n  fake_stream[11] = 0.8589987123720327; // Maxwellian Distribution\n  fake_stream[12] = 0.4981431293148418; // Sample Accepted. Sample is:\n  fake_stream[13] = 0.5932835342621010; // 0.39976547875177\n  fake_stream[14] = 0.6731968005067009; // Watt Distribution Sample Accepted. Sample is: 0.86877979533891\n\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  quantity<MegaElectronVolt> sample = unit_aware_distribution->sample();\n  UTILITY_TEST_FLOATING_EQUALITY( sample, 0.17431015530718*MeV, 1e-13 );\n\n  sample = unit_aware_distribution->sample();\n  UTILITY_TEST_FLOATING_EQUALITY( sample, 0.86877979533891*MeV, 1e-13 );\n\n  Utility::RandomNumberGenerator::unsetFakeStream();\n}\n\n//---------------------------------------------------------------------------//\n// Check that the distribution can be sampled using OpenMC method, passing in\n// parameters\nTEUCHOS_UNIT_TEST( WattDistribution, sample_pass_parameters )\n{\n  std::vector<double> fake_stream( 15 );\n  fake_stream[0] = 0.6617443503056450; // Maxwellian Distribution\n  fake_stream[1] = 0.8510592242616175; // Sample Accepted. Sample is:\n  fake_stream[2] = 0.5401745197210969; // 0.09667248521245\n  fake_stream[3] = 0.2005969462099806; // Watt Distribution Sample Accepted. Sample is: 0.07927727029875\n  fake_stream[4] = 0.5189418543931951; // Maxwellian Distribution\n  fake_stream[5] = 0.7484231272861934; // Sample Rejected. Sample is:\n  fake_stream[6] = 0.8345865134048199; // 0.13501824430785\n  fake_stream[7] = 0.8704061668810904; // Maxwellian Distribution\n  fake_stream[8] = 0.5575773053122431; // Sample Accepted. Sample is:\n  fake_stream[9] = 0.7452925729418971; // 0.04548390223293\n  fake_stream[10] = 0.6556974287666129; // Watt Distribution Sample Rejected. Sample is: 0.05068410532744\n  fake_stream[11] = 0.8140855348977614; // Maxwellian Distribution\n  fake_stream[12] = 0.5750169688125915; // Sample Accepted. Sample is:\n  fake_stream[13] = 0.8372435273691630; // 0.04821527540845\n  fake_stream[14] = 0.4721727279140688; // Watt Distribution Sample Accepted. Sample is: 0.04844237604136\n\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n  \n  double incident_energy, a_parameter, b_parameter, restriction_energy, sample;\n  \n  incident_energy = 0.5;\n  a_parameter = 0.2;\n  b_parameter = 0.3;\n  restriction_energy = 0.4;\n\n  sample = Utility::WattDistribution::sample( incident_energy, a_parameter, b_parameter, restriction_energy );\n  TEST_FLOATING_EQUALITY( sample, 0.07927727029875, 1e-13 );\n    \n  incident_energy = 0.3;\n  a_parameter = 0.2;\n  b_parameter = 0.1;\n  restriction_energy = 0.25;\n\n  sample = Utility::WattDistribution::sample( incident_energy, a_parameter, b_parameter, restriction_energy );\n  TEST_FLOATING_EQUALITY( sample, 0.04844237604136, 1e-13 );\n  \n  Utility::RandomNumberGenerator::unsetFakeStream();\n}\n\n//---------------------------------------------------------------------------//\n// Check that the unit-aware distribution can be sampled using OpenMC method, \n// passing in parameters\nTEUCHOS_UNIT_TEST( UnitAwareWattDistribution, \n\t\t   sample_pass_parameters )\n{\n  std::vector<double> fake_stream( 15 );\n  fake_stream[0] = 0.6617443503056450; // Maxwellian Distribution\n  fake_stream[1] = 0.8510592242616175; // Sample Accepted. Sample is:\n  fake_stream[2] = 0.5401745197210969; // 0.09667248521245\n  fake_stream[3] = 0.2005969462099806; // Watt Distribution Sample Accepted. Sample is: 0.07927727029875\n  fake_stream[4] = 0.5189418543931951; // Maxwellian Distribution\n  fake_stream[5] = 0.7484231272861934; // Sample Rejected. Sample is:\n  fake_stream[6] = 0.8345865134048199; // 0.13501824430785\n  fake_stream[7] = 0.8704061668810904; // Maxwellian Distribution\n  fake_stream[8] = 0.5575773053122431; // Sample Accepted. Sample is:\n  fake_stream[9] = 0.7452925729418971; // 0.04548390223293\n  fake_stream[10] = 0.6556974287666129; // Watt Distribution Sample Rejected. Sample is: 0.05068410532744\n  fake_stream[11] = 0.8140855348977614; // Maxwellian Distribution\n  fake_stream[12] = 0.5750169688125915; // Sample Accepted. Sample is:\n  fake_stream[13] = 0.8372435273691630; // 0.04821527540845\n  fake_stream[14] = 0.4721727279140688; // Watt Distribution Sample Accepted. Sample is: 0.04844237604136\n\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  Utility::UnitAwareWattDistribution<MegaElectronVolt>::IndepQuantity incident_energy, a_parameter, restriction_energy, sample;\n  \n  Utility::UnitAwareWattDistribution<MegaElectronVolt>::InverseIndepQuantity b_parameter;\n\n  incident_energy = 0.5*MeV;\n  a_parameter = 0.2*MeV;\n  b_parameter = 0.3/MeV;\n  restriction_energy = 0.4*MeV;\n\n  sample = Utility::UnitAwareWattDistribution<MegaElectronVolt>::sample( incident_energy, a_parameter, b_parameter, restriction_energy );\n  UTILITY_TEST_FLOATING_EQUALITY( sample, 0.07927727029875*MeV, 1e-13 );\n    \n  incident_energy = 0.3*MeV;\n  a_parameter = 0.2*MeV;\n  b_parameter = 0.1/MeV;\n  restriction_energy = 0.25*MeV;\n\n  sample = Utility::UnitAwareWattDistribution<MegaElectronVolt>::sample( incident_energy, a_parameter, b_parameter, restriction_energy );\n  UTILITY_TEST_FLOATING_EQUALITY( sample, 0.04844237604136*MeV, 1e-13 );\n  \n  Utility::RandomNumberGenerator::unsetFakeStream();\n}\n\n//---------------------------------------------------------------------------//\n// Check that the distribution can be sampled using OpenMC method, passing in\n// parameters\nTEUCHOS_UNIT_TEST( WattDistribution, sampleAndRecordTrials_pass_parameters )\n{\n  std::vector<double> fake_stream( 15 );\n  fake_stream[0] = 0.6617443503056450; // Maxwellian Distribution\n  fake_stream[1] = 0.8510592242616175; // Sample Accepted. Sample is:\n  fake_stream[2] = 0.5401745197210969; // 0.09667248521245\n  fake_stream[3] = 0.2005969462099806; // Watt Distribution Sample Accepted. Sample is: 0.07927727029875\n  fake_stream[4] = 0.5189418543931951; // Maxwellian Distribution\n  fake_stream[5] = 0.7484231272861934; // Sample Rejected. Sample is:\n  fake_stream[6] = 0.8345865134048199; // 0.13501824430785\n  fake_stream[7] = 0.8704061668810904; // Maxwellian Distribution\n  fake_stream[8] = 0.5575773053122431; // Sample Accepted. Sample is:\n  fake_stream[9] = 0.7452925729418971; // 0.04548390223293\n  fake_stream[10] = 0.6556974287666129; // Watt Distribution Sample Rejected. Sample is: 0.05068410532744\n  fake_stream[11] = 0.8140855348977614; // Maxwellian Distribution\n  fake_stream[12] = 0.5750169688125915; // Sample Accepted. Sample is:\n  fake_stream[13] = 0.8372435273691630; // 0.04821527540845\n  fake_stream[14] = 0.4721727279140688; // Watt Distribution Sample Accepted. Sample is: 0.04844237604136\n\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n  \n  double incident_energy, a_parameter, b_parameter, restriction_energy, sample;\n  unsigned trials = 0;\n  \n  incident_energy = 0.5;\n  a_parameter = 0.2;\n  b_parameter = 0.3;\n  restriction_energy = 0.4;\n\n  sample = Utility::WattDistribution::sampleAndRecordTrials(incident_energy, a_parameter, b_parameter, restriction_energy, trials);\n  TEST_FLOATING_EQUALITY( sample, 0.07927727029875, 1e-13 );\n  TEST_EQUALITY_CONST( trials, 1.0 );\n  \n  incident_energy = 0.3;\n  a_parameter = 0.2;\n  b_parameter = 0.1;\n  restriction_energy = 0.25;\n\n  sample = Utility::WattDistribution::sampleAndRecordTrials(incident_energy, a_parameter, b_parameter, restriction_energy, trials);\n  TEST_FLOATING_EQUALITY( sample, 0.04844237604136, 1e-13 );\n  TEST_EQUALITY_CONST( trials, 4.0 );\n\n  Utility::RandomNumberGenerator::unsetFakeStream();\n}\n\n//---------------------------------------------------------------------------//\n// Check that the unit-aware distribution can be sampled using OpenMC method, \n// passing in parameters\nTEUCHOS_UNIT_TEST( UnitAwareWattDistribution, \n\t\t   sampleAndRecordTrials_pass_parameters )\n{\n  std::vector<double> fake_stream( 15 );\n  fake_stream[0] = 0.6617443503056450; // Maxwellian Distribution\n  fake_stream[1] = 0.8510592242616175; // Sample Accepted. Sample is:\n  fake_stream[2] = 0.5401745197210969; // 0.09667248521245\n  fake_stream[3] = 0.2005969462099806; // Watt Distribution Sample Accepted. Sample is: 0.07927727029875\n  fake_stream[4] = 0.5189418543931951; // Maxwellian Distribution\n  fake_stream[5] = 0.7484231272861934; // Sample Rejected. Sample is:\n  fake_stream[6] = 0.8345865134048199; // 0.13501824430785\n  fake_stream[7] = 0.8704061668810904; // Maxwellian Distribution\n  fake_stream[8] = 0.5575773053122431; // Sample Accepted. Sample is:\n  fake_stream[9] = 0.7452925729418971; // 0.04548390223293\n  fake_stream[10] = 0.6556974287666129; // Watt Distribution Sample Rejected. Sample is: 0.05068410532744\n  fake_stream[11] = 0.8140855348977614; // Maxwellian Distribution\n  fake_stream[12] = 0.5750169688125915; // Sample Accepted. Sample is:\n  fake_stream[13] = 0.8372435273691630; // 0.04821527540845\n  fake_stream[14] = 0.4721727279140688; // Watt Distribution Sample Accepted. Sample is: 0.04844237604136\n\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  Utility::UnitAwareOneDDistribution<MegaElectronVolt,si::amount>::IndepQuantity incident_energy, a_parameter, restriction_energy, sample;\n  \n  Utility::UnitAwareOneDDistribution<MegaElectronVolt,si::amount>::InverseIndepQuantity b_parameter;\n\n  unsigned trials = 0;\n  \n  incident_energy = 0.5*MeV;\n  a_parameter = 0.2*MeV;\n  b_parameter = 0.3/MeV;\n  restriction_energy = 0.4*MeV;\n\n  sample = Utility::UnitAwareWattDistribution<MegaElectronVolt,si::amount>::sampleAndRecordTrials(incident_energy, a_parameter, b_parameter, restriction_energy, trials);\n  UTILITY_TEST_FLOATING_EQUALITY( sample, 0.07927727029875*MeV, 1e-13 );\n  TEST_EQUALITY_CONST( trials, 1.0 );\n  \n  incident_energy = 0.3*MeV;\n  a_parameter = 0.2*MeV;\n  b_parameter = 0.1/MeV;\n  restriction_energy = 0.25*MeV;\n\n  sample = Utility::UnitAwareWattDistribution<MegaElectronVolt,si::amount>::sampleAndRecordTrials(incident_energy, a_parameter, b_parameter, restriction_energy, trials);\n  UTILITY_TEST_FLOATING_EQUALITY( sample, 0.04844237604136*MeV, 1e-13 );\n  TEST_EQUALITY_CONST( trials, 4.0 );\n\n  Utility::RandomNumberGenerator::unsetFakeStream();\n}\n\n//---------------------------------------------------------------------------//\n// Check that the upper bound of the distribution independent variable can be\n// returned\nTEUCHOS_UNIT_TEST( WattDistribution, getUpperBoundOfIndepVar )\n{\n  TEST_EQUALITY_CONST( distribution->getUpperBoundOfIndepVar(), 0.9 );\n}\n\n//---------------------------------------------------------------------------//\n// Check that the upper bound of the unit-aware distribution independent \n// variable can be returned\nTEUCHOS_UNIT_TEST( UnitAwareWattDistribution, getUpperBoundOfIndepVar )\n{\n  TEST_EQUALITY_CONST( unit_aware_distribution->getUpperBoundOfIndepVar(), \n\t\t       0.9*MeV );\n}\n\n//---------------------------------------------------------------------------//\n// Check that the lower bound of the distribution independent variable can be\n// returned\nTEUCHOS_UNIT_TEST( WattDistribution, getLowerBoundOfIndepVar )\n{\n  TEST_EQUALITY_CONST( distribution->getLowerBoundOfIndepVar(), 0.0 );\n}\n\n//---------------------------------------------------------------------------//\n// Check that the lower bound of the unit-aware distribution independent \n// variable can be returned\nTEUCHOS_UNIT_TEST( UnitAwareWattDistribution, getLowerBoundOfIndepVar )\n{\n  TEST_EQUALITY_CONST( unit_aware_distribution->getLowerBoundOfIndepVar(), \n\t\t       0.0*MeV );\n}\n\n//---------------------------------------------------------------------------//\n// Check that the distribution type can be returned\nTEUCHOS_UNIT_TEST( WattDistribution, getDistributionType )\n{\n  TEST_EQUALITY_CONST( distribution->getDistributionType(),\n\t\t       Utility::WATT_DISTRIBUTION );\n}\n\n//---------------------------------------------------------------------------//\n// Check that the unit-aware distribution type can be returned\nTEUCHOS_UNIT_TEST( UnitAwareWattDistribution, getDistributionType )\n{\n  TEST_EQUALITY_CONST( unit_aware_distribution->getDistributionType(),\n\t\t       Utility::WATT_DISTRIBUTION );\n}\n\n//---------------------------------------------------------------------------//\n// Check if the distribution is tabular\nTEUCHOS_UNIT_TEST( WattDistribution, isTabular )\n{\n  TEST_ASSERT( !distribution->isTabular() );\n}\n\n//---------------------------------------------------------------------------//\n// Check if the unit-aware distribution is tabular\nTEUCHOS_UNIT_TEST( UnitAwareWattDistribution, isTabular )\n{\n  TEST_ASSERT( !unit_aware_distribution->isTabular() );\n}\n\n//---------------------------------------------------------------------------//\n// Check if the distribution is continuous\nTEUCHOS_UNIT_TEST( WattDistribution, isContinuous )\n{\n  TEST_ASSERT( distribution->isContinuous() );\n}\n\n//---------------------------------------------------------------------------//\n// Check if the unit-aware distribution is continuous\nTEUCHOS_UNIT_TEST( UnitAwareWattDistribution, isContinuous )\n{\n  TEST_ASSERT( unit_aware_distribution->isContinuous() );\n}\n\n//---------------------------------------------------------------------------//\n// Check that the distribution can be written to an xml file\nTEUCHOS_UNIT_TEST( WattDistribution, toParameterList )\n{\n  Teuchos::RCP<Utility::WattDistribution> true_distribution =\n  Teuchos::rcp_dynamic_cast<Utility::WattDistribution>( distribution );\n  \n  Teuchos::ParameterList parameter_list;\n  \n  parameter_list.set<Utility::WattDistribution>( \"test distribution\",\n                                                  *true_distribution );\n  \n  Teuchos::writeParameterListToXmlFile( parameter_list,\n                                       \"watt_dist_test_list.xml\" );\n  \n  Teuchos::RCP<Teuchos::ParameterList> read_parameter_list =\n  Teuchos::getParametersFromXmlFile( \"watt_dist_test_list.xml\" );\n\n  TEST_EQUALITY( parameter_list, *read_parameter_list );\n  \n  Teuchos::RCP<Utility::WattDistribution>\n  copy_distribution( new Utility::WattDistribution );\n  \n  *copy_distribution = read_parameter_list->get<Utility::WattDistribution>(\n                                                                             \"test distribution\");\n  \n  TEST_EQUALITY( *copy_distribution, *true_distribution );\n}\n\n//---------------------------------------------------------------------------//\n// Check that the unit-aware distribution can be written to an xml file\nTEUCHOS_UNIT_TEST( UnitAwareWattDistribution, toParameterList )\n{\n  typedef Utility::UnitAwareWattDistribution<MegaElectronVolt,si::amount> UnitAwareWattDistribution;\n  \n  Teuchos::RCP<UnitAwareWattDistribution> true_distribution =\n  Teuchos::rcp_dynamic_cast<UnitAwareWattDistribution>( unit_aware_distribution );\n  \n  Teuchos::ParameterList parameter_list;\n  \n  parameter_list.set<UnitAwareWattDistribution>( \"test distribution\",\n                                                  *true_distribution );\n  \n  Teuchos::writeParameterListToXmlFile( parameter_list,\n                                       \"unit_aware_watt_dist_test_list.xml\" );\n  \n  Teuchos::RCP<Teuchos::ParameterList> read_parameter_list =\n  Teuchos::getParametersFromXmlFile( \"unit_aware_watt_dist_test_list.xml\" );\n\n  TEST_EQUALITY( parameter_list, *read_parameter_list );\n  \n  Teuchos::RCP<UnitAwareWattDistribution>\n  copy_distribution( new UnitAwareWattDistribution );\n  \n  *copy_distribution = read_parameter_list->get<UnitAwareWattDistribution>(\n\t\t\t\t\t\t\t \"test distribution\" );\n  \n  TEST_EQUALITY( *copy_distribution, *true_distribution );\n}\n\n//---------------------------------------------------------------------------//\n// Check that the distribution can be read from an xml file\nTEUCHOS_UNIT_TEST( WattDistribution, fromParameterList )\n{\n  double test_value_1;\n  double test_value_2;\n\n  Utility::WattDistribution read_distribution = \n    test_dists_list->get<Utility::WattDistribution>( \"Watt Distribution A\" );\n\n  test_value_1 = 0.0 ;\n  test_value_2 = 0.25 * sqrt( Utility::PhysicalConstants::pi ) * exp( 0.25 ) * ( erf( sqrt(0.9) - sqrt(0.25) ) + erf( sqrt(0.9) + sqrt(0.25) ) ) - exp( -0.9 ) * sinh( sqrt(0.9) );\n  test_value_2 = pow( test_value_2, -1.0 ) * exp( -1.0 ) * sinh( 1.0 );\n  \n  TEST_EQUALITY_CONST( read_distribution.evaluatePDF( 0.0 ), test_value_1 );\n  TEST_FLOATING_EQUALITY( read_distribution.evaluatePDF( 1.0 ), \n\t\t\t  test_value_2,\n\t\t\t  1e-15 );\n\n   read_distribution = \n    test_dists_list->get<Utility::WattDistribution>( \"Watt Distribution B\" );\n\n  test_value_1 = 0.0 ;\n  test_value_2 = 0.25 * sqrt( Utility::PhysicalConstants::pi * pow( 2.0, 3.0 ) * 1.0 )\n    * exp( 0.25 * 2.0 ) * ( erf( sqrt( 1.5 ) - sqrt( 0.25 * 2.0 ) )\n    + erf( sqrt( 1.5 ) + sqrt( 0.25 * 2.0 ) ) )\n    - 2.0 * exp( - 1.5 ) * sinh( sqrt( 3.0 ) );\n  test_value_2 = pow( test_value_2, -1.0 ) * exp( -0.5 ) * sinh( 1.0 );\n \n  TEST_EQUALITY_CONST( read_distribution.evaluatePDF( 0.0 ), test_value_1 );\n  TEST_FLOATING_EQUALITY( read_distribution.evaluatePDF( 1.0 ), \n\t\t\t  test_value_2,\n\t\t\t  1e-15 );\n\n}\n\n//---------------------------------------------------------------------------//\n// Check that the unit-aware distribution can be read from an xml file\nTEUCHOS_UNIT_TEST( UnitAwareWattDistribution, fromParameterList )\n{\n  typedef Utility::UnitAwareWattDistribution<MegaElectronVolt,si::amount> UnitAwareWattDistribution;\n  \n  double scale_factor;\n  scale_factor = exp( -1.0 )*sinh( 1.0 );\n  scale_factor /= 0.25*sqrt( Utility::PhysicalConstants::pi )*exp( 0.25 )*\n    ( erf( sqrt(0.9) - sqrt(0.25) ) + \n      erf( sqrt(0.9) + sqrt(0.25) ) ) - exp( -0.9 ) * sinh( sqrt(0.9) );\n\n  UnitAwareWattDistribution read_distribution = \n    test_dists_list->get<UnitAwareWattDistribution>( \"Unit-Aware Watt Distribution A\" );\n  \n  TEST_EQUALITY_CONST( read_distribution.evaluate( 0.0*MeV ), 0.0*si::mole );\n  UTILITY_TEST_FLOATING_EQUALITY( read_distribution.evaluate( 1.0*MeV ), \n\t\t\t\t  exp( -1.0 )*sinh( 1.0 )*si::mole,\n\t\t\t\t  1e-15 );\n  UTILITY_TEST_FLOATING_EQUALITY( read_distribution.evaluatePDF( 1.0*MeV ), \n\t\t\t\t  scale_factor/MeV,\n\t\t\t\t  1e-15 );\n\n  read_distribution = \n    test_dists_list->get<UnitAwareWattDistribution>( \"Unit-Aware Watt Distribution B\" );\n   \n   scale_factor = exp( -0.5 )*sinh( 1.0 ); \n   scale_factor /= 0.25*sqrt( Utility::PhysicalConstants::pi*pow( 2.0, 3.0 ) )*\n     exp( 0.25 * 2.0 )*( erf( sqrt( 1.5 ) - sqrt( 0.25 * 2.0 ) ) + \n\t\t\t erf( sqrt( 1.5 ) + sqrt( 0.25 * 2.0 ) ) ) - \n     2.0*exp( -1.5 )*sinh( sqrt( 3.0 ) );\n \n   TEST_EQUALITY_CONST( read_distribution.evaluate( 0.0*MeV ), 0.0*si::mole );\n   UTILITY_TEST_FLOATING_EQUALITY( read_distribution.evaluate( 1.0*MeV ), \n\t\t\t\t   2*exp( -0.5 )*sinh( 1.0 )*si::mole,\n\t\t\t\t   1e-15 );\n   UTILITY_TEST_FLOATING_EQUALITY( read_distribution.evaluatePDF( 1.0*MeV ), \n\t\t\t\t   scale_factor/MeV,\n\t\t\t\t   1e-15 );\n\n}\n\n//---------------------------------------------------------------------------//\n// Check that distributions can be scaled\nTEUCHOS_UNIT_TEST_TEMPLATE_4_DECL( UnitAwareWattDistribution,\n\t\t\t\t   explicit_conversion,\n\t\t\t\t   IndepUnitA,\n\t\t\t\t   DepUnitA,\n\t\t\t\t   IndepUnitB,\n\t\t\t\t   DepUnitB )\n{\n  typedef typename Utility::UnitTraits<IndepUnitA>::template GetQuantityType<double>::type IndepQuantityA;\n  typedef typename Utility::UnitTraits<typename Utility::UnitTraits<IndepUnitA>::InverseUnit>::template GetQuantityType<double>::type InverseIndepQuantityA;\n  \n  typedef typename Utility::UnitTraits<IndepUnitB>::template GetQuantityType<double>::type IndepQuantityB;\n  typedef typename Utility::UnitTraits<typename Utility::UnitTraits<IndepUnitB>::InverseUnit>::template GetQuantityType<double>::type InverseIndepQuantityB;\n  \n  typedef typename Utility::UnitTraits<DepUnitA>::template GetQuantityType<double>::type DepQuantityA;\n  typedef typename Utility::UnitTraits<DepUnitB>::template GetQuantityType<double>::type DepQuantityB;\n\n  // Copy from unitless distribution to distribution type A (static method)\n  Utility::UnitAwareWattDistribution<IndepUnitA,DepUnitA>\n    unit_aware_dist_a_copy = Utility::UnitAwareWattDistribution<IndepUnitA,DepUnitA>::fromUnitlessDistribution( *Teuchos::rcp_dynamic_cast<Utility::WattDistribution>( distribution ) );\n\n  // Copy from distribution type A to distribution type B (explicit cast)\n  Utility::UnitAwareWattDistribution<IndepUnitB,DepUnitB>\n    unit_aware_dist_b_copy( unit_aware_dist_a_copy );\n\n  IndepQuantityA indep_quantity_a = \n    Utility::QuantityTraits<IndepQuantityA>::initializeQuantity( 0.0 );\n  InverseIndepQuantityA inv_indep_quantity_a = \n    Utility::QuantityTraits<InverseIndepQuantityA>::initializeQuantity( 0.0 );\n  DepQuantityA dep_quantity_a = \n    Utility::QuantityTraits<DepQuantityA>::initializeQuantity( 0.0 );\n\n  IndepQuantityB indep_quantity_b( indep_quantity_a );\n  InverseIndepQuantityB inv_indep_quantity_b( inv_indep_quantity_a );\n  DepQuantityB dep_quantity_b( dep_quantity_a );\n\n  UTILITY_TEST_FLOATING_EQUALITY( \n\t\t\t   unit_aware_dist_a_copy.evaluate( indep_quantity_a ),\n\t\t\t   dep_quantity_a,\n\t\t\t   1e-15 );\n  UTILITY_TEST_FLOATING_EQUALITY( \n\t\t\tunit_aware_dist_a_copy.evaluatePDF( indep_quantity_a ),\n\t\t\tinv_indep_quantity_a,\n\t\t\t1e-15 );\n  UTILITY_TEST_FLOATING_EQUALITY( \n\t\t\t   unit_aware_dist_b_copy.evaluate( indep_quantity_b ),\n\t\t\t   dep_quantity_b,\n\t\t\t   1e-15 );\n  UTILITY_TEST_FLOATING_EQUALITY( \n\t\t\tunit_aware_dist_b_copy.evaluatePDF( indep_quantity_b ),\n\t\t\tinv_indep_quantity_b,\n\t\t\t1e-15 );\n\n  Utility::setQuantity( indep_quantity_a, 1.0 );\n  Utility::setQuantity( inv_indep_quantity_a,\n\t\t\texp(-1.0)*sinh(1.0)/\n\t\t\t(0.25*sqrt( Utility::PhysicalConstants::pi )* \n\t\t\t exp( 0.25 )*( erf( sqrt(0.9) - sqrt(0.25) ) + \n\t\t\t\t       erf( sqrt(0.9) + sqrt(0.25) ) ) - \n\t\t\t exp( -0.9 ) * sinh( sqrt(0.9) )) );\n  Utility::setQuantity( dep_quantity_a, \n\t\t\texp(-1.0)*sinh(1.0) );\n  \n  indep_quantity_b = IndepQuantityB( indep_quantity_a );\n  inv_indep_quantity_b = InverseIndepQuantityB( inv_indep_quantity_a );\n  dep_quantity_b = DepQuantityB( dep_quantity_a );\n\n  UTILITY_TEST_FLOATING_EQUALITY( \n\t\t\t   unit_aware_dist_a_copy.evaluate( indep_quantity_a ),\n\t\t\t   dep_quantity_a,\n\t\t\t   1e-15 );\n  UTILITY_TEST_FLOATING_EQUALITY( \n\t\t\tunit_aware_dist_a_copy.evaluatePDF( indep_quantity_a ),\n\t\t\tinv_indep_quantity_a,\n\t\t\t1e-15 );\n  UTILITY_TEST_FLOATING_EQUALITY( \n\t\t\t   unit_aware_dist_b_copy.evaluate( indep_quantity_b ),\n\t\t\t   dep_quantity_b,\n\t\t\t   1e-15 );\n  UTILITY_TEST_FLOATING_EQUALITY( \n\t\t\tunit_aware_dist_b_copy.evaluatePDF( indep_quantity_b ),\n\t\t\tinv_indep_quantity_b,\n\t\t\t1e-15 );\n}\n\ntypedef si::energy si_energy;\ntypedef cgs::energy cgs_energy;\ntypedef si::amount si_amount;\ntypedef si::length si_length;\ntypedef cgs::length cgs_length;\ntypedef si::mass si_mass;\ntypedef cgs::mass cgs_mass;\ntypedef si::dimensionless si_dimensionless;\ntypedef cgs::dimensionless cgs_dimensionless;\n\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareWattDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      si_energy,\n\t\t\t\t      si_amount,\n\t\t\t\t      cgs_energy,\n\t\t\t\t      si_amount );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareWattDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      cgs_energy,\n\t\t\t\t      si_amount,\n\t\t\t\t      si_energy,\n\t\t\t\t      si_amount );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareWattDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      si_energy,\n\t\t\t\t      si_length,\n\t\t\t\t      cgs_energy,\n\t\t\t\t      cgs_length );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareWattDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      cgs_energy,\n\t\t\t\t      cgs_length,\n\t\t\t\t      si_energy,\n\t\t\t\t      si_length );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareWattDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      si_energy,\n\t\t\t\t      si_mass,\n\t\t\t\t      cgs_energy,\n\t\t\t\t      cgs_mass );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareWattDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      cgs_energy,\n\t\t\t\t      cgs_mass,\n\t\t\t\t      si_energy,\n\t\t\t\t      si_mass );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareWattDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      si_energy,\n\t\t\t\t      si_dimensionless,\n\t\t\t\t      cgs_energy,\n\t\t\t\t      cgs_dimensionless );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareWattDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      cgs_energy,\n\t\t\t\t      cgs_dimensionless,\n\t\t\t\t      si_energy,\n\t\t\t\t      si_dimensionless );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareWattDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      si_energy,\n\t\t\t\t      void,\n\t\t\t\t      cgs_energy,\n\t\t\t\t      void );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareWattDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      cgs_energy,\n\t\t\t\t      void,\n\t\t\t\t      si_energy,\n\t\t\t\t      void );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareWattDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      ElectronVolt,\n\t\t\t\t      si_amount,\n\t\t\t\t      si_energy,\n\t\t\t\t      si_amount );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareWattDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      ElectronVolt,\n\t\t\t\t      si_amount,\n\t\t\t\t      cgs_energy,\n\t\t\t\t      si_amount );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareWattDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      ElectronVolt,\n\t\t\t\t      si_amount,\n\t\t\t\t      KiloElectronVolt,\n\t\t\t\t      si_amount );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareWattDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      ElectronVolt,\n\t\t\t\t      si_amount,\n\t\t\t\t      MegaElectronVolt,\n\t\t\t\t      si_amount );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareWattDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      KiloElectronVolt,\n\t\t\t\t      si_amount,\n\t\t\t\t      si_energy,\n\t\t\t\t      si_amount );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareWattDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      KiloElectronVolt,\n\t\t\t\t      si_amount,\n\t\t\t\t      cgs_energy,\n\t\t\t\t      si_amount );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareWattDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      KiloElectronVolt,\n\t\t\t\t      si_amount,\n\t\t\t\t      ElectronVolt,\n\t\t\t\t      si_amount );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareWattDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      KiloElectronVolt,\n\t\t\t\t      si_amount,\n\t\t\t\t      MegaElectronVolt,\n\t\t\t\t      si_amount );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareWattDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      MegaElectronVolt,\n\t\t\t\t      si_amount,\n\t\t\t\t      si_energy,\n\t\t\t\t      si_amount );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareWattDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      MegaElectronVolt,\n\t\t\t\t      si_amount,\n\t\t\t\t      cgs_energy,\n\t\t\t\t      si_amount );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareWattDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      MegaElectronVolt,\n\t\t\t\t      si_amount,\n\t\t\t\t      ElectronVolt,\n\t\t\t\t      si_amount );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareWattDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      MegaElectronVolt,\n\t\t\t\t      si_amount,\n\t\t\t\t      KiloElectronVolt,\n\t\t\t\t      si_amount );\nTEUCHOS_UNIT_TEST_TEMPLATE_4_INSTANT( UnitAwareWattDistribution,\n\t\t\t\t      explicit_conversion,\n\t\t\t\t      void,\n\t\t\t\t      MegaElectronVolt,\n\t\t\t\t      void,\n\t\t\t\t      KiloElectronVolt );\n\n//---------------------------------------------------------------------------//\n// Custom main function\n//---------------------------------------------------------------------------//\nint main( int argc, char** argv )\n{\n  std::string test_dists_xml_file;\n\n  Teuchos::CommandLineProcessor& clp = Teuchos::UnitTestRepository::getCLP();\n\n  clp.setOption( \"test_dists_xml_file\",\n\t\t &test_dists_xml_file,\n\t\t \"Test distributions xml file name\" );\n  \n  const Teuchos::RCP<Teuchos::FancyOStream> out = \n    Teuchos::VerboseObjectBase::getDefaultOStream();\n\n  Teuchos::CommandLineProcessor::EParseCommandLineReturn parse_return = \n    clp.parse(argc,argv);\n\n  if ( parse_return != Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL ) {\n    *out << \"\\nEnd Result: TEST FAILED\" << std::endl;\n    return parse_return;\n  }\n\n  TEUCHOS_ADD_TYPE_CONVERTER( Utility::WattDistribution );\n  typedef Utility::UnitAwareWattDistribution<MegaElectronVolt,si::amount> UnitAwareWattDistribution;\n  TEUCHOS_ADD_TYPE_CONVERTER( UnitAwareWattDistribution );\n\n  test_dists_list = Teuchos::getParametersFromXmlFile( test_dists_xml_file );\n  \n  // Initialize the random number generator\n  Utility::RandomNumberGenerator::createStreams();\n  \n  // Run the unit tests\n  Teuchos::GlobalMPISession mpiSession( &argc, &argv );\n\n  const bool success = Teuchos::UnitTestRepository::runUnitTests(*out);\n\n  if (success)\n    *out << \"\\nEnd Result: TEST PASSED\" << std::endl;\n  else\n    *out << \"\\nEnd Result: TEST FAILED\" << std::endl;\n\n  clp.printFinalTimerSummary(out.ptr());\n\n  return (success ? 0 : 1);\n}\n\n//---------------------------------------------------------------------------//\n// end tstWattDistribution.cpp\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "451487d38cc364d74b150838512332e5d605e705", "size": 35326, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "packages/utility/distribution/test/tstWattDistribution.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/utility/distribution/test/tstWattDistribution.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/utility/distribution/test/tstWattDistribution.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": 41.0290360046, "max_line_length": 186, "alphanum_fraction": 0.6746588915, "num_tokens": 9497, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289835, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.45938115004992597}}
{"text": "#ifndef STAN_MATH_PRIM_SCAL_FUN_FMAX_HPP\n#define STAN_MATH_PRIM_SCAL_FUN_FMAX_HPP\n\n#include <stan/math/prim/meta.hpp>\n#include <stan/math/prim/scal/fun/is_nan.hpp>\n#include <boost/math/tools/promotion.hpp>\n\nnamespace stan {\nnamespace math {\n\n/**\n * Return the greater of the two specified arguments.  If one is\n * greater than the other, return not-a-number.\n *\n * @param x First argument.\n * @param y Second argument.\n * @return maximum of x or y and if one is NaN return the other\n */\ntemplate <typename T1, typename T2>\ninline typename boost::math::tools::promote_args<T1, T2>::type fmax(\n    const T1& x, const T2& y) {\n  if (is_nan(x))\n    return y;\n  if (is_nan(y))\n    return x;\n  return x > y ? x : y;\n}\n\n}  // namespace math\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "7858a38644c4824e7036731b24ae27e83019c9bb", "size": 762, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/prim/scal/fun/fmax.hpp", "max_stars_repo_name": "riddell-stan/math", "max_stars_repo_head_hexsha": "d84ee0d991400d6cf4b08a07a4e8d86e0651baea", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-07-23T14:57:41.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-23T14:57:41.000Z", "max_issues_repo_path": "stan/math/prim/scal/fun/fmax.hpp", "max_issues_repo_name": "Capri2014/math", "max_issues_repo_head_hexsha": "d4042bdf8623bba5a1633b557227325a324e32e9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-09-23T19:58:36.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-24T12:03:41.000Z", "max_forks_repo_path": "stan/math/prim/scal/fun/fmax.hpp", "max_forks_repo_name": "riddell-stan/math", "max_forks_repo_head_hexsha": "d84ee0d991400d6cf4b08a07a4e8d86e0651baea", "max_forks_repo_licenses": ["BSD-3-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.8125, "max_line_length": 68, "alphanum_fraction": 0.7007874016, "num_tokens": 216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289836, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.45938115004992597}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// BSD 3-Clause License\n//\n// Copyright (C) 2018-2020, LAAS-CNRS, The University of Edinburgh\n// Copyright note valid unless otherwise stated in individual files.\n// All rights reserved.\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef CROCODDYL_CORE_DIFF_ACTION_BASE_HPP_\n#define CROCODDYL_CORE_DIFF_ACTION_BASE_HPP_\n\n#include <stdexcept>\n#include <boost/shared_ptr.hpp>\n#include <boost/make_shared.hpp>\n#include \"crocoddyl/core/state-base.hpp\"\n#include \"crocoddyl/core/utils/to-string.hpp\"\n\nnamespace crocoddyl {\n\nstruct DifferentialActionDataAbstract;  // forward declaration\n\n/**\n * @brief This class DifferentialActionModelAbstract represents a first-order\n * ODE, i.e.\n * \\f[\n * \\mathbf{\\dot{v}} = \\mathbf{f}(\\mathbf{q}, \\mathbf{v}, \\boldsymbol{\\tau})\n * \\f]\n * where \\f$ xout = \\mathbf{\\dot{v}} \\f$ and represents the  acceleration of the\n * system. Note that Jacobians Fx and Fu in the\n * DifferentialActionDataAbstract are in \\f$ \\mathbb{R}^{nv\\times ndx} \\f$ and\n * \\f$ \\mathbb{R}^{nv\\times nu} \\f$, respectively.\n *\n * Then we use the acceleration to integrate the system, and as consequence we\n * obtain:\n * \\f[\n * \\mathbf{\\dot{x}} = (\\mathbf{v}, \\mathbf{\\dot{v}}) = \\mathbf{f}(\\mathbf{x},\\mathbf{u})\n * \\f]\n * where this \\f$ f \\f$ function is different to the other one.\n * So \\f$ xout \\f$ is interpreted here as \\f$ vdout \\f$ or \\f$ aout \\f$.\n */\nclass DifferentialActionModelAbstract {\n public:\n  DifferentialActionModelAbstract(boost::shared_ptr<StateAbstract> state, const std::size_t& nu,\n                                  const std::size_t& nr = 0);\n  virtual ~DifferentialActionModelAbstract();\n\n  virtual void calc(const boost::shared_ptr<DifferentialActionDataAbstract>& data,\n                    const Eigen::Ref<const Eigen::VectorXd>& x, const Eigen::Ref<const Eigen::VectorXd>& u) = 0;\n  virtual void calcDiff(const boost::shared_ptr<DifferentialActionDataAbstract>& data,\n                        const Eigen::Ref<const Eigen::VectorXd>& x, const Eigen::Ref<const Eigen::VectorXd>& u,\n                        const bool& recalc = true) = 0;\n  virtual boost::shared_ptr<DifferentialActionDataAbstract> createData();\n\n  void calc(const boost::shared_ptr<DifferentialActionDataAbstract>& data, const Eigen::Ref<const Eigen::VectorXd>& x);\n  void calcDiff(const boost::shared_ptr<DifferentialActionDataAbstract>& data,\n                const Eigen::Ref<const Eigen::VectorXd>& x);\n\n  const std::size_t& get_nu() const;\n  const std::size_t& get_nr() const;\n  const boost::shared_ptr<StateAbstract>& get_state() const;\n\n  const Eigen::VectorXd& get_u_lb() const;\n  const Eigen::VectorXd& get_u_ub() const;\n  bool const& get_has_control_limits() const;\n\n  void set_u_lb(const Eigen::VectorXd& u_lb);\n  void set_u_ub(const Eigen::VectorXd& u_ub);\n\n protected:\n  std::size_t nu_;                          //!< Control dimension\n  std::size_t nr_;                          //!< Dimension of the cost residual\n  boost::shared_ptr<StateAbstract> state_;  //!< Model of the state\n  Eigen::VectorXd unone_;                   //!< Neutral state\n  Eigen::VectorXd u_lb_;                    //!< Lower control limits\n  Eigen::VectorXd u_ub_;                    //!< Upper control limits\n  bool has_control_limits_;                 //!< Indicates whether any of the control limits is finite\n\n  void update_has_control_limits();\n\n#ifdef PYTHON_BINDINGS\n\n public:\n  void calc_wrap(const boost::shared_ptr<DifferentialActionDataAbstract>& data, const Eigen::VectorXd& x,\n                 const Eigen::VectorXd& u = Eigen::VectorXd()) {\n    if (u.size() == 0) {\n      calc(data, x);\n    } else {\n      calc(data, x, u);\n    }\n  }\n\n  void calcDiff_wrap(const boost::shared_ptr<DifferentialActionDataAbstract>& data, const Eigen::VectorXd& x,\n                     const Eigen::VectorXd& u, const bool& recalc) {\n    calcDiff(data, x, u, recalc);\n  }\n  void calcDiff_wrap(const boost::shared_ptr<DifferentialActionDataAbstract>& data, const Eigen::VectorXd& x,\n                     const Eigen::VectorXd& u) {\n    calcDiff(data, x, u, true);\n  }\n  void calcDiff_wrap(const boost::shared_ptr<DifferentialActionDataAbstract>& data, const Eigen::VectorXd& x) {\n    calcDiff(data, x, unone_, true);\n  }\n  void calcDiff_wrap(const boost::shared_ptr<DifferentialActionDataAbstract>& data, const Eigen::VectorXd& x,\n                     const bool& recalc) {\n    calcDiff(data, x, unone_, recalc);\n  }\n\n#endif\n};\n\nstruct DifferentialActionDataAbstract {\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n  template <typename Model>\n  explicit DifferentialActionDataAbstract(Model* const model)\n      : cost(0.),\n        xout(model->get_state()->get_nv()),\n        Fx(model->get_state()->get_nv(), model->get_state()->get_ndx()),\n        Fu(model->get_state()->get_nv(), model->get_nu()),\n        r(model->get_nr()),\n        Lx(model->get_state()->get_ndx()),\n        Lu(model->get_nu()),\n        Lxx(model->get_state()->get_ndx(), model->get_state()->get_ndx()),\n        Lxu(model->get_state()->get_ndx(), model->get_nu()),\n        Luu(model->get_nu(), model->get_nu()) {\n    xout.setZero();\n    r.setZero();\n    Fx.setZero();\n    Fu.setZero();\n    Lx.setZero();\n    Lu.setZero();\n    Lxx.setZero();\n    Lxu.setZero();\n    Luu.setZero();\n  }\n  virtual ~DifferentialActionDataAbstract() {}\n\n  double cost;\n  Eigen::VectorXd xout;\n  Eigen::MatrixXd Fx;\n  Eigen::MatrixXd Fu;\n  Eigen::VectorXd r;\n  Eigen::VectorXd Lx;\n  Eigen::VectorXd Lu;\n  Eigen::MatrixXd Lxx;\n  Eigen::MatrixXd Lxu;\n  Eigen::MatrixXd Luu;\n};\n\n}  // namespace crocoddyl\n\n#endif  // CROCODDYL_CORE_DIFF_ACTION_BASE_HPP_\n", "meta": {"hexsha": "492da1752d805f48829b02a55356741f5e363828", "size": 5684, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/crocoddyl/core/diff-action-base.hpp", "max_stars_repo_name": "Capri2014/crocoddyl", "max_stars_repo_head_hexsha": "341874fbad4507d6ed4e05e18e4a9cedf5470d01", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-04-25T13:17:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-25T13:17:23.000Z", "max_issues_repo_path": "include/crocoddyl/core/diff-action-base.hpp", "max_issues_repo_name": "Capri2014/crocoddyl", "max_issues_repo_head_hexsha": "341874fbad4507d6ed4e05e18e4a9cedf5470d01", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/crocoddyl/core/diff-action-base.hpp", "max_forks_repo_name": "Capri2014/crocoddyl", "max_forks_repo_head_hexsha": "341874fbad4507d6ed4e05e18e4a9cedf5470d01", "max_forks_repo_licenses": ["BSD-3-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.1503267974, "max_line_length": 119, "alphanum_fraction": 0.6439127375, "num_tokens": 1435, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.45938114349624176}}
{"text": "#include \"stdafx.h\"\n\n#include <cmath>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n#include <fmt/format.h>\n#include <nlohmann/json.hpp>\n\n#include \"contest_types.h\"\n#include \"judge.h\"\n#include \"solver_registry.h\"\n#include \"visual_editor.h\"\n\nnamespace OptunaAnnealingSolver {\n\n  namespace bg = boost::geometry;\n  using BoostPoint = bg::model::d2::point_xy<double>;\n  using BoostPolygon = bg::model::polygon<BoostPoint>;\n  using BoostLinestring = bg::model::linestring<BoostPoint>;\n\n  template <typename T>\n  void shrink(T& point_a, T& point_b) {\n    constexpr double eps = 1e-6;\n    auto shrink_a = point_a * (1.0 - eps) + point_b * eps;\n    auto shrink_b = point_b * (1.0 - eps) + point_a * eps;\n    point_a = shrink_a;\n    point_b = shrink_b;\n  }\n\n  template <typename T>\n  BoostPoint ToBoostPoint(const T& point) {\n    const auto [x, y] = point;\n    return BoostPoint(x, y);\n  }\n\n  template <typename T>\n  BoostPolygon ToBoostPolygon(const std::vector<T>& points) {\n    BoostPolygon polygon;\n    for (std::size_t i = 0; i <= points.size(); ++i) {\n      polygon.outer().push_back(ToBoostPoint(points[i % points.size()]));\n    }\n    if (bg::area(polygon) < 0.0) {\n      bg::reverse(polygon);\n    }\n    return polygon;\n  }\n\n  template <typename T, typename U>\n  double SquaredDistance(const T& vertex0, const U& vertex1) {\n    const auto [x0, y0] = vertex0;\n    const auto [x1, y1] = vertex1;\n    return (x0 - x1) * (x0 - x1) + (y0 - y1) * (y0 - y1);\n  }\n\n  template <typename T>\n  double SquaredEdgeLength(const T& vertices, const Edge& edge) {\n    const auto [a, b] = edge;\n    return SquaredDistance(vertices[a], vertices[b]);\n  }\n\n  class Solver : public SolverBase {\n  public:\n    SolverOutputs solve(const SolverArguments& args) override {\n      hole_ = args.problem->hole_polygon;\n      vertices_ = args.problem->vertices;\n      edges_ = args.problem->edges;\n      epsilon_ = args.problem->epsilon;\n      hole_polygon_ = ToBoostPolygon(hole_);\n\n      // \u30d1\u30e9\u30e1\u30fc\u30bf\u30fc\u30d5\u30a1\u30a4\u30eb\u3092\u8aad\u307f\u8fbc\u3080\n      std::ifstream ifs;\n      // \u5b9f\u884c\u30d0\u30a4\u30ca\u30ea\u3068\u540c\u3058\u30d5\u30a9\u30eb\u30c0\u304b\u3089\u8aad\u307f\u8fbc\u3080\n      ifs.open(args.parameters_file_path);\n      CHECK(ifs);\n      ifs >> parameters_;\n\n      SVisualEditorPtr editor;\n      if (args.visualize) {\n        editor = std::make_shared<SVisualEditor>(args.problem, \"OptunaAnnealingSolver\", \"visualize\");\n      }\n\n      const int N = vertices_.size();\n      auto pose = vertices_;\n      double cost = std::numeric_limits<double>::infinity();\n      double best_feasible_cost = std::numeric_limits<double>::infinity();\n      std::vector<Point> best_feasible_pose;\n\n      const int num_iters = 100000;\n      const double T0 = parameters_[\"T0\"]; // 10.0 1.0-100.0 log\n      const double T1 = parameters_[\"T1\"]; // 0.01 0.001-0.1 log\n      double progress = 0.0;\n\n      integer ymin = INT_MAX, ymax = INT_MIN;\n      integer xmin = INT_MAX, xmax = INT_MIN;\n      for (auto p : hole_) {\n        xmin = std::min(xmin, get_x(p));\n        ymin = std::min(ymin, get_y(p));\n        xmax = std::max(xmax, get_x(p));\n        ymax = std::max(ymax, get_y(p));\n      }\n\n      // lesser version of tonagi's idea \n      const int initialize_pose_by_hole = parameters_[\"initialize_pose_by_hole\"]; // 0 0-1\n      if (initialize_pose_by_hole) {\n        for (auto& p : pose) { p = hole_[0]; }\n      }\n\n      const int prohibit_unfeasible_after_feasible = parameters_[\"prohibit_unfeasible_after_feasible\"]; // 0 0-1\n      auto evaluate_and_descide_rollback = [&]() -> bool {\n        auto [feasible, updated_cost] = Evaluate(pose);\n\n        // tonagi's idea.\n        if (prohibit_unfeasible_after_feasible || !best_feasible_pose.empty()) {\n          auto res = judge(*args.problem, pose);\n          if (!res.fit_in_hole()) {\n            feasible = false;\n            updated_cost = DBL_MAX;\n          }\n        }\n\n#if 0\n        auto judge_valid = judge(*args.problem, pose).is_valid();\n        if (feasible != judge_valid) {\n          LOG(INFO) << feasible << \" \" << judge_valid;\n          if (editor) {\n            editor->set_pose(args.problem->create_solution(pose));\n            while (true) {\n              int c = editor->show(1);\n              if (c == 27) break;\n            }\n          }\n        }\n#endif\n\n        if (feasible && updated_cost < best_feasible_cost) {\n          best_feasible_cost = updated_cost;\n          best_feasible_pose = pose;\n          if (editor) editor->set_persistent_custom_stat(fmt::format(\"best_cost = {}\", best_feasible_cost));\n        }\n        const double T = std::pow(T0, 1.0 - progress) * std::pow(T1, progress);\n        if (std::uniform_real_distribution(0.0, 1.0)(rng_) < std::exp(-(updated_cost - cost) / T)) {\n          cost = updated_cost;\n          return false; // accepted\n        }\n        else {\n          return true; // rejected\n        }\n      };\n      evaluate_and_descide_rollback();\n\n      const int single_small_change_max_delta = parameters_[\"single_small_change_max_delta\"]; // 1 1-5\n      auto single_small_change = [&] { // ynasu87 original\n        const int v = std::uniform_int_distribution(0, N - 1)(rng_);\n        const int dx = std::uniform_int_distribution(-single_small_change_max_delta, single_small_change_max_delta)(rng_);\n        const int dy = std::uniform_int_distribution(-single_small_change_max_delta, single_small_change_max_delta)(rng_);\n        auto& [x, y] = pose[v];\n        x += dx;\n        y += dy;\n        if (evaluate_and_descide_rollback()) {\n          x -= dx;\n          y -= dy;\n        }\n      };\n\n      const int shift_max_delta = parameters_[\"shift_max_delta\"]; // 1 1-5\n      auto shift = [&] {\n        const int dx = std::uniform_int_distribution(-shift_max_delta, shift_max_delta)(rng_);\n        const int dy = std::uniform_int_distribution(-shift_max_delta, shift_max_delta)(rng_);\n        auto pose_bak = pose;\n        for (auto& p : pose) {\n          p.first += dx;\n          p.second += dy;\n        }\n        if (evaluate_and_descide_rollback()) {\n          pose = pose_bak;\n        }\n      };\n\n      const double slight_rotate_max_deg = parameters_[\"slight_rotate_max_deg\"]; // 2.0 1.0-180.0\n      auto slight_rotate = [&] {\n        const double deg = std::uniform_real_distribution(-slight_rotate_max_deg, slight_rotate_max_deg)(rng_);\n        auto pose_bak = pose;\n\n        integer curr_ymin = INT_MAX, curr_ymax = INT_MIN;\n        integer curr_xmin = INT_MAX, curr_xmax = INT_MIN;\n        for (auto p : hole_) {\n          curr_xmin = std::min(curr_xmin, get_x(p));\n          curr_ymin = std::min(curr_ymin, get_y(p));\n          curr_xmax = std::max(curr_xmax, get_x(p));\n          curr_ymax = std::max(curr_ymax, get_y(p));\n        }\n\n        const double cx = double(curr_xmin + curr_xmax) / 2;\n        const double cy = double(curr_ymin + curr_ymax) / 2;\n        const double sin = std::sin(deg * 3.1415 / 180.0);\n        const double cos = std::cos(deg * 3.1415 / 180.0);\n        for (auto& p : pose) {\n          const double dx = p.first - cx;\n          const double dy = p.second - cy;\n          p.first = std::round(dx * cos - dy * sin + cx);\n          p.second = std::round(dx * sin + dy * cos + cy);\n        }\n        if (evaluate_and_descide_rollback()) {\n          pose = pose_bak;\n        }\n      };\n\n      auto flip = [&] { // from FlipAnnealingSolver\n        const int v0 = std::uniform_int_distribution(0, N - 1)(rng_);\n        const int v1 = std::uniform_int_distribution(0, N - 1)(rng_);\n        if (v0 == v1) return;\n        auto pose_bak = pose;\n        auto reflect = [](Point a, Point c, Point v) {\n          return v - 2 * double(dot(v - c, a)) / double(dot(a, a)) * a;\n        };\n        auto diff = pose[v1] - pose[v0];\n        Point n = { get_y(diff), -get_x(diff) };\n        for (int v2 = 0; v2 < pose.size(); ++v2) {\n          if (ccw(pose[v0], pose[v1], pose[v2])) {\n            pose[v2] = reflect(n, pose[v0], pose[v2]);\n          }\n        }\n        if (evaluate_and_descide_rollback()) {\n          pose = pose_bak;\n        }\n      };\n\n      const double vote_pow = parameters_[\"vote_pow\"]; // 5.0 1.0-5.0\n      auto edges_cache = edges_from_vertex(*args.problem);\n      std::vector<std::vector<int> > good_pos(ymax - ymin + 1, std::vector<int>(xmax - xmin + 1));\n      std::vector<double> pow_table;\n      for (int i = 0; i < 1024; ++i) {\n        pow_table.push_back(std::pow(static_cast<double>(i), vote_pow));\n      }\n\n      auto hop_grid = [&] { // jump to a tolerated (by at least one edge) point.\n        const int pivot = std::uniform_int_distribution(0, N - 1)(rng_);\n        const auto pivot_bak = pose[pivot];\n        const auto& edges = edges_cache[pivot];\n        for (auto& row : good_pos) {\n          fill(row.begin(), row.end(), 0);\n        }\n        for (auto eid : edges) {\n          auto [u, v] = args.problem->edges[eid];\n          const int counter_vid = u == pivot ? v : u;\n          const auto org_d2 = distance2(args.problem->vertices[pivot], args.problem->vertices[counter_vid]);\n          for (int y = ymin; y <= ymax; ++y) {\n            for (int x = xmin; x <= xmax; ++x) {\n              const auto moved_d2 = distance2({ x, y }, pose[counter_vid]);\n              if (tolerate(org_d2, moved_d2, epsilon_)) {\n                ++good_pos[y - ymin][x - xmin];\n              }\n            }\n          }\n        }\n        // emphasize large votes.\n        double total_votes = 0;\n        for (int y = ymin; y <= ymax; ++y) {\n          for (int x = xmin; x <= xmax; ++x) {\n            total_votes += pow_table[good_pos[y - ymin][x - xmin]];\n          }\n        }\n        const double select_accum_vote = std::uniform_real_distribution<double>(0.0, total_votes)(rng_);\n        double accum_vote = 0;\n        bool found = false;\n        for (int y = ymin; !found && y <= ymax; ++y) {\n          for (int x = xmin; !found && x <= xmax; ++x) {\n            accum_vote += pow_table[good_pos[y - ymin][x - xmin]];\n            if (select_accum_vote <= accum_vote) {\n              pose[pivot] = {x, y};\n              found = true;\n            }\n          }\n        }\n        if (evaluate_and_descide_rollback()) {\n          pose[pivot] = pivot_bak;\n        }\n      };\n\n      // \u306f\u307f\u51fa\u3057\u3066\u3044\u308b\u7dda\u5206\u3092\u79fb\u52d5\u3055\u305b\u308b\n      const int slide_protrusion_max_delta = parameters_[\"slide_protrusion_max_delta\"]; // 1 1-5\n      auto slide_protrusion = [&] { // from OptunaAnnealingSolver\n        bool found = false;\n        int vertex_index_backup[2];\n        Point vertex_backup[2];\n        for (const auto& edge : edges_) {\n          const auto [a, b] = edge;\n          Point2d pa = pose[a];\n          Point2d pb = pose[b];\n          shrink(pa, pb);\n          const auto boost_point_a = ToBoostPoint(pa);\n          const auto boost_point_b = ToBoostPoint(pb);\n          BoostLinestring linestring{ boost_point_a, boost_point_b };\n          std::vector<BoostLinestring> differences;\n          bg::difference(linestring, hole_polygon_, differences);\n          if (differences.empty()) {\n            continue;\n          }\n\n          found = true;\n          vertex_index_backup[0] = a;\n          vertex_index_backup[1] = b;\n          vertex_backup[0] = pose[a];\n          vertex_backup[1] = pose[b];\n\n          pose[a].first += std::uniform_int_distribution(-slide_protrusion_max_delta, slide_protrusion_max_delta)(rng_);\n          pose[a].second += std::uniform_int_distribution(-slide_protrusion_max_delta, slide_protrusion_max_delta)(rng_);\n          pose[b].first += std::uniform_int_distribution(-slide_protrusion_max_delta, slide_protrusion_max_delta)(rng_);\n          pose[b].second += std::uniform_int_distribution(-slide_protrusion_max_delta, slide_protrusion_max_delta)(rng_);\n\n          break;\n        }\n\n        if (found) {\n          if (evaluate_and_descide_rollback()) {\n            pose[vertex_index_backup[0]] = vertex_backup[0];\n            pose[vertex_index_backup[1]] = vertex_backup[1];\n          }\n        }\n      };\n\n      using Action = std::function<void()>;\n      const double single_small_change_probability = parameters_[\"single_small_change_probability\"]; // 0.9 0.0-1.0\n      const double slight_rotate_probability = parameters_[\"slight_rotate_probability\"]; // 0.01 0.0-1.0\n      const double shift_probability = parameters_[\"shift_probability\"]; // 0.01 0.0-1.0\n      const double hop_grid_probability = parameters_[\"hop_grid_probability\"]; // 0.01 0.0-1.0\n      const double flip_probability = parameters_[\"flip_probability\"]; // 0.03 0.0-1.0\n      const double slide_protrusion_probability = parameters_[\"slide_protrusion_probability\"]; // 0.10 0.0-1.0\n      std::vector<std::pair<double, Action>> action_probs = {\n        {single_small_change_probability, single_small_change},\n        {slight_rotate_probability, slight_rotate},\n        {shift_probability, shift},\n        {hop_grid_probability, hop_grid},\n        {flip_probability, flip},\n        {slide_protrusion_probability, slide_protrusion},\n      };\n      {\n        // normalize probs\n        double p = 0.0;\n        for (int i = 0; i < action_probs.size(); ++i) { p += action_probs[i].first; }\n        for (int i = 0; i < action_probs.size(); ++i) { action_probs[i].first /= p; }\n      }\n\n      for (int iter = 0; iter < num_iters; ++iter) {\n        progress = 1.0 * iter / num_iters;\n\n        const double p_action = std::uniform_real_distribution(0.0, 1.0)(rng_);\n        double p_accum = 0.0;\n        for (int i = 0; i < action_probs.size(); ++i) {\n          p_accum += action_probs[i].first;\n          if (p_action < p_accum) {\n            action_probs[i].second();\n          }\n        }\n\n        if (editor && iter % 100 == 0) {\n          editor->set_oneshot_custom_stat(fmt::format(\"iter = {}/{}\", iter, num_iters));\n          editor->set_pose(args.problem->create_solution(pose));\n          if (auto show_result = editor->show(1); show_result.edit_result) {\n            pose = show_result.edit_result->pose_after_edit->vertices;\n          }\n        }\n      }\n\n      SolverOutputs outputs;\n      if (best_feasible_pose.empty()) {\n        outputs.solution = args.problem->create_solution(pose);\n      }\n      else {\n        outputs.solution = args.problem->create_solution(best_feasible_pose);\n      }\n      return outputs;\n    }\n\n    template <typename P>\n    std::tuple<bool, double> Evaluate(const std::vector<P>& pose) const {\n      const double protrusion_cost_coefficient0 = parameters_[\"protrusion_cost_coefficient0\"]; // 1.0 0.01-100.0 log\n      const double protrusion_cost_coefficient1 = parameters_[\"protrusion_cost_coefficient1\"]; // 0.01 0.01-100.0 log\n      const double deformation_cost_coefficient = parameters_[\"deformation_cost_coefficient\"]; // 10.0 0.01-100.0 log\n      const double dislikes_cost_coefficient = parameters_[\"dislikes_cost_coefficient\"]; // 0.01 0.01-100.0 log\n\n      double deformation_cost = 0.0;\n      double protrusion_cost = 0.0;\n      double dislikes_cost = 0.0;\n\n      const double tolerance = epsilon_ / 1'000'000.0;\n      for (const auto& vertex : pose) {\n        protrusion_cost += protrusion_cost_coefficient0 * bg::distance(ToBoostPoint(vertex), hole_polygon_);\n      }\n      for (const auto& edge : edges_) {\n        const auto [a, b] = edge;\n        Point2d pa = pose[a];\n        Point2d pb = pose[b];\n        shrink(pa, pb);\n        BoostLinestring linestring{ ToBoostPoint(pa), ToBoostPoint(pb) };\n        std::vector<BoostLinestring> differences;\n        bg::difference(linestring, hole_polygon_, differences);\n        for (const auto& segment : differences) {\n          protrusion_cost += protrusion_cost_coefficient1 * bg::length(segment);\n        }\n\n        const auto d0 = SquaredEdgeLength(vertices_, edge);\n        const auto d1 = SquaredEdgeLength(pose, edge);\n        deformation_cost += deformation_cost_coefficient * std::max(0.0, std::abs(d1 / d0 - 1.0) - tolerance);\n      }\n\n      for (const auto h : hole_) {\n        double best = std::numeric_limits<double>::infinity();\n        for (const auto v : pose) {\n          best = std::min(best, SquaredDistance(h, v));\n        }\n        dislikes_cost += best * dislikes_cost_coefficient;\n      }\n\n      const bool feasible = deformation_cost + protrusion_cost == 0.0;\n      const double cost = deformation_cost + protrusion_cost + dislikes_cost;\n\n      return { feasible, cost };\n    }\n\n  private:\n    std::mt19937 rng_;\n    std::vector<Point> hole_;\n    std::vector<Point> vertices_;\n    std::vector<Edge> edges_;\n    integer epsilon_;\n    BoostPolygon hole_polygon_;\n    nlohmann::json parameters_;\n  };\n\n}\n\nREGISTER_SOLVER(\"OptunaAnnealingSolver\", OptunaAnnealingSolver::Solver);\n// vim:ts=2 sw=2 sts=2 et ci\n", "meta": {"hexsha": "946dcad66e8d71b70b4c259f92eb85b5bfc8fa30", "size": 16568, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/solvers/optuna_annealing_solver.cpp", "max_stars_repo_name": "nodchip/icfpc2021", "max_stars_repo_head_hexsha": "e50f0172fd62097049dab19c01875c57468a13f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-12T13:52:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-12T13:52:18.000Z", "max_issues_repo_path": "src/solvers/optuna_annealing_solver.cpp", "max_issues_repo_name": "nodchip/icfpc2021", "max_issues_repo_head_hexsha": "e50f0172fd62097049dab19c01875c57468a13f1", "max_issues_repo_licenses": ["MIT"], "max_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/optuna_annealing_solver.cpp", "max_forks_repo_name": "nodchip/icfpc2021", "max_forks_repo_head_hexsha": "e50f0172fd62097049dab19c01875c57468a13f1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-24T08:49:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-24T08:49:18.000Z", "avg_line_length": 37.9130434783, "max_line_length": 122, "alphanum_fraction": 0.5988652825, "num_tokens": 4405, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.45938114349624176}}
{"text": "//==================================================================================================\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_MEANOF_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_MEANOF_HPP_INCLUDED\n\n#include <boost/simd/constant/half.hpp>\n#include <boost/simd/function/max.hpp>\n#include <boost/simd/function/min.hpp>\n#include <boost/simd/function/is_finite.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  BOOST_DISPATCH_OVERLOAD ( meanof_\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      if (is_finite(a0)&&is_finite(a1))\n      {\n        A0 m = min(a0, a1);\n        return m + (max(a0, a1)-m)*Half<A0>();\n      }\n      else\n        return a0+a1;\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( meanof_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_< bd::integer_<A0>>\n                          , bd::scalar_< bd::integer_<A0>>\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() ( A0 a0, A0 a1) const BOOST_NOEXCEPT\n    {\n      return (a0 & a1) + ((a0 ^ a1) >> 1);\n    }\n  };\n\n} } }\n\n\n#endif\n", "meta": {"hexsha": "97120dbf82d4e53723f4c0c33eab9c7a4bf64037", "size": 1794, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/scalar/function/meanof.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/meanof.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/meanof.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": 30.9310344828, "max_line_length": 100, "alphanum_fraction": 0.5, "num_tokens": 413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.45938114349624176}}
{"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#include <gtest/gtest.h>\n\n#include <Eigen/Core>\n\n#include \"smooth/feedback/collocation/dyn_error.hpp\"\n\nTEST(CollocationDyn, DynError)\n{\n  // given trajectory\n  const auto x = [](double t) -> Eigen::Vector<double, 1> {\n    return Eigen::Vector<double, 1>{{0.1 * t * t - 0.4 * t + 0.2}};\n  };\n\n  // system dynamics\n  const auto f =\n    []<typename T>(const T & t, const Eigen::Vector<T, 1> &, const Eigen::Vector<T, 0> &)\n    -> Eigen::Vector<T, 1> { return Eigen::Vector<T, 1>{{0.2 * t - 0.4}}; };\n\n  double t0 = 3;\n  double tf = 5;\n\n  smooth::feedback::Mesh<5, 5> m;\n\n  // trajectory is not a polynomial, so we need a couple of intervals for a good approximation\n  m.refine_ph(0, 16 * 5);\n  ASSERT_EQ(m.N_ivals(), 16);\n\n  // fill X with curve values at the two intervals\n  std::size_t M = 0;\n  Eigen::MatrixXd X(1, m.N_colloc() + 1);\n  for (auto p = 0u; p < m.N_ivals(); ++p) {\n    for (const auto & [i, tau] :\n         smooth::utils::zip(std::views::iota(0u, m.N_colloc_ival(p)), m.interval_nodes(p))) {\n      X.col(M + i) = x(t0 + (tf - t0) * tau);\n    }\n    M += m.N_colloc_ival(p);\n  }\n  X.col(m.N_colloc()) = x(tf);\n\n  auto xfun = [X = X, t0 = t0, tf = tf, m = m](const double t) -> Eigen::Vector<double, 1> {\n    return m.eval<Eigen::Vector<double, 1>>((t - t0) / (tf - t0), X.colwise(), 0, true);\n  };\n  auto ufun = [](const double) -> Eigen::Vector<double, 0> {\n    return Eigen::Vector<double, 0>::Zero();\n  };\n\n  m.increase_degrees();\n  auto rel_errs = smooth::feedback::mesh_dyn_error(f, m, t0, tf, xfun, ufun);\n  m.decrease_degrees();\n\n  ASSERT_LE(rel_errs.cwiseAbs().maxCoeff(), 1e-8);\n\n  const auto Npre = m.N_ivals();\n  m.refine_errors(rel_errs, 1e-8);\n\n  ASSERT_EQ(m.N_ivals(), Npre);\n}\n", "meta": {"hexsha": "a1fa29fe6cbd313a49f9094b2edda90d68fb8eed", "size": 2988, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_collocation_dyn_error.cpp", "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": "tests/test_collocation_dyn_error.cpp", "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": "tests/test_collocation_dyn_error.cpp", "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": 36.0, "max_line_length": 94, "alphanum_fraction": 0.6683400268, "num_tokens": 868, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255928, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.45938113694255744}}
{"text": "#include <iostream>\n#include <vector>\n#include <string>\n#include \"jefflib.h\" \n#include <boost/tokenizer.hpp>\n#include <map>\n#include <set>\n\nusing namespace std;\nusing namespace boost;\n\nvoid processNode(vector<int>& data, int& index, int& checksum);\n\nint main()\n{\n    vector<string> vect;\n    if(GetStringInput(vect)){\n        cout << \"Got data!\" << endl;\n        cout << endl;\n    }\n    else {\n        cout << \"Failed to read input :( \" << endl;\n        return -1;\n    }\n\n    char_separator<char> sep(\" \");\n    tokenizer< char_separator<char> > tokens(vect[0], sep);\n    vector<string> v_temp(tokens.begin(), tokens.end());\n\n    vector<int> data;\n    for(auto s : v_temp){\n        data.push_back(stoi(s));\n    }\n\n    cout << \"Data size: \" << data.size() << endl;\n\n    int checksum = 0;\n    int index = 0;\n    processNode(data, index, checksum);\n    cout << \"Checksum: \" << checksum << endl;\n}\n\nvoid processNode(vector<int>& data, int& index, int& checksum){\n    int numChildren = data[index];\n    int numMeta = data[++index];\n    \n    for(int i = 0; i < numChildren; i++){\n        processNode(data, ++index, checksum);\n    }\n\n    for(int i = 0; i < numMeta; i++){\n        checksum += data[++index];\n    }\n}\n\n\n", "meta": {"hexsha": "988dcf6eaa2185d21c2b55eca4e7c81b3ff5b426", "size": 1209, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "jeff/day-08/part-1.cpp", "max_stars_repo_name": "jeffphi/advent-of-code-2018", "max_stars_repo_head_hexsha": "8e54bd23ebfe42fcbede315f0ab85db903551532", "max_stars_repo_licenses": ["MIT"], "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/day-08/part-1.cpp", "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/day-08/part-1.cpp", "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": 21.2105263158, "max_line_length": 63, "alphanum_fraction": 0.5781637717, "num_tokens": 314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255928, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.45938113694255744}}
{"text": "/* test_negative_binomial_distribution.cpp\n *\n * Copyright Steven Watanabe 2010\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#include <boost/random/negative_binomial_distribution.hpp>\n#include <limits>\n\n#define BOOST_RANDOM_DISTRIBUTION boost::random::negative_binomial_distribution<>\n#define BOOST_RANDOM_ARG1 k\n#define BOOST_RANDOM_ARG2 p\n#define BOOST_RANDOM_ARG1_DEFAULT 1\n#define BOOST_RANDOM_ARG2_DEFAULT 0.5\n#define BOOST_RANDOM_ARG1_VALUE 10\n#define BOOST_RANDOM_ARG2_VALUE 0.25\n\n#define BOOST_RANDOM_DIST0_MIN 0\n#define BOOST_RANDOM_DIST0_MAX (std::numeric_limits<int>::max)()\n#define BOOST_RANDOM_DIST1_MIN 0\n#define BOOST_RANDOM_DIST1_MAX (std::numeric_limits<int>::max)()\n#define BOOST_RANDOM_DIST2_MIN 0\n#define BOOST_RANDOM_DIST2_MAX (std::numeric_limits<int>::max)()\n\n#define BOOST_RANDOM_TEST1_PARAMS\n#define BOOST_RANDOM_TEST1_MIN 0\n#define BOOST_RANDOM_TEST1_MAX 10\n\n#define BOOST_RANDOM_TEST2_PARAMS (100, 0.5)\n#define BOOST_RANDOM_TEST2_MIN 50\n\n#include \"test_distribution.ipp\"\n", "meta": {"hexsha": "c6cd6c9172af7ef8c0e4d71a6f583fff4ea9c9ff", "size": 1128, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/random/test/test_negative_binomial_distribution.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "boost/libs/random/test/test_negative_binomial_distribution.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "boost/libs/random/test/test_negative_binomial_distribution.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "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": 29.6842105263, "max_line_length": 81, "alphanum_fraction": 0.8156028369, "num_tokens": 283, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255927, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4593811369425573}}
{"text": "#ifndef SCROLLGRID3_HPP_I9SAOOSJ\n#define SCROLLGRID3_HPP_I9SAOOSJ\n\n#include <math.h>\n#include <stdint.h>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n#include <ros/ros.h>\n#include <ros/console.h>\n\n#include <pcl_util/point_types.hpp>\n#include <geom_cast/geom_cast.hpp>\n\n#include \"scrollgrid/mod_wrap.hpp\"\n#include \"scrollgrid/grid_types.hpp\"\n#include \"scrollgrid/box.hpp\"\n\nnamespace ca\n{\n\n/**\n * These are empty functors defining the interface for callbacks\n * to clear cells and fix edges.\n * TODO this could also be achieved with templates.\n */\nstruct ClearCellsFun {\n  virtual void operator()(const Vec3Ix& start,\n                          const Vec3Ix& finish) const { }\n};\n\nstruct FixEdgesFun {\n  virtual void operator()(grid_ix_t dim,\n                          grid_ix_t trailing,\n                          grid_ix_t leading) const { }\n};\n\n//typedef boost::function< void (grid_ix_t dim, grid_ix_t trailing, grid_ix_t leading) > FixEdgesFun;\n/**\n * \"world_xyz\" xyz world frame\n * \"grid_xyz\" xyz grid frame (shifted relative to world_xyz by origin)\n * \"grid_ijk\" scaled and discretized grid coordinates:\n *     i = floor( (x-origin_x-0.5)/resolution )\n * \"local_ijk\" grid_ijk shifted by scrolling and limited/wrapped to local extent\n *     li = (i - scroll_offset_i) modulo (dim_i)\n * \"mem_ix\" index into flat storage from local_ijk.\n *     mem_ix = local_ijk.dot(strides)\n * \"hash_ix\": bit-packed version of grid_ijk? TODO\n *\n */\n\n// TODO start using vec4 instead for SSE optimization\n\ntemplate<class Scalar>\nclass ScrollGrid3 {\npublic:\n  // TODO what if used vec4 instead for SSE optimizations?\n  typedef Eigen::Matrix<Scalar, 3, 1> Vec3;\n\n  typedef boost::shared_ptr<ScrollGrid3> Ptr;\n  typedef boost::shared_ptr<const ScrollGrid3> ConstPtr;\n\npublic:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n\n  ScrollGrid3() :\n      radius_ijk_(0,0,0),\n      box_(),\n      origin_(0, 0, 0),\n      min_world_corner_ijk_(0, 0, 0),\n      dimension_(0, 0, 0),\n      num_cells_(0),\n      strides_(0, 0, 0),\n      scroll_offset_(0, 0, 0),\n      last_ijk_(0, 0, 0),\n      wrap_ijk_min_(0, 0, 0),\n      wrap_ijk_max_(0, 0, 0),\n      unwrap_ijk_(0, 0, 0),\n      resolution_(0)\n  { }\n\n  ScrollGrid3(const Vec3& center,\n              const Vec3Ix& dimension,\n              Scalar resolution,\n              bool x_fastest=false) :\n      radius_ijk_(dimension/2),\n      box_(center-(radius_ijk_.cast<Scalar>()*resolution),\n           center+(radius_ijk_.cast<Scalar>()*resolution)),\n      origin_(center-box_.radius()),\n      dimension_(dimension),\n      num_cells_(dimension.prod()),\n      scroll_offset_(0, 0, 0),\n      last_ijk_(scroll_offset_ + dimension_),\n      wrap_ijk_min_(0, 0, 0),\n      wrap_ijk_max_(0, 0, 0),\n      unwrap_ijk_(0, 0, 0),\n      resolution_(resolution)\n  {\n    // calculate coordinates of min corner in ijk\n    Scalar m = -static_cast<Scalar>(std::numeric_limits<uint16_t>::max()/2)*resolution_;\n    Vec3 m3(m, m, m);\n    min_world_corner_ijk_ = this->world_to_grid(m3);\n\n    if (x_fastest) {\n      strides_ = Vec3Ix(1, dimension[0], dimension.head<2>().prod());\n    } else {\n      strides_ = Vec3Ix(dimension.tail<2>().prod(), dimension[2], 1);\n    }\n\n    this->update_wrap_ijk();\n  }\n\n  virtual ~ScrollGrid3() { }\n\n  ScrollGrid3(const ScrollGrid3& other) :\n      box_(other.box_),\n      origin_(other.origin_),\n      min_world_corner_ijk_(other.min_world_corner_ijk_),\n      dimension_(other.dimension_),\n      num_cells_(other.num_cells_),\n      strides_(other.strides_),\n      scroll_offset_(other.scroll_offset_),\n      last_ijk_(other.last_ijk_),\n      wrap_ijk_min_(other.wrap_ijk_min_),\n      wrap_ijk_max_(other.wrap_ijk_max_),\n      unwrap_ijk_(other.unwrap_ijk_),\n      resolution_(other.resolution_)\n  {\n  }\n\n  ScrollGrid3& operator=(const ScrollGrid3& other) {\n    if (this==&other) { return *this; }\n    box_ = other.box_;\n    origin_ = other.origin_;\n    min_world_corner_ijk_ = other.min_world_corner_ijk_;\n    dimension_ = other.dimension_;\n    num_cells_ = other.num_cells_;\n    strides_ = other.strides_;\n    scroll_offset_ = other.scroll_offset_;\n    last_ijk_ = other.last_ijk_;\n    wrap_ijk_min_ = other.wrap_ijk_min_;\n    wrap_ijk_max_ = other.wrap_ijk_max_;\n    unwrap_ijk_ = other.unwrap_ijk_;\n    resolution_ = other.resolution_;\n    return *this;\n  }\n\npublic:\n\n  void reset(const Vec3& center,\n             const Vec3Ix& dimension,\n             Scalar resolution,\n             bool x_fastest=false) {\n\n    radius_ijk_ = dimension/2;\n    box_.set_center(center);\n    box_.set_radius(radius_ijk_.cast<Scalar>() * resolution);\n    origin_ = center - box_.radius();\n\n    dimension_ = dimension;\n    num_cells_ = dimension.prod();\n    if (x_fastest) {\n      strides_ = Vec3Ix(1, dimension[0], dimension.head<2>().prod());\n    } else {\n      strides_ = Vec3Ix(dimension.tail<2>().prod(), dimension[2], 1);\n    }\n    scroll_offset_.setZero();\n    last_ijk_ = scroll_offset_ + dimension_;\n\n    this->update_wrap_ijk();\n\n    resolution_ = resolution;\n\n    Vec3 m;\n    m[0] = -static_cast<Scalar>(std::numeric_limits<uint16_t>::max()/2)*resolution_;\n    m[1] = -static_cast<Scalar>(std::numeric_limits<uint16_t>::max()/2)*resolution_;\n    m[2] = -static_cast<Scalar>(std::numeric_limits<uint16_t>::max()/2)*resolution_;\n    min_world_corner_ijk_ = this->world_to_grid(m);\n\n  }\n\n  /**\n   * Is inside 3D box containing grid?\n   * @param pt point in same frame as center (probably world_view)\n   */\n  bool is_inside_box(const Vec3& pt) const {\n    return box_.contains(pt);\n  }\n\n  template<class PointT>\n  bool is_inside_box(const PointT& pt) const {\n    return box_.contains(ca::point_cast<Vec3>(pt));\n  }\n\n  /**\n   * is i, j, k inside the grid limits?\n   */\n  bool is_inside_grid(const Vec3Ix& grid_ix) const {\n    return ((grid_ix.array() >= scroll_offset_.array()).all() &&\n            (grid_ix.array() < (scroll_offset_+dimension_).array()).all());\n  }\n\n  bool is_inside_grid(grid_ix_t i, grid_ix_t j, grid_ix_t k) const {\n    return this->is_inside_grid(Vec3Ix(i, j, k));\n  }\n\n  /**\n   * scroll grid.\n   * updates bounding box and offset_cells.\n   * @param offset_cells. how much to scroll. offset_cells is a signed integral.\n   *\n   */\n  void just_scroll(const Vec3Ix& offset_cells) {\n    Vec3Ix new_offset = scroll_offset_ + offset_cells;\n    box_.translate((offset_cells.cast<Scalar>()*resolution_));\n    scroll_offset_ = new_offset;\n    last_ijk_ = scroll_offset_ + dimension_;\n\n    this->update_wrap_ijk();\n  }\n\n/**\n   * functionally same as just_scroll.\n   * special case of scroll_and_clear_and_fix.\n   */\n  void scroll(const Vec3Ix& offset_cells) {\n    ClearCellsFun nullclear;\n    FixEdgesFun nullfix;\n    this->scroll_and_clear_and_fix(offset_cells, nullclear, nullfix);\n  }\n\n/**\n   * scroll grid by offset_cells and call clear_cells_fun on outgoing/incoming\n   * cells.\n   * special case of scroll_and_clear_and_fix.\n   */  \n  \n  void scroll_and_clear(const Vec3Ix& offset_cells,\n                        const ClearCellsFun& clear_cells_fun) {\n    FixEdgesFun nullfix;\n    this->scroll_and_clear_and_fix(offset_cells, clear_cells_fun, nullfix);\n  }\n\n/**\n   * scroll grid by offset_cells, call fix_edges_fun on outgoing/incoming\n   * edges, and clear_cells_fun on outgoing/incoming cells.\n   */  \n  void scroll_and_clear_and_fix(const Vec3Ix& offset_cells,\n                                const ClearCellsFun& clear_cells_fun,\n                                const FixEdgesFun& fix_edges_fun) {\n\n    Vec3Ix new_offset = scroll_offset_ + offset_cells;\n\n    // check if there is overlap between current box and box after scroll.\n    // if there is not, then the whole box must be wiped out.\n    if (( abs(offset_cells[0]) >= dimension_[0] ) ||\n        ( abs(offset_cells[1]) >= dimension_[1] ) ||\n        ( abs(offset_cells[2]) >= dimension_[2] ) ) {\n\n      clear_cells_fun(scroll_offset_, scroll_offset_+dimension_);\n\n      // not sure if *all* edges must be fixed or none of them should.\n      // according to current logic none of them should.\n      // TODO caveat: there is an -1 offset in all the edges calculations.\n      // also note: earlier logic completely ignored this case.\n\n    } else {\n      if (offset_cells[0] > 0) {\n        Vec3Ix finish(new_offset[0],\n                      scroll_offset_[1] + dimension_[1],\n                      scroll_offset_[2] + dimension_[2]);\n        clear_cells_fun(scroll_offset_, finish);\n        fix_edges_fun(0, finish[0], scroll_offset_[0]+dimension_[0]-1);\n      } else if (offset_cells[0] < 0) {\n        Vec3Ix start(scroll_offset_[0]+dimension_[0]+offset_cells[0],\n                     scroll_offset_[1],\n                     scroll_offset_[2]);\n        Vec3Ix finish = scroll_offset_ + dimension_;\n        clear_cells_fun(start, finish);\n        fix_edges_fun(0, start[0]-1, scroll_offset_[0]);\n      }\n\n      if (offset_cells[1] > 0) {\n        Vec3Ix finish(scroll_offset_[0] + dimension_[0],\n                      new_offset[1],\n                      scroll_offset_[2] + dimension_[2]);\n        clear_cells_fun(scroll_offset_, finish);\n        fix_edges_fun(1, finish[1], scroll_offset_[1]+dimension_[1]-1);\n      } else if(offset_cells[1] < 0) {\n        Vec3Ix start(scroll_offset_[0],\n                     scroll_offset_[1]+dimension_[1]+offset_cells[1],\n                     scroll_offset_[2]);\n        Vec3Ix finish = scroll_offset_ + dimension_;\n        clear_cells_fun(start, finish);\n        fix_edges_fun(1, start[1]-1, scroll_offset_[1]);\n      }\n\n      if (offset_cells[2] > 0) {\n        Vec3Ix finish(scroll_offset_[0] + dimension_[0],\n                      scroll_offset_[1] + dimension_[1],\n                      new_offset[2]);\n        clear_cells_fun(scroll_offset_, finish);\n        fix_edges_fun(2, finish[2], scroll_offset_[2]+dimension_[2]-1);\n      } else if(offset_cells[2] < 0) {\n        Vec3Ix start(scroll_offset_[0],\n                     scroll_offset_[1],\n                     scroll_offset_[2]+dimension_[2]+offset_cells[2]);\n        Vec3Ix finish = scroll_offset_ + dimension_;\n        clear_cells_fun(start, finish);\n        fix_edges_fun(2, start[2]-1, scroll_offset_[2]);\n      }\n    }\n\n    box_.translate((offset_cells.cast<Scalar>()*resolution_));\n    scroll_offset_ = new_offset;\n    last_ijk_ = scroll_offset_ + dimension_;\n    this->update_wrap_ijk();\n\n  }\n\n  /**\n   * get boxes to clear if scrolling by offset_cells.\n   * Call this *before* scroll().\n   * @param clear_i_min min corner of obsolete region in grid\n   * @param clear_i_max max corner of obsolete region in grid\n   * same for j and k\n   * Note that boxes may overlap.\n   *\n   * Note: this may be deprecated in favor of the clearfun callbacks\n   * in scroll.\n   */\n  void get_clear_boxes(const Vec3Ix& offset_cells,\n                       Vec3Ix& clear_i_min, Vec3Ix& clear_i_max,\n                       Vec3Ix& clear_j_min, Vec3Ix& clear_j_max,\n                       Vec3Ix& clear_k_min, Vec3Ix& clear_k_max) {\n\n    clear_i_min.setZero();\n    clear_j_min.setZero();\n    clear_k_min.setZero();\n    clear_i_max.setZero();\n    clear_j_max.setZero();\n    clear_k_max.setZero();\n\n    // first check if there is overlap between current and box after scroll.\n    // if there is not, then the whole box must be wiped out.\n    if (( abs(offset_cells[0]) >= dimension_[0] ) ||\n        ( abs(offset_cells[1]) >= dimension_[1] ) ||\n        ( abs(offset_cells[2]) >= dimension_[2] ) ) {\n      clear_i_min = scroll_offset_;\n      clear_i_max = scroll_offset_ + dimension_;\n      return;\n    }\n\n    Vec3Ix new_offset = scroll_offset_ + offset_cells;\n\n    // X axis\n    if (offset_cells[0] > 0) {\n      clear_i_min = scroll_offset_;\n      clear_i_max = Vec3Ix(new_offset[0],\n                           scroll_offset_[1]+dimension_[1],\n                           scroll_offset_[2]+dimension_[2]);\n    } else if (offset_cells[0] < 0) {\n      clear_i_min = Vec3Ix(scroll_offset_[0]+dimension_[0]+offset_cells[0],\n                           scroll_offset_[1],\n                           scroll_offset_[2]);\n      clear_i_max = scroll_offset_ + dimension_;\n    }\n\n    // Y axis\n    if (offset_cells[1] > 0) {\n      clear_j_min = scroll_offset_;\n      clear_j_max = Vec3Ix(scroll_offset_[0]+dimension_[0],\n                           new_offset[1],\n                           scroll_offset_[2]+dimension_[2]);\n    } else if (offset_cells[1] < 0) {\n      clear_j_min = Vec3Ix(scroll_offset_[0],\n                           scroll_offset_[1]+dimension_[1]+offset_cells[1],\n                           scroll_offset_[2]);\n      clear_j_max = scroll_offset_ + dimension_;\n    }\n\n    // Z axis\n    if (offset_cells[2] > 0) {\n      clear_k_min = scroll_offset_;\n      clear_k_max = Vec3Ix(scroll_offset_[0]+dimension_[0],\n                           scroll_offset_[1]+dimension_[1],\n                           new_offset[2]);\n    } else if(offset_cells[2] < 0) {\n      clear_k_min = Vec3Ix(scroll_offset_[0],\n                           scroll_offset_[1],\n                           scroll_offset_[2]+dimension_[2]+offset_cells[2]);\n      clear_k_max = scroll_offset_ + dimension_;\n    }\n\n  }\n\n  /**\n   * Given position in world coordinates, return grid coordinates.\n   * (grid coordinates are not wrapped to be inside grid!)\n   * Note: does not check if point is inside grid.\n   */\n  Vec3Ix world_to_grid(const Vec3& xyz) const {\n    Vec3 tmp = ((xyz - origin_).array() - 0.5*resolution_)/resolution_;\n    return Vec3Ix(round(tmp.x()), round(tmp.y()), round(tmp.z()));\n  }\n\n  Vec3Ix world_to_grid(Scalar x, Scalar y, Scalar z) const {\n    return this->world_to_grid(Vec3(x, y, z));\n  }\n\n  /**\n   * Like world to grid but xyz are offset by scroll grid center.\n   * DON'T USE OR YOU WILL SCREW UP.\n   */\n  Vec3Ix offset_world_to_grid(const Vec3& xyz) const {\n    Vec3 tmp = ((xyz + box_.center() - origin_).array() - 0.5*resolution_)/resolution_;\n    return Vec3Ix(round(tmp.x()), round(tmp.y()), round(tmp.z()));\n  }\n\n  Vec3Ix offset_world_to_grid(Scalar x, Scalar y, Scalar z) const {\n    return this->offset_world_to_grid(Vec3(x, y, z));\n  }\n\n  Vec3 grid_to_world(const Vec3Ix& grid_ix) const {\n    Vec3 w((grid_ix.cast<Scalar>()*resolution_ + origin_).array() + 0.5*resolution_);\n    return w;\n  }\n\n  Vec3 grid_to_world(grid_ix_t i, grid_ix_t j, grid_ix_t k) const {\n    return this->grid_to_world(Vec3Ix(i, j, k));\n  }\n\n  /**\n   * Translate grid indices to an address in linear memory.\n   * Does not check if grid_ix is inside current grid box.\n   * Assumes C-order, x the slowest and z the fastest.\n   */\n  mem_ix_t grid_to_mem_slow(const Vec3Ix& grid_ix) const {\n    Vec3Ix grid_ix2(ca::mod_wrap(grid_ix[0], dimension_[0]),\n                    ca::mod_wrap(grid_ix[1], dimension_[1]),\n                    ca::mod_wrap(grid_ix[2], dimension_[2]));\n    return strides_.dot(grid_ix2);\n  }\n\n  /**\n   * Faster than grid_to_mem_slow, as it avoids modulo.\n   * But it only works if the grid_ix are inside the bounding box.\n   * Hopefully branch prediction kicks in when using this in a loop.\n   */\n  mem_ix_t grid_to_mem(const Vec3Ix& grid_ix) const {\n    ROS_ASSERT( this->is_inside_grid(grid_ix) );\n\n    Vec3Ix grid_ix2(grid_ix);\n\n    if (grid_ix2[0] >= wrap_ijk_max_[0]) { grid_ix2[0] -= wrap_ijk_max_[0]; } else { grid_ix2[0] -= wrap_ijk_min_[0]; }\n    if (grid_ix2[1] >= wrap_ijk_max_[1]) { grid_ix2[1] -= wrap_ijk_max_[1]; } else { grid_ix2[1] -= wrap_ijk_min_[1]; }\n    if (grid_ix2[2] >= wrap_ijk_max_[2]) { grid_ix2[2] -= wrap_ijk_max_[2]; } else { grid_ix2[2] -= wrap_ijk_min_[2]; }\n\n    mem_ix_t mem_ix2 = strides_.dot(grid_ix2);\n\n    return mem_ix2;\n  }\n\n  mem_ix_t grid_to_mem_slow(grid_ix_t i, grid_ix_t j, grid_ix_t k) const {\n    return this->grid_to_mem_slow(Vec3Ix(i, j, k));\n  }\n\n  mem_ix_t grid_to_mem(grid_ix_t i, grid_ix_t j, grid_ix_t k) const {\n    return grid_to_mem( Vec3Ix(i, j, k) );\n  }\n\n  /**\n   * TODO should we do this in the sparse_array3 module?\n   */\n  uint64_t grid_to_hash(const Vec3Ix& grid_ix) const {\n    // grid2 should be all positive\n    Vec3Ix grid2(grid_ix - min_world_corner_ijk_);\n\n    uint64_t hi = static_cast<uint64_t>(grid2[0]);\n    uint64_t hj = static_cast<uint64_t>(grid2[1]);\n    uint64_t hk = static_cast<uint64_t>(grid2[2]);\n    uint64_t h = (hi << 48) | (hj << 32) | (hk << 16);\n    return h;\n  }\n\n  Vec3Ix hash_to_grid(uint64_t hix) const {\n    uint64_t hi = (hix & 0xffff000000000000) >> 48;\n    uint64_t hj = (hix & 0x0000ffff00000000) >> 32;\n    uint64_t hk = (hix & 0x00000000ffff0000) >> 16;\n    Vec3Ix grid_ix(hi, hj, hk);\n    grid_ix += min_world_corner_ijk_;\n    return grid_ix;\n  }\n\n  /**\n   * Note that no bound check is performed!\n   */\n  mem_ix_t world_to_mem(const Vec3& xyz) const {\n    Vec3Ix gix(this->world_to_grid(xyz));\n    return this->grid_to_mem(gix);\n  }\n\n  Vec3Ix mem_to_grid(grid_ix_t mem_ix) const {\n    // TODO does this work for x-fastest strides?\n    grid_ix_t i = mem_ix/strides_[0];\n    mem_ix -= i*strides_[0];\n    grid_ix_t j = mem_ix/strides_[1];\n    mem_ix -= j*strides_[1];\n    grid_ix_t k = mem_ix;\n\n    if (i < unwrap_ijk_[0]) { i += wrap_ijk_max_[0]; } else { i += wrap_ijk_min_[0]; }\n    if (j < unwrap_ijk_[1]) { j += wrap_ijk_max_[1]; } else { j += wrap_ijk_min_[1]; }\n    if (k < unwrap_ijk_[2]) { k += wrap_ijk_max_[2]; } else { k += wrap_ijk_min_[2]; }\n\n    return (Vec3Ix(i, j, k));\n\n  }\n\n public:\n  grid_ix_t dim_i() const { return dimension_[0]; }\n  grid_ix_t dim_j() const { return dimension_[1]; }\n  grid_ix_t dim_k() const { return dimension_[2]; }\n  grid_ix_t first_i() const { return scroll_offset_[0]; }\n  grid_ix_t first_j() const { return scroll_offset_[1]; }\n  grid_ix_t first_k() const { return scroll_offset_[2]; }\n  grid_ix_t last_i() const { return last_ijk_[0]; }\n  grid_ix_t last_j() const { return last_ijk_[1]; }\n  grid_ix_t last_k() const { return last_ijk_[2]; }\n  const Vec3Ix& scroll_offset() const { return scroll_offset_; }\n  const Vec3Ix& unwrap_ijk() const { return unwrap_ijk_; }\n//   const Vec3Ix& unwrap_ijk_() const { return unwrap_ijk_; }\n  const Vec3Ix& radius_ijk() const { return radius_ijk_; }\n  const Vec3Ix& dimension() const { return dimension_; }\n  const Vec3& radius() const { return box_.radius(); }\n  const Vec3& origin() const { return origin_; }\n  Vec3 min_pt() const { return box_.min_pt(); }\n  Vec3 max_pt() const { return box_.max_pt(); }\n  const Vec3& center() const { return box_.center(); }\n  Scalar resolution() const { return resolution_; }\n  const ca::scrollgrid::Box<Scalar, 3>& box() const { return box_; }\n\n  grid_ix_t num_cells() const { return num_cells_; }\n\n private:\n\n  /**\n   * (Re)calculate indices where wrapping occurs for faster lookups.\n   * This basically avoids modulo operations.\n   * Must be called each time scrollgrid moves.\n   */\n  void update_wrap_ijk() {\n    wrap_ijk_min_[0] = floor(static_cast<float>(scroll_offset_[0])/dimension_[0])*dimension_[0];\n    wrap_ijk_min_[1] = floor(static_cast<float>(scroll_offset_[1])/dimension_[1])*dimension_[1];\n    wrap_ijk_min_[2] = floor(static_cast<float>(scroll_offset_[2])/dimension_[2])*dimension_[2];\n\n    wrap_ijk_max_[0] = floor(static_cast<float>(scroll_offset_[0]+dimension_[0])/dimension_[0])*dimension_[0];\n    wrap_ijk_max_[1] = floor(static_cast<float>(scroll_offset_[1]+dimension_[1])/dimension_[1])*dimension_[1];\n    wrap_ijk_max_[2] = floor(static_cast<float>(scroll_offset_[2]+dimension_[2])/dimension_[2])*dimension_[2];\n\n    unwrap_ijk_[0] = ca::mod_wrap(scroll_offset_[0], dimension_[0]);\n    unwrap_ijk_[1] = ca::mod_wrap(scroll_offset_[1], dimension_[1]);\n    unwrap_ijk_[2] = ca::mod_wrap(scroll_offset_[2], dimension_[2]);\n\n  }\n\n private:\n\n  // discrete radius, used when calculating box dimensions\n  Vec3Ix radius_ijk_;\n\n  // 3d box enclosing grid. In whatever coordinates were given (probably\n  // world_view)\n  ca::scrollgrid::Box<Scalar, 3> box_;\n\n  // xyz position of grid origin in world_xyz frame.\n  // does not move when scrolling.\n  // initialized as (center - box.radius).\n  Vec3 origin_;\n\n  // minimum world corner in ijk. used for hash\n  Vec3Ix min_world_corner_ijk_;\n\n  // number of grid cells along each axis\n  Vec3Ix dimension_;\n\n  // number of cells\n  grid_ix_t num_cells_;\n\n  // grid strides to translate from linear to 3D layout.\n  // C-ordering, ie x slowest, z fastest.\n  Vec3Ix strides_;\n\n  // to keep track of scrolling along z.\n  Vec3Ix scroll_offset_;\n\n  // redundant but actually seems to have a performance benefit\n  // should always be dimension + offset\n  Vec3Ix last_ijk_;\n\n  // for grid_to_mem. the points where the grid crosses modulo boundaries. // nearly boundary pt\n  Vec3Ix wrap_ijk_min_;\n  Vec3Ix wrap_ijk_max_;\n\n  // delimits when extra offset needs to be added when unwrapping  offset % dimension \u4f59\u6570\n  Vec3Ix unwrap_ijk_;\n\n\n  // size of grid cells\n  Scalar resolution_;\n\n};\n\ntypedef ScrollGrid3<float> ScrollGrid3f;\ntypedef ScrollGrid3<double> ScrollGrid3d;\n\n} /* ca */\n\n#endif /* end of include guard: SCROLLGRID3_HPP_I9SAOOSJ */\n", "meta": {"hexsha": "8e127fe1690490f9b25ffe104b34d6af40df9474", "size": 20865, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dependency/scrollgrid/include/scrollgrid/scrollgrid3.hpp", "max_stars_repo_name": "ganlumomo/semantic_3d_mapping", "max_stars_repo_head_hexsha": "c6d2cebd26d4c08ac3f32fe151cf1db7f2d24fe5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 146.0, "max_stars_repo_stars_event_min_datetime": "2018-03-15T13:54:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T07:37:55.000Z", "max_issues_repo_path": "dependency/scrollgrid/include/scrollgrid/scrollgrid3.hpp", "max_issues_repo_name": "ganlumomo/semantic_3d_mapping", "max_issues_repo_head_hexsha": "c6d2cebd26d4c08ac3f32fe151cf1db7f2d24fe5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2018-04-28T09:33:00.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-08T23:46:00.000Z", "max_forks_repo_path": "dependency/scrollgrid/include/scrollgrid/scrollgrid3.hpp", "max_forks_repo_name": "ganlumomo/semantic_3d_mapping", "max_forks_repo_head_hexsha": "c6d2cebd26d4c08ac3f32fe151cf1db7f2d24fe5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 62.0, "max_forks_repo_forks_event_min_datetime": "2018-03-21T06:54:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-05T07:27:42.000Z", "avg_line_length": 33.6532258065, "max_line_length": 119, "alphanum_fraction": 0.6491732566, "num_tokens": 5697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079209, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.45933971807917845}}
{"text": "//\n// GibbsSamplerFromGMOM.hpp\n//\n// Copyright (c) 2017 Shion Hosoda\n//\n// This software is released under the MIT License.\n// http://opensource.org/licenses/mit-license.php\n//\n\n#ifndef GIBBSGMOM\n#define GIBBSGMOM\n\n#include<stdlib.h>\n#include<math.h>\n#include<cmath>\n#include<iostream>\n#include<vector>\n#include<numeric>\n#include<memory>\n#include<random>\n#include<iomanip>\n#include<fstream>\n#include<limits>\n#include <boost/math/distributions/beta.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/mpi/environment.hpp>\n#include <boost/mpi/communicator.hpp>\n#include <boost/mpi/collectives.hpp>\n#include\"CsvFileParser.hpp\"\n#include\"utils.hpp\"\n\n\nnamespace bmpi = boost::mpi;\n\n\ndouble calculateLogBetaFunction(std::vector<double> alpha, int i=-1);\n\n\ndouble calculateDirichletLogPDF(std::vector<double> x, std::vector<double> alpha, int i=-1);\n\n\nunsigned int calculateFactorial(unsigned int x);\n\n\nclass GibbsSamplerFromGMOM{\nprotected:\n    const std::vector<std::vector<double> > &_logO, &_U;\n    const unsigned int _N, _M, _G;\n    const unsigned int _iterationNumber, _burnIn, _samplingInterval;\n    const double _k, _theta, _A;\n    std::vector<std::vector<unsigned int> > _V;\n    std::vector<std::vector<double> > _sumOfVSampled;\n    std::vector<std::vector<double> > _P, _sumOfPSampled;\n    std::vector<std::vector<double> > _gamma;\n    unsigned int _samplingCount;\n    std::vector<double> _logLikelihood;\n    bmpi::communicator _world;\npublic:\n    GibbsSamplerFromGMOM(const CsvFileParser<double> &orthologFile, const CsvFileParser<double> &microbeFile, double A, double k, double theta, unsigned int iterationNumber, unsigned int burnIn, unsigned int samplingInterval, bmpi::communicator &world);\n    virtual ~GibbsSamplerFromGMOM();\n    virtual void initializeParameters();\n    virtual void updateGamma(unsigned int j, unsigned int k, int deltaVjk);\n    virtual double calculateDirichletLogPDF(int k=-1);\n    virtual void sampleV();\n    virtual void sampleP();\n    virtual void calculateLogLikelihood();\n    virtual void writeParameters(std::string PFilename, std::string VFilename)const;\n    virtual void writeLogLikelihood(std::string logLikelihoodFilename)const;\n    virtual void storeSamples();\n    virtual void runIteraions();\n};\n\n#endif\n", "meta": {"hexsha": "2e39ebdca4a3b80d4f36495ff1182a6f3573e704", "size": 2266, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/include/GibbsSamplerFromGMOM.hpp", "max_stars_repo_name": "shion-h/GenerativeMicrobialOrthologModel", "max_stars_repo_head_hexsha": "d1a9f1c88386bffc7291d806e901518723ba3286", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/include/GibbsSamplerFromGMOM.hpp", "max_issues_repo_name": "shion-h/GenerativeMicrobialOrthologModel", "max_issues_repo_head_hexsha": "d1a9f1c88386bffc7291d806e901518723ba3286", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/include/GibbsSamplerFromGMOM.hpp", "max_forks_repo_name": "shion-h/GenerativeMicrobialOrthologModel", "max_forks_repo_head_hexsha": "d1a9f1c88386bffc7291d806e901518723ba3286", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6216216216, "max_line_length": 253, "alphanum_fraction": 0.7497793469, "num_tokens": 563, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959545, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.45933971262236867}}
{"text": "#include \"neal3_algorithm.h\"\n\n#include <Eigen/Dense>\n#include <memory>\n\n#include \"hierarchy_id.pb.h\"\n#include \"mixing_id.pb.h\"\n#include \"src/hierarchies/base_hierarchy.h\"\n#include \"src/mixings/marginal_mixing.h\"\n\nEigen::VectorXd Neal3Algorithm::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 + 1);\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]->conditional_pred_lpdf(\n        data.row(data_idx), hier_covariates.row(data_idx));\n  }\n  // Probability of being assigned to a newly created cluster\n  loglpdf(n_clust) = unique_values[0]->prior_pred_lpdf(\n      data.row(data_idx), hier_covariates.row(data_idx));\n  return loglpdf;\n}\n\nvoid Neal3Algorithm::print_startup_message() const {\n  std::string msg = \"Running Neal3 algorithm with \" +\n                    bayesmix::HierarchyId_Name(unique_values[0]->get_id()) +\n                    \" hierarchies, \" +\n                    bayesmix::MixingId_Name(marg_mixing->get_id()) +\n                    \" mixing...\";\n  std::cout << msg << std::endl;\n}\n", "meta": {"hexsha": "31a42dbf322e291b826d39d59335b927e63394bd", "size": 1217, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/algorithms/neal3_algorithm.cc", "max_stars_repo_name": "ricardaxel/bayesmix", "max_stars_repo_head_hexsha": "c9fb79c2f6fb05783adf31dd31030440413ae9cb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_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/neal3_algorithm.cc", "max_issues_repo_name": "ricardaxel/bayesmix", "max_issues_repo_head_hexsha": "c9fb79c2f6fb05783adf31dd31030440413ae9cb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/neal3_algorithm.cc", "max_forks_repo_name": "ricardaxel/bayesmix", "max_forks_repo_head_hexsha": "c9fb79c2f6fb05783adf31dd31030440413ae9cb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-21T21:24:49.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-21T21:24:49.000Z", "avg_line_length": 34.7714285714, "max_line_length": 76, "alphanum_fraction": 0.674609696, "num_tokens": 312, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4593397126223686}}
{"text": "#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/numeric/conversion/cast.hpp>\n\n//typedef boost::multiprecision::cpp_dec_float_50 xmc_float;\ntypedef boost::multiprecision::number<boost::multiprecision::cpp_dec_float<64> > xmc_float;\ntypedef boost::multiprecision::cpp_int xmc_int;\ntypedef boost::multiprecision::uint128_t xmc_uint_128;\n\nconst xmc_float XMC_UINT = xmc_float(1000000000000.0);\nconst xmc_uint_128 XMC_INT_MAX = xmc_uint_128((uint64_t)10000000000000000000ull);\n\ninline double xmc_int_to_double(xmc_int amount) {\n        xmc_uint_128 amount_128 = amount.convert_to<xmc_uint_128>();\n        //std::cout<<\"uint128_t amount:\" << amount_128 << std::endl;\n\n\tif(amount_128 < XMC_INT_MAX)\n\t{\n\t\tuint64_t int_amount = amount_128.convert_to<uint64_t>();\n\t\t//std::cout<< \"amount < XMC_DEFAULT_DECIMAL :\" << int_amount << std::endl;\n\t\tdouble ret = int_amount / 1000000000000.0;\n\t\t//std::cout<< \"****** return value:\" << ret << std::endl;\n\t\treturn ret;\n\t}\n\t//std::setprecision(std::numeric_limits<xmc_float>::max_digits10);\n\t//std::cout<<\"# XMC int to double ==> xmc_int:\" << amount << std::endl;\n\t//xmc_float amount_float = amount_128.convert_to<xmc_float>();\n\txmc_float amount_float = xmc_float(amount_128);\n\t//std::cout<<\"# XMC int to double ==> xmc_float:\" << amount_float << std::endl;\n\txmc_float amount_xmc = amount_float / XMC_UINT;\n\t//std::cout<<\"#XMC int to double ==> amount_xmc:\" << amount_xmc << std::endl;\n\tdouble ret = amount_xmc.convert_to<double>();\n\t//std::cout<<\"#XMC int to double ==> result:\" << ret << std::endl;\n\treturn ret;\n}\n", "meta": {"hexsha": "29987c6ad2100a67b3e57a8eeb29b885fbc7ff8b", "size": 1608, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/libwalletqt/xmc_int_to_double.hpp", "max_stars_repo_name": "toints/monero-GUI", "max_stars_repo_head_hexsha": "ea29f0ae0e1bc9e00b8a9b69679e302513c3dfcd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-04-25T18:02:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-30T06:24:55.000Z", "max_issues_repo_path": "src/libwalletqt/xmc_int_to_double.hpp", "max_issues_repo_name": "toints/monero-GUI", "max_issues_repo_head_hexsha": "ea29f0ae0e1bc9e00b8a9b69679e302513c3dfcd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libwalletqt/xmc_int_to_double.hpp", "max_forks_repo_name": "toints/monero-GUI", "max_forks_repo_head_hexsha": "ea29f0ae0e1bc9e00b8a9b69679e302513c3dfcd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2018-04-25T01:34:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-20T01:55:13.000Z", "avg_line_length": 44.6666666667, "max_line_length": 91, "alphanum_fraction": 0.7232587065, "num_tokens": 466, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.4593397071655587}}
{"text": "#ifndef Integration_ModifiedArrheniusIntegralBase_hpp\n#define Integration_ModifiedArrheniusIntegralBase_hpp\n\n/** @file ModifiedArrheniusIntegralBase.hpp\n  * @brief \n  * @author C.D. Clark III\n  * @date 06/27/17\n  */\n\n#include <boost/math/tools/roots.hpp>\nusing boost::math::tools::bracket_and_solve_root;\nusing boost::math::tools::eps_tolerance;\n#include \"ArrheniusIntegralBase.hpp\"\n\nnamespace libArrhenius {\n\n/** @class ModifiedArrheniusIntegralBase\n  * @brief Base class for common modified Arrhenius integral data.\n  * @author C.D. Clark III\n  */\ntemplate<typename Real>\nclass ModifiedArrheniusIntegralBase : public ArrheniusIntegralBase<Real>\n{\n  protected:\n    Real n;\n\n  public:\n\n    template<typename T>\n    void setExponent( T n_ ) { n = n_; }\n    Real getExponent( ) { return n; }\n\n    Real getCriticalTemperature() const {\n      Real Tcrit = ArrheniusIntegralBase<Real>::getCriticalTemperature();\n      if( n == 0 )\n        return Tcrit;\n\n      // if n != 0, then we have a transcendental equation we need to solve.\n      //\n      // ln T^n - Ea/R/T + ln A = 0  (solve for T)\n      //\n      // use the n = 0 case as a first gues. this will be too high\n      Real factor = 1.1;\n      eps_tolerance<Real> tol( std::numeric_limits<Real>::digits - 3 );\n      boost::uintmax_t maxit = 100;\n      auto Tcrit_range =  bracket_and_solve_root(\n               [&](Real T){ \n               return Constants::MKS::R*T*log(this->A*pow(T,this->n)) - this->Ea; },\n               Tcrit, factor, true, tol, maxit );\n      Tcrit = Tcrit_range.first;\n      return Tcrit;\n    }\n\n    Real rate( Real T ) const { return pow(T,n)*this->A*exp( -this->Ea / Constants::MKS::R /T ); }\n\n  protected:\n};\n\n}\n\n#endif // include protector\n", "meta": {"hexsha": "b26c725e0dd4d90c1217fc15ec373eb0a09f6f90", "size": 1717, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/libArrhenius/Integration/ModifiedArrheniusIntegralBase.hpp", "max_stars_repo_name": "CD3/libArrhenius", "max_stars_repo_head_hexsha": "2cf65c9935c1661c6150ddfd86a999cf2fff2691", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/libArrhenius/Integration/ModifiedArrheniusIntegralBase.hpp", "max_issues_repo_name": "CD3/libArrhenius", "max_issues_repo_head_hexsha": "2cf65c9935c1661c6150ddfd86a999cf2fff2691", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libArrhenius/Integration/ModifiedArrheniusIntegralBase.hpp", "max_forks_repo_name": "CD3/libArrhenius", "max_forks_repo_head_hexsha": "2cf65c9935c1661c6150ddfd86a999cf2fff2691", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6935483871, "max_line_length": 98, "alphanum_fraction": 0.6482236459, "num_tokens": 470, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825006, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4593293470591112}}
{"text": "/*\nCopyright (C) 2016 Quaternion Risk Management Ltd\nAll rights reserved.\n\nThis file is part of ORE, a free-software/open-source library\nfor transparent pricing and risk analysis - http://opensourcerisk.org\n\nORE is free software: you can redistribute it and/or modify it\nunder the terms of the Modified BSD License.  You should have received a\ncopy of the license along with this program.\nThe license is also available online at <http://opensourcerisk.org>\n\nThis program is distributed on the basis that it will form a useful\ncontribution to risk analytics and model standardisation, but WITHOUT\nANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\nFITNESS FOR A PARTICULAR PURPOSE. See the license for more details.\n*/\n\n#include \"toplevelfixture.hpp\"\n#include \"utilities.hpp\"\n#include <boost/make_shared.hpp>\n#include <boost/test/unit_test.hpp>\n\n#include <qle/termstructures/interpolatedyoycapfloortermpricesurface.hpp>\n\n#include <ql/indexes/inflation/euhicp.hpp>\n#include <ql/math/interpolations/bilinearinterpolation.hpp>\n#include <ql/math/interpolations/linearinterpolation.hpp>\n#include <ql/math/matrix.hpp>\n#include <ql/quotes/simplequote.hpp>\n#include <ql/termstructures/inflation/piecewisezeroinflationcurve.hpp>\n#include <ql/termstructures/volatility/equityfx/blackvariancesurface.hpp>\n#include <ql/termstructures/yield/flatforward.hpp>\n#include <ql/time/calendars/target.hpp>\n\nusing namespace QuantExt;\nusing namespace QuantLib;\nusing namespace boost::unit_test_framework;\n\nBOOST_FIXTURE_TEST_SUITE(QuantExtTestSuite, qle::test::TopLevelFixture)\n\nBOOST_AUTO_TEST_SUITE(CapFloordTermPriceSurfaceTest)\n\nBOOST_AUTO_TEST_CASE(testInterpolatedYoyCapFloorTermPriceSurface) {\n\n    BOOST_TEST_MESSAGE(\"Testing InterpolatedYoyCapFloorTermPriceSurface\");\n\n    Date asof_ = Date(18, July, 2016);\n    Settings::instance().evaluationDate() = asof_;\n\n    Handle<YieldTermStructure> nominalTs =\n        Handle<YieldTermStructure>(boost::make_shared<FlatForward>(0, TARGET(), 0.005, Actual365Fixed()));\n\n    std::vector<Rate> capStrikes;\n    capStrikes.push_back(0.01);\n    capStrikes.push_back(0.02);\n    capStrikes.push_back(0.03);\n    capStrikes.push_back(0.04);\n    capStrikes.push_back(0.05);\n\n    std::vector<Rate> floorStrikes;\n    floorStrikes.push_back(-0.02);\n    floorStrikes.push_back(-0.01);\n    floorStrikes.push_back(0.0);\n    floorStrikes.push_back(0.01);\n    floorStrikes.push_back(0.02);\n\n    std::vector<Period> maturities;\n    maturities.push_back(Period(2, Years));\n    maturities.push_back(Period(5, Years));\n    maturities.push_back(Period(7, Years));\n    maturities.push_back(Period(10, Years));\n    maturities.push_back(Period(15, Years));\n    maturities.push_back(Period(20, Years));\n\n    Matrix capPrice(capStrikes.size(), maturities.size(), Null<Real>()),\n        floorPrice(floorStrikes.size(), maturities.size(), Null<Real>());\n\n    capPrice[0][0] = 0.00874;\n    capPrice[1][0] = 0.00146;\n    capPrice[2][0] = 0.00019;\n    capPrice[3][0] = 0.00003;\n    capPrice[4][0] = 0.00001;\n    capPrice[0][1] = 0.02946;\n    capPrice[1][1] = 0.00793;\n    capPrice[2][1] = 0.00214;\n    capPrice[3][1] = 0.00074;\n    capPrice[4][1] = 0.00032;\n    capPrice[0][2] = 0.04626;\n    capPrice[1][2] = 0.01448;\n    capPrice[2][2] = 0.00481;\n    capPrice[3][2] = 0.00206;\n    capPrice[4][2] = 0.00107;\n    capPrice[0][3] = 0.07622;\n    capPrice[1][3] = 0.02778;\n    capPrice[2][3] = 0.01106;\n    capPrice[3][3] = 0.00565;\n    capPrice[4][3] = 0.00343;\n    capPrice[0][4] = 0.13218;\n    capPrice[1][4] = 0.05476;\n    capPrice[2][4] = 0.0245;\n    capPrice[3][4] = 0.01393;\n    capPrice[4][4] = 0.00927;\n    capPrice[0][5] = 0.18889;\n    capPrice[1][5] = 0.08297;\n    capPrice[2][5] = 0.03909;\n    capPrice[3][5] = 0.02369;\n    capPrice[4][5] = 0.01674;\n    floorPrice[0][0] = 0.000000001;\n    floorPrice[1][0] = 0.00005;\n    floorPrice[2][0] = 0.00057;\n    floorPrice[3][0] = 0.00415;\n    floorPrice[4][0] = 0.01695;\n    floorPrice[0][1] = 0.00005;\n    floorPrice[1][1] = 0.00071;\n    floorPrice[2][1] = 0.00259;\n    floorPrice[3][1] = 0.01135;\n    floorPrice[4][1] = 0.03983;\n    floorPrice[0][2] = 0.00035;\n    floorPrice[1][2] = 0.00131;\n    floorPrice[2][2] = 0.00482;\n    floorPrice[3][2] = 0.0169;\n    floorPrice[4][2] = 0.05463;\n    floorPrice[0][3] = 0.0014;\n    floorPrice[1][3] = 0.0036;\n    floorPrice[2][3] = 0.00943;\n    floorPrice[3][3] = 0.02584;\n    floorPrice[4][3] = 0.07515;\n    floorPrice[0][4] = 0.00481;\n    floorPrice[1][4] = 0.00904;\n    floorPrice[2][4] = 0.01814;\n    floorPrice[3][4] = 0.04028;\n    floorPrice[4][4] = 0.10449;\n    floorPrice[0][5] = 0.00832;\n    floorPrice[1][5] = 0.01433;\n    floorPrice[2][5] = 0.02612;\n    floorPrice[3][5] = 0.05269;\n    floorPrice[4][5] = 0.12839;\n\n    // build a\n    std::vector<Date> datesZCII;\n    datesZCII.push_back(asof_ + 1 * Years);\n    std::vector<Rate> ratesZCII;\n    ratesZCII.push_back(1.1625);\n\n    // build EUHICPXT fixing history\n    Schedule fixingDatesEUHICPXT =\n        MakeSchedule().from(Date(1, May, 2015)).to(Date(1, July, 2016)).withTenor(1 * Months);\n    std::vector<Real> fixingRatesEUHICPXT(15, 100);\n\n    Handle<ZeroInflationIndex> hEUHICPXT;\n    boost::shared_ptr<EUHICPXT> ii = boost::shared_ptr<EUHICPXT>(new EUHICPXT(false));\n    boost::shared_ptr<ZeroInflationTermStructure> cpiTS;\n    for (Size i = 0; i < fixingDatesEUHICPXT.size(); i++) {\n        ii->addFixing(fixingDatesEUHICPXT[i], fixingRatesEUHICPXT[i], true);\n    };\n    // now build the helpers ...\n    std::vector<boost::shared_ptr<BootstrapHelper<ZeroInflationTermStructure> > > instruments;\n    for (Size i = 0; i < datesZCII.size(); i++) {\n        Handle<Quote> quote(boost::shared_ptr<Quote>(new SimpleQuote(ratesZCII[i] / 100.0)));\n        boost::shared_ptr<BootstrapHelper<ZeroInflationTermStructure> > anInstrument(new ZeroCouponInflationSwapHelper(\n            quote, Period(3, Months), datesZCII[i], TARGET(), ModifiedFollowing, Actual365Fixed(), ii, nominalTs));\n        instruments.push_back(anInstrument);\n    };\n\n    Rate baseZeroRate = ratesZCII[0] / 100.0;\n    boost::shared_ptr<PiecewiseZeroInflationCurve<Linear>> pCPIts(new PiecewiseZeroInflationCurve<Linear>(\n        asof_, TARGET(), Actual365Fixed(), Period(3, Months), Monthly, false, baseZeroRate, instruments));\n    pCPIts->recalculate();\n    cpiTS = boost::dynamic_pointer_cast<ZeroInflationTermStructure>(pCPIts);\n\n    boost::shared_ptr<EUHICPXT> zii(new EUHICPXT(false, Handle<ZeroInflationTermStructure>(pCPIts)));\n    boost::shared_ptr<ZeroInflationIndex> zeroIndex = boost::dynamic_pointer_cast<ZeroInflationIndex>(zii);\n\n    boost::shared_ptr<YoYInflationIndex> yoyIndex;\n\n    yoyIndex =\n        boost::make_shared<QuantExt::YoYInflationIndexWrapper>(zeroIndex, true, Handle<YoYInflationTermStructure>());\n\n    QuantExt::InterpolatedYoYCapFloorTermPriceSurface<Bilinear, Linear> ys(\n        0, Period(3, Months), yoyIndex, 1, nominalTs, Actual365Fixed(), TARGET(), Following, capStrikes, floorStrikes,\n        maturities, capPrice, floorPrice);\n\n    boost::shared_ptr<QuantExt::InterpolatedYoYCapFloorTermPriceSurface<Bilinear, Linear> > yoySurface =\n        boost::make_shared<QuantExt::InterpolatedYoYCapFloorTermPriceSurface<Bilinear, Linear> >(ys);\n\n    // check the cap and floor prices from the surface\n    Real tol = 1.0E-8;\n    for (Size i = 0; i < maturities.size(); i++) {\n        Date m = yoySurface->yoyOptionDateFromTenor(maturities[i]);\n        for (Size j = 0; j < capStrikes.size(); j++) {\n            BOOST_CHECK_CLOSE(yoySurface->capPrice(m, capStrikes[j]), capPrice[j][i], tol);\n        }\n        for (Size j = 0; j < floorStrikes.size(); j++) {\n            BOOST_CHECK_CLOSE(yoySurface->floorPrice(m, floorStrikes[j]), floorPrice[j][i], tol);\n        }\n    }\n} // testInterpolatedYoyCapFloorTermPriceSurface\n\nBOOST_AUTO_TEST_SUITE_END()\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "4685f28d7553bfcbc2f8f327026a2b26443eb639", "size": 7842, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QuantExt/test/interpolatedyoycapfloortermpricesurface.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/test/interpolatedyoycapfloortermpricesurface.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/test/interpolatedyoycapfloortermpricesurface.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": 38.6305418719, "max_line_length": 119, "alphanum_fraction": 0.6915327723, "num_tokens": 2549, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257126, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4593293350123311}}
{"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 * test_TDMatrix: a program for testing the TDMatrix module\n * prints out PASS/FAIL information. If a certain bit fails,\n * the bit index is returned in the message\n***********************************************************/\n//#include <mpfr.h>\n#include <NTL/lzz_p.h>\n\nNTL_CLIENT\n#include \"../utils/argmap.h\"\n#include \"../TDMatrix.h\"\n\n//#define VERBOSE //check extra information?\n\nint main(int argc, char *argv[])\n{\n#ifdef DEBUG\n    NTL::SetSeed((unsigned char*)\"test_sampleG\",12);\n#endif\n    ArgMapping amap;\n    long k = 2;\n    amap.arg(\"k\", k, \"number of factors (~ log q)\");\n    long n = 2;\n    amap.arg(\"n\", n, \"the small dimension\"); // no default info\n    long e=2;\n    amap.arg(\"e\", e, \"the power of each factor\");\n    long m=0;\n    amap.arg(\"m\", m, \"the dimension m\", \"0: set as n*(2+k*e)\");\n\n    amap.parse(argc, argv); // parses and overrides initail values\n    // for each parameter, one per line,\n\n    if (m < n*(2+k*e)) m = n*(2+k*e);\n\n    TDMatrixParams params(n,k,e,m);\n    //    Vec<long>& factors = params.factors;\n\n    cout << \"n=\" << n << \", m=\" << m << \", k=\"\n         << k     << \", e=\" << e\n\t << \", sigmaX=\" << params.sigmaX << \", q=\" << params.getQ() << endl;\n\n    long mBar = params.mBar;\n    TDMatrix aMat(params);\n    CRTmatrix A;\n    aMat.getA(A);\n\n    \n    const mat_l& R = aMat.getR();\n    #ifdef VERBOSE\n    if (R.NumRows()<50 && R.NumCols()<50)\n        cout << \"\\n R=\" << R << endl;\n    #endif\n\n    mat_l RI(INIT_SIZE, m, n*k*e);\n    for (long i=0; i<mBar; i++) for (long j=0; j<n*k*e; j++)\n        {\n            RI[i][j] = R[i][j];\n        }\n    for (long i=0; i<n*k*e; i++) for (long j=0; j<n*k*e; j++)\n        {\n            if (i==j) RI[i+mBar][j] = 1;\n            else      RI[i+mBar][j] = 0;\n        }\n\n    #ifdef VERBOSE\n    for (long i=0; i<k; i++)\n    {\n        params.zzp_context[i].restore();\n        if (params.m < 50)\n            cout << \"\\n A mod \" << zz_p::modulus() << \"=\" << A[i] << endl;\n\n        mat_zz_p A_RI;\n        mul(A_RI, A[i], conv<mat_zz_p>(RI));\n        if (params.m < 50)\n            cout << \"\\n A*[R/I] mod \" << zz_p::modulus() << \"=\"\n                 << A_RI << endl;\n    }\n    #endif\n\n    // Compute a random syndrome\n    Vec<vec_zz_p> syndrome(INIT_SIZE, k);\n    for (long i=0; i<k; i++)\n    {\n        params.zzp_context[i].restore();\n        syndrome[i].SetLength(n);\n        for (long j=0; j<n; j++) syndrome[i][j] = random_zz_p();\n\n        #ifdef VERBOSE\n        if (params.m < 50)\n            cout << \"syndrome mod \"\n                 << power_long(factors[i],e)<<\" ((factor \"<<i<<\")^\"<<e+1<<\")= \"<<syndrome[i]<<endl <<flush;\n        #endif\n    }\n\n    // Sample x such that A*x = syndrome\n    Vec<long> x;\n    aMat.sampleWithTrapdoor(x, syndrome);\n    // vec_l p, z;\n    // aMat.sampleWithTrapdoor(x, p, z, syndrome); // debugging version\n\n    #ifdef VERBOSE\n    if (params.m < 50) cout << \"sampled vector=\"<<x<<endl;\n    #endif\n\n    assert(x.length()== m);\n    // check that we have the right answer modulo p^e for all factors\n\n    bool bSuccess = true;\n\n    for (long i=0; i<k; i++)\n    {\n        params.zzp_context[i].restore();\n        vec_zz_p xMod = conv<vec_zz_p>(x);\n        vec_zz_p uu;\n        mul(uu, A[i], xMod);\n        if (syndrome[i]!=uu)\n        {\n            cout << \"bit \" << i << \" failed!\" << endl;\n            bSuccess = false;\n\n            //assert(syndrome[i]==uu);\n        }\n    }\n    if (bSuccess == true)\n        cout << \"\\nPASSED\\n\";\n    cout << \"maxSigma=\"<<Gaussian1Dsampler::maxSigma\n         << \", maxSample=\"<<TDMatrix::maxSample << endl;\n\n#ifdef DEBUG\n    printAllTimers(cout);\n#endif\n\n#ifdef CodeBlocks\n    cin.get();\n#endif\n\n    return 0;\n\n\n}\n", "meta": {"hexsha": "af3c563135bc15d9e6a12e6d709c4f619894d70d", "size": 4295, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "programs/test_TDmatrix.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": "programs/test_TDmatrix.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": "programs/test_TDmatrix.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.2565789474, "max_line_length": 107, "alphanum_fraction": 0.529685681, "num_tokens": 1249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191460821871, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.45930134896801744}}
{"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   testVector.cpp\n * @brief  Unit tests for Vector class\n * @author Frank Dellaert\n **/\n\n#include <gtsam/base/Vector.h>\n#include <gtsam/base/VectorSpace.h>\n#include <gtsam/base/testLie.h>\n#include <CppUnitLite/TestHarness.h>\n#include <boost/tuple/tuple.hpp>\n#include <iostream>\n\nusing namespace std;\nusing namespace gtsam;\n\nnamespace {\n  /* ************************************************************************* */\n  template<typename Derived>\n  Vector testFcn1(const Eigen::DenseBase<Derived>& in)\n  {\n    return in;\n  }\n\n  /* ************************************************************************* */\n  template<typename Derived>\n  Vector testFcn2(const Eigen::MatrixBase<Derived>& in)\n  {\n    return in;\n  }\n}\n\n/* ************************************************************************* */\nTEST(Vector, special_comma_initializer)\n{\n  Vector expected(3);\n  expected(0) = 1;\n  expected(1) = 2;\n  expected(2) = 3;\n\n  Vector actual1 = Vector3(1, 2, 3);\n  Vector actual2(Vector3(1, 2, 3));\n\n  Vector subvec1 = Vector2(2, 3);\n  Vector actual4 = (Vector(3) << 1, subvec1).finished();\n\n  Vector subvec2 = Vector2(1, 2);\n  Vector actual5 = (Vector(3) << subvec2, 3).finished();\n\n  Vector actual6 = testFcn1(Vector3(1, 2, 3));\n  Vector actual7 = testFcn2(Vector3(1, 2, 3));\n\n  EXPECT(assert_equal(expected, actual1));\n  EXPECT(assert_equal(expected, actual2));\n  EXPECT(assert_equal(expected, actual4));\n  EXPECT(assert_equal(expected, actual5));\n  EXPECT(assert_equal(expected, actual6));\n  EXPECT(assert_equal(expected, actual7));\n}\n\n/* ************************************************************************* */\nTEST(Vector, copy )\n{\n  Vector a(2); a(0) = 10; a(1) = 20;\n  double data[] = {10,20};\n  Vector b(2);\n  copy(data,data+2,b.data());\n  EXPECT(assert_equal(a, b));\n}\n\n/* ************************************************************************* */\nTEST(Vector, scalar_multiply )\n{\n  Vector a(2); a(0) = 10; a(1) = 20;\n  Vector b(2); b(0) = 1; b(1) = 2;\n  EXPECT(assert_equal(a,b*10.0));\n}\n\n/* ************************************************************************* */\nTEST(Vector, scalar_divide )\n{\n  Vector a(2); a(0) = 10; a(1) = 20;\n  Vector b(2); b(0) = 1; b(1) = 2;\n  EXPECT(assert_equal(b,a/10.0));\n}\n\n/* ************************************************************************* */\nTEST(Vector, negate )\n{\n  Vector a(2); a(0) = 10; a(1) = 20;\n  Vector b(2); b(0) = -10; b(1) = -20;\n  EXPECT(assert_equal(b, -a));\n}\n\n/* ************************************************************************* */\nTEST(Vector, householder )\n{\n  Vector x(4);\n  x(0) = 3; x(1) = 1; x(2) = 5; x(3) = 1;\n\n  Vector expected(4);\n  expected(0) = 1.0; expected(1) = -0.333333; expected(2) = -1.66667; expected(3) = -0.333333;\n\n  pair<double, Vector> result = house(x);\n\n  EXPECT(result.first==0.5);\n  EXPECT(equal_with_abs_tol(expected,result.second,1e-5));\n}\n\n/* ************************************************************************* */\nTEST(Vector, concatVectors)\n{\n  Vector A(2);\n  for(int i = 0; i < 2; i++)\n    A(i) = i;\n  Vector B(5);\n  for(int i = 0; i < 5; i++)\n    B(i) = i;\n\n  Vector C(7);\n  for(int i = 0; i < 2; i++) C(i) = A(i);\n  for(int i = 0; i < 5; i++) C(i+2) = B(i);\n\n  list<Vector> vs;\n  vs.push_back(A);\n  vs.push_back(B);\n  Vector AB1 = concatVectors(vs);\n  EXPECT(AB1 == C);\n\n  Vector AB2 = concatVectors(2, &A, &B);\n  EXPECT(AB2 == C);\n}\n\n/* ************************************************************************* */\nTEST(Vector, weightedPseudoinverse )\n{\n  // column from a matrix\n  Vector x(2);\n  x(0) = 1.0; x(1) = 2.0;\n\n  // create sigmas\n  Vector sigmas(2);\n  sigmas(0) = 0.1; sigmas(1) = 0.2;\n  Vector weights = sigmas.array().square().inverse();\n\n  // perform solve\n  Vector actual; double precision;\n  boost::tie(actual, precision) = weightedPseudoinverse(x, weights);\n\n  // construct expected\n  Vector expected(2);\n  expected(0) = 0.5; expected(1) = 0.25;\n  double expPrecision = 200.0;\n\n  // verify\n  EXPECT(assert_equal(expected,actual));\n  EXPECT(std::abs(expPrecision-precision) < 1e-5);\n}\n\n/* ************************************************************************* */\nTEST(Vector, weightedPseudoinverse_constraint )\n{\n  // column from a matrix\n  Vector x(2);\n  x(0) = 1.0; x(1) = 2.0;\n\n  // create sigmas\n  Vector sigmas(2);\n  sigmas(0) = 0.0; sigmas(1) = 0.2;\n  Vector weights = sigmas.array().square().inverse();\n  // perform solve\n  Vector actual; double precision;\n  boost::tie(actual, precision) = weightedPseudoinverse(x, weights);\n\n  // construct expected\n  Vector expected(2);\n  expected(0) = 1.0; expected(1) = 0.0;\n\n  // verify\n  EXPECT(assert_equal(expected,actual));\n  EXPECT(std::isinf(precision));\n}\n\n/* ************************************************************************* */\nTEST(Vector, weightedPseudoinverse_nan )\n{\n  Vector a = (Vector(4) << 1., 0., 0., 0.).finished();\n  Vector sigmas = (Vector(4) << 0.1, 0.1, 0., 0.).finished();\n  Vector weights = sigmas.array().square().inverse();\n  Vector pseudo; double precision;\n  boost::tie(pseudo, precision) = weightedPseudoinverse(a, weights);\n\n  Vector expected = (Vector(4) << 1., 0., 0.,0.).finished();\n  EXPECT(assert_equal(expected, pseudo));\n  DOUBLES_EQUAL(100, precision, 1e-5);\n}\n\n/* ************************************************************************* */\nTEST(Vector, dot )\n{\n  Vector a = Vector3(10., 20., 30.);\n  Vector b = Vector3(2.0, 5.0, 6.0);\n  DOUBLES_EQUAL(20+100+180,dot(a,b),1e-9);\n}\n\n/* ************************************************************************* */\nTEST(Vector, axpy )\n{\n  Vector x = Vector3(10., 20., 30.);\n  Vector y0 = Vector3(2.0, 5.0, 6.0);\n  Vector y1 = y0, y2 = y0;\n  y1 += 0.1 * x;\n  y2.head(3) += 0.1 * x;\n  Vector expected = Vector3(3.0, 7.0, 9.0);\n  EXPECT(assert_equal(expected,y1));\n  EXPECT(assert_equal(expected,Vector(y2)));\n}\n\n/* ************************************************************************* */\nTEST(Vector, equals )\n{\n  Vector v1 = (Vector(1) << 0.0/std::numeric_limits<double>::quiet_NaN()).finished(); //testing nan\n  Vector v2 = (Vector(1) << 1.0).finished();\n  double tol = 1.;\n  EXPECT(!equal_with_abs_tol(v1, v2, tol));\n}\n\n/* ************************************************************************* */\nTEST(Vector, greater_than )\n{\n  Vector v1 = Vector3(1.0, 2.0, 3.0),\n       v2 = Z_3x1;\n  EXPECT(greaterThanOrEqual(v1, v1)); // test basic greater than\n  EXPECT(greaterThanOrEqual(v1, v2)); // test equals\n}\n\n/* ************************************************************************* */\nTEST(Vector, linear_dependent )\n{\n  Vector v1 = Vector3(1.0, 2.0, 3.0);\n  Vector v2 = Vector3(-2.0, -4.0, -6.0);\n  EXPECT(linear_dependent(v1, v2));\n}\n\n/* ************************************************************************* */\nTEST(Vector, linear_dependent2 )\n{\n  Vector v1 = Vector3(0.0, 2.0, 0.0);\n  Vector v2 = Vector3(0.0, -4.0, 0.0);\n  EXPECT(linear_dependent(v1, v2));\n}\n\n/* ************************************************************************* */\nTEST(Vector, linear_dependent3 )\n{\n  Vector v1 = Vector3(0.0, 2.0, 0.0);\n  Vector v2 = Vector3(0.1, -4.1, 0.0);\n  EXPECT(!linear_dependent(v1, v2));\n}\n\n//******************************************************************************\nTEST(Vector, IsVectorSpace) {\n  BOOST_CONCEPT_ASSERT((IsVectorSpace<Vector5>));\n  BOOST_CONCEPT_ASSERT((IsVectorSpace<Vector>));\n  typedef Eigen::Matrix<double,1,-1> RowVector;\n  BOOST_CONCEPT_ASSERT((IsVectorSpace<RowVector>));\n}\n\n/* ************************************************************************* */\nint main() { TestResult tr; return TestRegistry::runAllTests(tr); }\n/* ************************************************************************* */\n", "meta": {"hexsha": "c87732b099ef44247ad47950e0b03a7d799ca309", "size": 8039, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/base/tests/testVector.cpp", "max_stars_repo_name": "h-rover/gtsam", "max_stars_repo_head_hexsha": "a0206e210d8f47b6ee295a1fbf95af84d98c5cf0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-04T07:01:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T07:01:48.000Z", "max_issues_repo_path": "gtsam/base/tests/testVector.cpp", "max_issues_repo_name": "h-rover/gtsam", "max_issues_repo_head_hexsha": "a0206e210d8f47b6ee295a1fbf95af84d98c5cf0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 22.0, "max_issues_repo_issues_event_min_datetime": "2022-02-08T18:34:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T16:14:32.000Z", "max_forks_repo_path": "gtsam/base/tests/testVector.cpp", "max_forks_repo_name": "h-rover/gtsam", "max_forks_repo_head_hexsha": "a0206e210d8f47b6ee295a1fbf95af84d98c5cf0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-14T10:10:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T10:10:40.000Z", "avg_line_length": 28.406360424, "max_line_length": 99, "alphanum_fraction": 0.48662769, "num_tokens": 2233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982315512489, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.45930134498499964}}
{"text": "//# /Users/arnold/Documents/prg/clang/bin/clang++ -U__STRICT_ANSI__ -std=c++14 -I/Users/arnold/Documents/prg/libraries/boost_1_56_0/ -I/Developer/SDKs/MacOSX10.6.sdk/usr/include -Wall -O2 -L/Users/arnold/Documents/prg/libraries/boost_1_56_0/stage/lib  -o sint sint.cpp -lboost_system -lboost_filesystem -lboost_iostreams \n#include <iostream>                                                \n#include <boost/format.hpp>\n\nusing namespace std;\n                       \nclass SInt {                        \npublic:\n\tstatic constexpr unsigned convert(int i)     { return (static_cast<unsigned>(i) << 1) ^ (i >> (sizeof(int)*8-1)); }\n\tstatic constexpr int convertBack(unsigned i) { return (i >> 1) ^ -static_cast<int>(i & 1); }\n\texplicit SInt(const int& i) : v_{convert(i)}{}\n\toperator unsigned() const noexcept { return v_; }\nprivate:\n\tunsigned v_;\n};\n\ntemplate<typename T>\nstruct Str2Bin {\n\texplicit Str2Bin(const T& t) : t_{t}{}\n\tconst volatile T& t_;\n};\n\ntemplate<typename T>\nostream& operator<<(ostream& o, const Str2Bin<T>& s) {\n\tT t = s.t_;\n\tfor(unsigned i = 0; i < sizeof(T) * 8; ++i, t<<=1) {\n\t\tif (i>0 && i % 8 == 0)\n\t\t\to << '.';\n\t\to << (t & (1<<(sizeof(T)*8-1) ) ? '1' : '0');\n\t}\n\treturn o;\n}\n\n\n\nint main (int argc, char const *argv[])\n{\n\tint ret = 0;\n\tint max = 255;\n\tfor(int i = -max; i <= max; ++i) {      \n\t\tSInt s(i);                                                                                         \n\t\tint j = SInt::convertBack(s);\n\t\tcout << boost::format{\"%3d _ \"} % i << Str2Bin<int>(i) \n\t\t\t << boost::format{\" _ %3d _ \"} % s \n\t\t\t<< Str2Bin<unsigned>(s) << boost::format{\" _ %3d _ \"} % j \n\t\t\t<< Str2Bin<int>(j) << endl;\n\t}\n\treturn ret;\n}", "meta": {"hexsha": "85a5eebc1f5ad51041bba2e6c80bbfd652e87daa", "size": 1654, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp14/sint.cpp", "max_stars_repo_name": "noeld/cpp", "max_stars_repo_head_hexsha": "572a145f8c79f7292b7b0611822ed34792df4e9c", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cpp14/sint.cpp", "max_issues_repo_name": "noeld/cpp", "max_issues_repo_head_hexsha": "572a145f8c79f7292b7b0611822ed34792df4e9c", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp14/sint.cpp", "max_forks_repo_name": "noeld/cpp", "max_forks_repo_head_hexsha": "572a145f8c79f7292b7b0611822ed34792df4e9c", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7551020408, "max_line_length": 321, "alphanum_fraction": 0.5525997582, "num_tokens": 503, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191460821871, "lm_q2_score": 0.6477982247516797, "lm_q1q2_score": 0.45930134414699264}}
{"text": "// Copyright Abel Sinkovics (abel@sinkovics.hu)  2011.\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#include <boost/metaparse/repeated.hpp>\r\n#include <boost/metaparse/sequence.hpp>\r\n#include <boost/metaparse/lit_c.hpp>\r\n#include <boost/metaparse/last_of.hpp>\r\n#include <boost/metaparse/first_of.hpp>\r\n#include <boost/metaparse/space.hpp>\r\n#include <boost/metaparse/int_.hpp>\r\n#include <boost/metaparse/foldl_reject_incomplete_start_with_parser.hpp>\r\n#include <boost/metaparse/one_of.hpp>\r\n#include <boost/metaparse/get_result.hpp>\r\n#include <boost/metaparse/token.hpp>\r\n#include <boost/metaparse/entire_input.hpp>\r\n#include <boost/metaparse/string.hpp>\r\n#include <boost/metaparse/build_parser.hpp>\r\n\r\n#include <boost/mpl/apply_wrap.hpp>\r\n#include <boost/mpl/fold.hpp>\r\n#include <boost/mpl/front.hpp>\r\n#include <boost/mpl/back.hpp>\r\n#include <boost/mpl/plus.hpp>\r\n#include <boost/mpl/minus.hpp>\r\n#include <boost/mpl/times.hpp>\r\n#include <boost/mpl/divides.hpp>\r\n#include <boost/mpl/bool.hpp>\r\n#include <boost/mpl/equal_to.hpp>\r\n#include <boost/mpl/eval_if.hpp>\r\n#include <boost/mpl/bool.hpp>\r\n\r\nusing boost::metaparse::sequence;\r\nusing boost::metaparse::lit_c;\r\nusing boost::metaparse::last_of;\r\nusing boost::metaparse::first_of;\r\nusing boost::metaparse::space;\r\nusing boost::metaparse::repeated;\r\nusing boost::metaparse::build_parser;\r\nusing boost::metaparse::int_;\r\nusing boost::metaparse::foldl_reject_incomplete_start_with_parser;\r\nusing boost::metaparse::get_result;\r\nusing boost::metaparse::one_of;\r\nusing boost::metaparse::token;\r\nusing boost::metaparse::entire_input;\r\n\r\nusing boost::mpl::apply_wrap1;\r\nusing boost::mpl::fold;\r\nusing boost::mpl::front;\r\nusing boost::mpl::back;\r\nusing boost::mpl::plus;\r\nusing boost::mpl::minus;\r\nusing boost::mpl::times;\r\nusing boost::mpl::divides;\r\nusing boost::mpl::eval_if;\r\nusing boost::mpl::bool_;\r\nusing boost::mpl::equal_to;\r\nusing boost::mpl::bool_;\r\n\r\n/*\r\n * The grammar\r\n *\r\n * expression ::= plus_exp\r\n * plus_exp ::= prod_exp ((plus_token | minus_token) prod_exp)*\r\n * prod_exp ::= int_token ((mult_token | div_token) int_token)*\r\n */\r\n\r\ntypedef token<lit_c<'+'> > plus_token;\r\ntypedef token<lit_c<'-'> > minus_token;\r\ntypedef token<lit_c<'*'> > mult_token;\r\ntypedef token<lit_c<'/'> > div_token;\r\n \r\ntypedef token<int_> int_token;\r\n\r\ntemplate <class T, char C>\r\nstruct is_c : bool_<T::type::value == C> {};\r\n\r\nstruct eval_plus\r\n{\r\n  template <class State, class C>\r\n  struct apply :\r\n    eval_if<\r\n      is_c<front<C>, '+'>,\r\n      plus<typename State::type, typename back<C>::type>,\r\n      minus<typename State::type, typename back<C>::type>\r\n    >\r\n  {};\r\n};\r\n\r\nstruct eval_mult\r\n{\r\n  template <class State, class C>\r\n  struct apply :\r\n    eval_if<\r\n      is_c<front<C>, '*'>,\r\n      times<typename State::type, typename back<C>::type>,\r\n      divides<typename State::type, typename back<C>::type>\r\n    >\r\n  {};\r\n};\r\n\r\ntypedef\r\n  foldl_reject_incomplete_start_with_parser<\r\n    sequence<one_of<mult_token, div_token>, int_token>,\r\n    int_token,\r\n    eval_mult\r\n  >\r\n  prod_exp;\r\n  \r\ntypedef\r\n  foldl_reject_incomplete_start_with_parser<\r\n    sequence<one_of<plus_token, minus_token>, prod_exp>,\r\n    prod_exp,\r\n    eval_plus\r\n  >\r\n  plus_exp;\r\n\r\ntypedef last_of<repeated<space>, plus_exp> expression;\r\n\r\ntypedef build_parser<entire_input<expression> > calculator_parser;\r\n\r\n#ifdef _STR\r\n#  error _STR already defined\r\n#endif\r\n#define _STR BOOST_METAPARSE_STRING\r\n\r\n#ifdef BOOST_NO_CXX11_CONSTEXPR\r\nint main()\r\n{\r\n  using std::cout;\r\n  using std::endl;\r\n  using boost::metaparse::string;\r\n  \r\n  cout\r\n    << apply_wrap1<calculator_parser, string<'1','3'> >::type::value << endl\r\n    <<\r\n      apply_wrap1<\r\n        calculator_parser, string<' ','1','+',' ','2','*','4','-','6','/','2'>\r\n      >::type::value\r\n    << endl\r\n    ;\r\n}\r\n#else\r\nint main()\r\n{\r\n  using std::cout;\r\n  using std::endl;\r\n  \r\n  cout\r\n    << apply_wrap1<calculator_parser, _STR(\"13\")>::type::value << endl\r\n    << apply_wrap1<calculator_parser, _STR(\" 1+ 2*4-6/2\")>::type::value << endl\r\n    ;\r\n}\r\n#endif\r\n\r\n\r\n", "meta": {"hexsha": "440d51e802a6d888632dacdb0cad19f2002f7167", "size": 4166, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/metaparse/example/calculator/main.cpp", "max_stars_repo_name": "lijgame/boost", "max_stars_repo_head_hexsha": "ec2214a19cdddd1048058321a8105dd0231dac47", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-12-15T19:57:24.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-15T19:57:24.000Z", "max_issues_repo_path": "thirdparty-cpp/boost_1_62_0/libs/metaparse/example/calculator/main.cpp", "max_issues_repo_name": "nxplatform/nx-mobile", "max_issues_repo_head_hexsha": "0dc174c893f2667377cb2ef7e5ffeb212fa8b3e5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thirdparty-cpp/boost_1_62_0/libs/metaparse/example/calculator/main.cpp", "max_forks_repo_name": "nxplatform/nx-mobile", "max_forks_repo_head_hexsha": "0dc174c893f2667377cb2ef7e5ffeb212fa8b3e5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.3670886076, "max_line_length": 80, "alphanum_fraction": 0.6819491119, "num_tokens": 1132, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191460821871, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.4593013393259678}}
{"text": "// Boost.Geometry\n\n// Copyright (c) 2021, Oracle and/or its affiliates.\n\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\n\n// Licensed under the Boost Software License version 1.0.\n// http://www.boost.org/users/license.html\n\n\n#include <geometry_test_common.hpp>\n\n#include <boost/geometry/algorithms/assign.hpp>\n\n#include <boost/geometry/core/cs.hpp>\n\n#include <boost/geometry/geometries/point.hpp>\n\n#include <boost/geometry/util/algorithm.hpp>\n\n\nvoid test_dimension(bg::util::index_constant<0> index)\n{\n    bool called = false;\n    bg::detail::for_each_index<0>([&](auto index) { called = true; });\n    BOOST_CHECK(!called);\n    BOOST_CHECK(bg::detail::all_indexes_of<0>([&](auto index) { return true; }) == true);\n    BOOST_CHECK(bg::detail::all_indexes_of<0>([&](auto index) { return false; }) == true);\n    BOOST_CHECK(bg::detail::any_index_of<0>([&](auto index) { return true; }) == false);\n    BOOST_CHECK(bg::detail::any_index_of<0>([&](auto index) { return false; }) == false);\n    BOOST_CHECK(bg::detail::none_index_of<0>([&](auto index) { return true; }) == true);\n    BOOST_CHECK(bg::detail::none_index_of<0>([&](auto index) { return false; }) == true);\n}\n\ntemplate <std::size_t I>\nvoid test_dimension(bg::util::index_constant<I>)\n{\n    using point = bg::model::point<double, I, bg::cs::cartesian>;\n    point p;\n    bg::assign_value(p, 10.0);\n\n    bg::detail::for_each_index<I>([&](auto index)\n    {\n        BOOST_CHECK(bg::get<index>(p) == 10.0);\n        bg::set<index>(p, double(index));\n    });\n    bg::detail::for_each_dimension<point>([&](auto index)\n    {\n        BOOST_CHECK(bg::get<index>(p) == double(index));\n    });\n\n    BOOST_CHECK(\n        bg::detail::all_indexes_of<0>([&](auto index)\n        {\n            return bg::get<index>(p) == double(index);\n        }) == true);\n    BOOST_CHECK(\n        bg::detail::all_dimensions_of<point>([&](auto index)\n        {\n            return bg::get<index>(p) == 10;\n        }) == false);\n    BOOST_CHECK(\n        bg::detail::any_index_of<0>([&](auto index)\n        {\n            return false;\n        }) == false);\n    BOOST_CHECK(\n        bg::detail::any_dimension_of<point>([&](auto index)\n        {\n            return bg::get<index>(p) == double(I - 1);\n        }) == true);\n    BOOST_CHECK(\n        bg::detail::none_index_of<0>([&](auto index)\n        {\n            return false;\n        }) == true);\n    BOOST_CHECK(\n        bg::detail::none_dimension_of<point>([&](auto index)\n        {\n            return bg::get<index>(p) == double(0);\n        }) == false);\n}\n\ntemplate <std::size_t I, std::size_t N>\nstruct test_dimensions\n{\n    static void apply()\n    {\n        test_dimension(bg::util::index_constant<I>());\n        test_dimensions<I + 1, N>::apply();\n    }\n};\n\ntemplate <std::size_t N>\nstruct test_dimensions<N, N>\n{\n    static void apply() {}\n};\n\nint test_main(int, char* [])\n{\n    test_dimensions<0, 5>::apply();\n\n    return 0;\n}\n", "meta": {"hexsha": "0aef4ce37d0f04b016884eeed0014472148da50a", "size": 2927, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/util/algorithm.cpp", "max_stars_repo_name": "sehe/geometry", "max_stars_repo_head_hexsha": "14aa0545936dc2ddb7b5c77ccb940e4efdc8d709", "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": "test/util/algorithm.cpp", "max_issues_repo_name": "sehe/geometry", "max_issues_repo_head_hexsha": "14aa0545936dc2ddb7b5c77ccb940e4efdc8d709", "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/util/algorithm.cpp", "max_forks_repo_name": "sehe/geometry", "max_forks_repo_head_hexsha": "14aa0545936dc2ddb7b5c77ccb940e4efdc8d709", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-05-27T13:45:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-27T13:45:19.000Z", "avg_line_length": 27.6132075472, "max_line_length": 90, "alphanum_fraction": 0.5927570892, "num_tokens": 801, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.709019146082187, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.45930133932596773}}
{"text": "/*\n * File:   random.cc\n * Author: ts337\n *\n * Created on 28 February 2011, 11:58\n */\n\n#include \"../random.h\"\n#include <boost/random/poisson_distribution.hpp>\n\n#include <unuran.h>\n#include <unuran_urng_rngstreams.h>\n#include <vector>\n#include <stdexcept>\n#include <string>\n\nusing std::string;\nusing std::logic_error;\nusing std::to_string;\n\nnamespace coela {\n//=========================================================================================================\nnamespace boost_random {\nUniformRandomVariate::UniformRandomVariate(unsigned int seed):\n    rng(seed), dist(0,1), rv(rng,dist) {}\n} //end namespace coela::boost_random\n//=========================================================================================================\n//=========================================================================================================\nnamespace unuran {\n\nint StreamWrapper::num_streams_created=0;\nbool StreamWrapper::package_seed_set=false;\n\nvoid StreamWrapper::set_unuran_package_seed(\n    std::vector<unsigned long>& six_seed_numbers,\n    bool check_if_already_set\n)\n{\n    if (six_seed_numbers.size()!=6) {\n        throw logic_error(\"random_number_stream::set_unuran_package_seed - \"\n                            \"please supply vector of six numbers\");\n    }\n\n    if (check_if_already_set && unuran_package_has_been_seeded()) {\n        throw logic_error(\"random_number_stream::set_unuran_package_seed - \"\n                            \"package seed already set\");\n    }\n\n    RngStream_SetPackageSeed(& six_seed_numbers[0]);\n\n    package_seed_set=true;\n\n}\n\nvoid StreamWrapper::advance_package_seed(const size_t n_steps)\n{\n    for (size_t i=0; i!=n_steps; ++i) {\n        StreamWrapper temp_instantiation_to_force_seed_advance;\n    }\n    return;\n}\n\nStreamWrapper::StreamWrapper()\n{\n    if (!package_seed_set) throw logic_error(\n            \"random_number_stream::random_number_stream() - please set package seed first\");\n\n    rn_stream_ob_ptr = unur_urng_rngstream_new(string(\"urng-\"+\n            to_string(num_streams_created)).c_str());\n\n    if (rn_stream_ob_ptr == NULL) throw std::runtime_error(\n            \"random_number_stream::random_number_stream - could not create new rng stream\");\n    num_streams_created++;\n}\n\nStreamWrapper::~StreamWrapper()\n{\n    unur_urng_free(rn_stream_ob_ptr);\n}\n\n\n//=========================================================================================================\nUniformRandomVariate::UniformRandomVariate(double lower_bound, double upper_bound,\n        StreamWrapper& rns)\n    :gen(NULL)\n{\n\n    assert(lower_bound < upper_bound);\n    UNUR_DISTR *distr;    /* distribution object                   */\n    UNUR_PAR   *par;      /* parameter object                      */\n    double urv_params[2];\n    urv_params[0]=lower_bound;\n    urv_params[1]=upper_bound;\n    distr = unur_distr_uniform(urv_params, 2);\n    par = unur_cstd_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(\"uniform_random_variate (constructor) - could not construct generator.\"); }\n\n}\nUniformRandomVariate::~UniformRandomVariate()\n{\n    unur_free(gen);\n}\n\n\ndouble UniformRandomVariate::operator()()\n{\n    return unur_sample_cont(gen);\n}\n\n\n//=========================================================================================================\n\nGaussianRandomVariate::GaussianRandomVariate(double mean, double sigma,\n        StreamWrapper& wrapped_rng)\n    :gen(NULL)\n{\n    UNUR_DISTR *distr;    /* distribution object                   */\n    UNUR_PAR   *par;      /* parameter object                      */\n    double gaussian_params[2];\n    gaussian_params[0]=mean;\n    gaussian_params[1]=sigma;\n    distr = unur_distr_normal(gaussian_params, 2);\n    par = unur_cstd_new(distr);\n\n    // Choose generation method: http://statmath.wu.ac.at/unuran/doc/unuran.html#normal\n    //TO DO: Profile which is faster for likely use case of single generation per instance.\n//    unur_cstd_set_variant(par, 2);\n\n\n    unur_set_urng(par, wrapped_rng.get_stream_pointer());\n    gen = unur_init(par);\n    unur_distr_free(distr);\n\n    if (gen==NULL) { throw std::runtime_error(\"gaussian_random_variate::gaussian_random_variate - could not construct generator.\"); }\n}\n\nGaussianRandomVariate::~GaussianRandomVariate()\n{\n    unur_free(gen);\n}\n\n//void gaussian_random_variate::update_params(double mean, double sigma){\n//    double gaussian_params[2];\n//    gaussian_params[0]=mean;\n//    gaussian_params[1]=sigma;\n//\n//    unur_distr_cont_set_pdfparams(unur_get_distr(gen), gaussian_params, 2);\n//    unur_distr_cont_upd_mode(unur_get_distr(gen));\n//    unur_distr_cont_upd_pdfarea(unur_get_distr(gen));\n//    if ( unur_reinit(gen) ) throw runtime_error(\"Gaussian_random_variate::update_params - threw an error code\");\n//}\n\ndouble GaussianRandomVariate::operator()()\n{\n    return unur_sample_cont(gen);\n}\n\n//=========================================================================================================\n//=========================================================================================================\n\n// Use default random number stream- deprecated to encourage good use of seeds\n//poisson_random_variate::poisson_random_variate(double lambda)\n//:gen(NULL)\n//{\n//    UNUR_DISTR *distr;    /* distribution object                   */\n//    UNUR_PAR   *par;      /* parameter object                      */\n//    double poisson_params[1];\n//    poisson_params[0]=lambda;\n//    distr = unur_distr_poisson(poisson_params, 1);\n//    par = unur_auto_new(distr);\n//    gen = unur_init(par);\n//    unur_distr_free(distr);\n//\n//    if (gen==NULL) throw std::runtime_error(\"simple_poisson_random_variate::simple_poisson_random_variate - could not construct generator.\");\n// }\n\nPoissonRandomVariate::PoissonRandomVariate(double lambda,\n        StreamWrapper& wrapped_rng)\n    :gen(NULL)\n{\n    UNUR_DISTR *distr;    /* distribution object                   */\n    UNUR_PAR   *par;      /* parameter object                      */\n    double poisson_params[1];\n    poisson_params[0]=lambda;\n    distr = unur_distr_poisson(poisson_params, 1);\n    par = unur_dstd_new(distr);\n    unur_set_urng(par, wrapped_rng.get_stream_pointer());\n    gen = unur_init(par);\n    unur_distr_free(distr);\n\n    if (gen==NULL) {\n        throw std::runtime_error(\n            \"simple_poisson_random_variate - could not construct generator.\");\n    }\n}\n\nPoissonRandomVariate::~PoissonRandomVariate()\n{\n    unur_free(gen);\n}\n\nint PoissonRandomVariate::operator()()\n{\n    return unur_sample_discr(gen);\n}\n\n//=========================================================================================================\n}//end namespace coela::unuran\n}//end namespace coela\n", "meta": {"hexsha": "1c2008fded6e1842e2a4bd65dfa5d721933fecf2", "size": 6774, "ext": "cc", "lang": "C++", "max_stars_repo_path": "coela_random/src/implementation/random.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_random/src/implementation/random.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_random/src/implementation/random.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.6542056075, "max_line_length": 143, "alphanum_fraction": 0.5983170948, "num_tokens": 1508, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850933, "lm_q2_score": 0.6477982247516797, "lm_q1q2_score": 0.45930133618095714}}
{"text": "/// random.hpp\n/// eigen\n///\n/// Purpose:\n/// Define randomization functions used in Eigen operators\n///\n\n#ifndef GLOBAL_RANDOM_HPP\n#define GLOBAL_RANDOM_HPP\n\n#include <random>\n#include <type_traits>\n\n#include <boost/uuid/uuid.hpp>\n#include <boost/uuid/uuid_generators.hpp>\n#include <boost/uuid/uuid_io.hpp>\n\n#include \"internal/global/config.hpp\"\n\nnamespace global\n{\n\n/// Function that returns a generated value\ntemplate <typename T>\nusing GenF = std::function<T()>;\n\nstruct iGenerator\n{\n\tvirtual ~iGenerator (void) = default;\n\n\t/// Return random string\n\tvirtual std::string get_str (void) const = 0;\n\n\t/// Return uniformly generate integer between a and b\n\tvirtual int64_t unif_int (\n\t\tconst int64_t& lower, const int64_t& upper) const = 0;\n\n\t/// Return uniformly generate decimal between a and b\n\tvirtual double unif_dec (\n\t\tconst double& lower, const double& upper) const = 0;\n\n\t/// Return normally generate decimal with mean and stdev\n\tvirtual double norm_dec (\n\t\tconst double& mean, const double& stdev) const = 0;\n\n\t/// Return random string generator function\n\tvirtual GenF<std::string> get_strgen (void) const = 0;\n\n\t/// Return generator function that uniformly generates integers between a and b\n\tvirtual GenF<int64_t> unif_intgen (\n\t\tconst int64_t& lower, const int64_t& upper) const = 0;\n\n\t/// Return generator function that uniformly generates decimals between a and b\n\tvirtual GenF<double> unif_decgen (\n\t\tconst double& lower, const double& upper) const = 0;\n\n\t/// Return generator function that normally generate decimal with mean and stdev\n\tvirtual GenF<double> norm_decgen (\n\t\tconst double& mean, const double& stdev) const = 0;\n};\n\nusing GenPtrT = std::shared_ptr<iGenerator>;\n\nstruct iRandGenerator : public iGenerator\n{\n\tvirtual ~iRandGenerator (void) = default;\n\n\t/// Seed the random engine using seed specified\n\tvirtual void seed (size_t s) = 0;\n};\n\nvoid set_generator (GenPtrT gen, CfgMapptrT ctx = context());\n\nGenPtrT get_generator (const CfgMapptrT& ctx = context());\n\nvoid seed (size_t s, const CfgMapptrT& ctx = context());\n\nstruct Randomizer final : public iRandGenerator\n{\n\t/// Implementation of iGenerator\n\tstd::string get_str (void) const override\n\t{\n\t\treturn boost::uuids::to_string(uengine_());\n\t}\n\n\t/// Implementation of iGenerator\n\tint64_t unif_int (const int64_t& lower, const int64_t& upper) const override\n\t{\n\t\tstd::uniform_int_distribution<int64_t> dist(lower, upper);\n\t\treturn dist(rengine_);\n\t}\n\n\t/// Implementation of iGenerator\n\tdouble unif_dec (const double& lower, const double& upper) const override\n\t{\n\t\tstd::uniform_real_distribution<double> dist(lower, upper);\n\t\treturn dist(rengine_);\n\t}\n\n\t/// Implementation of iGenerator\n\tdouble norm_dec (const double& mean, const double& stdev) const override\n\t{\n\t\tstd::normal_distribution<double> dist(mean, stdev);\n\t\treturn dist(rengine_);\n\t}\n\n\t/// Implementation of iGenerator\n\tGenF<std::string> get_strgen (void) const override\n\t{\n\t\treturn [this]{ return boost::uuids::to_string(this->uengine_()); };\n\t}\n\n\t/// Implementation of iGenerator\n\tGenF<int64_t> unif_intgen (\n\t\tconst int64_t& lower, const int64_t& upper) const override\n\t{\n\t\tstd::uniform_int_distribution<int64_t> dist(lower, upper);\n\t\treturn std::bind(dist, rengine_);\n\t}\n\n\t/// Implementation of iGenerator\n\tGenF<double> unif_decgen (\n\t\tconst double& lower, const double& upper) const override\n\t{\n\t\tstd::uniform_real_distribution<double> dist(lower, upper);\n\t\treturn std::bind(dist, rengine_);\n\t}\n\n\t/// Implementation of iGenerator\n\tGenF<double> norm_decgen (\n\t\tconst double& mean, const double& stdev) const override\n\t{\n\t\tstd::normal_distribution<double> dist(mean, stdev);\n\t\treturn std::bind(dist, rengine_);\n\t}\n\n\t/// Implementation of iRandGenerator\n\tvoid seed (size_t s) override\n\t{\n\t\trengine_.seed(s);\n\t}\n\n\tmutable std::default_random_engine rengine_;\n\n\tmutable boost::uuids::random_generator uengine_;\n};\n\n}\n\n#endif // GLOBAL_RANDOM_HPP\n", "meta": {"hexsha": "8e38b2680ccf8a2ed3b2dbd471e242cf08b13130", "size": 3893, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "internal/global/random.hpp", "max_stars_repo_name": "mingkaic/tenncor", "max_stars_repo_head_hexsha": "f2fa9652e55e9ca206de5e9741fe41bde43791c1", "max_stars_repo_licenses": ["BSL-1.0", "MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-29T20:38:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-29T20:38:08.000Z", "max_issues_repo_path": "internal/global/random.hpp", "max_issues_repo_name": "mingkaic/tenncor", "max_issues_repo_head_hexsha": "f2fa9652e55e9ca206de5e9741fe41bde43791c1", "max_issues_repo_licenses": ["BSL-1.0", "MIT"], "max_issues_count": 16.0, "max_issues_repo_issues_event_min_datetime": "2018-01-28T04:20:19.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-23T09:38:52.000Z", "max_forks_repo_path": "internal/global/random.hpp", "max_forks_repo_name": "mingkaic/tenncor", "max_forks_repo_head_hexsha": "f2fa9652e55e9ca206de5e9741fe41bde43791c1", "max_forks_repo_licenses": ["BSL-1.0", "MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7814569536, "max_line_length": 81, "alphanum_fraction": 0.7364500385, "num_tokens": 997, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191214879991, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.4593013233938966}}
{"text": "/*\n * mapr_project.cpp\n *\n *  Created on: June 15, 2020\n *      Author: Kamil Miedzinski Mateusz Grycmacher\n *\t Institute: Instute of Home, Poznan University of Technology\n */\n\n#include \"../include/mapr_project/mapr_project.hpp\"\n\n// Boost\n#include <boost/bind.hpp>\n#include <boost/thread/recursive_mutex.hpp>\n\n// STL\n#include <string>\n#include <math.h>\n#include <limits>\n#include <thread>\n\nusing namespace std;\nusing namespace ros;\n\nnamespace ob = ompl::base;\nnamespace og = ompl::geometric;\n\nnamespace mapr_project {\n\ngrid_map_msgs::GridMap gridMap;\n\ndouble point_start_x = -0.5;\ndouble point_start_y = -0.5;\ndouble point_end_x = -5.0;\ndouble point_end_y = -5.0;\n\nclass ValidityChecker : public ob::StateValidityChecker\n{\npublic:\n    ValidityChecker(const ob::SpaceInformationPtr& si) :\n        ob::StateValidityChecker(si) {}\n \n    bool isValid(const ob::State* state) const\n    {\n        return this->clearance(state);\n    }\n\n    double clearance(const ob::State* state) const\n    {\n        const ob::RealVectorStateSpace::StateType* state2D =\n            state->as<ob::RealVectorStateSpace::StateType>();\n        // Extract the robot's (x,y) position from its state\n        double x = state2D->values[0];\n        double y = state2D->values[0];\n        int col = (x)/(-0.1);\n     \tint row = (y)/(-0.1);\n\n\tfloat resolution = gridMap.info.resolution;\n\n  \tfloat point_start_z = 0;\n\tfloat point_end_z = 0;\n\n  \tif(gridMap.info.length_x>0)  // Mapa wysokosci subskyrbowana\n\t{\n\t\t// Wysokosc z jakiej startujemy i do jakiej zmierzamy\n\t\tpoint_start_z = gridMap.data[0].data[(point_start_x/resolution*(-1)) + (point_start_y/resolution*(-1)) * 64];\n\t\tpoint_end_z = gridMap.data[0].data[(point_end_x/resolution*(-1)) + (point_end_y/resolution*(-1)) * 64];\n\t\t//std::cout << \"point_start_z: \" << point_start_z << \" point_end_z: \" << point_end_z << \"\\n\";\n\n\t\t// Idziemy z gorki\n\t\tif(point_start_z > point_end_z) \t\n\t\t{\n\t\t\tif ((gridMap.data[0].data[col + row * 64]<point_start_z) && (gridMap.data[0].data[col + row * 64]>point_end_z))\n\t    \t\t{\n\t\t\t\t\n\t\t\t\treturn gridMap.data[0].data[col + row * 64]; \n\t \t\t} \n\t\t \telse\n\t\t\t{\n\t\t\t\treturn gridMap.data[0].data[col + row * 64]*gridMap.data[0].data[col + row * 64]; \n\t\t\t}\n\t\t}\n\t\telse // Idziemy pod gore\n\t\t{\n\t\t\tif ((gridMap.data[0].data[col + row * 64]>point_start_z) && (gridMap.data[0].data[col + row * 64]<point_end_z))\n\t    \t\t{\n\t\t\t\treturn gridMap.data[0].data[col + row * 64]; \n\t \t\t} \n\t\t \telse\n\t\t\t{\n\t\t\t\treturn gridMap.data[0].data[col + row * 64]*gridMap.data[0].data[col + row * 64]; \n\t\t\t}\n\n\t\t}\t\n\t}\n\telse // Brak mapy\n\t{\n\t\treturn 1;\n\t}\n    }\n};\n\nclass ClearanceObjective : public ob::StateCostIntegralObjective\n{\npublic:\n    ClearanceObjective(const ob::SpaceInformationPtr& si) :\n        ob::StateCostIntegralObjective(si, true)\n    {\n    }\n    ob::Cost stateCost(const ob::State* s) const\n    {\n        return ob::Cost(si_->getStateValidityChecker()->clearance(s));\n    }\n};\n\n//Optimization - getPathLengthObjective\n ob::OptimizationObjectivePtr getPathLengthObjective(const ob::SpaceInformationPtr& si)\n {\n     return ob::OptimizationObjectivePtr(new ob::PathLengthOptimizationObjective(si));\n }\n\n//Optimization - getClearanceObjective\nob::OptimizationObjectivePtr getClearanceObjective(const ob::SpaceInformationPtr& si)\n{\n    return std::make_shared<ClearanceObjective>(si);\n\n}\n\n//Optimization - getBalancedObjective\nob::OptimizationObjectivePtr getBalancedObjective(const ob::SpaceInformationPtr& si)\n{\n    ob::OptimizationObjectivePtr lengthObj(new ob::PathLengthOptimizationObjective(si));\n    ob::OptimizationObjectivePtr clearObj(new ClearanceObjective(si));\n    ob::MultiOptimizationObjective* opt = new ob::MultiOptimizationObjective(si);\n    opt->addObjective(lengthObj, 1.0);\n    opt->addObjective(clearObj, 10.0);\n    return ob::OptimizationObjectivePtr(opt);\n}\n\n\n\nPlanner2D::Planner2D(ros::NodeHandle& _nodeHandle)\n    : nodeHandle(_nodeHandle)\n{\n    ROS_INFO(\"Planner node started.\");\n    configure(point_start_x, point_start_y, point_end_x, point_end_y);\n}\n\nPlanner2D::~Planner2D()\n{\n}\n\n\n\nvoid Planner2D::returnPoints(std_msgs::UInt8 pStartX, std_msgs::UInt8 pStartY,\n                             std_msgs::UInt8 pEndX, std_msgs::UInt8 pEndY){\n    point_start_x = double(pStartX.data) * (-0.1);\n    point_start_y = double(pStartY.data) * (-0.1);\n    point_end_x = double(pEndX.data) * (-0.1);\n    point_end_y = double(pEndY.data) * (-0.1);\n}\n\n/// extract path\nnav_msgs::Path Planner2D::extractPath(ob::ProblemDefinition* pdef){\n   nav_msgs::Path plannedPath;\n    plannedPath.header.frame_id = \"/map\";\n    // get the obtained path\n    ob::PathPtr path = pdef->getSolutionPath();\n    // print the path to screen\n    path->print(std::cout);\n    // convert to geometric path\n    const auto *path_ = path.get()->as<og::PathGeometric>();\n    // iterate over each position\n    for(unsigned int i=0; i<path_->getStateCount(); ++i){\n        // get state\n        const ob::State* state = path_->getState(i);\n\n\tconst ob::RealVectorStateSpace::StateType* state2D = state->as<ob::RealVectorStateSpace::StateType>();\n\n        // Extract the robot's (x,y) position from its state\n        double x = state2D->values[0];\n        double y = state2D->values[1];\n\t// potrzebne do obliczania wspl. Z sciezki\n\tint col = (x)/(-0.1);\n     \tint row = (y)/(-0.1);\n\n        // fill in the ROS PoseStamped structure...\n        geometry_msgs::PoseStamped poseMsg;\n        poseMsg.pose.position.x = x;\n        poseMsg.pose.position.y = y;\n\tif (gridMap.info.length_x)\n    \t{\n\t\tposeMsg.pose.position.z = gridMap.data[0].data[col + row * 64] +0.1; \n \t}\n\telse\n\t{\n\t\tposeMsg.pose.position.z = 0;\n\t} \n        poseMsg.pose.orientation.w = 1.0;\n        poseMsg.pose.orientation.x = 0.0;\n        poseMsg.pose.orientation.y = 0.0;\n        poseMsg.pose.orientation.z = 0.0;\n        poseMsg.header.frame_id = \"/map\";\n        poseMsg.header.stamp = ros::Time::now();\n        // ... and add the pose to the path\n        plannedPath.poses.push_back(poseMsg);\n    }\n    return plannedPath;\n}\n\n\nnav_msgs::Path Planner2D::planPath(const grid_map_msgs::GridMap& globalMap){\n\n    \tgridMap = globalMap;\n\tconfigure(point_start_x, point_start_y, point_end_x, point_end_y);\n\n\t//std::cout << \"point_start_x\" << point_start_x << std::endl;\n\t//std::cout << \"point_start_y\" << point_start_y << std::endl;\n\n   \t // Construct the robot state space in which we're planning. We're\n\t// planning in [0,1]x[0,1], a subset of R^2.\n\tob::StateSpacePtr space(new ob::RealVectorStateSpace(2));\n\n\t// Set the bounds of space to be in [0,1].\n\tspace->as<ob::RealVectorStateSpace>()->setBounds(-6.4, 0.0);\n\n\t// Construct a space information instance for this state space\n\tob::SpaceInformationPtr si(new ob::SpaceInformation(space));\n\n\t // Set the object used to check which states in the space are valid\n\tsi->setStateValidityChecker(ob::StateValidityCheckerPtr(new ValidityChecker(si)));\n\tsi->setup();\n\n\t// Set our robot's starting state to be the bottom-left corner of\n\t// the environment, or (0,0).\n\tob::ScopedState<> start(space);\n\tstart->as<ob::RealVectorStateSpace::StateType>()->values[0] = point_start_x;\n\tstart->as<ob::RealVectorStateSpace::StateType>()->values[1] = point_start_y;\n\n\t// Set our robot's goal state to be the top-right corner of the\n\t// environment, or (5,5).\n\tob::ScopedState<> goal(space);\n\tgoal->as<ob::RealVectorStateSpace::StateType>()->values[0] = point_end_x;\n\tgoal->as<ob::RealVectorStateSpace::StateType>()->values[1] = point_end_y;\n\n\t// Create a problem instance\n\tob::ProblemDefinitionPtr pdef(new ob::ProblemDefinition(si));\n\n\t// Set the start and goal states\n\tpdef->setStartAndGoalStates(start, goal);\n\n\t// Create the optimization objective\n\tpdef->setOptimizationObjective(getBalancedObjective(si));\n\n\t// Construct our optimizing planner using the RRTstar algorithm.\n\tauto optimizingPlanner(std::make_shared<og::RRTstar>(si));\n\toptimizingPlanner->setRange(maxStepLength);// max step length\n\n\t// Set the problem instance for our planner to solve\n\toptimizingPlanner->setProblemDefinition(pdef);\n\toptimizingPlanner->setup();\n\n\t// attempt to solve the planning problem within one second of\n\t// planning time\n\tob::PlannerStatus solved = optimizingPlanner->ob::Planner::solve(1.0);\n\n \tnav_msgs::Path plannedPath;\n\t if (solved)\n \t    {\n  \t    \tplannedPath=extractPath(pdef.get());\n \t    }\n  \t   else\n\t    {\n  \t       std::cout << \"No solution found.\" << std::endl;\n\t    }\n\n\t return plannedPath;\n}\n\n/// configure planner\nvoid Planner2D::configure(double point_start_x, double point_start_y, double point_end_x, double point_end_y)\n{\n        maxStepLength = 0.05;// max step length\n}\n\n} /* namespace */\n", "meta": {"hexsha": "d3629f0743062da37b4cad09bdf140fd1235b20a", "size": 8600, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mapr_project.cpp", "max_stars_repo_name": "Kamilkim/MAPR_project", "max_stars_repo_head_hexsha": "26d55af2296d4f05249afe537dbc5a798964adc6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-07T09:16:32.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-07T09:16:32.000Z", "max_issues_repo_path": "src/mapr_project.cpp", "max_issues_repo_name": "TheGrycek/mapr_project", "max_issues_repo_head_hexsha": "f6de62d3dfb3d0ccb926a23400c422667cec9369", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mapr_project.cpp", "max_forks_repo_name": "TheGrycek/mapr_project", "max_forks_repo_head_hexsha": "f6de62d3dfb3d0ccb926a23400c422667cec9369", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-05-06T16:21:28.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-06T16:21:28.000Z", "avg_line_length": 30.0699300699, "max_line_length": 114, "alphanum_fraction": 0.6788372093, "num_tokens": 2415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.4592310846753406}}
{"text": "#include <boost/test/unit_test.hpp>\n#include \"functions/unary_minus.hh\"\n#include \"functions/full_function_defs.hh\"\n#include \"functions/variables.hh\"\n\nBOOST_AUTO_TEST_CASE(unary_minus_test) {\n  using namespace manifolds;\n  UnaryMinus<decltype(x)> a(x);\n\n  BOOST_CHECK_EQUAL(a(1, 2, 3, 4), -1);\n  BOOST_CHECK_EQUAL(a(1, 2, 4, 8, 16), -1);\n}\n", "meta": {"hexsha": "85e3f1fec6a1e63126803b2405bfd5687486d75d", "size": 339, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "functions/tests/test_unaryminus.cpp", "max_stars_repo_name": "GuylainGreer/manifolds", "max_stars_repo_head_hexsha": "96f996f67fc523c726f2edbc9705125c212bedae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "functions/tests/test_unaryminus.cpp", "max_issues_repo_name": "GuylainGreer/manifolds", "max_issues_repo_head_hexsha": "96f996f67fc523c726f2edbc9705125c212bedae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "functions/tests/test_unaryminus.cpp", "max_forks_repo_name": "GuylainGreer/manifolds", "max_forks_repo_head_hexsha": "96f996f67fc523c726f2edbc9705125c212bedae", "max_forks_repo_licenses": ["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.0769230769, "max_line_length": 43, "alphanum_fraction": 0.7315634218, "num_tokens": 101, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7248702761768249, "lm_q2_score": 0.6334102775181399, "lm_q1q2_score": 0.4591402827978134}}
{"text": "// Copyright (c) 2019 fortiss GmbH, Julian Bernhard, Klemens Esterle, Patrick Hart, Tobias Kessler\n//\n// This work is licensed under the terms of the MIT license.\n// For a copy, see <https://opensource.org/licenses/MIT>.\n\n\n#include <Eigen/Core>\n#include \"gtest/gtest.h\"\n\n#include \"modules/geometry/polygon.hpp\"\n#include \"modules/geometry/line.hpp\"\n#include \"modules/geometry/commons.hpp\"\n#include \"modules/models/dynamic/single_track.hpp\"\n#include \"modules/models/dynamic/triple_integrator.hpp\"\n#include \"modules/models/dynamic/integration.hpp\"\n#include \"modules/commons/params/setter_params.hpp\"\n#include \"modules/commons/params/default_params.hpp\"\n\n\nTEST(single_track_model, dynamic_test) {\n  using namespace std;\n  using namespace modules::geometry;\n  using namespace modules::models::dynamic;\n  using namespace modules::commons;\n\n  State x(static_cast<int>(StateDefinition::MIN_STATE_SIZE));\n  x << 0, 0, 0, 0, 5;\n\n  Input u(2);\n  u << 0, 0;\n\n  DynamicModel *m;\n  auto params = std::make_shared<DefaultParams>();\n  SingleTrackModel single_track_model(params);\n  m = &single_track_model;\n\n  float dt = 0.1;\n  for (int i = 0; i < 10; i++) {\n    x = euler_int(*m, x, u, dt);\n    cout << x << endl;\n  }\n}\n\nTEST(triple_integrator_model, dynamic_test) {\n  using namespace std;\n  using namespace modules::geometry;\n  using namespace modules::models::dynamic;\n  using namespace modules::commons;\n\n  State x(15);\n  x << 0, 0, 0, 0, 0, 0,  // time, x, y, theta, v, min_space\n       0, 1, 0,  // x, vx, ax\n       0, 1, 0,  // y, vy, ay\n       0, 1, 0;  // z, vz, az\n\n  Input u0(3);\n  u0 << 0, 0, 0.;\n\n  DynamicModel *m;\n  auto params = std::make_shared<DefaultParams>();\n  TripleIntegratorModel triple_int_model(params);\n  m = &triple_int_model;\n\n  float dt = 0.1;\n  for (int i = 0; i < 10; i++) {\n    x = euler_int(*m, x, u0, dt);\n    cout << x << endl << endl;\n  }\n  // TODO(@hart): assert state\n  u0 << 1., 1., 1.;\n  for (int i = 0; i < 10; i++) {\n    x = euler_int(*m, x, u0, dt);\n    cout << x << endl << endl;\n  }\n  // TODO(@hart): assert state\n\n}\n\n\nint main(int argc, char **argv) {\n  ::testing::InitGoogleTest(&argc, argv);\n  return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "a04d5161bee29984aa7aeae482350d17fa545152", "size": 2153, "ext": "cc", "lang": "C++", "max_stars_repo_path": "modules/models/tests/dynamic_test.cc", "max_stars_repo_name": "tom-doerr/bark", "max_stars_repo_head_hexsha": "cd524aeec070b3b92562d127c8f25501a616cd34", "max_stars_repo_licenses": ["MIT"], "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/models/tests/dynamic_test.cc", "max_issues_repo_name": "tom-doerr/bark", "max_issues_repo_head_hexsha": "cd524aeec070b3b92562d127c8f25501a616cd34", "max_issues_repo_licenses": ["MIT"], "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/models/tests/dynamic_test.cc", "max_forks_repo_name": "tom-doerr/bark", "max_forks_repo_head_hexsha": "cd524aeec070b3b92562d127c8f25501a616cd34", "max_forks_repo_licenses": ["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.630952381, "max_line_length": 98, "alphanum_fraction": 0.6511843939, "num_tokens": 667, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.6334102775181399, "lm_q1q2_score": 0.4591402827978133}}
{"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 tree_augmentation_example.cpp\n * @brief\n * @author Attila Bernath, Piotr Godlewski\n * @version 1.0\n * @date 2013-10-17\n */\n\n//! [Tree Augmentation Example]\n#include \"paal/iterative_rounding/treeaug/tree_augmentation.hpp\"\n\n#include <boost/graph/adjacency_list.hpp>\n\n#include <iostream>\n#include <vector>\n\nint main() {\n    using EdgeProp = boost::property<boost::edge_weight_t, double,\n                boost::property<boost::edge_color_t, bool>>;\n    using Graph = boost::adjacency_list<boost::vecS, boost::vecS,\n                boost::undirectedS, boost::no_property, EdgeProp>;\n    using Edge = boost::graph_traits<Graph>::edge_descriptor;\n\n    // sample problem\n    std::vector<std::pair<int, int>> edges {{0,1},{1,2},{1,3},{3,4},{3,5},\n            {0,3},{0,3},{2,4},{2,5},{4,5}};\n    std::vector<EdgeProp> edge_properties {EdgeProp(0, true),\n        EdgeProp(0, true), EdgeProp(0, true), EdgeProp(0, true),\n        EdgeProp(0, true), EdgeProp(1, false), EdgeProp(1, false),\n        EdgeProp(1, false), EdgeProp(1, false), EdgeProp(1,false)};\n\n    Graph g(edges.begin(), edges.end(), edge_properties.begin(), 6);\n\n    std::vector<Edge> solution;\n\n    // optional input validity checking\n    auto tree_aug = paal::ir::make_tree_aug(g, std::back_inserter(solution));\n    auto error = tree_aug.check_input_validity();\n    if (error) {\n        std::cerr << \"The input is not valid!\" << std::endl;\n        std::cerr << *error << std::endl;\n        return -1;\n    }\n\n    // solve it\n    auto result = paal::ir::tree_augmentation_iterative_rounding(\n        g, std::back_inserter(solution));\n\n    // print result\n    if (result.first == paal::lp::OPTIMAL) {\n        std::cout << \"The solution contains the following nontree edges:\"\n            << std::endl;\n        for (auto e : solution) {\n            std::cout << \"Edge \" << e << std::endl;\n        }\n        std::cout << \"Cost of the solution: \" << *(result.second) << std::endl;\n    } else {\n        std::cout << \"The instance is infeasible\" << std::endl;\n    }\n    paal::lp::glp::free_env();\n    return 0;\n}\n    //! [Tree Augmentation Example]\n", "meta": {"hexsha": "29172761416bcb724e87dcfc500c58d7d449be14", "size": 2431, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/iterative_rounding/tree_augmentation_example.cpp", "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": "examples/iterative_rounding/tree_augmentation_example.cpp", "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": "examples/iterative_rounding/tree_augmentation_example.cpp", "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": 34.2394366197, "max_line_length": 79, "alphanum_fraction": 0.5791855204, "num_tokens": 645, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.6334102705979902, "lm_q1q2_score": 0.45914027778160243}}
{"text": "/*\n * Copyright (C) 2018-2020 HERE Europe B.V.\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 * License-Filename: LICENSE\n */\n\n//\n// Created by Mitra, Aniket on 2019-04-03.\n//\n\n#include \"movetk/utils/GeometryBackendTraits.h\"\n#include \"movetk/utils/Iterators.h\"\n#include <boost/graph/breadth_first_search.hpp>\n#include <boost/graph/named_function_params.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/visitors.hpp>\n#include <boost/graph/properties.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/property_map/property_map.hpp>\n\n// treat a trajectory as a directed graph and\n// use the BFS algorithm to find the shortest path\nint main(int argc, char **argv)\n{\n#if CGAL_BACKEND_ENABLED\n    std::cerr << \"Using CGAL Backend for Geometry\\n\";\n#else\n    std::cerr << \"Using Boost Backend for Geometry\\n\";\n#endif\n\n    std::cout.setf(std::ios::fixed);\n\n    // PolyLine is a data structure that to store a collection of points\n    typedef std::vector<GeometryKernel::MovetkGeometryKernel::MovetkPoint> PolyLine;\n\n    // Define a graph using boost::adjacency_list\n    typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS,\n                                  boost::property<boost::vertex_index_t, int>, boost::property<boost::edge_index_t, int>>\n        Graph;\n\n    // Vertex iterator type\n    typedef typename boost::graph_traits<Graph>::vertex_iterator vertex_iterator;\n    // Edge iterator type\n    typedef typename boost::graph_traits<Graph>::edge_iterator edge_iterator;\n\n    typedef boost::property_map<Graph, boost::vertex_index_t>::type VertexId_PMap;\n\n    // functor to create a point\n    movetk_core::MakePoint<GeometryKernel::MovetkGeometryKernel> make_point;\n\n    // create polyline, each point in the polyline is vertex\n    PolyLine polyline({make_point({-6.19, -3.46}), make_point({-4.99, 1.16}),\n                       make_point({-2.79, -2.22}), make_point({-1.87, 0.58})});\n\n    // print each vertex\n    std::cout << \"Polyline: \";\n    std::cout << \"{\";\n    for (auto &vertex : polyline)\n    {\n        std::cout << vertex;\n        std::cout << \";\";\n    }\n    std::cout << \"}\\n\";\n\n    // edges to connect vertex pairs\n    std::vector<std::pair<std::size_t, std::size_t>> edges({\n        std::make_pair(0, 1),\n        std::make_pair(1, 2),\n        std::make_pair(0, 2),\n        std::make_pair(2, 3),\n    });\n\n    // print the edges\n    std::cout << \"Edges: \";\n    std::cout << \"{\";\n    for (auto &i : edges)\n    {\n        std::cout << i.first << \",\" << i.second << \";\";\n    }\n    std::cout << \"}\\n\";\n\n    /** Pass iterator over edges and the number of vertices\n     *  to create boost graph\n    */\n    Graph g{edges.begin(), edges.end(), polyline.size()};\n\n    std::cout << \"Number of vertices: \" << boost::num_vertices(g) << '\\n';\n    std::cout << \"Number of edges: \" << boost::num_edges(g) << '\\n';\n\n    // container stores computed distances\n    std::vector<std::size_t> distances(polyline.size());\n    //\n    std::vector<std::size_t> predecessors(polyline.size());\n\n    predecessors[0] = 0;\n\n    VertexId_PMap vertex_index = boost::get(boost::vertex_index, g);\n\n    // iterator property map for recording distances\n    boost::iterator_property_map<std::vector<std::size_t>::iterator, VertexId_PMap,\n                                 std::size_t, std::size_t &>\n        distances_pa(distances.begin(), vertex_index);\n\n    /* iterator property map for recording the previous point as the\n    * bfs algorithm proceeds to the next point\n    */\n    boost::iterator_property_map<std::vector<std::size_t>::iterator, VertexId_PMap,\n                                 std::size_t, std::size_t &>\n        predecessors_pa(predecessors.begin(), vertex_index);\n\n    /** the helper function to create a visitor that record distances\n    * distance is the number of lines that have to be crossed to get from one \n    * point to another starting from the point that is passed as a second \n    * argument to  boost::breadth_first_search\n    */\n    auto distance_recorder = boost::record_distances(distances_pa, boost::on_tree_edge{});\n    /* returns a visitor to store the predecessor of every point\n    *  whenever boost::breadth_first_search() visits a new point, the previous\n    *  point is stored in the property map passed to boost::record_predecessors\n    */\n    auto predecessor_recorder = boost::record_predecessors(predecessors_pa, boost::on_tree_edge{});\n    /* an adaptor that binds the two visitors distance_recorder & predecessor_recorder\n    * to the algorithm \n    */\n    auto bfs_visitor = boost::make_bfs_visitor(std::make_pair(distance_recorder, predecessor_recorder));\n\n    // the bfs algorithm on graph g\n    // bfs_visitor stores the result\n    // the algorithm starts at the first point as specified in the second argument\n    boost::breadth_first_search(g, 0, boost::visitor(bfs_visitor));\n\n    /* iterate over the graph and print all vertices, the distance\n    * between two vertices, and the predecessor for each vertex\n    */\n    vertex_iterator vi, vi_end;\n    for (std::tie(vi, vi_end) = boost::vertices(g); vi != vi_end; ++vi)\n    {\n        std::cout << \"vertex index: \" << *vi << \", distance: \" << boost::get(distances_pa, *vi) << std::endl;\n    }\n\n    for (std::tie(vi, vi_end) = boost::vertices(g); vi != vi_end; ++vi)\n    {\n        std::cout << \"vertex index: \" << *vi << \", predecessor: \" << boost::get(predecessors_pa, *vi) << std::endl;\n    }\n\n    /* get the index of the vertices returned by the\n    * shortest path\n    */\n    std::tie(vi, vi_end) = boost::vertices(g);\n    auto idx = boost::get(predecessors_pa, *(vi_end - 1));\n    std::vector<std::size_t> indexes;\n    indexes.push_back(*(vi_end - 1));\n    while (idx != boost::get(predecessors_pa, *vi))\n    {\n        indexes.push_back(idx);\n        idx = predecessors_pa[idx];\n    }\n    indexes.push_back(idx);\n\n    /* the order of the vertices returned by the bfs algorithm\n    * starts with the last vertex, so reverse the indexes \n    * so that it can be used to access points from the polyline\n    */\n    std::reverse(std::begin(indexes), std::end(indexes));\n\n    std::cout << \"Shortest Path Polyline: \";\n    std::cout << \"{\";\n    for (auto &idx : indexes)\n    {\n        std::cout << polyline[idx] << \";\";\n    }\n    std::cout << \"}\\n\";\n}\n", "meta": {"hexsha": "e45628117a6b5fae39553827de7036d9f39902f3", "size": 6828, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/directed_graph.cpp", "max_stars_repo_name": "aniketmitra001/movetk", "max_stars_repo_head_hexsha": "cdf0c98121da6df4cadbd715fba02b05be724218", "max_stars_repo_licenses": ["Apache-2.0"], "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/directed_graph.cpp", "max_issues_repo_name": "aniketmitra001/movetk", "max_issues_repo_head_hexsha": "cdf0c98121da6df4cadbd715fba02b05be724218", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-04-07T13:11:05.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-07T13:11:05.000Z", "max_forks_repo_path": "examples/directed_graph.cpp", "max_forks_repo_name": "aniketmitra001/movetk", "max_forks_repo_head_hexsha": "cdf0c98121da6df4cadbd715fba02b05be724218", "max_forks_repo_licenses": ["Apache-2.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.513368984, "max_line_length": 121, "alphanum_fraction": 0.6540714704, "num_tokens": 1717, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768249, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.45914027276539143}}
{"text": "/*\n * mean_and_variance.cc\n *\n *  Copyright (C) 2013 Diamond Light Source\n *\n *  Author: James Parkhurst\n *\n *  This code is distributed under the BSD license, a copy of which is\n *  included in the root directory of this package.\n */\n#include <boost/python.hpp>\n#include <boost/python/def.hpp>\n#include <dials/algorithms/image/filter/mean_and_variance.h>\n\nnamespace dials { namespace algorithms { namespace boost_python {\n\n  using namespace boost::python;\n\n  template <typename FloatType>\n  void mean_and_variance_filter_wrapper(const char *name) {\n    typedef MeanAndVarianceFilter<FloatType> MeanAndVarianceFilterType;\n\n    class_<MeanAndVarianceFilterType>(name, no_init)\n      .def(init<const af::const_ref<FloatType, af::c_grid<2> > &, int2>(\n        (arg(\"image\"), arg(\"size\"))))\n      .def(\"mean\", &MeanAndVarianceFilterType::mean)\n      .def(\"variance\", &MeanAndVarianceFilterType::variance)\n      .def(\"sample_variance\", &MeanAndVarianceFilterType::sample_variance);\n  }\n\n  template <typename FloatType>\n  void mean_and_variance_filter_masked_wrapper(const char *name) {\n    typedef MeanAndVarianceFilterMasked<FloatType> MeanAndVarianceFilterType;\n\n    class_<MeanAndVarianceFilterType>(name, no_init)\n      .def(init<const af::const_ref<FloatType, af::c_grid<2> > &,\n                const af::const_ref<int, af::c_grid<2> > &,\n                int2,\n                int>((arg(\"image\"), arg(\"mask\"), arg(\"size\"), arg(\"min_size\"))))\n      .def(\"mean\", &MeanAndVarianceFilterType::mean)\n      .def(\"variance\", &MeanAndVarianceFilterType::variance)\n      .def(\"sample_variance\", &MeanAndVarianceFilterType::sample_variance)\n      .def(\"mask\", &MeanAndVarianceFilterType::mask)\n      .def(\"count\", &MeanAndVarianceFilterType::count);\n  }\n\n  template <typename FloatType>\n  MeanAndVarianceFilter<FloatType> make_mean_and_variance_filter(\n    const af::const_ref<FloatType, af::c_grid<2> > &image,\n    int2 size) {\n    return MeanAndVarianceFilter<FloatType>(image, size);\n  }\n\n  template <typename FloatType>\n  MeanAndVarianceFilterMasked<FloatType> make_mean_and_variance_filter_masked(\n    const af::const_ref<FloatType, af::c_grid<2> > &image,\n    const af::const_ref<int, af::c_grid<2> > &mask,\n    int2 size,\n    int min_size) {\n    return MeanAndVarianceFilterMasked<FloatType>(image, mask, size, min_size);\n  }\n\n  template <typename FloatType>\n  void mean_and_variance_filter_suite() {\n    def(\"mean_filter\", &mean_filter<FloatType>, (arg(\"image\"), arg(\"size\")));\n\n    def(\"mean_filter\",\n        &mean_filter_masked<FloatType>,\n        (arg(\"image\"),\n         arg(\"mask\"),\n         arg(\"size\"),\n         arg(\"min_count\"),\n         arg(\"ignore_masked\") = true));\n\n    def(\"mean_and_variance_filter\",\n        &make_mean_and_variance_filter<FloatType>,\n        (arg(\"image\"), arg(\"kernel\")));\n\n    def(\"mean_and_variance_filter\",\n        &make_mean_and_variance_filter_masked<FloatType>,\n        (arg(\"image\"), arg(\"mask\"), arg(\"kernel\"), arg(\"min_count\")));\n  }\n\n  void export_mean_and_variance() {\n    mean_and_variance_filter_wrapper<float>(\"MeanAndVarianceFilterFloat\");\n    mean_and_variance_filter_wrapper<double>(\"MeanAndVarianceFilterDouble\");\n    mean_and_variance_filter_masked_wrapper<float>(\"MeanAndVarianceFilterMaskedFloat\");\n    mean_and_variance_filter_masked_wrapper<double>(\n      \"MeanAndVarianceFilterMaskedDouble\");\n\n    mean_and_variance_filter_suite<float>();\n    mean_and_variance_filter_suite<double>();\n  }\n\n}}}  // namespace dials::algorithms::boost_python\n", "meta": {"hexsha": "dbfb1cf981c5fe0213d809652ee88567b9363a43", "size": 3493, "ext": "cc", "lang": "C++", "max_stars_repo_path": "algorithms/image/filter/boost_python/mean_and_variance.cc", "max_stars_repo_name": "TiankunZhou/dials", "max_stars_repo_head_hexsha": "bd5c95b73c442cceb1c61b1690fd4562acf4e337", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 58.0, "max_stars_repo_stars_event_min_datetime": "2015-10-15T09:28:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T20:09:38.000Z", "max_issues_repo_path": "algorithms/image/filter/boost_python/mean_and_variance.cc", "max_issues_repo_name": "TiankunZhou/dials", "max_issues_repo_head_hexsha": "bd5c95b73c442cceb1c61b1690fd4562acf4e337", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1741.0, "max_issues_repo_issues_event_min_datetime": "2015-11-24T08:17:02.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:46:42.000Z", "max_forks_repo_path": "algorithms/image/filter/boost_python/mean_and_variance.cc", "max_forks_repo_name": "TiankunZhou/dials", "max_forks_repo_head_hexsha": "bd5c95b73c442cceb1c61b1690fd4562acf4e337", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 45.0, "max_forks_repo_forks_event_min_datetime": "2015-10-14T13:44:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T14:45:56.000Z", "avg_line_length": 36.3854166667, "max_line_length": 87, "alphanum_fraction": 0.7048382479, "num_tokens": 877, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.4591402727653914}}
{"text": "/*\n * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 \"votca/xtp/basisset.h\"\n#define BOOST_TEST_MAIN\n\n#define BOOST_TEST_MODULE aotransform_test\n\n// Third party includes\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/unit_test.hpp>\n\n// Local VOTCA includes\n#include \"votca/xtp/aotransform.h\"\n#include \"votca/xtp/orbitals.h\"\n#include <votca/tools/eigenio_matrixmarket.h>\n\nusing namespace votca::xtp;\nusing namespace votca;\nusing namespace std;\n\nBOOST_AUTO_TEST_SUITE(aotransform_test)\n\nBOOST_AUTO_TEST_CASE(transform_test) {\n  QMAtom a(0, \"C\", Eigen::Vector3d::Zero());\n  QMMolecule mol(\"zero\", 0);\n  mol.push_back(a);\n\n  BasisSet bs;\n  bs.Load(std::string(XTP_TEST_DATA_FOLDER) + \"/aotransform/all.xml\");\n  AOBasis basis;\n  basis.Fill(bs, mol);\n\n  std::array<Eigen::MatrixXd, 7> ref;\n\n  for (unsigned i = 0; i < ref.size(); i++) {\n    ref[i] = votca::tools::EigenIO_MatrixMarket::ReadMatrix(\n        std::string(XTP_TEST_DATA_FOLDER) + \"/aotransform/ref_\" +\n        std::to_string(i) + \".mm\");\n  }\n\n  Index ref_index = 0;\n  for (const AOShell& shell : basis) {\n    for (const AOGaussianPrimitive& gauss : shell) {\n      Eigen::MatrixXd transform = AOTransform::getTrafo(gauss);\n      bool check_transform = ref[ref_index].isApprox(transform, 1e-5);\n      BOOST_CHECK_EQUAL(check_transform, 1);\n      if (!check_transform) {\n        std::cout << \"ref \" << xtp::EnumToString(shell.getL()) << std::endl;\n        std::cout << ref[ref_index] << std::endl;\n        std::cout << \"result\" << std::endl;\n        std::cout << transform << std::endl;\n      }\n      ref_index++;\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE(xintegrate) {\n\n  BOOST_REQUIRE_THROW(AOTransform::XIntegrate(0, 0.1), std::runtime_error);\n\n  BOOST_REQUIRE_THROW(AOTransform::XIntegrate(1, -0.1);, std::runtime_error);\n\n  Eigen::VectorXd res1 = AOTransform::XIntegrate(1, 0.1);\n  Eigen::VectorXd res1_ref = Eigen::VectorXd::Zero(1);\n  res1_ref << 0.967643;\n  bool check_res1 = res1.isApprox(res1_ref, 1e-5);\n  BOOST_CHECK_EQUAL(check_res1, 1);\n  if (!check_res1) {\n    std::cout << \"ref\" << std::endl;\n    std::cout << res1_ref << std::endl;\n    std::cout << \"result\" << std::endl;\n    std::cout << res1 << std::endl;\n  }\n  Eigen::VectorXd res2 = AOTransform::XIntegrate(5, 0.1);\n  Eigen::VectorXd res2_ref = Eigen::VectorXd::Zero(5);\n  res2_ref << 0.967643, 0.314029, 0.186255, 0.132188, 0.102394;\n\n  bool check_res2 = res2.isApprox(res2_ref, 1e-5);\n  BOOST_CHECK_EQUAL(check_res2, 1);\n  if (!check_res1) {\n    std::cout << \"ref\" << std::endl;\n    std::cout << res2_ref << std::endl;\n    std::cout << \"result\" << std::endl;\n    std::cout << res2 << std::endl;\n  }\n\n  Eigen::VectorXd res3 = AOTransform::XIntegrate(1, 1e-12);\n  Eigen::VectorXd res3_ref = Eigen::VectorXd::Zero(1);\n  res3_ref[0] = 1.0;\n  bool check_res3 = res3.isApprox(res3_ref, 1e-5);\n  BOOST_CHECK_EQUAL(check_res3, 1);\n  if (!check_res3) {\n    std::cout << \"ref\" << std::endl;\n    std::cout << res3_ref << std::endl;\n    std::cout << \"result\" << std::endl;\n    std::cout << res3 << std::endl;\n  }\n\n  Eigen::VectorXd res4 = AOTransform::XIntegrate(5, 1e-12);\n  Eigen::VectorXd res4_ref = Eigen::VectorXd::Zero(5);\n  res4_ref << 1, 0.333333, 0.2, 0.142857, 0.111111;\n\n  bool check_res4 = res4.isApprox(res4_ref, 1e-5);\n  BOOST_CHECK_EQUAL(check_res4, 1);\n  if (!check_res4) {\n    std::cout << \"ref\" << std::endl;\n    std::cout << res4_ref << std::endl;\n    std::cout << \"result\" << std::endl;\n    std::cout << res4 << std::endl;\n  }\n\n  Eigen::VectorXd res5 = AOTransform::XIntegrate(1, 15);\n  Eigen::VectorXd res5_ref = Eigen::VectorXd::Zero(1);\n  res5_ref << 0.228823;\n  bool check_res5 = res5.isApprox(res5_ref, 1e-5);\n  BOOST_CHECK_EQUAL(check_res5, 1);\n  if (!check_res5) {\n    std::cout << \"ref\" << std::endl;\n    std::cout << res5_ref << std::endl;\n    std::cout << \"result\" << std::endl;\n    std::cout << res5 << std::endl;\n  }\n\n  Eigen::VectorXd res6 = AOTransform::XIntegrate(5, 15);\n  Eigen::VectorXd res6_ref = Eigen::VectorXd::Zero(5);\n  res6_ref << 0.228823, 0.00762742, 0.000762731, 0.000127112, 2.96492e-05;\n  bool check_res6 = res6.isApprox(res6_ref, 1e-5);\n  BOOST_CHECK_EQUAL(check_res6, 1);\n  if (!check_res6) {\n    std::cout << \"ref\" << std::endl;\n    std::cout << res6_ref << std::endl;\n    std::cout << \"result\" << std::endl;\n    std::cout << res6 << std::endl;\n  }\n}\n\nBOOST_AUTO_TEST_CASE(blocksize) {\n  BOOST_CHECK_EQUAL(AOTransform::getBlockSize(0), 1);\n\n  BOOST_CHECK_EQUAL(AOTransform::getBlockSize(0), 1);\n  BOOST_CHECK_EQUAL(AOTransform::getBlockSize(1), 4);\n  BOOST_CHECK_EQUAL(AOTransform::getBlockSize(2), 10);\n  BOOST_CHECK_EQUAL(AOTransform::getBlockSize(3), 20);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "06b8faaecf70b83623f56c0e66bf9abb8e8a772f", "size": 5228, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/tests/test_aotransform.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/tests/test_aotransform.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/tests/test_aotransform.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.4720496894, "max_line_length": 77, "alphanum_fraction": 0.665455241, "num_tokens": 1648, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.4591402727653914}}
{"text": "#include <boost/multiprecision/cpp_int.hpp>\r\nusing namespace boost::multiprecision;\r\nusing namespace std;\r\nusing namespace std;\r\n\r\nvoid MiniMax(long long arr[])\r\n{\r\nint i;\r\nint j=0;\r\nint128_t  MaxSum= INT_MIN;\r\nint128_t MinSum=INT_MAX;\r\nfor (i=0; i<5 ;i++)\r\n{\r\n    int128_t sum=0;\r\n    for(j=0; j<5; j++)\r\n    {\r\n        if(j != i)\r\n        {\r\n            sum +=arr[j];\r\n        }\r\n    }\r\n    MaxSum= max(sum, MaxSum);\r\n    MinSum=min(MinSum, sum);\r\n}\r\n\r\ncout<<MinSum<<\" \"<<MaxSum<<endl;\r\n}\r\n\r\n\r\nint main()\r\n{\r\n    int128_t arr[5];\r\n    for(int i=0;i<5;i++)\r\n    {\r\n      cin>>arr[i];\r\n    }\r\n    MiniMax(arr);\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "b45ea72407952edefd0d17807bbc40bf1f1a7494", "size": 630, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Program/Algorithms/Sieve_PrimeNo.cpp", "max_stars_repo_name": "anurag-singh2001/Algo_Engineering", "max_stars_repo_head_hexsha": "58345da47378213c3b383ac3cdfdd5e829faee63", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-12-21T18:33:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T19:57:01.000Z", "max_issues_repo_path": "Program/Algorithms/Sieve_PrimeNo.cpp", "max_issues_repo_name": "anurag-singh2001/Algo_Engineering", "max_issues_repo_head_hexsha": "58345da47378213c3b383ac3cdfdd5e829faee63", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2021-08-13T08:52:43.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-08T06:28:21.000Z", "max_forks_repo_path": "Program/Algorithms/Sieve_PrimeNo.cpp", "max_forks_repo_name": "anurag-singh2001/Algo_Engineering", "max_forks_repo_head_hexsha": "58345da47378213c3b383ac3cdfdd5e829faee63", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2021-09-30T18:23:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-08T05:19:18.000Z", "avg_line_length": 15.75, "max_line_length": 44, "alphanum_fraction": 0.5158730159, "num_tokens": 190, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.7248702702332476, "lm_q1q2_score": 0.45914026900066857}}
{"text": "// This file is part of PoseEstimation.\n// Copyright (c) 2021, Eijiro Shibusawa <phd_kimberlite@yahoo.co.jp>\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#ifndef P3P_UTIL_HPP_\n#define P3P_UTIL_HPP_\n\n#include <Eigen/Dense>\n\n#include <random>\n#include <vector>\n\nnamespace P3P\n{\ntemplate <typename FloatType, typename RNG>\nvoid getRandomPose(RNG &rng, FloatType *R, FloatType *t)\n{\n\tstd::uniform_real_distribution<FloatType> ufd(-1, 1);\n\t// compute random rotation\n\tEigen::Matrix<FloatType, 3, 3> mR1;\n\tfor (int k = 0; k < 3; k++)\n\t{\n\t\tfor (int l = 0; l < 3; l++)\n\t\t{\n\t\t\tmR1(k, l) = ufd(rng);\n\t\t}\n\t}\n\tEigen::JacobiSVD<Eigen::Matrix<FloatType, 3, 3, Eigen::RowMajor> > svd(mR1, Eigen::ComputeFullU | Eigen::ComputeFullV);\n\tmR1 = svd.matrixU() * svd.matrixV().transpose();\n\tif (mR1.determinant() < 0)\n\t{\n\t\tmR1.col(0) = -mR1.col(0);\n\t}\n\tEigen::Map<Eigen::Matrix<FloatType, 3, 3, Eigen::RowMajor> > mR(R);\n\tmR = mR1;\n\n\t// compute random translation\n\tEigen::Map<Eigen::Matrix<FloatType, 3, 1> > mt(t);\n\tmt[0] = 0.5 * ufd(rng);\n\tmt[1] = 0.5 * ufd(rng);\n\tmt[2] = 6 + 0.5 * ufd(rng);\n}\n\ntemplate <typename FloatType, typename RNG>\nvoid getRandomPoints(RNG &rng, int n, std::vector<FloatType> &p)\n{\n\tstd::uniform_real_distribution<FloatType> ufd(-1, 1);\n\t// compute random point\n\tp.reserve(3 * n);\n\tp.resize(0);\n\tfor (int k = 0; k < n; k++)\n\t{\n\t\tp.push_back(2 * ufd(rng));\n\t\tp.push_back(2 * ufd(rng));\n\t\tp.push_back(2 * ufd(rng));\n\t}\n}\n\ntemplate <typename FloatType>\nvoid getRandomProjections(int n, FloatType *R, FloatType *t, std::vector<FloatType> &p2d, std::vector<FloatType> &p3d)\n{\n\t// x = R*X + t\n\tstd::random_device rd;\n\tstd::mt19937 rng(rd());\n\tgetRandomPose(rng, R, t);\n\tgetRandomPoints(rng, n, p3d);\n\n\tEigen::Map<Eigen::Matrix<FloatType, 3, 3, Eigen::RowMajor> > mR(R);\n\tEigen::Map<Eigen::Matrix<FloatType, 3, 1> > mt(t);\n\tEigen::Map<Eigen::Matrix<FloatType, 3, Eigen::Dynamic> > mX(&(p3d[0]), 3, n);\n\t// project 3D point\n\tEigen::Matrix<FloatType, 3, Eigen::Dynamic> mTmp(3, n);\n\tmTmp = (mR*mX).colwise() + mt;\n\t// get 2D Point\n\tp2d.resize(2 * n);\n\tEigen::Map<Eigen::Matrix<FloatType, 2, Eigen::Dynamic> > mx(&(p2d[0]), 2, n);\n\t// perspective projection\n\tmx.row(0) = mTmp.row(0).array() / mTmp.row(2).array();\n\tmx.row(1) = mTmp.row(1).array() / mTmp.row(2).array();\n}\n}\n\n#endif // P3P_UTIL_HPP_", "meta": {"hexsha": "edca9b760f04f069d2275478aa394af5193951e0", "size": 3574, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/P3PUtil.hpp", "max_stars_repo_name": "eshibusawa/PoseEstimation", "max_stars_repo_head_hexsha": "7eca2b21673b2cd42f40c1f05d4f67ee89bdc279", "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/P3PUtil.hpp", "max_issues_repo_name": "eshibusawa/PoseEstimation", "max_issues_repo_head_hexsha": "7eca2b21673b2cd42f40c1f05d4f67ee89bdc279", "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/P3PUtil.hpp", "max_forks_repo_name": "eshibusawa/PoseEstimation", "max_forks_repo_head_hexsha": "7eca2b21673b2cd42f40c1f05d4f67ee89bdc279", "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.6990291262, "max_line_length": 120, "alphanum_fraction": 0.6950195859, "num_tokens": 1100, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.72487026428967, "lm_q2_score": 0.6334102636778403, "lm_q1q2_score": 0.45914026523594564}}
{"text": "#pragma once\n\n// ROS\n#include <std_msgs/Float64MultiArray.h>\n#include <std_msgs/MultiArrayDimension.h>\n\n// EIGEN\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n\n// CPLEX\n#include <ilcplex/ilocplex.h>\n\n// Others\n#include <mission.hpp>\n#include <param.hpp>\n\nILOSTLBEGIN\n\nnamespace SwarmPlanning {\n    class SCPPlanner {\n    public:\n        std_msgs::Float64MultiArray msgs_traj_info;\n        std_msgs::Float64MultiArray msgs_traj_input;\n\n        SCPPlanner(Mission _mission,\n                   Param _param)\n                : mission(_mission),\n                  param(_param) {\n            h = param.time_step;\n            T = 34;\n            K = round(T / h) + 1;         // number of segments\n            N = mission.qn;\n            outdim = 3;                 // number of outputs (x,y,z)\n\n            p_max = 5;\n            v_max = 10;\n            a_max = 10;\n            j_max = 10;\n            epsilon = 0.01;\n\n            u_prev = Eigen::MatrixXd::Zero(outdim * N * K, 1);\n        }\n\n        bool update(bool log) {\n            IloEnv env;\n            Timer timer;\n\n            u.resize(outdim * N * K);\n            try {\n                timer.reset();\n                buildConstMtx();\n                timer.stop();\n                ROS_INFO_STREAM(\"Constraint Matrix runtime: \" << timer.elapsedSeconds());\n\n                timer.reset();\n                solveQP(env, log);\n                timer.stop();\n                ROS_INFO_STREAM(\"QP runtime: \" << timer.elapsedSeconds());\n            }\n            catch (IloException &e) {\n                ROS_ERROR_STREAM(\"Concert exception caught: \" << e);\n                return false;\n            }\n            catch (...) {\n                ROS_ERROR(\"Unknown exception caught\");\n                return false;\n            }\n            env.end();\n\n            createMsg();\n            return true;\n        }\n\n    private:\n        Mission mission;\n        Param param;\n\n        double h, T, p_max, v_max, a_max, j_max, epsilon;\n        int K, N, outdim;\n        IloNum count_x, count_eq, count_lq;\n\n        Eigen::MatrixXd Q, A_eq, b_eq, A_ineq, b_ineq,\n                P, V, A, J, p_start, p_goal,\n                A_ineq_dynamics, b_ineq_dynamics, u_prev;\n        std::vector<double> u;\n\n        void buildConstMtx() {\n            build_Q();\n            build_mapping_mtx();\n            build_eq_const();\n            build_ineq_const();\n        }\n\n        void solveQP(const IloEnv &env, bool log) {\n            Timer timer;\n            IloNum cost_total, cost_prev;\n\n            IloCplex cplex(env);\n//        cplex.setParam(IloCplex::Param::TimeLimit, 0.04);\n\n            cost_total = SP_INFINITY;\n            cost_prev = 0;\n            int iter = 0;\n\n            timer.reset();\n            while (abs(cost_total - cost_prev) > epsilon * cost_total) {\n                IloModel model(env);\n                IloNumVarArray var(env);\n                IloRangeArray con(env);\n\n                populatebyrow(model, var, con);\n\n                cplex.extract(model);\n\n                if (log) {\n                    cplex.exportModel(\"/home/jungwon/QPmodel.lp\");\n                } else {\n                    cplex.setOut(env.getNullStream());\n                }\n\n                // Optimize the problem and obtain solution.\n                if (!cplex.solve()) {\n                    env.error() << \"Failed to optimize QP, Check ~/.ros/QPresult.txt\" << endl;\n                    throw (-1);\n                }\n\n                IloNumArray vals(env);\n                cost_prev = cost_total;\n                cost_total = cplex.getObjValue();\n                cplex.getValues(vals, var);\n\n                // update input\n                for (int dim = 0; dim < outdim; dim++) {\n                    for (int qi = 0; qi < N; qi++) {\n                        for (int k = 0; k < K; k++) {\n                            u[dim * N * K + qi * K + k] = vals[dim * N * K + qi * K + k];\n                            u_prev(dim * N * K + qi * K + k, 0) = vals[dim * N * K + qi * K + k];\n                        }\n                    }\n                }\n\n                timer.stop();\n                ROS_INFO_STREAM(\"QP iteration \" << iter << \" : \" << \"total_cost : \" << cost_total);\n                ROS_INFO_STREAM(\"QP iteration \" << iter << \" : \" << \"iteration time : \" << timer.elapsedSeconds());\n                ROS_INFO_STREAM(\"QP iteration \" << iter << \" : \" << \"x size: \" << count_x);\n                ROS_INFO_STREAM(\"QP iteration \" << iter << \" : \" << \"eq const size: \" << count_eq);\n                ROS_INFO_STREAM(\"QP iteration \" << iter << \" : \" << \"ineq const size: \" << count_lq);\n                iter++;\n                timer.reset();\n\n                // update inequality constraints\n                update_ineq_const();\n            }\n\n            ROS_INFO_STREAM(\"QP total cost = \" << cost_total);\n        }\n\n        void createMsg() {\n            std::vector<double> traj_info;\n            traj_info.emplace_back(N);\n            traj_info.emplace_back(K);\n            traj_info.emplace_back(h);\n            msgs_traj_info.data = traj_info;\n            msgs_traj_input.data = u;\n        }\n\n        // Cost matrix Q\n        void build_Q() {\n            Q = Eigen::MatrixXd::Identity(outdim * N * K, outdim * N * K);\n        }\n\n        void build_mapping_mtx() {\n            P = Eigen::MatrixXd::Zero(outdim * N * K, outdim * N * K); // position matrix p = Pu + p_start\n            V = Eigen::MatrixXd::Zero(outdim * N * K, outdim * N * K); // velocity matrix v = Vu, assume v_start = 0\n            A = Eigen::MatrixXd::Identity(outdim * N * K, outdim * N * K); // accelation matrix a = Au\n            J = Eigen::MatrixXd::Zero(outdim * N * K, outdim * N * K); // accelation matrix a = Au\n\n            p_start = Eigen::MatrixXd::Zero(outdim * N * K, 1);\n            p_goal = Eigen::MatrixXd::Zero(outdim * N, 1);\n\n            for (int dim = 0; dim < outdim; dim++) {\n                for (int qi = 0; qi < N; qi++) {\n                    int offset = dim * N * K + qi * K;\n                    for (int k = 0; k < K; k++) {\n                        for (int j = 0; j < k; j++) {\n                            P(offset + k, offset + j) = 0.5 * h * h * (2 * (k - j) - 1);\n                            V(offset + k, offset + j) = h;\n                        }\n                        if (k != 0) {\n                            J(offset + k, offset + k) = 1 / h;\n                            J(offset + k, offset + k - 1) = -1 / h;\n                        }\n\n                        p_start(offset + k, 0) = mission.startState[qi][dim];\n                    }\n                    p_goal(dim * N + qi, 0) = mission.goalState[qi][dim];\n                }\n            }\n        }\n\n        void build_eq_const() {\n            A_eq = Eigen::MatrixXd::Zero(4 * outdim * N, outdim * N * K);\n            b_eq = Eigen::MatrixXd::Zero(4 * outdim * N, 1);\n\n            Eigen::MatrixXd A_init = Eigen::MatrixXd::Zero(outdim * N, outdim * N * K);\n            Eigen::MatrixXd A_final = Eigen::MatrixXd::Zero(outdim * N, outdim * N * K);\n\n            for (int dim = 0; dim < outdim; dim++) {\n                for (int qi = 0; qi < N; qi++) {\n                    int offset = dim * N * K + qi * K;\n                    A_init(dim * N + qi, offset) = 1;\n                    A_final(dim * N + qi, offset + K - 1) = 1;\n                }\n            }\n\n            A_eq.block(0 * outdim * N, 0, outdim * N, outdim * N * K) = A_init;\n            A_eq.block(1 * outdim * N, 0, outdim * N, outdim * N * K) = A_final * P;\n            A_eq.block(2 * outdim * N, 0, outdim * N, outdim * N * K) = A_final * V;\n            A_eq.block(3 * outdim * N, 0, outdim * N, outdim * N * K) = A_final;\n\n            b_eq.block(outdim * N, 0, outdim * N, 1) = p_goal - A_final * p_start;\n        }\n\n        void build_ineq_const() {\n            A_ineq_dynamics = Eigen::MatrixXd::Zero(8 * outdim * N * K, outdim * N * K);\n            A_ineq_dynamics << P,\n                    -P,\n                    V,\n                    -V,\n                    A,\n                    -A,\n                    J,\n                    -J;\n\n            b_ineq_dynamics = Eigen::MatrixXd::Zero(8 * outdim * N * K, 1);\n            Eigen::MatrixXd b_ineq_base = Eigen::MatrixXd::Ones(outdim * N * K, 1);\n            b_ineq_dynamics << b_ineq_base * p_max - p_start,\n                    b_ineq_base * p_max + p_start,\n                    b_ineq_base * v_max,\n                    b_ineq_base * v_max,\n                    b_ineq_base * a_max,\n                    b_ineq_base * a_max,\n                    b_ineq_base * j_max,\n                    b_ineq_base * j_max;\n\n            A_ineq = Eigen::MatrixXd::Zero(8 * outdim * N * K, outdim * N * K);\n            A_ineq = A_ineq_dynamics;\n            b_ineq = Eigen::MatrixXd::Zero(8 * outdim * N * K, 1);\n            b_ineq = b_ineq_dynamics;\n        }\n\n        void update_ineq_const() {\n            Eigen::MatrixXd A_ineq_col = Eigen::MatrixXd::Zero(N * (N - 1) / 2 * K, outdim * N * K);\n            Eigen::MatrixXd b_ineq_col = Eigen::MatrixXd::Zero(N * (N - 1) / 2 * K, 1);\n\n            Eigen::MatrixXd picker_i, picker_j, p_i, p_j, p_prev, eta, temp;\n            p_prev = P * u_prev + p_start;\n\n            double offset = 0;\n            for (int qi = 0; qi < N; qi++) {\n                for (int qj = qi + 1; qj < N; qj++) {\n                    double R = mission.quad_size[qi] + mission.quad_size[qj];\n                    for (int k = 0; k < K; k++) {\n\n                        position_picker(qi, k, picker_i);\n                        position_picker(qj, k, picker_j);\n\n                        p_i = picker_i * p_prev;\n                        p_j = picker_j * p_prev;\n\n                        double distance = (p_i - p_j).norm();\n                        eta = (p_i - p_j) / distance;\n\n                        A_ineq_col.block(offset + k, 0, 1, outdim * N * K) =\n                                -eta.transpose() * (picker_i - picker_j) * P;\n\n                        temp = eta.transpose() * ((p_i - p_j) - (picker_i - picker_j) * p_start);\n                        b_ineq_col(offset + k, 0) = -(R - distance + temp(0, 0));\n                    }\n                    offset += K;\n                }\n            }\n\n            A_ineq = Eigen::MatrixXd::Zero(8 * outdim * N * K + N * (N - 1) / 2 * K, outdim * N * K);\n            A_ineq << A_ineq_dynamics,\n                    A_ineq_col;\n            b_ineq = Eigen::MatrixXd::Zero(8 * outdim * N * K + N * (N - 1) / 2 * K, 1);\n            b_ineq << b_ineq_dynamics,\n                    b_ineq_col;\n        }\n\n        void populatebyrow(IloModel model, IloNumVarArray x, IloRangeArray c) {\n            IloEnv env = model.getEnv();\n\n            for (int dim = 0; dim < outdim; dim++) {\n                for (int qi = 0; qi < N; qi++) {\n                    for (int k = 0; k < K; k++) {\n                        x.add(IloNumVar(env, -IloInfinity, IloInfinity));\n\n                        std::string name;\n                        if (dim == 0) {\n                            name = \"x_\" + std::to_string(qi) + \"_\" + std::to_string(k);\n                        } else if (dim == 1) {\n                            name = \"y_\" + std::to_string(qi) + \"_\" + std::to_string(k);\n                        } else {\n                            name = \"z_\" + std::to_string(qi) + \"_\" + std::to_string(k);\n                        }\n\n                        int row = dim * N * K + qi * K + k;\n                        x[row].setName(name.c_str());\n                    }\n                }\n            }\n            count_x = x.getSize();\n\n            // Cost function\n            IloNumExpr cost(env);\n            for (int i = 0; i < Q.rows(); i++) {\n                for (int j = 0; j < Q.cols(); j++) {\n                    if (Q(i, j) != 0) {\n                        cost += Q(i, j) * x[i] * x[j];\n                    }\n                }\n            }\n            model.add(IloMinimize(env, cost));\n\n\n            // Equality Constraints\n            for (int i = 0; i < A_eq.rows(); i++) {\n                IloNumExpr expr(env);\n                for (int j = 0; j < A_eq.cols(); j++) {\n                    if (A_eq(i, j) != 0) {\n                        expr += A_eq(i, j) * x[j];\n                    }\n                }\n                c.add(expr == b_eq(i));\n                expr.end();\n            }\n            count_eq = c.getSize();\n\n            // Inequality Constraints\n            for (int i = 0; i < A_ineq.rows(); i++) {\n                IloNumExpr expr(env);\n                for (int j = 0; j < A_ineq.cols(); j++) {\n                    if (A_ineq(i, j) != 0) {\n                        expr += A_ineq(i, j) * x[j];\n                    }\n                }\n                c.add(expr <= b_ineq(i));\n                expr.end();\n            }\n            count_lq = c.getSize() - count_eq;\n\n            model.add(c);\n        }\n\n        void position_picker(int qi, int k, Eigen::MatrixXd &P_pick) {\n            P_pick = Eigen::MatrixXd::Zero(outdim, outdim * N * K);\n            for (int dim = 0; dim < outdim; dim++) {\n                P_pick(dim, dim * N * K + qi * K + k) = 1;\n            }\n        }\n    };\n}", "meta": {"hexsha": "94cb642b8a9c172ec1f571d7c07f7fe0adb79b8b", "size": 13142, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "swarm_planner/include/scp_planner.hpp", "max_stars_repo_name": "snu-larr/swarm_simulator", "max_stars_repo_head_hexsha": "dc3f272158132cda4e1c319c7bd1a965d7bf9c40", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-15T03:50:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-15T03:50:54.000Z", "max_issues_repo_path": "swarm_planner/include/scp_planner.hpp", "max_issues_repo_name": "snu-larr/swarm_simulator", "max_issues_repo_head_hexsha": "dc3f272158132cda4e1c319c7bd1a965d7bf9c40", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "swarm_planner/include/scp_planner.hpp", "max_forks_repo_name": "snu-larr/swarm_simulator", "max_forks_repo_head_hexsha": "dc3f272158132cda4e1c319c7bd1a965d7bf9c40", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-03-30T10:58:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T08:19:08.000Z", "avg_line_length": 36.0054794521, "max_line_length": 116, "alphanum_fraction": 0.4159184295, "num_tokens": 3352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938819, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.4591146020295656}}
{"text": "// Author(s): Thomas Neele\n// Copyright: see the accompanying file COPYING or copy at\n// https://github.com/mCRL2org/mCRL2/blob/master/COPYING\n//\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//\n/// \\file quantifiers_propagate_test.cpp\n/// \\brief Test program for absinthe algorithm.\n\n#define BOOST_TEST_MODULE quantifiers_propagate_test\n#include <boost/test/included/unit_test_framework.hpp>\n#include \"mcrl2/pbes/quantifier_propagate.h\"\n#include \"mcrl2/pbes/txt2pbes.h\"\n\nusing namespace mcrl2;\nusing namespace mcrl2::pbes_system;\n\nBOOST_AUTO_TEST_CASE(test_single_forall)\n{\n  std::string PBES_TEXT =\n    \"pbes                                                                                          \\n\"\n    \" nu X(s: List(Nat)) =                                                                         \\n\"\n    \"   forall m1: Nat. Y(s, m1);                                                                  \\n\"\n    \" mu Y(s: List(Nat), m1: Nat) =                                                                \\n\"\n    \"   forall n: Nat. val(!(n mod 6 == m1)) || val(!(n <= 50 && n div 3 == 5)) || Y(n |> s, m1);  \\n\"\n    \"init X([]);                                                                                   \\n\"\n  ;\n\n  std::string RESULT_TEXT =\n    \"pbes                                                                                                         \\n\"\n    \" nu X(s: List(Nat)) =                                                                                        \\n\"\n    \"   Y1(s);                                                                                                    \\n\"\n    \" mu Y1(s: List(Nat)) =                                                                                       \\n\"\n    \"   forall m1: Nat. forall n: Nat. val(!(n mod 6 == m1)) || val(!(n <= 50 && n div 3 == 5)) || Y(n |> s, m1); \\n\"\n    \" mu Y(s: List(Nat), m1: Nat) =                                                                               \\n\"\n    \"   forall n: Nat. val(!(n mod 6 == m1)) || val(!(n <= 50 && n div 3 == 5)) || Y(n |> s, m1);                 \\n\"\n    \"init X([]);                                                                                                  \\n\"\n  ;\n\n  BOOST_CHECK_EQUAL(quantifier_propagate(txt2pbes(PBES_TEXT)), txt2pbes(RESULT_TEXT));\n}\n\nBOOST_AUTO_TEST_CASE(test_two_quantifiers)\n{\n  std::string PBES_TEXT =\n    \"pbes                                                                                          \\n\"\n    \" nu X(s: List(Nat)) =                                                                         \\n\"\n    \"   exists m2: Nat. forall m1: Nat. Y(s, m1 + m2);                                             \\n\"\n    \" mu Y(s: List(Nat), m1: Nat) =                                                                \\n\"\n    \"   forall n: Nat. val(!(n mod 6 == m1)) || val(!(n <= 50 && n div 3 == 5)) || Y(n |> s, m1);  \\n\"\n    \"init X([]);                                                                                   \\n\"\n  ;\n\n  std::string RESULT_TEXT =\n    \"pbes                                                                                                                                   \\n\"\n    \" nu X(s: List(Nat)) =                                                                                                                  \\n\"\n    \"   Y1(s);                                                                                                                              \\n\"\n    \" mu Y1(s: List(Nat)) =                                                                                                                 \\n\"\n    \"   exists m2: Nat. forall m1: Nat. forall n: Nat. val(!(n mod 6 == m1 + m2)) || val(!(n <= 50 && n div 3 == 5)) || Y(n |> s, m1 + m2); \\n\"\n    \" mu Y(s: List(Nat), m1: Nat) =                                                                                                         \\n\"\n    \"   forall n: Nat. val(!(n mod 6 == m1)) || val(!(n <= 50 && n div 3 == 5)) || Y(n |> s, m1);                                           \\n\"\n    \"init X([]);                                                                                                                            \\n\"\n  ;\n\n  BOOST_CHECK_EQUAL(quantifier_propagate(txt2pbes(PBES_TEXT)), txt2pbes(RESULT_TEXT));\n}\n\nBOOST_AUTO_TEST_CASE(test_parameter_dependency)\n{\n  std::string PBES_TEXT =\n    \"pbes                                                                                          \\n\"\n    \" nu X(s: List(Nat)) =                                                                         \\n\"\n    \"   forall m1: Nat. Y(s, head(s) + m1);                                                        \\n\"\n    \" mu Y(s: List(Nat), m1: Nat) =                                                                \\n\"\n    \"   forall n: Nat. val(!(n mod 6 == m1)) || val(!(n <= 50 && n div 3 == 5)) || Y(n |> s, m1);  \\n\"\n    \"init X([]);                                                                                   \\n\"\n  ;\n\n  // No changes expected, since m1 depends on the parameter s in Y(s, head(s) + m1)\n  std::string RESULT_TEXT = PBES_TEXT;\n\n  BOOST_CHECK_EQUAL(quantifier_propagate(txt2pbes(PBES_TEXT)), txt2pbes(RESULT_TEXT));\n}\n\nBOOST_AUTO_TEST_CASE(test_no_quantifier)\n{\n  std::string PBES_TEXT =\n    \"pbes             \\n\"\n    \" nu X(s: Nat) =  \\n\"\n    \"   Y(2);         \\n\"\n    \" mu Y(s: Nat) =  \\n\"\n    \"   val(s == 2);  \\n\"\n    \"init X(0);       \\n\"\n  ;\n\n  // No changes expected, since there is no quantifier to propagate\n  std::string RESULT_TEXT = PBES_TEXT;\n\n  BOOST_CHECK_EQUAL(quantifier_propagate(txt2pbes(PBES_TEXT)), txt2pbes(RESULT_TEXT));\n}\n", "meta": {"hexsha": "6d1eee15c1272c4ed3252489c560f217b2f33af8", "size": 5710, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libraries/pbes/test/quantifier_propagate_test.cpp", "max_stars_repo_name": "Noxsense/mCRL2", "max_stars_repo_head_hexsha": "dd2fcdd6eb8b15af2729633041c2dbbd2216ad24", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 61.0, "max_stars_repo_stars_event_min_datetime": "2018-05-24T13:14:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T11:35:03.000Z", "max_issues_repo_path": "libraries/pbes/test/quantifier_propagate_test.cpp", "max_issues_repo_name": "Noxsense/mCRL2", "max_issues_repo_head_hexsha": "dd2fcdd6eb8b15af2729633041c2dbbd2216ad24", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 229.0, "max_issues_repo_issues_event_min_datetime": "2018-05-28T08:31:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T11:02:41.000Z", "max_forks_repo_path": "libraries/pbes/test/quantifier_propagate_test.cpp", "max_forks_repo_name": "Noxsense/mCRL2", "max_forks_repo_head_hexsha": "dd2fcdd6eb8b15af2729633041c2dbbd2216ad24", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 28.0, "max_forks_repo_forks_event_min_datetime": "2018-04-11T14:09:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-25T15:57:39.000Z", "avg_line_length": 55.4368932039, "max_line_length": 143, "alphanum_fraction": 0.3280210158, "num_tokens": 1263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.5698526514141572, "lm_q1q2_score": 0.45909164427423926}}
{"text": "#ifndef PARMCB_DETAIL_LEX_DIJKSTRA_HPP_\n#define PARMCB_DETAIL_LEX_DIJKSTRA_HPP_\n\n//    Copyright (C) Dimitrios Michail 2019 - 2021.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          https://www.boost.org/LICENSE_1_0.txt)\n\n#include <iostream>\n\n#include <boost/scoped_array.hpp>\n#include <boost/throw_exception.hpp>\n#include <boost/functional/hash.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <boost/property_map/function_property_map.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/graph_concepts.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/detail/d_ary_heap.hpp>\n\n#include <parmcb/detail/dijkstra.hpp>\n#include <parmcb/detail/util.hpp>\n\nnamespace parmcb {\n\n    namespace detail {\n\n        template<class Graph, class DistanceMap>\n        struct LexDistance {\n            typedef typename boost::property_traits<DistanceMap>::value_type DistanceType;\n\n            LexDistance() :\n                    distance(DistanceType()), edge_count(0), min_vertex_index(0) {\n            }\n\n            LexDistance(DistanceType distance, std::size_t edge_count, std::size_t min_vertex_index) :\n                    distance(distance), edge_count(edge_count), min_vertex_index(min_vertex_index) {\n            }\n\n            DistanceType distance;\n            std::size_t edge_count;\n            std::size_t min_vertex_index;\n        };\n\n        template<class Graph, class DistanceMap>\n        struct LexDistanceCompare {\n            typedef typename boost::property_traits<DistanceMap>::value_type DistanceType;\n\n            bool operator()(const LexDistance<Graph, DistanceMap> &a, const LexDistance<Graph, DistanceMap> &b) {\n                if (a.distance < b.distance) {\n                    return true;\n                } else if (a.distance > b.distance) {\n                    return false;\n                }\n                if (a.edge_count < b.edge_count) {\n                    return true;\n                } else if (a.edge_count > b.edge_count) {\n                    return false;\n                }\n                if (a.min_vertex_index < b.min_vertex_index) {\n                    return true;\n                }\n                return false;\n            }\n        };\n\n        template<class Graph, class IndexMap, class WeightMap, class DistanceMap>\n        struct LexDistanceCombine {\n            typedef typename boost::property_map<Graph, boost::vertex_index_t>::type VertexIndexMapType;\n            typedef typename boost::graph_traits<Graph>::edge_descriptor Edge;\n            typedef typename boost::property_traits<DistanceMap>::value_type DistanceType;\n            typedef typename boost::property_traits<WeightMap>::value_type WeightType;\n\n            LexDistanceCombine(const Graph &g, const IndexMap &index_map, const WeightMap &weight_map) :\n                    inf((std::numeric_limits<DistanceType>::max)()), g(g), index_map(\n                            index_map), weight_map(weight_map) {\n            }\n\n            LexDistance<Graph, DistanceMap> operator()(const LexDistance<Graph, DistanceMap> &a, const Edge &e) {\n                const auto index_target = index_map[boost::target(e, g)];\n                const auto index_source = index_map[boost::source(e, g)];\n\n                const WeightType e_weight = boost::get(weight_map, e);\n                const WeightType sum = combine(a.distance, e_weight);\n\n                return LexDistance<Graph, DistanceMap>(sum, a.edge_count + 1, std::min( { a.min_vertex_index,\n                        index_target, index_source }));\n            }\n\n            const DistanceType inf;\n            const parmcb::detail::closed_plus<DistanceType> combine;\n            const Graph &g;\n            const VertexIndexMapType &index_map;\n            const WeightMap &weight_map;\n        };\n\n    } // detail\n\n    template<class Graph, class WeightMap, class DistanceMap, class PredecessorMap>\n    void lex_dijkstra(const Graph &g, const WeightMap &weight_map,\n            const typename boost::graph_traits<Graph>::vertex_descriptor &s, DistanceMap &dist_map,\n            PredecessorMap &pred_map) {\n\n        typedef typename boost::graph_traits<Graph>::vertex_descriptor Vertex;\n        typedef typename boost::property_map<Graph, boost::vertex_index_t>::type VertexIndexMapType;\n        typedef typename boost::graph_traits<Graph>::edge_descriptor Edge;\n        typedef typename boost::property_traits<DistanceMap>::value_type DistanceType;\n\n        typedef typename parmcb::detail::LexDistance<Graph, DistanceMap> LexDistanceType;\n        typedef typename parmcb::detail::LexDistanceCompare<Graph, DistanceMap> LexDistanceCompareType;\n\n        const VertexIndexMapType &index_map = boost::get(boost::vertex_index, g);\n        std::vector<std::size_t> index_in_heap(boost::num_vertices(g));\n        boost::function_property_map<parmcb::detail::VertexIndexFunctor<Graph, std::size_t>, Vertex, std::size_t&> index_in_heap_map(\n                parmcb::detail::VertexIndexFunctor<Graph, std::size_t>(index_in_heap, index_map));\n\n        std::vector<LexDistanceType> lex_dist(boost::num_vertices(g));\n        boost::function_property_map<parmcb::detail::VertexIndexFunctor<Graph, LexDistanceType>, Vertex,\n                LexDistanceType&> lex_dist_map(\n                parmcb::detail::VertexIndexFunctor<Graph, LexDistanceType>(lex_dist, index_map));\n\n        typedef boost::d_ary_heap_indirect<Vertex, 4,\n                boost::function_property_map<parmcb::detail::VertexIndexFunctor<Graph, std::size_t>, Vertex,\n                        std::size_t&>,\n                boost::function_property_map<parmcb::detail::VertexIndexFunctor<Graph, LexDistanceType>, Vertex,\n                        LexDistanceType&>, LexDistanceCompareType> VertexQueue;\n\n        LexDistanceCompareType compare;\n        parmcb::detail::LexDistanceCombine<Graph, VertexIndexMapType, WeightMap, DistanceMap> combine(g, index_map, weight_map);\n\n        VertexQueue queue(lex_dist_map, index_in_heap_map, compare);\n\n        boost::put(lex_dist_map, s, LexDistanceType(DistanceType(), 0, index_map[s]));\n        boost::put(pred_map, s, std::make_tuple(false, Edge()));\n        queue.push(s);\n\n        while (!queue.empty()) {\n            Vertex u = queue.top();\n            queue.pop();\n            LexDistanceType d_u = boost::get(lex_dist_map, u);\n\n            auto eiRange = boost::out_edges(u, g);\n            for (auto ei = eiRange.first; ei != eiRange.second; ++ei) {\n                auto e = *ei;\n\n                auto w = boost::target(e, g);\n                if (w == u) {\n                    w = boost::source(e, g);\n                }\n                if (w == u) {\n                    // self-loop\n                    continue;\n                }\n                if (w == s) {\n                    continue;\n                }\n\n                const LexDistanceType c = combine(d_u, e);\n                bool visited_w = std::get<0>(boost::get(pred_map, w));\n                if (!visited_w) {\n                    // first time found\n                    boost::put(lex_dist_map, w, c);\n                    boost::put(dist_map, w, c.distance);\n                    boost::put(pred_map, w, std::make_tuple(true, e));\n                    queue.push(w);\n                } else if (compare(c, boost::get(lex_dist_map, w))) {\n                    // already reached\n                    boost::put(lex_dist_map, w, c);\n                    boost::put(dist_map, w, c.distance);\n                    boost::put(pred_map, w, std::make_tuple(true, e));\n                    queue.update(w);\n                }\n            }\n        }\n    }\n\n} // mcb\n\n#endif\n", "meta": {"hexsha": "4fedac3b2a8f65d946af9e57284a755fd8629f9a", "size": 7697, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/parmcb/detail/lex_dijkstra.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/detail/lex_dijkstra.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/detail/lex_dijkstra.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": 42.7611111111, "max_line_length": 133, "alphanum_fraction": 0.6015330648, "num_tokens": 1657, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146847, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4590916442742391}}
{"text": "#ifndef MST_CONTROLLER_HPP\n#define MST_CONTROLLER_HPP 1\n\n#include \"linterp.h\"\n#include \"toml.h\"\n#include <Eigen/Core>\n#include <boost/numeric/odeint.hpp>\n#include <fstream>\n#include <functional>\n#include <iostream>\n#include <memory>\n#include <string>\n\nnamespace MST { // The MST namespace contains the classes used for control.\n\nusing std::string;\nusing namespace boost::numeric::odeint;\nnamespace pl = std::placeholders;\n\n// Matrix and Vector are shortcuts for Eigen types\nusing Matrix = Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>;\nusing Vector = Eigen::Matrix<double, Eigen::Dynamic, 1>;\nusing Eigen::Vector2d;\n\nnamespace Utils {\ntemplate <typename T> T load_dat(const std::string &path) {\n\tstd::ifstream indata(path);\n\tstd::string line;\n\tstd::vector<double> values;\n\tsize_t rows = 0;\n\twhile (std::getline(indata, line)) {\n\t\tstd::stringstream lineStream(line);\n\t\tstd::string cell;\n\t\twhile (std::getline(lineStream, cell, ' ')) {\n\t\t\tvalues.push_back(std::stod(cell));\n\t\t}\n\t\t++rows;\n\t}\n\treturn Eigen::Map<const T>(values.data(), rows, values.size() / rows);\n}\n} // namespace Utils\n\nclass Config {\npublic:\n\tConfig(const char *filename) : Config(std::string(filename)) {}\n\tConfig(const std::string &filename) {\n\t\tstd::ifstream config_file(filename);\n\t\ttoml::ParseResult parsed_config = toml::parse(config_file);\n\n\t\t// make sure config parsed correctly\n\t\tif (!parsed_config.valid()) {\n\t\t\tthrow std::runtime_error(parsed_config.errorReason);\n\t\t}\n\n\t\t// extract control parameters\n\t\tm_config = parsed_config.value;\n\t}\n\n\tConfig operator[](const std::string &path) {\n\t\treturn Config(m_config[path]);\n\t}\n\n\tdouble getDouble(const std::string &name) const {\n\t\treturn m_config.get<double>(name);\n\t}\n\n\tstd::string getString(const std::string &name) const {\n\t\treturn m_config.get<std::string>(name);\n\t}\n\n\t// Load a column vector from a TOML array.\n\t// All rows of the TOML array must have exactly one element.\n\tVector getVector(const std::string &name) const {\n\t\tconst toml::Array &rows = m_config.get<toml::Array>(name);\n\t\tconst size_t n = rows.size();\n\t\tVector vec(n);\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tconst toml::Value row = rows[i];\n\t\t\tvec(i) = row.get<double>(0);\n\t\t}\n\t\treturn vec;\n\t}\n\n\t// Load a matrix from a TOML array.\n\t// All rows of the TOML array must have the same length.\n\tMatrix getMatrix(const std::string &name) const {\n\t\tconst toml::Array &rows = m_config.get<toml::Array>(name);\n\t\tconst size_t n = rows.size();\n\t\tconst size_t p = rows.at(0).size();\n\t\tMatrix mat(n, p);\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tconst toml::Value row = rows.at(i);\n\t\t\tfor (int j = 0; j < p; ++j) {\n\t\t\t\tmat(i, j) = row.get<double>(j);\n\t\t\t}\n\t\t}\n\t\treturn mat;\n\t}\n\nprivate:\n\ttoml::Value m_config;\n\n\tConfig(const toml::Value &config) : m_config(config) {}\n};\n\nclass System {\npublic:\n\ttemplate <typename T> System &operator>>(const T &next) {\n\t\tif (m_next) {\n\t\t\t*m_next >> next;\n\t\t} else {\n\t\t\tm_next = std::make_shared<T>(next);\n\t\t}\n\t\treturn *this;\n\t}\n\n\tVector operator()(const double t, const Vector &v) {\n\t\tconst Vector output = step(t, v, Vector());\n\t\tif (m_next) {\n\t\t\treturn (*m_next)(t, output, Vector());\n\t\t}\n\t\treturn output;\n\t}\n\n\tVector operator()(const double t, const Vector &ref, const Vector &actual) {\n\t\tconst Vector output = step(t, ref, actual);\n\t\tif (m_next) {\n\t\t\treturn (*m_next)(t, output, actual);\n\t\t}\n\t\treturn output;\n\t}\n\nprivate:\n\tstd::shared_ptr<System> m_next;\n\n\tvirtual Vector step(const double t, const Vector &ref,\n\t                    const Vector &actual) = 0;\n};\n\nclass Controller : public System {\nprivate:\n\t// Matrices of coefficients\n\tMatrix A;\n\tMatrix B;\n\tMatrix C;\n\tMatrix D;\n\tMatrix F;\n\tMatrix K;\n\tMatrix Ki;\n\tMatrix L;\n\n\t// Precalculated matrices\n\tMatrix AmLC;\n\tMatrix BmLD;\n\n\t// Desired values\n\tVector ud;\n\tVector xd;\n\n\t// Natural equilibrium\n\tVector r0;\n\tVector u0;\n\n\t// Saturation\n\tVector u_min;\n\tVector u_max;\n\n\t// State of the controller\n\tVector xh;\n\tVector xi;\n\n\t// Time step\n\tdouble dt;\n\npublic:\n\tController(const Config &config) {\n\t\tA = config.getMatrix(\"A\");\n\t\tB = config.getMatrix(\"B\");\n\t\tC = config.getMatrix(\"C\");\n\t\tD = config.getMatrix(\"D\");\n\t\tF = config.getMatrix(\"F\");\n\t\tK = config.getMatrix(\"K\");\n\t\tKi = config.getMatrix(\"Ki\");\n\t\tL = config.getMatrix(\"L\");\n\n\t\tAmLC = A - L * C;\n\t\tBmLD = B - L * D;\n\n\t\tud = config.getVector(\"ud\");\n\t\txd = config.getVector(\"xd\");\n\n\t\tr0 = config.getVector(\"r0\");\n\t\tu0 = config.getVector(\"u0\");\n\n\t\tu_min = config.getVector(\"u_min\");\n\t\tu_max = config.getVector(\"u_max\");\n\n\t\tdt = config.getDouble(\"dt\");\n\n\t\txh.setZero(A.rows());\n\t\txi.setZero(C.rows());\n\t}\n\n\tvirtual Vector step(const double t, const Vector &r, const Vector &y) {\n\t\tif (r.rows() == 0 || r.cols() == 0) {\n\t\t\treturn Vector();\n\t\t}\n\n\t\tVector u = F * (r - r0) - K * xh - Ki * xi;\n\n\t\t// Saturation\n\t\tu = (u + u0).cwiseMax(u_min).cwiseMin(u_max) - u0;\n\n\t\txh = AmLC * xh + BmLD * u + L * (y - r0);\n\t\txi += dt * (y - r);\n\n\t\treturn u + u0;\n\t}\n};\n\nclass OutputConverter : public System {\npublic:\n\tOutputConverter(const Config &config) {\n\t\tm_coeff(0) = config.getDouble(\"coeff_phi\");\n\t\tm_coeff(1) = config.getDouble(\"coeff_theta\");\n\t\tm_R(0) = config.getDouble(\"R_phi\");\n\t\tm_R(1) = config.getDouble(\"R_theta\");\n\t\tm_L(0) = config.getDouble(\"L_phi\");\n\t\tm_L(1) = config.getDouble(\"L_theta\");\n\t\tm_dt = config.getDouble(\"dt\");\n\t\tm_shot = Utils::load_dat<Matrix>(config.getString(\"shot_data\"));\n\t\tm_count = 1;\n\t}\n\n\tvirtual Vector step(const double, const Vector &V, const Vector &) {\n\t\tif (V.rows() == 0 || V.cols() == 0) {\n\t\t\tm_V = m_shot.row(m_count);\n\t\t} else {\n\t\t\tm_V = V;\n\t\t}\n\t\tm_stepper.do_step(std::bind(&OutputConverter::primaryCurrentDot, this,\n\t\t                            pl::_1, pl::_2, pl::_3),\n\t\t                  m_I, 0.0, m_dt);\n\t\t++m_count;\n\n\t\treturn m_I;\n\t}\n\nprivate:\n\t// state\n\tVector2d m_I;\n\tVector2d m_V;\n\n\t// parameters\n\tVector2d m_coeff;\n\tVector2d m_R;\n\tVector2d m_L;\n\tdouble m_dt;\n\tMatrix m_shot;\n\tsize_t m_count;\n\n\trunge_kutta_dopri5<Vector2d, double, Vector2d, double, vector_space_algebra>\n\t    m_stepper;\n\n\tvoid primaryCurrentDot(const Vector2d &I, Vector2d &dIdt,\n\t                       const double /*t*/) {\n\t\tdIdt(0) = (m_coeff(0) * m_V(0) - m_R(0) * I(0)) / m_L(0);\n\t\tdIdt(1) = (m_coeff(1) * m_V(1) - m_R(1) * I(1)) / m_L(1);\n\t}\n};\n\nclass NonLinearityFirstComponent : public System {\npublic:\n\tNonLinearityFirstComponent(const Config &config) {\n\t\tVector x(Utils::load_dat<Vector>(config.getString(\"x\")));\n\t\tVector y(Utils::load_dat<Vector>(config.getString(\"y\")));\n\n\t\tconst auto grid_iter_list = {x.data()};\n\t\tconst auto grid_sizes = {x.size()};\n\t\tconst size_t num_elements = x.size();\n\n\t\tm_f.reset(new InterpMultilinear<1, double>(grid_iter_list.begin(),\n\t\t                                           grid_sizes.begin(), y.data(),\n\t\t                                           y.data() + num_elements));\n\t}\n\n\tvirtual Vector step(const double, const Vector &r, const Vector &) {\n\t\tif (r.rows() == 0 || r.cols() == 0) {\n\t\t\treturn Vector();\n\t\t}\n\t\tVector r1(r);\n\t\tr1(0) = f(r(0));\n\t\treturn r1;\n\t}\n\n\tdouble f(const double x) const {\n\t\tconst std::array<double, 1> args = {{x}};\n\t\treturn m_f->interp(args.begin());\n\t}\n\nprivate:\n\tstd::shared_ptr<InterpMultilinear<1, double>> m_f;\n};\n\nclass InputConverter : public System {\npublic:\n\tInputConverter(const Config &config) {\n\t\tVector F(Utils::load_dat<Vector>(config.getString(\"F\")));\n\t\tVector Ip(Utils::load_dat<Vector>(config.getString(\"Ip\")));\n\t\tMatrix lambda0(Utils::load_dat<Matrix>(config.getString(\"lambda0\")));\n\t\tMatrix flux(Utils::load_dat<Matrix>(config.getString(\"flux\")));\n\n\t\tconst auto grid_iter_list = {F.data(), Ip.data()};\n\t\tconst auto grid_sizes = {F.size(), Ip.size()};\n\t\tconst size_t num_elements = F.size() * Ip.size();\n\n\t\tlambda0.transposeInPlace();\n\t\tflux.transposeInPlace();\n\n\t\tm_lambda0.reset(new InterpMultilinear<2, double>(\n\t\t    grid_iter_list.begin(), grid_sizes.begin(), lambda0.data(),\n\t\t    lambda0.data() + num_elements));\n\t\tm_flux.reset(new InterpMultilinear<2, double>(\n\t\t    grid_iter_list.begin(), grid_sizes.begin(), flux.data(),\n\t\t    flux.data() + num_elements));\n\t}\n\n\tvirtual Vector step(const double, const Vector &r, const Vector &) {\n\t\tif (r.rows() == 0 || r.cols() == 0) {\n\t\t\treturn Vector();\n\t\t}\n\t\tVector r1(2);\n\t\tr1(0) = lambda0(r(0), r(1));\n\t\tr1(1) = flux(r(0), r(1));\n\t\treturn r1;\n\t}\n\n\tdouble lambda0(const double F, const double Ip) const {\n\t\tconst std::array<double, 2> args = {{F, Ip}};\n\t\treturn m_lambda0->interp(args.begin());\n\t}\n\n\tdouble flux(const double F, const double Ip) const {\n\t\tconst std::array<double, 2> args = {{F, Ip}};\n\t\treturn m_flux->interp(args.begin());\n\t}\n\nprivate:\n\tstd::unique_ptr<InterpMultilinear<2, double>> m_lambda0;\n\tstd::unique_ptr<InterpMultilinear<2, double>> m_flux;\n};\n\nclass ReferenceOutput {\npublic:\n\tReferenceOutput(const Config &config) {\n\t\tconst double F1 = config.getDouble(\"F1\");\n\t\tconst double F2 = config.getDouble(\"F2\");\n\t\tconst double Ip1 = config.getDouble(\"Ip1\");\n\t\tconst double Ip2 = config.getDouble(\"Ip2\");\n\n\t\tm_t1 = config.getDouble(\"t1\");\n\t\tm_t2 = config.getDouble(\"t2\");\n\n\t\tm_r1 = Vector2d(F1, Ip1);\n\t\tm_r2 = Vector2d(F2, Ip2);\n\t}\n\n\tVector operator()(const double t) const {\n\t\tif (t < m_t1) {\n\t\t\treturn Vector(); // FIXME openloop\n\t\t} else if (t < m_t2) {\n\t\t\treturn m_r1;\n\t\t} else {\n\t\t\treturn m_r2;\n\t\t}\n\t}\n\nprivate:\n\tdouble m_t1;\n\tdouble m_t2;\n\tVector2d m_r1;\n\tVector2d m_r2;\n};\n\n} // namespace MST\n\n#endif", "meta": {"hexsha": "4b64cb01e4113cbcc05a4f88d770440266b3b731", "size": 9294, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "MST.hpp", "max_stars_repo_name": "igoumiri/MSTpp", "max_stars_repo_head_hexsha": "39065ad51bc507f94c70b5b3d06863c84458c283", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MST.hpp", "max_issues_repo_name": "igoumiri/MSTpp", "max_issues_repo_head_hexsha": "39065ad51bc507f94c70b5b3d06863c84458c283", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MST.hpp", "max_forks_repo_name": "igoumiri/MSTpp", "max_forks_repo_head_hexsha": "39065ad51bc507f94c70b5b3d06863c84458c283", "max_forks_repo_licenses": ["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.015503876, "max_line_length": 77, "alphanum_fraction": 0.6423499032, "num_tokens": 2702, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4590916389555596}}
{"text": "/**\n * @file async_learning_test.hpp\n * @author Shangtong Zhang\n *\n * Test for async deep RL methods.\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#include <mlpack/core.hpp>\n\n#include <mlpack/methods/ann/ffn.hpp>\n#include <mlpack/methods/ann/init_rules/gaussian_init.hpp>\n#include <mlpack/methods/ann/layer/layer.hpp>\n#include <mlpack/methods/ann/loss_functions/mean_squared_error.hpp>\n#include <mlpack/methods/ann/loss_functions/sigmoid_cross_entropy_error.hpp>\n#include <mlpack/methods/reinforcement_learning/async_learning.hpp>\n#include <mlpack/methods/reinforcement_learning/environment/cart_pole.hpp>\n#include <mlpack/core/optimizers/sgd/update_policies/vanilla_update.hpp>\n#include <mlpack/methods/reinforcement_learning/policy/greedy_policy.hpp>\n#include <mlpack/methods/reinforcement_learning/policy/aggregated_policy.hpp>\n#include <mlpack/methods/reinforcement_learning/training_config.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n\nusing namespace mlpack;\nusing namespace mlpack::ann;\nusing namespace mlpack::optimization;\nusing namespace mlpack::rl;\n\nBOOST_AUTO_TEST_SUITE(AsyncLearningTest);\n\n// Test async one step q-learning in Cart Pole.\nBOOST_AUTO_TEST_CASE(OneStepQLearningTest)\n{\n  /**\n   * This is for the Travis CI server, in your own machine you should use more\n   * threads.\n   */\n  #ifdef HAS_OPENMP\n    omp_set_num_threads(1);\n  #endif\n\n  // Set up the network.\n  FFN<MeanSquaredError<>, GaussianInitialization> model(MeanSquaredError<>(),\n      GaussianInitialization(0, 0.001));\n  model.Add<Linear<>>(4, 20);\n  model.Add<ReLULayer<>>();\n  model.Add<Linear<>>(20, 20);\n  model.Add<ReLULayer<>>();\n  model.Add<Linear<>>(20, 2);\n\n  // Set up the policy.\n  using Policy = GreedyPolicy<CartPole>;\n  AggregatedPolicy<Policy> policy({Policy(0.7, 5000, 0.1),\n                                  Policy(0.7, 5000, 0.01),\n                                  Policy(0.7, 5000, 0.5)},\n                                  arma::colvec(\"0.4 0.3 0.3\"));\n\n  TrainingConfig config;\n  config.StepSize() = 0.0001;\n  config.Discount() = 0.99;\n  config.NumWorkers() = 16;\n  config.UpdateInterval() = 6;\n  config.StepLimit() = 200;\n  config.TargetNetworkSyncInterval() = 200;\n\n  OneStepQLearning<CartPole, decltype(model), VanillaUpdate, decltype(policy)>\n      agent(std::move(config), std::move(model), std::move(policy));\n\n  arma::vec rewards(20, arma::fill::zeros);\n  size_t pos = 0;\n  size_t testEpisodes = 0;\n  auto measure = [&rewards, &pos, &testEpisodes](double reward)\n  {\n    size_t maxEpisode = 10000;\n    if (testEpisodes > maxEpisode)\n      BOOST_REQUIRE(false);\n    testEpisodes++;\n    rewards[pos++] = reward;\n    pos %= rewards.n_elem;\n    // Maybe underestimated.\n    double avgReward = arma::mean(rewards);\n    Log::Debug << \"Average return: \" << avgReward\n        << \" Episode return: \" << reward << std::endl;\n    if (avgReward > 60)\n      return true;\n    return false;\n  };\n\n  agent.Train(measure);\n  Log::Debug << \"Total test episodes: \" << testEpisodes << std::endl;\n}\n\n// Test async one step Sarsa in Cart Pole.\nBOOST_AUTO_TEST_CASE(OneStepSarsaTest)\n{\n  /**\n   * This is for the Travis CI server, in your own machine you shuold use more\n   * threads.\n   */\n  #ifdef HAS_OPENMP\n    omp_set_num_threads(1);\n  #endif\n\n  // Set up the network.\n  FFN<MeanSquaredError<>, GaussianInitialization> model(MeanSquaredError<>(),\n      GaussianInitialization(0, 0.001));\n  model.Add<Linear<>>(4, 20);\n  model.Add<ReLULayer<>>();\n  model.Add<Linear<>>(20, 20);\n  model.Add<ReLULayer<>>();\n  model.Add<Linear<>>(20, 2);\n\n  // Set up the policy.\n  using Policy = GreedyPolicy<CartPole>;\n  AggregatedPolicy<Policy> policy({Policy(0.7, 5000, 0.1),\n                                  Policy(0.7, 5000, 0.01),\n                                  Policy(0.7, 5000, 0.5)},\n                                  arma::colvec(\"0.4 0.3 0.3\"));\n\n  TrainingConfig config;\n  config.StepSize() = 0.0001;\n  config.Discount() = 0.99;\n  config.NumWorkers() = 16;\n  config.UpdateInterval() = 6;\n  config.StepLimit() = 200;\n  config.TargetNetworkSyncInterval() = 200;\n\n  OneStepSarsa<CartPole, decltype(model), VanillaUpdate, decltype(policy)>\n      agent(std::move(config), std::move(model), std::move(policy));\n\n  arma::vec rewards(20, arma::fill::zeros);\n  size_t pos = 0;\n  size_t testEpisodes = 0;\n  auto measure = [&rewards, &pos, &testEpisodes](double reward)\n  {\n    size_t maxEpisode = 100000;\n    if (testEpisodes > maxEpisode)\n      BOOST_REQUIRE(false);\n    testEpisodes++;\n    rewards[pos++] = reward;\n    pos %= rewards.n_elem;\n    // Maybe underestimated.\n    double avgReward = arma::mean(rewards);\n    Log::Debug << \"Average return: \" << avgReward\n               << \" Episode return: \" << reward << std::endl;\n    if (avgReward > 60)\n      return true;\n    return false;\n  };\n\n  agent.Train(measure);\n  Log::Debug << \"Total test episodes: \" << testEpisodes << std::endl;\n}\n\n// Test async n step q-learning in Cart Pole.\nBOOST_AUTO_TEST_CASE(NStepQLearningTest)\n{\n  /**\n   * This is for the Travis CI server, in your own machine you shuold use more\n   * threads.\n   */\n  #ifdef HAS_OPENMP\n    omp_set_num_threads(1);\n  #endif\n\n  // Set up the network.\n  FFN<MeanSquaredError<>, GaussianInitialization> model(MeanSquaredError<>(),\n      GaussianInitialization(0, 0.001));\n  model.Add<Linear<>>(4, 20);\n  model.Add<ReLULayer<>>();\n  model.Add<Linear<>>(20, 20);\n  model.Add<ReLULayer<>>();\n  model.Add<Linear<>>(20, 2);\n\n  // Set up the policy.\n  using Policy = GreedyPolicy<CartPole>;\n  AggregatedPolicy<Policy> policy({Policy(0.7, 5000, 0.1),\n                                   Policy(0.7, 5000, 0.01),\n                                   Policy(0.7, 5000, 0.5)},\n                                  arma::colvec(\"0.4 0.3 0.3\"));\n\n  TrainingConfig config;\n  config.StepSize() = 0.0001;\n  config.Discount() = 0.99;\n  config.NumWorkers() = 16;\n  config.UpdateInterval() = 6;\n  config.StepLimit() = 200;\n  config.TargetNetworkSyncInterval() = 200;\n\n  NStepQLearning<CartPole, decltype(model), VanillaUpdate, decltype(policy)>\n      agent(std::move(config), std::move(model), std::move(policy));\n\n  arma::vec rewards(20, arma::fill::zeros);\n  size_t pos = 0;\n  size_t testEpisodes = 0;\n  auto measure = [&rewards, &pos, &testEpisodes](double reward)\n  {\n    size_t maxEpisode = 100000;\n    if (testEpisodes > maxEpisode)\n      BOOST_REQUIRE(false);\n    testEpisodes++;\n    rewards[pos++] = reward;\n    pos %= rewards.n_elem;\n    // Maybe underestimated.\n    double avgReward = arma::mean(rewards);\n    Log::Debug << \"Average return: \" << avgReward\n               << \" Episode return: \" << reward << std::endl;\n    if (avgReward > 60)\n      return true;\n    return false;\n  };\n\n  agent.Train(measure);\n  Log::Debug << \"Total test episodes: \" << testEpisodes << std::endl;\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "11cbe66900699e572a63f529630b8e762ef49742", "size": 7067, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/async_learning_test.cpp", "max_stars_repo_name": "chigur/mlpack", "max_stars_repo_head_hexsha": "aff1eda03b7c279acb6d3e660d5c5a6f697d3735", "max_stars_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/mlpack/tests/async_learning_test.cpp", "max_issues_repo_name": "chigur/mlpack", "max_issues_repo_head_hexsha": "aff1eda03b7c279acb6d3e660d5c5a6f697d3735", "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/tests/async_learning_test.cpp", "max_forks_repo_name": "chigur/mlpack", "max_forks_repo_head_hexsha": "aff1eda03b7c279acb6d3e660d5c5a6f697d3735", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.6905829596, "max_line_length": 78, "alphanum_fraction": 0.6527522287, "num_tokens": 1984, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4590916389555596}}
{"text": "#pragma once\n\n#include <boost/math/constants/constants.hpp>\n\n#include \"fft/ft_grid_helpers.hpp\"\n\n\nenum class derivative_t\n{\n  dX,\n  dY\n};\n\ntemplate <typename DERIVED1, typename DERIVED2>\ndouble\ncompute_mass_entry(const Eigen::SparseMatrixBase<DERIVED1> &m1,\n                   const Eigen::SparseMatrixBase<DERIVED2> &m2)\n{\n  int n = std::max(m1.rows(), m2.rows());\n  int m = std::max(m1.cols(), m2.cols());\n\n  typedef Eigen::SparseMatrix<double, Eigen::RowMajor> sp_mat_t;\n  sp_mat_t b1, b2;\n  ftpad(b1, m1, n, m);\n  ftpad(b2, m2, n, m);\n\n  double sum = 0;\n\n  for (int ii = 0; ii < b1.outerSize(); ++ii) {\n    sp_mat_t::InnerIterator it2(b2, ii);\n    for (sp_mat_t::InnerIterator it1(b1, ii); it1; ++it1) {\n      while (it2.col() < it1.col()) ++it2;\n      if (!bool(it2))\n        break;\n      else if (it2.col() == it1.col())\n        sum += it2.value() * it1.value();\n      else\n        continue;\n    }\n  }\n  return sum;\n}\n\n/**\n * \\f$ computes ... \\f$\n *\n * @param m1\n * @param m2\n * @param tdx\n * @param tdy\n *\n * @return\n */\ntemplate <typename DERIVED1, typename DERIVED2>\ndouble\ncompute_mass_entry(const Eigen::SparseMatrixBase<DERIVED1> &m1,\n                   const Eigen::SparseMatrixBase<DERIVED2> &m2,\n                   double tdx,\n                   double tdy)\n{\n  const double PI = boost::math::constants::pi<double>();\n\n  int n = std::max(m1.rows(), m2.rows());\n  int m = std::max(m1.cols(), m2.cols());\n\n  typedef Eigen::SparseMatrix<double, Eigen::RowMajor> sp_mat_t;\n  sp_mat_t b1, b2;\n  ftpad(b1, m1, n, m);\n  ftpad(b2, m2, n, m);\n\n  double sum = 0;\n\n  for (int ii = 0; ii < b1.outerSize(); ++ii) {\n    int yhat = to_freq(ii, n);\n    sp_mat_t::InnerIterator it2(b2, ii);\n    for (sp_mat_t::InnerIterator it1(b1, ii); it1; ++it1) {\n      while (bool(it2) && it2.col() < it1.col()) ++it2;\n      if (!bool(it2))\n        break;\n      else if (it2.col() == it1.col()) {\n        int xhat = to_freq(it2.col(), m);\n        const double f = std::cos(2 * PI * (tdy * yhat + tdx * xhat));\n        sum += it2.value() * it1.value() * f;\n      }\n\n      else\n        continue;\n    }\n  }\n  return sum;\n}\n\n/**\n * \\f$ \\int_{L_x, L_y} \\partial_k r_{i1}(x) \\partial_l r_{i2}(x) \\mathrm{d}x \\f$\n *\n * @param m1 Fourier coefficients corresponding to r_{i1}\n * @param m2 Fourier coefficients corresponding to r_{i2}\n * @param tdx translation grid difference vector in x\n * @param tdy translation grid difference vector in y\n * @param dm1 derivative applied to \\f$r_{i1}\\f$\n * @param dm2 derivative applied to \\f$r_{i2}\\f$\n *\n * @return\n */\ntemplate <typename DERIVED1, typename DERIVED2>\ndouble\ncompute_tentry(const Eigen::SparseMatrixBase<DERIVED1> &m1,\n               const Eigen::SparseMatrixBase<DERIVED2> &m2,\n               double tdx,\n               double tdy,\n               derivative_t dm1,\n               derivative_t dm2,\n               double Lx = 1.0,\n               double Ly = 1.0)\n{\n  const double PI = boost::math::constants::pi<double>();\n  const double PI2 = PI * PI;\n\n  int n = std::max(m1.rows(), m2.rows());\n  int m = std::max(m1.cols(), m2.cols());\n\n  typedef Eigen::SparseMatrix<double, Eigen::RowMajor> sp_mat_t;\n  sp_mat_t b1, b2;\n  ftpad(b1, m1, n, m);\n  ftpad(b2, m2, n, m);\n\n  double sum = 0;\n  if (dm1 == derivative_t::dX && dm2 == derivative_t::dX) {\n    for (int ii = 0; ii < b1.outerSize(); ++ii) {\n      int yhat = to_freq(ii, n);\n      sp_mat_t::InnerIterator it2(b2, ii);\n      for (sp_mat_t::InnerIterator it1(b1, ii); it1; ++it1) {\n        while (bool(it2) && it2.col() < it1.col()) ++it2;\n        if (!bool(it2))\n          break;\n        else if (it2.col() == it1.col()) {\n          int xhat = to_freq(it2.col(), m);\n          const double f = std::cos(2 * PI * (tdy * yhat + tdx * xhat));\n          sum += xhat * xhat / (Lx * Lx) * it2.value() * it1.value() * f;\n        } else\n          continue;\n      }\n    }\n  } else if (dm1 == derivative_t::dY && dm2 == derivative_t::dY) {\n    for (int ii = 0; ii < b1.outerSize(); ++ii) {\n      int yhat = to_freq(ii, n);\n      sp_mat_t::InnerIterator it2(b2, ii);\n      for (sp_mat_t::InnerIterator it1(b1, ii); it1; ++it1) {\n        while (bool(it2) && it2.col() < it1.col()) ++it2;\n        if (!bool(it2))\n          break;\n        else if (it2.col() == it1.col()) {\n          int xhat = to_freq(it2.col(), m);\n          const double f = std::cos(2 * PI * (tdy * yhat + tdx * xhat));\n          sum += yhat * yhat / (Ly * Ly) * it2.value() * it1.value() * f;\n        } else\n          continue;\n      }\n    }\n  } else {\n    // dm1 == dY and dm2 == dX or vice versa\n    for (int ii = 0; ii < b1.outerSize(); ++ii) {\n      int yhat = to_freq(ii, n);\n      sp_mat_t::InnerIterator it2(b2, ii);\n      for (sp_mat_t::InnerIterator it1(b1, ii); it1; ++it1) {\n        while (bool(it2) && it2.col() < it1.col()) ++it2;\n        if (!bool(it2))\n          break;\n        else if (it2.col() == it1.col()) {\n          int xhat = to_freq(it2.col(), m);\n          const double f = std::cos(2 * PI * (tdy * yhat + tdx * xhat));\n          sum += xhat * yhat / (Lx * Ly) * it2.value() * it1.value() * f;\n        } else\n          continue;\n      }\n    }\n  }\n\n  return 4 * PI2 * sum;\n}\n", "meta": {"hexsha": "4763825eaf04b7cf2ee7538c3af855b6212b3fef", "size": 5143, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "matrices/matrix_entries.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": "matrices/matrix_entries.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": "matrices/matrix_entries.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.4143646409, "max_line_length": 80, "alphanum_fraction": 0.5440404433, "num_tokens": 1683, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.45906970067394215}}
{"text": "// Copyright (c) 2019 fortiss GmbH, Julian Bernhard, Klemens Esterle, Patrick Hart, Tobias Kessler\n//\n// This work is licensed under the terms of the MIT license.\n// For a copy, see <https://opensource.org/licenses/MIT>.\n\n\n#ifndef MODULES_GEOMETRY_POLYGON_HPP_\n#define MODULES_GEOMETRY_POLYGON_HPP_\n\n#include <vector>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/geometries.hpp>\n#include \"commons.hpp\"\n#include \"modules/geometry/line.hpp\"\n\nnamespace modules {\nnamespace geometry {\n\n//! templated polygon class with a boost polygon as a member function\ntemplate <typename T>\nstruct Polygon_t : public Shape<bg::model::polygon<T>, T> {\n  Polygon_t() : Shape<bg::model::polygon<T>, T>(Pose(0, 0, 0),\n    std::vector<T>(), 0) {}\n  Polygon_t(const Pose &center, const std::vector<T>& points) :\n    Shape<bg::model::polygon<T>, T>(center, points, 0) {}\n\n  Polygon_t(\n      const Pose &center,\n      const Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> &points) : Shape<bg::model::polygon<T>, T>(center, points, 0) {}\n\n  virtual Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> toArray() const;\n\n  virtual Shape<bg::model::polygon<T>, T> *Clone() const;\n\n};\n\ntemplate <typename T>\ninline Shape<bg::model::polygon<T>, T> *Polygon_t<T>::Clone() const {\n  return new Polygon_t<T>(*this);\n}\n\n//! for better usage simple float defines\nusing PolygonPoint = Point2d;  // for internal stores of collision checkers\nusing Polygon = Polygon_t<PolygonPoint>;\n\ntemplate <>\ninline Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> Polygon::toArray() const {\n  std::vector<Point2d> points = obj_.outer();\n  Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> mat(points.size(), 2);\n  for (std::vector<Point2d>::size_type i = 0; i < points.size(); ++i) {\n    mat.row(i) << bg::get<0>(points[i]), bg::get<1>(points[i]);\n  }\n  return mat;\n}\n\ninline bool equals(const Polygon &poly1, const Polygon &poly2) {\n  return bg::equals(poly1.obj_, poly2.obj_);\n}\n\ninline float distance(const Polygon &poly, const Point2d &p) {\n  return bg::distance(poly.obj_, p);\n}\n\ninline float distance(const Polygon &poly, const Line &l) {\n  return bg::distance(poly.obj_, l.obj_);\n}\n\ninline float distance(const Polygon &poly1, const Polygon &poly2) {\n  return bg::distance(poly1.obj_, poly2.obj_);\n}\n\n//! Polygon - Point collision checker using boost::within\ninline bool Collide(const Polygon &poly, const PolygonPoint &p) {\n  return bg::within(p, poly.obj_);\n}\n\n//! Point - Polygon collision checker using boost::within\ninline bool Collide(const PolygonPoint &p, const Polygon &poly) {\n  return Collide(poly, p);\n}\n\n//! Polygon - Line collision checker using boost::intersection\n//! @note we only check the shape intersection(s) and no line RHS/LHS line crossing!\ninline bool Collide(const Polygon &poly, const Line &l) {\n  std::vector<bg::model::linestring<LinePoint>> shape_intersect;\n  bg::intersection(poly.obj_, l.obj_, shape_intersect);\n  const bool inner_intersection = !shape_intersect.empty();\n  if (inner_intersection) {\n    return inner_intersection;\n  } else {\n    // boost interection does not treat edge intersections as intersection1,\n    // but this shall be a collision! -> cast poly edge to line and re-check collision.\n    Line outer_polyline;\n    //! @todo geht das eleganter?\n    for (auto it = boost::begin(boost::geometry::exterior_ring(poly.obj_)); it != boost::end(boost::geometry::exterior_ring(poly.obj_)); ++it) {\n      outer_polyline.add_point(*it);\n    }\n    return Collide(outer_polyline, l);\n  }\n}\n\n//! Line - Polygon collision checker using boost::intersection\ninline bool Collide(const Line &line, const Polygon &poly) {\n  return Collide(poly, line);\n}\n\n//! Polygon - Polygon collision checker using boost::intersection\n//! @todo might not be very efficient without Strategy...\ninline bool Collide(const Polygon &poly1, const Polygon &poly2) {\n  std::vector<bg::model::polygon<PolygonPoint>> shape_intersect;\n  bg::intersection(poly1.obj_, poly2.obj_, shape_intersect);\n  const bool inner_intersection = !shape_intersect.empty();\n  if (inner_intersection) {\n    return inner_intersection;\n  } else {\n    // boost interection does not treat edge intersections as intersection,\n    // but this shall be a collision! -> cast poly edge to line and re-check collision.\n    Line outer_polyline1;\n    Line outer_polyline2;\n    //! @todo geht das eleganter?\n    for (auto it = boost::begin(boost::geometry::exterior_ring(poly1.obj_)); it != boost::end(boost::geometry::exterior_ring(poly1.obj_)); ++it) {\n      outer_polyline1.add_point(*it);\n    }\n    for (auto it = boost::begin(boost::geometry::exterior_ring(poly2.obj_)); it != boost::end(boost::geometry::exterior_ring(poly2.obj_)); ++it) {\n      outer_polyline2.add_point(*it);\n    }\n    return Collide(outer_polyline1, outer_polyline2);\n  }\n}\n\n}  // namespace geometry\n}  // namespace modules\n\n#endif  // MODULES_GEOMETRY_POLYGON_HPP_\n", "meta": {"hexsha": "72c9b590ee7971dcbc59ad5fd2aeb1fb3ef08ec7", "size": 4910, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/geometry/polygon.hpp", "max_stars_repo_name": "grzPat/bark", "max_stars_repo_head_hexsha": "807092815c81eeb23defff473449a535a9c42f8b", "max_stars_repo_licenses": ["MIT"], "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/geometry/polygon.hpp", "max_issues_repo_name": "grzPat/bark", "max_issues_repo_head_hexsha": "807092815c81eeb23defff473449a535a9c42f8b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/geometry/polygon.hpp", "max_forks_repo_name": "grzPat/bark", "max_forks_repo_head_hexsha": "807092815c81eeb23defff473449a535a9c42f8b", "max_forks_repo_licenses": ["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.1029411765, "max_line_length": 146, "alphanum_fraction": 0.7101832994, "num_tokens": 1244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4590697006739421}}
{"text": "/*\r\nCopyright 2010 Intel Corporation\r\n\r\nUse, modification and distribution are subject to the Boost Software License,\r\nVersion 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\nhttp://www.boost.org/LICENSE_1_0.txt).\r\n*/\r\n#include <iostream>\r\n#include <boost/polygon/polygon.hpp>\r\n\r\ntypedef boost::polygon::point_data<int> point;\r\ntypedef boost::polygon::polygon_set_data<int> polygon_set;\r\ntypedef boost::polygon::polygon_with_holes_data<int> polygon;\r\ntypedef std::pair<point, point> edge;\r\nusing namespace boost::polygon::operators;\r\n\r\nvoid convolve_two_segments(std::vector<point>& figure, const edge& a, const edge& b) {\r\n  using namespace boost::polygon;\r\n  figure.clear();\r\n  figure.push_back(point(a.first));\r\n  figure.push_back(point(a.first));\r\n  figure.push_back(point(a.second));\r\n  figure.push_back(point(a.second));\r\n  convolve(figure[0], b.second);\r\n  convolve(figure[1], b.first);\r\n  convolve(figure[2], b.first);\r\n  convolve(figure[3], b.second);\r\n}\r\n\r\ntemplate <typename itrT1, typename itrT2>\r\nvoid convolve_two_point_sequences(polygon_set& result, itrT1 ab, itrT1 ae, itrT2 bb, itrT2 be) {\r\n  using namespace boost::polygon;\r\n  if(ab == ae || bb == be)\r\n    return;\r\n  point first_a = *ab;\r\n  point prev_a = *ab;\r\n  std::vector<point> vec;\r\n  polygon poly;\r\n  ++ab;\r\n  for( ; ab != ae; ++ab) {\r\n    point first_b = *bb;\r\n    point prev_b = *bb;\r\n    itrT2 tmpb = bb;\r\n    ++tmpb;\r\n    for( ; tmpb != be; ++tmpb) {\r\n      convolve_two_segments(vec, std::make_pair(prev_b, *tmpb), std::make_pair(prev_a, *ab));\r\n      set_points(poly, vec.begin(), vec.end());\r\n      result.insert(poly);\r\n      prev_b = *tmpb;\r\n    }\r\n    prev_a = *ab;\r\n  }\r\n}\r\n\r\ntemplate <typename itrT>\r\nvoid convolve_point_sequence_with_polygons(polygon_set& result, itrT b, itrT e, const std::vector<polygon>& polygons) {\r\n  using namespace boost::polygon;\r\n  for(std::size_t i = 0; i < polygons.size(); ++i) {\r\n    convolve_two_point_sequences(result, b, e, begin_points(polygons[i]), end_points(polygons[i]));\r\n    for(polygon_with_holes_traits<polygon>::iterator_holes_type itrh = begin_holes(polygons[i]);\r\n        itrh != end_holes(polygons[i]); ++itrh) {\r\n      convolve_two_point_sequences(result, b, e, begin_points(*itrh), end_points(*itrh));\r\n    }\r\n  }\r\n}\r\n\r\nvoid convolve_two_polygon_sets(polygon_set& result, const polygon_set& a, const polygon_set& b) {\r\n  using namespace boost::polygon;\r\n  result.clear();\r\n  std::vector<polygon> a_polygons;\r\n  std::vector<polygon> b_polygons;\r\n  a.get(a_polygons);\r\n  b.get(b_polygons);\r\n  for(std::size_t ai = 0; ai < a_polygons.size(); ++ai) {\r\n    convolve_point_sequence_with_polygons(result, begin_points(a_polygons[ai]), \r\n                                          end_points(a_polygons[ai]), b_polygons);\r\n    for(polygon_with_holes_traits<polygon>::iterator_holes_type itrh = begin_holes(a_polygons[ai]);\r\n        itrh != end_holes(a_polygons[ai]); ++itrh) {\r\n      convolve_point_sequence_with_polygons(result, begin_points(*itrh), \r\n                                            end_points(*itrh), b_polygons);\r\n    }\r\n    for(std::size_t bi = 0; bi < b_polygons.size(); ++bi) {\r\n      polygon tmp_poly = a_polygons[ai];\r\n      result.insert(convolve(tmp_poly, *(begin_points(b_polygons[bi]))));\r\n      tmp_poly = b_polygons[bi];\r\n      result.insert(convolve(tmp_poly, *(begin_points(a_polygons[ai]))));\r\n    }\r\n  }\r\n}\r\n\r\nnamespace boost { namespace polygon{\r\n\r\n  template <typename T>\r\n  std::ostream& operator<<(std::ostream& o, const polygon_data<T>& poly) {\r\n    o << \"Polygon { \";\r\n    for(typename polygon_data<T>::iterator_type itr = poly.begin(); \r\n        itr != poly.end(); ++itr) {\r\n      if(itr != poly.begin()) o << \", \";\r\n      o << (*itr).get(HORIZONTAL) << \" \" << (*itr).get(VERTICAL);\r\n    } \r\n    o << \" } \";\r\n    return o;\r\n  } \r\n\r\n  template <typename T>\r\n  std::ostream& operator<<(std::ostream& o, const polygon_with_holes_data<T>& poly) {\r\n    o << \"Polygon With Holes { \";\r\n    for(typename polygon_with_holes_data<T>::iterator_type itr = poly.begin(); \r\n        itr != poly.end(); ++itr) {\r\n      if(itr != poly.begin()) o << \", \";\r\n      o << (*itr).get(HORIZONTAL) << \" \" << (*itr).get(VERTICAL);\r\n    } o << \" { \";\r\n    for(typename polygon_with_holes_data<T>::iterator_holes_type itr = poly.begin_holes();\r\n        itr != poly.end_holes(); ++itr) {\r\n      o << (*itr);\r\n    }\r\n    o << \" } } \";\r\n    return o;\r\n  }\r\n}}\r\n\r\nint main(int argc, char **argv) {\r\n  polygon_set a, b, c;\r\n  a += boost::polygon::rectangle_data<int>(0, 0, 1000, 1000);\r\n  a -= boost::polygon::rectangle_data<int>(100, 100, 900, 900);\r\n  a += boost::polygon::rectangle_data<int>(1000, -1000, 1010, -990);\r\n  std::vector<polygon> polys;\r\n  std::vector<point> pts;\r\n  pts.push_back(point(-40, 0));\r\n  pts.push_back(point(-10, 10));\r\n  pts.push_back(point(0, 40));\r\n  pts.push_back(point(10, 10));\r\n  pts.push_back(point(40, 0));\r\n  pts.push_back(point(10, -10));\r\n  pts.push_back(point(0, -40));\r\n  pts.push_back(point(-10, -10));\r\n  pts.push_back(point(-40, 0));\r\n  polygon poly;\r\n  boost::polygon::set_points(poly, pts.begin(), pts.end());\r\n  b+=poly;\r\n  pts.clear();\r\n  pts.push_back(point(1040, 1040));\r\n  pts.push_back(point(1050, 1045));\r\n  pts.push_back(point(1045, 1050));\r\n  boost::polygon::set_points(poly, pts.begin(), pts.end());\r\n  b+=poly;\r\n  polys.clear();\r\n  convolve_two_polygon_sets(c, a, b);\r\n  c.get(polys);\r\n  for(int i = 0; i < polys.size(); ++i ){\r\n    std::cout << polys[i] << std::endl;\r\n  }\r\n  return 0;\r\n}\r\n", "meta": {"hexsha": "400d7575098240a171e29c1653f80907ecc5ea5f", "size": 5489, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/polygon/doc/tutorial/minkowski.cpp", "max_stars_repo_name": "zyiacas/boost-doc-zh", "max_stars_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 198.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T05:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:46:46.000Z", "max_issues_repo_path": "libs/polygon/doc/tutorial/minkowski.cpp", "max_issues_repo_name": "sdfict/boost-doc-zh", "max_issues_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/polygon/doc/tutorial/minkowski.cpp", "max_forks_repo_name": "sdfict/boost-doc-zh", "max_forks_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 35.4129032258, "max_line_length": 120, "alphanum_fraction": 0.6267079614, "num_tokens": 1530, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4590696945059379}}
{"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_POW_ABS_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_POW_ABS_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n    @ingroup group-exponential\n    This function object computes \\f$|x|^y\\f$.\n\n    @par Header <boost/simd/function/pow_abs.hpp>\n\n    @par Decorators\n\n    - raw_  is faster but can be inaccurate.\n\n    @see pow, abs\n\n\n    @par Example:\n\n      @snippet pow_abs.cpp pow_abs\n\n    @par Possible output:\n\n      @snippet pow_abs.txt pow_abs\n\n  **/\n  IEEEValue pow_abs(IEEEValue const& x, IEEEValue const& y);\n} }\n#endif\n\n#include <boost/simd/function/scalar/pow_abs.hpp>\n#include <boost/simd/function/simd/pow_abs.hpp>\n\n#endif\n", "meta": {"hexsha": "751bc310e449920dbcc4b0650d7f7e2581e59d55", "size": 1081, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/pow_abs.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/pow_abs.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/pow_abs.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.5208333333, "max_line_length": 100, "alphanum_fraction": 0.5809435708, "num_tokens": 238, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4590696945059379}}
{"text": "#include <iostream>\n#include <cassert>\n#include <vector>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/push_relabel_max_flow.hpp>\n#include <boost/graph/successive_shortest_path_nonnegative_weights.hpp>\n#include <boost/graph/find_flow_cost.hpp>\n\ntypedef boost::adjacency_list_traits<boost::vecS, boost::vecS, boost::directedS> GraphTraits;\ntypedef boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS, boost::no_property,\n                              boost::property<boost::edge_capacity_t, long,\n                                              boost::property<boost::edge_residual_capacity_t, long,\n                                                              boost::property<boost::edge_reverse_t, GraphTraits::edge_descriptor,\n                                                                              boost::property<boost::edge_weight_t, long>>>>>\n    Graph;\n\nconst int max_possible_bid = 100;\n\nconst int debug_level = 0;\n\n#define DEBUG(min_level, x)      \\\n  if (debug_level >= min_level)  \\\n  {                              \\\n    std::cerr << x << std::endl; \\\n  }\n\nclass EdgeAdder\n{\n  Graph &G;\n\npublic:\n  explicit EdgeAdder(Graph &G) : G(G) {}\n  void add_edge(int from, int to, long capacity, long cost)\n  {\n    auto c_map = boost::get(boost::edge_capacity, G);\n    auto r_map = boost::get(boost::edge_reverse, G);\n    auto w_map = boost::get(boost::edge_weight, G);\n    const Graph::edge_descriptor e = boost::add_edge(from, to, G).first;\n    const Graph::edge_descriptor rev_e = boost::add_edge(to, from, G).first;\n    c_map[e] = capacity;\n    c_map[rev_e] = 0; // reverse edge has no capacity!\n    r_map[e] = rev_e;\n    r_map[rev_e] = e;\n    w_map[e] = cost;\n    w_map[rev_e] = -cost;\n  }\n};\n\nvoid testcase()\n{\n  int n, m, s;\n  std::cin >> n >> m >> s;\n  assert(n >= 1 && n <= 100 && m >= 1 && m <= 100 && s >= 1 && s <= m);\n\n  std::vector<int> limits_by_state(s);\n  for (int &limit : limits_by_state)\n  {\n    std::cin >> limit;\n    assert(limit >= 0 && limit <= n);\n  }\n\n  std::vector<int> state_by_site(m);\n  for (int &state : state_by_site)\n  {\n    std::cin >> state;\n    assert(state >= 1 && state <= s);\n    state--;\n  }\n\n  std::vector<std::vector<int>> bids_by_buyer(n, std::vector<int>(m));\n  for (std::vector<int> &bids : bids_by_buyer)\n  {\n    for (int &bid : bids)\n    {\n      std::cin >> bid;\n      assert(bid >= 1 && bid <= max_possible_bid);\n    }\n  }\n\n  int next_free_node = 0;\n  const int node_source = next_free_node++;\n  const int node_sink = next_free_node++;\n  const auto get_node_for_buyer = [next_free_node, n](int buyer) {\n    assert(buyer >= 0 && buyer < n);\n    return next_free_node + buyer;\n  };\n  next_free_node += n;\n  const auto get_node_for_site = [next_free_node, m](int site) {\n    assert(site >= 0 && site < m);\n    return next_free_node + site;\n  };\n  next_free_node += m;\n  const auto get_node_for_state = [next_free_node, s](int state) {\n    assert(state >= 0 && state < s);\n    return next_free_node + state;\n  };\n  next_free_node += s;\n  const int num_nodes = next_free_node;\n\n  Graph G(num_nodes);\n  EdgeAdder adder(G);\n\n  for (int i = 0; i < n; i++)\n  {\n    adder.add_edge(node_source, get_node_for_buyer(i), 1, 0);\n    for (int j = 0; j < m; j++)\n    {\n      const int bid = bids_by_buyer.at(i).at(j);\n      adder.add_edge(get_node_for_buyer(i), get_node_for_site(j), 1, -bid + max_possible_bid);\n    }\n  }\n\n  for (int i = 0; i < m; i++)\n  {\n    adder.add_edge(get_node_for_site(i), get_node_for_state(state_by_site.at(i)), 1, 0);\n  }\n\n  for (int i = 0; i < s; i++)\n  {\n    adder.add_edge(get_node_for_state(i), node_sink, limits_by_state.at(i), 0);\n  }\n\n  const int flow = boost::push_relabel_max_flow(G, node_source, node_sink);\n  assert(flow >= std::min(s, std::min(n, m)) && flow <= std::min(n, m));\n  boost::successive_shortest_path_nonnegative_weights(G, node_source, node_sink);\n  const int profit = -(boost::find_flow_cost(G) - max_possible_bid * flow);\n  assert(profit > 0);\n  std::cout << flow << \" \" << profit << \"\\n\";\n}\n\nint main()\n{\n  std::ios_base::sync_with_stdio(false);\n\n  int t;\n  std::cin >> t;\n  for (int i = 0; i < t; i++)\n  {\n    testcase();\n  }\n\n  return 0;\n}", "meta": {"hexsha": "c01acd59159ddb814133cd961466aefbe9075508", "size": 4167, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "week-09/real-estate-market/src/main.cpp", "max_stars_repo_name": "tehwalris/algolab", "max_stars_repo_head_hexsha": "489e0f6dd137336fa32b8002fc6eed8a7d35d87a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-17T08:21:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-17T08:21:32.000Z", "max_issues_repo_path": "week-09/real-estate-market/src/main.cpp", "max_issues_repo_name": "tehwalris/algolab", "max_issues_repo_head_hexsha": "489e0f6dd137336fa32b8002fc6eed8a7d35d87a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "week-09/real-estate-market/src/main.cpp", "max_forks_repo_name": "tehwalris/algolab", "max_forks_repo_head_hexsha": "489e0f6dd137336fa32b8002fc6eed8a7d35d87a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.1398601399, "max_line_length": 130, "alphanum_fraction": 0.6006719462, "num_tokens": 1193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.5926665999540697, "lm_q1q2_score": 0.45906969450593776}}
{"text": "/*\n * InnerMapTask.cpp\n *\n *  Created on: 25 Jul 2018\n *      Author: scsjd\n */\n\n#include <fstream>\n#include <sstream>\n#include <iterator>\n#include <chrono>\n#include <NTL/ZZ.h>\n#include <NTL/ZZ_p.h>\n#include <NTL/vec_ZZ.h>\n#include <jsoncpp/json/json.h>\n#include \"InnerMapTask.h\"\n#include \"HE1CiphertextCPU.h\"\n\nInnerMapTask::InnerMapTask(int numPerLine, const char* parametersPath, const char* inputPath){\n\tthis->inputPath = inputPath;\n\tthis->numPerLine = numPerLine;\n\tparseParameters(parametersPath);\n\ttotalSumTime=0;\n\tnumberAdditions=0;\n\ttotalProductTime=0;\n\tnumberMultiplications=0;\n}\n\nInnerMapTask::~InnerMapTask(){\n}\n\nvoid InnerMapTask::parseParameters(const char* parametersPath){\n\tNTL::ZZ mod;\n\tstd::ifstream ifs(parametersPath);\n\tif (ifs.is_open()){\n\t\tstd::string json;\n\t\tgetline(ifs,json);\n\t\tJson::Value root;   // will contains the root value after parsing.\n\t\tJson::Reader reader;\n\t\tbool parsingSuccessful = reader.parse(json,root);\n\t\tif (parsingSuccessful){\n\t\t\tmodulus = NTL::conv<NTL::ZZ>(root[\"modulus\"].asCString());\n\t\t}\n\t}\n}\n\nNTL::ZZ InnerMapTask::run(){\n\tstd::ifstream ifs(inputPath);\n\tif (!ifs.is_open()){\n\t\tthrow std::ios_base::failure(\"Could not open input file.\");\n\t}\n\tstd::string line;\n\n\tHE1CiphertextCPU::setModulus(modulus);\n\tNTL::ZZ zero;\n\tHE1CiphertextCPU sum(zero);\n\n\twhile(getline(ifs,line)){\n\t\tNTL::ZZ one;\n\t\tset(one);\n\t\tHE1CiphertextCPU prod(one);\n\t\tstd::istringstream iss(line);\n\t\tstd::vector<std::string> words((std::istream_iterator<std::string>(iss)),std::istream_iterator<std::string>());\n\t\tfor(int i = 0; i < words.size(); i++){\n\t\t\tNTL::ZZ z = NTL::conv<NTL::ZZ>(words[i].c_str());\n\t\t\tHE1CiphertextCPU tmp(z);\n\t\t\tauto start = std::chrono::high_resolution_clock::now();\n\t\t\tprod*=tmp;\n\t\t\tauto finish = std::chrono::high_resolution_clock::now();\n\t\t\ttotalProductTime += std::chrono::duration_cast<std::chrono::nanoseconds>(finish-start).count();\n\t\t\tnumberMultiplications++;\n\t\t}\n\t\tauto start = std::chrono::high_resolution_clock::now();\n\t\tsum+=prod;\n\t\tauto finish = std::chrono::high_resolution_clock::now();\n\t\ttotalSumTime += std::chrono::duration_cast<std::chrono::nanoseconds>(finish-start).count();\n\t\tnumberAdditions++;\n\t}\n\tifs.close();\n\n\treturn NTL::rep(sum.get_ciphertext());\n};\n\n\n", "meta": {"hexsha": "2f416b0df9b5dd1f9cf69359ae1ea8d2133d3361", "size": 2217, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/inner_product/inner/src/worker/InnerMapTask.cpp", "max_stars_repo_name": "TANGO-Project/cryptango", "max_stars_repo_head_hexsha": "be6a2d74d238bffd3f3e899ea0eea01966097ebe", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/inner_product/inner/src/worker/InnerMapTask.cpp", "max_issues_repo_name": "TANGO-Project/cryptango", "max_issues_repo_head_hexsha": "be6a2d74d238bffd3f3e899ea0eea01966097ebe", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/inner_product/inner/src/worker/InnerMapTask.cpp", "max_forks_repo_name": "TANGO-Project/cryptango", "max_forks_repo_head_hexsha": "be6a2d74d238bffd3f3e899ea0eea01966097ebe", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.0823529412, "max_line_length": 113, "alphanum_fraction": 0.701849346, "num_tokens": 621, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891218080991, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.4590503811543571}}
{"text": "//\n// Copyright \u00a9 2017 Arm Ltd. All rights reserved.\n// See LICENSE file in the project root for full license information.\n//\n#include \"InferenceTestImage.hpp\"\n#include \"MobileNetDatabase.hpp\"\n\n#include <boost/numeric/conversion/cast.hpp>\n#include <boost/assert.hpp>\n#include <boost/format.hpp>\n\n#include <iostream>\n#include <fcntl.h>\n#include <array>\n\nnamespace\n{\n\ninline float Lerp(float a, float b, float w)\n{\n    return w * b + (1.f - w) * a;\n}\n\ninline void PutData(std::vector<float> & data,\n                    const unsigned int width,\n                    const unsigned int x,\n                    const unsigned int y,\n                    const unsigned int c,\n                    float value)\n{\n    data[(3*((y*width)+x)) + c] = value;\n}\n\nstd::vector<float>\nResizeBilinearAndNormalize(const InferenceTestImage & image,\n                           const unsigned int outputWidth,\n                           const unsigned int outputHeight)\n{\n    std::vector<float> out;\n    out.resize(outputWidth * outputHeight * 3);\n\n    // We follow the definition of TensorFlow and AndroidNN: The top-left corner of a texel in the output\n    // image is projected into the input image to figure out the interpolants and weights. Note that this\n    // will yield different results than if projecting the centre of output texels.\n\n    const unsigned int inputWidth = image.GetWidth();\n    const unsigned int inputHeight = image.GetHeight();\n\n    // How much to scale pixel coordinates in the output image to get the corresponding pixel coordinates\n    // in the input image\n    const float scaleY = boost::numeric_cast<float>(inputHeight) / boost::numeric_cast<float>(outputHeight);\n    const float scaleX = boost::numeric_cast<float>(inputWidth) / boost::numeric_cast<float>(outputWidth);\n\n    uint8_t rgb_x0y0[3];\n    uint8_t rgb_x1y0[3];\n    uint8_t rgb_x0y1[3];\n    uint8_t rgb_x1y1[3];\n\n    for (unsigned int y = 0; y < outputHeight; ++y)\n    {\n        // Corresponding real-valued height coordinate in input image\n        const float iy = boost::numeric_cast<float>(y) * scaleY;\n\n        // Discrete height coordinate of top-left texel (in the 2x2 texel area used for interpolation)\n        const float fiy = floorf(iy);\n        const unsigned int y0 = boost::numeric_cast<unsigned int>(fiy);\n\n        // Interpolation weight (range [0,1])\n        const float yw = iy - fiy;\n\n        for (unsigned int x = 0; x < outputWidth; ++x)\n        {\n            // Real-valued and discrete width coordinates in input image\n            const float ix = boost::numeric_cast<float>(x) * scaleX;\n            const float fix = floorf(ix);\n            const unsigned int x0 = boost::numeric_cast<unsigned int>(fix);\n\n            // Interpolation weight (range [0,1])\n            const float xw = ix - fix;\n\n            // Discrete width/height coordinates of texels below and to the right of (x0, y0)\n            const unsigned int x1 = std::min(x0 + 1, inputWidth - 1u);\n            const unsigned int y1 = std::min(y0 + 1, inputHeight - 1u);\n\n            std::tie(rgb_x0y0[0], rgb_x0y0[1], rgb_x0y0[2]) = image.GetPixelAs3Channels(x0, y0);\n            std::tie(rgb_x1y0[0], rgb_x1y0[1], rgb_x1y0[2]) = image.GetPixelAs3Channels(x1, y0);\n            std::tie(rgb_x0y1[0], rgb_x0y1[1], rgb_x0y1[2]) = image.GetPixelAs3Channels(x0, y1);\n            std::tie(rgb_x1y1[0], rgb_x1y1[1], rgb_x1y1[2]) = image.GetPixelAs3Channels(x1, y1);\n\n            for (unsigned c=0; c<3; ++c)\n            {\n                const float ly0 = Lerp(float(rgb_x0y0[c]), float(rgb_x1y0[c]), xw);\n                const float ly1 = Lerp(float(rgb_x0y1[c]), float(rgb_x1y1[c]), xw);\n                const float l = Lerp(ly0, ly1, yw);\n                PutData(out, outputWidth, x, y, c, l/255.0f);\n            }\n        }\n    }\n\n    return out;\n}\n\n} // end of anonymous namespace\n\n\nMobileNetDatabase::MobileNetDatabase(const std::string& binaryFileDirectory,\n                                     unsigned int width,\n                                     unsigned int height,\n                                     const std::vector<ImageSet>& imageSet)\n:   m_BinaryDirectory(binaryFileDirectory)\n,   m_Height(height)\n,   m_Width(width)\n,   m_ImageSet(imageSet)\n{\n}\n\nstd::unique_ptr<MobileNetDatabase::TTestCaseData>\nMobileNetDatabase::GetTestCaseData(unsigned int testCaseId)\n{\n    testCaseId = testCaseId % boost::numeric_cast<unsigned int>(m_ImageSet.size());\n    const ImageSet& imageSet = m_ImageSet[testCaseId];\n    const std::string fullPath = m_BinaryDirectory + imageSet.first;\n\n    InferenceTestImage image(fullPath.c_str());\n\n    // this ResizeBilinear result is closer to the tensorflow one than STB.\n    // there is still some difference though, but the inference results are\n    // similar to tensorflow for MobileNet\n    std::vector<float> resized(ResizeBilinearAndNormalize(image, m_Width, m_Height));\n\n    const unsigned int label = imageSet.second;\n    return std::make_unique<TTestCaseData>(label, std::move(resized));\n}\n", "meta": {"hexsha": "66f297c502b00dc6faacbfe094c9821721caf43f", "size": 4992, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/MobileNetDatabase.cpp", "max_stars_repo_name": "Air000/armnn_s32v", "max_stars_repo_head_hexsha": "ec3ee60825d6b7642a70987c4911944cef7a3ee6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-03-19T08:44:28.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-19T08:44:28.000Z", "max_issues_repo_path": "tests/MobileNetDatabase.cpp", "max_issues_repo_name": "Air000/armnn_s32v", "max_issues_repo_head_hexsha": "ec3ee60825d6b7642a70987c4911944cef7a3ee6", "max_issues_repo_licenses": ["MIT"], "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/MobileNetDatabase.cpp", "max_forks_repo_name": "Air000/armnn_s32v", "max_forks_repo_head_hexsha": "ec3ee60825d6b7642a70987c4911944cef7a3ee6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-10-11T05:58:56.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-11T05:58:56.000Z", "avg_line_length": 37.2537313433, "max_line_length": 108, "alphanum_fraction": 0.6360176282, "num_tokens": 1258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189121808099, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.459050381154357}}
{"text": "// Petter Strandmark 2013.\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\n#include <spii/spii.h>\n#include <spii/solver.h>\n\n#ifndef USE_SYM_ILDL\n\nvoid spii::Solver::BKP_sym_ildl(const Eigen::MatrixXd& Hinput,\n                                const Eigen::VectorXd& g,\n                                Eigen::VectorXd* p,\n                                SolverResults* results) const\n{\n\tthrow std::runtime_error(\"sym-ildl is not available.\");\n}\n\nvoid spii::Solver::BKP_sym_ildl(const Eigen::SparseMatrix<double>& Hinput,\n                                const Eigen::VectorXd& g,\n                                Eigen::VectorXd* p,\n                                SolverResults* results) const\n{\n\tthrow std::runtime_error(\"sym-ildl is not available.\");\n}\n\n#else\n\n#include <lilc_matrix.h>\n\n#include <spii/sym-ildl-conversions.h>\n\nnamespace spii {\n\nnamespace{\nvoid modify_block_diagonal_matrix(block_diag_matrix<double>* B)\n{\n\tusing namespace Eigen;\n\n\tauto n = B->n_rows();\n\tspii_assert(B->n_cols() == n);\n\n\t//\n\t// Modify the block diagonalization.\n\t//\n\tconst double delta = 1e-12;\n\n\tVectorXd tau(n);\n\tVectorXd lambda(n);\n\n\tSelfAdjointEigenSolver<MatrixXd> eigensolver;\n\n\tbool onebyone;\n\tfor (int i = 0; i < n; i = (onebyone ? i+1 : i+2) ) {\n\t\tonebyone = (i == n-1 || B->block_size(i) == 1);\n\n\t\tif ( onebyone ) {\n\t\t\tauto& Bii = (*B)[i];\n\n\t\t\tdouble lambda = Bii;\n\t\t\tdouble tau;\n\t\t\tif (lambda >= delta) {\n\t\t\t\ttau = 0;\n\t\t\t}\n\t\t\telse {\n\t\t\t\ttau = delta - (1.0 + delta) * lambda;\n\t\t\t}\n\t\t\t//Q(i, i) = 1;\n\t\t\tBii = Bii + tau;\n\t\t}\n\t\telse {\n\t\t\tMatrix2d Bblock;\n\t\t\tBblock(0, 0) = (*B)[i];\n\t\t\tBblock(0, 1) = B->off_diagonal(i);\n\t\t\tBblock(1, 0) = B->off_diagonal(i);\n\t\t\tBblock(1, 1) = (*B)[i+1];\n\t\t\tspii_assert(Bblock(1, 0) == Bblock(0, 1));\n\n\t\t\teigensolver.compute(Bblock);\n\t\t\tVector2d lambda;\n\t\t\tlambda(0) = eigensolver.eigenvalues()(0);\n\t\t\tlambda(1) = eigensolver.eigenvalues()(1);\n\n\t\t\tVector2d tau;\n\t\t\tfor (int k = 0; k < 2; ++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\tMatrix2d Qblock = eigensolver.eigenvectors();\n\t\t\tBblock = Bblock + Qblock * tau.asDiagonal() * Qblock.transpose();\n\t\t\t(*B)[i]            = Bblock(0, 0);\n\t\t\tB->off_diagonal(i) = Bblock(0, 1);\n\t\t\t(*B)[i+1]          = Bblock(1, 1);\n\t\t}\n\t}\n}\n} // anon. namespace\n\n\ntemplate<typename MatrixType>\nvoid BKP_sym_ildl_generic(const MatrixType& Hinput,\n                          const Eigen::VectorXd& g,\n                          Eigen::VectorXd* p,\n                          SolverResults* results)\n{\n\tusing namespace std;\n\tusing namespace Eigen;\n\tdouble start_time = wall_time();\n\n\t//\n\t// Create sym-ildl matrix.\n\t//\n\tlilc_matrix<double> Hlilc;\n\teigen_to_lilc(Hinput, &Hlilc);\n\n\t//\n\t// Factorize the matrix.\n\t//\n\tlilc_matrix<double> L;\t          // The lower triangular factor of A.\n\tvector<int> perm;\t                  // A permutation vector containing all permutations on A.\n\tperm.reserve(Hlilc.n_cols());\n\tblock_diag_matrix<double> B; // The diagonal factor of A.\n\n\tHlilc.sym_amd(perm);\n\tHlilc.sym_perm(perm);\n\n\tconst double fill_factor = 1.0;\n\tconst double tol         = 1e-12;\n\tconst double pp_tol      = 1.0; // For full Bunch-Kaufman.\n\tHlilc.ildl(L, B, perm, fill_factor, tol, pp_tol);\n\n\t// Convert back to Eigen matrices.\n\tMyPermutation P(perm);\n\tauto S = diag_to_eigen(Hlilc.S);\n\n\t//\n\t// Modify the block diagonalization.\n\t//\n\tmodify_block_diagonal_matrix(&B);\n\n\tresults->matrix_factorization_time += wall_time() - start_time;\n\t//\n\t// Solve the system.\n\t//\n\tstart_time = wall_time();\n\n\tsolve_system_ildl(B, L, S, P, -g, p);\n\n\tresults->linear_solver_time += wall_time() - start_time;\n}\n\nvoid Solver::BKP_sym_ildl(const Eigen::MatrixXd& Hinput,\n                          const Eigen::VectorXd& g,\n                          Eigen::VectorXd* p,\n                          SolverResults* results) const\n{\n\tBKP_sym_ildl_generic(Hinput, g, p, results);\n}\n\nvoid Solver::BKP_sym_ildl(const Eigen::SparseMatrix<double>& Hinput,\n                          const Eigen::VectorXd& g,\n                          Eigen::VectorXd* p,\n                          SolverResults* results) const\n{\n\tBKP_sym_ildl_generic(Hinput, g, p, results);\n}\n\n}  // namespace spii\n#endif // #ifndef USE_SYM_ILDL\n", "meta": {"hexsha": "795c03ff642bcf4e8201a38408b685d59cde7984", "size": 4501, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/solver_newton_factorization_sym_ildl.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_sym_ildl.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_sym_ildl.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": 23.8148148148, "max_line_length": 94, "alphanum_fraction": 0.5945345479, "num_tokens": 1314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891130942474, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.4590503762891784}}
{"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#include <boost/simd/pack.hpp>\n#include <boost/simd/function/significants.hpp>\n#include <boost/simd/function/rec.hpp>\n#include <boost/simd/detail/dispatch/meta/as_integer.hpp>\n#include <boost/simd/meta/cardinal_of.hpp>\n#include <simd_test.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/minf.hpp>\n#include <boost/simd/constant/nan.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/mone.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/constant/mzero.hpp>\n\ntemplate <typename T, std::size_t N, typename Env>\nvoid test(Env& runtime)\n{\n\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using iT =  bd::as_integer_t<T>;\n  using p_t = bs::pack<T, N>;\n  using pi_t= bs::pack<iT, N>;\n\n  T a1[N], b[N];\n  iT a2[N];\n  for(std::size_t i = 0; i < N; ++i)\n  {\n    a1[i] = (i%2) ? T(i) : bs::rec(T(i));\n    a2[i] = i+2;\n    b[i] = bs::significants(a1[i], a2[i]) ;\n  }\n  p_t aa1(&a1[0], &a1[0]+N);\n  pi_t aa2(&a2[0], &a2[0]+N);\n  p_t bb (&b[0], &b[0]+N);\n\n  STF_ULP_EQUAL(bs::significants(aa1, aa2), bb, 0.5);\n}\n\nSTF_CASE_TPL(\"Check significants on pack\" , STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  using p_t = bs::pack<T>;\n  static const std::size_t N = bs::cardinal_of<p_t>::value;\n  test<T, N>(runtime);\n  test<T, N/2>(runtime);\n  test<T, N*2>(runtime);\n}\n\n\n\n\nSTF_CASE_TPL (\" significants\",  (float))//STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n\n  using bs::significants;\n  using p_t = bs::pack<T>;\n\n  using ip_t =  bd::as_integer_t<p_t>;\n  using r_t = decltype(significants(p_t(), ip_t()));\n\n  // return type conformity test\n  STF_TYPE_IS( r_t, p_t );\n\n#ifndef BOOST_SIMD_NO_INVALIDS\n   STF_ULP_EQUAL(significants(bs::Inf<p_t>(), ip_t(1)), bs::Inf<r_t>(), 0.5);\n   STF_ULP_EQUAL(significants(bs::Minf<p_t>(), ip_t(1)), bs::Minf<r_t>(), 0.5);\n   STF_ULP_EQUAL(significants(bs::Nan<p_t>(),ip_t(1)), bs::Nan<r_t>(), 0.5);\n#endif\n   STF_ULP_EQUAL(significants(p_t(0), ip_t(1)), p_t(0), 0.5);\n   STF_ULP_EQUAL(significants(p_t(25.34), ip_t(1)), p_t(30), 0.5);\n   STF_ULP_EQUAL(significants(p_t(25.34), ip_t(2)), p_t(25), 0.5);\n   STF_ULP_EQUAL(significants(p_t(25.34), ip_t(3)), p_t(25.3), 0.5);\n   STF_ULP_EQUAL(significants(p_t(25.34), ip_t(4)), p_t(25.34), 0.5);\n   STF_ULP_EQUAL(significants(p_t(-25.34), ip_t(1)), p_t(-30), 0.5);\n   STF_ULP_EQUAL(significants(p_t(-25.34),ip_t(2)), p_t(-25), 0.5);\n   STF_ULP_EQUAL(significants(p_t(-25.34), ip_t(3)), p_t(-25.3), 0.5);\n   STF_ULP_EQUAL(significants(p_t(-25.34), ip_t(4)), p_t(-25.34), 0.5);\n   STF_ULP_EQUAL(significants(p_t(-25.34), 4), p_t(-25.34), 0.5);\n}\n", "meta": {"hexsha": "2cdea880f88ae0e70744698b75a54240cdc655ec", "size": 3021, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/simd/significants.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": "test/function/simd/significants.cpp", "max_issues_repo_name": "remymuller/boost.simd", "max_issues_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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/function/simd/significants.cpp", "max_forks_repo_name": "remymuller/boost.simd", "max_forks_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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": 32.4838709677, "max_line_length": 100, "alphanum_fraction": 0.6133730553, "num_tokens": 1047, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646140788307, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.4589649359270863}}
{"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   testLinearEquality.cpp\n *  @brief  Unit tests for LinearEquality\n *  @author Duy-Nguyen Ta\n **/\n\n#include <gtsam_unstable/linear/LinearEquality.h>\n#include <gtsam/base/TestableAssertions.h>\n#include <gtsam/linear/HessianFactor.h>\n#include <gtsam/linear/VectorValues.h>\n#include <CppUnitLite/TestHarness.h>\n\n#include <boost/assign/std/vector.hpp>\n#include <boost/assign/list_of.hpp>\n\nusing namespace std;\nusing namespace gtsam;\nusing namespace boost::assign;\n\nGTSAM_CONCEPT_TESTABLE_INST (LinearEquality)\n\nnamespace {\nnamespace simple {\n// Terms we'll use\nconst vector<pair<Key, Matrix> > terms = list_of < pair<Key, Matrix>\n    > (make_pair(5, Matrix3::Identity()))(\n        make_pair(10, 2 * Matrix3::Identity()))(\n        make_pair(15, 3 * Matrix3::Identity()));\n\n// RHS and sigmas\nconst Vector b = (Vector(3) << 1., 2., 3.).finished();\nconst SharedDiagonal noise = noiseModel::Constrained::All(3);\n}\n}\n\n/* ************************************************************************* */\nTEST(LinearEquality, constructors_and_accessors)\n{\n  using namespace simple;\n\n  // Test for using different numbers of terms\n  {\n    // One term constructor\n    LinearEquality expected(\n        boost::make_iterator_range(terms.begin(), terms.begin() + 1), b, 0);\n    LinearEquality actual(terms[0].first, terms[0].second, b, 0);\n    EXPECT(assert_equal(expected, actual));\n    LONGS_EQUAL((long)terms[0].first, (long)actual.keys().back());\n    EXPECT(assert_equal(terms[0].second, actual.getA(actual.end() - 1)));\n    EXPECT(assert_equal(b, expected.getb()));\n    EXPECT(assert_equal(b, actual.getb()));\n    EXPECT(assert_equal(*noise, *actual.get_model()));\n  }\n  {\n    // Two term constructor\n    LinearEquality expected(\n        boost::make_iterator_range(terms.begin(), terms.begin() + 2), b, 0);\n    LinearEquality actual(terms[0].first, terms[0].second,\n        terms[1].first, terms[1].second, b, 0);\n    EXPECT(assert_equal(expected, actual));\n    LONGS_EQUAL((long)terms[1].first, (long)actual.keys().back());\n    EXPECT(assert_equal(terms[1].second, actual.getA(actual.end() - 1)));\n    EXPECT(assert_equal(b, expected.getb()));\n    EXPECT(assert_equal(b, actual.getb()));\n    EXPECT(assert_equal(*noise, *actual.get_model()));\n  }\n  {\n    // Three term constructor\n    LinearEquality expected(\n        boost::make_iterator_range(terms.begin(), terms.begin() + 3), b, 0);\n    LinearEquality actual(terms[0].first, terms[0].second,\n        terms[1].first, terms[1].second, terms[2].first, terms[2].second, b, 0);\n    EXPECT(assert_equal(expected, actual));\n    LONGS_EQUAL((long)terms[2].first, (long)actual.keys().back());\n    EXPECT(assert_equal(terms[2].second, actual.getA(actual.end() - 1)));\n    EXPECT(assert_equal(b, expected.getb()));\n    EXPECT(assert_equal(b, actual.getb()));\n    EXPECT(assert_equal(*noise, *actual.get_model()));\n  }\n}\n\n/* ************************************************************************* */\nTEST(LinearEquality, Hessian_conversion) {\n  HessianFactor hessian(0, (Matrix(4,4) <<\n          1.57, 2.695, -1.1, -2.35,\n          2.695, 11.3125, -0.65, -10.225,\n          -1.1, -0.65, 1, 0.5,\n          -2.35, -10.225, 0.5, 9.25).finished(),\n      (Vector(4) << -7.885, -28.5175, 2.75, 25.675).finished(),\n      73.1725);\n\n  try {\n    LinearEquality actual(hessian);\n    EXPECT(false);\n  }\n  catch (const std::runtime_error& exception) {\n    EXPECT(true);\n  }\n}\n\n/* ************************************************************************* */\nTEST(LinearEquality, error)\n{\n  LinearEquality factor(simple::terms, simple::b, 0);\n\n  VectorValues values;\n  values.insert(5, Vector::Constant(3, 1.0));\n  values.insert(10, Vector::Constant(3, 0.5));\n  values.insert(15, Vector::Constant(3, 1.0/3.0));\n\n  Vector expected_unwhitened(3); expected_unwhitened << 2.0, 1.0, 0.0;\n  Vector actual_unwhitened = factor.unweighted_error(values);\n  EXPECT(assert_equal(expected_unwhitened, actual_unwhitened));\n\n  // whitened is meaningless in constraints\n  Vector expected_whitened(3); expected_whitened = expected_unwhitened;\n  Vector actual_whitened = factor.error_vector(values);\n  EXPECT(assert_equal(expected_whitened, actual_whitened));\n\n  double expected_error = 0.0;\n  double actual_error = factor.error(values);\n  DOUBLES_EQUAL(expected_error, actual_error, 1e-10);\n}\n\n/* ************************************************************************* */\nTEST(LinearEquality, matrices_NULL)\n{\n  // Make sure everything works with NULL noise model\n  LinearEquality factor(simple::terms, simple::b, 0);\n\n  Matrix AExpected(3, 9);\n  AExpected << simple::terms[0].second, simple::terms[1].second, simple::terms[2].second;\n  Vector rhsExpected = simple::b;\n  Matrix augmentedJacobianExpected(3, 10);\n  augmentedJacobianExpected << AExpected, rhsExpected;\n\n  // Whitened Jacobian\n  EXPECT(assert_equal(AExpected, factor.jacobian().first));\n  EXPECT(assert_equal(rhsExpected, factor.jacobian().second));\n  EXPECT(assert_equal(augmentedJacobianExpected, factor.augmentedJacobian()));\n\n  // Unwhitened Jacobian\n  EXPECT(assert_equal(AExpected, factor.jacobianUnweighted().first));\n  EXPECT(assert_equal(rhsExpected, factor.jacobianUnweighted().second));\n  EXPECT(assert_equal(augmentedJacobianExpected, factor.augmentedJacobianUnweighted()));\n}\n\n/* ************************************************************************* */\nTEST(LinearEquality, matrices)\n{\n  // And now witgh a non-unit noise model\n  LinearEquality factor(simple::terms, simple::b, 0);\n\n  Matrix jacobianExpected(3, 9);\n  jacobianExpected << simple::terms[0].second, simple::terms[1].second, simple::terms[2].second;\n  Vector rhsExpected = simple::b;\n  Matrix augmentedJacobianExpected(3, 10);\n  augmentedJacobianExpected << jacobianExpected, rhsExpected;\n\n  Matrix augmentedHessianExpected =\n  augmentedJacobianExpected.transpose() * simple::noise->R().transpose()\n  * simple::noise->R() * augmentedJacobianExpected;\n\n  // Whitened Jacobian\n  EXPECT(assert_equal(jacobianExpected, factor.jacobian().first));\n  EXPECT(assert_equal(rhsExpected, factor.jacobian().second));\n  EXPECT(assert_equal(augmentedJacobianExpected, factor.augmentedJacobian()));\n\n  // Unwhitened Jacobian\n  EXPECT(assert_equal(jacobianExpected, factor.jacobianUnweighted().first));\n  EXPECT(assert_equal(rhsExpected, factor.jacobianUnweighted().second));\n  EXPECT(assert_equal(augmentedJacobianExpected, factor.augmentedJacobianUnweighted()));\n}\n\n/* ************************************************************************* */\nTEST(LinearEquality, operators )\n{\n  Matrix I = I_2x2;\n  Vector b = (Vector(2) << 0.2,-0.1).finished();\n  LinearEquality lf(1, -I, 2, I, b, 0);\n\n  VectorValues c;\n  c.insert(1, (Vector(2) << 10.,20.).finished());\n  c.insert(2, (Vector(2) << 30.,60.).finished());\n\n  // test A*x\n  Vector expectedE = (Vector(2) << 20.,40.).finished();\n  Vector actualE = lf * c;\n  EXPECT(assert_equal(expectedE, actualE));\n\n  // test A^e\n  VectorValues expectedX;\n  expectedX.insert(1, (Vector(2) << -20.,-40.).finished());\n  expectedX.insert(2, (Vector(2) << 20., 40.).finished());\n  VectorValues actualX = VectorValues::Zero(expectedX);\n  lf.transposeMultiplyAdd(1.0, actualE, actualX);\n  EXPECT(assert_equal(expectedX, actualX));\n\n  // test gradient at zero\n  Matrix A; Vector b2; boost::tie(A,b2) = lf.jacobian();\n  VectorValues expectedG;\n  expectedG.insert(1, (Vector(2) << 0.2, -0.1).finished());\n  expectedG.insert(2, (Vector(2) << -0.2, 0.1).finished());\n  VectorValues actualG = lf.gradientAtZero();\n  EXPECT(assert_equal(expectedG, actualG));\n}\n\n/* ************************************************************************* */\nTEST(LinearEquality, default_error )\n{\n  LinearEquality f;\n  double actual = f.error(VectorValues());\n  DOUBLES_EQUAL(0.0, actual, 1e-15);\n}\n\n//* ************************************************************************* */\nTEST(LinearEquality, empty )\n{\n  // create an empty factor\n  LinearEquality f;\n  EXPECT(f.empty());\n}\n\n/* ************************************************************************* */\nint main() {\n  TestResult tr;\n  return TestRegistry::runAllTests(tr);\n}\n/* ************************************************************************* */\n", "meta": {"hexsha": "fa94dd255c82df91cb3d59aeeff1631485536241", "size": 8560, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam_unstable/linear/tests/testLinearEquality.cpp", "max_stars_repo_name": "kvmanohar22/gtsam", "max_stars_repo_head_hexsha": "8194b931fe07fb1bd346cdcf116a35f9c4e208ba", "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/linear/tests/testLinearEquality.cpp", "max_issues_repo_name": "kvmanohar22/gtsam", "max_issues_repo_head_hexsha": "8194b931fe07fb1bd346cdcf116a35f9c4e208ba", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-10-30T21:17:33.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-18T18:47:40.000Z", "max_forks_repo_path": "gtsam_unstable/linear/tests/testLinearEquality.cpp", "max_forks_repo_name": "kvmanohar22/gtsam", "max_forks_repo_head_hexsha": "8194b931fe07fb1bd346cdcf116a35f9c4e208ba", "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": 35.5186721992, "max_line_length": 96, "alphanum_fraction": 0.6226635514, "num_tokens": 2180, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.4589649315388217}}
{"text": "\n#pragma once\n\n#include <cstdint>\n#include <utility>\n#include <Eigen/Core>\n\nnamespace neon\n{\nusing indices = Eigen::Array<std::int32_t, Eigen::Dynamic, Eigen::Dynamic>;\n\n/// Type alias for whatever type is returned from these views\nusing index_view = decltype(std::declval<const indices>()(Eigen::placeholders::all, 0l));\n}\n", "meta": {"hexsha": "37bedd14422a17bd79c37618767e64ef413f0c9a", "size": 324, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/numeric/index_types.hpp", "max_stars_repo_name": "annierhea/neon", "max_stars_repo_head_hexsha": "4eb51a06bda6bbf32c54fff8f39c9e02d429cfd1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/numeric/index_types.hpp", "max_issues_repo_name": "annierhea/neon", "max_issues_repo_head_hexsha": "4eb51a06bda6bbf32c54fff8f39c9e02d429cfd1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/numeric/index_types.hpp", "max_forks_repo_name": "annierhea/neon", "max_forks_repo_head_hexsha": "4eb51a06bda6bbf32c54fff8f39c9e02d429cfd1", "max_forks_repo_licenses": ["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.6, "max_line_length": 89, "alphanum_fraction": 0.7345679012, "num_tokens": 77, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.45896492266889516}}
{"text": "#ifndef AIKIDO_COMMON_PSEUDOINVERSE_HPP_\n#define AIKIDO_COMMON_PSEUDOINVERSE_HPP_\n\n#include <Eigen/Dense>\n\nnamespace aikido {\nnamespace common {\n\n/// Computes the Moore-Penrose pseudoinverse of a matrix.\n///\n/// \\param mat input matrix\n/// \\param eps represents tolerance\n/// \\return pseudo-inverse of \\c mat\nEigen::MatrixXd pseudoinverse(const Eigen::MatrixXd& mat, double eps = 1e-6);\n\n} // namespace common\n} // namespace aikido\n\n#endif // AIKIDO_COMMON_PSEUDOINVERSE_HPP_\n", "meta": {"hexsha": "b883d0018b34645cb286a81a6b79aea8517b13b0", "size": 476, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/aikido/common/PseudoInverse.hpp", "max_stars_repo_name": "usc-csci-545/aikido", "max_stars_repo_head_hexsha": "afd8b203c17cb0b05d7db436f8bffbbe2111a75a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 181.0, "max_stars_repo_stars_event_min_datetime": "2016-04-22T15:11:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T12:51:08.000Z", "max_issues_repo_path": "include/aikido/common/PseudoInverse.hpp", "max_issues_repo_name": "usc-csci-545/aikido", "max_issues_repo_head_hexsha": "afd8b203c17cb0b05d7db436f8bffbbe2111a75a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 514.0, "max_issues_repo_issues_event_min_datetime": "2016-04-20T04:29:51.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T19:46:21.000Z", "max_forks_repo_path": "include/aikido/common/PseudoInverse.hpp", "max_forks_repo_name": "usc-csci-545/aikido", "max_forks_repo_head_hexsha": "afd8b203c17cb0b05d7db436f8bffbbe2111a75a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 31.0, "max_forks_repo_forks_event_min_datetime": "2017-03-17T09:53:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T10:35:05.000Z", "avg_line_length": 23.8, "max_line_length": 77, "alphanum_fraction": 0.7668067227, "num_tokens": 124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6757646010190475, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.4589649226688951}}
{"text": "/*\n * COPYRIGHT AND PERMISSION NOTICE\n * Penn Software MSCKF_VIO\n * Copyright (C) 2017 The Trustees of the University of Pennsylvania\n * All rights reserved.\n */\n\n#ifndef GTSAM_VIO_FEATURE_H\n#define GTSAM_VIO_FEATURE_H\n\n#include <iostream>\n#include <map>\n#include <vector>\n\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#include <Eigen/StdVector>\n\n#include \"math_utils.hpp\"\n#include \"imu_state.h\"\n#include \"cam_state.h\"\n\nnamespace gtsam_vio {\n\n/*\n * @brief Feature Salient part of an image. Please refer\n *    to the Appendix of \"A Multi-State Constraint Kalman\n *    Filter for Vision-aided Inertial Navigation\" for how\n *    the 3d position of a feature is initialized.\n */\nstruct Feature {\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n  typedef long long int FeatureIDType;\n\n  /*\n   * @brief OptimizationConfig Configuration parameters\n   *    for 3d feature position optimization.\n   */\n  struct OptimizationConfig {\n    double translation_threshold;\n    double huber_epsilon;\n    double estimation_precision;\n    double initial_damping;\n    int outer_loop_max_iteration;\n    int inner_loop_max_iteration;\n\n    OptimizationConfig():\n      translation_threshold(0.2),\n      huber_epsilon(0.01),\n      estimation_precision(5e-7),\n      initial_damping(1e-3),\n      outer_loop_max_iteration(10),\n      inner_loop_max_iteration(10) {\n      return;\n    }\n  };\n\n  // Constructors for the struct.\n  Feature(): id(0), position(Eigen::Vector3d::Zero()),\n    is_initialized(false) {}\n\n  Feature(const FeatureIDType& new_id): id(new_id),\n    position(Eigen::Vector3d::Zero()),\n    is_initialized(false) {}\n\n  /*\n   * @brief cost Compute the cost of the camera observations\n   * @param T_c0_c1 A rigid body transformation takes\n   *    a vector in c0 frame to ci frame.\n   * @param x The current estimation.\n   * @param z The ith measurement of the feature j in ci frame.\n   * @return e The cost of this observation.\n   */\n  inline void cost(const Eigen::Isometry3d& T_c0_ci,\n      const Eigen::Vector3d& x, const Eigen::Vector2d& z,\n      double& e) const;\n\n  /*\n   * @brief jacobian Compute the Jacobian of the camera observation\n   * @param T_c0_c1 A rigid body transformation takes\n   *    a vector in c0 frame to ci frame.\n   * @param x The current estimation.\n   * @param z The actual measurement of the feature in ci frame.\n   * @return J The computed Jacobian.\n   * @return r The computed residual.\n   * @return w Weight induced by huber kernel.\n   */\n  inline void jacobian(const Eigen::Isometry3d& T_c0_ci,\n      const Eigen::Vector3d& x, const Eigen::Vector2d& z,\n      Eigen::Matrix<double, 2, 3>& J, Eigen::Vector2d& r,\n      double& w) const;\n\n  /*\n   * @brief generateInitialGuess Compute the initial guess of\n   *    the feature's 3d position using only two views.\n   * @param T_c1_c2: A rigid body transformation taking\n   *    a vector from c2 frame to c1 frame.\n   * @param z1: feature observation in c1 frame.\n   * @param z2: feature observation in c2 frame.\n   * @return p: Computed feature position in c1 frame.\n   */\n  inline void generateInitialGuess(\n      const Eigen::Isometry3d& T_c1_c2, const Eigen::Vector2d& z1,\n      const Eigen::Vector2d& z2, Eigen::Vector3d& p) const;\n\n  /*\n   * @brief checkMotion Check the input camera poses to ensure\n   *    there is enough translation to triangulate the feature\n   *    positon.\n   * @param cam_states : input camera poses.\n   * @return True if the translation between the input camera\n   *    poses is sufficient.\n   */\n  inline bool checkMotion(\n      const CamStateServer& cam_states) const;\n\n  /*\n   * @brief InitializePosition Intialize the feature position\n   *    based on all current available measurements.\n   * @param cam_states: A map containing the camera poses with its\n   *    ID as the associated key value.\n   * @return The computed 3d position is used to set the position\n   *    member variable. Note the resulted position is in world\n   *    frame.\n   * @return True if the estimated 3d position of the feature\n   *    is valid.\n   */\n  inline bool initializePosition(\n      const CamStateServer& cam_states);\n\n\n  // An unique identifier for the feature.\n  // In case of long time running, the variable\n  // type of id is set to FeatureIDType in order\n  // to avoid duplication.\n  FeatureIDType id;\n\n  // id for next feature\n  static FeatureIDType next_id;\n\n  // Store the observations of the features in the\n  // state_id(key)-image_coordinates(value) manner.\n  std::map<StateIDType, Eigen::Vector4d, std::less<StateIDType>,\n    Eigen::aligned_allocator<\n      std::pair<const StateIDType, Eigen::Vector4d> > > observations;\n\n  // 3d postion of the feature in the world frame.\n  Eigen::Vector3d position;\n\n  // A indicator to show if the 3d postion of the feature\n  // has been initialized or not.\n  bool is_initialized;\n\n  // Noise for a normalized feature measurement.\n  static double observation_noise;\n\n  // Optimization configuration for solving the 3d position.\n  static OptimizationConfig optimization_config;\n\n};\n\ntypedef Feature::FeatureIDType FeatureIDType;\ntypedef std::map<FeatureIDType, Feature, std::less<int>,\n        Eigen::aligned_allocator<\n        std::pair<const FeatureIDType, Feature> > > MapServer;\n\n\nvoid Feature::cost(const Eigen::Isometry3d& T_c0_ci,\n    const Eigen::Vector3d& x, const Eigen::Vector2d& z,\n    double& e) const {\n  // Compute hi1, hi2, and hi3 as Equation (37).\n  const double& alpha = x(0);\n  const double& beta = x(1);\n  const double& rho = x(2);\n\n  Eigen::Vector3d h = T_c0_ci.linear()*\n    Eigen::Vector3d(alpha, beta, 1.0) + rho*T_c0_ci.translation();\n  double& h1 = h(0);\n  double& h2 = h(1);\n  double& h3 = h(2);\n\n  // Predict the feature observation in ci frame.\n  Eigen::Vector2d z_hat(h1/h3, h2/h3);\n\n  // Compute the residual.\n  e = (z_hat-z).squaredNorm();\n  return;\n}\n\nvoid Feature::jacobian(const Eigen::Isometry3d& T_c0_ci,\n    const Eigen::Vector3d& x, const Eigen::Vector2d& z,\n    Eigen::Matrix<double, 2, 3>& J, Eigen::Vector2d& r,\n    double& w) const {\n\n  // Compute hi1, hi2, and hi3 as Equation (37).\n  const double& alpha = x(0);\n  const double& beta = x(1);\n  const double& rho = x(2);\n\n  Eigen::Vector3d h = T_c0_ci.linear()*\n    Eigen::Vector3d(alpha, beta, 1.0) + rho*T_c0_ci.translation();\n  double& h1 = h(0);\n  double& h2 = h(1);\n  double& h3 = h(2);\n\n  // Compute the Jacobian.\n  Eigen::Matrix3d W;\n  W.leftCols<2>() = T_c0_ci.linear().leftCols<2>();\n  W.rightCols<1>() = T_c0_ci.translation();\n\n  J.row(0) = 1/h3*W.row(0) - h1/(h3*h3)*W.row(2);\n  J.row(1) = 1/h3*W.row(1) - h2/(h3*h3)*W.row(2);\n\n  // Compute the residual.\n  Eigen::Vector2d z_hat(h1/h3, h2/h3);\n  r = z_hat - z;\n\n  // Compute the weight based on the residual.\n  double e = r.norm();\n  if (e <= optimization_config.huber_epsilon)\n    w = 1.0;\n  else\n    w = optimization_config.huber_epsilon / (2*e);\n\n  return;\n}\n\nvoid Feature::generateInitialGuess(\n    const Eigen::Isometry3d& T_c1_c2, const Eigen::Vector2d& z1,\n    const Eigen::Vector2d& z2, Eigen::Vector3d& p) const {\n  // Construct a least square problem to solve the depth.\n  Eigen::Vector3d m = T_c1_c2.linear() * Eigen::Vector3d(z1(0), z1(1), 1.0);\n\n  Eigen::Vector2d A(0.0, 0.0);\n  A(0) = m(0) - z2(0)*m(2);\n  A(1) = m(1) - z2(1)*m(2);\n\n  Eigen::Vector2d b(0.0, 0.0);\n  b(0) = z2(0)*T_c1_c2.translation()(2) - T_c1_c2.translation()(0);\n  b(1) = z2(1)*T_c1_c2.translation()(2) - T_c1_c2.translation()(1);\n\n  // Solve for the depth.\n  double depth = (A.transpose() * A).inverse() * A.transpose() * b;\n  p(0) = z1(0) * depth;\n  p(1) = z1(1) * depth;\n  p(2) = depth;\n  return;\n}\n\nbool Feature::checkMotion(\n    const CamStateServer& cam_states) const {\n\n  const StateIDType& first_cam_id = observations.begin()->first;\n  const StateIDType& last_cam_id = (--observations.end())->first;\n\n  Eigen::Isometry3d first_cam_pose;\n  first_cam_pose.linear() = quaternionToRotation(\n      cam_states.find(first_cam_id)->second.orientation).transpose();\n  first_cam_pose.translation() =\n    cam_states.find(first_cam_id)->second.position;\n\n  Eigen::Isometry3d last_cam_pose;\n  last_cam_pose.linear() = quaternionToRotation(\n      cam_states.find(last_cam_id)->second.orientation).transpose();\n  last_cam_pose.translation() =\n    cam_states.find(last_cam_id)->second.position;\n\n  // Get the direction of the feature when it is first observed.\n  // This direction is represented in the world frame.\n  Eigen::Vector3d feature_direction(\n      observations.begin()->second(0),\n      observations.begin()->second(1), 1.0);\n  feature_direction = feature_direction / feature_direction.norm();\n  feature_direction = first_cam_pose.linear()*feature_direction;\n\n  // Compute the translation between the first frame\n  // and the last frame. We assume the first frame and\n  // the last frame will provide the largest motion to\n  // speed up the checking process.\n  Eigen::Vector3d translation = last_cam_pose.translation() -\n    first_cam_pose.translation();\n  double parallel_translation =\n    translation.transpose()*feature_direction;\n  Eigen::Vector3d orthogonal_translation = translation -\n    parallel_translation*feature_direction;\n\n  if (orthogonal_translation.norm() >\n      optimization_config.translation_threshold)\n    return true;\n  else return false;\n}\n\nbool Feature::initializePosition(\n    const CamStateServer& cam_states) {\n  // Organize camera poses and feature observations properly.\n  std::vector<Eigen::Isometry3d,\n    Eigen::aligned_allocator<Eigen::Isometry3d> > cam_poses(0);\n  std::vector<Eigen::Vector2d,\n    Eigen::aligned_allocator<Eigen::Vector2d> > measurements(0);\n\n  for (auto& m : observations) {\n    // TODO: This should be handled properly. Normally, the\n    //    required camera states should all be available in\n    //    the input cam_states buffer.\n    auto cam_state_iter = cam_states.find(m.first);\n    if (cam_state_iter == cam_states.end()) continue;\n\n    // Add the measurement.\n    measurements.push_back(m.second.head<2>());\n    measurements.push_back(m.second.tail<2>());\n\n    // This camera pose will take a vector from this camera frame\n    // to the world frame.\n    Eigen::Isometry3d cam0_pose;\n    cam0_pose.linear() = quaternionToRotation(\n        cam_state_iter->second.orientation).transpose();\n    cam0_pose.translation() = cam_state_iter->second.position;\n\n    Eigen::Isometry3d cam1_pose;\n    cam1_pose = cam0_pose * CAMState::T_cam0_cam1.inverse();\n\n    cam_poses.push_back(cam0_pose);\n    cam_poses.push_back(cam1_pose);\n  }\n\n  // All camera poses should be modified such that it takes a\n  // vector from the first camera frame in the buffer to this\n  // camera frame.\n  Eigen::Isometry3d T_c0_w = cam_poses[0];\n  for (auto& pose : cam_poses)\n    pose = pose.inverse() * T_c0_w;\n\n  // Generate initial guess\n  Eigen::Vector3d initial_position(0.0, 0.0, 0.0);\n  generateInitialGuess(cam_poses[cam_poses.size()-1], measurements[0],\n      measurements[measurements.size()-1], initial_position);\n  Eigen::Vector3d solution(\n      initial_position(0)/initial_position(2),\n      initial_position(1)/initial_position(2),\n      1.0/initial_position(2));\n\n  // Apply Levenberg-Marquart method to solve for the 3d position.\n  double lambda = optimization_config.initial_damping;\n  int inner_loop_cntr = 0;\n  int outer_loop_cntr = 0;\n  bool is_cost_reduced = false;\n  double delta_norm = 0;\n\n  // Compute the initial cost.\n  double total_cost = 0.0;\n  for (int i = 0; i < cam_poses.size(); ++i) {\n    double this_cost = 0.0;\n    cost(cam_poses[i], solution, measurements[i], this_cost);\n    total_cost += this_cost;\n  }\n\n  // Outer loop.\n  do {\n    Eigen::Matrix3d A = Eigen::Matrix3d::Zero();\n    Eigen::Vector3d b = Eigen::Vector3d::Zero();\n\n    for (int i = 0; i < cam_poses.size(); ++i) {\n      Eigen::Matrix<double, 2, 3> J;\n      Eigen::Vector2d r;\n      double w;\n\n      jacobian(cam_poses[i], solution, measurements[i], J, r, w);\n\n      if (w == 1) {\n        A += J.transpose() * J;\n        b += J.transpose() * r;\n      } else {\n        double w_square = w * w;\n        A += w_square * J.transpose() * J;\n        b += w_square * J.transpose() * r;\n      }\n    }\n\n    // Inner loop.\n    // Solve for the delta that can reduce the total cost.\n    do {\n      Eigen::Matrix3d damper = lambda * Eigen::Matrix3d::Identity();\n      Eigen::Vector3d delta = (A+damper).ldlt().solve(b);\n      Eigen::Vector3d new_solution = solution - delta;\n      delta_norm = delta.norm();\n\n      double new_cost = 0.0;\n      for (int i = 0; i < cam_poses.size(); ++i) {\n        double this_cost = 0.0;\n        cost(cam_poses[i], new_solution, measurements[i], this_cost);\n        new_cost += this_cost;\n      }\n\n      if (new_cost < total_cost) {\n        is_cost_reduced = true;\n        solution = new_solution;\n        total_cost = new_cost;\n        lambda = lambda/10 > 1e-10 ? lambda/10 : 1e-10;\n      } else {\n        is_cost_reduced = false;\n        lambda = lambda*10 < 1e12 ? lambda*10 : 1e12;\n      }\n\n    } while (inner_loop_cntr++ <\n        optimization_config.inner_loop_max_iteration && !is_cost_reduced);\n\n    inner_loop_cntr = 0;\n\n  } while (outer_loop_cntr++ <\n      optimization_config.outer_loop_max_iteration &&\n      delta_norm > optimization_config.estimation_precision);\n\n  // Covert the feature position from inverse depth\n  // representation to its 3d coordinate.\n  Eigen::Vector3d final_position(solution(0)/solution(2),\n      solution(1)/solution(2), 1.0/solution(2));\n\n  // Check if the solution is valid. Make sure the feature\n  // is in front of every camera frame observing it.\n  bool is_valid_solution = true;\n  for (const auto& pose : cam_poses) {\n    Eigen::Vector3d position =\n      pose.linear()*final_position + pose.translation();\n    if (position(2) <= 0) {\n      is_valid_solution = false;\n      break;\n    }\n  }\n\n  // Convert the feature position to the world frame.\n  position = T_c0_w.linear()*final_position + T_c0_w.translation();\n\n  if (is_valid_solution)\n    is_initialized = true;\n\n  return is_valid_solution;\n}\n} // namespace gtsam_vio\n\n#endif // GTSAM_VIO_FEATURE_H\n", "meta": {"hexsha": "ef3bb727ea84818a845c7ca0c331ba1473849180", "size": 14003, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/gtsam_vio/feature.hpp", "max_stars_repo_name": "vkopli/isam2_vio", "max_stars_repo_head_hexsha": "2fe49c74a307921b4af29a4197ef43b9757c4b8c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 71.0, "max_stars_repo_stars_event_min_datetime": "2020-04-05T08:16:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T17:31:37.000Z", "max_issues_repo_path": "include/gtsam_vio/feature.hpp", "max_issues_repo_name": "vkopli/isam2_vio", "max_issues_repo_head_hexsha": "2fe49c74a307921b4af29a4197ef43b9757c4b8c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-09-01T02:26:22.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-09T04:35:29.000Z", "max_forks_repo_path": "include/gtsam_vio/feature.hpp", "max_forks_repo_name": "vkopli/isam2_vio", "max_forks_repo_head_hexsha": "2fe49c74a307921b4af29a4197ef43b9757c4b8c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-09-30T23:02:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T09:59:07.000Z", "avg_line_length": 31.7528344671, "max_line_length": 76, "alphanum_fraction": 0.6796400771, "num_tokens": 3847, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757645879592642, "lm_q2_score": 0.6791787121629465, "lm_q1q2_score": 0.4589649225754972}}
{"text": "// Copyright (c) 2015\n// Author: Chrono Law\n#include <std.hpp>\nusing namespace std;\n\n#include <boost/static_assert.hpp>\n\n//////////////////////////////////////////\n\nvoid case1()\n{\n    BOOST_STATIC_ASSERT(2 == sizeof(short));\n    BOOST_STATIC_ASSERT(true);\n    BOOST_STATIC_ASSERT_MSG(16 == 0x10, \"test static assert\");\n}\n\n//////////////////////////////////////////\n\ntemplate<typename T>\nT my_min(T a, T b)\n{\n    BOOST_STATIC_ASSERT_MSG(sizeof(T) < sizeof(int), \"only short or char\");\n    return a < b? a: b;\n}\nvoid case2()\n{\n    cout << my_min((short)1, (short)3);\n    //cout << my_min(1L, 3L);\n}\n\n//////////////////////////////////////////\n\nnamespace my_space\n{\n    class empty_class\n    {\n        BOOST_STATIC_ASSERT_MSG(sizeof(int)>=4, \"for 32 bit\");\n    };\n\n    BOOST_STATIC_ASSERT(sizeof(empty_class) == 1);\n}\n\n\nint main()\n{\n    case1();\n    case2();\n}\n\n", "meta": {"hexsha": "d1d2d219920824847d9ae1b5cbcbff0911fd3f8b", "size": 859, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/static_assert.cpp", "max_stars_repo_name": "xujungp02/boost_guide", "max_stars_repo_head_hexsha": "328516455d334506f824402455a17afc606ca3bc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 355.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T12:03:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T04:15:00.000Z", "max_issues_repo_path": "test/static_assert.cpp", "max_issues_repo_name": "lak123456/boost_guide", "max_issues_repo_head_hexsha": "1886ec8014838717222484f0fe872ecebc324e91", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-10-04T18:14:17.000Z", "max_issues_repo_issues_event_max_datetime": "2017-10-09T02:38:12.000Z", "max_forks_repo_path": "test/static_assert.cpp", "max_forks_repo_name": "lak123456/boost_guide", "max_forks_repo_head_hexsha": "1886ec8014838717222484f0fe872ecebc324e91", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 202.0, "max_forks_repo_forks_event_min_datetime": "2015-03-23T16:16:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T07:55:48.000Z", "avg_line_length": 17.18, "max_line_length": 75, "alphanum_fraction": 0.5355064028, "num_tokens": 215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6150878696277513, "lm_q2_score": 0.7461389873857265, "lm_q1q2_score": 0.4589410401972941}}
{"text": "/********************************************************************************\nCopyright (c) 2015, TRACLabs, Inc.\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\n are permitted provided that the following conditions are met:\n\n    1. Redistributions of source code must retain the above copyright notice,\n       this list of conditions and the following disclaimer.\n\n    2. Redistributions in binary form must reproduce the above copyright notice,\n       this list of conditions and the following disclaimer in the documentation\n       and/or other materials provided with the distribution.\n\n    3. Neither the name of the copyright holder nor the names of its contributors\n       may be used to endorse or promote products derived from this software\n       without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\nIN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\nINDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\nBUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\nOR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\nOF THE POSSIBILITY OF SUCH DAMAGE.\n********************************************************************************/\n\n#include <boost/date_time.hpp>\n#include <boost/math/tools/precision.hpp>\n#include <cmath>\n#include <limits>\n#include <trac_ik/dual_quaternion.h>\n#include <trac_ik/nlopt_ik.hpp>\n\nnamespace NLOPT_IK\n{\n\n    dual_quaternion targetDQ;\n\n    double minfunc(const std::vector<double> &x, std::vector<double> &grad, void *data)\n    {\n        // Auxilory function to minimize (Sum of Squared joint angle error\n        // from the requested configuration).  Because we wanted a Class\n        // without static members, but NLOpt library does not support\n        // passing methods of Classes, we use these auxilary functions.\n\n        NLOPT_IK *c = (NLOPT_IK *)data;\n\n        return c->minJoints(x, grad);\n    }\n\n    double minfuncDQ(const std::vector<double> &x, std::vector<double> &grad, void *data)\n    {\n        // Auxilory function to minimize (Sum of Squared joint angle error\n        // from the requested configuration).  Because we wanted a Class\n        // without static members, but NLOpt library does not support\n        // passing methods of Classes, we use these auxilary functions.\n        NLOPT_IK *c = (NLOPT_IK *)data;\n\n        std::vector<double> vals(x);\n\n        double jump = boost::math::tools::epsilon<float>();\n        double result[1];\n        c->cartDQError(vals, result);\n\n        if (!grad.empty())\n        {\n            double v1[1];\n            for (uint i = 0; i < x.size(); i++)\n            {\n                double original = vals[i];\n\n                vals[i] = original + jump;\n                c->cartDQError(vals, v1);\n\n                vals[i] = original;\n                grad[i] = (v1[0] - result[0]) / (2 * jump);\n            }\n        }\n\n        return result[0];\n    }\n\n    double minfuncSumSquared(const std::vector<double> &x, std::vector<double> &grad, void *data)\n    {\n        // Auxilory function to minimize (Sum of Squared joint angle error\n        // from the requested configuration).  Because we wanted a Class\n        // without static members, but NLOpt library does not support\n        // passing methods of Classes, we use these auxilary functions.\n\n        NLOPT_IK *c = (NLOPT_IK *)data;\n\n        std::vector<double> vals(x);\n\n        double jump = boost::math::tools::epsilon<float>();\n        double result[1];\n        c->cartSumSquaredError(vals, result);\n\n        if (!grad.empty())\n        {\n            double v1[1];\n            for (uint i = 0; i < x.size(); i++)\n            {\n                double original = vals[i];\n\n                vals[i] = original + jump;\n                c->cartSumSquaredError(vals, v1);\n\n                vals[i] = original;\n                grad[i] = (v1[0] - result[0]) / (2.0 * jump);\n            }\n        }\n\n        return result[0];\n    }\n\n    double minfuncL2(const std::vector<double> &x, std::vector<double> &grad, void *data)\n    {\n        // Auxilory function to minimize (Sum of Squared joint angle error\n        // from the requested configuration).  Because we wanted a Class\n        // without static members, but NLOpt library does not support\n        // passing methods of Classes, we use these auxilary functions.\n\n        NLOPT_IK *c = (NLOPT_IK *)data;\n\n        std::vector<double> vals(x);\n\n        double jump = boost::math::tools::epsilon<float>();\n        double result[1];\n        c->cartL2NormError(vals, result);\n\n        if (!grad.empty())\n        {\n            double v1[1];\n            for (uint i = 0; i < x.size(); i++)\n            {\n                double original = vals[i];\n\n                vals[i] = original + jump;\n                c->cartL2NormError(vals, v1);\n\n                vals[i] = original;\n                grad[i] = (v1[0] - result[0]) / (2.0 * jump);\n            }\n        }\n\n        return result[0];\n    }\n\n    void constrainfuncm(uint m, double *result, uint n, const double *x, double *grad, void *data)\n    {\n        //Equality constraint auxilary function for Euclidean distance .\n        //This also uses a small walk to approximate the gradient of the\n        //constraint function at the current joint angles.\n\n        NLOPT_IK *c = (NLOPT_IK *)data;\n\n        std::vector<double> vals(n);\n\n        for (uint i = 0; i < n; i++)\n        {\n            vals[i] = x[i];\n        }\n\n        double jump = boost::math::tools::epsilon<float>();\n\n        c->cartSumSquaredError(vals, result);\n\n        if (grad != NULL)\n        {\n            std::vector<double> v1(m);\n            for (uint i = 0; i < n; i++)\n            {\n                double o = vals[i];\n                vals[i] = o + jump;\n                c->cartSumSquaredError(vals, v1.data());\n                vals[i] = o;\n                for (uint j = 0; j < m; j++)\n                {\n                    grad[j * n + i] = (v1[j] - result[j]) / (2 * jump);\n                }\n            }\n        }\n    }\n\n    NLOPT_IK::NLOPT_IK(const KDL::Chain &_chain, const KDL::JntArray &_q_min, const KDL::JntArray &_q_max, double _maxtime, double _eps, OptType _type) : chain(_chain), fksolver(chain), maxtime(_maxtime), eps(std::abs(_eps)), TYPE(_type)\n    {\n        assert(chain.getNrOfJoints() == _q_min.data.size());\n        assert(chain.getNrOfJoints() == _q_max.data.size());\n\n        //Constructor for an IK Class.  Takes in a Chain to operate on,\n        //the min and max joint limits, an (optional) maximum number of\n        //iterations, and an (optional) desired error.\n        reset();\n\n        if (chain.getNrOfJoints() < 2)\n        {\n            std::cout << \"WARNING :\"\n                      << \"NLOpt_IK can only be run for chains of length 2 or more\";\n            return;\n        }\n        opt = nlopt::opt(nlopt::LD_SLSQP, _chain.getNrOfJoints());\n\n        for (uint i = 0; i < chain.getNrOfJoints(); i++)\n        {\n            lb.push_back(_q_min(i));\n            ub.push_back(_q_max(i));\n        }\n\n        for (uint i = 0; i < chain.segments.size(); i++)\n        {\n            std::string type = chain.segments[i].getJoint().getTypeName();\n            if (type.find(\"Rot\") != std::string::npos)\n            {\n                if (_q_max(types.size()) >= std::numeric_limits<float>::max() &&\n                    _q_min(types.size()) <= std::numeric_limits<float>::lowest())\n                    types.push_back(KDL::BasicJointType::Continuous);\n                else\n                    types.push_back(KDL::BasicJointType::RotJoint);\n            }\n            else if (type.find(\"Trans\") != std::string::npos)\n                types.push_back(KDL::BasicJointType::TransJoint);\n        }\n\n        assert(types.size() == lb.size());\n\n        std::vector<double> tolerance(1, boost::math::tools::epsilon<float>());\n        opt.set_xtol_abs(tolerance[0]);\n\n        switch (TYPE)\n        {\n        case Joint:\n            opt.set_min_objective(minfunc, this);\n            opt.add_equality_mconstraint(constrainfuncm, this, tolerance);\n            break;\n        case DualQuat:\n            opt.set_min_objective(minfuncDQ, this);\n            break;\n        case SumSq:\n            opt.set_min_objective(minfuncSumSquared, this);\n            break;\n        case L2:\n            opt.set_min_objective(minfuncL2, this);\n            break;\n        }\n    }\n\n    double NLOPT_IK::minJoints(const std::vector<double> &x, std::vector<double> &grad)\n    {\n        // Actual function to compute the error between the current joint\n        // configuration and the desired.  The SSE is easy to provide a\n        // closed form gradient for.\n\n        bool gradient = !grad.empty();\n\n        double err = 0;\n        for (uint i = 0; i < x.size(); i++)\n        {\n            err += pow(x[i] - des[i], 2);\n            if (gradient)\n                grad[i] = 2.0 * (x[i] - des[i]);\n        }\n\n        return err;\n    }\n\n    void NLOPT_IK::cartSumSquaredError(const std::vector<double> &x, double error[])\n    {\n        // Actual function to compute Euclidean distance error.  This uses\n        // the KDL Forward Kinematics solver to compute the Cartesian pose\n        // of the current joint configuration and compares that to the\n        // desired Cartesian pose for the IK solve.\n\n        if (aborted || progress != -3)\n        {\n            opt.force_stop();\n            return;\n        }\n\n        KDL::JntArray q(x.size());\n\n        for (uint i = 0; i < x.size(); i++)\n            q(i) = x[i];\n\n        int rc = fksolver.JntToCart(q, currentPose);\n\n        if (rc < 0)\n            std::cout << \"KDL FKSolver is failing: \" << q.data;\n\n        if (std::isnan(currentPose.p.x()))\n        {\n            std::cout << \"ERROR :\"\n                      << \"NaNs from NLOpt!!\";\n            error[0] = std::numeric_limits<float>::max();\n            progress = -1;\n            return;\n        }\n\n        KDL::Twist delta_twist = KDL::diffRelative(targetPose, currentPose);\n\n        for (int i = 0; i < 6; i++)\n        {\n            if (std::abs(delta_twist[i]) <= std::abs(bounds[i]))\n                delta_twist[i] = 0.0;\n        }\n\n        error[0] = KDL::dot(delta_twist.vel, delta_twist.vel) + KDL::dot(delta_twist.rot, delta_twist.rot);\n\n        if (KDL::Equal(delta_twist, KDL::Twist::Zero(), eps))\n        {\n            progress = 1;\n            best_x = x;\n            return;\n        }\n    }\n\n    void NLOPT_IK::cartL2NormError(const std::vector<double> &x, double error[])\n    {\n        // Actual function to compute Euclidean distance error.  This uses\n        // the KDL Forward Kinematics solver to compute the Cartesian pose\n        // of the current joint configuration and compares that to the\n        // desired Cartesian pose for the IK solve.\n\n        if (aborted || progress != -3)\n        {\n            opt.force_stop();\n            return;\n        }\n\n        KDL::JntArray q(x.size());\n\n        for (uint i = 0; i < x.size(); i++)\n            q(i) = x[i];\n\n        int rc = fksolver.JntToCart(q, currentPose);\n\n        if (rc < 0)\n            std::cout << \"KDL FKSolver is failing: \" << q.data;\n\n        if (std::isnan(currentPose.p.x()))\n        {\n            std::cout << \"ERROR :\"\n                      << \"NaNs from NLOpt!!\";\n            error[0] = std::numeric_limits<float>::max();\n            progress = -1;\n            return;\n        }\n\n        KDL::Twist delta_twist = KDL::diffRelative(targetPose, currentPose);\n\n        for (int i = 0; i < 6; i++)\n        {\n            if (std::abs(delta_twist[i]) <= std::abs(bounds[i]))\n                delta_twist[i] = 0.0;\n        }\n\n        error[0] = std::sqrt(KDL::dot(delta_twist.vel, delta_twist.vel) + KDL::dot(delta_twist.rot, delta_twist.rot));\n\n        if (KDL::Equal(delta_twist, KDL::Twist::Zero(), eps))\n        {\n            progress = 1;\n            best_x = x;\n            return;\n        }\n    }\n\n    void NLOPT_IK::cartDQError(const std::vector<double> &x, double error[])\n    {\n        // Actual function to compute Euclidean distance error.  This uses\n        // the KDL Forward Kinematics solver to compute the Cartesian pose\n        // of the current joint configuration and compares that to the\n        // desired Cartesian pose for the IK solve.\n\n        if (aborted || progress != -3)\n        {\n            opt.force_stop();\n            return;\n        }\n\n        KDL::JntArray q(x.size());\n\n        for (uint i = 0; i < x.size(); i++)\n            q(i) = x[i];\n\n        int rc = fksolver.JntToCart(q, currentPose);\n\n        if (rc < 0)\n            std::cout << \"KDL FKSolver is failing: \" << q.data;\n\n        if (std::isnan(currentPose.p.x()))\n        {\n            std::cout << \"ERROR :\"\n                      << \"NaNs from NLOpt!!\";\n            error[0] = std::numeric_limits<float>::max();\n            progress = -1;\n            return;\n        }\n\n        KDL::Twist delta_twist = KDL::diffRelative(targetPose, currentPose);\n\n        for (int i = 0; i < 6; i++)\n        {\n            if (std::abs(delta_twist[i]) <= std::abs(bounds[i]))\n                delta_twist[i] = 0.0;\n        }\n\n        math3d::matrix3x3<double> currentRotationMatrix(currentPose.M.data);\n        math3d::quaternion<double> currentQuaternion = math3d::rot_matrix_to_quaternion<double>(currentRotationMatrix);\n        math3d::point3d currentTranslation(currentPose.p.data);\n        dual_quaternion currentDQ = dual_quaternion::rigid_transformation(currentQuaternion, currentTranslation);\n\n        dual_quaternion errorDQ = (currentDQ * !targetDQ).normalize();\n        errorDQ.log();\n        error[0] = 4.0f * dot(errorDQ, errorDQ);\n\n        if (KDL::Equal(delta_twist, KDL::Twist::Zero(), eps))\n        {\n            progress = 1;\n            best_x = x;\n            return;\n        }\n    }\n\n    int NLOPT_IK::CartToJnt(const KDL::JntArray &q_init, const KDL::Frame &p_in, KDL::JntArray &q_out, const KDL::Twist _bounds, const KDL::JntArray &q_desired)\n    {\n        // User command to start an IK solve.  Takes in a seed\n        // configuration, a Cartesian pose, and (optional) a desired\n        // configuration.  If the desired is not provided, the seed is\n        // used.  Outputs the joint configuration found that solves the\n        // IK.\n\n        // Returns -3 if a configuration could not be found within the eps\n        // set up in the constructor.\n\n        boost::posix_time::ptime start_time = boost::posix_time::microsec_clock::local_time();\n        boost::posix_time::time_duration diff;\n\n        bounds = _bounds;\n        q_out = q_init;\n\n        if (chain.getNrOfJoints() < 2)\n        {\n            std::cout << \"ERROR \uff1a\"\n                      << \"NLOpt_IK can only be run for chains of length 2 or more\";\n            return -3;\n        }\n\n        if (q_init.data.size() != types.size())\n        {\n            printf(\" ERROR : IK seeded with wrong number of joints.  Expected %d but got %d\", (int)types.size(), (int)q_init.data.size());\n            return -3;\n        }\n\n        opt.set_maxtime(maxtime);\n\n        double minf; /* the minimum objective value, upon return */\n\n        targetPose = p_in;\n\n        if (TYPE == 1) // DQ\n        {\n            math3d::matrix3x3<double> targetRotationMatrix(targetPose.M.data);\n            math3d::quaternion<double> targetQuaternion = math3d::rot_matrix_to_quaternion<double>(targetRotationMatrix);\n            math3d::point3d targetTranslation(targetPose.p.data);\n            targetDQ = dual_quaternion::rigid_transformation(targetQuaternion, targetTranslation);\n        }\n        // else if (TYPE == 1)\n        // {\n        //   z_target = targetPose*z_up;\n        //   x_target = targetPose*x_out;\n        //   y_target = targetPose*y_out;\n        // }\n\n        //    fksolver.JntToCart(q_init,currentPose);\n\n        std::vector<double> x(chain.getNrOfJoints());\n\n        for (uint i = 0; i < x.size(); i++)\n        {\n            x[i] = q_init(i);\n\n            if (types[i] == KDL::BasicJointType::Continuous)\n                continue;\n\n            if (types[i] == KDL::BasicJointType::TransJoint)\n            {\n                x[i] = std::min(x[i], ub[i]);\n                x[i] = std::max(x[i], lb[i]);\n            }\n            else\n            {\n\n                // Below is to handle bad seeds outside of limits\n\n                if (x[i] > ub[i])\n                {\n                    //Find actual angle offset\n                    double diffangle = fmod(x[i] - ub[i], 2 * M_PI);\n                    // Add that to upper bound and go back a full rotation\n                    x[i] = ub[i] + diffangle - 2 * M_PI;\n                }\n\n                if (x[i] < lb[i])\n                {\n                    //Find actual angle offset\n                    double diffangle = fmod(lb[i] - x[i], 2 * M_PI);\n                    // Subtract that from lower bound and go forward a full rotation\n                    x[i] = lb[i] - diffangle + 2 * M_PI;\n                }\n\n                if (x[i] > ub[i])\n                    x[i] = (ub[i] + lb[i]) / 2.0;\n            }\n        }\n\n        best_x = x;\n        progress = -3;\n\n        std::vector<double> artificial_lower_limits(lb.size());\n\n        for (uint i = 0; i < lb.size(); i++)\n            if (types[i] == KDL::BasicJointType::Continuous)\n                artificial_lower_limits[i] = best_x[i] - 2 * M_PI;\n            else if (types[i] == KDL::BasicJointType::TransJoint)\n                artificial_lower_limits[i] = lb[i];\n            else\n                artificial_lower_limits[i] = std::max(lb[i], best_x[i] - 2 * M_PI);\n\n        opt.set_lower_bounds(artificial_lower_limits);\n\n        std::vector<double> artificial_upper_limits(lb.size());\n\n        for (uint i = 0; i < ub.size(); i++)\n            if (types[i] == KDL::BasicJointType::Continuous)\n                artificial_upper_limits[i] = best_x[i] + 2 * M_PI;\n            else if (types[i] == KDL::BasicJointType::TransJoint)\n                artificial_upper_limits[i] = ub[i];\n            else\n                artificial_upper_limits[i] = std::min(ub[i], best_x[i] + 2 * M_PI);\n\n        opt.set_upper_bounds(artificial_upper_limits);\n\n        if (q_desired.data.size() == 0)\n        {\n            des = x;\n        }\n        else\n        {\n            des.resize(x.size());\n            for (uint i = 0; i < des.size(); i++)\n                des[i] = q_desired(i);\n        }\n\n        try\n        {\n            opt.optimize(x, minf);\n        }\n        catch (...)\n        {\n        }\n\n        if (progress == -1) // Got NaNs\n            progress = -3;\n\n        if (!aborted && progress < 0)\n        {\n\n            double time_left;\n            diff = boost::posix_time::microsec_clock::local_time() - start_time;\n            time_left = maxtime - diff.total_nanoseconds() / 1000000000.0;\n\n            while (time_left > 0 && !aborted && progress < 0)\n            {\n\n                for (uint i = 0; i < x.size(); i++)\n                    x[i] = fRand(artificial_lower_limits[i], artificial_upper_limits[i]);\n\n                opt.set_maxtime(time_left);\n\n                try\n                {\n                    opt.optimize(x, minf);\n                }\n                catch (...)\n                {\n                }\n\n                if (progress == -1) // Got NaNs\n                    progress = -3;\n\n                diff = boost::posix_time::microsec_clock::local_time() - start_time;\n                time_left = maxtime - diff.total_nanoseconds() / 1000000000.0;\n            }\n        }\n\n        for (uint i = 0; i < x.size(); i++)\n        {\n            q_out(i) = best_x[i];\n        }\n\n        return progress;\n    }\n\n}\n", "meta": {"hexsha": "ff6526c72642e09016b6347d22a30079d4caaccd", "size": 20035, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdparty/trac_ik/src/nlopt_ik.cpp", "max_stars_repo_name": "rocos-sia/rocos-app", "max_stars_repo_head_hexsha": "83aa8aa31dd303d77693cfc5ad48055d051fa4bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-12-06T15:30:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T13:21:40.000Z", "max_issues_repo_path": "3rdparty/trac_ik/src/nlopt_ik.cpp", "max_issues_repo_name": "thinkexist1989/rocos-app", "max_issues_repo_head_hexsha": "7d6ab256c8212504b0a8bbe1ec1dea0c41ea3ff2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "3rdparty/trac_ik/src/nlopt_ik.cpp", "max_forks_repo_name": "thinkexist1989/rocos-app", "max_forks_repo_head_hexsha": "7d6ab256c8212504b0a8bbe1ec1dea0c41ea3ff2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.9523026316, "max_line_length": 237, "alphanum_fraction": 0.530122286, "num_tokens": 4893, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4589410400845741}}
{"text": "//\n// Created by Alex Beccaro on 18/01/18.\n//\n\n#define BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n#include \"../../src/problems/1-50/16/problem16.hpp\"\n\nBOOST_AUTO_TEST_SUITE( Problem16 )\n\n    BOOST_AUTO_TEST_CASE( Example ) {\n        auto res = problems::problem16::solve(15);\n        BOOST_CHECK_EQUAL(res, 26);\n    }\n\n    BOOST_AUTO_TEST_CASE( Solution ) {\n        auto res = problems::problem16::solve();\n        BOOST_CHECK_EQUAL(res, 1366);\n    }\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "f8b663b8bef2b032402364db1c1f41929f1be045", "size": 492, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/1-50/test_problem16.cpp", "max_stars_repo_name": "abeccaro/project-euler", "max_stars_repo_head_hexsha": "c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T10:17:15.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-25T10:17:15.000Z", "max_issues_repo_path": "tests/1-50/test_problem16.cpp", "max_issues_repo_name": "abeccaro/project-euler", "max_issues_repo_head_hexsha": "c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3", "max_issues_repo_licenses": ["MIT"], "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/1-50/test_problem16.cpp", "max_forks_repo_name": "abeccaro/project-euler", "max_forks_repo_head_hexsha": "c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.4285714286, "max_line_length": 51, "alphanum_fraction": 0.674796748, "num_tokens": 125, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.45894103661238805}}
{"text": "/**\n\n\\file\n\\author Datta Ramadasan\n//==============================================================================\n//         Copyright 2015 INSTITUT PASCAL UMR 6602 CNRS/Univ. Clermont II\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n\n*/\n\n#ifndef __LMA_OPT2_TRAIT_USE_ESTIMATOR_HPP__\n#define __LMA_OPT2_TRAIT_USE_ESTIMATOR_HPP__\n\n#include <libv/lma/version.hpp>\n\n#include <libv/lma/lm/container/container.hpp>\n#include <boost/type_traits/is_convertible.hpp>\n#include <boost/fusion/include/for_each.hpp>\n#include <boost/mpl/bool.hpp>\n#include <libv/lma/numeric/mediane.hpp>\n#include <iostream>\n\nnamespace lma\n{\n  struct MEstimator_{};\n  \n  template<class Base> struct MEstimator : MEstimator_\n  {\n    Base const& cast() const {return static_cast<Base const &>(*this); }\n    \n    template<class Float, size_t N>\n    Eigen::Matrix<Float,N,1> me(const std::array<Float,N>& res, Float C) const\n    {\n      Eigen::Matrix<Float,N,1> ret;\n      for(size_t i = 0 ; i < N ; ++i)\n        ret[i] = cast().weight(res[i],C);\n      return ret;\n    }\n    \n    template<class Float>\n    Eigen::Matrix<Float,1,1> me(const Float& res,const Float& C) const\n    {\n      Eigen::Matrix<Float,1,1> ret;\n      ret << cast().weight(res,C);\n      return ret;\n    }\n    \n    template<class Float, int N>\n    Eigen::Matrix<Float,N,1> me(const Eigen::Matrix<Float,N,1>& res, Float C) const\n    {\n      Eigen::Matrix<Float,N,1> ret;\n      for(int i = 0 ; i < N ; ++i)\n        ret[i] = cast().weight(res[i],C);\n      return ret;\n    }\n  };\n  \n  namespace detail\n  {\n    template<class F> struct IsMEstimator : boost::is_convertible<F*,MEstimator_*>::type {};\n  \n    template<class W> struct Weight_J\n    {\n      const W& weight;\n      Weight_J(const W& w_):weight(w_){}\n      \n      template<class Pair> void operator()(Pair& pair) const\n      {\n        for(int i = 0 ; i < Rows<decltype(pair.second)>::value ; ++i)\n          for(int j = 0 ; j < Cols<decltype(pair.second)>::value ; ++j)\n            pair.second(i,j) = pair.second(i,j)*weight[i];\n      }\n    };\n\n    template< class F, class Jacobs, class Erreurs, class Mad>\n    void apply_mestimator(const F& f, Jacobs& jacobs, Erreurs& erreur, const Mad& mad, typename boost::enable_if<detail::IsMEstimator<F>>::type* =0)\n    {\n      auto weight  = f.me(erreur,boost::fusion::at_key<F>(mad));\n//       std::cout << \" erreur \" << erreur[0] << \", \" << weight <<  std::endl;\n      cwise_product(erreur,weight,erreur);\n      boost::fusion::for_each(jacobs,Weight_J<decltype(weight)>(weight));\n    }\n    \n    template<class F, class Jacobs, class Erreurs, class Mad> void apply_mestimator(const F&, Jacobs&, Erreurs&, const Mad&,typename boost::disable_if<detail::IsMEstimator<F>>::type* =0) { }\n    \n    template<class F, class Erreurs, class Mad>\n    void apply_mestimator_erreur(const F& f, Erreurs& erreur, const Mad& mad, typename boost::enable_if<detail::IsMEstimator<F>>::type* =0)\n    {\n      auto weight  = f.me(erreur,boost::fusion::at_key<F>(mad));\n      cwise_product(erreur,weight,erreur);\n    }\n    \n    template<class F, class Erreurs, class Mad> void apply_mestimator_erreur(const F&, Erreurs&, const Mad&, typename boost::disable_if<detail::IsMEstimator<F>>::type* =0) { }\n    \n  }\n  \n  \n  template<class Float>\n  struct GermanMcClure : MEstimator<GermanMcClure<Float>>\n  {\n    Float coeff_mad;\n    GermanMcClure(Float a_):coeff_mad(a_){}\n\n    Float weight(const Float& res, const Float& C) const\n    {\n      return (C != 0 ? (C / (res*res+C*C)) : 1.0);\n    }\n    \n    Float compute(std::vector<Float> norms) const\n    {\n      if (norms.empty())\n        return 0;\n\n      Float med = mediane(norms);\n\n      for(Float& m : norms)\n        m = std::abs(m-med);\n      \n      Float MAD = mediane(norms);\n      \n      Float C = med + coeff_mad * MAD;\n      // std::cout << \" C : \" << C << \" = \" << med << \" + \" << coeff_mad << \" * \" << MAD << std::endl;\n      return C;\n    }\n  };\n}\n\n#endif\n", "meta": {"hexsha": "d5eaf23a5088be447e9619f8c9c025bef6655ada", "size": 4152, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/libv/lma/lm/trait/use_estimator.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/trait/use_estimator.hpp", "max_issues_repo_name": "bezout/LMA", "max_issues_repo_head_hexsha": "9555e41eed5f44690c5f6e3ea2d22d520ff1a9d2", "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/trait/use_estimator.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": 31.2180451128, "max_line_length": 190, "alphanum_fraction": 0.58477842, "num_tokens": 1152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.458941033140202}}
{"text": "#ifndef PARTICLES_HPP\n#define PARTICLES_HPP\n\n#include \"integration.hpp\"\n#include <Eigen/Dense>\n#include <vector>\n\nusing namespace Eigen;\n\nclass Particle;\nclass Force;\n\nclass ParticleSystem: public PhysicalSystem {\npublic:\n    std::vector<Particle*> particles;\n    std::vector<Force*> forces;\n    void init();          // initialize the system\n    void step(double dt); // perform a time step of length dt\n    void draw();          // draw everything\n    // PhysicalSystem functions, see integration.hpp\n    int getDOFs();\n    void getState(VectorXd &x, VectorXd &v);\n    void setState(const VectorXd &x, const VectorXd &v);\n    void getInertia(MatrixXd &M);\n    void getForces(VectorXd &f);\n    void getJacobians(MatrixXd &Jx, MatrixXd &Jv);\n};\n\nclass Particle {\npublic:\n\tEIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    int i;      // index\n    double m;   // mass\n    Vector2d x; // position\n    Vector2d v; // velocity\n    Particle(int i, double m, const Vector2d& x, const Vector2d& v): i(i), m(m), x(x), v(v) {}\n    void draw();\n};\n\nclass Force {\npublic:\n\tEIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    virtual void addForces(VectorXd &f) = 0;\n    virtual void addJacobians(MatrixXd &Jx, MatrixXd &Jv) = 0;\n    virtual void draw() = 0;\n};\n\nclass DragForce: public Force {\npublic:\n    ParticleSystem *ps; // apply drag to all particles\n    double kd;          // drag coefficient\n    DragForce(ParticleSystem *ps, double kd): ps(ps), kd(kd) {}\n    void addForces(VectorXd &f);\n    void addJacobians(MatrixXd &Jx, MatrixXd &Jv);\n    void draw();\n};\n\nclass SpringForce: public Force {\n    // connects two particles by a spring\npublic:\n    Particle *p0, *p1; // particles\n    double ks, kd;     // spring constant, damping coefficient\n    double l0;         // rest length\n    SpringForce(Particle *p0, Particle *p1, double ks, double kd, double l0):\n        p0(p0), p1(p1), ks(ks), kd(kd), l0(l0) {}\n    void addForces(VectorXd &f);\n    void addJacobians(MatrixXd &Jx, MatrixXd &Jv);\n    void draw();\n};\n\nclass AnchorForce: public Force {\n    // attaches a particle to a fixed point by a spring\npublic:\n\t\n    Particle *p;   // particle\n    Vector2d x;    // point to anchor it to\n    double ks, kd; // spring constant, damping coefficient\n    AnchorForce(Particle *p, const Vector2d& x, double ks, double kd):\n        p(p), x(x), ks(ks), kd(kd) {}\n    void addForces(VectorXd &f);\n    void addJacobians(MatrixXd &Jx, MatrixXd &Jv);\n    void draw();\n};\n \n#endif\n", "meta": {"hexsha": "7bf4e6c3ad3761d71fe6a1dd348c71c0c8aaeb26", "size": 2439, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "C++/1_MassSpring_Explicit/particles.hpp", "max_stars_repo_name": "mmmovania/ConstrainedDynamicsExperiments", "max_stars_repo_head_hexsha": "9ebcd7256037fb50785bb2a1ddb7473b034a0c5b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2016-08-02T08:15:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-23T09:29:04.000Z", "max_issues_repo_path": "C++/1_MassSpring_Explicit/particles.hpp", "max_issues_repo_name": "mmmovania/ConstrainedDynamicsExperiments", "max_issues_repo_head_hexsha": "9ebcd7256037fb50785bb2a1ddb7473b034a0c5b", "max_issues_repo_licenses": ["Apache-2.0"], "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++/1_MassSpring_Explicit/particles.hpp", "max_forks_repo_name": "mmmovania/ConstrainedDynamicsExperiments", "max_forks_repo_head_hexsha": "9ebcd7256037fb50785bb2a1ddb7473b034a0c5b", "max_forks_repo_licenses": ["Apache-2.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.3604651163, "max_line_length": 94, "alphanum_fraction": 0.6527265273, "num_tokens": 678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.458941033140202}}
{"text": "/*\n    MIT License\n\n    Copyright (c) 2021 Zhepei Wang (wangzhepei@live.com)\n\n    Permission is hereby granted, free of charge, to any person obtaining a copy\n    of this software and associated documentation files (the \"Software\"), to deal\n    in the Software without restriction, including without limitation the rights\n    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n    copies of the Software, and to permit persons to whom the Software is\n    furnished to do so, subject to the following conditions:\n\n    The above copyright notice and this permission notice shall be included in all\n    copies or substantial portions of the Software.\n\n    THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n    SOFTWARE.\n*/\n\n/* This is an old version of FIRI for temporary usage here. */\n\n#ifndef FIRI_HPP\n#define FIRI_HPP\n\n#include \"lbfgs.hpp\"\n#include \"sdlp.hpp\"\n\n#include <Eigen/Eigen>\n\n#include <cstdint>\n#include <cstdio>\n#include <cstdlib>\n#include <cfloat>\n#include <cmath>\n#include <vector>\n\nnamespace firi\n{\n\n    inline void chol3d(const Eigen::Matrix3d &A,\n                       Eigen::Matrix3d &L)\n    {\n        L(0, 0) = sqrt(A(0, 0));\n        L(0, 1) = 0.0;\n        L(0, 2) = 0.0;\n        L(1, 0) = 0.5 * (A(0, 1) + A(1, 0)) / L(0, 0);\n        L(1, 1) = sqrt(A(1, 1) - L(1, 0) * L(1, 0));\n        L(1, 2) = 0.0;\n        L(2, 0) = 0.5 * (A(0, 2) + A(2, 0)) / L(0, 0);\n        L(2, 1) = (0.5 * (A(1, 2) + A(2, 1)) - L(2, 0) * L(1, 0)) / L(1, 1);\n        L(2, 2) = sqrt(A(2, 2) - L(2, 0) * L(2, 0) - L(2, 1) * L(2, 1));\n        return;\n    }\n\n    inline bool smoothedL1(const double &mu,\n                           const double &x,\n                           double &f,\n                           double &df)\n    {\n        if (x < 0.0)\n        {\n            return false;\n        }\n        else if (x > mu)\n        {\n            f = x - 0.5 * mu;\n            df = 1.0;\n            return true;\n        }\n        else\n        {\n            const double xdmu = x / mu;\n            const double sqrxdmu = xdmu * xdmu;\n            const double mumxd2 = mu - 0.5 * x;\n            f = mumxd2 * sqrxdmu * xdmu;\n            df = sqrxdmu * ((-0.5) * xdmu + 3.0 * mumxd2 / mu);\n            return true;\n        }\n    }\n\n    inline double costMVIE(void *data,\n                           const Eigen::VectorXd &x,\n                           Eigen::VectorXd &grad)\n    {\n        const int *pM = (int *)data;\n        const double *pSmoothEps = (double *)(pM + 1);\n        const double *pPenaltyWt = pSmoothEps + 1;\n        const double *pA = pPenaltyWt + 1;\n\n        const int M = *pM;\n        const double smoothEps = *pSmoothEps;\n        const double penaltyWt = *pPenaltyWt;\n        Eigen::Map<const Eigen::MatrixX3d> A(pA, M, 3);\n        Eigen::Map<const Eigen::Vector3d> p(x.data());\n        Eigen::Map<const Eigen::Vector3d> rtd(x.data() + 3);\n        Eigen::Map<const Eigen::Vector3d> cde(x.data() + 6);\n        Eigen::Map<Eigen::Vector3d> gdp(grad.data());\n        Eigen::Map<Eigen::Vector3d> gdrtd(grad.data() + 3);\n        Eigen::Map<Eigen::Vector3d> gdcde(grad.data() + 6);\n\n        double cost = 0;\n        gdp.setZero();\n        gdrtd.setZero();\n        gdcde.setZero();\n\n        Eigen::Matrix3d L;\n        L(0, 0) = rtd(0) * rtd(0) + DBL_EPSILON;\n        L(0, 1) = 0.0;\n        L(0, 2) = 0.0;\n        L(1, 0) = cde(0);\n        L(1, 1) = rtd(1) * rtd(1) + DBL_EPSILON;\n        L(1, 2) = 0.0;\n        L(2, 0) = cde(2);\n        L(2, 1) = cde(1);\n        L(2, 2) = rtd(2) * rtd(2) + DBL_EPSILON;\n\n        const Eigen::MatrixX3d AL = A * L;\n        const Eigen::VectorXd normAL = AL.rowwise().norm();\n        const Eigen::Matrix3Xd adjNormAL = (AL.array().colwise() / normAL.array()).transpose();\n        const Eigen::VectorXd consViola = (normAL + A * p).array() - 1.0;\n\n        double c, dc;\n        Eigen::Vector3d vec;\n        for (int i = 0; i < M; ++i)\n        {\n            if (smoothedL1(smoothEps, consViola(i), c, dc))\n            {\n                cost += c;\n                vec = dc * A.row(i).transpose();\n                gdp += vec;\n                gdrtd += adjNormAL.col(i).cwiseProduct(vec);\n                gdcde(0) += adjNormAL(0, i) * vec(1);\n                gdcde(1) += adjNormAL(1, i) * vec(2);\n                gdcde(2) += adjNormAL(0, i) * vec(2);\n            }\n        }\n        cost *= penaltyWt;\n        gdp *= penaltyWt;\n        gdrtd *= penaltyWt;\n        gdcde *= penaltyWt;\n\n        cost -= log(L(0, 0)) + log(L(1, 1)) + log(L(2, 2));\n        gdrtd(0) -= 1.0 / L(0, 0);\n        gdrtd(1) -= 1.0 / L(1, 1);\n        gdrtd(2) -= 1.0 / L(2, 2);\n\n        gdrtd(0) *= 2.0 * rtd(0);\n        gdrtd(1) *= 2.0 * rtd(1);\n        gdrtd(2) *= 2.0 * rtd(2);\n\n        return cost;\n    }\n\n    // Each row of hPoly is defined by h0, h1, h2, h3 as\n    // h0*x + h1*y + h2*z + h3 <= 0\n    // R, p, r are ALWAYS taken as the initial guess\n    // R is also assumed to be a rotation matrix\n    inline bool maxVolInsEllipsoid(const Eigen::MatrixX4d &hPoly,\n                                   Eigen::Matrix3d &R,\n                                   Eigen::Vector3d &p,\n                                   Eigen::Vector3d &r)\n    {\n        // Find the deepest interior point\n        const int M = hPoly.rows();\n        Eigen::MatrixX4d Alp(M, 4);\n        Eigen::VectorXd blp(M);\n        Eigen::Vector4d clp, xlp;\n        const Eigen::ArrayXd hNorm = hPoly.leftCols<3>().rowwise().norm();\n        Alp.leftCols<3>() = hPoly.leftCols<3>().array().colwise() / hNorm;\n        Alp.rightCols<1>().setConstant(1.0);\n        blp = -hPoly.rightCols<1>().array() / hNorm;\n        clp.setZero();\n        clp(3) = -1.0;\n        const double maxdepth = -sdlp::linprog<4>(clp, Alp, blp, xlp);\n        if (!(maxdepth > 0.0) || std::isinf(maxdepth))\n        {\n            return false;\n        }\n        const Eigen::Vector3d interior = xlp.head<3>();\n\n        // Prepare the data for MVIE optimization\n        uint8_t *optData = new uint8_t[sizeof(int) + (2 + 3 * M) * sizeof(double)];\n        int *pM = (int *)optData;\n        double *pSmoothEps = (double *)(pM + 1);\n        double *pPenaltyWt = pSmoothEps + 1;\n        double *pA = pPenaltyWt + 1;\n\n        *pM = M;\n        Eigen::Map<Eigen::MatrixX3d> A(pA, M, 3);\n        A = Alp.leftCols<3>().array().colwise() /\n            (blp - Alp.leftCols<3>() * interior).array();\n\n        Eigen::VectorXd x(9);\n        const Eigen::Matrix3d Q = R * (r.cwiseProduct(r)).asDiagonal() * R.transpose();\n        Eigen::Matrix3d L;\n        chol3d(Q, L);\n\n        x.head<3>() = p - interior;\n        x(3) = sqrt(L(0, 0));\n        x(4) = sqrt(L(1, 1));\n        x(5) = sqrt(L(2, 2));\n        x(6) = L(1, 0);\n        x(7) = L(2, 1);\n        x(8) = L(2, 0);\n\n        double minCost;\n        lbfgs::lbfgs_parameter_t paramsMVIE;\n        paramsMVIE.mem_size = 18;\n        paramsMVIE.g_epsilon = 0.0;\n        paramsMVIE.min_step = 1.0e-32;\n        paramsMVIE.past = 3;\n        paramsMVIE.delta = 1.0e-7;\n        *pSmoothEps = 1.0e-2;\n        *pPenaltyWt = 1.0e+3;\n\n        int ret = lbfgs::lbfgs_optimize(x,\n                                        minCost,\n                                        &costMVIE,\n                                        nullptr,\n                                        nullptr,\n                                        optData,\n                                        paramsMVIE);\n\n        if (ret < 0)\n        {\n            printf(\"FIRI WARNING: %s\\n\", lbfgs::lbfgs_strerror(ret));\n        }\n\n        p = x.head<3>() + interior;\n        L(0, 0) = x(3) * x(3);\n        L(0, 1) = 0.0;\n        L(0, 2) = 0.0;\n        L(1, 0) = x(6);\n        L(1, 1) = x(4) * x(4);\n        L(1, 2) = 0.0;\n        L(2, 0) = x(8);\n        L(2, 1) = x(7);\n        L(2, 2) = x(5) * x(5);\n        Eigen::JacobiSVD<Eigen::Matrix3d, Eigen::FullPivHouseholderQRPreconditioner> svd(L, Eigen::ComputeFullU);\n        const Eigen::Matrix3d U = svd.matrixU();\n        const Eigen::Vector3d S = svd.singularValues();\n        if (U.determinant() < 0.0)\n        {\n            R.col(0) = U.col(1);\n            R.col(1) = U.col(0);\n            R.col(2) = U.col(2);\n            r(0) = S(1);\n            r(1) = S(0);\n            r(2) = S(2);\n        }\n        else\n        {\n            R = U;\n            r = S;\n        }\n\n        delete[] optData;\n\n        return ret >= 0;\n    }\n\n    inline bool firi(const Eigen::MatrixX4d &bd,\n                     const Eigen::Matrix3Xd &pc,\n                     const Eigen::Vector3d &a,\n                     const Eigen::Vector3d &b,\n                     Eigen::MatrixX4d &hPoly,\n                     const int iterations = 4,\n                     const double epsilon = 1.0e-6)\n    {\n        const Eigen::Vector4d ah(a(0), a(1), a(2), 1.0);\n        const Eigen::Vector4d bh(b(0), b(1), b(2), 1.0);\n\n        if ((bd * ah).maxCoeff() > 0.0 ||\n            (bd * bh).maxCoeff() > 0.0)\n        {\n            return false;\n        }\n\n        const int M = bd.rows();\n        const int N = pc.cols();\n\n        Eigen::Matrix3d R = Eigen::Matrix3d::Identity();\n        Eigen::Vector3d p = 0.5 * (a + b);\n        Eigen::Vector3d r = Eigen::Vector3d::Ones();\n        Eigen::MatrixX4d forwardH(M + N, 4);\n        int nH = 0;\n\n        for (int loop = 0; loop < iterations; ++loop)\n        {\n            const Eigen::Matrix3d forward = r.cwiseInverse().asDiagonal() * R.transpose();\n            const Eigen::Matrix3d backward = R * r.asDiagonal();\n            const Eigen::MatrixX3d forwardB = bd.leftCols<3>() * backward;\n            const Eigen::VectorXd forwardD = bd.rightCols<1>() + bd.leftCols<3>() * p;\n            const Eigen::Matrix3Xd forwardPC = forward * (pc.colwise() - p);\n            const Eigen::Vector3d fwd_a = forward * (a - p);\n            const Eigen::Vector3d fwd_b = forward * (b - p);\n\n            const Eigen::VectorXd distDs = forwardD.cwiseAbs().cwiseQuotient(forwardB.rowwise().norm());\n            Eigen::MatrixX4d tangents(N, 4);\n            Eigen::VectorXd distRs(N);\n\n            for (int i = 0; i < N; i++)\n            {\n                distRs(i) = forwardPC.col(i).norm();\n                tangents(i, 3) = -distRs(i);\n                tangents.block<1, 3>(i, 0) = forwardPC.col(i).transpose() / distRs(i);\n                if (tangents.block<1, 3>(i, 0).dot(fwd_a) + tangents(i, 3) > epsilon)\n                {\n                    const Eigen::Vector3d delta = forwardPC.col(i) - fwd_a;\n                    tangents.block<1, 3>(i, 0) = fwd_a - (delta.dot(fwd_a) / delta.squaredNorm()) * delta;\n                    distRs(i) = tangents.block<1, 3>(i, 0).norm();\n                    tangents(i, 3) = -distRs(i);\n                    tangents.block<1, 3>(i, 0) /= distRs(i);\n                }\n                if (tangents.block<1, 3>(i, 0).dot(fwd_b) + tangents(i, 3) > epsilon)\n                {\n                    const Eigen::Vector3d delta = forwardPC.col(i) - fwd_b;\n                    tangents.block<1, 3>(i, 0) = fwd_b - (delta.dot(fwd_b) / delta.squaredNorm()) * delta;\n                    distRs(i) = tangents.block<1, 3>(i, 0).norm();\n                    tangents(i, 3) = -distRs(i);\n                    tangents.block<1, 3>(i, 0) /= distRs(i);\n                }\n                if (tangents.block<1, 3>(i, 0).dot(fwd_a) + tangents(i, 3) > epsilon)\n                {\n                    tangents.block<1, 3>(i, 0) = (fwd_a - forwardPC.col(i)).cross(fwd_b - forwardPC.col(i)).normalized();\n                    tangents(i, 3) = -tangents.block<1, 3>(i, 0).dot(fwd_a);\n                    tangents.row(i) *= tangents(i, 3) > 0.0 ? -1.0 : 1.0;\n                }\n            }\n\n            Eigen::Matrix<uint8_t, -1, 1> bdFlags = Eigen::Matrix<uint8_t, -1, 1>::Constant(M, 1);\n            Eigen::Matrix<uint8_t, -1, 1> pcFlags = Eigen::Matrix<uint8_t, -1, 1>::Constant(N, 1);\n\n            nH = 0;\n\n            bool completed = false;\n            int bdMinId, pcMinId;\n            double minSqrD = distDs.minCoeff(&bdMinId);\n            double minSqrR = distRs.minCoeff(&pcMinId);\n            for (int i = 0; !completed && i < (M + N); ++i)\n            {\n                bdMinId = bdMinId;\n                pcMinId = pcMinId;\n                if (minSqrD < minSqrR)\n                {\n                    forwardH.block<1, 3>(nH, 0) = forwardB.row(bdMinId);\n                    forwardH(nH, 3) = forwardD(bdMinId);\n                    bdFlags(bdMinId) = 0;\n                }\n                else\n                {\n                    forwardH.row(nH) = tangents.row(pcMinId);\n                    pcFlags(pcMinId) = 0;\n                }\n\n                completed = true;\n                minSqrD = INFINITY;\n                for (int j = 0; j < M; ++j)\n                {\n                    if (bdFlags(j))\n                    {\n                        completed = false;\n                        if (minSqrD > distDs(j))\n                        {\n                            bdMinId = j;\n                            minSqrD = distDs(j);\n                        }\n                    }\n                }\n                minSqrR = INFINITY;\n                for (int j = 0; j < N; ++j)\n                {\n                    if (pcFlags(j))\n                    {\n                        if (forwardH.block<1, 3>(nH, 0).dot(forwardPC.col(j)) + forwardH(nH, 3) > -epsilon)\n                        {\n                            pcFlags(j) = 0;\n                        }\n                        else\n                        {\n                            completed = false;\n                            if (minSqrR > distRs(j))\n                            {\n                                pcMinId = j;\n                                minSqrR = distRs(j);\n                            }\n                        }\n                    }\n                }\n                ++nH;\n            }\n\n            hPoly.resize(nH, 4);\n            for (int i = 0; i < nH; ++i)\n            {\n                hPoly.block<1, 3>(i, 0) = forwardH.block<1, 3>(i, 0) * forward;\n                hPoly(i, 3) = forwardH(i, 3) - hPoly.block<1, 3>(i, 0).dot(p);\n            }\n\n            if (loop == iterations - 1)\n            {\n                break;\n            }\n\n            maxVolInsEllipsoid(hPoly, R, p, r);\n        }\n\n        return true;\n    }\n\n}\n\n#endif\n", "meta": {"hexsha": "a1954abbf5c0eb5db1a3345e7efe12a37c3b323f", "size": 14638, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "gcopter/include/gcopter/firi.hpp", "max_stars_repo_name": "edmundwsy/GCOPTER", "max_stars_repo_head_hexsha": "97281f671f51ea211308f32aac6f82ff4f9a22a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-28T11:17:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T11:17:51.000Z", "max_issues_repo_path": "gcopter/include/gcopter/firi.hpp", "max_issues_repo_name": "edmundwsy/GCOPTER", "max_issues_repo_head_hexsha": "97281f671f51ea211308f32aac6f82ff4f9a22a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gcopter/include/gcopter/firi.hpp", "max_forks_repo_name": "edmundwsy/GCOPTER", "max_forks_repo_head_hexsha": "97281f671f51ea211308f32aac6f82ff4f9a22a0", "max_forks_repo_licenses": ["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.9355608592, "max_line_length": 121, "alphanum_fraction": 0.449310015, "num_tokens": 4437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.458941033140202}}
{"text": "/*=============================================================================\nCopyright 2019 Sarthak Singhal <singhalsarthak2007@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#define BOOST_TEST_MODULE cartesian_differential_test\n\n#include <boost/test/unit_test.hpp>\n#include <boost/units/quantity.hpp>\n#include <boost/units/systems/si/plane_angle.hpp>\n#include <boost/units/systems/si/prefixes.hpp>\n#include <boost/units/systems/si/length.hpp>\n#include <boost/units/systems/si/velocity.hpp>\n#include <boost/units/systems/si/time.hpp>\n#include <boost/units/systems/angle/degrees.hpp>\n#include <boost/astronomy/coordinate/arithmetic.hpp>\n#include <boost/astronomy/coordinate/diff/differential.hpp>\n\nusing namespace std;\nusing namespace boost::astronomy::coordinate;\nusing namespace boost::units::si;\nusing namespace boost::geometry;\nusing namespace boost::units;\nnamespace bud = boost::units::degree;\n\nBOOST_AUTO_TEST_SUITE(cartesian_differential_constructor)\n\nBOOST_AUTO_TEST_CASE(cartesian_differential_default_constructor)\n{\n    //using set functions\n    cartesian_differential<double, quantity<si::velocity>, quantity<si::velocity>,\n    quantity<si::velocity>> motion1;\n    motion1.set_dx_dy_dz(2.5*meters/seconds, 91.0*meters/seconds, 12.0*meters/seconds);\n    BOOST_CHECK_CLOSE(motion1.get_dx().value(), 2.5, 0.001);\n    BOOST_CHECK_CLOSE(motion1.get_dy().value(), 91.0, 0.001);\n    BOOST_CHECK_CLOSE(motion1.get_dz().value(), 12, 0.001);\n\n    //checking whether quantity stored is as expected or not\n    BOOST_TEST((std::is_same<decltype(motion1.get_dx()), quantity<si::velocity>>::value));\n    BOOST_TEST((std::is_same<decltype(motion1.get_dy()), quantity<si::velocity>>::value));\n    BOOST_TEST((std::is_same<decltype(motion1.get_dz()), quantity<si::velocity>>::value));\n}\n\nBOOST_AUTO_TEST_CASE(cartesian_differential_quantities_constructor)\n{\n    //checking construction from value\n    auto motion1 = make_cartesian_differential\n    (1.5*meters/seconds, 9.0*si::kilo*meters/seconds, 3.0*meters/seconds);\n    BOOST_CHECK_CLOSE(motion1.get_dx().value(), 1.5, 0.001);\n    BOOST_CHECK_CLOSE(motion1.get_dy().value(), 9.0, 0.001);\n    BOOST_CHECK_CLOSE(motion1.get_dz().value(), 3, 0.001);\n\n    //checking whether quantity stored is as expected or not\n    BOOST_TEST((std::is_same<decltype(motion1.get_dx()), quantity<si::velocity>>::value));\n    BOOST_TEST((std::is_same<decltype(motion1.get_dy()),\n        quantity<bu::divide_typeof_helper<decltype(si::kilo*meters), si::time>::type>>::value));\n    BOOST_TEST((std::is_same<decltype(motion1.get_dz()), quantity<si::velocity>>::value));\n\n    cartesian_differential<double, quantity<si::velocity>, quantity<si::velocity>, quantity<si::velocity>>\n        motion2(1.5*meters/seconds, 9.0*meters/seconds, 3.0*meters/seconds);\n    BOOST_CHECK_CLOSE(motion2.get_dx().value(), 1.5, 0.001);\n    BOOST_CHECK_CLOSE(motion2.get_dy().value(), 9.0, 0.001);\n    BOOST_CHECK_CLOSE(motion2.get_dz().value(), 3, 0.001);\n\n    //checking whether quantity stored is as expected or not\n    BOOST_TEST((std::is_same<decltype(motion2.get_dx()), quantity<si::velocity>>::value));\n    BOOST_TEST((std::is_same<decltype(motion2.get_dy()), quantity<si::velocity>>::value));\n    BOOST_TEST((std::is_same<decltype(motion2.get_dz()), quantity<si::velocity>>::value));\n}\n\nBOOST_AUTO_TEST_CASE(cartesian_differential_copy_constructor)\n{\n    //checking construction from value\n    auto motion1 = make_cartesian_differential\n    (1.5*meters/seconds, 9.0*si::kilo*meters/seconds, 3.0*meters/seconds);\n    BOOST_CHECK_CLOSE(motion1.get_dx().value(), 1.5, 0.001);\n    BOOST_CHECK_CLOSE(motion1.get_dy().value(), 9.0, 0.001);\n    BOOST_CHECK_CLOSE(motion1.get_dz().value(), 3, 0.001);\n\n    //checking whether quantity stored is as expected or not\n    BOOST_TEST((std::is_same<decltype(motion1.get_dx()), quantity<si::velocity>>::value));\n    BOOST_TEST((std::is_same<decltype(motion1.get_dy()),\n        quantity<bu::divide_typeof_helper<decltype(si::kilo*meters), si::time>::type>>::value));\n    BOOST_TEST((std::is_same<decltype(motion1.get_dz()), quantity<si::velocity>>::value));\n\n    //copy constructor\n    auto motion2 = make_cartesian_differential(motion1);\n    BOOST_CHECK_CLOSE(motion1.get_dx().value(), motion2.get_dx().value(), 0.001);\n    BOOST_CHECK_CLOSE(motion1.get_dy().value(), motion2.get_dy().value(), 0.001);\n    BOOST_CHECK_CLOSE(motion1.get_dz().value(), motion2.get_dz().value(), 0.001);\n\n    //checking whether quantity stored is as expected or not\n    BOOST_TEST((std::is_same<decltype(motion2.get_dx()), quantity<si::velocity>>::value));\n    BOOST_TEST((std::is_same<decltype(motion2.get_dy()),\n        quantity<bu::divide_typeof_helper<decltype(si::kilo*meters), si::time>::type>>::value));\n    BOOST_TEST((std::is_same<decltype(motion2.get_dz()), quantity<si::velocity>>::value));\n\n    cartesian_differential<double, quantity<bu::divide_typeof_helper<si::length, si::time>::\n        type>, quantity<bu::divide_typeof_helper<decltype(si::kilo*meters), si::time>::type>, quantity\n        <si::velocity>> motion3(motion1);\n    BOOST_CHECK_CLOSE(motion1.get_dx().value(), motion3.get_dx().value(), 0.001);\n    BOOST_CHECK_CLOSE(motion1.get_dy().value(), motion3.get_dy().value(), 0.001);\n    BOOST_CHECK_CLOSE(motion1.get_dz().value(), motion3.get_dz().value(), 0.001);\n\n    //checking whether quantity stored is as expected or not\n    BOOST_TEST((std::is_same<decltype(motion3.get_dx()), quantity<si::velocity>>::value));\n    BOOST_TEST((std::is_same<decltype(motion3.get_dy()),\n        quantity<bu::divide_typeof_helper<decltype(si::kilo*meters), si::time>::type>>::value));\n    BOOST_TEST((std::is_same<decltype(motion3.get_dz()), quantity<si::velocity>>::value));\n}\n\nBOOST_AUTO_TEST_CASE(cartesian_differential_copy_constructor_with_different_units)\n{\n    //checking construction from value\n    auto motion1 = make_cartesian_differential\n    (1.5*meters/seconds, 9.0*si::kilo*meters/seconds, 3.0*meters/seconds);\n    BOOST_CHECK_CLOSE(motion1.get_dx().value(), 1.5, 0.001);\n    BOOST_CHECK_CLOSE(motion1.get_dy().value(), 9.0, 0.001);\n    BOOST_CHECK_CLOSE(motion1.get_dz().value(), 3, 0.001);\n\n    //checking whether quantity stored is as expected or not\n    BOOST_TEST((std::is_same<decltype(motion1.get_dx()), quantity<si::velocity>>::value));\n    BOOST_TEST((std::is_same<decltype(motion1.get_dy()),\n        quantity<bu::divide_typeof_helper<decltype(si::kilo*meters), si::time>::type>>::value));\n    BOOST_TEST((std::is_same<decltype(motion1.get_dz()), quantity<si::velocity>>::value));\n\n    // //Conversion from one unit type to other\n    auto motion2 = make_cartesian_differential\n    <double, quantity<si::velocity>, quantity<si::velocity>, quantity<si::velocity>>(motion1);\n    BOOST_CHECK_CLOSE(motion2.get_dx().value(), 1.5, 0.001);\n    BOOST_CHECK_CLOSE(motion2.get_dy().value(), 9000.0, 0.001);\n    BOOST_CHECK_CLOSE(motion2.get_dz().value(), 3, 0.001);\n\n    //checking whether quantity stored is as expected or not\n    BOOST_TEST((std::is_same<decltype(motion2.get_dx()), quantity<si::velocity>>::value));\n    BOOST_TEST((std::is_same<decltype(motion2.get_dy()), quantity<si::velocity>>::value));\n    BOOST_TEST((std::is_same<decltype(motion2.get_dz()), quantity<si::velocity>>::value));\n}\n\nBOOST_AUTO_TEST_CASE(cartesian_differential_geometry_point_constructor)\n{\n    //constructing from boost::geometry::model::motion\n    model::point<double, 3, cs::spherical<boost::geometry::degree>> model_point(30, 60, 1);\n    auto motion1 = make_cartesian_differential\n    <double,quantity<si::velocity>,quantity<si::velocity>,quantity<si::velocity>>(model_point);\n    BOOST_CHECK_CLOSE(motion1.get_dx().value(), 0.75, 0.001);\n    BOOST_CHECK_CLOSE(motion1.get_dy().value(), 0.4330127019, 0.001);\n    BOOST_CHECK_CLOSE(motion1.get_dz().value(), 0.5, 0.001);\n\n    //checking whether quantity stored is as expected or not\n    BOOST_TEST((std::is_same<decltype(motion1.get_dx()), quantity<si::velocity>>::value));\n    BOOST_TEST((std::is_same<decltype(motion1.get_dy()), quantity<si::velocity>>::value));\n    BOOST_TEST((std::is_same<decltype(motion1.get_dz()), quantity<si::velocity>>::value));\n\n    cartesian_differential<double, quantity<si::velocity>, quantity<si::velocity>,\n    quantity<si::velocity>> motion2(model_point);\n    BOOST_CHECK_CLOSE(motion2.get_dx().value(), 0.75, 0.001);\n    BOOST_CHECK_CLOSE(motion2.get_dy().value(), 0.4330127019, 0.001);\n    BOOST_CHECK_CLOSE(motion2.get_dz().value(), 0.5, 0.001);\n\n    //checking whether quantity stored is as expected or not\n    BOOST_TEST((std::is_same<decltype(motion2.get_dx()), quantity<si::velocity>>::value));\n    BOOST_TEST((std::is_same<decltype(motion2.get_dy()), quantity<si::velocity>>::value));\n    BOOST_TEST((std::is_same<decltype(motion2.get_dz()), quantity<si::velocity>>::value));\n}\n\nBOOST_AUTO_TEST_CASE(cartesian_differential_conversion_from_spherical_differential)\n{\n    //constructing from spherical differential\n    auto spherical_motion = make_spherical_differential\n    (0.523599 * si::radian, 60.0 * bud::degrees, 1.0 * meters/seconds);\n    auto motion1 = make_cartesian_differential(spherical_motion);\n    BOOST_CHECK_CLOSE(motion1.get_dx().value(), 0.75, 0.001);\n    BOOST_CHECK_CLOSE(motion1.get_dy().value(), 0.4330127019, 0.001);\n    BOOST_CHECK_CLOSE(motion1.get_dz().value(), 0.5, 0.001);\n\n    //checking whether quantity stored is as expected or not\n    BOOST_TEST((std::is_same<decltype(motion1.get_dx()), quantity<si::velocity>>::value));\n    BOOST_TEST((std::is_same<decltype(motion1.get_dy()), quantity<si::velocity>>::value));\n    BOOST_TEST((std::is_same<decltype(motion1.get_dz()), quantity<si::velocity>>::value));\n}\n\nBOOST_AUTO_TEST_CASE(cartesian_differential_conversion_from_spherical_equatorial_differential)\n{\n    //constructing from spherical_equitorial differential\n    auto spherical_equatorial_motion = make_spherical_equatorial_differential\n    (0.523599 * si::radian, 60.0 * bud::degrees, 1.0 * meters/seconds);\n    auto motion2 = make_cartesian_differential(spherical_equatorial_motion);\n    BOOST_CHECK_CLOSE(motion2.get_dx().value(), 0.433012646, 0.001);\n    BOOST_CHECK_CLOSE(motion2.get_dy().value(), 0.250000097, 0.001);\n    BOOST_CHECK_CLOSE(motion2.get_dz().value(), 0.866025405, 0.001);\n\n    //checking whether quantity stored is as expected or not\n    BOOST_TEST((std::is_same<decltype(motion2.get_dx()), quantity<si::velocity>>::value));\n    BOOST_TEST((std::is_same<decltype(motion2.get_dy()), quantity<si::velocity>>::value));\n    BOOST_TEST((std::is_same<decltype(motion2.get_dz()), quantity<si::velocity>>::value));\n}\n\nBOOST_AUTO_TEST_CASE(cartesian_differential_conversion_from_spherical_coslat_differential)\n{\n    //constructing from spherical_coslat differential\n    auto spherical_coslat_motion = make_spherical_coslat_differential\n    (0.523599 * si::radian, 60.0 * bud::degrees, 1.0 * meters/seconds);\n    auto motion3 = make_cartesian_differential(spherical_coslat_motion);\n    BOOST_CHECK_CLOSE(motion3.get_dx().value(), 0.8100222, 0.001);\n    BOOST_CHECK_CLOSE(motion3.get_dy().value(), 0.467666778, 0.001);\n    BOOST_CHECK_CLOSE(motion3.get_dz().value(), 0.353768031, 0.001);\n\n    //checking whether quantity stored is as expected or not\n    BOOST_TEST((std::is_same<decltype(motion3.get_dx()), quantity<si::velocity>>::value));\n    BOOST_TEST((std::is_same<decltype(motion3.get_dy()), quantity<si::velocity>>::value));\n    BOOST_TEST((std::is_same<decltype(motion3.get_dz()), quantity<si::velocity>>::value));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\nBOOST_AUTO_TEST_SUITE(cartesian_differential_operators)\n\nBOOST_AUTO_TEST_CASE(cartesian_differential_addition_operator)\n{\n    auto motion1 = make_cartesian_differential\n        (11.0*meters/seconds, 15.0*meters/seconds, 19.0*meters/seconds);\n    auto motion2 = make_cartesian_differential\n        (6.0*si::milli*meters/seconds, 10.0*si::centi*meters/seconds, 11.0*meters/seconds);\n\n    auto sum = make_cartesian_differential(motion1 + motion2);\n\n    BOOST_CHECK_CLOSE(sum.get_dx().value(), 11.006, 0.001);\n    BOOST_CHECK_CLOSE(sum.get_dy().value(), 15.1, 0.001);\n    BOOST_CHECK_CLOSE(sum.get_dz().value(), 30, 0.001);\n\n    //checking whether quantity stored is as expected or not\n    BOOST_TEST((std::is_same<decltype(sum.get_dx()), quantity<si::velocity>>::value));\n    BOOST_TEST((std::is_same<decltype(sum.get_dy()), quantity<si::velocity>>::value));\n    BOOST_TEST((std::is_same<decltype(sum.get_dz()), quantity<si::velocity>>::value));\n}\n\nBOOST_AUTO_TEST_CASE(cartesian_differential_multiplication_operator)\n{\n    auto motion1 = make_cartesian_differential\n        (3.0*meters/seconds, 9.0*meters/seconds, 6.0*meters/seconds);\n\n    auto product = make_cartesian_differential\n        (motion1 * quantity<si::time>(5*seconds));\n\n    BOOST_CHECK_CLOSE(product.get_dx().value(), 15.0, 0.001);\n    BOOST_CHECK_CLOSE(product.get_dy().value(), 45.0, 0.001);\n    BOOST_CHECK_CLOSE(product.get_dz().value(), 30.0, 0.001);\n\n    //checking whether quantity stored is as expected or not\n    BOOST_TEST((std::is_same<decltype(product.get_dx()), quantity<si::length>>::value));\n    BOOST_TEST((std::is_same<decltype(product.get_dy()), quantity<si::length>>::value));\n    BOOST_TEST((std::is_same<decltype(product.get_dz()), quantity<si::length>>::value));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n", "meta": {"hexsha": "ee84c8ea2585eebab309b3a714f98de558a99f0f", "size": 13498, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/coordinate/cartesian_differential.cpp", "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": "test/coordinate/cartesian_differential.cpp", "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": "test/coordinate/cartesian_differential.cpp", "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": 51.9153846154, "max_line_length": 106, "alphanum_fraction": 0.7213661283, "num_tokens": 3619, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.45894103314020196}}
{"text": "#include <boost/container/flat_map.hpp>\n#include <boost/container/static_vector.hpp>\n#include <map>\n#include <forward_list>\n#include <chrono>\n#include <deque>\n#include <iomanip>\n#include <iostream>\n#include <list>\n#include <string>\n#include <vector>\n#include <numeric>\n#include <random>\n\nconst int SIZE = 100'000'000; \n\n// function by Rainer Grimm\ntemplate <typename T>\nvoid accumContainer(const T& t, const std::string& cont){\n  \n  std::cout << std::fixed << std::setprecision(10);\n\n  auto begin= std::chrono::steady_clock::now();\n  std::size_t res = std::accumulate(t.begin(), t.end(), 0LL);\n  std::chrono::duration<double> last=  std::chrono::steady_clock::now() - begin;\n  std::cout << cont << \" with std::accumulate\" <<  std::endl;\n  std::cout << \"accumulate time: \" << last.count() << std::endl;\n  std::cout << \"res: \" << res << std::endl;\n  std::cout << std::endl;\n \n  std::cout << std::endl;\n     \n}\n\ntemplate <typename T>\nvoid sumContainer(const T& t, const std::string& cont){\n  \n   std::cout << std::fixed << std::setprecision(10);\n\n   auto begin= std::chrono::steady_clock::now();\n   size_t res{0};\n   for (int n : t){\n      res += n;\n   }\n   std::chrono::duration<double> last=  std::chrono::steady_clock::now() - begin;\n   std::cout << cont << \" foreach loop\" <<  std::endl;\n   std::cout << \"sum time: \" << last.count() << std::endl;\n   std::cout << \"res: \" << res << std::endl;\n   std::cout << std::endl;\n \n   std::cout << std::endl;\n     \n}\n\ntemplate <typename T>\nvoid sumContainerData(const T& t, const std::string& cont){\n  \n   std::cout << std::fixed << std::setprecision(10);\n\n   auto begin= std::chrono::steady_clock::now();\n   size_t res{0};\n   for (int i=0; i < SIZE; ++i){\n      res += t[i];\n   }\n   std::chrono::duration<double> last=  std::chrono::steady_clock::now() - begin;\n   std::cout << cont << \" loop over container indices\" <<  std::endl;\n   std::cout << \"sum time: \" << last.count() << std::endl;\n   std::cout << \"res: \" << res << std::endl;\n   std::cout << std::endl;\n \n   std::cout << std::endl;\n     \n}\n\ntemplate <typename T>\nvoid sumContainerDataPtr(const T& t, const std::string& cont){\n  \n   std::cout << std::fixed << std::setprecision(10);\n\n   auto begin= std::chrono::steady_clock::now();\n   const int* ptr = t.data();\n   size_t res{0};\n   for (int i=0; i < SIZE; ++i){\n      res += ptr[i];\n   }\n   std::chrono::duration<double> last=  std::chrono::steady_clock::now() - begin;\n   std::cout << cont << \" loop over indices into .data() pointer\" <<  std::endl;\n   std::cout << \"sum time: \" << last.count() << std::endl;\n   std::cout << \"res: \" << res << std::endl;\n   std::cout << std::endl;\n \n   std::cout << std::endl;\n     \n}\n\nvoid sumCArray(int* t, const std::string& cont){\n  \n   std::cout << std::fixed << std::setprecision(10);\n\n   auto begin= std::chrono::steady_clock::now();\n   size_t res{0};\n   for (int i=0; i < SIZE; ++i){\n      res += t[i];\n   }\n   std::chrono::duration<double> last=  std::chrono::steady_clock::now() - begin;\n   std::cout << cont <<  std::endl;\n   std::cout << \"sum time: \" << last.count() << std::endl;\n   std::cout << \"res: \" << res << std::endl;\n   std::cout << std::endl;\n \n   std::cout << std::endl;\n     \n}\n\n\nint main(){\n    \n    std::cout << std::endl;\n    \n    std::random_device seed;\n    std::mt19937 engine(seed());\n    std::uniform_int_distribution<int> dist(0, 100);\n    std::vector<int> randNumbers;\n    randNumbers.reserve(SIZE);\n    for (int i=0; i < SIZE; ++i){\n        randNumbers.push_back(dist(engine));\n    }\n    \n    auto begin= std::chrono::steady_clock::now();\n    std::chrono::duration<double> last=  std::chrono::steady_clock::now() - begin;\n    {\n      begin = std::chrono::steady_clock::now();\n      std::vector<int> myVec(randNumbers.begin(), randNumbers.end());\n      std::chrono::duration<double> last=  std::chrono::steady_clock::now() - begin;\n      std::cout << \"************ Time to create and fill std::vector<int>: \" << last.count() << std::endl;\n      accumContainer(myVec,\"std::vector<int>\");\n      sumContainer(myVec,\"std::vector<int>\");\n      sumContainerData(myVec,\"std::vector<int>\");\n      sumContainerDataPtr(myVec,\"std::vector<int>\");\n      sumCArray(myVec.data(),\"std::vector<int>.data()\");\n    }\n\n    {\n       begin = std::chrono::steady_clock::now();\n       boost::container::static_vector<int, SIZE> myVec(randNumbers.begin(), randNumbers.end());\n       std::chrono::duration<double> last=  std::chrono::steady_clock::now() - begin;\n       std::cout << \"************ Time to create and fill boost::container::static_vector<int,SIZE>: \" << last.count() << std::endl;\n       accumContainer(myVec,\"boost::container::static_vector<int>\");\n    }\n\n    {\n       begin = std::chrono::steady_clock::now();\n       std::array<int, SIZE> stdArray;\n       int counter = 0;\n       int next_counter = 10;\n       for (int i=0; i < SIZE; ++i){\n          stdArray[i] = randNumbers[i];\n       }\n       std::chrono::duration<double> last=  std::chrono::steady_clock::now() - begin;\n       std::cout << \"************ Time to create and fill std::array<int>: \" << last.count() << std::endl;\n       accumContainer(stdArray,\"std::array<int>\");  // (6)\n    }\n\n    {\n       begin = std::chrono::steady_clock::now();\n       int stackArray[SIZE];\n       int counter = 0;\n       int next_counter = 10;\n       for (int i=0; i < SIZE; ++i){\n          stackArray[i] = randNumbers[i];\n       }\n       std::chrono::duration<double> last=  std::chrono::steady_clock::now() - begin;\n       std::cout << \"************ Time to create and fill stack C array: \" << last.count() << std::endl;\n       sumCArray(stackArray,\"stack C array<int>\");  // (7)\n    }\n\n    {\n       begin = std::chrono::steady_clock::now();\n       int *heapArray = (int*)malloc(sizeof(int)*SIZE);\n       int counter = 0;\n       int next_counter = 10;\n       for (int i=0; i < SIZE; ++i){\n          heapArray[i] = randNumbers[i];\n       }\n       std::chrono::duration<double> last=  std::chrono::steady_clock::now() - begin;\n       std::cout << \"************ Time to create and fill heap C array: \" << last.count() << std::endl;\n       sumCArray(heapArray,\"heap C array<int>\");  // (8)\n    }\n  \n}\n\n\n", "meta": {"hexsha": "9a96374cbd44405a2b0b0a61a4c12ba49e0a21a2", "size": 6155, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "vector_speed_test.cpp", "max_stars_repo_name": "lshort/cpp_container_speed_tests", "max_stars_repo_head_hexsha": "963e7740e046cc29c79544128e7be724b34e031d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "vector_speed_test.cpp", "max_issues_repo_name": "lshort/cpp_container_speed_tests", "max_issues_repo_head_hexsha": "963e7740e046cc29c79544128e7be724b34e031d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vector_speed_test.cpp", "max_forks_repo_name": "lshort/cpp_container_speed_tests", "max_forks_repo_head_hexsha": "963e7740e046cc29c79544128e7be724b34e031d", "max_forks_repo_licenses": ["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.8911917098, "max_line_length": 132, "alphanum_fraction": 0.5785540211, "num_tokens": 1743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.7461389817407016, "lm_q1q2_score": 0.4589410261958296}}
{"text": "/*\n\tThis file is part of cpp-ethereum.\n\n\tcpp-ethereum 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\tcpp-ethereum 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 cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.\n*/\n/** @file QBigInt.cpp\n * @author Yann yann@ethdev.com\n * @date 2015\n */\n\n#include <boost/variant/multivisitors.hpp>\n#include <boost/variant.hpp>\n#include <libethcore/CommonJS.h>\n#include \"QBigInt.h\"\n\nusing namespace dev;\nusing namespace dev::mix;\nusing namespace std;\n\nvoid QBigInt::manageException() const\n{\n\ttry\n\t{\n\t\tthrow;\n\t}\n\tcatch (boost::exception const& _e)\n\t{\n\t\tcerr << boost::diagnostic_information(_e);\n\t}\n\tcatch (exception const& _e)\n\t{\n\t\tcerr << _e.what();\n\t}\n\tcatch (...)\n\t{\n\t\tcerr << boost::current_exception_diagnostic_information();\n\t}\n}\n\nQString QBigInt::value() const\n{\n\ttry\n\t{\n\t\tostringstream s;\n\t\ts << m_internalValue;\n\t\treturn QString::fromStdString(s.str());\n\t}\n\tcatch (...)\n\t{\n\t\tmanageException();\n\t\treturn QString();\n\t}\n}\n\nQBigInt* QBigInt::subtract(QBigInt* const& _value) const\n{\n\ttry\n\t{\n\t\tif (!_value)\n\t\t\treturn nullptr;\n\t\tBigIntVariant toSubtract = _value->internalValue();\n\t\treturn new QBigInt(boost::apply_visitor(mix::subtract(), m_internalValue, toSubtract));\n\t}\n\tcatch (...)\n\t{\n\t\tmanageException();\n\t\treturn nullptr;\n\t}\n}\n\nQBigInt* QBigInt::add(QBigInt* const& _value) const\n{\n\ttry\n\t{\n\t\tif (!_value)\n\t\t\treturn nullptr;\n\t\tBigIntVariant toAdd = _value->internalValue();\n\t\treturn new QBigInt(boost::apply_visitor(mix::add(), m_internalValue, toAdd));\n\t}\n\tcatch (...)\n\t{\n\t\tmanageException();\n\t\treturn nullptr;\n\t}\n}\n\nQBigInt* QBigInt::multiply(QBigInt* const& _value) const\n{\n\ttry\n\t{\n\t\tif (!_value)\n\t\t\treturn nullptr;\n\t\tBigIntVariant toMultiply = _value->internalValue();\n\t\treturn new QBigInt(boost::apply_visitor(mix::multiply(), m_internalValue, toMultiply));\n\t}\n\tcatch (...)\n\t{\n\t\tmanageException();\n\t\treturn nullptr;\n\t}\n}\n\nQBigInt* QBigInt::divide(QBigInt* const& _value) const\n{\n\ttry\n\t{\n\t\tif (!_value)\n\t\t\treturn nullptr;\n\t\tBigIntVariant toDivide = _value->internalValue();\n\t\treturn new QBigInt(boost::apply_visitor(mix::divide(), m_internalValue, toDivide));\n\t}\n\tcatch (...)\n\t{\n\t\tmanageException();\n\t\treturn nullptr;\n\t}\n}\n\nQVariantMap QBigInt::checkAgainst(QString const& _type) const\n{\n\tQVariantMap ret;\n\ttry\n\t{\n\t\tQString type = _type;\n\t\tQString capacity = type.replace(\"uint\", \"\").replace(\"int\", \"\");\n\t\tif (capacity.isEmpty())\n\t\t\tcapacity = \"256\";\n\t\tbigint range = 1;\n\t\tfor (int k = 0; k < capacity.toInt() / 8; ++k)\n\t\t\trange = range * 256;\n\t\tbigint value = boost::get<bigint>(this->internalValue());\n\t\tret.insert(\"valid\", true);\n\t\tif (_type.startsWith(\"uint\") && value > range - 1)\n\t\t{\n\t\t\tret.insert(\"minValue\", \"0\");\n\t\t\tostringstream s;\n\t\t\ts << range - 1;\n\t\t\tret.insert(\"maxValue\", QString::fromStdString(s.str()));\n\t\t\tif (value > range)\n\t\t\t\tret[\"valid\"] = false;\n\t\t}\n\t\telse if (_type.startsWith(\"int\"))\n\t\t{\n\t\t\trange = range / 2;\n\t\t\tostringstream s;\n\t\t\ts << -range;\n\t\t\tret.insert(\"minValue\", QString::fromStdString(s.str()));\n\t\t\ts.str(\"\");\n\t\t\ts.clear();\n\t\t\ts << range - 1;\n\t\t\tret.insert(\"maxValue\", QString::fromStdString(s.str()));\n\t\t\tif (-range > value || value > range - 1)\n\t\t\t\tret[\"valid\"] = false;\n\t\t}\n\t}\n\tcatch (...)\n\t{\n\t\tmanageException();\n\t}\n\treturn ret;\n}\n", "meta": {"hexsha": "4161220b0c3b93ad67cadc7925c86373b84385a5", "size": 3666, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/QBigInt.cpp", "max_stars_repo_name": "isabella232/mix", "max_stars_repo_head_hexsha": "b2f4994d63015ad3386281d51e36771492c5aca5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 214.0, "max_stars_repo_stars_event_min_datetime": "2015-08-25T06:10:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-10T07:43:21.000Z", "max_issues_repo_path": "src/QBigInt.cpp", "max_issues_repo_name": "ethereum/mix", "max_issues_repo_head_hexsha": "b2f4994d63015ad3386281d51e36771492c5aca5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 216.0, "max_issues_repo_issues_event_min_datetime": "2015-08-18T12:07:37.000Z", "max_issues_repo_issues_event_max_datetime": "2017-06-24T01:18:47.000Z", "max_forks_repo_path": "src/QBigInt.cpp", "max_forks_repo_name": "isabella232/mix", "max_forks_repo_head_hexsha": "b2f4994d63015ad3386281d51e36771492c5aca5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 58.0, "max_forks_repo_forks_event_min_datetime": "2015-08-18T15:21:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T19:14:38.000Z", "avg_line_length": 21.1907514451, "max_line_length": 89, "alphanum_fraction": 0.6707583197, "num_tokens": 1020, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389817407016, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4589410261958296}}
{"text": "/*\n    Copyright (c) 2015-2017 Xavier Leclercq\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 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 DEALINGS\n    IN THE SOFTWARE.\n*/\n\n#include <boost/random/random_device.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <iostream>\n#include <vector>\n#include <ctime>\n\nint main(int argc, char* argv[])\n{\n    // Create a random number generator using the platform default\n    boost::random_device rng;\n    \n    std::cout << \"Random number generator:\" << std::endl;\n    std::cout << \"\\tMin generated number: \" << rng.min() << std::endl;\n    std::cout << \"\\tMax generated number: \" << rng.max() << std::endl;\n    std::cout << std::endl;\n\n    // Create a Mersenne Twister pseudo-random number generator\n    boost::random::mt19937 prng;\n\n    std::cout << \"Pseudo-random number generator:\" << std::endl;\n    std::cout << \"\\tMin generated number: \" << prng.min() << std::endl;\n    std::cout << \"\\tMax generated number: \" << prng.max() << std::endl;\n    std::cout << std::endl;\n\n    // Generate a random number to be used as the seed\n    unsigned int seed = rng();\n    std::cout << \"The seed is: \" << seed << std::endl;\n    std::cout << std::endl;\n\n    prng.seed(seed);\n\n    // Generate a few pseudo-random numbers one by one\n    std::cout << \"Pseudo-random number 1: \" << prng() << std::endl;\n    std::cout << \"Pseudo-random number 2: \" << prng() << std::endl;\n    std::cout << \"Pseudo-random number 3: \" << prng() << std::endl;\n    std::cout << std::endl;\n\n    // Fill a vector with pseudo-random numbers\n    std::vector<unsigned int> v;\n    v.resize(5);\n    prng.generate(v.begin(), v.end());\n\n    std::cout << \"Pseudo-random numbers vector: \";\n    for (size_t i = 0; i < v.size(); ++i)\n    {\n        std::cout << v[i] << \" \";\n    }\n    std::cout << std::endl;\n    \n    return 0;\n}\n", "meta": {"hexsha": "7da2404e6d3c47bd0868abdf57a46115ec469236", "size": 2786, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Random/Random1/Source/main.cpp", "max_stars_repo_name": "needful-software/BoostTutorials", "max_stars_repo_head_hexsha": "19bf04e054093a1011a065583ad2ddd93164718f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Random/Random1/Source/main.cpp", "max_issues_repo_name": "needful-software/BoostTutorials", "max_issues_repo_head_hexsha": "19bf04e054093a1011a065583ad2ddd93164718f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-10-30T13:17:34.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-30T13:17:34.000Z", "max_forks_repo_path": "Random/Random1/Source/main.cpp", "max_forks_repo_name": "needful-software/BoostTutorials", "max_forks_repo_head_hexsha": "19bf04e054093a1011a065583ad2ddd93164718f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-08T20:51:45.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T20:51:45.000Z", "avg_line_length": 37.6486486486, "max_line_length": 80, "alphanum_fraction": 0.6582914573, "num_tokens": 697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723317123102955, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.4589159676354708}}
{"text": "// Copyright (c) 2020 Marcus Valtonen \u00d6rnhag\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 <Eigen/Dense>\n#include <vector>\n#include <chrono>  // NOLINT [build/c++11]\n#include <iostream>\n#include \"get_fitzgibbon_cvpr_2001.hpp\"\n#include \"get_kukelova_cvpr_2015.hpp\"\n#include \"get_valtonenornhag_arxiv_2020a.hpp\"\n#include \"get_valtonenornhag_arxiv_2020b.hpp\"\n#include \"problem_instance.hpp\"\n#include \"generate_problem_instance.hpp\"\n#include \"posedata.hpp\"\n\nint main() {\n    /* Timing experiments */\n    int nbr_iter = 1e2;\n    Eigen::MatrixXcd out;\n    int N = 5;\n    HomLib::ProblemInstance inst;\n\n    /* TEST SOLVERS HERE */\n    std::cout << \"--- COMPLETE SOLVERS, INCLUDING PRE- and POST-PROCESSING ---\" << std::endl;\n    HomLib::PoseData posedata;\n    N = 2;\n\n    // fHf complete\n    std::vector<HomLib::PoseData> posedata_fHf;\n    auto start = std::chrono::steady_clock::now();\n    for (int i=0; i < nbr_iter; i++) {\n        inst = HomLib::generate_problem_instance(N);\n        posedata_fHf = HomLib::ValtonenOrnhagArxiv2020B::get_fHf(inst.x1, inst.x2, inst.R1g, inst.R2g);\n    }\n    auto end = std::chrono::steady_clock::now();\n    std::cout << \"(fHf complete) Elapsed time in microseconds : \"\n        << std::chrono::duration_cast<std::chrono::microseconds>(end - start).count() / nbr_iter\n        << \" \u00b5s\" << std::endl;\n\n    // frHfr elim complete\n    N = 3;\n    start = std::chrono::steady_clock::now();\n    for (int i=0; i < nbr_iter; i++) {\n        inst = HomLib::generate_problem_instance(N);\n        posedata = HomLib::ValtonenOrnhagArxiv2020B::get_frHfr(inst.x1, inst.x2, inst.R1g, inst.R2g);\n    }\n    end = std::chrono::steady_clock::now();\n    std::cout << \"(frHfr elim complete) Elapsed time in microseconds : \"\n        << std::chrono::duration_cast<std::chrono::microseconds>(end - start).count() / nbr_iter\n        << \" \u00b5s\" << std::endl;\n\n    // floor_fHf complete\n    start = std::chrono::steady_clock::now();\n    for (int i=0; i < nbr_iter; i++) {\n        inst = HomLib::generate_problem_instance(N);\n        posedata = HomLib::ValtonenOrnhagArxiv2020A::get_fHf(inst.x1, inst.x2, inst.R1g, inst.R2g);\n    }\n    end = std::chrono::steady_clock::now();\n    std::cout << \"(floor fHf complete) Elapsed time in microseconds : \"\n        << std::chrono::duration_cast<std::chrono::microseconds>(end - start).count() / nbr_iter\n        << \" \u00b5s\" << std::endl;\n\n    // Kukelova Hlam1lam2 complete\n    std::vector<HomLib::PoseData> posedata2;\n    start = std::chrono::steady_clock::now();\n    N = 5;\n    for (int i=0; i < nbr_iter; i++) {\n        inst = HomLib::generate_problem_instance(N);\n        posedata2 = HomLib::KukelovaCVPR2015::get(inst.x1, inst.x2);\n    }\n    end = std::chrono::steady_clock::now();\n    std::cout << \"(Kukelova Hlam1lam2 complete) Elapsed time in microseconds : \"\n        << std::chrono::duration_cast<std::chrono::microseconds>(end - start).count() / nbr_iter\n        << \" \u00b5s\" << std::endl;\n\n    // Fitzgibbon\n    start = std::chrono::steady_clock::now();\n    for (int i=0; i < nbr_iter; i++) {\n        inst = HomLib::generate_problem_instance(N);\n        posedata = HomLib::FitzgibbonCVPR2001::get(inst.x1, inst.x2);\n    }\n    end = std::chrono::steady_clock::now();\n    std::cout << \"(Fitzgibbon complete) Elapsed time in microseconds : \"\n        << std::chrono::duration_cast<std::chrono::microseconds>(end - start).count() / nbr_iter\n        << \" \u00b5s\" << std::endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "6aa0fe4582c9cb7b0cf7c450440e392d9c7a134a", "size": 4462, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example.cpp", "max_stars_repo_name": "marcusvaltonen/HomLib", "max_stars_repo_head_hexsha": "cc8c3ba78bbfcb30fdbe17e5aa45405f4757889b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-01-07T18:58:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-28T10:37:37.000Z", "max_issues_repo_path": "example.cpp", "max_issues_repo_name": "marcusvaltonen/HomLib", "max_issues_repo_head_hexsha": "cc8c3ba78bbfcb30fdbe17e5aa45405f4757889b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example.cpp", "max_forks_repo_name": "marcusvaltonen/HomLib", "max_forks_repo_head_hexsha": "cc8c3ba78bbfcb30fdbe17e5aa45405f4757889b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-11-19T19:59:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-19T19:59:02.000Z", "avg_line_length": 42.0943396226, "max_line_length": 103, "alphanum_fraction": 0.6676378306, "num_tokens": 1251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723317123102955, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.4589159676354708}}
{"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\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include <iostream>\n#include <cmath>\n#include <complex>\n#include <boost/numeric/mtl/concept/collection.hpp>\n#include <boost/numeric/mtl/matrix/dense2D.hpp>\n#include <boost/numeric/mtl/matrix/morton_dense.hpp> \n#include <boost/numeric/mtl/matrix/compressed2D.hpp> \n#include <boost/numeric/mtl/matrix/inserter.hpp> \n#include <boost/numeric/mtl/matrix/element_matrix.hpp> \n#include <boost/numeric/mtl/matrix/element_array.hpp> \n#include <boost/numeric/mtl/recursion/predefined_masks.hpp>\n#include <boost/numeric/mtl/operation/print.hpp>\n\n\nusing namespace std;  \n\ntemplate <typename Matrix>\nvoid test(Matrix& matrix, const char* name)\n{\n    cout << \"\\n\" << name << \"\\n\";\n\n    using mtl::mat::inserter; using mtl::element_array;\n    typedef typename mtl::Collection<Matrix>::value_type value_type;\n\n    mtl::dense2D<double>       m1(2, 2);\n    m1[0][0]= 1.0; m1[0][1]= 2.0; \n    m1[1][0]= 3.0; m1[1][1]= 4.0; \n    std::vector<int>           row1, col1;\n    row1.push_back(1); row1.push_back(2);\n    col1.push_back(0); col1.push_back(2);\n    \n\n    double a2[2][2]= {{11., 12.},{13., 14.}};\n    std::vector<int>           ind2;\n    ind2.push_back(2); ind2.push_back(4);\n\n    std::vector<int>           ind3;\n    ind3.push_back(3); ind3.push_back(1);\n\n    set_to_zero(matrix); // dense matrices are not automatically set to zero\n\n    {\n\tinserter<Matrix, mtl::operations::update_plus<value_type> > ins(matrix);\n\n\tins << element_matrix(m1, row1, col1)\n\t    << element_array(a2, ind2);\n\tins << element_array(a2, ind3);\n    }\n\n    cout << \"Filled matrix:\\n\" << matrix << \"\\n\";\n    MTL_THROW_IF(matrix[0][0] != 0.0, mtl::runtime_error(\"wrong zero-element\"));\n    MTL_THROW_IF(matrix[1][0] != 1.0, mtl::runtime_error(\"wrong insertion (single value)\"));\n    MTL_THROW_IF(matrix[2][2] != 15.0, mtl::runtime_error(\"wrong summation\"));\n    MTL_THROW_IF(matrix[1][1] != 14.0, mtl::runtime_error(\"wrong insertion (single value)\"));\n    \n}\n\n\n\nint main(int , char**)\n{\n    using namespace mtl;\n    unsigned size= 5;\n\n    dense2D<double>                                      dr(size, size);\n    dense2D<double, mat::parameters<col_major> >      dc(size, size);\n    morton_dense<double, recursion::morton_z_mask>       mzd(size, size);\n    morton_dense<double, recursion::doppled_2_row_mask>  d2r(size, size);\n    compressed2D<double>                                 cr(size, size);\n    compressed2D<double, mat::parameters<col_major> > cc(size, size);\n\n    dense2D<complex<double> >                            drc(size, size);\n    compressed2D<complex<double> >                       crc(size, size);\n\n    test(dr, \"Dense row major\");\n    test(dc, \"Dense column major\");\n    test(mzd, \"Morton Z-order\");\n    test(d2r, \"Hybrid 2 row-major\");\n    test(cr, \"Compressed row major\");\n    test(cc, \"Compressed column major\");\n    test(drc, \"Dense row major complex\");\n    test(crc, \"Compressed row major complex\");\n\n    return 0;\n}\n", "meta": {"hexsha": "ec70bb595a201b423366f1384f43aa69b2d082af", "size": 3347, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/element_matrix_test.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/mtl/test/element_matrix_test.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/mtl/test/element_matrix_test.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 34.1530612245, "max_line_length": 94, "alphanum_fraction": 0.639976098, "num_tokens": 970, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723316991792861, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.45891596301395193}}
{"text": "/*  ------------------------------------------------------------------\n    Copyright (c) 2017 Marc Toussaint\n    email: marc.toussaint@informatik.uni-stuttgart.de\n\n    This code is distributed under the MIT License.\n    Please see <root-path>/LICENSE for details.\n    --------------------------------------------------------------  */\n\n#ifdef RAI_EIGEN\n#include <Eigen/Sparse>\n#include <Eigen/SparseCholesky>\n#include <Eigen/SparseLU>\n#include <Eigen/SparseQR>\n#endif\n\n#include \"array.h\"\n#include \"util.h\"\n\n#ifdef RAI_LAPACK\nextern \"C\" {\n#include \"cblas.h\"\n#ifdef RAI_MSVC\n#  include \"lapack/blaswrap.h\"\n#endif\n#include \"f2c.h\"\n#undef small\n#undef large\n#ifndef ATLAS\n#  include \"lapack/clapack.h\"\n#endif\n#undef double\n#undef max\n#undef min\n#undef abs\n}\n\n#ifdef ATLAS\n#include <complex>\n#define lapack_complex_float std::complex<float>\n#define lapack_complex_double std::complex<double>\n\n#include \"lapack/lapacke.h\"\n#define integer int\n#undef MAX\n#undef MIN\n#endif\n#endif //RAI_LAPACK\n\n\nnamespace rai {\n//===========================================================================\n\nbool useLapack=true;\n#ifdef RAI_LAPACK\nconst bool lapackSupported=true;\n#else\nconst bool lapackSupported=false;\n#endif\nuint64_t globalMemoryTotal=0, globalMemoryBound=1ull<<30; //this is 1GB\nbool globalMemoryStrict=false;\nconst char* arrayElemsep=\", \";\nconst char* arrayLinesep=\",\\n \";\nconst char* arrayBrackets=\"[]\";\n\n//===========================================================================\n}\n\narr __NoArr(new SpecialArray(SpecialArray::ST_NoArr));\narr& NoArr = __NoArr;\narrA __NoArrA(new SpecialArray(SpecialArray::ST_NoArr));\narrA& NoArrA = __NoArrA;\nuintA __NoUintA(new SpecialArray(SpecialArray::ST_NoArr));\nuintA& NoUintA = __NoUintA;\nuint16A __NoUint16A(new SpecialArray(SpecialArray::ST_NoArr));\nuint16A& NoUint16A = __NoUint16A;\nbyteA __NoByteA(new SpecialArray(SpecialArray::ST_NoArr));\nbyteA& NoByteA = __NoByteA;\nintAA __NoIntAA(new SpecialArray(SpecialArray::ST_NoArr));\nintAA& NoIntAA = __NoIntAA;\nuintAA __NoUintAA(new SpecialArray(SpecialArray::ST_NoArr));\nuintAA& NoUintAA = __NoUintAA;\n\n/* LAPACK notes\nUse the documentation at\n  http://www.netlib.org/lapack/double/\n  http://www.netlib.org/lapack/individualroutines.html\nto find the right function! Also use the man tools with Debian package lapack-doc installed.\n\nI've put the clapack.h directly into the rai directory - one only has to link to the Fortran lib\n*/\n\nnamespace rai{\n\n/// make sparse: create the \\ref sparse index\ntemplate<> rai::SparseVector& rai::Array<double>::sparseVec() {\n  SparseVector *s;\n  if(!special){\n    s = new SparseVector(*this);\n    if(N){\n      CHECK_EQ(nd, 1, \"\");\n      arr copy;\n      copy.swap(*this);\n      s->setFromDense(copy);\n    }else{\n      nd=1;\n    }\n  }else{\n    s = dynamic_cast<SparseVector*>(special);\n    CHECK(s, \"\");\n  }\n  return *s;\n}\n\ntemplate<> const rai::SparseVector& rai::Array<double>::sparseVec() const{\n  CHECK(isSparseVector(*this), \"\");\n  SparseVector *s = dynamic_cast<SparseVector*>(special);\n  CHECK(s, \"\");\n  return *s;\n}\n\n/// make sparse: create the \\ref sparse index\ntemplate<> rai::SparseMatrix& rai::Array<double>::sparse() {\n  SparseMatrix *s;\n  if(!special){\n    s = new SparseMatrix(*this);\n    if(N){\n      CHECK_EQ(nd, 2, \"\");\n      arr copy;\n      copy.swap(*this);\n      s->setFromDense(copy);\n    }else{\n      nd=2;\n    }\n  }else{\n    s = dynamic_cast<SparseMatrix*>(special);\n    CHECK(s, \"\");\n  }\n  return *s;\n}\n\n/// make sparse: create the \\ref sparse index\ntemplate<> const rai::SparseMatrix& rai::Array<double>::sparse() const{\n  CHECK(isSparseMatrix(*this), \"\");\n  SparseMatrix *s = dynamic_cast<SparseMatrix*>(special);\n  CHECK(s, \"\");\n  return *s;\n}\n\n#define NONSENSE( type ) \\\ntemplate<> rai::SparseMatrix& rai::Array<type>::sparse() { NIY; return *(new SparseMatrix(NoArr)); }\nNONSENSE(float)\nNONSENSE(uint)\nNONSENSE(int)\n#undef NONSENSE\n\n}\n\n//===========================================================================\n//\n/// @name matrix operations\n//\n\narr grid(const arr& lo, const arr& hi, const uintA& steps) {\n  CHECK(lo.N==hi.N && lo.N==steps.N,\"\");\n  arr X;\n  uint i, j, k;\n  if(lo.N==1) {\n    X.resize(steps(0)+1, 1);\n    for(i=0; i<X.d0; i++) X.operator()(i, 0)=lo(0)+(hi(0)-lo(0))*i/steps(0);\n    return X;\n  }\n  if(lo.N==2) {\n    X.resize(steps(0)+1, steps(1)+1, 2);\n    for(i=0; i<X.d0; i++) for(j=0; j<X.d1; j++) {\n        X.operator()(i, j, 0)=lo(0)+(i?(hi(0)-lo(0))*i/steps(0):0.);\n        X.operator()(i, j, 1)=lo(1)+(j?(hi(1)-lo(1))*j/steps(1):0.);\n      }\n    X.reshape(X.d0*X.d1, 2);\n    return X;\n  }\n  if(lo.N==3) {\n    X.resize(TUP(steps(0)+1, steps(1)+1, steps(2)+1, 3));\n    for(i=0; i<X.d0; i++) for(j=0; j<X.d1; j++) for(k=0; k<X.d2; k++) {\n          X.elem(TUP(i, j, k, 0))=lo(0)+(hi(0)-lo(0))*i/steps(0);\n          X.elem(TUP(i, j, k, 1))=lo(1)+(hi(1)-lo(1))*j/steps(1);\n          X.elem(TUP(i, j, k, 2))=lo(2)+(hi(2)-lo(2))*k/steps(2);\n        }\n    X.reshape(X.d0*X.d1*X.d2, 3);\n    return X;\n  }\n  HALT(\"not implemented yet\");\n  \n}\n\narr repmat(const arr& A, uint m, uint n) {\n  CHECK(A.nd==1 || A.nd==2, \"\");\n  arr B;\n  B.referTo(A);\n  if(B.nd==1) B.reshape(B.N, 1);\n  arr z;\n  z.resize(B.d0*m, B.d1*n);\n  for(uint i=0; i<m; i++)\n    for(uint j=0; j<n; j++)\n      z.setMatrixBlock(B, i*B.d0, j*B.d1);\n  return z;\n}\narr rand(const uintA& d) {  arr z;  z.resize(d);  rndUniform(z, false); return z;  }\narr randn(const uintA& d) {  arr z;  z.resize(d);  rndGauss(z, 1., false);  return z;  }\n\narr diag(double d, uint n) {\n  arr z;\n  z.setDiag(d, n);\n  return z;\n}\n\nvoid addDiag(arr& A, double d) {\n  if(isRowShifted(A)) {\n    RowShifted *Aaux = (RowShifted*) A.special;\n    if(!Aaux->symmetric) HALT(\"this is not a symmetric matrix\");\n    for(uint i=0; i<A.d0; i++) A(i,0) += d;\n  } else {\n    for(uint i=0; i<A.d0; i++) A(i,i) += d;\n  }\n}\n\n/// make symmetric \\f$A=(A+A^T)/2\\f$\nvoid makeSymmetric(arr& A) {\n  CHECK(A.nd==2 && A.d0==A.d1, \"not symmetric\");\n  uint n=A.d0, i, j;\n  for(i=1; i<n; i++) for(j=0; j<i; j++) A(j, i) = A(i, j) = .5 * (A(i, j) + A(j, i));\n}\n\n/// make its transpose \\f$A \\gets A^T\\f$\nvoid transpose(arr& A) {\n  CHECK(A.nd==2 && A.d0==A.d1, \"not symmetric\");\n  uint n=A.d0, i, j;\n  double z;\n  for(i=1; i<n; i++) for(j=0; j<i; j++) { z=A(j, i); A(j, i)=A(i, j); A(i, j)=z; }\n}\n\narr oneover(const arr& A) {\n  arr B = A;\n  for(double& b:B) b=1./b;\n  return B;\n}\n\nnamespace rai {\n/// use this to turn on Lapack routines [default true if RAI_LAPACK is defined]\nextern bool useLapack;\n}\n\nvoid normalizeWithJac(arr& y, arr& J) {\n  double l = length(y);\n  CHECK(l>1e-10, \"can't normalize\");\n  y /= l;\n  if(!!J && J.N){\n    J -= y*(~y*J); //same as (y^y)*J;\n    J /= l;\n  }\n}\n\n//===========================================================================\n//\n/// @name SVD etc\n//\n\n/// called from svd if RAI_LAPACK is not defined\nuint own_SVD(\n  arr& U,\n  arr& w,\n  arr& V,\n  const arr& A,\n  bool sort2Dpoints);\n\n/** @brief Singular Value Decomposition (from Numerical Recipes);\n  computes \\f$U, D, V\\f$ with \\f$A = U D V^T\\f$ from \\f$A\\f$ such that\n  \\f$U\\f$ and \\f$V\\f$ are orthogonal and \\f$D\\f$ diagonal (the\n  returned array d is 1-dimensional) -- uses LAPACK if RAI_LAPACK is\n  defined */\nuint svd(arr& U, arr& d, arr& V, const arr& A, bool sort) {\n  uint r;\n#ifdef RAI_LAPACK\n  if(rai::useLapack) {\n    r=lapack_SVD(U, d, V, A);\n    V=~V;\n  } else {\n    r=own_SVD(U, d, V, A, sort);\n  }\n#else\n  r=own_SVD(U, d, V, A, sort);\n#endif\n  \n#ifdef RAI_CHECK_SVD\n  bool uselapack=rai::useLapack;\n  rai::useLapack=false;\n  double err;\n  arr dD, I;\n  setDiagonal(dD, d);\n  //cout <<U <<dD <<Vt;\n  //Atmp = V * D * U;\n  arr Atmp;\n  Atmp = U * dD * ~V;\n  //cout <<\"\\nA=\" <<A <<\"\\nAtmp=\" <<Atmp <<\"U=\" <<U <<\"W=\" <<dD <<\"~V=\" <<~V <<endl;\n  std::cout <<\"SVD is correct:  \" <<(err=maxDiff(Atmp, A)) <<' ' <<endl;    CHECK(err<RAI_CHECK_SVD, \"\");\n  if(A.d0<=A.d1) {\n    I.setId(U.d0);\n    std::cout <<\"U is orthogonal: \" <<(err=maxDiff(U * ~U, I)) <<' ' <<endl;  CHECK(err<RAI_CHECK_SVD, \"\");\n    I.setId(V.d1);\n    std::cout <<\"V is orthogonal: \" <<(err=maxDiff(~V * V, I)) <<endl;        CHECK(err<RAI_CHECK_SVD, \"\");\n  } else {\n    I.setId(U.d1);\n    std::cout <<\"U is orthogonal: \" <<(err=maxDiff(~U * U, I)) <<' ' <<endl;  CHECK(err<RAI_CHECK_SVD, \"\");\n    I.setId(V.d0);\n    std::cout <<\"V is orthogonal: \" <<(err=sqrDistance(V * ~V, I)) <<endl;        CHECK(err<1e-5, \"\");\n  }\n  rai::useLapack=uselapack;\n#endif\n  \n  return r;\n}\n\n/// gives a decomposition \\f$A = U V^T\\f$\nvoid svd(arr& U, arr& V, const arr& A) {\n  arr d, D;\n  ::svd(U, d, V, A);\n  D.resize(d.N, d.N); D=0.;\n  for(uint i=0; i<d.N; i++) D(i, i)=::sqrt(d(i));\n  U=U*D;\n  V=V*D;\n  //CHECK(maxDiff(A, U*~V) <1e-4, \"\");\n}\n\nvoid pca(arr &Y, arr &v, arr &W, const arr &X, uint npc) {\n  CHECK(X.nd == 2 && X.d0 > 0 && X.d1 > 0, \"Invalid data matrix X.\");\n  CHECK_LE(npc ,  X.d1, \"More principal components than data matrix X can offer.\");\n  \n  if(npc == 0)\n    npc = X.d1;\n    \n  // centering around the mean\n  arr m = sum(X, 0) / (double)X.d0;\n  arr D = X;\n  for(uint i = 0; i < D.d0; i++)\n    D[i]() -= m;\n    \n  arr U;\n  svd(U, v, W, D, true);\n  v = v % v;\n  /*\n  cout << \"X: \" << X << endl;\n  cout << \"D: \" << D << endl;\n  cout << \"~D*D: \" << ~D*D << endl;\n  cout << \"UU: \" << U << endl;\n  cout << \"vv: \" << v << endl;\n  cout << \"WW: \" << W << endl;\n  */\n  \n  W = W.cols(0, npc);\n  Y = D * W;\n  \n  v *= 1./sum(v);\n  v.sub(0, npc-1);\n}\n\nvoid check_inverse(const arr& Ainv, const arr& A) {\n#ifdef RAI_CHECK_INVERSE\n  arr D, _D; D.setId(A.d0);\n  uint me;\n  _D=A*Ainv;\n  double err=maxDiff(_D, D, &me);\n  cout <<\"inverse is correct: \" <<err <<endl;\n  if(A.d0<10) {\n    CHECK(err<RAI_CHECK_INVERSE , \"inverting failed, error=\" <<err <<\" \" <<_D.elem(me) <<\"!=\" <<D.elem(me) <<\"\\nA=\" <<A <<\"\\nAinv=\" <<Ainv <<\"\\nA*Ainv=\" <<_D);\n  } else {\n    CHECK(err<RAI_CHECK_INVERSE , \"inverting failed, error=\" <<err <<\" \" <<_D.elem(me) <<\"!=\" <<D.elem(me));\n  }\n#endif\n}\n\nuint inverse(arr& Ainv, const arr& A) {\n  uint r=inverse_SVD(Ainv, A);\n  //rai::inverse_LU(inverse, A); return A.d0;\n  return r;\n}\n\n/// calls inverse(B, A) and returns B\narr inverse(const arr& A) { arr B; inverse(B, A); return B; }\n\n/// Pseudo Inverse based on SVD; computes \\f$B\\f$ such that \\f$ABA = A\\f$\nuint inverse_SVD(arr& Ainv, const arr& A) {\n  CHECK_EQ(A.nd, 2, \"requires a matrix\");\n  unsigned i, j, k, m=A.d0, n=A.d1, r;\n  arr U, V, w, winv;\n  Ainv.resize(n, m);\n  if(m==0 || n==0) return 0;\n  if(m==n && m==1) { Ainv(0, 0)=1./A(0, 0); return 0; }\n  if(m==n && m==2) { inverse2d(Ainv, A); return 0; }\n  \n  r=svd(U, w, V, A, true);\n  \n  //arr W;\n  //setDiagonal(W, w);\n  //CHECK(fabs(maxDiff(A, U*W*~V))<1e-10, \"\");\n  \n  winv.resizeAs(w);\n  for(i=0; i<r; i++) {\n    if(w(i)>1e-10) winv(i) = 1./w(i); else winv(i) = 1e10;\n  }\n  for(; i<w.N; i++) winv(i) = 0.;\n  \n#if 0\n  //arr W;\n  setDiagonal(W, winv);\n  Ainv = V * W * ~U;\n#else\n  double *Ainvij=&Ainv(0, 0);\n  for(i=0; i<n; i++) for(j=0; j<m; j++) {\n      double* vi = &V(i, 0);\n      double* uj = &U(j, 0);\n      double  t  = 0.;\n      for(k=0; k<w.N; k++) t += vi[k] * winv.p[k] * uj[k];\n      *Ainvij = t;\n      Ainvij++;\n    }\n#endif\n  \n#ifdef RAI_CHECK_INVERSE\n  check_inverse(Ainv, A);\n#endif\n  return r;\n}\n\nvoid mldivide(arr& X, const arr& A, const arr& b) {\n#ifdef RAI_LAPACK\n  lapack_mldivide(X, A, b);\n#else\n  NIY;\n#endif\n}\n\nvoid inverse_LU(arr& Xinv, const arr& X) {\n  NIY;\n#if 0\n  CHECK(X.nd==2 && X.d0==X.d1, \"\");\n  uint n=X.d0, i, j;\n  Xinv.resize(n, n);\n  if(n==0) return;\n  if(n==n && n==1) { Xinv(0, 0)=1./X(0, 0); return; }\n  if(n==n && n==2) { inverse2d(Xinv, X); return; }\n  arr LU, piv;\n  lapackLU(X, LU, piv);\n  arr col(n);\n  for(j=0; j<n; j++) {\n    col.setZero();\n    col(j)=1.0;\n    lubksb(LU.pp, n, idx, col.p);\n    for(i=0; i<n; i++) Xinv(i, j)=col(i);\n  }\n  \n  delete[] idx;\n  delete[] d;\n  \n#ifdef RAI_CHECK_INVERSE\n  check_inverse(Xinv, X);\n#endif\n#endif\n}\n\nvoid inverse_SymPosDef(arr& Ainv, const arr& A) {\n  CHECK_EQ(A.d0,A.d1, \"\");\n#ifdef RAI_LAPACK\n  lapack_inverseSymPosDef(Ainv, A);\n#else\n  inverse_SVD(Ainv, A);\n#endif\n#ifdef RAI_CHECK_INVERSE\n  check_inverse(Ainv, A);\n#endif\n}\n\narr pseudoInverse(const arr& A, const arr& Winv, double eps) {\n  arr AAt;\n  arr At = ~A;\n  if(!!Winv) {\n    if(Winv.nd==1) AAt = A*(Winv%At); else AAt = A*Winv*At;\n  } else AAt = A*At;\n  if(eps) for(uint i=0; i<AAt.d0; i++) AAt(i,i) += eps;\n  arr AAt_inv = inverse_SymPosDef(AAt);\n  arr Ainv = At * AAt_inv;\n  if(!!Winv) { if(Winv.nd==1) Ainv = Winv%Ainv; else Ainv = Winv*Ainv; }\n  return Ainv;\n}\n\n/// the determinant of a 2D squared matrix\ndouble determinant(const arr& A);\n\n/** @brief the cofactor is the determinant of a 2D squared matrix after removing\n  the ith row and the jth column */\ndouble cofactor(const arr& A, uint i, uint j);\n\nvoid gaussFromData(arr& a, arr& A, const arr& X) {\n  CHECK_EQ(X.nd,2, \"\");\n  uint N=X.d0, n=X.d1;\n  arr ones(N); ones=1.;\n  a = ones*X/(double)N; a.reshape(n);\n  A = (~X*X)/(double)N - (a^a);\n}\n\n/* compute a rotation matrix that rotates a onto v in arbitrary dimensions */\nvoid rotationFromAtoB(arr& R, const arr& a, const arr& v) {\n  CHECK_EQ(a.N,v.N, \"\");\n  CHECK(fabs(1.-length(a))<1e-10 && fabs(1.-length(v))<1e-10, \"\");\n  uint n=a.N, i, j;\n  if(maxDiff(a, v)<1e-10) { R.setId(n); return; }  //nothing to rotate!!\n  R.resize(n, n);\n  //-- compute b orthogonal to a such that (a, b) span the rotation plane\n  arr b;\n  b = v - a*scalarProduct(a, v);\n  b /= length(b);\n  //-- compute rotation coefficients within the (a, b) plane, namely, R_2D=(v_a  -v_b ;  v_b  v_a)\n  double v_a, v_b;\n  v_a=scalarProduct(v, a);     //component along a\n  v_b=scalarProduct(v, b);     //component along b\n  //-- compute columns of R:\n  arr x(n), x_res;\n  double x_a, x_b;\n  for(i=0; i<n; i++) {\n    x.setZero(); x(i)=1.;       //x=i-th unit vector\n    x_a=scalarProduct(x, a);     //component along a\n    x_b=scalarProduct(x, b);     //component along b\n    x_res = x - x_a*a - x_b*b;  //residual (rest) of the vector\n    //rotated vector = residual + rotated a-component + rotated b-component\n    x = x_res + (v_a*x_a-v_b*x_b)*a + (v_b*x_a+v_a*x_b)*b;\n    for(j=0; j<n; j++) R(j, i)=x(j);  //store as column of the final rotation\n  }\n}\n\ninline double RAI_SIGN_SVD(double a, double b) { return b>0 ? ::fabs(a) : -::fabs(a); }\n#define RAI_max_SVD(a, b) ( (a)>(b) ? (a) : (b) )\n#define RAI_SVD_MINVALUE .0 //1e-10\n\nuint own_SVD(\n  arr& U,\n  arr& w,\n  arr& V,\n  const arr& A,\n  bool sort) {\n  //rai::Array<double*> Apointers, Upointers, Vpointers;\n  unsigned m = A.d0; /* rows */\n  unsigned n = A.d1; /* cols */\n  U.resize(m, n);\n  V.resize(n, n);\n  w.resize(n);\n  rai::Array<double*> Ap, Up, Vp;\n  double **a = A.getCarray(Ap); //Pointers(Apointers); /* input matrix */\n  double **u = U.getCarray(Up); //Pointers(Upointers); /* left vectors */\n  double **v = V.getCarray(Vp); //Pointers(Vpointers); /* right vectors */\n  \n  int flag;\n  unsigned i, its, j, jj, k, l, nm(0), r;\n  double anorm, c, f, g, h, s, scale, x, y, z, t;\n  \n  arr rv1(n);\n  \n  /* copy A to U */\n  for(i=0; i<m; i++) for(j=0; j<n; j++) u[i][j] = a[i][j];\n  \n  /* householder reduction to pickBiagonal form */\n  g = scale = anorm = 0.0;\n  \n  for(i=0; i<n; i++) {\n    l = i + 1;\n    rv1(i) = scale * g;\n    g = s = scale = 0.0;\n    \n    if(i<m) {\n      for(k=i; k<m; k++) scale += fabs(u[k][i]);\n      \n      if(scale!=0.0) {\n        for(k=i; k<m; k++) {\n          u[k][i] /= scale;\n          s += u[k][i] * u[k][i];\n        }\n        \n        f = u[i][i];\n        g = -RAI_SIGN_SVD(sqrt(s), f);\n        h = f * g - s;\n        u[i][i] = f - g;\n        \n        for(j=l; j<n; j++) {\n          s = 0.0;\n          for(k=i; k<m; k++) s += u[k][i] * u[k][j];\n          \n          f = s / h;\n          for(k=i; k<m; k++) u[k][j] += f * u[k][i];\n        }\n        \n        for(k=i; k<m; k++) u[k][i] *= scale;\n      }\n    }\n    \n    w(i) = scale * g;\n    g = s = scale = 0.0;\n    \n    if(i<m && i!=n-1) {\n      for(k=l; k<n; k++)scale += fabs(u[i][k]);\n      \n      if(scale!=0.0) {\n        for(k=l; k<n; k++) {\n          u[i][k] /= scale;\n          s += u[i][k] * u[i][k];\n        }\n        \n        f = u[i][l];\n        g = -RAI_SIGN_SVD(sqrt(s), f);\n        h = f * g - s;\n        u[i][l] = f - g;\n        \n        for(k=l; k<n; k++) rv1(k) = u[i][k] / h;\n        \n        for(j=l; j<m; j++) {\n          s = 0.0;\n          for(k=l; k<n; k++) s += u[j][k] * u[i][k];\n          \n          for(k=l; k<n; k++) u[j][k] += s * rv1(k);\n        }\n        \n        for(k=l; k<n; k++) u[i][k] *= scale;\n      }\n    }\n    \n    anorm = RAI_max_SVD(anorm, fabs(w(i)) + fabs(rv1(i)));\n  }\n  \n  /* accumulation of right-hand transformations */\n  for(l=i=n; i--; l--) {\n    if(l<n) {\n      if(g!=0.0) {\n        /* double division avoids possible underflow */\n        for(j=l; j<n; j++) v[j][i] = (u[i][j] / u[i][l]) / g;\n        \n        for(j=l; j<n; j++) {\n          s = 0.0;\n          for(k=l; k<n; k++) s += u[i][k] * v[k][j];\n          \n          for(k=l; k<n; k++) v[k][j] += s * v[k][i];\n        }\n      }\n      \n      for(j=l; j<n; j++) v[i][j] = v[j][i] = 0.0;\n    }\n    \n    v[i][i] = 1.0;\n    g = rv1(i);\n  }\n  \n  /* accumulation of left-hand transformations */\n  for(l=i=(m<n?m:n); i--; l--) {\n    g = w(i);\n    \n    for(j=l; j<n; j++) u[i][j] = 0.0;\n    \n    if(g!=0.0) {\n      g = 1.0 / g;\n      \n      for(j=l; j<n; j++) {\n        s = 0.0;\n        for(k=l; k<m; k++) s += u[k][i] * u[k][j];\n        \n        /* double division avoids possible underflow */\n        f = (s / u[i][i]) * g;\n        \n        for(k=i; k<m; k++) u[k][j] += f * u[k][i];\n      }\n      \n      for(j=i; j<m; j++) u[j][i] *= g;\n    } else {\n      for(j=i; j<m; j++) u[j][i] = 0.0;\n    }\n    \n    u[i][i]++;\n  }\n  \n  /* diagonalization of the pickBiagonal form */\n  for(k=n; k--;) {\n    for(its=1; its<=30; its++) {\n      flag = 1;\n      \n      /* test for splitting */\n      for(l = k + 1; l--;) {\n        /* rv1 [0] is always zero, so there is no exit */\n        nm = l - 1;\n        \n        if(fabs(rv1(l)) + anorm == anorm) {\n          flag = 0;\n          break;\n        }\n        \n        //if(!l) break; //(mt 07-01-16)\n        if(fabs(w(nm)) + anorm == anorm) break;\n      }\n      \n      if(flag) {\n        /* cancellation of rv1 [l] if l greater than 0 */\n        c = 0.0;\n        s = 1.0;\n        \n        for(i=l; i<=k; i++) {\n          f = s * rv1(i);\n          rv1(i) *= c;\n          \n          if(fabs(f) + anorm == anorm) break;\n          \n          g = w(i);\n          h = hypot(f, g);\n          w(i) = h;\n          h = 1.0 / h;\n          c = g * h;\n          s = -f * h;\n          \n          for(j=0; j<m; j++) {\n            y = u[j][nm];\n            z = u[j][i];\n            u[j][nm] = y * c + z * s;\n            u[j][i] = z * c - y * s;\n          }\n        }\n      }\n      \n      /* test for convergence */\n      z = w(k);\n      \n      if(l==k) {\n        if(z<0.0) {\n          w(k) = -z;\n          for(j=0; j<n; j++) v[j][k] = -v[j][k];\n        }\n        break;\n      }\n      \n      if(its==50) HALT(\"svd failed\");\n      //if(its==30) throw k;\n      \n      /* shift from bottom 2 by 2 minor */\n      x = w(l);\n      nm = k - 1;\n      y = w(nm);\n      g = rv1(nm);\n      h = rv1(k);\n      f = ((y - z) * (y + z) + (g - h) * (g + h)) / (2.0 * h * y);\n      g = hypot(f, 1.0);\n      f = ((x - z) * (x + z) + h * ((y / (f + RAI_SIGN_SVD(g, f))) - h)) / x;\n      \n      /* next qr transformation */\n      c = s = 1.0;\n      \n      for(j=l; j<k; j++) {\n        i = j + 1;\n        g = rv1(i);\n        y = w(i);\n        h = s * g;\n        g *= c;\n        z = hypot(f, h);\n        rv1(j) = z;\n        c = f / z;\n        s = h / z;\n        f = x * c + g * s;\n        g = g * c - x * s;\n        h = y * s;\n        y *= c;\n        \n        for(jj=0; jj<n; jj++) {\n          x = v[jj][j];\n          z = v[jj][i];\n          v[jj][j] = x * c + z * s;\n          v[jj][i] = z * c - x * s;\n        }\n        \n        z = hypot(f, h);\n        w(j) = z;\n        \n        /* rotation can be arbitrary if z is zero */\n        if(z!=0.0) {\n          z = 1.0 / z;\n          c = f * z;\n          s = h * z;\n        }\n        \n        f = c * g + s * y;\n        x = c * y - s * g;\n        \n        for(jj=0; jj<m; jj++) {\n          y = u[jj][j];\n          z = u[jj][i];\n          u[jj][j] = y * c + z * s;\n          u[jj][i] = z * c - y * s;\n        }\n      }\n      \n      rv1(l) = 0.0;\n      rv1(k) = f;\n      w(k) = x;\n    }\n  }\n  \n  //sorting:\n  if(sort) {\n    unsigned i, j, k;\n    double   p;\n    \n    for(i=0; i<n-1; i++) {\n      p = w(k=i);\n      \n      for(j=i+1; j<n; j++) if(w(j)>=p) p = w(k=j);\n      \n      if(k!=i) {\n        w(k) = w(i);\n        w(i) = p;\n        \n        for(j=0; j<n; j++) {\n          p       = v[j][i];\n          v[j][i] = v[j][k];\n          v[j][k] = p;\n        }\n        \n        for(j=0; j<m; j++) {\n          p       = u[j][i];\n          u[j][i] = u[j][k];\n          u[j][k] = p;\n        }\n      }\n    }\n  }\n  \n  //rank analysis\n  \n  for(r=0; r<n && w(r)>RAI_SVD_MINVALUE; r++) {};\n  \n  t = r < n ? fabs(w(n-1)) : 0.0;\n  r = 0;\n  s = 0.0;\n  while(r<n && w(r)>t && w(r)+s>s) s += w(r++);\n  \n  return r;\n}\n\ndouble determinantSubroutine(double **A, uint n) {\n  if(n==1) return A[0][0];\n  if(n==2) return A[0][0]*A[1][1]-A[0][1]*A[1][0];\n  uint i, j;\n  double d=0;\n  double **B=new double*[n-1];\n  for(i=0; i<n; i++) {\n    for(j=0; j<n; j++) {\n      if(j<i) B[j]=&A[j][1];\n      if(j>i) B[j-1]=&A[j][1];\n    }\n    d+=((i&1)?-1.:1.) * A[i][0] * determinantSubroutine(B, n-1);\n  }\n  delete[] B; B=NULL;\n  return d;\n}\n\ndouble determinant(const arr& A) {\n  CHECK(A.nd==2 && A.d0==A.d1, \"determinants require a squared 2D matrix\");\n  rai::Array<double*> tmp;\n  return determinantSubroutine(A.getCarray(tmp), A.d0);\n}\n\ndouble cofactor(const arr& A, uint i, uint j) {\n  CHECK(A.nd==2 && A.d0==A.d1, \"determinants require a squared 2D matrix\");\n  arr B=A;\n  B.delRows(i);\n  B.delColumns(j, 1);\n  return ((i&1)^(j&1)?-1.:1) * determinant(B);\n}\n\n/** Given a distribution p over a discrete domain {0, .., p.N-1}\n    Stochastic Universal Sampling draws n samples from this\n    distribution, stored as integers in s */\nuintA sampleMultinomial_SUS(const arr& p, uint n) {\n  //following T. Baeck \"EA in Theo. and Prac.\" p120\n  uintA s(n);\n  double sum=0, ptr=rnd.uni();\n  uint i, j=0;\n  for(i=0; i<p.N; i++) {\n    sum+=p(i)*n;\n    while(sum>ptr) { s(j)=i; j++; ptr+=1.; }\n  }\n  //now, 'sum' should = 'n' and 'ptr' has been 'n'-times increased -> 'j=n'\n  CHECK_EQ(j,n, \"error in rnd::sampleMultinomial_SUS(p, n) -> p not normalized?\");\n  return s;\n}\n\nuint sampleMultinomial(const arr& p) {\n  double sum=0, ptr=rnd.uni();\n  uint i;\n  for(i=0; i<p.N; i++) {\n    sum+=p(i);\n    if(sum>ptr) return i;\n  }\n  HALT(\"error in rnd::sampleMultinomial(p) -> p not normalized? \" <<p);\n  return 0;\n}\n\n/// calls gnuplot to display the (n, 2) or (n, 3) array (n=number of points of line or surface)\nvoid gnuplot(const arr& X, bool pauseMouse, bool persist, const char* PDFfile) {\n  rai::arrayBrackets=\"  \";\n  if(X.nd==2 && X.d1!=2) {  //assume array -> splot\n    FILE(\"z.pltX\") <<X;\n    gnuplot(\"splot 'z.pltX' matrix with pm3d, 'z.pltX' matrix with lines\", pauseMouse, persist, PDFfile);\n    return;\n  }\n  if(X.nd==2 && X.d1==2) {  //assume curve -> plot\n    FILE(\"z.pltX\") <<X;\n    gnuplot(\"plot 'z.pltX' us 1:2\", pauseMouse, persist, PDFfile);\n    return;\n  }\n  if(X.nd==1) {  //assume curve -> plot\n    arr Y;\n    Y.referTo(X);\n    Y.reshape(Y.N, 1);\n    FILE(\"z.pltX\") <<Y;\n    gnuplot(\"plot 'z.pltX' us 1\", pauseMouse, persist, PDFfile);\n    return;\n  }\n}\n\narr bootstrap(const arr& x) {\n  arr y(x.N);\n  for(uint i=0; i<y.N; i++) y(i) = x(rnd(y.N));\n  return y;\n}\n\nvoid write(const arrL& X, const char *filename, const char *ELEMSEP, const char *LINESEP, const char *BRACKETS, bool dimTag, bool binary) {\n  std::ofstream fil;\n  rai::open(fil, filename);\n  catCol(X).write(fil, ELEMSEP, LINESEP, BRACKETS, dimTag, binary);\n  fil.close();\n}\n\n//===========================================================================\n//\n/// @name simple image formats\n//\n\n/** save data as ppm or pgm. Images are (height, width, [0, 2, 3, 4])-dim\n  byte arrays, where the 3rd dimension determines whether it's a grey\n  (0), grey-alpha (2), RGB (3), or RGBA (4) image */\nvoid write_ppm(const byteA &img, const char *file_name, bool swap_rows) {\n  if(!img.N) RAI_MSG(\"empty image\");\n  CHECK(img.nd==2 || (img.nd==3 && img.d2==3), \"only rgb or gray images to ppm\");\n  ofstream os;\n  os.open(file_name, std::ios::out | std::ios::binary);\n  if(!os.good()) HALT(\"could not open file `\" <<file_name <<\"' for output\");\n  switch(img.d2) {\n    case 0:  os <<\"P5 \" <<img.d1 <<' ' <<img.d0 <<\" 255\\n\";  break; //PGM\n    case 3:  os <<\"P6 \" <<img.d1 <<' ' <<img.d0 <<\" 255\\n\";  break; //PPM\n    default: NIY;\n  }\n  if(!swap_rows) {\n    os.write((char*)img.p, img.N);\n  } else {\n    if(img.d2)\n      for(uint i=img.d0; i--;) os.write((char*)&img(i, 0, 0), img.d1*img.d2);\n    else\n      for(uint i=img.d0; i--;) os.write((char*)&img(i, 0), img.d1);\n  }\n}\n\n/** read data from an ppm or pgm file */\nvoid read_ppm(byteA &img, const char *file_name, bool swap_rows) {\n  uint mode, width, height, max;\n  ifstream is;\n  is.open(file_name, std::ios::in | std::ios::binary);\n  if(!is.good()) HALT(\"could not open file `\" <<file_name <<\"' for input\");\n  if(is.get()!='P') HALT(\"NO PPM FILE:\" <<file_name);\n  is >>mode;\n  if(rai::peerNextChar(is)=='#') rai::skipRestOfLine(is);\n  is >>width >>height >>max;\n  is.get(); //MUST be a white character if everything went ok\n  switch(mode) {\n    case 5:  img.resize(height, width);    break; //PGM\n    case 6:  img.resize(height, width, 3);  break; //PPM\n  }\n  if(!swap_rows) {\n    is.read((char*)img.p, img.N);\n  } else {\n    for(uint i=img.d0; i--;) is.read((char*)&img(i, 0, 0), img.d1*img.d2);\n  }\n}\n\n/// add an alpha channel to an image array\nvoid add_alpha_channel(byteA &img, byte alpha) {\n  uint w=img.d1, h=img.d0;\n  img.reshape(h*w, 3);\n  img.insColumns(3, 1);\n  for(uint i=0; i<img.d0; i++) img(i, 3)=alpha;\n  img.reshape(h, w, 4);\n}\n\n/// add an alpha channel to an image array\nvoid remove_alpha_channel(byteA &img) {\n  uint w=img.d1, h=img.d0;\n  img.reshape(h*w, 4);\n  img.delColumns(3, 1);\n  img.reshape(h, w, 3);\n}\n\nvoid image_halfResolution(byteA &img) {\n  byteA org = img;\n  img.resize(org.d0/2, org.d1/2, org.d2);\n  for(uint i=0; i<img.d0; i++) for(uint j=0; j<img.d1; j++) for(uint k=0; k<img.d2; k++) {\n        float v = (float)org(2*i, 2*j, k) + (float)org(2*i, 2*j+1, k)\n                  + (float)org(2*i+1, 2*j, k) +(float)org(2*i+1, 2*j+1, k);\n        v /= 4;\n        img(i,j,k) = (byte)v;\n      }\n}\n\nvoid flip_image(byteA &img) {\n  if(!img.N) return;\n  uint h=img.d0, n=img.N/img.d0;\n  byteA line(n);\n  byte *a, *b, *c;\n  for(uint i=0; i<h/2; i++) {\n    a=img.p+i*n;\n    b=img.p+(h-1-i)*n;\n    c=line.p;\n    memmove(c, a, n);\n    memmove(a, b, n);\n    memmove(b, c, n);\n  }\n}\n\nvoid flip_image(floatA &img) {\n  if(!img.N) return;\n  uint h=img.d0, n=img.N/img.d0;\n  floatA line(n);\n  float *a, *b, *c;\n  uint s=sizeof(float);\n  for(uint i=0; i<h/2; i++) {\n    a=img.p+i*n;\n    b=img.p+(h-1-i)*n;\n    c=line.p;\n    memmove(c, a, n*s);\n    memmove(a, b, n*s);\n    memmove(b, c, n*s);\n  }\n}\n\n/// make grey scale image\nvoid make_grey(byteA &img) {\n  CHECK(img.nd==3 && (img.d2==3 || img.d1==4), \"makeGray requires color image as input\");\n  byteA tmp;\n  tmp.resize(img.d0, img.d1);\n  for(uint i=0; i<img.d0; i++) for(uint j=0; j<img.d1; j++) {\n      tmp(i, j) = ((uint)img(i, j, 0) + img(i, j, 1) + img(i, j, 2))/3;\n    }\n  img=tmp;\n}\n\n/// make a grey image and RGA image\nvoid make_RGB(byteA &img) {\n  CHECK_EQ(img.nd,2, \"make_RGB requires grey image as input\");\n  byteA tmp;\n  tmp.resize(img.d0, img.d1, 3);\n  for(uint i=0; i<img.d0; i++) for(uint j=0; j<img.d1; j++) {\n      tmp(i, j, 0) = img(i, j);\n      tmp(i, j, 1) = img(i, j);\n      tmp(i, j, 2) = img(i, j);\n    }\n  img=tmp;\n}\n\n/// make a grey image and RGA image\nvoid make_RGB2BGRA(byteA &img) {\n  CHECK(img.nd==3 && img.d2==3, \"make_RGB2RGBA requires color image as input\");\n  byteA tmp;\n  tmp.resize(img.d0, img.d1, 4);\n  for(uint i=0; i<img.d0; i++) for(uint j=0; j<img.d1; j++) {\n      tmp(i, j, 0) = img(i, j, 2);\n      tmp(i, j, 1) = img(i, j, 1);\n      tmp(i, j, 2) = img(i, j, 0);\n      tmp(i, j, 3) = 255;\n    }\n  img=tmp;\n}\n\n/// make a grey image and RGA image\nvoid swap_RGB_BGR(byteA &img) {\n  CHECK(img.nd==3 && img.d2==3, \"make_RGB2RGBA requires color image as input\");\n  byte *b=img.p, *bstop=img.p+img.N;\n  byte z;\n  for(; b<bstop; b+=3) {\n    z=b[0]; b[0]=b[2]; b[2]=z;\n  }\n}\n\nuintA getIndexTuple(uint i, const uintA &d) {\n  CHECK(i<product(d), \"out of range\");\n  uintA I(d.N);\n  I.setZero();\n  for(uint j=d.N; j--;) {\n    I.p[j] = i%d.p[j];\n    i -= I.p[j];\n    i /= d.p[j];\n  }\n  return I;\n}\n\nvoid lognormScale(arr& P, double& logP, bool force) {\n#ifdef RAI_NoLognormScale\n  return;\n#endif\n  double Z=0.;\n  for(uint i=0; i<P.N; i++) Z += fabs(P.elem(i));\n  if(!force && Z>1e-3 && Z<1e3) return;\n  if(fabs(Z-1.)<1e-10) return;\n  if(Z>1e-100) {\n    logP+=::log(Z);\n    P/=Z;\n  } else {\n    logP+=::log(Z);\n    P=1.;\n    RAI_MSG(\"ill-conditioned table factor for norm scaling\");\n  }\n}\n\nvoid sparseProduct(arr& y, arr& A, const arr& x) {\n  if(!A.special && !x.special) {\n    innerProduct(y, A, x);\n    return;\n  }\n#if 0\n  NIY; //replace by Eigen\n#else\n  if(isSparseMatrix(A) && !isSparseVector(x)) {\n    uint i, j;\n    int *k, *kstop;\n    y.resize(A.d0); y.setZero();\n    double *Ap=A.p;\n    intA& A_elems = dynamic_cast<rai::SparseMatrix*>(A.special)->elems;\n    for(k=A_elems.p, kstop=A_elems.p+A_elems.N; k!=kstop; Ap++) {\n      i=*k; k++;\n      j=*k; k++;\n      y.p[i] += (*Ap) * x.p[j];\n    }\n    return;\n  }\n  if(isSparseMatrix(A) && isSparseVector(x)) {\n    A.sparse().setupRowsCols();\n    rai::SparseVector *sx = dynamic_cast<rai::SparseVector*>(x.special);\n    CHECK(x.nd==1 && A.nd==2 && x.d0==A.d1, \"not a proper matrix-vector multiplication\");\n    uint i, j, n;\n    int *k, *kstop;\n    uint *l, *lstop;\n    y.sparseVec();\n    y.d0 = A.d0;\n    intA& y_elems= dynamic_cast<rai::SparseVector*>(y.special)->elems;\n    double *xp=x.p;\n    intA& x_elems = sx->elems;\n    for(k=x_elems.p, kstop=x_elems.p+x_elems.N; k!=kstop; xp++) {\n      j=*k; k++;\n      uintA& A_col = dynamic_cast<rai::SparseMatrix*>(A.special)->cols(j);\n      for(l=A_col.p, lstop=A_col.p+A_col.N; l!=lstop;) {\n        i =*l; l++;\n        n =*l; l++;\n#if 0\n        slot=&y_col(i);\n        if(*slot==(uint)-1) {\n          *slot=y.N;\n          y.resizeMEM(y.N+1, true); y(y.N-1)=0.;\n          y_elems.append(i);\n          CHECK_EQ(y_elems.N,y.N, \"\");\n        }\n        i=*slot;\n        y(i) += A.elem(n) * (*xp);\n#else\n        double a = A.elem(n) * (*xp);\n        y_elems.append(i);\n        y.resizeMEM(y.N+1, true);\n        y.elem(y.N-1)=a;\n#endif\n      }\n    }\n    return;\n  }\n  if(!isSparseMatrix(A) && isSparseVector(x)) {\n    uint i, j, d1=A.d1;\n    int *k, *kstop;\n    y.resize(A.d0); y.setZero();\n    double *xp=x.p;\n    intA& elems = dynamic_cast<rai::SparseMatrix*>(x.special)->elems;\n    for(k=elems.p, kstop=elems.p+elems.N; k!=kstop; xp++) {\n      j=*k; k++;\n      for(i=0; i<A.d0; i++) {\n        y.p[i] += A.p[i*d1+j] * (*xp);\n      }\n    }\n    return;\n  }\n#endif\n}\n\nvoid scanArrFile(const char* name) {\n  ifstream is(name, std::ios::binary);\n  CHECK(is.good(), \"couldn't open file \" <<name);\n  arr x;\n  rai::String tag;\n  for(;;) {\n    tag.read(is, \" \\n\\r\\t\", \" \\n\\r\\t\");\n    if(!is.good() || tag.N==0) return;\n    x.readTagged(is, NULL);\n    x.writeTagged(cout, tag);  cout <<endl;\n    if(!is.good()) return;\n  }\n}\n\n#ifndef CHECK_EPS\n#  define CHECK_EPS 1e-8\n#endif\n\n/// numeric (finite difference) computation of the gradient\narr finiteDifferenceGradient(const ScalarFunction& f, const arr& x, arr& Janalytic) {\n  arr dx, J;\n  double y, dy;\n  y=f(Janalytic, NoArr, x);\n  \n  J.resize(x.N);\n  double eps=CHECK_EPS;\n  uint i;\n  for(i=0; i<x.N; i++) {\n    dx=x;\n    dx.elem(i) += eps;\n    dy = f(NoArr, NoArr, dx);\n    dy = (dy-y)/eps;\n    J(i)=dy;\n  }\n  return J;\n}\n\n/// numeric (finite difference) computation of the gradient\narr finiteDifferenceJacobian(const VectorFunction& f, const arr& _x, arr& Janalytic) {\n  arr x=_x;\n  arr y, dx, dy, J;\n  f(y, Janalytic, x);\n  if(isRowShifted(Janalytic)\n     || isSparseMatrix(Janalytic)){\n    Janalytic = unpack(Janalytic);\n  }\n  \n  J.resize(y.N, x.N);\n  double eps=CHECK_EPS;\n  uint i, k;\n  for(i=0; i<x.N; i++) {\n    dx=x;\n    dx.elem(i) += eps;\n    f(dy, NoArr, dx);\n    dy = (dy-y)/eps;\n    for(k=0; k<y.N; k++) J(k, i)=dy.elem(k);\n  }\n  J.reshapeAs(Janalytic);\n  return J;\n}\n\n/// numeric (finite difference) check of the gradient of f at x\nbool checkGradient(const ScalarFunction& f,\n                   const arr& x, double tolerance, bool verbose) {\n  arr J;\n  arr JJ = finiteDifferenceGradient(f, x, J);\n  uint i;\n  double md=maxDiff(J, JJ, &i);\n  if(md>tolerance && md>fabs(J.elem(i))*tolerance) {\n    RAI_MSG(\"checkGradient -- FAILURE -- max diff=\" <<md <<\" |\"<<J.elem(i)<<'-'<<JJ.elem(i)<<\"| (stored in files z.J_*)\");\n    J >>FILE(\"z.J_analytical\");\n    JJ >>FILE(\"z.J_empirical\");\n    //cout <<\"\\nmeasured grad=\" <<JJ <<\"\\ncomputed grad=\" <<J <<endl;\n    //HALT(\"\");\n    return false;\n  } else {\n    cout <<\"checkGradient -- SUCCESS (max diff error=\" <<md <<\")\" <<endl;\n  }\n  return true;\n}\n\nbool checkHessian(const ScalarFunction& f, const arr& x, double tolerance, bool verbose) {\n  arr g, H, dx, dy, Jg;\n  f(g, H, x);\n  if(isRowShifted(H)) H = unpack(H);\n  \n  Jg.resize(g.N, x.N);\n  double eps=CHECK_EPS;\n  uint i, k;\n  for(i=0; i<x.N; i++) {\n    dx=x;\n    dx.elem(i) += eps;\n    f(dy, NoArr, dx);\n    dy = (dy-g)/eps;\n    for(k=0; k<g.N; k++) Jg(k, i)=dy.elem(k);\n  }\n  Jg.reshapeAs(H);\n  double md=maxDiff(H, Jg, &i);\n  //   J >>FILE(\"z.J\");\n  //   JJ >>FILE(\"z.JJ\");\n  if(md>tolerance) {\n    RAI_MSG(\"checkHessian -- FAILURE -- max diff=\" <<md <<\" |\"<<H.elem(i)<<'-'<<Jg.elem(i)<<\"| (stored in files z.J_*)\");\n    H >>FILE(\"z.J_analytical\");\n    Jg >>FILE(\"z.J_empirical\");\n    //cout <<\"\\nmeasured grad=\" <<JJ <<\"\\ncomputed grad=\" <<J <<endl;\n    //HALT(\"\");\n    return false;\n  } else {\n    cout <<\"checkHessian -- SUCCESS (max diff error=\" <<md <<\")\" <<endl;\n  }\n  return true;\n}\n\nbool checkJacobian(const VectorFunction& f,\n                   const arr& x, double tolerance, bool verbose) {\n  arr J;\n  arr JJ = finiteDifferenceJacobian(f, x, J);\n  uint i;\n  double md=maxDiff(J, JJ, &i);\n  if(md>tolerance && md>fabs(J.elem(i))*tolerance) {\n    RAI_MSG(\"checkJacobian -- FAILURE -- max diff=\" <<md <<\" |\"<<J.elem(i)<<'-'<<JJ.elem(i)<<\"| (stored in files z.J_*)\");\n    J >>FILE(\"z.J_analytical\");\n    JJ >>FILE(\"z.J_empirical\");\n    if(verbose) {\n      cout <<\"J_analytical = \" <<J\n           <<\"\\nJ_empirical  = \" <<JJ <<endl;\n    }\n    return false;\n  } else {\n    cout <<\"checkJacobian -- SUCCESS (max diff error=\" <<md <<\")\" <<endl;\n  }\n  return true;\n}\n\n#define EXP ::exp //rai::approxExp\n\ndouble NNinv(const arr& a, const arr& b, const arr& Cinv) {\n  double d=sqrDistance(Cinv, a, b);\n  double norm = ::sqrt(lapack_determinantSymPosDef((1./RAI_2PI)*Cinv));\n  return norm*EXP(-.5*d);\n}\ndouble logNNinv(const arr& a, const arr& b, const arr& Cinv) {\n  NIY;\n  return 1;\n  /*\n  arr d=a-b;\n  double norm = ::sqrt(fabs(rai::determinant_LU((1./RAI_2PI)*Cinv)));\n  return ::log(norm) + (-.5*scalarProduct(Cinv, d, d));\n  */\n}\ndouble logNNprec(const arr& a, const arr& b, double prec) {\n  uint n=a.N;\n  arr d=a-b;\n  double norm = pow(prec/RAI_2PI, .5*n);\n  return ::log(norm) + (-.5*prec*scalarProduct(d, d));\n}\ndouble logNN(const arr& a, const arr& b, const arr& C) {\n  arr Cinv;\n  inverse_SymPosDef(Cinv, C);\n  return logNNinv(a, b, Cinv);\n}\ndouble NN(const arr& a, const arr& b, const arr& C) {\n  arr Cinv;\n  inverse_SymPosDef(Cinv, C);\n  return NNinv(a, b, Cinv);\n}\n/// non-normalized!! Gaussian function (f(0)=1)\ndouble NNNNinv(const arr& a, const arr& b, const arr& Cinv) {\n  double d=sqrDistance(Cinv, a, b);\n  return EXP(-.5*d);\n}\ndouble NNNN(const arr& a, const arr& b, const arr& C) {\n  arr Cinv;\n  inverse_SymPosDef(Cinv, C);\n  return NNNNinv(a, b, Cinv);\n}\ndouble NNzeroinv(const arr& x, const arr& Cinv) {\n  double norm = ::sqrt(lapack_determinantSymPosDef((1./RAI_2PI)*Cinv));\n  return norm*EXP(-.5*scalarProduct(Cinv, x, x));\n}\n/// gradient of a Gaussian\ndouble dNNinv(const arr& x, const arr& a, const arr& Ainv, arr& grad) {\n  double y=NNinv(x, a, Ainv);\n  grad = y * Ainv * (a-x);\n  return y;\n}\n/// gradient of a non-normalized Gaussian\ndouble dNNNNinv(const arr& x, const arr& a, const arr& Ainv, arr& grad) {\n  double y=NNNNinv(x, a, Ainv);\n  grad = y * Ainv * (a-x);\n  return y;\n}\ndouble NNsdv(const arr& a, const arr& b, double sdv) {\n  double norm = 1./(::sqrt(RAI_2PI)*sdv);\n  return norm*EXP(-.5*sqrDistance(a, b)/(sdv*sdv));\n}\ndouble NNzerosdv(const arr& x, double sdv) {\n  double norm = 1./(::sqrt(RAI_2PI)*sdv);\n  return norm*EXP(-.5*sumOfSqr(x)/(sdv*sdv));\n}\n\nrai::String singleString(const StringA& strs) {\n  rai::String s;\n  for(const rai::String& str:strs) {\n    if(s.N) s<<\"_\";\n    s<<str;\n  }\n  return s;\n}\n\n//===========================================================================\n//\n// LAPACK\n//\n\n// file:///usr/share/doc/liblapack-doc/lug/index.html\n\n#ifdef RAI_LAPACK\n#if 1 //def NO_BLAS\nvoid blas_MM(arr& X, const arr& A, const arr& B) {       rai::useLapack=false; innerProduct(X, A, B); rai::useLapack=true; };\nvoid blas_MsymMsym(arr& X, const arr& A, const arr& B) { rai::useLapack=false; innerProduct(X, A, B); rai::useLapack=true; };\nvoid blas_Mv(arr& y, const arr& A, const arr& x) {       rai::useLapack=false; innerProduct(y, A, x); rai::useLapack=true; };\nvoid blas_A_At(arr& X, const arr& A) { X = A*~A; }\nvoid blas_At_A(arr& X, const arr& A) { X = ~A*A; }\n#else\nvoid blas_MM(arr& X, const arr& A, const arr& B) {\n  CHECK_EQ(A.d1,B.d0, \"matrix multiplication: wrong dimensions\");\n  X.resize(A.d0, B.d1);\n  cblas_dgemm(CblasRowMajor,\n              CblasNoTrans, CblasNoTrans,\n              A.d0, B.d1, A.d1,\n              1., A.p, A.d1,\n              B.p, B.d1,\n              0., X.p, X.d1);\n#if 0//test\n  rai::useLapack=false;\n  std::cout  <<\"blas_MM error = \" <<maxDiff(A*B, X, 0) <<std::endl;\n  rai::useLapack=true;\n#endif\n}\n\nvoid blas_A_At(arr& X, const arr& A) {\n  uint n=A.d0;\n  CHECK(n,\"blas doesn't like n=0 !\");\n  X.resize(n,n);\n  cblas_dsyrk(CblasRowMajor, CblasUpper, CblasNoTrans,\n              X.d0, A.d1,\n              1.f, A.p, A.d1,\n              0., X.p, X.d1);\n  for(uint i=0; i<n; i++) for(uint j=0; j<i; j++) X.p[i*n+j] = X.p[j*n+i]; //fill in the lower triangle\n#if 0//test\n  rai::useLapack=false;\n  std::cout  <<\"blas_MM error = \" <<maxDiff(A*~A, X, 0) <<std::endl;\n  rai::useLapack=true;\n#endif\n}\n\nvoid blas_At_A(arr& X, const arr& A) {\n  uint n=A.d1;\n  CHECK(n,\"blas doesn't like n=0 !\");\n  X.resize(n,n);\n  cblas_dsyrk(CblasRowMajor, CblasUpper, CblasTrans,\n              X.d0, A.d0,\n              1.f, A.p, A.d1,\n              0., X.p, X.d1);\n  for(uint i=0; i<n; i++) for(uint j=0; j<i; j++) X.p[i*n+j] = X.p[j*n+i]; //fill in the lower triangle\n#if 0//test\n  rai::useLapack=false;\n  std::cout  <<\"blas_MM error = \" <<maxDiff(~A*A, X, 0) <<std::endl;\n  rai::useLapack=true;\n#endif\n}\n\nvoid blas_Mv(arr& y, const arr& A, const arr& x) {\n  CHECK_EQ(A.d1,x.N, \"matrix multiplication: wrong dimensions\");\n  y.resize(A.d0);\n  if(!x.N && !A.d1) { y.setZero(); return; }\n  cblas_dgemv(CblasRowMajor,\n              CblasNoTrans,\n              A.d0, A.d1,\n              1., A.p, A.d1,\n              x.p, 1,\n              0., y.p, 1);\n#if 0 //test\n  rai::useLapack=false;\n  std::cout  <<\"blas_Mv error = \" <<maxDiff(A*x, y, 0) <<std::endl;\n  rai::useLapack=true;\n#endif\n}\n\nvoid blas_MsymMsym(arr& X, const arr& A, const arr& B) {\n  CHECK_EQ(A.d1,B.d0, \"matrix multiplication: wrong dimensions\");\n  X.resize(A.d0, B.d1);\n  cblas_dsymm(CblasRowMajor,\n              CblasLeft, CblasUpper,\n              A.d0, B.d1,\n              1., A.p, A.d1,\n              B.p, B.d1,\n              0., X.p, X.d1);\n#if 0 //test\n  arr Y(A.d0, B.d1);\n  uint i, j, k;\n  Y.setZero();\n  for(i=0; i<Y.d0; i++) for(j=0; j<Y.d1; j++) for(k=0; k<A.d1; k++)\n        Y(i, j) += A(i, k) * B(k, j);\n  std::cout  <<\"blas_MsymMsym error = \" <<sqrDistance(X, Y) <<std::endl;\n#endif\n}\n\n#endif //RAI_NOBLAS\n\narr lapack_Ainv_b_sym(const arr& A, const arr& b) {\n  if(isSparseMatrix(A)) {\n    return eigen_Ainv_b(A, b);\n  }\n  arr x;\n  if(b.nd==2) { //b is a matrix (unusual) repeat for each col:\n    RAI_MSG(\"TODO: directly call lapack with the matrix!\")\n    arr bT = ~b;\n    x.resizeAs(bT);\n    for(uint i=0; i<bT.d0; i++) x[i]() = lapack_Ainv_b_sym(A, bT[i]);\n    x=~x;\n    return x;\n  }\n  if(isRowShifted(A)) {\n    RowShifted *Aaux = (RowShifted*) A.special;\n    if(!Aaux->symmetric) HALT(\"this is not a symmetric matrix\");\n    for(uint i=0; i<A.d0; i++) if(Aaux->rowShift(i)!=i) HALT(\"this is not shifted as an upper triangle\");\n  }\n  x=b;\n  arr Acol=A;\n  integer N=A.d0, KD=A.d1-1, NRHS=1, LDAB=A.d1, INFO;\n  try {\n    if(!isRowShifted(A)) {\n      dposv_((char*)\"L\", &N, &NRHS, Acol.p, &N, x.p, &N, &INFO);\n    } else {\n      //assumes symmetric and upper banded\n      dpbsv_((char*)\"L\", &N, &KD, &NRHS, Acol.p, &LDAB, x.p, &N, &INFO);\n    }\n  } catch(...) {\n    HALT(\"here\");\n  }\n  if(INFO) {\n#if 1\n    uint k=(N>3?3:N); //number of required eigenvalues\n    rai::Array<integer> IWORK(5*N), IFAIL(N);\n    arr WORK(10*(3*N)), Acopy=A;\n    integer M, IL=1, IU=k, LDQ=0, LDZ=1, LWORK=WORK.N;\n    double VL=0., VU=0., ABSTOL=1e-8;\n    arr sig(N);\n    if(!isSpecial(A)) {\n//      sig.resize(N);\n//      dsyev_ ((char*)\"N\", (char*)\"L\", &N, A.p, &N, sig.p, WORK.p, &LWORK, &INFO);\n//      lapack_EigenDecomp(A, sig, NoArr);\n      dsyevx_((char*)\"N\", (char*)\"I\", (char*)\"L\", &N, Acopy.p, &LDAB, &VL, &VU, &IL, &IU, &ABSTOL, &M, sig.p, (double*)NULL, &LDZ, WORK.p, &LWORK, IWORK.p, IFAIL.p, &INFO);\n    } else if(isRowShifted(A)){\n      dsbevx_((char*)\"N\", (char*)\"I\", (char*)\"L\", &N, &KD, Acopy.p, &LDAB, (double*)NULL, &LDQ, &VL, &VU, &IL, &IU, &ABSTOL, &M, sig.p, (double*)NULL, &LDZ, WORK.p, IWORK.p, IFAIL.p, &INFO);\n    } else NIY;\n    sig.resizeCopy(k);\n#else\n    arr sig, eig;\n    lapack_EigenDecomp(A, sig, eig);\n#endif\n    rai::errString <<\"lapack_Ainv_b_sym error info = \" <<INFO\n                   <<\". Typically this is because A is not pos-def.\\nsmallest \"<<k<<\" eigenvalues=\" <<sig;\n    throw(rai::errString.p);\n//    THROW(\"lapack_Ainv_b_sym error info = \" <<INFO\n//         <<\". Typically this is because A is not pos-def.\\nsmallest \"<<k<<\" eigenvalues=\" <<sig);\n  }\n  return x;\n}\n\nuint lapack_SVD(\n  arr& U,\n  arr& d,\n  arr& Vt,\n  const arr& A) {\n  arr Atmp, work;\n  Atmp=A;\n  //transpose(Atmp, A);\n  integer M=A.d0, N=A.d1, D=M<N?M:N;\n  U.resize(M, D);\n  d.resize(D);\n  Vt.resize(D, N);\n  work.resize(10*(M+N));\n  integer info, wn=work.N;\n  dgesvd_((char*)\"S\", (char*)\"S\", &N, &M, Atmp.p, &N, d.p, Vt.p, &N, U.p, &D, work.p, &wn, &info);\n  CHECK(!info, \"LAPACK SVD error info = \" <<info);\n  return D;\n}\n\nvoid lapack_LU(arr& LU, const arr& A) {\n  LU = A;\n  integer M=A.d0, N=A.d1, D=M<N?M:N, info;\n  intA piv(D);\n  dgetrf_(&N, &M, LU.p, &N, (integer*)piv.p, &info);\n  CHECK(!info, \"LAPACK SVD error info = \" <<info);\n}\n\nvoid lapack_RQ(arr& R, arr &Q, const arr& A) {\n  transpose(Q, A);\n  R.resizeAs(A); R.setZero();\n  integer M=A.d0, N=A.d1, D=M<N?M:N, LWORK=M*N, info;\n  arr tau(D), work(LWORK);\n  dgerqf_(&N, &M, Q.p, &N, tau.p, work.p, &LWORK, &info);\n  CHECK(!info, \"LAPACK RQ error info = \" <<info);\n  for(int i=0; i<M; i++) for(int j=0; j<=i; j++) R(j, i) = Q(i, j); //copy upper triangle\n  dorgrq_(&N, &M, &N, Q.p, &N, tau.p, work.p, &LWORK, &info);\n  CHECK(!info, \"LAPACK RQ error info = \" <<info);\n  Q=~Q;\n  //cout <<\"\\nR=\" <<R <<\"\\nQ=\" <<Q <<\"\\nRQ=\" <<R*Q <<\"\\nA=\" <<A <<endl;\n}\n\nvoid lapack_EigenDecomp(const arr& symmA, arr& Evals, arr& Evecs) {\n  CHECK(symmA.nd==2 && symmA.d0==symmA.d1, \"not symmetric\");\n  arr work, symmAcopy = symmA;\n  integer N=symmA.d0;\n  Evals.resize(N);\n  work.resize(10*(3*N));\n  integer info, wn=work.N;\n  if(!!Evecs) {\n    dsyev_((char*)\"V\", (char*)\"L\", &N, symmAcopy.p, &N, Evals.p, work.p, &wn, &info);\n    Evecs = symmAcopy;\n  } else {\n    dsyev_((char*)\"N\", (char*)\"L\", &N, symmAcopy.p, &N, Evals.p, work.p, &wn, &info);\n  }\n  CHECK(!info, \"lapack_EigenDecomp error info = \" <<info);\n}\n\narr lapack_kSmallestEigenValues_sym(const arr& A, uint k) {\n  if(k>A.d0) k=A.d0; //  CHECK_LE(k, A.d0,\"\");\n  integer N=A.d0, KD=A.d1-1, LDAB=A.d1, INFO;\n  rai::Array<integer> IWORK(5*N), IFAIL(N);\n  arr WORK(10*(3*N)), Acopy=A;\n  integer M, IL=1, IU=k, LDQ=0, LDZ=1, LWORK=WORK.N;\n  double VL=0., VU=0., ABSTOL=1e-8;\n  arr sig(N);\n  if(!isRowShifted(A)) {\n    dsyevx_((char*)\"N\", (char*)\"I\", (char*)\"L\", &N, Acopy.p, &LDAB, &VL, &VU, &IL, &IU, &ABSTOL, &M, sig.p, (double*)NULL, &LDZ, WORK.p, &LWORK, IWORK.p, IFAIL.p, &INFO);\n  } else {\n    dsbevx_((char*)\"N\", (char*)\"I\", (char*)\"L\", &N, &KD, Acopy.p, &LDAB, (double*)NULL, &LDQ, &VL, &VU, &IL, &IU, &ABSTOL, &M, sig.p, (double*)NULL, &LDZ, WORK.p, IWORK.p, IFAIL.p, &INFO);\n  }\n  sig.resizeCopy(k);\n  return sig;\n}\n\nbool lapack_isPositiveSemiDefinite(const arr& symmA) {\n  // Check that all eigenvalues are nonnegative.\n  arr d, V;\n  lapack_EigenDecomp(symmA, d, V);\n  // d is nondecreasing ??!??\n  for(double x:d) if(x<0.) return false;\n  return true;\n}\n\n/// A=C^T C (C is upper triangular!)\nvoid lapack_cholesky(arr& C, const arr& A) {\n  CHECK_EQ(A.d0,A.d1, \"\");\n  integer n=A.d0;\n  integer info;\n  C=A;\n  //compute cholesky\n  dpotrf_((char*)\"L\", &n, C.p, &n, &info);\n  CHECK(!info, \"LAPACK Cholesky decomp error info = \" <<info);\n  //clear the lower triangle:\n  uint i, j;\n  for(i=0; i<C.d0; i++) for(j=0; j<i; j++) C(i, j)=0.;\n}\n\nconst char *potrf_ERR=\"\\n\\\n*  INFO    (output) INTEGER\\n\\\n*          = 0:  successful exit\\n\\\n*          < 0:  if INFO = -i, the i-th argument had an illegal value\\n\\\n*          > 0:  if INFO = i, the leading minor of order i is not\\n\\\n*                positive definite, and the factorization could not be\\n\\\n*                completed.\\n\";\n\nvoid lapack_mldivide(arr& X, const arr& A, const arr& B) {\n  if(isSparseMatrix(A)) {\n    X = eigen_Ainv_b(A, B);\n    return;\n  }\n\n  CHECK_EQ(A.nd, 2, \"A in Ax=b must be a NxN matrix.\");\n  CHECK_EQ(A.d0, A.d1, \"A in Ax=b must be square matrix.\");\n  CHECK(B.nd==1 || B.nd==2, \"b in Ax=b must be a vector or matrix.\");\n  CHECK_EQ(A.d0, B.d0, \"b and A must have the same amount of rows in Ax=b.\");\n  \n  X = ~B;\n  arr LU = ~A;\n  integer N = A.d0, NRHS = (B.nd==1?1:B.d1), LDA = A.d1, INFO;\n  rai::Array<integer> IPIV(N);\n  \n  dgesv_(&N, &NRHS, LU.p, &LDA, IPIV.p, X.p, &LDA, &INFO);\n  CHECK(!INFO, \"LAPACK gaussian elemination error info = \" <<INFO);\n  \n  if(B.nd==1) X.reshape(X.N);\n  else X = ~X;\n}\n\nvoid lapack_choleskySymPosDef(arr& Achol, const arr& A) {\n  if(isRowShifted(A)) {\n    RowShifted *Aaux = (RowShifted*) A.special;\n    if(!Aaux->symmetric) HALT(\"this is not a symmetric matrix\");\n    for(uint i=0; i<A.d0; i++) if(Aaux->rowShift(i)!=i) HALT(\"this is not shifted as an upper triangle\");\n    \n    Achol=A;\n    integer N=A.d0, KD=A.d1-1, LDAB=A.d1, INFO;\n    \n    dpbtrf_((char*)\"L\", &N, &KD, Achol.p, &LDAB, &INFO);\n    CHECK(!INFO, \"LAPACK Cholesky decomp error info = \" <<INFO);\n    \n  } else {\n    NIY;\n  }\n  \n}\n\nvoid lapack_inverseSymPosDef(arr& Ainv, const arr& A) {\n  Ainv=A;\n  integer N=A.d0, LDAB=A.d1, INFO;\n  //compute cholesky\n  dpotrf_((char*)\"L\", &N, Ainv.p, &LDAB, &INFO);\n  CHECK(!INFO, \"LAPACK Cholesky decomp error info = \" <<INFO <<potrf_ERR);\n  //invert\n  dpotri_((char*)\"L\", &N, Ainv.p, &N, &INFO);\n  CHECK(!INFO, \"lapack_inverseSymPosDef error info = \" <<INFO);\n  //fill in the lower triangular elements\n  for(uint i=0; i<(uint)N; i++) for(uint j=0; j<i; j++) Ainv.p[i*N+j]=Ainv.p[j*N+i]; //fill in the lower triangle\n}\n\ndouble lapack_determinantSymPosDef(const arr& A) {\n  arr C;\n  lapack_cholesky(C, A);\n  double det=1.;\n  for(uint i=0; i<C.d0; i++) det *= C(i, i)*C(i, i);\n  return det;\n}\n\nvoid lapack_min_Ax_b(arr& x,const arr& A, const arr& b) {\n  CHECK(A.d0>=A.d1 && A.d0==b.N && b.nd==1 && A.nd==2, \"\");\n  arr At = ~A;\n  x=b;\n  integer M=A.d0, N=A.d1, NRHS=1, LWORK=2*M*N, info;\n  arr work(LWORK);\n  dgels_((char*)\"N\", &M, &N, &NRHS, At.p, &M, x.p, &M, work.p, &LWORK, &info);\n  CHECK(!info, \"dgels_ error info = \" <<info);\n  x.resizeCopy(A.d1);\n}\n\narr lapack_Ainv_b_symPosDef_givenCholesky(const arr& U, const arr& b) {\n  //in lapack (or better fortran) the rows and columns are switched!! (ARGH)\n  integer N = U.d0, LDA = U.d1, INFO, LDB = b.d0, NRHS = 1;\n  arr x;\n  if(b.nd > 1) {\n    NRHS = b.d1;\n    x = ~b; //TODO is there a chance to remove this?\n    dpotrs_((char*)\"L\", &N, &NRHS, U.p, &LDA, x.p, &LDB, &INFO);\n    CHECK(!INFO, \"lapack dpotrs error info = \" << INFO);\n    return ~x;\n  } else {\n    x = b;\n    dpotrs_((char*)\"L\", &N, &NRHS, U.p, &LDA, x.p, &LDB, &INFO);\n    CHECK(!INFO, \"lapack dpotrs error info = \" << INFO);\n    return x;\n  }\n}\n\narr lapack_Ainv_b_triangular(const arr& L, const arr& b) {\n  //DTRTRS\n  integer N = L.d0, LDA = L.d0, INFO, LDB = b.d0, NRHS = 1;\n  arr x = b;\n  dtrtrs_((char*)\"L\", (char*)\"N\", (char*)\"N\", &N, &NRHS, L.p, &LDA, x.p, &LDB, &INFO);\n  CHECK(!INFO, \"lapack dtrtrs error info = \" << INFO);\n  return x;\n}\n\n/*\ndpotri uses:\ndtrtri = invert triangular\n\ndlauum = multiply L'*L\n*/\n\n#else //if defined RAI_LAPACK\n#if !defined RAI_MSVC && defined RAI_NOCHECK\n#  warning \"RAI_LAPACK undefined - using inefficient implementations\"\n#endif\nvoid blas_MM(arr& X, const arr& A, const arr& B) { rai::useLapack=false; innerProduct(X, A, B); };\nvoid blas_MsymMsym(arr& X, const arr& A, const arr& B) { rai::useLapack=false; innerProduct(X, A, B); };\nvoid blas_Mv(arr& y, const arr& A, const arr& x) {       rai::useLapack=false; innerProduct(y, A, x); rai::useLapack=true; };\nvoid blas_A_At(arr& X, const arr& A) { NICO }\nvoid blas_At_A(arr& X, const arr& A) { NICO }\nvoid lapack_cholesky(arr& C, const arr& A) { NICO }\nuint lapack_SVD(arr& U, arr& d, arr& Vt, const arr& A) { NICO; }\nvoid lapack_LU(arr& LU, const arr& A) { NICO; }\nvoid lapack_RQ(arr& R, arr &Q, const arr& A) { NICO; }\nvoid lapack_EigenDecomp(const arr& symmA, arr& Evals, arr& Evecs) { NICO; }\nbool lapack_isPositiveSemiDefinite(const arr& symmA) { NICO; }\nvoid lapack_inverseSymPosDef(arr& Ainv, const arr& A) { NICO; }\narr lapack_kSmallestEigenValues_sym(const arr& A, uint k) { NICO; }\narr lapack_Ainv_b_sym(const arr& A, const arr& b) {\n  arr invA;\n  inverse(invA, A);\n  return invA*b;\n};\ndouble lapack_determinantSymPosDef(const arr& A) { NICO; }\nvoid lapack_mldivide(arr& X, const arr& A, const arr& b) { NICO; }\narr lapack_Ainv_b_symPosDef_givenCholesky(const arr& U, const arr&b) { return inverse(U)*b; }\narr lapack_Ainv_b_triangular(const arr& L, const arr& b) { return inverse(L)*b; }\n#endif\n\n//===========================================================================\n//\n// Eigen\n//\n\nEigen::SparseMatrix<double> conv_sparseArr2sparseEigen(const rai::SparseMatrix& S){\n  arr& Z = S.Z;\n  Eigen::SparseMatrix<double> E;\n  E.resize(Z.d0, Z.d1);\n  std::vector<Eigen::Triplet<double>> triplets;\n  triplets.reserve(Z.N);\n  for(uint k=0;k<Z.N;k++) triplets.push_back(Eigen::Triplet<double>(S.elems.p[2*k], S.elems.p[2*k+1], Z.p[k]));\n  E.setFromTriplets(triplets.begin(), triplets.end());\n  return E;\n//  cout <<E <<endl;\n}\n\narr conv_sparseEigen2sparseArr(Eigen::SparseMatrix<double>& E){\n  arr X;\n  rai::SparseMatrix& Xs = X.sparse();\n  Xs.resize(E.rows(), E.cols(), E.nonZeros());\n\n  uint n=0;\n  for(int k=0; k<E.outerSize(); ++k){\n    for(Eigen::SparseMatrix<double>::InnerIterator it(E,k); it; ++it) {\n      Xs.entry(it.row(), it.col(), n) = it.value();\n      n++;\n    }\n  }\n  return X;\n}\n\n\narr eigen_Ainv_b(const arr& A, const arr& b){\n  if(isSparseMatrix(A)){\n    rai::SparseMatrix& As = *dynamic_cast<rai::SparseMatrix*>(A.special);\n    Eigen::SparseMatrix<double> Aeig = conv_sparseArr2sparseEigen(As);\n    Eigen::MatrixXd beig = conv_arr2eigen(b);\n    if(A.d0==A.d1){ //square matrix\n      Eigen::SimplicialLDLT<Eigen::SparseMatrix<double>> solver;\n  //    Eigen::SimplicialLLT<Eigen::SparseMatrix<double>> solver;\n      solver.compute(Aeig);\n      if(solver.info()!=Eigen::Success) {\n        HALT(\"decomposition failed\");\n        return NoArr;\n      }\n      Eigen::MatrixXd x = solver.solve(beig);\n      if(solver.info()!=Eigen::Success) {\n        HALT(\"solving failed\");\n        return NoArr;\n      }\n      return conv_eigen2arr(x);\n    }else{ //non-square matrix\n      Eigen::SparseQR<Eigen::SparseMatrix<double>, Eigen::COLAMDOrdering<int> > solver;\n      solver.compute(Aeig);\n      if(solver.info()!=Eigen::Success) {\n        HALT(\"decomposition failed\");\n        return NoArr;\n      }\n      Eigen::MatrixXd x = solver.solve(beig);\n      if(solver.info()!=Eigen::Success) {\n        HALT(\"solving failed\");\n        return NoArr;\n      }\n      return conv_eigen2arr(x);\n    }\n  }else NIY;\n    return NoArr;\n}\n\n\n//===========================================================================\n//\n// RowShifted\n//\n\nRowShifted::RowShifted(arr& X):Z(X), real_d1(0), symmetric(false) {\n  type = SpecialArray::RowShiftedST;\n  Z.special = this;\n}\n\nRowShifted::RowShifted(arr& X, RowShifted &aux):\n  Z(X),\n  real_d1(aux.real_d1),\n  rowShift(aux.rowShift),\n  rowLen(aux.rowLen),\n  colPatches(aux.colPatches),\n  symmetric(aux.symmetric) {\n  type = SpecialArray::RowShiftedST;\n  Z.special=this;\n}\n\nRowShifted *makeRowShifted(arr& Z, uint d0, uint pack_d1, uint real_d1) {\n  RowShifted *Zaux;\n  if(!Z.special) {\n    Zaux = new RowShifted(Z);\n  } else {\n    CHECK_EQ(Z.special->type, SpecialArray::RowShiftedST, \"\");\n    Zaux = dynamic_cast<RowShifted*>(Z.special);\n  }\n  Z.resize(d0, pack_d1);\n  Z.setZero();\n  Zaux->real_d1=real_d1;\n  Zaux->rowShift.resize(d0);\n  Zaux->rowShift.setZero();\n  Zaux->rowLen.resize(d0);\n  if(d0) Zaux->rowLen = pack_d1;\n  return Zaux;\n}\n\nRowShifted::~RowShifted() {\n  Z.special = NULL;\n}\n\ndouble RowShifted::elem(uint i, uint j) {\n  uint rs=rowShift(i);\n  if(j<rs || j>=rs+Z.d1) return 0.;\n  return Z(i, j-rs);\n}\n\nvoid RowShifted::reshift() {\n  rowLen.resize(Z.d0);\n  for(uint i=0; i<Z.d0; i++) {\n#if 1\n    //find number of leading and trailing zeros\n    double *Zp = Z.p + i*Z.d1;\n    double *Zlead = Zp;\n    double *Ztrail = Zp + Z.d1-1;\n    while(Ztrail>=Zlead && *Ztrail==0.) Ztrail--;\n    while(Zlead<=Ztrail && *Zlead==0.) Zlead++;\n    if(Ztrail<Zlead) { //all zeros\n      rowLen.p[i]=0.;\n    } else {\n      uint rs = Zlead-Zp;\n      uint len = 1+Ztrail-Zlead;\n      rowShift.p[i] += rs;\n      rowLen.p[i] = len;\n      if(Zlead!=Zp) {\n        memmove(Zp, Zlead, len*Z.sizeT);\n        memset(Zp+len, 0, (Z.d1-len)*Z.sizeT);\n      }\n    }\n#else\n    //find number of leading zeros\n    uint j=0;\n    while(j<Z.d1 && Z(i,j)==0.) j++;\n    //shift or so..\n    if(j==Z.d1) { //all zeros...\n    } else if(j) { //some zeros\n      rowShift(i) += j;\n      memmove(&Z(i,0), &Z(i,j), (Z.d1-j)*Z.sizeT);\n      memset(&Z(i,Z.d1-j), 0, j*Z.sizeT);\n    }\n    //find number of trailing zeros\n    j=Z.d1;\n    while(j>0 && Z(i,j-1)==0.) j--;\n    rowLen(i)=j;\n#endif\n  }\n}\n\narr packRowShifted(const arr& X) {\n#if 1\n  arr Z;\n  RowShifted *Zaux = makeRowShifted(Z, X.d0, X.d1, X.d1);\n  memmove(Z.p, X.p, Z.N*Z.sizeT);\n  Zaux->reshift();\n  return Z;\n#else\n  arr Z;\n  RowShifted *Zaux = makeRowShifted(Z, X.d0, 0, X.d1);\n  Z.setZero();\n  //-- compute rowShifts and pack_d1:\n  uint pack_d1=0;\n  for(uint i=0; i<X.d0; i++) {\n    uint j=0,rs;\n    while(j<X.d1 && X(i,j)==0.) j++;\n    Zaux->rowShift(i)=rs=j;\n    j=X.d1;\n    while(j>rs && X(i,j-1)==0.) j--;\n    if(j-rs>pack_d1) pack_d1=j-rs;\n  }\n  \n  Z.resize(X.d0,pack_d1);\n  Z.setZero();\n  for(uint i=0; i<Z.d0; i++) for(uint j=0; j<Z.d1 && Zaux->rowShift(i)+j<X.d1; j++)\n      Z(i,j) = X(i,Zaux->rowShift(i)+j);\n  return Z;\n#endif\n}\n\narr unpackRowShifted(const arr& Y) {\n  CHECK(isRowShifted(Y),\"\");\n  RowShifted *Yaux = (RowShifted*)Y.special;\n  arr X(Y.d0, Yaux->real_d1);\n  CHECK(!Yaux->symmetric || Y.d0==Yaux->real_d1,\"cannot be symmetric!\");\n  X.setZero();\n  for(uint i=0; i<Y.d0; i++) {\n    uint rs=Yaux->rowShift(i);\n    for(uint j=0; j<Y.d1 && rs+j<X.d1; j++) {\n      X(i,j+rs) = Y(i,j);\n      if(Yaux->symmetric) X(j+rs,i) = Y(i,j);\n    }\n  }\n  return X;\n}\n\nvoid RowShifted::computeColPatches(bool assumeMonotonic) {\n  colPatches.resize(real_d1,2);\n  uint a=0,b=Z.d0;\n  if(!assumeMonotonic) {\n    for(uint j=0; j<real_d1; j++) {\n      a=0;\n      while(a<Z.d0 && elem(a,j)==0) a++;\n      b=Z.d0;\n      while(b>a && elem(b-1,j)==0) b--;\n      colPatches.p[2*j]=a;\n      colPatches.p[2*j+1]=b;\n    }\n  } else {\n    for(uint j=0; j<real_d1; j++) {\n      while(a<Z.d0 && j>=rowShift.p[a]+Z.d1) a++;\n      colPatches.p[2*j]=a;\n    }\n    for(uint j=real_d1; j--;) {\n      while(b>0 && j<rowShift.p[b-1]) b--;\n      colPatches.p[2*j+1]=b;\n    }\n  }\n}\n\narr RowShifted::At_A() {\n  //TODO use blas DSYRK instead?\n  CHECK_EQ(rowLen.N, rowShift.N, \"\");\n  arr R;\n  RowShifted *Raux = makeRowShifted(R, real_d1, Z.d1, real_d1);\n  R.setZero();\n  for(uint i=0; i<R.d0; i++) Raux->rowShift(i) = i;\n  Raux->symmetric=true;\n  if(!Z.d1) return R; //Z is identically zero, all rows fully packed -> return zero R\n  for(uint i=0; i<Z.d0; i++) {\n    uint rs=rowShift.p[i];\n    uint rlen=rowLen.p[i];\n    double* Zi = Z.p+i*Z.d1;\n    for(uint j=0; j<rlen/*Z.d1*/; j++) {\n      uint real_j=j+rs;\n      if(real_j>=real_d1) break;\n      double Zij=Zi[j];\n      if(Zij!=0.) {\n        double* Rp=R.p + real_j*R.d1;\n        double* Jp=Zi+j;\n        double* Jpstop=Zi+rlen; //Z.d1;\n        for(; Jp!=Jpstop; Rp++,Jp++) if(*Jp!=0.) *Rp += Zij * *Jp;\n      }\n    }\n  }\n  return R;\n}\n\narr RowShifted::A_At() {\n  //-- determine pack_d1 for the resulting symmetric matrix\n  uint pack_d1=1;\n  for(uint i=0; i<Z.d0; i++) {\n    uint rs_i=rowShift.p[i];\n    for(uint j=Z.d0-1; j>=i+pack_d1; j--) {\n      uint rs_j=rowShift.p[j];\n      uint a,b;\n      if(rs_i<rs_j) { a=rs_j; b=rs_i+Z.d1; } else { a=rs_i; b=rs_j+Z.d1; }\n      if(real_d1<b) b=real_d1;\n      if(a<b) if(pack_d1<j-i+1) pack_d1=j-i+1;\n    }\n  }\n  \n  arr R;\n  RowShifted *Raux = makeRowShifted(R, Z.d0, pack_d1, Z.d0);\n  R.setZero();\n  for(uint i=0; i<R.d0; i++) Raux->rowShift(i) = i;\n  Raux->symmetric=true;\n  if(!Z.d1) return R; //Z is identically zero, all rows fully packed -> return zero R\n  for(uint i=0; i<Z.d0; i++) {\n    uint rs_i=rowShift.p[i];\n    double* Zi=&Z(i,0);\n    for(uint j=i; j<Z.d0 && j<i+pack_d1; j++) {\n      uint rs_j=rowShift.p[j];\n      double* Zj=&Z(j,0);\n      double* Rij=&R(i,j-i);\n      \n      uint a,b;\n      if(rs_i<rs_j) { a=rs_j; b=rs_i+Z.d1; } else { a=rs_i; b=rs_j+Z.d1; }\n      if(real_d1<b) b=real_d1;\n      for(uint k=a; k<b; k++) *Rij += Zi[k-rs_i]*Zj[k-rs_j];\n    }\n  }\n  return R;\n}\n\narr RowShifted::At_x(const arr& x) {\n  CHECK_EQ(rowLen.N, rowShift.N, \"\");\n  CHECK_EQ(x.N,Z.d0,\"\");\n  arr y(real_d1);\n  y.setZero();\n//  cout <<\"SPARSITY = \" <<Z.sparsity() <<endl;\n  if(!Z.d1) return y; //Z is identically zero, all rows fully packed -> return zero y\n  for(uint i=0; i<Z.d0; i++) {\n    double xi = x.p[i];\n    uint rs=rowShift.p[i];\n#if 0\n    for(uint j=0; j<Z.d1; j++) y.p[rs+j] += xi * Z.p[i*Z.d1+j]; // sum += acc(i,j)*x(i);\n#else //PROFILED\n    double *Zp = Z.p + i*Z.d1;\n    double *yp = y.p + rs;\n    double *ypstop = yp + rowLen.p[i]; //+ Z.d1;\n    for(; yp!=ypstop;) { *yp += xi * *Zp;  Zp++;  yp++; }\n#endif\n  }\n  return y;\n}\n\narr RowShifted::A_x(const arr& x) {\n  if(x.nd==2) {\n    arr Y(x.d1, Z.d0);\n    arr X = ~x;\n    for(uint j=0; j<x.d1; j++) Y[j]() = A_x(X[j]);\n    return ~Y;\n  }\n  CHECK_EQ(x.N,real_d1,\"\");\n  arr y = zeros(Z.d0);\n  if(!Z.d1) return y; //Z is identically zero, all rows fully packed -> return zero y\n  for(uint i=0; i<Z.d0; i++) {\n    double sum=0.;\n    uint rs=rowShift.p[i];\n    for(uint j=0; j<Z.d1 && j+rs<x.N; j++) {\n      sum += Z(i,j)*x(j+rs);\n    }\n    y(i) = sum;\n  }\n  return y;\n}\n\narr RowShifted::At() {\n  uint width = 0;\n  if(!colPatches.N) computeColPatches(false);\n  for(uint i=0; i<colPatches.d0; i++) { uint a=colPatches(i,1)-colPatches(i,0); if(a>width) width=a; }\n  \n  arr At;\n  RowShifted* At_ = makeRowShifted(At, real_d1, width, Z.d0);\n  for(uint i=0; i<real_d1; i++) {\n    uint rs = colPatches(i,0);\n    At_->rowShift(i) = rs;\n    uint rlen = colPatches(i,1)-rs;\n    for(uint j=0; j<rlen; j++) At_->Z(i,j) = elem(rs+j,i);\n  }\n  return At;\n}\n\n\n//===========================================================================\n//\n// SparseMatrix\n//\n\nnamespace rai{\n\nSparseVector::SparseVector(arr& _Z) : Z(_Z) {\n  CHECK(!isSpecial(_Z), \"only once yet\");\n  type = sparseVectorST;\n  Z.special = this;\n}\n\nSparseMatrix::SparseMatrix(arr& _Z) : Z(_Z) {\n  CHECK(!isSpecial(_Z), \"only once yet\");\n  type = sparseMatrixST;\n  Z.special = this;\n}\n\nSparseVector::SparseVector(arr& _Z, const SparseVector& s) : SparseVector(_Z){\n  elems = s.elems;\n}\n\nSparseMatrix::SparseMatrix(arr& _Z, const SparseMatrix& s) : SparseMatrix(_Z){\n  elems = s.elems;\n}\n\n/// return fraction of non-zeros in the array\ntemplate<> double Array<double>::sparsity() {\n  uint i, m=0;\n  for(i=0; i<N; i++) if(elem(i)) m++;\n  return ((double)m)/N;\n}\n\nvoid SparseVector::resize(uint d0, uint n){\n  Z.nd=1; Z.d0=d0;\n  Z.resizeMEM(n, false);\n  Z.setZero();\n  elems.resize(n);\n  for(int& e:elems) e=-1;\n}\n\nvoid SparseMatrix::resize(uint d0, uint d1, uint n){\n  Z.nd=2; Z.d0=d0; Z.d1=d1;\n  Z.resizeMEM(n, false);\n  Z.setZero();\n  elems.resize(n,2);\n  for(int& e:elems) e=-1;\n}\n\nvoid SparseMatrix::resizeCopy(uint d0, uint d1, uint n){\n  Z.nd=2; Z.d0=d0; Z.d1=d1;\n  uint Nold = Z.N;\n  Z.resizeMEM(n, true);\n  if(n>Nold) memset(Z.p+Nold, 0, Z.sizeT*(n-Nold));\n  elems.resizeCopy(n,2);\n  for(uint i=Nold;i<n;i++) elems(i,0) = elems(i,1) =-1;\n}\n\nvoid SparseMatrix::reshape(uint d0, uint d1){\n  Z.nd=2; Z.d0=d0; Z.d1=d1;\n}\n\ndouble& SparseVector::entry(uint i, uint k){\n  CHECK_LE(k, Z.N-1, \"\");\n  if(elems.p[k]==-1){ //new element\n    elems.p[k]=i;\n  }else{\n    CHECK_EQ(elems.p[k], (int)i, \"\");\n  }\n  return Z.p[k];\n}\n\ndouble& SparseMatrix::entry(uint i, uint j, uint k){\n  CHECK_LE(k, Z.N-1, \"\");\n  int *elemsk = elems.p+2*k;\n  if(*elemsk==-1){ //new element\n    *elemsk=i;\n    elemsk[1]=j;\n    rows.clear();\n    cols.clear();\n  }else{\n    CHECK_EQ(*elemsk, (int)i, \"\");\n    CHECK_EQ(elemsk[1], (int)j, \"\");\n  }\n  return Z.p[k];\n}\n\ndouble& SparseMatrix::elem(uint i, uint j){\n  if(rows.N){\n    uintA& r = rows(i);\n    uintA& c = cols(j);\n    if(r.N < c.N){\n      for(uint rj=0;rj<r.d0;rj++) if(r(rj,0)==j) return Z.elem(r(rj,1));\n    }else{\n      for(uint ci=0;ci<c.d0;ci++) if(c(ci,0)==i) return Z.elem(c(ci,1));\n    }\n  }else{\n    for(uint k=0;k<elems.d0;k++)\n      if(elems.p[2*k]==(int)i && elems.p[2*k+1]==(int)j) return Z.elem(k);\n  }\n  return addEntry(i,j);\n}\n\ndouble& SparseVector::addEntry(int i){\n  if(i<0) i += Z.d0;\n  CHECK(Z.nd==1 && (uint)i<Z.d0,\n        \"1D range error (\" <<Z.nd <<\"=1, \" <<i <<\"<\" <<Z.d0 <<\")\");\n  uint k=Z.N;\n  CHECK_EQ(elems.N, k, \"\");\n  elems.resizeCopy(k+1);\n  elems(k)=i;\n  Z.resizeMEM(k+1, true);\n  Z.last()=0.;\n  return Z.last();\n}\n\ndouble& SparseMatrix::addEntry(int i, int j){\n  if(i<0) i += Z.d0;\n  if(j<0) j += Z.d1;\n  CHECK(Z.nd==2 && (uint)i<Z.d0 && (uint)j<Z.d1,\n        \"2D range error (\" <<Z.nd <<\"=2, \" <<i <<\"<\" <<Z.d0 <<\", \" <<j <<\"<\" <<Z.d1 <<\")\");\n  uint k=Z.N;\n  CHECK_EQ(elems.d0, k, \"\");\n  elems.resizeCopy(k+1,2);\n  elems(k,0)=i;\n  elems(k,1)=j;\n  rows.clear();\n  cols.clear();\n  Z.resizeMEM(k+1, true);\n  Z.last()=0.;\n  return Z.last();\n}\n\narr SparseMatrix::getSparseRow(uint i){\n  arr v;\n  SparseVector& vS = v.sparseVec();\n  if(rows.N){\n    uintA& r = rows(i);\n    uint n=r.d0;\n    vS.resize(Z.d1, n);\n    for(uint k=0;k<n;k++){\n      vS.entry(r(k,0), k) = Z.elem(r(k,1));\n    }\n  }else{\n    NIY\n  }\n  return v;\n}\n\nvoid SparseVector::setFromDense(const arr& x) {\n  CHECK_EQ(x.nd, 1, \"\");\n  CHECK(&Z!=&x, \"can't initialize from yourself\");\n  //count non-zeros\n  uint n=0;\n  for(const double& a:x) if(a) n++;\n  //resize\n  resize(x.d0, n);\n  //set entries\n  n=0;\n  for(uint i=0; i<x.d0; i++){\n    double a = x.p[i];\n    if(a){\n      entry(i,n) = a;\n      n++;\n    }\n  }\n}\n\nvoid SparseMatrix::setFromDense(const arr& X) {\n  CHECK_EQ(X.nd, 2, \"\");\n  CHECK(&Z!=&X, \"can't initialize from yourself\");\n  //count non-zeros\n  uint n=0;\n  for(const double& a:X) if(a) n++;\n  //resize\n  resize(X.d0, X.d1, n);\n  //set entries\n  n=0;\n  for(uint i=0; i<X.d0; i++) for(uint j=0; j<X.d1; j++){\n    double a = X.p[i*X.d1+j];\n    if(a){\n      entry(i,j,n) = a;\n      n++;\n    }\n  }\n}\n\nvoid SparseMatrix::setupRowsCols(){\n  rows.resize(Z.d0);\n  cols.resize(Z.d1);\n  for(uint k=0;k<elems.d0;k++){\n    uint i = elems(k,0);\n    uint j = elems(k,1);\n    rows(i).append(TUP(j,k));\n    cols(j).append(TUP(i,k));\n  }\n  for(uint i=0;i<Z.d0;i++) rows(i).reshape(rows(i).N/2,2);\n  for(uint j=0;j<Z.d1;j++) cols(j).reshape(cols(j).N/2,2);\n}\n\nvoid SparseMatrix::rowShift(int shift){\n  for(uint i=0;i<elems.d0;i++){\n    int &j = elems(i,1);\n    CHECK_GE(j+shift, 0, \"\");\n    CHECK_LE(j+shift+1, (int)Z.d1, \"\");\n    j += shift;\n  }\n}\n\narr SparseMatrix::At_x(const arr& x){\n  Eigen::SparseMatrix<double> A_eig = conv_sparseArr2sparseEigen(*this);\n  Eigen::MatrixXd x_eig = conv_arr2eigen(x);\n\n  x_eig = A_eig.transpose() * x_eig;\n\n  arr y(x_eig.rows());\n  for(uint i = 0; i<y.d0; i++) y(i) = x_eig(i,0);\n  return y;\n}\n\narr SparseMatrix::At_A(){\n  Eigen::SparseMatrix<double> s = conv_sparseArr2sparseEigen(*this);\n\n  Eigen::SparseMatrix<double> W(Z.d1, Z.d1);\n  W = s.transpose() * s;\n\n  return conv_sparseEigen2sparseArr(W);\n}\n\narr SparseMatrix::A_B(const arr& B) const{\n  Eigen::SparseMatrix<double> A_eig = conv_sparseArr2sparseEigen(*this);\n  Eigen::SparseMatrix<double> B_eig = conv_sparseArr2sparseEigen(B.copy().sparse());\n\n  Eigen::SparseMatrix<double> W = A_eig * B_eig;\n\n  return conv_sparseEigen2sparseArr(W);\n}\n\narr SparseMatrix::B_A(const arr& B) const{\n  Eigen::SparseMatrix<double> A_eig = conv_sparseArr2sparseEigen(*this);\n  Eigen::SparseMatrix<double> B_eig = conv_sparseArr2sparseEigen(B.copy().sparse());\n\n  Eigen::SparseMatrix<double> W = B_eig * A_eig;\n\n  return conv_sparseEigen2sparseArr(W);\n}\n\nvoid SparseMatrix::transpose(){\n  uint d0 = Z.d0;\n  Z.d0 = Z.d1;\n  Z.d1 = d0;\n  for(uint i=0;i<elems.d0;i++){\n    int k = elems(i,0);\n    elems(i,0) = elems(i,1);\n    elems(i,1) = k;\n  }\n  cols.clear();\n  rows.clear();\n}\n\nvoid SparseMatrix::rowWiseMult(const arr& a){\n  CHECK_EQ(a.N, Z.d0, \"\");\n  for(uint k=0;k<Z.N;k++) Z.elem(k) *= a.elem(elems.p[2*k]);\n}\n\nvoid SparseMatrix::subtract(const SparseMatrix& a){\n  CHECK_EQ(a.Z.d0, Z.d0, \"\");\n  CHECK_EQ(a.Z.d1, Z.d1, \"\");\n  uint Nold=Z.N;\n  resizeCopy(Z.d0, Z.d1, Z.N + a.Z.N);\n  for(uint j=0;j<a.Z.N;j++){\n    entry(a.elems(j,0), a.elems(j,1), Nold+j) = -a.Z.elem(j);\n  }\n}\n\narr SparseVector::unsparse(){\n  arr x;\n  x.resize(Z.d0).setZero();\n  for(uint k=0;k<Z.N;k++) x(elems(k)) += Z.elem(k);\n  return x;\n}\n\narr SparseMatrix::unsparse(){\n  arr x;\n  x.resize(Z.d0, Z.d1).setZero();\n  for(uint k=0;k<Z.N;k++) x(elems(k,0), elems(k,1)) += Z.elem(k);\n  return x;\n}\n\n} //namespace rai\n\nvoid operator -= (rai::SparseMatrix& x, const rai::SparseMatrix& y){ x.subtract(y); }\nvoid operator -= (rai::SparseMatrix& x, double y){ arr& X=x.Z; x.unsparse(); X -= y; }\n\nvoid operator += (rai::SparseMatrix& x, const rai::SparseMatrix& y){ NIY; }\nvoid operator += (rai::SparseMatrix& x, double y){ arr& X=x.Z; x.unsparse(); X += y; }\n\nvoid operator *= (rai::SparseMatrix& x, const rai::SparseMatrix& y){ NIY; }\nvoid operator *= (rai::SparseMatrix& x, double y){ x.Z.ref() *= y; }\n\nvoid operator /= (rai::SparseMatrix& x, const rai::SparseMatrix& y){ NIY; }\nvoid operator /= (rai::SparseMatrix& x, double y){ x.Z.ref() /= y; }\n\n//void operator %= (rai::SparseMatrix& x, const rai::SparseMatrix& y){ NIY; }\n\n\n//===========================================================================\n//\n// generic special\n//\n\narr unpack(const arr& X) {\n  if(!isSpecial(X)) HALT(\"this is not special\");\n  if(isRowShifted(X)) return unpackRowShifted(X);\n  if(isSparseMatrix(X)) return dynamic_cast<rai::SparseMatrix*>(X.special)->unsparse();\n  HALT(\"should not be here\");\n  return arr();\n}\n\narr comp_At_A(const arr& A) {\n  if(!isSpecial(A)) { arr X; blas_At_A(X,A); return X; }\n  if(isRowShifted(A)) return ((RowShifted*)A.special)->At_A();\n  if(isSparseMatrix(A)) return ((rai::SparseMatrix*)A.special)->At_A();\n  return NoArr;\n}\n\narr comp_A_At(const arr& A) {\n  if(!isSpecial(A)) { arr X; blas_A_At(X,A); return X; }\n  if(isRowShifted(A)) return ((RowShifted*)A.special)->A_At();\n  return NoArr;\n}\n\n//arr comp_A_H_At(arr& A, const arr& H){\n//  if(!isSpecial(A)) { arr X; blas_A_At(X,A); return X; }\n//  if(isRowShifted(A)) return ((RowShifted*)A.aux)->A_H_At(H);\n//  return NoArr;\n//}\n\narr comp_At_x(const arr& A, const arr& x) {\n  if(!isSpecial(A)) { arr y; innerProduct(y, ~A, x); return y; }\n  if(isRowShifted(A)) return ((RowShifted*)A.special)->At_x(x);\n  if(isSparseMatrix(A)) return ((rai::SparseMatrix*)A.special)->At_x(x);\n  return NoArr;\n}\n\narr comp_At(const arr& A) {\n  if(!isSpecial(A)) { return ~A; }\n  if(isRowShifted(A)) return ((RowShifted*)A.special)->At();\n  return NoArr;\n}\n\narr comp_A_x(const arr& A, const arr& x) {\n  if(!isSpecial(A)) { arr y; innerProduct(y, A, x); return y; }\n  if(isRowShifted(A)) return ((RowShifted*)A.special)->A_x(x);\n  return NoArr;\n}\n\n//===========================================================================\n//\n// conv with Eigen\n//\n\n#ifdef RAI_EIGEN\n\narr conv_eigen2arr(const Eigen::MatrixXd& in) {\n  if(in.cols()==1){\n    arr out(in.rows());\n    for(uint i = 0; i<in.rows(); i++)\n        out(i) = in(i, 0);\n    return out;\n  }\n  arr out(in.rows(), in.cols());\n  for(uint i = 0; i<in.rows(); i++)\n    for(uint j = 0; j<in.cols(); j++)\n      out(i, j) = in(i, j);\n  return out;\n}\n\nEigen::MatrixXd conv_arr2eigen(const arr& in) {\n  if(in.nd == 1) {\n    Eigen::MatrixXd out(in.d0, 1);\n    for(uint i = 0; i<in.d0; i++)\n      out(i, 0) = in(i);\n    return out;\n  } else if(in.nd == 2) {\n    Eigen::MatrixXd out(in.d0, in.d1);\n    for(uint i = 0; i<in.d0; i++)\n      for(uint j = 0; j<in.d1; j++)\n        out(i, j) = in(i, j);\n    return out;\n  }\n  NIY;\n  return Eigen::MatrixXd(1,1);\n}\n\n#endif\n\n//===========================================================================\n//\n// graphs\n//\n\nvoid graphRandomUndirected(uintA& E, uint n, double connectivity) {\n  uint i, j;\n  for(i=0; i<n; i++) for(j=i+1; j<n; j++) {\n      if(rnd.uni()<connectivity) E.append(TUP(i,j));\n    }\n  E.reshape(E.N/2,2);\n}\n\nvoid graphRandomTree(uintA& E, uint N, uint roots) {\n  uint i;\n  CHECK_GE(roots, 1, \"\");\n  for(i=roots; i<N; i++) E.append(TUP(rnd(i), i));\n  E.reshape(E.N/2,2);\n}\n\nvoid graphRandomFixedDegree(uintA& E, uint N, uint d) {\n  // --- from Joris' libDAI!!\n  // Algorithm 1 in \"Generating random regular graphs quickly\"\n  // by A. Steger and N.C. Wormald\n  //\n  // Draws a random graph with size N and uniform degree d\n  // from an almost uniform probability distribution over these graphs\n  // (which becomes uniform in the limit that d is small and N goes\n  // to infinity).\n  \n  CHECK_EQ((N*d)%2,0, \"It's impossible to create a graph with \" <<N<<\" nodes and fixed degree \" <<d);\n  \n  uint j;\n  \n  bool ready = false;\n  uint tries = 0;\n  while(!ready) {\n    tries++;\n    \n    // Start with N*d points {0, 1, ..., N*d-1} (N*d even) in N groups.\n    // Put U = {0, 1, ..., N*d-1}. (U denotes the set of unpaired points.)\n    uintA U;\n    U.setStraightPerm(N*d);\n    \n    // Repeat the following until no suitable pair can be found: Choose\n    // two random points i and j in U, and if they are suitable, pair\n    // i with j and delete i and j from U.\n    E.clear();\n    bool finished = false;\n    while(!finished) {\n      U.permuteRandomly();\n      uint i1, i2;\n      bool suit_pair_found = false;\n      for(i1=0; i1<U.N-1 && !suit_pair_found; i1++) {\n        for(i2=i1+1; i2<U.N && !suit_pair_found; i2++) {\n          if((U(i1)/d) != (U(i2)/d)) {  // they are suitable (refer to different nodes)\n            suit_pair_found = true;\n            E.append(TUP(U(i1)/d, U(i2)/d));\n            U.remove(i2);  // first remove largest\n            U.remove(i1);  // remove smallest\n          }\n          if(!suit_pair_found || !U.N)  finished = true;\n        }\n      }\n    }\n    E.reshape(E.N/2,2);\n    if(!U.N) {\n      // G is a graph with edge from vertex r to vertex s if and only if\n      // there is a pair containing points in the r'th and s'th groups.\n      // If G is d-regular, output, otherwise return to Step 1.\n      uintA degrees(N);\n      degrees.setZero();\n      for(j=0; j<E.d0; j++) {\n        degrees(E(j,0))++;\n        degrees(E(j,1))++;\n      }\n      ready = true;\n      for(uint n=0; n<N; n++) {\n        CHECK_LE(degrees(n), d, \"\");\n        if(degrees(n)!=d) {\n          ready = false;\n          break;\n        }\n      }\n    } else ready=false;\n  }\n  \n  E.reshape(E.N/2,2);\n}\n\n//===========================================================================\n//\n// explicit instantiations\n// (in old versions, array.tpp was not included by array.h -- one could revive this)\n//\n\n//#include \"array.tpp\"\n//#define T double\n//#  include \"array_instantiate.cxx\"\n//#undef T\n\n//#define NOFLOAT\n//#define T float\n//#  include \"array_instantiate.cxx\"\n//#undef T\n\n//#define T uint\n//#  include \"array_instantiate.cxx\"\n//#undef T\n\n//#define T uint16_t\n//#  include \"array_instantiate.cxx\"\n//#undef T\n\n//#define T int\n//#  include \"array_instantiate.cxx\"\n//#undef T\n\n//#define T long\n//#  include \"array_instantiate.cxx\"\n//#undef T\n//#define T byte\n//#  include \"array_instantiate.cxx\"\n//#undef T\n//#undef NOFLOAT\n\ntemplate rai::Array<rai::String>::Array();\ntemplate rai::Array<rai::String>::~Array();\n\ntemplate rai::Array<rai::String*>::Array();\ntemplate rai::Array<rai::String*>::~Array();\n\ntemplate arrL::Array();\ntemplate arrL::Array(uint);\ntemplate arrL::~Array();\n\ntemplate rai::Array<char const*>::Array();\ntemplate rai::Array<char const*>::Array(uint);\ntemplate rai::Array<char const*>::~Array();\n\ntemplate rai::Array<uintA>::Array();\ntemplate rai::Array<uintA>::Array(uint);\ntemplate rai::Array<uintA>::~Array();\n\ntemplate rai::Array<arr>::Array();\ntemplate rai::Array<arr>::Array(uint);\ntemplate rai::Array<arr>::~Array();\n\n#include \"util.tpp\"\n\ntemplate rai::Array<double> rai::getParameter<arr>(char const*);\ntemplate rai::Array<double> rai::getParameter<arr>(char const*, const arr&);\ntemplate rai::Array<float> rai::getParameter<floatA>(char const*);\ntemplate rai::Array<uint> rai::getParameter<uintA>(char const*);\ntemplate bool rai::checkParameter<arr>(char const*);\ntemplate void rai::getParameter(uintA&, const char*, const uintA&);\n\nvoid linkArray() { cout <<\"*** libArray.so dynamically loaded ***\" <<endl; }\n                         \n//namespace rai{\n//template<> template<> Array<rai::String>::Array(std::initializer_list<const char*> list) {\n//  init();\n//  for(const char* t : list) append(rai::String(t));\n//}\n//}\n                         \n\n", "meta": {"hexsha": "288805c4ff08c251aed3ec8501d10a2db61050e3", "size": 74845, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "motionplanner/rai/rai/Core/array.cpp", "max_stars_repo_name": "hageldave/2020-VINCI-VisNLP", "max_stars_repo_head_hexsha": "1f6b1a92b674dc3858a6a0a5aee5b158e9a72650", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "motionplanner/rai/rai/Core/array.cpp", "max_issues_repo_name": "hageldave/2020-VINCI-VisNLP", "max_issues_repo_head_hexsha": "1f6b1a92b674dc3858a6a0a5aee5b158e9a72650", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "motionplanner/rai/rai/Core/array.cpp", "max_forks_repo_name": "hageldave/2020-VINCI-VisNLP", "max_forks_repo_head_hexsha": "1f6b1a92b674dc3858a6a0a5aee5b158e9a72650", "max_forks_repo_licenses": ["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.3256663016, "max_line_length": 190, "alphanum_fraction": 0.5487741332, "num_tokens": 26652, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.4589159586725886}}
{"text": "/* boost random_demo.cpp profane demo\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: random_demo.cpp 28794 2005-05-10 20:40:59Z jmaurer $\n *\n * A short demo program how to use the random number library.\n */\n\n#include <iostream>\n#include <fstream>\n#include <ctime>            // std::time\n\n#include <boost/random/linear_congruential.hpp>\n#include <boost/random/uniform_int.hpp>\n#include <boost/random/uniform_real.hpp>\n#include <boost/random/variate_generator.hpp>\n\n// Sun CC doesn't handle boost::iterator_adaptor yet\n#if !defined(__SUNPRO_CC) || (__SUNPRO_CC > 0x530)\n#include <boost/generator_iterator.hpp>\n#endif\n\n#ifdef BOOST_NO_STDC_NAMESPACE\nnamespace std {\n  using ::time;\n}\n#endif\n\n// This is a typedef for a random number generator.\n// Try boost::mt19937 or boost::ecuyer1988 instead of boost::minstd_rand\ntypedef boost::minstd_rand base_generator_type;\n\n// This is a reproducible simulation experiment.  See main().\nvoid experiment(base_generator_type & generator)\n{\n  // Define a uniform random number distribution of integer values between\n  // 1 and 6 inclusive.\n  typedef boost::uniform_int<> distribution_type;\n  typedef boost::variate_generator<base_generator_type&, distribution_type> gen_type;\n  gen_type die_gen(generator, distribution_type(1, 6));\n\n#if !defined(__SUNPRO_CC) || (__SUNPRO_CC > 0x530)\n  // If you want to use an STL iterator interface, use iterator_adaptors.hpp.\n  // Unfortunately, this doesn't work on SunCC yet.\n  boost::generator_iterator<gen_type> die(&die_gen);\n  for(int i = 0; i < 10; i++)\n    std::cout << *die++ << \" \";\n  std::cout << '\\n';\n#endif\n}\n\nint main()\n{\n  // Define a random number generator and initialize it with a reproducible\n  // seed.\n  // (The seed is unsigned, otherwise the wrong overload may be selected\n  // when using mt19937 as the base_generator_type.)\n  base_generator_type generator(42u);\n\n  std::cout << \"10 samples of a uniform distribution in [0..1):\\n\";\n\n  // Define a uniform random number distribution which produces \"double\"\n  // values between 0 and 1 (0 inclusive, 1 exclusive).\n  boost::uniform_real<> uni_dist(0,1);\n  boost::variate_generator<base_generator_type&, boost::uniform_real<> > uni(generator, uni_dist);\n\n  std::cout.setf(std::ios::fixed);\n  // You can now retrieve random numbers from that distribution by means\n  // of a STL Generator interface, i.e. calling the generator as a zero-\n  // argument function.\n  for(int i = 0; i < 10; i++)\n    std::cout << uni() << '\\n';\n\n  /*\n   * Change seed to something else.\n   *\n   * Caveat: std::time(0) is not a very good truly-random seed.  When\n   * called in rapid succession, it could return the same values, and\n   * thus the same random number sequences could ensue.  If not the same\n   * values are returned, the values differ only slightly in the\n   * lowest bits.  A linear congruential generator with a small factor\n   * wrapped in a uniform_smallint (see experiment) will produce the same\n   * values for the first few iterations.   This is because uniform_smallint\n   * takes only the highest bits of the generator, and the generator itself\n   * needs a few iterations to spread the initial entropy from the lowest bits\n   * to the whole state.\n   */\n  generator.seed(static_cast<unsigned int>(std::time(0)));\n\n  std::cout << \"\\nexperiment: roll a die 10 times:\\n\";\n\n  // You can save a generator's state by copy construction.\n  base_generator_type saved_generator = generator;\n\n  // When calling other functions which take a generator or distribution\n  // as a parameter, make sure to always call by reference (or pointer).\n  // Calling by value invokes the copy constructor, which means that the\n  // sequence of random numbers at the caller is disconnected from the\n  // sequence at the callee.\n  experiment(generator);\n\n  std::cout << \"redo the experiment to verify it:\\n\";\n  experiment(saved_generator);\n\n  // After that, both generators are equivalent\n  assert(generator == saved_generator);\n\n  // as a degenerate case, you can set min = max for uniform_int\n  boost::uniform_int<> degen_dist(4,4);\n  boost::variate_generator<base_generator_type&, boost::uniform_int<> > deg(generator, degen_dist);\n  std::cout << deg() << \" \" << deg() << \" \" << deg() << std::endl;\n  \n#ifndef BOOST_NO_OPERATORS_IN_NAMESPACE\n  {\n    // You can save the generator state for future use.  You can read the\n    // state back in at any later time using operator>>.\n    std::ofstream file(\"rng.saved\", std::ofstream::trunc);\n    file << generator;\n  }\n#endif\n  // Some compilers don't pay attention to std:3.6.1/5 and issue a\n  // warning here if \"return 0;\" is omitted.\n  return 0;\n}\n", "meta": {"hexsha": "f6a0e5674920b4c143f2fac0b8f88901c9545ee8", "size": 4768, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/random/random_demo.cpp", "max_stars_repo_name": "mike-code/boost_1_38_0", "max_stars_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-04-27T15:35:46.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-27T15:35:46.000Z", "max_issues_repo_path": "libs/random/random_demo.cpp", "max_issues_repo_name": "mike-code/boost_1_38_0", "max_issues_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/random/random_demo.cpp", "max_forks_repo_name": "mike-code/boost_1_38_0", "max_forks_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-07T05:20:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-07T05:20:43.000Z", "avg_line_length": 36.9612403101, "max_line_length": 99, "alphanum_fraction": 0.7168624161, "num_tokens": 1205, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737214979746, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.458915949989862}}
{"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__FLATTEN_OCP_HPP_\n#define SMOOTH__FEEDBACK__FLATTEN_OCP_HPP_\n\n/**\n * @file\n * @brief Reformulate an optimal control problem on a Lie group as an optimal control problem in the\n * tangent space around a reference trajectory.\n *\n * @todo More efficient implementation of Hessian in FlatDyn.\n * @todo Accept dxl as a template argument to avoid double differentiation.\n */\n\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n\n#include <smooth/bundle.hpp>\n#include <smooth/diff.hpp>\n\n#include \"ocp.hpp\"\n#include \"smooth/lie_group_sparse.hpp\"\n#include \"utils/sparse.hpp\"\n\nnamespace smooth::feedback {\n\n// \\cond\nnamespace detail {\n\n/// @brief The first Bernoulli numbers\nstatic constexpr std::array<double, 23> kBn{\n  1,               // 0\n  -1. / 2,         // 1\n  1. / 6,          // 2\n  0.,              // 3\n  -1. / 30,        // 4\n  0,               // 5\n  1. / 42,         // 6\n  0,               // 7\n  -1. / 30,        // 8\n  0,               // 9\n  5. / 66,         // 10\n  0,               // 11\n  -691. / 2730,    // 12\n  0,               // 13\n  7. / 6,          // 14\n  0,               // 15\n  -3617. / 510,    // 16\n  0,               // 17\n  43867. / 798,    // 18\n  0,               // 19\n  -174611. / 330,  // 20\n  0,               // 21\n  854513. / 138,   // 22\n};\n\n/**\n * @brief Sparse matrices containing reordered rows of algebra generators.\n */\ntemplate<LieGroup G>\ninline auto generators_sparse_reordered =\n  []() -> std::array<Eigen::SparseMatrix<double, Eigen::RowMajor>, Dof<G>> {\n  std::array<Eigen::SparseMatrix<double, Eigen::RowMajor>, Dof<G>> ret;\n  for (auto k = 0u; k < Dof<G>; ++k) {\n    ret[k].resize(Dof<G>, Dof<G>);\n    for (auto i = 0u; i < Dof<G>; ++i) { ret[k].row(i) = ::smooth::generators_sparse<G>[i].row(k); }\n    ret[k].makeCompressed();\n  }\n  return ret;\n}();\n\n/**\n * @brief Derivative of the adjoint as sparse matrix\n */\ntemplate<LieGroup G>\ninline Eigen::SparseMatrix<double> d_ad = []() -> Eigen::SparseMatrix<double> {\n  Eigen::SparseMatrix<double> ret;\n  ret.resize(Dof<G>, Dof<G> * Dof<G>);\n  for (auto i = 0u; i < Dof<G>; ++i) {\n    for (auto j = 0u; j < Dof<G>; ++j) {\n      ret.col(j * Dof<G> + i) = smooth::generators_sparse<G>[i].row(j).transpose();\n    }\n  }\n  ret.makeCompressed();\n  return ret;\n}();\n\n/**\n * @brief Flattening of dynamics function (t, x, u) -> Tangent, and its derivatives.\n *\n * @note Do not use numeric differentiation of operator() (it differentiates inside)\n * @note Only considers first derivative of xl and ul\n */\ntemplate<LieGroup X, Manifold U, typename F, typename Xl, typename Ul>\nclass FlatDyn\n{\nprivate:\n  using BundleT = smooth::Bundle<Eigen::Vector<double, 1>, X, U>;\n\n  static constexpr auto Nx    = Dof<X>;\n  static constexpr auto Nu    = Dof<U>;\n  static constexpr auto Nouts = Nx;\n  static constexpr auto Nvars = 1 + Nx + Nu;\n\n  static constexpr auto t_B = 0;\n  static constexpr auto x_B = t_B + 1;\n  static constexpr auto u_B = x_B + Nx;\n\n  using E = Tangent<X>;\n  using V = Tangent<U>;\n\n  F f;\n  Xl xl;\n  Ul ul;\n\n  Eigen::SparseMatrix<double> ad_e_ = smooth::ad_sparse_pattern<X>;\n  Eigen::SparseMatrix<double> ad_vi = smooth::ad_sparse_pattern<X>;\n\n  Eigen::SparseMatrix<double> Joplus_ = smooth::d_exp_sparse_pattern<BundleT>;\n  Eigen::SparseMatrix<double> Hoplus_ = smooth::d2_exp_sparse_pattern<BundleT>;\n\n  Eigen::SparseMatrix<double> dexpinv_e_  = smooth::d_exp_sparse_pattern<X>;\n  Eigen::SparseMatrix<double> d2expinv_e_ = smooth::d2_exp_sparse_pattern<X>;\n\n  Eigen::SparseMatrix<double> J_{Nouts, Nvars};\n  Eigen::SparseMatrix<double> H_{Nvars, Nouts * Nvars};\n\n  // Would ideally like to remove these temporaries...\n  Eigen::SparseMatrix<double> ji_{Nouts, Nvars}, ji_tmp_{Nouts, Nvars}, hi_{Nvars, Nouts *Nvars},\n    hi_tmp_{Nvars, Nouts *Nvars};\n\n  /// @brief Calculate jacobian of (t, x(t)+e, u(t)+v) w.r.t. (t, e, v)\n  void update_joplus(const E & e, const V & v, const E & dxl, const V & dul)\n  {\n    dr_exp_sparse<BundleT>(Joplus_, (Tangent<BundleT>() << 1, e, v).finished());\n\n    block_write(Joplus_, x_B, t_B, Ad<X>(smooth::exp<X>(-e)) * dxl);\n    block_write(Joplus_, u_B, t_B, Ad<U>(smooth::exp<U>(-v)) * dul);\n\n    Joplus_.makeCompressed();\n  }\n\n  /// @brief Calculate hessian of (t, x(t)+e, u(t)+v) w.r.t. (t, e, v)\n  void update_hoplus(const E & e, const V & v, const E & dxl, const V & dul)\n  {\n    d2r_exp_sparse<BundleT>(Hoplus_, (Tangent<BundleT>() << 1, e, v).finished());\n\n    // d (Ad_X b) = -ad_(Ad_X b) * Ad_X\n    const TangentMap<X> Adexp_X  = Ad<X>(smooth::exp<X>(-e));\n    const TangentMap<X> dAdexp_X = ad<X>(Adexp_X * dxl) * Adexp_X * dr_exp<X>(-e);\n    const TangentMap<U> Adexp_U  = Ad<U>(smooth::exp<U>(-v));\n    const TangentMap<U> dAdexp_U = ad<U>(Adexp_U * dul) * Adexp_U * dr_exp<U>(-v);\n\n    for (auto nx = 0u; nx < Nx; ++nx) {\n      const auto b0 = Nvars * (x_B + nx);\n      block_write(Hoplus_, t_B, b0 + x_B, dAdexp_X.middleRows(nx, 1));\n    }\n    for (auto nu = 0u; nu < Nu; ++nu) {\n      const auto b0 = Nvars * (u_B + nu);\n      block_write(Hoplus_, t_B, b0 + u_B, dAdexp_U.middleRows(nu, 1));\n    }\n\n    Hoplus_.makeCompressed();\n  }\n\npublic:\n  template<typename A1, typename A2, typename A3>\n  FlatDyn(A1 && a1, A2 && a2, A3 && a3)\n      : f(std::forward<A1>(a1)), xl(std::forward<A2>(a2)), ul(std::forward<A3>(a3))\n  {}\n\n  template<typename T>\n  CastT<T, E> operator()(const T & t, const CastT<T, E> & e, const CastT<T, V> & v) const\n  {\n    using XT = CastT<T, X>;\n\n    // can not double-differentiate, so we hide derivative of xl w.r.t. t\n    const double tdbl           = static_cast<double>(t);\n    const auto [unused, dxlval] = diff::dr(xl, wrt(tdbl));\n\n    return dr_expinv<XT>(e) * (f(t, rplus(xl(t), e), rplus(ul(t), v)) - dxlval.template cast<T>())\n         + ad<XT>(e) * dxlval.template cast<T>();\n  }\n\n  // First derivative\n  std::reference_wrapper<const Eigen::SparseMatrix<double>>\n  jacobian(double t, const E & e, const V & v) requires(\n    diff::detail::diffable_order1<F, std::tuple<double, X, U>>)\n  {\n    const double tdbl          = static_cast<double>(t);\n    const auto [xlval, dxlval] = diff::dr(xl, wrt(tdbl));\n    const auto [ulval, dulval] = diff::dr(ul, wrt(tdbl));\n    const auto x               = rplus(xlval, e);\n    const auto u               = rplus(ulval, v);\n\n    dr_expinv_sparse<X>(dexpinv_e_, e);\n    d2r_expinv_sparse<X>(d2expinv_e_, e);\n    update_joplus(e, v, dxlval, dulval);\n\n    // value and derivative of f\n    const auto fval = f(t, x, u);\n    const auto & Jf = f.jacobian(t, x, u);\n\n    // Want to differentiate  drexpinv * (f o plus - dxl) + ad dxl\n\n    // Start with drexpinv * d (f \\circ (+))\n    J_ = dexpinv_e_ * Jf * Joplus_;\n    // Add d ( drexpinv ) * (f \\circ (+) - dxl)\n    for (auto i = 0u; i < d2expinv_e_.outerSize(); ++i) {\n      for (Eigen::InnerIterator it(d2expinv_e_, i); it; ++it) {\n        J_.coeffRef(it.col() / Nx, 1 + (it.col() % Nx)) +=\n          (fval(it.row()) - dxlval(it.row())) * it.value();\n      }\n    }\n    // Add d ( ad ) * dxl\n    for (auto i = 0u; i < d_ad<X>.outerSize(); ++i) {\n      for (Eigen::InnerIterator it(d_ad<X>, i); it; ++it) {\n        J_.coeffRef(it.col() / Nx, 1 + (it.col() % Nx)) += dxlval(it.row()) * it.value();\n      }\n    }\n\n    J_.makeCompressed();\n    return J_;\n  }\n\n  // Second derivative\n  //    \\sum Bn (-1)^n / n! d2r (ad_a^n f)_aa - \\sum Bn / n! d2r(ad_a^n dxl)_aa\n  std::reference_wrapper<const Eigen::SparseMatrix<double>>\n  hessian(double t, const E & e, const V & v) requires(\n    diff::detail::diffable_order1<F, std::tuple<double, X, U>> &&\n      diff::detail::diffable_order2<F, std::tuple<double, X, U>>)\n  {\n    const double tdbl          = static_cast<double>(t);\n    const auto [xlval, dxlval] = diff::dr(xl, wrt(tdbl));\n    const auto [ulval, dulval] = diff::dr(ul, wrt(tdbl));\n\n    const auto x    = rplus(xlval, e);\n    const auto u    = rplus(ul(t), v);\n    const auto & Jf = f.jacobian(t, x, u);  // nx x (1 + nx + nu)\n    const auto & Hf = f.hessian(t, x, u);   // (1 + nx + nu) x (nx * (1 + nx + nu))\n\n    ad_sparse<X>(ad_e_, e);\n    update_joplus(e, v, dxlval, dulval);\n    update_hoplus(e, v, dxlval, dulval);\n\n    double coef   = 1;                    // hold (-1)^i / i!\n    Tangent<X> vi = f(t, x, u) - dxlval;  // (ad_a)^i * (f - dxl)\n    ji_           = Jf * Joplus_;         // dr (vi)_{t, e, v}\n    set_zero(hi_);\n    d2r_fog(hi_, Jf, Hf, Joplus_, Hoplus_);  // d2r (vi)_{t, e, v}\n\n    set_zero(H_);\n    for (auto iter = 0u; iter < std::tuple_size_v<decltype(kBn)>; ++iter) {\n      if (kBn[iter] != 0) { block_add(H_, 0, 0, hi_, kBn[iter] * coef); }\n\n      // update hi_\n      hi_tmp_.setZero();\n      for (auto i = 0u; i < ad_e_.outerSize(); ++i) {\n        for (Eigen::InnerIterator it(ad_e_, i); it; ++it) {\n          const auto b0 = it.row() * Nvars;\n          block_add(hi_tmp_, 0, b0, hi_.middleCols(it.col() * Nvars, Nvars), it.value());\n        }\n      }\n      for (auto k = 0u; k < Nx; ++k) {\n        const auto b0 = k * Nvars;\n        block_add(hi_tmp_, 1, b0, generators_sparse_reordered<X>[k] * ji_);\n        block_add(hi_tmp_, 0, b0 + 1, ji_.transpose() * generators_sparse_reordered<X>[k], -1);\n      }\n      std::swap(hi_, hi_tmp_);\n\n      // update ji\n      ji_tmp_.setZero();\n      ji_tmp_ = ad_e_ * ji_;\n      ad_sparse<X>(ad_vi, vi);\n      block_add(ji_tmp_, 0, 1, ad_vi, -1);\n      std::swap(ji_, ji_tmp_);\n\n      // update vi\n      vi.applyOnTheLeft(ad_e_);\n\n      coef *= (-1.) / (iter + 1);\n    }\n\n    H_.makeCompressed();\n    return H_;\n  }\n};\n\n/**\n * @brief Flattening of inner function (t, x, u) -> Vector, and its derivatives.\n *\n * @note Only considers first derivative of xl and ul\n */\ntemplate<LieGroup X, Manifold U, std::size_t Nouts, typename F, typename Xl, typename Ul>\nclass FlatInnerFun\n{\nprivate:\n  using BundleT = smooth::Bundle<Eigen::Vector<double, 1>, X, U>;\n\n  F f;\n  Xl xl;\n  Ul ul;\n\n  static constexpr auto Nx    = Dof<X>;\n  static constexpr auto Nu    = Dof<U>;\n  static constexpr auto Nvars = 1 + Nx + Nu;\n\n  using E = Tangent<X>;\n  using V = Tangent<U>;\n\n  static constexpr auto t_B = 0;\n  static constexpr auto x_B = t_B + 1;\n  static constexpr auto u_B = x_B + Nx;\n\n  Eigen::SparseMatrix<double> Joplus_ = smooth::d_exp_sparse_pattern<BundleT>;\n  Eigen::SparseMatrix<double> Hoplus_ = smooth::d2_exp_sparse_pattern<BundleT>;\n\n  Eigen::SparseMatrix<double> J_{Nouts, Nvars};\n  Eigen::SparseMatrix<double> H_{Nvars, Nouts * Nvars};\n\n  /// @brief Calculate jacobian of (t, x(t)+e, u(t)+v) w.r.t. (t, e, v)\n  void update_joplus(const E & e, const V & v, const E & dxl, const V & dul)\n  {\n    dr_exp_sparse<BundleT>(Joplus_, (Tangent<BundleT>() << 1, e, v).finished());\n\n    block_write(Joplus_, x_B, t_B, Ad<X>(smooth::exp<X>(-e)) * dxl);\n    block_write(Joplus_, u_B, t_B, Ad<U>(smooth::exp<U>(-v)) * dul);\n\n    Joplus_.makeCompressed();\n  }\n\n  /// @brief Calculate hessian of (t, x(t)+e, u(t)+v) w.r.t. (t, e, v)\n  void update_hoplus(const E & e, const V & v, const E & dxl, const V & dul)\n  {\n    d2r_exp_sparse<BundleT>(Hoplus_, (Tangent<BundleT>() << 1, e, v).finished());\n\n    // d (Ad_X b) = -ad_(Ad_X b) * Ad_X\n    const TangentMap<X> Adexp_X  = Ad<X>(smooth::exp<X>(-e));\n    const TangentMap<X> dAdexp_X = ad<X>(Adexp_X * dxl) * Adexp_X * dr_exp<X>(-e);\n    const TangentMap<U> Adexp_U  = Ad<U>(smooth::exp<U>(-v));\n    const TangentMap<U> dAdexp_U = ad<U>(Adexp_U * dul) * Adexp_U * dr_exp<U>(-v);\n\n    for (auto nx = 0u; nx < Nx; ++nx) {\n      const auto b0 = Nvars * (x_B + nx);\n      block_write(Hoplus_, t_B, b0 + x_B, dAdexp_X.middleRows(nx, 1));\n    }\n    for (auto nu = 0u; nu < Nu; ++nu) {\n      const auto b0 = Nvars * (u_B + nu);\n      block_write(Hoplus_, t_B, b0 + u_B, dAdexp_U.middleRows(nu, 1));\n    }\n\n    Hoplus_.makeCompressed();\n  }\n\npublic:\n  template<typename A1, typename A2, typename A3>\n  FlatInnerFun(A1 && a1, A2 && a2, A3 && a3)\n      : f(std::forward<A1>(a1)), xl(std::forward<A2>(a2)), ul(std::forward<A3>(a3))\n  {}\n\n  template<typename T>\n  Eigen::Vector<T, Nouts>\n  operator()(const T & t, const CastT<T, E> & e, const CastT<T, V> & v) const\n  {\n    return f.template operator()<T>(t, rplus(xl(t), e), rplus(ul(t), v));\n  }\n\n  std::reference_wrapper<const Eigen::SparseMatrix<double>>\n  jacobian(double t, const E & e, const V & v) requires(\n    diff::detail::diffable_order1<F, std::tuple<double, X, U>>)\n  {\n    const auto & [xlval, dxlval] = diff::dr(xl, wrt(t));\n    const auto & [ulval, dulval] = diff::dr(ul, wrt(t));\n    const auto & Jf              = f.jacobian(t, rplus(xlval, e), rplus(ulval, v));\n\n    update_joplus(e, v, dxlval, dulval);\n\n    J_ = Jf * Joplus_;\n    J_.makeCompressed();\n    return J_;\n  }\n\n  std::reference_wrapper<const Eigen::SparseMatrix<double>>\n  hessian(double t, const E & e, const V & v) requires(\n    diff::detail::diffable_order1<F, std::tuple<double, X, U>> &&\n      diff::detail::diffable_order2<F, std::tuple<double, X, U>>)\n  {\n    const auto & [xlval, dxlval] = diff::dr(xl, wrt(t));\n    const auto & [ulval, dulval] = diff::dr(ul, wrt(t));\n    const auto x                 = rplus(xlval, e);\n    const auto u                 = rplus(ulval, v);\n    const auto & Jf              = f.jacobian(t, x, u);\n    const auto & Hf              = f.hessian(t, x, u);\n\n    update_joplus(e, v, dxlval, dulval);\n    update_hoplus(e, v, dxlval, dulval);\n\n    set_zero(H_);\n    d2r_fog(H_, Jf, Hf, Joplus_, Hoplus_);\n    H_.makeCompressed();\n    return H_;\n  }\n};\n\n/**\n * @brief Flattening of endpoint function (tf, x0, xf, q) -> Vector, and its derivatives.\n *\n * @note Only considers first derivative of xl\n */\ntemplate<LieGroup X, Manifold U, std::size_t Nq, std::size_t Nouts, typename F, typename Xl>\nclass FlatEndptFun\n{\nprivate:\n  using E       = Tangent<X>;\n  using Q       = Eigen::Vector<Scalar<X>, Nq>;\n  using BundleT = smooth::Bundle<Eigen::Vector<double, 1>, X, X, Q>;\n\n  F f;\n  Xl xl;\n\n  static constexpr auto Nx    = Dof<X>;\n  static constexpr auto Nvars = 1 + 2 * Nx + Nq;\n\n  static constexpr auto tf_B = 0;\n  static constexpr auto x0_B = tf_B + 1;\n  static constexpr auto xf_B = x0_B + Nx;\n  static constexpr auto q_B  = xf_B + Nx;\n\n  Eigen::SparseMatrix<double> Joplus_ = d_exp_sparse_pattern<BundleT>;\n  Eigen::SparseMatrix<double> Hoplus_ = d2_exp_sparse_pattern<BundleT>;\n\n  Eigen::SparseMatrix<double> J_{Nouts, Nvars};\n  Eigen::SparseMatrix<double> H_{Nvars, Nouts * Nvars};\n\n  /// @brief Calculate jacobian of (tf, xl(0.)+e0, xl(tf)+ef, q) w.r.t. (tf, e0, ef, q)\n  void update_joplus(const E & e0, const E & ef, const E & dxlf)\n  {\n    dr_exp_sparse<BundleT>(Joplus_, (Tangent<BundleT>() << 1, e0, ef, Q::Ones()).finished());\n\n    block_write(Joplus_, xf_B, tf_B, Ad<X>(smooth::exp<X>(-ef)) * dxlf);\n\n    Joplus_.makeCompressed();\n  }\n\n  /// @brief Calculate hessian of (tf, xl(0.)+e0, xl(tf)+ef, q) w.r.t. (tf, e0, ef, q)\n  void update_hoplus(const E & e0, const E & ef, [[maybe_unused]] const E & dxlf)\n  {\n    d2r_exp_sparse<BundleT>(Hoplus_, (Tangent<BundleT>() << 1, e0, ef, Q::Ones()).finished());\n\n    // dr (Ad_X b)_X = -ad_{Ad_X b} Ad_X\n    const TangentMap<X> Adexp_f  = Ad<X>(smooth::exp<X>(-ef));\n    const TangentMap<X> dAdexp_f = ad<X>(Adexp_f * dxlf) * Adexp_f * dr_exp<X>(-ef);\n\n    for (auto nx = 0u; nx < Nx; ++nx) {\n      const auto b0 = Nvars * (xf_B + nx);\n      block_write(Hoplus_, tf_B, b0 + xf_B, dAdexp_f.middleRows(nx, 1));\n    }\n\n    Hoplus_.makeCompressed();\n  }\n\npublic:\n  template<typename A1, typename A2>\n  FlatEndptFun(A1 && a1, A2 && a2) : f(std::forward<A1>(a1)), xl(std::forward<A2>(a2))\n  {}\n\n  template<typename T>\n  auto operator()(\n    const T & tf, const CastT<T, E> & e0, const CastT<T, E> & ef, const CastT<T, Q> & q) const\n  {\n    return f.template operator()<T>(tf, rplus(xl(T(0.)), e0), rplus(xl(tf), ef), q);\n  }\n\n  std::reference_wrapper<const Eigen::SparseMatrix<double>>\n  jacobian(double tf, const E & e0, const E & ef, const Q & q) requires(\n    diff::detail::diffable_order1<F, std::tuple<double, X, X, Q>>)\n  {\n    const auto & [xlfval, dxlfval] = diff::dr(xl, wrt(tf));\n    const auto & Jf                = f.jacobian(tf, rplus(xl(0.), e0), rplus(xlfval, ef), q);\n\n    update_joplus(e0, ef, dxlfval);\n\n    J_ = Jf * Joplus_;\n    J_.makeCompressed();\n    return J_;\n  }\n\n  std::reference_wrapper<const Eigen::SparseMatrix<double>>\n  hessian(double tf, const E & e0, const E & ef, const Q & q) requires(\n    diff::detail::diffable_order1<F, std::tuple<double, X, X, Q>> &&\n      diff::detail::diffable_order2<F, std::tuple<double, X, X, Q>>)\n  {\n    const auto & [xlfval, dxlfval] = diff::dr(xl, wrt(tf));\n    const auto x0                  = rplus(xl(0.), e0);\n    const auto xf                  = rplus(xlfval, ef);\n    const auto & Jf                = f.jacobian(tf, x0, xf, q);  // Nouts x Nx\n    const auto & Hf                = f.hessian(tf, x0, xf, q);   // Nx x (Nouts * Nx)\n\n    update_joplus(e0, ef, dxlfval);\n    update_hoplus(e0, ef, dxlfval);\n\n    set_zero(H_);\n    d2r_fog(H_, Jf, Hf, Joplus_, Hoplus_);\n    H_.makeCompressed();\n    return H_;\n  }\n};\n\n}  // namespace detail\n// \\endcond\n\n/**\n * @brief Flatten a LieGroup OCP by defining it in the tangent space around a trajectory.\n *\n * @param ocp OCPType defined on a LieGroup\n * @param xl nominal state trajectory\n * @param ul nominal state trajectory\n *\n * @note The flattened problem defines analytical jacobians and hessians if \\p ocp does.\n *\n * @warn The Hessian of the flattened dynamics is not implemented in an efficient manner.\n *\n * @return FlatOCPType in variables (xe, ue) obtained via variables change x = xl \u2295 xe, u = ul \u2295\n * ue,\n */\nauto flatten_ocp(const OCPType auto & ocp, auto && xl, auto && ul)\n{\n  using ocp_t = std::decay_t<decltype(ocp)>;\n  using X     = typename ocp_t::X;\n  using U     = typename ocp_t::U;\n  using Xl    = decltype(xl);\n  using Ul    = decltype(ul);\n\n  static constexpr auto Nq = ocp_t::Nq;\n\n  return OCP<\n    Tangent<X>,\n    Tangent<U>,\n    detail::FlatEndptFun<X, U, Nq, 1, decltype(ocp.theta), Xl>,\n    detail::FlatDyn<X, U, decltype(ocp.f), Xl, Ul>,\n    detail::FlatInnerFun<X, U, Nq, decltype(ocp.g), Xl, Ul>,\n    detail::FlatInnerFun<X, U, ocp_t::Ncr, decltype(ocp.cr), Xl, Ul>,\n    detail::FlatEndptFun<X, U, Nq, ocp_t::Nce, decltype(ocp.ce), Xl>>{\n    .theta = detail::FlatEndptFun<X, U, Nq, 1, decltype(ocp.theta), Xl>{ocp.theta, xl},\n    .f     = detail::FlatDyn<X, U, decltype(ocp.f), Xl, Ul>{ocp.f, xl, ul},\n    .g     = detail::FlatInnerFun<X, U, Nq, decltype(ocp.g), Xl, Ul>{ocp.g, xl, ul},\n    .cr    = detail::FlatInnerFun<X, U, ocp_t::Ncr, decltype(ocp.cr), Xl, Ul>{ocp.cr, xl, ul},\n    .crl   = ocp.crl,\n    .cru   = ocp.cru,\n    .ce    = detail::FlatEndptFun<X, U, Nq, ocp_t::Nce, decltype(ocp.ce), Xl>{ocp.ce, xl},\n    .cel   = ocp.cel,\n    .ceu   = ocp.ceu,\n  };\n}\n\n/**\n * @brief Unflatten a FlatOCPSolution\n *\n * If flat_sol is a solution to flat_ocp = flatten_ocp(ocp, xl_fun, ul_fun),\n * then unflatten_ocpsol(flat_sol, xl_fun, ul_fun) is a solution to ocp.\n */\ntemplate<LieGroup X, Manifold U>\nauto unflatten_ocpsol(const auto & flatsol, auto && xl_fun, auto && ul_fun)\n{\n  using ocpsol_t = std::decay_t<decltype(flatsol)>;\n\n  auto u_unflat = [ul_fun = std::forward<decltype(ul_fun)>(ul_fun),\n                   usol   = flatsol.u](double t) -> U { return rplus(ul_fun(t), usol(t)); };\n\n  auto x_unflat = [xl_fun = std::forward<decltype(xl_fun)>(xl_fun),\n                   xsol   = flatsol.x](double t) -> X { return rplus(xl_fun(t), xsol(t)); };\n\n  return OCPSolution<X, U, ocpsol_t::Nq, ocpsol_t::Ncr, ocpsol_t::Nce>{\n    .t0         = flatsol.t0,\n    .tf         = flatsol.tf,\n    .Q          = flatsol.Q,\n    .u          = std::move(u_unflat),\n    .x          = std::move(x_unflat),\n    .lambda_q   = flatsol.lambda_q,\n    .lambda_ce  = flatsol.lambda_ce,\n    .lambda_dyn = flatsol.lambda_dyn,\n    .lambda_cr  = flatsol.lambda_cr,\n  };\n}\n\n}  // namespace smooth::feedback\n\n#endif  // SMOOTH__FEEDBACK__FLATTEN_OCP_HPP_\n", "meta": {"hexsha": "7009acdcf2df2d9e4dbe5564c7a816466dd9d45b", "size": 21138, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/smooth/feedback/ocp_flatten.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_flatten.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_flatten.hpp", "max_forks_repo_name": "tgurriet/smooth_feedback", "max_forks_repo_head_hexsha": "1f926cb4269741ddc09ba048af5bea5e0390a053", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.5392156863, "max_line_length": 100, "alphanum_fraction": 0.6052133598, "num_tokens": 7072, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.6224593452091672, "lm_q1q2_score": 0.4588509872254431}}
{"text": "// gradientDescent.hpp\n#ifndef COURSERA_GRADIENTDESCENT_HPP\n#define COURSERA_GRADIENTDESCENT_HPP\n\n#include <memory>\n#include <armadillo>\n\nvoid gradientDescent(std::shared_ptr<arma::fvec> &J_history, std::shared_ptr<arma::fvec> &theta,\n                     const std::shared_ptr<arma::fmat> &X, const std::shared_ptr<arma::fvec> &y,\n                     const float alpha, const size_t num_iters);\n\n#endif // COURSERA_GRADIENTDESCENT_HPP\n", "meta": {"hexsha": "b0ae8faee8248b5695206b64de0651dddea54f97", "size": 437, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ex1/gradientDescent.hpp", "max_stars_repo_name": "kolbma/coursera-ml", "max_stars_repo_head_hexsha": "a8473829138804cf6a46cc60e076d9851b55ae25", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-15T21:08:21.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-15T21:08:21.000Z", "max_issues_repo_path": "ex1/gradientDescent.hpp", "max_issues_repo_name": "kolbma/coursera-ml", "max_issues_repo_head_hexsha": "a8473829138804cf6a46cc60e076d9851b55ae25", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ex1/gradientDescent.hpp", "max_forks_repo_name": "kolbma/coursera-ml", "max_forks_repo_head_hexsha": "a8473829138804cf6a46cc60e076d9851b55ae25", "max_forks_repo_licenses": ["Apache-2.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.6153846154, "max_line_length": 96, "alphanum_fraction": 0.7139588101, "num_tokens": 121, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593452091672, "lm_q2_score": 0.7371581510799253, "lm_q1q2_score": 0.4588509800368107}}
{"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_AVERAGE_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_AVERAGE_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n                  {\n\n  /*!\n    @ingroup group-arithmetic\n    This function object computes the arithmetic mean of its parameters.\n\n    @par Header <boost/simd/abs.hpp>\n\n    @par Notes\n\n    Using `average(x, y)` for floating entries is similar to  `(x+y)/2`\n\n    for integer types, it returns a rounded value at a distance guaranteed\n    to be less than or equal to 0.5 of the average floating value, but may differ\n    by unity from the truncation given by `(x+y)/2`.\n\n    @par Note:\n      This function does not overflow.\n\n    @see meanof\n\n    @par Example:\n\n      @snippet average.cpp average\n\n    @par Possible output:\n\n      @snippet average.txt average\n\n\n  **/\n  Value average(Value const& x, Value const& y);\n} }\n#endif\n\n#include <boost/simd/function/scalar/average.hpp>\n#include <boost/simd/function/simd/average.hpp>\n\n#endif\n", "meta": {"hexsha": "4fc42b10aa0f5d04fb68536d9f3b8118580b3536", "size": 1385, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/average.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/average.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/average.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": 25.1818181818, "max_line_length": 100, "alphanum_fraction": 0.597833935, "num_tokens": 292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4588509768998382}}
{"text": "/**\n * \\ file LMSFilter.cpp\n */\n\n#include <array>\n#include <fstream>\n\n#include <ATK/Adaptive/LMSFilter.h>\n\n#include <ATK/Core/InPointerFilter.h>\n#include <ATK/Core/OutPointerFilter.h>\n#include <ATK/Core/Utilities.h>\n\n#include <ATK/Tools/SumFilter.h>\n\n#include <Eigen/Core>\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_NO_MAIN\n#include <boost/test/unit_test.hpp>\n\n#include <boost/math/constants/constants.hpp>\n\nconstexpr gsl::index PROCESSSIZE = 1200;\n\nBOOST_AUTO_TEST_CASE(LMSFilter_size_negative_test)\n{\n  ATK::LMSFilter<double> filter(100);\n  BOOST_CHECK_THROW(filter.set_size(0), ATK::RuntimeError);\n}\n\nBOOST_AUTO_TEST_CASE(LMSFilter_size_set_test)\n{\n  ATK::LMSFilter<double> filter(100);\n  filter.set_size(10);\n  BOOST_CHECK_EQUAL(filter.get_size(), 10);\n}\n\nBOOST_AUTO_TEST_CASE(LMSFilter_mode_set_test)\n{\n  ATK::LMSFilter<double> filter(100);\n  filter.set_mode(ATK::LMSFilter<double>::Mode::NORMALIZED);\n  BOOST_CHECK(filter.get_mode() == ATK::LMSFilter<double>::Mode::NORMALIZED);\n}\n\nBOOST_AUTO_TEST_CASE(LMSFilter_memory_negative_test)\n{\n  ATK::LMSFilter<double> filter(100);\n  BOOST_CHECK_THROW(filter.set_memory(0), ATK::RuntimeError);\n}\n\nBOOST_AUTO_TEST_CASE(LMSFilter_memory_test)\n{\n  ATK::LMSFilter<double> filter(100);\n  filter.set_memory(0.5);\n  BOOST_CHECK_EQUAL(filter.get_memory(), 0.5);\n}\n\nBOOST_AUTO_TEST_CASE( LMSFilter_memory_positive1_test )\n{\n  ATK::LMSFilter<double> filter(100);\n  BOOST_CHECK_THROW(filter.set_memory(1), ATK::RuntimeError);\n}\n\nBOOST_AUTO_TEST_CASE(LMSFilter_mu_negative_test)\n{\n  ATK::LMSFilter<double> filter(100);\n  BOOST_CHECK_THROW(filter.set_mu(0), ATK::RuntimeError);\n}\n\nBOOST_AUTO_TEST_CASE(LMSFilter_mu_test)\n{\n  ATK::LMSFilter<double> filter(100);\n  filter.set_mu(0.5);\n  BOOST_CHECK_EQUAL(filter.get_mu(), 0.5);\n}\n\nBOOST_AUTO_TEST_CASE( LMSFilter_mu_positive1_test )\n{\n  ATK::LMSFilter<double> filter(100);\n  BOOST_CHECK_THROW(filter.set_mu(1), ATK::RuntimeError);\n}\n\nBOOST_AUTO_TEST_CASE(LMSFilter_learning_set_test)\n{\n  ATK::LMSFilter<double> filter(100);\n  BOOST_CHECK_EQUAL(filter.get_learning(), true);\n  filter.set_learning(false);\n  BOOST_CHECK_EQUAL(filter.get_learning(), false);\n}\n\nBOOST_AUTO_TEST_CASE( LMSFilter_memory_99_test )\n{\n  std::array<double, PROCESSSIZE> data;\n  {\n    std::ifstream input(ATK_SOURCE_TREE \"/tests/data/input_lms.dat\", std::ios::binary);\n    input.read(reinterpret_cast<char*>(data.data()), PROCESSSIZE * sizeof(double));\n  }\n  \n  ATK::InPointerFilter<double> generator(data.data(), 1, PROCESSSIZE, false);\n  generator.set_output_sampling_rate(48000);\n\n  ATK::LMSFilter<double> filter(100);\n  filter.set_input_sampling_rate(48000);\n  filter.set_output_sampling_rate(48000);\n  filter.set_memory(.999);\n  filter.set_mu(.01);\n  \n  filter.set_input_port(0, &generator, 0);\n  filter.set_input_port(1, &generator, 0);\n  \n  filter.process(PROCESSSIZE);\n\n  std::array<double, PROCESSSIZE> outdata;\n  {\n    std::ifstream input(ATK_SOURCE_TREE \"/tests/data/output_lms.dat\", std::ios::binary);\n    input.read(reinterpret_cast<char*>(outdata.data()), PROCESSSIZE * sizeof(double));\n  }\n\n  for (unsigned int i = 0; i < PROCESSSIZE; ++i)\n  {\n    BOOST_CHECK_CLOSE(outdata[i], filter.get_output_array(0)[i], 0.0001);\n  }\n}\n", "meta": {"hexsha": "5669398cfc508b151722b087facd289a0726a3a6", "size": 3200, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/Adaptive/LMSFilter.cpp", "max_stars_repo_name": "D-J-Roberts/AudioTK", "max_stars_repo_head_hexsha": "accf009d7238f32702eb1d5ee23c5148fc68e3bd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 249.0, "max_stars_repo_stars_event_min_datetime": "2015-01-05T13:36:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T18:47:46.000Z", "max_issues_repo_path": "tests/Adaptive/LMSFilter.cpp", "max_issues_repo_name": "D-J-Roberts/AudioTK", "max_issues_repo_head_hexsha": "accf009d7238f32702eb1d5ee23c5148fc68e3bd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 22.0, "max_issues_repo_issues_event_min_datetime": "2015-07-28T15:20:24.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-11T14:18:19.000Z", "max_forks_repo_path": "tests/Adaptive/LMSFilter.cpp", "max_forks_repo_name": "D-J-Roberts/AudioTK", "max_forks_repo_head_hexsha": "accf009d7238f32702eb1d5ee23c5148fc68e3bd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 48.0, "max_forks_repo_forks_event_min_datetime": "2015-08-15T12:08:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-07T02:33:07.000Z", "avg_line_length": 25.6, "max_line_length": 88, "alphanum_fraction": 0.7509375, "num_tokens": 853, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4588509768998382}}
{"text": "/*\nCopyright 2014 Rogier van Dalen.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/** \\file\nTest product.hpp.\n*/\n\n#define BOOST_TEST_MODULE test_math_product\n#include \"utility/test/boost_unit_test.hpp\"\n\n#include \"math/product.hpp\"\n\n#include <string>\n#include <vector>\n\n#include <boost/mpl/assert.hpp>\n\n#include \"math/arithmetic_magma.hpp\"\n#include \"math/cost.hpp\"\n#include \"math/sequence.hpp\"\n#include \"math/check/check_magma.hpp\"\n\nBOOST_AUTO_TEST_SUITE (test_suite_product)\n\nBOOST_AUTO_TEST_CASE (test_product_annihilator) {\n    typedef math::product <\n        math::over <math::sequence <char>, math::cost <double>>>\n        without_inverse;\n    typedef math::product <\n        math::over <math::sequence <char>, math::cost <double>>,\n        math::with_inverse <math::callable::times>> with_divide;\n    typedef math::product <\n        math::over <math::sequence <char>, math::cost <double>>,\n        math::with_inverse <math::callable::plus>> with_minus;\n\n    auto sequence_one = math::one <math::sequence <char>>();\n    auto sequence_annihilator =\n        math::annihilator <math::sequence <char>> (math::times);\n    auto cost_one = math::one <math::cost <double>> ();\n    auto cost_annihilator =\n        math::annihilator <math::cost <double>> (math::times);\n\n    // divide.\n    BOOST_MPL_ASSERT_NOT ((math::has <math::callable::divide <math::left> (\n        without_inverse, without_inverse)>));\n    BOOST_MPL_ASSERT_NOT ((math::has <math::callable::invert <\n        math::left, math::callable::times> (without_inverse)>));\n\n    BOOST_MPL_ASSERT ((math::has <math::callable::divide <math::left> (\n        with_divide, with_divide)>));\n    // sequence does not have invert.\n    BOOST_MPL_ASSERT_NOT ((math::has <math::callable::invert <\n        math::left, math::callable::times> (with_divide)>));\n\n    BOOST_MPL_ASSERT_NOT ((math::has <math::callable::divide <math::left> (\n        with_minus, with_minus)>));\n    BOOST_MPL_ASSERT_NOT ((math::has <\n        math::callable::invert <math::left, math::callable::times> (\n            with_minus)>));\n\n    // minus.\n    BOOST_MPL_ASSERT_NOT ((math::has <math::callable::minus <math::left> (\n        without_inverse, without_inverse)>));\n    BOOST_MPL_ASSERT_NOT ((math::has <math::callable::minus <math::left> (\n        with_divide, with_divide)>));\n    // minus is not actually implemented, since sequence does not have it.\n    BOOST_MPL_ASSERT_NOT ((math::has <math::callable::minus <math::left> (\n        with_minus, with_minus)>));\n\n    // All components annihilators.\n    BOOST_CHECK (math::is_annihilator (math::times,\n        without_inverse (sequence_annihilator, cost_annihilator)));\n    BOOST_CHECK (math::is_annihilator (math::times,\n        with_divide (sequence_annihilator, cost_annihilator)));\n    BOOST_CHECK (math::is_annihilator (math::times,\n        with_minus (sequence_annihilator, cost_annihilator)));\n\n    // One component annihilator.\n    BOOST_CHECK (!math::is_annihilator (math::times,\n        without_inverse (sequence_one, cost_annihilator)));\n    BOOST_CHECK (math::is_annihilator (math::times,\n        with_divide (sequence_one, cost_annihilator)));\n    BOOST_CHECK (!math::is_annihilator (math::times,\n        with_minus (sequence_one, cost_annihilator)));\n\n    BOOST_CHECK (!math::is_annihilator (math::times,\n        without_inverse (sequence_annihilator, cost_one)));\n    BOOST_CHECK (math::is_annihilator (math::times,\n        with_divide (sequence_annihilator, cost_one)));\n    BOOST_CHECK (!math::is_annihilator (math::times,\n        with_minus (sequence_annihilator, cost_one)));\n\n    // No components annihilators.\n    BOOST_CHECK (!math::is_annihilator (math::times,\n        without_inverse (sequence_one, cost_one)));\n    BOOST_CHECK (!math::is_annihilator (math::times,\n        with_divide (sequence_one, cost_one)));\n    BOOST_CHECK (!math::is_annihilator (math::times,\n        with_minus (sequence_one, cost_one)));\n\n    // Annihilators compare equal.\n    BOOST_CHECK_EQUAL (\n        without_inverse (sequence_annihilator, cost_annihilator),\n        without_inverse (sequence_annihilator, cost_annihilator));\n    BOOST_CHECK (!math::compare (\n        without_inverse (sequence_annihilator, cost_annihilator),\n        without_inverse (sequence_annihilator, cost_annihilator)));\n\n    BOOST_CHECK_EQUAL (\n        with_minus (sequence_annihilator, cost_annihilator),\n        with_minus (sequence_annihilator, cost_annihilator));\n    BOOST_CHECK (!math::compare (\n        with_minus (sequence_annihilator, cost_annihilator),\n        with_minus (sequence_annihilator, cost_annihilator)));\n\n    BOOST_CHECK_EQUAL (\n        with_divide (sequence_annihilator, cost_annihilator),\n        with_divide (sequence_annihilator, cost_one));\n    BOOST_CHECK (!math::compare (\n        with_divide (sequence_annihilator, cost_annihilator),\n        with_divide (sequence_annihilator, cost_one)));\n\n    BOOST_CHECK_EQUAL (\n        with_divide (sequence_annihilator, cost_annihilator),\n        with_divide (sequence_one, cost_annihilator));\n    BOOST_CHECK (!math::compare (\n        with_divide (sequence_annihilator, cost_annihilator),\n        with_divide (sequence_one, cost_annihilator)));\n\n    BOOST_CHECK_EQUAL (\n        with_divide (sequence_annihilator, cost_one),\n        with_divide (sequence_one, cost_annihilator));\n    BOOST_CHECK (!math::compare (\n        with_divide (sequence_annihilator, cost_one),\n        with_divide (sequence_one, cost_annihilator)));\n\n    // Annihilators and non-annihilators compare unequal.\n    BOOST_CHECK (! math::equal (\n        without_inverse (sequence_annihilator, cost_annihilator),\n        without_inverse (sequence_annihilator, cost_one)));\n    BOOST_CHECK (! math::equal (\n        with_minus (sequence_annihilator, cost_annihilator),\n        with_minus (sequence_annihilator, cost_one)));\n\n    BOOST_CHECK (! math::equal (\n        without_inverse (sequence_annihilator, cost_annihilator),\n        without_inverse (sequence_one, cost_annihilator)));\n    BOOST_CHECK (! math::equal (\n        with_minus (sequence_annihilator, cost_annihilator),\n        with_minus (sequence_one, cost_annihilator)));\n\n    BOOST_CHECK (! math::equal (\n        without_inverse (sequence_annihilator, cost_one),\n        without_inverse (sequence_one, cost_annihilator)));\n    BOOST_CHECK (! math::equal (\n        with_minus (sequence_annihilator, cost_one),\n        with_minus (sequence_one, cost_annihilator)));\n\n\n    BOOST_CHECK (! math::equal (\n        with_divide (sequence_annihilator, cost_one),\n        with_divide (sequence_one, cost_one)));\n\n    // compare.\n    BOOST_CHECK (math::compare (\n        with_divide (sequence_one, cost_one),\n        with_divide (sequence_annihilator, cost_one)));\n    BOOST_CHECK (!math::compare (\n        with_divide (sequence_annihilator, cost_one),\n        with_divide (sequence_one, cost_one)));\n\n    BOOST_CHECK (!math::compare (\n        without_inverse (sequence_annihilator, cost_annihilator),\n        without_inverse (sequence_one, cost_annihilator)));\n    BOOST_CHECK (math::compare (\n        without_inverse (sequence_one, cost_annihilator),\n        without_inverse (sequence_annihilator, cost_annihilator)));\n}\n\nBOOST_AUTO_TEST_CASE (test_product_spot_three) {\n    typedef math::product <\n        math::over <math::sequence <char>, int, math::cost <float>>> product;\n\n    product a_4_4 (\n        math::sequence <char> (std::string (\"a\")), 4, math::cost <float> (4.));\n    product bc_2_2 (\n        math::sequence <char> (std::string (\"bc\")), 2, math::cost <float> (2.));\n\n    BOOST_CHECK ((math::not_equal (a_4_4, bc_2_2)));\n\n    product abc_8_6 = a_4_4 * bc_2_2;\n    BOOST_CHECK_EQUAL (range::at_c <0> (abc_8_6.components()),\n        math::sequence <char> (std::string (\"abc\")));\n    BOOST_CHECK_EQUAL (range::at_c <1> (abc_8_6.components()), 8);\n    BOOST_CHECK_EQUAL (\n        range::at_c <2> (abc_8_6.components()), math::cost <float> (6.));\n\n    product a_12_4 = abc_8_6 + a_4_4;\n    BOOST_CHECK_EQUAL (range::at_c <0> (a_12_4.components()),\n        math::sequence <char> (std::string (\"a\")));\n    BOOST_CHECK_EQUAL (range::at_c <1> (a_12_4.components()), 12);\n    BOOST_CHECK_EQUAL (\n        range::at_c <2> (a_12_4.components()), math::cost <float> (4.));\n}\n\nBOOST_AUTO_TEST_CASE (test_product_spot_floats) {\n    typedef math::product <math::over <float, float>,\n        math::with_inverse <math::callable::times>> product;\n\n    product a (4, 4);\n    product inverse = math::invert <math::callable::times> (a);\n    BOOST_CHECK_EQUAL (inverse, product (.25, .25));\n}\n\nBOOST_AUTO_TEST_CASE (test_product_automaton_determinisation) {\n    /*\n    This is a simple use case: determinisation of a finite-state automaton.\n    This does things like turning (a*b) + (a*c) into a*(b+c).\n    Imagine an automaton with two paths:\n    (a, 1), (b, 3)\n    (a, 2), (c, 4)\n    This can be turned into, e.g.\n    (a, 1), (b, 3)\n    (a, 1), (c, 5)\n    and now the first transition is the same and can be shared.\n    */\n\n    using math::divide;\n    using math::left;\n    typedef math::with_inverse <math::callable::times> inverses;\n\n    typedef math::single_sequence <char> symbol;\n    typedef math::product <math::over <symbol, math::cost <double>>, inverses>\n        product;\n    product a_1 (symbol ('a'), 1.);\n    product a_2 (symbol ('a'), 2.);\n    product b_3 (symbol ('b'), 3.);\n    product c_4 (symbol ('c'), 4.);\n\n    auto merged_untyped = a_1 + a_2;\n    // Explicitly convert to \"product\".\n    product merged (merged_untyped);\n    auto residue1 = divide <left> (a_1, merged);\n    auto residue2 = divide <left> (a_2, merged);\n\n    auto follow1 = residue1 * b_3;\n    auto follow2 = residue2 * c_4;\n\n    BOOST_CHECK_EQUAL (merged, a_1);\n    BOOST_CHECK_EQUAL (follow1, b_3);\n    BOOST_CHECK_EQUAL (follow2, product (symbol ('c'), 5.));\n\n    BOOST_CHECK_EQUAL (merged * follow1, a_1 * b_3);\n    BOOST_CHECK_EQUAL (merged * follow2, a_2 * c_4);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "a25c14df2c63a57746d03829284bd7285bcd8e48", "size": 10397, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/math/test-product-1-spot.cpp", "max_stars_repo_name": "rogiervd/math", "max_stars_repo_head_hexsha": "96174afac1a2933d71cb7ae3962437f860fc10ec", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/math/test-product-1-spot.cpp", "max_issues_repo_name": "rogiervd/math", "max_issues_repo_head_hexsha": "96174afac1a2933d71cb7ae3962437f860fc10ec", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/math/test-product-1-spot.cpp", "max_forks_repo_name": "rogiervd/math", "max_forks_repo_head_hexsha": "96174afac1a2933d71cb7ae3962437f860fc10ec", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.3653136531, "max_line_length": 80, "alphanum_fraction": 0.6822160239, "num_tokens": 2661, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.737158174177441, "lm_q2_score": 0.6224593171945416, "lm_q1q2_score": 0.45885097376286493}}
{"text": "#include <boost/test/unit_test.hpp>\n\n#include <sway/math.h>\n\nusing namespace sway;\n\nBOOST_AUTO_TEST_SUITE(TColorTestSuite)\n\n/*!\n * \\brief\n *    \u0423\u0431\u0435\u0436\u0434\u0430\u0435\u043c\u0441\u044f, \u0447\u0442\u043e \u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u043e\u0440 \u043f\u043e \u0443\u043c\u043e\u043b\u0447\u0430\u043d\u0438\u044e \u043f\u0440\u0438\u0432\u043e\u0434\u0438\u0442 \u0432\u0441\u0435 \u043a\u043e\u043c\u043f\u043e\u043d\u0435\u043d\u0442\u044b \u043a \u043d\u0443\u043b\u044e.\n */\nBOOST_AUTO_TEST_CASE(TColorTestCase_DefaultConstructor) {\n\tconst math::col4f_t color;\n\n\tBOOST_CHECK_EQUAL(color.getR(), 0.0f);\n\tBOOST_CHECK_EQUAL(color.getG(), 0.0f);\n\tBOOST_CHECK_EQUAL(color.getB(), 0.0f);\n\tBOOST_CHECK_EQUAL(color.getA(), 1.0f);\n}\n\n/*!\n * \\brief\n *    \u0423\u0431\u0435\u0436\u0434\u0430\u0435\u043c\u0441\u044f, \u0447\u0442\u043e \u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u043e\u0440 \u0443\u0441\u0442\u0430\u043d\u0430\u0432\u043b\u0438\u0432\u0430\u0435\u0442 \u0432\u0441\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f \u043a\u043e\u043c\u043f\u043e\u043d\u0435\u043d\u0442\u043e\u0432 \u0432 \u0442\u0435, \n *    \u043a\u043e\u0442\u043e\u0440\u044b\u0435 \u0431\u044b\u043b\u0438 \u0437\u0430\u0434\u0430\u043d\u044b.\n */\nBOOST_AUTO_TEST_CASE(TColorTestCase_ComponentConstructor) {\n\tconst f32_t r = 0.1f, g = 0.2f, b = 0.3f, a = 1.0f;\n\tconst math::col4f_t color(r, g, b, a);\n\n\tBOOST_CHECK_EQUAL(color.getR(), r);\n\tBOOST_CHECK_EQUAL(color.getG(), g);\n\tBOOST_CHECK_EQUAL(color.getB(), b);\n\tBOOST_CHECK_EQUAL(color.getA(), a);\n}\n\n/*!\n * \\brief\n *    \u0423\u0431\u0435\u0436\u0434\u0430\u0435\u043c\u0441\u044f, \u0447\u0442\u043e \u043f\u0440\u0435\u043e\u0431\u0440\u0430\u0437\u043e\u0432\u0430\u043d\u0438\u0435 \u0432 TVector4<type> \u043f\u0440\u043e\u0445\u043e\u0434\u0438\u0442 \u043f\u0440\u0430\u0432\u0438\u043b\u044c\u043d\u043e.\n */\nBOOST_AUTO_TEST_CASE(TColorTestCase_ConvertToVector4) {\n\tconst f32_t r = 0.1f, g = 0.2f, b = 0.3f, a = 1.0f;\n\n\tmath::col4f_t color(r, g, b, a);\n\tmath::vec4f_t vec4 = color.toVec4();\n\n\tBOOST_CHECK_EQUAL(vec4.getX(), r);\n\tBOOST_CHECK_EQUAL(vec4.getY(), g);\n\tBOOST_CHECK_EQUAL(vec4.getZ(), b);\n\tBOOST_CHECK_EQUAL(vec4.getW(), a);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "2fdae2796cc5d7b752f0c687c5b91c9f8336bfe9", "size": 1351, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/color.spec.cpp", "max_stars_repo_name": "timcogames/sway.module_math", "max_stars_repo_head_hexsha": "1e9f8045952b8521146cf32cabf5b839354ea767", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/color.spec.cpp", "max_issues_repo_name": "timcogames/sway.module_math", "max_issues_repo_head_hexsha": "1e9f8045952b8521146cf32cabf5b839354ea767", "max_issues_repo_licenses": ["MIT"], "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/color.spec.cpp", "max_forks_repo_name": "timcogames/sway.module_math", "max_forks_repo_head_hexsha": "1e9f8045952b8521146cf32cabf5b839354ea767", "max_forks_repo_licenses": ["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.0185185185, "max_line_length": 79, "alphanum_fraction": 0.7150259067, "num_tokens": 443, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321964553657, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.4588378723345194}}
{"text": "///////////////////////////////////////////////////////////////////////////////\r\n// tail_quantile.hpp\r\n//\r\n//  Copyright 2006 Daniel Egloff, Olivier Gygi. Distributed under the Boost\r\n//  Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef BOOST_ACCUMULATORS_STATISTICS_TAIL_QUANTILE_HPP_DE_01_01_2006\r\n#define BOOST_ACCUMULATORS_STATISTICS_TAIL_QUANTILE_HPP_DE_01_01_2006\r\n\r\n#include <vector>\r\n#include <limits>\r\n#include <functional>\r\n#include <sstream>\r\n#include <stdexcept>\r\n#include <cmath>             // For ceil\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/mpl/if.hpp>\r\n#include <boost/type_traits/is_same.hpp>\r\n#include <boost/accumulators/framework/depends_on.hpp>\r\n#include <boost/accumulators/framework/accumulator_base.hpp>\r\n#include <boost/accumulators/framework/extractor.hpp>\r\n#include <boost/accumulators/numeric/functional.hpp>\r\n#include <boost/accumulators/framework/parameters/sample.hpp>\r\n#include <boost/accumulators/statistics_fwd.hpp>\r\n#include <boost/accumulators/statistics/tail.hpp>\r\n#include <boost/accumulators/statistics/count.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 { namespace accumulators\r\n{\r\n\r\nnamespace impl\r\n{\r\n    ///////////////////////////////////////////////////////////////////////////////\r\n    // tail_quantile_impl\r\n    //  Tail quantile estimation based on order statistics\r\n    /**\r\n        @brief Tail quantile estimation based on order statistics (for both left and right tails)\r\n\r\n        The estimation of a tail quantile \\f$\\hat{q}\\f$ with level \\f$\\alpha\\f$ based on order statistics requires the\r\n        chaching of at least the \\f$\\lceil n\\alpha\\rceil\\f$ smallest or the \\f$\\lceil n(1-\\alpha)\\rceil\\f$ largest samples,\r\n        \\f$n\\f$ being the total number of samples. The largest of the \\f$\\lceil n\\alpha\\rceil\\f$ smallest samples or the\r\n        smallest of the \\f$\\lceil n(1-\\alpha)\\rceil\\f$ largest samples provides an estimate for the quantile:\r\n\r\n        \\f[\r\n            \\hat{q}_{n,\\alpha} = X_{\\lceil \\alpha n \\rceil:n}\r\n        \\f]\r\n\r\n        @param quantile_probability\r\n    */\r\n    template<typename Sample, typename LeftRight>\r\n    struct tail_quantile_impl\r\n      : accumulator_base\r\n    {\r\n        // for boost::result_of\r\n        typedef Sample result_type;\r\n\r\n        tail_quantile_impl(dont_care) {}\r\n\r\n        template<typename Args>\r\n        result_type result(Args const &args) const\r\n        {\r\n            std::size_t cnt = count(args);\r\n\r\n            std::size_t n = static_cast<std::size_t>(\r\n                std::ceil(\r\n                    cnt * ( ( is_same<LeftRight, left>::value ) ? args[quantile_probability] : 1. - args[quantile_probability] )\r\n                )\r\n            );\r\n\r\n            // If n is in a valid range, return result, otherwise return NaN or throw exception\r\n            if ( n < static_cast<std::size_t>(tail(args).size()))\r\n            {\r\n               // Note that the cached samples of the left are sorted in ascending order,\r\n               // whereas the samples of the right tail are sorted in descending order\r\n               return *(boost::begin(tail(args)) + n - 1);\r\n            }\r\n            else\r\n            {\r\n                if (std::numeric_limits<result_type>::has_quiet_NaN)\r\n                {\r\n                    return std::numeric_limits<result_type>::quiet_NaN();\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                    return Sample(0);\r\n                }\r\n            }\r\n        }\r\n    };\r\n} // namespace impl\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// tag::tail_quantile<>\r\n//\r\nnamespace tag\r\n{\r\n    template<typename LeftRight>\r\n    struct tail_quantile\r\n      : depends_on<count, tail<LeftRight> >\r\n    {\r\n        /// INTERNAL ONLY\r\n        ///\r\n        typedef accumulators::impl::tail_quantile_impl<mpl::_1, LeftRight> impl;\r\n    };\r\n}\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// extract::tail_quantile\r\n//\r\nnamespace extract\r\n{\r\n    extractor<tag::quantile> const tail_quantile = {};\r\n}\r\n\r\nusing extract::tail_quantile;\r\n\r\n// for the purposes of feature-based dependency resolution,\r\n// tail_quantile<LeftRight> provide the same feature as quantile\r\ntemplate<typename LeftRight>\r\nstruct feature_of<tag::tail_quantile<LeftRight> >\r\n  : feature_of<tag::quantile>\r\n{\r\n};\r\n\r\n// So that tail_quantile can be automatically substituted with\r\n// weighted_tail_quantile when the weight parameter is non-void.\r\ntemplate<typename LeftRight>\r\nstruct as_weighted_feature<tag::tail_quantile<LeftRight> >\r\n{\r\n    typedef tag::weighted_tail_quantile<LeftRight> type;\r\n};\r\n\r\ntemplate<typename LeftRight>\r\nstruct feature_of<tag::weighted_tail_quantile<LeftRight> >\r\n  : feature_of<tag::tail_quantile<LeftRight> >\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": "a93dcd04496ac2dbec51e6e9df1b039492c41528", "size": 5438, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "windows/include/boost/accumulators/statistics/tail_quantile.hpp", "max_stars_repo_name": "jaredhoberock/gotham", "max_stars_repo_head_hexsha": "e3551cc355646530574d086d7cc2b82e41e8f798", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-12-29T07:21:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-29T10:47:38.000Z", "max_issues_repo_path": "windows/include/boost/accumulators/statistics/tail_quantile.hpp", "max_issues_repo_name": "jaredhoberock/gotham", "max_issues_repo_head_hexsha": "e3551cc355646530574d086d7cc2b82e41e8f798", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "windows/include/boost/accumulators/statistics/tail_quantile.hpp", "max_forks_repo_name": "jaredhoberock/gotham", "max_forks_repo_head_hexsha": "e3551cc355646530574d086d7cc2b82e41e8f798", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.6369426752, "max_line_length": 129, "alphanum_fraction": 0.6040823832, "num_tokens": 1173, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321964553657, "lm_q2_score": 0.6442251133170357, "lm_q1q2_score": 0.4588378674694992}}
{"text": "/*    This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.\n *    See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.\n *    Author(s):       Pawel Dlotko\n *\n *    Copyright (C) 2016 Inria\n *\n *    Modification(s):\n *      - YYYY/MM Author: Description of the modification\n */\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE \"Persistence_intervals_with_distances_test\"\n#include <boost/test/unit_test.hpp>\n#include <gudhi/reader_utils.h>\n#include <gudhi/Persistence_intervals_with_distances.h>\n#include <gudhi/common_persistence_representations.h>\n#include <gudhi/Unitary_tests_utils.h>\n\n#include <iostream>\n\nusing namespace Gudhi;\nusing namespace Gudhi::Persistence_representations;\n\nBOOST_AUTO_TEST_CASE(check_bottleneck_distances_computation) {\n  Persistence_intervals_with_distances p(\"data/file_with_diagram\");\n  Persistence_intervals_with_distances q(\"data/file_with_diagram_1\");\n\n  double dist = p.distance(q);\n\n  GUDHI_TEST_FLOAT_EQUALITY_CHECK(dist, 0.389043, Gudhi::Persistence_representations::epsi);\n}\n\nBOOST_AUTO_TEST_CASE(check_default_parameters_in_distance) {\n  Persistence_intervals_with_distances p(\"data/file_with_diagram\");\n  Persistence_intervals_with_distances q(\"data/file_with_diagram_1\");\n\n  double default_parameter_distance = p.distance(q);\n  double max_parameter_distance = p.distance(q, std::numeric_limits<double>::max());\n  double inf_parameter_distance = p.distance(q, std::numeric_limits<double>::infinity());\n\n  GUDHI_TEST_FLOAT_EQUALITY_CHECK(default_parameter_distance, max_parameter_distance);\n  GUDHI_TEST_FLOAT_EQUALITY_CHECK(inf_parameter_distance, max_parameter_distance);\n  GUDHI_TEST_FLOAT_EQUALITY_CHECK(inf_parameter_distance, max_parameter_distance);\n}\n", "meta": {"hexsha": "48d6e8edc20343ad55a22bb34efe774c4269a6e9", "size": 1780, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Persistence_representations/test/persistence_intervals_with_distances_test.cpp", "max_stars_repo_name": "jmarino/gudhi-devel", "max_stars_repo_head_hexsha": "b1824e4de6fd1d037af3c1341c3065731472ffc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 146.0, "max_stars_repo_stars_event_min_datetime": "2019-03-15T14:10:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T21:14:52.000Z", "max_issues_repo_path": "src/Persistence_representations/test/persistence_intervals_with_distances_test.cpp", "max_issues_repo_name": "jmarino/gudhi-devel", "max_issues_repo_head_hexsha": "b1824e4de6fd1d037af3c1341c3065731472ffc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 398.0, "max_issues_repo_issues_event_min_datetime": "2019-03-07T14:55:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T14:50:40.000Z", "max_forks_repo_path": "src/Persistence_representations/test/persistence_intervals_with_distances_test.cpp", "max_forks_repo_name": "jmarino/gudhi-devel", "max_forks_repo_head_hexsha": "b1824e4de6fd1d037af3c1341c3065731472ffc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 51.0, "max_forks_repo_forks_event_min_datetime": "2019-03-08T15:58:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T10:23:23.000Z", "avg_line_length": 39.5555555556, "max_line_length": 101, "alphanum_fraction": 0.8033707865, "num_tokens": 409, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321964553657, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.45883786260447895}}
{"text": "#include \"headers/rmat.h\"\n#include \"headers/util.h\"\n#include <boost/numeric/ublas/matrix.hpp>\n\nusing boost::numeric::ublas::matrix;\nusing will::util::hash32Prob;\n\nRmatConfig::RmatConfig(double _a, double _b, double _c) : a(_a), b(_b), c(_c) {\n  d = 1. - _a + _b + _c;\n  totalA = _a;\n  totalB = totalA + _b;\n  totalC = totalB + _c;\n  if (d < 0) {\n    std::cout << \"Warning: a + b + c > 1\" << std::endl;\n  }\n}\n\nstd::list<Edge> listRmat(size_t n, size_t nEdges, const RmatConfig &cfg) {\n  cilk::reducer<cilk::op_list_append<Edge>> red;\n  listRmatHelper(red, nEdges, cfg, 0, 0, n, n);\n  const std::list<Edge> &edgeList = red.get_value();\n  // std::vector<Edge> out(edgeList.size());\n  // std::copy(edgeList.begin(), edgeList.end(), out.begin());\n  return std::move(edgeList);\n}\n\nvoid listRmatHelper(cilk::reducer<cilk::op_list_append<Edge>> &red, size_t nEdges,\n                    const RmatConfig &cfg, size_t x0, size_t y0, size_t x1, size_t y1) {\n  if (nEdges == 0) return;\n  size_t xMid = (x0 + x1) / 2;\n  size_t yMid = (y0 + y1) / 2;\n  size_t nCells = (x1 - x0) * (y1 - y0);\n\n  if (nCells == 1) {\n    red->push_back({y0, x0});\n    return;\n  }\n\n  cilk::reducer< cilk::op_add<size_t> > redA(0);\n  cilk::reducer< cilk::op_add<size_t> > redB(0);\n  cilk::reducer< cilk::op_add<size_t> > redC(0);\n  cilk::reducer< cilk::op_add<size_t> > redD(0);\n\n  cilk_for(size_t i = 0; i < nEdges; ++i) {\n    double prob = hash32Prob(i);\n    if (prob <= cfg.totalA)\n      *redA += 1;\n    else if (prob <= cfg.totalB)\n      *redB += 1;\n    else if (prob <= cfg.totalC)\n      *redC += 1;\n    else\n      *redD += 1;\n  }\n  // Required for some reason, can't use .get_value() directly in recursive call\n  size_t numA = redA.get_value();\n  size_t numB = redB.get_value();\n  size_t numC = redC.get_value();\n  size_t numD = redD.get_value();\n\n  if (nCells == 4) {\n    if (numA > 0) red->push_back({ y0, x0 });\n    if (numB > 0) red->push_back({ y0, x1 - 1 });\n    if (numC > 0) red->push_back({ y1 - 1, x0 });\n    if (numD > 0) red->push_back({ y1 - 1, x1 - 1 });\n  } else if (nCells > 4) {\n    cilk_spawn listRmatHelper(red, numA, cfg, x0, y0, xMid, yMid);\n    cilk_spawn listRmatHelper(red, numB, cfg, xMid, y0, x1, yMid);\n    cilk_spawn listRmatHelper(red, numC, cfg, x0, yMid, xMid, y1);\n    listRmatHelper(red, numD, cfg, xMid, yMid, x1, y1);\n    cilk_sync;\n  }\n}\n", "meta": {"hexsha": "dab238c6ab7b5ab12e6dd88132a26814c82b2b4d", "size": 2343, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/rmat.cpp", "max_stars_repo_name": "willshiao/cs260-rmat", "max_stars_repo_head_hexsha": "d7103e0a643976ce1553b9e674468c1d40fbaf72", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-03-16T21:08:00.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-16T21:11:04.000Z", "max_issues_repo_path": "src/rmat.cpp", "max_issues_repo_name": "willshiao/cs260-rmat", "max_issues_repo_head_hexsha": "d7103e0a643976ce1553b9e674468c1d40fbaf72", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/rmat.cpp", "max_forks_repo_name": "willshiao/cs260-rmat", "max_forks_repo_head_hexsha": "d7103e0a643976ce1553b9e674468c1d40fbaf72", "max_forks_repo_licenses": ["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.6621621622, "max_line_length": 88, "alphanum_fraction": 0.6013657704, "num_tokens": 886, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.6442251064863698, "lm_q1q2_score": 0.4588378547343553}}
{"text": "/**\n * Simulate: Diffusion-Limited Aggregation from Form+Code in Art, Design, and Architecture\n * implemented in C++ by Patrick Tierney (patrick.l.tierney@gmail.com || http://ptierney.com)\n *\n * Requires Cinder 0.8.2 available at http://libcinder.org\n *\n * Project files are located at https://github.com/hlp/form-and-code\n *\n * For more information about Form+Code visit http://formandcode.com\n */\n\n#include <vector>\n\n#include <boost/shared_ptr.hpp>\n#include <boost/date_time.hpp>\n\n#include \"cinder/gl/gl.h\"\n#include \"cinder/gl/Texture.h\"\n#include \"cinder/app/AppBasic.h\"\n#include \"cinder/Rand.h\"\n#include \"cinder/CinderMath.h\"\n\nclass Particle;\n\n// soon to be std::shared_ptr\ntypedef boost::shared_ptr<Particle> ParticlePtr;\n\nclass Simulate_DLA : public ci::app::AppBasic {\npublic:\n    void prepareSettings(Settings* settings);\n    void setup();\n    void update();\n    void draw();\n    void shutdown();\n\n    std::vector<bool> field;\n\nprivate:\n    int particleCount;\n    std::vector<ParticlePtr> particles;\n    GLubyte* data;\n    int dataSize;\n};\n\nclass Particle {\npublic:\n    Particle(Simulate_DLA& diffusionApp) : field(diffusionApp.field) {\n        stuck = false;\n        width = diffusionApp.getWindowWidth();\n        height = diffusionApp.getWindowHeight();\n\n        reset();\n    }\n\n    void reset() {\n        // keep choosing random spots until an empty one is found\n        do {\n            x = ci::Rand::randInt(width);\n            y = ci::Rand::randInt(height);\n        } while (field[y * width + x]);\n    }\n\n    void update() {\n        // move around\n        if (!stuck) {\n            // get random int [-1, 1] (hence 2)\n            x += ci::Rand::randInt(-1, 2);\n            y += ci::Rand::randInt(-1, 2);\n      \n            if (x < 0 || y < 0 || x >= width || y >= height) {\n                reset();\n                return; \n            }\n\n            // test if something is next to us\n            if (!alone()) {\n                stuck = true;\n                field[y * width + x] = true;        \n            }\n        }\n    }\n\n    // returns true if no neighboring pixels\n    bool alone() {\n        int cx = x;\n        int cy = y;\n\n        // get positions\n        int lx = cx-1;\n        int rx = cx+1;\n        int ty = cy-1;\n        int by = cy+1;\n\n        if (cx <= 0 || cx >= width || \n            lx <= 0 || lx >= width || \n            rx <= 0 || rx >= width || \n            cy <= 0 || cy >= height || \n            ty <= 0 || ty >= height || \n            by <= 0 || by >= height) return true;\n\n        // pre multiply the ys\n        cy *= width;\n        by *= width;\n        ty *= width;\n    \n        // N, W, E, S\n        if (field[cx + ty] || \n            field[lx + cy] ||\n            field[rx + cy] ||\n            field[cx + by]) return false;\n    \n        // NW, NE, SW, SE\n        if (field[lx + ty] || \n            field[lx + by] ||\n            field[rx + ty] ||\n            field[rx + by]) return false;\n    \n        return true;\n    } \n\n    bool stuck;\n    int x, y;\n\nprivate:\n    int width, height;\n    std::vector<bool>& field;\n};\n\n\nvoid Simulate_DLA::prepareSettings(Settings* settings) {\n    settings->setWindowSize(1024, 700);\n}\n\nvoid Simulate_DLA::setup() {\n    // this number might need to be smaller for some computers\n    particleCount = 20000;\n    particles.resize(particleCount);\n\n    // create an array that stores the position of our particles and set them to false\n    field.resize(getWindowWidth() * getWindowHeight());\n\n    for (std::vector<bool>::iterator it = field.begin(); it != field.end(); ++it) {\n        *it = false;\n    }\n\n    // add seed in the center\n    int fcenterX = getWindowWidth() / 2;\n    int fcenterY = getWindowHeight() / 2;\n    field[fcenterX + fcenterY * getWindowWidth()] = true;\n\n    // make particles\n    for (int i = 0; i < particles.size(); ++i) {\n        particles[i] = ParticlePtr(new Particle(*this));\n    }\n\n    // create pixel buffer\n    dataSize = getWindowWidth() * getWindowHeight() * 3;\n    data = new GLubyte[dataSize];\n\n    // set all pixels to white\n    for (int i = 0; i < dataSize; i++) {\n        data[i] = (GLubyte) 255;\n    }\n}\n\nvoid Simulate_DLA::update() {\n    for(int i = 0; i < particleCount; i++) {\n        particles[i]->update();\n        if (particles[i]->stuck) {\n            data[particles[i]->y * getWindowWidth() * 3 + particles[i]->x * 3] = (GLubyte) 0;\n            data[particles[i]->y * getWindowWidth() * 3 + particles[i]->x * 3 + 1] = (GLubyte) 0;\n            data[particles[i]->y * getWindowWidth() * 3 + particles[i]->x * 3 + 2] = (GLubyte) 0;\n        }\n    }\n}\n\nvoid Simulate_DLA::draw() {\n    glDrawPixels(getWindowWidth(), getWindowHeight(), GL_RGB, GL_UNSIGNED_BYTE, data);  \n}\n\nvoid Simulate_DLA::shutdown() {\n    delete [] data;\n}\n\nCINDER_APP_BASIC(Simulate_DLA, ci::app::RendererGl)\n", "meta": {"hexsha": "db0bdeadf42bd732292b460caceb33c00e33a177", "size": 4793, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "reference/contributions/Cinder/Simulate_DLA/src/Simulate_DLA.cpp", "max_stars_repo_name": "TakafumiOyama/FormCodePractice", "max_stars_repo_head_hexsha": "80421242631114071e7d50fd2231122c04b37b92", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "reference/contributions/Cinder/Simulate_DLA/src/Simulate_DLA.cpp", "max_issues_repo_name": "TakafumiOyama/FormCodePractice", "max_issues_repo_head_hexsha": "80421242631114071e7d50fd2231122c04b37b92", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "reference/contributions/Cinder/Simulate_DLA/src/Simulate_DLA.cpp", "max_forks_repo_name": "TakafumiOyama/FormCodePractice", "max_forks_repo_head_hexsha": "80421242631114071e7d50fd2231122c04b37b92", "max_forks_repo_licenses": ["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.7688172043, "max_line_length": 97, "alphanum_fraction": 0.5443354893, "num_tokens": 1274, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.4588378547343552}}
{"text": "/*\n * GraphBLAS Template Library (GBTL), Version 3.0\n *\n * Copyright 2020 Carnegie Mellon University, Battelle Memorial Institute, and\n * Authors.\n *\n * THIS MATERIAL WAS PREPARED AS AN ACCOUNT OF WORK SPONSORED BY AN AGENCY OF\n * THE UNITED STATES GOVERNMENT.  NEITHER THE UNITED STATES GOVERNMENT NOR THE\n * UNITED STATES DEPARTMENT OF ENERGY, NOR THE UNITED STATES DEPARTMENT OF\n * DEFENSE, NOR CARNEGIE MELLON UNIVERSITY, NOR BATTELLE, NOR ANY OF THEIR\n * EMPLOYEES, NOR ANY JURISDICTION OR ORGANIZATION THAT HAS COOPERATED IN THE\n * DEVELOPMENT OF THESE MATERIALS, MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR\n * ASSUMES ANY LEGAL LIABILITY OR RESPONSIBILITY FOR THE ACCURACY, COMPLETENESS,\n * OR USEFULNESS OR ANY INFORMATION, APPARATUS, PRODUCT, SOFTWARE, OR PROCESS\n * DISCLOSED, OR REPRESENTS THAT ITS USE WOULD NOT INFRINGE PRIVATELY OWNED\n * RIGHTS.\n *\n * Released under a BSD-style license, please see LICENSE file or contact\n * permission@sei.cmu.edu for full terms.\n *\n * [DISTRIBUTION STATEMENT A] This material has been approved for public release\n * and unlimited distribution.  Please see Copyright notice for non-US\n * Government use and distribution.\n *\n * This Software includes and/or makes use of the following Third-Party Software\n * subject to its own license:\n *\n * 1. Boost Unit Test Framework\n * (https://www.boost.org/doc/libs/1_45_0/libs/test/doc/html/utf.html)\n * Copyright 2001 Boost software license, Gennadiy Rozental.\n *\n * DM20-0442\n */\n\n#include <iostream>\n\n#include <graphblas/graphblas.hpp>\n#include <algorithms/triangle_count.hpp>\n\nusing namespace grb;\nusing namespace algorithms;\n\n#define BOOST_TEST_MAIN\n#define BOOST_TEST_MODULE triangle_count_test_suite\n\n#include <boost/test/included/unit_test.hpp>\n\nBOOST_AUTO_TEST_SUITE(BOOST_TEST_MODULE)\n\n//****************************************************************************\n/*\nstatic double const INF = std::numeric_limits<double>::max();\n\nstatic std::vector<double> gr={0,1,1,2,2,2,2,3,3,3,3,4,4,4,5,6,6,6,8,8};\nstatic std::vector<double> gc={3,3,6,4,5,6,8,0,1,4,6,2,3,8,2,1,2,3,2,4};\nstatic std::vector<double> gv(gr.size(), 1);\n\nstatic Matrix<double, DirectedMatrixTag> G_tn(9,9);\n\n\n//static Matrix<double, DirectedMatrixTag> G_tn_answer(\n//    {{2, 2, 3, 1, 2, 4, 2, INF, 3},\n//     {2, 2, 2, 1, 2, 3, 1, INF, 3},\n//     {3, 2, 2, 2, 1, 1, 1, INF, 1},\n//     {1, 1, 2, 2, 1, 3, 1, INF, 2},\n//     {2, 2, 1, 1, 2, 2, 2, INF, 1},\n//     {4, 3, 1, 3, 2, 2, 2, INF, 2},\n//     {2, 1, 1, 1, 2, 2, 2, INF, 2},\n//     {INF, INF, INF, INF, INF, INF, INF, INF, INF},\n//     {3, 3, 1, 2, 1, 2, 2, INF, 2}},\n//    INF);\n\nstatic std::vector<double> tr={0,0,1,1,2,2,2,2,3,3,4,4};\nstatic std::vector<double> tc={1,2,0,2,0,1,3,4,2,4,2,3};\nstatic std::vector<double> tv(tr.size(), 1);\n\n//static Matrix<double, DirectedMatrixTag> test5x5(\n//    {{INF,   1,   1, INF, INF},\n//     {  1, INF,   1, INF, INF},\n//     {  1,   1, INF,   1,   1},\n//     {INF, INF,   1, INF,   1},\n//     {INF, INF,   1,   1, INF}},\n//    INF);\nstatic Matrix<double, DirectedMatrixTag> test5x5(5,5,INF);\n*/\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_triangle_count)\n{\n    //Matrix<double, DirectedMatrixTag> testtriangle(\n    //                       {{0,1,1,1,0},\n    //                        {1,0,1,0,1},\n    //                        {1,1,0,1,1},\n    //                        {1,0,1,0,1},\n    //                        {0,1,1,1,0}});\n\n    std::vector<double> ar={0, 0, 0, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4};\n    std::vector<double> ac={1, 2, 3, 0, 2, 4, 0, 1, 3, 4, 0, 2, 4, 1, 2, 3};\n    std::vector<double> av={1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};\n    Matrix<double, DirectedMatrixTag> testtriangle(5,5);\n    testtriangle.build(ar.begin(), ac.begin(), av.begin(), av.size());\n\n    IndexType result = triangle_count(testtriangle);\n    BOOST_CHECK_EQUAL(result, 4);\n}\n\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_triangle_count_masked)\n{\n    //Matrix<double, DirectedMatrixTag> testtriangle(\n    //                       {{0,1,1,1,0},\n    //                        {1,0,1,0,1},\n    //                        {1,1,0,1,1},\n    //                        {1,0,1,0,1},\n    //                        {0,1,1,1,0}});\n\n    std::vector<double> ar={0, 0, 0, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4};\n    std::vector<double> ac={1, 2, 3, 0, 2, 4, 0, 1, 3, 4, 0, 2, 4, 1, 2, 3};\n    std::vector<double> av={1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};\n    Matrix<double, DirectedMatrixTag> testtriangle(5,5);\n    testtriangle.build(ar.begin(), ac.begin(), av.begin(), av.size());\n\n    Matrix<double, DirectedMatrixTag> L(5,5), U(5,5);\n    grb::split(testtriangle, L, U);\n\n    IndexType result = triangle_count_masked(L);\n    BOOST_CHECK_EQUAL(result, 4);\n}\n\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_triangle_count_masked_noT)\n{\n    //Matrix<double, DirectedMatrixTag> testtriangle(\n    //                       {{0,1,1,1,0},\n    //                        {1,0,1,0,1},\n    //                        {1,1,0,1,1},\n    //                        {1,0,1,0,1},\n    //                        {0,1,1,1,0}});\n\n    std::vector<double> ar={0, 0, 0, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4};\n    std::vector<double> ac={1, 2, 3, 0, 2, 4, 0, 1, 3, 4, 0, 2, 4, 1, 2, 3};\n    std::vector<double> av={1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};\n    Matrix<double, DirectedMatrixTag> testtriangle(5,5);\n    testtriangle.build(ar.begin(), ac.begin(), av.begin(), av.size());\n\n    Matrix<double, DirectedMatrixTag> L(5,5), U(5,5);\n    grb::split(testtriangle, L, U);\n\n    IndexType result = triangle_count_masked_noT(L);\n    BOOST_CHECK_EQUAL(result, 4);\n}\n\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_triangle_counting_newGBTL)\n{\n    //Matrix<double, DirectedMatrixTag> testtriangle(\n    //                       {{0,1,1,1,0},\n    //                        {1,0,1,0,1},\n    //                        {1,1,0,1,1},\n    //                        {1,0,1,0,1},\n    //                        {0,1,1,1,0}});\n\n    std::vector<double> ar={0, 0, 0, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4};\n    std::vector<double> ac={1, 2, 3, 0, 2, 4, 0, 1, 3, 4, 0, 2, 4, 1, 2, 3};\n    std::vector<double> av={1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};\n    Matrix<double, DirectedMatrixTag> testtriangle(5,5), L(5,5), U(5,5);\n    testtriangle.build(ar.begin(), ac.begin(), av.begin(), av.size());\n    grb::split(testtriangle, L, U);\n\n    IndexType result = triangle_count_newGBTL(L, U);\n    BOOST_CHECK_EQUAL(result, 4);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "8145c3441b8fa3d8c213c135bc24b75ca4c89c41", "size": 6732, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/test_triangle_count.cpp", "max_stars_repo_name": "KIwabuchi/gbtl", "max_stars_repo_head_hexsha": "62c6b1e3262f3623359e793edb5ec4fa7bb471f0", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 112.0, "max_stars_repo_stars_event_min_datetime": "2016-04-26T05:54:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T05:56:16.000Z", "max_issues_repo_path": "src/test/test_triangle_count.cpp", "max_issues_repo_name": "KIwabuchi/gbtl", "max_issues_repo_head_hexsha": "62c6b1e3262f3623359e793edb5ec4fa7bb471f0", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 21.0, "max_issues_repo_issues_event_min_datetime": "2016-03-22T19:06:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-07T15:40:18.000Z", "max_forks_repo_path": "src/test/test_triangle_count.cpp", "max_forks_repo_name": "KIwabuchi/gbtl", "max_forks_repo_head_hexsha": "62c6b1e3262f3623359e793edb5ec4fa7bb471f0", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2016-04-26T05:54:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-21T03:33:20.000Z", "avg_line_length": 37.8202247191, "max_line_length": 80, "alphanum_fraction": 0.536244801, "num_tokens": 2401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.4588378507992933}}
{"text": "/* boost random/inversive_congruential.hpp header file\r\n *\r\n * Copyright Jens Maurer 2000-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 most recent version including documentation.\r\n *\r\n * $Id: inversive_congruential.hpp,v 1.9 2004/07/27 03:43:32 dgregor Exp $\r\n *\r\n * Revision history\r\n *  2001-02-18  moved to individual header files\r\n */\r\n\r\n#ifndef BOOST_RANDOM_INVERSIVE_CONGRUENTIAL_HPP\r\n#define BOOST_RANDOM_INVERSIVE_CONGRUENTIAL_HPP\r\n\r\n#include <iostream>\r\n#include <cassert>\r\n#include <boost/config.hpp>\r\n#include <boost/static_assert.hpp>\r\n#include <boost/random/detail/const_mod.hpp>\r\n\r\nnamespace boost {\r\nnamespace random {\r\n\r\n// Eichenauer and Lehn 1986\r\ntemplate<class IntType, IntType a, IntType b, IntType p, IntType val>\r\nclass inversive_congruential\r\n{\r\npublic:\r\n  typedef IntType result_type;\r\n#ifndef BOOST_NO_INCLASS_MEMBER_INITIALIZATION\r\n  static const bool has_fixed_range = true;\r\n  static const result_type min_value = (b == 0 ? 1 : 0);\r\n  static const result_type max_value = p-1;\r\n#else\r\n  BOOST_STATIC_CONSTANT(bool, has_fixed_range = false);\r\n#endif\r\n  BOOST_STATIC_CONSTANT(result_type, multiplier = a);\r\n  BOOST_STATIC_CONSTANT(result_type, increment = b);\r\n  BOOST_STATIC_CONSTANT(result_type, modulus = p);\r\n\r\n  result_type min BOOST_PREVENT_MACRO_SUBSTITUTION () const { return b == 0 ? 1 : 0; }\r\n  result_type max BOOST_PREVENT_MACRO_SUBSTITUTION () const { return p-1; }\r\n\r\n  explicit inversive_congruential(IntType y0 = 1) : value(y0)\r\n  {\r\n    BOOST_STATIC_ASSERT(b >= 0);\r\n    BOOST_STATIC_ASSERT(p > 1);\r\n    BOOST_STATIC_ASSERT(a >= 1);\r\n    if(b == 0) \r\n      assert(y0 > 0); \r\n  }\r\n  template<class It> inversive_congruential(It& first, It last)\r\n  { seed(first, last); }\r\n\r\n  void seed(IntType y0 = 1) { value = y0; if(b == 0) assert(y0 > 0); }\r\n  template<class It> void seed(It& first, It last)\r\n  {\r\n    if(first == last)\r\n      throw std::invalid_argument(\"inversive_congruential::seed\");\r\n    value = *first++;\r\n  }\r\n  IntType operator()()\r\n  {\r\n    typedef const_mod<IntType, p> do_mod;\r\n    value = do_mod::mult_add(a, do_mod::invert(value), b);\r\n    return value;\r\n  }\r\n\r\n  bool validation(result_type x) const { return val == x; }\r\n\r\n#ifndef BOOST_NO_OPERATORS_IN_NAMESPACE\r\n\r\n#ifndef BOOST_NO_MEMBER_TEMPLATE_FRIENDS\r\n  template<class CharT, class Traits>\r\n  friend std::basic_ostream<CharT,Traits>&\r\n  operator<<(std::basic_ostream<CharT,Traits>& os, inversive_congruential x)\r\n  { os << x.value; return os; }\r\n\r\n  template<class CharT, class Traits>\r\n  friend std::basic_istream<CharT,Traits>&\r\n  operator>>(std::basic_istream<CharT,Traits>& is, inversive_congruential& x)\r\n  { is >> x.value; return is; }\r\n#endif\r\n\r\n  friend bool operator==(inversive_congruential x, inversive_congruential y)\r\n  { return x.value == y.value; }\r\n  friend bool operator!=(inversive_congruential x, inversive_congruential y)\r\n  { return !(x == y); }\r\n#else\r\n  // Use a member function; Streamable concept not supported.\r\n  bool operator==(inversive_congruential rhs) const\r\n  { return value == rhs.value; }\r\n  bool operator!=(inversive_congruential rhs) const\r\n  { return !(*this == rhs); }\r\n#endif\r\nprivate:\r\n  IntType value;\r\n};\r\n\r\n#ifndef BOOST_NO_INCLASS_MEMBER_INITIALIZATION\r\n//  A definition is required even for integral static constants\r\ntemplate<class IntType, IntType a, IntType b, IntType p, IntType val>\r\nconst bool inversive_congruential<IntType, a, b, p, val>::has_fixed_range;\r\ntemplate<class IntType, IntType a, IntType b, IntType p, IntType val>\r\nconst typename inversive_congruential<IntType, a, b, p, val>::result_type inversive_congruential<IntType, a, b, p, val>::min_value;\r\ntemplate<class IntType, IntType a, IntType b, IntType p, IntType val>\r\nconst typename inversive_congruential<IntType, a, b, p, val>::result_type inversive_congruential<IntType, a, b, p, val>::max_value;\r\ntemplate<class IntType, IntType a, IntType b, IntType p, IntType val>\r\nconst typename inversive_congruential<IntType, a, b, p, val>::result_type inversive_congruential<IntType, a, b, p, val>::multiplier;\r\ntemplate<class IntType, IntType a, IntType b, IntType p, IntType val>\r\nconst typename inversive_congruential<IntType, a, b, p, val>::result_type inversive_congruential<IntType, a, b, p, val>::increment;\r\ntemplate<class IntType, IntType a, IntType b, IntType p, IntType val>\r\nconst typename inversive_congruential<IntType, a, b, p, val>::result_type inversive_congruential<IntType, a, b, p, val>::modulus;\r\n#endif\r\n\r\n} // namespace random\r\n\r\ntypedef random::inversive_congruential<int32_t, 9102, 2147483647-36884165,\r\n  2147483647, 0> hellekalek1995;\r\n\r\n} // namespace boost\r\n\r\n#endif // BOOST_RANDOM_INVERSIVE_CONGRUENTIAL_HPP\r\n", "meta": {"hexsha": "fdc31627621ac0b7a40886bf5c0e82d9e41c0fbf", "size": 4828, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "CvGameCoreDLL/Boost-1.32.0/include/boost/random/inversive_congruential.hpp", "max_stars_repo_name": "macaurther/DOCUSA", "max_stars_repo_head_hexsha": "40586727c351d1b1130c05c2d4648cca3a8bacf5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 93.0, "max_stars_repo_stars_event_min_datetime": "2015-11-20T04:13:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T00:03:08.000Z", "max_issues_repo_path": "CvGameCoreDLL/Boost-1.32.0/include/boost/random/inversive_congruential.hpp", "max_issues_repo_name": "macaurther/DOCUSA", "max_issues_repo_head_hexsha": "40586727c351d1b1130c05c2d4648cca3a8bacf5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 206.0, "max_issues_repo_issues_event_min_datetime": "2015-11-09T00:27:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-04T19:05:18.000Z", "max_forks_repo_path": "CvGameCoreDLL/Boost-1.32.0/include/boost/random/inversive_congruential.hpp", "max_forks_repo_name": "dguenms/Dawn-of-Civilization", "max_forks_repo_head_hexsha": "1c4f510af97a869637cddb4c0859759158cea5ce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 117.0, "max_forks_repo_forks_event_min_datetime": "2015-11-08T02:43:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-12T06:29:00.000Z", "avg_line_length": 37.71875, "max_line_length": 133, "alphanum_fraction": 0.7234879867, "num_tokens": 1349, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321720225278, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.4588378468642313}}
{"text": "#include <boost/ut.hpp>// single header\n// import boost.ut;        // single module (C++20)\n#include \"tl/random.hpp\"\n#include \"tl/algorithm.hpp\"\n#include <string_view>\nint\n  main()\n{\n  using namespace boost::ut::literals;\n  using namespace boost::ut::operators::terse;\n  using namespace boost::ut;\n  using namespace std::string_view_literals;\n  using namespace std::string_literals;\n  [[maybe_unused]] suite random = [] {\n    const auto check_type = []<tl::concepts::is_integral integralT>() {\n      const auto random_values = tl::random::iota<char, 10U>();\n      expect(tl::algorithm::any_of(random_values, [](const auto &value) -> bool {\n        return value != integralT{};\n      }));\n    };\n    const auto check_types = [&check_type]<tl::concepts::is_integral... integralT2>()\n    {\n      (check_type.template operator()<integralT2>(), ...);\n    };\n    \"create random char array\"_test = [&check_types] {\n      check_types.operator()<std::int8_t,\n                             std::uint8_t,\n                             std::int16_t,\n                             std::uint16_t,\n                             std::int32_t,\n                             std::uint32_t,\n                             std::int64_t,\n                             std::uint64_t>();\n    };\n  };\n}", "meta": {"hexsha": "151f4c2aee59925973914854980f7b94daee4ede", "size": 1270, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/src/random_test.cpp", "max_stars_repo_name": "Sebanisu/ToolsLibrary", "max_stars_repo_head_hexsha": "008773ee21bb160abc24c2f28c4f743813cdc777", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-04T17:11:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-04T17:11:34.000Z", "max_issues_repo_path": "tests/src/random_test.cpp", "max_issues_repo_name": "Sebanisu/ToolsLibrary", "max_issues_repo_head_hexsha": "008773ee21bb160abc24c2f28c4f743813cdc777", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-03-04T17:12:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-25T02:08:29.000Z", "max_forks_repo_path": "tests/src/random_test.cpp", "max_forks_repo_name": "Sebanisu/ToolsLibrary", "max_forks_repo_head_hexsha": "008773ee21bb160abc24c2f28c4f743813cdc777", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.2777777778, "max_line_length": 85, "alphanum_fraction": 0.5488188976, "num_tokens": 291, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.685949467848392, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.45881806318346674}}
{"text": "// Copyright 2019 Hans Dembinski\n//\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n// clang-format off\n\n//[ getting_started_listing_05\n\n//////////////// Begin: put this in header file ////////////////////\n\n#include <algorithm>           // std::max_element\n#include <boost/format.hpp>    // only needed for printing\n#include <boost/histogram.hpp> // make_histogram, integer, indexed\n#include <iostream>            // std::cout, std::endl\n#include <sstream>             // std::ostringstream\n#include <tuple>\n#include <vector>\n\n// use this when axis configuration is fix to get highest performance\nstruct HolderOfStaticHistogram {\n  // put axis types here\n  using axes_t = std::tuple<\n    boost::histogram::axis::regular<>,\n    boost::histogram::axis::integer<>    \n  >;\n  using hist_t = boost::histogram::histogram<axes_t>;\n  hist_t hist_;\n};\n\n// use this when axis configuration should be flexible\nstruct HolderOfDynamicHistogram {\n  // put all axis types here that you are going to use\n  using axis_t = boost::histogram::axis::variant<\n    boost::histogram::axis::regular<>,\n    boost::histogram::axis::variable<>,    \n    boost::histogram::axis::integer<>    \n  >;\n  using axes_t = std::vector<axis_t>;\n  using hist_t = boost::histogram::histogram<axes_t>;\n  hist_t hist_;\n};\n\n//////////////// End: put this in header file ////////////////////\n\nint main() {\n  using namespace boost::histogram;\n\n  HolderOfStaticHistogram hs;\n  hs.hist_ = make_histogram(axis::regular<>(5, 0, 1), axis::integer<>(0, 3));\n  // now assign a different histogram\n  hs.hist_ = make_histogram(axis::regular<>(3, 1, 2), axis::integer<>(4, 6));\n  // hs.hist_ = make_histogram(axis::regular<>(5, 0, 1)); does not work;\n  // the static histogram cannot change the number or order of axis types\n\n  HolderOfDynamicHistogram hd;\n  hd.hist_ = make_histogram(axis::regular<>(5, 0, 1), axis::integer<>(0, 3));\n  // now assign a different histogram\n  hd.hist_ = make_histogram(axis::regular<>(3, -1, 2));\n  // and assign another\n  hd.hist_ = make_histogram(axis::integer<>(0, 5), axis::integer<>(3, 5));\n}\n\n//]\n", "meta": {"hexsha": "52706284b33ab521af35a97eac273f33216c611a", "size": 2189, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/histogram/examples/getting_started_listing_05.cpp", "max_stars_repo_name": "uosorio/heroku_face", "max_stars_repo_head_hexsha": "7d6465e71dba17a15d8edaef520adb2fcd09d91e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 188.0, "max_stars_repo_stars_event_min_datetime": "2019-02-08T14:11:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T08:37:05.000Z", "max_issues_repo_path": "3rdparty/boost_1_73_0/libs/histogram/examples/getting_started_listing_05.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 186.0, "max_issues_repo_issues_event_min_datetime": "2016-05-05T14:01:09.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-20T22:38:43.000Z", "max_forks_repo_path": "3rdparty/boost_1_73_0/libs/histogram/examples/getting_started_listing_05.cpp", "max_forks_repo_name": "qingkouwei/mediaones", "max_forks_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 43.0, "max_forks_repo_forks_event_min_datetime": "2019-02-09T16:16:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-25T20:24:36.000Z", "avg_line_length": 33.1666666667, "max_line_length": 77, "alphanum_fraction": 0.6614892645, "num_tokens": 571, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081925, "lm_q2_score": 0.6688802735722129, "lm_q1q2_score": 0.45881805912259016}}
{"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// Use the Boost `ibeta` implementation to generate an array of weights for the\n// Harrell-Davis quantile estimator.\n//\n// For an array `v` of length `l` and quantile `q`,\n//   v[i] = I_x1(a, b) - I_x0(a, b)\n// where\n//   x0 = i / l\n//   x1 = (i + 1) / l\n//   a = l * q\n//   b = l * (1 - q)\n//   and I_x() is the regularized beta function.\n//\n// Harrell, F., & Davis, C. (1982). A New Distribution-Free Quantile Estimator.\n// Biometrika, 69(3), 635-640. doi:10.2307/2335999\n//\n// By default, gives a tab-seperated-values (tsv) output on stdout, but can also\n// output raw doubles as bytes, so can be piped as input to another program\n// (e.g. into a JS TypedArray).\n\nusing ExtendedDouble = long double;\n// Other options for checking with extended precision, but little difference\n// unless comparison also in extended precision. Note: no float128.hpp in Clang.\n// #include <boost/multiprecision/cpp_bin_float.hpp>\n// using ExtendedDouble = boost::multiprecision::cpp_bin_float_50;\n\nint main(int argc, char** argv) {\n  int arr_length = 0;\n  ExtendedDouble quantile = 0;\n\n  // Output tab separated if true, binary if not.\n  bool output_tsv = true;\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        \"length,l\", po::value<int>(&arr_length)->required(),\n        \"length of the target array\")(\n        \"quantile,q\", po::value<ExtendedDouble>(&quantile)->required(),\n        \"quantile to use\")(\n        \"format,f\", po::value<std::string>()->default_value(\"tsv\"),\n        \"Output format: either 'tsv' or 'bin'. Defaults to 'tsv'.\");\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 << \"Print a Harrell-Davis quantile estimator weight array.\\n\"\n                << desc << \"\\n\";\n      return 1;\n    }\n\n    if (vm.count(\"format\")) {\n      std::string output_format = vm[\"format\"].as<std::string>();\n      if (output_format == \"bin\") {\n        output_tsv = false;\n      } else if (output_format != \"tsv\") {\n        throw po::validation_error(po::validation_error::invalid_option_value,\n                                   \"format\");\n      }\n    }\n\n    // Ensure we have > double precision.\n    int max_digits_10 = std::numeric_limits<ExtendedDouble>::max_digits10;\n    if (max_digits_10 < 21) {\n      throw std::runtime_error(\n          \"Insuffient precision available for calculation\");\n    }\n\n    // Notify about missing arg(s) after --help, checking --format, etc.\n    po::notify(vm);\n  } catch (std::exception& e) {\n    std::cerr << \"Error: \" << e.what() << \"\\n\";\n    return 1;\n  }\n\n  if (output_tsv) {\n    // Column headers for tsv.\n    std::cout << \"index\\tvalue\"\n              << \"\\n\";\n    // Make sure enough digits of the upcoming numbers are printed.\n    std::cout << std::setprecision(\n        std::numeric_limits<ExtendedDouble>::max_digits10);\n  }\n\n  ExtendedDouble a = arr_length * quantile;\n  ExtendedDouble b = arr_length * (1 - quantile);\n  ExtendedDouble total = 0;\n\n  for (int i = 0; i < arr_length; i++) {\n    ExtendedDouble start =\n        boost::math::ibeta(a, b, i / (ExtendedDouble)arr_length);\n    ExtendedDouble end =\n        boost::math::ibeta(a, b, (i + 1) / (ExtendedDouble)arr_length);\n    ExtendedDouble value = end - start;\n    total += value;\n\n    if (output_tsv) {\n      std::cout << i << \"\\t\" << value << \"\\n\";\n    } else {\n      // Only write doubles (not higher precision) to stdout so they can be\n      // imported in JS.\n      // Uncomment for boost::multiprecision.\n      // double d_value = value.convert_to<double>();\n      double d_value = (double)value;\n      std::cout.write(reinterpret_cast<char*>(&d_value), sizeof d_value);\n    }\n  }\n\n  if (output_tsv) {\n    std::cerr << std::setprecision(\n                     std::numeric_limits<ExtendedDouble>::max_digits10)\n              << \"Complete with a total of \" << std::setprecision(20) << total\n              << \"\\n\";\n  }\n}\n", "meta": {"hexsha": "a6291a2f1c2103afe427d34589c27fc591373d80", "size": 4717, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "c++/hd-weight-generator.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++/hd-weight-generator.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++/hd-weight-generator.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": 34.6838235294, "max_line_length": 80, "alphanum_fraction": 0.6326054696, "num_tokens": 1233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081925, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.4588180500672312}}
{"text": "// transform algorithm example\n#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <boost/lambda/lambda.hpp>\n#include <boost/lambda/bind.hpp>\n\nusing namespace std;\nusing namespace boost::lambda;\n\nint op_increase (int i) { return ++i; }\nint op_sum (int i, int j) { return i+j; }\n\nint main () {\n  vector<int> first;\n  vector<int> second;\n  vector<int>::iterator it;\n\n  // set some values:\n  for (int i=1; i<6; i++) first.push_back (i*10); //  first: 10 20 30 40 50\n\n  second.resize(first.size());     // allocate space\n  transform (first.begin(), first.end(), second.begin(), op_increase);\n                                                  // second: 11 21 31 41 51\n\n  transform (first.begin(), first.end(), second.begin(), first.begin(), op_sum);\n                                                  //  first: 21 41 61 81 101\n\n  cout << \"first contains:\";\n  for (it=first.begin(); it!=first.end(); ++it)\n    cout << \" \" << *it;\n\n  cout << endl;\n\n  vector<int> third;\n  third.resize(first.size());\n  transform(first.begin(), first.end(), third.begin(), _1 * _1);\n  cout << \"third: \";\n  for_each(third.begin(), third.end(), cout << _1 << ' ');\n  cout << endl;\n  return 0;\n}\n\n", "meta": {"hexsha": "e04a3bfb552cc689d54882e546e3d5d33ac9e2f8", "size": 1186, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "langs/c++/transform/transform.cpp", "max_stars_repo_name": "danielgrigg/sandbox", "max_stars_repo_head_hexsha": "95128ef44ddc2df2a819b14b9930f95d9c9fd423", "max_stars_repo_licenses": ["WTFPL"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-02-23T03:57:39.000Z", "max_stars_repo_stars_event_max_datetime": "2017-02-23T03:57:39.000Z", "max_issues_repo_path": "langs/c++/transform/transform.cpp", "max_issues_repo_name": "danielgrigg/sandbox", "max_issues_repo_head_hexsha": "95128ef44ddc2df2a819b14b9930f95d9c9fd423", "max_issues_repo_licenses": ["WTFPL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "langs/c++/transform/transform.cpp", "max_forks_repo_name": "danielgrigg/sandbox", "max_forks_repo_head_hexsha": "95128ef44ddc2df2a819b14b9930f95d9c9fd423", "max_forks_repo_licenses": ["WTFPL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9545454545, "max_line_length": 80, "alphanum_fraction": 0.5750421585, "num_tokens": 315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494678483918, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.4588180496004278}}
{"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 testNoiseModel.cpp\n * @date Jan 13, 2010\n * @author Richard Roberts\n * @author Frank Dellaert\n */\n\n\n#include <gtsam/linear/NoiseModel.h>\n#include <gtsam/base/TestableAssertions.h>\n\n#include <CppUnitLite/TestHarness.h>\n\n#include <boost/assign/std/vector.hpp>\n\n#include <iostream>\n#include <limits>\n\nusing namespace std;\nusing namespace gtsam;\nusing namespace noiseModel;\nusing namespace boost::assign;\n\nstatic const double kSigma = 2, kInverseSigma = 1.0 / kSigma,\n                    kVariance = kSigma * kSigma, prc = 1.0 / kVariance;\nstatic const Matrix R = Matrix3::Identity() * kInverseSigma;\nstatic const Matrix kCovariance = Matrix3::Identity() * kVariance;\nstatic const Vector3 kSigmas(kSigma, kSigma, kSigma);\n\n/* ************************************************************************* */\nTEST(NoiseModel, constructors)\n{\n  Vector whitened = Vector3(5.0,10.0,15.0);\n  Vector unwhitened = Vector3(10.0,20.0,30.0);\n\n  // Construct noise models\n  vector<Gaussian::shared_ptr> m;\n  m.push_back(Gaussian::SqrtInformation(R,false));\n  m.push_back(Gaussian::Covariance(kCovariance,false));\n  m.push_back(Gaussian::Information(kCovariance.inverse(),false));\n  m.push_back(Diagonal::Sigmas(kSigmas,false));\n  m.push_back(Diagonal::Variances((Vector3(kVariance, kVariance, kVariance)),false));\n  m.push_back(Diagonal::Precisions(Vector3(prc, prc, prc),false));\n  m.push_back(Isotropic::Sigma(3, kSigma,false));\n  m.push_back(Isotropic::Variance(3, kVariance,false));\n  m.push_back(Isotropic::Precision(3, prc,false));\n\n  // test kSigmas\n  for(Gaussian::shared_ptr mi: m)\n    EXPECT(assert_equal(kSigmas,mi->sigmas()));\n\n  // test whiten\n  for(Gaussian::shared_ptr mi: m)\n    EXPECT(assert_equal(whitened,mi->whiten(unwhitened)));\n\n  // test unwhiten\n  for(Gaussian::shared_ptr mi: m)\n    EXPECT(assert_equal(unwhitened,mi->unwhiten(whitened)));\n\n  // test Mahalanobis distance\n  double distance = 5*5+10*10+15*15;\n  for(Gaussian::shared_ptr mi: m)\n    DOUBLES_EQUAL(distance,mi->Mahalanobis(unwhitened),1e-9);\n\n  // test R matrix\n  for(Gaussian::shared_ptr mi: m)\n    EXPECT(assert_equal(R,mi->R()));\n\n  // test covariance\n  for(Gaussian::shared_ptr mi: m)\n    EXPECT(assert_equal(kCovariance,mi->covariance()));\n\n  // test covariance\n  for(Gaussian::shared_ptr mi: m)\n    EXPECT(assert_equal(kCovariance.inverse(),mi->information()));\n\n  // test Whiten operator\n  Matrix H((Matrix(3, 4) <<\n      0.0, 0.0, 1.0, 1.0,\n      0.0, 1.0, 0.0, 1.0,\n      1.0, 0.0, 0.0, 1.0).finished());\n  Matrix expected = kInverseSigma * H;\n  for(Gaussian::shared_ptr mi: m)\n    EXPECT(assert_equal(expected,mi->Whiten(H)));\n\n  // can only test inplace version once :-)\n  m[0]->WhitenInPlace(H);\n  EXPECT(assert_equal(expected,H));\n}\n\n/* ************************************************************************* */\nTEST(NoiseModel, Unit)\n{\n  Vector v = Vector3(5.0,10.0,15.0);\n  Gaussian::shared_ptr u(Unit::Create(3));\n  EXPECT(assert_equal(v,u->whiten(v)));\n}\n\n/* ************************************************************************* */\nTEST(NoiseModel, equals)\n{\n  Gaussian::shared_ptr g1 = Gaussian::SqrtInformation(R),\n                       g2 = Gaussian::SqrtInformation(I_3x3);\n  Diagonal::shared_ptr d1 = Diagonal::Sigmas(Vector3(kSigma, kSigma, kSigma)),\n                       d2 = Diagonal::Sigmas(Vector3(0.1, 0.2, 0.3));\n  Isotropic::shared_ptr i1 = Isotropic::Sigma(3, kSigma),\n                        i2 = Isotropic::Sigma(3, 0.7);\n\n  EXPECT(assert_equal(*g1,*g1));\n  EXPECT(assert_inequal(*g1, *g2));\n\n  EXPECT(assert_equal(*d1,*d1));\n  EXPECT(assert_inequal(*d1,*d2));\n\n  EXPECT(assert_equal(*i1,*i1));\n  EXPECT(assert_inequal(*i1,*i2));\n}\n\n// TODO enable test once a mechanism for smart constraints exists\n///* ************************************************************************* */\n//TEST(NoiseModel, ConstrainedSmart )\n//{\n//  Gaussian::shared_ptr nonconstrained = Constrained::MixedSigmas((Vector3(sigma, 0.0, sigma), true);\n//  Diagonal::shared_ptr n1 = boost::dynamic_pointer_cast<Diagonal>(nonconstrained);\n//  Constrained::shared_ptr n2 = boost::dynamic_pointer_cast<Constrained>(nonconstrained);\n//  EXPECT(n1);\n//  EXPECT(!n2);\n//\n//  Gaussian::shared_ptr constrained = Constrained::MixedSigmas(zero(3), true);\n//  Diagonal::shared_ptr c1 = boost::dynamic_pointer_cast<Diagonal>(constrained);\n//  Constrained::shared_ptr c2 = boost::dynamic_pointer_cast<Constrained>(constrained);\n//  EXPECT(c1);\n//  EXPECT(c2);\n//}\n\n/* ************************************************************************* */\nTEST(NoiseModel, ConstrainedConstructors )\n{\n  Constrained::shared_ptr actual;\n  size_t d = 3;\n  double m = 100.0;\n  Vector3 sigmas(kSigma, 0.0, 0.0);\n  Vector3 mu(200.0, 300.0, 400.0);\n  actual = Constrained::All(d);\n  // TODO: why should this be a thousand ??? Dummy variable?\n  EXPECT(assert_equal(Vector::Constant(d, 1000.0), actual->mu()));\n  EXPECT(assert_equal(Vector::Constant(d, 0), actual->sigmas()));\n  EXPECT(assert_equal(Vector::Constant(d, 0), actual->invsigmas())); // Actually zero as dummy value\n  EXPECT(assert_equal(Vector::Constant(d, 0), actual->precisions())); // Actually zero as dummy value\n\n  actual = Constrained::All(d, m);\n  EXPECT(assert_equal(Vector::Constant(d, m), actual->mu()));\n\n  actual = Constrained::All(d, mu);\n  EXPECT(assert_equal(mu, actual->mu()));\n\n  actual = Constrained::MixedSigmas(mu, sigmas);\n  EXPECT(assert_equal(mu, actual->mu()));\n\n  actual = Constrained::MixedSigmas(m, sigmas);\n  EXPECT(assert_equal(Vector::Constant(d, m), actual->mu()));\n}\n\n/* ************************************************************************* */\nTEST(NoiseModel, ConstrainedMixed )\n{\n  Vector feasible = Vector3(1.0, 0.0, 1.0),\n      infeasible = Vector3(1.0, 1.0, 1.0);\n  Diagonal::shared_ptr d = Constrained::MixedSigmas(Vector3(kSigma, 0.0, kSigma));\n  // NOTE: we catch constrained variables elsewhere, so whitening does nothing\n  EXPECT(assert_equal(Vector3(0.5, 1.0, 0.5),d->whiten(infeasible)));\n  EXPECT(assert_equal(Vector3(0.5, 0.0, 0.5),d->whiten(feasible)));\n\n  DOUBLES_EQUAL(1000.0 + 0.25 + 0.25,d->distance(infeasible),1e-9);\n  DOUBLES_EQUAL(0.5,d->distance(feasible),1e-9);\n}\n\n/* ************************************************************************* */\nTEST(NoiseModel, ConstrainedAll )\n{\n  Vector feasible = Vector3(0.0, 0.0, 0.0),\n       infeasible = Vector3(1.0, 1.0, 1.0);\n\n  Constrained::shared_ptr i = Constrained::All(3);\n  // NOTE: we catch constrained variables elsewhere, so whitening does nothing\n  EXPECT(assert_equal(Vector3(1.0, 1.0, 1.0),i->whiten(infeasible)));\n  EXPECT(assert_equal(Vector3(0.0, 0.0, 0.0),i->whiten(feasible)));\n\n  DOUBLES_EQUAL(1000.0 * 3.0,i->distance(infeasible),1e-9);\n  DOUBLES_EQUAL(0.0,i->distance(feasible),1e-9);\n}\n\n/* ************************************************************************* */\nnamespace exampleQR {\n  // create a matrix to eliminate\n  Matrix Ab = (Matrix(4, 7) <<\n      -1.,  0.,  1.,  0.,  0.,  0., -0.2,\n      0., -1.,  0.,  1.,  0.,  0.,  0.3,\n      1.,  0.,  0.,  0., -1.,  0.,  0.2,\n      0.,  1.,  0.,  0.,  0., -1., -0.1).finished();\n  Vector sigmas = (Vector(4) << 0.2, 0.2, 0.1, 0.1).finished();\n\n  // the matrix AB yields the following factorized version:\n  Matrix Rd = (Matrix(4, 7) <<\n      11.1803,   0.0,   -2.23607, 0.0,    -8.94427, 0.0,     2.23607,\n      0.0,   11.1803,    0.0,    -2.23607, 0.0,    -8.94427,-1.56525,\n      0.0,       0.0,    4.47214, 0.0,    -4.47214, 0.0,     0.0,\n      0.0,       0.0,   0.0,     4.47214, 0.0,    -4.47214, 0.894427).finished();\n\n  SharedDiagonal diagonal = noiseModel::Diagonal::Sigmas(sigmas);\n}\n\n/* ************************************************************************* */\nTEST( NoiseModel, QR )\n{\n  Matrix Ab1 = exampleQR::Ab;\n  Matrix Ab2 = exampleQR::Ab; // otherwise overwritten !\n\n  // Call Gaussian version\n  SharedDiagonal actual1 = exampleQR::diagonal->QR(Ab1);\n  EXPECT(actual1->isUnit());\n  EXPECT(linear_dependent(exampleQR::Rd,Ab1,1e-4)); // Ab was modified in place !!!\n\n  // Expected result for constrained version\n  Vector expectedSigmas = (Vector(4) << 0.0894427, 0.0894427, 0.223607, 0.223607).finished();\n  SharedDiagonal expectedModel = noiseModel::Diagonal::Sigmas(expectedSigmas);\n  Matrix expectedRd2 = (Matrix(4, 7) <<\n      1.,  0., -0.2,  0., -0.8, 0.,  0.2,\n      0.,  1.,  0.,-0.2,   0., -0.8,-0.14,\n      0.,  0.,  1.,   0., -1.,  0.,  0.0,\n      0.,  0.,  0.,   1.,  0., -1.,  0.2).finished();\n\n  // Call Constrained version\n  SharedDiagonal constrained = noiseModel::Constrained::MixedSigmas(exampleQR::sigmas);\n  SharedDiagonal actual2 = constrained->QR(Ab2);\n  EXPECT(assert_equal(*expectedModel, *actual2, 1e-6));\n  EXPECT(linear_dependent(expectedRd2, Ab2, 1e-6));  // Ab was modified in place !!!\n}\n\n/* ************************************************************************* */\nTEST(NoiseModel, OverdeterminedQR) {\n  Matrix Ab1(9, 4);\n  Ab1 << 0, 1, 0, 0,  //\n      0, 0, 1, 0,    //\n      Matrix74::Ones();\n  Matrix Ab2 = Ab1; // otherwise overwritten !\n\n  // Call Gaussian version\n  Vector9 sigmas = Vector9::Ones() ;\n  SharedDiagonal diagonal = noiseModel::Diagonal::Sigmas(sigmas);\n  SharedDiagonal actual1 = diagonal->QR(Ab1);\n  EXPECT(actual1->isUnit());\n  Matrix expectedRd(9,4);\n  expectedRd << -2.64575131, -2.64575131, -2.64575131, -2.64575131,  //\n      0.0, -1, 0, 0,                                                 //\n      0.0, 0.0, -1, 0,                                               //\n      Matrix64::Zero();\n  EXPECT(assert_equal(expectedRd, Ab1, 1e-4));  // Ab was modified in place !!!\n\n  // Expected result for constrained version\n  Vector3 expectedSigmas(0.377964473, 1, 1);\n  SharedDiagonal expectedModel = noiseModel::Diagonal::Sigmas(expectedSigmas);\n\n  // Call Constrained version\n  SharedDiagonal constrained = noiseModel::Constrained::MixedSigmas(sigmas);\n  SharedDiagonal actual2 = constrained->QR(Ab2);\n  EXPECT(assert_equal(*expectedModel, *actual2, 1e-6));\n  expectedRd.row(0) *= 0.377964473; // not divided by sigma!\n  EXPECT(assert_equal(-expectedRd, Ab2, 1e-6));  // Ab was modified in place !!!\n}\n\n/* ************************************************************************* */\nTEST( NoiseModel, MixedQR )\n{\n  // Call Constrained version, with first and third row treated as constraints\n  // Naming the 6 variables u,v,w,x,y,z, we have\n  // u = -z\n  // w = -x\n  // And let's have simple priors on variables\n  Matrix Ab(5,6+1);\n  Ab <<\n      1,0,0,0,0,1,  0, // u+z = 0\n      0,0,0,0,1,0,  0, // y^2\n      0,0,1,1,0,0,  0, // w+x = 0\n      0,1,0,0,0,0,  0, // v^2\n      0,0,0,0,0,1,  0; // z^2\n  Vector mixed_sigmas = (Vector(5) << 0, 1, 0, 1, 1).finished();\n  SharedDiagonal constrained = noiseModel::Constrained::MixedSigmas(mixed_sigmas);\n\n  // Expected result\n  Vector expectedSigmas = (Vector(5) << 0, 1, 0, 1, 1).finished();\n  SharedDiagonal expectedModel = noiseModel::Diagonal::Sigmas(expectedSigmas);\n  Matrix expectedRd(5, 6+1);\n  expectedRd << 1, 0, 0, 0, 0, 1, 0,  //\n                0, 1, 0, 0, 0, 0, 0,  //\n                0, 0, 1, 1, 0, 0, 0,  //\n                0, 0, 0, 0, 1, 0, 0,  //\n                0, 0, 0, 0, 0, 1, 0;  //\n\n  SharedDiagonal actual = constrained->QR(Ab);\n  EXPECT(assert_equal(*expectedModel,*actual,1e-6));\n  EXPECT(linear_dependent(expectedRd,Ab,1e-6)); // Ab was modified in place !!!\n}\n\n/* ************************************************************************* */\nTEST( NoiseModel, MixedQR2 )\n{\n  // Let's have three variables x,y,z, but x=z and y=z\n  // Hence, all non-constraints are really measurements on z\n  Matrix Ab(11,3+1);\n  Ab <<\n      1,0,0,  0, //\n      0,1,0,  0, //\n      0,0,1,  0, //\n     -1,0,1,  0, // x=z\n      1,0,0,  0, //\n      0,1,0,  0, //\n      0,0,1,  0, //\n     0,-1,1,  0, // y=z\n      1,0,0,  0, //\n      0,1,0,  0, //\n      0,0,1,  0; //\n\n  Vector sigmas(11);\n  sigmas.setOnes();\n  sigmas[3] = 0;\n  sigmas[7] = 0;\n  SharedDiagonal constrained = noiseModel::Constrained::MixedSigmas(sigmas);\n\n  // Expected result\n  Vector3 expectedSigmas(0,0,1.0/3);\n  SharedDiagonal expectedModel = noiseModel::Constrained::MixedSigmas(expectedSigmas);\n  Matrix expectedRd(11, 3+1);\n  expectedRd.setZero();\n  expectedRd.row(0) << -1,  0, 1,  0;  // x=z\n  expectedRd.row(1) <<  0, -1, 1,  0;  // y=z\n  expectedRd.row(2) <<  0,  0, 1,  0;  // z=0 +/- 1/3\n\n  SharedDiagonal actual = constrained->QR(Ab);\n  EXPECT(assert_equal(*expectedModel,*actual,1e-6));\n  EXPECT(assert_equal(expectedRd,Ab,1e-6)); // Ab was modified in place !!!\n}\n\n/* ************************************************************************* */\nTEST( NoiseModel, FullyConstrained )\n{\n  Matrix Ab(3,7);\n  Ab <<\n      1,0,0,0,0,1,  2, // u+z = 2\n      0,0,1,1,0,0,  4, // w+x = 4\n      0,1,0,1,1,1,  8; // v+x+y+z=8\n  SharedDiagonal constrained = noiseModel::Constrained::All(3);\n\n  // Expected result\n  SharedDiagonal expectedModel = noiseModel::Diagonal::Sigmas(Vector3 (0,0,0));\n  Matrix expectedRd(3, 7);\n  expectedRd << 1, 0, 0, 0, 0, 1, 2,  //\n                0, 1, 0, 1, 1, 1, 8,  //\n                0, 0, 1, 1, 0, 0, 4;  //\n\n  SharedDiagonal actual = constrained->QR(Ab);\n  EXPECT(assert_equal(*expectedModel,*actual,1e-6));\n  EXPECT(linear_dependent(expectedRd,Ab,1e-6)); // Ab was modified in place !!!\n}\n\n/* ************************************************************************* */\n// This matches constraint_eliminate2 in testJacobianFactor\nTEST(NoiseModel, QRNan )\n{\n  SharedDiagonal constrained = noiseModel::Constrained::All(2);\n  Matrix Ab = (Matrix25() << 2, 4, 2, 4, 6,   2, 1, 2, 4, 4).finished();\n\n  SharedDiagonal expected = noiseModel::Constrained::All(2);\n  Matrix expectedAb = (Matrix25() << 1, 2, 1, 2, 3, 0, 1, 0, 0, 2.0/3).finished();\n\n  SharedDiagonal actual = constrained->QR(Ab);\n  EXPECT(assert_equal(*expected,*actual));\n  EXPECT(linear_dependent(expectedAb,Ab));\n}\n\n/* ************************************************************************* */\nTEST(NoiseModel, SmartSqrtInformation )\n{\n  bool smart = true;\n  gtsam::SharedGaussian expected = Unit::Create(3);\n  gtsam::SharedGaussian actual = Gaussian::SqrtInformation(I_3x3, smart);\n  EXPECT(assert_equal(*expected,*actual));\n}\n\n/* ************************************************************************* */\nTEST(NoiseModel, SmartSqrtInformation2 )\n{\n  bool smart = true;\n  gtsam::SharedGaussian expected = Unit::Isotropic::Sigma(3,2);\n  gtsam::SharedGaussian actual = Gaussian::SqrtInformation(0.5*I_3x3, smart);\n  EXPECT(assert_equal(*expected,*actual));\n}\n\n/* ************************************************************************* */\nTEST(NoiseModel, SmartInformation )\n{\n  bool smart = true;\n  gtsam::SharedGaussian expected = Unit::Isotropic::Variance(3,2);\n  Matrix M = 0.5*I_3x3;\n  EXPECT(checkIfDiagonal(M));\n  gtsam::SharedGaussian actual = Gaussian::Information(M, smart);\n  EXPECT(assert_equal(*expected,*actual));\n}\n\n/* ************************************************************************* */\nTEST(NoiseModel, SmartCovariance )\n{\n  bool smart = true;\n  gtsam::SharedGaussian expected = Unit::Create(3);\n  gtsam::SharedGaussian actual = Gaussian::Covariance(I_3x3, smart);\n  EXPECT(assert_equal(*expected,*actual));\n}\n\n/* ************************************************************************* */\nTEST(NoiseModel, ScalarOrVector )\n{\n  bool smart = true;\n  SharedGaussian expected = Unit::Create(3);\n  SharedGaussian actual = Gaussian::Covariance(I_3x3, smart);\n  EXPECT(assert_equal(*expected,*actual));\n}\n\n/* ************************************************************************* */\nTEST(NoiseModel, WhitenInPlace)\n{\n  Vector sigmas = Vector3(0.1, 0.1, 0.1);\n  SharedDiagonal model = Diagonal::Sigmas(sigmas);\n  Matrix A = I_3x3;\n  model->WhitenInPlace(A);\n  Matrix expected = I_3x3 * 10;\n  EXPECT(assert_equal(expected, A));\n}\n\n/* ************************************************************************* */\n\n/*\n * These tests are responsible for testing the weight functions for the m-estimators in GTSAM.\n * The weight function is related to the analytic derivative of the residual function. See\n *  https://members.loria.fr/MOBerger/Enseignement/Master2/Documents/ZhangIVC-97-01.pdf\n * for details. This weight function is required when optimizing cost functions with robust\n * penalties using iteratively re-weighted least squares.\n */\n\nTEST(NoiseModel, robustFunctionFair)\n{\n  const double k = 5.0, error1 = 1.0, error2 = 10.0, error3 = -10.0, error4 = -1.0;\n  const mEstimator::Fair::shared_ptr fair = mEstimator::Fair::Create(k);\n  DOUBLES_EQUAL(0.8333333333333333, fair->weight(error1), 1e-8);\n  DOUBLES_EQUAL(0.3333333333333333, fair->weight(error2), 1e-8);\n  // Test negative value to ensure we take absolute value of error.\n  DOUBLES_EQUAL(0.3333333333333333, fair->weight(error3), 1e-8);\n  DOUBLES_EQUAL(0.8333333333333333, fair->weight(error4), 1e-8);\n\n  DOUBLES_EQUAL(0.441961080151135, fair->residual(error1), 1e-8);\n  DOUBLES_EQUAL(22.534692783297260, fair->residual(error2), 1e-8);\n  DOUBLES_EQUAL(22.534692783297260, fair->residual(error3), 1e-8);\n  DOUBLES_EQUAL(0.441961080151135, fair->residual(error4), 1e-8);\n}\n\nTEST(NoiseModel, robustFunctionHuber)\n{\n  const double k = 5.0, error1 = 1.0, error2 = 10.0, error3 = -10.0, error4 = -1.0;\n  const mEstimator::Huber::shared_ptr huber = mEstimator::Huber::Create(k);\n  DOUBLES_EQUAL(1.0, huber->weight(error1), 1e-8);\n  DOUBLES_EQUAL(0.5, huber->weight(error2), 1e-8);\n  // Test negative value to ensure we take absolute value of error.\n  DOUBLES_EQUAL(0.5, huber->weight(error3), 1e-8);\n  DOUBLES_EQUAL(1.0, huber->weight(error4), 1e-8);\n\n  DOUBLES_EQUAL(0.5000, huber->residual(error1), 1e-8);\n  DOUBLES_EQUAL(37.5000, huber->residual(error2), 1e-8);\n  DOUBLES_EQUAL(37.5000, huber->residual(error3), 1e-8);\n  DOUBLES_EQUAL(0.5000, huber->residual(error4), 1e-8);\n}\n\nTEST(NoiseModel, robustFunctionCauchy)\n{\n  const double k = 5.0, error1 = 1.0, error2 = 10.0, error3 = -10.0, error4 = -1.0;\n  const mEstimator::Cauchy::shared_ptr cauchy = mEstimator::Cauchy::Create(k);\n  DOUBLES_EQUAL(0.961538461538461, cauchy->weight(error1), 1e-8);\n  DOUBLES_EQUAL(0.2000, cauchy->weight(error2), 1e-8);\n  // Test negative value to ensure we take absolute value of error.\n  DOUBLES_EQUAL(0.2000, cauchy->weight(error3), 1e-8);\n  DOUBLES_EQUAL(0.961538461538461, cauchy->weight(error4), 1e-8);\n\n  DOUBLES_EQUAL(0.490258914416017, cauchy->residual(error1), 1e-8);\n  DOUBLES_EQUAL(20.117973905426254, cauchy->residual(error2), 1e-8);\n  DOUBLES_EQUAL(20.117973905426254, cauchy->residual(error3), 1e-8);\n  DOUBLES_EQUAL(0.490258914416017, cauchy->residual(error4), 1e-8);\n}\n\nTEST(NoiseModel, robustFunctionGemanMcClure)\n{\n  const double k = 1.0, error1 = 1.0, error2 = 10.0, error3 = -10.0, error4 = -1.0;\n  const mEstimator::GemanMcClure::shared_ptr gmc = mEstimator::GemanMcClure::Create(k);\n  DOUBLES_EQUAL(0.25      , gmc->weight(error1), 1e-8);\n  DOUBLES_EQUAL(9.80296e-5, gmc->weight(error2), 1e-8);\n  DOUBLES_EQUAL(9.80296e-5, gmc->weight(error3), 1e-8);\n  DOUBLES_EQUAL(0.25      , gmc->weight(error4), 1e-8);\n\n  DOUBLES_EQUAL(0.2500, gmc->residual(error1), 1e-8);\n  DOUBLES_EQUAL(0.495049504950495, gmc->residual(error2), 1e-8);\n  DOUBLES_EQUAL(0.495049504950495, gmc->residual(error3), 1e-8);\n  DOUBLES_EQUAL(0.2500, gmc->residual(error4), 1e-8);\n}\n\nTEST(NoiseModel, robustFunctionWelsch)\n{\n  const double k = 5.0, error1 = 1.0, error2 = 10.0, error3 = -10.0, error4 = -1.0;\n  const mEstimator::Welsch::shared_ptr welsch = mEstimator::Welsch::Create(k);\n  DOUBLES_EQUAL(0.960789439152323, welsch->weight(error1), 1e-8);\n  DOUBLES_EQUAL(0.018315638888734, welsch->weight(error2), 1e-8);\n  // Test negative value to ensure we take absolute value of error.\n  DOUBLES_EQUAL(0.018315638888734, welsch->weight(error3), 1e-8);\n  DOUBLES_EQUAL(0.960789439152323, welsch->weight(error4), 1e-8);\n\n  DOUBLES_EQUAL(0.490132010595960, welsch->residual(error1), 1e-8);\n  DOUBLES_EQUAL(12.271054513890823, welsch->residual(error2), 1e-8);\n  DOUBLES_EQUAL(12.271054513890823, welsch->residual(error3), 1e-8);\n  DOUBLES_EQUAL(0.490132010595960, welsch->residual(error4), 1e-8);\n}\n\nTEST(NoiseModel, robustFunctionTukey)\n{\n  const double k = 5.0, error1 = 1.0, error2 = 10.0, error3 = -10.0, error4 = -1.0;\n  const mEstimator::Tukey::shared_ptr tukey = mEstimator::Tukey::Create(k);\n  DOUBLES_EQUAL(0.9216, tukey->weight(error1), 1e-8);\n  DOUBLES_EQUAL(0.0, tukey->weight(error2), 1e-8);\n  // Test negative value to ensure we take absolute value of error.\n  DOUBLES_EQUAL(0.0, tukey->weight(error3), 1e-8);\n  DOUBLES_EQUAL(0.9216, tukey->weight(error4), 1e-8);\n\n  DOUBLES_EQUAL(0.480266666666667, tukey->residual(error1), 1e-8);\n  DOUBLES_EQUAL(4.166666666666667, tukey->residual(error2), 1e-8);\n  DOUBLES_EQUAL(4.166666666666667, tukey->residual(error3), 1e-8);\n  DOUBLES_EQUAL(0.480266666666667, tukey->residual(error4), 1e-8);\n}\n\nTEST(NoiseModel, robustFunctionDCS)\n{\n  const double k = 1.0, error1 = 1.0, error2 = 10.0;\n  const mEstimator::DCS::shared_ptr dcs = mEstimator::DCS::Create(k);\n\n  DOUBLES_EQUAL(1.0       , dcs->weight(error1), 1e-8);\n  DOUBLES_EQUAL(0.00039211, dcs->weight(error2), 1e-8);\n\n  DOUBLES_EQUAL(0.5         , dcs->residual(error1), 1e-8);\n  DOUBLES_EQUAL(0.9900990099, dcs->residual(error2), 1e-8);\n}\n\nTEST(NoiseModel, robustFunctionL2WithDeadZone)\n{\n  const double k = 1.0, e0 = -10.0, e1 = -1.01, e2 = -0.99, e3 = 0.99, e4 = 1.01, e5 = 10.0;\n  const mEstimator::L2WithDeadZone::shared_ptr lsdz = mEstimator::L2WithDeadZone::Create(k);\n\n  DOUBLES_EQUAL(0.9,           lsdz->weight(e0), 1e-8);\n  DOUBLES_EQUAL(0.00990099009, lsdz->weight(e1), 1e-8);\n  DOUBLES_EQUAL(0.0,           lsdz->weight(e2), 1e-8);\n  DOUBLES_EQUAL(0.0,           lsdz->weight(e3), 1e-8);\n  DOUBLES_EQUAL(0.00990099009, lsdz->weight(e4), 1e-8);\n  DOUBLES_EQUAL(0.9,           lsdz->weight(e5), 1e-8);\n\n  DOUBLES_EQUAL(40.5,    lsdz->residual(e0), 1e-8);\n  DOUBLES_EQUAL(0.00005, lsdz->residual(e1), 1e-8);\n  DOUBLES_EQUAL(0.0,     lsdz->residual(e2), 1e-8);\n  DOUBLES_EQUAL(0.0,     lsdz->residual(e3), 1e-8);\n  DOUBLES_EQUAL(0.00005, lsdz->residual(e4), 1e-8);\n  DOUBLES_EQUAL(40.5,    lsdz->residual(e5), 1e-8);\n}\n\n/* ************************************************************************* */\nTEST(NoiseModel, robustNoiseHuber)\n{\n  const double k = 10.0, error1 = 1.0, error2 = 100.0;\n  Matrix A = (Matrix(2, 2) << 1.0, 10.0, 100.0, 1000.0).finished();\n  Vector b = Vector2(error1, error2);\n  const Robust::shared_ptr robust = Robust::Create(\n    mEstimator::Huber::Create(k, mEstimator::Huber::Scalar),\n    Unit::Create(2));\n\n  robust->WhitenSystem(A, b);\n\n  DOUBLES_EQUAL(error1, b(0), 1e-8);\n  DOUBLES_EQUAL(sqrt(k*error2), b(1), 1e-8);\n\n  DOUBLES_EQUAL(1.0, A(0,0), 1e-8);\n  DOUBLES_EQUAL(10.0, A(0,1), 1e-8);\n  DOUBLES_EQUAL(sqrt(k*100.0), A(1,0), 1e-8);\n  DOUBLES_EQUAL(sqrt(k/100.0)*1000.0, A(1,1), 1e-8);\n}\n\nTEST(NoiseModel, robustNoiseGemanMcClure)\n{\n  const double k = 1.0, error1 = 1.0, error2 = 100.0;\n  const double a00 = 1.0, a01 = 10.0, a10 = 100.0, a11 = 1000.0;\n  Matrix A = (Matrix(2, 2) << a00, a01, a10, a11).finished();\n  Vector b = Vector2(error1, error2);\n  const Robust::shared_ptr robust = Robust::Create(\n    mEstimator::GemanMcClure::Create(k, mEstimator::GemanMcClure::Scalar),\n    Unit::Create(2));\n\n  robust->WhitenSystem(A, b);\n\n  const double k2 = k*k;\n  const double k4 = k2*k2;\n  const double k2error = k2 + error2*error2;\n\n  const double sqrt_weight_error1 = sqrt(0.25);\n  const double sqrt_weight_error2 = sqrt(k4/(k2error*k2error));\n\n  DOUBLES_EQUAL(sqrt_weight_error1*error1, b(0), 1e-8);\n  DOUBLES_EQUAL(sqrt_weight_error2*error2, b(1), 1e-8);\n\n  DOUBLES_EQUAL(sqrt_weight_error1*a00, A(0,0), 1e-8);\n  DOUBLES_EQUAL(sqrt_weight_error1*a01, A(0,1), 1e-8);\n  DOUBLES_EQUAL(sqrt_weight_error2*a10, A(1,0), 1e-8);\n  DOUBLES_EQUAL(sqrt_weight_error2*a11, A(1,1), 1e-8);\n}\n\nTEST(NoiseModel, robustNoiseDCS)\n{\n  const double k = 1.0, error1 = 1.0, error2 = 100.0;\n  const double a00 = 1.0, a01 = 10.0, a10 = 100.0, a11 = 1000.0;\n  Matrix A = (Matrix(2, 2) << a00, a01, a10, a11).finished();\n  Vector b = Vector2(error1, error2);\n  const Robust::shared_ptr robust = Robust::Create(\n    mEstimator::DCS::Create(k, mEstimator::DCS::Scalar),\n    Unit::Create(2));\n\n  robust->WhitenSystem(A, b);\n\n  const double sqrt_weight = 2.0*k/(k + error2*error2);\n\n  DOUBLES_EQUAL(error1, b(0), 1e-8);\n  DOUBLES_EQUAL(sqrt_weight*error2, b(1), 1e-8);\n\n  DOUBLES_EQUAL(a00, A(0,0), 1e-8);\n  DOUBLES_EQUAL(a01, A(0,1), 1e-8);\n  DOUBLES_EQUAL(sqrt_weight*a10, A(1,0), 1e-8);\n  DOUBLES_EQUAL(sqrt_weight*a11, A(1,1), 1e-8);\n}\n\nTEST(NoiseModel, robustNoiseL2WithDeadZone)\n{\n  double dead_zone_size = 1.0;\n  SharedNoiseModel robust = noiseModel::Robust::Create(\n    noiseModel::mEstimator::L2WithDeadZone::Create(dead_zone_size),\n    Unit::Create(3));\n\n/*\n * TODO(mike): There is currently a bug in GTSAM, where none of the mEstimator classes\n * implement a residual function, and GTSAM calls the weight function to evaluate the\n * total penalty, rather than calling the residual function. The weight function should be\n * used during iteratively reweighted least squares optimization, but should not be used to\n * evaluate the total penalty. The long-term solution is for all mEstimators to implement\n * both a weight and a residual function, and for GTSAM to call the residual function when\n * evaluating the total penalty. This bug causes the test below to fail, so I'm leaving it\n * commented out until the underlying bug in GTSAM is fixed.\n *\n * for (int i = 0; i < 5; i++) {\n *   Vector3 error = Vector3(i, 0, 0);\n *   DOUBLES_EQUAL(0.5*max(0,i-1)*max(0,i-1), robust->distance(error), 1e-8);\n * }\n */\n\n}\n\n/* ************************************************************************* */\n#define TEST_GAUSSIAN(gaussian)\\\n  EQUALITY(info, gaussian->information());\\\n  EQUALITY(cov, gaussian->covariance());\\\n  EXPECT(assert_equal(white, gaussian->whiten(e)));\\\n  EXPECT(assert_equal(e, gaussian->unwhiten(white)));\\\n  EXPECT_DOUBLES_EQUAL(251, gaussian->distance(e), 1e-9);\\\n  Matrix A = R.inverse(); Vector b = e;\\\n  gaussian->WhitenSystem(A, b);\\\n  EXPECT(assert_equal(I, A));\\\n  EXPECT(assert_equal(white, b));\n\nTEST(NoiseModel, NonDiagonalGaussian)\n{\n  Matrix3 R;\n  R << 6, 5, 4, 0, 3, 2, 0, 0, 1;\n  const Matrix3 info = R.transpose() * R;\n  const Matrix3 cov = info.inverse();\n  const Vector3 e(1, 1, 1), white = R * e;\n  Matrix I = Matrix3::Identity();\n\n\n  {\n  SharedGaussian gaussian = Gaussian::SqrtInformation(R);\n  TEST_GAUSSIAN(gaussian);\n  }\n\n  {\n  SharedGaussian gaussian = Gaussian::Information(info);\n  TEST_GAUSSIAN(gaussian);\n  }\n\n  {\n  SharedGaussian gaussian = Gaussian::Covariance(cov);\n  TEST_GAUSSIAN(gaussian);\n  }\n}\n\n/* ************************************************************************* */\nint main() {  TestResult tr; return TestRegistry::runAllTests(tr); }\n/* ************************************************************************* */\n", "meta": {"hexsha": "10578627f0c3bc9bb594ac6dcc4bf53589a48809", "size": 27242, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/linear/tests/testNoiseModel.cpp", "max_stars_repo_name": "kvmanohar22/gtsam", "max_stars_repo_head_hexsha": "8194b931fe07fb1bd346cdcf116a35f9c4e208ba", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-21T14:19:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-21T14:19:34.000Z", "max_issues_repo_path": "gtsam/linear/tests/testNoiseModel.cpp", "max_issues_repo_name": "kvmanohar22/gtsam", "max_issues_repo_head_hexsha": "8194b931fe07fb1bd346cdcf116a35f9c4e208ba", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-03-02T17:39:13.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-02T17:39:13.000Z", "max_forks_repo_path": "gtsam/linear/tests/testNoiseModel.cpp", "max_forks_repo_name": "kvmanohar22/gtsam", "max_forks_repo_head_hexsha": "8194b931fe07fb1bd346cdcf116a35f9c4e208ba", "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": 37.5751724138, "max_line_length": 102, "alphanum_fraction": 0.6162910212, "num_tokens": 9197, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.6859494485880927, "lm_q1q2_score": 0.4588180457729532}}
{"text": "////////////////////////////////////////////////////////////////////////////////\n#include \"boundary_loop.h\"\n#include <cellogram/tri2hex.h>\n#include <cellogram/navigation.h>\n// #include <igl/is_border_vertex.h>\n#include <igl/edges.h>\n#include <Eigen/Dense>\n#include <vector>\n#include <iostream>\n////////////////////////////////////////////////////////////////////////////////\n\nnamespace cellogram {\n\n// -----------------------------------------------------------------------------\n\ttypedef std::vector<int> Path;\n\nPath get_longest_path(const std::vector<Path> &paths) {\n\tif (paths.empty()) return Path();\n\tint maxi = 0;\n\tfor (unsigned int i = 1; i < paths.size(); i++) {\n\t\tif (paths[maxi].size() < paths[i].size()) {\n\t\t\tmaxi = i;\n\t\t}\n\t}\n\treturn paths[maxi];\n}\n\nEigen::VectorXi path_to_vecXi(const Path &p) {\n\tEigen::VectorXi res(p.size());\n\tfor (size_t i = 0; i < p.size(); i++) res(i)=p[i];\n\treturn res;\n}\n\nvoid boundary_graph(const Eigen::MatrixXi &F, std::vector<std::vector<int>> &adj) {\n\tint num_vertices = F.maxCoeff() + 1;\n\tNavigationData data(F);\n\tadj.clear();\n\tadj.resize(num_vertices);\n\tfor (int f = 0; f < F.rows(); ++f) {\n\t\tNavigationIndex idx = index_from_face(F, data, f, 0);\n\t\tfor (int lv = 0; lv < F.cols(); ++lv) {\n\t\t\tif (switch_face(data, idx).face < 0) {\n\t\t\t\tint v1 = idx.vertex;\n\t\t\t\tint v2 = switch_vertex(data, idx).vertex;\n\t\t\t\tadj[v1].push_back(v2);\n\t\t\t\tadj[v2].push_back(v1);\n\t\t\t}\n\t\t\tidx = next_around_face(data, idx);\n\t\t}\n\t}\n}\n\nvoid boundary_loop(const Eigen::MatrixXi &F, Eigen::VectorXi &longest_path) {\n\n\tint n = F.maxCoeff() + 1;\n\n\t// Eigen::VectorXd Vdummy(F.maxCoeff() + 1, 1);\n\t// std::vector<bool> border_vertex = igl::is_border_vertex(Vdummy, F);\n\n\tstd::vector<std::vector<int>> adj;\n\t//tri2hex(F, adj);\n\tboundary_graph(F, adj);\n\n\tstd::vector< Path > paths; // paths that we detect\n\n\tint num_vertices = adj.size();\n\tstd::vector<bool> possible_starting_point(num_vertices, true);\n\tfor (int v0 = 0; v0 < num_vertices; ++v0) {\n\t\tif (adj[v0].size() == 2 && possible_starting_point[v0]) {\n\t\t\tstd::vector<bool> in_the_path(num_vertices, false);\n\t\t\tstd::vector<bool> has_been_removed(num_vertices, false);\n\t\t\tstd::vector<int> prev(num_vertices, -1);\n\t\t\tint x = v0;\n\t\t\tPath path;\n\t\t\tpath.push_back(v0);\n\t\t\tin_the_path[v0] = true;\n\t\t\tprev[v0] = v0;\n\t\t\tfor (int i = 0; i < num_vertices; ++i) {\n\t\t\t\t// Check neighbors of x\n\t\t\t\tbool found_v0 = false;\n\t\t\t\tfor (int y : adj[x]) {\n\t\t\t\t\tif (in_the_path[y]) {\n\t\t\t\t\t\tif (y == v0) {\n\t\t\t\t\t\t\tfound_v0 = true;\n\t\t\t\t\t\t} else if (prev[x] != y) {\n\t\t\t\t\t\t\tint z = x;\n\t\t\t\t\t\t\twhile (z != y) {\n\t\t\t\t\t\t\t\tpath.pop_back();\n\t\t\t\t\t\t\t\thas_been_removed[z] = true;\n\t\t\t\t\t\t\t\tin_the_path[z] = false;\n\t\t\t\t\t\t\t\tint old_z = z;\n\t\t\t\t\t\t\t\tz = prev[z];\n\t\t\t\t\t\t\t\tprev[old_z] = -1;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\thas_been_removed[y] = false;\n\t\t\t\t\t\t\tx = y;\n\t\t\t\t\t\t\tfound_v0 = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (!has_been_removed[y]) {\n\t\t\t\t\t\tprev[y] = x;\n\t\t\t\t\t\tx = y;\n\t\t\t\t\t\tfound_v0 = false;\n\t\t\t\t\t\tpath.push_back(x);\n\t\t\t\t\t\tin_the_path[x] = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (x == v0 || found_v0) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Cleanup\n\t\t\tfor (int x : path) {\n\t\t\t\tpossible_starting_point[x] = false;\n\t\t\t}\n\t\t\tif (!path.empty()) {\n\t\t\t\tif (path.size() == 3) {\n\t\t\t\t\t//std::cout << \"boundary_loop.cpp, path size is only three \" << v0 << std::endl << \"Path not added\\n\";\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\t//std::cout << path.size() << std::endl;\n\t\t\t\t\tpaths.push_back(path);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\n\tlongest_path = path_to_vecXi( get_longest_path(paths) );\n\n}\n\n// -----------------------------------------------------------------------------\n\n} // namespace cellogram\n", "meta": {"hexsha": "f46f5615435feb0ad91272c15624751bf2a4ef06", "size": 3568, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cellogram/boundary_loop.cpp", "max_stars_repo_name": "cellogram/cellogram", "max_stars_repo_head_hexsha": "d378e9b87e56b879b2fb352b08b0fed714481968", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-09-25T15:04:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-20T08:17:44.000Z", "max_issues_repo_path": "src/cellogram/boundary_loop.cpp", "max_issues_repo_name": "cellogram/cellogram", "max_issues_repo_head_hexsha": "d378e9b87e56b879b2fb352b08b0fed714481968", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cellogram/boundary_loop.cpp", "max_forks_repo_name": "cellogram/cellogram", "max_forks_repo_head_hexsha": "d378e9b87e56b879b2fb352b08b0fed714481968", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-10-14T01:36:20.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-11T20:27:57.000Z", "avg_line_length": 25.6690647482, "max_line_length": 107, "alphanum_fraction": 0.5322309417, "num_tokens": 1033, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081925, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.4588180455395517}}
{"text": "#include \"ros/ros.h\"\n#include \"std_msgs/String.h\"\n#include \"geometry_msgs/Twist.h\"\n#include \"geometry_msgs/PoseStamped.h\"\n#include \"videoray/Throttle.h\"\n#include \"nav_msgs/Odometry.h\"\n\n#include <iostream>\n#include <sstream>\n\n#include <boost/numeric/odeint.hpp>\n\nusing std::cout;\nusing std::endl;\n\nusing namespace boost::numeric::odeint;\n\ntypedef boost::array< double , 6 > state_type;\n\n#define PI (3.14159265359)\n\nvideoray::Throttle throttle_;\nvoid throttleCallback(const videoray::Throttle::ConstPtr& msg)\n{\n     throttle_ = *msg;\n     //// Left Throttle Conversion:\n     //left_vel_ = saturate(msg->LeftThrottle, -100, 100);\n     //left_vel_ = normalize(left_vel_, -100, 100, -1, 1);\n     //\n     //// Right Throttle Conversion:\n     //right_vel_ = saturate(msg->RightThrottle, -100, 100);\n     //right_vel_ = normalize(right_vel_, -100, 100, -1, 1);\n     //\n     //// Vertical Throttle Conversion:\n     //vert_vel_ = saturate(msg->VerticalThrottle, -100, 100);\n     //vert_vel_ = normalize(vert_vel_, -100, 100, -1, 1);\n}\n\nnav_msgs::Odometry odom_;\nvoid odomCallback(const nav_msgs::Odometry::ConstPtr& msg)\n{\n     odom_ = *msg;\n}\n\n// Linear and angular velocity states\ndouble u;\ndouble v;\ndouble w;\ndouble p;\ndouble q;\ndouble r;\n          \n// Added Mass Terms\ndouble X_udot = 1.94; // inertia matrix M (m11)\ndouble Y_vdot = 6.05; // inertia matrix M (m22)\ndouble Z_wdot = 3.95; // m33\ndouble N_rdot = 1.18e-2; // vehicle's motion of inertia about z-axis\n// (6,6) entry of the vehicle inertia Matrix M\n\n// Linear Drag Coefficients\ndouble Xu = -0.95;\ndouble Yv = -5.87;\ndouble Nr = -0.023;\ndouble Zw = -3.70;\n\n// Quadratic Drag Coefficients\ndouble Xuu = -6.04;\ndouble Yvv = -30.73;\ndouble Nrr = -0.45;\ndouble Zww = -26.36;\n\ndouble Ct_forw = 0.026667;\ndouble Ct_back = 0.026667;\ndouble Ct_vert_forw = 0.026667;\ndouble Ct_vert_back = 0.026667;\n\ndouble u_sat_low = -150;\ndouble u_sat_high = 150;\n     \n// Control inputs\ndouble X = 0;\ndouble N = 0;\ndouble Z = 0;\n\ndouble u_port = 0;\ndouble u_star = 0;\ndouble u_vert = 0;\n\nvoid videoray_model( const state_type &x , state_type &dxdt , double t )\n{\n/// States: \n/// 0:  u     : surge velocity\n/// 1:  v     : sway velocity\n/// 2:  w     : heave velocity\n/// 3:  p     : roll rate\n/// 4:  q     : pitch rate\n/// 5:  r     : yaw rate\n     u = x[0];\n     v = x[1];\n     w = x[2];\n     p = x[3];\n     q = x[4];\n     r = x[5];\n          \n     // Calculate fixed frame velocity rates\n     dxdt[0] = (-Y_vdot*v*r + Xu*u + Xuu*u*abs(u) + X) / X_udot;\n     dxdt[1] = (X_udot*u*r + Yv*v + Yvv*v*abs(v)) / Y_vdot;\n     dxdt[2] = (Zw*w + Zww*w*abs(w) + Z) / Z_wdot;\n\n     // Calculate fixed frame orientation rates\n     dxdt[3] = 0;\n     dxdt[4] = 0;\n     dxdt[5] = (Nr*r + Nrr*r*abs(r) + N) / N_rdot;     \n}\n\n//\n// Converts input throttle commands to simulated linear and angular velocities.\n//\ngeometry_msgs::Twist velocity_cmd_;\ngeometry_msgs::Vector3 velocity_linear_;\ngeometry_msgs::Vector3 velocity_angular_;\n\ndouble saturate(double input, const double &min, const double &max)\n{\n     if (min > max) {\n          ROS_INFO(\"saturate(): Invalid Min / Max Combo\");\n          return 0;\n     } else if (input < min) {\n          input = min;\n     } else if(input > max) {\n          input = max;\n     }\n     return input;\n}\n\n// Assumes that input has already been saturated within the in_min and in_max\n// boundaries. Use the saturate() function on input before calling normalize\ndouble normalize(double input, const double &in_min, const double &in_max,\n                 const double &out_min, const double &out_max)\n{\n     if (in_min >= in_max || out_min >= out_max) {\n          ROS_INFO(\"normalize(): Invalid Min / Max Combo\");\n          return 0;\n     }\n\n     double ratio = input / (in_max - in_min);\n     return ratio * (out_max - out_min);\n\n     return input;\n}\n\ndouble thrust_port = 0, thrust_star = 0;\nvoid processThrottleCmds()\n{\n     u_port = saturate(throttle_.PortInput, u_sat_low, u_sat_high);\n     u_star = saturate(throttle_.StarInput, u_sat_low, u_sat_high);\n     u_vert = saturate(throttle_.VertInput, u_sat_low, u_sat_high);\n\n     // Ct is different for reverse and forward\n     if ( u_port >= 0 ) {\n          thrust_port = u_port * Ct_forw;\n     } else {\n          thrust_port = u_port * Ct_back;\n     }\n\n     if ( u_star >= 0 ) {\n          thrust_star = u_star * Ct_forw;\n     } else {\n          thrust_star = u_star * Ct_back;\n     }\n\n     X = thrust_port + thrust_star;\n     N = thrust_star - thrust_port;\n\n     // Ct is different for reverse and forward\n     if ( u_vert >= 0 ) {\n          Z = u_vert * Ct_vert_forw;\n     } else {\n          Z = u_vert * Ct_vert_back;\n     }\n\n}\n\nvoid quaternionToEuler(const double &q0, const double &q1, \n                       const double &q2, const double &q3,\n                       double &roll, double &pitch, double &yaw)\n{\n     roll = atan2(2*(q0*q1 + q2*q3), 1 - 2*(q1*q1 + q2*q2) );\n     pitch = asin(2*(q0*q2-q3*q1));\n     yaw = atan2(2*(q0*q3 + q1*q2), 1 - 2*(q2*q2 + q3*q3) );\n}\n\nrunge_kutta4< state_type > stepper; \n\nint main(int argc, char **argv)\n{\n     ros::init(argc, argv, \"videoray_sim\");     \n     ros::NodeHandle n;\n\n     ros::Publisher twist_pub = n.advertise<geometry_msgs::Twist>(\"motion\", 1);\n     ros::Subscriber throttle_sub = n.subscribe(\"throttle_cmds\", 1, \n                                                throttleCallback);\n     ros::Subscriber odom_sub = n.subscribe(\"odometry\", 1, \n                                            odomCallback);\n     \n     double rate = 10;\n     ros::Rate loop_rate(rate);\n\n     ros::Time begin = ros::Time::now();\n     ros::Time curr_time = begin;\n     ros::Time prev_time = begin;\n     ros::Duration dt = curr_time - prev_time;\n     \n     while (ros::ok())\n     {\n          //cout << \"*\" << std::flush;\n          \n\n          curr_time = ros::Time::now();\n          dt = curr_time - prev_time;\n          prev_time = curr_time;\n\n          //cout << dt.toSec() << endl << std::flush;\n\n          // Update state vector with odometry data from morse...\n          state_type x = {0,0,0,0,0,0};\n          x[0] = odom_.twist.twist.linear.x;\n          x[1] = odom_.twist.twist.linear.y;\n          x[2] = odom_.twist.twist.linear.z;\n          x[3] = odom_.twist.twist.angular.x;\n          x[4] = odom_.twist.twist.angular.y;\n          x[5] = odom_.twist.twist.angular.z;\n\n          processThrottleCmds();\n\n          //geometry_msgs::Quaternion quat = odom_.pose.pose.orientation;\n          //quaternionToEuler(quat.x, quat.y, quat.z, quat.w,\n          //                  roll_, pitch_, yaw_);\n          \n          //boost::numeric::odeint::integrate(videoray_model, \n          //                                  x, \n          //                                  curr_time.toSec() , \n          //                                  (curr_time + dt).toSec(), \n          //                                  dt.toSec());\n          boost::numeric::odeint::integrate(videoray_model, \n                                            x, \n                                            curr_time.toSec() , \n                                            curr_time.toSec() + 1.0/rate, \n                                            1.0/rate);\n\n          //ROS_INFO(\"========================\");\n          //ROS_INFO(\"Current: %f, \\tdt: %f\", curr_time.toSec(), dt.toSec());\n          //ROS_INFO(\"Surge: %f\", x[0]);\n          //ROS_INFO(\"Sway: %f\", x[1]);\n          //ROS_INFO(\"Heave: %f\", x[2]);\n          //\n          //ROS_INFO(\"3: %f\", x[3]);\n          //ROS_INFO(\"4: %f\", x[4]);\n          //ROS_INFO(\"5: %f\", x[5]);\n          ////ROS_INFO(\"6: %f\", x[6]);\n          ////ROS_INFO(\"7: %f\", x[7]);\n          ////ROS_INFO(\"8: %f\", x[8]);\n          ////ROS_INFO(\"9: %f\", x[9]);\n          ////ROS_INFO(\"10: %f\", x[10]);\n          ////ROS_INFO(\"11: %f\", x[11]);\n          \n          velocity_linear_.x = x[0];\n          velocity_linear_.y = x[1];\n          velocity_linear_.z = x[2];\n          velocity_angular_.z = x[5];\n          \n          velocity_cmd_.linear = velocity_linear_;\n          velocity_cmd_.angular = velocity_angular_;\n          twist_pub.publish(velocity_cmd_);\n\n          ros::spinOnce();\n\n          loop_rate.sleep();\n     }\n     return 0;\n}\n", "meta": {"hexsha": "c01be4ba4d2f5e9eb17b5f19287de61c15c0a614", "size": 8179, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/videoray/catkin_ws/src/videoray/src/sim/videoray_sim.cpp", "max_stars_repo_name": "toremobjo/VideoRayROS", "max_stars_repo_head_hexsha": "aa13a6d4f924fbcd7c2b0b2016a7b409b9272d63", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-06-17T18:23:27.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-14T05:33:24.000Z", "max_issues_repo_path": "src/videoray/catkin_ws/src/videoray/src/sim/videoray_sim.cpp", "max_issues_repo_name": "toremobjo/VideoRayROS", "max_issues_repo_head_hexsha": "aa13a6d4f924fbcd7c2b0b2016a7b409b9272d63", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-07-01T09:01:17.000Z", "max_issues_repo_issues_event_max_datetime": "2016-07-02T15:24:15.000Z", "max_forks_repo_path": "src/videoray/catkin_ws/src/videoray/src/sim/videoray_sim.cpp", "max_forks_repo_name": "toremobjo/VideoRayROS", "max_forks_repo_head_hexsha": "aa13a6d4f924fbcd7c2b0b2016a7b409b9272d63", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2015-02-20T11:57:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-20T12:42:54.000Z", "avg_line_length": 29.0035460993, "max_line_length": 79, "alphanum_fraction": 0.5449321433, "num_tokens": 2333, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4587460898750612}}
{"text": "//////////////////////////////////////////////////////////////////////////////\n// random::poisson_ex::devroye::detail::step4::squeeze.hpp         \t\t\t//\n//                                                                          //\n//                                                                          //\n//  (C) Copyright 2010 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_RANDOM_POISSON_EXT_DEVROYE_DETAIL_STEP4_SQUEEZE_HPP_ER_2010\n#define BOOST_RANDOM_POISSON_EXT_DEVROYE_DETAIL_STEP4_SQUEEZE_HPP_ER_2010\n#include <boost/random/poisson_ext/devroye/detail/q.hpp>\n#include <boost/random/poisson_ext/devroye/detail/math.hpp>\n#include <boost/random/poisson_ext/devroye/detail/int_mean.hpp>\n\nnamespace boost{\nnamespace random{\nnamespace poisson{\nnamespace devroye{  \nnamespace detail{\nnamespace step4{\n\n    // Poisson sampler by the method of Devroye with a squeeze step4\n\t//\n\t// Complexity O(1) as mean -> infinity, p.204\n    //\n    // Bug : currently does not converge.\n\ttemplate<typename Int ,typename T,typename P>\n    class squeeze :\n        detail::q<Int,T,P>, \n        public detail::int_mean<step4::squeeze<Int,T,P>,Int,T,P>\n    {\n\n\t\ttypedef detail::q<Int,T,P> q_fun_;\n        typedef devroye::detail::math<Int,T,P> ma_;\n\n\t\ttypedef detail::int_mean<step4::squeeze<Int,T,P>,Int,T,P> super_;\n\n\t\tpublic:\n\t\ttypedef typename super_::result_type result_type;\n\t\ttypedef typename super_::input_type input_type;\n\n\t\tsqueeze():super_(){}\n\t\texplicit squeeze(const result_type& mean):super_(mean){}\n\n\t\tbool accept(){        \n            bool a = ma_::is_strictly_negative(this->x());\n\n\t\t\ttypedef result_type int_; \t\n\t\t\ttypedef input_type float_;  \t\n\t\t\tint_ y1 = this->y();\n\t\t\tint_ yp1 = y1 + 1;\n            int_ y1yp1 = y1 * yp1;\n\n\t\t\tfloat_ t = ma_::to_float(y1yp1) / this->m2(); \t// 1.\n            \n\t\t\tif(\n            \t(!a) && ( this->v() < (-t) )\n            ){\n\t\t\t\t// exit\n            }else{\n                int_ m1 = this->int_mean_val();\n                int_ m6 = 6 * m1;\n                int_ y2 = 2 * y1;\n                int_ y2p1 = y2 + 1;\n                int_ m1p_ayp1 = m1 + a ? yp1 : 0;\n\n            \tfloat_ qr = t * ( \n                \tma_::to_float(y2p1) /ma_::to_float(m6) - ma_::to_float(1) \n                );\n                float_ tsq = t * t;\n            \tfloat_ qa =  qr - tsq  / ma_::to_float(3 * m1p_ayp1); \n\n\t\t\t\tif(this->v()<qa){\n\t\t\t\t\t// exit                \n                }else{\n                \tif(this->v()>qr){\n                    \treturn false;\n                    }else{\n\t\t\t\t\t\t\n                    \tfloat_ q_val = this->q_fun(m1,this->y());\n                    \n                    \tif(this->v() < q_val)\n                        {\n                        \t// exit\n                        }else{\n                        \treturn false;\n                        }\n                    }\n                }\n\t\t\t\treturn false;            \n            }\n\n            // exit :\n            this->y_ += this->int_mean_val();\n            return true;\n\t\t}\n\n\n\t};\n    \n}// detail\n}// step4\n}// devroye\n}// poisson\n}// random\n}// boost\n\n#endif\n\n", "meta": {"hexsha": "78469f8735362c7a9e85ef6fe99e7fe994b64b7c", "size": 3396, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "random/boost/random/poisson_ext/devroye/detail/step4/squeeze.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": "random/boost/random/poisson_ext/devroye/detail/step4/squeeze.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": "random/boost/random/poisson_ext/devroye/detail/step4/squeeze.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": 30.5945945946, "max_line_length": 78, "alphanum_fraction": 0.464958775, "num_tokens": 825, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4587460846929107}}
{"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_filter_nonlinear_generic.hpp\n * \\date October 2014\n * \\author Jan Issac (jan.issac@gmail.com)\n */\n\n#pragma once\n\n\n#include <Eigen/Dense>\n\n#include <fl/util/meta.hpp>\n#include <fl/util/traits.hpp>\n#include <fl/filter/filter_interface.hpp>\n#include <fl/distribution/gaussian.hpp>\n\nnamespace fl\n{\n\n/**\n* \\defgroup generic_nonlinear_gaussian_filter Generic Nonlinear Gaussian Filter\n* \\ingroup filters\n*/\n\n// Forward delcaration\ntemplate <typename...> class GaussianFilter;\n\n/**\n * \\internal\n * \\ingroup nonlinear_gaussian_filter\n * \\ingroup generic_nonlinear_gaussian_filter\n *\n * Traits for generic GaussianFilter based on quadrature (numeric integration)\n * with customizable policies, i.e implementations of the time and measurement\n * updates.\n */\ntemplate <\n    typename Transition,\n    typename Sensor,\n    typename Quadrature,\n    typename ... Policies\n>\nstruct Traits<\n           GaussianFilter<\n               Transition, Sensor, Quadrature, Policies...>>\n{\n    typedef typename Transition::State State;\n    typedef typename Transition::Input Input;\n    typedef typename Sensor::Obsrv Obsrv;\n    typedef Gaussian<State> Belief;\n};\n\n/**\n * \\ingroup nonlinear_gaussian_filter\n * \\ingroup generic_nonlinear_gaussian_filter\n *\n * GaussianFilter represents all filters based on Gaussian distributed systems.\n * This includes the Kalman Filter and filters using non-linear models such as\n * Sigma Point Kalman Filter family.\n *\n * \\tparam TransitionFunction\n * \\tparam SensorFunction\n * \\tparam Quadrature\n * \\tparam PredictionPolicy\n * \\tparam UpdatePolicy\n */\ntemplate<\n    typename TransitionFunction,\n    typename SensorFunction,\n    typename Quadrature,\n    typename PredictionPolicy,\n    typename UpdatePolicy\n>\nclass GaussianFilter<\n          TransitionFunction,\n          SensorFunction,\n          Quadrature,\n          PredictionPolicy,\n          UpdatePolicy>\n    :\n    /* Implement the filter interface */\n    public FilterInterface<\n               GaussianFilter<\n                   TransitionFunction,\n                   SensorFunction,\n                   Quadrature,\n                   PredictionPolicy,\n                   UpdatePolicy>>\n{\npublic:\n    typedef typename TransitionFunction::State State;\n    typedef typename TransitionFunction::Input Input;\n    typedef typename SensorFunction::Obsrv Obsrv;\n    typedef Gaussian<State> Belief;\n\npublic:\n    /**\n     * Creates a Gaussian filter\n     *\n     * \\param transition         Process model instance\n     * \\param sensor           Obsrv model instance\n     * \\param transform   Point set tranfrom such as the unscented\n     *                              transform\n     */\n    GaussianFilter(const TransitionFunction& transition,\n                   const SensorFunction& sensor,\n                   const Quadrature& quadrature)\n        : transition_(transition),\n          sensor_(sensor),\n          quadrature_(quadrature)\n    { }\n\n    /**\n     * \\brief Overridable default destructor\n     */\n    virtual ~GaussianFilter() { }\n\n    /**\n     * \\copydoc FilterInterface::predict\n     */\n    virtual void predict(const Belief& prior_belief,\n                         const Input& input,\n                         Belief& predicted_belief)\n    {\n        prediction_policy_(transition(),\n                           quadrature(),\n                           prior_belief,\n                           input,\n                           predicted_belief);\n    }\n\n    /**\n     * \\copydoc FilterInterface::update\n     */\n    virtual void update(const Belief& predicted_belief,\n                        const Obsrv& obsrv,\n                        Belief& posterior_belief)\n    {\n        update_policy_(sensor(),\n                       quadrature(),\n                       predicted_belief,\n                       obsrv,\n                       posterior_belief);\n    }\n\npublic: /* factory functions */\n    virtual Belief create_belief() const\n    {\n        auto belief = Belief(transition().state_dimension());\n        return belief; // RVO\n    }\n\npublic: /* accessors & mutators */\n    TransitionFunction& transition()\n    {\n        return transition_;\n    }\n\n    SensorFunction& sensor()\n    {\n        return sensor_;\n    }\n\n    Quadrature& quadrature()\n    {\n        return quadrature_;\n    }\n\n    const TransitionFunction& transition() const\n    {\n        return transition_;\n    }\n\n    const SensorFunction& sensor() const\n    {\n        return sensor_;\n    }\n\n    const Quadrature& quadrature() const\n    {\n        return quadrature_;\n    }\n\n    virtual std::string name() const\n    {\n        return \"GaussianFilter<\"\n                + this->list_arguments(\n                            transition().name(),\n                            sensor().name(),\n                            quadrature().name(),\n                            prediction_policy_.name(),\n                            update_policy_.name())\n                + \">\";\n    }\n\n    virtual std::string description() const\n    {\n        return \"Sigma point based GaussianFilter with\"\n                + this->list_descriptions(\n                            transition().description(),\n                            sensor().description(),\n                            quadrature().description(),\n                            prediction_policy_.description(),\n                            update_policy_.description());\n    }\n\nprotected:\n    /** \\cond internal */\n    TransitionFunction transition_;\n    SensorFunction sensor_;\n    Quadrature quadrature_;\n    PredictionPolicy prediction_policy_;\n    UpdatePolicy update_policy_;\n    /** \\endcond */\n};\n\n}\n\n\n", "meta": {"hexsha": "4af28f28459f58b5919c3fbb01b41b415f2317ba", "size": 6007, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/fl/filter/gaussian/gaussian_filter_nonlinear_generic.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/gaussian_filter_nonlinear_generic.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/gaussian_filter_nonlinear_generic.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": 25.7811158798, "max_line_length": 79, "alphanum_fraction": 0.5944731147, "num_tokens": 1133, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788903594354, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.45874607432860937}}
{"text": "// math_fwd.hpp\n\n// TODO revise completely for new distribution classes.\n\n// Copyright Paul A. Bristow 2006.\n// Copyright John Maddock 2006.\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// Omnibus list of forward declarations of math special functions.\n\n// IT = Integer type.\n// RT = Real type (built-in floating-point types, float, double, long double) & User Defined Types\n// AT = Integer or Real type\n\n#ifndef BOOST_MATH_SPECIAL_MATH_FWD_HPP\n#define BOOST_MATH_SPECIAL_MATH_FWD_HPP\n\n#ifdef _MSC_VER\n#pragma once\n#endif\n\n#include <vector>\n#include <boost/math/special_functions/detail/round_fwd.hpp>\n#include <boost/math/tools/promotion.hpp> // for argument promotion.\n#include <boost/math/policies/policy.hpp>\n#include <boost/mpl/comparison.hpp>\n#include <boost/utility/enable_if.hpp>\n#include <boost/config/no_tr1/complex.hpp>\n\n#define BOOST_NO_MACRO_EXPAND /**/\n\nnamespace boost\n{\n   namespace math\n   { // Math functions (in roughly alphabetic order).\n\n   // Beta functions.\n   template <class RT1, class RT2>\n   typename tools::promote_args<RT1, RT2>::type\n         beta(RT1 a, RT2 b); // Beta function (2 arguments).\n\n   template <class RT1, class RT2, class A>\n   typename tools::promote_args<RT1, RT2, A>::type\n         beta(RT1 a, RT2 b, A x); // Beta function (3 arguments).\n\n   template <class RT1, class RT2, class RT3, class Policy>\n   typename tools::promote_args<RT1, RT2, RT3>::type\n         beta(RT1 a, RT2 b, RT3 x, const Policy& pol); // Beta function (3 arguments).\n\n   template <class RT1, class RT2, class RT3>\n   typename tools::promote_args<RT1, RT2, RT3>::type\n         betac(RT1 a, RT2 b, RT3 x);\n\n   template <class RT1, class RT2, class RT3, class Policy>\n   typename tools::promote_args<RT1, RT2, RT3>::type\n         betac(RT1 a, RT2 b, RT3 x, const Policy& pol);\n\n   template <class RT1, class RT2, class RT3>\n   typename tools::promote_args<RT1, RT2, RT3>::type\n         ibeta(RT1 a, RT2 b, RT3 x); // Incomplete beta function.\n\n   template <class RT1, class RT2, class RT3, class Policy>\n   typename tools::promote_args<RT1, RT2, RT3>::type\n         ibeta(RT1 a, RT2 b, RT3 x, const Policy& pol); // Incomplete beta function.\n\n   template <class RT1, class RT2, class RT3>\n   typename tools::promote_args<RT1, RT2, RT3>::type\n         ibetac(RT1 a, RT2 b, RT3 x); // Incomplete beta complement function.\n\n   template <class RT1, class RT2, class RT3, class Policy>\n   typename tools::promote_args<RT1, RT2, RT3>::type\n         ibetac(RT1 a, RT2 b, RT3 x, const Policy& pol); // Incomplete beta complement function.\n\n   template <class T1, class T2, class T3, class T4>\n   typename tools::promote_args<T1, T2, T3, T4>::type\n         ibeta_inv(T1 a, T2 b, T3 p, T4* py);\n\n   template <class T1, class T2, class T3, class T4, class Policy>\n   typename tools::promote_args<T1, T2, T3, T4>::type\n         ibeta_inv(T1 a, T2 b, T3 p, T4* py, const Policy& pol);\n\n   template <class RT1, class RT2, class RT3>\n   typename tools::promote_args<RT1, RT2, RT3>::type\n         ibeta_inv(RT1 a, RT2 b, RT3 p); // Incomplete beta inverse function.\n\n   template <class RT1, class RT2, class RT3, class Policy>\n   typename tools::promote_args<RT1, RT2, RT3>::type\n         ibeta_inv(RT1 a, RT2 b, RT3 p, const Policy&); // Incomplete beta inverse function.\n\n   template <class RT1, class RT2, class RT3>\n   typename tools::promote_args<RT1, RT2, RT3>::type\n         ibeta_inva(RT1 a, RT2 b, RT3 p); // Incomplete beta inverse function.\n\n   template <class RT1, class RT2, class RT3, class Policy>\n   typename tools::promote_args<RT1, RT2, RT3>::type\n         ibeta_inva(RT1 a, RT2 b, RT3 p, const Policy&); // Incomplete beta inverse function.\n\n   template <class RT1, class RT2, class RT3>\n   typename tools::promote_args<RT1, RT2, RT3>::type\n         ibeta_invb(RT1 a, RT2 b, RT3 p); // Incomplete beta inverse function.\n\n   template <class RT1, class RT2, class RT3, class Policy>\n   typename tools::promote_args<RT1, RT2, RT3>::type\n         ibeta_invb(RT1 a, RT2 b, RT3 p, const Policy&); // Incomplete beta inverse function.\n\n   template <class T1, class T2, class T3, class T4>\n   typename tools::promote_args<T1, T2, T3, T4>::type\n         ibetac_inv(T1 a, T2 b, T3 q, T4* py);\n\n   template <class T1, class T2, class T3, class T4, class Policy>\n   typename tools::promote_args<T1, T2, T3, T4>::type\n         ibetac_inv(T1 a, T2 b, T3 q, T4* py, const Policy& pol);\n\n   template <class RT1, class RT2, class RT3>\n   typename tools::promote_args<RT1, RT2, RT3>::type\n         ibetac_inv(RT1 a, RT2 b, RT3 q); // Incomplete beta complement inverse function.\n\n   template <class RT1, class RT2, class RT3, class Policy>\n   typename tools::promote_args<RT1, RT2, RT3>::type\n         ibetac_inv(RT1 a, RT2 b, RT3 q, const Policy&); // Incomplete beta complement inverse function.\n\n   template <class RT1, class RT2, class RT3>\n   typename tools::promote_args<RT1, RT2, RT3>::type\n         ibetac_inva(RT1 a, RT2 b, RT3 q); // Incomplete beta complement inverse function.\n\n   template <class RT1, class RT2, class RT3, class Policy>\n   typename tools::promote_args<RT1, RT2, RT3>::type\n         ibetac_inva(RT1 a, RT2 b, RT3 q, const Policy&); // Incomplete beta complement inverse function.\n\n   template <class RT1, class RT2, class RT3>\n   typename tools::promote_args<RT1, RT2, RT3>::type\n         ibetac_invb(RT1 a, RT2 b, RT3 q); // Incomplete beta complement inverse function.\n\n   template <class RT1, class RT2, class RT3, class Policy>\n   typename tools::promote_args<RT1, RT2, RT3>::type\n         ibetac_invb(RT1 a, RT2 b, RT3 q, const Policy&); // Incomplete beta complement inverse function.\n\n   template <class RT1, class RT2, class RT3>\n   typename tools::promote_args<RT1, RT2, RT3>::type\n         ibeta_derivative(RT1 a, RT2 b, RT3 x);  // derivative of incomplete beta\n\n   template <class RT1, class RT2, class RT3, class Policy>\n   typename tools::promote_args<RT1, RT2, RT3>::type\n         ibeta_derivative(RT1 a, RT2 b, RT3 x, const Policy& pol);  // derivative of incomplete beta\n\n   // Binomial:\n   template <class T, class Policy>\n   T binomial_coefficient(unsigned n, unsigned k, const Policy& pol);\n   template <class T>\n   T binomial_coefficient(unsigned n, unsigned k);\n\n   // erf & erfc error functions.\n   template <class RT> // Error function.\n   typename tools::promote_args<RT>::type erf(RT z);\n   template <class RT, class Policy> // Error function.\n   typename tools::promote_args<RT>::type erf(RT z, const Policy&);\n\n   template <class RT>// Error function complement.\n   typename tools::promote_args<RT>::type erfc(RT z);\n   template <class RT, class Policy>// Error function complement.\n   typename tools::promote_args<RT>::type erfc(RT z, const Policy&);\n\n   template <class RT>// Error function inverse.\n   typename tools::promote_args<RT>::type erf_inv(RT z);\n   template <class RT, class Policy>// Error function inverse.\n   typename tools::promote_args<RT>::type erf_inv(RT z, const Policy& pol);\n\n   template <class RT>// Error function complement inverse.\n   typename tools::promote_args<RT>::type erfc_inv(RT z);\n   template <class RT, class Policy>// Error function complement inverse.\n   typename tools::promote_args<RT>::type erfc_inv(RT z, const Policy& pol);\n\n   // Polynomials:\n   template <class T1, class T2, class T3>\n   typename tools::promote_args<T1, T2, T3>::type\n         legendre_next(unsigned l, T1 x, T2 Pl, T3 Plm1);\n\n   template <class T>\n   typename tools::promote_args<T>::type\n         legendre_p(int l, T x);\n   template <class T>\n   typename tools::promote_args<T>::type\n          legendre_p_prime(int l, T x);\n\n\n   template <class T, class Policy>\n   inline std::vector<T> legendre_p_zeros(int l, const Policy& pol);\n\n   template <class T>\n   inline std::vector<T> legendre_p_zeros(int l);\n\n#if !BOOST_WORKAROUND(BOOST_MSVC, <= 1310)\n   template <class T, class Policy>\n   typename boost::enable_if_c<policies::is_policy<Policy>::value, typename tools::promote_args<T>::type>::type\n         legendre_p(int l, T x, const Policy& pol);\n   template <class T, class Policy>\n   inline typename boost::enable_if_c<policies::is_policy<Policy>::value, typename tools::promote_args<T>::type>::type\n      legendre_p_prime(int l, T x, const Policy& pol);\n#endif\n   template <class T>\n   typename tools::promote_args<T>::type\n         legendre_q(unsigned l, T x);\n#if !BOOST_WORKAROUND(BOOST_MSVC, <= 1310)\n   template <class T, class Policy>\n   typename boost::enable_if_c<policies::is_policy<Policy>::value, typename tools::promote_args<T>::type>::type\n         legendre_q(unsigned l, T x, const Policy& pol);\n#endif\n   template <class T1, class T2, class T3>\n   typename tools::promote_args<T1, T2, T3>::type\n         legendre_next(unsigned l, unsigned m, T1 x, T2 Pl, T3 Plm1);\n\n   template <class T>\n   typename tools::promote_args<T>::type\n         legendre_p(int l, int m, T x);\n\n   template <class T, class Policy>\n   typename tools::promote_args<T>::type\n         legendre_p(int l, int m, T x, const Policy& pol);\n\n   template <class T1, class T2, class T3>\n   typename tools::promote_args<T1, T2, T3>::type\n         laguerre_next(unsigned n, T1 x, T2 Ln, T3 Lnm1);\n\n   template <class T1, class T2, class T3>\n   typename tools::promote_args<T1, T2, T3>::type\n      laguerre_next(unsigned n, unsigned l, T1 x, T2 Pl, T3 Plm1);\n\n   template <class T>\n   typename tools::promote_args<T>::type\n      laguerre(unsigned n, T x);\n\n   template <class T, class Policy>\n   typename tools::promote_args<T>::type\n      laguerre(unsigned n, unsigned m, T x, const Policy& pol);\n\n   template <class T1, class T2>\n   struct laguerre_result\n   {\n      typedef typename mpl::if_<\n         policies::is_policy<T2>,\n         typename tools::promote_args<T1>::type,\n         typename tools::promote_args<T2>::type\n      >::type type;\n   };\n\n   template <class T1, class T2>\n   typename laguerre_result<T1, T2>::type\n      laguerre(unsigned n, T1 m, T2 x);\n\n   template <class T>\n   typename tools::promote_args<T>::type\n      hermite(unsigned n, T x);\n\n   template <class T, class Policy>\n   typename tools::promote_args<T>::type\n      hermite(unsigned n, T x, const Policy& pol);\n\n   template <class T1, class T2, class T3>\n   typename tools::promote_args<T1, T2, T3>::type\n      hermite_next(unsigned n, T1 x, T2 Hn, T3 Hnm1);\n\n   template<class T1, class T2, class T3>\n   typename tools::promote_args<T1, T2, T3>::type chebyshev_next(T1 const & x, T2 const & Tn, T3 const & Tn_1);\n\n   template <class Real, class Policy>\n   typename tools::promote_args<Real>::type\n      chebyshev_t(unsigned n, Real const & x, const Policy&);\n   template<class Real>\n   typename tools::promote_args<Real>::type chebyshev_t(unsigned n, Real const & x);\n   \n   template <class Real, class Policy>\n   typename tools::promote_args<Real>::type\n      chebyshev_u(unsigned n, Real const & x, const Policy&);\n   template<class Real>\n   typename tools::promote_args<Real>::type chebyshev_u(unsigned n, Real const & x);\n\n   template <class Real, class Policy>\n   typename tools::promote_args<Real>::type\n      chebyshev_t_prime(unsigned n, Real const & x, const Policy&);\n   template<class Real>\n   typename tools::promote_args<Real>::type chebyshev_t_prime(unsigned n, Real const & x);\n\n   template<class Real, class T2>\n   Real chebyshev_clenshaw_recurrence(const Real* const c, size_t length, const T2& x);\n\n   template <class T1, class T2>\n   std::complex<typename tools::promote_args<T1, T2>::type>\n         spherical_harmonic(unsigned n, int m, T1 theta, T2 phi);\n\n   template <class T1, class T2, class Policy>\n   std::complex<typename tools::promote_args<T1, T2>::type>\n      spherical_harmonic(unsigned n, int m, T1 theta, T2 phi, const Policy& pol);\n\n   template <class T1, class T2>\n   typename tools::promote_args<T1, T2>::type\n         spherical_harmonic_r(unsigned n, int m, T1 theta, T2 phi);\n\n   template <class T1, class T2, class Policy>\n   typename tools::promote_args<T1, T2>::type\n      spherical_harmonic_r(unsigned n, int m, T1 theta, T2 phi, const Policy& pol);\n\n   template <class T1, class T2>\n   typename tools::promote_args<T1, T2>::type\n         spherical_harmonic_i(unsigned n, int m, T1 theta, T2 phi);\n\n   template <class T1, class T2, class Policy>\n   typename tools::promote_args<T1, T2>::type\n      spherical_harmonic_i(unsigned n, int m, T1 theta, T2 phi, const Policy& pol);\n\n   // Elliptic integrals:\n   template <class T1, class T2, class T3>\n   typename tools::promote_args<T1, T2, T3>::type\n         ellint_rf(T1 x, T2 y, T3 z);\n\n   template <class T1, class T2, class T3, class Policy>\n   typename tools::promote_args<T1, T2, T3>::type\n         ellint_rf(T1 x, T2 y, T3 z, const Policy& pol);\n\n   template <class T1, class T2, class T3>\n   typename tools::promote_args<T1, T2, T3>::type\n         ellint_rd(T1 x, T2 y, T3 z);\n\n   template <class T1, class T2, class T3, class Policy>\n   typename tools::promote_args<T1, T2, T3>::type\n         ellint_rd(T1 x, T2 y, T3 z, const Policy& pol);\n\n   template <class T1, class T2>\n   typename tools::promote_args<T1, T2>::type\n         ellint_rc(T1 x, T2 y);\n\n   template <class T1, class T2, class Policy>\n   typename tools::promote_args<T1, T2>::type\n         ellint_rc(T1 x, T2 y, const Policy& pol);\n\n   template <class T1, class T2, class T3, class T4>\n   typename tools::promote_args<T1, T2, T3, T4>::type\n         ellint_rj(T1 x, T2 y, T3 z, T4 p);\n\n   template <class T1, class T2, class T3, class T4, class Policy>\n   typename tools::promote_args<T1, T2, T3, T4>::type\n         ellint_rj(T1 x, T2 y, T3 z, T4 p, const Policy& pol);\n\n   template <class T1, class T2, class T3>\n   typename tools::promote_args<T1, T2, T3>::type\n      ellint_rg(T1 x, T2 y, T3 z);\n\n   template <class T1, class T2, class T3, class Policy>\n   typename tools::promote_args<T1, T2, T3>::type\n      ellint_rg(T1 x, T2 y, T3 z, const Policy& pol);\n\n   template <typename T>\n   typename tools::promote_args<T>::type ellint_2(T k);\n\n   template <class T1, class T2>\n   typename tools::promote_args<T1, T2>::type ellint_2(T1 k, T2 phi);\n\n   template <class T1, class T2, class Policy>\n   typename tools::promote_args<T1, T2>::type ellint_2(T1 k, T2 phi, const Policy& pol);\n\n   template <typename T>\n   typename tools::promote_args<T>::type ellint_1(T k);\n\n   template <class T1, class T2>\n   typename tools::promote_args<T1, T2>::type ellint_1(T1 k, T2 phi);\n\n   template <class T1, class T2, class Policy>\n   typename tools::promote_args<T1, T2>::type ellint_1(T1 k, T2 phi, const Policy& pol);\n\n   template <typename T>\n   typename tools::promote_args<T>::type ellint_d(T k);\n\n   template <class T1, class T2>\n   typename tools::promote_args<T1, T2>::type ellint_d(T1 k, T2 phi);\n\n   template <class T1, class T2, class Policy>\n   typename tools::promote_args<T1, T2>::type ellint_d(T1 k, T2 phi, const Policy& pol);\n\n   template <class T1, class T2>\n   typename tools::promote_args<T1, T2>::type jacobi_zeta(T1 k, T2 phi);\n\n   template <class T1, class T2, class Policy>\n   typename tools::promote_args<T1, T2>::type jacobi_zeta(T1 k, T2 phi, const Policy& pol);\n\n   template <class T1, class T2>\n   typename tools::promote_args<T1, T2>::type heuman_lambda(T1 k, T2 phi);\n\n   template <class T1, class T2, class Policy>\n   typename tools::promote_args<T1, T2>::type heuman_lambda(T1 k, T2 phi, const Policy& pol);\n\n   namespace detail{\n\n   template <class T, class U, class V>\n   struct ellint_3_result\n   {\n      typedef typename mpl::if_<\n         policies::is_policy<V>,\n         typename tools::promote_args<T, U>::type,\n         typename tools::promote_args<T, U, V>::type\n      >::type type;\n   };\n\n   } // namespace detail\n\n\n   template <class T1, class T2, class T3>\n   typename detail::ellint_3_result<T1, T2, T3>::type ellint_3(T1 k, T2 v, T3 phi);\n\n   template <class T1, class T2, class T3, class Policy>\n   typename tools::promote_args<T1, T2, T3>::type ellint_3(T1 k, T2 v, T3 phi, const Policy& pol);\n\n   template <class T1, class T2>\n   typename tools::promote_args<T1, T2>::type ellint_3(T1 k, T2 v);\n\n   // Factorial functions.\n   // Note: not for integral types, at present.\n   template <class RT>\n   struct max_factorial;\n   template <class RT>\n   RT factorial(unsigned int);\n   template <class RT, class Policy>\n   RT factorial(unsigned int, const Policy& pol);\n   template <class RT>\n   RT unchecked_factorial(unsigned int BOOST_MATH_APPEND_EXPLICIT_TEMPLATE_TYPE(RT));\n   template <class RT>\n   RT double_factorial(unsigned i);\n   template <class RT, class Policy>\n   RT double_factorial(unsigned i, const Policy& pol);\n\n   template <class RT>\n   typename tools::promote_args<RT>::type falling_factorial(RT x, unsigned n);\n\n   template <class RT, class Policy>\n   typename tools::promote_args<RT>::type falling_factorial(RT x, unsigned n, const Policy& pol);\n\n   template <class RT>\n   typename tools::promote_args<RT>::type rising_factorial(RT x, int n);\n\n   template <class RT, class Policy>\n   typename tools::promote_args<RT>::type rising_factorial(RT x, int n, const Policy& pol);\n\n   // Gamma functions.\n   template <class RT>\n   typename tools::promote_args<RT>::type tgamma(RT z);\n\n   template <class RT>\n   typename tools::promote_args<RT>::type tgamma1pm1(RT z);\n\n   template <class RT, class Policy>\n   typename tools::promote_args<RT>::type tgamma1pm1(RT z, const Policy& pol);\n\n   template <class RT1, class RT2>\n   typename tools::promote_args<RT1, RT2>::type tgamma(RT1 a, RT2 z);\n\n   template <class RT1, class RT2, class Policy>\n   typename tools::promote_args<RT1, RT2>::type tgamma(RT1 a, RT2 z, const Policy& pol);\n\n   template <class RT>\n   typename tools::promote_args<RT>::type lgamma(RT z, int* sign);\n\n   template <class RT, class Policy>\n   typename tools::promote_args<RT>::type lgamma(RT z, int* sign, const Policy& pol);\n\n   template <class RT>\n   typename tools::promote_args<RT>::type lgamma(RT x);\n\n   template <class RT, class Policy>\n   typename tools::promote_args<RT>::type lgamma(RT x, const Policy& pol);\n\n   template <class RT1, class RT2>\n   typename tools::promote_args<RT1, RT2>::type tgamma_lower(RT1 a, RT2 z);\n\n   template <class RT1, class RT2, class Policy>\n   typename tools::promote_args<RT1, RT2>::type tgamma_lower(RT1 a, RT2 z, const Policy&);\n\n   template <class RT1, class RT2>\n   typename tools::promote_args<RT1, RT2>::type gamma_q(RT1 a, RT2 z);\n\n   template <class RT1, class RT2, class Policy>\n   typename tools::promote_args<RT1, RT2>::type gamma_q(RT1 a, RT2 z, const Policy&);\n\n   template <class RT1, class RT2>\n   typename tools::promote_args<RT1, RT2>::type gamma_p(RT1 a, RT2 z);\n\n   template <class RT1, class RT2, class Policy>\n   typename tools::promote_args<RT1, RT2>::type gamma_p(RT1 a, RT2 z, const Policy&);\n\n   template <class T1, class T2>\n   typename tools::promote_args<T1, T2>::type tgamma_delta_ratio(T1 z, T2 delta);\n\n   template <class T1, class T2, class Policy>\n   typename tools::promote_args<T1, T2>::type tgamma_delta_ratio(T1 z, T2 delta, const Policy&);\n\n   template <class T1, class T2>\n   typename tools::promote_args<T1, T2>::type tgamma_ratio(T1 a, T2 b);\n\n   template <class T1, class T2, class Policy>\n   typename tools::promote_args<T1, T2>::type tgamma_ratio(T1 a, T2 b, const Policy&);\n\n   template <class T1, class T2>\n   typename tools::promote_args<T1, T2>::type gamma_p_derivative(T1 a, T2 x);\n\n   template <class T1, class T2, class Policy>\n   typename tools::promote_args<T1, T2>::type gamma_p_derivative(T1 a, T2 x, const Policy&);\n\n   // gamma inverse.\n   template <class T1, class T2>\n   typename tools::promote_args<T1, T2>::type gamma_p_inv(T1 a, T2 p);\n\n   template <class T1, class T2, class Policy>\n   typename tools::promote_args<T1, T2>::type gamma_p_inva(T1 a, T2 p, const Policy&);\n\n   template <class T1, class T2>\n   typename tools::promote_args<T1, T2>::type gamma_p_inva(T1 a, T2 p);\n\n   template <class T1, class T2, class Policy>\n   typename tools::promote_args<T1, T2>::type gamma_p_inv(T1 a, T2 p, const Policy&);\n\n   template <class T1, class T2>\n   typename tools::promote_args<T1, T2>::type gamma_q_inv(T1 a, T2 q);\n\n   template <class T1, class T2, class Policy>\n   typename tools::promote_args<T1, T2>::type gamma_q_inv(T1 a, T2 q, const Policy&);\n\n   template <class T1, class T2>\n   typename tools::promote_args<T1, T2>::type gamma_q_inva(T1 a, T2 q);\n\n   template <class T1, class T2, class Policy>\n   typename tools::promote_args<T1, T2>::type gamma_q_inva(T1 a, T2 q, const Policy&);\n\n   // digamma:\n   template <class T>\n   typename tools::promote_args<T>::type digamma(T x);\n\n   template <class T, class Policy>\n   typename tools::promote_args<T>::type digamma(T x, const Policy&);\n\n   // trigamma:\n   template <class T>\n   typename tools::promote_args<T>::type trigamma(T x);\n\n   template <class T, class Policy>\n   typename tools::promote_args<T>::type trigamma(T x, const Policy&);\n\n   // polygamma:\n   template <class T>\n   typename tools::promote_args<T>::type polygamma(int n, T x);\n\n   template <class T, class Policy>\n   typename tools::promote_args<T>::type polygamma(int n, T x, const Policy&);\n\n   // Hypotenuse function sqrt(x ^ 2 + y ^ 2).\n   template <class T1, class T2>\n   typename tools::promote_args<T1, T2>::type\n         hypot(T1 x, T2 y);\n\n   template <class T1, class T2, class Policy>\n   typename tools::promote_args<T1, T2>::type\n         hypot(T1 x, T2 y, const Policy&);\n\n   // cbrt - cube root.\n   template <class RT>\n   typename tools::promote_args<RT>::type cbrt(RT z);\n\n   template <class RT, class Policy>\n   typename tools::promote_args<RT>::type cbrt(RT z, const Policy&);\n\n   // log1p is log(x + 1)\n   template <class T>\n   typename tools::promote_args<T>::type log1p(T);\n\n   template <class T, class Policy>\n   typename tools::promote_args<T>::type log1p(T, const Policy&);\n\n   // log1pmx is log(x + 1) - x\n   template <class T>\n   typename tools::promote_args<T>::type log1pmx(T);\n\n   template <class T, class Policy>\n   typename tools::promote_args<T>::type log1pmx(T, const Policy&);\n\n   // Exp (x) minus 1 functions.\n   template <class T>\n   typename tools::promote_args<T>::type expm1(T);\n\n   template <class T, class Policy>\n   typename tools::promote_args<T>::type expm1(T, const Policy&);\n\n   // Power - 1\n   template <class T1, class T2>\n   typename tools::promote_args<T1, T2>::type\n         powm1(const T1 a, const T2 z);\n\n   template <class T1, class T2, class Policy>\n   typename tools::promote_args<T1, T2>::type\n         powm1(const T1 a, const T2 z, const Policy&);\n\n   // sqrt(1+x) - 1\n   template <class T>\n   typename tools::promote_args<T>::type sqrt1pm1(const T& val);\n\n   template <class T, class Policy>\n   typename tools::promote_args<T>::type sqrt1pm1(const T& val, const Policy&);\n\n   // sinus cardinals:\n   template <class T>\n   typename tools::promote_args<T>::type sinc_pi(T x);\n\n   template <class T, class Policy>\n   typename tools::promote_args<T>::type sinc_pi(T x, const Policy&);\n\n   template <class T>\n   typename tools::promote_args<T>::type sinhc_pi(T x);\n\n   template <class T, class Policy>\n   typename tools::promote_args<T>::type sinhc_pi(T x, const Policy&);\n\n   // inverse hyperbolics:\n   template<typename T>\n   typename tools::promote_args<T>::type asinh(T x);\n\n   template<typename T, class Policy>\n   typename tools::promote_args<T>::type asinh(T x, const Policy&);\n\n   template<typename T>\n   typename tools::promote_args<T>::type acosh(T x);\n\n   template<typename T, class Policy>\n   typename tools::promote_args<T>::type acosh(T x, const Policy&);\n\n   template<typename T>\n   typename tools::promote_args<T>::type atanh(T x);\n\n   template<typename T, class Policy>\n   typename tools::promote_args<T>::type atanh(T x, const Policy&);\n\n   namespace detail{\n\n      typedef mpl::int_<0> bessel_no_int_tag;      // No integer optimisation possible.\n      typedef mpl::int_<1> bessel_maybe_int_tag;   // Maybe integer optimisation.\n      typedef mpl::int_<2> bessel_int_tag;         // Definite integer optimistaion.\n\n      template <class T1, class T2, class Policy>\n      struct bessel_traits\n      {\n         typedef typename mpl::if_<\n            is_integral<T1>,\n            typename tools::promote_args<T2>::type,\n            typename tools::promote_args<T1, T2>::type\n         >::type result_type;\n\n         typedef typename policies::precision<result_type, Policy>::type precision_type;\n\n         typedef typename mpl::if_<\n            mpl::or_<\n               mpl::less_equal<precision_type, mpl::int_<0> >,\n               mpl::greater<precision_type, mpl::int_<64> > >,\n            bessel_no_int_tag,\n            typename mpl::if_<\n               is_integral<T1>,\n               bessel_int_tag,\n               bessel_maybe_int_tag\n            >::type\n         >::type optimisation_tag;\n         typedef typename mpl::if_<\n            mpl::or_<\n               mpl::less_equal<precision_type, mpl::int_<0> >,\n               mpl::greater<precision_type, mpl::int_<113> > >,\n            bessel_no_int_tag,\n            typename mpl::if_<\n               is_integral<T1>,\n               bessel_int_tag,\n               bessel_maybe_int_tag\n            >::type\n         >::type optimisation_tag128;\n      };\n   } // detail\n\n   // Bessel functions:\n   template <class T1, class T2, class Policy>\n   typename detail::bessel_traits<T1, T2, Policy>::result_type cyl_bessel_j(T1 v, T2 x, const Policy& pol);\n   template <class T1, class T2, class Policy>\n   typename detail::bessel_traits<T1, T2, Policy>::result_type cyl_bessel_j_prime(T1 v, T2 x, const Policy& pol);\n\n   template <class T1, class T2>\n   typename detail::bessel_traits<T1, T2, policies::policy<> >::result_type cyl_bessel_j(T1 v, T2 x);\n   template <class T1, class T2>\n   typename detail::bessel_traits<T1, T2, policies::policy<> >::result_type cyl_bessel_j_prime(T1 v, T2 x);\n\n   template <class T, class Policy>\n   typename detail::bessel_traits<T, T, Policy>::result_type sph_bessel(unsigned v, T x, const Policy& pol);\n   template <class T, class Policy>\n   typename detail::bessel_traits<T, T, Policy>::result_type sph_bessel_prime(unsigned v, T x, const Policy& pol);\n\n   template <class T>\n   typename detail::bessel_traits<T, T, policies::policy<> >::result_type sph_bessel(unsigned v, T x);\n   template <class T>\n   typename detail::bessel_traits<T, T, policies::policy<> >::result_type sph_bessel_prime(unsigned v, T x);\n\n   template <class T1, class T2, class Policy>\n   typename detail::bessel_traits<T1, T2, Policy>::result_type cyl_bessel_i(T1 v, T2 x, const Policy& pol);\n   template <class T1, class T2, class Policy>\n   typename detail::bessel_traits<T1, T2, Policy>::result_type cyl_bessel_i_prime(T1 v, T2 x, const Policy& pol);\n\n   template <class T1, class T2>\n   typename detail::bessel_traits<T1, T2, policies::policy<> >::result_type cyl_bessel_i(T1 v, T2 x);\n   template <class T1, class T2>\n   typename detail::bessel_traits<T1, T2, policies::policy<> >::result_type cyl_bessel_i_prime(T1 v, T2 x);\n\n   template <class T1, class T2, class Policy>\n   typename detail::bessel_traits<T1, T2, Policy>::result_type cyl_bessel_k(T1 v, T2 x, const Policy& pol);\n   template <class T1, class T2, class Policy>\n   typename detail::bessel_traits<T1, T2, Policy>::result_type cyl_bessel_k_prime(T1 v, T2 x, const Policy& pol);\n\n   template <class T1, class T2>\n   typename detail::bessel_traits<T1, T2, policies::policy<> >::result_type cyl_bessel_k(T1 v, T2 x);\n   template <class T1, class T2>\n   typename detail::bessel_traits<T1, T2, policies::policy<> >::result_type cyl_bessel_k_prime(T1 v, T2 x);\n\n   template <class T1, class T2, class Policy>\n   typename detail::bessel_traits<T1, T2, Policy>::result_type cyl_neumann(T1 v, T2 x, const Policy& pol);\n   template <class T1, class T2, class Policy>\n   typename detail::bessel_traits<T1, T2, Policy>::result_type cyl_neumann_prime(T1 v, T2 x, const Policy& pol);\n\n   template <class T1, class T2>\n   typename detail::bessel_traits<T1, T2, policies::policy<> >::result_type cyl_neumann(T1 v, T2 x);\n   template <class T1, class T2>\n   typename detail::bessel_traits<T1, T2, policies::policy<> >::result_type cyl_neumann_prime(T1 v, T2 x);\n\n   template <class T, class Policy>\n   typename detail::bessel_traits<T, T, Policy>::result_type sph_neumann(unsigned v, T x, const Policy& pol);\n   template <class T, class Policy>\n   typename detail::bessel_traits<T, T, Policy>::result_type sph_neumann_prime(unsigned v, T x, const Policy& pol);\n\n   template <class T>\n   typename detail::bessel_traits<T, T, policies::policy<> >::result_type sph_neumann(unsigned v, T x);\n   template <class T>\n   typename detail::bessel_traits<T, T, policies::policy<> >::result_type sph_neumann_prime(unsigned v, T x);\n\n   template <class T, class Policy>\n   typename detail::bessel_traits<T, T, Policy>::result_type cyl_bessel_j_zero(T v, int m, const Policy& pol);\n\n   template <class T>\n   typename detail::bessel_traits<T, T, policies::policy<> >::result_type cyl_bessel_j_zero(T v, int m);\n\n   template <class T, class OutputIterator>\n   OutputIterator cyl_bessel_j_zero(T v,\n                          int start_index,\n                          unsigned number_of_zeros,\n                          OutputIterator out_it);\n\n   template <class T, class OutputIterator, class Policy>\n   OutputIterator cyl_bessel_j_zero(T v,\n                          int start_index,\n                          unsigned number_of_zeros,\n                          OutputIterator out_it,\n                          const Policy&);\n\n   template <class T, class Policy>\n   typename detail::bessel_traits<T, T, Policy>::result_type cyl_neumann_zero(T v, int m, const Policy& pol);\n\n   template <class T>\n   typename detail::bessel_traits<T, T, policies::policy<> >::result_type cyl_neumann_zero(T v, int m);\n\n   template <class T, class OutputIterator>\n   OutputIterator cyl_neumann_zero(T v,\n                         int start_index,\n                         unsigned number_of_zeros,\n                         OutputIterator out_it);\n\n   template <class T, class OutputIterator, class Policy>\n   OutputIterator cyl_neumann_zero(T v,\n                         int start_index,\n                         unsigned number_of_zeros,\n                         OutputIterator out_it,\n                         const Policy&);\n\n   template <class T1, class T2>\n   std::complex<typename detail::bessel_traits<T1, T2, policies::policy<> >::result_type> cyl_hankel_1(T1 v, T2 x);\n\n   template <class T1, class T2, class Policy>\n   std::complex<typename detail::bessel_traits<T1, T2, Policy>::result_type> cyl_hankel_1(T1 v, T2 x, const Policy& pol);\n\n   template <class T1, class T2, class Policy>\n   std::complex<typename detail::bessel_traits<T1, T2, Policy>::result_type> cyl_hankel_2(T1 v, T2 x, const Policy& pol);\n\n   template <class T1, class T2>\n   std::complex<typename detail::bessel_traits<T1, T2, policies::policy<> >::result_type> cyl_hankel_2(T1 v, T2 x);\n\n   template <class T1, class T2, class Policy>\n   std::complex<typename detail::bessel_traits<T1, T2, Policy>::result_type> sph_hankel_1(T1 v, T2 x, const Policy& pol);\n\n   template <class T1, class T2>\n   std::complex<typename detail::bessel_traits<T1, T2, policies::policy<> >::result_type> sph_hankel_1(T1 v, T2 x);\n\n   template <class T1, class T2, class Policy>\n   std::complex<typename detail::bessel_traits<T1, T2, Policy>::result_type> sph_hankel_2(T1 v, T2 x, const Policy& pol);\n\n   template <class T1, class T2>\n   std::complex<typename detail::bessel_traits<T1, T2, policies::policy<> >::result_type> sph_hankel_2(T1 v, T2 x);\n\n   template <class T, class Policy>\n   typename tools::promote_args<T>::type airy_ai(T x, const Policy&);\n\n   template <class T>\n   typename tools::promote_args<T>::type airy_ai(T x);\n\n   template <class T, class Policy>\n   typename tools::promote_args<T>::type airy_bi(T x, const Policy&);\n\n   template <class T>\n   typename tools::promote_args<T>::type airy_bi(T x);\n\n   template <class T, class Policy>\n   typename tools::promote_args<T>::type airy_ai_prime(T x, const Policy&);\n\n   template <class T>\n   typename tools::promote_args<T>::type airy_ai_prime(T x);\n\n   template <class T, class Policy>\n   typename tools::promote_args<T>::type airy_bi_prime(T x, const Policy&);\n\n   template <class T>\n   typename tools::promote_args<T>::type airy_bi_prime(T x);\n\n   template <class T>\n   T airy_ai_zero(int m);\n   template <class T, class Policy>\n   T airy_ai_zero(int m, const Policy&);\n\n   template <class OutputIterator>\n   OutputIterator airy_ai_zero(\n                     int start_index,\n                     unsigned number_of_zeros,\n                     OutputIterator out_it);\n   template <class OutputIterator, class Policy>\n   OutputIterator airy_ai_zero(\n                     int start_index,\n                     unsigned number_of_zeros,\n                     OutputIterator out_it,\n                     const Policy&);\n\n   template <class T>\n   T airy_bi_zero(int m);\n   template <class T, class Policy>\n   T airy_bi_zero(int m, const Policy&);\n\n   template <class OutputIterator>\n   OutputIterator airy_bi_zero(\n                     int start_index,\n                     unsigned number_of_zeros,\n                     OutputIterator out_it);\n   template <class OutputIterator, class Policy>\n   OutputIterator airy_bi_zero(\n                     int start_index,\n                     unsigned number_of_zeros,\n                     OutputIterator out_it,\n                     const Policy&);\n\n   template <class T, class Policy>\n   typename tools::promote_args<T>::type sin_pi(T x, const Policy&);\n\n   template <class T>\n   typename tools::promote_args<T>::type sin_pi(T x);\n\n   template <class T, class Policy>\n   typename tools::promote_args<T>::type cos_pi(T x, const Policy&);\n\n   template <class T>\n   typename tools::promote_args<T>::type cos_pi(T x);\n\n   template <class T>\n   int fpclassify BOOST_NO_MACRO_EXPAND(T t);\n\n   template <class T>\n   bool isfinite BOOST_NO_MACRO_EXPAND(T z);\n\n   template <class T>\n   bool isinf BOOST_NO_MACRO_EXPAND(T t);\n\n   template <class T>\n   bool isnan BOOST_NO_MACRO_EXPAND(T t);\n\n   template <class T>\n   bool isnormal BOOST_NO_MACRO_EXPAND(T t);\n\n   template<class T>\n   int signbit BOOST_NO_MACRO_EXPAND(T x);\n\n   template <class T>\n   int sign BOOST_NO_MACRO_EXPAND(const T& z);\n\n   template <class T, class U>\n   typename tools::promote_args_permissive<T, U>::type copysign BOOST_NO_MACRO_EXPAND(const T& x, const U& y);\n\n   template <class T>\n   typename tools::promote_args_permissive<T>::type changesign BOOST_NO_MACRO_EXPAND(const T& z);\n\n   // Exponential integrals:\n   namespace detail{\n\n   template <class T, class U>\n   struct expint_result\n   {\n      typedef typename mpl::if_<\n         policies::is_policy<U>,\n         typename tools::promote_args<T>::type,\n         typename tools::promote_args<U>::type\n      >::type type;\n   };\n\n   } // namespace detail\n\n   template <class T, class Policy>\n   typename tools::promote_args<T>::type expint(unsigned n, T z, const Policy&);\n\n   template <class T, class U>\n   typename detail::expint_result<T, U>::type expint(T const z, U const u);\n\n   template <class T>\n   typename tools::promote_args<T>::type expint(T z);\n\n   // Zeta:\n   template <class T, class Policy>\n   typename tools::promote_args<T>::type zeta(T s, const Policy&);\n\n   // Owen's T function:\n   template <class T1, class T2, class Policy>\n   typename tools::promote_args<T1, T2>::type owens_t(T1 h, T2 a, const Policy& pol);\n\n   template <class T1, class T2>\n   typename tools::promote_args<T1, T2>::type owens_t(T1 h, T2 a);\n\n   // Jacobi Functions:\n   template <class T, class U, class V, class Policy>\n   typename tools::promote_args<T, U, V>::type jacobi_elliptic(T k, U theta, V* pcn, V* pdn, const Policy&);\n\n   template <class T, class U, class V>\n   typename tools::promote_args<T, U, V>::type jacobi_elliptic(T k, U theta, V* pcn = 0, V* pdn = 0);\n\n   template <class U, class T, class Policy>\n   typename tools::promote_args<T, U>::type jacobi_sn(U k, T theta, const Policy& pol);\n\n   template <class U, class T>\n   typename tools::promote_args<T, U>::type jacobi_sn(U k, T theta);\n\n   template <class T, class U, class Policy>\n   typename tools::promote_args<T, U>::type jacobi_cn(T k, U theta, const Policy& pol);\n\n   template <class T, class U>\n   typename tools::promote_args<T, U>::type jacobi_cn(T k, U theta);\n\n   template <class T, class U, class Policy>\n   typename tools::promote_args<T, U>::type jacobi_dn(T k, U theta, const Policy& pol);\n\n   template <class T, class U>\n   typename tools::promote_args<T, U>::type jacobi_dn(T k, U theta);\n\n   template <class T, class U, class Policy>\n   typename tools::promote_args<T, U>::type jacobi_cd(T k, U theta, const Policy& pol);\n\n   template <class T, class U>\n   typename tools::promote_args<T, U>::type jacobi_cd(T k, U theta);\n\n   template <class T, class U, class Policy>\n   typename tools::promote_args<T, U>::type jacobi_dc(T k, U theta, const Policy& pol);\n\n   template <class T, class U>\n   typename tools::promote_args<T, U>::type jacobi_dc(T k, U theta);\n\n   template <class T, class U, class Policy>\n   typename tools::promote_args<T, U>::type jacobi_ns(T k, U theta, const Policy& pol);\n\n   template <class T, class U>\n   typename tools::promote_args<T, U>::type jacobi_ns(T k, U theta);\n\n   template <class T, class U, class Policy>\n   typename tools::promote_args<T, U>::type jacobi_sd(T k, U theta, const Policy& pol);\n\n   template <class T, class U>\n   typename tools::promote_args<T, U>::type jacobi_sd(T k, U theta);\n\n   template <class T, class U, class Policy>\n   typename tools::promote_args<T, U>::type jacobi_ds(T k, U theta, const Policy& pol);\n\n   template <class T, class U>\n   typename tools::promote_args<T, U>::type jacobi_ds(T k, U theta);\n\n   template <class T, class U, class Policy>\n   typename tools::promote_args<T, U>::type jacobi_nc(T k, U theta, const Policy& pol);\n\n   template <class T, class U>\n   typename tools::promote_args<T, U>::type jacobi_nc(T k, U theta);\n\n   template <class T, class U, class Policy>\n   typename tools::promote_args<T, U>::type jacobi_nd(T k, U theta, const Policy& pol);\n\n   template <class T, class U>\n   typename tools::promote_args<T, U>::type jacobi_nd(T k, U theta);\n\n   template <class T, class U, class Policy>\n   typename tools::promote_args<T, U>::type jacobi_sc(T k, U theta, const Policy& pol);\n\n   template <class T, class U>\n   typename tools::promote_args<T, U>::type jacobi_sc(T k, U theta);\n\n   template <class T, class U, class Policy>\n   typename tools::promote_args<T, U>::type jacobi_cs(T k, U theta, const Policy& pol);\n\n   template <class T, class U>\n   typename tools::promote_args<T, U>::type jacobi_cs(T k, U theta);\n\n\n   template <class T>\n   typename tools::promote_args<T>::type zeta(T s);\n\n   // pow:\n   template <int N, typename T, class Policy>\n   typename tools::promote_args<T>::type pow(T base, const Policy& policy);\n\n   template <int N, typename T>\n   typename tools::promote_args<T>::type pow(T base);\n\n   // next:\n   template <class T, class U, class Policy>\n   typename tools::promote_args<T, U>::type nextafter(const T&, const U&, const Policy&);\n   template <class T, class U>\n   typename tools::promote_args<T, U>::type nextafter(const T&, const U&);\n   template <class T, class Policy>\n   typename tools::promote_args<T>::type float_next(const T&, const Policy&);\n   template <class T>\n   typename tools::promote_args<T>::type float_next(const T&);\n   template <class T, class Policy>\n   typename tools::promote_args<T>::type float_prior(const T&, const Policy&);\n   template <class T>\n   typename tools::promote_args<T>::type float_prior(const T&);\n   template <class T, class U, class Policy>\n   typename tools::promote_args<T, U>::type float_distance(const T&, const U&, const Policy&);\n   template <class T, class U>\n   typename tools::promote_args<T, U>::type float_distance(const T&, const U&);\n   template <class T, class Policy>\n   typename tools::promote_args<T>::type float_advance(T val, int distance, const Policy& pol);\n   template <class T>\n   typename tools::promote_args<T>::type float_advance(const T& val, int distance);\n\n   template <class T, class Policy>\n   typename tools::promote_args<T>::type ulp(const T& val, const Policy& pol);\n   template <class T>\n   typename tools::promote_args<T>::type ulp(const T& val);\n\n   template <class T, class U>\n   typename tools::promote_args<T, U>::type relative_difference(const T&, const U&);\n   template <class T, class U>\n   typename tools::promote_args<T, U>::type epsilon_difference(const T&, const U&);\n\n   template<class T>\n   BOOST_MATH_CONSTEXPR_TABLE_FUNCTION T unchecked_bernoulli_b2n(const std::size_t n);\n   template <class T, class Policy>\n   T bernoulli_b2n(const int i, const Policy &pol);\n   template <class T>\n   T bernoulli_b2n(const int i);\n   template <class T, class OutputIterator, class Policy>\n   OutputIterator bernoulli_b2n(const int start_index,\n                                       const unsigned number_of_bernoullis_b2n,\n                                       OutputIterator out_it,\n                                       const Policy& pol);\n   template <class T, class OutputIterator>\n   OutputIterator bernoulli_b2n(const int start_index,\n                                       const unsigned number_of_bernoullis_b2n,\n                                       OutputIterator out_it);\n   template <class T, class Policy>\n   T tangent_t2n(const int i, const Policy &pol);\n   template <class T>\n   T tangent_t2n(const int i);\n   template <class T, class OutputIterator, class Policy>\n   OutputIterator tangent_t2n(const int start_index,\n                                       const unsigned number_of_bernoullis_b2n,\n                                       OutputIterator out_it,\n                                       const Policy& pol);\n   template <class T, class OutputIterator>\n   OutputIterator tangent_t2n(const int start_index,\n                                       const unsigned number_of_bernoullis_b2n,\n                                       OutputIterator out_it);\n\n    } // namespace math\n} // namespace boost\n\n#ifdef BOOST_HAS_LONG_LONG\n#define BOOST_MATH_DETAIL_LL_FUNC(Policy)\\\n   \\\n   template <class T>\\\n   inline T modf(const T& v, boost::long_long_type* ipart){ using boost::math::modf; return modf(v, ipart, Policy()); }\\\n   \\\n   template <class T>\\\n   inline boost::long_long_type lltrunc(const T& v){ using boost::math::lltrunc; return lltrunc(v, Policy()); }\\\n   \\\n   template <class T>\\\n   inline boost::long_long_type llround(const T& v){ using boost::math::llround; return llround(v, Policy()); }\\\n\n#else\n#define BOOST_MATH_DETAIL_LL_FUNC(Policy)\n#endif\n\n#define BOOST_MATH_DECLARE_SPECIAL_FUNCTIONS(Policy)\\\n   \\\n   BOOST_MATH_DETAIL_LL_FUNC(Policy)\\\n   \\\n   template <class RT1, class RT2>\\\n   inline typename boost::math::tools::promote_args<RT1, RT2>::type \\\n   beta(RT1 a, RT2 b) { return ::boost::math::beta(a, b, Policy()); }\\\n\\\n   template <class RT1, class RT2, class A>\\\n   inline typename boost::math::tools::promote_args<RT1, RT2, A>::type \\\n   beta(RT1 a, RT2 b, A x){ return ::boost::math::beta(a, b, x, Policy()); }\\\n\\\n   template <class RT1, class RT2, class RT3>\\\n   inline typename boost::math::tools::promote_args<RT1, RT2, RT3>::type \\\n   betac(RT1 a, RT2 b, RT3 x) { return ::boost::math::betac(a, b, x, Policy()); }\\\n\\\n   template <class RT1, class RT2, class RT3>\\\n   inline typename boost::math::tools::promote_args<RT1, RT2, RT3>::type \\\n   ibeta(RT1 a, RT2 b, RT3 x){ return ::boost::math::ibeta(a, b, x, Policy()); }\\\n\\\n   template <class RT1, class RT2, class RT3>\\\n   inline typename boost::math::tools::promote_args<RT1, RT2, RT3>::type \\\n   ibetac(RT1 a, RT2 b, RT3 x){ return ::boost::math::ibetac(a, b, x, Policy()); }\\\n\\\n   template <class T1, class T2, class T3, class T4>\\\n   inline typename boost::math::tools::promote_args<T1, T2, T3, T4>::type  \\\n   ibeta_inv(T1 a, T2 b, T3 p, T4* py){ return ::boost::math::ibeta_inv(a, b, p, py, Policy()); }\\\n\\\n   template <class RT1, class RT2, class RT3>\\\n   inline typename boost::math::tools::promote_args<RT1, RT2, RT3>::type \\\n   ibeta_inv(RT1 a, RT2 b, RT3 p){ return ::boost::math::ibeta_inv(a, b, p, Policy()); }\\\n\\\n   template <class T1, class T2, class T3, class T4>\\\n   inline typename boost::math::tools::promote_args<T1, T2, T3, T4>::type \\\n   ibetac_inv(T1 a, T2 b, T3 q, T4* py){ return ::boost::math::ibetac_inv(a, b, q, py, Policy()); }\\\n\\\n   template <class RT1, class RT2, class RT3>\\\n   inline typename boost::math::tools::promote_args<RT1, RT2, RT3>::type \\\n   ibeta_inva(RT1 a, RT2 b, RT3 p){ return ::boost::math::ibeta_inva(a, b, p, Policy()); }\\\n\\\n   template <class T1, class T2, class T3>\\\n   inline typename boost::math::tools::promote_args<T1, T2, T3>::type \\\n   ibetac_inva(T1 a, T2 b, T3 q){ return ::boost::math::ibetac_inva(a, b, q, Policy()); }\\\n\\\n   template <class RT1, class RT2, class RT3>\\\n   inline typename boost::math::tools::promote_args<RT1, RT2, RT3>::type \\\n   ibeta_invb(RT1 a, RT2 b, RT3 p){ return ::boost::math::ibeta_invb(a, b, p, Policy()); }\\\n\\\n   template <class T1, class T2, class T3>\\\n   inline typename boost::math::tools::promote_args<T1, T2, T3>::type \\\n   ibetac_invb(T1 a, T2 b, T3 q){ return ::boost::math::ibetac_invb(a, b, q, Policy()); }\\\n\\\n   template <class RT1, class RT2, class RT3>\\\n   inline typename boost::math::tools::promote_args<RT1, RT2, RT3>::type \\\n   ibetac_inv(RT1 a, RT2 b, RT3 q){ return ::boost::math::ibetac_inv(a, b, q, Policy()); }\\\n\\\n   template <class RT1, class RT2, class RT3>\\\n   inline typename boost::math::tools::promote_args<RT1, RT2, RT3>::type \\\n   ibeta_derivative(RT1 a, RT2 b, RT3 x){ return ::boost::math::ibeta_derivative(a, b, x, Policy()); }\\\n\\\n   template <class T> T binomial_coefficient(unsigned n, unsigned k){ return ::boost::math::binomial_coefficient<T, Policy>(n, k, Policy()); }\\\n\\\n   template <class RT>\\\n   inline typename boost::math::tools::promote_args<RT>::type erf(RT z) { return ::boost::math::erf(z, Policy()); }\\\n\\\n   template <class RT>\\\n   inline typename boost::math::tools::promote_args<RT>::type erfc(RT z){ return ::boost::math::erfc(z, Policy()); }\\\n\\\n   template <class RT>\\\n   inline typename boost::math::tools::promote_args<RT>::type erf_inv(RT z) { return ::boost::math::erf_inv(z, Policy()); }\\\n\\\n   template <class RT>\\\n   inline typename boost::math::tools::promote_args<RT>::type erfc_inv(RT z){ return ::boost::math::erfc_inv(z, Policy()); }\\\n\\\n   using boost::math::legendre_next;\\\n\\\n   template <class T>\\\n   inline typename boost::math::tools::promote_args<T>::type \\\n   legendre_p(int l, T x){ return ::boost::math::legendre_p(l, x, Policy()); }\\\n\\\n   template <class T>\\\n   inline typename boost::math::tools::promote_args<T>::type \\\n   legendre_p_prime(int l, T x){ return ::boost::math::legendre_p(l, x, Policy()); }\\\n\\\n   template <class T>\\\n   inline typename boost::math::tools::promote_args<T>::type \\\n   legendre_q(unsigned l, T x){ return ::boost::math::legendre_q(l, x, Policy()); }\\\n\\\n   using ::boost::math::legendre_next;\\\n\\\n   template <class T>\\\n   inline typename boost::math::tools::promote_args<T>::type \\\n   legendre_p(int l, int m, T x){ return ::boost::math::legendre_p(l, m, x, Policy()); }\\\n\\\n   using ::boost::math::laguerre_next;\\\n\\\n   template <class T>\\\n   inline typename boost::math::tools::promote_args<T>::type \\\n   laguerre(unsigned n, T x){ return ::boost::math::laguerre(n, x, Policy()); }\\\n\\\n   template <class T1, class T2>\\\n   inline typename boost::math::laguerre_result<T1, T2>::type \\\n   laguerre(unsigned n, T1 m, T2 x) { return ::boost::math::laguerre(n, m, x, Policy()); }\\\n\\\n   template <class T>\\\n   inline typename boost::math::tools::promote_args<T>::type \\\n   hermite(unsigned n, T x){ return ::boost::math::hermite(n, x, Policy()); }\\\n\\\n   using boost::math::hermite_next;\\\n\\\n   using boost::math::chebyshev_next;\\\n\\\n  template<class Real>\\\n  Real chebyshev_t(unsigned n, Real const & x){ return ::boost::math::chebyshev_t(n, x, Policy()); }\\\n\\\n  template<class Real>\\\n  Real chebyshev_u(unsigned n, Real const & x){ return ::boost::math::chebyshev_u(n, x, Policy()); }\\\n\\\n  template<class Real>\\\n  Real chebyshev_t_prime(unsigned n, Real const & x){ return ::boost::math::chebyshev_t_prime(n, x, Policy()); }\\\n\\\n  using ::boost::math::chebyshev_clenshaw_recurrence;\\\n\\\n   template <class T1, class T2>\\\n   inline std::complex<typename boost::math::tools::promote_args<T1, T2>::type> \\\n   spherical_harmonic(unsigned n, int m, T1 theta, T2 phi){ return boost::math::spherical_harmonic(n, m, theta, phi, Policy()); }\\\n\\\n   template <class T1, class T2>\\\n   inline typename boost::math::tools::promote_args<T1, T2>::type \\\n   spherical_harmonic_r(unsigned n, int m, T1 theta, T2 phi){ return ::boost::math::spherical_harmonic_r(n, m, theta, phi, Policy()); }\\\n\\\n   template <class T1, class T2>\\\n   inline typename boost::math::tools::promote_args<T1, T2>::type \\\n   spherical_harmonic_i(unsigned n, int m, T1 theta, T2 phi){ return boost::math::spherical_harmonic_i(n, m, theta, phi, Policy()); }\\\n\\\n   template <class T1, class T2, class Policy>\\\n   inline typename boost::math::tools::promote_args<T1, T2>::type \\\n      spherical_harmonic_i(unsigned n, int m, T1 theta, T2 phi, const Policy& pol);\\\n\\\n   template <class T1, class T2, class T3>\\\n   inline typename boost::math::tools::promote_args<T1, T2, T3>::type \\\n   ellint_rf(T1 x, T2 y, T3 z){ return ::boost::math::ellint_rf(x, y, z, Policy()); }\\\n\\\n   template <class T1, class T2, class T3>\\\n   inline typename boost::math::tools::promote_args<T1, T2, T3>::type \\\n   ellint_rd(T1 x, T2 y, T3 z){ return ::boost::math::ellint_rd(x, y, z, Policy()); }\\\n\\\n   template <class T1, class T2>\\\n   inline typename boost::math::tools::promote_args<T1, T2>::type \\\n   ellint_rc(T1 x, T2 y){ return ::boost::math::ellint_rc(x, y, Policy()); }\\\n\\\n   template <class T1, class T2, class T3, class T4>\\\n   inline typename boost::math::tools::promote_args<T1, T2, T3, T4>::type \\\n   ellint_rj(T1 x, T2 y, T3 z, T4 p){ return boost::math::ellint_rj(x, y, z, p, Policy()); }\\\n\\\n   template <class T1, class T2, class T3>\\\n   inline typename boost::math::tools::promote_args<T1, T2, T3>::type \\\n   ellint_rg(T1 x, T2 y, T3 z){ return ::boost::math::ellint_rg(x, y, z, Policy()); }\\\n   \\\n   template <typename T>\\\n   inline typename boost::math::tools::promote_args<T>::type ellint_2(T k){ return boost::math::ellint_2(k, Policy()); }\\\n\\\n   template <class T1, class T2>\\\n   inline typename boost::math::tools::promote_args<T1, T2>::type ellint_2(T1 k, T2 phi){ return boost::math::ellint_2(k, phi, Policy()); }\\\n\\\n   template <typename T>\\\n   inline typename boost::math::tools::promote_args<T>::type ellint_d(T k){ return boost::math::ellint_d(k, Policy()); }\\\n\\\n   template <class T1, class T2>\\\n   inline typename boost::math::tools::promote_args<T1, T2>::type ellint_d(T1 k, T2 phi){ return boost::math::ellint_d(k, phi, Policy()); }\\\n\\\n   template <class T1, class T2>\\\n   inline typename boost::math::tools::promote_args<T1, T2>::type jacobi_zeta(T1 k, T2 phi){ return boost::math::jacobi_zeta(k, phi, Policy()); }\\\n\\\n   template <class T1, class T2>\\\n   inline typename boost::math::tools::promote_args<T1, T2>::type heuman_lambda(T1 k, T2 phi){ return boost::math::heuman_lambda(k, phi, Policy()); }\\\n\\\n   template <typename T>\\\n   inline typename boost::math::tools::promote_args<T>::type ellint_1(T k){ return boost::math::ellint_1(k, Policy()); }\\\n\\\n   template <class T1, class T2>\\\n   inline typename boost::math::tools::promote_args<T1, T2>::type ellint_1(T1 k, T2 phi){ return boost::math::ellint_1(k, phi, Policy()); }\\\n\\\n   template <class T1, class T2, class T3>\\\n   inline typename boost::math::tools::promote_args<T1, T2, T3>::type ellint_3(T1 k, T2 v, T3 phi){ return boost::math::ellint_3(k, v, phi, Policy()); }\\\n\\\n   template <class T1, class T2>\\\n   inline typename boost::math::tools::promote_args<T1, T2>::type ellint_3(T1 k, T2 v){ return boost::math::ellint_3(k, v, Policy()); }\\\n\\\n   using boost::math::max_factorial;\\\n   template <class RT>\\\n   inline RT factorial(unsigned int i) { return boost::math::factorial<RT>(i, Policy()); }\\\n   using boost::math::unchecked_factorial;\\\n   template <class RT>\\\n   inline RT double_factorial(unsigned i){ return boost::math::double_factorial<RT>(i, Policy()); }\\\n   template <class RT>\\\n   inline typename boost::math::tools::promote_args<RT>::type falling_factorial(RT x, unsigned n){ return boost::math::falling_factorial(x, n, Policy()); }\\\n   template <class RT>\\\n   inline typename boost::math::tools::promote_args<RT>::type rising_factorial(RT x, unsigned n){ return boost::math::rising_factorial(x, n, Policy()); }\\\n\\\n   template <class RT>\\\n   inline typename boost::math::tools::promote_args<RT>::type tgamma(RT z){ return boost::math::tgamma(z, Policy()); }\\\n\\\n   template <class RT>\\\n   inline typename boost::math::tools::promote_args<RT>::type tgamma1pm1(RT z){ return boost::math::tgamma1pm1(z, Policy()); }\\\n\\\n   template <class RT1, class RT2>\\\n   inline typename boost::math::tools::promote_args<RT1, RT2>::type tgamma(RT1 a, RT2 z){ return boost::math::tgamma(a, z, Policy()); }\\\n\\\n   template <class RT>\\\n   inline typename boost::math::tools::promote_args<RT>::type lgamma(RT z, int* sign){ return boost::math::lgamma(z, sign, Policy()); }\\\n\\\n   template <class RT>\\\n   inline typename boost::math::tools::promote_args<RT>::type lgamma(RT x){ return boost::math::lgamma(x, Policy()); }\\\n\\\n   template <class RT1, class RT2>\\\n   inline typename boost::math::tools::promote_args<RT1, RT2>::type tgamma_lower(RT1 a, RT2 z){ return boost::math::tgamma_lower(a, z, Policy()); }\\\n\\\n   template <class RT1, class RT2>\\\n   inline typename boost::math::tools::promote_args<RT1, RT2>::type gamma_q(RT1 a, RT2 z){ return boost::math::gamma_q(a, z, Policy()); }\\\n\\\n   template <class RT1, class RT2>\\\n   inline typename boost::math::tools::promote_args<RT1, RT2>::type gamma_p(RT1 a, RT2 z){ return boost::math::gamma_p(a, z, Policy()); }\\\n\\\n   template <class T1, class T2>\\\n   inline typename boost::math::tools::promote_args<T1, T2>::type tgamma_delta_ratio(T1 z, T2 delta){ return boost::math::tgamma_delta_ratio(z, delta, Policy()); }\\\n\\\n   template <class T1, class T2>\\\n   inline typename boost::math::tools::promote_args<T1, T2>::type tgamma_ratio(T1 a, T2 b) { return boost::math::tgamma_ratio(a, b, Policy()); }\\\n\\\n   template <class T1, class T2>\\\n   inline typename boost::math::tools::promote_args<T1, T2>::type gamma_p_derivative(T1 a, T2 x){ return boost::math::gamma_p_derivative(a, x, Policy()); }\\\n\\\n   template <class T1, class T2>\\\n   inline typename boost::math::tools::promote_args<T1, T2>::type gamma_p_inv(T1 a, T2 p){ return boost::math::gamma_p_inv(a, p, Policy()); }\\\n\\\n   template <class T1, class T2>\\\n   inline typename boost::math::tools::promote_args<T1, T2>::type gamma_p_inva(T1 a, T2 p){ return boost::math::gamma_p_inva(a, p, Policy()); }\\\n\\\n   template <class T1, class T2>\\\n   inline typename boost::math::tools::promote_args<T1, T2>::type gamma_q_inv(T1 a, T2 q){ return boost::math::gamma_q_inv(a, q, Policy()); }\\\n\\\n   template <class T1, class T2>\\\n   inline typename boost::math::tools::promote_args<T1, T2>::type gamma_q_inva(T1 a, T2 q){ return boost::math::gamma_q_inva(a, q, Policy()); }\\\n\\\n   template <class T>\\\n   inline typename boost::math::tools::promote_args<T>::type digamma(T x){ return boost::math::digamma(x, Policy()); }\\\n\\\n   template <class T>\\\n   inline typename boost::math::tools::promote_args<T>::type trigamma(T x){ return boost::math::trigamma(x, Policy()); }\\\n\\\n   template <class T>\\\n   inline typename boost::math::tools::promote_args<T>::type polygamma(int n, T x){ return boost::math::polygamma(n, x, Policy()); }\\\n   \\\n   template <class T1, class T2>\\\n   inline typename boost::math::tools::promote_args<T1, T2>::type \\\n   hypot(T1 x, T2 y){ return boost::math::hypot(x, y, Policy()); }\\\n\\\n   template <class RT>\\\n   inline typename boost::math::tools::promote_args<RT>::type cbrt(RT z){ return boost::math::cbrt(z, Policy()); }\\\n\\\n   template <class T>\\\n   inline typename boost::math::tools::promote_args<T>::type log1p(T x){ return boost::math::log1p(x, Policy()); }\\\n\\\n   template <class T>\\\n   inline typename boost::math::tools::promote_args<T>::type log1pmx(T x){ return boost::math::log1pmx(x, Policy()); }\\\n\\\n   template <class T>\\\n   inline typename boost::math::tools::promote_args<T>::type expm1(T x){ return boost::math::expm1(x, Policy()); }\\\n\\\n   template <class T1, class T2>\\\n   inline typename boost::math::tools::promote_args<T1, T2>::type \\\n   powm1(const T1 a, const T2 z){ return boost::math::powm1(a, z, Policy()); }\\\n\\\n   template <class T>\\\n   inline typename boost::math::tools::promote_args<T>::type sqrt1pm1(const T& val){ return boost::math::sqrt1pm1(val, Policy()); }\\\n\\\n   template <class T>\\\n   inline typename boost::math::tools::promote_args<T>::type sinc_pi(T x){ return boost::math::sinc_pi(x, Policy()); }\\\n\\\n   template <class T>\\\n   inline typename boost::math::tools::promote_args<T>::type sinhc_pi(T x){ return boost::math::sinhc_pi(x, Policy()); }\\\n\\\n   template<typename T>\\\n   inline typename boost::math::tools::promote_args<T>::type asinh(const T x){ return boost::math::asinh(x, Policy()); }\\\n\\\n   template<typename T>\\\n   inline typename boost::math::tools::promote_args<T>::type acosh(const T x){ return boost::math::acosh(x, Policy()); }\\\n\\\n   template<typename T>\\\n   inline typename boost::math::tools::promote_args<T>::type atanh(const T x){ return boost::math::atanh(x, Policy()); }\\\n\\\n   template <class T1, class T2>\\\n   inline typename boost::math::detail::bessel_traits<T1, T2, Policy >::result_type cyl_bessel_j(T1 v, T2 x)\\\n   { return boost::math::cyl_bessel_j(v, x, Policy()); }\\\n\\\n   template <class T1, class T2>\\\n   inline typename boost::math::detail::bessel_traits<T1, T2, Policy >::result_type cyl_bessel_j_prime(T1 v, T2 x)\\\n   { return boost::math::cyl_bessel_j_prime(v, x, Policy()); }\\\n\\\n   template <class T>\\\n   inline typename boost::math::detail::bessel_traits<T, T, Policy >::result_type sph_bessel(unsigned v, T x)\\\n   { return boost::math::sph_bessel(v, x, Policy()); }\\\n\\\n   template <class T>\\\n   inline typename boost::math::detail::bessel_traits<T, T, Policy >::result_type sph_bessel_prime(unsigned v, T x)\\\n   { return boost::math::sph_bessel_prime(v, x, Policy()); }\\\n\\\n   template <class T1, class T2>\\\n   inline typename boost::math::detail::bessel_traits<T1, T2, Policy >::result_type \\\n   cyl_bessel_i(T1 v, T2 x) { return boost::math::cyl_bessel_i(v, x, Policy()); }\\\n\\\n   template <class T1, class T2>\\\n   inline typename boost::math::detail::bessel_traits<T1, T2, Policy >::result_type \\\n   cyl_bessel_i_prime(T1 v, T2 x) { return boost::math::cyl_bessel_i_prime(v, x, Policy()); }\\\n\\\n   template <class T1, class T2>\\\n   inline typename boost::math::detail::bessel_traits<T1, T2, Policy >::result_type \\\n   cyl_bessel_k(T1 v, T2 x) { return boost::math::cyl_bessel_k(v, x, Policy()); }\\\n\\\n   template <class T1, class T2>\\\n   inline typename boost::math::detail::bessel_traits<T1, T2, Policy >::result_type \\\n   cyl_bessel_k_prime(T1 v, T2 x) { return boost::math::cyl_bessel_k_prime(v, x, Policy()); }\\\n\\\n   template <class T1, class T2>\\\n   inline typename boost::math::detail::bessel_traits<T1, T2, Policy >::result_type \\\n   cyl_neumann(T1 v, T2 x){ return boost::math::cyl_neumann(v, x, Policy()); }\\\n\\\n   template <class T1, class T2>\\\n   inline typename boost::math::detail::bessel_traits<T1, T2, Policy >::result_type \\\n   cyl_neumann_prime(T1 v, T2 x){ return boost::math::cyl_neumann_prime(v, x, Policy()); }\\\n\\\n   template <class T>\\\n   inline typename boost::math::detail::bessel_traits<T, T, Policy >::result_type \\\n   sph_neumann(unsigned v, T x){ return boost::math::sph_neumann(v, x, Policy()); }\\\n\\\n   template <class T>\\\n   inline typename boost::math::detail::bessel_traits<T, T, Policy >::result_type \\\n   sph_neumann_prime(unsigned v, T x){ return boost::math::sph_neumann_prime(v, x, Policy()); }\\\n\\\n   template <class T>\\\n   inline typename boost::math::detail::bessel_traits<T, T, Policy >::result_type cyl_bessel_j_zero(T v, int m)\\\n   { return boost::math::cyl_bessel_j_zero(v, m, Policy()); }\\\n\\\ntemplate <class OutputIterator, class T>\\\n   inline void cyl_bessel_j_zero(T v,\\\n                                 int start_index,\\\n                                 unsigned number_of_zeros,\\\n                                 OutputIterator out_it)\\\n   { boost::math::cyl_bessel_j_zero(v, start_index, number_of_zeros, out_it, Policy()); }\\\n\\\n   template <class T>\\\n   inline typename boost::math::detail::bessel_traits<T, T, Policy >::result_type cyl_neumann_zero(T v, int m)\\\n   { return boost::math::cyl_neumann_zero(v, m, Policy()); }\\\n\\\ntemplate <class OutputIterator, class T>\\\n   inline void cyl_neumann_zero(T v,\\\n                                int start_index,\\\n                                unsigned number_of_zeros,\\\n                                OutputIterator out_it)\\\n   { boost::math::cyl_neumann_zero(v, start_index, number_of_zeros, out_it, Policy()); }\\\n\\\n   template <class T>\\\n   inline typename boost::math::tools::promote_args<T>::type sin_pi(T x){ return boost::math::sin_pi(x); }\\\n\\\n   template <class T>\\\n   inline typename boost::math::tools::promote_args<T>::type cos_pi(T x){ return boost::math::cos_pi(x); }\\\n\\\n   using boost::math::fpclassify;\\\n   using boost::math::isfinite;\\\n   using boost::math::isinf;\\\n   using boost::math::isnan;\\\n   using boost::math::isnormal;\\\n   using boost::math::signbit;\\\n   using boost::math::sign;\\\n   using boost::math::copysign;\\\n   using boost::math::changesign;\\\n   \\\n   template <class T, class U>\\\n   inline typename boost::math::tools::promote_args<T,U>::type expint(T const& z, U const& u)\\\n   { return boost::math::expint(z, u, Policy()); }\\\n   \\\n   template <class T>\\\n   inline typename boost::math::tools::promote_args<T>::type expint(T z){ return boost::math::expint(z, Policy()); }\\\n   \\\n   template <class T>\\\n   inline typename boost::math::tools::promote_args<T>::type zeta(T s){ return boost::math::zeta(s, Policy()); }\\\n   \\\n   template <class T>\\\n   inline T round(const T& v){ using boost::math::round; return round(v, Policy()); }\\\n   \\\n   template <class T>\\\n   inline int iround(const T& v){ using boost::math::iround; return iround(v, Policy()); }\\\n   \\\n   template <class T>\\\n   inline long lround(const T& v){ using boost::math::lround; return lround(v, Policy()); }\\\n   \\\n   template <class T>\\\n   inline T trunc(const T& v){ using boost::math::trunc; return trunc(v, Policy()); }\\\n   \\\n   template <class T>\\\n   inline int itrunc(const T& v){ using boost::math::itrunc; return itrunc(v, Policy()); }\\\n   \\\n   template <class T>\\\n   inline long ltrunc(const T& v){ using boost::math::ltrunc; return ltrunc(v, Policy()); }\\\n   \\\n   template <class T>\\\n   inline T modf(const T& v, T* ipart){ using boost::math::modf; return modf(v, ipart, Policy()); }\\\n   \\\n   template <class T>\\\n   inline T modf(const T& v, int* ipart){ using boost::math::modf; return modf(v, ipart, Policy()); }\\\n   \\\n   template <class T>\\\n   inline T modf(const T& v, long* ipart){ using boost::math::modf; return modf(v, ipart, Policy()); }\\\n   \\\n   template <int N, class T>\\\n   inline typename boost::math::tools::promote_args<T>::type pow(T v){ return boost::math::pow<N>(v, Policy()); }\\\n   \\\n   template <class T> T nextafter(const T& a, const T& b){ return boost::math::nextafter(a, b, Policy()); }\\\n   template <class T> T float_next(const T& a){ return boost::math::float_next(a, Policy()); }\\\n   template <class T> T float_prior(const T& a){ return boost::math::float_prior(a, Policy()); }\\\n   template <class T> T float_distance(const T& a, const T& b){ return boost::math::float_distance(a, b, Policy()); }\\\n   template <class T> T ulp(const T& a){ return boost::math::ulp(a, Policy()); }\\\n   \\\n   template <class RT1, class RT2>\\\n   inline typename boost::math::tools::promote_args<RT1, RT2>::type owens_t(RT1 a, RT2 z){ return boost::math::owens_t(a, z, Policy()); }\\\n   \\\n   template <class T1, class T2>\\\n   inline std::complex<typename boost::math::detail::bessel_traits<T1, T2, Policy >::result_type> cyl_hankel_1(T1 v, T2 x)\\\n   {  return boost::math::cyl_hankel_1(v, x, Policy()); }\\\n   \\\n   template <class T1, class T2>\\\n   inline std::complex<typename boost::math::detail::bessel_traits<T1, T2, Policy >::result_type> cyl_hankel_2(T1 v, T2 x)\\\n   { return boost::math::cyl_hankel_2(v, x, Policy()); }\\\n   \\\n   template <class T1, class T2>\\\n   inline std::complex<typename boost::math::detail::bessel_traits<T1, T2, Policy >::result_type> sph_hankel_1(T1 v, T2 x)\\\n   { return boost::math::sph_hankel_1(v, x, Policy()); }\\\n   \\\n   template <class T1, class T2>\\\n   inline std::complex<typename boost::math::detail::bessel_traits<T1, T2, Policy >::result_type> sph_hankel_2(T1 v, T2 x)\\\n   { return boost::math::sph_hankel_2(v, x, Policy()); }\\\n   \\\n   template <class T>\\\n   inline typename boost::math::tools::promote_args<T>::type jacobi_elliptic(T k, T theta, T* pcn, T* pdn)\\\n   { return boost::math::jacobi_elliptic(k, theta, pcn, pdn, Policy()); }\\\n   \\\n   template <class U, class T>\\\n   inline typename boost::math::tools::promote_args<T, U>::type jacobi_sn(U k, T theta)\\\n   { return boost::math::jacobi_sn(k, theta, Policy()); }\\\n   \\\n   template <class T, class U>\\\n   inline typename boost::math::tools::promote_args<T, U>::type jacobi_cn(T k, U theta)\\\n   { return boost::math::jacobi_cn(k, theta, Policy()); }\\\n   \\\n   template <class T, class U>\\\n   inline typename boost::math::tools::promote_args<T, U>::type jacobi_dn(T k, U theta)\\\n   { return boost::math::jacobi_dn(k, theta, Policy()); }\\\n   \\\n   template <class T, class U>\\\n   inline typename boost::math::tools::promote_args<T, U>::type jacobi_cd(T k, U theta)\\\n   { return boost::math::jacobi_cd(k, theta, Policy()); }\\\n   \\\n   template <class T, class U>\\\n   inline typename boost::math::tools::promote_args<T, U>::type jacobi_dc(T k, U theta)\\\n   { return boost::math::jacobi_dc(k, theta, Policy()); }\\\n   \\\n   template <class T, class U>\\\n   inline typename boost::math::tools::promote_args<T, U>::type jacobi_ns(T k, U theta)\\\n   { return boost::math::jacobi_ns(k, theta, Policy()); }\\\n   \\\n   template <class T, class U>\\\n   inline typename boost::math::tools::promote_args<T, U>::type jacobi_sd(T k, U theta)\\\n   { return boost::math::jacobi_sd(k, theta, Policy()); }\\\n   \\\n   template <class T, class U>\\\n   inline typename boost::math::tools::promote_args<T, U>::type jacobi_ds(T k, U theta)\\\n   { return boost::math::jacobi_ds(k, theta, Policy()); }\\\n   \\\n   template <class T, class U>\\\n   inline typename boost::math::tools::promote_args<T, U>::type jacobi_nc(T k, U theta)\\\n   { return boost::math::jacobi_nc(k, theta, Policy()); }\\\n   \\\n   template <class T, class U>\\\n   inline typename boost::math::tools::promote_args<T, U>::type jacobi_nd(T k, U theta)\\\n   { return boost::math::jacobi_nd(k, theta, Policy()); }\\\n   \\\n   template <class T, class U>\\\n   inline typename boost::math::tools::promote_args<T, U>::type jacobi_sc(T k, U theta)\\\n   { return boost::math::jacobi_sc(k, theta, Policy()); }\\\n   \\\n   template <class T, class U>\\\n   inline typename boost::math::tools::promote_args<T, U>::type jacobi_cs(T k, U theta)\\\n   { return boost::math::jacobi_cs(k, theta, Policy()); }\\\n   \\\n   template <class T>\\\n   inline typename boost::math::tools::promote_args<T>::type airy_ai(T x)\\\n   {  return boost::math::airy_ai(x, Policy());  }\\\n   \\\n   template <class T>\\\n   inline typename boost::math::tools::promote_args<T>::type airy_bi(T x)\\\n   {  return boost::math::airy_bi(x, Policy());  }\\\n   \\\n   template <class T>\\\n   inline typename boost::math::tools::promote_args<T>::type airy_ai_prime(T x)\\\n   {  return boost::math::airy_ai_prime(x, Policy());  }\\\n   \\\n   template <class T>\\\n   inline typename boost::math::tools::promote_args<T>::type airy_bi_prime(T x)\\\n   {  return boost::math::airy_bi_prime(x, Policy());  }\\\n   \\\n   template <class T>\\\n   inline T airy_ai_zero(int m)\\\n   { return boost::math::airy_ai_zero<T>(m, Policy()); }\\\n   template <class T, class OutputIterator>\\\n   OutputIterator airy_ai_zero(int start_index, unsigned number_of_zeros, OutputIterator out_it)\\\n   { return boost::math::airy_ai_zero<T>(start_index, number_of_zeros, out_it, Policy()); }\\\n   \\\n   template <class T>\\\n   inline T airy_bi_zero(int m)\\\n   { return boost::math::airy_bi_zero<T>(m, Policy()); }\\\n   template <class T, class OutputIterator>\\\n   OutputIterator airy_bi_zero(int start_index, unsigned number_of_zeros, OutputIterator out_it)\\\n   { return boost::math::airy_bi_zero<T>(start_index, number_of_zeros, out_it, Policy()); }\\\n   \\\n   template <class T>\\\n   T bernoulli_b2n(const int i)\\\n   { return boost::math::bernoulli_b2n<T>(i, Policy()); }\\\n   template <class T, class OutputIterator>\\\n   OutputIterator bernoulli_b2n(int start_index, unsigned number_of_bernoullis_b2n, OutputIterator out_it)\\\n   { return boost::math::bernoulli_b2n<T>(start_index, number_of_bernoullis_b2n, out_it, Policy()); }\\\n   \\\n   template <class T>\\\n   T tangent_t2n(const int i)\\\n   { return boost::math::tangent_t2n<T>(i, Policy()); }\\\n   template <class T, class OutputIterator>\\\n   OutputIterator tangent_t2n(int start_index, unsigned number_of_bernoullis_b2n, OutputIterator out_it)\\\n   { return boost::math::tangent_t2n<T>(start_index, number_of_bernoullis_b2n, out_it, Policy()); }\\\n   \\\n\n\n\n\n\n#endif // BOOST_MATH_SPECIAL_MATH_FWD_HPP\n", "meta": {"hexsha": "4f44f561136e5a1b8791a0f66cda7c268b42f384", "size": 69766, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "thirdparty/boost_1_67_0/boost/math/special_functions/math_fwd.hpp", "max_stars_repo_name": "cfsengineering/tigl", "max_stars_repo_head_hexsha": "abfbb57b82dc6beac7cde212a4cd5e0aed866db8", "max_stars_repo_licenses": ["Apache-2.0"], "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": "thirdparty/boost_1_67_0/boost/math/special_functions/math_fwd.hpp", "max_issues_repo_name": "cfsengineering/tigl", "max_issues_repo_head_hexsha": "abfbb57b82dc6beac7cde212a4cd5e0aed866db8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 127.0, "max_issues_repo_issues_event_min_datetime": "2016-07-06T15:43:14.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-11T18:46:27.000Z", "max_forks_repo_path": "thirdparty/boost_1_67_0/boost/math/special_functions/math_fwd.hpp", "max_forks_repo_name": "cfsengineering/tigl", "max_forks_repo_head_hexsha": "abfbb57b82dc6beac7cde212a4cd5e0aed866db8", "max_forks_repo_licenses": ["Apache-2.0"], "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": 42.2312348668, "max_line_length": 164, "alphanum_fraction": 0.6698821776, "num_tokens": 20480, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149978955811, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4587340405756195}}
{"text": "#include <boost/integer/static_log2.hpp>\n", "meta": {"hexsha": "32768d31c5844583aa0c88158ffee112b43323b1", "size": 41, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_integer_static_log2.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_integer_static_log2.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_integer_static_log2.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 20.5, "max_line_length": 40, "alphanum_fraction": 0.8048780488, "num_tokens": 10, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149978955811, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4587340405756195}}
{"text": "#include \"MPContext.hpp\"\n#include \"fhe/NumbTh.h\"\n#include <set>\n#include <NTL/ZZ.h>\n#include <cmath>\n#include <vector>\n#include <thread>\n#ifdef FHE_THREADS\nconst long WORKER_NR = 8;\n#else\nconst long WORKER_NR = 1;\n#endif\n\nstatic long getSlots(long m, long p)\n{\n    return phi_N(m) / multOrd(p, m);\n}\n\nstatic long gcd(long a, long b) {\n    if (a > b) std::swap(a, b);\n\n    auto r = b % a;\n    while (r > 0) {\n        a = r;\n        b = a;\n        r = b % a;\n    }\n    return a;\n}\n\nbool checkSlots(long required, long check) {\n    if (check < required) return false;\n    return gcd(required, check) == required;\n}\n\nstatic std::set<long> FindPrimes(long m, long p, long parts)\n{\n    auto slots = getSlots(m, p);\n    auto bits = static_cast<long>(std::ceil(std::log2(static_cast<double>(p))));\n    std::set<long> primes;\n\t// {\n\t// \tstd::vector<long> pprimes = {4139, 7321, 5381, 5783, 4231, 4937, 5279, 6679, 6323, 7459, 6791};\n\t// \tauto len = pprimes.size();\n\t// \tfor (long pp = 0; pp < parts; pp++) primes.insert(pprimes[len - 1 - pp]);\n\t// \treturn primes;\n\t// }\n    primes.insert(p);\n\tlong generated = 1;\n\tlong trial = 0;\n\twhile (generated < parts) {\n\n\t\tauto prime = NTL::RandomPrime_long(bits);\n        auto s = getSlots(m, prime);\n\t\tif (checkSlots(slots, s)) {\n\t\t\tauto ok = primes.insert(prime);\n\t\t\tif (ok.second) {\n\t\t\t\tgenerated += 1;\n\t\t\t}\n        }\n\n\t\tif (trial++ > 1000) {\n\t\t\tprintf(\"Error: Can not find enough primes, only found %ld\\n\",\n\t\t\t\t   generated);\n\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn primes;\n}\n\n\tMPContext::MPContext(long m, long p, long r, long parts)\n: m_r(r)\n{\n\tcontexts.reserve(parts);\n\tauto primesSet = FindPrimes(m, p, parts);\n\n\tfor (auto prime : primesSet) {\n\t\tm_plainSpace *= std::pow(prime, r);\n\t\tm_primes.push_back(prime);\n\t}\n\n\tstd::vector<std::thread> worker;\n\tstd::atomic<size_t> counter(0);\n\tconst size_t num = m_primes.size();\n\tauto job = [this, &counter, &m, &r, &num]() {\n\t\tsize_t i;\n\t\twhile ((i = counter.fetch_add(1)) < num) {\n\t\t\tcontexts[i] = std::make_shared<FHEcontext>(m, m_primes[i], r);\n\t\t}\n\t};\n\n\tcontexts.resize(num);\n\n\tfor (long wr = 0; wr < WORKER_NR; wr++) worker.push_back(std::thread(job));\n\n\tfor (auto &&wr : worker) wr.join();\n}\n\nvoid MPContext::buildModChain(long L)\n{\n\tstd::vector<std::thread> worker;\n\tstd::atomic<size_t> counter(0);\n\tconst size_t num = contexts.size();\n\tauto job = [this, &counter, &num, &L]() {\n\t\tsize_t i;\n\t\twhile ((i = counter.fetch_add(1)) < num) {\n\t\t\t::buildModChain(*contexts[i], L);\n\t\t}\n\t};\n\n\tcontexts.resize(num);\n\n\tfor (long wr = 0; wr < WORKER_NR; wr++) worker.push_back(std::thread(job));\n\n\tfor (auto &&wr : worker) wr.join();\n}\n\ndouble MPContext::precision() const\n{\n\treturn NTL::log(plainSpace()) / NTL::log(NTL::to_ZZ(2));\n}\n", "meta": {"hexsha": "f5e3754ba5e97662acc66dc24e0dd100d94c8c68", "size": 2695, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "multiprecision/MPContext.cpp", "max_stars_repo_name": "fionser/MDLHElib", "max_stars_repo_head_hexsha": "3c686ab35d7b26a893213a6e9d4249cd46c2969d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2017-01-16T06:20:07.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-17T12:36:34.000Z", "max_issues_repo_path": "multiprecision/MPContext.cpp", "max_issues_repo_name": "fionser/MDLHElib", "max_issues_repo_head_hexsha": "3c686ab35d7b26a893213a6e9d4249cd46c2969d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "multiprecision/MPContext.cpp", "max_forks_repo_name": "fionser/MDLHElib", "max_forks_repo_head_hexsha": "3c686ab35d7b26a893213a6e9d4249cd46c2969d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-08-26T13:16:35.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-15T02:08:20.000Z", "avg_line_length": 22.0901639344, "max_line_length": 100, "alphanum_fraction": 0.6111317254, "num_tokens": 859, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.754914997895581, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.45873404057561945}}
{"text": "/*! \\file boxplot_simple.cpp\n\n    \\brief An example to demonstrate simplest use of boxplot.\\n\n           See also boxplot_full.cpp for a wider range of use.\n\n\n    \\author Paul A Bristow\n\n    \\date 2009\n*/\n\n// Copyright Jacob Voytko 2007\n// Copyright Paul A. Bristow 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// This file is written to be included from a Quickbook .qbk document.\n// It can be compiled by the C++ compiler, and run. Any output can\n// also be added here as comment or included or pasted in elsewhere.\n\n// Caution: this file contains Quickbook markup as well as code\n// and comments: don't change any of the special comment markups!\n\n//[boxplot_1d_1\n\n/*`\nBoxplot is a  convenient way of graphically depicting groups of numerical data\nthrough their five-number summaries.\nShow 1st quartile, median and 3rd quartile as a box, outliers and extreme outliers.\n\nSee [@http://en.wikipedia.org/wiki/Boxplot boxplot] and\n\nSome Implementations of the Boxplot\nMichael Frigge, David C. Hoaglin and Boris Iglewicz\nThe American Statistician, Vol. 43, No. 1 (Feb., 1989), pp. 50-54\n\nFirst we need a few includes to use Boost.Plot.\n*/\n\n#include <vector>\nusing std::vector;\n#include <cmath>\nusing ::sin;\n#include <boost/svg_plot/svg_boxplot.hpp>\n\n#include <iostream>\nusing std::cout;\nusing std::endl;\n\n/*`Use two functions, 1/x and sin(x), to simulate distributions.\n*/\n\ndouble f(double x)\n{ // Effectively 1/x.\n  return 50 / x;\n}\n\ndouble g(double x)\n{ // Effectively sin(x).\n  return 40 + 25 * sin(x * 50);\n}\n//] [boxplot_1d_1]\n\nint main()\n{\n  using namespace boost::svg;\n  try\n  {\n//[boxplot_1d_2]\n/*`10 values are computed and stored in two std:: vectors.\n*/\n  std::vector<double> data1;\n  std::vector<double> data2;\n\n  cout.precision(2);\n  for(double i = 0.1; i < 10; i += 0.1)\n  {   // Fill our vectors with 100 values:\n    double fv = f(i);\n    double gv = g(i);\n    // cout << i << ' ' << fv << ' ' << gv << endl;\n    data1.push_back(fv);\n    data2.push_back(gv);\n  }\n\n/*`A new boxplot is contructed and a few settings added.\n*/\n  svg_boxplot my_boxplot;\n\n  my_boxplot.background_border_color(darkblue);\n  my_boxplot.background_color(azure);\n\n  my_boxplot  // Title and axes labels.\n    .title(\"Boxplots of 1/x and sin(x) Functions\")\n    .x_label(\"Functions\")\n    .y_label(\"Population Size\");\n\n  my_boxplot.y_range(0, 100)  // Axis information.\n    //.y_minor_tick_length(20)\n    .y_major_interval(20);\n\n/*`Add the two data series containers, and their labels, to the plot.\n*/\n\n  my_boxplot.plot(data1, \"[50 / x]\");\n  my_boxplot.plot(data2, \"[40 + 25 * sin(x * 50)]\");\n\n/*  cout << \"my_boxplot.title \" << my_boxplot.title() << endl;\n  cout << \"my_boxplot.x_label_text \"<< my_boxplot.x_label_text() << endl;\n  cout << \"my_boxplot.y_label_text \" << my_boxplot.y_label_text() << endl;\n\n  cout << \"my_boxplot.background_color \" << my_boxplot.background_color() << endl;\n  cout << \"my_boxplot.background_border_color \" << my_boxplot.background_border_color() << endl;\n  cout << \"my_boxplot.plot_background_color \" << my_boxplot.plot_background_color() << endl;\n */ cout << \"my_boxplot.plot_border_color \" << my_boxplot.plot_border_color() << endl;\n\n\n/*`Finally write the SVG plot to a file.\n*/\n  my_boxplot.write(\"boxplot_simple.svg\");\n/*`You can view the plot at boxplot_simple.svg.\"\n*/\n\n//] [boxplot_1d_2]\n  }\n  catch(const std::exception& e)\n  {\n    std::cout <<\n      \"\\n\"\"Message from thrown exception was:\\n  \" << e.what() << std::endl;\n  }\n  return 0;\n} // int main()\n\n/*\n\nOutput:\n\n\n*/\n\n", "meta": {"hexsha": "192244da630b6982b59f70e85e349dee3230ecf4", "size": 3648, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/boxplot_simple.cpp", "max_stars_repo_name": "pabristow/svg_plot", "max_stars_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2016-03-09T03:23:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T14:02:07.000Z", "max_issues_repo_path": "example/boxplot_simple.cpp", "max_issues_repo_name": "pabristow/svg_plot", "max_issues_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2018-03-05T14:39:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-22T09:00:33.000Z", "max_forks_repo_path": "example/boxplot_simple.cpp", "max_forks_repo_name": "pabristow/svg_plot", "max_forks_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2016-11-04T14:36:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-17T08:12:03.000Z", "avg_line_length": 25.5104895105, "max_line_length": 96, "alphanum_fraction": 0.6820175439, "num_tokens": 1037, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.45873403722497913}}
{"text": "/* test_ranlux4.cpp\n *\n * Copyright Steven Watanabe 2011\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#include <boost/random/ranlux.hpp>\n\n#define BOOST_RANDOM_URNG boost::random::ranlux4\n\n#define BOOST_RANDOM_SEED_WORDS 24\n\n// principal operation validated with CLHEP, values by experiment\n#define BOOST_RANDOM_VALIDATION_VALUE 8587295U\n#define BOOST_RANDOM_SEED_SEQ_VALIDATION_VALUE 10794046U\n#define BOOST_RANDOM_ITERATOR_VALIDATION_VALUE 4515722U\n\n#define BOOST_RANDOM_GENERATE_VALUES { 0x55E57B2CU, 0xF2DEF915U, 0x6D1A0CD9U, 0xCA0109F9U }\n\n#include \"test_generator.ipp\"\n", "meta": {"hexsha": "1ba17e943ded47ef44f8c54f82eaa5e499163856", "size": 704, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/random/test/test_ranlux4.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "boost/libs/random/test/test_ranlux4.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "boost/libs/random/test/test_ranlux4.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 27.0769230769, "max_line_length": 91, "alphanum_fraction": 0.8025568182, "num_tokens": 208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4587340338743387}}
{"text": "/*\n * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\n#define BOOST_TEST_MAIN\n\n#define BOOST_TEST_MODULE akimaspline_test\n\n// Standard includes\n#include <iostream>\n\n// Third party includes\n#include <boost/test/unit_test.hpp>\n\n// Local VOTCA includes\n#include \"votca/tools/akimaspline.h\"\n\nusing namespace votca::tools;\n\nBOOST_AUTO_TEST_SUITE(akimaspline_test)\n\nBOOST_AUTO_TEST_CASE(interpolate_test) {\n\n  int size = 80;\n  Eigen::VectorXd x = Eigen::VectorXd::Zero(size);\n  Eigen::VectorXd y = Eigen::VectorXd::Zero(size);\n  for (int i = 0; i < size; ++i) {\n    x(i) = 0.25 * i;\n    y(i) = std::sin(x(i));\n  }\n  AkimaSpline cspline;\n  cspline.setBCInt(0);\n  cspline.Interpolate(x, y);\n\n  Eigen::VectorXd rs = Eigen::VectorXd::Zero(10);\n  rs << 0.45, 0.47, 0.8, 0.75, 0.6, 0.4, 0.9, 0.55, 0, 0;\n  Eigen::VectorXd values_ref = Eigen::VectorXd::Zero(10);\n  values_ref << 0.434362, 0.452449, 0.717761, 0.681639, 0.564937, 0.388734,\n      0.783279, 0.52316, 0, 0;\n  Eigen::VectorXd derivatives_ref = Eigen::VectorXd::Zero(10);\n  derivatives_ref << 0.906562, 0.902216, 0.698382, 0.747323, 0.818045, 0.918909,\n      0.615268, 0.854075, 1.02038, 1.02038;\n  Eigen::VectorXd values = cspline.Calculate(rs);\n  Eigen::VectorXd derivatives = cspline.CalculateDerivative(rs);\n\n  bool equal_val = values_ref.isApprox(values, 1e-5);\n\n  if (!equal_val) {\n    std::cout << \"result value\" << std::endl;\n    std::cout << values.transpose() << std::endl;\n    std::cout << \"ref value\" << std::endl;\n    std::cout << values_ref.transpose() << std::endl;\n  }\n  BOOST_CHECK_EQUAL(equal_val, true);\n\n  bool equal_derivative = derivatives_ref.isApprox(derivatives, 1e-5);\n\n  if (!equal_derivative) {\n    std::cout << \"result value\" << std::endl;\n    std::cout << derivatives.transpose() << std::endl;\n    std::cout << \"ref value\" << std::endl;\n    std::cout << derivatives_ref.transpose() << std::endl;\n  }\n  BOOST_CHECK_EQUAL(equal_derivative, true);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "8769b3585f61b49e7cfc78ac3e8c03683387bacd", "size": 2542, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/tests/test_akimaspline.cc", "max_stars_repo_name": "MrTheodor/tools", "max_stars_repo_head_hexsha": "9bb95454a188e827bdf25a6de8302cde70355ecb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/tests/test_akimaspline.cc", "max_issues_repo_name": "MrTheodor/tools", "max_issues_repo_head_hexsha": "9bb95454a188e827bdf25a6de8302cde70355ecb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tests/test_akimaspline.cc", "max_forks_repo_name": "MrTheodor/tools", "max_forks_repo_head_hexsha": "9bb95454a188e827bdf25a6de8302cde70355ecb", "max_forks_repo_licenses": ["Apache-2.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.3827160494, "max_line_length": 80, "alphanum_fraction": 0.6872541306, "num_tokens": 759, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4587340338743387}}
{"text": "\n#include <qlo/objects/obj_defaultbasket.hpp>\n\n#include <ql/currencies/europe.hpp>\n#include <ql/experimental/credit/basket.hpp>\n#include <boost/make_shared.hpp>\n\nQuantLibAddin::Basket::Basket(\n    const boost::shared_ptr<reposit::ValueObject>& properties,\n            // BEGIN typemap rp_tm_default\n            std::vector< std::string > const &IssuerNames,\n            std::vector< boost::shared_ptr< QuantLib::Issuer > > const &Issuers,\n            std::vector< QuantLib::Real > const &Notionals,\n            QuantLib::Date const &ReferenceDate,\n            QuantLib::Real AttachmentRatio,\n            QuantLib::Real DettachmentRatio,\n            bool Amortizing,\n            // END   typemap rp_tm_default\n    bool permanent) : reposit::LibraryObject<QuantLib::Basket>(properties, permanent) {\n\n        QL_REQUIRE(IssuerNames.size() == Issuers.size(), \n            \"Different number of names and issuers.\");\n\n        std::vector<QuantLib::DefaultProbKey> contractTriggers(\n            IssuerNames.size(), \n            QuantLib::NorthAmericaCorpDefaultKey(QuantLib::EURCurrency(),\n                QuantLib::SeniorSec, \n                QuantLib::Period(),\n                1. // amount threshold\n            ));\n\n        boost::shared_ptr<QuantLib::Pool> pool(new QuantLib::Pool());\n        for(QuantLib::Size i=0; i<IssuerNames.size(); i++)\n                pool->add(IssuerNames[i], *Issuers[i], contractTriggers[i]);\n        libraryObject_ = \n            boost::make_shared<QuantLib::Basket>(\n                QuantLib::Basket(ReferenceDate, IssuerNames, Notionals, pool,\n                    AttachmentRatio, DettachmentRatio));\n}\n", "meta": {"hexsha": "7d092fabb3c790ecbb452616162d87394a7b9058", "size": 1632, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "qlo/objects/obj_defaultbasket_hw.cpp", "max_stars_repo_name": "eehlers/QuantLibAddin", "max_stars_repo_head_hexsha": "bcbd9d1c0e7a4f4ce608470c6576d6e772305980", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2016-07-13T14:05:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T15:15:17.000Z", "max_issues_repo_path": "qlo/objects/obj_defaultbasket_hw.cpp", "max_issues_repo_name": "eehlers/QuantLibAddin", "max_issues_repo_head_hexsha": "bcbd9d1c0e7a4f4ce608470c6576d6e772305980", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "qlo/objects/obj_defaultbasket_hw.cpp", "max_forks_repo_name": "eehlers/QuantLibAddin", "max_forks_repo_head_hexsha": "bcbd9d1c0e7a4f4ce608470c6576d6e772305980", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2016-01-28T07:18:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-15T03:48:52.000Z", "avg_line_length": 40.8, "max_line_length": 87, "alphanum_fraction": 0.6200980392, "num_tokens": 383, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4587340271730578}}
{"text": "/*=============================================================================\r\n    Copyright (c) 2017 Paul Fultz II\r\n    rotate_lazy.cpp\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#include <boost/hof/lazy.hpp>\r\n#include <boost/hof/placeholders.hpp>\r\n#include <boost/hof/rotate.hpp>\r\n\r\nint main() {\r\n    auto i = (boost::hof::rotate(boost::hof::_1 - boost::hof::_2) * boost::hof::_1)(3, 6);\r\n    (void)i;\r\n}\r\n", "meta": {"hexsha": "be35aae82b1e0c38010913e33ebef20b1b462366", "size": 607, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/hof/test/fail/rotate_lazy.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": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/hof/test/fail/rotate_lazy.cpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-04T18:00:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-04T18:00:00.000Z", "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/hof/test/fail/rotate_lazy.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 40.4666666667, "max_line_length": 91, "alphanum_fraction": 0.4876441516, "num_tokens": 136, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4587049518396029}}
{"text": "#define HAVE_SINGLEPRECISION_MATH\n#define _CRT_SECURE_NO_WARNINGS\n#define COIN_DLL\n#define SOWIN_DLL\n#define HAVE_INT8_T\n#include <Inventor/Win/SoWin.h>\n#include <Inventor/Win/viewers/SoWinExaminerViewer.h>\n#include <Inventor/nodes/SoSphere.h>\n#include <Inventor/nodes/SoTransform.h>\n#include <Inventor/nodes/SoMaterial.h>\n#include <Eigen/Dense>\n#include \"glm/glm.hpp\"\n#include \"glm/ext/scalar_constants.inl\"\n#include \"GMM.h\"\n\n#include \"Mesh.h\"\n#include \"Painter.h\"\n#include <string>\n#include <cstring>\n#include <queue>\n#include <chrono>\n#include <functional>\n#include <cmath>\n#include <fstream>\n#include <stack>\n#include <set>\n#include <algorithm>\n#include <random>\n\n//using Eigen::MatrixXd;\nusing namespace Eigen;\n\nclass Ray\n{\npublic:\n\tRay();\n\tRay(glm::vec3 origin, glm::vec3 direction) : Origin(origin), Direction(direction){}\n\t~Ray();\n\tglm::vec3 Origin,\n\t\t\tDirection;\n};\n\nRay::Ray(){}\n\nRay::~Ray(){}\n\nclass RayHitInfo\n{\npublic:\n\tRayHitInfo();\n\t~RayHitInfo();\n\tRay Ray;\n\tglm::vec3 Normal,\n\t\tWo,\n\t\tWi,\n\t\tPoint;\n\tfloat T, U, V;\n\tbool IsHit;\n\tint HitMaterialID;\n};\n\nRayHitInfo::RayHitInfo(){}\n\n\nRayHitInfo::~RayHitInfo(){}\n\n\nclass BBox\n{\npublic:\n\tglm::vec3 Min, Max, Center;\n\tBBox();\n\t~BBox();\n\tbool Intersect(const Ray& ray) const;\n};\n\nBBox::BBox(){}\nBBox::~BBox(){}\nbool BBox::Intersect(const Ray& ray) const\n{\n\tconst glm::vec3 inverseDir = 1.0f / ray.Direction;\n\tconst glm::vec3 invMin = (Min - ray.Origin) * inverseDir;\n\tconst glm::vec3 invMax = (Max - ray.Origin) * inverseDir;\n\tconst glm::vec3 t0 = glm::min(invMin, invMax);\n\tconst glm::vec3 t1 = glm::max(invMin, invMax);\n\tfloat tmin = t0.x;\n\tfloat tmax = t1.x;\n\ttmin = std::max(tmin, std::max(t0.y, t0.z));\n\ttmax = std::min(tmax, std::min(t1.y, t1.z));\n\treturn tmin <= tmax;\n}\n\nclass Object\n{\npublic:\n\tObject();\n\t~Object();\n\tTriangle* Triangle;\n\tBBox BoundingBox;\n};\n\nObject::Object() {};\nObject::~Object() {};\n\n\nclass BVH\n{\npublic:\n\tBVH();\n\tBVH(std::vector<Object*>& triangles, const Mesh* mesh, int currentAxis);\n\t~BVH();\n\tbool Intersect(Ray& ray, const Mesh* mesh, double& tmin, RayHitInfo& rayHitInfo);\n\tBBox CalculateBoundingBox();\n\tBVH * LeftNode;\n\tBVH * RightNode;\n\tBBox BoundingBox;\n\tTriangle * ShapeObject;\n\tbool IsLeaf;\n};\n\nBVH::BVH()\n{\n\tLeftNode = nullptr;\n\tRightNode = nullptr;\n\tShapeObject = nullptr;\n\tBoundingBox = BBox();\n}\nBVH::~BVH(){}\n\nbool compareBBoxX(Object* o1, Object* o2) {\n\treturn (o1->BoundingBox.Center.x < o2->BoundingBox.Center.x);\n}\n\nbool compareBBoxY(Object* o1, Object* o2) {\n\treturn (o1->BoundingBox.Center.y < o2->BoundingBox.Center.y);\n}\n\nbool compareBBoxZ(Object* o1, Object* o2) {\n\treturn (o1->BoundingBox.Center.z < o2->BoundingBox.Center.z);\n}\n\nBVH::BVH(std::vector<Object*>& triangles, const Mesh* mesh, int currentAxis)\n{\n\tif(triangles.size() == 1)\n\t{\n\t\tShapeObject = triangles[0]->Triangle;\n\t\tBoundingBox = triangles[0]->BoundingBox;\n\t\tIsLeaf = true;\n\t\treturn;\n\t}\n\tIsLeaf = false;\n\tint axis = (currentAxis % 3);\n\tauto trianglesSorted = triangles;\n\tif(axis == 0){\n\t\tstd::sort(trianglesSorted.begin(), trianglesSorted.end(), compareBBoxX);\n\t}\n\telse if(axis == 1){\n\t\tstd::sort(trianglesSorted.begin(), trianglesSorted.end(), compareBBoxY);\n\t}\n\telse{\n\t\tstd::sort(trianglesSorted.begin(), trianglesSorted.end(), compareBBoxZ);\n\t}\n\tstd::vector<Object*> leftObjects, rightObjects;\n\t\n\tfor (auto it = trianglesSorted.begin(); it != trianglesSorted.begin() + trianglesSorted.size() / 2; ++it)\n\t{\n\t\tleftObjects.push_back(*it);\t\n\t}\n\tfor (auto it = trianglesSorted.begin() + trianglesSorted.size() / 2; it != trianglesSorted.end(); ++it) {\n\t\trightObjects.push_back(*it);\n\t}\n\tLeftNode = new BVH(leftObjects, mesh, axis + 1);\n\tRightNode = new BVH(rightObjects, mesh, axis + 1);\n\tBoundingBox.Min.x = std::min(LeftNode->BoundingBox.Min.x, RightNode->BoundingBox.Min.x);\n\tBoundingBox.Min.y = std::min(LeftNode->BoundingBox.Min.y, RightNode->BoundingBox.Min.y);\n\tBoundingBox.Min.z = std::min(LeftNode->BoundingBox.Min.z, RightNode->BoundingBox.Min.z);\n\tBoundingBox.Max.x = std::max(LeftNode->BoundingBox.Max.x, RightNode->BoundingBox.Max.x);\n\tBoundingBox.Max.y = std::max(LeftNode->BoundingBox.Max.y, RightNode->BoundingBox.Max.y);\n\tBoundingBox.Max.z = std::max(LeftNode->BoundingBox.Max.z, RightNode->BoundingBox.Max.z);\n\tBoundingBox.Center.x = (BoundingBox.Min.x + BoundingBox.Max.x) * 0.5f;\n\tBoundingBox.Center.y = (BoundingBox.Min.y + BoundingBox.Max.y) * 0.5f;\n\tBoundingBox.Center.z = (BoundingBox.Min.z + BoundingBox.Max.z) * 0.5f;\n\treturn;\n}\n\nbool BVH::Intersect(Ray &ray, const Mesh* mesh, double &tmin, RayHitInfo& rayHitInfo)\n{\n\tif (BoundingBox.Intersect(ray))\n\t{\n\t\tif (IsLeaf)\n\t\t{\n\t\t\tconst glm::vec3 v1(mesh->verts[ShapeObject->v1i]->coords[0],\n\t\t\t\t\t\tmesh->verts[ShapeObject->v1i]->coords[1],\n\t\t\t\t\t\tmesh->verts[ShapeObject->v1i]->coords[2]);\n\t\t\tconst glm::vec3 v2(mesh->verts[ShapeObject->v2i]->coords[0],\n\t\t\t\tmesh->verts[ShapeObject->v2i]->coords[1],\n\t\t\t\tmesh->verts[ShapeObject->v2i]->coords[2]);\n\t\t\tconst glm::vec3 v3(mesh->verts[ShapeObject->v3i]->coords[0],\n\t\t\t\tmesh->verts[ShapeObject->v3i]->coords[1],\n\t\t\t\tmesh->verts[ShapeObject->v3i]->coords[2]);\n\t\t\tconst glm::vec3 v1v2 = v2 - v1;\n\t\t\tconst glm::vec3 v1v3 = v3 - v1;\n\t\t\tconst glm::vec3 p = glm::cross(ray.Direction, v1v3);\n\t\t\tconst double d = glm::dot(v1v2, p);\n\t\t\tif(abs(d) < 0){ return false; }\n\t\t\tconst glm::vec3 t = ray.Origin - v1;\n\t\t\tconst double u = glm::dot(t, p) * (1.0 / d);\n\t\t\tif(u < 0.0f || u > 1.0f){return false;}\n\t\t\tconst glm::vec3 q = glm::cross(t, v1v2);\n\t\t\tconst double v = glm::dot(ray.Direction, q) * (1.0f / d);\n\t\t\tif (v < 0.0f || u + v > 1.0f) { return false; }\n\t\t\tdouble dist = glm::dot(v1v3, q) * (1.0 / d);\n\t\t\tif (dist < 0) { return false; }\n\t\t\tif(dist <= tmin)\n\t\t\t{\n\t\t\t\tglm::vec3 normalAtIntersection = -glm::normalize(glm::cross(v1v2, v1v3));\t//inwards facing normal\n\t\t\t\tfloat dotBetween = glm::dot(ray.Direction, normalAtIntersection);\n\t\t\t\tif(glm::degrees(glm::acos(dotBetween)) >= 90.0f)\t// termination condition for same direction facing normals\n\t\t\t\t{\n\t\t\t\t\t// add termination condition for rays (from paper)\t\n\t\t\t\t\ttmin = dist;\n\t\t\t\t\trayHitInfo.T = tmin;\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false;\n\t\t\t//return ShapeObject->Shape->Intersect(ray, tmin, rayHitInfo);\n\t\t}\n\t\tRayHitInfo leftHitInfo, rightHitInfo;\n\t\tbool leftHit = LeftNode == nullptr ? false : LeftNode->Intersect(ray, mesh, tmin, leftHitInfo);\n\t\tbool rightHit = RightNode == nullptr ? false : RightNode->Intersect(ray, mesh, tmin, rightHitInfo);\n\t\tif (leftHit && rightHit)\n\t\t{\n\t\t\trayHitInfo = leftHitInfo.T < rightHitInfo.T ? leftHitInfo : rightHitInfo;\n\t\t\ttmin = rayHitInfo.T;\n\t\t\treturn true;\n\t\t}\n\t\trayHitInfo = leftHit ? leftHitInfo : rayHitInfo;\n\t\trayHitInfo = rightHit ? rightHitInfo : rayHitInfo;\n\t\tif (leftHit || rightHit)\n\t\t{\n\t\t\ttmin = rayHitInfo.T;\n\t\t}\n\t\treturn (leftHit || rightHit);\n\t}\n\treturn false;\n}\n\nBBox BVH::CalculateBoundingBox()\n{\n\treturn BBox();\n}\n\n\n\nint main(int, char ** argv)\n{\n\n\tHWND window = SoWin::init(argv[0]);\n\tSoWinExaminerViewer * viewer = new SoWinExaminerViewer(window);\n\tSoSeparator * root = new SoSeparator;\n\troot->ref();\n\tMesh* mesh = new Mesh();\n\tPainter* painter = new Painter();\n\t// load mesh\n\tchar* x = (char*)malloc(strlen(\"man.off\") + 1); \n\tstrcpy(x, \"man.off\");\n\tmesh->loadOff(x);\n\n\tconst int numVertices = mesh->verts.size();\n\n\tvector<glm::vec3> normals(mesh->verts.size());\n\tvector<glm::vec3> centroids(mesh->verts.size());\n\tvector<glm::vec3> directions(mesh->verts.size());\n\tvector<glm::vec3> negatedNormals(mesh->verts.size());\n\tvector<vector<Ray>> rays(mesh->verts.size());\n\n\t//vector<glm::vec3> normals(mesh->tris.size());\n\t//vector<glm::vec3> centroids(mesh->tris.size());\n\t//vector<glm::vec3> directions(mesh->tris.size());\n\t//vector<glm::vec3> negatedNormals(mesh->tris.size());\n\t//vector<vector<Ray>> rays(mesh->tris.size());\n\n\tfor (unsigned i = 0; i < normals.size(); ++i) {\n\t\tnormals[i] = glm::vec3(0,0,0);\n\t}\n\tstd::vector<BBox> boundingBoxes(mesh->tris.size());\n\tstd::vector<Object*> objects(mesh->tris.size());\n#pragma omp parallel for\n\tfor (int i = 0; i < mesh->tris.size(); ++i) \n\t{\n\t\tint v1Index = (mesh->tris[i]->v1i);\n\t\tint v2Index = (mesh->tris[i]->v2i);\n\t\tint v3Index = (mesh->tris[i]->v3i);\n\t\tglm::vec3 v1(mesh->verts[v1Index]->coords[0], mesh->verts[v1Index]->coords[1], mesh->verts[v1Index]->coords[2]);\n\t\tglm::vec3 v2(mesh->verts[v2Index]->coords[0], mesh->verts[v2Index]->coords[1], mesh->verts[v2Index]->coords[2]);\n\t\tglm::vec3 v3(mesh->verts[v3Index]->coords[0], mesh->verts[v3Index]->coords[1], mesh->verts[v3Index]->coords[2]);\n\t\tglm::vec3 v1v2 = v2 - v1;\n\t\tglm::vec3 v1v3 = v3 - v1;\n\t\tglm::vec3 p = glm::cross(v1v2, v1v3);\n\t\tnormals[v1Index] += p;\n\t\tnormals[v2Index] += p;\n\t\tnormals[v3Index] += p;\n\t\tBBox triangleBox; // bounding box for acceleration\n\t\ttriangleBox.Center = glm::vec3((v1.x + v2.x + v3.x) / 3.0,\n\t\t\t(v1.y + v2.y + v3.y) / 3.0,\n\t\t\t(v1.z + v2.z + v3.z) / 3.0f);\n\t\ttriangleBox.Min = glm::vec3(std::min(std::min(v1.x, v2.x), v3.x),\n\t\t\tstd::min(std::min(v1.y, v2.y), v3.y),\n\t\t\tstd::min(std::min(v1.z, v2.z), v3.z));\n\t\ttriangleBox.Max = glm::vec3(std::max(std::max(v1.x, v2.x), v3.x),\n\t\t\tstd::max(std::max(v1.y, v2.y), v3.y),\n\t\t\tstd::max(std::max(v1.z, v2.z), v3.z));\n\t\tboundingBoxes[i] = triangleBox;\n\t\tobjects[i] = new Object();\n\t\tobjects[i]->Triangle = mesh->tris[i];\n\t\tobjects[i]->BoundingBox = boundingBoxes[i];\n\t}\n\n\tBVH bvhNode(objects, mesh, 0);\n\n\tfor (unsigned i = 0; i < normals.size(); ++i) {\n\t\tnormals[i] = glm::normalize(normals[i]);\n\t}\n\n\tstd::mt19937 generator;\n\tstd::uniform_real_distribution<float> distribution(0.0f, 1.0f);\n#pragma omp parallel for\n\tfor(int i = 0; i < mesh->verts.size(); ++i)\n\t{\n\t\tglm::vec3 normal(0, 0, 0);\n\t\tglm::vec3 vx(mesh->verts[i]->coords[0], mesh->verts[i]->coords[1], mesh->verts[i]->coords[2]);\n\t\tcentroids[i] = vx;\n\t\tnormal = glm::normalize(normal);\n\t\tnegatedNormals[i] = -normals[i];\n\t\trays[i].resize(30);\n\t\tfor(unsigned j = 0; j < rays[i].size(); ++j)\n\t\t{\n\t\t\t// rejection sampling, over the unit sphere, reject the ones that are not in cone\n\t\t\tbool accepted = false;\n\t\t\twhile(!accepted)\n\t\t\t{\n\t\t\t\t// take samples over the unit sphere\n\t\t\t\tfloat z = distribution(generator) * 2.0f - 1.0f;\t// z uniformly distributed btw [-1, 1]\n\t\t\t\tfloat t = distribution(generator) * 2.0f * glm::pi<float>();\t// t uniformly distributed btw [0, 2pi)\n\t\t\t\tfloat r = sqrt(1.0f - z * z);\n\t\t\t\tfloat xx = r * cos(t);\n\t\t\t\tfloat y = r * sin(t);\n\t\t\t\tglm::vec3 sampledVec(xx, y, z);\n\t\t\t\tfloat dotProduct = glm::dot(glm::normalize(negatedNormals[i]), glm::normalize(sampledVec));\n\t\t\t\tfloat angleBetween = glm::acos(dotProduct);\t// vector lengths are 1 since they are normals & normalized\n\t\t\t\tif(glm::degrees(angleBetween) <= 60.0f)\t//accept the sample\n\t\t\t\t{\n\t\t\t\t\trays[i][j].Direction = glm::normalize(sampledVec);\n\t\t\t\t\taccepted = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\trays[i][j].Origin = centroids[i] + rays[i][j].Direction * (float)1e-6;\t// some epsilon for robustness in intersection tests\n\t\t}\n\t\tdirections[i] = rays[i][0].Direction;\n\t\tcentroids[i] = rays[i][0].Origin;\n\t}\n\tvector<vector<float>> rayDistances(rays.size());\n\t#pragma omp parallel for\n\tfor(int i = 0; i < rays.size(); ++i)\n\t{\n\t\tfor(unsigned j = 0; j < rays[i].size(); ++j)\n\t\t{\n\t\t\t//bool isHit = false;\n\t\t\tdouble tmin = DBL_MAX;\n\t\t\tRayHitInfo info;\n\t\t\tif(bvhNode.Intersect(rays[i][j], mesh, tmin, info))\n\t\t\t{\n\t\t\t\t//isHit = true;\n\t\t\t\trayDistances[i].push_back(tmin);\n\t\t\t}\n\t\t\t//for(unsigned k = 0; k < mesh->tris.size(); ++k)\n\t\t\t//{\n\t\t\t//\tconst glm::vec3 v1(mesh->verts[mesh->tris[k]->v1i]->coords[0],\n\t\t\t//\t\tmesh->verts[mesh->tris[k]->v1i]->coords[1],\n\t\t\t//\t\tmesh->verts[mesh->tris[k]->v1i]->coords[2]);\n\t\t\t//\tconst glm::vec3 v2(mesh->verts[mesh->tris[k]->v2i]->coords[0],\n\t\t\t//\t\tmesh->verts[mesh->tris[k]->v2i]->coords[1],\n\t\t\t//\t\tmesh->verts[mesh->tris[k]->v2i]->coords[2]);\n\t\t\t//\tconst glm::vec3 v3(mesh->verts[mesh->tris[k]->v3i]->coords[0],\n\t\t\t//\t\tmesh->verts[mesh->tris[k]->v3i]->coords[1],\n\t\t\t//\t\tmesh->verts[mesh->tris[k]->v3i]->coords[2]);\n\t\t\t//\tconst glm::vec3 v1v2 = v2 - v1;\n\t\t\t//\tconst glm::vec3 v1v3 = v3 - v1;\n\t\t\t//\tconst glm::vec3 p = glm::cross(rays[i][j].Direction, v1v3);\n\t\t\t//\tconst double d = glm::dot(v1v2, p);\n\t\t\t//\tif(abs(d) < 0){ continue; }\n\t\t\t//\tconst glm::vec3 t = rays[i][j].Origin - v1;\n\t\t\t//\tconst double u = glm::dot(t, p) * (1.0 / d);\n\t\t\t//\tif(u < 0.0f || u > 1.0f){continue;}\n\t\t\t//\tconst glm::vec3 q = glm::cross(t, v1v2);\n\t\t\t//\tconst double v = glm::dot(rays[i][j].Direction, q) * (1.0f / d);\n\t\t\t//\tif (v < 0.0f || u + v > 1.0f) { continue; }\n\t\t\t//\tdouble dist = glm::dot(v1v3, q) * (1.0 / d);\n\t\t\t//\tif (dist < 0) { continue; }\n\t\t\t//\tif(dist <= tmin)\n\t\t\t//\t{\n\t\t\t//\t\tglm::vec3 normalAtIntersection = -glm::normalize(glm::cross(v1v2, v1v3));\t//inwards facing normal\n\t\t\t//\t\tfloat dotBetween = glm::dot(rays[i][j].Direction, normalAtIntersection);\n\t\t\t//\t\tif(glm::degrees(glm::acos(dotBetween)) >= 90.0f)\t// termination condition for same direction facing normals\n\t\t\t//\t\t{\n\t\t\t//\t\t\t// add termination condition for rays (from paper)\t\n\t\t\t//\t\t\tisHit = true;\n\t\t\t//\t\t\ttmin = dist;\n\t\t\t//\t\t}\n\t\t\t//\t}\t\t\n\t\t\t//}\n\t\t\t//if(isHit)\n\t\t\t//{\n\t\t\t//\trayDistances[i].push_back(tmin);\n\t\t\t//}\n\t\t}\n\t}\n\tvector<float> sdf;\n\tfor(unsigned i = 0; i < rayDistances.size(); ++i)\n\t{\n\t\tif(rayDistances[i].empty())\n\t\t{\n\t\t\tsdf.push_back(0.0f);\n\t\t\tcontinue;\n\t\t}\n\t\telse if(rayDistances[i].size() == 1)\n\t\t{\n\t\t\tsdf.push_back(rayDistances[i][0]);\n\t\t\tcontinue;\n\t\t}\n\t\tstd::sort(rayDistances[i].begin(), rayDistances[i].end());\n\t\tfloat mean = 0;\n\t\tfloat variance = 0;\n\t\tfor(unsigned j = 0; j < rayDistances[i].size(); ++j)\n\t\t{\n\t\t\tmean += rayDistances[i][j] / (float)rayDistances[i].size();\n\t\t}\n\t\tfor(unsigned j = 0; j < rayDistances[i].size(); ++j)\n\t\t{\n\t\t\tvariance += (rayDistances[i][j] - mean) * (rayDistances[i][j] - mean);\n\t\t}\n\t\tvariance /= (float)rayDistances[i].size();\n\t\tfloat stdDev = glm::sqrt(variance);\n\t\tfloat rightMax = rayDistances[i][rayDistances[i].size() / 2] + stdDev; // 1 std dev away from median\n\t\tfloat leftMax = std::max(0.0f, rayDistances[i][rayDistances[i].size() / 2] - stdDev);\n\t\tfloat sum = 0.0f;\n\t\tfloat numElementsInSum = 0.0f;\n\t\tfor(unsigned j = 0; j < rayDistances[i].size(); ++j)\n\t\t{\n\t\t\tif(rayDistances[i][j] <= rightMax && rayDistances[i][j] >= leftMax)\n\t\t\t{\n\t\t\t\tnumElementsInSum += 1.0f;\n\t\t\t\tsum += rayDistances[i][j];\n\t\t\t}\n\t\t}\n\t\tsdf.push_back(sum / numElementsInSum);\n\t}\n\tfloat minSdf = FLT_MAX;\n\tfloat maxSdf = FLT_MIN;\n\tfor(unsigned i = 0; i < sdf.size(); ++i){\n\t\tif(sdf[i] <= minSdf){\n\t\t\tminSdf = sdf[i];\n\t\t}\n\t\tif (sdf[i] >= maxSdf) {\n\t\t\tmaxSdf = sdf[i];\n\t\t}\n\t}\n\tvector<float> nsdf;\n\tconst float sdfAlpha = 4.0f;\n\tofstream nsdfFile;\n\tnsdfFile.open(\"nsdf.csv\");\n\tfor(unsigned i = 0; i < sdf.size(); ++i)\n\t{\n\t\tfloat normalized = glm::log(((sdf[i] - minSdf) / (maxSdf - minSdf)) * sdfAlpha + 1.0f) / glm::log(sdfAlpha + 1.0f);\n\t\tnsdf.push_back(normalized);\n\t\tnsdfFile << normalized << std::endl;\n\t}\n\tnsdfFile.close();\n\n\tint dimension = 1;\n\tint numData = nsdf.size();\n\tint numIterations = 200;\n\tint numGaussianComponents = 3;\n\n\tGaussian_Mixture_Model GMM = Gaussian_Mixture_Model(\"full\", dimension, numGaussianComponents);\n\tdouble **data = new double*[numData];\n\tfor (int i = 0; i < numData; ++i) {\n\t\tdata[i] = new double[dimension];\n\t\tdata[i][0] = nsdf[i];\n\t}\n\tfor (int i = 0; i < numIterations; ++i) {\n\t\tdouble logLikelihood;\n\t\tif (i == 0) GMM.Initialize(numData, data);\n\t\tlogLikelihood = GMM.Expectaion_Maximization(numData, data);\n\t\tif ((i + 1) % 10 == 0) { \n\t\t\tcout << i + 1 << \" , \" << logLikelihood << std::endl;\n\t\t}\n\t}\n\tcout << std::endl <<\"mean\" << std::endl;\n\tfor (int i = 0; i < numGaussianComponents; ++i) {\n\t\tfor (int j = 0; j < dimension; ++j) {\n\t\t\tcout << GMM.mean[i][j];\n\t\t}\n\t\tcout << std::endl;\n\t}\n\tofstream gmmfile;\n\tgmmfile.open(\"gmmresult.txt\");\n\tstd::vector<int> nsdfSegments(nsdf.size());\n\t/*for (int j = 0; j < numGaussianComponents; ++j) {\n\t\tfor (int i = 0; i < numData; ++i) {\n\t\t\tif (GMM.Classify(data[i]) == j) {\n\t\t\t\tnsdfSegments[i] = GMM.Classify(data[i]);\n\t\t\t\tgmmfile << data[i][0] << \" , \" << GMM.Classify(data[i]) << std::endl;\n \t\t\t}\n\t\t}\n\t}*/\n\tfor (int i = 0; i < numData; ++i) {\n\t\tfor (int j = 0; j < numGaussianComponents; ++j) {\t\n\t\t\tif (GMM.Classify(data[i]) == j) {\n\t\t\t\tnsdfSegments[i] = GMM.Classify(data[i]);\n\t\t\t\tgmmfile << data[i][0] << \" , \" << j << std::endl;\n\t\t\t}\n\t\t}\n\t}\n\tgmmfile.close();\n\tfor (int i = 0; i < numData; ++i) {\n\t\tdelete[] data[i];\n\t}\n\tdelete[] data;\n\t\n\tvector<int> histogramBins(50);\n\tfor (unsigned i = 0; i < histogramBins.size(); ++i) {\n\t\thistogramBins[i] = 0;\n\t}\n\tconst double binStep = 1.0 / (double)histogramBins.size();\n\tfor (unsigned i = 0; i < nsdf.size(); ++i) {\n\t\tauto idx = std::min(glm::floor(nsdf[i] / binStep), histogramBins.size() - 1.0);\n\t\thistogramBins[idx] += 1;\n\t}\n\tofstream histogramFile;\n\thistogramFile.open(\"histogram.csv\");\n\tfor (unsigned i = 0; i < histogramBins.size(); ++i) {\n\t\thistogramFile << (i + 1) * binStep << \",\" << histogramBins[i] << std::endl;\n\t}\n\thistogramFile.close();\n\n\t/*\n\tcout << \"------------------\" << endl << \"Dijkstra\" << endl << \"------------------\" << endl;\n#pragma region dijkstraQuery\n\t\n\tint dijkstraQueryFirst = -1;\n\tint dijkstraQuerySecond = -1;\n\twhile (dijkstraQueryFirst < 0 || dijkstraQueryFirst >= numVertices) {\n\t\tcout << \"Enter first vertex index, [0,\" << numVertices - 1 << \"] :\";\n\t\tcin >> dijkstraQueryFirst;\n\t\tif(dijkstraQueryFirst < 0 || dijkstraQueryFirst >= numVertices){\n\t\t\tcout << \"Invalid index, try again: \";\n\t\t}\n\t}\n\twhile (dijkstraQuerySecond < 0 || dijkstraQuerySecond >= numVertices) {\n\t\tcout << \"Enter second vertex index, [0,\" << numVertices-1 << \"] :\";\n\t\tcin >> dijkstraQuerySecond;\n\t\tif (dijkstraQuerySecond < 0 || dijkstraQuerySecond >= numVertices) {\n\t\t\tcout << \"Invalid index, try again: \";\n\t\t}\n\t}\n\tcout << dijkstraQueryFirst << \" \" << dijkstraQuerySecond << endl;\n\t\n#pragma endregion \n*/\n#pragma region array\n\t/*\n\tdistances.clear();\n\tdistances.resize(numVertices);\n\tfor(auto &d:distances){\n\t\td.resize(numVertices);\n\t}\n\tparents.clear();\n\tparents.resize(numVertices);\n\tt0 = chrono::high_resolution_clock::now();\n\tfor (int i = 0; i < numVertices; ++i) {\n\t\tfloat * arr = nullptr;\n\t\tarr = new float[numVertices];\n\t\tfor(int j = 0; j < numVertices; ++j){\n\t\t\tif (i == j) arr[j] = 0;\n\t\t\telse arr[j] = FLT_MAX;\n\t\t}\n\t\tstd::vector<int> parent(numVertices, -1);\n\t\tparent[i] = i;\n\t\tstd::vector<bool> visited(numVertices, false);\n\t\twhile (true)\n\t\t{\n\t\t\tfloat minDist = FLT_MAX;\n\t\t\tint minDistIndex = -1;\n\t\t\tfor(int k = 0; k < numVertices; k++){\n\t\t\t\tif(!visited[k] && arr[k] < minDist){\n\t\t\t\t\tminDist = arr[k];\n\t\t\t\t\tminDistIndex = k;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (minDistIndex == -1) break;\n\t\t\tint u = minDistIndex;\n\t\t\tvisited[u] = true;\n\t\t\tfor (int l = 0; l < mesh->verts[u]->vertList.size(); ++l){\n\t\t\t\tint v = mesh->verts[u]->vertList[l];\n\t\t\t\tauto v1 = mesh->verts[u]->coords;\n\t\t\t\tauto v2 = mesh->verts[v]->coords;\n\t\t\t\tfloat weight = sqrt((v1[0] - v2[0]) * (v1[0] - v2[0]) +\n\t\t\t\t\t(v1[1] - v2[1]) * (v1[1] - v2[1]) +\n\t\t\t\t\t(v1[2] - v2[2]) * (v1[2] - v2[2]));\n\t\t\t\tif (!visited[v] && (arr[v] > arr[u] + weight)){\n\t\t\t\t\tarr[v] = arr[u] + weight;\n\t\t\t\t\tparent[v] = u;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor(int m = 0; m < numVertices; ++m){\n\t\t\tdistances[i][m] = arr[m];\n\t\t}\n\t\tparents[i] = parent;\n\t\tdelete [] arr;\n\t}\n\tt1 = chrono::high_resolution_clock::now();\n\tduration= chrono::duration_cast<chrono::duration<float>>(t1 - t0).count();\n\tstd::cout << \"Array: \" << duration << \" seconds\"  << endl;\n\t*/\n#pragma endregion \n\t\n#pragma region minHeap\n\t/*\n\tstd::vector<std::vector<float>> distances(numVertices);\n\tstd::vector<std::vector<int>> parents(numVertices);\n\tchrono::high_resolution_clock::time_point t0 = chrono::high_resolution_clock::now();\n\tfor (int i = 0; i < numVertices; ++i) {\n\t\tstd::priority_queue<std::pair<float, int>, std::vector<std::pair<float, int>>, std::greater<>> pq;\n\t\tint source = i;\n\t\tstd::vector<int> parent(numVertices, -1);\n\t\tparent[source] = source;\n\t\tstd::vector<float> dist(numVertices, FLT_MAX);\n\t\tdist[source] = 0;\n\t\tstd::vector<bool> visited(numVertices, false);\n\t\tvisited[source] = true;\n\t\tpq.push(std::make_pair(0, source));\n\t\twhile (!pq.empty())\n\t\t{\n\t\t\tauto top = pq.top();\n\t\t\tint u = top.second;\n\t\t\tvisited[u] = true;\n\t\t\tpq.pop();\n\t\t\tfor (int j = 0; j < mesh->verts[u]->vertList.size(); ++j)\n\t\t\t{\n\t\t\t\tint v = mesh->verts[u]->vertList[j];\n\t\t\t\tauto v1 = mesh->verts[u]->coords;\n\t\t\t\tauto v2 = mesh->verts[v]->coords;\n\t\t\t\tfloat weight = sqrt((v1[0] - v2[0]) * (v1[0] - v2[0]) +\n\t\t\t\t\t(v1[1] - v2[1]) * (v1[1] - v2[1]) +\n\t\t\t\t\t(v1[2] - v2[2]) * (v1[2] - v2[2]));\n\t\t\t\tif (!visited[v] && (dist[v] > dist[u] + weight))\n\t\t\t\t{\n\t\t\t\t\tdist[v] = dist[u] + weight;\n\t\t\t\t\tpq.push(make_pair(dist[v], v));\n\t\t\t\t\tparent[v] = u;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tdistances[i] = dist;\n\t\tparents[i] = parent;\n\t}\n\tchrono::high_resolution_clock::time_point t1 = chrono::high_resolution_clock::now();\n\tauto duration = chrono::duration_cast<chrono::duration<float>>(t1 - t0).count();\n\tstd::cout << \"Dijkstra: \" << duration << \" seconds\" << endl;\n\t*/\n#pragma endregion \n\t/*\n\tstd::vector<int> boundaryIndices;\n\tconst int numEdges = mesh->edges.size();\n\tconst int numTris = mesh->tris.size();\n\tconst auto edges = mesh->edges;\n\tconst auto tris = mesh->tris;\n\tconst auto verts = mesh->verts;\n\tstd::vector<bool> isVertexBoundary(numVertices, false);\n\tint i = 0;\n\tint belongsTo = 0;\n\tt0 = chrono::high_resolution_clock::now();\n\t//#pragma omp parallel for private (i) \n\tfor (i = 0; i < numEdges; ++i) {\n\t\tbelongsTo = 0;\n\t\tconst int ev1 = edges[i]->v1i;\n\t\tconst int ev2 = edges[i]->v2i;\n\t\t//#pragma omp parallel for reduction(+: belongsTo)\n\t\tfor (int j = 0; j < numTris; ++j) {\n\t\t\tconst int tv1 = tris[j]->v1i;\n\t\t\tconst int tv2 = tris[j]->v2i;\n\t\t\tconst int tv3 = tris[j]->v3i;\n\t\t\tif (ev1 == tv1) {\n\t\t\t\tif (ev2 == tv2 || ev2 == tv3) {\n\t\t\t\t\tbelongsTo++;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (ev1 == tv2) {\n\t\t\t\tif (ev2 == tv1 || ev2 == tv2) {\n\t\t\t\t\tbelongsTo++;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (ev1 == tv3) {\n\t\t\t\tif (ev2 == tv1 || ev2 == tv3) {\n\t\t\t\t\tbelongsTo++;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (ev2 == tv1) {\n\t\t\t\tif (ev1 == tv2 || ev1 == tv3) {\n\t\t\t\t\tbelongsTo++;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (ev2 == tv2) {\n\t\t\t\tif (ev1 == tv1 || ev1 == tv3) {\n\t\t\t\t\tbelongsTo++;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (ev2 == tv3) {\n\t\t\t\tif (ev1 == tv1 || ev1 == tv2) {\n\t\t\t\t\tbelongsTo++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (belongsTo == 1) {\n\t\t\tif (!isVertexBoundary[ev1]) boundaryIndices.push_back(ev1);\n\t\t\tif (!isVertexBoundary[ev2]) boundaryIndices.push_back(ev2);\n\t\t\tisVertexBoundary[ev1] = true;\n\t\t\tisVertexBoundary[ev2] = true;\n\t\t}\n\t}\n\tt1 = chrono::high_resolution_clock::now();\n\tduration = chrono::duration_cast<chrono::duration<float>>(t1 - t0).count();\n\tstd::cout << \"Boundary edges: \" << duration << \" seconds\" << endl;\n\n\tstd::vector<int> firstSetIndices;\n\tstd::set<int> firstSet;\n\tfirstSetIndices.push_back(boundaryIndices[0]);\n\tfirstSet.insert(boundaryIndices[0]);\n\twhile(firstSetIndices.size() < boundaryIndices.size())\n\t{\n\t\tconst auto top = firstSetIndices[firstSetIndices.size() - 1];\n\t\tconst auto neighbours = mesh->verts[top]->vertList;\n\t\tstd::vector<int> candidateVertices;\n\t\tfor(int i = 0; i < boundaryIndices.size(); ++i){\n\t\t\tif (boundaryIndices[i] == top) continue;\n\t\t\tbool isVertexCandidate = false;\n\t\t\tfor(int j = 0; j < neighbours.size(); ++j){\n\t\t\t\tif(neighbours[j] == boundaryIndices[i]){\n\t\t\t\t\tcandidateVertices.push_back(boundaryIndices[i]);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfloat minDist = FLT_MAX;\n\t\tint nextIdx = -1;\n\t\tif (candidateVertices.size() == 0) break;\n\t\tfor(int i = 0; i < candidateVertices.size(); ++i){\n\t\t\tif(distances[top][candidateVertices[i]] < minDist){\n\t\t\t\tbool isContained = false;\n\t\t\t\tfor(int j = 0; j < firstSetIndices.size(); ++j){\n\t\t\t\t\tif(firstSetIndices[j] == candidateVertices[i]){\n\t\t\t\t\t\tisContained = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (isContained == false) {\n\t\t\t\t\tminDist = distances[top][candidateVertices[i]] < minDist;\n\t\t\t\t\tnextIdx = candidateVertices[i];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (nextIdx == -1) break;\n\t\tfirstSetIndices.push_back(nextIdx);\n\t\tfirstSet.insert(nextIdx);\n\t}\n\tvector<int> secondSetIndices;\n\tfor(int i = 0; i < boundaryIndices.size(); ++i){\n\t\tif(firstSet.find(boundaryIndices[i]) == firstSet.end()){\n\t\t\tsecondSetIndices.push_back(boundaryIndices[i]);\n\t\t}\n\t}\n\tbool useSymmetricTriangles = false;\n\tif (firstSetIndices.size() != boundaryIndices.size()) {\n\t\tint symmetric = -1;\n\t\twhile (symmetric != 0 && symmetric != 1) {\n\t\t\tstd::cout << \"The mesh contains holes. Should I use symmetric triangles? 0 -> No, 1 -> Yes\" << std::endl;\n\t\t\tcin >> symmetric;\n\t\t}\n\t\tif (symmetric == 0) useSymmetricTriangles = false;\n\t\telse if (symmetric == 1) useSymmetricTriangles = true;\n\t\tfloat bboxFirstMin[3], bboxFirstMax[3], bboxSecondMin[3], bboxSecondMax[3];\n\t\tbboxFirstMin[0] = FLT_MAX; bboxFirstMin[1] = FLT_MAX; bboxFirstMin[2] = FLT_MAX;\n\t\tbboxFirstMax[0] = FLT_MIN; bboxFirstMax[1] = FLT_MIN; bboxFirstMax[2] = FLT_MIN;\n\t\tfor (int i = 0; i < firstSetIndices.size(); ++i) {\n\t\t\tconst auto coords = mesh->verts[firstSetIndices[i]]->coords;\n\t\t\tbboxFirstMin[0] = min(bboxFirstMin[0], coords[0]);\n\t\t\tbboxFirstMin[1] = min(bboxFirstMin[1], coords[1]);\n\t\t\tbboxFirstMin[2] = min(bboxFirstMin[2], coords[2]);\n\t\t\tbboxFirstMax[0] = max(bboxFirstMax[0], coords[0]);\n\t\t\tbboxFirstMax[1] = max(bboxFirstMax[1], coords[1]);\n\t\t\tbboxFirstMax[2] = max(bboxFirstMax[2], coords[2]);\n\t\t}\n\t\tbboxSecondMin[0] = FLT_MAX; bboxSecondMin[1] = FLT_MAX; bboxSecondMin[2] = FLT_MAX;\n\t\tbboxSecondMax[0] = FLT_MIN; bboxSecondMax[1] = FLT_MIN; bboxSecondMax[2] = FLT_MIN;\n\t\tfor (int i = 0; i < secondSetIndices.size(); ++i) {\n\t\t\tconst auto coords = mesh->verts[firstSetIndices[i]]->coords;\n\t\t\tbboxSecondMin[0] = min(bboxSecondMin[0], coords[0]);\n\t\t\tbboxSecondMin[1] = min(bboxSecondMin[1], coords[1]);\n\t\t\tbboxSecondMin[2] = min(bboxSecondMin[2], coords[2]);\n\t\t\tbboxSecondMax[0] = max(bboxSecondMax[0], coords[0]);\n\t\t\tbboxSecondMax[1] = max(bboxSecondMax[1], coords[1]);\n\t\t\tbboxSecondMax[2] = max(bboxSecondMax[2], coords[2]);\n\t\t}\n\n\t\tconst auto bboxFirstXSqr = pow(bboxFirstMin[0] - bboxFirstMax[0], 2.0);\n\t\tconst auto bboxFirstYSqr = pow(bboxFirstMin[1] - bboxFirstMax[1], 2.0);\n\t\tconst auto bboxFirstZSqr = pow(bboxFirstMin[2] - bboxFirstMax[2], 2.0);\n\t\tconst auto bboxFirstLen = sqrt(bboxFirstXSqr + bboxFirstYSqr + bboxFirstZSqr);\n\n\t\tconst auto bboxSecondXSqr = pow(bboxSecondMin[0] - bboxSecondMax[0], 2.0);\n\t\tconst auto bboxSecondYSqr = pow(bboxSecondMin[1] - bboxSecondMax[1], 2.0);\n\t\tconst auto bboxSecondZSqr = pow(bboxSecondMin[2] - bboxSecondMax[2], 2.0);\n\t\tconst auto bboxSecondLen = sqrt(bboxSecondXSqr + bboxSecondYSqr + bboxSecondZSqr);\n\t\t//\n\t\tint abandonSecondaryVertices = -1;\n\t\tstd::cout << \"Should I abandon secondary vertices? 0 -> No, 1 -> Yes\" << endl;\n\t\twhile(abandonSecondaryVertices != 0 && abandonSecondaryVertices != 1)\n\t\t{\n\t\t\tcin >> abandonSecondaryVertices;\n\t\t}\n\t\tif (bboxFirstLen > bboxSecondLen)\n\t\t{\n\t\t\tboundaryIndices = firstSetIndices;\n\t\t\tif (abandonSecondaryVertices == 1) {\n\t\t\t\tfor (int j = 0; j < secondSetIndices.size(); ++j) {\n\t\t\t\t\tisVertexBoundary[secondSetIndices[j]] = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tboundaryIndices = secondSetIndices;\n\t\t\tif (abandonSecondaryVertices == 1) {\n\t\t\t\tfor (int j = 0; j < firstSetIndices.size(); ++j) {\n\t\t\t\t\tisVertexBoundary[firstSetIndices[j]] = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t}\n\t\n\tMatrixXd w(numVertices, numVertices), xx(numVertices, 1), bx(numVertices, 1),\n\t\txy(numVertices, 1), by(numVertices, 1);\n\tt0 = chrono::high_resolution_clock::now();\n\n\tint mode = -1;\n\tstd::cout << \"Enter mode: 0 -> Uniform, 1 -> Harmonic, 2 -> Mean Value\" << endl;\n\twhile(mode != 0 && mode != 1 && mode != 2)\n\t{\n\t\tcin >> mode;\n\t}\n\tif (mode == 0) {\n#pragma region uniform\n\t\tfor (int i = 0; i < numVertices; i++) {\n\t\t\tfor (int j = 0; j < numVertices; j++) {\n\t\t\t\tif (isVertexBoundary[i]) {\n\t\t\t\t\tw(i, j) = i == j ? 1 : 0;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (i == j) {\n\t\t\t\t\tw(i, j) = (double)verts[i]->vertList.size() * -1.0;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tw(i, j) = 0;\n\t\t\t\tfor (const auto &k : verts[i]->vertList) {\n\t\t\t\t\tif (k == j) {\n\t\t\t\t\t\tw(i, j) = 1;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n#pragma endregion\n\t}\n\telse if (mode == 1) {\n#pragma region harmonic\n\t\tstd::vector<int> nonBoundaryIndices;\n\t\tfor (int i = 0; i < numVertices; ++i) {\n\t\t\tif (!isVertexBoundary[i]) {\n\t\t\t\tnonBoundaryIndices.push_back(i);\n\t\t\t}\n\t\t\tfor (int j = 0; j < numVertices; ++j) {\n\t\t\t\tif (isVertexBoundary[i]) {\n\t\t\t\t\tif (i == j) {\n\t\t\t\t\t\tw(i, j) = 1;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tw(i, j) = 0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tw(i, j) = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor (int i = 0; i < nonBoundaryIndices.size(); ++i) {\n\t\t\tconst auto vertexId = nonBoundaryIndices[i];\n\t\t\tconst auto neighbouringEdges = mesh->verts[vertexId]->edgeList;\n\t\t\tconst auto neighbouringTris = mesh->verts[vertexId]->triList;\n\t\t\tif (neighbouringTris.size() < 2) {\n\t\t\t\tstd::cout << \"error on vertex \" << vertexId << \" : non-boundary vertex belongs to less than 2 triangles\" << std::endl;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfor (int j = 0; j < neighbouringEdges.size(); ++j) {\n\t\t\t\tstd::vector<int> triangleIndices;\n\t\t\t\tconst int ev1 = mesh->edges[neighbouringEdges[j]]->v1i;\n\t\t\t\tconst int ev2 = mesh->edges[neighbouringEdges[j]]->v2i;\n\t\t\t\tfor (int k = 0; k < neighbouringTris.size(); ++k) {\n\t\t\t\t\tconst int tv1 = mesh->tris[neighbouringTris[k]]->v1i;\n\t\t\t\t\tconst int tv2 = mesh->tris[neighbouringTris[k]]->v2i;\n\t\t\t\t\tconst int tv3 = mesh->tris[neighbouringTris[k]]->v3i;\n\t\t\t\t\tif (ev1 == tv1) {\n\t\t\t\t\t\tif (ev2 == tv2 || ev2 == tv3) {\n\t\t\t\t\t\t\ttriangleIndices.push_back(neighbouringTris[k]);\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if (ev1 == tv2) {\n\t\t\t\t\t\tif (ev2 == tv1 || ev2 == tv2) {\n\t\t\t\t\t\t\ttriangleIndices.push_back(neighbouringTris[k]);\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if (ev1 == tv3) {\n\t\t\t\t\t\tif (ev2 == tv1 || ev2 == tv3) {\n\t\t\t\t\t\t\ttriangleIndices.push_back(neighbouringTris[k]);\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (ev2 == tv1) {\n\t\t\t\t\t\tif (ev1 == tv2 || ev1 == tv3) {\n\t\t\t\t\t\t\ttriangleIndices.push_back(neighbouringTris[k]);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if (ev2 == tv2) {\n\t\t\t\t\t\tif (ev1 == tv1 || ev1 == tv3) {\n\t\t\t\t\t\t\ttriangleIndices.push_back(neighbouringTris[k]);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if (ev2 == tv3) {\n\t\t\t\t\t\tif (ev1 == tv1 || ev1 == tv2) {\n\t\t\t\t\t\t\ttriangleIndices.push_back(neighbouringTris[k]);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (triangleIndices.size() == 2) {\n\t\t\t\t\tauto firstTriangleIdx = mesh->tris[triangleIndices[0]];\n\t\t\t\t\tauto secondTriangleIdx = mesh->tris[triangleIndices[1]];\n\t\t\t\t\tint firstTriangleOtherVertexIdx = -1;\n\t\t\t\t\tint secondTriangleOtherVertexIdx = -1;\n\t\t\t\t\tif (firstTriangleIdx->v1i == ev1) {\n\t\t\t\t\t\tif (firstTriangleIdx->v2i == ev2) {\n\t\t\t\t\t\t\tfirstTriangleOtherVertexIdx = firstTriangleIdx->v3i;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tfirstTriangleOtherVertexIdx = firstTriangleIdx->v2i;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if (firstTriangleIdx->v2i == ev1) {\n\t\t\t\t\t\tif (firstTriangleIdx->v1i == ev2) {\n\t\t\t\t\t\t\tfirstTriangleOtherVertexIdx = firstTriangleIdx->v3i;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tfirstTriangleOtherVertexIdx = firstTriangleIdx->v1i;\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\tif (firstTriangleIdx->v2i == ev2) {\n\t\t\t\t\t\t\tfirstTriangleOtherVertexIdx = firstTriangleIdx->v1i;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tfirstTriangleOtherVertexIdx = firstTriangleIdx->v2i;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (secondTriangleIdx->v1i == ev1) {\n\t\t\t\t\t\tif (secondTriangleIdx->v2i == ev2) {\n\t\t\t\t\t\t\tsecondTriangleOtherVertexIdx = secondTriangleIdx->v3i;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tsecondTriangleOtherVertexIdx = secondTriangleIdx->v2i;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if (secondTriangleIdx->v2i == ev1) {\n\t\t\t\t\t\tif (secondTriangleIdx->v1i == ev2) {\n\t\t\t\t\t\t\tsecondTriangleOtherVertexIdx = secondTriangleIdx->v3i;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tsecondTriangleOtherVertexIdx = secondTriangleIdx->v1i;\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\tif (secondTriangleIdx->v2i == ev2) {\n\t\t\t\t\t\t\tsecondTriangleOtherVertexIdx = secondTriangleIdx->v1i;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tsecondTriangleOtherVertexIdx = secondTriangleIdx->v2i;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tauto x1 = mesh->verts[ev1]->coords[0] - mesh->verts[firstTriangleOtherVertexIdx]->coords[0];\n\t\t\t\t\tauto y1 = mesh->verts[ev1]->coords[1] - mesh->verts[firstTriangleOtherVertexIdx]->coords[1];\n\t\t\t\t\tauto z1 = mesh->verts[ev1]->coords[2] - mesh->verts[firstTriangleOtherVertexIdx]->coords[2];\n\t\t\t\t\tauto x2 = mesh->verts[ev2]->coords[0] - mesh->verts[firstTriangleOtherVertexIdx]->coords[0];\n\t\t\t\t\tauto y2 = mesh->verts[ev2]->coords[1] - mesh->verts[firstTriangleOtherVertexIdx]->coords[1];\n\t\t\t\t\tauto z2 = mesh->verts[ev2]->coords[2] - mesh->verts[firstTriangleOtherVertexIdx]->coords[2];\n\t\t\t\t\tauto dot = x1 * x2 + y1 * y2 + z1 * z2;\n\t\t\t\t\tauto lenSq1 = x1 * x1 + y1 * y1 + z1 * z1;\n\t\t\t\t\tauto lenSq2 = x2 * x2 + y2 * y2 + z2 * z2;\n\t\t\t\t\tauto angle = acos(dot / sqrt(lenSq1 * lenSq2));\n\t\t\t\t\tif (angle < 0) angle += 2 * M_PI;\n\t\t\t\t\tauto cotangent1 = cos(angle) / sin(angle);\n\t\t\t\t\tx1 = mesh->verts[ev1]->coords[0] - mesh->verts[secondTriangleOtherVertexIdx]->coords[0];\n\t\t\t\t\ty1 = mesh->verts[ev1]->coords[1] - mesh->verts[secondTriangleOtherVertexIdx]->coords[1];\n\t\t\t\t\tz1 = mesh->verts[ev1]->coords[2] - mesh->verts[secondTriangleOtherVertexIdx]->coords[2];\n\t\t\t\t\tx2 = mesh->verts[ev2]->coords[0] - mesh->verts[secondTriangleOtherVertexIdx]->coords[0];\n\t\t\t\t\ty2 = mesh->verts[ev2]->coords[1] - mesh->verts[secondTriangleOtherVertexIdx]->coords[1];\n\t\t\t\t\tz2 = mesh->verts[ev2]->coords[2] - mesh->verts[secondTriangleOtherVertexIdx]->coords[2];\n\t\t\t\t\tdot = x1 * x2 + y1 * y2 + z1 * z2;\n\t\t\t\t\tlenSq1 = x1 * x1 + y1 * y1 + z1 * z1;\n\t\t\t\t\tlenSq2 = x2 * x2 + y2 * y2 + z2 * z2;\n\t\t\t\t\tangle = acos(dot / sqrt(lenSq1 * lenSq2));\n\t\t\t\t\tif (angle < 0) angle += 2 * M_PI;\n\t\t\t\t\tauto cotangent2 = cos(angle) / sin(angle);\n\t\t\t\t\tif (vertexId == ev1) {\n\t\t\t\t\t\tw(ev1, ev2) = (cotangent1 + cotangent2) * 0.5f;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tw(ev2, ev1) = (cotangent1 + cotangent2) * 0.5f;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tstd::cout << \"Vertex \" << vertexId << \" : non-boundary hole vertex belongs to \" << triangleIndices.size() << \" triangles\" << std::endl;\n\t\t\t\t\tif (useSymmetricTriangles) {\n\t\t\t\t\t\tstd::cout << \"But I'll override with symmetric triangle\" << std::endl;\n\t\t\t\t\t\tauto firstTriangleIdx = mesh->tris[triangleIndices[0]];\n\t\t\t\t\t\tint firstTriangleOtherVertexIdx = -1;\n\t\t\t\t\t\tif (firstTriangleIdx->v1i == ev1) {\n\t\t\t\t\t\t\tif (firstTriangleIdx->v2i == ev2) {\n\t\t\t\t\t\t\t\tfirstTriangleOtherVertexIdx = firstTriangleIdx->v3i;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tfirstTriangleOtherVertexIdx = firstTriangleIdx->v2i;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (firstTriangleIdx->v2i == ev1) {\n\t\t\t\t\t\t\tif (firstTriangleIdx->v1i == ev2) {\n\t\t\t\t\t\t\t\tfirstTriangleOtherVertexIdx = firstTriangleIdx->v3i;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tfirstTriangleOtherVertexIdx = firstTriangleIdx->v1i;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tif (firstTriangleIdx->v2i == ev2) {\n\t\t\t\t\t\t\t\tfirstTriangleOtherVertexIdx = firstTriangleIdx->v1i;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tfirstTriangleOtherVertexIdx = firstTriangleIdx->v2i;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tauto x1 = mesh->verts[ev1]->coords[0] - mesh->verts[firstTriangleOtherVertexIdx]->coords[0];\n\t\t\t\t\t\tauto y1 = mesh->verts[ev1]->coords[1] - mesh->verts[firstTriangleOtherVertexIdx]->coords[1];\n\t\t\t\t\t\tauto z1 = mesh->verts[ev1]->coords[2] - mesh->verts[firstTriangleOtherVertexIdx]->coords[2];\n\t\t\t\t\t\tauto x2 = mesh->verts[ev2]->coords[0] - mesh->verts[firstTriangleOtherVertexIdx]->coords[0];\n\t\t\t\t\t\tauto y2 = mesh->verts[ev2]->coords[1] - mesh->verts[firstTriangleOtherVertexIdx]->coords[1];\n\t\t\t\t\t\tauto z2 = mesh->verts[ev2]->coords[2] - mesh->verts[firstTriangleOtherVertexIdx]->coords[2];\n\t\t\t\t\t\tauto dot = x1 * x2 + y1 * y2 + z1 * z2;\n\t\t\t\t\t\tauto lenSq1 = x1 * x1 + y1 * y1 + z1 * z1;\n\t\t\t\t\t\tauto lenSq2 = x2 * x2 + y2 * y2 + z2 * z2;\n\t\t\t\t\t\tauto angle = acos(dot / sqrt(lenSq1 * lenSq2));\n\t\t\t\t\t\tif (angle < 0) {\n\t\t\t\t\t\t\tangle += 2 * M_PI;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tauto cotangent1 = cos(angle) / sin(angle);\n\t\t\t\t\t\tauto cotangent2 = cos(angle) / sin(angle);\n\t\t\t\t\t\tif (vertexId == ev1) {\n\t\t\t\t\t\t\tw(ev1, ev2) = (cotangent1) * 0.5f;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tw(ev2, ev1) = (cotangent1) * 0.5f;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor (int i = 0; i < numVertices; ++i)\n\t\t{\n\t\t\tif (isVertexBoundary[i]) continue;\n\t\t\tdouble sum = 0.0;\n\t\t\tfor (int j = 0; j < numVertices; ++j)\n\t\t\t{\n\t\t\t\tsum += w(i, j);\n\t\t\t}\n\t\t\tw(i, i) = -sum;\n\t\t}\n#pragma endregion\n\t}\n\telse if (mode == 2) {\n#pragma region meanvalueweights\n\t\tstd::vector<int> nonBoundaryIndices;\n\t\tfor (int i = 0; i < numVertices; ++i) {\n\t\t\tif (!isVertexBoundary[i]) {\n\t\t\t\tnonBoundaryIndices.push_back(i);\n\t\t\t}\n\t\t\tfor (int j = 0; j < numVertices; ++j) {\n\t\t\t\tif (isVertexBoundary[i]) {\n\t\t\t\t\tif (i == j) {\n\t\t\t\t\t\tw(i, j) = 1;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tw(i, j) = 0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tw(i, j) = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor (int i = 0; i < nonBoundaryIndices.size(); ++i) {\n\t\t\tconst auto vertexId = nonBoundaryIndices[i];\n\t\t\tconst auto neighbouringEdges = mesh->verts[vertexId]->edgeList;\n\t\t\tconst auto neighbouringTris = mesh->verts[vertexId]->triList;\n\t\t\tif (neighbouringTris.size() < 2) {\n\t\t\t\tstd::cout << \"error on vertex \" << vertexId << \" : non-boundary vertex belongs to less than 2 triangles\" << std::endl;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfor (int j = 0; j < neighbouringEdges.size(); ++j) {\n\t\t\t\tstd::vector<int> triangleIndices;\n\t\t\t\tconst int ev1 = mesh->edges[neighbouringEdges[j]]->v1i;\n\t\t\t\tconst int ev2 = mesh->edges[neighbouringEdges[j]]->v2i;\n\t\t\t\tfor (int k = 0; k < neighbouringTris.size(); ++k) {\n\t\t\t\t\tconst int tv1 = mesh->tris[neighbouringTris[k]]->v1i;\n\t\t\t\t\tconst int tv2 = mesh->tris[neighbouringTris[k]]->v2i;\n\t\t\t\t\tconst int tv3 = mesh->tris[neighbouringTris[k]]->v3i;\n\t\t\t\t\tif (ev1 == tv1) {\n\t\t\t\t\t\tif (ev2 == tv2 || ev2 == tv3) {\n\t\t\t\t\t\t\ttriangleIndices.push_back(neighbouringTris[k]);\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if (ev1 == tv2) {\n\t\t\t\t\t\tif (ev2 == tv1 || ev2 == tv2) {\n\t\t\t\t\t\t\ttriangleIndices.push_back(neighbouringTris[k]);\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if (ev1 == tv3) {\n\t\t\t\t\t\tif (ev2 == tv1 || ev2 == tv3) {\n\t\t\t\t\t\t\ttriangleIndices.push_back(neighbouringTris[k]);\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (ev2 == tv1) {\n\t\t\t\t\t\tif (ev1 == tv2 || ev1 == tv3) {\n\t\t\t\t\t\t\ttriangleIndices.push_back(neighbouringTris[k]);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if (ev2 == tv2) {\n\t\t\t\t\t\tif (ev1 == tv1 || ev1 == tv3) {\n\t\t\t\t\t\t\ttriangleIndices.push_back(neighbouringTris[k]);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if (ev2 == tv3) {\n\t\t\t\t\t\tif (ev1 == tv1 || ev1 == tv2) {\n\t\t\t\t\t\t\ttriangleIndices.push_back(neighbouringTris[k]);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (triangleIndices.size() == 2) {\n\t\t\t\t\tauto firstTriangleIdx = mesh->tris[triangleIndices[0]];\n\t\t\t\t\tauto secondTriangleIdx = mesh->tris[triangleIndices[1]];\n\t\t\t\t\tint firstTriangleOtherVertexIdx = -1;\n\t\t\t\t\tint secondTriangleOtherVertexIdx = -1;\n\t\t\t\t\tif (firstTriangleIdx->v1i == ev1) {\n\t\t\t\t\t\tif (firstTriangleIdx->v2i == ev2) {\n\t\t\t\t\t\t\tfirstTriangleOtherVertexIdx = firstTriangleIdx->v3i;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tfirstTriangleOtherVertexIdx = firstTriangleIdx->v2i;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if (firstTriangleIdx->v2i == ev1) {\n\t\t\t\t\t\tif (firstTriangleIdx->v1i == ev2) {\n\t\t\t\t\t\t\tfirstTriangleOtherVertexIdx = firstTriangleIdx->v3i;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tfirstTriangleOtherVertexIdx = firstTriangleIdx->v1i;\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\tif (firstTriangleIdx->v2i == ev2) {\n\t\t\t\t\t\t\tfirstTriangleOtherVertexIdx = firstTriangleIdx->v1i;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tfirstTriangleOtherVertexIdx = firstTriangleIdx->v2i;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (secondTriangleIdx->v1i == ev1) {\n\t\t\t\t\t\tif (secondTriangleIdx->v2i == ev2) {\n\t\t\t\t\t\t\tsecondTriangleOtherVertexIdx = secondTriangleIdx->v3i;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tsecondTriangleOtherVertexIdx = secondTriangleIdx->v2i;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if (secondTriangleIdx->v2i == ev1) {\n\t\t\t\t\t\tif (secondTriangleIdx->v1i == ev2) {\n\t\t\t\t\t\t\tsecondTriangleOtherVertexIdx = secondTriangleIdx->v3i;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tsecondTriangleOtherVertexIdx = secondTriangleIdx->v1i;\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\tif (secondTriangleIdx->v2i == ev2) {\n\t\t\t\t\t\t\tsecondTriangleOtherVertexIdx = secondTriangleIdx->v1i;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tsecondTriangleOtherVertexIdx = secondTriangleIdx->v2i;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tfloat x1, y1, z1, x2, y2, z2, angle, tangent1, tangent2;\n\t\t\t\t\tif (vertexId == ev1)\n\t\t\t\t\t{\n\t\t\t\t\t\tx1 = mesh->verts[secondTriangleOtherVertexIdx]->coords[0] - mesh->verts[ev1]->coords[0];\n\t\t\t\t\t\ty1 = mesh->verts[secondTriangleOtherVertexIdx]->coords[1] - mesh->verts[ev1]->coords[1];\n\t\t\t\t\t\tz1 = mesh->verts[secondTriangleOtherVertexIdx]->coords[2] - mesh->verts[ev1]->coords[2];\n\t\t\t\t\t\tx2 = mesh->verts[ev2]->coords[0] - mesh->verts[ev1]->coords[0];\n\t\t\t\t\t\ty2 = mesh->verts[ev2]->coords[1] - mesh->verts[ev1]->coords[1];\n\t\t\t\t\t\tz2 = mesh->verts[ev2]->coords[2] - mesh->verts[ev1]->coords[2];\n\t\t\t\t\t\tauto dot = x1 * x2 + y1 * y2 + z1 * z2;\n\t\t\t\t\t\tauto lenSq1 = x1 * x1 + y1 * y1 + z1 * z1;\n\t\t\t\t\t\tauto lenSq2 = x2 * x2 + y2 * y2 + z2 * z2;\n\t\t\t\t\t\tangle = acos(dot / sqrt(lenSq1 * lenSq2));\n\t\t\t\t\t\tif (angle < 0) angle += 2 * M_PI;\n\t\t\t\t\t\ttangent1 = sin(angle * 0.5f) / cos(angle * 0.5f);\n\t\t\t\t\t\tx1 = mesh->verts[firstTriangleOtherVertexIdx]->coords[0] - mesh->verts[ev1]->coords[0];\n\t\t\t\t\t\ty1 = mesh->verts[firstTriangleOtherVertexIdx]->coords[1] - mesh->verts[ev1]->coords[1];\n\t\t\t\t\t\tz1 = mesh->verts[firstTriangleOtherVertexIdx]->coords[2] - mesh->verts[ev1]->coords[2];\n\t\t\t\t\t\tx2 = mesh->verts[ev2]->coords[0] - mesh->verts[ev1]->coords[0];\n\t\t\t\t\t\ty2 = mesh->verts[ev2]->coords[1] - mesh->verts[ev1]->coords[1];\n\t\t\t\t\t\tz2 = mesh->verts[ev2]->coords[2] - mesh->verts[ev1]->coords[2];\n\t\t\t\t\t\tdot = x1 * x2 + y1 * y2 + z1 * z2;\n\t\t\t\t\t\tlenSq1 = x1 * x1 + y1 * y1 + z1 * z1;\n\t\t\t\t\t\tlenSq2 = x2 * x2 + y2 * y2 + z2 * z2;\n\t\t\t\t\t\tangle = acos(dot / sqrt(lenSq1 * lenSq2));\n\t\t\t\t\t\tif (angle < 0) angle += 2 * M_PI;\n\t\t\t\t\t\ttangent2 = sin(angle * 0.5f) / cos(angle * 0.5f);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tx1 = mesh->verts[secondTriangleOtherVertexIdx]->coords[0] - mesh->verts[ev2]->coords[0];\n\t\t\t\t\t\ty1 = mesh->verts[secondTriangleOtherVertexIdx]->coords[1] - mesh->verts[ev2]->coords[1];\n\t\t\t\t\t\tz1 = mesh->verts[secondTriangleOtherVertexIdx]->coords[2] - mesh->verts[ev2]->coords[2];\n\t\t\t\t\t\tx2 = mesh->verts[ev1]->coords[0] - mesh->verts[ev2]->coords[0];\n\t\t\t\t\t\ty2 = mesh->verts[ev1]->coords[1] - mesh->verts[ev2]->coords[1];\n\t\t\t\t\t\tz2 = mesh->verts[ev1]->coords[2] - mesh->verts[ev2]->coords[2];\n\t\t\t\t\t\tauto dot = x1 * x2 + y1 * y2 + z1 * z2;\n\t\t\t\t\t\tauto lenSq1 = x1 * x1 + y1 * y1 + z1 * z1;\n\t\t\t\t\t\tauto lenSq2 = x2 * x2 + y2 * y2 + z2 * z2;\n\t\t\t\t\t\tangle = acos(dot / sqrt(lenSq1 * lenSq2));\n\t\t\t\t\t\tif (angle < 0) angle += 2 * M_PI;\n\t\t\t\t\t\ttangent1 = sin(angle * 0.5f) / cos(angle * 0.5f);\n\t\t\t\t\t\tx1 = mesh->verts[firstTriangleOtherVertexIdx]->coords[0] - mesh->verts[ev2]->coords[0];\n\t\t\t\t\t\ty1 = mesh->verts[firstTriangleOtherVertexIdx]->coords[1] - mesh->verts[ev2]->coords[1];\n\t\t\t\t\t\tz1 = mesh->verts[firstTriangleOtherVertexIdx]->coords[2] - mesh->verts[ev2]->coords[2];\n\t\t\t\t\t\tx2 = mesh->verts[ev1]->coords[0] - mesh->verts[ev2]->coords[0];\n\t\t\t\t\t\ty2 = mesh->verts[ev1]->coords[1] - mesh->verts[ev2]->coords[1];\n\t\t\t\t\t\tz2 = mesh->verts[ev1]->coords[2] - mesh->verts[ev2]->coords[2];\n\t\t\t\t\t\tdot = x1 * x2 + y1 * y2 + z1 * z2;\n\t\t\t\t\t\tlenSq1 = x1 * x1 + y1 * y1 + z1 * z1;\n\t\t\t\t\t\tlenSq2 = x2 * x2 + y2 * y2 + z2 * z2;\n\t\t\t\t\t\tangle = acos(dot / sqrt(lenSq1 * lenSq2));\n\t\t\t\t\t\tif (angle < 0) angle += 2 * M_PI;\n\t\t\t\t\t\ttangent2 = sin(angle * 0.5f) / cos(angle * 0.5f);\n\t\t\t\t\t}\n\t\t\t\t\tauto xsq = pow(mesh->verts[ev1]->coords[0] - mesh->verts[ev2]->coords[0], 2.0);\n\t\t\t\t\tauto ysq = pow(mesh->verts[ev1]->coords[1] - mesh->verts[ev2]->coords[1], 2.0);\n\t\t\t\t\tauto zsq = pow(mesh->verts[ev1]->coords[2] - mesh->verts[ev2]->coords[2], 2.0);\n\t\t\t\t\tauto len = sqrt(xsq + ysq + zsq);\n\t\t\t\t\tif (vertexId == ev1) {\n\t\t\t\t\t\tw(ev1, ev2) = (tangent1 + tangent2) / (2.0f * len);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tw(ev2, ev1) = (tangent1 + tangent2) / (2.0f * len);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tstd::cout << \"Vertex \" << vertexId << \" : non-boundary vertex belongs to \" << triangleIndices.size() << \" triangles\" << std::endl;\n\t\t\t\t\tif (useSymmetricTriangles)\n\t\t\t\t\t{\n\t\t\t\t\t\tstd::cout << \"But I'll override with a symmetric triangle\" << std::endl;\n\t\t\t\t\t\tauto firstTriangleIdx = mesh->tris[triangleIndices[0]];\n\t\t\t\t\t\tint firstTriangleOtherVertexIdx = -1;\n\t\t\t\t\t\tif (firstTriangleIdx->v1i == ev1) {\n\t\t\t\t\t\t\tif (firstTriangleIdx->v2i == ev2) {\n\t\t\t\t\t\t\t\tfirstTriangleOtherVertexIdx = firstTriangleIdx->v3i;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tfirstTriangleOtherVertexIdx = firstTriangleIdx->v2i;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (firstTriangleIdx->v2i == ev1) {\n\t\t\t\t\t\t\tif (firstTriangleIdx->v1i == ev2) {\n\t\t\t\t\t\t\t\tfirstTriangleOtherVertexIdx = firstTriangleIdx->v3i;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tfirstTriangleOtherVertexIdx = firstTriangleIdx->v1i;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tif (firstTriangleIdx->v2i == ev2) {\n\t\t\t\t\t\t\t\tfirstTriangleOtherVertexIdx = firstTriangleIdx->v1i;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tfirstTriangleOtherVertexIdx = firstTriangleIdx->v2i;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfloat x1, y1, z1, x2, y2, z2, angle, tangent1, tangent2;\n\t\t\t\t\t\tif (vertexId == ev1)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tx1 = mesh->verts[firstTriangleOtherVertexIdx]->coords[0] - mesh->verts[ev1]->coords[0];\n\t\t\t\t\t\t\ty1 = mesh->verts[firstTriangleOtherVertexIdx]->coords[1] - mesh->verts[ev1]->coords[1];\n\t\t\t\t\t\t\tz1 = mesh->verts[firstTriangleOtherVertexIdx]->coords[2] - mesh->verts[ev1]->coords[2];\n\t\t\t\t\t\t\tx2 = mesh->verts[ev2]->coords[0] - mesh->verts[ev1]->coords[0];\n\t\t\t\t\t\t\ty2 = mesh->verts[ev2]->coords[1] - mesh->verts[ev1]->coords[1];\n\t\t\t\t\t\t\tz2 = mesh->verts[ev2]->coords[2] - mesh->verts[ev1]->coords[2];\n\t\t\t\t\t\t\tauto dot = x1 * x2 + y1 * y2 + z1 * z2;\n\t\t\t\t\t\t\tauto lenSq1 = x1 * x1 + y1 * y1 + z1 * z1;\n\t\t\t\t\t\t\tauto lenSq2 = x2 * x2 + y2 * y2 + z2 * z2;\n\t\t\t\t\t\t\tangle = acos(dot / sqrt(lenSq1 * lenSq2));\n\t\t\t\t\t\t\tif (angle < 0) angle += 2 * M_PI;\n\t\t\t\t\t\t\ttangent1 = sin(angle * 0.5f) / cos(angle * 0.5f);\n\t\t\t\t\t\t\tx1 = mesh->verts[firstTriangleOtherVertexIdx]->coords[0] - mesh->verts[ev1]->coords[0];\n\t\t\t\t\t\t\ty1 = mesh->verts[firstTriangleOtherVertexIdx]->coords[1] - mesh->verts[ev1]->coords[1];\n\t\t\t\t\t\t\tz1 = mesh->verts[firstTriangleOtherVertexIdx]->coords[2] - mesh->verts[ev1]->coords[2];\n\t\t\t\t\t\t\tx2 = mesh->verts[ev2]->coords[0] - mesh->verts[ev1]->coords[0];\n\t\t\t\t\t\t\ty2 = mesh->verts[ev2]->coords[1] - mesh->verts[ev1]->coords[1];\n\t\t\t\t\t\t\tz2 = mesh->verts[ev2]->coords[2] - mesh->verts[ev1]->coords[2];\n\t\t\t\t\t\t\tdot = x1 * x2 + y1 * y2 + z1 * z2;\n\t\t\t\t\t\t\tlenSq1 = x1 * x1 + y1 * y1 + z1 * z1;\n\t\t\t\t\t\t\tlenSq2 = x2 * x2 + y2 * y2 + z2 * z2;\n\t\t\t\t\t\t\tangle = acos(dot / sqrt(lenSq1 * lenSq2));\n\t\t\t\t\t\t\tif (angle < 0) angle += 2 * M_PI;\n\t\t\t\t\t\t\ttangent2 = sin(angle * 0.5f) / cos(angle * 0.5f);\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\tx1 = mesh->verts[firstTriangleOtherVertexIdx]->coords[0] - mesh->verts[ev2]->coords[0];\n\t\t\t\t\t\t\ty1 = mesh->verts[firstTriangleOtherVertexIdx]->coords[1] - mesh->verts[ev2]->coords[1];\n\t\t\t\t\t\t\tz1 = mesh->verts[firstTriangleOtherVertexIdx]->coords[2] - mesh->verts[ev2]->coords[2];\n\t\t\t\t\t\t\tx2 = mesh->verts[ev1]->coords[0] - mesh->verts[ev2]->coords[0];\n\t\t\t\t\t\t\ty2 = mesh->verts[ev1]->coords[1] - mesh->verts[ev2]->coords[1];\n\t\t\t\t\t\t\tz2 = mesh->verts[ev1]->coords[2] - mesh->verts[ev2]->coords[2];\n\t\t\t\t\t\t\tauto dot = x1 * x2 + y1 * y2 + z1 * z2;\n\t\t\t\t\t\t\tauto lenSq1 = x1 * x1 + y1 * y1 + z1 * z1;\n\t\t\t\t\t\t\tauto lenSq2 = x2 * x2 + y2 * y2 + z2 * z2;\n\t\t\t\t\t\t\tangle = acos(dot / sqrt(lenSq1 * lenSq2));\n\t\t\t\t\t\t\tif (angle < 0) angle += 2 * M_PI;\n\t\t\t\t\t\t\ttangent1 = sin(angle * 0.5f) / cos(angle * 0.5f);\n\t\t\t\t\t\t\tx1 = mesh->verts[firstTriangleOtherVertexIdx]->coords[0] - mesh->verts[ev2]->coords[0];\n\t\t\t\t\t\t\ty1 = mesh->verts[firstTriangleOtherVertexIdx]->coords[1] - mesh->verts[ev2]->coords[1];\n\t\t\t\t\t\t\tz1 = mesh->verts[firstTriangleOtherVertexIdx]->coords[2] - mesh->verts[ev2]->coords[2];\n\t\t\t\t\t\t\tx2 = mesh->verts[ev1]->coords[0] - mesh->verts[ev2]->coords[0];\n\t\t\t\t\t\t\ty2 = mesh->verts[ev1]->coords[1] - mesh->verts[ev2]->coords[1];\n\t\t\t\t\t\t\tz2 = mesh->verts[ev1]->coords[2] - mesh->verts[ev2]->coords[2];\n\t\t\t\t\t\t\tdot = x1 * x2 + y1 * y2 + z1 * z2;\n\t\t\t\t\t\t\tlenSq1 = x1 * x1 + y1 * y1 + z1 * z1;\n\t\t\t\t\t\t\tlenSq2 = x2 * x2 + y2 * y2 + z2 * z2;\n\t\t\t\t\t\t\tangle = acos(dot / sqrt(lenSq1 * lenSq2));\n\t\t\t\t\t\t\tif (angle < 0) angle += 2 * M_PI;\n\t\t\t\t\t\t\ttangent2 = sin(angle * 0.5f) / cos(angle * 0.5f);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tauto xsq = pow(mesh->verts[ev1]->coords[0] - mesh->verts[ev2]->coords[0], 2.0);\n\t\t\t\t\t\tauto ysq = pow(mesh->verts[ev1]->coords[1] - mesh->verts[ev2]->coords[1], 2.0);\n\t\t\t\t\t\tauto zsq = pow(mesh->verts[ev1]->coords[2] - mesh->verts[ev2]->coords[2], 2.0);\n\t\t\t\t\t\tauto len = sqrt(xsq + ysq + zsq);\n\t\t\t\t\t\tif (vertexId == ev1) {\n\t\t\t\t\t\t\tw(ev1, ev2) = (tangent1 + tangent2) / (2.0f * len);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tw(ev2, ev1) = (tangent1 + tangent2) / (2.0f * len);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor (int i = 0; i < numVertices; ++i)\n\t\t{\n\t\t\tif (isVertexBoundary[i]) continue;\n\t\t\tdouble sum = 0.0;\n\t\t\tfor (int j = 0; j < numVertices; ++j)\n\t\t\t{\n\t\t\t\tsum += w(i, j);\n\t\t\t}\n\t\t\tw(i, i) = -sum;\n\t\t}\n#pragma endregion\n\t}\n\tt1 = chrono::high_resolution_clock::now();\n\tduration = chrono::duration_cast<chrono::duration<float>>(t1 - t0).count();\n\tstd::cout << \"Creating W matrix: \" << duration << \" seconds\" << endl;\n\tfor (int i = 0; i < numVertices; ++i) {\n\t\txx(i, 0) = 0; xy(i, 0) = 0; bx(i, 0) = 0; by(i, 0) = 0; // init\n\t}\n\n\tt0 = chrono::high_resolution_clock::now();\n\tstd::vector<std::pair<float, float>> diskPoints;\n\tauto stepSize = M_PI * 2.0 / (double)(boundaryIndices.size());\n\tdouble currentPointAngle = 0;\n\t//while (currentPointAngle <= M_PI * 2.0)\n\twhile (diskPoints.size() != boundaryIndices.size())\n\t{\n\t\tdiskPoints.push_back(std::make_pair(std::cos(currentPointAngle), std::sin(currentPointAngle)));\n\t\tcurrentPointAngle += stepSize;\n\t}\n\t//int currentDiskPoint = diskPoints.size() - 1;\n\tint currentDiskPoint = 0;\n\tint selectedIndex = boundaryIndices[0];\n\tstd::vector<bool> isVertexBoundaryBackup = isVertexBoundary;\n\tbx(selectedIndex, 0) = diskPoints[0].first;\n\tby(selectedIndex, 0) = diskPoints[0].second;\n\tisVertexBoundary[selectedIndex] = false;\n\tcurrentDiskPoint++;\n\tint minBoundaryIdx = -1;\n\twhile(currentDiskPoint < boundaryIndices.size() )\n\t{\n\t\tfloat minDist = FLT_MAX;\n\t\tminBoundaryIdx = -1;\n\t\tauto neighbours = mesh->verts[selectedIndex]->vertList;\n\t\tfor(int i = 0; i < neighbours.size(); ++i)\n\t\t{\n\t\t\tauto neighbourIdx = neighbours[i];\n\t\t\tif(isVertexBoundary[neighbourIdx])\n\t\t\t{\n\t\t\t\tif(distances[selectedIndex][neighbourIdx] < minDist)\n\t\t\t\t{\n\t\t\t\t\tminDist = distances[selectedIndex][neighbourIdx];\n\t\t\t\t\tminBoundaryIdx = neighbourIdx;\n\t\t\t\t\tisVertexBoundary[neighbourIdx] = false;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\t\t}\n\t\tif (minBoundaryIdx != -1) {\n\t\t\tbx(minBoundaryIdx, 0) = diskPoints[currentDiskPoint].first;\n\t\t\tby(minBoundaryIdx, 0) = diskPoints[currentDiskPoint].second;\n\t\t\tselectedIndex = minBoundaryIdx;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tbx(selectedIndex, 0) = diskPoints[currentDiskPoint].first;\n\t\t\tby(selectedIndex, 0) = diskPoints[currentDiskPoint].second;\n\t\t}\n\t\tcurrentDiskPoint++;\n\t}\n\tcurrentDiskPoint = 0;\n\tt1 = chrono::high_resolution_clock::now();\n\tduration = chrono::duration_cast<chrono::duration<float>>(t1 - t0).count();\n\tstd::cout << \"Mapping on disk: \" << duration << \" seconds\" << endl;\n\n\t// checking for degenerate cases for debugging, namely bx and by values\n\tfor(int i = 0; i < numVertices; ++i)\n\t{\n\t\tif(isVertexBoundaryBackup[i] && (bx(i, 0) == 0.0 && by(i, 0) == 0.0))\n\t\t{\n\t\t\tstd::cout << \"WARNING BOUNDARY VERTEX \" << i << \" HAS 0 VAL\" << std::endl;\n\t\t}\n\t\telse if(isVertexBoundaryBackup[i] == false && (bx(i, 0) != 0.0 || by(i, 0) != 0))\n\t\t{\n\t\t\tstd::cout << \"WARNING NON-BOUNDARY VERTEX \" << i << \" HAS NONZERO VAL\" << std::endl;\n\t\t}\n\t}\n\n\t//std::ofstream file(\"matrices.txt\");\n\n\t//file << \"bx\" << std::endl;\n\t//file << bx << std::endl;\n\t//file << \"by\" << std::endl;\n\t//file << by << std::endl;\n\t//file << \"w\" << std::endl;\n\t//file << w << std::endl;;\n\n\tcurrentDiskPoint = 0;\n\tauto winverse = w.inverse();\n\tt0 = chrono::high_resolution_clock::now();\n\t//\txx = w.bdcSvd(ComputeThinU | ComputeThinV).solve(bx);\n\t\t//xx = w.colPivHouseholderQr().solve(bx);\n\txx = winverse * bx;\n\t\t//xx = w.ldlt().solve(bx);\n\tt1 = chrono::high_resolution_clock::now();\n\tduration = chrono::duration_cast<chrono::duration<float>>(t1 - t0).count();\n\tstd::cout << \"Solving xx: \" << duration << \" seconds\" << endl;\n\tt0 = chrono::high_resolution_clock::now();\n\t//xy = w.colPivHouseholderQr().solve(by);\n\txy = winverse * by;\n\t//xy = w.bdcSvd(ComputeThinU | ComputeThinV).solve(by);\n\t//xy = w.ldlt().solve(by);\n\tt1 = chrono::high_resolution_clock::now();\n\tduration = chrono::duration_cast<chrono::duration<float>>(t1 - t0).count();\n\tstd::cout << \"Solving xy: \" << duration << \" seconds\" << endl;\n\t//file << \"x\" << std::endl;\n\t//file << xx << std::endl;\n\t//file << \"y\" << std::endl;\n\t//file << xy << std::endl;\n\t//file.close();\n\t/*\n\tFILE * pFile;\n\tpFile = fopen(\"dijkstra_out.txt\", \"w\");\n\n\tfor(int i = 0; i < numVertices; ++i)\n\t{\n\t\tfor(int j = 0; j < numVertices; j++)\n\t\t{\n\t\t\tfprintf(pFile, \"%g \",distances[i][j]);\n\t\t}\n\t\tfprintf(pFile, \"\\n\");\n\t}\n\tfclose(pFile);\n\t*/\n\t//int p1 = 0, p2 = 200;\n\t/*\n\tint p1 = -1, p2 = -1;\n\twhile (p1 < 0 || p1 >= numVertices) {\n\t\tcout << \"Enter first vertex index for query, [0,\" << numVertices - 1 << \"] :\";\n\t\tcin >> p1;\n\t\tif (p1 < 0 || p1 >= numVertices) {\n\t\t\tcout << \"Invalid index, try again: \";\n\t\t}\n\t}\n\twhile (p2 < 0 || p2 >= numVertices) {\n\t\tcout << \"Enter second vertex index for query, [0,\" << numVertices - 1 << \"] :\";\n\t\tcin >> p2;\n\t\tif (p2 < 0 || p2 >= numVertices) {\n\t\t\tcout << \"Invalid index, try again: \";\n\t\t}\n\t}\n\t\n\tstd::vector<int> shortestPathVertices;\n\tshortestPathVertices.push_back(p2);\t// add dest node\n\tint p2Parent = parents[p1][p2];\n\twhile(p2Parent != p1){\n\t\tshortestPathVertices.push_back(p2Parent);\n\t\tp2Parent = parents[p1][p2Parent];\n\t}\n\tshortestPathVertices.push_back(p1);\t// add source node\n\tcout << \"Shortest path vertices for queried indices \" << p1 << \", \" << p2 << endl;\n\tfor(const auto &spv:shortestPathVertices){\n\t\tcout << spv << \" \";\n\t}\n\tcout << endl;\n\t\n#pragma region fps\n\tcout << \"------------------\" << endl << \"FPS\" << endl << \"------------------\" << endl;\n\tt0 = chrono::high_resolution_clock::now();\n\tstd::vector<int> fpsVertices;\n\tint randomIndex = rand() % numVertices;\n\tfpsVertices.push_back(randomIndex);\n\tfloat maxDist = FLT_MIN;\n\tint maxDistIndex = -1;\n\tfor (int i = 0; i < numVertices; ++i) {\n\t\tif (distances[randomIndex][i] > maxDist) {\n\t\t\tmaxDist = distances[randomIndex][i];\n\t\t\tmaxDistIndex = i;\n\t\t}\n\t}\n\tfpsVertices.push_back(maxDistIndex);\n\tcout << \"Random seed and farthest vertex to it are: \";\n\tfor (int i = 0; i < fpsVertices.size(); ++i) {\n\t\tcout << fpsVertices[i] << \" \";\n\t}\n\tcout << endl;\n\tconst int numSamples = 100;\n\twhile (fpsVertices.size() < numSamples) {\n\t\tstd::vector<pair<int, int>> associations;\t// which vertex is associated with whom\t(i, j)\n\t\tfor (int i = 0; i < numVertices; ++i) {\n\t\t\tfloat minDist = FLT_MAX;\n\t\t\tint minIndex = -1;\n\t\t\tfor (int j = 0; j < fpsVertices.size(); ++j) {\n\t\t\t\tif (i == fpsVertices[j]) {\n\t\t\t\t\tminIndex = -1;\n\t\t\t\t\tminDist = FLT_MAX;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (distances[i][fpsVertices[j]] < minDist) {\n\t\t\t\t\tminDist = distances[i][fpsVertices[j]];\n\t\t\t\t\tminIndex = fpsVertices[j];\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (minIndex != -1) {\n\t\t\t\tassociations.push_back(make_pair(i, minIndex));\n\t\t\t}\t\t// pair.first is in the elements to be sampled, pair.second are already sampled\n\t\t}\n\t\t// get the argmax out of all\n\t\tfloat maxGeoDist = FLT_MIN;\n\t\tint maxIndex = -1;\n\t\tfor (int i = 0; i < associations.size(); ++i) {\n\t\t\tif (distances[associations[i].first][associations[i].second] > maxGeoDist) {\n\t\t\t\tmaxIndex = associations[i].first;\n\t\t\t\tmaxGeoDist = distances[associations[i].first][associations[i].second];\n\t\t\t}\n\t\t}\n\t\tfpsVertices.push_back(maxIndex);\n\t}\n\tmesh->samples = fpsVertices;\n\tt1 = chrono::high_resolution_clock::now();\n\tduration = chrono::duration_cast<chrono::duration<float>>(t1 - t0).count();\n\tstd::cout << endl << \"Sampling points: \" << duration << \" seconds\" << endl;\n#pragma endregion\n\n#pragma region geodesic isocurves\n\tcout << \"------------------\" << endl << \"Geodesic Isocurves\" << endl << \"------------------\" << endl;\n\tint seedIndex = -1;\n\twhile (seedIndex < 0 || seedIndex >= numVertices) {\n\t\tcout << \"Enter the seed index, [0,\" << numVertices - 1 << \"] :\";\n\t\tcin >> seedIndex;\n\t\tif (seedIndex < 0 || seedIndex >= numVertices) {\n\t\t\tcout << \"Invalid seed index, try again: \";\n\t\t}\n\t}\n\tint k = -1;\n\twhile (k < 0 || k >= numVertices) {\n\t\tcout << \"Enter the number of bins, [0,\" << numVertices - 1 << \"] :\";\n\t\tcin >> k;\n\t\tif (k < 0 || k >= numVertices) {\n\t\t\tcout << \"Invalid bin count, try again: \";\n\t\t}\n\t}\n\tt0 = chrono::high_resolution_clock::now();\n\tfloat maxVertexDist = FLT_MIN;\n\tfor(int i = 0; i < numVertices; ++i){\n\t\tif(distances[seedIndex][i] > maxVertexDist){\n\t\t\tmaxVertexDist = distances[seedIndex][i];\n\t\t}\n\t}\n\tfloat d = maxVertexDist / (float)k;\n\tint numTris = mesh->tris.size();\n\tauto triangles = mesh->tris;\n\tstd::vector<float> histogramBins(k);\n\tstd::vector<std::vector<pair<std::vector<float>, std::vector<float>>>> isoCurveLines(k);\n\tfor(int i = 1; i <= k; ++i){\n\t\tfloat radius = i * d;\n\t\tfloat isoCurveLength = 0.0f;\n\t\tfor(int j = 0; j < numTris; ++j){\n\t\t\tauto distV1 = distances[seedIndex][triangles[j]->v1i];\n\t\t\tauto distV2 = distances[seedIndex][triangles[j]->v2i];\n\t\t\tauto distV3 = distances[seedIndex][triangles[j]->v3i];\n\t\t\tif ((distV1 < radius && distV2 < radius && distV3 < radius)\n\t\t\t\t|| (distV1 > radius && distV2 > radius && distV3 > radius)) continue;\n\t\t\tstd::vector<int> lt, gt;\n\t\t\tdistV1 <= radius ? lt.push_back(triangles[j]->v1i) : gt.push_back(triangles[j]->v1i);\n\t\t\tdistV2 <= radius ? lt.push_back(triangles[j]->v2i) : gt.push_back(triangles[j]->v2i);\n\t\t\tdistV3 <= radius ? lt.push_back(triangles[j]->v3i) : gt.push_back(triangles[j]->v3i);\n\t\t\tif (lt.empty() || gt.empty()) continue;\n\t\t\tfloat a1, a2, g0, g1, g2;\n\t\t\tstd::vector<float> p1(3), p2(3);\n\t\t\tfloat * v0, * v1, * v2;\n\t\t\tif(lt.size() < gt.size()){\n\t\t\t\tg0 = distances[seedIndex][lt[0]];\n\t\t\t\tg1 = distances[seedIndex][gt[0]];\n\t\t\t\tg2 = distances[seedIndex][gt[1]];\n\t\t\t\ta1 = fabs(radius - g0) / fabs(g1 - g0);\n\t\t\t\ta2 = fabs(radius - g0) / fabs(g2 - g0);\n\t\t\t\tv0 = mesh->verts[lt[0]]->coords;\n\t\t\t\tv1 = mesh->verts[gt[0]]->coords;\n\t\t\t\tv2 = mesh->verts[gt[1]]->coords;\n\t\t\t\tp1[0] = (1.0f - a1) * v0[0] + a1 * v1[0];\n\t\t\t\tp1[1] = (1.0f - a1) * v0[1] + a1 * v1[1];\n\t\t\t\tp1[2] = (1.0f - a1) * v0[2] + a1 * v1[2];\n\t\t\t\tp2[0] = (1.0f - a2) * v0[0] + a2 * v2[0];\n\t\t\t\tp2[1] = (1.0f - a2) * v0[1] + a2 * v2[1];\n\t\t\t\tp2[2] = (1.0f - a2) * v0[2] + a2 * v2[2];\n\t\t\t}\n\t\t\telse if(lt.size() > gt.size()){\n\t\t\t\tg0 = distances[seedIndex][lt[0]];\n\t\t\t\tg1 = distances[seedIndex][lt[1]];\n\t\t\t\tg2 = distances[seedIndex][gt[0]];\n\t\t\t\ta1 = fabs(radius - g0) / fabs(g2 - g0);\n\t\t\t\ta2 = fabs(radius - g1) / fabs(g2 - g1);\n\t\t\t\tv0 = mesh->verts[lt[0]]->coords;\n\t\t\t\tv1 = mesh->verts[lt[1]]->coords;\n\t\t\t\tv2 = mesh->verts[gt[0]]->coords;\n\t\t\t\tp1[0] = (1.0f - a1) * v0[0] + a1 * v2[0];\n\t\t\t\tp1[1] = (1.0f - a1) * v0[1] + a1 * v2[1];\n\t\t\t\tp1[2] = (1.0f - a1) * v0[2] + a1 * v2[2];\n\t\t\t\tp2[0] = (1.0f - a2) * v1[0] + a2 * v2[0];\n\t\t\t\tp2[1] = (1.0f - a2) * v1[1] + a2 * v2[1];\n\t\t\t\tp2[2] = (1.0f - a2) * v1[2] + a2 * v2[2];\n\t\t\t}\n\t\t\tfloat p1p2dist = sqrt((p1[0] - p2[0]) * (p1[0] - p2[0]) +\n\t\t\t\t\t\t\t\t(p1[1] - p2[1]) * (p1[1] - p2[1]) + \n\t\t\t\t\t\t\t\t(p1[2] - p2[2]) * (p1[2] - p2[2]));\n\t\t\tisoCurveLength += p1p2dist;\n\t\t\tisoCurveLines[i - 1].push_back(make_pair(p1, p2));\n\t\t}\n\t\thistogramBins[i - 1] = isoCurveLength;\n\t}\n\tt1 = chrono::high_resolution_clock::now();\n\tduration = chrono::duration_cast<chrono::duration<float>>(t1 - t0).count();\n\tstd::cout << endl << \"Geodesic isocurve: \" << duration << \" seconds \" << endl;\n#pragma endregion\n\tfloat globalMaxDist = FLT_MIN;\n\tfor (int i = 0; i < distances.size(); ++i) {\n\t\tfor (int j = 0; j < distances[i].size(); ++j) {\n\t\t\tif (distances[i][j] > globalMaxDist) {\n\t\t\t\tglobalMaxDist = distances[i][j];\n\t\t\t}\n\t\t}\n\t}\n\t*/\n\t\n\t//root->addChild( painter->getShapeSep(mesh) );\n\t//root->addChild(painter->getSdfShapeSep(mesh, nsdf));\n\troot->addChild(painter->getSdfSegmentedShapeSep(mesh, nsdf, nsdfSegments));\n\t//root->addChild(painter->getRayCastRaysShapeSep(mesh, centroids, directions));\n\tint visualization = 1;\n\twhile (visualization <= 0 || visualization > 4) {\n\t\tcout << endl << \"Select the visualization: 1 -> Dijkstra, 2 -> Geodesic Isocurves, 3 -> Farthest Point Sampling, 4 -> Boundary Vertices :\";\n\t\tcin >> visualization;\n\t\tif (visualization <= 0 || visualization > 3) {\n\t\t\tcout << \"Invalid visualization query, try again: \" << endl;\n\t\t}\n\t}\n\tif(visualization == 1){\n\t\t//root->addChild(painter->getShortestPathSep(mesh, shortestPathVertices));\t// visualization for shortest path vertices\n\t}\n\telse if(visualization == 2){\n\t\t//root->addChild(painter->getGeodesicIsoCurveSep(mesh, isoCurveLines, histogramBins, seedIndex));\n\t}\n\telse if (visualization == 3) {\n\t\troot->addChild(painter->getSpheresSep(mesh, 0, 0, 1.0f)); // visualization for sampled points\n\t}\n\telse if(visualization == 4)\n\t{\n\t\t//mesh->samples = boundaryIndices;\n\t\t//root->addChild(painter->getSpheresSep(mesh, 0, 0, 1.0f));\n\t\t//root->addChild(painter->getParametrizedMeshSep(mesh, xx, xy));\n\n\t}\n\t\n\t\n\t//viewer->setSize(SbVec2s(800, 600));\n\tviewer->setSize(SbVec2s(1280, 760));\n\tviewer->setSceneGraph(root);\n\tviewer->show();\n\n\tSoWin::show(window);\n\tSoWin::mainLoop();\n\tdelete viewer;\n\troot->unref();\n\treturn 0;\n}\n", "meta": {"hexsha": "7781d80d7af89a93d9c45174e31759f9e9f3a947", "size": 60713, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Main.cpp", "max_stars_repo_name": "serkan3k/dgp", "max_stars_repo_head_hexsha": "232ab3b2bc68d6d9474957eadd7707c73c2bfa0e", "max_stars_repo_licenses": ["MIT"], "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": "serkan3k/dgp", "max_issues_repo_head_hexsha": "232ab3b2bc68d6d9474957eadd7707c73c2bfa0e", "max_issues_repo_licenses": ["MIT"], "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": "serkan3k/dgp", "max_forks_repo_head_hexsha": "232ab3b2bc68d6d9474957eadd7707c73c2bfa0e", "max_forks_repo_licenses": ["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.3399321267, "max_line_length": 141, "alphanum_fraction": 0.6051092847, "num_tokens": 20490, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.4587049455260385}}
{"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_PREDICATES_FUNCTIONS_SIMD_COMMON_IS_NOT_INFINITE_HPP_INCLUDED\n#define BOOST_SIMD_PREDICATES_FUNCTIONS_SIMD_COMMON_IS_NOT_INFINITE_HPP_INCLUDED\n\n#include <boost/simd/predicates/functions/is_not_infinite.hpp>\n#include <boost/simd/include/functions/simd/abs.hpp>\n#include <boost/simd/include/functions/simd/is_not_equal.hpp>\n#include <boost/simd/include/constants/inf.hpp>\n#include <boost/simd/sdk/meta/as_logical.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT         (is_not_infinite_, tag::cpu_,\n                                    (A0)(X),\n                                    ((simd_<arithmetic_<A0>,X>))\n                                   )\n  {\n    typedef typename meta::as_logical<A0>::type result_type;\n    inline result_type operator()(const A0&) const\n    {\n      return boost::simd::True<result_type>();\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT         (is_not_infinite_, tag::cpu_,\n                                    (A0)(X),\n                                    ((simd_<floating_<A0>,X>))\n                                   )\n  {\n    typedef typename meta::as_logical<A0>::type result_type;\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(1) { return is_not_equal(abs(a0),boost::simd::Inf<A0>()); }\n  };\n} } }\n#endif\n", "meta": {"hexsha": "22e16a0f7a845c91ca8f1a8cd7e96010b7d585a0", "size": 1772, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/base/include/boost/simd/predicates/functions/simd/common/is_not_infinite.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/predicates/functions/simd/common/is_not_infinite.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/predicates/functions/simd/common/is_not_infinite.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 42.1904761905, "max_line_length": 94, "alphanum_fraction": 0.5586907449, "num_tokens": 380, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.45870494552603847}}
{"text": "/*\n * ----------------- BEGIN LICENSE BLOCK ---------------------------------\n *\n * Copyright (c) 2017 Computer Vision Center (CVC) at the Universitat Autonoma\n * de Barcelona (UAB).\n * Copyright (C) 2019 Intel Corporation\n *\n * SPDX-License-Identifier: MIT\n *\n * ----------------- END LICENSE BLOCK -----------------------------------\n */\n\n#include \"opendrive/geometry/Geometry.h\"\n\n#include \"opendrive/types.hpp\"\n\n#include <boost/array.hpp>\n#include <boost/math/tools/rational.hpp>\n#include <cmath>\n#include <stdexcept>\n\nnamespace opendrive {\nnamespace geometry {\n\nDirectedPoint::DirectedPoint()\n  : location(0, 0)\n  , tangent(0)\n{\n}\nDirectedPoint::DirectedPoint(const Point &point, double t)\n  : location(point)\n  , tangent(t)\n{\n}\nDirectedPoint::DirectedPoint(double x, double y, double t)\n  : location(x, y)\n  , tangent(t)\n{\n}\n\nvoid DirectedPoint::ApplyLateralOffset(double lateral_offset)\n{\n  auto normal_x = -std::sin(tangent);\n  auto normal_y = std::cos(tangent);\n  location.x += lateral_offset * normal_x;\n  location.y += lateral_offset * normal_y;\n}\n\nGeometryType Geometry::GetType() const\n{\n  return _type;\n}\ndouble Geometry::GetLength() const\n{\n  return _length;\n}\ndouble Geometry::GetStartOffset() const\n{\n  return _start_position_offset;\n}\ndouble Geometry::GetHeading() const\n{\n  return _heading;\n}\n\nconst Point &Geometry::GetStartPosition()\n{\n  return _start_position;\n}\n\nGeometry::Geometry(GeometryType type, double start_offset, double length, double heading, const Point &start_pos)\n  : _type(type)\n  , _length(length)\n  , _start_position_offset(start_offset)\n  , _heading(heading)\n  , _start_position(start_pos)\n{\n  if (_length == 0.)\n  {\n    throw std::invalid_argument(\"Geometry of length 0\");\n  }\n}\n\nGeometryLine::GeometryLine(double start_offset, double length, double heading, const Point &start_pos)\n  : Geometry(GeometryType::LINE, start_offset, length, heading, start_pos)\n{\n}\n\nconst DirectedPoint GeometryLine::PosFromDist(const double dist) const\n{\n  DirectedPoint p(_start_position, _heading);\n  p.location.x += dist * std::cos(p.tangent);\n  p.location.y += dist * std::sin(p.tangent);\n  return p;\n}\n\nGeometryArc::GeometryArc(double start_offset, double length, double heading, const Point &start_pos, double curv)\n  : Geometry(GeometryType::ARC, start_offset, length, heading, start_pos)\n  , _curvature(curv)\n{\n}\n\nconst DirectedPoint GeometryArc::PosFromDist(double dist) const\n{\n  if (std::fabs(_curvature) < 1e-15)\n  {\n    // case not supported given the small curvature\n    return DirectedPoint(_start_position, _heading);\n  }\n  const double radius = 1.0 / _curvature;\n  const double theta = _heading - M_PI_2;\n  double x = _start_position.x - radius * (cos(theta) - cos(theta + dist * _curvature));\n  double y = _start_position.y - radius * (sin(theta) - sin(theta + dist * _curvature));\n\n  double tangent = _heading + dist * _curvature;\n\n  DirectedPoint p(x, y, tangent);\n\n  return p;\n}\n\ndouble GeometryArc::GetCurvature() const\n{\n  return _curvature;\n}\n\nGeometryPoly3::GeometryPoly3(\n  double start_offset, double length, double heading, const Point &start_pos, double a, double b, double c, double d)\n  : Geometry(GeometryType::POLY3, start_offset, length, heading, start_pos)\n  , _a{a}\n  , _b{b}\n  , _c{c}\n  , _d{d}\n{\n}\n\nconst DirectedPoint GeometryPoly3::PosFromDist(const double dist) const\n{\n  auto poly = boost::array<double, 4>{{_a, _b, _c, _d}};\n\n  double u = dist;\n  double v = boost::math::tools::evaluate_polynomial(poly, u);\n\n  const double cos_t = std::cos(_heading);\n  const double sin_t = std::sin(_heading);\n\n  double x0 = _start_position.x;\n  double y0 = _start_position.y;\n  double x = u * cos_t - v * sin_t;\n  double y = u * sin_t + v * cos_t;\n\n  auto tangentPoly = boost::array<double, 4>{{_b, 2.0 * _c, 3.0 * _d}};\n\n  double tangentV = boost::math::tools::evaluate_polynomial(tangentPoly, u);\n  double theta = atan2(tangentV, 1.0);\n\n  DirectedPoint point(x0 + x, y0 + y, _heading + theta);\n  return point;\n}\n\nGeometryParamPoly3::GeometryParamPoly3(double start_offset,\n                                       double length,\n                                       double heading,\n                                       const Point &start_pos,\n                                       double aU,\n                                       double bU,\n                                       double cU,\n                                       double dU,\n                                       double aV,\n                                       double bV,\n                                       double cV,\n                                       double dV)\n  : Geometry(GeometryType::PARAMPOLY3, start_offset, length, heading, start_pos)\n  , _aU{aU}\n  , _bU{bU}\n  , _cU{cU}\n  , _dU{dU}\n  , _aV{aV}\n  , _bV{bV}\n  , _cV{cV}\n  , _dV{dV}\n{\n}\n\nconst DirectedPoint GeometryParamPoly3::PosFromDist(const double dist) const\n{\n  double p = std::min(1.0, dist / _length);\n\n  auto polyU = boost::array<double, 4>{{_aU, _bU, _cU, _dU}};\n  auto polyV = boost::array<double, 4>{{_aV, _bV, _cV, _dV}};\n\n  double u = boost::math::tools::evaluate_polynomial(polyU, p);\n  double v = boost::math::tools::evaluate_polynomial(polyV, p);\n\n  const double cos_t = std::cos(_heading);\n  const double sin_t = std::sin(_heading);\n  double x0 = _start_position.x;\n  double y0 = _start_position.y;\n  double x = u * cos_t - v * sin_t;\n  double y = u * sin_t + v * cos_t;\n\n  auto tangentPolyU = boost::array<double, 4>{{_bU, 2.0 * _cU, 3.0 * _dU, 0.0}};\n  auto tangentPolyV = boost::array<double, 4>{{_bV, 2.0 * _cV, 3.0 * _dV, 0.0}};\n\n  double tangentU = boost::math::tools::evaluate_polynomial(tangentPolyU, p);\n  double tangentV = boost::math::tools::evaluate_polynomial(tangentPolyV, p);\n  double theta = atan2(tangentV, tangentU);\n\n  DirectedPoint point(x0 + x, y0 + y, _heading + theta);\n  return point;\n}\n\n} // namespace\n} // namespace\n", "meta": {"hexsha": "052d196268ad7045e47b8442a2558d0e5e33559c", "size": 5852, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ad_map_opendrive_reader/src/geometry/Geometry.cpp", "max_stars_repo_name": "fgolemo/map", "max_stars_repo_head_hexsha": "5af0f99ff781e63ef72192ea714dce295a44298c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ad_map_opendrive_reader/src/geometry/Geometry.cpp", "max_issues_repo_name": "fgolemo/map", "max_issues_repo_head_hexsha": "5af0f99ff781e63ef72192ea714dce295a44298c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ad_map_opendrive_reader/src/geometry/Geometry.cpp", "max_forks_repo_name": "fgolemo/map", "max_forks_repo_head_hexsha": "5af0f99ff781e63ef72192ea714dce295a44298c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-10-27T11:09:30.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-27T11:09:30.000Z", "avg_line_length": 27.2186046512, "max_line_length": 117, "alphanum_fraction": 0.6368762816, "num_tokens": 1612, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.45870494552603847}}
{"text": "#include \"BitmaskProgramExecutor.h\"\n\n#include <AdventOfCodeCommon/DisableLibraryWarningsMacros.h>\n\n__BEGIN_LIBRARIES_DISABLE_WARNINGS\n#include <boost/algorithm/string.hpp>\n\n#include <numeric>\n__END_LIBRARIES_DISABLE_WARNINGS\n\nnamespace AdventOfCode\n{\nnamespace Year2020\n{\nnamespace Day14\n{\n\nInstruction::Instruction(InstructionType type, std::string arg, uint64_t addr)\n    : type{type}\n    , arg{std::move(arg)}\n    , addr{addr}\n{\n\n}\n\nInstruction::Instruction(InstructionType type, std::string arg)\n    : type{type}\n    , arg{std::move(arg)}\n    , addr{boost::none}\n{\n\n}\n\nBitmaskProgramExecutor::BitmaskProgramExecutor(std::vector<Instruction> instructions)\n    : m_instructions{std::move(instructions)}\n{\n\n}\n\nvoid BitmaskProgramExecutor::execute()\n{\n    for (const auto& instruction : m_instructions)\n    {\n        executeInstruction(instruction);\n    }\n}\n\nuint64_t BitmaskProgramExecutor::getSumOfValuesInMemory() const\n{\n    return std::accumulate(m_memoryLocationToValue.cbegin(), m_memoryLocationToValue.cend(), 0ull, [](auto acc, const auto& elem)\n                           {\n                               return acc + elem.second;\n                           });\n}\n\nvoid BitmaskProgramExecutor::executeMemInstruction(const Instruction& instruction)\n{\n    uint64_t value = std::stoull(instruction.arg);\n    value &= m_andBitmask;\n    value |= m_orBitmask;\n\n    m_memoryLocationToValue[instruction.addr.get()] = value;\n}\n\nvoid BitmaskProgramExecutor::executeMaskInstruction(const Instruction& instruction)\n{\n    std::string orBitmaskString = instruction.arg;\n    boost::replace_all(orBitmaskString, \"X\", \"0\");\n    m_orBitmask = std::stoull(orBitmaskString, nullptr, 2);\n\n    std::string andBitmaskString = instruction.arg;\n    boost::replace_all(andBitmaskString, \"X\", \"1\");\n    m_andBitmask = std::stoull(andBitmaskString, nullptr, 2);\n}\n\nvoid BitmaskProgramExecutor::executeInstruction(const Instruction& instruction)\n{\n    if (instruction.type == InstructionType::MEM)\n    {\n        executeMemInstruction(instruction);\n    }\n    else\n    {\n        executeMaskInstruction(instruction);\n    }\n}\n\nvoid BitmaskDecoderProgramExecutor::executeMemInstruction(const Instruction& instruction)\n{\n    uint64_t baseAddress = instruction.addr.get();\n    baseAddress |= m_orBitmask;\n\n    std::vector<uint64_t> addresses = getAllAddresses(baseAddress);\n    uint64_t value = std::stoull(instruction.arg);\n\n    for (auto address : addresses)\n    {\n        m_memoryLocationToValue[address] = value;\n    }\n}\n\nvoid BitmaskDecoderProgramExecutor::executeMaskInstruction(const Instruction& instruction)\n{\n    BitmaskProgramExecutor::executeMaskInstruction(instruction);\n\n    std::string digitToValue = instruction.arg;\n    std::reverse(digitToValue.begin(), digitToValue.end());\n    m_floatingDigits.clear();\n    for (size_t i = 0; i < digitToValue.size(); ++i)\n    {\n        if (digitToValue[i] == 'X')\n        {\n            m_floatingDigits.push_back(i);\n        }\n    }\n}\n\nstd::vector<uint64_t> BitmaskDecoderProgramExecutor::getAllAddresses(uint64_t baseAddress) const\n{\n    std::vector<uint64_t> allAddresses;\n    getAllAddressesRecursive(baseAddress, 0, allAddresses);\n    return allAddresses;\n}\n\nvoid BitmaskDecoderProgramExecutor::getAllAddressesRecursive(uint64_t baseAddress, size_t floatingDigitsIndex, std::vector<uint64_t>& allAddresses) const\n{\n    if (floatingDigitsIndex >= m_floatingDigits.size())\n    {\n        allAddresses.push_back(baseAddress);\n        return;\n    }\n\n    size_t floatingIndex = m_floatingDigits.at(floatingDigitsIndex);\n\n    uint64_t baseAddressLower = baseAddress;\n    baseAddressLower &= ~(1ull << floatingIndex);\n    getAllAddressesRecursive(baseAddressLower, floatingDigitsIndex + 1, allAddresses);\n\n    uint64_t baseAddressHigher = baseAddress;\n    baseAddressHigher |= (1ull << floatingIndex);\n    getAllAddressesRecursive(baseAddressHigher, floatingDigitsIndex + 1, allAddresses);\n}\n\n}\n}\n}\n", "meta": {"hexsha": "c6c2b4de3a500467e1d91b5c907c6ae76117bb9e", "size": 3923, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/AdventOfCode2020/Day14-DockingData/BitmaskProgramExecutor.cpp", "max_stars_repo_name": "dbartok/advent-of-code-cpp", "max_stars_repo_head_hexsha": "c8c2df7a21980f8f3e42128f7bc5df8288f18490", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/AdventOfCode2020/Day14-DockingData/BitmaskProgramExecutor.cpp", "max_issues_repo_name": "dbartok/advent-of-code-cpp", "max_issues_repo_head_hexsha": "c8c2df7a21980f8f3e42128f7bc5df8288f18490", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/AdventOfCode2020/Day14-DockingData/BitmaskProgramExecutor.cpp", "max_forks_repo_name": "dbartok/advent-of-code-cpp", "max_forks_repo_head_hexsha": "c8c2df7a21980f8f3e42128f7bc5df8288f18490", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6870748299, "max_line_length": 153, "alphanum_fraction": 0.7152689268, "num_tokens": 913, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.45870494552603847}}
{"text": "#include \"software/geom/util.h\"\n\n#include <algorithm>\n#include <boost/geometry/algorithms/intersection.hpp>\n#include <boost/geometry/geometries/segment.hpp>\n#include <boost/polygon/voronoi.hpp>\n#include <cassert>\n#include <cmath>\n#include <g3log/g3log.hpp>\n#include <iostream>\n#include <limits>\n#include <tuple>\n\n#include \"software/geom/rectangle.h\"\n#include \"software/geom/segment.h\"\n#include \"software/geom/voronoi_diagram.h\"\n#include \"software/new_geom/angle.h\"\n\ndouble proj_length(const Segment &first, const Vector &second)\n{\n    return proj_length(first.toVector(), second - first.getSegStart().toVector());\n}\n\ndouble proj_length(const Vector &first, const Vector &second)\n{\n    return first.dot(second) / first.length();\n}\n\ndouble dist(const Point &first, const Point &second)\n{\n    return (first - second).length();\n}\n\ndouble dist(const Segment &first, const Segment &second)\n{\n    if (intersects(first, second))\n    {\n        return 0.0;\n    }\n    return std::sqrt(std::min(\n        std::min(distsq(first, second.getSegStart()), distsq(first, second.getEnd())),\n        std::min(distsq(second, first.getSegStart()), distsq(second, first.getEnd()))));\n}\n\ndouble dist(const Line &first, const Point &second)\n{\n    if (isDegenerate(first))\n    {\n        return dist(first.getFirst(), second);\n    }\n    return fabs((second - first.getFirst()).cross(first.getSecond() - first.getFirst()) /\n                (first.getSecond() - first.getFirst()).length());\n}\n\ndouble dist(const Point &first, const Line &second)\n{\n    return dist(second, first);\n}\n\ndouble dist(const Point &first, const Segment &second)\n{\n    return std::sqrt(distsq(first, second));\n}\n\ndouble dist(const Segment &first, const Point &second)\n{\n    return dist(second, first);\n}\n\ndouble dist(const Point &first, const Polygon &second)\n{\n    if (second.containsPoint(first))\n    {\n        return 0;\n    }\n\n    double min_dist = DBL_MAX;\n\n    // Calculate the distance from the point to each edge\n    for (auto &segment : second.getSegments())\n    {\n        double current_dist = dist(first, segment);\n        if (current_dist < min_dist)\n        {\n            min_dist = current_dist;\n        }\n    }\n    return min_dist;\n}\n\ndouble dist(const Point &first, const Rectangle &second)\n{\n    if (second.containsPoint(first))\n    {\n        return 0;\n    }\n\n    // Calculate the distance from the point to each edge of the rectangle\n    std::array<double, 4> distances = {\n        dist(first, Segment(second.posXPosYCorner(), second.posXNegYCorner())),\n        dist(first, Segment(second.posXNegYCorner(), second.negXNegYCorner())),\n        dist(first, Segment(second.negXNegYCorner(), second.negXPosYCorner())),\n        dist(first, Segment(second.negXPosYCorner(), second.posXPosYCorner()))};\n    return *std::min_element(distances.begin(), distances.end());\n}\n\ndouble distsq(const Point &first, const Segment &second)\n{\n    double seglensq    = lengthSquared(second);\n    Vector relsecond_s = first - second.getSegStart();\n    Vector relsecond_e = first - second.getEnd();\n\n    Vector s_vec2 = second.toVector();\n\n    if (s_vec2.dot(relsecond_s) > 0 && second.reverse().toVector().dot(relsecond_e) > 0)\n    {\n        if (isDegenerate(second))\n        {\n            return relsecond_s.length();\n        }\n        double cross = relsecond_s.cross(s_vec2);\n        return std::fabs(cross * cross / seglensq);\n    }\n\n    double lensq_s = distsq(second.getSegStart(), first),\n           lensq_e = distsq(second.getEnd(), first);\n\n    return std::min(lensq_s, lensq_e);\n}\n\ndouble distsq(const Segment &first, const Point &second)\n{\n    return distsq(second, first);\n}\n\ndouble distsq(const Point &first, const Point &second)\n{\n    return (first - second).lengthSquared();\n}\n\nbool isDegenerate(const Segment &segment)\n{\n    return distsq(segment.getSegStart(), segment.getEnd()) < EPS2;\n}\n\nbool isDegenerate(const Line &line)\n{\n    return distsq(line.getFirst(), line.getSecond()) < EPS2;\n}\n\nbool isDegenerate(const Ray &ray)\n{\n    return distsq(ray.getRayStart(), Point(ray.getDirection())) < EPS2;\n}\n\ndouble length(const Segment &segment)\n{\n    return dist(segment.getSegStart(), segment.getEnd());\n}\n\ndouble lengthSquared(const Segment &segment)\n{\n    return distsq(segment.getSegStart(), segment.getEnd());\n}\n\ndouble lengthSquared(const Line &line)\n{\n    (void)line;  // unused\n    return std::numeric_limits<double>::infinity();\n}\n\nbool contains(const LegacyTriangle &out, const Point &in)\n{\n    double angle = 0;\n    for (int i = 0, j = 2; i < 3; j = i++)\n    {\n        if ((in - out[i]).length() < EPS)\n        {\n            return true;  // SPECIAL CASE\n        }\n        double a =\n            atan2((out[i] - in).cross(out[j] - in), (out[i] - in).dot(out[j] - in));\n        angle += a;\n    }\n    return std::fabs(angle) > 6;\n}\n\nbool contains(const Circle &out, const Point &in)\n{\n    return distsq(out.getOrigin(), in) <= out.getRadius() * out.getRadius();\n}\n\nbool contains(const Circle &out, const Segment &in)\n{\n    return dist(in, out.getOrigin()) < out.getRadius();\n}\n\nbool contains(const Segment &out, const Point &in)\n{\n    if (collinear(in, out.getSegStart(), out.getEnd()))\n    {\n        // If the segment and point are in a perfect vertical line, we must use Y\n        // coordinate centric logic\n        if ((std::abs(in.x() - out.getEnd().x()) < EPS) &&\n            (std::abs(out.getEnd().x() - out.getSegStart().x()) < EPS))\n        {\n            // if collinear we only need to check one of the coordinates,\n            // in this case we select Y because all X values are equal\n            return (in.y() <= out.getSegStart().y() && in.y() >= out.getEnd().y()) ||\n                   (in.y() <= out.getEnd().y() && in.y() >= out.getSegStart().y());\n        }\n\n        // if collinear we only need to check one of the coordinates,\n        // choose x because we know there is variance in these values\n        return (in.x() <= out.getSegStart().x() && in.x() >= out.getEnd().x()) ||\n               (in.x() <= out.getEnd().x() && in.x() >= out.getSegStart().x());\n    }\n\n    return false;\n}\n\nbool contains(const Ray &out, const Point &in)\n{\n    Point point_in_ray_direction = out.getRayStart() + out.getDirection();\n    if (collinear(in, out.getRayStart(), point_in_ray_direction) &&\n        (((in - out.getRayStart()).normalize() - out.getDirection().normalize())\n             .length() < EPS))\n    {\n        return true;\n    }\n    return false;\n}\n\nbool contains(const Rectangle &out, const Point &in)\n{\n    return out.containsPoint(in);\n}\n\nbool intersects(const LegacyTriangle &first, const Circle &second)\n{\n    return contains(first, second.getOrigin()) ||\n           dist(getSide(first, 0), second.getOrigin()) < second.getRadius() ||\n           dist(getSide(first, 1), second.getOrigin()) < second.getRadius() ||\n           dist(getSide(first, 2), second.getOrigin()) < second.getRadius();\n}\nbool intersects(const Circle &first, const LegacyTriangle &second)\n{\n    return intersects(second, first);\n}\n\nbool intersects(const Circle &first, const Circle &second)\n{\n    return (first.getOrigin() - second.getOrigin()).length() <\n           (first.getRadius() + second.getRadius());\n}\n\nbool intersects(const Ray &first, const Segment &second)\n{\n    auto isect =\n        lineIntersection(first.getRayStart(), first.getRayStart() + first.getDirection(),\n                         second.getSegStart(), second.getEnd());\n    // If the infinitely long vectors defined by ray and segment intersect, check that the\n    // intersection is within their definitions\n    if (isect.has_value())\n    {\n        return contains(first, isect.value()) && contains(second, isect.value());\n    }\n    // If there is no intersection, the ray and segment may be parallel, check if they are\n    // overlapped\n    return contains(second, first.getRayStart());\n}\nbool intersects(const Segment &first, const Ray &second)\n{\n    return intersects(second, first);\n}\n\nbool intersects(const Segment &first, const Circle &second)\n{\n    // if the segment is inside the circle AND at least one of the points is\n    // outside the circle\n    return contains(second, first) && (distsq(first.getSegStart(), second.getOrigin()) >\n                                           second.getRadius() * second.getRadius() ||\n                                       distsq(first.getEnd(), second.getOrigin()) >\n                                           second.getRadius() * second.getRadius());\n}\nbool intersects(const Circle &first, const Segment &second)\n{\n    return intersects(second, first);\n}\n\nbool intersects(const Segment &first, const Segment &second)\n{\n    boost::geometry::model::segment<Point> AB(first.getSegStart(), first.getEnd());\n    boost::geometry::model::segment<Point> CD(second.getSegStart(),\n                                              second.getEnd());  // similar code\n\n    return boost::geometry::intersects(AB, CD);\n}\n\ntemplate <size_t N>\nPoint getVertex(const LegacyPolygon<N> &poly, unsigned int i)\n{\n    if (i > N)\n        throw std::out_of_range(\"poly does not have that many sides!!!\");\n    else\n        return poly[i];\n}\n\ntemplate <size_t N>\nvoid setVertex(LegacyPolygon<N> &poly, unsigned int i, const Vector &v)\n{\n    if (i > N)\n        throw std::out_of_range(\"poly does not have that many sides!!!\");\n    else\n        poly[i] = v;\n}\n\ntemplate <size_t N>\nSegment getSide(const LegacyPolygon<N> &poly, unsigned int i)\n{\n    return Segment(getVertex(poly, i), getVertex(poly, (i + 1) % N));\n}\n\nstd::vector<Shot> angleSweepCirclesAll(const Point &src, const Point &p1, const Point &p2,\n                                       const std::vector<Point> &obstacles,\n                                       const double &radius)\n{\n    Angle p1_angle = (p1 - src).orientation();\n    Angle p2_angle = (p2 - src).orientation();\n\n    Angle start_angle = std::min(p1_angle, p2_angle);\n    Angle end_angle   = std::max(p1_angle, p2_angle);\n\n    // This handles the special case where the start and end angle straddle the\n    // negative y axis, which causes some issues with angles \"ticking over\" from pi to\n    // -pi and vice-versa\n    if (end_angle - start_angle > Angle::half())\n    {\n        Angle start_angle_new = start_angle + (end_angle - start_angle).angleMod();\n        end_angle             = start_angle;\n        start_angle           = start_angle_new;\n    }\n\n    if (collinear(src, p1, p2))\n    {\n        // return a result that contains the direction of the line and zero angle if not\n        // blocked by obstacles\n        Segment collinear_seg = Segment(src, p1);\n        for (Point p : obstacles)\n        {\n            if (intersects(collinear_seg, Circle(p, radius)))\n            {\n                // intersection with obstacle found, we're done here and we return nothing\n                return {};\n            }\n        }\n\n        return {Shot(Point(collinear_seg.toVector()), Angle::zero())};\n    }\n\n    // \"Sweep\" a line from the `src` to the target line segment, and create an \"event\"\n    // whenever the line enters or leaves an obstacle, int value of `-1` to indicate the\n    // sweep \"leaving\" an obstacle, and `+1` to indicate the sweep \"entering\" another\n    // obstacle\n    // The angle for each event is measured relative to the start angle\n    std::vector<std::pair<Angle, int>> events;\n    for (const Point &obstacle : obstacles)\n    {\n        Vector diff = obstacle - src;\n        if (diff.length() < radius)\n        {\n            // `src` is within `radius` of this obstacle\n            return {};\n        }\n\n        const Angle cent   = (diff.orientation() - start_angle).angleMod();\n        const Angle span   = Angle::asin(radius / diff.length());\n        const Angle range1 = cent - span;\n        const Angle range2 = cent + span;\n\n        if (range1 < Angle::zero() && range2 > end_angle - start_angle)\n        {\n            // Obstacle takes up entire angle we are sweeping\n            return {};\n        }\n\n        if (range1 < -Angle::half() || range2 > Angle::half())\n        {\n            continue;\n        }\n        if (range1 > Angle::zero() && range1 < end_angle - start_angle)\n        {\n            events.push_back(std::make_pair(range1, -1));\n        }\n        if (range2 > Angle::zero() && range2 < end_angle - start_angle)\n        {\n            events.push_back(std::make_pair(range2, 1));\n        }\n    }\n\n    if (events.empty())\n    {\n        // No obstacles in the way, so just return a range hitting the entire target\n        // line segment\n        return {\n            Shot(Point((p1.toVector() + p2.toVector()) / 2), end_angle - start_angle)};\n    }\n\n    // Sort the events by angle\n    std::sort(events.begin(), events.end());\n\n    // Collapse all contiguous sections of \"+1\" and \"-1\" respectively, as these represent\n    // overlapping obstacles (from the perspective of the `src` point to the target line\n    // segment)\n    std::vector<std::pair<Angle, int>> events_collapsed;\n    for (auto &event : events)\n    {\n        if (events_collapsed.empty() || event.second != events_collapsed.back().second)\n        {\n            events_collapsed.emplace_back(event);\n        }\n    }\n\n    if (events_collapsed[0].second == -1)\n    {\n        events_collapsed.insert(events_collapsed.begin(),\n                                std::make_pair(Angle::zero(), 1));\n    }\n    if (events_collapsed.back().second == 1)\n    {\n        events_collapsed.emplace_back(std::make_pair(end_angle - start_angle, -1));\n    }\n\n    std::vector<Shot> result;\n    for (unsigned i = 1; i < events_collapsed.size(); i += 2)\n    {\n        // Calculate the center of this range on the target line segement\n        Angle range_start = events_collapsed[i - 1].first + start_angle;\n        Angle range_end   = events_collapsed[i].first + start_angle;\n        Angle mid         = (range_end - range_start) / 2 + range_start;\n        Vector ray        = Vector::createFromAngle(mid) * 10.0;\n        Point inter       = lineIntersection(src, src + ray, p1, p2).value();\n\n        // Offset the final values by the start angle\n        result.emplace_back(Shot(inter, range_end - range_start));\n    }\n\n    return result;\n}\n\nstd::optional<Shot> angleSweepCircles(const Point &src, const Point &p1, const Point &p2,\n                                      const std::vector<Point> &obstacles,\n                                      const double &radius)\n{\n    // Get all possible shots we could take\n    std::vector<Shot> possible_shots =\n        angleSweepCirclesAll(src, p1, p2, obstacles, radius);\n\n    // Sort by the interval angle (ie. the open angle the shot is going through)\n    std::sort(possible_shots.begin(), possible_shots.end(),\n              [](auto s1, auto s2) { return s1.getOpenAngle() > s2.getOpenAngle(); });\n\n    // Return the shot through the largest open interval if there are any\n    if (possible_shots.empty())\n    {\n        return std::nullopt;\n    }\n    return possible_shots[0];\n}\n\nstd::vector<Point> circleBoundaries(const Point &centre, double radius, int num_points)\n{\n    Angle rotate_amount = Angle::full() / num_points;\n    std::vector<Point> ans;\n    Vector bound(radius, 0.0);\n    for (int i = 0; i < num_points; i++)\n    {\n        Point temp = centre + bound;\n        ans.push_back(temp);\n        bound = bound.rotate(rotate_amount);\n    }\n    return ans;\n}\n\nbool collinear(const Point &a, const Point &b, const Point &c)\n{\n    if ((a - b).lengthSquared() < EPS2 || (b - c).lengthSquared() < EPS2 ||\n        (a - c).lengthSquared() < EPS2)\n    {\n        return true;\n    }\n    return std::fabs((b - a).cross(c - a)) < EPS;\n}\n\nPoint clipPoint(const Point &p, const Point &bound1, const Point &bound2)\n{\n    const double minx = std::min(bound1.x(), bound2.x());\n    const double miny = std::min(bound1.y(), bound2.y());\n    const double maxx = std::max(bound1.x(), bound2.x());\n    const double maxy = std::max(bound1.y(), bound2.y());\n    Point ret         = p;\n    if (p.x() < minx)\n    {\n        ret.set(minx, ret.y());\n    }\n    else if (p.x() > maxx)\n    {\n        ret.set(maxx, ret.y());\n    }\n    if (p.y() < miny)\n    {\n        ret.set(ret.x(), miny);\n    }\n    else if (p.y() > maxy)\n    {\n        ret.set(ret.x(), maxy);\n    }\n    return ret;\n}\n\nPoint clipPoint(const Point &p, const Rectangle &r)\n{\n    const double minx = r.negXNegYCorner().x();\n    const double miny = r.negXNegYCorner().y();\n    const double maxx = r.posXPosYCorner().x();\n    const double maxy = r.posXPosYCorner().y();\n    Point ret         = p;\n    if (p.x() < minx)\n    {\n        ret.set(minx, ret.y());\n    }\n    else if (p.x() > maxx)\n    {\n        ret.set(maxx, ret.y());\n    }\n    if (p.y() < miny)\n    {\n        ret.set(ret.x(), miny);\n    }\n    else if (p.y() > maxy)\n    {\n        ret.set(ret.x(), maxy);\n    }\n    return ret;\n}\n\nstd::vector<Point> lineCircleIntersect(const Point &centre, double radius,\n                                       const Point &segA, const Point &segB)\n{\n    std::vector<Point> ans;\n\n    // take care of 0 length segments too much error here\n    if ((segB - segA).lengthSquared() < EPS)\n    {\n        return ans;\n    }\n\n    double lenseg = (segB - segA).dot(centre - segA) / (segB - segA).length();\n    Point C       = segA + lenseg * (segB - segA).normalize();\n\n    // if C outside circle no intersections\n    if ((C - centre).lengthSquared() > radius * radius + EPS)\n    {\n        return ans;\n    }\n\n    // if C on circle perimeter return the only intersection\n    if ((C - centre).lengthSquared() < radius * radius + EPS &&\n        (C - centre).lengthSquared() > radius * radius - EPS)\n    {\n        ans.push_back(C);\n        return ans;\n    }\n    // first possible intersection\n    double lensegb = radius * radius - (C - centre).lengthSquared();\n\n    ans.push_back(C - (lensegb * (segB - segA).normalize()));\n    ans.push_back(C + lensegb * (segB - segA).normalize());\n\n    return ans;\n}\n\nstd::vector<Point> lineRectIntersect(const Rectangle &r, const Point &segA,\n                                     const Point &segB)\n{\n    std::vector<Point> ans;\n    for (unsigned int i = 0; i < 4; i++)\n    {\n        const Point &a = r[i];\n        // to draw a line segment from point 3 to point 0\n        const Point &b = r[(i + 1) % 4];\n        if (intersects(Segment(a, b), Segment(segA, segB)) &&\n            uniqueLineIntersects(a, b, segA, segB))\n        {\n            ans.push_back(lineIntersection(a, b, segA, segB).value());\n        }\n    }\n    return ans;\n}\n\nPoint vectorRectIntersect(const Rectangle &r, const Point &pointA, const Point &pointB)\n{\n    std::vector<Point> points =\n        lineRectIntersect(r, pointA, pointA + ((pointB - pointA) * 100));\n    for (Point i : points)\n    {\n        if (contains(Ray(pointA, (pointB - pointA)), i))\n        {\n            return i;\n        }\n    }\n    return Point(1.0 / 0.0, 1.0 / 0.0);  // no solution found, propagate infinity\n}\n\n\nPoint closestPointOnSeg(const Point &p, const Segment &segment)\n{\n    return closestPointOnSeg(p, segment.getSegStart(), segment.getEnd());\n}\nPoint closestPointOnSeg(const Point &centre, const Point &segA, const Point &segB)\n{\n    // if one of the end-points is extremely close to the centre point\n    // then return 0.0\n    if ((segB - centre).lengthSquared() < EPS2)\n    {\n        return segB;\n    }\n\n    if ((segA - centre).lengthSquared() < EPS2)\n    {\n        return segA;\n    }\n\n    // take care of 0 length segments\n    if ((segB - segA).lengthSquared() < EPS2)\n    {\n        return segA;\n    }\n\n    // find point C\n    // which is the projection onto the line\n    double lenseg = (segB - segA).dot(centre - segA) / (segB - segA).length();\n    Point C       = segA + lenseg * (segB - segA).normalize();\n\n    // check if C is in the line seg range\n    double AC     = (segA - C).lengthSquared();\n    double BC     = (segB - C).lengthSquared();\n    double AB     = (segA - segB).lengthSquared();\n    bool in_range = AC <= AB && BC <= AB;\n\n    // if so return C\n    if (in_range)\n    {\n        return C;\n    }\n    double lenA = (centre - segA).length();\n    double lenB = (centre - segB).length();\n\n    // otherwise return closest end of line-seg\n    if (lenA < lenB)\n    {\n        return segA;\n    }\n    return segB;\n}\n\nPoint closestPointOnLine(const Point &p, const Line &line)\n{\n    return closestPointOnLine(p, line.getFirst(), line.getSecond());\n}\nPoint closestPointOnLine(const Point &centre, const Point &lineA, const Point &lineB)\n{\n    // find point C, the projection onto the line\n    double len_line = (lineB - lineA).dot(centre - lineA) / (lineB - lineA).length();\n    Point C         = lineA + len_line * (lineB - lineA).normalize();\n    return C;\n\n    // check if C is in the line range\n    double AC     = (lineA - C).lengthSquared();\n    double BC     = (lineB - C).lengthSquared();\n    double AB     = (lineA - lineB).lengthSquared();\n    bool in_range = AC <= AB && BC <= AB;\n\n    // if so return C\n    if (in_range)\n    {\n    }\n\n    double lenA = (centre - lineA).length();\n    double lenB = (centre - lineB).length();\n\n    // otherwise return closest end of line-seg\n    if (lenA < lenB)\n    {\n        return lineA;\n    }\n    return lineB;\n}\n\nbool uniqueLineIntersects(const Point &a, const Point &b, const Point &c, const Point &d)\n{\n    return std::abs((d - c).cross(b - a)) > EPS;\n}\n\nstd::vector<Point> lineIntersection(const Segment &a, const Segment &b)\n{\n    if (std::fabs((b.getEnd() - b.getSegStart()).cross(a.getEnd() - a.getSegStart())) <\n        EPS)\n    {\n        // parallel line segments, find if they're collinear and return the 2 points\n        // on the line they both lay on if they are collinear and intersecting\n        // shamelessly copypasted from\n        // https://stackoverflow.com/questions/22456517/algorithm-for-finding-the-segment-overlapping-two-collinear-segments\n        if (collinear(a.getSegStart(), b.getSegStart(), b.getEnd()) &&\n            collinear(a.getEnd(), b.getSegStart(), b.getEnd()))\n        {\n            double slope = (a.getEnd().y() - a.getSegStart().y()) /\n                           (a.getEnd().x() - a.getSegStart().x());\n            bool isHorizontal = slope < EPS;\n            bool isDescending = slope < 0 && !isHorizontal;\n            double invertY    = isDescending || isHorizontal ? -1 : 1;\n\n            Point min1 =\n                Point(std::min(a.getSegStart().x(), a.getEnd().x()),\n                      std::min(a.getSegStart().y() * invertY, a.getEnd().y() * invertY));\n            Point max1 =\n                Point(std::max(a.getSegStart().x(), a.getEnd().x()),\n                      std::max(a.getSegStart().y() * invertY, a.getEnd().y() * invertY));\n\n            Point min2 =\n                Point(std::min(b.getSegStart().x(), b.getEnd().x()),\n                      std::min(b.getSegStart().y() * invertY, b.getEnd().y() * invertY));\n            Point max2 =\n                Point(std::max(b.getSegStart().x(), b.getEnd().x()),\n                      std::max(b.getSegStart().y() * invertY, b.getEnd().y() * invertY));\n\n            Point minIntersection;\n            if (isDescending)\n                minIntersection = Point(std::max(min1.x(), min2.x()),\n                                        std::min(min1.y() * invertY, min2.y() * invertY));\n            else\n                minIntersection = Point(std::max(min1.x(), min2.x()),\n                                        std::max(min1.y() * invertY, min2.y() * invertY));\n\n            Point maxIntersection;\n            if (isDescending)\n                maxIntersection = Point(std::min(max1.x(), max2.x()),\n                                        std::max(max1.y() * invertY, max2.y() * invertY));\n            else\n                maxIntersection = Point(std::min(max1.x(), max2.x()),\n                                        std::min(max1.y() * invertY, max2.y() * invertY));\n\n            bool intersect =\n                minIntersection.x() <= maxIntersection.x() &&\n                ((!isDescending && minIntersection.y() <= maxIntersection.y()) ||\n                 (isDescending && minIntersection.y() >= maxIntersection.y()));\n\n            if (intersect)\n            {\n                return std::vector<Point>{minIntersection, maxIntersection};\n            }\n            else\n                return std::vector<Point>();\n        }\n        else\n            return std::vector<Point>();\n    }\n\n    return std::vector<Point>{\n        a.getSegStart() +\n        (a.getSegStart() - b.getSegStart()).cross(b.getEnd() - b.getSegStart()) /\n            (b.getEnd() - b.getSegStart()).cross(a.getEnd() - a.getSegStart()) *\n            (a.getEnd() - a.getSegStart())};\n}\n\n// shamelessly copy-pasted from RoboJackets\nstd::optional<Point> lineIntersection(const Point &a, const Point &b, const Point &c,\n                                      const Point &d)\n{\n    Segment line1(a, b), line2(c, d);\n    double x1 = line1.getSegStart().x();\n    double y1 = line1.getSegStart().y();\n    double x2 = line1.getEnd().x();\n    double y2 = line1.getEnd().y();\n    double x3 = line2.getSegStart().x();\n    double y3 = line2.getSegStart().y();\n    double x4 = line2.getEnd().x();\n    double y4 = line2.getEnd().y();\n\n    double denom = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);\n    if (denom == 0)\n    {\n        // log the parallel lines when we actually implement logging?\n        return std::nullopt;\n    }\n\n    double deta = x1 * y2 - y1 * x2;\n    double detb = x3 * y4 - y3 * x4;\n\n    Point intersection;\n\n    intersection.set((deta * (x3 - x4) - (x1 - x2) * detb) / denom,\n                     (deta * (y3 - y4) - (y1 - y2) * detb) / denom);\n\n    return std::make_optional(intersection);\n}\n\nstd::pair<std::optional<Point>, std::optional<Point>> raySegmentIntersection(\n    const Ray &ray, const Segment &segment)\n{\n    Point ray2 = ray.getRayStart() + ray.getDirection();\n\n    std::optional<Point> intersection = lineIntersection(\n        ray.getRayStart(), ray2, segment.getSegStart(), segment.getEnd());\n\n    // If there exists a single intersection, and it exists on the ray and within the\n    // segment\n    if (intersection.has_value() && contains(ray, intersection.value()) &&\n        contains(segment, intersection.value()))\n    {\n        return std::make_pair(intersection, std::nullopt);\n    }\n    // The ray and segment are parallel, and collinear\n    else if (!intersection.has_value() &&\n             collinear(ray.getRayStart(), segment.getSegStart(), segment.getEnd()))\n    {\n        // Check if ray passes through both segment start and end\n        if (ray.getDirection().normalize() ==\n                (segment.getSegStart() - ray.getRayStart()).normalize() &&\n            ray.getDirection().normalize() ==\n                (segment.getEnd() - ray.getRayStart()).normalize())\n        {\n            return std::make_pair(segment.getSegStart(), segment.getEnd());\n        }\n\n        // Since we know the ray and segment are overlapping (with ray origin within the\n        // segment), return the ray start position, and the end of the segment that is in\n        // the direction of the ray\n        ray.getDirection().normalize() ==\n                (segment.getEnd() - segment.getSegStart()).normalize()\n            ? intersection = std::make_optional(segment.getEnd())\n            : intersection = std::make_optional(segment.getSegStart());\n        return std::make_pair(ray.getRayStart(), intersection.value());\n    }\n    // The ray and segment do not intersect at all\n    else\n    {\n        return std::make_pair(std::nullopt, std::nullopt);\n    }\n}\n\nstd::pair<std::optional<Point>, std::optional<Point>> rayRectangleIntersection(\n    const Ray &ray, const Rectangle &rectangle)\n{\n    std::vector<Segment> rectangle_segments = {\n        Segment(rectangle.posXPosYCorner(), rectangle.negXPosYCorner()),\n        Segment(rectangle.negXPosYCorner(), rectangle.negXNegYCorner()),\n        Segment(rectangle.negXNegYCorner(), rectangle.posXNegYCorner()),\n        Segment(rectangle.posXNegYCorner(), rectangle.posXPosYCorner()),\n    };\n    std::pair<std::optional<Point>, std::optional<Point>> result =\n        std::make_pair(std::nullopt, std::nullopt);\n    for (const auto &seg : rectangle_segments)\n    {\n        auto intersection = raySegmentIntersection(ray, seg);\n        // Always take the result with more non-nullopt values\n        if ((intersection.first && !result.first) ||\n            (intersection.second && !result.second))\n        {\n            result = intersection;\n        }\n    }\n\n    return result;\n}\n\nstd::optional<Point> getRayIntersection(Ray ray1, Ray ray2)\n{\n    // Calculate if the intersecion exists along segments of infinite length\n    std::optional<Point> intersection =\n        lineIntersection(ray1.getRayStart(), ray1.getRayStart() + ray1.getDirection(),\n                         ray2.getRayStart(), ray2.getRayStart() + ray2.getDirection());\n\n    // Return if no intersection exists\n    if (!intersection.has_value())\n    {\n        return std::nullopt;\n    }\n\n    // Check of the intersection exits along the direction of both rays\n    if (((intersection.value() - ray1.getRayStart()).normalize() ==\n         ray1.getDirection().normalize()) &&\n        (intersection.value() - ray2.getRayStart()).normalize() ==\n            ray2.getDirection().normalize())\n    {\n        return intersection.value();\n    }\n    else\n    {\n        return std::nullopt;\n    }\n}\n\nVector reflect(const Vector &v, const Vector &n)\n{\n    if (n.length() < EPS)\n    {\n        return v;\n    }\n    Vector normal = n.normalize();\n    return v - 2 * v.dot(normal) * normal;\n}\n\nPoint reflect(const Point &a, const Point &b, const Point &p)\n{\n    // Make a as origin.\n    // Rotate by 90 degrees, does not matter which direction?\n    Vector n = (b - a).rotate(Angle::quarter());\n    return a + reflect(p - a, n);\n}\n\nPoint calcBlockCone(const Vector &a, const Vector &b, const double &radius)\n{\n    if (a.length() < EPS || b.length() < EPS)\n    {\n    }\n    // unit vector and bisector\n    Vector au = a / a.length();\n    Vector c  = au + b / b.length();\n    // use similar triangle\n    return Point(c * (radius / std::fabs(au.cross(c))));\n}\n\nPoint calcBlockCone(const Point &a, const Point &b, const Point &p, const double &radius)\n{\n    return p + (calcBlockCone(a - p, b - p, radius)).toVector();\n}\n\nVector calcBlockOtherRay(const Point &a, const Point &c, const Point &g)\n{\n    return reflect(c - a, g - c);  // this, and the next two instances, were\n                                   // changed from a - c since reflect() was\n                                   // fixed\n}\n\ndouble offsetToLine(Point x0, Point x1, Point p)\n{\n    Vector n;\n\n    // get normal to line\n    n = (x1 - x0).perpendicular().normalize();\n\n    return fabs(n.dot(p - x0));\n}\n\ndouble offsetAlongLine(Point x0, Point x1, Point p)\n{\n    Vector n, v;\n\n    // get normal to line\n    n = x1 - x0;\n    n = n.normalize();\n\n    v = p - x0;\n\n    return n.dot(v);\n}\n\nPoint segmentNearLine(Point a0, Point a1, Point b0, Point b1)\n{\n    Vector v, n;\n    Point p;\n    double dn, t;\n\n    v = a1 - a0;\n    n = (b1 - b0).normalize();\n    n = n.perpendicular();\n\n    dn = v.dot(n);\n    if (std::fabs(dn) < EPS)\n    {\n        return a0;\n    }\n\n    t = -(a0 - b0).dot(n) / dn;\n\n    if (t < 0)\n    {\n        t = 0;\n    }\n    if (t > 1)\n    {\n        t = 1;\n    }\n    p = a0 + v * t;\n\n    return p;\n}\n\nPoint intersection(Point a1, Point a2, Point b1, Point b2)\n{\n    Vector a = a2 - a1;\n\n    Vector b1r = (b1 - a1).rotate(-a.orientation());\n    Vector b2r = (b2 - a1).rotate(-a.orientation());\n    Vector br  = (b1r - b2r);\n\n    return Vector(b2r.x() - b2r.y() * (br.x() / br.y()), 0.0).rotate(a.orientation()) +\n           a1;\n}\n\nAngle acuteVertexAngle(Vector v1, Vector v2)\n{\n    return v1.orientation().minDiff(v2.orientation());\n}\n\nAngle acuteVertexAngle(Point p1, Point p2, Point p3)\n{\n    return acuteVertexAngle(p1 - p2, p3 - p2);\n}\n\ndouble closestPointTime(Point x1, Vector v1, Point x2, Vector v2)\n{\n    Vector v  = v1 - v2;\n    double sl = v.lengthSquared();\n    double t;\n\n    if (sl < EPS)\n    {\n        return 0.0;  // parallel tracks, any time is ok.\n    }\n    t = -v.dot(x1 - x2) / sl;\n    if (t < 0.0)\n    {\n        return 0.0;  // nearest time was in the past, now is closest point from\n                     // now on.\n    }\n    return t;\n}\n\nbool pointInFrontVector(Point offset, Vector direction, Point p)\n{\n    // compare angle different\n    Angle a1   = direction.orientation();\n    Angle a2   = (p - offset).orientation();\n    Angle diff = (a1 - a2).angleMod();\n    return diff < Angle::quarter() && diff > -Angle::quarter();\n}\n\nstd::pair<Point, Point> getCircleTangentPoints(const Point &start, const Circle &circle,\n                                               double buffer)\n{\n    // If the point is already inside the circe arccos won't work so just return\n    // the perp points\n    if (contains(circle, start))\n    {\n        double perpDist = std::sqrt(circle.getRadius() * circle.getRadius() -\n                                    (circle.getOrigin() - start).lengthSquared());\n        Point p1 =\n            start +\n            (circle.getOrigin() - start).perpendicular().normalize(perpDist + buffer);\n        Point p2 =\n            start -\n            ((circle.getOrigin() - start).perpendicular().normalize(perpDist + buffer));\n        return std::make_pair(p1, p2);\n    }\n    else\n    {\n        double radiusAngle =\n            std::acos(circle.getRadius() / (start - circle.getOrigin()).length());\n        Point p1 = circle.getOrigin() + (start - circle.getOrigin())\n                                            .rotate(Angle::fromRadians(radiusAngle))\n                                            .normalize(circle.getRadius() + buffer);\n        Point p2 = circle.getOrigin() + (start - circle.getOrigin())\n                                            .rotate(-Angle::fromRadians(radiusAngle))\n                                            .normalize(circle.getRadius() + buffer);\n        return std::make_pair(p1, p2);\n    }\n}\n\nstd::pair<Ray, Ray> getCircleTangentRays(const Point reference, const Circle circle,\n                                         double buffer)\n{\n    auto [tangent_point1, tangent_point2] =\n        getCircleTangentPoints(reference, circle, buffer);\n\n    return std::make_pair(Ray(tangent_point1, (tangent_point1 - reference).normalize()),\n                          Ray(tangent_point2, (tangent_point2 - reference).normalize()));\n}\n\nbool pointIsRightOfLine(const Segment &line, const Point &point)\n{\n    return (line.getEnd().x() - line.getSegStart().x()) *\n                   (point.y() - line.getSegStart().y()) -\n               (line.getEnd().y() - line.getSegStart().y()) *\n                   (point.x() - line.getSegStart().x()) <\n           0.0;\n}\n\nPoint getPointsMean(const std::vector<Point> &points)\n{\n    Point average = Point(0, 0);\n    for (unsigned int i = 0; i < points.size(); i++)\n    {\n        average += points[i].toVector();\n    }\n\n    Vector averageVector = average.toVector();\n\n    averageVector /= static_cast<double>(points.size());\n    return Point(averageVector);\n}\n\ndouble getPointsVariance(const std::vector<Point> &points)\n{\n    Point mean = getPointsMean(points);\n\n    double sum = 0.0;\n    for (unsigned int i = 0; i < points.size(); i++)\n    {\n        sum += (points[i] - mean).lengthSquared();\n    }\n\n    sum /= static_cast<double>(points.size());\n    return sqrt(sum);\n}\n\nstd::optional<Segment> segmentEnclosedBetweenRays(Segment segment, Ray ray1, Ray ray2)\n{\n    // Create rays located at the extremes of the segment, that point in the direction\n    // outwards are parallel to the segment\n    const Ray extremes1 =\n        Ray(segment.getEnd(), Vector(segment.getEnd() - segment.getSegStart()));\n    const Ray extremes2 =\n        Ray(segment.getSegStart(), Vector(segment.getSegStart() - segment.getEnd()));\n\n    const std::optional<Point> extreme_intersect11 = getRayIntersection(extremes1, ray1);\n    const std::optional<Point> extreme_intersect12 = getRayIntersection(extremes2, ray1);\n    const std::optional<Point> extreme_intersect21 = getRayIntersection(extremes1, ray2);\n    const std::optional<Point> extreme_intersect22 = getRayIntersection(extremes2, ray2);\n\n    // Check for the cases that the rays intersect the same segment projection\n    if ((extreme_intersect11.has_value() == extreme_intersect21.has_value()) ||\n        (extreme_intersect21.has_value() == extreme_intersect22.has_value()))\n    {\n        return std::nullopt;\n    }\n    else\n    {\n        // Since we know that both rays aren't passing through the same side of the\n        // segment at this point, then as long as they both only intersect 1 point the\n        // segment must be enclosed between them\n        if ((extreme_intersect11.has_value() != extreme_intersect12.has_value()) &&\n            (extreme_intersect21.has_value() != extreme_intersect22.has_value()))\n        {\n            return std::make_optional(segment);\n        }\n        // Covers the case where a single ray passes by both sides of the segment\n        else\n        {\n            return std::nullopt;\n        }\n    }\n}\n\nstd::optional<Segment> getIntersectingSegment(Ray ray1, Ray ray2, Segment segment)\n{\n    // Check if the segment is enclosed between the rays\n    if (segmentEnclosedBetweenRays(segment, ray1, ray2))\n    {\n        return segment;\n    }\n\n    // Calculate intersections of each individual ray and the segment\n    auto [intersect11, intersect12] = raySegmentIntersection(ray1, segment);\n    auto [intersect21, intersect22] = raySegmentIntersection(ray2, segment);\n\n    // Check if there are any real intersections\n    if (!intersect11.has_value() && !intersect21.has_value())\n    {\n        return std::nullopt;\n    }\n    // Check if one of the rays is overlapping the segment. If this is the case, return\n    // the segment (If a ray intersects a ray more than one time it must be overlapping)\n    else if ((intersect11.has_value() && intersect12.has_value()) ||\n             (intersect21.has_value() && intersect22.has_value()))\n    {\n        return segment;\n    }\n    // If there is only one intersection point for each ray combine the intersections into\n    // a segment\n    else if ((intersect11.has_value() && !intersect12.has_value()) &&\n             (intersect21.has_value() && !intersect22.has_value()))\n    {\n        return std::make_optional(Segment(intersect11.value(), intersect21.value()));\n    }\n    // If only one ray intersects the segment return the segment between the intersection\n    // and the segment extreme (intersection11 is real, intersection22 is not)\n    else if (intersect11.has_value() && !intersect21.has_value())\n    {\n        const Ray extremes1 =\n            Ray(segment.getEnd(), Vector(segment.getEnd() - segment.getSegStart()));\n        const Ray extremes2 =\n            Ray(segment.getSegStart(), Vector(segment.getSegStart() - segment.getEnd()));\n        ;\n\n        std::optional<Point> extreme_intersect1 = getRayIntersection(extremes1, ray2);\n        std::optional<Point> extreme_intersect2 = getRayIntersection(extremes2, ray2);\n\n        if (extreme_intersect1.has_value())\n        {\n            return std::make_optional(Segment(intersect11.value(), segment.getEnd()));\n        }\n        else if (extreme_intersect2.has_value())\n        {\n            return std::make_optional(\n                Segment(intersect11.value(), segment.getSegStart()));\n        }\n    }\n    // If only one ray intersects the segment return the segment between the intersection\n    // and the segment extreme (intersection11 is real, intersection22 is not)\n    else if (intersect11.has_value() && !intersect21.has_value())\n    {\n        const Ray extremes1 =\n            Ray(segment.getEnd(), Vector(segment.getEnd() - segment.getSegStart()));\n        const Ray extremes2 =\n            Ray(segment.getSegStart(), Vector(segment.getSegStart() - segment.getEnd()));\n        ;\n\n        std::optional<Point> extreme_intersect1 = getRayIntersection(extremes1, ray1);\n        std::optional<Point> extreme_intersect2 = getRayIntersection(extremes2, ray1);\n\n        if (extreme_intersect1.has_value())\n        {\n            return std::make_optional(Segment(intersect21.value(), segment.getEnd()));\n        }\n        else if (extreme_intersect2.has_value())\n        {\n            return std::make_optional(\n                Segment(intersect21.value(), segment.getSegStart()));\n        }\n    }\n    // All cases have been checked, return std::nullopt\n    return std::nullopt;\n}\n\nstd::optional<Segment> mergeOverlappingParallelSegments(Segment segment1,\n                                                        Segment segment2)\n{\n    std::optional<Segment> redundant_segment =\n        mergeFullyOverlappingSegments(segment1, segment2);\n\n    // If the segments are not parallel, then return std::nullopt. (The segments are\n    // parallel of all points are collinear)\n    if (!collinear(segment1.getSegStart(), segment1.getEnd(), segment2.getSegStart()) &&\n        !collinear(segment1.getSegStart(), segment1.getEnd(), segment2.getEnd()))\n    {\n        return std::nullopt;\n    }\n    // Check the case where one segment is completely contained in the other\n    else if (redundant_segment.has_value())\n    {\n        return redundant_segment;\n    }\n    // Check if the beginning of segment2 lays inside segment1\n    else if (contains(segment1, segment2.getSegStart()))\n    {\n        // If segment2.getSegStart() lays in segment1, then the combined segment is\n        // segment2,getEnd() and the point furthest from segmen2.getEnd()\n        return (segment1.getSegStart() - segment2.getEnd()).lengthSquared() >\n                       (segment1.getEnd() - segment2.getEnd()).lengthSquared()\n                   ? Segment(segment1.getSegStart(), segment2.getEnd())\n                   : Segment(segment1.getEnd(), segment2.getEnd());\n    }\n    // Now check if the end of segment2 lays inside segment1\n    else if (contains(segment1, segment2.getEnd()))\n    {\n        // If segment2.getSegStart() lays in segment1, then the combined segment is\n        // segment2,getEnd() and the point furtherst from segmen2.getEnd()\n        return (segment1.getSegStart() - segment2.getSegStart()).lengthSquared() >\n                       (segment1.getEnd() - segment2.getSegStart()).lengthSquared()\n                   ? Segment(segment1.getSegStart(), segment2.getSegStart())\n                   : Segment(segment1.getEnd(), segment2.getSegStart());\n    }\n    return std::nullopt;\n}\n\nstd::optional<Segment> mergeFullyOverlappingSegments(Segment segment1, Segment segment2)\n{\n    // If the segments are not parallel, then return std::nullopt. (The segments are\n    // parallel if all points are collinear)\n    if (!collinear(segment1.getSegStart(), segment1.getEnd(), segment2.getSegStart()) &&\n        !collinear(segment1.getSegStart(), segment1.getEnd(), segment2.getEnd()))\n    {\n        return std::nullopt;\n    }\n\n    Segment largest_segment, smallest_segment;\n    // Grab the largest segment\n    if (segment1.toVector().lengthSquared() > segment2.toVector().lengthSquared())\n    {\n        largest_segment  = segment1;\n        smallest_segment = segment2;\n    }\n    else\n    {\n        largest_segment  = segment2;\n        smallest_segment = segment1;\n    }\n\n    // The segment is redundant if both points of the smallest segment are contained in\n    // the largest segment\n    if (contains(largest_segment, smallest_segment.getSegStart()) &&\n        contains(largest_segment, smallest_segment.getEnd()))\n    {\n        return std::make_optional(largest_segment);\n    }\n    else\n    {\n        return std::nullopt;\n    }\n}\n\nint calcBinaryTrespassScore(const Rectangle &rectangle, const Point &point)\n{\n    if (rectangle.containsPoint(point))\n    {\n        return 1;\n    }\n    else\n    {\n        return 0;\n    }\n}\n\n\nstd::vector<Circle> findOpenCircles(Rectangle bounding_box, std::vector<Point> points)\n{\n    // We use a Voronoi Diagram and it's Delaunay triangulation to find the largest\n    // open circles in the field\n    // Reference: https://www.cs.swarthmore.edu/~adanner/cs97/s08/papers/schuster.pdf\n    //\n    // You can think of the Delauney triangulation as a way to connect all the points\n    // (and the bounding_box corners) such that every point has three edges, and the\n    // triangles formed are setup to be as regular as possible (ie. we avoid things\n    // like super narrow triangles). The Voronoi diagram is the *dual* of this (scary\n    // math words, I know), which just means you can construct it by taking the center\n    // of each triangle and connecting it to the center of every adjacent triangle.\n    //\n    // So we can take each vertex on our voronoi diagram as the center of a open circle\n    // on the field, and the size of the circle is the distance to the closest vertex\n    // on the triangle that this vertex was created from\n\n    // Filters out points that are outside of the bounding box\n    points.erase(std::remove_if(points.begin(), points.end(),\n                                [&bounding_box](const Point &p) {\n                                    return !bounding_box.containsPoint(p);\n                                }),\n                 points.end());\n\n    std::vector<Circle> empty_circles;\n\n    // Creating the Voronoi diagram with 2 or less points will produce no edges so we need\n    // to handle these cases manually\n    if (points.empty())\n    {\n        // If there are no points, return an empty vector since there are no constraints\n        // to the size of the circle.\n        return empty_circles;\n    }\n    if (points.size() == 1)\n    {\n        // If there is only 1 point, return circles centered at all four corners of the\n        // bounding bounding_box.\n        for (Point &corner : bounding_box.corners())\n        {\n            empty_circles.emplace_back(Circle(corner, dist(points.front(), corner)));\n        }\n        return empty_circles;\n    }\n    if (points.size() == 2)\n    {\n        // If there are 2 point, split the points with a vector perpendicular to the\n        // vector connecting the two points. Return 2 circles that are centered at the\n        // points where the splitting vector intercepts the bounding_box. We should also\n        // include circles centered at each of the corners.\n        Vector connectedVec           = points[1] - points[0];\n        Point halfPoint               = points[0] + (connectedVec * 0.5);\n        Vector perpVec                = connectedVec.perpendicular();\n        std::vector<Point> intersects = lineRectIntersect(\n            bounding_box,\n            halfPoint +\n                (perpVec * dist(bounding_box.furthestCorner(halfPoint), halfPoint)),\n            halfPoint -\n                (perpVec * dist(bounding_box.furthestCorner(halfPoint), halfPoint)));\n        std::vector<Point> corners = bounding_box.corners();\n        intersects.insert(intersects.end(), corners.begin(), corners.end());\n        for (const Point &intersect : intersects)\n        {\n            double radius = dist(findClosestPoint(intersect, points).value(), intersect);\n            empty_circles.emplace_back(intersect, radius);\n        }\n        return empty_circles;\n    }\n\n    // Construct the voronoi diagram\n    VoronoiDiagram vd(points);\n\n    // The corners of the rectangles are locations for the centre of circles with their\n    // radius being the distance to the corner's closest point.\n    for (const Point &corner : bounding_box.corners())\n    {\n        Point closest = findClosestPoint(corner, points).value();\n        empty_circles.emplace_back(Circle(corner, dist(corner, closest)));\n    }\n\n    std::vector<Point> intersects = vd.findVoronoiEdgeRecIntersects(bounding_box);\n\n    // Radius of the circle will be the distance from the interception point\n    // to the nearest input point.\n    for (const Point &p : intersects)\n    {\n        double radius = (points[0] - p).length();\n        for (const Point &inputP : points)\n        {\n            radius = std::min(radius, (inputP - p).length());\n        }\n        empty_circles.emplace_back(Circle(p, radius));\n    }\n\n    std::vector<Circle> calculatedEmptyCircles =\n        vd.voronoiVerticesToOpenCircles(bounding_box);\n    empty_circles.insert(empty_circles.end(), calculatedEmptyCircles.begin(),\n                         calculatedEmptyCircles.end());\n\n    // Sort the circles in descending order of radius\n    std::sort(empty_circles.begin(), empty_circles.end(),\n              [](auto c1, auto c2) { return c1.getRadius() > c2.getRadius(); });\n\n    return empty_circles;\n}\n\nPolygon circleToPolygon(const Circle &circle, size_t num_points)\n{\n    std::vector<Point> points;\n    for (unsigned i = 0; i < num_points; i++)\n    {\n        Point p = circle.getOrigin() +\n                  Vector(circle.getRadius(), 0)\n                      .rotate(Angle::fromDegrees((360.0 / num_points) * i));\n        points.emplace_back(p);\n    }\n    return Polygon(points);\n}\n\nstd::optional<Point> findClosestPoint(const Point &origin_point,\n                                      std::vector<Point> test_points)\n{\n    std::optional<Point> closest_point = std::nullopt;\n\n    if (!test_points.empty())\n    {\n        closest_point = *std::min_element(\n            test_points.begin(), test_points.end(),\n            [&](const Point &test_point1, const Point &test_point2) {\n                return dist(origin_point, test_point1) < dist(origin_point, test_point2);\n            });\n    }\n\n    return closest_point;\n}\n", "meta": {"hexsha": "20a9eb19ce7eed70f2f8f11a1c5cb2baa03ddc88", "size": 49324, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/software/geom/util.cpp", "max_stars_repo_name": "matthewberends/Software", "max_stars_repo_head_hexsha": "4681c7cffc9c1ca8f739ea692daffc490a8c1910", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/software/geom/util.cpp", "max_issues_repo_name": "matthewberends/Software", "max_issues_repo_head_hexsha": "4681c7cffc9c1ca8f739ea692daffc490a8c1910", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/software/geom/util.cpp", "max_forks_repo_name": "matthewberends/Software", "max_forks_repo_head_hexsha": "4681c7cffc9c1ca8f739ea692daffc490a8c1910", "max_forks_repo_licenses": ["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.5081521739, "max_line_length": 124, "alphanum_fraction": 0.5996877788, "num_tokens": 11968, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.45870494552603847}}
{"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    cholesky.cpp\n * @brief   Efficient incomplete Cholesky on rank-deficient matrices, todo: constrained Cholesky\n * @author  Richard Roberts\n * @date    Nov 5, 2010\n */\n\n#include <gtsam/base/debug.h>\n#include <gtsam/base/cholesky.h>\n#include <gtsam/base/timing.h>\n\n#include <boost/format.hpp>\n#include <cmath>\n\nusing namespace std;\n\nnamespace gtsam {\n\n  static const double negativePivotThreshold = -1e-1;\n  static const double zeroPivotThreshold = 1e-6;\n  static const double underconstrainedPrior = 1e-5;\n  static const int underconstrainedExponentDifference = 12;\n\n/* ************************************************************************* */\nstatic inline int choleskyStep(Matrix& ATA, size_t k, size_t order) {\n\n  const bool debug = ISDEBUG(\"choleskyCareful\");\n\n  // Get pivot value\n  double alpha = ATA(k,k);\n\n  // Correct negative pivots from round-off error\n  if(alpha < negativePivotThreshold) {\n    if(debug) {\n      cout << \"pivot = \" << alpha << endl;\n      print(ATA, \"Partially-factorized matrix: \");\n    }\n    return -1;\n  } else if(alpha < 0.0)\n    alpha = 0.0;\n    \n  const double beta = sqrt(alpha);\n\n  if(beta > zeroPivotThreshold) {\n    const double betainv = 1.0 / beta;\n\n    // Update k,k\n    ATA(k,k) = beta;\n\n    if(k < (order-1)) {\n      // Update A(k,k+1:end) <- A(k,k+1:end) / beta\n      typedef Matrix::RowXpr::SegmentReturnType BlockRow;\n      BlockRow V = ATA.row(k).segment(k+1, order-(k+1));\n      V *= betainv;\n\n      // Update A(k+1:end, k+1:end) <- A(k+1:end, k+1:end) - v*v' / alpha\n      ATA.block(k+1, k+1, order-(k+1), order-(k+1)) -= V.transpose() * V;\n//      ATA.bottomRightCorner(order-(k+1), order-(k+1)).selfadjointView<Eigen::Upper>()\n//          .rankUpdate(V.adjoint(), -1);\n    }\n    return 1;\n  } else {\n    // For zero pivots, add the underconstrained variable prior\n    ATA(k,k) = underconstrainedPrior;\n    for(size_t j=k+1; j<order; ++j)\n      ATA(k,j) = 0.0;\n    if(debug) cout << \"choleskyCareful:  Skipping \" << k << endl;\n    return 0;\n  }\n}\n\n/* ************************************************************************* */\npair<size_t,bool> choleskyCareful(Matrix& ATA, int order) {\n\n  const bool debug = ISDEBUG(\"choleskyCareful\");\n\n  // Check that the matrix is square (we do not check for symmetry)\n  assert(ATA.rows() == ATA.cols());\n\n  // Number of rows/columns\n  const size_t n = ATA.rows();\n\n  // Negative order means factor the entire matrix\n  if(order < 0)\n    order = int(n);\n\n  assert(size_t(order) <= n);\n\n  // The index of the row after the last non-zero row of the square-root factor\n  size_t maxrank = 0;\n  bool success = true;\n\n  // Factor row-by-row\n  for(size_t k = 0; k < size_t(order); ++k) {\n    int stepResult = choleskyStep(ATA, k, size_t(order));\n    if(stepResult == 1) {\n      if(debug) cout << \"choleskyCareful:  Factored through \" << k << endl;\n      if(debug) print(ATA, \"ATA: \");\n      maxrank = k+1;\n    } else if(stepResult == -1) {\n      success = false;\n      break;\n    } /* else if(stepResult == 0) Found zero pivot */\n  }\n\n  return make_pair(maxrank, success);\n}\n\n/* ************************************************************************* */\nbool choleskyPartial(Matrix& ABC, size_t nFrontal) {\n\n  gttic(choleskyPartial);\n\n  const bool debug = ISDEBUG(\"choleskyPartial\");\n\n  assert(ABC.rows() == ABC.cols());\n  assert(ABC.rows() >= 0 && nFrontal <= size_t(ABC.rows()));\n\n  const size_t n = ABC.rows();\n\n  // Compute Cholesky factorization of A, overwrites A.\n  gttic(lld);\n  Eigen::ComputationInfo lltResult;\n  if(nFrontal > 0)\n  {\n    Eigen::LLT<Matrix, Eigen::Upper> llt = ABC.block(0, 0, nFrontal, nFrontal).selfadjointView<Eigen::Upper>().llt();\n    ABC.block(0, 0, nFrontal, nFrontal).triangularView<Eigen::Upper>() = llt.matrixU();\n    lltResult = llt.info();\n  }\n  else\n  {\n    lltResult = Eigen::Success;\n  }\n  gttoc(lld);\n\n  if(debug) cout << \"R:\\n\" << Eigen::MatrixXd(ABC.topLeftCorner(nFrontal,nFrontal).triangularView<Eigen::Upper>()) << endl;\n\n  // Compute S = inv(R') * B\n  gttic(compute_S);\n  if(n - nFrontal > 0) {\n    ABC.topLeftCorner(nFrontal,nFrontal).triangularView<Eigen::Upper>().transpose().solveInPlace(\n        ABC.topRightCorner(nFrontal, n-nFrontal));\n  }\n  if(debug) cout << \"S:\\n\" << ABC.topRightCorner(nFrontal, n-nFrontal) << endl;\n  gttoc(compute_S);\n\n  // Compute L = C - S' * S\n  gttic(compute_L);\n  if(debug) cout << \"C:\\n\" << Eigen::MatrixXd(ABC.bottomRightCorner(n-nFrontal,n-nFrontal).selfadjointView<Eigen::Upper>()) << endl;\n  if(n - nFrontal > 0)\n    ABC.bottomRightCorner(n-nFrontal,n-nFrontal).selfadjointView<Eigen::Upper>().rankUpdate(\n        ABC.topRightCorner(nFrontal, n-nFrontal).transpose(), -1.0);\n  if(debug) cout << \"L:\\n\" << Eigen::MatrixXd(ABC.bottomRightCorner(n-nFrontal,n-nFrontal).selfadjointView<Eigen::Upper>()) << endl;\n  gttoc(compute_L);\n\n  // Check last diagonal element - Eigen does not check it\n  bool ok;\n  if(lltResult == Eigen::Success) {\n    if(nFrontal >= 2) {\n      int exp2, exp1;\n      (void)frexp(ABC(nFrontal-2, nFrontal-2), &exp2);\n      (void)frexp(ABC(nFrontal-1, nFrontal-1), &exp1);\n      ok = (exp2 - exp1 < underconstrainedExponentDifference);\n    } else if(nFrontal == 1) {\n      int exp1;\n      (void)frexp(ABC(0,0), &exp1);\n      ok = (exp1 > -underconstrainedExponentDifference);\n    } else {\n      ok = true;\n    }\n  } else {\n    ok = false;\n  }\n\n  return ok;\n}\n\n}\n", "meta": {"hexsha": "f6e2848f6cc8a75001a19f9c3ba4424c7015ca9e", "size": 5763, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/base/cholesky.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/base/cholesky.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/base/cholesky.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": 30.3315789474, "max_line_length": 132, "alphanum_fraction": 0.5936144369, "num_tokens": 1692, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.45870494552603847}}
{"text": "/******************************************************************************\nCopyright (c) 2017, Farbod Farshidian. 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 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#include <algorithm>\n#include <cmath>\n#include <iostream>\n#include <vector>\n\n#include <boost/numeric/odeint.hpp>\n\n#include <ocs2_core/Types.h>\n#include <ocs2_core/integration/eigenIntegration.h>\n\n#include \"ocs2_ddp/test/bouncingmass/Reference.h\"\n\nReference::Reference(scalar_t t0, scalar_t t1, const vector_t& p0, const vector_t& p1) {\n  Create5thOrdPol(t0, t1, p0, p1);\n  polV_ = polyder(polX_);\n  polU_ = polyder(polV_);\n\n  t0_ = t0;\n  t1_ = t1;\n}\n\nvoid Reference::getInput(scalar_t time, vector_t& input) const {\n  input.setZero(1);\n  for (int i = 0; i < polU_.size(); i++) {\n    input[0] += polU_[i] * std::pow(time, i);\n  }\n}\n\nvector_t Reference::getInput(scalar_t time) const {\n  vector_t input;\n  getInput(time, input);\n  return input;\n}\n\nvoid Reference::getState(scalar_t time, vector_t& x) const {\n  if (time <= t1_ && time >= t0_) {\n    x.setZero(3);\n    for (int i = 0; i < polU_.size(); i++) {\n      x[0] += polX_[i] * std::pow(time, i);\n      x[1] += polV_[i] * std::pow(time, i);\n    }\n  } else {\n    interpolate_ext(time, x);\n  }\n}\n\nvoid Reference::extendref(scalar_t delta, Reference* refPre, Reference* refPost) {\n  delta_ = delta;\n  boost::numeric::odeint::runge_kutta_dopri5<vector_t, scalar_t, vector_t, scalar_t, boost::numeric::odeint::vector_space_algebra> stepper;\n  // Lambda for general system dynamics, assuming that the reference input is available\n  auto model = [](const vector_t& x, vector_t& dxdt, const double t, vector_t uref) {\n    matrix_t A(3, 3);\n    A << 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0;\n    matrix_t B(3, 1);\n    B << 0.0, 1.0, 0.0;\n\n    dxdt = A * x + B * uref;\n  };\n  // pre-part of extension\n  if (refPre != nullptr) {\n    // Construct Lambda to represent System Dynamics with correct reference input\n    auto preModel = [&refPre, &model](const vector_t& x, vector_t& dxdt, const double t) {\n      vector_t uref = refPre->getInput(t);\n      model(x, dxdt, t, uref);\n    };\n    // Construct lambda to act as observer, which will store the time and state trajectories\n    scalar_array_t* timeStorePtr = &tPre_;\n    vector_array_t* stateStorePtr = &xPre_;\n    auto preObserver = [&timeStorePtr, &stateStorePtr](vector_t& x, scalar_t& t) {\n      timeStorePtr->push_back(t);\n      stateStorePtr->push_back(x);\n    };\n\n    vector_t x0;\n    getState(t0_, x0);\n    scalar_t t0 = t0_;\n    scalar_t t1 = t0 - delta;\n    scalar_t dt = -1e-3;\n\n    boost::numeric::odeint::integrate_adaptive(stepper, preModel, x0, t0, t1, dt, preObserver);\n    std::reverse(std::begin(tPre_), std::end(tPre_));\n    std::reverse(std::begin(xPre_), std::end(xPre_));\n  }\n\n  // post-part of extension\n  if (refPost != nullptr) {\n    // Construct Lambda to represent System Dynamics with correct reference input\n    auto postModel = [&refPost, &model](const vector_t& x, vector_t& dxdt, const double t) {\n      vector_t uref = refPost->getInput(t);\n      model(x, dxdt, t, uref);\n    };\n    // Construct lambda to act as observer, which will store the time and state trajectories\n    scalar_array_t* timeStorePtr = &tPost_;\n    vector_array_t* stateStorePtr = &xPost_;\n    auto postObserver = [&timeStorePtr, &stateStorePtr](vector_t& x, scalar_t& t) {\n      timeStorePtr->push_back(t);\n      stateStorePtr->push_back(x);\n    };\n\n    vector_t x0;\n    getState(t1_, x0);\n    scalar_t t0 = t1_;\n    scalar_t t1 = t0 + delta;\n    scalar_t dt = 1e-3;\n    boost::numeric::odeint::integrate_adaptive(stepper, postModel, x0, t0, t1, dt, postObserver);\n  }\n}\n\nvoid Reference::Create5thOrdPol(scalar_t t0, scalar_t t1, const vector_t& p0, const vector_t& p1) {\n  Eigen::Matrix<scalar_t, 6, 6> A;\n  Eigen::Matrix<scalar_t, 6, 6> Ainv;\n\n  A << 1, t0, std::pow(t0, 2), std::pow(t0, 3), std::pow(t0, 4), std::pow(t0, 5), 0, 1, 2 * t0, 3 * std::pow(t0, 2), 4 * std::pow(t0, 3),\n      5 * std::pow(t0, 4), 0, 0, 2, 6 * t0, 12 * std::pow(t0, 2), 20 * std::pow(t0, 3), 1, t1, std::pow(t1, 2), std::pow(t1, 3),\n      std::pow(t1, 4), std::pow(t1, 5), 0, 1, 2 * t1, 3 * std::pow(t1, 2), 4 * std::pow(t1, 3), 5 * std::pow(t1, 4), 0, 0, 2, 6 * t1,\n      12 * std::pow(t1, 2), 20 * std::pow(t1, 3);\n\n  Ainv = A.inverse();\n\n  Eigen::Matrix<scalar_t, 6, 1> x;\n  x << p0, p1;\n  polX_ = Ainv * x;\n}\n\nvoid Reference::interpolate_ext(scalar_t time, vector_t& x) const {\n  const scalar_array_t* tVec;\n  const vector_array_t* xVec;\n  if (time < t0_) {\n    tVec = &tPre_;\n    xVec = &xPre_;\n    x = xPre_.front();\n  } else {\n    tVec = &tPost_;\n    xVec = &xPost_;\n    x = xPost_.back();\n  }\n\n  int idx;\n  for (int i = 0; i < tVec->size() - 1; i++) {\n    if (time > tVec->at(i) && time < tVec->at(i + 1)) {\n      idx = i;\n      scalar_t fac = (time - tVec->at(idx)) / (tVec->at(idx + 1) - tVec->at(idx));\n      x = fac * xVec->at(idx) + (1 - fac) * xVec->at(idx + 1);\n      return;\n    }\n  }\n}\n\nvoid Reference::display() {\n  std::cerr << \"#########################\" << std::endl;\n  std::cerr << \"#Pre-Extended-Trajectory#\" << std::endl;\n  std::cerr << \"#########################\" << std::endl;\n  for (int i = 0; i < tPre_.size(); i++) {\n    std::cerr << tPre_[i] << \";\" << xPre_[i][0] << \";\" << xPre_[i][1] << std::endl;\n  }\n\n  std::cerr << \"#########################\" << std::endl;\n  std::cerr << \"####Normal-Trajectory####\" << std::endl;\n  std::cerr << \"#########################\" << std::endl;\n\n  scalar_t dt = 0.01;\n  for (int i = 0; i < (t1_ - t0_) / dt; i++) {\n    scalar_t t = t0_ + dt * i;\n    vector_t x;\n    getState(t, x);\n\n    std::cerr << t << \";\" << x[0] << \";\" << x[1] << std::endl;\n  }\n\n  std::cerr << \"##########################\" << std::endl;\n  std::cerr << \"#Post-Extended-Trajectory#\" << std::endl;\n  std::cerr << \"##########################\" << std::endl;\n\n  for (int i = 0; i < tPost_.size(); i++) {\n    std::cerr << tPost_[i] << \";\" << xPost_[i][0] << \";\" << xPost_[i][1] << std::endl;\n  }\n}\n\nEigen::Matrix<scalar_t, 6, 1> Reference::polyder(Eigen::Matrix<scalar_t, 6, 1> pol) {\n  Eigen::Matrix<scalar_t, 6, 1> polOld = pol;\n\n  for (int i = 0; i < pol.size(); i++) {\n    if (i < pol.size() - 1) {\n      pol[i] = (i + 1) * polOld[i + 1];\n    } else {\n      pol[i] = 0;\n    }\n  }\n\n  return pol;\n}\n", "meta": {"hexsha": "2a1fc96562f6ec128b0043f72070d81d290d9f75", "size": 7766, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ocs2_ddp/test/bouncingmass/Reference.cpp", "max_stars_repo_name": "grizzi/ocs2", "max_stars_repo_head_hexsha": "4b78c4825deb8b2efc992fdbeef6fdb1fcca2345", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 126.0, "max_stars_repo_stars_event_min_datetime": "2021-07-13T13:59:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T02:52:18.000Z", "max_issues_repo_path": "ocs2_ddp/test/bouncingmass/Reference.cpp", "max_issues_repo_name": "grizzi/ocs2", "max_issues_repo_head_hexsha": "4b78c4825deb8b2efc992fdbeef6fdb1fcca2345", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2021-07-14T12:14:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T16:27:52.000Z", "max_forks_repo_path": "ocs2_ddp/test/bouncingmass/Reference.cpp", "max_forks_repo_name": "grizzi/ocs2", "max_forks_repo_head_hexsha": "4b78c4825deb8b2efc992fdbeef6fdb1fcca2345", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 55.0, "max_forks_repo_forks_event_min_datetime": "2021-07-14T07:08:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:54:30.000Z", "avg_line_length": 35.1402714932, "max_line_length": 139, "alphanum_fraction": 0.6075199588, "num_tokens": 2461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.45870494552603835}}
{"text": "#include \"ekf.h\"\n\n#include <ros/ros.h>\n#include <ros/console.h>\n#include <sensor_msgs/Imu.h>\n#include <sensor_msgs/Range.h>\n#include <nav_msgs/Odometry.h>\n#include <Eigen/Eigen>\n#include <Eigen/Geometry>\n#include <Eigen/Dense>\n#include <geometry_msgs/Pose.h>\n#include <geometry_msgs/PoseStamped.h>\n#include \"conversion.h\"\n\nusing namespace std;\nusing namespace Eigen;\n\n//X_state: p q v gb ab   with time stamp aligned between imu and img\n/*\n    EKF model\n    prediction:\n    xt~ = xt-1 + dt*f(xt-1, ut, 0)\n    sigmat~ = Ft*sigmat-1*Ft' + Vt*Qt*Vt'\n    Update:\n    Kt = sigmat~*Ct'*(Ct*sigmat~*Ct' + Wt*Rt*Wt')^-1\n    xt = xt~ + Kt*(zt - g(xt~,0))\n    sigmat = sigmat~ - Kt*Ct*sigmat~\n*/\n/*\n   -pi ~ pi crossing problem:\n   1. the model prpagation: X_state should be limited to [-pi,pi] after predicting and updating\n   2. inovation crossing: (measurement - g(X_state)) should also be limited to [-pi,pi] when getting the inovation.\n   z_measurement is normally in [-pi~pi]\n*/\n\n// imu frame is imu body frame\n\n//odom: pose px,py pz orientation qw qx qy qz\n//imu: acc: x y z gyro: wx wy wz\n\nros::Publisher odom_pub;\nros::Publisher cam_odom_pub;\n\n//state\ngeometry_msgs::Pose pose;\nVector3d position, orientation, velocity;\n\n// Now set up the relevant matrices\n//states X [p q pdot]  [px,py,pz, wx,wy,wz, vx,vy,vz]\nsize_t stateSize;                                // x = [p q pdot bg ba]\nsize_t stateSize_pqv;                                // x = [p q pdot]\nsize_t measurementSize;                          // z = [p q]\nsize_t inputSize;                                // u = [w a]\nVectorXd X_state(stateSize);                     // x (in most literature)\nVectorXd u_input;\nVectorXd Z_measurement;                          // z\nMatrixXd StateCovariance;                        // sigma\nMatrixXd Kt_kalmanGain;                          // Kt\nVectorXd X_state_correct(stateSize);                     // x (in most literature)\nMatrixXd StateCovariance_correct;                        // sigma\nMatrixXd Qt;\nMatrixXd Rt;\nVector3d u_gyro;\nVector3d u_acc;\nVector3d gravity(0., 0., -9.8); //need to estimate the bias 9.8099\nVector3d bg_0(0., 0., 0); //need to estimate the bias\nVector3d ba_0(0., 0., 0); //need to estimate the bias  0.1\nVector3d ng(0., 0., 0.);\nVector3d na(0., 0., 0.);\nVector3d nbg(0., 0., 0.);\nVector3d nba(0., 0., 0.);\n\nVector3d q_last;\nVector3d bg_last;\nVector3d ba_last;\n\n//Qt imu covariance matrix  smaller believe system(imu) more\ndouble gyro_cov = 0.01;\ndouble acc_cov = 0.01;\n//Rt visual odomtry covariance smaller believe measurement more\ndouble position_cov = 0.1;\ndouble q_rp_cov = 0.1;\ndouble q_yaw_cov = 0.1;\n\ndouble dt = 0.005; //second\ndouble t_last, t_now;  \nbool first_frame_imu = true;\nbool first_frame_tag_odom = true;\nbool test_odomtag_call = false;\nbool odomtag_call = false;\n\ndouble time_now, time_last;\ndouble time_odom_tag_now;\ndouble diff_time;\n//world frame points velocity\nvector< pair<VectorXd, sensor_msgs::Imu> > sys_seq;  // keep a sequence of sys imu and X_state(before imu system prediction)\nvector<MatrixXd> cov_seq;\n\n//Rotation from the camera frame to the IMU frame\nMatrix3d Rc_i;     \nVector3d tc_i;  //  cam in imu frame\nint cnt = 0;\nVector3d INNOVATION_;\nMatrix3d Rr_i;     \nVector3d tr_i;  //  rigid body in imu frame\n\nvoid imu_callback(const sensor_msgs::Imu::ConstPtr &msg)\n{\n    // first_frame_tag_odom \u521d\u59cb\u4e3atrue\uff0c\u6536\u5230vicon\u540e\u8bbe\u7f6e\u4e3afalse\n    if(!first_frame_tag_odom)\n    { \n        // \u7b2c\u4e00\u6b21\u56de\u8c03\uff1a\u53d1\u5e03\u521d\u59cb\u503c\n        if(first_frame_imu)\n        {\n            first_frame_imu = false;\n            time_now = msg->header.stamp.toSec();\n            time_last = time_now;\n            // \u53d1\u5e03\u521d\u59cb\u503c\n            system_pub(msg->header.stamp);\n        }\n        else\n        {\n            time_now = msg->header.stamp.toSec();\n            // \u65f6\u95f4\u5dee\n            dt = time_now - time_last;\n\n            if(odomtag_call)\n            {\n                odomtag_call = false;\n                diff_time = time_now - time_odom_tag_now;\n                if(diff_time<0)\n                {\n                    cout << \"diff time: \" << diff_time << endl;  //???!!! exist !!!???\n                    cout << \"timeimu: \" << time_now - 1.60889e9 << \" time_odom: \" << time_odom_tag_now - 1.60889e9 << endl;\n                    // cout << \"diff time: \" << diff_time << endl;  //about 30ms\n                }\n            }\n            MatrixXd Ft;\n            MatrixXd Vt;\n\n            // \u5c06imu\u5b58\u4e3a\u8f93\u5165\u503c\n            u_gyro(0) = msg->angular_velocity.x;\n            u_gyro(1) = msg->angular_velocity.y;\n            u_gyro(2) = msg->angular_velocity.z;\n            u_acc(0)  = msg->linear_acceleration.x;\n            u_acc(1)  = msg->linear_acceleration.y;\n            u_acc(2)  = msg->linear_acceleration.z;\n\n            // \u4e0a\u4e00\u65f6\u523b\u59ff\u6001\n            q_last = X_state.segment<3>(3);  // last X2\n            bg_last = X_state.segment<3>(9);  //last X4\n            ba_last = X_state.segment<3>(12);  //last X5\n            Ft = MatrixXd::Identity(stateSize, stateSize) + dt*diff_f_diff_x(q_last, u_gyro, u_acc, bg_last, ba_last);\n         \n            Vt = dt*diff_f_diff_n(q_last);\n\n            // \u4f7f\u7528\u8f93\u5165\u66f4\u65b0\u72b6\u6001\n            X_state += dt*F_model(u_gyro, u_acc);\n            // \u6b27\u62c9\u89d2\u9650\u5236\u5e45\u5ea6\n            if(X_state(3) > PI)  X_state(3) -= 2*PI;\n            if(X_state(3) < -PI) X_state(3) += 2*PI;\n            if(X_state(4) > PI)  X_state(4) -= 2*PI;\n            if(X_state(4) < -PI) X_state(4) += 2*PI;\n            if(X_state(5) > PI)  X_state(5) -= 2*PI;\n            if(X_state(5) < -PI) X_state(5) += 2*PI;\n            // \u66f4\u65b0COV\n            StateCovariance = Ft*StateCovariance*Ft.transpose() + Vt*Qt*Vt.transpose();\n \n            time_last = time_now;\n            \n            system_pub(msg->header.stamp);\n        }\n    }\n  \n}\n\nVectorXd get_pose_from_mocap(const geometry_msgs::PoseStamped::ConstPtr &msg) \n{\n    Matrix3d Rr_w;    //rigid body in world\n    Vector3d tr_w;\n    Matrix3d Ri_w;  \n    Vector3d ti_w;\n    Vector3d p_temp;\n    // \u4f4d\u7f6e\n    p_temp(0) = msg->pose.position.x;\n    p_temp(1) = msg->pose.position.y;\n    p_temp(2) = msg->pose.position.z;\n    //quaternion2euler:  ZYX  roll pitch yaw\n    Quaterniond q;\n    // \u59ff\u6001\n    q.w() = msg->pose.orientation.w;\n    q.x() = msg->pose.orientation.x;\n    q.y() = msg->pose.orientation.y;\n    q.z() = msg->pose.orientation.z;\n    \n    // \u521a\u4f53\u7684\u4f4d\u7f6e\u548c\u59ff\u6001\n    Rr_w = q.toRotationMatrix();\n    tr_w = p_temp;\n    // imu\u7684\u4f4d\u7f6e\u548c\u59ff\u6001\n    Ri_w = Rr_w * Rr_i.inverse();\n    ti_w = tr_w - Ri_w*tr_i;\n    Vector3d euler = mat2euler(Ri_w);\n\n    VectorXd pose = VectorXd::Random(6);\n    // imu\u7684\u4f4d\u7f6e\u548c\u59ff\u6001\n    pose.segment<3>(0) = ti_w;\n    pose.segment<3>(3) = euler;\n\n    return pose;\n}\n\nvoid mocap_callback(const geometry_msgs::PoseStamped::ConstPtr &msg)\n{\n    // \u7b2c\u4e00\u6b21\u56de\u8c03\n    if(first_frame_tag_odom)\n    {\n        first_frame_tag_odom = false;\n        time_odom_tag_now = msg->header.stamp.toSec();\n\n        VectorXd odom_pose = get_pose_from_mocap(msg);\n        X_state.segment<3>(0) = odom_pose.segment<3>(0);\n        X_state.segment<3>(3) = odom_pose.segment<3>(3);\n    }\n    else\n    {\n        time_odom_tag_now = msg->header.stamp.toSec();\n        MatrixXd Ct;\n        MatrixXd Wt;\n\n        // \u83b7\u53d6\u5f97\u5230imu\u7684\u4f4d\u7f6e\u59ff\u6001\uff08imu\u548c\u8d28\u5fc3\u5b58\u5728\u504f\u5dee\uff09\n        VectorXd odom_pose = get_pose_from_mocap(msg);\n        // \u66f4\u65b0\u6d4b\u91cf\u503c\n        Z_measurement.segment<3>(0) = odom_pose.segment<3>(0);\n        Z_measurement.segment<3>(3) = odom_pose.segment<3>(3);\n        // \u53d1\u5e03\u6d4b\u91cf\u503c\uff08\u5373mocap\u7684\u539f\u59cb\u503c\uff09\n        cam_system_pub(msg->header.stamp);\n\n        Ct = diff_g_diff_x();\n        Wt = diff_g_diff_v();\n\n        // \u66f4\u65b0kalman\u589e\u76ca\n        Kt_kalmanGain = StateCovariance*Ct.transpose() * (Ct*StateCovariance*Ct.transpose() + Wt*Rt*Wt.transpose()).inverse();\n        VectorXd gg = g_model();\n        VectorXd innovation = Z_measurement - gg;\n    \n        //Prevent innovation changing suddenly when euler from -Pi to Pi\n        if(innovation(3) > 6)  innovation(3) -= 2*PI;\n        if(innovation(3) < -6) innovation(3) += 2*PI;\n        if(innovation(4) > 6)  innovation(4) -= 2*PI;\n        if(innovation(4) < -6) innovation(4) += 2*PI;\n        if(innovation(5) > 6)  innovation(5) -= 2*PI;\n        if(innovation(5) < -6) innovation(5) += 2*PI;\n        INNOVATION_ = innovation.segment<3>(3);\n        // \u4f7f\u7528\u6d4b\u91cf\u503c\u66f4\u65b0\u72b6\u6001\n        X_state += Kt_kalmanGain*(innovation);\n        if(X_state(3) > PI)  X_state(3) -= 2*PI;\n        if(X_state(3) < -PI) X_state(3) += 2*PI;\n        if(X_state(4) > PI)  X_state(4) -= 2*PI;\n        if(X_state(4) < -PI) X_state(4) += 2*PI;\n        if(X_state(5) > PI)  X_state(5) -= 2*PI;\n        if(X_state(5) < -PI) X_state(5) += 2*PI;\n        StateCovariance = StateCovariance - Kt_kalmanGain*Ct*StateCovariance;\n        \n        test_odomtag_call = true;\n        odomtag_call = true;\n        \n        if(cnt == 10||cnt==50||cnt==90)\n        {\n            // cout << \"Ct: \\n\" << Ct << \"\\nWt:\\n\" << Wt << endl; \n            // cout << \"Kt_kalmanGain: \\n\" << Kt_kalmanGain << endl; \n            // cout << \"\\ninnovation: \\n\" << Kt_kalmanGain*innovation  << \"\\ndt:\\n\" << dt << endl;\n            // cout << \"\\ninnovation: \\n\" << Kt_kalmanGain*innovation  << endl;\n            // cout << \"\\ninnovation: \\n\" << INNOVATION_ << endl; \n        }\n        cnt++;\n        if(cnt>100) cnt=101;\n    }\n    \n}\n\nint main(int argc, char **argv)\n{\n    ros::init(argc, argv, \"mocap_ekf_node\");\n    ros::NodeHandle n(\"~\");\n    // \u3010\u8ba2\u9605\u3011 IMU\u6570\u636e\uff0c\u6765\u81eaPX4\n    ros::Subscriber s1 = n.subscribe(\"imu\", 100, imu_callback, ros::TransportHints().tcpNoDelay());\n    // \u3010\u8ba2\u9605\u3011 VICON\u6570\u636e\n    ros::Subscriber s2 = n.subscribe(\"pose\", 100, mocap_callback, ros::TransportHints().tcpNoDelay());\n    // \u3010\u53d1\u5e03\u3011 \u878d\u5408\u540e\u7684odom(\u53d1\u5e03\u9891\u7387\u4e3aimu\u7684\u9891\u7387)\n    odom_pub = n.advertise<nav_msgs::Odometry>(\"ekf_odom\", 100);  \n    // \u3010\u53d1\u5e03\u3011 \u76f8\u673aodom\uff1f\n    cam_odom_pub = n.advertise<nav_msgs::Odometry>(\"cam_ekf_odom\", 100);  \n    \n    n.getParam(\"gyro_cov\", gyro_cov);\n    n.getParam(\"acc_cov\", acc_cov);\n    n.getParam(\"position_cov\", position_cov);\n    n.getParam(\"q_rp_cov\", q_rp_cov);\n    n.getParam(\"q_yaw_cov\", q_yaw_cov);\n\n    cout << \"Q:\" << gyro_cov << \" \" << acc_cov << \" R: \" << position_cov << \" \" << q_rp_cov << \" \" << q_yaw_cov << endl;\n\n    // \u521d\u59cb\u5316\n    initsys();\n    cout << \"initsys\" << endl;\n\n    cout << \"======================\" << endl;\n    double r = atan2(1,-100);\n    double p = asin(-0.707);\n    double y = atan2(-1, -100);   \n    cout << \"r: \" << r << \" p: \" << p << \" y: \" << y << endl;\n    cout << \"======================\" << endl;\n\n    ros::spin();\n}\n\nvoid system_pub(ros::Time stamp)\n{\n    nav_msgs::Odometry odom_fusion;\n    odom_fusion.header.stamp = stamp;\n    odom_fusion.header.frame_id = \"world\";\n    // odom_fusion.header.frame_id = \"imu\";\n    odom_fusion.pose.pose.position.x = X_state(0);\n    odom_fusion.pose.pose.position.y = X_state(1);\n    odom_fusion.pose.pose.position.z = X_state(2);\n    Quaterniond q;\n    q = euler2quaternion(X_state.segment<3>(3));\n    odom_fusion.pose.pose.orientation.w = q.w();\n    odom_fusion.pose.pose.orientation.x = q.x();\n    odom_fusion.pose.pose.orientation.y = q.y();\n    odom_fusion.pose.pose.orientation.z = q.z();\n    odom_fusion.twist.twist.linear.x = X_state(6);\n    odom_fusion.twist.twist.linear.y = X_state(7);\n    odom_fusion.twist.twist.linear.z = X_state(8);\n    odom_pub.publish(odom_fusion);\n}\n\nvoid cam_system_pub(ros::Time stamp)\n{\n    // \u6d4b\u91cf\u503c\n    nav_msgs::Odometry odom_fusion;\n    odom_fusion.header.stamp = stamp;\n    odom_fusion.header.frame_id = \"world\";\n\n    odom_fusion.pose.pose.position.x = Z_measurement(0);\n    odom_fusion.pose.pose.position.y = Z_measurement(1);\n    odom_fusion.pose.pose.position.z = Z_measurement(2);\n    Quaterniond q;\n    q = euler2quaternion(Z_measurement.segment<3>(3));\n    odom_fusion.pose.pose.orientation.w = q.w();\n    odom_fusion.pose.pose.orientation.x = q.x();\n    odom_fusion.pose.pose.orientation.y = q.y();\n    odom_fusion.pose.pose.orientation.z = q.z();\n\n    odom_fusion.twist.twist.angular.x = diff_time;\n    odom_fusion.twist.twist.angular.y = dt;\n    cam_odom_pub.publish(odom_fusion);\n}\n\n//process model\nvoid initsys()\n{\n    //  camera position in the IMU frame = (0.05, 0.05, 0)\n    // camera orientaion in the IMU frame = Quaternion(0, 1, 0, 0); w x y z, respectively\n    //\t\t\t\t\t   RotationMatrix << 1, 0, 0,\n    //\t\t\t\t\t\t\t             0, -1, 0,\n    //                                       0, 0, -1;\n    //set the cam2imu params\n    Rc_i = Quaterniond(0, 1, 0, 0).toRotationMatrix();\n    // cout << \"R_cam\" << endl << Rc_i << endl;\n    tc_i << 0.05, 0.05, 0; \n\n    Rr_i = Quaterniond(1, 0, 0, 0).toRotationMatrix();\n    tr_i << 0, 0, 0.055;\n    cout << \"Rr_i: \" << endl << Rr_i << endl;\n    cout << \"tr_i: \" << endl << tr_i << endl;\n    //  rigid body position in the IMU frame = (0, 0, 0.04)\n    // rigid body orientaion in the IMU frame = Quaternion(1, 0, 0, 0); w x y z, respectively\n    //\t\t\t\t\t   RotationMatrix << 1, 0, 0,\n    //\t\t\t\t\t\t\t             0, 1, 0,\n    //                                       0, 0, 1; \n\n    //states X \n    // \u72b6\u6001\u7ef4\u5ea6 [p q pdot bg ba]  [px,py,pz, wx,wy,wz\uff08\u6b27\u62c9\u89d2\uff09, vx,vy,vz bgx,bgy,bgz bax,bay,baz]\n    stateSize = 15;                                                                 // x = [p q pdot bg ba]\n    stateSize_pqv = 9;                                                              // x = [p q pdot]\n    // \u6d4b\u91cf\u7ef4\u5ea6 \u4f4d\u7f6e+\u59ff\u6001\n    measurementSize = 6;                                                            // z = [p q]\n    // \u8f93\u5165\u7ef4\u5ea6 w\u662f\u89d2\u901f\u5ea6 a\u662f\u52a0\u901f\u5ea6\n    inputSize = 6;                                                                  // u = [w a]\n    X_state = VectorXd::Zero(stateSize);                                            // x \n    //velocity\n    X_state(6) = 0;\n    X_state(7) = 0;\n    X_state(8) = 0; \n    // bias\n    X_state.segment<3>(9) = bg_0;\n    X_state.segment<3>(12) = ba_0;\n    // \u8f93\u5165\n    u_input = VectorXd::Zero(inputSize);\n    // \u6d4b\u91cf\n    Z_measurement = VectorXd::Zero(measurementSize);                                // z\n    // \u72b6\u6001cov\n    StateCovariance = MatrixXd::Identity(stateSize, stateSize);                     // sigma\n    // kalman\u589e\u76ca\n    Kt_kalmanGain = MatrixXd::Identity(stateSize, measurementSize);                 // Kt\n    // Ct_stateToMeasurement = MatrixXd::Identity(stateSize, measurementSize);         // Ct\n    // \uff1f\n    X_state_correct = X_state;\n    // \uff1f\n    StateCovariance_correct = StateCovariance;\n\n    Qt = MatrixXd::Identity(inputSize, inputSize);  //6x6 input [gyro acc]covariance\n    Rt = MatrixXd::Identity(measurementSize, measurementSize); //6x6 measurement [p q]covariance\n\n    // You should also tune these parameters\n    // Q imu covariance matrix; Rt visual odomtry covariance matrix\n    // //Rt visual odomtry covariance smaller believe measurement more\n    Qt.topLeftCorner(3, 3) = gyro_cov * Qt.topLeftCorner(3, 3);\n    Qt.bottomRightCorner(3, 3) = acc_cov * Qt.bottomRightCorner(3, 3);\n    Rt.topLeftCorner(3, 3) = position_cov * Rt.topLeftCorner(3, 3);\n    Rt.bottomRightCorner(3, 3) = q_rp_cov * Rt.bottomRightCorner(3, 3);\n    Rt.bottomRightCorner(1, 1) = q_yaw_cov * Rt.bottomRightCorner(1, 1);\n}\n\nvoid getState(Vector3d& p, Vector3d& q, Vector3d& v, Vector3d& bg, Vector3d& ba)\n{\n\tp = X_state.segment<3>(0);\n\tq = X_state.segment<3>(3);\n\tv = X_state.segment<3>(6);\n    bg = X_state.segment<3>(9);\n    ba = X_state.segment<3>(12);\n}\n\nVectorXd F_model(Vector3d gyro, Vector3d acc)\n{\n    // IMU is in FLU frame\n    // Transform IMU frame into \"world\" frame whose original point is FLU's original point and the XOY plain is parallel with the ground and z axis is up\n    VectorXd f(VectorXd::Zero(stateSize));\n    Vector3d p, q, v, bg, ba;\n    getState(p, q, v, bg, ba);\n    f.segment<3>(0) = v;\n    f.segment<3>(3) = w_Body2Euler(q)*(gyro-bg-ng);\n    f.segment<3>(6) = gravity + euler2mat(q)*(acc-ba-na);\n    f.segment<3>(9) = nbg;\n    f.segment<3>(12) = nba;\n    return f;\n}\n\nVectorXd g_model()\n{\n    VectorXd g(VectorXd::Zero(measurementSize));\n\n    g.segment<6>(0) = X_state.segment<6>(0);\n\n    return g;\n}\n\n//F_model G_model Jocobian\n//diff_f()/diff_x (x_t-1  ut  noise=0)   At     Ft = I+dt*At\nMatrixXd diff_f_diff_x(Vector3d q_last, Vector3d gyro, Vector3d acc, Vector3d bg_last, Vector3d ba_last)\n{\n    double cr = cos( q_last(0));\n    double sr = sin( q_last(0));\n    double cp = cos( q_last(1));\n    double sp = sin( q_last(1));\n    double cy = cos( q_last(2));\n    double sy = sin( q_last(2));\n \n    // ng na = 0 nbg nba = 0\n    double Ax = acc(0) - ba_last(0);\n    double Ay = acc(1) - ba_last(1);\n    double Az = acc(2) - ba_last(2);\n    // double Wx = gyro(0) - bg_last(0);\n    double Wy = gyro(1) - bg_last(1);\n    double Wz = gyro(2) - bg_last(2);\n\n    MatrixXd diff_f_diff_x_jacobian(MatrixXd::Zero(stateSize, stateSize));\n    MatrixXd diff_f_diff_x_jacobian_pqv(MatrixXd::Zero(stateSize_pqv, stateSize_pqv));\n\n    diff_f_diff_x_jacobian_pqv <<  0, 0, 0, 0, 0, 0, 1, 0, 0,\n      0, 0, 0, 0, 0, 0, 0, 1, 0, \n      0, 0, 0, 0, 0, 0, 0, 0, 1,  \n      0, 0, 0, (sp*(Wy*cr - Wz*sr))/cp, (Wz*cr + Wy*sr)/(cp*cp), 0, 0, 0, 0,  \n      0, 0, 0, (- Wz*cr - Wy*sr), 0, 0, 0, 0, 0, \n      0, 0, 0, (Wy*cr - Wz*sr)/cp, (sp*(Wz*cr + Wy*sr))/(cp*cp), 0, 0, 0, 0, \n      0, 0, 0, (Ay*(sr*sy + cr*cy*sp) + Az*(cr*sy - cy*sp*sr)), (Az*cp*cr*cy - Ax*cy*sp + Ay*cp*cy*sr), (Az*(cy*sr - cr*sp*sy) - Ay*(cr*cy + sp*sr*sy) - Ax*cp*sy), 0, 0, 0, \n      0, 0, 0, (- Ay*(cy*sr - cr*sp*sy) - Az*(cr*cy + sp*sr*sy)), (Az*cp*cr*sy - Ax*sp*sy + Ay*cp*sr*sy), (Az*(sr*sy + cr*cy*sp) - Ay*(cr*sy - cy*sp*sr) + Ax*cp*cy), 0, 0, 0,\n      0, 0, 0, (Ay*cp*cr - Az*cp*sr), (- Ax*cp - Az*cr*sp - Ay*sp*sr), 0, 0, 0, 0 ;\n    \n    diff_f_diff_x_jacobian.block<9, 9>(0, 0) = diff_f_diff_x_jacobian_pqv;\n    diff_f_diff_x_jacobian.block<3, 3>(3, 9) = -w_Body2Euler(q_last);\n    diff_f_diff_x_jacobian.block<3, 3>(6, 12) = -euler2mat(q_last);\n\n    return diff_f_diff_x_jacobian;\n\n    // cp != 0 pitch != 90\u00b0 !!!!!!!!!\n}\n//diff_f()/diff_n (x_t-1  ut  noise=0)  Ut    Vt = dt*Ut\nMatrixXd diff_f_diff_n(Vector3d q_last)\n{\n    MatrixXd diff_f_diff_n_jacobian(MatrixXd::Zero(stateSize, inputSize));\n    diff_f_diff_n_jacobian.block<3,3>(3,0) = -w_Body2Euler(q_last);\n    diff_f_diff_n_jacobian.block<3,3>(6,3) = -euler2mat(q_last);\n\n    return diff_f_diff_n_jacobian;\n}\n//diff_g()/diff_x  (xt~ noise=0)  Ct \nMatrixXd diff_g_diff_x()\n{\n    MatrixXd diff_g_diff_x_jacobian(MatrixXd::Zero(measurementSize, stateSize));\n    diff_g_diff_x_jacobian.block<3,3>(0,0) = MatrixXd::Identity(3,3);\n    diff_g_diff_x_jacobian.block<3,3>(3,3) = MatrixXd::Identity(3,3);\n\n    return diff_g_diff_x_jacobian;\n}\n//diff_g()/diff_v  (xt~ noise=0) Wt\nMatrixXd diff_g_diff_v()\n{\n    MatrixXd diff_g_diff_v_jacobian(MatrixXd::Identity(measurementSize, measurementSize));\n\n    return diff_g_diff_v_jacobian;\n}\n", "meta": {"hexsha": "c57e00af4ec2aa18815d19d96d5c0aafab2465c4", "size": 18564, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Modules/mocap_ekf/src/mocap_ekf_node.cpp", "max_stars_repo_name": "473867143/Prometheus", "max_stars_repo_head_hexsha": "df1e1b0d861490223ac8b94d8cc4796537172292", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1217.0, "max_stars_repo_stars_event_min_datetime": "2020-07-02T13:15:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T06:17:44.000Z", "max_issues_repo_path": "Modules/mocap_ekf/src/mocap_ekf_node.cpp", "max_issues_repo_name": "473867143/Prometheus", "max_issues_repo_head_hexsha": "df1e1b0d861490223ac8b94d8cc4796537172292", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 167.0, "max_issues_repo_issues_event_min_datetime": "2020-07-12T15:35:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T11:57:40.000Z", "max_forks_repo_path": "Modules/mocap_ekf/src/mocap_ekf_node.cpp", "max_forks_repo_name": "473867143/Prometheus", "max_forks_repo_head_hexsha": "df1e1b0d861490223ac8b94d8cc4796537172292", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 270.0, "max_forks_repo_forks_event_min_datetime": "2020-07-02T13:28:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T05:43:08.000Z", "avg_line_length": 35.4952198853, "max_line_length": 174, "alphanum_fraction": 0.5791855204, "num_tokens": 6105, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851919, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4587049392124737}}
{"text": "//  saturating.cpp  ----------------------------------------------------------//\n\n//  Copyright 2008 Howard Hinnant\n//  Copyright 2008 Beman Dawes\n//  Copyright 2009 Vicente J. Botet Escriba\n\n//  Distributed under the Boost Software License, Version 1.0.\n//  See http://www.boost.org/LICENSE_1_0.txt\n\n/*\nThis code was extracted by Vicente J. Botet Escriba from Beman Dawes time2_demo.cpp which\nwas derived by Beman Dawes from Howard Hinnant's time2_demo prototype.\nMany thanks to Howard for making his code available under the Boost license.\nThe original code was modified to conform to Boost conventions and to section\n20.9 Time utilities [time] of the C++ committee's working paper N2798.\nSee http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2798.pdf.\n\ntime2_demo contained this comment:\n\n    Much thanks to Andrei Alexandrescu,\n                   Walter Brown,\n                   Peter Dimov,\n                   Jeff Garland,\n                   Terry Golubiewski,\n                   Daniel Krugler,\n                   Anthony Williams.\n*/\n\n#define _CRT_SECURE_NO_WARNINGS  // disable VC++ foolishness\n\n#include <boost/chrono/chrono.hpp>\n#include <boost/type_traits.hpp>\n\n#include <iostream>\n\n//////////////////////////////////////////////////////////\n//////////////////// User2 Example ///////////////////////\n//////////////////////////////////////////////////////////\n\n// Demonstrate User2:\n// A \"saturating\" signed integral type  is developed.  This type has +/- infinity and a nan\n// (like IEEE floating point) but otherwise obeys signed integral arithmetic.\n// This class is subsequently used as the rep in boost::chrono::duration to demonstrate a\n// duration class that does not silently ignore overflow.\n#include <ostream>\n#include <stdexcept>\n#include <climits>\n\nnamespace User2\n{\n\ntemplate <class I>\nclass saturate\n{\npublic:\n    typedef I int_type;\n\n    static const int_type nan = int_type(int_type(1) << (sizeof(int_type) * CHAR_BIT - 1));\n    static const int_type neg_inf = nan + 1;\n    static const int_type pos_inf = -neg_inf;\nprivate:\n    int_type i_;\n\n//     static_assert(std::is_integral<int_type>::value && std::is_signed<int_type>::value,\n//                   \"saturate only accepts signed integral types\");\n//     static_assert(nan == -nan && neg_inf < pos_inf,\n//                   \"saturate assumes two's complement hardware for signed integrals\");\n\npublic:\n    saturate() : i_(nan) {}\n    explicit saturate(int_type i) : i_(i) {}\n    // explicit\n    operator int_type() const;\n\n    saturate& operator+=(saturate x);\n    saturate& operator-=(saturate x) {return *this += -x;}\n    saturate& operator*=(saturate x);\n    saturate& operator/=(saturate x);\n    saturate& operator%=(saturate x);\n\n    saturate  operator- () const {return saturate(-i_);}\n    saturate& operator++()       {*this += saturate(int_type(1)); return *this;}\n    saturate  operator++(int)    {saturate tmp(*this); ++(*this); return tmp;}\n    saturate& operator--()       {*this -= saturate(int_type(1)); return *this;}\n    saturate  operator--(int)    {saturate tmp(*this); --(*this); return tmp;}\n\n    friend saturate operator+(saturate x, saturate y) {return x += y;}\n    friend saturate operator-(saturate x, saturate y) {return x -= y;}\n    friend saturate operator*(saturate x, saturate y) {return x *= y;}\n    friend saturate operator/(saturate x, saturate y) {return x /= y;}\n    friend saturate operator%(saturate x, saturate y) {return x %= y;}\n\n    friend bool operator==(saturate x, saturate y)\n    {\n        if (x.i_ == nan || y.i_ == nan)\n            return false;\n        return x.i_ == y.i_;\n    }\n\n    friend bool operator!=(saturate x, saturate y) {return !(x == y);}\n\n    friend bool operator<(saturate x, saturate y)\n    {\n        if (x.i_ == nan || y.i_ == nan)\n            return false;\n        return x.i_ < y.i_;\n    }\n\n    friend bool operator<=(saturate x, saturate y)\n    {\n        if (x.i_ == nan || y.i_ == nan)\n            return false;\n        return x.i_ <= y.i_;\n    }\n\n    friend bool operator>(saturate x, saturate y)\n    {\n        if (x.i_ == nan || y.i_ == nan)\n            return false;\n        return x.i_ > y.i_;\n    }\n\n    friend bool operator>=(saturate x, saturate y)\n    {\n        if (x.i_ == nan || y.i_ == nan)\n            return false;\n        return x.i_ >= y.i_;\n    }\n\n    friend std::ostream& operator<<(std::ostream& os, saturate s)\n    {\n        switch (s.i_)\n        {\n        case pos_inf:\n            return os << \"inf\";\n        case nan:\n            return os << \"nan\";\n        case neg_inf:\n            return os << \"-inf\";\n        };\n        return os << s.i_;\n    }\n};\n\ntemplate <class I>\nsaturate<I>::operator I() const\n{\n    switch (i_)\n    {\n    case nan:\n    case neg_inf:\n    case pos_inf:\n        throw std::out_of_range(\"saturate special value can not convert to int_type\");\n    }\n    return i_;\n}\n\ntemplate <class I>\nsaturate<I>&\nsaturate<I>::operator+=(saturate x)\n{\n    switch (i_)\n    {\n    case pos_inf:\n        switch (x.i_)\n        {\n        case neg_inf:\n        case nan:\n            i_ = nan;\n        }\n        return *this;\n    case nan:\n        return *this;\n    case neg_inf:\n        switch (x.i_)\n        {\n        case pos_inf:\n        case nan:\n            i_ = nan;\n        }\n        return *this;\n    }\n    switch (x.i_)\n    {\n    case pos_inf:\n    case neg_inf:\n    case nan:\n        i_ = x.i_;\n        return *this;\n    }\n    if (x.i_ >= 0)\n    {\n        if (i_ < pos_inf - x.i_)\n            i_ += x.i_;\n        else\n            i_ = pos_inf;\n        return *this;\n    }\n    if (i_ > neg_inf - x.i_)\n        i_ += x.i_;\n    else\n        i_ = neg_inf;\n    return *this;\n}\n\ntemplate <class I>\nsaturate<I>&\nsaturate<I>::operator*=(saturate x)\n{\n    switch (i_)\n    {\n    case 0:\n        switch (x.i_)\n        {\n        case pos_inf:\n        case neg_inf:\n        case nan:\n            i_ = nan;\n        }\n        return *this;\n    case pos_inf:\n        switch (x.i_)\n        {\n        case nan:\n        case 0:\n            i_ = nan;\n            return *this;\n        }\n        if (x.i_ < 0)\n            i_ = neg_inf;\n        return *this;\n    case nan:\n        return *this;\n    case neg_inf:\n        switch (x.i_)\n        {\n        case nan:\n        case 0:\n            i_ = nan;\n            return *this;\n        }\n        if (x.i_ < 0)\n            i_ = pos_inf;\n        return *this;\n    }\n    switch (x.i_)\n    {\n    case 0:\n        i_ = 0;\n        return *this;\n    case nan:\n        i_ = nan;\n        return *this;\n    case pos_inf:\n        if (i_ < 0)\n            i_ = neg_inf;\n        else\n            i_ = pos_inf;\n        return *this;\n    case neg_inf:\n        if (i_ < 0)\n            i_ = pos_inf;\n        else\n            i_ = neg_inf;\n        return *this;\n    }\n    int s = (i_ < 0 ? -1 : 1) * (x.i_ < 0 ? -1 : 1);\n    i_ = i_ < 0 ? -i_ : i_;\n    int_type x_i_ = x.i_ < 0 ? -x.i_ : x.i_;\n    if (i_ <= pos_inf / x_i_)\n        i_ *= x_i_;\n    else\n        i_ = pos_inf;\n    i_ *= s;\n    return *this;\n}\n\ntemplate <class I>\nsaturate<I>&\nsaturate<I>::operator/=(saturate x)\n{\n    switch (x.i_)\n    {\n    case pos_inf:\n    case neg_inf:\n        switch (i_)\n        {\n        case pos_inf:\n        case neg_inf:\n        case nan:\n            i_ = nan;\n            break;\n        default:\n            i_ = 0;\n            break;\n        }\n        return *this;\n    case nan:\n        i_ = nan;\n        return *this;\n    case 0:\n        switch (i_)\n        {\n        case pos_inf:\n        case neg_inf:\n        case nan:\n            return *this;\n        case 0:\n            i_ = nan;\n            return *this;\n        }\n        if (i_ > 0)\n            i_ = pos_inf;\n        else\n            i_ = neg_inf;\n        return *this;\n    }\n    switch (i_)\n    {\n    case 0:\n    case nan:\n        return *this;\n    case pos_inf:\n    case neg_inf:\n        if (x.i_ < 0)\n            i_ = -i_;\n        return *this;\n    }\n    i_ /= x.i_;\n    return *this;\n}\n\ntemplate <class I>\nsaturate<I>&\nsaturate<I>::operator%=(saturate x)\n{\n//    *this -= *this / x * x;  // definition\n    switch (x.i_)\n    {\n    case nan:\n    case neg_inf:\n    case 0:\n    case pos_inf:\n        i_ = nan;\n        return *this;\n    }\n    switch (i_)\n    {\n    case neg_inf:\n    case pos_inf:\n        i_ = nan;\n    case nan:\n        return *this;\n    }\n    i_ %= x.i_;\n    return *this;\n}\n\n// Demo overflow-safe integral durations ranging from picoseconds resolution to millennium resolution\ntypedef boost::chrono::duration<saturate<long long>, boost::pico                 > picoseconds;\ntypedef boost::chrono::duration<saturate<long long>, boost::nano                 > nanoseconds;\ntypedef boost::chrono::duration<saturate<long long>, boost::micro                > microseconds;\ntypedef boost::chrono::duration<saturate<long long>, boost::milli                > milliseconds;\ntypedef boost::chrono::duration<saturate<long long>                            > seconds;\ntypedef boost::chrono::duration<saturate<long long>, boost::ratio<         60LL> > minutes;\ntypedef boost::chrono::duration<saturate<long long>, boost::ratio<       3600LL> > hours;\ntypedef boost::chrono::duration<saturate<long long>, boost::ratio<      86400LL> > days;\ntypedef boost::chrono::duration<saturate<long long>, boost::ratio<   31556952LL> > years;\ntypedef boost::chrono::duration<saturate<long long>, boost::ratio<31556952000LL> > millennium;\n\n}  // User2\n\n// Demonstrate custom promotion rules (needed only if there are no implicit conversions)\nnamespace User2 { namespace detail {\n\ntemplate <class T1, class T2, bool = boost::is_integral<T1>::value>\nstruct promote_helper;\n\ntemplate <class T1, class T2>\nstruct promote_helper<T1, saturate<T2>, true>  // integral\n{\n    typedef typename boost::common_type<T1, T2>::type rep;\n    typedef User2::saturate<rep> type;\n};\n\ntemplate <class T1, class T2>\nstruct promote_helper<T1, saturate<T2>, false>  // floating\n{\n    typedef T1 type;\n};\n\n} }\n\nnamespace boost\n{\n\ntemplate <class T1, class T2>\nstruct common_type<User2::saturate<T1>, User2::saturate<T2> >\n{\n    typedef typename common_type<T1, T2>::type rep;\n    typedef User2::saturate<rep> type;\n};\n\ntemplate <class T1, class T2>\nstruct common_type<T1, User2::saturate<T2> >\n    : User2::detail::promote_helper<T1, User2::saturate<T2> > {};\n\ntemplate <class T1, class T2>\nstruct common_type<User2::saturate<T1>, T2>\n    : User2::detail::promote_helper<T2, User2::saturate<T1> > {};\n\n\n// Demonstrate specialization of duration_values:\n\nnamespace chrono {\n\ntemplate <class I>\nstruct duration_values<User2::saturate<I> >\n{\n    typedef User2::saturate<I> Rep;\npublic:\n    static Rep zero() {return Rep(0);}\n    static Rep max BOOST_PREVENT_MACRO_SUBSTITUTION ()  {return Rep(Rep::pos_inf-1);}\n    static Rep min BOOST_PREVENT_MACRO_SUBSTITUTION ()  {return -(max)();}\n};\n\n}  // namespace chrono\n\n}  // namespace boost\n\n#include <iostream>\n\nvoid testUser2()\n{\n    std::cout << \"*************\\n\";\n    std::cout << \"* testUser2 *\\n\";\n    std::cout << \"*************\\n\";\n    using namespace User2;\n    typedef seconds::rep sat;\n    years yr(sat(100));\n    std::cout << \"100 years expressed as years = \" << yr.count() << '\\n';\n    nanoseconds ns = yr;\n    std::cout << \"100 years expressed as nanoseconds = \" << ns.count() << '\\n';\n    ns += yr;\n    std::cout << \"200 years expressed as nanoseconds = \" << ns.count() << '\\n';\n    ns += yr;\n    std::cout << \"300 years expressed as nanoseconds = \" << ns.count() << '\\n';\n//    yr = ns;  // does not compile\n    std::cout << \"yr = ns;  // does not compile\\n\";\n//    picoseconds ps1 = yr;  // does not compile, compile-time overflow in ratio arithmetic\n    std::cout << \"ps = yr;  // does not compile\\n\";\n    ns = yr;\n    picoseconds ps = ns;\n    std::cout << \"100 years expressed as picoseconds = \" << ps.count() << '\\n';\n    ps = ns / sat(1000);\n    std::cout << \"0.1 years expressed as picoseconds = \" << ps.count() << '\\n';\n    yr = years(sat(-200000000));\n    std::cout << \"200 million years ago encoded in years: \" << yr.count() << '\\n';\n    days d = boost::chrono::duration_cast<days>(yr);\n    std::cout << \"200 million years ago encoded in days: \" << d.count() << '\\n';\n    millennium c = boost::chrono::duration_cast<millennium>(yr);\n    std::cout << \"200 million years ago encoded in millennium: \" << c.count() << '\\n';\n    std::cout << \"Demonstrate \\\"uninitialized protection\\\" behavior:\\n\";\n    seconds sec;\n    for (++sec; sec < seconds(sat(10)); ++sec)\n        ;\n    std::cout << sec.count() << '\\n';\n    std::cout << \"\\n\";\n}\n\nvoid testStdUser()\n{\n    std::cout << \"***************\\n\";\n    std::cout << \"* testStdUser *\\n\";\n    std::cout << \"***************\\n\";\n    using namespace boost::chrono;\n    hours hr = hours(100);\n    std::cout << \"100 hours expressed as hours = \" << hr.count() << '\\n';\n    nanoseconds ns = hr;\n    std::cout << \"100 hours expressed as nanoseconds = \" << ns.count() << '\\n';\n    ns += hr;\n    std::cout << \"200 hours expressed as nanoseconds = \" << ns.count() << '\\n';\n    ns += hr;\n    std::cout << \"300 hours expressed as nanoseconds = \" << ns.count() << '\\n';\n//    hr = ns;  // does not compile\n    std::cout << \"hr = ns;  // does not compile\\n\";\n//    hr * ns;  // does not compile\n    std::cout << \"hr * ns;  // does not compile\\n\";\n    duration<double> fs(2.5);\n    std::cout << \"duration<double> has count() = \" << fs.count() << '\\n';\n//    seconds sec = fs;  // does not compile\n    std::cout << \"seconds sec = duration<double> won't compile\\n\";\n    seconds sec = duration_cast<seconds>(fs);\n    std::cout << \"seconds has count() = \" << sec.count() << '\\n';\n    std::cout << \"\\n\";\n}\n\n\nint main()\n{\n    testStdUser();\n    testUser2();\n    return 0;\n}\n", "meta": {"hexsha": "e7a082c0b2a2cfa82469a4a405b84d81973370c3", "size": 13673, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/libs/chrono/example/saturating.cpp", "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/libs/chrono/example/saturating.cpp", "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/libs/chrono/example/saturating.cpp", "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": 27.0752475248, "max_line_length": 101, "alphanum_fraction": 0.5518174504, "num_tokens": 3750, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410572017153, "lm_q2_score": 0.6893056295505783, "lm_q1q2_score": 0.4586712532538941}}
{"text": "/* vim: set tabstop=4 expandtab shiftwidth=4 softtabstop=4: */\n\n/**\n * \\file libs/numeric/ublasx/test/sqrt.cpp\n *\n * \\brief Test suite for the \\c sqrt operation.\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n *\n * <hr/>\n *\n * Copyright (c) 2011, Marco Guazzone\n *\n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublasx/operation/sqrt.hpp>\n#include <cmath>\n#include <complex>\n#include <cstddef>\n#include \"libs/numeric/ublasx/test/utils.hpp\"\n\n\nnamespace ublas = ::boost::numeric::ublas;\nnamespace ublasx = ::boost::numeric::ublasx;\n\n\nstatic const double tol = 1.0e-5;\n\n\nBOOST_UBLASX_TEST_DEF( test_real_vector )\n{\n    BOOST_UBLASX_DEBUG_TRACE( \"Test Case: Real - Vector\" );\n\n    typedef double value_type;\n    typedef std::size_t size_type;\n    typedef ublas::vector<value_type> vector_type;\n\n    const size_type n(4);\n\n    vector_type v(n);\n\n    v(0) = 1;\n    v(1) = 2;\n    v(2) = 3;\n    v(3) = 4;\n\n    vector_type res;\n    vector_type expect_res(n);\n\n    res = ublasx::sqrt(v);\n\n    BOOST_UBLASX_DEBUG_TRACE( \"v = \" << v );\n    BOOST_UBLASX_DEBUG_TRACE( \"sqrt(v) = \" << res );\n\n    for (size_type i = 0; i < n; ++i)\n    {\n        expect_res(i) = ::std::sqrt(v(i));\n    }\n\n    BOOST_UBLASX_TEST_CHECK_VECTOR_CLOSE( res, expect_res, n, tol );\n}\n\n\nBOOST_UBLASX_TEST_DEF( test_complex_vector )\n{\n    BOOST_UBLASX_DEBUG_TRACE( \"Test Case: Complex - Vector\" );\n\n    typedef std::complex<double> in_value_type;\n    typedef in_value_type out_value_type;\n    typedef std::size_t size_type;\n    typedef ublas::vector<in_value_type> in_vector_type;\n    typedef ublas::vector<out_value_type> out_vector_type;\n\n    const size_type n(4);\n\n    in_vector_type v(n);\n\n    v(0) = in_value_type( 1, 2);\n    v(1) = in_value_type(-2, 3);\n    v(2) = in_value_type(-3,-4);\n    v(3) = in_value_type( 4,-5);\n\n    out_vector_type res;\n    out_vector_type expect_res(n);\n\n    res = ublasx::sqrt(v);\n\n    BOOST_UBLASX_DEBUG_TRACE( \"v = \" << v );\n    BOOST_UBLASX_DEBUG_TRACE( \"sqrt(v) = \" << res );\n\n    for (size_type i = 0; i < n; ++i)\n    {\n        expect_res(i) = ::std::sqrt(v(i));\n    }\n\n    BOOST_UBLASX_TEST_CHECK_VECTOR_CLOSE( res, expect_res, n, tol );\n}\n\n\nBOOST_UBLASX_TEST_DEF( test_real_matrix )\n{\n    BOOST_UBLASX_DEBUG_TRACE( \"Test Case: Real - Matrix\" );\n\n    typedef double value_type;\n    typedef std::size_t size_type;\n    typedef ublas::matrix<value_type> matrix_type;\n\n    const size_type nr(2);\n    const size_type nc(3);\n\n    matrix_type A(nr,nc);\n\n    A(0,0) = 1; A(0,1) = 2; A(0,2) = 3;\n    A(1,0) = 4; A(1,1) = 5; A(1,2) = 6;\n\n    matrix_type R;\n    matrix_type expect_R(nr,nc);\n\n    R = ublasx::sqrt(A);\n\n    BOOST_UBLASX_DEBUG_TRACE( \"A = \" << A );\n    BOOST_UBLASX_DEBUG_TRACE( \"sqrt(A) = \" << R );\n\n    for (size_type r = 0; r < nr; ++r)\n    {\n        for (size_type c = 0; c < nc; ++c)\n        {\n            expect_R(r,c) = ::std::sqrt(A(r,c));\n        }\n    }\n\n    BOOST_UBLASX_TEST_CHECK_MATRIX_CLOSE( R, expect_R, nr, nc, tol );\n}\n\n\nBOOST_UBLASX_TEST_DEF( test_complex_matrix )\n{\n    BOOST_UBLASX_DEBUG_TRACE( \"Test Case: Complex - Matrix\" );\n\n    typedef std::complex<double> in_value_type;\n    typedef in_value_type out_value_type;\n    typedef std::size_t size_type;\n    typedef ublas::matrix<in_value_type> in_matrix_type;\n    typedef ublas::matrix<out_value_type> out_matrix_type;\n\n    const size_type nr(2);\n    const size_type nc(3);\n\n    in_matrix_type A(nr,nc);\n\n    A(0,0) = in_value_type( 1, 2); A(0,1) = in_value_type(-2, 3); A(0,2) = in_value_type(-3,-4);\n    A(1,0) = in_value_type(-4,-5); A(1,1) = in_value_type( 5,-6); A(1,2) = in_value_type( 6, 7);\n\n    out_matrix_type R;\n    out_matrix_type expect_R(nr,nc);\n\n    R = ublasx::sqrt(A);\n\n    BOOST_UBLASX_DEBUG_TRACE( \"A = \" << A );\n    BOOST_UBLASX_DEBUG_TRACE( \"sqrt(A) = \" << R );\n\n    for (size_type r = 0; r < nr; ++r)\n    {\n        for (size_type c = 0; c < nc; ++c)\n        {\n            expect_R(r,c) = ::std::sqrt(A(r,c));\n        }\n    }\n\n    BOOST_UBLASX_TEST_CHECK_MATRIX_CLOSE( R, expect_R, nr, nc, tol );\n}\n\n\nint main()\n{\n\n    BOOST_UBLASX_DEBUG_TRACE(\"Test Suite: 'sqrt' operation\");\n\n    BOOST_UBLASX_TEST_BEGIN();\n\n    BOOST_UBLASX_TEST_DO( test_real_vector );\n    BOOST_UBLASX_TEST_DO( test_complex_vector );\n    BOOST_UBLASX_TEST_DO( test_real_matrix );\n    BOOST_UBLASX_TEST_DO( test_complex_matrix );\n\n    BOOST_UBLASX_TEST_END();\n}\n", "meta": {"hexsha": "c8e25732392070c939e7fcc59dc84e98bf702bf9", "size": 4594, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/ublasx/test/sqrt.cpp", "max_stars_repo_name": "sguazt/boost-ublasx", "max_stars_repo_head_hexsha": "21c9b393d33a6ec2a8071ba8d48680073d766409", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2016-05-14T11:08:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-05T14:22:20.000Z", "max_issues_repo_path": "libs/numeric/ublasx/test/sqrt.cpp", "max_issues_repo_name": "sguazt/boost-ublasx", "max_issues_repo_head_hexsha": "21c9b393d33a6ec2a8071ba8d48680073d766409", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-12-28T18:36:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-06T11:28:51.000Z", "max_forks_repo_path": "libs/numeric/ublasx/test/sqrt.cpp", "max_forks_repo_name": "sguazt/boost-ublasx", "max_forks_repo_head_hexsha": "21c9b393d33a6ec2a8071ba8d48680073d766409", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-12-23T02:53:27.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-23T02:53:27.000Z", "avg_line_length": 23.6804123711, "max_line_length": 96, "alphanum_fraction": 0.6382237701, "num_tokens": 1473, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.689305616785446, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.4586712401861805}}
{"text": "// -----------------------------------------------------------------------\r\n// RTToolbox - DKFZ radiotherapy quantitative evaluation library\r\n//\r\n// Copyright (c) German Cancer Research Center (DKFZ),\r\n// Software development for Integrated Diagnostics and Therapy (SIDT).\r\n// ALL RIGHTS RESERVED.\r\n// See rttbCopyright.txt or\r\n// http://www.dkfz.de/en/sidt/projects/rttb/copyright.html\r\n//\r\n// This software is distributed WITHOUT ANY WARRANTY; without even\r\n// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\r\n// PURPOSE.  See the above copyright notices for more information.\r\n//\r\n//------------------------------------------------------------------------\r\n\r\n#include <boost/make_shared.hpp>\r\n#include <boost/shared_ptr.hpp>\r\n\r\n#include \"litCheckMacros.h\"\r\n\r\n#include \"rttbDVH.h\"\r\n#include \"rttbDvhBasedModels.h\"\r\n#include \"rttbInvalidParameterException.h\"\r\n\r\nnamespace rttb\r\n{\r\n\tnamespace testing\r\n\t{\r\n\r\n\t\ttypedef core::DVH::DataDifferentialType DataDifferentialType;\r\n\r\n\t\t/*! @brief DvhBasedModelsTest.\r\n\t\t1) Test bed und lqed2\r\n\t\t*/\r\n\t\tint DvhBasedModelsTest(int argc, char* argv[])\r\n\t\t{\r\n\t\t\tPREPARE_DEFAULT_TEST_REPORTING;\r\n\r\n\t\t\t//1) test calcBEDDVH and calcLQED2DVH\r\n\t\t\t//generate artificial DVH and corresponding statistical values\r\n\t\t\tDoseTypeGy binSize = DoseTypeGy(0.1);\r\n\t\t\tDoseVoxelVolumeType voxelVolume = 8;\r\n\t\t\tconst IDType structureID = \"myStructure\";\r\n\t\t\tconst IDType doseID = \"myDose\";\r\n\t\t\tconst IDType voxelizationID = \"myVoxelization\";\r\n\t\t\tDataDifferentialType aDataDifferential;\r\n\t\t\tstd::vector<double> bedVector;\r\n\t\t\tstd::vector<double> lqed2Vector;\r\n\t\t\tint numberOfFractions = 2;\r\n\t\t\tdouble alpha_beta = 10;\r\n\r\n\t\t\tfor (int i = 0; i < 100; i++)\r\n\t\t\t{\r\n\t\t\t\tdouble volume = DoseCalcType((double(rand()) / RAND_MAX) * 1000);\r\n\t\t\t\tdouble dose = (i + 0.5) * binSize;\r\n\t\t\t\taDataDifferential.push_back(volume);\r\n\t\t\t\tbedVector.push_back(dose * (1 + dose / (numberOfFractions * alpha_beta)));\r\n\t\t\t\tlqed2Vector.push_back(dose * ((alpha_beta + (dose / numberOfFractions)) / (alpha_beta + 2)));\r\n\t\t\t}\r\n\r\n\t\t\tcore::DVH myDVH(aDataDifferential, binSize, voxelVolume, structureID, doseID, voxelizationID);\r\n\t\t\tcore::DVH::Pointer dvhPtr = boost::make_shared<core::DVH>(myDVH);\r\n\r\n\t\t\tCHECK_THROW_EXPLICIT(rttb::models::calcBEDDVH(dvhPtr, 0, 10), core::InvalidParameterException);\r\n\t\t\tCHECK_THROW_EXPLICIT(rttb::models::calcBEDDVH(dvhPtr, 10, -1), core::InvalidParameterException);\r\n\t\t\tCHECK_NO_THROW(rttb::models::calcBEDDVH(dvhPtr, 10, 10));\r\n\t\t\tCHECK_EQUAL(rttb::models::calcBEDDVH(dvhPtr, 2, 10).size(), myDVH.getDataDifferential().size());\r\n\t\t\trttb::models::BEDDVHType bedDVH = rttb::models::calcBEDDVH(dvhPtr, numberOfFractions, alpha_beta);\r\n\r\n\t\t\tCHECK_THROW_EXPLICIT(rttb::models::calcLQED2DVH(dvhPtr, 1, 10), core::InvalidParameterException);\r\n\t\t\tCHECK_THROW_EXPLICIT(rttb::models::calcLQED2DVH(dvhPtr, 10, -1), core::InvalidParameterException);\r\n\t\t\tCHECK_NO_THROW(rttb::models::calcLQED2DVH(dvhPtr, 10, 10, true));\r\n\t\t\tCHECK_EQUAL(rttb::models::calcLQED2DVH(dvhPtr, 2, 10).size(), myDVH.getDataDifferential().size());\r\n\t\t\trttb::models::BEDDVHType lqed2DVH = rttb::models::calcLQED2DVH(dvhPtr, numberOfFractions,\r\n\t\t\t                                    alpha_beta);\r\n\r\n\t\t\t//check the calculation\r\n\t\t\trttb::models::BEDDVHType::iterator itBED, itLQED2;\r\n\t\t\tstd::vector<double>::iterator itBEDVec, itLQED2Vec;\r\n\t\t\tDataDifferentialType::iterator itDiff;\r\n\r\n\t\t\tfor (itBED = bedDVH.begin(), itLQED2 = lqed2DVH.begin(), itBEDVec = bedVector.begin(),\r\n\t\t\t     itLQED2Vec = lqed2Vector.begin(), itDiff = aDataDifferential.begin();\r\n\t\t\t     itBED != bedDVH.end(), itLQED2 != lqed2DVH.end(), itBEDVec != bedVector.end(),\r\n\t\t\t     itLQED2Vec != lqed2Vector.end(), itDiff != aDataDifferential.end();\r\n\t\t\t     ++itBED, ++itLQED2, ++itBEDVec, ++itLQED2Vec, ++itDiff)\r\n\t\t\t{\r\n\r\n\t\t\t\t//check volume\r\n\t\t\t\tCHECK_EQUAL(*itDiff, (*itBED).second);\r\n\t\t\t\tCHECK_EQUAL((*itBED).second, (*itLQED2).second);\r\n\r\n\t\t\t\t//check bed\r\n\t\t\t\tCHECK_EQUAL(*itBEDVec, (*itBED).first);\r\n\r\n\t\t\t\t//check lqed2\r\n\t\t\t\tCHECK_EQUAL(*itLQED2Vec, (*itLQED2).first);\r\n\t\t\t}\r\n\r\n\t\t\tRETURN_AND_REPORT_TEST_SUCCESS;\r\n\r\n\t\t}\r\n\r\n\t}//testing\r\n}//rttb", "meta": {"hexsha": "318bc4df37deb907fa23f2693c1a0a84777e00e8", "size": 4120, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "testing/models/DvhBasedModelsTest.cpp", "max_stars_repo_name": "MIC-DKFZ/RTTB", "max_stars_repo_head_hexsha": "8b772501fd3fffcb67233a9307661b03dff72785", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2018-04-19T12:57:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T17:43:02.000Z", "max_issues_repo_path": "testing/models/DvhBasedModelsTest.cpp", "max_issues_repo_name": "MIC-DKFZ/RTTB", "max_issues_repo_head_hexsha": "8b772501fd3fffcb67233a9307661b03dff72785", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "testing/models/DvhBasedModelsTest.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": 39.2380952381, "max_line_length": 102, "alphanum_fraction": 0.6694174757, "num_tokens": 1203, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6654105587468141, "lm_q2_score": 0.6893056231680121, "lm_q1q2_score": 0.45867123985954783}}
{"text": "// BenchmarkFloatConv.cpp : Defines the entry point for the console application.\n//\n\n#include <vector>\n#include <iostream>\n#include <iomanip>\n#include <string>\n#include <cstring>\n#include <cmath>\n#include <cassert>\n#include <sstream>\n#include <cstdlib>\n#include <chrono>\n#include <boost/lexical_cast.hpp>\n#include <boost/spirit/include/qi.hpp>\n#include \"google_double_conversion/double-conversion.h\"\n#include <charconv>\n\ntypedef std::pair<const std::string, const double> pair_type;\ntypedef std::vector< pair_type > vector_type;\n\n#ifdef WIN32\n\n#pragma optimize(\"\", off)\ntemplate <class T>\nvoid do_not_optimize_away(T&& datum) {\n\tdatum = datum;\n}\n#pragma optimize(\"\", on)\n\n#else\nstatic void do_not_optimize_away(void* p) { \n    asm volatile(\"\" : : \"g\"(p) : \"memory\");\n}\n#endif\n\nvoid init(vector_type& vec);\n\n#define MYASSERT(value, expected) \n\n//#define MYASSERT(value, expected) if(value != expected) { std::cerr << value << \" and expected:\" << expected << \" are different\" << std::endl; }\n\nclass timer\n{\npublic: \n\ttimer() = default;\n\tvoid start(const std::string& text_)\n\t{\n\t\ttext = text_;\n\t\tbegin = std::chrono::high_resolution_clock::now();\n\t}\n\tvoid stop()\n\t{\n\t\tauto end = std::chrono::high_resolution_clock::now();\n\t\tauto dur = end - begin;\n\t\tauto ms = std::chrono::duration_cast<std::chrono::milliseconds>(dur).count();\n\t\tstd::cout << std::setw(19) << text << \":\" << std::setw(5) << ms << \"ms\" << std::endl;\n\t}\n\nprivate:\n\tstd::string text;\n\tstd::chrono::high_resolution_clock::time_point begin;\n};\n\n// Original crack_atof version is at http://crackprogramming.blogspot.sg/2012/10/implement-atof.html\n// But it cannot convert floating point with high +/- exponent.\n// The version below by Tian Bo fixes that problem and improves performance by 10%\n// http://coliru.stacked-crooked.com/a/2e28f0d71f47ca5e\ndouble pow10(int n)\n{\n\tdouble ret = 1.0;\n\tdouble r = 10.0;\n\tif (n < 0) {\n\t\tn = -n;\n\t\tr = 0.1;\n\t}\n\n\twhile (n) {\n\t\tif (n & 1) {\n\t\t\tret *= r;\n\t\t}\n\t\tr *= r;\n\t\tn >>= 1;\n\t}\n\treturn ret;\n}\n\ndouble crack_atof(const char* num)\n{\n\tif (!num || !*num) {\n\t\treturn 0;\n\t}\n\n\tint sign = 1;\n\tdouble integerPart = 0.0;\n\tdouble fractionPart = 0.0;\n\tbool hasFraction = false;\n\tbool hasExpo = false;\n\n\t// Take care of +/- sign\n\tif (*num == '-') {\n\t\t++num;\n\t\tsign = -1;\n\t}\n\telse if (*num == '+') {\n\t\t++num;\n\t}\n\n\twhile (*num != '\\0') {\n\t\tif (*num >= '0' && *num <= '9') {\n\t\t\tintegerPart = integerPart * 10 + (*num - '0');\n\t\t}\n\t\telse if (*num == '.') {\n\t\t\thasFraction = true;\n\t\t\t++num;\n\t\t\tbreak;\n\t\t}\n\t\telse if (*num == 'e') {\n\t\t\thasExpo = true;\n\t\t\t++num;\n\t\t\tbreak;\n\t\t}\n\t\telse {\n\t\t\treturn sign * integerPart;\n\t\t}\n\t\t++num;\n\t}\n\n\tif (hasFraction) {\n\t\tdouble fractionExpo = 0.1;\n\n\t\twhile (*num != '\\0') {\n\t\t\tif (*num >= '0' && *num <= '9') {\n\t\t\t\tfractionPart += fractionExpo * (*num - '0');\n\t\t\t\tfractionExpo *= 0.1;\n\t\t\t}\n\t\t\telse if (*num == 'e') {\n\t\t\t\thasExpo = true;\n\t\t\t\t++num;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\telse {\n\t\t\t\treturn sign * (integerPart + fractionPart);\n\t\t\t}\n\t\t\t++num;\n\t\t}\n\t}\n\n\t// parsing exponet part\n\tdouble expPart = 1.0;\n\tif (*num != '\\0' && hasExpo) {\n\t\tint expSign = 1;\n\t\tif (*num == '-') {\n\t\t\texpSign = -1;\n\t\t\t++num;\n\t\t}\n\t\telse if (*num == '+') {\n\t\t\t++num;\n\t\t}\n\n\t\tint e = 0;\n\t\twhile (*num != '\\0' && *num >= '0' && *num <= '9') {\n\t\t\te = e * 10 + *num - '0';\n\t\t\t++num;\n\t\t}\n\n\t\texpPart = pow10(expSign * e);\n\t}\n\n\treturn sign * (integerPart + fractionPart) * expPart;\n}\n\n\n#define white_space(c) ((c) == ' ' || (c) == '\\t')\n#define valid_digit(c) ((c) >= '0' && (c) <= '9')\n// http://www.leapsecond.com/tools/fast_atof.c\n// Do not use this one because the converison is imprecise.\ndouble fast_atof(const char *p)\n{\n\tint frac;\n\tdouble sign, value, scale;\n\n\t// Skip leading white space, if any.\n\n\twhile (white_space(*p)) {\n\t\tp += 1;\n\t}\n\n\t// Get sign, if any.\n\n\tsign = 1.0;\n\tif (*p == '-') {\n\t\tsign = -1.0;\n\t\tp += 1;\n\n\t}\n\telse if (*p == '+') {\n\t\tp += 1;\n\t}\n\n\t// Get digits before decimal point or exponent, if any.\n\n\tfor (value = 0.0; valid_digit(*p); p += 1) {\n\t\tvalue = value * 10.0 + (*p - '0');\n\t}\n\n\t// Get digits after decimal point, if any.\n\n\tif (*p == '.') {\n\t\tdouble pow10 = 10.0;\n\t\tp += 1;\n\t\twhile (valid_digit(*p)) {\n\t\t\tvalue += (*p - '0') / pow10;\n\t\t\tpow10 *= 10.0;\n\t\t\tp += 1;\n\t\t}\n\t}\n\n\t// Handle exponent, if any.\n\n\tfrac = 0;\n\tscale = 1.0;\n\tif ((*p == 'e') || (*p == 'E')) {\n\t\tunsigned int expon;\n\n\t\t// Get sign of exponent, if any.\n\n\t\tp += 1;\n\t\tif (*p == '-') {\n\t\t\tfrac = 1;\n\t\t\tp += 1;\n\n\t\t}\n\t\telse if (*p == '+') {\n\t\t\tp += 1;\n\t\t}\n\n\t\t// Get digits of exponent, if any.\n\n\t\tfor (expon = 0; valid_digit(*p); p += 1) {\n\t\t\texpon = expon * 10 + (*p - '0');\n\t\t}\n\t\tif (expon > 308) expon = 308;\n\n\t\t// Calculate scaling factor.\n\n\t\twhile (expon >= 50) { scale *= 1E50; expon -= 50; }\n\t\twhile (expon >= 8) { scale *= 1E8;  expon -= 8; }\n\t\twhile (expon > 0) { scale *= 10.0; expon -= 1; }\n\t}\n\n\t// Return signed and scaled floating point result.\n\n\treturn sign * (frac ? (value / scale) : (value * scale));\n}\nint main(int argc, char *argv [])\n{\n\tconst size_t MAX_LOOP = (argc == 2) ? atoi(argv[1]) : 100000;\n\n\tvector_type vec;\n\tinit(vec);\n\ttimer stopwatch;\n\tdouble d = 0.0;\n\n\tstopwatch.start(\"atof\");\n\tfor (size_t k = 0; k<MAX_LOOP; ++k)\n\t{\n\t\tfor (size_t j=0; j<vec.size(); ++j)\n\t\t{\n\t\t\tpair_type& pr = vec[j];\n\t\t\td = std::atof(pr.first.c_str());\n\t\t\tdo_not_optimize_away(&d);\n\t\t\tMYASSERT(d, pr.second);\n\t\t}\n\t}\n\tstopwatch.stop();\n\t\n\tstopwatch.start(\"lexical_cast\");\n\tfor (size_t k = 0; k < MAX_LOOP; ++k)\n\t{\n\t\tfor (size_t j=0; j<vec.size(); ++j)\n\t\t{\n\t\t\tpair_type& pr = vec[j];\n\t\t\td = boost::lexical_cast<double>(pr.first.c_str());\n\t\t\tdo_not_optimize_away(&d);\n\t\t\tMYASSERT(d, pr.second);\n\t\t}\n\t}\n\tstopwatch.stop();\n\t\n\tstopwatch.start(\"std::istringstream\");\n\tfor (size_t k = 0; k < MAX_LOOP; ++k)\n\t{\n\t\tfor (size_t i = 0; i<vec.size(); ++i)\n\t\t{\n\t\t\tpair_type& pr = vec[i];\n\t\t\tstd::istringstream oss(pr.first);\n\t\t\toss >> d;\n\t\t\tdo_not_optimize_away(&d);\n\t\t\tMYASSERT(d, pr.second);\n\t\t}\n\t}\n\tstopwatch.stop();\n\n\tstopwatch.start(\"std::stod\");\n\tfor (size_t k = 0; k < MAX_LOOP; ++k)\n\t{\n\t\tfor (size_t i = 0; i<vec.size(); ++i)\n\t\t{\n\t\t\tpair_type& pr = vec[i];\n\t\t\td = std::stod(pr.first, nullptr);\n\t\t\tdo_not_optimize_away(&d);\n\t\t\tMYASSERT(d, pr.second);\n\t\t}\n\t}\n\tstopwatch.stop();\n\n\tstopwatch.start(\"std::strtod\");\n\tfor (size_t k = 0; k < MAX_LOOP; ++k)\n\t{\n\t\tfor (size_t i = 0; i < vec.size(); ++i)\n\t\t{\n\t\t\tpair_type& pr = vec[i];\n\t\t\td = std::strtod(pr.first.c_str(), nullptr);\n\t\t\tdo_not_optimize_away(&d);\n\t\t\tMYASSERT(d, pr.second);\n\t\t}\n\t}\n\tstopwatch.stop();\n\n\tstopwatch.start(\"crack_atof\");\n\tfor (size_t k = 0; k < MAX_LOOP; ++k)\n\t{\n\t\tfor (size_t j=0; j<vec.size(); ++j)\n\t\t{\n\t\t\tpair_type& pr = vec[j];\n\t\t\td = crack_atof(pr.first.c_str());\n\t\t\tdo_not_optimize_away(&d);\n\t\t\tMYASSERT(d, pr.second);\n\t\t}\n\t}\n\tstopwatch.stop();\n\n\tstopwatch.start(\"fast_atof\");\n\tfor (size_t k = 0; k < MAX_LOOP; ++k)\n\t{\n\t\tfor (size_t j=0; j<vec.size(); ++j)\n\t\t{\n\t\t\tpair_type& pr = vec[j];\n\t\t\td = fast_atof(pr.first.c_str());\n\t\t\tdo_not_optimize_away(&d);\n\t\t\tMYASSERT(d, pr.second);\n\t\t}\n\t}\n\tstopwatch.stop();\n\t\n\tnamespace qi = boost::spirit::qi;\n\n\tstopwatch.start(\"boost_spirit\");\n\tfor (size_t k = 0; k < MAX_LOOP; ++k)\n\t{\n\t\tfor (size_t j=0; j<vec.size(); ++j)\n\t\t{\n\t\t\tpair_type& pr = vec[j];\n\t\t\tbool success = qi::parse(pr.first.cbegin(), pr.first.cend(), qi::double_, d);\n\t\t\tdo_not_optimize_away(&d);\n\t\t\tMYASSERT(d, pr.second);\n\t\t}\n\t}\n\tstopwatch.stop();\n\t\n\tstopwatch.start(\"google_dconv\");\n\tint processed_characters_count = 0;\n\tusing namespace double_conversion;\n\tfor (size_t k = 0; k < MAX_LOOP; ++k)\n\t{\n\t\tfor (size_t j = 0; j < vec.size(); ++j)\n\t\t{\n\t\t\tpair_type& pr = vec[j];\n\n\t\t\tstatic StringToDoubleConverter conv(StringToDoubleConverter::NO_FLAGS, 0.0, NAN, \"infinity\", \"nan\");\n\t\t\td = conv.StringToDouble(pr.first.c_str(), pr.first.size(), &processed_characters_count);\n\n\t\t\tdo_not_optimize_away(&d);\n\t\t\tMYASSERT(d, pr.second);\n\t\t}\n\t}\n\tstopwatch.stop();\n\n\tstopwatch.start(\"std::from_chars\");\n\tfor (size_t k = 0; k < MAX_LOOP; ++k)\n\t{\n\t\tfor (size_t j = 0; j < vec.size(); ++j)\n\t\t{\n\t\t\tpair_type& pr = vec[j];\n\t\t\tstd::from_chars(pr.first.data(), pr.first.data() + pr.first.size(), d);\n\t\t\tdo_not_optimize_away(&d);\n\t\t\tMYASSERT(d, pr.second);\n\t\t}\n\t}\n\tstopwatch.stop();\n\n\tstd::cout << \"Last float value: \" << d << \" <-- Ignore this\" << std::endl;\n\treturn 0;\n}\n\nvoid init(vector_type& vec)\n{\n\tstd::string float_str = \"+12369\";\n\tvec.push_back(std::make_pair(float_str, atof(float_str.c_str())));\n\tfloat_str = \"-25934\";\n\tvec.push_back(std::make_pair(float_str, atof(float_str.c_str())));\n\tfloat_str = \"-47896.36\";\n\tvec.push_back(std::make_pair(float_str, atof(float_str.c_str())));\n\tfloat_str = \"+532.102\";\n\tvec.push_back(std::make_pair(float_str, atof(float_str.c_str())));\n\tfloat_str = \"4.5655\";\n\tvec.push_back(std::make_pair(float_str, atof(float_str.c_str())));\n\tfloat_str = \"8.3658\";\n\tvec.push_back(std::make_pair(float_str, atof(float_str.c_str())));\n\tfloat_str = \"-125.6900\";\n\tvec.push_back(std::make_pair(float_str, atof(float_str.c_str())));\n\tfloat_str = \"-1236.2311\";\n\tvec.push_back(std::make_pair(float_str, atof(float_str.c_str())));\n\tfloat_str = \"-5522.2389\";\n\tvec.push_back(std::make_pair(float_str, atof(float_str.c_str())));\n\tfloat_str = \"-14.23\";\n\tvec.push_back(std::make_pair(float_str, atof(float_str.c_str())));\n}\n\n", "meta": {"hexsha": "7e01cef52e7184523309c13324339ec8fdf88521", "size": 9159, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "BenchmarkFloatConv/BenchmarkFloatConv/BenchmarkFloatConv.cpp", "max_stars_repo_name": "shaovoon/floatbench", "max_stars_repo_head_hexsha": "b13794c63d824b95998dac18b8cf3d05e7d84e57", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2017-08-17T17:08:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-24T13:48:48.000Z", "max_issues_repo_path": "BenchmarkFloatConv/BenchmarkFloatConv/BenchmarkFloatConv.cpp", "max_issues_repo_name": "shaovoon/floatbench", "max_issues_repo_head_hexsha": "b13794c63d824b95998dac18b8cf3d05e7d84e57", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-06-05T08:17:48.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-07T09:10:57.000Z", "max_forks_repo_path": "BenchmarkFloatConv/BenchmarkFloatConv/BenchmarkFloatConv.cpp", "max_forks_repo_name": "shaovoon/floatbench", "max_forks_repo_head_hexsha": "b13794c63d824b95998dac18b8cf3d05e7d84e57", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-05-18T11:42:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-24T13:48:50.000Z", "avg_line_length": 21.2505800464, "max_line_length": 146, "alphanum_fraction": 0.5931870292, "num_tokens": 3026, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.6893056167854461, "lm_q1q2_score": 0.45867123561252093}}
{"text": "#pragma once\n\n#include <Eigen/Core>\n\nnamespace kt84 {\n\ntypedef Eigen::Matrix<double, 6, 1> PointNormal;\ninline double pn_norm(const PointNormal& pn) { return pn.head(3).norm(); }\ninline void   pn_normalize(PointNormal& pn) { pn.tail(3).normalize(); }\ninline PointNormal pn_normalized(const PointNormal& pn) { auto temp = pn; temp.tail(3).normalize(); return temp; }\n\n}\n", "meta": {"hexsha": "f3b8473548964fb6e0ba0c7d6400251d85fb0a99", "size": 369, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/kt84/geometry/PointNormal.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/PointNormal.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/PointNormal.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": 28.3846153846, "max_line_length": 114, "alphanum_fraction": 0.7235772358, "num_tokens": 95, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6893056040203135, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.4586712225448073}}
{"text": "//\n//  Copyright (c) 2020, Cem Bassoy, cem.bassoy@gmail.com\n//  Copyright (c) 2019, Amit Singh, amitsingh19975@gmail.com\n//\n//  Distributed under the Boost Software License, Version 1.0. (See\n//  accompanying file LICENSE_1_0.txt or copy at\n//  http://www.boost.org/LICENSE_1_0.txt)\n//\n//  The authors gratefully acknowledge the support of\n//  Google and Fraunhofer IOSB, Ettlingen, Germany\n//\n\n#include <boost/numeric/ublas/tensor/extents.hpp>\n#include <boost/test/unit_test.hpp>\n\nBOOST_AUTO_TEST_SUITE(test_static_strides)\n\nusing test_types = std::tuple<boost::numeric::ublas::layout::first_order,\n                              boost::numeric::ublas::layout::last_order>;\n\ntemplate<std::size_t ... es>\nusing extents = boost::numeric::ublas::extents<es...>;\n\nusing first_order = boost::numeric::ublas::layout::first_order;\nusing last_order  = boost::numeric::ublas::layout::last_order;\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_static_strides_ctor, value, test_types)\n{\n  namespace ublas = boost::numeric::ublas;\n\n  constexpr auto s11  = ublas::to_strides_v<extents  <1,1>,first_order>;\n  constexpr auto s12  = ublas::to_strides_v<extents  <1,2>,first_order>;\n  constexpr auto s21  = ublas::to_strides_v<extents  <2,1>,first_order>;\n  constexpr auto s23  = ublas::to_strides_v<extents  <2,3>,first_order>;\n  constexpr auto s231 = ublas::to_strides_v<extents<2,3,1>,first_order>;\n  constexpr auto s123 = ublas::to_strides_v<extents<1,2,3>,first_order>;\n  constexpr auto s423 = ublas::to_strides_v<extents<4,2,3>,first_order>;\n\n  BOOST_CHECK_EQUAL(s11.empty(), false);\n  BOOST_CHECK_EQUAL(s12.empty(), false);\n  BOOST_CHECK_EQUAL(s21.empty(), false);\n  BOOST_CHECK_EQUAL(s23.empty(), false);\n  BOOST_CHECK_EQUAL(s231.empty(), false);\n  BOOST_CHECK_EQUAL(s123.empty(), false);\n  BOOST_CHECK_EQUAL(s423.empty(), false);\n\n  BOOST_CHECK_EQUAL(s11.size(), 2);\n  BOOST_CHECK_EQUAL(s12.size(), 2);\n  BOOST_CHECK_EQUAL(s21.size(), 2);\n  BOOST_CHECK_EQUAL(s23.size(), 2);\n  BOOST_CHECK_EQUAL(s231.size(), 3);\n  BOOST_CHECK_EQUAL(s123.size(), 3);\n  BOOST_CHECK_EQUAL(s423.size(), 3);\n}\n\nBOOST_AUTO_TEST_CASE(test_static_strides_ctor_access_first_order)\n{\n  namespace ublas = boost::numeric::ublas;\n\n  constexpr auto s11  = ublas::to_strides_v<extents  <1,1>,first_order>;\n  constexpr auto s12  = ublas::to_strides_v<extents  <1,2>,first_order>;\n  constexpr auto s21  = ublas::to_strides_v<extents  <2,1>,first_order>;\n  constexpr auto s23  = ublas::to_strides_v<extents  <2,3>,first_order>;\n  constexpr auto s231 = ublas::to_strides_v<extents<2,3,1>,first_order>;\n  constexpr auto s213 = ublas::to_strides_v<extents<2,1,3>,first_order>;\n  constexpr auto s123 = ublas::to_strides_v<extents<1,2,3>,first_order>;\n  constexpr auto s423 = ublas::to_strides_v<extents<4,2,3>,first_order>;\n\n  BOOST_REQUIRE_EQUAL(s11.size(), 2);\n  BOOST_REQUIRE_EQUAL(s12.size(), 2);\n  BOOST_REQUIRE_EQUAL(s21.size(), 2);\n  BOOST_REQUIRE_EQUAL(s23.size(), 2);\n  BOOST_REQUIRE_EQUAL(s231.size(), 3);\n  BOOST_REQUIRE_EQUAL(s213.size(), 3);\n  BOOST_REQUIRE_EQUAL(s123.size(), 3);\n  BOOST_REQUIRE_EQUAL(s423.size(), 3);\n\n\n  BOOST_CHECK_EQUAL(s11[0], 1);\n  BOOST_CHECK_EQUAL(s11[1], 1);\n\n  BOOST_CHECK_EQUAL(s12[0], 1);\n  BOOST_CHECK_EQUAL(s12[1], 1);\n\n  BOOST_CHECK_EQUAL(s21[0], 1);\n  BOOST_CHECK_EQUAL(s21[1], 2); // NOTE: is this the way we want to have it?\n\n  BOOST_CHECK_EQUAL(s23[0], 1);\n  BOOST_CHECK_EQUAL(s23[1], 2);\n\n  BOOST_CHECK_EQUAL(s231[0], 1);\n  BOOST_CHECK_EQUAL(s231[1], 2);\n  BOOST_CHECK_EQUAL(s231[2], 6);\n\n  BOOST_CHECK_EQUAL(s123[0], 1);\n  BOOST_CHECK_EQUAL(s123[1], 1);\n  BOOST_CHECK_EQUAL(s123[2], 2);\n\n  BOOST_CHECK_EQUAL(s213[0], 1);\n  BOOST_CHECK_EQUAL(s213[1], 2);\n  BOOST_CHECK_EQUAL(s213[2], 2);\n\n  BOOST_CHECK_EQUAL(s423[0], 1);\n  BOOST_CHECK_EQUAL(s423[1], 4);\n  BOOST_CHECK_EQUAL(s423[2], 8);\n}\n\nBOOST_AUTO_TEST_CASE(test_static_strides_ctor_access_last_order)\n{\n  namespace ublas = boost::numeric::ublas;\n\n  constexpr auto s11  = ublas::to_strides_v<extents  <1,1>,last_order>;\n  constexpr auto s12  = ublas::to_strides_v<extents  <1,2>,last_order>;\n  constexpr auto s21  = ublas::to_strides_v<extents  <2,1>,last_order>;\n  constexpr auto s23  = ublas::to_strides_v<extents  <2,3>,last_order>;\n  constexpr auto s231 = ublas::to_strides_v<extents<2,3,1>,last_order>;\n  constexpr auto s213 = ublas::to_strides_v<extents<2,1,3>,last_order>;\n  constexpr auto s123 = ublas::to_strides_v<extents<1,2,3>,last_order>;\n  constexpr auto s423 = ublas::to_strides_v<extents<4,2,3>,last_order>;\n\n  BOOST_REQUIRE_EQUAL(s11.size(), 2);\n  BOOST_REQUIRE_EQUAL(s12.size(), 2);\n  BOOST_REQUIRE_EQUAL(s21.size(), 2);\n  BOOST_REQUIRE_EQUAL(s23.size(), 2);\n  BOOST_REQUIRE_EQUAL(s231.size(), 3);\n  BOOST_REQUIRE_EQUAL(s213.size(), 3);\n  BOOST_REQUIRE_EQUAL(s123.size(), 3);\n  BOOST_REQUIRE_EQUAL(s423.size(), 3);\n\n\n  BOOST_CHECK_EQUAL(s11[0], 1);\n  BOOST_CHECK_EQUAL(s11[1], 1);\n\n  BOOST_CHECK_EQUAL(s12[0], 2); //NOTE: is this the way we want the stride to be computed?\n  BOOST_CHECK_EQUAL(s12[1], 1);\n\n  BOOST_CHECK_EQUAL(s21[0], 1);\n  BOOST_CHECK_EQUAL(s21[1], 1);\n\n  BOOST_CHECK_EQUAL(s23[0], 3);\n  BOOST_CHECK_EQUAL(s23[1], 1);\n\n  BOOST_CHECK_EQUAL(s231[0], 3);\n  BOOST_CHECK_EQUAL(s231[1], 1);\n  BOOST_CHECK_EQUAL(s231[2], 1);\n\n  BOOST_CHECK_EQUAL(s123[0], 6);\n  BOOST_CHECK_EQUAL(s123[1], 3);\n  BOOST_CHECK_EQUAL(s123[2], 1);\n\n  BOOST_CHECK_EQUAL(s213[0], 3);\n  BOOST_CHECK_EQUAL(s213[1], 3);\n  BOOST_CHECK_EQUAL(s213[2], 1);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "5f5a203e9997a44ea87fb124fd1469bf08f03eb2", "size": 5431, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/tensor/test_static_strides.cpp", "max_stars_repo_name": "samd2/ublas", "max_stars_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 96.0, "max_stars_repo_stars_event_min_datetime": "2015-01-23T10:15:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T18:31:02.000Z", "max_issues_repo_path": "test/tensor/test_static_strides.cpp", "max_issues_repo_name": "samd2/ublas", "max_issues_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 105.0, "max_issues_repo_issues_event_min_datetime": "2015-01-14T09:01:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-05T06:10:39.000Z", "max_forks_repo_path": "test/tensor/test_static_strides.cpp", "max_forks_repo_name": "samd2/ublas", "max_forks_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 157.0, "max_forks_repo_forks_event_min_datetime": "2015-01-26T13:35:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T11:12:27.000Z", "avg_line_length": 34.5923566879, "max_line_length": 90, "alphanum_fraction": 0.7219664887, "num_tokens": 1726, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6654105454764747, "lm_q2_score": 0.6893056040203136, "lm_q1q2_score": 0.45867121797114774}}
{"text": "#include <Eigen/Dense>\n#include \"control.hpp\"\n#include \"defines.hpp\"\n#include \"fad.hpp\"\n#include \"global_residual.hpp\"\n#include \"J2_plane_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_plane_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}\n\nstatic ParameterList get_valid_material_params() {\n  ParameterList p;\n  p.set<double>(\"E\", 0.);\n  p.set<double>(\"nu\", 0.);\n  p.set<double>(\"K\", 0.);\n  p.set<double>(\"Y\", 0.);\n  return p;\n}\n\ntemplate <typename T>\nJ2_plane_strain<T>::J2_plane_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 = 4;\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] = \"zeta\";\n  this->m_var_types[0] = SYM_TENSOR;\n  this->m_num_eqs[0] = get_num_eqs(SYM_TENSOR, ndims);\n\n  this->m_resid_names[1] = \"Ie\";\n  this->m_var_types[1] = SCALAR;\n  this->m_num_eqs[1] = get_num_eqs(SCALAR, ndims);\n\n  this->m_resid_names[2] = \"alpha\";\n  this->m_var_types[2] = SCALAR;\n  this->m_num_eqs[2] = get_num_eqs(SCALAR, ndims);\n\n  this->m_resid_names[3] = \"zeta_zz\";\n  this->m_var_types[3] = SCALAR;\n  this->m_num_eqs[3] = 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>\nvoid J2_plane_strain<T>::init_params() {\n\n  int const num_params = 4;\n  this->m_params.resize(num_params);\n  this->m_param_names.resize(num_params);\n\n  this->m_param_names.resize(num_params);\n  this->m_param_names[0] = \"E\";\n  this->m_param_names[1] = \"nu\";\n  this->m_param_names[2] = \"K\";\n  this->m_param_names[3] = \"Y\";\n\n  int const num_elem_sets = this->m_elem_set_names.size();\n  resize(this->m_param_values, num_elem_sets, num_params);\n\n  ParameterList& all_material_params =\n      this->m_params_list.sublist(\"materials\", true);\n\n  for (int es = 0; es < num_elem_sets; ++es) {\n    std::string const& elem_set_name = this->m_elem_set_names[es];\n    ParameterList& material_params =\n        all_material_params.sublist(elem_set_name, true);\n    material_params.validateParameters(get_valid_material_params(), 0);\n    this->m_param_values[es][0] = material_params.get<double>(\"E\");\n    this->m_param_values[es][1] = material_params.get<double>(\"nu\");\n    this->m_param_values[es][2] = material_params.get<double>(\"K\");\n    this->m_param_values[es][3] = material_params.get<double>(\"Y\");\n  }\n\n  this->m_active_indices.resize(1);\n  this->m_active_indices[0].resize(1);\n  this->m_active_indices[0][0] = 0;\n}\n\ntemplate <typename T>\nJ2_plane_strain<T>::~J2_plane_strain() {\n}\n\ntemplate <typename T>\nvoid J2_plane_strain<T>::init_variables_impl() {\n\n  int const ndims = this->m_num_dims;\n  int const zeta_idx = 0;\n  int const Ie_idx = 1;\n  int const alpha_idx = 2;\n  int const zeta_zz_idx = 3;\n\n  T const Ie = 1.0;\n  T const alpha = 0.0;\n  Tensor<T> const zeta = minitensor::zero<T>(ndims);\n  T const zeta_zz = 0.0;\n\n  this->set_scalar_xi(Ie_idx, Ie);\n  this->set_scalar_xi(alpha_idx, alpha);\n  this->set_sym_tensor_xi(zeta_idx, zeta);\n  this->set_scalar_xi(zeta_zz_idx, zeta_zz);\n\n}\n\ntemplate <typename T>\nvoid eval_be_bar_plane_strain(\n    RCP<GlobalResidual<T>> global,\n    Tensor<T> const& zeta,\n    T const& Ie,\n    T const& zeta_zz,\n    Tensor<T>& be_bar_2D,\n    T& be_bar_zz) {\n  int const ndims = global->num_dims();\n  Tensor<T> const I = minitensor::eye<T>(ndims);\n  Tensor<T> const grad_u = global->grad_vector_x(0);\n  Tensor<T> const grad_u_prev = global->grad_vector_x_prev(0);\n  Tensor<T> const F = grad_u + I;\n  Tensor<T> const F_prev = grad_u_prev + I;\n  Tensor<T> const rF = F * minitensor::inverse(F_prev);\n  T const det_rF = minitensor::det(rF);\n  T const det_rF_13 = cbrt(det_rF);\n  Tensor<T> const rF_bar = rF / det_rF_13;\n  Tensor<T> const rF_barT = minitensor::transpose(rF_bar);\n  be_bar_2D = rF_bar * (zeta + Ie * I) * rF_barT;\n  be_bar_zz = (zeta_zz + Ie) / (det_rF_13 * det_rF_13);\n}\n\ntemplate <typename T>\nT norm_s_3D(Tensor<T> const& s_2D, T const& s_zz) {\n  return sqrt(s_2D(0, 0) * s_2D(0, 0) + s_2D(1, 1) * s_2D(1, 1)\n      + 2. * s_2D(0, 1) * s_2D(0, 1) + s_zz * s_zz);\n}\n\ntemplate <typename T>\nT det_be_bar_3D(Tensor<T> const& zeta_2D, T const& zeta_zz, T const& Ie) {\n  return ((zeta_2D(0, 0) + Ie) * (zeta_2D(1, 1) + Ie)\n      - zeta_2D(0, 1) * zeta_2D(0, 1)) * (zeta_zz + Ie);\n}\n\ntemplate <>\nint J2_plane_strain<double>::solve_nonlinear(RCP<GlobalResidual<double>>) {\n  return 0;\n}\n\ntemplate <>\nint J2_plane_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 zeta_old = this->sym_tensor_xi_prev(0);\n    FADT const Ie_old = this->scalar_xi_prev(1);\n    FADT const alpha_old = this->scalar_xi_prev(2);\n    FADT const zeta_zz_old = this->scalar_xi_prev(3);\n\n    int const ndims = global->num_dims();\n    Tensor<FADT> be_bar_2D_trial;\n    FADT be_bar_zz_trial;\n    eval_be_bar_plane_strain(global, zeta_old, Ie_old, zeta_zz_old,\n        be_bar_2D_trial, be_bar_zz_trial);\n    FADT const Ie_trial = (minitensor::trace(be_bar_2D_trial)\n        + be_bar_zz_trial) / 3.;\n    Tensor<FADT> const I = minitensor::eye<FADT>(ndims);\n    Tensor<FADT> const zeta_trial = be_bar_2D_trial - Ie_trial * I;\n    FADT const zeta_zz_trial = be_bar_zz_trial - Ie_trial;\n    FADT const alpha_trial = alpha_old;\n    this->set_sym_tensor_xi(0, zeta_trial);\n    this->set_scalar_xi(1, Ie_trial);\n    this->set_scalar_xi(2, alpha_trial);\n    this->set_scalar_xi(3, zeta_zz_trial);\n    path = ELASTIC;\n  }\n\n  // newton iteration until convergence\n\n  int iter = 1;\n  double R_norm_0 = 1.;\n  bool converged = false;\n\n  while ((iter <= m_max_iters) && (!converged)) {\n\n    path = this->evaluate(global);\n\n    double const R_norm = this->norm_residual();\n    if (iter == 1) R_norm_0 = R_norm;\n    double const R_norm_rel = R_norm / R_norm_0;\n    if ((R_norm_rel < m_rel_tol) || (R_norm < m_abs_tol)) {\n      converged = true;\n      break;\n    }\n\n    EMatrix const J = this->eigen_jacobian();\n    EVector const R = this->eigen_residual();\n    EVector const dxi = J.fullPivLu().solve(-R);\n\n    this->add_to_sym_tensor_xi(0, dxi);\n    this->add_to_scalar_xi(1, dxi);\n    this->add_to_scalar_xi(2, dxi);\n    this->add_to_scalar_xi(3, dxi);\n\n    iter++;\n\n  }\n\n  // fail if convergence was not achieved\n  if ((iter > m_max_iters) && (!converged)) {\n    fail(\"J2_plane_strain:solve_nonlinear failed in %d iterations\", m_max_iters);\n  }\n\n  return path;\n\n}\n\ntemplate <typename T>\nint J2_plane_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 zeta_old = this->sym_tensor_xi_prev(0);\n  T const Ie_old = this->scalar_xi_prev(1);\n  T const alpha_old = this->scalar_xi_prev(2);\n  T const zeta_zz_old = this->scalar_xi_prev(3);\n\n  Tensor<T> const zeta = this->sym_tensor_xi(0);\n  T const Ie = this->scalar_xi(1);\n  T const alpha = this->scalar_xi(2);\n  T const zeta_zz = this->scalar_xi(3);\n\n  Tensor<T> const I = minitensor::eye<T>(ndims);\n  Tensor<T> be_bar_trial_2D;\n  T be_bar_trial_zz;\n  eval_be_bar_plane_strain(global, zeta_old, Ie_old, zeta_zz_old,\n      be_bar_trial_2D, be_bar_trial_zz);\n  T const Ie_trial = (minitensor::trace(be_bar_trial_2D)\n      + be_bar_trial_zz) / 3.;\n  Tensor<T> const zeta_trial = be_bar_trial_2D - Ie_trial * I;\n  T const zeta_zz_trial = be_bar_trial_zz - Ie_trial;\n  Tensor<T> const s_2D = mu * zeta;\n  T const s_zz = mu * zeta_zz;\n  T const s_mag = norm_s_3D(s_2D, s_zz);\n  Tensor<T> const n_2D = s_2D / s_mag;\n  T const n_zz = s_zz / s_mag;\n  T const sigma_yield = Y + K * alpha;\n  T const f = s_mag - sqrt_23 * sigma_yield;\n\n  Tensor<T> R_zeta;\n  T R_Ie;\n  T R_alpha;\n  T R_zeta_zz;\n\n  if (!force_path) {\n    // plastic step\n    if (f > m_abs_tol || std::abs(f) < m_abs_tol) {\n      T const dgam = sqrt_32 * (alpha - alpha_old);\n      R_zeta = zeta - zeta_trial + 2. * dgam * Ie * n_2D;\n      R_Ie = det_be_bar_3D(zeta, zeta_zz, Ie) - 1.;\n      R_alpha = (s_mag - sqrt_23 * sigma_yield) / val(mu);\n      R_zeta_zz = zeta_zz - zeta_zz_trial + 2. * dgam * Ie * n_zz;\n      path = PLASTIC;\n    }\n    // elastic step\n    else {\n      R_zeta = (0. * mu + 1.) * zeta - zeta_trial;\n      R_Ie = Ie - Ie_trial + 0. * mu;\n      R_alpha = alpha - alpha_old + 0. * mu;\n      R_zeta_zz = zeta_zz - zeta_zz_trial + 0. * mu;\n      path = ELASTIC;\n    }\n  }\n\n  // force the path\n  else {\n    path = path_in;\n    // plastic step\n    if (path == PLASTIC) {\n      T const dgam = sqrt_32 * (alpha - alpha_old);\n      R_zeta = zeta - zeta_trial + 2. * dgam * Ie * n_2D;\n      R_Ie = det_be_bar_3D(zeta, zeta_zz, Ie) - 1.;\n      R_alpha = (s_mag - sqrt_23 * sigma_yield) / val(mu);\n      R_zeta_zz = zeta_zz - zeta_zz_trial + 2. * dgam * Ie * n_zz;\n    }\n    // elastic step\n    else {\n      R_zeta = (0. * mu + 1.) * zeta - zeta_trial;\n      R_Ie = Ie - Ie_trial + 0. * mu;\n      R_alpha = alpha - alpha_old + 0. * mu;\n      R_zeta_zz = zeta_zz - zeta_zz_trial + 0. * mu;\n    }\n  }\n\n  this->set_sym_tensor_R(0, R_zeta);\n  this->set_scalar_R(1, R_Ie);\n  this->set_scalar_R(2, R_alpha);\n  this->set_scalar_R(3, R_zeta_zz);\n\n  return path;\n\n}\n\ntemplate <typename T>\nTensor<T> J2_plane_strain<T>::dev_cauchy(RCP<GlobalResidual<T>> global) {\n  int const ndims = global->num_dims();\n  T const E = this->m_params[0];\n  T const nu = this->m_params[1];\n  T const mu = E / (2. * (1. + nu));\n  Tensor<T> const I = minitensor::eye<T>(ndims);\n  Tensor<T> const grad_u = global->grad_vector_x(0);\n  Tensor<T> const F = grad_u + I;\n  Tensor<T> const zeta = this->sym_tensor_xi(0);\n  T const J = minitensor::det(F);\n  return mu * zeta / J;\n}\n\ntemplate <typename T>\nTensor<T> J2_plane_strain<T>::cauchy(RCP<GlobalResidual<T>> global, T p) {\n  int const ndims = global->num_dims();\n  Tensor<T> const I = minitensor::eye<T>(ndims);\n  Tensor<T> const dev_sigma = this->dev_cauchy(global);\n  Tensor<T> const sigma = dev_sigma - p * I;\n  return sigma;\n}\n\ntemplate class J2_plane_strain<double>;\ntemplate class J2_plane_strain<FADT>;\n\n}\n", "meta": {"hexsha": "a14644c49ac3c2651bb7c5070a78273faa81c6a6", "size": 10809, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/J2_plane_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_plane_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_plane_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": 30.025, "max_line_length": 81, "alphanum_fraction": 0.6659265427, "num_tokens": 3698, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391595913457, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.4586417086413549}}
{"text": "#if !defined(BALSA_EIGEN_SHAPE_CHECKS_HPP)\n#define BALSA_EIGEN_SHAPE_CHECKS_HPP\n#include <Eigen/Core>\n#include \"balsa/eigen/concepts/shape_types.hpp\"\n#include <fmt/format.h>\n#include <fmt/ranges.h>\n\nnamespace balsa::eigen {\n\n// These functions return in case asserts are disabled\ntemplate<int... Cs, typename MatType>\nrequires(concepts::ColCompatible<Cs, MatType> || ... || false) constexpr bool col_check_oneof(const MatType &N,\n                                                                                              std::integer_sequence<int, Cs...>) {\n\n    constexpr int cols = MatType::ColsAtCompileTime;\n    if constexpr (cols == Eigen::Dynamic) {\n        return ((N.cols() == Cs) || ... || false);\n    }\n    return true;\n}\n\ntemplate<int... Rs, typename MatType>\nrequires(concepts::RowCompatible<Rs, MatType> || ... || false) constexpr bool row_check_oneof(const MatType &N,\n                                                                                              std::integer_sequence<int, Rs...>) {\n    constexpr int rows = MatType::RowsAtCompileTime;\n    if constexpr (rows == Eigen::Dynamic) {\n        return ((N.rows() == Rs) || ... || false);\n    }\n    return true;\n}\n\ntemplate<int C, typename MatType>\nrequires concepts::ColCompatible<C, MatType> constexpr bool col_check(const MatType &N) {\n    return col_check_oneof(N, std::integer_sequence<int, C>{});\n}\n\ntemplate<int R, typename MatType>\nrequires concepts::RowCompatible<R, MatType> constexpr bool row_check(const MatType &N) {\n    return row_check_oneof(N, std::integer_sequence<int, R>{});\n}\ntemplate<int R, int C, typename MatType>\nconstexpr bool shape_check(const MatType &N) {\n    return row_check<R>(N) && col_check<C>(N);\n}\n\ntemplate<int C, typename MatType>\nrequires concepts::ColCompatible<C, MatType> constexpr void col_check_with_throw(const MatType &N) {\n    if (!col_check<C>(N)) {\n        throw std::invalid_argument(fmt::format(\"Col check: wrong size, got {} expected {}\", N.cols(), C));\n    }\n}\n\ntemplate<int R, typename MatType>\nrequires concepts::RowCompatible<R, MatType> constexpr void row_check_with_throw(const MatType &N) {\n\n    if (!row_check<R>(N)) {\n        throw std::invalid_argument(fmt::format(\"Row check: wrong size, got {} expected {}\", N.rows(), R));\n    }\n}\ntemplate<int R, int C, typename MatType>\nconstexpr void shape_check_with_throw(const MatType &N) {\n    row_check_with_throw<R>(N);\n    col_check_with_throw<C>(N);\n}\n\ntemplate<int... C, typename MatType>\nvoid col_check_with_throw(const MatType &N, std::integer_sequence<int, C...> Seq) {\n    if (!col_check_oneof(N, Seq)) {\n        std::string msg = fmt::format(\"Col check: wrong size, got {} expected one of {}\", N.cols(), std::make_tuple(C...));\n        throw std::invalid_argument(msg);\n    }\n}\n\ntemplate<int... R, typename MatType>\nvoid row_check_with_throw(const MatType &N, std::integer_sequence<int, R...> Seq) {\n\n    if (!row_check_oneof(N, Seq)) {\n        std::string msg = fmt::format(\"Row check: wrong size, got {} expected {}\", N.rows(), std::make_tuple(R...));\n        throw std::invalid_argument(msg);\n    }\n}\ntemplate<int... R, int... C, typename MatType>\nvoid shape_check_with_throw(const MatType &N, std::integer_sequence<int, R...> RSeq, std::integer_sequence<int, C...> CSeq) {\n    row_check_with_throw(N, RSeq) && col_check_with_throw(N, CSeq);\n}\n}// namespace balsa::eigen\n#endif\n", "meta": {"hexsha": "d655db18b6bc2b719c67256a087b3298c190c9e1", "size": 3370, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/balsa/eigen/shape_checks.hpp", "max_stars_repo_name": "mtao/balsa", "max_stars_repo_head_hexsha": "1552f3a367a80dfc41fffc50b5628b46ba716ab8", "max_stars_repo_licenses": ["MIT"], "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/balsa/eigen/shape_checks.hpp", "max_issues_repo_name": "mtao/balsa", "max_issues_repo_head_hexsha": "1552f3a367a80dfc41fffc50b5628b46ba716ab8", "max_issues_repo_licenses": ["MIT"], "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/balsa/eigen/shape_checks.hpp", "max_forks_repo_name": "mtao/balsa", "max_forks_repo_head_hexsha": "1552f3a367a80dfc41fffc50b5628b46ba716ab8", "max_forks_repo_licenses": ["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.2954545455, "max_line_length": 130, "alphanum_fraction": 0.6489614243, "num_tokens": 828, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419958239132, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.4584755864296074}}
{"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    testImuFactor.cpp\n * @brief   Unit test for ImuFactor\n * @author  Luca Carlone, Stephen Williams, Richard Roberts\n */\n\n#include <gtsam/nonlinear/Values.h>\n#include <gtsam/nonlinear/Symbol.h>\n#include <gtsam/navigation/ImuFactor.h>\n#include <gtsam/navigation/CombinedImuFactor.h>\n#include <gtsam/navigation/ImuBias.h>\n#include <gtsam/geometry/Pose3.h>\n#include <gtsam/base/LieVector.h>\n#include <gtsam/base/TestableAssertions.h>\n#include <gtsam/base/numericalDerivative.h>\n#include <CppUnitLite/TestHarness.h>\n\n#include <boost/bind.hpp>\n#include <list>\n\nusing namespace std;\nusing namespace gtsam;\n\n// Convenience for named keys\nusing symbol_shorthand::X;\nusing symbol_shorthand::V;\nusing symbol_shorthand::B;\n\n/* ************************************************************************* */\nnamespace {\n\nVector callEvaluateError(const ImuFactor& factor,\n    const Pose3& pose_i, const LieVector& vel_i, const Pose3& pose_j, const LieVector& vel_j,\n    const imuBias::ConstantBias& bias)\n{\n  return factor.evaluateError(pose_i, vel_i, pose_j, vel_j, bias);\n}\n\nRot3 evaluateRotationError(const ImuFactor& factor,\n    const Pose3& pose_i, const LieVector& vel_i, const Pose3& pose_j, const LieVector& vel_j,\n    const imuBias::ConstantBias& bias)\n{\n  return Rot3::Expmap(factor.evaluateError(pose_i, vel_i, pose_j, vel_j, bias).tail(3) ) ;\n}\n\nImuFactor::PreintegratedMeasurements evaluatePreintegratedMeasurements(\n    const imuBias::ConstantBias& bias,\n    const list<Vector3>& measuredAccs,\n    const list<Vector3>& measuredOmegas,\n    const list<double>& deltaTs,\n    const Vector3& initialRotationRate = Vector3(0.0,0.0,0.0)\n    )\n{\n  ImuFactor::PreintegratedMeasurements result(bias, Matrix3::Identity(),\n      Matrix3::Identity(), Matrix3::Identity());\n\n  list<Vector3>::const_iterator itAcc = measuredAccs.begin();\n  list<Vector3>::const_iterator itOmega = measuredOmegas.begin();\n  list<double>::const_iterator itDeltaT = deltaTs.begin();\n  for( ; itAcc != measuredAccs.end(); ++itAcc, ++itOmega, ++itDeltaT) {\n    result.integrateMeasurement(*itAcc, *itOmega, *itDeltaT);\n  }\n\n  return result;\n}\n\nVector3 evaluatePreintegratedMeasurementsPosition(\n    const imuBias::ConstantBias& bias,\n    const list<Vector3>& measuredAccs,\n    const list<Vector3>& measuredOmegas,\n    const list<double>& deltaTs,\n    const Vector3& initialRotationRate = Vector3(0.0,0.0,0.0) )\n{\n  return evaluatePreintegratedMeasurements(bias,\n      measuredAccs, measuredOmegas, deltaTs, initialRotationRate).deltaPij;\n}\n\nVector3 evaluatePreintegratedMeasurementsVelocity(\n    const imuBias::ConstantBias& bias,\n    const list<Vector3>& measuredAccs,\n    const list<Vector3>& measuredOmegas,\n    const list<double>& deltaTs,\n    const Vector3& initialRotationRate = Vector3(0.0,0.0,0.0) )\n{\n  return evaluatePreintegratedMeasurements(bias,\n      measuredAccs, measuredOmegas, deltaTs).deltaVij;\n}\n\nRot3 evaluatePreintegratedMeasurementsRotation(\n    const imuBias::ConstantBias& bias,\n    const list<Vector3>& measuredAccs,\n    const list<Vector3>& measuredOmegas,\n    const list<double>& deltaTs,\n    const Vector3& initialRotationRate = Vector3(0.0,0.0,0.0) )\n{\n  return evaluatePreintegratedMeasurements(bias,\n      measuredAccs, measuredOmegas, deltaTs).deltaRij;\n}\n\nRot3 evaluateRotation(const Vector3 measuredOmega, const Vector3 biasOmega, const double deltaT)\n{\n  return Rot3::Expmap((measuredOmega - biasOmega) * deltaT);\n}\n\n\nVector3 evaluateLogRotation(const Vector3 thetahat, const Vector3 deltatheta)\n{\n  return Rot3::Logmap( Rot3::Expmap(thetahat).compose( Rot3::Expmap(deltatheta) ) );\n}\n\n}\n\n/* ************************************************************************* */\nTEST( CombinedImuFactor, PreintegratedMeasurements )\n{\n  cout << \"++++++++++++++++++++++++++++++ PreintegratedMeasurements +++++++++++++++++++++++++++++++++++++++ \" << endl;\n  // Linearization point\n  imuBias::ConstantBias bias(Vector3(0,0,0), Vector3(0,0,0)); ///< Current estimate of acceleration and angular rate biases\n\n  // Measurements\n  Vector3 measuredAcc(0.1, 0.0, 0.0);\n  Vector3 measuredOmega(M_PI/100.0, 0.0, 0.0);\n  double deltaT = 0.5;\n  double tol = 1e-6;\n\n  // Actual preintegrated values\n  ImuFactor::PreintegratedMeasurements expected1(bias, Matrix3::Zero(),\n\t\t  Matrix3::Zero(), Matrix3::Zero());\n  expected1.integrateMeasurement(measuredAcc, measuredOmega, deltaT);\n\n  CombinedImuFactor::CombinedPreintegratedMeasurements actual1(bias,\n\t\t  Matrix3::Zero(), Matrix3::Zero(), Matrix3::Zero(),\n\t\t  Matrix3::Zero(), Matrix3::Zero(), Matrix::Zero(6,6));\n\n//           const imuBias::ConstantBias& bias, ///< Current estimate of acceleration and rotation rate biases\n//           const Matrix3& measuredAccCovariance, ///< Covariance matrix of measuredAcc\n//           const Matrix3& measuredOmegaCovariance, ///< Covariance matrix of measuredAcc\n//           const Matrix3& integrationErrorCovariance, ///< Covariance matrix of measuredAcc\n//           const Matrix3& biasAccCovariance, ///< Covariance matrix of biasAcc (random walk describing BIAS evolution)\n//           const Matrix3& biasOmegaCovariance, ///< Covariance matrix of biasOmega (random walk describing BIAS evolution)\n//           const Matrix& biasAccOmegaInit ///< Covariance of biasAcc & biasOmega when preintegrating measurements\n\n  actual1.integrateMeasurement(measuredAcc, measuredOmega, deltaT);\n\n  EXPECT(assert_equal(Vector(expected1.deltaPij), Vector(actual1.deltaPij), tol));\n  EXPECT(assert_equal(Vector(expected1.deltaVij), Vector(actual1.deltaVij), tol));\n  EXPECT(assert_equal(expected1.deltaRij, actual1.deltaRij, tol));\n  DOUBLES_EQUAL(expected1.deltaTij, actual1.deltaTij, tol);\n}\n\n\n/* ************************************************************************* */\nTEST( CombinedImuFactor, ErrorWithBiases )\n{\n  cout << \"++++++++++++++++++++++++++++++ ErrorWithBiases +++++++++++++++++++++++++++++++++++++++ \" << endl;\n\n  imuBias::ConstantBias bias(Vector3(0.2, 0, 0), Vector3(0, 0, 0.3)); // Biases (acc, rot)\n  imuBias::ConstantBias bias2(Vector3(0.2, 0.2, 0), Vector3(1, 0, 0.3)); // Biases (acc, rot)\n  Pose3 x1(Rot3::Expmap(Vector3(0, 0, M_PI/4.0)), Point3(5.0, 1.0, -50.0));\n  LieVector v1(3, 0.5, 0.0, 0.0);\n  Pose3 x2(Rot3::Expmap(Vector3(0, 0, M_PI/4.0 + M_PI/10.0)), Point3(5.5, 1.0, -50.0));\n  LieVector v2(3, 0.5, 0.0, 0.0);\n\n  // Measurements\n  Vector3 gravity; gravity << 0, 0, 9.81;\n  Vector3 omegaCoriolis; omegaCoriolis << 0, 0.1, 0.1;\n  Vector3 measuredOmega; measuredOmega << 0, 0, M_PI/10.0+0.3;\n  Vector3 measuredAcc = x1.rotation().unrotate(-Point3(gravity)).vector() + Vector3(0.2,0.0,0.0);\n  double deltaT = 1.0;\n  double tol = 1e-6;\n\n  //           const imuBias::ConstantBias& bias, ///< Current estimate of acceleration and rotation rate biases\n  //           const Matrix3& measuredAccCovariance, ///< Covariance matrix of measuredAcc\n  //           const Matrix3& measuredOmegaCovariance, ///< Covariance matrix of measuredAcc\n  //           const Matrix3& integrationErrorCovariance, ///< Covariance matrix of measuredAcc\n  //           const Matrix3& biasAccCovariance, ///< Covariance matrix of biasAcc (random walk describing BIAS evolution)\n  //           const Matrix3& biasOmegaCovariance, ///< Covariance matrix of biasOmega (random walk describing BIAS evolution)\n  //           const Matrix& biasAccOmegaInit ///< Covariance of biasAcc & biasOmega when preintegrating measurements\n\n  Matrix I6x6(6,6);\n  I6x6 = Matrix::Identity(6,6);\n\n\n  ImuFactor::PreintegratedMeasurements pre_int_data(imuBias::ConstantBias(Vector3(0.2, 0.0, 0.0), Vector3(0.0, 0.0, 0.0)),\n\t\t  Matrix3::Identity(), Matrix3::Identity(), Matrix3::Identity());\n\n    pre_int_data.integrateMeasurement(measuredAcc, measuredOmega, deltaT);\n\n   CombinedImuFactor::CombinedPreintegratedMeasurements Combined_pre_int_data(\n\t\t   imuBias::ConstantBias(Vector3(0.2, 0.0, 0.0),  Vector3(0.0, 0.0, 0.0)),\n  \t\t  Matrix3::Identity(), Matrix3::Identity(), Matrix3::Identity(), Matrix3::Identity(), 2 * Matrix3::Identity(),\tI6x6 );\n\n   Combined_pre_int_data.integrateMeasurement(measuredAcc, measuredOmega, deltaT);\n\n\n    // Create factor\n    ImuFactor factor(X(1), V(1), X(2), V(2), B(1), pre_int_data, gravity, omegaCoriolis);\n\n    noiseModel::Gaussian::shared_ptr Combinedmodel = noiseModel::Gaussian::Covariance(Combined_pre_int_data.PreintMeasCov);\n    CombinedImuFactor Combinedfactor(X(1), V(1), X(2), V(2), B(1), B(2), Combined_pre_int_data, gravity, omegaCoriolis, Combinedmodel);\n\n\n    Vector errorExpected = factor.evaluateError(x1, v1, x2, v2, bias);\n\n    Vector errorActual = Combinedfactor.evaluateError(x1, v1, x2, v2, bias, bias2);\n\n\n    EXPECT(assert_equal(errorExpected, errorActual.head(9), tol));\n\n    // Expected Jacobians\n    Matrix H1e, H2e, H3e, H4e, H5e;\n    (void) factor.evaluateError(x1, v1, x2, v2, bias, H1e, H2e, H3e, H4e, H5e);\n\n\n    // Actual Jacobians\n\tMatrix H1a, H2a, H3a, H4a, H5a, H6a;\n\t(void) Combinedfactor.evaluateError(x1, v1, x2, v2, bias, bias2, H1a, H2a, H3a, H4a, H5a, H6a);\n\n\tEXPECT(assert_equal(H1e, H1a.topRows(9)));\n\tEXPECT(assert_equal(H2e, H2a.topRows(9)));\n\tEXPECT(assert_equal(H3e, H3a.topRows(9)));\n\tEXPECT(assert_equal(H4e, H4a.topRows(9)));\n\tEXPECT(assert_equal(H5e, H5a.topRows(9)));\n}\n\n/* ************************************************************************* */\nTEST( CombinedImuFactor, FirstOrderPreIntegratedMeasurements )\n{\n  cout << \"++++++++++++++++++++++++++++++ FirstOrderPreIntegratedMeasurements +++++++++++++++++++++++++++++++++++++++ \" << endl;\n  // Linearization point\n  imuBias::ConstantBias bias; ///< Current estimate of acceleration and rotation rate biases\n\n  Pose3 body_P_sensor(Rot3::Expmap(Vector3(0,0.1,0.1)), Point3(1, 0, 1));\n\n  // Measurements\n  list<Vector3> measuredAccs, measuredOmegas;\n  list<double> deltaTs;\n  measuredAccs.push_back(Vector3(0.1, 0.0, 0.0));\n  measuredOmegas.push_back(Vector3(M_PI/100.0, 0.0, 0.0));\n  deltaTs.push_back(0.01);\n  measuredAccs.push_back(Vector3(0.1, 0.0, 0.0));\n  measuredOmegas.push_back(Vector3(M_PI/100.0, 0.0, 0.0));\n  deltaTs.push_back(0.01);\n  for(int i=1;i<100;i++)\n  {\n    measuredAccs.push_back(Vector3(0.05, 0.09, 0.01));\n    measuredOmegas.push_back(Vector3(M_PI/100.0, M_PI/300.0, 2*M_PI/100.0));\n    deltaTs.push_back(0.01);\n  }\n\n  // Actual preintegrated values\n  ImuFactor::PreintegratedMeasurements preintegrated =\n      evaluatePreintegratedMeasurements(bias, measuredAccs, measuredOmegas, deltaTs, Vector3(M_PI/100.0, 0.0, 0.0));\n\n  // Compute numerical derivatives\n  Matrix expectedDelPdelBias = numericalDerivative11<imuBias::ConstantBias>(\n      boost::bind(&evaluatePreintegratedMeasurementsPosition, _1, measuredAccs, measuredOmegas, deltaTs, Vector3(M_PI/100.0, 0.0, 0.0)), bias);\n  Matrix expectedDelPdelBiasAcc   = expectedDelPdelBias.leftCols(3);\n  Matrix expectedDelPdelBiasOmega = expectedDelPdelBias.rightCols(3);\n\n  Matrix expectedDelVdelBias = numericalDerivative11<imuBias::ConstantBias>(\n      boost::bind(&evaluatePreintegratedMeasurementsVelocity, _1, measuredAccs, measuredOmegas, deltaTs, Vector3(M_PI/100.0, 0.0, 0.0)), bias);\n  Matrix expectedDelVdelBiasAcc   = expectedDelVdelBias.leftCols(3);\n  Matrix expectedDelVdelBiasOmega = expectedDelVdelBias.rightCols(3);\n\n  Matrix expectedDelRdelBias = numericalDerivative11<Rot3,imuBias::ConstantBias>(\n      boost::bind(&evaluatePreintegratedMeasurementsRotation, _1, measuredAccs, measuredOmegas, deltaTs, Vector3(M_PI/100.0, 0.0, 0.0)), bias);\n  Matrix expectedDelRdelBiasAcc   = expectedDelRdelBias.leftCols(3);\n  Matrix expectedDelRdelBiasOmega = expectedDelRdelBias.rightCols(3);\n\n  // Compare Jacobians\n  EXPECT(assert_equal(expectedDelPdelBiasAcc, preintegrated.delPdelBiasAcc));\n  EXPECT(assert_equal(expectedDelPdelBiasOmega, preintegrated.delPdelBiasOmega));\n  EXPECT(assert_equal(expectedDelVdelBiasAcc, preintegrated.delVdelBiasAcc));\n  EXPECT(assert_equal(expectedDelVdelBiasOmega, preintegrated.delVdelBiasOmega));\n  EXPECT(assert_equal(expectedDelRdelBiasAcc, Matrix::Zero(3,3)));\n  EXPECT(assert_equal(expectedDelRdelBiasOmega, preintegrated.delRdelBiasOmega));\n}\n\n#include <gtsam/linear/GaussianFactorGraph.h>\n\n\n/* ************************************************************************* */\n  int main() { TestResult tr; return TestRegistry::runAllTests(tr);}\n/* ************************************************************************* */\n", "meta": {"hexsha": "e46b736728ccf9c3b0002fe5913550b86bc9b1ef", "size": 12732, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/navigation/tests/testCombinedImuFactor.cpp", "max_stars_repo_name": "malcolmreynolds/GTSAM", "max_stars_repo_head_hexsha": "e911b4d39f8a8c8604663bd46f10e7f53c860ae8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-07-23T19:34:50.000Z", "max_stars_repo_stars_event_max_datetime": "2017-07-23T19:34:50.000Z", "max_issues_repo_path": "gtsam/navigation/tests/testCombinedImuFactor.cpp", "max_issues_repo_name": "malcolmreynolds/GTSAM", "max_issues_repo_head_hexsha": "e911b4d39f8a8c8604663bd46f10e7f53c860ae8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gtsam/navigation/tests/testCombinedImuFactor.cpp", "max_forks_repo_name": "malcolmreynolds/GTSAM", "max_forks_repo_head_hexsha": "e911b4d39f8a8c8604663bd46f10e7f53c860ae8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.8686868687, "max_line_length": 143, "alphanum_fraction": 0.685516808, "num_tokens": 3606, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347362, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.45847558264971383}}
{"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 testUnit3.cpp\n * @date Feb 03, 2012\n * @author Can Erdogan\n * @author Frank Dellaert\n * @author Alex Trevor\n * @brief Tests the Unit3 class\n */\n\n#include <gtsam/geometry/Unit3.h>\n#include <gtsam/geometry/Rot3.h>\n#include <gtsam/base/Testable.h>\n#include <gtsam/base/numericalDerivative.h>\n#include <CppUnitLite/TestHarness.h>\n#include <boost/bind.hpp>\n#include <boost/foreach.hpp>\n#include <boost/random.hpp>\n#include <boost/thread.hpp>\n#include <boost/assign/std/vector.hpp>\n#include <cmath>\n\nusing namespace boost::assign;\nusing namespace gtsam;\nusing namespace std;\n\nGTSAM_CONCEPT_TESTABLE_INST(Unit3)\nGTSAM_CONCEPT_MANIFOLD_INST(Unit3)\n\n//*******************************************************************************\nPoint3 point3_(const Unit3& p) {\n  return p.point3();\n}\nTEST(Unit3, point3) {\n  vector<Point3> ps;\n  ps += Point3(1, 0, 0), Point3(0, 1, 0), Point3(0, 0, 1), Point3(1, 1, 0)\n      / sqrt(2.0);\n  Matrix actualH, expectedH;\n  BOOST_FOREACH(Point3 p,ps) {\n    Unit3 s(p);\n    expectedH = numericalDerivative11<Point3, Unit3>(point3_, s);\n    EXPECT(assert_equal(p, s.point3(actualH), 1e-8));\n    EXPECT(assert_equal(expectedH, actualH, 1e-9));\n  }\n}\n\n//*******************************************************************************\nstatic Unit3 rotate_(const Rot3& R, const Unit3& p) {\n  return R * p;\n}\n\nTEST(Unit3, rotate) {\n  Rot3 R = Rot3::yaw(0.5);\n  Unit3 p(1, 0, 0);\n  Unit3 expected = Unit3(R.column(1));\n  Unit3 actual = R * p;\n  EXPECT(assert_equal(expected, actual, 1e-8));\n  Matrix actualH, expectedH;\n  // Use numerical derivatives to calculate the expected Jacobian\n  {\n    expectedH = numericalDerivative21(rotate_, R, p);\n    R.rotate(p, actualH, boost::none);\n    EXPECT(assert_equal(expectedH, actualH, 1e-9));\n  }\n  {\n    expectedH = numericalDerivative22(rotate_, R, p);\n    R.rotate(p, boost::none, actualH);\n    EXPECT(assert_equal(expectedH, actualH, 1e-9));\n  }\n}\n\n//*******************************************************************************\nstatic Unit3 unrotate_(const Rot3& R, const Unit3& p) {\n  return R.unrotate(p);\n}\n\nTEST(Unit3, unrotate) {\n  Rot3 R = Rot3::yaw(-M_PI / 4.0);\n  Unit3 p(1, 0, 0);\n  Unit3 expected = Unit3(1, 1, 0);\n  Unit3 actual = R.unrotate(p);\n  EXPECT(assert_equal(expected, actual, 1e-8));\n  Matrix actualH, expectedH;\n  // Use numerical derivatives to calculate the expected Jacobian\n  {\n    expectedH = numericalDerivative21(unrotate_, R, p);\n    R.unrotate(p, actualH, boost::none);\n    EXPECT(assert_equal(expectedH, actualH, 1e-9));\n  }\n  {\n    expectedH = numericalDerivative22(unrotate_, R, p);\n    R.unrotate(p, boost::none, actualH);\n    EXPECT(assert_equal(expectedH, actualH, 1e-9));\n  }\n}\n\n//*******************************************************************************\nTEST(Unit3, error) {\n  Unit3 p(1, 0, 0), q = p.retract((Vector(2) << 0.5, 0)), //\n  r = p.retract((Vector(2) << 0.8, 0));\n  EXPECT(assert_equal((Vector(2) << 0, 0), p.error(p), 1e-8));\n  EXPECT(assert_equal((Vector(2) << 0.479426, 0), p.error(q), 1e-5));\n  EXPECT(assert_equal((Vector(2) << 0.717356, 0), p.error(r), 1e-5));\n\n  Matrix actual, expected;\n  // Use numerical derivatives to calculate the expected Jacobian\n  {\n    expected = numericalDerivative11<Unit3>(\n        boost::bind(&Unit3::error, &p, _1, boost::none), q);\n    p.error(q, actual);\n    EXPECT(assert_equal(expected.transpose(), actual, 1e-9));\n  }\n  {\n    expected = numericalDerivative11<Unit3>(\n        boost::bind(&Unit3::error, &p, _1, boost::none), r);\n    p.error(r, actual);\n    EXPECT(assert_equal(expected.transpose(), actual, 1e-9));\n  }\n}\n\n//*******************************************************************************\nTEST(Unit3, distance) {\n  Unit3 p(1, 0, 0), q = p.retract((Vector(2) << 0.5, 0)), //\n  r = p.retract((Vector(2) << 0.8, 0));\n  EXPECT_DOUBLES_EQUAL(0, p.distance(p), 1e-8);\n  EXPECT_DOUBLES_EQUAL(0.47942553860420301, p.distance(q), 1e-8);\n  EXPECT_DOUBLES_EQUAL(0.71735609089952279, p.distance(r), 1e-8);\n\n  Matrix actual, expected;\n  // Use numerical derivatives to calculate the expected Jacobian\n  {\n    expected = numericalGradient<Unit3>(\n        boost::bind(&Unit3::distance, &p, _1, boost::none), q);\n    p.distance(q, actual);\n    EXPECT(assert_equal(expected.transpose(), actual, 1e-9));\n  }\n  {\n    expected = numericalGradient<Unit3>(\n        boost::bind(&Unit3::distance, &p, _1, boost::none), r);\n    p.distance(r, actual);\n    EXPECT(assert_equal(expected.transpose(), actual, 1e-9));\n  }\n}\n\n//*******************************************************************************\nTEST(Unit3, localCoordinates0) {\n  Unit3 p;\n  Vector actual = p.localCoordinates(p);\n  EXPECT(assert_equal(zero(2), actual, 1e-8));\n}\n\n//*******************************************************************************\nTEST(Unit3, localCoordinates1) {\n  Unit3 p, q(1, 6.12385e-21, 0);\n  Vector actual = p.localCoordinates(q);\n  CHECK(assert_equal(zero(2), actual, 1e-8));\n}\n\n//*******************************************************************************\nTEST(Unit3, localCoordinates2) {\n  Unit3 p, q(-1, 0, 0);\n  Vector expected = (Vector(2) << M_PI, 0);\n  Vector actual = p.localCoordinates(q);\n  CHECK(assert_equal(expected, actual, 1e-8));\n}\n\n//*******************************************************************************\nTEST(Unit3, basis) {\n  Unit3 p;\n  Matrix expected(3, 2);\n  expected << 0, 0, 0, -1, 1, 0;\n  Matrix actual = p.basis();\n  EXPECT(assert_equal(expected, actual, 1e-8));\n}\n\n//*******************************************************************************\nTEST(Unit3, retract) {\n  Unit3 p;\n  Vector v(2);\n  v << 0.5, 0;\n  Unit3 expected(0.877583, 0, 0.479426);\n  Unit3 actual = p.retract(v);\n  EXPECT(assert_equal(expected, actual, 1e-6));\n  EXPECT(assert_equal(v, p.localCoordinates(actual), 1e-8));\n}\n\n//*******************************************************************************\nTEST(Unit3, retract_expmap) {\n  Unit3 p;\n  Vector v(2);\n  v << (M_PI / 2.0), 0;\n  Unit3 expected(Point3(0, 0, 1));\n  Unit3 actual = p.retract(v);\n  EXPECT(assert_equal(expected, actual, 1e-8));\n  EXPECT(assert_equal(v, p.localCoordinates(actual), 1e-8));\n}\n\n//*******************************************************************************\n/// Returns a random vector\ninline static Vector randomVector(const Vector& minLimits,\n    const Vector& maxLimits) {\n\n  // Get the number of dimensions and create the return vector\n  size_t numDims = dim(minLimits);\n  Vector vector = zero(numDims);\n\n  // Create the random vector\n  for (size_t i = 0; i < numDims; i++) {\n    double range = maxLimits(i) - minLimits(i);\n    vector(i) = (((double) rand()) / RAND_MAX) * range + minLimits(i);\n  }\n  return vector;\n}\n\n//*******************************************************************************\n// Let x and y be two Unit3's.\n// The equality x.localCoordinates(x.retract(v)) == v should hold.\nTEST(Unit3, localCoordinates_retract) {\n\n  size_t numIterations = 10000;\n  Vector minSphereLimit = (Vector(3) << -1.0, -1.0, -1.0), maxSphereLimit =\n      (Vector(3) << 1.0, 1.0, 1.0);\n  Vector minXiLimit = (Vector(2) << -1.0, -1.0), maxXiLimit = (Vector(2) << 1.0, 1.0);\n  for (size_t i = 0; i < numIterations; i++) {\n\n    // Sleep for the random number generator (TODO?: Better create all of them first).\n    boost::this_thread::sleep(boost::posix_time::milliseconds(0));\n\n    // Create the two Unit3s.\n    // NOTE: You can not create two totally random Unit3's because you cannot always compute\n    // between two any Unit3's. (For instance, they might be at the different sides of the circle).\n    Unit3 s1(Point3(randomVector(minSphereLimit, maxSphereLimit)));\n//      Unit3 s2 (Point3(randomVector(minSphereLimit, maxSphereLimit)));\n    Vector v12 = randomVector(minXiLimit, maxXiLimit);\n    Unit3 s2 = s1.retract(v12);\n\n    // Check if the local coordinates and retract return the same results.\n    Vector actual_v12 = s1.localCoordinates(s2);\n    EXPECT(assert_equal(v12, actual_v12, 1e-3));\n    Unit3 actual_s2 = s1.retract(actual_v12);\n    EXPECT(assert_equal(s2, actual_s2, 1e-3));\n  }\n}\n\n//*******************************************************************************\n// Let x and y be two Unit3's.\n// The equality x.localCoordinates(x.retract(v)) == v should hold.\nTEST(Unit3, localCoordinates_retract_expmap) {\n\n  size_t numIterations = 10000;\n  Vector minSphereLimit = (Vector(3) << -1.0, -1.0, -1.0), maxSphereLimit =\n      (Vector(3) << 1.0, 1.0, 1.0);\n  Vector minXiLimit = (Vector(2) << -M_PI, -M_PI), maxXiLimit = (Vector(2) << M_PI, M_PI);\n  for (size_t i = 0; i < numIterations; i++) {\n\n    // Sleep for the random number generator (TODO?: Better create all of them first).\n    boost::this_thread::sleep(boost::posix_time::milliseconds(0));\n\n    // Create the two Unit3s.\n    // Unlike the above case, we can use any two sphers.\n    Unit3 s1(Point3(randomVector(minSphereLimit, maxSphereLimit)));\n//      Unit3 s2 (Point3(randomVector(minSphereLimit, maxSphereLimit)));\n    Vector v12 = randomVector(minXiLimit, maxXiLimit);\n\n    // Magnitude of the rotation can be at most pi\n    if (v12.norm() > M_PI)\n      v12 = v12 / M_PI;\n    Unit3 s2 = s1.retract(v12);\n\n    // Check if the local coordinates and retract return the same results.\n    Vector actual_v12 = s1.localCoordinates(s2);\n    EXPECT(assert_equal(v12, actual_v12, 1e-3));\n    Unit3 actual_s2 = s1.retract(actual_v12);\n    EXPECT(assert_equal(s2, actual_s2, 1e-3));\n  }\n}\n\n//*******************************************************************************\n//TEST( Pose2, between )\n//{\n//  // <\n//  //\n//  //       ^\n//  //\n//  // *--0--*--*\n//  Pose2 gT1(M_PI/2.0, Point2(1,2)); // robot at (1,2) looking towards y\n//  Pose2 gT2(M_PI, Point2(-1,4));  // robot at (-1,4) loooking at negative x\n//\n//  Matrix actualH1,actualH2;\n//  Pose2 expected(M_PI/2.0, Point2(2,2));\n//  Pose2 actual1 = gT1.between(gT2);\n//  Pose2 actual2 = gT1.between(gT2,actualH1,actualH2);\n//  EXPECT(assert_equal(expected,actual1));\n//  EXPECT(assert_equal(expected,actual2));\n//\n//  Matrix expectedH1 = (Matrix(3,3) <<\n//      0.0,-1.0,-2.0,\n//      1.0, 0.0,-2.0,\n//      0.0, 0.0,-1.0\n//  );\n//  Matrix numericalH1 = numericalDerivative21<Pose2,Pose2,Pose2>(testing::between, gT1, gT2);\n//  EXPECT(assert_equal(expectedH1,actualH1));\n//  EXPECT(assert_equal(numericalH1,actualH1));\n//  // Assert H1 = -AdjointMap(between(p2,p1)) as in doc/math.lyx\n//  EXPECT(assert_equal(-gT2.between(gT1).AdjointMap(),actualH1));\n//\n//  Matrix expectedH2 = (Matrix(3,3) <<\n//       1.0, 0.0, 0.0,\n//       0.0, 1.0, 0.0,\n//       0.0, 0.0, 1.0\n//  );\n//  Matrix numericalH2 = numericalDerivative22<Pose2,Pose2,Pose2>(testing::between, gT1, gT2);\n//  EXPECT(assert_equal(expectedH2,actualH2));\n//  EXPECT(assert_equal(numericalH2,actualH2));\n//\n//}\n\n//*******************************************************************************\nTEST(Unit3, Random) {\n  boost::mt19937 rng(42);\n  // Check that is deterministic given same random seed\n  Point3 expected(-0.667578, 0.671447, 0.321713);\n  Point3 actual = Unit3::Random(rng).point3();\n  EXPECT(assert_equal(expected,actual,1e-5));\n  // Check that means are all zero at least\n  Point3 expectedMean, actualMean;\n  for (size_t i = 0; i < 100; i++)\n    actualMean = actualMean + Unit3::Random(rng).point3();\n  actualMean = actualMean / 100;\n  EXPECT(assert_equal(expectedMean,actualMean,0.1));\n}\n\n//*************************************************************************\nTEST (Unit3, FromPoint3) {\n  Matrix actualH;\n  Point3 point(1, -2, 3); // arbitrary point\n  Unit3 expected(point);\n  EXPECT(assert_equal(expected, Unit3::FromPoint3(point, actualH), 1e-8));\n  Matrix expectedH = numericalDerivative11<Unit3, Point3>(\n      boost::bind(Unit3::FromPoint3, _1, boost::none), point);\n  EXPECT(assert_equal(expectedH, actualH, 1e-8));\n}\n\n/* ************************************************************************* */\nint main() {\n  srand(time(NULL));\n  TestResult tr;\n  return TestRegistry::runAllTests(tr);\n}\n/* ************************************************************************* */\n", "meta": {"hexsha": "eb45ea60f23ff1f6c6ed0f9220dd2b188c18cb90", "size": 12438, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/geometry/tests/testUnit3.cpp", "max_stars_repo_name": "Ellon/gtsam-3.1.0", "max_stars_repo_head_hexsha": "7968c07cf79ff39ffce05dd7c1aadcd97d7c3c21", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-03-13T21:19:55.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-11T12:14:04.000Z", "max_issues_repo_path": "gtsam/geometry/tests/testUnit3.cpp", "max_issues_repo_name": "Ellon/gtsam-3.1.0", "max_issues_repo_head_hexsha": "7968c07cf79ff39ffce05dd7c1aadcd97d7c3c21", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gtsam/geometry/tests/testUnit3.cpp", "max_forks_repo_name": "Ellon/gtsam-3.1.0", "max_forks_repo_head_hexsha": "7968c07cf79ff39ffce05dd7c1aadcd97d7c3c21", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.4542936288, "max_line_length": 99, "alphanum_fraction": 0.5723589001, "num_tokens": 3534, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228891883799, "lm_q2_score": 0.6926419767901476, "lm_q1q2_score": 0.4584755784500853}}
{"text": "//==================================================================================================\n/*!\n\n  Copyright 2015 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#include <boost/simd/constant/log_2hi.hpp>\n#include <boost/simd/constant/log_2lo.hpp>\n#include <boost/simd/constant/log_2.hpp>\n#include <boost/simd/constant/eps.hpp>\n#include <boost/simd/as.hpp>\n#include <simd_test.hpp>\n\nSTF_CASE_TPL( \"Check log_2hi behavior for integral types\"\n            , (std::uint32_t)(std::uint64_t)\n              (std::int32_t)(std::int64_t)\n            )\n{\n  using boost::simd::as;\n  using boost::simd::detail::log_2hi;\n  using boost::simd::Log_2hi;\n  T ref = T(0);\n  STF_TYPE_IS(decltype(Log_2hi<T>()), T);\n  STF_EQUAL(Log_2hi<T>(), ref);\n  STF_EQUAL(log_2hi( as(T{}) ),ref);\n}\n\nSTF_CASE_TPL( \"Check log_2hi behavior for double\"\n            , (double)\n            )\n{\n  using boost::simd::as;\n  using boost::simd::detail::log_2hi;\n  using boost::simd::Log_2hi;\n  T ref = T(0.6931471803691238);\n  #ifdef HAS_LONG_DOUBLE\n  using boost::simd::Log_2lo;\n  using boost::simd::Eps;\n  long double L_2 = 0.693147180559945309417232121458;\n  STF_LESS((double)((long double)(Log_2lo<double>())+(long double)(Log_2hi<double>()))- L_2, Eps<double>()/2);\n  #endif\n\n  STF_TYPE_IS(decltype(Log_2hi<T>()), T);\n  STF_IEEE_EQUAL(Log_2hi<T>(), ref);\n  STF_IEEE_EQUAL(log_2hi( as(T{}) ), ref);\n}\n\nSTF_CASE_TPL( \"Check log_2hi behavior for float\"\n            , (float)\n            )\n{\n  using boost::simd::as;\n  using boost::simd::detail::log_2hi;\n  using boost::simd::Log_2hi;\n  using boost::simd::Log_2lo;\n  using boost::simd::Log_2;\n  using boost::simd::Eps;\n  STF_LESS(float(double(Log_2lo<float>())+double(Log_2hi<float>())- Log_2<double>()), Eps<float>());\n  T ref = T(6.9335937500000000e-1);\n  STF_TYPE_IS(decltype(Log_2hi<T>()), T);\n  STF_IEEE_EQUAL(Log_2hi<T>(), ref);\n  STF_IEEE_EQUAL(log_2hi( as(T{}) ), ref);\n}\n", "meta": {"hexsha": "8b68c1263d61b308b22e3795f9958f7073ccafbc", "size": 2110, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/constant/scalar/log_2hi.cpp", "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": "test/constant/scalar/log_2hi.cpp", "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": "test/constant/scalar/log_2hi.cpp", "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": 31.4925373134, "max_line_length": 110, "alphanum_fraction": 0.5995260664, "num_tokens": 642, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.6619228825191871, "lm_q1q2_score": 0.4584755780303507}}
{"text": "\n// BLAS level 1 (vector) -- complex numbers\n\n#include <iostream>\n#include <cmath>\n#include <complex> \n\n//#define BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n\n#include <boost/numeric/bindings/ublas/vector.hpp>\n#include <boost/numeric/bindings/blas/level1.hpp>\n#include \"utils.h\" \n\nnamespace blas = boost::numeric::bindings::blas;\nnamespace ublas = boost::numeric::ublas;\n\nusing std::cout;\nusing std::endl; \n\ntypedef double real_t;\ntypedef std::complex<real_t> cmplx_t;  \ntypedef ublas::vector<cmplx_t> vct_t; \n\nint main() {\n\n  int n = 6; \n\n  cout << endl; \n  vct_t v (n); \n  init_v (v, times_plus<cmplx_t> (cmplx_t (1, -1), cmplx_t (0, .1))); \n  print_v (v, \"v\"); \n\n  blas::scal (2.0, v); \n  print_v (v, \"2.0 v\"); \n\n  blas::scal (cmplx_t (-1, 0), v); \n  print_v (v, \"(-1, 0) v\"); \n\n  blas::scal (cmplx_t (0, 1), v);\n  print_v (v, \"(0, 1) v\"); \n\n  blas::set (cmplx_t (1, -1), v); \n  print_v (v, \"v\"); \n  vct_t v1 (n); \n  blas::set (cmplx_t (0, -1), v1); \n  print_v (v1, \"v1\"); \n\n  cout << endl; \n  cout << \"v^T v1 = \" << blas::dot (v, v1) << \" == \"\n    << blas::dotu (v, v1) << \" == \"\n    << inner_prod (v, v1) << endl; \n  cout << \"v^T v = \" << blas::dot (v, v) << \" == \"\n    << blas::dotu (v, v) << \" == \"\n    << inner_prod (v, v) << endl; \n  cout << \"v1^T v1 = \" << blas::dot (v1, v1) << \" == \"\n    << blas::dotu (v1, v1) << \" == \"\n    << inner_prod (v1, v1) << endl; \n\n  cout << endl; \n  cout << \"v^H v1 = \" << blas::dotc (v, v1) << \" == \"\n    << inner_prod (conj (v), v1) << \" == \"\n    << inner_prod (v1, conj (v)) << \" != \"\n    << inner_prod (v, conj (v1)) << endl; \n  cout << \"v^H v = \" << blas::dotc (v, v) << \" == \"\n    << inner_prod (conj (v), v) << \" == \"\n    << inner_prod (v, conj (v)) << endl; \n  cout << \"v1^H v1 = \" << blas::dotc (v1, v1) << \" == \"\n    << inner_prod (conj (v1), v1) << \" == \"\n    << inner_prod (v1, conj (v1)) << endl; \n\n  \n  cout << endl;\n  cout << \"||v||_1 = \" << blas::asum (v) << endl; \n  cout << \"||v||_2 = \" << blas::nrm2 (v) << \" == \"\n    << norm_2 (v) << endl; \n  \n  cout << endl;\n}\n", "meta": {"hexsha": "bb0b681879f10106925e0f498aba1946de5cfbb5", "size": 2014, "ext": "cc", "lang": "C++", "max_stars_repo_path": "externals/numeric_bindings/libs/numeric/bindings/atlas/ublas_cvct.cc", "max_stars_repo_name": "ljktest/siconos", "max_stars_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 137.0, "max_stars_repo_stars_event_min_datetime": "2015-06-16T15:55:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T06:01:59.000Z", "max_issues_repo_path": "externals/numeric_bindings/libs/numeric/bindings/atlas/ublas_cvct.cc", "max_issues_repo_name": "ljktest/siconos", "max_issues_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 381.0, "max_issues_repo_issues_event_min_datetime": "2015-09-22T15:31:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-14T09:05:23.000Z", "max_forks_repo_path": "externals/numeric_bindings/libs/numeric/bindings/atlas/ublas_cvct.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": 25.4936708861, "max_line_length": 70, "alphanum_fraction": 0.4980139027, "num_tokens": 799, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419958239132, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.45847557719088117}}
{"text": "#include <stan/math/prim/scal.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <gtest/gtest.h>\n\nTEST(MathFunctions,logical_gt) {\n  using stan::math::logical_gt;\n  EXPECT_TRUE(logical_gt(1,0));\n  EXPECT_TRUE(logical_gt(2,1.00));\n  EXPECT_TRUE(logical_gt(2.0,1));\n  EXPECT_TRUE(logical_gt(0,-1));\n\n  EXPECT_FALSE(logical_gt(1,1));\n  EXPECT_FALSE(logical_gt(5.7,5.7));\n  EXPECT_FALSE(logical_gt(-5.7,9.0));\n  EXPECT_FALSE(logical_gt(0,0.0));\n}\n\nTEST(MathFunctions, logical_gt_nan) {\n  double nan = std::numeric_limits<double>::quiet_NaN();\n  \n  EXPECT_FALSE(stan::math::logical_gt(1.0, nan));\n  EXPECT_FALSE(stan::math::logical_gt(nan, 2.0));\n  EXPECT_FALSE(stan::math::logical_gt(nan, nan));\n}\n", "meta": {"hexsha": "1320f679f20b2217d3b9fba36c100291289dee35", "size": 712, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/scal/fun/logical_gt_test.cpp", "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/test/unit/math/prim/scal/fun/logical_gt_test.cpp", "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/test/unit/math/prim/scal/fun/logical_gt_test.cpp", "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": 28.48, "max_line_length": 56, "alphanum_fraction": 0.7219101124, "num_tokens": 223, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419958239132, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.45847557719088117}}
{"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_FREXP_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_FREXP_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n    @ingroup group-ieee\n    This function object returns a mantissa and an exponent pair for the input\n\n\n    @par Header <boost/simd/function/frexp.hpp>\n\n    @par Semantic:\n\n    For every parameter of floating type\n\n    @code\n    std::tie(m, e)= frexp(x);\n    @endcode\n\n    is similar to:\n\n    @code\n    auto e = tofloat(exponent(x)+1);\n    auto m = mantissa(x)/2;\n    @endcode\n\n    @par Notes:\n\n    - Without the pedantic_ decorator,  calling @c frexp on @c Nan or @c Inf\n    has undefined behavior.\n\n    - the exponent and matissa are both returned as floating values:\n      if you need integral type exponent (as in the standard library)\n      use @ref ifrexp\n\n    - This function splits a floating point value \\f$x\\f$ in a signed\n      mantissa \\f$m\\f$ and an exponent \\f$e\\f$ so that:  \\f$x = m\\times 2^e\\f$,\n      with absolute value of \\f$m \\in [0.5, 1[\\f$ (except for \\f$x = 0\\f$)\n\n      @warningbox{Take care that these results differ from the returns\n      of the functions @ref mantissa and @ref exponent}\n\n    @par Decorators\n\n     - pedantic_ slower, but special values as @ref Nan or @ref Inf are handled properly.\n\n     - std_ transmits the call to @c std::frexp and converts the exponent.\n\n    @see ifrexp, exponent, mantissa\n\n\n    @par Example:\n\n      @snippet frexp.cpp frexp\n\n    @par Possible output:\n\n      @snippet frexp.txt frexp\n\n  **/\n  std::pair<IEEEValue, IEEEValue> frexp(IEEEValue const& x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/frexp.hpp>\n#include <boost/simd/function/scalar/frexp.hpp>\n#include <boost/simd/function/simd/frexp.hpp>\n\n#endif\n", "meta": {"hexsha": "9fdec7f2e4d3beb1d43379a9d444cf2d048afc38", "size": 2140, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/frexp.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/frexp.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/frexp.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": 25.7831325301, "max_line_length": 100, "alphanum_fraction": 0.6186915888, "num_tokens": 538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419704455589, "lm_q2_score": 0.6619228825191871, "lm_q1q2_score": 0.4584755696310939}}
{"text": "/* Copyright (C) 2012-2017 IBM Corp.\n * This program is Licensed under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *   http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License. See accompanying LICENSE file.\n */\n#include <cassert>\n#include <iostream>\n#include <iomanip>\n#include <numeric>\n#include <cmath>\n#include <atomic>\n#include <NTL/BasicThreadPool.h>\n#include <NTL/ZZ_pX.h>\n#include <NTL/xdouble.h>\n#include \"NumbTh.h\"\n#include \"PAlgebra.h\"\n#include \"DoubleCRT.h\"\n#include \"Context.h\"\n#include \"sample.h\"\n#include \"timing.h\"\n#include \"norms.h\"\n\nNTL_CLIENT\n\nvoid printHistogram(const vector<double>& data,\n                    const cx_double& mean, double step)\n{\n  vector<long> hist(8,0); // histogram: hist[i]= # of x'es with |x|<i*stdev\n  double max = 0.0;\n  double sum=0.0, sumSqr=0.0;\n  for (double x: data) {\n    sum += x;\n    sumSqr += x*x;\n    long j = std::floor(x/step);\n    if (j >= lsize(hist)) hist.resize(j+1, 0);\n    hist[j]++;\n    if (x > max) max = x;\n  }\n  sum /= data.size();    // E[x]\n  sumSqr /= data.size(); // E[x^2]\n  double stdev = sqrt(sumSqr - (sum*sum));\n\n  for (long i=hist.size()-1; i>0; i--) // cumulative\n    hist[i-1] += hist[i];\n\n  vector<double> dhist(hist.size(), 1.0);\n  vector<double> ratio(hist.size(), 0.0);\n  for (long i=1; i<lsize(dhist); i++) {\n    dhist[i] = hist[i]/double(hist[0]);\n    if (dhist[i]>0.0) ratio[i] = dhist[i-1]/dhist[i];\n  }\n  cout << data.size() << \" points, mean=\"<<mean<<endl;\n  cout << \"size mean=\"<<sum<<\", stdev=\"<<stdev\n       << \", max=\"<<max<<\".  Step=\"<<step<<endl;\n  cout << \"  histogram =\"<< hist<<endl\n       << \" probability=\"<<dhist<<endl\n       << \"      ratio =\"<<ratio<<endl<<endl;\n}\n\nvoid freshCtxtNoise(zzX& f, const Context& context,\n                    double sigma, bool modPhimX)\n{\n  zzX s, r, e1, e2, e3;\n  const PAlgebra& palg = context.zMStar;\n  sampleSmallBounded(s, context);\n  if (modPhimX) {\n    sampleSmall(r, palg.getPhiM()-1);\n    sampleGaussian(e1, palg.getPhiM()-1, sigma);\n    sampleGaussianBounded(e2, context, sigma);\n    sampleGaussian(e3, palg.getPhiM()-1, sigma);\n  } else {\n    sampleSmall(r, context);\n    sampleGaussian(e1, context, sigma);\n    sampleGaussianBounded(e2, context, sigma);\n    sampleGaussian(e3, context, sigma);\n  }\n  f = MulMod(s, e1, palg) + MulMod(r, e2, palg) + e3;\n}\n\nvoid roundingNoise(zzX& f, const Context& context,\n                   long p2r, bool modPhimX)\n{\n  zzX s, e1, e2;\n  const PAlgebra& palg = context.zMStar;\n  sampleSmallBounded(s, context);\n  if (modPhimX) {\n    sampleUniform(e1, palg.getPhiM()-1, p2r);\n    sampleUniform(e2, palg.getPhiM()-1, p2r);\n  } else {\n    sampleUniform(e1, context, p2r);\n    sampleUniform(e2, context, p2r);\n  }\n  f = MulMod(s, e1, palg) + e2;\n}\n\nint main(int argc, char **argv)\n{\n  FHE_NTIMER_START(init);\n  // get parameters from the command line\n  ArgMapping amap;\n\n  // long noPrint = 1;\n  // amap.arg(\"noPrint\", noPrint, \"suppress printouts\");\n\n  long m = 15;\n  amap.arg(\"m\", m, \"the cyclotomic index\");\n  double sigma = 0.0;\n  amap.arg(\"sigma\", sigma, \"nomral standard deviation\", \"heristic\");\n  long p = 2;\n  amap.arg(\"p\", p, \"plaintext base\");\n  long r = 1;\n  amap.arg(\"r\", r, \"lifting\");\n  long N = 1000;\n  amap.arg(\"N\", N, \"# of samples to use\");\n  long seed=0;\n  amap.arg(\"seed\", seed, \"PRG seed\");\n  long nt=4;\n  amap.arg(\"nt\", nt, \"number of threads\");\n  amap.parse(argc, argv);\n\n  if (seed != 0) NTL::SetSeed(ZZ(seed));\n  if (nt > 1)    NTL::SetNumThreads(nt);\n  long p2r = power_long(p, r);\n  if (sigma<=0.0) {\n    if (m&1) // odd m\n      sigma = 3.2*sqrt(m);\n    else\n      sigma=3.2;\n  }\n\n  Context context(m, p, r);\n  const PAlgebra& palg = context.zMStar;\n  buildModChain(context, /*L=*/5, /*c=*/3);\n  long phim = palg.getPhiM();\n  FHE_NTIMER_STOP(init);\n\n  cout << \"m=\"<<m<<\", phi(m)=\"<<palg.getPhiM()\n       << \", sigma=\"<<std::setprecision(3)<<sigma\n       << \", p^r=\"<<p2r << endl;\n\n  zzX f;\n  vector<double> data;\n  cx_double sum, mean;\n  double step;\n\n  step = (sigma+0.1)*0.54*(1+((m&1)? sqrt(phim*m): phim));\n  // fresh ciphertext, sampling mod X^m-1\n  data.resize(0);\n  sum = 0;\n  for (long i=0; i<N; i++) {\n    std::vector<cx_double> cemb;\n    freshCtxtNoise(f, context, sigma, false);\n    canonicalEmbedding(cemb, f, palg); // Canonical embedding of f\n    for (auto& entry : cemb) {\n      double sz2 = conv<double>(std::norm<double>(entry));\n      data.push_back(std::sqrt(sz2));\n      sum += entry/double(lsize(cemb));\n    }\n  }\n  mean = sum / double(N);\n  cout << \"fresh ctxt noise, sample mod X^m-1: \";\n  printHistogram(data, mean, step);\n  data.resize(0);\n  sum = 0;\n  // rounding error, mod Phi_m(X)\n\n  step = (2*p2r+1)*(phim-2)/8.0;\n  for (long i=0; i<N; i++) {\n    std::vector<cx_double> cemb;\n    roundingNoise(f, context, p2r, true);\n    canonicalEmbedding(cemb, f, palg); // Canonical embedding of f\n    for (auto& entry : cemb) {\n      double sz2 = conv<double>(std::norm<double>(entry));\n      data.push_back(std::sqrt(sz2));\n      sum += entry/double(lsize(cemb));\n    }\n  }\n  mean = sum / double(N);\n  cout << \"\\nrounding noise, sample mod Phi_m(X): \";\n  printHistogram(data, mean, step);\n  data.resize(0);\n  sum = 0;\n\n  cout << endl;\n\n  //  printAllTimers();\n  return 0;\n}\n\n/********************************************************************/\n#if 0 // OLD CODE\n  vector<xdouble> l2(8, xdouble(0.0));\n  vector<xdouble> ratio(8, xdouble(1.0));\n\n  cout << \"*** m=\"<<m<<\", sampling \"<<N<<\" different f's ***\\n\";\n  for (long i=0; i<N; i++) {\n    ZZX f;\n    sampleSmall(f, m);\n    rem(f, f, phimX);\n    if (IsZero(f)) continue;\n    xdouble ll = embeddingL2NormSquared(f,m)/phim;\n    l2[0] += ll;\n    for (long j=1; j<lsize(l2); j++) {\n      NTL::SqrMod(f, f, phimX); // fd -> fd^2\n      ll *= ll;\n\n      xdouble tt = embeddingL2NormSquared(f, m)/phim;\n      l2[j] += tt;\n\n      tt /= ll;\n      if (tt>ratio[j]) ratio[j] = tt;\n    }\n  }\n  xdouble base = l2[0] / N;\n  long e = 1;\n  xdouble factorial(1.0);\n  for (long j=0; j<lsize(l2); j++) {\n    l2[j] /= N;\n    for (long i=e/2 +1; i<=e; i++) factorial *= i;\n    cout << \"E[|f^\"<<e<<\"|^2]=\"<<l2[j]\n         << \",\\t= \"<<(l2[j]/base)<<\"*E[|f^2|]^{\"<<e<<\"} (vs. \"\n         << e<<\"! =\"<<factorial<<\")\\n\";\n    cout << \"\\t\\t\\t max ratio = \"<<ratio[j]<<endl;\n    base *= base;\n    e *= 2;\n  }\n#endif\n#if 0\n  step = (1+sqrt(phim*log(phim)))*0.85;\n  for (long i=0; i<N; i++) {\n    sampleSmall(f, palg);\n    data.push_back(embeddingLargestCoeff(f, palg));\n  }\n  cout << \"sampleSmall noise: \";\n  printHistogram(data, mean, step);\n  data.resize(0);\n  step = sigma*(2+((m&1)? sqrt(m*log(phim)) : sqrt(phim*log(phim))))*1.2;\n  for (long i=0; i<N; i++) {\n    sampleGaussian(f, palg, sigma);\n    data.push_back(embeddingLargestCoeff(f, palg));\n  }\n  cout << \"sampleGaussian noise: \";\n  printHistogram(data, mean, step);\n  data.resize(0);\n  exit(0);\n#endif\n#if 0\n  // First test: fresh ciphertext, sampling mod Phi_m(X)\n  for (long i=0; i<N; i++) {\n    std::vector<cx_double> cemb;\n    freshCtxtNoise(f, palg, sigma, true);\n    canonicalEmbedding(cemb, f, palg); // Canonical embedding of f\n    for (auto& entry : cemb) {\n      double sz2 = conv<double>(std::norm<double>(entry));\n      data.push_back(std::sqrt(sz2));\n      sum += entry/double(lsize(cemb));\n    }\n  }\n  mean = sum / double(N);\n  cout << \"fresh ctxt noise, sample mod Phi_m(X): \";\n  printHistogram(data, mean, step);\n#endif\n#if 0\n  for (long i=0; i<N; i++) {\n    std::vector<cx_double> cemb;\n    roundingNoise(f, palg, p2r, false);\n    canonicalEmbedding(cemb, f, palg); // Canonical embedding of f\n    for (auto& entry : cemb) {\n      double sz2 = conv<double>(std::norm<double>(entry));\n      data.push_back(std::sqrt(sz2));\n      sum += entry/double(lsize(cemb));\n    }\n  }\n  mean = sum / double(N);\n  cout << \"rounding noise, sample mod X^m-1: \";\n  printHistogram(data, mean, step);\n#endif\n", "meta": {"hexsha": "a7c25b473a01739fd5ba11c11bcc644dd506c032", "size": 8234, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "misc/Test_embedding.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": "misc/Test_embedding.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": "misc/Test_embedding.cpp", "max_forks_repo_name": "felipeturing/HElib", "max_forks_repo_head_hexsha": "6b9ae8b5ab43af3b566598c095d4edaba6d6a775", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 402.0, "max_forks_repo_forks_event_min_datetime": "2015-01-03T04:14:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T00:50:34.000Z", "avg_line_length": 28.9929577465, "max_line_length": 75, "alphanum_fraction": 0.588292446, "num_tokens": 2722, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419704455588, "lm_q2_score": 0.6619228825191871, "lm_q1q2_score": 0.4584755696310938}}
{"text": "#include <rct_optimizations/validation/homography_validation.h>\n#include <Eigen/Dense>\n#include <rct_optimizations/types.h>\n\nnamespace rct_optimizations\n{\nGridCorrespondenceSampler::GridCorrespondenceSampler(const std::size_t rows_, const std::size_t cols_, const std::size_t stride_)\n  : rows(rows_)\n  , cols(cols_)\n  , stride(stride_)\n{\n}\n\nstd::vector<std::size_t> GridCorrespondenceSampler::getSampleCorrespondenceIndices() const\n{\n  const std::size_t n_samples = 4;\n\n  // Make sure there are at least two times as many points as the number of sample points\n  if ((rows * cols / 2) < n_samples)\n  {\n    std::stringstream ss;\n    ss << \"Number of correspondences does not exceed minimum of \" << n_samples * 2 << \" (\" << rows * cols << \" provided)\";\n    throw std::runtime_error(ss.str());\n  }\n\n  std::vector<std::size_t> correspondence_indices;\n  correspondence_indices.reserve(n_samples);\n\n  // Sample points should be the corners of the grid, using the first element in the stride\n  std::size_t upper_left_idx = 0;\n  std::size_t upper_right_idx = (cols - 1) * stride;\n  std::size_t lower_left_idx = (rows - 1) * (cols * stride);\n  std::size_t lower_right_idx = (rows * cols * stride) - stride;\n\n  correspondence_indices.push_back(upper_left_idx);\n  correspondence_indices.push_back(upper_right_idx);\n  correspondence_indices.push_back(lower_left_idx);\n  correspondence_indices.push_back(lower_right_idx);\n\n  return correspondence_indices;\n}\n\nRandomCorrespondenceSampler::RandomCorrespondenceSampler(const std::size_t n_correspondences_, const std::size_t n_samples_, const unsigned seed_)\n  : n_correspondences(n_correspondences_)\n  , n_samples(n_samples_)\n  , seed(seed_)\n{\n  const unsigned min_samples = 4;\n  if (n_samples < min_samples)\n  {\n    std::stringstream ss;\n    ss << \"Not enough samples specified: \" << n_samples << \" vs. \" << min_samples << \" required\";\n    throw std::runtime_error(ss.str());\n  }\n  if (n_samples > n_correspondences)\n  {\n    std::stringstream ss;\n    ss << \"Number of correspondences (\" << n_correspondences << \") must exceed number of samples (\" << n_samples << \")\";\n    throw std::runtime_error(ss.str());\n  }\n}\n\nstd::vector<std::size_t> RandomCorrespondenceSampler::getSampleCorrespondenceIndices() const\n{\n  // Create a random number generator with a uniform distribution across all indices\n  std::mt19937 rand_gen(seed);\n  std::uniform_int_distribution<std::size_t> dist(0, n_correspondences - 1);\n  auto fn = [&rand_gen, &dist]() -> std::size_t { return dist(rand_gen); };\n\n  // Generate a vector of 4 random correspondence indices\n  std::vector<std::size_t> output(n_samples);\n  std::generate(output.begin(), output.end(), fn);\n\n  return output;\n}\n\nEigen::VectorXd calculateHomographyError(const Correspondence2D3D::Set &correspondences,\n                                         const CorrespondenceSampler &correspondence_sampler)\n{\n  /* There is a 3x3 homography matrix, H, that can transform a point from one plane onto a different plane\n   * | u | = k * | H00 H01 H02 | * | x |\n   * | v |       | H10 H11 H12 |   | y |\n   * | 1 |       | H20 H12  1  |   | 1 |\n   *\n   * In our case we have 2 sets of known corresponding planar points: points on the planar target, and points in the image plane\n   * Therefore, there is some matrix, H, which can transform target points into the image plane.\n   * If the target points and camera points actually match, we should be able to:\n   *   1. Calculate H for a subset of corresponding points\n   *   2. Transform the remaining target points by H to obtain estimates of their locations in the image plane\n   *   3. Compare the calculated estimations to the actual image points to make sure they are very close. If they are not close, we know that the correspondences are not valid\n   *\n   * The matrix H has 8 unique values.\n   * These 8 values of the homography matrix can be solved for, given a set of (at least) 8 corresponding planar vectors, by rearranging the above equations:\n   *\n   * A * H = b, where\n   * H = inv(A) * b\n   *   - A is matrix (size 2*n x 8), where n is the number of corresponding vectors\n   *   - H is a vector (size 8 x 1) of the unknown elements of the homography matrix\n   *   - B is a vector (size 2*n x 1) representing the elements of one set of planar vectors\n   *\n   *                  A               *              H    =    b\n   * |-x0 -y0  -1   0    0    0   u0*x0   u0*y0 | * | H00 | = | -u0 |\n   * | 0   0   0  -x0   -y0  -1   v0*x0   v0*y0 | * | H01 | = | -v0 |\n   *                              ...\n   * |-x7 -y7  -1   0    0    0   u7*x7   u7*y7 | * | H20 | = | -u7 |\n   * | 0   0   0  -x7   -y7  -1   v7*x7   v7*y7 | * | H21 | = | -v7 |\n   *\n   */\n\n  // Select the points that we want to use to create the H matrix\n  std::vector<std::size_t> sample_correspondence_indices = correspondence_sampler\n                                                             .getSampleCorrespondenceIndices();\n  std::size_t n_samples = sample_correspondence_indices.size();\n\n  // Ensure that there are enough points for testing outside of the sampled set\n  if (correspondences.size() < 2 * n_samples)\n  {\n    std::stringstream ss;\n    ss << \"Correspondences size is not more than 2x sample size (\" << correspondences.size()\n       << \" correspondences vs. \" << n_samples << \")\";\n    throw std::runtime_error(ss.str());\n  }\n\n  // Create the A and b matrices\n  Eigen::MatrixXd A(2 * n_samples, 8);\n  Eigen::MatrixXd b(2 * n_samples, 1);\n\n  // Fill the A and B matrices with data from the selected correspondences\n  for (std::size_t i = 0; i < n_samples; ++i)\n  {\n    std::size_t corr_idx = sample_correspondence_indices.at(i);\n    const Correspondence2D3D &corr = correspondences.at(corr_idx);\n\n    //assign A row-th row:\n    const double x = corr.in_target.x();\n    const double y = corr.in_target.y();\n    const double u = corr.in_image.x();\n    const double v = corr.in_image.y();\n    A.row(2 * i) << -x, -y, -1.0, 0.0, 0.0, 0.0, u * x, u * y;\n    A.row(2 * i + 1) << 0.0, 0.0, 0.0, -x, -y, -1.0, v * x, v * y;\n\n    b.block<2, 1>(2 * i, 0) = -1.0 * corr.in_image;\n  }\n\n  // Create the homography matrix\n  Eigen::Matrix<double, 3, 3, Eigen::RowMajor> H = Eigen::Matrix3d::Ones();\n\n  // Map the elements of the H matrix into a column vector and solve for the first 8\n  {\n    Eigen::Map<Eigen::VectorXd> hv(H.data(), 9);\n    hv.head<8>() = A.fullPivLu().solve(b);\n  }\n\n  // Estimate the image locations of all the target observations and compare to the actual image locations\n  Eigen::VectorXd error(correspondences.size());\n  for (std::size_t i = 0; i < correspondences.size(); ++i)\n  {\n    const Correspondence2D3D &corr = correspondences[i];\n\n    // Calculate the scaling factor\n    double ki = 1.0 / (H(2, 0) * corr.in_target.x() + H(2, 1) * corr.in_target.y() + 1.0);\n\n    // Replace the z-element of the point with 1\n    Eigen::Vector3d xy(corr.in_target);\n    xy(2) = 1.0;\n\n    // Estimate the point in the image plane\n    Eigen::Vector3d in_image_estimate = ki * H * xy;\n\n    // Calculate the error\n    Eigen::Vector2d image_error = corr.in_image - in_image_estimate.head<2>();\n    error(i) = image_error.norm();\n  }\n\n  return error;\n}\n\nEigen::VectorXd calculateHomographyError(const Correspondence3D3D::Set& correspondences,\n                                         const CorrespondenceSampler& correspondence_sampler)\n{\n  // Convert the 3D correspondence points into 2D points by scaling the x and y components by the z component\n  Correspondence2D3D::Set correspondences_2d;\n  correspondences_2d.reserve(correspondences.size());\n\n  // Store the z values for scaling later\n  Eigen::VectorXd z_values(correspondences.size());\n\n  for (std::size_t i = 0; i < correspondences.size(); ++i)\n  {\n    const auto& corr = correspondences[i];\n\n    // Store the z value of the correspondence\n    z_values[i] = corr.in_image.z();\n\n    // Generate a scaled 2D correspondence\n    Correspondence2D3D corr_2d;\n    corr_2d.in_target = corr.in_target;\n    corr_2d.in_image = (corr.in_image / corr.in_image.z()).head<2>();\n    correspondences_2d.push_back(corr_2d);\n  }\n\n  // Calculate the homography error\n  Eigen::VectorXd error = calculateHomographyError(correspondences_2d, correspondence_sampler);\n\n  // Scale the errors again by the z values of the original correspondences\n  return error.cwiseProduct(z_values);\n}\n\n} // namespace rct_optimizations\n\n", "meta": {"hexsha": "0fd60bad16850c327439d1315a3abb72cfbbd4d4", "size": 8355, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rct_optimizations/src/rct_optimizations/validation/homography_validation.cpp", "max_stars_repo_name": "m-limbird/robot_cal_tools", "max_stars_repo_head_hexsha": "c3ee0c26895af50219afc450e7e6f866b7b86cbe", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "rct_optimizations/src/rct_optimizations/validation/homography_validation.cpp", "max_issues_repo_name": "m-limbird/robot_cal_tools", "max_issues_repo_head_hexsha": "c3ee0c26895af50219afc450e7e6f866b7b86cbe", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rct_optimizations/src/rct_optimizations/validation/homography_validation.cpp", "max_forks_repo_name": "m-limbird/robot_cal_tools", "max_forks_repo_head_hexsha": "c3ee0c26895af50219afc450e7e6f866b7b86cbe", "max_forks_repo_licenses": ["Apache-2.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.5971563981, "max_line_length": 175, "alphanum_fraction": 0.6649910233, "num_tokens": 2319, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419704455589, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.45847556501173103}}
{"text": "//////////////////////////////////////////////////////////////////\r\n//\r\n// lazy_thunk_tests.cpp\r\n//\r\n// Tests for thunk functions.\r\n//\r\n//\r\n/*=============================================================================\r\n    Copyright (c) 2000-2003 Brian McNamara and Yannis Smaragdakis\r\n    Copyright (c) 2001-2007 Joel de Guzman\r\n    Copyright (c) 2015 John Fletcher\r\n\r\n    Distributed under the Boost Software License, Version 1.0. (See accompanying\r\n    file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n==============================================================================*/\r\n\r\n#include <iostream>\r\n#include <boost/phoenix/core.hpp>\r\n#include <boost/phoenix/function.hpp>\r\n#include <boost/shared_ptr.hpp>\r\n#include <boost/phoenix/function/lazy_prelude.hpp>\r\n\r\n#include <boost/detail/lightweight_test.hpp>\r\n\r\nusing namespace boost::phoenix;\r\n\r\nusing std::cout;\r\nusing std::endl;\r\n\r\n\r\n\r\nint main() {\r\n   using boost::phoenix::arg_names::arg1;\r\n   using boost::phoenix::arg_names::arg2;\r\n\r\n   BOOST_TEST( thunk1(inc,1)()()             == 2);\r\n   BOOST_TEST( thunk1(inc,arg1)(1)()         == 2);\r\n   BOOST_TEST( thunk2(plus,1,2)()()          == 3);\r\n   BOOST_TEST( thunk2(plus,arg1,arg2)(1,2)() == 3);\r\n\r\n   list<int> l  = enum_from_to(1,5);\r\n   list<int> l4 = take(4,l)();\r\n   BOOST_TEST( foldl(plus,0,l4)()              == 10);\r\n   BOOST_TEST( thunk3(foldl,plus,0,l4)()()     == 10);\r\n   BOOST_TEST( thunk3(foldl,plus,arg1,l4)(0)() == 10);\r\n\r\n   return boost::report_errors();\r\n}\r\n", "meta": {"hexsha": "3cd6ad5a4e7f8e0c1dad275bf1de468bbcb53413", "size": 1514, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/phoenix/test/function/lazy_thunk_tests.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": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/phoenix/test/function/lazy_thunk_tests.cpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-04T18:00:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-04T18:00:00.000Z", "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/phoenix/test/function/lazy_thunk_tests.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 30.8979591837, "max_line_length": 81, "alphanum_fraction": 0.5330250991, "num_tokens": 392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.6926419704455589, "lm_q1q2_score": 0.45847556501173103}}
{"text": "//=======================================================================\n// Copyright 1997, 1998, 1999, 2000 University of Notre Dame.\n// Authors: Andrew Lumsdaine, Lie-Quan Lee, Jeremy G. Siek\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n#include <boost/config.hpp>\n#include <iostream>\n#include <iterator>\n#include <vector>\n#include <list>\n// Use boost::queue instead of std::queue because std::queue doesn't\n// model Buffer; it has to top() function. -Jeremy\n#include <boost/pending/queue.hpp>\n\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/visitors.hpp>\n#include <boost/graph/breadth_first_search.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <boost/graph/graph_utility.hpp>\n\nusing namespace std;\nusing namespace boost;\n/*\n  This example does a best-first-search (using dijkstra's) and\n  simultaneously makes a copy of the graph (assuming the graph is\n  connected).\n\n  Example Graph: (p. 90 \"Data Structures and Network Algorithms\", Tarjan)\n\n              g\n            3+ +2\n            / 1 \\\n           e+----f\n           |+0 5++\n           | \\ / |\n         10|  d  |12\n           |8++\\7|\n           +/ | +|\n           b 4|  c\n            \\ | +\n            6+|/3\n              a\n\n  Sample Output:\na --> c d \nb --> a d\nc --> f\nd --> c e f\ne --> b g\nf --> e g\ng -->\nStarting graph:\na(32767); c d\nc(32767); f\nd(32767); c e f\nf(32767); e g\ne(32767); b g\ng(32767);\nb(32767); a d\nResult:\na(0); d c\nd(4); f e c\nc(3); f\nf(9); g e\ne(4); g b\ng(7);\nb(14); d a \n\n*/\n\ntypedef property<vertex_color_t, default_color_type, \n         property<vertex_distance_t,int> > VProperty;\ntypedef int weight_t;\ntypedef property<edge_weight_t,weight_t> EProperty;\n\ntypedef adjacency_list<vecS, vecS, directedS, VProperty, EProperty > Graph;\n\n\n\ntemplate <class Tag>\nstruct endl_printer\n  : public boost::base_visitor< endl_printer<Tag> >\n{\n  typedef Tag event_filter;\n  endl_printer(std::ostream& os) : m_os(os) { }\n  template <class T, class Graph>\n  void operator()(T, Graph&) { m_os << std::endl; }\n  std::ostream& m_os;\n};\ntemplate <class Tag>\nendl_printer<Tag> print_endl(std::ostream& os, Tag) {\n  return endl_printer<Tag>(os);\n}\n\ntemplate <class PA, class Tag>\nstruct edge_printer\n : public boost::base_visitor< edge_printer<PA, Tag> >\n{\n  typedef Tag event_filter;\n\n  edge_printer(PA pa, std::ostream& os) : m_pa(pa), m_os(os) { }\n\n  template <class T, class Graph>\n  void operator()(T x, Graph& g) {\n    m_os << \"(\" << get(m_pa, source(x, g)) << \",\" \n         << get(m_pa, target(x, g)) << \") \";\n  }\n  PA m_pa;\n  std::ostream& m_os;\n};\ntemplate <class PA, class Tag>\nedge_printer<PA, Tag>\nprint_edge(PA pa, std::ostream& os, Tag) {\n  return edge_printer<PA, Tag>(pa, os);\n}\n\n\ntemplate <class NewGraph, class Tag>\nstruct graph_copier \n  : public boost::base_visitor<graph_copier<NewGraph, Tag> >\n{\n  typedef Tag event_filter;\n\n  graph_copier(NewGraph& graph) : new_g(graph) { }\n\n  template <class Edge, class Graph>\n  void operator()(Edge e, Graph& g) {\n    add_edge(source(e, g), target(e, g), new_g);\n  }\nprivate:\n  NewGraph& new_g;\n};\ntemplate <class NewGraph, class Tag>\ninline graph_copier<NewGraph, Tag>\ncopy_graph(NewGraph& g, Tag) {\n  return graph_copier<NewGraph, Tag>(g);\n}\n\ntemplate <class Graph, class Name>\nvoid print(Graph& G, Name name)\n{\n  typename boost::graph_traits<Graph>::vertex_iterator ui, uiend;\n  for (boost::tie(ui, uiend) = vertices(G); ui != uiend; ++ui) {\n    cout << name[*ui] << \" --> \";\n    typename boost::graph_traits<Graph>::adjacency_iterator vi, viend;\n    for(boost::tie(vi, viend) = adjacent_vertices(*ui, G); vi != viend; ++vi)\n      cout << name[*vi] << \" \";\n    cout << endl;\n  }\n    \n}\n\n\nint \nmain(int , char* [])\n{\n  // Name and ID numbers for the vertices\n  char name[] = \"abcdefg\";\n  enum { a, b, c, d, e, f, g, N};\n\n  Graph G(N);\n  boost::property_map<Graph, vertex_index_t>::type \n    vertex_id = get(vertex_index, G);\n\n  std::vector<weight_t> distance(N, (numeric_limits<weight_t>::max)());\n  typedef boost::graph_traits<Graph>::vertex_descriptor Vertex;\n  std::vector<Vertex> parent(N);\n\n  typedef std::pair<int,int> E;\n\n  E edges[] = { E(a,c), E(a,d),\n                E(b,a), E(b,d),\n                E(c,f),\n                E(d,c), E(d,e), E(d,f),\n                E(e,b), E(e,g),\n                E(f,e), E(f,g) };\n\n  int weight[] = { 3, 4,\n                   6, 8,\n                   12,\n                   7, 0, 5,\n                   10, 3,\n                   1, 2 };\n\n  for (int i = 0; i < 12; ++i)\n    add_edge(edges[i].first, edges[i].second, weight[i], G);\n\n  print(G, name);\n\n  adjacency_list<listS, vecS, directedS, \n    property<vertex_color_t, default_color_type> > G_copy(N);\n\n  cout << \"Starting graph:\" << endl;\n\n  std::ostream_iterator<int> cout_int(std::cout, \" \");\n  std::ostream_iterator<char> cout_char(std::cout, \" \");\n\n  boost::queue<Vertex> Q;\n  boost::breadth_first_search\n    (G, vertex(a, G), Q,\n     make_bfs_visitor(\n     boost::make_list\n      (write_property(make_iterator_property_map(name, vertex_id,\n                                                name[0]),\n                      cout_char, on_examine_vertex()),\n       write_property(make_iterator_property_map(distance.begin(),\n                                                vertex_id, \n                                                distance[0]), \n                      cout_int, on_examine_vertex()),\n       print_edge(make_iterator_property_map(name, vertex_id, \n                                            name[0]),\n                  std::cout, on_examine_edge()),\n       print_endl(std::cout, on_finish_vertex()))),\n     get(vertex_color, G));\n\n  std::cout << \"about to call dijkstra's\" << std::endl;\n\n  parent[vertex(a, G)] = vertex(a, G);\n  boost::dijkstra_shortest_paths\n    (G, vertex(a, G), \n     distance_map(make_iterator_property_map(distance.begin(), vertex_id, \n                                             distance[0])).\n     predecessor_map(make_iterator_property_map(parent.begin(), vertex_id,\n                                                parent[0])).\n     visitor(make_dijkstra_visitor(copy_graph(G_copy, on_examine_edge()))));\n\n  cout << endl;\n  cout << \"Result:\" << endl;\n  boost::breadth_first_search\n    (G, vertex(a, G), \n     visitor(make_bfs_visitor(\n     boost::make_list\n     (write_property(make_iterator_property_map(name, vertex_id,\n                                                name[0]),\n                     cout_char, on_examine_vertex()),\n      write_property(make_iterator_property_map(distance.begin(),\n                                                vertex_id, \n                                                distance[0]), \n                     cout_int, on_examine_vertex()),\n      print_edge(make_iterator_property_map(name, vertex_id, \n                                            name[0]),\n                 std::cout, on_examine_edge()),\n      print_endl(std::cout, on_finish_vertex())))));\n\n  return 0;\n}\n", "meta": {"hexsha": "04c69f888a31079eb75bd3a6562805e316fcece9", "size": 7099, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/graph/example/dave.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "boost/libs/graph/example/dave.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "boost/libs/graph/example/dave.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 28.396, "max_line_length": 77, "alphanum_fraction": 0.5666995351, "num_tokens": 1860, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419704455588, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.4584755650117309}}
{"text": "\n\n/* --------------------------------------------------------------------- \n * \n * Copyright (C) 2009 - 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: Guido Kanschat, Texas A&M University, 2009 \n *         Timo Heister, Clemson University, 2019 \n */ \n\n\n\n// \u524d\u9762\u51e0\u4e2a\u6587\u4ef6\u5df2\u7ecf\u5728\u524d\u9762\u7684\u4f8b\u5b50\u4e2d\u8bb2\u8fc7\u4e86\uff0c\u56e0\u6b64\u4e0d\u518d\u505a\u8fdb\u4e00\u6b65\u7684\u8bc4\u8bba\u3002\n\n#include <deal.II/base/quadrature_lib.h> \n#include <deal.II/base/function.h> \n#include <deal.II/lac/vector.h> \n#include <deal.II/lac/dynamic_sparsity_pattern.h> \n#include <deal.II/lac/sparse_matrix.h> \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/fe/fe_values.h> \n#include <deal.II/dofs/dof_handler.h> \n#include <deal.II/numerics/vector_tools.h> \n#include <deal.II/dofs/dof_tools.h> \n#include <deal.II/numerics/data_out.h> \n#include <deal.II/fe/mapping_q1.h> \n\n// \u8fd9\u91cc\u5b9a\u4e49\u4e86\u4e0d\u8fde\u7eed\u7684\u6709\u9650\u5143\u3002\u5b83\u4eec\u7684\u4f7f\u7528\u65b9\u5f0f\u4e0e\u6240\u6709\u5176\u4ed6\u6709\u9650\u5143\u76f8\u540c\uff0c\u4e0d\u8fc7--\u6b63\u5982\u4f60\u5728\u4ee5\u524d\u7684\u6559\u7a0b\u7a0b\u5e8f\u4e2d\u6240\u770b\u5230\u7684--\u7528\u6237\u4e0e\u6709\u9650\u5143\u7c7b\u7684\u4ea4\u4e92\u6839\u672c\u4e0d\u591a\uff1a\u5b83\u4eec\u88ab\u4f20\u9012\u7ed9 <code>DoFHandler</code> \u548c <code>FEValues</code> \u5bf9\u8c61\uff0c\u4ec5\u6b64\u800c\u5df2\u3002\n\n#include <deal.II/fe/fe_dgq.h> \n\n// FEInterfaceValues\u9700\u8981\u8fd9\u4e2a\u5934\u6765\u8ba1\u7b97\u754c\u9762\u4e0a\u7684\u79ef\u5206\u3002\n\n#include <deal.II/fe/fe_interface_values.h> \n\n// \u6211\u4eec\u5c06\u4f7f\u7528\u6700\u7b80\u5355\u7684\u6c42\u89e3\u5668\uff0c\u79f0\u4e3aRichardson\u8fed\u4ee3\uff0c\u5b83\u4ee3\u8868\u4e86\u4e00\u4e2a\u7b80\u5355\u7684\u7f3a\u9677\u4fee\u6b63\u3002\u8fd9\u4e0e\u4e00\u4e2a\u5757\u72b6SSOR\u9884\u5904\u7406\u5668\uff08\u5b9a\u4e49\u5728precondition_block.h\u4e2d\uff09\u76f8\u7ed3\u5408\uff0c\u8be5\u9884\u5904\u7406\u5668\u4f7f\u7528DG\u79bb\u6563\u4ea7\u751f\u7684\u7cfb\u7edf\u77e9\u9635\u7684\u7279\u6b8a\u5757\u72b6\u7ed3\u6784\u3002\n\n#include <deal.II/lac/solver_richardson.h> \n#include <deal.II/lac/precondition_block.h> \n\n// \u6211\u4eec\u5c06\u4f7f\u7528\u68af\u5ea6\u4f5c\u4e3a\u7ec6\u5316\u6307\u6807\u3002\n\n#include <deal.II/numerics/derivative_approximation.h> \n\n// \u6700\u540e\uff0c\u65b0\u7684\u5305\u542b\u6587\u4ef6\u7528\u4e8e\u4f7f\u7528MeshWorker\u6846\u67b6\u4e2d\u7684Mesh_loop\u3002\n\n#include <deal.II/meshworker/mesh_loop.h> \n\n// \u50cf\u6240\u6709\u7684\u7a0b\u5e8f\u4e00\u6837\uff0c\u6211\u4eec\u5728\u5b8c\u6210\u8fd9\u4e00\u90e8\u5206\u65f6\uff0c\u8981\u5305\u62ec\u6240\u9700\u7684C++\u5934\u6587\u4ef6\uff0c\u5e76\u58f0\u660e\u6211\u4eec\u8981\u4f7f\u7528dealii\u547d\u540d\u7a7a\u95f4\u4e2d\u7684\u5bf9\u8c61\uff0c\u4e0d\u542b\u524d\u7f00\u3002\n\n#include <iostream> \n#include <fstream> \n\nnamespace Step12 \n{ \n  using namespace dealii; \n// @sect3{Equation data}  \n\n// \u9996\u5148\uff0c\u6211\u4eec\u5b9a\u4e49\u4e00\u4e2a\u63cf\u8ff0\u4e0d\u5747\u5300\u8fb9\u754c\u6570\u636e\u7684\u7c7b\u3002\u7531\u4e8e\u53ea\u4f7f\u7528\u5b83\u7684\u503c\uff0c\u6211\u4eec\u5b9e\u73b0value_list()\uff0c\u4f46\u4e0d\u5b9a\u4e49Function\u7684\u6240\u6709\u5176\u4ed6\u51fd\u6570\u3002\n\n  template <int dim> \n  class BoundaryValues : public Function<dim> \n  { \n  public: \n    BoundaryValues() = default; \n    virtual void value_list(const std::vector<Point<dim>> &points, \n                            std::vector<double> &          values, \n                            const unsigned int component = 0) const override; \n  }; \n\n// \u8003\u8651\u5230\u6d41\u52a8\u65b9\u5411\uff0c\u5355\u4f4d\u65b9\u5757 $[0,1]^2$ \u7684\u6d41\u5165\u8fb9\u754c\u662f\u53f3\u8fb9\u754c\u548c\u4e0b\u8fb9\u754c\u3002\u6211\u4eec\u5728x\u8f74\u4e0a\u89c4\u5b9a\u4e86\u4e0d\u8fde\u7eed\u7684\u8fb9\u754c\u503c1\u548c0\uff0c\u5728\u53f3\u8fb9\u754c\u4e0a\u89c4\u5b9a\u4e86\u503c0\u3002\u8be5\u51fd\u6570\u5728\u6d41\u51fa\u8fb9\u754c\u4e0a\u7684\u503c\u5c06\u4e0d\u4f1a\u5728DG\u65b9\u6848\u4e2d\u4f7f\u7528\u3002\n\n  template <int dim> \n  void BoundaryValues<dim>::value_list(const std::vector<Point<dim>> &points, \n                                       std::vector<double> &          values, \n                                       const unsigned int component) const \n  {  \n    (void)component; \n    AssertIndexRange(component, 1); \n    Assert(values.size() == points.size(), \n           ExcDimensionMismatch(values.size(), points.size())); \n\n    for (unsigned int i = 0; i < values.size(); ++i) \n      { \n        if (points[i](0) < 0.5)  \n          values[i] = 1.; \n        else \n          values[i] = 0.; \n      } \n  } \n\n// \u6700\u540e\uff0c\u4e00\u4e2a\u8ba1\u7b97\u5e76\u8fd4\u56de\u98ce\u573a\u7684\u51fd\u6570  $\\beta=\\beta(\\mathbf x)$  \u3002\u6b63\u5982\u5728\u4ecb\u7ecd\u4e2d\u6240\u89e3\u91ca\u7684\uff0c\u57282D\u4e2d\u6211\u4eec\u5c06\u4f7f\u7528\u4e00\u4e2a\u56f4\u7ed5\u539f\u70b9\u7684\u65cb\u8f6c\u573a\u3002\u57283D\u4e2d\uff0c\u6211\u4eec\u53ea\u9700\u4e0d\u8bbe\u7f6e $z$ \u5206\u91cf\uff08\u5373\u4e3a\u96f6\uff09\uff0c\u800c\u8fd9\u4e2a\u51fd\u6570\u5728\u76ee\u524d\u7684\u5b9e\u73b0\u4e2d\u4e0d\u80fd\u7528\u4e8e1D\u3002\n\n  template <int dim> \n  Tensor<1, dim> beta(const Point<dim> &p) \n  { \n    Assert(dim >= 2, ExcNotImplemented()); \n\n    Tensor<1, dim> wind_field; \n    wind_field[0] = -p[1]; \n    wind_field[1] = p[0]; \n\n    if (wind_field.norm() > 1e-10) \n      wind_field /= wind_field.norm(); \n\n    return wind_field; \n  } \n// @sect3{The ScratchData and CopyData classes}  \n\n// \u4ee5\u4e0b\u5bf9\u8c61\u662f\u6211\u4eec\u5728\u8c03\u7528 MeshWorker::mesh_loop(). \u65f6\u4f7f\u7528\u7684\u6293\u53d6\u548c\u590d\u5236\u5bf9\u8c61 \u65b0\u5bf9\u8c61\u662fFEInterfaceValues\u5bf9\u8c61\uff0c\u5b83\u7684\u5de5\u4f5c\u539f\u7406\u7c7b\u4f3c\u4e8eFEValues\u6216FEFacesValues\uff0c\u53ea\u662f\u5b83\u4f5c\u7528\u4e8e\u4e24\u4e2a\u5355\u5143\u683c\u4e4b\u95f4\u7684\u63a5\u53e3\uff0c\u5e76\u5141\u8bb8\u6211\u4eec\u4ee5\u6211\u4eec\u7684\u5f31\u5f62\u5f0f\u7ec4\u88c5\u63a5\u53e3\u6761\u6b3e\u3002\n\n  template <int dim> \n  struct ScratchData \n  { \n    ScratchData(const Mapping<dim> &       mapping, \n                const FiniteElement<dim> & fe, \n                const Quadrature<dim> &    quadrature, \n                const Quadrature<dim - 1> &quadrature_face, \n                const UpdateFlags          update_flags = update_values | \n                                                 update_gradients | \n                                                 update_quadrature_points | \n                                                 update_JxW_values, \n                const UpdateFlags interface_update_flags = \n                  update_values | update_gradients | update_quadrature_points | \n                  update_JxW_values | update_normal_vectors) \n      : fe_values(mapping, fe, quadrature, update_flags) \n      , fe_interface_values(mapping, \n                            fe, \n                            quadrature_face, \n                            interface_update_flags) \n    {} \n\n    ScratchData(const ScratchData<dim> &scratch_data) \n      : fe_values(scratch_data.fe_values.get_mapping(), \n                  scratch_data.fe_values.get_fe(), fas\n                  scratch_data.fe_values.get_quadrature(), \n                  scratch_data.fe_values.get_update_flags()) \n      , fe_interface_values(scratch_data.fe_interface_values.get_mapping(), \n                            scratch_data.fe_interface_values.get_fe(), \n                            scratch_data.fe_interface_values.get_quadrature(), \n                            scratch_data.fe_interface_values.get_update_flags()) \n    {} \n\n    FEValues<dim>          fe_values; \n    FEInterfaceValues<dim> fe_interface_values; \n  }; \n\n  struct CopyDataFace \n  { \n    FullMatrix<double>                   cell_matrix; \n    std::vector<types::global_dof_index> joint_dof_indices; \n  }; \n\n  struct CopyData \n  { \n    FullMatrix<double>                   cell_matrix; \n    Vector<double>                       cell_rhs; \n    std::vector<types::global_dof_index> local_dof_indices; \n    std::vector<CopyDataFace>            face_data; \n\n    template <class Iterator> \n    void reinit(const Iterator &cell, unsigned int dofs_per_cell) \n    { \n      cell_matrix.reinit(dofs_per_cell, dofs_per_cell); \n      cell_rhs.reinit(dofs_per_cell); \n\n      local_dof_indices.resize(dofs_per_cell); \n      cell->get_dof_indices(local_dof_indices); \n    } \n  }; \n// @sect3{The AdvectionProblem class}  \n\n// \u5728\u8fd9\u4e2a\u51c6\u5907\u5de5\u4f5c\u4e4b\u540e\uff0c\u6211\u4eec\u7ee7\u7eed\u8fdb\u884c\u8fd9\u4e2a\u7a0b\u5e8f\u7684\u4e3b\u7c7b\uff0c\u79f0\u4e3aAdvectionProblem\u3002\n\n// \u8fd9\u5bf9\u4f60\u6765\u8bf4\u5e94\u8be5\u662f\u975e\u5e38\u719f\u6089\u7684\u3002\u6709\u8da3\u7684\u7ec6\u8282\u53ea\u6709\u5728\u5b9e\u73b0\u96c6\u5408\u51fd\u6570\u7684\u65f6\u5019\u624d\u4f1a\u51fa\u73b0\u3002\n\n  template <int dim> \n  class AdvectionProblem \n  { \n  public: \n    AdvectionProblem(); \n    void run(); \n\n  private: \n    void setup_system(); \n    void assemble_system(); \n    void solve(); \n    void refine_grid(); \n    void output_results(const unsigned int cycle) const; \n\n    Triangulation<dim>   triangulation; \n    const MappingQ1<dim> mapping; \n\n// \u6b64\u5916\uff0c\u6211\u4eec\u8981\u4f7f\u7528DG\u5143\u7d20\u3002\n\n    const FE_DGQ<dim> fe; \n    DoFHandler<dim>   dof_handler; \n\n    const QGauss<dim>     quadrature; \n    const QGauss<dim - 1> quadrature_face; \n\n// \u63a5\u4e0b\u6765\u7684\u56db\u4e2a\u6210\u5458\u4ee3\u8868\u8981\u89e3\u51b3\u7684\u7ebf\u6027\u7cfb\u7edf\u3002  <code>system_matrix</code> and <code>right_hand_side</code> \u662f\u7531 <code>assemble_system()</code>, the <code>solution</code> \u4ea7\u751f\u7684\uff0c\u5728 <code>solve()</code>. The <code>sparsity_pattern</code> \u4e2d\u8ba1\u7b97\uff0c\u7528\u4e8e\u786e\u5b9a <code>system_matrix</code> \u4e2d\u975e\u96f6\u5143\u7d20\u7684\u4f4d\u7f6e\u3002\n\n    SparsityPattern      sparsity_pattern; \n    SparseMatrix<double> system_matrix; \n\n    Vector<double> solution; \n    Vector<double> right_hand_side; \n  }; \n\n// \u6211\u4eec\u4ece\u6784\u9020\u51fd\u6570\u5f00\u59cb\u3002 <code>fe</code> \u7684\u6784\u9020\u5668\u8c03\u7528\u4e2d\u76841\u662f\u591a\u9879\u5f0f\u7684\u5ea6\u6570\u3002\n\n  template <int dim> \n  AdvectionProblem<dim>::AdvectionProblem() \n    : mapping() \n    , fe(1) \n    , dof_handler(triangulation) \n    , quadrature(fe.tensor_degree() + 1) \n    , quadrature_face(fe.tensor_degree() + 1) \n  {} \n\n  template <int dim> \n  void AdvectionProblem<dim>::setup_system() \n  { \n\n// \u5728\u8bbe\u7f6e\u901a\u5e38\u7684\u6709\u9650\u5143\u6570\u636e\u7ed3\u6784\u7684\u51fd\u6570\u4e2d\uff0c\u6211\u4eec\u9996\u5148\u9700\u8981\u5206\u914dDoF\u3002\n\n    dof_handler.distribute_dofs(fe); \n\n// \u6211\u4eec\u4ece\u751f\u6210\u7a00\u758f\u6a21\u5f0f\u5f00\u59cb\u3002\u4e3a\u6b64\uff0c\u6211\u4eec\u9996\u5148\u7528\u7cfb\u7edf\u4e2d\u51fa\u73b0\u7684\u8026\u5408\u7269\u586b\u5145\u4e00\u4e2a\u52a8\u6001\u7a00\u758f\u6a21\u5f0f\uff08DynamicSparsityPattern\uff09\u7c7b\u578b\u7684\u4e2d\u95f4\u5bf9\u8c61\u3002\u5728\u5efa\u7acb\u6a21\u5f0f\u4e4b\u540e\uff0c\u8fd9\u4e2a\u5bf9\u8c61\u88ab\u590d\u5236\u5230 <code>sparsity_pattern</code> \u5e76\u53ef\u4ee5\u88ab\u4e22\u5f03\u3002\n\n// \u4e3a\u4e86\u5efa\u7acbDG\u79bb\u6563\u7684\u7a00\u758f\u6a21\u5f0f\uff0c\u6211\u4eec\u53ef\u4ee5\u8c03\u7528\u7c7b\u4f3c\u4e8e DoFTools::make_sparsity_pattern, \u7684\u51fd\u6570\uff0c\u8be5\u51fd\u6570\u88ab\u79f0\u4e3a DoFTools::make_flux_sparsity_pattern:  \u3002\n    DynamicSparsityPattern dsp(dof_handler.n_dofs()); \n    DoFTools::make_flux_sparsity_pattern(dof_handler, dsp); \n    sparsity_pattern.copy_from(dsp); \n\n// \u6700\u540e\uff0c\u6211\u4eec\u8bbe\u7f6e\u4e86\u7ebf\u6027\u7cfb\u7edf\u7684\u6240\u6709\u7ec4\u6210\u90e8\u5206\u7684\u7ed3\u6784\u3002\n\n    system_matrix.reinit(sparsity_pattern); \n    solution.reinit(dof_handler.n_dofs()); \n    right_hand_side.reinit(dof_handler.n_dofs()); \n  } \n// @sect4{The assemble_system function}  \n\n// \u8fd9\u91cc\u6211\u4eec\u770b\u5230\u4e86\u4e0e\u624b\u5de5\u7ec4\u88c5\u7684\u4e3b\u8981\u533a\u522b\u3002\u6211\u4eec\u4e0d\u9700\u8981\u5728\u5355\u5143\u683c\u548c\u9762\u4e0a\u5199\u5faa\u73af\uff0c\u800c\u662f\u5728\u8c03\u7528 MeshWorker::mesh_loop() \u65f6\u5305\u542b\u903b\u8f91\uff0c\u6211\u4eec\u53ea\u9700\u8981\u6307\u5b9a\u5728\u6bcf\u4e2a\u5355\u5143\u683c\u3001\u6bcf\u4e2a\u8fb9\u754c\u9762\u548c\u6bcf\u4e2a\u5185\u90e8\u9762\u5e94\u8be5\u53d1\u751f\u4ec0\u4e48\u3002\u8fd9\u4e09\u4e2a\u4efb\u52a1\u662f\u7531\u4e0b\u9762\u7684\u51fd\u6570\u91cc\u9762\u7684lambda\u51fd\u6570\u5904\u7406\u7684\u3002\n\n  template <int dim> \n  void AdvectionProblem<dim>::assemble_system() \n  { \n    using Iterator = typename DoFHandler<dim>::active_cell_iterator; \n    const BoundaryValues<dim> boundary_function; \n\n// \u8fd9\u662f\u5c06\u5bf9\u6bcf\u4e2a\u5355\u5143\u683c\u6267\u884c\u7684\u51fd\u6570\u3002\n\n    const auto cell_worker = [&](const Iterator &  cell, \n                                 ScratchData<dim> &scratch_data, \n                                 CopyData &        copy_data) { \n      const unsigned int n_dofs = \n        scratch_data.fe_values.get_fe().n_dofs_per_cell(); \n      copy_data.reinit(cell, n_dofs); \n      scratch_data.fe_values.reinit(cell); \n\n      const auto &q_points = scratch_data.fe_values.get_quadrature_points(); \n\n      const FEValues<dim> &      fe_v = scratch_data.fe_values; \n      const std::vector<double> &JxW  = fe_v.get_JxW_values(); \n\n// \u6211\u4eec\u89e3\u51b3\u7684\u662f\u4e00\u4e2a\u540c\u8d28\u65b9\u7a0b\uff0c\u56e0\u6b64\u5728\u5355\u5143\u9879\u4e2d\u6ca1\u6709\u663e\u793a\u51fa\u53f3\u624b\u3002 \u5269\u4e0b\u7684\u5c31\u662f\u6574\u5408\u77e9\u9635\u6761\u76ee\u3002\n\n      for (unsigned int point = 0; point < fe_v.n_quadrature_points; ++point) \n        { \n          auto beta_q = beta(q_points[point]); \n          for (unsigned int i = 0; i < n_dofs; ++i) \n            for (unsigned int j = 0; j < n_dofs; ++j) \n              { \n                copy_data.cell_matrix(i, j) += \n                  -beta_q                      // -\\beta \n                  * fe_v.shape_grad(i, point)  // \\nabla \\phi_i \n                  * fe_v.shape_value(j, point) // \\phi_j \n                  * JxW[point];                // dx \n              } \n        } \n    }; \n\n// \u8fd9\u662f\u4e3a\u8fb9\u754c\u9762\u8c03\u7528\u7684\u51fd\u6570\uff0c\u5305\u62ec\u4f7f\u7528FEFaceValues\u7684\u6b63\u5e38\u79ef\u5206\u3002\u65b0\u7684\u903b\u8f91\u662f\u51b3\u5b9a\u8be5\u672f\u8bed\u662f\u8fdb\u5165\u7cfb\u7edf\u77e9\u9635\uff08\u6d41\u51fa\uff09\u8fd8\u662f\u8fdb\u5165\u53f3\u624b\u8fb9\uff08\u6d41\u5165\uff09\u3002\n\n    const auto boundary_worker = [&](const Iterator &    cell, \n                                     const unsigned int &face_no, \n                                     ScratchData<dim> &  scratch_data, \n                                     CopyData &          copy_data) { \n      scratch_data.fe_interface_values.reinit(cell, face_no); \n      const FEFaceValuesBase<dim> &fe_face = \n        scratch_data.fe_interface_values.get_fe_face_values(0); \n\n      const auto &q_points = fe_face.get_quadrature_points(); \n\n      const unsigned int n_facet_dofs = fe_face.get_fe().n_dofs_per_cell(); \n      const std::vector<double> &        JxW     = fe_face.get_JxW_values(); \n      const std::vector<Tensor<1, dim>> &normals = fe_face.get_normal_vectors(); \n\n      std::vector<double> g(q_points.size()); \n      boundary_function.value_list(q_points, g); \n\n      for (unsigned int point = 0; point < q_points.size(); ++point) \n        { \n          const double beta_dot_n = beta(q_points[point]) * normals[point]; \n\n          if (beta_dot_n > 0) \n            { \n              for (unsigned int i = 0; i < n_facet_dofs; ++i) \n                for (unsigned int j = 0; j < n_facet_dofs; ++j) \n                  copy_data.cell_matrix(i, j) += \n                    fe_face.shape_value(i, point)   // \\phi_i \n                    * fe_face.shape_value(j, point) // \\phi_j \n                    * beta_dot_n                    // \\beta . n \n                    * JxW[point];                   // dx \n            } \n          else \n            for (unsigned int i = 0; i < n_facet_dofs; ++i) \n              copy_data.cell_rhs(i) += -fe_face.shape_value(i, point) // \\phi_i \n                                       * g[point]                     // g \n                                       * beta_dot_n  // \\beta . n \n                                       * JxW[point]; // dx \n        } \n    }; \n\n// \u8fd9\u662f\u5728\u5185\u90e8\u9762\u8c03\u7528\u7684\u51fd\u6570\u3002\u53c2\u6570\u6307\u5b9a\u4e86\u5355\u5143\u683c\u3001\u9762\u548c\u5b50\u9762\u7684\u6307\u6570\uff08\u7528\u4e8e\u81ea\u9002\u5e94\u7ec6\u5316\uff09\u3002\u6211\u4eec\u53ea\u662f\u5c06\u5b83\u4eec\u4f20\u9012\u7ed9FEInterfaceValues\u7684reinit()\u51fd\u6570\u3002\n\n    const auto face_worker = [&](const Iterator &    cell, \n                                 const unsigned int &f, \n                                 const unsigned int &sf, \n                                 const Iterator &    ncell, \n                                 const unsigned int &nf, \n                                 const unsigned int &nsf, \n                                 ScratchData<dim> &  scratch_data, \n                                 CopyData &          copy_data) { \n      FEInterfaceValues<dim> &fe_iv = scratch_data.fe_interface_values; \n      fe_iv.reinit(cell, f, sf, ncell, nf, nsf); \n      const auto &q_points = fe_iv.get_quadrature_points(); \n\n      copy_data.face_data.emplace_back(); \n      CopyDataFace &copy_data_face = copy_data.face_data.back(); \n\n      const unsigned int n_dofs        = fe_iv.n_current_interface_dofs(); \n      copy_data_face.joint_dof_indices = fe_iv.get_interface_dof_indices(); \n\n      copy_data_face.cell_matrix.reinit(n_dofs, n_dofs); \n\n      const std::vector<double> &        JxW     = fe_iv.get_JxW_values(); \n      const std::vector<Tensor<1, dim>> &normals = fe_iv.get_normal_vectors(); \n\n      for (unsigned int qpoint = 0; qpoint < q_points.size(); ++qpoint) \n        { \n          const double beta_dot_n = beta(q_points[qpoint]) * normals[qpoint]; \n          for (unsigned int i = 0; i < n_dofs; ++i) \n            for (unsigned int j = 0; j < n_dofs; ++j) \n              copy_data_face.cell_matrix(i, j) +=  \n                fe_iv.jump(i, qpoint) // [\\phi_i] \n                * \n                fe_iv.shape_value((beta_dot_n > 0), j, qpoint) // phi_j^{upwind} \n                * beta_dot_n                                   // (\\beta . n) \n                * JxW[qpoint];                                 // dx \n        }  \n    }; \n\n// \u4e0b\u9762\u7684lambda\u51fd\u6570\u5c06\u5904\u7406\u4ece\u5355\u5143\u683c\u548c\u9762\u7ec4\u4ef6\u4e2d\u590d\u5236\u6570\u636e\u5230\u5168\u5c40\u77e9\u9635\u548c\u53f3\u4fa7\u7684\u95ee\u9898\u3002\n\n// \u867d\u7136\u6211\u4eec\u4e0d\u9700\u8981AffineConstraints\u5bf9\u8c61\uff0c\u56e0\u4e3a\u5728DG\u79bb\u6563\u4e2d\u6ca1\u6709\u60ac\u7a7a\u8282\u70b9\u7ea6\u675f\uff0c\u4f46\u6211\u4eec\u5728\u8fd9\u91cc\u4f7f\u7528\u4e00\u4e2a\u7a7a\u5bf9\u8c61\uff0c\u56e0\u4e3a\u8fd9\u5141\u8bb8\u6211\u4eec\u4f7f\u7528\u5176`copy_local_to_global`\u529f\u80fd\u3002\n\n    const AffineConstraints<double> constraints; \n\n    const auto copier = [&](const CopyData &c) { \n      constraints.distribute_local_to_global(c.cell_matrix, \n                                             c.cell_rhs, \n                                             c.local_dof_indices, \n                                             system_matrix, \n                                             right_hand_side); \n\n      for (auto &cdf : c.face_data) \n        { \n          constraints.distribute_local_to_global(cdf.cell_matrix, \n                                                 cdf.joint_dof_indices, \n                                                 system_matrix); \n        } \n    }; \n\n    ScratchData<dim> scratch_data(mapping, fe, quadrature, quadrature_face); \n    CopyData         copy_data; \n\n// \u5728\u8fd9\u91cc\uff0c\u6211\u4eec\u6700\u7ec8\u5904\u7406\u4e86\u88c5\u914d\u95ee\u9898\u3002\u6211\u4eec\u4f20\u5165ScratchData\u548cCopyData\u5bf9\u8c61\uff0c\u4ee5\u53ca\u4e0a\u9762\u7684lambda\u51fd\u6570\uff0c\u5e76\u6307\u5b9a\u6211\u4eec\u8981\u5bf9\u5185\u90e8\u9762\u8fdb\u884c\u4e00\u6b21\u88c5\u914d\u3002\n\n    MeshWorker::mesh_loop(dof_handler.begin_active(), \n                          dof_handler.end(), \n                          cell_worker, \n                          copier, \n                          scratch_data, \n                          copy_data, \n                          MeshWorker::assemble_own_cells | \n                            MeshWorker::assemble_boundary_faces | \n                            MeshWorker::assemble_own_interior_faces_once, \n                          boundary_worker, \n                          face_worker); \n  } \n// @sect3{All the rest}  \n\n// \u5bf9\u4e8e\u8fd9\u4e2a\u7b80\u5355\u7684\u95ee\u9898\uff0c\u6211\u4eec\u4f7f\u7528\u4e86\u6700\u7b80\u5355\u7684\u6c42\u89e3\u5668\uff0c\u79f0\u4e3aRichardson\u8fed\u4ee3\uff0c\u5b83\u4ee3\u8868\u4e86\u7b80\u5355\u7684\u7f3a\u9677\u4fee\u6b63\u3002\u8fd9\u4e0e\u4e00\u4e2a\u5757\u72b6SSOR\u9884\u5904\u7406\u76f8\u7ed3\u5408\uff0c\u8be5\u9884\u5904\u7406\u4f7f\u7528DG\u79bb\u6563\u5316\u4ea7\u751f\u7684\u7cfb\u7edf\u77e9\u9635\u7684\u7279\u6b8a\u5757\u72b6\u7ed3\u6784\u3002\u8fd9\u4e9b\u5757\u7684\u5927\u5c0f\u662f\u6bcf\u4e2a\u5355\u5143\u7684DoF\u6570\u91cf\u3002\u8fd9\u91cc\uff0c\u6211\u4eec\u4f7f\u7528SSOR\u9884\u5904\u7406\uff0c\u56e0\u4e3a\u6211\u4eec\u6ca1\u6709\u6839\u636e\u6d41\u573a\u5bf9DoFs\u8fdb\u884c\u91cd\u65b0\u7f16\u53f7\u3002\u5982\u679c\u5728\u6d41\u7684\u4e0b\u6e38\u65b9\u5411\u5bf9DoFs\u8fdb\u884c\u91cd\u65b0\u7f16\u53f7\uff0c\u90a3\u4e48\u5757\u72b6\u7684Gauss-Seidel\u9884\u5904\u7406\uff08\u89c1PreconditionBlockSOR\u7c7b\uff0c\u653e\u677e=1\uff09\u4f1a\u505a\u5f97\u66f4\u597d\u3002\n\n  template <int dim> \n  void AdvectionProblem<dim>::solve() \n  { \n    SolverControl                    solver_control(1000, 1e-12); \n    SolverRichardson<Vector<double>> solver(solver_control); \n\n// \u8fd9\u91cc\u6211\u4eec\u521b\u5efa\u4e86\u9884\u5904\u7406\u7a0b\u5e8f\u3002\n\n    PreconditionBlockSSOR<SparseMatrix<double>> preconditioner; \n\n// \u7136\u540e\u5c06\u77e9\u9635\u5206\u914d\u7ed9\u5b83\uff0c\u5e76\u8bbe\u7f6e\u6b63\u786e\u7684\u5757\u5927\u5c0f\u3002\n\n    preconditioner.initialize(system_matrix, fe.n_dofs_per_cell()); \n\n// \u505a\u5b8c\u8fd9\u4e9b\u51c6\u5907\u5de5\u4f5c\u540e\uff0c\u6211\u4eec\u5c31\u53ef\u4ee5\u542f\u52a8\u7ebf\u6027\u6c42\u89e3\u5668\u4e86\u3002\n\n    solver.solve(system_matrix, solution, right_hand_side, preconditioner); \n\n    std::cout << \"  Solver converged in \" << solver_control.last_step() \n              << \" iterations.\" << std::endl; \n  } \n\n// \u6211\u4eec\u6839\u636e\u4e00\u4e2a\u975e\u5e38\u7b80\u5355\u7684\u7ec6\u5316\u6807\u51c6\u6765\u7ec6\u5316\u7f51\u683c\uff0c\u5373\u5bf9\u89e3\u7684\u68af\u5ea6\u7684\u8fd1\u4f3c\u3002\u7531\u4e8e\u8fd9\u91cc\u6211\u4eec\u8003\u8651\u7684\u662fDG(1)\u65b9\u6cd5\uff08\u5373\u6211\u4eec\u4f7f\u7528\u7247\u72b6\u53cc\u7ebf\u6027\u5f62\u72b6\u51fd\u6570\uff09\uff0c\u6211\u4eec\u53ef\u4ee5\u7b80\u5355\u5730\u8ba1\u7b97\u6bcf\u4e2a\u5355\u5143\u7684\u68af\u5ea6\u3002\u4f46\u662f\u6211\u4eec\u5e76\u4e0d\u5e0c\u671b\u6211\u4eec\u7684\u7ec6\u5316\u6307\u6807\u53ea\u5efa\u7acb\u5728\u6bcf\u4e2a\u5355\u5143\u7684\u68af\u5ea6\u4e0a\uff0c\u800c\u662f\u5e0c\u671b\u540c\u65f6\u5efa\u7acb\u5728\u76f8\u90bb\u5355\u5143\u4e4b\u95f4\u7684\u4e0d\u8fde\u7eed\u89e3\u51fd\u6570\u7684\u8df3\u8dc3\u4e0a\u3002\u6700\u7b80\u5355\u7684\u65b9\u6cd5\u662f\u901a\u8fc7\u5dee\u5206\u5546\u8ba1\u7b97\u8fd1\u4f3c\u68af\u5ea6\uff0c\u5305\u62ec\u8003\u8651\u4e2d\u7684\u5355\u5143\u548c\u5176\u76f8\u90bb\u7684\u5355\u5143\u3002\u8fd9\u662f\u7531 <code>DerivativeApproximation</code> \u7c7b\u5b8c\u6210\u7684\uff0c\u5b83\u8ba1\u7b97\u8fd1\u4f3c\u68af\u5ea6\u7684\u65b9\u5f0f\u7c7b\u4f3c\u4e8e\u672c\u6559\u7a0b step-9 \u4e2d\u63cf\u8ff0\u7684 <code>GradientEstimation</code> \u3002\u4e8b\u5b9e\u4e0a\uff0c <code>DerivativeApproximation</code> \u7c7b\u662f\u5728 step-9 \u7684 <code>GradientEstimation</code> \u7c7b\u4e4b\u540e\u5f00\u53d1\u7684\u3002\u4e0e  step-9  \u4e2d\u7684\u8ba8\u8bba\u76f8\u5173\uff0c\u8fd9\u91cc\u6211\u4eec\u8003\u8651  $h^{1+d/2}|\\nabla_h u_h|$  \u3002\u6b64\u5916\uff0c\u6211\u4eec\u6ce8\u610f\u5230\uff0c\u6211\u4eec\u4e0d\u8003\u8651\u8fd1\u4f3c\u7684\u4e8c\u6b21\u5bfc\u6570\uff0c\u56e0\u4e3a\u7ebf\u6027\u5e73\u6d41\u65b9\u7a0b\u7684\u89e3\u4e00\u822c\u4e0d\u5728 $H^2$ \u4e2d\uff0c\u800c\u53ea\u5728 $H^1$ \u4e2d\uff08\u6216\u8005\uff0c\u66f4\u51c6\u786e\u5730\u8bf4\uff1a\u5728 $H^1_\\beta$ \u4e2d\uff0c\u5373\u5728\u65b9\u5411 $\\beta$ \u4e0a\u7684\u5bfc\u6570\u662f\u53ef\u5e73\u65b9\u6574\u9664\u7684\u51fd\u6570\u7a7a\u95f4\uff09\u3002\n\n  template <int dim> \n  void AdvectionProblem<dim>::refine_grid() \n  { \n\n//  <code>DerivativeApproximation</code> \u7c7b\u5c06\u68af\u5ea6\u8ba1\u7b97\u4e3a\u6d6e\u70b9\u7cbe\u5ea6\u3002\u8fd9\u5df2\u7ecf\u8db3\u591f\u4e86\uff0c\u56e0\u4e3a\u5b83\u4eec\u662f\u8fd1\u4f3c\u7684\uff0c\u53ea\u4f5c\u4e3a\u7ec6\u5316\u6307\u6807\u3002\n\n    Vector<float> gradient_indicator(triangulation.n_active_cells()); \n\n// \u73b0\u5728\uff0c\u8fd1\u4f3c\u68af\u5ea6\u88ab\u8ba1\u7b97\u51fa\u6765\u4e86\n\n    DerivativeApproximation::approximate_gradient(mapping, \n                                                  dof_handler, \n                                                  solution, \n                                                  gradient_indicator); \n\n//\u5e76\u4e14\u5b83\u4eec\u7684\u5355\u5143\u683c\u6309\u7cfb\u6570 $h^{1+d/2}$ \u8fdb\u884c\u7f29\u653e\u3002\n    unsigned int cell_no = 0; \n    for (const auto &cell : dof_handler.active_cell_iterators()) \n      gradient_indicator(cell_no++) *= \n        std::pow(cell->diameter(), 1 + 1.0 * dim / 2); \n\n// \u6700\u540e\u5b83\u4eec\u4f5c\u4e3a\u7ec6\u5316\u6307\u6807\u3002\n\n    GridRefinement::refine_and_coarsen_fixed_number(triangulation, \n                                                    gradient_indicator, \n                                                    0.3, \n                                                    0.1); \n\n    triangulation.execute_coarsening_and_refinement(); \n  } \n\n// \u8fd9\u4e2a\u7a0b\u5e8f\u7684\u8f93\u51fa\u5305\u62ec\u4e00\u4e2a\u81ea\u9002\u5e94\u7ec6\u5316\u7f51\u683c\u7684vtk\u6587\u4ef6\u548c\u6570\u503c\u89e3\u3002\u6700\u540e\uff0c\u6211\u4eec\u8fd8\u7528 VectorTools::integrate_difference(). \u8ba1\u7b97\u4e86\u89e3\u7684L-\u65e0\u7a77\u5927\u89c4\u8303\u3002\n  template <int dim> \n  void AdvectionProblem<dim>::output_results(const unsigned int cycle) const \n  { \n    const std::string filename = \"solution-\" + std::to_string(cycle) + \".vtk\"; \n    std::cout << \"  Writing solution to <\" << filename << \">\" << std::endl; \n    std::ofstream output(filename); \n\n    DataOut<dim> data_out; \n    data_out.attach_dof_handler(dof_handler);  \n    data_out.add_data_vector(solution, \"u\", DataOut<dim>::type_dof_data); \n\n    data_out.build_patches(mapping); \n\n    data_out.write_vtk(output); \n\n    { \n      Vector<float> values(triangulation.n_active_cells()); \n      VectorTools::integrate_difference(mapping, \n                                        dof_handler, \n                                        solution, \n                                        Functions::ZeroFunction<dim>(), \n                                        values, \n                                        quadrature, \n                                        VectorTools::Linfty_norm); \n      const double l_infty = \n        VectorTools::compute_global_error(triangulation, \n                                          values,  \n                                          VectorTools::Linfty_norm); \n      std::cout << \"  L-infinity norm: \" << l_infty << std::endl; \n    } \n  } \n\n// \u4e0b\u9762\u7684 <code>run</code> \u51fd\u6570\u4e0e\u524d\u9762\u7684\u4f8b\u5b50\u7c7b\u4f3c\u3002\n\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); \n            triangulation.refine_global(3); \n          } \n        else \n          refine_grid(); \n\n        std::cout << \"  Number of active cells:       \" \n                  << triangulation.n_active_cells() << std::endl; \n\n        setup_system(); \n\n        std::cout << \"  Number of degrees of freedom: \" << dof_handler.n_dofs() \n                  << std::endl; \n\n        assemble_system(); \n        solve(); \n\n        output_results(cycle); \n      } \n  } \n} // namespace Step12 \n\n// \u4e0b\u9762\u7684 <code>main</code> \u51fd\u6570\u4e0e\u524d\u9762\u7684\u4f8b\u5b50\u4e5f\u7c7b\u4f3c\uff0c\u4e0d\u9700\u8981\u6ce8\u91ca\u3002\n\nint main() \n{ \n  try \n    { \n      Step12::AdvectionProblem<2> dgmethod; \n      dgmethod.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      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": "b39a90fb038ac1fd043d9df16b8dd397f3da7260", "size": 21127, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-12/step-12.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-12/step-12.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-12/step-12.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": 36.3006872852, "max_line_length": 543, "alphanum_fraction": 0.5675675676, "num_tokens": 6538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419704455589, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.45847556039236803}}
{"text": "/*\n * Copyright (C) 2019  Rhys Mainwaring\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 <cmath>\n#include <iostream>\n#include <string>\n\n#include <Eigen/Dense>\n#include <ignition/common/Console.hh>\n#include <ignition/math/Pose3.hh>\n#include <ignition/math/Vector2.hh>\n#include <ignition/math/Vector3.hh>\n\n#include \"Wavefield.hh\"\n\nusing namespace ignition;\nusing namespace gazebo;\n\n///////////////////////////////////////////////////////////////////////////////\n// Utilities\nstd::ostream& operator<<(std::ostream &_os, const std::vector<double> &_vec)\n{\n  for (auto&& v : _vec ) // NOLINT\n    _os << v << \", \";\n  return _os;\n}\n\n///////////////////////////////////////////////////////////////////////////////\n/// \\brief Private data for the WavefieldParameters.\nclass ignition::gazebo::WavefieldPrivate\n{\n  /// \\brief Constructor.\n  public: WavefieldPrivate():\n    size({1000, 1000}),\n    cellCount({50, 50}),\n    model(\"PMS\"),\n    number(1),\n    scale(2),\n    angle(2.0*M_PI/10.0),\n    steepness(1.0),\n    amplitude(0.0),\n    period(1.0),\n    phase(0.0),\n    direction(1, 0),\n    angularFrequency(2.0*M_PI),\n    wavelength(2 * M_PI / this->DeepWaterDispersionToWavenumber(2.0 * M_PI)),\n    wavenumber(this->DeepWaterDispersionToWavenumber(2.0 * M_PI)),\n    tau(1.0),\n    gain(1.0)\n  {\n  }\n\n  /// \\brief The size of the wavefield.\n  public: ignition::math::Vector2d size;\n\n  /// \\brief The number of grid cells in the wavefield.\n  public: ignition::math::Vector2d cellCount;\n\n  /// \\brief Name of wavefield model to use - must be \"PMS\" or \"CWR\"\n  public: std::string model;\n\n  /// \\brief The number of component waves.\n  public: size_t number;\n\n  /// \\brief Set the scale of the largest and smallest waves.\n  public: double scale;\n\n  /// \\brief Set the angle between component waves and the mean direction.\n  public: double angle;\n\n  /// \\brief Control the wave steepness. 0 is sine waves, 1 is Gerstner waves.\n  public: double steepness;\n\n  /// \\brief The mean wave amplitude [m].\n  public: double amplitude;\n\n  /// \\brief The mean wave period [s]\n  public: double period;\n\n  /// \\brief The mean wave phase (not currently enabled).\n  public: double phase;\n\n  /// \\brief The mean wave direction.\n  public: ignition::math::Vector2d direction;\n\n  /// \\brief The time constant for exponential increasing waves on startup\n  public: double tau;\n\n  /// \\brief The multiplier applied to PM spectra\n  public: double gain;\n\n  /// \\brief The mean wave angular frequency (derived).\n  public: double angularFrequency;\n\n  /// \\brief The mean wavelength (derived).\n  public: double wavelength;\n\n  /// \\brief The mean wavenumber (derived).\n  public: double wavenumber;\n\n  /// \\brief The component wave angular frequencies (derived).\n  public: std::vector<double> angularFrequencies;\n\n  /// \\brief The component wave amplitudes (derived).\n  public: std::vector<double> amplitudes;\n\n  /// \\brief The component wave phases (derived).\n  public: std::vector<double> phases;\n\n  /// \\brief The component wave steepness factors (derived).\n  public: std::vector<double> steepnesses;\n\n  /// \\brief The component wavenumbers (derived).\n  public: std::vector<double> wavenumbers;\n\n  /// \\brief The component wave dirctions (derived).\n  public: std::vector<ignition::math::Vector2d> directions;\n\n  /// \\brief Recalculate for constant wavelength-amplitude ratio\n  public: void RecalculateCwr()\n  {\n    // Normalize direction\n    this->direction.Normalize();\n\n    // Derived mean values\n    this->angularFrequency = 2.0 * M_PI / this->period;\n    this->wavenumber = \\\n      this->DeepWaterDispersionToWavenumber(this->angularFrequency);\n    this->wavelength = 2.0 * M_PI / this->wavenumber;\n\n    // Update components\n    this->angularFrequencies.clear();\n    this->amplitudes.clear();\n    this->phases.clear();\n    this->wavenumbers.clear();\n    this->steepnesses.clear();\n    this->directions.clear();\n\n    for (size_t i = 0; i < this->number; ++i)\n    {\n      const int n = i - this->number / 2;\n      const double scaleFactor = std::pow(this->scale, n);\n      const double a = scaleFactor * this->amplitude;\n      const double k = this->wavenumber / scaleFactor;\n      const double omega = this->DeepWaterDispersionToOmega(k);\n      const double phi = this->phase;\n      double q = 0.0;\n      if (!ignition::math::equal(a, 0.0))\n      {\n        q = std::min(1.0, this->steepness / (a * k * this->number));\n      }\n\n      this->amplitudes.push_back(a);\n      this->angularFrequencies.push_back(omega);\n      this->phases.push_back(phi);\n      this->steepnesses.push_back(q);\n      this->wavenumbers.push_back(k);\n\n      // Direction\n      const double c = std::cos(n * this->angle);\n      const double s = std::sin(n * this->angle);\n\n      const ignition::math::Vector2d d(\n        c * this->direction.X() - s * this->direction.Y(),\n        s * this->direction.X() + c * this->direction.Y());\n      directions.push_back(d);\n    }\n  }\n\n  // \\brief Pierson-Moskowitz wave spectrum\n  public: double pm(double _omega, double _omegaP)\n  {\n    double alpha = 0.0081;\n    double g = 9.81;\n    return alpha * std::pow(g, 2.0) / std::pow(_omega, 5.0) * \\\n      std::exp(-(5.0 / 4.0) * std::pow(_omegaP / _omega, 4.0));\n  }\n\n  /// \\brief Recalculate for Pierson-Moskowitz spectrum sampling model\n  public: void RecalculatePms()\n  {\n    // Normalize direction\n    this->direction.Normalize();\n\n    // Derived mean values\n    this->angularFrequency = 2.0 * M_PI / this->period;\n    this->wavenumber = \\\n      this->DeepWaterDispersionToWavenumber(this->angularFrequency);\n    this->wavelength = 2.0 * M_PI / this->wavenumber;\n\n    // Update components\n    this->angularFrequencies.clear();\n    this->amplitudes.clear();\n    this->phases.clear();\n    this->wavenumbers.clear();\n    this->steepnesses.clear();\n    this->directions.clear();\n\n    // Vector for spaceing\n    std::vector<double> omegaSpacing;\n    omegaSpacing.push_back(this->angularFrequency * (1.0 - 1.0 / this->scale));\n    omegaSpacing.push_back(this->angularFrequency * \\\n                            (this->scale - 1.0 / this->scale) / 2.0);\n    omegaSpacing.push_back(this->angularFrequency * (this->scale - 1.0));\n\n    for (size_t i = 0; i < this->number; ++i)\n    {\n      const int n = i - 1;\n      const double scaleFactor = std::pow(this->scale, n);\n      const double omega = this->angularFrequency * scaleFactor;\n      const double pms = pm(omega, this->angularFrequency);\n      const double a = this->gain * std::sqrt(2.0 * pms * omegaSpacing[i]);\n      const double k = this->DeepWaterDispersionToWavenumber(omega);\n      const double phi = this->phase;\n      double q = 0.0;\n      if (!ignition::math::equal(a, 0.0))\n      {\n        q = std::min(1.0, this->steepness / (a * k * this->number));\n      }\n\n      this->amplitudes.push_back(a);\n      this->angularFrequencies.push_back(omega);\n      this->phases.push_back(phi);\n      this->steepnesses.push_back(q);\n      this->wavenumbers.push_back(k);\n\n      // Direction\n      const double c = std::cos(n * this->angle);\n      const double s = std::sin(n * this->angle);\n\n      const ignition::math::Vector2d d(\n        c * this->direction.X() - s * this->direction.Y(),\n        s * this->direction.X() + c * this->direction.Y());\n      directions.push_back(d);\n    }\n  }\n\n  /// \\brief Recalculate all derived quantities from inputs.\n  public: void Recalculate()\n  {\n    if (!this->model.compare(\"PMS\"))\n    {\n      ignmsg << \"Using Pierson-Moskowitz spectrum sampling wavefield model \"\n            << std::endl;\n      this->RecalculatePms();\n    }\n    else if (!this->model.compare(\"CWR\"))\n    {\n      ignmsg << \"Using Constant wavelength-ampltude ratio wavefield model \"\n            << std::endl;\n      this->RecalculateCwr();\n    }\n    else\n    {\n      ignwarn<< \"Wavefield model specified as <\" << this->model\n            << \"> which is not one of the two supported wavefield models: \"\n            << \"PMS or CWR!!!\" << std::endl;\n    }\n  }\n\n  /////////////////////////////////////////////////\n  private: double DeepWaterDispersionToOmega(double _wavenumber)\n  {\n    const double g = std::fabs(-9.8);\n    return std::sqrt(g * _wavenumber);\n  }\n\n  /////////////////////////////////////////////////\n  private: double DeepWaterDispersionToWavenumber(double _omega)\n  {\n    const double g = std::fabs(-9.8);\n    return _omega * _omega / g;\n  }\n};\n\n/////////////////////////////////////////////////////////////////////////////\nWavefield::Wavefield()\n  : data(std::make_unique<WavefieldPrivate>())\n{\n  this->data->Recalculate();\n}\n\n///////////////////////////////////////////////////////////////////////////////\nWavefield::~Wavefield()\n{\n}\n\n///////////////////////////////////////////////////////////////////////////////\nvoid Wavefield::Load(const std::shared_ptr<const sdf::Element> &_sdf)\n{\n  if (!_sdf->HasElement(\"wavefield\"))\n    return;\n\n  auto ptr = const_cast<sdf::Element *>(_sdf.get());\n  auto sdfWavefield = ptr->GetElement(\"wavefield\");\n\n  this->data->size = sdfWavefield->Get<ignition::math::Vector2d>(\"size\",\n    this->data->size).first;\n  this->data->cellCount = sdfWavefield->Get<ignition::math::Vector2d>(\"cell_count\",\n    this->data->cellCount).first;\n  if (sdfWavefield->HasElement(\"wave\"))\n  {\n    auto sdfWave = sdfWavefield->GetElement(\"wave\");\n\n    this->data->model = sdfWave->Get<std::string>(\"model\", \"PMS\").first;\n    this->data->number =\n      sdfWave->Get<double>(\"number\", this->data->number).first;\n    this->data->amplitude =\n      sdfWave->Get<double>(\"amplitude\", this->data->amplitude).first;\n    this->data->period =\n      sdfWave->Get<double>(\"period\", this->data->period).first;\n    this->data->phase = sdfWave->Get<double>(\"phase\", this->data->phase).first;\n    this->data->direction =\n      sdfWave->Get<ignition::math::Vector2d>(\"direction\",\n        this->data->direction).first;\n    this->data->scale = sdfWave->Get<double>(\"scale\", this->data->scale).first;\n    this->data->angle = sdfWave->Get<double>(\"angle\", this->data->angle).first;\n    this->data->steepness =\n      sdfWave->Get<double>(\"steepness\", this->data->steepness).first;\n    this->data->tau = sdfWave->Get<double>(\"tau\", this->data->tau).first;\n    this->data->gain = sdfWave->Get<double>(\"gain\", this->data->gain).first;\n\n    this->data->Recalculate();\n  }\n  this->DebugPrint();\n}\n\n///////////////////////////////////////////////////////////////////////////////\nsize_t Wavefield::Number() const\n{\n  return this->data->number;\n}\n\n///////////////////////////////////////////////////////////////////////////////\ndouble Wavefield::Angle() const\n{\n  return this->data->angle;\n}\n\n///////////////////////////////////////////////////////////////////////////////\ndouble Wavefield::Scale() const\n{\n  return this->data->scale;\n}\n\n///////////////////////////////////////////////////////////////////////////////\ndouble Wavefield::Steepness() const\n{\n  return this->data->steepness;\n}\n\n///////////////////////////////////////////////////////////////////////////////\ndouble Wavefield::AngularFrequency() const\n{\n  return this->data->angularFrequency;\n}\n\n///////////////////////////////////////////////////////////////////////////////\ndouble Wavefield::Amplitude() const\n{\n  return this->data->amplitude;\n}\n\n///////////////////////////////////////////////////////////////////////////////\ndouble Wavefield::Period() const\n{\n  return this->data->period;\n}\n\n///////////////////////////////////////////////////////////////////////////////\ndouble Wavefield::Phase() const\n{\n  return this->data->phase;\n}\n\n///////////////////////////////////////////////////////////////////////////////\ndouble Wavefield::Wavelength() const\n{\n  return this->data->wavelength;\n}\n\n///////////////////////////////////////////////////////////////////////////////\ndouble Wavefield::Wavenumber() const\n{\n  return this->data->wavenumber;\n}\n\n///////////////////////////////////////////////////////////////////////////////\nfloat Wavefield::Tau() const\n{\n  return this->data->tau;\n}\n\n///////////////////////////////////////////////////////////////////////////////\nfloat Wavefield::Gain() const\n{\n  return this->data->gain;\n}\n\n///////////////////////////////////////////////////////////////////////////////\nignition::math::Vector2d Wavefield::Direction() const\n{\n  return this->data->direction;\n}\n\n///////////////////////////////////////////////////////////////////////////////\nvoid Wavefield::SetNumber(size_t _number)\n{\n  this->data->number = _number;\n  this->data->Recalculate();\n}\n\n///////////////////////////////////////////////////////////////////////////////\nvoid Wavefield::SetAngle(double _angle)\n{\n  this->data->angle = _angle;\n  this->data->Recalculate();\n}\n\n///////////////////////////////////////////////////////////////////////////////\nvoid Wavefield::SetScale(double _scale)\n{\n  this->data->scale = _scale;\n  this->data->Recalculate();\n}\n\n///////////////////////////////////////////////////////////////////////////////\nvoid Wavefield::SetSteepness(double _steepness)\n{\n  this->data->steepness = _steepness;\n  this->data->Recalculate();\n}\n\n///////////////////////////////////////////////////////////////////////////////\nvoid Wavefield::SetAmplitude(double _amplitude)\n{\n  this->data->amplitude = _amplitude;\n  this->data->Recalculate();\n}\n\n///////////////////////////////////////////////////////////////////////////////\nvoid Wavefield::SetPeriod(double _period)\n{\n  this->data->period = _period;\n  this->data->Recalculate();\n}\n\n///////////////////////////////////////////////////////////////////////////////\nvoid Wavefield::SetPhase(double _phase)\n{\n  this->data->phase = _phase;\n  this->data->Recalculate();\n}\n\n///////////////////////////////////////////////////////////////////////////////\nvoid Wavefield::SetTau(double _tau)\n{\n  this->data->tau = _tau;\n}\n\n///////////////////////////////////////////////////////////////////////////////\nvoid Wavefield::SetGain(double _gain)\n{\n  this->data->gain = _gain;\n}\n\n///////////////////////////////////////////////////////////////////////////////\nvoid Wavefield::SetDirection(const ignition::math::Vector2d &_direction)\n{\n  this->data->direction = _direction;\n  this->data->Recalculate();\n}\n\n///////////////////////////////////////////////////////////////////////////////\nconst std::vector<double> &Wavefield::AngularFrequency_V() const\n{\n  return this->data->angularFrequencies;\n}\n\n///////////////////////////////////////////////////////////////////////////////\nconst std::vector<double> &Wavefield::Amplitude_V() const\n{\n  return this->data->amplitudes;\n}\n\n///////////////////////////////////////////////////////////////////////////////\nconst std::vector<double> &Wavefield::Phase_V() const\n{\n  return this->data->phases;\n}\n\n///////////////////////////////////////////////////////////////////////////////\nconst std::vector<double> &Wavefield::Steepness_V() const\n{\n  return this->data->steepnesses;\n}\n\n///////////////////////////////////////////////////////////////////////////////\nconst std::vector<double> &Wavefield::Wavenumber_V() const\n{\n  return this->data->wavenumbers;\n}\n\n///////////////////////////////////////////////////////////////////////////////\nconst std::vector<ignition::math::Vector2d> &Wavefield::Direction_V() const\n{\n  return this->data->directions;\n}\n\n///////////////////////////////////////////////////////////////////////////////\nvoid Wavefield::DebugPrint() const\n{\n  ignmsg << \"Input Parameters:\" << std::endl;\n  ignmsg << \"model:     \" << this->data->model << std::endl;\n  ignmsg << \"number:     \" << this->data->number << std::endl;\n  ignmsg << \"scale:      \" << this->data->scale << std::endl;\n  ignmsg << \"angle:      \" << this->data->angle << std::endl;\n  ignmsg << \"steepness:  \" << this->data->steepness << std::endl;\n  ignmsg << \"amplitude:  \" << this->data->amplitude << std::endl;\n  ignmsg << \"period:     \" << this->data->period << std::endl;\n  ignmsg << \"direction:  \" << this->data->direction << std::endl;\n  ignmsg << \"tau:  \" << this->data->tau << std::endl;\n  ignmsg << \"gain:  \" << this->data->gain << std::endl;\n  ignmsg << \"Derived Parameters:\" << std::endl;\n  ignmsg << \"amplitudes:  \" << this->data->amplitudes << std::endl;\n  ignmsg << \"wavenumbers: \" << this->data->wavenumbers << std::endl;\n  ignmsg << \"omegas:      \" << this->data->angularFrequencies << std::endl;\n  ignmsg << \"periods:     \";\n  for (auto&& omega : this->data->angularFrequencies) // NOLINT\n  {\n    ignmsg << 2.0 * M_PI / omega <<\", \";\n  }\n  ignmsg << std::endl;\n  ignmsg << \"phases:      \" << this->data->phases << std::endl;\n  ignmsg << \"steepnesses: \" << this->data->steepnesses << std::endl;\n  ignmsg << \"directions:  \";\n  for (auto&& d : this->data->directions) // NOLINT\n  {\n    ignmsg << d << \"; \";\n  }\n  ignmsg << std::endl;\n}\n\n///////////////////////////////////////////////////////////////////////////////\ndouble Wavefield::ComputeDepthSimply(const ignition::math::Vector3d &_point,\n  double _time, double _timeInit)\n{\n  double h = 0.0;\n  for (std::size_t i = 0; i < this->Number(); ++i)\n  {\n    double k = this->Wavenumber_V()[i];\n    double a = this->Amplitude_V()[i];\n    double dx =  this->Direction_V()[i].X();\n    double dy =  this->Direction_V()[i].Y();\n    double dot = _point.X() * dx + _point.Y() * dy;\n    double omega = this->AngularFrequency_V()[i];\n    double theta = k * dot - omega * _time;\n    double c = cos(theta);\n    h += a*c;\n  }\n\n  // Exponentially grow the waves\n  return h * (1 - exp(-1.0 * (_time - _timeInit) / this->Tau()));\n}\n\n///////////////////////////////////////////////////////////////////////////////\ndouble Wavefield::ComputeDepthDirectly(const ignition::math::Vector3d &_point,\n  double _time, double _timeInit)\n{\n  // Struture for passing wave parameters to lambdas\n  struct WaveParams\n  {\n    WaveParams(\n      const std::vector<double>& _a,\n      const std::vector<double>& _k,\n      const std::vector<double>& _omega,\n      const std::vector<double>& _phi,\n      const std::vector<double>& _q,\n      const std::vector<ignition::math::Vector2d>& _dir) :\n      a(_a), k(_k), omega(_omega), phi(_phi), q(_q), dir(_dir) {}\n\n    const std::vector<double>& a;\n    const std::vector<double>& k;\n    const std::vector<double>& omega;\n    const std::vector<double>& phi;\n    const std::vector<double>& q;\n    const std::vector<ignition::math::Vector2d>& dir;\n  };\n\n  // Compute the target function and Jacobian. Also calculate pz,\n  // the z-component of the Gerstner wave, which we essentially get for free.\n  // cppcheck-suppress constParameter\n  auto wave_fdf = [=](auto x, auto p, auto t, auto &wp, auto &F, auto &J)\n  {\n    double pz = 0;\n    F(0) = p.x() - x.x();\n    F(1) = p.y() - x.y();\n    J(0, 0) = -1;\n    J(0, 1) =  0;\n    J(1, 0) =  0;\n    J(1, 1) = -1;\n    const size_t n = wp.a.size();\n    for (auto&& i = 0; i < n; ++i) // NOLINT\n    {\n      const double dx = wp.dir[i].X();\n      const double dy = wp.dir[i].Y();\n      const double q = wp.q[i];\n      const double a = wp.a[i];\n      const double k = wp.k[i];\n      const double dot = x.x() * dx + x.y() * dy;\n      const double theta = k * dot - wp.omega[i] * t;\n      const double s = std::sin(theta);\n      const double c = std::cos(theta);\n      const double qakc = q * a * k * c;\n      const double df1x = qakc * dx * dx;\n      const double df1y = qakc * dx * dy;\n      const double df2x = df1y;\n      const double df2y = qakc * dy * dy;\n      pz += a * c;\n      F(0) += a * dx * s;\n      F(1) += a * dy * s;\n      J(0, 0) += df1x;\n      J(0, 1) += df1y;\n      J(1, 0) += df2x;\n      J(1, 1) += df2y;\n    }\n    // Exponentially grow the waves\n    return pz * (1 - exp(-1.0 * (_time - _timeInit) / this->Tau()));\n  };\n\n  // Simple multi-variate Newton solver -\n  // this version returns the z-component of the\n  // wave field at the desired point p.\n  // cppcheck-suppress constParameter\n  auto solver = [=](auto& fdfunc, auto x0, auto p, auto t, \\\n                    auto& wp, auto tol, auto nmax)\n  {\n    int n = 0;\n    double err = 1;\n    double pz = 0;\n    auto xn = x0;\n    Eigen::Vector2d F;\n    Eigen::Matrix2d J;\n    while (std::abs(err) > tol && n < nmax)\n    {\n      pz = fdfunc(x0, p, t, wp, F, J);\n      xn = x0 - J.inverse() * F;\n      x0 = xn;\n      err = F.norm();\n      n++;\n    }\n    return pz;\n  };\n\n  // Set up parameter references\n  WaveParams wp(\n    this->Amplitude_V(),\n    this->Wavenumber_V(),\n    this->AngularFrequency_V(),\n    this->Phase_V(),\n    this->Steepness_V(),\n    this->Direction_V());\n\n  // Tolerances etc.\n  const double tol = 1.0E-10;\n  const double nmax = 30;\n\n  // Use the target point as the initial guess\n  // (this is within sum{amplitudes} of the solution)\n  Eigen::Vector2d p2(_point.X(), _point.Y());\n  const double pz = solver(wave_fdf, p2, p2, _time, wp, tol, nmax);\n  // Removed so that height is reported relative to mean water level\n  // const double h = pz - _point.Z();\n  const double h = pz;\n  return h;\n}\n", "meta": {"hexsha": "5bbcfc24ad93dc5fa7b08a5efd1f3775b34cfebe", "size": 21319, "ext": "cc", "lang": "C++", "max_stars_repo_path": "mbzirc_ign/src/Wavefield.cc", "max_stars_repo_name": "GGMul/mbzirc", "max_stars_repo_head_hexsha": "da7033510ae0384ef4a3bf9a39131dd0a9aabe15", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2022-01-06T06:08:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:56:45.000Z", "max_issues_repo_path": "mbzirc_ign/src/Wavefield.cc", "max_issues_repo_name": "GGMul/mbzirc", "max_issues_repo_head_hexsha": "da7033510ae0384ef4a3bf9a39131dd0a9aabe15", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 28.0, "max_issues_repo_issues_event_min_datetime": "2021-12-16T17:59:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T18:40:09.000Z", "max_forks_repo_path": "mbzirc_ign/src/Wavefield.cc", "max_forks_repo_name": "GGMul/mbzirc", "max_forks_repo_head_hexsha": "da7033510ae0384ef4a3bf9a39131dd0a9aabe15", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2022-01-07T20:15:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T07:41:06.000Z", "avg_line_length": 30.8523878437, "max_line_length": 83, "alphanum_fraction": 0.5397532717, "num_tokens": 5356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.727975460709318, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.4584604700851747}}
{"text": "/*\n * visualization.cpp\n *\n *  Created on: Jan 18, 2012\n *      Author: eba\n */\n\n#include \"mhfpython.h\"\n\n#include <boost/foreach.hpp>\n#include \"visualization.h\"\n#include <numpy/noprefix.h>\n\n\n// TODO expand the definition of this function to handle higher dimensional cases\n//PyObject * actualDistributionAfterPredict(const GaussianHypothesis<dim> & gh,\n//\t\t\t\t\t\t\t\t\t\t transformations<dim,procnoisedim,inputdim> &trans,\n//\t\t\t\t\t\t\t\t\t\t const Matrix<double,inputdim,1> & input,\n//\t\t\t\t\t\t\t\t\t\t const Matrix<double,procnoisedim,procnoisedim> & noisecov,\n//\t\t\t\t\t\t\t\t\t\t int samples, double limit, const int steps) {\n//    double * zData = new double[steps * steps];\n//    Map<Matrix<double, Dynamic, Dynamic> > z(zData, steps,steps);\n//    z.fill(0);\n//    double cellArea = pow(2 * limit / steps,2);\n//    const Matrix<double,dim,1> & mean = gh.mean;\n//    Matrix<double,dim,dim> cholState = gh.cov.llt().matrixL();\n//    Matrix<double,procnoisedim,procnoisedim> cholNoise = noisecov.llt().matrixL();\n//    boost::mt19937 rng;\n//    boost::normal_distribution<> nd(0,1);\n//    boost::variate_generator<boost::mt19937&, boost::normal_distribution<> > var_nor(rng, nd);\n//\n//\n//    for (int i=0; i<samples; i++) {\n//\t\tMatrix<double,dim,1> sample = mean + cholState * randomMatrix<dim,1>(var_nor);\n//\t\tMatrix<double,procnoisedim,1> noise = cholNoise * randomMatrix<procnoisedim,1>(var_nor);\n//\t\tsample = trans.statetrans(sample,noise,input);\n//\t\tif(limit>sample.maxCoeff() && sample.minCoeff()>-limit) {\n//\t\t\tMatrix<int,dim,1> index = (sample.array() * steps/2 / limit + steps/2).matrix().cast<int>();\n//\t\t\tz(index(0,0),index(1,0)) += 1./(samples*cellArea);\n//\t\t}\n//\t}\n//    int N[] = {steps,steps};\n//    PyArrayObject * result = (PyArrayObject*) PyArray_SimpleNewFromData(2,N, PyArray_DOUBLE, zData);\n//    result->flags = result->flags | OWNDATA;\n//    return (PyObject *)result;\n//}\n\nvoid propagateSamples(samplevector & samples,\n\t\t\t\t\t  transformations<dim,procnoisedim,inputdim> &trans,\n\t\t\t\t\t  const Matrix<double,inputdim,1> & input,\n\t\t\t\t\t  const Matrix<double,procnoisedim,procnoisedim> & noisecov\n\t) {\n    Matrix<double,procnoisedim,procnoisedim> cholNoise = noisecov.llt().matrixL();\n    boost::mt19937 rng;\n    boost::normal_distribution<> nd(0,1);\n    boost::variate_generator<boost::mt19937&, boost::normal_distribution<> > var_nor(rng, nd);\n\n    BOOST_FOREACH(Sample & sample, samples) {\n\t\tMatrix<double,procnoisedim,1> noise = cholNoise * randomMatrix<procnoisedim,1>(var_nor);\n\t\tsample.state = trans.statetrans(sample.state,noise,input);\n\t}\n}\n\nvoid updateSamples(samplevector & samples,\n\t\t\t\t   transformations<dim,measdim,measdim> &trans,\n\t\t\t\t   const Matrix<double,measdim,1> & meas,\n\t\t\t\t   const Matrix<double,measdim,measdim> & noisecov\n\t) {\n\n\tnullclass nullobj;\n\tdouble totalWeight = 0;\n    BOOST_FOREACH(Sample & sample, samples) {\n\t\tsample.weight = trans.measlikelihood(sample.state,noisecov,meas,nullobj);\n\t\ttotalWeight += sample.weight;\n\t}\n    BOOST_FOREACH(Sample & sample, samples) {\n    \tsample.weight /= totalWeight;\n    }\n}\n\n// TODO expand the definition of this function to handle higher dimensional cases\nPyObject * layoutSamples(const samplevector & samples, double limit, const int steps) {\n    double * zData = new double[steps * steps];\n    Map<Matrix<double, Dynamic, Dynamic> > z(zData, steps,steps);\n    z.fill(0);\n    double cellArea = pow(2 * limit / steps,2);\n\n    typedef Matrix<double,dim,1> SampleMat;\n\n    BOOST_FOREACH(const Sample & sample, samples) {\n\t\tif(limit>sample.state.block<2,1>(0,0).maxCoeff() && sample.state.block<2,1>(0,0).minCoeff()>-limit) { // TODO This line is temporary\n\t\t\tMatrix<int,dim,1> index = (sample.state.array() * steps/2 / limit + steps/2).matrix().cast<int>();\n\t\t\tz(index(0,0),index(1,0)) += sample.weight/cellArea;\n\t\t}\n\t}\n    npy_intp N[] = {steps,steps};\n    PyArrayObject * result = (PyArrayObject*) PyArray_SimpleNewFromData(2,N, PyArray_DOUBLE, zData);\n    result->flags = result->flags | OWNDATA;\n    return (PyObject *)result;\n}\n\nvoid resample(samplevector & samples) {\n\trandom_shuffle ( samples.begin(), samples.end() );\n\tint sampleCount = samples.size();\n\tdouble sampleWeight = 1.0/sampleCount;\n\tsamplevector oldsamples = samples;\n\tdouble weight = (double(rand()) / double(RAND_MAX)) * sampleWeight;\n\tint sampleNum = 0;\n\tBOOST_FOREACH(const Sample & sample, oldsamples) {\n\t\twhile(sample.weight>=weight) {\n\t\t\tsamples[sampleNum].state = sample.state;\n\t\t\tsamples[sampleNum].weight = sampleWeight;\n\t\t\tweight += sampleWeight;\n\t\t\tsampleNum++;\n\t\t}\n\t\tweight -= sample.weight;\n\t}\n\tif(sampleNum!=sampleCount) std::cerr<<\"problem!\\n\";\n}\n\nvoid export_visualization() {\n\timport_array();\n\tclass_<samplevector>(\"samplevector\");\n\t//def(\"actualDistributionAfterPredict\", actualDistributionAfterPredict);\n\tdef(\"drawSamples\", drawSamples<dim>);\n\tdef(\"propagateSamples\", propagateSamples);\n\tdef(\"updateSamples\", updateSamples);\n\tdef(\"layoutSamples\", layoutSamples);\n\tdef(\"resample\", resample);\n}\n", "meta": {"hexsha": "399ee4f15294f7e9e971158036547c9702a60fa8", "size": 4943, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "MHFPython/visualization.cpp", "max_stars_repo_name": "enobayram/MHFlib", "max_stars_repo_head_hexsha": "bfb978aee59ac1916b0a54ce881d4eb35311e763", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-29T08:50:55.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-29T08:50:55.000Z", "max_issues_repo_path": "MHFPython/visualization.cpp", "max_issues_repo_name": "enobayram/MHFlib", "max_issues_repo_head_hexsha": "bfb978aee59ac1916b0a54ce881d4eb35311e763", "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": "MHFPython/visualization.cpp", "max_forks_repo_name": "enobayram/MHFlib", "max_forks_repo_head_hexsha": "bfb978aee59ac1916b0a54ce881d4eb35311e763", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.7328244275, "max_line_length": 134, "alphanum_fraction": 0.6888529233, "num_tokens": 1373, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059775, "lm_q2_score": 0.629774621301746, "lm_q1q2_score": 0.45846046265173057}}
{"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 testUnit3.cpp\n * @date Feb 03, 2012\n * @author Can Erdogan\n * @author Frank Dellaert\n * @author Alex Trevor\n * @brief Tests the Unit3 class\n */\n\n#include <gtsam/base/Testable.h>\n#include <gtsam/base/numericalDerivative.h>\n#include <gtsam/base/serializationTestHelpers.h>\n#include <gtsam/geometry/Unit3.h>\n#include <gtsam/geometry/Rot3.h>\n#include <gtsam/inference/Symbol.h>\n#include <gtsam/nonlinear/ExpressionFactor.h>\n#include <gtsam/nonlinear/GaussNewtonOptimizer.h>\n#include <gtsam/nonlinear/NonlinearFactorGraph.h>\n\n\n#include <CppUnitLite/TestHarness.h>\n\n#include <boost/bind.hpp>\n#include <boost/assign/std/vector.hpp>\n\n#include <cmath>\n#include <random>\n\nusing namespace boost::assign;\nusing namespace gtsam;\nusing namespace std;\nusing gtsam::symbol_shorthand::U;\n\nGTSAM_CONCEPT_TESTABLE_INST(Unit3)\nGTSAM_CONCEPT_MANIFOLD_INST(Unit3)\n\n//*******************************************************************************\nPoint3 point3_(const Unit3& p) {\n  return p.point3();\n}\n\nTEST(Unit3, point3) {\n  vector<Point3> ps;\n  ps += Point3(1, 0, 0), Point3(0, 1, 0), Point3(0, 0, 1), Point3(1, 1, 0)\n      / sqrt(2.0);\n  Matrix actualH, expectedH;\n  for(Point3 p: ps) {\n    Unit3 s(p);\n    expectedH = numericalDerivative11<Point3, Unit3>(point3_, s);\n    EXPECT(assert_equal(p, s.point3(actualH), 1e-8));\n    EXPECT(assert_equal(expectedH, actualH, 1e-9));\n  }\n}\n\n//*******************************************************************************\nstatic Unit3 rotate_(const Rot3& R, const Unit3& p) {\n  return R * p;\n}\n\nTEST(Unit3, rotate) {\n  Rot3 R = Rot3::Yaw(0.5);\n  Unit3 p(1, 0, 0);\n  Unit3 expected = Unit3(R.column(1));\n  Unit3 actual = R * p;\n  EXPECT(assert_equal(expected, actual, 1e-8));\n  Matrix actualH, expectedH;\n  // Use numerical derivatives to calculate the expected Jacobian\n  {\n    expectedH = numericalDerivative21(rotate_, R, p);\n    R.rotate(p, actualH, boost::none);\n    EXPECT(assert_equal(expectedH, actualH, 1e-9));\n  }\n  {\n    expectedH = numericalDerivative22(rotate_, R, p);\n    R.rotate(p, boost::none, actualH);\n    EXPECT(assert_equal(expectedH, actualH, 1e-9));\n  }\n}\n\n//*******************************************************************************\nstatic Unit3 unrotate_(const Rot3& R, const Unit3& p) {\n  return R.unrotate(p);\n}\n\nTEST(Unit3, unrotate) {\n  Rot3 R = Rot3::Yaw(-M_PI / 4.0);\n  Unit3 p(1, 0, 0);\n  Unit3 expected = Unit3(1, 1, 0);\n  Unit3 actual = R.unrotate(p);\n  EXPECT(assert_equal(expected, actual, 1e-8));\n\n  Matrix actualH, expectedH;\n  // Use numerical derivatives to calculate the expected Jacobian\n  {\n    expectedH = numericalDerivative21(unrotate_, R, p);\n    R.unrotate(p, actualH, boost::none);\n    EXPECT(assert_equal(expectedH, actualH, 1e-9));\n  }\n  {\n    expectedH = numericalDerivative22(unrotate_, R, p);\n    R.unrotate(p, boost::none, actualH);\n    EXPECT(assert_equal(expectedH, actualH, 1e-9));\n  }\n}\n\nTEST(Unit3, dot) {\n  Unit3 p(1, 0.2, 0.3);\n  Unit3 q = p.retract(Vector2(0.5, 0));\n  Unit3 r = p.retract(Vector2(0.8, 0));\n  Unit3 t = p.retract(Vector2(0, 0.3));\n  EXPECT(assert_equal(1.0, p.dot(p), 1e-8));\n  EXPECT(assert_equal(0.877583, p.dot(q), 1e-5));\n  EXPECT(assert_equal(0.696707, p.dot(r), 1e-5));\n  EXPECT(assert_equal(0.955336, p.dot(t), 1e-5));\n\n  // Use numerical derivatives to calculate the expected Jacobians\n  Matrix H1, H2;\n  boost::function<double(const Unit3&, const Unit3&)> f = boost::bind(&Unit3::dot, _1, _2,  //\n                                                                      boost::none, boost::none);\n  {\n    p.dot(q, H1, H2);\n    EXPECT(assert_equal(numericalDerivative21<double,Unit3>(f, p, q), H1, 1e-9));\n    EXPECT(assert_equal(numericalDerivative22<double,Unit3>(f, p, q), H2, 1e-9));\n  }\n  {\n    p.dot(r, H1, H2);\n    EXPECT(assert_equal(numericalDerivative21<double,Unit3>(f, p, r), H1, 1e-9));\n    EXPECT(assert_equal(numericalDerivative22<double,Unit3>(f, p, r), H2, 1e-9));\n  }\n  {\n    p.dot(t, H1, H2);\n    EXPECT(assert_equal(numericalDerivative21<double,Unit3>(f, p, t), H1, 1e-9));\n    EXPECT(assert_equal(numericalDerivative22<double,Unit3>(f, p, t), H2, 1e-9));\n  }\n}\n\n//*******************************************************************************\nTEST(Unit3, error) {\n  Unit3 p(1, 0, 0), q = p.retract(Vector2(0.5, 0)), //\n  r = p.retract(Vector2(0.8, 0));\n  EXPECT(assert_equal((Vector)(Vector2(0, 0)), p.error(p), 1e-8));\n  EXPECT(assert_equal((Vector)(Vector2(0.479426, 0)), p.error(q), 1e-5));\n  EXPECT(assert_equal((Vector)(Vector2(0.717356, 0)), p.error(r), 1e-5));\n\n  Matrix actual, expected;\n  // Use numerical derivatives to calculate the expected Jacobian\n  {\n    expected = numericalDerivative11<Vector2,Unit3>(\n        boost::bind(&Unit3::error, &p, _1, boost::none), q);\n    p.error(q, actual);\n    EXPECT(assert_equal(expected.transpose(), actual, 1e-9));\n  }\n  {\n    expected = numericalDerivative11<Vector2,Unit3>(\n        boost::bind(&Unit3::error, &p, _1, boost::none), r);\n    p.error(r, actual);\n    EXPECT(assert_equal(expected.transpose(), actual, 1e-9));\n  }\n}\n\n//*******************************************************************************\nTEST(Unit3, error2) {\n  Unit3 p(0.1, -0.2, 0.8);\n  Unit3 q = p.retract(Vector2(0.2, -0.1));\n  Unit3 r = p.retract(Vector2(0.8, 0));\n\n  // Hard-coded as simple regression values\n  EXPECT(assert_equal((Vector)(Vector2(0.0, 0.0)), p.errorVector(p), 1e-8));\n  EXPECT(assert_equal((Vector)(Vector2(0.198337495, -0.0991687475)), p.errorVector(q), 1e-5));\n  EXPECT(assert_equal((Vector)(Vector2(0.717356, 0)), p.errorVector(r), 1e-5));\n\n  Matrix actual, expected;\n  // Use numerical derivatives to calculate the expected Jacobian\n  {\n    expected = numericalDerivative21<Vector2, Unit3, Unit3>(\n        boost::bind(&Unit3::errorVector, _1, _2, boost::none, boost::none), p, q);\n    p.errorVector(q, actual, boost::none);\n    EXPECT(assert_equal(expected, actual, 1e-9));\n  }\n  {\n    expected = numericalDerivative21<Vector2, Unit3, Unit3>(\n        boost::bind(&Unit3::errorVector, _1, _2, boost::none, boost::none), p, r);\n    p.errorVector(r, actual, boost::none);\n    EXPECT(assert_equal(expected, actual, 1e-9));\n  }\n  {\n    expected = numericalDerivative22<Vector2, Unit3, Unit3>(\n        boost::bind(&Unit3::errorVector, _1, _2, boost::none, boost::none), p, q);\n    p.errorVector(q, boost::none, actual);\n    EXPECT(assert_equal(expected, actual, 1e-9));\n  }\n  {\n    expected = numericalDerivative22<Vector2, Unit3, Unit3>(\n        boost::bind(&Unit3::errorVector, _1, _2, boost::none, boost::none), p, r);\n    p.errorVector(r, boost::none, actual);\n    EXPECT(assert_equal(expected, actual, 1e-9));\n  }\n}\n\n//*******************************************************************************\nTEST(Unit3, distance) {\n  Unit3 p(1, 0, 0), q = p.retract(Vector2(0.5, 0)), //\n  r = p.retract(Vector2(0.8, 0));\n  EXPECT_DOUBLES_EQUAL(0, p.distance(p), 1e-8);\n  EXPECT_DOUBLES_EQUAL(0.47942553860420301, p.distance(q), 1e-8);\n  EXPECT_DOUBLES_EQUAL(0.71735609089952279, p.distance(r), 1e-8);\n\n  Matrix actual, expected;\n  // Use numerical derivatives to calculate the expected Jacobian\n  {\n    expected = numericalGradient<Unit3>(\n        boost::bind(&Unit3::distance, &p, _1, boost::none), q);\n    p.distance(q, actual);\n    EXPECT(assert_equal(expected.transpose(), actual, 1e-9));\n  }\n  {\n    expected = numericalGradient<Unit3>(\n        boost::bind(&Unit3::distance, &p, _1, boost::none), r);\n    p.distance(r, actual);\n    EXPECT(assert_equal(expected.transpose(), actual, 1e-9));\n  }\n}\n\n//*******************************************************************************\nTEST(Unit3, localCoordinates0) {\n  Unit3 p;\n  Vector actual = p.localCoordinates(p);\n  EXPECT(assert_equal(Z_2x1, actual, 1e-8));\n}\n\nTEST(Unit3, localCoordinates) {\n  {\n    Unit3 p, q;\n    Vector2 expected = Vector2::Zero();\n    Vector2 actual = p.localCoordinates(q);\n    EXPECT(assert_equal((Vector) Z_2x1, actual, 1e-8));\n    EXPECT(assert_equal(q, p.retract(expected), 1e-8));\n  }\n  {\n    Unit3 p, q(1, 6.12385e-21, 0);\n    Vector2 expected = Vector2::Zero();\n    Vector2 actual = p.localCoordinates(q);\n    EXPECT(assert_equal((Vector) Z_2x1, actual, 1e-8));\n    EXPECT(assert_equal(q, p.retract(expected), 1e-8));\n  }\n  {\n    Unit3 p, q(-1, 0, 0);\n    Vector2 expected(M_PI, 0);\n    Vector2 actual = p.localCoordinates(q);\n    EXPECT(assert_equal(expected, actual, 1e-8));\n    EXPECT(assert_equal(q, p.retract(expected), 1e-8));\n  }\n  {\n    Unit3 p, q(0, 1, 0);\n    Vector2 expected(0,-M_PI_2);\n    Vector2 actual = p.localCoordinates(q);\n    EXPECT(assert_equal(expected, actual, 1e-8));\n    EXPECT(assert_equal(q, p.retract(expected), 1e-8));\n  }\n  {\n    Unit3 p, q(0, -1, 0);\n    Vector2 expected(0, M_PI_2);\n    Vector2 actual = p.localCoordinates(q);\n    EXPECT(assert_equal(expected, actual, 1e-8));\n    EXPECT(assert_equal(q, p.retract(expected), 1e-8));\n  }\n  {\n    Unit3 p(0,1,0), q(0,-1,0);\n    Vector2 actual = p.localCoordinates(q);\n    EXPECT(assert_equal(q, p.retract(actual), 1e-8));\n  }\n  {\n    Unit3 p(0,0,1), q(0,0,-1);\n    Vector2 actual = p.localCoordinates(q);\n    EXPECT(assert_equal(q, p.retract(actual), 1e-8));\n  }\n\n  double twist = 1e-4;\n  {\n    Unit3 p(0, 1, 0), q(0 - twist, -1 + twist, 0);\n    Vector2 actual = p.localCoordinates(q);\n    EXPECT(actual(0) < 1e-2);\n    EXPECT(actual(1) > M_PI - 1e-2)\n  }\n  {\n    Unit3 p(0, 1, 0), q(0 + twist, -1 - twist, 0);\n    Vector2 actual = p.localCoordinates(q);\n    EXPECT(actual(0) < 1e-2);\n    EXPECT(actual(1) < -M_PI + 1e-2)\n  }\n}\n\n//*******************************************************************************\n// Wrapper to make basis return a Vector6 so we can test numerical derivatives.\nVector6 BasisTest(const Unit3& p, OptionalJacobian<6, 2> H) {\n  Matrix32 B = p.basis(H);\n  Vector6 B_vec;\n  B_vec << B.col(0), B.col(1);\n  return B_vec;\n}\n\nTEST(Unit3, basis) {\n  Unit3 p(0.1, -0.2, 0.9);\n\n  Matrix expected(3, 2);\n  expected << 0.0, -0.994169047, 0.97618706, -0.0233922129, 0.216930458, 0.105264958;\n\n  Matrix62 actualH;\n  Matrix62 expectedH = numericalDerivative11<Vector6, Unit3>(\n      boost::bind(BasisTest, _1, boost::none), p);\n\n  // without H, first time\n  EXPECT(assert_equal(expected, p.basis(), 1e-6));\n\n  // without H, cached\n  EXPECT(assert_equal(expected, p.basis(), 1e-6));\n\n  // with H, first time\n  EXPECT(assert_equal(expected, p.basis(actualH), 1e-6));\n  EXPECT(assert_equal(expectedH, actualH, 1e-8));\n\n  // with H, cached\n  EXPECT(assert_equal(expected, p.basis(actualH), 1e-6));\n  EXPECT(assert_equal(expectedH, actualH, 1e-8));\n}\n\n//*******************************************************************************\n/// Check the basis derivatives of a bunch of random Unit3s.\nTEST(Unit3, basis_derivatives) {\n  int num_tests = 100;\n  std::mt19937 rng(42);\n  for (int i = 0; i < num_tests; i++) {\n    Unit3 p = Unit3::Random(rng);\n\n    Matrix62 actualH;\n    p.basis(actualH);\n\n    Matrix62 expectedH = numericalDerivative11<Vector6, Unit3>(\n                           boost::bind(BasisTest, _1, boost::none), p);\n    EXPECT(assert_equal(expectedH, actualH, 1e-8));\n  }\n}\n\n//*******************************************************************************\nTEST(Unit3, retract) {\n  {\n    Unit3 p;\n    Vector2 v(0.5, 0);\n    Unit3 expected(0.877583, 0, 0.479426);\n    Unit3 actual = p.retract(v);\n    EXPECT(assert_equal(expected, actual, 1e-6));\n    EXPECT(assert_equal(v, p.localCoordinates(actual), 1e-8));\n  }\n  {\n    Unit3 p;\n    Vector2 v(0, 0);\n    Unit3 actual = p.retract(v);\n    EXPECT(assert_equal(p, actual, 1e-6));\n    EXPECT(assert_equal(v, p.localCoordinates(actual), 1e-8));\n  }\n}\n\n//*******************************************************************************\nTEST (Unit3, jacobian_retract) {\n  Matrix22 H;\n  Unit3 p;\n  boost::function<Unit3(const Vector2&)> f =\n      boost::bind(&Unit3::retract, p, _1, boost::none);\n  {\n      Vector2 v (-0.2, 0.1);\n      p.retract(v, H);\n      Matrix H_expected_numerical = numericalDerivative11(f, v);\n      EXPECT(assert_equal(H_expected_numerical, H, 1e-9));\n  }\n  {\n      Vector2 v (0, 0);\n      p.retract(v, H);\n      Matrix H_expected_numerical = numericalDerivative11(f, v);\n      EXPECT(assert_equal(H_expected_numerical, H, 1e-9));\n  }\n}\n\n//*******************************************************************************\nTEST(Unit3, retract_expmap) {\n  Unit3 p;\n  Vector2 v((M_PI / 2.0), 0);\n  Unit3 expected(Point3(0, 0, 1));\n  Unit3 actual = p.retract(v);\n  EXPECT(assert_equal(expected, actual, 1e-8));\n  EXPECT(assert_equal(v, p.localCoordinates(actual), 1e-8));\n}\n\n//*******************************************************************************\nTEST(Unit3, Random) {\n  std::mt19937 rng(42);\n  // Check that means are all zero at least\n  Point3 expectedMean(0,0,0), actualMean(0,0,0);\n  for (size_t i = 0; i < 100; i++)\n    actualMean = actualMean + Unit3::Random(rng).point3();\n  actualMean = actualMean / 100;\n  EXPECT(assert_equal(expectedMean,actualMean,0.1));\n}\n\n//*******************************************************************************\n// New test that uses Unit3::Random\nTEST(Unit3, localCoordinates_retract) {\n  std::mt19937 rng(42);\n  size_t numIterations = 10000;\n\n  for (size_t i = 0; i < numIterations; i++) {\n    // Create two random Unit3s\n    const Unit3 s1 = Unit3::Random(rng);\n    const Unit3 s2 = Unit3::Random(rng);\n    // Check that they are not at opposite ends of the sphere, which is ill defined\n    if (s1.unitVector().dot(s2.unitVector())<-0.9) continue;\n\n    // Check if the local coordinates and retract return consistent results.\n    Vector v12 = s1.localCoordinates(s2);\n    Unit3 actual_s2 = s1.retract(v12);\n    EXPECT(assert_equal(s2, actual_s2, 1e-9));\n  }\n}\n\n//*************************************************************************\nTEST (Unit3, FromPoint3) {\n  Matrix actualH;\n  Point3 point(1, -2, 3); // arbitrary point\n  Unit3 expected(point);\n  EXPECT(assert_equal(expected, Unit3::FromPoint3(point, actualH), 1e-8));\n  Matrix expectedH = numericalDerivative11<Unit3, Point3>(\n      boost::bind(Unit3::FromPoint3, _1, boost::none), point);\n  EXPECT(assert_equal(expectedH, actualH, 1e-8));\n}\n\n//*******************************************************************************\nTEST(Unit3, ErrorBetweenFactor) {\n  std::vector<Unit3> data;\n  data.push_back(Unit3(1.0, 0.0, 0.0));\n  data.push_back(Unit3(0.0, 0.0, 1.0));\n\n  NonlinearFactorGraph graph;\n  Values initial_values;\n\n  // Add prior factors.\n  SharedNoiseModel R_prior = noiseModel::Unit::Create(2);\n  for (size_t i = 0; i < data.size(); i++) {\n    graph.addPrior(U(i), data[i], R_prior);\n  }\n\n  // Add process factors using the dot product error function.\n  SharedNoiseModel R_process = noiseModel::Isotropic::Sigma(2, 0.01);\n  for (size_t i = 0; i < data.size() - 1; i++) {\n    Expression<Vector2> exp(Expression<Unit3>(U(i)), &Unit3::errorVector,\n                            Expression<Unit3>(U(i + 1)));\n    graph.addExpressionFactor<Vector2>(R_process, Vector2::Zero(), exp);\n  }\n\n  // Add initial values. Since there is no identity, just pick something.\n  for (size_t i = 0; i < data.size(); i++) {\n    initial_values.insert(U(i), Unit3(0.0, 1.0, 0.0));\n  }\n\n  Values values = GaussNewtonOptimizer(graph, initial_values).optimize();\n\n  // Check that the y-value is very small for each.\n  for (size_t i = 0; i < data.size(); i++) {\n    EXPECT(assert_equal(0.0, values.at<Unit3>(U(i)).unitVector().y(), 1e-3));\n  }\n\n  // Check that the dot product between variables is close to 1.\n  for (size_t i = 0; i < data.size() - 1; i++) {\n    EXPECT(assert_equal(1.0, values.at<Unit3>(U(i)).dot(values.at<Unit3>(U(i + 1))), 1e-2));\n  }\n}\n\n/* ************************************************************************* */\nTEST(actualH, Serialization) {\n  Unit3 p(0, 1, 0);\n  EXPECT(serializationTestHelpers::equalsObj(p));\n  EXPECT(serializationTestHelpers::equalsXML(p));\n  EXPECT(serializationTestHelpers::equalsBinary(p));\n}\n\n/* ************************************************************************* */\nint main() {\n  srand(time(nullptr));\n  TestResult tr;\n  return TestRegistry::runAllTests(tr);\n}\n/* ************************************************************************* */\n", "meta": {"hexsha": "60f491a1cec00ae44935e811f65efbe49b918f28", "size": 16528, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/geometry/tests/testUnit3.cpp", "max_stars_repo_name": "victor1234/gtsam", "max_stars_repo_head_hexsha": "fbece35715d6c6eed8d98fd5f62fdbb205dbdcfa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gtsam/geometry/tests/testUnit3.cpp", "max_issues_repo_name": "victor1234/gtsam", "max_issues_repo_head_hexsha": "fbece35715d6c6eed8d98fd5f62fdbb205dbdcfa", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/geometry/tests/testUnit3.cpp", "max_forks_repo_name": "victor1234/gtsam", "max_forks_repo_head_hexsha": "fbece35715d6c6eed8d98fd5f62fdbb205dbdcfa", "max_forks_repo_licenses": ["BSD-3-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.9243027888, "max_line_length": 96, "alphanum_fraction": 0.5861568248, "num_tokens": 4874, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.629774621301746, "lm_q1q2_score": 0.45846046265173046}}
{"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//#define NDEBUG\n//#define VIENNACL_DEBUG_BUILD\n\n//\n// *** System\n//\n#include <iostream>\n\n// We don't need debug mode in UBLAS:\n#define BOOST_UBLAS_NDEBUG\n\n//\n// *** Boost\n//\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/triangular.hpp>\n#include <boost/numeric/ublas/matrix_sparse.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n//\n// *** ViennaCL\n//\n//#define VIENNACL_DEBUG_ALL\n//#define VIENNACL_DEBUG_BUILD\n#define VIENNACL_WITH_UBLAS 1\n#include \"viennacl/scalar.hpp\"\n#include \"viennacl/matrix.hpp\"\n#include \"viennacl/matrix_proxy.hpp\"\n#include \"viennacl/vector.hpp\"\n#include \"viennacl/linalg/prod.hpp\"\n#include \"viennacl/linalg/norm_2.hpp\"\n#include \"viennacl/linalg/direct_solve.hpp\"\n#include \"examples/tutorial/Random.hpp\"\n//\n// -------------------------------------------------------------\n//\nusing namespace boost::numeric;\n//\n// -------------------------------------------------------------\n//\ntemplate<typename ScalarType>\nScalarType diff(ScalarType & s1, viennacl::scalar<ScalarType> & s2)\n{\n   viennacl::backend::finish();\n   if (s1 != s2)\n      return (s1 - s2) / std::max(fabs(s1), fabs(s2));\n   return 0;\n}\n\ntemplate<typename ScalarType>\nScalarType diff(ublas::vector<ScalarType> & v1, viennacl::vector<ScalarType> & v2)\n{\n   ublas::vector<ScalarType> v2_cpu(v2.size());\n   viennacl::backend::finish();\n   viennacl::copy(v2.begin(), v2.end(), v2_cpu.begin());\n   viennacl::backend::finish();\n\n   for (std::size_t i=0;i<v1.size(); ++i)\n   {\n      if ( std::max( fabs(v2_cpu[i]), fabs(v1[i]) ) > 0 )\n         v2_cpu[i] = fabs(v2_cpu[i] - v1[i]) / std::max( fabs(v2_cpu[i]), fabs(v1[i]) );\n      else\n         v2_cpu[i] = 0.0;\n   }\n\n   return norm_inf(v2_cpu);\n}\n\n\ntemplate<typename ScalarType, typename VCLMatrixType>\nScalarType diff(ublas::matrix<ScalarType> & mat1, VCLMatrixType & mat2)\n{\n   ublas::matrix<ScalarType> mat2_cpu(mat2.size1(), mat2.size2());\n   viennacl::backend::finish();  //workaround for a bug in APP SDK 2.7 on Trinity APUs (with Catalyst 12.8)\n   viennacl::copy(mat2, mat2_cpu);\n   ScalarType ret = 0;\n   ScalarType act = 0;\n\n    for (unsigned int i = 0; i < mat2_cpu.size1(); ++i)\n    {\n      for (unsigned int j = 0; j < mat2_cpu.size2(); ++j)\n      {\n         act = std::fabs(mat2_cpu(i,j) - mat1(i,j)) / std::max( std::fabs(mat2_cpu(i, j)), std::fabs(mat1(i,j)) );\n         if (act > ret)\n           ret = act;\n      }\n    }\n   //std::cout << ret << std::endl;\n   return ret;\n}\n\n\n\n//\n// Triangular solvers\n//\n\n\n\ntemplate<typename RHSTypeRef, typename RHSTypeCheck, typename Epsilon >\nvoid run_solver_check(RHSTypeRef & B_ref, RHSTypeCheck & B_check, int & retval, Epsilon const & epsilon)\n{\n   double act_diff = fabs(diff(B_ref, B_check));\n   if ( act_diff > epsilon )\n   {\n     std::cout << \" FAILED!\" << std::endl;\n     std::cout << \"# Error at operation: matrix-matrix solve\" << std::endl;\n     std::cout << \"  diff: \" << act_diff << std::endl;\n     retval = EXIT_FAILURE;\n   }\n   else\n     std::cout << \" passed! \" << act_diff << std::endl;\n\n}\n\n\ntemplate< typename NumericT, typename Epsilon,\n          typename ReferenceMatrixTypeA, typename ReferenceMatrixTypeB, typename ReferenceMatrixTypeC,\n          typename MatrixTypeA, typename MatrixTypeB, typename MatrixTypeC, typename MatrixTypeResult>\nint test_solve(Epsilon const& epsilon,\n\n              ReferenceMatrixTypeA const & A,\n              ReferenceMatrixTypeB const & B_start,\n              ReferenceMatrixTypeC const & C_start,\n\n              MatrixTypeA const & vcl_A,\n              MatrixTypeB & vcl_B,\n              MatrixTypeC & vcl_C,\n              MatrixTypeResult const &\n             )\n{\n   int retval = EXIT_SUCCESS;\n\n   // --------------------------------------------------------------------------\n\n   ReferenceMatrixTypeA result;\n   ReferenceMatrixTypeC C_trans;\n\n   ReferenceMatrixTypeB B = B_start;\n   ReferenceMatrixTypeC C = C_start;\n\n   MatrixTypeResult vcl_result;\n\n   // Test: A \\ B with various tags --------------------------------------------------------------------------\n   std::cout << \"Testing A \\\\ B: \" << std::endl;\n   std::cout << \" * upper_tag:      \";\n   result = ublas::solve(A, B, ublas::upper_tag());\n   vcl_result = viennacl::linalg::solve(vcl_A, vcl_B, viennacl::linalg::upper_tag());\n   run_solver_check(result, vcl_result, retval, epsilon);\n\n   std::cout << \" * unit_upper_tag: \";\n   result = ublas::solve(A, B, ublas::unit_upper_tag());\n   vcl_result = viennacl::linalg::solve(vcl_A, vcl_B, viennacl::linalg::unit_upper_tag());\n   run_solver_check(result, vcl_result, retval, epsilon);\n\n   std::cout << \" * lower_tag:      \";\n   result = ublas::solve(A, B, ublas::lower_tag());\n   vcl_result = viennacl::linalg::solve(vcl_A, vcl_B, viennacl::linalg::lower_tag());\n   run_solver_check(result, vcl_result, retval, epsilon);\n\n   std::cout << \" * unit_lower_tag: \";\n   result = ublas::solve(A, B, ublas::unit_lower_tag());\n   vcl_result = viennacl::linalg::solve(vcl_A, vcl_B, viennacl::linalg::unit_lower_tag());\n   run_solver_check(result, vcl_result, retval, epsilon);\n\n   if (retval == EXIT_SUCCESS)\n     std::cout << \"Test A \\\\ B passed!\" << std::endl;\n\n   B = B_start;\n   C = C_start;\n\n   // Test: A \\ B^T --------------------------------------------------------------------------\n   std::cout << \"Testing A \\\\ B^T: \" << std::endl;\n   std::cout << \" * upper_tag:      \";\n   viennacl::copy(C, vcl_C); C_trans = trans(C);\n   //check solve():\n   result = ublas::solve(A, C_trans, ublas::upper_tag());\n   vcl_result = viennacl::linalg::solve(vcl_A, trans(vcl_C), viennacl::linalg::upper_tag());\n   run_solver_check(result, vcl_result, retval, epsilon);\n   //check compute kernels:\n   std::cout << \" * upper_tag:      \";\n   ublas::inplace_solve(A, C_trans, ublas::upper_tag());\n   viennacl::linalg::inplace_solve(vcl_A, trans(vcl_C), viennacl::linalg::upper_tag());\n   C = trans(C_trans); run_solver_check(C, vcl_C, retval, epsilon);\n\n   std::cout << \" * unit_upper_tag: \";\n   viennacl::copy(C, vcl_C); C_trans = trans(C);\n   ublas::inplace_solve(A, C_trans, ublas::unit_upper_tag());\n   viennacl::linalg::inplace_solve(vcl_A, trans(vcl_C), viennacl::linalg::unit_upper_tag());\n   C = trans(C_trans); run_solver_check(C, vcl_C, retval, epsilon);\n\n   std::cout << \" * lower_tag:      \";\n   viennacl::copy(C, vcl_C); C_trans = trans(C);\n   ublas::inplace_solve(A, C_trans, ublas::lower_tag());\n   viennacl::linalg::inplace_solve(vcl_A, trans(vcl_C), viennacl::linalg::lower_tag());\n   C = trans(C_trans); run_solver_check(C, vcl_C, retval, epsilon);\n\n   std::cout << \" * unit_lower_tag: \";\n   viennacl::copy(C, vcl_C); C_trans = trans(C);\n   ublas::inplace_solve(A, C_trans, ublas::unit_lower_tag());\n   viennacl::linalg::inplace_solve(vcl_A, trans(vcl_C), viennacl::linalg::unit_lower_tag());\n   C = trans(C_trans); run_solver_check(C, vcl_C, retval, epsilon);\n\n   if (retval == EXIT_SUCCESS)\n     std::cout << \"Test A \\\\ B^T passed!\" << std::endl;\n\n   B = B_start;\n   C = C_start;\n\n   // Test: A \\ B with various tags --------------------------------------------------------------------------\n   std::cout << \"Testing A^T \\\\ B: \" << std::endl;\n   std::cout << \" * upper_tag:      \";\n   viennacl::copy(B, vcl_B);\n   result = ublas::solve(trans(A), B, ublas::upper_tag());\n   vcl_result = viennacl::linalg::solve(trans(vcl_A), vcl_B, viennacl::linalg::upper_tag());\n   run_solver_check(result, vcl_result, retval, epsilon);\n\n   std::cout << \" * unit_upper_tag: \";\n   viennacl::copy(B, vcl_B);\n   result = ublas::solve(trans(A), B, ublas::unit_upper_tag());\n   vcl_result = viennacl::linalg::solve(trans(vcl_A), vcl_B, viennacl::linalg::unit_upper_tag());\n   run_solver_check(result, vcl_result, retval, epsilon);\n\n   std::cout << \" * lower_tag:      \";\n   viennacl::copy(B, vcl_B);\n   result = ublas::solve(trans(A), B, ublas::lower_tag());\n   vcl_result = viennacl::linalg::solve(trans(vcl_A), vcl_B, viennacl::linalg::lower_tag());\n   run_solver_check(result, vcl_result, retval, epsilon);\n\n   std::cout << \" * unit_lower_tag: \";\n   viennacl::copy(B, vcl_B);\n   result = ublas::solve(trans(A), B, ublas::unit_lower_tag());\n   vcl_result = viennacl::linalg::solve(trans(vcl_A), vcl_B, viennacl::linalg::unit_lower_tag());\n   run_solver_check(result, vcl_result, retval, epsilon);\n\n   if (retval == EXIT_SUCCESS)\n     std::cout << \"Test A^T \\\\ B passed!\" << std::endl;\n\n   B = B_start;\n   C = C_start;\n\n   // Test: A^T \\ B^T --------------------------------------------------------------------------\n   std::cout << \"Testing A^T \\\\ B^T: \" << std::endl;\n   std::cout << \" * upper_tag:      \";\n   viennacl::copy(C, vcl_C); C_trans = trans(C);\n   //check solve():\n   result = ublas::solve(trans(A), C_trans, ublas::upper_tag());\n   vcl_result = viennacl::linalg::solve(trans(vcl_A), trans(vcl_C), viennacl::linalg::upper_tag());\n   run_solver_check(result, vcl_result, retval, epsilon);\n   //check kernels:\n   std::cout << \" * upper_tag:      \";\n   ublas::inplace_solve(trans(A), C_trans, ublas::upper_tag());\n   viennacl::linalg::inplace_solve(trans(vcl_A), trans(vcl_C), viennacl::linalg::upper_tag());\n   C = trans(C_trans); run_solver_check(C, vcl_C, retval, epsilon);\n\n   std::cout << \" * unit_upper_tag: \";\n   viennacl::copy(C, vcl_C); C_trans = trans(C);\n   ublas::inplace_solve(trans(A), C_trans, ublas::unit_upper_tag());\n   viennacl::linalg::inplace_solve(trans(vcl_A), trans(vcl_C), viennacl::linalg::unit_upper_tag());\n   C = trans(C_trans); run_solver_check(C, vcl_C, retval, epsilon);\n\n   std::cout << \" * lower_tag:      \";\n   viennacl::copy(C, vcl_C); C_trans = trans(C);\n   ublas::inplace_solve(trans(A), C_trans, ublas::lower_tag());\n   viennacl::linalg::inplace_solve(trans(vcl_A), trans(vcl_C), viennacl::linalg::lower_tag());\n   C = trans(C_trans); run_solver_check(C, vcl_C, retval, epsilon);\n\n   std::cout << \" * unit_lower_tag: \";\n   viennacl::copy(C, vcl_C); C_trans = trans(C);\n   ublas::inplace_solve(trans(A), C_trans, ublas::unit_lower_tag());\n   viennacl::linalg::inplace_solve(trans(vcl_A), trans(vcl_C), viennacl::linalg::unit_lower_tag());\n   C = trans(C_trans); run_solver_check(C, vcl_C, retval, epsilon);\n\n   if (retval == EXIT_SUCCESS)\n     std::cout << \"Test A^T \\\\ B^T passed!\" << std::endl;\n\n   return retval;\n}\n\n\ntemplate< typename NumericT, typename F_A, typename F_B, typename Epsilon >\nint test_solve(Epsilon const& epsilon)\n{\n  int ret = EXIT_SUCCESS;\n  std::size_t matrix_size = 135;  //some odd number, not too large\n  std::size_t rhs_num = 67;\n\n  std::cout << \"--- Part 2: Testing matrix-matrix solver ---\" << std::endl;\n\n\n  ublas::matrix<NumericT> A(matrix_size, matrix_size);\n  ublas::matrix<NumericT> B_start(matrix_size, rhs_num);\n  ublas::matrix<NumericT> C_start(rhs_num, matrix_size);\n\n  for (std::size_t i = 0; i < A.size1(); ++i)\n  {\n    for (std::size_t j = 0; j < A.size2(); ++j)\n        A(i,j) = static_cast<NumericT>(-0.5) * random<NumericT>();\n    A(i,i) = NumericT(1.0) + NumericT(2.0) * random<NumericT>(); //some extra weight on diagonal for stability\n  }\n\n  for (std::size_t i = 0; i < B_start.size1(); ++i)\n    for (std::size_t j = 0; j < B_start.size2(); ++j)\n        B_start(i,j) = random<NumericT>();\n\n  for (std::size_t i = 0; i < C_start.size1(); ++i)\n    for (std::size_t j = 0; j < C_start.size2(); ++j)\n        C_start(i,j) = random<NumericT>();\n\n\n  // A\n  viennacl::range range1_A(matrix_size, 2*matrix_size);\n  viennacl::range range2_A(2*matrix_size, 3*matrix_size);\n  viennacl::slice slice1_A(matrix_size, 2, matrix_size);\n  viennacl::slice slice2_A(0, 3, matrix_size);\n\n  viennacl::matrix<NumericT, F_A>    vcl_A(matrix_size, matrix_size);\n  viennacl::copy(A, vcl_A);\n\n  viennacl::matrix<NumericT, F_A>    vcl_big_range_A(4*matrix_size, 4*matrix_size);\n  viennacl::matrix_range<viennacl::matrix<NumericT, F_A> > vcl_range_A(vcl_big_range_A, range1_A, range2_A);\n  viennacl::copy(A, vcl_range_A);\n\n  viennacl::matrix<NumericT, F_A>    vcl_big_slice_A(4*matrix_size, 4*matrix_size);\n  viennacl::matrix_slice<viennacl::matrix<NumericT, F_A> > vcl_slice_A(vcl_big_slice_A, slice1_A, slice2_A);\n  viennacl::copy(A, vcl_slice_A);\n\n\n  // B\n  viennacl::range range1_B(matrix_size, 2*matrix_size);\n  viennacl::range range2_B(2*rhs_num, 3*rhs_num);\n  viennacl::slice slice1_B(matrix_size, 2, matrix_size);\n  viennacl::slice slice2_B(0, 3, rhs_num);\n\n  viennacl::matrix<NumericT, F_B>    vcl_B(matrix_size, rhs_num);\n  viennacl::copy(B_start, vcl_B);\n\n  viennacl::matrix<NumericT, F_B>    vcl_big_range_B(4*matrix_size, 4*rhs_num);\n  viennacl::matrix_range<viennacl::matrix<NumericT, F_B> > vcl_range_B(vcl_big_range_B, range1_B, range2_B);\n  viennacl::copy(B_start, vcl_range_B);\n\n  viennacl::matrix<NumericT, F_B>    vcl_big_slice_B(4*matrix_size, 4*rhs_num);\n  viennacl::matrix_slice<viennacl::matrix<NumericT, F_B> > vcl_slice_B(vcl_big_slice_B, slice1_B, slice2_B);\n  viennacl::copy(B_start, vcl_slice_B);\n\n\n  // C\n  viennacl::range range1_C(rhs_num, 2*rhs_num);\n  viennacl::range range2_C(2*matrix_size, 3*matrix_size);\n  viennacl::slice slice1_C(rhs_num, 2, rhs_num);\n  viennacl::slice slice2_C(0, 3, matrix_size);\n\n  viennacl::matrix<NumericT, F_B>    vcl_C(rhs_num, matrix_size);\n  viennacl::copy(C_start, vcl_C);\n\n  viennacl::matrix<NumericT, F_B>    vcl_big_range_C(4*rhs_num, 4*matrix_size);\n  viennacl::matrix_range<viennacl::matrix<NumericT, F_B> > vcl_range_C(vcl_big_range_C, range1_C, range2_C);\n  viennacl::copy(C_start, vcl_range_C);\n\n  viennacl::matrix<NumericT, F_B>    vcl_big_slice_C(4*rhs_num, 4*matrix_size);\n  viennacl::matrix_slice<viennacl::matrix<NumericT, F_B> > vcl_slice_C(vcl_big_slice_C, slice1_C, slice2_C);\n  viennacl::copy(C_start, vcl_slice_C);\n\n\n  std::cout << \"Now using A=matrix, B=matrix\" << std::endl;\n  ret = test_solve<NumericT>(epsilon,\n                             A, B_start, C_start,\n                             vcl_A, vcl_B, vcl_C, vcl_B\n                            );\n  if (ret != EXIT_SUCCESS)\n    return ret;\n\n  std::cout << \"Now using A=matrix, B=range\" << std::endl;\n  ret = test_solve<NumericT>(epsilon,\n                             A, B_start, C_start,\n                             vcl_A, vcl_range_B, vcl_range_C, vcl_B\n                            );\n  if (ret != EXIT_SUCCESS)\n    return ret;\n\n  std::cout << \"Now using A=matrix, B=slice\" << std::endl;\n  ret = test_solve<NumericT>(epsilon,\n                             A, B_start, C_start,\n                             vcl_A, vcl_slice_B, vcl_slice_C, vcl_B\n                            );\n  if (ret != EXIT_SUCCESS)\n    return ret;\n\n\n\n  std::cout << \"Now using A=range, B=matrix\" << std::endl;\n  ret = test_solve<NumericT>(epsilon,\n                             A, B_start, C_start,\n                             vcl_range_A, vcl_B, vcl_C, vcl_B\n                            );\n  if (ret != EXIT_SUCCESS)\n    return ret;\n\n  std::cout << \"Now using A=range, B=range\" << std::endl;\n  ret = test_solve<NumericT>(epsilon,\n                             A, B_start, C_start,\n                             vcl_range_A, vcl_range_B, vcl_range_C, vcl_B\n                            );\n  if (ret != EXIT_SUCCESS)\n    return ret;\n\n  std::cout << \"Now using A=range, B=slice\" << std::endl;\n  ret = test_solve<NumericT>(epsilon,\n                             A, B_start, C_start,\n                             vcl_range_A, vcl_slice_B, vcl_slice_C, vcl_B\n                            );\n  if (ret != EXIT_SUCCESS)\n    return ret;\n\n\n\n\n  std::cout << \"Now using A=slice, B=matrix\" << std::endl;\n  ret = test_solve<NumericT>(epsilon,\n                             A, B_start, C_start,\n                             vcl_slice_A, vcl_B, vcl_C, vcl_B\n                            );\n  if (ret != EXIT_SUCCESS)\n    return ret;\n\n  std::cout << \"Now using A=slice, B=range\" << std::endl;\n  ret = test_solve<NumericT>(epsilon,\n                             A, B_start, C_start,\n                             vcl_slice_A, vcl_range_B, vcl_range_C, vcl_B\n                            );\n  if (ret != EXIT_SUCCESS)\n    return ret;\n\n  std::cout << \"Now using A=slice, B=slice\" << std::endl;\n  ret = test_solve<NumericT>(epsilon,\n                             A, B_start, C_start,\n                             vcl_slice_A, vcl_slice_B, vcl_slice_C, vcl_B\n                            );\n  if (ret != EXIT_SUCCESS)\n    return ret;\n\n\n\n\n  return ret;\n\n}\n\n\n\n//\n// Control functions\n//\n\n\ntemplate< typename NumericT, typename Epsilon >\nint test(Epsilon const& epsilon)\n{\n  int ret;\n\n  std::cout << \"////////////////////////////////\" << std::endl;\n  std::cout << \"/// Now testing A=row, B=row ///\" << std::endl;\n  std::cout << \"////////////////////////////////\" << std::endl;\n  ret = test_solve<NumericT, viennacl::row_major, viennacl::row_major>(epsilon);\n  if (ret != EXIT_SUCCESS)\n    return ret;\n\n\n  std::cout << \"////////////////////////////////\" << std::endl;\n  std::cout << \"/// Now testing A=row, B=col ///\" << std::endl;\n  std::cout << \"////////////////////////////////\" << std::endl;\n  ret = test_solve<NumericT, viennacl::row_major, viennacl::column_major>(epsilon);\n  if (ret != EXIT_SUCCESS)\n    return ret;\n\n  std::cout << \"////////////////////////////////\" << std::endl;\n  std::cout << \"/// Now testing A=col, B=row ///\" << std::endl;\n  std::cout << \"////////////////////////////////\" << std::endl;\n  ret = test_solve<NumericT, viennacl::column_major, viennacl::row_major>(epsilon);\n  if (ret != EXIT_SUCCESS)\n    return ret;\n\n  std::cout << \"////////////////////////////////\" << std::endl;\n  std::cout << \"/// Now testing A=col, B=col ///\" << std::endl;\n  std::cout << \"////////////////////////////////\" << std::endl;\n  ret = test_solve<NumericT, viennacl::column_major, viennacl::column_major>(epsilon);\n  if (ret != EXIT_SUCCESS)\n    return ret;\n\n\n\n  return ret;\n}\n\n//\n// -------------------------------------------------------------\n//\nint main()\n{\n   std::cout << std::endl;\n   std::cout << \"----------------------------------------------\" << std::endl;\n   std::cout << \"----------------------------------------------\" << std::endl;\n   std::cout << \"## Test :: BLAS 3 routines\" << std::endl;\n   std::cout << \"----------------------------------------------\" << std::endl;\n   std::cout << \"----------------------------------------------\" << std::endl;\n   std::cout << std::endl;\n\n   int retval = EXIT_SUCCESS;\n\n   std::cout << std::endl;\n   std::cout << \"----------------------------------------------\" << std::endl;\n   std::cout << std::endl;\n   {\n      typedef float NumericT;\n      NumericT epsilon = NumericT(1.0E-3);\n      std::cout << \"# Testing setup:\" << std::endl;\n      std::cout << \"  eps:     \" << epsilon << std::endl;\n      std::cout << \"  numeric: float\" << std::endl;\n      retval = test<NumericT>(epsilon);\n      if ( retval == EXIT_SUCCESS )\n        std::cout << \"# Test passed\" << std::endl;\n      else\n        return retval;\n   }\n   std::cout << std::endl;\n   std::cout << \"----------------------------------------------\" << std::endl;\n   std::cout << std::endl;\n#ifdef VIENNACL_WITH_OPENCL\n   if ( viennacl::ocl::current_device().double_support() )\n#endif\n   {\n      {\n        typedef double NumericT;\n        NumericT epsilon = 1.0E-11;\n        std::cout << \"# Testing setup:\" << std::endl;\n        std::cout << \"  eps:     \" << epsilon << std::endl;\n        std::cout << \"  numeric: double\" << std::endl;\n        retval = test<NumericT>(epsilon);\n        if ( retval == EXIT_SUCCESS )\n          std::cout << \"# Test passed\" << std::endl;\n        else\n          return retval;\n      }\n      std::cout << std::endl;\n      std::cout << \"----------------------------------------------\" << std::endl;\n      std::cout << std::endl;\n   }\n\n   std::cout << std::endl;\n   std::cout << \"------- Test completed --------\" << std::endl;\n   std::cout << std::endl;\n\n\n   return retval;\n}\n", "meta": {"hexsha": "0e8ba0f7e5ed2b4b7c58bfdb5f97fc37ffac31fb", "size": 20589, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/src/blas3_solve.cpp", "max_stars_repo_name": "denis14/ViennaCL-1.5.2", "max_stars_repo_head_hexsha": "fec808905cca30196e10126681611bdf8da5297a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/src/blas3_solve.cpp", "max_issues_repo_name": "denis14/ViennaCL-1.5.2", "max_issues_repo_head_hexsha": "fec808905cca30196e10126681611bdf8da5297a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/src/blas3_solve.cpp", "max_forks_repo_name": "denis14/ViennaCL-1.5.2", "max_forks_repo_head_hexsha": "fec808905cca30196e10126681611bdf8da5297a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.7447916667, "max_line_length": 114, "alphanum_fraction": 0.5773471271, "num_tokens": 5869, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754607093178, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.4584604599682576}}
{"text": "//\n// Copyright \u00a9 2017 Arm Ltd. All rights reserved.\n// SPDX-License-Identifier: MIT\n//\n\n#include <boost/test/unit_test.hpp>\n#include \"ParserFlatbuffersFixture.hpp\"\n#include \"../TfLiteParser.hpp\"\n\n#include <string>\n#include <iostream>\n\nBOOST_AUTO_TEST_SUITE(TensorflowLiteParser)\n\nstruct DepthwiseConvolution2dFixture : public ParserFlatbuffersFixture\n{\n    explicit DepthwiseConvolution2dFixture(const std::string& inputShape,\n                                           const std::string& outputShape,\n                                           const std::string& filterShape,\n                                           const std::string& filterData,\n                                           const std::string& strides,\n                                           const std::string& paddingType,\n                                           const std::string biasShape = \"\",\n                                           const std::string biasData = \"\")\n    {\n        std::string inputTensors = \"[ 0, 2 ]\";\n        std::string biasTensor = \"\";\n        std::string biasBuffer = \"\";\n        if (biasShape.size() > 0 && biasData.size() > 0)\n        {\n            inputTensors = \"[ 0, 2, 3 ]\";\n            biasTensor = R\"(\n                        {\n                            \"shape\": )\" + biasShape + R\"( ,\n                            \"type\": \"INT32\",\n                            \"buffer\": 3,\n                            \"name\": \"biasTensor\",\n                            \"quantization\": {\n                                \"min\": [ 0.0 ],\n                                \"max\": [ 255.0 ],\n                                \"scale\": [ 1.0 ],\n                                \"zero_point\": [ 0 ],\n                            }\n                        } )\";\n            biasBuffer = R\"(\n                    { \"data\": )\" + biasData + R\"(, }, )\";\n        }\n        m_JsonString = R\"(\n            {\n                \"version\": 3,\n                \"operator_codes\": [ { \"builtin_code\": \"DEPTHWISE_CONV_2D\" } ],\n                \"subgraphs\": [ {\n                    \"tensors\": [\n                        {\n                            \"shape\": )\" + inputShape + R\"(,\n                            \"type\": \"UINT8\",\n                            \"buffer\": 0,\n                            \"name\": \"inputTensor\",\n                            \"quantization\": {\n                                \"min\": [ 0.0 ],\n                                \"max\": [ 255.0 ],\n                                \"scale\": [ 1.0 ],\n                                \"zero_point\": [ 0 ],\n                            }\n                        },\n                        {\n                            \"shape\": )\" + outputShape + R\"(,\n                            \"type\": \"UINT8\",\n                            \"buffer\": 1,\n                            \"name\": \"outputTensor\",\n                            \"quantization\": {\n                                \"min\": [ 0.0 ],\n                                \"max\": [ 511.0 ],\n                                \"scale\": [ 2.0 ],\n                                \"zero_point\": [ 0 ],\n                            }\n                        },\n                        {\n                            \"shape\": )\" + filterShape + R\"(,\n                            \"type\": \"UINT8\",\n                            \"buffer\": 2,\n                            \"name\": \"filterTensor\",\n                            \"quantization\": {\n                                \"min\": [ 0.0 ],\n                                \"max\": [ 255.0 ],\n                                \"scale\": [ 1.0 ],\n                                \"zero_point\": [ 0 ],\n                            }\n                        }, )\" + biasTensor + R\"(\n                    ],\n                    \"inputs\": [ 0 ],\n                    \"outputs\": [ 1 ],\n                    \"operators\": [\n                        {\n                            \"opcode_index\": 0,\n                            \"inputs\": )\" + inputTensors + R\"(,\n                            \"outputs\": [ 1 ],\n                            \"builtin_options_type\": \"DepthwiseConv2DOptions\",\n                            \"builtin_options\": {\n                                \"padding\": \")\" + paddingType + R\"(\",\n                                \"stride_w\": )\" + strides+ R\"(,\n                                \"stride_h\": )\" + strides+ R\"(,\n                                \"depth_multiplier\": 1,\n                                \"fused_activation_function\": \"NONE\"\n                            },\n                            \"custom_options_format\": \"FLEXBUFFERS\"\n                        }\n                    ],\n                } ],\n                \"buffers\" : [\n                    { },\n                    { },\n                    { \"data\": )\" + filterData + R\"(, }, )\"\n                    + biasBuffer + R\"(\n                ]\n            }\n        )\";\n        SetupSingleInputSingleOutput(\"inputTensor\", \"outputTensor\");\n    }\n};\n\nstruct DepthwiseConvolution2dSameFixture : DepthwiseConvolution2dFixture\n{\n    DepthwiseConvolution2dSameFixture()\n    : DepthwiseConvolution2dFixture(\"[ 1, 3, 3, 1 ]\",           // inputShape\n                                    \"[ 1, 3, 3, 1 ]\",           // outputShape\n                                    \"[ 1, 3, 3, 1 ]\",           // filterShape\n                                    \"[ 9,8,7, 6,5,4, 3,2,1 ]\",  // filterData\n                                    \"1\",                        // stride w and h\n                                    \"SAME\")                     // padding type\n    {}\n};\n\nBOOST_FIXTURE_TEST_CASE(ParseDepthwiseConv2DSame, DepthwiseConvolution2dSameFixture)\n{\n    RunTest<4, armnn::DataType::QuantisedAsymm8>(\n        0,\n        { 0, 1, 2,\n          3, 4, 5,\n          6, 7, 8 },\n        // the expected values were generated using the example python implementation at\n        // https://eli.thegreenplace.net/2018/depthwise-separable-convolutions-for-machine-learning/\n        // divide the expected values by the output scale, as it is not 1.0\n        {  14/2,  35/2,  38/2,\n           57/2, 120/2, 111/2,\n          110/2, 197/2, 158/2 });\n}\n\nstruct DepthwiseConvolution2dValidFixture : DepthwiseConvolution2dFixture\n{\n    DepthwiseConvolution2dValidFixture ()\n    : DepthwiseConvolution2dFixture(\"[ 1, 3, 3, 1 ]\",           // inputShape\n                                    \"[ 1, 1, 1, 1 ]\",           // outputShape\n                                    \"[ 1, 3, 3, 1 ]\",           // filterShape\n                                    \"[ 9,8,7, 6,5,4, 3,2,1 ]\",  // filterData\n                                    \"1\",                        // stride w and h\n                                    \"VALID\")                    // padding type\n    {}\n};\n\nBOOST_FIXTURE_TEST_CASE(ParseDepthwiseConv2DValid, DepthwiseConvolution2dValidFixture)\n{\n    RunTest<4, armnn::DataType::QuantisedAsymm8>(\n        0,\n        { 0, 1, 2,\n          3, 4, 5,\n          6, 7, 8 },\n        // divide the expected values by the output scale, as it is not 1.0\n        { 120/2 });\n}\n\nstruct DepthwiseConvolution2dSameBiasFixture : DepthwiseConvolution2dFixture\n{\n    DepthwiseConvolution2dSameBiasFixture()\n    : DepthwiseConvolution2dFixture(\"[ 1, 3, 3, 1 ]\",           // inputShape\n                                    \"[ 1, 3, 3, 1 ]\",           // outputShape\n                                    \"[ 1, 3, 3, 1 ]\",           // filterShape\n                                    \"[ 9,8,7, 6,5,4, 3,2,1 ]\",  // filterData\n                                    \"1\",                        // stride w and h\n                                    \"SAME\",                     // padding type\n                                    \"[ 1 ]\",                    // biasShape\n                                    \"[ 10, 0, 0, 0 ]\")          // biasData\n    {}\n};\n\nBOOST_FIXTURE_TEST_CASE(ParseDepthwiseConv2DSameBias, DepthwiseConvolution2dSameBiasFixture)\n{\n    RunTest<4, armnn::DataType::QuantisedAsymm8>(\n        0,\n        { 0, 1, 2,\n          3, 4, 5,\n          6, 7, 8 },\n        // divide the expected values by the output scale, as it is not 1.0\n        { ( 14+10)/2, ( 35+10)/2, ( 38+10)/2,\n          ( 57+10)/2, (120+10)/2, (111+10)/2,\n          (110+10)/2, (197+10)/2, (158+10)/2 });\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "c0767801b38a07af0e159a4ca7e2b7b179f18dc5", "size": 8207, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/armnnTfLiteParser/test/DepthwiseConvolution2D.cpp", "max_stars_repo_name": "VinayKarnam/armnn", "max_stars_repo_head_hexsha": "98525965c7cfecd9bf48297b433b2122cd1b4a1d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-06-26T23:00:46.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-26T23:00:46.000Z", "max_issues_repo_path": "src/armnnTfLiteParser/test/DepthwiseConvolution2D.cpp", "max_issues_repo_name": "VinayKarnam/armnn", "max_issues_repo_head_hexsha": "98525965c7cfecd9bf48297b433b2122cd1b4a1d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/armnnTfLiteParser/test/DepthwiseConvolution2D.cpp", "max_forks_repo_name": "VinayKarnam/armnn", "max_forks_repo_head_hexsha": "98525965c7cfecd9bf48297b433b2122cd1b4a1d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-15T04:31:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-15T04:31:21.000Z", "avg_line_length": 41.035, "max_line_length": 100, "alphanum_fraction": 0.3549409041, "num_tokens": 1823, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754371026367, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.45846045521828593}}
{"text": "#include <iostream>\n\n#include <Eigen/Geometry>\n#include <Eigen/StdVector>\n\n// contains indices of the mesh vertex that are handle points \nEigen::MatrixXi BE;\n\n\nint main(int argc, char **argv){\n\n        std::vector<int> CE_ind = {0,28821, 33603};\n\n\n        BE.resize(2,2);\n        BE << 0,1, \n            1,2;\n\n}", "meta": {"hexsha": "79afb22eadfdfd6b45fad21cc83a8d7d5a0a9daa", "size": 311, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "project/demos/dog_params.cpp", "max_stars_repo_name": "avadesh02/geometric_modeling", "max_stars_repo_head_hexsha": "dc5d884d1295b0393ea3fae4acff9d973acb3cac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "project/demos/dog_params.cpp", "max_issues_repo_name": "avadesh02/geometric_modeling", "max_issues_repo_head_hexsha": "dc5d884d1295b0393ea3fae4acff9d973acb3cac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "project/demos/dog_params.cpp", "max_forks_repo_name": "avadesh02/geometric_modeling", "max_forks_repo_head_hexsha": "dc5d884d1295b0393ea3fae4acff9d973acb3cac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.3684210526, "max_line_length": 62, "alphanum_fraction": 0.6012861736, "num_tokens": 87, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7279754489059775, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.4584604525348136}}
{"text": "#include \"Outer_Parameters.hxx\"\n#include \"Function.hxx\"\n#include \"../sdp_read.hxx\"\n#include \"../sdp_solve.hxx\"\n\n#include \"../ostream_vector.hxx\"\n\n#include <boost/date_time/posix_time/posix_time.hpp>\n#include <boost/property_tree/json_parser.hpp>\n\n// We convert the optimization problem into a regular linear\n// programming problem.\n//\n// 1) Each polynomial in Block::polys adds two variables.  The\n// weights of those polynomials are unbounded, while linear\n// programming requires a strictly positive variable.  So we\n// substitute W_n = w_n+ - w_n+, where both w_n+ and w_n- are\n// strictly positive.  All blocks should have the same number of\n// polynomials, so we only need to look at the first one.\n//\n// 2) Each constraint adds one 'slack' variable s_n.  There is one\n// constraint per coordinate 'x', with each block having multiple,\n// separate coordinates.\n//\n// 3) One more global variable delta, which gives the linear\n// program something to minimize.\n//\n// This turns the problem\n//\n//   A_0 . W > 0\n//   A_1 . W > 0\n//   ...\n//\n// into\n//\n//   min delta\n//\n// where\n//\n//   A_0 . (w_+ - w_-) + delta - s_0 = 0\n//   A_1 . (w_+ - w_-) + delta - s_1 = 0\n//   ...\n//   w_n+, w_n-, s_n, delta >= 0\n//\n// There is a constraint for every point that is sampled.  At the\n// beginning, we sample the min and max for each block, so there are\n// 2*num_blocks constraints.  For the single correlator example, there\n// is an additional constraint on the first block at x=0.  In general\n//\n// => num_rows == num_constraints\n// => num_columns == 2*num_weights + num_constraints + 1\n\nstd::vector<El::BigFloat>\nload_vector(const boost::filesystem::path &vector_path);\n\nvoid read_function_blocks(\n  const boost::filesystem::path &input_file,\n  std::vector<El::BigFloat> &objectives,\n  std::vector<El::BigFloat> &normalization,\n  std::vector<std::vector<std::vector<std::vector<Function>>>> &functions);\n\nvoid read_points(const boost::filesystem::path &input_path,\n                 std::vector<std::vector<El::BigFloat>> &points);\n\nstd::vector<El::BigFloat> compute_optimal(\n  const std::vector<std::vector<std::vector<std::vector<Function>>>> &functions,\n  const std::vector<std::vector<El::BigFloat>> &initial_points,\n  const std::vector<El::BigFloat> &objectives,\n  const std::vector<El::BigFloat> &normalization,\n  const Outer_Parameters &parameters_in);\n\nint main(int argc, char **argv)\n{\n  El::Environment env(argc, argv);\n  Outer_Parameters parameters(argc, argv);\n  if(!parameters.is_valid())\n    {\n      return 0;\n    }\n\n  const int64_t precision(parameters.solver.precision);\n  El::gmp::SetPrecision(precision);\n  // El::gmp wants base-2 bits, but boost::multiprecision wants\n  // base-10 digits.\n  Boost_Float::default_precision(precision * log(2) / log(10));\n\n  if(parameters.verbosity >= Verbosity::regular && El::mpi::Rank() == 0)\n    {\n      std::cout << \"Outer_Limits started at \"\n                << boost::posix_time::second_clock::local_time() << '\\n'\n                << parameters << '\\n'\n                << std::flush;\n    }\n\n  std::vector<El::BigFloat> objectives, normalization;\n  std::vector<std::vector<std::vector<std::vector<Function>>>> functions;\n  read_function_blocks(parameters.functions_path, objectives, normalization,\n                       functions);\n\n  std::vector<std::vector<El::BigFloat>> initial_points;\n  read_points(parameters.points_path, initial_points);\n\n  std::vector<El::BigFloat> weights(compute_optimal(\n    functions, initial_points, objectives, normalization, parameters));\n\n  El::BigFloat optimal(0);\n  for(size_t index(0); index < objectives.size(); ++index)\n    {\n      optimal += objectives[index] * weights[index];\n    }\n  if(parameters.verbosity >= Verbosity::regular && El::mpi::Rank() == 0)\n    {\n      set_stream_precision(std::cout);\n      std::cout << \"optimal: \" << optimal << \"\\n\";\n    }\n  if(El::mpi::Rank() == 0)\n    {\n      if(parameters.verbosity >= Verbosity::regular)\n        {\n          std::cout << \"Saving solution to \" << parameters.output_path << \"\\n\";\n        }\n      boost::filesystem::ofstream output(parameters.output_path);\n      set_stream_precision(output);\n      output << \"{\\n  \\\"optimal\\\": \\\"\" << optimal << \"\\\",\\n\"\n             << \"  \\\"y\\\":\\n  [\\n\";\n      for(auto weight(weights.begin()); weight != weights.end(); ++weight)\n        {\n          if(weight != weights.begin())\n            {\n              output << \",\\n\";\n            }\n          output << \"    \\\"\" << *weight << \"\\\"\";\n        }\n\n      output << \"\\n  ],\\n  \\\"options\\\": \\n\";\n      boost::property_tree::write_json(output, to_property_tree(parameters));\n      output << \"}\\n\";\n    }\n}\n", "meta": {"hexsha": "41431e305d76148e4981f89194d81ebf4082b00b", "size": 4629, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/outer_limits/main.cxx", "max_stars_repo_name": "ChrisPattison/sdpb", "max_stars_repo_head_hexsha": "4668f72c935e7feba705dd8247d9aacb23185f1c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 45.0, "max_stars_repo_stars_event_min_datetime": "2015-02-10T15:45:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T07:45:01.000Z", "max_issues_repo_path": "src/outer_limits/main.cxx", "max_issues_repo_name": "ChrisPattison/sdpb", "max_issues_repo_head_hexsha": "4668f72c935e7feba705dd8247d9aacb23185f1c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 58.0, "max_issues_repo_issues_event_min_datetime": "2015-02-27T10:03:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-10T04:21:42.000Z", "max_forks_repo_path": "src/outer_limits/main.cxx", "max_forks_repo_name": "ChrisPattison/sdpb", "max_forks_repo_head_hexsha": "4668f72c935e7feba705dd8247d9aacb23185f1c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 38.0, "max_forks_repo_forks_event_min_datetime": "2015-02-10T11:11:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-11T20:59:42.000Z", "avg_line_length": 33.0642857143, "max_line_length": 80, "alphanum_fraction": 0.6411751998, "num_tokens": 1190, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.45846045253481355}}
{"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\u00e4nkt), 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_NEW_ALGEBRAIC_CONCEPTS_INCLUDE\n#define MTL_NEW_ALGEBRAIC_CONCEPTS_INCLUDE\n\n#include <concepts>\n#include <boost/numeric/linear_algebra/intrinsic_concept_maps.hpp>\n#include <boost/numeric/linear_algebra/operators.hpp>\n\n\nnamespace math {\n\nconcept Commutative<typename Operation, typename Element>\n  : std::Callable2<Operation, Element, Element>\n{\n    axiom Commutativity(Operation op, Element x, Element y)\n    {\n\top(x, y) == op(y, x); \n    }   \n};\n\n\nconcept SemiGroup<typename Operation, typename Element>\n  : std::Callable2<Operation, Element, Element>\n{\n    axiom Associativity(Operation op, Element x, Element y, Element z)\n    {\n\top(x, op(y, z)) == op(op(x, y), z); \n    }\n};\n\n\nconcept Monoid<typename Operation, typename Element>\n  : SemiGroup<Operation, Element> \n{\n    typename identity_result_type;\n    identity_result_type identity(Operation, Element);\n    \n    axiom Neutrality(Operation op, Element x)\n    {\n\top( x, identity(op, x) ) == x;\n\top( identity(op, x), x ) == x;\n    }\n};\n\n\nauto concept Inversion<typename Operation, typename Element>\n{\n    typename result_type;\n    result_type inverse(Operation, Element);\n    \n};\n\n\nconcept PIMonoid<typename Operation, typename Element>\n  : Monoid<Operation, Element>, \n    Inversion<Operation, Element>\n{\n    bool is_invertible(Operation, Element);\n    \n    requires std::Convertible<Inversion<Operation, Element>::result_type, Element>;\n\n    axiom Invertibility(Operation op, Element x)\n    {\n\t// Only for invertible elements:\n\tif (is_invertible(op, x))\n\t    op( x, inverse(op, x) ) == identity(op, x); \n\tif ( is_invertible(op, x) )\n\t    op( inverse(op, x), x ) == identity(op, x); \n    }\n}\n\n#if 0 \n    // Alternative approach to convert the result of inversion to Element\n    // Unfortunately, this doesn't compile\n    template <typename Operation, typename Element>\n        requires PIMonoid<Operation, Element>\n    concept_map PIMonoid<Operation, Inversion<Operation, Element>::result_type> {}\n#endif\n\n\nconcept Group<typename Operation, typename Element>\n  : PIMonoid<Operation, Element>\n{\n    bool is_invertible(Operation, Element) { return true; }\n    \n    // Just in case somebody redefines is_invertible\n    axiom AlwaysInvertible(Operation op, Element x)\n    {\n\tis_invertible(op, x);\n    }\n\n    // In fact this is implied by AlwaysInvertible and inherited Invertibility axiom\n    // Maybe remove\n    axiom GlobalInvertibility(Operation op, Element x)\n    {\n\top( x, inverse(op, x) ) == identity(op, x);\n\top( inverse(op, x), x ) == identity(op, x);\n    }\n};\n\n\nauto concept AbelianGroup<typename Operation, typename Element>\n  : Group<Operation, Element>, Commutative<Operation, Element>\n{};\n    \n\n// =======================\n// Operator-based concepts\n// =======================\n\n\nconcept Additive<typename Element>\n  : std::HasPlus<Element>\n{\n    typename plus_assign_result_type;  \n    plus_assign_result_type operator+=(Element& x, Element y)\n    {\n\tx= x + y; return x;\n    }\n    \n    requires std::Convertible<plus_assign_result_type, Element&>;\n    \n    // Do we need the opposite conversion too?\n    // This line produces a compiler error\n    // requires std::Convertible<add<Element>::result_type,\n    //                           std::HasPlus<Element>::result_type>;\n\n    axiom Consistency(add<Element> op, Element x, Element y)\n    {\n\top(x, y) == x + y;\n\top(x, y) == (x += y, x);\n    }\n}\n\n    \nauto concept AdditiveCommutative<typename Element>\n  : Additive<Element>,\n    Commutative< add<Element>, Element >\n{}\n\n    \nauto concept AdditiveSemiGroup<typename Element>\n  : Additive<Element>,\n    SemiGroup< add<Element>, Element >\n{}\n\n    \n#ifdef COMPILER_WITHOUT_OVERLOAD_ERROR  // Uncompilable due to error in compiler\nconcept AdditiveMonoid<typename Element>\n  : AdditiveSemiGroup<Element>,\n    Monoid< add<Element>, Element >\n{\n    Element zero(Element x)\n    {\n\treturn identity(add<Element>(), x);\n    }\n    \n    // If we don't use the default definition\n    axiom IdentityConsistency (add<Element> op, Element x)\n    {\n\tzero(x) == identity(op, x);\n    }\n};\n\nconcept AdditivePIMonoid<typename Element>\n  : std::HasMinus<Element>, AdditiveMonoid<Element>, \n    PIMonoid< add<Element>, Element >\n{\n    typename minus_assign_result_type;  \n    minus_assign_result_type operator-=(Element& x, Element y)\n    {\n\tx= x - y; return x;\n    }\n    \n    requires std::Convertible<minus_assign_result_type, Element&>;\n    \n    typename unary_result_type;  \n    unary_result_type operator-(Element x)\n    {\n\treturn zero(x) - x;\n    }\n    \n    axiom InverseConsistency(add<Element> op, Element x, Element y)\n    {\n\t// consistency between additive and functor concept\n\tif ( is_invertible(op, y) )\n\t    op(x, inverse(op, y)) == x - y;\n\tif ( is_invertible(op, y) )\n\t    op(x, y) == (x -= y, x);\n\t\n\t// consistency of unary inversion\n\tif ( is_invertible(op, y) )\n\t    inverse(op, y) == -y;                      \n\n\t// consistency between unary and binary -\n\tif ( is_invertible(op, x) )\n\t    identity(op, x) - x == -x;                 \n    }\n}\n\n\nauto concept AdditiveGroup<typename Element>\n  : AdditivePIMonoid<Element>,\n    Group< add<Element>, Element >\n{};\n\n\nauto concept AdditiveAbelianGroup<typename Element>\n  : AdditiveGroup<Element>,\n    Commutative< add<Element>, Element >\n{}\n\n#endif\n\n\nconcept Multiplicative<typename Element>\n  : std::HasMultiply<Element>\n{\n    typename times_assign_result_type;  \n    times_assign_result_type operator*=(Element& x, Element y)\n    {\n\tx= x * y; return x;\n    }\n\t\n    requires std::Convertible<times_assign_result_type, Element&>;\n    \n    // Do we need the opposite conversion too?\n    // This line produces a compiler error\n    // requires std::Convertible<mult<Element>::result_type,\n    //                           std::HasMultiply<Element>::result_type>;\n\n    axiom Consistency(mult<Element> op, Element x, Element y)\n    {\n\top(x, y) == x * y;\n\top(x, y) == (x *= y, x);\n    }\n}\n\n\nauto concept MultiplicativeCommutative<typename Element>\n  : Multiplicative<Element>,\n    Commutative< mult<Element>, Element >\n{}\n\n    \nauto concept MultiplicativeSemiGroup<typename Element>\n  : Multiplicative<Element>,\n    SemiGroup< mult<Element>, Element >\n{}\n\n\n#ifdef COMPILER_WITHOUT_OVERLOAD_ERROR  // Uncompilable due to error in compiler\nconcept MultiplicativeMonoid<typename Element>\n  : MultiplicativeSemiGroup<Element>,\n    Monoid< mult<Element>, Element >\n{\n    Element one(Element x)\n    {\n\treturn identity(mult<Element>(), x);\n    }\n\t\n    // If we don't use the default definition\n    axiom IdentityConsistency (math::mult<Element> op, Element x)\n    {\n\tone(x) == identity(op, x);\n    }\n};\n\nconcept MultiplicativePIMonoid<typename Element>\n  : std::HasDivide<Element>, MultiplicativeMonoid<Element>,\n    PIMonoid< mult<Element>, Element >\n{\n    typename divide_assign_result_type;  \n    divide_assign_result_type operator/=(Element& x, Element y)\n    {\n\tx= x / y; return x;\n    }\n    \n    requires std::Convertible<divide_assign_result_type, Element&>;\n    \n    axiom InverseConsistency(mult<Element> op, Element x, Element y)\n    {\n\t// consistency between multiplicative and functor concept\n\tif ( is_invertible(op, y) )\n\t    op(x, inverse(op, y)) == x / y;\n\tif ( is_invertible(op, y) )\n\t    op(x, y) == (x /= y, x);\n    }\n}\n\n\nauto concept MultiplicativeGroup<typename Element>\n  : MultiplicativePIMonoid<Element>,\n    Group< mult<Element>, Element >\n{};\n\n\nauto concept MultiplicativeAbelianGroup<typename Element>\n  : MultiplicativeGroup<Element>,\n    Commutative< mult<Element>, Element >\n{}\n\n\n// ==========================\n// Concepts with 2 operations\n// ==========================\n\n\n\nconcept Distributive<typename AddOp, typename MultOp, typename Element>\n{\n    axiom Distributivity(AddOp add, MultOp mult, Element x, Element y, Element z)\n    {\n\t// From left\n\tmult(x, add(y, z)) == add(mult(x, y), mult(x, z));\n\t// from right\n\tmult(add(x, y), z) == add(mult(x, z), mult(y, z));\n    }\n}\n\n\nauto concept Ring<typename AddOp, typename MultOp, typename Element>\n  : AbelianGroup<AddOp, Element>,\n    SemiGroup<MultOp, Element>,\n    Distributive<AddOp, MultOp, Element>\n{}\n\n\nauto concept RingWithIdentity<typename AddOp, typename MultOp, typename Element>\n  : Ring<AddOp, MultOp, Element>,\n    Monoid<MultOp, Element>\n{}\n\n\nconcept DivisionRing<typename AddOp, typename MultOp, typename Element>\n  : RingWithIdentity<AddOp, MultOp, Element>,\n    Inversion<MultOp, Element>\n{\n    // 0 != 1, otherwise trivial\n    axiom ZeroIsDifferentFromOne(AddOp add, MultOp mult, Element x)\n    {\n\tidentity(add, x) != identity(mult, x);       \n    }\n    \n    // Non-zero divisibility from left and from right\n    axiom NonZeroDivisibility(AddOp add, MultOp mult, Element x)\n    {\n\tif (x != identity(add, x))\n\t    mult(inverse(mult, x), x) == identity(mult, x);\n\tif (x != identity(add, x))\n\t    mult(x, inverse(mult, x)) == identity(mult, x);\n    }\n}    \n\n\nauto concept Field<typename AddOp, typename MultOp, typename Element>\n  : DivisionRing<AddOp, MultOp, Element>,\n    Commutative<MultOp, Element>\n{}\n\n\nauto concept OperatorRing<typename Element>\n  : AdditiveAbelianGroup<Element>,\n    MultiplicativeSemiGroup<Element>,\n    Ring<add<Element>, mult<Element>, Element>\n{}\n\n        \nauto concept OperatorRingWithIdentity<typename Element>\n  : OperatorRing<Element>,\n    MultiplicativeMonoid<Element>,\n    RingWithIdentity<add<Element>, mult<Element>, Element>\n{}\n       \n \nauto concept OperatorDivisionRing<typename Element>\n  : OperatorRingWithIdentity<Element>,\n    MultiplicativePIMonoid<Element>, \n    DivisionRing<add<Element>, mult<Element>, Element>\n{}    \n\n\nauto concept OperatorField<typename Element>\n  : OperatorDivisionRing<Element>,\n    Field<add<Element>, mult<Element>, Element>\n{}\n        \n\n\n#endif\n\nconcept IntrinsicType<typename T> {}\n\nconcept IntrinsicArithmetic<typename T> : IntrinsicType<T> {}\n\nconcept IntrinsicIntegral<typename T> : IntrinsicArithmetic<T> {}\n\nconcept IntrinsicSignedIntegral<typename T> \n  : std::SignedIntegralLike<T>,\n    IntrinsicIntegral<T>\n{}\n\nconcept IntrinsicUnsignedIntegral<typename T> \n  : std::UnsignedIntegralLike<T>,\n    IntrinsicIntegral<T>\n{}\n\nconcept IntrinsicFloatingPoint<typename T>\n  : std::FloatingPointLike<T>,\n    IntrinsicArithmetic<T>\n{}\n\n\n\n\n#if 0\n\n// ====================\n// Default Concept Maps\n// ====================\n\n// ==============\n// Arithmetic\n// ==============\n\n// ----------------\n// Signed integrals\n// ----------------\n\ntemplate <typename T>\n  requires IntrinsicSignedIntegral<T>\nconcept_map OperatorRingWithIdentity<T> {}\n\ntemplate <typename T>\n  requires IntrinsicSignedIntegral<T>\nconcept_map MultiplicativeCommutative<T> {}\n\n// ------------------\n// Unsigned integrals\n// ------------------\n\n\ntemplate <typename T>\n  requires IntrinsicUnsignedIntegral<T>\nconcept_map AdditiveCommutative<T> {}\n\ntemplate <typename T>\n  requires IntrinsicUnsignedIntegral<T>\nconcept_map AdditiveMonoid<T> {}\n\ntemplate <typename T>\n  requires IntrinsicUnsignedIntegral<T>\nconcept_map MultiplicativeCommutative<T> {}\n\ntemplate <typename T>\n  requires IntrinsicUnsignedIntegral<T>\nconcept_map MultiplicativeMonoid<T> {}\n\n// ---------------\n// Floationg Point\n// ---------------\n\n\ntemplate <typename T>\n  requires IntrinsicFloatingPoint<T>\nconcept_map Field<T> {}\n\ntemplate <typename T>\n  requires IntrinsicFloatingPoint<T>\nconcept_map Field< std::complex<T> > {}\n\n\n// ===========\n// Min and Max\n// ===========\n\n\ntemplate <typename T>\n  requires IntrinsicArithmetic<T>\nconcept_map Commutative< max<T>, T > {}\n\ntemplate <typename T>\n  requires IntrinsicArithmetic<T>\nconcept_map Monoid< max<T>, T > {}\n\ntemplate <typename T>\n  requires IntrinsicArithmetic<T>\nconcept_map Commutative< min<T>, T > {}\n\ntemplate <typename T>\n  requires IntrinsicArithmetic<T>\nconcept_map Monoid< min<T>, T > {}\n\n\n// ==========\n// And and Or\n// ==========\n\ntemplate <typename T>\n  requires Intrinsic<T> && std::HasLogicalAnd<T>\nconcept_map Commutative< std::logical_and<T>, T > {}\n\ntemplate <typename T>\n  requires Intrinsic<T> && std::HasLogicalAnd<T>\nconcept_map Monoid< std::logical_and<T>, T > {}\n\ntemplate <typename T>\n  requires Intrinsic<T> && std::HasLogicalOr<T>\nconcept_map Commutative< std::logical_or<T>, T > {}\n\ntemplate <typename T>\n  requires Intrinsic<T> && std::HasLogicalOr<T>\nconcept_map Monoid< std::logical_or<T>, T > {}\n\ntemplate <typename T>\n  requires Intrinsic<T> && std::HasLogicalAnd<T> && std::HasLogicalOr<T>\nconcept_map Distributive<std::logical_and<T>, std::logical_or<T>, T> {}\n\ntemplate <typename T>\n  requires Intrinsic<T> && std::HasLogicalAnd<T> && std::HasLogicalOr<T>\nconcept_map Distributive<std::logical_or<T>, std::logical_and<T>, T> {}\n\n\n// ==================\n// Bitwise operations\n// ==================\n\n// not yet defined\n\ntemplate <typename T>\n  requires IntrinsicIntegral<T>\nconcept_map Commutative< bit_and<T>, T > {}\n\ntemplate <typename T>\n  requires IntrinsicIntegral<T>\nconcept_map Monoid< bit_and<T>, T > {}\n\ntemplate <typename T>\n  requires IntrinsicIntegral<T>\nconcept_map Commutative< bit_or<T>, T > {}\n\ntemplate <typename T>\n  requires IntrinsicIntegral<T>\nconcept_map Monoid< bit_or<T>, T > {}\n\ntemplate <typename T>\n  requires IntrinsicIntegral<T>\nconcept_map Distributive<bit_and<T>, bit_or<T>, T> {}\n\ntemplate <typename T>\n  requires IntrinsicIntegral<T> \nconcept_map Distributive<bit_or<T>, bit_and<T>, T> {}\n\ntemplate <typename T>\n  requires IntrinsicIntegral<T>\nconcept_map Commutative< bit_xor<T>, T > {}\n\ntemplate <typename T>\n  requires IntrinsicIntegral<T>\nconcept_map SemiGroup< bit_xor<T>, T > {}\n\n// ====================\n// String concatenation\n// ====================\n\nconcept_map AdditiveMonoid<std::string> {}\n\n\n#endif\n\n\n\n} // namespace math\n\n#endif // MTL_NEW_ALGEBRAIC_CONCEPTS_INCLUDE\n", "meta": {"hexsha": "3d955cff6d1e2c9d761e04b83517557c4352e32f", "size": 14136, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/linear_algebra/new_concepts.hpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "lib/mtl4/boost/numeric/linear_algebra/new_concepts.hpp", "max_issues_repo_name": "spraetor/amdis2", "max_issues_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "lib/mtl4/boost/numeric/linear_algebra/new_concepts.hpp", "max_forks_repo_name": "spraetor/amdis2", "max_forks_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 24.0817717206, "max_line_length": 94, "alphanum_fraction": 0.6720430108, "num_tokens": 3492, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754607093178, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.4584604498513404}}
{"text": "//\n// Created by huangkun on 2020/8/26.\n//\n\n#include <Eigen/SparseCholesky>\n#include <cmath>\n#include <algorithm>\n#include <numeric>\n\n#include <opengv2/spline/BsplineSO3.hpp>\n\nopengv2::BsplineSO3::BsplineSO3(int p,\n                                const std::vector<Sophus::SO3d, Eigen::aligned_allocator<Sophus::SO3d>> &samples,\n                                int controlPointsNum, const std::vector<double> &correspondingUs,\n                                const std::vector<std::vector<Eigen::Vector3d>> &derivativeSamples,\n                                double derivativeWeight) : degree_(p), derivativeWeight_(derivativeWeight) {\n    // if dataPoints given, then do approximation\n    if (!samples.empty()) {\n        samples_ = samples;\n\n        // Data registration\n        if (!correspondingUs.empty()) {\n            correspondingUs_ = correspondingUs;\n        } else {\n            // Data registration using chord length, Range: [0,1]\n            correspondingUs_.resize(samples_.size());\n\n            double d = 0;\n            for (int i = 1; i < samples_.size(); ++i) {\n                d += 2 * std::acos((samples_[i] * samples_[i - 1].inverse()).unit_quaternion().w());\n            }\n\n            correspondingUs_.front() = 0;\n            correspondingUs_.back() = 1;\n            for (int i = 1; i < samples_.size() - 1; ++i) {\n                correspondingUs_[i] = correspondingUs_[i - 1] +\n                                      2 * std::acos((samples_[i] * samples_[i - 1].inverse()).unit_quaternion().w()) /\n                                      d;\n            }\n        }\n\n        // derivative\n        if (!derivativeSamples.empty()) {\n            derivativeSamples_ = derivativeSamples;\n        }\n\n        // initialization\n        if (controlPointsNum < 0)\n            controlPointsNum = std::max(int(samples_.size() / 3), degree_ + 1);\n        if (controlPointsNum <= degree_) {\n            std::cerr << \"BsplineSO3 Constructor: control points number should greater than degree!\" << std::endl;\n            return;\n        }\n        knotSpacing(controlPointsNum);\n        initialGuess();\n        optimizeCP();\n    }\n}\n\nvoid opengv2::BsplineSO3::knotSpacing(int controlPointsNum) {\n    /*** knot initialization (9.68) in NURBS book ***/\n    knotVector_.resize(controlPointsNum + degree_ + 1);\n    std::fill_n(knotVector_.begin(), degree_ + 1, correspondingUs_.front());\n    std::fill_n(knotVector_.rbegin(), degree_ + 1, correspondingUs_.back());\n    double d = samples_.size() / double(controlPointsNum - degree_);\n    for (int j = 1; j <= controlPointsNum - 1 - degree_; j++) {\n        int i = floor(j * d);\n        double alpha = j * d - i;\n        knotVector_[degree_ + j] = (1 - alpha) * correspondingUs_[i - 1] + alpha * correspondingUs_[i];\n    }\n}\n\nvoid opengv2::BsplineSO3::derBasisFuns(double u, size_t spanIdx, int derivativeLimit,\n                                       std::vector<std::vector<double>> &ders) const {\n    // check\n    if (knotVector_.empty()) {\n        std::cerr << \"Function derBasisFuns: knotVector is empty!\" << std::endl;\n        return;\n    }\n\n    ders.resize(derivativeLimit + 1);\n    for (auto itr = ders.begin(); itr != ders.end(); itr++) {\n        itr->assign(degree_, 0);\n    }\n\n    std::vector<std::vector<double>> basisN;\n\n    // 0-th derivative: $\\beta_{k,i}(u) = \\sum_{j=i}^{k} N_{j,p}(u), i \\in [k-p+1, k]$.\n    // since \\sum_{j=k-p}^{k} N_{j,p}(u) = 1\n    basis(u, spanIdx, 0, degree_, basisN);\n    ders[0][degree_ - 1] = basisN[0][degree_];\n    for (int i = degree_ - 2; i >= 0; i--) {\n        ders[0][i] = ders[0][i + 1] + basisN[0][i + 1];\n    }\n\n    // \\alpha-th derivative, \\alpha >= 1\n    if (derivativeLimit > 0) {\n        basisN.clear();\n        basis(u, spanIdx, derivativeLimit - 1, degree_ - 1, basisN);\n\n        for (int alpha = 1; alpha <= derivativeLimit; alpha++) {\n            for (int i = spanIdx - degree_ + 1; i <= spanIdx; i++) {\n                ders[alpha][i - (spanIdx - degree_ + 1)] =\n                        degree_ / (knotVector_[i + degree_] - knotVector_[i]) *\n                        basisN[alpha][i - (spanIdx - degree_ + 1)];\n            }\n        }\n    }\n}\n\nvoid opengv2::BsplineSO3::basis(double u, size_t spanIdx, int derivativeLimit, int degree,\n                                std::vector<std::vector<double>> &ders) const {\n    ders.resize(derivativeLimit + 1);\n    for (auto &it:ders) {\n        it.assign(degree + 1, 0);\n    }\n\n    double ndu[degree + 1][degree + 1]; // store the basis functions and knot differences\n\n    // store (in an alternating fashion) the two most recently computed rows a_{k,j} and a_{k-1,j}\n    double a[2][degree + 1];\n\n    std::vector<double> left, right;\n    left.resize(degree + 1);\n    right.resize(degree + 1);\n\n    ndu[0][0] = 1;\n    for (int j = 1; j <= degree; j++) {\n        left[j] = u - knotVector_[spanIdx + 1 - j];\n        right[j] = knotVector_[spanIdx + j] - u;\n        double saved = 0.0;\n        for (int r = 0; r < j; ++r) {\n            ndu[j][r] = right[r + 1] + left[j - r];\n            double temp = ndu[r][j - 1] / ndu[j][r];\n\n            ndu[r][j] = saved + right[r + 1] * temp;\n            saved = left[j - r] * temp;\n        }\n        ndu[j][j] = saved;\n    }\n\n    /* Load the basis functions */\n    for (int j = 0; j <= degree; j++)\n        ders[0][j] = ndu[j][degree];\n\n    if (derivativeLimit > 0) {\n        /*** This section computes the derivatives (Eq.[2.9]) ***/\n        /* Load over function index */\n        for (int r = 0; r <= degree; r++) {\n            int s1 = 0, s2 = 1; // Alternate rows in array a\n            a[0][0] = 1;\n\n            // loop to compute kth derivative\n            for (int k = 1; k <= derivativeLimit; k++) {\n                double d = 0;\n                int rk = r - k, pk = degree - k;\n                if (r >= k) {\n                    a[s2][0] = a[s1][0] / ndu[pk + 1][rk];\n                    d = a[s2][0] * ndu[rk][pk];\n                }\n\n                int j1, j2;\n                if (rk >= -1)\n                    j1 = 1;\n                else\n                    j1 = -rk;\n\n                if (r - 1 <= pk)\n                    j2 = k - 1;\n                else\n                    j2 = degree - r;\n\n                for (int j = j1; j <= j2; j++) {\n                    a[s2][j] = (a[s1][j] - a[s1][j - 1]) / ndu[pk + 1][rk + j];\n                    d += a[s2][j] * ndu[rk + j][pk];\n                }\n\n                if (r <= pk) {\n                    a[s2][k] = -a[s1][k - 1] / ndu[pk + 1][r];\n                    d += a[s2][k] * ndu[r][pk];\n                }\n\n                ders[k][r] = d;\n\n                // switch rows\n                std::swap(s1, s2);\n            }\n        }\n\n        /* Multiply through by correct factors (Eq. [2.9]) */\n        int r = degree;\n        for (int k = 1; k <= derivativeLimit; ++k) {\n            for (int j = 0; j <= degree; j++)\n                ders[k][j] *= r;\n\n            r *= (degree - k);\n        }\n    }\n}\n\n// TODO: an acceleration penalty factor\nvoid opengv2::BsplineSO3::initialGuess() {\n    /*** check ***/\n    if (samples_.empty()) {\n        std::cerr << \"Function initialGuess: dataPoints is empty!\" << std::endl;\n        return;\n    }\n    if (knotVector_.empty()) {\n        std::cerr << \"Function initialGuess: knotVector is empty!\" << std::endl;\n        return;\n    }\n\n    int controlPointsNum = knotVector_.size() - degree_ - 1;\n\n    // initialize controlPoints\n    controlPoints_.resize(controlPointsNum);\n    controlPoints_.front() = samples_.front();\n    controlPoints_.back() = samples_.back();\n\n    /*** Problem ***/\n    Eigen::SparseMatrix<double> N(samples_.size(), controlPointsNum);\n    Eigen::SparseMatrix<double> M(samples_.size(), controlPointsNum);\n    std::vector<std::vector<double>> ders;\n    for (int k = 0; k < samples_.size(); ++k) {\n        size_t spanIdx = findSpan(correspondingUs_[k]);\n        basis(correspondingUs_[k], spanIdx, 0, degree_, ders);\n\n        for (int j = 0; j <= degree_; ++j) {\n            if (ders[0][j] != 0)\n                N.insert(k, spanIdx - degree_ + j) = ders[0][j]; // N_{i-p+j,p}^{0}(\\bar{u}_k)\n        }\n    }\n\n    // formulating B\n    std::vector<Eigen::Matrix<double, 4, 1>, Eigen::aligned_allocator<Eigen::Matrix<double, 4, 1>>> B;\n    B.assign(controlPointsNum - 2, Eigen::Matrix<double, 4, 1>::Zero());\n    for (int l = 1; l <= controlPointsNum - 2; ++l) {\n        // for l-th col of N\n        for (Eigen::SparseMatrix<double>::InnerIterator it(N, l); it; ++it) {\n            // N_{l,p}(\\bar{u}_k), valid for column-major\n            int k = it.row();\n            if (k != 0 && k != samples_.size() - 1) {\n                B[l - 1] += it.value() * (samples_[k].unit_quaternion().coeffs() -\n                                          N.coeff(k, 0) * samples_.front().unit_quaternion().coeffs() -\n                                          N.coeff(k, controlPointsNum - 1) *\n                                          samples_.back().unit_quaternion().coeffs());\n            }\n        }\n    }\n\n    // formulating M,N\n    Eigen::SparseMatrix<double> Nc = N.block(1, 1, samples_.size() - 2, controlPointsNum - 2);\n    Eigen::SparseMatrix<double> A = Nc.transpose() * Nc;\n\n    // solving\n    A.makeCompressed();\n    Eigen::SimplicialLDLT<Eigen::SparseMatrix<double>> solver;\n    solver.compute(A);\n    if (solver.info() != Eigen::Success) {\n        std::cerr << \"Function initialGuess: decomposition failed!\" << std::endl;\n        return;\n    }\n    Eigen::VectorXd b(controlPointsNum - 2);\n\n    std::vector<Eigen::Matrix<double, 4, 1>, Eigen::aligned_allocator<Eigen::Matrix<double, 4, 1>>> cp;\n    cp.resize(controlPointsNum - 2);\n    for (int i = 0; i < 4; i++) {\n        for (int j = 0; j < B.size(); ++j) {\n            b[j] = B[j][i];\n        }\n        Eigen::VectorXd x = solver.solve(b);\n        if (solver.info() != Eigen::Success) {\n            std::cerr << \"Function initialGuess: solving failed!\" << std::endl;\n            return;\n        }\n        for (int j = 1; j <= controlPointsNum - 2; ++j) {\n            cp[j - 1][i] = x[j - 1];\n        }\n    }\n    for (int j = 1; j <= controlPointsNum - 2; ++j) {\n        controlPoints_[j].setQuaternion(Eigen::Quaterniond(cp[j - 1]));\n    }\n}\n\nvoid opengv2::BsplineSO3::optimizeCP() {\n    ceres::Problem problem;\n    ceres::LocalParameterization *SO3_parameterization = new LocalParameterizationSO3();\n\n    // Specify local update rule for our parameter\n    for (Sophus::SO3d &cp:controlPoints_) {\n        problem.AddParameterBlock(cp.data(), Sophus::SO3d::num_parameters, SO3_parameterization);\n    }\n    problem.SetParameterBlockConstant(controlPoints_.front().data());\n    problem.SetParameterBlockConstant(controlPoints_.back().data());\n\n    // pre-calculate spline basis\n    std::unordered_map<int, std::shared_ptr<std::vector<std::vector<double>>>> basisFuns;\n    std::unordered_map<int, size_t> spanIdxs;\n    for (int i = 0; i < samples_.size(); ++i) {\n        double u = correspondingUs_[i];\n        auto basisFun = std::make_shared<std::vector<std::vector<double>>>();\n        size_t spanIdx = findSpan(u);\n        derBasisFuns(u, spanIdx, 0, *basisFun);\n\n        basisFuns[i] = basisFun;\n        spanIdxs[i] = spanIdx;\n    }\n\n    // Create and add cost functions. Derivatives will be evaluated via automatic differentiation\n    for (int i = 0; i < samples_.size(); ++i) {\n        auto spanIdx = spanIdxs[i];\n        ceres::CostFunction *cost_function;\n        if (degree_ == 4) {\n            cost_function = P4ApproximationError::Create(samples_[i].inverse(), basisFuns[i]);\n            problem.AddResidualBlock(cost_function, nullptr,\n                                     controlPoints_[spanIdx - 4 + 0].data(),\n                                     controlPoints_[spanIdx - 4 + 1].data(),\n                                     controlPoints_[spanIdx - 4 + 2].data(),\n                                     controlPoints_[spanIdx - 4 + 3].data(),\n                                     controlPoints_[spanIdx - 4 + 4].data());\n        } else if (degree_ == 3) {\n            cost_function = P3ApproximationError::Create(samples_[i].inverse(), basisFuns[i]);\n            problem.AddResidualBlock(cost_function, nullptr,\n                                     controlPoints_[spanIdx - 3 + 0].data(),\n                                     controlPoints_[spanIdx - 3 + 1].data(),\n                                     controlPoints_[spanIdx - 3 + 2].data(),\n                                     controlPoints_[spanIdx - 3 + 3].data());\n        }\n    }\n\n    // Set solver options (precision / method)\n    ceres::Solver::Options options;\n    options.gradient_tolerance = Sophus::Constants<double>::epsilon();\n    options.function_tolerance = Sophus::Constants<double>::epsilon();\n    options.linear_solver_type = ceres::SPARSE_NORMAL_CHOLESKY;\n\n    // Solve\n    ceres::Solver::Summary summary;\n    Solve(options, &problem, &summary);\n    std::cout << summary.BriefReport() << std::endl;\n}\n\nvoid opengv2::BsplineSO3::evaluate(double u, int derivativeLimit, Sophus::SO3d &val,\n                                   std::vector<Eigen::Vector3d> &Ders) const {\n    if (controlPoints_.empty()) {\n        std::cerr << \"Function evaluate: controlPoints is empty!\" << std::endl;\n        return;\n    }\n    if (derivativeLimit > 2) {\n        std::cerr << \"Function evaluate: derivativeLimit should <= 2!\" << std::endl;\n        return;\n    }\n    Ders.clear();\n\n    // compute basis, [k-p+1,k]\n    std::vector<std::vector<double>> basis;\n    size_t spanIdx = findSpan(u);\n    derBasisFuns(u, spanIdx, derivativeLimit, basis);\n\n    // d_{k-p+j}, j \\in [1,p]\n    std::vector<Eigen::Vector3d> d; // since Sophus::SO3d::DoF = 3\n    for (int j = 1; j <= degree_; ++j) {\n        d.push_back(\n                (controlPoints_[spanIdx - degree_ + j - 1].inverse() * controlPoints_[spanIdx - degree_ + j]).log());\n    }\n\n    // A_j(u), j \\in [1,p]\n    std::vector<Sophus::SO3d, Eigen::aligned_allocator<Sophus::SO3d>> A;\n    for (int j = 1; j <= degree_; ++j) {\n        int j_idx = j - 1;\n        A.push_back(Sophus::SO3d::exp(basis[0][j_idx] * d[j_idx]));\n    }\n\n    // derivative = 0\n    val = controlPoints_[spanIdx - degree_ + 0];\n    for (int j = 1; j <= degree_; ++j) {\n        int j_idx = j - 1;\n        val *= A[j_idx];\n    }\n\n    if (derivativeLimit >= 1) {\n        std::vector<std::vector<Eigen::Vector3d>> angVDer; // since Sophus::SO3d::DoF = 3\n        angVDer.resize(derivativeLimit);\n        for (auto &ad: angVDer) {\n            ad.assign(degree_ + 1, Eigen::Vector3d::Zero());\n        }\n\n        for (int j = 2; j <= degree_ + 1; j++) {\n            int j_idx = j - 1;\n            angVDer[0][j_idx] =\n                    A[j_idx - 1].inverse().Adj() * angVDer[0][j_idx - 1] + basis[1][j_idx - 1] * d[j_idx - 1];\n        }\n\n        Ders.push_back(angVDer[0].back());\n\n        if (derivativeLimit >= 2) {\n            for (int j = 2; j <= degree_ + 1; j++) {\n                int j_idx = j - 1;\n                angVDer[1][j_idx] = basis[1][j_idx - 1] * Sophus::SO3d::lieBracket(angVDer[0][j_idx], d[j_idx - 1]) +\n                                    A[j_idx - 1].inverse().Adj() * angVDer[1][j_idx - 1] +\n                                    basis[2][j_idx - 1] * d[j_idx - 1];\n            }\n\n            Ders.push_back(angVDer[1].back());\n        }\n    }\n}\n", "meta": {"hexsha": "19b4a1cf410e10e3b3f52b7ea53e38e19cb5efe6", "size": 15286, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/core/spline/src/BsplineSO3.cpp", "max_stars_repo_name": "MobilePerceptionLab/EventCameraCalibration", "max_stars_repo_head_hexsha": "debd774ac989674b500caf27641b7ad4e94681e9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2021-08-06T03:21:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T03:40:54.000Z", "max_issues_repo_path": "modules/core/spline/src/BsplineSO3.cpp", "max_issues_repo_name": "MobilePerceptionLab/MultiCamCalib", "max_issues_repo_head_hexsha": "2f0e94228c2c4aea7f20c26e3e8daa6321ce8022", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-02-25T02:55:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-25T15:18:45.000Z", "max_forks_repo_path": "modules/core/spline/src/BsplineSO3.cpp", "max_forks_repo_name": "MobilePerceptionLab/MultiCamCalib", "max_forks_repo_head_hexsha": "2f0e94228c2c4aea7f20c26e3e8daa6321ce8022", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2021-08-11T12:29:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-25T03:41:01.000Z", "avg_line_length": 37.4656862745, "max_line_length": 118, "alphanum_fraction": 0.5143922544, "num_tokens": 4326, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754371026367, "lm_q2_score": 0.6297745935070808, "lm_q1q2_score": 0.45846043498445244}}
{"text": "/*=============================================================================\nCopyright (c) 2016 Paul W. Bible\n\nDistributed under the Boost Software License, Version 1.0. (See accompanying\nfile LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n==============================================================================*/\n#ifndef ENRICHMENT_TOOLS\n#define ENRICHMENT_TOOLS\n\n#include <stdlib.h>\n\n#include <ggtk/AnnotationData.hpp>\n#include <ggtk/GoGraph.hpp>\n#include <ggtk/SetUtilities.hpp>\n\n#include <boost/math/distributions.hpp>\n#include <boost/unordered_map.hpp>\n\n//! The EnrichmentTools namespace provides simple functions for calulating GO term enrichment.\n/*!\n\tThis namespace defines free functions that allow enrichment p-values to be calculated.\n\tThese funcitons can serve as the foundation for more sophisticated enrichment anlayis.\n*/\nnamespace EnrichmentTools{\n\n\t//! A method for determining which genes are annotated with the given term or a child of that term.\n\t/*!\n\t\tThis method calculates the set of the genes annotated with a given term or transatively with a child of that term.\n\t*/\n\tinline boost::unordered_set<std::string> getDescendantGenes(GoGraph *go, AnnotationData *data, const std::string &term){\n\t\tboost::unordered_set<std::string> descendants = go->getDescendantTerms(term);\n\t\tdescendants.insert(term);\n\n\t\tboost::unordered_set<std::string>::iterator si;\n\t\tboost::unordered_set<std::string> genes;\n\n\t\tfor(si = descendants.begin(); si != descendants.end(); ++si){\n\t\t\tstd::string currentTerm = *si;\n\t\t\t//std::cout << *si << \" \" << go->getTermName(*si) << std::endl;\n\t\t\tdata->addGenesForGoTerm(currentTerm,genes);\n\t\t}\n\t\t//std::cout << genes.size() << std::endl;\n\n\t\treturn genes;\n\t};\n\n\t//! A method for calculating the result of a hypergeometic test.\n\t/*!\n\t\tThis method calculates p-value of a hypergeometice test give 4 values.\n\t\tThe sample size,         n\n\t\tThe population success   K\n\t\tThe the population size  N\n\t\tThe test value           k\n\n\t\tAnswers the question:\n\t\t\"What is probability of seeing value of k or more successes\n\t\t  in a sample of size n, given that the population of size N \n\t\t  contains K total successes.\"\n\t*/\n\tinline double oneSidedRawPvalue_hyper(size_t sample, size_t success,size_t population,size_t test_value){\n\t\tdouble sum = 0.0;\n\t\tboost::math::hypergeometric dist(sample,success,population);\n\t\tfor(size_t i = test_value; i <= sample && i <= success; ++i){\n\t\t\tdouble prob = boost::math::pdf(dist,i);\n\t\t\tsum += prob;\n\t\t}\n\t\treturn sum;\n\t};\n\n\n\t//! A method to calculate the enrichment of a specific term in a sample of genes.\n\t/*!\n\t\tThis method performs a hypergeometic test of enrichment for a term given\n\t\ta set of genes that serves as the sample. The population is taken as all genes\n\t\tin the annotation database.\n\t*/\n\tinline double enrichmentSignificance(GoGraph *go, AnnotationData *data,\n\t\t\t\t\t\t\t\t\t\t\tboost::unordered_set<std::string> &genes,\n\t\t\t\t\t\t\t\t\t\t\tconst std::string &term)\n\t{\n\t\tboost::unordered_set<std::string> termGenes = getDescendantGenes(go, data, term);\n\t\tboost::unordered_set<std::string> sharedGenes = SetUtilities::set_intersection(genes,termGenes);\n\n\t\tif(sharedGenes.size() == 0){\n\t\t\treturn 1.0;\n\t\t}\n\t\t\n\t\tsize_t sampleSize = genes.size();\n\t\tsize_t sampleWithTerm = sharedGenes.size();\n\t\tsize_t populationWithTerm = termGenes.size();\n\t\tsize_t populationSize = data->getNumGenes();\n\n\t\treturn oneSidedRawPvalue_hyper(sampleSize,populationWithTerm,populationSize,sampleWithTerm);\n\t};\n\n\n};\n#endif\n", "meta": {"hexsha": "836da24abe9dbad83b8f0b82e44f9d13b209eaa7", "size": 3481, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ggtk/EnrichmentTools.hpp", "max_stars_repo_name": "paulbible/ggtk", "max_stars_repo_head_hexsha": "9cdfb1ecced55db7353683b312b250e7238f61da", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-09-11T04:32:51.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-27T20:51:59.000Z", "max_issues_repo_path": "ggtk/EnrichmentTools.hpp", "max_issues_repo_name": "paulbible/ggtk", "max_issues_repo_head_hexsha": "9cdfb1ecced55db7353683b312b250e7238f61da", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-10-12T05:36:18.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-30T19:47:01.000Z", "max_forks_repo_path": "ggtk/EnrichmentTools.hpp", "max_forks_repo_name": "paulbible/ggtk", "max_forks_repo_head_hexsha": "9cdfb1ecced55db7353683b312b250e7238f61da", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-08T21:30:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-08T21:30:32.000Z", "avg_line_length": 35.1616161616, "max_line_length": 121, "alphanum_fraction": 0.695202528, "num_tokens": 848, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.45838726811205305}}
{"text": "#include <algorithm>\n#include <bitset>\n// #include <boost/algorithm/string/replace.hpp>\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n#include <map>\n#include <set>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\n#define FOR(i, j, n) for (int i = j; i < n; i++)\n#define OUT(s) cout << s << \" \";\n#define IN(a) cin >> a;\n#define PACK(a, n)                                                             \\\n  for (int i = 0; i < n; i++)                                                  \\\n    cin >> a[i];\n#define LIST(a, n)                                                             \\\n  for (int i = 0; i < n; i++)                                                  \\\n    cout << i << \": \" << a[i] << endl;\n#define PP(label, obj) cout << \"[\" << label << \"] \" << obj << endl;\n\nint main() {\n  string S;\n  IN(S);\n\n  int len = S.length();\n  int even = 0;\n  int odd = 0;\n  int rpos = -1;\n  FOR(i, 0, len) {\n    if (i % 2 == 0) {\n      even += 1;\n    } else {\n      odd += 1;\n    }\n    if ((i + 1 == len || S[i + 1] == 'R') && S[i] == 'L') {\n      if (rpos % 2 == 0) {\n        OUT(even);\n        OUT(odd);\n      } else {\n        OUT(odd);\n        OUT(even);\n      }\n      FOR(j, 0, i - rpos - 1) OUT(0);\n      rpos = -1;\n      even = odd = 0;\n    } else if (S[i + 1] == 'L' && S[i] == 'R') {\n      rpos = i;\n    } else {\n      if (rpos < 0) {\n        OUT(0);\n      }\n    }\n  }\n}", "meta": {"hexsha": "2ee2888ea802b2263f23423a910a3bcc2ff4def8", "size": 1384, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "contests/abc136/abc136_d.cpp", "max_stars_repo_name": "uetchy/atcoder", "max_stars_repo_head_hexsha": "8fc96737fc5bc45b2a834c8ec18b59969f99fdd5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "contests/abc136/abc136_d.cpp", "max_issues_repo_name": "uetchy/atcoder", "max_issues_repo_head_hexsha": "8fc96737fc5bc45b2a834c8ec18b59969f99fdd5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "contests/abc136/abc136_d.cpp", "max_forks_repo_name": "uetchy/atcoder", "max_forks_repo_head_hexsha": "8fc96737fc5bc45b2a834c8ec18b59969f99fdd5", "max_forks_repo_licenses": ["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.8620689655, "max_line_length": 80, "alphanum_fraction": 0.3663294798, "num_tokens": 419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.715424007918532, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.458326280703119}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// QuickBook Example\n\n// Copyright (c) 2011 Barend Gehrels, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n//[tag\n//` Shows how tag dispatching essentially works in Boost.Geometry\n\n#include <iostream>\n\n#include <boost/assign.hpp>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n#include <boost/geometry/multi/geometries/multi_polygon.hpp>\n#include <boost/geometry/geometries/adapted/boost_tuple.hpp>\n\nBOOST_GEOMETRY_REGISTER_BOOST_TUPLE_CS(cs::cartesian)\n\ntemplate <typename Tag> struct dispatch {};\n\n// Specialization for points\ntemplate <> struct dispatch<boost::geometry::point_tag>\n{\n    template <typename Point>\n    static inline void apply(Point const& p)\n    {\n        // Use the Boost.Geometry free function \"get\"\n        // working on all supported point types\n        std::cout << \"Hello POINT, you are located at: \" \n            << boost::geometry::get<0>(p) << \", \" \n            << boost::geometry::get<1>(p) \n            << std::endl;\n    }\n};\n\n// Specialization for polygons\ntemplate <> struct dispatch<boost::geometry::polygon_tag>\n{\n    template <typename Polygon>\n    static inline void apply(Polygon const& p)\n    {\n        // Use the Boost.Geometry manipulator \"dsv\" \n        // working on all supported geometries\n        std::cout << \"Hello POLYGON, you look like: \" \n            << boost::geometry::dsv(p) \n            << std::endl;\n    }\n};\n\n// Specialization for multipolygons\ntemplate <> struct dispatch<boost::geometry::multi_polygon_tag>\n{\n    template <typename MultiPolygon>\n    static inline void apply(MultiPolygon const& m)\n    {\n        // Use the Boost.Range free function \"size\" because all\n        // multigeometries comply to Boost.Range\n        std::cout << \"Hello MULTIPOLYGON, you contain: \" \n            << boost::size(m) << \" polygon(s)\"\n            << std::endl;\n    }\n};\n\ntemplate <typename Geometry>\ninline void hello(Geometry const& geometry)\n{\n    // Call the metafunction \"tag\" to dispatch, and call method (here \"apply\")\n    dispatch\n        <\n            typename boost::geometry::tag<Geometry>::type\n        >::apply(geometry);\n}\n\nint main()\n{\n    // Define polygon type (here: based on a Boost.Tuple)\n    typedef boost::geometry::model::polygon<boost::tuple<int, int> > polygon_type;\n\n    // Declare and fill a polygon and a multipolygon\n    polygon_type poly;\n    boost::geometry::exterior_ring(poly) = boost::assign::tuple_list_of(0, 0)(0, 10)(10, 5)(0, 0);\n        \n    boost::geometry::model::multi_polygon<polygon_type> multi;\n    multi.push_back(poly);\n\n    // Call \"hello\" for point, polygon, multipolygon\n    hello(boost::make_tuple(2, 3));\n    hello(poly);\n    hello(multi);\n\n    return 0;\n}\n\n//]\n\n//[tag_output\n/*`\nOutput:\n[pre\nHello POINT, you are located at: 2, 3\nHello POLYGON, you look like: (((0, 0), (0, 10), (10, 5), (0, 0)))\nHello MULTIPOLYGON, you contain: 1 polygon(s)\n]\n*/\n//]\n", "meta": {"hexsha": "86e8f5a8353fbd3d11798f9e0e916d1e09ee5df6", "size": 3107, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/doc/src/examples/core/tag.cpp", "max_stars_repo_name": "olegshnitko/libboost", "max_stars_repo_head_hexsha": "548eb6365af3724d8f4b47ebbabf7eb3ad8e66a8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-10-31T00:40:22.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-31T00:40:22.000Z", "max_issues_repo_path": "libs/geometry/doc/src/examples/core/tag.cpp", "max_issues_repo_name": "olegshnitko/libboost", "max_issues_repo_head_hexsha": "548eb6365af3724d8f4b47ebbabf7eb3ad8e66a8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-01-17T10:11:43.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-17T10:11:43.000Z", "max_forks_repo_path": "libs/geometry/doc/src/examples/core/tag.cpp", "max_forks_repo_name": "olegshnitko/libboost", "max_forks_repo_head_hexsha": "548eb6365af3724d8f4b47ebbabf7eb3ad8e66a8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.990990991, "max_line_length": 98, "alphanum_fraction": 0.6559382041, "num_tokens": 786, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.640635868562172, "lm_q2_score": 0.7154240079185319, "lm_q1q2_score": 0.4583262807031189}}
{"text": "// Copyright (c) 2019 fortiss GmbH, Julian Bernhard, Klemens Esterle, Patrick Hart, Tobias Kessler\n//\n// This work is licensed under the terms of the MIT license.\n// For a copy, see <https://opensource.org/licenses/MIT>.\n\n\n#ifndef MODULES_WORLD_OPENDRIVE_PLAN_VIEW_HPP_\n#define MODULES_WORLD_OPENDRIVE_PLAN_VIEW_HPP_\n\n#include <Eigen/Core>\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/geometries.hpp>\n\n#include \"modules/geometry/commons.hpp\"\n#include \"modules/geometry/line.hpp\"\n#include \"modules/world/opendrive/lane.hpp\"\n\nnamespace modules {\nnamespace world {\nnamespace opendrive {\n\nclass PlanView {\n public:\n  PlanView() : length_(0.0) {}\n  ~PlanView() {}\n\n  //! setter functions\n  bool add_line(geometry::Point2d start_point, float heading, float length);\n\n  bool add_spiral(geometry::Point2d start_point, float heading, float length, float curvStart, float curvEnd, float s_inc = 2.0f);\n  bool add_arc(geometry::Point2d start_point, float heading, float length, float curvature, float s_inc = 2.0f);\n\n  void calc_arc_position(const float s, float initial_heading, float curvature, float &dx, float &dy);\n\n  //! getter functions\n  geometry::Line get_reference_line() const { return reference_line_; }\n\n  geometry::Point2d test(geometry::Point2d p) { return p; }\n\n  float get_length() const { return length_; }\n  float get_distance( const geometry::Point2d &p) const { return boost::geometry::distance(reference_line_.obj_, p); }\n\n private:\n  geometry::Line reference_line_;  // sequential build up\n  float length_;\n};\n\nusing PlanViewPtr = std::shared_ptr<PlanView>;\n\n}  // namespace opendrive\n}  // namespace world\n}  // namespace modules\n\n#endif  // MODULES_WORLD_OPENDRIVE_PLAN_VIEW_HPP_\n", "meta": {"hexsha": "0f9675efea8a4bc7d7f3e0081315badea77ca4e5", "size": 1715, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/world/opendrive/plan_view.hpp", "max_stars_repo_name": "cirrostratus1/bark", "max_stars_repo_head_hexsha": "6629a9bbc455d0fd708e09bb8e162425e62c4165", "max_stars_repo_licenses": ["MIT"], "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/world/opendrive/plan_view.hpp", "max_issues_repo_name": "cirrostratus1/bark", "max_issues_repo_head_hexsha": "6629a9bbc455d0fd708e09bb8e162425e62c4165", "max_issues_repo_licenses": ["MIT"], "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/world/opendrive/plan_view.hpp", "max_forks_repo_name": "cirrostratus1/bark", "max_forks_repo_head_hexsha": "6629a9bbc455d0fd708e09bb8e162425e62c4165", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-04-16T07:56:43.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-16T07:56:43.000Z", "avg_line_length": 31.1818181818, "max_line_length": 130, "alphanum_fraction": 0.7539358601, "num_tokens": 436, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.6406358617010351, "lm_q1q2_score": 0.45832626802034315}}
{"text": "/***********************************************************************\nCopyright (c) 2014-2020, Jan Elffers\nCopyright (c) 2019-2020, Jo Devriendt\nCopyright (c) 2020, Stephan Gocht\n\nParts of the code were copied or adapted from MiniSat.\n\nMiniSAT -- Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson\n           Copyright (c) 2007-2010  Niklas Sorensson\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be 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\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\nLIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\nOF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\nWITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n***********************************************************************/\n\n#pragma once\n\n#include <boost/multiprecision/cpp_int.hpp>\n#if WITHGMP\n#include <boost/multiprecision/gmp.hpp>\n#endif  // WITHGMP\n#include <cassert>\n#include <exception>\n#include <iostream>\n#include <limits>\n#include <unordered_map>\n#include <vector>\n\nnamespace rs {\n\n#if WITHGMP\nusing int128 = boost::multiprecision::int128_t;  // NOTE: a bit slower than __int128, but plays nice with mpz_int\nusing bigint = boost::multiprecision::mpz_int;   // NOTE: requires GMP\n#else\nusing int128 = __int128;\nusing bigint = boost::multiprecision::cpp_int;\n#endif  // WITHGMP\nusing int256 = boost::multiprecision::int256_t;\nusing BigCoef = bigint;\nusing BigVal = bigint;\n\nusing ID = uint64_t;\nconst ID ID_Undef = std::numeric_limits<ID>::max();\nconst ID ID_Unsat = ID_Undef - 1;\nconst ID ID_Trivial = 1;  // represents constraint 0 >= 0\n\nusing Var = int;\nusing Lit = int;\ninline Var toVar(Lit l) { return std::abs(l); }\n\nconst int resize_factor = 2;\n\nconst int INF = 1e9 + 1;  // 1e9 is the maximum number of variables in the system, anything beyond is infinity\nconst long long INFLPINT = 1e15 + 1;  // based on max long range captured by double\n\nconst int limit32 = 1e9;         // 2^29-2^30\nconst long long limit64 = 2e18;  // 2^60-2^61\nconst double limit96 = 8e27;     // 2^92-2^93, so 46 bits is less than half\nconst double limit128 = 32e36;   // 2^124-2^125, so 62 bits is less than half\nconst double limit256 = 1e76;    // 2^252-2^253, so 126 bits is less than half\nconst int conflLimit32 = 14;\nconst int conflLimit64 = 30;\nconst int conflLimit96 = 46;\nconst int conflLimit128 = 62;\n\nusing IntVecIt = std::vector<int>::iterator;\n\nusing ActValV = long double;\nconst ActValV actLimitV = (ActValV)1e300 * (ActValV)1e300 * (ActValV)1e300 * (ActValV)1e300 * (ActValV)1e300 *\n                          (ActValV)1e300 * (ActValV)1e300 * (ActValV)1e300;  // ~1e2400 << 2^(2^13)\nusing ActValC = float;\nconst ActValC actLimitC = 1e30;  // ~1e30 << 2^(2^7)\n\n/*\n * UNKNOWN: uninitialized value\n * FORMULA: original input formula constraints\n * LEARNED: learned from regular conflict analysis\n * FARKAS: LP solver infeasibility witness\n * LEARNEDFARKAS: constraint learned from conflict analysis on FARKAS\n * GOMORY: Gomory cut\n * UPPERBOUND: upper and lower bounds on the objective function\n *\n * max number of types is 16, as the type is stored with 4 bits in Constr\n */\nenum class Origin {\n  UNKNOWN,\n  FORMULA,\n  LEARNED,\n  FARKAS,\n  LEARNEDFARKAS,\n  GOMORY,\n  UPPERBOUND,\n  GAUSS,\n};\n\ntemplate <typename SMALL, typename LARGE>\nstruct ConstrExp;\nusing ConstrExp32 = ConstrExp<int, long long>;\nusing ConstrExp64 = ConstrExp<long long, int128>;\nusing ConstrExp96 = ConstrExp<int128, int128>;\nusing ConstrExp128 = ConstrExp<int128, int256>;\nusing ConstrExpArb = ConstrExp<bigint, bigint>;\nstruct ConstrExpSuper;\n\ntemplate <typename CE>\nstruct CePtr;\nusing Ce32 = CePtr<ConstrExp32>;\nusing Ce64 = CePtr<ConstrExp64>;\nusing Ce96 = CePtr<ConstrExp96>;\nusing Ce128 = CePtr<ConstrExp128>;\nusing CeArb = CePtr<ConstrExpArb>;\nusing CeSuper = CePtr<ConstrExpSuper>;\nusing CeNull = CePtr<ConstrExp32>;\n\ntemplate <typename CF, typename DG>\nstruct ConstrSimple;\nusing ConstrSimple32 = ConstrSimple<int, long long>;\nusing ConstrSimple64 = ConstrSimple<long long, int128>;\nusing ConstrSimple96 = ConstrSimple<int128, int128>;\nusing ConstrSimple128 = ConstrSimple<int128, int256>;\nusing ConstrSimpleArb = ConstrSimple<bigint, bigint>;\nstruct ConstrSimpleSuper;\n\nstruct Constr;\nstruct Clause;\nstruct Cardinality;\n\ntemplate <typename CF, typename DG>\nstruct Counting;\nusing Counting32 = Counting<int, long long>;\nusing Counting64 = Counting<long long, int128>;\nusing Counting96 = Counting<int128, int128>;\n\ntemplate <typename CF, typename DG>\nstruct Watched;\nusing Watched32 = Watched<int, long long>;\nusing Watched64 = Watched<long long, int128>;\nusing Watched96 = Watched<int128, int128>;\n\ntemplate <typename CF, typename DG>\nstruct CountingSafe;\nusing CountingSafe32 = CountingSafe<int, long long>;\nusing CountingSafe64 = CountingSafe<long long, int128>;\nusing CountingSafe96 = CountingSafe<int128, int128>;\nusing CountingSafeArb = CountingSafe<bigint, bigint>;\n\ntemplate <typename CF, typename DG>\nstruct WatchedSafe;\nusing WatchedSafe32 = WatchedSafe<int, long long>;\nusing WatchedSafe64 = WatchedSafe<long long, int128>;\nusing WatchedSafe96 = WatchedSafe<int128, int128>;\nusing WatchedSafeArb = WatchedSafe<bigint, bigint>;\n\ntemplate <typename CF>\nstruct Term {\n  Term() : c(0), l(0) {}\n  Term(const CF& x, Lit y) : c(x), l(y) {}\n  CF c;\n  Lit l;\n};\n\ntemplate <typename CF>\nstd::ostream& operator<<(std::ostream& o, const Term<CF>& t) {\n  return o << t.c << \"x\" << t.l;\n}\n\ninline class AsynchronousInterrupt : public std::exception {\n public:\n  virtual const char* what() const throw() { return \"Program interrupted by user.\"; }\n} asynchInterrupt;\n\n}  // namespace rs\n", "meta": {"hexsha": "ea9202243ec73d9149c06ecba594eb0d0a65e223", "size": 6292, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/typedefs.hpp", "max_stars_repo_name": "meelgroup/RoundXOR", "max_stars_repo_head_hexsha": "c35d7316a46deed7cca0ab7eb314b5aa2ff7d7f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-10-29T18:39:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T11:53:46.000Z", "max_issues_repo_path": "src/typedefs.hpp", "max_issues_repo_name": "meelgroup/RoundXOR", "max_issues_repo_head_hexsha": "c35d7316a46deed7cca0ab7eb314b5aa2ff7d7f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-02-09T10:56:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T10:56:30.000Z", "max_forks_repo_path": "src/typedefs.hpp", "max_forks_repo_name": "meelgroup/linpb", "max_forks_repo_head_hexsha": "c35d7316a46deed7cca0ab7eb314b5aa2ff7d7f7", "max_forks_repo_licenses": ["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.4680851064, "max_line_length": 113, "alphanum_fraction": 0.7285441831, "num_tokens": 1737, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.45832626311172103}}
{"text": "#pragma once \n\n#include <crab/common/os.hpp>\n#include <boost/functional/hash.hpp>\n#include <gmp.h>\n\n// TODO: replace ikos with crab namespace. This class has nothing to\n// do with the ikos one. Kept for now for compatibility issues with\n// some clients.\nnamespace ikos {\n\n// GMP can convert directly from/to signed/unsigned long and\n// signed/unsigned int. However, the C++11 standard only guarantees:\n//\n//  - unsigned/signed int  >= 16 bits.\n//  - unsigned/signed long >= 32 bits.\n//\n\n// TODO/FIXME:\n//\n// We don't have a conversion from GMP numbers to 64-bit integers,\n// because GMP cannot convert directly from/to int64_t or\n// uint64_t. For that, we need to use mpz_export and mpz_import but\n// they are significantly more expensive.\n// \n// Note that the actual size of **long** integer varies depending on\n// the architecture and OS (see e.g.,\n// https://en.cppreference.com/w/cpp/language/types). For instance,\n// both Linux and mac OS on an Intel 64, the size of long integers is\n// 8 bytes. But for Windows on Intel 64, the size is 4 bytes.\n\nclass z_number {\n  friend class q_number;\n\nprivate:\n  mpz_t _n;\n\npublic:\n  \n  // overloaded typecast operators\n  explicit operator long() const;\n  explicit operator int() const;\n  \n  z_number();\n  z_number(signed long long int n);\n  z_number(const std::string& s, unsigned base = 10);\n\n  static z_number from_ulong(unsigned long n);\n  static z_number from_slong(signed long n);\n  static z_number from_mpz_t(mpz_t n);  \n  static z_number from_mpz_srcptr(mpz_srcptr n);\n  \n  z_number(const z_number& o);\n  z_number(z_number&& o);\n  z_number& operator=(const z_number& o);\n  z_number& operator=(z_number&& o);  \n  \n  ~z_number();\n\n  mpz_srcptr get_mpz_t() const { return _n; }\n  \n  mpz_ptr get_mpz_t() { return _n; }\n  \n  std::string get_str(unsigned base = 10) const;\n\n  std::size_t hash() const;\n  \n  bool fits_sint() const;\n\n  bool fits_slong() const;\n\n  z_number operator+(z_number x) const; \n\n  z_number operator*(z_number x) const;\n\n  z_number operator-(z_number x) const; \n\n  z_number operator-() const;\n\n  z_number operator/(z_number x) const;\n\n  z_number operator%(z_number x) const;\n\n  z_number& operator+=(z_number x);\n\n  z_number& operator*=(z_number x);\n\n  z_number& operator-=(z_number x);\n\n  z_number& operator/=(z_number x);\n\n  z_number& operator%=(z_number x);\n\n  z_number& operator--();\n\n  z_number& operator++();\n\n  z_number operator++(int);\n\n  z_number operator--(int);\n\n  bool operator==(z_number x) const;\n\n  bool operator!=(z_number x) const;\n\n  bool operator<(z_number x) const;\n\n  bool operator<=(z_number x) const;\n\n  bool operator>(z_number x) const;\n\n  bool operator>=(z_number x) const;\n\n  z_number operator&(z_number x) const;\n\n  z_number operator|(z_number x) const;\n\n  z_number operator^(z_number x) const;\n\n  z_number operator<<(z_number x) const;\n\n  z_number operator>>(z_number x) const;\n\n  z_number fill_ones() const;\n\n  void write(crab::crab_os& o) const;\n\n}; // class z_number\n\nclass q_number {\n  \nprivate:\n  mpq_t _n;\n\npublic:\n  \n  q_number();\n  q_number(double n);\n  \n  q_number(const std::string& s, unsigned base = 10);  \n  q_number(const z_number& n);\n  q_number(const z_number& n, const z_number& d);\n\n  static q_number from_mpq_t(mpq_t n);\n  static q_number from_mpz_t(mpz_t n);\n  static q_number from_mpq_srcptr(mpq_srcptr q);\n  \n  q_number(const q_number& o);\n  q_number(q_number&& o);\n  q_number& operator=(const q_number& o);\n  q_number& operator=(q_number&& o);  \n  \n  ~q_number();\n\n  mpq_srcptr get_mpq_t() const { return _n; }\n  \n  mpq_ptr get_mpq_t() { return _n; }\n\n  double get_double() const;\n  \n  std::string get_str(unsigned base = 10) const;\n\n  std::size_t hash() const;\n  \n  q_number operator+(q_number x) const;\n\n  q_number operator*(q_number x) const;\n\n  q_number operator-(q_number x) const;\n\n  q_number operator-() const;\n\n  q_number operator/(q_number x) const;\n\n  q_number& operator+=(q_number x);\n\n  q_number& operator*=(q_number x);\n\n  q_number& operator-=(q_number x);\n\n  q_number& operator/=(q_number x);\n\n  q_number& operator--();\n\n  q_number& operator++();\n\n  q_number operator--(int);\n\n  q_number operator++(int);\n\n  bool operator==(q_number x) const;\n\n  bool operator!=(q_number x) const;\n\n  bool operator<(q_number x) const; \n\n  bool operator<=(q_number x) const;\n\n  bool operator>(q_number x) const;\n\n  bool operator>=(q_number x) const;\n\n  z_number numerator() const;\n\n  z_number denominator() const;\n\n  z_number round_to_upper() const;\n\n  z_number round_to_lower() const;\n\n  void write(crab::crab_os& o) const;\n\n}; // class q_number\n\ninline crab::crab_os& operator<<(crab::crab_os& o, const z_number& z) {\n  z.write(o);\n  return o;\n}\n\ninline crab::crab_os& operator<<(crab::crab_os& o, const q_number& q) {\n  q.write(o);\n  return o;\n}\n\n/** for boost::hash_combine **/\ninline std::size_t hash_value(const z_number& z) {\n  return z.hash();\n}\n\ninline std::size_t hash_value(const q_number& q) {\n  return q.hash();\n}\n} //end namespace\n\n/** for specializations of std::hash **/\nnamespace std {\ntemplate<>\nstruct hash<ikos::z_number> {\n  size_t operator()(const ikos::z_number& z) const {\n    return z.hash();\n  }\n};\n\ntemplate<>\nstruct hash<ikos::q_number> {\n  size_t operator()(const ikos::q_number& q) const {\n    return q.hash();\n  }\n};\n}\n", "meta": {"hexsha": "7a317c6a08e379b77991bd438cdadf0ebb6f7b55", "size": 5263, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/crab/numbers/bignums.hpp", "max_stars_repo_name": "numairmansur/crab", "max_stars_repo_head_hexsha": "316e3946d3a4d92db638c54fbfa8fb7bee1ebbc7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/crab/numbers/bignums.hpp", "max_issues_repo_name": "numairmansur/crab", "max_issues_repo_head_hexsha": "316e3946d3a4d92db638c54fbfa8fb7bee1ebbc7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/crab/numbers/bignums.hpp", "max_forks_repo_name": "numairmansur/crab", "max_forks_repo_head_hexsha": "316e3946d3a4d92db638c54fbfa8fb7bee1ebbc7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.96812749, "max_line_length": 71, "alphanum_fraction": 0.6889606688, "num_tokens": 1473, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.45832626311172103}}
{"text": "#include <iostream>\n#include <algorithm>\n#include <cmath>\n#include <vector>\n#include <map>\n#include <set>\n#include <tuple>\n#include <stdbool.h>\n#include <bitset>\n#include <string>\n#include <boost/multiprecision/cpp_int.hpp>\n\nnamespace mp = boost::multiprecision;\nusing namespace std;\n\nint mizuyari(vector<int> h) {\n    // 0\u304c\u542b\u307e\u308c\u306a\u3044\u533a\u9593\u3067\u5206\u5272\u7d71\u6cbb\u3059\u308b\n    // for(const auto& x : h) {\n    //     cout << x << \", \";\n    // }\n    // cout << endl;\n\n    int count = 0;\n    for(int i = 0 ; i < h.size() ; ) {\n        if (!h[i]) {\n            i++;\n            continue;\n        }\n        vector<int> sub; // \u5206\u5272\u7d71\u6cbb\u3059\u308bvector\n        int j;\n        for(j = i ; j < h.size() ; ++j ) {\n            if(!h[j]) {\n                break;\n            } else {\n                sub.push_back(h[j] - 1); // \u6c34\u3084\u308a\u3059\u308b\n            }\n        }\n        // (i, j]\u533a\u9593\u3067\u3044\u3051\u308b\n        count++; // \u4eca\u56de\u306e\u6c34\u3084\u308a\u5206\n        count += mizuyari(sub); // \u6c34\u3092\u3084\u3063\u305f\u5f8c\u306e\u6b8b\u308a\u306f\u307e\u304b\u3057\u305f\n        // \u5f8c\u51e6\u7406\n        i = j;\n    }\n    return count;\n}\n\nint main(void) {\n    int n;\n    cin >> n;\n    vector<int> h(n);\n    for(int i = 0 ; i < n ; ++i) {\n        cin >> h[i];\n    }\n    auto ans = mizuyari(h);\n    cout << ans << endl;\n    return 0;\n}", "meta": {"hexsha": "5af6ab7a3da03e18cfae005120d4ae42e524200e", "size": 1154, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "abc116/c/main.cpp", "max_stars_repo_name": "kamiyaowl/atcoder", "max_stars_repo_head_hexsha": "30521be1684e72e75c7ba21312c5f96ae81bf25a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "abc116/c/main.cpp", "max_issues_repo_name": "kamiyaowl/atcoder", "max_issues_repo_head_hexsha": "30521be1684e72e75c7ba21312c5f96ae81bf25a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-20T11:51:59.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-20T11:51:59.000Z", "max_forks_repo_path": "abc116/c/main.cpp", "max_forks_repo_name": "kamiyaowl/atcoder", "max_forks_repo_head_hexsha": "30521be1684e72e75c7ba21312c5f96ae81bf25a", "max_forks_repo_licenses": ["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.2456140351, "max_line_length": 49, "alphanum_fraction": 0.4601386482, "num_tokens": 377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239836484143, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.4583262455203231}}
{"text": "/* Copyright \u00a9 2017 Apple Inc. All rights reserved.\n *\n * Use of this source code is governed by a BSD-3-clause license that can\n * be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause\n */\n#ifndef TURI_GRADIENT_DESCENT_H_\n#define TURI_GRADIENT_DESCENT_H_\n\n#include <flexible_type/flexible_type.hpp>\n#include <Eigen/Core>\n\n#include <optimization/utils.hpp>\n#include <optimization/optimization_interface.hpp>\n#include <optimization/regularizer_interface.hpp>\n#include <optimization/line_search-inl.hpp>\n#include <table_printer/table_printer.hpp>\n\n\n// TODO: List of todo's for this file\n//------------------------------------------------------------------------------\n// 1. Constant line seach tuning?\n\nnamespace turi {\n  \nnamespace optimization {\n\n\n/**\n * \\ingroup group_optimization\n * \\addtogroup gradient_descent Gradient Descent\n * \\{\n */\n\n/**\n *\n * Solve a first_order_optimization_iterface model with a gradient descent\n * method.\n * \n * \\param[in,out] model  Model with first order optimization interface.\n * \\param[in] init_point Starting point for the solver.\n * \\param[in,out] opts   Solver options.\n * \\returns stats        Solver return stats.\n * \\param[in] reg        Shared ptr to an interface to a regularizer.\n * \\tparam Vector        Sparse or dense gradient representation.\n *\n *\n*/\ntemplate <typename Vector = DenseVector>\ninline solver_return gradient_descent(first_order_opt_interface& model,\n    const DenseVector& init_point, \n    std::map<std::string, flexible_type>& opts,\n    const std::shared_ptr<regularizer_interface> reg=NULL){ \n\n    // Benchmarking utils. \n    timer t;\n    double start_time = t.current_time();\n\n    logprogress_stream << \"Starting Gradient Descent \" << std::endl;\n    logprogress_stream << \"--------------------------------------------------------\" << std::endl;\n    std::stringstream ss;\n    ss.str(\"\");\n\n    // Step 1: Algorithm option init\n    // ------------------------------------------------------------------------\n    // Check that all solver options are present.\n    // Load options\n    size_t iter_limit = opts[\"max_iterations\"];\n    double convergence_threshold = opts[\"convergence_threshold\"];\n    double step_size = opts[\"step_size\"];\n    size_t iters = 1;\n    solver_return stats;\n\n    // Print progress\n    table_printer printer(\n        model.get_status_header({\"Iteration\", \"Passes\", \"Step size\", \"Elapsed Time\"}));\n    printer.print_header();\n\n\n    // First compute the residual. Sometimes, you already have the solution\n    // during the starting point. In these settings, you don't want to waste\n    // time performing a step of the algorithm.\n    DenseVector point = init_point; \n    Vector gradient(point.size());\n    double func_value;\n    model.compute_first_order_statistics(point, gradient, func_value);\n    double residual = compute_residual(gradient);\n\n    stats.func_evals++;\n    stats.gradient_evals++;\n\n    // Needs to store previous point and gradient information\n    DenseVector delta_point = point;\n    delta_point.setZero();\n    \n    // First iteration will take longer. Warn the user.\n    logprogress_stream <<\"Tuning step size. First iteration could take longer\"\n                       <<\" than subsequent iterations.\" << std::endl;\n    \n\n    // Nan Checking!\n    if (!std::isfinite(residual)) {\n      stats.status = OPTIMIZATION_STATUS::OPT_NUMERIC_OVERFLOW;\n    }\n    \n    // Step 2: Algorithm starts here\n    // ------------------------------------------------------------------------\n    // While not converged\n    while((residual >= convergence_threshold) && (iters <= iter_limit)){\n\n\n      // Line search for step size. \n      ls_return ls_stats;\n     \n      // Pick line search based on regularizers.\n      if (reg != NULL){\n        step_size  *= 2;\n        ls_stats =  backtracking(model, \n                                 step_size,\n                                 func_value, \n                                 point, \n                                 gradient, \n                                 -gradient,\n                                 reg);\n      } else {\n          ls_stats =  more_thuente(model, \n                                   step_size,\n                                   func_value, \n                                   point, \n                                   gradient, \n                                   -gradient);\n      }\n      \n\n      // Add info from line search \n      stats.func_evals += ls_stats.func_evals;\n      stats.gradient_evals += ls_stats.gradient_evals;\n      step_size = ls_stats.step_size;\n\n      // Line search failed\n      if (ls_stats.status == false){\n        stats.status = OPTIMIZATION_STATUS::OPT_LS_FAILURE;\n        break;\n      }\n\n      // \\delta x_k = x_{k} - x_{k-1}\n      delta_point =  point;\n      point = point -step_size * gradient;\n      if (reg != NULL)\n        reg->apply_proximal_operator(point, step_size);\n      delta_point = point - delta_point;\n\n      // Numerical error: Insufficient progress.\n      if (delta_point.norm() <= OPTIMIZATION_ZERO){\n        stats.status = OPTIMIZATION_STATUS::OPT_NUMERIC_ERROR;\n        break;\n      }\n      // Numerical error: Numerical overflow. (Step size was too large)\n      if (!delta_point.array().array().isFinite().all()) {\n        stats.status = OPTIMIZATION_STATUS::OPT_NUMERIC_OVERFLOW;\n        break;\n      }\n     \n      // Compute residual norm (to check for convergence)\n      model.compute_first_order_statistics(point, gradient, func_value);\n      stats.num_passes++;\n      residual = compute_residual(gradient);\n      iters++;\n\n      // Print progress\n      auto stat_info = {std::to_string(iters), \n                        std::to_string(stats.num_passes),\n                        std::to_string(step_size), \n                        std::to_string(t.current_time())};\n\n      auto row = model.get_status(point, stat_info);\n      printer.print_progress_row_strs(iters, row);\n    }\n\n    printer.print_footer();\n\n    // Step 3: Return optimization model status.\n    // ------------------------------------------------------------------------\n    if (stats.status == OPTIMIZATION_STATUS::OPT_UNSET) {\n      if (iters < iter_limit){\n        stats.status = OPTIMIZATION_STATUS::OPT_OPTIMAL;\n      } else {\n        stats.status = OPTIMIZATION_STATUS::OPT_ITERATION_LIMIT;\n      }\n    }\n    stats.iters = iters;\n    stats.residual = residual;\n    stats.gradient = gradient;\n    stats.func_value = func_value;\n    stats.solve_time = t.current_time() - start_time;\n    stats.solution = point;\n    stats.progress_table = printer.get_tracked_table();\n    \n    // Display solver stats\n    log_solver_summary_stats(stats);\n    return stats;\n}\n\n\n} // optimizaiton\n\n/// \\}\n} // turicreate\n\n#endif \n\n", "meta": {"hexsha": "ee59350c4d9b38df52919eb2c55dcea8eb285bbf", "size": 6718, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/optimization/gradient_descent-inl.hpp", "max_stars_repo_name": "LeeCenY/turicreate", "max_stars_repo_head_hexsha": "fb2f3bf313e831ceb42a2e10aacda6e472ea8d93", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/optimization/gradient_descent-inl.hpp", "max_issues_repo_name": "LeeCenY/turicreate", "max_issues_repo_head_hexsha": "fb2f3bf313e831ceb42a2e10aacda6e472ea8d93", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2022-01-13T04:03:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T01:02:31.000Z", "max_forks_repo_path": "src/optimization/gradient_descent-inl.hpp", "max_forks_repo_name": "ZeroInfinite/turicreate", "max_forks_repo_head_hexsha": "dd210c2563930881abd51fd69cb73007955b33fd", "max_forks_repo_licenses": ["BSD-3-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.8388625592, "max_line_length": 98, "alphanum_fraction": 0.5906519798, "num_tokens": 1385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.4583045482723261}}
{"text": "/** hoNFFT.cpp */\n\n#include \"hoNFFT.h\"\n\n#include \"hoNDFFT.h\"\n#include \"hoNDArray_elemwise.h\"\n#include \"hoNDArray_reductions.h\"\n#include \"hoNDArray_utils.h\"\n\n#include \"vector_td_utilities.h\"\n#include \"vector_td_operators.h\"\n#include \"vector_td_io.h\"\n\n#include <algorithm>\n#include <vector>\n#include <cmath>\n#include <stdexcept>\n\n#include <boost/range/algorithm/transform.hpp>\n\n#include \"GadgetronTimer.h\"\n\n#include \"NFFT.hpp\"\n#include \"NDArray_utils.h\"\n\n#include \"hoGriddingConvolution.h\"\n\nusing namespace std;\n\nnamespace Gadgetron {\n\n    namespace {\n\n        template<typename T, unsigned int D>\n        struct FFTD {\n        };\n\n        template<typename T>\n        struct FFTD<T, 1> {\n            using REAL = typename realType<T>::Type;\n\n            static void fft(hoNDArray<T> &array, NFFT_fft_mode mode, bool do_scale) {\n                if (mode == NFFT_fft_mode::FORWARDS) {\n                    hoNDFFT<REAL>::instance()->fft1c(array);\n                } else {\n                    hoNDFFT<REAL>::instance()->ifft1c(array);\n                }\n                if (!do_scale) array *= std::sqrt(REAL(array.get_size(0)));\n            }\n        };\n\n        template<typename T>\n        struct FFTD<T, 2> {\n            using REAL = typename realType<T>::Type;\n\n            static void fft(hoNDArray<T> &array, NFFT_fft_mode mode, bool do_scale ) {\n                if (mode == NFFT_fft_mode::FORWARDS) {\n                    hoNDFFT<REAL>::instance()->fft2c(array);\n                } else {\n                    hoNDFFT<REAL>::instance()->ifft2c(array);\n                }\n\n                if (!do_scale) array *= std::sqrt(REAL(array.get_size(0)*array.get_size(1)));\n\n            }\n        };\n\n        template<typename T>\n        struct FFTD<T, 3> {\n            using REAL = typename realType<T>::Type;\n\n            static void fft(hoNDArray<T> &array, NFFT_fft_mode mode, bool do_scale) {\n                if (mode == NFFT_fft_mode::FORWARDS) {\n                    hoNDFFT<REAL>::instance()->fft3c(array);\n                } else {\n                    hoNDFFT<REAL>::instance()->ifft3c(array);\n                }\n\n                if (!do_scale) array *= std::sqrt(REAL(array.get_size(0)*array.get_size(1)*array.get_size(2)));\n            }\n        };\n\n\n        template<class REAL, template<class, unsigned int> class K>\n        hoNDArray<std::complex<REAL>> compute_deapodization_filter(\n            const vector_td<size_t, 1>& image_dims,\n            const ConvolutionKernel<REAL, 1, K>& kernel)\n        {\n            hoNDArray<std::complex<REAL>> deapodization(to_std_vector(image_dims));\n            vector_td<REAL,1> image_dims_real(image_dims);\n            for (int x = 0; x < image_dims[0]; x++){\n                auto offset = x - image_dims_real[0]/2;\n                deapodization(x) = kernel.get(offset, 0);\n            }\n            return deapodization;\n        }\n\n\n        template<class REAL, template<class, unsigned int> class K>\n        hoNDArray<std::complex<REAL>> compute_deapodization_filter(\n            const vector_td<size_t, 2>& image_dims,\n            const ConvolutionKernel<REAL, 2, K>& kernel)\n        {\n            hoNDArray<std::complex<REAL>> deapodization(to_std_vector(image_dims));\n            vector_td<REAL,2> image_dims_real(image_dims);\n            for (int y = 0; y < image_dims[1]; y++) {\n                auto offset_y = y - image_dims_real[1]/2;\n                auto weight_y = kernel.get(offset_y, 1);\n\n                for (int x = 0; x < image_dims[0]; x++) {\n                    auto offset_x = x - image_dims_real[0]/2;\n                    auto weight_x = kernel.get(offset_x, 0);\n\n                    deapodization(x,y) = weight_x*weight_y;\n                }\n            }\n            return deapodization;\n        }\n\n\n        template<class REAL, template<class, unsigned int> class K>\n        hoNDArray<std::complex<REAL>> compute_deapodization_filter(\n            const vector_td<size_t, 3>& image_dims,\n            const ConvolutionKernel<REAL, 3, K>& kernel)\n        {\n            hoNDArray<std::complex<REAL>> deapodization(to_std_vector(image_dims));\n            vector_td<REAL,3> image_dims_real(image_dims);\n            for (int z = 0; z < image_dims[2]; z++) {\n                auto offset_z = z - image_dims_real[2]/2;\n                auto weight_z = kernel.get(offset_z, 2);\n\n                for (int y = 0; y < image_dims[1]; y++) {\n                    auto offset_y = y - image_dims_real[1]/2;\n                    auto weight_y = kernel.get(offset_y, 1);\n\n                    for (int x = 0; x < image_dims[0]; x++) {\n                        auto offset_x = x - image_dims_real[0]/2;\n                        auto weight_x = kernel.get(offset_x, 0);\n\n                        deapodization(x,y,z) = weight_x*weight_y*weight_z;\n                    }\n                }\n            }\n            return deapodization;\n        }\n    }\n\n\n\n    template<class REAL, unsigned int D>\n    hoNFFT_plan<REAL, D>::hoNFFT_plan(\n        const vector_td<size_t, D> &matrix_size,\n        const vector_td<size_t, D> &matrix_size_os,\n        REAL W)\n      : NFFT_plan<hoNDArray,REAL,D>(matrix_size,matrix_size_os,W)\n    {\n        this->deapodization_filter_IFFT = compute_deapodization_filter(\n            this->matrix_size_os_, this->conv_->get_kernel());\n        this->deapodization_filter_FFT = deapodization_filter_IFFT;\n\n        FFTD<std::complex<REAL>,D>::fft(\n            deapodization_filter_IFFT, NFFT_fft_mode::BACKWARDS, true);\n        FFTD<std::complex<REAL>,D>::fft(\n            deapodization_filter_FFT, NFFT_fft_mode::FORWARDS, true);\n\n        boost::transform(deapodization_filter_IFFT,\n                         deapodization_filter_IFFT.begin(),\n                         [](auto val) { return REAL(1)/val; });\n        boost::transform(deapodization_filter_FFT,\n                         deapodization_filter_FFT.begin(),\n                         [](auto val) { return REAL(1)/val; });\n    }\n\n\n    template<class REAL, unsigned int D>\n    hoNFFT_plan<REAL, D>::hoNFFT_plan(\n        const vector_td<size_t, D> &matrix_size,\n        REAL oversampling_factor,\n        REAL W)\n      : NFFT_plan<hoNDArray, REAL, D>(matrix_size, oversampling_factor, W)\n    {\n        this->deapodization_filter_IFFT = compute_deapodization_filter(\n            this->matrix_size_os_, this->conv_->get_kernel());\n        this->deapodization_filter_FFT = deapodization_filter_IFFT;\n\n        FFTD<std::complex<REAL>, D>::fft(\n            deapodization_filter_IFFT, NFFT_fft_mode::BACKWARDS, false);\n        FFTD<std::complex<REAL>, D>::fft(\n            deapodization_filter_FFT, NFFT_fft_mode::FORWARDS, false);\n        \n        boost::transform(deapodization_filter_IFFT,\n                         deapodization_filter_IFFT.begin(),\n                         [](auto val) { return REAL(1) / val; });\n        boost::transform(deapodization_filter_FFT,\n                         deapodization_filter_FFT.begin(),\n                         [](auto val) { return REAL(1) / val; });\n    }\n\n\n    template<class REAL, unsigned int D>\n    void hoNFFT_plan<REAL, D>::compute(\n            const hoNDArray<ComplexType> &d,\n            hoNDArray<ComplexType> &m,\n            const hoNDArray<REAL> *dcw,\n            NFFT_comp_mode mode\n    ) {\n        const auto *pd = reinterpret_cast<const hoNDArray<complext<REAL>> *>(&d);\n        auto *pm = reinterpret_cast<hoNDArray<complext<REAL>> *>(&m);\n\n        this->compute(*pd, *pm, dcw, mode);\n    }\n\n    template<class REAL, unsigned int D>\n    void hoNFFT_plan<REAL, D>::compute(\n            const hoNDArray<complext<REAL>> &d,\n            hoNDArray<complext<REAL>> &m,\n            const hoNDArray<REAL> *dcw,\n            NFFT_comp_mode mode\n    ) {\n       NFFT_plan<hoNDArray,REAL,D>::compute(d,m,dcw,mode);\n    }\n\n\n    template<class REAL, unsigned int D>\n    void hoNFFT_plan<REAL, D>::mult_MH_M(\n            const hoNDArray<complext<REAL>> &in,\n            hoNDArray<complext<REAL>> &out,\n            const hoNDArray<REAL>* dcw\n    ) {\n        const hoNDArray<ComplexType> *pin = reinterpret_cast<const hoNDArray<ComplexType> *>(&in);\n        hoNDArray<ComplexType> *pout = reinterpret_cast<hoNDArray<ComplexType> *>(&out);\n\n        this->mult_MH_M(*pin, *pout, dcw);\n    }\n\n\n    template<class REAL, unsigned int D>\n    void hoNFFT_plan<REAL, D>::mult_MH_M(\n            const hoNDArray<ComplexType> &in,\n            hoNDArray<ComplexType> &out,\n            const hoNDArray<REAL>* dcw\n    ) {\n        std::vector<size_t> dims = {this->number_of_samples,this->number_of_frames};\n        auto batches = in.get_number_of_elements()/(prod(this->matrix_size_)*this->number_of_frames);\n        dims.push_back(batches);\n\n        hoNDArray<ComplexType> tmp(dims);\n        compute(in, tmp, dcw, NFFT_comp_mode::FORWARDS_C2NC);\n        compute(tmp, out,dcw, NFFT_comp_mode::BACKWARDS_NC2C);\n    }\n\n    template<class REAL, unsigned int D>\n    void hoNFFT_plan<REAL, D>::fft(\n            hoNDArray<ComplexType> &d,\n            NFFT_fft_mode mode,\n            bool do_scale\n    ) {\n        FFTD<std::complex<REAL>, D>::fft(d, mode,do_scale);\n    }\n\n    template<class REAL, unsigned int D>\n    void hoNFFT_plan<REAL, D>::fft(\n            hoNDArray<complext<REAL>> &d,\n            NFFT_fft_mode mode,\n            bool do_scale\n    ) {\n        hoNDArray<ComplexType> *pd = reinterpret_cast<hoNDArray<ComplexType> *>(&d);\n        this->fft(*pd,mode,do_scale);\n    }\n\n    template<class REAL, unsigned int D>\n    void hoNFFT_plan<REAL, D>::deapodize(\n            hoNDArray<ComplexType> &d,\n            bool fourierDomain\n    ) {\n        if (fourierDomain){\n            d *= deapodization_filter_FFT;\n        } else {\n            d *= deapodization_filter_IFFT;\n        }\n    }\n\n    template<class REAL, unsigned int D>\n    void hoNFFT_plan<REAL, D>::deapodize(\n            hoNDArray<complext<REAL>> &d,\n            bool fourierDomain\n    ) {\n        hoNDArray<ComplexType> *pd = reinterpret_cast<hoNDArray<ComplexType> *>(&d);\n        this->deapodize(*pd,fourierDomain);\n    }\n\n    template<class REAL, unsigned int D>\n    boost::shared_ptr<hoNFFT_plan<REAL,D>> NFFT<hoNDArray,REAL,D>::make_plan(const Gadgetron::vector_td<size_t, D> &matrix_size,\n                                        const Gadgetron::vector_td<size_t, D> &matrix_size_os, REAL W) {\n        return boost::make_shared<hoNFFT_plan<REAL,D>>(matrix_size,matrix_size_os,W);\n    }\n\n\n\n}\n\ntemplate\nclass Gadgetron::hoNFFT_plan<float, 1>;\n\ntemplate\nclass Gadgetron::hoNFFT_plan<float, 2>;\n\ntemplate\nclass Gadgetron::hoNFFT_plan<float, 3>;\n\ntemplate\nclass Gadgetron::hoNFFT_plan<double, 1>;\n\ntemplate\nclass Gadgetron::hoNFFT_plan<double, 2>;\n\ntemplate\nclass Gadgetron::hoNFFT_plan<double, 3>;\n\ntemplate class Gadgetron::NFFT<Gadgetron::hoNDArray,float,1>;\ntemplate class Gadgetron::NFFT<Gadgetron::hoNDArray,float,2>;\ntemplate class Gadgetron::NFFT<Gadgetron::hoNDArray,float,3>;\n\n\n\ntemplate class Gadgetron::NFFT<Gadgetron::hoNDArray,double,1>;\ntemplate class Gadgetron::NFFT<Gadgetron::hoNDArray,double,2>;\ntemplate class Gadgetron::NFFT<Gadgetron::hoNDArray,double,3>;\n", "meta": {"hexsha": "5735b15ea5779b1cdd57358f1d0e954e59f84039", "size": 11077, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "toolboxes/nfft/cpu/hoNFFT.cpp", "max_stars_repo_name": "roopchansinghv/gadgetron", "max_stars_repo_head_hexsha": "fb6c56b643911152c27834a754a7b6ee2dd912da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-22T21:06:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T21:06:36.000Z", "max_issues_repo_path": "toolboxes/nfft/cpu/hoNFFT.cpp", "max_issues_repo_name": "apd47/gadgetron", "max_issues_repo_head_hexsha": "073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "toolboxes/nfft/cpu/hoNFFT.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": 33.6686930091, "max_line_length": 128, "alphanum_fraction": 0.5866209262, "num_tokens": 2883, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.458304548272326}}
{"text": "/* =========================================================================\n   Copyright (c) 2012-2014, Institute for Microelectronics,\n                            Institute for Analysis and Scientific Computing,\n                            TU Wien.\n                             -----------------\n               ViennaFEM - The Vienna Finite Element Method Library\n                             -----------------\n\n   Author:     Karl Rupp                          rupp@iue.tuwien.ac.at\n\n   License:    MIT (X11), see file LICENSE in the ViennaFEM base directory\n============================================================================ */\n\n\n// include necessary system headers\n#include <iostream>\n\n// ViennaFEM includes:\n#include \"viennafem/fem.hpp\"\n#include \"viennafem/io/vtk_writer.hpp\"\n\n// ViennaGrid includes:\n#include \"viennagrid/forwards.hpp\"\n#include \"viennagrid/config/default_configs.hpp\"\n#include \"viennagrid/io/netgen_reader.hpp\"\n\n// ViennaData includes:\n#include \"viennadata/api.hpp\"\n\n// ViennaMath includes:\n#include \"viennamath/expression.hpp\"\n\n// Boost.uBLAS includes:\n#include <boost/numeric/ublas/matrix_sparse.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/operation.hpp>\n#include <boost/numeric/ublas/operation_sparse.hpp>\n\n\n//ViennaCL includes:\n#ifndef VIENNACL_HAVE_UBLAS\n #define VIENNACL_HAVE_UBLAS\n#endif\n\n#include \"viennacl/linalg/cg.hpp\"\n#include \"viennacl/linalg/norm_2.hpp\"\n#include \"viennacl/linalg/prod.hpp\"\n\n\n\nint main()\n{\n  typedef viennagrid::tetrahedral_3d_mesh                                                 DomainType;\n  typedef viennagrid::result_of::segmentation<DomainType>::type                           SegmentationType;\n  typedef viennagrid::result_of::element<DomainType, viennagrid::vertex_tag>::type        VertexType;\n  typedef viennagrid::result_of::element_range<DomainType, viennagrid::vertex_tag>::type  VertexContainer;\n  typedef viennagrid::result_of::iterator<VertexContainer>::type                          VertexIterator;\n\n  typedef boost::numeric::ublas::compressed_matrix<viennafem::numeric_type>  MatrixType;\n  typedef boost::numeric::ublas::vector<viennafem::numeric_type>             VectorType;\n\n  typedef viennamath::function_symbol   FunctionSymbol;\n  typedef viennamath::equation          Equation;\n\n  //\n  // Create a domain from file\n  //\n  DomainType my_domain;\n  SegmentationType segments(my_domain);\n\n  //\n  // Create a storage object\n  //\n  typedef viennadata::storage<> StorageType;\n  StorageType   storage;\n\n  try\n  {\n    viennagrid::io::netgen_reader my_reader;\n    my_reader(my_domain, segments, \"../examples/data/sshape3d-pimped.mesh\");\n  }\n  catch (...)\n  {\n    std::cerr << \"File-Reader failed. Aborting program...\" << std::endl;\n    exit(EXIT_FAILURE);\n  }\n\n\n  //\n  // Specify PDE:\n  //\n  FunctionSymbol u(0, viennamath::unknown_tag<>());   //an unknown function used for PDE specification\n  Equation poisson_equ_1 = viennamath::make_equation( viennamath::laplace(u), -1);\n\n  MatrixType system_matrix;\n  VectorType load_vector;\n\n  //\n  // Setting boundary information on domain (this should come from device specification)\n  //\n  //setting some boundary flags:\n  VertexContainer vertices = viennagrid::elements<VertexType>(my_domain);\n  for (VertexIterator vit = vertices.begin();\n      vit != vertices.end();\n      ++vit)\n  {\n    //boundary for first equation: Homogeneous Dirichlet everywhere\n    if (viennagrid::point(my_domain, *vit)[2] == 3.0 || viennagrid::point(my_domain, *vit)[1] == 3.0 )\n      viennafem::set_dirichlet_boundary(storage, *vit, 0.0);\n  }\n\n\n  //\n  // Create PDE solver functors: (discussion about proper interface required)\n  //\n  viennafem::pde_assembler<StorageType> fem_assembler(storage);\n\n\n  //\n  // Solve system and write solution vector to pde_result:\n  // (discussion about proper interface required. Introduce a pde_result class?)\n  //\n  fem_assembler(viennafem::make_linear_pde_system(poisson_equ_1, u),\n                my_domain,\n                system_matrix,\n                load_vector\n               );\n\n  VectorType pde_result = viennacl::linalg::solve(system_matrix, load_vector, viennacl::linalg::cg_tag());\n  std::cout << \"* solve(): Residual: \" << norm_2(prod(system_matrix, pde_result) - load_vector) << std::endl;\n\n  //\n  // Writing solution back to domain (discussion about proper way of returning a solution required...)\n  //\n  viennafem::io::write_solution_to_VTK_file(pde_result, \"sshape_3d\", my_domain, segments, storage, 0);\n\n  std::cout << \"*****************************************\" << std::endl;\n  std::cout << \"* Poisson solver finished successfully! *\" << std::endl;\n  std::cout << \"*****************************************\" << std::endl;\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "f84e416ff7714d6bcd5c2449c71f274d576e54c9", "size": 4735, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/tutorials/sshape_3d.cpp", "max_stars_repo_name": "viennafem/viennafem-dev", "max_stars_repo_head_hexsha": "1f2d772cef5fb1c148e22e5bbbb6302b301e896b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-06-23T17:35:29.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-19T14:39:03.000Z", "max_issues_repo_path": "examples/tutorials/sshape_3d.cpp", "max_issues_repo_name": "viennafem/viennafem-dev", "max_issues_repo_head_hexsha": "1f2d772cef5fb1c148e22e5bbbb6302b301e896b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2019-11-17T03:28:47.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-04T03:40:11.000Z", "max_forks_repo_path": "examples/tutorials/sshape_3d.cpp", "max_forks_repo_name": "viennafem/viennafem-dev", "max_forks_repo_head_hexsha": "1f2d772cef5fb1c148e22e5bbbb6302b301e896b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-23T20:24:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-23T20:24:15.000Z", "avg_line_length": 33.3450704225, "max_line_length": 109, "alphanum_fraction": 0.6380147835, "num_tokens": 1128, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324848629214, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4583045457486715}}
{"text": "#include <boost/config.hpp>\n#include <iostream>\n#include <fstream>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <QDebug>\n#include \"shortestpath.h\"\n\nusing namespace boost;\n\nbool shortestPath(size_t nodeNum,\n    const std::vector<std::pair<size_t, size_t>> &edges,\n    const std::vector<int> &weights,\n    size_t start,\n    size_t stop,\n    std::vector<size_t> *path)\n{\n    typedef adjacency_list < listS, vecS, undirectedS,\n        no_property, property < edge_weight_t, int > > graph_t;\n    typedef graph_traits < graph_t >::vertex_descriptor vertex_descriptor;\n    typedef graph_traits < graph_t >::edge_descriptor edge_descriptor;\n    typedef std::pair<size_t, size_t> Edge;\n    \n    size_t edgeNum = edges.size();\n#if defined(BOOST_MSVC) && BOOST_MSVC <= 1300\n    graph_t g(nodeNum);\n    property_map<graph_t, edge_weight_t>::type weightmap = get(edge_weight, g);\n    for (std::size_t j = 0; j < edgeNum; ++j) {\n        edge_descriptor e; bool inserted;\n        tie(e, inserted) = add_edge(edges[j].first, edges[j].second, g);\n        weightmap[e] = weights[j];\n    }\n#else\n    graph_t g(edges.data(), edges.data() + edgeNum, weights.data(), nodeNum);\n    property_map<graph_t, edge_weight_t>::type weightmap = get(edge_weight, g);\n#endif\n\n    std::vector<vertex_descriptor> p(num_vertices(g));\n    std::vector<size_t> d(num_vertices(g));\n    vertex_descriptor s = vertex(start, g);\n\n#if defined(BOOST_MSVC) && BOOST_MSVC <= 1300\n    // VC++ has trouble with the named parameters mechanism\n    property_map<graph_t, vertex_index_t>::type indexmap = get(vertex_index, g);\n    dijkstra_shortest_paths(g, s, &p[0], &d[0], weightmap, indexmap,\n                          std::less<size_t>(), closed_plus<size_t>(),\n                          (std::numeric_limits<size_t>::max)(), 0,\n                          default_dijkstra_visitor());\n#else\n    dijkstra_shortest_paths(g, s, predecessor_map(&p[0]).distance_map(&d[0]));\n#endif\n\n    auto current = stop;\n    while (current != start) {\n        path->push_back(current);\n        size_t next = p[current];\n        if (next == current)\n            return false;\n        current = next;\n    }\n    path->push_back(current);\n    \n    return true;\n}\n", "meta": {"hexsha": "19a0df372f96ab8844cadda69378d749e1d5bcfe", "size": 2288, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/shortestpath.cpp", "max_stars_repo_name": "st4ll1/dust3d", "max_stars_repo_head_hexsha": "c1de02f7ddcfdacc730cc96740f8073f87e7818c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/shortestpath.cpp", "max_issues_repo_name": "st4ll1/dust3d", "max_issues_repo_head_hexsha": "c1de02f7ddcfdacc730cc96740f8073f87e7818c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/shortestpath.cpp", "max_forks_repo_name": "st4ll1/dust3d", "max_forks_repo_head_hexsha": "c1de02f7ddcfdacc730cc96740f8073f87e7818c", "max_forks_repo_licenses": ["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.6666666667, "max_line_length": 80, "alphanum_fraction": 0.6542832168, "num_tokens": 577, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174789, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4582340738293963}}
{"text": "/********************************************************************************\n * Copyright 2009 The Robotics Group, The Maersk Mc-Kinney Moller Institute,\n * Faculty of Engineering, University of Southern Denmark\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n ********************************************************************************/\n\n#ifndef RW_MATH_INTERIORPOINTOPTIMIZER_HPP\n#define RW_MATH_INTERIORPOINTOPTIMIZER_HPP\n\n#include <rw/math/Math.hpp>\n\n#include <iostream>\n#include <boost/function.hpp>\n#include <boost/bind.hpp>\n\nnamespace rw {\nnamespace math {\n\n\nclass InteriorPointOptimizer\n{\npublic:\n\n    typedef boost::function<void(const Eigen::VectorXd& x,\n                                 double& f,\n                                 Eigen::VectorXd& df,\n                                 Eigen::MatrixXd& ddf) > ObjectFunction;\n\n    typedef void*(Q& q) ObjectFunction;\n\n    typedef boost::function<void(const Eigen::VectorXd& x,\n                                 size_t no,\n                                 Eigen::VectorXd& g,\n                                 Eigen::MatrixXd& dg,\n                                 Eigen::MatrixXd& ddq) > ConstraintFunction;\n\n    InteriorPointOptimizer(size_t n,\n                           size_t m,\n                           ObjectFunction objectFunction,\n                           ConstraintFunction constraintFunction);\n\n    virtual ~InteriorPointOptimizer();\n\n\n    int solve(const Eigen::VectorXd& x_init);\n\n    void setAccuracy(double accuracy);\n    double getAccuracy();\n\n    void verify_user_defined_objective_and_constraints();\n\n\nprotected:\n    InteriorPointOptimizer(size_t n, size_t m);\n\n    void initialize();\n\n    virtual void objectFunction(const Eigen::VectorXd& x,\n                                double &f,\n                                Eigen::VectorXd &df,\n                                Eigen::MatrixXd &ddf);\n\n    virtual void constraintFunction(const Eigen::VectorXd& x,\n                                    int i,\n                                    Eigen::VectorXd &a,\n                                    Eigen::MatrixXd &da,\n                                    Eigen::MatrixXd &dda);\n\nprivate:\n    ObjectFunction compute_f_info_EXT;\n    ConstraintFunction compute_con_info_i_EXT;\n\n\n    void choleskySolve(int n_e,\n                       int bw,\n                       Eigen::MatrixXd &A,\n                       Eigen::VectorXd &b,\n                       Eigen::VectorXd &x);\n\n\n    void compute_f_info(Eigen::MatrixXd &A,\n                        Eigen::VectorXd &RHS);\n\n    void compute_con_info(Eigen::MatrixXd &A,\n                          Eigen::VectorXd &RHS);\n\n    void merit_info(Eigen::VectorXd &x,\n                    Eigen::VectorXd &s,\n                    double &phi,\n                    double &eta);\n\n    void Dmerit_info(Eigen::VectorXd &x,\n                     Eigen::VectorXd &s,\n                     Eigen::VectorXd &dx,\n                     Eigen::VectorXd &ds,\n                     double &Dphi,\n                     double &eta);\n\n    void update(Eigen::VectorXd &x,\n                Eigen::VectorXd &dx,\n                Eigen::VectorXd &s,\n                Eigen::VectorXd &z);\n\n    const size_t N;\n    const size_t M;\n    double _accuracy;\n    Eigen::VectorXd _x;\n    Eigen::VectorXd _s;\n    Eigen::VectorXd _z;\n    double _mu, _eta;\n\n    // objective and derivatives\n    double _f;\n    Eigen::VectorXd _df;\n    Eigen::MatrixXd _ddf;\n\n    // constraints and derivatives (second derivative only stored for one constraint at a time)\n    Eigen::VectorXd _a;\n    Eigen::MatrixXd _da;\n    Eigen::MatrixXd _dda;\n\n\n};\n\n} //end namespace math\n} //end namespace rw\n\n#endif //end include guard\n", "meta": {"hexsha": "058f85f889b06cc92a276b295173f913ebc94482", "size": 4190, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "RobWork/src/sandbox/interiorpoint/InteriorPointOptimizer.hpp", "max_stars_repo_name": "ZLW07/RobWork", "max_stars_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-29T14:16:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T14:16:27.000Z", "max_issues_repo_path": "RobWork/src/sandbox/interiorpoint/InteriorPointOptimizer.hpp", "max_issues_repo_name": "ZLW07/RobWork", "max_issues_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RobWork/src/sandbox/interiorpoint/InteriorPointOptimizer.hpp", "max_forks_repo_name": "ZLW07/RobWork", "max_forks_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9285714286, "max_line_length": 95, "alphanum_fraction": 0.5410501193, "num_tokens": 784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.45823407382939624}}
{"text": "//ros\n#include <ros/ros.h>\n#include <nav_msgs/Path.h>\n#include <geometry_msgs/PoseStamped.h>\n#include <geometry_msgs/Twist.h>\n#include <tf/tf.h>\n#include <tf/transform_listener.h>\n#include <geometry_msgs/TransformStamped.h>\n#include <geometry_msgs/PoseArray.h>\n\n//ipopt\n#include <Eigen/Core>\n#include <cppad/cppad.hpp>\n#include <cppad/ipopt/solve.hpp>\n\nusing CppAD::AD;\n\nclass MPC{\npublic:\n    MPC();\n\n    // state, ref_x, ref_y, ref_yaw\n    std::vector<double> solve(Eigen::VectorXd, Eigen::VectorXd, Eigen::VectorXd, Eigen::VectorXd);\n\n};\n\nclass FG_eval{\npublic:\n    FG_eval(Eigen::VectorXd, Eigen::VectorXd, Eigen::VectorXd);\n\n    typedef CPPAD_TESTVECTOR(AD<double>) ADvector;\n\n    void operator()(ADvector&, const ADvector&);\n\nprivate:\n    Eigen::VectorXd ref_x;\n    Eigen::VectorXd ref_y;\n    Eigen::VectorXd ref_yaw;\n\n};\n\nclass MPCPathTracker\n{\npublic:\n    MPCPathTracker(void);\n\n    void path_callback(const nav_msgs::PathConstPtr&);\n\n    void process(void);\n    void path_to_vector(void);\n\nprivate:\n    ros::NodeHandle nh;\n    ros::Publisher velocity_pub;\n    ros::Publisher path_pub;\n    ros::Subscriber path_sub;\n    MPC mpc;\n    nav_msgs::Path path;\n    tf::TransformListener listener;\n    geometry_msgs::PoseStamped current_pose;\n    geometry_msgs::PoseStamped previous_pose;\n    tf::StampedTransform _transform;\n    geometry_msgs::TransformStamped transform;\n    Eigen::VectorXd path_x;\n    Eigen::VectorXd path_y;\n    Eigen::VectorXd path_yaw;\n    bool first_transform = true;\n    double last_time;\n\n};\n\n// \u30db\u30e9\u30a4\u30be\u30f3\u9577\u3055\nint T = 15;\n// \u5468\u671f\ndouble DT = 0.1;// [s]\nconst double HZ = 10;\n// \u76ee\u6a19\u901f\u5ea6\ndouble VREF;// [m/s]\n// \u6700\u5927\u901f\u5ea6\ndouble MAX_VELOCITY; // [m/s]\n// \u6700\u5927\u89d2\u901f\u5ea6\ndouble MAX_ANGULAR_VELOCITY;// [rad/s]\n// \u30db\u30a4\u30fc\u30eb\u89d2\u52a0\u901f\u5ea6\ndouble WHEEL_ANGULAR_ACCELERATION_LIMIT;// [rad/s^2]\n// \u30db\u30a4\u30fc\u30eb\u89d2\u901f\u5ea6\ndouble WHEEL_ANGULAR_VELOCITY_LIMIT;// [rad/s]\n// \u30db\u30a4\u30fc\u30eb\u534a\u5f84\ndouble WHEEL_RADIUS;// [m]\n// \u30c8\u30ec\u30c3\u30c9\ndouble TREAD;// [m]\n// \u30b0\u30ea\u30c3\u30c9\u30de\u30c3\u30d7\u5206\u89e3\u80fd\ndouble RESOLUTION;// [m]\n\nstd::string WORLD_FRAME;\nstd::string ROBOT_FRAME;\nstd::string VELOCITY_TOPIC_NAME;\nstd::string INTERMEDIATE_PATH_TOPIC_NAME;\n\n// state\nsize_t x_start = 0;\nsize_t y_start = x_start + T;\nsize_t yaw_start = y_start + T;\nsize_t v_start = yaw_start + T;\nsize_t omega_start = v_start + T;\nsize_t omega_r_start = omega_start + T;\nsize_t omega_l_start = omega_r_start + T;\n// input\nsize_t domega_r_start = omega_l_start + T;\nsize_t domega_l_start = domega_r_start + T - 1;\n\n// \u6700\u9069\u5316\u5931\u6557\u6642\u306f\u6700\u5f8c\u306e\u6210\u529f\u30c7\u30fc\u30bf\u3092\u4f7f\u3046\nint failure_count = 0;\nstd::vector<double> result;\n\ndouble min_distance(nav_msgs::Path&, geometry_msgs::PoseStamped&);\ndouble get_distance(geometry_msgs::PoseStamped&, geometry_msgs::PoseStamped&);\n\nint main(int argc, char** argv)\n{\n    ros::init(argc, argv, \"diff_drive_mpc\");\n    ros::NodeHandle local_nh(\"~\");\n\n    local_nh.getParam(\"HORIZON_T\", T);\n    local_nh.getParam(\"/dynamic_avoidance/VREF\", VREF);\n    local_nh.getParam(\"/dynamic_avoidance/MAX_ANGULAR_VELOCITY\", MAX_ANGULAR_VELOCITY);\n    local_nh.getParam(\"/diff_drive/MAX_WHEEL_ANGULAR_ACCELERATION\", WHEEL_ANGULAR_ACCELERATION_LIMIT);\n    local_nh.getParam(\"/diff_drive/MAX_WHEEL_ANGULAR_VELOCITY\", WHEEL_ANGULAR_VELOCITY_LIMIT);\n    local_nh.getParam(\"/diff_drive/WHEEL_RADIUS\", WHEEL_RADIUS);\n    local_nh.getParam(\"/diff_drive/TREAD\", TREAD);\n    local_nh.getParam(\"/diff_drive/MAX_VELOCITY\", MAX_VELOCITY);\n    local_nh.getParam(\"/dynamic_avoidance/RESOLUTION\", RESOLUTION);\n    local_nh.getParam(\"/dynamic_avoidance/ROBOT_FRAME\", ROBOT_FRAME);\n    local_nh.getParam(\"/dynamic_avoidance/WORLD_FRAME\", WORLD_FRAME);\n    local_nh.getParam(\"/dynamic_avoidance/VELOCITY_TOPIC_NAME\", VELOCITY_TOPIC_NAME);\n    local_nh.getParam(\"/dynamic_avoidance/INTERMEDIATE_PATH_TOPIC_NAME\", INTERMEDIATE_PATH_TOPIC_NAME);\n\n    std::cout << \"T: \" << T << std::endl;\n    std::cout << \"VREF: \" << VREF << std::endl;\n    std::cout << \"MAX_VELOCITY: \" << MAX_VELOCITY << std::endl;\n    std::cout << \"MAX_ANGULAR_VELOCITY: \" << MAX_ANGULAR_VELOCITY << std::endl;\n    std::cout << \"WHEEL_ANGULAR_VELOCITY_LIMIT: \" << WHEEL_ANGULAR_VELOCITY_LIMIT << std::endl;\n    std::cout << \"WHEEL_ANGULAR_ACCELERATION_LIMIT: \" << WHEEL_ANGULAR_ACCELERATION_LIMIT << std::endl;\n    std::cout << \"WHEEL_RADIUS: \" << WHEEL_RADIUS << std::endl;\n    std::cout << \"TREAD: \" << TREAD << std::endl;\n    std::cout << \"RESOLUTION: \" << RESOLUTION << std::endl;\n    std::cout << \"ROBOT_FRAME: \" << ROBOT_FRAME << std::endl;\n    std::cout << \"WORLD_FRAME: \" << WORLD_FRAME << std::endl;\n    std::cout << \"VELOCITY_TOPIC_NAME: \" << VELOCITY_TOPIC_NAME << std::endl;\n    std::cout << \"INTERMEDIATE_PATH_TOPIC_NAME: \" << INTERMEDIATE_PATH_TOPIC_NAME << std::endl;\n\n    MPCPathTracker mpc_path_tracker;\n\n    ros::Rate loop_rate(HZ);\n\n    while(ros::ok()){\n        mpc_path_tracker.process();\n\n        ros::spinOnce();\n        loop_rate.sleep();\n    }\n    return 0;\n}\n\nMPC::MPC(){}\n\nstd::vector<double> MPC::solve(Eigen::VectorXd state, Eigen::VectorXd ref_x, Eigen::VectorXd ref_y, Eigen::VectorXd ref_yaw)\n{\n    /*\n     * state:x, y, yaw, v, omega, omega_r, omega_l\n     */\n    bool ok = true;\n    size_t i;\n    typedef CPPAD_TESTVECTOR(double) Dvector;\n\n    double x = state[0];\n    double y = state[1];\n    double yaw = state[2];\n    double v = state[3];\n    double omega = state[4];\n    double omega_r = state[5];\n    double omega_l = state[6];\n\n    /*\n    std::cout << \"--- state ---\" << std::endl;\n    std::cout << state << std::endl;\n    std::cout << \"--- path_x ---\" << std::endl;\n    std::cout << ref_x << std::endl;\n    std::cout << \"--- path_y ---\" << std::endl;\n    std::cout << ref_y << std::endl;\n    std::cout << \"--- path_yaw ---\" << std::endl;\n    std::cout << ref_yaw << std::endl;\n    */\n\n    // 7(x, y, yaw, v, omega, omega_r, omega_l), 2(domega_r, domega_l)\n    size_t n_variables = 7 * T + 2 * (T - 1);\n\n    size_t n_constraints = 7 * T;\n\n    Dvector vars(n_variables);\n    for(int i=0;i<n_variables;i++){\n        vars[i] = 0.0;\n    }\n\n    vars[x_start] = x;\n    vars[y_start] = y;\n    vars[yaw_start] = yaw;\n    vars[v_start] = v;\n    vars[omega_start] = omega;\n    vars[omega_r_start] = omega_r;\n    vars[omega_l_start] = omega_l;\n\n    Dvector vars_lower_bound(n_variables);\n    Dvector vars_upper_bound(n_variables);\n\n    for(int i=0;i<v_start;i++){\n        // x, y, yaw\n        vars_lower_bound[i] = -1.0e19;\n        vars_upper_bound[i] = 1.0e19;\n    }\n    for(int i=v_start;i<omega_start;i++){\n        // v\n        vars_lower_bound[i] = 0;\n        vars_upper_bound[i] = MAX_VELOCITY;\n    }\n    for(int i=omega_start;i<omega_r_start;i++){\n        // omega\n        vars_lower_bound[i] = -MAX_ANGULAR_VELOCITY;\n        vars_upper_bound[i] = MAX_ANGULAR_VELOCITY;\n    }\n    for(int i=omega_r_start;i<domega_r_start;i++){\n        // omega_r, omega_l\n        vars_lower_bound[i] = -WHEEL_ANGULAR_VELOCITY_LIMIT;\n        vars_upper_bound[i] = WHEEL_ANGULAR_VELOCITY_LIMIT;\n    }\n    for(int i=omega_start;i<n_variables;i++){\n        // domega_r, domega_l\n        vars_lower_bound[i] = -WHEEL_ANGULAR_ACCELERATION_LIMIT;\n        vars_upper_bound[i] = WHEEL_ANGULAR_ACCELERATION_LIMIT;\n    }\n\n    // \u7b49\u5f0f\u5236\u7d04\n    Dvector constraints_lower_bound(n_constraints);\n    Dvector constraints_upper_bound(n_constraints);\n\n    for(int i=0;i<n_constraints;i++){\n        constraints_lower_bound[i] = 0.0;\n        constraints_upper_bound[i] = 0.0;\n    }\n\n    // t=0\u306e\u8a2d\u5b9a\n    constraints_lower_bound[x_start] = x;\n    constraints_lower_bound[y_start] = y;\n    constraints_lower_bound[yaw_start] = yaw;\n    constraints_lower_bound[v_start] = v;\n    constraints_lower_bound[omega_start] = omega;\n    constraints_lower_bound[omega_r_start] = omega_r;\n    constraints_lower_bound[omega_l_start] = omega_l;\n\n    constraints_upper_bound[x_start] = x;\n    constraints_upper_bound[y_start] = y;\n    constraints_upper_bound[yaw_start] = yaw;\n    constraints_upper_bound[v_start] = v;\n    constraints_upper_bound[omega_start] = omega;\n    constraints_upper_bound[omega_r_start] = omega_r;\n    constraints_upper_bound[omega_l_start] = omega_l;\n\n    FG_eval fg_eval(ref_x, ref_y, ref_yaw);\n\n    std::string options;\n    options += \"Integer print_level  0\\n\";\n\n    options += \"Sparse  true                forward\\n\";\n    options += \"Sparse  true                reverse\\n\";\n\n    options += \"Numeric max_cpu_time                    0.5\\n\";\n\n    CppAD::ipopt::solve_result<Dvector> solution;\n\n    std::cout << \"optimization start\" << std::endl;\n    CppAD::ipopt::solve<Dvector, FG_eval>(\n            options, vars, vars_lower_bound, vars_upper_bound, constraints_lower_bound,\n            constraints_upper_bound, fg_eval, solution);\n\n    std::cout << \"optimization end\" << std::endl;\n    ok &= solution.status == CppAD::ipopt::solve_result<Dvector>::success;\n    std::cout << solution.status << std::endl;\n    std::cout << ok << std::endl;\n\n    auto cost = solution.obj_value;\n    std::cout << \"Cost \" << cost << std::endl;\n\n    if(ok){\n        failure_count = 0;\n        result.clear();\n        // \u4f55\u6545\u304b0\u3060\u3068\u3046\u307e\u304f\u884c\u304b\u306a\u3044\n        result.push_back(solution.x[v_start+1]);\n        result.push_back(solution.x[omega_start+1]);\n        //\u4e88\u6e2c\u8ecc\u9053\n        for(int i = 0; i < T-1; i++){\n            result.push_back(solution.x[x_start+i+1]);\n            result.push_back(solution.x[y_start+i+1]);\n            result.push_back(solution.x[yaw_start+i+1]);\n        }\n    }else{\n        if(failure_count < T - 1){\n            failure_count++;\n        }\n        result.push_back(solution.x[v_start+1+failure_count]);\n        result.push_back(solution.x[omega_start+1+failure_count]);\n        result[v_start] = result[v_start + failure_count];\n        result[omega_start] = result[omega_start + failure_count];\n\n        //\u4e88\u6e2c\u8ecc\u9053\n        for(int i = failure_count; i < T-1; i++){\n            /*\n            result.push_back(solution.x[x_start+i+1]);\n            result.push_back(solution.x[y_start+i+1]);\n            result.push_back(solution.x[yaw_start+i+1]);\n            */\n        }\n    }\n    /*\n    std::cout << \"--- result ---\" << std::endl;\n    for(int i=0;i<result.size();i++){\n        std::cout << result[i] << std::endl;\n    }\n    */\n    return result;\n}\n\nFG_eval::FG_eval(Eigen::VectorXd ref_x, Eigen::VectorXd ref_y, Eigen::VectorXd ref_yaw)\n{\n    this->ref_x = ref_x;\n    this->ref_y = ref_y;\n    this->ref_yaw = ref_yaw;\n}\n\nvoid FG_eval::operator()(ADvector& fg, const ADvector& vars)\n{\n    std::cout << \"FG_eval() start\" << std::endl;\n    // cost\n    fg[0] = 0;\n    // state\n    for(int i=0;i<T-1;i++){\n        // path\u3068\u306e\u8ddd\u96e2\n        fg[0] += 0.2 * (CppAD::pow(vars[x_start + i] - ref_x[i], 2) + CppAD::pow(vars[y_start + i] - ref_y[i], 2));\n        // \u5411\u304d\n        //fg[0] += 0.1 * CppAD::pow(vars[yaw_start + i] - ref_yaw[i], 2);\n        // \u901f\u5ea6\n        fg[0] += 100 * CppAD::pow(VREF - vars[v_start + i], 2);\n        // \u89d2\u52a0\u901f\u5ea6\n        fg[0] += 0.1 * CppAD::pow(vars[omega_start + i] - vars[omega_start + i+ 1], 2);\n    }\n    // input\n    for(int i=0;i<T-2;i++){\n    }\n\n    std::cout << \"constrains start\" << std::endl;\n    //constraint\n    //\u521d\u671f\u72b6\u614b\n    fg[1 + x_start] = vars[x_start];\n    fg[1 + y_start] = vars[y_start];\n    fg[1 + yaw_start] = vars[yaw_start];\n    fg[1 + v_start] = vars[v_start];\n    fg[1 + omega_start] = vars[omega_start];\n    fg[1 + omega_r_start] = vars[omega_r_start];\n    fg[1 + omega_l_start] = vars[omega_l_start];\n\n    std::cout << \"constraints loop start\" << std::endl;\n\n    for(int i=0;i<T-1;i++){\n        //t+1\n        AD<double> x1 = vars[x_start + i + 1];\n        AD<double> y1 = vars[y_start + i + 1];\n        AD<double> yaw1 = vars[yaw_start + i + 1];\n        AD<double> v1 = vars[v_start + i + 1];\n        AD<double> omega1 = vars[omega_start + i + 1];\n        AD<double> omega_r1 = vars[omega_r_start + i + 1];\n        AD<double> omega_l1 = vars[omega_l_start + i + 1];\n        //t\n        AD<double> x0 = vars[x_start + i];\n        AD<double> y0 = vars[y_start + i];\n        AD<double> yaw0 = vars[yaw_start + i];\n        AD<double> v0 = vars[v_start + i];\n        AD<double> omega0 = vars[omega_start + i];\n        AD<double> omega_r0 = vars[omega_r_start + i];\n        AD<double> omega_l0 = vars[omega_l_start + i];\n        //\u5165\u529b\u30db\u30e9\u30a4\u30be\u30f3\u306ft+1\u3092\u8003\u616e\u3057\u306a\u3044\n        AD<double> domega_r0 = vars[domega_r_start + i];\n        AD<double> domega_l0 = vars[domega_l_start + i];\n\n        //\u5236\u7d04\n        fg[2 + omega_r_start + i] = omega_r1 - (omega_r0 + domega_r0 * DT);\n        fg[2 + omega_l_start + i] = omega_l1 - (omega_l0 + domega_l0 * DT);\n        fg[2 + v_start + i] = v1 - (WHEEL_RADIUS / 2.0) * (omega_r1 + omega_l1);\n        fg[2 + omega_start + i] = omega1 - (WHEEL_RADIUS / TREAD) * (omega_r1 - omega_l1);\n        fg[2 + x_start + i] = x1 - (x0 + v0 * CppAD::cos(yaw0) * DT);\n        fg[2 + y_start + i] = y1 - (y0 + v0 * CppAD::sin(yaw0) * DT);\n        fg[2 + yaw_start + i] = yaw1 - (yaw0 + omega0 * DT);\n    }\n    std::cout << \"FG_eval() end\" << std::endl;\n}\n\nMPCPathTracker::MPCPathTracker(void)\n{\n    velocity_pub = nh.advertise<geometry_msgs::Twist>(VELOCITY_TOPIC_NAME, 1);\n    path_pub = nh.advertise<geometry_msgs::PoseArray>(\"/mpc_path\", 1);\n    path_sub = nh.subscribe(INTERMEDIATE_PATH_TOPIC_NAME, 1, &MPCPathTracker::path_callback, this);\n    path_x = Eigen::VectorXd::Zero(T);\n    path_y = Eigen::VectorXd::Zero(T);\n    path_yaw = Eigen::VectorXd::Zero(T);\n    std::cout << \"=== mpc_path_tracker ===\" << std::endl;\n}\n\nvoid MPCPathTracker::path_callback(const nav_msgs::PathConstPtr& msg)\n{\n    std::cout << \"path callback\" << std::endl;\n    path = *msg;\n}\n\nvoid MPCPathTracker::process(void)\n{\n    bool transformed = false;\n    geometry_msgs::PoseStamped pose;\n    try{\n        listener.lookupTransform(WORLD_FRAME, ROBOT_FRAME, ros::Time(0), _transform);\n        tf::transformStampedTFToMsg(_transform, transform);\n        current_pose.header = transform.header;\n        current_pose.pose.position.x = transform.transform.translation.x;\n        current_pose.pose.position.y = transform.transform.translation.y;\n        current_pose.pose.orientation = transform.transform.rotation;\n        pose.header = current_pose.header;\n        pose.pose.position.x = 0;\n        pose.pose.position.y = 0;\n        pose.pose.orientation = transform.transform.rotation;\n        transformed = true;\n    }catch(tf::TransformException &ex){\n        std::cout << ex.what() << std::endl;\n    }\n\n    if(!path.poses.empty() && transformed){\n        std::cout << \"=== diff drive mpc ===\" << std::endl;\n        ros::Time start_time = ros::Time::now();\n        if(first_transform){\n            last_time = ros::Time::now().toSec();\n            first_transform = false;\n        }else{\n            //std::cout << current_pose << std::endl;\n            double current_time = ros::Time::now().toSec();\n            double dt = current_time - last_time;\n            last_time = current_time;\n            double dx = current_pose.pose.position.x - previous_pose.pose.position.x;\n            double dy = current_pose.pose.position.y - previous_pose.pose.position.y;\n            double dyaw = tf::getYaw(current_pose.pose.orientation) - tf::getYaw(previous_pose.pose.orientation);\n            double v = sqrt(dx * dx + dy * dy) / dt;\n            double omega = dyaw / dt;\n            double omega_r = (v + omega * TREAD / 2.0) / WHEEL_RADIUS;\n            double omega_l = (v - omega * TREAD / 2.0) / WHEEL_RADIUS;\n\n            Eigen::VectorXd state(7);\n            state << pose.pose.position.x, pose.pose.position.y, tf::getYaw(pose.pose.orientation), v, omega, omega_r, omega_l;\n            std::cout << \"path to vector\" << std::endl;\n            path_to_vector();\n            std::cout << \"solving\" << std::endl;\n            auto result = mpc.solve(state, path_x, path_y, path_yaw);\n            std::cout << \"solved\" << std::endl;\n            geometry_msgs::Twist velocity;\n            velocity.linear.x = result[0];\n            velocity.angular.z = result[1];\n            std::cout << velocity << std::endl;\n            velocity_pub.publish(velocity);\n            // mpc\u8868\u793a\n            geometry_msgs::PoseArray mpc_path;\n            mpc_path.header.frame_id = ROBOT_FRAME;\n            double yaw0 = tf::getYaw(pose.pose.orientation);\n            for(int i=0;i<T-1;i++){\n                geometry_msgs::Pose temp;\n                temp.position.x = result[2+3*i] * cos(-yaw0) - result[3+3*i] * sin(-yaw0);\n                temp.position.y = result[2+3*i] * sin(-yaw0) + result[3+3*i] * cos(-yaw0);\n                temp.orientation = tf::createQuaternionMsgFromYaw(result[4+3*i] - yaw0);\n                mpc_path.poses.push_back(temp);\n            }\n            path_pub.publish(mpc_path);\n            // ~mpc\u8868\u793a\n            path.poses.erase(path.poses.begin());\n        }\n        std::cout << ros::Time::now() - start_time << \"[s]\" << std::endl;\n    }\n    previous_pose = current_pose;\n}\n\nvoid MPCPathTracker::path_to_vector(void)\n{\n    int m = VREF * DT / RESOLUTION + 1;// TODO:delete 1\n    int index = 0;\n    for(int i=0;i<T;i++){\n        if(i*m<path.poses.size()){\n            index = i*m;\n            path_x[i] = path.poses[index].pose.position.x;\n            path_y[i] = path.poses[index].pose.position.y;\n            path_yaw[i] = tf::getYaw(path.poses[index].pose.orientation);\n        }else{\n            path_x[i] = path.poses[path.poses.size() - 1].pose.position.x;\n            path_y[i] = path.poses[path.poses.size() - 1].pose.position.y;\n            path_yaw[i] = tf::getYaw(path.poses[path.poses.size() - 1].pose.orientation);\n        }\n    }\n}\n\ndouble min_distance(nav_msgs::Path& path, geometry_msgs::PoseStamped& pose)\n{\n    int length = path.poses.size();\n    double min_distance = 100;\n    for(int i=0;i<length;i++){\n        double distance = get_distance(path.poses[i], pose);\n        if(min_distance > distance){\n            min_distance = distance;\n        }\n    }\n    return min_distance;\n}\n\ndouble get_distance(geometry_msgs::PoseStamped& pose0, geometry_msgs::PoseStamped& pose1)\n{\n    return sqrt((pose0.pose.position.x - pose1.pose.position.x) * (pose0.pose.position.x - pose1.pose.position.x) + (pose0.pose.position.y - pose1.pose.position.y) * (pose0.pose.position.y - pose1.pose.position.y));\n}\n", "meta": {"hexsha": "736b3a96ef3c5027dd20f140d14c246674900c8c", "size": 18037, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/diff_drive_mpc.cpp", "max_stars_repo_name": "amslabtech/dynamic_obstacle_avoidance_planner", "max_stars_repo_head_hexsha": "e8d3a883f917cb247529204ab8ebb591247bae69", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 33.0, "max_stars_repo_stars_event_min_datetime": "2019-08-23T12:38:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-15T09:06:11.000Z", "max_issues_repo_path": "src/diff_drive_mpc.cpp", "max_issues_repo_name": "amslabtech/dynamic_obstacle_avoidance_planner", "max_issues_repo_head_hexsha": "e8d3a883f917cb247529204ab8ebb591247bae69", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2019-08-16T03:16:02.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-23T14:29:52.000Z", "max_forks_repo_path": "src/diff_drive_mpc.cpp", "max_forks_repo_name": "amslabtech/dynamic_obstacle_avoidance_planner", "max_forks_repo_head_hexsha": "e8d3a883f917cb247529204ab8ebb591247bae69", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2019-08-06T11:34:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-15T09:10:49.000Z", "avg_line_length": 34.2258064516, "max_line_length": 215, "alphanum_fraction": 0.6200033265, "num_tokens": 5133, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.45823407382939624}}
{"text": "/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\\n|  Phycas: Python software for phylogenetic analysis                          |\n|  Copyright (C) 2006 Mark T. Holder, Paul O. Lewis and David L. Swofford     |\n|                                                                             |\n|  This program is free software; you can redistribute it and/or modify       |\n|  it under the terms of the GNU General Public License as published by       |\n|  the Free Software Foundation; either version 2 of the License, or          |\n|  (at your option) any later version.                                        |\n|                                                                             |\n|  This program is distributed in the hope that it will be useful,            |\n|  but WITHOUT ANY WARRANTY; without even the implied warranty of             |\n|  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the              |\n|  GNU General Public License for more details.                               |\n|                                                                             |\n|  You should have received a copy of the GNU General Public License along    |\n|  with this program; if not, write to the Free Software Foundation, Inc.,    |\n|  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.                |\n\\~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n\n#if ! defined(STATE_FREQ_MOVE_HPP)\n#define STATE_FREQ_MOVE_HPP\n\n#include <vector>                           // for std::vector\n#include <boost/shared_ptr.hpp>             // for boost::shared_ptr\n#include <boost/weak_ptr.hpp>               // for boost::weak_ptr\n#include \"mcmc_updater.hpp\"\t\t// for base class MCMCUpdater\n#include \"partition_model.hpp\"   // for PartitionModelShPtr definition\n#include \"dirichlet_move.hpp\"\n#include \"multivariate_probability_distribution.hpp\"\n\nnamespace phycas\n{\n\nclass MCMCChainManager;\ntypedef boost::weak_ptr<MCMCChainManager>\t\t\tChainManagerWkPtr;\n\ntypedef boost::shared_ptr<DirichletDistribution>    DirichletShPtr;\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tA StateFreqMove proposes new state frequencies that are slightly different than the current frequencies by sampling\n|   from a Dirichlet distribution with parameters equal to the current frequencies multiplied by a large value (the\n|   tuning parameter 'psi').\n*/\nclass StateFreqMove : public DirichletMove\n\t{\n\tpublic:\n\t\t\t\t\t\t\t\t\tStateFreqMove();\n                                    virtual ~StateFreqMove() {}\n\n\t\tvirtual void\t\t\t\tsendCurrValuesToModel(const double_vect_t & v);\n\t\tvirtual void\t\t\t\tgetCurrValuesFromModel(double_vect_t & v) const;\n\t\tvirtual double_vect_t\t\tlistCurrValuesFromModel();\n        virtual void                getParams();\n        virtual void                setParams(const std::vector<double> & v);\n\n\tprivate:\n\n\t\tStateFreqMove &\t\t\t\toperator=(const StateFreqMove &);\t// never use - don't define\n    };\n\n} // namespace phycas\n\n#endif\n", "meta": {"hexsha": "027a64d8878001e0b1eeb6cbb21622f39544f986", "size": 3073, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/cpp/state_freq_move.hpp", "max_stars_repo_name": "plewis/phycas", "max_stars_repo_head_hexsha": "9f5a4d9b2342dab907d14a46eb91f92ad80a5605", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-09-24T23:12:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-12T07:07:01.000Z", "max_issues_repo_path": "src/cpp/state_freq_move.hpp", "max_issues_repo_name": "plewis/phycas", "max_issues_repo_head_hexsha": "9f5a4d9b2342dab907d14a46eb91f92ad80a5605", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cpp/state_freq_move.hpp", "max_forks_repo_name": "plewis/phycas", "max_forks_repo_head_hexsha": "9f5a4d9b2342dab907d14a46eb91f92ad80a5605", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-11-23T10:35:43.000Z", "max_forks_repo_forks_event_max_datetime": "2015-11-23T10:35:43.000Z", "avg_line_length": 48.015625, "max_line_length": 120, "alphanum_fraction": 0.5519036772, "num_tokens": 589, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4582340673694571}}
{"text": "/*\n Copyright (c) 2015-2017 Paul Lagr\u00e9e, Siyu Lei, Silviu Maniu, Luyi Mo\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n THE SOFTWARE.\n */\n\n#ifndef __oim__BetaInfluence__\n#define __oim__BetaInfluence__\n\n#include \"common.hpp\"\n#include \"InfluenceDistribution.hpp\"\n\n#include <boost/math/distributions.hpp>\n#include <random>\n#include <sys/time.h>\n#include <math.h>\n\nclass BetaInfluence: public InfluenceDistribution {\n private:\n  double alpha_prior_, beta_prior_;\n  double alpha_, beta_;\n  double quartile_med_;\n  double quartile_upper_;\n  double quartile_stdev_;\n  double original_mean_;\n  std::default_random_engine gen_;\n\n public:\n  BetaInfluence(double alpha, double beta, double orig)\n      : alpha_prior_(alpha), beta_prior_(beta), alpha_(alpha), beta_(beta),\n        original_mean_(orig), gen_(seed_ns()) {\n    update_quartiles();\n  }\n\n  void update(unode_int hit, unode_int miss) {\n    alpha_ += (double)hit;\n    beta_ += (double)miss;\n    hits_ += hit;\n    misses_ += miss;\n    update_quartiles();\n  };\n\n  void update_prior(double new_alpha, double new_beta) {\n    alpha_prior_ = (new_alpha) > 0 ? new_alpha : 1.0;\n    beta_prior_ = (new_beta) > 0 ? new_beta : 1.0;\n    alpha_ = alpha_prior_ + (double)hits_;\n    beta_ = beta_prior_ + (double)misses_;\n    update_quartiles();\n  }\n\n  double mean() { return (double)alpha_ / (double)(alpha_ + beta_); }\n\n  double sample(unsigned int interval) {\n    if (interval == INFLUENCE_MED) {\n      return quartile_med_;\n    } else if (interval == INFLUENCE_UPPER) {\n      return quartile_upper_;\n    } else if(interval == INFLUENCE_UCB) {\n      double val = quartile_med_ + sqrt(3.0 * log(round_) /\n          (2.0 * (alpha_ + beta_)));\n      return (val < 1) ? val : 1.0;\n    } else if (interval == INFLUENCE_THOMPSON) {\n      std::gamma_distribution<double> a(alpha_, 1.0);\n      std::gamma_distribution<double> b(beta_, 1.0);\n      double x = a(gen_);\n      double y = b(gen_);\n      return x / (x + y);\n    } else { // Case where we shift the distributions by theta stdev (EG)\n      double val = quartile_med_ + (interval - (double)THETA_OFFSET - 1.0)\n          * quartile_stdev_;\n      val = val < 1 ? val : 1.0;\n      return val > 0 ? val : 0.0;\n    }\n    return quartile_med_;\n  }\n\n  double sq_error() {\n    return (quartile_med_ - original_mean_) * (quartile_med_ - original_mean_);\n  }\n\n private:\n  void update_quartiles() {\n    boost::math::beta_distribution<> dist(alpha_, beta_);\n    quartile_med_ = alpha_ / (alpha_ + beta_);\n    quartile_stdev_ = sqrt(alpha_ * beta_ / (alpha_ + beta_ + 1.0))\n        / (alpha_ + beta_);\n    quartile_upper_ = quantile(dist, 0.75);\n  }\n};\n\n#endif /* defined(__oim__BetaInfluence__) */\n", "meta": {"hexsha": "9bce08e1d4d17445cbc987a42bd4649415f74093", "size": 3651, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/BetaInfluence.hpp", "max_stars_repo_name": "smaniu/oim", "max_stars_repo_head_hexsha": "312b02e74ce916cb8c7172e76726db9b8f2fb13f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2016-05-21T13:54:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-29T11:47:17.000Z", "max_issues_repo_path": "src/BetaInfluence.hpp", "max_issues_repo_name": "smaniu/oim", "max_issues_repo_head_hexsha": "312b02e74ce916cb8c7172e76726db9b8f2fb13f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-03-30T03:34:35.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-25T18:28:38.000Z", "max_forks_repo_path": "src/BetaInfluence.hpp", "max_forks_repo_name": "smaniu/oim", "max_forks_repo_head_hexsha": "312b02e74ce916cb8c7172e76726db9b8f2fb13f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2016-06-21T08:45:41.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-17T04:36:22.000Z", "avg_line_length": 33.8055555556, "max_line_length": 79, "alphanum_fraction": 0.694604218, "num_tokens": 961, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4582340673694571}}
{"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_RSQRT_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_RSQRT_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n\n    @ingroup group-arithmetic\n    This function object returns the inverse of the square root of the input.\n\n    @par Header <boost/simd/function/rsqrt.hpp>\n\n    Using `rsqrt(x)` is similar to `One(as(x))/sqrt(x)`\n\n    @par Decorators\n\n    - raw_  if full accuracy is not needed gives access on some architectures to faster\n    but less accurate version of the function.\n\n    @see sqrt\n\n    @par Example:\n\n      @snippet rsqrt.cpp rsqrt\n\n    @par Possible output:\n\n      @snippet rsqrt.txt rsqrt\n\n\n  **/\n  IEEEValue rsqrt(IEEEValue const& x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/rsqrt.hpp>\n#include <boost/simd/function/scalar/rsqrt.hpp>\n#include <boost/simd/function/simd/rsqrt.hpp>\n\n#endif\n", "meta": {"hexsha": "86c2a8e209d18d3419bce50550b73cdda67acdfe", "size": 1263, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/rsqrt.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/rsqrt.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/rsqrt.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 23.8301886792, "max_line_length": 100, "alphanum_fraction": 0.6041171813, "num_tokens": 275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.45823406736945704}}
{"text": "//---------------------------------------------------------------------------\n/// \\file   parser.hpp\n/// \\brief  Construct a constraint from a string\n//\n// Copyright 2012-2014, nocte@hippie.nu       Released under the MIT License.\n//---------------------------------------------------------------------------\n\n#include <unordered_map>\n#include <boost/spirit/include/qi.hpp>\n#include <boost/spirit/include/phoenix.hpp>\n\n#include \"constraint.hpp\"\n#include \"linear_equation.hpp\"\n#include \"linear_inequality.hpp\"\n\nnamespace rhea\n{\n\ntypedef boost::spirit::qi::symbols<char, variable> var_map;\n\ntemplate <typename Iterator>\nstruct constraint_grammar : boost::spirit::qi::grammar<Iterator, constraint()>\n{\n    typedef boost::spirit::ascii::space_type space_type;\n\n    constraint_grammar(var_map& vars)\n        : constraint_grammar::base_type{constr}\n    {\n        using namespace boost::spirit;\n        namespace phx = boost::phoenix;\n        using qi::double_;\n        using qi::_val;\n\n        constr = lineq[_val = phx::construct<constraint>(_1)]\n                 | linineq[_val = phx::construct<constraint>(_1)];\n\n        lineq = (expr >> '='\n                 >> expr)[_val = phx::construct<linear_equation>(_1, _2)];\n\n        linineq\n            = (expr >> \"<=\" >> expr)[_val = phx::construct<linear_inequality>(\n                                         _1, relation::leq, _2)]\n              | (expr >> \">=\"\n                 >> expr)[_val = phx::construct<linear_inequality>(\n                              _1, relation::geq, _2)];\n\n        expr = double_[_val = _1]\n               //| lexeme[raw[(ascii::alpha >> *(ascii::alnum | '_'))]] [\n               // vars.add, _val = vars[_1] ]\n               | vars[_val = _1] | (expr >> '+' >> expr)[_val = _1 + _2]\n               | (expr >> '-' >> expr)[_val = _1 - _2]\n               | (expr >> '*' >> expr)[_val = _1 * _2]\n               | (expr >> '/' >> expr)[_val = _1 / _2];\n\n        constr.name(\"constraint\");\n        lineq.name(\"linear equation\");\n        linineq.name(\"linear inequality\");\n        expr.name(\"expression\");\n\n        qi::on_error<qi::fail>(\n            constr, std::cout << phx::val(\"Error! Expecting \")\n                              << _4 // what failed?\n                              << phx::val(\" here: \\\"\")\n                              << phx::construct<std::string>(\n                                     _3, _2) // iterators to error-pos, end\n                              << phx::val(\"\\\"\") << std::endl);\n    }\n\n    boost::spirit::qi::rule<Iterator, constraint()> constr;\n    boost::spirit::qi::rule<Iterator, linear_equation()> lineq;\n    boost::spirit::qi::rule<Iterator, linear_inequality()> linineq;\n    boost::spirit::qi::rule<Iterator, linear_expression()> expr;\n};\n}\n", "meta": {"hexsha": "72f66779d613a4c9ec85eb54281728832e0a1c81", "size": 2746, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Pods/Headers/Private/Rhea/parser.hpp", "max_stars_repo_name": "sablib/ZZLayout", "max_stars_repo_head_hexsha": "cfe4bf73876d4735bc7bbb6de81fd8045df59325", "max_stars_repo_licenses": ["MIT"], "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/Rhea/parser.hpp", "max_issues_repo_name": "sablib/ZZLayout", "max_issues_repo_head_hexsha": "cfe4bf73876d4735bc7bbb6de81fd8045df59325", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-01-11T10:26:32.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-11T10:26:32.000Z", "max_forks_repo_path": "Pods/Headers/Private/Rhea/parser.hpp", "max_forks_repo_name": "sablib/ZZLayout", "max_forks_repo_head_hexsha": "cfe4bf73876d4735bc7bbb6de81fd8045df59325", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-01-11T10:25:49.000Z", "max_forks_repo_forks_event_max_datetime": "2018-01-11T10:25:49.000Z", "avg_line_length": 36.6133333333, "max_line_length": 78, "alphanum_fraction": 0.4970866715, "num_tokens": 648, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.45823406736945704}}
{"text": "#ifndef PA_MATH_TENSOR_FIELD_HPP\n#define PA_MATH_TENSOR_FIELD_HPP\n\n#include <boost/multi_array.hpp>\n\n#include <pa/math/types.hpp>\n#include <pa/export.hpp>\n\nnamespace pa\n{\nstruct PA_EXPORT tensor_field\n{\n  boost::multi_array<matrix3, 3> data    {};\n  vector3                        offset  {};\n  vector3                        size    {};\n  vector3                        spacing {};\n};\n}\n\n#endif", "meta": {"hexsha": "d993c70453707fd97dc22cea0918fb4e0db7cba5", "size": 395, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pa/include/pa/math/tensor_field.hpp", "max_stars_repo_name": "acdemiralp/pars", "max_stars_repo_head_hexsha": "e78876de860a4cd2751e3a4e314e2a42a10ea10d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-03-12T18:20:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T12:04:14.000Z", "max_issues_repo_path": "pa/include/pa/math/tensor_field.hpp", "max_issues_repo_name": "acdemiralp/pars", "max_issues_repo_head_hexsha": "e78876de860a4cd2751e3a4e314e2a42a10ea10d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pa/include/pa/math/tensor_field.hpp", "max_forks_repo_name": "acdemiralp/pars", "max_forks_repo_head_hexsha": "e78876de860a4cd2751e3a4e314e2a42a10ea10d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-18T14:35:49.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-18T14:35:49.000Z", "avg_line_length": 19.75, "max_line_length": 44, "alphanum_fraction": 0.5924050633, "num_tokens": 86, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7634837527911057, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4582340609095177}}
{"text": "/*********************************************************************\n* Rice University Software Distribution License\n*\n* Copyright (c) 2012, Rice University\n* All Rights Reserved.\n*\n* For a full description see the file named LICENSE.\n*\n*********************************************************************/\n\n/* Author: Ryan Luna */\n\n#include <omplapp/apps/SE2MultiRigidBodyPlanning.h>\n#include <omplapp/config.h>\n#include <ompl/geometric/planners/rrt/RRTConnect.h>\n\n#include <ompl/base/goals/GoalState.h>\n#include <ompl/base/spaces/SE2StateSpace.h>\n#include <ompl/base/spaces/DiscreteStateSpace.h>\n#include <ompl/base/spaces/TimeStateSpace.h>\n#include <ompl/control/spaces/RealVectorControlSpace.h>\n#include <ompl/control/SimpleSetup.h>\n#include <ompl/config.h>\n#include <iostream>\n#include <limits>\n#include <boost/math/constants/constants.hpp>\n\nnamespace ob = ompl::base;\nnamespace oc = ompl::control;\nusing namespace std;\n\nvoid propagate(const oc::SpaceInformation *si, const ob::State *state,\n    const oc::Control* control, const double duration, ob::State *result)\n{\n    static double timeStep = .01;\n    int nsteps = ceil(duration / timeStep);\n    double dt = duration / nsteps;\n    const double *u = control->as<oc::RealVectorControlSpace::ControlType>()->values;\n\n    ob::CompoundStateSpace::StateType& s = *result->as<ob::CompoundStateSpace::StateType>();\n    ob::SE2StateSpace::StateType& se2 = *s.as<ob::SE2StateSpace::StateType>(0);\n    ob::RealVectorStateSpace::StateType& velocity = *s.as<ob::RealVectorStateSpace::StateType>(1);\n    // ob::DiscreteStateSpace::StateType& gear = *s.as<ob::DiscreteStateSpace::StateType>(2);\n    ob::TimeStateSpace::StateType& timeSpace = *s.as<ob::TimeStateSpace::StateType>(2);\n\n    si->getStateSpace()->copyState(result, state);\n    for(int i = 0; i < nsteps; i++)\n    {\n        se2.setX(se2.getX() + dt * velocity.values[0] * cos(se2.getYaw()));\n        se2.setY(se2.getY() + dt * velocity.values[0] * sin(se2.getYaw()));\n        se2.setYaw(se2.getYaw() + dt * u[0]);\n        // velocity.values[0] = velocity.values[0] + dt * (u[1]*gear.value);\n        velocity.values[0] = velocity.values[0] + dt * u[1];\n        timeSpace.position = timeSpace.position + duration;\n\n        // 'guards' - conditions to change gears\n        // if (gear.value > 0)\n        // {\n        //     if (gear.value < 3 && velocity.values[0] > 10*(gear.value + 1))\n        //         gear.value++;\n        //     else if (gear.value > 1 && velocity.values[0] < 10*gear.value)\n        //         gear.value--;\n        // }\n\n        if (!si->satisfiesBounds(result))\n            return;\n    }\n}\n\nbool canPropagateBackward ()\n{\n    return false;\n}\n\nusing namespace ompl;\n\nint main()\n{\n    // plan for two bodies in SE2\n    app::SE2MultiRigidBodyPlanning setup(2);\n\n    // load the robot and the environment\n    std::string robot_fname = std::string(OMPLAPP_RESOURCE_DIR) + \"/2D/car1_planar_robot.dae\";\n    std::string env_fname = std::string(OMPLAPP_RESOURCE_DIR) + \"/2D/Maze_planar_env.dae\";\n    setup.setRobotMesh(robot_fname.c_str());    // The first mesh should use setRobotMesh.\n    setup.addRobotMesh(robot_fname.c_str());    // Subsequent robot meshes MUST use addRobotMesh!\n    setup.setEnvironmentMesh(env_fname.c_str());\n\n    // constructing start and goal states\n    base::ScopedState<base::CompoundStateSpace> start(setup.getSpaceInformation());\n    base::ScopedState<base::CompoundStateSpace> goal(setup.getSpaceInformation());\n\n    // define starting state for robot 1\n    base::SE2StateSpace::StateType* start1 = start.get()->as<base::SE2StateSpace::StateType>(0);\n    start1->setXY(0., 0.);\n    start1->setYaw(0.);\n    // define goal state for robot 1\n    base::SE2StateSpace::StateType* goal1 = goal.get()->as<base::SE2StateSpace::StateType>(0);\n    goal1->setXY(26., 0.);\n    goal1->setYaw(0.);\n\n    // define starting state for robot 2\n    base::SE2StateSpace::StateType* start2 = start.get()->as<base::SE2StateSpace::StateType>(1);\n    start2->setXY(26., 0.);\n    start2->setYaw(0.);\n    // define goal state for robot 2\n    base::SE2StateSpace::StateType* goal2 = goal.get()->as<base::SE2StateSpace::StateType>(1);\n    goal2->setXY(-30., 0.);\n    goal2->setYaw(0.);\n\n    // set the start & goal states\n    setup.setStartAndGoalStates(start, goal);\n\n    // use RRTConnect for planning\n    setup.setPlanner (base::PlannerPtr(new geometric::RRTConnect(setup.getSpaceInformation())));\n    setup.setStatePropagator(boost::bind(&propagate, setup.getSpaceInformation().get(), _1, _2, _3, _4));\n\n    setup.setup();\n    setup.print(std::cout);\n    // attempt to solve the problem, and print it to screen if a solution is found\n    if (setup.solve(60))\n    {\n        setup.simplifySolution();\n        setup.getSolutionPath().printAsMatrix(std::cout);\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "6345860530d9f4c3b50212f0a59c01b361e52f8c", "size": 4810, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "demos/SE2RigidBodyPlanning/SE2TimeMultiRigidBodyPlanning.cpp", "max_stars_repo_name": "SZanlongo/omplapp", "max_stars_repo_head_hexsha": "c56679337e2a71d266359450afbe63d700c0a666", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "demos/SE2RigidBodyPlanning/SE2TimeMultiRigidBodyPlanning.cpp", "max_issues_repo_name": "SZanlongo/omplapp", "max_issues_repo_head_hexsha": "c56679337e2a71d266359450afbe63d700c0a666", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/SE2RigidBodyPlanning/SE2TimeMultiRigidBodyPlanning.cpp", "max_forks_repo_name": "SZanlongo/omplapp", "max_forks_repo_head_hexsha": "c56679337e2a71d266359450afbe63d700c0a666", "max_forks_repo_licenses": ["BSD-3-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.2868217054, "max_line_length": 105, "alphanum_fraction": 0.6490644491, "num_tokens": 1302, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911056, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4582340609095176}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n#include <vector>\n\n\nnamespace polyfem\n{\n\n///\n/// Clip a polygon by a half-plane.\n/// https://github.com/alicevision/geogram/blob/cfbc0a5827d71d59f8bcf0369cc1731ef12f82ef/src/examples/graphics/demo_Delaunay2d/main.cpp#L677\n///\n/// @param[in]  P       { Input polygon }\n/// @param[in]  q1      { First endpoint of the clipping line }\n/// @param[in]  q2      { Second endpoint of the clipping line }\n/// @param[out] result  { Clipped polygon }\n///\nvoid clip_polygon_by_half_plane(const Eigen::MatrixXd &P, const Eigen::RowVector2d &q1,\n\tconst Eigen::RowVector2d &q2, Eigen::MatrixXd &result);\n\n///\n/// Determine the kernel of the given polygon.\n///\n/// @param[in]  IV    { #IV x (2|3) vertex positions around the input polygon }\n/// @param[out] OV    { #OV x (2|3) vertex positions around the output polygon }\n///\nvoid compute_visibility_kernel(const Eigen::MatrixXd &IV, Eigen::MatrixXd &OV);\n\n///\n/// Determine whether a polygon is star-shaped or not.\n///\n/// @param[in]  IV    { #IV x (2|3) of vertex positions around the polygon }\n/// @param[out] bary  { The barycenter of the kernel }\n///\n/// @return     True if star shaped, False otherwise.\n///\nbool is_star_shaped(const Eigen::MatrixXd &IV, Eigen::RowVector3d &bary);\n\n///\n/// Compute offset polygon\n///\n/// @param[in]  IV    { #IV x 2 of vertex positions for the input polygon }\n/// @param[out] OV    { #OV x 2 of vertex positions for the offset polygon }\n/// @param[in]  eps   { Offset distance }\n///\nvoid offset_polygon(const Eigen::MatrixXd &IV, Eigen::MatrixXd &OV, double eps);\n\n///\n/// Compute whether points are inside a polygon\n///\n/// @param[in]  IV      { #IV x 2 of vertex positions for the input polygon }\n/// @param[in]  Q       { #Q x 2 of query point positions }\n/// @param[out] inside  { Whether the i-th query point is inside or not }\n///\n/// @return     Number of points inside\n///\nint is_inside(const Eigen::MatrixXd &IV, const Eigen::MatrixXd &Q, std::vector<bool> &inside);\n\n///\n/// Sample points on a polygon, evenly spaced from each other\n///\n/// @param[in]  IV           { #IV x 2 vertex positions for the input polygon }\n/// @param[in]  num_samples  { Desired number of samples }\n/// @param[out] S            { #S x 2 output sample positions }\n///\nvoid sample_polygon(const Eigen::MatrixXd &IV, int num_samples, Eigen::MatrixXd &S);\n\n} // namespace polyfem\n", "meta": {"hexsha": "10696a0bbc045209d6bfce2e4d7ce77b1489817f", "size": 2375, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/mesh2D/PolygonUtils.hpp", "max_stars_repo_name": "ldXiao/polyfem", "max_stars_repo_head_hexsha": "d4103af16979ff67d461a9ebe46a14bbc4dc8c7c", "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/mesh2D/PolygonUtils.hpp", "max_issues_repo_name": "ldXiao/polyfem", "max_issues_repo_head_hexsha": "d4103af16979ff67d461a9ebe46a14bbc4dc8c7c", "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/mesh2D/PolygonUtils.hpp", "max_forks_repo_name": "ldXiao/polyfem", "max_forks_repo_head_hexsha": "d4103af16979ff67d461a9ebe46a14bbc4dc8c7c", "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": 33.9285714286, "max_line_length": 140, "alphanum_fraction": 0.6635789474, "num_tokens": 634, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583376458152, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.45823115849736334}}
{"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_CONSTANT_BITINCREMENT_HPP_INCLUDED\n#define BOOST_SIMD_CONSTANT_BITINCREMENT_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n  /*!\n    @ingroup group-constant\n\n    Generates a value of the chosen type which represents the minimal increment value for @c T.\n\n\n    @par Header <boost/simd/constant/bitincrement.hpp>\n\n    @par Semantic:\n\n    For any type @c T,\n\n    @code\n    T r = Bitincrement<T>();\n    @endcode\n\n    generates a value so that, for any value @c x of type @c T,\n\n    @code\n    x + r == simd::nextafter(x, 1);\n    @endcode\n\n    evaluates to @c true.\n\n    @return A value of type @c T containing the minimal increment value for @c T\n\n    @see functional::bitincrement\n  **/\n  template<typename T> T Bitincrement();\n\n  namespace functional\n  {\n    /*!\n      @ingroup group-callable-constant\n      Generates a value of the chosen type which represents the minimal increment value for @c T.\n\n      @par Semantic:\n\n      For any value @c x of type @c T:\n      @code\n      T r = simd::functional::bitincrement( boost::simd::as(x));\n      @endcode\n\n      is similar to:\n\n      @code\n      T r = simd::Bitincrement<T>();\n      @endcode\n\n      @return A value of type @c T containing the minimal increment value for @c T\n\n      @see Bitincrement\n    **/\n    Value Bitincrement();\n  }\n} }\n#endif\n\n#include <boost/simd/constant/scalar/bitincrement.hpp>\n#include <boost/simd/constant/simd/bitincrement.hpp>\n\n#endif\n", "meta": {"hexsha": "e1bc017764684cba772a6e1414c0ffbdcd74d5d8", "size": 1852, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/constant/bitincrement.hpp", "max_stars_repo_name": "TobiasLudwig/boost.simd", "max_stars_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/simd/constant/bitincrement.hpp", "max_issues_repo_name": "TobiasLudwig/boost.simd", "max_issues_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/constant/bitincrement.hpp", "max_forks_repo_name": "TobiasLudwig/boost.simd", "max_forks_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-02-16T09:58:18.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:22:43.000Z", "avg_line_length": 23.4430379747, "max_line_length": 100, "alphanum_fraction": 0.5971922246, "num_tokens": 420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583376458152, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.45823115849736334}}
{"text": "#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE \"test_range\"\n\n#include <boost/test/unit_test.hpp>\n#include \"nanocv/math/range.hpp\"\n#include \"nanocv/math/random.hpp\"\n\nnamespace test\n{\n        using namespace ncv;\n\n        void check_range(double min, double max, size_t tests)\n        {\n                range_t<double> range(min, max);\n\n                BOOST_CHECK_LT(min, max);\n                BOOST_CHECK_EQUAL(range.min(), min);\n                BOOST_CHECK_EQUAL(range.max(), max);\n\n                // check random values\n                for (size_t i = 0; i < tests; i ++)\n                {\n                        random_t<double> rgen(min - 0.1, max + 0.56);\n\n                        const auto val = rgen();\n                        if (val < min)\n                        {\n                                BOOST_CHECK_EQUAL(range.clamp(val), min);\n                        }\n                        else if (val > max)\n                        {\n                                BOOST_CHECK_EQUAL(range.clamp(val), max);\n                        }\n                        else\n                        {\n                                BOOST_CHECK_EQUAL(range.clamp(val), val);\n                        }\n                }\n        }\n}\n\nBOOST_AUTO_TEST_CASE(test_range)\n{\n        test::check_range(-0.03, 0.005, 32);\n        test::check_range(1.03, 13.005, 37);\n        test::check_range(-0.54, 0.105, 13);\n        test::check_range(-7.03, 10.005, 11);\n}\n", "meta": {"hexsha": "3f31b92abc723a6c8484bc31d9be7cafa7682c43", "size": 1459, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_range.cpp", "max_stars_repo_name": "0x0all/nanocv", "max_stars_repo_head_hexsha": "dc58dea6b4eb7be2089b168d39c2b02aa2730741", "max_stars_repo_licenses": ["MIT"], "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_range.cpp", "max_issues_repo_name": "0x0all/nanocv", "max_issues_repo_head_hexsha": "dc58dea6b4eb7be2089b168d39c2b02aa2730741", "max_issues_repo_licenses": ["MIT"], "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_range.cpp", "max_forks_repo_name": "0x0all/nanocv", "max_forks_repo_head_hexsha": "dc58dea6b4eb7be2089b168d39c2b02aa2730741", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-08-02T02:41:37.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-02T02:41:37.000Z", "avg_line_length": 29.7755102041, "max_line_length": 73, "alphanum_fraction": 0.440027416, "num_tokens": 306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.6584175072643415, "lm_q1q2_score": 0.45823114552839217}}
{"text": "/********************************************************************************\n * Copyright 2009 The Robotics Group, The Maersk Mc-Kinney Moller Institute,\n * Faculty of Engineering, University of Southern Denmark\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n ********************************************************************************/\n\n#ifndef RW_MATH_INERTIAMATRIX_HPP\n#define RW_MATH_INERTIAMATRIX_HPP\n\n/**\n * @file InertiaMatrix.hpp\n */\n\n#if !defined(SWIG)\n#include \"Rotation3D.hpp\"\n#include \"Vector3D.hpp\"\n\n#include <rw/common/Serializable.hpp>\n\n#include <Eigen/Core>\n#endif\n\nnamespace rw { namespace math {\n\n    /** @addtogroup math */\n    /* @{*/\n\n    /**\n     * @brief A 3x3 inertia matrix\n     */\n    template< class T = double > class InertiaMatrix\n    {\n      public:\n        //! @brief The type of the internal Eigen matrix implementation.\n        typedef Eigen::Matrix< T, 3, 3 > Base;\n#if !defined(SWIGJAVA)\n\n        /**\n         * @brief Constructs an initialized 3x3 rotation matrix\n         *\n         * @param r11 \\f$ r_{11} \\f$\n         * @param r12 \\f$ r_{12} \\f$\n         * @param r13 \\f$ r_{13} \\f$\n         * @param r21 \\f$ r_{21} \\f$\n         * @param r22 \\f$ r_{22} \\f$\n         * @param r23 \\f$ r_{23} \\f$\n         * @param r31 \\f$ r_{31} \\f$\n         * @param r32 \\f$ r_{32} \\f$\n         * @param r33 \\f$ r_{33} \\f$\n         *\n         * @f$\n         *  \\mathbf{R} =\n         *  \\left[\n         *  \\begin{array}{ccc}\n         *  r_{11} & r_{12} & r_{13} \\\\\n         *  r_{21} & r_{22} & r_{23} \\\\\n         *  r_{31} & r_{32} & r_{33}\n         *  \\end{array}\n         *  \\right]\n         * @f$\n         */\n\n#endif\n        InertiaMatrix (T r11, T r12, T r13, T r21, T r22, T r23, T r31, T r32, T r33)\n        {\n            _matrix (0, 0) = r11;\n            _matrix (0, 1) = r12;\n            _matrix (0, 2) = r13;\n            _matrix (1, 0) = r21;\n            _matrix (1, 1) = r22;\n            _matrix (1, 2) = r23;\n            _matrix (2, 0) = r31;\n            _matrix (2, 1) = r32;\n            _matrix (2, 2) = r33;\n        }\n#if !defined(SWIGJAVA)\n\n        /**\n         * @brief Constructs an initialized 3x3 rotation matrix\n         * @f$ \\robabx{a}{b}{\\mathbf{R}} =\n         * \\left[\n         *  \\begin{array}{ccc}\n         *   \\robabx{a}{b}{\\mathbf{i}} & \\robabx{a}{b}{\\mathbf{j}} & \\robabx{a}{b}{\\mathbf{k}}\n         *  \\end{array}\n         * \\right]\n         * @f$\n         *\n         * @param i @f$ \\robabx{a}{b}{\\mathbf{i}} @f$\n         * @param j @f$ \\robabx{a}{b}{\\mathbf{j}} @f$\n         * @param k @f$ \\robabx{a}{b}{\\mathbf{k}} @f$\n         */\n\n#endif\n        InertiaMatrix (const rw::math::Vector3D< T >& i, const rw::math::Vector3D< T >& j,\n                       const rw::math::Vector3D< T >& k)\n        {\n            _matrix (0, 0) = i[0];\n            _matrix (0, 1) = j[0];\n            _matrix (0, 2) = k[0];\n            _matrix (1, 0) = i[1];\n            _matrix (1, 1) = j[1];\n            _matrix (1, 2) = k[1];\n            _matrix (2, 0) = i[2];\n            _matrix (2, 1) = j[2];\n            _matrix (2, 2) = k[2];\n        }\n\n        /**\n         * @brief constructor - where only the diagonal is set\n         * @param i [in] m(0,0)\n         * @param j [in] m(1,1)\n         * @param k [in] m(2,2)\n         */\n        InertiaMatrix (T i = 0.0, T j = 0.0, T k = 0.0)\n        {\n            _matrix (0, 0) = i;\n            _matrix (0, 1) = 0;\n            _matrix (0, 2) = 0;\n            _matrix (1, 0) = 0;\n            _matrix (1, 1) = j;\n            _matrix (1, 2) = 0;\n            _matrix (2, 0) = 0;\n            _matrix (2, 1) = 0;\n            _matrix (2, 2) = k;\n        }\n\n        /**\n         * @brief Construct an internal matrix from a Eigen::MatrixBase\n         * It is the responsibility of the user that 3x3 matrix is indeed an\n         * inertia matrix.\n         */\n        explicit InertiaMatrix (const Base& r) : _matrix (r) {}\n\n        /**\n         * @brief Returns reference to matrix element\n         * @param row [in] row\n         * @param column [in] column\n         * @return reference to the element\n         */\n        T& operator() (size_t row, size_t column) { return _matrix (row, column); }\n\n        /**\n         * @brief Returns reference to matrix element\n         * @param row [in] row\n         * @param column [in] column\n         * @return reference to the element\n         */\n        const T& operator() (size_t row, size_t column) const { return _matrix (row, column); }\n#if defined(SWIG)\n        MATRIXOPERATOR (T);\n#endif\n        /**\n         * @brief Returns reference to the internal 3x3 matrix\n         */\n        const Base& e () const { return _matrix; }\n\n        /**\n         * @brief Returns reference to the internal 3x3 matrix\n         */\n        Base& e () { return _matrix; }\n\n#if !defined(SWIG)\n        /**\n         * @brief Calculates \\f$ \\robabx{a}{c}{\\mathbf{R}} =\n         * \\robabx{a}{b}{\\mathbf{R}} \\robabx{b}{c}{\\mathbf{R}} \\f$\n         * @param aRb [in] \\f$ \\robabx{a}{b}{\\mathbf{R}} \\f$\n         * @param bRc [in] \\f$ \\robabx{b}{c}{\\mathbf{R}} \\f$\n         * @return \\f$ \\robabx{a}{c}{\\mathbf{R}} \\f$\n         */\n        friend InertiaMatrix operator* (const rw::math::Rotation3D< T >& aRb,\n                                        const InertiaMatrix& bRc)\n        {\n            return InertiaMatrix (aRb.e () * bRc.e ());\n        }\n#endif\n#if !defined(SWIGJAVA)\n\n        /**\n         * @brief Calculates \\f$ \\robabx{a}{c}{\\mathbf{R}} =\n         * \\robabx{a}{b}{\\mathbf{R}} \\robabx{b}{c}{\\mathbf{R}} \\f$\n         * @param bRc [in] \\f$ \\robabx{b}{c}{\\mathbf{R}} \\f$\n         * @return \\f$ \\robabx{a}{c}{\\mathbf{R}} \\f$\n         */\n#endif\n        InertiaMatrix operator* (const rw::math::Rotation3D< T >& bRc) const\n        {\n            return InertiaMatrix (this->e () * bRc.e ());\n        }\n\n        /**\n         * @brief Calculates the addition between the two InertiaMatrices\n         */\n        InertiaMatrix operator+ (const InertiaMatrix& I2) const\n        {\n            return InertiaMatrix (this->e () + I2.e ());\n        }\n\n        /**\n         * @brief Calculates \\f$ \\robabx{a}{c}{\\mathbf{v}} =\n         * \\robabx{a}{b}{\\mathbf{R}} \\robabx{b}{c}{\\mathbf{v}} \\f$\n         * @param bVc [in] \\f$ \\robabx{b}{c}{\\mathbf{v}} \\f$\n         * @return \\f$ \\robabx{a}{c}{\\mathbf{v}} \\f$\n         */\n        rw::math::Vector3D< T > operator* (const rw::math::Vector3D< T >& bVc) const\n        {\n            return rw::math::Vector3D< T > (this->e () * bVc.e ());\n        }\n#if !defined(SWIG)\n        /**\n         * @brief Writes rotation matrix to stream\n         * @param os [in/out] output stream to use\n         * @param r [in] rotation matrix to print\n         * @return the updated output stream\n         */\n        friend std::ostream& operator<< (std::ostream& os, const InertiaMatrix& r)\n        {\n            return os << r.e ();\n        }\n#else\n        TOSTRING (rw::math::InertiaMatrix< T >);\n#endif\n\n        /**\n         * @brief Make inertia matrix for a solid sphere.\n         * @param mass [in] mass of solid sphere.\n         * @param radi [in] radius of sphere.\n         * @return the inertia matrix.\n         */\n        static InertiaMatrix< T > makeSolidSphereInertia (T mass, T radi)\n        {\n            T tmpV = (T) (2.0 / 5.0) * mass * radi * radi;\n            return InertiaMatrix< T > (tmpV, 0, 0, 0, tmpV, 0, 0, 0, tmpV);\n        }\n\n        /**\n         * @brief Make inertia matrix for a hollow sphere.\n         * @param mass [in] mass of hollow sphere.\n         * @param radi [in] radius of sphere.\n         * @return the inertia matrix.\n         */\n        static InertiaMatrix< T > makeHollowSphereInertia (T mass, T radi)\n        {\n            T tmpV = (T) (2.0 / 3.0) * mass * radi * radi;\n            return InertiaMatrix< T > (tmpV, 0, 0, 0, tmpV, 0, 0, 0, tmpV);\n        }\n\n        /**\n         * @brief calculates the inertia of a cuboid where the reference frame is in the\n         * center of the cuboid with\n         * @param mass\n         * @param x\n         * @param y\n         * @param z\n         * @return\n         */\n        static InertiaMatrix< T > makeCuboidInertia (T mass, T x, T y, T z)\n        {\n            return InertiaMatrix< T > ((T) (1 / 12.0 * mass * (y * y + z * z)),\n                                       0,\n                                       0,\n                                       0,\n                                       (T) (1 / 12.0 * mass * (x * x + z * z)),\n                                       0,\n                                       0,\n                                       0,\n                                       (T) (1 / 12.0 * mass * (x * x + y * y)));\n        }\n\n      private:\n        Base _matrix;\n    };\n#if !defined(SWIGJAVA)\n\n    /**\n     * @brief Calculates the inverse @f$ \\robabx{b}{a}{\\mathbf{R}} =\n     * \\robabx{a}{b}{\\mathbf{R}}^{-1} @f$ of a rotation matrix\n     *\n     * @param aRb [in] the rotation matrix @f$ \\robabx{a}{b}{\\mathbf{R}} @f$\n     *\n     * @return the matrix inverse @f$ \\robabx{b}{a}{\\mathbf{R}} =\n     * \\robabx{a}{b}{\\mathbf{R}}^{-1} @f$\n     *\n     * @f$ \\robabx{b}{a}{\\mathbf{R}} = \\robabx{a}{b}{\\mathbf{R}}^{-1} =\n     * \\robabx{a}{b}{\\mathbf{R}}^T @f$\n     */\n    \n    #endif \n    template< class Q > InertiaMatrix< Q > inverse (const InertiaMatrix< Q >& aRb)\n    {\n        return InertiaMatrix< Q > (aRb.e ().inverse ());\n    }\n\n    /**\n     * @brief Casts InertiaMatrix<T> to InertiaMatrix<Q>\n     * @param rot [in] InertiaMatrix with type T\n     * @return InertiaMatrix with type Q\n     */\n    template< class Q, class T > InertiaMatrix< Q > cast (const InertiaMatrix< T >& rot)\n    {\n        InertiaMatrix< Q > res;\n        for (size_t i = 0; i < 3; i++)\n            for (size_t j = 0; j < 3; j++)\n                res (i, j) = static_cast< Q > (rot (i, j));\n        return res;\n    }\n#if !defined(SWIG)\n    extern template class rw::math::InertiaMatrix< double >;\n    extern template class rw::math::InertiaMatrix< float >;\n#else\n    SWIG_DECLARE_TEMPLATE (InertiaMatrixd, rw::math::InertiaMatrix< double >);\n    SWIG_DECLARE_TEMPLATE (InertiaMatrixf, rw::math::InertiaMatrix< float >);\n#endif\n\n    using InertiaMatrixd = InertiaMatrix< double >;\n    using InertiaMatrixf = InertiaMatrix< float >;\n\n    /*@}*/\n}}    // namespace rw::math\n\nnamespace rw { namespace common {\n    class OutputArchive;\n    class InputArchive;\n    namespace serialization {\n        /**\n         * @copydoc rw::common::serialization::write\n         * @relatedalso rw::math::InertiaMatrix\n         */\n        template<>\n        void write (const rw::math::InertiaMatrix< double >& sobject,\n                    rw::common::OutputArchive& oarchive, const std::string& id);\n\n        /**\n         * @copydoc rw::common::serialization::write\n         * @relatedalso rw::math::InertiaMatrix\n         */\n        template<>\n        void write (const rw::math::InertiaMatrix< float >& sobject,\n                    rw::common::OutputArchive& oarchive, const std::string& id);\n\n        /**\n         * @copydoc rw::common::serialization::read\n         * @relatedalso rw::math::InertiaMatrix\n         */\n        template<>\n        void read (rw::math::InertiaMatrix< double >& sobject, rw::common::InputArchive& iarchive,\n                   const std::string& id);\n\n        /**\n         * @copydoc rw::common::serialization::read\n         * @relatedalso rw::math::InertiaMatrix\n         */\n        template<>\n        void read (rw::math::InertiaMatrix< float >& sobject, rw::common::InputArchive& iarchive,\n                   const std::string& id);\n    }    // namespace serialization\n}}       // namespace rw::common\n\n#endif    // end include guard\n", "meta": {"hexsha": "2989e8aa17f9f8ebc8696ceec0723dc80dcf9bdc", "size": 12163, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "RobWork/src/rw/math/InertiaMatrix.hpp", "max_stars_repo_name": "ZLW07/RobWork", "max_stars_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-29T14:16:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T14:16:27.000Z", "max_issues_repo_path": "RobWork/src/rw/math/InertiaMatrix.hpp", "max_issues_repo_name": "ZLW07/RobWork", "max_issues_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RobWork/src/rw/math/InertiaMatrix.hpp", "max_forks_repo_name": "ZLW07/RobWork", "max_forks_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.872972973, "max_line_length": 98, "alphanum_fraction": 0.4858998602, "num_tokens": 3651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583124210896, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.4582311418889623}}
{"text": "// Boost.Polygon library voronoi_predicates_test.cpp file\r\n\r\n//          Copyright Andrii Sydorchuk 2010-2012.\r\n// Distributed under the Boost Software License, Version 1.0.\r\n//    (See accompanying file LICENSE_1_0.txt or copy at\r\n//          http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n// See http://www.boost.org for updates, documentation, and revision history.\r\n\r\n#include <limits>\r\n#include <map>\r\n\r\n#define BOOST_TEST_MODULE voronoi_predicates_test\r\n#include <boost/test/test_case_template.hpp>\r\n\r\n#include <boost/polygon/detail/voronoi_ctypes.hpp>\r\n#include <boost/polygon/detail/voronoi_predicates.hpp>\r\n#include <boost/polygon/detail/voronoi_structures.hpp>\r\nusing namespace boost::polygon::detail;\r\n\r\n#include <boost/polygon/voronoi_geometry_type.hpp>\r\nusing namespace boost::polygon;\r\n\r\nulp_comparison<double> ulp_cmp;\r\n\r\ntypedef voronoi_predicates< voronoi_ctype_traits<int> > VP;\r\ntypedef point_2d<int> point_type;\r\ntypedef site_event<int> site_type;\r\ntypedef circle_event<double> circle_type;\r\nVP::event_comparison_predicate<site_type, circle_type> event_comparison;\r\n\r\ntypedef beach_line_node_key<site_type> key_type;\r\ntypedef VP::distance_predicate<site_type> distance_predicate_type;\r\ntypedef VP::node_comparison_predicate<key_type> node_comparison_type;\r\ntypedef std::map<key_type, int, node_comparison_type> beach_line_type;\r\ntypedef beach_line_type::iterator bieach_line_iterator;\r\ndistance_predicate_type distance_predicate;\r\nnode_comparison_type node_comparison;\r\n\r\ntypedef VP::circle_existence_predicate<site_type> CEP_type;\r\ntypedef VP::mp_circle_formation_functor<site_type, circle_type> MP_CFF_type;\r\ntypedef VP::lazy_circle_formation_functor<site_type, circle_type> lazy_CFF_type;\r\nVP::circle_formation_predicate<site_type, circle_type, CEP_type, MP_CFF_type> mp_predicate;\r\nVP::circle_formation_predicate<site_type, circle_type, CEP_type, lazy_CFF_type> lazy_predicate;\r\n\r\n#define CHECK_ORIENTATION(P1, P2, P3, R1, R2) \\\r\n    BOOST_CHECK_EQUAL(VP::ot::eval(P1, P2, P3) == R1, true); \\\r\n    BOOST_CHECK_EQUAL(VP::ot::eval(P1, P3, P2) == R2, true); \\\r\n    BOOST_CHECK_EQUAL(VP::ot::eval(P2, P1, P3) == R2, true); \\\r\n    BOOST_CHECK_EQUAL(VP::ot::eval(P2, P3, P1) == R1, true); \\\r\n    BOOST_CHECK_EQUAL(VP::ot::eval(P3, P1, P2) == R1, true); \\\r\n    BOOST_CHECK_EQUAL(VP::ot::eval(P3, P2, P1) == R2, true)\r\n\r\n#define CHECK_EVENT_COMPARISON(A, B, R1, R2) \\\r\n    BOOST_CHECK_EQUAL(event_comparison(A, B), R1); \\\r\n    BOOST_CHECK_EQUAL(event_comparison(B, A), R2)\r\n\r\n#define CHECK_DISTANCE_PREDICATE(S1, S2, S3, RES) \\\r\n    BOOST_CHECK_EQUAL(distance_predicate(S1, S2, S3), RES)\r\n\r\n#define CHECK_NODE_COMPARISON(node, nodes, res, sz) \\\r\n    for (int i = 0; i < sz; ++i) { \\\r\n      BOOST_CHECK_EQUAL(node_comparison(node, nodes[i]), res[i]); \\\r\n      BOOST_CHECK_EQUAL(node_comparison(nodes[i], node), !res[i]); \\\r\n    }\r\n\r\n#define CHECK_CIRCLE(circle, c_x, c_y, l_x) \\\r\n    BOOST_CHECK_EQUAL(ulp_cmp(c1.x(), c_x, 10), ulp_comparison<double>::EQUAL); \\\r\n    BOOST_CHECK_EQUAL(ulp_cmp(c1.y(), c_y, 10), ulp_comparison<double>::EQUAL); \\\r\n    BOOST_CHECK_EQUAL(ulp_cmp(c1.lower_x(), l_x, 10), ulp_comparison<double>::EQUAL)\r\n\r\n#define CHECK_CIRCLE_EXISTENCE(s1, s2, s3, RES) \\\r\n  { circle_type c1; \\\r\n    BOOST_CHECK_EQUAL(lazy_predicate(s1, s2, s3, c1), RES); }\r\n\r\n#define CHECK_CIRCLE_FORMATION_PREDICATE(s1, s2, s3, c_x, c_y, l_x) \\\r\n  { circle_type c1, c2; \\\r\n    BOOST_CHECK_EQUAL(mp_predicate(s1, s2, s3, c1), true); \\\r\n    BOOST_CHECK_EQUAL(lazy_predicate(s1, s2, s3, c2), true); \\\r\n    CHECK_CIRCLE(c1, c_x, c_y, l_x); \\\r\n    CHECK_CIRCLE(c2, c_x, c_y, l_x); }\r\n\r\nBOOST_AUTO_TEST_CASE(orientation_test) {\r\n  int min_int = (std::numeric_limits<int>::min)();\r\n  int max_int = (std::numeric_limits<int>::max)();\r\n  point_type point1(min_int, min_int);\r\n  point_type point2(0, 0);\r\n  point_type point3(max_int, max_int);\r\n  point_type point4(min_int, max_int);\r\n  point_type point5(max_int-1, max_int);\r\n  CHECK_ORIENTATION(point1, point2, point3, VP::ot::COLLINEAR, VP::ot::COLLINEAR);\r\n  CHECK_ORIENTATION(point1, point4, point3, VP::ot::RIGHT, VP::ot::LEFT);\r\n  CHECK_ORIENTATION(point1, point5, point3, VP::ot::RIGHT, VP::ot::LEFT);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(event_comparison_test1) {\r\n  site_type site(1, 2);\r\n  CHECK_EVENT_COMPARISON(site, site_type(0, 2), false, true);\r\n  CHECK_EVENT_COMPARISON(site, site_type(1, 3), true, false);\r\n  CHECK_EVENT_COMPARISON(site, site_type(1, 2), false, false);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(event_comparison_test2) {\r\n  site_type site(0, 0, 0, 2);\r\n  CHECK_EVENT_COMPARISON(site, site_type(0, 2), true, false);\r\n  CHECK_EVENT_COMPARISON(site, site_type(0, 0), false, true);\r\n  CHECK_EVENT_COMPARISON(site, site_type(0, -2, 0, -1), false, true);\r\n  CHECK_EVENT_COMPARISON(site, site_type(0, -2, 1, 1), true, false);\r\n  CHECK_EVENT_COMPARISON(site, site_type(0, 0, 1, 1), true, false);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(event_comparison_test3) {\r\n  site_type site(0, 0, 10, 10);\r\n  CHECK_EVENT_COMPARISON(site, site_type(0, 0), false, true);\r\n  CHECK_EVENT_COMPARISON(site, site_type(0, -1), false, true);\r\n  CHECK_EVENT_COMPARISON(site, site_type(0, 1), false, true);\r\n  CHECK_EVENT_COMPARISON(site, site_type(0, 1, 0, 10), false, true);\r\n  CHECK_EVENT_COMPARISON(site, site_type(0, -10, 0, -1), false, true);\r\n  CHECK_EVENT_COMPARISON(site, site_type(0, 0, 10, 9), true, false);\r\n  CHECK_EVENT_COMPARISON(site, site_type(0, 0, 9, 10), false, true);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(event_comparison_test4) {\r\n  circle_type circle(1, 2, 3);\r\n  CHECK_EVENT_COMPARISON(circle, circle_type(1, 2, 3), false, false);\r\n  CHECK_EVENT_COMPARISON(circle, circle_type(1, 3, 3), true, false);\r\n  CHECK_EVENT_COMPARISON(circle, circle_type(1, 2, 4), true, false);\r\n  CHECK_EVENT_COMPARISON(circle, circle_type(0, 2, 2), false, true);\r\n  CHECK_EVENT_COMPARISON(circle, circle_type(-1, 2, 3), false, false);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(event_comparison_test5) {\r\n  circle_type circle(1, 2, 3);\r\n  CHECK_EVENT_COMPARISON(circle, site_type(0, 100), false, true);\r\n  CHECK_EVENT_COMPARISON(circle, site_type(3, 0), false, true);\r\n  CHECK_EVENT_COMPARISON(circle, site_type(3, 2), false, false);\r\n  CHECK_EVENT_COMPARISON(circle, site_type(3, 3), true, false);\r\n  CHECK_EVENT_COMPARISON(circle, site_type(4, 2), true, false);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(distance_predicate_test1) {\r\n  site_type site1(-5, 0);\r\n  site_type site2(-8, 9);\r\n  site_type site3(-2, 1);\r\n  CHECK_DISTANCE_PREDICATE(site1, site2, site_type(0, 5), false);\r\n  CHECK_DISTANCE_PREDICATE(site3, site1, site_type(0, 5), false);\r\n  CHECK_DISTANCE_PREDICATE(site1, site2, site_type(0, 4), false);\r\n  CHECK_DISTANCE_PREDICATE(site3, site1, site_type(0, 4), false);\r\n  CHECK_DISTANCE_PREDICATE(site1, site2, site_type(0, 6), true);\r\n  CHECK_DISTANCE_PREDICATE(site3, site1, site_type(0, 6), true);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(distance_predicate_test2) {\r\n  site_type site1(-4, 0, -4, 20);\r\n  site_type site2(-2, 10);\r\n  CHECK_DISTANCE_PREDICATE(site2, site1, site_type(0, 11), false);\r\n  CHECK_DISTANCE_PREDICATE(site2, site1, site_type(0, 9), false);\r\n  CHECK_DISTANCE_PREDICATE(site1, site2, site_type(0, 11), true);\r\n  CHECK_DISTANCE_PREDICATE(site1, site2, site_type(0, 9), true);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(disntace_predicate_test3) {\r\n  site_type site1(-5, 5, 2, -2);\r\n  site1.inverse();\r\n  site_type site2(-2, 4);\r\n  CHECK_DISTANCE_PREDICATE(site1, site2, site_type(0, -1), false);\r\n  CHECK_DISTANCE_PREDICATE(site2, site1, site_type(0, -1), false);\r\n  CHECK_DISTANCE_PREDICATE(site1, site2, site_type(0, 1), false);\r\n  CHECK_DISTANCE_PREDICATE(site2, site1, site_type(0, 1), false);\r\n  CHECK_DISTANCE_PREDICATE(site1, site2, site_type(0, 4), true);\r\n  CHECK_DISTANCE_PREDICATE(site2, site1, site_type(0, 4), false);\r\n  CHECK_DISTANCE_PREDICATE(site1, site2, site_type(0, 5), true);\r\n  CHECK_DISTANCE_PREDICATE(site2, site1, site_type(0, 5), false);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(distance_predicate_test4) {\r\n  site_type site1(-5, 5, 2, -2);\r\n  site_type site2(-2, -4);\r\n  site_type site3(-4, 1);\r\n  CHECK_DISTANCE_PREDICATE(site1, site2, site_type(0, 1), true);\r\n  CHECK_DISTANCE_PREDICATE(site2, site1, site_type(0, 1), true);\r\n  CHECK_DISTANCE_PREDICATE(site1, site3, site_type(0, 1), true);\r\n  CHECK_DISTANCE_PREDICATE(site3, site1, site_type(0, 1), true);\r\n  CHECK_DISTANCE_PREDICATE(site1, site2, site_type(0, -2), true);\r\n  CHECK_DISTANCE_PREDICATE(site2, site1, site_type(0, -2), false);\r\n  CHECK_DISTANCE_PREDICATE(site1, site3, site_type(0, -2), true);\r\n  CHECK_DISTANCE_PREDICATE(site3, site1, site_type(0, -2), false);\r\n  CHECK_DISTANCE_PREDICATE(site1, site2, site_type(0, -8), true);\r\n  CHECK_DISTANCE_PREDICATE(site2, site1, site_type(0, -8), false);\r\n  CHECK_DISTANCE_PREDICATE(site1, site3, site_type(0, -8), true);\r\n  CHECK_DISTANCE_PREDICATE(site3, site1, site_type(0, -8), false);\r\n  CHECK_DISTANCE_PREDICATE(site1, site2, site_type(0, -9), true);\r\n  CHECK_DISTANCE_PREDICATE(site2, site1, site_type(0, -9), false);\r\n  CHECK_DISTANCE_PREDICATE(site1, site3, site_type(0, -9), true);\r\n  CHECK_DISTANCE_PREDICATE(site3, site1, site_type(0, -9), false);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(disntace_predicate_test5) {\r\n  site_type site1(-5, 5, 2, -2);\r\n  site_type site2 = site1;\r\n  site2.inverse();\r\n  site_type site3(-2, 4);\r\n  site_type site4(-2, -4);\r\n  site_type site5(-4, 1);\r\n  CHECK_DISTANCE_PREDICATE(site3, site2, site_type(0, 1), false);\r\n  CHECK_DISTANCE_PREDICATE(site3, site2, site_type(0, 4), false);\r\n  CHECK_DISTANCE_PREDICATE(site3, site2, site_type(0, 5), false);\r\n  CHECK_DISTANCE_PREDICATE(site3, site2, site_type(0, 7), true);\r\n  CHECK_DISTANCE_PREDICATE(site4, site1, site_type(0, -2), false);\r\n  CHECK_DISTANCE_PREDICATE(site5, site1, site_type(0, -2), false);\r\n  CHECK_DISTANCE_PREDICATE(site4, site1, site_type(0, -8), false);\r\n  CHECK_DISTANCE_PREDICATE(site5, site1, site_type(0, -8), false);\r\n  CHECK_DISTANCE_PREDICATE(site4, site1, site_type(0, -9), false);\r\n  CHECK_DISTANCE_PREDICATE(site5, site1, site_type(0, -9), false);\r\n  CHECK_DISTANCE_PREDICATE(site4, site1, site_type(0, -18), false);\r\n  CHECK_DISTANCE_PREDICATE(site5, site1, site_type(0, -18), false);\r\n  CHECK_DISTANCE_PREDICATE(site4, site1, site_type(0, -1), true);\r\n  CHECK_DISTANCE_PREDICATE(site5, site1, site_type(0, -1), true);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(distance_predicate_test6) {\r\n  site_type site1(-5, 0, 2, 7);\r\n  site_type site2 = site1;\r\n  site2.inverse();\r\n  CHECK_DISTANCE_PREDICATE(site1, site2, site_type(2, 7), false);\r\n  CHECK_DISTANCE_PREDICATE(site1, site2, site_type(1, 5), false);\r\n  CHECK_DISTANCE_PREDICATE(site1, site2, site_type(-1, 5), true);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(distance_predicate_test7) {\r\n  site_type site1(-5, 5, 2, -2);\r\n  site1.inverse();\r\n  site_type site2(-5, 5, 0, 6);\r\n  site_type site3(-2, 4, 0, 4);\r\n  site_type site4(0, 2);\r\n  site_type site5(0, 5);\r\n  site_type site6(0, 6);\r\n  site_type site7(0, 8);\r\n  CHECK_DISTANCE_PREDICATE(site1, site2, site4, false);\r\n  CHECK_DISTANCE_PREDICATE(site1, site2, site5, true);\r\n  CHECK_DISTANCE_PREDICATE(site1, site2, site6, true);\r\n  CHECK_DISTANCE_PREDICATE(site1, site2, site7, true);\r\n  CHECK_DISTANCE_PREDICATE(site1, site3, site4, false);\r\n  CHECK_DISTANCE_PREDICATE(site1, site3, site5, true);\r\n  CHECK_DISTANCE_PREDICATE(site1, site3, site6, true);\r\n  CHECK_DISTANCE_PREDICATE(site1, site3, site7, true);\r\n  site3.inverse();\r\n  CHECK_DISTANCE_PREDICATE(site3, site1, site4, false);\r\n  CHECK_DISTANCE_PREDICATE(site3, site1, site5, false);\r\n  CHECK_DISTANCE_PREDICATE(site3, site1, site6, false);\r\n  CHECK_DISTANCE_PREDICATE(site3, site1, site7, true);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(distatnce_predicate_test8) {\r\n  site_type site1(-5, 3, -2, 2);\r\n  site1.inverse();\r\n  site_type site2(-5, 5, -2, 2);\r\n  CHECK_DISTANCE_PREDICATE(site1, site2, site_type(-4, 2), false);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(node_comparison_test1) {\r\n  beach_line_type beach_line;\r\n  site_type site1(0, 0);\r\n  site1.sorted_index(0);\r\n  site_type site2(0, 2);\r\n  site2.sorted_index(1);\r\n  site_type site3(1, 0);\r\n  site3.sorted_index(2);\r\n  beach_line[key_type(site1, site2)] = 2;\r\n  beach_line[key_type(site1, site3)] = 0;\r\n  beach_line[key_type(site3, site1)] = 1;\r\n  int cur_index = 0;\r\n  for (bieach_line_iterator it = beach_line.begin();\r\n       it != beach_line.end(); ++it, ++cur_index) {\r\n    BOOST_CHECK_EQUAL(it->second, cur_index);\r\n  }\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(node_comparison_test2) {\r\n  beach_line_type beach_line;\r\n  site_type site1(0, 1);\r\n  site1.sorted_index(0);\r\n  site_type site2(2, 0);\r\n  site2.sorted_index(1);\r\n  site_type site3(2, 4);\r\n  site3.sorted_index(2);\r\n  beach_line[key_type(site1, site2)] = 0;\r\n  beach_line[key_type(site2, site1)] = 1;\r\n  beach_line[key_type(site1, site3)] = 2;\r\n  beach_line[key_type(site3, site1)] = 3;\r\n  int cur_index = 0;\r\n  for (bieach_line_iterator it = beach_line.begin();\r\n       it != beach_line.end(); ++it, ++cur_index) {\r\n    BOOST_CHECK_EQUAL(it->second, cur_index);\r\n  }\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(node_comparison_test3) {\r\n  key_type node(site_type(1, 0).sorted_index(1), site_type(0, 2).sorted_index(0));\r\n  key_type nodes[] = {\r\n    key_type(site_type(2, -10).sorted_index(2)),\r\n    key_type(site_type(2, -1).sorted_index(2)),\r\n    key_type(site_type(2, 0).sorted_index(2)),\r\n    key_type(site_type(2, 1).sorted_index(2)),\r\n    key_type(site_type(2, 2).sorted_index(2)),\r\n    key_type(site_type(2, 3).sorted_index(2)),\r\n  };\r\n  bool res[] = {false, false, false, false, true, true};\r\n  CHECK_NODE_COMPARISON(node, nodes, res, 6);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(node_comparison_test4) {\r\n  key_type node(site_type(0, 1).sorted_index(0), site_type(1, 0).sorted_index(1));\r\n  key_type nodes[] = {\r\n    key_type(site_type(2, -3).sorted_index(2)),\r\n    key_type(site_type(2, -2).sorted_index(2)),\r\n    key_type(site_type(2, -1).sorted_index(2)),\r\n    key_type(site_type(2, 0).sorted_index(2)),\r\n    key_type(site_type(2, 1).sorted_index(2)),\r\n    key_type(site_type(2, 3).sorted_index(2)),\r\n  };\r\n  bool res[] = {false, true, true, true, true, true};\r\n  CHECK_NODE_COMPARISON(node, nodes, res, 6);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(node_comparison_test5) {\r\n  key_type node(site_type(0, 0).sorted_index(0), site_type(1, 2).sorted_index(1));\r\n  key_type nodes[] = {\r\n    key_type(site_type(2, -10).sorted_index(2)),\r\n    key_type(site_type(2, 0).sorted_index(2)),\r\n    key_type(site_type(2, 1).sorted_index(2)),\r\n    key_type(site_type(2, 2).sorted_index(2)),\r\n    key_type(site_type(2, 5).sorted_index(2)),\r\n    key_type(site_type(2, 20).sorted_index(2)),\r\n  };\r\n  bool res[] = {false, false, true, true, true, true};\r\n  CHECK_NODE_COMPARISON(node, nodes, res, 6);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(node_comparison_test6) {\r\n  key_type node(site_type(1, 1).sorted_index(1), site_type(0, 0).sorted_index(0));\r\n  key_type nodes[] = {\r\n    key_type(site_type(2, -3).sorted_index(2)),\r\n    key_type(site_type(2, -2).sorted_index(2)),\r\n    key_type(site_type(2, 0).sorted_index(2)),\r\n    key_type(site_type(2, 1).sorted_index(2)),\r\n    key_type(site_type(2, 2).sorted_index(2)),\r\n    key_type(site_type(2, 3).sorted_index(2)),\r\n    key_type(site_type(2, 5).sorted_index(2)),\r\n  };\r\n  bool res[] = {false, false, false, false, false, false, true};\r\n  CHECK_NODE_COMPARISON(node, nodes, res, 7);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(node_comparison_test7) {\r\n  key_type node(site_type(0, 0).sorted_index(0), site_type(0, 2).sorted_index(1));\r\n  key_type nodes[] = {\r\n    key_type(site_type(1, 0).sorted_index(2)),\r\n    key_type(site_type(1, 1).sorted_index(2)),\r\n    key_type(site_type(1, 2).sorted_index(2)),\r\n  };\r\n  bool res[] = {false, false, true};\r\n  CHECK_NODE_COMPARISON(node, nodes, res, 3);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(node_comparison_test8) {\r\n  key_type node(site_type(0, 0).sorted_index(0), site_type(1, 1).sorted_index(2));\r\n  key_type nodes[] = {\r\n    key_type(site_type(1, 0).sorted_index(1)),\r\n    key_type(site_type(1, 1).sorted_index(2)),\r\n    key_type(site_type(1, 2).sorted_index(3)),\r\n    key_type(site_type(1, 1).sorted_index(2), site_type(0, 0).sorted_index(0)),\r\n  };\r\n  bool res[] = {false, true, true, true};\r\n  CHECK_NODE_COMPARISON(node, nodes, res, 4);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(circle_formation_predicate_test1) {\r\n  site_type site1(0, 0);\r\n  site_type site2(-8, 0);\r\n  site_type site3(0, 6);\r\n  CHECK_CIRCLE_FORMATION_PREDICATE(site1, site2, site3, -4.0, 3.0, 1.0);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(circle_formation_predicate_test2) {\r\n  int min_int = (std::numeric_limits<int>::min)();\r\n  int max_int = (std::numeric_limits<int>::max)();\r\n  site_type site1(min_int, min_int);\r\n  site_type site2(min_int, max_int);\r\n  site_type site3(max_int-1, max_int-1);\r\n  site_type site4(max_int, max_int);\r\n  CHECK_CIRCLE_EXISTENCE(site1, site2, site4, true);\r\n  CHECK_CIRCLE_EXISTENCE(site1, site3, site4, false);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(circle_formation_predicate_test3) {\r\n  site_type site1(-4, 0);\r\n  site_type site2(0, 4);\r\n  site_type site3(site1.point0(), site2.point0());\r\n  CHECK_CIRCLE_EXISTENCE(site1, site3, site2, false);\r\n  site_type site4(-2, 0);\r\n  site_type site5(0, 2);\r\n  CHECK_CIRCLE_EXISTENCE(site3, site4, site5, false);\r\n  CHECK_CIRCLE_EXISTENCE(site4, site5, site3, false);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(circle_formation_predicate_test4) {\r\n  site_type site1(-4, 0, -4, 20);\r\n  site_type site2(-2, 10);\r\n  site_type site3(4, 10);\r\n  CHECK_CIRCLE_FORMATION_PREDICATE(site1, site2, site3, 1.0, 6.0, 6.0);\r\n  CHECK_CIRCLE_FORMATION_PREDICATE(site3, site2, site1, 1.0, 14.0, 6.0);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(circle_formation_predicate_test5) {\r\n  site_type site1(1, 0, 7, 0);\r\n  site1.inverse();\r\n  site_type site2(-2, 4, 10, 4);\r\n  site_type site3(6, 2);\r\n  site_type site4(1, 0);\r\n  CHECK_CIRCLE_FORMATION_PREDICATE(site3, site1, site2, 4.0, 2.0, 6.0);\r\n  CHECK_CIRCLE_FORMATION_PREDICATE(site4, site2, site1, 1.0, 2.0, 3.0);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(circle_formation_predicate_test6) {\r\n  site_type site1(-1, 2, 8, -10);\r\n  site1.inverse();\r\n  site_type site2(-1, 0, 8, 12);\r\n  site_type site3(1, 1);\r\n  CHECK_CIRCLE_FORMATION_PREDICATE(site3, site2, site1, 6.0, 1.0, 11.0);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(circle_formation_predicate_test7) {\r\n  site_type site1(1, 0, 6, 0);\r\n  site1.inverse();\r\n  site_type site2(-6, 4, 0, 12);\r\n  site_type site3(1, 0);\r\n  CHECK_CIRCLE_FORMATION_PREDICATE(site3, site2, site1, 1.0, 5.0, 6.0);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(circle_formation_predicate_test8) {\r\n  site_type site1(1, 0, 5, 0);\r\n  site1.inverse();\r\n  site_type site2(0, 12, 8, 6);\r\n  site_type site3(1, 0);\r\n  CHECK_CIRCLE_FORMATION_PREDICATE(site3, site2, site1, 1.0, 5.0, 6.0);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(circle_formation_predicate_test9) {\r\n  site_type site1(0, 0, 4, 0);\r\n  site_type site2(0, 0, 0, 4);\r\n  site_type site3(0, 4, 4, 4);\r\n  site1.inverse();\r\n  CHECK_CIRCLE_FORMATION_PREDICATE(site1, site2, site3, 2.0, 2.0, 4.0);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(circle_formation_predicate_test10) {\r\n  site_type site1(1, 0, 41, 30);\r\n  site_type site2(-39, 30, 1, 60);\r\n  site_type site3(1, 60, 41, 30);\r\n  site1.inverse();\r\n  CHECK_CIRCLE_FORMATION_PREDICATE(site1, site2, site3, 1.0, 30.0, 25.0);\r\n}\r\n", "meta": {"hexsha": "40fff77874d7d121d9ad40bb0eeae7c6b120d0ad", "size": 19020, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/polygon/test/voronoi_predicates_test.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/polygon/test/voronoi_predicates_test.cpp", "max_issues_repo_name": "xiaoliang2121/Boost", "max_issues_repo_head_hexsha": "fc90c3fde129c62565c023f091eddc4a7ed9902b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-03-19T08:23:23.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-24T07:48:47.000Z", "max_forks_repo_path": "libs/polygon/test/voronoi_predicates_test.cpp", "max_forks_repo_name": "xiaoliang2121/Boost", "max_forks_repo_head_hexsha": "fc90c3fde129c62565c023f091eddc4a7ed9902b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 40.9913793103, "max_line_length": 96, "alphanum_fraction": 0.708044164, "num_tokens": 6125, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.4582311408636212}}
{"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/io.hpp>\r\n#include <boost/units/pow.hpp>\r\n#include <boost/units/systems/angle/degrees.hpp>\r\n#include <boost/units/systems/cgs.hpp>\r\n#include <boost/units/systems/cgs/io.hpp>\r\n#include <boost/units/systems/si.hpp>\r\n#include <boost/units/systems/si/io.hpp>\r\n#include <boost/lexical_cast.hpp>\r\n\r\nusing namespace boost::units;\r\n\r\nint main(int argc, char* argv[])\r\n{\r\n\tif (argc < 3)\r\n\t{\r\n\t\tstd::cout << \"Usage: ./units vertical_degrees horizontal_degrees\" << std::endl;\r\n\t\treturn -1;\r\n\t}\r\n\r\n    // test quantity_cast\r\n    {\r\n    // implicit value_type conversions\r\n    //[conversion_snippet_1\r\n    quantity<si::length>     L1 = quantity<si::length,int>(int(2.5)*si::meters);\r\n    quantity<si::length,int> L2(quantity<si::length,double>(2.5*si::meters));\r\n    //]\r\n    \r\n    //[conversion_snippet_3\r\n    quantity<si::length,int> L3 = static_cast<quantity<si::length,int> >(L1);\r\n    //]\r\n    \r\n    //[conversion_snippet_4\r\n    quantity<cgs::length>    L4 = static_cast<quantity<cgs::length> >(L1);\r\n    //]\r\n    \r\n    quantity<si::length,int> L5(4*si::meters),\r\n                             L6(5*si::meters);\r\n    quantity<cgs::length>    L7(L1);\r\n    \r\n    swap(L5,L6);\r\n    \r\n    std::cout << \"L1 = \" << L1 << std::endl\r\n              << \"L2 = \" << L2 << std::endl\r\n              << \"L3 = \" << L3 << std::endl\r\n              << \"L4 = \" << L4 << std::endl\r\n              << \"L5 = \" << L5 << std::endl\r\n              << \"L6 = \" << L6 << std::endl\r\n              << \"L7 = \" << L7 << std::endl\r\n              << std::endl;\r\n    }\r\n    \r\n    // test explicit unit system conversion\r\n    {\r\n    //[conversion_snippet_5\r\n    quantity<si::volume>    vs(1.0*pow<3>(si::meter));      \r\n    quantity<cgs::volume>   vc(vs);\r\n    quantity<si::volume>    vs2(vc);\r\n                        \r\n    quantity<si::energy>    es(1.0*si::joule);      \r\n    quantity<cgs::energy>   ec(es);\r\n    quantity<si::energy>    es2(ec);\r\n                        \r\n    quantity<si::velocity>  v1 = 2.0*si::meters/si::second,     \r\n                            v2(2.0*cgs::centimeters/cgs::second);\r\n    //]\r\n    \r\n    std::cout << \"volume (m^3)  = \" << vs << std::endl\r\n              << \"volume (cm^3) = \" << vc << std::endl\r\n              << \"volume (m^3)  = \" << vs2 << std::endl\r\n              << std::endl;\r\n            \r\n    std::cout << \"energy (joules) = \" << es << std::endl\r\n              << \"energy (ergs)   = \" << ec << std::endl\r\n              << \"energy (joules) = \" << es2 << std::endl\r\n              << std::endl;\r\n            \r\n    std::cout << \"velocity (2 m/s)  = \" << v1 << std::endl\r\n              << \"velocity (2 cm/s) = \" << v2 << std::endl\r\n              << std::endl;\r\n    }\r\n\r\n\t{\r\n\t\t// Unit\r\n\t\tconst si::plane_angle plane_angle_unit;\r\n\r\n\t\t// SI System Reference\r\n\t\tquantity<si::plane_angle> rad(1.0*si::radians); // 1 rad as plane angle\r\n\t\tquantity<si::plane_angle> degree_as_plane_angle(1.0*degree::degrees); // 1 degree as plane angle\r\n\r\n\t\t// Trigonometry and Angle System Reference\r\n\t\tquantity<degree::plane_angle> degree(1.0*degree::degrees);\r\n\r\n\t\tstd::cout << \"unit = \" << plane_angle_unit << std::endl; // rad\r\n\t\tstd::cout << \"1 radian = \" << rad << std::endl; // 1 rad \r\n\t\tstd::cout << \"1 degree as plane angle = \" << degree_as_plane_angle << std::endl; // 0.0174533 rad\r\n\t\tstd::cout << \"1 degree using angle system reference = \" << degree << std::endl; // 1 deg\r\n\r\n\t\t// Conversion from user input\r\n\t\tstd::cout << boost::lexical_cast<double>(argv[1]) << \" degrees: \"\r\n\t\t\t\t\t<< degree_as_plane_angle*boost::lexical_cast<double>(argv[1])\r\n\t\t\t\t\t<< \" \"\r\n\t\t\t\t\t<< boost::lexical_cast<double>(argv[2]) << \" degrees: \"\r\n\t\t\t\t\t<< degree_as_plane_angle*boost::lexical_cast<double>(argv[2])\r\n\t\t\t\t\t<< std::endl;\r\n\r\n\t\t// Get default radians values for AP and OS cameras \r\n\t\tstd:: cout << \"AP\" << std::endl;\r\n\r\n\t\tstd::cout << \"IRTV - MFOV\"\r\n\t\t\t\t\t<< \" vertical: \"\r\n\t\t\t\t\t<< degree_as_plane_angle*9.0\r\n\t\t\t\t\t<< \" horizontal: \"\r\n\t\t\t\t\t<< degree_as_plane_angle*14.0 << std::endl;\r\n\t\tstd::cout << \"IRTV - NFOV\"\r\n\t\t\t\t\t<< \" vertical: \"\r\n\t\t\t\t\t<< degree_as_plane_angle*3.0\r\n\t\t\t\t\t<< \" horizontal: \"\r\n\t\t\t\t\t<< degree_as_plane_angle*5.0 << std::endl;\r\n\t\tstd::cout << \"CTV - WFOV\"\r\n\t\t\t\t\t<< \" vertical: \"\r\n\t\t\t\t\t<< degree_as_plane_angle*17.0\r\n\t\t\t\t\t<< \" horizontal: \"\r\n\t\t\t\t\t<< degree_as_plane_angle*26.0 << std::endl;\r\n\t\tstd::cout << \"CTV - MFOV\"\r\n\t\t\t\t\t<< \" vertical: \"\r\n\t\t\t\t\t<< degree_as_plane_angle*4.0\r\n\t\t\t\t\t<< \" horizontal: \"\r\n\t\t\t\t\t<< degree_as_plane_angle*6.0 << std::endl;\r\n\t\tstd::cout << \"CTV - NFOV\"\r\n\t\t\t\t\t<< \" vertical: \"\r\n\t\t\t\t\t<< degree_as_plane_angle*2.0\r\n\t\t\t\t\t<< \" horizontal: \"\r\n\t\t\t\t\t<< degree_as_plane_angle*3.0 << std::endl;\r\n\r\n\t\tstd::cout << \"OS\" << std::endl;\r\n\r\n\t\tstd::cout << \"IRTV - MFOV\"\r\n\t\t\t\t\t<< \" vertical: \"\r\n\t\t\t\t\t<< degree_as_plane_angle*9.0\r\n\t\t\t\t\t<< \" horizontal: \"\r\n\t\t\t\t\t<< degree_as_plane_angle*14.0 << std::endl;\r\n\t\tstd::cout << \"IRTV - NFOV\"\r\n\t\t\t\t\t<< \" vertical: \"\r\n\t\t\t\t\t<< degree_as_plane_angle*3.0\r\n\t\t\t\t\t<< \" horizontal: \"\r\n\t\t\t\t\t<< degree_as_plane_angle*5.0 << std::endl;\r\n\t\tstd::cout << \"IRTV - UNFOV\"\r\n\t\t\t\t\t<< \" vertical: \"\r\n\t\t\t\t\t<< degree_as_plane_angle*2.0\r\n\t\t\t\t\t<< \" horizontal: \"\r\n\t\t\t\t\t<< degree_as_plane_angle*3.0 << std::endl;\r\n\t\tstd::cout << \"CHDTV - WFOV\"\r\n\t\t\t\t\t<< \" vertical: \"\r\n\t\t\t\t\t<< degree_as_plane_angle*27.0\r\n\t\t\t\t\t<< \" horizontal: \"\r\n\t\t\t\t\t<< degree_as_plane_angle*40.0 << std::endl;\r\n\t\tstd::cout << \"CHDTV - MFOV\"\r\n\t\t\t\t\t<< \" vertical: \"\r\n\t\t\t\t\t<< degree_as_plane_angle*10.0\r\n\t\t\t\t\t<< \" horizontal: \"\r\n\t\t\t\t\t<< degree_as_plane_angle*15.0 << std::endl;\r\n\t\tstd::cout << \"CHDTV - NFOV\"\r\n\t\t\t\t\t<< \" vertical: \"\r\n\t\t\t\t\t<< degree_as_plane_angle*3.0\r\n\t\t\t\t\t<< \" horizontal: \"\r\n\t\t\t\t\t<< degree_as_plane_angle*5.0 << std::endl;\r\n\t\tstd::cout << \"CHDTV - UNFOV\"\r\n\t\t\t\t\t<< \" vertical: \"\r\n\t\t\t\t\t<< degree_as_plane_angle*2.0\r\n\t\t\t\t\t<< \" horizontal: \"\r\n\t\t\t\t\t<< degree_as_plane_angle*3.0 << std::endl;\r\n\t\tstd::cout << \"LLLTV - WFOV\"\r\n\t\t\t\t\t<< \" vertical: \"\r\n\t\t\t\t\t<< degree_as_plane_angle*24.0\r\n\t\t\t\t\t<< \" horizontal: \"\r\n\t\t\t\t\t<< degree_as_plane_angle*36.0 << std::endl;\r\n\t\tstd::cout << \"LLLTV - MFOV\"\r\n\t\t\t\t\t<< \" vertical: \"\r\n\t\t\t\t\t<< degree_as_plane_angle*9.0\r\n\t\t\t\t\t<< \" horizontal: \"\r\n\t\t\t\t\t<< degree_as_plane_angle*14.0 << std::endl;\r\n\t\tstd::cout << \"LLLTV - NFOV\"\r\n\t\t\t\t\t<< \" vertical: \"\r\n\t\t\t\t\t<< degree_as_plane_angle*3.0\r\n\t\t\t\t\t<< \" horizontal: \"\r\n\t\t\t\t\t<< degree_as_plane_angle*5.0 << std::endl;\r\n\t}\r\n\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "50f184a9ce4830843039f3a82e14ad58b91368b7", "size": 6728, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/boost/boost.units/units.cpp", "max_stars_repo_name": "tarodnet/cplusplus-snippets", "max_stars_repo_head_hexsha": "2866102b53534163c2ebc1aaf6096467dfbdadaf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/boost/boost.units/units.cpp", "max_issues_repo_name": "tarodnet/cplusplus-snippets", "max_issues_repo_head_hexsha": "2866102b53534163c2ebc1aaf6096467dfbdadaf", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/boost/boost.units/units.cpp", "max_forks_repo_name": "tarodnet/cplusplus-snippets", "max_forks_repo_head_hexsha": "2866102b53534163c2ebc1aaf6096467dfbdadaf", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-06-06T02:23:20.000Z", "max_forks_repo_forks_event_max_datetime": "2015-06-06T02:23:20.000Z", "avg_line_length": 33.1428571429, "max_line_length": 100, "alphanum_fraction": 0.5374554102, "num_tokens": 2082, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.4582311408636212}}
{"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#include <nt2/trigonometric/include/functions/rem_pio2_medium.hpp>\n#include <boost/fusion/include/std_pair.hpp>\n#include <nt2/include/constants/pio_2.hpp>\n#include <nt2/include/constants/pio_4.hpp>\n#include <nt2/include/constants/one.hpp>\n#include <nt2/include/constants/zero.hpp>\n#include <nt2/include/constants/half.hpp>\n\n#include <nt2/sdk/unit/module.hpp>\n#include <nt2/sdk/unit/tests/relation.hpp>\n#include <nt2/sdk/unit/tests/ulp.hpp>\n#include <nt2/sdk/unit/tests/type_expr.hpp>\n\n#include <nt2/sdk/functor/meta/call.hpp>\n#include <nt2/sdk/meta/as_integer.hpp>\n\n\nNT2_TEST_CASE_TPL ( rem_pio2_medium_real__1_0,  NT2_REAL_TYPES)\n{\n\n  using nt2::rem_pio2_medium;\n  using nt2::tag::rem_pio2_medium_;\n  typedef typename nt2::meta::as_integer<T>::type iT;\n\n  NT2_TEST_TYPE_IS( (typename boost::dispatch::meta::call<rem_pio2_medium_(T)>::type)\n                  , (std::pair<iT,T>)\n                  );\n\n  {\n    T r1;\n    NT2_TEST_EQUAL( rem_pio2_medium(nt2::Pio_2<T>(), r1), nt2::One<iT>());\n    NT2_TEST_ULP_EQUAL( r1, nt2::Zero<T>(), 0.5);\n    NT2_TEST_EQUAL( rem_pio2_medium(nt2::Pio_4<T>()*nt2::Half<T>(), r1), nt2::Zero<iT>());\n    NT2_TEST_ULP_EQUAL( r1, nt2::Pio_4<T>()*nt2::Half<T>(), 0.5);\n  }\n}\n", "meta": {"hexsha": "103d15c34b389d6024770da38f478b1b7223292d", "size": 1711, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/core/trigonometric/unit/scalar/rem_pio2_medium.cpp", "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/unit/scalar/rem_pio2_medium.cpp", "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/unit/scalar/rem_pio2_medium.cpp", "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.0222222222, "max_line_length": 90, "alphanum_fraction": 0.6113383986, "num_tokens": 481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.4582311361988503}}
{"text": "#include <boost/numeric/ublas/operation.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <cstdlib>\n#include <cassert>\n#include <random>\n#include <cmath>\n#include \"Edec.hpp\"\nstatic int  n =2;\nstatic int  N =12;\nstatic int q =11158;\n//\u56db\u820d\u4e94\u5165\u53d6\u6574\u6570\ninline int mod(double num)\n{\n    int dev=(int)std::round(num/q);\n    return num-q*dev;\n}\nboost::numeric::ublas::matrix<int > FinalS(n+1,1);\ninline int RandomNum()\n{\n    std::random_device rd;\n    \n    std::mt19937 rng(rd());\n    \n    //\u5728\u8fd9\u91cc\u53d6\u5230\u4e00\u4e2a\u8303\u56f4\u57280\uff5e2q\u7684\u968f\u673a \u6570\u5b57\n    //\u5728\u53d6\u4e00\u4e2a\u77e9\u9635\u7684\u65f6\u5019mod q \u53d6\u56db\u820d\u4e94\u5165\n    std::uniform_int_distribution<int> uni(0,2*q);\n    \n    auto random_integer = uni(rng);\n   \n    return random_integer;\n}\nboost::numeric::ublas::matrix<int > GetRandomMatrixS()\n{\n    using matrix=boost::numeric::ublas::matrix<int>;\n    \n    matrix m1(n+1,1);\n    \n    m1(0,0)=1;\n    \n    for(unsigned int i=1;i<n+1;++i)\n    {\n      m1(i,0)=mod(RandomNum());\n    }\n    \n    return m1;\n}\nboost::numeric::ublas::matrix<int > GetRandomMatrixA()\n{\n    using matrix=boost::numeric::ublas::matrix<int>;\n    \n    matrix m1(N,n);\n    \n    for(unsigned int x=0;x<N;++x)\n    {\n        for(unsigned int y=0;y<n;++y)\n        {\n            m1(x,y)=mod(RandomNum());\n        }\n    }\n\n    return m1;\n}\n\nboost::numeric::ublas::matrix<int >  GetMatrixB()\n{\n    using matrix=boost::numeric::ublas::matrix<int>;\n    //\u5148\u53d6 e == N \u03c7 \u3002\n    matrix e(N,1);\n   \n    for(int i=0;i<N;++i)\n    {\n        e(i,0)=RandomNum()%2;\n\n    }\n//     std::cout<<e<<\"\\n\";\n    matrix b(N,1);\n    \n    auto MatrixA=GetRandomMatrixA();\n    \n    auto MatrixS=GetRandomMatrixS();\n    \n    FinalS=MatrixS;\n    \n    matrix MatrixSp(n,1);\n    \n    for(unsigned int i=1;i<=n;++i)\n    {\n        MatrixSp(i-1,0)=MatrixS(i,0);\n    }\n\n    auto MatrixB=boost::numeric::ublas::prod(MatrixA, MatrixSp);\n\n    b=( MatrixB+e);\n    \n    matrix MatrixAfinal(N,n+1);\n    \n    auto col1=boost::numeric::ublas::column(b, 0);\n    \n    MatrixA=-MatrixA;\n    \n    for(unsigned int i=0;i<N;++i)\n    {\n        for(unsigned int j=0;j<n+1;++j)\n        {\n            if(j==0){\n                MatrixAfinal(i,0)=b(i,0);\n            \n            }\n            \n            else\n            {\n                MatrixAfinal(i,j)=MatrixA(i,j-1);\n                \n            }\n        }\n   \n    }\n    \n    return MatrixAfinal;\n\n}\n\n//\u5bf9\u6d88\u606f\u7684\u52a0\u5bc6\n//secret\u4e3a\u8981\u52a0\u5bc6\u7684\u6570\u5b57\nboost::numeric::ublas::matrix<int > Enc(int secret)\n{\n    using matrix=boost::numeric::ublas::matrix<int>;\n    //\u5bc6\u6587 c\n    matrix c(n+1,1);\n\n    matrix r (N,1);\n    \n    auto MatrixA=GetMatrixB();\n    \n    \n    \n    for(unsigned int i=0;i<N;++i)\n    {\n        r(i,0)=RandomNum()%2;\n    }\n\n    //\u5012\u7f6e\u77e9\u9635\n    MatrixA= boost::numeric::ublas::trans(MatrixA);\n    \n    //A\u5012\u7f6eT * r\n    matrix tmp(n+1,1);\n    \n   tmp= boost::numeric::ublas::prod(MatrixA, r);\n    \n    //\u6784\u5efa\u52a0\u5bc6\u6d88\u606f\n    matrix m(n+1,1);\n    \n    m(0,0)=secret;\n    m(1,0)=0;\n    m(2,0)=0;\n    for(unsigned i=1;i<n+1;++i)\n    {\n        m(i,0)=m(i,0)*(q/2);\n    }\n    m(0,0)=m(0,0)*(q/2);\n\n    c=m+tmp;\n    \n    return c;\n}\ninline int InnerProduct(int (&arr1)[3],int (&arr2)[3])\n{\n    int res=0;\n    for(unsigned int i=0;i<n+1;++i)\n    {\n        res+=arr1[i]*arr2[i];\n    }\n    return res;\n}\n\nint  Dec(int val)\n{\n    //c\u4e3a\u5bc6\u6587\n    auto c=Enc(val);\n\n    \n    int arr1[3];\n    int arr2[3];\n    \n    auto res1=boost::numeric::ublas::column(c, 0);\n    \n    auto res2=boost::numeric::ublas::column(FinalS, 0);\n    \n    for(int i=0;i<n+1;++i)\n    {\n        arr1[i]=res1(i);\n        arr2[i]=res2(i);\n    }\n  int   res=InnerProduct(arr1, arr2);\n    \n    double qtwo=(double)2/q;\n    \n    res=res*qtwo;\n    \n    return res%2;\n}\n\n", "meta": {"hexsha": "073b21265b285df4ef1e238d7303e560c0598c83", "size": 3582, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Edec.cpp", "max_stars_repo_name": "fushenshen/ENC-AND-DEC", "max_stars_repo_head_hexsha": "c1d3c3c4cc09fd3951fd27ac62a3de202f2b37f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-10-10T03:09:12.000Z", "max_stars_repo_stars_event_max_datetime": "2016-10-10T03:09:12.000Z", "max_issues_repo_path": "Edec.cpp", "max_issues_repo_name": "fushenshen/ENC-AND-DEC", "max_issues_repo_head_hexsha": "c1d3c3c4cc09fd3951fd27ac62a3de202f2b37f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Edec.cpp", "max_forks_repo_name": "fushenshen/ENC-AND-DEC", "max_forks_repo_head_hexsha": "c1d3c3c4cc09fd3951fd27ac62a3de202f2b37f7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.645320197, "max_line_length": 64, "alphanum_fraction": 0.5156337242, "num_tokens": 1206, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.45812020174761703}}
{"text": "///////////////////////////////////////////////////////////////\n//  Copyright 2019 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#include \"../performance_test.hpp\"\n#if defined(TEST_MPQ)\n#include <boost/multiprecision/gmp.hpp>\n#endif\n\nvoid test21()\n{\n#ifdef TEST_MPQ\n   test<boost::multiprecision::mpq_rational>(\"mpq_rational\", 128);\n#endif\n}\n", "meta": {"hexsha": "4ff9e51731c43b1b5e7af0ce096a91b95a985d59", "size": 466, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/boost_1.78.0/libs/multiprecision/performance/performance_test_files/test21.cpp", "max_stars_repo_name": "LaudateCorpus1/math", "max_stars_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 106.0, "max_stars_repo_stars_event_min_datetime": "2015-08-07T04:23:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-27T18:25:15.000Z", "max_issues_repo_path": "3rdparty/boost_1_73_0/libs/multiprecision/performance/performance_test_files/test21.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 130.0, "max_issues_repo_issues_event_min_datetime": "2016-06-22T22:11:25.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-29T20:24:09.000Z", "max_forks_repo_path": "3rdparty/boost_1_73_0/libs/multiprecision/performance/performance_test_files/test21.cpp", "max_forks_repo_name": "qingkouwei/mediaones", "max_forks_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2015-07-08T19:18:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-14T16:39:56.000Z", "avg_line_length": 27.4117647059, "max_line_length": 68, "alphanum_fraction": 0.6459227468, "num_tokens": 113, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.78793120560257, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4580268450318738}}
{"text": "#include <fstream>\n#include <CGAL/Real_timer.h>\n#include <CGAL/Random.h>\n#include <CGAL/Simple_cartesian.h>\n\n#include <CGAL/Point_set_3.h>\n#include <CGAL/Point_set_3/IO.h>\n\n#include <CGAL/Shape_detection/Region_growing/Region_growing.h>\n#include <CGAL/Shape_detection/Region_growing/Region_growing_on_point_set.h>\n\n#include <boost/iterator/function_output_iterator.hpp>\n\n\nusing Kernel = CGAL::Simple_cartesian<double>;\nusing Point_3 = Kernel::Point_3;\nusing Vector_3 = Kernel::Vector_3;\n\nusing Point_set = CGAL::Point_set_3<Point_3>;\nusing Point_map = typename Point_set::Point_map;\nusing Normal_map = typename Point_set::Vector_map;\n\nnamespace Shape_detection = CGAL::Shape_detection::Point_set;\n\nusing Neighbor_query = Shape_detection::K_neighbor_query\n  <Kernel, Point_set, Point_map>;\nusing Region_type = Shape_detection::Least_squares_cylinder_fit_region\n  <Kernel, Point_set, Point_map, Normal_map>;\nusing Region_growing = CGAL::Shape_detection::Region_growing\n  <Point_set, Neighbor_query, Region_type>;\n\nint main (int argc, char** argv)\n{\n  std::ifstream ifile (argc > 1 ? argv[1] : \"data/cube.pwn\");\n  Point_set points;\n  ifile >> points;\n\n  std::cerr << points.size() << \" points read\" << std::endl;\n\n  // Input should have normals\n  assert (points.has_normal_map());\n\n  // Default parameters for data/cube.pwn\n  const std::size_t k = 24;\n  const double tolerance = 0.05;\n  const double max_angle = 5.;\n  const std::size_t min_region_size = 200;\n\n  // No constraint on radius\n  const double min_radius = 0.;\n  const double max_radius = std::numeric_limits<double>::infinity();\n\n  Neighbor_query neighbor_query(points, k, points.point_map());\n  Region_type region_type(points, tolerance, max_angle, min_region_size,\n                          min_radius, max_radius,\n                          points.point_map(), points.normal_map());\n  Region_growing region_growing(points, neighbor_query, region_type);\n\n  // Add maps to get colored output\n  Point_set::Property_map<unsigned char>\n    red = points.add_property_map<unsigned char>(\"red\", 0).first,\n    green = points.add_property_map<unsigned char>(\"green\", 0).first,\n    blue = points.add_property_map<unsigned char>(\"blue\", 0).first;\n\n  CGAL::Random random;\n\n  std::size_t nb_cylinders = 0;\n  CGAL::Real_timer timer;\n  timer.start();\n  region_growing.detect\n    (boost::make_function_output_iterator\n     ([&](const std::vector<std::size_t>& region)\n      {\n        // Assign a random color to each region\n        unsigned char r = (unsigned char)(random.get_int(64, 192));\n        unsigned char g = (unsigned char)(random.get_int(64, 192));\n        unsigned char b = (unsigned char)(random.get_int(64, 192));\n        for (const std::size_t& idx : region)\n        {\n          red[idx] = r;\n          green[idx] = g;\n          blue[idx] = b;\n        }\n        ++ nb_cylinders;\n      }));\n  timer.stop();\n\n  std::cerr << nb_cylinders << \" cylinders detected in \"\n            << timer.time() << \" seconds\" << std::endl;\n\n  // Save in colored_cylinders.ply\n  std::ofstream out (\"colored_cylinders.ply\");\n  CGAL::IO::set_binary_mode (out);\n  out << points;\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "60b8c956ec7741e5997be5bf5fe267a2350745ea", "size": 3139, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Shape_detection/examples/Shape_detection/region_growing_cylinders_on_point_set_3.cpp", "max_stars_repo_name": "Citronnier/cgal", "max_stars_repo_head_hexsha": "efad7b7b439096aebdc7a9a7ee9f56939a44bbf0", "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": "Shape_detection/examples/Shape_detection/region_growing_cylinders_on_point_set_3.cpp", "max_issues_repo_name": "Citronnier/cgal", "max_issues_repo_head_hexsha": "efad7b7b439096aebdc7a9a7ee9f56939a44bbf0", "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": "Shape_detection/examples/Shape_detection/region_growing_cylinders_on_point_set_3.cpp", "max_forks_repo_name": "Citronnier/cgal", "max_forks_repo_head_hexsha": "efad7b7b439096aebdc7a9a7ee9f56939a44bbf0", "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": 32.0306122449, "max_line_length": 76, "alphanum_fraction": 0.6935329723, "num_tokens": 808, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879312056025699, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.45802684503187374}}
{"text": "/* Copyright (c) 2015, Julian Straub <jstraub@csail.mit.edu>\n * Licensed under the MIT license. See the license file LICENSE.\n */\n\n#pragma once\n\n#include <Eigen/Dense>\n#include <iostream>\n\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/shared_ptr.hpp>\n\n//#include \"sphere.hpp\"\n//#include \"clusterer.hpp\"\n//#include \"sphericalKMeans.hpp\"\n#include \"ddpmeans.hpp\"\n//#include \"dpvMFmeans.hpp\"\n//#include \"dir.hpp\"\n//#include \"cat.hpp\"\n\nusing namespace Eigen;\nusing std::cout;\nusing std::endl;\n\ntemplate<class T>\nclass DDPvMFMeans : public DDPMeans<T>\n{\npublic:\n  DDPvMFMeans(const boost::shared_ptr<Matrix<T,Dynamic,Dynamic> >& spx,\n      T lambda, T beta, T Q, boost::mt19937* pRndGen);\n  virtual ~DDPvMFMeans();\n\n//  void initialize(const Matrix<T,Dynamic,Dynamic>& x);\n\n  virtual void updateLabelsParallel();\n  virtual void updateLabels();\n  virtual void updateCenters();\n  virtual void nextTimeStep(const boost::shared_ptr<Matrix<T,Dynamic,Dynamic> >& spx);\n  virtual void updateState(); // after converging for a single time instant\n//  virtual MatrixXu mostLikelyInds(uint32_t n, \n//     Matrix<T,Dynamic,Dynamic>& deviates);\n//  virtual T avgIntraClusterDeviation();\n  virtual uint32_t indOfClosestCluster(int32_t i);\n\n  virtual T dist(const Matrix<T,Dynamic,1>& a, const Matrix<T,Dynamic,1>& b);\n  virtual bool closer(T a, T b);\n  \nprotected:\n//  T lambda_;\n//  Sphere<T> S_;\n\n  T beta_;\n  T Q_; //TODO!\n\n  Matrix<T,Dynamic,Dynamic> xSums_;\n\n  virtual Matrix<T,Dynamic,1> computeSum(uint32_t k);\n  virtual void computeSums(void); // updates internal xSums_ \n\n  virtual void solveProblem1(T gamma, T age, T& phi, T& theta); \n  virtual void solveProblem2(const Matrix<T,Dynamic,1>& xSum, T zeta, T age, T w,\n      T& phi, T& theta, T& eta); \n\n  virtual T distToUninstantiated(const Matrix<T,Dynamic,1>& x_i, uint32_t k);\n  virtual void reInstantiatedOldCluster(const Matrix<T,Dynamic,1>& xSum, uint32_t k);\n\n};\n// --------------------------- impl -------------------------------------------\n\ntemplate<class T>\nDDPvMFMeans<T>::DDPvMFMeans(const boost::shared_ptr<Matrix<T,Dynamic,Dynamic> >& spx, \n    T lambda, T beta, T Q, boost::mt19937* pRndGen)\n  : DDPMeans<T>(spx,lambda,0.,0.,pRndGen), beta_(beta), Q_(Q)\n{\n  this->Kprev_ = 0; // so that centers are initialized directly from sample mean\n  this->psPrev_ = this->ps_;\n  xSums_ = Matrix<T,Dynamic,Dynamic>::Zero(this->D_,1);\n\n  assert(-2.0 < this->lambda_ && this->lambda_ < 0.0);\n}\n\ntemplate<class T>\nDDPvMFMeans<T>::~DDPvMFMeans()\n{}\n\ntemplate<class T>\nuint32_t DDPvMFMeans<T>::indOfClosestCluster(int32_t i)\n{\n  int z_i = this->K_;\n  T sim_closest = this->lambda_+1.;\n  T sim_k = 0.;\n  cout<<\"cluster dists \"<<i<<\": \"<< sim_closest;\n  for (uint32_t k=0; k<this->K_; ++k)\n  {\n    if(this->Ns_(k) == 0) \n    {// cluster not instantiated yet in this timestep\n      sim_k = distToUninstantiated(this->spx_->col(i), k);\n    }else{ // cluster instantiated\n      sim_k = dist(this->ps_.col(k), this->spx_->col(i));\n    }\n    cout<<\" \"<<sim_k;\n    if(closer(sim_k, sim_closest))\n    {\n      sim_closest = sim_k;\n      z_i = k;\n    }\n  }\n  cout<<\" => z_i=\"<<z_i<<endl;\n  return z_i;\n}\n\ntemplate<class T>\nT DDPvMFMeans<T>::distToUninstantiated(const Matrix<T,Dynamic,1>& x_i, uint32_t k)\n{\n\n  T phi, theta, eta;\n  T zeta = acos(max(static_cast<T>(-1.),min(static_cast<T>(1.0),\n          (x_i.transpose()*this->psPrev_.col(k))(0))));\n  solveProblem2(x_i, zeta, this->ts_[k], this->ws_[k], phi,theta,eta);\n\n//  cout<<\" phi = \"<<phi<<\" age=\"<<this->ts_[k]<<endl;\n\n  return this->ws_[k]*(cos(theta)-1.) \n    +this->ts_[k]*beta_*(cos(phi)-1.) \n    +cos(eta) // no minus 1 here cancels with Z(tau) from the two other assignments\n    +Q_*this->ts_[k];\n//  return cos(theta) + this->ts_[k]*cos(phi) + cos(eta);\n\n  // TODO: this was the old wrong way\n//  T phi, theta;\n//  solveProblem1( acos( max(static_cast<T>(-1.),min(static_cast<T>(1.), \n//            (this->ps_.col(k).transpose()*x_i)(0)))), this->ts_[k], phi, theta);\n//  return cos(theta) + beta_*this->ts_[k]*cos(phi);\n}\n\ntemplate<class T>\nvoid DDPvMFMeans<T>::updateLabels()\n{\n// TODO not sure how to parallelize\n//#pragma omp parallel for \n  for(uint32_t i=0; i<this->N_; ++i)\n  {\n    uint32_t z_i = indOfClosestCluster(i);\n    if(z_i == this->K_) \n    { // start a new cluster\n      this->ps_.conservativeResize(this->D_,this->K_+1);\n      this->Ns_.conservativeResize(this->K_+1); \n      this->ps_.col(this->K_) = this->spx_->col(i);\n      this->Ns_(z_i) = 1.;\n      this->K_ ++;\n//      cout<<\" added new cluster center at \"<<this->spx_->col(i).transpose()<<endl;\n    } else {\n      if(this->Ns_[z_i] == 0)\n      { // instantiated an old cluster\n        reInstantiatedOldCluster(this->spx_->col(i), z_i);\n      }\n      this->Ns_(z_i) ++;\n    }\n    if(this->z_(i) != this->UNASSIGNED) this->Ns_(this->z_(i)) --;\n    this->z_(i) = z_i;\n  }\n\n  for(uint32_t k=0; k<this->K_; ++k)\n        this->Ns_(k) =0;\n\n#pragma omp parallel for\n  for(uint32_t k=0; k<this->K_; ++k)\n    for(uint32_t i=0; i<this->N_; ++i)\n      if(this->z_(i) == k)\n      {\n        this->Ns_(k) ++; \n      }\n  cout<<\" Ns = \"<<this->Ns_.transpose()<<endl;\n};\n\ntemplate<class T>\nvoid DDPvMFMeans<T>::updateLabelsParallel()\n{\n// TODO not sure how to parallelize\n  Matrix<T,Dynamic,1> psNew(this->D_,1);\n  psNew.fill(0);\n  int32_t iNew = -1;\n  uint32_t reInstantiateOld = 0;\n  Matrix<T,Dynamic,1> reInstantiateFrom(this->D_,1);\n  reInstantiateFrom.fill(0);\n  int32_t iReinstantiate = -1;\n  cout<<\"::updateLabelsParallel\"<<endl;\n  uint32_t i0=0;\n  do{\n    iNew = -1;\n    iReinstantiate = -1;\n#pragma omp parallel for \n    for(uint32_t i=i0; i<this->N_; ++i)\n    {\n      uint32_t z_i = indOfClosestCluster(i);\n#pragma omp critical\n      {\n        if(z_i == this->K_) \n        { // start a new cluster\n          if(iNew < 0)\n          {\n            psNew = this->spx_->col(i);\n            iNew = i;\n          }\n        } else {\n          if(this->Ns_[z_i] == 0 && iReinstantiate < 0)\n          { // instantiated an old cluster\n            reInstantiateOld = z_i;\n            reInstantiateFrom =  this->spx_->col(i); \n            iReinstantiate = i;\n          }\n          //        this->Ns_(z_i) ++;\n        }\n      }\n      //    if(this->z_(i) != this->UNASSIGNED) this->Ns_(this->z_(i)) --;\n      this->z_(i) = z_i;\n    }\n    cout<<iReinstantiate<<\" \"<<iNew<<endl;\n\n    if(iReinstantiate >= 0 && iNew >= 0)\n    {\n      if(iNew < iReinstantiate)\n      {\n        this->ps_.conservativeResize(this->D_,this->K_+1);\n        this->Ns_.conservativeResize(this->K_+1); \n        this->ps_.col(this->K_) = psNew;\n        this->Ns_(this->K_) = 1.;\n        this->K_ ++;\n        i0 = iNew;\n      }else{\n        reInstantiatedOldCluster(reInstantiateFrom, reInstantiateOld);\n        i0 = iReinstantiate;\n      }\n    }else if(iReinstantiate < 0 && iNew >= 0)\n    {\n      this->ps_.conservativeResize(this->D_,this->K_+1);\n      this->Ns_.conservativeResize(this->K_+1); \n      this->ps_.col(this->K_) = psNew;\n      this->Ns_(this->K_) = 1.;\n      this->K_ ++;\n      i0 = iNew;\n    }else if(iReinstantiate >= 0 && iNew < 0)\n    {\n      reInstantiatedOldCluster(reInstantiateFrom, reInstantiateOld);\n        i0 = iReinstantiate;\n    }\n  }while(iReinstantiate >= 0 || iNew >= 0);\n\n  //TODO get counts from GPU\n#pragma omp parallel for\n  for(uint32_t k=0; k<this->K_; ++k)\n    for(uint32_t i=0; i<this->N_; ++i)\n      if(this->z_(i) == k)\n      {\n        this->Ns_(k) ++; \n      }\n\n};\n\ntemplate<class T>\nvoid DDPvMFMeans<T>::reInstantiatedOldCluster(const Matrix<T,Dynamic,1>& xSum, uint32_t k)\n{\n//  cout<<\"xSum: \"<<xSum.transpose()<<endl;\n  T phi, theta, eta;\n  T zeta = acos(max(static_cast<T>(-1.),min(static_cast<T>(1.0),\n          (xSum.transpose()*this->psPrev_.col(k))(0)/xSum.norm())));\n  solveProblem2(xSum , zeta, this->ts_[k], this->ws_[k], phi,theta,eta);\n\n  // rotate point from mean_k towards previous mean by angle eta?\n  this->ps_.col(k) = rotationFromAtoB<T>(xSum/xSum.norm(), \n      this->psPrev_.col(k), eta/(phi*this->ts_[k]+theta+eta)) \n};\n\ntemplate<class T>\nvoid DDPvMFMeans<T>::computeSums(void)\n{\n  xSums_ = Matrix<T,Dynamic,Dynamic>::Zero(this->D_, this->K_);\n#pragma omp parallel for\n  for(uint32_t k=0; k<this->K_; ++k)\n    for(uint32_t i=0; i<this->N_; ++i)\n      if(this->z_(i) == k)\n      {\n        xSums_.col(k) += this->spx_->col(i); \n      }\n}\n\n\ntemplate<class T>\nMatrix<T,Dynamic,1> DDPvMFMeans<T>::computeSum(uint32_t k)\n{\n  Matrix<T,Dynamic,1> mean_k(this->D_);\n  mean_k.setZero(this->D_);\n  for(uint32_t i=0; i<this->N_; ++i)\n    if(this->z_(i) == k)\n    {\n      mean_k += this->spx_->col(i); \n    }\n  return mean_k;\n}\n\ntemplate<class T>\nvoid DDPvMFMeans<T>::updateCenters()\n{\n//  xSums_ = computeSums();\n  computeSums();\n//#pragma omp parallel for \n  for(uint32_t k=0; k<this->K_; ++k)\n  {\n//    Matrix<T,Dynamic,1> mean_k = this->computeCenter(k);\n    if (this->Ns_(k) > 0) \n    { // have data to update kth cluster\n      if(k < this->Kprev_)\n      { //TODO\n        reInstantiatedOldCluster(xSums_.col(k), k);\n      }else{\n        this->ps_.col(k)= xSums_.col(k)/xSums_.col(k).norm(); //mean_k;\n      }\n    }\n  cout<<this->ps_<<endl;\n    assert(this->ps_(0,k) == this->ps_(0,k));\n  }\n};\n\ntemplate<class T>\nvoid DDPvMFMeans<T>::nextTimeStep(const boost::shared_ptr<Matrix<T,Dynamic,Dynamic> >& spx)\n{\n  assert(this->D_ == spx->rows());\n  if(this->spx_.get() != spx.get()) this->spx_ = spx; // update the data\n  this->N_ = spx->cols();\n  this->z_.resize(this->N_);\n  this->z_.fill(this->UNASSIGNED);\n};\n\ntemplate<class T>\nvoid DDPvMFMeans<T>::updateState()\n{\n//  xSums_ = computeSums(); // already computed from last updateCenters (and no\n//  label changes since)\n\n  for(uint32_t k=0; k<this->K_; ++k)\n  {\n    if (k<this->ws_.size() && this->Ns_(k) > 0)\n    { // instantiated cluster from previous time; \n      T phi, theta, eta;\n      T zeta = acos(max(static_cast<T>(-1.),min(static_cast<T>(1.),\n              (xSums_.col(k).transpose()*this->ps_.col(k))(0) \n              / xSums_.col(k).norm())));\n      solveProblem2(xSums_.col(k), zeta, this->ts_[k], this->ws_[k], phi,theta,eta);\n      this->ws_[k] = this->ws_[k]*cos(theta) \n        + beta_*this->ts_[k]*cos(phi)\n        + xSums_.col(k).norm()*cos(eta);\n\n      cout<<this->ws_[k]<<\" : \"<<theta<<\" \"<<phi<<\" \"<<eta\n        <<\" \"<< xSums_.col(k).norm()<<endl;\n\n//      this->ws_[k] = this->ws_[k]*cos(theta) + beta_*this->ts_[k]*cos(phi) \n//        + xSums_.col(k).norm()*cos(eta);\n//      this->ws_[k] = 1./(1./this->ws_[k] + this->ts_[k]*tau_) + this->Ns_(k);\n      this->ts_[k] = 0; // re-instantiated -> age is 0\n    }else if(k >= this->ws_.size()){\n      // new cluster\n      this->ts_.push_back(0);\n      //TODO\n      this->ws_.push_back(xSums_.col(k).norm());//this->Ns_(k));\n    }\n\n      assert(this->ws_[k] == this->ws_[k]);\n\n    this->ts_[k] ++; // increment all ages\n    cout<<\"cluster \"<<k\n      <<\"\\tN=\"<<this->Ns_(k)\n      <<\"\\tage=\"<<this->ts_[k]\n      <<\"\\tweight=\"<<this->ws_[k]\n      <<\"\\tcenter: \"<<this->ps_.col(k).transpose()<<endl;\n  }\n  this->psPrev_ = this->ps_;\n  this->Kprev_ = this->K_;\n};\n\n\ntemplate<class T>\nT DDPvMFMeans<T>::dist(const Matrix<T,Dynamic,1>& a, const Matrix<T,Dynamic,1>& b)\n{\n//  return acos(min(1.0,max(-1.0,(a.transpose()*b)(0)))); // angular similarity\n  return a.transpose()*b; // cosine similarity \n};\n\ntemplate<class T>\nbool DDPvMFMeans<T>::closer(T a, T b)\n{\n//  return a<b; // if dist a is greater than dist b a is closer than b (angular dist)\n  return a>b; // if dist a is greater than dist b a is closer than b (cosine dist)\n};\n\n\n\ntemplate<class T>\nvoid DDPvMFMeans<T>::solveProblem1(T gamma, T age, T& phi, T& theta)\n{\n  // solves\n  // (1)  sin(phi) beta = sin(theta)\n  // (2)  gamma = T phi + theta\n  // for phi and theta\n  phi = 0.0; \n\n  for (uint32_t i=0; i< 10; ++i)\n  {\n    T sinPhi = sin(phi);\n    T f = - gamma + age*phi + asin(beta_*sinPhi);\n    // mathematica\n    T df = age + (beta_*cos(phi))/sqrt(1.-beta_*beta_*sinPhi*sinPhi); \n    T dPhi = f/df;\n    phi = phi - dPhi; // Newton iteration\n//    cout<<\"@i=\"<<i<<\": \"<<phi<<\"\\t\"<<dPhi<<endl;\n    if(fabs(dPhi) < 1e-6) break;\n  }\n\n  theta = asin(beta_*sin(phi));\n};\n\n\ntemplate<class T>\nvoid DDPvMFMeans<T>::solveProblem2(const Matrix<T,Dynamic,1>& xSum, T zeta, \n    T age, T w, T& phi, T& theta, T& eta)\n{\n  // solves\n  // w sin(theta) = beta sin(phi) = ||xSum||_2 sin(eta) \n  // eta + T phi + theta = zeta = acos(\\mu0^T xSum/||xSum||_2)\n  phi = 0.0;\n\n//  cout<<\"w=\"<<w<<\" age=\"<<age<<\" zeta=\"<<zeta<<endl;\n\n  T L2xSum = xSum.norm();\n  for (uint32_t i=0; i< 10; ++i)\n  {\n    T sinPhi = sin(phi);\n    T cosPhi = cos(phi);\n    T f = - zeta + asin(beta_/L2xSum *sinPhi) + age * phi + asin(beta_/w *sinPhi);\n    T df = age + (beta_*cosPhi)/sqrt(L2xSum*L2xSum -\n        beta_*beta_*sinPhi*sinPhi) + (beta_*cosPhi)/sqrt(w*w -\n        beta_*beta_*sinPhi*sinPhi); \n\n    T dPhi = f/df;\n\n    phi = phi - dPhi; // Newton iteration\n//    cout<<\"@i=\"<<i<<\": \"<<\"f=\"<<f<<\" df=\"<<df<<\" phi=\"<<phi<<\"\\t\"<<dPhi<<endl;\n    if(fabs(dPhi) < 1e-6) break;\n  }\n\n  theta = asin(beta_/w *sin(phi));\n  eta = asin(beta_/L2xSum *sin(phi));\n};\n", "meta": {"hexsha": "045741598407659d7b173a0c9425f137a15e3ccf", "size": 13087, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/deprecated/ddpvMFmeans.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/deprecated/ddpvMFmeans.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/deprecated/ddpvMFmeans.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": 28.8896247241, "max_line_length": 91, "alphanum_fraction": 0.5895927256, "num_tokens": 4345, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311856832191, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4580268334526935}}
{"text": "#include \"gtest/gtest.h\"\n#include <Eigen/Core>\n#include \"Face.h\"\n#include \"Point.h\"\n\nnamespace {\n  using namespace Geotree;\n\n  class FaceTest : public ::testing::Test {\n  protected:\n  };\n\n  TEST_F(FaceTest, Basic)\n  {\n    Face face(Vector3d(0,0,0), Vector3d(0,0,1), Vector3d(0,0,2), 0);\n  }\n\n  TEST_F(FaceTest, intersect)\n  {\n    Face face(Vector3d(0,0,0), Vector3d(3,0,0), Vector3d(0,3,0), 0);\n    Segment segment(Vector3d(1,1,-1), Vector3d(1,1,1), 0);\n\n    std::vector <Point> points;\n    \n    face.intersect(segment, points);\n\n    EXPECT_EQ(points.size(), 1);\n  }\n\n  TEST_F(FaceTest, split)\n  {\n    Face face(Vector3d(0,0,0), Vector3d(1,0,0), Vector3d(0,1,0), 0);\n\n    std::vector <std::set<Point>> paths;\n    std::set<Point> path;\n    \n    Point p0(Vector3d(0.5,0,0));\n    Point p1(Vector3d(0,0.5,0));\n\n    path.insert(p0);\n    path.insert(p1);\n    paths.push_back(path);\n    std::vector <Matrix<int, Dynamic, 3>> split = face.split(paths);\n\n    EXPECT_EQ(split.size(), 2);\n  }\n}\n", "meta": {"hexsha": "985fafd3c0f3010be09d3e20a0e0fad53fc4622e", "size": 984, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/face.cc", "max_stars_repo_name": "untaugh/geotree", "max_stars_repo_head_hexsha": "4600a1cb4115094ed5c4c1500c6221a458e68be8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-07-27T00:58:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-20T22:26:10.000Z", "max_issues_repo_path": "test/face.cc", "max_issues_repo_name": "untaugh/geotree", "max_issues_repo_head_hexsha": "4600a1cb4115094ed5c4c1500c6221a458e68be8", "max_issues_repo_licenses": ["MIT"], "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/face.cc", "max_forks_repo_name": "untaugh/geotree", "max_forks_repo_head_hexsha": "4600a1cb4115094ed5c4c1500c6221a458e68be8", "max_forks_repo_licenses": ["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.5, "max_line_length": 68, "alphanum_fraction": 0.6117886179, "num_tokens": 346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.787931185683219, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.45802683345269346}}
{"text": "/**\n* This file is part of Fast-Planner.\n*\n* Copyright 2019 Boyu Zhou, Aerial Robotics Group, Hong Kong University of Science and Technology, <uav.ust.hk>\n* Developed by Boyu Zhou <bzhouai at connect dot ust dot hk>, <uv dot boyuzhou at gmail dot com>\n* for more information see <https://github.com/HKUST-Aerial-Robotics/Fast-Planner>.\n* If you use this code, please cite the respective publications as\n* listed on the above website.\n*\n* Fast-Planner 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* Fast-Planner is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU General Public License for more details.\n*\n* You should have received a copy of the GNU Lesser General Public License\n* along with Fast-Planner. If not, see <http://www.gnu.org/licenses/>.\n*/\n\n\n\n#ifndef _PLAN_CONTAINER_H_\n#define _PLAN_CONTAINER_H_\n\n#include <Eigen/Eigen>\n#include <vector>\n#include <ros/ros.h>\n\n#include <bspline/non_uniform_bspline.h>\n#include <traj_utils/polynomial_traj.h>\nusing std::vector;\n\nnamespace fast_planner {\n\nstruct PlanParameters {\n  /* planning algorithm parameters */\n  double max_vel_, max_acc_, max_jerk_;  // physical limits\n  double local_traj_len_;                // local replanning trajectory length\n  double ctrl_pt_dist;                   // distance between adjacient B-spline\n                                         // control points\n  double clearance_;\n  int dynamic_;\n  /* processing time */\n  double time_search_ = 0.0;\n  double time_optimize_ = 0.0;\n  double time_adjust_ = 0.0;\n};\n\nstruct LocalTrajData {\n  /* info of generated traj */\n\n  int traj_id_;\n  double duration_;\n  ros::Time start_time_;\n  Eigen::Vector3d start_pos_, Astar_Local_Target_;\n  NonUniformBspline position_traj_, velocity_traj_, acceleration_traj_, jerk_traj_, yaw_traj_, yawdot_traj_,\n      yawdotdot_traj_;\n  vector<vector<Eigen::Vector3d>> planned_wpts_, sampled_wpts_, motion_primitive_wpts_;\n  int best_primitive_index_;\n  vector<Eigen::Vector3d> geo_astar_wpts_;\n  vector<int> planned_motion_state_list_, sampled_state_list_;\n  PolynomialTraj best_traj_;\n  double compute_time_, benchmark_compute_time_, benchmark_acc_;\n};\n\nclass MidPlanData {\npublic:\n  MidPlanData(/* args */) {}\n  ~MidPlanData() {}\n\n  vector<Eigen::Vector3d> global_waypoints_;\n\n  // initial trajectory segment\n  NonUniformBspline initial_local_segment_;\n  vector<Eigen::Vector3d> local_start_end_derivative_;\n\n  // kinodynamic path\n  vector<Eigen::Vector3d> kino_path_;\n\n  // visibility constraint\n  vector<Eigen::Vector3d> block_pts_;\n  Eigen::MatrixXd ctrl_pts_;\n\n  // heading planning\n  vector<double> path_yaw_;\n  double dt_yaw_;\n  double dt_yaw_path_;\n};\n\n}  // namespace fast_planner\n\n#endif", "meta": {"hexsha": "b442483cb0ec52b14c05d1558a2614d8e6488f45", "size": 2990, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/TIE_navigation/plan_manage/include/plan_manage/plan_container.hpp", "max_stars_repo_name": "ZJU-FAST-Lab/Terrestrial-Aerial-Navigation", "max_stars_repo_head_hexsha": "3602623ff8cb9735c6ece8c25772a3809cb0362e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2022-01-09T06:35:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T02:34:39.000Z", "max_issues_repo_path": "src/TIE_navigation/plan_manage/include/plan_manage/plan_container.hpp", "max_issues_repo_name": "RoboticsZhang/Terrestrial-Aerial-Navigation", "max_issues_repo_head_hexsha": "d73b6fa9d51985f442fda6d0e282226cb7a45186", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/TIE_navigation/plan_manage/include/plan_manage/plan_container.hpp", "max_forks_repo_name": "RoboticsZhang/Terrestrial-Aerial-Navigation", "max_forks_repo_head_hexsha": "d73b6fa9d51985f442fda6d0e282226cb7a45186", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-09T05:44:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-09T05:44:24.000Z", "avg_line_length": 31.1458333333, "max_line_length": 111, "alphanum_fraction": 0.7451505017, "num_tokens": 723, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4580150165582799}}
{"text": "#include <cstdint>\n#include <memory>\n#include <vector>\n#include <string>\n#include <numeric>\n#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <omp.h>\n#include <stdio.h>\n#include <valarray>\n#include <boost/range/combine.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n\n#include <boost/numeric/mtl/mtl.hpp>\n#include <boost/numeric/itl/itl.hpp>\n\n#include <posit/posit>\n// Posit Arithmetic FPGA accelerator library\n#include <positarith.h>\n\n#include \"main.hpp\"\n#include \"defines.hpp\"\n#include \"utils.hpp\"\n#include \"blas.hpp\"\n#include \"vector_utils.hpp\"\n#include \"matrix_utils.hpp\"\n\nusing namespace std;\nusing namespace sw::unum;\nusing boost::multiprecision::cpp_dec_float_100;\n\nposit<NBITS, ES> random_number(float offset, float dev) {\n    float num_float;\n    posit<NBITS, 2> num_posit_2;\n    posit<NBITS, 3> num_posit_3;\n\n    do {\n        num_float = offset + (rand() * dev / RAND_MAX);\n        num_posit_2 = num_float;\n        num_posit_3 = num_float;\n    } while (num_posit_2 != num_float || num_posit_3 != num_float);\n\n    return posit<NBITS, ES>(num_float);\n}\n\nint main(int argc, char ** argv)\n{\n    vector<int> lengths = {10, 20, 30, 40, 50, 100, 200, 300, 400, 500, 1000, 2000, 3000, 4000, 5000, 10000, 20000, 30000, 40000, 50000, 100000, 200000, 300000, 400000, 500000};\n\n    std::string s_dot;\n    for(int length : lengths) {\n        s_dot = test_dot_product(length);\n\n        ofstream outfile(\"positarith_dot_es\" + std::to_string(ES) + \"_\" + std::to_string(length) + \".txt\", ios::out);\n        outfile << s_dot << endl;\n        outfile.close();\n\n        remove(\"top.wdb\");\n    }\n\n    return 0;\n}\n\nstd::string test_dot_product(int length) {\n    double t_fpga, t_sw, t_float;\n    double stop, start;\n    int i;\n    cpp_dec_float_100 da_sw = 0.0, da_hw = 0.0, da_float = 0.0;\n\n    // Test data set\n    std::vector<posit<NBITS,ES>> vec1, vec2;\n    // vec1.resize(length); vec2.resize(length);\n    for(int i = 0; i < length; i++) {\n        posit<NBITS,ES> pos1, pos2;\n        pos1 = random_number(0.0, 1.0);\n        pos2 = random_number(0.0, 1.0);\n\n        vec1.push_back(pos1);\n        vec2.push_back(pos2);\n    }\n\n    // Posit HW calculation\n    posit<NBITS,ES> res_hw = 0;\n    // t_fpga = vector_dot(vec1, vec2, res_hw);\n\n    // Posit SW calculation\n    posit<NBITS,ES> res_sw = 0.0;\n    start = omp_get_wtime();\n    // for(i = 0; i < length; i++) {\n    //     res_sw += vec1[i] * vec2[i];\n    // }\n    res_sw = sw::hprblas::dot(length, vec1, 1, vec2, 1);\n    stop = omp_get_wtime();\n    t_sw = stop - start;\n\n    // Float calculation\n    float res_float = 0.0;\n    start = omp_get_wtime();\n    #pragma omp parallel private(i) num_threads(8)\n    {\n        #pragma omp for reduction(+:res_float)\n        for(i = 0; i < length; i++) {\n            res_float += (float)vec1[i] * (float)vec2[i];\n        }\n    }\n    stop = omp_get_wtime();\n    t_float = stop - start;\n\n    // Reference calculation\n    cpp_dec_float_100 res_dec = 0.0;\n    for(int i = 0; i < length; i++) {\n        res_dec += (cpp_dec_float_100)((long double)vec1[i]) * (cpp_dec_float_100)((long double)vec2[i]);\n    }\n\n    // Calculate decimal accuracy\n    da_float = decimal_accuracy(res_dec, (cpp_dec_float_100)res_float);\n    da_sw = decimal_accuracy(res_dec, (cpp_dec_float_100)((long double)res_sw));\n    da_hw = decimal_accuracy(res_dec, (cpp_dec_float_100)((long double)res_hw));\n\n    return to_string_precision(t_fpga) + \",\" + to_string_precision(t_sw) + \",\" + to_string_precision(t_float) + \",\" + to_string_precision(da_hw) + \",\" + to_string_precision(da_sw) + \",\" + to_string_precision(da_float);\n}\n", "meta": {"hexsha": "76d3790f9c28d1449444427fd72a9bcaae0808b0", "size": 3599, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/positdot/src/main.cpp", "max_stars_repo_name": "lvandam/posit_blas_hdl", "max_stars_repo_head_hexsha": "4427bcf13cede86f626772903c546cbeae42457e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2018-10-31T10:22:02.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-31T22:24:22.000Z", "max_issues_repo_path": "examples/positdot/src/main.cpp", "max_issues_repo_name": "lvandam/posit_blas_hdl", "max_issues_repo_head_hexsha": "4427bcf13cede86f626772903c546cbeae42457e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-01T12:49:45.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-01T12:49:45.000Z", "max_forks_repo_path": "examples/positdot/src/main.cpp", "max_forks_repo_name": "lvandam/posit_blas_hdl", "max_forks_repo_head_hexsha": "4427bcf13cede86f626772903c546cbeae42457e", "max_forks_repo_licenses": ["Apache-2.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.2601626016, "max_line_length": 218, "alphanum_fraction": 0.6371214226, "num_tokens": 1090, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4580150109101094}}
{"text": "#ifndef YANNQ_GROUNDSTATE_NGDEXACT_HPP\n#define YANNQ_GROUNDSTATE_NGDEXACT_HPP\n#include <complex>\n\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n\n#include <tbb/tbb.h>\n\n#include \"ED/ConstructSparseMat.hpp\"\n#include \"Utilities/Utility.hpp\"\n\n#include \"Machines/AmplitudePhase.hpp\"\n\nnamespace yannq\n{\n\nclass NGDExact\n{\npublic:\n\tusing Machine = AmplitudePhase;\n\tusing RealScalar = typename Machine::RealScalar;\n\tusing ComplexScalar = typename Machine::ComplexScalar;\n\n\tusing RealMatrix = typename Machine::RealMatrix;\n\tusing RealVector = typename Machine::RealVector;\n\n\tusing ComplexMatrix = typename Machine::ComplexMatrix;\n\tusing ComplexVector = typename Machine::ComplexVector;\n\nprivate:\n\tconst uint32_t n_;\n\tconst AmplitudePhase& qs_;\n\ttbb::concurrent_vector<uint32_t> basis_;\n\n\tEigen::SparseMatrix<RealScalar> ham_;\n\n\tRealMatrix deltasAmp_;\n\tRealMatrix deltasPhase_;\n\n\tRealMatrix deltasAmpPsis_;\n\tRealMatrix deltasPhasePsis_;\n\n\tRealVector olocAmp_;\n\tRealVector olocPhase_;\n\n\tRealVector grad_;\n\n\tRealScalar energy_;\n\n\tvoid constructDeltaAmp()\n\t{\n\t\tusing Range = tbb::blocked_range<std::size_t>;\n\t\tconst int N = qs_.getN();\n\t\tdeltasAmp_.setZero(basis_.size(), qs_.getDimAmp());\n\t\tif(basis_.size() >= 32)\n\t\t{\n\t\t\ttbb::parallel_for(Range(std::size_t(0u), basis_.size(), 8),\n\t\t\t\t[&](const Range& r)\n\t\t\t{\n\t\t\t\tuint32_t start = r.begin();\n\t\t\t\tuint32_t end = r.end();\n\t\t\t\tRealMatrix tmp(end-start, qs_.getDimAmp());\n\t\t\t\tfor(uint32_t l = 0; l < end-start; ++l)\n\t\t\t\t{\n\t\t\t\t\ttmp.row(l) = \n\t\t\t\t\t\tqs_.logDerivAmp(qs_.makeAmpData(toSigma(N, basis_[l+start])));\n\t\t\t\t}\n\t\t\t\tdeltasAmp_.block(start, 0, end-start, qs_.getDimAmp()) = tmp;\n\t\t\t}, tbb::simple_partitioner());\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfor(uint32_t k = 0; k < basis_.size(); k++)\n\t\t\t{\n\t\t\t\tdeltasAmp_.row(k) = \n\t\t\t\t\tqs_.logDerivAmp(qs_.makeAmpData(toSigma(N, basis_[k])));\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid constructDeltaPhase()\n\t{\n\t\tusing Range = tbb::blocked_range<std::size_t>;\n\t\tconst int N = qs_.getN();\n\t\tdeltasPhase_.setZero(basis_.size(), qs_.getDimPhase());\n\t\n\t\tif(basis_.size() >= 32)\n\t\t{\n\t\t\ttbb::parallel_for(Range(std::size_t(0u), basis_.size(), 8),\n\t\t\t\t[&](const Range& r)\n\t\t\t{\n\t\t\t\tuint32_t start = r.begin();\n\t\t\t\tuint32_t end = r.end();\n\t\t\t\tRealMatrix tmp(end-start, qs_.getDimPhase());\n\t\t\t\tfor(uint32_t l = 0; l < end-start; ++l)\n\t\t\t\t{\n\t\t\t\t\ttmp.row(l) = \n\t\t\t\t\t\tqs_.logDerivPhase(qs_.makePhaseData(toSigma(N, basis_[l+start])));\n\t\t\t\t}\n\t\t\t\tdeltasPhase_.block(start, 0, end-start, qs_.getDimPhase()) = tmp;\n\t\t\t}, tbb::simple_partitioner());\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfor(uint32_t k = 0; k < basis_.size(); k++)\n\t\t\t{\n\t\t\t\tdeltasPhase_.row(k) = \n\t\t\t\t\tqs_.logDerivPhase(qs_.makePhaseData(toSigma(N, basis_[k])));\n\t\t\t}\n\t\t\n\t\t}\n\t}\n\npublic:\n\n\tRealScalar getEnergy() const\n\t{\n\t\treturn energy_;\n\t}\n\n\n\tvoid constructExact()\n\t{\n\t\tComplexVector st = getPsi(qs_, basis_, true);\n\t\tComplexVector k = ham_*st;\n\n\t\tenergy_ = std::real(ComplexScalar(st.adjoint()*k));\n\n\t\tconstructDeltaAmp();\n\t\tconstructDeltaPhase();\n\t\t\n\t\tdeltasAmpPsis_ = st.cwiseAbs2().asDiagonal()*deltasAmp_; \n\t\tolocAmp_ = deltasAmpPsis_.colwise().sum();\n\n\t\tdeltasPhasePsis_ = st.cwiseAbs2().asDiagonal()*deltasPhase_; \n\t\tolocPhase_ = deltasPhasePsis_.colwise().sum();\n\t\t\n\t\tk = st.conjugate().asDiagonal()*k;\n\t\tgrad_.resize(qs_.getDim());\n\t\tgrad_.head(qs_.getDimAmp()) = \n\t\t\t2.0*deltasAmp_.transpose()*k.real();\n\t\tgrad_.head(qs_.getDimAmp()) -= 2.0*energy_*olocAmp_;\n\t\tgrad_.tail(qs_.getDimPhase()) \n\t\t\t= 2.0*deltasPhase_.transpose()*k.imag();\n\t\t/*\n\t\tgrad_.tail(qs_.getDimPhase()) \n\t\t\t-= 2.0*energy_*olocPhase_;\n\t\t\t*/\n\t}\n\n\tRealScalar eloc() const\n\t{\n\t\treturn energy_;\n\t}\n\n\tconst RealVector& olocAmp() const&\n\t{\n\t\treturn olocAmp_;\n\t}\n\n\tRealMatrix olocAmp() &&\n\t{\n\t\treturn olocAmp_;\n\t}\n\n\tconst RealVector& olocPhase() const&\n\t{\n\t\treturn olocPhase_;\n\t}\n\n\tRealMatrix olocPhase() &&\n\t{\n\t\treturn olocPhase_;\n\t}\n\n\tRealMatrix corrMatAmp() const\n\t{\n\t\tRealMatrix res = deltasAmp_.transpose()*deltasAmpPsis_;\n\t\tres -= olocAmp_*olocAmp_.transpose();\n\t\treturn res;\n\t}\n\n\tRealMatrix corrMatPhase() const\n\t{\n\t\tRealMatrix res = deltasPhase_.transpose()*deltasPhasePsis_;\n\t\tres -= olocPhase_*olocPhase_.transpose();\n\t\treturn res;\n\t}\n\n\tRealVector energyGrad() const\n\t{\n\t\treturn grad_;\n\t}\n\n\ttemplate<class Iterable, class ColFunc>\n\tNGDExact(const AmplitudePhase& qs, Iterable&& basis, ColFunc&& col)\n\t  : n_{qs.getN()}, qs_(qs)\n\t{\n\t\ttbb::parallel_for_each(basis.begin(), basis.end(), \n\t\t\t\t[&](uint32_t elt)\n\t\t{\n\t\t\tbasis_.emplace_back(elt);\n\t\t});\n\t\ttbb::parallel_sort(basis_.begin(), basis_.end());\n\n\t\tham_ = edp::constructSubspaceMat(std::forward<ColFunc>(col), basis_);\n\t}\n};\n} //namespace yannq\n#endif//YANNQ_GROUNDSTATE_NGDEXACT_HPP\n", "meta": {"hexsha": "77cff594e6bbee20a4aa54178e9be66a1ba86210", "size": 4586, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Yannq/GroundState/NGDExact.hpp", "max_stars_repo_name": "cecri/yannq", "max_stars_repo_head_hexsha": "b78c1f86a255059f06b34dd5e538449e7261d0ee", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Yannq/GroundState/NGDExact.hpp", "max_issues_repo_name": "cecri/yannq", "max_issues_repo_head_hexsha": "b78c1f86a255059f06b34dd5e538449e7261d0ee", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Yannq/GroundState/NGDExact.hpp", "max_forks_repo_name": "cecri/yannq", "max_forks_repo_head_hexsha": "b78c1f86a255059f06b34dd5e538449e7261d0ee", "max_forks_repo_licenses": ["BSD-3-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.6320754717, "max_line_length": 72, "alphanum_fraction": 0.6768425643, "num_tokens": 1505, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4580150109101093}}
{"text": "//\n// Copyright Vardan Akopian 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_GBSV_HPP\n#define BOOST_NUMERIC_BINDINGS_LAPACK_GBSV_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/ublas_banded.hpp>\n#include <boost/numeric/bindings/traits/ublas_vector2.hpp>\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n#  include <boost/static_assert.hpp>\n#  include <boost/type_traits/is_same.hpp>\n#endif \n\n\nnamespace boost { namespace numeric { namespace bindings { \n\n  namespace lapack {\n\n\n    namespace detail {\n      inline \n      void gbtrf (int const n, int const m, int const kl, int const ku,\n                  double* ab, int const ldab, int* ipiv, int* info) \n      {\n        LAPACK_DGBTRF (&n, &m, &kl, &ku, ab, &ldab, ipiv, info);\n      }\n    }\n\n    template <typename MatrA, typename IVec>\n    inline\n    int gbtrf (MatrA& a, IVec& ipiv) {\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrA>::matrix_structure, \n        traits::banded_t\n      >::value)); \n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrA>::ordering_type, \n        traits::row_major_t\n      >::value)); \n#endif \n\n      int const n = traits::matrix_size1 (a);\n      int const m = traits::matrix_size2 (a); \n      assert (traits::vector_size (ipiv) == (m < n ? m : n));\n\n      // if the matrix has kl lower and ku upper diagonals, then we should have\n      // allocated kl lower and kl+ku upper diagonals\n      int const kl = traits::matrix_lower_bandwidth (a);\n      int const ku = traits::matrix_upper_bandwidth (a) - kl;\n      int const ld = traits::leading_dimension (a);\n\n      assert(ku >= 0);\n\n      int info; \n      detail::gbtrf (n, m, kl, ku,\n                     traits::matrix_storage (a), \n\t\t     ld,\n                     traits::vector_storage (ipiv),  \n                     &info);\n      return info; \n    }\n\n\n    namespace detail {\n      inline \n      void gbtrs (char const trans, int const n, int const kl, int const ku, int const m,\n                  double const* ab, int const ldab, int const* ipiv,\n\t\t  double* b, int const ldb, int* info) \n      {\n        LAPACK_DGBTRS (&trans, &n, &kl, &ku, &m, ab, &ldab, ipiv, b, &ldb, info);\n      }\n    }\n\n\n    template <typename MatrA, typename MatrB, typename IVec>\n    inline\n    int gbtrs (char const trans, MatrA const& a, IVec const& ipiv, MatrB& b) \n    {\n      assert (trans == 'N' || trans == 'T' || trans == 'C'); \n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrA>::matrix_structure, \n        traits::banded_t\n      >::value)); \n#endif \n\n      int 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 (ipiv)); \n\n      // if the matrix has kl lower and ku upper diagonals, then we should have\n      // allocated kl lower and kl+ku upper diagonals\n      int const kl = traits::matrix_lower_bandwidth (a);\n      int const ku = traits::matrix_upper_bandwidth (a) - kl;\n      int const ld = traits::leading_dimension (a);\n\n      assert(ku >= 0);\n\n      int info; \n      detail::gbtrs (trans, n, kl, ku, 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                     ld,\n#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n                     traits::vector_storage (ipiv),  \n#else\n                     traits::vector_storage_const (ipiv),  \n#endif\n                     traits::matrix_storage (b),\n                     traits::leading_dimension (b),\n                     &info);\n      return info; \n    }\n\n\n  }\n\n}}}\n\n#endif \n", "meta": {"hexsha": "6fd4c2e32f4fe76433acb088d47da89382ea9aec", "size": 4149, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/bindings/lapack/gbsv.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/gbsv.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/gbsv.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": 30.2846715328, "max_line_length": 89, "alphanum_fraction": 0.6189443239, "num_tokens": 1082, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.45800541278858004}}
{"text": "/*\n * Copyright Nick Thompson, 2017\n * Use, modification and distribution are subject to the\n * Boost Software License, Version 1.0. (See accompanying file\n * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#include <boost/math/quadrature/naive_monte_carlo.hpp>\n#include <iostream>\n#include <iomanip>\n#include <limits>\n#include <cmath>\n#include <thread>\n#include <future>\n#include <string>\n#include <chrono>\n#include <boost/math/special_functions/pow.hpp>\n#include <boost/math/constants/constants.hpp>\n\nusing std::vector;\nusing std::pair;\nusing boost::math::quadrature::naive_monte_carlo;\n\nvoid display_progress(double progress,\n                      double error_estimate,\n                      double current_estimate,\n                      std::chrono::duration<double> estimated_time_to_completion)\n{\n    int barWidth = 70;\n\n    std::cout << \"[\";\n    int pos = barWidth * progress;\n    for (int i = 0; i < barWidth; ++i) {\n        if (i < pos) std::cout << \"=\";\n        else if (i == pos) std::cout << \">\";\n        else std::cout << \" \";\n    }\n    std::cout << \"] \"\n              << int(progress * 100.0)\n              << \"%, E = \"\n              << std::setprecision(3)\n              << error_estimate\n              << \", time to completion: \"\n              << estimated_time_to_completion.count()\n              << \" seconds, estimate: \"\n              << std::setprecision(5)\n              << current_estimate\n              << \"     \\r\";\n\n    std::cout.flush();\n}\n\nint main()\n{\n    double exact = 1.3932039296856768591842462603255;\n    double A = 1.0 / boost::math::pow<3>(boost::math::constants::pi<double>());\n    auto g = [&](std::vector<double> const & x)\n    {\n      return A / (1.0 - cos(x[0])*cos(x[1])*cos(x[2]));\n    };\n    vector<pair<double, double>> bounds{{0, boost::math::constants::pi<double>() }, {0, boost::math::constants::pi<double>() }, {0, boost::math::constants::pi<double>() }};\n    naive_monte_carlo<double, decltype(g)> mc(g, bounds, 0.001);\n\n    auto task = mc.integrate();\n\n    int s = 0;\n    std::cout << \"Hit ctrl-c to cancel.\\n\";\n    while (task.wait_for(std::chrono::seconds(1)) != std::future_status::ready)\n    {\n        display_progress(mc.progress(),\n                         mc.current_error_estimate(),\n                         mc.current_estimate(),\n                         mc.estimated_time_to_completion());\n        // TODO: The following shows that cancellation works,\n        // but it would be nice to show how it works with a ctrl-c signal handler.\n        if (s++ > 25){\n          mc.cancel();\n          std::cout << \"\\nCancelling because this is too slow!\\n\";\n        }\n    }\n    double y = task.get();\n    display_progress(mc.progress(),\n                     mc.current_error_estimate(),\n                     mc.current_estimate(),\n                     mc.estimated_time_to_completion());\n    std::cout << std::setprecision(std::numeric_limits<double>::digits10) << std::fixed;\n    std::cout << \"\\nFinal value: \" << y << std::endl;\n    std::cout << \"Exact      : \" << exact << std::endl;\n    std::cout << \"Final error estimate: \" << mc.current_error_estimate() << std::endl;\n    std::cout << \"Actual error        : \" << abs(y - exact) << std::endl;\n    std::cout << \"Function calls: \" << mc.calls() << std::endl;\n    std::cout << \"Is this good enough? [y/N] \";\n    bool goodenough = true;\n    std::string line;\n    std::getline(std::cin, line);\n    if (line[0] != 'y')\n    {\n         goodenough = false;\n    }\n    double new_error = -1;\n    if (!goodenough)\n    {\n        std::cout << \"What is the new target error? \";\n        std::getline(std::cin, line);\n        new_error = atof(line.c_str());\n        if (new_error >= mc.current_error_estimate())\n        {\n           std::cout << \"That error bound is already satisfied.\\n\";\n           return 0;\n        }\n    }\n    if (new_error > 0)\n    {\n        mc.update_target_error(new_error);\n        auto task = mc.integrate();\n        std::cout << \"Hit ctrl-c to cancel.\\n\";\n        while (task.wait_for(std::chrono::seconds(1)) != std::future_status::ready)\n        {\n            display_progress(mc.progress(),\n                             mc.current_error_estimate(),\n                             mc.current_estimate(),\n                             mc.estimated_time_to_completion());\n        }\n        double y = task.get();\n        display_progress(mc.progress(),\n                         mc.current_error_estimate(),\n                         mc.current_estimate(),\n                         mc.estimated_time_to_completion());\n        std::cout << std::setprecision(std::numeric_limits<double>::digits10) << std::fixed;\n        std::cout << \"\\nFinal value: \" << y << std::endl;\n        std::cout << \"Exact      : \" << exact << std::endl;\n        std::cout << \"Final error estimate: \" << mc.current_error_estimate() << std::endl;\n        std::cout << \"Actual error        : \" << abs(y - exact) << std::endl;\n        std::cout << \"Function calls: \" << mc.calls() << std::endl;\n    }\n}\n", "meta": {"hexsha": "800eb679475cd9606e621be0831867224cc36476", "size": 5009, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/libs/math/example/naive_monte_carlo_example.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/math/example/naive_monte_carlo_example.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/math/example/naive_monte_carlo_example.cpp", "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": 36.5620437956, "max_line_length": 172, "alphanum_fraction": 0.5428229187, "num_tokens": 1204, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.45800541278858004}}
{"text": "// Copyright  (C)  2007  Ruben Smits <ruben dot smits at mech dot kuleuven dot be>\n\n// Version: 1.0\n// Author: Ruben Smits <ruben dot smits at mech dot kuleuven dot be>\n// Maintainer: Ruben Smits <ruben dot smits at mech dot kuleuven dot be>\n// URL: http://www.orocos.org/kdl\n\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 2.1 of the License, or (at your option) any later version.\n\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n// Lesser General Public License for more details.\n\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n// Modified to account for \"mimic\" joints, i.e. joints whose motion has a\n// linear relationship to that of another joint.\n// Copyright  (C)  2013  Sachin Chitta, Willow Garage\n\n#ifndef KDL_CHAIN_IKSOLVERVEL_PINV_Mimic_HPP\n#define KDL_CHAIN_IKSOLVERVEL_PINV_Mimic_HPP\n\n#include <kdl/config.h>\n#include <kdl/chainiksolver.hpp>\n#include <kdl/chainjnttojacsolver.hpp>\n\n#include <moveit/kdl_kinematics_plugin/joint_mimic.hpp>\n#include <Eigen/SVD>\n\nnamespace KDL\n{\n/**\n * Implementation of a inverse velocity kinematics algorithm based\n * on the generalize pseudo inverse to calculate the velocity\n * transformation from Cartesian to joint space of a general\n * KDL::Chain. It uses a svd-calculation based on householders\n * rotations.\n *\n * @ingroup KinematicFamily\n */\nclass ChainIkSolverVelMimicSVD : public ChainIkSolverVel\n{\npublic:\n  /**\n   * Constructor of the solver\n   *\n   * @param chain the chain to calculate the inverse velocity kinematics for\n   * @param mimic_joints A vector of indices that map each (and every) joint onto the corresponding joint in a\n   * reduced set of joints that do not include the mimic joints. This vector must be of size chain.getNrOfJoints().\n   * E.g. if an arm has 7 joints: j0 to j6. Say j2 mimics (follows) j0. Then, mimic_joints should be: [0 1 0 3 4 5 6]\n   * @param num_mimic_joints The number of joints that are setup to follow other joints\n   * @param position_ik false if you want to solve for the full 6 dof end-effector pose,\n   *        true if you want to solve only for the 3 dof end-effector position.\n   * @param threshold if a singular value is below this value, its inverse is set to zero, default: 0.001\n   */\n  explicit ChainIkSolverVelMimicSVD(const Chain& chain_,\n                                    const std::vector<kdl_kinematics_plugin::JointMimic>& mimic_joints,\n                                    bool position_ik = false, double threshold = 0.001);\n\n// TODO: simplify after kinetic support is dropped\n#define KDL_VERSION_LESS(a, b, c) ((KDL_VERSION) < ((a << 16) | (b << 8) | c))\n#if KDL_VERSION_LESS(1, 4, 0)\n  void updateInternalDataStructures();\n#else\n  void updateInternalDataStructures() override;\n#endif\n#undef KDL_VERSION_LESS\n\n  ~ChainIkSolverVelMimicSVD() override;\n\n  int CartToJnt(const JntArray& q_in, const Twist& v_in, JntArray& qdot_out) override\n  {\n    return CartToJnt(q_in, v_in, qdot_out, Eigen::VectorXd::Constant(svd_.cols(), 1.0),\n                     Eigen::Matrix<double, 6, 1>::Constant(1.0));\n  }\n\n  /** Compute qdot_out = W_q * (W_x * J * W_q)^# * W_x * v_in\n   *\n   * where W_q and W_x are joint- and Cartesian weights respectively.\n   * A smaller joint weight (< 1.0) will reduce the contribution of this joint to the solution. */\n  int CartToJnt(const JntArray& q_in, const Twist& v_in, JntArray& qdot_out, const Eigen::VectorXd& joint_weights,\n                const Eigen::Matrix<double, 6, 1>& cartesian_weights);\n\n  /// not implemented.\n  int CartToJnt(const JntArray& q_init, const FrameVel& v_in, JntArrayVel& q_out) override\n  {\n    return -1;\n  }\n\n  /// Return true iff we ignore orientation but only consider position for inverse kinematics\n  bool isPositionOnly() const\n  {\n    return svd_.rows() == 3;\n  }\n\nprivate:\n  bool jacToJacReduced(const Jacobian& jac, Jacobian& jac_reduced);\n\n  // Mimic joint specific\n  const std::vector<kdl_kinematics_plugin::JointMimic>& mimic_joints_;\n  int num_mimic_joints_;\n\n  const Chain& chain_;\n  ChainJntToJacSolver jnt2jac_;\n\n  Eigen::JacobiSVD<Eigen::MatrixXd> svd_;\n  Eigen::VectorXd qdot_out_reduced_;\n\n  Jacobian jac_;          // full Jacobian\n  Jacobian jac_reduced_;  // reduced Jacobian with contributions of mimic joints mapped onto active DoFs\n};\n}\n#endif\n", "meta": {"hexsha": "9cff711601d8275f18a8de4d340648c7fe50a2a4", "size": 4723, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "moveit_kinematics/kdl_kinematics_plugin/include/moveit/kdl_kinematics_plugin/chainiksolver_vel_mimic_svd.hpp", "max_stars_repo_name": "limcatrina/moveit", "max_stars_repo_head_hexsha": "f94fcc33882aaac20f7e3c07e5df88a4a77e6e8a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-11-17T13:57:15.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-06T19:34:00.000Z", "max_issues_repo_path": "moveit_kinematics/kdl_kinematics_plugin/include/moveit/kdl_kinematics_plugin/chainiksolver_vel_mimic_svd.hpp", "max_issues_repo_name": "limcatrina/moveit", "max_issues_repo_head_hexsha": "f94fcc33882aaac20f7e3c07e5df88a4a77e6e8a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-11-14T23:50:30.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-14T16:07:03.000Z", "max_forks_repo_path": "moveit_kinematics/kdl_kinematics_plugin/include/moveit/kdl_kinematics_plugin/chainiksolver_vel_mimic_svd.hpp", "max_forks_repo_name": "limcatrina/moveit", "max_forks_repo_head_hexsha": "f94fcc33882aaac20f7e3c07e5df88a4a77e6e8a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-12-19T01:45:06.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-19T01:50:18.000Z", "avg_line_length": 39.3583333333, "max_line_length": 117, "alphanum_fraction": 0.7224221893, "num_tokens": 1299, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.61878043374385, "lm_q1q2_score": 0.4580054127885799}}
{"text": "//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\file StaticNoiseModel-inl.hpp\n///\n/// \\author Sean Anderson, ASRL\n//////////////////////////////////////////////////////////////////////////////////////////////\n\n#include <steam/problem/NoiseModel.hpp>\n\n#include <iostream>\n#include <stdexcept>\n\n#include <Eigen/Cholesky>\n\nnamespace steam {\n\n\ntemplate<int MEAS_DIM>\nDynamicNoiseModel<MEAS_DIM>::DynamicNoiseModel(std::shared_ptr<NoiseEvaluator<MEAS_DIM>> eval) :\neval_(eval) {\n  this->setByCovariance(eval_->evaluateCovariance());\n}\n\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Get a reference to the square root information matrix\n//////////////////////////////////////////////////////////////////////////////////////////////\ntemplate<int MEAS_DIM>\nconst Eigen::Matrix<double,MEAS_DIM,MEAS_DIM>& DynamicNoiseModel<MEAS_DIM>::getSqrtInformation() const {\n  this->setByCovariance(eval_->evaluateCovariance());\n  return this->sqrtInformation_;\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Get the norm of the whitened error vector, sqrt(rawError^T * info * rawError)\n//////////////////////////////////////////////////////////////////////////////////////////////\ntemplate<int MEAS_DIM>\ndouble DynamicNoiseModel<MEAS_DIM>::getWhitenedErrorNorm(\n    const Eigen::Matrix<double,MEAS_DIM,1>& rawError) const {\n  this->setByCovariance(eval_->evaluateCovariance());\n  return (this->sqrtInformation_*rawError).norm();\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Get the whitened error vector, sqrtInformation*rawError\n//////////////////////////////////////////////////////////////////////////////////////////////\ntemplate<int MEAS_DIM>\nEigen::Matrix<double,MEAS_DIM,1> DynamicNoiseModel<MEAS_DIM>::whitenError(\n    const Eigen::Matrix<double,MEAS_DIM,1>& rawError) const {\n  this->setByCovariance(eval_->evaluateCovariance());\n  return this->sqrtInformation_*rawError;\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Default constructor\n//////////////////////////////////////////////////////////////////////////////////////////////\ntemplate<int MEAS_DIM>\nStaticNoiseModel<MEAS_DIM>::StaticNoiseModel() {\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief General constructor\n//////////////////////////////////////////////////////////////////////////////////////////////\ntemplate<int MEAS_DIM>\nBaseNoiseModel<MEAS_DIM>::BaseNoiseModel(const Eigen::Matrix<double,MEAS_DIM,MEAS_DIM>& matrix,\n                                 MatrixType type) {\n\n  // Depending on the type of 'matrix', we set the internal storage\n  switch(type) {\n    case COVARIANCE :\n      setByCovariance(matrix);\n      break;\n    case INFORMATION :\n      setByInformation(matrix);\n      break;\n    case SQRT_INFORMATION :\n      setBySqrtInformation(matrix);\n      break;\n  }\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Set by covariance matrix\n//////////////////////////////////////////////////////////////////////////////////////////////\ntemplate<int MEAS_DIM>\nvoid BaseNoiseModel<MEAS_DIM>::setByCovariance(\n    const Eigen::Matrix<double,MEAS_DIM,MEAS_DIM>& matrix) const {\n\n  // Information is the inverse of covariance\n  this->setByInformation(matrix.inverse());\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Set by information matrix\n//////////////////////////////////////////////////////////////////////////////////////////////\ntemplate<int MEAS_DIM>\nvoid BaseNoiseModel<MEAS_DIM>::setByInformation(\n    const Eigen::Matrix<double,MEAS_DIM,MEAS_DIM>& matrix) const {\n\n  // Check that the matrix is positive definite\n  this->assertPositiveDefiniteMatrix(matrix);\n\n  // Perform an LLT decomposition\n  Eigen::LLT<Eigen::Matrix<double,MEAS_DIM,MEAS_DIM> > lltOfInformation(matrix);\n\n  // Store upper triangular matrix (the square root information matrix)\n  this->setBySqrtInformation(lltOfInformation.matrixL().transpose());\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Set by square root of information matrix\n//////////////////////////////////////////////////////////////////////////////////////////////\ntemplate<int MEAS_DIM>\nvoid BaseNoiseModel<MEAS_DIM>::setBySqrtInformation(\n    const Eigen::Matrix<double,MEAS_DIM,MEAS_DIM>& matrix)  const {\n\n  // Set internal storage matrix\n  sqrtInformation_ = matrix; // todo: check this is upper triangular\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Assert that the matrix is positive definite\n//////////////////////////////////////////////////////////////////////////////////////////////\ntemplate<int MEAS_DIM>\nvoid BaseNoiseModel<MEAS_DIM>::assertPositiveDefiniteMatrix(\n    const Eigen::Matrix<double,MEAS_DIM,MEAS_DIM>& matrix)  const{\n\n  // Initialize an eigen value solver\n  Eigen::SelfAdjointEigenSolver<Eigen::Matrix<double,MEAS_DIM,MEAS_DIM> >\n      eigsolver(matrix, Eigen::EigenvaluesOnly);\n\n  // Check the minimum eigen value\n  if (eigsolver.eigenvalues().minCoeff() <= 0) {\n    std::stringstream ss; ss << \"Covariance \\n\" << matrix << \"\\n must be positive definite. \"\n                             << \"Min. eigenvalue : \" << eigsolver.eigenvalues().minCoeff();\n    throw std::invalid_argument(ss.str());\n  }\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief General constructor\n//////////////////////////////////////////////////////////////////////////////////////////////\ntemplate<int MEAS_DIM>\nStaticNoiseModel<MEAS_DIM>::StaticNoiseModel(const Eigen::Matrix<double,MEAS_DIM,MEAS_DIM>& matrix,\n                                             MatrixType type)\n: BaseNoiseModel<MEAS_DIM>::BaseNoiseModel(matrix,type) {\n\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Get a reference to the square root information matrix\n//////////////////////////////////////////////////////////////////////////////////////////////\ntemplate<int MEAS_DIM>\nconst Eigen::Matrix<double,MEAS_DIM,MEAS_DIM>& StaticNoiseModel<MEAS_DIM>::getSqrtInformation() const {\n  return this->sqrtInformation_;\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Get the norm of the whitened error vector, sqrt(rawError^T * info * rawError)\n//////////////////////////////////////////////////////////////////////////////////////////////\ntemplate<int MEAS_DIM>\ndouble StaticNoiseModel<MEAS_DIM>::getWhitenedErrorNorm(\n    const Eigen::Matrix<double,MEAS_DIM,1>& rawError) const {\n  return (this->sqrtInformation_*rawError).norm();\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Get the whitened error vector, sqrtInformation*rawError\n//////////////////////////////////////////////////////////////////////////////////////////////\ntemplate<int MEAS_DIM>\nEigen::Matrix<double,MEAS_DIM,1> StaticNoiseModel<MEAS_DIM>::whitenError(\n    const Eigen::Matrix<double,MEAS_DIM,1>& rawError) const {\n  return this->sqrtInformation_*rawError;\n}\n\n\n} // steam\n", "meta": {"hexsha": "9c2e3b7b6c465d5fe663af7df84b107e01909982", "size": 7481, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/steam/problem/NoiseModel-inl.hpp", "max_stars_repo_name": "utiasASRL/steam", "max_stars_repo_head_hexsha": "0905736fa356ce743636453b37e952580d40d425", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 38.0, "max_stars_repo_stars_event_min_datetime": "2019-10-17T01:37:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T03:55:47.000Z", "max_issues_repo_path": "include/steam/problem/NoiseModel-inl.hpp", "max_issues_repo_name": "utiasASRL/steam", "max_issues_repo_head_hexsha": "0905736fa356ce743636453b37e952580d40d425", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-12-21T21:25:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-01T23:08:57.000Z", "max_forks_repo_path": "include/steam/problem/NoiseModel-inl.hpp", "max_forks_repo_name": "utiasASRL/steam", "max_forks_repo_head_hexsha": "0905736fa356ce743636453b37e952580d40d425", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-12-21T21:13:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T23:42:14.000Z", "avg_line_length": 42.2655367232, "max_line_length": 104, "alphanum_fraction": 0.4749365058, "num_tokens": 1307, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390162, "lm_q2_score": 0.6187804196836383, "lm_q1q2_score": 0.45800540238157167}}
{"text": "/*\n * Copyright (C) 2018, Matt Zucker\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 * Original source: https://github.com/mzucker/ccdwrapper\n */\n\n#ifndef _CCD_EIGEN_H_\n#define _CCD_EIGEN_H_\n\n#include <ccd/ccd.h>\n#include <Eigen/Geometry>\n#include <iostream>\n#include <type_traits>\n\nstatic_assert(std::is_same<double, ccd_real_t>::value,\n    \"This plugin requires libccd to be built with double precision support.\");\n\nnamespace ccdw {\n\ntypedef Eigen::Matrix<ccd_real_t, 3, 1> vec3;\ntypedef Eigen::Matrix<ccd_real_t, 4, 1> vec4;\n\ntypedef Eigen::Matrix<ccd_real_t, 3, 3> mat3;\ntypedef Eigen::Matrix<ccd_real_t, 4, 4> mat4;\ntypedef Eigen::Quaternion<ccd_real_t> quat;\n\nclass Transform3 {\npublic:\n\n    Transform3():\n        _rotation(quat::Identity()),\n        _translation(0,0,0) { _update(); }\n\n    explicit Transform3(const vec3& t):\n        _rotation(quat::Identity()),\n        _translation(t) { _update(); }\n\n    explicit Transform3(const quat& r):\n        _rotation(r),\n        _translation(0, 0, 0) { _update(); }\n\n    Transform3(const quat& q, const vec3& t):\n        _rotation(q), _translation(t) { _update(); }\n\n    Transform3 inverse() const {\n        return Transform3(rotation().inverse(),\n                          -(rotation().inverse()*translation()));\n\n    }\n\n    void setTranslation(const vec3& t) {\n        _translation = t;\n        _update();\n    }\n\n    void setRotation(const quat& q) {\n        _rotation = q;\n        _update();\n    }\n\n    const vec3& translation() const {\n        return _translation;\n    }\n\n    const quat& rotation() const {\n        return _rotation;\n    }\n\n    const Eigen::Affine3d& tobj() const {\n        return _xform;\n    }\n\n    mat4 matrix() const {\n        return _xform.matrix();\n    }\n\n    vec3 transformInv(const vec3& p) const {\n        return _xform_inv * p;\n    }\n\n    vec3 transformFwd(const vec3& p) const {\n        return _xform * p;\n    }\n\n    Transform3 compose(const Transform3& other) const {\n        return Transform3(this->rotation() * other.rotation(),\n                          this->translation() + this->rotation()*other.translation());\n    }\n\nprivate:\n\n    quat _rotation;\n    vec3 _translation;\n\n    Eigen::Affine3d _xform;\n    Eigen::Affine3d _xform_inv;\n\n    void _update() {\n        _xform = Eigen::Translation<double, 3>(_translation) * _rotation;\n        _xform_inv = _rotation.inverse() * Eigen::Translation<double, 3>(-_translation);\n    }\n\n};\n\ninline vec3 operator*(const Transform3& x, const vec3& v) {\n    return x.transformFwd(v);\n}\n\ninline Transform3 operator*(const Transform3& x1, const Transform3& x2) {\n    return x1.compose(x2);\n}\n\nclass Box3 {\npublic:\n    vec3 p0;\n    vec3 p1;\n\n    Box3(): p0(1,1,1), p1(0,0,0) {}\n    Box3(const vec3& a, const vec3& b): p0(a), p1(b) {}\n\n};\n\ninline quat quatFromTwoVectors(const vec3& yy,\n                               const vec3& z) {\n\n    vec3 x = yy.cross(z);\n    vec3 y = z.cross(x);\n\n    mat3 m;\n    m.col(0) = x / x.norm();\n    m.col(1) = y / y.norm();\n    m.col(2) = z / z.norm();\n\n    return quat(m);\n\n}\n\ninline quat quatFromOneVector(const vec3& z) {\n\n    int maxaxis = 0;\n    if (fabs(z[1]) > fabs(z[maxaxis])) { maxaxis = 1; }\n    if (fabs(z[2]) > fabs(z[maxaxis])) { maxaxis = 2; }\n\n    vec3 y = vec3(0, 0, 0);\n    y[(maxaxis + 1) % 3] = 1;\n\n    return quatFromTwoVectors(y, z);\n\n}\n\ninline quat quatFromAxisAngle(const vec3& axis,\n                              double angle) {\n\n    return quat(Eigen::AngleAxisd(angle, axis));\n\n}\n\ninline quat quatFromOmega(const vec3& v) {\n    double l = v.norm();\n    vec3 vn = v / l;\n    return quat(Eigen::AngleAxisd(l, vn));\n}\n\n} // namespace ccdw\n\n#endif\n", "meta": {"hexsha": "25f1cbeb650d1f447d43591adc9b8c5a04e179d9", "size": 4656, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ccd_eigen.hpp", "max_stars_repo_name": "osrf/minimum_distance_plugin", "max_stars_repo_head_hexsha": "042cf0d6068cd35eb6c3f40f4d1ff29de75ae974", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-05-16T18:41:17.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-16T18:41:17.000Z", "max_issues_repo_path": "ccd_eigen.hpp", "max_issues_repo_name": "osrf/minimum_distance_plugin", "max_issues_repo_head_hexsha": "042cf0d6068cd35eb6c3f40f4d1ff29de75ae974", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-05-16T17:51:59.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-16T17:51:59.000Z", "max_forks_repo_path": "ccd_eigen.hpp", "max_forks_repo_name": "osrf/minimum_distance_plugin", "max_forks_repo_head_hexsha": "042cf0d6068cd35eb6c3f40f4d1ff29de75ae974", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-05-16T17:44:28.000Z", "max_forks_repo_forks_event_max_datetime": "2018-05-16T17:44:28.000Z", "avg_line_length": 25.1675675676, "max_line_length": 88, "alphanum_fraction": 0.6357388316, "num_tokens": 1238, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872243177518, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4579784253728255}}
{"text": "#include \"common.h\"\n\n#include \"hexutil/basics/hexgrid.h\"\n\n#define BOOST_TEST_MODULE HexgridTest\n#include <boost/test/included/unit_test.hpp>\n\n\nnamespace hex {\n\nstruct Fixture {\n};\n\nBOOST_FIXTURE_TEST_SUITE(hexgrid_test, Fixture)\n\nvoid check_neighbours(Point point, Point *expected_neighbours) {\n    PointNeighbours all_neighbours = get_neighbours(point);\n    for (int i = 0; i < 6; i++) {\n        Point neighbour = get_neighbour(point, i);\n        BOOST_CHECK_EQUAL(neighbour, expected_neighbours[i]);\n        BOOST_CHECK_EQUAL(all_neighbours[i], expected_neighbours[i]);\n        int dir = get_direction(point, neighbour);\n        BOOST_CHECK_EQUAL(dir, i);\n        int dist = distance_between(point, neighbour);\n        BOOST_CHECK_EQUAL(dist, 1);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(test_neighbours_even) {\n    Point even_point(6,6);\n    Point expected_even_neighbours[] = { Point(6,5), Point(7,5), Point(7,6), Point(6,7), Point(5,6), Point(5,5) };\n    check_neighbours(even_point, expected_even_neighbours);\n}\n\nBOOST_AUTO_TEST_CASE(test_neighbours_odd) {\n    Point odd_point(7,7);\n    Point expected_odd_neighbours[] = { Point(7,6), Point(8,7), Point(8,8), Point(7,8), Point(6,8), Point(6,7) };\n    check_neighbours(odd_point, expected_odd_neighbours);\n}\n\nBOOST_AUTO_TEST_CASE(test_get_circle_even) {\n    Point even_point(6,6);\n    int radius = 3;\n    int expected_num_scanlines = radius*2 + 1;\n    int expected_scanlines[] = { 1, 3, 3, 3, 3, 2, 0 };\n\n    std::vector<int> scanlines = get_circle_scanlines(even_point, radius);\n    BOOST_CHECK_EQUAL(scanlines.size(), expected_num_scanlines);\n    for (int i = 0; i < expected_num_scanlines; i++) {\n        BOOST_CHECK_EQUAL(scanlines[i], expected_scanlines[i]);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(test_get_circle_odd) {\n    Point odd_point(7,7);\n    int radius = 3;\n    int expected_num_scanlines = radius*2 + 1;\n    int expected_scanlines[] = { 0, 2, 3, 3, 3, 3, 1 };\n\n    std::vector<int> scanlines = get_circle_scanlines(odd_point, radius);\n    BOOST_CHECK_EQUAL(scanlines.size(), expected_num_scanlines);\n    for (int i = 0; i < expected_num_scanlines; i++) {\n        BOOST_CHECK_EQUAL(scanlines[i], expected_scanlines[i]);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(test_pixel_to_point) {\n    int x_spacing = 16;\n    int y_spacing = 16;\n    int slope_width = 4;\n    int slope_height = 8;\n    Point point = pixel_to_point(0, 0, x_spacing, y_spacing, slope_width, slope_height);\n    BOOST_CHECK_EQUAL(point, Point(-1, -1));\n    point = pixel_to_point(2, 0, x_spacing, y_spacing, slope_width, slope_height);\n    BOOST_CHECK_EQUAL(point, Point(-1, -1));\n    point = pixel_to_point(4, 0, x_spacing, y_spacing, slope_width, slope_height);\n    BOOST_CHECK_EQUAL(point, Point(0, 0));\n    point = pixel_to_point(11, 0, x_spacing, y_spacing, slope_width, slope_height);\n    BOOST_CHECK_EQUAL(point, Point(0, 0));\n}\n\nBOOST_AUTO_TEST_CASE(test_circle_iterator_zero_radius) {\n    hexgrid_circle circle(Point(7,21), 0);\n    auto iter = circle.begin();\n    BOOST_CHECK_EQUAL(*iter, Point(7, 21));\n    BOOST_CHECK_EQUAL(iter == circle.end(), false);\n    BOOST_CHECK_EQUAL(iter != circle.end(), true);\n    iter++;\n    BOOST_CHECK_EQUAL(iter == circle.end(), true);\n    BOOST_CHECK_EQUAL(iter != circle.end(), false);\n}\n\nBOOST_AUTO_TEST_CASE(test_circle_iterator_big) {\n    hexgrid_circle circle(Point(7,21), 2);\n    std::vector<Point> points;\n    int max = 20;\n    for (auto iter = circle.begin(); iter != circle.end() && max > 0; iter++, max--) {\n        points.push_back(*iter);\n    }\n    std::vector<Point> expected_points = get_circle_points(Point(7,21), 2, 100, 100);\n    BOOST_CHECK_EQUAL(points, expected_points);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n};\n", "meta": {"hexsha": "3407205783ec5ac27f3948a9d559972d9b61c2fa", "size": 3672, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tests/auto/hexgrid_test.cpp", "max_stars_repo_name": "ejrh/hex", "max_stars_repo_head_hexsha": "3c063ce142e6b62fb0f92f71bc94280305b53322", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2015-09-15T13:20:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-07T10:14:57.000Z", "max_issues_repo_path": "src/tests/auto/hexgrid_test.cpp", "max_issues_repo_name": "ejrh/hex", "max_issues_repo_head_hexsha": "3c063ce142e6b62fb0f92f71bc94280305b53322", "max_issues_repo_licenses": ["MIT"], "max_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/auto/hexgrid_test.cpp", "max_forks_repo_name": "ejrh/hex", "max_forks_repo_head_hexsha": "3c063ce142e6b62fb0f92f71bc94280305b53322", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-09-07T00:54:35.000Z", "max_forks_repo_forks_event_max_datetime": "2018-09-07T00:54:35.000Z", "avg_line_length": 34.3177570093, "max_line_length": 114, "alphanum_fraction": 0.6928104575, "num_tokens": 1006, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872243177518, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4579784253728255}}
{"text": "#include <boost/hana.hpp>\n\nusing namespace boost::hana;\n\nint main()\n{\n\tconstexpr auto t1 = make_tuple(int_c<5>, int_c<2>, int_c<3>, int_c<1>, int_c<4>);\n\tconstexpr auto r1 = index_if(t1, equal.to(int_c<3>));\n\tstatic_assert(r1.value().value == 2);\n\n\tconstexpr auto t2 = tuple_c<int, 5, 2, 3, 1, 4>;\n\tconstexpr auto r2 = index_if(t2, equal.to(int_c<6>));\n\tstatic_assert(r2.value_or(-1) == -1);\n}\n", "meta": {"hexsha": "bcc353da7d8577573f80408bb5cff8154341448b", "size": 394, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "03_hana_with_values/main.cpp", "max_stars_repo_name": "BorisSchaeling/boost-meta-programming-2020", "max_stars_repo_head_hexsha": "1bb70e88070953daa4bc19f91f891b43583df06e", "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": "03_hana_with_values/main.cpp", "max_issues_repo_name": "BorisSchaeling/boost-meta-programming-2020", "max_issues_repo_head_hexsha": "1bb70e88070953daa4bc19f91f891b43583df06e", "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": "03_hana_with_values/main.cpp", "max_forks_repo_name": "BorisSchaeling/boost-meta-programming-2020", "max_forks_repo_head_hexsha": "1bb70e88070953daa4bc19f91f891b43583df06e", "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.2666666667, "max_line_length": 82, "alphanum_fraction": 0.6624365482, "num_tokens": 134, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4579784185234984}}
{"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_ACOSD_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_ACOSD_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-trigonometric\n    Function object implementing acosd capabilities\n\n    inverse cosine in degree.\n\n    @par Semantic:\n\n    For every parameter of floating type\n\n    @code\n    auto r = acosd(x);\n    @endcode\n\n    Returns the arc @c r in the interval\n    \\f$[0, 180[\\f$ such that <tt>cosd(r) == x</tt>.\n    If @c x is outside \\f$[-1, 1[\\f$ the result is @ref Nan.\n\n    @see acos, acospi, cosd\n\n  **/\n  Value acosd(Value const & v0);\n} }\n#endif\n\n#include <boost/simd/function/scalar/acosd.hpp>\n#include <boost/simd/function/simd/acosd.hpp>\n\n#endif\n", "meta": {"hexsha": "987af9cbdc21b46058685580672180c2b2b0826f", "size": 1118, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/acosd.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/acosd.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/acosd.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": 23.2916666667, "max_line_length": 100, "alphanum_fraction": 0.5688729875, "num_tokens": 264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.4579784185234983}}
{"text": "// Copyright 2016 Arizona Board of Regents. See README.md and LICENSE for more.\n\n#include <iostream>\n#include <algorithm>\n#include <iterator>\n#include <ctime>\n\n#include <boost/random.hpp>\n#include <boost/generator_iterator.hpp>\n#include <boost/date_time/gregorian/gregorian.hpp>\n#include <boost/date_time/posix_time/posix_time.hpp>\n#include <boost/algorithm/string.hpp>\n\n#include \"nanocube.h\"\n#include \"nanocube_traversals.h\"\n#include \"debug.h\"\n#include \"test_utils.h\"\n\nint atoi(const std::string &s) { return atoi(s.c_str()); }\ndouble atof(const std::string &s) { return atof(s.c_str()); }\n\n// convert lat,lon to quad tree address\nint64_t loc2addr(double lat, double lon, int qtreeLevel)\n{\n    double xd = (lon + M_PI) / (2.0 * M_PI);\n    double yd = (log(tan(M_PI / 4.0 + lat / 2.0)) + M_PI) / (2.0 * M_PI);\n    //cout << lat << \" \" << lon << \" \" << endl;\n    int x = xd * (1 << qtreeLevel), y = yd * (1 << qtreeLevel);\n\n    int64_t z = 0; // z gets the resulting Morton Number.\n\n    for (int i = 0; i < sizeof(x) * 8; i++) // unroll for more speed...\n    {\n        z |= (x & 1U << i) << i | (y & 1U << i) << (i + 1);\n    }\n\n    return z;\n}\n\nint main(int argc, char **argv)\n{\n    using namespace boost::gregorian;\n    using namespace boost::posix_time;\n\n    ifstream is(argv[1]);\n    std::cout << \"Data file: \" << argv[1] << std::endl;\n    string s;\n\n    int qtreeLevel = 16;\n\n    vector<int> schema = {qtreeLevel*2, qtreeLevel*2};\n    // use a quadtree\n    Nanocube<int> nc(schema);\n\n    vector<pair<int64_t,int64_t> > dataarray;\n\n    int i = 0;\n\n    clock_t begin = clock();\n\n    while (std::getline(is, s)) {\n        vector<string> output;\n        boost::split(output,s,boost::is_any_of(\"\\t\"));\n        if (output.size() != 4) {\n            cerr << \"Bad line:\" << s << endl;\n            continue;\n        }\n\n        double ori_lat = atof(output[0]) * M_PI / 180.0;\n        double ori_lon = atof(output[1]) * M_PI / 180.0;\n        double des_lat = atof(output[2]) * M_PI / 180.0;\n        double des_lon = atof(output[3]) * M_PI / 180.0;\n\n        if (ori_lat > 85.0511 || ori_lat < -85.0511 ||\n            des_lat > 85.0511 || des_lat < -85.0511 ){\n            cerr << \"Invalid latitude: \" << ori_lat << \", \" << des_lat;\n            cerr << \" (should be in [-85.0511, 85.0511])\" << endl;\n            continue;\n        }\n\n        int64_t d1 = loc2addr(ori_lat, ori_lon, qtreeLevel);\n        int64_t d2 = loc2addr(des_lat, des_lon, qtreeLevel);\n\n        nc.insert(1, {d1, d2});\n        dataarray.push_back({d1,d2});\n\n        if (++i % 10000 == 0) {\n            //nc.report_size();\n            cout << i << endl;\n        }\n    }\n\n    clock_t end = clock();\n    double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;\n    cout << \"Running time: \" << elapsed_secs << endl;\n\n    //nc.dump_internals(true);\n    //{\n        ////nc.content_compact();\n        //ofstream os(\"flights.nc\");\n        //nc.write_to_binary_stream(os);\n    //}\n\n    test(nc, dataarray, schema);\n}\n", "meta": {"hexsha": "213848fc94602a03facaf6b45060255dd46d0b6a", "size": 2971, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/tests/test_flights.cc", "max_stars_repo_name": "cscheid/nanocube2", "max_stars_repo_head_hexsha": "c544d853e399ac95194e93020c34f570ce596642", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-11-04T17:13:57.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-24T17:50:22.000Z", "max_issues_repo_path": "src/tests/test_flights.cc", "max_issues_repo_name": "cscheid/nanocube2", "max_issues_repo_head_hexsha": "c544d853e399ac95194e93020c34f570ce596642", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tests/test_flights.cc", "max_forks_repo_name": "cscheid/nanocube2", "max_forks_repo_head_hexsha": "c544d853e399ac95194e93020c34f570ce596642", "max_forks_repo_licenses": ["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.0283018868, "max_line_length": 79, "alphanum_fraction": 0.565466173, "num_tokens": 884, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.749087201911703, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4579784116741712}}
{"text": "#include <boost/algorithm/hex.hpp>\n#include <boost/filesystem.hpp>\n#include <boost/program_options.hpp>\n\n#include <nil/crypto3/zk/components/blueprint.hpp>\n#include <nil/crypto3/zk/components/blueprint_variable.hpp>\n\n#include <nil/crypto3/zk/snark/schemes/ppzksnark/r1cs_gg_ppzksnark.hpp>\n#include <nil/crypto3/zk/snark/schemes/ppzksnark/r1cs_gg_ppzksnark/marshalling.hpp>\n\n#include <nil/crypto3/zk/snark/algorithms/generate.hpp>\n#include <nil/crypto3/zk/snark/algorithms/verify.hpp>\n#include <nil/crypto3/zk/snark/algorithms/prove.hpp>\n\n#include <nil/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 \"detail/components.hpp\"\n\ntypedef algebra::curves::bls12<381> curve_type;\ntypedef curve_type::scalar_field_type field_type;\ntypedef field_type::value_type value_type;\ntypedef zk::snark::r1cs_gg_ppzksnark<curve_type> scheme_type;\n\nusing namespace nil::crypto3::zk::components;\nusing namespace nil::crypto3::zk::snark;\n\nboost::filesystem::path PRIMARY_KEY_PATH = \"prov_key\",\n    VERIFICATION_KEY_PATH = \"ver_key\",\n    PROOF_PATH = \"proof\";\n\nstd::vector<std::uint8_t> readfile(boost::filesystem::path path) {\n    boost::filesystem::ifstream stream(path, std::ios::in | std::ios::binary);\n    auto eos = std::istreambuf_iterator<char>();\n    auto buffer = std::vector<uint8_t>(std::istreambuf_iterator<char>(stream), eos);\n    return buffer;\n}\n\nbool generate_keys() {\n    blueprint<field_type> bp;\n    contest::bank_component<field_type> contest_component(bp);\n    contest_component.generate_r1cs_constraints();\n\n    const r1cs_constraint_system<field_type> constraint_system = bp.get_constraint_system();\n\n    scheme_type::keypair_type keypair = generate<scheme_type>(constraint_system);\n\n    std::vector<std::uint8_t> proving_key_byteblob =\n        nil::marshalling::verifier_input_serializer_tvm<scheme_type>::process(keypair.first);\n    std::vector<std::uint8_t> verification_key_byteblob =\n        nil::marshalling::verifier_input_serializer_tvm<scheme_type>::process(keypair.second);\n\n    boost::filesystem::ofstream pk_out(PRIMARY_KEY_PATH);\n    for (const auto &v : proving_key_byteblob) {\n        pk_out << v;\n    }\n    pk_out.close();\n    std::cout << \"prooving key saved to \" << PRIMARY_KEY_PATH << std::endl;\n\n    boost::filesystem::ofstream vk_out(VERIFICATION_KEY_PATH );\n    for (const auto &v : verification_key_byteblob) {\n        vk_out << v;\n    }\n    vk_out.close();\n    std::cout << \"verification key saved to \" << VERIFICATION_KEY_PATH << std::endl;\n\n    return true;\n}\n\n\nbool generate_proof(uint min_salary, uint min_age, uint salary, uint age) {\n    std::vector<std::uint8_t> proving_key_byteblob = readfile(PRIMARY_KEY_PATH);\n    nil::marshalling::status_type provingProcessingStatus = nil::marshalling::status_type::success;\n    typename scheme_type::proving_key_type pk = nil::marshalling::verifier_input_deserializer_tvm<scheme_type>::proving_key_process(\n        proving_key_byteblob.cbegin(),\n        proving_key_byteblob.cend(),\n        provingProcessingStatus);\n\n    blueprint<field_type> bp;\n    contest::bank_component<field_type> contest_component(bp);\n    contest_component.generate_r1cs_constraints();\n    contest_component.generate_r1cs_witness(min_salary, min_age, salary, age);\n\n    std::cout << \"Circuit satisfied: \" << bp.is_satisfied() << std::endl;\n    if (!bp.is_satisfied()) {\n        return false;\n    }\n\n    const scheme_type::proof_type proof = prove<scheme_type>(pk, bp.primary_input(), bp.auxiliary_input());\n\n    std::vector<std::uint8_t> proof_byteblob =\n        nil::marshalling::verifier_input_serializer_tvm<scheme_type>::process(proof);\n\n    std::cout << \"proof is saved to \" << PROOF_PATH << std::endl;\n    boost::filesystem::ofstream proof_out(PROOF_PATH);\n    for (const auto &v : proof_byteblob) {\n        proof_out << v;\n    }\n    proof_out.close();\n\n    return true;\n}\n\n\nbool verify_proof(uint min_salary, uint min_age) {\n    std::vector<std::uint8_t> proof_byteblob = readfile(PROOF_PATH);\n    nil::marshalling::status_type proofProcessingStatus = nil::marshalling::status_type::success;\n    typename scheme_type::proof_type proof = nil::marshalling::verifier_input_deserializer_tvm<scheme_type>::proof_process(\n        proof_byteblob.cbegin(),\n        proof_byteblob.cend(),\n        proofProcessingStatus);\n\n    std::vector<std::uint8_t> verification_key_byteblob = readfile(VERIFICATION_KEY_PATH);\n    nil::marshalling::status_type verificationProcessingStatus = nil::marshalling::status_type::success;\n    typename scheme_type::verification_key_type vk = nil::marshalling::verifier_input_deserializer_tvm<scheme_type>::verification_key_process(\n        verification_key_byteblob.cbegin(),\n        verification_key_byteblob.cend(),\n        verificationProcessingStatus );\n\n    r1cs_primary_input<field_type> input = contest::get_public_input<field_type>(min_salary, min_age);\n    using basic_proof_system = r1cs_gg_ppzksnark<curve_type>;\n    const bool verified = verify<basic_proof_system>(vk, input, proof);\n    std::cout << \"proof verified \" << verified << std::endl;\n\n    return verified;\n}\n\n\nint main(int argc, char *argv[]) {\n    uint salary, age;\n    uint min_salary, min_age;\n\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    options.add_options()\n    (\"help,h\", \"Display help message\")\n    (\"keygen\", \"Generate keys\")\n    (\"proof\", \"Generate proof\")\n    (\"verify\", \"Verify proof\")\n    (\"min-age,x\", boost::program_options::value<uint>(&min_age)->default_value(18))\n    (\"min-salary,y\", boost::program_options::value<uint>(&min_salary)->default_value(1000))\n    (\"age,a\", boost::program_options::value<uint>(&age)->default_value(0))\n    (\"salary,s\", boost::program_options::value<uint>(&salary)->default_value(0));\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    } else if (vm.count(\"keygen\")) {\n        generate_keys();\n    } else if (vm.count(\"proof\")) {\n        generate_proof(min_salary, min_age, salary, age);\n    } else if (vm.count(\"verify\")) {\n        verify_proof(min_salary, min_age);\n    }\n    return 0;\n}\n", "meta": {"hexsha": "c8bbddd0af507e5b4d55a836dc1558a7fdef9aa4", "size": 6744, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bin/cli/src/main.cpp", "max_stars_repo_name": "cnot54/ton-proof-verification-contest", "max_stars_repo_head_hexsha": "fa2edd901aaef729223b75dde54a0bfa427f539e", "max_stars_repo_licenses": ["MIT"], "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": "cnot54/ton-proof-verification-contest", "max_issues_repo_head_hexsha": "fa2edd901aaef729223b75dde54a0bfa427f539e", "max_issues_repo_licenses": ["MIT"], "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": "cnot54/ton-proof-verification-contest", "max_forks_repo_head_hexsha": "fa2edd901aaef729223b75dde54a0bfa427f539e", "max_forks_repo_licenses": ["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.8727272727, "max_line_length": 142, "alphanum_fraction": 0.7258303677, "num_tokens": 1679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511322604134, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.4579645960108535}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   DataGen_AdjointBremsstrahlungCrossSectionEvaluator.cpp\n//! \\author Luke Kersting\n//! \\brief  Adjoint bremsstrahlung cross section 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_AdjointBremsstrahlungCrossSectionEvaluator.hpp\"\n#include \"Utility_GaussKronrodIntegrator.hpp\"\n#include \"Utility_PhysicalConstants.hpp\"\n#include \"Utility_ContractException.hpp\"\n#include \"MonteCarlo_TwoDDistributionHelpers.hpp\"\n\nnamespace DataGen{\n\n// Constructor\nAdjointBremsstrahlungCrossSectionEvaluator::AdjointBremsstrahlungCrossSectionEvaluator(\n    Teuchos::RCP<MonteCarlo::ElectroatomicReaction>& bremsstrahlung_reaction,\n    const BremsstrahlungDistribution& energy_loss_distribution )\n  : d_bremsstrahlung_reaction( bremsstrahlung_reaction ),\n    d_energy_loss_distribution( energy_loss_distribution )\n{\n  // Make sure the data is valid\n  testPrecondition( !d_bremsstrahlung_reaction.is_null() );\n  testPrecondition( d_energy_loss_distribution.size() > 0 );\n}\n\n// Evaluate the differential adjoint bremsstrahlung cross section (dc/dx)\ndouble AdjointBremsstrahlungCrossSectionEvaluator::evaluateDifferentialCrossSection(\n\t  const double incoming_energy, \n          const double outgoing_energy ) const\n{\n  // Make sure the energies are valid\n  testPrecondition( incoming_energy > 0.0 );\n  testPrecondition( outgoing_energy > 0.0 );\n\n  // Evaluate the forward cross section at the incoming energy\n  double forward_cs = d_bremsstrahlung_reaction->getCrossSection( incoming_energy );\n\n  // Evaluate the energy loss distribution at a given incoming and outgoing energy\n  double forward_pdf = MonteCarlo::evaluateTwoDDistributionCorrelatedPDF( \n                                     incoming_energy,\n                                     outgoing_energy,\n                                     d_energy_loss_distribution );\n\n  return forward_cs*forward_pdf;\n}\n\n// Return the cross section value at a given energy\ndouble AdjointBremsstrahlungCrossSectionEvaluator::evaluateCrossSection( \n                               const double energy, \n\t\t\t       const double precision ) const\n{\n  // Make sure the energies are valid\n  testPrecondition( energy > 0.0 );\n\n  double cross_section = 0.0;\n\n  // Create boost rapper function for the adjoint Bremsstahlung differential cross section\n  boost::function<double (double x)> diff_adjoint_brem_wrapper = \n    boost::bind<double>( &AdjointBremsstrahlungCrossSectionEvaluator::evaluateDifferentialCrossSection,\n                         boost::cref( *this ),\n                         _1,\n                         energy );\n\n    double abs_error;\n    \n    Utility::GaussKronrodIntegrator integrator( precision );\n\n    integrator.integrateAdaptively<15>(\n\t\t\t\t\tdiff_adjoint_brem_wrapper,\n\t\t\t\t\td_energy_loss_distribution.front().first,\n\t\t\t\t\td_energy_loss_distribution.back().first,\n\t\t\t\t\tcross_section,\n\t\t\t\t\tabs_error );\n}\n\n} // end DataGen namespace\n\n//---------------------------------------------------------------------------//\n// end DataGen_AdjointBremsstrahlungCrossSectionEvaluator.cpp\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "145265b72fbd32c44b664104c2c59ec57de9885b", "size": 3389, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "packages/data_gen/electron_photon/src/DataGen_AdjointBremsstrahlungCrossSectionEvaluator.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_AdjointBremsstrahlungCrossSectionEvaluator.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_AdjointBremsstrahlungCrossSectionEvaluator.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": 36.8369565217, "max_line_length": 103, "alphanum_fraction": 0.6656830924, "num_tokens": 696, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619959279793, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.4579587886020616}}
{"text": "//\n// Created by Alex Beccaro on 18/01/18.\n//\n\n#define BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n#include \"../../src/problems/1-50/24/problem24.hpp\"\n\nBOOST_AUTO_TEST_SUITE( Problem24 )\n\n    BOOST_AUTO_TEST_CASE( Example ) {\n        std::vector<uint32_t> base = {0,1,2};\n        std::vector<uint32_t> sol = base;\n        for (uint32_t i = 1; i <= 6; i++) {\n            std::vector<uint32_t> res = problems::problem24::solve(base, i);\n            BOOST_CHECK_EQUAL_COLLECTIONS(res.begin(), res.end(),sol.begin(), sol.end());\n            next_permutation(sol.begin(), sol.end());\n        }\n    }\n\n    BOOST_AUTO_TEST_CASE( Solution ) {\n        auto res = problems::problem24::solve();\n        std::vector<uint32_t> sol = {2,7,8,3,9,1,5,4,6,0};\n        BOOST_CHECK_EQUAL_COLLECTIONS(res.begin(), res.end(), sol.begin(), sol.end());\n    }\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "d91ae76ea687170b9347b46754cf11ea988e3cb1", "size": 876, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/1-50/test_problem24.cpp", "max_stars_repo_name": "abeccaro/project-euler", "max_stars_repo_head_hexsha": "c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T10:17:15.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-25T10:17:15.000Z", "max_issues_repo_path": "tests/1-50/test_problem24.cpp", "max_issues_repo_name": "abeccaro/project-euler", "max_issues_repo_head_hexsha": "c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3", "max_issues_repo_licenses": ["MIT"], "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/1-50/test_problem24.cpp", "max_forks_repo_name": "abeccaro/project-euler", "max_forks_repo_head_hexsha": "c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3", "max_forks_repo_licenses": ["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.4444444444, "max_line_length": 89, "alphanum_fraction": 0.6164383562, "num_tokens": 240, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947425132315, "lm_q2_score": 0.6992544335934766, "lm_q1q2_score": 0.45793805223943546}}
{"text": "#include \"alpha_shapes.hpp\"\n#include <boost/lexical_cast.hpp>\n#include <iostream>\n#include <fstream>\n\ntypedef float f_t;\n\nint main(int argc, char* argv[]){\n\tif(argc != 3){\n\t\tstd::cout << \"usage: \" << argv[0] << \" <alpha> <coord/radii file>\" << std::endl;\n\t\treturn 1;\n\t}\n\tf_t alpha = boost::lexical_cast<f_t>(argv[1]);\n\tconst char* infilename = argv[2];\n\n\tstd::vector<f_t> points, radii;\n\tf_t x, y, z, r;\n\tstd::ifstream fs;\n\tfs.open(infilename, std::ifstream::in);\n\twhile(fs >> x >> y >> z >> r){\n\t\tpoints.push_back(x);\n\t\tpoints.push_back(y);\n\t\tpoints.push_back(z);\n\t\tradii.push_back(r);\n\t}\n\tsize_t numPoints = radii.size();\n\tstd::cout << \"number of points: \" << numPoints << std::endl;\n\n\tunsigned int numEdges, numTriangles, numTetrahedra;\n\tunsigned int* edges, * triangles, * tetrahedra, * t;\n\tbusv::alpha_shapes<f_t, unsigned int>(\n\t\tnumPoints, alpha, \n\t\t&(points[0]), &(radii[0]), \n\t\t&numEdges, &edges,\n\t\t&numTriangles, &triangles,\n\t\t&numTetrahedra, &tetrahedra\n\t);\n\t\n\tstd::cout << \"tetrahedra\" << std::endl;\n\tt = tetrahedra;\n\tfor(unsigned int i = 0; i<numTetrahedra; ++i){\n\t\tstd::cout << \"\\t\" << t[0] << \" \" << t[1] << \" \" << t[2] << \" \" << t[3] << std::endl;\n\t\tt += 4;\n\t}\n\tstd::cout << std::endl;\n\n\tstd::cout << \"triangles\" << std::endl;\n\tt = triangles;\n\tfor(unsigned int i = 0; i<numTriangles; ++i){\n\t\tstd::cout << \"\\t\" << t[0] << \" \" << t[1] << \" \" << t[2] << std::endl;\n\t\tt += 3;\n\t}\n\tstd::cout << std::endl;\n\n\tstd::cout << \"edges\" << std::endl;\n\tt = edges;\n\tfor(unsigned int i = 0; i<numEdges; ++i){\n\t\tstd::cout << \"\\t\" << t[0] << \" \" << t[1] << std::endl;\n\t\tt += 2;\n\t}\n\tstd::cout << std::endl;\n\n\treturn 0;\n}\n\n", "meta": {"hexsha": "9bf4b2fe72ee8387860a22fbd49ad990b4f88c45", "size": 1618, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/alpha_shapes/pointComplex.cpp", "max_stars_repo_name": "academicRobot/mmstructlib", "max_stars_repo_head_hexsha": "76949620c9e9ca26faf10ff1a21c6fda1a564f5c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/alpha_shapes/pointComplex.cpp", "max_issues_repo_name": "academicRobot/mmstructlib", "max_issues_repo_head_hexsha": "76949620c9e9ca26faf10ff1a21c6fda1a564f5c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/alpha_shapes/pointComplex.cpp", "max_forks_repo_name": "academicRobot/mmstructlib", "max_forks_repo_head_hexsha": "76949620c9e9ca26faf10ff1a21c6fda1a564f5c", "max_forks_repo_licenses": ["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.5151515152, "max_line_length": 86, "alphanum_fraction": 0.5735475896, "num_tokens": 569, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.4579380440305144}}
{"text": "/**\n * @file /sophus_ros_conversions/src/lib/geometry.cpp\n */\n/*****************************************************************************\n** Includes\n*****************************************************************************/\n\n#include <Eigen/Geometry>\n#include \"../../include/sophus_ros_conversions/eigen.hpp\"\n#include \"../../include/sophus_ros_conversions/geometry.hpp\"\n\n/*****************************************************************************\n** Namespaces\n*****************************************************************************/\n\nnamespace sophus_ros_conversions {\n\n/*****************************************************************************\n** Implementation\n*****************************************************************************/\n\nvoid poseMsgToSophus(const geometry_msgs::Pose &pose, Sophus::SE3f &se3)\n{\n  Eigen::Quaternion<Sophus::SE3f::Scalar> orientation;\n  Sophus::SE3f::Point translation;\n  pointMsgToEigen(pose.position, translation);\n  quaternionMsgToEigen(pose.orientation, orientation);\n  se3 = Sophus::SE3f(orientation, translation);  // TODO faster way to set this than reconstructing\n}\n\ngeometry_msgs::Pose sophusToPoseMsg(const Sophus::SE3f& s) {\n  geometry_msgs::Pose pose;\n  Eigen::Vector3f translation = s.translation();\n  pose.position = eigenToPointMsg(translation);\n  Eigen::Quaternionf quaternion = s.unit_quaternion();\n  pose.orientation = eigenToQuaternionMsg(quaternion);\n  return pose;\n}\n\n// Sophus uses SE3f::Point as the translation type in the constructors of SE3f types.\nvoid vector3MsgToSophus(const geometry_msgs::Vector3 &v, Sophus::SE3f::Point &translation)\n{\n  translation << v.x, v.y, v.z;\n}\n\n\nvoid transformMsgToSophus(const geometry_msgs::Transform &transform, Sophus::SE3f &se3)\n{\n  Sophus::SE3f::Point translation;\n  Eigen::Quaternion<Sophus::SE3f::Scalar> orientation;\n  vector3MsgToSophus(transform.translation, translation);\n  quaternionMsgToEigen(transform.rotation, orientation);\n  se3 = Sophus::SE3f(orientation, translation);  // TODO faster way to set this than reconstructing\n}\n\nSophus::SE3f transformMsgToSophus(const geometry_msgs::Transform &transform)\n{\n  Sophus::SE3f T;\n  transformMsgToSophus(transform, T);\n  return T;\n}\n\ngeometry_msgs::Transform sophusToTransformMsg(const Sophus::SE3f& se3) {\n  geometry_msgs::Transform msg;\n  msg.translation.x = se3.translation().x();\n  msg.translation.y = se3.translation().y();\n  msg.translation.z = se3.translation().z();\n  msg.rotation.x = se3.unit_quaternion().x();\n  msg.rotation.y = se3.unit_quaternion().y();\n  msg.rotation.z = se3.unit_quaternion().z();\n  msg.rotation.w = se3.unit_quaternion().w();\n  return msg;\n}\n\n/*****************************************************************************\n ** Trailers\n *****************************************************************************/\n\n} // namespace sophus_ros_conversions\n", "meta": {"hexsha": "a63a08005bf93d528a63390a2e4505f8c5f66d0e", "size": 2864, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sophus_ros_conversions/src/lib/geometry.cpp", "max_stars_repo_name": "mortaas/sophus_ros_toolkit", "max_stars_repo_head_hexsha": "d803a2b9639033d7fc87a9454ae7824a5c1ef653", "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": "sophus_ros_conversions/src/lib/geometry.cpp", "max_issues_repo_name": "mortaas/sophus_ros_toolkit", "max_issues_repo_head_hexsha": "d803a2b9639033d7fc87a9454ae7824a5c1ef653", "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": "sophus_ros_conversions/src/lib/geometry.cpp", "max_forks_repo_name": "mortaas/sophus_ros_toolkit", "max_forks_repo_head_hexsha": "d803a2b9639033d7fc87a9454ae7824a5c1ef653", "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.8, "max_line_length": 99, "alphanum_fraction": 0.5844972067, "num_tokens": 597, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544335934766, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.45793804281970624}}
{"text": "\n#define EIGEN_DONT_PARALLELIZE\n#ifndef _MSC_VER\n#include \"update_ops_cpp.hpp\"\nextern \"C\" {\n#include \"utility.h\"\n#include \"update_ops.h\"\n}\n#else\n#include \"update_ops_cpp.hpp\"\n#include \"update_ops.h\"\n#include \"utility.h\"\n#endif\n#include <Eigen/Core>\n\nvoid double_qubit_dense_matrix_gate(UINT target_qubit_index1, UINT target_qubit_index2, const CTYPE matrix[16], CTYPE *state, ITYPE dim) {\n\tdouble_qubit_dense_matrix_gate_c(target_qubit_index1, target_qubit_index2, matrix, state, dim);\n}\n\nvoid double_qubit_dense_matrix_gate(UINT target_qubit_index1, UINT target_qubit_index2, const Eigen::Matrix4cd& eigen_matrix, CTYPE *state, ITYPE dim) {\n\tdouble_qubit_dense_matrix_gate_eigen(target_qubit_index1, target_qubit_index2, eigen_matrix, state, dim);\n}\n\nvoid double_qubit_dense_matrix_gate_eigen(UINT target_qubit_index1, UINT target_qubit_index2, const Eigen::Matrix4cd& eigen_matrix, CTYPE *state, ITYPE dim) {\n\t// target mask\n\n\tconst UINT min_qubit_index = get_min_ui(target_qubit_index1, target_qubit_index2);\n\tconst UINT max_qubit_index = get_max_ui(target_qubit_index1, target_qubit_index2);\n\tconst ITYPE min_qubit_mask = 1ULL << min_qubit_index;\n\tconst ITYPE max_qubit_mask = 1ULL << (max_qubit_index - 1);\n\tconst ITYPE low_mask = min_qubit_mask - 1;\n\tconst ITYPE mid_mask = (max_qubit_mask - 1) ^ low_mask;\n\tconst ITYPE high_mask = ~(max_qubit_mask - 1);\n\n\tconst ITYPE target_mask1 = 1ULL << target_qubit_index1;\n\tconst ITYPE target_mask2 = 1ULL << target_qubit_index2;\n\tstd::complex<double>* eigen_state = reinterpret_cast<std::complex<double>*>(state);\n\n\t// loop variables\n\tconst ITYPE loop_dim = dim / 4;\n\tITYPE state_index;\n\n\tfor (state_index = 0; state_index < loop_dim; ++state_index) {\n\t\t// create index\n\t\tITYPE basis_0 = (state_index&low_mask)\n\t\t\t+ ((state_index&mid_mask) << 1)\n\t\t\t+ ((state_index&high_mask) << 2);\n\n\t\t// gather index\n\t\tITYPE basis_1 = basis_0 + target_mask1;\n\t\tITYPE basis_2 = basis_0 + target_mask2;\n\t\tITYPE basis_3 = basis_1 + target_mask2;\n\n\t\t// fetch values\n\t\tEigen::Vector4cd vec(state[basis_0], state[basis_1], state[basis_2], state[basis_3]);\n\t\tvec = eigen_matrix * vec;\n\t\teigen_state[basis_0] = vec[0];\n\t\teigen_state[basis_1] = vec[1];\n\t\teigen_state[basis_2] = vec[2];\n\t\teigen_state[basis_3] = vec[3];\n\t}\n}\n", "meta": {"hexsha": "0ab221fa83c7e8da7284a3372856c95c0a76aa93", "size": 2247, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/csim/update_ops_matrix_dense_double_eigen.cpp", "max_stars_repo_name": "kamakiri01/qulacs", "max_stars_repo_head_hexsha": "1e3e6ac26390abdfe5abe7f4d52349bcfd68e20c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 260.0, "max_stars_repo_stars_event_min_datetime": "2018-10-13T15:58:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T11:03:58.000Z", "max_issues_repo_path": "src/csim/update_ops_matrix_dense_double_eigen.cpp", "max_issues_repo_name": "kamakiri01/qulacs", "max_issues_repo_head_hexsha": "1e3e6ac26390abdfe5abe7f4d52349bcfd68e20c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 182.0, "max_issues_repo_issues_event_min_datetime": "2018-10-14T02:29:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-06T20:23:18.000Z", "max_forks_repo_path": "src/csim/update_ops_matrix_dense_double_eigen.cpp", "max_forks_repo_name": "kamakiri01/qulacs", "max_forks_repo_head_hexsha": "1e3e6ac26390abdfe5abe7f4d52349bcfd68e20c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 88.0, "max_forks_repo_forks_event_min_datetime": "2018-10-10T03:46:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-27T21:56:05.000Z", "avg_line_length": 35.6666666667, "max_line_length": 158, "alphanum_fraction": 0.7627948376, "num_tokens": 679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587586, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.45793803461078547}}
{"text": "#include \"sv/util/eigen.h\"\n\n#include <benchmark/benchmark.h>\n#include <glog/logging.h>\n#include <gtest/gtest.h>\n\n#include <Eigen/Cholesky>\n#include <Eigen/Geometry>\n\nnamespace sv {\nnamespace {\n\nnamespace bm = benchmark;\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\n\n/// @brief Invert PSD matrix, taken from ceres\ntemplate <int N>\nvoid InvertPSDMatrix(const MatrixMNd<N, N>& m, MatrixXdRef m_inv) {\n  const auto size = m.rows();\n\n  // If the matrix can be assumed to be full rank, then if it is small\n  // (< 5) and fixed size, use Eigen's optimized inverse()\n  // implementation.\n  //\n  // https://eigen.tuxfamily.org/dox/group__TutorialLinearAlgebra.html#title3\n  if constexpr (0 < N && N < 5) {\n    m_inv = m.inverse();\n  }\n  m_inv = m.template selfadjointView<Eigen::Upper>().llt().solve(\n      MatrixMNd<N, N>::Identity(size, size));\n}\n\nTEST(EigenTest, TestSafeCwiseInverse) {\n  VectorXd x0 = VectorXd::Zero(4);\n  x0(0) = 1;\n  x0(2) = 1;\n  VectorXd x1 = x0;\n\n  SafeCwiseInverse(x1);\n  EXPECT_EQ(x1, x0);\n}\n\nTEST(EigenTest, TestStableRotateBlockUpperLeftSize1) {\n  Eigen::Matrix3d H;\n  // clang-format off\n  H << 1, 2, 3,\n       4, 5, 6,\n       7, 8, 9;\n  // clang-format on\n  Eigen::Vector3d b;\n  b << 1, 2, 3;\n\n  StableRotateBlockTopLeft(H, b, /*ind*/ 2, /*size*/ 1);\n\n  Eigen::Matrix3d H1;\n  // clang-format off\n  H1 << 9, 7, 8,\n        3, 1, 2,\n        6, 4, 5;\n  // clang-format on\n  EXPECT_EQ(H, H1);\n  EXPECT_EQ(b, Eigen::Vector3d(3, 1, 2));\n}\n\nTEST(EigenTest, TestStableRotateBlockUpperLeftSize2) {\n  // 0, 1, 2,\n  // 3, 4, 5,\n  // 6, 7, 8\n\n  Eigen::Matrix<double, 6, 6> H;\n  Eigen::Matrix<double, 6, 1> b;\n  int k = 0;\n  for (int i = 0; i < 3; ++i) {\n    b.segment<2>(i * 2).setConstant(i);\n    for (int j = 0; j < 3; ++j) {\n      H.block<2, 2>(i * 2, j * 2).setConstant(k);\n      ++k;\n    }\n  }\n\n  LOG(INFO) << \"\\n\" << H;\n  LOG(INFO) << \"\\n\" << b.transpose();\n\n  StableRotateBlockTopLeft(H, b, 2, 2);\n\n  LOG(INFO) << \"\\n\" << H;\n  LOG(INFO) << \"\\n\" << b.transpose();\n\n  const auto H00 = H.topLeftCorner<2, 2>().eval();\n  EXPECT_EQ(H00, Eigen::Matrix2d::Constant(8));\n\n  const auto b0 = b.head<2>().eval();\n  EXPECT_EQ(b0, Eigen::Vector2d::Constant(2));\n}\n\nTEST(EigenTest, TestStableRotateBlockUpperLeft) {\n  using Matrix6d = MatrixMNd<6, 6>;\n  using Vector6d = MatrixMNd<6, 1>;\n  MatrixXd A = MatrixXd::Random(6, 100);\n  Matrix6d H = A * A.transpose();\n\n  Vector6d x;\n  x << 1, 2, 3, 4, 5, 6;\n\n  Vector6d b = H * x;\n  Vector6d x0 = H.selfadjointView<Eigen::Lower>().llt().solve(b);\n  EXPECT_EQ(x.isApprox(x0), true);\n\n  // Now we rotate\n  StableRotateBlockTopLeft(H, b, 1, 2);\n  Vector6d x1 = H.selfadjointView<Eigen::Lower>().llt().solve(b);\n  LOG(INFO) << x1.transpose();\n}\n\nTEST(EigenTest, TestFillLowerTriangular) {\n  Eigen::Matrix3d M;\n  // clang-format off\n  M << 1, 2, 3,\n       4, 5, 6,\n       7, 8, 9;\n  // clang-format on\n  M = M.triangularView<Eigen::Upper>();\n\n  Eigen::Matrix3d Mu;\n  // clang-format off\n  Mu << 1, 2, 3,\n        0, 5, 6,\n        0, 0, 9;\n  // clang-format on\n  EXPECT_EQ(M, Mu);\n\n  Eigen::Matrix3d M0;\n  // clang-format off\n  M0 << 1, 2, 3,\n        2, 5, 6,\n        3, 6, 9;\n  // clang-format on\n\n  FillLowerTriangular(M);\n  EXPECT_EQ(M, M0);\n}\n\nTEST(EigenTest, TestFillUpperTriangular) {\n  Eigen::Matrix3d M;\n  // clang-format off\n  M << 1, 2, 3,\n       4, 5, 6,\n       7, 8, 9;\n  // clang-format on\n  M = M.triangularView<Eigen::Lower>();\n\n  Eigen::Matrix3d Ml;\n  // clang-format off\n  Ml << 1, 0, 0,\n        4, 5, 0,\n        7, 8, 9;\n  // clang-format on\n  EXPECT_EQ(M, Ml);\n\n  Eigen::Matrix3d M0;\n  // clang-format off\n  M0 << 1, 4, 7,\n        4, 5, 8,\n        7, 8, 9;\n  // clang-format on\n\n  FillUpperTriangular(M);\n  EXPECT_EQ(M, M0);\n}\n\nTEST(EigenTest, TestMakeSymmetric) {\n  MatrixXd A = MatrixXd::Random(5, 5);\n  MakeSymmetric(A);\n  CHECK_EQ(A, A.transpose()) << \"\\n\" << A;\n}\n\nTEST(MargTest, TestMargTopLeftBlock) {\n  MatrixXd Hsc = MatrixXd::Zero(4, 4);\n  Hsc.topLeftCorner<2, 2>().setIdentity();\n  Hsc.topRightCorner<2, 2>().setOnes();\n  Hsc.bottomLeftCorner<2, 2>().setOnes();\n  Hsc.bottomRightCorner<2, 2>().setIdentity();\n\n  VectorXd bsc = VectorXd::Ones(4);\n  MatrixXd Hpr = MatrixXd::Zero(2, 2);\n  VectorXd bpr = VectorXd::Zero(2);\n\n  MargTopLeftBlock(Hsc, bsc, Hpr, bpr, 2);\n\n  MatrixXd Hpr0(2, 2);\n  Hpr0 << -1, -2, -2, -1;\n  VectorXd bpr0(2);\n  bpr0 << -1, -1;\n  EXPECT_EQ(Hpr, Hpr0);\n  EXPECT_EQ(bpr, bpr0);\n}\n\nTEST(MargTest, TestMargTopLeftBlock2) {\n  MatrixXd A = MatrixXd::Random(10, 40);\n  MatrixXd Hsc = A * A.transpose();\n  MakeSymmetric(Hsc);\n  VectorXd bsc = VectorXd::Ones(10);\n\n  MatrixXd Hpr(5, 5);\n  VectorXd bpr(5);\n\n  MargTopLeftBlock(Hsc, bsc, Hpr, bpr, 5);\n  EXPECT_EQ(Hpr, Hpr.transpose()) << \"\\n\" << Hpr;\n  EXPECT_EQ(Hpr.isApprox(Hpr.transpose()), true) << \"\\n\" << Hpr;\n}\n\n/// ============================================================================\nvoid BM_CwiseInverse(bm::State& state) {\n  Eigen::VectorXd v(state.range(0));\n  v.setOnes();\n\n  for (auto _ : state) {\n    v = v.cwiseInverse();\n    bm::DoNotOptimize(v);\n  }\n}\nBENCHMARK(BM_CwiseInverse)->Arg(1024)->Arg(2048)->Arg(4096);\n\nvoid BM_SafeCwiseInverse(bm::State& state) {\n  Eigen::VectorXd v(state.range(0));\n  v.setZero();\n  for (int i = 0; i < v.size(); i += 2) {\n    v[i] = 1;\n  }\n\n  for (auto _ : state) {\n    SafeCwiseInverse(v);\n    bm::DoNotOptimize(v);\n  }\n}\nBENCHMARK(BM_SafeCwiseInverse)->Arg(1024)->Arg(2048)->Arg(4096);\n\n/// ============================================================================\nvoid BM_InvertPSDEigen(bm::State& state) {\n  const auto n = state.range(0);\n  Eigen::MatrixXd m(n, n);\n  Eigen::MatrixXd m_inv(n, n);\n  m.setIdentity();\n\n  for (auto _ : state) {\n    m_inv = m.inverse();\n    bm::DoNotOptimize(m_inv);\n  }\n}\nBENCHMARK(BM_InvertPSDEigen)->Arg(4)->Arg(8)->Arg(16)->Arg(32);\n\nvoid BM_InvertPSDCeres(bm::State& state) {\n  const auto n = state.range(0);\n  Eigen::MatrixXd m(n, n);\n  Eigen::MatrixXd m_inv(n, n);\n  m.setIdentity();\n\n  for (auto _ : state) {\n    InvertPSDMatrix(m, m_inv);\n    bm::DoNotOptimize(m_inv);\n  }\n}\nBENCHMARK(BM_InvertPSDCeres)->Arg(4)->Arg(8)->Arg(16)->Arg(32);\n\n}  // namespace\n}  // namespace sv\n", "meta": {"hexsha": "025b04073cd8bf8d29d633fb6b8cbd3c5e9730a5", "size": 6113, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sv/util/eigen_test.cpp", "max_stars_repo_name": "versatran01/dsol", "max_stars_repo_head_hexsha": "1c390f10f55fed0d0ef62b0f18e9003bd82c3876", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 52.0, "max_stars_repo_stars_event_min_datetime": "2022-03-17T02:03:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T06:11:52.000Z", "max_issues_repo_path": "sv/util/eigen_test.cpp", "max_issues_repo_name": "versatran01/dsol", "max_issues_repo_head_hexsha": "1c390f10f55fed0d0ef62b0f18e9003bd82c3876", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sv/util/eigen_test.cpp", "max_forks_repo_name": "versatran01/dsol", "max_forks_repo_head_hexsha": "1c390f10f55fed0d0ef62b0f18e9003bd82c3876", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2022-03-17T06:13:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T09:15:58.000Z", "avg_line_length": 22.8097014925, "max_line_length": 80, "alphanum_fraction": 0.5882545395, "num_tokens": 2229, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587586, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.45793803461078547}}
{"text": "// date_time_gregorian.cpp\n//\n#include <iostream>\n#include <string>\n\n#include <boost/date_time/gregorian/gregorian.hpp>\n\nint main(int argc, char* argv[])\n{\n    namespace greg = boost::gregorian;\n\n    greg::date d(2015, 4, 1);\n    std::cout << d.year() << ' '\n              << d.month() << ' '\n              << d.day() << ' '\n              << d.day_of_week() << '\\n';\n    greg::date d1 = d + greg::date_duration(30);\n    greg::date_period dp(d, d1);\n    std::cout << std::boolalpha << dp.contains(greg::from_simple_string(\"2015-04-25\")) << '\\n';\n\n    greg::date today = greg::day_clock::local_day();\n    greg::date two_days_later = today + greg::days(2);\n    greg::day_iterator it(today);\n    while (*it != two_days_later)\n        std::cout << *(++it) << '\\n';\n}\n", "meta": {"hexsha": "fd6c9ec67e6f98ad3a7cb2e70b928140f06a0c40", "size": 762, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/date_time_gregorian.cpp", "max_stars_repo_name": "uwydoc/the-practices", "max_stars_repo_head_hexsha": "61ea1d868017ac88fddf6c0e726f0e9adde3f80e", "max_stars_repo_licenses": ["MIT"], "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/date_time_gregorian.cpp", "max_issues_repo_name": "uwydoc/the-practices", "max_issues_repo_head_hexsha": "61ea1d868017ac88fddf6c0e726f0e9adde3f80e", "max_issues_repo_licenses": ["MIT"], "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/date_time_gregorian.cpp", "max_forks_repo_name": "uwydoc/the-practices", "max_forks_repo_head_hexsha": "61ea1d868017ac88fddf6c0e726f0e9adde3f80e", "max_forks_repo_licenses": ["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.2222222222, "max_line_length": 95, "alphanum_fraction": 0.5590551181, "num_tokens": 232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.45793803461078536}}
{"text": "//  Copyright John Maddock 2006.\r\n//  Use, modification and distribution are subject to the\r\n//  Boost Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#define BOOST_MATH_ASSERT_UNDEFINED_POLICY false\r\n\r\n#include <boost/math/distributions.hpp>\r\n#include <boost/math/concepts/distributions.hpp>\r\n\r\n\r\ntemplate <class RealType>\r\nvoid instantiate(RealType)\r\n{\r\n   using namespace boost;\r\n   using namespace boost::math;\r\n   using namespace boost::math::concepts;\r\n\r\n   function_requires<DistributionConcept<normal_distribution<RealType> > >();\r\n   function_requires<DistributionConcept<beta_distribution<RealType> > >();\r\n   function_requires<DistributionConcept<binomial_distribution<RealType> > >();\r\n   function_requires<DistributionConcept<cauchy_distribution<RealType> > >();\r\n   function_requires<DistributionConcept<bernoulli_distribution<RealType> > >();\r\n   function_requires<DistributionConcept<chi_squared_distribution<RealType> > >();\r\n   function_requires<DistributionConcept<exponential_distribution<RealType> > >();\r\n   function_requires<DistributionConcept<extreme_value_distribution<RealType> > >();\r\n   function_requires<DistributionConcept<fisher_f_distribution<RealType> > >();\r\n   function_requires<DistributionConcept<gamma_distribution<RealType> > >();\r\n   function_requires<DistributionConcept<students_t_distribution<RealType> > >();\r\n   function_requires<DistributionConcept<pareto_distribution<RealType> > >();\r\n   function_requires<DistributionConcept<poisson_distribution<RealType> > >();\r\n   function_requires<DistributionConcept<rayleigh_distribution<RealType> > >();\r\n   function_requires<DistributionConcept<weibull_distribution<RealType> > >();\r\n   function_requires<DistributionConcept<lognormal_distribution<RealType> > >();\r\n   function_requires<DistributionConcept<triangular_distribution<RealType> > >();\r\n   function_requires<DistributionConcept<uniform_distribution<RealType> > >();\r\n   function_requires<DistributionConcept<negative_binomial_distribution<RealType> > >();\r\n   function_requires<DistributionConcept<non_central_chi_squared_distribution<RealType> > >();\r\n}\r\n\r\n\r\nint main()\r\n{\r\n   instantiate(float(0));\r\n   instantiate(double(0));\r\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\r\n   instantiate((long double)(0));\r\n#endif\r\n}\r\n\r\n", "meta": {"hexsha": "708dd550257524a0b7be6d1dad293c347deed40b", "size": 2360, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/test/compile_test/distribution_concept_check.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/math/test/compile_test/distribution_concept_check.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/math/test/compile_test/distribution_concept_check.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": 46.2745098039, "max_line_length": 95, "alphanum_fraction": 0.7805084746, "num_tokens": 485, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544085240402, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.45793803111172887}}
{"text": "#include <string>\n#include <sstream>\n#include <iostream>\n#include <map>\n#include <regex>\n#include <fstream>\n#include <boost/algorithm/string.hpp>\n\n#include \"../common.hpp\"\n\nusing namespace std;\n\nmap<int, long> mem;\n\nlong dfs(const vector<int> & adapters, int root) {\n    assert(root >= 0 && root < adapters.size());\n\n    if (root == adapters.size() - 1) {\n        return 1;\n    }\n\n    long counts = 0;\n    for (int i = root + 1; i < adapters.size(); i++) {\n        // Gone too far \n        if (adapters[root] + 3 < adapters[i]) {\n            break;\n        }\n\n        if (mem.find(adapters[i]) != mem.end()) {\n            counts += mem[adapters[i]];\n        } else {\n            counts += dfs(adapters, i);\n        }\n    }\n    return mem[adapters[root]] = counts;\n}\n\nint main() {\n    ifstream file (\"2020/10.txt\");\n    if (!file.is_open()) {\n        cout << \"Failed to open file: \" << strerror(errno) << endl;\n        return -1;\n    }\n\n    int answer1 = 0;\n    long answer2 = 0;\n\n    vector<int> adapters;\n    string line; \n    while (getline(file, line, '\\n')) {\n        boost::trim(line);\n        if (line == \"\") {\n            continue;\n        }\n\n        adapters.push_back(stoi(line));\n    }\n\n    adapters.push_back(0);\n    sort(adapters.begin(), adapters.end());\n    adapters.push_back(adapters[adapters.size() - 1] + 3);\n\n    map<int, int> diffs;\n    for (int i = 1; i < adapters.size(); i++) {\n        int diff = adapters[i] - adapters[i-1];\n\n        diffs[diff]++;\n    }\n\n    answer1 = diffs[1] * diffs[3];\n    answer2 = dfs(adapters, 0);\n\n    cout << \"Answer 10.1: \" << answer1 << endl;\n    cout << \"Answer 10.2: \" << answer2 << endl;\n\n    file.close();\n}", "meta": {"hexsha": "dfef14b9d5f0e33c8d82a3493270f0a21b0b090e", "size": 1664, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "2020/10.cpp", "max_stars_repo_name": "bramp/aoc", "max_stars_repo_head_hexsha": "e6e2bf343786e58b3e0513dc88858e54c06f1cf6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2020/10.cpp", "max_issues_repo_name": "bramp/aoc", "max_issues_repo_head_hexsha": "e6e2bf343786e58b3e0513dc88858e54c06f1cf6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2020/10.cpp", "max_forks_repo_name": "bramp/aoc", "max_forks_repo_head_hexsha": "e6e2bf343786e58b3e0513dc88858e54c06f1cf6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.6103896104, "max_line_length": 67, "alphanum_fraction": 0.5222355769, "num_tokens": 453, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.6992544085240401, "lm_q1q2_score": 0.4579380264018644}}
{"text": "//  (C) Copyright John Maddock 2005.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef NTL_STD_CXX\n#  define NTL_STD_CXX\n#endif\n\n#include <NTL/RR.h>\n#include <iostream>\n#include <iomanip>\n\nint main()\n{\n   NTL::RR r, root_two;\n   r.SetPrecision(256);\n   root_two.SetPrecision(256);\n   r = 1.0;\n   root_two = 2.0;\n   root_two = NTL::sqrt(root_two);\n   r /= root_two;\n   NTL::RR lim = NTL::pow(NTL::RR(NTL::INIT_VAL, 2.0), NTL::RR(NTL::INIT_VAL, -128));\n   NTL::RR::SetOutputPrecision(40);\n   while(r > lim)\n   {\n      std::cout << \"   { \" << r << \"L, \" << NTL::log1p(r) << \"L, \" << NTL::expm1(r) << \"L, }, \\n\";\n      std::cout << \"   { \" << -r << \"L, \" << NTL::log1p(-r) << \"L, \" << NTL::expm1(-r) << \"L, }, \\n\";\n      r /= root_two;\n   }\n   return 0;\n}\n\n", "meta": {"hexsha": "78f16df33ef8406827b6be3eefb675f4ef4b46bb", "size": 903, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/math/tools/generate_test_values.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "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": "boost/libs/math/tools/generate_test_values.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 61.0, "max_issues_repo_issues_event_min_datetime": "2015-05-27T11:20:11.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-20T15:06:21.000Z", "max_forks_repo_path": "boost/libs/math/tools/generate_test_values.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-09-09T02:38:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-30T00:24:24.000Z", "avg_line_length": 26.5588235294, "max_line_length": 101, "alphanum_fraction": 0.5714285714, "num_tokens": 335, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.45793671978692585}}
{"text": "#include <boost/test/unit_test.hpp>\n#include \"functions/streaming.hh\"\n#include \"functions/std_functions.hh\"\n#include \"functions/polynomial.hh\"\n#include \"functions/variables.hh\"\n#include \"functions/operators.hh\"\n#include \"functions/all_simplifications.hh\"\n#include <iostream>\n\nBOOST_AUTO_TEST_CASE(streaming_test) {\n  using namespace manifolds;\n  auto p1 = x * x;\n  auto p = p1(IP<1>() + x * x) + x * x * x;\n  Stream2(std::cout, p) << \"\\n\\n\";\n}\n", "meta": {"hexsha": "aa3c6bad8c0b065b5c3a8c037b23418805e85451", "size": 444, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "functions/tests/test_streaming.cpp", "max_stars_repo_name": "GuylainGreer/manifolds", "max_stars_repo_head_hexsha": "96f996f67fc523c726f2edbc9705125c212bedae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "functions/tests/test_streaming.cpp", "max_issues_repo_name": "GuylainGreer/manifolds", "max_issues_repo_head_hexsha": "96f996f67fc523c726f2edbc9705125c212bedae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "functions/tests/test_streaming.cpp", "max_forks_repo_name": "GuylainGreer/manifolds", "max_forks_repo_head_hexsha": "96f996f67fc523c726f2edbc9705125c212bedae", "max_forks_repo_licenses": ["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.75, "max_line_length": 43, "alphanum_fraction": 0.713963964, "num_tokens": 117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.45793671978692585}}
{"text": "// Copyright (c) by respective owners including Yahoo!, Microsoft, and\n// individual contributors. All rights reserved. Released under a BSD (revised)\n// license as described in the file LICENSE.\n\n#include \"vw/core/loss_functions.h\"\n\n#include \"test_common.h\"\n#include \"vw/core/named_labels.h\"\n\n#include <boost/test/test_tools.hpp>\n#include <boost/test/unit_test.hpp>\n\nBOOST_AUTO_TEST_CASE(squared_loss_test)\n{\n  auto& vw = *VW::initialize(\"--quiet\");\n  const std::string loss_type(\"squared\");\n\n  auto loss = get_loss_function(vw, loss_type);\n  shared_data sd;\n  sd.min_label = 0.0f;\n  sd.max_label = 1.0f;\n  constexpr float eta = 0.1f;     // learning rate\n  constexpr float weight = 1.0f;  // example weight\n\n  constexpr float label = 0.5f;\n  constexpr float prediction = 0.4f;\n  constexpr float update_scale = eta * weight;\n  constexpr float pred_per_update = 1.0f;  // Use dummy value here, see gd.cc for details.\n\n  BOOST_CHECK_EQUAL(loss_type, loss->get_type());\n  BOOST_CHECK_CLOSE(0.0f, loss->get_parameter(), FLOAT_TOL);\n\n  BOOST_CHECK_CLOSE(0.01f, loss->get_loss(&sd, prediction, label), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(0.01812692f, loss->get_update(prediction, label, update_scale, pred_per_update), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(0.02f, loss->get_unsafe_update(prediction, label, update_scale), FLOAT_TOL);\n\n  BOOST_CHECK_CLOSE(0.04f, loss->get_square_grad(prediction, label), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(-0.2f, loss->first_derivative(&sd, prediction, label), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(2.0f, loss->second_derivative(&sd, prediction, label), FLOAT_TOL);\n\n  VW::finish(vw);\n}\n\nBOOST_AUTO_TEST_CASE(expectile_loss_label_is_greater_than_prediction_test1)\n{\n  auto& vw = *VW::initialize(\"--quiet\");\n  const std::string loss_type(\"expectile\");\n  constexpr float parameter(0.4f);\n\n  auto loss = get_loss_function(vw, loss_type, parameter);\n  shared_data sd;\n  sd.min_label = 0.0f;\n  sd.max_label = 1.0f;\n  constexpr float eta = 0.1f;     // learning rate\n  constexpr float weight = 1.0f;  // example weight\n\n  constexpr float label = 0.5f;\n  constexpr float prediction = 0.4f;\n  constexpr float update_scale = eta * weight;\n  constexpr float pred_per_update = 1.0f;  // Use dummy value here, see gd.cc for details.\n\n  BOOST_CHECK_EQUAL(loss_type, loss->get_type());\n  BOOST_CHECK_CLOSE(parameter, loss->get_parameter(), FLOAT_TOL);\n\n  BOOST_CHECK_CLOSE(0.006f, loss->get_loss(&sd, prediction, label), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(0.011307956f, loss->get_update(prediction, label, update_scale, pred_per_update), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(0.012f, loss->get_unsafe_update(prediction, label, update_scale), FLOAT_TOL);\n\n  BOOST_CHECK_CLOSE(0.0144f, loss->get_square_grad(prediction, label), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(-0.12f, loss->first_derivative(&sd, prediction, label), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(1.2f, loss->second_derivative(&sd, prediction, label), FLOAT_TOL);\n\n  VW::finish(vw);\n}\n\nBOOST_AUTO_TEST_CASE(expectile_loss_label_is_greater_than_prediction_test2)\n{\n  auto& vw = *VW::initialize(\"--quiet\");\n  const std::string loss_type(\"expectile\");\n  constexpr float parameter(0.25f);\n\n  auto loss = get_loss_function(vw, loss_type, parameter);\n  shared_data sd;\n  sd.min_label = 0.0f;\n  sd.max_label = 1.0f;\n  constexpr float eta = 0.1f;     // learning rate\n  constexpr float weight = 1.0f;  // example weight\n\n  constexpr float label = 0.74f;\n  constexpr float prediction = 0.18f;\n  constexpr float update_scale = eta * weight;\n  constexpr float pred_per_update = 1.0f;  // Use dummy value here, see gd.cc for details.\n\n  BOOST_CHECK_EQUAL(loss_type, loss->get_type());\n  BOOST_CHECK_CLOSE(parameter, loss->get_parameter(), FLOAT_TOL);\n\n  BOOST_CHECK_CLOSE(0.2352f, loss->get_loss(&sd, prediction, label), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(0.0780035332f, loss->get_update(prediction, label, update_scale, pred_per_update), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(0.084f, loss->get_unsafe_update(prediction, label, update_scale), FLOAT_TOL);\n\n  BOOST_CHECK_CLOSE(0.7056f, loss->get_square_grad(prediction, label), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(-0.84f, loss->first_derivative(&sd, prediction, label), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(1.5f, loss->second_derivative(&sd, prediction, label), FLOAT_TOL);\n\n  VW::finish(vw);\n}\n\nBOOST_AUTO_TEST_CASE(expectile_loss_label_is_greater_than_prediction_test3)\n{\n  auto& vw = *VW::initialize(\"--quiet\");\n  const std::string loss_type(\"expectile\");\n  constexpr float parameter(0.2f);\n\n  auto loss = get_loss_function(vw, loss_type, parameter);\n  shared_data sd;\n  sd.min_label = 0.0f;\n  sd.max_label = 1.0f;\n  constexpr float eta = 0.1f;     // learning rate\n  constexpr float weight = 1.0f;  // example weight\n\n  constexpr float label = 0.84f;\n  constexpr float prediction = 0.48f;\n  constexpr float update_scale = eta * weight;\n  constexpr float pred_per_update = 1.0f;  // Use dummy value here, see gd.cc for details.\n\n  BOOST_CHECK_EQUAL(loss_type, loss->get_type());\n  BOOST_CHECK_CLOSE(parameter, loss->get_parameter(), FLOAT_TOL);\n\n  BOOST_CHECK_CLOSE(0.10368f, loss->get_loss(&sd, prediction, label), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(0.05322823597f, loss->get_update(prediction, label, update_scale, pred_per_update), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(0.0576f, loss->get_unsafe_update(prediction, label, update_scale), FLOAT_TOL);\n\n  BOOST_CHECK_CLOSE(0.331776f, loss->get_square_grad(prediction, label), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(-0.576f, loss->first_derivative(&sd, prediction, label), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(1.6f, loss->second_derivative(&sd, prediction, label), FLOAT_TOL);\n\n  VW::finish(vw);\n}\n\nBOOST_AUTO_TEST_CASE(expectile_loss_label_is_greater_than_prediction_test4)\n{\n  auto& vw = *VW::initialize(\"--quiet\");\n  const std::string loss_type(\"expectile\");\n  constexpr float parameter(0.3f);\n\n  auto loss = get_loss_function(vw, loss_type, parameter);\n  shared_data sd;\n  sd.min_label = 0.0f;\n  sd.max_label = 1.0f;\n  constexpr float eta = 0.1f;     // learning rate\n  constexpr float weight = 1.0f;  // example weight\n\n  constexpr float label = 0.29f;\n  constexpr float prediction = 0.06f;\n  constexpr float update_scale = eta * weight;\n  constexpr float pred_per_update = 1.0f;  // Use dummy value here, see gd.cc for details.\n\n  BOOST_CHECK_EQUAL(loss_type, loss->get_type());\n  BOOST_CHECK_CLOSE(parameter, loss->get_parameter(), FLOAT_TOL);\n\n  BOOST_CHECK_CLOSE(0.03703f, loss->get_loss(&sd, prediction, label), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(0.03004760586f, loss->get_update(prediction, label, update_scale, pred_per_update), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(0.0322f, loss->get_unsafe_update(prediction, label, update_scale), FLOAT_TOL);\n\n  BOOST_CHECK_CLOSE(0.103684f, loss->get_square_grad(prediction, label), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(-0.322f, loss->first_derivative(&sd, prediction, label), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(1.4f, loss->second_derivative(&sd, prediction, label), FLOAT_TOL);\n\n  VW::finish(vw);\n}\n\nBOOST_AUTO_TEST_CASE(expectile_loss_label_is_greater_than_prediction_test5)\n{\n  auto& vw = *VW::initialize(\"--quiet\");\n  const std::string loss_type(\"expectile\");\n  constexpr float parameter(0.25f);\n\n  auto loss = get_loss_function(vw, loss_type, parameter);\n  shared_data sd;\n  sd.min_label = 0.0f;\n  sd.max_label = 1.0f;\n  constexpr float eta = 0.1f;     // learning rate\n  constexpr float weight = 1.0f;  // example weight\n\n  constexpr float label = 0.50f;\n  constexpr float prediction = 0.09f;\n  constexpr float update_scale = eta * weight;\n  constexpr float pred_per_update = 1.0f;  // Use dummy value here, see gd.cc for details.\n\n  BOOST_CHECK_EQUAL(loss_type, loss->get_type());\n  BOOST_CHECK_CLOSE(parameter, loss->get_parameter(), FLOAT_TOL);\n\n  BOOST_CHECK_CLOSE(0.126075f, loss->get_loss(&sd, prediction, label), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(0.05710972967f, loss->get_update(prediction, label, update_scale, pred_per_update), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(0.0615f, loss->get_unsafe_update(prediction, label, update_scale), FLOAT_TOL);\n\n  BOOST_CHECK_CLOSE(0.378225f, loss->get_square_grad(prediction, label), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(-0.615f, loss->first_derivative(&sd, prediction, label), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(1.5f, loss->second_derivative(&sd, prediction, label), FLOAT_TOL);\n\n  VW::finish(vw);\n}\n\nBOOST_AUTO_TEST_CASE(expectile_loss_prediction_is_greater_than_label_test1)\n{\n  auto& vw = *VW::initialize(\"--quiet\");\n  const std::string loss_type(\"expectile\");\n  constexpr float parameter(0.4f);\n\n  auto loss = get_loss_function(vw, loss_type, parameter);\n  shared_data sd;\n  sd.min_label = 0.0f;\n  sd.max_label = 1.0f;\n  constexpr float eta = 0.1f;     // learning rate\n  constexpr float weight = 1.0f;  // example weight\n\n  constexpr float label = 0.4f;\n  constexpr float prediction = 0.5f;\n  constexpr float update_scale = eta * weight;\n  constexpr float pred_per_update = 1.0f;  // Use dummy value here, see gd.cc for details.\n\n  BOOST_CHECK_EQUAL(loss_type, loss->get_type());\n  BOOST_CHECK_CLOSE(parameter, loss->get_parameter(), FLOAT_TOL);\n\n  BOOST_CHECK_CLOSE(0.004f, loss->get_loss(&sd, prediction, label), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(-0.007688365f, loss->get_update(prediction, label, update_scale, pred_per_update), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(-0.008f, loss->get_unsafe_update(prediction, label, update_scale), FLOAT_TOL);\n\n  BOOST_CHECK_CLOSE(0.0064f, loss->get_square_grad(prediction, label), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(0.08f, loss->first_derivative(&sd, prediction, label), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(0.8f, loss->second_derivative(&sd, prediction, label), FLOAT_TOL);\n\n  VW::finish(vw);\n}\n\nBOOST_AUTO_TEST_CASE(expectile_loss_prediction_is_greater_than_label_test2)\n{\n  auto& vw = *VW::initialize(\"--quiet\");\n  const std::string loss_type(\"expectile\");\n  constexpr float parameter(0.25f);\n\n  auto loss = get_loss_function(vw, loss_type, parameter);\n  shared_data sd;\n  sd.min_label = 0.0f;\n  sd.max_label = 1.0f;\n  constexpr float eta = 0.1f;     // learning rate\n  constexpr float weight = 1.0f;  // example weight\n\n  constexpr float label = 0.57f;\n  constexpr float prediction = 0.64f;\n  constexpr float update_scale = eta * weight;\n  constexpr float pred_per_update = 1.0f;  // Use dummy value here, see gd.cc for details.\n\n  BOOST_CHECK_EQUAL(loss_type, loss->get_type());\n  BOOST_CHECK_CLOSE(parameter, loss->get_parameter(), FLOAT_TOL);\n\n  BOOST_CHECK_CLOSE(0.001225f, loss->get_loss(&sd, prediction, label), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(-0.003413940285f, loss->get_update(prediction, label, update_scale, pred_per_update), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(-0.0035f, loss->get_unsafe_update(prediction, label, update_scale), FLOAT_TOL);\n\n  BOOST_CHECK_CLOSE(0.001225f, loss->get_square_grad(prediction, label), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(0.035f, loss->first_derivative(&sd, prediction, label), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(0.5f, loss->second_derivative(&sd, prediction, label), FLOAT_TOL);\n\n  VW::finish(vw);\n}\n\nBOOST_AUTO_TEST_CASE(expectile_loss_prediction_is_greater_than_label_test3)\n{\n  auto& vw = *VW::initialize(\"--quiet\");\n  const std::string loss_type(\"expectile\");\n  constexpr float parameter(0.2f);\n\n  auto loss = get_loss_function(vw, loss_type, parameter);\n  shared_data sd;\n  sd.min_label = 0.0f;\n  sd.max_label = 1.0f;\n  constexpr float eta = 0.1f;     // learning rate\n  constexpr float weight = 1.0f;  // example weight\n\n  constexpr float label = 0.79f;\n  constexpr float prediction = 0.91f;\n  constexpr float update_scale = eta * weight;\n  constexpr float pred_per_update = 1.0f;  // Use dummy value here, see gd.cc for details.\n\n  BOOST_CHECK_EQUAL(loss_type, loss->get_type());\n  BOOST_CHECK_CLOSE(parameter, loss->get_parameter(), FLOAT_TOL);\n\n  BOOST_CHECK_CLOSE(0.00288f, loss->get_loss(&sd, prediction, label), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(-0.004705267302f, loss->get_update(prediction, label, update_scale, pred_per_update), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(-0.0048f, loss->get_unsafe_update(prediction, label, update_scale), FLOAT_TOL);\n\n  BOOST_CHECK_CLOSE(0.002304f, loss->get_square_grad(prediction, label), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(0.048f, loss->first_derivative(&sd, prediction, label), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(0.4f, loss->second_derivative(&sd, prediction, label), FLOAT_TOL);\n\n  VW::finish(vw);\n}\n\nBOOST_AUTO_TEST_CASE(expectile_loss_prediction_is_greater_than_label_test4)\n{\n  auto& vw = *VW::initialize(\"--quiet\");\n  const std::string loss_type(\"expectile\");\n  constexpr float parameter(0.2f);\n\n  auto loss = get_loss_function(vw, loss_type, parameter);\n  shared_data sd;\n  sd.min_label = 0.0f;\n  sd.max_label = 1.0f;\n  constexpr float eta = 0.1f;     // learning rate\n  constexpr float weight = 1.0f;  // example weight\n\n  constexpr float label = 0.02f;\n  constexpr float prediction = 0.29f;\n  constexpr float update_scale = eta * weight;\n  constexpr float pred_per_update = 1.0f;  // Use dummy value here, see gd.cc for details.\n\n  BOOST_CHECK_EQUAL(loss_type, loss->get_type());\n  BOOST_CHECK_CLOSE(parameter, loss->get_parameter(), FLOAT_TOL);\n\n  BOOST_CHECK_CLOSE(0.01458f, loss->get_loss(&sd, prediction, label), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(-0.01058685143f, loss->get_update(prediction, label, update_scale, pred_per_update), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(-0.0108f, loss->get_unsafe_update(prediction, label, update_scale), FLOAT_TOL);\n\n  BOOST_CHECK_CLOSE(0.011664f, loss->get_square_grad(prediction, label), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(0.108f, loss->first_derivative(&sd, prediction, label), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(0.4f, loss->second_derivative(&sd, prediction, label), FLOAT_TOL);\n\n  VW::finish(vw);\n}\n\nBOOST_AUTO_TEST_CASE(expectile_loss_prediction_is_greater_than_label_test5)\n{\n  auto& vw = *VW::initialize(\"--quiet\");\n  const std::string loss_type(\"expectile\");\n  constexpr float parameter(0.4f);\n\n  auto loss = get_loss_function(vw, loss_type, parameter);\n  shared_data sd;\n  sd.min_label = 0.0f;\n  sd.max_label = 1.0f;\n  constexpr float eta = 0.1f;     // learning rate\n  constexpr float weight = 1.0f;  // example weight\n\n  constexpr float label = 0.24f;\n  constexpr float prediction = 0.44f;\n  constexpr float update_scale = eta * weight;\n  constexpr float pred_per_update = 1.0f;  // Use dummy value here, see gd.cc for details.\n\n  BOOST_CHECK_EQUAL(loss_type, loss->get_type());\n  BOOST_CHECK_CLOSE(parameter, loss->get_parameter(), FLOAT_TOL);\n\n  BOOST_CHECK_CLOSE(0.016f, loss->get_loss(&sd, prediction, label), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(-0.01537673072f, loss->get_update(prediction, label, update_scale, pred_per_update), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(-0.016f, loss->get_unsafe_update(prediction, label, update_scale), FLOAT_TOL);\n\n  BOOST_CHECK_CLOSE(0.0256f, loss->get_square_grad(prediction, label), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(0.16f, loss->first_derivative(&sd, prediction, label), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(0.8f, loss->second_derivative(&sd, prediction, label), FLOAT_TOL);\n\n  VW::finish(vw);\n}\nBOOST_AUTO_TEST_CASE(expectile_loss_parameter_equals_zero_test)\n{\n  auto& vw = *VW::initialize(\"--quiet\");\n  const std::string loss_type(\"expectile\");\n  constexpr float parameter(0.0f);\n\n  auto loss = get_loss_function(vw, loss_type, parameter);\n  shared_data sd;\n  sd.min_label = 0.0f;\n  sd.max_label = 1.0f;\n  constexpr float eta = 0.1f;     // learning rate\n  constexpr float weight = 1.0f;  // example weight\n\n  constexpr float label = 0.5f;\n  constexpr float prediction = 0.4f;\n  constexpr float update_scale = eta * weight;\n  constexpr float pred_per_update = 1.0f;  // Use dummy value here, see gd.cc for details.\n\n  BOOST_CHECK_EQUAL(loss_type, loss->get_type());\n  BOOST_CHECK_CLOSE(parameter, loss->get_parameter(), FLOAT_TOL);\n\n  BOOST_CHECK_CLOSE(0.01f, loss->get_loss(&sd, prediction, label), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(0.01812692f, loss->get_update(prediction, label, update_scale, pred_per_update), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(0.02f, loss->get_unsafe_update(prediction, label, update_scale), FLOAT_TOL);\n\n  BOOST_CHECK_CLOSE(0.04f, loss->get_square_grad(prediction, label), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(-0.2f, loss->first_derivative(&sd, prediction, label), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(2.0f, loss->second_derivative(&sd, prediction, label), FLOAT_TOL);\n\n  VW::finish(vw);\n}\n\nBOOST_AUTO_TEST_CASE(expectile_loss_parameter_equals_one_test)\n{\n  auto& vw = *VW::initialize(\"--quiet\");\n  const std::string loss_type(\"expectile\");\n  constexpr float parameter(1.0f);\n\n  auto loss = get_loss_function(vw, loss_type, parameter);\n  shared_data sd;\n  sd.min_label = 0.0f;\n  sd.max_label = 1.0f;\n  constexpr float eta = 0.1f;     // learning rate\n  constexpr float weight = 1.0f;  // example weight\n\n  constexpr float label = 0.5f;\n  constexpr float prediction = 0.4f;\n  constexpr float update_scale = eta * weight;\n  constexpr float pred_per_update = 1.0f;  // Use dummy value here, see gd.cc for details.\n\n  BOOST_CHECK_EQUAL(loss_type, loss->get_type());\n  BOOST_CHECK_CLOSE(parameter, loss->get_parameter(), FLOAT_TOL);\n\n  BOOST_CHECK_CLOSE(0.0f, loss->get_loss(&sd, prediction, label), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(0.0f, loss->get_update(prediction, label, update_scale, pred_per_update), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(0.0f, loss->get_unsafe_update(prediction, label, update_scale), FLOAT_TOL);\n\n  BOOST_CHECK_CLOSE(0.0f, loss->get_square_grad(prediction, label), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(0.0f, loss->first_derivative(&sd, prediction, label), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(0.0f, loss->second_derivative(&sd, prediction, label), FLOAT_TOL);\n\n  VW::finish(vw);\n}\n\nBOOST_AUTO_TEST_CASE(compare_expectile_loss_with_squared_loss_test)\n{\n  auto& vw = *VW::initialize(\"--quiet\");\n  const std::string loss_type_expectile(\"expectile\");\n  const std::string loss_type_squared(\"squared\");\n  constexpr float parameter(0.3f);\n\n  auto loss_expectile = get_loss_function(vw, loss_type_expectile, parameter);\n  auto loss_squared = get_loss_function(vw, loss_type_squared);\n  shared_data sd;\n  sd.min_label = 0.0f;\n  sd.max_label = 1.0f;\n  constexpr float eta = 0.1f;     // learning rate\n  constexpr float weight = 1.0f;  // example weight\n\n  constexpr float label = 0.4f;\n  constexpr float prediction = 0.5f;\n  constexpr float update_scale = eta * weight;\n  constexpr float pred_per_update = 1.0f;  // Use dummy value here, see gd.cc for details.\n\n  BOOST_CHECK_CLOSE(loss_expectile->get_loss(&sd, prediction, label),\n      loss_squared->get_loss(&sd, prediction, label) * parameter, FLOAT_TOL);\n  BOOST_CHECK_CLOSE(loss_expectile->get_update(prediction, label, update_scale, pred_per_update),\n      loss_squared->get_update(prediction, label, update_scale * parameter, pred_per_update), FLOAT_TOL);\n  BOOST_CHECK_CLOSE(loss_expectile->get_unsafe_update(prediction, label, update_scale),\n      loss_squared->get_unsafe_update(prediction, label, update_scale * parameter), FLOAT_TOL);\n\n  BOOST_CHECK_CLOSE(loss_expectile->get_square_grad(prediction, label),\n      loss_squared->get_square_grad(prediction, label) * parameter * parameter, FLOAT_TOL);\n  BOOST_CHECK_CLOSE(loss_expectile->first_derivative(&sd, prediction, label),\n      loss_squared->first_derivative(&sd, prediction, label) * parameter, FLOAT_TOL);\n  BOOST_CHECK_CLOSE(loss_expectile->second_derivative(&sd, prediction, label),\n      loss_squared->second_derivative(&sd, prediction, label) * parameter, FLOAT_TOL);\n\n  VW::finish(vw);\n}\n", "meta": {"hexsha": "76b6d09f7b71017e83c063bc278b69924ffe4b45", "size": 19338, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/unit_test/loss_functions_test.cc", "max_stars_repo_name": "HollowMan6/vowpal_wabbit", "max_stars_repo_head_hexsha": "eecdaccce568b53ed195bc4d50a6a582ab9a83d5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4332.0, "max_stars_repo_stars_event_min_datetime": "2015-01-01T10:26:51.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-01T14:05:43.000Z", "max_issues_repo_path": "test/unit_test/loss_functions_test.cc", "max_issues_repo_name": "HollowMan6/vowpal_wabbit", "max_issues_repo_head_hexsha": "eecdaccce568b53ed195bc4d50a6a582ab9a83d5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1004.0, "max_issues_repo_issues_event_min_datetime": "2015-01-01T12:00:54.000Z", "max_issues_repo_issues_event_max_datetime": "2018-09-30T22:13:42.000Z", "max_forks_repo_path": "test/unit_test/loss_functions_test.cc", "max_forks_repo_name": "HollowMan6/vowpal_wabbit", "max_forks_repo_head_hexsha": "eecdaccce568b53ed195bc4d50a6a582ab9a83d5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1182.0, "max_forks_repo_forks_event_min_datetime": "2015-01-02T20:38:55.000Z", "max_forks_repo_forks_event_max_datetime": "2018-09-26T02:47:37.000Z", "avg_line_length": 41.7667386609, "max_line_length": 117, "alphanum_fraction": 0.7490433344, "num_tokens": 5389, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.45793671978692585}}
{"text": "/*******************************************************************************\n * Copyright (c) 2014, 2015  IBM Corporation and others\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *******************************************************************************/\n\n#ifndef ArrayUtils_hpp\n#define ArrayUtils_hpp\n\n#include <stdio.h>\n#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <cmath>\n\n#include <Eigen/Core>\n\nclass ArrayUtils{\n    \npublic:\n    static void normalize(double outArray[], const double inArray[], int n);\n    static std::vector<double> arrayToVector(double *array);\n    \n    static std::vector<double> computeWeightsFromLogLikelihood(std::vector<double> logLikelihoods);\n    \n    static Eigen::VectorXd vectorToEigenVector(std::vector<double>);\n    static std::vector<double> eigenVectorToEigen(Eigen::VectorXd);\n};\n\n#endif /* ArrayUtils_hpp */\n", "meta": {"hexsha": "532e093f18d44da9b9e466c4aeea4395f521980a", "size": 1909, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ble-cpp/src/utils/ArrayUtils.hpp", "max_stars_repo_name": "harsh-agarwal/blelocpp", "max_stars_repo_head_hexsha": "eaba46c6239981c7b8e69bef2ab33bb08ecb15b4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2016-06-13T20:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-22T17:29:32.000Z", "max_issues_repo_path": "ble-cpp/src/utils/ArrayUtils.hpp", "max_issues_repo_name": "harsh-agarwal/blelocpp", "max_issues_repo_head_hexsha": "eaba46c6239981c7b8e69bef2ab33bb08ecb15b4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2016-03-14T07:00:04.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-07T18:20:15.000Z", "max_forks_repo_path": "ble-cpp/src/utils/ArrayUtils.hpp", "max_forks_repo_name": "harsh-agarwal/blelocpp", "max_forks_repo_head_hexsha": "eaba46c6239981c7b8e69bef2ab33bb08ecb15b4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2016-02-03T07:41:00.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-11T10:03:48.000Z", "avg_line_length": 40.6170212766, "max_line_length": 99, "alphanum_fraction": 0.6904138292, "num_tokens": 376, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.4579367168207952}}
{"text": "/* Copyright 2020, 2021 Evandro Chagas Ribeiro da Rosa <evandro.crr@posgrad.ufsc.br>\n * Copyright 2020, 2021 Rafael de Santiago <r.santiago@ufsc.br>\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 \"../include/ket_bitwise.hpp\"\n#include <boost/container/map.hpp>\n#include <random>\n#include <algorithm>\n\nusing namespace ket;\nusing namespace std::complex_literals;\n\nBitwise::Bitwise() {\n    qbits[Index()] = 1;\n}\n\nvoid Bitwise::x(size_t idx, const ctrl_list& ctrl) {\n    map qbits_tmp{};\n    for (auto &i : qbits) {\n        bool exec = true;\n        for (auto j : ctrl) exec &= i.first.is_one(j);\n        if (exec) {\n            auto j = i.first;\n            j.flip(idx);\n            qbits_tmp[j] = i.second; \n        } else {\n            qbits_tmp[i.first] = i.second; \n        }\n    }\n    qbits.swap(qbits_tmp);\n}\n\nvoid Bitwise::y(size_t idx, const ctrl_list& ctrl) {\n    map qbits_tmp{};\n    for (auto &i : qbits) {\n        bool exec = true;\n        for (auto j : ctrl) exec &= i.first.is_one(j);\n        if (exec) {\n            auto j = i.first;\n            j.flip(idx);\n            if (i.first.is_one(idx)) {\n                qbits_tmp[j] = i.second*-1i;\n            } else {\n                qbits_tmp[j] = i.second*1i;\n            }\n        } else {\n            qbits_tmp[i.first] = i.second; \n        }\n    }\n    qbits.swap(qbits_tmp);\n}\n\nvoid Bitwise::z(size_t idx, const ctrl_list& ctrl) {\n    for (auto &i : qbits) {\n        bool exec = true;\n        for (auto j : ctrl) exec &= i.first.is_one(j);\n        if (exec and i.first.is_one(idx)) {\n            qbits[i.first] *= -1;\n        }\n    }\n}\n\nvoid Bitwise::h(size_t idx, const ctrl_list& ctrl) {\n    map qbits_tmp{};\n    for (auto &i : qbits) {\n        bool exec = true;\n        for (auto j : ctrl) exec &= i.first.is_one(j);\n        if (exec) {\n            if (i.first.is_one(idx)) {\n                qbits_tmp[i.first] -= i.second/std::sqrt(2);\n            } else {\n                qbits_tmp[i.first] += i.second/std::sqrt(2);\n            }\n            if (std::abs(qbits_tmp[i.first]) < 1e-10) {\n                qbits_tmp.erase(i.first);\n            }\n            auto j = i.first;\n            j.flip(idx);\n            qbits_tmp[j] += i.second/std::sqrt(2);\n            if (std::abs(qbits_tmp[j]) < 1e-10) {\n                qbits_tmp.erase(j);\n            }\n        } else {\n            qbits_tmp[i.first] = i.second; \n        }\n\n    }\n    qbits.swap(qbits_tmp);\n}\n\nvoid Bitwise::s(size_t idx, const ctrl_list& ctrl) {\n    for (auto &i : qbits) {\n        bool exec = true;\n        for (auto j : ctrl) exec &= i.first.is_one(j);\n        if (exec and i.first.is_one(idx)) {\n            qbits[i.first] *= 1i;\n        }\n    }\n}\n\nvoid Bitwise::sd(size_t idx, const ctrl_list& ctrl) {\n    for (auto &i : qbits) {\n        bool exec = true;\n        for (auto j : ctrl) exec &= i.first.is_one(j);\n        if (exec and i.first.is_one(idx)) {\n            qbits[i.first] *= -1i;\n        }\n    }\n}\n\nvoid Bitwise::t(size_t idx, const ctrl_list& ctrl) {\n    for (auto &i : qbits) {\n        bool exec = true;\n        for (auto j : ctrl) exec &= i.first.is_one(j);\n        if (exec and i.first.is_one(idx)) {\n            qbits[i.first] *= std::exp(1i*M_PI/4.0);\n        }\n    }\n}\n\nvoid Bitwise::td(size_t idx, const ctrl_list& ctrl) {\n    for (auto &i : qbits) {\n        bool exec = true;\n        for (auto j : ctrl) exec &= i.first.is_one(j);\n        if (exec and i.first.is_one(idx)) {\n            qbits[i.first] *= std::exp(-1i*M_PI/4.0);\n        }\n    }\n}\n\nvoid Bitwise::cnot(size_t ctrl, size_t target,  const ctrl_list& ctrl2) {\n    map qbits_tmp{};\n\n    for (auto &i : qbits) {\n        bool exec = true;\n        for (auto j : ctrl2) exec &= i.first.is_one(j);\n        if (exec and i.first.is_one(ctrl)) {\n            auto j = i.first;\n            j.flip(target);\n            qbits_tmp[j] = i.second; \n        } else {\n            qbits_tmp[i.first] = i.second; \n        }\n    }\n\n    qbits.swap(qbits_tmp);\n}\n\nvoid Bitwise::p(double lambda, size_t idx, const ctrl_list& ctrl) {\n    for (auto &i : qbits) {\n        bool exec = true;\n        for (auto j : ctrl) exec &= i.first.is_one(j);\n        if (exec and i.first.is_one(idx)) {\n            qbits[i.first] *= std::exp(1i*lambda);\n        }\n    }\n}\n\nvoid Bitwise::u2(double phi, double lambda, size_t idx, const ctrl_list& ctrl) {\n    map qbits_tmp{};\n    for (auto &i : qbits) {\n        bool exec = true;\n        for (auto j : ctrl) exec &= i.first.is_one(j);\n        if (exec) {\n            auto j = i.first;\n            j.flip(idx);\n            if (i.first.is_one(idx)) {\n                qbits_tmp[i.first] += i.second*std::exp(1i*(lambda+phi))/std::sqrt(2);\n                if (std::abs(qbits_tmp[i.first]) < 1e-10)\n                    qbits_tmp.erase(i.first);\n                \n                qbits_tmp[j] -= i.second*std::exp(1i*lambda)/std::sqrt(2);\n                if (std::abs(qbits_tmp[j]) < 1e-10)\n                    qbits_tmp.erase(j);\n            } else {\n                qbits_tmp[i.first] += i.second/sqrt(2);\n                if (std::abs(qbits_tmp[i.first]) < 1e-10)\n                    qbits_tmp.erase(i.first);\n                \n                qbits_tmp[j] += i.second*std::exp(1i*phi)/std::sqrt(2);\n                if (std::abs(qbits_tmp[j]) < 1e-10)\n                    qbits_tmp.erase(j);\n            }\n\n        } else {\n            qbits_tmp[i.first] = i.second;\n        }\n    }\n\n    qbits.swap(qbits_tmp);\n} \n\nvoid Bitwise::u3(double theta, double phi, double lambda, size_t idx, const ctrl_list& ctrl) {\n    map qbits_tmp{};\n    std::complex<double> amp;\n    for (auto &i : qbits) {\n        bool exec = true;\n        for (auto j : ctrl) exec &= i.first.is_one(j);\n        if (exec) {\n            auto j = i.first;\n            j.flip(idx);\n            if (i.first.is_one(idx)) {\n                amp = std::exp(1i*(lambda+phi))*std::cos(theta/2);\n                qbits_tmp[i.first] += i.second*amp;\n                if (std::abs(qbits_tmp[i.first]) < 1e-10)\n                    qbits_tmp.erase(i.first);\n                \n                amp = std::exp(1i*lambda)*std::sin(theta/2);\n                qbits_tmp[j] -= i.second*amp;\n                if (std::abs(qbits_tmp[j]) < 1e-10)\n                    qbits_tmp.erase(j);\n            } else {\n                amp = std::cos(theta/2);\n                qbits_tmp[i.first] += i.second*amp;\n                if (std::abs(qbits_tmp[i.first]) < 1e-10)\n                    qbits_tmp.erase(i.first);\n\n                amp = std::exp(1i*phi)*std::sin(theta/2);\n                qbits_tmp[j] += i.second*amp;\n                if (std::abs(qbits_tmp[j]) < 1e-10)\n                    qbits_tmp.erase(j);\n            }\n        } else {\n            qbits_tmp[i.first] = i.second;\n        }\n    }\n\n    qbits.swap(qbits_tmp);\n}\n\nvoid Bitwise::rx(double theta, size_t idx, const ctrl_list& ctrl) {\n    u3(theta, -M_PI_2, M_PI_2, idx, ctrl);\n}\n\nvoid Bitwise::ry(double theta, size_t idx, const ctrl_list& ctrl) {\n    u3(theta, 0, 0, idx, ctrl);\n}\n\nvoid Bitwise::rz(double lambda, size_t idx, const ctrl_list& ctrl) {\n    for (auto &i : qbits) {\n        bool exec = true;\n        for (auto j : ctrl) exec &= i.first.is_one(j);\n        if (exec) {\n            if (i.first.is_one(idx))\n                qbits[i.first] *= std::exp(1i*lambda/2.0);\n            else \n                qbits[i.first] *= std::exp(-1i*lambda/2.0);\n        } \n    }\n}\n\nint Bitwise::measure(size_t idx) {\n    double p = 0;\n\n    for (auto &i : qbits) {\n        if (i.first.is_zero(idx)) {\n            p += std::pow(std::abs(i.second), 2);\n        }\n    }\n    \n    auto result = p != 0 and \n                  (double(std::rand()) / double(RAND_MAX) <= p)?\n                  0 : 1;\n    \n    p = result == 0? std::sqrt(p) : std::sqrt(1.0-p);\n\n    map qbits_tmp{};\n\n    for (auto &i : qbits)\n        if (i.first.is_zero(idx) xor result) \n            qbits_tmp[i.first] = i.second/p;\n\n    qbits.swap(qbits_tmp);\n    return result;\n}\n\nvoid Bitwise::measure_zero(size_t idx) {\n    double p = 0;\n\n    for (auto &i : qbits) \n        if (i.first.is_zero(idx)) \n            p += std::pow(std::abs(i.second), 2);\n            \n    auto result = p != 0 and \n                  (double(std::rand()) / double(RAND_MAX) <= p)?\n                  0 : 1;\n    \n    p = result == 0? std::sqrt(p) : std::sqrt(1.0-p);\n\n    map qbits_tmp{};\n\n    for (auto &i : qbits) {\n        if (i.first.is_zero(idx) xor result) {\n            if (result == 0) {\n                qbits_tmp[i.first] = i.second/p;\n            } else {\n                auto j = i.first;\n                j.flip(idx);\n                qbits_tmp[j] = i.second/p;\n            }\n        }\n    }\n    \n    qbits.swap(qbits_tmp);\n}\n\nstd::ostream& ket::operator<<(std::ostream &os, const Bitwise& q) {\n    boost::container::map<Index, complex> sorted;\n    sorted.insert(q.qbits.begin(), q.qbits.end());\n    for (auto &i : sorted) {\n        os << i.first << ' ' << i.second << std::endl;\n    }\n    return os;\n}\n\nBitwise::Bitwise(const Bitwise& a, const Bitwise& b) {\n    for (const auto &i: a.qbits) for (const auto &j: b.qbits) \n        qbits[i.first|j.first] = i.second*j.second; \n}\n\nvoid Bitwise::swap(size_t a, size_t b) {\n    map qbits_tmp{};\n    for (auto &i : qbits) {\n        if (i.first.is_one(a) != i.first.is_one(b)) {\n            auto j = i.first;\n            j.flip(a);\n            j.flip(b);\n            qbits_tmp[j] = i.second;\n        } else {\n            qbits_tmp[i.first] = i.second;\n        }\n    }\n    qbits.swap(qbits_tmp);\n}\n\nmap& Bitwise::get_map() {\n    return qbits;\n}\n\ndump_t Bitwise::dump(size_t size) const {\n    dump_t state;\n\n    for (auto &i : qbits) {\n        std::vector<uint64_t> tmp_state;\n        for (auto j = 0ul; j < size/64; j++)\n            tmp_state.push_back(i.first[j]);\n        tmp_state.push_back(i.first[size/64] & ((1ul << size%64) -1));\n        state[tmp_state].push_back(i.second);\n    }\n    for (auto &i : state) {\n        std::sort(i.second.begin(), i.second.end(), [](std::complex<double> a, std::complex<double> b) {\n            if (a.real() == b.real()) return a.imag() < b.imag();\n            else return a.real() < b.real();\n        });\n    }\n    \n    return state;\n}", "meta": {"hexsha": "f9860207c78ef8ca21d90b6e7940193b66124c9c", "size": 10693, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/bitwise.cpp", "max_stars_repo_name": "quantum-ket/kbw", "max_stars_repo_head_hexsha": "c3c4d5a1b81703911a0d0499b26e3737ac9a1057", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/bitwise.cpp", "max_issues_repo_name": "quantum-ket/kbw", "max_issues_repo_head_hexsha": "c3c4d5a1b81703911a0d0499b26e3737ac9a1057", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/bitwise.cpp", "max_forks_repo_name": "quantum-ket/kbw", "max_forks_repo_head_hexsha": "c3c4d5a1b81703911a0d0499b26e3737ac9a1057", "max_forks_repo_licenses": ["Apache-2.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.9, "max_line_length": 104, "alphanum_fraction": 0.5020106612, "num_tokens": 3004, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4579025195033162}}
{"text": "/******************************************************************************\n\n  This source file is part of the Avogadro project.\n\n  Copyright 2012-2014 Kitware, Inc.\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 \"camera.h\"\n\n#include <Eigen/LU>\n\n#include <cmath>\n\nnamespace Avogadro {\nnamespace Rendering {\n\nCamera::Camera() : m_width(0), m_height(0),\n  m_projectionType(Perspective), m_orthographicScale(1.0)\n{\n  m_projection.setIdentity();\n  m_modelView.setIdentity();\n}\n\nCamera::~Camera()\n{\n}\n\nvoid Camera::translate(const Vector3f &translate_)\n{\n  m_modelView.translate(translate_);\n}\n\nvoid Camera::preTranslate(const Vector3f &translate_)\n{\n  m_modelView.pretranslate(translate_);\n}\n\nvoid Camera::rotate(float angle, const Vector3f &axis)\n{\n  m_modelView.rotate(Eigen::AngleAxisf(angle, axis));\n}\n\nvoid Camera::preRotate(float angle, const Vector3f &axis)\n{\n  m_modelView.prerotate(Eigen::AngleAxisf(angle, axis));\n}\n\nvoid Camera::scale(float s)\n{\n  if (m_projectionType == Perspective)\n    m_modelView.scale(s);\n  else\n    m_orthographicScale *= s;\n}\n\nvoid Camera::lookAt(const Vector3f &eye, const Vector3f &center,\n                    const Vector3f &up)\n{\n  Vector3f f = (center - eye).normalized();\n  Vector3f u = up.normalized();\n  Vector3f s = f.cross(u).normalized();\n  u = s.cross(f);\n\n  m_modelView.setIdentity();\n  m_modelView(0, 0) = s.x();\n  m_modelView(0, 1) = s.y();\n  m_modelView(0, 2) = s.z();\n  m_modelView(1, 0) = u.x();\n  m_modelView(1, 1) = u.y();\n  m_modelView(1, 2) = u.z();\n  m_modelView(2, 0) =-f.x();\n  m_modelView(2, 1) =-f.y();\n  m_modelView(2, 2) =-f.z();\n  m_modelView(0, 3) =-s.dot(eye);\n  m_modelView(1, 3) =-u.dot(eye);\n  m_modelView(2, 3) = f.dot(eye);\n}\n\nfloat Camera::distance(const Vector3f &point) const\n{\n  return (m_modelView * point).norm();\n}\n\nVector3f Camera::project(const Vector3f &point) const\n{\n  Eigen::Matrix4f mvp = m_projection.matrix() * m_modelView.matrix();\n  Vector4f tPoint(point.x(), point.y(), point.z(), 1.0f);\n  tPoint = mvp * tPoint;\n  Vector3f result(static_cast<float>(m_width)\n                  * (tPoint.x() / tPoint.w() + 1.0f) / 2.0f,\n                  static_cast<float>(m_height)\n                  * (tPoint.y() / tPoint.w() + 1.0f) / 2.0f,\n                  (tPoint.z() / tPoint.w() + 1.0f) / 2.0f);\n  return result;\n}\n\nVector3f Camera::unProject(const Vector3f &point) const\n{\n  Eigen::Matrix4f mvp = m_projection.matrix() * m_modelView.matrix();\n  Vector4f result(2.0f * point.x() / static_cast<float>(m_width) - 1.0f,\n                  2.0f * (static_cast<float>(m_height) - point.y()) /\n                  static_cast<float>(m_height) - 1.0f,\n                  2.0f * point.z() - 1.0f,\n                  1.0f);\n  result = mvp.matrix().inverse() * result;\n  return Vector3f(result.x() / result.w(), result.y() / result.w(),\n                  result.z() / result.w());\n}\n\nVector3f Camera::unProject(const Vector2f &point,\n                           const Vector3f &reference) const\n{\n  return unProject(Vector3f(point.x(), point.y(), project(reference).z()));\n}\n\nvoid Camera::calculatePerspective(float fieldOfView, float aspectRatio,\n                                  float zNear, float zFar)\n{\n  m_projection.setIdentity();\n  float f = 1.0f / std::tan(fieldOfView * float(M_PI) / 360.0f);\n  m_projection(0, 0) = f / aspectRatio;\n  m_projection(1, 1) = f;\n  m_projection(2, 2) = (zNear + zFar) / (zNear - zFar);\n  m_projection(2, 3) = (2.0f * zFar * zNear) / (zNear - zFar);\n  m_projection(3, 2) = -1;\n  m_projection(3, 3) = 0;\n}\n\nvoid Camera::calculatePerspective(float fieldOfView, float zNear, float zFar)\n{\n  calculatePerspective(fieldOfView, static_cast<float>(m_width) /\n                       static_cast<float>(m_height), zNear, zFar);\n}\n\nvoid Camera::calculateOrthographic(float left, float right,\n                                   float bottom, float top,\n                                   float zNear, float zFar)\n{\n  left *= m_orthographicScale;\n  right *= m_orthographicScale;\n  bottom *= m_orthographicScale;\n  top *= m_orthographicScale;\n  m_projection.setIdentity();\n  m_projection(0, 0) = 2.0f / (right - left);\n  m_projection(0, 3) = -(right + left) / (right - left);\n  m_projection(1, 1) = 2.0f / (top - bottom);\n  m_projection(1, 3) = -(top + bottom) / (top - bottom);\n  m_projection(2, 2) = -2.0f / (zFar - zNear);\n  m_projection(2, 3) = -(zFar + zNear) / (zFar - zNear);\n  m_projection(3, 3) = 1;\n}\n\nvoid Camera::setViewport(int w, int h)\n{\n  m_width = w;\n  m_height = h;\n}\n\nvoid Camera::setProjection(const Eigen::Affine3f &transform)\n{\n  m_projection = transform;\n}\n\nvoid Camera::setModelView(const Eigen::Affine3f &transform)\n{\n  m_modelView = transform;\n}\n\n} // End Rendering namespace\n} // End Avogadro namespace\n", "meta": {"hexsha": "e78bbf10d09ba98b6b997c3b8e2f6c445f31d1ba", "size": 5160, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "avogadro/rendering/camera.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/rendering/camera.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/rendering/camera.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.6666666667, "max_line_length": 79, "alphanum_fraction": 0.6182170543, "num_tokens": 1511, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4579025195033162}}
{"text": "#include <iostream>\n\n#include \"KokkosCore/kokkosConfigCommon.h\"\n#include \"KokkosCore/kokkosConfig.h\"\n\n#include <Eigen/Core>\n#include <Eigen/Eigenvalues>\n\n#ifdef USE_BL\n#include \"plugin-PixelTriplets/kokkos/BrokenLine.h\"\n#else\n#include \"plugin-PixelTriplets/kokkos/RiemannFit.h\"\n#endif\n\n#include \"../test_common.h\"\n\nusing namespace Eigen;\n\nnamespace KOKKOS_NAMESPACE {\n  namespace Rfit {\n    constexpr uint32_t maxNumberOfTracks() { return 5 * 1024; }\n    constexpr uint32_t stride() { return maxNumberOfTracks(); }\n    // hits\n    template <int N>\n    using Matrix3xNd = Eigen::Matrix<double, 3, N>;\n    template <int N>\n    using Map3xNd = Eigen::Map<Matrix3xNd<N>, 0, Eigen::Stride<3 * stride(), stride()>>;\n    // errors\n    template <int N>\n    using Matrix6xNf = Eigen::Matrix<float, 6, N>;\n    template <int N>\n    using Map6xNf = Eigen::Map<Matrix6xNf<N>, 0, Eigen::Stride<6 * stride(), stride()>>;\n    // fast fit\n    using Map4d = Eigen::Map<Vector4d, 0, Eigen::InnerStride<stride()>>;\n\n  }  // namespace Rfit\n\n  template <int N>\n  KOKKOS_INLINE_FUNCTION void kernelPrintSizes(Kokkos::View<double*, KokkosExecSpace> vhits,\n                                               Kokkos::View<float*, KokkosExecSpace> vhits_ge,\n                                               const int& i) {\n    double* __restrict__ phits = vhits.data();\n    float* __restrict__ phits_ge = vhits_ge.data();\n\n    Rfit::Map3xNd<N> hits(phits + i, 3, 4);\n    Rfit::Map6xNf<N> hits_ge(phits_ge + i, 6, 4);\n    if (i != 0)\n      return;\n    printf(\"GPU sizes %lu %lu %lu %lu %lu\\n\",\n           sizeof(hits[i]),\n           sizeof(hits_ge[i]),\n           sizeof(Vector4d),\n           sizeof(Rfit::line_fit),\n           sizeof(Rfit::circle_fit));\n  }  // namespace Rfit\n}  // namespace KOKKOS_NAMESPACE\n\nusing namespace KOKKOS_NAMESPACE;\n\ntemplate <int N>\nKOKKOS_INLINE_FUNCTION void kernelFastFit(Kokkos::View<double*, KokkosExecSpace> vhits,\n                                          Kokkos::View<double*, KokkosExecSpace> vresults,\n                                          const int& i) {\n  double* __restrict__ phits = vhits.data();\n  double* __restrict__ presults = vresults.data();\n\n  Rfit::Map3xNd<N> hits(phits + i, 3, N);\n  Rfit::Map4d result(presults + i, 4);\n#ifdef USE_BL\n  BrokenLine::BL_Fast_fit(hits, result);\n#else\n  Rfit::Fast_fit(hits, result);\n#endif\n}\n\n#ifdef USE_BL\n\ntemplate <int N>\nKOKKOS_INLINE_FUNCTION void kernelBrokenLineFit(Kokkos::View<double*, KokkosExecSpace> vhits,\n                                                Kokkos::View<float*, KokkosExecSpace> vhits_ge,\n                                                Kokkos::View<double*, KokkosExecSpace> vfast_fit_input,\n                                                double B,\n                                                Kokkos::View<Rfit::circle_fit*, KokkosExecSpace> vcircle_fit,\n                                                Kokkos::View<Rfit::line_fit*, KokkosExecSpace> vline_fit,\n                                                const int& i) {\n  double* __restrict__ phits = vhits.data();\n  float* __restrict__ phits_ge = vhits_ge.data();\n  double* __restrict__ pfast_fit_input = vfast_fit_input.data();\n  Rfit::circle_fit* __restrict__ circle_fit = vcircle_fit.data();\n  Rfit::line_fit* __restrict__ line_fit = vline_fit.data();\n\n  Rfit::Map3xNd<N> hits(phits + i, 3, N);\n  Rfit::Map4d fast_fit_input(pfast_fit_input + i, 4);\n  Rfit::Map6xNf<N> hits_ge(phits_ge + i, 6, N);\n\n  BrokenLine::PreparedBrokenLineData<N> data;\n  Rfit::Matrix3d Jacob;\n\n  auto& line_fit_results = line_fit[i];\n  auto& circle_fit_results = circle_fit[i];\n\n  BrokenLine::prepareBrokenLineData(hits, fast_fit_input, B, data);\n  BrokenLine::BL_Line_fit(hits_ge, fast_fit_input, B, data, line_fit_results);\n  BrokenLine::BL_Circle_fit(hits, hits_ge, fast_fit_input, B, data, circle_fit_results);\n  Jacob << 1., 0, 0, 0, 1., 0, 0, 0,\n      -B / std::copysign(Rfit::sqr(circle_fit_results.par(2)), circle_fit_results.par(2));\n  circle_fit_results.par(2) = B / std::abs(circle_fit_results.par(2));\n  circle_fit_results.cov = Jacob * circle_fit_results.cov * Jacob.transpose();\n\n#ifdef TEST_DEBUG\n  if (0 == i) {\n    printf(\"Circle param %f,%f,%f\\n\", circle_fit[i].par(0), circle_fit[i].par(1), circle_fit[i].par(2));\n  }\n#endif\n}\n\n#else\n\ntemplate <int N>\nKOKKOS_INLINE_FUNCTION void kernelCircleFit(Kokkos::View<double*, KokkosExecSpace> vhits,\n                                            Kokkos::View<float*, KokkosExecSpace> vhits_ge,\n                                            Kokkos::View<double*, KokkosExecSpace> vfast_fit_input,\n                                            double B,\n                                            Kokkos::View<Rfit::circle_fit*, KokkosExecSpace> vcircle_fit,\n                                            const int& i) {\n  double* __restrict__ phits = vhits.data();\n  float* __restrict__ phits_ge = vhits_ge.data();\n  double* __restrict__ pfast_fit_input = vfast_fit_input.data();\n  Rfit::circle_fit* __restrict__ pcircle_fit = vcircle_fit.data();\n\n  Rfit::Map3xNd<N> hits(phits + i, 3, N);\n  Rfit::Map4d fast_fit_input(pfast_fit_input + i, 4);\n  Rfit::Map6xNf<N> hits_ge(phits_ge + i, 6, N);\n\n  constexpr auto n = N;\n\n  Rfit::VectorNd<N> rad = (hits.block(0, 0, 2, n).colwise().norm());\n  Rfit::Matrix2Nd<N> hits_cov = MatrixXd::Zero(2 * n, 2 * n);\n  Rfit::loadCovariance2D(hits_ge, hits_cov);\n\n#ifdef TEST_DEBUG\n  if (0 == i) {\n    printf(\"hits %f, %f\\n\", hits.block(0, 0, 2, n)(0, 0), hits.block(0, 0, 2, n)(0, 1));\n    printf(\"hits %f, %f\\n\", hits.block(0, 0, 2, n)(1, 0), hits.block(0, 0, 2, n)(1, 1));\n    printf(\"fast_fit_input(0): %f\\n\", fast_fit_input(0));\n    printf(\"fast_fit_input(1): %f\\n\", fast_fit_input(1));\n    printf(\"fast_fit_input(2): %f\\n\", fast_fit_input(2));\n    printf(\"fast_fit_input(3): %f\\n\", fast_fit_input(3));\n    printf(\"rad(0,0): %f\\n\", rad(0, 0));\n    printf(\"rad(1,1): %f\\n\", rad(1, 1));\n    printf(\"rad(2,2): %f\\n\", rad(2, 2));\n    printf(\"hits_cov(0,0): %f\\n\", (*hits_cov)(0, 0));\n    printf(\"hits_cov(1,1): %f\\n\", (*hits_cov)(1, 1));\n    printf(\"hits_cov(2,2): %f\\n\", (*hits_cov)(2, 2));\n    printf(\"hits_cov(11,11): %f\\n\", (*hits_cov)(11, 11));\n    printf(\"B: %f\\n\", B);\n  }\n#endif\n  pcircle_fit[i] = Rfit::Circle_fit(hits.block(0, 0, 2, n), hits_cov, fast_fit_input, rad, B, true);\n#ifdef TEST_DEBUG\n  if (0 == i) {\n    printf(\"Circle param %f,%f,%f\\n\", pcircle_fit[i].par(0), pcircle_fit[i].par(1), pcircle_fit[i].par(2));\n  }\n#endif\n}\n\ntemplate <int N>\nKOKKOS_INLINE_FUNCTION void kernelLineFit(Kokkos::View<double*, KokkosExecSpace> vhits,\n                                          Kokkos::View<float*, KokkosExecSpace> vhits_ge,\n                                          double B,\n                                          Kokkos::View<Rfit::circle_fit*, KokkosExecSpace> vcircle_fit,\n                                          Kokkos::View<double*, KokkosExecSpace> vfast_fit_input,\n                                          Kokkos::View<Rfit::line_fit*, KokkosExecSpace> vline_fit,\n                                          const int& i) {\n  double* __restrict__ phits = vhits.data();\n  float* __restrict__ phits_ge = vhits_ge.data();\n  Rfit::circle_fit* __restrict__ circle_fit = vcircle_fit.data();\n  double* __restrict__ pfast_fit_input = vfast_fit_input.data();\n  Rfit::line_fit* __restrict__ line_fit = vline_fit.data();\n\n  Rfit::Map3xNd<N> hits(phits + i, 3, N);\n  Rfit::Map4d fast_fit_input(pfast_fit_input + i, 4);\n  Rfit::Map6xNf<N> hits_ge(phits_ge + i, 6, N);\n  line_fit[i] = Rfit::Line_fit(hits, hits_ge, circle_fit[i], fast_fit_input, B, true);\n}\n#endif\n\ntemplate <typename M3xN, typename M6xN>\nKOKKOS_INLINE_FUNCTION void fillHitsAndHitsCov(M3xN& hits, M6xN& hits_ge) {\n  constexpr uint32_t N = M3xN::ColsAtCompileTime;\n\n  if (N == 5) {\n    hits << 2.934787, 6.314229, 8.936963, 10.360559, 12.856387, 0.773211, 1.816356, 2.765734, 3.330824, 4.422212,\n        -10.980247, -23.162731, -32.759060, -38.061260, -47.518867;\n    hits_ge.col(0) << 1.424715e-07, -4.996975e-07, 1.752614e-06, 3.660689e-11, 1.644638e-09, 7.346080e-05;\n    hits_ge.col(1) << 6.899177e-08, -1.873414e-07, 5.087101e-07, -2.078806e-10, -2.210498e-11, 4.346079e-06;\n    hits_ge.col(2) << 1.406273e-06, 4.042467e-07, 6.391180e-07, -3.141497e-07, 6.513821e-08, 1.163863e-07;\n    hits_ge.col(3) << 1.176358e-06, 2.154100e-07, 5.072816e-07, -8.161219e-08, 1.437878e-07, 5.951832e-08;\n    hits_ge.col(4) << 2.852843e-05, 7.956492e-06, 3.117701e-06, -1.060541e-06, 8.777413e-09, 1.426417e-07;\n    return;\n  }\n\n  if (N > 3)\n    hits << 1.98645, 4.72598, 7.65632, 11.3151, 2.18002, 4.88864, 7.75845, 11.3134, 2.46338, 6.99838, 11.808, 17.793;\n  else\n    hits << 1.98645, 4.72598, 7.65632, 2.18002, 4.88864, 7.75845, 2.46338, 6.99838, 11.808;\n\n  hits_ge.col(0)[0] = 7.14652e-06;\n  hits_ge.col(1)[0] = 2.15789e-06;\n  hits_ge.col(2)[0] = 1.63328e-06;\n  if (N > 3)\n    hits_ge.col(3)[0] = 6.27919e-06;\n  hits_ge.col(0)[2] = 6.10348e-06;\n  hits_ge.col(1)[2] = 2.08211e-06;\n  hits_ge.col(2)[2] = 1.61672e-06;\n  if (N > 3)\n    hits_ge.col(3)[2] = 6.28081e-06;\n  hits_ge.col(0)[5] = 5.184e-05;\n  hits_ge.col(1)[5] = 1.444e-05;\n  hits_ge.col(2)[5] = 6.25e-06;\n  if (N > 3)\n    hits_ge.col(3)[5] = 3.136e-05;\n  hits_ge.col(0)[1] = -5.60077e-06;\n  hits_ge.col(1)[1] = -1.11936e-06;\n  hits_ge.col(2)[1] = -6.24945e-07;\n  if (N > 3)\n    hits_ge.col(3)[1] = -5.28e-06;\n}\n\ntemplate <int N>\nKOKKOS_INLINE_FUNCTION void kernelFillHitsAndHitsCov(Kokkos::View<double*, KokkosExecSpace> vhits,\n                                                     Kokkos::View<float*, KokkosExecSpace> vhits_ge,\n                                                     const int& i) {\n  double* __restrict__ phits = vhits.data();\n  float* __restrict__ phits_ge = vhits_ge.data();\n\n  Rfit::Map3xNd<N> hits(phits + i, 3, N);\n  Rfit::Map6xNf<N> hits_ge(phits_ge + i, 6, N);\n  hits_ge = MatrixXf::Zero(6, N);\n  fillHitsAndHitsCov(hits, hits_ge);\n}\n\ntemplate <int N>\nvoid testFit() {\n  constexpr double B = 0.0113921;\n\n  Kokkos::View<double*, KokkosExecSpace> d_hits(\"d_hits\", Rfit::maxNumberOfTracks() * sizeof(Rfit::Matrix3xNd<N>));\n  Kokkos::View<float*, KokkosExecSpace> d_hits_ge(\"d_hits_ge\", Rfit::maxNumberOfTracks() * sizeof(Rfit::Matrix6xNf<N>));\n  Kokkos::View<double*, KokkosExecSpace> d_fast_fit_results(\"d_fast_fit_results\",\n                                                            Rfit::maxNumberOfTracks() * sizeof(Vector4d));\n  Kokkos::View<Rfit::line_fit*, KokkosExecSpace> d_line_fit_results(\"d_line_fit_results\",\n                                                                    Rfit::maxNumberOfTracks() * sizeof(Rfit::line_fit));\n  Kokkos::View<Rfit::circle_fit*, KokkosExecSpace> d_circle_fit_results(\n      \"d_circle_fit_results\", Rfit::maxNumberOfTracks() * sizeof(Rfit::circle_fit));\n\n  Rfit::Matrix3xNd<N> hits;\n  Rfit::Matrix6xNf<N> hits_ge = MatrixXf::Zero(6, N);\n\n  double* fast_fit_resultsGPUret = new double[Rfit::maxNumberOfTracks() * sizeof(Vector4d)];\n  Rfit::circle_fit* circle_fit_resultsGPUret = new Rfit::circle_fit();\n  Rfit::line_fit* line_fit_resultsGPUret = new Rfit::line_fit();\n\n  fillHitsAndHitsCov(hits, hits_ge);\n\n  std::cout << \"sizes \" << N << ' ' << sizeof(hits) << ' ' << sizeof(hits_ge) << ' ' << sizeof(Vector4d) << ' '\n            << sizeof(Rfit::line_fit) << ' ' << sizeof(Rfit::circle_fit) << std::endl;\n\n  std::cout << \"Generated hits:\\n\" << hits << std::endl;\n  std::cout << \"Generated cov:\\n\" << hits_ge << std::endl;\n\n  // FAST_FIT_CPU\n  Vector4d fast_fit_results;\n#ifdef USE_BL\n  BrokenLine::BL_Fast_fit(hits, fast_fit_results);\n#else\n  Rfit::Fast_fit(hits, fast_fit_results);\n#endif\n  std::cout << \"Fitted values (FastFit, [X0, Y0, R, tan(theta)]):\\n\" << fast_fit_results << std::endl;\n\n  // cudaMemset d_fast_fit_results & d_line_fit_results to 0\n  Kokkos::deep_copy(KokkosExecSpace(), d_fast_fit_results, 0);\n  // Kokkos::deep_copy(KokkosExecSpace(), d_line_fit_results, 0) will result in compilation error:\n  // no instance of overloaded function \"Kokkos::deep_copy\" matches the argument list. argument\n  // types are: (KokkosExecSpace, Kokkos::View<kokkos_cuda::Rfit::line_fit *, KokkosExecSpace>, int).\n  // Use for loop instead\n  Kokkos::parallel_for(\n      \"init_line_fit_res\",\n      Kokkos::RangePolicy<KokkosExecSpace>(KokkosExecSpace(), 0, Rfit::maxNumberOfTracks()),\n      KOKKOS_LAMBDA(const int& i) {\n        d_line_fit_results(i).par = Vector2d::Zero();\n        d_line_fit_results(i).cov = Matrix2d::Zero();\n        d_line_fit_results(i).chi2 = 0.;\n      });\n\n  // for timing purposes we fit 4096 tracks\n  constexpr uint32_t Ntracks = 4096;\n\n  auto policy = Kokkos::RangePolicy<KokkosExecSpace>(KokkosExecSpace(), 0, Ntracks);\n\n  Kokkos::parallel_for(\n      \"kernelPrintSizes\", policy, KOKKOS_LAMBDA(const int& i) { kernelPrintSizes<N>(d_hits, d_hits_ge, i); });\n  Kokkos::parallel_for(\n      \"kernelFillHitsAndHitsCov\", policy, KOKKOS_LAMBDA(const int& i) {\n        kernelFillHitsAndHitsCov<N>(d_hits, d_hits_ge, i);\n      });\n\n  // FAST_FIT GPU\n  Kokkos::parallel_for(\n      \"kernelFastFit\", policy, KOKKOS_LAMBDA(const int& i) { kernelFastFit<N>(d_hits, d_fast_fit_results, i); });\n  KokkosExecSpace().fence();\n\n  auto h_fast_fit_results = Kokkos::create_mirror_view(d_fast_fit_results);\n  Kokkos::deep_copy(KokkosExecSpace(), h_fast_fit_results, d_fast_fit_results);\n  KokkosExecSpace().fence();\n\n  auto* presults = h_fast_fit_results.data();\n  Rfit::Map4d fast_fit(presults + 10, 4);\n  std::cout << \"Fitted values (FastFit, [X0, Y0, R, tan(theta)]): GPU\\n\" << fast_fit << std::endl;\n  assert(isEqualFuzzy(fast_fit_results, fast_fit));\n\n#ifdef USE_BL\n  // CIRCLE AND LINE FIT CPU\n  BrokenLine::PreparedBrokenLineData<N> data;\n  BrokenLine::karimaki_circle_fit circle_fit_results;\n  Rfit::line_fit line_fit_results;\n  Rfit::Matrix3d Jacob;\n  BrokenLine::prepareBrokenLineData(hits, fast_fit_results, B, data);\n  BrokenLine::BL_Line_fit(hits_ge, fast_fit_results, B, data, line_fit_results);\n  BrokenLine::BL_Circle_fit(hits, hits_ge, fast_fit_results, B, data, circle_fit_results);\n  Jacob << 1., 0, 0, 0, 1., 0, 0, 0,\n      -B / std::copysign(Rfit::sqr(circle_fit_results.par(2)), circle_fit_results.par(2));\n  circle_fit_results.par(2) = B / std::abs(circle_fit_results.par(2));\n  circle_fit_results.cov = Jacob * circle_fit_results.cov * Jacob.transpose();\n\n  // fit on device\n  Kokkos::parallel_for(\n      \"kernelBrokenLineFit\", policy, KOKKOS_LAMBDA(const int& i) {\n        kernelBrokenLineFit<N>(d_hits, d_hits_ge, d_fast_fit_results, B, d_circle_fit_results, d_line_fit_results, i);\n      });\n  KokkosExecSpace().fence();\n\n#else\n  // CIRCLE_FIT CPU\n  Rfit::VectorNd<N> rad = (hits.block(0, 0, 2, N).colwise().norm());\n\n  Rfit::Matrix2Nd<N> hits_cov = Rfit::Matrix2Nd<N>::Zero();\n  Rfit::loadCovariance2D(hits_ge, hits_cov);\n  Rfit::circle_fit circle_fit_results =\n      Rfit::Circle_fit(hits.block(0, 0, 2, N), hits_cov, fast_fit_results, rad, B, true);\n\n  // CIRCLE_FIT GPU\n  Kokkos::parallel_for(\n      \"kernelCircleFit\", policy, KOKKOS_LAMBDA(const int& i) {\n        kernelCircleFit<N>(d_hits, d_hits_ge, d_fast_fit_results, B, d_circle_fit_results, i);\n      });\n  KokkosExecSpace().fence();\n\n  // LINE_FIT CPU\n  Rfit::line_fit line_fit_results = Rfit::Line_fit(hits, hits_ge, circle_fit_results, fast_fit_results, B, true);\n\n  Kokkos::parallel_for(\n      \"kernelLineFit\", policy, KOKKOS_LAMBDA(const int& i) {\n        kernelLineFit<N>(d_hits, d_hits_ge, B, d_circle_fit_results, d_fast_fit_results, d_line_fit_results, i);\n      });\n  KokkosExecSpace().fence();\n\n#endif\n\n  std::cout << \"Fitted values (CircleFit):\\n\" << circle_fit_results.par << std::endl;\n\n  auto h_circle_fit_results = Kokkos::create_mirror_view(d_circle_fit_results);\n  Kokkos::deep_copy(KokkosExecSpace(), h_circle_fit_results, d_circle_fit_results);\n  auto* p_circle_fit_res = h_circle_fit_results.data();\n\n  std::cout << \"Fitted values (CircleFit) GPU:\\n\" << p_circle_fit_res->par << std::endl;\n  assert(isEqualFuzzy(circle_fit_results.par, p_circle_fit_res->par));\n\n  std::cout << \"Fitted values (LineFit):\\n\" << line_fit_results.par << std::endl;\n\n  // LINE_FIT GPU\n  auto h_line_fit_results = Kokkos::create_mirror_view(d_line_fit_results);\n  Kokkos::deep_copy(KokkosExecSpace(), h_line_fit_results, d_line_fit_results);\n  auto* p_line_fit_res = h_line_fit_results.data();\n  std::cout << \"Fitted values (LineFit) GPU:\\n\" << p_line_fit_res->par << std::endl;\n  assert(isEqualFuzzy(line_fit_results.par, p_line_fit_res->par, N == 5 ? 1e-4 : 1e-6));  // requires fma on CPU\n\n  std::cout << \"Fitted cov (CircleFit) CPU:\\n\" << circle_fit_results.cov << std::endl;\n  std::cout << \"Fitted cov (LineFit): CPU\\n\" << line_fit_results.cov << std::endl;\n  std::cout << \"Fitted cov (CircleFit) GPU:\\n\" << p_circle_fit_res->cov << std::endl;\n  std::cout << \"Fitted cov (LineFit): GPU\\n\" << p_line_fit_res->cov << std::endl;\n}\n\nint main(int argc, char* argv[]) {\n  kokkos_common::InitializeScopeGuard kokkosGuard({KokkosBackend<KokkosExecSpace>::value});\n  testFit<4>();\n  testFit<3>();\n  testFit<5>();\n\n  std::cout << \"TEST FIT, NO ERRORS\" << std::endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "ccb3403d47f1b2b68df56c46cad0da37e31513b3", "size": 17073, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/kokkos/test/kokkos/testEigenGPU.cc", "max_stars_repo_name": "alexstrel/pixeltrack-standalone", "max_stars_repo_head_hexsha": "0b625eef0ef0b5c0f018d9b466457c5575b3442c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2021-03-02T08:40:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T14:31:40.000Z", "max_issues_repo_path": "src/kokkos/test/kokkos/testEigenGPU.cc", "max_issues_repo_name": "alexstrel/pixeltrack-standalone", "max_issues_repo_head_hexsha": "0b625eef0ef0b5c0f018d9b466457c5575b3442c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 158.0, "max_issues_repo_issues_event_min_datetime": "2020-03-22T19:46:40.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-24T09:51:35.000Z", "max_forks_repo_path": "src/kokkos/test/kokkos/testEigenGPU.cc", "max_forks_repo_name": "alexstrel/pixeltrack-standalone", "max_forks_repo_head_hexsha": "0b625eef0ef0b5c0f018d9b466457c5575b3442c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-03-20T15:18:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T16:58:07.000Z", "avg_line_length": 42.364764268, "max_line_length": 120, "alphanum_fraction": 0.6419492766, "num_tokens": 5513, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4579025195033161}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2015 Johannes Goettker-Schnetmann\n Copyright (C) 2015 Klaus Spanderen\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n/*! \\file hestonblackvolsurface.hpp\n    \\brief Black volatility surface back by Heston model\n*/\n\n#include <ql/math/functional.hpp>\n#include <ql/math/solvers1d/brent.hpp>\n#include <ql/time/calendars/nullcalendar.hpp>\n#include <ql/pricingengines/blackformula.hpp>\n#include <ql/termstructures/volatility/equityfx/hestonblackvolsurface.hpp>\n\n#include <boost/bind.hpp>\n#include <boost/make_shared.hpp>\n\n#include <limits>\n\nnamespace QuantLib {\n\n    namespace {\n        Real blackValue(Option::Type optionType, Real strike,\n                        Real forward, Real maturity,\n                        Volatility vol, Real discount, Real npv) {\n\n            return blackFormula(optionType, strike, forward,\n                                std::max(0.0, vol)*std::sqrt(maturity),\n                                discount)-npv;\n        }\n    }\n\n    HestonBlackVolSurface::HestonBlackVolSurface(\n        const Handle<HestonModel>& hestonModel)\n    : BlackVolTermStructure(\n          hestonModel->process()->riskFreeRate()->referenceDate(),\n          NullCalendar(),\n          Following,\n          hestonModel->process()->riskFreeRate()->dayCounter()),\n      hestonModel_(hestonModel),\n      integration_(AnalyticHestonEngine::Integration::gaussLaguerre(164)) {\n        registerWith(hestonModel_);\n    }\n\n    DayCounter HestonBlackVolSurface::dayCounter() const {\n        return hestonModel_->process()->riskFreeRate()->dayCounter();\n    }\n    Date HestonBlackVolSurface::maxDate() const {\n        return Date::maxDate();\n    }\n    Real HestonBlackVolSurface::minStrike() const {\n        return 0.0;\n    }\n    Real HestonBlackVolSurface::maxStrike() const {\n        return std::numeric_limits<Real>::max();\n    }\n\n    Real HestonBlackVolSurface::blackVarianceImpl(Time t, Real strike) const {\n        return square<Real>()(blackVolImpl(t, strike))*t;\n    }\n\n    Volatility HestonBlackVolSurface::blackVolImpl(Time t, Real strike) const {\n        const boost::shared_ptr<HestonProcess> process = hestonModel_->process();\n\n        const DiscountFactor df = process->riskFreeRate()->discount(t, true);\n        const DiscountFactor div = process->dividendYield()->discount(t, true);\n        const Real spotPrice = process->s0()->value();\n\n        const Real fwd = spotPrice\n            * process->dividendYield()->discount(t, true)\n            / process->riskFreeRate()->discount(t, true);\n\n\n        const PlainVanillaPayoff payoff(\n            fwd > strike ? Option::Put : Option::Call, strike);\n\n        const Real kappa = hestonModel_->kappa();\n        const Real theta = hestonModel_->theta();\n        const Real rho   = hestonModel_->rho();\n        const Real sigma = hestonModel_->sigma();\n        const Real v0    = hestonModel_->v0();\n\n        const AnalyticHestonEngine::ComplexLogFormula cpxLogFormula\n            = AnalyticHestonEngine::Gatheral;\n\n        const AnalyticHestonEngine* const hestonEnginePtr = 0;\n\n        Real npv;\n        Size evaluations;\n\n        AnalyticHestonEngine::doCalculation(\n            df, div, spotPrice, strike, t,\n            kappa, theta, sigma, v0, rho,\n            payoff, integration_, cpxLogFormula,\n            hestonEnginePtr, npv, evaluations);\n\n        if (npv <= 0.0) return std::sqrt(theta);\n\n        Brent solver;\n        solver.setMaxEvaluations(10000);\n        const Volatility guess = std::sqrt(theta);\n        const Real accuracy = std::numeric_limits<Real>::epsilon();\n\n        const boost::function<Real(Real)> f = boost::bind(\n            &blackValue, payoff.optionType(), strike, fwd, t, _1, df, npv);\n\n        return solver.solve(f, accuracy, guess, 0.01);\n    }\n}\n", "meta": {"hexsha": "60d8482f280af50b569370ca9cf5366efa0c8f23", "size": 4463, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ql/termstructures/volatility/equityfx/hestonblackvolsurface.cpp", "max_stars_repo_name": "grandtiger/quantlib", "max_stars_repo_head_hexsha": "4cf3d80ffc071ae74f026bb25fbb1dd9093e6301", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 41.0, "max_stars_repo_stars_event_min_datetime": "2016-03-19T02:31:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T13:23:20.000Z", "max_issues_repo_path": "ql/termstructures/volatility/equityfx/hestonblackvolsurface.cpp", "max_issues_repo_name": "grandtiger/quantlib", "max_issues_repo_head_hexsha": "4cf3d80ffc071ae74f026bb25fbb1dd9093e6301", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-02-02T20:32:43.000Z", "max_issues_repo_issues_event_max_datetime": "2015-02-02T20:32:43.000Z", "max_forks_repo_path": "ql/termstructures/volatility/equityfx/hestonblackvolsurface.cpp", "max_forks_repo_name": "grandtiger/quantlib", "max_forks_repo_head_hexsha": "4cf3d80ffc071ae74f026bb25fbb1dd9093e6301", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2016-03-17T14:14:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T10:33:19.000Z", "avg_line_length": 35.4206349206, "max_line_length": 81, "alphanum_fraction": 0.6576293973, "num_tokens": 1083, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186768138228, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4579025139952042}}
{"text": "/** * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n * @file ClothoidSpline-LMSolver.cc\n * @author Matteo Ragni (info@ragni.me)\n *\n * @copyright Copyright (c) 2022 Matteo Ragni\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#ifdef G2LIB_LMSOLVE_CLOTHOID_SPLINE\n\n#include \"Clothoids/ClothoidSpline-Interpolation.hxx\"\n\n#include <vector>\n#include <algorithm>\n#include <stdexcept>\n#include <Eigen/Eigen>\n#include <unsupported/Eigen/LevenbergMarquardt>\n\nnamespace G2lib {\n  namespace Interpolation {\n\n    using G2lib::ClothoidSplineG2;\n    using G2lib::int_type;\n    using G2lib::real_type;\n    typedef Eigen::SparseFunctor<real_type, int_type> SparseFunctor;\n\n    /* Levemberg Marquardt Solver */\n    class LMSolver : public Solver {\n      struct ClothoidSplineProblem : SparseFunctor {\n        LMSolver &             m_solver;\n        std::vector<int_type>  m_jacobian_rows;\n        std::vector<int_type>  m_jacobian_cols;\n        std::vector<real_type> m_jacobian_result;\n\n        ClothoidSplineProblem(LMSolver & solver);\n        int operator()(const SparseFunctor::InputType & theta, SparseFunctor::ValueType & constraints_value) const;\n        int df(const SparseFunctor::InputType & theta, SparseFunctor::JacobianType & jacobian_value);\n      };\n\n     public:\n      LMSolver(const ClothoidSplineG2 & spline) : Solver(spline) {};\n      virtual Result solve() override;\n    };\n\n    LMSolver::ClothoidSplineProblem::ClothoidSplineProblem(LMSolver & solver)\n        : SparseFunctor(solver.theta_size(), solver.constraints_size()), m_solver(solver),\n          m_jacobian_rows(std::vector<int_type>(solver.jacobian_pattern_size(), 0)),\n          m_jacobian_cols(std::vector<int_type>(solver.jacobian_pattern_size(), 0)),\n          m_jacobian_result(std::vector<real_type>(solver.jacobian_pattern_size(), 0.0)) {\n      m_solver.spline().jacobian_pattern(&m_jacobian_rows.front(), &m_jacobian_cols.front());\n    }\n\n    int LMSolver::ClothoidSplineProblem::operator()(\n        const SparseFunctor::InputType & theta, SparseFunctor::ValueType & constraints_value) const {\n      if (m_solver.spline().constraints(theta.data(), constraints_value.data()))\n        return 0;\n      return 1;\n    }\n\n    int LMSolver::ClothoidSplineProblem::df(\n        const SparseFunctor::InputType & theta, SparseFunctor::JacobianType & jacobian_value) {\n      if (!(m_solver.spline().jacobian(theta.data(), &m_jacobian_result.front())))\n        return 1;\n      for (int i = 0; i < m_solver.jacobian_pattern_size(); i++) {\n        jacobian_value.coeffRef(m_jacobian_rows[i], m_jacobian_cols[i]) = m_jacobian_result[i];\n      }\n      jacobian_value.makeCompressed();\n      return 0;\n    }\n\n    Result LMSolver::solve() {\n      LMSolver::ClothoidSplineProblem problem(*this);\n      Eigen::LevenbergMarquardt<LMSolver::ClothoidSplineProblem> lm(problem);\n      lm.setFtol(1e-20);\n\n      Eigen::VectorXd theta_opts = Eigen::VectorXd::Map(theta_solution().data(), theta_solution().size());\n      lm.minimize(theta_opts);\n      Eigen::ComputationInfo info = lm.info();\n      std::copy(theta_opts.data(), theta_opts.data() + theta_opts.size(), theta_solution().begin());\n\n      switch (info) {\n        case (Eigen::Success):\n          return Result(ResultType::Success, lm.fnorm(), static_cast<int_type>(lm.iterations()));\n          break;\n        case (Eigen::NumericalIssue):\n          return Result(ResultType::NumericalIssue, lm.fnorm(), static_cast<int_type>(lm.iterations()));\n          break;\n        case (Eigen::NoConvergence):\n          return Result(ResultType::NoConvergence, lm.fnorm(), static_cast<int_type>(lm.iterations()));\n          break;\n        case (Eigen::InvalidInput):\n          return Result(ResultType::InvalidInput, lm.fnorm(), static_cast<int_type>(lm.iterations()));\n          break;\n      }\n      return Result(ResultType::InternalError);\n    }\n\n    Result Interpolator::buildP1(real_type theta_0, real_type theta_1, ClothoidList & result) {\n      m_spline.setP1(theta_0, theta_1);\n      build_clothoid_spline();\n      LMSolver solver(m_spline);\n      solver.guess();\n      auto status = solver.solve();\n      build_clothoid_list(solver.theta_solution(), result);\n      return status;\n    }\n\n    Result Interpolator::buildP2(ClothoidList & result) {\n      m_spline.setP2();\n      build_clothoid_spline();\n      LMSolver solver(m_spline);\n      solver.guess();\n      auto status = solver.solve();\n      build_clothoid_list(solver.theta_solution(), result);\n      return status;\n    }\n\n  } /* namespace Interpolation */\n} /* namespace G2lib */\n\n#endif", "meta": {"hexsha": "ec30627e3a9bce06bf5e1f496fff4f16b44d00f7", "size": 5696, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/ClothoidSpline-LMSolver.cc", "max_stars_repo_name": "MatteoRagni/Clothoids-1", "max_stars_repo_head_hexsha": "b7fa270e65ba291a67ff3a3612810595fa436d0f", "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/ClothoidSpline-LMSolver.cc", "max_issues_repo_name": "MatteoRagni/Clothoids-1", "max_issues_repo_head_hexsha": "b7fa270e65ba291a67ff3a3612810595fa436d0f", "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/ClothoidSpline-LMSolver.cc", "max_forks_repo_name": "MatteoRagni/Clothoids-1", "max_forks_repo_head_hexsha": "b7fa270e65ba291a67ff3a3612810595fa436d0f", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.2753623188, "max_line_length": 115, "alphanum_fraction": 0.6739817416, "num_tokens": 1424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.45776858191620806}}
{"text": "#pragma comment(linker, \"/STACK:100000000\")\n#pragma comment(linker, \"/HEAP:1000000000\")\n\n#include <iostream>\n#include <fstream>\n#include <Eigen/Dense>\n#include \"Lookup.h\"\n#include <random>\n#include <string>\n#include <algorithm>\n#include <thread>\n#include <iterator>\nusing std::string;\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\n#include <chrono>\n\nfloat Q_rsqrt(float number)\n{\n\tlong i;\n\tfloat x2, y;\n\tconst float threehalfs = 1.5F;\n\n\tx2 = number * 0.5F;\n\ty = number;\n\ti = *(long *)&y;                       // evil floating point bit level hacking\n\ti = 0x5f3759df - (i >> 1);               // what the fuck? \n\ty = *(float *)&i;\n\ty = y * (threehalfs - (x2 * y * y));   // 1st iteration\n\t\t\t\t\t\t\t\t\t\t   //\ty  = y * ( threehalfs - ( x2 * y * y ) );   // 2nd iteration, this can be removed\n\n\treturn y;\n}\n\nvoid call_from_thread() {\n\tstd::cout << \"Hello, World\" << std::endl;\n\t\n}\nfloat get_random(float min, float max)\n{\n\tstatic std::mt19937_64 rng(std::chrono::system_clock::now().time_since_epoch().count());\n\tstd::uniform_real_distribution<> dis(min, max);\n\treturn dis(rng);\n}\n\nstring GetInput(string message) {\n\tprintf(message.c_str());\n\tstring response;\n\tstd::getline(std::cin, response);\n\n\treturn response;\n}\n\nvoid Write(string filename, string value) {\n\tstd::ofstream file;\n\tfile.open(filename);\n\tfile << value.c_str();\n\tfile.close();\n}\n\nstring Read(string filename) {\n\t{\n\t\tstring line;\n\t\tstd::ifstream input(filename);\n\t\tif (input.is_open())\n\t\t{\n\t\t\tstd::stringstream strStream;\n\t\t\tstrStream << input.rdbuf();//read the file\n\t\t\treturn strStream.str();//str holds the content of the file\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn \"\";\n\t\t}\n\t}\n}\n\nvoid MakeLower(string& value) {\n\tstd::transform(value.begin(), value.end(), value.begin(), ::tolower);\n}\n\nint main()\n{\n\tauto inputFile = GetInput(\"Please enter full filename to train chain from : \\n\");\n\tauto outputFile = GetInput(\"Please enter full filename set output to : \\n\");\n\n\tauto defaults = split(Read(\"default.ini\"), v<string>(\"\\n\"));\n\tbool usedDefaults = false;\n\n\tif (inputFile == \"\") {\n\t\tinputFile = defaults[0];\n\t\tbool usedDefaults = true;\n\t}\n\tif (outputFile == \"\") {\n\t\toutputFile = defaults[1];\n\t\tbool usedDefaults = true;\n\t}\n\n\tif (!usedDefaults)\n\t\tWrite(\"default.ini\", inputFile + \"\\n\" + outputFile);\n\n\tstring trainingText = \"\";\n\n\n\n\t{\n\t\tstring line;\n\t\tstd::ifstream input(inputFile);\n\t\tif (input.is_open())\n\t\t{\n\t\t\tstd::stringstream strStream;\n\t\t\tstrStream << input.rdbuf();//read the file\n\t\t\ttrainingText = strStream.str();//str holds the content of the file\n\t\t}\n\t\telse {\n\t\t\treturn 0;\n\t\t}\n\t}\n\tauto words = split(trainingText, v<string>(\" \", \"\t \", \".\", \",\", \"(\", \")\", \";\", \"\\\"\", \"-\", \"!\", \":\", \"?\"));\n\t\n\n\n\tMatrixXd m(2, 2);\n\tm(0, 0) = 3;\n\tm(1, 0) = 2.;\n\tm(0, 1) = -1;\n\tm(1, 1) = m(1, 0) + m(0, 1);\n\tstd::cout << m << std::endl;\n\tLookup lookup;\n\tauto result = lookup.Convert(words);\n\tauto resultSize = (int)result.size();\n\tauto lookupSize = (int)lookup.size();\n\n\tMatrixXd data = MatrixXd::Zero(lookupSize, lookupSize);\n\n\tfor (int index = 0; index < resultSize; index++) {\n\t\tfor (int subIndex = std::max(0, index - 5); subIndex < std::min(resultSize, index + 30); subIndex++) {\n\t\t\tdouble weight = 5;\n\t\t\tif (subIndex < index)\n\t\t\t\tweight = 0.2;\n\t\t\telse if (subIndex == index)\n\t\t\t\tcontinue;\n\n\t\t\t//auto change = weight / pow(index - subIndex, 2);\n\t\t\tdata(result[subIndex], result[index]) += weight / pow(abs(index - subIndex), 1.2);\n\t\t//\tdata(result[subIndex], result[index]) = std::max(0.0, data(result[subIndex], result[index]));\n\t\t}\n\t}\n\n\tfor (int index = 0; index < data.cols(); index++) {\n\t\tdata.col(index) /= data.col(index).sum();\n\t}\n\n\tVectorXd input = VectorXd::Zero(lookupSize);\n\tinput[0] = 1;\n\n\tvector<int> textOutput(500);\n\n\tstring finalResult = \"\";\n\tfor (int i = 0; i < 500; i++) {\n\t\tinput = data * input;\n\t\t//auto max = input[0];\n\t\t//max = input[0];\n\t\t//auto maxIndex = 0;\n\n\t\t//for (int index = 1; index < lookupSize; index++) {\n\t\t//\tmaxIndex = input[index] > max ? index : maxIndex;\n\n\t\t//\tif (maxIndex == index) {\n\t\t//\t\tmax = input[index];\n\t\t//\t}\n\t\t//}\n\n\t\tfloat potSize = (float)input.sum();\n\t\tauto random = (double)get_random(0, potSize);\n\n\t\tint index = 0;\n\t\tfor (double cursor = 0; cursor + input[index] < random; cursor += input[index]) {\n\t\t\tindex++;\n\t\t}\n\t\t\n\t\tinput[index] = 1;\n\n\t\ttextOutput[i] = index;\n\t\tfinalResult = join(lookup.Extract<string>(textOutput, \"\"), \" \");\n\t\tstd::cout << finalResult + \"\\n\";\n\t}\n\n\n\tWrite(outputFile, finalResult);\n\n\tint i = 0;\n}", "meta": {"hexsha": "a5c5ea22be49e1429d313d12f348c120b7a5229f", "size": 4407, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "MarkovTaxtGenerator/src/main.cpp", "max_stars_repo_name": "nathanwblair/markov", "max_stars_repo_head_hexsha": "38d5ec5d3068d643d75a6cf2de4c641ec625306e", "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": "MarkovTaxtGenerator/src/main.cpp", "max_issues_repo_name": "nathanwblair/markov", "max_issues_repo_head_hexsha": "38d5ec5d3068d643d75a6cf2de4c641ec625306e", "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": "MarkovTaxtGenerator/src/main.cpp", "max_forks_repo_name": "nathanwblair/markov", "max_forks_repo_head_hexsha": "38d5ec5d3068d643d75a6cf2de4c641ec625306e", "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": 22.8341968912, "max_line_length": 107, "alphanum_fraction": 0.6137962333, "num_tokens": 1295, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893335913536, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.45776858191620806}}
{"text": "#ifndef _MLES_NN_HPP_\n#define _MLES_NN_HPP_\n\n#include \"Activation.hpp\"\n#include \"DataSet.hpp\"\n#include \"Layer.hpp\"\n#include \"Training.hpp\"\n#include <Eigen/Dense>\n#include <memory>\n#include <stdarg.h>\n#include <string>\n#include <time.h>\n#include <vector>\n\nnamespace mles\n{\n    class NN\n    {\n      private:\n        bool isVerbose;\n        unsigned int inputSize, outputSize;\n        ActivationPtr defaultActivation;\n        ActivationPtr outputActivation;\n        std::vector<unsigned int> layersSize;\n        std::vector<ActivationPtr> layersActivation;\n        std::vector<Layer> layers;\n\n        bool transformInput, transformOutput;\n        Eigen::VectorXd inputA, inputB;\n        Eigen::VectorXd outputA, outputB;\n\n        std::vector<ActivationPtr> supportedActivations;\n        ActivationPtr getActivation(const std::string &name, bool allowDefault = false);\n        void init();\n        void reset();\n\n      public:\n        NN();\n        NN(unsigned int inputSize, unsigned int outputSize);\n        virtual ~NN();\n\n        void verbose(bool v);\n\n        template <class A> void registerActivation()\n        {\n            supportedActivations.push_back(ActivationPtr(new A()));\n        }\n\n        void setInputSize(unsigned int size);\n        void setOutputSize(unsigned int size);\n        void setOutputActivation(std::string name = \"\", ...);\n        void setDefaultActivation(std::string name = \"\", ...);\n        void setOutputActivationVec(std::string name, std::vector<double> &args);\n        void setDefaultActivationVec(std::string name, std::vector<double> &args);\n\n        Eigen::VectorXd createInputVector();\n        Eigen::VectorXd createOutputVector();\n\n        void setInputTransformation(const Eigen::VectorXd &a, const Eigen::VectorXd &b);\n        void setOutputTransformation(const Eigen::VectorXd &a, const Eigen::VectorXd &b);\n\n        void addLayer(unsigned int size, std::string name = \"\", ...);\n        void insertLayer(unsigned int pos, unsigned int size, std::string name = \"\", ...);\n        void changeLayer(unsigned int pos, unsigned int size, std::string name = \"\", ...);\n        void removeLayer(unsigned int pos);\n        void addLayerVec(unsigned int size, std::string name, std::vector<double> &args);\n        void insertLayerVec(unsigned int pos, unsigned int size, std::string name, std::vector<double> &args);\n        void changeLayerVec(unsigned int pos, unsigned int size, std::string name, std::vector<double> &args);\n\n        TrainingResults train(DataSet &trainingSet, const TrainingSettings &settings);\n        void test(DataSet &testSet);\n        Eigen::VectorXd test(const Eigen::VectorXd &data);\n\n        bool load(const std::string &fileName);\n        bool save(const std::string &fileName);\n        void print();\n        void build();\n\n        DataSet createDataSet();\n    };\n} // namespace mles\n\n#endif\n", "meta": {"hexsha": "92b854f7495c2524189318d10f5ab8d2b0d11ff0", "size": 2853, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/lib/mles/NN.hpp", "max_stars_repo_name": "AlexanderSilvaB/mles", "max_stars_repo_head_hexsha": "e1bc81de8a0a4625343500a69ebd0001729ad654", "max_stars_repo_licenses": ["MIT"], "max_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/mles/NN.hpp", "max_issues_repo_name": "AlexanderSilvaB/mles", "max_issues_repo_head_hexsha": "e1bc81de8a0a4625343500a69ebd0001729ad654", "max_issues_repo_licenses": ["MIT"], "max_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/mles/NN.hpp", "max_forks_repo_name": "AlexanderSilvaB/mles", "max_forks_repo_head_hexsha": "e1bc81de8a0a4625343500a69ebd0001729ad654", "max_forks_repo_licenses": ["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.9642857143, "max_line_length": 110, "alphanum_fraction": 0.6533473537, "num_tokens": 607, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185944046238981, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.4577667743903437}}
{"text": "/*!\n * Copyright (C) tkornuta, IBM Corporation 2015-2019\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 RandomGenerator.hpp\n * \\brief Contains declaration of a random generator singleton.\n * \\author tkornuta\n * \\date Dec 24, 2015\n */\n\n#ifndef SRC_DATA_UTILS_RANDOMGENERATOR_HPP_\n#define SRC_DATA_UTILS_RANDOMGENERATOR_HPP_\n\n#include <boost/atomic.hpp>\n#include <boost/thread/mutex.hpp>\n\n#include <random>\n\nnamespace mic {\nnamespace utils {\n\n/*!\n * \\brief Random generator - defined in the form of a singleton, with double-checked locking pattern (DCLP) based access to instance.\n * \\author tkornuta\n */\nclass RandomGenerator {\npublic:\n\n\t/*!\n\t * Method for accessing the object instance, with double-checked locking optimization.\n\t * @return Instance of ApplicationState singleton.\n\t */\n\tstatic RandomGenerator* getInstance();\n\n\n\t/*!\n\t * Return a random integer from range <0, RAND_MAX> - uniform distribution.\n\t * @return Random integer.\n\t */\n\tuint64_t uniRandInt(int min = 0, int max = RAND_MAX);\n\n\t/*!\n\t * Return a random real number from range <min, max> - uniform distribution.\n\t * @param min Min value.\n\t * @param max Max value.\n\t * @return Random real value.\n\t */\n\tdouble uniRandReal(double min = 0, double max = 1);\n\n\t/*!\n\t * Return a random real number - normal distribution.\n\t * @param mean Mean.\n\t * @param variance Variance.\n\t * @return Random real value.\n\t */\n\tdouble normRandReal(double mean = 0, double variance = 1);\n\nprivate:\n    /*!\n     * Private instance - accessed as atomic operation.\n     */\n\tstatic boost::atomic<RandomGenerator*> instance_;\n\n\t/*!\n\t * Mutex used for instantiation of the instance.\n\t */\n\tstatic boost::mutex instantiation_mutex;\n\n\t/*!\n\t * Private constructor. Initialize pseudo-random generator and distributions parameters.\n\t */\n\tRandomGenerator();\n\n\t/*!\n\t * Random device used for generation of random numbers.\n\t */\n\tstd::random_device rd;\n\n\t/*!\n\t *  Mersenne Twister pseudo-random generator of 32-bit numbers with a state size of 19937 bits.\n\t */\n\tstd::mt19937_64 rng_mt19937_64;\n\n\t/// Uniform distribution from 0 to RAND_MAX (integers).\n\tstd::uniform_int_distribution<> uniform_int_dist;\n\n\t/// Uniform distribution from 0 to 1 (real values).\n\tstd::uniform_real_distribution<> uniform_real_dist;\n\n\t/// Normal distribution from 0 to 1 (real values).\n\tstd::normal_distribution<> normal_real_dist;\n\n};\n\n/*!\n * \\brief Macro returning random generator instance.\n * \\author tkornuta\n */\n#define RAN_GEN mic::utils::RandomGenerator::getInstance()\n\n\n} /* namespace utils */\n} /* namespace mic */\n\n#endif /* SRC_DATA_UTILS_RANDOMGENERATOR_HPP_ */\n", "meta": {"hexsha": "135d9c48ebc9dbb42e88436181304061af44c344", "size": 3109, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/utils/RandomGenerator.hpp", "max_stars_repo_name": "kant/mi-algorithms", "max_stars_repo_head_hexsha": "7e510577f57cb5e7d36c9d2506b61395739b0bef", "max_stars_repo_licenses": ["Apache-2.0"], "max_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/RandomGenerator.hpp", "max_issues_repo_name": "kant/mi-algorithms", "max_issues_repo_head_hexsha": "7e510577f57cb5e7d36c9d2506b61395739b0bef", "max_issues_repo_licenses": ["Apache-2.0"], "max_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/RandomGenerator.hpp", "max_forks_repo_name": "kant/mi-algorithms", "max_forks_repo_head_hexsha": "7e510577f57cb5e7d36c9d2506b61395739b0bef", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-30T09:51:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-30T09:51:14.000Z", "avg_line_length": 26.3474576271, "max_line_length": 133, "alphanum_fraction": 0.7201672564, "num_tokens": 719, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6370308082623217, "lm_q2_score": 0.7185943925708562, "lm_q1q2_score": 0.45776676671218464}}
{"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 *      110527    L. van der Ham    File created.\n *      110602    L. van der Ham    Made LibrationPoints class and added comments.\n *      110707    L. van der Ham    Make code compatible with Tudat revision 114.\n *      110629    L. van der Ham    Modifications according to comments first code check.\n *      110710    K. Kumar          Removed duplicated code; modified libration point\n *                                  compute-functions; changed filename and class; L1 and L2\n *                                  function coefficient discrepancies spotted.\n *      110712    L. van der Ham    Changed L1, L2 and L3 function coefficients.\n *      110927    L. van der Ham    Reverted to full equations of motion for determination location\n *                                  of colinear libration points.\n *      111027    K. Kumar          Moved 1-line functions to header file.\n *      120307    K. Kumar          Moved file.\n *      120326    D. Dirkx          Changed raw pointers to shared pointers.\n *      120813    P. Musegaas       Changed code to new root finding structure.\n *\n *    References\n *      van der Ham, L. Interplanetary trajectory design using dynamical systems theory,\n *          MSc thesis, Delft University of Technology, Delft, The Netherlands, 2012.\n *      Mireles James, J.D. Celestial Mechanics Notes Set 4: The Circular Restricted Three Body\n *          Problem, 2006, http://www.math.utexas.edu/users/jjames/hw4Notes.pdf,\n *          last accessed: 18th May, 2012.\n *\n *    Notes\n *      WARNING: There seems to be a bug in the computation of the L3 location!\n *\n */\n\n#include <cmath>\n#include <iostream>\n#include <stdexcept>\n\n#include <boost/bind.hpp>\n#include <boost/exception/all.hpp>\n\n#include \"Tudat/Astrodynamics/Gravitation/librationPoint.h\"\n#include \"Tudat/Mathematics/BasicMathematics/functionProxy.h\"\n\nnamespace tudat\n{\nnamespace gravitation\n{\nnamespace circular_restricted_three_body_problem\n{\n\nusing namespace root_finders;\nusing namespace basic_mathematics;\n\n//! Compute location of Lagrange libration point.\nvoid LibrationPoint::computeLocationOfLibrationPoint(\n        LagrangeLibrationPoints lagrangeLibrationPoint )\n{\n    using std::pow;\n    using std::sqrt;\n\n    // Set functions for Newton-Raphson based on collinear libration point passed as input\n    // parameter, or computed locations directly of equilateral libration points.\n    switch( lagrangeLibrationPoint )\n    {\n    case l1:\n    {\n        // Create an object containing the function of which we whish to obtain the root from.\n        UnivariateProxyPointer rootFunction = boost::make_shared< UnivariateProxy >(\n                    boost::bind( &LibrationPoint::computeL1LocationFunction, this, _1 ) );\n\n        // Add the first derivative of the root function.\n        rootFunction->addBinding( -1, boost::bind( &LibrationPoint::\n                computeL1FirstDerivativeLocationFunction, this, _1 ) );\n\n        // Set position vector of L1 in Cartesian elements based on result of Newton-Raphson\n        // root-finding algorithm.\n        positionOfLibrationPoint_ << rootFinder->execute( rootFunction, 1.0 ), 0.0, 0.0;\n    }\n        break;\n\n    case l2:\n    {\n        // Create an object containing the function of which we whish to obtain the root from.\n        UnivariateProxyPointer rootFunction = boost::make_shared< UnivariateProxy >(\n                    boost::bind( &LibrationPoint::computeL2LocationFunction, this, _1 ) );\n\n        // Add the first derivative of the root function.\n        rootFunction->addBinding( -1, boost::bind( &LibrationPoint::\n                computeL2FirstDerivativeLocationFunction, this, _1 ) );\n\n        // Set position vector of L1 in Cartesian elements based on result of Newton-Raphson\n        // root-finding algorithm.\n        positionOfLibrationPoint_ << rootFinder->execute( rootFunction, 1.0 ), 0.0, 0.0;\n    }\n        break;\n\n    case l3:\n    {\n        // Create an object containing the function of which we whish to obtain the root from.\n        UnivariateProxyPointer rootFunction = boost::make_shared< UnivariateProxy >(\n                    boost::bind( &LibrationPoint::computeL3LocationFunction, this, _1 ) );\n\n        // Add the first derivative of the root function.\n        rootFunction->addBinding( -1, boost::bind( &LibrationPoint::\n                computeL3FirstDerivativeLocationFunction, this, _1 ) );\n\n        // Set position vector of L1 in Cartesian elements based on result of Newton-Raphson\n        // root-finding algorithm.\n        positionOfLibrationPoint_ << rootFinder->execute( rootFunction, -1.0 ), 0.0, 0.0;\n    }\n        break;\n\n    case l4:\n\n        // Set position vector of L4 in Cartesian elements.\n        positionOfLibrationPoint_.x( ) = 0.5 - massParameter;\n        positionOfLibrationPoint_.y( ) = 0.5 * sqrt( 3.0 );\n        positionOfLibrationPoint_.z( ) = 0.0;\n\n        break;\n\n    case l5:\n\n        // Set position vector of L5 in Cartesian elements.\n        positionOfLibrationPoint_.x( ) = 0.5 - massParameter;\n        positionOfLibrationPoint_.y( ) = -0.5 * sqrt( 3.0 );\n        positionOfLibrationPoint_.z( ) = 0.0;\n\n        break;\n\n    default:\n\n        boost::throw_exception(\n                    boost::enable_error_info(\n                        std::runtime_error(\n                            \"The Lagrange libration point requested does not exist.\" ) ) );\n    };\n}\n\n} // namespace circular_restricted_three_body_problem\n} // namespace gravitation\n} // namespace tudat\n", "meta": {"hexsha": "56646dd8f84fa4f44ccd0f135e331b6fbfef5602", "size": 7217, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/Gravitation/librationPoint.cpp", "max_stars_repo_name": "JPelamatti/ThesisTUDAT", "max_stars_repo_head_hexsha": "b94ce35fb7c8fa44ae83238e296a979dfa3adfe8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tudat/Astrodynamics/Gravitation/librationPoint.cpp", "max_issues_repo_name": "JPelamatti/ThesisTUDAT", "max_issues_repo_head_hexsha": "b94ce35fb7c8fa44ae83238e296a979dfa3adfe8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tudat/Astrodynamics/Gravitation/librationPoint.cpp", "max_forks_repo_name": "JPelamatti/ThesisTUDAT", "max_forks_repo_head_hexsha": "b94ce35fb7c8fa44ae83238e296a979dfa3adfe8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-05-30T03:42:22.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-30T03:42:22.000Z", "avg_line_length": 44.2760736196, "max_line_length": 99, "alphanum_fraction": 0.6705002078, "num_tokens": 1660, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.4577667667121846}}
{"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__COMPAT__ODEINT_HPP_\n#define SMOOTH__COMPAT__ODEINT_HPP_\n\n/**\n * @file\n * @brief boost::odeint compatability header.\n */\n\n#include <boost/numeric/odeint/algebra/operations_dispatcher.hpp>\n\n#include \"smooth/concepts.hpp\"\n\n\nnamespace smooth\n{\n\n/**\n * @brief \\p boost::odeint Stepper operations for Manifold types.\n *\n * \\p boost::odeint Butcher tableaus are evaluated by weighted\n * calculations of the form y = \u03a3_{i=1}^n alpha_i x_i which are generically\n * implemented.\n *\n * However, for the special case of butcher tableaus it holds that alpha_1 = 1,\n * and furthermore x_1 is always of the state type while x_2 ... x_n are\n * of the derivative type. The scale sum can therefore be generalized to the Lie\n * group case as\n *\n *   y = x_1 * exp(\u03a3_{i=2}^n alpha_i x_i)\n *\n * The methods below inject those calculations into boost:odeint to enable\n * numerical integration on Lie groups. For succintness we implement a single\n * method using variadic templates.\n */\nstruct BoostOdeintOps\n{\n  /**\n   * @brief Variadic scale_sum implementation.\n   */\n  template<typename ... Fac>\n  struct scale_sum\n  {\n    //! Storage for scale sum weights.\n    const std::tuple<Fac ...> m_alpha;\n\n    //! Constructor for scale sum.\n    scale_sum(Fac ... alpha)\n    : m_alpha(alpha ...)\n    {\n      if (std::get<0>(m_alpha) != std::tuple_element_t<0, std::tuple<Fac...>>(1)) {\n        throw std::runtime_error(\"BoostOdeintOps only valid for alpha1 = 1\");\n      }\n    }\n\n    //! Helper for scaled addition operation.\n    template<typename ... Ts, std::size_t ... Is>\n    auto helper(std::index_sequence<Is...>, const Ts & ... as)\n    {\n      // plus 1 since alpha1 = 1 is not included in Ts...\n      return ((std::get<Is + 1>(m_alpha) * as) + ...);\n    }\n\n    //! Scaled addition operation.\n    template<Manifold T1, Manifold T2, typename ... Ts>\n    requires std::is_same_v<T1, T2>&&\n    std::conjunction_v<std::is_same<typename T1::Tangent, Ts>...>\n    void operator()(T1 & y, const T2 & x, const Ts & ... as)\n    {\n      y = x + helper(std::make_index_sequence<sizeof...(Ts)>(), as...);\n    }\n\n    //! Required typedef.\n    using result_type = void;\n  };\n\n  // \\cond\n  template<typename Fac1, typename Fac2 = Fac1>\n  using scale_sum2 = scale_sum<Fac1, Fac2>;\n\n  template<typename Fac1, typename Fac2 = Fac1, typename Fac3 = Fac2>\n  using scale_sum3 = scale_sum<Fac1, Fac2, Fac3>;\n\n  template<typename Fac1, typename Fac2 = Fac1, typename Fac3 = Fac2, typename Fac4 = Fac3>\n  using scale_sum4 = scale_sum<Fac1, Fac2, Fac3, Fac4>;\n\n  template<typename Fac1, typename Fac2 = Fac1, typename Fac3 = Fac2, typename Fac4 = Fac3, typename Fac5 = Fac4>\n  using scale_sum5 = scale_sum<Fac1, Fac2, Fac3, Fac4, Fac5>;\n\n  template<typename Fac1, typename Fac2 = Fac1, typename Fac3 = Fac2, typename Fac4 = Fac3, typename Fac5 = Fac4, typename Fac6 = Fac5>\n  using scale_sum6 = scale_sum<Fac1, Fac2, Fac3, Fac4, Fac5, Fac6>;\n\n  template<typename Fac1, typename Fac2 = Fac1, typename Fac3 = Fac2, typename Fac4 = Fac3, typename Fac5 = Fac4, typename Fac6 = Fac5, typename Fac7 = Fac6>\n  using scale_sum7 = scale_sum<Fac1, Fac2, Fac3, Fac4, Fac5, Fac6, Fac7>;\n\n  template<typename Fac1, typename Fac2 = Fac1, typename Fac3 = Fac2, typename Fac4 = Fac3, typename Fac5 = Fac4, typename Fac6 = Fac5, typename Fac7 = Fac6, typename Fac8 = Fac7>\n  using scale_sum8 = scale_sum<Fac1, Fac2, Fac3, Fac4, Fac5, Fac6, Fac7, Fac8>;\n\n  template<typename Fac1, typename Fac2 = Fac1, typename Fac3 = Fac2, typename Fac4 = Fac3, typename Fac5 = Fac4, typename Fac6 = Fac5, typename Fac7 = Fac6, typename Fac8 = Fac7, typename Fac9 = Fac8>\n  using scale_sum9 = scale_sum<Fac1, Fac2, Fac3, Fac4, Fac5, Fac6, Fac7, Fac8, Fac9>;\n\n  template<typename Fac1, typename Fac2 = Fac1, typename Fac3 = Fac2, typename Fac4 = Fac3, typename Fac5 = Fac4, typename Fac6 = Fac5, typename Fac7 = Fac6, typename Fac8 = Fac7, typename Fac9 = Fac8, typename Fac10 = Fac9>\n  using scale_sum10 = scale_sum<Fac1, Fac2, Fac3, Fac4, Fac5, Fac6, Fac7, Fac8, Fac9, Fac10>;\n\n  template<typename Fac1, typename Fac2 = Fac1, typename Fac3 = Fac2, typename Fac4 = Fac3, typename Fac5 = Fac4, typename Fac6 = Fac5, typename Fac7 = Fac6, typename Fac8 = Fac7, typename Fac9 = Fac8, typename Fac10 = Fac9, typename Fac11 = Fac10>\n  using scale_sum11 = scale_sum<Fac1, Fac2, Fac3, Fac4, Fac5, Fac6, Fac7, Fac8, Fac9, Fac10, Fac11>;\n\n  template<typename Fac1, typename Fac2 = Fac1, typename Fac3 = Fac2, typename Fac4 = Fac3, typename Fac5 = Fac4, typename Fac6 = Fac5, typename Fac7 = Fac6, typename Fac8 = Fac7, typename Fac9 = Fac8, typename Fac10 = Fac9, typename Fac11 = Fac10, typename Fac12 = Fac11>\n  using scale_sum12 = scale_sum<Fac1, Fac2, Fac3, Fac4, Fac5, Fac6, Fac7, Fac8, Fac9, Fac10, Fac11, Fac12>;\n\n  template<typename Fac1, typename Fac2 = Fac1, typename Fac3 = Fac2, typename Fac4 = Fac3, typename Fac5 = Fac4, typename Fac6 = Fac5, typename Fac7 = Fac6, typename Fac8 = Fac7, typename Fac9 = Fac8, typename Fac10 = Fac9, typename Fac11 = Fac10, typename Fac12 = Fac11, typename Fac13 = Fac12>\n  using scale_sum13 = scale_sum<Fac1, Fac2, Fac3, Fac4, Fac5, Fac6, Fac7, Fac8, Fac9, Fac10, Fac11, Fac12, Fac13>;\n\n  template<typename Fac1, typename Fac2 = Fac1, typename Fac3 = Fac2, typename Fac4 = Fac3, typename Fac5 = Fac4, typename Fac6 = Fac5, typename Fac7 = Fac6, typename Fac8 = Fac7, typename Fac9 = Fac8, typename Fac10 = Fac9, typename Fac11 = Fac10, typename Fac12 = Fac11, typename Fac13 = Fac12, typename Fac14 = Fac13>\n  using scale_sum14 = scale_sum<Fac1, Fac2, Fac3, Fac4, Fac5, Fac6, Fac7, Fac8, Fac9, Fac10, Fac11, Fac12, Fac13, Fac14>;\n  // \\endcond\n};\n\n}  // namespace smooth\n\n/**\n * @brief SFINAE dispatcher for Manifold types.\n */\n// \\cond\ntemplate<smooth::LieGroup G>\nstruct boost::numeric::odeint::operations_dispatcher_sfinae<G, void>\n{\n  using operations_type = ::smooth::BoostOdeintOps;\n};\n// \\endcond\n\n#endif  // SMOOTH__COMPAT__ODEINT_HPP_\n", "meta": {"hexsha": "3972fe8ac40dc6c3ad5f24c574b445e5c6007370", "size": 7178, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/smooth/compat/odeint.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/compat/odeint.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/compat/odeint.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": 45.7197452229, "max_line_length": 320, "alphanum_fraction": 0.7084146002, "num_tokens": 2099, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185944046238981, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.4577667644867198}}
{"text": "//\r\n// OpenTissue, A toolbox for physical based simulation and animation.\r\n// Copyright (C) 2007 Department of Computer Science, University of Copenhagen\r\n//\r\n#include <OpenTissue/configuration.h>\r\n\r\n#include <OpenTissue/core/math/math_basic_types.h>\r\n#include <OpenTissue/collision/gjk/gjk_outside_triangle.h>\r\n\r\n#define BOOST_AUTO_TEST_MAIN\r\n#include <OpenTissue/utility/utility_push_boost_filter.h>\r\n#include <boost/test/auto_unit_test.hpp>\r\n#include <boost/test/unit_test_suite.hpp>\r\n#include <boost/test/floating_point_comparison.hpp>\r\n#include <boost/test/test_tools.hpp>\r\n#include <OpenTissue/utility/utility_pop_boost_filter.h>\r\n\r\n#include <cmath>\r\n\r\nusing namespace OpenTissue;\r\n\r\nBOOST_AUTO_TEST_SUITE(opentissue_collision_gjk_outside_triangle);\r\n\r\nBOOST_AUTO_TEST_CASE(case_by_case_test)\r\n{\r\n  typedef OpenTissue::math::BasicMathTypes<double, size_t> math_types;\r\n  typedef math_types::vector3_type                         V;\r\n\r\n  V const a = V(0.0, 0.0, 0.0);\r\n  V const b = V(1.0, 0.0, 0.0);;\r\n  V const c = V(0.0, 1.0, 0.0);;\r\n  V const q = V(0.33, 0.33, -1.0);\r\n\r\n  {\r\n    V p = V(0.33, 0.33,  1.0);\r\n    bool outside = OpenTissue::gjk::detail::outside_triangle(p, a, b, c, q );\r\n    BOOST_CHECK( outside );\r\n  }\r\n  {\r\n    V p = V(0.1, 0.1,  -1.0);\r\n    bool outside = OpenTissue::gjk::detail::outside_triangle(p, a, b, c, q );\r\n    BOOST_CHECK( !outside );\r\n  }\r\n  {\r\n    V p = V(0.1, 0.1,  0.0);\r\n    bool outside = OpenTissue::gjk::detail::outside_triangle(p, a, b, c, q );\r\n    BOOST_CHECK( outside );\r\n  }\r\n}\r\n\r\nBOOST_AUTO_TEST_SUITE_END();\r\n", "meta": {"hexsha": "7e06f0207edf435c2cd660989771bbf36d741022", "size": 1562, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/collision/gjk/outside_triangle/src/unit_outside_tri.cpp", "max_stars_repo_name": "ricortiz/OpenTissue", "max_stars_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 76.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:45:06.000Z", "max_issues_repo_path": "unit_tests/collision/gjk/outside_triangle/src/unit_outside_tri.cpp", "max_issues_repo_name": "ricortiz/OpenTissue", "max_issues_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2018-11-20T14:32:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T15:26:45.000Z", "max_forks_repo_path": "unit_tests/collision/gjk/outside_triangle/src/unit_outside_tri.cpp", "max_forks_repo_name": "ricortiz/OpenTissue", "max_forks_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2018-02-21T01:45:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T07:06:49.000Z", "avg_line_length": 30.0384615385, "max_line_length": 79, "alphanum_fraction": 0.6709346991, "num_tokens": 461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185944046238982, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.45776676448671977}}
{"text": "#ifndef ALEPH_MATH_BOOTSTRAP_HH__\n#define ALEPH_MATH_BOOTSTRAP_HH__\n\n#include <aleph/math/KahanSummation.hh>\n\n#include <boost/math/distributions/students_t.hpp>\n\n#include <algorithm>\n#include <iterator>\n#include <random>\n#include <vector>\n\n#include <cmath>\n\nnamespace aleph\n{\n\nnamespace math\n{\n\n/**\n  @class Bootstrap\n  @brief Generic bootstrap functor\n\n  This functor provides a generic interface for performing bootstrap\n  operations on *arbitrary* data, using an *arbitrary* statistic for\n  testing. Several convenience functions for estimating *confidence*\n  values are provided.\n*/\n\nclass Bootstrap\n{\npublic:\n\n  /**\n    Given a range of data of some type, calculates a set of bootstrap replicates\n    for a desired statistic. This function will not perform any type conversions\n    in order to preserve all original types. The type of the output data depends\n    on the return value type of the functor.\n\n    @param[in]  numSamples samples Number of bootstrap samples\n    @param[in]  begin      Input iterator to begin of data range\n    @param[in]  end        Input iterator to end of data range\n    @param[in]  functor    Functor for calculating a statistic on the replicate\n    @param[out] result     Output iterator for storing the results\n  */\n\n  template <class InputIterator, class OutputIterator, class Functor>\n  void makeReplicates( unsigned numSamples,\n                       InputIterator begin, InputIterator end,\n                       Functor functor,\n                       OutputIterator result )\n  {\n    using SampleValueType  = typename std::iterator_traits<InputIterator>::value_type;\n    using FunctorValueType = decltype( functor( begin, end ) );\n\n    std::vector<SampleValueType> samples( begin, end );\n\n    // We cannot continue anyway, so let's just be nice and stop. This\n    // does *not* constitute an error condition, though, because users\n    // might just be weird when calling this function with empty data.\n    if( samples.empty() )\n      return;\n\n    std::random_device rd;\n    std::mt19937 rng( rd() );\n\n    std::uniform_int_distribution<std::size_t> distribution( 0, samples.size() - 1 );\n\n    std::vector<FunctorValueType> replicates;\n    replicates.reserve( numSamples );\n\n    for( unsigned sampleIndex = 0; sampleIndex < numSamples; sampleIndex++ )\n    {\n      std::vector<SampleValueType> sample;\n      sample.reserve( samples.size() );\n\n      for( std::size_t i = 0; i < samples.size(); i++ )\n        sample.push_back( samples.at( distribution( rng ) ) );\n\n      replicates.push_back( functor( sample.begin(),\n                                     sample.end() ) );\n    }\n\n    std::copy( replicates.begin(), replicates.end(), result );\n  }\n\n  /**\n    Calculates a bootstrap estimate of the standard error of a test\n    statistics on a data set.\n\n    @param numSamples Number of bootstrap samples\n    @param begin      Input iterator to begin of data range\n    @param end        Input iterator to end of data range\n    @param functor    Functor to describe the test statistics that is to be\n                      calculated on the data range. The functor has to take\n                      the `value_type` of the range as a parameter, because\n                      the function will show the individual samples to it.\\n\n\n                      A good example of a functor is the following *mean*\n                      functor:\\n\n\n    \\code{.cpp}\n    auto meanCalculation = [] ( auto begin, auto end )\n    {\n      using T  = typename std::iterator_traits<decltype(begin)>::value_type;\n      auto sum = std::accumulate( begin, end, T() );\n\n      return static_cast<double>( sum / static_cast<double>( std::distance(begin, end) ) );\n    };\n    \\endcode\n                     Note that the functor requires `C++14` because the use\n                     of `auto` in a lambda expression.\n\n    @returns Bootstrapped estimated of the standard error\n  */\n\n  template <class InputIterator, class Functor>\n  double standardError( unsigned numSamples,\n                        InputIterator begin, InputIterator end,\n                        Functor functor )\n  {\n    using FunctorValueType = decltype( functor(begin, end) );\n\n    std::vector<FunctorValueType> estimates;\n    estimates.reserve( numSamples );\n\n    this->makeReplicates( numSamples,\n                          begin, end,\n                          functor,\n                          std::back_inserter( estimates ) );\n\n    using namespace aleph::math;\n\n    double mean  = static_cast<double>( accumulate_kahan( estimates.begin(), estimates.end(), FunctorValueType() ) );\n    mean        /= numSamples;\n\n    std::vector<double> sampleSquaredDeviations;\n    sampleSquaredDeviations.reserve( numSamples );\n\n    for( auto&& estimate : estimates )\n    {\n      auto delta  = mean - estimate;\n      delta      *= delta;\n\n      sampleSquaredDeviations.push_back( delta );\n    }\n\n    double sumSquaredDeviations\n      = accumulate_kahan_sorted(\n          sampleSquaredDeviations.begin(),\n          sampleSquaredDeviations.end(),\n          0.0 );\n\n    sumSquaredDeviations /= (numSamples - 1);\n    return std::sqrt( static_cast<double>( sumSquaredDeviations ) );\n  }\n\n  template <class InputIterator, class Functor>\n  auto basicConfidenceInterval( unsigned numSamples,\n                                double alpha,\n                                InputIterator begin, InputIterator end,\n                                Functor functor ) -> std::pair< decltype( functor(begin, end) ), decltype( functor(begin, end) ) >\n  {\n    auto theta             = functor( begin, end );\n    using FunctorValueType = decltype( theta );\n\n    std::vector<FunctorValueType> estimates;\n    estimates.reserve( numSamples );\n\n    this->makeReplicates( numSamples,\n                          begin, end,\n                          functor,\n                          std::back_inserter( estimates ) );\n\n    std::sort( estimates.begin(), estimates.end() );\n\n    auto upperPercentile = alpha / 2;\n    auto upperEstimate   = estimates.at( Bootstrap::index( numSamples, upperPercentile ) );\n    auto lowerPercentile = 1 - upperPercentile;\n    auto lowerEstimate   = estimates.at( Bootstrap::index( numSamples, lowerPercentile ) );\n\n    return std::make_pair( 2*theta - lowerEstimate, 2*theta - upperEstimate );\n  }\n\n  template <class InputIterator, class Functor>\n  auto percentileConfidenceInterval( unsigned numSamples,\n                                     double alpha,\n                                     InputIterator begin, InputIterator end,\n                                     Functor functor ) -> std::pair< decltype( functor(begin, end) ), decltype( functor(begin, end) ) >\n  {\n    using FunctorValueType = decltype( functor( begin, end ) );\n\n    std::vector<FunctorValueType> estimates;\n    estimates.reserve( numSamples );\n\n    this->makeReplicates( numSamples,\n                          begin, end,\n                          functor,\n                          std::back_inserter( estimates ) );\n\n    std::sort( estimates.begin(), estimates.end() );\n\n    auto lowerPercentile = alpha / 2;\n    auto lowerEstimate   = estimates.at( Bootstrap::index( numSamples, lowerPercentile ) );\n    auto upperPercentile = 1 - lowerPercentile;\n    auto upperEstimate   = estimates.at( Bootstrap::index( numSamples, upperPercentile ) );\n\n    return std::make_pair( lowerEstimate, upperEstimate );\n  }\n\n  template <class InputIterator, class Functor>\n  auto studentConfidenceInterval( unsigned numSamples,\n                                  double alpha,\n                                  InputIterator begin, InputIterator end,\n                                  Functor functor ) -> std::pair< decltype( functor(begin, end) ), decltype( functor(begin, end) ) >\n  {\n    auto theta = functor( begin, end );\n\n    boost::math::students_t distribution( static_cast<double>( std::distance( begin, end ) - 1 ) );\n\n    auto tl = boost::math::quantile( distribution, 1 - alpha );\n    auto tu = boost::math::quantile( distribution,     alpha );\n    auto se = this->standardError( numSamples,\n                                   begin, end,\n                                   functor );\n\n    return std::make_pair( theta - tl * se, theta - tu * se );\n  }\n\n  /** Calculates index at a certain percentile of the data */\n  static unsigned index( unsigned int samples, double alpha )\n  {\n    // This accounts for rounding and works regardless of whether\n    // the product samples * alpha is an integer or not. Note the\n    // offset of -1. It is required because, say, the 100th value\n    // is at index 99 of the vector.\n    return static_cast<unsigned>( std::ceil( samples * alpha ) ) - 1;\n  }\n};\n\n} // namespace math\n\n} // namespace aleph\n\n#endif\n", "meta": {"hexsha": "1e6ccae7d3121b852b89132a7eee7d5d12f4e448", "size": 8685, "ext": "hh", "lang": "C++", "max_stars_repo_path": "include/aleph/math/Bootstrap.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/math/Bootstrap.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/math/Bootstrap.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": 35.1619433198, "max_line_length": 135, "alphanum_fraction": 0.6256764537, "num_tokens": 1867, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708562, "lm_q2_score": 0.6370308013713525, "lm_q1q2_score": 0.4577667617603728}}
{"text": "/*\n// Copyright (c) 2018 Intel Corporation\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n*/\n\n///////////////////////////////////////////////////////////////////////////////////////////////////\n#include <gtest/gtest.h>\n#include \"api/CPP/memory.hpp\"\n#include <api/CPP/input_layout.hpp>\n#include \"api/CPP/embed.hpp\"\n#include <api/CPP/topology.hpp>\n#include <api/CPP/tensor.hpp>\n#include <api/CPP/network.hpp>\n#include <api/CPP/engine.hpp>\n#include <api/CPP/data.hpp>\n#include <boost/filesystem.hpp>\n#include \"test_utils/test_utils.h\"\n\n\n#include <cmath>\n\nusing namespace cldnn;\nusing namespace tests;\n\n\nTEST(embed_gpu, seq3num4) {\n    //  Input  : 1x1x1x3\n    //  Weights: 4x1x3x1\n    //  Bias   : 1x1x1x4\n    //  Output : 1x3x4x1\n    //  Input:\n    //   1.0    2.0   0.0\n    //\n    //  Weights:\n    //   1.0    1.0   1.0    1.0\n    //   2.0    2.0   2.0    2.0\n    //   3.0    3.0   3.0    3.0\n    //  Biases:\n    //   1.0    2.0   3.0    4.0\n    //\n    //  Output:\n    //   2.0    4.0   6.0    8.0\n    //   0.0    0.0   0.0    0.0\n    //   6.0    8.0  -2.0   -2.0\n\n    engine engine;\n    auto batch = 1;\n    auto sequence_length = 3;\n    auto num_output_size = 4;\n    auto vocab_size = 3;\n    auto input_prim = memory::allocate(engine, { data_types::f32,format::bfyx,{ batch, 1, 1, sequence_length } });\n    auto weights_prim = memory::allocate(engine, { data_types::f32,format::bfyx,{ num_output_size, 1, vocab_size, 1 } });\n    auto bias_prim = memory::allocate(engine, { data_types::f32,format::bfyx,{ batch, 1, 1, num_output_size } });\n    auto output_ref = memory::allocate(engine, { data_types::f32,format::bfyx,{ batch, sequence_length, num_output_size, 1 } });\n\n    set_values(input_prim, { 1.0f, 2.0f, 0.0f });\n    set_values(weights_prim, { 1.0f, 1.0f, 1.0f, 1.0f,\n        2.0f, 2.0f, 2.0f, 2.0f,\n        3.0f, 3.0f, 3.0f, 3.0f });\n    set_values(bias_prim, { 1.0f, 2.0f, 3.0f, 4.0f });\n    set_values(output_ref, { 3.0f, 4.0f, 5.0f, 6.0f,\n        4.0f, 5.0f, 6.0f, 7.0f,\n        2.0f, 3.0f, 4.0f, 5.0f });\n\n    auto input = input_layout(\"input\", input_prim.get_layout());\n    auto w_data = data(\"weights\", weights_prim);\n    auto b_data = data(\"bias\", bias_prim);\n\n    auto embed_test = embed(\"embed_prim\", \"input\", \"weights\", \"bias\");\n    topology topology;\n    topology.add(input);\n    topology.add(w_data);\n    topology.add(b_data);\n    topology.add(embed_test);\n\n    network network(engine, topology);\n    network.set_input_data(\"input\", input_prim);\n\n    auto outputs = network.execute();\n    EXPECT_EQ(outputs.size(), size_t(1));\n    EXPECT_EQ(outputs.begin()->first, \"embed_prim\");\n\n    auto output_prim = outputs.begin()->second.get_memory();\n    auto ref = output_ref.pointer<float>();\n    auto output_ptr = output_prim.pointer<float>();\n    for (auto i = 0; i < batch * sequence_length * num_output_size; i++) {\n        EXPECT_EQ(ref[i], output_ptr[i]);\n    }\n\n}\n\nTEST(embed_gpu, b2seq2num3) {\n    //  Input  : 2x1x1x2\n    //  Weights: 3x1x3x1\n    //  Bias   : 1x1x1x4\n    //  Output : 1x3x4x1\n    //  Input:\n    //   0.0    1.0\n    //   2.0    0.0\n    //\n    //  Weights:\n    //  -1.0   -2.0  -3.0 \n    //  -1.0    2.0   0.0 \n    //   10.0   16.0  15.0 \n    //  Biases:\n    //   0.0    2.0   4.0\n    //\n    //  Output:\n    //   -1.0   0.0   1.0   -1.0   4.0   4.0\n    //    10.0  18.0  19.0  -1.0   0.0   1.0\n\n    engine engine;\n    auto batch = 2;\n    auto sequence_length = 2;\n    auto num_output_size = 3;\n    auto vocab_size = 3;\n    auto input_prim = memory::allocate(engine, { data_types::f32,format::bfyx,{ batch, 1, 1, sequence_length } });\n    auto weights_prim = memory::allocate(engine, { data_types::f32,format::bfyx,{ num_output_size, 1, vocab_size, 1 } });\n    auto bias_prim = memory::allocate(engine, { data_types::f32,format::bfyx,{ 1, 1, 1, num_output_size } });\n    auto output_ref = memory::allocate(engine, { data_types::f32,format::bfyx,{ batch, sequence_length, num_output_size, 1 } });\n\n    set_values(input_prim, { 0.0f, 1.0f, 2.0f, 0.0f });\n    set_values(weights_prim, { -1.0f, -2.0f, -3.0f,\n        -1.0f,  2.0f,  0.0f,\n        10.0f, 16.0f, 15.0f });\n    set_values(bias_prim, { 0.0f, 2.0f, 4.0f });\n    set_values(output_ref, { -1.0f, 0.0f, 1.0f, -1.0f, 4.0f, 4.0f,\n        10.0f, 18.0f, 19.0f, -1.0f, 0.0f, 1.0f });\n\n    auto input = input_layout(\"input\", input_prim.get_layout());\n    auto w_data = data(\"weights\", weights_prim);\n    auto b_data = data(\"bias\", bias_prim);\n\n    auto embed_test = embed(\"embed_prim\", \"input\", \"weights\", \"bias\");\n    topology topology;\n    topology.add(input);\n    topology.add(w_data);\n    topology.add(b_data);\n    topology.add(embed_test);\n\n    network network(engine, topology);\n    network.set_input_data(\"input\", input_prim);\n\n    auto outputs = network.execute();\n    EXPECT_EQ(outputs.size(), size_t(1));\n    EXPECT_EQ(outputs.begin()->first, \"embed_prim\");\n\n    auto output_prim = outputs.begin()->second.get_memory();\n    auto ref = output_ref.pointer<float>();\n    auto output_ptr = output_prim.pointer<float>();\n    for (auto i = 0; i < batch * sequence_length * num_output_size; i++) {\n        EXPECT_EQ(ref[i], output_ptr[i]);\n    }\n\n}\n\n", "meta": {"hexsha": "286b3b3b2c1de30728a77dd0da50282efe79fd1d", "size": 5648, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "inference-engine/thirdparty/clDNN/tests/test_cases/embed_gpu_test.cpp", "max_stars_repo_name": "mypopydev/dldt", "max_stars_repo_head_hexsha": "8cd639116b261adbbc8db860c09807c3be2cc2ca", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-07-08T09:03:03.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-09T10:34:17.000Z", "max_issues_repo_path": "inference-engine/thirdparty/clDNN/tests/test_cases/embed_gpu_test.cpp", "max_issues_repo_name": "openvino-pushbot/dldt", "max_issues_repo_head_hexsha": "e607ee70212797cf9ca51dac5b7ac79f66a1c73f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-11-13T18:59:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T02:14:53.000Z", "max_forks_repo_path": "inference-engine/thirdparty/clDNN/tests/test_cases/embed_gpu_test.cpp", "max_forks_repo_name": "openvino-pushbot/dldt", "max_forks_repo_head_hexsha": "e607ee70212797cf9ca51dac5b7ac79f66a1c73f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-12-05T07:38:25.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-05T07:38:25.000Z", "avg_line_length": 33.619047619, "max_line_length": 128, "alphanum_fraction": 0.5966713881, "num_tokens": 1944, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.6370308013713525, "lm_q1q2_score": 0.45776676176037273}}
{"text": "/*\n * Copyright 2018,\n * Julian Viereck\n *\n * CNRS/AIST\n *\n */\n\n#include <boost/function.hpp>\n\n#include <dynamic-graph/all-commands.h>\n#include <dynamic-graph/factory.h>\n\n#include <sot/core/exp-moving-avg.hh>\n#include <sot/core/factory.hh>\n\nnamespace dg = ::dynamicgraph;\n\n/* ---------------------------------------------------------------------------*/\n/* ------- GENERIC HELPERS -------------------------------------------------- */\n/* ---------------------------------------------------------------------------*/\n\nnamespace dynamicgraph {\nnamespace sot {\n\nDYNAMICGRAPH_FACTORY_ENTITY_PLUGIN(ExpMovingAvg, \"ExpMovingAvg\");\n\n/* --------------------------------------------------------------------- */\n/* --- CLASS ----------------------------------------------------------- */\n/* --------------------------------------------------------------------- */\n\nExpMovingAvg::ExpMovingAvg(const std::string &n)\n    : Entity(n),\n      updateSIN(NULL, \"ExpMovingAvg(\" + n + \")::input(vector)::update\"),\n      refresherSINTERN(\"ExpMovingAvg(\" + n + \")::intern(dummy)::refresher\"),\n      averageSOUT(boost::bind(&ExpMovingAvg::update, this, _1, _2),\n                  updateSIN << refresherSINTERN,\n                  \"ExpMovingAvg(\" + n + \")::output(vector)::average\"),\n      alpha(0.), init(false) {\n  // Register signals into the entity.\n  signalRegistration(updateSIN << averageSOUT);\n  refresherSINTERN.setDependencyType(TimeDependency<int>::ALWAYS_READY);\n\n  std::string docstring;\n  // setAlpha\n  docstring = \"\\n\"\n              \"    Set the alpha used to update the current value.\"\n              \"\\n\";\n  addCommand(std::string(\"setAlpha\"),\n             new ::dynamicgraph::command::Setter<ExpMovingAvg, double>(\n                 *this, &ExpMovingAvg::setAlpha, docstring));\n}\n\nExpMovingAvg::~ExpMovingAvg() {}\n\n/* --- COMPUTE ----------------------------------------------------------- */\n/* --- COMPUTE ----------------------------------------------------------- */\n/* --- COMPUTE ----------------------------------------------------------- */\n\nvoid ExpMovingAvg::setAlpha(const double &alpha_) {\n  assert(alpha <= 1. && alpha >= 0.);\n  alpha = alpha_;\n}\n\ndynamicgraph::Vector &ExpMovingAvg::update(dynamicgraph::Vector &res,\n                                           const int &inTime) {\n  const dynamicgraph::Vector &update = updateSIN(inTime);\n\n  if (init == false) {\n    init = true;\n    average = update;\n    average.setZero();\n    res.resize(average.size());\n  }\n\n  res = average = alpha * average + (1. - alpha) * update;\n  return res;\n}\n\n} /* namespace sot */\n} /* namespace dynamicgraph */\n", "meta": {"hexsha": "47863c810359d9a2e77e4eb37f637475e8243c11", "size": 2596, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tools/exp-moving-avg.cpp", "max_stars_repo_name": "Rascof/sot-core", "max_stars_repo_head_hexsha": "281ed2a1b40b7945b5a3d5735f785b9004b19f87", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2016-03-28T07:15:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-05T13:41:06.000Z", "max_issues_repo_path": "src/tools/exp-moving-avg.cpp", "max_issues_repo_name": "Rascof/sot-core", "max_issues_repo_head_hexsha": "281ed2a1b40b7945b5a3d5735f785b9004b19f87", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 121.0, "max_issues_repo_issues_event_min_datetime": "2015-02-17T08:38:25.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-01T10:54:05.000Z", "max_forks_repo_path": "src/tools/exp-moving-avg.cpp", "max_forks_repo_name": "Rascof/sot-core", "max_forks_repo_head_hexsha": "281ed2a1b40b7945b5a3d5735f785b9004b19f87", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2015-07-01T16:25:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-08T15:06:58.000Z", "avg_line_length": 31.6585365854, "max_line_length": 80, "alphanum_fraction": 0.4761171032, "num_tokens": 525, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.45776675680856077}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// kernel::functional::nw_visitor.hpp                                        //\n//                                                                           //\n//  Copyright 2009 Erwann Rogard. Distributed under the Boost                //\n//  Software License, Version 1.0. (See accompanying file                    //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)         //\n/////////////////////////////////////////////////////////////////////////////// \n#ifndef BOOST_STATISTICS_DETAIL_KERNEL_ESTIMATION_NW_VISITOR_HPP_ER_2009\n#define BOOST_STATISTICS_DETAIL_KERNEL_ESTIMATION_NW_VISITOR_HPP_ER_2009\n#include <boost/type_traits/is_reference.hpp>\n#include <boost/mpl/not.hpp>\n#include <boost/call_traits.hpp>\n#include <boost/statistics/detail/kernel/estimation/detail/mean_accumulator.hpp>\n#include <boost/statistics/detail/kernel/estimation/rp_visitor.hpp>\n\nnamespace boost{\nnamespace statistics{\nnamespace detail{\nnamespace kernel{\n   \n// This visitor, f, updates a Nadaraya-Watson estimate of E[Y|X=x0] each\n// time f(x,y) is called. \n//\n// K,X,A : See rp_visitor \ntemplate<\n    typename K,\n    typename X,\n    typename A = typename \n        statistics::detail::kernel::detail::mean_accumulator<typename K::result_type>::type \n>\nclass nw_visitor{\n    public:\n    typedef rp_visitor<K,X,A> rp_visitor_type;\n    typedef typename rp_visitor_type::result_type result_type;\n    typedef K kernel_type;\n    typedef A accumulator_type;\n        \n    //Construct\n    nw_visitor();\n    nw_visitor(typename call_traits<X>::param_type);\n    nw_visitor(\n        K k, // passing radius should call implicit conversion\n        typename call_traits<X>::param_type x  \n    );\n    nw_visitor(\n        K k,\n        typename call_traits<X>::param_type,\n        const accumulator_type&\n    );\n    nw_visitor(const nw_visitor&);\n    nw_visitor& operator=(const nw_visitor&);\n        \n    // Update\n    protected:\n    template<typename X1,typename Y1> // Training data point\n    result_type operator()(const X1& x1,const Y1& y1);\n\n    public:\n    // Access\n    result_type unnormalized_estimate()const;\n    result_type normalizing_constant()const;\n    result_type estimate()const; \n\n    \n    const A& accumulator()const;\n    const rp_visitor_type& rp_visitor()const;\n        \n    private:\n    rp_visitor_type rp_visitor_;\n    A a_;\n};\n    \n//Construction\ntemplate<typename K,typename X,typename A>\nnw_visitor<K,X,A>::nw_visitor():rp_visitor_(),a_(){}\n    \ntemplate<typename K,typename X,typename A>\nnw_visitor<K,X,A>::nw_visitor(K k,typename call_traits<X>::param_type x)\n:rp_visitor_(k,x),a_(){}\n    \ntemplate<typename K,typename X,typename A>\nnw_visitor<K,X,A>::nw_visitor(\n    K k,typename call_traits<X>::param_type x,const A& a\n):rp_visitor_(k,x,a),a_(a){}\n    \ntemplate<typename K,typename X,typename A>\nnw_visitor<K,X,A>::nw_visitor(const nw_visitor& that)\n:rp_visitor_(that.rp_visitor_),a_(that.a_){}\n    \ntemplate<typename K,typename X,typename A>\ntypename nw_visitor<K,X,A>::nw_visitor& \nnw_visitor<K,X,A>::operator=(const nw_visitor& that){\n    if(&that!=this){\n        rp_visitor_ = that.rp_visitor_;\n        a_ = that.a_;\n    }   \n    return *this;\n}\n    \n// Update\ntemplate<typename K,typename X,typename A>\ntemplate<typename X1,typename Y1>\ntypename nw_visitor<K,X,A>::result_type\nnw_visitor<K,X,A>::operator()(const X1& x1,const Y1& y){\n    result_type w = (this->rp_visitor_(x1));\n    result_type wy = w * y; \n    this->a_(wy);\n    return wy;\n}\n\n// Access\ntemplate<typename K,typename X,typename A>\ntypename nw_visitor<K,X,A>::result_type\nnw_visitor<K,X,A>::unnormalized_estimate()const{\n    return accumulators::mean(\n        this->accumulator()\n    );\n}\n\ntemplate<typename K,typename X,typename A>\ntypename nw_visitor<K,X,A>::result_type\nnw_visitor<K,X,A>::normalizing_constant()const{\n    return (this->rp_visitor_).estimate();\n}\n    \ntemplate<typename K,typename X,typename A>\ntypename nw_visitor<K,X,A>::result_type\nnw_visitor<K,X,A>::estimate()const{\n    return (this->unnormalized_estimate()/this->normalizing_constant());\n}\n    \ntemplate<typename K,typename X,typename A>\nconst A& nw_visitor<K,X,A>::accumulator()const{ return  this->a_; }\n        \ntemplate<typename K,typename X,typename A>\nconst rp_visitor<K,X,A>& \nnw_visitor<K,X,A>::rp_visitor()const{\n    return (this->rp_visitor_);\n}\n    \n}// kernel\n}// detail\n}// statistics\n}// boost\n\n#endif", "meta": {"hexsha": "9d143550e26887c97c9a0ca13a5ce84049eaf8fd", "size": 4459, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "kernel/boost/statistics/detail/kernel/estimation/nw_visitor.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": "kernel/boost/statistics/detail/kernel/estimation/nw_visitor.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": "kernel/boost/statistics/detail/kernel/estimation/nw_visitor.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": 30.5410958904, "max_line_length": 92, "alphanum_fraction": 0.6539582866, "num_tokens": 1051, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.4577667469049369}}
{"text": "#include \"coordsys.h\"\n#include \"utils.h\"\n#include <iostream>\n#include <Eigen/Dense>\n#include <Eigen/LU>\n\nusing Eigen::Vector3d;\nusing Eigen::Matrix3d;\n\nnamespace batoid {\n\n    CoordSys::CoordSys() :\n        m_origin(Vector3d::Zero()), m_rot(Matrix3d::Identity()) {}\n\n    CoordSys::CoordSys(const Vector3d origin, const Matrix3d rot) :\n        m_origin(origin), m_rot(rot) {}\n\n    CoordSys::CoordSys(const Vector3d origin) :\n        m_origin(origin), m_rot(Matrix3d::Identity()) {}\n\n    CoordSys::CoordSys(const Matrix3d rot) :\n        m_origin(Vector3d::Zero()), m_rot(rot) {}\n\n    CoordSys CoordSys::shiftGlobal(const Vector3d& dr) const {\n        return CoordSys(m_origin+dr, m_rot);\n    }\n\n    CoordSys CoordSys::shiftLocal(const Vector3d& dr) const {\n        // Note m_rot*dr instead of m_rot.transpose()*dr, b/c we are doing a passive rotation\n        // instead of an active one.\n        return shiftGlobal(m_rot*dr);\n    }\n\n    CoordSys CoordSys::rotateGlobal(const Matrix3d& rot) const {\n        return CoordSys(rot*m_origin, rot*m_rot);\n    }\n\n    CoordSys CoordSys::rotateGlobal(const Matrix3d& rot, const Vector3d& rotCenter, const CoordSys& coordSys) const {\n        CoordTransform toGlobal(coordSys, CoordSys());\n        Vector3d globalRotCenter = toGlobal.applyForward(rotCenter);\n        return CoordSys(\n            rot*(m_origin-globalRotCenter)+globalRotCenter,\n            rot*m_rot\n        );\n    }\n\n    CoordSys CoordSys::rotateLocal(const Matrix3d& rot) const {\n        // first rotate rot into global coords, then apply that\n        // m_rot rot m_rot^-1 m_rot = m_rot rot\n        return CoordSys(m_origin, m_rot*rot);\n    }\n\n    CoordSys CoordSys::rotateLocal(const Matrix3d& rot, const Vector3d& rotCenter, const CoordSys& coordSys) const {\n        CoordTransform toGlobal(coordSys, CoordSys());\n        Vector3d globalRotCenter = toGlobal.applyForward(rotCenter);\n        return CoordSys(\n            m_rot*rot*(m_rot.transpose())*(m_origin-globalRotCenter)+globalRotCenter,\n            m_rot*rot\n        );\n    }\n\n    Vector3d CoordSys::getXHat() const {\n        return Vector3d(m_rot.data()[0], m_rot.data()[3], m_rot.data()[6]);\n    }\n\n    Vector3d CoordSys::getYHat() const {\n        return Vector3d(m_rot.data()[1], m_rot.data()[4], m_rot.data()[7]);\n    }\n\n    Vector3d CoordSys::getZHat() const {\n        return Vector3d(m_rot.data()[2], m_rot.data()[5], m_rot.data()[8]);\n    }\n\n    std::ostream& operator<<(std::ostream& os, const CoordSys& cs) {\n        return os << cs.repr();\n    }\n\n    bool operator==(const CoordSys& cs1, const CoordSys& cs2) {\n        return cs1.m_origin == cs2.m_origin && cs1.m_rot == cs2.m_rot;\n    }\n\n    bool operator!=(const CoordSys& cs1, const CoordSys& cs2) {\n        return !(cs1 == cs2);\n    }\n\n\n    // x is global coordinate\n    // y is destination, with corresponding R and dr\n    // z is source, with corresponding S and ds\n    //\n    // y = Rinv(x-dr)\n    // z = Sinv(x-ds)\n    // implies\n    // x = S z + ds\n    //\n    // y = Rinv(S z + ds - dr)\n    //   = Rinv S z + Rinv ds - Rinv dr\n    //   = Rinv S z + Rinv S Sinv ds - Rinv S Sinv dr\n    //   = Rinv S (z + Sinv ds - Sinv dr)\n    //   = (Sinv R)^-1 (z - (Sinv dr - Sinv ds))\n    //   = (Sinv R)^-1 (z - Sinv (dr - ds))\n\n    CoordTransform::CoordTransform(const CoordSys& source, const CoordSys& destination) :\n        _dr(source.m_rot.transpose()*(destination.m_origin - source.m_origin)),\n        _rot(source.m_rot.transpose()*destination.m_rot),\n        _source(source), _destination(destination) {}\n\n    CoordTransform::CoordTransform(const Vector3d& dr, const Matrix3d& rot) :\n        _dr(dr), _rot(rot) {}\n\n    // We actively shift and rotate the coordinate system axes,\n    // This looks like y = R x + dr\n    // For a passive transformation of a fixed vector from one coord sys to another\n    // though, we want the opposite transformation: y = R^-1 (x - dr)\n    Vector3d CoordTransform::applyForward(const Vector3d& r) const {\n        return _rot.transpose()*(r-_dr);\n    }\n\n    Vector3d CoordTransform::applyReverse(const Vector3d& r) const {\n        return _rot*r+_dr;\n    }\n\n    Ray CoordTransform::applyForward(const Ray& r) const {\n        if (r.failed) return r;\n        return Ray(_rot.transpose()*(r.r-_dr), _rot.transpose()*r.v,\n                r.t, r.wavelength, r.flux, r.vignetted);\n    }\n\n    Ray CoordTransform::applyReverse(const Ray& r) const {\n        if (r.failed) return r;\n        return Ray(_rot*r.r + _dr, _rot*r.v,\n            r.t, r.wavelength, r.flux, r.vignetted);\n    }\n\n    void CoordTransform::applyForwardInPlace(Ray& r) const {\n        if (r.failed) return;\n        r.r = _rot.transpose()*(r.r-_dr);\n        r.v = _rot.transpose()*r.v;\n    }\n\n    void CoordTransform::applyReverseInPlace(Ray& r) const {\n        if (r.failed) return;\n        r.r = _rot*r.r+_dr;\n        r.v = _rot*r.v;\n    }\n\n    RayVector CoordTransform::applyForward(const RayVector& rv) const {\n        std::vector<Ray> result(rv.size());\n        parallelTransform(rv.cbegin(), rv.cend(), result.begin(),\n            [this](const Ray& r) { return applyForward(r); }\n        );\n        return RayVector(std::move(result), rv.getWavelength());\n    }\n\n    RayVector CoordTransform::applyReverse(const RayVector& rv) const {\n        std::vector<Ray> result(rv.size());\n        parallelTransform(rv.cbegin(), rv.cend(), result.begin(),\n            [this](const Ray& r) { return applyReverse(r); }\n        );\n        return RayVector(std::move(result), rv.getWavelength());\n    }\n\n    void CoordTransform::applyForwardInPlace(RayVector& rv) const {\n        parallel_for_each(rv.begin(), rv.end(),\n            [this](Ray& r) { applyForwardInPlace(r); }\n        );\n    }\n\n    void CoordTransform::applyReverseInPlace(RayVector& rv) const {\n        parallel_for_each(rv.begin(), rv.end(),\n            [this](Ray& r) { applyReverseInPlace(r); }\n        );\n    }\n\n    bool operator==(const CoordTransform& ct1, const CoordTransform& ct2) {\n        return ct1.getRot() == ct2.getRot() &&\n               ct1.getDr() == ct2.getDr();\n    }\n\n    bool operator!=(const CoordTransform& ct1, const CoordTransform& ct2) {\n        return !(ct1 == ct2);\n    }\n\n    std::ostream& operator<<(std::ostream &os, const CoordTransform& ct) {\n        return os << ct.repr();\n    }\n\n}\n", "meta": {"hexsha": "b3e96f0a151b28805ec86715dbd7aacc20e681dd", "size": 6294, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/coordsys.cpp", "max_stars_repo_name": "dkirkby/batoid", "max_stars_repo_head_hexsha": "734dccc289eb7abab77a62cdc14563ed5981753b", "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/coordsys.cpp", "max_issues_repo_name": "dkirkby/batoid", "max_issues_repo_head_hexsha": "734dccc289eb7abab77a62cdc14563ed5981753b", "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/coordsys.cpp", "max_forks_repo_name": "dkirkby/batoid", "max_forks_repo_head_hexsha": "734dccc289eb7abab77a62cdc14563ed5981753b", "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.3015873016, "max_line_length": 117, "alphanum_fraction": 0.6112170321, "num_tokens": 1690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.6370307806984443, "lm_q1q2_score": 0.45776674690493685}}
{"text": "#include <algorithm>\n#include <errno.h>\n#include <iostream>\n#include <numeric>\n#include <stdlib.h>\n#include <string.h>\n#include <time.h>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/SVD>\n\n#ifdef _WIN32\n#else\n#include <stdbool.h>\n#include <unistd.h>\n#endif\n\n#include \"arrayproperties.h\"\n#include \"arraytools.h\"\n#include \"mathtools.h\"\n#include \"printfheader.h\"\n#include \"tools.h\"\n\nusing namespace Eigen;\n\nmvalue_t< long > A3A4 (const array_link &al) {\n        const int N = al.n_rows;\n\n        std::vector< double > gwlp = al.GWLP ();\n        long w3 = 0;\n        if (gwlp.size () > 3) {\n                w3 = N * N * gwlp[3]; // the maximum value for w3 is N*choose(k, jj)\n        }\n        long w4 = 0;\n        if (gwlp.size () > 4) {\n                w4 = N * N * gwlp[4];\n        }\n        std::vector< long > w;\n        w.push_back (w3);\n        w.push_back (w4);\n\n        mvalue_t< long > wm (w, mvalue_t< long >::LOW);\n        return wm;\n}\n\n\n/// calculate Hamming distance between two rows of an array\ninline int dH (const int N, int k, const array_link &al, int r1, int r2) {\n        int dh = 0;\n        carray_t *D = al.array;\n        carray_t *d1 = D + r1;\n        carray_t *d2 = D + r2;\n\n        for (int c = 0; c < k; c++) {\n                dh += d1[c * N] != d2[c * N];\n        }\n        return dh;\n}\n\n/// calculate Hamming distance between two rows of an array with mixed levels\ninline void dHmixed (const int N, int k, const array_link &al, int r1, int r2, int *dh, int ncolgroups,\n                     const std::vector< int > colgroupindex) {\n        for (int i = 0; i < ncolgroups; i++)\n                dh[i] = 0;\n\n        carray_t *D = al.array;\n        carray_t *d1 = D + r1;\n        carray_t *d2 = D + r2;\n\n        for (int c = 0; c < k; c++) {\n                int ci = colgroupindex[c];\n                dh[ci] += d1[c * N] != d2[c * N];\n        }\n}\n\n/// Hamming distance (transposed array)\ninline int dHx (const int nr, int k, carray_t *data, int c1, int c2) {\n        // nr is the OA column variable\n\n        int dh = 0;\n        carray_t *d1 = data + c1 * nr;\n        carray_t *d2 = data + c2 * nr;\n\n        for (int c = 0; c < nr; c++) {\n                dh += d1[c] != d2[c];\n        }\n        return dh;\n}\n\n/// compare 2 GWPL sequences\nint GWPcompare (const std::vector< double > &a, const std::vector< double > &b) {\n        for (size_t x = 0; x < a.size (); x++) {\n                if (a[x] != b[x])\n                        return a[x] < b[x];\n        }\n        return 0;\n}\n\n/// calculate distance distrubution (array is transposed for speed)\nstd::vector< double > distance_distributionT (const array_link &al, int norm = 1) {\n        int N = al.n_rows;\n        int n = al.n_columns;\n\n        // transpose array\n        array_t *x = new array_t[N * n];\n        array_t *xx = x;\n        for (int i = 0; i < N; i++)\n                for (int j = 0; j < n; j++) {\n                        (*xx) = al.array[i + j * N];\n                        xx++;\n                }\n\n        // calculate distance distribution\n        std::vector< double > dd (n + 1);\n\n        for (int r1 = 0; r1 < N; r1++) {\n                for (int r2 = 0; r2 < r1; r2++) {\n                        int dh = dHx (n, N, x, r1, r2);\n                        dd[dh] += 2; // factor 2: dH is symmetric\n                }\n        }\n        // along diagonal\n        dd[0] += N;\n\n        if (norm) {\n                for (int x = 0; x <= n; x++) {\n                        dd[x] /= N;\n                }\n        }\n\n        delete[] x;\n        return dd;\n}\n\nvoid distance_distribution_mixed_inplace (const array_link &al, ndarray< double > &B, int verbose) {\n        int N = al.n_rows;\n        int n = al.n_columns;\n\n        // calculate distance distribution\n        std::vector< double > dd (n + 1);\n\n        arraydata_t ad = arraylink2arraydata (al);\n\n        symmetry_group sg (ad.factor_levels (), false);\n\n        int *dh = new int[sg.ngroups];\n\n        std::vector< int > dims (ad.ncolgroups);\n        for (size_t i = 0; i < dims.size(); i++) {\n            dims[i] = ad.colgroupsize[i];\n            if (B.dims[i]!=dims[i]+1)\n                throw_runtime_exception(printfstring(\"distance_distribution_mixed: output array specified has incorrect dimensions, B.dims[%d]=%d!=%d\", i, B.dims[i], dims[i]+1 ));\n\n        }\n        if (verbose >= 3) {\n                myprintf (\"distance_distribution_mixed before: \\n\");\n                B.show ();\n        }\n\n        for (int r1 = 0; r1 < N; r1++) {\n                for (int r2 = 0; r2 < r1; r2++) {\n                        dHmixed (N, n, al, r1, r2, dh, sg.ngroups, sg.gidx);\n\n                        if (verbose >= 4) {\n                                myprintf (\"distance_distribution_mixed: rows %d %d: index \", r1, r2);\n                                print_perm (dh, sg.ngroups);\n                        }\n                        int v = B.get (dh);\n                        B.set (dh, v + 2);\n\n                        if (verbose >= 3) {\n                                int w = B.getlinearidx (dh);\n                                if (w == 0) {\n                                        myprintf (\"distance_distribution_mixed: row1 %d, row2 %d\\n\", r1, r2);\n                                }\n                        }\n                }\n        }\n        if (verbose >= 3) {\n                myprintf (\"distance_distribution_mixed low: \\n\");\n                B.show ();\n        }\n\n        // along diagonal\n        for (unsigned int i = 0; i < dims.size (); i++)\n                dh[i] = 0;\n        int v = B.get (dh);\n        B.set (dh, v + N);\n\n        if (verbose >= 3) {\n                myprintf (\"distance_distribution_mixed integer: \\n\");\n                B.show ();\n        }\n\n        for (int x = 0; x < B.n; x++) {\n                B.data[x] /= N;\n        }\n\n        if (verbose) {\n                myprintf (\"distance_distribution_mixed: \\n\");\n                B.show ();\n        }\n\n        delete[] dh;\n}\n\nndarray<double> distance_distribution_mixed(const array_link& al, int verbose) {\n    std::vector<int> d = distance_distribution_shape(arraylink2arraydata(al));\n    ndarray<double> B(d);\n    distance_distribution_mixed_inplace(al, B, verbose);\n    return B;\n}\n\nstd::vector< double > distance_distribution (const array_link &al) {\n        int N = al.n_rows;\n        int n = al.n_columns;\n\n        // calculate distance distribution\n        std::vector< double > dd (n + 1);\n\n        for (int r1 = 0; r1 < N; r1++) {\n                for (int r2 = 0; r2 < r1; r2++) {\n                        int dh = dH (N, n, al, r1, r2);\n                        dd[dh] += 2;\n                }\n        }\n        // along diagonal\n        dd[0] += N;\n\n        for (int x = 0; x <= n; x++) {\n                dd[x] /= N;\n        }\n\n        return dd;\n}\n\nndarray< double >  macwilliams_transform_mixed(const ndarray< double >& B, int N, const std::vector<int> &factor_levels_for_groups, int verbose) {\n\n    ndarray<double> Bout = ndarray<double>(B.dims);\n\n    const int ngroups = B.k;\n    const int total_number_of_elements = B.n;\n\n    int* index_in = new int[ngroups];\n    int* index_out = new int[ngroups];\n\n    for (int i = 0; i < ngroups; i++)\n        index_in[i] = 0;\n    for (int i = 0; i < ngroups; i++)\n        index_out[i] = 0;\n\n    for (int j = 0; j < Bout.n; j++) {\n        Bout.linear2idx(j, index_out);\n        Bout.setlinear(j, 0);\n\n        for (int i = 0; i < B.n; i++) {\n            B.linear2idx(i, index_in);\n\n            long fac = 1;\n            for (int f = 0; f < B.k; f++) {\n                long ji = index_out[f];\n                long ii = index_in[f];\n                long ni = B.dims[f] - 1;\n                long si = factor_levels_for_groups[f];\n                long krw = krawtchouk(ji, ii, ni, si);\n                fac *= krw;\n                if (verbose >= 4)\n                    myprintf(\"  (j,i,f)=(%d, %d, %d): fac*= krw(%ld %ld %ld %ld)=%ld -> fac %ld\\n\", j, i, f,\n                        ji, ii, ni, si, krw, fac);\n            }\n            Bout.data[j] += B.data[i] * fac;\n            if (verbose >= 4)\n                myprintf(\"  Bout[%d] += B[%d] * fac = %.1f * %ld \\n\", j, i, (double)B.data[i], fac);\n        }\n        Bout.data[j] /= N;\n        if (verbose >= 2)\n            myprintf(\"macwilliams_transform_mixed: Bout[%d]=Bout%s= %f\\n\", j, Bout.idxstring(j).c_str(),\n                Bout.data[j]);\n    }\n\n    if (verbose >= 1) {\n        myprintf(\"Bout: \\n\");\n        Bout.show();\n    }\n\n\n    delete[] index_out;\n    delete[] index_in;\n\n    return Bout;\n}\n\n/** @brief Calculate the GWLP of a mixed level design using the MacWilliams transform\n *\n * See \"GENERALIZED MINIMUM ABERRATION FOR ASYMMETRICAL FRACTIONAL FACTORIAL DESIGNS\", Xu and Wu, 2001.\n *\n * @param B Input array\n * @param N\n * @param factor_levels_for_groups Factor levels for the groups\n * @param verbose Verbosity level\n * @return MacWilliams transform\n*/\nstd::vector< double > gwpl_macwilliams_transform_mixed (const ndarray< double > &B, int N,\n                                                   const std::vector< int > &factor_levels_for_groups,\n                                                   int verbose) {\n        if (verbose) {\n                myprintf (\"macwilliams_transform_mixed:\\n\");\n                myprintf (\"factor_levels_for_groups: \");\n                display_vector (factor_levels_for_groups);\n                myprintf (\"\\n\");\n        }\n\n        const ndarray<double> Bout = macwilliams_transform_mixed(B, N, factor_levels_for_groups, verbose);\n\n        const int ngroups = B.k;\n        const int total_number_of_elements = B.n;\n\n        int* index_in = new int[ngroups];\n        int* index_out = new int[ngroups];\n\n        // use formula from page 555 in Xu and Wu (Theorem 4.i)\n        int jmax = B.cumdims[B.k] - B.k;\n        std::vector< double > A (jmax+1, 0);\n\n        for (int i = 0; i < total_number_of_elements; i++) {\n                Bout.linear2idx (i, index_in);\n                int jsum = 0;\n                for (int j = 0; j < Bout.k; j++)\n                        jsum += index_in[j];\n                if (verbose >= 2)\n                        myprintf (\"   jsum %d/%d, i %d\\n\", jsum, (int)A.size (), i);\n                A[jsum] += Bout.data[i];\n        }\n\n        delete[] index_out;\n        delete[] index_in;\n\n        return A;\n}\n\n/** Calculate D-efficiencies for all projection designs\n *\n * \\param orthogonal_array Design to calculate D-efficiencies for\n * \\param number_of_factors Number of factors into which to project\n * \\returns Vector with calculated D-efficiencies\n */\nstd::vector< double > projDeff (const array_link &orthogonal_array, int number_of_factors, int verbose) {\n        myassert (orthogonal_array.is2level (), \"array is not 2-level\");\n\n        int number_of_columns = orthogonal_array.n_columns;\n        std::vector< int > column_combination (number_of_factors);\n        for (int i = 0; i < number_of_factors; i++)\n                column_combination[i] = i;\n        int64_t number_combinations = ncombsm< int64_t > (number_of_columns, number_of_factors);\n\n        int m = 1 + number_of_factors + number_of_factors * (number_of_factors - 1) / 2;\n        int N = orthogonal_array.n_rows;\n\n        if (verbose)\n                myprintf (\"projDeff: k %d, kp %d: start with %ld combinations \\n\", number_of_columns,\n                          number_of_factors, (long)number_combinations);\n\n\t\tstd::vector< double > efficiencies(number_combinations);\n\t\tfor (int64_t i = 0; i < number_combinations; i++) {\n                if (m > N)\n                        efficiencies[i] = 0;\n                else {\n                        array_link alsub = orthogonal_array.selectColumns (column_combination);\n                        efficiencies[i] = alsub.Defficiency ();\n                }\n                if (verbose >= 2)\n                        myprintf (\"projDeff: k %d, kp %d: i %ld, D %f\\n\", number_of_columns, number_of_factors,\n                                  (long)i, efficiencies[i]);\n                next_comb (column_combination, number_of_factors, number_of_columns);\n        }\n\n        if (verbose)\n                myprintf (\"projDeff: k %d, kp %d: done\\n\", number_of_columns, number_of_factors);\n\n        return efficiencies;\n}\n\nstd::vector< double > PECsequence (const array_link &array, int verbose) {\n\n        int N = array.n_rows;\n\n        int number_of_factors = array.n_columns;\n        std::vector< double > pec (number_of_factors);\n\n        if (number_of_factors >= 20) {\n\t\t\tthrow_runtime_exception(\"PECsequence: error: not implemented for 20 or more columns\\n\");\n        }\n\n#ifdef DOOPENMP\n#pragma omp parallel for\n#endif\n        for (int i = 0; i < number_of_factors; i++) {\n                int kp = i + 1;\n                int m = 1 + kp + kp * (kp - 1) / 2;\n\n                if (m > N) {\n                        // if size of model is larger than number of runs the model cannot be estimated\n                        pec[i] = 0;\n                } else {\n                        std::vector< double > dd = projDeff (array, kp, verbose >= 2);\n                        pec[i] = fraction_nonzero(dd);\n                }\n        }\n\n        return pec;\n}\n\nstd::vector< double > PICsequence(const array_link &array, int verbose) {\n\n\tint N = array.n_rows;\n\tint number_of_factors = array.n_columns;\n\tstd::vector< double > pic(number_of_factors);\n\n\tif (number_of_factors >= 20) {\n\t\tthrow_runtime_exception(\"PICsequence: error: not implemented for 20 or more columns\\n\");\n\t}\n\n\n#ifdef DOOPENMP\n#pragma omp parallel for\n#endif\n\tfor (int i = 0; i < number_of_factors; i++) {\n\t\tint number_projection_factors = i + 1;\n\t\tint m = 1 + number_projection_factors + number_projection_factors * (number_projection_factors - 1) / 2;\n\n\t\tif (m > N) {\n\t\t\t// if size of model is larger than number of runs the model cannot be estimated\n\t\t\tpic[i] = 0;\n\t\t}\n\t\telse {\n\t\t\tstd::vector< double > dd = projDeff(array, number_projection_factors, verbose >= 2);\n\n\t\t\tpic[i] = average(dd);\n\t\t}\n\t}\n\n\treturn pic;\n}\n\nvoid round_GWLP_zero_values(std::vector<double> &gma, int N)\n{\n\tfor (size_t i = 0; i < gma.size(); i++) {\n\t\tgma[i] = round(N * N * gma[i]) / (N * N);\n\t\tif (gma[i] == 0)\n\t\t\tgma[i] = 0; // fix minus zero float number\n\t}\n\n}\n\n/**\n * @brief Return shape for distance distribution of the specified array class\n * @param adata Specification of the array class\n * @return Vector with dimension of the shape of the distance distribution\n*/\nstd::vector<int> distance_distribution_shape(const arraydata_t adata) {\n    std::vector< int > dims(adata.ncolgroups);\n    for (unsigned int i = 0; i < dims.size(); i++)\n        dims[i] = adata.colgroupsize[i] + 1;\n    return dims;\n}\n\nstd::vector< double > GWLPmixed (const array_link &al, int verbose, int truncate) {\n        arraydata_t adata = arraylink2arraydata (al);\n\n\n        const ndarray<double> B = distance_distribution_mixed (al, verbose);\n\n        if (verbose >= 3) {\n                myprintf (\"GWLPmixed: distance distribution\\n\");\n                B.show ();\n        }\n\n        int N = adata.N;\n\n        std::vector< int > factor_levels = adata.factor_levels ();\n\n        std::vector< int > factor_levels_for_groups = adata.factor_levels_column_groups();\n\n        std::vector< double > gma = gwpl_macwilliams_transform_mixed (B, N, factor_levels_for_groups, verbose);\n\n        if (truncate)\n\t\t\tround_GWLP_zero_values(gma, N);\n        return gma;\n}\n\n/** Calculate GWLP for 2-level design\n *\n * @param array Input array\n * @param verbose Verbosity level\n * @param truncate If true, then round floating point values to zero\n * @return GWLP\n*/\nstd::vector< double > GWLP_two_level_design(const array_link &array, int verbose, int truncate) {\n\tint N = array.n_rows;\n\tint s = 2;\n\n\t// calculate distance distribution\n\tstd::vector< double > B = distance_distributionT(array);\n\tif (verbose) {\n\t\tmyprintf(\"distance_distributionT: \");\n\t\tdisplay_vector(B);\n\t\tmyprintf(\"\\n\");\n\t}\n\t// calculate GWLP\n\tstd::vector< double > gma = macwilliams_transform(B, N, s);\n\n\tif (truncate)\n\t\tround_GWLP_zero_values(gma, N);\n\n\treturn gma;\n}\n\nstd::vector< double > GWLP (const array_link &al, int verbose, int truncate) {\n        int N = al.n_rows;\n        int n = al.n_columns;\n\n\t\tint domixed = al.is_mixed_level();\n\n        if (verbose)\n                myprintf (\"GWLP: N %d, domixed %d\\n\", N, domixed);\n\n        if (domixed) {\n                std::vector< double > gma = GWLPmixed (al, verbose, truncate);\n                return gma;\n        } else {\n\t\t\t\tstd::vector< double > gma = GWLP_two_level_design(al, verbose, truncate);\n                return gma;\n        }\n}\n\n/// convert GWLP sequence to unique value\ninline double GWPL2val (GWLPvalue x) {\n        double r = 0;\n        for (int i = x.size () - 1; i > 0; i--)\n                r = r / 10 + x.values[i];\n\n        return r;\n}\n\n/// convert GWLP sequence to unique value\ninline double GWPL2val (std::vector< double > x) {\n        double r = 0;\n        for (int i = x.size () - 1; i > 0; i--)\n                r = r / 10 + x[i];\n\n        return r;\n}\n\nstd::vector< GWLPvalue > sortGWLP (const std::vector< GWLPvalue > in) {\n        std::vector< GWLPvalue > v = in;\n\n        std::sort (v.begin (), v.end ());\n        return v;\n}\n\nstd::vector< GWLPvalue > projectionGWLPs (const array_link &al) {\n        int ncols = al.n_columns;\n\n        std::vector< GWLPvalue > v (ncols);\n        for (int i = 0; i < ncols; i++) {\n                array_link d = al.deleteColumn (i);\n                std::vector< double > gma = GWLP (d);\n                v[i] = gma;\n        }\n        return v;\n}\n\nstd::vector< double > projectionGWLPdoublevalues (const array_link &al) {\n        int ncols = al.n_columns;\n\n        std::vector< double > v (ncols);\n        for (int i = 0; i < ncols; i++) {\n                array_link d = al.deleteColumn (i);\n                std::vector< double > gma = GWLP (d);\n                v[i] = GWPL2val (gma);\n        }\n        return v;\n}\n\n/// convert array to Eigen matrix structure\nEigen::MatrixXd arraylink2eigen (const array_link &al) {\n        int k = al.n_columns;\n        int n = al.n_rows;\n        assert (n >= 0);\n        assert (k >= 0);\n\n        Eigen::MatrixXd mymatrix = Eigen::MatrixXd::Zero (n, k);\n\n        for (int c = 0; c < k; ++c) {\n                // int ci = c*n;\n                array_t *p = al.array + c * n;\n                for (int r = 0; r < n; ++r) {\n                        mymatrix (r, c) = p[r];\n                }\n        }\n        return mymatrix;\n}\n\n/// return rank of an array based on Eigen::FullPivHouseholderQR\nint arrayrankFullPivQR (const array_link &al, double threshold) {\n        Eigen::MatrixXd mymatrix = arraylink2eigen (al);\n        FullPivHouseholderQR< Eigen::MatrixXd > decomp (mymatrix.rows (), mymatrix.cols ());\n        decomp.compute (mymatrix);\n        if (threshold > 0) {\n                decomp.setThreshold (threshold);\n        }\n        int rank = decomp.rank ();\n        return rank;\n}\n\n/// return rank of an array based on Eigen::ColPivHouseholderQR\nint arrayrankColPivQR (const array_link &al, double threshold) {\n        Eigen::MatrixXd mymatrix = arraylink2eigen (al);\n        Eigen::ColPivHouseholderQR< Eigen::MatrixXd > decomp (mymatrix);\n        if (threshold > 0) {\n                decomp.setThreshold (threshold);\n        }\n        int rank = decomp.rank ();\n        return rank;\n}\n\n/// return rank of an array based on Eigen::FullPivLU\nint arrayrankFullPivLU (const array_link &al, double threshold) {\n        Eigen::MatrixXd mymatrix = arraylink2eigen (al);\n        Eigen::FullPivLU< Eigen::MatrixXd > decomp (mymatrix);\n        if (threshold > 0) {\n                decomp.setThreshold (threshold);\n        }\n        int rank = decomp.rank ();\n        return rank;\n}\n\n/// return rank of an array based on Eigen::JacobiSVD\nint arrayrankSVD (const array_link &al, double threshold) {\n        Eigen::MatrixXd mymatrix = arraylink2eigen (al);\n        Eigen::JacobiSVD< Eigen::MatrixXd > decomp (mymatrix);\n        if (threshold > 0) {\n                decomp.setThreshold (threshold);\n        }\n        int rank = decomp.rank ();\n        return rank;\n}\n\n/// return rank of an array based on Eigen::FullPivLU\nint arrayrank (const array_link &al) {\n        Eigen::MatrixXd mymatrix = arraylink2eigen (al);\n        Eigen::FullPivLU< Eigen::MatrixXd > lu_decomp (mymatrix);\n        // printfd(\"threshold %e\\n\", lu_decomp.threshold() );\n        int rank = lu_decomp.rank ();\n        return rank;\n}\n\nint arrayrankInfo (const Eigen::MatrixXd &mymatrix, int verbose) {\n        if (verbose) {\n                printfd (\"arrayrankInfo\\n\");\n        }\n        Eigen::FullPivLU< Eigen::MatrixXd > lu_decomp (mymatrix);\n        int rank = lu_decomp.rank ();\n        if (verbose) {\n                double p = lu_decomp.maxPivot ();\n                printfd (\"arrayrankInfo: FullPivLU: rank %d, threshold %e, max pivot %e\\n\", rank,\n                         lu_decomp.threshold (), p);\n        }\n        Eigen::FullPivHouseholderQR< Eigen::MatrixXd > qr_decomp (mymatrix);\n        int rank2 = qr_decomp.rank ();\n        if (verbose) {\n                Eigen::MatrixXd qr = qr_decomp.matrixQR ();\n                qr_decomp.colsPermutation ();\n\n                Eigen::FullPivHouseholderQR< Eigen::MatrixXd >::PermutationType P = qr_decomp.colsPermutation ();\n\n                Eigen::MatrixXd R = qr_decomp.matrixQ ().inverse () * mymatrix * P;\n                if (verbose >= 3) {\n                        eigenInfo (R, \"arrayrankInfo: R \");\n                        std::cout << R << std::endl;\n                        std::cout << R.diagonal () << std::endl;\n                }\n                Eigen::VectorXd d = R.diagonal ();\n\n                double dmin = qr_decomp.maxPivot ();\n                double dfalse = 0;\n                for (int i = 0; i < d.size (); i++) {\n                        double q = std::fabs ((double)d (i));\n                        // printf(\"i %d, q %e\\n\", i, q);\n                        if (q < dmin && q > qr_decomp.threshold ())\n                                dmin = q;\n                        if (q > dfalse && q < qr_decomp.threshold ())\n                                dfalse = q;\n                }\n                double p = qr_decomp.maxPivot ();\n                printfd (\"arrayrankInfo: FullPivHouseholderQR: rank %d, threshold %e, max pivot %e, min non-zero \"\n                         \"pivot %e, false pivot %e\\n\",\n                         rank, qr_decomp.threshold (), p, dmin, dfalse);\n        }\n\n        return rank;\n}\n\nint arrayrankInfo (const array_link &al, int verbose) {\n        Eigen::MatrixXd mymatrix = arraylink2eigen (al);\n        int rank = arrayrankInfo (mymatrix, verbose);\n        return rank;\n}\n\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n/// helper function\nstd::vector< int > subIndices (int ks, int k) {\n        const int m = 1 + k + k * (k - 1) / 2;\n        const int msub = 1 + ks + ks * (ks - 1) / 2;\n        std::vector< int > idxsub (msub);\n        for (int i = 0; i < ks + 1; i++)\n                idxsub[i] = i;\n        int n = ks * (ks - 1) / 2;\n        for (int i = 0; i < n; i++)\n                idxsub[i + 1 + ks] = i + 1 + k;\n\n        return idxsub;\n}\n/// helper function\nstd::vector< int > subIndicesRemainder (int ks, int k) {\n        const int m = 1 + k + k * (k - 1) / 2;\n        const int msub = 1 + ks + ks * (ks - 1) / 2;\n\n        const int t2 = k * (k - 1) / 2;\n        const int t2s = ks * (ks - 1) / 2;\n\n        std::vector< int > idxsub (m - msub);\n\n        for (int i = 0; i < (k - ks); i++)\n                idxsub[i] = 1 + ks + i;\n        for (int i = 0; i < (t2 - t2s); i++)\n                idxsub[(k - ks) + i] = 1 + k + t2s + i;\n\n        return idxsub;\n}\n/// helper function\nEigen::MatrixXi permM (int ks, int k, const Eigen::MatrixXi subperm, int verbose = 1) {\n        std::vector< int > idxsub = subIndices (ks, k);\n        std::vector< int > idxrem = subIndicesRemainder (ks, k);\n\n        if (verbose) {\n                myprintf (\"ks: %d, k %d, idxsub: \", ks, k);\n                print_perm (idxsub);\n                myprintf (\"ks: %d, k %d, idxrem: \", ks, k);\n                print_perm (idxrem);\n        }\n\n        const int m = 1 + k + k * (k - 1) / 2;\n        const int msub = 1 + ks + ks * (ks - 1) / 2;\n\n        std::vector< int > ww (idxsub.size ());\n\n        for (size_t i = 0; i < ww.size (); i++)\n                ww[i] = idxsub[subperm (i)];\n\n        Eigen::MatrixXi pm (m, 1);\n        for (size_t i = 0; i < ww.size (); i++)\n                pm (i) = ww[i];\n        for (int i = 0; i < (m - msub); i++)\n                pm (msub + i) = idxrem[i];\n\n        return pm;\n}\n\n/// return the condition number of a matrix\ndouble conditionNumber (const array_link &M) {\n        Eigen::MatrixXd A = arraylink2eigen (M);\n        Eigen::JacobiSVD< Eigen::Matrix< double, -1, -1 > > svd (A);\n        double cond = svd.singularValues () (0) / svd.singularValues () (svd.singularValues ().size () - 1);\n        return cond;\n}\nvoid rankStructure::info() const {\n\tmyprintf(\"\trankStructure: submatrix %dx%d, rank %d, rank of xf %d\\n\", alsub.n_rows,\n\t\talsub.n_columns, this->alsub.rank(), (int)decomp.rank());\n}\n\n/// update the structure cache with a new array\nvoid rankStructure::updateStructure(const array_link &al) {\n\tthis->alsub = al;\n\tthis->ks = al.n_columns;\n\tEigen::MatrixXd A = array2xf(al).getEigenMatrix();\n\tdecomp.compute(A);\n\n\tthis->Qi = decomp.matrixQ().inverse();\n\n\tnupdate++;\n\n\tif (this->verbose >= 1 && nupdate % 30 == 0) {\n\t\tprintfd(\"updateStructure: ncalc %d, nupdate %d\\n\", ncalc, nupdate);\n\t}\n}\n\n/// calculate the rank of an array directly, uses special threshold\nint rankStructure::rankdirect(const Eigen::MatrixXd &A) const {\n\tEigenDecomp decomp(A);\n\tdecomp.setThreshold(1e-12);\n\tint rank = decomp.rank();\n\treturn rank;\n}\n\n/// calculate the rank of the second order interaction matrix of an array directly\nint rankStructure::rankxfdirect(const array_link &al) const {\n\tEigen::MatrixXd mymatrix = arraylink2eigen(array2xf(al));\n\treturn rankdirect(mymatrix);\n}\n\n/// calculate the rank of the second order interaction matrix of an array using the cache system\nint rankStructure::rankxf (const array_link &al) {\n        this->ncalc++;\n\n        int k = al.n_columns;\n        const int m = 1 + k + k * (k - 1) / 2;\n        const int msub = 1 + ks + ks * (ks - 1) / 2;\n        const int N = al.n_rows;\n\n        if (verbose) {\n                if (al.n_columns != alsub.n_columns + nsub)\n                        printf (\"rankStructure: rankxf: alsub %d, al %d (nsub %d, ks %d, id %d)\\n\", alsub.n_columns,\n                                al.n_columns, nsub, ks, this->id);\n        }\n        if (verbose)\n                printf (\"rankStructure: rankxf: alsub %d, al %d (ks %d)\\n\", alsub.n_columns, al.n_columns, ks);\n        if (al.selectFirstColumns (ks) == this->alsub) {\n\n        } else {\n                // update structure\n                if (verbose >= 2)\n                        printf (\"rankStructure: update structure (current ks %d, al.n_columns %d)\\n\", ks,\n                                al.n_columns);\n                updateStructure (al.selectFirstColumns (al.n_columns - nsub));\n        }\n        int rank0 = decomp.rank ();\n        if (verbose >= 2)\n                printfd (\"rankStructure: rank0 %d\\n\", rank0);\n\n        // special case: the same matrix!\n        if (ks == al.n_columns) {\n                if (verbose)\n                        printfd (\"special case: k==al.n_columns\\n\");\n                return decomp.rank ();\n        }\n        Eigen::MatrixXd A = array2xfeigen (al);\n\n        // caculate permutation\n\n        EigenDecomp::PermutationType subperm = decomp.colsPermutation ();\n        MatrixXi perm = permM (ks, k, subperm.indices (), verbose);\n        EigenDecomp::PermutationType ptmp (perm);\n\n        // transform second order interaction matrix into suitable format\n\n        Eigen::MatrixXd Zxp = A * ptmp;\n        Eigen::MatrixXd ZxSub = this->Qi.block (rank0, 0, N - rank0, N) * Zxp.block (0, rank0, N, m - rank0);\n\n        if (verbose >= 2) {\n                printf (\"  rankStructure: k %d, m %d\\n\", k, m);\n                printf (\"  rankStructure: msub %d, m %d\\n\", msub, m);\n        }\n\n        if (verbose >= 2) {\n                printfd (\"rankStructure: ZxSub\\n\");\n                eigenInfo (ZxSub);\n\n                arrayrankInfo (ZxSub, 1);\n\n                if (verbose >= 3) {\n                        fflush (stdout);\n                        printf (\"ZxSub\\n\");\n                        std::cout << ZxSub;\n                        printf (\"\\n\");\n                }\n        }\n\n        int rankx = rankdirect (ZxSub);\n        int rank = rank0 + rankx;\n\n        if (verbose) {\n                printf (\"rankStructure: rank %d + %d = %d (%d)\\n\", rank0, rankx, rank, rankxfdirect (al));\n        }\n        return rank;\n}\n\nEigen::MatrixXd array2xfeigen (const array_link &al) {\n        const int k = al.n_columns;\n        const int n = al.n_rows;\n        const int m = 1 + k + k * (k - 1) / 2;\n        Eigen::MatrixXd mymatrix = Eigen::MatrixXd::Zero (n, m);\n\n        // init first column\n        int ww = 0;\n        for (int r = 0; r < n; ++r) {\n                mymatrix (r, 0) = 1;\n        }\n        // set main effects\n        ww = 1;\n        for (int c = 0; c < k; ++c) {\n                int ci = c * n;\n                for (int r = 0; r < n; ++r) {\n                        mymatrix (r, ww + c) = 2 * al.array[r + ci] - 1;\n                }\n        }\n\n        // set interactions\n        ww = k + 1;\n        for (int c = 0; c < k; ++c) {\n                int ci = c + 1;\n                for (int c2 = 0; c2 < c; ++c2) {\n                        int ci2 = c2 + 1;\n\n                        for (int r = 0; r < n; ++r) {\n                                mymatrix (r, ww) = -mymatrix (r, ci) * mymatrix (r, ci2);\n                        }\n                        ww++;\n                }\n        }\n\n        return mymatrix;\n}\n\n/// convert 2-level design to second order interaction matrix\ninline void array2eigenxf (const array_link &al, Eigen::MatrixXd &mymatrix) {\n        int k = al.n_columns;\n        int n = al.n_rows;\n        int m = 1 + k + k * (k - 1) / 2;\n\n        mymatrix = Eigen::MatrixXd::Zero (n, m);\n\n        // init first column\n        int ww = 0;\n        for (int r = 0; r < n; ++r) {\n                mymatrix (r, ww) = 1;\n        }\n\n        // init array\n        ww = 1;\n        for (int c = 0; c < k; ++c) {\n                int ci = c * n;\n                for (int r = 0; r < n; ++r) {\n                        mymatrix (r, ww + c) = al.array[r + ci];\n                }\n        }\n\n        // init interactions\n        ww = k + 1;\n        for (int c = 0; c < k; ++c) {\n                int ci = c * n;\n                for (int c2 = 0; c2 < c; ++c2) {\n                        int ci2 = c2 * n;\n\n                        const array_t *p1 = al.array + ci;\n                        const array_t *p2 = al.array + ci2;\n                        for (int r = 0; r < n; ++r) {\n                                mymatrix (r, ww) = (*p1 + *p2) % 2;\n                                p1++;\n                                p2++;\n                        }\n                        ww++;\n                }\n        }\n\n        mymatrix.array () *= 2;\n        mymatrix.array () -= 1;\n}\n\narray_link array2secondorder (const array_link &al) {\n        int k = al.n_columns;\n        int nrows = al.n_rows;\n        int m = 1 + k + k * (k - 1) / 2;\n        int m2 = k * (k - 1) / 2;\n        array_link modelmatrix (nrows, m2, array_link::INDEX_DEFAULT);\n\n        // init interactions\n        int output_column_idx = 0;\n        for (int c = 0; c < k; ++c) {\n                int ci = c * nrows;\n\t\t\t\tconst array_t *p1 = al.array + ci;\n\t\t\t\tfor (int c2 = 0; c2 < c; ++c2) {\n                        int ci2 = c2 * nrows;\n\n                        const array_t *p2 = al.array + ci2;\n                        array_t *pout = modelmatrix.array + output_column_idx * modelmatrix.n_rows;\n\n                        for (int r = 0; r < nrows; ++r) {\n                                pout[r] = (p1[r] + p2[r]) % 2;\n                        }\n                        output_column_idx++;\n                }\n        }\n\n        modelmatrix *= 2;\n        modelmatrix -= 1;\n\n        return modelmatrix;\n}\n\narray_link array2xf (const array_link &al) {\n        const int k = al.n_columns;\n        const int nrows = al.n_rows;\n        const int m = 1 + k + k * (k - 1) / 2;\n\n        array_link modelmatrix (nrows, m, array_link::INDEX_DEFAULT);\n\n        // init first column\n        int ww = 0;\n        for (int r = 0; r < nrows; ++r) {\n                modelmatrix.array[r] = 1;\n        }\n\n        // init array\n        ww = 1;\n        for (int c = 0; c < k; ++c) {\n                int ci = c * nrows;\n                array_t *pout = modelmatrix.array + (ww + c) * modelmatrix.n_rows;\n                for (int r = 0; r < nrows; ++r) {\n                        pout[r] = 2 * al.array[r + ci] - 1;\n                }\n        }\n\n        // init interactions\n        ww = k + 1;\n        for (int c = 0; c < k; ++c) {\n                int ci = c * nrows + nrows;\n\t\t\t\tconst array_t *p1 = modelmatrix.array + ci;\n\t\t\t\tfor (int c2 = 0; c2 < c; ++c2) {\n                        int ci2 = c2 * nrows + nrows;\n\n                        const array_t *p2 = modelmatrix.array + ci2;\n                        array_t *pout = modelmatrix.array + ww * modelmatrix.n_rows;\n\n                        for (int r = 0; r < nrows; ++r) {\n                                pout[r] = -(p1[r] * p2[r]);\n                        }\n                        ww++;\n                }\n        }\n        return modelmatrix;\n}\n\nmodel_matrix_t _model2idx(const std::string mode) {\n\tif (mode == \"c\" || mode == \"constant\")\n\t\treturn MODEL_CONSTANT;\n\telse if (mode == \"linear\" || mode == \"main\" || mode ==\"m\" || mode==\"main_effects\")\n\t\treturn MODEL_MAIN;\n\telse if (mode == \"i\" || mode == \"interaction\")\n\t\treturn MODEL_INTERACTION;\n\telse if (mode == \"q\" || mode == \"quadratic\")\n\t\treturn MODEL_SECONDORDER;\n\telse throw_runtime_exception(printfstring(\"mode %s is not valid for model matrix\", mode.c_str()));\n\n\treturn MODEL_INVALID;\n}\n\narray_link conference_design2modelmatrix(const array_link & conference_design, const char*mode, int verbose)\n{\n\tstd::vector<int> sizes = array2modelmatrix_sizes(conference_design);\n\tmodel_matrix_t model_type_idx = _model2idx(mode);\n\tconst int n_columns = conference_design.n_columns;\n\tconst int n_rows = conference_design.n_rows;\n\n\tarray_link model_matrix(conference_design.n_rows, sizes[model_type_idx], array_link::INDEX_DEFAULT);\n\tmodel_matrix.setconstant(1);\n\n\t// main effects\n\tif (model_type_idx >= 2) {\n\t\tfor (int column = 0; column < n_columns; column++) {\n\t\t\tfor (int row = 0; row < conference_design.n_rows; row++) {\n\t\t\t\tmodel_matrix.at(row, column + sizes[0]) = conference_design.at(row, column);\n\t\t\t}\n\t\t}\n\t}\n\t// interactions\n\tif (model_type_idx >= 2) {\n\t\tint column_index = 0;\n\t\tfor (int column1 = 0; column1 < n_columns; column1++) {\n\t\t\tfor (int column2 = 0; column2 < column1; column2++) {\n\t\t\t\tfor (int row = 0; row < conference_design.n_rows; row++) {\n\t\t\t\t\tmodel_matrix.atfast(row, column_index + sizes[1]) = conference_design.atfast(row, column1)*conference_design.atfast(row, column2);\n\t\t\t\t}\n\t\t\t\tcolumn_index++;\n\t\t\t}\n\t\t}\n\t}\n\tif (model_type_idx == 3) {\n\t\t// quadratics\n\t\tfor (int column = 0; column < n_columns; column++) {\n\t\t\tfor (int row = 0; row < conference_design.n_rows; row++) {\n\t\t\t\tmodel_matrix.at(row, column + sizes[2]) = conference_design.at(row, column)*conference_design.at(row, column);\n\t\t\t}\n\t\t}\n\t}\n\treturn model_matrix;\n}\n\nEigen::MatrixXd array2modelmatrix(const array_link & array, const char*mode, int verbose)\n{\n\tif (array.is_orthogonal_array()) {\n\t\tconst int n_columns = array.n_columns;\n\t\tconst int n_rows = array.n_rows;\n\t\tstd::vector<int> sizes = array2modelmatrix_sizes(array);\n\t\tmodel_matrix_t model_type_idx = _model2idx(mode);\n\n\t\tif (verbose)\n\t\t\tmyprintf(\"array2modelmatrix: type orthogonal array, model_matrix_t %d\\n\", _model2idx(mode));\n\n\t\tif (model_type_idx == MODEL_SECONDORDER)\n\t\t\tthrow_runtime_exception(\"quadratic mode not implemented\");\n\n\t\tMatrixFloat model_matrix = array.getModelMatrix(2, 1);\n\t\tif (verbose>=2)\n\t\t\teigenInfo(model_matrix, \"array2modelmatrix: model_matrix\", 1);\n\t\tmodel_matrix = model_matrix.block(0,0,n_rows, sizes[model_type_idx]);\n\t\treturn model_matrix;\n\n\t}\n\tif (array.is_conference()) {\n\t\tif (verbose)\n\t\t\tmyprintf(\"array2modelmatrix: type conference, model_type_idx %d\\n\", _model2idx(mode));\n\t\tarray_link model_matrix = conference_design2modelmatrix(array, mode, verbose);\n\t\treturn model_matrix.getEigenMatrix();\n\t}\n\n\tthrow_runtime_exception(\"no modelmatrix for array type\");\n\treturn MatrixFloat();\n}\n\nstd::vector<int> array2modelmatrix_sizes(const array_link & array)\n{\n    std::vector<int> modelmatrix_components_sizes = numberModelParams(array);\n\n\tstd::vector<int> modelmatrix_sizes(modelmatrix_components_sizes.size());\n\tstd::partial_sum(modelmatrix_components_sizes.begin(), modelmatrix_components_sizes.end(), modelmatrix_sizes.begin(), std::plus<int>());\n\treturn modelmatrix_sizes;\n}\n\nusing namespace Eigen;\n\n#include <Eigen/LU>\n\nvoid DAEefficiencyWithSVD (const Eigen::MatrixXd &secondorder_interaction_matrix, double &Deff, double &vif, double &Eeff, int &rank, int verbose) {\n        Eigen::FullPivLU< MatrixXd > lu_decomp (secondorder_interaction_matrix);\n        rank = lu_decomp.rank ();\n\n        JacobiSVD< Eigen::MatrixXd > svd (secondorder_interaction_matrix);\n\n        const Eigen::VectorXd S = svd.singularValues ();\n        int rank2 = svd.nonzeroSingularValues ();\n        if (rank2 != rank) {\n                if (verbose >= 3) {\n                        myprintf (\"DAEefficiencyWithSVD: rank calculations differ, unstable matrix: ranklu %d, ranksvd: %d\\n\",\n                                  rank, rank2);\n                }\n        }\n        int m = secondorder_interaction_matrix.cols ();\n        int N = secondorder_interaction_matrix.rows ();\n\n        if (m > N) {\n                Deff = 0;\n                vif = 0;\n                Eeff = 0;\n\n                return;\n        }\n        if (verbose >= 3)\n                myprintf (\"N %d, m %d\\n\", N, m);\n\n        if (S[m - 1] < 1e-15 || rank < m) {\n                if (verbose >= 2) {\n                        myprintf (\"   array is singular, setting D-efficiency to zero\\n\");\n\n                }\n                Deff = 0;\n                vif = 0;\n                Eeff = 0;\n\n                if (verbose >= 3) {\n                        int rankold = rank2;\n                        Eigen::MatrixXd Smat (S);\n                        Eigen::ArrayXd Sa = Smat.array ();\n                        double Deff = exp (2 * Sa.log ().sum () / m) / N;\n\n                        std::cout << \"  singular matrix: the rank of A is \" << rank << std::endl;\n                        myprintf (\"   Deff %e, smallest eigenvalue %e, rankold %d, rank lu %d\\n\", Deff, S[m - 1],\n                                  rankold, rank);\n                }\n                if (verbose >= 4)\n                        std::cout << \"Its singular values are:\" << std::endl << S << std::endl;\n                return;\n        }\n\n        Eeff = S[m - 1] * S[m - 1] / N;\n\n        vif = 0;\n        for (int i = 0; i < m; i++)\n                vif += 1 / (S[i] * S[i]);\n        vif = N * vif / m;\n\n        Eigen::MatrixXd Smat (S);\n        Eigen::ArrayXd Sa = Smat.array ();\n        Deff = exp (2 * Sa.log ().sum () / m) / N;\n\n        if (verbose >= 2) {\n                myprintf (\"ABwithSVD: Defficiency %.3f, Aefficiency %.3f (%.3f), Eefficiency %.3f\\n\", Deff, vif,\n                          vif * m, Eeff);\n\n                Eigen::FullPivLU< MatrixXd > lu (secondorder_interaction_matrix);\n                int ranklu = lu.rank ();\n\n                myprintf (\"   Defficiency %e, smallest eigenvalue %e, rank %d, rank lu %d\\n\", Deff, S[m - 1], rank,\n                          ranklu);\n        }\n}\n\nint array2rank_Deff_Beff (const array_link &al, std::vector< double > *return_values, int verbose) {\n        int k = al.n_columns;\n        int n = al.n_rows;\n        int m = 1 + k + k * (k - 1) / 2;\n\n        Eigen::MatrixXd mymatrix (n, m);\n        array2eigenxf (al, mymatrix);\n\n        double Deff;\n        double Beff;\n        double Eeff;\n        int rank;\n\n        DAEefficiencyWithSVD (mymatrix, Deff, Beff, Eeff, rank, verbose);\n\n        if (return_values != 0) {\n                return_values->push_back (rank);\n                return_values->push_back (Deff);\n                return_values->push_back (Beff);\n                return_values->push_back (Eeff);\n        }\n        return rank;\n}\n\nstd::vector< double > Aefficiencies (const array_link &al, int verbose) {\n        myassert (al.is2level (), \"array is not 2-level\");\n        int N = al.n_rows;\n        int k = al.n_columns;\n        int m = 1 + k + (k * (k - 1)) / 2;\n        if (verbose)\n                printf (\"Aefficiencies: array %d, %d\\n\", N, k);\n        MatrixFloat modelmatrix = array2eigenModelMatrix (al);\n\n        Eigen::FullPivLU< MatrixXd > lu_decomp (modelmatrix);\n        int rank = lu_decomp.rank ();\n        if (rank < m) {\n                if (verbose)\n                        printf (\"Aefficiencies: rank %d/%d\\n\", rank, m);\n                std::vector< double > aa (3);\n                aa[0] = 0;\n                aa[1] = 0;\n                aa[2] = 0;\n                return aa;\n        }\n\n        if (verbose)\n                printf (\"Aefficiencies: calculate information matrix\\n\");\n\n        MatrixFloat information_matrix = (modelmatrix.transpose () * (modelmatrix)) / N;\n\n        if (verbose)\n                printf (\"Aefficiencies: invert information matrix\\n\");\n        MatrixFloat M = information_matrix.inverse ();\n\n        std::vector< double > aa (3);\n        double Ax = 0;\n        for (int i = 0; i < m; i++) {\n                Ax += M (i, i);\n        }\n        aa[0] = 1. / (Ax / m);\n        Ax = 0;\n        for (int i = 1; i < k + 1; i++) {\n                Ax += M (i, i);\n        }\n\n        aa[1] = 1. / (Ax / k);\n        Ax = 0;\n        for (int i = k + 1; i < m; i++) {\n                Ax += M (i, i);\n        }\n        aa[2] = 1. / (Ax / (k * (k - 1) / 2));\n        return aa;\n}\n\ndouble VIFefficiency (const array_link &al, int verbose) {\n        std::vector< double > ret;\n        array2rank_Deff_Beff (al, &ret, verbose);\n        return ret[2];\n}\n\ndouble Aefficiency (const array_link &al, int verbose) {\n\t\tdouble vif = VIFefficiency(al);\n        if (vif == 0)\n                return 0;\n        else\n                return 1. / vif;\n}\n\ndouble Eefficiency (const array_link &al, int verbose) {\n        std::vector< double > ret;\n        int r = array2rank_Deff_Beff (al, &ret, verbose);\n        return ret[3];\n}\n\nstd::vector< int > Jcharacteristics (const array_link &al, int jj, int verbose) {\n        jstruct_t js (al, jj);\n        return js.values;\n}\n\n/// calculate determinant of X^T X by using the SVD\ndouble detXtX (const Eigen::MatrixXd &mymatrix, int verbose) {\n        double dd = -1;\n        int m = mymatrix.cols ();\n\n        Eigen::MatrixXd mm = mymatrix.transpose () * mymatrix;\n        SelfAdjointEigenSolver< Eigen::MatrixXd > es;\n        es.compute (mm);\n        const Eigen::VectorXd evs = es.eigenvalues ();\n        Eigen::VectorXd S = evs; // sqrt(S);\n\n        if (S[m - 1] < 1e-15) {\n                if (verbose >= 2) {\n                        myprintf (\"   array is singular, setting det to zero\\n\");\n                }\n                dd = 0;\n                return dd;\n        }\n\n        for (int j = 0; j < m; j++) {\n                if (S[j] < 1e-14) {\n                        if (verbose >= 3)\n                                myprintf (\"  singular!\\n\");\n                        S[j] = 0;\n                } else {\n                        S[j] = sqrt (S[j]);\n                }\n        }\n\n        Eigen::MatrixXd Smat (S);\n        Eigen::ArrayXd Sa = Smat.array ();\n        dd = exp (2 * Sa.log ().sum ());\n\n        if (S[0] < 1e-15) {\n                if (verbose >= 2)\n                        myprintf (\"Avalue: singular matrix\\n\");\n                dd = 0;\n                return dd;\n        }\n        return dd;\n}\n\ntypedef Eigen::MatrixXf MyMatrixf;\ntypedef Eigen::ArrayXf MyArrayf;\ntypedef Eigen::VectorXf MyVectorf;\n\n/// calculate determinant of X^T X by using the SVD\ndouble detXtXfloat (const MyMatrixf &mymatrix, int verbose) {\n        double dd = -1;\n        int m = mymatrix.cols ();\n\n        MyMatrixf mm = mymatrix.transpose () * mymatrix;\n        SelfAdjointEigenSolver< MyMatrixf > es;\n        es.compute (mm);\n        const MyVectorf evs = es.eigenvalues ();\n        MyVectorf S = evs;\n\n        if (S[m - 1] < 1e-15) {\n                if (verbose >= 2) {\n                        myprintf (\"   array is singular, setting det to zero\\n\");\n                }\n                dd = 0;\n                return dd;\n        }\n\n        for (int j = 0; j < m; j++) {\n                if (S[j] < 1e-14) {\n                        if (verbose >= 3)\n                                myprintf (\"  singular!\\n\");\n                        S[j] = 0;\n                } else {\n                        S[j] = sqrt (S[j]);\n                }\n        }\n\n        MyMatrixf Smat (S);\n        MyArrayf Sa = Smat.array ();\n        dd = exp (2 * Sa.log ().sum ());\n\n        if (S[0] < 1e-15) {\n                if (verbose >= 2)\n                        myprintf (\"Avalue: singular matrix\\n\");\n                dd = 0;\n                return dd;\n        }\n        return dd;\n}\n\n// typedef Eigen::MatrixXd MyMatrix;\ntypedef MatrixFloat EigenMatrixFloat;\n\nstd::vector< double > Defficiencies (const array_link &array, const arraydata_t &arrayclass, int verbose, int addDs0) {\n        if ((array.n_rows > 500) || (array.n_columns > 500)) {\n                myprintf (\"Defficiencies: array size not supported\\n\");\n                return std::vector< double > (3);\n        }\n\n        int k = array.n_columns;\n        int k1 = array.n_columns + 1;\n        int nrows = array.n_rows;\n        int m = 1 + k + k * (k - 1) / 2;\n\n        EigenMatrixFloat X;\n\n\t\t/// number of 2-factor interactions in contrast matrix\n        int n2fi = -1;\n        /// number of main effects in contrast matrix\n        int size_main_effects = -1;\n\n        if (arrayclass.is2level ()) {\n\n                X = array2eigenModelMatrix (array);\n\n                n2fi = k * (k - 1) / 2;\n                size_main_effects = k;\n        } else {\n                if (verbose >= 2)\n                        myprintf (\"Defficiencies: mixed design!\\n\");\n                std::pair< EigenMatrixFloat, EigenMatrixFloat > mm = array2eigenModelMatrixMixed (array, 0);\n                const EigenMatrixFloat &X1 = mm.first;\n                const EigenMatrixFloat &X2 = mm.second;\n                X.resize (nrows, 1 + X1.cols () + X2.cols ());\n                X << EigenMatrixFloat::Constant (nrows, 1, 1), X1, X2;\n\n                n2fi = X2.cols ();\n                size_main_effects = X1.cols ();\n        }\n        EigenMatrixFloat matXtX = (X.transpose () * (X)) / nrows;\n\n        double f1 = matXtX.determinant ();\n\n        int number_model_columns = 1 + size_main_effects + n2fi;\n\n        EigenMatrixFloat tmp (number_model_columns, 1 + n2fi);\n        tmp << matXtX.block (0, 0, number_model_columns, 1), matXtX.block (0, 1 + size_main_effects, number_model_columns, n2fi);\n        EigenMatrixFloat mX02 (1 + n2fi, 1 + n2fi);\n        mX02 << tmp.block (0, 0, 1, 1 + n2fi), tmp.block (1 + size_main_effects, 0, n2fi, 1 + n2fi);\n\n        double f2i = (mX02).determinant ();\n        double t = (matXtX.block (0, 0, 1 + size_main_effects, 1 + size_main_effects)).determinant ();\n\n        double D = 0, Ds = 0, D1 = 0;\n        int rank = m;\n        if (fabs (f1) < 1e-15) {\n                Eigen::FullPivLU< EigenMatrixFloat > lu_decomp (X);\n                rank = lu_decomp.rank ();\n\n                if (verbose >= 1) {\n                        myprintf (\"Defficiencies: rank of model matrix %d/%d, f1 %e, f2i %e\\n\", rank, m, f1, f2i);\n                }\n        }\n        if (rank < m) {\n                if (verbose >= 1) {\n                        myprintf (\"Defficiencies: model matrix does not have max rank, setting D-efficiency to zero \"\n                                  \"(f1 %e)\\n\",\n                                  f1);\n                        myprintf (\"   rank lu_decomp %d/%d\\n\", rank, m);\n                        myprintf (\"   calculated D %f\\n\", pow (f1, 1. / m));\n                }\n\n        } else {\n                if (verbose >= 2) {\n                        myprintf (\"Defficiencies: f1 %f, f2i %f, t %f\\n\", f1, f2i, t);\n                }\n\n                Ds = pow ((f1 / f2i), 1. / k);\n                D = pow (f1, 1. / m);\n        }\n        D1 = pow (t, 1. / k1);\n\n        if (verbose >= 2) {\n                myprintf (\"Defficiencies: D %f, Ds %f, D1 %f\\n\", D, Ds, D1);\n        }\n\n        std::vector< double > efficiencies (3);\n        efficiencies[0] = D;\n        efficiencies[1] = Ds;\n        efficiencies[2] = D1;\n\n        if (addDs0) {\n                double f2 = (matXtX.block (1 + size_main_effects, 1 + size_main_effects, n2fi, n2fi)).determinant ();\n                double Ds0 = 0;\n                if (fabs (f1) >= 1e-15) {\n                        Ds0 = pow ((f1 / f2), 1. / k1);\n                }\n                efficiencies.push_back (Ds0);\n        }\n        return efficiencies;\n}\n\ntypedef MatrixFloat DMatrix;\ntypedef VectorFloat DVector;\ntypedef ArrayFloat DArray;\n\ndouble Defficiency (const array_link &al, int verbose) {\n        int k = al.n_columns;\n        int n = al.n_rows;\n        int m = 1 + k + k * (k - 1) / 2;\n        int N = n;\n        double Deff = -1;\n\n        DMatrix mymatrix = array2eigenModelMatrix (al);\n\n        Eigen::FullPivLU< DMatrix > lu_decomp (mymatrix);\n        int rank = lu_decomp.rank ();\n\n        DMatrix mm = mymatrix.transpose () * mymatrix;\n        SelfAdjointEigenSolver< DMatrix > es;\n        es.compute (mm);\n        const DVector evs = es.eigenvalues ();\n        DVector S = evs;\n\n        if (S[m - 1] < 1e-15 || rank < m) {\n                if (verbose >= 2) {\n\n                        Eigen::FullPivLU< DMatrix > lu_decomp2 (mm);\n                        int rank2 = lu_decomp2.rank ();\n\n                        myprintf (\"Defficiency: array is singular (rank %d/%d/%d), setting D-efficiency to zero \"\n                                  \"(S[m-1] %e)\\n\",\n                                  rank, rank2, m, S[m - 1]);\n                }\n                Deff = 0;\n                return Deff;\n        }\n\n        for (int j = 0; j < m; j++) {\n                if (S[j] < 1e-14) {\n                        if (verbose >= 3)\n                                myprintf (\"  singular!\\n\");\n                        S[j] = 0;\n                } else {\n                        S[j] = sqrt (S[j]);\n                }\n        }\n\n        if (verbose >= 2) {\n                JacobiSVD< DMatrix > svd (mymatrix);\n                const DVector S2 = svd.singularValues ();\n\n                if (!(S2[m - 1] < 1e-15)) {\n                        for (int ii = 0; ii < m - 3; ii++) {\n                                myprintf (\"ii %d: singular values sqrt(SelfAdjointEigenSolver) SelfAdjointEigenSolver \"\n                                          \"svd %f %f %f\\n\",\n                                          ii, (double)S[m - ii - 1], (double)evs[m - ii - 1], (double)S2[ii]);\n                        }\n                        for (int ii = m - 3; ii < m - 1; ii++) {\n                                myprintf (\"ii %d: %f %f %f\\n\", ii, (double)S[m - ii - 1], (double)evs[m - ii - 1],\n                                          (double)S2[ii]);\n                        }\n\n                        DMatrix Smat (S);\n                        DArray Sa = Smat.array ();\n                        Deff = exp (2 * Sa.log ().sum () / m) / N;\n                        myprintf (\"  Aold: %.6f\\n\", Deff);\n                }\n        }\n\n        if (S[0] < 1e-15) {\n                if (verbose >= 2)\n                        myprintf (\"Avalue: singular matrix\\n\");\n                Deff = 0;\n                return Deff;\n        }\n\n        DMatrix Smat (S);\n        DArray Sa = Smat.array ();\n        Deff = exp (2 * Sa.log ().sum () / m) / N;\n\n        if (verbose >= 2) {\n                myprintf (\"Avalue: A %.6f (S[0] %e)\\n\", Deff, S[0]);\n        }\n\n        Deff = std::min (Deff, 1.); // for numerical stability\n        return Deff;\n}\n\ndouble CL2discrepancy (const array_link &al) {\n        const int m = al.n_columns;\n\n        std::vector< double > gwp = al.GWLP ();\n\n        double v = 1;\n        for (int k = 1; k <= m; k++) {\n                v += gwp[k] / std::pow (double(9), k);\n        }\n        double w = std::pow (double(13) / 12, m) - 2 * pow (35. / 32, m) + std::pow (9. / 8, m) * v;\n\n        return w;\n}\n\n\ntypedef Pareto< mvalue_t< long >, array_link >::pValue (*pareto_cb) (const array_link &, int);\n\n/** Calculate the Pareto optimal arrays from a list of array files\n\n    Pareto optimality is calculated according to (rank; A3,A4; F4)\n*/\nvoid calculateParetoEvenOdd (const std::vector< std::string > infiles, const char *outfile, int verbose,\n                             arrayfilemode_t afmode, int nrows, int ncols, paretomethod_t paretomethod) {\n        pareto_cb paretofunction = calculateArrayParetoRankFA< array_link >;\n        switch (paretomethod) {\n        case PARETOFUNCTION_J5:\n                paretofunction = calculateArrayParetoJ5< array_link >;\n                break;\n        default:\n                break;\n        }\n        Pareto< mvalue_t< long >, array_link > pset;\n\n        long ntotal = 0;\n        for (size_t i = 0; i < infiles.size (); i++) {\n                // open arrayfile\n                arrayfile_t af (infiles[i].c_str ());\n\n                if (verbose) {\n                        myprintf (\"calculateParetoEvenOdd: read file %s (%d arrays)\\n\", af.filename.c_str (),\n                                  af.narrays);\n                }\n                int narrays = af.narrays;\n#pragma omp parallel for\n                for (int k = 0; k < narrays; k++) {\n                        array_link al;\n#pragma omp critical\n                        {\n                                al = af.readnext ();\n                                ntotal++;\n                        }\n                        Pareto< mvalue_t< long >, array_link >::pValue p = paretofunction (al, verbose >= 3);\n\n                        if (verbose >= 2) {\n                                printf (\"values: \");\n                                Pareto< mvalue_t< long >, array_link >::showvalue (p);\n                        }\n#pragma omp critical\n                        {\n                                // add the new tuple to the Pareto set\n                                pset.addvalue (p, al);\n                        }\n\n#pragma omp critical\n                        {\n                                if (verbose >= 2 || (k % 500000 == 0 && k > 0)) {\n                                        printf (\"calculateParetoEvenOdd: file %d/%d, array %d/%d\\n\", (int)i,\n                                                (int)infiles.size (), k, narrays);\n                                }\n                        }\n                }\n        }\n\n        if (verbose)\n                printf (\"calculateParetoEvenOdd: %ld arrays -> %d pareto values, %d pareto arrays \\n\", ntotal,\n                        pset.number (), pset.numberindices ());\n\n        if (verbose) {\n                pset.show (verbose);\n        }\n\n        arraylist_t lst = pset.allindicesdeque ();\n\n        // write files to disk\n        if (verbose)\n                printf (\"calculateParetoEvenOdd: writing arrays to file %s\\n\", outfile);\n        if (verbose >= 3) {\n                printf (\"calculateParetoEvenOdd: afmode %d (TEXT %d)\\n\", afmode, ATEXT);\n        }\n\n        if (outfile != 0) {\n                writearrayfile (outfile, lst, afmode, nrows, ncols);\n        }\n        return;\n}\n\nPareto< mvalue_t< long >, long > parsePareto (const arraylist_t &arraylist, int verbose, paretomethod_t paretomethod) {\n        pareto_cb paretofunction = calculateArrayParetoRankFA< array_link >;\n        switch (paretomethod) {\n        case PARETOFUNCTION_J5:\n                paretofunction = calculateArrayParetoJ5< array_link >;\n                break;\n        default:\n                break;\n        }\n\n        Pareto< mvalue_t< long >, long > pset;\n        pset.verbose = verbose;\n\n#pragma omp parallel for num_threads(4) schedule(dynamic, 1)\n        for (size_t i = 0; i < arraylist.size (); i++) {\n                if (verbose >= 2 || ((i % 2000 == 0) && verbose >= 1)) {\n                        myprintf (\"parsePareto: array %ld/%ld\\n\", (long)i, (long)arraylist.size ());\n                }\n                if (((i % 10000 == 0) && verbose >= 1)) {\n                        pset.show (1);\n                }\n                const array_link &al = arraylist.at (i);\n\n                Pareto< mvalue_t< long >, long >::pValue p = paretofunction (al, verbose);\n#pragma omp critical\n                {\n                        // add the new tuple to the Pareto set\n                        pset.addvalue (p, i);\n                }\n        }\n        return pset;\n}\n\nvoid addArray (Pareto< mvalue_t< long >, long > &pset, const array_link &al, int idx, int verbose,\n               paretomethod_t paretomethod) {\n        pareto_cb paretofunction = calculateArrayParetoRankFA< array_link >;\n        switch (paretomethod) {\n        case PARETOFUNCTION_J5:\n                paretofunction = calculateArrayParetoJ5< array_link >;\n                break;\n        default:\n                break;\n        }\n        Pareto< mvalue_t< long >, long >::pValue p = paretofunction (al, verbose);\n        pset.addvalue (p, idx);\n}\n\ntemplate Pareto< mvalue_t< long >, array_link >::pValue calculateArrayParetoJ5< array_link > (const array_link &al,\n                                                                                              int verbose);\ntemplate Pareto< mvalue_t< long >, int >::pValue calculateArrayParetoJ5< int > (const array_link &al, int verbose);\ntemplate Pareto< mvalue_t< long >, long >::pValue calculateArrayParetoJ5< long > (const array_link &al, int verbose);\n", "meta": {"hexsha": "67d24013c834a966748cac25385d9131490dcbd7", "size": 58132, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/arrayproperties.cpp", "max_stars_repo_name": "ABohynDOE/oapackage", "max_stars_repo_head_hexsha": "d4df98ee94ecd98e5e9eec62dc29df9a7ec8c9ce", "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/arrayproperties.cpp", "max_issues_repo_name": "ABohynDOE/oapackage", "max_issues_repo_head_hexsha": "d4df98ee94ecd98e5e9eec62dc29df9a7ec8c9ce", "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/arrayproperties.cpp", "max_forks_repo_name": "ABohynDOE/oapackage", "max_forks_repo_head_hexsha": "d4df98ee94ecd98e5e9eec62dc29df9a7ec8c9ce", "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.3134670487, "max_line_length": 179, "alphanum_fraction": 0.4978841258, "num_tokens": 15496, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.45774344566918956}}
{"text": "// ---------------------------------------------------------------------\n//\n// Copyright (c) 2014 - 2019 by the IBAMR developers\n// All rights reserved.\n//\n// This file is part of IBAMR.\n//\n// IBAMR is free software and is distributed under the 3-clause BSD\n// license. The full text of the license can be found in the file\n// COPYRIGHT at the top level directory of IBAMR.\n//\n// ---------------------------------------------------------------------\n\n/////////////////////////////// INCLUDES /////////////////////////////////////\n\n#include \"ibtk/IndexUtilities.h\"\n#include \"ibtk/LData.h\"\n#include \"ibtk/LEInteractor.h\"\n#include \"ibtk/LIndexSetData.h\"\n#include \"ibtk/LSet.h\"\n#include \"ibtk/app_namespaces.h\" // IWYU pragma: keep\n#include \"ibtk/ibtk_utilities.h\"\n\n#include \"ArrayData.h\"\n#include \"Box.h\"\n#include \"CartesianPatchGeometry.h\"\n#include \"CellData.h\"\n#include \"EdgeData.h\"\n#include \"EdgeGeometry.h\"\n#include \"Index.h\"\n#include \"NodeData.h\"\n#include \"NodeGeometry.h\"\n#include \"Patch.h\"\n#include \"SideData.h\"\n#include \"SideGeometry.h\"\n#include \"tbox/Database.h\"\n#include \"tbox/Pointer.h\"\n#include \"tbox/Utilities.h\"\n\nIBTK_DISABLE_EXTRA_WARNINGS\n#include <Eigen/Dense>\nIBTK_ENABLE_EXTRA_WARNINGS\n\nIBTK_DISABLE_EXTRA_WARNINGS\n#include <boost/multi_array.hpp>\nIBTK_ENABLE_EXTRA_WARNINGS\n\n#include <algorithm>\n#include <array>\n#include <cmath>\n#include <ostream>\n#include <string>\n#include <vector>\n\n// FORTRAN ROUTINES\n#if (NDIM == 2)\n#define LAGRANGIAN_PIECEWISE_CONSTANT_INTERP_FC                                                                        \\\n    IBTK_FC_FUNC_(lagrangian_piecewise_constant_interp2d, LAGRANGIAN_PIECEWISE_CONSTANT_INTERP2D)\n#define LAGRANGIAN_PIECEWISE_CONSTANT_SPREAD_FC                                                                        \\\n    IBTK_FC_FUNC_(lagrangian_piecewise_constant_spread2d, LAGRANGIAN_PIECEWISE_CONSTANT_SPREAD2D)\n\n#define LAGRANGIAN_DISCONTINUOUS_LINEAR_INTERP_FC                                                                      \\\n    IBTK_FC_FUNC_(lagrangian_discontinuous_linear_interp2d, LAGRANGIAN_DISCONTINUOUS_LINEAR_INTERP2D)\n#define LAGRANGIAN_DISCONTINUOUS_LINEAR_SPREAD_FC                                                                      \\\n    IBTK_FC_FUNC_(lagrangian_discontinuous_linear_spread2d, LAGRANGIAN_DISCONTINUOUS_LINEAR_SPREAD2D)\n\n#define LAGRANGIAN_PIECEWISE_LINEAR_INTERP_FC                                                                          \\\n    IBTK_FC_FUNC_(lagrangian_piecewise_linear_interp2d, LAGRANGIAN_PIECEWISE_LINEAR_INTERP2D)\n#define LAGRANGIAN_PIECEWISE_LINEAR_SPREAD_FC                                                                          \\\n    IBTK_FC_FUNC_(lagrangian_piecewise_linear_spread2d, LAGRANGIAN_PIECEWISE_LINEAR_SPREAD2D)\n\n#define LAGRANGIAN_PIECEWISE_CUBIC_INTERP_FC                                                                           \\\n    IBTK_FC_FUNC_(lagrangian_piecewise_cubic_interp2d, LAGRANGIAN_PIECEWISE_CUBIC_INTERP2D)\n#define LAGRANGIAN_PIECEWISE_CUBIC_SPREAD_FC                                                                           \\\n    IBTK_FC_FUNC_(lagrangian_piecewise_cubic_spread2d, LAGRANGIAN_PIECEWISE_CUBIC_SPREAD2D)\n\n#define LAGRANGIAN_IB_3_INTERP_FC IBTK_FC_FUNC_(lagrangian_ib_3_interp2d, LAGRANGIAN_IB_3_INTERP2D)\n#define LAGRANGIAN_IB_3_SPREAD_FC IBTK_FC_FUNC_(lagrangian_ib_3_spread2d, LAGRANGIAN_IB_3_SPREAD2D)\n\n#define LAGRANGIAN_IB_4_INTERP_FC IBTK_FC_FUNC_(lagrangian_ib_4_interp2d, LAGRANGIAN_IB_4_INTERP2D)\n#define LAGRANGIAN_IB_4_SPREAD_FC IBTK_FC_FUNC_(lagrangian_ib_4_spread2d, LAGRANGIAN_IB_4_SPREAD2D)\n\n#define LAGRANGIAN_IB_4_W8_INTERP_FC IBTK_FC_FUNC_(lagrangian_ib_4_w8_interp2d, LAGRANGIAN_IB_4_W8_INTERP2D)\n#define LAGRANGIAN_IB_4_W8_SPREAD_FC IBTK_FC_FUNC_(lagrangian_ib_4_w8_spread2d, LAGRANGIAN_IB_4_W8_SPREAD2D)\n\n#define LAGRANGIAN_IB_5_INTERP_FC IBTK_FC_FUNC_(lagrangian_ib_5_interp2d, LAGRANGIAN_ib_5_INTERP2D)\n#define LAGRANGIAN_IB_5_SPREAD_FC IBTK_FC_FUNC_(lagrangian_ib_5_spread2d, LAGRANGIAN_ib_5_SPREAD2D)\n\n#define LAGRANGIAN_IB_6_INTERP_FC IBTK_FC_FUNC_(lagrangian_ib_6_interp2d, LAGRANGIAN_IB_6_INTERP2D)\n#define LAGRANGIAN_IB_6_SPREAD_FC IBTK_FC_FUNC_(lagrangian_ib_6_spread2d, LAGRANGIAN_IB_6_SPREAD2D)\n\n#define LAGRANGIAN_BSPLINE_3_INTERP_FC IBTK_FC_FUNC_(lagrangian_bspline_3_interp2d, LAGRANGIAN_BSPLINE_3_INTERP2D)\n#define LAGRANGIAN_BSPLINE_3_SPREAD_FC IBTK_FC_FUNC_(lagrangian_bspline_3_spread2d, LAGRANGIAN_BSPLINE_3_SPREAD2D)\n\n#define LAGRANGIAN_BSPLINE_4_INTERP_FC IBTK_FC_FUNC_(lagrangian_bspline_4_interp2d, LAGRANGIAN_BSPLINE_4_INTERP2D)\n#define LAGRANGIAN_BSPLINE_4_SPREAD_FC IBTK_FC_FUNC_(lagrangian_bspline_4_spread2d, LAGRANGIAN_BSPLINE_4_SPREAD2D)\n\n#define LAGRANGIAN_BSPLINE_5_INTERP_FC IBTK_FC_FUNC_(lagrangian_bspline_5_interp2d, LAGRANGIAN_BSPLINE_5_INTERP2D)\n#define LAGRANGIAN_BSPLINE_5_SPREAD_FC IBTK_FC_FUNC_(lagrangian_bspline_5_spread2d, LAGRANGIAN_BSPLINE_5_SPREAD2D)\n\n#define LAGRANGIAN_BSPLINE_6_INTERP_FC IBTK_FC_FUNC_(lagrangian_bspline_6_interp2d, LAGRANGIAN_BSPLINE_6_INTERP2D)\n#define LAGRANGIAN_BSPLINE_6_SPREAD_FC IBTK_FC_FUNC_(lagrangian_bspline_6_spread2d, LAGRANGIAN_BSPLINE_6_SPREAD2D)\n#endif\n\n#if (NDIM == 3)\n#define LAGRANGIAN_PIECEWISE_CONSTANT_INTERP_FC                                                                        \\\n    IBTK_FC_FUNC_(lagrangian_piecewise_constant_interp3d, LAGRANGIAN_PIECEWISE_CONSTANT_INTERP3D)\n#define LAGRANGIAN_PIECEWISE_CONSTANT_SPREAD_FC                                                                        \\\n    IBTK_FC_FUNC_(lagrangian_piecewise_constant_spread3d, LAGRANGIAN_PIECEWISE_CONSTANT_SPREAD3D)\n\n#define LAGRANGIAN_DISCONTINUOUS_LINEAR_INTERP_FC                                                                      \\\n    IBTK_FC_FUNC_(lagrangian_discontinuous_linear_interp3d, LAGRANGIAN_DISCONTINUOUS_LINEAR_INTERP3D)\n#define LAGRANGIAN_DISCONTINUOUS_LINEAR_SPREAD_FC                                                                      \\\n    IBTK_FC_FUNC_(lagrangian_discontinuous_linear_spread3d, LAGRANGIAN_DISCONTINUOUS_LINEAR_SPREAD3D)\n\n#define LAGRANGIAN_PIECEWISE_LINEAR_INTERP_FC                                                                          \\\n    IBTK_FC_FUNC_(lagrangian_piecewise_linear_interp3d, LAGRANGIAN_PIECEWISE_LINEAR_INTERP3D)\n#define LAGRANGIAN_PIECEWISE_LINEAR_SPREAD_FC                                                                          \\\n    IBTK_FC_FUNC_(lagrangian_piecewise_linear_spread3d, LAGRANGIAN_PIECEWISE_LINEAR_SPREAD3D)\n\n#define LAGRANGIAN_PIECEWISE_CUBIC_INTERP_FC                                                                           \\\n    IBTK_FC_FUNC_(lagrangian_piecewise_cubic_interp3d, LAGRANGIAN_PIECEWISE_CUBIC_INTERP3D)\n#define LAGRANGIAN_PIECEWISE_CUBIC_SPREAD_FC                                                                           \\\n    IBTK_FC_FUNC_(lagrangian_piecewise_cubic_spread3d, LAGRANGIAN_PIECEWISE_CUBIC_SPREAD3D)\n\n#define LAGRANGIAN_IB_3_INTERP_FC IBTK_FC_FUNC_(lagrangian_ib_3_interp3d, LAGRANGIAN_IB_3_INTERP3D)\n#define LAGRANGIAN_IB_3_SPREAD_FC IBTK_FC_FUNC_(lagrangian_ib_3_spread3d, LAGRANGIAN_IB_3_SPREAD3D)\n\n#define LAGRANGIAN_IB_4_INTERP_FC IBTK_FC_FUNC_(lagrangian_ib_4_interp3d, LAGRANGIAN_IB_4_INTERP3D)\n#define LAGRANGIAN_IB_4_SPREAD_FC IBTK_FC_FUNC_(lagrangian_ib_4_spread3d, LAGRANGIAN_IB_4_SPREAD3D)\n\n#define LAGRANGIAN_IB_4_W8_INTERP_FC IBTK_FC_FUNC_(lagrangian_ib_4_w8_interp3d, LAGRANGIAN_IB_4_W8_INTERP3D)\n#define LAGRANGIAN_IB_4_W8_SPREAD_FC IBTK_FC_FUNC_(lagrangian_ib_4_w8_spread3d, LAGRANGIAN_IB_4_W8_SPREAD3D)\n\n#define LAGRANGIAN_IB_5_INTERP_FC IBTK_FC_FUNC_(lagrangian_ib_5_interp3d, LAGRANGIAN_ib_5_INTERP3D)\n#define LAGRANGIAN_IB_5_SPREAD_FC IBTK_FC_FUNC_(lagrangian_ib_5_spread3d, LAGRANGIAN_ib_5_SPREAD3D)\n\n#define LAGRANGIAN_IB_6_INTERP_FC IBTK_FC_FUNC_(lagrangian_ib_6_interp3d, LAGRANGIAN_IB_6_INTERP3D)\n#define LAGRANGIAN_IB_6_SPREAD_FC IBTK_FC_FUNC_(lagrangian_ib_6_spread3d, LAGRANGIAN_IB_6_SPREAD3D)\n\n#define LAGRANGIAN_BSPLINE_3_INTERP_FC IBTK_FC_FUNC_(lagrangian_bspline_3_interp3d, LAGRANGIAN_BSPLINE_3_INTERP3D)\n#define LAGRANGIAN_BSPLINE_3_SPREAD_FC IBTK_FC_FUNC_(lagrangian_bspline_3_spread3d, LAGRANGIAN_BSPLINE_3_SPREAD3D)\n\n#define LAGRANGIAN_BSPLINE_4_INTERP_FC IBTK_FC_FUNC_(lagrangian_bspline_4_interp3d, LAGRANGIAN_BSPLINE_4_INTERP3D)\n#define LAGRANGIAN_BSPLINE_4_SPREAD_FC IBTK_FC_FUNC_(lagrangian_bspline_4_spread3d, LAGRANGIAN_BSPLINE_4_SPREAD3D)\n\n#define LAGRANGIAN_BSPLINE_5_INTERP_FC IBTK_FC_FUNC_(lagrangian_bspline_5_interp3d, LAGRANGIAN_BSPLINE_5_INTERP3D)\n#define LAGRANGIAN_BSPLINE_5_SPREAD_FC IBTK_FC_FUNC_(lagrangian_bspline_5_spread3d, LAGRANGIAN_BSPLINE_5_SPREAD3D)\n\n#define LAGRANGIAN_BSPLINE_6_INTERP_FC IBTK_FC_FUNC_(lagrangian_bspline_6_interp3d, LAGRANGIAN_BSPLINE_6_INTERP3D)\n#define LAGRANGIAN_BSPLINE_6_SPREAD_FC IBTK_FC_FUNC_(lagrangian_bspline_6_spread3d, LAGRANGIAN_BSPLINE_6_SPREAD3D)\n#endif\n\nextern \"C\"\n{\n    void LAGRANGIAN_PIECEWISE_CONSTANT_INTERP_FC(const double*,\n                                                 const double*,\n                                                 const double*,\n                                                 const int&,\n#if (NDIM == 2)\n                                                 const int&,\n                                                 const int&,\n                                                 const int&,\n                                                 const int&,\n                                                 const int&,\n                                                 const int&,\n#endif\n#if (NDIM == 3)\n                                                 const int&,\n                                                 const int&,\n                                                 const int&,\n                                                 const int&,\n                                                 const int&,\n                                                 const int&,\n                                                 const int&,\n                                                 const int&,\n                                                 const int&,\n#endif\n                                                 const double*,\n                                                 const int*,\n                                                 const double*,\n                                                 const int&,\n                                                 const double*,\n                                                 double*);\n\n    void LAGRANGIAN_PIECEWISE_CONSTANT_SPREAD_FC(const double*,\n                                                 const double*,\n                                                 const double*,\n                                                 const int&,\n                                                 const int*,\n                                                 const double*,\n                                                 const int&,\n                                                 const double*,\n                                                 const double*,\n#if (NDIM == 2)\n                                                 const int&,\n                                                 const int&,\n                                                 const int&,\n                                                 const int&,\n                                                 const int&,\n                                                 const int&,\n#endif\n#if (NDIM == 3)\n                                                 const int&,\n                                                 const int&,\n                                                 const int&,\n                                                 const int&,\n                                                 const int&,\n                                                 const int&,\n                                                 const int&,\n                                                 const int&,\n                                                 const int&,\n#endif\n                                                 double*);\n\n    void LAGRANGIAN_DISCONTINUOUS_LINEAR_INTERP_FC(const double*,\n                                                   const double*,\n                                                   const double*,\n                                                   const int&,\n                                                   const int&,\n#if (NDIM == 2)\n                                                   const int&,\n                                                   const int&,\n                                                   const int&,\n                                                   const int&,\n                                                   const int&,\n                                                   const int&,\n#endif\n#if (NDIM == 3)\n                                                   const int&,\n                                                   const int&,\n                                                   const int&,\n                                                   const int&,\n                                                   const int&,\n                                                   const int&,\n                                                   const int&,\n                                                   const int&,\n                                                   const int&,\n#endif\n                                                   const double*,\n                                                   const int*,\n                                                   const double*,\n                                                   const int&,\n                                                   const double*,\n                                                   double*);\n\n    void LAGRANGIAN_DISCONTINUOUS_LINEAR_SPREAD_FC(const double*,\n                                                   const double*,\n                                                   const double*,\n                                                   const int&,\n                                                   const int&,\n                                                   const int*,\n                                                   const double*,\n                                                   const int&,\n                                                   const double*,\n                                                   const double*,\n#if (NDIM == 2)\n                                                   const int&,\n                                                   const int&,\n                                                   const int&,\n                                                   const int&,\n                                                   const int&,\n                                                   const int&,\n#endif\n#if (NDIM == 3)\n                                                   const int&,\n                                                   const int&,\n                                                   const int&,\n                                                   const int&,\n                                                   const int&,\n                                                   const int&,\n                                                   const int&,\n                                                   const int&,\n                                                   const int&,\n#endif\n                                                   double*);\n\n    void LAGRANGIAN_PIECEWISE_LINEAR_INTERP_FC(const double*,\n                                               const double*,\n                                               const double*,\n                                               const int&,\n#if (NDIM == 2)\n                                               const int&,\n                                               const int&,\n                                               const int&,\n                                               const int&,\n                                               const int&,\n                                               const int&,\n#endif\n#if (NDIM == 3)\n                                               const int&,\n                                               const int&,\n                                               const int&,\n                                               const int&,\n                                               const int&,\n                                               const int&,\n                                               const int&,\n                                               const int&,\n                                               const int&,\n#endif\n                                               const double*,\n                                               const int*,\n                                               const double*,\n                                               const int&,\n                                               const double*,\n                                               double*);\n\n    void LAGRANGIAN_PIECEWISE_LINEAR_SPREAD_FC(const double*,\n                                               const double*,\n                                               const double*,\n                                               const int&,\n                                               const int*,\n                                               const double*,\n                                               const int&,\n                                               const double*,\n                                               const double*,\n#if (NDIM == 2)\n                                               const int&,\n                                               const int&,\n                                               const int&,\n                                               const int&,\n                                               const int&,\n                                               const int&,\n#endif\n#if (NDIM == 3)\n                                               const int&,\n                                               const int&,\n                                               const int&,\n                                               const int&,\n                                               const int&,\n                                               const int&,\n                                               const int&,\n                                               const int&,\n                                               const int&,\n#endif\n                                               double*);\n\n    void LAGRANGIAN_PIECEWISE_CUBIC_INTERP_FC(const double*,\n                                              const double*,\n                                              const double*,\n                                              const int&,\n#if (NDIM == 2)\n                                              const int&,\n                                              const int&,\n                                              const int&,\n                                              const int&,\n                                              const int&,\n                                              const int&,\n#endif\n#if (NDIM == 3)\n                                              const int&,\n                                              const int&,\n                                              const int&,\n                                              const int&,\n                                              const int&,\n                                              const int&,\n                                              const int&,\n                                              const int&,\n                                              const int&,\n#endif\n                                              const double*,\n                                              const int*,\n                                              const double*,\n                                              const int&,\n                                              const double*,\n                                              double*);\n\n    void LAGRANGIAN_PIECEWISE_CUBIC_SPREAD_FC(const double*,\n                                              const double*,\n                                              const double*,\n                                              const int&,\n                                              const int*,\n                                              const double*,\n                                              const int&,\n                                              const double*,\n                                              const double*,\n#if (NDIM == 2)\n                                              const int&,\n                                              const int&,\n                                              const int&,\n                                              const int&,\n                                              const int&,\n                                              const int&,\n#endif\n#if (NDIM == 3)\n                                              const int&,\n                                              const int&,\n                                              const int&,\n                                              const int&,\n                                              const int&,\n                                              const int&,\n                                              const int&,\n                                              const int&,\n                                              const int&,\n#endif\n                                              double*);\n\n    void LAGRANGIAN_IB_3_INTERP_FC(const double*,\n                                   const double*,\n                                   const double*,\n                                   const int&,\n#if (NDIM == 2)\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n#endif\n#if (NDIM == 3)\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n#endif\n                                   const double*,\n                                   const int*,\n                                   const double*,\n                                   const int&,\n                                   const double*,\n                                   double*);\n\n    void LAGRANGIAN_IB_3_SPREAD_FC(const double*,\n                                   const double*,\n                                   const double*,\n                                   const int&,\n                                   const int*,\n                                   const double*,\n                                   const int&,\n                                   const double*,\n                                   const double*,\n#if (NDIM == 2)\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n#endif\n#if (NDIM == 3)\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n#endif\n                                   double*);\n\n    void LAGRANGIAN_IB_4_INTERP_FC(const double*,\n                                   const double*,\n                                   const double*,\n                                   const int&,\n#if (NDIM == 2)\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n#endif\n#if (NDIM == 3)\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n#endif\n                                   const double*,\n                                   const int*,\n                                   const double*,\n                                   const int&,\n                                   const double*,\n                                   double*);\n\n    void LAGRANGIAN_IB_4_SPREAD_FC(const double*,\n                                   const double*,\n                                   const double*,\n                                   const int&,\n                                   const int*,\n                                   const double*,\n                                   const int&,\n                                   const double*,\n                                   const double*,\n#if (NDIM == 2)\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n#endif\n#if (NDIM == 3)\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n#endif\n                                   double*);\n\n    void LAGRANGIAN_IB_4_W8_INTERP_FC(const double*,\n                                      const double*,\n                                      const double*,\n                                      const int&,\n#if (NDIM == 2)\n                                      const int&,\n                                      const int&,\n                                      const int&,\n                                      const int&,\n                                      const int&,\n                                      const int&,\n#endif\n#if (NDIM == 3)\n                                      const int&,\n                                      const int&,\n                                      const int&,\n                                      const int&,\n                                      const int&,\n                                      const int&,\n                                      const int&,\n                                      const int&,\n                                      const int&,\n#endif\n                                      const double*,\n                                      const int*,\n                                      const double*,\n                                      const int&,\n                                      const double*,\n                                      double*);\n\n    void LAGRANGIAN_IB_4_W8_SPREAD_FC(const double*,\n                                      const double*,\n                                      const double*,\n                                      const int&,\n                                      const int*,\n                                      const double*,\n                                      const int&,\n                                      const double*,\n                                      const double*,\n#if (NDIM == 2)\n                                      const int&,\n                                      const int&,\n                                      const int&,\n                                      const int&,\n                                      const int&,\n                                      const int&,\n#endif\n#if (NDIM == 3)\n                                      const int&,\n                                      const int&,\n                                      const int&,\n                                      const int&,\n                                      const int&,\n                                      const int&,\n                                      const int&,\n                                      const int&,\n                                      const int&,\n#endif\n                                      double*);\n\n    void LAGRANGIAN_IB_5_INTERP_FC(const double*,\n                                   const double*,\n                                   const double*,\n                                   const int&,\n#if (NDIM == 2)\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n#endif\n#if (NDIM == 3)\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n#endif\n                                   const double*,\n                                   const int*,\n                                   const double*,\n                                   const int&,\n                                   const double*,\n                                   double*);\n\n    void LAGRANGIAN_IB_5_SPREAD_FC(const double*,\n                                   const double*,\n                                   const double*,\n                                   const int&,\n                                   const int*,\n                                   const double*,\n                                   const int&,\n                                   const double*,\n                                   const double*,\n#if (NDIM == 2)\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n#endif\n#if (NDIM == 3)\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n#endif\n                                   double*);\n\n    void LAGRANGIAN_IB_6_INTERP_FC(const double*,\n                                   const double*,\n                                   const double*,\n                                   const int&,\n#if (NDIM == 2)\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n#endif\n#if (NDIM == 3)\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n#endif\n                                   const double*,\n                                   const int*,\n                                   const double*,\n                                   const int&,\n                                   const double*,\n                                   double*);\n\n    void LAGRANGIAN_IB_6_SPREAD_FC(const double*,\n                                   const double*,\n                                   const double*,\n                                   const int&,\n                                   const int*,\n                                   const double*,\n                                   const int&,\n                                   const double*,\n                                   const double*,\n#if (NDIM == 2)\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n#endif\n#if (NDIM == 3)\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n                                   const int&,\n#endif\n                                   double*);\n\n    void LAGRANGIAN_BSPLINE_3_INTERP_FC(const double*,\n                                        const double*,\n                                        const double*,\n                                        const int&,\n#if (NDIM == 2)\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n#endif\n#if (NDIM == 3)\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n#endif\n                                        const double*,\n                                        const int*,\n                                        const double*,\n                                        const int&,\n                                        const double*,\n                                        double*);\n\n    void LAGRANGIAN_BSPLINE_3_SPREAD_FC(const double*,\n                                        const double*,\n                                        const double*,\n                                        const int&,\n                                        const int*,\n                                        const double*,\n                                        const int&,\n                                        const double*,\n                                        const double*,\n#if (NDIM == 2)\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n#endif\n#if (NDIM == 3)\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n#endif\n                                        double*);\n\n    void LAGRANGIAN_BSPLINE_4_INTERP_FC(const double*,\n                                        const double*,\n                                        const double*,\n                                        const int&,\n#if (NDIM == 2)\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n#endif\n#if (NDIM == 3)\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n#endif\n                                        const double*,\n                                        const int*,\n                                        const double*,\n                                        const int&,\n                                        const double*,\n                                        double*);\n\n    void LAGRANGIAN_BSPLINE_4_SPREAD_FC(const double*,\n                                        const double*,\n                                        const double*,\n                                        const int&,\n                                        const int*,\n                                        const double*,\n                                        const int&,\n                                        const double*,\n                                        const double*,\n#if (NDIM == 2)\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n#endif\n#if (NDIM == 3)\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n#endif\n                                        double*);\n\n    void LAGRANGIAN_BSPLINE_5_INTERP_FC(const double*,\n                                        const double*,\n                                        const double*,\n                                        const int&,\n#if (NDIM == 2)\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n#endif\n#if (NDIM == 3)\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n#endif\n                                        const double*,\n                                        const int*,\n                                        const double*,\n                                        const int&,\n                                        const double*,\n                                        double*);\n\n    void LAGRANGIAN_BSPLINE_5_SPREAD_FC(const double*,\n                                        const double*,\n                                        const double*,\n                                        const int&,\n                                        const int*,\n                                        const double*,\n                                        const int&,\n                                        const double*,\n                                        const double*,\n#if (NDIM == 2)\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n#endif\n#if (NDIM == 3)\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n#endif\n                                        double*);\n\n    void LAGRANGIAN_BSPLINE_6_INTERP_FC(const double*,\n                                        const double*,\n                                        const double*,\n                                        const int&,\n#if (NDIM == 2)\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n#endif\n#if (NDIM == 3)\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n#endif\n                                        const double*,\n                                        const int*,\n                                        const double*,\n                                        const int&,\n                                        const double*,\n                                        double*);\n\n    void LAGRANGIAN_BSPLINE_6_SPREAD_FC(const double*,\n                                        const double*,\n                                        const double*,\n                                        const int&,\n                                        const int*,\n                                        const double*,\n                                        const int&,\n                                        const double*,\n                                        const double*,\n#if (NDIM == 2)\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n#endif\n#if (NDIM == 3)\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n                                        const int&,\n#endif\n                                        double*);\n}\n\n/////////////////////////////// NAMESPACE ////////////////////////////////////\n\nnamespace IBTK\n{\n/////////////////////////////// STATIC ///////////////////////////////////////\n\nnamespace\n{\ninline double\nib4_kernel_fcn(double r)\n{\n    r = std::abs(r);\n    if (r < 1.0)\n    {\n        const double t2 = r * r;\n        const double t6 = std::sqrt(-0.4e1 * t2 + 0.4e1 * r + 0.1e1);\n        return -r / 0.4e1 + 0.3e1 / 0.8e1 + t6 / 0.8e1;\n    }\n    else if (r < 2.0)\n    {\n        const double t2 = r * r;\n        const double t6 = std::sqrt(0.12e2 * r - 0.7e1 - 0.4e1 * t2);\n        return -r / 0.4e1 + 0.5e1 / 0.8e1 - t6 / 0.8e1;\n    }\n    else\n    {\n        return 0.0;\n    }\n}\n\ninline int\nNINT(double a)\n{\n    return (a >= 0.0 ? static_cast<int>(a + 0.5) : static_cast<int>(a - 0.5));\n}\n\nusing Weight = boost::multi_array<double, 1>;\nusing TensorProductWeights = std::array<Weight, NDIM>;\nusing MLSWeight = boost::multi_array<double, NDIM>;\n\nvoid\nperform_mls(const int stencil_sz,\n            const double* const X,\n            const int* const stencil_lower,\n            const int* const /*stencil_upper*/,\n            const double* const p_start,\n            const double* const dx,\n            const ArrayData<NDIM, double>& mask_data,\n            const TensorProductWeights& D,\n            MLSWeight& Psi)\n{\n    MLSWeight::extent_gen extents;\n    MLSWeight T;\n\n#if (NDIM == 2)\n    T.resize(extents[stencil_sz][stencil_sz]);\n    Psi.resize(extents[stencil_sz][stencil_sz]);\n#elif (NDIM == 3)\n    T.resize(extents[stencil_sz][stencil_sz][stencil_sz]);\n    Psi.resize(extents[stencil_sz][stencil_sz][stencil_sz]);\n#endif\n\n    // Compute the tensor product of the weights.\n    double x[NDIM], p_j, p_k;\n#if (NDIM == 3)\n    for (int i2 = 0; i2 < stencil_sz; ++i2)\n    {\n        const int ic2 = stencil_lower[2] + i2;\n#endif\n        for (int i1 = 0; i1 < stencil_sz; ++i1)\n        {\n            const int ic1 = stencil_lower[1] + i1;\n            for (int i0 = 0; i0 < stencil_sz; ++i0)\n            {\n                const int ic0 = stencil_lower[0] + i0;\n#if (NDIM == 2)\n                const hier::Index<NDIM> idx(ic0, ic1);\n                T[i1][i0] = D[0][i0] * D[1][i1] * mask_data(idx, /*depth*/ 0);\n#elif (NDIM == 3)\n                const hier::Index<NDIM> idx(ic0, ic1, ic2);\n                T[i2][i1][i0] = D[0][i0] * D[1][i1] * D[2][i2] * mask_data(idx, /*depth*/ 0);\n#endif\n            }\n        }\n#if (NDIM == 3)\n    }\n#endif\n\n    // Set the Gram matrix and the RHS.\n    // Here we are solving the equation of the type G L = p, in which p\n    // is the vector of basis functions that we want to reproduce, G is Gram\n    // matrix and L is Lagrange muliplier which imposes the reproducibilty constraint.\n    Eigen::Matrix<double, NDIM + 1, NDIM + 1> G;\n    G.setZero();\n    Eigen::Matrix<double, NDIM + 1, 1> p, L;\n    p[0] = 1.0;\n    for (unsigned int d = 0; d < NDIM; ++d)\n    {\n        p[d + 1] = X[d];\n    }\n\n    for (int j = 0; j <= NDIM; ++j)\n    {\n        for (int k = 0; k <= NDIM; ++k)\n        {\n#if (NDIM == 3)\n            for (int i2 = 0; i2 < stencil_sz; ++i2)\n            {\n                x[2] = p_start[2] + i2 * dx[2];\n#endif\n                for (int i1 = 0; i1 < stencil_sz; ++i1)\n                {\n                    x[1] = p_start[1] + i1 * dx[1];\n                    for (int i0 = 0; i0 < stencil_sz; ++i0)\n                    {\n                        x[0] = p_start[0] + i0 * dx[0];\n\n#if (NDIM == 2)\n                        p_j = j == 0 ? 1.0 : (j == 1 ? x[0] : x[1]);\n                        p_k = k == 0 ? 1.0 : (k == 1 ? x[0] : x[1]);\n                        G(j, k) += p_j * p_k * T[i1][i0];\n#elif (NDIM == 3)\n                        p_j = j == 0 ? 1.0 : (j == 1 ? x[0] : j == 2 ? x[1] : x[2]);\n                        p_k = k == 0 ? 1.0 : (k == 1 ? x[0] : k == 2 ? x[1] : x[2]);\n                        G(j, k) += p_j * p_k * T[i2][i1][i0];\n#endif\n                    }\n                }\n#if (NDIM == 3)\n            }\n#endif\n        }\n    }\n\n    // Solve the system for L\n    L = G.ldlt().solve(p);\n\n    // Find the modified weights using the Lagrange multiplier and to-be-reproduced\n    // polynomial basis.\n    std::fill(Psi.origin(), Psi.origin() + Psi.num_elements(), 0.0);\n#if (NDIM == 3)\n    for (int i2 = 0; i2 < stencil_sz; ++i2)\n    {\n        x[2] = p_start[2] + i2 * dx[2];\n#endif\n        for (int i1 = 0; i1 < stencil_sz; ++i1)\n        {\n            x[1] = p_start[1] + i1 * dx[1];\n            for (int i0 = 0; i0 < stencil_sz; ++i0)\n            {\n                x[0] = p_start[0] + i0 * dx[0];\n#if (NDIM == 2)\n                for (int j = 0; j <= 2; ++j)\n                {\n                    p_j = j == 0 ? 1.0 : (j == 1 ? x[0] : x[1]);\n                    Psi[i1][i0] += L[j] * p_j;\n                }\n                Psi[i1][i0] *= T[i1][i0];\n#elif (NDIM == 3)\n                for (int j = 0; j <= 3; ++j)\n                {\n                    p_j = j == 0 ? 1.0 : (j == 1 ? x[0] : j == 2 ? x[1] : x[2]);\n                    Psi[i2][i1][i0] += L[j] * p_j;\n                }\n                Psi[i2][i1][i0] *= T[i2][i1][i0];\n#endif\n            }\n        }\n#if (NDIM == 3)\n    }\n#endif\n\n    return;\n\n} // perform_mls\n\nvoid\nget_mls_weights(const std::string& kernel_fcn,\n                const double* const X,\n                const double* const X_shift,\n                const double* const dx,\n                const double* const x_lower,\n                const int* const ilower,\n                const ArrayData<NDIM, double>& mask_data,\n                int* stencil_lower,\n                int* stencil_upper,\n                MLSWeight& Psi)\n{\n    Weight::extent_gen extents;\n\n    if (kernel_fcn == \"IB_4\")\n    {\n        // Resize some arrays.\n        const int stencil_sz = LEInteractor::getStencilSize(\"IB_4\");\n        TensorProductWeights D;\n        for (unsigned int d = 0; d < NDIM; ++d)\n        {\n            D[d].resize(extents[stencil_sz]);\n        }\n\n        // Determine the interpolation stencil corresponding to the position\n        // of X within the cell and compute the regular IB weights.\n        double X_dx, q, r, p_start[NDIM];\n        for (unsigned int d = 0; d < NDIM; ++d)\n        {\n            X_dx = (X[d] + X_shift[d] - x_lower[d]) / dx[d];\n            stencil_lower[d] = NINT(X_dx) + ilower[d] - 2;\n            stencil_upper[d] = stencil_lower[d] + 3;\n            r = X_dx - ((stencil_lower[d] + 1 - ilower[d]) + 0.5);\n            p_start[d] = X[d] - (r + 1) * dx[d];\n            q = std::sqrt(1.0 + 4.0 * r * (1.0 - r));\n            D[d][0] = 0.125 * (3.0 - 2.0 * r - q);\n            D[d][1] = 0.125 * (3.0 - 2.0 * r + q);\n            D[d][2] = 0.125 * (1.0 + 2.0 * r + q);\n            D[d][3] = 0.125 * (1.0 + 2.0 * r - q);\n        }\n        perform_mls(stencil_sz, X, stencil_lower, stencil_upper, p_start, dx, mask_data, D, Psi);\n    }\n    else if (kernel_fcn == \"USER_DEFINED\")\n    {\n        std::array<double, NDIM> X_cell;\n        std::array<int, NDIM> stencil_center;\n\n        // Determine the Cartesian cell in which X is located.\n        for (unsigned int d = 0; d < NDIM; ++d)\n        {\n            stencil_center[d] = static_cast<int>(std::floor((X[d] + X_shift[d] - x_lower[d]) / dx[d])) + ilower[d];\n            X_cell[d] = x_lower[d] + (static_cast<double>(stencil_center[d] - ilower[d]) + 0.5) * dx[d];\n        }\n\n        // Determine the interpolation stencil corresponding to the position of\n        // X within the cell.\n        if (LEInteractor::s_kernel_fcn_stencil_size % 2 == 0)\n        {\n            for (unsigned int d = 0; d < NDIM; ++d)\n            {\n                if (X[d] < X_cell[d])\n                {\n                    stencil_lower[d] = stencil_center[d] - LEInteractor::s_kernel_fcn_stencil_size / 2;\n                    stencil_upper[d] = stencil_center[d] + LEInteractor::s_kernel_fcn_stencil_size / 2 - 1;\n                }\n                else\n                {\n                    stencil_lower[d] = stencil_center[d] - LEInteractor::s_kernel_fcn_stencil_size / 2 + 1;\n                    stencil_upper[d] = stencil_center[d] + LEInteractor::s_kernel_fcn_stencil_size / 2;\n                }\n            }\n        }\n        else\n        {\n            for (unsigned int d = 0; d < NDIM; ++d)\n            {\n                stencil_lower[d] = stencil_center[d] - LEInteractor::s_kernel_fcn_stencil_size / 2;\n                stencil_upper[d] = stencil_center[d] + LEInteractor::s_kernel_fcn_stencil_size / 2;\n            }\n        }\n\n        // Compute the kernel function weights.\n        TensorProductWeights D;\n        for (unsigned int d = 0; d < NDIM; ++d)\n        {\n            D[d].resize(extents[LEInteractor::s_kernel_fcn_stencil_size]);\n        }\n\n        double p_start[NDIM];\n        for (unsigned int d = 0; d < NDIM; ++d)\n        {\n            p_start[d] = X_cell[d] + static_cast<double>(stencil_lower[d] - stencil_center[d]) * dx[d];\n            for (int k = 0, j = stencil_lower[d]; j <= stencil_upper[d]; ++j, ++k)\n            {\n                D[d][k] = LEInteractor::s_kernel_fcn(\n                    (X[d] + X_shift[d] - (X_cell[d] + static_cast<double>(j - stencil_center[d]) * dx[d])) / dx[d]);\n            }\n        }\n        perform_mls(\n            LEInteractor::s_kernel_fcn_stencil_size, X, stencil_lower, stencil_upper, p_start, dx, mask_data, D, Psi);\n    }\n\n    return;\n} // get_mls_weights\n\nvoid\ninterpolate_data(const int stencil_sz,\n                 const int* const ig_lower,\n                 const int* const ig_upper,\n                 const int* const stencil_lower,\n                 const int* const stencil_upper,\n                 const ArrayData<NDIM, double>& q_data,\n                 const int q_comp,\n                 const MLSWeight& Psi,\n                 double& Q)\n{\n    int istart[NDIM], istop[NDIM];\n    for (unsigned int d = 0; d < NDIM; ++d)\n    {\n        istart[d] = std::max(ig_lower[d] - stencil_lower[d], 0);\n        istop[d] = (stencil_sz - 1) - std::max(stencil_upper[d] - ig_upper[d], 0);\n    }\n\n    // Interpolate q onto Q using the modified weights.\n    Q = 0.0;\n#if (NDIM == 3)\n    for (int i2 = istart[2]; i2 <= istop[2]; ++i2)\n    {\n        const int ic2 = stencil_lower[2] + i2;\n#endif\n        for (int i1 = istart[1]; i1 <= istop[1]; ++i1)\n        {\n            const int ic1 = stencil_lower[1] + i1;\n            for (int i0 = istart[0]; i0 <= istop[0]; ++i0)\n            {\n                const int ic0 = stencil_lower[0] + i0;\n#if (NDIM == 2)\n                const hier::Index<NDIM> idx(ic0, ic1);\n                Q += q_data(idx, q_comp) * Psi[i1][i0];\n#elif (NDIM == 3)\n                const hier::Index<NDIM> idx(ic0, ic1, ic2);\n                Q += q_data(idx, q_comp) * Psi[i2][i1][i0];\n#endif\n            }\n        }\n#if (NDIM == 3)\n    }\n#endif\n\n    return;\n\n} // interpolate_data\n\nvoid\nspread_data(const int stencil_sz,\n            const int* const ig_lower,\n            const int* const ig_upper,\n            const int* const stencil_lower,\n            const int* const stencil_upper,\n            const double* const dx,\n            ArrayData<NDIM, double>& q_data,\n            const int q_comp,\n            const MLSWeight& Psi,\n            const double& Q)\n{\n    int istart[NDIM], istop[NDIM];\n    double fac = 1.0;\n    for (unsigned int d = 0; d < NDIM; ++d)\n    {\n        istart[d] = std::max(ig_lower[d] - stencil_lower[d], 0);\n        istop[d] = (stencil_sz - 1) - std::max(stencil_upper[d] - ig_upper[d], 0);\n        fac /= dx[d];\n    }\n\n#if (NDIM == 3)\n    for (int i2 = istart[2]; i2 <= istop[2]; ++i2)\n    {\n        const int ic2 = stencil_lower[2] + i2;\n#endif\n        for (int i1 = istart[1]; i1 <= istop[1]; ++i1)\n        {\n            const int ic1 = stencil_lower[1] + i1;\n            for (int i0 = istart[0]; i0 <= istop[0]; ++i0)\n            {\n                const int ic0 = stencil_lower[0] + i0;\n#if (NDIM == 2)\n                const hier::Index<NDIM> idx(ic0, ic1);\n                q_data(idx, q_comp) += Q * Psi[i1][i0] * fac;\n#elif (NDIM == 3)\n                const hier::Index<NDIM> idx(ic0, ic1, ic2);\n                q_data(idx, q_comp) += Q * Psi[i2][i1][i0] * fac;\n#endif\n            }\n        }\n#if (NDIM == 3)\n    }\n#endif\n} // spread_data\n} // namespace\n\ndouble (*LEInteractor::s_kernel_fcn)(double r) = &ib4_kernel_fcn;\nint LEInteractor::s_kernel_fcn_stencil_size = 4;\n\nvoid LEInteractor::setFromDatabase(Pointer<Database> /*db*/)\n{\n    // intentionally blank\n    return;\n}\n\nvoid\nLEInteractor::printClassData(std::ostream& os)\n{\n    os << \"LEInteractor::printClassData():\\n\";\n    return;\n}\n\n/////////////////////////////// PUBLIC ///////////////////////////////////////\n\nint\nLEInteractor::getStencilSize(const std::string& kernel_fcn)\n{\n    if (kernel_fcn == \"PIECEWISE_CONSTANT\") return 1;\n    if (kernel_fcn == \"DISCONTINUOUS_LINEAR\") return 2;\n    if (kernel_fcn == \"PIECEWISE_LINEAR\") return 2;\n    if (kernel_fcn == \"PIECEWISE_CUBIC\") return 4;\n    if (kernel_fcn == \"IB_3\") return 4;\n    if (kernel_fcn == \"IB_4\") return 4;\n    if (kernel_fcn == \"IB_4_W8\") return 8;\n    if (kernel_fcn == \"IB_5\") return 6;\n    if (kernel_fcn == \"IB_6\") return 6;\n    if (kernel_fcn == \"BSPLINE_3\") return 4;\n    if (kernel_fcn == \"BSPLINE_4\") return 4;\n    if (kernel_fcn == \"BSPLINE_5\") return 6;\n    if (kernel_fcn == \"BSPLINE_6\") return 6;\n    if (kernel_fcn == \"USER_DEFINED\") return s_kernel_fcn_stencil_size;\n    TBOX_ERROR(\"LEInteractor::getStencilSize()\\n\"\n               << \"  Unknown kernel function \" << kernel_fcn << std::endl);\n    return -1;\n}\n\nint\nLEInteractor::getMinimumGhostWidth(const std::string& kernel_fcn)\n{\n    return static_cast<int>(floor(0.5 * getStencilSize(kernel_fcn))) + 1;\n}\n\ntemplate <class T>\nvoid\nLEInteractor::interpolate(Pointer<LData> Q_data,\n                          const Pointer<LData> X_data,\n                          const Pointer<LIndexSetData<T> > idx_data,\n                          const Pointer<CellData<NDIM, double> > q_data,\n                          const Pointer<Patch<NDIM> > patch,\n                          const Box<NDIM>& interp_box,\n                          const IntVector<NDIM>& periodic_shift,\n                          const std::string& interp_fcn)\n{\n#if !defined(NDEBUG)\n    TBOX_ASSERT(Q_data);\n    TBOX_ASSERT(q_data);\n    TBOX_ASSERT(X_data);\n    TBOX_ASSERT(idx_data);\n    TBOX_ASSERT(patch);\n    TBOX_ASSERT(Q_data->getDepth() == static_cast<unsigned int>(q_data->getDepth()));\n    TBOX_ASSERT(X_data->getDepth() == NDIM);\n#endif\n    interpolate(Q_data->getGhostedLocalFormVecArray()->data(),\n                Q_data->getDepth(),\n                X_data->getGhostedLocalFormVecArray()->data(),\n                X_data->getDepth(),\n                idx_data,\n                q_data,\n                patch,\n                interp_box,\n                periodic_shift,\n                interp_fcn);\n    Q_data->restoreArrays();\n    X_data->restoreArrays();\n    return;\n}\n\ntemplate <class T>\nvoid\nLEInteractor::interpolate(Pointer<LData> Q_data,\n                          const Pointer<LData> X_data,\n                          const Pointer<LIndexSetData<T> > idx_data,\n                          const Pointer<NodeData<NDIM, double> > q_data,\n                          const Pointer<Patch<NDIM> > patch,\n                          const Box<NDIM>& interp_box,\n                          const IntVector<NDIM>& periodic_shift,\n                          const std::string& interp_fcn)\n{\n#if !defined(NDEBUG)\n    TBOX_ASSERT(Q_data);\n    TBOX_ASSERT(q_data);\n    TBOX_ASSERT(X_data);\n    TBOX_ASSERT(idx_data);\n    TBOX_ASSERT(patch);\n    TBOX_ASSERT(Q_data->getDepth() == static_cast<unsigned int>(q_data->getDepth()));\n    TBOX_ASSERT(X_data->getDepth() == NDIM);\n#endif\n    interpolate(Q_data->getGhostedLocalFormVecArray()->data(),\n                Q_data->getDepth(),\n                X_data->getGhostedLocalFormVecArray()->data(),\n                X_data->getDepth(),\n                idx_data,\n                q_data,\n                patch,\n                interp_box,\n                periodic_shift,\n                interp_fcn);\n    Q_data->restoreArrays();\n    X_data->restoreArrays();\n    return;\n}\n\ntemplate <class T>\nvoid\nLEInteractor::interpolate(Pointer<LData> Q_data,\n                          const Pointer<LData> X_data,\n                          const Pointer<LIndexSetData<T> > idx_data,\n                          const Pointer<SideData<NDIM, double> > q_data,\n                          const Pointer<Patch<NDIM> > patch,\n                          const Box<NDIM>& interp_box,\n                          const IntVector<NDIM>& periodic_shift,\n                          const std::string& interp_fcn)\n{\n    if (Q_data->getDepth() != NDIM || q_data->getDepth() != 1)\n    {\n        TBOX_ERROR(\"LEInteractor::interpolate():\\n\"\n                   << \"  side-centered interpolation requires vector-valued data.\\n\");\n    }\n#if !defined(NDEBUG)\n    TBOX_ASSERT(Q_data);\n    TBOX_ASSERT(q_data);\n    TBOX_ASSERT(X_data);\n    TBOX_ASSERT(idx_data);\n    TBOX_ASSERT(patch);\n    TBOX_ASSERT(Q_data->getDepth() == NDIM);\n    TBOX_ASSERT(X_data->getDepth() == NDIM);\n    TBOX_ASSERT(q_data->getDepth() == 1);\n#endif\n    interpolate(Q_data->getGhostedLocalFormVecArray()->data(),\n                Q_data->getDepth(),\n                X_data->getGhostedLocalFormVecArray()->data(),\n                X_data->getDepth(),\n                idx_data,\n                q_data,\n                patch,\n                interp_box,\n                periodic_shift,\n                interp_fcn);\n    Q_data->restoreArrays();\n    X_data->restoreArrays();\n    return;\n}\n\ntemplate <class T>\nvoid\nLEInteractor::interpolate(Pointer<LData> Q_data,\n                          const Pointer<LData> X_data,\n                          const Pointer<LIndexSetData<T> > idx_data,\n                          const Pointer<EdgeData<NDIM, double> > q_data,\n                          const Pointer<Patch<NDIM> > patch,\n                          const Box<NDIM>& interp_box,\n                          const IntVector<NDIM>& periodic_shift,\n                          const std::string& interp_fcn)\n{\n    if (NDIM != 3 || Q_data->getDepth() != NDIM || q_data->getDepth() != 1)\n    {\n        TBOX_ERROR(\"LEInteractor::interpolate():\\n\"\n                   << \"  edge-centered interpolation requires 3D vector-valued data.\\n\");\n    }\n#if !defined(NDEBUG)\n    TBOX_ASSERT(Q_data);\n    TBOX_ASSERT(q_data);\n    TBOX_ASSERT(X_data);\n    TBOX_ASSERT(idx_data);\n    TBOX_ASSERT(patch);\n    TBOX_ASSERT(Q_data->getDepth() == NDIM);\n    TBOX_ASSERT(X_data->getDepth() == NDIM);\n    TBOX_ASSERT(q_data->getDepth() == 1);\n#endif\n    interpolate(Q_data->getGhostedLocalFormVecArray()->data(),\n                Q_data->getDepth(),\n                X_data->getGhostedLocalFormVecArray()->data(),\n                X_data->getDepth(),\n                idx_data,\n                q_data,\n                patch,\n                interp_box,\n                periodic_shift,\n                interp_fcn);\n    Q_data->restoreArrays();\n    X_data->restoreArrays();\n    return;\n}\n\ntemplate <class T>\nvoid\nLEInteractor::interpolate(double* const Q_data,\n                          const int Q_depth,\n                          const double* const X_data,\n                          const int X_depth,\n                          const Pointer<LIndexSetData<T> > idx_data,\n                          const Pointer<CellData<NDIM, double> > q_data,\n                          const Pointer<Patch<NDIM> > patch,\n                          const Box<NDIM>& interp_box,\n                          const IntVector<NDIM>& periodic_shift,\n                          const std::string& interp_fcn)\n{\n#if !defined(NDEBUG)\n    TBOX_ASSERT(q_data);\n    TBOX_ASSERT(idx_data);\n    TBOX_ASSERT(patch);\n    TBOX_ASSERT(Q_depth == q_data->getDepth());\n    TBOX_ASSERT(X_depth == NDIM);\n#else\n    NULL_USE(X_depth);\n#endif\n    // Determine the patch geometry.\n    const Pointer<CartesianPatchGeometry<NDIM> > pgeom = patch->getPatchGeometry();\n    const double* const x_lower = pgeom->getXLower();\n    const double* const x_upper = pgeom->getXUpper();\n    const double* const dx = pgeom->getDx();\n    std::array<int, NDIM> patch_touches_lower_physical_bdry(array_zero<int, NDIM>());\n    std::array<int, NDIM> patch_touches_upper_physical_bdry(array_zero<int, NDIM>());\n    for (unsigned int axis = 0; axis < NDIM; ++axis)\n    {\n        static const int lower = 0;\n        patch_touches_lower_physical_bdry[axis] = pgeom->getTouchesRegularBoundary(axis, lower);\n        static const int upper = 1;\n        patch_touches_upper_physical_bdry[axis] = pgeom->getTouchesRegularBoundary(axis, upper);\n    }\n\n    // Generate a list of local indices which lie in the specified box.\n    std::vector<int> local_indices;\n    std::vector<double> periodic_shifts;\n    buildLocalIndices(local_indices, periodic_shifts, interp_box, patch, periodic_shift, idx_data);\n\n    // Interpolate.\n    if (!local_indices.empty())\n    {\n        interpolate(Q_data,\n                    Q_depth,\n                    X_data,\n                    q_data->getPointer(),\n                    q_data->getBox(),\n                    q_data->getGhostCellWidth(),\n                    q_data->getDepth(),\n                    x_lower,\n                    x_upper,\n                    dx,\n                    patch_touches_lower_physical_bdry,\n                    patch_touches_upper_physical_bdry,\n                    local_indices,\n                    periodic_shifts,\n                    interp_fcn);\n    }\n    return;\n}\n\ntemplate <class T>\nvoid\nLEInteractor::interpolate(double* const Q_data,\n                          const int Q_depth,\n                          const double* const X_data,\n                          const int X_depth,\n                          const Pointer<LIndexSetData<T> > idx_data,\n                          const Pointer<NodeData<NDIM, double> > q_data,\n                          const Pointer<Patch<NDIM> > patch,\n                          const Box<NDIM>& interp_box,\n                          const IntVector<NDIM>& periodic_shift,\n                          const std::string& interp_fcn)\n{\n#if !defined(NDEBUG)\n    TBOX_ASSERT(q_data);\n    TBOX_ASSERT(idx_data);\n    TBOX_ASSERT(patch);\n    TBOX_ASSERT(Q_depth == q_data->getDepth());\n    TBOX_ASSERT(X_depth == NDIM);\n#else\n    NULL_USE(X_depth);\n#endif\n    // Determine the patch geometry.\n    const Pointer<CartesianPatchGeometry<NDIM> > pgeom = patch->getPatchGeometry();\n    const double* const x_lower = pgeom->getXLower();\n    const double* const x_upper = pgeom->getXUpper();\n    const double* const dx = pgeom->getDx();\n    std::array<int, NDIM> patch_touches_lower_physical_bdry(array_zero<int, NDIM>());\n    std::array<int, NDIM> patch_touches_upper_physical_bdry(array_zero<int, NDIM>());\n    for (unsigned int axis = 0; axis < NDIM; ++axis)\n    {\n        static const int lower = 0;\n        patch_touches_lower_physical_bdry[axis] = pgeom->getTouchesRegularBoundary(axis, lower);\n        static const int upper = 1;\n        patch_touches_upper_physical_bdry[axis] = pgeom->getTouchesRegularBoundary(axis, upper);\n    }\n\n    // Generate a list of local indices which lie in the specified box.\n    std::vector<int> local_indices;\n    std::vector<double> periodic_shifts;\n    buildLocalIndices(local_indices, periodic_shifts, interp_box, patch, periodic_shift, idx_data);\n\n    // Interpolate.\n    if (!local_indices.empty())\n    {\n        std::array<double, NDIM> x_lower_node, x_upper_node;\n        for (unsigned int d = 0; d < NDIM; ++d)\n        {\n            x_lower_node[d] = x_lower[d] - 0.5 * dx[d];\n            x_upper_node[d] = x_upper[d] + 0.5 * dx[d];\n        }\n        interpolate(Q_data,\n                    Q_depth,\n                    X_data,\n                    q_data->getPointer(),\n                    NodeGeometry<NDIM>::toNodeBox(q_data->getBox()),\n                    q_data->getGhostCellWidth(),\n                    q_data->getDepth(),\n                    x_lower_node.data(),\n                    x_upper_node.data(),\n                    dx,\n                    patch_touches_lower_physical_bdry,\n                    patch_touches_upper_physical_bdry,\n                    local_indices,\n                    periodic_shifts,\n                    interp_fcn);\n    }\n    return;\n}\n\ntemplate <class T>\nvoid\nLEInteractor::interpolate(double* const Q_data,\n                          const int Q_depth,\n                          const double* const X_data,\n                          const int X_depth,\n                          const Pointer<LIndexSetData<T> > idx_data,\n                          const Pointer<SideData<NDIM, double> > q_data,\n                          const Pointer<Patch<NDIM> > patch,\n                          const Box<NDIM>& interp_box,\n                          const IntVector<NDIM>& periodic_shift,\n                          const std::string& interp_fcn)\n{\n#if !defined(NDEBUG)\n    TBOX_ASSERT(q_data);\n    TBOX_ASSERT(idx_data);\n    TBOX_ASSERT(patch);\n    TBOX_ASSERT(Q_depth == NDIM);\n    TBOX_ASSERT(X_depth == NDIM);\n    TBOX_ASSERT(q_data->getDepth() == 1);\n#else\n    NULL_USE(X_depth);\n#endif\n    if (Q_depth != NDIM || q_data->getDepth() != 1)\n    {\n        TBOX_ERROR(\"LEInteractor::interpolate():\\n\"\n                   << \"  side-centered interpolation requires vector-valued data.\\n\");\n    }\n\n    // Determine the patch geometry.\n    const Pointer<CartesianPatchGeometry<NDIM> > pgeom = patch->getPatchGeometry();\n    const double* const x_lower = pgeom->getXLower();\n    const double* const x_upper = pgeom->getXUpper();\n    const double* const dx = pgeom->getDx();\n    std::array<int, NDIM> patch_touches_lower_physical_bdry(array_zero<int, NDIM>());\n    std::array<int, NDIM> patch_touches_upper_physical_bdry(array_zero<int, NDIM>());\n    for (unsigned int axis = 0; axis < NDIM; ++axis)\n    {\n        static const int lower = 0;\n        patch_touches_lower_physical_bdry[axis] = pgeom->getTouchesRegularBoundary(axis, lower);\n        static const int upper = 1;\n        patch_touches_upper_physical_bdry[axis] = pgeom->getTouchesRegularBoundary(axis, upper);\n    }\n\n    // Generate a list of local indices which lie in the specified box.\n    std::vector<int> local_indices;\n    std::vector<double> periodic_shifts;\n    buildLocalIndices(local_indices, periodic_shifts, interp_box, patch, periodic_shift, idx_data);\n\n    // Interpolate.\n    if (!local_indices.empty())\n    {\n        std::array<double, NDIM> x_lower_axis, x_upper_axis;\n        const int local_sz = (*std::max_element(local_indices.begin(), local_indices.end())) + 1;\n        std::vector<double> Q_data_axis(local_sz);\n        for (unsigned int axis = 0; axis < NDIM; ++axis)\n        {\n            for (unsigned int d = 0; d < NDIM; ++d)\n            {\n                x_lower_axis[d] = x_lower[d];\n                x_upper_axis[d] = x_upper[d];\n            }\n            x_lower_axis[axis] -= 0.5 * dx[axis];\n            x_upper_axis[axis] += 0.5 * dx[axis];\n            interpolate(&Q_data_axis[0],\n                        /*Q_depth*/ 1,\n                        X_data,\n                        q_data->getPointer(axis),\n                        SideGeometry<NDIM>::toSideBox(q_data->getBox(), axis),\n                        q_data->getGhostCellWidth(),\n                        /*q_depth*/ 1,\n                        x_lower_axis.data(),\n                        x_upper_axis.data(),\n                        dx,\n                        patch_touches_lower_physical_bdry,\n                        patch_touches_upper_physical_bdry,\n                        local_indices,\n                        periodic_shifts,\n                        interp_fcn,\n                        axis);\n            for (const auto& local_index : local_indices)\n            {\n                Q_data[NDIM * local_index + axis] = Q_data_axis[local_index];\n            }\n        }\n    }\n    return;\n}\n\ntemplate <class T>\nvoid\nLEInteractor::interpolate(double* const Q_data,\n                          const int Q_depth,\n                          const double* const X_data,\n                          const int X_depth,\n                          const Pointer<LIndexSetData<T> > idx_data,\n                          const Pointer<EdgeData<NDIM, double> > q_data,\n                          const Pointer<Patch<NDIM> > patch,\n                          const Box<NDIM>& interp_box,\n                          const IntVector<NDIM>& periodic_shift,\n                          const std::string& interp_fcn)\n{\n#if !defined(NDEBUG)\n    TBOX_ASSERT(q_data);\n    TBOX_ASSERT(idx_data);\n    TBOX_ASSERT(patch);\n    TBOX_ASSERT(Q_depth == NDIM);\n    TBOX_ASSERT(X_depth == NDIM);\n    TBOX_ASSERT(q_data->getDepth() == 1);\n#else\n    NULL_USE(X_depth);\n#endif\n    if (NDIM != 3 || Q_depth != NDIM || q_data->getDepth() != 1)\n    {\n        TBOX_ERROR(\"LEInteractor::interpolate():\\n\"\n                   << \"  edge-centered interpolation requires 3D vector-valued data.\\n\");\n    }\n\n    // Determine the patch geometry.\n    const Pointer<CartesianPatchGeometry<NDIM> > pgeom = patch->getPatchGeometry();\n    const double* const x_lower = pgeom->getXLower();\n    const double* const x_upper = pgeom->getXUpper();\n    const double* const dx = pgeom->getDx();\n    std::array<int, NDIM> patch_touches_lower_physical_bdry(array_zero<int, NDIM>());\n    std::array<int, NDIM> patch_touches_upper_physical_bdry(array_zero<int, NDIM>());\n    for (unsigned int axis = 0; axis < NDIM; ++axis)\n    {\n        static const int lower = 0;\n        patch_touches_lower_physical_bdry[axis] = pgeom->getTouchesRegularBoundary(axis, lower);\n        static const int upper = 1;\n        patch_touches_upper_physical_bdry[axis] = pgeom->getTouchesRegularBoundary(axis, upper);\n    }\n\n    // Generate a list of local indices which lie in the specified box.\n    std::vector<int> local_indices;\n    std::vector<double> periodic_shifts;\n    buildLocalIndices(local_indices, periodic_shifts, interp_box, patch, periodic_shift, idx_data);\n\n    // Interpolate.\n    if (!local_indices.empty())\n    {\n        std::array<double, NDIM> x_lower_axis, x_upper_axis;\n        const int local_sz = (*std::max_element(local_indices.begin(), local_indices.end())) + 1;\n        std::vector<double> Q_data_axis(local_sz);\n        for (unsigned int axis = 0; axis < NDIM; ++axis)\n        {\n            for (unsigned int d = 0; d < NDIM; ++d)\n            {\n                x_lower_axis[d] = x_lower[d];\n                x_upper_axis[d] = x_upper[d];\n                if (d != axis)\n                {\n                    x_lower_axis[d] -= 0.5 * dx[d];\n                    x_upper_axis[d] += 0.5 * dx[d];\n                }\n            }\n            interpolate(&Q_data_axis[0],\n                        /*Q_depth*/ 1,\n                        X_data,\n                        q_data->getPointer(axis),\n                        EdgeGeometry<NDIM>::toEdgeBox(q_data->getBox(), axis),\n                        q_data->getGhostCellWidth(),\n                        /*q_depth*/ 1,\n                        x_lower_axis.data(),\n                        x_upper_axis.data(),\n                        dx,\n                        patch_touches_lower_physical_bdry,\n                        patch_touches_upper_physical_bdry,\n                        local_indices,\n                        periodic_shifts,\n                        interp_fcn,\n                        axis);\n            for (const auto& local_index : local_indices)\n            {\n                Q_data[NDIM * local_index + axis] = Q_data_axis[local_index];\n            }\n        }\n    }\n    return;\n}\n\nvoid\nLEInteractor::interpolate(std::vector<double>& Q_data,\n                          const int Q_depth,\n                          const std::vector<double>& X_data,\n                          const int X_depth,\n                          const Pointer<CellData<NDIM, double> > q_data,\n                          const Pointer<Patch<NDIM> > patch,\n                          const Box<NDIM>& interp_box,\n                          const std::string& interp_fcn)\n{\n    if (Q_data.empty()) return;\n    interpolate(&Q_data[0],\n                static_cast<int>(Q_data.size()),\n                Q_depth,\n                &X_data[0],\n                static_cast<int>(X_data.size()),\n                X_depth,\n                q_data,\n                patch,\n                interp_box,\n                interp_fcn);\n}\n\nvoid\nLEInteractor::interpolate(std::vector<double>& Q_data,\n                          const int Q_depth,\n                          const std::vector<double>& X_data,\n                          const int X_depth,\n                          const Pointer<CellData<NDIM, double> > mask_data,\n                          const Pointer<CellData<NDIM, double> > q_data,\n                          const Pointer<Patch<NDIM> > patch,\n                          const Box<NDIM>& interp_box,\n                          const std::string& interp_fcn)\n{\n    if (Q_data.empty()) return;\n    interpolate(&Q_data[0],\n                static_cast<int>(Q_data.size()),\n                Q_depth,\n                &X_data[0],\n                static_cast<int>(X_data.size()),\n                X_depth,\n                mask_data,\n                q_data,\n                patch,\n                interp_box,\n                interp_fcn);\n}\n\nvoid\nLEInteractor::interpolate(std::vector<double>& Q_data,\n                          const int Q_depth,\n                          const std::vector<double>& X_data,\n                          const int X_depth,\n                          const Pointer<NodeData<NDIM, double> > q_data,\n                          const Pointer<Patch<NDIM> > patch,\n                          const Box<NDIM>& interp_box,\n                          const std::string& interp_fcn)\n{\n    if (Q_data.empty()) return;\n    interpolate(&Q_data[0],\n                static_cast<int>(Q_data.size()),\n                Q_depth,\n                &X_data[0],\n                static_cast<int>(X_data.size()),\n                X_depth,\n                q_data,\n                patch,\n                interp_box,\n                interp_fcn);\n}\n\nvoid\nLEInteractor::interpolate(std::vector<double>& Q_data,\n                          const int Q_depth,\n                          const std::vector<double>& X_data,\n                          const int X_depth,\n                          const Pointer<SideData<NDIM, double> > q_data,\n                          const Pointer<Patch<NDIM> > patch,\n                          const Box<NDIM>& interp_box,\n                          const std::string& interp_fcn)\n{\n    if (Q_data.empty()) return;\n    interpolate(&Q_data[0],\n                static_cast<int>(Q_data.size()),\n                Q_depth,\n                &X_data[0],\n                static_cast<int>(X_data.size()),\n                X_depth,\n                q_data,\n                patch,\n                interp_box,\n                interp_fcn);\n}\n\nvoid\nLEInteractor::interpolate(std::vector<double>& Q_data,\n                          const int Q_depth,\n                          const std::vector<double>& X_data,\n                          const int X_depth,\n                          const Pointer<SideData<NDIM, double> > mask_data,\n                          const Pointer<SideData<NDIM, double> > q_data,\n                          const Pointer<Patch<NDIM> > patch,\n                          const Box<NDIM>& interp_box,\n                          const std::string& interp_fcn)\n{\n    if (Q_data.empty()) return;\n    interpolate(&Q_data[0],\n                static_cast<int>(Q_data.size()),\n                Q_depth,\n                &X_data[0],\n                static_cast<int>(X_data.size()),\n                X_depth,\n                mask_data,\n                q_data,\n                patch,\n                interp_box,\n                interp_fcn);\n}\n\nvoid\nLEInteractor::interpolate(std::vector<double>& Q_data,\n                          const int Q_depth,\n                          const std::vector<double>& X_data,\n                          const int X_depth,\n                          const Pointer<EdgeData<NDIM, double> > q_data,\n                          const Pointer<Patch<NDIM> > patch,\n                          const Box<NDIM>& interp_box,\n                          const std::string& interp_fcn)\n{\n    if (Q_data.empty()) return;\n    interpolate(&Q_data[0],\n                static_cast<int>(Q_data.size()),\n                Q_depth,\n                &X_data[0],\n                static_cast<int>(X_data.size()),\n                X_depth,\n                q_data,\n                patch,\n                interp_box,\n                interp_fcn);\n}\n\nvoid\nLEInteractor::interpolate(double* const Q_data,\n                          const int Q_size,\n                          const int Q_depth,\n                          const double* const X_data,\n                          const int X_size,\n                          const int X_depth,\n                          const Pointer<CellData<NDIM, double> > q_data,\n                          const Pointer<Patch<NDIM> > patch,\n                          const Box<NDIM>& interp_box,\n                          const std::string& interp_fcn)\n{\n#if !defined(NDEBUG)\n    TBOX_ASSERT(q_data);\n    TBOX_ASSERT(patch);\n    TBOX_ASSERT(Q_depth == q_data->getDepth());\n    TBOX_ASSERT(X_depth == NDIM);\n    TBOX_ASSERT(Q_size / Q_depth == X_size / X_depth);\n#else\n    NULL_USE(Q_size);\n#endif\n    // Determine the patch geometry.\n    const Pointer<CartesianPatchGeometry<NDIM> > pgeom = patch->getPatchGeometry();\n    const double* const x_lower = pgeom->getXLower();\n    const double* const x_upper = pgeom->getXUpper();\n    const double* const dx = pgeom->getDx();\n    std::array<int, NDIM> patch_touches_lower_physical_bdry(array_zero<int, NDIM>());\n    std::array<int, NDIM> patch_touches_upper_physical_bdry(array_zero<int, NDIM>());\n    for (unsigned int axis = 0; axis < NDIM; ++axis)\n    {\n        static const int lower = 0;\n        patch_touches_lower_physical_bdry[axis] = pgeom->getTouchesRegularBoundary(axis, lower);\n        static const int upper = 1;\n        patch_touches_upper_physical_bdry[axis] = pgeom->getTouchesRegularBoundary(axis, upper);\n    }\n\n    // Generate a list of local indices which lie in the specified box and set\n    // all periodic offsets to zero.\n    std::vector<int> local_indices;\n    buildLocalIndices(local_indices, interp_box, patch, X_data, X_size, X_depth);\n    std::vector<double> periodic_shifts(NDIM * local_indices.size());\n\n    // Interpolate.\n    if (!local_indices.empty())\n    {\n        interpolate(Q_data,\n                    Q_depth,\n                    X_data,\n                    q_data->getPointer(),\n                    q_data->getBox(),\n                    q_data->getGhostCellWidth(),\n                    q_data->getDepth(),\n                    x_lower,\n                    x_upper,\n                    dx,\n                    patch_touches_lower_physical_bdry,\n                    patch_touches_upper_physical_bdry,\n                    local_indices,\n                    periodic_shifts,\n                    interp_fcn);\n    }\n    return;\n}\n\nvoid\nLEInteractor::interpolate(double* const Q_data,\n                          const int Q_size,\n                          const int Q_depth,\n                          const double* const X_data,\n                          const int X_size,\n                          const int X_depth,\n                          const Pointer<CellData<NDIM, double> > mask_data,\n                          const Pointer<CellData<NDIM, double> > q_data,\n                          const Pointer<Patch<NDIM> > patch,\n                          const Box<NDIM>& interp_box,\n                          const std::string& interp_fcn)\n{\n#if !defined(NDEBUG)\n    TBOX_ASSERT(q_data);\n    TBOX_ASSERT(patch);\n    TBOX_ASSERT(Q_depth == q_data->getDepth());\n    TBOX_ASSERT(X_depth == NDIM);\n    TBOX_ASSERT(Q_size / Q_depth == X_size / X_depth);\n    TBOX_ASSERT(mask_data);\n    TBOX_ASSERT(mask_data->getDepth() == 1);\n#else\n    NULL_USE(Q_size);\n#endif\n    // Determine the patch geometry.\n    const Pointer<CartesianPatchGeometry<NDIM> > pgeom = patch->getPatchGeometry();\n    const double* const x_lower = pgeom->getXLower();\n    const double* const dx = pgeom->getDx();\n    const Box<NDIM>& patch_box = patch->getBox();\n    const IntVector<NDIM>& ilower = patch_box.lower();\n    const IntVector<NDIM>& iupper = patch_box.upper();\n\n    // Get ghost cell width info.\n    const IntVector<NDIM>& q_gcw = q_data->getGhostCellWidth();\n    const IntVector<NDIM>& mask_gcw = q_data->getGhostCellWidth();\n    const int stencil_size = getStencilSize(interp_fcn);\n    const int min_ghosts = getMinimumGhostWidth(interp_fcn);\n    const int q_gcw_min = q_gcw.min();\n    const int mask_gcw_min = mask_gcw.min();\n    if (q_gcw_min < min_ghosts)\n    {\n        TBOX_ERROR(\"LEInteractor::interpolate(): insufficient ghost cells for Eulerian field data:\\n\"\n                   << \"  kernel function          = \" << interp_fcn << \"\\n\"\n                   << \"  kernel stencil size      = \" << stencil_size << \"\\n\"\n                   << \"  minimum ghost cell width = \" << min_ghosts << \"\\n\"\n                   << \"  ghost cell width         = \" << q_gcw_min << \"\\n\");\n    }\n    if (mask_gcw_min < stencil_size)\n    {\n        TBOX_ERROR(\"LEInteractor::interpolate(): insufficient ghost cells for Eulerian mask data:\\n\"\n                   << \"  kernel function          = \" << interp_fcn << \"\\n\"\n                   << \"  kernel stencil size      = \" << stencil_size << \"\\n\"\n                   << \"  minimum ghost cell width = \" << stencil_size << \"\\n\"\n                   << \"  ghost cell width         = \" << mask_gcw_min << \"\\n\");\n    }\n    const IntVector<NDIM> ig_lower = ilower - q_gcw;\n    const IntVector<NDIM> ig_upper = iupper + q_gcw;\n\n    // Get boundary info.\n    std::array<int, NDIM> patch_touches_lower_physical_bdry(array_zero<int, NDIM>());\n    std::array<int, NDIM> patch_touches_upper_physical_bdry(array_zero<int, NDIM>());\n    for (unsigned int axis = 0; axis < NDIM; ++axis)\n    {\n        static const int lower = 0;\n        patch_touches_lower_physical_bdry[axis] = pgeom->getTouchesRegularBoundary(axis, lower);\n        static const int upper = 1;\n        patch_touches_upper_physical_bdry[axis] = pgeom->getTouchesRegularBoundary(axis, upper);\n    }\n\n    // Generate a list of local indices which lie in the specified box and set\n    // all periodic offsets to zero.\n    std::vector<int> local_indices;\n    buildLocalIndices(local_indices, interp_box, patch, X_data, X_size, X_depth);\n    std::vector<double> periodic_shifts(NDIM * local_indices.size());\n\n    // Interpolate.\n    const int nindices = static_cast<int>(local_indices.size());\n    if (nindices)\n    {\n        IntVector<NDIM> stencil_lower, stencil_upper;\n        for (int k = 0; k < nindices; ++k)\n        {\n            int s = local_indices[k];\n            MLSWeight Psi;\n            const int stencil_sz = LEInteractor::getStencilSize(interp_fcn);\n            get_mls_weights(interp_fcn,\n                            &X_data[s * NDIM],\n                            &periodic_shifts[k * NDIM],\n                            dx,\n                            x_lower,\n                            ilower,\n                            mask_data->getArrayData(),\n                            stencil_lower,\n                            stencil_upper,\n                            Psi);\n\n            for (int comp = 0; comp < Q_depth; ++comp)\n            {\n                interpolate_data(stencil_sz,\n                                 ig_lower,\n                                 ig_upper,\n                                 stencil_lower,\n                                 stencil_upper,\n                                 q_data->getArrayData(),\n                                 comp,\n                                 Psi,\n                                 Q_data[s * Q_depth + comp]);\n            }\n        }\n    }\n\n    return;\n}\n\nvoid\nLEInteractor::interpolate(double* const Q_data,\n                          const int Q_size,\n                          const int Q_depth,\n                          const double* const X_data,\n                          const int X_size,\n                          const int X_depth,\n                          const Pointer<NodeData<NDIM, double> > q_data,\n                          const Pointer<Patch<NDIM> > patch,\n                          const Box<NDIM>& interp_box,\n                          const std::string& interp_fcn)\n{\n#if !defined(NDEBUG)\n    TBOX_ASSERT(q_data);\n    TBOX_ASSERT(patch);\n    TBOX_ASSERT(Q_depth == q_data->getDepth());\n    TBOX_ASSERT(X_depth == NDIM);\n    TBOX_ASSERT(Q_size / Q_depth == X_size / X_depth);\n#else\n    NULL_USE(Q_size);\n#endif\n    // Determine the patch geometry.\n    const Pointer<CartesianPatchGeometry<NDIM> > pgeom = patch->getPatchGeometry();\n    const double* const x_lower = pgeom->getXLower();\n    const double* const x_upper = pgeom->getXUpper();\n    const double* const dx = pgeom->getDx();\n    std::array<int, NDIM> patch_touches_lower_physical_bdry(array_zero<int, NDIM>());\n    std::array<int, NDIM> patch_touches_upper_physical_bdry(array_zero<int, NDIM>());\n    for (unsigned int axis = 0; axis < NDIM; ++axis)\n    {\n        static const int lower = 0;\n        patch_touches_lower_physical_bdry[axis] = pgeom->getTouchesRegularBoundary(axis, lower);\n        static const int upper = 1;\n        patch_touches_upper_physical_bdry[axis] = pgeom->getTouchesRegularBoundary(axis, upper);\n    }\n\n    // Generate a list of local indices which lie in the specified box and set\n    // all periodic offsets to zero.\n    std::vector<int> local_indices;\n    buildLocalIndices(local_indices, interp_box, patch, X_data, X_size, X_depth);\n    std::vector<double> periodic_shifts(NDIM * local_indices.size());\n\n    // Interpolate.\n    if (!local_indices.empty())\n    {\n        std::array<double, NDIM> x_lower_node, x_upper_node;\n        for (unsigned int d = 0; d < NDIM; ++d)\n        {\n            x_lower_node[d] = x_lower[d] - 0.5 * dx[d];\n            x_upper_node[d] = x_upper[d] + 0.5 * dx[d];\n        }\n        interpolate(Q_data,\n                    Q_depth,\n                    X_data,\n                    q_data->getPointer(),\n                    NodeGeometry<NDIM>::toNodeBox(q_data->getBox()),\n                    q_data->getGhostCellWidth(),\n                    q_data->getDepth(),\n                    x_lower_node.data(),\n                    x_upper_node.data(),\n                    dx,\n                    patch_touches_lower_physical_bdry,\n                    patch_touches_upper_physical_bdry,\n                    local_indices,\n                    periodic_shifts,\n                    interp_fcn);\n    }\n    return;\n}\n\nvoid\nLEInteractor::interpolate(double* const Q_data,\n                          const int Q_size,\n                          const int Q_depth,\n                          const double* const X_data,\n                          const int X_size,\n                          const int X_depth,\n                          const Pointer<SideData<NDIM, double> > q_data,\n                          const Pointer<Patch<NDIM> > patch,\n                          const Box<NDIM>& interp_box,\n                          const std::string& interp_fcn)\n{\n#if !defined(NDEBUG)\n    TBOX_ASSERT(q_data);\n    TBOX_ASSERT(patch);\n    TBOX_ASSERT(Q_depth == NDIM);\n    TBOX_ASSERT(X_depth == NDIM);\n    TBOX_ASSERT(Q_size / Q_depth == X_size / X_depth);\n    TBOX_ASSERT(q_data->getDepth() == 1);\n#else\n    NULL_USE(Q_size);\n#endif\n    if (Q_depth != NDIM || q_data->getDepth() != 1)\n    {\n        TBOX_ERROR(\"LEInteractor::interpolate():\\n\"\n                   << \"  side-centered interpolation requires vector-valued data.\\n\");\n    }\n\n    // Determine the patch geometry.\n    const Pointer<CartesianPatchGeometry<NDIM> > pgeom = patch->getPatchGeometry();\n    const double* const x_lower = pgeom->getXLower();\n    const double* const x_upper = pgeom->getXUpper();\n    const double* const dx = pgeom->getDx();\n    std::array<int, NDIM> patch_touches_lower_physical_bdry(array_zero<int, NDIM>());\n    std::array<int, NDIM> patch_touches_upper_physical_bdry(array_zero<int, NDIM>());\n    for (unsigned int axis = 0; axis < NDIM; ++axis)\n    {\n        static const int lower = 0;\n        patch_touches_lower_physical_bdry[axis] = pgeom->getTouchesRegularBoundary(axis, lower);\n        static const int upper = 1;\n        patch_touches_upper_physical_bdry[axis] = pgeom->getTouchesRegularBoundary(axis, upper);\n    }\n\n    // Generate a list of local indices which lie in the specified box and set\n    // all periodic offsets to zero.\n    std::vector<int> local_indices;\n    buildLocalIndices(local_indices, interp_box, patch, X_data, X_size, X_depth);\n    std::vector<double> periodic_shifts(NDIM * local_indices.size());\n\n    // Interpolate.\n    if (!local_indices.empty())\n    {\n        std::array<double, NDIM> x_lower_axis, x_upper_axis;\n        const int local_sz = (*std::max_element(local_indices.begin(), local_indices.end())) + 1;\n        std::vector<double> Q_data_axis(local_sz);\n        for (unsigned int axis = 0; axis < NDIM; ++axis)\n        {\n            for (unsigned int d = 0; d < NDIM; ++d)\n            {\n                x_lower_axis[d] = x_lower[d];\n                x_upper_axis[d] = x_upper[d];\n            }\n            x_lower_axis[axis] -= 0.5 * dx[axis];\n            x_upper_axis[axis] += 0.5 * dx[axis];\n            interpolate(&Q_data_axis[0],\n                        /*Q_depth*/ 1,\n                        X_data,\n                        q_data->getPointer(axis),\n                        SideGeometry<NDIM>::toSideBox(q_data->getBox(), axis),\n                        q_data->getGhostCellWidth(),\n                        /*q_depth*/ 1,\n                        x_lower_axis.data(),\n                        x_upper_axis.data(),\n                        dx,\n                        patch_touches_lower_physical_bdry,\n                        patch_touches_upper_physical_bdry,\n                        local_indices,\n                        periodic_shifts,\n                        interp_fcn,\n                        axis);\n            for (const auto& local_index : local_indices)\n            {\n                Q_data[NDIM * local_index + axis] = Q_data_axis[local_index];\n            }\n        }\n    }\n    return;\n}\n\nvoid\nLEInteractor::interpolate(double* const Q_data,\n                          const int Q_size,\n                          const int Q_depth,\n                          const double* const X_data,\n                          const int X_size,\n                          const int X_depth,\n                          const Pointer<SideData<NDIM, double> > mask_data,\n                          const Pointer<SideData<NDIM, double> > q_data,\n                          const Pointer<Patch<NDIM> > patch,\n                          const Box<NDIM>& interp_box,\n                          const std::string& interp_fcn)\n{\n#if !defined(NDEBUG)\n    TBOX_ASSERT(q_data);\n    TBOX_ASSERT(patch);\n    TBOX_ASSERT(Q_depth == NDIM);\n    TBOX_ASSERT(X_depth == NDIM);\n    TBOX_ASSERT(Q_size / Q_depth == X_size / X_depth);\n    TBOX_ASSERT(q_data->getDepth() == 1);\n    TBOX_ASSERT(mask_data);\n    TBOX_ASSERT(mask_data->getDepth() == 1);\n#else\n    NULL_USE(Q_size);\n#endif\n    // Determine the patch geometry.\n    const Pointer<CartesianPatchGeometry<NDIM> > pgeom = patch->getPatchGeometry();\n    const double* const x_lower = pgeom->getXLower();\n    const double* const x_upper = pgeom->getXUpper();\n    const double* const dx = pgeom->getDx();\n    const Box<NDIM>& patch_box = patch->getBox();\n    const IntVector<NDIM>& ilower = patch_box.lower();\n\n    // Get ghost cell width info.\n    const IntVector<NDIM>& q_gcw = q_data->getGhostCellWidth();\n    const IntVector<NDIM>& mask_gcw = mask_data->getGhostCellWidth();\n    const int stencil_size = getStencilSize(interp_fcn);\n    const int min_ghosts = getMinimumGhostWidth(interp_fcn);\n    const int q_gcw_min = q_gcw.min();\n    const int mask_gcw_min = mask_gcw.min();\n    if (q_gcw_min < min_ghosts)\n    {\n        TBOX_ERROR(\"LEInteractor::interpolate(): insufficient ghost cells for Eulerian field data:\\n\"\n                   << \"  kernel function          = \" << interp_fcn << \"\\n\"\n                   << \"  kernel stencil size      = \" << stencil_size << \"\\n\"\n                   << \"  minimum ghost cell width = \" << min_ghosts << \"\\n\"\n                   << \"  ghost cell width         = \" << q_gcw_min << \"\\n\");\n    }\n    if (mask_gcw_min < stencil_size)\n    {\n        TBOX_ERROR(\"LEInteractor::interpolate(): insufficient ghost cells for Eulerian mask data:\\n\"\n                   << \"  kernel function          = \" << interp_fcn << \"\\n\"\n                   << \"  kernel stencil size      = \" << stencil_size << \"\\n\"\n                   << \"  minimum ghost cell width = \" << stencil_size << \"\\n\"\n                   << \"  ghost cell width         = \" << mask_gcw_min << \"\\n\");\n    }\n\n    // Get boundary info.\n    std::array<int, NDIM> patch_touches_lower_physical_bdry(array_zero<int, NDIM>());\n    std::array<int, NDIM> patch_touches_upper_physical_bdry(array_zero<int, NDIM>());\n    for (unsigned int axis = 0; axis < NDIM; ++axis)\n    {\n        static const int lower = 0;\n        patch_touches_lower_physical_bdry[axis] = pgeom->getTouchesRegularBoundary(axis, lower);\n        static const int upper = 1;\n        patch_touches_upper_physical_bdry[axis] = pgeom->getTouchesRegularBoundary(axis, upper);\n    }\n\n    // Generate a list of local indices which lie in the specified box and set\n    // all periodic offsets to zero.\n    std::vector<int> local_indices;\n    buildLocalIndices(local_indices, interp_box, patch, X_data, X_size, X_depth);\n    std::vector<double> periodic_shifts(NDIM * local_indices.size());\n\n    // Interpolate.\n    const int nindices = static_cast<int>(local_indices.size());\n    if (nindices)\n    {\n        std::array<double, NDIM> x_lower_axis, x_upper_axis;\n        IntVector<NDIM> stencil_lower, stencil_upper;\n\n        for (int axis = 0; axis < NDIM; ++axis)\n        {\n            Box<NDIM> data_box = SideGeometry<NDIM>::toSideBox(q_data->getBox(), axis);\n            const IntVector<NDIM> ig_lower = data_box.lower() - q_gcw;\n            const IntVector<NDIM> ig_upper = data_box.upper() + q_gcw;\n\n            for (int d = 0; d < NDIM; ++d)\n            {\n                x_lower_axis[d] = x_lower[d];\n                x_upper_axis[d] = x_upper[d];\n            }\n            x_lower_axis[axis] -= 0.5 * dx[axis];\n            x_upper_axis[axis] += 0.5 * dx[axis];\n\n            for (int k = 0; k < nindices; ++k)\n            {\n                int s = local_indices[k];\n                MLSWeight Psi;\n                const int stencil_sz = LEInteractor::getStencilSize(interp_fcn);\n                get_mls_weights(interp_fcn,\n                                &X_data[s * NDIM],\n                                &periodic_shifts[k * NDIM],\n                                dx,\n                                x_lower_axis.data(),\n                                ilower,\n                                mask_data->getArrayData(axis),\n                                stencil_lower,\n                                stencil_upper,\n                                Psi);\n                interpolate_data(stencil_sz,\n                                 ig_lower,\n                                 ig_upper,\n                                 stencil_lower,\n                                 stencil_upper,\n                                 q_data->getArrayData(axis),\n                                 0,\n                                 Psi,\n                                 Q_data[s * Q_depth + axis]);\n            }\n        }\n    }\n\n    return;\n}\n\nvoid\nLEInteractor::interpolate(double* const Q_data,\n                          const int Q_size,\n                          const int Q_depth,\n                          const double* const X_data,\n                          const int X_size,\n                          const int X_depth,\n                          const Pointer<EdgeData<NDIM, double> > q_data,\n                          const Pointer<Patch<NDIM> > patch,\n                          const Box<NDIM>& interp_box,\n                          const std::string& interp_fcn)\n{\n#if !defined(NDEBUG)\n    TBOX_ASSERT(q_data);\n    TBOX_ASSERT(patch);\n    TBOX_ASSERT(Q_depth == NDIM);\n    TBOX_ASSERT(X_depth == NDIM);\n    TBOX_ASSERT(Q_size / Q_depth == X_size / X_depth);\n    TBOX_ASSERT(q_data->getDepth() == 1);\n#else\n    NULL_USE(Q_size);\n#endif\n    if (Q_depth != NDIM || q_data->getDepth() != 1)\n    {\n        TBOX_ERROR(\"LEInteractor::interpolate():\\n\"\n                   << \"  side-centered interpolation requires vector-valued data.\\n\");\n    }\n\n    // Determine the patch geometry.\n    const Pointer<CartesianPatchGeometry<NDIM> > pgeom = patch->getPatchGeometry();\n    const double* const x_lower = pgeom->getXLower();\n    const double* const x_upper = pgeom->getXUpper();\n    const double* const dx = pgeom->getDx();\n    std::array<int, NDIM> patch_touches_lower_physical_bdry(array_zero<int, NDIM>());\n    std::array<int, NDIM> patch_touches_upper_physical_bdry(array_zero<int, NDIM>());\n    for (unsigned int axis = 0; axis < NDIM; ++axis)\n    {\n        static const int lower = 0;\n        patch_touches_lower_physical_bdry[axis] = pgeom->getTouchesRegularBoundary(axis, lower);\n        static const int upper = 1;\n        patch_touches_upper_physical_bdry[axis] = pgeom->getTouchesRegularBoundary(axis, upper);\n    }\n\n    // Generate a list of local indices which lie in the specified box and set\n    // all periodic offsets to zero.\n    std::vector<int> local_indices;\n    buildLocalIndices(local_indices, interp_box, patch, X_data, X_size, X_depth);\n    std::vector<double> periodic_shifts(NDIM * local_indices.size());\n\n    // Interpolate.\n    if (!local_indices.empty())\n    {\n        std::array<double, NDIM> x_lower_axis, x_upper_axis;\n        const int local_sz = (*std::max_element(local_indices.begin(), local_indices.end())) + 1;\n        std::vector<double> Q_data_axis(local_sz);\n        for (unsigned int axis = 0; axis < NDIM; ++axis)\n        {\n            for (unsigned int d = 0; d < NDIM; ++d)\n            {\n                x_lower_axis[d] = x_lower[d];\n                x_upper_axis[d] = x_upper[d];\n                if (d != axis)\n                {\n                    x_lower_axis[d] -= 0.5 * dx[d];\n                    x_upper_axis[d] += 0.5 * dx[d];\n                }\n            }\n            interpolate(&Q_data_axis[0],\n                        /*Q_depth*/ 1,\n                        X_data,\n                        q_data->getPointer(axis),\n                        EdgeGeometry<NDIM>::toEdgeBox(q_data->getBox(), axis),\n                        q_data->getGhostCellWidth(),\n                        /*q_depth*/ 1,\n                        x_lower_axis.data(),\n                        x_upper_axis.data(),\n                        dx,\n                        patch_touches_lower_physical_bdry,\n                        patch_touches_upper_physical_bdry,\n                        local_indices,\n                        periodic_shifts,\n                        interp_fcn,\n                        axis);\n            for (const auto& local_index : local_indices)\n            {\n                Q_data[NDIM * local_index + axis] = Q_data_axis[local_index];\n            }\n        }\n    }\n    return;\n}\n\ntemplate <class T>\nvoid\nLEInteractor::spread(Pointer<CellData<NDIM, double> > q_data,\n                     const Pointer<LData> Q_data,\n                     const Pointer<LData> X_data,\n                     const Pointer<LIndexSetData<T> > idx_data,\n                     const Pointer<Patch<NDIM> > patch,\n                     const Box<NDIM>& spread_box,\n                     const IntVector<NDIM>& periodic_shift,\n                     const std::string& spread_fcn)\n{\n#if !defined(NDEBUG)\n    TBOX_ASSERT(Q_data);\n    TBOX_ASSERT(q_data);\n    TBOX_ASSERT(X_data);\n    TBOX_ASSERT(idx_data);\n    TBOX_ASSERT(patch);\n    TBOX_ASSERT(Q_data->getDepth() == static_cast<unsigned int>(q_data->getDepth()));\n    TBOX_ASSERT(X_data->getDepth() == NDIM);\n#endif\n    spread(q_data,\n           Q_data->getGhostedLocalFormVecArray()->data(),\n           Q_data->getDepth(),\n           X_data->getGhostedLocalFormVecArray()->data(),\n           X_data->getDepth(),\n           idx_data,\n           patch,\n           spread_box,\n           periodic_shift,\n           spread_fcn);\n    Q_data->restoreArrays();\n    X_data->restoreArrays();\n    return;\n}\n\ntemplate <class T>\nvoid\nLEInteractor::spread(Pointer<NodeData<NDIM, double> > q_data,\n                     const Pointer<LData> Q_data,\n                     const Pointer<LData> X_data,\n                     const Pointer<LIndexSetData<T> > idx_data,\n                     const Pointer<Patch<NDIM> > patch,\n                     const Box<NDIM>& spread_box,\n                     const IntVector<NDIM>& periodic_shift,\n                     const std::string& spread_fcn)\n{\n#if !defined(NDEBUG)\n    TBOX_ASSERT(Q_data);\n    TBOX_ASSERT(q_data);\n    TBOX_ASSERT(X_data);\n    TBOX_ASSERT(idx_data);\n    TBOX_ASSERT(patch);\n    TBOX_ASSERT(Q_data->getDepth() == static_cast<unsigned int>(q_data->getDepth()));\n    TBOX_ASSERT(X_data->getDepth() == NDIM);\n#endif\n    spread(q_data,\n           Q_data->getGhostedLocalFormVecArray()->data(),\n           Q_data->getDepth(),\n           X_data->getGhostedLocalFormVecArray()->data(),\n           X_data->getDepth(),\n           idx_data,\n           patch,\n           spread_box,\n           periodic_shift,\n           spread_fcn);\n    Q_data->restoreArrays();\n    X_data->restoreArrays();\n    return;\n}\n\ntemplate <class T>\nvoid\nLEInteractor::spread(Pointer<SideData<NDIM, double> > q_data,\n                     const Pointer<LData> Q_data,\n                     const Pointer<LData> X_data,\n                     const Pointer<LIndexSetData<T> > idx_data,\n                     const Pointer<Patch<NDIM> > patch,\n                     const Box<NDIM>& spread_box,\n                     const IntVector<NDIM>& periodic_shift,\n                     const std::string& spread_fcn)\n{\n    if (Q_data->getDepth() != NDIM || q_data->getDepth() != 1)\n    {\n        TBOX_ERROR(\"LEInteractor::spread():\\n\"\n                   << \"  side-centered spreading requires vector-valued data.\\n\");\n    }\n#if !defined(NDEBUG)\n    TBOX_ASSERT(Q_data);\n    TBOX_ASSERT(q_data);\n    TBOX_ASSERT(X_data);\n    TBOX_ASSERT(idx_data);\n    TBOX_ASSERT(patch);\n    TBOX_ASSERT(q_data->getDepth() == 1);\n    TBOX_ASSERT(Q_data->getDepth() == NDIM);\n    TBOX_ASSERT(X_data->getDepth() == NDIM);\n#endif\n    spread(q_data,\n           Q_data->getGhostedLocalFormVecArray()->data(),\n           Q_data->getDepth(),\n           X_data->getGhostedLocalFormVecArray()->data(),\n           X_data->getDepth(),\n           idx_data,\n           patch,\n           spread_box,\n           periodic_shift,\n           spread_fcn);\n    Q_data->restoreArrays();\n    X_data->restoreArrays();\n    return;\n}\n\ntemplate <class T>\nvoid\nLEInteractor::spread(Pointer<EdgeData<NDIM, double> > q_data,\n                     const Pointer<LData> Q_data,\n                     const Pointer<LData> X_data,\n                     const Pointer<LIndexSetData<T> > idx_data,\n                     const Pointer<Patch<NDIM> > patch,\n                     const Box<NDIM>& spread_box,\n                     const IntVector<NDIM>& periodic_shift,\n                     const std::string& spread_fcn)\n{\n    if (NDIM != 3 || Q_data->getDepth() != NDIM || q_data->getDepth() != 1)\n    {\n        TBOX_ERROR(\"LEInteractor::spread():\\n\"\n                   << \"  edge-centered interpolation requires 3D vector-valued data.\\n\");\n    }\n#if !defined(NDEBUG)\n    TBOX_ASSERT(Q_data);\n    TBOX_ASSERT(q_data);\n    TBOX_ASSERT(X_data);\n    TBOX_ASSERT(idx_data);\n    TBOX_ASSERT(patch);\n    TBOX_ASSERT(q_data->getDepth() == 1);\n    TBOX_ASSERT(Q_data->getDepth() == NDIM);\n    TBOX_ASSERT(X_data->getDepth() == NDIM);\n#endif\n    spread(q_data,\n           Q_data->getGhostedLocalFormVecArray()->data(),\n           Q_data->getDepth(),\n           X_data->getGhostedLocalFormVecArray()->data(),\n           X_data->getDepth(),\n           idx_data,\n           patch,\n           spread_box,\n           periodic_shift,\n           spread_fcn);\n    Q_data->restoreArrays();\n    X_data->restoreArrays();\n    return;\n}\n\ntemplate <class T>\nvoid\nLEInteractor::spread(Pointer<CellData<NDIM, double> > q_data,\n                     const double* const Q_data,\n                     const int Q_depth,\n                     const double* const X_data,\n                     const int X_depth,\n                     const Pointer<LIndexSetData<T> > idx_data,\n                     const Pointer<Patch<NDIM> > patch,\n                     const Box<NDIM>& spread_box,\n                     const IntVector<NDIM>& periodic_shift,\n                     const std::string& spread_fcn)\n{\n#if !defined(NDEBUG)\n    TBOX_ASSERT(q_data);\n    TBOX_ASSERT(idx_data);\n    TBOX_ASSERT(patch);\n    TBOX_ASSERT(Q_depth == q_data->getDepth());\n    TBOX_ASSERT(X_depth == NDIM);\n#else\n    NULL_USE(X_depth);\n#endif\n    // Determine the patch geometry.\n    const Pointer<CartesianPatchGeometry<NDIM> > pgeom = patch->getPatchGeometry();\n    const double* const x_lower = pgeom->getXLower();\n    const double* const x_upper = pgeom->getXUpper();\n    const double* const dx = pgeom->getDx();\n    std::array<int, NDIM> patch_touches_lower_physical_bdry(array_zero<int, NDIM>());\n    std::array<int, NDIM> patch_touches_upper_physical_bdry(array_zero<int, NDIM>());\n    for (unsigned int axis = 0; axis < NDIM; ++axis)\n    {\n        static const int lower = 0;\n        patch_touches_lower_physical_bdry[axis] = pgeom->getTouchesRegularBoundary(axis, lower);\n        static const int upper = 1;\n        patch_touches_upper_physical_bdry[axis] = pgeom->getTouchesRegularBoundary(axis, upper);\n    }\n\n    // Generate a list of local indices which lie in the specified box.\n    std::vector<int> local_indices;\n    std::vector<double> periodic_shifts;\n    buildLocalIndices(local_indices, periodic_shifts, spread_box, patch, periodic_shift, idx_data);\n\n    // Spread.\n    if (!local_indices.empty())\n    {\n        spread(q_data->getPointer(),\n               q_data->getBox(),\n               q_data->getGhostCellWidth(),\n               q_data->getDepth(),\n               Q_data,\n               Q_depth,\n               X_data,\n               x_lower,\n               x_upper,\n               dx,\n               patch_touches_lower_physical_bdry,\n               patch_touches_upper_physical_bdry,\n               local_indices,\n               periodic_shifts,\n               spread_fcn);\n    }\n    return;\n}\n\ntemplate <class T>\nvoid\nLEInteractor::spread(Pointer<NodeData<NDIM, double> > q_data,\n                     const double* const Q_data,\n                     const int Q_depth,\n                     const double* const X_data,\n                     const int X_depth,\n                     const Pointer<LIndexSetData<T> > idx_data,\n                     const Pointer<Patch<NDIM> > patch,\n                     const Box<NDIM>& spread_box,\n                     const IntVector<NDIM>& periodic_shift,\n                     const std::string& spread_fcn)\n{\n#if !defined(NDEBUG)\n    TBOX_ASSERT(q_data);\n    TBOX_ASSERT(idx_data);\n    TBOX_ASSERT(patch);\n    TBOX_ASSERT(Q_depth == q_data->getDepth());\n    TBOX_ASSERT(X_depth == NDIM);\n#else\n    NULL_USE(X_depth);\n#endif\n    // Determine the patch geometry.\n    const Pointer<CartesianPatchGeometry<NDIM> > pgeom = patch->getPatchGeometry();\n    const double* const x_lower = pgeom->getXLower();\n    const double* const x_upper = pgeom->getXUpper();\n    const double* const dx = pgeom->getDx();\n    std::array<int, NDIM> patch_touches_lower_physical_bdry(array_zero<int, NDIM>());\n    std::array<int, NDIM> patch_touches_upper_physical_bdry(array_zero<int, NDIM>());\n    for (unsigned int axis = 0; axis < NDIM; ++axis)\n    {\n        static const int lower = 0;\n        patch_touches_lower_physical_bdry[axis] = pgeom->getTouchesRegularBoundary(axis, lower);\n        static const int upper = 1;\n        patch_touches_upper_physical_bdry[axis] = pgeom->getTouchesRegularBoundary(axis, upper);\n    }\n\n    // Generate a list of local indices which lie in the specified box.\n    std::vector<int> local_indices;\n    std::vector<double> periodic_shifts;\n    buildLocalIndices(local_indices, periodic_shifts, spread_box, patch, periodic_shift, idx_data);\n\n    // Spread.\n    if (!local_indices.empty())\n    {\n        std::array<double, NDIM> x_lower_node, x_upper_node;\n        for (unsigned int d = 0; d < NDIM; ++d)\n        {\n            x_lower_node[d] = x_lower[d] - 0.5 * dx[d];\n            x_upper_node[d] = x_upper[d] + 0.5 * dx[d];\n        }\n        spread(q_data->getPointer(),\n               NodeGeometry<NDIM>::toNodeBox(q_data->getBox()),\n               q_data->getGhostCellWidth(),\n               q_data->getDepth(),\n               Q_data,\n               Q_depth,\n               X_data,\n               x_lower_node.data(),\n               x_upper_node.data(),\n               dx,\n               patch_touches_lower_physical_bdry,\n               patch_touches_upper_physical_bdry,\n               local_indices,\n               periodic_shifts,\n               spread_fcn);\n    }\n    return;\n}\n\ntemplate <class T>\nvoid\nLEInteractor::spread(Pointer<SideData<NDIM, double> > q_data,\n                     const double* const Q_data,\n                     const int Q_depth,\n                     const double* const X_data,\n                     const int X_depth,\n                     const Pointer<LIndexSetData<T> > idx_data,\n                     const Pointer<Patch<NDIM> > patch,\n                     const Box<NDIM>& spread_box,\n                     const IntVector<NDIM>& periodic_shift,\n                     const std::string& spread_fcn)\n{\n#if !defined(NDEBUG)\n    TBOX_ASSERT(q_data);\n    TBOX_ASSERT(idx_data);\n    TBOX_ASSERT(patch);\n    TBOX_ASSERT(q_data->getDepth() == 1);\n    TBOX_ASSERT(Q_depth == NDIM);\n    TBOX_ASSERT(X_depth == NDIM);\n#else\n    NULL_USE(X_depth);\n#endif\n    if (Q_depth != NDIM || q_data->getDepth() != 1)\n    {\n        TBOX_ERROR(\"LEInteractor::spread():\\n\"\n                   << \"  side-centered spreading requires vector-valued data.\\n\");\n    }\n\n    // Determine the patch geometry.\n    const Pointer<CartesianPatchGeometry<NDIM> > pgeom = patch->getPatchGeometry();\n    const double* const x_lower = pgeom->getXLower();\n    const double* const x_upper = pgeom->getXUpper();\n    const double* const dx = pgeom->getDx();\n    std::array<int, NDIM> patch_touches_lower_physical_bdry(array_zero<int, NDIM>());\n    std::array<int, NDIM> patch_touches_upper_physical_bdry(array_zero<int, NDIM>());\n    for (unsigned int axis = 0; axis < NDIM; ++axis)\n    {\n        static const int lower = 0;\n        patch_touches_lower_physical_bdry[axis] = pgeom->getTouchesRegularBoundary(axis, lower);\n        static const int upper = 1;\n        patch_touches_upper_physical_bdry[axis] = pgeom->getTouchesRegularBoundary(axis, upper);\n    }\n\n    // Generate a list of local indices which lie in the specified box.\n    std::vector<int> local_indices;\n    std::vector<double> periodic_shifts;\n    buildLocalIndices(local_indices, periodic_shifts, spread_box, patch, periodic_shift, idx_data);\n\n    // Spread.\n    if (!local_indices.empty())\n    {\n        std::array<double, NDIM> x_lower_axis, x_upper_axis;\n        const int local_sz = (*std::max_element(local_indices.begin(), local_indices.end())) + 1;\n        std::vector<double> Q_data_axis(local_sz);\n        for (unsigned int axis = 0; axis < NDIM; ++axis)\n        {\n            for (unsigned int d = 0; d < NDIM; ++d)\n            {\n                x_lower_axis[d] = x_lower[d];\n                x_upper_axis[d] = x_upper[d];\n            }\n            x_lower_axis[axis] -= 0.5 * dx[axis];\n            x_upper_axis[axis] += 0.5 * dx[axis];\n            for (const auto& local_index : local_indices)\n            {\n                Q_data_axis[local_index] = Q_data[NDIM * local_index + axis];\n            }\n            spread(q_data->getPointer(axis),\n                   SideGeometry<NDIM>::toSideBox(q_data->getBox(), axis),\n                   q_data->getGhostCellWidth(),\n                   /*q_depth*/ 1,\n                   &Q_data_axis[0],\n                   /*Q_depth*/ 1,\n                   X_data,\n                   x_lower_axis.data(),\n                   x_upper_axis.data(),\n                   dx,\n                   patch_touches_lower_physical_bdry,\n                   patch_touches_upper_physical_bdry,\n                   local_indices,\n                   periodic_shifts,\n                   spread_fcn,\n                   axis);\n        }\n    }\n    return;\n}\n\ntemplate <class T>\nvoid\nLEInteractor::spread(Pointer<EdgeData<NDIM, double> > q_data,\n                     const double* const Q_data,\n                     const int Q_depth,\n                     const double* const X_data,\n                     const int X_depth,\n                     const Pointer<LIndexSetData<T> > idx_data,\n                     const Pointer<Patch<NDIM> > patch,\n                     const Box<NDIM>& spread_box,\n                     const IntVector<NDIM>& periodic_shift,\n                     const std::string& spread_fcn)\n{\n#if !defined(NDEBUG)\n    TBOX_ASSERT(q_data);\n    TBOX_ASSERT(idx_data);\n    TBOX_ASSERT(patch);\n    TBOX_ASSERT(q_data->getDepth() == 1);\n    TBOX_ASSERT(Q_depth == NDIM);\n    TBOX_ASSERT(X_depth == NDIM);\n#else\n    NULL_USE(X_depth);\n#endif\n    if (NDIM != 3 || Q_depth != NDIM || q_data->getDepth() != 1)\n    {\n        TBOX_ERROR(\"LEInteractor::spread():\\n\"\n                   << \"  edge-centered interpolation requires 3D vector-valued data.\\n\");\n    }\n\n    // Determine the patch geometry.\n    const Pointer<CartesianPatchGeometry<NDIM> > pgeom = patch->getPatchGeometry();\n    const double* const x_lower = pgeom->getXLower();\n    const double* const x_upper = pgeom->getXUpper();\n    const double* const dx = pgeom->getDx();\n    std::array<int, NDIM> patch_touches_lower_physical_bdry(array_zero<int, NDIM>());\n    std::array<int, NDIM> patch_touches_upper_physical_bdry(array_zero<int, NDIM>());\n    for (unsigned int axis = 0; axis < NDIM; ++axis)\n    {\n        static const int lower = 0;\n        patch_touches_lower_physical_bdry[axis] = pgeom->getTouchesRegularBoundary(axis, lower);\n        static const int upper = 1;\n        patch_touches_upper_physical_bdry[axis] = pgeom->getTouchesRegularBoundary(axis, upper);\n    }\n\n    // Generate a list of local indices which lie in the specified box.\n    std::vector<int> local_indices;\n    std::vector<double> periodic_shifts;\n    buildLocalIndices(local_indices, periodic_shifts, spread_box, patch, periodic_shift, idx_data);\n\n    // Spread.\n    if (!local_indices.empty())\n    {\n        std::array<double, NDIM> x_lower_axis, x_upper_axis;\n        const int local_sz = (*std::max_element(local_indices.begin(), local_indices.end())) + 1;\n        std::vector<double> Q_data_axis(local_sz);\n        for (unsigned int axis = 0; axis < NDIM; ++axis)\n        {\n            for (unsigned int d = 0; d < NDIM; ++d)\n            {\n                x_lower_axis[d] = x_lower[d];\n                x_upper_axis[d] = x_upper[d];\n                if (d != axis)\n                {\n                    x_lower_axis[d] -= 0.5 * dx[d];\n                    x_upper_axis[d] += 0.5 * dx[d];\n                }\n            }\n            for (const auto& local_index : local_indices)\n            {\n                Q_data_axis[local_index] = Q_data[NDIM * local_index + axis];\n            }\n            spread(q_data->getPointer(axis),\n                   EdgeGeometry<NDIM>::toEdgeBox(q_data->getBox(), axis),\n                   q_data->getGhostCellWidth(),\n                   /*q_depth*/ 1,\n                   &Q_data_axis[0],\n                   /*Q_depth*/ 1,\n                   X_data,\n                   x_lower_axis.data(),\n                   x_upper_axis.data(),\n                   dx,\n                   patch_touches_lower_physical_bdry,\n                   patch_touches_upper_physical_bdry,\n                   local_indices,\n                   periodic_shifts,\n                   spread_fcn,\n                   axis);\n        }\n    }\n    return;\n}\n\nvoid\nLEInteractor::spread(Pointer<CellData<NDIM, double> > q_data,\n                     const std::vector<double>& Q_data,\n                     const int Q_depth,\n                     const std::vector<double>& X_data,\n                     const int X_depth,\n                     const Pointer<Patch<NDIM> > patch,\n                     const Box<NDIM>& spread_box,\n                     const std::string& spread_fcn)\n{\n    if (Q_data.empty()) return;\n    spread(q_data,\n           &Q_data[0],\n           static_cast<int>(Q_data.size()),\n           Q_depth,\n           &X_data[0],\n           static_cast<int>(X_data.size()),\n           X_depth,\n           patch,\n           spread_box,\n           spread_fcn);\n}\n\nvoid\nLEInteractor::spread(Pointer<CellData<NDIM, double> > mask_data,\n                     Pointer<CellData<NDIM, double> > q_data,\n                     const std::vector<double>& Q_data,\n                     const int Q_depth,\n                     const std::vector<double>& X_data,\n                     const int X_depth,\n                     const Pointer<Patch<NDIM> > patch,\n                     const Box<NDIM>& spread_box,\n                     const std::string& spread_fcn)\n{\n    if (Q_data.empty()) return;\n    spread(mask_data,\n           q_data,\n           &Q_data[0],\n           static_cast<int>(Q_data.size()),\n           Q_depth,\n           &X_data[0],\n           static_cast<int>(X_data.size()),\n           X_depth,\n           patch,\n           spread_box,\n           spread_fcn);\n}\n\nvoid\nLEInteractor::spread(Pointer<NodeData<NDIM, double> > q_data,\n                     const std::vector<double>& Q_data,\n                     const int Q_depth,\n                     const std::vector<double>& X_data,\n                     const int X_depth,\n                     const Pointer<Patch<NDIM> > patch,\n                     const Box<NDIM>& spread_box,\n                     const std::string& spread_fcn)\n{\n    if (Q_data.empty()) return;\n    spread(q_data,\n           &Q_data[0],\n           static_cast<int>(Q_data.size()),\n           Q_depth,\n           &X_data[0],\n           static_cast<int>(X_data.size()),\n           X_depth,\n           patch,\n           spread_box,\n           spread_fcn);\n}\n\nvoid\nLEInteractor::spread(Pointer<SideData<NDIM, double> > q_data,\n                     const std::vector<double>& Q_data,\n                     const int Q_depth,\n                     const std::vector<double>& X_data,\n                     const int X_depth,\n                     const Pointer<Patch<NDIM> > patch,\n                     const Box<NDIM>& spread_box,\n                     const std::string& spread_fcn)\n{\n    if (Q_data.empty()) return;\n    spread(q_data,\n           &Q_data[0],\n           static_cast<int>(Q_data.size()),\n           Q_depth,\n           &X_data[0],\n           static_cast<int>(X_data.size()),\n           X_depth,\n           patch,\n           spread_box,\n           spread_fcn);\n}\n\nvoid\nLEInteractor::spread(Pointer<SideData<NDIM, double> > mask_data,\n                     Pointer<SideData<NDIM, double> > q_data,\n                     const std::vector<double>& Q_data,\n                     const int Q_depth,\n                     const std::vector<double>& X_data,\n                     const int X_depth,\n                     const Pointer<Patch<NDIM> > patch,\n                     const Box<NDIM>& spread_box,\n                     const std::string& spread_fcn)\n{\n    if (Q_data.empty()) return;\n    spread(mask_data,\n           q_data,\n           &Q_data[0],\n           static_cast<int>(Q_data.size()),\n           Q_depth,\n           &X_data[0],\n           static_cast<int>(X_data.size()),\n           X_depth,\n           patch,\n           spread_box,\n           spread_fcn);\n}\n\nvoid\nLEInteractor::spread(Pointer<EdgeData<NDIM, double> > q_data,\n                     const std::vector<double>& Q_data,\n                     const int Q_depth,\n                     const std::vector<double>& X_data,\n                     const int X_depth,\n                     const Pointer<Patch<NDIM> > patch,\n                     const Box<NDIM>& spread_box,\n                     const std::string& spread_fcn)\n{\n    if (Q_data.empty()) return;\n    spread(q_data,\n           &Q_data[0],\n           static_cast<int>(Q_data.size()),\n           Q_depth,\n           &X_data[0],\n           static_cast<int>(X_data.size()),\n           X_depth,\n           patch,\n           spread_box,\n           spread_fcn);\n}\n\nvoid\nLEInteractor::spread(Pointer<CellData<NDIM, double> > q_data,\n                     const double* const Q_data,\n                     const int Q_size,\n                     const int Q_depth,\n                     const double* const X_data,\n                     const int X_size,\n                     const int X_depth,\n                     const Pointer<Patch<NDIM> > patch,\n                     const Box<NDIM>& spread_box,\n                     const std::string& spread_fcn)\n{\n#if !defined(NDEBUG)\n    TBOX_ASSERT(q_data);\n    TBOX_ASSERT(patch);\n    TBOX_ASSERT(Q_depth == q_data->getDepth());\n    TBOX_ASSERT(X_depth == NDIM);\n    TBOX_ASSERT(Q_size / Q_depth == X_size / X_depth);\n#else\n    NULL_USE(Q_size);\n#endif\n    // Determine the patch geometry.\n    const Pointer<CartesianPatchGeometry<NDIM> > pgeom = patch->getPatchGeometry();\n    const double* const x_lower = pgeom->getXLower();\n    const double* const x_upper = pgeom->getXUpper();\n    const double* const dx = pgeom->getDx();\n    std::array<int, NDIM> patch_touches_lower_physical_bdry(array_zero<int, NDIM>());\n    std::array<int, NDIM> patch_touches_upper_physical_bdry(array_zero<int, NDIM>());\n    for (unsigned int axis = 0; axis < NDIM; ++axis)\n    {\n        static const int lower = 0;\n        patch_touches_lower_physical_bdry[axis] = pgeom->getTouchesRegularBoundary(axis, lower);\n        static const int upper = 1;\n        patch_touches_upper_physical_bdry[axis] = pgeom->getTouchesRegularBoundary(axis, upper);\n    }\n\n    // Generate a list of local indices which lie in the specified box and set\n    // all periodic offsets to zero.\n    std::vector<int> local_indices;\n    buildLocalIndices(local_indices, spread_box, patch, X_data, X_size, X_depth);\n    std::vector<double> periodic_shifts(NDIM * local_indices.size());\n\n    // Spread.\n    if (!local_indices.empty())\n    {\n        spread(q_data->getPointer(),\n               q_data->getBox(),\n               q_data->getGhostCellWidth(),\n               q_data->getDepth(),\n               Q_data,\n               Q_depth,\n               X_data,\n               x_lower,\n               x_upper,\n               dx,\n               patch_touches_lower_physical_bdry,\n               patch_touches_upper_physical_bdry,\n               local_indices,\n               periodic_shifts,\n               spread_fcn);\n    }\n    return;\n}\n\nvoid\nLEInteractor::spread(Pointer<CellData<NDIM, double> > mask_data,\n                     Pointer<CellData<NDIM, double> > q_data,\n                     const double* const Q_data,\n                     const int Q_size,\n                     const int Q_depth,\n                     const double* const X_data,\n                     const int X_size,\n                     const int X_depth,\n                     const Pointer<Patch<NDIM> > patch,\n                     const Box<NDIM>& spread_box,\n                     const std::string& spread_fcn)\n{\n#if !defined(NDEBUG)\n    TBOX_ASSERT(q_data);\n    TBOX_ASSERT(patch);\n    TBOX_ASSERT(Q_depth == q_data->getDepth());\n    TBOX_ASSERT(X_depth == NDIM);\n    TBOX_ASSERT(Q_size / Q_depth == X_size / X_depth);\n    TBOX_ASSERT(mask_data);\n    TBOX_ASSERT(mask_data->getDepth() == 1);\n#else\n    NULL_USE(Q_size);\n#endif\n    // Determine the patch geometry.\n    const Pointer<CartesianPatchGeometry<NDIM> > pgeom = patch->getPatchGeometry();\n    const double* const x_lower = pgeom->getXLower();\n    const double* const dx = pgeom->getDx();\n    const Box<NDIM>& patch_box = patch->getBox();\n    const IntVector<NDIM>& ilower = patch_box.lower();\n    const IntVector<NDIM>& iupper = patch_box.upper();\n\n    // Get ghost cell width info.\n    const IntVector<NDIM>& q_gcw = q_data->getGhostCellWidth();\n    const IntVector<NDIM>& mask_gcw = mask_data->getGhostCellWidth();\n    const int stencil_size = getStencilSize(spread_fcn);\n    const int min_ghosts = getMinimumGhostWidth(spread_fcn);\n    const int q_gcw_min = q_gcw.min();\n    const int mask_gcw_min = mask_gcw.min();\n    if (q_gcw_min < min_ghosts)\n    {\n        TBOX_ERROR(\"LEInteractor::spread(): insufficient ghost cells for Eulerian field data:\\n\"\n                   << \"  kernel function          = \" << spread_fcn << \"\\n\"\n                   << \"  kernel stencil size      = \" << stencil_size << \"\\n\"\n                   << \"  minimum ghost cell width = \" << min_ghosts << \"\\n\"\n                   << \"  ghost cell width         = \" << q_gcw_min << \"\\n\");\n    }\n    if (mask_gcw_min < stencil_size)\n    {\n        TBOX_ERROR(\"LEInteractor::spread(): insufficient ghost cells for Eulerian mask data:\\n\"\n                   << \"  kernel function          = \" << spread_fcn << \"\\n\"\n                   << \"  kernel stencil size      = \" << stencil_size << \"\\n\"\n                   << \"  minimum ghost cell width = \" << stencil_size << \"\\n\"\n                   << \"  ghost cell width         = \" << mask_gcw_min << \"\\n\");\n    }\n    const IntVector<NDIM> ig_lower = ilower - q_gcw;\n    const IntVector<NDIM> ig_upper = iupper + q_gcw;\n\n    // Get boundary info.\n    std::array<int, NDIM> patch_touches_lower_physical_bdry(array_zero<int, NDIM>());\n    std::array<int, NDIM> patch_touches_upper_physical_bdry(array_zero<int, NDIM>());\n    for (unsigned int axis = 0; axis < NDIM; ++axis)\n    {\n        static const int lower = 0;\n        patch_touches_lower_physical_bdry[axis] = pgeom->getTouchesRegularBoundary(axis, lower);\n        static const int upper = 1;\n        patch_touches_upper_physical_bdry[axis] = pgeom->getTouchesRegularBoundary(axis, upper);\n    }\n\n    // Generate a list of local indices which lie in the specified box and set\n    // all periodic offsets to zero.\n    std::vector<int> local_indices;\n    buildLocalIndices(local_indices, spread_box, patch, X_data, X_size, X_depth);\n    std::vector<double> periodic_shifts(NDIM * local_indices.size());\n\n    // Spread.\n    const int nindices = static_cast<int>(local_indices.size());\n    if (nindices)\n    {\n        IntVector<NDIM> stencil_lower, stencil_upper;\n        for (int k = 0; k < nindices; ++k)\n        {\n            int s = local_indices[k];\n            MLSWeight Psi;\n            const int stencil_sz = LEInteractor::getStencilSize(spread_fcn);\n            get_mls_weights(spread_fcn,\n                            &X_data[s * NDIM],\n                            &periodic_shifts[k * NDIM],\n                            dx,\n                            x_lower,\n                            ilower,\n                            mask_data->getArrayData(),\n                            stencil_lower,\n                            stencil_upper,\n                            Psi);\n\n            for (int comp = 0; comp < Q_depth; ++comp)\n            {\n                spread_data(stencil_sz,\n                            ig_lower,\n                            ig_upper,\n                            stencil_lower,\n                            stencil_upper,\n                            dx,\n                            q_data->getArrayData(),\n                            comp,\n                            Psi,\n                            Q_data[s * Q_depth + comp]);\n            }\n        }\n    }\n\n    return;\n}\n\nvoid\nLEInteractor::spread(Pointer<NodeData<NDIM, double> > q_data,\n                     const double* const Q_data,\n                     const int Q_size,\n                     const int Q_depth,\n                     const double* const X_data,\n                     const int X_size,\n                     const int X_depth,\n                     const Pointer<Patch<NDIM> > patch,\n                     const Box<NDIM>& spread_box,\n                     const std::string& spread_fcn)\n{\n#if !defined(NDEBUG)\n    TBOX_ASSERT(q_data);\n    TBOX_ASSERT(patch);\n    TBOX_ASSERT(Q_depth == q_data->getDepth());\n    TBOX_ASSERT(X_depth == NDIM);\n    TBOX_ASSERT(Q_size / Q_depth == X_size / X_depth);\n#else\n    NULL_USE(Q_size);\n#endif\n    // Determine the patch geometry.\n    const Pointer<CartesianPatchGeometry<NDIM> > pgeom = patch->getPatchGeometry();\n    const double* const x_lower = pgeom->getXLower();\n    const double* const x_upper = pgeom->getXUpper();\n    const double* const dx = pgeom->getDx();\n    std::array<int, NDIM> patch_touches_lower_physical_bdry(array_zero<int, NDIM>());\n    std::array<int, NDIM> patch_touches_upper_physical_bdry(array_zero<int, NDIM>());\n    for (unsigned int axis = 0; axis < NDIM; ++axis)\n    {\n        static const int lower = 0;\n        patch_touches_lower_physical_bdry[axis] = pgeom->getTouchesRegularBoundary(axis, lower);\n        static const int upper = 1;\n        patch_touches_upper_physical_bdry[axis] = pgeom->getTouchesRegularBoundary(axis, upper);\n    }\n\n    // Generate a list of local indices which lie in the specified box and set\n    // all periodic offsets to zero.\n    std::vector<int> local_indices;\n    buildLocalIndices(local_indices, spread_box, patch, X_data, X_size, X_depth);\n    std::vector<double> periodic_shifts(NDIM * local_indices.size());\n\n    // Spread.\n    if (!local_indices.empty())\n    {\n        std::array<double, NDIM> x_lower_node, x_upper_node;\n        for (unsigned int d = 0; d < NDIM; ++d)\n        {\n            x_lower_node[d] = x_lower[d] - 0.5 * dx[d];\n            x_upper_node[d] = x_upper[d] + 0.5 * dx[d];\n        }\n        spread(q_data->getPointer(),\n               NodeGeometry<NDIM>::toNodeBox(q_data->getBox()),\n               q_data->getGhostCellWidth(),\n               q_data->getDepth(),\n               Q_data,\n               Q_depth,\n               X_data,\n               x_lower_node.data(),\n               x_upper_node.data(),\n               dx,\n               patch_touches_lower_physical_bdry,\n               patch_touches_upper_physical_bdry,\n               local_indices,\n               periodic_shifts,\n               spread_fcn);\n    }\n    return;\n}\n\nvoid\nLEInteractor::spread(Pointer<SideData<NDIM, double> > q_data,\n                     const double* const Q_data,\n                     const int /*Q_size*/,\n                     const int Q_depth,\n                     const double* const X_data,\n                     const int X_size,\n                     const int X_depth,\n                     const Pointer<Patch<NDIM> > patch,\n                     const Box<NDIM>& spread_box,\n                     const std::string& spread_fcn)\n{\n    if (Q_depth != NDIM || q_data->getDepth() != 1)\n    {\n        TBOX_ERROR(\"LEInteractor::spread():\\n\"\n                   << \"  side-centered spreading requires vector-valued data.\\n\");\n    }\n#if !defined(NDEBUG)\n    TBOX_ASSERT(q_data);\n    TBOX_ASSERT(patch);\n    TBOX_ASSERT(Q_depth == NDIM);\n    TBOX_ASSERT(X_depth == NDIM);\n#endif\n    // Determine the patch geometry.\n    const Pointer<CartesianPatchGeometry<NDIM> > pgeom = patch->getPatchGeometry();\n    const double* const x_lower = pgeom->getXLower();\n    const double* const x_upper = pgeom->getXUpper();\n    const double* const dx = pgeom->getDx();\n    std::array<int, NDIM> patch_touches_lower_physical_bdry(array_zero<int, NDIM>());\n    std::array<int, NDIM> patch_touches_upper_physical_bdry(array_zero<int, NDIM>());\n    for (unsigned int axis = 0; axis < NDIM; ++axis)\n    {\n        static const int lower = 0;\n        patch_touches_lower_physical_bdry[axis] = pgeom->getTouchesRegularBoundary(axis, lower);\n        static const int upper = 1;\n        patch_touches_upper_physical_bdry[axis] = pgeom->getTouchesRegularBoundary(axis, upper);\n    }\n\n    // Generate a list of local indices which lie in the specified box and set\n    // all periodic offsets to zero.\n    std::vector<int> local_indices;\n    buildLocalIndices(local_indices, spread_box, patch, X_data, X_size, X_depth);\n    std::vector<double> periodic_shifts(NDIM * local_indices.size());\n\n    // Spread.\n    if (!local_indices.empty())\n    {\n        std::array<double, NDIM> x_lower_axis, x_upper_axis;\n        const int local_sz = (*std::max_element(local_indices.begin(), local_indices.end())) + 1;\n        std::vector<double> Q_data_axis(local_sz);\n        for (unsigned int axis = 0; axis < NDIM; ++axis)\n        {\n            for (unsigned int d = 0; d < NDIM; ++d)\n            {\n                x_lower_axis[d] = x_lower[d];\n                x_upper_axis[d] = x_upper[d];\n            }\n            x_lower_axis[axis] -= 0.5 * dx[axis];\n            x_upper_axis[axis] += 0.5 * dx[axis];\n            for (const auto& local_index : local_indices)\n            {\n                Q_data_axis[local_index] = Q_data[NDIM * local_index + axis];\n            }\n            spread(q_data->getPointer(axis),\n                   SideGeometry<NDIM>::toSideBox(q_data->getBox(), axis),\n                   q_data->getGhostCellWidth(),\n                   /*q_depth*/ 1,\n                   &Q_data_axis[0],\n                   /*Q_depth*/ 1,\n                   X_data,\n                   x_lower_axis.data(),\n                   x_upper_axis.data(),\n                   dx,\n                   patch_touches_lower_physical_bdry,\n                   patch_touches_upper_physical_bdry,\n                   local_indices,\n                   periodic_shifts,\n                   spread_fcn,\n                   axis);\n        }\n    }\n    return;\n}\n\nvoid\nLEInteractor::spread(Pointer<SideData<NDIM, double> > mask_data,\n                     Pointer<SideData<NDIM, double> > q_data,\n                     const double* const Q_data,\n                     const int Q_size,\n                     const int Q_depth,\n                     const double* const X_data,\n                     const int X_size,\n                     const int X_depth,\n                     const Pointer<Patch<NDIM> > patch,\n                     const Box<NDIM>& spread_box,\n                     const std::string& spread_fcn)\n{\n#if !defined(NDEBUG)\n    TBOX_ASSERT(q_data);\n    TBOX_ASSERT(patch);\n    TBOX_ASSERT(Q_depth == NDIM);\n    TBOX_ASSERT(X_depth == NDIM);\n    TBOX_ASSERT(Q_size / Q_depth == X_size / X_depth);\n    TBOX_ASSERT(q_data->getDepth() == 1);\n    TBOX_ASSERT(mask_data);\n#else\n    NULL_USE(Q_size);\n#endif\n    // Determine the patch geometry.\n    const Pointer<CartesianPatchGeometry<NDIM> > pgeom = patch->getPatchGeometry();\n    const double* const x_lower = pgeom->getXLower();\n    const double* const x_upper = pgeom->getXUpper();\n    const double* const dx = pgeom->getDx();\n    const Box<NDIM>& patch_box = patch->getBox();\n    const IntVector<NDIM>& ilower = patch_box.lower();\n\n    // Get ghost cell width info.\n    const IntVector<NDIM>& q_gcw = q_data->getGhostCellWidth();\n    const IntVector<NDIM>& mask_gcw = mask_data->getGhostCellWidth();\n    const int stencil_size = getStencilSize(spread_fcn);\n    const int min_ghosts = getMinimumGhostWidth(spread_fcn);\n    const int q_gcw_min = q_gcw.min();\n    const int mask_gcw_min = mask_gcw.min();\n    if (q_gcw_min < min_ghosts)\n    {\n        TBOX_ERROR(\"LEInteractor::interpolate(): insufficient ghost cells for Eulerian field data:\"\n                   << \"  kernel function          = \" << spread_fcn << \"\\n\"\n                   << \"  kernel stencil size      = \" << stencil_size << \"\\n\"\n                   << \"  minimum ghost cell width = \" << min_ghosts << \"\\n\"\n                   << \"  ghost cell width         = \" << q_gcw_min << \"\\n\");\n    }\n    if (mask_gcw_min < stencil_size)\n    {\n        TBOX_ERROR(\"LEInteractor::interpolate(): insufficient ghost cells for Eulerian mask data:\"\n                   << \"  kernel function          = \" << spread_fcn << \"\\n\"\n                   << \"  kernel stencil size      = \" << stencil_size << \"\\n\"\n                   << \"  minimum ghost cell width = \" << stencil_size << \"\\n\"\n                   << \"  ghost cell width         = \" << mask_gcw_min << \"\\n\");\n    }\n\n    // Determine the boundary info.\n    std::array<int, NDIM> patch_touches_lower_physical_bdry(array_zero<int, NDIM>());\n    std::array<int, NDIM> patch_touches_upper_physical_bdry(array_zero<int, NDIM>());\n    for (unsigned int axis = 0; axis < NDIM; ++axis)\n    {\n        static const int lower = 0;\n        patch_touches_lower_physical_bdry[axis] = pgeom->getTouchesRegularBoundary(axis, lower);\n        static const int upper = 1;\n        patch_touches_upper_physical_bdry[axis] = pgeom->getTouchesRegularBoundary(axis, upper);\n    }\n\n    // Generate a list of local indices which lie in the specified box and set\n    // all periodic offsets to zero.\n    std::vector<int> local_indices;\n    buildLocalIndices(local_indices, spread_box, patch, X_data, X_size, X_depth);\n    std::vector<double> periodic_shifts(NDIM * local_indices.size());\n\n    // Spread.\n    const int nindices = static_cast<int>(local_indices.size());\n    if (nindices)\n    {\n        std::array<double, NDIM> x_lower_axis, x_upper_axis;\n        IntVector<NDIM> stencil_lower, stencil_upper;\n        for (int axis = 0; axis < NDIM; ++axis)\n        {\n            Box<NDIM> data_box = SideGeometry<NDIM>::toSideBox(q_data->getBox(), axis);\n            const IntVector<NDIM> ig_lower = data_box.lower() - q_gcw;\n            const IntVector<NDIM> ig_upper = data_box.upper() + q_gcw;\n\n            for (int d = 0; d < NDIM; ++d)\n            {\n                x_lower_axis[d] = x_lower[d];\n                x_upper_axis[d] = x_upper[d];\n            }\n            x_lower_axis[axis] -= 0.5 * dx[axis];\n            x_upper_axis[axis] += 0.5 * dx[axis];\n\n            for (int k = 0; k < nindices; ++k)\n            {\n                int s = local_indices[k];\n                MLSWeight Psi;\n                const int stencil_sz = LEInteractor::getStencilSize(spread_fcn);\n                get_mls_weights(spread_fcn,\n                                &X_data[s * NDIM],\n                                &periodic_shifts[k * NDIM],\n                                dx,\n                                x_lower_axis.data(),\n                                ilower,\n                                mask_data->getArrayData(axis),\n                                stencil_lower,\n                                stencil_upper,\n                                Psi);\n                spread_data(stencil_sz,\n                            ig_lower,\n                            ig_upper,\n                            stencil_lower,\n                            stencil_upper,\n                            dx,\n                            q_data->getArrayData(axis),\n                            0,\n                            Psi,\n                            Q_data[s * Q_depth + axis]);\n            }\n        }\n    }\n    return;\n}\n\nvoid\nLEInteractor::spread(Pointer<EdgeData<NDIM, double> > q_data,\n                     const double* const Q_data,\n                     const int /*Q_size*/,\n                     const int Q_depth,\n                     const double* const X_data,\n                     const int X_size,\n                     const int X_depth,\n                     const Pointer<Patch<NDIM> > patch,\n                     const Box<NDIM>& spread_box,\n                     const std::string& spread_fcn)\n{\n    if (NDIM != 3 || Q_depth != NDIM || q_data->getDepth() != 1)\n    {\n        TBOX_ERROR(\"LEInteractor::spread():\\n\"\n                   << \"  edge-centered interpolation requires 3D vector-valued data.\\n\");\n    }\n#if !defined(NDEBUG)\n    TBOX_ASSERT(q_data);\n    TBOX_ASSERT(patch);\n    TBOX_ASSERT(Q_depth == NDIM);\n    TBOX_ASSERT(X_depth == NDIM);\n#endif\n    // Determine the patch geometry.\n    const Pointer<CartesianPatchGeometry<NDIM> > pgeom = patch->getPatchGeometry();\n    const double* const x_lower = pgeom->getXLower();\n    const double* const x_upper = pgeom->getXUpper();\n    const double* const dx = pgeom->getDx();\n    std::array<int, NDIM> patch_touches_lower_physical_bdry(array_zero<int, NDIM>());\n    std::array<int, NDIM> patch_touches_upper_physical_bdry(array_zero<int, NDIM>());\n    for (unsigned int axis = 0; axis < NDIM; ++axis)\n    {\n        static const int lower = 0;\n        patch_touches_lower_physical_bdry[axis] = pgeom->getTouchesRegularBoundary(axis, lower);\n        static const int upper = 1;\n        patch_touches_upper_physical_bdry[axis] = pgeom->getTouchesRegularBoundary(axis, upper);\n    }\n\n    // Generate a list of local indices which lie in the specified box and set\n    // all periodic offsets to zero.\n    std::vector<int> local_indices;\n    buildLocalIndices(local_indices, spread_box, patch, X_data, X_size, X_depth);\n    std::vector<double> periodic_shifts(NDIM * local_indices.size());\n\n    // Spread.\n    if (!local_indices.empty())\n    {\n        std::array<double, NDIM> x_lower_axis, x_upper_axis;\n        const int local_sz = (*std::max_element(local_indices.begin(), local_indices.end())) + 1;\n        std::vector<double> Q_data_axis(local_sz);\n        for (unsigned int axis = 0; axis < NDIM; ++axis)\n        {\n            for (unsigned int d = 0; d < NDIM; ++d)\n            {\n                x_lower_axis[d] = x_lower[d];\n                x_upper_axis[d] = x_upper[d];\n                if (d != axis)\n                {\n                    x_lower_axis[axis] -= 0.5 * dx[axis];\n                    x_upper_axis[axis] += 0.5 * dx[axis];\n                }\n            }\n            for (const auto& local_index : local_indices)\n            {\n                Q_data_axis[local_index] = Q_data[NDIM * local_index + axis];\n            }\n            spread(q_data->getPointer(axis),\n                   EdgeGeometry<NDIM>::toEdgeBox(q_data->getBox(), axis),\n                   q_data->getGhostCellWidth(),\n                   /*q_depth*/ 1,\n                   &Q_data_axis[0],\n                   /*Q_depth*/ 1,\n                   X_data,\n                   x_lower_axis.data(),\n                   x_upper_axis.data(),\n                   dx,\n                   patch_touches_lower_physical_bdry,\n                   patch_touches_upper_physical_bdry,\n                   local_indices,\n                   periodic_shifts,\n                   spread_fcn,\n                   axis);\n        }\n    }\n    return;\n}\n\n/////////////////////////////// PROTECTED ////////////////////////////////////\n\n/////////////////////////////// PRIVATE //////////////////////////////////////\n\nvoid\nLEInteractor::interpolate(double* const Q_data,\n                          const int Q_depth,\n                          const double* const X_data,\n                          const double* const q_data,\n                          const Box<NDIM>& q_data_box,\n                          const IntVector<NDIM>& q_gcw,\n                          const int q_depth,\n                          const double* const x_lower,\n                          const double* const x_upper,\n                          const double* const dx,\n                          const std::array<int, NDIM>& /*patch_touches_lower_physical_bdry*/,\n                          const std::array<int, NDIM>& /*patch_touches_upper_physical_bdry*/,\n                          const std::vector<int>& local_indices,\n                          const std::vector<double>& periodic_shifts,\n                          const std::string& interp_fcn,\n                          const int axis)\n{\n    const int stencil_size = getStencilSize(interp_fcn);\n    const int min_ghosts = getMinimumGhostWidth(interp_fcn);\n    const int q_gcw_min = q_gcw.min();\n    if (q_gcw_min < min_ghosts)\n    {\n        TBOX_ERROR(\"LEInteractor::interpolate(): insufficient ghost cells:\"\n                   << \"  kernel function          = \" << interp_fcn << \"\\n\"\n                   << \"  kernel stencil size      = \" << stencil_size << \"\\n\"\n                   << \"  minimum ghost cell width = \" << min_ghosts << \"\\n\"\n                   << \"  ghost cell width         = \" << q_gcw_min << \"\\n\");\n    }\n    if (local_indices.empty()) return;\n    const int local_indices_size = static_cast<int>(local_indices.size());\n    const IntVector<NDIM>& ilower = q_data_box.lower();\n    const IntVector<NDIM>& iupper = q_data_box.upper();\n    if (interp_fcn == \"PIECEWISE_CONSTANT\")\n    {\n        LAGRANGIAN_PIECEWISE_CONSTANT_INTERP_FC(dx,\n                                                x_lower,\n                                                x_upper,\n                                                q_depth,\n#if (NDIM == 2)\n                                                ilower(0),\n                                                iupper(0),\n                                                ilower(1),\n                                                iupper(1),\n                                                q_gcw(0),\n                                                q_gcw(1),\n#endif\n#if (NDIM == 3)\n                                                ilower(0),\n                                                iupper(0),\n                                                ilower(1),\n                                                iupper(1),\n                                                ilower(2),\n                                                iupper(2),\n                                                q_gcw(0),\n                                                q_gcw(1),\n                                                q_gcw(2),\n#endif\n                                                q_data,\n                                                &local_indices[0],\n                                                &periodic_shifts[0],\n                                                local_indices_size,\n                                                X_data,\n                                                Q_data);\n    }\n    else if (interp_fcn == \"DISCONTINUOUS_LINEAR\")\n    {\n        LAGRANGIAN_DISCONTINUOUS_LINEAR_INTERP_FC(dx,\n                                                  x_lower,\n                                                  x_upper,\n                                                  q_depth,\n                                                  axis,\n#if (NDIM == 2)\n                                                  ilower(0),\n                                                  iupper(0),\n                                                  ilower(1),\n                                                  iupper(1),\n                                                  q_gcw(0),\n                                                  q_gcw(1),\n#endif\n#if (NDIM == 3)\n                                                  ilower(0),\n                                                  iupper(0),\n                                                  ilower(1),\n                                                  iupper(1),\n                                                  ilower(2),\n                                                  iupper(2),\n                                                  q_gcw(0),\n                                                  q_gcw(1),\n                                                  q_gcw(2),\n#endif\n                                                  q_data,\n                                                  &local_indices[0],\n                                                  &periodic_shifts[0],\n                                                  local_indices_size,\n                                                  X_data,\n                                                  Q_data);\n    }\n    else if (interp_fcn == \"PIECEWISE_LINEAR\")\n    {\n        LAGRANGIAN_PIECEWISE_LINEAR_INTERP_FC(dx,\n                                              x_lower,\n                                              x_upper,\n                                              q_depth,\n#if (NDIM == 2)\n                                              ilower(0),\n                                              iupper(0),\n                                              ilower(1),\n                                              iupper(1),\n                                              q_gcw(0),\n                                              q_gcw(1),\n#endif\n#if (NDIM == 3)\n                                              ilower(0),\n                                              iupper(0),\n                                              ilower(1),\n                                              iupper(1),\n                                              ilower(2),\n                                              iupper(2),\n                                              q_gcw(0),\n                                              q_gcw(1),\n                                              q_gcw(2),\n#endif\n                                              q_data,\n                                              &local_indices[0],\n                                              &periodic_shifts[0],\n                                              local_indices_size,\n                                              X_data,\n                                              Q_data);\n    }\n    else if (interp_fcn == \"PIECEWISE_CUBIC\")\n    {\n        LAGRANGIAN_PIECEWISE_CUBIC_INTERP_FC(dx,\n                                             x_lower,\n                                             x_upper,\n                                             q_depth,\n#if (NDIM == 2)\n                                             ilower(0),\n                                             iupper(0),\n                                             ilower(1),\n                                             iupper(1),\n                                             q_gcw(0),\n                                             q_gcw(1),\n#endif\n#if (NDIM == 3)\n                                             ilower(0),\n                                             iupper(0),\n                                             ilower(1),\n                                             iupper(1),\n                                             ilower(2),\n                                             iupper(2),\n                                             q_gcw(0),\n                                             q_gcw(1),\n                                             q_gcw(2),\n#endif\n                                             q_data,\n                                             &local_indices[0],\n                                             &periodic_shifts[0],\n                                             local_indices_size,\n                                             X_data,\n                                             Q_data);\n    }\n    else if (interp_fcn == \"IB_3\")\n    {\n        LAGRANGIAN_IB_3_INTERP_FC(dx,\n                                  x_lower,\n                                  x_upper,\n                                  q_depth,\n#if (NDIM == 2)\n                                  ilower(0),\n                                  iupper(0),\n                                  ilower(1),\n                                  iupper(1),\n                                  q_gcw(0),\n                                  q_gcw(1),\n#endif\n#if (NDIM == 3)\n                                  ilower(0),\n                                  iupper(0),\n                                  ilower(1),\n                                  iupper(1),\n                                  ilower(2),\n                                  iupper(2),\n                                  q_gcw(0),\n                                  q_gcw(1),\n                                  q_gcw(2),\n#endif\n                                  q_data,\n                                  &local_indices[0],\n                                  &periodic_shifts[0],\n                                  local_indices_size,\n                                  X_data,\n                                  Q_data);\n    }\n    else if (interp_fcn == \"IB_4\")\n    {\n        LAGRANGIAN_IB_4_INTERP_FC(dx,\n                                  x_lower,\n                                  x_upper,\n                                  q_depth,\n#if (NDIM == 2)\n                                  ilower(0),\n                                  iupper(0),\n                                  ilower(1),\n                                  iupper(1),\n                                  q_gcw(0),\n                                  q_gcw(1),\n#endif\n#if (NDIM == 3)\n                                  ilower(0),\n                                  iupper(0),\n                                  ilower(1),\n                                  iupper(1),\n                                  ilower(2),\n                                  iupper(2),\n                                  q_gcw(0),\n                                  q_gcw(1),\n                                  q_gcw(2),\n#endif\n                                  q_data,\n                                  &local_indices[0],\n                                  &periodic_shifts[0],\n                                  local_indices_size,\n                                  X_data,\n                                  Q_data);\n    }\n    else if (interp_fcn == \"IB_4_W8\")\n    {\n        LAGRANGIAN_IB_4_W8_INTERP_FC(dx,\n                                     x_lower,\n                                     x_upper,\n                                     q_depth,\n#if (NDIM == 2)\n                                     ilower(0),\n                                     iupper(0),\n                                     ilower(1),\n                                     iupper(1),\n                                     q_gcw(0),\n                                     q_gcw(1),\n#endif\n#if (NDIM == 3)\n                                     ilower(0),\n                                     iupper(0),\n                                     ilower(1),\n                                     iupper(1),\n                                     ilower(2),\n                                     iupper(2),\n                                     q_gcw(0),\n                                     q_gcw(1),\n                                     q_gcw(2),\n#endif\n                                     q_data,\n                                     &local_indices[0],\n                                     &periodic_shifts[0],\n                                     local_indices_size,\n                                     X_data,\n                                     Q_data);\n    }\n    else if (interp_fcn == \"IB_5\")\n    {\n        LAGRANGIAN_IB_5_INTERP_FC(dx,\n                                  x_lower,\n                                  x_upper,\n                                  q_depth,\n#if (NDIM == 2)\n                                  ilower(0),\n                                  iupper(0),\n                                  ilower(1),\n                                  iupper(1),\n                                  q_gcw(0),\n                                  q_gcw(1),\n#endif\n#if (NDIM == 3)\n                                  ilower(0),\n                                  iupper(0),\n                                  ilower(1),\n                                  iupper(1),\n                                  ilower(2),\n                                  iupper(2),\n                                  q_gcw(0),\n                                  q_gcw(1),\n                                  q_gcw(2),\n#endif\n                                  q_data,\n                                  &local_indices[0],\n                                  &periodic_shifts[0],\n                                  local_indices_size,\n                                  X_data,\n                                  Q_data);\n    }\n    else if (interp_fcn == \"IB_6\")\n    {\n        LAGRANGIAN_IB_6_INTERP_FC(dx,\n                                  x_lower,\n                                  x_upper,\n                                  q_depth,\n#if (NDIM == 2)\n                                  ilower(0),\n                                  iupper(0),\n                                  ilower(1),\n                                  iupper(1),\n                                  q_gcw(0),\n                                  q_gcw(1),\n#endif\n#if (NDIM == 3)\n                                  ilower(0),\n                                  iupper(0),\n                                  ilower(1),\n                                  iupper(1),\n                                  ilower(2),\n                                  iupper(2),\n                                  q_gcw(0),\n                                  q_gcw(1),\n                                  q_gcw(2),\n#endif\n                                  q_data,\n                                  &local_indices[0],\n                                  &periodic_shifts[0],\n                                  local_indices_size,\n                                  X_data,\n                                  Q_data);\n    }\n    else if (interp_fcn == \"BSPLINE_3\")\n    {\n        LAGRANGIAN_BSPLINE_3_INTERP_FC(dx,\n                                       x_lower,\n                                       x_upper,\n                                       q_depth,\n#if (NDIM == 2)\n                                       ilower(0),\n                                       iupper(0),\n                                       ilower(1),\n                                       iupper(1),\n                                       q_gcw(0),\n                                       q_gcw(1),\n#endif\n#if (NDIM == 3)\n                                       ilower(0),\n                                       iupper(0),\n                                       ilower(1),\n                                       iupper(1),\n                                       ilower(2),\n                                       iupper(2),\n                                       q_gcw(0),\n                                       q_gcw(1),\n                                       q_gcw(2),\n#endif\n                                       q_data,\n                                       &local_indices[0],\n                                       &periodic_shifts[0],\n                                       local_indices_size,\n                                       X_data,\n                                       Q_data);\n    }\n    else if (interp_fcn == \"BSPLINE_4\")\n    {\n        LAGRANGIAN_BSPLINE_4_INTERP_FC(dx,\n                                       x_lower,\n                                       x_upper,\n                                       q_depth,\n#if (NDIM == 2)\n                                       ilower(0),\n                                       iupper(0),\n                                       ilower(1),\n                                       iupper(1),\n                                       q_gcw(0),\n                                       q_gcw(1),\n#endif\n#if (NDIM == 3)\n                                       ilower(0),\n                                       iupper(0),\n                                       ilower(1),\n                                       iupper(1),\n                                       ilower(2),\n                                       iupper(2),\n                                       q_gcw(0),\n                                       q_gcw(1),\n                                       q_gcw(2),\n#endif\n                                       q_data,\n                                       &local_indices[0],\n                                       &periodic_shifts[0],\n                                       local_indices_size,\n                                       X_data,\n                                       Q_data);\n    }\n    else if (interp_fcn == \"BSPLINE_5\")\n    {\n        LAGRANGIAN_BSPLINE_5_INTERP_FC(dx,\n                                       x_lower,\n                                       x_upper,\n                                       q_depth,\n#if (NDIM == 2)\n                                       ilower(0),\n                                       iupper(0),\n                                       ilower(1),\n                                       iupper(1),\n                                       q_gcw(0),\n                                       q_gcw(1),\n#endif\n#if (NDIM == 3)\n                                       ilower(0),\n                                       iupper(0),\n                                       ilower(1),\n                                       iupper(1),\n                                       ilower(2),\n                                       iupper(2),\n                                       q_gcw(0),\n                                       q_gcw(1),\n                                       q_gcw(2),\n#endif\n                                       q_data,\n                                       &local_indices[0],\n                                       &periodic_shifts[0],\n                                       local_indices_size,\n                                       X_data,\n                                       Q_data);\n    }\n    else if (interp_fcn == \"BSPLINE_6\")\n    {\n        LAGRANGIAN_BSPLINE_6_INTERP_FC(dx,\n                                       x_lower,\n                                       x_upper,\n                                       q_depth,\n#if (NDIM == 2)\n                                       ilower(0),\n                                       iupper(0),\n                                       ilower(1),\n                                       iupper(1),\n                                       q_gcw(0),\n                                       q_gcw(1),\n#endif\n#if (NDIM == 3)\n                                       ilower(0),\n                                       iupper(0),\n                                       ilower(1),\n                                       iupper(1),\n                                       ilower(2),\n                                       iupper(2),\n                                       q_gcw(0),\n                                       q_gcw(1),\n                                       q_gcw(2),\n#endif\n                                       q_data,\n                                       &local_indices[0],\n                                       &periodic_shifts[0],\n                                       local_indices_size,\n                                       X_data,\n                                       Q_data);\n    }\n    else if (interp_fcn == \"USER_DEFINED\")\n    {\n        userDefinedInterpolate(Q_data,\n                               Q_depth,\n                               X_data,\n                               q_data,\n                               q_data_box,\n                               q_gcw,\n                               q_depth,\n                               x_lower,\n                               x_upper,\n                               dx,\n                               &local_indices[0],\n                               &periodic_shifts[0],\n                               local_indices_size);\n    }\n    else\n    {\n        TBOX_ERROR(\"LEInteractor::interpolate()\\n\"\n                   << \"  Unknown interpolation kernel function \" << interp_fcn << std::endl);\n    }\n    return;\n}\n\nvoid\nLEInteractor::spread(double* const q_data,\n                     const Box<NDIM>& q_data_box,\n                     const IntVector<NDIM>& q_gcw,\n                     const int q_depth,\n                     const double* const Q_data,\n                     const int Q_depth,\n                     const double* const X_data,\n                     const double* const x_lower,\n                     const double* const x_upper,\n                     const double* const dx,\n                     const std::array<int, NDIM>& patch_touches_lower_physical_bdry,\n                     const std::array<int, NDIM>& patch_touches_upper_physical_bdry,\n                     const std::vector<int>& local_indices,\n                     const std::vector<double>& periodic_shifts,\n                     const std::string& spread_fcn,\n                     const int axis)\n{\n    const int stencil_size = getStencilSize(spread_fcn);\n    const int min_ghosts = getMinimumGhostWidth(spread_fcn);\n    const int q_gcw_min = q_gcw.min();\n    bool patch_touches_physical_bdry = false;\n    for (unsigned int d = 0; d < NDIM; ++d)\n    {\n        patch_touches_physical_bdry = patch_touches_physical_bdry || patch_touches_lower_physical_bdry[d];\n        patch_touches_physical_bdry = patch_touches_physical_bdry || patch_touches_upper_physical_bdry[d];\n    }\n    if (patch_touches_physical_bdry && q_gcw_min < min_ghosts)\n    {\n        TBOX_ERROR(\"LEInteractor::spread(): insufficient ghost cells at physical boundary:\"\n                   << \"  kernel function          = \" << spread_fcn << \"\\n\"\n                   << \"  kernel stencil size      = \" << stencil_size << \"\\n\"\n                   << \"  minimum ghost cell width = \" << min_ghosts << \"\\n\"\n                   << \"  ghost cell width         = \" << q_gcw_min << \"\\n\");\n    }\n    if (local_indices.empty()) return;\n    const int local_indices_size = static_cast<int>(local_indices.size());\n    const IntVector<NDIM>& ilower = q_data_box.lower();\n    const IntVector<NDIM>& iupper = q_data_box.upper();\n    if (spread_fcn == \"PIECEWISE_CONSTANT\")\n    {\n        LAGRANGIAN_PIECEWISE_CONSTANT_SPREAD_FC(dx,\n                                                x_lower,\n                                                x_upper,\n                                                q_depth,\n                                                &local_indices[0],\n                                                &periodic_shifts[0],\n                                                local_indices_size,\n                                                X_data,\n                                                Q_data,\n#if (NDIM == 2)\n                                                ilower(0),\n                                                iupper(0),\n                                                ilower(1),\n                                                iupper(1),\n                                                q_gcw(0),\n                                                q_gcw(1),\n#endif\n#if (NDIM == 3)\n                                                ilower(0),\n                                                iupper(0),\n                                                ilower(1),\n                                                iupper(1),\n                                                ilower(2),\n                                                iupper(2),\n                                                q_gcw(0),\n                                                q_gcw(1),\n                                                q_gcw(2),\n#endif\n                                                q_data);\n    }\n    else if (spread_fcn == \"DISCONTINUOUS_LINEAR\")\n    {\n        LAGRANGIAN_DISCONTINUOUS_LINEAR_SPREAD_FC(dx,\n                                                  x_lower,\n                                                  x_upper,\n                                                  q_depth,\n                                                  axis,\n                                                  &local_indices[0],\n                                                  &periodic_shifts[0],\n                                                  local_indices_size,\n                                                  X_data,\n                                                  Q_data,\n#if (NDIM == 2)\n                                                  ilower(0),\n                                                  iupper(0),\n                                                  ilower(1),\n                                                  iupper(1),\n                                                  q_gcw(0),\n                                                  q_gcw(1),\n#endif\n#if (NDIM == 3)\n                                                  ilower(0),\n                                                  iupper(0),\n                                                  ilower(1),\n                                                  iupper(1),\n                                                  ilower(2),\n                                                  iupper(2),\n                                                  q_gcw(0),\n                                                  q_gcw(1),\n                                                  q_gcw(2),\n#endif\n                                                  q_data);\n    }\n    else if (spread_fcn == \"PIECEWISE_LINEAR\")\n    {\n        LAGRANGIAN_PIECEWISE_LINEAR_SPREAD_FC(dx,\n                                              x_lower,\n                                              x_upper,\n                                              q_depth,\n                                              &local_indices[0],\n                                              &periodic_shifts[0],\n                                              local_indices_size,\n                                              X_data,\n                                              Q_data,\n#if (NDIM == 2)\n                                              ilower(0),\n                                              iupper(0),\n                                              ilower(1),\n                                              iupper(1),\n                                              q_gcw(0),\n                                              q_gcw(1),\n#endif\n#if (NDIM == 3)\n                                              ilower(0),\n                                              iupper(0),\n                                              ilower(1),\n                                              iupper(1),\n                                              ilower(2),\n                                              iupper(2),\n                                              q_gcw(0),\n                                              q_gcw(1),\n                                              q_gcw(2),\n#endif\n                                              q_data);\n    }\n    else if (spread_fcn == \"PIECEWISE_CUBIC\")\n    {\n        LAGRANGIAN_PIECEWISE_CUBIC_SPREAD_FC(dx,\n                                             x_lower,\n                                             x_upper,\n                                             q_depth,\n                                             &local_indices[0],\n                                             &periodic_shifts[0],\n                                             local_indices_size,\n                                             X_data,\n                                             Q_data,\n#if (NDIM == 2)\n                                             ilower(0),\n                                             iupper(0),\n                                             ilower(1),\n                                             iupper(1),\n                                             q_gcw(0),\n                                             q_gcw(1),\n#endif\n#if (NDIM == 3)\n                                             ilower(0),\n                                             iupper(0),\n                                             ilower(1),\n                                             iupper(1),\n                                             ilower(2),\n                                             iupper(2),\n                                             q_gcw(0),\n                                             q_gcw(1),\n                                             q_gcw(2),\n#endif\n                                             q_data);\n    }\n    else if (spread_fcn == \"IB_3\")\n    {\n        LAGRANGIAN_IB_3_SPREAD_FC(dx,\n                                  x_lower,\n                                  x_upper,\n                                  q_depth,\n                                  &local_indices[0],\n                                  &periodic_shifts[0],\n                                  local_indices_size,\n                                  X_data,\n                                  Q_data,\n#if (NDIM == 2)\n                                  ilower(0),\n                                  iupper(0),\n                                  ilower(1),\n                                  iupper(1),\n                                  q_gcw(0),\n                                  q_gcw(1),\n#endif\n#if (NDIM == 3)\n                                  ilower(0),\n                                  iupper(0),\n                                  ilower(1),\n                                  iupper(1),\n                                  ilower(2),\n                                  iupper(2),\n                                  q_gcw(0),\n                                  q_gcw(1),\n                                  q_gcw(2),\n#endif\n                                  q_data);\n    }\n    else if (spread_fcn == \"IB_4\")\n    {\n        LAGRANGIAN_IB_4_SPREAD_FC(dx,\n                                  x_lower,\n                                  x_upper,\n                                  q_depth,\n                                  &local_indices[0],\n                                  &periodic_shifts[0],\n                                  local_indices_size,\n                                  X_data,\n                                  Q_data,\n#if (NDIM == 2)\n                                  ilower(0),\n                                  iupper(0),\n                                  ilower(1),\n                                  iupper(1),\n                                  q_gcw(0),\n                                  q_gcw(1),\n#endif\n#if (NDIM == 3)\n                                  ilower(0),\n                                  iupper(0),\n                                  ilower(1),\n                                  iupper(1),\n                                  ilower(2),\n                                  iupper(2),\n                                  q_gcw(0),\n                                  q_gcw(1),\n                                  q_gcw(2),\n#endif\n                                  q_data);\n    }\n    else if (spread_fcn == \"IB_4_W8\")\n    {\n        LAGRANGIAN_IB_4_W8_SPREAD_FC(dx,\n                                     x_lower,\n                                     x_upper,\n                                     q_depth,\n                                     &local_indices[0],\n                                     &periodic_shifts[0],\n                                     local_indices_size,\n                                     X_data,\n                                     Q_data,\n#if (NDIM == 2)\n                                     ilower(0),\n                                     iupper(0),\n                                     ilower(1),\n                                     iupper(1),\n                                     q_gcw(0),\n                                     q_gcw(1),\n#endif\n#if (NDIM == 3)\n                                     ilower(0),\n                                     iupper(0),\n                                     ilower(1),\n                                     iupper(1),\n                                     ilower(2),\n                                     iupper(2),\n                                     q_gcw(0),\n                                     q_gcw(1),\n                                     q_gcw(2),\n#endif\n                                     q_data);\n    }\n    else if (spread_fcn == \"IB_5\")\n    {\n        LAGRANGIAN_IB_5_SPREAD_FC(dx,\n                                  x_lower,\n                                  x_upper,\n                                  q_depth,\n                                  &local_indices[0],\n                                  &periodic_shifts[0],\n                                  local_indices_size,\n                                  X_data,\n                                  Q_data,\n#if (NDIM == 2)\n                                  ilower(0),\n                                  iupper(0),\n                                  ilower(1),\n                                  iupper(1),\n                                  q_gcw(0),\n                                  q_gcw(1),\n#endif\n#if (NDIM == 3)\n                                  ilower(0),\n                                  iupper(0),\n                                  ilower(1),\n                                  iupper(1),\n                                  ilower(2),\n                                  iupper(2),\n                                  q_gcw(0),\n                                  q_gcw(1),\n                                  q_gcw(2),\n#endif\n                                  q_data);\n    }\n    else if (spread_fcn == \"IB_6\")\n    {\n        LAGRANGIAN_IB_6_SPREAD_FC(dx,\n                                  x_lower,\n                                  x_upper,\n                                  q_depth,\n                                  &local_indices[0],\n                                  &periodic_shifts[0],\n                                  local_indices_size,\n                                  X_data,\n                                  Q_data,\n#if (NDIM == 2)\n                                  ilower(0),\n                                  iupper(0),\n                                  ilower(1),\n                                  iupper(1),\n                                  q_gcw(0),\n                                  q_gcw(1),\n#endif\n#if (NDIM == 3)\n                                  ilower(0),\n                                  iupper(0),\n                                  ilower(1),\n                                  iupper(1),\n                                  ilower(2),\n                                  iupper(2),\n                                  q_gcw(0),\n                                  q_gcw(1),\n                                  q_gcw(2),\n#endif\n                                  q_data);\n    }\n    else if (spread_fcn == \"BSPLINE_3\")\n    {\n        LAGRANGIAN_BSPLINE_3_SPREAD_FC(dx,\n                                       x_lower,\n                                       x_upper,\n                                       q_depth,\n                                       &local_indices[0],\n                                       &periodic_shifts[0],\n                                       local_indices_size,\n                                       X_data,\n                                       Q_data,\n#if (NDIM == 2)\n                                       ilower(0),\n                                       iupper(0),\n                                       ilower(1),\n                                       iupper(1),\n                                       q_gcw(0),\n                                       q_gcw(1),\n#endif\n#if (NDIM == 3)\n                                       ilower(0),\n                                       iupper(0),\n                                       ilower(1),\n                                       iupper(1),\n                                       ilower(2),\n                                       iupper(2),\n                                       q_gcw(0),\n                                       q_gcw(1),\n                                       q_gcw(2),\n#endif\n                                       q_data);\n    }\n    else if (spread_fcn == \"BSPLINE_4\")\n    {\n        LAGRANGIAN_BSPLINE_4_SPREAD_FC(dx,\n                                       x_lower,\n                                       x_upper,\n                                       q_depth,\n                                       &local_indices[0],\n                                       &periodic_shifts[0],\n                                       local_indices_size,\n                                       X_data,\n                                       Q_data,\n#if (NDIM == 2)\n                                       ilower(0),\n                                       iupper(0),\n                                       ilower(1),\n                                       iupper(1),\n                                       q_gcw(0),\n                                       q_gcw(1),\n#endif\n#if (NDIM == 3)\n                                       ilower(0),\n                                       iupper(0),\n                                       ilower(1),\n                                       iupper(1),\n                                       ilower(2),\n                                       iupper(2),\n                                       q_gcw(0),\n                                       q_gcw(1),\n                                       q_gcw(2),\n#endif\n                                       q_data);\n    }\n    else if (spread_fcn == \"BSPLINE_5\")\n    {\n        LAGRANGIAN_BSPLINE_5_SPREAD_FC(dx,\n                                       x_lower,\n                                       x_upper,\n                                       q_depth,\n                                       &local_indices[0],\n                                       &periodic_shifts[0],\n                                       local_indices_size,\n                                       X_data,\n                                       Q_data,\n#if (NDIM == 2)\n                                       ilower(0),\n                                       iupper(0),\n                                       ilower(1),\n                                       iupper(1),\n                                       q_gcw(0),\n                                       q_gcw(1),\n#endif\n#if (NDIM == 3)\n                                       ilower(0),\n                                       iupper(0),\n                                       ilower(1),\n                                       iupper(1),\n                                       ilower(2),\n                                       iupper(2),\n                                       q_gcw(0),\n                                       q_gcw(1),\n                                       q_gcw(2),\n#endif\n                                       q_data);\n    }\n    else if (spread_fcn == \"BSPLINE_6\")\n    {\n        LAGRANGIAN_BSPLINE_6_SPREAD_FC(dx,\n                                       x_lower,\n                                       x_upper,\n                                       q_depth,\n                                       &local_indices[0],\n                                       &periodic_shifts[0],\n                                       local_indices_size,\n                                       X_data,\n                                       Q_data,\n#if (NDIM == 2)\n                                       ilower(0),\n                                       iupper(0),\n                                       ilower(1),\n                                       iupper(1),\n                                       q_gcw(0),\n                                       q_gcw(1),\n#endif\n#if (NDIM == 3)\n                                       ilower(0),\n                                       iupper(0),\n                                       ilower(1),\n                                       iupper(1),\n                                       ilower(2),\n                                       iupper(2),\n                                       q_gcw(0),\n                                       q_gcw(1),\n                                       q_gcw(2),\n#endif\n                                       q_data);\n    }\n    else if (spread_fcn == \"USER_DEFINED\")\n    {\n        userDefinedSpread(q_data,\n                          q_data_box,\n                          q_gcw,\n                          q_depth,\n                          x_lower,\n                          x_upper,\n                          dx,\n                          Q_data,\n                          Q_depth,\n                          X_data,\n                          &local_indices[0],\n                          &periodic_shifts[0],\n                          local_indices_size);\n    }\n    else\n    {\n        TBOX_ERROR(\"LEInteractor::spread()\\n\"\n                   << \"  Unknown spreading kernel function \" << spread_fcn << std::endl);\n    }\n    return;\n}\n\ntemplate <class T>\nvoid\nLEInteractor::buildLocalIndices(std::vector<int>& local_indices,\n                                std::vector<double>& periodic_shifts,\n                                const Box<NDIM>& box,\n                                const Pointer<Patch<NDIM> > patch,\n                                const IntVector<NDIM>& periodic_shift,\n                                const Pointer<LIndexSetData<T> > idx_data)\n{\n    local_indices.clear();\n    periodic_shifts.clear();\n    const size_t upper_bound = idx_data->getLocalPETScIndices().size();\n    if (upper_bound == 0) return;\n    local_indices.reserve(upper_bound);\n    periodic_shifts.reserve(NDIM * upper_bound);\n\n    const Box<NDIM>& patch_box = patch->getBox();\n    const hier::Index<NDIM>& ilower = patch_box.lower();\n    const hier::Index<NDIM>& iupper = patch_box.upper();\n    const Box<NDIM>& ghost_box = idx_data->getGhostBox();\n\n    const Pointer<CartesianPatchGeometry<NDIM> > pgeom = patch->getPatchGeometry();\n    const double* const dx = pgeom->getDx();\n    std::array<bool, NDIM> patch_touches_lower_periodic_bdry, patch_touches_upper_periodic_bdry;\n    for (unsigned int axis = 0; axis < NDIM; ++axis)\n    {\n        patch_touches_lower_periodic_bdry[axis] = pgeom->getTouchesPeriodicBoundary(axis, 0);\n        patch_touches_upper_periodic_bdry[axis] = pgeom->getTouchesPeriodicBoundary(axis, 1);\n    }\n\n    if (box == patch_box)\n    {\n        local_indices = idx_data->getInteriorLocalPETScIndices();\n        periodic_shifts = idx_data->getInteriorPeriodicShifts();\n    }\n    else if (box == ghost_box)\n    {\n        local_indices = idx_data->getLocalPETScIndices();\n        periodic_shifts = idx_data->getPeriodicShifts();\n    }\n    else\n    {\n        for (typename LIndexSetData<T>::SetIterator it(*idx_data); it; it++)\n        {\n            const hier::Index<NDIM>& i = it.getIndex();\n            if (!box.contains(i)) continue;\n\n            std::array<int, NDIM> offset;\n            for (unsigned int d = 0; d < NDIM; ++d)\n            {\n                if (patch_touches_lower_periodic_bdry[d] && i(d) < ilower(d))\n                {\n                    offset[d] = -periodic_shift(d); // X is ABOVE the top    of the patch --- need\n                                                    // to shift DOWN\n                }\n                else if (patch_touches_upper_periodic_bdry[d] && i(d) > iupper(d))\n                {\n                    offset[d] = +periodic_shift(d); // X is BELOW the bottom of the patch ---\n                                                    // need to shift UP\n                }\n                else\n                {\n                    offset[d] = 0;\n                }\n            }\n            const LSet<T>& idx_set = it.getItem();\n            for (auto n = idx_set.begin(); n != idx_set.end(); ++n)\n            {\n                const typename LSet<T>::value_type& idx = *n;\n                local_indices.push_back(idx->getLocalPETScIndex());\n                for (unsigned int d = 0; d < NDIM; ++d)\n                {\n                    periodic_shifts.push_back(static_cast<double>(offset[d]) * dx[d]);\n                }\n            }\n        }\n    }\n    return;\n}\n\nvoid\nLEInteractor::buildLocalIndices(std::vector<int>& local_indices,\n                                const Box<NDIM>& box,\n                                const Pointer<Patch<NDIM> > patch,\n                                const double* const X_data,\n                                const int X_size,\n                                const int X_depth)\n{\n    local_indices.clear();\n    const int upper_bound = X_size / X_depth;\n    if (upper_bound == 0) return;\n\n    const Box<NDIM>& patch_box = patch->getBox();\n    const Pointer<CartesianPatchGeometry<NDIM> > patch_geom = patch->getPatchGeometry();\n    local_indices.reserve(upper_bound);\n    for (int k = 0; k < X_size / X_depth; ++k)\n    {\n        const double* const X = &X_data[NDIM * k];\n        const hier::Index<NDIM> i = IndexUtilities::getCellIndex(X, patch_geom, patch_box);\n        if (box.contains(i)) local_indices.push_back(k);\n    }\n    return;\n}\n\nvoid\nLEInteractor::userDefinedInterpolate(double* Q,\n                                     const int Q_depth,\n                                     const double* const X,\n                                     const double* const q,\n                                     const Box<NDIM>& q_data_box,\n                                     const int* const q_gcw,\n                                     const int q_depth,\n                                     const double* const x_lower,\n                                     const double* const /*x_upper*/,\n                                     const double* const dx,\n                                     const int* const local_indices,\n                                     const double* const X_shift,\n                                     const int num_local_indices)\n{\n    const int* const ilower = q_data_box.lower();\n    const int* const iupper = q_data_box.upper();\n    using range = boost::multi_array_types::extent_range;\n    boost::const_multi_array_ref<double, NDIM + 1> q_data(\n        q,\n        (boost::extents[range(ilower[0] - q_gcw[0], iupper[0] + q_gcw[0] + 1)]\n                       [range(ilower[1] - q_gcw[1], iupper[1] + q_gcw[1] + 1)]\n#if (NDIM == 3)\n                       [range(ilower[2] - q_gcw[2], iupper[2] + q_gcw[2] + 1)]\n#endif\n                       [range(0, q_depth)]),\n        boost::fortran_storage_order());\n    std::array<double, NDIM> X_cell;\n    std::array<int, NDIM> stencil_center, stencil_lower, stencil_upper;\n    for (int l = 0; l < num_local_indices; ++l)\n    {\n        const int s = local_indices[l];\n\n        // Determine the Cartesian cell in which X(s) is located.\n        for (unsigned int d = 0; d < NDIM; ++d)\n        {\n            stencil_center[d] =\n                static_cast<int>(std::floor((X[d + s * NDIM] + X_shift[d + l * NDIM] - x_lower[d]) / dx[d])) +\n                ilower[d];\n            X_cell[d] = x_lower[d] + (static_cast<double>(stencil_center[d] - ilower[d]) + 0.5) * dx[d];\n        }\n\n        // Determine the interpolation stencil corresponding to the position of\n        // X(s) within the cell.\n        if (s_kernel_fcn_stencil_size % 2 == 0)\n        {\n            for (unsigned int d = 0; d < NDIM; ++d)\n            {\n                if (X[d + s * NDIM] < X_cell[d])\n                {\n                    stencil_lower[d] = stencil_center[d] - s_kernel_fcn_stencil_size / 2;\n                    stencil_upper[d] = stencil_center[d] + s_kernel_fcn_stencil_size / 2 - 1;\n                }\n                else\n                {\n                    stencil_lower[d] = stencil_center[d] - s_kernel_fcn_stencil_size / 2 + 1;\n                    stencil_upper[d] = stencil_center[d] + s_kernel_fcn_stencil_size / 2;\n                }\n            }\n        }\n        else\n        {\n            for (unsigned int d = 0; d < NDIM; ++d)\n            {\n                stencil_lower[d] = stencil_center[d] - s_kernel_fcn_stencil_size / 2;\n                stencil_upper[d] = stencil_center[d] + s_kernel_fcn_stencil_size / 2;\n            }\n        }\n\n        for (unsigned int d = 0; d < NDIM; ++d)\n        {\n            stencil_lower[d] = std::min(std::max(stencil_lower[d], ilower[d] - q_gcw[d]), iupper[d] + q_gcw[d]);\n            stencil_upper[d] = std::min(std::max(stencil_upper[d], ilower[d] - q_gcw[d]), iupper[d] + q_gcw[d]);\n        }\n\n        // Compute the kernel function weights.\n        boost::multi_array<double, 1> w0(boost::extents[range(stencil_lower[0], stencil_upper[0] + 1)]);\n        for (int ic0 = stencil_lower[0]; ic0 <= stencil_upper[0]; ++ic0)\n        {\n            w0[ic0] = s_kernel_fcn((X[0 + s * NDIM] + X_shift[0 + l * NDIM] -\n                                    (X_cell[0] + static_cast<double>(ic0 - stencil_center[0]) * dx[0])) /\n                                   dx[0]);\n        }\n\n        boost::multi_array<double, 1> w1(boost::extents[range(stencil_lower[1], stencil_upper[1] + 1)]);\n        for (int ic1 = stencil_lower[1]; ic1 <= stencil_upper[1]; ++ic1)\n        {\n            w1[ic1] = s_kernel_fcn((X[1 + s * NDIM] + X_shift[1 + l * NDIM] -\n                                    (X_cell[1] + static_cast<double>(ic1 - stencil_center[1]) * dx[1])) /\n                                   dx[1]);\n        }\n#if (NDIM == 3)\n        boost::multi_array<double, 1> w2(boost::extents[range(stencil_lower[2], stencil_upper[2] + 1)]);\n        for (int ic2 = stencil_lower[2]; ic2 <= stencil_upper[2]; ++ic2)\n        {\n            w2[ic2] = s_kernel_fcn((X[2 + s * NDIM] + X_shift[2 + l * NDIM] -\n                                    (X_cell[2] + static_cast<double>(ic2 - stencil_center[2]) * dx[2])) /\n                                   dx[2]);\n        }\n#endif\n        // Interpolate u onto V.\n        for (int d = 0; d < Q_depth; ++d)\n        {\n            Q[d + s * Q_depth] = 0.0;\n#if (NDIM == 3)\n            for (int ic2 = stencil_lower[2]; ic2 <= stencil_upper[2]; ++ic2)\n            {\n#endif\n                for (int ic1 = stencil_lower[1]; ic1 <= stencil_upper[1]; ++ic1)\n                {\n                    for (int ic0 = stencil_lower[0]; ic0 <= stencil_upper[0]; ++ic0)\n                    {\n#if (NDIM == 2)\n                        Q[d + s * Q_depth] += w0[ic0] * w1[ic1] * q_data[ic0][ic1][d];\n#endif\n#if (NDIM == 3)\n                        Q[d + s * Q_depth] += w0[ic0] * w1[ic1] * w2[ic2] * q_data[ic0][ic1][ic2][d];\n#endif\n                    }\n                }\n#if (NDIM == 3)\n            }\n#endif\n        }\n    }\n    return;\n}\n\nvoid\nLEInteractor::userDefinedSpread(double* q,\n                                const Box<NDIM>& q_data_box,\n                                const int* const q_gcw,\n                                const int q_depth,\n                                const double* const x_lower,\n                                const double* const /*x_upper*/,\n                                const double* const dx,\n                                const double* const Q,\n                                const int Q_depth,\n                                const double* const X,\n                                const int* const local_indices,\n                                const double* const X_shift,\n                                const int num_local_indices)\n{\n    const int* const ilower = q_data_box.lower();\n    const int* const iupper = q_data_box.upper();\n    using range = boost::multi_array_types::extent_range;\n    boost::multi_array_ref<double, NDIM + 1> q_data(\n        q,\n        (boost::extents[range(ilower[0] - q_gcw[0], iupper[0] + q_gcw[0] + 1)]\n                       [range(ilower[1] - q_gcw[1], iupper[1] + q_gcw[1] + 1)]\n#if (NDIM == 3)\n                       [range(ilower[2] - q_gcw[2], iupper[2] + q_gcw[2] + 1)]\n#endif\n                       [range(0, q_depth)]),\n        boost::fortran_storage_order());\n    std::array<double, NDIM> X_cell;\n    std::array<int, NDIM> stencil_center, stencil_lower, stencil_upper;\n    for (int l = 0; l < num_local_indices; ++l)\n    {\n        const int s = local_indices[l];\n\n        // Determine the Cartesian cell in which X(s) is located.\n        for (unsigned int d = 0; d < NDIM; ++d)\n        {\n            stencil_center[d] =\n                static_cast<int>(std::floor((X[d + s * NDIM] + X_shift[d + l * NDIM] - x_lower[d]) / dx[d])) +\n                ilower[d];\n            X_cell[d] = x_lower[d] + (static_cast<double>(stencil_center[d] - ilower[d]) + 0.5) * dx[d];\n        }\n\n        // Determine the interpolation stencil corresponding to the position of\n        // X(s) within the cell.\n        if (s_kernel_fcn_stencil_size % 2 == 0)\n        {\n            for (unsigned int d = 0; d < NDIM; ++d)\n            {\n                if (X[d + s * NDIM] < X_cell[d])\n                {\n                    stencil_lower[d] = stencil_center[d] - s_kernel_fcn_stencil_size / 2;\n                    stencil_upper[d] = stencil_center[d] + s_kernel_fcn_stencil_size / 2 - 1;\n                }\n                else\n                {\n                    stencil_lower[d] = stencil_center[d] - s_kernel_fcn_stencil_size / 2 + 1;\n                    stencil_upper[d] = stencil_center[d] + s_kernel_fcn_stencil_size / 2;\n                }\n            }\n        }\n        else\n        {\n            for (unsigned int d = 0; d < NDIM; ++d)\n            {\n                stencil_lower[d] = stencil_center[d] - s_kernel_fcn_stencil_size / 2;\n                stencil_upper[d] = stencil_center[d] + s_kernel_fcn_stencil_size / 2;\n            }\n        }\n\n        for (unsigned int d = 0; d < NDIM; ++d)\n        {\n            stencil_lower[d] = std::min(std::max(stencil_lower[d], ilower[d] - q_gcw[d]), iupper[d] + q_gcw[d]);\n            stencil_upper[d] = std::min(std::max(stencil_upper[d], ilower[d] - q_gcw[d]), iupper[d] + q_gcw[d]);\n        }\n\n        // Compute the kernel function weights.\n        boost::multi_array<double, 1> w0(boost::extents[range(stencil_lower[0], stencil_upper[0] + 1)]);\n        for (int ic0 = stencil_lower[0]; ic0 <= stencil_upper[0]; ++ic0)\n        {\n            w0[ic0] = s_kernel_fcn((X[0 + s * NDIM] + X_shift[0 + l * NDIM] -\n                                    (X_cell[0] + static_cast<double>(ic0 - stencil_center[0]) * dx[0])) /\n                                   dx[0]);\n        }\n\n        boost::multi_array<double, 1> w1(boost::extents[range(stencil_lower[1], stencil_upper[1] + 1)]);\n        for (int ic1 = stencil_lower[1]; ic1 <= stencil_upper[1]; ++ic1)\n        {\n            w1[ic1] = s_kernel_fcn((X[1 + s * NDIM] + X_shift[1 + l * NDIM] -\n                                    (X_cell[1] + static_cast<double>(ic1 - stencil_center[1]) * dx[1])) /\n                                   dx[1]);\n        }\n#if (NDIM == 3)\n        boost::multi_array<double, 1> w2(boost::extents[range(stencil_lower[2], stencil_upper[2] + 1)]);\n        for (int ic2 = stencil_lower[2]; ic2 <= stencil_upper[2]; ++ic2)\n        {\n            w2[ic2] = s_kernel_fcn((X[2 + s * NDIM] + X_shift[2 + l * NDIM] -\n                                    (X_cell[2] + static_cast<double>(ic2 - stencil_center[2]) * dx[2])) /\n                                   dx[2]);\n        }\n#endif\n        // Spread V onto u.\n        for (int d = 0; d < Q_depth; ++d)\n        {\n#if (NDIM == 3)\n            for (int ic2 = stencil_lower[2]; ic2 <= stencil_upper[2]; ++ic2)\n            {\n#endif\n                for (int ic1 = stencil_lower[1]; ic1 <= stencil_upper[1]; ++ic1)\n                {\n                    for (int ic0 = stencil_lower[0]; ic0 <= stencil_upper[0]; ++ic0)\n                    {\n#if (NDIM == 2)\n                        q_data[ic0][ic1][d] += w0[ic0] * w1[ic1] * Q[d + s * Q_depth] / (dx[0] * dx[1]);\n#endif\n#if (NDIM == 3)\n                        q_data[ic0][ic1][ic2][d] +=\n                            w0[ic0] * w1[ic1] * w2[ic2] * Q[d + s * Q_depth] / (dx[0] * dx[1] * dx[2]);\n#endif\n                    }\n                }\n#if (NDIM == 3)\n            }\n#endif\n        }\n    }\n    return;\n}\n\n/////////////////////////////// NAMESPACE ////////////////////////////////////\n\n} // namespace IBTK\n\n/////////////////////////////// TEMPLATE INSTANTIATION ///////////////////////\n\ntemplate void IBTK::LEInteractor::interpolate(SAMRAI::tbox::Pointer<LData> Q_data,\n                                              const SAMRAI::tbox::Pointer<LData> X_data,\n                                              const SAMRAI::tbox::Pointer<LIndexSetData<LNode> > idx_data,\n                                              const SAMRAI::tbox::Pointer<SAMRAI::pdat::CellData<NDIM, double> > q_data,\n                                              const SAMRAI::tbox::Pointer<SAMRAI::hier::Patch<NDIM> > patch,\n                                              const SAMRAI::hier::Box<NDIM>& interp_box,\n                                              const SAMRAI::hier::IntVector<NDIM>& periodic_shift,\n                                              const std::string& interp_fcn);\n\ntemplate void IBTK::LEInteractor::interpolate(SAMRAI::tbox::Pointer<LData> Q_data,\n                                              const SAMRAI::tbox::Pointer<LData> X_data,\n                                              const SAMRAI::tbox::Pointer<LIndexSetData<LNode> > idx_data,\n                                              const SAMRAI::tbox::Pointer<SAMRAI::pdat::NodeData<NDIM, double> > q_data,\n                                              const SAMRAI::tbox::Pointer<SAMRAI::hier::Patch<NDIM> > patch,\n                                              const SAMRAI::hier::Box<NDIM>& interp_box,\n                                              const SAMRAI::hier::IntVector<NDIM>& periodic_shift,\n                                              const std::string& interp_fcn);\n\ntemplate void IBTK::LEInteractor::interpolate(SAMRAI::tbox::Pointer<LData> Q_data,\n                                              const SAMRAI::tbox::Pointer<LData> X_data,\n                                              const SAMRAI::tbox::Pointer<LIndexSetData<LNode> > idx_data,\n                                              const SAMRAI::tbox::Pointer<SAMRAI::pdat::SideData<NDIM, double> > q_data,\n                                              const SAMRAI::tbox::Pointer<SAMRAI::hier::Patch<NDIM> > patch,\n                                              const SAMRAI::hier::Box<NDIM>& interp_box,\n                                              const SAMRAI::hier::IntVector<NDIM>& periodic_shift,\n                                              const std::string& interp_fcn);\n\ntemplate void IBTK::LEInteractor::interpolate(SAMRAI::tbox::Pointer<LData> Q_data,\n                                              const SAMRAI::tbox::Pointer<LData> X_data,\n                                              const SAMRAI::tbox::Pointer<LIndexSetData<LNode> > idx_data,\n                                              const SAMRAI::tbox::Pointer<SAMRAI::pdat::EdgeData<NDIM, double> > q_data,\n                                              const SAMRAI::tbox::Pointer<SAMRAI::hier::Patch<NDIM> > patch,\n                                              const SAMRAI::hier::Box<NDIM>& interp_box,\n                                              const SAMRAI::hier::IntVector<NDIM>& periodic_shift,\n                                              const std::string& interp_fcn);\n\ntemplate void IBTK::LEInteractor::interpolate(double* const Q_data,\n                                              const int Q_depth,\n                                              const double* const X_data,\n                                              const int X_depth,\n                                              const SAMRAI::tbox::Pointer<LIndexSetData<LNode> > idx_data,\n                                              const SAMRAI::tbox::Pointer<SAMRAI::pdat::CellData<NDIM, double> > q_data,\n                                              const SAMRAI::tbox::Pointer<SAMRAI::hier::Patch<NDIM> > patch,\n                                              const SAMRAI::hier::Box<NDIM>& interp_box,\n                                              const SAMRAI::hier::IntVector<NDIM>& periodic_shift,\n                                              const std::string& interp_fcn);\n\ntemplate void IBTK::LEInteractor::interpolate(double* const Q_data,\n                                              const int Q_depth,\n                                              const double* const X_data,\n                                              const int X_depth,\n                                              const SAMRAI::tbox::Pointer<LIndexSetData<LNode> > idx_data,\n                                              const SAMRAI::tbox::Pointer<SAMRAI::pdat::NodeData<NDIM, double> > q_data,\n                                              const SAMRAI::tbox::Pointer<SAMRAI::hier::Patch<NDIM> > patch,\n                                              const SAMRAI::hier::Box<NDIM>& interp_box,\n                                              const SAMRAI::hier::IntVector<NDIM>& periodic_shift,\n                                              const std::string& interp_fcn);\n\ntemplate void IBTK::LEInteractor::interpolate(double* const Q_data,\n                                              const int Q_depth,\n                                              const double* const X_data,\n                                              const int X_depth,\n                                              const SAMRAI::tbox::Pointer<LIndexSetData<LNode> > idx_data,\n                                              const SAMRAI::tbox::Pointer<SAMRAI::pdat::SideData<NDIM, double> > q_data,\n                                              const SAMRAI::tbox::Pointer<SAMRAI::hier::Patch<NDIM> > patch,\n                                              const SAMRAI::hier::Box<NDIM>& interp_box,\n                                              const SAMRAI::hier::IntVector<NDIM>& periodic_shift,\n                                              const std::string& interp_fcn);\n\ntemplate void IBTK::LEInteractor::interpolate(double* const Q_data,\n                                              const int Q_depth,\n                                              const double* const X_data,\n                                              const int X_depth,\n                                              const SAMRAI::tbox::Pointer<LIndexSetData<LNode> > idx_data,\n                                              const SAMRAI::tbox::Pointer<SAMRAI::pdat::EdgeData<NDIM, double> > q_data,\n                                              const SAMRAI::tbox::Pointer<SAMRAI::hier::Patch<NDIM> > patch,\n                                              const SAMRAI::hier::Box<NDIM>& interp_box,\n                                              const SAMRAI::hier::IntVector<NDIM>& periodic_shift,\n                                              const std::string& interp_fcn);\n\ntemplate void IBTK::LEInteractor::spread(SAMRAI::tbox::Pointer<SAMRAI::pdat::CellData<NDIM, double> > q_data,\n                                         const SAMRAI::tbox::Pointer<LData> Q_data,\n                                         const SAMRAI::tbox::Pointer<LData> X_data,\n                                         const SAMRAI::tbox::Pointer<LIndexSetData<LNode> > idx_data,\n                                         const SAMRAI::tbox::Pointer<SAMRAI::hier::Patch<NDIM> > patch,\n                                         const SAMRAI::hier::Box<NDIM>& spread_box,\n                                         const SAMRAI::hier::IntVector<NDIM>& periodic_shift,\n                                         const std::string& spread_fcn);\n\ntemplate void IBTK::LEInteractor::spread(SAMRAI::tbox::Pointer<SAMRAI::pdat::NodeData<NDIM, double> > q_data,\n                                         const SAMRAI::tbox::Pointer<LData> Q_data,\n                                         const SAMRAI::tbox::Pointer<LData> X_data,\n                                         const SAMRAI::tbox::Pointer<LIndexSetData<LNode> > idx_data,\n                                         const SAMRAI::tbox::Pointer<SAMRAI::hier::Patch<NDIM> > patch,\n                                         const SAMRAI::hier::Box<NDIM>& spread_box,\n                                         const SAMRAI::hier::IntVector<NDIM>& periodic_shift,\n                                         const std::string& spread_fcn);\n\ntemplate void IBTK::LEInteractor::spread(SAMRAI::tbox::Pointer<SAMRAI::pdat::SideData<NDIM, double> > q_data,\n                                         const SAMRAI::tbox::Pointer<LData> Q_data,\n                                         const SAMRAI::tbox::Pointer<LData> X_data,\n                                         const SAMRAI::tbox::Pointer<LIndexSetData<LNode> > idx_data,\n                                         const SAMRAI::tbox::Pointer<SAMRAI::hier::Patch<NDIM> > patch,\n                                         const SAMRAI::hier::Box<NDIM>& spread_box,\n                                         const SAMRAI::hier::IntVector<NDIM>& periodic_shift,\n                                         const std::string& spread_fcn);\n\ntemplate void IBTK::LEInteractor::spread(SAMRAI::tbox::Pointer<SAMRAI::pdat::EdgeData<NDIM, double> > q_data,\n                                         const SAMRAI::tbox::Pointer<LData> Q_data,\n                                         const SAMRAI::tbox::Pointer<LData> X_data,\n                                         const SAMRAI::tbox::Pointer<LIndexSetData<LNode> > idx_data,\n                                         const SAMRAI::tbox::Pointer<SAMRAI::hier::Patch<NDIM> > patch,\n                                         const SAMRAI::hier::Box<NDIM>& spread_box,\n                                         const SAMRAI::hier::IntVector<NDIM>& periodic_shift,\n                                         const std::string& spread_fcn);\n\ntemplate void IBTK::LEInteractor::spread(SAMRAI::tbox::Pointer<SAMRAI::pdat::CellData<NDIM, double> > q_data,\n                                         const double* const Q_data,\n                                         const int Q_depth,\n                                         const double* const X_data,\n                                         const int X_depth,\n                                         const SAMRAI::tbox::Pointer<LIndexSetData<LNode> > idx_data,\n                                         const SAMRAI::tbox::Pointer<SAMRAI::hier::Patch<NDIM> > patch,\n                                         const SAMRAI::hier::Box<NDIM>& spread_box,\n                                         const SAMRAI::hier::IntVector<NDIM>& periodic_shift,\n                                         const std::string& spread_fcn);\n\ntemplate void IBTK::LEInteractor::spread(SAMRAI::tbox::Pointer<SAMRAI::pdat::NodeData<NDIM, double> > q_data,\n                                         const double* const Q_data,\n                                         const int Q_depth,\n                                         const double* const X_data,\n                                         const int X_depth,\n                                         const SAMRAI::tbox::Pointer<LIndexSetData<LNode> > idx_data,\n                                         const SAMRAI::tbox::Pointer<SAMRAI::hier::Patch<NDIM> > patch,\n                                         const SAMRAI::hier::Box<NDIM>& spread_box,\n                                         const SAMRAI::hier::IntVector<NDIM>& periodic_shift,\n                                         const std::string& spread_fcn);\n\ntemplate void IBTK::LEInteractor::spread(SAMRAI::tbox::Pointer<SAMRAI::pdat::SideData<NDIM, double> > q_data,\n                                         const double* const Q_data,\n                                         const int Q_depth,\n                                         const double* const X_data,\n                                         const int X_depth,\n                                         const SAMRAI::tbox::Pointer<LIndexSetData<LNode> > idx_data,\n                                         const SAMRAI::tbox::Pointer<SAMRAI::hier::Patch<NDIM> > patch,\n                                         const SAMRAI::hier::Box<NDIM>& spread_box,\n                                         const SAMRAI::hier::IntVector<NDIM>& periodic_shift,\n                                         const std::string& spread_fcn);\n\ntemplate void IBTK::LEInteractor::spread(SAMRAI::tbox::Pointer<SAMRAI::pdat::EdgeData<NDIM, double> > q_data,\n                                         const double* const Q_data,\n                                         const int Q_depth,\n                                         const double* const X_data,\n                                         const int X_depth,\n                                         const SAMRAI::tbox::Pointer<LIndexSetData<LNode> > idx_data,\n                                         const SAMRAI::tbox::Pointer<SAMRAI::hier::Patch<NDIM> > patch,\n                                         const SAMRAI::hier::Box<NDIM>& spread_box,\n                                         const SAMRAI::hier::IntVector<NDIM>& periodic_shift,\n                                         const std::string& spread_fcn);\n\ntemplate void IBTK::LEInteractor::buildLocalIndices(std::vector<int>& local_indices,\n                                                    std::vector<double>& periodic_shifts,\n                                                    const SAMRAI::hier::Box<NDIM>& box,\n                                                    const SAMRAI::tbox::Pointer<SAMRAI::hier::Patch<NDIM> > patch,\n                                                    const SAMRAI::hier::IntVector<NDIM>& periodic_shift,\n                                                    const SAMRAI::tbox::Pointer<LIndexSetData<LNode> > idx_data);\n\n//////////////////////////////////////////////////////////////////////////////\n", "meta": {"hexsha": "f6b2207dc01da349fae0bb3fb279b8865eb47c02", "size": 217436, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ibtk/src/lagrangian/LEInteractor.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": "ibtk/src/lagrangian/LEInteractor.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": "ibtk/src/lagrangian/LEInteractor.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": 42.0572533849, "max_line_length": 120, "alphanum_fraction": 0.4198338822, "num_tokens": 43684, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.45774344566918956}}
{"text": "// Boost.Geometry\n\n// Copyright (c) 2021, Oracle and/or its affiliates.\n\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\n\n// Licensed under the Boost Software License version 1.0.\n// http://www.boost.org/users/license.html\n\n#ifndef BOOST_GEOMETRY_STRATEGIES_LENGTH_SPHERICAL_HPP\n#define BOOST_GEOMETRY_STRATEGIES_LENGTH_SPHERICAL_HPP\n\n\n#include <boost/geometry/strategies/detail.hpp>\n#include <boost/geometry/strategies/distance/detail.hpp>\n#include <boost/geometry/strategies/length/services.hpp>\n\n#include <boost/geometry/strategies/spherical/distance_haversine.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\nnamespace strategies { namespace length\n{\n\ntemplate\n<\n    typename RadiusTypeOrSphere = double,\n    typename CalculationType = void\n>\nclass spherical\n    : public strategies::detail::spherical_base<RadiusTypeOrSphere>\n{\n    using base_t = strategies::detail::spherical_base<RadiusTypeOrSphere>;\n\npublic:\n    spherical() = default;\n\n    template <typename RadiusOrSphere>\n    explicit spherical(RadiusOrSphere const& radius_or_sphere)\n        : base_t(radius_or_sphere)\n    {}\n\n    template <typename Geometry1, typename Geometry2>\n    auto distance(Geometry1 const&, Geometry2 const&,\n                  distance::detail::enable_if_pp_t<Geometry1, Geometry2> * = nullptr) const\n    {\n        return strategy::distance::haversine\n                <\n                    typename base_t::radius_type, CalculationType\n                >(base_t::radius());\n    }\n};\n\n\nnamespace services\n{\n\ntemplate <typename Geometry>\nstruct default_strategy<Geometry, spherical_equatorial_tag>\n{\n    using type = strategies::length::spherical<>;\n};\n\n\ntemplate <typename R, typename CT>\nstruct strategy_converter<strategy::distance::haversine<R, CT> >\n{\n    static auto get(strategy::distance::haversine<R, CT> const& s)\n    {\n        return strategies::length::spherical<R, CT>(s.radius());\n    }\n};\n\n\n} // namespace services\n\n}} // namespace strategies::length\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_STRATEGIES_LENGTH_SPHERICAL_HPP\n", "meta": {"hexsha": "3c45ff2fd027ffccbd6851cb2bd217f33b1f6700", "size": 2064, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/boost_1.78.0/boost/geometry/strategies/length/spherical.hpp", "max_stars_repo_name": "LaudateCorpus1/math", "max_stars_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 326.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T13:47:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T02:13:59.000Z", "max_issues_repo_path": "lib/boost_1.78.0/boost/geometry/strategies/length/spherical.hpp", "max_issues_repo_name": "LaudateCorpus1/math", "max_issues_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 623.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T23:45:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T11:15:23.000Z", "max_forks_repo_path": "lib/boost_1.78.0/boost/geometry/strategies/length/spherical.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": 24.5714285714, "max_line_length": 91, "alphanum_fraction": 0.7262596899, "num_tokens": 464, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.45774344566918956}}
{"text": "/**\n * @file nonlinschroedingerequation.cc\n * @brief NPDE homework NonLinSchroedingerEquation code\n * @author Oliver Rietmann\n * @date 22.04.2020\n * @copyright Developed at ETH Zurich\n */\n\n#include \"nonlinschroedingerequation.h\"\n\n#include <cmath>\n\n#include <Eigen/Core>\n\n#include <lf/base/base.h>\n#include <lf/geometry/geometry.h>\n#include <lf/mesh/mesh.h>\n\nnamespace NonLinSchroedingerEquation {\n\n/* SAM_LISTING_BEGIN_1 */\nEigen::Matrix3d MassElementMatrixProvider::Eval(const lf::mesh::Entity &cell) {\n  LF_VERIFY_MSG(cell.RefEl() == lf::base::RefEl::kTria(),\n                \"Unsupported cell type \" << cell.RefEl());\n  Eigen::Matrix3d element_matrix;\n  //====================\n  // Your code goes here\n  //====================\n  return element_matrix;\n}\n/* SAM_LISTING_END_1 */\n\n/* SAM_LISTING_BEGIN_2 */\ndouble Norm(const Eigen::VectorXcd &mu, const Eigen::SparseMatrix<double> &D) {\n  //====================\n  // Your code goes here\n  // Replace this dummy value by the approximate\n  // norm of the mesh function assiciated with mu\n  return 1.0;\n  //====================\n}\n\ndouble KineticEnergy(const Eigen::VectorXcd &mu,\n                     const Eigen::SparseMatrix<double> &A) {\n  //====================\n  // Your code goes here\n  // Replace this dummy value by the kinetic energy\n  // of the mesh function assiciated with mu\n  return 0.0;\n  //====================\n}\n\ndouble InteractionEnergy(const Eigen::VectorXcd &mu,\n                         const Eigen::SparseMatrix<double> &D) {\n  //====================\n  // Your code goes here\n  // Replace this dummy value by the interaction\n  // energy of the mesh function assiciated with mu\n  return 0.0;\n  //====================\n}\n/* SAM_LISTING_END_2 */\n\n}  // namespace NonLinSchroedingerEquation\n", "meta": {"hexsha": "ba65e0b670bc776f72aae22af33b4f550c4b6710", "size": 1756, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/NonLinSchroedingerEquation/templates/nonlinschroedingerequation.cc", "max_stars_repo_name": "padomu/NPDECODES", "max_stars_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "homeworks/NonLinSchroedingerEquation/templates/nonlinschroedingerequation.cc", "max_issues_repo_name": "padomu/NPDECODES", "max_issues_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homeworks/NonLinSchroedingerEquation/templates/nonlinschroedingerequation.cc", "max_forks_repo_name": "padomu/NPDECODES", "max_forks_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_forks_repo_licenses": ["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.0153846154, "max_line_length": 79, "alphanum_fraction": 0.6230068337, "num_tokens": 452, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.7772998663336157, "lm_q1q2_score": 0.45774344263115496}}
{"text": "#include <urdf_model/model.h>\n\n#include <kdl/chainiksolverpos_lma.hpp>\n\n#include \"ros/ros.h\"\n\n#include \"applicable_pose_generator/pose_reachability_filter.h\"\n#include <boost/shared_ptr.hpp>\n\n#include <kdl_parser/kdl_parser.hpp>\n#include <eigen_conversions/eigen_kdl.h>\n\n\nnamespace CreateChain\n{\nchain_creation::chain_creation()\n{\n  ros::NodeHandle pnh(\"~\");\n  if (!pnh.getParam(\"robot_urdf\", robot_urdf_)){\n    ROS_ERROR(\"did not set parameter robot_urdf\");\n    exit (EXIT_FAILURE);\n  }\n  if (!pnh.getParam(\"base_link\", base_link_param_)){\n    ROS_ERROR(\"did not set parameter base_link\");\n    exit (EXIT_FAILURE);\n  }\n  if (!pnh.getParam(\"tool0\", tool0_param_)){\n    ROS_ERROR(\"did not set parameter tool0\");\n    exit (EXIT_FAILURE);\n  }\n  if (!Mymodel.initFile(robot_urdf_))\n  {\n    ROS_ERROR(\"Failed to parse urdf file\");\n    return;\n  }\n  else\n  {\n  ROS_INFO(\"Successfully parsed urdf file\");\n  }\n  urdf::ModelInterfaceConstSharedPtr model_ptr = boost::make_shared<urdf::Model>(Mymodel);\n  if(!CK.init(model_ptr,base_link_param_,tool0_param_,\"Robot_from_urdf\"))\n  {\n    ROS_ERROR(\"failed to initiat the chain\");\n    return;\n  }\n  kdl_parser::treeFromUrdfModel(*model_ptr, robot_tree);\n  robot_tree.getChain(base_link_param_,tool0_param_,robot_chain);\n}\n\nbool chain_creation::chain_Parse(Eigen::Affine3d ei_transform_to_check)\n{\n  //get transform that we are trying to reach with robot\n  KDL::ChainIkSolverPos_LMA solving_Ik(robot_chain);\n  robot_joints.resize(robot_chain.getNrOfJoints());\n  return_joint_values.resize(robot_chain.getNrOfJoints());\n  tf::transformEigenToKDL(ei_transform_to_check,transform_goal_kdl);\n\n  ROS_INFO(\"%d\",solving_Ik.CartToJnt(robot_joints,transform_goal_kdl,return_joint_values));\n\n  if(!solving_Ik.CartToJnt(robot_joints,transform_goal_kdl,return_joint_values))\n  {\n    ROS_INFO(\"Reachable Pose Found\");\n    return true;\n  }\n  else\n  {\n    ROS_INFO(\"Unreachable pose found\");\n    return false;\n  }\n}\n}//end of namespace create_chain_take_pose_inverse_kinamatics\n\n\n", "meta": {"hexsha": "5921b9de56798b12b58a4f03f8cfb52bd9ca3fbb", "size": 1999, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "applicable_pose_generator/src/pose_reachability_filter.cpp", "max_stars_repo_name": "Julien-Livet/industrial_calibration", "max_stars_repo_head_hexsha": "078030b2d9eeca64b34e3ef48b7d23f7be5e5717", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 98.0, "max_stars_repo_stars_event_min_datetime": "2015-01-20T22:13:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T23:54:24.000Z", "max_issues_repo_path": "applicable_pose_generator/src/pose_reachability_filter.cpp", "max_issues_repo_name": "Julien-Livet/industrial_calibration", "max_issues_repo_head_hexsha": "078030b2d9eeca64b34e3ef48b7d23f7be5e5717", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 96.0, "max_issues_repo_issues_event_min_datetime": "2015-03-02T15:57:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-29T14:12:26.000Z", "max_forks_repo_path": "applicable_pose_generator/src/pose_reachability_filter.cpp", "max_forks_repo_name": "Julien-Livet/industrial_calibration", "max_forks_repo_head_hexsha": "078030b2d9eeca64b34e3ef48b7d23f7be5e5717", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 85.0, "max_forks_repo_forks_event_min_datetime": "2015-02-09T23:04:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-15T13:45:07.000Z", "avg_line_length": 27.0135135135, "max_line_length": 91, "alphanum_fraction": 0.7468734367, "num_tokens": 538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.45774343959312036}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// independence.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_INCLUDE_PEARSON_CHISQ_INDEPENDENCE_HPP_ER_2010\n#define BOOST_STATISTICS_DETAIL_NON_PARAMETRIC_CONTINGENCY_TABLE_INCLUDE_PEARSON_CHISQ_INDEPENDENCE_HPP_ER_2010\n\n#include <boost/statistics/detail/non_parametric/contingency_table/pearson_chisq/independence/feature.hpp>\n#include <boost/statistics/detail/non_parametric/contingency_table/pearson_chisq/independence/null_hypothesis.hpp>\n\n#endif\n", "meta": {"hexsha": "d92f2be81900a7ca3419efb90aa38dad1492353b", "size": 1015, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "non_parametric/boost/statistics/detail/non_parametric/contingency_table/include/pearson_chisq/independence.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/include/pearson_chisq/independence.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/include/pearson_chisq/independence.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": 67.6666666667, "max_line_length": 114, "alphanum_fraction": 0.5684729064, "num_tokens": 184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.45774343959312036}}
{"text": "#include <benchmark/benchmark.h>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include \"UKF/Types.h\"\n#include \"UKF/StateVector.h\"\n#include \"UKF/MeasurementVector.h\"\n\nenum MyStateVectorFields {\n    AngularVelocity,\n    Altitude,\n    Velocity,\n    Attitude\n};\n\nusing MyStateVector = UKF::StateVector<\n    UKF::Field<Velocity, UKF::Vector<3>>,\n    UKF::Field<AngularVelocity, UKF::Vector<3>>,\n    UKF::Field<Attitude, UKF::Quaternion>,\n    UKF::Field<Altitude, real_t>\n>;\n\nenum MyFields {\n    StaticPressure,\n    DynamicPressure,\n    Accelerometer,\n    Gyroscope\n};\n\nusing MV_Fixed = UKF::FixedMeasurementVector<\n    UKF::Field<Accelerometer, UKF::Vector<3>>,\n    UKF::Field<Gyroscope, UKF::Vector<3>>,\n    UKF::Field<StaticPressure, real_t>,\n    UKF::Field<DynamicPressure, real_t>\n>;\n\nnamespace UKF {\ntemplate <> template <>\nUKF::Vector<3> MV_Fixed::expected_measurement\n<MyStateVector, Accelerometer>(const MyStateVector& state) {\n    return state.get_field<Attitude>() * UKF::Vector<3>(0, 0, -9.8);\n}\n\ntemplate <> template <>\nUKF::Vector<3> MV_Fixed::expected_measurement\n<MyStateVector, Gyroscope>(const MyStateVector& state) {\n    return state.get_field<AngularVelocity>();\n}\n\ntemplate <> template <>\nreal_t MV_Fixed::expected_measurement\n<MyStateVector, StaticPressure>(const MyStateVector& state) {\n    return 101.3 - 1.2*(state.get_field<Altitude>() / 100.0);\n}\n\ntemplate <> template <>\nreal_t MV_Fixed::expected_measurement\n<MyStateVector, DynamicPressure>(const MyStateVector& state) {\n    return 0.5 * 1.225 * state.get_field<Velocity>().squaredNorm();\n}\n\n}\n\nusing MV_Dynamic = UKF::DynamicMeasurementVector<\n    UKF::Field<Accelerometer, UKF::Vector<3>>,\n    UKF::Field<Gyroscope, UKF::Vector<3>>,\n    UKF::Field<StaticPressure, real_t>,\n    UKF::Field<DynamicPressure, real_t>\n>;\n\nnamespace UKF {\ntemplate <> template <>\nUKF::Vector<3> MV_Dynamic::expected_measurement\n<MyStateVector, Accelerometer>(const MyStateVector& state) {\n    return state.get_field<Attitude>() * UKF::Vector<3>(0, 0, -9.8);\n}\n\ntemplate <> template <>\nUKF::Vector<3> MV_Dynamic::expected_measurement\n<MyStateVector, Gyroscope>(const MyStateVector& state) {\n    return state.get_field<AngularVelocity>();\n}\n\ntemplate <> template <>\nreal_t MV_Dynamic::expected_measurement\n<MyStateVector, StaticPressure>(const MyStateVector& state) {\n    return 101.3 - 1.2*(state.get_field<Altitude>() / 100.0);\n}\n\ntemplate <> template <>\nreal_t MV_Dynamic::expected_measurement\n<MyStateVector, DynamicPressure>(const MyStateVector& state) {\n    return 0.5 * 1.225 * state.get_field<Velocity>().squaredNorm();\n}\n\n}\n\n/*\nTests to compare set/get performance between fixed and dynamic measurement vectors.\n*/\nvoid MeasurementVectorFixed_SetGetField(benchmark::State& state) {\n    MV_Fixed test_measurement;\n    while(state.KeepRunning()) {\n        test_measurement.set_field<Accelerometer>(UKF::Vector<3>(1, 2, 3));\n        benchmark::DoNotOptimize(test_measurement.get_field<Accelerometer>());\n    }\n}\n\nBENCHMARK(MeasurementVectorFixed_SetGetField);\n\nvoid MeasurementVectorDynamic_SetGetField(benchmark::State& state) {\n    MV_Dynamic test_measurement;\n    while(state.KeepRunning()) {\n        test_measurement.set_field<Accelerometer>(UKF::Vector<3>(1, 2, 3));\n        benchmark::DoNotOptimize(test_measurement.get_field<Accelerometer>());\n    }\n}\n\nBENCHMARK(MeasurementVectorDynamic_SetGetField);\n\nvoid MeasurementVectorFixed_SigmaPointGeneration(benchmark::State& state) {\n    MyStateVector test_state;\n    MV_Fixed test_measurement;\n\n    test_measurement.set_field<Accelerometer>(UKF::Vector<3>(0, 0, 0));\n    test_measurement.set_field<Gyroscope>(UKF::Vector<3>(0, 0, 0));\n    test_measurement.set_field<StaticPressure>(0);\n    test_measurement.set_field<DynamicPressure>(0);\n\n    test_state.set_field<Velocity>(UKF::Vector<3>(1, 2, 3));\n    test_state.set_field<AngularVelocity>(UKF::Vector<3>(1, 0, 0));\n    test_state.set_field<Attitude>(UKF::Quaternion(1, 0, 0, 0));\n    test_state.set_field<Altitude>(1000);\n\n    MyStateVector::CovarianceMatrix covariance = MyStateVector::CovarianceMatrix::Zero();\n    covariance.diagonal() << 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0;\n\n    MyStateVector::SigmaPointDistribution sigma_points = test_state.calculate_sigma_point_distribution(covariance);\n\n    while(state.KeepRunning()) {\n        benchmark::DoNotOptimize(test_measurement.calculate_sigma_point_distribution<MyStateVector>(sigma_points));\n    }\n}\n\nBENCHMARK(MeasurementVectorFixed_SigmaPointGeneration);\n\nvoid MeasurementVectorDynamic_SigmaPointGeneration(benchmark::State& state) {\n    MyStateVector test_state;\n    MV_Dynamic test_measurement;\n\n    test_measurement.set_field<Accelerometer>(UKF::Vector<3>(0, 0, 0));\n    test_measurement.set_field<Gyroscope>(UKF::Vector<3>(0, 0, 0));\n    test_measurement.set_field<StaticPressure>(0);\n    test_measurement.set_field<DynamicPressure>(0);\n\n    test_state.set_field<Velocity>(UKF::Vector<3>(1, 2, 3));\n    test_state.set_field<AngularVelocity>(UKF::Vector<3>(1, 0, 0));\n    test_state.set_field<Attitude>(UKF::Quaternion(1, 0, 0, 0));\n    test_state.set_field<Altitude>(1000);\n\n    MyStateVector::CovarianceMatrix covariance = MyStateVector::CovarianceMatrix::Zero();\n    covariance.diagonal() << 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0;\n\n    MyStateVector::SigmaPointDistribution sigma_points = test_state.calculate_sigma_point_distribution(covariance);\n\n    while(state.KeepRunning()) {\n        benchmark::DoNotOptimize(test_measurement.calculate_sigma_point_distribution<MyStateVector>(sigma_points));\n    }\n}\n\nBENCHMARK(MeasurementVectorDynamic_SigmaPointGeneration);\n\nvoid MeasurementVectorFixed_FullMeasurementCalculation(benchmark::State& state) {\n    MyStateVector test_state;\n    MV_Fixed test_measurement;\n\n    test_measurement.set_field<Accelerometer>(UKF::Vector<3>(0, 0, 0));\n    test_measurement.set_field<Gyroscope>(UKF::Vector<3>(0, 0, 0));\n    test_measurement.set_field<StaticPressure>(0);\n    test_measurement.set_field<DynamicPressure>(0);\n\n    test_state.set_field<Velocity>(UKF::Vector<3>(1, 2, 3));\n    test_state.set_field<AngularVelocity>(UKF::Vector<3>(1, 0, 0));\n    test_state.set_field<Attitude>(UKF::Quaternion(1, 0, 0, 0));\n    test_state.set_field<Altitude>(1000);\n\n    MyStateVector::CovarianceMatrix covariance = MyStateVector::CovarianceMatrix::Zero();\n    covariance.diagonal() << 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0;\n\n    MyStateVector::SigmaPointDistribution sigma_points = test_state.calculate_sigma_point_distribution(covariance);\n\n    MV_Fixed::SigmaPointDistribution<MyStateVector> measurement_sigma_points;\n    MV_Fixed mean_measurement;\n    MV_Fixed::SigmaPointDeltas<MyStateVector> sigma_point_deltas;\n    MV_Fixed::CovarianceMatrix calculated_covariance;\n\n    while(state.KeepRunning()) {\n        measurement_sigma_points = test_measurement.calculate_sigma_point_distribution<MyStateVector>(sigma_points);\n        mean_measurement = test_measurement.calculate_sigma_point_mean<MyStateVector>(measurement_sigma_points);\n        sigma_point_deltas = mean_measurement.calculate_sigma_point_deltas<MyStateVector>(measurement_sigma_points);\n        calculated_covariance = mean_measurement.calculate_sigma_point_covariance<MyStateVector>(sigma_point_deltas);\n    }\n}\n\nBENCHMARK(MeasurementVectorFixed_FullMeasurementCalculation);\n\nvoid MeasurementVectorDynamic_FullMeasurementCalculation(benchmark::State& state) {\n    MyStateVector test_state;\n    MV_Dynamic test_measurement;\n\n    test_measurement.set_field<Accelerometer>(UKF::Vector<3>(0, 0, 0));\n    test_measurement.set_field<Gyroscope>(UKF::Vector<3>(0, 0, 0));\n    test_measurement.set_field<StaticPressure>(0);\n    test_measurement.set_field<DynamicPressure>(0);\n\n    test_state.set_field<Velocity>(UKF::Vector<3>(1, 2, 3));\n    test_state.set_field<AngularVelocity>(UKF::Vector<3>(1, 0, 0));\n    test_state.set_field<Attitude>(UKF::Quaternion(1, 0, 0, 0));\n    test_state.set_field<Altitude>(1000);\n\n    MyStateVector::CovarianceMatrix covariance = MyStateVector::CovarianceMatrix::Zero();\n    covariance.diagonal() << 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0;\n\n    MyStateVector::SigmaPointDistribution sigma_points = test_state.calculate_sigma_point_distribution(covariance);\n\n    MV_Dynamic::SigmaPointDistribution<MyStateVector> measurement_sigma_points(\n        test_measurement.size(), MyStateVector::num_sigma());\n    MV_Dynamic mean_measurement(test_measurement.size());\n    MV_Dynamic::SigmaPointDeltas<MyStateVector> sigma_point_deltas(test_measurement.size(), MyStateVector::num_sigma());\n    MV_Dynamic::CovarianceMatrix calculated_covariance(test_measurement.size(), test_measurement.size());\n\n    while(state.KeepRunning()) {\n        measurement_sigma_points = test_measurement.calculate_sigma_point_distribution<MyStateVector>(sigma_points);\n        mean_measurement = test_measurement.calculate_sigma_point_mean<MyStateVector>(measurement_sigma_points);\n        sigma_point_deltas = mean_measurement.calculate_sigma_point_deltas<MyStateVector>(measurement_sigma_points);\n        calculated_covariance = mean_measurement.calculate_sigma_point_covariance<MyStateVector>(sigma_point_deltas);\n    }\n}\n\nBENCHMARK(MeasurementVectorDynamic_FullMeasurementCalculation);\n\nvoid MeasurementVectorFixed_MeasurementCovariance(benchmark::State& state) {\n    MV_Fixed test_measurement, expected_measurement;\n    MV_Fixed::CovarianceVector measurement_covariance;\n\n    measurement_covariance.set_field<Accelerometer>(UKF::Vector<3>(1, 2, 3));\n    measurement_covariance.set_field<Gyroscope>(UKF::Vector<3>(4, 5, 6));\n    measurement_covariance.set_field<StaticPressure>(7);\n    measurement_covariance.set_field<DynamicPressure>(8);\n\n    expected_measurement.set_field<Accelerometer>(UKF::Vector<3>(1, 2, 3));\n    expected_measurement.set_field<Gyroscope>(UKF::Vector<3>(4, 5, 6));\n    expected_measurement.set_field<StaticPressure>(7);\n    expected_measurement.set_field<DynamicPressure>(8);\n\n    while(state.KeepRunning()) {\n        benchmark::DoNotOptimize(test_measurement.calculate_measurement_covariance(\n            measurement_covariance, expected_measurement));\n    }\n}\n\nBENCHMARK(MeasurementVectorFixed_MeasurementCovariance);\n\nvoid MeasurementVectorDynamic_MeasurementCovariance(benchmark::State& state) {\n    MV_Dynamic test_measurement, expected_measurement;\n    MV_Dynamic::CovarianceVector measurement_covariance;\n\n    measurement_covariance.set_field<Accelerometer>(UKF::Vector<3>(1, 2, 3));\n    measurement_covariance.set_field<Gyroscope>(UKF::Vector<3>(4, 5, 6));\n    measurement_covariance.set_field<StaticPressure>(7);\n    measurement_covariance.set_field<DynamicPressure>(8);\n\n    expected_measurement.set_field<Accelerometer>(UKF::Vector<3>(1, 2, 3));\n    expected_measurement.set_field<Gyroscope>(UKF::Vector<3>(4, 5, 6));\n    expected_measurement.set_field<StaticPressure>(7);\n    expected_measurement.set_field<DynamicPressure>(8);\n\n    while(state.KeepRunning()) {\n        benchmark::DoNotOptimize(test_measurement.calculate_measurement_covariance(\n            measurement_covariance, expected_measurement));\n    }\n}\n\nBENCHMARK(MeasurementVectorDynamic_MeasurementCovariance);\n", "meta": {"hexsha": "edc310e89300aec2b6ac2337862772ca3877d685", "size": 11168, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "benchmark/MeasurementVectorBenchmark.cpp", "max_stars_repo_name": "rafaelrietmann/ukf", "max_stars_repo_head_hexsha": "bf53dacafbfee8c7591c48a66b50229f82afe4b4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 320.0, "max_stars_repo_stars_event_min_datetime": "2015-01-07T05:49:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:52:15.000Z", "max_issues_repo_path": "benchmark/MeasurementVectorBenchmark.cpp", "max_issues_repo_name": "msnh2012/ukf", "max_issues_repo_head_hexsha": "04f0a996fee1f49699142bf5b149548a8d3a4ad1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 22.0, "max_issues_repo_issues_event_min_datetime": "2015-03-03T17:28:32.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T14:46:54.000Z", "max_forks_repo_path": "benchmark/MeasurementVectorBenchmark.cpp", "max_forks_repo_name": "msnh2012/ukf", "max_forks_repo_head_hexsha": "04f0a996fee1f49699142bf5b149548a8d3a4ad1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 155.0, "max_forks_repo_forks_event_min_datetime": "2015-02-20T01:18:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-22T01:58:53.000Z", "avg_line_length": 39.323943662, "max_line_length": 120, "alphanum_fraction": 0.7560888252, "num_tokens": 2923, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4577434395931203}}
{"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#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MAIN\n\n#include <limits>\n#include <Eigen/Core>\n\n#include <boost/test/unit_test.hpp>\n\n#include \"tudat/astro/basic_astro/timeConversions.h\"\n#include \"tudat/interface/sofa/sofaTimeConversions.h\"\n#include \"tudat/basics/timeType.h\"\n\n\nnamespace tudat\n{\nnamespace unit_tests\n{\n\nusing namespace tudat::sofa_interface;\nusing namespace tudat::basic_astrodynamics;\n\nBOOST_AUTO_TEST_SUITE( test_sofa_time_conversions )\n\n//! Function to test Sofa time conversion functions (except TT<->TDB) for templated time scalar type.\ntemplate< typename ScalarType >\nvoid testTimeConversions( )\n{\n    // Define UTC date and time.\n    int year = 2006;\n    int months = 1;\n    int days = 15;\n    int hours = 21;\n    int minutes = 24;\n    ScalarType seconds = static_cast< ScalarType >( 37.5 );\n\n    // Get UTC time.\n    ScalarType utcSecondsSinceJ2000 =\n            convertCalendarDateToJulianDaysSinceEpoch< ScalarType >(\n                year, months, days, hours, minutes, seconds,\n                getJulianDayOnJ2000< ScalarType >( ) ) *\n            physical_constants::getJulianDay< ScalarType >( );\n\n    // Convert to TAI time.\n    ScalarType taiSecondsSinceJ2000 = convertUTCtoTAI( utcSecondsSinceJ2000 );\n\n    // Get number of leap seconds and test\n    ScalarType numberOfLeapSeconds = static_cast< ScalarType >( 33 );\n    BOOST_CHECK_CLOSE_FRACTION( taiSecondsSinceJ2000 - utcSecondsSinceJ2000, numberOfLeapSeconds,\n                                utcSecondsSinceJ2000 * std::numeric_limits< ScalarType >::epsilon( ) );\n\n    // Recover UTC and test\n    ScalarType recoveredUtcSecondsSinceJ2000 = convertTAItoUTC( taiSecondsSinceJ2000 );\n    BOOST_CHECK_SMALL( recoveredUtcSecondsSinceJ2000 - utcSecondsSinceJ2000,\n                       std::numeric_limits< ScalarType >::epsilon( ) );\n\n    // Get TT time and compare against expected result.\n    ScalarType ttSecondsSinceJ2000 = convertUTCtoTT( utcSecondsSinceJ2000 );\n    ScalarType ttMinusTai = static_cast< ScalarType >( 32.184 );\n    BOOST_CHECK_CLOSE_FRACTION( ttSecondsSinceJ2000 - utcSecondsSinceJ2000,\n                                numberOfLeapSeconds + ttMinusTai,\n                                utcSecondsSinceJ2000 * std::numeric_limits< ScalarType >::epsilon( ) );\n\n    // Recover UTC from TT and compare against original UTC.\n    recoveredUtcSecondsSinceJ2000 = convertTTtoUTC( ttSecondsSinceJ2000 );\n    BOOST_CHECK_SMALL( recoveredUtcSecondsSinceJ2000 - utcSecondsSinceJ2000,\n                       std::numeric_limits< ScalarType >::epsilon( ) );\n\n}\n\n//! Test TDB<->TT conversions using SOFA cookbook data\nBOOST_AUTO_TEST_CASE( testSofaTimeConversions )\n{\n\n    // Test conversions for double/long double\n    testTimeConversions< double >( );\n    testTimeConversions< long double >( );\n\n\n    // Test TDB - TT calculation, using code from SOFA Time Conversions cookbook.\n    {\n        // Calculate UTC time from date/time\n        int year = 2006;\n        int months = 1;\n        int days = 15;\n        int hours = 21;\n        int minutes = 24;\n        double seconds = 37.5;\n        double utcSecondsSinceJ2000 =\n                convertCalendarDateToJulianDaysSinceEpoch< double >(\n                    year, months, days, hours, minutes, seconds, getJulianDayOnJ2000< double >( ) ) *\n                physical_constants::getJulianDay< double >( );\n\n        // Get UT1 time\n        double dut = 0.3341;\n        double ut1SecondsSinceEpoch = utcSecondsSinceJ2000 + dut;\n\n        // Convert UTC to TT\n        double ttSecondsSinceJ2000 = convertUTCtoTT( utcSecondsSinceJ2000 );\n\n        int latnd, latnm, lonwd, lonwm, iy, mo, id, ih, im;\n        double slatn, slonw, hm, elon, phi, xyz[3], u, v, sec,\n                utc1, utc2, ut11, ut12, ut, tai1, tai2, tt1, tt2,\n                tcg1, tcg2;\n\n        // Run code from Sofa cookbook to obtain TDB - TT (and ground station position).\n        Eigen::Vector3d referencePoint;\n        double dtr;\n        {\n            /* UTC date and time. */\n            iy = 2006;\n            mo = 1;\n            id = 15;\n            ih = 21;\n            im = 24;\n            sec = 37.5;\n            /* Transform into internal format. */\n            iauDtf2d ( \"UTC\", iy, mo, id, ih, im, sec, &utc1, &utc2 );\n\n            /* UTC -> UT1. */\n            iauUtcut1 ( utc1, utc2, dut, &ut11, &ut12 );\n\n\n            /* Extract fraction for TDB-TT calculation, later. */\n            ut = fmod ( fmod(ut11,1.0) + fmod(ut12,1.0), 1.0 ) + 0.5;\n            /* UTC -> TAI -> TT -> TCG. */\n            iauUtctai ( utc1, utc2, &tai1, &tai2 );\n\n            iauTaitt ( tai1, tai2, &tt1, &tt2 );\n\n            iauTttcg ( tt1, tt2, &tcg1, &tcg2 );\n\n\n            /* Site terrestrial coordinates (WGS84). */\n            latnd = 19;\n            latnm = 28;\n            slatn = 52.5;\n            lonwd = 155;\n            lonwm = 55;\n            slonw = 59.6;\n            hm = 0.0;\n\n            /* Transform to geocentric. */\n            iauAf2a ( '+', latnd, latnm, slatn, &phi );\n            iauAf2a ( '-', lonwd, lonwm, slonw, &elon );\n            iauGd2gc ( 1, elon, phi, hm, xyz );\n            u = sqrt ( xyz[0]*xyz[0] + xyz[1]*xyz[1] );\n            v = xyz[2];\n\n            /* UTC date and time. */\n            iy = 2006;\n            mo = 1;\n            id = 15;\n            ih = 21;\n            im = 24;\n            sec = 37.5;\n\n            /* Transform into internal format. */\n            iauDtf2d ( \"UTC\", iy, mo, id, ih, im, sec, &utc1, &utc2 );\n\n\n            /* UT1-UTC (s, from IERS). */\n            dut = 0.3341;\n\n            /* UTC -> UT1. */\n            iauUtcut1 ( utc1, utc2, dut, &ut11, &ut12 );\n\n\n            /* Extract fraction for TDB-TT calculation, later. */\n            ut = fmod ( fmod(ut11,1.0) + fmod(ut12,1.0), 1.0 ) + 0.5;\n\n            /* UTC -> TAI -> TT -> TCG. */\n            iauUtctai ( utc1, utc2, &tai1, &tai2 );\n            iauTaitt ( tai1, tai2, &tt1, &tt2 );\n            iauTttcg ( tt1, tt2, &tcg1, &tcg2 );\n\n            /* TDB-TT (using TT as a substitute for TDB). */\n            dtr = iauDtdb ( tt1, tt2, ut, elon, u/1e3, v/1e3 );\n\n            // Define reference point and\n            referencePoint = ( Eigen::Vector3d( ) << xyz[ 0 ], xyz[ 1 ], xyz[ 2 ] ).finished( );\n        }\n\n        // Calculate UT1 fraction of day\n        double utFractionOfDay = std::fmod( ut1SecondsSinceEpoch / physical_constants::JULIAN_DAY + 0.5, 1.0 );\n\n        // Calculate TDB - TT from Sofa and comapre against cookbook result.\n        double tdbMinusTt = getTDBminusTT( ttSecondsSinceJ2000, utFractionOfDay, referencePoint );\n        BOOST_CHECK_SMALL( tdbMinusTt - dtr, std::numeric_limits< double >::epsilon( ) );\n\n        // Check validity of using TT as subsititute for TDB in conversions\n        double dtr2 = iauDtdb ( tt1, tt2 + dtr / physical_constants::JULIAN_DAY, ut, elon, u/1.0e3, v/1.0e3 );\n        double dtr3 = iauDtdb ( tt1, tt2 + dtr2 / physical_constants::JULIAN_DAY, ut, elon, u/1.0e3, v/1.0e3 );\n        BOOST_CHECK_SMALL( dtr - dtr2, 1.0E-12 );\n        BOOST_CHECK_SMALL( dtr2 - dtr3, 1.0E-15 );\n\n        // Check approximate conversion, omitting utc-ut1 correction.\n        double tdbMinusTtApproximate = getTDBminusTT( ttSecondsSinceJ2000, referencePoint );\n        BOOST_CHECK_SMALL( tdbMinusTtApproximate - tdbMinusTt, 1.0E-10 );    }\n\n}\n\nBOOST_AUTO_TEST_CASE( testLeapSecondIdentification )\n{\n    Eigen::Matrix< int, Eigen::Dynamic, 3 > leapSecondDays;\n    leapSecondDays.resize( 27, 3 );\n    leapSecondDays << 1, 7, 1972,\n            1, 1, 1973,\n            1, 1, 1974,\n            1, 1, 1975,\n            1, 1, 1976,\n            1, 1, 1977,\n            1, 1, 1978,\n            1, 1, 1979,\n            1, 1, 1980,\n            1, 7, 1981,\n            1, 7, 1982,\n            1, 7, 1983,\n            1, 7, 1985,\n            1, 1, 1988,\n            1, 1, 1990,\n            1, 1, 1991,\n            1, 7, 1992,\n            1, 7, 1993,\n            1, 7, 1994,\n            1, 1, 1996,\n            1, 7, 1997,\n            1, 1, 1999,\n            1, 1, 2006,\n            1, 1, 2009,\n            1, 7, 2012,\n            1, 7, 2015,\n            1, 1, 2017;\n\n    for( unsigned int i = 0; i < leapSecondDays.rows( ); i++ )\n    {\n        double utcTimeOfLeapSeconds = basic_astrodynamics::convertCalendarDateToJulianDaysSinceEpoch(\n                    leapSecondDays( i, 2 ), leapSecondDays( i, 1 ), leapSecondDays( i, 0 ), 0, 0, 0.0,\n                    basic_astrodynamics::JULIAN_DAY_ON_J2000 );\n        BOOST_CHECK_EQUAL( sofa_interface::getDeltaAtFromUtc( utcTimeOfLeapSeconds - 1.0E-6 ) -\n                           sofa_interface::getDeltaAtFromUtc( utcTimeOfLeapSeconds + 1.0E-6 ), -1.0 );\n        BOOST_CHECK_EQUAL( sofa_interface::getDeltaAtFromUtc( utcTimeOfLeapSeconds + 1.0E-6 ) -\n                           sofa_interface::getDeltaAtFromUtc( utcTimeOfLeapSeconds + 2.0E-6 ), 0.0 );\n\n        double taiPreLeap = tudat::sofa_interface::convertUTCtoTAI< double >(\n                    utcTimeOfLeapSeconds * physical_constants::JULIAN_DAY - 1.0E-6 );\n        double taiPostLeap = tudat::sofa_interface::convertUTCtoTAI< double >(\n                    utcTimeOfLeapSeconds * physical_constants::JULIAN_DAY + 1.0E-6 );\n        BOOST_CHECK_SMALL(  std::fabs( taiPostLeap - taiPreLeap - ( 1.0 + 2.0E-6 ) ), 1.0E-7 );\n\n        double utcPreLeap = tudat::sofa_interface::convertTAItoUTC< double >( taiPreLeap );\n        double utcPostLeap = tudat::sofa_interface::convertTAItoUTC< double >( taiPostLeap );\n\n        BOOST_CHECK_SMALL( std::fabs( utcPostLeap - utcPreLeap - ( 2.0E-6 ) ), 1.0E-7 );\n    }\n\n    for( unsigned int i = 0; i < leapSecondDays.rows( ); i++ )\n    {\n        Time utcTimeOfLeapSeconds = basic_astrodynamics::convertCalendarDateToJulianDaysSinceEpoch(\n                    leapSecondDays( i, 2 ), leapSecondDays( i, 1 ), leapSecondDays( i, 0 ), 0, 0, 0.0,\n                    basic_astrodynamics::JULIAN_DAY_ON_J2000 );\n        BOOST_CHECK_EQUAL( sofa_interface::getDeltaAtFromUtc( utcTimeOfLeapSeconds - 1.0E-6 ) -\n                           sofa_interface::getDeltaAtFromUtc( utcTimeOfLeapSeconds + 1.0E-6 ), -1.0 );\n        BOOST_CHECK_EQUAL( sofa_interface::getDeltaAtFromUtc( utcTimeOfLeapSeconds + 1.0E-6 ) -\n                           sofa_interface::getDeltaAtFromUtc( utcTimeOfLeapSeconds + 2.0E-6 ), 0.0 );\n\n        Time taiPreLeap = tudat::sofa_interface::convertUTCtoTAI< Time >(\n                    utcTimeOfLeapSeconds * physical_constants::JULIAN_DAY - 1.0E-6 );\n        Time taiPostLeap = tudat::sofa_interface::convertUTCtoTAI< Time >(\n                    utcTimeOfLeapSeconds * physical_constants::JULIAN_DAY + 1.0E-6 );\n\n        long double timeDifferenceTai = static_cast< long double >( taiPostLeap - taiPreLeap ) - ( 1.0L + 2.0E-6 );\n        BOOST_CHECK_SMALL( std::fabs( timeDifferenceTai ), 3600.0L * std::numeric_limits< long double >::epsilon( ) );\n\n        Time utcPreLeap = tudat::sofa_interface::convertTAItoUTC< Time >( taiPreLeap );\n        Time utcPostLeap = tudat::sofa_interface::convertTAItoUTC< Time >( taiPostLeap );\n\n        long double timeDifferenceUtc = static_cast< long double >( utcPostLeap - utcPreLeap ) - ( 2.0E-6 );\n        BOOST_CHECK_SMALL( std::fabs( timeDifferenceUtc ), 3600.0L * std::numeric_limits< long double >::epsilon( ) );\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END( )\n\n} // namespace unit_tests\n\n} // namespace tudat\n\n\n\n\n", "meta": {"hexsha": "b5f716d28e7813b7ab984fe532e5cbe30083196a", "size": 11771, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/src/interface/sofa/unitTestSofaTimeConversions.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": "tests/src/interface/sofa/unitTestSofaTimeConversions.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": "tests/src/interface/sofa/unitTestSofaTimeConversions.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": 39.1063122924, "max_line_length": 118, "alphanum_fraction": 0.5929827542, "num_tokens": 3523, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4577434395931203}}
{"text": "#include <frovedis.hpp>\n#include <frovedis/matrix/dense_eigen.hpp>\n#include <boost/program_options.hpp>\n\nusing namespace boost;\nusing namespace frovedis;\nusing namespace std;\n\n/*\n  input: m x n\n  u: m x k (<-m)\n  s: k(<-m) x k(<-n)\n  vt: k(<-n) x n / v: n x k\n */\nvoid do_dense_eigen_sym(const string& input_matrix, const string& d_file,\n                         const string& v_file, string mode, int k,\n                         bool binary) {\n  time_spent t(DEBUG);\n  rowmajor_matrix<double> matrix;\n  if(binary) {\n    matrix = make_rowmajor_matrix_loadbinary<double>(input_matrix);\n  } else {\n    matrix = make_rowmajor_matrix_load<double>(input_matrix);\n  }\n  t.show(\"load time: \");\n  colmajor_matrix<double> v;\n  diag_matrix_local<double> d;\n  time_spent t2(DEBUG), t3(DEBUG);\n  dense_eigen_sym<double>(matrix, d, v, mode, k); \n  t2.show(\"dense_eigen_sym: \");\n  t3.show(\"total time w/o I/O: \");\n  if(binary) {\n    d.savebinary(d_file);\n    v.to_rowmajor().savebinary(v_file);\n  } else {\n    d.save(d_file);\n    v.to_rowmajor().save(v_file);\n  }\n  t2.show(\"save time: \");\n}\n\nint main(int argc, char* argv[]) {\n  use_frovedis use(argc, argv);\n\n  using namespace boost::program_options;\n\n  options_description opt(\"option\");\n  opt.add_options()\n    (\"help,h\", \"print help\")\n    (\"input,i\", value<string>(), \"input dense data matrix\")\n    (\"d,d\", value<string>(), \"eigen values to save\")\n    (\"v,v\", value<string>(), \"eigen vectors to save\")\n    (\"k,k\", value<int>(), \"number of eigen values to compute\")\n    (\"mode\", value<string>(), \"SM: from small, LM: from large, etc. [default: SM]\")\n    (\"verbose\", \"set loglevel DEBUG\")\n    (\"verbose2\", \"set loglevel TRACE\")\n    (\"binary,b\", \"use binary input/output\");\n\n  variables_map argmap;\n  store(command_line_parser(argc,argv).options(opt).allow_unregistered().\n        run(), argmap);\n  notify(argmap);\n\n  string input, d, v;\n  int k;\n  bool binary = false;\n\n  string mode = \"SM\";\n  \n  if(argmap.count(\"help\")){\n    cerr << opt << endl;\n    exit(1);\n  }\n\n  if(argmap.count(\"input\")){\n    input = argmap[\"input\"].as<string>();\n  } else {\n    cerr << \"input is not specified\" << endl;\n    cerr << opt << endl;\n    exit(1);\n  }\n\n  if(argmap.count(\"d\")){\n    d = argmap[\"d\"].as<string>();\n  } else {\n    cerr << \"file to store eigen value is not specified\" << endl;\n    cerr << opt << endl;\n    exit(1);\n  }\n\n  if(argmap.count(\"v\")){\n    v = argmap[\"v\"].as<string>();\n  } else {\n    cerr << \"file to store eigen vector is not specified\" << endl;\n    cerr << opt << endl;\n    exit(1);\n  }\n\n  if(argmap.count(\"mode\")){\n    mode = argmap[\"mode\"].as<string>();\n  } \n\n  if(argmap.count(\"k\")){\n    k = argmap[\"k\"].as<int>();\n  } else {\n    cerr << \"number of eigen values to compute is not specified\" << endl;\n    cerr << opt << endl;\n    exit(1);\n  }\n\n  if(argmap.count(\"binary\")){\n    binary = true;\n  }\n\n  if(argmap.count(\"verbose\")){\n    set_loglevel(DEBUG);\n  }\n\n  if(argmap.count(\"verbose2\")){\n    set_loglevel(TRACE);\n  }\n\n  do_dense_eigen_sym(input, d, v, mode, k, binary);\n}\n", "meta": {"hexsha": "290f97bdc4cd63cfc248f12a0c5a0df1fd4a3471", "size": 3024, "ext": "cc", "lang": "C++", "max_stars_repo_path": "samples/eigen/eigen.cc", "max_stars_repo_name": "XpressAI/frovedis", "max_stars_repo_head_hexsha": "bda0f2c688fb832671c5b542dd8df1c9657642ff", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 63.0, "max_stars_repo_stars_event_min_datetime": "2018-06-21T14:11:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T11:24:36.000Z", "max_issues_repo_path": "samples/eigen/eigen.cc", "max_issues_repo_name": "XpressAI/frovedis", "max_issues_repo_head_hexsha": "bda0f2c688fb832671c5b542dd8df1c9657642ff", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2018-09-22T14:01:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-27T16:11:05.000Z", "max_forks_repo_path": "samples/eigen/eigen.cc", "max_forks_repo_name": "XpressAI/frovedis", "max_forks_repo_head_hexsha": "bda0f2c688fb832671c5b542dd8df1c9657642ff", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2018-08-23T15:59:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T06:47:22.000Z", "avg_line_length": 24.192, "max_line_length": 83, "alphanum_fraction": 0.6005291005, "num_tokens": 863, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.4577334612508736}}
{"text": "\r\n#include <NTL/ZZ.h>\r\n#include <NTL/vec_ZZ.h>\r\n#include <NTL/Lazy.h>\r\n#include <NTL/fileio.h>\r\n\r\n\r\n\r\nNTL_START_IMPL\r\n\r\n\r\n\r\n\r\n\r\nconst ZZ& ZZ::zero()\r\n{\r\n   NTL_THREAD_LOCAL static ZZ z;\r\n   return z;\r\n}\r\n\r\n\r\nconst ZZ& ZZ_expo(long e)\r\n{\r\n   NTL_THREAD_LOCAL static ZZ expo_helper;\r\n   conv(expo_helper, e);\r\n   return expo_helper;\r\n}\r\n\r\n\r\n\r\nvoid AddMod(ZZ& x, const ZZ& a, long b, const ZZ& n)\r\n{\r\n   NTL_ZZRegister(B);\r\n   conv(B, b);\r\n   AddMod(x, a, B, n);\r\n}\r\n\r\n\r\nvoid SubMod(ZZ& x, const ZZ& a, long b, const ZZ& n)\r\n{\r\n   NTL_ZZRegister(B);\r\n   conv(B, b);\r\n   SubMod(x, a, B, n);\r\n}\r\n\r\nvoid SubMod(ZZ& x, long a, const ZZ& b, const ZZ& n)\r\n{\r\n   NTL_ZZRegister(A);\r\n   conv(A, a);\r\n   SubMod(x, A, b, n);\r\n}\r\n\r\n\r\n\r\n// ****** input and output\r\n\r\nNTL_THREAD_LOCAL static long iodigits = 0;\r\nNTL_THREAD_LOCAL static long ioradix = 0;\r\n\r\n// iodigits is the greatest integer such that 10^{iodigits} < NTL_WSP_BOUND\r\n// ioradix = 10^{iodigits}\r\n\r\nstatic void InitZZIO()\r\n{\r\n   long x;\r\n\r\n   x = (NTL_WSP_BOUND-1)/10;\r\n   iodigits = 0;\r\n   ioradix = 1;\r\n\r\n   while (x) {\r\n      x = x / 10;\r\n      iodigits++;\r\n      ioradix = ioradix * 10;\r\n   }\r\n\r\n   if (iodigits <= 0) TerminalError(\"problem with I/O\");\r\n}\r\n\r\n\r\nistream& operator>>(istream& s, ZZ& x)\r\n{\r\n   long c;\r\n   long cval;\r\n   long sign;\r\n   long ndigits;\r\n   long acc;\r\n   NTL_ZZRegister(a);\r\n\r\n   if (!s) NTL_INPUT_ERROR(s, \"bad ZZ input\");\r\n\r\n   if (!iodigits) InitZZIO();\r\n\r\n   a = 0;\r\n\r\n   SkipWhiteSpace(s);\r\n   c = s.peek();\r\n\r\n   if (c == '-') {\r\n      sign = -1;\r\n      s.get();\r\n      c = s.peek();\r\n   }\r\n   else\r\n      sign = 1;\r\n\r\n   cval = CharToIntVal(c);\r\n\r\n   if (cval < 0 || cval > 9) NTL_INPUT_ERROR(s, \"bad ZZ input\");\r\n\r\n   ndigits = 0;\r\n   acc = 0;\r\n   while (cval >= 0 && cval <= 9) {\r\n      acc = acc*10 + cval;\r\n      ndigits++;\r\n\r\n      if (ndigits == iodigits) {\r\n         mul(a, a, ioradix);\r\n         add(a, a, acc);\r\n         ndigits = 0;\r\n         acc = 0;\r\n      }\r\n\r\n      s.get();\r\n      c = s.peek();\r\n      cval = CharToIntVal(c);\r\n   }\r\n\r\n   if (ndigits != 0) {\r\n      long mpy = 1;\r\n      while (ndigits > 0) {\r\n         mpy = mpy * 10;\r\n         ndigits--;\r\n      }\r\n\r\n      mul(a, a, mpy);\r\n      add(a, a, acc);\r\n   }\r\n\r\n   if (sign == -1)\r\n      negate(a, a);\r\n\r\n   x = a;\r\n   return s;\r\n}\r\n\r\n\r\n// The class _ZZ_local_stack should be defined in an empty namespace,\r\n// but since I don't want to rely on namespaces, we just give it a funny \r\n// name to avoid accidental name clashes.\r\n\r\nstruct _ZZ_local_stack {\r\n   long top;\r\n   Vec<long> data;\r\n\r\n   _ZZ_local_stack() { top = -1; }\r\n\r\n   long pop() { return data[top--]; }\r\n   long empty() { return (top == -1); }\r\n   void push(long x);\r\n};\r\n\r\nvoid _ZZ_local_stack::push(long x)\r\n{\r\n   if (top+1 >= data.length()) \r\n      data.SetLength(max(32, long(1.414*data.length())));\r\n\r\n   top++;\r\n   data[top] = x;\r\n}\r\n\r\n\r\nstatic\r\nvoid PrintDigits(ostream& s, long d, long justify)\r\n{\r\n   NTL_THREAD_LOCAL static Vec<char> buf(INIT_SIZE, iodigits);\r\n\r\n   long i = 0;\r\n\r\n   while (d) {\r\n      buf[i] = IntValToChar(d % 10);\r\n      d = d / 10;\r\n      i++;\r\n   }\r\n\r\n   if (justify) {\r\n      long j = iodigits - i;\r\n      while (j > 0) {\r\n         s << \"0\";\r\n         j--;\r\n      }\r\n   }\r\n\r\n   while (i > 0) {\r\n      i--;\r\n      s << buf[i];\r\n   }\r\n}\r\n      \r\n\r\n   \r\n\r\nostream& operator<<(ostream& s, const ZZ& a)\r\n{\r\n   ZZ b;\r\n   _ZZ_local_stack S;\r\n   long r;\r\n   long k;\r\n\r\n   if (!iodigits) InitZZIO();\r\n\r\n   b = a;\r\n\r\n   k = sign(b);\r\n\r\n   if (k == 0) {\r\n      s << \"0\";\r\n      return s;\r\n   }\r\n\r\n   if (k < 0) {\r\n      s << \"-\";\r\n      negate(b, b);\r\n   }\r\n\r\n   do {\r\n      r = DivRem(b, b, ioradix);\r\n      S.push(r);\r\n   } while (!IsZero(b));\r\n\r\n   r = S.pop();\r\n   PrintDigits(s, r, 0);\r\n\r\n   while (!S.empty()) {\r\n      r = S.pop();\r\n      PrintDigits(s, r, 1);\r\n   }\r\n      \r\n   return s;\r\n}\r\n\r\n\r\n\r\nlong GCD(long a, long b)\r\n{\r\n   long u, v, t, x;\r\n\r\n   if (a < 0) {\r\n      if (a < -NTL_MAX_LONG) ResourceError(\"GCD: integer overflow\");\r\n      a = -a;\r\n   }\r\n\r\n   if (b < 0) {\r\n      if (b < -NTL_MAX_LONG) ResourceError(\"GCD: integer overflow\");\r\n      b = -b;\r\n   }\r\n\r\n\r\n   if (b==0)\r\n      x = a;\r\n   else {\r\n      u = a;\r\n      v = b;\r\n      do {\r\n         t = u % v;\r\n         u = v; \r\n         v = t;\r\n      } while (v != 0);\r\n\r\n      x = u;\r\n   }\r\n\r\n   return x;\r\n}\r\n\r\n         \r\n\r\nvoid XGCD(long& d, long& s, long& t, long a, long b)\r\n{\r\n   long  u, v, u0, v0, u1, v1, u2, v2, q, r;\r\n\r\n   long aneg = 0, bneg = 0;\r\n\r\n   if (a < 0) {\r\n      if (a < -NTL_MAX_LONG) ResourceError(\"XGCD: integer overflow\");\r\n      a = -a;\r\n      aneg = 1;\r\n   }\r\n\r\n   if (b < 0) {\r\n      if (b < -NTL_MAX_LONG) ResourceError(\"XGCD: integer overflow\");\r\n      b = -b;\r\n      bneg = 1;\r\n   }\r\n\r\n   u1=1; v1=0;\r\n   u2=0; v2=1;\r\n   u = a; v = b;\r\n\r\n   while (v != 0) {\r\n      q = u / v;\r\n      r = u % v;\r\n      u = v;\r\n      v = r;\r\n      u0 = u2;\r\n      v0 = v2;\r\n      u2 =  u1 - q*u2;\r\n      v2 = v1- q*v2;\r\n      u1 = u0;\r\n      v1 = v0;\r\n   }\r\n\r\n   if (aneg)\r\n      u1 = -u1;\r\n\r\n   if (bneg)\r\n      v1 = -v1;\r\n\r\n   d = u;\r\n   s = u1;\r\n   t = v1;\r\n}\r\n   \r\n\r\nlong InvMod(long a, long n)\r\n{\r\n   long d, s, t;\r\n\r\n   XGCD(d, s, t, a, n);\r\n   if (d != 1) InvModError(\"InvMod: inverse undefined\");\r\n   if (s < 0)\r\n      return s + n;\r\n   else\r\n      return s;\r\n}\r\n\r\n\r\nlong PowerMod(long a, long ee, long n)\r\n{\r\n   long x, y;\r\n\r\n   unsigned long e;\r\n\r\n   if (ee < 0)\r\n      e = - ((unsigned long) ee);\r\n   else\r\n      e = ee;\r\n\r\n   x = 1;\r\n   y = a;\r\n   while (e) {\r\n      if (e & 1) x = MulMod(x, y, n);\r\n      y = MulMod(y, y, n);\r\n      e = e >> 1;\r\n   }\r\n\r\n   if (ee < 0) x = InvMod(x, n);\r\n\r\n   return x;\r\n}\r\n\r\nlong ProbPrime(long n, long NumTests)\r\n{\r\n   long m, x, y, z;\r\n   long i, j, k;\r\n\r\n   if (n <= 1) return 0;\r\n\r\n\r\n   if (n == 2) return 1;\r\n   if (n % 2 == 0) return 0;\r\n\r\n   if (n == 3) return 1;\r\n   if (n % 3 == 0) return 0;\r\n\r\n   if (n == 5) return 1;\r\n   if (n % 5 == 0) return 0;\r\n\r\n   if (n == 7) return 1;\r\n   if (n % 7 == 0) return 0;\r\n\r\n   if (n >= NTL_SP_BOUND) {\r\n      return ProbPrime(to_ZZ(n), NumTests);\r\n   }\r\n\r\n   m = n - 1;\r\n   k = 0;\r\n   while((m & 1) == 0) {\r\n      m = m >> 1;\r\n      k++;\r\n   }\r\n\r\n   // n - 1 == 2^k * m, m odd\r\n\r\n   for (i = 0; i < NumTests; i++) {\r\n      do {\r\n         x = RandomBnd(n);\r\n      } while (x == 0);\r\n      // x == 0 is not a useful candidtae for a witness!\r\n\r\n\r\n      if (x == 0) continue;\r\n      z = PowerMod(x, m, n);\r\n      if (z == 1) continue;\r\n   \r\n      j = 0;\r\n      do {\r\n         y = z;\r\n         z = MulMod(y, y, n);\r\n         j++;\r\n      } while (j != k && z != 1);\r\n\r\n      if (z != 1 || y !=  n-1) return 0;\r\n   }\r\n\r\n   return 1;\r\n}\r\n\r\n\r\nlong MillerWitness(const ZZ& n, const ZZ& x)\r\n{\r\n   ZZ m, y, z;\r\n   long j, k;\r\n\r\n   if (x == 0) return 0;\r\n\r\n   add(m, n, -1);\r\n   k = MakeOdd(m);\r\n   // n - 1 == 2^k * m, m odd\r\n\r\n   PowerMod(z, x, m, n);\r\n   if (z == 1) return 0;\r\n\r\n   j = 0;\r\n   do {\r\n      y = z;\r\n      SqrMod(z, y, n);\r\n      j++;\r\n   } while (j != k && z != 1);\r\n\r\n   if (z != 1) return 1;\r\n   add(y, y, 1);\r\n   if (y != n) return 1;\r\n   return 0;\r\n}\r\n\r\n\r\n// ComputePrimeBound computes a reasonable bound for trial\r\n// division in the Miller-Rabin test.\r\n// It is computed a bit on the \"low\" side, since being a bit\r\n// low doesn't hurt much, but being too high can hurt a lot.\r\n\r\nstatic\r\nlong ComputePrimeBound(long bn)\r\n{\r\n   long wn = (bn+NTL_ZZ_NBITS-1)/NTL_ZZ_NBITS;\r\n\r\n   long fn;\r\n\r\n   if (wn <= 36)\r\n      fn = wn/4 + 1;\r\n   else\r\n      fn = long(1.67*sqrt(double(wn)));\r\n\r\n   long prime_bnd;\r\n\r\n   if (NumBits(bn) + NumBits(fn) > NTL_SP_NBITS)\r\n      prime_bnd = NTL_SP_BOUND;\r\n   else\r\n      prime_bnd = bn*fn;\r\n\r\n   return prime_bnd;\r\n}\r\n\r\n\r\nlong ProbPrime(const ZZ& n, long NumTrials)\r\n{\r\n   if (n <= 1) return 0;\r\n\r\n   if (n.SinglePrecision()) {\r\n      return ProbPrime(to_long(n), NumTrials);\r\n   }\r\n\r\n\r\n   long prime_bnd = ComputePrimeBound(NumBits(n));\r\n\r\n\r\n   PrimeSeq s;\r\n   long p;\r\n\r\n   p = s.next();\r\n   while (p && p < prime_bnd) {\r\n      if (rem(n, p) == 0)\r\n         return 0;\r\n\r\n      p = s.next();\r\n   }\r\n\r\n   ZZ W;\r\n   W = 2;\r\n\r\n   // first try W == 2....the exponentiation\r\n   // algorithm runs slightly faster in this case\r\n\r\n   if (MillerWitness(n, W))\r\n      return 0;\r\n\r\n\r\n   long i;\r\n\r\n   for (i = 0; i < NumTrials; i++) {\r\n      do {\r\n         RandomBnd(W, n);\r\n      } while (W == 0);\r\n      // W == 0 is not a useful candidate for a witness!\r\n\r\n      if (MillerWitness(n, W)) \r\n         return 0;\r\n   }\r\n\r\n   return 1;\r\n}\r\n\r\n\r\nvoid RandomPrime(ZZ& n, long l, long NumTrials)\r\n{\r\n   if (l <= 1)\r\n      LogicError(\"RandomPrime: l out of range\");\r\n\r\n   if (l == 2) {\r\n      if (RandomBnd(2))\r\n         n = 3;\r\n      else\r\n         n = 2;\r\n\r\n      return;\r\n   }\r\n\r\n   do {\r\n      RandomLen(n, l);\r\n      if (!IsOdd(n)) add(n, n, 1);\r\n   } while (!ProbPrime(n, NumTrials));\r\n}\r\n\r\nvoid NextPrime(ZZ& n, const ZZ& m, long NumTrials)\r\n{\r\n   ZZ x;\r\n\r\n   if (m <= 2) {\r\n      n = 2;\r\n      return;\r\n   }\r\n\r\n   x = m;\r\n\r\n   while (!ProbPrime(x, NumTrials))\r\n      add(x, x, 1);\r\n\r\n   n = x;\r\n}\r\n\r\nlong NextPrime(long m, long NumTrials)\r\n{\r\n   long x;\r\n\r\n   if (m <= 2) \r\n      return 2;\r\n\r\n   x = m;\r\n\r\n   while (x < NTL_SP_BOUND && !ProbPrime(x, NumTrials))\r\n      x++;\r\n\r\n   if (x >= NTL_SP_BOUND)\r\n      ResourceError(\"NextPrime: no more primes\");\r\n\r\n   return x;\r\n}\r\n\r\n\r\n\r\nlong NextPowerOfTwo(long m)\r\n{\r\n   long k; \r\n   unsigned long n, um;\r\n\r\n   if (m < 0) return 0;\r\n\r\n   um = m;\r\n   n = 1;\r\n   k = 0;\r\n\r\n   while (n < um) {\r\n      n = n << 1;\r\n      k++;\r\n   }\r\n\r\n   if (k >= NTL_BITS_PER_LONG-1)\r\n      ResourceError(\"NextPowerOfTwo: overflow\");\r\n\r\n   return k;\r\n}\r\n\r\n\r\n\r\nlong NumBits(long a)\r\n{\r\n   unsigned long aa;\r\n   if (a < 0) \r\n      aa = - ((unsigned long) a);\r\n   else\r\n      aa = a;\r\n\r\n   long k = 0;\r\n   while (aa) {\r\n      k++;\r\n      aa = aa >> 1;\r\n   }\r\n\r\n   return k;\r\n}\r\n\r\n\r\nlong bit(long a, long k)\r\n{\r\n   unsigned long aa;\r\n   if (a < 0)\r\n      aa = - ((unsigned long) a);\r\n   else\r\n      aa = a;\r\n\r\n   if (k < 0 || k >= NTL_BITS_PER_LONG) \r\n      return 0;\r\n   else\r\n      return long((aa >> k) & 1);\r\n}\r\n\r\n\r\n\r\nlong divide(ZZ& q, const ZZ& a, const ZZ& b)\r\n{\r\n   NTL_ZZRegister(qq);\r\n   NTL_ZZRegister(r);\r\n\r\n   if (IsZero(b)) {\r\n      if (IsZero(a)) {\r\n         clear(q);\r\n         return 1;\r\n      }\r\n      else\r\n         return 0;\r\n   }\r\n\r\n\r\n   if (IsOne(b)) {\r\n      q = a;\r\n      return 1;\r\n   }\r\n\r\n   DivRem(qq, r, a, b);\r\n   if (!IsZero(r)) return 0;\r\n   q = qq;\r\n   return 1;\r\n}\r\n\r\nlong divide(const ZZ& a, const ZZ& b)\r\n{\r\n   NTL_ZZRegister(r);\r\n\r\n   if (IsZero(b)) return IsZero(a);\r\n   if (IsOne(b)) return 1;\r\n\r\n   rem(r, a, b);\r\n   return IsZero(r);\r\n}\r\n\r\nlong divide(ZZ& q, const ZZ& a, long b)\r\n{\r\n   NTL_ZZRegister(qq);\r\n\r\n   if (!b) {\r\n      if (IsZero(a)) {\r\n         clear(q);\r\n         return 1;\r\n      }\r\n      else\r\n         return 0;\r\n   }\r\n\r\n   if (b == 1) {\r\n      q = a;\r\n      return 1;\r\n   }\r\n\r\n   long r = DivRem(qq, a, b);\r\n   if (r) return 0;\r\n   q = qq;\r\n   return 1;\r\n}\r\n\r\nlong divide(const ZZ& a, long b)\r\n{\r\n   if (!b) return IsZero(a);\r\n   if (b == 1) {\r\n      return 1;\r\n   }\r\n\r\n   long r = rem(a,  b);\r\n   return (r == 0);\r\n}\r\n\r\n\r\nvoid InvMod(ZZ& x, const ZZ& a, const ZZ& n)\r\n{\r\n   // NOTE: the underlying LIP routines write to the first argument,\r\n   // even if inverse is undefined\r\n\r\n   NTL_ZZRegister(xx);\r\n   if (InvModStatus(xx, a, n)) \r\n      InvModError(\"InvMod: inverse undefined\", a, n);\r\n   x = xx;\r\n}\r\n\r\nvoid PowerMod(ZZ& x, const ZZ& a, const ZZ& e, const ZZ& n)\r\n{\r\n   // NOTE: this ensures that all modular inverses are computed\r\n   // in the routine InvMod above, rather than the LIP-internal\r\n   // modular inverse routine\r\n   if (e < 0) {\r\n      ZZ a_inv;\r\n      ZZ e_neg;\r\n\r\n      InvMod(a_inv, a, n);\r\n      negate(e_neg, e);\r\n      LowLevelPowerMod(x, a_inv, e_neg, n);\r\n   }\r\n   else\r\n      LowLevelPowerMod(x, a, e, n); \r\n}\r\n   \r\n#ifdef NTL_EXCEPTIONS\r\n\r\nvoid InvModError(const char *s, const ZZ& a, const ZZ& n)\r\n{\r\n   throw InvModErrorObject(s, a, n); \r\n}\r\n\r\n#else\r\n\r\nvoid InvModError(const char *s, const ZZ& a, const ZZ& n)\r\n{\r\n   TerminalError(s);\r\n}\r\n\r\n\r\n#endif\r\n\r\nlong RandomPrime_long(long l, long NumTrials)\r\n{\r\n   if (l <= 1 || l >= NTL_BITS_PER_LONG)\r\n      ResourceError(\"RandomPrime: length out of range\");\r\n\r\n   long n;\r\n   do {\r\n      n = RandomLen_long(l);\r\n   } while (!ProbPrime(n, NumTrials));\r\n\r\n   return n;\r\n}\r\n\r\n\r\nstatic Lazy< Vec<char> > lowsieve_storage;\r\n// This is a GLOBAL VARIABLE\r\n\r\n\r\nPrimeSeq::PrimeSeq()\r\n{\r\n   movesieve = 0;\r\n   pshift = -1;\r\n   pindex = -1;\r\n   exhausted = 0;\r\n}\r\n\r\n\r\nlong PrimeSeq::next()\r\n{\r\n   if (exhausted) {\r\n      return 0;\r\n   }\r\n\r\n   if (pshift < 0) {\r\n      shift(0);\r\n      return 2;\r\n   }\r\n\r\n   for (;;) {\r\n      const char *p = movesieve;\r\n      long i = pindex;\r\n\r\n      while ((++i) < NTL_PRIME_BND) {\r\n         if (p[i]) {\r\n            pindex = i;\r\n            return pshift + 2 * i + 3;\r\n         }\r\n      }\r\n\r\n      long newshift = pshift + 2*NTL_PRIME_BND;\r\n\r\n      if (newshift > 2 * NTL_PRIME_BND * (2 * NTL_PRIME_BND + 1)) {\r\n         /* end of the road */\r\n         exhausted = 1;\r\n         return 0;\r\n      }\r\n\r\n      shift(newshift);\r\n   }\r\n}\r\n\r\nvoid PrimeSeq::shift(long newshift)\r\n{\r\n   long i;\r\n   long j;\r\n   long jstep;\r\n   long jstart;\r\n   long ibound;\r\n   char *p;\r\n\r\n   if (!lowsieve_storage.built())\r\n      start();\r\n\r\n   const char *lowsieve = lowsieve_storage->elts();\r\n\r\n\r\n   if (newshift < 0) {\r\n      pshift = -1;\r\n   }\r\n   else if (newshift == 0) {\r\n      pshift = 0;\r\n      movesieve = lowsieve;\r\n   } \r\n   else if (newshift != pshift) {\r\n      if (movesieve_mem.length() == 0) {\r\n         movesieve_mem.SetLength(NTL_PRIME_BND);\r\n      }\r\n\r\n      pshift = newshift;\r\n      movesieve = p = movesieve_mem.elts();\r\n      for (i = 0; i < NTL_PRIME_BND; i++)\r\n         p[i] = 1;\r\n\r\n      jstep = 3;\r\n      ibound = pshift + 2 * NTL_PRIME_BND + 1;\r\n      for (i = 0; jstep * jstep <= ibound; i++) {\r\n         if (lowsieve[i]) {\r\n            if (!((jstart = (pshift + 2) / jstep + 1) & 1))\r\n               jstart++;\r\n            if (jstart <= jstep)\r\n               jstart = jstep;\r\n            jstart = (jstart * jstep - pshift - 3) / 2;\r\n            for (j = jstart; j < NTL_PRIME_BND; j += jstep)\r\n               p[j] = 0;\r\n         }\r\n         jstep += 2;\r\n      }\r\n   }\r\n\r\n   pindex = -1;\r\n   exhausted = 0;\r\n}\r\n\r\n\r\nvoid PrimeSeq::start()\r\n{\r\n   long i;\r\n   long j;\r\n   long jstep;\r\n   long jstart;\r\n   long ibnd;\r\n   char *p;\r\n\r\n   do {\r\n      Lazy< Vec<char> >::Builder builder(lowsieve_storage);\r\n      if (!builder()) break;\r\n\r\n      UniquePtr< Vec<char> > ptr;\r\n      ptr.make();\r\n      ptr->SetLength(NTL_PRIME_BND);\r\n\r\n      p = ptr->elts();\r\n\r\n      for (i = 0; i < NTL_PRIME_BND; i++)\r\n         p[i] = 1;\r\n         \r\n      jstep = 1;\r\n      jstart = -1;\r\n      ibnd = (SqrRoot(2 * NTL_PRIME_BND + 1) - 3) / 2;\r\n      for (i = 0; i <= ibnd; i++) {\r\n         jstart += 2 * ((jstep += 2) - 1);\r\n         if (p[i])\r\n            for (j = jstart; j < NTL_PRIME_BND; j += jstep)\r\n               p[j] = 0;\r\n      }\r\n\r\n      builder.move(ptr);\r\n   } while (0);\r\n\r\n}\r\n\r\nvoid PrimeSeq::reset(long b)\r\n{\r\n   if (b > (2*NTL_PRIME_BND+1)*(2*NTL_PRIME_BND+1)) {\r\n      exhausted = 1;\r\n      return;\r\n   }\r\n\r\n   if (b <= 2) {\r\n      shift(-1);\r\n      return;\r\n   }\r\n\r\n   if ((b & 1) == 0) b++;\r\n\r\n   shift(((b-3) / (2*NTL_PRIME_BND))* (2*NTL_PRIME_BND));\r\n   pindex = (b - pshift - 3)/2 - 1;\r\n}\r\n \r\nlong Jacobi(const ZZ& aa, const ZZ& nn)\r\n{\r\n   ZZ a, n;\r\n   long t, k;\r\n   long d;\r\n\r\n   a = aa;\r\n   n = nn;\r\n   t = 1;\r\n\r\n   while (a != 0) {\r\n      k = MakeOdd(a);\r\n      d = trunc_long(n, 3);\r\n      if ((k & 1) && (d == 3 || d == 5)) t = -t;\r\n\r\n      if (trunc_long(a, 2) == 3 && (d & 3) == 3) t = -t;\r\n      swap(a, n);\r\n      rem(a, a, n);\r\n   }\r\n\r\n   if (n == 1)\r\n      return t;\r\n   else\r\n      return 0;\r\n}\r\n\r\n\r\nvoid SqrRootMod(ZZ& x, const ZZ& aa, const ZZ& nn)\r\n{\r\n   if (aa == 0 || aa == 1) {\r\n      x = aa;\r\n      return;\r\n   }\r\n\r\n   // at this point, we must have nn >= 5\r\n\r\n   if (trunc_long(nn, 2) == 3) {  // special case, n = 3 (mod 4)\r\n      ZZ n, a, e, z;\r\n\r\n      n = nn;\r\n      a  = aa;\r\n\r\n      add(e, n, 1);\r\n      RightShift(e, e, 2);\r\n\r\n      PowerMod(z, a, e, n);\r\n      x = z;\r\n\r\n      return;\r\n   }\r\n\r\n   ZZ n, m;\r\n   int h, nlen;\r\n\r\n   n = nn;\r\n   nlen = NumBits(n);\r\n\r\n   sub(m, n, 1);\r\n   h = MakeOdd(m);  // h >= 2\r\n\r\n\r\n   if (nlen > 50 && h < SqrRoot(nlen)) {\r\n      long i, j;\r\n      ZZ a, b, a_inv, c, r, m1, d;\r\n\r\n      a = aa;\r\n      InvMod(a_inv, a, n);\r\n\r\n      if (h == 2) \r\n         b = 2;\r\n      else {\r\n         do {\r\n            RandomBnd(b, n);\r\n         } while (Jacobi(b, n) != -1);\r\n      }\r\n\r\n\r\n      PowerMod(c, b, m, n);\r\n      \r\n      add(m1, m, 1);\r\n      RightShift(m1, m1, 1);\r\n      PowerMod(r, a, m1, n);\r\n\r\n      for (i = h-2; i >= 0; i--) {\r\n         SqrMod(d, r, n);\r\n         MulMod(d, d, a_inv, n);\r\n         for (j = 0; j < i; j++)\r\n            SqrMod(d, d, n);\r\n         if (!IsOne(d))\r\n            MulMod(r, r, c, n);\r\n         SqrMod(c, c, n);\r\n      } \r\n\r\n      x = r;\r\n      return;\r\n   } \r\n\r\n\r\n\r\n\r\n\r\n   long i, k;\r\n   ZZ ma, t, u, v, e;\r\n   ZZ t1, t2, t3, t4;\r\n\r\n   n = nn;\r\n   NegateMod(ma, aa, n);\r\n\r\n   // find t such that t^2 - 4*a is not a square\r\n\r\n   MulMod(t1, ma, 4, n);\r\n   do {\r\n      RandomBnd(t, n);\r\n      SqrMod(t2, t, n);\r\n      AddMod(t2, t2, t1, n);\r\n   } while (Jacobi(t2, n) != -1);\r\n\r\n   // compute u*X + v = X^{(n+1)/2} mod f, where f = X^2 - t*X + a\r\n\r\n   add(e, n, 1);\r\n   RightShift(e, e, 1);\r\n\r\n   u = 0;\r\n   v = 1;\r\n\r\n   k = NumBits(e);\r\n\r\n   for (i = k - 1; i >= 0; i--) {\r\n      add(t2, u, v);\r\n      sqr(t3, t2);  // t3 = (u+v)^2\r\n      sqr(t1, u);\r\n      sqr(t2, v);\r\n      sub(t3, t3, t1);\r\n      sub(t3, t3, t2); // t1 = u^2, t2 = v^2, t3 = 2*u*v\r\n      rem(t1, t1, n);\r\n      mul(t4, t1, t);\r\n      add(t4, t4, t3);\r\n      rem(u, t4, n);\r\n\r\n      mul(t4, t1, ma);\r\n      add(t4, t4, t2);\r\n      rem(v, t4, n);\r\n      \r\n      if (bit(e, i)) {\r\n         MulMod(t1, u, t, n);\r\n         AddMod(t1, t1, v, n);\r\n         MulMod(v, u, ma, n);\r\n         u = t1;\r\n      }\r\n\r\n   }\r\n\r\n   x = v;\r\n}\r\n\r\n\r\n\r\n// Chinese Remaindering.\r\n//\r\n// This version in new to v3.7, and is significantly\r\n// simpler and faster than the previous version.\r\n//\r\n// This function takes as input g, a, G, p,\r\n// such that a > 0, 0 <= G < p, and gcd(a, p) = 1.\r\n// It computes a' = a*p and g' such that \r\n//   * g' = g (mod a);\r\n//   * g' = G (mod p);\r\n//   * -a'/2 < g' <= a'/2.\r\n// It then sets g := g' and a := a', and returns 1 iff g has changed.\r\n//\r\n// Under normal use, the input value g satisfies -a/2 < g <= a/2;\r\n// however, this was not documented or enforced in earlier versions,\r\n// so to maintain backward compatability, no restrictions are placed\r\n// on g.  This routine runs faster, though, if -a/2 < g <= a/2,\r\n// and the first thing the routine does is to make this condition\r\n// hold.\r\n//\r\n// Also, under normal use, both a and p are odd;  however, the routine\r\n// will still work even if this is not so.\r\n//\r\n// The routine is based on the following simple fact.\r\n//\r\n// Let -a/2 < g <= a/2, and let h satisfy\r\n//   * g + a h = G (mod p);\r\n//   * -p/2 < h <= p/2.\r\n// Further, if p = 2*h and g > 0, set\r\n//   g' := g - a h;\r\n// otherwise, set\r\n//   g' := g + a h.\r\n// Then g' so defined satisfies the above requirements.\r\n//\r\n// It is trivial to see that g's satisfies the congruence conditions.\r\n// The only thing is to check that the \"balancing\" condition\r\n// -a'/2 < g' <= a'/2 also holds.\r\n\r\n\r\nlong CRT(ZZ& gg, ZZ& a, long G, long p)\r\n{\r\n   if (p >= NTL_SP_BOUND) {\r\n      ZZ GG, pp;\r\n      conv(GG, G);\r\n      conv(pp, p);\r\n      return CRT(gg, a, GG, pp);\r\n   }\r\n\r\n   long modified = 0;\r\n\r\n   NTL_ZZRegister(g);\r\n\r\n   if (!CRTInRange(gg, a)) {\r\n      modified = 1;\r\n      ZZ a1;\r\n      rem(g, gg, a);\r\n      RightShift(a1, a, 1);\r\n      if (g > a1) sub(g, g, a);\r\n   }\r\n   else\r\n      g = gg;\r\n\r\n\r\n   long p1;\r\n   p1 = p >> 1;\r\n\r\n   long a_inv;\r\n   a_inv = rem(a, p);\r\n   a_inv = InvMod(a_inv, p);\r\n\r\n   long h;\r\n   h = rem(g, p);\r\n   h = SubMod(G, h, p);\r\n   h = MulMod(h, a_inv, p);\r\n   if (h > p1)\r\n      h = h - p;\r\n\r\n   if (h != 0) {\r\n      modified = 1;\r\n\r\n      if (!(p & 1) && g > 0 && (h == p1))\r\n         MulSubFrom(g, a, h);\r\n      else\r\n         MulAddTo(g, a, h);\r\n   }\r\n\r\n   mul(a, a, p);\r\n   gg = g;\r\n\r\n   return modified;\r\n}\r\n\r\nlong CRT(ZZ& gg, ZZ& a, const ZZ& G, const ZZ& p)\r\n{\r\n   long modified = 0;\r\n\r\n   ZZ g;\r\n\r\n   if (!CRTInRange(gg, a)) {\r\n      modified = 1;\r\n      ZZ a1;\r\n      rem(g, gg, a);\r\n      RightShift(a1, a, 1);\r\n      if (g > a1) sub(g, g, a);\r\n   }\r\n   else\r\n      g = gg;\r\n\r\n\r\n   ZZ p1;\r\n   RightShift(p1, p, 1);\r\n\r\n   ZZ a_inv;\r\n   rem(a_inv, a, p);\r\n   InvMod(a_inv, a_inv, p);\r\n\r\n   ZZ h;\r\n   rem(h, g, p);\r\n   SubMod(h, G, h, p);\r\n   MulMod(h, h, a_inv, p);\r\n   if (h > p1)\r\n      sub(h, h, p);\r\n\r\n   if (h != 0) {\r\n      modified = 1;\r\n      ZZ ah;\r\n      mul(ah, a, h);\r\n\r\n      if (!IsOdd(p) && g > 0 &&  (h == p1))\r\n         sub(g, g, ah);\r\n      else\r\n         add(g, g, ah);\r\n   }\r\n\r\n   mul(a, a, p);\r\n   gg = g;\r\n\r\n   return modified;\r\n}\r\n\r\n\r\n\r\nvoid sub(ZZ& x, const ZZ& a, long b)\r\n{\r\n   NTL_ZZRegister(B);\r\n   conv(B, b);\r\n   sub(x, a, B);\r\n}\r\n\r\nvoid sub(ZZ& x, long a, const ZZ& b)\r\n{\r\n   NTL_ZZRegister(A);\r\n   conv(A, a);\r\n   sub(x, A, b);\r\n}\r\n\r\n\r\nvoid power2(ZZ& x, long e)\r\n{\r\n   if (e < 0) ArithmeticError(\"power2: negative exponent\");\r\n   set(x);\r\n   LeftShift(x, x, e);\r\n}\r\n\r\n   \r\nvoid conv(ZZ& x, const char *s)\r\n{\r\n   long c;\r\n   long cval;\r\n   long sign;\r\n   long ndigits;\r\n   long acc;\r\n   long i = 0;\r\n\r\n   NTL_ZZRegister(a);\r\n\r\n   if (!s) InputError(\"bad ZZ input\");\r\n\r\n   if (!iodigits) InitZZIO();\r\n\r\n   a = 0;\r\n\r\n   c = s[i];\r\n   while (IsWhiteSpace(c)) {\r\n      i++;\r\n      c = s[i];\r\n   }\r\n\r\n   if (c == '-') {\r\n      sign = -1;\r\n      i++;\r\n      c = s[i];\r\n   }\r\n   else\r\n      sign = 1;\r\n\r\n   cval = CharToIntVal(c);\r\n   if (cval < 0 || cval > 9) InputError(\"bad ZZ input\");\r\n\r\n   ndigits = 0;\r\n   acc = 0;\r\n   while (cval >= 0 && cval <= 9) {\r\n      acc = acc*10 + cval;\r\n      ndigits++;\r\n\r\n      if (ndigits == iodigits) {\r\n         mul(a, a, ioradix);\r\n         add(a, a, acc);\r\n         ndigits = 0;\r\n         acc = 0;\r\n      }\r\n\r\n      i++;\r\n      c = s[i];\r\n      cval = CharToIntVal(c);\r\n   }\r\n\r\n   if (ndigits != 0) {\r\n      long mpy = 1;\r\n      while (ndigits > 0) {\r\n         mpy = mpy * 10;\r\n         ndigits--;\r\n      }\r\n\r\n      mul(a, a, mpy);\r\n      add(a, a, acc);\r\n   }\r\n\r\n   if (sign == -1)\r\n      negate(a, a);\r\n\r\n   x = a;\r\n}\r\n\r\n\r\n\r\nvoid bit_and(ZZ& x, const ZZ& a, long b)\r\n{\r\n   NTL_ZZRegister(B);\r\n   conv(B, b);\r\n   bit_and(x, a, B);\r\n}\r\n\r\nvoid bit_or(ZZ& x, const ZZ& a, long b)\r\n{\r\n   NTL_ZZRegister(B);\r\n   conv(B, b);\r\n   bit_or(x, a, B);\r\n}\r\n\r\nvoid bit_xor(ZZ& x, const ZZ& a, long b)\r\n{\r\n   NTL_ZZRegister(B);\r\n   conv(B, b);\r\n   bit_xor(x, a, B);\r\n}\r\n\r\n\r\nlong power_long(long a, long e)\r\n{\r\n   if (e < 0) ArithmeticError(\"power_long: negative exponent\");\r\n\r\n   if (e == 0) return 1;\r\n\r\n   if (a == 1) return 1;\r\n   if (a == -1) {\r\n      if (e & 1)\r\n         return -1;\r\n      else\r\n         return 1;\r\n   }\r\n\r\n   // no overflow check --- result is computed correctly\r\n   // modulo word size\r\n\r\n   unsigned long res = 1;\r\n   unsigned long aa = a;\r\n   long i;\r\n\r\n   for (i = 0; i < e; i++)\r\n      res *= aa;\r\n\r\n   return to_long(res);\r\n}\r\n\r\n\r\n\r\n//  RANDOM NUMBER GENERATION\r\n\r\n// Idea for this PRNG.  Iteratively hash seed using md5 \r\n// to get 256 bytes to initialize arc4.\r\n// Then use arc4 to get a pseudo-random byte stream.\r\n\r\n// I've taken care that the pseudo-random numbers generated by\r\n// the routines RandomBnd, RandomBits, and RandomLen \r\n// are completely platform independent.\r\n\r\n// I make use of the md5 compression function,\r\n// which I've modified to work on 64-bit machines\r\n\r\n\r\n/*\r\n *  BEGIN RSA's md5 stuff\r\n *\r\n */\r\n\r\n/*\r\n **********************************************************************\r\n ** md5.c                                                            **\r\n ** RSA Data Security, Inc. MD5 Message Digest Algorithm             **\r\n ** Created: 2/17/90 RLR                                             **\r\n ** Revised: 1/91 SRD,AJ,BSK,JT Reference C Version                  **\r\n **********************************************************************\r\n */\r\n\r\n/*\r\n **********************************************************************\r\n ** Copyright (C) 1990, RSA Data Security, Inc. All rights reserved. **\r\n **                                                                  **\r\n ** License to copy and use this software is granted provided that   **\r\n ** it is identified as the \"RSA Data Security, Inc. MD5 Message     **\r\n ** Digest Algorithm\" in all material mentioning or referencing this **\r\n ** software or this function.                                       **\r\n **                                                                  **\r\n ** License is also granted to make and use derivative works         **\r\n ** provided that such works are identified as \"derived from the RSA **\r\n ** Data Security, Inc. MD5 Message Digest Algorithm\" in all         **\r\n ** material mentioning or referencing the derived work.             **\r\n **                                                                  **\r\n ** RSA Data Security, Inc. makes no representations concerning      **\r\n ** either the merchantability of this software or the suitability   **\r\n ** of this software for any particular purpose.  It is provided \"as **\r\n ** is\" without express or implied warranty of any kind.             **\r\n **                                                                  **\r\n ** These notices must be retained in any copies of any part of this **\r\n ** documentation and/or software.                                   **\r\n **********************************************************************\r\n */\r\n\r\n\r\n#if (NTL_BITS_PER_LONG <= 32)\r\n#define TRUNC32(x) (x)\r\n#else\r\n#define TRUNC32(x) ((x) & ((1UL << 32)-1UL))\r\n#endif\r\n\r\n/* F, G and H are basic MD5 functions: selection, majority, parity */\r\n#define F(x, y, z) (((x) & (y)) | ((~x) & (z)))\r\n#define G(x, y, z) (((x) & (z)) | ((y) & (~z)))\r\n#define H(x, y, z) ((x) ^ (y) ^ (z))\r\n#define I(x, y, z) (TRUNC32((y) ^ ((x) | (~z)))) \r\n\r\n/* ROTATE_LEFT rotates x left n bits */\r\n#define ROTATE_LEFT(x, n) (TRUNC32(((x) << (n)) | ((x) >> (32-(n)))))\r\n\r\n/* FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4 */\r\n/* Rotation is separate from addition to prevent recomputation */\r\n#define FF(a, b, c, d, x, s, ac) \\\r\n  {(a) = TRUNC32((a) + F((b), (c), (d)) + (x) + (ac)); \\\r\n   (a) = ROTATE_LEFT((a), (s)); \\\r\n   (a) = TRUNC32((a) + (b)); \\\r\n  }\r\n#define GG(a, b, c, d, x, s, ac) \\\r\n  {(a) = TRUNC32((a) + G((b), (c), (d)) + (x) + (ac)); \\\r\n   (a) = ROTATE_LEFT((a), (s)); \\\r\n   (a) = TRUNC32((a) + (b)); \\\r\n  }\r\n#define HH(a, b, c, d, x, s, ac) \\\r\n  {(a) = TRUNC32((a) + H((b), (c), (d)) + (x) + (ac)); \\\r\n   (a) = ROTATE_LEFT((a), (s)); \\\r\n   (a) = TRUNC32((a) + (b)); \\\r\n  }\r\n#define II(a, b, c, d, x, s, ac) \\\r\n  {(a) = TRUNC32((a) + I((b), (c), (d)) + (x) + (ac)); \\\r\n   (a) = ROTATE_LEFT((a), (s)); \\\r\n   (a) = TRUNC32((a) + (b)); \\\r\n  }\r\n\r\n\r\n\r\nstatic\r\nvoid MD5_default_IV(unsigned long *buf)\r\n{\r\n   buf[0] = 0x67452301UL;\r\n   buf[1] = 0xefcdab89UL;\r\n   buf[2] = 0x98badcfeUL;\r\n   buf[3] = 0x10325476UL;\r\n}\r\n\r\n\r\n\r\n/* Basic MD5 step. Transform buf based on in.\r\n */\r\n\r\nstatic\r\nvoid MD5_compress(unsigned long *buf, unsigned long *in)\r\n{\r\n  unsigned long a = buf[0], b = buf[1], c = buf[2], d = buf[3];\r\n\r\n  /* Round 1 */\r\n#define S11 7\r\n#define S12 12\r\n#define S13 17\r\n#define S14 22\r\n  FF ( a, b, c, d, in[ 0], S11, 3614090360UL); /* 1 */\r\n  FF ( d, a, b, c, in[ 1], S12, 3905402710UL); /* 2 */\r\n  FF ( c, d, a, b, in[ 2], S13,  606105819UL); /* 3 */\r\n  FF ( b, c, d, a, in[ 3], S14, 3250441966UL); /* 4 */\r\n  FF ( a, b, c, d, in[ 4], S11, 4118548399UL); /* 5 */\r\n  FF ( d, a, b, c, in[ 5], S12, 1200080426UL); /* 6 */\r\n  FF ( c, d, a, b, in[ 6], S13, 2821735955UL); /* 7 */\r\n  FF ( b, c, d, a, in[ 7], S14, 4249261313UL); /* 8 */\r\n  FF ( a, b, c, d, in[ 8], S11, 1770035416UL); /* 9 */\r\n  FF ( d, a, b, c, in[ 9], S12, 2336552879UL); /* 10 */\r\n  FF ( c, d, a, b, in[10], S13, 4294925233UL); /* 11 */\r\n  FF ( b, c, d, a, in[11], S14, 2304563134UL); /* 12 */\r\n  FF ( a, b, c, d, in[12], S11, 1804603682UL); /* 13 */\r\n  FF ( d, a, b, c, in[13], S12, 4254626195UL); /* 14 */\r\n  FF ( c, d, a, b, in[14], S13, 2792965006UL); /* 15 */\r\n  FF ( b, c, d, a, in[15], S14, 1236535329UL); /* 16 */\r\n\r\n  /* Round 2 */\r\n#define S21 5\r\n#define S22 9\r\n#define S23 14\r\n#define S24 20\r\n  GG ( a, b, c, d, in[ 1], S21, 4129170786UL); /* 17 */\r\n  GG ( d, a, b, c, in[ 6], S22, 3225465664UL); /* 18 */\r\n  GG ( c, d, a, b, in[11], S23,  643717713UL); /* 19 */\r\n  GG ( b, c, d, a, in[ 0], S24, 3921069994UL); /* 20 */\r\n  GG ( a, b, c, d, in[ 5], S21, 3593408605UL); /* 21 */\r\n  GG ( d, a, b, c, in[10], S22,   38016083UL); /* 22 */\r\n  GG ( c, d, a, b, in[15], S23, 3634488961UL); /* 23 */\r\n  GG ( b, c, d, a, in[ 4], S24, 3889429448UL); /* 24 */\r\n  GG ( a, b, c, d, in[ 9], S21,  568446438UL); /* 25 */\r\n  GG ( d, a, b, c, in[14], S22, 3275163606UL); /* 26 */\r\n  GG ( c, d, a, b, in[ 3], S23, 4107603335UL); /* 27 */\r\n  GG ( b, c, d, a, in[ 8], S24, 1163531501UL); /* 28 */\r\n  GG ( a, b, c, d, in[13], S21, 2850285829UL); /* 29 */\r\n  GG ( d, a, b, c, in[ 2], S22, 4243563512UL); /* 30 */\r\n  GG ( c, d, a, b, in[ 7], S23, 1735328473UL); /* 31 */\r\n  GG ( b, c, d, a, in[12], S24, 2368359562UL); /* 32 */\r\n\r\n  /* Round 3 */\r\n#define S31 4\r\n#define S32 11\r\n#define S33 16\r\n#define S34 23\r\n  HH ( a, b, c, d, in[ 5], S31, 4294588738UL); /* 33 */\r\n  HH ( d, a, b, c, in[ 8], S32, 2272392833UL); /* 34 */\r\n  HH ( c, d, a, b, in[11], S33, 1839030562UL); /* 35 */\r\n  HH ( b, c, d, a, in[14], S34, 4259657740UL); /* 36 */\r\n  HH ( a, b, c, d, in[ 1], S31, 2763975236UL); /* 37 */\r\n  HH ( d, a, b, c, in[ 4], S32, 1272893353UL); /* 38 */\r\n  HH ( c, d, a, b, in[ 7], S33, 4139469664UL); /* 39 */\r\n  HH ( b, c, d, a, in[10], S34, 3200236656UL); /* 40 */\r\n  HH ( a, b, c, d, in[13], S31,  681279174UL); /* 41 */\r\n  HH ( d, a, b, c, in[ 0], S32, 3936430074UL); /* 42 */\r\n  HH ( c, d, a, b, in[ 3], S33, 3572445317UL); /* 43 */\r\n  HH ( b, c, d, a, in[ 6], S34,   76029189UL); /* 44 */\r\n  HH ( a, b, c, d, in[ 9], S31, 3654602809UL); /* 45 */\r\n  HH ( d, a, b, c, in[12], S32, 3873151461UL); /* 46 */\r\n  HH ( c, d, a, b, in[15], S33,  530742520UL); /* 47 */\r\n  HH ( b, c, d, a, in[ 2], S34, 3299628645UL); /* 48 */\r\n\r\n  /* Round 4 */\r\n#define S41 6\r\n#define S42 10\r\n#define S43 15\r\n#define S44 21\r\n  II ( a, b, c, d, in[ 0], S41, 4096336452UL); /* 49 */\r\n  II ( d, a, b, c, in[ 7], S42, 1126891415UL); /* 50 */\r\n  II ( c, d, a, b, in[14], S43, 2878612391UL); /* 51 */\r\n  II ( b, c, d, a, in[ 5], S44, 4237533241UL); /* 52 */\r\n  II ( a, b, c, d, in[12], S41, 1700485571UL); /* 53 */\r\n  II ( d, a, b, c, in[ 3], S42, 2399980690UL); /* 54 */\r\n  II ( c, d, a, b, in[10], S43, 4293915773UL); /* 55 */\r\n  II ( b, c, d, a, in[ 1], S44, 2240044497UL); /* 56 */\r\n  II ( a, b, c, d, in[ 8], S41, 1873313359UL); /* 57 */\r\n  II ( d, a, b, c, in[15], S42, 4264355552UL); /* 58 */\r\n  II ( c, d, a, b, in[ 6], S43, 2734768916UL); /* 59 */\r\n  II ( b, c, d, a, in[13], S44, 1309151649UL); /* 60 */\r\n  II ( a, b, c, d, in[ 4], S41, 4149444226UL); /* 61 */\r\n  II ( d, a, b, c, in[11], S42, 3174756917UL); /* 62 */\r\n  II ( c, d, a, b, in[ 2], S43,  718787259UL); /* 63 */\r\n  II ( b, c, d, a, in[ 9], S44, 3951481745UL); /* 64 */\r\n\r\n  buf[0] = TRUNC32(buf[0] + a);\r\n  buf[1] = TRUNC32(buf[1] + b);\r\n  buf[2] = TRUNC32(buf[2] + c);\r\n  buf[3] = TRUNC32(buf[3] + d);\r\n}\r\n\r\n\r\n/*\r\n *  END RSA's md5 stuff\r\n *\r\n */\r\n\r\n\r\nstatic\r\nvoid words_from_bytes(unsigned long *txtl, const unsigned char *txtc, long n)\r\n{\r\n   long i;\r\n   unsigned long v;\r\n\r\n   for (i = 0; i < n; i++) {\r\n      v = txtc[4*i];\r\n      v += ((unsigned long) (txtc[4*i+1])) << 8;\r\n      v += ((unsigned long) (txtc[4*i+2])) << 16;\r\n      v += ((unsigned long) (txtc[4*i+3])) << 24;\r\n      txtl[i] = v;\r\n   }\r\n}\r\n\r\nstatic \r\nvoid bytes_from_words(unsigned char *txtc, const unsigned long *txtl, long n)\r\n{\r\n   long i;\r\n   unsigned long v;\r\n\r\n   for (i = 0; i < n; i++) {\r\n      v = txtl[i];\r\n      txtc[4*i] = v & 255;\r\n      v = v >> 8;\r\n      txtc[4*i+1] = v & 255;\r\n      v = v >> 8;\r\n      txtc[4*i+2] = v & 255;\r\n      v = v >> 8;\r\n      txtc[4*i+3] = v & 255;\r\n   }\r\n}\r\n\r\n\r\nstatic\r\nvoid MD5_compress1(unsigned long *buf, unsigned char *in, long n)\r\n{\r\n   unsigned long txtl[16];\r\n   unsigned char txtc[64]; \r\n   long i, j, k;\r\n\r\n   if (n < 0) n = 0;\r\n\r\n   i = 0;\r\n   while (i < n) {\r\n      k = n-i;\r\n      if (k > 64) k = 64;\r\n      for (j = 0; j < k; j++)\r\n         txtc[j] = in[i+j];\r\n      for (; j < 64; j++)\r\n         txtc[j] = 0;\r\n      words_from_bytes(txtl, txtc, 16);\r\n      MD5_compress(buf, txtl);\r\n      i += k;\r\n   }\r\n}\r\n\r\n\r\n// the \"cipherpunk\" version of arc4 \r\n\r\nstruct _ZZ_arc4_key\r\n{      \r\n    unsigned char state[256];       \r\n    unsigned char x;        \r\n    unsigned char y;\r\n};\r\n\r\n\r\nstatic inline\r\nvoid swap_byte(unsigned char *a, unsigned char *b)\r\n{\r\n    unsigned char swapByte; \r\n    \r\n    swapByte = *a; \r\n    *a = *b;      \r\n    *b = swapByte;\r\n}\r\n\r\nstatic\r\nvoid prepare_key(unsigned char *key_data_ptr, \r\n                 long key_data_len, _ZZ_arc4_key *key)\r\n{\r\n    unsigned char index1;\r\n    unsigned char index2;\r\n    unsigned char* state;\r\n    long counter;     \r\n    \r\n    state = &key->state[0];         \r\n    for(counter = 0; counter < 256; counter++)              \r\n       state[counter] = counter;               \r\n    key->x = 0;     \r\n    key->y = 0;     \r\n    index1 = 0;     \r\n    index2 = 0;             \r\n    for(counter = 0; counter < 256; counter++)      \r\n    {               \r\n         index2 = (key_data_ptr[index1] + state[counter] + index2) & 255;                \r\n         swap_byte(&state[counter], &state[index2]);            \r\n\r\n         index1 = (index1 + 1) % key_data_len;  \r\n    }       \r\n}\r\n\r\n\r\n\r\nstatic\r\nvoid arc4(unsigned char *buffer_ptr, long buffer_len, _ZZ_arc4_key *key)\r\n{ \r\n    unsigned char x;\r\n    unsigned char y;\r\n    unsigned char* state;\r\n    unsigned char xorIndex;\r\n    long counter;              \r\n    \r\n    x = key->x;     \r\n    y = key->y;     \r\n    \r\n    state = &key->state[0];         \r\n    for(counter = 0; counter < buffer_len; counter ++)      \r\n    {               \r\n         x = (x + 1) & 255;\r\n         y = (state[x] + y) & 255;\r\n         swap_byte(&state[x], &state[y]);                        \r\n              \r\n         xorIndex = (state[x] + state[y]) & 255;\r\n              \r\n         buffer_ptr[counter] = state[xorIndex];         \r\n     }               \r\n     key->x = x;     \r\n     key->y = y;\r\n}\r\n\r\n// global state information for PRNG\r\n\r\nNTL_THREAD_LOCAL static long ran_initialized = 0;\r\nNTL_THREAD_LOCAL static _ZZ_arc4_key ran_key;\r\n\r\nstatic const unsigned long default_md5_tab[16] = {\r\n744663023UL, 1011602954UL, 3163087192UL, 3383838527UL, \r\n3305324122UL, 3197458079UL, 2266495600UL, 2760303563UL, \r\n346234297UL, 1919920720UL, 1896169861UL, 2192176675UL, \r\n2027150322UL, 2090160759UL, 2134858730UL, 1131796244UL\r\n};\r\n\r\n\r\n\r\nstatic\r\nvoid build_arc4_tab(unsigned char *seed_bytes, const ZZ& s)\r\n{\r\n   long nb = NumBytes(s);\r\n   \r\n   unsigned char *txt;\r\n\r\n   Vec<unsigned char> txt_storage;\r\n   txt_storage.SetLength(nb + 68);\r\n   txt = txt_storage.elts();\r\n\r\n   BytesFromZZ(txt + 4, s, nb);\r\n\r\n   bytes_from_words(txt + nb + 4, default_md5_tab, 16);\r\n\r\n   unsigned long buf[4];\r\n\r\n   unsigned long i;\r\n   for (i = 0; i < 16; i++) {\r\n      MD5_default_IV(buf);\r\n      bytes_from_words(txt, &i, 1);\r\n\r\n      MD5_compress1(buf, txt, nb + 68);\r\n\r\n      bytes_from_words(seed_bytes + 16*i, buf, 4);\r\n   }\r\n}\r\n\r\n\r\nvoid SetSeed(const ZZ& s)\r\n{\r\n   unsigned char seed_bytes[256];\r\n\r\n   build_arc4_tab(seed_bytes, s);\r\n   prepare_key(seed_bytes, 256, &ran_key);\r\n\r\n   // we discard the first 1024 bytes of the arc4 stream, as this is\r\n   // recommended practice.\r\n\r\n   arc4(seed_bytes, 256, &ran_key);\r\n   arc4(seed_bytes, 256, &ran_key);\r\n   arc4(seed_bytes, 256, &ran_key);\r\n   arc4(seed_bytes, 256, &ran_key);\r\n\r\n   ran_initialized = 1;\r\n}\r\n\r\n\r\nstatic \r\nvoid ran_bytes(unsigned char *bytes, long n)\r\n{\r\n   if (!ran_initialized) {\r\n      ZZ x;\r\n      const string& id = UniqueID();\r\n      ZZFromBytes(x, (const unsigned char *) id.c_str(), id.length());\r\n      SetSeed(x);\r\n   }\r\n   arc4(bytes, n, &ran_key);\r\n}\r\n\r\n\r\nunsigned long RandomWord()\r\n{\r\n   unsigned char buf[NTL_BITS_PER_LONG/8];\r\n   long i;\r\n   unsigned long res;\r\n\r\n   ran_bytes(buf, NTL_BITS_PER_LONG/8);\r\n\r\n   res = 0;\r\n   for (i = NTL_BITS_PER_LONG/8 - 1; i >= 0; i--) {\r\n      res = res << 8;\r\n      res = res | buf[i];\r\n   }\r\n\r\n   return res;\r\n}\r\n\r\nlong RandomBits_long(long l)\r\n{\r\n   if (l <= 0) return 0;\r\n   if (l >= NTL_BITS_PER_LONG) \r\n      ResourceError(\"RandomBits: length too big\");\r\n\r\n   unsigned char buf[NTL_BITS_PER_LONG/8];\r\n   unsigned long res;\r\n   long i;\r\n\r\n   long nb = (l+7)/8;\r\n   ran_bytes(buf, nb);\r\n\r\n   res = 0;\r\n   for (i = nb - 1; i >= 0; i--) {\r\n      res = res << 8;\r\n      res = res | buf[i];\r\n   }\r\n\r\n   return long(res & ((1UL << l)-1UL)); \r\n}\r\n\r\nunsigned long RandomBits_ulong(long l)\r\n{\r\n   if (l <= 0) return 0;\r\n   if (l > NTL_BITS_PER_LONG) \r\n      ResourceError(\"RandomBits: length too big\");\r\n\r\n   unsigned char buf[NTL_BITS_PER_LONG/8];\r\n   unsigned long res;\r\n   long i;\r\n\r\n   long nb = (l+7)/8;\r\n   ran_bytes(buf, nb);\r\n\r\n   res = 0;\r\n   for (i = nb - 1; i >= 0; i--) {\r\n      res = res << 8;\r\n      res = res | buf[i];\r\n   }\r\n\r\n   if (l < NTL_BITS_PER_LONG)\r\n      res = res & ((1UL << l)-1UL);\r\n\r\n   return res;\r\n}\r\n\r\nlong RandomLen_long(long l)\r\n{\r\n   if (l <= 0) return 0;\r\n   if (l == 1) return 1;\r\n   if (l >= NTL_BITS_PER_LONG) \r\n      ResourceError(\"RandomLen: length too big\");\r\n\r\n   return RandomBits_long(l-1) + (1L << (l-1)); \r\n}\r\n\r\n\r\nvoid RandomBits(ZZ& x, long l)\r\n{\r\n   if (l <= 0) {\r\n      x = 0;\r\n      return;\r\n   }\r\n\r\n   if (NTL_OVERFLOW(l, 1, 0))\r\n      ResourceError(\"RandomBits: length too big\");\r\n\r\n   long nb = (l+7)/8;\r\n\r\n   NTL_THREAD_LOCAL static Vec<unsigned char> buf_mem;\r\n   Vec<unsigned char>::Watcher watch_buf_mem(buf_mem);\r\n\r\n   buf_mem.SetLength(nb);\r\n   unsigned char *buf = buf_mem.elts();\r\n\r\n   ran_bytes(buf, nb);\r\n\r\n   NTL_ZZRegister(res);\r\n\r\n   ZZFromBytes(res, buf, nb);\r\n   trunc(res, res, l);\r\n\r\n   x = res;\r\n}\r\n\r\n\r\nvoid RandomLen(ZZ& x, long l)\r\n{\r\n   if (l <= 0) {\r\n      x = 0;\r\n      return;\r\n   }\r\n\r\n   if (l == 1) {\r\n      x = 1;\r\n      return;\r\n   }\r\n\r\n   if (NTL_OVERFLOW(l, 1, 0))\r\n      ResourceError(\"RandomLen: length too big\");\r\n\r\n   // pre-allocate space to avoid two allocations\r\n   long nw = (l + NTL_ZZ_NBITS - 1)/NTL_ZZ_NBITS;\r\n   x.SetSize(nw);\r\n\r\n   RandomBits(x, l-1);\r\n   SetBit(x, l-1);\r\n}\r\n\r\n\r\nconst long RandomBndExcess = 8;\r\n\r\n\r\nvoid RandomBnd(ZZ& x, const ZZ& bnd)\r\n{\r\n   if (bnd <= 1) {\r\n      x = 0;\r\n      return;\r\n   }\r\n\r\n   long k = NumBits(bnd);\r\n\r\n   if (weight(bnd) == 1) {\r\n      RandomBits(x, k-1);\r\n      return;\r\n   }\r\n\r\n   long l = k + RandomBndExcess;\r\n\r\n   NTL_ZZRegister(t);\r\n   NTL_ZZRegister(r);\r\n   NTL_ZZRegister(t1);\r\n   \r\n   do {\r\n      RandomBits(t, l);\r\n      rem(r, t, bnd);\r\n      sub(t1, bnd, r);\r\n      add(t, t, t1);\r\n   } while (NumBits(t) > l);\r\n\r\n   x = r;\r\n}\r\n\r\nlong RandomBnd(long bnd)\r\n{\r\n   if (bnd <= 1) return 0;\r\n\r\n   long k = NumBits(bnd);\r\n\r\n   if (((bnd - 1) & bnd) == 0) \r\n      return RandomBits_long(k-1);\r\n\r\n   long l = k + RandomBndExcess;\r\n\r\n   if (l > NTL_BITS_PER_LONG-2) {\r\n      NTL_ZZRegister(Bnd);\r\n      NTL_ZZRegister(res);\r\n\r\n      Bnd = bnd;\r\n      RandomBnd(res, Bnd);\r\n      return to_long(res);\r\n   }\r\n\r\n   long t, r;\r\n\r\n   do {\r\n      t = RandomBits_long(l);\r\n      r = t % bnd;\r\n   } while (t + bnd - r > (1L << l)); \r\n\r\n   return r;\r\n}\r\n\r\n\r\n\r\n\r\n// More prime generation stuff...\r\n\r\nstatic\r\ndouble Log2(double x)\r\n{\r\n   NTL_THREAD_LOCAL static double log2 = log(2.0);\r\n   return log(x)/log2;\r\n}\r\n\r\n// Define p(k,t) to be the conditional probability that a random, odd, k-bit \r\n// number is composite, given that it passes t iterations of the \r\n// Miller-Rabin test.\r\n// This routine returns 0 or 1, and if it returns 1 then\r\n// p(k,t) <= 2^{-n}.\r\n// This basically encodes the estimates of Damgard, Landrock, and Pomerance;\r\n// it uses floating point arithmetic, but is coded in such a way\r\n// that its results should be correct, assuming that the log function\r\n// is computed with reasonable precision.\r\n// \r\n// It is assumed that k >= 3 and t >= 1; if this does not hold,\r\n// then 0 is returned.\r\n\r\nstatic\r\nlong ErrBoundTest(long kk, long tt, long nn)\r\n\r\n{\r\n   const double fudge = (1.0 + 1024.0/NTL_FDOUBLE_PRECISION);\r\n   const double log2_3 = Log2(3.0);\r\n   const double log2_7 = Log2(7.0);\r\n   const double log2_20 = Log2(20.0);\r\n\r\n   double k = kk;\r\n   double t = tt;\r\n   double n = nn;\r\n\r\n   if (k < 3 || t < 1) return 0;\r\n   if (n < 1) return 1;\r\n\r\n   // the following test is largely academic\r\n   if (9*t > NTL_FDOUBLE_PRECISION) LogicError(\"ErrBoundTest: t too big\");\r\n\r\n   double log2_k = Log2(k);\r\n\r\n   if ((n + log2_k)*fudge <= 2*t)\r\n      return 1;\r\n\r\n   if ((2*log2_k + 4.0 + n)*fudge <= 2*sqrt(k))\r\n      return 2;\r\n\r\n   if ((t == 2 && k >= 88) || (3 <= t && 9*t <= k && k >= 21)) {\r\n      if ((1.5*log2_k + t + 4.0 + n)*fudge <= 0.5*Log2(t) + 2*(sqrt(t*k)))\r\n         return 3;\r\n   }\r\n\r\n   if (k <= 9*t && 4*t <= k && k >= 21) {\r\n      if ( ((log2_3 + log2_7 + log2_k + n)*fudge <= log2_20 + 5*t)  &&\r\n           ((log2_3 + (15.0/4.0)*log2_k + n)*fudge <= log2_7 + k/2 + 2*t) &&\r\n           ((2*log2_3 + 2 + log2_k + n)*fudge <= k/4 + 3*t) )\r\n         return 4; \r\n   }\r\n\r\n   if (4*t >= k && k >= 21) {\r\n      if (((15.0/4.0)*log2_k + n)*fudge <= log2_7 + k/2 + 2*t)\r\n         return 5;\r\n   }\r\n\r\n   return 0;\r\n}\r\n\r\n\r\nvoid GenPrime(ZZ& n, long k, long err)\r\n{\r\n   if (k <= 1) LogicError(\"GenPrime: bad length\");\r\n\r\n   if (k > (1L << 20)) ResourceError(\"GenPrime: length too large\");\r\n\r\n   if (err < 1) err = 1;\r\n   if (err > 512) err = 512;\r\n\r\n   if (k == 2) {\r\n      if (RandomBnd(2))\r\n         n = 3;\r\n      else\r\n         n = 2;\r\n\r\n      return;\r\n   }\r\n\r\n\r\n   long t;\r\n\r\n   t = 1;\r\n   while (!ErrBoundTest(k, t, err))\r\n      t++;\r\n\r\n   RandomPrime(n, k, t);\r\n}\r\n\r\n\r\nlong GenPrime_long(long k, long err)\r\n{\r\n   if (k <= 1) LogicError(\"GenPrime: bad length\");\r\n\r\n   if (k >= NTL_BITS_PER_LONG) ResourceError(\"GenPrime: length too large\");\r\n\r\n   if (err < 1) err = 1;\r\n   if (err > 512) err = 512;\r\n\r\n   if (k == 2) {\r\n      if (RandomBnd(2))\r\n         return 3;\r\n      else\r\n         return 2;\r\n   }\r\n\r\n   long t;\r\n\r\n   t = 1;\r\n   while (!ErrBoundTest(k, t, err))\r\n      t++;\r\n\r\n   return RandomPrime_long(k, t);\r\n}\r\n\r\n\r\nvoid GenGermainPrime(ZZ& n, long k, long err)\r\n{\r\n   if (k <= 1) LogicError(\"GenGermainPrime: bad length\");\r\n\r\n   if (k > (1L << 20)) ResourceError(\"GenGermainPrime: length too large\");\r\n\r\n   if (err < 1) err = 1;\r\n   if (err > 512) err = 512;\r\n\r\n   if (k == 2) {\r\n      if (RandomBnd(2))\r\n         n = 3;\r\n      else\r\n         n = 2;\r\n\r\n      return;\r\n   }\r\n\r\n\r\n   long prime_bnd = ComputePrimeBound(k);\r\n\r\n   if (NumBits(prime_bnd) >= k/2)\r\n      prime_bnd = (1L << (k/2-1));\r\n\r\n\r\n   ZZ two;\r\n   two = 2;\r\n\r\n   ZZ n1;\r\n\r\n   \r\n   PrimeSeq s;\r\n\r\n   ZZ iter;\r\n   iter = 0;\r\n\r\n\r\n   for (;;) {\r\n      iter++;\r\n\r\n      RandomLen(n, k);\r\n      if (!IsOdd(n)) add(n, n, 1);\r\n\r\n      s.reset(3);\r\n      long p;\r\n\r\n      long sieve_passed = 1;\r\n\r\n      p = s.next();\r\n      while (p && p < prime_bnd) {\r\n         long r = rem(n, p);\r\n\r\n         if (r == 0) {\r\n            sieve_passed = 0;\r\n            break;\r\n         }\r\n\r\n         // test if 2*r + 1 = 0 (mod p)\r\n         if (r == p-r-1) {\r\n            sieve_passed = 0;\r\n            break;\r\n         }\r\n\r\n         p = s.next();\r\n      }\r\n\r\n      if (!sieve_passed) continue;\r\n\r\n\r\n      if (MillerWitness(n, two)) continue;\r\n\r\n      // n1 = 2*n+1\r\n      mul(n1, n, 2);\r\n      add(n1, n1, 1);\r\n\r\n\r\n      if (MillerWitness(n1, two)) continue;\r\n\r\n      // now do t M-R iterations...just to make sure\r\n \r\n      // First compute the appropriate number of M-R iterations, t\r\n      // The following computes t such that \r\n      //       p(k,t)*8/k <= 2^{-err}/(5*iter^{1.25})\r\n      // which suffices to get an overall error probability of 2^{-err}.\r\n      // Note that this method has the advantage of not requiring \r\n      // any assumptions on the density of Germain primes.\r\n\r\n      long err1 = max(1, err + 7 + (5*NumBits(iter) + 3)/4 - NumBits(k));\r\n      long t;\r\n      t = 1;\r\n      while (!ErrBoundTest(k, t, err1))\r\n         t++;\r\n\r\n      ZZ W;\r\n      long MR_passed = 1;\r\n\r\n      long i;\r\n      for (i = 1; i <= t; i++) {\r\n         do {\r\n            RandomBnd(W, n);\r\n         } while (W == 0);\r\n         // W == 0 is not a useful candidate witness!\r\n\r\n         if (MillerWitness(n, W)) {\r\n            MR_passed = 0;\r\n            break;\r\n         }\r\n      }\r\n\r\n      if (MR_passed) break;\r\n   }\r\n}\r\n\r\nlong GenGermainPrime_long(long k, long err)\r\n{\r\n   if (k >= NTL_BITS_PER_LONG-1)\r\n      ResourceError(\"GenGermainPrime_long: length too long\");\r\n\r\n   ZZ n;\r\n   GenGermainPrime(n, k, err);\r\n   return to_long(n);\r\n}\r\n\r\n\r\nNTL_END_IMPL\r\n", "meta": {"hexsha": "98866d3ef27411decba91c68abc6a7ecf08fa261", "size": 45174, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "WinNTL-8_1_2/src/ZZ.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.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.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": 20.2120805369, "max_line_length": 90, "alphanum_fraction": 0.4677469341, "num_tokens": 15369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6261241772283035, "lm_q2_score": 0.7310585903489891, "lm_q1q2_score": 0.45773345838794416}}
{"text": "/*\n  * qGeod\n  *\n*/\n\n#define _MAIN_\n\n#include <iostream>\n#include <armadillo>\n\n\n#include \"../core/UAmoeba.hpp\"\n\n\n#include \"../io/cxmatLoad.cpp\"\n\n#ifdef _ALGEBRA_TOOLS_\n#else\n#include \"../core/algebraTools.hpp\"\n#endif\n\n#ifdef _AMOEBA_INIT_\n#else\n#include \"../core/amoebaParam.cpp\"\n#endif\n\n\n#include \"../core/translate.cpp\"\n\n#include \"../solvers/segSolver.cpp\"\n#include \"../solvers/serialSolver.cpp\"\n#include \"../solvers/monte.cpp\"\n\nusing namespace arma;\n\nint main(int argc, char **argv)\n{\n\tint rank;\n\tint size;\n\n\tMPI_Init(&argc, &argv);\n\tMPI_Comm_size(MPI_COMM_WORLD, &size);\n\tMPI_Comm_rank(MPI_COMM_WORLD, &rank);\n\n\tcx_mat startBoundary;\n\tcx_mat endBoundary;\n\n\tint maxIters;\n\tint precision;\n\tint matSize;\n\tint parallelFlag;\n\n\tif(argc==1)\n\t{\n\t\tcout<< \"Usage : /qGeod <0/1/2> start.mat target.mat n maxAmoebaIters nGridPoints precision maxMainIters penalty\\n\"\n\t\t\t\t<< \"=================================================================================================== \\n\"\n\t\t\t\t<< \"n   \t\t\t\t: exponent in SU(2^n)                                  \\n\"\n\t\t\t\t<< \"precision   : working accuracy for qGeod                           \\n\"\n\t\t\t\t<< \"maxIters    : maximum number of iterations in leap-frog            \\n\"\n\t\t\t\t<< \"target.mat  : matrix containing desired unitary operation,         \\n\"\n\t\t\t\t<< \"              in format described by                               \\n\"\n\t\t\t  << \"              http://arma.sourceforge.net/docs.html#save_load_mat  \\n\"\n\t\t\t\t<< \"nGridPoints : number of guess points in amoeba                     \\n\"\n\t\t\t\t<< \"0/1/2       : run in serial 0, parallel 1, 2 monte carlo           \\n\"\n\t\t\t\t<< \"=================================================================================================== \\n\";\n\t}\n\telse\n\t{\n\n\t\tparallelFlag = atoi(argv[1]);\n\t\tchar *sBoundary = argv[2];\n\t\tchar *eBoundary = argv[3];\n\t\tmatSize = pow(2,atoi(argv[4]));\n\n\t\tcout << \"Loading target matrix \\n\";\n\t\tcxmatLoad(endBoundary, matSize, eBoundary);\n\t\tcxmatLoad(startBoundary, matSize, sBoundary);\n\n\t\tcout << \"Initialising solver parameters\\n\";\n\t\tAmoebaParam<cx_mat> amoebaParam;\n\t\tamoebaParam.getData(argc, argv);\n\n\t\tamoebaParam.startBoundary = startBoundary;\n\t\tamoebaParam.endBoundary = endBoundary;\n\n\t\tswitch(parallelFlag)\n\t\t{\n\t\t\tcase 0:\n\t\t\t\tcout << \"Running serial solver\\n\";\n\t\t\t\tserialSolver<cx_mat>(amoebaParam);\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\tcout << \"Running leap-frog solver\\n\";\n\t\t\t\tsegSolver<cx_mat>(amoebaParam, rank, size);\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tcout << \"Running Monte Carlo solver\\n\";\n\t\t\t\tmonteCarlo<cx_mat>(amoebaParam);\n\t\t}\n\t}\n\n\n\tMPI_Finalize();\n\treturn 0;\n}\n", "meta": {"hexsha": "e3c1085cf4cb314913ac88f0eb33f23e0d61f588", "size": 2557, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/front/qGeod.cpp", "max_stars_repo_name": "Swaddle/qGeod", "max_stars_repo_head_hexsha": "8108fe44c09c0c89b23cf5f14efa098b09d6bcf3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/front/qGeod.cpp", "max_issues_repo_name": "Swaddle/qGeod", "max_issues_repo_head_hexsha": "8108fe44c09c0c89b23cf5f14efa098b09d6bcf3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/front/qGeod.cpp", "max_forks_repo_name": "Swaddle/qGeod", "max_forks_repo_head_hexsha": "8108fe44c09c0c89b23cf5f14efa098b09d6bcf3", "max_forks_repo_licenses": ["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.1226415094, "max_line_length": 116, "alphanum_fraction": 0.5701994525, "num_tokens": 675, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585903489891, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.4577334583879441}}
{"text": "#pragma once\n\n#include <map>\n\n#include <Eigen/Sparse>\n\n#include \"eigen.hh\"\n#include \"util/optional.hh\"\n\nnamespace estimation {\nnamespace optimization {\n\n// BSR Matrix\nclass BlockSparseMatrix {\n  using SpMat = Eigen::SparseMatrix<double>;\n  using SpVec = Eigen::SparseVector<double>;\n\n public:\n  BlockSparseMatrix() {\n    valid_ = false;\n  }\n  BlockSparseMatrix(const int n_block_rows, const int n_block_cols);\n\n  void set(int row, int col, const Eigen::MatrixXd& mat);\n  const Eigen::MatrixXd& get(int row, int col) const;\n\n  int real_rows() const;\n  int real_cols() const;\n\n  int real_rows_above_block(int block_row) const;\n  int real_cols_left_of_block(int block_col) const;\n\n  SpMat to_eigen_sparse() const;\n\n  jcc::Optional<VecXd> solve_lst_sq(const std::vector<VecXd>& residuals,\n                                    const BlockSparseMatrix& R_inv,\n                                    const double lambda = 0.0) const;\n\n  int block_rows() const {\n    return rows_.size();\n  }\n  int block_cols() const {\n    return n_cols_.size();\n  }\n\n  // Here's a little mock for what an LDLT will feel like.\n  /*\n  void ldlt() {\n    D;\n    L;\n\n    for (int j = 0; j < i; ++j) {\n      DDii = 0;\n      for (int k = 0; k < j; ++k) {\n        DDii += L[j, k] * D[k] * L[j, k].transpose();\n      }\n      D[j] = A[j, j] - DDii;\n\n      for (int i = 0; i < n; ++i) {\n        DD = 0;\n\n        d_llt = llt(D[j]);\n        for (int k = 0; k < j; ++k) {\n          DD += L(i, k) * D[k] * L[j, k].transpose();\n        }\n        L[i, j] = d_llt.solve((A[i, j] - DD).transpose()).transpose();\n      }\n    }\n  }\n  */\n\n private:\n  struct Block {\n    Eigen::MatrixXd block;\n  };\n\n  struct Row {\n    std::map<int, Block> cols;\n    int n_rows = -1;\n  };\n\n  // The number of columns in each column block\n  std::vector<int> n_cols_;\n  // The block rows\n  std::vector<Row> rows_;\n\n  bool valid_ = false;\n};\n}  // namespace optimization\n}  // namespace estimation", "meta": {"hexsha": "814b37d4fd188e0740ceaf8882344192e4195379", "size": 1926, "ext": "hh", "lang": "C++", "max_stars_repo_path": "estimation/optimization/block_sparse_matrix.hh", "max_stars_repo_name": "jpanikulam/experiments", "max_stars_repo_head_hexsha": "be36319a89f8baee54d7fa7618b885edb7025478", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-04-14T11:40:28.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-14T11:40:28.000Z", "max_issues_repo_path": "estimation/optimization/block_sparse_matrix.hh", "max_issues_repo_name": "jpanikulam/experiments", "max_issues_repo_head_hexsha": "be36319a89f8baee54d7fa7618b885edb7025478", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2018-04-18T13:54:29.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-22T20:04:17.000Z", "max_forks_repo_path": "estimation/optimization/block_sparse_matrix.hh", "max_forks_repo_name": "jpanikulam/experiments", "max_forks_repo_head_hexsha": "be36319a89f8baee54d7fa7618b885edb7025478", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-12-24T03:45:47.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-24T03:45:47.000Z", "avg_line_length": 21.4, "max_line_length": 72, "alphanum_fraction": 0.5742471443, "num_tokens": 552, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.45773345105040475}}
{"text": "//  ================================================================\n//  Created by Gregory Kramida on 10/23/18.\n//  Copyright (c) 2018 Gregory Kramida\n//  Licensed under the Apache License, Version 2.0 (the \"License\");\n//  you may not use this file except in compliance with the License.\n//  You may obtain a copy of the License at\n\n//  http://www.apache.org/licenses/LICENSE-2.0\n\n//  Unless required by applicable law or agreed to in writing, software\n//  distributed under the License is distributed on an \"AS IS\" BASIS,\n//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//  See the License for the specific language governing permissions and\n//  limitations under the License.\n//  ================================================================\n#pragma once\n\n//libraries\n#include <Eigen/Eigen>\n\n//local\n#include \"../../math/typedefs.hpp\"\n\nnamespace eig = Eigen;\n\nnamespace nonrigid_optimization {\nnamespace slavcheva{\n\nvoid\ncompute_tikhonov_regularization_gradient(math::MatrixXv2f& gradient, float& energy, const math::MatrixXv2f& warp_field);\n\nvoid\ncompute_tikhonov_regularization_gradient_within_band_union(math::MatrixXv2f& gradient, float& energy,\n                                                           const math::MatrixXv2f& warp_field,\n                                                           const eig::MatrixXf& live_field,\n                                                           const eig::MatrixXf& canonical_field);\n} //namespace slavcheva\n}//nonrigid_optimization\n", "meta": {"hexsha": "746c19193231088760d5ad47b33b827b66e5bc48", "size": 1519, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/nonrigid_optimization/slavcheva/smoothing_term.hpp", "max_stars_repo_name": "Algomorph/LevelSetFusionExperimentsCPP", "max_stars_repo_head_hexsha": "f56962f0ad5c62e6706f818062782a2e1660afda", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2019-01-07T14:12:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T01:48:03.000Z", "max_issues_repo_path": "src/nonrigid_optimization/slavcheva/smoothing_term.hpp", "max_issues_repo_name": "Algomorph/LevelSetFusionExperimentsCPP", "max_issues_repo_head_hexsha": "f56962f0ad5c62e6706f818062782a2e1660afda", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2018-12-19T16:43:33.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-06T19:50:22.000Z", "max_forks_repo_path": "src/nonrigid_optimization/slavcheva/smoothing_term.hpp", "max_forks_repo_name": "Algomorph/LevelSetFusionExperimentsCPP", "max_forks_repo_head_hexsha": "f56962f0ad5c62e6706f818062782a2e1660afda", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-01-07T14:12:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-06T06:30:24.000Z", "avg_line_length": 38.9487179487, "max_line_length": 120, "alphanum_fraction": 0.6115865701, "num_tokens": 317, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.45773345105040475}}
{"text": "#ifndef COMMON_HPP_INCLUDED\r\n#define COMMON_HPP_INCLUDED\r\n\r\n#include <boost/numeric/ublas/matrix_sparse.hpp>\r\n#include <boost/numeric/ublas/vector.hpp>\r\n\r\nstatic constexpr std::size_t n = 8;\r\nstatic constexpr std::size_t N = n*n;\r\n\r\nusing Matrix = boost::numeric::ublas::compressed_matrix<double>;\r\nusing Vector = boost::numeric::ublas::vector<double>;\r\nusing Index = std::remove_const_t<decltype(N)>;\r\nusing Color = Index;\r\nusing Block = Index;\r\nusing Level = Index;\r\n\r\n#endif\r\n", "meta": {"hexsha": "90bf1ca134c79952048501241e442264d4536025", "size": 479, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Abmc/common.hpp", "max_stars_repo_name": "fixstars/AlgebraicBlockMulticolorOrdering", "max_stars_repo_head_hexsha": "f1dcd7f2a0d766bf2cbe96bb48c3c870d41dea1b", "max_stars_repo_licenses": ["CC-BY-4.0", "MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-10-25T09:50:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-28T01:37:30.000Z", "max_issues_repo_path": "Abmc/common.hpp", "max_issues_repo_name": "fixstars/AlgebraicBlockMulticolorOrdering", "max_issues_repo_head_hexsha": "f1dcd7f2a0d766bf2cbe96bb48c3c870d41dea1b", "max_issues_repo_licenses": ["CC-BY-4.0", "MIT"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2018-03-19T06:41:07.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-09T03:12:09.000Z", "max_forks_repo_path": "Abmc/common.hpp", "max_forks_repo_name": "fixstars/AlgebraicBlockMulticolorOrdering", "max_forks_repo_head_hexsha": "f1dcd7f2a0d766bf2cbe96bb48c3c870d41dea1b", "max_forks_repo_licenses": ["CC-BY-4.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": 26.6111111111, "max_line_length": 65, "alphanum_fraction": 0.7369519833, "num_tokens": 112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300048, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.4577334510504047}}
{"text": "/*\nLICENSE: see isogeometric_application/LICENSE.txt\n*/\n\n//\n//   Project Name:        Kratos\n//   Last modified by:    $Author: hbui $\n//   Date:                $Date: Nov 24, 2017 $\n//   Revision:            $Revision: 1.0 $\n//\n//\n\n\n// System includes\n#include <string>\n\n// External includes\n#include <boost/foreach.hpp>\n#include <boost/python.hpp>\n#include <boost/python/stl_iterator.hpp>\n#include <boost/python/operators.hpp>\n\n// Project includes\n#include \"includes/define.h\"\n#include \"python/pointer_vector_set_python_interface.h\"\n#include \"custom_utilities/patch.h\"\n#include \"custom_utilities/control_grid_utility.h\"\n#include \"custom_utilities/hbsplines/deprecated_hb_mesh.h\"\n#include \"custom_utilities/hbsplines/hbsplines_basis_function.h\"\n#include \"custom_utilities/hbsplines/hbsplines_fespace.h\"\n#include \"custom_utilities/hbsplines/hbsplines_patch_utility.h\"\n#include \"custom_utilities/hbsplines/hbsplines_refinement_utility.h\"\n#include \"custom_utilities/import_export/multi_hbsplines_patch_matlab_exporter.h\"\n#include \"custom_python/iga_define_python.h\"\n#include \"custom_python/add_hbsplines_to_python.h\"\n#include \"custom_python/add_point_based_control_grid_to_python.h\"\n#include \"custom_python/add_import_export_to_python.h\"\n\n\nnamespace Kratos\n{\n\nnamespace Python\n{\n\nusing namespace boost::python;\n\n////////////////////////////////////////\n\n// template<int TDim>\n// std::size_t HBSplinesBasisFunction_GetId(HBSplinesBasisFunction<TDim>& rDummy)\n// {\n//     return rDummy.Id();\n// }\n\ntemplate<int TDim>\nvoid HBSplinesBasisFunction_SetId(HBSplinesBasisFunction<TDim>& rDummy, std::size_t Id)\n{\n    // DO NOTHING\n}\n\ntemplate<int TDim>\nstd::size_t HBSplinesBasisFunction_GetLevel(HBSplinesBasisFunction<TDim>& rDummy)\n{\n    return rDummy.Level();\n}\n\n// template<int TDim>\n// std::size_t HBSplinesBasisFunction_GetEquationId(HBSplinesBasisFunction<TDim>& rDummy)\n// {\n//     return rDummy.EquationId();\n// }\n\n// template<int TDim>\n// void HBSplinesBasisFunction_SetEquationId(HBSplinesBasisFunction<TDim>& rDummy, std::size_t EquationId)\n// {\n//     rDummy.SetEquationId(EquationId);\n// }\n\ntemplate<int TDim>\nboost::python::list HBSplinesFESpace_ExtractBoundaryBfsByFlag(HBSplinesFESpace<TDim>& rDummy, std::size_t boundary_id)\n{\n    typedef typename HBSplinesFESpace<TDim>::bf_t bf_t;\n\n    std::vector<bf_t> bf_list = rDummy.ExtractBoundaryBfsByFlag(boundary_id);\n\n    boost::python::list Output;\n    for (std::size_t i = 0; i < bf_list.size(); ++i)\n        Output.append(bf_list[i]);\n\n    return Output;\n}\n\ntemplate<int TDim>\nstd::size_t HBSplinesFESpace_MaxLevel(HBSplinesFESpace<TDim>& rDummy)\n{\n    return rDummy.MaxLevel();\n}\n\ntemplate<int TDim>\ntypename HBSplinesBasisFunction<TDim>::Pointer HBSplinesFESpace_GetItem(HBSplinesFESpace<TDim>& rDummy, std::size_t i)\n{\n    return rDummy[i];\n}\n\n////////////////////////////////////////\n\ntemplate<int TDim>\nvoid HBSplinesPatchUtility_ListBoundaryBfs(HBSplinesPatchUtility& rDummy,\n    typename HBSplinesFESpace<TDim>::Pointer pFESpace, BoundarySide side)\n{\n    rDummy.ListBoundaryBfs<TDim>(std::cout, pFESpace, side);\n}\n\ntemplate<int TDim>\ntypename Patch<TDim>::Pointer HBSplinesPatchUtility_CreatePatchFromBSplines(HBSplinesPatchUtility& rDummy,\n    typename Patch<TDim>::Pointer pPatch)\n{\n    return HBSplinesPatchUtility::CreatePatchFromBSplines<TDim>(pPatch);\n}\n\ntemplate<int TDim>\ntypename HBSplinesFESpace<TDim>::bf_t HBSplinesPatchUtility_GetBfByEquationId(HBSplinesPatchUtility& rDummy,\n    typename MultiPatch<TDim>::Pointer pMultiPatch, const std::size_t& EquationId)\n{\n    return rDummy.GetBfByEquationId<TDim>(pMultiPatch, EquationId);\n}\n\ntemplate<int TDim>\nvoid HBSplinesPatchUtility_ReportDuplicatedEquationId(HBSplinesPatchUtility& rDummy,\n    typename MultiPatch<TDim>::Pointer pMultiPatch, const bool& throw_error)\n{\n    return rDummy.ReportDuplicatedEquationId<TDim>(pMultiPatch, throw_error);\n}\n\n////////////////////////////////////////\n\ntemplate<int TDim>\nvoid HBSplinesRefinementUtility_Refine(HBSplinesRefinementUtility& rDummy,\n        typename Patch<TDim>::Pointer pPatch, const std::size_t& Id, const int& EchoLevel)\n{\n    rDummy.Refine<TDim>(pPatch, Id, EchoLevel);\n}\n\ntemplate<int TDim>\nvoid HBSplinesRefinementUtility_RefineBf(HBSplinesRefinementUtility& rDummy,\n        typename Patch<TDim>::Pointer pPatch, typename HBSplinesFESpace<TDim>::bf_t p_bf, const int& EchoLevel)\n{\n    rDummy.Refine<TDim>(pPatch, p_bf, EchoLevel);\n}\n\ntemplate<int TDim>\nvoid HBSplinesRefinementUtility_RefineWindow(HBSplinesRefinementUtility& rDummy,\n        typename Patch<TDim>::Pointer pPatch, boost::python::list& window, const int& EchoLevel)\n{\n    std::vector<std::vector<double> > window_vector;\n    std::size_t cnt1 = 0, cnt2 = 0;\n    typedef boost::python::stl_input_iterator<boost::python::list> iterator_value_type;\n    BOOST_FOREACH(const iterator_value_type::value_type& vect, std::make_pair(iterator_value_type(window), iterator_value_type() ) )\n    {\n        typedef boost::python::stl_input_iterator<double> iterator_value_type2;\n        std::vector<double> win_vect;\n        BOOST_FOREACH(const iterator_value_type2::value_type& v, std::make_pair(iterator_value_type2(vect), iterator_value_type2() ) )\n        {\n            win_vect.push_back(v);\n        }\n        window_vector.push_back(win_vect);\n    }\n    rDummy.RefineWindow<TDim>(pPatch, window_vector, EchoLevel);\n}\n\ntemplate<int TDim>\nvoid HBSplinesRefinementUtility_LinearDependencyRefine(HBSplinesRefinementUtility& rDummy,\n        typename Patch<TDim>::Pointer pPatch, const std::size_t& refine_cycle, const int& EchoLevel)\n{\n    rDummy.LinearDependencyRefine<TDim>(pPatch, refine_cycle, EchoLevel);\n}\n\n////////////////////////////////////////\n\n// template<typename TDataType, class TFESpaceType>\n// typename ControlGrid<TDataType>::Pointer ControlGridUtility_CreatePointBasedControlGrid(\n//         ControlGridUtility& rDummy,\n//         const Variable<TDataType>& rVariable, typename TFESpaceType::Pointer pFESpace)\n// {\n//     return rDummy.CreatePointBasedControlGrid<TDataType, TFESpaceType>(rVariable, pFESpace);\n// }\n\n////////////////////////////////////////\n\ntemplate<int TDim>\nvoid IsogeometricApplication_AddHBSplinesSpaceToPython()\n{\n\n    std::stringstream ss;\n\n    ss.str(std::string());\n    ss << \"HBSplinesBasisFunction\" << TDim << \"D\";\n    class_<HBSplinesBasisFunction<TDim>, typename HBSplinesBasisFunction<TDim>::Pointer, boost::noncopyable>\n    (ss.str().c_str(), init<const std::size_t&, const std::size_t&>())\n    // .add_property(\"Id\", HBSplinesBasisFunction_GetId<TDim>, HBSplinesBasisFunction_SetId<TDim>)\n    .add_property(\"Id\", Isogeometric_GetId<HBSplinesBasisFunction<TDim> >, HBSplinesBasisFunction_SetId<TDim>)\n    // .add_property(\"EquationId\", HBSplinesBasisFunction_GetEquationId<TDim>, HBSplinesBasisFunction_SetEquationId<TDim>)\n    .add_property(\"EquationId\", Isogeometric_GetEquationId<HBSplinesBasisFunction<TDim>>, Isogeometric_SetEquationId<HBSplinesBasisFunction<TDim>>)\n    .def(\"Weight\", &HBSplinesBasisFunction<TDim>::Weight)\n    .def(\"Level\", &HBSplinesBasisFunction_GetLevel<TDim>)\n    .def(self_ns::str(self))\n    ;\n\n    ss.str(std::string());\n    ss << \"HBSplinesFESpace\" << TDim << \"D\";\n//    typename FESpace<TDim-1>::Pointer(HBSplinesFESpace<TDim>::*pointer_to_ConstructBoundaryFESpace1)(const BoundarySide& side) const = &HBSplinesFESpace<TDim>::ConstructBoundaryFESpace;\n    // typename FESpace<TDim-1>::Pointer(HBSplinesFESpace<TDim>::*pointer_to_ConstructBoundaryFESpace2)(const BoundarySide& side, const BoundaryRotation& rotation) const = &HBSplinesFESpace<TDim>::ConstructBoundaryFESpace;\n    class_<HBSplinesFESpace<TDim>, typename HBSplinesFESpace<TDim>::Pointer, bases<FESpace<TDim> >, boost::noncopyable>\n    (ss.str().c_str(), init<>())\n    .def(\"__getitem__\", &HBSplinesFESpace_GetItem<TDim>)\n    .def(\"GetBoundaryBfs\", &HBSplinesFESpace_ExtractBoundaryBfsByFlag<TDim>) // deprecated\n    .def(\"ExtractBoundaryBfsByFlag\", &HBSplinesFESpace_ExtractBoundaryBfsByFlag<TDim>)\n//    .def(\"ConstructBoundaryFESpace\", pointer_to_ConstructBoundaryFESpace1)\n    // .def(\"ConstructBoundaryFESpace\", pointer_to_ConstructBoundaryFESpace2)\n    .def(\"UpdateCells\", &HBSplinesFESpace<TDim>::UpdateCells)\n    .def(\"MaxLevel\", &HBSplinesFESpace_MaxLevel<TDim>)\n    .def(\"SetMaxLevel\", &HBSplinesFESpace<TDim>::SetMaxLevel)\n    .def(\"GetBfByEquationId\", &HBSplinesFESpace<TDim>::pGetBfByEquationId)\n    .def(\"HasBfByEquationId\", &HBSplinesFESpace<TDim>::HasBfByEquationId)\n    .def(\"HasBfById\", &HBSplinesFESpace<TDim>::HasBfById)\n    .def(self_ns::str(self))\n    ;\n\n    IsogeometricApplication_AddPointBasedControlGrid_Helper<Variable<double>, HBSplinesFESpace<TDim> >::Execute();\n    IsogeometricApplication_AddPointBasedControlGrid_Helper<Variable<array_1d<double, 3> >, HBSplinesFESpace<TDim> >::Execute();\n    IsogeometricApplication_AddPointBasedControlGrid_Helper<Variable<Vector>, HBSplinesFESpace<TDim> >::Execute();\n\n    ////////////////////OLD H-SPLINES////////////////////////\n\n    ss.str(std::string());\n    ss << \"DeprecatedHBMesh\" << TDim << \"D\";\n    class_<DeprecatedHBMesh<TDim>, bases<Patch<TDim> > >\n    // class_<DeprecatedHBMesh<TDim>, typename DeprecatedHBMesh<TDim>::Pointer, bases<Patch<TDim> > >\n    (ss.str().c_str(), init<const std::size_t&, const std::string&>())\n    .def(\"SetEchoLevel\", &DeprecatedHBMesh<TDim>::SetEchoLevel)\n    .def(\"ReadMesh\", &DeprecatedHBMesh<TDim>::ReadMesh)\n    /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n    .def(\"Refine\", &DeprecatedHBMesh<TDim>::Refine) // use this for debugging only, use RefineNodes and LinearDependencyRefine instead\n    .def(\"RefineNodes\", &DeprecatedHBMesh<TDim>::RefineNodes)\n    .def(\"LinearDependencyRefine\", &DeprecatedHBMesh<TDim>::LinearDependencyRefine)\n    .def(\"BuildMesh\", &DeprecatedHBMesh<TDim>::BuildMesh)\n    /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n    .def(\"ExportCellTopology\", &DeprecatedHBMesh<TDim>::ExportCellTopology)\n    .def(\"ExportCellGeology\", &DeprecatedHBMesh<TDim>::ExportCellGeology)\n    //    .def(\"ExportRefinedDomain\", &DeprecatedHBMesh<TDim>::ExportRefinedDomain)\n    .def(\"ExportSupportDomain\", &DeprecatedHBMesh<TDim>::ExportSupportDomain)\n    .def(\"ExportMatlab\", &DeprecatedHBMesh<TDim>::ExportMatlab)\n    /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n    .def(\"ExportMDPA\", &DeprecatedHBMesh<TDim>::ExportMDPA)\n    .def(\"ExportMDPA2\", &DeprecatedHBMesh<TDim>::ExportMDPA2)\n    .def(\"ExportPostMDPA\", &DeprecatedHBMesh<TDim>::ExportPostMDPA)\n    .def(\"ExportCellGeologyAsPostMDPA\", &DeprecatedHBMesh<TDim>::ExportCellGeologyAsPostMDPA)\n    /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n    .def(\"PrintKnotVectors\", &DeprecatedHBMesh<TDim>::PrintKnotVectors)\n    .def(\"PrintCells\", &DeprecatedHBMesh<TDim>::PrintCells)\n    .def(\"PrintBasisFuncs\", &DeprecatedHBMesh<TDim>::PrintBasisFuncs)\n    .def(\"PrintRefinementHistory\", &DeprecatedHBMesh<TDim>::PrintRefinementHistory)\n    .def(\"CheckNestedSpace\", &DeprecatedHBMesh<TDim>::CheckNestedSpace)\n    .def(self_ns::str(self))\n    ;\n\n    ss.str(std::string());\n    ss << \"DeprecatedHBMesh\" << TDim << \"DPointer\";\n    class_<typename DeprecatedHBMesh<TDim>::Pointer>\n    (ss.str().c_str(), init<typename DeprecatedHBMesh<TDim>::Pointer>())\n    .def(\"GetReference\", GetReference<DeprecatedHBMesh<TDim> >, return_value_policy<reference_existing_object>())\n    .def(self_ns::str(self))\n    ;\n\n}\n\n////////////////////////////////////////\n\nvoid IsogeometricApplication_AddHBSplinesToPython()\n{\n\n    /////////////////////////////////////////////////////////////////\n    ///////////////////////HIERARCHICAL BSplines/////////////////////\n    /////////////////////////////////////////////////////////////////\n\n    IsogeometricApplication_AddHBSplinesSpaceToPython<1>();\n    IsogeometricApplication_AddHBSplinesSpaceToPython<2>();\n    IsogeometricApplication_AddHBSplinesSpaceToPython<3>();\n\n    class_<HBSplinesPatchUtility, HBSplinesPatchUtility::Pointer, boost::noncopyable>\n    (\"HBSplinesPatchUtility\", init<>())\n    .def(\"CreatePatchFromBSplines\", &HBSplinesPatchUtility_CreatePatchFromBSplines<2>)\n    .def(\"CreatePatchFromBSplines\", &HBSplinesPatchUtility_CreatePatchFromBSplines<3>)\n    .def(\"ListBoundaryBfs\", &HBSplinesPatchUtility_ListBoundaryBfs<2>)\n    .def(\"ListBoundaryBfs\", &HBSplinesPatchUtility_ListBoundaryBfs<3>)\n    .def(\"GetBfByEquationId\", &HBSplinesPatchUtility_GetBfByEquationId<2>)\n    .def(\"GetBfByEquationId\", &HBSplinesPatchUtility_GetBfByEquationId<3>)\n    .def(\"ReportDuplicatedEquationId\", &HBSplinesPatchUtility_ReportDuplicatedEquationId<2>)\n    .def(\"ReportDuplicatedEquationId\", &HBSplinesPatchUtility_ReportDuplicatedEquationId<3>)\n    .def(self_ns::str(self))\n    ;\n\n    class_<HBSplinesRefinementUtility, typename HBSplinesRefinementUtility::Pointer, boost::noncopyable>\n    (\"HBSplinesRefinementUtility\", init<>())\n    .def(\"Refine\", &HBSplinesRefinementUtility_Refine<2>)\n    .def(\"Refine\", &HBSplinesRefinementUtility_Refine<3>)\n    .def(\"Refine\", &HBSplinesRefinementUtility_RefineBf<2>)\n    .def(\"Refine\", &HBSplinesRefinementUtility_RefineBf<3>)\n    .def(\"RefineWindow\", &HBSplinesRefinementUtility_RefineWindow<2>)\n    .def(\"RefineWindow\", &HBSplinesRefinementUtility_RefineWindow<3>)\n    .def(\"LinearDependencyRefine\", &HBSplinesRefinementUtility_LinearDependencyRefine<2>)\n    .def(\"LinearDependencyRefine\", &HBSplinesRefinementUtility_LinearDependencyRefine<3>)\n    .def(self_ns::str(self))\n    ;\n\n    class_<MultiHBSplinesPatchMatlabExporter, MultiHBSplinesPatchMatlabExporter::Pointer, boost::noncopyable>\n    (\"MultiHBSplinesPatchMatlabExporter\", init<>())\n    .def(\"Export\", &MultiPatchExporter_Export<1, MultiHBSplinesPatchMatlabExporter, Patch<1> >)\n    .def(\"Export\", &MultiPatchExporter_Export<2, MultiHBSplinesPatchMatlabExporter, Patch<2> >)\n    .def(\"Export\", &MultiPatchExporter_Export<3, MultiHBSplinesPatchMatlabExporter, Patch<3> >)\n    .def(\"Export\", &MultiPatchExporter_Export<1, MultiHBSplinesPatchMatlabExporter, MultiPatch<1> >)\n    .def(\"Export\", &MultiPatchExporter_Export<2, MultiHBSplinesPatchMatlabExporter, MultiPatch<2> >)\n    .def(\"Export\", &MultiPatchExporter_Export<3, MultiHBSplinesPatchMatlabExporter, MultiPatch<3> >)\n    .def(self_ns::str(self))\n    ;\n\n}\n\n}  // namespace Python.\n\n} // Namespace Kratos\n\n", "meta": {"hexsha": "d21d8011d9f4ffe232a0132bb2a4f57bf427b725", "size": 14224, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "custom_python/add_hbsplines_to_python.cpp", "max_stars_repo_name": "rwilliams01/isogeometric_application", "max_stars_repo_head_hexsha": "e505061603b56b4f426220946da5ec551dc6c142", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "custom_python/add_hbsplines_to_python.cpp", "max_issues_repo_name": "rwilliams01/isogeometric_application", "max_issues_repo_head_hexsha": "e505061603b56b4f426220946da5ec551dc6c142", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "custom_python/add_hbsplines_to_python.cpp", "max_forks_repo_name": "rwilliams01/isogeometric_application", "max_forks_repo_head_hexsha": "e505061603b56b4f426220946da5ec551dc6c142", "max_forks_repo_licenses": ["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.5868263473, "max_line_length": 222, "alphanum_fraction": 0.7253937008, "num_tokens": 3969, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585669110203, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.4577334437128652}}
{"text": "#ifndef ZSVM_SPHERICAL_ECG_JACOBI_CONTEXT_HPP\n#define ZSVM_SPHERICAL_ECG_JACOBI_CONTEXT_HPP\n\n// C++ standard library headers\n#include <cstddef> // for std::size_t\n#include <vector>\n\n// Eigen linear algebra library headers\n#include <Eigen/Core>\n\n// Project-specific headers\n#include \"Restrict.hpp\"\n#include \"JacobiCoordinates.hpp\"\n#include \"PackedLinearAlgebra.hpp\"\n#include \"Particle.hpp\"\n#include \"Permutation.hpp\"\n\nnamespace zsvm {\n\n    template <typename T>\n    class SphericalECGJacobiContext {\n\n    private: // =============================================== MEMBER VARIABLES\n\n        typedef Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> MatrixXT;\n\n        const std::size_t num_particles;\n        const std::size_t num_pairs;\n        const std::size_t num_permutations;\n        const std::size_t matrix_size;\n        const long long int space_dimension;\n        const T dimension_factor;\n        const T kinetic_factor;\n\n        const std::vector<T> inverse_masses;\n        const std::vector<T> weight_vectors;\n        const std::vector<T> weight_matrices;\n        const std::vector<T> charge_products;\n        const std::vector<T> permutation_signs;\n        const std::vector<T> permutation_matrices;\n\n        std::vector<T> vax;\n        std::vector<T> vbx;\n        std::vector<T> vcx;\n        std::vector<T> vdx;\n\n        const packed_determinant_inverse_function<T> packed_determinant_inverse;\n        const packed_kinetic_trace_function<T> packed_kinetic_trace;\n        const packed_quadratic_form_function<T> packed_quadratic_form;\n        const packed_permutation_conjugate_function<T> packed_permutation_conjugate;\n\n    private: // ============================================ FACTORY CONSTRUCTOR\n\n        T gamma(const T &x) {\n            using std::tgamma;\n            return tgamma(x);\n        }\n\n        explicit SphericalECGJacobiContext(\n                const std::vector<T> &charges,\n                std::size_t num_permutations,\n                long long int space_dimension,\n                const MatrixXT &inverse_mass_matrix,\n                const MatrixXT &pairwise_weight_vectors,\n                const std::vector<T> &permutation_sign_vector,\n                const std::vector<MatrixXT> &permutation_matrix_vector)\n                : num_particles(charges.size()),\n                  num_pairs(num_particles * (num_particles - 1) / 2),\n                  num_permutations(num_permutations),\n                  matrix_size((num_particles - 1) * (num_particles - 1)),\n                  space_dimension(space_dimension),\n                  dimension_factor(gamma((space_dimension - static_cast<T>(1)) /\n                                         static_cast<T>(2)) /\n                                   gamma(space_dimension / static_cast<T>(2))),\n                  kinetic_factor(space_dimension / (2 * dimension_factor)),\n                  inverse_masses(num_particles - 1),\n                  weight_vectors(num_pairs * (num_particles - 1)),\n                  weight_matrices(num_pairs * num_pairs),\n                  charge_products(num_pairs),\n                  permutation_signs(num_permutations),\n                  permutation_matrices(num_permutations * matrix_size),\n                  vax(num_pairs),\n                  vbx(num_pairs),\n                  vcx(num_pairs),\n                  vdx(num_pairs),\n                  packed_determinant_inverse(\n                          PackedDeterminantInverse<T>::functions()[\n                                  num_particles - 2]),\n                  packed_kinetic_trace(\n                          PackedKineticTrace<T>::functions()[\n                                  num_particles - 2]),\n                  packed_quadratic_form(\n                          PackedQuadraticForm<T>::functions()[\n                                  num_particles - 2]),\n                  packed_permutation_conjugate(\n                          PackedPermutationConjugate<T>::functions()[\n                                  num_particles - 2]) {\n            auto inverse_mass_pointer = const_cast<T *>(inverse_masses.data());\n            for (std::size_t i = 0; i < num_particles - 1; ++i) {\n                inverse_mass_pointer[i] = inverse_mass_matrix(i, i);\n            }\n            auto weight_vector_pointer = const_cast<T *>(weight_vectors.data());\n            for (std::size_t p = 0, k = 0; p < num_pairs; ++p) {\n                for (std::size_t i = 0; i < num_particles - 1; ++i, ++k) {\n                    weight_vector_pointer[k] = pairwise_weight_vectors(i, p);\n                }\n            }\n            auto weight_matrix_pointer = const_cast<T *>(weight_matrices.data());\n            for (std::size_t p = 0, k = 0; p < num_pairs; ++p) {\n                for (std::size_t i = 0; i < num_particles - 1; ++i) {\n                    for (std::size_t j = 0; j <= i; ++j, ++k) {\n                        weight_matrix_pointer[k] =\n                                pairwise_weight_vectors(i, p) *\n                                pairwise_weight_vectors(j, p);\n                    }\n                }\n            }\n            auto charge_product_pointer = const_cast<T *>(charge_products.data());\n            for (std::size_t i = 0, k = 0; i < num_particles - 1; ++i) {\n                for (std::size_t j = i + 1; j < num_particles; ++j, ++k) {\n                    charge_product_pointer[k] = charges[i] * charges[j];\n                }\n            }\n            auto permutation_sign_pointer = const_cast<T *>(permutation_signs.data());\n            for (std::size_t p = 0; p < num_permutations; ++p) {\n                permutation_sign_pointer[p] = permutation_sign_vector[p];\n            }\n            auto permutation_matrix_pointer = const_cast<T *>(permutation_matrices.data());\n            for (std::size_t p = 0, k = 0; p < num_permutations; ++p) {\n                for (std::size_t i = 0; i < num_particles - 1; ++i) {\n                    for (std::size_t j = 0; j < num_particles - 1; ++j, ++k) {\n                        permutation_matrix_pointer[k] =\n                                permutation_matrix_vector[p](j, i);\n                    }\n                }\n            }\n        }\n\n    public: // =========================================== STATIC FACTORY METHOD\n\n        static SphericalECGJacobiContext create(\n                const std::vector<zsvm::Particle<T>> &particles,\n                const std::string &mass_carrier,\n                const std::string &charge_carrier,\n                long long int space_dimension) {\n            const std::size_t num_particles = particles.size();\n            if (num_particles < 2) {\n                throw std::invalid_argument(\n                        \"Attempted to construct SphericalECGJacobiContext \"\n                        \"with fewer than 2 particles\");\n            }\n            std::vector<T> masses(num_particles);\n            std::vector<T> charges(num_particles);\n            for (std::size_t i = 0; i < num_particles; ++i) {\n                masses[i] = particles[i].carriers.at(mass_carrier);\n                charges[i] = particles[i].carriers.at(charge_carrier);\n            }\n            const std::vector<std::vector<std::size_t>> allowed_permutations =\n                    dznl::invariant_permutations(particles);\n            std::vector<T> permutation_signs;\n            for (const auto &permutation : allowed_permutations) {\n                const std::size_t signature =\n                        dznl::count_changes(particles, permutation) / 2 +\n                        dznl::count_inversions(permutation);\n                permutation_signs.push_back((signature % 2 == 0) ? +1 : -1);\n            }\n            return SphericalECGJacobiContext(\n                    charges,\n                    allowed_permutations.size(),\n                    space_dimension,\n                    jaco::reduced_inverse_mass_matrix(masses),\n                    jaco::pairwise_weights(masses),\n                    permutation_signs,\n                    jaco::permutation_matrices(masses, allowed_permutations));\n        }\n\n    private: // ================================== MATRIX ELEMENT HELPER METHODS\n\n        void matrix_element_kernel(\n                T &RESTRICT overlap_kernel,\n                T &RESTRICT hamiltonian_kernel) {\n            using std::sqrt;\n            T *RESTRICT const ax = vax.data();\n            T *RESTRICT const bx = vbx.data();\n            T *RESTRICT const cx = vcx.data();\n            T *RESTRICT const dx = vdx.data();\n            for (std::size_t i = 0; i < num_pairs; ++i) {\n                cx[i] = ax[i] + bx[i];\n            }\n            overlap_kernel = half_inverse_pow(\n                    packed_determinant_inverse(cx, dx), space_dimension);\n            hamiltonian_kernel = kinetic_factor * packed_kinetic_trace(\n                    ax, bx, dx, inverse_masses.data());\n            for (std::size_t k = 0; k < num_pairs; ++k) {\n                const T alpha = packed_quadratic_form(\n                        dx, weight_vectors.data() + (num_particles - 1) * k);\n                hamiltonian_kernel += charge_products[k] / sqrt(2 * alpha);\n            }\n            hamiltonian_kernel *= dimension_factor * overlap_kernel;\n        }\n\n    public: // ========================================== MATRIX ELEMENT METHODS\n\n        void gaussian_parameter_matrix(\n                const T *RESTRICT correlation_coefficients,\n                T *RESTRICT result) const {\n            using std::exp;\n            for (std::size_t p = 0; p < num_pairs; ++p) { result[p] = 0; }\n            for (std::size_t p = 0, k = 0; p < num_pairs; ++p) {\n                const T c = exp(correlation_coefficients[p]);\n                for (std::size_t q = 0; q < num_pairs; ++q, ++k) {\n                    result[q] += c * weight_matrices[k];\n                }\n            }\n        }\n\n        void evaluate_matrix_elements(\n                T &RESTRICT overlap_element,\n                T &RESTRICT hamiltonian_element,\n                const T *a, const T *b) {\n            T *RESTRICT const ax = vax.data();\n            T *RESTRICT const bx = vbx.data();\n            overlap_element = hamiltonian_element = 0;\n            T overlap_kernel, hamiltonian_kernel;\n            for (std::size_t i = 0; i < num_permutations; ++i) {\n                for (std::size_t j = 0; j < num_permutations; ++j) {\n                    const T sign = permutation_signs[i] * permutation_signs[j];\n                    packed_permutation_conjugate(\n                            a, permutation_matrices.data() + i * matrix_size,\n                            ax);\n                    packed_permutation_conjugate(\n                            b, permutation_matrices.data() + j * matrix_size,\n                            bx);\n                    matrix_element_kernel(overlap_kernel, hamiltonian_kernel);\n                    overlap_element += sign * overlap_kernel;\n                    hamiltonian_element += sign * hamiltonian_kernel;\n                }\n            }\n        }\n\n    }; // class SphericalECGJacobiContext\n\n} // namespace zsvm\n\n#endif // ZSVM_SPHERICAL_ECG_JACOBI_CONTEXT_HPP\n", "meta": {"hexsha": "2c87b654cb54ddfc143a7525edad7469669699c6", "size": 11073, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "SphericalECGJacobiContext.hpp", "max_stars_repo_name": "dzhang314/zsvm", "max_stars_repo_head_hexsha": "cf7155627e446e095b5888f828ea879378834eaa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SphericalECGJacobiContext.hpp", "max_issues_repo_name": "dzhang314/zsvm", "max_issues_repo_head_hexsha": "cf7155627e446e095b5888f828ea879378834eaa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SphericalECGJacobiContext.hpp", "max_forks_repo_name": "dzhang314/zsvm", "max_forks_repo_head_hexsha": "cf7155627e446e095b5888f828ea879378834eaa", "max_forks_repo_licenses": ["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.012195122, "max_line_length": 91, "alphanum_fraction": 0.5227129053, "num_tokens": 2330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795402, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4576907227698702}}
{"text": "#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <boost/graph/kruskal_min_spanning_tree.hpp>\n#include <boost/graph/connected_components.hpp>\n#include <boost/graph/metric_tsp_approx.hpp>\n#include \"cPathFinder.h\"\nusing namespace boost;\n\nvoid cPathFinder::clear()\n{\n    myGraph.clear();\n    myDirGraph.clear();\n    myMaxNegCost = 0;\n}\n\nvoid cPathFinder::start(int start)\n{\n    myStart = start;\n}\nvoid cPathFinder::start(const std::string &start)\n{\n    myStart = find(start);\n    if (myStart < 0)\n        throw std::runtime_error(\"cPathFinder::bad start node\");\n}\nint cPathFinder::start() const\n{\n    return myStart;\n}\n\nvoid cPathFinder::paths(int start)\n{\n    if (!myfDirected)\n        pathsT(start, myGraph);\n    else\n        pathsT(start, myDirGraph);\n}\ntemplate <typename T>\nvoid cPathFinder::pathsT(int start, T &g)\n{\n    // run dijkstra algorithm\n    myPred.clear();\n    myDist.clear();\n    myPred.resize(num_vertices(g));\n    myDist.resize(num_vertices(g));\n    dijkstra_shortest_paths(\n        g,\n        start,\n        weight_map(get(&cEdge::myCost, g))\n            .predecessor_map(boost::make_iterator_property_map(\n                myPred.begin(), get(boost::vertex_index, g)))\n            .distance_map(boost::make_iterator_property_map(\n                myDist.begin(), get(boost::vertex_index, g))));\n    // std::cout << \"<-cPathFinder::path \";\n}\n\nvoid cPathFinder::path()\n{\n    if (myStart < 0)\n        throw std::runtime_error(\"cPathFinder::path start node undefined\");\n\n    // run the Dijsktra algorithm\n    paths(myStart);\n\n    if (myEnd >= 0)\n\n        // pick out the path from source to destination\n        pathPick(myEnd);\n\n    else\n    {\n        std::cout << \"Hop count from root to every node:\\n\";\n        for (int kv = 0; kv < num_vertices(myGraph); kv++)\n        {\n            if (kv == myStart)\n                continue;\n            pathPick(kv);\n            //std::cout << pathText() << \"\\n\";\n            std::cout << nodeName(myStart) << \" to \"\n                      << nodeName(kv) << \" \"\n                      << myPath.size() - 1 << \"\\n\";\n        }\n    }\n}\n\nint cPathFinder::distance(int end)\n{\n    if (0 > end || end >> (int)myDist.size())\n        return -1;\n    return myDist[end];\n}\n\nvoid cPathFinder::span()\n{\n    typedef graph_traits<graph_t>::edge_descriptor edge_t;\n    std::vector<edge_t> spanning_tree;\n    kruskal_minimum_spanning_tree(\n        myGraph,\n        std::back_inserter(spanning_tree),\n        weight_map(get(&cEdge::myCost, myGraph)));\n\n    std::cout << \"spanning_tree \" << spanning_tree.size() << \"\\n\";\n    mySpanCost = 0;\n    mySpan.clear();\n    for (auto e : spanning_tree)\n    {\n        mySpanCost += myGraph[e].myCost;\n        std::vector<int> ve{\n            (int)source(e, myGraph),\n            (int)target(e, myGraph)};\n        mySpan.push_back(ve);\n    }\n}\n\nstd::vector<int> cPathFinder::pathPick(int end)\n{\n    myPath.clear();\n    // std::cout << \"->cPathFinder::pathPick \"\n    //     << myStart <<\" \" << end << \"\\n\";\n\n    if (end < 0)\n        throw std::runtime_error(\"cPathFinder::pathPick bad end node\");\n    if (myPred[end] == end)\n        throw std::runtime_error(\"There is no path from \" + std::to_string(myStart) + \" to \" + std::to_string(end));\n\n    // pick out path, starting at goal and finishing at start\n    myPath.push_back(end);\n    int prev = end;\n    while (1)\n    {\n        //std::cout << prev << \" \" << myPred[prev] << \", \";\n        int next = myPred[prev];\n        myPath.push_back(next);\n        if (next == myStart)\n            break;\n        prev = next;\n    }\n\n    // reverse so path goes from start to goal\n    std::reverse(myPath.begin(), myPath.end());\n\n    return myPath;\n}\n\nvoid cPathFinder::tsp()\n{\n    if (myfDirected)\n        throw std::runtime_error(\n            \"cPathFinder::tsp does not handle directed graphs\");\n\n    double len = 0; //length of the tour\n    auto tour_visitor = make_tsp_tour_len_visitor(\n        myGraph,\n        std::back_inserter(myPath),\n        len,\n        get(&cEdge::myCost, myGraph));\n    metric_tsp_approx(\n        myGraph,\n        get(&cEdge::myCost, myGraph),\n        get(vertex_index, myGraph),\n        tour_visitor);\n    // metric_tsp_approx_from_vertex(\n    //     myGraph,\n    //     myStart,\n    //     get(&cEdge::myCost, myGraph),\n    //     get(vertex_index, myGraph),\n    //     tour_visitor);\n}\n\nvoid cPathFinder::addLink(\n    int u,\n    int v,\n    float cost)\n{\n    if (u < 0 || v < 0)\n        throw std::runtime_error(\"cPathFinder::addLink bad node\");\n    if (!myfDirected)\n        myGraph[add_edge(u, v, myGraph).first].myCost = cost;\n    else\n        myDirGraph[add_edge(u, v, myDirGraph).first].myCost = cost;\n}\n\nvoid cPathFinder::addLink(\n    const std::string &su,\n    const std::string &sv,\n    float cost)\n{\n    addLink(\n        findoradd(su),\n        findoradd(sv),\n        cost);\n}\n\nint cPathFinder::findoradd(const std::string &name)\n{\n    int n = find(name);\n    if (n < 0)\n        n = add_vertex(name, myGraph);\n    return n;\n}\n\nint cPathFinder::addNode(const std::string &name)\n{\n    if (myfDirected)\n        return add_vertex(name, myDirGraph);\n    else\n        return add_vertex(name, myGraph);\n}\n\nvoid cPathFinder::deleteNode(int n)\n{\n    if (myfDirected)\n        return remove_vertex(n, myDirGraph);\n    else\n        return remove_vertex(n, myGraph);\n}\nint cPathFinder::find(const std::string &name)\n{\n    for (int n = 0; n < num_vertices(myGraph); n++)\n    {\n        //std::cout << myGraph[n].myName << \" \";\n        if (myGraph[n].myName == name)\n        {\n            return n;\n        }\n    }\n    //std::cout << name << \" not found\\n\";\n    return -1;\n}\n\nint cPathFinder::nodeCount()\n{\n    if (!myfDirected)\n        return num_vertices(myGraph);\n    else\n        return num_vertices(myDirGraph);\n}\nint cPathFinder::linkCount()\n{\n    if (!myfDirected)\n        return num_edges(myGraph);\n    else\n        return num_edges(myDirGraph);\n}\n\nstd::string cPathFinder::linksText()\n{\n    if (!myfDirected)\n        return linksTextT(myGraph);\n    else\n        return linksTextT(myDirGraph);\n}\ntemplate <typename T>\nstd::string cPathFinder::linksTextT(T &g)\n{\n    std::stringstream ss;\n    typename graph_traits<T>::edge_iterator ei, ei_end;\n    for (tie(ei, ei_end) = edges(g); ei != ei_end; ++ei)\n    {\n        std::string un = g[source(*ei, g)].myName;\n        if (un == \"???\")\n            un = std::to_string(source(*ei, g));\n        std::string vn = g[target(*ei, g)].myName;\n        if (vn == \"???\")\n            vn = std::to_string(target(*ei, g));\n        ss << \"(\"\n           << un << \",\"\n           << vn << \",\"\n           << g[*ei].myCost\n           << \") \";\n    }\n    ss << \"\\n\";\n    return ss.str();\n}\n\nbool cPathFinder::IsAdjacent(int u, int v)\n{\n    if (u < 0 || v < 0)\n        return false;\n    return edge(u, v, myGraph).second;\n}\n\nbool cPathFinder::IsConnected()\n{\n    return (1 == islandCount());\n}\nint cPathFinder::islandCount()\n{\n    std::vector<int> component(boost::num_vertices(myGraph));\n    return boost::connected_components(myGraph, &component[0]);\n}\n\nstd::string cPathFinder::nodeName(int n) const\n{\n    std::string sn = myGraph[n].myName;\n    if (sn == \"???\")\n        sn = std::to_string(n);\n    return sn;\n}\n\nstd::string cPathFinder::nodeColor(int n) const\n{\n    return myGraph[n].myColor;\n}\nvoid cPathFinder::nodeColor(int n, const std::string &color)\n{\n    if (myfDirected)\n        myDirGraph[n].myColor = color;\n    else\n        myGraph[n].myColor = color;\n}\nstd::string cPathFinder::pathText()\n{\n    std::stringstream ss;\n    for (auto n : myPath)\n    {\n        std::string sn;\n        if (myfDirected)\n        {\n            sn = myDirGraph[n].myName;\n        }\n        else\n        {\n            sn = myGraph[n].myName;\n        }\n        if (sn == \"???\")\n            sn = std::to_string(n);\n        ss << sn << \" -> \";\n        //ss << std::to_string(n) << \" -> \";\n    }\n\n    if (myPath.size())\n    {\n        //std::cout << \"dbg \" << myDist[myPath.back()] << \" \" << myMaxNegCost << \" \" << myPath.size() << \"\\n\";\n        ss << \" Cost is \"\n           << myDist[myPath.back()] + myMaxNegCost * (myPath.size() - 1)\n           << \"\\n\";\n    }\n\n    return ss.str();\n}\n\nstd::string cPathFinder::spanText()\n{\n    // std::cout << \"spanText \" << mySpan.size()\n    //           << \" cost \" << mySpanCost << \"\\n\";\n\n    std::stringstream ss;\n    for (auto e : mySpan)\n    {\n        ss << nodeName(e[0])\n           << \" - \"\n           << nodeName(e[1])\n           << \", \";\n    }\n    ss << \" cost \" << mySpanCost << \"\\n\";\n    return ss.str();\n}\n\nvoid cPathFinder::makeCostsPositive(int cost)\n{\n    graph_traits<graph_t>::edge_iterator ei, ei_end;\n    for (tie(ei, ei_end) = edges(myGraph); ei != ei_end; ++ei)\n    {\n        myGraph[*ei].myCost -= cost;\n    }\n    myMaxNegCost = cost;\n}\n\nvoid cPathFinder::makeComplete()\n{\n    for (int u = 0; u < linkCount(); u++)\n    {\n        for (int v = u + 1; v < linkCount(); v++)\n        {\n            if (!edge(u, v, myGraph).second)\n                addLink(\n                    u, v,\n                    INT_MAX);\n        }\n    }\n}\n\nstd::string cPathFinder::pathViz()\n{\n    return pathViz(myPath);\n}\n\nstd::string cPathFinder::pathViz(\n    const std::vector<int> &vp,\n    bool all)\n{\n    if (myfDirected)\n        return pathVizT(vp, all, myDirGraph);\n    else\n        return pathVizT(vp, all, myGraph);\n}\n\ntemplate <typename T>\nstd::string cPathFinder::pathVizT(\n    const std::vector<int> &vp,\n    bool all,\n    T &g)\n{\n    std::string graphvizgraph = \"graph\";\n    std::string graphvizlink = \"--\";\n    if (myfDirected)\n    {\n        graphvizgraph = \"digraph\";\n        graphvizlink = \"->\";\n    }\n\n    std::stringstream f;\n    f << graphvizgraph << \" G {\\n\";\n    for (int v = *vertices(g).first; v != *vertices(g).second; ++v)\n    {\n        f << g[v].myName\n          << \" [color=\\\"\" << g[v].myColor << \"\\\"  penwidth = 3.0 ];\\n\";\n    }\n\n    // loop over links\n    typename graph_traits<T>::edge_iterator ei, ei_end;\n    for (tie(ei, ei_end) = edges(g); ei != ei_end; ++ei)\n    {\n        // check if link between two nodes on path\n        bool onpath = false;\n        int src = source(*ei, g);\n        int dst = target(*ei, g);\n        auto pathItsrc = std::find(vp.begin(), vp.end(), src);\n        auto pathItdst = std::find(vp.begin(), vp.end(), dst);\n        if (pathItsrc != vp.end() && pathItdst != vp.end())\n        {\n            if (myfDirected)\n            {\n                if (pathItsrc == pathItdst - 1)\n                    onpath = true;\n            }\n            else\n            {\n                if (pathItsrc == pathItdst + 1 || pathItsrc == pathItdst - 1)\n                    onpath = true;\n            }\n        }\n\n        if (all)\n        {\n            f << g[src].myName << graphvizlink\n              << g[dst].myName << \" \";\n            if (onpath)\n                f << \"[color=\\\"red\\\"] \";\n            f << \";\\n\";\n        }\n        else\n        {\n            if (onpath)\n                f << g[src].myName << graphvizlink\n                  << g[dst].myName << \" ;\\n\";\n        }\n    }\n\n    f << \"}\\n\";\n    return f.str();\n}\n\nstd::string cPathFinder::spanViz(bool all)\n{\n    std::stringstream f;\n    f << \"graph G {\\n\";\n    for (int v = *vertices(myGraph).first; v != *vertices(myGraph).second; ++v)\n    {\n        auto sn = myGraph[v].myName;\n        int x = atoi(sn.substr(1).c_str());\n        int y = atoi(sn.substr(sn.find(\"x\") + 1).c_str());\n        f << sn\n          << \" [pos=\\\"\"\n          << std::to_string(x)\n          << \",\"\n          << std::to_string(y)\n          << \"\\\"];\\n\";\n    }\n\n    graph_traits<graph_t>::edge_iterator ei, ei_end;\n    for (tie(ei, ei_end) = edges(myGraph); ei != ei_end; ++ei)\n    {\n        auto src = myGraph[source(*ei, myGraph)].myName;\n        auto dst = myGraph[target(*ei, myGraph)].myName;\n        bool span = false;\n        for (auto &se : mySpan)\n        {\n            if (src == myGraph[se[0]].myName && dst == myGraph[se[1]].myName ||\n                src == myGraph[se[1]].myName && dst == myGraph[se[0]].myName)\n            {\n                span = true;\n                break;\n            }\n        }\n        if (all)\n        {\n            f << src << \"--\"\n              << dst << \" \";\n            if (span)\n                f << \"[color=\\\"red\\\"]\";\n            f << \";\\n\";\n        }\n        else if (span)\n        {\n            f << src << \"--\"\n              << dst\n              << \" [color=\\\"red\\\"];\\n\";\n        }\n    }\n    f << \"}\\n\";\n    return f.str();\n}\n\nvoid cPathFinder::cams()\n{\n    //     APPROXIMATION-VERTEX-COVER(G)=\n    // C = \u2205\n    // E'= G.E\n\n    // while E' \u2260 \u2205:\n    //     let (u, v) be an arbitrary edge of E'\n    //     C = C \u222a {u, v}\n    //     remove from E' every edge incident on either u or v\n\n    // remove all leaf nodes from C\n    // return C\n\n    // store indices of nodes that cover links\n    std::set<int> setCover;\n\n    // graph of links between covering nodes\n    graph_t cover;\n\n    // working copy on input graph\n    auto work = myGraph;\n\n    myPath.clear();\n\n    graph_traits<graph_t>::out_edge_iterator ei, ei_end;\n\n    // loop until all links are covered\n    while (num_edges(work))\n    {\n        // select first link in working graph\n        auto it = edges(work).first;\n        int u = source(*it, work);\n        int v = target(*it, work);\n\n        // add  non leaf nodes on selected link to cover\n        if (out_degree(u, myGraph) > 1)\n            setCover.insert(u);\n        if (out_degree(v, myGraph) > 1)\n            setCover.insert(v);\n\n        // remove all links that can be seen from new cover nodes\n        for (boost::tie(ei, ei_end) = out_edges(u, work); ei != ei_end; ++ei)\n        {\n            remove_edge(*ei, work);\n        }\n        for (boost::tie(ei, ei_end) = out_edges(v, work); ei != ei_end; ++ei)\n        {\n            remove_edge(*ei, work);\n        }\n    }\n\n    std::cout << \"nodes that cover all vertices:\\n\";\n    for (int u : setCover)\n    {\n        // exclude edge nodes, their link will be covered from other end\n        std::cout << u << \" \";\n        myGraph[u].myColor = \"red\";\n    }\n    std::cout << \"\\n\";\n}\n\nvoid cPathFinder::hills(\n    const std::vector<std::vector<float>> &gheight)\n{\n\n    // cost links according to change in height they incur\n    int rowCount = gheight.size();\n    if (!rowCount)\n        throw std::runtime_error(\n            \"cPathFinder::hills bad grid\");\n    int colCount = gheight[0].size();\n\n    graph_traits<dir_graph_t>::edge_iterator ei, ei_end;\n    for (boost::tie(ei, ei_end) = edges(myDirGraph); ei != ei_end; ++ei)\n    {\n        int source = boost::source(*ei, myDirGraph);\n        int target = boost::target(*ei, myDirGraph);\n        int srow = source / colCount;\n        int scol = source - srow * colCount;\n        int trow = target / colCount;\n        int tcol = target - trow * colCount;\n        float sh = gheight[srow][scol];\n        float th = gheight[trow][tcol];\n        float delta = th - sh;\n        myDirGraph[*ei].myCost = 1 + delta * delta;\n    }\n\n    path();\n\n    std::cout << \"hills \" << pathText() << \"\\n\";\n}\n\nvoid cPathFinder::gsingh()\n{\n    //loop over source nodes\n    for (int src = 0; src < nodeCount(); src++)\n    {\n        // Run Dijsktra\n        myStart = src;\n        paths(src);\n\n        // loop over destination nodes\n        for (int dst = 0; dst < nodeCount(); dst++)\n        {\n            if (src == dst)\n                continue;\n\n            // display paths that visit 5 nodes\n            if (pathPick(dst).size() == 5)\n                std::cout << pathText();\n        }\n    }\n}\nvoid cPathFinder::shaun()\n{\n    int MaxNegCost = 0;\n    graph_traits<graph_t>::edge_iterator ei, ei_end;\n    for (boost::tie(ei, ei_end) = edges(myGraph); ei != ei_end; ++ei)\n    {\n        int source = boost::source(*ei, myGraph);\n        int target = boost::target(*ei, myGraph);\n        int cost = atoi(myGraph[target].myColor.c_str()) - atoi(myGraph[source].myColor.c_str());\n        myDirGraph[add_edge(source, target, myDirGraph).first].myCost = cost;\n        myDirGraph[add_edge(target, source, myDirGraph).first].myCost = -cost;\n        if (cost < MaxNegCost)\n            MaxNegCost = cost;\n        if (-cost < MaxNegCost)\n            MaxNegCost = -cost;\n    }\n    graph_traits<dir_graph_t>::edge_iterator dei, dei_end;\n    for (boost::tie(dei, dei_end) = edges(myDirGraph); dei != dei_end; ++dei)\n    {\n        std::cout << boost::source(*dei, myDirGraph) << \" -> \"\n                  << boost::target(*dei, myDirGraph) << \" cost \"\n                  << myDirGraph[*dei].myCost << \" converts to \";\n\n        myDirGraph[*dei].myCost -= MaxNegCost;\n        myDirGraph[*dei].myCost += 2 * MaxNegCost;\n        myDirGraph[*dei].myCost *= -1;\n\n        std::cout\n            << myDirGraph[*dei].myCost << \"\\n\\n\";\n    }\n    myfDirected = true;\n    //tsp();\n}", "meta": {"hexsha": "fcd0f01137c3fe92af4e78788ad30100dd93a806", "size": 16751, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cPathFinder.cpp", "max_stars_repo_name": "JamesBremner/PathFinderMay2021", "max_stars_repo_head_hexsha": "beb18dfa3b6ffedc268fa10c273ea422ffcbf48c", "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/cPathFinder.cpp", "max_issues_repo_name": "JamesBremner/PathFinderMay2021", "max_issues_repo_head_hexsha": "beb18dfa3b6ffedc268fa10c273ea422ffcbf48c", "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/cPathFinder.cpp", "max_forks_repo_name": "JamesBremner/PathFinderMay2021", "max_forks_repo_head_hexsha": "beb18dfa3b6ffedc268fa10c273ea422ffcbf48c", "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": 25.3419062027, "max_line_length": 116, "alphanum_fraction": 0.5251626769, "num_tokens": 4647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4576907174003546}}
{"text": "#include <iostream>\n#include <cmath>\n#include <fstream>\n#include <functional>\n#include <boost/exception/diagnostic_information.hpp>\n#include <boost/lexical_cast.hpp>\n#include \"fft.hpp\"\n#include \"potgen.hpp\"\n#include \"fileIO.hpp\"\n#include \"potgen_args.h\"\n#include \"profiling.hpp\"\n#include \"correlation.hpp\"\n#include \"discretize.hpp\"\n\nint main(int argc, const char* argv[])\n{\n\tparse_parameters(argc, argv);\n\n\tPGOptions opt;\n\n    // Get options from command line\n\topt.randomSeed         = pargs::seed;\n\topt.maxDerivativeOrder = pargs::derivative_order;\n\topt.corrlength         = pargs::correlation_length;\n\topt.numThreads         = pargs::threads;\n\topt.verbose            = pargs::print_profile;\n\n\t\n\t// check that dimension is valid\n\tif( pargs::dim < 1 || pargs::dim > 3)\n\t{\n\t\tstd::cerr << \"invalid dimension \" << pargs::dim << \" specified\\n\";\n\t\treturn EXIT_FAILURE;\n\t}\n\t\n    try\n\t{\n\t\t// create output file, so if sth goes wrong we do not need to wait for the computation to finish\n\t\t// to issue an error\n\t\tstd::fstream save(pargs::potential_outfile, std::fstream::out | std::fstream::binary);\n\t\tif( !save.good())\n\t\t{\n\t\t\tstd::cerr << \"could not open result file \" << pargs::potential_outfile << \" \" << std::strerror(errno) << \"\\n\";\n\t\t\treturn EXIT_FAILURE;\n\t\t}\n\n\t\t// generate the correlation function\n\t\topt.cor_fun = makeCorrelation( pargs::correlation_function, pargs::correlation_length, pargs::correlation_trafo);\n\n\t\tstd::vector<std::size_t> extents(pargs::size.begin(), pargs::size.end());\n\t\tif(extents.size() == 1)\n\t\t\textents.resize( pargs::dim, extents[0] );\n\n\t\tif( extents.size() != pargs::dim )\n\t\t{\n\t\t\tstd::cerr << \"Invalid number of size factors\\n\";\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\n\t\t// debug output\n\t\tstd::cout << \"generate potential of size \" << extents[0];\n\t\tfor(int i = 1; i < pargs::dim; ++i)\n\t\t\tstd::cout << \"x\"<<extents[i];\n\t\tstd::cout << \"\\n\";\n\n\t\t// make support area\n\t\t// we use the same aspect ratio as for the extents\n\t\tstd::vector<double> support(pargs::dim);\n\t\tdouble min_ext = *std::min_element( extents.begin(), extents.end() );\n\t\tfor(int i = 0; i < pargs::dim; ++i)\n\t\t{\n\t\t\tsupport[i] = (double)extents[i] / min_ext;\n\t\t}\n\n\t\tif(pargs::correlation_only)\n\t\t{\n\t\t\tauto grid = discretizeFunctionForFFT(extents, support, opt.cor_fun);\n\n            // convert to real\n            default_grid real_pot(extents, TransformationType::FFT_INDEX);\n\n            auto it = real_pot.begin();\n            for(const auto& value : grid)\n            {\n                *it = std::real(value);\n                ++it;\n            }\n\n\n\t\t\tstd::cout << \"saving correlation to \" << pargs::potential_outfile << \"\\n\";\n            real_pot.dump(save);\n\t\t\tsave.close();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tauto pot = generatePotential(extents, support, opt);\n\n\t\t\tauto &pot_data = pot.getPotential();\n\n\t\t\t// control result\n\t\t\tstd::cout << \"Avg: \" << std::accumulate(pot_data.begin(), pot_data.end(), 0.0) / (double) (pot_data.size())\n\t\t\t\t\t  << \"\\n\";\n\n\t\t\tdouble variance = 0;\n\t\t\tdouble min = 0;\n\t\t\tdouble max = 0;;\n\t\t\tfor (auto val : pot_data) {\n\t\t\t\tif (val > max) max = val;\n\t\t\t\tif (val < min) min = val;\n\t\t\t\tvariance += val * val / pot_data.size();\n\t\t\t}\n\n\t\t\tstd::cout << \"Var: \" << variance << \"\\n\";\n\n\t\t\tpot.setStrength(pargs::strength);\n\n\t\t\tstd::cout << \"saving potential to \" << pargs::potential_outfile << \"\\n\";\n\t\t\tchar write_buffer[1024 * 512];\n\t\t\tsave.rdbuf()->pubsetbuf(write_buffer, sizeof(write_buffer));\n\t\t\tpot.writeToFile(save);\n\t\t\tsave.close();\n\t\t}\n\n\t\tif( !pargs::no_wisdom )\n\t\t{\n\t\t\tsaveFFTWisdom();\n\t\t}\n\n\t\t// profiling output\n\t\tif( pargs::print_profile )\n\t\t{\n\t\t\tProfileRecord::print_profiling_data();\n\t\t}\n\t} catch ( boost::exception& e )\n\t{\n\t\tstd::cerr << \"an exception occurred: \" << boost::diagnostic_information(e) << \"\\n\";\n\t\treturn 1;\n\t}\n}\n", "meta": {"hexsha": "6d7667ce24bcee861e9d49440561e6ac82b91788", "size": 3722, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/potgen/potgen_main.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/potgen/potgen_main.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/potgen/potgen_main.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": 26.5857142857, "max_line_length": 115, "alphanum_fraction": 0.6227834498, "num_tokens": 1054, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4576907174003546}}
{"text": "/**\n * \\copyright\n * Copyright (c) 2012-2017, 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 \"LevelSetFunction.h\"\n\n#include <boost/math/special_functions/sign.hpp>\n\n#include \"FractureProperty.h\"\n\nnamespace\n{\n// Heaviside step function\ninline double Heaviside(double v)\n{\n    return (v < 0.0) ? 0.0 : 1.0;\n}\n\n} // no named namespace\n\nnamespace ProcessLib\n{\nnamespace LIE\n{\n\ndouble calculateLevelSetFunction(\n        FractureProperty const& frac, double const* x_)\n{\n    Eigen::Map<Eigen::Vector3d const> x(x_, 3);\n    return Heaviside(\n                boost::math::sign(\n                    frac.normal_vector.dot(x - frac.point_on_fracture)));\n}\n\n} // LIE\n} // ProcessLib\n", "meta": {"hexsha": "3dfe4b27c3ae2161dba85711267a345b2d95f369", "size": 855, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ProcessLib/LIE/Common/LevelSetFunction.cpp", "max_stars_repo_name": "michaelpacherres/ogs", "max_stars_repo_head_hexsha": "c51c8cc74d689fd7ccd4ffb65230b1f682b03cdd", "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": "ProcessLib/LIE/Common/LevelSetFunction.cpp", "max_issues_repo_name": "michaelpacherres/ogs", "max_issues_repo_head_hexsha": "c51c8cc74d689fd7ccd4ffb65230b1f682b03cdd", "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": "ProcessLib/LIE/Common/LevelSetFunction.cpp", "max_forks_repo_name": "michaelpacherres/ogs", "max_forks_repo_head_hexsha": "c51c8cc74d689fd7ccd4ffb65230b1f682b03cdd", "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": 20.8536585366, "max_line_length": 76, "alphanum_fraction": 0.6479532164, "num_tokens": 222, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.45769071203083866}}
{"text": "// Copyright 2021 Jan Niklas Hasse <jhasse@bixense.com>\n// For conditions of distribution and use, see copyright notice in LICENSE.txt\n#include \"Mat3.hpp\"\n\n#include \"Vec2.hpp\"\n#include \"screen.hpp\"\n\n#include <boost/qvm/map_vec_mat.hpp>\n#include <boost/qvm/mat_operations.hpp>\n#include <boost/qvm/mat_operations3.hpp>\n#include <boost/qvm/vec.hpp>\n\nnamespace jngl {\nMat3::Mat3(std::initializer_list<float> elements) {\n\tint row = 0;\n\tint column = 0;\n\tfor (float element : elements) {\n\t\tdata[column * 3 + row] = element;\n\t\t++column;\n\t\tif (column == 3) {\n\t\t\t++row;\n\t\t\tcolumn = 0;\n\t\t}\n\t}\n}\n\nMat3& Mat3::translate(const jngl::Vec2& v) {\n\treturn *this *= boost::qvm::translation_mat(\n\t           boost::qvm::vec<double, 2>{ { v.x * getScaleFactor(), v.y * getScaleFactor() } });\n}\n\nMat3& Mat3::scale(const float factor) {\n\treturn scale(factor, factor);\n}\n\nMat3& Mat3::scale(const float xfactor, const float yfactor) {\n\treturn *this *= boost::qvm::diag_mat(boost::qvm::vec<float, 3>{ { xfactor, yfactor, 1 } });\n}\n\nMat3& Mat3::rotate(const float radian) {\n\tboost::qvm::rotate_z(*this, radian);\n\treturn *this;\n}\n\n} // namespace jngl\n", "meta": {"hexsha": "b4471d21b65a17f5b7c761acc5c959d01d9e4fbb", "size": 1123, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/jngl/Mat3.cpp", "max_stars_repo_name": "jhasse/jngl", "max_stars_repo_head_hexsha": "1aab1bb5b9712eca50786418d44e9559373441a8", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 61.0, "max_stars_repo_stars_event_min_datetime": "2015-09-30T14:42:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T13:56:54.000Z", "max_issues_repo_path": "src/jngl/Mat3.cpp", "max_issues_repo_name": "jhasse/jngl", "max_issues_repo_head_hexsha": "1aab1bb5b9712eca50786418d44e9559373441a8", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 57.0, "max_issues_repo_issues_event_min_datetime": "2016-08-10T19:28:36.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-15T07:18:00.000Z", "max_forks_repo_path": "src/jngl/Mat3.cpp", "max_forks_repo_name": "jhasse/jngl", "max_forks_repo_head_hexsha": "1aab1bb5b9712eca50786418d44e9559373441a8", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-12-14T18:08:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T08:29:19.000Z", "avg_line_length": 24.4130434783, "max_line_length": 94, "alphanum_fraction": 0.6714158504, "num_tokens": 341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412809, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.4576571761464374}}
{"text": "/*******************************************************************************\n* Copyright 2020 Jose Manuel Fajardo\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n*     http://www.apache.org/licenses/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*******************************************************************************/\n\n#pragma once\n\n#include <iostream> \n#include <algorithm> \n#include <vector>\n#include <math.h> \n#include <Eigen/Dense>\n\n#include <ros/ros.h>\n\n#include <std_msgs/String.h>\n#include <std_msgs/Float32.h>\n\n#include <sensor_msgs/JointState.h>\n\n#include <nav_msgs/Odometry.h>\n\n#include <tf2_ros/transform_listener.h>\n#include <tf2_ros/transform_broadcaster.h>\n#include <tf2_ros/buffer.h>\n#include <tf2_geometry_msgs/tf2_geometry_msgs.h>\n#include <tf2/LinearMath/Quaternion.h>\n\n#include <std_srvs/SetBool.h>\n\nnamespace mobile_odometry {\n\n/*!\n * Class containing the Robotino Odometry class\n */\nclass MobileOdom {\npublic:\n\t/*!\n\t * Constructor.\n\t */\n\tMobileOdom(ros::NodeHandle& nodeHandle);\n\t\n\t/*!\n\t * Destructor.\n\t */\n\tvirtual ~MobileOdom();\n\n\nprivate:\n\n\t// Node handle\n\tros::NodeHandle nodeHandle_;\n\n\t/* \n\t*\tSubscribers\n\t*/\n\tros::Subscriber joint_sts_sub_;\n\n\t/* \n\t*\tPublisher\n\t*/\n\tros::Publisher pub_odom;\n\n\t/*\n\t*  Service servers\n\t*/\n\tros::ServiceServer service_reset_odom_;\n\tros::ServiceServer service_reset_odom_cov_;\n\n\t/*!\n\t*\tTF objects\n\t*/ \n\ttf2_ros::TransformBroadcaster broadcaster_;\n\n\t/*!\n\t * Parameters \n\t*/\n\tstd::string output_rf;\n\tstd::string input_rf;\n\tstd::string robot_name;\n\tfloat init_x;\n\tfloat init_y;\n\tfloat init_theta;\n\n\t/*!\n\t* Variables \n\t*/\n\n\tgeometry_msgs::TransformStamped odom_transform_;\n\tstd::string joint_state_topic ;\n\n\tfloat phi_0_dot;\n\tfloat phi_1_dot;\n\tfloat phi_2_dot;\n\n\tfloat radius;\n\tfloat wheel_sep;\n\n\tint  frecuency_rate;\n\tbool broadcast_tf;\n\n\tstd::string odometry_topic;\n\tnav_msgs::Odometry odom_msg;\n\tfloat scale;\n\n\t// Eigen Variables\n\tEigen::MatrixXd J1;\n\tEigen::MatrixXd J2;\n\tEigen::MatrixXd Jacob;\n\tEigen::Matrix3d Rot_mat;\n\tEigen::VectorXd x_dot_local;\n\tEigen::VectorXd x_dot_global;\n\tEigen::VectorXd q_dot;\n\n\n\t/*\n\tFunctions\n\t*/\n\n\t/*!\n\t* Reads and verifies the ROS parameters.\n\t* @return true if successful.\n\t*/\n\tbool readParameters();\n\n\t/*!\n\t* Callback function for the joint states of the robot\n\t* @param jointState the states of the three wheels \n\t*/\n\tvoid Joint_state_Callback_function(const sensor_msgs::JointState jointState);\n\n\t/*!\n\t* Function to refresh publisher and subscribers\n\t*/\n\tvoid spin();\n\n\t/*!\n\t* Service callback function to reset odometry\n\t* @param req the request of the service\n\t* @param res the reply of the service\n\t*/\n\tbool reset_odometry(std_srvs::SetBool::Request  &req, std_srvs::SetBool::Response &res);\n\n\t/*!\n\t* Service callback function to reset odometry covariance\n\t* @param req the request of the service\n\t* @param res the reply of the service\n\t*/\n\tbool reset_odom_cov(std_srvs::SetBool::Request  &req, std_srvs::SetBool::Response &res);\n\n};\n\n} /* namespace */\n", "meta": {"hexsha": "e63ab2abc9f354d9b542c01919a2b2c9af60acd5", "size": 3374, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "mobile_robot_unal_description/include/mobile_robot_unal_description/MobileOdom.hpp", "max_stars_repo_name": "jmfajardod/osf_wbc_bsc_thesis", "max_stars_repo_head_hexsha": "ff6abdba73ed1822e8d03e7d8f5919dc60f4810a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-04-06T20:42:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-06T21:07:01.000Z", "max_issues_repo_path": "mobile_robot_unal_description/include/mobile_robot_unal_description/MobileOdom.hpp", "max_issues_repo_name": "jmfajardod/osf_wbc_bsc_thesis", "max_issues_repo_head_hexsha": "ff6abdba73ed1822e8d03e7d8f5919dc60f4810a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mobile_robot_unal_description/include/mobile_robot_unal_description/MobileOdom.hpp", "max_forks_repo_name": "jmfajardod/osf_wbc_bsc_thesis", "max_forks_repo_head_hexsha": "ff6abdba73ed1822e8d03e7d8f5919dc60f4810a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.4484848485, "max_line_length": 89, "alphanum_fraction": 0.6941315945, "num_tokens": 830, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145998, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.45765615083809297}}
{"text": "/***************************************************************************\n * Copyright 1998-2015 by authors (see AUTHORS.txt)                        *\n *                                                                         *\n *   This file is part of LuxRender.                                       *\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 <stdexcept>\n#include <boost/foreach.hpp>\n#include <boost/regex.hpp>\n\n#include \"slg/film/film.h\"\n#include \"slg/film/imagepipeline/plugins/gammacorrection.h\"\n\n\nusing namespace std;\nusing namespace luxrays;\nusing namespace slg;\n\n//------------------------------------------------------------------------------\n// Gamma correction plugin\n//------------------------------------------------------------------------------\n\nBOOST_CLASS_EXPORT_IMPLEMENT(slg::GammaCorrectionPlugin)\n\nGammaCorrectionPlugin::GammaCorrectionPlugin(const float g, const u_int tableSize) {\n\tgamma = g;\n\n\tgammaTable.resize(tableSize, 0.f);\n\tfloat x = 0.f;\n\tconst float dx = 1.f / tableSize;\n\tfor (u_int i = 0; i < tableSize; ++i, x += dx)\n\t\tgammaTable[i] = powf(Clamp(x, 0.f, 1.f), 1.f / g);\n}\n\nImagePipelinePlugin *GammaCorrectionPlugin::Copy() const {\n\treturn new GammaCorrectionPlugin(gamma, gammaTable.size());\n}\n\nfloat GammaCorrectionPlugin::Radiance2PixelFloat(const float x) const {\n\t// Very slow !\n\t//return powf(Clamp(x, 0.f, 1.f), 1.f / 2.2f);\n\n\tconst u_int tableSize = gammaTable.size();\n\tconst int index = Clamp<int>(Floor2UInt(tableSize * Clamp(x, 0.f, 1.f)), 0, tableSize - 1);\n\treturn gammaTable[index];\n}\n\nvoid GammaCorrectionPlugin::Apply(const Film &film, Spectrum *pixels, vector<bool> &pixelsMask) const {\n\tconst u_int pixelCount = film.GetWidth() * film.GetHeight();\n\n\tfor (u_int i = 0; i < pixelCount; ++i) {\n\t\tif (pixelsMask[i]) {\n\t\t\tpixels[i].c[0] = Radiance2PixelFloat(pixels[i].c[0]);\n\t\t\tpixels[i].c[1] = Radiance2PixelFloat(pixels[i].c[1]);\n\t\t\tpixels[i].c[2] = Radiance2PixelFloat(pixels[i].c[2]);\n\t\t}\n\t}\n}\n", "meta": {"hexsha": "9ce43f392da2c2edc2275861902e98c02904c1c3", "size": 2922, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/slg/film/imagepipeline/plugins/gammacorrection.cpp", "max_stars_repo_name": "DavidBluecame/LuxRays", "max_stars_repo_head_hexsha": "be0f5228b8b65268278a6c6a1c98564ebdc27c05", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/slg/film/imagepipeline/plugins/gammacorrection.cpp", "max_issues_repo_name": "DavidBluecame/LuxRays", "max_issues_repo_head_hexsha": "be0f5228b8b65268278a6c6a1c98564ebdc27c05", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/slg/film/imagepipeline/plugins/gammacorrection.cpp", "max_forks_repo_name": "DavidBluecame/LuxRays", "max_forks_repo_head_hexsha": "be0f5228b8b65268278a6c6a1c98564ebdc27c05", "max_forks_repo_licenses": ["Apache-2.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.1549295775, "max_line_length": 103, "alphanum_fraction": 0.5143737166, "num_tokens": 612, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4576561442311034}}
{"text": "#include <vector>\r\n#include <iostream>\r\n#include <cstdlib>\r\n#include <cassert>\r\n#include <fstream>\r\n#include <sstream>\r\n#include <algorithm>\r\n#include <chrono>\r\n#include <ctime>\r\n\r\n#include <boost/property_tree/ptree.hpp>\r\n#include <boost/property_tree/json_parser.hpp>\r\n#include <boost/foreach.hpp>\r\n\r\nusing boost::property_tree::ptree;\r\nusing boost::property_tree::read_json;\r\n\r\ntemplate <typename T>\r\nstd::vector<T> as_vector(ptree const &pt, ptree::key_type const &key)\r\n{\r\n\tstd::vector<T> r;\r\n\tfor (auto &item : pt.get_child(key))\r\n\t\tr.push_back(item.second.get_value<T>());\r\n\treturn r;\r\n}\r\n\r\ntemplate <typename T>\r\nstd::vector<std::vector<T>> asLayerVector(ptree const &pt, ptree::key_type const &key)\r\n{\r\n\tstd::vector<std::vector<T>> r;\r\n\tfor (auto &item : pt.get_child(key))\r\n\t{\r\n\t\tstd::vector<T> tmp;\r\n\t\ttmp.clear();\r\n\t\tfor (auto &connectionWeight : item.second)\r\n\t\t\ttmp.push_back(connectionWeight.second.get_value<T>());\r\n\t\tr.push_back(tmp);\r\n\t}\r\n\treturn r;\r\n}\r\n\r\ntemplate <typename T>\r\nvoid showVectorVals(std::string label, std::vector<T> &v)\r\n{\r\n\tstd::cout << label << \" \";\r\n\tfor (unsigned i = 0; i < v.size(); ++i)\r\n\t{\r\n\t\tstd::cout << v[i] << \" \";\r\n\t}\r\n\tstd::cout << std::endl;\r\n}\r\n\r\nstruct Connection\r\n{\r\n\tdouble weight;\r\n};\r\n\r\nclass Neuron;\r\n\r\ntypedef std::vector<Neuron> Layer;\r\n\r\n// ****************** class Neuron ******************\r\n\r\nclass Neuron\r\n{\r\n  public:\r\n\tNeuron(unsigned numOutputs, unsigned myIndex);\r\n\tNeuron(std::vector<float> connectionWeights, unsigned myIndex);\r\n\tvoid setOutputVal(double val) { m_outputVal = val; }\r\n\tdouble getOutputVal(void) const { return m_outputVal; }\r\n\tvoid feedForward(const Layer &prevLayer, std::string);\r\n\r\n  private:\r\n\tstatic double transferFunction(double x, std::string actFunc);\r\n\t// randomWeight: 0 - 1\r\n\tstatic double randomWeight(void) { return rand() / double(RAND_MAX); }\r\n\tdouble m_outputVal;\r\n\tstd::vector<Connection> m_outputWeights;\r\n\tunsigned m_myIndex;\r\n};\r\n\r\ndouble Neuron::transferFunction(double x, std::string actFunc = \"relu\")\r\n{\r\n\tif (actFunc == \"relu\")\r\n\t{\r\n\t\treturn std::max(0.0, x);\r\n\t}\r\n\telse if (actFunc == \"linear\")\r\n\t{\r\n\t\treturn x;\r\n\t}\r\n}\r\n\r\nvoid Neuron::feedForward(const Layer &prevLayer, std::string actFunc = \"relu\")\r\n{\r\n\tdouble sum = 0.0;\r\n\r\n\t// Sum the previous layer's outputs (which are our inputs)\r\n\t// Include the bias node from the previous layer.\r\n\r\n\tfor (unsigned n = 0; n < prevLayer.size(); ++n)\r\n\t{\r\n\t\tsum += prevLayer[n].getOutputVal() *\r\n\t\t\t   prevLayer[n].m_outputWeights[m_myIndex].weight;\r\n\t}\r\n\r\n\tm_outputVal = Neuron::transferFunction(sum, actFunc);\r\n}\r\n\r\nNeuron::Neuron(unsigned numOutputs, unsigned myIndex)\r\n{\r\n\tfor (unsigned c = 0; c < numOutputs; ++c)\r\n\t{\r\n\t\tm_outputWeights.push_back(Connection());\r\n\t\tm_outputWeights.back().weight = randomWeight();\r\n\t}\r\n\r\n\tm_myIndex = myIndex;\r\n}\r\n\r\nNeuron::Neuron(std::vector<float> connectionWeights, unsigned myIndex)\r\n{\r\n\tfor (auto &v : connectionWeights)\r\n\t{\r\n\t\tm_outputWeights.push_back(Connection());\r\n\t\tm_outputWeights.back().weight = v;\r\n\t}\r\n\r\n\tm_myIndex = myIndex;\r\n}\r\n\r\n// ****************** class Net ******************\r\nclass Net\r\n{\r\n  public:\r\n\tNet(const std::vector<std::vector<std::vector<float>>> &modelWeights);\r\n\tvoid feedForward(const std::vector<double> &inputVals);\r\n\tvoid getResults(std::vector<double> &resultVals) const;\r\n\tbool infer(std::vector<double> &data_in, std::vector<double> &out);\r\n\r\n  private:\r\n\tstd::vector<Layer> m_layers; //m_layers[layerNum][neuronNum]\r\n};\r\n\r\nvoid Net::getResults(std::vector<double> &resultVals) const\r\n{\r\n\tresultVals.clear();\r\n\r\n\tfor (unsigned n = 0; n < m_layers.back().size(); ++n)\r\n\t{\r\n\t\tresultVals.push_back(m_layers.back()[n].getOutputVal());\r\n\t}\r\n}\r\n\r\nvoid Net::feedForward(const std::vector<double> &inputVals)\r\n{\r\n\t// Check the num of inputVals equal to neuronnum expect bias\r\n\tassert(inputVals.size() == m_layers[0].size() - 1);\r\n\r\n\t// Assign {latch} the input values into the input neurons\r\n\tfor (unsigned i = 0; i < inputVals.size(); ++i)\r\n\t{\r\n\t\tm_layers[0][i].setOutputVal(inputVals[i]);\r\n\t}\r\n\r\n\t// Forward propagate\r\n\tfor (unsigned layerNum = 1; layerNum < m_layers.size() - 1; ++layerNum)\r\n\t{\r\n\t\tLayer &prevLayer = m_layers[layerNum - 1];\r\n\t\tfor (unsigned n = 0; n < m_layers[layerNum].size() - 1; ++n)\r\n\t\t{\r\n\t\t\t// std::cout << \"n:\" << n << '\\n';\r\n\t\t\tm_layers[layerNum][n].feedForward(prevLayer, \"relu\");\r\n\t\t}\r\n\t}\r\n\t//output layer\r\n\t{\r\n\t\tunsigned linearOutputLayer = m_layers.size() - 1;\r\n\t\tLayer &prevLayer = m_layers[linearOutputLayer - 1];\r\n\t\tfor (auto &n : m_layers[linearOutputLayer])\r\n\t\t{\r\n\t\t\tn.feedForward(prevLayer, \"linear\");\r\n\t\t}\r\n\t}\r\n}\r\n\r\nbool Net::infer(std::vector<double> &data_in, std::vector<double> &out)\r\n{\r\n\tstd::vector<double> inputVals, resultVals;\r\n\tint trainingPass = 0;\r\n\tauto t_start = std::chrono::high_resolution_clock::now();\r\n\r\n\twhile (trainingPass < 1e6)\r\n\t{\r\n\t\t++trainingPass;\r\n\t\t// std::cout << \"Pass:\" << trainingPass << \"\\n\";\r\n\r\n\t\tinputVals = data_in;\r\n\r\n\t\tthis->feedForward(inputVals);\r\n\r\n\t\t// Collect the net's actual results:\r\n\t\tthis->getResults(resultVals);\r\n\t\t// showVectorVals<double>(\"Outputs:\", resultVals);\r\n\r\n\t\t// assert(targetVals.size() == topology.back());\r\n\t}\r\n\tauto t_end = std::chrono::high_resolution_clock::now();\r\n\tauto total = std::chrono::duration<float, std::milli>(t_end - t_start).count();\r\n\tstd::cout << \"totol time is \" << total << \"ms.\\n\";\r\n\tout = resultVals;\r\n\treturn 0;\r\n}\r\n\r\nNet::Net(const std::vector<std::vector<std::vector<float>>> &modelWeight)\r\n{\r\n\tunsigned numLayers = modelWeight.size();\r\n\tfor (unsigned layerNum = 0; layerNum < numLayers; ++layerNum)\r\n\t{\r\n\t\tstd::cout << \"layer:\" << layerNum << '\\n';\r\n\t\tm_layers.push_back(Layer());\r\n\r\n\t\tstd::vector<std::vector<float>> layerWeights = modelWeight[layerNum];\r\n\t\tfor (unsigned neuronNum = 0; neuronNum < modelWeight[layerNum].size(); ++neuronNum)\r\n\t\t{\r\n\t\t\tm_layers.back().push_back(Neuron(layerWeights[neuronNum], neuronNum));\r\n\t\t\t// std::cout << \"Mad a Neuron! Index:\" << neuronNum << std::endl;\r\n\t\t}\r\n\t\tm_layers.back().back().setOutputVal(1.0);\r\n\t}\r\n\t//output layer\r\n\tstd::cout << \"layer:output\\n\";\r\n\tm_layers.push_back(Layer());\r\n\tfor (unsigned neuronNum = 0; neuronNum < modelWeight[numLayers - 1][0].size(); ++neuronNum)\r\n\t{\r\n\t\tm_layers.back().push_back(Neuron(0, neuronNum));\r\n\t\t// std::cout << \"Mad a Neuron! Index:\" << neuronNum << std::endl;\r\n\t}\r\n\tm_layers.back().back().setOutputVal(1.0);\r\n\r\n\tassert(m_layers.size() == (modelWeight.size() + 1));\r\n}\r\n\r\nint main()\r\n{\r\n\tstd::ifstream myfile;\r\n\tmyfile.open(\"data.json\");\r\n\t// myfile.open(\"test.json\");\r\n\tstd::stringstream buffer;\r\n\tbuffer << myfile.rdbuf();\r\n\t// std::cout << buffer.str() << '\\n';\r\n\r\n\tptree pt2;\r\n\tread_json(buffer, pt2);\r\n\r\n\tstd::vector<std::vector<std::vector<float>>> modelWeights;\r\n\tstd::vector<std::vector<float>> layer1, layer2, output;\r\n\r\n\tlayer1 = asLayerVector<float>(pt2, \"l1\");\r\n\tlayer2 = asLayerVector<float>(pt2, \"l2\");\r\n\toutput = asLayerVector<float>(pt2, \"output\");\r\n\r\n\tmodelWeights.push_back(layer1);\r\n\tmodelWeights.push_back(layer2);\r\n\tmodelWeights.push_back(output);\r\n\r\n\tNet myNet(modelWeights);\r\n\r\n\tstd::vector<double> inputVals, resultVals;\r\n\t// int trainingPass = 0;\r\n\t// while (trainingPass < 1)\r\n\t// {\r\n\t// \t++trainingPass;\r\n\t// \tstd::cout << \"Pass:\" << trainingPass << \"\\n\";\r\n\r\n\t// \tinputVals = as_vector<double>(pt2, \"in\");\r\n\t// \tshowVectorVals<double>(\": Inputs :\", inputVals);\r\n\t// \tmyNet.feedForward(inputVals);\r\n\r\n\t// \t// Collect the net's actual results:\r\n\t// \tmyNet.getResults(resultVals);\r\n\t// \tshowVectorVals<double>(\"Outputs:\", resultVals);\r\n\r\n\t// \t// assert(targetVals.size() == topology.back());\r\n\t// }\r\n\tinputVals = as_vector<double>(pt2, \"in\");\r\n\tshowVectorVals<double>(\": Inputs :\", inputVals);\r\n\tmyNet.infer(inputVals, resultVals);\r\n\tshowVectorVals<double>(\"Outputs:\", resultVals);\r\n\r\n\tstd::cout << std::endl\r\n\t\t\t  << \"Done\" << std::endl;\r\n}", "meta": {"hexsha": "c52e8bd25f5e2bfb30775cb3e6aae6c7b612f859", "size": 7802, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "simpleInferenceCpp/wudi.cpp", "max_stars_repo_name": "uqyge/combustionML", "max_stars_repo_head_hexsha": "b0052fce732f38af478b26b5b2c0d9c94310c89e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 21.0, "max_stars_repo_stars_event_min_datetime": "2018-03-01T12:39:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-01T15:59:03.000Z", "max_issues_repo_path": "simpleInferenceCpp/wudi.cpp", "max_issues_repo_name": "uqyge/combustionML", "max_issues_repo_head_hexsha": "b0052fce732f38af478b26b5b2c0d9c94310c89e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-06-01T16:31:46.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-12T09:07:59.000Z", "max_forks_repo_path": "simpleInferenceCpp/wudi.cpp", "max_forks_repo_name": "uqyge/combustionML", "max_forks_repo_head_hexsha": "b0052fce732f38af478b26b5b2c0d9c94310c89e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-09-07T18:57:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-07T07:46:33.000Z", "avg_line_length": 26.6279863481, "max_line_length": 93, "alphanum_fraction": 0.644450141, "num_tokens": 2117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4576561442311033}}
{"text": "#pragma once\n\n#include <algorithm>\n#include <atomic>\n#include <limits>\n#include <stack>\n#include <thread>\n#include <queue>\n\n#include <Eigen/Dense>\n\nnamespace pcs {\n\ntemplate<uint16_t K, typename index_t = unsigned>\nclass KDTree {\npublic:\n  const index_t nai_v = std::numeric_limits<index_t>::max();\npublic:\n  KDTree(const std::vector<Eigen::Matrix<double, K, 1>> &vertices,\n         int max_threads = 2 * std::thread::hardware_concurrency());\n\n  std::pair<index_t, double>\n  find_nn(Eigen::Matrix<double, K, 1> point,\n          double max_dist = std::numeric_limits<double>::infinity()) const;\n\n  std::vector<std::pair<index_t, double>>\n  find_nns(Eigen::Matrix<double, K, 1> point, std::size_t n,\n           double max_dist = std::numeric_limits<double>::infinity()) const;\n\nprivate:\n  const std::vector<Eigen::Matrix<double, K, 1>> &vertices;\n\n  struct Node {\n    typedef index_t ID;\n    decltype(K) d;\n    index_t first;\n    index_t last;\n    index_t vertex_id;\n    Node::ID left;\n    Node::ID right;\n  };\n\n  std::atomic<index_t> num_nodes;\n  std::vector<Node> nodes;\n\n  typename Node::ID CreateNode(decltype(K) d, index_t first, index_t last) {\n    typename Node::ID node_id = num_nodes++;\n    Node &node = nodes[node_id];\n    node.first = first;\n    node.last = last;\n    node.left = nai_v;\n    node.right = nai_v;\n    node.vertex_id = nai_v;\n    node.d = d;\n    return node_id;\n  }\n\n  std::pair<typename Node::ID, typename Node::ID>\n  ssplit(typename Node::ID node_id, std::vector<index_t> *indices);\n\n  void split(typename Node::ID node_id, std::vector<index_t> *indices,\n             std::atomic<int> *num_threads);\n};\n\ntemplate<uint16_t K, typename IdxType>\nKDTree<K, IdxType>::KDTree(const std::vector<Eigen::Matrix<double, K, 1>>&vertices,\n                           int max_threads)\n    : vertices(vertices), num_nodes(0) {\n\n  std::size_t num_vertices = vertices.size();\n  nodes.resize(num_vertices);\n\n  std::vector<IdxType> indices(num_vertices);\n  for (std::size_t i = 0; i < indices.size(); ++i) {\n    indices[i] = i;\n  }\n\n  std::atomic<int> num_threads(max_threads);\n  split(CreateNode(0, 0, num_vertices), &indices, &num_threads);\n}\n\ntemplate<uint16_t K, typename IdxType>\nvoid KDTree<K, IdxType>::split(typename Node::ID node_id,\n                               std::vector<IdxType> *indices,\n                               std::atomic<int> *num_threads) {\n  typename Node::ID left, right;\n  if ((*num_threads -= 1) >= 1) {\n    std::tie(left, right) = ssplit(node_id, indices);\n    if (left != nai_v && right != nai_v) {\n      std::thread other(&KDTree::split, this, left, indices, num_threads);\n      split(right, indices, num_threads);\n      other.join();\n    } else {\n      if (left != nai_v)\n        split(left, indices, num_threads);\n      if (right != nai_v)\n        split(right, indices, num_threads);\n    }\n  } else {\n    std::deque<typename Node::ID> queue;\n    queue.push_back(node_id);\n    while (!queue.empty()) {\n      typename Node::ID node_id = queue.front();\n      queue.pop_front();\n\n      std::tie(left, right) = ssplit(node_id, indices);\n      if (left != nai_v)\n        queue.push_back(left);\n      if (right != nai_v)\n        queue.push_back(right);\n    }\n  }\n  *num_threads += 1;\n}\n\ntemplate<uint16_t K, typename IdxType>\nstd::pair<typename KDTree<K, IdxType>::Node::ID, typename KDTree<K, IdxType>::Node::ID>\nKDTree<K, IdxType>::ssplit(typename Node::ID node_id, std::vector<IdxType> *indices) {\n  Node &node = nodes[node_id];\n  decltype(K) d = node.d;\n  std::sort(indices->data() + node.first, indices->data() + node.last,\n            [this, d](IdxType a, IdxType b) -> bool {\n              return vertices[a][d] < vertices[b][d];\n            }\n  );\n  d = (d + 1) % K;\n  IdxType mid = (node.last + node.first) / 2;\n  node.vertex_id = indices->at(mid);\n  if (mid - node.first > 0) {\n    node.left = CreateNode(d, node.first, mid);\n  }\n  if (node.last - (mid + 1) > 0) {\n    node.right = CreateNode(d, mid + 1, node.last);\n  }\n  return std::make_pair(node.left, node.right);\n}\n\ntemplate<uint16_t K, typename IdxType>\nstd::pair<IdxType, double>\nKDTree<K, IdxType>::find_nn(Eigen::Matrix<double, K, 1> point, double max_dist) const {\n  return find_nns(point, 1, max_dist)[0];\n}\n\ntemplate<uint16_t K, typename IdxType>\nstd::vector<std::pair<IdxType, double>>\nKDTree<K, IdxType>::find_nns(Eigen::Matrix<double, K, 1> vertex, std::size_t n, double max_dist) const {\n\n  std::pair<IdxType, double> nn = std::make_pair(nai_v, max_dist);\n  std::vector<std::pair<IdxType, double>> nns(n, nn);\n\n  std::stack<std::pair<typename Node::ID, bool> > s;\n  s.emplace(0, true);\n  while (!s.empty()) {\n    typename Node::ID node_id;\n    bool down;\n    std::tie(node_id, down) = s.top();\n    s.pop();\n\n    if (node_id == nai_v)\n      continue;\n\n    Node const &node = nodes[node_id];\n\n    double diff = vertex[node.d] - vertices[node.vertex_id][node.d];\n    if (down) {\n      double dist = (vertex - vertices[node.vertex_id]).norm();\n      if (dist < max_dist) {\n        nns.emplace_back(node.vertex_id, dist);\n        std::sort(nns.begin(), nns.end(),\n                  [](std::pair<IdxType, double> a, std::pair<IdxType, double> b) -> bool {\n                    return a.second < b.second;\n                  });\n        nns.pop_back();\n        max_dist = nns.back().second;\n      }\n\n      if (node.left == nai_v && node.right == nai_v)\n        continue;\n\n      s.emplace(node_id, false);\n      if (diff < 0.0f) {\n        s.emplace(node.left, true);\n      } else {\n        s.emplace(node.right, true);\n      }\n    } else {\n      if (std::abs(diff) >= max_dist)\n        continue;\n\n      if (diff < 0.0f) {\n        s.emplace(node.right, true);\n      } else {\n        s.emplace(node.left, true);\n      }\n    }\n  }\n  return nns;\n}\n\n}// namespace pcs", "meta": {"hexsha": "73fd27b7aa04d78d52922bbf1234177bddd5a168", "size": 5764, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/kd_tree.hpp", "max_stars_repo_name": "aleksrgarkusha/pcs", "max_stars_repo_head_hexsha": "597a2aa020a60473307ef09a8939db1d93657f8a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-12-26T02:17:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T13:20:33.000Z", "max_issues_repo_path": "src/kd_tree.hpp", "max_issues_repo_name": "aleksrgarkusha/pcs", "max_issues_repo_head_hexsha": "597a2aa020a60473307ef09a8939db1d93657f8a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kd_tree.hpp", "max_forks_repo_name": "aleksrgarkusha/pcs", "max_forks_repo_head_hexsha": "597a2aa020a60473307ef09a8939db1d93657f8a", "max_forks_repo_licenses": ["Apache-2.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.82, "max_line_length": 104, "alphanum_fraction": 0.6080846634, "num_tokens": 1636, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4576561442311033}}
{"text": "#include <catch.hpp>\n#include <Eigen/Core>\n#include <random>\n\n#include \"check_adjoint.h\"\n#include \"test_utils.h\"\n#include \"renderer_interpolation.cuh\"\n\n\ntemplate<typename Tensor_t>\nTensor_t accessor4D(const VectorXr& tf, const int3& xyz)\n{\n\tconst int64_t sizes[] = {\n\t\t1, xyz.x, xyz.y, xyz.z\n\t};\n\tconst int64_t strides[] = {\n\t\t0, xyz.y*xyz.z, xyz.z, 1\n\t};\n\treturn Tensor_t(\n\t\tconst_cast<real_t*>(tf.data()), sizes, strides);\n}\n\ntemplate<bool hasVolumeDerivative>\nvoid testAdjointInterpolation()\n{\n\ttypedef empty TmpStorage_t;\n\ttypedef VectorXr Vector_t;\n\n\tstd::default_random_engine rnd(42);\n\tstd::uniform_real_distribution<real_t> distr(0.01, 0.99);\n\tstatic const int3 resolution = make_int3(2, 3, 4);\n\tstatic const int resolution_prod = resolution.x * resolution.y * resolution.z;\n\tstatic const real3 voxelSize = make_real3(1.0f) / make_real3(resolution);\n\tVector_t baseVolume(resolution_prod);\n\tfor (int j = 0; j < baseVolume.size(); ++j) baseVolume[j] = distr(rnd);\n\n\tauto forward = [&baseVolume](const Vector_t& x, TmpStorage_t* tmp) -> Vector_t\n\t{\n\t\tconst real3 pos = fromEigen3(x.segment(0, 3));\n\n\t\tconst Vector_t volume = hasVolumeDerivative\n\t\t\t? x.segment(3, resolution_prod)\n\t\t\t: baseVolume;\n\t\tconst auto volume_acc = accessor4D<kernel::Tensor4Read>(volume, resolution);\n\n\t\tkernel::VolumeInterpolation<kernel::FilterTrilinear> volumeInterpolation;\n\t\treal_t density = volumeInterpolation.fetch(volume_acc, resolution, 0, pos);\n\n\t\tVector_t result(1);\n\t\tresult[0] = density;\n\t\treturn result;\n\t};\n\tauto adjoint = [baseVolume](const Vector_t& x, const Vector_t& e, const Vector_t& g,\n\t\tVector_t& z, const TmpStorage_t& tmp)\n\t{\n\t\tconst real3 pos = fromEigen3(x.segment(0, 3));\n\n\t\tconst Vector_t volume = hasVolumeDerivative\n\t\t\t? x.segment(3, resolution_prod)\n\t\t\t: baseVolume;\n\t\tconst auto volume_acc = accessor4D<kernel::Tensor4Read>(volume, resolution);\n\n\t\treal_t density = e[0];\n\t\treal_t adj_density = g[0];\n\t\treal3 adj_pos;\n\t\tVector_t adjVolume = Vector_t::Zero(resolution_prod);\n\t\tauto adjVolume_acc = accessor4D<kernel::BTensor4RW>(adjVolume, resolution);\n\n\t\t{\n\t\t\tkernel::VolumeInterpolation<kernel::FilterTrilinear, true, hasVolumeDerivative> volumeInterpolation(\n\t\t\t\t0, resolution, adjVolume_acc);\n\t\t\tvolumeInterpolation.fetch(volume_acc, resolution, 0, pos);\n\t\t\tvolumeInterpolation.adjoint(adj_density, adj_pos);\n\t\t}\n\n\t\tz.segment(0, 3) = toEigen(adj_pos);\n\t\tif (hasVolumeDerivative) z.segment(3, resolution_prod) = adjVolume;\n\t};\n\n\tint N = 20;\n\tfor (int i = 0; i < N; ++i)\n\t{\n\t\tINFO(\"N=\" << i);\n\t\tVector_t x;\n\t\tif (hasVolumeDerivative) {\n\t\t\tx.resize(3 + resolution_prod);\n\t\t\tx.segment(3, resolution_prod) = baseVolume;\n\t\t}\n\t\telse {\n\t\t\tx.resize(3);\n\t\t}\n\t\tx[0] = distr(rnd) / voxelSize.x;\n\t\tx[1] = distr(rnd) / voxelSize.y;\n\t\tx[2] = distr(rnd) / voxelSize.z;\n\t\tcheckAdjoint<Vector_t, TmpStorage_t>(x, forward, adjoint,\n\t\t\t1e-5, 1e-5, 1e-6);\n\t}\n}\n\nTEST_CASE(\"Adjoint-Interpolation-NoVolumeDerivatives\", \"[adjoint]\")\n{\n\ttestAdjointInterpolation<false>();\n}\n\nTEST_CASE(\"Adjoint-Interpolation-withVolumeDerivatives\", \"[adjoint]\")\n{\n\ttestAdjointInterpolation<true>();\n}\n\n\n", "meta": {"hexsha": "026592b96080ab597bf1e921c5301e4181dec640", "size": 3077, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittests/testAdjointInterpolation.cpp", "max_stars_repo_name": "shamanDevel/DiffDVR", "max_stars_repo_head_hexsha": "99fbe9f114d0097daf402bde2ae35f18dade335d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2021-08-02T04:51:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-14T18:02:27.000Z", "max_issues_repo_path": "unittests/testAdjointInterpolation.cpp", "max_issues_repo_name": "shamanDevel/DiffDVR", "max_issues_repo_head_hexsha": "99fbe9f114d0097daf402bde2ae35f18dade335d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-11-04T14:23:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-28T10:30:13.000Z", "max_forks_repo_path": "unittests/testAdjointInterpolation.cpp", "max_forks_repo_name": "shamanDevel/DiffDVR", "max_forks_repo_head_hexsha": "99fbe9f114d0097daf402bde2ae35f18dade335d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-07-16T10:23:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-04T02:51:43.000Z", "avg_line_length": 27.7207207207, "max_line_length": 103, "alphanum_fraction": 0.7149821254, "num_tokens": 924, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4576561442311033}}
{"text": "//////////////////////////////////////////////////////////////////\n// example93.cpp\n//\n// Copyright (c) 2015 Robert Ramey\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#include <iostream>\n\n// include headers to support safe integers\n#include <boost/safe_numerics/cpp.hpp>\n#include <boost/safe_numerics/exception.hpp>\n#include <boost/safe_numerics/safe_integer.hpp>\n#include <boost/safe_numerics/safe_integer_range.hpp>\n#include <boost/safe_numerics/safe_integer_literal.hpp>\n\n// use same type promotion as used by the pic compiler\n// target compiler XC8 supports:\nusing pic16_promotion = boost::safe_numerics::cpp<\n    8,  // char      8 bits\n    16, // short     16 bits\n    16, // int       16 bits\n    16, // long      16 bits\n    32  // long long 32 bits\n>;\n\n// ***************************\n// 1. Specify exception policies so we will generate a\n// compile time error whenever an operation MIGHT fail.\n\n// ***************************\n// generate runtime errors if operation could fail\nusing exception_policy = boost::safe_numerics::default_exception_policy;\n\n// generate compile time errors if operation could fail\nusing trap_policy = boost::safe_numerics::loose_trap_policy;\n\n// ***************************\n// 2. Create a macro named literal an integral value\n// that can be evaluated at compile time.\n#define literal(n) make_safe_literal(n, pic16_promotion, void)\n\n// For min speed of 2 mm / sec (24.8 format)\n// sec / step = sec / 2 mm * 2 mm / rotation * rotation / 200 steps\n#define C0      literal(5000 << 8)\n\n// For max speed of 400 mm / sec\n// sec / step = sec / 400 mm * 2 mm / rotation * rotation / 200 steps\n#define C_MIN   literal(25 << 8)\n\nstatic_assert(\n    C0 < make_safe_literal(0xffffff, pic16_promotion,trap_policy),\n    \"Largest step too long\"\n);\nstatic_assert(\n    C_MIN > make_safe_literal(0, pic16_promotion,trap_policy),\n    \"Smallest step must be greater than zero\"\n);\n\n// ***************************\n// 3. Create special ranged types for the motor program\n// These wiil guarantee that values are in the expected\n// ranges and permit compile time determination of when\n// exceptional conditions might occur.\n\nusing pic_register_t = boost::safe_numerics::safe<\n    uint8_t,\n    pic16_promotion,\n    trap_policy // use for compiling and running tests\n>;\n\n// note: the maximum value of step_t would be:\n// 50000 = 500 mm / 2 mm/rotation * 200 steps/rotation.\n// But in one expression the value of number of steps * 4 is\n// used.  To prevent introduction of error, permit this\n// type to hold the larger value.\nusing step_t = boost::safe_numerics::safe_unsigned_range<\n    0,\n    200000,\n    pic16_promotion,\n    exception_policy\n>;\n\n// position\nusing position_t = boost::safe_numerics::safe_unsigned_range<\n    0,\n    50000, // 500 mm / 2 mm/rotation * 200 steps/rotation\n    pic16_promotion,\n    exception_policy\n>;\n\n// next end of step timer value in format 24.8\n// where the .8 is the number of bits in the fractional part.\nusing ccpr_t = boost::safe_numerics::safe<\n    uint32_t,\n    pic16_promotion,\n    exception_policy\n>;\n\n// pulse length in format 24.8\n// note: this value is constrainted to be a positive value. But\n// we still need to make it a signed type. We get an arithmetic\n// error when moving to a negative step number.\nusing c_t = boost::safe_numerics::safe_unsigned_range<\n    C_MIN,\n    C0,\n    pic16_promotion,\n    exception_policy\n>;\n\n// 32 bit unsigned integer used for temporary purposes\nusing temp_t = boost::safe_numerics::safe_unsigned_range<\n    0, 0xffffffff,\n    pic16_promotion,\n    exception_policy\n>;\n\n// index into phase table\n// note: The legal values are 0-3.  So why must this be a signed\n// type?  Turns out that expressions like phase_ix + d\n// will convert both operands to unsigned.  This in turn will\n// create an exception.  So leave it signed even though the\n// value is greater than zero.\nusing phase_ix_t = boost::safe_numerics::safe_signed_range<\n    0,\n    3,\n    pic16_promotion,\n    trap_policy\n>;\n\n// settings for control value output\nusing phase_t = boost::safe_numerics::safe<\n    uint16_t,\n    pic16_promotion,\n    trap_policy\n>;\n\n// direction of rotation\nusing direction_t = boost::safe_numerics::safe_signed_range<\n    -1,\n    +1,\n    pic16_promotion,\n    trap_policy\n>;\n\n// some number of microseconds\nusing microseconds = boost::safe_numerics::safe<\n    uint32_t,\n    pic16_promotion,\n    trap_policy\n>;\n\n// *************************** \n// emulate PIC features on the desktop\n\n// filter out special keyword used only by XC8 compiler\n#define __interrupt\n// filter out XC8 enable/disable global interrupts\n#define ei()\n#define di()\n\n// emulate PIC special registers\npic_register_t RCON;\npic_register_t INTCON;\npic_register_t CCP1IE;\npic_register_t CCP2IE;\npic_register_t PORTC;\npic_register_t TRISC;\npic_register_t T3CON;\npic_register_t T1CON;\n\npic_register_t CCPR2H;\npic_register_t CCPR2L;\npic_register_t CCPR1H;\npic_register_t CCPR1L;\npic_register_t CCP1CON;\npic_register_t CCP2CON;\npic_register_t TMR1H;\npic_register_t TMR1L;\n\n// ***************************\n// special checked type for bits - values restricted to 0 or 1\nusing safe_bit_t = boost::safe_numerics::safe_unsigned_range<\n    0,\n    1,\n    pic16_promotion,\n    trap_policy\n>;\n\n// create type used to map PIC bit names to\n// correct bit in PIC register\ntemplate<typename T, std::int8_t N>\nstruct bit {\n    T & m_word;\n    constexpr explicit bit(T & rhs) :\n        m_word(rhs)\n    {}\n    // special functions for assignment of literal\n    constexpr bit & operator=(decltype(literal(1))){\n        m_word |= literal(1 << N);\n        return *this;\n    }\n    constexpr bit & operator=(decltype(literal(0))){\n        m_word &= ~literal(1 << N);\n        return *this;\n    }\n    // operator to convert to 0 or 1\n    constexpr operator safe_bit_t () const {\n        return m_word >> literal(N) & literal(1);\n    }\n};\n\n// define bits for T1CON register\nstruct  {\n    bit<pic_register_t, 7> RD16{T1CON};\n    bit<pic_register_t, 5> T1CKPS1{T1CON};\n    bit<pic_register_t, 4> T1CKPS0{T1CON};\n    bit<pic_register_t, 3> T1OSCEN{T1CON};\n    bit<pic_register_t, 2> T1SYNC{T1CON};\n    bit<pic_register_t, 1> TMR1CS{T1CON};\n    bit<pic_register_t, 0> TMR1ON{T1CON};\n} T1CONbits;\n\n// define bits for T1CON register\nstruct  {\n    bit<pic_register_t, 7> GEI{INTCON};\n    bit<pic_register_t, 5> PEIE{INTCON};\n    bit<pic_register_t, 4> TMR0IE{INTCON};\n    bit<pic_register_t, 3> RBIE{INTCON};\n    bit<pic_register_t, 2> TMR0IF{INTCON};\n    bit<pic_register_t, 1> INT0IF{INTCON};\n    bit<pic_register_t, 0> RBIF{INTCON};\n} INTCONbits;\n\n#include \"motor3.c\"\n\n#include <chrono>\n#include <thread>\n\n// round 24.8 format to microseconds\nmicroseconds to_microseconds(ccpr_t t){\n    return (t + literal(128)) / literal(256);\n}\n\nusing result_t = uint8_t;\nconst result_t success = 1;\nconst result_t fail = 0;\n\n// move motor to the indicated target position in steps\nresult_t test(position_t new_position){\n    try {\n        std::cout << \"move motor to \" << new_position << '\\n';\n        motor_run(new_position);\n        std::cout\n        << \"step #\" << ' '\n        << \"delay(us)(24.8)\" << ' '\n        << \"delay(us)\" << ' '\n        << \"CCPR\" << ' '\n        << \"motor position\" << '\\n';\n        while(busy()){\n            std::this_thread::sleep_for(std::chrono::microseconds(to_microseconds(c)));\n            c_t last_c = c;\n            ccpr_t last_ccpr = ccpr;\n            isr_motor_step();\n            std::cout << i << ' '\n            << last_c << ' '\n            << to_microseconds(last_c) << ' '\n            << std::hex << last_ccpr << std::dec << ' '\n            << motor_position << '\\n';\n        };\n    }\n    catch(const std::exception & e){\n        std::cout << e.what() << '\\n';\n        return fail;\n    }\n    return success;\n}\n\nint main(){\n    std::cout << \"start test\\n\";\n    result_t result = success;\n    try {\n        initialize();\n        // move motor to position 1000\n        result &= test(literal(9000));\n        // move to the left before zero position\n        // fails to compile !\n        // result &= ! test(-10);\n        // move motor to position 200\n        result &= test(literal(200));\n        // move motor to position 200 again! Should result in no movement.\n        result &= test(literal(200));\n        // move motor to position 50000.\n        result &= test(literal(50000));\n        // move motor back to position 0.\n        result &= test(literal(0));\n    }\n    catch(...){\n        std::cout << \"test interrupted\\n\";\n        return EXIT_FAILURE;\n    }\n    std::cout << \"end test\\n\";\n    return result == success ? EXIT_SUCCESS : EXIT_FAILURE;\n} \n", "meta": {"hexsha": "4044b2540614f952855afe5d773213d6df3b854c", "size": 8703, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/example93.cpp", "max_stars_repo_name": "giomasce-throwaway/safe_numerics", "max_stars_repo_head_hexsha": "3a1676e5831bab93b9be50caec69c1887a4af7da", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-08-09T13:37:39.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-09T13:37:39.000Z", "max_issues_repo_path": "example/example93.cpp", "max_issues_repo_name": "giomasce-throwaway/safe_numerics", "max_issues_repo_head_hexsha": "3a1676e5831bab93b9be50caec69c1887a4af7da", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-13T08:54:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-17T17:25:14.000Z", "max_forks_repo_path": "example/example93.cpp", "max_forks_repo_name": "giomasce-throwaway/safe_numerics", "max_forks_repo_head_hexsha": "3a1676e5831bab93b9be50caec69c1887a4af7da", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-08-28T07:14:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-13T11:18:41.000Z", "avg_line_length": 28.348534202, "max_line_length": 87, "alphanum_fraction": 0.6501206481, "num_tokens": 2306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943603346811, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4576561376241135}}
{"text": "#include \"ElasticRod.h\"\n\n#include <cmath>\n#include <dlib/optimization.h>\n#include \"Utils.h\"\n\ntypedef dlib::matrix<double> Hessian;\n\n//====================================== MinimizationPImpl definition - minimize Energy with respect to twist angle theta =======================================\n\nstruct ElasticRod::MinimizationPImpl\n{\npublic:\n    MinimizationPImpl() { }\n    ~MinimizationPImpl() { }\n\n    double minimize(const ElasticRod *rod, ColumnVector& io_theta);\n\npublic:\n\n    static void extractThetaVars(const ElasticRod* rod, const ColumnVector& theta, ColumnVector& o_thetaVars);\n    static void constructTheta(const ElasticRod* rod, const ColumnVector& thetaVars, ColumnVector& o_theta);\n\npublic:\n\n    struct evaluate\n    {\n        double operator() (const ColumnVector& theta) const;\n        const ElasticRod* m_rod;\n    };\n\n    struct evaluateGradient\n    {\n        ColumnVector operator() (const ColumnVector& theta) const;\n        const ElasticRod* m_rod;\n    };\n\n    struct evaluateHessian\n    {\n        Hessian operator() (const ColumnVector& theta) const;\n        const ElasticRod* m_rod;\n    };\n\n    evaluate m_evaluate;\n    evaluateGradient m_evaluateGradient;\n    evaluateHessian m_evaluateHessian;\n};\n\n\n//====================================== ElasticRod implementation =======================================\n\nElasticRod::ElasticRod(const ElasticRodParams *params)\n{\n    assert( params != NULL );\n    m_params = params;\n    m_minimization = new MinimizationPImpl();\n}\n\nElasticRod::~ElasticRod()\n{\n    delete m_minimization;\n}\n\nvoid ElasticRod::init(const std::vector<mg::Vec3D>& restpos,\n                      const mg::Vec3D& u0,\n                      const std::vector<mg::Vec3D>& pos,\n                      const std::vector<mg::Vec3D>& vel,\n                      const std::vector<mg::Real>& mass,\n                      const ColumnVector& theta,\n                      const std::set<unsigned> &isClamped)\n{\n    assert( pos.size() > 2 );\n    assert( pos.size() == restpos.size() );\n    assert( pos.size() == vel.size() );\n    assert( pos.size() == mass.size() );\n    assert( (unsigned)theta.size() == (pos.size() - 1) );\n\n    m_u0 = u0;\n    m_ppos = pos;\n    m_pprepos = pos;\n    m_pvel = vel;\n    m_pmass = mass;\n    m_theta = theta;\n    m_isClamped = isClamped;\n\n    m_edges.resize(m_ppos.size() - 1);\n    m_kb.resize(m_edges.size());\n    m_m1.resize(m_edges.size());\n    m_m2.resize(m_edges.size());\n\n    m_restEdgeL.resize(m_edges.size());\n    m_restRegionL.resize(m_edges.size());\n    m_restWprev.resize(m_edges.size());\n    m_restWnext.resize(m_edges.size());\n\n//    compute edges & lengths for rest shape\n    computeEdges(restpos, m_edges);\n    computeLengths(m_edges, m_restEdgeL, m_restRegionL);\n//    compute kb and material frame (Bishop frame) for rest shape\n    computeBishopFrame(m_u0, m_edges, m_kb, m_m1, m_m2);\n//    precompute material curvature for rest shape\n    computeMaterialCurvature(m_kb, m_m1, m_m2, m_restWprev, m_restWnext);\n\n//    initialize current state\n    updateCurrentState();\n\n#ifdef DBUGG\n//    store elasic force for debug purpose\n    m_elasticForce.resize(m_ppos.size(), mg::Vec3D(0, 0, 0));\n    accumulateInternalElasticForces(m_elasticForce);\n#endif\n\n}\n\nvoid ElasticRod::getState(ElasticRodState& o_state) const\n{\n    o_state.m_ppos = m_ppos;\n    o_state.m_pvel = m_pvel;\n    o_state.m_u0 = m_u0;\n}\n\nvoid ElasticRod::setState(const ElasticRodState& state)\n{\n    m_ppos = state.m_ppos;\n    m_pvel = state.m_pvel;\n    m_u0 = state.m_u0;\n\n    computeEdges(m_ppos, m_edges);\n    updateCurrentState();\n}\n\nvoid ElasticRod::computeEdges(const std::vector<mg::Vec3D>& vertices,\n                              std::vector<mg::Vec3D>& o_edges) const\n{\n    for (unsigned i = 0; i < vertices.size() - 1; ++i)\n    {\n        o_edges[i] = vertices[i + 1] - vertices[i];\n        assert( std::isfinite(o_edges[i].length_squared()) );\n    }\n}\n\nvoid ElasticRod::computeLengths(const std::vector<mg::Vec3D>& edges,\n                                std::vector<mg::Real> &o_edgeL,\n                                std::vector<mg::Real> &o_regionL) const\n{\n    for (unsigned i = 0; i < edges.size(); ++i)\n    {\n        o_edgeL[i] = edges[i].length();\n        assert( std::isfinite(o_edgeL[i]) && o_edgeL[i] > mg::ERR );\n    }\n\n    o_regionL[0] = 0.0;\n    for (unsigned i = 1; i < edges.size(); ++i)\n    {\n        o_regionL[i] = o_edgeL[i - 1] + o_edgeL[i];\n    }\n}\n\nvoid ElasticRod::computeMaterialCurvature(const std::vector<mg::Vec3D>& kb,\n                                        const std::vector<mg::Vec3D>& m1,\n                                        const std::vector<mg::Vec3D>& m2,\n                                        std::vector<mg::Vec2D>& o_Wprev,\n                                        std::vector<mg::Vec2D>& o_Wnext) const\n{\n    o_Wprev[0].zero();\n    o_Wnext[0].zero();\n    for (unsigned i = 1; i < kb.size(); ++i)\n    {\n        computeW(kb[i], m1[i - 1], m2[i - 1], o_Wprev[i]);\n        computeW(kb[i], m1[i], m2[i], o_Wnext[i]);\n    }\n}\n\nvoid ElasticRod::computeW(const mg::Vec3D& kb, const mg::Vec3D& m1, const mg::Vec3D& m2, mg::Vec2D& o_wij) const\n{\n    o_wij.set( mg::dot( kb, m2 ), -mg::dot( kb, m1 ));\n}\n\nvoid ElasticRod::computeKB(const std::vector<mg::Vec3D>& edges,\n                           std::vector<mg::Vec3D>& o_kb) const\n{\n    o_kb[0].zero();\n\n    for (unsigned i = 1; i < edges.size(); ++i)\n    {\n///     NOTE: as metioned in the paper the following formula produces ||kb|| = 2 * tan(phi / 2),\n///     where phi is the angle of rotation defined by the 2 edges\n///     This holds only if ||edges[i]|| = ||rest_edges[i]||,\n///     otherwise errors occur in consequent frame rotations and force calculations\n///     in particular this assumption can be violated if the constraint enforcement DOES NOT GUARANTEE inextensibility,\n///     which is the case with PBD used below\n///     note that tan maps [-pi/2, pi/2] to [-inf, inf], so interestingly for arbitrary real number an arbitrary bounded angle can be extracted\n///\n        o_kb[i] = 2 * mg::cross( edges[i - 1], edges[i] ) /\n                (m_restEdgeL[i - 1] * m_restEdgeL[i] + mg::dot( edges[i - 1], edges[i]) );\n    }\n}\n\nvoid ElasticRod::extractSinAndCos(const double &magnitude,\n                                  double &o_sinPhi, double &o_cosPhi) const\n{\n    o_cosPhi = mg::sqrt_safe(4.0 / (4.0 + magnitude));\n    o_sinPhi = mg::sqrt_safe(magnitude / (4.0 + magnitude));\n}\n\nvoid ElasticRod::computeBishopFrame(const mg::Vec3D& u0,\n                        const std::vector<mg::Vec3D>& edges,\n                        std::vector<mg::Vec3D>& o_kb,\n                        std::vector<mg::Vec3D>& o_u,\n                        std::vector<mg::Vec3D>& o_v) const\n{\n    computeKB(edges, o_kb);\n\n    o_u[0] = u0;\n    o_v[0] = mg::cross(edges[0], o_u[0]);\n    o_v[0].normalize();\n\n    double magnitude;\n    double sinPhi, cosPhi;\n//    compute Bishop frame for current configuration by parallel transporting u0\n    for (unsigned i = 1; i < edges.size(); ++i)\n    {\n//        here sinPhi and cosPhi are derived from the length of kb ||kb|| = 2 * tan( phi/2 )\n        magnitude = mg::dot(o_kb[i], o_kb[i]);\n        extractSinAndCos(magnitude, sinPhi, cosPhi);\n        assert( cosPhi >= 0 && cosPhi <= 1 );\n\n        if ( (1 - cosPhi) < mg::ERR )\n        {\n            o_u[i] = o_u[i - 1];\n            o_v[i] = o_v[i - 1];\n            continue;\n        }\n\n//        rotate frame u axis around kb\n        mg::Quaternion q(cosPhi, sinPhi * mg::normalize(o_kb[i]));\n        mg::Quaternion p(0, o_u[i - 1]);\n        p = q * p * mg::conjugate(q);\n\n        o_u[i].set(p[1], p[2], p[3]);\n        o_u[i].normalize();\n        o_v[i] = mg::cross(edges[i], o_u[i]);\n        o_v[i].normalize();\n    }\n}\n\nvoid ElasticRod::parallelTransportFrame(const mg::Vec3D& e0, const mg::Vec3D& e1,\n                                        mg::Vec3D& io_u) const\n{\n    mg::Vec3D axis = 2 * mg::cross(e0, e1) /\n            (e0.length() * e1.length() + mg::dot(e0, e1));\n\n//    here sinPhi and cosPhi are derived from the length of axis ||axis|| = 2 * tan( phi/2 )\n    double sinPhi, cosPhi;\n    double magnitude = mg::dot(axis, axis);\n    extractSinAndCos(magnitude, sinPhi, cosPhi);\n    assert( cosPhi >= 0 && cosPhi <= 1 );\n\n    if ( (1 - cosPhi) < mg::ERR )\n    {\n        io_u = mg::cross(e1, io_u);\n        io_u = mg::normalize( mg::cross(io_u, e1) );\n        return;\n    }\n    mg::Quaternion q(cosPhi, sinPhi * mg::normalize(axis));\n    mg::Quaternion p(0, io_u);\n    p = q * p * mg::conjugate(q);\n\n    io_u.set(p[1], p[2], p[3]);\n    io_u.normalize();\n}\n\nvoid ElasticRod::computeMaterialFrame(const ColumnVector &theta,\n                                      std::vector<mg::Vec3D>& io_m1,\n                                      std::vector<mg::Vec3D>& io_m2) const\n{\n    mg::Real sinQ, cosQ;\n    mg::Vec3D m1, m2;\n    for (unsigned i = 0; i < io_m1.size(); ++i)\n    {\n        cosQ = std::cos(theta(i));\n        sinQ = std::sqrt(1 - cosQ * cosQ);\n\n        m1 = cosQ * io_m1[i] + sinQ * io_m2[i];\n        m2 = -sinQ * io_m1[i] + cosQ * io_m2[i];\n\n        io_m1[i] = m1;\n        io_m2[i] = m2;\n    }\n}\n\n\nvoid ElasticRod::applyInternalConstraintsIteration()\n{\n    mg::Vec3D e;\n    mg::Real l, l1, l2;\n    for (unsigned i = 0; i < m_ppos.size() - 1; ++i)\n    {\n        bool clamped_i = m_isClamped.count(i);\n        bool clamped_i1 = m_isClamped.count(i + 1);\n\n        e = m_ppos[i + 1] - m_ppos[i];\n//            approximate e.length() with first order accurate Taylor expansion of square root function in the neightbourhood of (restLength^2)\n        l = 1 - 2 * m_restEdgeL[i] * m_restEdgeL[i] / (m_restEdgeL[i] * m_restEdgeL[i] +  mg::dot(e, e));\n\n        if (clamped_i)\n        {\n            l1 = 0;\n            l2 = -l;\n        }\n        else if (clamped_i1)\n        {\n            l1 = l;\n            l2 = 0;\n        }\n        else\n        {\n            l1 = m_pmass[i + 1] / (m_pmass[i] + m_pmass[i + 1]) * l;\n            l2 = -m_pmass[i] / (m_pmass[i] + m_pmass[i + 1]) * l;\n        }\n\n        m_ppos[i] += l1 * e;\n        m_ppos[i + 1] += l2 * e;\n    }\n}\n\nvoid ElasticRod::accumulateInternalElasticForces(std::vector<mg::Vec3D>& o_forces)\n{\n    std::vector<mg::Matrix3D> minusGKB(m_edges.size());\n    std::vector<mg::Matrix3D> plusGKB(m_edges.size());\n    std::vector<mg::Matrix3D> eqGKB(m_edges.size());\n    computeGradientKB(m_kb, m_edges, minusGKB, plusGKB, eqGKB);\n\n    std::vector<mg::Vec3D> minusGH(m_kb.size());\n    std::vector<mg::Vec3D> plusGH(m_kb.size());\n    std::vector<mg::Vec3D> eqGH(m_kb.size());\n    computeGradientHolonomyTerms(m_kb, minusGH, plusGH, eqGH);\n\n    mg::Vec2D wkj;\n    mg::Matrix2D J;\n    mg::matrix_rotation_2D(J, mg::Constants::pi_over_2());\n\n//    compute dE/dQn\n    unsigned n = m_edges.size() - 1;\n    mg::Real dEdQn;\n    computedEdQj(n, m_m1[n], m_m2[n], m_theta, J * m_params->m_B, dEdQn);\n\n    mg::Matrix23D GW;\n    mg::Vec3D GH, term;\n    for (unsigned i = 0; i < m_ppos.size(); ++i)\n    {\n        if (m_isClamped.count(i))\n        {\n            continue;\n        }\n\n        for (unsigned k = std::max((int)i - 1, 1); k < m_edges.size(); ++k)\n        {\n            computeW(m_kb[k], m_m1[k - 1], m_m2[k - 1], wkj);\n            computeGradientCurvature(i, k, k - 1,\n                                     minusGKB, plusGKB, eqGKB,\n                                     minusGH, plusGH, eqGH,\n                                     wkj,\n                                     J,\n                                     GW);\n\n//            o_forces[i] -= (mg::transpose(GW) * m_params->m_B * (wkj - m_restWprev[k])) / m_restRegionL[k];\n//            assert( std::isfinite(o_forces[i].length_squared()) );\n            term = (mg::transpose(GW) * m_params->m_B * (wkj - m_restWprev[k]));\n\n            computeW(m_kb[k], m_m1[k], m_m2[k], wkj);\n            computeGradientCurvature(i, k, k,\n                                     minusGKB, plusGKB, eqGKB,\n                                     minusGH, plusGH, eqGH,\n                                     wkj,\n                                     J,\n                                     GW);\n//            o_forces[i] -= (mg::transpose(GW) * m_params->m_B * (wkj - m_restWnext[k])) / m_restRegionL[k];\n//            assert( std::isfinite(o_forces[i].length_squared()) );\n            term += (mg::transpose(GW) * m_params->m_B * (wkj - m_restWnext[k]));\n            o_forces[i] -= term / m_restRegionL[k];\n            assert( std::isfinite(o_forces[i].length_squared()) );\n        }\n\n//    need to add  dE/dQn * gradient holonomy(GH) if we have clamped ends since not all twist angles minimize the energy\n        if (m_isClamped.size())\n        {\n            computeGradientHolonomy(i, n, minusGH, plusGH, eqGH, GH);\n            o_forces[i] += dEdQn * GH;\n            assert( std::isfinite(o_forces[i].length_squared()) );\n        }\n\n//        need to limit the force otherwise when e[i] ~ -e[i - 1] ||kb|| goes to infinity => force goes to infinity\n        if (o_forces[i].length_squared() > m_params->m_maxElasticForce * m_params->m_maxElasticForce)\n        {\n            o_forces[i].normalize();\n            o_forces[i] *= m_params->m_maxElasticForce;\n        }\n    }\n\n#ifdef DBUGG\n    m_elasticForce = o_forces;\n#endif\n}\n\nvoid ElasticRod::computeGradientKB(const std::vector<mg::Vec3D> &kb,\n                                   const std::vector<mg::Vec3D> &edges,\n                                   std::vector<mg::Matrix3D>& o_minusGKB,\n                                   std::vector<mg::Matrix3D>& o_plusGKB,\n                                   std::vector<mg::Matrix3D>& o_eqGKB) const\n{\n// Compute skew-symmetric matrix 3x3 [e], such that [e] * x = cross( e, x )\n    std::vector<mg::Matrix3D> edgeMatrix(edges.size());\n    for (unsigned i = 0; i < edges.size(); ++i)\n    {\n        mg::matrix_skew_symmetric(edgeMatrix[i], edges[i]);\n    }\n\n    o_minusGKB[0].zero();\n    o_plusGKB[0].zero();\n    o_eqGKB[0].zero();\n\n    mg::Real scalarFactor;\n    for (unsigned i = 1; i < edges.size(); ++i)\n    {\n        scalarFactor = (m_restEdgeL[i - 1] * m_restEdgeL[i] + mg::dot( edges[i - 1], edges[i] ));\n        assert( std::isfinite(scalarFactor) && fabs(scalarFactor) > 0 );\n\n        o_minusGKB[i] = (2.0 * edgeMatrix[i - 1] + mg::outer( kb[i], edges[i - 1] )) / scalarFactor;\n        o_plusGKB[i] = (2.0 * edgeMatrix[i] - mg::outer( kb[i], edges[i] )) / scalarFactor;\n        o_eqGKB[i] = -(o_plusGKB[i] + o_minusGKB[i]);\n\n//        o_minusGKB[i] = (2.0 * edgeMatrix[i] + mg::outer( kb[i], edges[i] )) / scalarFactor;\n//        o_plusGKB[i] = (2.0 * edgeMatrix[i - 1] - mg::outer( kb[i], edges[i - 1] )) / scalarFactor;\n//        o_eqGKB[i] = -(o_minusGKB[i] + o_plusGKB[i]);\n    }\n}\n\nvoid ElasticRod::computeGradientHolonomyTerms(const std::vector<mg::Vec3D> &kb,\n                                       std::vector<mg::Vec3D>& o_minusGH,\n                                       std::vector<mg::Vec3D>& o_plusGH,\n                                       std::vector<mg::Vec3D>& o_eqGH) const\n{\n    o_minusGH[0].zero();\n    o_plusGH[0].zero();\n    o_eqGH[0].zero();\n\n    for (unsigned i = 1; i < kb.size(); ++i)\n    {\n        o_minusGH[i] = 0.5 * kb[i] / m_restEdgeL[i - 1];\n        o_plusGH[i]  = -0.5 * kb[i] / m_restEdgeL[i];\n        o_eqGH[i] = -(o_minusGH[i] + o_plusGH[i]);\n\n        assert( std::isfinite( o_minusGH[i].length_squared() ) );\n        assert( std::isfinite( o_plusGH[i].length_squared() ) );\n        assert( std::isfinite( o_eqGH[i].length_squared() ) );\n    }\n}\n\nvoid ElasticRod::computeGradientCurvature(unsigned i, unsigned k, unsigned j,\n                                        const std::vector<mg::Matrix3D>& minusGKB,\n                                        const std::vector<mg::Matrix3D>& plusGKB,\n                                        const std::vector<mg::Matrix3D>& eqGKB,\n                                        const std::vector<mg::Vec3D>& minusGH,\n                                        const std::vector<mg::Vec3D>& plusGH,\n                                        const std::vector<mg::Vec3D>& eqGH,\n                                        const mg::Vec2D &wkj,\n                                        const mg::Matrix2D &J,\n                                        mg::Matrix23D &o_GW) const\n{\n    assert( k >= (i - 1) && (j == k || j == (k - 1)) && j < m_m1.size() );\n\n//    need to make o_GW zero 3x2 matrix\n    o_GW.zero();\n//    compute gradient KB(GKB) term\n    if (k < i + 2)\n    {\n        o_GW(0,0) = m_m2[j][0];\n        o_GW(0,1) = m_m2[j][1];\n        o_GW(0,2) = m_m2[j][2];\n\n        o_GW(1,0) = -m_m1[j][0];\n        o_GW(1,1) = -m_m1[j][1];\n        o_GW(1,2) = -m_m1[j][2];\n\n        if (k == (i - 1))\n        {\n            o_GW = o_GW * plusGKB[k];\n        } else if (k == i)\n        {\n            o_GW = o_GW * eqGKB[k];\n        } else if (k == i + 1)\n        {\n            o_GW = o_GW * minusGKB[k];\n        }\n    }\n//    compute gradient Holonomy(GH) term\n    mg::Vec3D GH;\n    computeGradientHolonomy(i, j, minusGH, plusGH, eqGH, GH);\n    o_GW -= J * mg::outer(wkj, GH);\n}\n\nvoid ElasticRod::computeGradientHolonomy(unsigned i , unsigned j,\n                                 const std::vector<mg::Vec3D>& minusGH,\n                                 const std::vector<mg::Vec3D>& plusGH,\n                                 const std::vector<mg::Vec3D>& eqGH,\n                                 mg::Vec3D& o_GH) const\n{\n    o_GH.zero();\n\n    if (j >= (i - 1) && i > 1 && (i - 1) < plusGH.size())\n    {\n        o_GH += plusGH[i - 1];\n    }\n    if (j >= i && i < eqGH.size())\n    {\n        o_GH += eqGH[i];\n    }\n    if (j >= (i + 1) && (i + 1) < minusGH.size())\n    {\n        o_GH += minusGH[i + 1];\n    }\n}\n\nvoid ElasticRod::computeEnergy(const std::vector<mg::Vec3D>& m1,\n                               const std::vector<mg::Vec3D>& m2,\n                               const ColumnVector &theta,\n                               mg::Real &o_E) const\n{\n    o_E = 0.0;\n    mg::Vec2D wij;\n    mg::Real mi;\n    for (unsigned i = 1; i < m_edges.size(); ++i)\n    {\n//        bend energy term\n        computeW(m_kb[i], m1[i - 1], m2[i - 1], wij);\n        o_E += mg::dot(wij - m_restWprev[i], m_params->m_B * (wij - m_restWprev[i])) * 0.5 / m_restRegionL[i];\n\n        computeW(m_kb[i], m1[i], m2[i], wij);\n        o_E += mg::dot(wij - m_restWnext[i], m_params->m_B * (wij - m_restWnext[i])) * 0.5 / m_restRegionL[i];\n\n//        twist energy term\n        mi = (theta(i) - theta(i - 1));\n        o_E += m_params->m_beta * mi * mi / m_restRegionL[i];\n    }\n}\n\nvoid ElasticRod::computedEdQj(unsigned j,\n                              const mg::Vec3D& m1j,\n                              const mg::Vec3D& m2j,\n                              const ColumnVector &theta,\n                              const mg::Matrix2D &JB,\n                              mg::Real &o_dEQj) const\n{\n    o_dEQj = 0.0;\n    mg::Vec2D wij;\n    mg::Real term;\n//    compute first term dWj/dQj + 2 * beta * mj / lj\n    if (j > 0)\n    {\n        computeW(m_kb[j], m1j, m2j, wij);\n\n        term = mg::dot(wij, JB * (wij - m_restWnext[j]));\n        term += 2 * m_params->m_beta * (theta(j) - theta(j - 1));\n        term /= m_restRegionL[j];\n\n        o_dEQj += term;\n    }\n//    compute second term dWj+1/dQj - 2 * beta * mj+1 / lj+1\n    if (j < m_edges.size() - 1)\n    {\n        computeW(m_kb[j + 1], m1j, m2j, wij);\n\n        term = mg::dot(wij, JB * (wij - m_restWprev[j + 1]));\n        term -= 2 * m_params->m_beta * (theta(j + 1) - theta(j));\n        term /= m_restRegionL[j + 1];\n\n        o_dEQj += term;\n    }\n}\n\nvoid ElasticRod::computeHessian(unsigned j,\n                                const mg::Vec3D& m1j,\n                                const mg::Vec3D& m2j,\n                                const mg::Matrix2D& J,\n                                mg::Real &o_Hjjm1,\n                                mg::Real &o_Hjj,\n                                mg::Real &o_Hjjp1) const\n{\n    o_Hjjm1 = o_Hjj = o_Hjjp1 = 0;\n\n    mg::Vec2D wij;\n    double hjj;\n    if (j > 0)\n    {\n        o_Hjjm1 = -2 * m_params->m_beta / m_restRegionL[j];\n\n        computeW(m_kb[j], m1j, m2j, wij);\n\n        hjj = 2 * m_params->m_beta;\n        hjj += mg::dot( wij, mg::transpose(J) * m_params->m_B * J * wij );\n        hjj -= mg::dot( wij, m_params->m_B * (wij - m_restWnext[j]) );\n        hjj /= m_restRegionL[j];\n\n        o_Hjj = hjj;\n    }\n    if (j < m_edges.size() - 1)\n    {\n        o_Hjjp1 = -2 * m_params->m_beta / m_restRegionL[j + 1];\n\n        computeW(m_kb[j + 1], m1j, m2j, wij);\n        hjj = 2 * m_params->m_beta;\n        hjj += mg::dot( wij, mg::transpose(J) * m_params->m_B * J * wij );\n        hjj -= mg::dot( wij, m_params->m_B * (wij - m_restWprev[j + 1]) );\n        hjj /= m_restRegionL[j + 1];\n\n        o_Hjj += hjj;\n    }\n}\n\nvoid ElasticRod::updateCurrentState()\n{\n//    parallel transport first frame in time\n    mg::Vec3D e0 = m_edges[0];\n    computeEdges(m_ppos, m_edges);\n    mg::Vec3D e1 = m_edges[0];\n\n    parallelTransportFrame(e0, e1, m_u0);\n    computeBishopFrame(m_u0, m_edges, m_kb, m_m1, m_m2);\n\n    double minE = 0;\n    if (m_params->m_strategy != ElasticRodParams::NONE)\n    {\n        minE = m_minimization->minimize(this, m_theta);\n    }\n    computeMaterialFrame(m_theta, m_m1, m_m2);\n\n#ifdef DBUGG\n    mg::Real E;\n    computeEnergy(m_m1, m_m2, m_theta, E);\n    std::cout<< \"Theta:\" << m_theta << \"\\n\";\n    std::cout<< \"Total Energy: \" << E << \" MIN Energy: \" << minE << std::endl;\n#endif\n}\n\nvoid ElasticRod::printself()\n{\n    for (std::vector<mg::Vec3D>::iterator it = m_ppos.begin();it!=m_ppos.end();it++)\n    {\n        std::cout << \"(\";\n        for (int i=0;i<it->dimension;i++)\n        {\n            std::cout << it->data()[i]<<\",\";\n        }\n        std::cout << \")\";\n    }\n    std::cout << std::endl;\n   \n}\n\n\n\n\n//====================================== MinimizationPImpl implementation =======================================\n\nvoid ElasticRod::MinimizationPImpl::extractThetaVars(const ElasticRod *rod, const ColumnVector& theta, ColumnVector& o_thetaVars)\n{\n    o_thetaVars.set_size(theta.size() - rod->m_isClamped.size());\n    unsigned j = 0;\n    for (unsigned i = 0; i < theta.size(); ++i)\n    {\n        if (rod->m_isClamped.count(i) || rod->m_isClamped.count(i + 1))\n        {\n            continue;\n        }\n        o_thetaVars(j) = theta(i);\n        ++j;\n    }\n}\n\nvoid ElasticRod::MinimizationPImpl::constructTheta(const ElasticRod *rod, const ColumnVector& thetaVars, ColumnVector& o_theta)\n{\n\n    unsigned j = 0;\n    for (unsigned i = 0; i < o_theta.size(); ++i)\n    {\n        if (rod->m_isClamped.count(i) || rod->m_isClamped.count(i + 1))\n        {\n            continue;\n        }\n        o_theta(i) = thetaVars(j);\n        ++j;\n    }\n}\n\ndouble ElasticRod::MinimizationPImpl::minimize(const ElasticRod* rod, ColumnVector &io_theta)\n{\n    m_evaluate.m_rod = rod;\n    m_evaluateGradient.m_rod = rod;\n    m_evaluateHessian.m_rod = rod;\n\n    ColumnVector thetaVars;\n    extractThetaVars(rod, io_theta, thetaVars);\n\n    double minE = -1;\n    switch (rod->m_params->m_strategy) {\n    case ElasticRodParams::BFGS_NUMERIC:\n        minE = dlib::find_min(dlib::bfgs_search_strategy(),\n                             dlib::objective_delta_stop_strategy(rod->m_params->m_tolerance, rod->m_params->m_maxIter),\n                             m_evaluate,\n                             dlib::derivative(m_evaluate),\n                             thetaVars,\n                             0.0);\n        break;\n    case ElasticRodParams::BFGS:\n        minE = dlib::find_min(dlib::bfgs_search_strategy(),\n                             dlib::objective_delta_stop_strategy(rod->m_params->m_tolerance, rod->m_params->m_maxIter),\n                             m_evaluate,\n                             m_evaluateGradient,\n                             thetaVars,\n                             0.0);\n        break;\n    case ElasticRodParams::NEWTON:\n        minE = dlib::find_min(dlib::newton_search_strategy(m_evaluateHessian),\n                             dlib::objective_delta_stop_strategy(rod->m_params->m_tolerance, rod->m_params->m_maxIter),\n                             m_evaluate,\n                             m_evaluateGradient,\n                             thetaVars,\n                             0.0);\n        break;\n    default:\n        break;\n    }\n\n    constructTheta(rod, thetaVars, io_theta);\n\n    return minE;\n}\n\ndouble ElasticRod::MinimizationPImpl::evaluate::operator ()(const ColumnVector& theta) const\n{\n//    TODO FIX: can I avoid copying ?????\n//    keeping m1, m2 as members and copying the data gives ~ 1ms performance benefit\n    std::vector<mg::Vec3D> m1 = m_rod->m_m1;\n    std::vector<mg::Vec3D> m2 = m_rod->m_m2;\n    ColumnVector theta_full = m_rod->m_theta;\n\n    constructTheta(m_rod, theta, theta_full);\n    m_rod->computeMaterialFrame(theta_full, m1, m2);\n\n    mg::Real E;\n    m_rod->computeEnergy(m1, m2, theta_full, E);\n    return (double)E;\n}\n\nColumnVector ElasticRod::MinimizationPImpl::evaluateGradient::operator ()(const ColumnVector &theta) const\n{\n    ColumnVector gradient(theta.size());\n//    TODO FIX: can I avoid copying ?????\n    std::vector<mg::Vec3D> m1 = m_rod->m_m1;\n    std::vector<mg::Vec3D> m2 = m_rod->m_m2;\n    ColumnVector theta_full = m_rod->m_theta;\n\n    constructTheta(m_rod, theta, theta_full);\n    m_rod->computeMaterialFrame(theta_full, m1, m2);\n\n    mg::Matrix2D JB;\n    mg::matrix_rotation_2D(JB, mg::Constants::pi_over_2());\n    JB *= m_rod->m_params->m_B;\n\n    mg::Real dEdQj;\n    unsigned j = 0;\n    for (unsigned i = 0; i < theta_full.size(); ++i)\n    {\n        if (m_rod->m_isClamped.count(i) || m_rod->m_isClamped.count(i + 1))\n        {\n            continue;\n        }\n        m_rod->computedEdQj(i, m1[i], m2[i], theta_full, JB, dEdQj);\n        gradient(j) = dEdQj;\n        ++j;\n    }\n\n    return gradient;\n}\n\nHessian ElasticRod::MinimizationPImpl::evaluateHessian::operator ()(const ColumnVector& theta) const\n{\n    Hessian hessian(theta.size(), theta.size());\n    hessian = dlib::zeros_matrix(hessian);\n//    TODO FIX: can I avoid copying ?????\n    std::vector<mg::Vec3D> m1 = m_rod->m_m1;\n    std::vector<mg::Vec3D> m2 = m_rod->m_m2;\n    ColumnVector theta_full = m_rod->m_theta;\n\n    constructTheta(m_rod, theta, theta_full);\n    m_rod->computeMaterialFrame(theta_full, m1, m2);\n\n    mg::Matrix2D J;\n    mg::matrix_rotation_2D(J, mg::Constants::pi_over_2());\n    mg::Real Hjjm1, Hjj, Hjjp1;\n    unsigned j = 0;\n    for (unsigned i = 0; i < m_rod->m_theta.size(); ++i)\n    {\n        if (m_rod->m_isClamped.count(i) || m_rod->m_isClamped.count(i + 1))\n        {\n            continue;\n        }\n\n        m_rod->computeHessian(i, m1[i], m2[i], J, Hjjm1, Hjj, Hjjp1);\n\n        if (j > 0)\n        {\n            hessian(j, j - 1) = Hjjm1;\n        }\n        hessian(j, j) = Hjj;\n        if ((j + 1) < theta.size())\n        {\n            hessian(j, j + 1) = Hjjp1;\n        }\n        ++j;\n    }\n\n    return hessian;\n}\n\n\n\n\n\n\n\n\n\n//============================  =======================\n\n\n\n//    mg::Real dEdQj;\n//        for (unsigned j = std::max((int)(i) - 1, 0); j < m_edges.size(); ++j)\n//        {\n//            computedEdQj(j, J * m_B, dEdQj);\n//            computeGradientHolonomySum(i, n, minusGH, plusGH, eqGH, GH);\n//            o_forces[i] += dEdQj * GH;\n//        }\n\n\n//void ElasticRod::computeElasticForces(const std::vector<mg::Vec3D>& vertices, std::vector<mg::Vec3D>& o_forces)\n//{\n////    TODO: need to implement minimization of energy for twistAngles first\n\n//    std::vector<mg::Matrix3D> minusGKB(3);\n//    std::vector<mg::Matrix3D> eqGKB(3);\n//    std::vector<mg::Matrix3D> plusGKB(3);\n//    std::vector<mg::Vec3D> minusGH(3);\n//    std::vector<mg::Vec3D> eqGH(3);\n//    std::vector<mg::Vec3D> plusGH(3);\n//    for (unsigned i = 0; i < minusGKB.size(); ++i)\n//    {\n//        minusGKB.zero();\n//        eqGKB.zero();\n//        plusGKB.zero();\n//        minusGH.zero();\n//        eqGH.zero();\n//        plusGH.zero();\n//    }\n\n\n\n//    mg::Matrix23D gw;\n//    for (unsigned i = 0; i < vertices.size(); ++i)\n//    {\n//        computeGKBandGH(i + 1, minusGKB, eqGKB, plusGKB, minusGH, eqGH, plusGH);\n\n//        if (m_isClamped.count(i))\n//        {\n//            continue;\n//        } ...\n\n\n\n//void ElasticRod::computeGKBandGH(unsigned idx,\n//                                std::vector<mg::Matrix3D> &o_minusGKB,\n//                                std::vector<mg::Matrix3D> &o_eqGKB,\n//                                std::vector<mg::Matrix3D> &o_plusGKB,\n//                                std::vector<mg::Vec3D> &o_minusGH,\n//                                std::vector<mg::Vec3D> &o_eqGH,\n//                                std::vector<mg::Vec3D> &o_plusGH) const\n//{\n//    assert(idx > 0 && idx < m_edges.size());\n\n//    for (unsigned i = 0; i < o_minusGKB.size() - 1; ++i)\n//    {\n//        o_minusGKB[i] = o_minusGKB[i + 1];\n//        o_eqGKB[i] = o_eqGKB[i + 1];\n//        o_plusGKB[i] = o_plusGKB[i + 1];\n\n//        o_minusGH[i] = o_minusGH[i + 1];\n//        o_eqGH[i] = o_eqGH[i + 1];\n//        o_plusGH[i] = o_plusGH[i + 1];\n//    }\n\n//    mg::Real scalarFactor = (m_restEdgeL[idx - 1] * m_restEdgeL[idx] + mg::dot( m_edges[idx - 1], m_edges[idx] ));;\n//    assert( std::isfinite(scalarFactor) && fabs(scalarFactor) > 0 );\n//    mg::Matrix3D edgeMatrix;\n//    mg::matrix_skew_symmetric(edgeMatrix, edges[idx]);\n\n//    o_minusGKB[i] = (2.0 * edgeMatrix[i] + mg::outer( kb[i], edges[i] )) / scalarFactor;\n//    o_plusGKB[i] = (2.0 * edgeMatrix[i - 1] - mg::outer( kb[i], edges[i - 1] )) / scalarFactor;\n//    o_eqGKB[i] = -(o_minusGKB[i] + o_plusGKB[i]);\n\n//}\n\n", "meta": {"hexsha": "ca2cd47b04bcb54cd25222324a7e12578def8695", "size": 29511, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Plugins/Mipf_Plugin_Simulation/DER/ElasticRod.cpp", "max_stars_repo_name": "linson7017/MIPF", "max_stars_repo_head_hexsha": "adf982ae5de69fca9d6599fbbbd4ca30f4ae9767", "max_stars_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2017-04-13T06:01:49.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-04T07:23:53.000Z", "max_issues_repo_path": "Plugins/Mipf_Plugin_Simulation/DER/ElasticRod.cpp", "max_issues_repo_name": "linson7017/MIPF", "max_issues_repo_head_hexsha": "adf982ae5de69fca9d6599fbbbd4ca30f4ae9767", "max_issues_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-10-27T02:00:44.000Z", "max_issues_repo_issues_event_max_datetime": "2017-10-27T02:00:44.000Z", "max_forks_repo_path": "Plugins/Mipf_Plugin_Simulation/DER/ElasticRod.cpp", "max_forks_repo_name": "linson7017/MIPF", "max_forks_repo_head_hexsha": "adf982ae5de69fca9d6599fbbbd4ca30f4ae9767", "max_forks_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-09-06T01:59:07.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-04T07:23:54.000Z", "avg_line_length": 32.2877461707, "max_line_length": 161, "alphanum_fraction": 0.5249567958, "num_tokens": 8827, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.45763347935827314}}
{"text": "/*\n@copyright Louis Dionne 2015\nDistributed under the Boost Software License, Version 1.0.\n(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n */\n\n#include <boost/hana/assert.hpp>\n#include <boost/hana/ext/std/integral_constant.hpp>\n#include <boost/hana/integral_constant.hpp>\n#include <boost/hana/maybe.hpp>\n#include <boost/hana/tuple.hpp>\n#include <boost/hana/type.hpp>\n\n#include <string>\n#include <type_traits>\nusing namespace boost::hana;\n\n\nint main() {\n\n{\n\n//! [concat]\nusing namespace literals;\nBOOST_HANA_CONSTEXPR_CHECK(\n    concat(make<Tuple>(1, '2'), make<Tuple>(3.3, 4_c)) == make<Tuple>(1, '2', 3.3, 4_c)\n);\n//! [concat]\n\n}{\n\n//! [empty]\nBOOST_HANA_CONSTANT_CHECK(empty<Tuple>() == make<Tuple>());\nBOOST_HANA_CONSTANT_CHECK(empty<Maybe>() == nothing);\n//! [empty]\n\n}{\n\n//! [prepend]\nBOOST_HANA_CONSTEXPR_CHECK(prepend(1, make<Tuple>()) == make<Tuple>(1));\nBOOST_HANA_CONSTEXPR_CHECK(prepend(1, make<Tuple>('2', 3.3)) == make<Tuple>(1, '2', 3.3));\nBOOST_HANA_CONSTEXPR_CHECK(\n    prepend(1, prepend('2', prepend(3.3, make<Tuple>()))) == make<Tuple>(1, '2', 3.3)\n);\n//! [prepend]\n\n}{\n\n//! [append]\nBOOST_HANA_CONSTEXPR_CHECK(append(make<Tuple>(), 1) == make<Tuple>(1));\nBOOST_HANA_CONSTEXPR_CHECK(append(make<Tuple>(1, '2'), 3.3) == make<Tuple>(1, '2', 3.3));\nBOOST_HANA_CONSTEXPR_CHECK(\n    append(append(append(make<Tuple>(), 1), '2'), 3.3) == make<Tuple>(1, '2', 3.3)\n);\n//! [append]\n\n}{\n\n//! [filter]\nBOOST_HANA_CONSTEXPR_CHECK(\n    filter(make<Tuple>(1, 2.0, 3, 4.0), trait_<std::is_integral>) == make<Tuple>(1, 3)\n);\n\nBOOST_HANA_CONSTEXPR_CHECK(\n    filter(just(3), trait_<std::is_integral>) == just(3)\n);\n\nBOOST_HANA_CONSTANT_CHECK(\n    filter(just(3.0), trait_<std::is_integral>) == nothing\n);\n//! [filter]\n\n}{\n\n//! [cycle]\nBOOST_HANA_CONSTEXPR_CHECK(\n    cycle(size_t<2>, make<Tuple>('x', 'y', 'z')) == make<Tuple>('x', 'y', 'z', 'x', 'y', 'z')\n);\n//! [cycle]\n\n}{\n\n//! [repeat]\nBOOST_HANA_CONSTEXPR_CHECK(repeat<Tuple>(size_t<2>, 'x') == make<Tuple>('x', 'x'));\n\n// Of course, because Maybe can hold at most one element.\nstatic_assert(repeat<Maybe>(size_t<2>, 'x') == just('x'), \"\");\n//! [repeat]\n\n}{\n\n//! [prefix]\nusing namespace std::literals;\nBOOST_HANA_RUNTIME_CHECK(\n    prefix(\"my\"s, make<Tuple>(\"dog\"s, \"car\"s, \"house\"s)) ==\n    make<Tuple>(\"my\", \"dog\", \"my\", \"car\", \"my\", \"house\")\n);\n//! [prefix]\n\n}{\n\n//! [suffix]\nBOOST_HANA_CONSTEXPR_CHECK(\n    suffix(0, make<Tuple>(1, 2, 3, 4)) == make<Tuple>(1, 0, 2, 0, 3, 0, 4, 0)\n);\n//! [suffix]\n\n}\n\n}\n", "meta": {"hexsha": "7e5cc014ee520e1eac24f839a508b94aad654c34", "size": 2497, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/monad_plus.cpp", "max_stars_repo_name": "josephwinston/hana", "max_stars_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/monad_plus.cpp", "max_issues_repo_name": "josephwinston/hana", "max_issues_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/monad_plus.cpp", "max_forks_repo_name": "josephwinston/hana", "max_forks_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.4954954955, "max_line_length": 93, "alphanum_fraction": 0.6391670004, "num_tokens": 794, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6513548646660543, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.4575963745152162}}
{"text": "/*\n * test_statinfos.cpp\n *\n *  Created on: 13 mai 2016\n *      Author: boubad\n */\n///////////////////////////////////\n#include <boost/test/unit_test.hpp>\n///////////////////////////\n#include \"indivproviderfixture.h\"\n/////////////////////////\n#include <statinfo.h>\n#include <indivcluster.h>\n//////////////////////\nusing namespace std;\nusing namespace info;\n/////////////////////////////\nBOOST_FIXTURE_TEST_SUITE(MiscTestSuite, IndivProviderFixture)\n;\nBOOST_AUTO_TEST_CASE(testStatInfo) {\n\tIIndivProvider *pProvider = m_provider.get();\n\tstatinfos_map oRes;\n\tsize_t n = info_global_compute_stats(pProvider, oRes);\n\tBOOST_CHECK(n == this->m_nbcols);\n} //testStatInfo\nBOOST_AUTO_TEST_CASE(testComputeDistances) {\n\tIIndivProvider *pProvider = m_provider.get();\n\t//\n\tsize_t nc = 0;\n\tbool bRet = pProvider->indivs_count(nc);\n\tBOOST_CHECK(bRet);\n\tBOOST_CHECK(m_nbrows == nc);\n\t//\n\tIndivDistanceMap oDistances;\n\tinfo_global_compute_distances(pProvider, oDistances);\n\t//\n\tconst ints_set &oSetIndivs = oDistances.indexes();\n\tBOOST_CHECK(oSetIndivs.size() == nc);\n\t//\n\tfor (size_t i = 0; i < nc; ++i) {\n\t\tIndiv oInd1;\n\t\tbRet = pProvider->find_indiv_at(i, oInd1);\n\t\tBOOST_CHECK(bRet);\n\t\tIntType aIndex1 = oInd1.id();\n\t\tBOOST_CHECK(aIndex1 != 0);\n\t\tfor (size_t j = 0; j < i; ++j) {\n\t\t\tIndiv oInd2;\n\t\t\tbRet = pProvider->find_indiv_at(j, oInd2);\n\t\t\tBOOST_CHECK(bRet);\n\t\t\tIntType aIndex2 = oInd2.id();\n\t\t\tBOOST_CHECK(aIndex2 != 0);\n\t\t\tdouble dRes = 0;\n\t\t\tbRet = oDistances.get(aIndex1, aIndex2, dRes);\n\t\t\tBOOST_CHECK(bRet);\n\t\t\tBOOST_CHECK(dRes > 0);\n\t\t} // j\n\t} // i\n} //testComputeDistances\n\nBOOST_AUTO_TEST_SUITE_END();\n\n", "meta": {"hexsha": "5577565da14b01d133268106f54e22b5970d1286", "size": 1606, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost_testdtatdata/tests/test_statinfos.cpp", "max_stars_repo_name": "boubad/CygProjects", "max_stars_repo_head_hexsha": "cdc0dc2cb6e34b94d1bafbf3fd216b32c320985d", "max_stars_repo_licenses": ["Apache-2.0"], "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_testdtatdata/tests/test_statinfos.cpp", "max_issues_repo_name": "boubad/CygProjects", "max_issues_repo_head_hexsha": "cdc0dc2cb6e34b94d1bafbf3fd216b32c320985d", "max_issues_repo_licenses": ["Apache-2.0"], "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_testdtatdata/tests/test_statinfos.cpp", "max_forks_repo_name": "boubad/CygProjects", "max_forks_repo_head_hexsha": "cdc0dc2cb6e34b94d1bafbf3fd216b32c320985d", "max_forks_repo_licenses": ["Apache-2.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.9032258065, "max_line_length": 61, "alphanum_fraction": 0.6457036115, "num_tokens": 471, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548646660543, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.45759636640176243}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2014   LASMEA UMR 6602 CNRS/UBP\n//         Copyright 2009 - 2014   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n// cover for functor fast_tand in scalar mode\n#include <nt2/trigonometric/include/functions/fast_tand.hpp>\n#include <boost/simd/sdk/simd/io.hpp>\n#include <cmath>\n#include <iostream>\n#include <nt2/sdk/unit/args.hpp>\n#include <nt2/sdk/unit/module.hpp>\n#include <nt2/sdk/unit/tests/cover.hpp>\n#include <vector>\n\nextern \"C\" {extern long double cephes_tanl(long double);}\n\nNT2_TEST_CASE_TPL(fast_tand_0,  NT2_SIMD_REAL_TYPES)\n{\n  using nt2::unit::args;\n  const std::size_t NR = args(\"samples\", NT2_NB_RANDOM_TEST);\n  const double ulpd = args(\"ulpd\", 2.5);\n\n  const T min = args(\"min\", T(-45));\n  const T max = args(\"max\", T(45));\n  std::cout << \"Argument samples #0 chosen in range: [\" << min << \",  \" << max << \"]\" << std::endl;\n  NT2_CREATE_BUF(a0,T, NR, min, max);\n    const long double long_deginrad = 0.017453292519943295769236907684886l;\n\n  std::vector<T> ref(NR);\n  for(std::size_t i=0; i!=NR; ++i)\n    ref[i] = ::cephes_tanl(a0[i]*long_deginrad);\n\n  NT2_COVER_ULP_EQUAL(nt2::tag::fast_tand_, ((T, a0)), ref, ulpd);\n\n}\n", "meta": {"hexsha": "5e8ddac61c442d88be1f1e56d17f39d838fbe23f", "size": 1515, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/core/trigonometric/cover/scalar/fast_tand.cpp", "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/cover/scalar/fast_tand.cpp", "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/cover/scalar/fast_tand.cpp", "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.875, "max_line_length": 99, "alphanum_fraction": 0.5887788779, "num_tokens": 428, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7025300573952052, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.457596365703864}}
{"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//This algorithm is described in \"Network Flows: Theory, Algorithms, and Applications\"\r\n// by Ahuja, Magnanti, Orlin.\r\n\r\n#ifndef BOOST_GRAPH_SUCCESSIVE_SHORTEST_PATH_HPP\r\n#define BOOST_GRAPH_SUCCESSIVE_SHORTEST_PATH_HPP \r\n\r\n#include <numeric>\r\n\r\n#include <boost/property_map/property_map.hpp>\r\n#include <boost/graph/graph_traits.hpp>\r\n#include <boost/graph/graph_concepts.hpp>\r\n#include <boost/pending/indirect_cmp.hpp>\r\n#include <boost/pending/relaxed_heap.hpp>\r\n#include <boost/graph/dijkstra_shortest_paths.hpp>\r\n#include <boost/graph/properties.hpp>\r\n#include <boost/graph/iteration_macros.hpp>\r\n#include <boost/graph/detail/augment.hpp>\r\n\r\nnamespace boost {\r\n\r\n\r\nnamespace detail {\r\n    \r\ntemplate <class Graph, class Weight, class Distance, class Reversed>\r\nclass MapReducedWeight : \r\n    public put_get_helper<typename property_traits<Weight>::value_type, MapReducedWeight<Graph, Weight, Distance, Reversed> > {\r\n    typedef graph_traits<Graph> gtraits;\r\npublic:\r\n    typedef boost::readable_property_map_tag category;\r\n    typedef typename property_traits<Weight>::value_type value_type;\r\n    typedef value_type reference;\r\n    typedef typename gtraits::edge_descriptor key_type;\r\n    MapReducedWeight(const Graph & g, Weight w, Distance d, Reversed r) : \r\n        g_(g), weight_(w), distance_(d), rev_(r) {}\r\n\r\n    reference operator[](key_type v) const {\r\n        return get(distance_, source(v, g_)) - get(distance_,target(v, g_)) + get(weight_, v); \r\n    }\r\nprivate:\r\n    const Graph & g_;\r\n    Weight weight_;\r\n    Distance distance_;\r\n    Reversed rev_;\r\n};\r\n\r\ntemplate <class Graph, class Weight, class Distance, class Reversed>\r\nMapReducedWeight<Graph, Weight, Distance, Reversed> \r\nmake_mapReducedWeight(const Graph & g, Weight w, Distance d, Reversed r)  {\r\n    return MapReducedWeight<Graph, Weight, Distance, Reversed>(g, w, d, r);\r\n}\r\n\r\n}//detail\r\n\r\n\r\ntemplate <class Graph, class Capacity, class ResidualCapacity, class Reversed, class Pred, class Weight, class Distance, class Distance2, class VertexIndex>\r\nvoid successive_shortest_path_nonnegative_weights(\r\n        const Graph &g, \r\n        typename graph_traits<Graph>::vertex_descriptor s, \r\n        typename graph_traits<Graph>::vertex_descriptor t,\r\n        Capacity capacity,\r\n        ResidualCapacity residual_capacity,\r\n        Weight weight, \r\n        Reversed rev,\r\n        VertexIndex index,\r\n        Pred pred, \r\n        Distance distance,\r\n        Distance2 distance_prev) {\r\n    filtered_graph<const Graph, is_residual_edge<ResidualCapacity> >\r\n        gres = detail::residual_graph(g, residual_capacity);\r\n    typedef typename graph_traits<Graph>::edge_descriptor edge_descriptor;\r\n    \r\n    BGL_FORALL_EDGES_T(e, g, Graph) {\r\n        put(residual_capacity, e, get(capacity, e));\r\n    }\r\n\r\n    BGL_FORALL_VERTICES_T(v, g, Graph) {\r\n        put(distance_prev, v, 0);\r\n    }\r\n\r\n    while(true) {\r\n        BGL_FORALL_VERTICES_T(v, g, Graph) {\r\n            put(pred, v, edge_descriptor());\r\n        }\r\n        dijkstra_shortest_paths(gres, s, \r\n                weight_map(detail::make_mapReducedWeight(gres, weight, distance_prev, rev)).\r\n                distance_map(distance).\r\n                vertex_index_map(index).\r\n                visitor(make_dijkstra_visitor(record_edge_predecessors(pred, on_edge_relaxed()))));\r\n\r\n        if(get(pred, t) == edge_descriptor()) {\r\n            break;\r\n        }\r\n\r\n        BGL_FORALL_VERTICES_T(v, g, Graph) {\r\n            put(distance_prev, v, get(distance_prev, v) + get(distance, v));\r\n        }\r\n\r\n        detail::augment(g, s, t, pred, residual_capacity, rev);\r\n    }\r\n}\r\n\r\n//in this namespace argument dispatching tak place\r\nnamespace detail {\r\n\r\ntemplate <class Graph, class Capacity, class ResidualCapacity, class Weight, class Reversed, class Pred, class Distance, class Distance2, class VertexIndex>\r\nvoid successive_shortest_path_nonnegative_weights_dispatch3(\r\n        const Graph &g, \r\n        typename graph_traits<Graph>::vertex_descriptor s, \r\n        typename graph_traits<Graph>::vertex_descriptor t,\r\n        Capacity capacity,\r\n        ResidualCapacity residual_capacity,\r\n        Weight weight,\r\n        Reversed rev,\r\n        VertexIndex index,\r\n        Pred pred,\r\n        Distance dist,\r\n        Distance2 dist_pred) {\r\n    successive_shortest_path_nonnegative_weights(g, s, t, capacity, residual_capacity, weight, rev, index, pred, dist, dist_pred);\r\n}\r\n\r\n//setting default distance map\r\ntemplate <class Graph, class Capacity, class ResidualCapacity, class Weight, class Reversed, class Pred, class Distance, class VertexIndex>\r\nvoid successive_shortest_path_nonnegative_weights_dispatch3(\r\n        Graph &g, \r\n        typename graph_traits<Graph>::vertex_descriptor s, \r\n        typename graph_traits<Graph>::vertex_descriptor t,\r\n        Capacity capacity,\r\n        ResidualCapacity residual_capacity,\r\n        Weight weight,\r\n        Reversed rev,\r\n        VertexIndex index,\r\n        Pred pred,\r\n        Distance dist,\r\n        param_not_found) {\r\n    typedef typename property_traits<Weight>::value_type D;\r\n\r\n    std::vector<D> d_map(num_vertices(g));\r\n\r\n    successive_shortest_path_nonnegative_weights(g, s, t, capacity, residual_capacity, weight, rev, index, pred, dist,\r\n                             make_iterator_property_map(d_map.begin(), index));\r\n}\r\n\r\ntemplate <class Graph, class P, class T, class R, class Capacity, class ResidualCapacity, class Weight, class Reversed, class Pred, class Distance, class VertexIndex>\r\nvoid successive_shortest_path_nonnegative_weights_dispatch2(\r\n        Graph &g, \r\n        typename graph_traits<Graph>::vertex_descriptor s, \r\n        typename graph_traits<Graph>::vertex_descriptor t,\r\n        Capacity capacity,\r\n        ResidualCapacity residual_capacity,\r\n        Weight weight,\r\n        Reversed rev,\r\n        VertexIndex index,\r\n        Pred pred,\r\n        Distance dist,\r\n        const bgl_named_params<P, T, R>& params) {\r\n    successive_shortest_path_nonnegative_weights_dispatch3(g, s, t, capacity, residual_capacity, weight, rev, index, pred, dist, get_param(params, vertex_distance2));\r\n}\r\n\r\n//setting default distance map\r\ntemplate <class Graph, class P, class T, class R, class Capacity, class ResidualCapacity, class Weight, class Reversed, class Pred, class VertexIndex>\r\nvoid successive_shortest_path_nonnegative_weights_dispatch2(\r\n        Graph &g, \r\n        typename graph_traits<Graph>::vertex_descriptor s, \r\n        typename graph_traits<Graph>::vertex_descriptor t,\r\n        Capacity capacity,\r\n        ResidualCapacity residual_capacity,\r\n        Weight weight,\r\n        Reversed rev,\r\n        VertexIndex index,\r\n        Pred pred,\r\n        param_not_found, \r\n        const bgl_named_params<P, T, R>& params) {\r\n    typedef typename property_traits<Weight>::value_type D;\r\n\r\n    std::vector<D> d_map(num_vertices(g));\r\n\r\n    successive_shortest_path_nonnegative_weights_dispatch3(g, s, t, capacity, residual_capacity, weight, rev, index, pred,\r\n            make_iterator_property_map(d_map.begin(), index),\r\n            get_param(params, vertex_distance2));\r\n}\r\n\r\ntemplate <class Graph, class P, class T, class R, class Capacity, class ResidualCapacity, class Weight, class Reversed, class Pred, class VertexIndex>\r\nvoid successive_shortest_path_nonnegative_weights_dispatch1(\r\n        Graph &g, \r\n        typename graph_traits<Graph>::vertex_descriptor s, \r\n        typename graph_traits<Graph>::vertex_descriptor t,\r\n        Capacity capacity,\r\n        ResidualCapacity residual_capacity,\r\n        Weight weight, \r\n        Reversed rev,\r\n        VertexIndex index,\r\n        Pred pred,\r\n        const bgl_named_params<P, T, R>& params) {\r\n    successive_shortest_path_nonnegative_weights_dispatch2(g, s, t, capacity, residual_capacity, weight,  rev, index, pred,\r\n                                get_param(params, vertex_distance), params);\r\n}\r\n\r\n//setting default predecessors map\r\ntemplate <class Graph, class P, class T, class R, class Capacity, class ResidualCapacity, class Weight, class Reversed, class VertexIndex>\r\nvoid successive_shortest_path_nonnegative_weights_dispatch1(\r\n        Graph &g, \r\n        typename graph_traits<Graph>::vertex_descriptor s, \r\n        typename graph_traits<Graph>::vertex_descriptor t,\r\n        Capacity capacity,\r\n        ResidualCapacity residual_capacity,\r\n        Weight weight, \r\n        Reversed rev,\r\n        VertexIndex index,\r\n        param_not_found,\r\n        const bgl_named_params<P, T, R>& params) {\r\n    typedef typename graph_traits<Graph>::edge_descriptor edge_descriptor;\r\n    std::vector<edge_descriptor> pred_vec(num_vertices(g));\r\n\r\n    successive_shortest_path_nonnegative_weights_dispatch2(g, s, t, capacity, residual_capacity, weight, rev, index, \r\n            make_iterator_property_map(pred_vec.begin(), index),\r\n            get_param(params, vertex_distance), params); \r\n}\r\n\r\n}//detail\r\n\r\n\r\ntemplate <class Graph, class P, class T, class R>\r\nvoid successive_shortest_path_nonnegative_weights(\r\n        Graph &g, \r\n        typename graph_traits<Graph>::vertex_descriptor s, \r\n        typename graph_traits<Graph>::vertex_descriptor t,\r\n        const bgl_named_params<P, T, R>& params) {\r\n           \r\n    return detail::successive_shortest_path_nonnegative_weights_dispatch1(g, s, t, \r\n           choose_const_pmap(get_param(params, edge_capacity), g, edge_capacity),\r\n           choose_pmap(get_param(params, edge_residual_capacity), \r\n                       g, edge_residual_capacity),\r\n           choose_const_pmap(get_param(params, edge_weight), g, edge_weight),\r\n           choose_const_pmap(get_param(params, edge_reverse), g, edge_reverse),\r\n           choose_const_pmap(get_param(params, vertex_index), g, vertex_index),\r\n           get_param(params, vertex_predecessor), \r\n           params);\r\n}\r\n\r\ntemplate <class Graph>\r\nvoid successive_shortest_path_nonnegative_weights(\r\n        Graph &g,\r\n        typename graph_traits<Graph>::vertex_descriptor s, \r\n        typename graph_traits<Graph>::vertex_descriptor t) {\r\n    bgl_named_params<int, buffer_param_t> params(0);\r\n    successive_shortest_path_nonnegative_weights(g, s, t, params);\r\n}\r\n\r\n\r\n}//boost\r\n#endif /* BOOST_GRAPH_SUCCESSIVE_SHORTEST_PATH_HPP */\r\n\r\n", "meta": {"hexsha": "81cfb5ca0289ddb52fe1406bbf15184b5c99b884", "size": 10603, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ios/Pods/boost-for-react-native/boost/graph/successive_shortest_path_nonnegative_weights.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/successive_shortest_path_nonnegative_weights.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/successive_shortest_path_nonnegative_weights.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": 40.4694656489, "max_line_length": 167, "alphanum_fraction": 0.6789587852, "num_tokens": 2261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.6513548511303336, "lm_q1q2_score": 0.4575963609492387}}
{"text": "//\n//  Copyright Toon Knapen, Karl Meerbergen\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\n#include \"../../blas/test/random.hpp\"\n\n#include <boost/numeric/bindings/lapack/computational/sytrd.hpp>\n#include <boost/numeric/bindings/ublas/matrix.hpp>\n#include <boost/numeric/bindings/ublas/symmetric.hpp>\n#include <boost/numeric/bindings/ublas/vector.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <algorithm>\n#include <limits>\n#include <iostream>\n\n\nnamespace ublas = boost::numeric::ublas;\nnamespace lapack = boost::numeric::bindings::lapack;\nnamespace bindings = boost::numeric::bindings;\n\n\ntemplate <typename T, typename UPLO>\nint do_value_type() {\n   const int n = 10 ;\n\n   typedef typename bindings::remove_imaginary<T>::type real_type ;\n   typedef std::complex< real_type >                                            complex_type ;\n\n   typedef ublas::matrix<T, ublas::column_major> matrix_type ;\n   typedef ublas::symmetric_adaptor<matrix_type, UPLO> symmetric_type ;\n   typedef ublas::vector<T>                      vector_type ;\n\n   // Set matrix\n   matrix_type a( n, n );\n   vector_type d( n ), e ( n - 1 ), tau( n - 1 ) ;\n\n   for (int i=0; i<n; ++i ) {\n     for (int j=0; j<n; ++j ) {\n       a(j,i) = 0.0 ;\n     }\n   }\n\n   a(0,0) = 2.0 ;\n   for (int i=1; i<n; ++i ) {\n      a(i,i) = 2.0 ;\n      a(i-1,i) = -1.0 ;\n   }\n\n   // Compute eigendecomposition.\n   symmetric_type s_a( a );\n   lapack::sytrd( s_a, d, e, tau ) ;\n\n   for ( int i=0; i<d.size(); ++i) {\n      if (std::abs( d(i) - 2.0 ) > 10 * std::numeric_limits<T>::epsilon() ) return 1 ;\n   }\n   for ( int i=0; i<e.size(); ++i) {\n      if (std::abs( e(i) + 1.0 ) > 10 * std::numeric_limits<T>::epsilon() ) return 1 ;\n   }\n\n   return 0 ;\n} // do_value_type()\n\n\n\nint main() {\n   // Run tests for different value_types\n   if (do_value_type<float, ublas::upper>()) return 255;\n   if (do_value_type<double, ublas::upper>()) return 255;\n\n   std::cout << \"Regression test succeeded\\n\" ;\n   return 0;\n}\n\n", "meta": {"hexsha": "d420e6e5fb990b9a7befed5e283344adcdde61d4", "size": 2080, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "externals/numeric_bindings/libs/numeric/bindings/lapack/test/ublas_sytrd.cpp", "max_stars_repo_name": "ljktest/siconos", "max_stars_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-08-02T14:21:57.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-05T10:34:45.000Z", "max_issues_repo_path": "externals/numeric_bindings/libs/numeric/bindings/lapack/test/ublas_sytrd.cpp", "max_issues_repo_name": "ljktest/siconos", "max_issues_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-11-07T21:30:35.000Z", "max_issues_repo_issues_event_max_datetime": "2017-11-08T19:44:18.000Z", "max_forks_repo_path": "externals/numeric_bindings/libs/numeric/bindings/lapack/test/ublas_sytrd.cpp", "max_forks_repo_name": "ljktest/siconos", "max_forks_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-07T19:35:16.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-07T19:35:16.000Z", "avg_line_length": 26.3291139241, "max_line_length": 94, "alphanum_fraction": 0.6134615385, "num_tokens": 628, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300449389326, "lm_q2_score": 0.6513548511303336, "lm_q1q2_score": 0.45759635283578504}}
{"text": "// -----------------------------------------------------------------------------\n// Fern \u00a9 Geoneric\n//\n// This file is part of Geoneric Fern which is available under the terms of\n// the GNU General Public License (GPL), version 2. If you do not want to\n// be bound by the terms of the GPL, you may purchase a proprietary license\n// from Geoneric (http://www.geoneric.eu/contact).\n// -----------------------------------------------------------------------------\n#define BOOST_TEST_MODULE fern expression_tree evaluate_visitor\n#include <boost/multi_array.hpp>\n#include <boost/test/unit_test.hpp>\n#include <boost/variant/get.hpp>\n#include \"fern/expression_tree/plus.h\"\n#include \"fern/expression_tree/sqrt.h\"\n#include \"fern/expression_tree/times.h\"\n#include \"fern/expression_tree/evaluate_visitor.h\"\n#include \"fern/feature/core/masked_array.h\"\n\n\nnamespace fern {\nnamespace expression_tree {\n\n// template<\n//     class U,\n//     class V>\n// Operation<typename Plus<Raster<U>, Raster<V>>::result_type> operator+(\n//     Raster<U> const& lhs,\n//     Raster<V> const& rhs)\n// {\n//     return Operation<typename Plus<Raster<U>, Raster<V>>::result_type>(\n//         \"plus\",\n//         Implementation(Plus<Raster<U>, Raster<V>>()),\n//         {\n//             lhs,\n//             rhs\n//         }\n//     );\n// }\n\n\n// template<\n//     class U,\n//     class V>\n// Operation<typename Plus<Raster<U>, Raster<V>>::result_type> operator/(\n//     Operation<Raster<U>> const& lhs,\n//     Raster<V> const& rhs)\n// {\n//     return Operation<typename Plus<Raster<U>, Raster<V>>::result_type>(\n//         \"plus\",\n//         Implementation(Plus<Raster<U>, Raster<V>>()),\n//         {\n//             lhs,\n//             rhs\n//         }\n//     );\n// }\n\n\ntemplate<\n    class U,\n    class V>\nOperation<typename Plus<U, V>::result_type> operator+(\n    U const& lhs,\n    V const& rhs)\n{\n    return Operation<typename Plus<U, V>::result_type>(\n        \"plus\",\n        Implementation(Plus<U, V>()),\n        {\n            lhs,\n            rhs\n        }\n    );\n}\n\n} // namespace expression_tree\n} // namespace fern\n\n\nBOOST_AUTO_TEST_CASE(visit_constants)\n{\n    namespace fet = fern::expression_tree;\n\n    // 2\n    {\n        fet::Constant<int32_t> constant(2);\n        auto expression(constant);\n\n        using Result = decltype(expression)::result_type;\n\n        fet::Data result(fet::evaluate(expression));\n\n        BOOST_REQUIRE_NO_THROW(boost::get<Result>(result));\n        BOOST_CHECK_EQUAL(boost::get<Result>(result).value, 2);\n    }\n\n    // 2 + 1\n    {\n        fet::Constant<int32_t> expression1(2);\n        using Result1 = decltype(expression1)::result_type;\n\n        fet::Constant<int32_t> expression2(1);\n        using Result2 = decltype(expression2)::result_type;\n\n        using Result3 = typename fet::Plus<Result1, Result2>::result_type;\n\n        fet::Operation<Result3> expression3(\n            \"plus\",\n            fet::Implementation(\n                fet::Plus<Result1, Result2>()),\n            {\n                expression1,\n                expression2\n            }\n        );\n\n        fet::Data result(fet::evaluate(expression3));\n\n        BOOST_REQUIRE_NO_THROW(boost::get<Result3>(result));\n        BOOST_CHECK_EQUAL(boost::get<Result3>(result).value, 3);\n    }\n\n    // sqrt((2 + 1) * 3.0)\n    {\n        // 1: 2\n        fet::Constant<int32_t> expression1(2);\n        using Result1 = decltype(expression1)::result_type;\n\n        // 2: 1\n        fet::Constant<int32_t> expression2(1);\n        using Result2 = decltype(expression2)::result_type;\n\n        // 3: 2 + 1\n        using Result3 = typename fet::Plus<Result1, Result2>::result_type;\n\n        fet::Operation<Result3> expression3(\n            \"plus\",\n            fet::Implementation(\n                fet::Plus<Result1, Result2>()),\n            {\n                expression1,\n                expression2\n            }\n        );\n\n        // 4: 3.0\n        fet::Constant<double> expression4(3.0);\n        using Result4 = decltype(expression4)::result_type;\n\n        // 5: (2 + 1) * 3.0\n        using Result5 = typename fet::Times<Result3, Result4>::result_type;\n\n        fet::Operation<Result5> expression5(\n            \"times\",\n            fet::Implementation(\n                fet::Times<Result3, Result4>()),\n            {\n                expression3,\n                expression4\n            }\n        );\n\n        // 6: sqrt((2 + 1) * 3.0)\n        using Result6 = typename fet::Sqrt<Result5>::result_type;\n\n        fet::Operation<Result6> expression6(\n            \"sqrt\",\n            fet::Implementation(\n                fet::Sqrt<Result5>()),\n            {\n                expression5\n            }\n        );\n\n        fet::Data result(fet::evaluate(expression6));\n\n        BOOST_REQUIRE_NO_THROW(boost::get<Result6>(result));\n        BOOST_CHECK_CLOSE(boost::get<Result6>(result).value, 3.0, 1e-6);\n    }\n}\n\n\ntemplate<\n    class T>\nusing Raster = fern::MaskedArray<T, 2>;\n\n\nBOOST_AUTO_TEST_CASE(visit_raster)\n{\n    namespace fet = fern::expression_tree;\n\n    size_t const nr_rows = 3;\n    size_t const nr_cols = 4;\n    auto extents(fern::extents[nr_rows][nr_cols]);\n\n    Raster<int32_t> raster1(extents);\n    raster1[0][0] = -2;\n    raster1[0][1] = -1;\n    raster1[1][0] = 0;\n    raster1.mask()[1][1] = true;\n    raster1[2][0] = 1;\n    raster1[2][1] = 2;\n\n    auto expression1 = fet::Raster<int32_t>(raster1);\n    using Result1 = decltype(expression1)::result_type;\n    static_assert(std::is_same<Result1, fet::Raster<int32_t>>::value, \"\");\n\n    Raster<int32_t> raster2(extents);\n    raster2[0][0] = -20;\n    raster2[0][1] = -10;\n    raster2[1][0] = 0;\n    raster2.mask()[1][1] = true;\n    raster2[2][0] = 10;\n    raster2[2][1] = 20;\n\n    auto expression2 = fet::Raster<int32_t>(raster2);\n    using Result2 = decltype(expression2)::result_type;\n    static_assert(std::is_same<Result2, fet::Raster<int32_t>>::value, \"\");\n\n    Raster<double> raster3(extents);\n    raster3[0][0] = 2.0;\n    raster3[0][1] = 4.0;\n    raster3[1][0] = 6.0;\n    raster3[1][1] = 8.0;\n    raster3[2][0] = 10.0;\n    raster3[2][1] = 12.0;\n\n    auto expression3 = fet::Raster<double>(raster3);\n    using Result3 = decltype(expression3)::result_type;\n    static_assert(std::is_same<Result3, fet::Raster<double>>::value, \"\");\n\n    // raster + raster\n    {\n        using namespace fern::expression_tree;\n\n        auto operation = expression1 + expression2;\n\n        fet::evaluate(operation);\n        fet::Data result(fet::evaluate(operation));\n\n        BOOST_REQUIRE_NO_THROW(boost::get<fet::Raster<int32_t> const&>(result));\n        fet::Raster<int32_t> const& result_raster(\n            boost::get<fet::Raster<int32_t> const&>(result));\n        Raster<int32_t> const& raster(result_raster.value);\n\n        BOOST_REQUIRE_EQUAL(raster.num_dimensions(), 2);\n        BOOST_REQUIRE_EQUAL(raster.shape()[0], nr_rows);\n        BOOST_REQUIRE_EQUAL(raster.shape()[1], nr_cols);\n\n        BOOST_CHECK(!raster.mask()[0][0]);\n        BOOST_CHECK_EQUAL(raster[0][0], -22);\n\n        BOOST_CHECK(!raster.mask()[0][1]);\n        BOOST_CHECK_EQUAL(raster[0][1], -11);\n\n        BOOST_CHECK(!raster.mask()[1][0]);\n        BOOST_CHECK_EQUAL(raster[1][0],  0);\n\n        BOOST_CHECK( raster.mask()[1][1]);\n\n        BOOST_CHECK(!raster.mask()[2][0]);\n        BOOST_CHECK_EQUAL(raster[2][0],  11);\n\n        BOOST_CHECK(!raster.mask()[2][1]);\n        BOOST_CHECK_EQUAL(raster[2][1],  22);\n    }\n\n    // raster + raster + raster\n    {\n        auto operation = expression1 + expression2 + expression3;\n\n        // std::cout << \"evaluate...\" << std::endl;\n        fet::evaluate(operation);\n        // std::cout << \"/evaluate...\" << std::endl;\n        // fet::Data result(fet::evaluate(operation));\n\n        // BOOST_REQUIRE_NO_THROW(boost::get<fet::Raster<double> const&>(result));\n        // fet::Raster<double> const& result_raster(\n        //     boost::get<fet::Raster<double> const&>(result));\n        // Raster<double> const& raster(result_raster.value);\n        // return;\n\n        // BOOST_REQUIRE_EQUAL(raster.num_dimensions(), 2);\n        // BOOST_REQUIRE_EQUAL(raster.shape()[0], nr_rows);\n        // BOOST_REQUIRE_EQUAL(raster.shape()[1], nr_cols);\n\n        // BOOST_CHECK(!raster.mask()[0][0]);\n        // BOOST_CHECK_EQUAL(raster[0][0], -22);\n\n        // BOOST_CHECK(!raster.mask()[0][1]);\n        // BOOST_CHECK_EQUAL(raster[0][1], -11);\n\n        // BOOST_CHECK(!raster.mask()[1][0]);\n        // BOOST_CHECK_EQUAL(raster[1][0],  0);\n\n        // BOOST_CHECK( raster.mask()[1][1]);\n\n        // BOOST_CHECK(!raster.mask()[2][0]);\n        // BOOST_CHECK_EQUAL(raster[2][0],  11);\n\n        // BOOST_CHECK(!raster.mask()[2][1]);\n        // BOOST_CHECK_EQUAL(raster[2][1],  22);\n    }\n}\n\n\nBOOST_AUTO_TEST_CASE(visit_vector)\n{\n    {\n        /// std::vector<int32_t> vector1({1, 2, 3, 4, 5});\n        /// fern::Array<int32_t> expression1(vector1);\n        /// using Result1 = decltype(expression1)::result_type;\n\n        /// std::vector<int32_t> vector2({10, 11, 12, 13, 14});\n        /// fern::Array<int32_t> expression2(vector2);\n        /// using Result2 = decltype(expression2)::result_type;\n\n        /// using Result3 = typename fern::Plus<Result1, Result2>::result_type;\n\n        /// fern::Operation<Result3> expression3(\n        ///     \"plus\",\n        ///     fern::Implementation(\n        ///         fern::Plus<Result1, Result2>()),\n        ///     {\n        ///         expression1,\n        ///         expression2\n        ///     }\n        /// );\n\n        // TODO How to create the resulting collection. Do it in the evaluate?\n        //      We need the type of the result and the extent(s) of the\n        //      input(s).\n\n        // fern::Data result(fern::evaluate(expression3));\n\n        // BOOST_REQUIRE_NO_THROW(boost::get<Result3>(result));\n        // BOOST_CHECK_EQUAL(boost::get<Result3>(result).collection,\n        //     std::vector<int32_t>({1, 2, 3, 4, 6}));\n    }\n}\n\n\n// BOOST_AUTO_TEST_CASE(visit_boost_multi_array)\n// {\n//     // 2 + 1\n//     {\n//         using Array = boost::multi_array<int32_t, 2>;\n//         // using Index = Array::index;\n//         auto extents(boost::extents[30000][40000]);\n// \n//         Array array1(extents);\n//         fern::Array<int32_t> expression1(array1);\n//         using Result1 = decltype(expression1)::result_type;\n// \n//         Array array2(extents);\n//         fern::Array<int32_t> expression2(array2);\n//         using Result2 = decltype(expression2)::result_type;\n// \n//         using Result3 = typename fern::Plus<Result1, Result2>::result_type;\n// \n//         fern::Operation<Result3> expression3(\n//             \"plus\",\n//             fern::Implementation(\n//                 fern::Plus<Result1, Result2>()),\n//             {\n//                 expression1,\n//                 expression2\n//             }\n//         );\n// \n//         // fern::Data result(fern::evaluate(expression3));\n// \n//         // BOOST_REQUIRE_NO_THROW(boost::get<Result3>(result));\n//         // BOOST_CHECK_EQUAL(boost::get<Result3>(result).value, 3);\n//     }\n// }\n", "meta": {"hexsha": "e95feb263980df3a74a3848f16e314e7941c4e0a", "size": 11005, "ext": "cc", "lang": "C++", "max_stars_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/fern/source/fern/expression_tree/test/evaluate_visitor_test.cc", "max_stars_repo_name": "quanpands/wflow", "max_stars_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/fern/source/fern/expression_tree/test/evaluate_visitor_test.cc", "max_issues_repo_name": "quanpands/wflow", "max_issues_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/fern/source/fern/expression_tree/test/evaluate_visitor_test.cc", "max_forks_repo_name": "quanpands/wflow", "max_forks_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.1909814324, "max_line_length": 82, "alphanum_fraction": 0.5576556111, "num_tokens": 2818, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435083355187, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4574458677818326}}
{"text": "#ifndef PYTHONIC_INCLUDE_NUMPY_SQUARE_HPP\n#define PYTHONIC_INCLUDE_NUMPY_SQUARE_HPP\n\n#include \"pythonic/include/types/numpy_op_helper.hpp\"\n#include \"pythonic/include/utils/meta.hpp\"\n#include \"pythonic/include/utils/numpy_traits.hpp\"\n#include \"pythonic/include/utils/functor.hpp\"\n\n#include <boost/simd/function/sqr.hpp>\n#include <complex>\n\n#ifdef USE_GMP\n#include \"pythonic/include/types/long.hpp\"\n#endif\n\nnamespace wrapper\n{\n}\n\nnamespace pythonic\n{\n\n  namespace numpy\n  {\n\n    namespace wrapper\n    {\n#ifdef USE_GMP\n      template <class T, class U>\n      auto square(__gmp_expr<T, U> const &a) -> decltype(a *a)\n      {\n        return a * a;\n      }\n#endif\n      template <class T>\n      std::complex<T> square(std::complex<T> const &arg)\n      {\n        return arg * arg;\n      }\n      template <class T>\n      auto square(T const &arg) -> decltype(boost::simd::sqr(arg))\n      {\n        return boost::simd::sqr(arg);\n      }\n    }\n\n#define NUMPY_NARY_FUNC_NAME square\n#define NUMPY_NARY_FUNC_SYM wrapper::square\n#include \"pythonic/include/types/numpy_nary_expr.hpp\"\n  }\n}\n\n#endif\n", "meta": {"hexsha": "f81e52bb88160515d0cacdd8a646c7da64607ceb", "size": 1083, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pythran/pythonic/include/numpy/square.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": "pythran/pythonic/include/numpy/square.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": "pythran/pythonic/include/numpy/square.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": 20.0555555556, "max_line_length": 66, "alphanum_fraction": 0.6795937211, "num_tokens": 273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435083355187, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4574458677818326}}
{"text": "/*\n@copyright Louis Dionne 2015\nDistributed under the Boost Software License, Version 1.0.\n(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n */\n\n#include <boost/hana/applicative.hpp>\n#include <boost/hana/assert.hpp>\n#include <boost/hana/comparable.hpp>\n#include <boost/hana/config.hpp>\n#include <boost/hana/foldable.hpp>\n#include <boost/hana/functional/curry.hpp>\n#include <boost/hana/functional/flip.hpp>\n#include <boost/hana/functional/partial.hpp>\n#include <boost/hana/functor.hpp>\n#include <boost/hana/monad.hpp>\n#include <boost/hana/sequence.hpp>\n#include <boost/hana/traversable.hpp>\n#include <boost/hana/tuple.hpp>\n\n#include <utility>\n\n\nstruct Tree;\n\ntemplate <typename X, typename Subforest>\nstruct node_type {\n    struct hana { using datatype = Tree; };\n    X value;\n    Subforest subforest;\n};\n\nauto forest = boost::hana::make_tuple;\n\nauto node = [](auto x, auto subforest) {\n    return node_type<decltype(x), decltype(subforest)>{x, subforest};\n};\n\nnamespace boost { namespace hana {\n    //////////////////////////////////////////////////////////////////////////\n    // Comparable\n    //////////////////////////////////////////////////////////////////////////\n    template <>\n    struct equal_impl<Tree, Tree> {\n        template <typename N1, typename N2>\n        static constexpr decltype(auto) apply(N1&& n1, N2&& n2) {\n            return and_(\n                equal(std::forward<N1>(n1).value, std::forward<N2>(n2).value),\n                equal(std::forward<N1>(n1).subforest, std::forward<N2>(n2).subforest)\n            );\n        }\n    };\n\n    //////////////////////////////////////////////////////////////////////////\n    // Functor\n    //////////////////////////////////////////////////////////////////////////\n    template <>\n    struct transform_impl<Tree> {\n        template <typename N, typename F>\n        static constexpr decltype(auto) apply(N&& n, F f) {\n            auto g = [=](auto&& subtree) -> decltype(auto) {\n                return transform(std::forward<decltype(subtree)>(subtree), f);\n            };\n            return node(\n                f(std::forward<N>(n).value),\n                transform(std::forward<N>(n).subforest, g)\n            );\n        }\n    };\n\n    //////////////////////////////////////////////////////////////////////////\n    // Applicative\n    //////////////////////////////////////////////////////////////////////////\n    template <>\n    struct lift_impl<Tree> {\n        template <typename X>\n        static constexpr decltype(auto) apply(X&& x)\n        { return node(std::forward<X>(x), forest()); }\n    };\n\n    template <>\n    struct ap_impl<Tree> {\n        template <typename F, typename X>\n        static constexpr decltype(auto) apply(F&& f, X&& x) {\n            return node(\n                f.value(x.value),\n                concat(\n                    transform(x.subforest, partial(flip(transform), f.value)),\n                    transform(f.subforest, partial(flip(ap), x))\n                )\n            );\n        }\n    };\n\n    //////////////////////////////////////////////////////////////////////////\n    // Monad\n    //////////////////////////////////////////////////////////////////////////\n    template <>\n    struct flatten_impl<Tree> {\n        template <typename N>\n        static constexpr decltype(auto) apply(N&& n) {\n            return node(\n                std::forward<N>(n).value.value,\n                concat(\n                    std::forward<N>(n).value.subforest,\n                    transform(std::forward<N>(n).subforest, flatten)\n                )\n            );\n        }\n    };\n\n    //////////////////////////////////////////////////////////////////////////\n    // Foldable\n    //////////////////////////////////////////////////////////////////////////\n    template <>\n    struct foldl_impl<Tree> {\n        template <typename N, typename S, typename F>\n        static constexpr decltype(auto) apply(N&& n, S&& s, F f) {\n            return foldl(\n                std::forward<N>(n).subforest,\n                f(std::forward<S>(s), std::forward<N>(n).value),\n                [=](auto&& state, auto&& subtree) -> decltype(auto) {\n                    return foldl(\n                        std::forward<decltype(subtree)>(subtree),\n                        std::forward<decltype(state)>(state),\n                        f\n                    );\n                }\n            );\n        }\n    };\n\n    template <>\n    struct foldr_impl<Tree> {\n        template <typename N, typename S, typename F>\n        static constexpr decltype(auto) apply(N&& n, S&& s, F f) {\n            return f(\n                std::forward<N>(n).value,\n                foldr(std::forward<N>(n).subforest, std::forward<S>(s),\n                    [=](auto&& subtree, auto&& state) -> decltype(auto) {\n                        return foldr(\n                            std::forward<decltype(subtree)>(subtree),\n                            std::forward<decltype(state)>(state),\n                            f\n                        );\n                    }\n                )\n            );\n        }\n    };\n\n    //////////////////////////////////////////////////////////////////////////\n    // Traversable\n    //////////////////////////////////////////////////////////////////////////\n    template <>\n    struct traverse_impl<Tree> {\n        template <typename A, typename N, typename F>\n        static constexpr decltype(auto) apply(N&& n, F&& f) {\n            return hana::ap(\n                hana::transform(f(std::forward<N>(n).value), curry<2>(node)),\n                traverse<A>(\n                    std::forward<N>(n).subforest,\n                    hana::partial(hana::flip(traverse<A>), f)\n                )\n            );\n        }\n    };\n}}\n\nint main() {\n    BOOST_HANA_CONSTEXPR_LAMBDA auto tree = node(1, forest(\n        node(2, forest()),\n        node(3, forest()),\n        node(4, forest())\n    ));\n\n    BOOST_HANA_CONSTEXPR_CHECK(boost::hana::sum(tree) == 10);\n}\n", "meta": {"hexsha": "fdc7dcdac4aa141e7af4ed065b109a7ec8145a34", "size": 5959, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/sandbox/tree.cpp", "max_stars_repo_name": "josephwinston/hana", "max_stars_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/sandbox/tree.cpp", "max_issues_repo_name": "josephwinston/hana", "max_issues_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/sandbox/tree.cpp", "max_forks_repo_name": "josephwinston/hana", "max_forks_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.2905027933, "max_line_length": 85, "alphanum_fraction": 0.4371538849, "num_tokens": 1178, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4574458553400487}}
{"text": "/*===================================================================\n\nMSI applications for interactive analysis in MITK (M2aia)\n\nCopyright (c) Jonas Cordes\n\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt for details.\n\n===================================================================*/\n\n#include \"mitkIOUtil.h\"\n#include <algorithm>\n#include <m2Normalization.h>\n#include <m2TestingConfig.h>\n#include <mitkTestFixture.h>\n#include <mitkTestingMacros.h>\n#include <numeric>\n#include <random>\n\n//#include <boost/algorithm/string.hpp>\n\nclass m2CalibrationTestSuite : public mitk::TestFixture\n{\n  CPPUNIT_TEST_SUITE(m2CalibrationTestSuite);\n  MITK_TEST(ApplyTIC_RandomGaussianSignal_shouldReturnTrue);\n\n  CPPUNIT_TEST_SUITE_END();\n\n  /*\n  Signal was generated once using the following procedure\n    -----\n  const double mean = 1.0;\n    const double stddev = 0.33;\n    std::default_random_engine generator;\n    generator.seed(142191);\n    std::normal_distribution<double> dist(mean, stddev);\n\n    std::vector<double> signal;\n    auto it = std::inserter(signal, std::begin(signal));\n    for (int i = 0; i < 1000; ++i)\n      it = dist(generator);\n    -----\n  */\n\nprivate:\n  std::vector<double> ReadDoubleVector(const std::string &fileNameInM2aiaDir, char delim = '\\n')\n  {\n    std::vector<double> signal;\n    std::ifstream f(GetTestDataFilePath(fileNameInM2aiaDir, M2AIA_DATA_DIR));\n    std::string line;\n    while (std::getline(f, line, delim))\n    {\n      signal.push_back(std::stod(line));\n    }\n    return signal;\n  }\n\n  template <class T>\n  void WriteVector(\n    const std::vector<T> & vec, const std::string &fileNameInM2aiaDir, char delim = '\\n', std::function<double(T &)> &func = [](T &t) {\n    return t; })\n  {\n    std::ofstream f(GetTestDataFilePath(fileNameInM2aiaDir, M2AIA_DATA_DIR));\n\n    for (int i = 0; i < vec.size(); i++)\n    {\n      f << std::setprecision(128) << vec[i];\n      if (i < vec.size() - 1)\n        f << delim;\n    }\n  }\n\npublic:\n  void ApplyTIC_RandomGaussianSignal_shouldReturnTrue()\n  {\n    /*{\n      std::ofstream f(GetTestDataFilePath(\"quadratic.data\", M2AIA_DATA_DIR));\n\n      for (int i = 0; i < 1000; i++)\n      {\n        f << std::setprecision(128) << -0.00012 * i * i + 0.32 * i + 800;\n        if (i < 1000 - 1)\n          f << \"\\n\";\n      }\n    }*/\n    std::vector<double> signal = ReadDoubleVector(\"signal.data\");\n    std::vector<double> mzs = ReadDoubleVector(\"quadratic.data\");\n    std::vector<double> expected = ReadDoubleVector(\"quadratic_tic_calibration.result\");\n\n    std::vector<double> result(signal.size());\n    double tic = m2::Signal::TotalIonCurrent(std::begin(mzs), std::end(mzs), std::begin(signal));\n    MITK_INFO << tic;\n    std::transform(std::begin(signal), std::end(signal), std::begin(result), [&tic](const auto &v) { return v / tic; });\n\n    CPPUNIT_ASSERT(std::equal(std::begin(result), std::end(result), std::begin(expected)));\n  }\n};\n\nMITK_TEST_SUITE_REGISTRATION(m2Calibration)\n", "meta": {"hexsha": "81c68eb2e9e387fefcb226e0f76796c8deca7809", "size": 3070, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Modules/M2aiaSignalProcessing/Testing/m2CalibrationTest.cpp", "max_stars_repo_name": "ivowolf/M2aia", "max_stars_repo_head_hexsha": "03cfe3495bc706cbb0b00a2916b8f0a3cb398e25", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2021-07-22T06:52:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T12:53:31.000Z", "max_issues_repo_path": "Modules/M2aiaSignalProcessing/Testing/m2CalibrationTest.cpp", "max_issues_repo_name": "ivowolf/M2aia", "max_issues_repo_head_hexsha": "03cfe3495bc706cbb0b00a2916b8f0a3cb398e25", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-07-25T22:29:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-22T13:21:30.000Z", "max_forks_repo_path": "Modules/M2aiaSignalProcessing/Testing/m2CalibrationTest.cpp", "max_forks_repo_name": "ivowolf/M2aia", "max_forks_repo_head_hexsha": "03cfe3495bc706cbb0b00a2916b8f0a3cb398e25", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-06-23T11:53:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-22T06:14:24.000Z", "avg_line_length": 28.9622641509, "max_line_length": 135, "alphanum_fraction": 0.6348534202, "num_tokens": 803, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672320414787, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.457381031020086}}
{"text": "#ifndef HELPER_FUNCTIONS_HPP_INCLUDED\n#define HELPER_FUNCTIONS_HPP_INCLUDED\n\n#include <iostream>\n#include <OpenMesh/Core/IO/MeshIO.hh>\n#include <OpenMesh/Core/Mesh/TriMesh_ArrayKernelT.hh>\n//#include <OpenMesh/Core/IO/reader/OBJReader.hh>\n//#include <OpenMesh/Core/IO/writer/OBJWriter.hh>\n#include <nanoflann.hpp>\n#include <Eigen/Dense>\n#include <Eigen/SparseCore>\n#include \"../global.hpp\"\n\ntypedef OpenMesh::TriMesh_ArrayKernelT<>  TriMesh;\ntypedef Eigen::SparseMatrix<float, 0, int> SparseMat;\ntypedef Eigen::Matrix< int, Eigen::Dynamic, Eigen::Dynamic> MatDynInt; //matrix MxN of type unsigned int\ntypedef Eigen::Matrix< int, Eigen::Dynamic, 3> FacesMat; //matrix Mx3 of type unsigned int\ntypedef Eigen::VectorXf VecDynFloat;\ntypedef Eigen::Matrix< float, Eigen::Dynamic, Eigen::Dynamic> MatDynFloat; //matrix MxN of type float\ntypedef Eigen::Matrix< float, Eigen::Dynamic, registration::NUM_FEATURES> FeatureMat; //matrix Mx6 of type float\ntypedef Eigen::MatrixX3f Vec3Mat;\n\nnamespace registration {\n\nvoid fuse_affinities(SparseMat &ioAffinity1,\n                    const SparseMat &inAffinity2);\n\nvoid normalize_sparse_matrix(SparseMat &ioMat);\n\ntemplate <typename VecMatType>\nvoid radius_nearest_neighbours(const VecMatType &inQueriedPoints,\n                                const VecMatType &inSourcePoints,\n                                MatDynInt &outNeighbourIndices,\n                                MatDynFloat &outNeighbourSquaredDistances,\n                                const float paramRadius = 3.0,\n                                const size_t paramLeafsize = 15);\n\n\n\n\n\n\nvoid convert_mesh_to_matrices(const TriMesh &inMesh,\n                                FeatureMat &outFeatures,\n                                FacesMat &outFaces);\n\nvoid convert_mesh_to_matrices(const TriMesh &inMesh,\n                                FeatureMat &outFeatures);\n\nvoid convert_mesh_to_matrices(const TriMesh &inMesh,\n                                FeatureMat &outFeatures,\n                                FacesMat &outFaces,\n                                VecDynFloat &outFlags);\n\nvoid convert_matrices_to_mesh(const Vec3Mat &inPositions,\n                                const FacesMat &inFaces,\n                                TriMesh &outMesh);\n\nvoid convert_matrices_to_mesh(const FeatureMat &inFeatures,\n                                const FacesMat &inFaces,\n                                TriMesh &outMesh);\n\nvoid convert_matrices_to_mesh(const FeatureMat &inFeatures,\n                                const FacesMat &inFaces,\n                                const VecDynFloat &inFlags,\n                                TriMesh &outMesh);\n\n\n//void load_obj_to_eigen(const std::string inObjFilename,\n//                                TriMesh &outMesh,\n//                                FeatureMat &outFeatureMatrix);\n\n\n//void write_eigen_to_obj(const FeatureMat &inFeatures,\n//                                TriMesh &inMesh,\n//                                const std::string inObjFilename);\n\n//bool import_data(const std::string inFloatingMeshPath,\n//                 const std::string inTargetMeshPath,\n//                 FeatureMat &outFloatingFeatures,\n//                 FeatureMat &outTargetFeatures,\n//                 FacesMat &outFloatingFaces,\n//                 FacesMat &outTargetFaces);\n\n//bool export_data(FeatureMat &inResultFeatures,\n//                 FacesMat &inResultFaces,\n//                 const std::string inResultMeshPath);\n\n\nvoid update_normals_for_altered_positions(TriMesh &ioMesh,\n                                        FeatureMat &ioFeatures);\n\nvoid update_normals_for_altered_positions(const Vec3Mat &inPositions,\n                                        const FacesMat &inFaces,\n                                        Vec3Mat &outNormals);\n\nvoid update_normals_safely(const FeatureMat &features, TriMesh &mesh);\n\n}//namespace registration\n#endif // HELPER_FUNCTIONS_HPP_INCLUDED\n", "meta": {"hexsha": "92717df59ca9edcb71b9458076a57ddfea37e23b", "size": 3922, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/helper_functions.hpp", "max_stars_repo_name": "brisyramshere/meshmonk", "max_stars_repo_head_hexsha": "a0a7cf79902541cf9c800d83a4d4f14fcd756f6f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 53.0, "max_stars_repo_stars_event_min_datetime": "2017-02-03T14:59:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T05:40:58.000Z", "max_issues_repo_path": "src/helper_functions.hpp", "max_issues_repo_name": "brisyramshere/meshmonk", "max_issues_repo_head_hexsha": "a0a7cf79902541cf9c800d83a4d4f14fcd756f6f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 16.0, "max_issues_repo_issues_event_min_datetime": "2018-07-16T10:34:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-18T04:37:12.000Z", "max_forks_repo_path": "src/helper_functions.hpp", "max_forks_repo_name": "brisyramshere/meshmonk", "max_forks_repo_head_hexsha": "a0a7cf79902541cf9c800d83a4d4f14fcd756f6f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 23.0, "max_forks_repo_forks_event_min_datetime": "2018-07-05T14:59:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T07:01:47.000Z", "avg_line_length": 38.8316831683, "max_line_length": 112, "alphanum_fraction": 0.6093829679, "num_tokens": 788, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.45738102055513036}}
{"text": "#pragma once\n\n#include <armadillo>\n#include <algorithm>\n#include <random>\n#include <cassert>\n\n#include \"net.hpp\"\n\ntemplate <typename activation = Logistic, typename error = Squared_Error>\nvoid train_online(FeedForward_Network<activation, error>& network,\n    arma::Mat<float> inputs, arma::Mat<float> targets, float learning_rate) {\n    for (int i = 0; i < targets.n_rows; ++i) {\n      calculate_activation(network, inputs.row(i));\n      backprop(network, targets.row(i), learning_rate);\n    }\n}\n\ntemplate <typename activation, typename error>\nvoid train_batch(FeedForward_Network<activation, error>& network,\n    arma::Mat<float> inputs, arma::Mat<float> targets, int batch_size, float learning_rate) {\n    network.resize_activation(batch_size);\n\n    int batches_in_train = targets.n_rows/batch_size - 1;\n    for (int i = 0; i < batches_in_train; ++i) {\n      arma::Mat<float> input_slice = inputs.rows(i*batch_size, (i+1) * batch_size-1);\n      calculate_activation(network, input_slice);\n      arma::Mat<float> target_slice = targets.rows(i*batch_size, (i+1) * batch_size-1);\n      backprop(network, target_slice, learning_rate);\n    }\n}\n\n//Randomize weights in a network.\ntemplate <typename activation, typename error>\nvoid randomize(FeedForward_Network<activation, error>& network, float standard_deviation = 0.05) {\n  std::default_random_engine generator;\n  std::normal_distribution<float> distribution(0, standard_deviation);\n\n  auto random_num = [&]() {return distribution(generator);};\n  for (int i=0; i < network.weights.size(); ++i) {\n    network.weights[i].imbue(random_num);\n    //TODO figure out which one is right\n    //avoid local nearby local maximum\n    network.last_weights[i].imbue(random_num);\n    //network.last_weights[i] = network.weights[i];\n  }\n}\n\ntemplate <typename arma_t, typename activation, typename error>\nvoid backprop(FeedForward_Network<activation, error> &network,\n    arma_t target, float learning_rate = 0.8f, float momentum = 0.8f) {\n  //Calculate deltas\n\n  //output delta first\n  network.deltas.back() = error::error_dir(target, network.activations.back()) % activation::activation_dir(network.activations.back());\n\n  //rest of the delta\n  for (int i = network.deltas.size() - 2; i >= 0; --i) {\n    network.deltas[i] = (network.deltas[i+1] * network.weights[i+1].t()) % activation::activation_dir(network.activations[i+1]);\n  }\n\n  //update weights\n  for (int i=0; i < network.weights.size(); ++i) {\n    auto & standard_piece = (1 - momentum) * learning_rate * (network.deltas[i].t() * network.activations[i]).t();\n    auto & momentum_piece = momentum * (network.weights[i] - network.last_weights[i]);\n    arma::Mat<float> delta_weights = standard_piece + momentum_piece;\n    network.last_weights[i] = network.weights[i];\n    network.weights[i] += delta_weights;\n  }\n}\n\ntemplate <typename arma_t, typename activation, typename error>\nvoid calculate_activation(FeedForward_Network<activation, error>& network,\n    arma_t input) {\n\n  network.activations[0] = input;\n  for(int i=1; i < network.activations.size(); ++i) {\n    network.activations[i] = network.activations[i-1] * network.weights[i-1];\n    network.activations[i] = activation::activation(network.activations[i]);\n  }\n}\n\n//TODO remove this function??\ntemplate <typename activation, typename error>\narma::Mat<float> predict(FeedForward_Network<activation, error>& network,\n    arma::Mat<float> input) {\n  calculate_activation(network, input);\n  return network.activations.back();\n}\n\n//Scoring function for classification.\ninline double classify_percent_score(arma::Mat<float> result, arma::Mat<float> correct) {\n  assert(result.n_cols == correct.n_cols);\n  int num_correct = 0;\n  for (int i=0; i < result.n_rows; ++i) {\n    auto sort_vec = arma::sort_index(result.row(i), 1);\n    if (correct.row(i)[sort_vec[0]] == 1) {\n      num_correct += 1;\n    }\n  }\n  return static_cast<float>(num_correct) / static_cast<float>(result.n_rows);\n}\n\n//Scoring function that calculates the difference in squares between two matrices.\ninline float squared_diff(arma::Mat<float> result, arma::Mat<float> correct) {\n  assert(result.n_cols == correct.n_cols);\n  auto error_diff = correct - result;\n  return arma::accu(error_diff % error_diff);\n}\n", "meta": {"hexsha": "81d3b714f95fec202959903850ef3023ee2924f7", "size": 4223, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/net_cpu.hpp", "max_stars_repo_name": "lukemetz/Neural-Net-Experiments", "max_stars_repo_head_hexsha": "c50e93ec2f0e4acac2db7815174af71cf191420f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28.0, "max_stars_repo_stars_event_min_datetime": "2015-02-24T17:17:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-05T09:46:37.000Z", "max_issues_repo_path": "src/net_cpu.hpp", "max_issues_repo_name": "lukemetz/Neural-Net-Experiments", "max_issues_repo_head_hexsha": "c50e93ec2f0e4acac2db7815174af71cf191420f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-04-09T00:41:28.000Z", "max_issues_repo_issues_event_max_datetime": "2015-04-09T00:41:28.000Z", "max_forks_repo_path": "src/net_cpu.hpp", "max_forks_repo_name": "lukemetz/Neural-Net-Experiments", "max_forks_repo_head_hexsha": "c50e93ec2f0e4acac2db7815174af71cf191420f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2015-03-29T15:24:29.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-11T07:45:41.000Z", "avg_line_length": 38.3909090909, "max_line_length": 136, "alphanum_fraction": 0.7130002368, "num_tokens": 1055, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527631, "lm_q2_score": 0.5660185351961013, "lm_q1q2_score": 0.4573810205551302}}
{"text": "//\n// Created by yalavrinenko on 18.06.2021.\n//\n\n#ifndef TRASH_ROGAINE_SOLVER_FULL_LINKED_GRAPH_HPP\n#define TRASH_ROGAINE_SOLVER_FULL_LINKED_GRAPH_HPP\n\n#include <array>\n#include <boost/graph/astar_search.hpp>\n#include <boost/graph/grid_graph.hpp>\n#include <boost/functional/hash.hpp>\n#include <opencv2/opencv.hpp>\n#include <tuple>\n#include <utility>\n\nnamespace trs{\n  class full_linked_grid {\n  public:\n    using vertex_t = std::array<size_t, 2>;\n    using edge_t = std::pair<vertex_t, vertex_t>;\n\n    struct target_visitor : public boost::default_astar_visitor {\n      struct target_reached {\n      };\n\n      explicit target_visitor(vertex_t to) : target_{std::move(to)} {}\n\n      void examine_vertex(vertex_t u, const full_linked_grid &) {\n        if (u == target_)\n          throw target_visitor::target_reached();\n      }\n\n    private:\n      vertex_t target_;\n    };\n    using visitor_t = target_visitor;\n\n    struct graph_vertex_hash {\n      size_t operator()(vertex_t const &u) const {\n        size_t hash = 0;\n        boost::hash_combine(hash, u[0]);\n        boost::hash_combine(hash, u[1]);\n        return hash;\n      }\n    };\n    using hash_t = graph_vertex_hash;\n\n    explicit full_linked_grid(cv::Mat  mat): road_map_(std::move(mat)) {}\n\n    [[nodiscard]] bool check_vertex(vertex_t const& v) const {\n      return v[0] < static_cast<size_t>(road_map_.rows) && v[1] < static_cast<size_t>(road_map_.cols) &&\n             road_map_.at<char>(static_cast<int>(v[0]), static_cast<int>(v[1]));\n    }\n\n    struct edge_iterator : public boost::iterator_facade<edge_iterator, edge_t, boost::forward_traversal_tag, edge_t>{\n      edge_iterator(vertex_t vertex, full_linked_grid const &graph): graph_{graph}, current_(vertex){\n        next_ = next_vertex();\n      }\n\n      edge_t operator* () const {\n        return {current_, next_};\n      }\n\n      bool operator == (edge_iterator const& rhs) const {\n        return current_ == rhs.current_ && next_ == rhs.next_;\n      }\n\n      bool operator != (edge_iterator const& rhs) const {\n        return !(*this == rhs);\n      }\n\n      [[nodiscard]] bool equal(edge_iterator const& rhs) const {\n        return this->operator==(rhs);\n      }\n\n      void operator++ () {\n        next_ = next_vertex();\n      }\n\n      explicit operator bool() const {\n        return has_vertex_;\n      }\n\n      void increment() {\n        ++(*this);\n      }\n\n    private:\n      vertex_t next_vertex() {\n        has_vertex_ = false;\n        next_ = current_;\n        while (!has_vertex_ && current_shift_ < shifts_.size()){\n          next_[0] = current_[0] + shifts_[current_shift_].first;\n          next_[1] = current_[1] + shifts_[current_shift_].second;\n          ++current_shift_;\n\n          if (graph_.check_vertex(next_))\n            has_vertex_ = true;\n        }\n        return next_;\n      }\n\n      size_t current_shift_ = 0;\n      bool has_vertex_;\n      full_linked_grid const &graph_;\n      vertex_t current_;\n      vertex_t next_;\n\n      std::array<std::pair<int, int>, 8> shifts_ = {\n          std::pair{-1, 1}, {0, 1}, {1, 1},\n          {-1, 0}, {1, 0},\n          {-1, -1}, {0, -1}, {1, -1}\n      };\n    };\n\n    [[nodiscard]] auto& graph() const{\n      return *this;\n    }\n\n    static visitor_t visitor(vertex_t const& v) {\n      return target_visitor(v);\n    }\n\n    static vertex_t vertex2d(size_t row, size_t col) {\n      return vertex_t {row, col};\n    }\n\n  private:\n    cv::Mat road_map_;\n  };\n\n  template<>\n  struct rogain_graph_traits<full_linked_grid>{\n    using graph_t = full_linked_grid;\n    using vertex_t = typename full_linked_grid::vertex_t;\n    using visitor_t = typename full_linked_grid::visitor_t;\n    using hash_t = typename full_linked_grid::hash_t;\n    using stop_exception_t = full_linked_grid::visitor_t::target_reached;\n  };\n\n  template<>\n  struct vertex_accessor<rogain_graph_traits<full_linked_grid>::vertex_t> {\n    static size_t field(rogain_graph_traits<full_linked_grid>::vertex_t const& v, size_t id) {\n      return v[id];\n    }\n  };\n}\n\nnamespace boost{\n  template<>\n  struct graph_traits<trs::full_linked_grid>{\n    using vertex_descriptor = trs::full_linked_grid::vertex_t;\n    using edge_descriptor = trs::full_linked_grid::edge_t;\n    using directed_category = boost::undirected_tag;\n    using edge_parallel_category = boost::disallow_parallel_edge_tag;\n    using traversal_category = boost::incidence_graph_tag;\n\n    using out_edge_iterator = trs::full_linked_grid::edge_iterator;\n    using degree_size_type = size_t;\n    using edges_size_type = size_t;\n  };\n}\n\n#endif//TRASH_ROGAINE_SOLVER_FULL_LINKED_GRAPH_HPP\n", "meta": {"hexsha": "371452ab4cf6f76fdcccd632a374579dc1648999", "size": 4583, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/pathfinders/boost_graph/full_linked_graph.hpp", "max_stars_repo_name": "yalavrinenko/trash_rogaine_solver", "max_stars_repo_head_hexsha": "88833935419ea340a9e51722da4b4907a502ea38", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/pathfinders/boost_graph/full_linked_graph.hpp", "max_issues_repo_name": "yalavrinenko/trash_rogaine_solver", "max_issues_repo_head_hexsha": "88833935419ea340a9e51722da4b4907a502ea38", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pathfinders/boost_graph/full_linked_graph.hpp", "max_forks_repo_name": "yalavrinenko/trash_rogaine_solver", "max_forks_repo_head_hexsha": "88833935419ea340a9e51722da4b4907a502ea38", "max_forks_repo_licenses": ["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.7757575758, "max_line_length": 118, "alphanum_fraction": 0.6432467816, "num_tokens": 1143, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672043084051, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4573810153226523}}
{"text": "#ifndef PYTHONIC_INCLUDE_NUMPY_EXP_HPP\n#define PYTHONIC_INCLUDE_NUMPY_EXP_HPP\n\n#include \"pythonic/include/utils/functor.hpp\"\n#include \"pythonic/include/types/ndarray.hpp\"\n#include \"pythonic/include/utils/numpy_traits.hpp\"\n\n#include <boost/simd/function/exp.hpp>\n#include <cmath>\n\nPYTHONIC_NS_BEGIN\n\nnamespace numpy\n{\n  namespace wrapper\n  {\n    template <class T>\n    std::complex<T> exp(std::complex<T> const &val)\n    {\n      return std::exp(val);\n    }\n    template <class T>\n    auto exp(T const &val) -> decltype(boost::simd::exp(val))\n    {\n      return boost::simd::exp(val);\n    }\n  }\n#define NUMPY_NARY_FUNC_NAME exp\n#define NUMPY_NARY_FUNC_SYM wrapper::exp\n#include \"pythonic/include/types/numpy_nary_expr.hpp\"\n}\nPYTHONIC_NS_END\n\n#endif\n", "meta": {"hexsha": "7c4a0729dfe56653f6152d83368075402d388625", "size": 747, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pythran/pythonic/include/numpy/exp.hpp", "max_stars_repo_name": "SylvainCorlay/pythran", "max_stars_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-03-24T00:33:03.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-24T00:33:03.000Z", "max_issues_repo_path": "pythran/pythonic/include/numpy/exp.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": "pythran/pythonic/include/numpy/exp.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_forks_repo_licenses": ["BSD-3-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.3428571429, "max_line_length": 61, "alphanum_fraction": 0.7255689424, "num_tokens": 191, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.808067204308405, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.45738101532265224}}
{"text": "// -------------------------------------------------------------------------------------------------\n//                              Copyright 2016 - NumScale SAS\n//\n//                   Distributed under the Boost Software License, Version 1.0.\n//                        See accompanying file LICENSE.txt or copy at\n//                            http://www.boost.org/LICENSE_1_0.txt\n// -------------------------------------------------------------------------------------------------\n\n#include <ns.bench.hpp>\n#include <boost/simd/function/simd/is_nlt.hpp>\n#include <cmath>\n\nnamespace bs = boost::simd;\nnamespace nsb = ns::bench;\n\ntemplate <typename T>\nstruct is_nlt_simd\n{\n   template <typename U>\n   void operator()(U min0, U max0, U min1, U max1)\n   {\n         { return bs::is_nlt(x0, x1); }\n       );\n   }\n};\n\n\nint main(int argc, char **argv) {\n   nsb::parse_args(argc, argv);\n   nsb::make_for_each<is_nlt_simd, NS_BENCH_SIGNED_NUMERIC_TYPES>( -10,  10,  -10,  10);\n   nsb::make_for_each<is_nlt_simd, NS_BENCH_UNSIGNED_NUMERIC_TYPES>(0,  10, 0,  10);\n   return 0;\n}\n\n", "meta": {"hexsha": "3c7b7d3f718fa781829288313e41f49732b5f346", "size": 1071, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bench/function/scalar/is_nlt.cpp", "max_stars_repo_name": "nickporubsky/boost-simd-clone", "max_stars_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_stars_repo_licenses": ["BSL-1.0"], "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": "bench/function/scalar/is_nlt.cpp", "max_issues_repo_name": "nickporubsky/boost-simd-clone", "max_issues_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "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": "bench/function/scalar/is_nlt.cpp", "max_forks_repo_name": "nickporubsky/boost-simd-clone", "max_forks_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_forks_repo_licenses": ["BSL-1.0"], "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": 30.6, "max_line_length": 100, "alphanum_fraction": 0.487394958, "num_tokens": 255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.6477982247516796, "lm_q1q2_score": 0.45720628808913066}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// Unit Test\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// This file was modified by Oracle on 2014.\n// Modifications copyright (c) 2014 Oracle and/or its affiliates.\n\n// Contributed and/or modified by 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\n#include <geometry_test_common.hpp>\n\n#include <boost/concept_check.hpp>\n\n#include <boost/geometry/strategies/geographic/distance_vincenty.hpp>\n#include <boost/geometry/algorithms/detail/vincenty_inverse.hpp>\n#include <boost/geometry/algorithms/detail/vincenty_direct.hpp>\n\n#include <boost/geometry/core/srs.hpp>\n#include <boost/geometry/strategies/strategies.hpp>\n#include <boost/geometry/algorithms/assign.hpp>\n#include <boost/geometry/geometries/point.hpp>\n#include <test_common/test_point.hpp>\n\n#ifdef HAVE_TTMATH\n#  include <boost/geometry/extensions/contrib/ttmath_stub.hpp>\n#endif\n\ntemplate <typename T>\nvoid normalize_deg(T & deg)\n{\n    while ( deg > T(180) )\n        deg -= T(360);\n    while ( deg <= T(-180) )\n        deg += T(360);\n}\n\ntemplate <typename T>\nT difference_deg(T const& a1, T const& a2)\n{\n    T d = a1 - a2;\n    normalize_deg(d);\n    return d;\n}\n\ntemplate <typename T>\nvoid check_deg(std::string const& name, T const& a1, T const& a2, T const& percent, T const& error)\n{\n    T diff = bg::math::abs(difference_deg(a1, a2));\n    \n    if ( bg::math::equals(a1, T(0)) || bg::math::equals(a2, T(0)) )\n    {\n        if ( diff > error )\n        {\n            BOOST_ERROR(name << \" - the difference {\" << diff << \"} between {\" << a1 << \"} and {\" << a2 << \"} exceeds {\" << error << \"}\");\n        }\n    }\n    else\n    {\n        T greater = (std::max)(bg::math::abs(a1), bg::math::abs(a2));\n\n        if ( diff > greater * percent / T(100) )\n        {\n            BOOST_ERROR(name << \" the difference {\" << diff << \"} between {\" << a1 << \"} and {\" << a2 << \"} exceeds {\" << percent << \"}%\");\n        }\n    }\n}\n\ndouble azimuth(double deg, double min, double sec)\n{\n    min = fabs(min);\n    sec = fabs(sec);\n\n    if ( deg < 0 )\n    {\n        min = -min;\n        sec = -sec;\n    }\n\n    return deg + min/60.0 + sec/3600.0;\n}\n\ndouble azimuth(double deg, double min)\n{\n    return azimuth(deg, min, 0.0);\n}\n\ntemplate <typename P>\nbool non_precise_ct()\n{\n    typedef typename bg::coordinate_type<P>::type ct;\n    return boost::is_integral<ct>::value || boost::is_float<ct>::value;\n}\n\ntemplate <typename P1, typename P2, typename Spheroid>\nvoid test_vincenty(double lon1, double lat1, double lon2, double lat2,\n                   double expected_distance,\n                   double expected_azimuth_12,\n                   double expected_azimuth_21,\n                   Spheroid const& spheroid)\n{\n    typedef typename bg::promote_floating_point\n        <\n            typename bg::select_calculation_type<P1, P2, void>::type\n        >::type calc_t;\n\n    calc_t tolerance = non_precise_ct<P1>() || non_precise_ct<P2>() ?\n                       5.0 : 0.001;\n    calc_t error = non_precise_ct<P1>() || non_precise_ct<P2>() ?\n                   1e-5 : 1e-12;\n\n    // formula\n    {\n        bg::detail::vincenty_inverse<calc_t> vi(lon1 * bg::math::d2r,\n                                                lat1 * bg::math::d2r,\n                                                lon2 * bg::math::d2r,\n                                                lat2 * bg::math::d2r,\n                                                spheroid);\n        calc_t dist = vi.distance();\n        calc_t az12 = vi.azimuth12();\n        calc_t az21 = vi.azimuth21();\n\n        calc_t az12_deg = az12 * bg::math::r2d;\n        calc_t az21_deg = az21 * bg::math::r2d;\n        \n        BOOST_CHECK_CLOSE(dist, calc_t(expected_distance), tolerance);\n        check_deg(\"az12_deg\", az12_deg, calc_t(expected_azimuth_12), tolerance, error);\n        check_deg(\"az21_deg\", az21_deg, calc_t(expected_azimuth_21), tolerance, error);\n\n        bg::detail::vincenty_direct<calc_t> vd(lon1 * bg::math::d2r,\n                                               lat1 * bg::math::d2r,\n                                               dist,\n                                               az12,\n                                               spheroid);\n        calc_t direct_lon2 = vd.lon2();\n        calc_t direct_lat2 = vd.lat2();\n        calc_t direct_az21 = vd.azimuth21();\n\n        calc_t direct_lon2_deg = direct_lon2 * bg::math::r2d;\n        calc_t direct_lat2_deg = direct_lat2 * bg::math::r2d;\n        calc_t direct_az21_deg = direct_az21 * bg::math::r2d;\n        \n        check_deg(\"direct_lon2_deg\", direct_lon2_deg, calc_t(lon2), tolerance, error);\n        check_deg(\"direct_lat2_deg\", direct_lat2_deg, calc_t(lat2), tolerance, error);\n        check_deg(\"direct_az21_deg\", direct_az21_deg, az21_deg, tolerance, error);\n    }\n\n    // strategy\n    {\n        typedef bg::strategy::distance::vincenty<Spheroid> vincenty_type;\n\n        BOOST_CONCEPT_ASSERT(\n            (\n                bg::concept::PointDistanceStrategy<vincenty_type, P1, P2>)\n            );\n\n        vincenty_type vincenty(spheroid);\n        typedef typename bg::strategy::distance::services::return_type<vincenty_type, P1, P2>::type return_type;\n\n        P1 p1;\n        P2 p2;\n\n        bg::assign_values(p1, lon1, lat1);\n        bg::assign_values(p2, lon2, lat2);\n        \n        BOOST_CHECK_CLOSE(vincenty.apply(p1, p2), return_type(expected_distance), tolerance);\n        BOOST_CHECK_CLOSE(bg::distance(p1, p2, vincenty), return_type(expected_distance), tolerance);\n    }\n}\n\ntemplate <typename P1, typename P2>\nvoid test_vincenty(double lon1, double lat1, double lon2, double lat2,\n                   double expected_distance,\n                   double expected_azimuth_12,\n                   double expected_azimuth_21)\n{\n    test_vincenty<P1, P2>(lon1, lat1, lon2, lat2,\n                          expected_distance, expected_azimuth_12, expected_azimuth_21,\n                          bg::srs::spheroid<double>());\n}\n\ntemplate <typename P1, typename P2>\nvoid test_all()\n{\n    // See:\n    //  - http://www.ga.gov.au/geodesy/datums/vincenty_inverse.jsp\n    //  - http://www.ga.gov.au/geodesy/datums/vincenty_direct.jsp\n    // Values in the comments below was calculated using the above pages\n    // in some cases distances may be different, previously used values was left\n\n    // use km\n    double gda_a = 6378.1370;\n    double gda_f = 1.0 / 298.25722210;\n    double gda_b = gda_a * ( 1.0 - gda_f );\n    bg::srs::spheroid<double> gda_spheroid(gda_a, gda_b);\n\n    // Test fractional coordinates only for non-integral types\n    if ( BOOST_GEOMETRY_CONDITION(\n            ! boost::is_integral<typename bg::coordinate_type<P1>::type>::value\n         && ! boost::is_integral<typename bg::coordinate_type<P2>::type>::value  ) )\n    {\n        // Flinders Peak -> Buninyong\n        test_vincenty<P1, P2>(azimuth(144,25,29.52440), azimuth(-37,57,3.72030),\n                              azimuth(143,55,35.38390), azimuth(-37,39,10.15610),\n                              54.972271, azimuth(306,52,5.37), azimuth(127,10,25.07),\n                              gda_spheroid);\n    }\n\n    // Lodz -> Trondheim\n    test_vincenty<P1, P2>(azimuth(19,28), azimuth(51,47),\n                          azimuth(10,21), azimuth(63,23),\n                          1399.032724, azimuth(340,54,25.14), azimuth(153,10,0.19),\n                          gda_spheroid);\n    // London -> New York\n    test_vincenty<P1, P2>(azimuth(0,7,39), azimuth(51,30,26),\n                          azimuth(-74,0,21), azimuth(40,42,46),\n                          5602.044851, azimuth(288,31,36.82), azimuth(51,10,33.43),\n                          gda_spheroid);\n\n    // Shanghai -> San Francisco\n    test_vincenty<P1, P2>(azimuth(121,30), azimuth(31,12),\n                          azimuth(-122,25), azimuth(37,47),\n                          9899.698550, azimuth(45,12,44.76), azimuth(309,50,20.88),\n                          gda_spheroid);\n\n    test_vincenty<P1, P2>(0, 0, 0, 50, 5540.847042, 0, 180, gda_spheroid); // N\n    test_vincenty<P1, P2>(0, 0, 0, -50, 5540.847042, 180, 0, gda_spheroid); // S\n    test_vincenty<P1, P2>(0, 0, 50, 0, \t5565.974540, 90, -90, gda_spheroid); // E\n    test_vincenty<P1, P2>(0, 0, -50, 0, 5565.974540, -90, 90, gda_spheroid); // W\n    \n    test_vincenty<P1, P2>(0, 0, 50, 50, 7284.879297, azimuth(32,51,55.87), azimuth(237,24,50.12), gda_spheroid); // NE\n    \n    // The original distance values, azimuths calculated using the web form mentioned above\n    // Using default spheroid units (meters)\n    test_vincenty<P1, P2>(0, 89, 1, 80, 1005153.5769, azimuth(178,53,23.85), azimuth(359,53,18.35)); // sub-polar\n    test_vincenty<P1, P2>(4, 52, 4, 52, 0.0, 0, 0); // no point difference\n    test_vincenty<P1, P2>(4, 52, 3, 40, 1336039.890, azimuth(183,41,29.08), azimuth(2,58,5.13)); // normal case\n}\n\ntemplate <typename P>\nvoid test_all()\n{\n    test_all<P, P>();\n}\n\nint test_main(int, char* [])\n{\n    //test_all<float[2]>();\n    //test_all<double[2]>();\n    test_all<bg::model::point<double, 2, bg::cs::geographic<bg::degree> > >();\n    test_all<bg::model::point<float, 2, bg::cs::geographic<bg::degree> > >();\n    test_all<bg::model::point<int, 2, bg::cs::geographic<bg::degree> > >();\n\n#if defined(HAVE_TTMATH)\n    test_all<bg::model::point<ttmath::Big<1,4>, 2, bg::cs::geographic<bg::degree> > >();\n    test_all<bg::model::point<ttmath_big, 2, bg::cs::geographic<bg::degree> > >();\n#endif\n\n\n    return 0;\n}\n", "meta": {"hexsha": "b80da4bb52ae06c9c8a0ecbf9f82fd3faeccecc7", "size": 9886, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/test/strategies/vincenty.cpp", "max_stars_repo_name": "lilinj2000/boost_1_58_0", "max_stars_repo_head_hexsha": "21edb36c6ad359027f23fb4dd1536ed6e9cf911b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-04-26T22:34:42.000Z", "max_stars_repo_stars_event_max_datetime": "2015-10-22T17:03:48.000Z", "max_issues_repo_path": "libs/geometry/test/strategies/vincenty.cpp", "max_issues_repo_name": "lilinj2000/boost_1_58_0", "max_issues_repo_head_hexsha": "21edb36c6ad359027f23fb4dd1536ed6e9cf911b", "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/geometry/test/strategies/vincenty.cpp", "max_forks_repo_name": "lilinj2000/boost_1_58_0", "max_forks_repo_head_hexsha": "21edb36c6ad359027f23fb4dd1536ed6e9cf911b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-05-05T04:32:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-13T15:06:24.000Z", "avg_line_length": 36.3455882353, "max_line_length": 139, "alphanum_fraction": 0.5894193809, "num_tokens": 2897, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.705785040214066, "lm_q2_score": 0.647798211152541, "lm_q1q2_score": 0.45720628650889616}}
{"text": "#ifndef CIRCLE_DETECTION_INCLUDE_GAURD\n#define CIRCLE_DETECTION_INCLUDE_GAURD\n#include <Eigen/Dense>\n#include <vector>\n#include \"rigid2d/rigid2d.hpp\"\n\nusing std::vector;\nusing Eigen::Vector3d;\nusing rigid2d::Vector2D;\n\nnamespace circleDetection\n{\nstruct Point2d\n{\n  Point2d(double x, double y);\n  double x, y;\n};\n\n\nVector3d fitCircle(vector<Vector2D> circlePoints);\ndouble calculateError(const vector<Vector2D>& observedPoints, Vector3d circleCoeff);\n}\n\n\n\n#endif\n", "meta": {"hexsha": "c03baa0d34d0f1bae8d38cf7a6df2857c3811fad", "size": 463, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "nuslam/include/nuslam/circle_detection.hpp", "max_stars_repo_name": "nithin-gunamgari/turtlebot_slam", "max_stars_repo_head_hexsha": "4e755dc2c055b59a058d890f0cdb9a099e1a1a82", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "nuslam/include/nuslam/circle_detection.hpp", "max_issues_repo_name": "nithin-gunamgari/turtlebot_slam", "max_issues_repo_head_hexsha": "4e755dc2c055b59a058d890f0cdb9a099e1a1a82", "max_issues_repo_licenses": ["MIT"], "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/circle_detection.hpp", "max_forks_repo_name": "nithin-gunamgari/turtlebot_slam", "max_forks_repo_head_hexsha": "4e755dc2c055b59a058d890f0cdb9a099e1a1a82", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.1481481481, "max_line_length": 84, "alphanum_fraction": 0.7861771058, "num_tokens": 127, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.4572062832900965}}
{"text": "//=======================================================================\n// Copyright 2007 Aaron Windsor\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n#include <iostream>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/properties.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <boost/ref.hpp>\n#include <vector>\n\n#include <boost/graph/biconnected_components.hpp>\n#include <boost/graph/make_biconnected_planar.hpp>\n#include <boost/graph/boyer_myrvold_planar_test.hpp>\n\n\nusing namespace boost;\n\nint main(int argc, char** argv)\n{\n  \n  typedef adjacency_list\n    < vecS,\n      vecS,\n      undirectedS,\n      property<vertex_index_t, int>,\n      property<edge_index_t, int>\n    > \n    graph;\n\n  graph g(11);\n  add_edge(0,1,g);\n  add_edge(2,3,g);\n  add_edge(3,0,g);\n  add_edge(3,4,g);\n  add_edge(4,5,g);\n  add_edge(5,3,g);\n  add_edge(5,6,g);\n  add_edge(6,7,g);\n  add_edge(7,8,g);\n  add_edge(8,5,g);\n  add_edge(8,9,g);\n  add_edge(0,10,g);\n\n\n  //Initialize the interior edge index\n  property_map<graph, edge_index_t>::type e_index = get(edge_index, g);\n  graph_traits<graph>::edges_size_type edge_count = 0;\n  graph_traits<graph>::edge_iterator ei, ei_end;\n  for(tie(ei, ei_end) = edges(g); ei != ei_end; ++ei)\n    put(e_index, *ei, edge_count++);\n  \n  \n  //Test for planarity; compute the planar embedding as a side-effect\n  typedef std::vector< graph_traits<graph>::edge_descriptor > vec_t;\n  std::vector<vec_t> embedding(num_vertices(g));\n  if (boyer_myrvold_planarity_test(boyer_myrvold_params::graph = g,\n                                   boyer_myrvold_params::embedding = \n                                     &embedding[0]\n                                   )\n      )\n    std::cout << \"Input graph is planar\" << std::endl;\n  else\n    std::cout << \"Input graph is not planar\" << std::endl;\n  \n  typedef std::vector< graph_traits<graph>::edges_size_type > \n    component_storage_t;\n  typedef iterator_property_map\n    < component_storage_t::iterator, \n      property_map<graph, edge_index_t>::type\n    >\n    component_map_t;\n  \n  component_storage_t component_storage(num_edges(g));\n  component_map_t component(component_storage.begin(), get(edge_index, g));\n  \n  std::cout << \"Before calling make_biconnected_planar, the graph has \"\n            << biconnected_components(g, component)\n            << \" biconnected components\" << std::endl;\n  \n  make_biconnected_planar(g, &embedding[0]);\n\n  // Re-initialize the edge index, since we just added a few edges\n  edge_count = 0;\n  for(tie(ei, ei_end) = edges(g); ei != ei_end; ++ei)\n    put(e_index, *ei, edge_count++);\n\n  // Re-size the storage for the biconnected components, since we\n  // just added a few edges\n  \n  component_storage.resize(num_edges(g));\n  component = component_map_t(component_storage.begin(), get(edge_index,g));\n\n  std::cout << \"After calling make_biconnected_planar, the graph has \"\n            << biconnected_components(g, component)\n            << \" biconnected components\" << std::endl;\n\n  if (boyer_myrvold_planarity_test(g))\n    std::cout << \"Also, the graph is still planar.\" << std::endl;\n  else\n    std::cout << \"But the graph is not still planar.\" << std::endl;\n\n  return 0;  \n}\n", "meta": {"hexsha": "3c4a7745b09a5d0ac5d68129130994678a79310d", "size": 3415, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/graph/example/make_biconnected_planar.cpp", "max_stars_repo_name": "oudream/boost_1_42_0", "max_stars_repo_head_hexsha": "e92227bf374e478030e89876ec353de6eecaeac0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-06-25T23:20:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-14T19:38:34.000Z", "max_issues_repo_path": "libs/graph/example/make_biconnected_planar.cpp", "max_issues_repo_name": "boost-cmake/vintage", "max_issues_repo_head_hexsha": "dcfb7da3177134eddaee6789d6f582259cb0d6ee", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/graph/example/make_biconnected_planar.cpp", "max_forks_repo_name": "boost-cmake/vintage", "max_forks_repo_head_hexsha": "dcfb7da3177134eddaee6789d6f582259cb0d6ee", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-07-26T08:07:09.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-25T23:20:21.000Z", "avg_line_length": 31.3302752294, "max_line_length": 76, "alphanum_fraction": 0.6404099561, "num_tokens": 896, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.647798211152541, "lm_q1q2_score": 0.4572062784910622}}
{"text": "/**\nGood tutorial: http://www.informit.com/articles/article.aspx?p=673259\n*/\n\n#include <algorithm>\n#include <fstream>\n#include <iostream>\n#include <set>\n#include <vector>\n\n#include <boost/config.hpp>\n//-lboost_graph\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\nint main() {\n\n    /*\n    #Graph\n\n        The following class hierarchy exists:\n\n            BidirectionalGraph -------- Incience ---------+\n                                                          |\n                                        Adjacency --------+\n                                                          |\n            VertexAndEdgeList ----+---- VertexList -------+---- Graph\n                                  |                       |\n                                  +---- EdgeList ---------+\n                                                          |\n                                        AdjacenyMatrix ---+\n    */\n    {\n        /*\n        #properties\n\n            Properties are values associated to edges and vertices.\n        */\n        {\n            /*\n            There are a few predefined properties which you should use whenever possible\n            as they are already used in many algorithms, but you can also define your own properties.\n\n            Predefined properties include:\n\n            - `edge_weight_t`. Used for most algorithms that have a single value associated to each\n                edge such as Dijikstra.\n\n            - `vertex_name_t`\n            */\n            {\n                typedef boost::property<boost::vertex_name_t, std::string> VertexProperties;\n                typedef boost::property<boost::edge_weight_t, int> EdgeProperties;\n            }\n\n            /*\n            Multiple properties can be specified either by:\n\n            - using a custom class as the property type. TODO is there any limitation to this?\n            - chaining multile properties\n            */\n            {\n            }\n\n            /*\n            The absense of a property is speficied by boost::no_property.\n            */\n            {\n                typedef boost::no_property VertexProperties;\n            }\n\n        }\n\n        typedef boost::property<boost::vertex_name_t, std::string> VertexProperties;\n        typedef boost::property<boost::edge_weight_t, int> EdgeProperties;\n        typedef boost::adjacency_list<\n            // Data structure to represent the out edges for each vertex.\n            // Possibilities:\n            //\n            // #vecS selects std::vector.\n            // #listS selects std::list.\n            // #slistS selects std::slist.\n            // #setS selects std::set.\n            // #multisetS selects std::multiset.\n            // #hash_setS selects std::hash_set.\n            //\n            // `S` standas for Selector.\n            boost::vecS,\n\n            // Data structure to represent the vertex set.\n            boost::vecS,\n\n            // Directed type.\n            // #bidirectionalS: directed graph with access to in and out edges\n            // #directedS:      directed graph with access only to out-edges\n            // #undirectedS:    undirected graph\n            boost::bidirectionalS,\n\n            // Optional.\n            VertexProperties,\n\n            // Optional.\n            EdgeProperties\n        > Graph;\n        //typedef boost::graph_traits<Graph>::vertex_iterator VertexIter;\n        //typedef boost::graph_traits<Graph>::vertex_descriptor Vertex;\n        //typedef boost::property_map<Graph, boost::vertex_index_t>::type IndexMap;\n\n        // Fix number of vertices, and add one edge at a time.\n        int num_vertices = 3;\n        Graph g(num_vertices);\n        boost::add_edge(0, 1, g);\n        boost::add_edge(1, 2, g);\n\n        // Fix number of vertices, and add one edge array.\n        {\n            int num_vertices = 3;\n            typedef std::pair<int, int> Edge;\n            std::vector<Edge> edges{\n                {0, 1},\n                {1, 2},\n            };\n            Graph g(edges.data(), edges.data() + edges.size(), num_vertices);\n        }\n\n        // It is also possible to add vertices with #add_vertex.\n\n        //#vertices\n        {\n            // Number of vertices.\n            boost::graph_traits<Graph>::vertices_size_type num_vertices = boost::num_vertices(g);\n            assert(num_vertices == 3u);\n\n            //#vertices() Returns a begin() end() vertex iterator pair so we know where to stop.\n            {\n                typedef std::vector<boost::graph_traits<Graph>::vertex_descriptor> Vertices;\n                Vertices vertices;\n                vertices.reserve(num_vertices);\n                //IndexMap\n                auto index = boost::get(boost::vertex_index, g);\n                //std::pair<vertex_iter, vertex_iter> vp\n                for (auto vp = boost::vertices(g); vp.first != vp.second; ++vp.first) {\n                    // Vertex\n                    auto v = *vp.first;\n                    vertices.push_back(index[v]);\n                }\n                assert((vertices == Vertices{0, 1, 2}));\n            }\n\n            // The iterator is a ranom access iterator.\n            {\n                auto index = boost::get(boost::vertex_index, g);\n                auto it = boost::vertices(g).first;\n                assert(index[it[2]] == 2);\n                assert(index[it[1]] == 1);\n            }\n        }\n\n        //#edges\n        {\n            // It seems that only AdjencyMatrix has a method to get an edge given two vertices:\n            //edge(u, v, g)\n        }\n    }\n\n    //#source is also a global function: <http://stackoverflow.com/questions/16114616/why-is-boost-graph-librarys-source-a-global-function>\n\n    //#dijikstra\n    std::cout << \"#dijkstra\" << std::endl;\n    {\n        typedef boost::adjacency_list<\n            boost::listS,\n            boost::vecS,\n            boost::directedS,\n            boost::no_property,\n            boost::property<boost::edge_weight_t, int>\n        > Graph;\n        typedef boost::graph_traits<Graph>::vertex_descriptor vertex_descriptor;\n        typedef boost::graph_traits<Graph>::edge_descriptor edge_descriptor;\n        typedef std::pair<int, int> Edge;\n\n        // Model inputs.\n        const int num_nodes = 5;\n        const int sorce = 0;\n        std::vector<Edge> edges{\n            {0, 2}, {1, 1}, {1, 3}, {1, 4}, {2, 1},\n            {2, 3}, {3, 4}, {4, 0}, {4, 1}\n        };\n        std::vector<int> weights{\n            1, 2, 1, 2, 7,\n            3, 1, 1, 1\n        };\n\n        // Solve.\n        Graph g(edges.data(), edges.data() + edges.size(), weights.data(), num_nodes);\n        std::vector<vertex_descriptor> p(num_vertices(g));\n        std::vector<int> d(num_vertices(g));\n        vertex_descriptor s = vertex(sorce, g);\n        dijkstra_shortest_paths(g, s,\n            predecessor_map(boost::make_iterator_property_map(\n                p.begin(),\n                boost::get(boost::vertex_index, g)\n            )).distance_map(boost::make_iterator_property_map(\n                d.begin(),\n                boost::get(boost::vertex_index, g)\n            ))\n        );\n\n        // Print solution to stdout.\n        std::cout << \"node | distance from source | parent\" << std::endl;\n        boost::graph_traits<Graph>::vertex_iterator vi, vend;\n        for (boost::tie(vi, vend) = vertices(g); vi != vend; ++vi)\n            std::cout << *vi << \" \" << d[*vi] << \" \" << p[*vi] << std::endl;\n        std::cout <<std::endl;\n\n        // Generate a .dot graph file with shortest path highlighted.\n        // To PNG with: dot -Tpng -o outfile.png input.dot\n        boost::property_map<Graph, boost::edge_weight_t>::type weightmap = boost::get(boost::edge_weight, g);\n        std::ofstream dot_file(\"dijkstra.dot\");\n        dot_file << \"digraph D {\\n\"      << \"  rankdir=LR\\n\"           << \"  size=\\\"4,3\\\"\\n\"\n                 << \"  ratio=\\\"fill\\\"\\n\" << \"  edge[style=\\\"bold\\\"]\\n\" << \"  node[shape=\\\"circle\\\"]\\n\";\n        boost::graph_traits <Graph>::edge_iterator ei, ei_end;\n        for (std::tie(ei, ei_end) = boost::edges(g); ei != ei_end; ++ei) {\n            edge_descriptor e = *ei;\n            boost::graph_traits<Graph>::vertex_descriptor\n                u = boost::source(e, g), v = boost::target(e, g);\n            dot_file << u << \" -> \" << v << \"[label=\\\"\" << boost::get(weightmap, e) << \"\\\"\";\n            if (p[v] == u)\n                dot_file << \", color=\\\"black\\\"\";\n            else\n                dot_file << \", color=\\\"grey\\\"\";\n            dot_file << \"]\";\n        }\n        dot_file << \"}\";\n\n        // Construct forward path to a destination.\n        int dest = 4;\n        int cur = dest;\n        std::vector<int> path;\n        path.push_back(cur);\n        while(cur != sorce) {\n            cur = p[cur];\n            path.push_back(cur);\n        }\n        std::reverse(path.begin(), path.end());\n        // Print.\n        std::cout << \"Path to node \" << std::to_string(dest) << \":\" << std::endl;\n        for(auto& node : path) {\n            std::cout << node << std::endl;\n        }\n    }\n}\n", "meta": {"hexsha": "27a995bbe830a8b74c2be04c3d35928096ac03b2", "size": 9130, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "awesome/c_cpp/cpp-cheat/boost/graph.cpp", "max_stars_repo_name": "liujiamingustc/phd", "max_stars_repo_head_hexsha": "4f815a738abad43531d02ac66f5bd0d9a1def52a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-01-06T03:01:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T03:02:55.000Z", "max_issues_repo_path": "awesome/c_cpp/cpp-cheat/boost/graph.cpp", "max_issues_repo_name": "liujiamingustc/phd", "max_issues_repo_head_hexsha": "4f815a738abad43531d02ac66f5bd0d9a1def52a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "awesome/c_cpp/cpp-cheat/boost/graph.cpp", "max_forks_repo_name": "liujiamingustc/phd", "max_forks_repo_head_hexsha": "4f815a738abad43531d02ac66f5bd0d9a1def52a", "max_forks_repo_licenses": ["Apache-2.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.8039215686, "max_line_length": 139, "alphanum_fraction": 0.5036144578, "num_tokens": 2007, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.7057850154599562, "lm_q1q2_score": 0.45720627527226226}}
{"text": "\n#include <iostream>\n#include <Eigen/Dense>\n#include \"RigidBodyManipulator.h\"\n\nusing namespace std;\n\nint main(int argc, char* argv[])\n{\n  if (argc < 2) {\n    cerr << \"Usage: urdfManipulatorDynamicsTest urdf_filename\" << endl;\n    exit(-1);\n  }\n  RigidBodyManipulator* model = new RigidBodyManipulator(argv[1]);\n  if (!model) {\n    cerr << \"ERROR: Failed to load model from \" << argv[1] << endl;\n    return -1;\n  }\n  cout << \"=======\" << endl;\n\n  // the order of the bodies may be different in matlab, so print it out once here\n  cout << model->num_bodies << endl;\n  for (int i = 0; i < model->num_bodies; i++) {\n    cout << model->bodies[i]->linkname << endl;\n  }\n\n  VectorXd q = VectorXd::Zero(model->num_positions);\n  VectorXd v = VectorXd::Zero(model->num_velocities);\n  int i;\n\n  if (argc >= 2 + model->num_positions) {\n    for (i = 0; i < model->num_positions; i++)\n      sscanf(argv[2 + i], \"%lf\", &q(i));\n  }\n\n  if (argc >= 2 + model->num_positions + model->num_velocities) {\n    for (i = 0; i < model->num_velocities; i++)\n      sscanf(argv[2 + model->num_positions + i], \"%lf\", &v(i));\n  }\n\n  model->doKinematicsNew(q, v, true, true);\n\n  auto H = model->massMatrix<double>();\n  cout << H.value() << endl;\n\n  map<int, unique_ptr<GradientVar<double, TWIST_SIZE, 1>> > f_ext;\n  auto C = model->inverseDynamics(f_ext);\n  cout << C.value() << endl;\n\n  cout << model->B << endl;\n\n  if (model->loops.size()>0) {\n    auto phi = model->positionConstraintsNew<double>(1);\n    cout << phi.value() << endl;\n    cout << phi.gradient().value() << endl;\n  }\n\n  delete model;\n  return 0;\n}\n", "meta": {"hexsha": "fe49fdc29932a1992d21f2e0ee00a64fcb1e054b", "size": 1583, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "systems/plants/test/urdfManipulatorDynamicsTest.cpp", "max_stars_repo_name": "jacob-izr/drake", "max_stars_repo_head_hexsha": "d8f0f1f231ecba83ed53b1a1c2f9f43da50396b9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "systems/plants/test/urdfManipulatorDynamicsTest.cpp", "max_issues_repo_name": "jacob-izr/drake", "max_issues_repo_head_hexsha": "d8f0f1f231ecba83ed53b1a1c2f9f43da50396b9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "systems/plants/test/urdfManipulatorDynamicsTest.cpp", "max_forks_repo_name": "jacob-izr/drake", "max_forks_repo_head_hexsha": "d8f0f1f231ecba83ed53b1a1c2f9f43da50396b9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-29T19:37:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-29T19:37:28.000Z", "avg_line_length": 25.9508196721, "max_line_length": 82, "alphanum_fraction": 0.6070751737, "num_tokens": 478, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.6334102775181399, "lm_q1q2_score": 0.4571595645977936}}
{"text": "// Solving a puzzle below\r\n// https://sist8.com/yougun\r\n\r\n#include <cstdlib>\r\n#include <cmath>\r\n#include <fstream>\r\n#include <iomanip>\r\n#include <iostream>\r\n#include <limits>\r\n#include <random>\r\n#include <sstream>\r\n#include <string>\r\n#include <vector>\r\n#include <boost/optional.hpp>\r\n#include <boost/program_options.hpp>\r\n#include <boost/multi_array.hpp>\r\n\r\nnamespace {\r\n    using Count = long long int;\r\n    // Bitmap (1 to alive) of survivors 0..(N_PLAYERS-1)\r\n    using State = unsigned int;\r\n    using Index = int;\r\n    using Survivors = std::vector<Index>;\r\n\r\n    struct Action {\r\n        Index player;\r\n        State state;\r\n        Index target;\r\n    };\r\n    using ActionChain = std::vector<Action>;\r\n\r\n    // Rule of the game\r\n    constexpr Index N_PLAYERS = 3;\r\n    constexpr Index N_STATES = 1 << N_PLAYERS;  // 2^N_PLAYERS combinations\r\n    constexpr Index N_ACTIONS = N_PLAYERS + 1;  // Shoot Player 0, ... (N_PLAYERS-1), or nobody\r\n    constexpr Index N_WINNERS = N_PLAYERS;\r\n    constexpr Index ALIVE = 1;\r\n    const std::vector<double> HIT_RATE {0.3, 0.5, 1.0};\r\n\r\n    // Optimal actions (responses)\r\n    enum class ExpectedAction {\r\n        A,\r\n        B,\r\n        C,\r\n        Nobody,\r\n        Undefined,\r\n    };\r\n\r\n    const ExpectedAction ExpectedActions[N_PLAYERS][N_STATES] = {\r\n        {ExpectedAction::Undefined, ExpectedAction::Undefined, ExpectedAction::Undefined, ExpectedAction::B,\r\n         ExpectedAction::Undefined, ExpectedAction::C, ExpectedAction::Undefined, ExpectedAction::Nobody},\r\n        {ExpectedAction::Undefined, ExpectedAction::Undefined, ExpectedAction::Undefined, ExpectedAction::A,\r\n         ExpectedAction::Undefined, ExpectedAction::Undefined, ExpectedAction::C, ExpectedAction::C},\r\n        {ExpectedAction::Undefined, ExpectedAction::Undefined, ExpectedAction::Undefined, ExpectedAction::Undefined,\r\n         ExpectedAction::Undefined, ExpectedAction::A, ExpectedAction::B, ExpectedAction::B}};\r\n\r\n    // Hyper parameters\r\n    constexpr Count DEFAULT_SAMPLES_SOFTMAX = 1000000ll;\r\n    constexpr Count DEFAULT_SAMPLES_LINEAR = 10000000ll;\r\n    constexpr double DEFAULT_LEARNING_RATE_LINEAR = 0.00001;\r\n    constexpr double DEFAULT_LEARNING_RATE_SOFTMAX = 0.0001;\r\n    constexpr double DEFAULT_EXPLORATION_RATIO_LINEAR = 0.1;\r\n    constexpr double DEFAULT_EXPLORATION_RATIO_SOFTMAX = 0.2;\r\n\r\n    constexpr Count MIN_TRIALS = 1ll;\r\n    constexpr bool DEFAULT_USE_SOFTMAX = false;\r\n    constexpr bool IID_CHOICE = false;\r\n    constexpr Index MAX_DEPTH = 15;\r\n}\r\n\r\n#define OPTION_NAME_TRIALS \"trials\"\r\n#define OPTION_NAME_SAMPLES \"samples\"\r\n#define OPTION_NAME_SOFTMAX \"softmax\"\r\n#define OPTION_NAME_LEARNING_RATE \"learning_rate\"\r\n#define OPTION_NAME_EXPLORATION_RATIO \"exploration_ratio\"\r\n#define OPTION_NAME_LOGFILE \"logfile\"\r\n\r\nclass OptimalAction {\r\npublic:\r\n    struct Setting {\r\n        bool useSoftmax {DEFAULT_USE_SOFTMAX};\r\n        boost::optional<Count> numSamples;\r\n        boost::optional<double> learningRate;\r\n        boost::optional<double> explorationRatio;\r\n        std::string logFilename;\r\n    };\r\n\r\n    OptimalAction(const Setting& setting) :\r\n        rand_gen_(rand_dev_()), unit_distribution_(0.0, 1.0),\r\n        value_(boost::extents[N_PLAYERS][N_STATES][N_ACTIONS]),\r\n        useSoftmax_(setting.useSoftmax) {\r\n        numSamples_ = (setting.numSamples) ? (*setting.numSamples) :\r\n            ((useSoftmax_) ? DEFAULT_SAMPLES_SOFTMAX : DEFAULT_SAMPLES_LINEAR);\r\n        learningRate_ = (setting.learningRate) ? (*setting.learningRate) :\r\n            ((useSoftmax_) ? DEFAULT_LEARNING_RATE_SOFTMAX : DEFAULT_LEARNING_RATE_LINEAR);\r\n        explorationRatio_ = (setting.explorationRatio) ? (*setting.explorationRatio) :\r\n            ((useSoftmax_) ? DEFAULT_EXPLORATION_RATIO_SOFTMAX : DEFAULT_EXPLORATION_RATIO_LINEAR);\r\n\r\n        if (!setting.logFilename.empty()) {\r\n            outStream_ = std::make_unique<std::ofstream>(setting.logFilename);\r\n            *outStream_ << \"B,C,Nobody\\n\";\r\n        }\r\n\r\n        for (Index player = 0; player < N_PLAYERS; ++player) {\r\n            for (Index state = 0; state < N_STATES; ++state) {\r\n                initialize(player, state);\r\n            }\r\n        }\r\n\r\n        std::cout << \"UseSoftmax=\" << useSoftmax_ << \", # of Samples=\" << numSamples_;\r\n        std::cout << \", Learning Rate=\" << learningRate_;\r\n        std::cout << \", Exploration Ratio=\" << explorationRatio_ << \"\\n\";\r\n        return;\r\n    }\r\n\r\n    virtual ~OptimalAction(void) = default;\r\n\r\n    void Exec(void) {\r\n        for (Count i = 0; i < numSamples_; ++i) {\r\n            exec();\r\n            if (!outStream_) {\r\n                continue;\r\n            }\r\n\r\n            Index player = static_cast<decltype(player)>(ExpectedAction::A);\r\n            for (Index action = 0; action < N_ACTIONS; ++action) {\r\n                if (player != action) {\r\n                    *outStream_ << value_[player][N_STATES-1][action];\r\n                    if ((action + 1) < N_ACTIONS) {\r\n                        *outStream_ << \",\";\r\n                    }\r\n                }\r\n            }\r\n            *outStream_ << \"\\n\";\r\n        }\r\n        return;\r\n    }\r\n\r\n    void Print(void) {\r\n        for (Index player = 0; player < N_PLAYERS; ++player) {\r\n            std::cout << printValue(player);\r\n        }\r\n        return;\r\n    }\r\n\r\n    bool Check(void) {\r\n        bool result = true;\r\n\r\n        for (Index player = 0; player < N_PLAYERS; ++player) {\r\n            for (Index state = 0; state < N_STATES; ++state) {\r\n                const auto expectedAction = ExpectedActions[player][state];\r\n                if (expectedAction == ExpectedAction::Undefined) {\r\n                    continue;\r\n                }\r\n\r\n                Index actual = N_ACTIONS;\r\n                double maxValue = -std::numeric_limits<double>::infinity();\r\n                for (Index action = 0; action < N_ACTIONS; ++action) {\r\n                    auto value = value_[player][state][action];\r\n                    if (maxValue < value) {\r\n                        actual = action;\r\n                        maxValue = value;\r\n                    }\r\n                }\r\n\r\n                const auto expected = static_cast<decltype(actual)>(expectedAction);\r\n                if (static_cast<decltype(actual)>(expected) != actual) {\r\n                    result = false;\r\n                    std::cout << \"! Player=\" << player << \", State=\" << state;\r\n                    std::cout << \", Expected=\" << expected << \", Actual=\" << actual << \"\\n\";\r\n                }\r\n            }\r\n        }\r\n        return result;\r\n    }\r\n\r\n    void initialize(Index player, State state) {\r\n        for (Index action = 0; action < N_ACTIONS; ++action) {\r\n            // Do not shoot yourself!\r\n            auto count = checkAliveOrNobody(player, state);\r\n            if (useSoftmax_) {\r\n                value_[player][state][action] = count && checkAliveOrNobody(action, state) &&\r\n                    (player != action) ? 0.0 : -std::numeric_limits<double>::infinity();\r\n            } else {\r\n                value_[player][state][action] = count && checkAliveOrNobody(action, state) &&\r\n                    (player != action) ? (1.0 / static_cast<double>(count)) : 0.0;\r\n            }\r\n        }\r\n\r\n        if (useSoftmax_) {\r\n            normalizeSoftmaxProbabilities(player, state);\r\n        }\r\n        return;\r\n    }\r\n\r\n    void exec(void) {\r\n        Survivors survivors(N_PLAYERS, ALIVE);\r\n        ActionChain actionChain;\r\n        aimAndShoot(0, 0, survivors, actionChain);\r\n        return;\r\n    }\r\n\r\n    char printIndexChar(Index player) {\r\n        return player + 'A';\r\n    }\r\n\r\n    std::string printValue(Index player) {\r\n        std::ostringstream os;\r\n\r\n        os << std::setprecision(5) << \"[States, actions and values for Player \" << printIndexChar(player) << \"]\\n\";\r\n        for (Index state = 0; state < N_STATES; ++state) {\r\n            // Exclude when the player is not alive or only alive\r\n            if (checkPlayerAlive(player, state) < 2) {\r\n                continue;\r\n            }\r\n\r\n            for (Index action = 0; action < N_ACTIONS; ++action) {\r\n                if ((player != action) && checkPlayerAlive(action, state)) {\r\n                    os << \"Target \" << printIndexChar(action) << \":\" << value_[player][state][action] << \", \";\r\n                }\r\n                if (action >= N_PLAYERS) {\r\n                    os << \"Nobody:\" << value_[player][state][action] << \"\\n\" ;\r\n                }\r\n            }\r\n        }\r\n\r\n        os << \"\\n\";\r\n        return os.str();\r\n    }\r\n\r\n    // Converts an array to a bitmap\r\n    State survivorsToState(const Survivors& survivors) {\r\n        State state = 0;\r\n        State index = 1;\r\n        for(const auto value : survivors) {\r\n            state += index * (value ? 1 : 0);\r\n            index <<= 1;\r\n        }\r\n        return state;\r\n    }\r\n\r\n    // Notice that nobody is always not alive (population - player(1) + nobady(1))\r\n    template<typename T>\r\n    auto countPopulation(T state) {\r\n        return __builtin_popcount(state);\r\n    }\r\n\r\n    // Return population of the state if the player is alive in the state, 0 othewise\r\n    Index checkAliveOrNobody(Index player, State state) {\r\n        return ((player >= N_PLAYERS) || (state & (1 << player))) ? countPopulation(state) : 0;\r\n    }\r\n\r\n    Index checkPlayerAlive(Index player, State state) {\r\n        return (state & (1 << player)) ? countPopulation(state) : 0;\r\n    }\r\n\r\n    // exp(elements) /= exp(max(elements)) to avoid overflow\r\n    void normalizeSoftmaxProbabilities(Index player, State state) {\r\n        double max_log = -std::numeric_limits<double>::infinity();\r\n        for (Index action = 0; action < N_ACTIONS; ++action) {\r\n            max_log = std::max(max_log, value_[player][state][action]);\r\n        }\r\n\r\n        // Adjust max(log(probabilities)) to zero\r\n        for (Index action = 0; action < N_ACTIONS; ++action) {\r\n            value_[player][state][action] -= max_log;\r\n        }\r\n        return;\r\n    }\r\n\r\n    std::vector<double> getSoftmaxProbabilities(Index player, State state) {\r\n        std::vector<double> probabilities(N_ACTIONS, 0.0);\r\n        double sum = 0.0;\r\n\r\n        for (Index action = 0; action < N_ACTIONS; ++action) {\r\n            const auto value = ::exp(value_[player][state][action]);\r\n            probabilities.at(action) = value;\r\n            sum += value;\r\n        }\r\n\r\n        for (Index action = 0; action < N_ACTIONS; ++action) {\r\n            probabilities.at(action) /= sum;\r\n        }\r\n\r\n        return probabilities;\r\n    }\r\n\r\n    // Overwrites survivors\r\n    void aimAndShoot(Index player, Index depth, Survivors& survivors, const ActionChain& actionChain) {\r\n        if (depth >= MAX_DEPTH) {\r\n            return;\r\n        }\r\n\r\n        const auto targets = getTargets(player, survivors);\r\n        const auto state = survivorsToState(survivors);\r\n        const auto target = getActionTarget(player, state, survivors, targets);\r\n\r\n        ActionChain nextActionChain = actionChain;\r\n        Action nextAction {player, state, target};\r\n        nextActionChain.push_back(nextAction);\r\n        shoot(player, survivors, target);\r\n\r\n        if (std::accumulate(survivors.begin(), survivors.end(), 0) == 1) {\r\n            const auto winner = std::distance(survivors.begin(),\r\n                                              std::find(survivors.begin(), survivors.end(), ALIVE));\r\n\r\n            // Pick up one sample to i.i.d.\r\n            if (IID_CHOICE) {\r\n                auto raw_index = unit_distribution_(rand_gen_) * static_cast<double>(nextActionChain.size()) - 0.5;\r\n                auto index = std::min(nextActionChain.size() - 1,\r\n                                      static_cast<decltype(nextActionChain.size())>(\r\n                                          std::max(0, static_cast<int>(raw_index))));\r\n                backpropagate(nextActionChain.at(index), winner);\r\n            } else {\r\n                // Reverse if you deduct rewards\r\n                for(const auto& action : nextActionChain) {\r\n                    backpropagate(action, winner);\r\n                }\r\n            }\r\n        } else {\r\n            aimAndShoot((player + 1) % N_PLAYERS, depth + 1, survivors, nextActionChain);\r\n        }\r\n\r\n        return;\r\n    }\r\n\r\n    std::vector<Index> getTargets(Index player, const Survivors& survivors) {\r\n        std::vector<Index> targets;\r\n        for(Index target = 0; target < N_PLAYERS; ++target) {\r\n            if ((target != player) && survivors.at(target)) {\r\n                targets.push_back(target);\r\n            }\r\n        }\r\n\r\n        if (targets.size() > 1) {\r\n            // Can shoot nobody\r\n            targets.push_back(N_PLAYERS);\r\n        }\r\n\r\n        return targets;\r\n    }\r\n\r\n    std::vector<double> getProportions(Index player, State state) {\r\n        // Number of targets = number of survivors - player(1) + nobody(1)\r\n        std::vector<double> proportions(N_ACTIONS, 0.0);\r\n\r\n        // Epsilon-greedy\r\n        const auto rand_proportional = unit_distribution_(rand_gen_);\r\n        const bool proportional = (rand_proportional < explorationRatio_);\r\n\r\n        if (proportional) {\r\n            // Number of targets = number of survivors - player(1) + nobody(1)\r\n            const auto population = checkPlayerAlive(player, state);\r\n            const double proportion = (population > 0) ? (1.0 / static_cast<double>(population)) : 0.0;\r\n            for (Index action = 0; action < N_ACTIONS; ++action) {\r\n                proportions.at(action) = (checkPlayerAlive(player, state) &&\r\n                                          checkAliveOrNobody(action, state) &&\r\n                                          (player != action)) ? proportion : 0.0;\r\n            }\r\n        } else {\r\n            if (useSoftmax_) {\r\n                proportions = getSoftmaxProbabilities(player, state);\r\n            } else {\r\n                for (Index action = 0; action < N_ACTIONS; ++action) {\r\n                    proportions.at(action) = value_[player][state][action];\r\n                }\r\n            }\r\n        }\r\n\r\n        return proportions;\r\n    }\r\n\r\n    Index getActionTarget(Index player, State state, const Survivors& survivors, const std::vector<Index>& targets) {\r\n        const auto proportions = getProportions(player, state);\r\n        auto rand_value = unit_distribution_(rand_gen_);\r\n        Index target = 0;\r\n\r\n        while(rand_value >= 0.0) {\r\n            rand_value -= proportions.at(target);\r\n            target += 1;\r\n            if (target >= N_ACTIONS) {\r\n                break;\r\n            }\r\n        }\r\n\r\n        return target - 1;\r\n    }\r\n\r\n    // Overwrites survivors\r\n    void shoot(Index player, Survivors& survivors, Index target) {\r\n        if (target < N_PLAYERS) {\r\n            if (unit_distribution_(rand_gen_) < HIT_RATE.at(player)) {\r\n                survivors.at(target) = 0;\r\n            }\r\n        }\r\n\r\n        return;\r\n    }\r\n\r\n    void backpropagate(const Action& action, Index final_surviver) {\r\n        // Normalizes such that the sum of values is 1\r\n        if (useSoftmax_) {\r\n            // backpropagate Y-T * delta(error)/delta(y)\r\n            auto exp_proportions = getSoftmaxProbabilities(action.player, action.state);\r\n            for (Index i = 0; i < N_ACTIONS; ++i) {\r\n                const auto delta = (exp_proportions[i] - ((action.player == final_surviver) ? 1.0 : 0.0)) * learningRate_;\r\n                value_[action.player][action.state][action.target] -= delta;\r\n            }\r\n            normalizeSoftmaxProbabilities(action.player, action.state);\r\n        } else {\r\n            const auto target_value = value_[action.player][action.state][action.target];\r\n            const auto delta = target_value * learningRate_ * ((action.player == final_surviver) ? 1.0 : -1.0);\r\n            value_[action.player][action.state][action.target] += delta;\r\n            double sum = 0.0;\r\n            for (Index i = 0; i < N_ACTIONS; ++i) {\r\n                sum += value_[action.player][action.state][i];\r\n            }\r\n            for (Index i = 0; i < N_ACTIONS; ++i) {\r\n                value_[action.player][action.state][i] /= sum;\r\n            }\r\n        }\r\n    }\r\n\r\nprivate:\r\n    using StateActionValue = boost::multi_array<double, 3>;\r\n    std::random_device rand_dev_;\r\n    std::mt19937 rand_gen_;\r\n    std::uniform_real_distribution<double> unit_distribution_;\r\n    StateActionValue value_;\r\n\r\n    bool useSoftmax_ {DEFAULT_USE_SOFTMAX};\r\n    Count numSamples_ {0};\r\n    double learningRate_ {0.0};\r\n    double explorationRatio_ {0.0};\r\n    std::unique_ptr<std::ofstream> outStream_;\r\n};\r\n\r\nint main(int argc, char* argv[]) {\r\n    Count numTrials = MIN_TRIALS;\r\n    OptimalAction::Setting setting;\r\n\r\n    boost::program_options::options_description description(\"Options\");\r\n    description.add_options()\r\n        (OPTION_NAME_TRIALS\",t\",\r\n         boost::program_options::value<decltype(numTrials)>(),\r\n         \"Number of searches\")\r\n        (OPTION_NAME_SAMPLES\",s\",\r\n         boost::program_options::value<decltype(setting.numSamples)>(),\r\n         \"Number of samples in a search\")\r\n        (OPTION_NAME_SOFTMAX\",x\",\r\n         boost::program_options::value<decltype(setting.useSoftmax)>()->default_value(false),\r\n         \"Use softmax instead of linear\")\r\n        (OPTION_NAME_LEARNING_RATE\",l\",\r\n         boost::program_options::value<decltype(setting.learningRate)::value_type>(),\r\n         \"Learning rate\")\r\n        (OPTION_NAME_EXPLORATION_RATIO\",e\",\r\n         boost::program_options::value<decltype(setting.explorationRatio)::value_type>(),\r\n         \"Probability of explorations\")\r\n        (OPTION_NAME_LOGFILE\",o\",\r\n         boost::program_options::value<decltype(setting.logFilename)>(),\r\n         \"Output log file name\")\r\n        ;\r\n\r\n    boost::program_options::variables_map varMap;\r\n    boost::program_options::store(parse_command_line(argc, argv, description), varMap);\r\n    boost::program_options::notify(varMap);\r\n\r\n    if (varMap.count(OPTION_NAME_TRIALS)) {\r\n        numTrials = std::max(MIN_TRIALS, varMap[OPTION_NAME_TRIALS].\r\n                             as<decltype(numTrials)>());\r\n    }\r\n\r\n    if (varMap.count(OPTION_NAME_SAMPLES)) {\r\n        setting.numSamples = varMap[OPTION_NAME_SAMPLES].\r\n            as<decltype(setting.numSamples)>();\r\n    }\r\n\r\n    if (varMap.count(OPTION_NAME_SOFTMAX)) {\r\n        setting.useSoftmax = varMap[OPTION_NAME_SOFTMAX].\r\n            as<decltype(setting.useSoftmax)>();\r\n    }\r\n\r\n    if (varMap.count(OPTION_NAME_LEARNING_RATE)) {\r\n        setting.learningRate = varMap[OPTION_NAME_LEARNING_RATE].\r\n            as<decltype(setting.learningRate)::value_type>();\r\n    }\r\n\r\n    if (varMap.count(OPTION_NAME_EXPLORATION_RATIO)) {\r\n        setting.explorationRatio = varMap[OPTION_NAME_EXPLORATION_RATIO]\r\n            .as<decltype(setting.explorationRatio)::value_type>();\r\n    }\r\n\r\n    if (varMap.count(OPTION_NAME_LOGFILE)) {\r\n        setting.logFilename = varMap[OPTION_NAME_LOGFILE]\r\n            .as<decltype(setting.logFilename)>();\r\n    }\r\n\r\n    OptimalAction optimalAction(setting);\r\n    Count n_correct = 0;\r\n    Count n_wrong = 0;\r\n    for (Count trial = 0; trial < numTrials; ++trial) {\r\n        optimalAction.Exec();\r\n        const auto correct = optimalAction.Check();\r\n        n_correct += (correct ? 1 : 0);\r\n        n_wrong += (correct ? 0 : 1);\r\n\r\n        if (!trial || !correct) {\r\n            optimalAction.Print();\r\n        } else {\r\n            std::cerr << \".\";\r\n        }\r\n    }\r\n\r\n    std::cout << \"Correct cases=\" << n_correct << \", Wrong cases=\" << n_wrong << \"\\n\";\r\n    return 0;\r\n}\r\n\r\n/*\r\nLocal Variables:\r\nmode: c++\r\ncoding: utf-8-dos\r\ntab-width: nil\r\nc-file-style: \"stroustrup\"\r\nEnd:\r\n*/\r\n", "meta": {"hexsha": "cff8e80b2e4d5c5f692e1302e92af68a5f4fbadf", "size": 19663, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "optimal_action/optimal_action.cpp", "max_stars_repo_name": "zettsu-t/cPlusPlusFriend", "max_stars_repo_head_hexsha": "5399065abe2c0eda2b9aec26e6435d8c27cda9cd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2017-04-15T00:05:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-10T05:11:14.000Z", "max_issues_repo_path": "optimal_action/optimal_action.cpp", "max_issues_repo_name": "zettsu-t/cPlusPlusFriend", "max_issues_repo_head_hexsha": "5399065abe2c0eda2b9aec26e6435d8c27cda9cd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "optimal_action/optimal_action.cpp", "max_forks_repo_name": "zettsu-t/cPlusPlusFriend", "max_forks_repo_head_hexsha": "5399065abe2c0eda2b9aec26e6435d8c27cda9cd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-02-23T22:47:08.000Z", "max_forks_repo_forks_event_max_datetime": "2018-02-23T22:47:08.000Z", "avg_line_length": 37.3821292776, "max_line_length": 123, "alphanum_fraction": 0.5660885928, "num_tokens": 4380, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432182679957, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.4571595621908241}}
{"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_MAJORITY_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_MAJORITY_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-predicates\n    Function object implementing majority capabilities\n\n    Returns @ref True if at least two inputs are not @ref Zero else @ref False.\n\n    @par Semantic:\n\n    @code\n    auto r = majority(x,y,z);\n    @endcode\n\n    is similar to:\n\n    @code\n    auto r = (x!= 0)+(y!= 0)+(z!= 0) >= 2;\n    @endcode\n\n  **/\n  as_logical_t<Value> Value majority(Value const& x, Value const& y, Value const& z);\n} }\n#endif\n\n#include <boost/simd/function/scalar/majority.hpp>\n#include <boost/simd/function/simd/majority.hpp>\n\n#endif\n", "meta": {"hexsha": "c20221543ea41582675091e457b2be7d62ced46c", "size": 1101, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/majority.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/majority.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/majority.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": 23.9347826087, "max_line_length": 100, "alphanum_fraction": 0.5722070845, "num_tokens": 247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432182679956, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.45715956219082404}}
{"text": "// Copyright 2020 Advanced Remanufacturing and Technology Centre\n// Copyright 2020 ROS-Industrial Consortium Asia Pacific Team\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 PLANNING_FUNCTIONS_HPP_\n#define PLANNING_FUNCTIONS_HPP_\n\n#include <boost/filesystem.hpp>\n#include <ament_index_cpp/get_package_share_directory.hpp>\n#include <opencv2/opencv.hpp>\n#include <cv_bridge/cv_bridge.h>\n\n#include <iostream>\n#include <vector>\n#include <fstream>\n#include <sstream>\n#include <algorithm>\n#include \"cmath\"\n#include \"sensor_msgs/msg/camera_info.hpp\"\n#include \"sensor_msgs/image_encodings.hpp\"\n#include \"yaml-cpp/yaml.h\"\n\nfloat PI = 3.14159265;\n/**\n * Calculate length of two points in 2D space\n */\nfloat length(int x1, int y1, int x2, int y2)\n{\n  return sqrt(pow(static_cast<float>(x1 - x2), 2) + pow(static_cast<float>(y1 - y2), 2));\n}\n\n/**\n * Checks if a point is in a circle.\n */\nbool in_circle(float radius, std::vector<int> centre, std::vector<int> point)\n{\n  if (pow((point[0] - centre[0]), 2) + pow((point[1] - centre[1]), 2) - pow(radius, 2) < 0) {\n    return true;\n  } else {\n    return false;\n  }\n}\n\n/**\n * Quadratic equation solver\n */\nstd::vector<float> quadratic_equation(float a, float b, float c)\n{\n  std::vector<float> result;\n  float discriminant = pow(b, 2) - (4 * a * c);\n  if (discriminant < 0) {\n    return result;\n  } else if (discriminant == 0) {\n    result.push_back(-b / (2 * a));\n  } else {\n    result.push_back(((-b + sqrt(discriminant)) / (2 * a)));\n    result.push_back(((-b - sqrt(discriminant)) / (2 * a)));\n  }\n  return result;\n}\n\n/**\n * Get the intersecting coordinates between a circle and a line\n */\nstd::vector<std::vector<int>> circle_line_intersect(\n  float gradient,\n  float intersect,\n  float radius,\n  std::vector<float> circle_centre)\n{\n  std::vector<std::vector<int>> result;\n\n  if (circle_centre.size() == 2 && radius > 0) {\n    // Get the quadratic equation to determine the x coordinates of point\n    float a = 1 + pow(gradient, 2);\n    float b = 2 * ((gradient * (intersect - circle_centre[1])) - circle_centre[0]);\n    float c = pow(circle_centre[0], 2) +\n      pow((intersect - circle_centre[1]), 2) - pow(radius, 2);\n\n    std::vector<float> x_coords = quadratic_equation(a, b, c);\n\n    // Solve the equation to get the x coordinates\n    if (static_cast<int>(x_coords.size()) == 2) {\n      for (int i = 0; i < static_cast<int>(x_coords.size()); i++) {\n        std::vector<int> temp_coords {static_cast<int>(round(x_coords[i])),\n          static_cast<int>(round(gradient * x_coords[i] + intersect))};\n        result.push_back(temp_coords);\n      }\n    } else {\n      return result;\n    }\n  }\n\n  return result;\n}\n\n/**\n * Get a bounding box based on coodinate centre and radius of box area.\n */\n\nstd::vector<std::vector<int>> get_border_corners(std::vector<int> centre, float radius)\n{\n  std::vector<std::vector<int>> result;\n  if (centre.size() == 2 && radius > 0 && centre[0] >= 0 && centre[1] >= 0) {\n    std::vector<int> top_left;\n    std::vector<int> bottom_right;\n    if (centre[0] - radius < 0) {\n      top_left.push_back(0);\n    } else {\n      top_left.push_back(static_cast<int>(round(centre[0] - radius)));\n    }\n    if (centre[1] - radius < 0) {\n      top_left.push_back(0);\n    } else {\n      top_left.push_back(static_cast<int>(round(centre[1] - radius)));\n    }\n    bottom_right = {static_cast<int>(round(centre[0] + radius)),\n      static_cast<int>(round(centre[1] + radius))};\n    result = {top_left, bottom_right};\n  } else {\n    return result;\n  }\n  return result;\n}\n\n/**\n * Make sure input is within 0 to Pi\n */\n\nfloat keep_angle_in_bounds(float input)\n{\n  if (input < 0 || input >= PI) {\n    if (input < 0) {\n      while (input < 0) {\n        input += PI;\n      }\n    }\n    if (input >= PI) {\n      while (input >= PI) {\n        input -= PI;\n      }\n    }\n  }\n  return input;\n}\n\n#endif  // PLANNING_FUNCTIONS_HPP_\n", "meta": {"hexsha": "6370b6230d4931e4e37d0e9ffdd91feec42a0f88", "size": 4393, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "grasp_planner/include/planning_functions.hpp", "max_stars_repo_name": "tanjpg/easy_manipulation_deployment", "max_stars_repo_head_hexsha": "83073fcebb25306619c4958fc98a74b1bf216141", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "grasp_planner/include/planning_functions.hpp", "max_issues_repo_name": "tanjpg/easy_manipulation_deployment", "max_issues_repo_head_hexsha": "83073fcebb25306619c4958fc98a74b1bf216141", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "grasp_planner/include/planning_functions.hpp", "max_forks_repo_name": "tanjpg/easy_manipulation_deployment", "max_forks_repo_head_hexsha": "83073fcebb25306619c4958fc98a74b1bf216141", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-01T07:11:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-01T07:11:35.000Z", "avg_line_length": 27.6289308176, "max_line_length": 93, "alphanum_fraction": 0.6462554063, "num_tokens": 1210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.63341026367784, "lm_q1q2_score": 0.4571595546086512}}
{"text": "#pragma once\n\n#include \"enum/enum.hpp\"\n#include \"matrix/sparsity_pattern/helpers.hpp\"\n\n#include <deal.II/lac/dynamic_sparsity_pattern.h>\n\nnamespace boltzmann {\n\ntemplate <enum METHOD>\nstruct vsparsity\n{\n};\n\ntemplate <>\nstruct vsparsity<METHOD::MODLEASTSQUARES>\n{\n  template <typename VELOCITY_VARFORM>\n  static void make(dealii::SparsityPattern& lhs_sparsity,\n                   dealii::SparsityPattern& rhs_sparsity,\n                   int N,\n                   const VELOCITY_VARFORM& var_form);\n};\n\ntemplate <typename VELOCITY_VARFORM>\nvoid\nvsparsity<METHOD::MODLEASTSQUARES>::make(dealii::SparsityPattern& lhs_vsparsity,\n                                         dealii::SparsityPattern& rhs_vsparsity,\n                                         int N,\n                                         const VELOCITY_VARFORM& var_form)\n{\n  dealii::DynamicSparsityPattern csp(N, N);\n  sparsity_helper::add_to_csp(csp, var_form.get_s0());\n  sparsity_helper::add_to_csp(csp, var_form.get_t2());\n  lhs_vsparsity.copy_from(csp);\n  lhs_vsparsity.compress();\n\n  dealii::DynamicSparsityPattern csp2(N, N);\n  sparsity_helper::add_to_csp(csp2, var_form.get_s0());\n  sparsity_helper::add_to_csp(csp2, var_form.get_t1());\n  rhs_vsparsity.copy_from(csp2);\n  rhs_vsparsity.compress();\n}\n\n}  // boltzmann\n", "meta": {"hexsha": "4ea27785554378888fe0ee35cc27d97b230382b2", "size": 1283, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/matrix/vsparsity.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/matrix/vsparsity.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/matrix/vsparsity.hpp", "max_forks_repo_name": "simonpintarelli/2dBoltzmann", "max_forks_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8913043478, "max_line_length": 80, "alphanum_fraction": 0.6687451286, "num_tokens": 329, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217431943271999, "lm_q2_score": 0.63341027059799, "lm_q1q2_score": 0.4571595520210494}}
{"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 *    References\n *      Musegaas, P. (2012). Optimization of Space Trajectories Including Multiple Gravity Assists\n *          and Deep Space Maneuvers. MSc Thesis, Delft University of Technology, Delft,\n *          The Netherlands.\n *\n */\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MAIN\n\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/unit_test.hpp>\n\n#include <Eigen/Core>\n\n#include <tudat/astro/basic_astro/physicalConstants.h>\n#include <tudat/basics/testMacros.h>\n\n#include \"tudat/astro/ephemerides/constantEphemeris.h\"\n#include \"tudat/astro/mission_segments/transferLeg.h\"\n#include \"tudat/astro/mission_segments/transferNode.h\"\n\nnamespace tudat\n{\nnamespace unit_tests\n{\n\n//! Test implementation of the swing-by leg within MGA trajectory model\nBOOST_AUTO_TEST_SUITE( test_swingby_leg_mga )\n\n//! Test delta-V computation\nBOOST_AUTO_TEST_CASE( testVelocities )\n{\n    // Set tolerance. Due to iterative nature in the process, (much) higher accuracy cannot be\n    // achieved.\n    const double tolerance = 1.0e-6;\n\n    // Expected test result based on the second leg of the ideal Cassini 1 trajectory as modelled\n    // by GTOP software distributed and downloadable from the ESA website, or within the PaGMO\n    // Astrotoolbox.\n    const double expectedDeltaV = 1090.64622926316;\n    const Eigen::Vector3d expectedArrivalVelocity (\n                37952.8844553685, -14096.9656774702, -5753.51245833761 );\n\n    // Specify the required parameters.\n    // Set the planetary positions and velocities.\n\n    // Specify the required parameters.\n    // Set the planetary positions and velocities.\n    const Eigen::Vector6d planet1State =\n            ( Eigen::Vector6d( ) <<\n              -35554348960.8278, -102574987127.178, 648696819.780156,\n              32851.224953746, -11618.7310059974, -2055.04615890989 ).finished( );\n    std::shared_ptr< ephemerides::Ephemeris > constantEphemeris1 =\n            std::make_shared< ephemerides::ConstantEphemeris >( planet1State );\n\n    const Eigen::Vector6d planet2State =\n            ( Eigen::Vector6d( ) <<\n              -35568329915.7073, -102569794949.529, 650816245.825226,\n              TUDAT_NAN, TUDAT_NAN, TUDAT_NAN ).finished( );\n    std::shared_ptr< ephemerides::Ephemeris > constantEphemeris2 =\n            std::make_shared< ephemerides::ConstantEphemeris >( planet2State );\n\n\n    // Set the time of flight, which has to be converted from JD (in GTOP) to seconds (in Tudat).\n    const double timeOfFlight = 449.385873819743 * physical_constants::JULIAN_DAY;\n\n    // Set the gravitational parameters\n    const double sunGravitationalParameter = 1.32712428e20;\n\n\n    using namespace mission_segments;\n    tudat::mission_segments::UnpoweredUnperturbedTransferLeg transferLeg(\n                constantEphemeris1, constantEphemeris2,\n                sunGravitationalParameter );\n    transferLeg.updateLegParameters( ( Eigen::VectorXd( 2 )<<0.0, timeOfFlight ).finished( ) );\n\n    // Set velocity before and after swingby body\n    Eigen::Vector3d velocityBeforePlanet1 (\n                34216.4827530912, -15170.1440677825, 395.792122152361 );\n    Eigen::Vector3d velocityAfterPlanet1 = transferLeg.getDepartureVelocity( );\n\n    // Set the planet gravitational parameters\n    const double planet1GravitationalParameter = 3.24860e14;\n\n    //set the minimum pericenter radius\n    const double minimumRadiusPlanet1 = 6351800;\n\n    SwingbyWithFixedOutgoingVelocity transferNode(\n                constantEphemeris1,\n                planet1GravitationalParameter, minimumRadiusPlanet1,\n                [=]( ){ return velocityBeforePlanet1; },\n                [=]( ){ return velocityAfterPlanet1; } );\n    transferNode.updateNodeParameters( ( Eigen::VectorXd( 1 ) << 0.0 ).finished( ) );\n\n    BOOST_CHECK_CLOSE_FRACTION( transferLeg.getLegDeltaV( ), 0.0, tolerance );\n    BOOST_CHECK_CLOSE_FRACTION( transferNode.getNodeDeltaV( ), expectedDeltaV, tolerance );\n\n    TUDAT_CHECK_MATRIX_CLOSE_FRACTION( transferLeg.getArrivalVelocity( ), expectedArrivalVelocity, tolerance );\n\n    // Get data on 10 equispace points on trajectory\n    std::map< double, Eigen::Vector6d > statesAlongTrajectory;\n    transferLeg.getStatesAlongTrajectory( statesAlongTrajectory, 10 );\n\n    // Check initial and final time on output list\n    BOOST_CHECK_SMALL( statesAlongTrajectory.begin( )->first, 1.0E-14 );\n    BOOST_CHECK_CLOSE_FRACTION( statesAlongTrajectory.rbegin( )->first, timeOfFlight, 1.0E-14 );\n\n    // Check if Keplerian state (slow elements) is the same for each output point\n    Eigen::Vector6d previousKeplerianState = Eigen::Vector6d::Constant( TUDAT_NAN );\n    for( auto it : statesAlongTrajectory )\n    {\n        Eigen::Vector6d currentCartesianState = it.second;\n        Eigen::Vector6d currentKeplerianState = tudat::orbital_element_conversions::convertCartesianToKeplerianElements(\n                    currentCartesianState, sunGravitationalParameter );\n        if( previousKeplerianState == previousKeplerianState )\n        {\n            TUDAT_CHECK_MATRIX_CLOSE_FRACTION(\n                        ( previousKeplerianState.segment( 0, 5 ) ),\n                        ( currentKeplerianState.segment( 0, 5 ) ),\n                        1.0E-14 );\n\n        }\n        previousKeplerianState = currentKeplerianState;\n    }\n\n    // Check if output meets boundary conditions\n    for( int i = 0; i < 3; i++ )\n    {\n        //TODO: Find out why tolerance needs to be so big for one of the legs\n        BOOST_CHECK_SMALL( std::fabs( statesAlongTrajectory.begin( )->second( i ) - planet1State( i ) ), 20.0E3 );\n        BOOST_CHECK_SMALL( std::fabs( statesAlongTrajectory.rbegin( )->second( i ) - planet2State( i ) ), 20.0E3 );\n    }\n}\n\n\nBOOST_AUTO_TEST_SUITE_END( )\n\n} // namespace unit_tests\n} // namespace tudat\n\n", "meta": {"hexsha": "e1e67c4b920eacc0102ea16ddd5ec9bcffdc303a", "size": 6197, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/src/astro/mission_segments/unitTestSwingbyLegMga.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": "tests/src/astro/mission_segments/unitTestSwingbyLegMga.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": "tests/src/astro/mission_segments/unitTestSwingbyLegMga.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": 41.0397350993, "max_line_length": 120, "alphanum_fraction": 0.7008229789, "num_tokens": 1606, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619436290699, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.45713979722618797}}
{"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_MULTIPLIES_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_MULTIPLIES_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n    @ingroup group-operator\n    Function object implementing multiplies capabilities\n\n    Perform the product of two parameters of the same type.\n\n    Infix notation can be used with operator '*',\n\n    @par Semantic\n\n    For any value @c a and @c b of type @c T,\n\n    @code\n    auto x = multiplies(a,b);\n    @endcode\n\n    or\n\n    @code\n    auto r = a*b;\n    @endcode\n\n    returns the product of @c a and @c b\n\n    @see fma, fms, fnma, fnms\n\n  **/\n  Value multiplies(Value const & x, Value const& y);\n} }\n#endif\n\n#include <boost/simd/function/scalar/multiplies.hpp>\n#include <boost/simd/function/simd/multiplies.hpp>\n\n#endif\n", "meta": {"hexsha": "682f8b9ed763cfc28eed4b8d27006301817a94c9", "size": 1188, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/multiplies.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/multiplies.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/multiplies.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": 22.4150943396, "max_line_length": 100, "alphanum_fraction": 0.5808080808, "num_tokens": 265, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743168019989179, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.45711362370326536}}
{"text": "//=======================================================================\r\n// Copyright 2001 Jeremy G. Siek, Andrew Lumsdaine, Lie-Quan Lee, \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 <fstream>              // for file I/O\r\n#include <boost/graph/graphviz.hpp>     // for read/write_graphviz()\r\n#include <boost/graph/dijkstra_shortest_paths.hpp>\r\n#include <boost/lexical_cast.hpp>\r\n\r\nnamespace boost {\r\n  enum graph_color_t { graph_color = 5556 };\r\n  BOOST_INSTALL_PROPERTY(graph, color);\r\n}\r\n\r\nint\r\nmain()\r\n{\r\n  using namespace boost;\r\n  typedef \r\n    adjacency_list<vecS, vecS, directedS,\r\n                   property<vertex_name_t, std::string>, \r\n                   property<edge_color_t, std::string,\r\n                            property<edge_weight_t, int> >,\r\n                   property<graph_color_t, std::string> >\r\n    g_dot_type;\r\n  g_dot_type g_dot;\r\n\r\n  dynamic_properties dp(ignore_other_properties);\r\n  dp.property(\"node_id\", get(vertex_name, g_dot));\r\n  dp.property(\"label\", get(edge_weight, g_dot));\r\n  dp.property(\"color\", get(edge_color, g_dot));\r\n  dp.property(\"color\", ref_property_map<g_dot_type*, std::string>(get_property(g_dot, graph_color)));\r\n  {\r\n    std::ifstream infile(\"figs/ospf-graph.dot\");\r\n    read_graphviz(infile, g_dot, dp);\r\n  }\r\n\r\n  typedef adjacency_list < vecS, vecS, directedS, no_property,\r\n    property < edge_weight_t, int > > Graph;\r\n  typedef graph_traits < Graph >::vertex_descriptor vertex_descriptor;\r\n  Graph g(num_vertices(g_dot));\r\n  graph_traits < g_dot_type >::edge_iterator ei, ei_end;\r\n  for (boost::tie(ei, ei_end) = edges(g_dot); ei != ei_end; ++ei) {\r\n    int weight = get(edge_weight, g_dot, *ei);\r\n    property < edge_weight_t, int >edge_property(weight);\r\n    add_edge(source(*ei, g_dot), target(*ei, g_dot), edge_property, g);\r\n  }\r\n\r\n  vertex_descriptor router_six;\r\n  graph_traits < g_dot_type >::vertex_iterator vi, vi_end;\r\n  for (boost::tie(vi, vi_end) = vertices(g_dot); vi != vi_end; ++vi)\r\n    if (\"RT6\" == get(vertex_name, g_dot, *vi)) {\r\n      router_six = *vi;\r\n      break;\r\n    }\r\n\r\n  std::vector < vertex_descriptor > parent(num_vertices(g));\r\n  // All vertices start out as there own parent\r\n  typedef graph_traits < Graph >::vertices_size_type size_type;\r\n  for (size_type p = 0; p < num_vertices(g); ++p)\r\n    parent[p] = p;\r\n\r\n#if defined(BOOST_MSVC) && BOOST_MSVC <= 1300\r\n  std::vector<int> distance(num_vertices(g));\r\n  property_map<Graph, edge_weight_t>::type weightmap = get(edge_weight, g);\r\n  property_map<Graph, vertex_index_t>::type indexmap = get(vertex_index, g);\r\n  dijkstra_shortest_paths\r\n    (g, router_six, &parent[0], &distance[0], weightmap,\r\n     indexmap, std::less<int>(), closed_plus<int>(), \r\n     (std::numeric_limits<int>::max)(), 0, default_dijkstra_visitor());\r\n#else\r\n  dijkstra_shortest_paths(g, router_six, predecessor_map(&parent[0]));\r\n#endif\r\n\r\n  graph_traits < g_dot_type >::edge_descriptor e;\r\n  for (size_type i = 0; i < num_vertices(g); ++i)\r\n    if (parent[i] != i) {\r\n      e = edge(parent[i], i, g_dot).first;\r\n      put(edge_color, g_dot, e, \"black\");\r\n    }\r\n\r\n  get_property(g_dot, graph_color) = \"grey\";\r\n  {\r\n    std::ofstream outfile(\"figs/ospf-sptree.dot\");\r\n    write_graphviz_dp(outfile, g_dot, dp);\r\n  }\r\n\r\n  std::ofstream rtable(\"routing-table.dat\");\r\n  rtable << \"Dest    Next Hop    Total Cost\" << std::endl;\r\n  for (boost::tie(vi, vi_end) = vertices(g_dot); vi != vi_end; ++vi)\r\n    if (parent[*vi] != *vi) {\r\n      rtable << get(vertex_name, g_dot, *vi) << \"    \";\r\n      vertex_descriptor v = *vi, child;\r\n      int path_cost = 0;\r\n      property_map < Graph, edge_weight_t >::type\r\n        weight_map = get(edge_weight, g);\r\n      do {\r\n        path_cost += get(weight_map, edge(parent[v], v, g).first);\r\n        child = v;\r\n        v = parent[v];\r\n      } while (v != parent[v]);\r\n      rtable << get(vertex_name, g_dot, child) << \"     \";\r\n      rtable << path_cost << std::endl;\r\n\r\n    }\r\n\r\n  return EXIT_SUCCESS;\r\n}\r\n", "meta": {"hexsha": "17a28c1a0665a5aecce7c6cf5c05aa757760d1f8", "size": 4168, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/graph/example/ospf-example.cpp", "max_stars_repo_name": "zyiacas/boost-doc-zh", "max_stars_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 198.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T05:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:46:46.000Z", "max_issues_repo_path": "libs/graph/example/ospf-example.cpp", "max_issues_repo_name": "sdfict/boost-doc-zh", "max_issues_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/graph/example/ospf-example.cpp", "max_forks_repo_name": "sdfict/boost-doc-zh", "max_forks_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 37.2142857143, "max_line_length": 102, "alphanum_fraction": 0.6118042226, "num_tokens": 1082, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743168019989179, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.45711362370326536}}
{"text": "#define BOOST_TEST_MODULE spherical_representation_test\n\n#include <boost/test/unit_test.hpp>\n#include <boost/units/quantity.hpp>\n#include <boost/units/systems/si/plane_angle.hpp>\n#include <boost/units/systems/si/prefixes.hpp>\n#include <boost/units/systems/si/length.hpp>\n#include <boost/units/systems/angle/degrees.hpp>\n#include <boost/astronomy/coordinate/arithmetic.hpp>\n#include <boost/astronomy/coordinate/representation.hpp>\n\nusing namespace std;\nusing namespace boost::astronomy::coordinate;\nusing namespace boost::units::si;\nusing namespace boost::geometry;\nusing namespace boost::units;\nnamespace bud = boost::units::degree;\n\nBOOST_AUTO_TEST_SUITE(spherical_representation_constructors)\n\nBOOST_AUTO_TEST_CASE(spherical_representation_default_constructor)\n{\n    //using set functions\n    spherical_representation<double, quantity<bud::plane_angle>, quantity<bud::plane_angle>,\n    quantity<si::length>> point1;\n    point1.set_lat_lon_dist(45.0 * bud::degrees, 18.0 * bud::degrees, 3.5 * meters);\n    BOOST_CHECK_CLOSE(point1.get_lat().value(), 45.0, 0.001);\n    BOOST_CHECK_CLOSE(point1.get_lon().value(), 18.0, 0.001);\n    BOOST_CHECK_CLOSE(point1.get_dist().value(), 3.5, 0.001);\n\n    //checking whether quantity stored is as expected or not\n    BOOST_TEST((std::is_same<decltype(point1.get_lat()), quantity<bud::plane_angle>>::value));\n    BOOST_TEST((std::is_same<decltype(point1.get_lon()), quantity<bud::plane_angle>>::value));\n    BOOST_TEST((std::is_same<decltype(point1.get_dist()), quantity<si::length>>::value));\n}\n\nBOOST_AUTO_TEST_CASE(spherical_representation_quantities_constructor)\n{\n    //checking construction from value\n    auto point1 = make_spherical_representation\n    (15.0 * bud::degrees, 39.0 * bud::degrees, 3.0*si::centi*meter);\n    BOOST_CHECK_CLOSE(point1.get_lat().value(), 15.0, 0.001);\n    BOOST_CHECK_CLOSE(point1.get_lon().value(), 39.0, 0.001);\n    BOOST_CHECK_CLOSE(point1.get_dist().value(), 3.0, 0.001);\n\n    //checking whether quantity stored is as expected or not\n    BOOST_TEST((std::is_same<decltype(point1.get_lat()), quantity<bud::plane_angle>>::value));\n    BOOST_TEST((std::is_same<decltype(point1.get_lon()), quantity<bud::plane_angle>>::value));\n    BOOST_TEST((std::is_same<decltype(point1.get_dist()), quantity<decltype(si::centi*meter)>>::value));\n\n    spherical_representation<double, quantity<bud::plane_angle>, quantity<bud::plane_angle>,\n    quantity<si::length>> point2(1.5 * bud::degrees, 9.0 * bud::degrees, 3.0 * meter);\n    BOOST_CHECK_CLOSE(point2.get_lat().value(), 1.5, 0.001);\n    BOOST_CHECK_CLOSE(point2.get_lon().value(), 9.0, 0.001);\n    BOOST_CHECK_CLOSE(point2.get_dist().value(), 3, 0.001);\n\n    //checking whether quantity stored is as expected or not\n    BOOST_TEST((std::is_same<decltype(point2.get_lat()), quantity<bud::plane_angle>>::value));\n    BOOST_TEST((std::is_same<decltype(point2.get_lon()), quantity<bud::plane_angle>>::value));\n    BOOST_TEST((std::is_same<decltype(point2.get_dist()), quantity<si::length>>::value));\n}\n\nBOOST_AUTO_TEST_CASE(spherical_representation_copy_constructor)\n{\n    //checking construction from value\n    auto point1 = make_spherical_representation\n    (15.0 * bud::degrees, 30.0 * bud::degrees, 3.0*si::centi*meter);\n    BOOST_CHECK_CLOSE(point1.get_lat().value(), 15.0, 0.001);\n    BOOST_CHECK_CLOSE(point1.get_lon().value(), 30.0, 0.001);\n    BOOST_CHECK_CLOSE(point1.get_dist().value(), 3, 0.001);\n\n    //checking whether quantity stored is as expected or not\n    BOOST_TEST((std::is_same<decltype(point1.get_lat()), quantity<bud::plane_angle>>::value));\n    BOOST_TEST((std::is_same<decltype(point1.get_lon()), quantity<bud::plane_angle>>::value));\n    BOOST_TEST((std::is_same<decltype(point1.get_dist()), quantity<decltype(si::centi*meter)>>::value));\n\n    //copy constructor\n    auto point2 = make_spherical_representation(point1);\n    BOOST_CHECK_CLOSE(point1.get_lat().value(), point2.get_lat().value(), 0.001);\n    BOOST_CHECK_CLOSE(point1.get_lon().value(), point2.get_lon().value(), 0.001);\n    BOOST_CHECK_CLOSE(point1.get_dist().value(), point2.get_dist().value(), 0.001);\n\n    //checking whether quantity stored is as expected or not\n    BOOST_TEST((std::is_same<decltype(point2.get_lat()), quantity<bud::plane_angle>>::value));\n    BOOST_TEST((std::is_same<decltype(point2.get_lon()), quantity<bud::plane_angle>>::value));\n    BOOST_TEST((std::is_same<decltype(point2.get_dist()), quantity<decltype(si::centi*meter)>>::value));\n}\n\nBOOST_AUTO_TEST_CASE(spherical_representation_copy_constructor_with_different_units)\n{\n    //checking construction from value\n    auto point1 = make_spherical_representation\n    (15.0 * bud::degrees, 10.0 * bud::degrees, 3.0*si::centi*meter);\n    BOOST_CHECK_CLOSE(point1.get_lat().value(), 15.0, 0.001);\n    BOOST_CHECK_CLOSE(point1.get_lon().value(), 10.0, 0.001);\n    BOOST_CHECK_CLOSE(point1.get_dist().value(), 3, 0.001);\n\n    //checking whether quantity stored is as expected or not\n    BOOST_TEST((std::is_same<decltype(point1.get_lat()), quantity<bud::plane_angle>>::value));\n    BOOST_TEST((std::is_same<decltype(point1.get_lon()), quantity<bud::plane_angle>>::value));\n    BOOST_TEST((std::is_same<decltype(point1.get_dist()), quantity<decltype(si::centi*meter)>>::value));\n\n    //Conversion from one unit type to other\n    auto point2 = make_spherical_representation\n    <double, quantity<bud::plane_angle>, quantity<bud::plane_angle>, quantity<si::length>>(point1);\n    BOOST_CHECK_CLOSE(point2.get_lat().value(), 15.0, 0.001);\n    BOOST_CHECK_CLOSE(point2.get_lon().value(), 10.0, 0.001);\n    BOOST_CHECK_CLOSE(point2.get_dist().value(), 0.03, 0.001);\n\n    //checking whether quantity stored is as expected or not\n    BOOST_TEST((std::is_same<decltype(point2.get_lat()), quantity<bud::plane_angle>>::value));\n    BOOST_TEST((std::is_same<decltype(point2.get_lon()), quantity<bud::plane_angle>>::value));\n    BOOST_TEST((std::is_same<decltype(point2.get_dist()), quantity<si::length>>::value));\n}\n\nBOOST_AUTO_TEST_CASE(spherical_representation_geometry_point_constructor)\n{\n    //constructing from boost::geometry::model::point\n    model::point<double, 3, cs::cartesian> model_point(30, 60, 10);\n    auto point1 = make_spherical_representation\n    <double,quantity<bud::plane_angle>,quantity<bud::plane_angle>,quantity<si::length>>(model_point);\n    BOOST_CHECK_CLOSE(point1.get_lat().value(), 63.434948822922, 0.001);\n    BOOST_CHECK_CLOSE(point1.get_lon().value(), 81.521286852914, 0.001);\n    BOOST_CHECK_CLOSE(point1.get_dist().value(), 67.823299831253, 0.001);\n\n    //checking whether quantity stored is as expected or not\n    BOOST_TEST((std::is_same<decltype(point1.get_lat()), quantity<bud::plane_angle>>::value));\n    BOOST_TEST((std::is_same<decltype(point1.get_lon()), quantity<bud::plane_angle>>::value));\n    BOOST_TEST((std::is_same<decltype(point1.get_dist()), quantity<si::length>>::value));\n\n    spherical_representation<double, quantity<bud::plane_angle>, quantity<bud::plane_angle>,\n    quantity<si::length>> point2(model_point);\n    BOOST_CHECK_CLOSE(point2.get_lat().value(), 63.434948822922, 0.001);\n    BOOST_CHECK_CLOSE(point2.get_lon().value(), 81.521286852914, 0.001);\n    BOOST_CHECK_CLOSE(point2.get_dist().value(), 67.823299831253, 0.001);\n\n    //checking whether quantity stored is as expected or not\n    BOOST_TEST((std::is_same<decltype(point2.get_lat()), quantity<bud::plane_angle>>::value));\n    BOOST_TEST((std::is_same<decltype(point2.get_lon()), quantity<bud::plane_angle>>::value));\n    BOOST_TEST((std::is_same<decltype(point2.get_dist()), quantity<si::length>>::value));\n} \n    \nBOOST_AUTO_TEST_CASE(spherical_representation_conversion_from_cartesian_representation)\n{   \n    //constructing from spherical representation\n    auto cartesian_point = make_cartesian_representation(20.0 * meters, 60.0 * meters, 1.0 * meter);\n    auto point1 = make_spherical_representation(cartesian_point);\n    BOOST_CHECK_CLOSE(point1.get_lat().value(), 1.2490457723983, 0.001);\n    BOOST_CHECK_CLOSE(point1.get_lon().value(), 1.5549862559121, 0.001);\n    BOOST_CHECK_CLOSE(point1.get_dist().value(), 63.253458403474, 0.001);\n\n    //checking whether quantity stored is as expected or not\n    BOOST_TEST((std::is_same<decltype(point1.get_lat()), quantity<si::plane_angle>>::value));\n    BOOST_TEST((std::is_same<decltype(point1.get_lon()), quantity<si::plane_angle>>::value));\n    BOOST_TEST((std::is_same<decltype(point1.get_dist()), quantity<si::length>>::value));\n}\n\nBOOST_AUTO_TEST_CASE(spherical_representation_conversion_from_spherical_equatorial_representation)\n{   \n    //constructing from spherical_equitorial representation\n    auto spherical_equatorial_point = make_spherical_equatorial_representation\n    (0.523599 * si::radian, 60.0 * bud::degrees, 1.0 * meter);\n    auto point2 = make_spherical_representation(spherical_equatorial_point);\n    BOOST_CHECK_CLOSE(point2.get_lat().value(), 0.523599, 0.001);\n    BOOST_CHECK_CLOSE(point2.get_lon().value(), 0.523598776, 0.001);\n    BOOST_CHECK_CLOSE(point2.get_dist().value(), 1.0, 0.001);\n\n    //checking whether quantity stored is as expected or not\n    BOOST_TEST((std::is_same<decltype(point2.get_lat()), quantity<si::plane_angle>>::value));\n    BOOST_TEST((std::is_same<decltype(point2.get_lon()), quantity<si::plane_angle>>::value));\n    BOOST_TEST((std::is_same<decltype(point2.get_dist()), quantity<si::length>>::value));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\nBOOST_AUTO_TEST_SUITE(spherical_representation_operators)\n\nBOOST_AUTO_TEST_CASE(spherical_representation_addition_operator)\n{\n    auto point1 = make_spherical_representation(15.0 * bud::degrees, 30.0 * bud::degrees, 10.0 * meters);\n    auto point2 = make_spherical_representation(30.0 * bud::degrees, 45.0 * bud::degrees, 20.0 * meters);\n\n    auto sum = make_spherical_representation(point1 + point2);\n\n    BOOST_CHECK_CLOSE(sum.get_lat().value(), 26.097805456, 0.001);\n    BOOST_CHECK_CLOSE(sum.get_lon().value(), 39.826115507, 0.001);\n    BOOST_CHECK_CLOSE(sum.get_dist().value(), 29.6909332103, 0.001);\n\n    //checking whether quantity stored is as expected or not\n    BOOST_TEST((std::is_same<decltype(sum.get_lat()), quantity<bud::plane_angle>>::value));\n    BOOST_TEST((std::is_same<decltype(sum.get_lon()), quantity<bud::plane_angle>>::value));\n    BOOST_TEST((std::is_same<decltype(sum.get_dist()), quantity<si::length>>::value));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\nBOOST_AUTO_TEST_SUITE(spherical_representation_arithmetic_functions)\n\n// BOOST_AUTO_TEST_CASE(spherical_representation_cross_product)\n// {\n//     auto point1 = make_spherical_representation(3.0 * bud::degrees, 50.0 * bud::degrees, 40.0 * meters);\n//     auto point2 = make_spherical_representation(30.0 * bud::degrees, 45.0 * bud::degrees, 14.0 * meters);\n\n//     auto result = cross(point1, point2);\n\n//     BOOST_CHECK_CLOSE(result.get_lat().value(), -143.4774246228, 0.001);\n//     BOOST_CHECK_CLOSE(result.get_lon().value(), 45.186034054587, 0.001);\n//     BOOST_CHECK_CLOSE(result.get_dist().value(), 195.39050840581, 0.001);\n\n//     //checking whether quantity stored is as expected or not\n//     BOOST_TEST((std::is_same<decltype(result.get_lat()), quantity\n//         <bu::multiply_typeof_helper<si::length, si::length>::type>>::value));\n//     BOOST_TEST((std::is_same<decltype(result.get_lon()), quantity\n//         <bu::multiply_typeof_helper<si::length, si::length>::type>>::value));\n//     BOOST_TEST((std::is_same<decltype(result.get_dist()), quantity\n//         <bu::multiply_typeof_helper<si::length, si::length>::type>>::value));\n// }\n\nBOOST_AUTO_TEST_CASE(spherical_representation_dot_product)\n{\n    auto point1 = make_spherical_representation(3.0 * bud::degrees, 50.0 * bud::degrees, 40.0 * meters);\n    auto point2 = make_spherical_representation(30.0 * bud::degrees, 45.0 * bud::degrees, 14.0 * meters);\n\n    auto result = dot(point1, point2);\n\n    BOOST_CHECK_CLOSE(result.value(), 524.807154, 0.001);\n\n    //checking whether quantity stored is as expected or not\n    BOOST_TEST((std::is_same<decltype(result), quantity\n        <bu::multiply_typeof_helper<si::length, si::length>::type>>::value));\n}\n\n// BOOST_AUTO_TEST_CASE(spherical_representation_unit_vector)\n// {\n//     auto point1 = make_spherical_representation(25.0 * bud::degrees, 30.0 * bud::degrees, 90.0*meter);\n\n//     auto result = boost::astronomy::coordinate::unit_vector(point1);\n\n//     BOOST_CHECK_CLOSE(result.get_lat().value(), 25.0, 0.001);\n//     BOOST_CHECK_CLOSE(result.get_lon().value(), 30.0, 0.001);\n//     BOOST_CHECK_CLOSE(result.get_dist().value(), 1, 0.001);\n\n//     //checking whether quantity stored is as expected or not\n//     BOOST_TEST((std::is_same<decltype(result.get_lat()), quantity<bud::plane_angle>>::value));\n//     BOOST_TEST((std::is_same<decltype(result.get_lon()), quantity<bud::plane_angle>>::value));\n//     BOOST_TEST((std::is_same<decltype(result.get_dist()), quantity<si::length>>::value));\n// }\n\nBOOST_AUTO_TEST_CASE(spherical_representation_magnitude)\n{\n    auto point1 = make_spherical_representation(25.0 * bud::degrees, 36.0 * bud::degrees, 9.0 * meters);\n\n    auto result = boost::astronomy::coordinate::magnitude(point1);\n\n    BOOST_CHECK_CLOSE(result.value(), 9, 0.001);\n\n    //checking whether quantity stored is as expected or not\n    BOOST_TEST((std::is_same<decltype(result), quantity<si::length>>::value));\n\n}\n\nBOOST_AUTO_TEST_CASE(spherical_representation_sum)\n{\n    auto point1 = make_spherical_representation(15.0 * bud::degrees, 30.0 * bud::degrees, 10.0 * meters);\n    auto point2 = make_spherical_representation(30.0 * bud::degrees, 45.0 * bud::degrees, 20.0 * meters);\n\n    auto result = boost::astronomy::coordinate::sum(point1, point2);\n\n    BOOST_CHECK_CLOSE(result.get_lat().value(), 26.097805456, 0.001);\n    BOOST_CHECK_CLOSE(result.get_lon().value(), 39.826115507, 0.001);\n    BOOST_CHECK_CLOSE(result.get_dist().value(), 29.6909332103, 0.001);\n\n    //checking whether quantity stored is as expected or not\n    BOOST_TEST((std::is_same<decltype(result.get_lat()), quantity<bud::plane_angle>>::value));\n    BOOST_TEST((std::is_same<decltype(result.get_lon()), quantity<bud::plane_angle>>::value));\n    BOOST_TEST((std::is_same<decltype(result.get_dist()), quantity<si::length>>::value));\n}\n\nBOOST_AUTO_TEST_CASE(spherical_representation_mean)\n{\n    auto point1 = make_spherical_representation(15.0 * bud::degrees, 30.0 * bud::degrees, 10.0 * meter);\n    auto point2 = make_spherical_representation(30.0 * bud::degrees, 45.0 * bud::degrees, 20.0 * meter);\n\n    auto result = boost::astronomy::coordinate::mean(point1, point2);\n\n    BOOST_CHECK_CLOSE(result.get_lat().value(), 26.097805456543, 0.001);\n    BOOST_CHECK_CLOSE(result.get_lon().value(), 39.826115384099, 0.001);\n    BOOST_CHECK_CLOSE(result.get_dist().value(), 14.845466643593, 0.001);\n\n    //checking whether quantity stored is as expected or not\n    BOOST_TEST((std::is_same<decltype(result.get_lat()), quantity<bud::plane_angle>>::value));\n    BOOST_TEST((std::is_same<decltype(result.get_lon()), quantity<bud::plane_angle>>::value));\n    BOOST_TEST((std::is_same<decltype(result.get_dist()), quantity<si::length>>::value));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "9355ceb0c1e5406f0c254a13e0dd5abd7ddfff6b", "size": 15163, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/coordinate/spherical_representation.cpp", "max_stars_repo_name": "sarthak2007/astronomy", "max_stars_repo_head_hexsha": "dad10fe9fe4d704a6ecbfbd561693f8bb1285a54", "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": "test/coordinate/spherical_representation.cpp", "max_issues_repo_name": "sarthak2007/astronomy", "max_issues_repo_head_hexsha": "dad10fe9fe4d704a6ecbfbd561693f8bb1285a54", "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/coordinate/spherical_representation.cpp", "max_forks_repo_name": "sarthak2007/astronomy", "max_forks_repo_head_hexsha": "dad10fe9fe4d704a6ecbfbd561693f8bb1285a54", "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": 51.0538720539, "max_line_length": 108, "alphanum_fraction": 0.726439359, "num_tokens": 3954, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4571136167055967}}
{"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\u00e4nkt), 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_FROBENIUS_NORM_INCLUDE\n#define MTL_FROBENIUS_NORM_INCLUDE\n\n#include <boost/numeric/mtl/concept/collection.hpp>\n#include <boost/numeric/mtl/utility/is_row_major.hpp>\n#include <boost/numeric/mtl/utility/tag.hpp>\n#include <boost/numeric/mtl/utility/range_generator.hpp>\n#include <boost/numeric/mtl/utility/property_map.hpp>\n#include <boost/numeric/mtl/operation/max_of_sums.hpp>\n#include <boost/numeric/mtl/operation/squared_abs.hpp>\n#include <boost/numeric/linear_algebra/identity.hpp>\n#include <boost/numeric/mtl/interface/vpt.hpp>\n\n\nnamespace mtl { namespace mat {\n\n/// Frobenius norm, i.e. square root of sum of squares of all entries: \\f$\\sqrt{\\sum_i \\sum_j|a_{ij}|^2}\\f$. \ntemplate <typename Matrix>\ntypename RealMagnitude<typename Collection<Matrix>::value_type>::type\ninline frobenius_norm(const Matrix& matrix)\n{\n    vampir_trace<3010> tracer;\n    using std::sqrt; using std::abs; using math::zero;\n    namespace traits = mtl::traits;\n    typename traits::const_value<Matrix>::type     value(matrix); \n\n    typedef typename Collection<Matrix>::value_type   value_type;\n    typedef typename RealMagnitude<value_type>::type  real_type;\n    real_type ref, sum= zero(ref);\n\n    typedef typename traits::range_generator<tag::major, Matrix>::type     cursor_type;\n    typedef typename traits::range_generator<tag::nz, cursor_type>::type   icursor_type;\n\n    for (cursor_type cursor = begin<tag::major>(matrix), cend = end<tag::major>(matrix); cursor != cend; ++cursor) \n\tfor (icursor_type icursor = begin<tag::nz>(cursor), icend = end<tag::nz>(cursor); icursor != icend; ++icursor) \n\t    sum+= squared_abs(value(*icursor));\n    return sqrt(sum);\n}\n\n}} // namespace mtl::matrix\n\n#endif // MTL_FROBENIUS_NORM_INCLUDE\n", "meta": {"hexsha": "04bcc82d87291477acb5035c144f8b2d380b7014", "size": 2171, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/mtl/operation/frobenius_norm.hpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "boost/numeric/mtl/operation/frobenius_norm.hpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "boost/numeric/mtl/operation/frobenius_norm.hpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.4727272727, "max_line_length": 115, "alphanum_fraction": 0.7360663289, "num_tokens": 567, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4571136167055967}}
{"text": " /* Copyright (c) 2016, Michal Startek\n  * \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  *\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 HOLDER\n  * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n  */\n\n\n\n#include <random>\n#include <boost/random.hpp>\n#include <boost/random/random_device.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <boost/random/binomial_distribution.hpp>\n#include <unordered_map>\n\n\n#define DO_CLOCK(str) { std::cout << str << \": \" << ((double)(clock() - timer))/CLOCKS_PER_SEC << std::endl; timer = clock(); }\n\nstd::random_device rd;\nstd::mt19937 gen(rd());\nboost::random::mt19937 rng(rd());\n\nstd::uniform_real_distribution<double> stdunif(0.0, 1.0);\n\n\ninline double beta_1_b(double b, std::mt19937 rdev = gen)\n{\n\treturn 1.0 - pow(stdunif(rdev), 1.0/b);\n}\n\n\ninline int binom(int tries, double succ_prob, boost::random::mt19937 rdev = rng)\n{\n\tif (succ_prob >= 1.0)\n\t\treturn tries;\n\tboost::random::binomial_distribution<> bd(tries, succ_prob);\n\tboost::variate_generator<boost::mt19937&, boost::random::binomial_distribution<> > var_b(rdev, bd);\n\treturn var_b();\n}\n\n\n\n\n\nvoid sample(const double* probs, unsigned int* samplespace, unsigned int samples, double switchover = 1.0, double total_prob = 1.0, std::mt19937 crdev = gen, boost::random::mt19937 boost_rdev = rng)\n/* Generates a random sample from population 0..n-1 with probabilities probs, and saves it to\n * table sample (which must be of size equal to samples parameter). Parameter switchover controls \n * preference between beta and binomial modes.\n */\n{\n\tdouble pprob = 0.0;\n\tdouble cprob = 0.0;\n\tunsigned int pidx = 0;\n\tunsigned int sampleidx = 0;\n\twhile(samples > 0)\n\t{\n\t\tpprob += probs[pidx];\n\t\twhile(((pprob - cprob) * samples / (total_prob - cprob)) < switchover)\n\t\t{\n\t\t\tcprob += beta_1_b(samples, crdev) * (total_prob - cprob);\n\t\t\twhile(pprob < cprob)\n\t\t\t\tpprob += probs[++pidx];\n\t\t\tsamplespace[sampleidx++] = pidx;\n\t\t\tsamples--;\n\t\t\tif(samples == 0)\n\t\t\t\tbreak;\n\t\t}\n\t\tif(samples == 0)\n\t\t\tbreak;\n\t\tunsigned int nrtaken = binom(samples, (pprob-cprob)/(total_prob-cprob)), boost_rdev;\n\t\tfor(unsigned int i=0; i<nrtaken; i++)\n\t\t\tsamplespace[sampleidx++] = pidx;\n\t\tsamples -= nrtaken;\n\t\tpidx++;\n\t\tcprob = pprob;\n\t}\n}\n\nvoid sample_cntr(const double* probs, unsigned int* sample, unsigned int popsize, unsigned int samples, double switchover = 1.0)\n/* Generates a random sample from population 0..n-1 with probabilities probs, and saves counts to\n * the table sample (which must be of size popsize). Parameter switchover controls\n * preference between beta and binomial modes.\n */\n{\n\tmemset(sample, 0, sizeof(int)*popsize);\n        double pprob = 0.0;\n        double cprob = 0.0;\n        unsigned int pidx = 0;\n        while(samples > 0)\n        {\n                pprob += probs[pidx];\n                while(((pprob - cprob) * samples / (1.0 - cprob)) < switchover)\n                {\n                        cprob += beta_1_b(samples) * (1.0 - cprob);\n                        while(pprob < cprob)\n                                pprob += probs[++pidx];\n\t\t\tsample[pidx] += 1;\n                        samples--;\n                        if(samples == 0)\n                                break;\n                }\n                if(samples == 0)\n                        break;\n                unsigned int nrtaken = binom(samples, (pprob-cprob)/(1.0-cprob));\n\t\tsample[pidx] += nrtaken;\n                samples -= nrtaken;\n                pidx++;\n                cprob = pprob;\n        }\n}\n\nstd::unordered_map<int, int>* sample_ht(const double* probs, unsigned int samples, double switchover)\n/* Generates a random sample from population 0..n-1 with probabilities probs, and returns a hashtable\n * containing the counts. Parameter switchover controls preference between beta and binomial modes.\n */\n{\n\tstd::unordered_map<int, int>* sampl_multiset = new std::unordered_map<int, int>();\n        double pprob = 0.0;\n        double cprob = 0.0;\n        unsigned int pidx = 0;\n        while(samples > 0)\n        {\n                pprob += probs[pidx];\n                while(((pprob - cprob) * samples / (1.0 - cprob)) < switchover)\n                {\n                        cprob += beta_1_b(samples) * (1.0 - cprob);\n                        while(pprob < cprob)\n                                pprob += probs[++pidx];\n\t\t\tif(sampl_multiset->find(pidx) == sampl_multiset->end())\n\t\t\t\t(*sampl_multiset)[pidx] = 1;\n\t\t\telse\n\t\t\t\t(*sampl_multiset)[pidx] += 1;\n                        samples--;\n                        if(samples == 0)\n                                break;\n                }\n                if(samples == 0)\n                        break;\n                unsigned int nrtaken = binom(samples, (pprob-cprob)/(1.0-cprob));\n\t\tif(nrtaken > 0)\n\t\t{\n\t\t\tif(sampl_multiset->find(pidx) == sampl_multiset->end())\n\t\t\t\t(*sampl_multiset)[pidx] = nrtaken;\n\t\t\telse\n\t\t\t\t(*sampl_multiset)[pidx] += nrtaken;\n\t\t}\n                samples -= nrtaken;\n                pidx++;\n                cprob = pprob;\n        }\n        return sampl_multiset;\n\n}\n\n\n/* \n * The following is a multithreaded implementation of the above\n */\n\n\n\n\n#ifdef THREADS\n#include <pthread.h>\n#include <sstream>\n\nstruct threadargs_t\n{\n        const double* probs;\n\tunsigned int probsstart;\n\tunsigned int probsend;\n        unsigned int* samplespace;\n        unsigned int totalsamples;\n        double switchover;\n        double* fragment_probs;\n\tunsigned int* fragment_sizes;\n        unsigned int thread_id;\n\tpthread_barrier_t* barrier;\n\tunsigned int no_threads;\n\tunsigned int pidx;\n};\n\ntemplate<typename T> void print_array(T* array, unsigned int size)\n{\n\tstd::cout << \"-------------------------------------\" << std::endl;\n\tfor(int ii=0; ii<size; ii++)\n\t\tstd::cout << array[ii] << \" \";\n\tstd::cout << std::endl << \"-------------------------------------\" << std::endl;\n}\n\n\nvoid sample_threadfunc(threadargs_t* args)\n{\n\tclock_t timer = clock();\n\tstd::random_device rd;\n\tstd::mt19937 gen(rd());\n\tboost::random::mt19937 rng(rd());\n\n\tif(args->thread_id == 0)\n\t\tDO_CLOCK(\"RNG init\");\n\n\tdouble myprobs = 0.0;\n\tconst double* mprobs = args->probs;\n\tunsigned int mprobsstart = args->probsstart;\n\tunsigned int mprobsend = args->probsend;\n\tfor (int ii = mprobsstart; ii < mprobsend; ii++)\n\t\tmyprobs += args->probs[ii];\n\n\tif(args->thread_id == 0)\n\t\tDO_CLOCK(\"After MT init\")\n\t\n\targs->fragment_probs[args->thread_id] = myprobs;\n\n\tint leader = pthread_barrier_wait(args->barrier);\n\n\tif(args->thread_id == 0)\n\t\tDO_CLOCK(\"First barrier\");\n\n\tif(leader == PTHREAD_BARRIER_SERIAL_THREAD)\n\t\t/* Deliberately not using switchover arg. Even if input has weird distribution which justifies it,\n\t\t * this distribution is different. */\n\t\tsample_cntr(args->fragment_probs, args->fragment_sizes, args->no_threads, args->totalsamples);\n\n\tpthread_barrier_wait(args->barrier);\n\n\tif(args->thread_id == 0)\n\t\tDO_CLOCK(\"Sample_cntr, second barrier\");\n\n\t/* Probably faster to compute this in each thread from scratch, like this,\n\t * than to synchronise again just to compute this... */\n\tunsigned int* samplespace = args->samplespace;\n\tfor(int ii=0; ii<args->thread_id; ii++)\n\t\tsamplespace += args->fragment_sizes[ii];\n\n\tunsigned int samples = args->fragment_sizes[args->thread_id];\n\tdouble switchover = args->switchover;\n\t\n\t/* Sadly, not *quite* the same as the single-threaded version above... */\n\n\t#if 0\n\tdouble correction = 1.0/myprobs;\n        double pprob = 0.0;\n        double cprob = 0.0;\n\tconst double* probs = args->probs;\n\t\n        unsigned int pidx = args->probsstart;\n        unsigned int sampleidx = 0;\n        while(samples > 0)\n        {\n                pprob += probs[pidx];\n                while(((pprob - cprob) * samples / (myprobs - cprob)) < switchover)\n                {\n                        cprob += beta_1_b(samples, gen) * (myprobs - cprob);\n                        while(pprob < cprob)\n                                pprob += probs[++pidx]*correction;\n                        samplespace[sampleidx++] = pidx;\n                        samples--;\n                        if(samples == 0)\n                                break;\n                }\n                if(samples == 0)\n                        break;\n                unsigned int nrtaken = binom(samples, (pprob-cprob)/(myprobs-cprob), rng);\n                for(unsigned int i=0; i<nrtaken; i++)\n                        samplespace[sampleidx++] = pidx;\n                samples -= nrtaken;\n                pidx++;\n                cprob = pprob;\n        }\n\t#endif\n\n\tstd::stringstream s;\n\ts << \"Calling sample with args: probs: \" << args->probs+args->probsstart << \" samplespace: \" << samplespace << \" samples: \" << samples << \" switchover: \" << args->switchover << \" totalprobs: \" << myprobs << std::endl;\n\tstd::cout << s.str();\n\tsample(args->probs+args->probsstart, samplespace, samples, args->switchover, myprobs);\n\n\tif(args->thread_id == 0)\n\t        DO_CLOCK(\"After main loop\");\n\n}\n\nvoid sample_multithreaded(const double* probs, unsigned int* samplespace, unsigned int popsize, unsigned int samples, double switchover = 1.0, unsigned int no_threads = 1)\n{\n\tclock_t timer = clock();\n\n\t\n        if(1 || no_threads == 1)\n\t{\n\t\tstd::cout << \"Calling sample with args: probs: \" << probs << \" samplespace: \" << samplespace << \" samples: \" << samples << \" switchover: \" << switchover << \" totalprobs: 1.0\"  << std::endl;\n                //return sample(probs, samplespace, samples, switchover);\n\t\tsample(probs, samplespace, samples, switchover);\n\t\tDO_CLOCK(\"Single-threaded\")\n\t}\n        threadargs_t* threadargs = new threadargs_t[no_threads];\n        double* fragment_probs = new double[no_threads];\n\tunsigned int* fragment_sizes = new unsigned int[no_threads];\n\n        pthread_barrier_t barrier;\n        pthread_barrier_init(&barrier, nullptr, no_threads);\n\n        pthread_t* thread_ids = new pthread_t[no_threads];\n\n\tunsigned int perthread = popsize / no_threads;\n\tif(popsize % no_threads > 0)\n\t\tperthread++;\n\n\tDO_CLOCK(\"MT_init\");\n        for(unsigned int ii=0; ii<no_threads; ii++)\n        {\n                threadargs[ii].thread_id = ii;\n\t\tthreadargs[ii].probs = probs;\n\t\tthreadargs[ii].probsstart = perthread*ii;\n\t\tthreadargs[ii].probsend = std::min(perthread*(ii+1), popsize);\n\t\tthreadargs[ii].samplespace = samplespace;\n\t\tthreadargs[ii].totalsamples = samples;\n\t\tthreadargs[ii].switchover = 1.0;\n\t\tthreadargs[ii].fragment_probs = fragment_probs;\n\t\tthreadargs[ii].fragment_sizes = fragment_sizes;\n\t\tthreadargs[ii].barrier = &barrier;\n\t\tthreadargs[ii].no_threads = no_threads;\n\n\t\tassert(pthread_create(&thread_ids[ii], NULL, (void* (*)(void*)) sample_threadfunc, &threadargs[ii]) == 0);\n\n        }\n\tDO_CLOCK(\"MT: spawned threads\");\n\n\tfor(unsigned int ii=0; ii<no_threads; ii++)\n\t{\n\t\tpthread_join(thread_ids[ii], nullptr);\n\t}\n\tDO_CLOCK(\"Multithreaded body\");\n\n\n\tdelete[] threadargs;\n\tdelete[] fragment_probs;\n\tdelete[] fragment_sizes;\n\tdelete[] thread_ids;\n\tpthread_barrier_destroy(&barrier);\n\n}\n#endif /* THREADS */\n\n\n\n\nint main(int argc, char** argv)\n{\n\tint popsize = atoi(argv[1]);\n\tint samplesize = atoi(argv[2]);\n\tint threads = atoi(argv[3]);\n\n\tdouble* probs = new double[popsize];\n\tunsigned int* samplespace = new unsigned int[samplesize];\n\n\tdouble csum = 0.0;\n\tfor (int ii=0; ii<popsize; ii++)\n\t{\n\t\tprobs[ii] = stdunif(gen);\n\t\tcsum += probs[ii];\n\t}\n\tfor (int ii=0; ii<popsize; ii++)\n\t\tprobs[ii] /= csum;\n\n\tclock_t timer = clock();\n\tsample_multithreaded(probs, samplespace, popsize, samplesize, 1.0, threads);\n\tstd::cout << ((double)(clock() - timer))/CLOCKS_PER_SEC << std::endl;\n\n//\tfor (int ii=0; ii<samplesize; ii++)\n//\t\tstd::cout << samplespace[ii] << std::endl;\n\n\tdelete[] probs;\n\tdelete[] samplespace;\n\t\n}\n", "meta": {"hexsha": "9a196ddad5cf237dc5244c226f2b801c40f0077d", "size": 12861, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sampling/sample.cpp", "max_stars_repo_name": "michalsta/stats", "max_stars_repo_head_hexsha": "bbfae1d5fd8f7810cfccc97e4f424dfac58239f7", "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": "sampling/sample.cpp", "max_issues_repo_name": "michalsta/stats", "max_issues_repo_head_hexsha": "bbfae1d5fd8f7810cfccc97e4f424dfac58239f7", "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": "sampling/sample.cpp", "max_forks_repo_name": "michalsta/stats", "max_forks_repo_head_hexsha": "bbfae1d5fd8f7810cfccc97e4f424dfac58239f7", "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.4772727273, "max_line_length": 218, "alphanum_fraction": 0.6218023482, "num_tokens": 3344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4571136167055967}}
{"text": "#ifdef MEX\n\n#include <igl/copyleft/cgal/signed_distance_isosurface.h>\n#include <igl/copyleft/offset_surface.h>\n#include <igl/matlab/validate_arg.h>\n#include <igl/matlab/MexStream.h>\n#include <igl/matlab/mexErrMsgTxt.h>\n#include <igl/matlab/prepare_lhs.h>\n#include <igl/matlab/parse_rhs.h>\n#include <igl/C_STR.h>\n\n#include <mex.h>\n#include <Eigen/Dense>\n#include <iostream>\n\n#include <cstring>\n\nenum ContouringMethod\n{\n  CONTOURING_METHOD_MARCHING_CUBES = 0,\n  CONTOURING_METHOD_CGAL = 1,\n  NUM_CONTOURING_METHOD = 2,\n};\n\nvoid parse_rhs(\n  const int nrhs, \n  const mxArray *prhs[], \n  Eigen::MatrixXd & IV,\n  Eigen::MatrixXi & IF,\n  double & level,\n  double & angle_bound,\n  double & radius_bound,\n  double & distance_bound,\n  igl::SignedDistanceType & type,\n  ContouringMethod & contouring_method,\n  int & grid_size)\n{\n  using namespace std;\n  using namespace igl;\n  using namespace igl::matlab;\n  using namespace Eigen;\n  mexErrMsgTxt(nrhs >= 2, \"The number of input arguments must be >=2.\");\n\n  const int dim = mxGetN(prhs[0]);\n  mexErrMsgTxt(dim == 3,\n    \"Mesh vertex list must be #V by 3 list of vertex positions\");\n\n  parse_rhs_double(prhs,IV);\n  parse_rhs_index(prhs+1,IF);\n\n  // defaults\n  level = 0.0;\n  angle_bound = 28.0;\n  double bbd = 1.0;\n  // Radius and distance in terms of fraction of bbd\n  if(IV.size() > 0)\n  {\n    bbd = (IV.colwise().maxCoeff()-IV.colwise().minCoeff()).norm();\n  }\n  radius_bound = 0.02*bbd;\n  distance_bound = 0.02*bbd;\n  type = SIGNED_DISTANCE_TYPE_DEFAULT;\n  contouring_method = CONTOURING_METHOD_MARCHING_CUBES;\n  grid_size = 40;\n\n  {\n    int i = 2;\n    while(i<nrhs)\n    {\n      mexErrMsgTxt(mxIsChar(prhs[i]),\"Parameter names should be strings\");\n      // Cast to char\n      const char * name = mxArrayToString(prhs[i]);\n      if(strcmp(\"Level\",name) == 0)\n      {\n        validate_arg_double(i,nrhs,prhs,name);\n        validate_arg_scalar(i,nrhs,prhs,name);\n        level = (double)*mxGetPr(prhs[++i]);\n      }else if(strcmp(\"GridSize\",name) == 0)\n      {\n        validate_arg_double(i,nrhs,prhs,name);\n        validate_arg_scalar(i,nrhs,prhs,name);\n        grid_size = (int)*mxGetPr(prhs[++i]);\n      }else if(strcmp(\"AngleBound\",name) == 0)\n      {\n        validate_arg_double(i,nrhs,prhs,name);\n        validate_arg_scalar(i,nrhs,prhs,name);\n        angle_bound = (double)*mxGetPr(prhs[++i]);\n      }else if(strcmp(\"RadiusBound\",name) == 0)\n      {\n        validate_arg_double(i,nrhs,prhs,name);\n        validate_arg_scalar(i,nrhs,prhs,name);\n        radius_bound = ((double)*mxGetPr(prhs[++i])) * bbd;\n      }else if(strcmp(\"DistanceBound\",name) == 0)\n      {\n        validate_arg_double(i,nrhs,prhs,name);\n        validate_arg_scalar(i,nrhs,prhs,name);\n        distance_bound = ((double)*mxGetPr(prhs[++i])) * bbd;\n      }else if(strcmp(\"ContouringMethod\",name) == 0)\n      {\n        validate_arg_char(i,nrhs,prhs,name);\n        const char * contouring_name = mxArrayToString(prhs[++i]);\n        if(strcmp(\"cgal\",contouring_name)==0)\n        {\n          contouring_method = CONTOURING_METHOD_CGAL;\n        }else if(strcmp(\"marching_cubes\",contouring_name)==0)\n        {\n          contouring_method = CONTOURING_METHOD_MARCHING_CUBES;\n        }\n      }else if(strcmp(\"SignedDistanceType\",name) == 0)\n      {\n        validate_arg_char(i,nrhs,prhs,name);\n        const char * type_name = mxArrayToString(prhs[++i]);\n        if(strcmp(\"pseudonormal\",type_name)==0)\n        {\n          type = igl::SIGNED_DISTANCE_TYPE_PSEUDONORMAL;\n        }else if(strcmp(\"winding_number\",type_name)==0)\n        {\n          type = igl::SIGNED_DISTANCE_TYPE_WINDING_NUMBER;\n        }else if(strcmp(\"default\",type_name)==0)\n        {\n          type = igl::SIGNED_DISTANCE_TYPE_DEFAULT;\n        }else if(strcmp(\"unsigned\",type_name)==0)\n        {\n          type = igl::SIGNED_DISTANCE_TYPE_UNSIGNED;\n        }else\n        {\n          mexErrMsgTxt(false,C_STR(\"Unknown SignedDistanceType: \"<<type_name));\n        }\n      }else\n      {\n        mexErrMsgTxt(false,\"Unknown parameter\");\n      }\n      i++;\n    }\n  }\n\n  if(type != igl::SIGNED_DISTANCE_TYPE_UNSIGNED)\n  {\n    mexErrMsgTxt(dim == mxGetN(prhs[1]),\n      \"Mesh \\\"face\\\" simplex size must equal dimension\");\n  }\n}\n\nvoid mexFunction(\n  int nlhs, mxArray *plhs[], \n  int nrhs, const mxArray *prhs[])\n{\n  using namespace std;\n  using namespace Eigen;\n  using namespace igl;\n  using namespace igl::matlab;\n  using namespace igl::copyleft::cgal;\n\n  igl::matlab::MexStream mout;        \n  std::streambuf *outbuf = cout.rdbuf(&mout);\n  //mexPrintf(\"Compiled at %s on %s\\n\",__TIME__,__DATE__);\n\n  MatrixXd IV,V;\n  MatrixXi IF,F;\n  double level,angle_bound,radius_bound,distance_bound;\n  SignedDistanceType type;\n  ContouringMethod contouring_method;\n  int grid_size;\n  parse_rhs(\n    nrhs,prhs,\n    IV,IF,\n    level,angle_bound,radius_bound,distance_bound,type,\n    contouring_method, grid_size);\n  Eigen::MatrixXd GV;\n  Eigen::RowVector3i side;\n  Eigen::VectorXd S;\n  switch(contouring_method)\n  {\n    default:\n    case CONTOURING_METHOD_MARCHING_CUBES:\n      {\n        igl::copyleft::offset_surface(IV,IF,level,grid_size,type,V,F,GV,side,S);\n      }\n      break;\n    case CONTOURING_METHOD_CGAL:\n      signed_distance_isosurface(\n        IV,IF,level,angle_bound,radius_bound,distance_bound,type,V,F);\n      break;\n  }\n  switch(nlhs)\n  {\n    default:\n    {\n      mexErrMsgTxt(false,\"Too many output parameters.\");\n    }\n    case 5:\n    {\n      prepare_lhs_double(S,plhs+4);\n      // Fall through\n    }\n    case 4:\n    {\n      prepare_lhs_double(side,plhs+3);\n      // Fall through\n    }\n    case 3:\n    {\n      prepare_lhs_double(GV,plhs+2);\n      // Fall through\n    }\n    case 2:\n    {\n      prepare_lhs_index(F,plhs+1);\n      // Fall through\n    }\n    case 1:\n    {\n      prepare_lhs_double(V,plhs+0);\n      // Fall through\n    }\n    case 0: break;\n  }\n\n  // Restore the std stream buffer Important!\n  std::cout.rdbuf(outbuf);\n}\n\n#endif\n", "meta": {"hexsha": "b9cbfb852e7f8370fd7b325ede1fb527b57cd97c", "size": 5916, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Geometry_Processing_Toolbox/src/cppmex/signed_distance_isosurface.cpp", "max_stars_repo_name": "sidgairo18/SCILAB_MEX_TOOLBOX", "max_stars_repo_head_hexsha": "fc679f6d226c03b992b632823a5e57abea05cefa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-09-16T19:46:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-11T14:51:37.000Z", "max_issues_repo_path": "Geometry_Processing_Toolbox/src/cppmex/signed_distance_isosurface.cpp", "max_issues_repo_name": "sidgairo18/SCILAB_MEX_TOOLBOX", "max_issues_repo_head_hexsha": "fc679f6d226c03b992b632823a5e57abea05cefa", "max_issues_repo_licenses": ["MIT"], "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_Processing_Toolbox/src/cppmex/signed_distance_isosurface.cpp", "max_forks_repo_name": "sidgairo18/SCILAB_MEX_TOOLBOX", "max_forks_repo_head_hexsha": "fc679f6d226c03b992b632823a5e57abea05cefa", "max_forks_repo_licenses": ["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.4107142857, "max_line_length": 80, "alphanum_fraction": 0.6359026369, "num_tokens": 1683, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.45711361670559664}}
{"text": "\n/******************************************************************************\n\n  Implementation of the original Hough transform for 2D line tracking.\n\n  Reference papers:\n\n  P.V.C. Hough, \"Machine Analysis of Bubble Chamber Pictures\",\n  Proc. Int. Conf. High Energy Accelerators and Instrumentation, 1959.\n  (U.S. Patent 3,069,654)\n\n  Duda, R. O. and P. E. Hart, \"Use of the Hough Transformation to Detect\n  Lines and Curves in Pictures,\" Comm. ACM, Vol. 15, pp. 11\u201315, 1972.\n\n  Copyright (c) 2013\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 HOUGH_TRANSFORM_HPP_F8fEE77D_37A4_4DFB_83ED_CF832D40772D_\n#define HOUGH_TRANSFORM_HPP_F8fEE77D_37A4_4DFB_83ED_CF832D40772D_\n\n#include <cmath>\n#include <utility>\n#include <algorithm>\n#include <vector>\n#include <boost/assert.hpp>\n#include <boost/math/constants/constants.hpp>\n\n#include \"bo/core/raw_image_2d.hpp\"\n\nnamespace bo {\nnamespace recognition {\n\ntemplate <typename RealType>\nclass HoughTransform\n{\npublic:\n\n    typedef bo::RawImage2D<float> Image;\n    // Pair (rho, theta) used in the transform.\n    typedef std::pair<RealType, RealType> RhoTheta;\n    typedef std::vector<RhoTheta> RhoThetas;\n    // Pixel in the transformed image. First element corresponds to\n    // theta, the second one to rho.\n    typedef std::pair<std::size_t, std::size_t> HoughPixel;\n    typedef std::vector<HoughPixel> HoughPixels;\n\n    HoughTransform(const Image &image): input_image_(image),\n        max_vote_(0)\n    {\n        std::size_t w = image.width();\n        std::size_t h = image.height();\n\n        BOOST_ASSERT(w > 0 && h > 0);\n\n        max_rho_ = std::sqrt(w * w + h * h);\n        min_rho_ = -w;\n\n        max_theta_ = boost::math::constants::pi<RealType>();\n        min_theta_ = RealType(0);\n    }\n\n    // Returns the Hough transform (in the rho-theta parametrization) of the points\n    // from the input image whose values exceed the given threshold. Represents the\n    // result as a 2D image of size (output_width * output_height).\n    // The resulted image covers the following rectangle in the rho-theta space:\n    // width = values of theta [0, Pi], height = values of rho [-w, sqrt(w^2 + h^2)],\n    // where w and h are the width and the height of the input image correspondingly.\n    Image compute(RealType threshold, std::size_t output_width, std::size_t output_height)\n    {\n        BOOST_ASSERT(output_height > 0 && output_width > 0);\n\n        max_vote_ = 0;\n\n        // Compute the output image resolution.\n        theta_scaling_ = static_cast<RealType>(output_width) / (max_theta_ - min_theta_);\n        rho_scaling_ = static_cast<RealType>(output_height - 1) / (max_rho_ - min_rho_);\n\n        // Allocate the output image.\n        bo::RawImage2D<RealType> hough(output_width, output_height, 0);\n\n        std::size_t w = input_image_.width();\n        std::size_t h = input_image_.height();\n\n        // Compute sinusoids in the rho-theta space for each point of the input image\n        // whose value is greater that the threshold.\n        for (std::size_t i = 0; i < w; ++i)\n            for (std::size_t j = 0; j < h; ++j)\n            {\n                if (input_image_(i,j) > threshold)\n                {\n                    // Accumulate the sinusoid.\n                    for (std::size_t x = 0; x < output_width; ++x)\n                    {\n                        RealType theta = min_theta_ + x / theta_scaling_;\n                        RealType rho = i * std::cos(theta) + j * std::sin(theta);\n\n                        std::size_t y = round(rho_scaling_ * (rho - min_rho_));\n\n                        RealType vote = ++hough(x, y);\n\n                        if(max_vote_ < vote)\n                        {\n                            max_vote_ = vote;\n                        }\n                    }\n                }\n            }\n\n        return hough;\n    }\n\n    // Returns the image with the lines reconstructed from the given Hough parameters.\n    Image reconstruct_lines(const RhoThetas &parameters)\n    {\n        const RealType kEpsilon(0.001);\n\n        // Allocate the output image.\n        std::size_t w = input_image_.width();\n        std::size_t h = input_image_.height();\n        Image line_image(w, h, 0);\n\n        for (typename RhoThetas::const_iterator it = parameters.begin();\n             it != parameters.end(); ++it)\n        {\n            RealType rho = it->first;\n            RealType theta = it->second;\n\n            RealType sint = std::sin(theta);\n            RealType cost = std::cos(theta);\n\n            RealType t1, t2;\n\n            // Find the min (t1) and max (t2) parametric values of the line\n            // segment within the image.\n            if (std::abs(sint) < kEpsilon)\n            {\n                t1 = 0;\n                t2 = h;\n            }\n            else if (std::abs(cost) < kEpsilon)\n            {\n                t1 = -w;\n                t2 = 0;\n            }\n            else\n            {\n                RealType tc = rho * cost / sint;\n                t1 = t2 = tc;\n\n                tc = -rho * sint / cost;\n                t1 = std::min(t1, tc);\n                t2 = std::max(t2, tc);\n\n                tc = (rho * cost - w) / sint;\n                t1 = std::min(t1, tc);\n                t2 = std::max(t2, tc);\n\n                tc = (h - rho * sint) / cost;\n                t1 = std::min(t1, tc);\n                t2 = std::max(t2, tc);\n            }\n\n            RealType delta_t = RealType(1);\n            RealType t = t1;\n\n            // Draw the segment of the line.\n            while (t < t2)\n            {\n                std::size_t x = round(rho * cost - t * sint);\n                std::size_t y = round(rho * sint + t * cost);\n\n                if (x >= 0 && x < w && y >= 0 && y < h)\n                {\n                    line_image(x, y) = 1;\n                }\n\n                t += delta_t;\n            }\n        }\n\n        return line_image;\n    }\n\n    // Returns the image with the lines reconstructed from the given subset of pixels\n    // from the Hough image returned by compute() method.\n    Image reconstruct_lines(const HoughPixels &pixels)\n    {\n        RhoThetas parameters;\n\n        // Transform the pixels into rho-theta parameters.\n        for (HoughPixels::const_iterator it = pixels.begin(); it != pixels.end(); ++it)\n        {\n            RealType rho = min_rho_ + it->second / rho_scaling_;\n            RealType theta = min_theta_ + it->first / theta_scaling_;\n\n            parameters.push_back(RhoTheta(rho, theta));\n        }\n\n        return reconstruct_lines(parameters);\n    }\n\n    // Returns the image with the lines detected in the input image. Only the points\n    // whose values exceed the given threshold are considered. The number of the\n    // detected lines is defined by quantity parameter. Only the lines with the\n    // number of votes not less than quantity * (maximal vote in the accumulator)\n    // are reconstructed.\n    Image reconstruct_lines(RealType threshold, RealType quantity,\n                            std::size_t accu_width = 1024,\n                            std::size_t accu_height = 1024)\n    {\n        BOOST_ASSERT(quantity >= RealType(0) && quantity <= RealType(1));\n\n        // Compute the accumulator.\n        Image hough = compute(threshold, accu_width, accu_height);\n\n        RealType accu_threshold = max_vote_ * quantity;\n\n        RhoThetas detected;\n\n        // Collect the best parameters from the accumulator.\n        for (std::size_t i = 0; i < accu_width; ++i)\n            for (std::size_t j = 0; j < accu_height; ++j)\n            {\n                if (hough(i, j) >= accu_threshold)\n                {\n                    RealType rho = min_rho_ + j / rho_scaling_;\n                    RealType theta = min_theta_ + i / theta_scaling_;\n\n                    detected.push_back(RhoTheta(rho, theta));\n                }\n            }\n\n        return reconstruct_lines(detected);\n    }\n\n    RealType get_rho_scaling()\n    {\n        return rho_scaling_;\n    }\n\n    RealType get_theta_scaling()\n    {\n        return theta_scaling_;\n    }\n\nprotected:\n\n    inline std::size_t round(RealType x) const\n    {\n        return static_cast<std::size_t>(std::floor(x + 0.5));\n    }\n\n    Image input_image_;\n\n    RealType max_rho_;\n    RealType min_rho_;\n    RealType max_theta_;\n    RealType min_theta_;\n\n    RealType theta_scaling_;\n    RealType rho_scaling_;\n\n\n    RealType max_vote_;\n};\n\n} // namespace recognition\n} // namespace bo\n\n#endif // HOUGH_TRANSFORM_HPP_F8fEE77D_37A4_4DFB_83ED_CF832D40772D_\n", "meta": {"hexsha": "05a093b088c06322e20871e90042d19a7ed65133", "size": 9845, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Bo/recognition/hough_transform.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/recognition/hough_transform.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/recognition/hough_transform.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": 33.3728813559, "max_line_length": 90, "alphanum_fraction": 0.5814118842, "num_tokens": 2337, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743167997235783, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.45711360970792775}}
{"text": "#include <iostream>\n#include <ros/ros.h>\n#include <ros/console.h>\n#include <geometry_msgs/PoseStamped.h>\n#include <geometry_msgs/Vector3Stamped.h>\n#include <Eigen/Eigen>\n#include <queue>\n\nusing namespace Eigen;\nusing namespace std;\nros::Publisher twist_pub, debug_pub;\nconst double interval = 1000.0;\nconst double dt = 0.01;\n\nint main(int argc, char **argv) {\n    ros::init(argc, argv, \"visual_ekf_test\");\n    ros::NodeHandle n(\"~\");\n\n    twist_pub = n.advertise<geometry_msgs::Vector3Stamped>(\"/visual_ekf/test_twist\", 100);\n    debug_pub = n.advertise<geometry_msgs::PoseStamped>(\"/visual_ekf/test_pose_debug\", 100);\n\n    ros::Rate r(1 / dt);\n\n    Quaterniond start(1, 0, 0, 0);\n    Quaterniond end(1, 2, 3, 100);\n    end = end.normalized();\n\n    Quaterniond q = end * start.conjugate();\n    Quaterniond q_state = start;\n    AngleAxisd R(q);\n    double theta  = R.angle();\n    Vector3d axis = R.axis();\n\n    auto t_start = ros::Time::now();\n    double t_total = interval * dt;\n    // theta = theta / t_total;\n\n    while (ros::ok()) {\n        auto cur_t = ros::Time::now();\n        if ((cur_t.toSec() - t_start.toSec()) < t_total) {\n            geometry_msgs::Vector3Stamped twist;\n            twist.header.stamp = cur_t;\n            twist.vector.x = 0;\n            twist.vector.y = 0;\n            twist.vector.z = 0;\n            twist_pub.publish(twist);\n\n            geometry_msgs::PoseStamped pose;\n            pose.header.stamp = cur_t;\n            pose.pose.orientation.w = start.w();\n            pose.pose.orientation.x = start.x();\n            pose.pose.orientation.y = start.y();\n            pose.pose.orientation.z = start.z();\n            debug_pub.publish(pose);\n        }\n        else if ((cur_t.toSec() - t_start.toSec()) < t_total * 2) {\n            geometry_msgs::Vector3Stamped twist;\n            twist.header.stamp = cur_t;\n            twist.vector.x = theta * axis(0);\n            twist.vector.y = theta * axis(1);\n            twist.vector.z = theta * axis(2);\n            twist_pub.publish(twist);\n\n\n            // AngleAxisd dR(d_theta, axis);\n            Quaterniond dq;\n            dq.w() = cos(0.5 * theta * dt);\n            dq.x() = sin(0.5 * theta * dt) * axis(0);\n            dq.y() = sin(0.5 * theta * dt) * axis(1);\n            dq.z() = sin(0.5 * theta * dt) * axis(2);\n            q_state = (q_state * dq).normalized();\n\n            geometry_msgs::PoseStamped pose;\n            pose.header.stamp = cur_t;\n            pose.pose.orientation.w = q_state.w();\n            pose.pose.orientation.x = q_state.x();\n            pose.pose.orientation.y = q_state.y();\n            pose.pose.orientation.z = q_state.z();\n            debug_pub.publish(pose);\n        }\n\n        r.sleep();\n        ros::spinOnce();\n    }\n}", "meta": {"hexsha": "8846d1c67602b3c79edc62fb090a01f236629f91", "size": 2738, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3_estimator/history/visual_ekf/src/visual_ekf_test_rotation.cpp", "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/history/visual_ekf/src/visual_ekf_test_rotation.cpp", "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/history/visual_ekf/src/visual_ekf_test_rotation.cpp", "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.2117647059, "max_line_length": 92, "alphanum_fraction": 0.5609934259, "num_tokens": 699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743167997235783, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.45711360970792775}}
{"text": "#include <SmurffCpp/Types.h>\n#include <Eigen/IterativeLinearSolvers>\n\n#include <SmurffCpp/Utils/MatrixUtils.h>\n#include <SmurffCpp/Utils/Error.h>\n#include <SmurffCpp/Utils/counters.h>\n\n#include <SmurffCpp/SideInfo/SparseSideInfo.h>\n#include \"linop.h\"\n\nnamespace smurff {\nnamespace linop {\n  class AtA;\n} }\n\nnamespace Eigen {\nnamespace internal {\n  // AtA looks-like a SparseMatrix, so let's inherits its traits:\n  template<>\n  struct traits<smurff::linop::AtA> :  public Eigen::internal::traits<smurff::SparseMatrix>\n  {};\n}\n}\n\nnamespace smurff\n{\nnamespace linop\n{\n\n// Example of a matrix-free wrapper from a user type to Eigen's compatible type\n// For the sake of simplicity, this example simply wrap a Eigen::SparseMatrix.\nclass AtA : public Eigen::EigenBase<AtA>\n{\npublic:\n  // Required typedefs, constants, and method:\n  typedef float_type Scalar;\n  typedef float_type RealScalar;\n  typedef int StorageIndex;\n  enum\n  {\n    ColsAtCompileTime = Eigen::Dynamic,\n    MaxColsAtCompileTime = Eigen::Dynamic,\n    IsRowMajor = true\n  };\n  Index outerSize() const { return m_A.cols(); }\n  Index innerSize() const { return m_A.cols(); }\n  Index rows()      const { return m_A.cols(); }\n  Index cols()      const { return m_A.cols(); }\n  template <typename Rhs>\n  Eigen::Product<AtA, Rhs, Eigen::AliasFreeProduct> operator*(const Eigen::MatrixBase<Rhs> &x) const\n  {\n    return Eigen::Product<AtA, Rhs, Eigen::AliasFreeProduct>(*this, x.derived());\n  }\n  // Custom API:\n  AtA(const SparseMatrix &A, const SparseMatrix &At, double reg) : m_A(A), m_At(At), m_reg(reg) {}\n\n  const SparseMatrix &m_A;\n  const SparseMatrix &m_At;\n  double m_reg;\n};\n\n} // namespace linop\n} // namespace smurff\n\n// Implementation of AtA * Eigen::DenseVector though a specialization of internal::generic_product_impl:\nnamespace Eigen {\nnamespace internal {\n  template<typename Rhs>\n  struct generic_product_impl<smurff::linop::AtA, Rhs, SparseShape, DenseShape, GemvProduct> // GEMV stands for matrix-vector\n  : generic_product_impl_base<smurff::linop::AtA,Rhs,generic_product_impl<smurff::linop::AtA,Rhs> >\n  {\n    typedef typename Product<smurff::linop::AtA,Rhs>::Scalar Scalar;\n    template<typename Dest>\n    static void scaleAndAddTo(Dest& dst, const smurff::linop::AtA& lhs, const Rhs& rhs, const Scalar& alpha)\n    {\n      // This method should implement \"dst += alpha * lhs * rhs\" inplace,\n      dst += alpha * ((lhs.m_At * (lhs.m_A * rhs)) + lhs.m_reg * rhs);\n    }\n  };\n}\n}\n\nnamespace smurff\n{\nnamespace linop\n{\n\ninline void makeSymmetric(Matrix &A)\n{\n  A = A.selfadjointView<Eigen::Lower>();\n}\n\ninline void AtA_mul_B(Matrix& out, const SparseSideInfo& A, double reg, const Matrix& B) {\n  out.noalias() = (A.Ft * (A.F * B)) + reg * B;\n}\n\n//\n//-- Solves the system (K' * K + reg * I) * X = B for X for m right-hand sides\n//   K = d x n matrix\n//   I = n x n identity\n//   X = n x m matrix\n//   B = n x m matrix\n//\nint solve_blockcg_1block(Matrix & X, const SparseSideInfo& K, double reg, Matrix & B, double tol, bool throw_on_cholesky_error) {\n  // initialize\n  const int nfeat = B.rows();\n  const int nrhs  = B.cols();\n  double tolsq = tol*tol;\n\n  if (nfeat != K.cols()) {THROWERROR(\"B.rows() must equal K.cols()\");}\n\n  Vector norms(nrhs), inorms(nrhs); \n  norms.setZero();\n  inorms.setZero();\n  #pragma omp parallel for schedule(static)\n  for (int rhs = 0; rhs < nrhs; rhs++) \n  {\n    double sumsq = 0.0;\n    for (int feat = 0; feat < nfeat; feat++) \n    {\n      sumsq += B(feat, rhs) * B(feat, rhs);\n    }\n    norms(rhs)  = std::sqrt(sumsq);\n    inorms(rhs) = 1.0 / norms(rhs);\n  }\n  Matrix R(nfeat, nrhs);\n  Matrix P(nfeat, nrhs);\n  Matrix Ptmp(nfeat, nrhs);\n  X.setZero();\n  // normalize R and P:\n  #pragma omp parallel for schedule(static) collapse(2)\n  for (int feat = 0; feat < nfeat; feat++) \n  {\n    for (int rhs = 0; rhs < nrhs; rhs++) \n    {\n      R(feat, rhs) = B(feat, rhs) * inorms(rhs);\n      P(feat, rhs) = R(feat, rhs);\n    }\n  }\n  Matrix* RtR = new Matrix(nrhs, nrhs);\n  Matrix* RtR2 = new Matrix(nrhs, nrhs);\n\n  Matrix   KP(nfeat, nrhs);\n  Matrix KPtP(nrhs, nrhs);\n  Matrix A;\n  Matrix Psi;\n\n  //A_mul_At_combo(*RtR, R);\n  *RtR = R.transpose() * R;\n  makeSymmetric(*RtR);\n\n  const int nblocks = (int)ceil(nfeat / 64.0);\n\n  // CG iteration:\n  int iter = 0;\n  for (iter = 0; iter < 1000; iter++) {\n    // KP = K * P\n    ////double t1 = tick();\n    AtA_mul_B(KP, K, reg, P);\n    ////double t2 = tick();\n\n    KPtP = KP.transpose() * P;\n    auto chol_KPtP = KPtP.llt();\n    THROWERROR_ASSERT_MSG(!throw_on_cholesky_error || chol_KPtP.info() != Eigen::NumericalIssue, \"Cholesky Decomposition failed! (Numerical Issue)\");\n    THROWERROR_ASSERT_MSG(!throw_on_cholesky_error || chol_KPtP.info() != Eigen::InvalidInput, \"Cholesky Decomposition failed! (Invalid Input)\");\n    A = chol_KPtP.solve(*RtR);\n    ////double t3 = tick();\n\n    \n    #pragma omp parallel for schedule(guided)\n    for (int block = 0; block < nblocks; block++) \n    {\n      int row = block * 64;\n      int brows = std::min(64, nfeat - row);\n      // X += A' * P\n      X.block(row, 0, brows, nrhs).noalias() += P.block(row, 0, brows, nrhs) * A;\n      // R -= A' * KP\n      R.block(row, 0, brows, nrhs).noalias() -= KP.block(row, 0, brows, nrhs) * A;\n    }\n    ////double t4 = tick();\n\n    // convergence check:\n    //A_mul_At_combo(*RtR2, R);\n    *RtR2 = R.transpose() * R;\n    makeSymmetric(*RtR2);\n\n    Vector d = RtR2->diagonal();\n    // std::cout << \"[ iter \" << iter << \"] \" << std::scientific << d.transpose() << \" (max: \" << d.maxCoeff() << \" > \" << tolsq << \")\" << std::endl;\n    //std::cout << iter << \":\" << std::scientific << d.transpose() << std::endl;\n    if ( (d.array() < tolsq).all()) {\n      break;\n    } \n\n    // Psi = (R R') \\ R2 R2'\n    auto chol_RtR = RtR->llt();\n    THROWERROR_ASSERT_MSG(!throw_on_cholesky_error || chol_RtR.info() != Eigen::NumericalIssue, \"Cholesky Decomposition failed! (Numerical Issue)\");\n    THROWERROR_ASSERT_MSG(!throw_on_cholesky_error || chol_RtR.info() != Eigen::InvalidInput, \"Cholesky Decomposition failed! (Invalid Input)\");\n    Psi  = chol_RtR.solve(*RtR2);\n    ////double t5 = tick();\n\n    // P = R + Psi' * P (P and R are already transposed)\n    #pragma omp parallel for schedule(guided)\n    for (int block = 0; block < nblocks; block++) \n    {\n      int row = block * 64;\n      int brows = std::min(64, nfeat - row);\n      Matrix xtmp(brows, nrhs);\n      xtmp = P.block(row, 0, brows, nrhs) * Psi;\n      P.block(row, 0, brows, nrhs) = R.block(row, 0, brows, nrhs) + xtmp;\n    }\n\n    // R R' = R2 R2'\n    std::swap(RtR, RtR2);\n    ////double t6 = tick();\n    ////double t_total = 0.01 * (t6-t1);\n    ////printf(\"t2-t1 = %.3f, t3-t2 = %.3f, t4-t3 = %.3f, t5-t4 = %.3f, t6-t5 = %.3f\\n\", t2-t1, t3-t2, t4-t3, t5-t4, t6-t5);\n    ////printf(\"t2-t1 = %.3f, t3-t2 = %.3f, t4-t3 = %.3f, t5-t4 = %.3f, t6-t5 = %.3f\\n\", \n    ////  (t2-t1)/(t_total), (t3-t2)/(t_total), (t4-t3)/(t_total), (t5-t4)/(t_total), (t6-t5)/(t_total));\n  }\n  \n  if (iter == 1000)\n  {\n    Vector d = RtR2->diagonal().cwiseSqrt();\n    std::cerr << \"warning: block_cg: could not find a solution in 1000 iterations; residual: [\"\n              << d.transpose() << \" ].all() > \" << tol << std::endl;\n  }\n\n\n  // unnormalizing X:\n  #pragma omp parallel for schedule(static) collapse(2)\n  for (int feat = 0; feat < nfeat; feat++) \n  {\n    for (int rhs = 0; rhs < nrhs; rhs++) \n    {\n      X(feat, rhs) *= norms(rhs);\n    }\n  }\n  delete RtR;\n  delete RtR2;\n  return iter;\n}\n\n\n/** good values for solve_blockcg are blocksize=32 an excess=8 */\nint solve_blockcg(Matrix & X, const SparseSideInfo& K, double reg, Matrix & B, double tol, const int blocksize, const int excess, bool throw_on_cholesky_error) {\n  if (B.cols() <= excess + blocksize) {\n    return solve_blockcg_1block(X, K, reg, B, tol, throw_on_cholesky_error);\n  }\n  // split B into blocks of size <blocksize> (+ excess if needed)\n  Matrix Xblock, Bblock;\n  int max_iter = 0;\n  for (int i = 0; i < B.cols(); i += blocksize) {\n    int ncols = blocksize;\n    if (i + ncols + excess >= B.cols()) {\n      ncols = B.cols() - i;\n    }\n    Bblock.resize(B.rows(), ncols);\n    Xblock.resize(X.rows(), ncols);\n\n    Bblock = B.block(0, i, B.rows(), ncols);\n    int niter = solve_blockcg_1block(Xblock, K, reg, Bblock, tol, throw_on_cholesky_error);\n    max_iter = std::max(niter, max_iter);\n    X.block(0, i, X.rows(), ncols) = Xblock;\n  }\n\n  return max_iter;\n}\n\nint solve_blockcg_eigen(Matrix & X, const SparseSideInfo& K, double reg, Matrix & B, double tol, bool throw_on_cholesky_error)\n{\n   COUNTER(\"eigen_cg\");\n   linop::AtA A(K.F, K.Ft, reg);\n   Eigen::ConjugateGradient<linop::AtA, Eigen::Lower | Eigen::Upper, Eigen::IdentityPreconditioner> cg;\n   cg.setTolerance(tol);\n   cg.compute(A);\n   X = cg.solve(B);\n   return cg.iterations();\n}\n\n}}", "meta": {"hexsha": "dc0ca83fbec8a21c1e0cf69d1849bb879bbf4f28", "size": 8768, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/SmurffCpp/SideInfo/linop.cpp", "max_stars_repo_name": "ExaScience/smurff", "max_stars_repo_head_hexsha": "29c3859badca49275833024cd77f8ca7fa6f76be", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 65.0, "max_stars_repo_stars_event_min_datetime": "2017-06-23T14:01:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T16:13:48.000Z", "max_issues_repo_path": "cpp/SmurffCpp/SideInfo/linop.cpp", "max_issues_repo_name": "ExaScience/smurff", "max_issues_repo_head_hexsha": "29c3859badca49275833024cd77f8ca7fa6f76be", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 143.0, "max_issues_repo_issues_event_min_datetime": "2017-08-11T10:43:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T17:07:51.000Z", "max_forks_repo_path": "cpp/SmurffCpp/SideInfo/linop.cpp", "max_forks_repo_name": "ExaScience/smurff", "max_forks_repo_head_hexsha": "29c3859badca49275833024cd77f8ca7fa6f76be", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2018-05-17T18:33:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-23T20:41:32.000Z", "avg_line_length": 31.3142857143, "max_line_length": 161, "alphanum_fraction": 0.6204379562, "num_tokens": 2830, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936537604181, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4570429348749417}}
{"text": "#include \"b3.h\"\n#include \"descriptor.h\"\n#include \"test_structure.h\"\n#include \"gtest/gtest.h\"\n#include <Eigen/Dense>\n#include <cmath>\n#include <iostream>\n\nTEST_F(StructureTest, RotationTest) {\n\n  // Choose arbitrary rotation angles.\n  double xrot = 1.28;\n  double yrot = -3.21;\n  double zrot = 0.42;\n\n  // Define rotation matrices.\n  Eigen::MatrixXd Rx{3, 3}, Ry{3, 3}, Rz{3, 3}, R{3, 3};\n  Rx << 1, 0, 0, 0, cos(xrot), -sin(xrot), 0, sin(xrot), cos(xrot);\n  Ry << cos(yrot), 0, sin(yrot), 0, 1, 0, -sin(yrot), 0, cos(yrot);\n  Rz << cos(zrot), -sin(zrot), 0, sin(zrot), cos(zrot), 0, 0, 0, 1;\n  R = Rx * Ry * Rz;\n\n  Eigen::MatrixXd rotated_pos = positions * R.transpose();\n  Eigen::MatrixXd rotated_cell = cell * R.transpose();\n\n  // Define descriptors.\n  descriptor_settings[2] = 2;\n  B3 descriptor = B3(radial_string, cutoff_string, radial_hyps, cutoff_hyps,\n                     descriptor_settings);\n\n  std::vector<Descriptor *> descriptors;\n  descriptors.push_back(&descriptor);\n\n  Structure struc1 = Structure(cell, species, positions, cutoff, descriptors);\n  Structure struc2 =\n      Structure(rotated_cell, species, rotated_pos, cutoff, descriptors);\n\n  // Check that B1 is rotationally invariant.\n  double d1, d2, diff;\n  double tol = 1e-10;\n\n  for (int n = 0; n < struc1.descriptors[0].n_descriptors; n++) {\n    d1 = struc1.descriptors[0].descriptors[0](0, n);\n    d2 = struc2.descriptors[0].descriptors[0](0, n);\n    diff = d1 - d2;\n    EXPECT_LE(abs(diff), tol);\n  }\n}\n\n  // TEST_F(DescriptorTest, SingleBond) {\n  //   // Check that B1 descriptors match the corresponding elements of the\n  //   // single bond vector.\n  //   double d1, d2, diff;\n  //   double tol = 1e-10;\n\n  //   desc1.compute(env1);\n  //   desc2.compute(env2);\n\n  //   for (int n = 0; n < no_desc; n++) {\n  //     d1 = desc1.descriptor_vals(n);\n  //     d2 = desc1.single_bond_vals(n);\n  //     diff = d1 - d2;\n  //     EXPECT_LE(abs(diff), tol);\n  //   }\n// }\n\n// TEST_F(DescriptorTest, CentTest) {\n//   double finite_diff, exact, diff;\n//   double tolerance = 1e-5;\n\n//   desc1.compute(env1);\n//   desc2.compute(env2);\n\n//   // Perturb the coordinates of the central atom.\n//   for (int m = 0; m < 3; m++) {\n//     positions_3 = positions_1;\n//     positions_3(0, m) += delta;\n//     struc3 = Structure(cell, species, positions_3);\n//     env3 = LocalEnvironment(struc3, 0, rcut);\n//     env3.many_body_cutoffs = many_body_cutoffs;\n//     env3.compute_indices();\n//     desc3.compute(env3);\n\n//     // Check derivatives.\n//     for (int n = 0; n < no_desc; n++) {\n//       finite_diff =\n//           (desc3.descriptor_vals(n) - desc1.descriptor_vals(n)) / delta;\n//       exact = desc1.descriptor_force_dervs(m, n);\n//       diff = abs(finite_diff - exact);\n//       EXPECT_LE(diff, tolerance);\n//     }\n//   }\n\n//   int lmax = 8;\n//   desc4.compute(env1);\n//   desc5.compute(env2);\n//   no_desc = desc4.descriptor_vals.rows();\n\n//   // Perturb the coordinates of the central atom.\n//   for (int m = 0; m < 3; m++) {\n//     positions_3 = positions_1;\n//     positions_3(0, m) += delta;\n//     struc3 = Structure(cell, species, positions_3);\n//     env3 = LocalEnvironment(struc3, 0, rcut);\n//     env3.many_body_cutoffs = many_body_cutoffs;\n//     env3.compute_indices();\n//     desc6.compute(env3);\n\n//     // Check derivatives.\n//     for (int n = 0; n < no_desc; n++) {\n//       finite_diff =\n//           (desc6.descriptor_vals(n) - desc4.descriptor_vals(n)) / delta;\n//       exact = desc4.descriptor_force_dervs(m, n);\n//       diff = abs(finite_diff - exact);\n//       EXPECT_LE(diff, tolerance);\n//     }\n//   }\n// }\n\n// TEST_F(DescriptorTest, EnvTest) {\n//   double finite_diff, exact, diff;\n//   double tolerance = 1e-5;\n\n//   desc1.compute(env1);\n//   desc2.compute(env2);\n\n//   // Perturb the coordinates of the environment atoms.\n//   for (int p = 1; p < noa; p++) {\n//     for (int m = 0; m < 3; m++) {\n//       positions_3 = positions_1;\n//       positions_3(p, m) += delta;\n//       struc3 = Structure(cell, species, positions_3);\n//       env3 = LocalEnvironment(struc3, 0, rcut);\n//       env3.many_body_cutoffs = many_body_cutoffs;\n//       env3.compute_indices();\n//       desc3.compute(env3);\n\n//       // Check derivatives.\n//       for (int n = 0; n < no_desc; n++) {\n//         finite_diff =\n//             (desc3.descriptor_vals(n) - desc1.descriptor_vals(n)) / delta;\n//         exact = desc1.descriptor_force_dervs(p * 3 + m, n);\n//         diff = abs(finite_diff - exact);\n//         EXPECT_LE(diff, tolerance);\n//       }\n//     }\n//   }\n\n//   int lmax = 8;\n//   desc4.compute(env1);\n//   desc5.compute(env2);\n//   no_desc = desc1.descriptor_vals.rows();\n\n//   // Perturb the coordinates of the environment atoms.\n//   for (int p = 1; p < noa; p++) {\n//     for (int m = 0; m < 3; m++) {\n//       positions_3 = positions_1;\n//       positions_3(p, m) += delta;\n//       struc3 = Structure(cell, species, positions_3);\n//       env3 = LocalEnvironment(struc3, 0, rcut);\n//       env3.many_body_cutoffs = many_body_cutoffs;\n//       env3.compute_indices();\n//       desc6.compute(env3);\n\n//       // Check derivatives.\n//       for (int n = 0; n < no_desc; n++) {\n//         finite_diff =\n//             (desc6.descriptor_vals(n) - desc5.descriptor_vals(n)) / delta;\n//         exact = desc4.descriptor_force_dervs(p * 3 + m, n);\n//         diff = abs(finite_diff - exact);\n//         EXPECT_LE(diff, tolerance);\n//       }\n//     }\n//   }\n// }\n\n// TEST_F(DescriptorTest, StressTest) {\n//   int stress_ind = 0;\n//   double finite_diff, exact, diff;\n//   double tolerance = 1e-5;\n\n//   desc1.compute(env1);\n//   desc2.compute(env2);\n\n//   // Test all 6 independent strains (xx, xy, xz, yy, yz, zz).\n//   for (int m = 0; m < 3; m++) {\n//     for (int n = m; n < 3; n++) {\n//       cell_2 = cell;\n//       positions_2 = positions_1;\n\n//       // Perform strain.\n//       cell_2(0, m) += cell(0, n) * delta;\n//       cell_2(1, m) += cell(1, n) * delta;\n//       cell_2(2, m) += cell(2, n) * delta;\n//       for (int k = 0; k < noa; k++) {\n//         positions_2(k, m) += positions_1(k, n) * delta;\n//       }\n\n//       struc2 = Structure(cell_2, species, positions_2);\n//       env2 = LocalEnvironment(struc2, 0, rcut);\n//       env2.many_body_cutoffs = many_body_cutoffs;\n//       env2.compute_indices();\n//       desc2.compute(env2);\n\n//       // Check stress derivatives.\n//       for (int p = 0; p < no_desc; p++) {\n//         finite_diff =\n//             (desc2.descriptor_vals(p) - desc1.descriptor_vals(p)) / delta;\n//         exact = desc1.descriptor_stress_dervs(stress_ind, p);\n//         diff = abs(finite_diff - exact);\n//         EXPECT_LE(diff, tolerance);\n//       }\n\n//       stress_ind++;\n//     }\n//   }\n\n//   int lmax = 8;\n//   desc4.compute(env1);\n//   desc5.compute(env2);\n//   no_desc = desc1.descriptor_vals.rows();\n//   stress_ind = 0;\n\n//   // Test all 6 independent strains (xx, xy, xz, yy, yz, zz).\n//   for (int m = 0; m < 3; m++) {\n//     for (int n = m; n < 3; n++) {\n//       cell_2 = cell;\n//       positions_2 = positions_1;\n\n//       // Perform strain.\n//       cell_2(0, m) += cell(0, n) * delta;\n//       cell_2(1, m) += cell(1, n) * delta;\n//       cell_2(2, m) += cell(2, n) * delta;\n//       for (int k = 0; k < noa; k++) {\n//         positions_2(k, m) += positions_1(k, n) * delta;\n//       }\n\n//       struc2 = Structure(cell_2, species, positions_2);\n//       env2 = LocalEnvironment(struc2, 0, rcut);\n//       env2.many_body_cutoffs = many_body_cutoffs;\n//       env2.compute_indices();\n//       desc5.compute(env2);\n\n//       // Check stress derivatives.\n//       for (int p = 0; p < no_desc; p++) {\n//         finite_diff =\n//             (desc5.descriptor_vals(p) - desc4.descriptor_vals(p)) / delta;\n//         exact = desc4.descriptor_stress_dervs(stress_ind, p);\n//         diff = abs(finite_diff - exact);\n//         EXPECT_LE(diff, tolerance);\n//       }\n\n//       stress_ind++;\n//     }\n//   }\n// }\n", "meta": {"hexsha": "1c9ff0c7de69cd862cc06408d0ace130faed0228", "size": 7956, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_descriptor.cpp", "max_stars_repo_name": "stevetorr/flare_pp", "max_stars_repo_head_hexsha": "5767bb0787dc38516b582e5134dfd39e6694e8ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2021-03-12T02:53:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T18:59:38.000Z", "max_issues_repo_path": "tests/test_descriptor.cpp", "max_issues_repo_name": "stevetorr/flare_pp", "max_issues_repo_head_hexsha": "5767bb0787dc38516b582e5134dfd39e6694e8ae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2021-04-27T22:52:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-25T08:07:41.000Z", "max_forks_repo_path": "tests/test_descriptor.cpp", "max_forks_repo_name": "stevetorr/flare_pp", "max_forks_repo_head_hexsha": "5767bb0787dc38516b582e5134dfd39e6694e8ae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-28T14:29:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-28T14:29:57.000Z", "avg_line_length": 30.9571984436, "max_line_length": 78, "alphanum_fraction": 0.5646053293, "num_tokens": 2460, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.766293653760418, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.45704293487494163}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n//  Copyright 2019 John Maddock. Distributed under the Boost\n//  Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include <boost/multiprecision/cpp_bin_float.hpp>\n#ifdef TEST_MPFR\n#include <boost/multiprecision/mpfr.hpp>\n#endif\n#ifdef TEST_FLOAT128\n#include <boost/multiprecision/float128.hpp>\n#endif\n#include \"test.hpp\"\n\ntemplate <class T>\nvoid test()\n{\n   T d = 360;\n   for (int i = 2; i >= -2; --i)\n   {\n      T x = i * d;\n      T y = remainder(x, d);\n      if (y == 0)\n         BOOST_CHECK_EQUAL(signbit(y), signbit(x));\n      if (i == 0)\n      {\n         x = -x;\n         y = remainder(x, d);\n         if (y == 0)\n            BOOST_CHECK_EQUAL(signbit(y), signbit(x));\n      }\n   }\n}\n\nint main()\n{\n   test<boost::multiprecision::cpp_bin_float_50>();\n   // No signed zero:\n   //test<boost::multiprecision::cpp_dec_float_50>();\n   //test<boost::multiprecision::mpf_float_50>();\n#ifdef TEST_MPFR\n   test<boost::multiprecision::mpfr_float_50>();\n#endif\n#ifdef TEST_FLOAT128\n   test<boost::multiprecision::float128>();\n#endif\n   return boost::report_errors();\n}\n\n\n", "meta": {"hexsha": "a905b97b76a693d7ad9e9f6014661343614e0cf1", "size": 1220, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/git_issue_426.cpp", "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": "test/git_issue_426.cpp", "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": "test/git_issue_426.cpp", "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": 23.9215686275, "max_line_length": 79, "alphanum_fraction": 0.5918032787, "num_tokens": 323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.45704292850834094}}
{"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_INRAD_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_INRAD_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n    @ingroup group-trigonometric\n    This function object converts degree to radian.\n\n\n    @par Header <boost/simd/function/inrad.hpp>\n\n    @par Example:\n\n      @snippet inrad.cpp inrad\n\n    @par Possible output:\n\n      @snippet inrad.txt inrad\n\n  **/\n  IEEEValue inrad(IEEEValue const& x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/inrad.hpp>\n#include <boost/simd/function/simd/inrad.hpp>\n\n#endif\n", "meta": {"hexsha": "2fc3f20921d22f4f199a056abb5361880032af5d", "size": 962, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/inrad.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/inrad.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/inrad.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.9047619048, "max_line_length": 100, "alphanum_fraction": 0.5748440748, "num_tokens": 198, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4570429285083409}}
{"text": "#include \"tracer.hpp\"\n#include \"initial_conditions/initial_conditions.hpp\"\n#include \"dynamics/sound.hpp\"\n#include \"observers/observer.hpp\"\n#define BOOST_TEST_MODULE sound_test\n#include <boost/test/unit_test.hpp>\n\nusing zero_vec = boost::numeric::ublas::zero_vector<double>;\n\n// make an observer that checks that analytic and numeric solutins coincide\n\n// x(t) = (1+y0 - sqrt(1+t^2)/2)t + sinh^-1(t)/2\n// y(t) = 1 - sqrt(1+t^2) + y0\n\nclass CheckSoundObserver final: public ThreadLocalObserver\n{\npublic:\n\t/// create an observer and specify the time interval for saving the particle's position\n\tCheckSoundObserver( );\n\n\t/// d'tor\n\t~CheckSoundObserver() = default;\n\n\t// standard observer functions\n\t// for documentation look at observer.hpp\n\tbool watch( const State& state, double t ) override;\n\tvoid startTrajectory(const InitialCondition& start, std::size_t trajectory) override;\n\tvoid save( std::ostream& ) override {}\n\tstd::shared_ptr<ThreadLocalObserver> clone() const override;\n\tvoid combine(ThreadLocalObserver&) override {}\n\t\n\tdouble x0;\n\tdouble y0;\n};\n\n\n\nCheckSoundObserver::CheckSoundObserver() : ThreadLocalObserver(\"tlo\") { }\n\n\nvoid CheckSoundObserver::startTrajectory( const InitialCondition& start, std::size_t )\n{\n    x0 = start.getState().getPosition()[0];\n    y0 = start.getState().getPosition()[1];\n}\n\nbool CheckSoundObserver::watch( const State& state, double t )\n{\n    double ax = (1 + y0 - std::sqrt(1+t*t)/2)*t + std::asinh(t)/2 + x0;\n    double ay = 1 - std::sqrt( 1 + t*t ) + y0;\n    double nx = state.getPosition()[0];\n    double ny = state.getPosition()[1];\n\tBOOST_CHECK_CLOSE( ax, nx, 1e-9 );\n\tBOOST_CHECK_CLOSE( ay, ny, 1e-9 );\n\treturn true;\n}\n\n\nstd::shared_ptr<ThreadLocalObserver> CheckSoundObserver::clone() const\n{\n\treturn std::make_shared<CheckSoundObserver>( );\n}\n\n\nBOOST_AUTO_TEST_SUITE(sound_trace_tests)\n\nBOOST_AUTO_TEST_CASE(gradient)\n{\n    Potential potential(2, 1, 256);\n    default_grid g(2, 256);\n    g.setAccessMode(TransformationType::PERIODIC);\n    for(auto& data : g)\n        data = 0;\n    potential.setDerivative(std::vector<int>{0,0}, g.clone(), \"velocity1\");\n    potential.setDerivative(std::vector<int>{1,0}, g.clone(), \"velocity1\");\n    potential.setDerivative(std::vector<int>{0,1}, g.clone(), \"velocity1\");\n    potential.setDerivative(std::vector<int>{1,0}, g.clone(), \"velocity0\");\n    for(auto& data : g)\n        data = 1;\n    potential.setDerivative(std::vector<int>{0,1}, g.clone(), \"velocity0\");\n    for(auto ind = g.getIndex(); ind.valid(); ++ind)\n    {\n        g(ind) = ind[1] / 256.;\n    }\n    potential.setDerivative(std::vector<int>{0,0}, g.clone(), \"velocity0\");\n    \n\tstd::unique_ptr<RayDynamics> dynamics(new Sound(potential, false, false));\n\tauto tracer = std::make_shared<Tracer>( potential, std::move(dynamics));\n\ttracer->setMaxThreads(1);\n\ttracer->addObserver( CheckSoundObserver().clone() );\n\t\n\tauto generator = createInitialConditionGenerator( 2, std::vector<std::string>{\"planar\"} );\n\tinit_cond::InitialConditionConfiguration config;\n\tconfig.setParticleCount(1000).setEnergyNormalization(true).setSupport(potential.getSupport())\n            .setOffset(zero_vec(2));\n\ttracer->trace( generator, config );\n\tstd::cout << \"FINNISHED\\n\";\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "07fef36a90cca78330e077e9288badef4ba48d0b", "size": 3232, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tracer/test/sound_test.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/test/sound_test.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/test/sound_test.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": 32.0, "max_line_length": 94, "alphanum_fraction": 0.7008044554, "num_tokens": 857, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4570429221417399}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2014 Jose Aparicio\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n#ifndef quantlib_tcopula_policy_hpp\n#define quantlib_tcopula_policy_hpp\n\n#include <ql/errors.hpp>\n#include <ql/utilities/disposable.hpp>\n#include <ql/experimental/math/convolvedstudentt.hpp>\n#include <boost/math/distributions/students_t.hpp>\n#include <boost/bind.hpp>\n#include <vector>\n\nnamespace QuantLib {\n\n    /*! \\brief Student-T Latent Model's copula policy.\n\n    Describes the copula of a set of normalized Student-T independent random \n    factors to be fed into the latent variable model. \n    The latent model requires the independent variables to be of unit variance \n    so the policy expects the factors coefficients to be as usual and the T \n    variables to be normalized, the normalization is performed by the policy. \n    To normalize the random variables they are divided by the square root of \n    the variance of each T (\\f$ \\frac{\\nu}{\\nu-2}\\f$)\n    */\n    class TCopulaPolicy {\n    public:\n        /*! Stores the parameters defining the factors random variable \n        T-distributions. As it is now the latent models are restricted to\n        having the same distribution for all idiosyncratic factors, so only\n        one parameter is needed for them.\n        */\n        typedef \n            struct { \n                std::vector<Integer> tOrders;\n            } initTraits;\n\n        /*! Delayed initialization of the distribution parameters and caches. \n        To be called by the latent model. */\n        /* \\todo \n        Explore other constructors, with different vector dimensions, defining\n        simpler combinations (only one correlation, only one variable) might\n        simplify memory.\n        */\n        explicit TCopulaPolicy(\n            const std::vector<std::vector<Real> >& factorWeights = \n                std::vector<std::vector<Real> >(), \n            const initTraits& vals = initTraits());\n\n        //! Number of independent random factors.\n        Size numFactors() const {\n            return latentVarsInverters_.size() + varianceFactors_.size() - 1;\n        }\n\n        //! returns a copy of the initialization arguments\n        //... better to have a cache?\n        initTraits getInitTraits() const {\n            initTraits data;\n            data.tOrders.resize(distributions_.size());\n            for (Size i=0; i<distributions_.size(); ++i) {\n                data.tOrders[i] = static_cast<Integer>(\n                    distributions_[i].degrees_of_freedom());\n            }\n            return data;\n        }\n        const std::vector<Real>& varianceFactors() const {\n            return varianceFactors_;\n        }\n        /*! Cumulative probability of a given latent variable.\n            The iVariable parameter is the index of the requested variable.\n        */\n        Probability cumulativeY(Real val, Size iVariable) const {\n    #if defined(QL_EXTRA_SAFETY_CHECKS)\n            QL_REQUIRE(iVariable < latentVarsCumul_.size(), \n                \"Latent variable index out of bounds.\");\n    #endif\n            return latentVarsCumul_[iVariable](val);\n        }\n        //! Cumulative probability of the idiosyncratic factors (all the same)\n        Probability cumulativeZ(Real z) const {\n            return boost::math::cdf(distributions_.back(), z / \n                varianceFactors_.back());\n        }\n        /*! Probability density of a given realization of values of the systemic\n          factors (remember they are independent).\n          Intended to be used in numerical integration of an arbitrary function \n          depending on those values.\n        */\n        Probability density(const std::vector<Real>& m) const {\n    #if defined(QL_EXTRA_SAFETY_CHECKS)\n            QL_REQUIRE(m.size() == distributions_.size()-1, \n                \"Incompatible sample and latent model sizes\");\n    #endif\n            Real prodDensities = 1.;\n            for(Size i=0; i<m.size(); i++) \n                prodDensities *= boost::math::pdf(distributions_[i], \n                    m[i] /varianceFactors_[i]) /varianceFactors_[i];\n                 // accumulate lambda\n            return prodDensities;\n        }\n        /*! Returns the inverse of the cumulative distribution of the (modelled) \n          latent variable (as indexed by iVariable). Involves the convolution\n          of the factors' distributions.\n        */\n        Real inverseCumulativeY(Probability p, Size iVariable) const {\n    #if defined(QL_EXTRA_SAFETY_CHECKS)\n            QL_REQUIRE(iVariable < latentVarsCumul_.size(), \n                \"Latent variable index out of bounds.\");\n    #endif\n            return latentVarsInverters_[iVariable](p);\n        }\n        /*! Returns the inverse of the cumulative distribution of the \n        idiosincratic factor. The LM here is limited to all idiosincratic \n        factors following the same distribution.\n        */\n        Real inverseCumulativeZ(Probability p) const {\n            return boost::math::quantile(distributions_.back(), p)\n                * varianceFactors_.back();\n        }\n        /*! Returns the inverse of the cumulative distribution of the \n          systemic factor iFactor.\n        */\n        Real inverseCumulativeDensity(Probability p, Size iFactor) const {\n    #if defined(QL_EXTRA_SAFETY_CHECKS)\n            QL_REQUIRE(iFactor < distributions_.size()-1, \n                \"Random factor variable index out of bounds.\");\n    #endif\n            return boost::math::quantile(distributions_[iFactor], p)\n                * varianceFactors_[iFactor];\n        }\n        //to use this (by default) version, the generator must be a uniform one.\n        Disposable<std::vector<Real> > \n            allFactorCumulInverter(const std::vector<Real>& probs) const;\n    private:\n        mutable std::vector<boost::math::students_t_distribution<> > \n            distributions_;\n        mutable std::vector<Real> varianceFactors_;\n        mutable std::vector<CumulativeBehrensFisher> latentVarsCumul_;\n        mutable std::vector<InverseCumulativeBehrensFisher> \n            latentVarsInverters_;\n    };\n\n}\n\n#endif\n", "meta": {"hexsha": "736485755bd8a21e75224ad99dfda34e7360d39b", "size": 6789, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/experimental/math/tcopulapolicy.hpp", "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/experimental/math/tcopulapolicy.hpp", "max_issues_repo_name": "grandtiger/quantlib", "max_issues_repo_head_hexsha": "4cf3d80ffc071ae74f026bb25fbb1dd9093e6301", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-07-17T18:49:22.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-17T18:49:22.000Z", "max_forks_repo_path": "ql/experimental/math/tcopulapolicy.hpp", "max_forks_repo_name": "grandtiger/quantlib", "max_forks_repo_head_hexsha": "4cf3d80ffc071ae74f026bb25fbb1dd9093e6301", "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": 41.9074074074, "max_line_length": 81, "alphanum_fraction": 0.6442775077, "num_tokens": 1444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.45704038930817503}}
{"text": "/*\n(**************************************************************************)\n(*                                                                        *)\n(*                                Schifra                                 *)\n(*                Reed-Solomon Error Correcting Code Library              *)\n(*                                                                        *)\n(* Release Version 0.0.1                                                  *)\n(* http://www.schifra.com                                                 *)\n(* Copyright (c) 2000-2020 Arash Partow, All Rights Reserved.             *)\n(*                                                                        *)\n(* The Schifra Reed-Solomon error correcting code library and all its     *)\n(* components are supplied under the terms of the General Schifra License *)\n(* agreement. The contents of the Schifra Reed-Solomon error correcting   *)\n(* code library and all its components may not be copied or disclosed     *)\n(* except in accordance with the terms of that agreement.                 *)\n(*                                                                        *)\n(* URL: http://www.schifra.com/license.html                               *)\n(*                                                                        *)\n(**************************************************************************)\n*/\n\n\n/*\n   Description: This example will demonstrate the use of the Reed-Solomon\n                erasure channel coding capabilities in a threaded context.\n                One must note that the number of threads should not exceed\n                the architecture's ability to efficiently and productively\n                run the threads. A simple limiting strategy would be not to\n                have more threads than the number of available cores on the\n                processor.\n*/\n\n\n#include <cstddef>\n#include <iostream>\n#include <string>\n\n#include <boost/bind.hpp>\n#include <boost/shared_ptr.hpp>\n#include <boost/thread/thread.hpp>\n\n#include \"schifra_galois_field.hpp\"\n#include \"schifra_galois_field_polynomial.hpp\"\n#include \"schifra_sequential_root_generator_polynomial_creator.hpp\"\n#include \"schifra_reed_solomon_encoder.hpp\"\n#include \"schifra_reed_solomon_decoder.hpp\"\n#include \"schifra_reed_solomon_block.hpp\"\n#include \"schifra_erasure_channel.hpp\"\n#include \"schifra_ecc_traits.hpp\"\n#include \"schifra_utilities.hpp\"\n\n\nconst std::size_t round_count = 100;\n\ntemplate <typename Encoder, typename Decoder>\nclass erasure_process\n{\npublic:\n\n   erasure_process(const unsigned int& process_id,\n                   schifra::galois::field& field,\n                   schifra::galois::field_polynomial& generator_polynomial,\n                   const std::size_t& generator_polynomial_index)\n   : process_id_(process_id),\n     total_time_(0.0),\n     encoder_(field,generator_polynomial),\n     decoder_(field,generator_polynomial_index)\n   {}\n\n   erasure_process& operator=(const erasure_process& ep)\n   {\n      process_id_ = ep.process_id_;\n      total_time_ = ep.total_time_;\n      return *this;\n   }\n\n   double time() { return total_time_; }\n\n   void execute()\n   {\n      schifra::traits::equivalent_encoder_decoder<Encoder,Decoder>();\n\n      const std::size_t code_length = Encoder::trait::code_length;\n      const std::size_t fec_length  = Encoder::trait::fec_length;\n      const std::size_t data_length = Encoder::trait::data_length;\n      const std::size_t stack_size  = Encoder::trait::code_length;\n      const std::size_t data_size   = stack_size * data_length;\n\n      typedef schifra::reed_solomon::block<code_length,fec_length> block_type;\n\n      block_type block_stack[stack_size];\n      unsigned char send_data[data_size];\n      unsigned char recv_data[data_size];\n\n      schifra::utils::timer timer;\n      total_time_ = 0.0;\n\n      for (std::size_t k = 0; k < round_count; ++k)\n      {\n         /* Populate block stack with data */\n         for (std::size_t i = 0; i < data_size; ++i)\n         {\n            send_data[i] = static_cast<unsigned char>((i * 3 + 7 * k) & 0xFF);\n         }\n\n         schifra::reed_solomon::copy<unsigned char,code_length,fec_length,stack_size>(send_data,data_size,block_stack);\n\n         timer.start();\n\n         schifra::reed_solomon::erasure_channel_stack_encode<code_length,fec_length>(encoder_,block_stack);\n\n         /* Add Erasures - Simulate network packet loss (e.g: UDP) */\n         schifra::reed_solomon::erasure_locations_t missing_row_index;\n         missing_row_index.clear();\n\n         for (std::size_t i = 0; i < fec_length; ++i)\n         {\n            std::size_t missing_index = (k + (i * 4)) % stack_size;\n            block_stack[missing_index].clear();\n            missing_row_index.push_back(missing_index);\n         }\n\n         schifra::reed_solomon::erasure_channel_stack_decode<code_length,fec_length>(decoder_,missing_row_index,block_stack);\n\n         schifra::reed_solomon::copy<unsigned char,code_length,fec_length,stack_size>(block_stack,recv_data);\n\n         timer.stop();\n         total_time_ += timer.time();\n\n         for (std::size_t i = 0; i < data_size; ++i)\n         {\n            if (recv_data[i] != send_data[i])\n            {\n               std::cout << \"[\" << process_id_ << \"] Error: Final block stack comparison failed! stack: \" << i << std::endl;\n               return;\n            }\n         }\n      }\n   }\n\nprivate:\n\n   unsigned int process_id_;\n   double total_time_;\n   Encoder encoder_;\n   Decoder decoder_;\n};\n\nint main()\n{\n   /* Finite Field Parameters */\n   const std::size_t field_descriptor                =   8;\n   const std::size_t generator_polynomial_index      = 120;\n   const std::size_t generator_polynomial_root_count = 128;\n\n   /* Reed Solomon Code Parameters */\n   const std::size_t code_length = 255;\n   const std::size_t fec_length  = 128;\n   const std::size_t data_length = code_length - fec_length;\n\n   /* Instantiate Finite Field and Generator Polynomials */\n   schifra::galois::field field(field_descriptor,\n                                schifra::galois::primitive_polynomial_size06,\n                                schifra::galois::primitive_polynomial06);\n\n   schifra::galois::field_polynomial generator_polynomial(field);\n\n   if (\n        !schifra::make_sequential_root_generator_polynomial(field,\n                                                            generator_polynomial_index,\n                                                            generator_polynomial_root_count,\n                                                            generator_polynomial)\n      )\n   {\n      std::cout << \"Error - Failed to create sequential root generator!\" << std::endl;\n      return 1;\n   }\n\n   typedef schifra::reed_solomon::encoder<code_length,fec_length>              encoder_type;\n   typedef schifra::reed_solomon::erasure_code_decoder<code_length,fec_length> decoder_type;\n\n   typedef erasure_process<encoder_type,decoder_type> erasure_process_type;\n   typedef boost::shared_ptr<erasure_process_type>    erasure_process_ptr_type;\n\n   const unsigned int max_thread_count = 4; // number of functional cores.\n\n   std::vector<erasure_process_ptr_type> erasure_process_list;\n\n   boost::thread_group threads;\n\n   for (unsigned int i = 0; i < max_thread_count; ++i)\n   {\n      erasure_process_list.push_back(erasure_process_ptr_type(new\n                                     erasure_process_type\n                                     (\n                                       i,\n                                       field,\n                                       generator_polynomial,\n                                       generator_polynomial_index\n                                     )));\n\n      threads.create_thread(boost::bind(&erasure_process_type::execute,erasure_process_list[i]));\n   }\n\n   threads.join_all();\n\n   double time = -1.0;\n\n   /* Determine the process with the longest running time. */\n   for (std::size_t i = 0; i < erasure_process_list.size(); ++i)\n   {\n      time = ((time < erasure_process_list[i]->time()) ? erasure_process_list[i]->time() : time);\n   }\n\n   double mbps = (max_thread_count * round_count * 8.0 * code_length * data_length) / (1048576.0 * time);\n\n   std::cout << \"Blocks decoded: \" << max_thread_count * round_count * code_length << \"\\tTime: \" << time <<\"sec\\tRate: \" << mbps << \"Mbps\" << std::endl;\n\n   return 0;\n}\n\n", "meta": {"hexsha": "a1251b2588f7a758040d0eca5e5b15f986f9fb29", "size": 8350, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ecc-schifra/schifra_reed_solomon_threads_example02.cpp", "max_stars_repo_name": "m-ll/backup", "max_stars_repo_head_hexsha": "8c7be6f059bddafe95a1debf1d4f5472a354d6d6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ecc-schifra/schifra_reed_solomon_threads_example02.cpp", "max_issues_repo_name": "m-ll/backup", "max_issues_repo_head_hexsha": "8c7be6f059bddafe95a1debf1d4f5472a354d6d6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ecc-schifra/schifra_reed_solomon_threads_example02.cpp", "max_forks_repo_name": "m-ll/backup", "max_forks_repo_head_hexsha": "8c7be6f059bddafe95a1debf1d4f5472a354d6d6", "max_forks_repo_licenses": ["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.6126126126, "max_line_length": 152, "alphanum_fraction": 0.5753293413, "num_tokens": 1764, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256631249076, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.45699624334285865}}
{"text": "#include <iostream>\n#include <boost/numeric/mtl/mtl.hpp>\n\nint main(int, char**)\n{\n    using namespace mtl;\n    \n    const unsigned n= 10;\n    compressed2D<double>                         A(n, n);\n    dense2D<int, mat::parameters<col_major> > B(n, n);\n    morton_dense<double, 0x555555f0>             C(n, n), D(n, n);\n\n    mat::laplacian_setup(A, 2, 5);\n    mat::hessian_setup(B, 1); mat::hessian_setup(C, 2.0); mat::hessian_setup(D, 3.0);\n\n    D+= A - 2 * B + C;\n\n    std::cout << \"The matrices are: A=\\n\" << A << \"B=\\n\" << B << \"C=\\n\" << C << \"D=\\n\" << D;\n\n    return 0;\n}\n", "meta": {"hexsha": "96116ffb9c268487a285ae0c6871e197b1fb4e6a", "size": 575, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/examples/matrix_addition.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/matrix_addition.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/matrix_addition.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": 26.1363636364, "max_line_length": 92, "alphanum_fraction": 0.5252173913, "num_tokens": 205, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515684, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.45699623472580564}}
{"text": "// Std includes\n#include <vector>\n#include <iostream>\n// Thirdparties includes\n#include <Eigen/Dense>\n// Lib includes\n#include \"fl0w/kinematic.h\"\n\nconst unsigned int DIM = 3;\n\nusing TypeScalar = double;\nusing TypeVector = Eigen::Matrix<TypeScalar, DIM, 1>;\nusing TypeMatrix = Eigen::Matrix<TypeScalar, DIM, DIM>;\ntemplate<typename... Args>\nusing TypeRef = Eigen::Ref<Args...>;\nusing TypeFlow = fl0w::kinematic::Kinematic<TypeVector, TypeMatrix, TypeRef, std::vector>;\n\nvoid print(const TypeFlow& flow, const TypeVector& x, const TypeScalar& t) {\n    std::cout << std::endl;\n    std::cout << \"flow.getVelocity(\" << x.transpose() << \", \" << t << \") -> \" << flow.getVelocity(x, t).transpose() << std::endl;\n    std::cout << \"flow.getVorticity(\" << x.transpose() << \", \" << t << \") -> \" << flow.getVorticity(x, t).transpose() << std::endl;\n    std::cout << \"flow.getAcceleration(\" << x.transpose() << \", \" << t << \") -> \" << flow.getAcceleration(x, t).transpose() << std::endl;\n    std::cout << std::endl;\n}\n\nint main () { \n    TypeFlow flow;\n    flow.init();\n    std::cout << \"k \" << (*flow.sK)[0] << std::endl;\n    std::cout << \"k \" << (*flow.sK)[1] << std::endl;\n    std::cout << \"k \" << (*flow.sK)[2] << std::endl;\n    std::cout << \"k \" << (*flow.sK)[3] << std::endl;\n    std::cout << \"n0 \" << (*flow.sK)[0].norm() << std::endl;\n    std::cout << \"nl \" << (*flow.sK)[(*flow.sK).size()-1].norm() << std::endl;\n    std::cout << \"a \" << flow.a[0] << std::endl;\n    std::cout << \"b \" << flow.b[0] << std::endl;\n    std::cout << \"o \" << flow.omega[0] << std::endl;\n    TypeVector x;\n    double t;\n    // Init\n    x << 0.0, 0.0, 0.0;\n    t = 0.0;\n    print(flow, x, t);\n    //x << 10.0, -10.0, 40.0;\n    //t = 10.0;\n    //print(flow, x, t);\n    //x << 1.0, -3.0, -1000.0;\n    //t = 40.0;\n    //print(flow, x, t);\n}\n", "meta": {"hexsha": "556b32f5b93726cc72351f9360966d49fea359aa", "size": 1808, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/kinematic/main.cpp", "max_stars_repo_name": "C0PEP0D/fl0w", "max_stars_repo_head_hexsha": "7e6b1ea0577d73ab98bfa10ae35e827d653cd1f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/kinematic/main.cpp", "max_issues_repo_name": "C0PEP0D/fl0w", "max_issues_repo_head_hexsha": "7e6b1ea0577d73ab98bfa10ae35e827d653cd1f1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/kinematic/main.cpp", "max_forks_repo_name": "C0PEP0D/fl0w", "max_forks_repo_head_hexsha": "7e6b1ea0577d73ab98bfa10ae35e827d653cd1f1", "max_forks_repo_licenses": ["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.4509803922, "max_line_length": 137, "alphanum_fraction": 0.5414823009, "num_tokens": 614, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042768, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.45697490952343844}}
{"text": "#include \"spdlog/spdlog.h\"\n#include <Eigen/Dense>\n#include <cmath>\n#include <iomanip>\n#include <nanogui/nanogui.h>\n\n#include \"lodepng.h\"\n#include \"renderer.hpp\"\n\nusing namespace Eigen;\nusing namespace nanogui;\nusing namespace SnowSimulator;\n\nRenderer::Renderer(Screen &screen, Grid &grid, MaterialPoints &materialPoints)\n    : m_screen(screen), m_grid(grid), m_materialPoints(materialPoints) {\n  logger = spdlog::get(\"snowsim\");\n  m_snowShader.initFromFiles(\"snow_shader\", \"../shaders/snow.vert\",\n                             \"../shaders/snow.frag\");\n\n  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n  glEnable(GL_BLEND);\n\n  glEnable(GL_PROGRAM_POINT_SIZE);\n  glEnable(GL_DEPTH_TEST);\n\n  // Vector3d avg_pm_position(0, 0, 0);\n\n  Vector3d gridDimensions = grid.m_dim.cast<double>();\n\n  Vector3d target(gridDimensions * (0.5 * grid.m_spacing));\n  Vector3d c_dir(0., 0., 0.);\n\n  m_canonicalViewDistance = (gridDimensions * grid.m_spacing).norm() / 2 * 1.5;\n  m_scrollRate = m_canonicalViewDistance / 10;\n\n  m_viewDistance = m_canonicalViewDistance * 2;\n  m_minViewDistance = m_canonicalViewDistance / 10.0;\n  m_maxViewDistance = m_canonicalViewDistance * 20.0;\n\n  // canonicalCamera is a copy used for view resets\n\n  m_camera.place(target, acos(c_dir.y()), atan2(c_dir.x(), c_dir.z()),\n                 m_viewDistance, m_minViewDistance, m_maxViewDistance);\n  m_canonicalCamera.place(target, acos(c_dir.y()), atan2(c_dir.x(), c_dir.z()),\n                          m_viewDistance, m_minViewDistance, m_maxViewDistance);\n\n  m_screenWidth = m_defaultWindowSize(0);\n  m_screenHeight = m_defaultWindowSize(1);\n\n  double hFov = 50;\n  double vFov = 35;\n  double nearClip = 0.01;\n  double farClip = 10000;\n\n  m_camera.configure(nearClip, farClip, hFov, vFov, m_screenWidth,\n                     m_screenHeight);\n  m_canonicalCamera.configure(nearClip, farClip, hFov, vFov, m_screenWidth,\n                              m_screenHeight);\n}\n\nvoid Renderer::render() {\n  m_snowShader.bind();\n\n  glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);\n\n  // m_camera.rotate_by(0, 1.0e-3);\n\n  Matrix4d view = getViewMatrix();\n  Matrix4d projection = getProjectionMatrix();\n\n  Matrix4f modelViewProjection = (projection * view).cast<float>();\n\n  m_snowShader.setUniform(\"modelViewProjection\", modelViewProjection);\n\n  int numNodes = m_grid.dim().prod();\n  auto nodes = m_grid.nodes();\n\n  float s = m_grid.spacing();\n\n  MatrixXf positions(3, numNodes * 36);\n  RowVectorXf masses(numNodes * 36);\n\n  for (int i = 0; i < nodes.size(); i++) {\n    auto node = nodes[i];\n    Vector3f position = node->position();\n\n    double mass = node->mass();\n    if (mass > 1) {\n      mass = 1;\n    } else if (mass < 0) {\n      mass = 0;\n    }\n\n    int idx = i * 36;\n\n    for (int j = 0; j < 36; j++) {\n      masses(idx + j) = mass;\n    }\n\n    float x = position.x(), y = position.y(), z = position.z();\n\n    positions.col(idx) << x, y, z;\n    positions.col(idx + 1) << x, y + s, z;\n    positions.col(idx + 2) << x + s, y, z;\n\n    positions.col(idx + 3) << x + s, y, z;\n    positions.col(idx + 4) << x, y + s, z;\n    positions.col(idx + 5) << x + s, y + s, z;\n\n    positions.col(idx + 6) << x, y, z + s;\n    positions.col(idx + 7) << x, y + s, z + s;\n    positions.col(idx + 8) << x + s, y, z + s;\n\n    positions.col(idx + 9) << x + s, y, z + s;\n    positions.col(idx + 10) << x, y + s, z + s;\n    positions.col(idx + 11) << x + s, y + s, z + s;\n\n    positions.col(idx + 12) << x, y, z;\n    positions.col(idx + 13) << x, y, z + s;\n    positions.col(idx + 14) << x, y + s, z;\n\n    positions.col(idx + 15) << x, y + s, z;\n    positions.col(idx + 16) << x, y, z + s;\n    positions.col(idx + 17) << x, y + s, z + s;\n\n    positions.col(idx + 18) << x + s, y, z;\n    positions.col(idx + 19) << x, y, z + s;\n    positions.col(idx + 20) << x + s, y + s, z;\n\n    positions.col(idx + 21) << x + s, y + s, z;\n    positions.col(idx + 22) << x, y, z + s;\n    positions.col(idx + 23) << x, y + s, z + s;\n\n    positions.col(idx + 24) << x, y, z;\n    positions.col(idx + 25) << x, y, z + s;\n    positions.col(idx + 26) << x + s, y, z;\n\n    positions.col(idx + 27) << x + s, y, z;\n    positions.col(idx + 28) << x, y, z + s;\n    positions.col(idx + 29) << x + s, y, z + s;\n\n    positions.col(idx + 30) << x, y + s, z;\n    positions.col(idx + 31) << x, y + s, z + s;\n    positions.col(idx + 32) << x + s, y + s, z;\n\n    positions.col(idx + 33) << x + s, y + s, z;\n    positions.col(idx + 34) << x, y + s, z + s;\n    positions.col(idx + 35) << x + s, y + s, z + s;\n  }\n\n  m_snowShader.setUniform(\"in_color\", Color(1.0f, 1.0f, 1.0f, 1.0f));\n\n  m_snowShader.uploadAttrib(\"in_position\", positions);\n  m_snowShader.uploadAttrib(\"in_mass\", masses);\n\n  // GLint massIdx = m_snowShader.attrib(\"in_mass\");\n  // glVertexBindingDivisor(massIdx, 36);\n\n  m_snowShader.drawArray(GL_TRIANGLES, 0, numNodes * 36);\n\n  // for (auto &node : m_grid.nodes()) {\n  //   // float density = node->density();\n  //   double mass = std::clamp(node->mass(), 0, 1);\n  //   positions()\n  //\n  //       idx++\n  // }\n\n  // int numParticles = m_materialPoints.particles().size();\n  // MatrixXf particlePositions(3, numParticles);\n  // RowVectorXf masses(numParticles);\n  //\n  // for (int i = 0; i < numParticles; i++) {\n  //   particlePositions.col(i) = m_materialPoints.particles()[i]->m_position;\n  //   masses(i) = m_materialPoints.particles()[i]->mass();\n  // }\n\n  // MatrixXf positions(3, 1000);\n  // int idx = 0;\n  //\n  // for (int i = 0; i < 10; i++) {\n  //   for (int j = 0; j < 10; j++) {\n  //     for (int k = 0; k < 10; k++) {\n  //       positions.col(idx++) << i, j, k;\n  //     }\n  //   }\n  // }\n\n  // m_snowShader.uploadAttrib(\"in_position\", particlePositions);\n  // m_snowShader.uploadAttrib(\"in_mass\", masses);\n  // m_snowShader.drawArray(GL_POINTS, 0, numParticles);\n\n  // Draw the grid bounding box\n\n  // Vector3f bboxMin = m_grid.m_origin;\n  // Vector3f bboxMax = bboxMin + m_grid.m_dim.cast<float>() * m_grid.m_spacing;\n  //\n  // MatrixXf bboxVertices(3, 24);\n  //\n  // bboxVertices.col(0) = bboxMin;\n  // bboxVertices.col(1) << bboxMax.x(), bboxMin.y(), bboxMin.z();\n  //\n  // bboxVertices.col(2) = bboxMin;\n  // bboxVertices.col(3) << bboxMin.x(), bboxMax.y(), bboxMin.z();\n  //\n  // bboxVertices.col(4) = bboxMin;\n  // bboxVertices.col(5) << bboxMin.x(), bboxMin.y(), bboxMax.z();\n  //\n  // bboxVertices.col(6) << bboxMax.x(), bboxMin.y(), bboxMax.z();\n  // bboxVertices.col(7) << bboxMax.x(), bboxMin.y(), bboxMin.z();\n  //\n  // bboxVertices.col(8) << bboxMax.x(), bboxMin.y(), bboxMax.z();\n  // bboxVertices.col(9) << bboxMax.x(), bboxMax.y(), bboxMax.z();\n  //\n  // bboxVertices.col(10) << bboxMax.x(), bboxMin.y(), bboxMax.z();\n  // bboxVertices.col(11) << bboxMin.x(), bboxMin.y(), bboxMax.z();\n  //\n  // bboxVertices.col(12) << bboxMin.x(), bboxMax.y(), bboxMax.z();\n  // bboxVertices.col(13) << bboxMin.x(), bboxMax.y(), bboxMin.z();\n  //\n  // bboxVertices.col(14) << bboxMin.x(), bboxMax.y(), bboxMax.z();\n  // bboxVertices.col(15) = bboxMax;\n  //\n  // bboxVertices.col(16) << bboxMin.x(), bboxMax.y(), bboxMax.z();\n  // bboxVertices.col(17) << bboxMin.x(), bboxMin.y(), bboxMax.z();\n  //\n  // bboxVertices.col(18) << bboxMax.x(), bboxMax.y(), bboxMin.z();\n  // bboxVertices.col(19) << bboxMin.x(), bboxMax.y(), bboxMin.z();\n  //\n  // bboxVertices.col(20) << bboxMax.x(), bboxMax.y(), bboxMin.z();\n  // bboxVertices.col(21) = bboxMax;\n  //\n  // bboxVertices.col(22) << bboxMax.x(), bboxMax.y(), bboxMin.z();\n  // bboxVertices.col(23) << bboxMax.x(), bboxMin.y(), bboxMin.z();\n  //\n  // m_snowShader.uploadAttrib(\"in_position\", bboxVertices);\n  // m_snowShader.drawArray(GL_LINES, 0, 24);\n}\n\n// ============================================================================\n// Event Handling\n// ============================================================================\n\nbool Renderer::keyCallbackEvent(int key, int scancode, int action, int mods) {\n  m_ctrlDown = (bool)(mods & GLFW_MOD_CONTROL);\n\n  if (action == GLFW_PRESS) {\n    switch (key) {\n    case GLFW_KEY_ESCAPE:\n      // is_alive = false;\n      break;\n    case 'r':\n    case 'R':\n      // cloth->reset();\n      break;\n    case ' ':\n      resetCamera();\n      break;\n    case 'p':\n    case 'P':\n      m_isPaused = !m_isPaused;\n      break;\n    }\n  }\n\n  return true;\n}\n\nbool Renderer::cursorPosCallbackEvent(double x, double y) {\n  if (m_leftDown && !m_middleDown && !m_rightDown) {\n    if (m_ctrlDown) {\n      mouseRightDragged(x, y);\n    } else {\n      mouseLeftDragged(x, y);\n    }\n  } else if (!m_leftDown && !m_middleDown && m_rightDown) {\n    mouseRightDragged(x, y);\n  } else if (!m_leftDown && !m_middleDown && !m_rightDown) {\n    mouseMoved(x, y);\n  }\n\n  m_mouseX = x;\n  m_mouseY = y;\n\n  return true;\n}\n\nbool Renderer::mouseButtonCallbackEvent(int button, int action, int modifiers) {\n  switch (action) {\n  case GLFW_PRESS:\n    switch (button) {\n    case GLFW_MOUSE_BUTTON_LEFT:\n      m_leftDown = true;\n      break;\n    case GLFW_MOUSE_BUTTON_MIDDLE:\n      m_middleDown = true;\n      break;\n    case GLFW_MOUSE_BUTTON_RIGHT:\n      m_rightDown = true;\n      break;\n    }\n    return true;\n\n  case GLFW_RELEASE:\n    switch (button) {\n    case GLFW_MOUSE_BUTTON_LEFT:\n      m_leftDown = false;\n      break;\n    case GLFW_MOUSE_BUTTON_MIDDLE:\n      m_middleDown = false;\n      break;\n    case GLFW_MOUSE_BUTTON_RIGHT:\n      m_rightDown = false;\n      break;\n    }\n    return true;\n  }\n\n  return false;\n}\n\nvoid Renderer::mouseMoved(double x, double y) { y = m_screenHeight - y; }\n\nvoid Renderer::mouseLeftDragged(double x, double y) {\n  float dx = x - m_mouseX;\n  float dy = y - m_mouseY;\n\n  m_camera.rotate_by(-dy * (PI / m_screenHeight), -dx * (PI / m_screenWidth));\n}\n\nvoid Renderer::mouseRightDragged(double x, double y) {\n  m_camera.move_by(m_mouseX - x, y - m_mouseY, m_canonicalViewDistance);\n}\n\nbool Renderer::scrollCallbackEvent(double x, double y) {\n  m_camera.move_forward(y * m_scrollRate);\n  return true;\n}\n\nbool Renderer::resizeCallbackEvent(int width, int height) {\n  m_screenWidth = width;\n  m_screenHeight = height;\n\n  m_camera.set_screen_size(m_screenWidth, m_screenHeight);\n  return true;\n}\n\nvoid Renderer::resetCamera() { m_camera.copy_placement(m_canonicalCamera); }\n\nMatrix4d Renderer::getProjectionMatrix() {\n  Matrix4d perspective;\n  perspective.setZero();\n\n  double near = m_camera.near_clip();\n  double far = m_camera.far_clip();\n\n  double theta = m_camera.v_fov() * M_PI / 360;\n  double range = far - near;\n  double invtan = 1. / tanf(theta);\n\n  perspective(0, 0) = invtan / m_camera.aspect_ratio();\n  perspective(1, 1) = invtan;\n  perspective(2, 2) = -(near + far) / range;\n  perspective(3, 2) = -1;\n  perspective(2, 3) = -2 * near * far / range;\n  perspective(3, 3) = 0;\n\n  return perspective;\n}\n\nMatrix4d Renderer::getViewMatrix() {\n  Matrix4d lookAt;\n  Matrix3d R;\n\n  lookAt.setZero();\n\n  Vector3d c_pos = m_camera.position();\n  Vector3d c_udir = m_camera.up_dir();\n  Vector3d c_target = m_camera.view_point();\n\n  Vector3d eye(c_pos.x(), c_pos.y(), c_pos.z());\n  Vector3d up(c_udir.x(), c_udir.y(), c_udir.z());\n  Vector3d target(c_target.x(), c_target.y(), c_target.z());\n\n  R.col(2) = (eye - target).normalized();\n  R.col(0) = up.cross(R.col(2)).normalized();\n  R.col(1) = R.col(2).cross(R.col(0));\n\n  lookAt.topLeftCorner<3, 3>() = R.transpose();\n  lookAt.topRightCorner<3, 1>() = -R.transpose() * eye;\n  lookAt(3, 3) = 1.0;\n\n  return lookAt;\n}\n\nvoid Renderer::writeScreenshot(int stepCount) {\n  std::vector<unsigned char> windowPixels(4 * m_screenWidth * m_screenHeight);\n  glReadPixels(0, 0, m_screenWidth, m_screenHeight, GL_RGBA, GL_UNSIGNED_BYTE,\n               &windowPixels[0]);\n\n  std::vector<unsigned char> flippedPixels(4 * m_screenWidth * m_screenHeight);\n  for (int row = 0; row < m_screenHeight; ++row)\n    memcpy(&flippedPixels[row * m_screenWidth * 4],\n           &windowPixels[(m_screenHeight - row - 1) * m_screenWidth * 4],\n           4 * m_screenWidth);\n\n  time_t t = time(nullptr);\n  tm *lt = localtime(&t);\n  std::stringstream ss;\n\n  ss << \"../renders/render_\" << std::setfill('0') << std::setw(6) << stepCount\n     << \".png\";\n\n  std::string file = ss.str();\n  if (lodepng::encode(file, flippedPixels, m_screenWidth, m_screenHeight)) {\n    logger->error(\"Failed to write screenshot to disk!\");\n  }\n}\n", "meta": {"hexsha": "e877d30ad46a23120024130a5f52dc27e95088b8", "size": 12250, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/renderer.cpp", "max_stars_repo_name": "kvchen/snowsim", "max_stars_repo_head_hexsha": "09a75f24e86cc340ed327074904255fb08a3e7eb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/renderer.cpp", "max_issues_repo_name": "kvchen/snowsim", "max_issues_repo_head_hexsha": "09a75f24e86cc340ed327074904255fb08a3e7eb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-08-14T16:38:11.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-14T16:38:11.000Z", "max_forks_repo_path": "src/renderer.cpp", "max_forks_repo_name": "kvchen/snowsim", "max_forks_repo_head_hexsha": "09a75f24e86cc340ed327074904255fb08a3e7eb", "max_forks_repo_licenses": ["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.2362768496, "max_line_length": 80, "alphanum_fraction": 0.6068571429, "num_tokens": 3723, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128672997041659, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4569748942321753}}
{"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// Author: Steffen Urban (steffen.urban@googlemail.com), March 2021\n\n#include \"theia/sfm/global_pose_estimation/LiGT_position_estimator.h\"\n\n#include <Eigen/Core>\n#include <Eigen/SparseCore>\n#include <Eigen/SparseLU>\n#include <Eigen/Geometry>\n#include <Eigen/Dense>\n#include <algorithm>\n#include <ceres/rotation.h>\n#include <glog/logging.h>\n#include <memory>\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n\n#include \"spectra/include/SymEigsShiftSolver.h\"\n\n#include \"theia/math/graph/triplet_extractor.h\"\n#include \"theia/math/matrix/spectra_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_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\nEigen::Matrix3d GetSkew(const Eigen::Vector3d& f) {\n  Eigen::Matrix3d skew_mat;\n  skew_mat << 0.0, -f(2), f(1), f(2), 0.0, -f(0), -f(1), f(0), 0.0;\n  return skew_mat;\n}\n\nEigen::Matrix3d GetRij(const Eigen::Matrix3d& i, const Eigen::Matrix3d& j) {\n  return j * i.transpose();\n}\n\ndouble GetThetaSq(const Eigen::Vector3d& feat_i,\n                  const Eigen::Vector3d& feat_j,\n                  const Eigen::Matrix3d& Rij) {\n  return (GetSkew(feat_j) * Rij * feat_i).squaredNorm();\n}\n\nEigen::Vector3d Get_aij(const Eigen::Matrix3d& Rij,\n                        const Eigen::Vector3d Xi,\n                        const Eigen::Vector3d Xj) {\n  return (GetSkew(Rij * Xi) * Xj).transpose() * GetSkew(Xj);\n}\n\n// Adds the constraint from the triplet to the symmetric matrix. Our standard\n// constraint matrix A is a 3M x 3N matrix with M triplet constraints and N\n// cameras. We seek to construct A^t * A directly. For each triplet constraint\n// in our matrix A (i.e. a 3-row block), we can compute the corresponding\n// entries in A^t * A with the following summation:\n//\n//   A^t * A += Row(i)^t * Row(i)\n//\n// for each triplet constraint i.\nvoid AddTripletConstraintToSymmetricMatrix(\n    const std::vector<Matrix3d>& constraints,\n    const std::vector<int>& view_indices,\n    std::unordered_map<std::pair<int, int>, double>* sparse_matrix_entries) {\n  // Construct Row(i)^t * Row(i). If we denote the row as a block matrix:\n  //\n  //   Row(i) = [A | B | C]\n  //\n  // then we have:\n  //\n  //   Row(i)^t * Row(i) = [A | B | C]^t * [A | B | C]\n  //                     = [ A^t * A  |  A^t * B  |  A^t * C]\n  //                       [ B^t * A  |  B^t * B  |  B^t * C]\n  //                       [ C^t * A  |  C^t * B  |  C^t * C]\n  //\n  // Since A^t * A is symmetric, we only store the upper triangular portion.\n  for (int i = 0; i < 3; i++) {\n    for (int j = 0; j < 3; j++) {\n      // Skip any block entries that correspond to the lower triangular portion\n      // of the matrix.\n      if (view_indices[i] > view_indices[j]) {\n        continue;\n      }\n\n      // Compute the A^t * B, etc. matrix.\n      const Eigen::Matrix3d symmetric_constraint =\n          constraints[i].transpose() * constraints[j];\n\n      // Add to the 3x3 block corresponding to (i, j)\n      for (int r = 0; r < 3; r++) {\n        for (int c = 0; c < 3; c++) {\n          const std::pair<int, int> row_col(view_indices[i] + r,\n                                            view_indices[j] + c);\n          (*sparse_matrix_entries)[row_col] += symmetric_constraint(r, c);\n        }\n      }\n    }\n  }\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// 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// Returns the features as a unit-norm pixel ray after camera intrinsics\n// (i.e. focal length an principal point) have been removed.\nFeature GetNormalizedFeature(const View& view, const TrackId track_id) {\n  Feature feature = *view.GetFeature(track_id);\n  const Camera& camera = view.Camera();\n  Eigen::Vector3d ray = camera.PixelToNormalizedCoordinates(feature.point_);\n  Feature normalized_Feature(ray.hnormalized());\n  // todo normalized covariance?\n  return normalized_Feature;\n}\n\nstd::pair<ViewId, ViewId> GetBestBaseViews(\n    const Reconstruction& reconstruction,\n    const TrackId& track_id) {\n\n    const Track* track = reconstruction.Track(track_id);\n    std::vector<ViewId> view_ids(track->ViewIds().begin(), track->ViewIds().end());\n    double theta_max = 0.0;\n    std::pair<ViewId, ViewId> base_views;\n    for (size_t i = 0; i < view_ids.size(); ++i) {\n      for (size_t j = i+1; j < view_ids.size(); ++j) {\n        ViewId id1 = view_ids[i];\n        ViewId id2 = view_ids[j];\n        const View* view1 = reconstruction.View(id1);\n        const View* view2 = reconstruction.View(id2);\n        const Vector3d feature1 =\n            GetNormalizedFeature(*view1, track_id).point_.homogeneous();\n        const Vector3d feature2 =\n            GetNormalizedFeature(*view2, track_id).point_.homogeneous();\n\n        const Eigen::Matrix3d R1 = view1->Camera().GetOrientationAsRotationMatrix();\n        const Eigen::Matrix3d R2 = view2->Camera().GetOrientationAsRotationMatrix();\n        const Matrix3d R12 = GetRij(R1, R2);\n        const double theta = GetThetaSq(feature1, feature2, R12);\n        if (theta > theta_max) {\n            base_views = std::make_pair(id1, id2);\n            theta_max = theta;\n        }\n      }\n    }\n    return base_views;\n}\n\n}  // namespace\n\nLiGTPositionEstimator::LiGTPositionEstimator(\n    const Options& options, const Reconstruction& reconstruction)\n    : options_(options), reconstruction_(reconstruction) {\n  CHECK_GT(options.num_threads, 0);\n}\n\nbool LiGTPositionEstimator::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  num_triplets_for_view_.clear();\n  linear_system_index_.clear();\n  BCDs_.clear();\n  triplets_for_tracks_.clear();\n\n  view_pairs_ = &view_pairs;\n  orientations_ = &orientations;\n\n  VLOG(2) << \"Extracting triplets from tracks and calculating BCDs for tracks.\";\n  FindTripletsForTracks();\n\n//  VLOG(2) << \"Calculating BCD for tracks.\";\n//  for (const auto& t : triplets_for_tracks_) {\n//    auto t_id = t.first;\n//    auto view_ids = t.second;\n//    for (const auto& vids : view_ids) {\n//      const auto view1 = reconstruction_.View(std::get<0>(vids));\n//      const auto view2 = reconstruction_.View(std::get<1>(vids));\n//      const auto view3 = reconstruction_.View(std::get<2>(vids));\n//      std::tuple<Matrix3d, Matrix3d, Matrix3d> BCD;\n//      CalculateBCDForTrack(view1, view2, view3, t_id, BCD);\n\n////      Eigen::Vector3d shouldnull = std::get<1>(BCD)*view1->Camera().GetPosition() +\n////              std::get<0>(BCD)*view2->Camera().GetPosition() +\n////              std::get<2>(BCD)*view3->Camera().GetPosition();\n////      std::cout<<\"shouldnull: \"<<shouldnull<<\"\\n\";\n\n//      BCDs_[t_id].push_back(BCD);\n//    }\n//  }\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(&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(constraint_matrix);\n  Spectra::SymEigsShiftSolver<double, Spectra::LARGEST_MAGN,\n                              SparseSymShiftSolveLLT>\n  eigs(&op, 1, 6, 0.0);\n  eigs.init();\n  eigs.compute();\n\n  // Compute with power iterations.\n  const Eigen::VectorXd solution = eigs.eigenvectors().col(0);\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  return true;\n}\n\nvoid LiGTPositionEstimator::CalculateBCDForTrack(\n    const theia::View* view1,\n    const theia::View* view2,\n    const theia::View* view3,\n    const TrackId& track_id,\n    std::tuple<Eigen::Matrix3d, Eigen::Matrix3d, Eigen::Matrix3d>& BCD) {\n  const Vector3d feature1 =\n      GetNormalizedFeature(*view1, track_id).point_.homogeneous();\n  const Vector3d feature2 =\n      GetNormalizedFeature(*view2, track_id).point_.homogeneous();\n  const Vector3d feature3 =\n      GetNormalizedFeature(*view3, track_id).point_.homogeneous();\n\n  const Eigen::Matrix3d R1 = view1->Camera().GetOrientationAsRotationMatrix();\n  const Eigen::Matrix3d R2 = view2->Camera().GetOrientationAsRotationMatrix();\n  const Eigen::Matrix3d R3 = view3->Camera().GetOrientationAsRotationMatrix();\n\n  const Matrix3d R31 = GetRij(R3, R1);\n  const Matrix3d R32 = GetRij(R3, R2);\n\n  const Vector3d a32 = Get_aij(R32, feature3, feature2);\n\n  const Matrix3d skew_feat1 = GetSkew(feature1);\n  // equation 18\n  std::get<0>(BCD) = skew_feat1 * R31 * feature3 * a32.transpose() * R2;\n\n  const double theta = GetThetaSq(feature3, feature2, R32);\n  std::get<1>(BCD) = theta * skew_feat1 * R1;\n\n  std::get<2>(BCD) = -(std::get<0>(BCD) + std::get<1>(BCD));\n}\n\nvoid LiGTPositionEstimator::FindTripletsForTracks() {\n  auto track_ids = reconstruction_.TrackIds();\n  uint32_t total_nr_triplets = 0;\n  for (size_t t = 0; t < track_ids.size(); ++t) {\n    auto t_id = track_ids[t];\n    std::cout<<\"searching triplet for \"<<t_id<<\"\\n\";\n\n    auto view_ids_for_track = reconstruction_.Track(t_id)->ViewIds();\n    std::cout<<\"view_ids_for_track size: \"<<view_ids_for_track.size()<<\"\\n\";\n    if (view_ids_for_track.size() < 3) {\n      continue;\n    }\n    // implements equation 29 from paper. Get base views for point\n    std::pair<ViewId, ViewId> base_views = GetBestBaseViews(reconstruction_, t_id);\n    // now iterate all other observations beside the base views\n    for (size_t v = 0; v < view_ids_for_track.size(); ++v) {\n      ViewId cur_id = *std::next(view_ids_for_track.begin(), v);\n      // check if the current id is one of the base views\n      if (cur_id == base_views.first || cur_id == base_views.second) {\n          continue;\n      }\n      std::cout<<\"Track: \"<<t_id<<\" triplet: (base l, central, base r) (\"<<base_views.first<<\", \"<<cur_id<<\", \"<<base_views.second<<\")\\n\";\n\n      ViewIdTriplet triplet = std::make_tuple(base_views.first, cur_id, base_views.second);\n      AddTripletConstraint(triplet);\n\n      const auto view1 = reconstruction_.View(base_views.first);\n      const auto view2 = reconstruction_.View(cur_id);\n      const auto view3 = reconstruction_.View(base_views.second);\n      std::tuple<Matrix3d, Matrix3d, Matrix3d> BCD;\n      CalculateBCDForTrack(view1, view2, view3, t_id, BCD);\n\n//      Eigen::Vector3d shouldbezero = std::get<1>(BCD)*view1->Camera().GetPosition() +\n//              std::get<0>(BCD)*view2->Camera().GetPosition() +\n//              std::get<2>(BCD)*view3->Camera().GetPosition();\n//      std::cout<<\"shouldbezero: \"<<shouldbezero<<\"\\n\";\n\n      triplets_for_tracks_[t_id].push_back(triplet);\n      BCDs_[t_id].push_back(BCD);\n      total_nr_triplets++;\n    }\n  }\n\n  std::cout<<\"Total number of triplets: \"<<total_nr_triplets<<\" for \"<< track_ids.size()<<\" tracks and \"<<reconstruction_.ViewIds().size()<<\" views.\\n\";\n}\n\n// An alternative interface is to instead add triplets one by one to linear\n// estimator. This allows for adding redundant observations of triplets, which\n// may be useful if there are multiple estimates of the data.\nvoid LiGTPositionEstimator::AddTripletConstraint(\n    const ViewIdTriplet& view_triplet) {\n  num_triplets_for_view_[std::get<0>(view_triplet)] += 1;\n  num_triplets_for_view_[std::get<1>(view_triplet)] += 1;\n  num_triplets_for_view_[std::get<2>(view_triplet)] += 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                     std::get<0>(view_triplet),\n                     linear_system_index_.size() - 1);\n  InsertIfNotPresent(&linear_system_index_,\n                     std::get<1>(view_triplet),\n                     linear_system_index_.size() - 1);\n  InsertIfNotPresent(&linear_system_index_,\n                     std::get<2>(view_triplet),\n                     linear_system_index_.size() - 1);\n}\n\n// Sets up the linear system with the constraints that each triplet adds.\nvoid LiGTPositionEstimator::CreateLinearSystem(\n    Eigen::SparseMatrix<double>* constraint_matrix) {\n  const int num_views = num_triplets_for_view_.size();\n\n    std::unordered_map<std::pair<int, int>, double> sparse_matrix_entries;\n    sparse_matrix_entries.reserve(27 * num_triplets_for_view_.size());\n    for (const auto& triplet_vector : triplets_for_tracks_) {\n        const TrackId t_id = triplet_vector.first;\n        const std::vector<ViewIdTriplet> triplet_v = triplet_vector.second;\n        for (size_t i = 0; i < triplet_v.size(); ++i) {\n            const ViewId &view_id1 = std::get<0>(triplet_v[i]);\n            const ViewId &view_id2 = std::get<1>(triplet_v[i]);\n            const ViewId &view_id3 = std::get<2>(triplet_v[i]);\n            AddTripletConstraintToSparseMatrix(view_id1, view_id2, view_id3,\n                                               BCDs_[t_id][i],\n                                               &sparse_matrix_entries);\n\n        }\n    }\n\n    // Set the sparse matrix from the container of the accumulated entries.\n    std::vector<Eigen::Triplet<double>> triplet_list;\n    triplet_list.reserve(sparse_matrix_entries.size());\n    for (const auto &sparse_matrix_entry : sparse_matrix_entries) {\n      // Skip this entry if the indices are invalid. This only occurs when we\n      // encounter a constraint with the constant camera (which has a view index\n      // of -1).\n      if (sparse_matrix_entry.first.first < 0 ||\n          sparse_matrix_entry.first.second < 0) {\n        continue;\n      }\n      triplet_list.emplace_back(sparse_matrix_entry.first.first,\n                                sparse_matrix_entry.first.second,\n                                sparse_matrix_entry.second);\n    }\n\n    // We construct the constraint matrix A^t * A directly, which is an\n    // N - 1 x N - 1 matrix where N is the number of cameras (and 3 entries per\n    // camera, corresponding to the camera position entries).\n\n    constraint_matrix->resize((num_views - 1) * 3, (num_views - 1) * 3);\n    constraint_matrix->setFromTriplets(triplet_list.begin(),\n    triplet_list.end());\n}\n\nvoid LiGTPositionEstimator::ComputeRotatedRelativeTranslationRotations(\n    const ViewId view_id0,\n    const ViewId view_id1,\n    const ViewId view_id2,\n    Eigen::Matrix3d* r012,\n    Eigen::Matrix3d* r201,\n    Eigen::Matrix3d* r120) {\n  // Relative camera positions.\n  const Eigen::Vector3d& orientation0_aa =\n      FindOrDieNoPrint(*orientations_, view_id0);\n  const Eigen::Vector3d& orientation1_aa =\n      FindOrDieNoPrint(*orientations_, view_id1);\n  const Matrix3d orientation0 = AngleAxisToRotationMatrix(orientation0_aa);\n  const Matrix3d orientation1 = AngleAxisToRotationMatrix(orientation1_aa);\n  const Vector3d t01 =\n      -orientation0.transpose() *\n      FindOrDieNoPrint(*view_pairs_, ViewIdPair(view_id0, view_id1)).position_2;\n  const Vector3d t02 =\n      -orientation0.transpose() *\n      FindOrDieNoPrint(*view_pairs_, ViewIdPair(view_id0, view_id2)).position_2;\n  const Vector3d t12 =\n      -orientation1.transpose() *\n      FindOrDieNoPrint(*view_pairs_, ViewIdPair(view_id1, view_id2)).position_2;\n\n  // Rotations between the translation vectors.\n  *r012 = Eigen::Quaterniond::FromTwoVectors(t12, -t01).toRotationMatrix();\n  *r201 = Eigen::Quaterniond::FromTwoVectors(t01, t02).toRotationMatrix();\n  *r120 = Eigen::Quaterniond::FromTwoVectors(-t02, -t12).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 LiGTPositionEstimator::AddTripletConstraintToSparseMatrix(\n    const ViewId view_id0,\n    const ViewId view_id1,\n    const ViewId view_id2,\n    const std::tuple<Matrix3d, Matrix3d, Matrix3d>& BCD,\n    std::unordered_map<std::pair<int, int>, double>* sparse_matrix_entries) {\n//  // Weight each term by the inverse of the # of triplet that the nodes\n//  // participate in.\n//  const double w =\n//      1.0 / std::sqrt(std::min({num_triplets_for_view_[view_id0],\n//                                num_triplets_for_view_[view_id1],\n//                                num_triplets_for_view_[view_id2]}));\n\n  // Get the index of each camera in the sparse matrix.\n  const std::vector<int> view_indices = {\n      static_cast<int>(3 * FindOrDie(linear_system_index_, view_id0)),\n      static_cast<int>(3 * FindOrDie(linear_system_index_, view_id1)),\n      static_cast<int>(3 * FindOrDie(linear_system_index_, view_id2))};\n\n  // important to use index 1 0 2 here.\n  // 0 ist the central camera and equation 17 is using it that way\n  std::vector<Matrix3d> constraints = {std::get<1>(BCD),std::get<0>(BCD),std::get<2>(BCD)};\n  AddTripletConstraintToSymmetricMatrix(\n      constraints, view_indices, sparse_matrix_entries);\n}\n\nvoid LiGTPositionEstimator::FlipSignOfPositionsIfNecessary(\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  for (const auto& view_pair : *view_pairs_) {\n    // Only count the votes for edges where both positions were successfully\n    // estimated.\n    const Vector3d* position1 = FindOrNull(*positions, view_pair.first.first);\n    const Vector3d* position2 = FindOrNull(*positions, view_pair.first.second);\n    if (position1 == nullptr || position2 == nullptr) {\n      continue;\n    }\n\n    // Check the relative translation of views 1 and 2 in the triplet.\n    if (VectorsAreSameDirection(\n            *position1,\n            *position2,\n            FindOrDieNoPrint(*orientations_, view_pair.first.first),\n            view_pair.second.position_2)) {\n      correct_sign_votes += 1;\n    } else {\n      correct_sign_votes -= 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        (view_pairs_->size() + correct_sign_votes) / 2;\n    VLOG(2) << \"Sign of the positions was incorrect: \" << num_correct_votes\n            << \" of \" << view_pairs_->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\nstd::unordered_map<ViewId, Eigen::Vector3d>\nLiGTPositionEstimator::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": "04fd6508b5b6244bec3ad1bf3de2e5ea826eb0ec", "size": 22116, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/sfm/global_pose_estimation/LiGT_position_estimator.cc", "max_stars_repo_name": "urbste/TheiaSfM", "max_stars_repo_head_hexsha": "a92fa27e90b6182e2a2511a46d24283afad1a995", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T03:01:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-04T08:08:45.000Z", "max_issues_repo_path": "src/theia/sfm/global_pose_estimation/LiGT_position_estimator.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/global_pose_estimation/LiGT_position_estimator.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": 41.0315398887, "max_line_length": 152, "alphanum_fraction": 0.6740368964, "num_tokens": 5728, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4569703443250696}}
{"text": "<<<<<<< HEAD\n/*    Copyright (c) 2010-2018, Delft University of Technology\n=======\n/*    Copyright (c) 2010-2019, Delft University of Technology\n>>>>>>> origin/master\n *    All rigths reserved\n *\n *    This file is part of the Tudat. Redistribution and use in source and\n *    binary forms, with or without modification, are permitted exclusively\n *    under the terms of the Modified BSD license. You should have received\n *    a copy of the license with this file. If not, please or visit:\n *    http://tudat.tudelft.nl/LICENSE.\n *\n */\n\n#define BOOST_TEST_MAIN\n\n#include <limits>\n\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/unit_test.hpp>\n\n#include \"Tudat/Mathematics/BasicMathematics/mathematicalConstants.h\"\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/physicalConstants.h\"\n\nnamespace tudat\n{\nnamespace unit_tests\n{\n\nBOOST_AUTO_TEST_SUITE( test_physical_constants )\n\n//! Test if the physical constants have the correct relations (ratios/offsets).\nBOOST_AUTO_TEST_CASE( testRelationsBetweenPhysicalConstant )\n{    \n    using namespace physical_constants;\n\n    // Test for the number of seconds in a year.\n    BOOST_CHECK_CLOSE_FRACTION( JULIAN_YEAR, JULIAN_DAY * JULIAN_YEAR_IN_DAYS,\n                                std::numeric_limits< double >::epsilon( ) );\n\n    // Test for the number of seconds in a year.\n    BOOST_CHECK_CLOSE_FRACTION( SIDEREAL_YEAR, JULIAN_DAY * SIDEREAL_YEAR_IN_DAYS,\n                                std::numeric_limits< double >::epsilon( ) );\n\n    // Test pre-computed powers of speed of light.\n    BOOST_CHECK_CLOSE_FRACTION( std::pow( SPEED_OF_LIGHT, -2.0 ), INVERSE_SQUARE_SPEED_OF_LIGHT,\n                                std::numeric_limits< double >::epsilon( ) );\n    BOOST_CHECK_CLOSE_FRACTION( std::pow( SPEED_OF_LIGHT, -3.0 ), INVERSE_CUBIC_SPEED_OF_LIGHT,\n                                std::numeric_limits< double >::epsilon( ) );\n    BOOST_CHECK_CLOSE_FRACTION( std::pow( SPEED_OF_LIGHT, -4.0 ), INVERSE_QUARTIC_SPEED_OF_LIGHT,\n                                std::numeric_limits< double >::epsilon( ) );\n    BOOST_CHECK_CLOSE_FRACTION( std::pow( SPEED_OF_LIGHT, -5.0 ), INVERSE_QUINTIC_SPEED_OF_LIGHT,\n                                std::numeric_limits< double >::epsilon( ) );\n}\n\n//! Test if physical constants have the expected value.\nBOOST_AUTO_TEST_CASE( testOtherConstants )\n{\n    using namespace physical_constants;\n\n    // Test for gravitational constant.\n    BOOST_CHECK_CLOSE_FRACTION( GRAVITATIONAL_CONSTANT, 6.67259e-11,\n                                std::numeric_limits< double >::epsilon( ) );\n\n    // Test for speed of light.\n    BOOST_CHECK_CLOSE_FRACTION( SPEED_OF_LIGHT, 299792458.0,\n                                std::numeric_limits< double >::epsilon( ) );\n    BOOST_CHECK_CLOSE_FRACTION( SPEED_OF_LIGHT_LONG, 299792458.0L,\n                                std::numeric_limits< long double >::epsilon( ) );\n\n    // Test for astronomical unit.\n    BOOST_CHECK_CLOSE_FRACTION( ASTRONOMICAL_UNIT, 1.49597870691e11,\n                                std::numeric_limits< double >::epsilon( ) );\n\n    // Test for molar gas constant.\n    BOOST_CHECK_CLOSE_FRACTION( MOLAR_GAS_CONSTANT, 8.3144598,\n                                std::numeric_limits< double >::epsilon( ) );\n\n    // Test for Avogadro's number.\n    BOOST_CHECK_CLOSE_FRACTION( AVOGADRO_CONSTANT, 6.022140857e23,\n                                std::numeric_limits< double >::epsilon( ) );\n\n    // Test for Planck constant.\n    BOOST_CHECK_CLOSE_FRACTION( PLANCK_CONSTANT, 6.62606957E-34,\n                                std::numeric_limits< double >::epsilon( ) );\n\n    // Test for Boltzmann constant.\n    BOOST_CHECK_CLOSE_FRACTION( BOLTZMANN_CONSTANT, 1.3806488E-23,\n                                std::numeric_limits< double >::epsilon( ) );\n\n    // Test permittivity/permeability fo vacuum\n    BOOST_CHECK_CLOSE_FRACTION( VACUUM_PERMEABILITY, 4.0 * mathematical_constants::PI * 1.0E-7,\n                                std::numeric_limits< double >::epsilon( ) );\n    BOOST_CHECK_CLOSE_FRACTION( VACUUM_PERMITTIVITY, 1.0 /\n                                ( 4.0 * mathematical_constants::PI * 1.0E-7 * std::pow( SPEED_OF_LIGHT, 2.0 ) ),\n                                std::numeric_limits< double >::epsilon( ) );\n\n    // Test for Stefan-Boltzmann constant relation (derived from Planck and Boltzmann constants).\n    BOOST_CHECK_CLOSE_FRACTION( STEFAN_BOLTZMANN_CONSTANT, 2.0 * physical_constants::compile_time_pow(\n                                    mathematical_constants::PI, 5 ) *\n                                physical_constants::compile_time_pow( BOLTZMANN_CONSTANT, 4 ) /\n                                ( 15.0 * SPEED_OF_LIGHT * SPEED_OF_LIGHT *\n                                  PLANCK_CONSTANT * PLANCK_CONSTANT * PLANCK_CONSTANT ),\n                                std::numeric_limits< double >::epsilon( ) );\n\n    // Test for Stefan-boltzmann constant value (NIST, 2013)\n    BOOST_CHECK_CLOSE_FRACTION( STEFAN_BOLTZMANN_CONSTANT, 5.670373E-8, 1.0E-7 );\n\n    // Test time scale rate difference factors\n    BOOST_CHECK_CLOSE_FRACTION( LG_TIME_RATE_TERM, 6.969290134E-10, std::numeric_limits< double >::epsilon( ) );\n    BOOST_CHECK_CLOSE_FRACTION( LB_TIME_RATE_TERM, 1.550519768E-8, std::numeric_limits< double >::epsilon( ) );\n    BOOST_CHECK_CLOSE_FRACTION( LG_TIME_RATE_TERM_LONG, 6.969290134E-10L, std::numeric_limits< long double >::epsilon( ) );\n    BOOST_CHECK_CLOSE_FRACTION( LB_TIME_RATE_TERM_LONG, 1.550519768E-8L, std::numeric_limits< long  double >::epsilon( ) );\n\n\n}\n\n//! Check if the time constants have the expected values.\nBOOST_AUTO_TEST_CASE( testTimeConstants )\n{\n    using namespace physical_constants;\n\n    // Test for the number of Julian days in a year.\n    BOOST_CHECK_CLOSE_FRACTION( JULIAN_YEAR_IN_DAYS, 365.25,\n                                std::numeric_limits< double >::epsilon( ) );\n    BOOST_CHECK_CLOSE_FRACTION( JULIAN_YEAR_IN_DAYS_LONG, 365.25L,\n                                std::numeric_limits< long double >::epsilon( ) );\n\n    // Test for the number of sidereal days in a year.\n    BOOST_CHECK_CLOSE_FRACTION( SIDEREAL_YEAR_IN_DAYS, 365.25636,\n                                std::numeric_limits< double >::epsilon( ) );\n\n    // Test for the Julian day length.\n    BOOST_CHECK_CLOSE_FRACTION( SIDEREAL_DAY, 86164.09054,\n                                std::numeric_limits< double >::epsilon( ) );\n\n    // Test for the sidereal day length.\n    BOOST_CHECK_CLOSE_FRACTION( JULIAN_DAY, 86400.0,\n                                std::numeric_limits< double >::epsilon( ) );\n    BOOST_CHECK_CLOSE_FRACTION( JULIAN_DAY_LONG, 86400.0L,\n                                std::numeric_limits< long double >::epsilon( ) );\n}\n\n//! Test templated get physical constant functions\nBOOST_AUTO_TEST_CASE( testTemplatedConstantFunctions )\n{\n    using namespace physical_constants;\n\n    // Test for the number of Julian days in a year.\n    BOOST_CHECK_CLOSE_FRACTION( JULIAN_YEAR_IN_DAYS, getJulianYearInDays< double >( ),\n                                std::numeric_limits< double >::epsilon( ) );\n    BOOST_CHECK_CLOSE_FRACTION( JULIAN_YEAR_IN_DAYS_LONG, getJulianYearInDays< long double >( ),\n                                std::numeric_limits< long double >::epsilon( ) );\n\n    // Test for the sidereal day length.\n    BOOST_CHECK_CLOSE_FRACTION( JULIAN_DAY, getJulianDay< double >( ),\n                                std::numeric_limits< double >::epsilon( ) );\n    BOOST_CHECK_CLOSE_FRACTION( JULIAN_DAY_LONG, getJulianDay< long double >( ),\n                                std::numeric_limits< long double >::epsilon( ) );\n\n    // Test for speed of light.\n    BOOST_CHECK_CLOSE_FRACTION( SPEED_OF_LIGHT, getSpeedOfLight< double >( ),\n                                std::numeric_limits< double >::epsilon( ) );\n    BOOST_CHECK_CLOSE_FRACTION( SPEED_OF_LIGHT_LONG, getSpeedOfLight< long double >( ),\n                                std::numeric_limits< long double >::epsilon( ) );\n\n    // Test time scale rate difference factors\n    BOOST_CHECK_CLOSE_FRACTION( LG_TIME_RATE_TERM, getLgTimeRateTerm< double >( ),\n                                std::numeric_limits< double >::epsilon( ) );\n    BOOST_CHECK_CLOSE_FRACTION( LB_TIME_RATE_TERM, getLbTimeRateTerm< double >( ),\n                                std::numeric_limits< double >::epsilon( ) );\n    BOOST_CHECK_CLOSE_FRACTION( LG_TIME_RATE_TERM_LONG, getLgTimeRateTerm< long double >( ),\n                                std::numeric_limits< long double >::epsilon( ) );\n    BOOST_CHECK_CLOSE_FRACTION( LB_TIME_RATE_TERM_LONG, getLbTimeRateTerm< long double >( ),\n                                std::numeric_limits< long  double >::epsilon( ) );\n\n\n}\n\nBOOST_AUTO_TEST_SUITE_END( )\n\n} // namespace unit_tests\n} // namespace tudat\n", "meta": {"hexsha": "60751de0d2086f0d3a0c45b9da9707c644405fb9", "size": 8785, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/BasicAstrodynamics/UnitTests/unitTestPhysicalConstants.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/BasicAstrodynamics/UnitTests/unitTestPhysicalConstants.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/BasicAstrodynamics/UnitTests/unitTestPhysicalConstants.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": 47.4864864865, "max_line_length": 123, "alphanum_fraction": 0.6417757541, "num_tokens": 2057, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125626441471, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.45697033757049843}}
{"text": "#include <algorithm>\n#include <cstdlib>\n#include <memory>\n#include <tuple>\n#include <vector>\n#include <utility>\n\n#include <boost/filesystem.hpp>\n\n#include \"blas.h\"\n\nnamespace {\n\nclass Index {\n public:\n  Index(int order, int trans, int ld) : order_(order), trans_(trans), ld_(ld) { }\n  int operator()(int i, int j) {\n    if (trans_ == Blas::Trans) { int tmp = i; i = j; j = tmp; }  // transpose\n    return (order_ == Blas::RowMajor) ? (i * ld_ + j) : (i + ld_ * j);\n  }\n\n private:\n  int order_;\n  int trans_;\n  int ld_;\n};\n\nfloat builtin_sdot(int size, const float *x, int xstride, const float *y, int ystride) {\n  float result = 0.0f;\n  for (int i = 0; i < size; ++i) result += (x[i*xstride] * y[i*ystride]);\n  return result;\n}\n\nvoid builtin_saxpy(const int size, const float alpha,\n                   const float *x, const int xstride,\n                   float *y, const int ystride)\n{\n  for (int i = 0; i < size; ++i) {\n    y[i * ystride] += alpha * x[i * xstride];\n  }\n}\n\n// Convert sparse matrix from CSC to CSR format\n// CSC and CSR format described here: http://docs.nvidia.com/cuda/cusparse/#compressed-sparse-row-format-csr\n// Here is short summary for CSR format (Compressed Sparse Row Format):\n// - float* _val is an array of length NNZ (represents non-zero values of the matrix),\n// - int*   _ptr is an array of length m+1 (represents indices of the first non-zero element in row)\n// - int*   _ind is an array of length NNZ (represents column indices of non-zero values of the matrix)\n// All indices are 0-based.\nvoid builtin_scsr2csc(int m, int n, int nnz,\n                      const float *csr_val, const int* csr_row_ptr, const int *csr_col_ind,\n                      float *csc_val, int* csc_row_ind, int* csc_col_ptr)\n{\n  if (nnz <= 0) return;\n  std::vector<std::tuple<int, int, float>> coo_row_ind(nnz);\n  for (int i = 0; i < m; ++i) {\n    for (int j = csr_row_ptr[i]; j < csr_row_ptr[i + 1]; j++) {\n      std::get<0>(coo_row_ind[j]) = csr_col_ind[j];\n      std::get<1>(coo_row_ind[j]) = i;\n      std::get<2>(coo_row_ind[j]) = csr_val[j];\n    }\n  }\n\n  std::stable_sort(coo_row_ind.begin(), coo_row_ind.end());\n\n  for (int i = 0; i < nnz; ++i) {\n    csc_row_ind[i] = std::get<1>(coo_row_ind[i]);\n    csc_val[i] = std::get<2>(coo_row_ind[i]);\n  }\n\n  csc_col_ptr[n] = nnz;\n  for (int j = 0, i = 0; j < n; ++j) {\n    csc_col_ptr[j] = i;\n    while ((i < nnz) && (std::get<0>(coo_row_ind[i]) == j))\n      i++;\n  }\n}\n\n\nvoid builtin_sgemm(int order, const int transa, const int transb,\n                   const int m, const int n, const int k,\n                   const float alpha,\n                   const float * a, const int lda,\n                   const float * b, const int ldb,\n                   const float beta,\n                   float * c, const int ldc)\n{\n  Index ia(order, transa, lda);\n  Index ib(order, transb, ldb);\n  Index ic(order, Blas::NoTrans, ldc);\n\n  bool rowa_contiguous = (order == Blas::ColMajor) ? (transa == Blas::Trans) : (transa != Blas::Trans);\n  bool colb_contiguous = (order == Blas::ColMajor) ? (transb != Blas::Trans) : (transb == Blas::Trans);\n\n  // Remember that if any stride is non-contiguous then computation will be ~10 times slower.\n  // In such case consider to store transposed version of the matrix.\n  int astride = rowa_contiguous ? 1 : lda;\n  int bstride = colb_contiguous ? 1 : ldb;\n\n  for (int i = 0; i < m; ++i) {\n    for (int j = 0; j < n; ++j) {\n      const float* aa = a + ia(i, 0);\n      const float* bb = b + ib(0, j);\n      float& cc = c[ic(i, j)];\n      float result = builtin_sdot(k, aa, astride, bb, bstride);\n      cc = alpha * result + cc * beta;\n    }\n  }\n}\n\nclass BuiltinBlas : public Blas {\n public:\n  BuiltinBlas() {\n    sgemm = builtin_sgemm;\n    sdot = builtin_sdot;\n    saxpy = builtin_saxpy;\n    scsr2csc = builtin_scsr2csc;\n  }\n\n  virtual bool is_loaded() { return true; }\n};\n\n}  // namespace\n\n\nBlas* Blas::builtin() {\n  static BuiltinBlas impl;\n  return &impl;\n}\n", "meta": {"hexsha": "8d1a076354aea0ad0145fd450b87296283fd2e1b", "size": 3944, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/blas.cc", "max_stars_repo_name": "MelLain/cluster-bigartm", "max_stars_repo_head_hexsha": "bbd2a08a8c3f84238d6d3d44ffd305dde93eea7c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/blas.cc", "max_issues_repo_name": "MelLain/cluster-bigartm", "max_issues_repo_head_hexsha": "bbd2a08a8c3f84238d6d3d44ffd305dde93eea7c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-11-29T08:39:54.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-22T14:18:06.000Z", "max_forks_repo_path": "src/blas.cc", "max_forks_repo_name": "MelLain/cluster-bigartm", "max_forks_repo_head_hexsha": "bbd2a08a8c3f84238d6d3d44ffd305dde93eea7c", "max_forks_repo_licenses": ["BSD-3-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.3384615385, "max_line_length": 108, "alphanum_fraction": 0.599137931, "num_tokens": 1228, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.752012562644147, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4569703375704983}}
{"text": "#include <iostream>\n#include <Eigen/Core>\n#include <sys/time.h>\n\n#include \"celerite.h\"\n\nusing namespace Eigen;\n\ndouble get_timestamp () {\n  struct timeval now;\n  gettimeofday (&now, NULL);\n  return double(now.tv_usec) * 1.0e-6 + double(now.tv_sec);\n}\n\ntemplate <typename matrix, typename vector>\ntypename matrix::Scalar compute_likelihood (\n  const vector& a, const matrix& U, const matrix& V, const matrix& P, const vector& y\n) {\n  typedef typename matrix::Scalar T;\n  const int J = matrix::ColsAtCompileTime;\n  int N = a.rows();\n\n  vector d, z;\n  matrix W;\n  Matrix<T, J, J> S(J, J), bS(J, J);\n  Matrix<T, J, 1> F(J), G(J), bF(J), bG(J);\n\n  S.setZero();\n  d = a;\n  W = V;\n  int flag = celerite::factor(U, P, d, W, S);\n  T ll = log(d.array()).sum();\n\n  z = y;\n  celerite::solve(U, P, d, W, z, F, G);\n  ll += y.transpose() * z;\n\n  return ll;\n}\n\ntemplate <typename matrix, typename vector>\ntypename matrix::Scalar compute_grad_likelihood (\n  const vector& a, const matrix& U, const matrix& V, const matrix& P, const vector& y,\n  vector& ba, matrix& bU, matrix& bV, matrix& bP, vector& by\n) {\n  typedef typename matrix::Scalar T;\n  const int J = matrix::ColsAtCompileTime;\n  int N = a.rows();\n\n  vector d, z, bd(N), bz(N);\n  matrix W, bW(N, J);\n  Matrix<T, J, J> S(J, J), bS(J, J);\n  Matrix<T, J, 1> F(J), G(J), bF(J), bG(J);\n\n  S.setZero();\n  d = a;\n  W = V;\n  int flag = celerite::factor(U, P, d, W, S);\n  if (flag) std::cerr << flag << std::endl;\n  T ll = log(d.array()).sum();\n\n  z = y;\n  celerite::solve(U, P, d, W, z, F, G);\n  ll += y.transpose() * z;\n\n  // Seed gradients.\n  bz = y;\n  by = z;\n  bd.array() = 1.0 / d.array();\n\n  bF.setZero();\n  bG.setZero();\n\n  bU.setZero();\n  bP.setZero();\n  bW.setZero();\n\n  celerite::solve_grad(U, P, d, W, z, F, G, bz, bF, bG, bU, bP, bd, bW, by);\n\n  bS.setZero();\n  ba = bd;\n  bV = bW;\n  celerite::factor_grad(U, P, d, W, S, bS, bU, bP, ba, bV);\n\n  return ll;\n}\n\n#define NUMERICAL_GRAD(ARG, BARG)                         \\\n    ARG += eps;                                           \\\n    plus = compute_likelihood(a, U, V, P, y);             \\\n    ARG -= 2*eps;                                         \\\n    minus = compute_likelihood(a, U, V, P, y);            \\\n    ARG += eps;                                           \\\n    error = std::abs(BARG - 0.5 * (plus - minus) / eps);  \\\n    if (error > max_error) {                              \\\n      max_error = error;                                  \\\n      max_error_name = #ARG;                              \\\n    }\n\ntemplate <typename T, int J>\nvoid run_test (int N) {\n  const auto Options = J == 1 ? ColMajor : RowMajor;\n  typedef Matrix<T, Dynamic, J, Options> matrix;\n  typedef Matrix<T, Dynamic, 1> vector;\n\n  // Random matrices\n  srand(1234);\n  vector a(N), y = vector::Random(N);\n  matrix U = matrix::Random(N, J),\n         V = matrix::Random(N, J),\n         P = matrix::Random(N-1, J);\n  a.setConstant(10*J);\n\n  // Gradients\n  vector ba(N), by(N);\n  matrix bU(N, J),\n         bV(N, J),\n         bP(N-1, J);\n\n  compute_grad_likelihood(a, U, V, P, y, ba, bU, bV, bP, by);\n\n  T eps = T(1e-8);\n  T plus, minus, error, max_error = T(0.0);\n  auto max_error_name = \"nothing\";\n  for (int n = 0; n < N; ++n) {\n    NUMERICAL_GRAD(a(n), ba(n));\n    NUMERICAL_GRAD(y(n), by(n));\n    for (int j = 0; j < J; ++j) {\n      NUMERICAL_GRAD(U(n, j), bU(n, j));\n      NUMERICAL_GRAD(V(n, j), bV(n, j));\n      if (n < N-1) {\n        NUMERICAL_GRAD(P(n, j), bP(n, j));\n      }\n    }\n  }\n\n  std::cout << max_error << std::endl;\n  std::cout << max_error_name << std::endl;\n}\n\nint main ()\n{\n  run_test<double, 5>(10);\n\n  return 0;\n}\n", "meta": {"hexsha": "7d680b3a39952dc40ede7b598711c32ebbccf23f", "size": 3612, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/test.cc", "max_stars_repo_name": "dfm/celerite-grad", "max_stars_repo_head_hexsha": "5c7e8aa38ba33a37d9a9ef9ea66e54bd24dd119b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-09-27T22:46:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-03T10:00:55.000Z", "max_issues_repo_path": "src/test.cc", "max_issues_repo_name": "dfm/celerite-grad", "max_issues_repo_head_hexsha": "5c7e8aa38ba33a37d9a9ef9ea66e54bd24dd119b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/test.cc", "max_forks_repo_name": "dfm/celerite-grad", "max_forks_repo_head_hexsha": "5c7e8aa38ba33a37d9a9ef9ea66e54bd24dd119b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-01-26T02:54:24.000Z", "max_forks_repo_forks_event_max_datetime": "2018-05-19T15:35:55.000Z", "avg_line_length": 24.5714285714, "max_line_length": 86, "alphanum_fraction": 0.5246400886, "num_tokens": 1196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.752012562644147, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4569703375704983}}
{"text": "#include <blitz/timer.h>\n#include <iostream>\n#include <fstream>\n\nBZ_USING_NAMESPACE(blitz)\nBZ_USING_NAMESPACE(std)\n\nextern \"C\" {\n    void echo_f77tuned(int& N, int& niters, float& check, int& blockSize);\n}\n\nint main()\n{\n    int N = 1024;\n    int niters = 48;\n    float check;\n    double Mflops = niters * 9;\n    Timer timer;\n\n    ofstream ofs(\"echotune.log\");\n\n    cout << \"This program decides on the best block size for a typical 2D \"\n         << endl << \"stencil operation.  Pick the block size which has the \"\n         << endl << \"maximum Mflops/s.\" << endl << endl;\n\n    cout << \"Block size\\tMflops/s\" << endl;\n\n    int blockSize;\n\n    for (blockSize=1; blockSize < 32; ++blockSize)\n    {\n        timer.start();\n        echo_f77tuned(N, niters, check, blockSize);\n        timer.stop();\n        cout << blockSize << \"\\t\" << (Mflops/timer.elapsedSeconds()) << endl;\n        ofs << blockSize << \"\\t\" << (Mflops/timer.elapsedSeconds()) << endl;\n    }\n    for (; blockSize < 1024; blockSize += 32)\n    {\n        timer.start();\n        echo_f77tuned(N, niters, check, blockSize);\n        timer.stop();\n        cout << blockSize << \"\\t\" << (Mflops/timer.elapsedSeconds()) << endl;\n        ofs << blockSize << \"\\t\" << (Mflops/timer.elapsedSeconds()) << endl;\n    }\n    \n    return 0;\n}\n\n", "meta": {"hexsha": "22f6e32da31876d7256cad42494969e4a8eb57b9", "size": 1284, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depspawn-blitz-0.10/benchmarks/echotune.cpp", "max_stars_repo_name": "fraguela/depspawn", "max_stars_repo_head_hexsha": "b5760f4c0d38a1b245ee5274e2ccc5c5fe2d3d45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-04-12T11:05:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T11:10:27.000Z", "max_issues_repo_path": "ibtk/third_party/blitz-0.10/benchmarks/echotune.cpp", "max_issues_repo_name": "MSV-Project/IBAMR", "max_issues_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ibtk/third_party/blitz-0.10/benchmarks/echotune.cpp", "max_forks_repo_name": "MSV-Project/IBAMR", "max_forks_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.68, "max_line_length": 77, "alphanum_fraction": 0.5786604361, "num_tokens": 358, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195385342971, "lm_q2_score": 0.622459338205511, "lm_q1q2_score": 0.4569595621197937}}
{"text": "/*\n@copyright Louis Dionne 2015\nDistributed under the Boost Software License, Version 1.0.\n(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n */\n\n#include <boost/hana/assert.hpp>\n#include <boost/hana/equal.hpp>\n#include <boost/hana/integral_constant.hpp>\n#include <boost/hana/negate.hpp>\nnamespace hana = boost::hana;\n\n\nint main() {\n    BOOST_HANA_CONSTANT_CHECK(hana::negate(hana::int_c<3>) == hana::int_c<-3>);\n    static_assert(hana::negate(2) == -2, \"\");\n}\n", "meta": {"hexsha": "5ec6b225ee090f85c4a917bbfb86144cba4e4820", "size": 490, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/negate.cpp", "max_stars_repo_name": "qicosmos/hana", "max_stars_repo_head_hexsha": "b0f8cf2bf19d491b7b739dcb7b8d7497b0e5829f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-12-06T05:10:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-05T21:48:27.000Z", "max_issues_repo_path": "example/negate.cpp", "max_issues_repo_name": "qicosmos/hana", "max_issues_repo_head_hexsha": "b0f8cf2bf19d491b7b739dcb7b8d7497b0e5829f", "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": "example/negate.cpp", "max_forks_repo_name": "qicosmos/hana", "max_forks_repo_head_hexsha": "b0f8cf2bf19d491b7b739dcb7b8d7497b0e5829f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-06-06T10:50:17.000Z", "max_forks_repo_forks_event_max_datetime": "2017-06-06T10:50:17.000Z", "avg_line_length": 27.2222222222, "max_line_length": 79, "alphanum_fraction": 0.7204081633, "num_tokens": 139, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7341195385342971, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.45695955697827273}}
{"text": "#include \"mview.h\"\n#include \"FreeImage.h\"\n#include <Eigen/Dense>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n\nstatic CameraParameter ReadCameraParameterSet(std::string);\nstatic std::pair<GrayImage, RgbImage> ReadImageFromFile(std::string);\nstatic float ColourToGray(Eigen::Vector3f rgb);\n\nstd::string dataset_file() {\n\treturn \"data/rathaus/parameter.txt\";\n}\n\nauto read_dataset(std::istream& inputfile) -> std::vector<CameraParameter> {\n    std::vector<CameraParameter> cameraParameters;\n    std::string line;\n\n    while(std::getline(inputfile,line)) {\n\t\tcameraParameters.push_back(ReadCameraParameterSet(line));\n\t}\n\n\treturn cameraParameters;\n}\n\nauto read_image(CameraParameter cameraParameter) -> Image\n{\n  Image image;\n  image.intrinsics = cameraParameter.intrinsics;\n  image.extrinsics = cameraParameter.extrinsics;\n  std::tie(image.gray_pixels, image.rgb_pixels) = ReadImageFromFile(cameraParameter.filename);\n\n  return image;\n}\n\nstd::pair<GrayImage, RgbImage> ReadImageFromFile(std::string filename)\n{\n  std::cout << \"Reading \" << filename << std::endl;\n  std::string linebuffer;\n  int w = 3072, h = 2048;\n\n  std::fstream file(filename, std::ios_base::in | std::ios_base::binary);\n  file >> linebuffer >> w >> h >> linebuffer;\n\n  std::vector<unsigned char> raw_bytes(w*h*3);\n  auto read = file.rdbuf()->sgetn((char*)raw_bytes.data(), raw_bytes.size());\n  assert(read == raw_bytes.size());\n\n  RgbImage rgb_target { h, w };\n  for(int i = 0; i < w*h; i++)\n\tfor(int s = 0; s < 3; s++)\n      rgb_target(i/w, i%w)(s) = static_cast<float>(raw_bytes[3*i+s])/255.f;\n\n  GrayImage gray_target = rgb_target.unaryExpr([](auto color) { return ColourToGray(color); });\n\n  return {gray_target, rgb_target};\n}\n\nstatic CameraParameter ReadCameraParameterSet(std::string line) {\n\tCameraParameter cameraParameter;\n\tstd::istringstream iss(line);\n\tiss >> cameraParameter.filename;\n\tfloat ignore;\n\n\tfor(int i = 0; i < 3; i++)\n\t\tfor(int j = 0; j < 3; j++)\n\t\t\tiss >> cameraParameter.intrinsics(i, j);\n\t\n\tfor(int i = 0; i < 3; i++)\n\t\tiss >> ignore;\n\n\tEigen::Matrix3f rotation (3, 3);\n\tEigen::Vector3f translation (3, 1);\n\tfor(int i = 0; i < 3; i++)\n\t\tfor(int j = 0; j < 3; j++)\n\t\t\tiss >> rotation(i, j);\n\tfor(int i = 0; i < 3; i++)\n\t\tiss >> translation(i, 0);\n\n\tcameraParameter.extrinsics.block<3,3>(0, 0) = rotation.transpose();\n\tcameraParameter.extrinsics.block<3,1>(0, 3) = -rotation.transpose()*translation;\n\tcameraParameter.extrinsics(3, 3) = 1.0;\n\treturn cameraParameter;\n}\n\nstatic float ColourToGray(Eigen::Vector3f rgb) {\n  static constexpr float GAMMA = 2.2;\n\n  const Eigen::Vector3f gamma_correct = Eigen::Array3f(rgb).pow(GAMMA);\n  return gamma_correct.dot(Eigen::Vector3f { .2126, .7152, .0722 });\n}\n\n", "meta": {"hexsha": "f2203e5ad7543af85e9775da0bb782d0f969eb1a", "size": 2705, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "read_rathaus.cpp", "max_stars_repo_name": "temple-reconstruction/mview", "max_stars_repo_head_hexsha": "1440b5716d595c5c4d568fc45dd5afbb6f54dfc7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-09-17T07:39:35.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-24T21:09:27.000Z", "max_issues_repo_path": "read_rathaus.cpp", "max_issues_repo_name": "temple-reconstruction/mview", "max_issues_repo_head_hexsha": "1440b5716d595c5c4d568fc45dd5afbb6f54dfc7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-06-11T19:25:03.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-11T21:51:32.000Z", "max_forks_repo_path": "read_rathaus.cpp", "max_forks_repo_name": "temple-reconstruction/mview", "max_forks_repo_head_hexsha": "1440b5716d595c5c4d568fc45dd5afbb6f54dfc7", "max_forks_repo_licenses": ["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.7765957447, "max_line_length": 95, "alphanum_fraction": 0.6946395564, "num_tokens": 779, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195385342971, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.45695955697827273}}
{"text": "/*\n *  utils.hpp\n *\n *\tAuthor(s): Tamas D. Nagy\n *\tCreated on: 2016-11-08\n *\n *  Useful functions to provide compatibility\n *  of basic datatypes, mainly in matematical\n *  calculations.\n *\n */\n\n#ifndef DVRK_UTILS_HPP_\n#define DVRK_UTILS_HPP_\n\n#include <iostream>\n#include <sstream>\n#include <vector>\n#include <cmath>\n#include <Eigen/Dense>\n#include <Eigen/Geometry> \n#include <limits>\n\n#include <std_msgs/Float32.h>\n#include <irob_msgs/FloatArray.h>\n#include <geometry_msgs/PoseStamped.h>\n#include <geometry_msgs/Pose.h>\n#include <geometry_msgs/Vector3.h>\n#include <geometry_msgs/Transform.h>\n#include <sensor_msgs/JointState.h>\n#include <irob_msgs/ToolPose.h>\n#include <irob_msgs/ToolPoseStamped.h>\n#include <irob_msgs/Environment.h>\n\nnamespace saf {\n\ntypedef enum InterpolationMethod \n{LINEAR, BEZIER} InterpolationMethod;\n\ninline double degToRad(double deg) {\n  return (deg / 180.0) * M_PI;\n}\n\ninline double radToDeg(double rad) {\n  return (rad * 180.0) / M_PI;\n}\n\ntemplate<typename T>\nstd::ostream& operator<<(std::ostream& out, const std::vector<T>& v) {\n  out << \"[\";\n  size_t last = v.size() - 1;\n  for(size_t i = 0; i < v.size(); ++i) {\n    out << v[i];\n    if (i != last)\n      out << \", \";\n  }\n  out << \"]\";\n  return out;\n}\n\n\n/*std::ostream& operator<<(std::ostream& out, const Eigen::Affine3d& T) {\n  out << \"Translation:\\t\" << T.translation() << \"\\tRotation:\\t\" << T.rotation();\n  return out;\n}*/\n\n// Interpolation\n\ntemplate<typename T>\ninline T interpolate(double a, T const& x1, T const& x2) {\n  return ((1.0-a) * x1) + ((a) * x2);\n}\n\n\ntemplate <>\ninline Eigen::Quaterniond interpolate(double a,\n                                             const Eigen::Quaterniond& x1,\n                                             const Eigen::Quaterniond& x2) {\n  return x1.slerp(a, x2);\n}\n\n// Distance\n\ntemplate<typename T>\ninline double distanceEuler(T const& x1, T const& x2) {\n  return std::abs(x2 - x1);\n}\n\n\ntemplate <>\ninline double distanceEuler(const Eigen::Vector3d& x1,\n                            const Eigen::Vector3d& x2) {\n  return std::abs((x2-x1).norm());\n}\n\n// Conversion from ROS msg\ntemplate<typename MsgT, typename DataT>\ninline DataT unwrapMsg(const MsgT& msg);\n\ntemplate <>\ninline irob_msgs::Environment unwrapMsg(const irob_msgs::Environment& msg){\n  return msg;\n}\n\n\ntemplate <>\ninline double unwrapMsg(const std_msgs::Float32& msg){\n  return msg.data;\n}\n\n\ntemplate <>\ninline Eigen::Vector3d unwrapMsg(const geometry_msgs::Vector3& msg){\n  Eigen::Vector3d ret(msg.x, msg.y, msg.z);\n  return ret;\n}\n\ntemplate <>\ninline Eigen::Vector3d unwrapMsg(const geometry_msgs::Point& msg){\n  Eigen::Vector3d ret(msg.x, msg.y, msg.z);\n  return ret;\n}\n\n\n\ntemplate <>\ninline Eigen::Quaterniond unwrapMsg(const geometry_msgs::Quaternion& msg){\n  Eigen::Quaterniond ret(msg.w, msg.x, msg.y, msg.z);\n  return ret;\n}\n\ntemplate <>\ninline std::vector<double> unwrapMsg(const irob_msgs::FloatArray& msg){\n  return msg.data;\n}\n\ntemplate <>\ninline Eigen::Affine3d unwrapMsg(const geometry_msgs::Transform& msg){\n  Eigen::Quaterniond q(msg.rotation.w, msg.rotation.x,\n                            msg.rotation.y,msg.rotation.z);\n  Eigen::Translation3d t(msg.translation.x, msg.translation.y, msg.translation.z);\n  Eigen::Affine3d ret(t * q);\n  return ret;\n}\n\n// Conversion to ROS msg\ntemplate<typename MsgT, typename DataT>\ninline MsgT wrapToMsg(const DataT& data);\n\ntemplate <>\ninline std_msgs::Float32 wrapToMsg(const double& data){\n  std_msgs::Float32 msg;\n  msg.data = data;\n  return msg;\n}\n\ntemplate <>\ninline sensor_msgs::JointState wrapToMsg(const double& data){\n  sensor_msgs::JointState msg;\n  msg.name.push_back(\"jaw\");\n  msg.position.push_back(data);\n  return msg;\n}\n\n\ntemplate <>\ninline geometry_msgs::Vector3 wrapToMsg(const Eigen::Vector3d& data){\n  geometry_msgs::Vector3 msg;\n  msg.x = data.x();\n  msg.y = data.y();\n  msg.z = data.z();\n  return msg;\n}\n\ntemplate <>\ninline geometry_msgs::Point wrapToMsg(const Eigen::Vector3d& data){\n  geometry_msgs::Point msg;\n  msg.x = data.x();\n  msg.y = data.y();\n  msg.z = data.z();\n  return msg;\n}\n\ntemplate <>\ninline geometry_msgs::Quaternion wrapToMsg(\n    const Eigen::Quaterniond& data){\n  geometry_msgs::Quaternion msg;\n  msg.w = data.w();\n  msg.x = data.x();\n  msg.y = data.y();\n  msg.z = data.z();\n  return msg;\n}\n\ntemplate <>\ninline geometry_msgs::Transform wrapToMsg(\n    const Eigen::Affine3d& data){\n  geometry_msgs::Transform msg;\n\n  Eigen::Vector3d translation(data.translation());\n  Eigen::Quaterniond rotation(data.rotation());\n  msg.translation.x = translation.x();\n  msg.translation.y = translation.y();\n  msg.translation.z = translation.z();\n\n  msg.rotation.x = rotation.x();\n  msg.rotation.y = rotation.y();\n  msg.rotation.z = rotation.z();\n  msg.rotation.w = rotation.w();\n  return msg;\n}\n\n// NaN\ntemplate<typename DataT>\ninline DataT makeNaN();\n\n\ntemplate <>\ninline double makeNaN(){\n  return std::numeric_limits<double>::quiet_NaN();\n}\n\n\n\n\ntemplate <>\ninline Eigen::Vector3d makeNaN(){\n  Eigen::Vector3d ret(std::numeric_limits<double>::quiet_NaN(),\n                      std::numeric_limits<double>::quiet_NaN(),\n                      std::numeric_limits<double>::quiet_NaN());\n  return ret;\n}\n\n\ntemplate <>\ninline Eigen::Quaterniond makeNaN(){\n  Eigen::Quaterniond ret(std::numeric_limits<double>::quiet_NaN(),\n                                std::numeric_limits<double>::quiet_NaN(),\n                                std::numeric_limits<double>::quiet_NaN(),\n                                std::numeric_limits<double>::quiet_NaN());\n  return ret;\n}\n\ntemplate <>\ninline Eigen::Affine3d makeNaN(){\n  Eigen::Affine3d ret(Eigen::Translation3d(makeNaN<Eigen::Vector3d>()));\n  return ret;\n}\n\ntemplate <>\ninline std_msgs::Float32 makeNaN(){\n  std_msgs::Float32 msg;\n  msg.data = std::numeric_limits<double>::quiet_NaN();\n  return msg;\n}\n\ntemplate <>\ninline irob_msgs::FloatArray makeNaN(){\n  irob_msgs::FloatArray msg;\n  msg.data.push_back(std::numeric_limits<double>::quiet_NaN());\n  return msg;\n}\n\ntemplate <>\ninline geometry_msgs::Pose makeNaN(){\n  geometry_msgs::Pose nanp;\n  nanp.position.x = std::numeric_limits<double>::quiet_NaN();\n  nanp.position.y = std::numeric_limits<double>::quiet_NaN();\n  nanp.position.z = std::numeric_limits<double>::quiet_NaN();\n  nanp.orientation.x = std::numeric_limits<double>::quiet_NaN();\n  nanp.orientation.y = std::numeric_limits<double>::quiet_NaN();\n  nanp.orientation.z = std::numeric_limits<double>::quiet_NaN();\n  nanp.orientation.w = std::numeric_limits<double>::quiet_NaN();\n  return nanp;\n}\n\ntemplate <>\ninline irob_msgs::ToolPose makeNaN(){\n  irob_msgs::ToolPose nanp;\n  nanp.transform.translation.x = std::numeric_limits<double>::quiet_NaN();\n  nanp.transform.translation.y = std::numeric_limits<double>::quiet_NaN();\n  nanp.transform.translation.z = std::numeric_limits<double>::quiet_NaN();\n  nanp.transform.rotation.x = std::numeric_limits<double>::quiet_NaN();\n  nanp.transform.rotation.y = std::numeric_limits<double>::quiet_NaN();\n  nanp.transform.rotation.z = std::numeric_limits<double>::quiet_NaN();\n  nanp.transform.rotation.w = std::numeric_limits<double>::quiet_NaN();\n  nanp.jaw = std::numeric_limits<double>::quiet_NaN();\n  return nanp;\n}\n\ntemplate <>\ninline irob_msgs::Environment makeNaN(){\n  irob_msgs::Environment nanp;\n  nanp.valid = irob_msgs::Environment::INVALID;\n  return nanp;\n}\n\ntemplate <>\ninline geometry_msgs::Point makeNaN(){\n  geometry_msgs::Point msg;\n  msg.x = std::numeric_limits<double>::quiet_NaN();\n  msg.y = std::numeric_limits<double>::quiet_NaN();\n  msg.z = std::numeric_limits<double>::quiet_NaN();\n  return msg;\n}\n\ntemplate <>\ninline geometry_msgs::Transform makeNaN(){\n  geometry_msgs::Transform msg;\n  msg.translation.x = std::numeric_limits<double>::quiet_NaN();\n  msg.translation.y = std::numeric_limits<double>::quiet_NaN();\n  msg.translation.z = std::numeric_limits<double>::quiet_NaN();\n\n  msg.rotation.x = std::numeric_limits<double>::quiet_NaN();\n  msg.rotation.y = std::numeric_limits<double>::quiet_NaN();\n  msg.rotation.z = std::numeric_limits<double>::quiet_NaN();\n  msg.rotation.w = std::numeric_limits<double>::quiet_NaN();\n  return msg;\n}\n\n\n\ntemplate <>\ninline geometry_msgs::Quaternion makeNaN(){\n  geometry_msgs::Quaternion msg;\n  msg.w = std::numeric_limits<double>::quiet_NaN();\n  msg.x = std::numeric_limits<double>::quiet_NaN();\n  msg.y = std::numeric_limits<double>::quiet_NaN();\n  msg.z = std::numeric_limits<double>::quiet_NaN();\n  return msg;\n}\n\n\n// isnan\ntemplate<typename DataT>\ninline bool isnan(const DataT& d);\n\n\ntemplate <>\ninline bool isnan(const double& d)\n{\n  return std::isnan(d);\n}\n\n\n\n\ntemplate <>\ninline bool isnan(const Eigen::Vector3d& d)\n{\n  return (std::isnan(d.x())\n          || std::isnan(d.y())\n          || std::isnan(d.z()));\n}\n\n\ntemplate <>\ninline bool isnan(const Eigen::Quaterniond& d)\n{\n  return (std::isnan(d.x())\n          || std::isnan(d.y())\n          || std::isnan(d.z())\n          || std::isnan(d.w()));\n}\n\ntemplate <>\ninline bool isnan(const Eigen::Affine3d& d)\n{\n  return (d.translation().hasNaN() || d.rotation().hasNaN());\n}\n\n\ntemplate <>\ninline bool isnan(const std_msgs::Float32& d)\n{\n\n  return (std::isnan(d.data));\n}\n\ntemplate <>\ninline bool isnan(const geometry_msgs::Pose& d)\n{\n  return (std::isnan(d.position.x)\n          || std::isnan(d.position.y)\n          || std::isnan(d.position.z)\n          || std::isnan(d.orientation.x)\n          || std::isnan(d.orientation.y)\n          || std::isnan(d.orientation.z)\n          || std::isnan(d.orientation.w));\n}\n\ntemplate <>\ninline bool isnan(const irob_msgs::ToolPose& d)\n{\n  return (std::isnan(d.transform.translation.x)\n          || std::isnan(d.transform.translation.y)\n          || std::isnan(d.transform.translation.z)\n          || std::isnan(d.transform.rotation.x)\n          || std::isnan(d.transform.rotation.y)\n          || std::isnan(d.transform.rotation.z)\n          || std::isnan(d.transform.rotation.w)\n          || std::isnan(d.jaw));\n}\n\ntemplate <>\ninline bool isnan(const geometry_msgs::Point& d)\n{\n  return (std::isnan(d.x)\n          || std::isnan(d.y)\n          || std::isnan(d.z) );\n}\n\ntemplate <>\ninline bool isnan(const geometry_msgs::Transform& d)\n{\n  return (std::isnan(d.translation.x)\n          || std::isnan(d.translation.y)\n          || std::isnan(d.translation.z)\n          || std::isnan(d.rotation.x)\n          || std::isnan(d.rotation.y)\n          || std::isnan(d.rotation.z)\n          || std::isnan(d.rotation.w));\n}\n\n\ntemplate <>\ninline bool isnan(const geometry_msgs::Quaternion& d)\n{\n  return (std::isnan(d.x)\n          || std::isnan(d.y)\n          || std::isnan(d.z)\n          || std::isnan(d.w));\n}\n\n// Unit vector + rotation to quat\ntemplate<typename QuatT, typename VecT>\ninline QuatT vecToQuat(const VecT& vec, double angle);\n\ntemplate <>\ninline Eigen::Quaterniond vecToQuat(const Eigen::Vector3d& vec,\n                                           double angle){\n  Eigen::Quaterniond quat_start(0.0, 0.707107, 0.707106, 0.0);\n  double angle_rad = (angle / 180.0) * M_PI;\n  Eigen::Matrix3d R1m;\n  R1m = Eigen::AngleAxisd(0.0, Eigen::Vector3d::UnitX())\n      * Eigen::AngleAxisd(0.0,  Eigen::Vector3d::UnitY())\n      * Eigen::AngleAxisd(angle_rad, Eigen::Vector3d::UnitZ());\n  Eigen::Quaterniond R1(R1m);\n\n  Eigen::Quaterniond ret = R1 * quat_start;\n\n  Eigen::Vector3d vec_start(0.0, 0.0, -1.0);\n  Eigen::Quaterniond R2 =\n      Eigen::Quaterniond::FromTwoVectors(vec_start, vec);\n  ret = R2 * ret;\n  return ret;\n}\n\n// Quat to unit vector\ntemplate<typename QuatT, typename VecT>\ninline VecT quatToVec(const QuatT& quat);\n\ntemplate <>\ninline Eigen::Vector3d quatToVec(const Eigen::Quaterniond& quat){\n\n  Eigen::Quaterniond quat_start(0.0, 0.707107, 0.707106, 0.0);\n\n  Eigen::Quaterniond R = quat * quat_start.inverse();\n\n  Eigen::Vector3d vec_start(0.0, 0.0, -1.0);\n  Eigen::Vector3d ret = R * vec_start;\n  return ret;\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}\n\n#endif /* DVRK_UTILS_HPP_ */\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "dd301aab5b5f360d12b5ef78c6946b4ca658f6e9", "size": 11901, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "irob_utils/include/irob_utils/utils.hpp", "max_stars_repo_name": "ABC-iRobotics/irob-saf", "max_stars_repo_head_hexsha": "27832e1657912f7ad7e9812bb5020d6254137454", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2018-06-07T22:56:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-04T14:56:36.000Z", "max_issues_repo_path": "irob_utils/include/irob_utils/utils.hpp", "max_issues_repo_name": "ABC-iRobotics/irob-saf", "max_issues_repo_head_hexsha": "27832e1657912f7ad7e9812bb5020d6254137454", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-12-19T10:04:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-19T13:45:25.000Z", "max_forks_repo_path": "irob_utils/include/irob_utils/utils.hpp", "max_forks_repo_name": "ABC-iRobotics/irob-saf", "max_forks_repo_head_hexsha": "27832e1657912f7ad7e9812bb5020d6254137454", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2018-05-24T23:45:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-07T23:33:43.000Z", "avg_line_length": 23.1087378641, "max_line_length": 82, "alphanum_fraction": 0.6594403832, "num_tokens": 3078, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195385342971, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.45695955697827273}}
{"text": "#include <boost/config.hpp>\n#include <iostream>\n#include <vector>\n#include <boost/graph/connected_components.hpp>\n#include <boost/graph/adjacency_list.hpp>\n//using namespace std;\n//extern std::istream cin;\n//extern std::ostream cout;\nint main (){\n\tusing namespace boost;\n\t{\n\t\ttypedef adjacency_list < vecS, vecS, undirectedS > Graph;\n\t\tGraph G;\n\t\tlong int a, b, j = 0;\n\t\tstd::cin>>a;std::cin>>b;\n\t\twhile (!std::cin.eof()){\n\t\t\tadd_edge (a, b, G);\n\t\t\tstd::cin>>a;std::cin>>b;\n\t\t\tif (! ((j++)%100000000)) std::cerr << j << std::endl;\n\t\t}\n\t\tstd::cerr << \"done reading:\" << j << std::endl;\n\n\t\tstd::vector <long int> component (num_vertices(G));\n\t\tstd::cerr << \"Created graph\" << std::endl;\n\n\t\tint num = connected_components (G, &component[0]);\n\t\tstd::cerr << \"Connected graph\" << std::endl;\n\n\t\tstd::vector <long int>::size_type i;\n\t\tfor (i = 0; i != component.size(); ++i){\n\t\t\tstd::cout << i << \";\" << component[i] << std::endl;\n\t\t}\n\t}\n\treturn 0;\n}\n", "meta": {"hexsha": "98b94d85fb4ea6e861df061275be2588be92e781", "size": 944, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "connect.cpp", "max_stars_repo_name": "k----n/lookup", "max_stars_repo_head_hexsha": "d89367e6ff3e43947dbc902c14c4fe2b015b98fa", "max_stars_repo_licenses": ["RSA-MD"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "connect.cpp", "max_issues_repo_name": "k----n/lookup", "max_issues_repo_head_hexsha": "d89367e6ff3e43947dbc902c14c4fe2b015b98fa", "max_issues_repo_licenses": ["RSA-MD"], "max_issues_count": 35.0, "max_issues_repo_issues_event_min_datetime": "2020-03-18T07:45:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-16T18:22:31.000Z", "max_forks_repo_path": "connect.cpp", "max_forks_repo_name": "k----n/lookup", "max_forks_repo_head_hexsha": "d89367e6ff3e43947dbc902c14c4fe2b015b98fa", "max_forks_repo_licenses": ["RSA-MD"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-08-08T08:40:59.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-12T19:34:30.000Z", "avg_line_length": 26.2222222222, "max_line_length": 59, "alphanum_fraction": 0.6144067797, "num_tokens": 290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195385342971, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.45695955697827273}}
{"text": "#include <algorithm>\n#include <boost/functional/hash.hpp>\n#include <iostream>\n#include <sstream>\n#include <unordered_set>\n#include <vector>\n\nsize_t checksum(const std::vector<int>& nums) {\n    size_t seed = 0;\n    for (auto n : nums) {\n        boost::hash_combine(seed, n);\n    }\n    return seed;\n}\n\n\nint main() {\n    std::vector<int> nums;\n    {\n        std::string line;\n        std::getline(std::cin, line);\n        std::stringstream ss{line};\n        while (!ss.eof()) {\n            int x;\n            ss >> x;\n            nums.push_back(x);\n        }\n    }\n\n    std::unordered_set<size_t> hashes;\n    hashes.insert(checksum(nums));\n\n    int steps = 0;\n    for(;;) {\n        auto it = std::max_element(std::begin(nums), std::end(nums));\n        if (it == std::end(nums)) {\n            std::cerr << \"NO MAX!\\n\";\n            exit(1);\n        }\n        int val = 0;\n        std::swap(val, *it);\n        for(++it; val > 0; ++it, --val) {\n            if (it == std::end(nums)) {\n                it = std::begin(nums);\n            }\n            (*it)++;\n        }\n        ++steps;\n        if (!hashes.insert(checksum(nums)).second) {\n            break;\n        }\n    }\n\n    std::cout << \"steps: \" << steps << \"\\n\";\n}\n", "meta": {"hexsha": "56d98d425f9f10f030c43c9f409ee92f95d4ac9a", "size": 1215, "ext": "cc", "lang": "C++", "max_stars_repo_path": "puzzle_06_1.cc", "max_stars_repo_name": "mody/Advent-of-Code-2017", "max_stars_repo_head_hexsha": "446300f2562ad56c3da14644111d06ea4d0303f8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "puzzle_06_1.cc", "max_issues_repo_name": "mody/Advent-of-Code-2017", "max_issues_repo_head_hexsha": "446300f2562ad56c3da14644111d06ea4d0303f8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "puzzle_06_1.cc", "max_forks_repo_name": "mody/Advent-of-Code-2017", "max_forks_repo_head_hexsha": "446300f2562ad56c3da14644111d06ea4d0303f8", "max_forks_repo_licenses": ["Apache-2.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.6964285714, "max_line_length": 69, "alphanum_fraction": 0.4658436214, "num_tokens": 315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.734119526900183, "lm_q2_score": 0.6224593382055109, "lm_q1q2_score": 0.4569595548780307}}
{"text": "//Authors: Dario Cattaruzza, Alessandro Abate, Peter Schrammel, Daniel Kroening\n//University of Oxford 2016\n//This code is supplied under the BSD license agreement (see license.txt)\n\n#include <streambuf>\n#include <iostream>\n#include <fstream>\n#include <math.h>\n\n#include <boost/timer.hpp>\n\n#include \"Polyhedra.h\"\n#include \"VertexEnumerator.h\"\n\nnamespace abstract{\n\nusing std::max;\n\ntemplate <class scalar>\ntypename Tableau<scalar>::MatrixS Polyhedra<scalar>::ms_emptyMatrix(0,0);\n\ntemplate <class scalar>\nEigen::JacobiSVD<typename Tableau<scalar>::MatrixS> Polyhedra<scalar>::ms_svd;\n\ntemplate <class scalar>\nJordanMatrix<scalar>* Polyhedra<scalar>::ms_pJordan(NULL);\n\ntemplate <class scalar>\ntraceVertices_t Polyhedra<scalar>::ms_trace_vertices=eTraceNoVertex;\n\ntemplate <class scalar>\ntraceDynamics_t Polyhedra<scalar>::ms_trace_dynamics=eTraceNoDynamics;\n\ntemplate <class scalar>\nbool Polyhedra<scalar>::ms_auto_make_vertices=true;\n\n/// Constructs an empty buffer\ntemplate <class scalar>\nPolyhedra<scalar>::Polyhedra(int dimension) :\n  DualSimplex<scalar>(0,dimension),\n  m_isCentralised(false),\n  m_vertices(0,dimension),\n  m_tag(0),\n  m_loadTime(0),\n  m_transformTime(0),\n  m_enumerationTime(0),\n  m_calculationTime(0)\n{}\n\n/// Constructs transformed polyhedra\ntemplate <class scalar>\nPolyhedra<scalar>::Polyhedra(const Polyhedra &source,const MatrixS &transform,const MatrixS &inverse) :\n  DualSimplex<scalar>(source.m_size,source.getDimension()),\n  m_isCentralised(false),\n  m_vertices(0,getDimension()),\n  m_tag(0),\n  m_loadTime(0),\n  m_transformTime(0),\n  m_enumerationTime(0),\n  m_calculationTime(0)\n{\n  copy(source);\n  if (transform.rows()>0) this->transform(transform,inverse);\n}\n\n/// Calculates the convex hull of a point cloud\ntemplate <class scalar>\nbool Polyhedra<scalar>::convexHull(const MatrixS &points,const MatrixS &vectors)\n{\n  MatrixS supports=points*vectors;\n  m_faces=vectors.transpose();\n  m_supports=supports.transpose().rowwise().maxCoeff();\n  return load(m_faces,m_supports);\n}\n\n/// Loads a polyhedral description from file\ntemplate <class scalar>\nint Polyhedra<scalar>::loadData(const std::string &data,size_t pos,const bool vertices)\n{\n  size_t result=0;\n  boost::timer timer;\n  this->m_isNormalised=false;\n  m_vertices.resize(0,m_vertices.cols());\n  if ((result=data.find(\"cube<\",pos)) >= 0) {\n    int dimension=getDimension();\n    m_faces.resize(2*dimension,dimension);\n    m_faces.block(0,0,dimension,dimension)=MatrixS::Identity(dimension,dimension);\n    m_faces.block(dimension,0,dimension,dimension)=-MatrixS::Identity(dimension,dimension);\n    m_supports.resize(m_faces.rows(),1);\n    result+=5;\n    m_supports.coeffRef(0,0)=ms_logger.getNumber(data,result);\n    for (int row=1;row<m_faces.rows();row++) {\n      m_supports.coeffRef(row,0)=m_supports.coeff(row-1,0);\n    }\n    load(m_faces,m_supports);\n    m_loadTime=timer.elapsed()*1000;\n    return result;\n  }\n  int lines=MatToStr<scalar>::ms_defaultLogger.lines(data,pos);\n  if (lines==0) {\n    result=ms_logger.StringToMat(m_faces,data,pos);\n    clear();\n    return result;\n  }\n  if (vertices) {\n    result=ms_logger.StringToMat(m_vertices,data,pos);\n    if (result>0) makeFaces();\n    m_loadTime=timer.elapsed()*1000;\n    return result;\n  }\n  if (getDimension()==0) {\n    int cols=MatToStr<scalar>::ms_defaultLogger.cols(data,pos);\n    changeDimension(cols);\n  }\n  m_supports.resize(lines,1);\n  m_faces.resize(lines,getDimension());\n  result=ms_logger.StringToMat(m_faces,m_supports,data,pos);\n  if (result>0) {\n    load(m_faces,m_supports);\n    m_loadTime=timer.elapsed()*1000;\n    if (ms_trace_tableau>=eTraceTableau) logTableau(\"loaded \");\n    if (ms_auto_make_vertices && (m_faces.rows()>m_dimension)) makeVertices();\n  }\n  return result;\n}\n\n/// Loads a polyhedral description\ntemplate <class scalar>\nbool Polyhedra<scalar>::loadVertices(const MatrixS &vertices)\n{\n  changeDimension(vertices.cols());\n  m_vertices.conservativeResize(vertices.rows(),vertices.cols());\n  m_vertices.block(0,0,vertices.rows(),vertices.cols())=vertices;\n  if (makeFaces()) return true;\n  if (ms_trace_errors) ms_logger.logData(\"Failed to load vertices\");\n  return false;\n}\n\n/// Changes the dimensionality of the polyhedra\ntemplate <class scalar>\nvoid Polyhedra<scalar>::changeDimension(const int dimension,const bool keep)\n{\n  int cols=m_faces.cols();\n  int rows=keep ? m_faces.rows() : 0;\n  bool extend=keep && (dimension>cols);\n  int newRows=extend ? 2*(dimension-cols) : 0;\n  if (dimension!=cols) {\n    m_faces.conservativeResize(rows+newRows,dimension);\n    m_supports.conservativeResize(rows+newRows,1);\n    if (extend) {\n      m_faces.block(0,cols,rows,dimension-cols)=MatrixS::Zero(rows,dimension-cols);\n      m_faces.block(rows,0,newRows,cols)=MatrixS::Zero(newRows,cols);\n      m_faces.block(rows,cols,dimension-cols,dimension-cols)=MatrixS::Identity(dimension-cols,dimension-cols);\n      m_faces.block(rows+dimension-cols,cols,dimension-cols,dimension-cols)=-MatrixS::Identity(dimension-cols,dimension-cols);\n      m_supports.block(rows,0,newRows,1)=MatrixS::Zero(newRows,1);\n    }\n    load(m_faces,m_supports);\n  }\n}\n\n/// Loads a polyhedral description from file\ntemplate <class scalar>\nbool Polyhedra<scalar>::loadFromFile(const std::string &fileName)\n{\n  std::stringstream buffer;\n  std::ifstream file;\n  file.open(fileName.data());\n  if (!file.is_open()) return false;\n  buffer << file.rdbuf();\n  file.close();\n  std::string str=buffer.str();\n  return loadData(str);\n}\n\n/// Returns a description of the polyhedra\ntemplate <class scalar>\nstd::string Polyhedra<scalar>::getDescription(displayType_t displayType,bool interval,bool useBrackets,MatrixS& templates)\n{\n  if (displayType==eVertices) return getVertices(\",\",interval,useBrackets);\n  return getFaces(displayType==eNormalised,interval,useBrackets,templates);\n}\n\n/// Returns a description of the polyhedra\ntemplate <class scalar>\nstd::string Polyhedra<scalar>::getFaces(bool normalised,bool interval,bool useBrackets,MatrixS& templates)\n{\n  std::string result;\n  MatrixS faces=m_faces;\n  MatrixS supports=m_supports;\n  if (templates.cols()>0) {\n    faces=templates.transpose();\n    maximiseAll(templates,supports);\n  }\n  if (supports.rows()!=faces.rows()) {\n    int row=supports.rows();\n    supports.conservativeResize(faces.cols(),1);\n    for (;row<supports.rows();row++) supports.coeffRef(row,0)=func::ms_nan;\n  }\n\n  if (useBrackets) result+=ms_logger.IneToString(faces,supports,interval,normalised);\n  else          result+=ms_decoder.IneToString(faces,supports,interval,normalised);\n  if (m_isCentralised) {\n    result+=\"\\nc=\";\n    if (useBrackets)   result+=ms_logger.MatToString(m_centre,interval);\n    else            result+=ms_decoder.MatToString(m_centre,interval);\n  }\n  return result;\n}\n\n/// Returns a description of the vertices of the polyhedra\ntemplate <class scalar>\nstd::string Polyhedra<scalar>::getVertices(std::string separator,bool interval,bool useBrackets)\n{\n  makeVertices();\n  std::string result=ms_decoder.MatToString(m_vertices,interval);\n  if (m_isCentralised) {\n    result+=\"\\nc=\";\n    result+=ms_decoder.MatToString(m_centre,interval);\n  }\n  return result;\n}\n\n/// Copies the polyhedra from another source\ntemplate <class scalar>\nbool Polyhedra<scalar>::copy(const Polyhedra &source)\n{\n  if (!load(source.m_faces,source.m_supports)) return false;\n  this->m_isNormalised=source.m_isNormalised;\n  m_centre=source.m_centre;\n  m_isCentralised=source.m_isCentralised;\n  m_vertices.resize(source.m_vertices.rows(),source.m_vertices.cols());\n  m_vertices.block(0,0,m_vertices.rows(),m_vertices.cols())=source.m_vertices;\n  return true;\n}\n\ntemplate <class scalar>\nbool Polyhedra<scalar>::load(const MatrixS &faces,const MatrixS &supports,const bool transpose)\n{\n  boost::timer timer;\n  this->m_dimension=faces.cols()+1;\n  m_vertices.resize(0,getDimension());\n  if (!DualSimplex<scalar>::load(faces,supports,transpose)) return false;\n  if (&faces!=&m_faces) {\n    m_centre=MatrixS::Zero(1,getDimension());\n    m_isCentralised=false;\n  }\n  m_loadTime=timer.elapsed()*1000;\n  return true;\n}\n\n/// Indicates if the referenced polyhedra is contained inside this one\ntemplate <class scalar>\nbool Polyhedra<scalar>::contains(Polyhedra<scalar>& polyhedra)\n{\n  MatrixS supports(m_faces.rows(),1);\n  MatrixS matrix=m_faces.transpose();\n  polyhedra.maximiseAll(matrix,supports,this->eUnderAprox);\n  supports-=m_supports;\n  for (int i=0;i<supports.rows();i++) {\n    if (func::isPositive(supports.coeff(i,0))) {\n      return false;\n    }\n  }\n  return true;\n}\n\n/// Intersects the polyhedra with another polyhedra\ntemplate <class scalar>\nbool Polyhedra<scalar>::pseudoIntersect(const Polyhedra &polyhedra)\n{\n  if (polyhedra.m_dimension!=this->m_dimension) return false;\n  this->m_isNormalised=false;\n  int count=m_supports.rows();\n  int remoteCount=polyhedra.m_supports.rows();\n  m_faces.conservativeResize(count+remoteCount,m_faces.cols());\n  m_faces.block(count,0,remoteCount,m_faces.cols())=polyhedra.m_faces;\n  m_supports.conservativeResize(count+remoteCount,1);\n  m_supports.block(count,0,remoteCount,1)=polyhedra.m_supports;\n  load(m_faces,m_supports);\n  return true;\n}\n\n/// Calculates the pseudoinverse of a matrix\ntemplate <class scalar>\ntypename Tableau<scalar>::MatrixS Polyhedra<scalar>::pseudoInverseEigen(const MatrixS &matrix,bool &hasInverse)\n{\n  if (matrix.rows()!=matrix.cols()) return pseudoInverseSVD(matrix,hasInverse);\n  // We only care about the directions, so errors are acceptable (they only cause wrapping\n  MatrixR refMatrix(matrix.rows(),matrix.cols());\n  for (int row=0;row<matrix.rows();row++) {\n    for (int col=0;col<matrix.cols();col++) {\n      refMatrix.coeffRef(row,col)=func::toCentre(matrix.coeff(row,col));\n    }\n  }\n  Eigen::EigenSolver<MatrixR> eigenSpace(refMatrix);\n  if (eigenSpace.info()!=Eigen::Success) return this->getJordanSolver()->getSVDpseudoInverse(matrix,hasInverse);\n  MatrixRC eigenvalues=eigenSpace.eigenvalues().asDiagonal();\n  for (int row=0;row<matrix.rows();row++)\n  {\n    if (func::isZero(func::norm2(eigenvalues.coeff(row,row)),func::ms_weakZero)) hasInverse=false;\n    else eigenvalues.coeffRef(row,row)=refScalar(1)/eigenvalues.coeff(row,row);\n  }\n  if (hasInverse) return matrix.inverse();\n  MatrixRC eigenVectors=eigenSpace.eigenvectors();\n  eigenvalues=eigenVectors.inverse()*eigenvalues*eigenVectors;\n  MatrixS result(matrix.rows(),matrix.cols());\n  for (int row=0;row<matrix.rows();row++) {\n    for (int col=0;col<matrix.cols();col++) {\n      result.coeffRef(row,col)=eigenvalues.coeff(row,col).real();\n    }\n  }\n  if (ms_trace_dynamics>=eTraceDynamics) {\n    ms_logger.logData(matrix,\"Matrix:\");\n    ms_logger.logData(result,\"Inverse:\");\n  }\n  return result;\n}\n\n/// Calculates the pseudoinverse of a matrix\ntemplate <class scalar>\ntypename Tableau<scalar>::MatrixS Polyhedra<scalar>::pseudoInverseSVD(const MatrixS &matrix,bool &hasInverse)\n{\n  // We only care about the directions, so errors are acceptable (they only cause wrapping\n  MatrixR refMatrix(matrix.rows(),matrix.cols());\n  for (int row=0;row<matrix.rows();row++) {\n    for (int col=0;col<matrix.cols();col++) {\n      refMatrix.coeffRef(row,col)=func::toCentre(matrix.coeff(row,col));\n    }\n  }\n  return this->getJordanSolver()->getSVDpseudoInverse(matrix,hasInverse);\n}\n\n/// Calculates the pseudoinverse of a matrix\ntemplate <class scalar>\ntypename Tableau<scalar>::MatrixS Polyhedra<scalar>::pseudoInverseJordan(const MatrixS &matrix,bool &hasInverse)\n{\n  return this->getJordanSolver()->getPseudoInverse(matrix,hasInverse);\n}\n\n/// Intersects the polyhedra with another polyhedra\ntemplate <class scalar>\nbool Polyhedra<scalar>::intersect(const Polyhedra &polyhedra,const bool over)\n{\n  if (polyhedra.isEmpty()) return true;\n  if (pseudoIntersect(polyhedra)) {\n    MatrixS supports(m_faces.rows(),1);\n    bool redundant[supports.rows()];\n    MatrixS matrix=m_faces.transpose();\n    maximiseAll(matrix,supports);\n    for (int i=0;i<supports.rows();i++) {\n      scalar dif=m_supports.coeff(i,0)-supports.coeff(i,0);\n      char sign=func::hardSign(dif);\n      redundant[i]=(sign>0) || (over && (sign==0));\n    }\n    int pos=0;\n    for (int i=0;i<supports.rows();i++) {\n      if (!redundant[i]) {\n        m_faces.row(pos)=m_faces.row(i);\n        m_supports.coeffRef(pos++,0)=m_supports.coeff(i,0);\n      }\n    }\n    m_faces.conservativeResize(pos,m_faces.cols());\n    m_supports.conservativeResize(pos,1);\n    load(m_faces,m_supports);\n    return true;\n  }\n  return false;\n}\n\n/// Performs the union of another polyhedra with this one\ntemplate <class scalar>\nbool Polyhedra<scalar>::merge(Polyhedra &polyhedra,const bool extend)\n{\n  boost::timer timer;\n  if (polyhedra.isEmpty()) return true;\n  MatrixS supports2(m_faces.rows(),1);\n  MatrixS faceVectors2=m_faces.transpose();\n  polyhedra.maximiseAll(faceVectors2,supports2);\n  if (this->ms_trace_tableau>=eTraceTransforms) {\n    ms_logger.logData(m_faces,m_supports,\"Orig Set\");\n    ms_logger.logData(m_faces,supports2,\"Merge Set\");\n  }\n  if (extend) {\n    MatrixS supports(polyhedra.m_faces.rows(),1);\n    MatrixS faceVectors=polyhedra.m_faces.transpose();\n    maximiseAll(faceVectors,supports);\n    if (!pseudoIntersect(polyhedra)) return false;\n    for (int i=0;i<supports2.rows();i++) m_supports.coeffRef(i,0)=max(m_supports.coeff(i,0),supports2.coeff(i,0));\n    for (int i=0;i<supports.rows();i++) m_supports.coeffRef(i+supports2.rows(),0)=max(polyhedra.m_supports.coeff(i,0),supports.coeff(i,0));\n    this->removeRedundancies();\n  }\n  else {\n    for (int i=0;i<supports2.rows();i++) m_supports.coeffRef(i,0)=max(m_supports.coeff(i,0),supports2.coeff(i,0));\n  }\n  if (this->ms_trace_tableau>=eTraceTransforms) {\n    ms_logger.logData(m_faces,m_supports,\"Merged Set\");\n  }\n  if (this->ms_trace_time) {\n    int elapsed=timer.elapsed()*1000;\n    ms_logger.logData(elapsed,\" Merge time\",true);\n  }\n  return true;\n}\n\ntemplate <class scalar>\nbool Polyhedra<scalar>::concatenate(Polyhedra &polyhedra)\n{\n  return concatenate(polyhedra.m_faces,polyhedra.m_supports);\n}\n\ntemplate <class scalar>\nbool Polyhedra<scalar>::concatenate(MatrixS &faces,MatrixS &supports)\n{\n  int oldRows=m_faces.rows();\n  int oldCols=m_faces.cols();\n  m_faces.conservativeResize(oldRows+faces.rows(),oldCols+faces.cols());\n  m_supports.conservativeResize(oldRows+supports.rows(),1);\n  m_faces.block(0,oldCols,oldRows,faces.cols())=MatrixS::Zero(oldRows,faces.cols());\n  m_faces.block(oldRows,0,faces.rows(),oldCols)=MatrixS::Zero(faces.rows(),oldCols);\n  m_faces.block(oldRows,oldCols,faces.rows(),faces.cols())=faces;\n  m_supports.block(oldRows,0,supports.rows(),1)=supports;\n  load(m_faces,m_supports);\n  return true;\n}\n\n/// Performs the Minkowski sum of this polyhedra to another\ntemplate <class scalar>\nbool Polyhedra<scalar>::add(Polyhedra &polyhedra,const bool extended)\n{\n  if (polyhedra.isEmpty()) return true;\n  MatrixS supports2(m_faces.rows(),1);\n  MatrixS faceVectors2=m_faces.transpose();\n  polyhedra.maximiseAll(faceVectors2,supports2);\n  if (!extended) {\n    for (int i=0;i<supports2.rows();i++) {\n      m_supports.coeffRef(i,0)=m_supports.coeff(i,0)+supports2.coeff(i,0);\n    }\n    return true;\n  }\n  MatrixS supports(polyhedra.m_faces.rows(),1);\n  MatrixS faceVectors=polyhedra.m_faces.transpose();\n  maximiseAll(faceVectors,supports);\n  if (!pseudoIntersect(polyhedra)) return false;\n  for (int i=0;i<supports2.rows();i++) m_supports.coeffRef(i,0)=m_supports.coeff(i,0)+supports2.coeff(i,0);\n  int j=0;\n  for (int i=supports2.rows();i<m_supports.rows();i++,j++) m_supports.coeffRef(i,0)=m_supports.coeff(i,0)+supports.coeff(j,0);\n  this->removeRedundancies();\n  return true;\n}\n\n/// Performs the Minkowski difference of this polyhedra with another\ntemplate <class scalar>\nbool Polyhedra<scalar>::erode(Polyhedra &polyhedra)\n{\n  MatrixS supports(polyhedra.m_faces.rows(),1);\n  MatrixS supports2(m_faces.rows(),1);\n  MatrixS faceVectors=polyhedra.m_faces.transpose();\n  maximiseAll(faceVectors,supports);\n  MatrixS faceVectors2=m_faces.transpose();\n  polyhedra.maximiseAll(faceVectors2,supports2);\n  if (!pseudoIntersect(polyhedra)) return false;\n  for (int i=0;i<supports2.rows();i++) m_supports.coeffRef(i,0)=m_supports.coeff(i,0)-supports2.coeff(i,0);\n  int j=0;\n  for (int i=supports2.rows();i<m_supports.rows();i++,j++) m_supports.coeffRef(i,0)=m_supports.coeff(i,0)-supports.coeff(j,0);\n  this->removeRedundancies();\n  return true;\n}\n\n/// Adds a number of directions to the template of the polhedra\ntemplate <class scalar>\nbool Polyhedra<scalar>::addDirection(const MatrixS &directions)\n{\n  MatrixS supports(directions.cols(),1);\n  if (directions.rows()!=getDimension()) return false;\n  maximiseAll(directions,supports);\n  return addDirection(directions,supports);\n}\n\n/// Adds a number of directions to the template of the polhedra\ntemplate <class scalar>\nbool Polyhedra<scalar>::addDirection(const MatrixS &directions,MatrixS &supports)\n{\n  if (directions.rows()!=getDimension()) return false;\n  this->m_isNormalised=false;\n  int count=m_faces.rows();\n  m_faces.conservativeResize(count+directions.cols(),getDimension());\n  m_faces.block(count,0,directions.cols(),m_faces.cols())=directions.transpose();\n  m_supports.conservativeResize(count+directions.cols(),1);\n  m_supports.block(count,0,directions.cols(),1)=supports;  \n  this->removeRedundancies();\n  m_centre.resize(0,m_centre.cols());\n  m_vertices.resize(0,m_vertices.cols());\n  return true;\n}\n\n/// Retrieves a copy of this polyhedra transformed by the given matrix\ntemplate <class scalar>\nPolyhedra<scalar>& Polyhedra<scalar>::getTransformedPolyhedra(Polyhedra& polyhedra,const MatrixS& transform,const MatrixS& inverse,const MatrixS &templates)\n{\n  if (!polyhedra.copy(*this)) {\n    ms_logger.logData(m_name,false);\n    ms_logger.logData(\" loading Error\");\n    throw loadError;\n  }\n  if ((transform.rows()>0) || (inverse.rows()>0)) polyhedra.transform(transform,inverse);\n  if (templates.cols()>0) polyhedra.retemplate(templates);\n  return polyhedra;\n}\n\n/// linearly transofrm the polyhedra (rotate, translate, stretch)\ntemplate <class scalar>\nbool Polyhedra<scalar>::transform(const MatrixS &transform,const MatrixS& inverse)\n{\n  bool hasInverse=true;\n  if (this->isEmpty()) return true;\n  boost::timer timer;\n  if ((transform.rows()<=0) && (inverse.rows()>0)) {\n    this->m_isNormalised=false;\n    if (m_faces.cols()==inverse.rows()) m_faces*=inverse;\n    else m_faces*=inverse.transpose();\n    m_centre.resize(0,m_centre.cols());\n    m_vertices.resize(0,m_vertices.cols());\n  }\n  else {\n    if (transform.cols()!=getDimension()) return false;\n    if (transform.rows()>transform.cols()) {\n      int rows=transform.rows();\n      int cols=transform.cols();\n      MatrixS newTransform(rows,rows);\n      newTransform.block(0,0,rows,cols)=transform;\n      newTransform.block(0,cols,rows,rows-cols)=MatrixS::Zero(rows,rows-cols);\n      changeDimension(rows,true);\n      return this->transform(newTransform);\n    }\n    if (m_centre.rows()>0) {\n      if (m_centre.cols()==transform.cols()) {\n        m_centre=m_centre*transform.transpose();\n        if (m_isCentralised) m_isCentralised=(func::isPositive(m_centre.norm()));\n      }\n    }\n    if (m_vertices.rows()>0) m_vertices*=transform.transpose();\n    this->m_isNormalised=false;\n    if (inverse.rows()>0) m_faces*=inverse;\n    else {\n      MatrixS matrix=pseudoInverseEigen(transform,hasInverse);\n      if (ms_trace_dynamics>=eTraceDynamics) {\n        ms_logger.logData(transform,\"Transform:\");\n        ms_logger.logData(matrix,\"Pseudo Inverse:\");\n      }\n      if (hasInverse) m_faces*=matrix;// The normal gets multiplied by A^-1^T\n      else {\n        MatrixS faces(2*m_faces.rows(),getDimension());\n        faces.block(0,0,m_faces.rows(),getDimension())=m_faces;\n        faces.block(m_faces.rows(),0,m_faces.rows(),getDimension())=m_faces*matrix;\n        MatrixS supports;\n        MatrixS vectors=transform.transpose()*faces.transpose();\n        if (this->ms_trace_tableau>=eTraceTableau) this->logTableau();\n        maximiseAll(vectors,supports);\n        m_faces=faces;\n        m_supports=supports;\n        return this->removeRedundancies();\n      }\n    }\n  }\n  bool result=DualSimplex<scalar>::load(m_faces,m_supports);\n  m_transformTime=timer.elapsed()*1000;\n  if (this->ms_trace_time) {\n    if (m_transformTime>1) {\n      ms_logger.logData(m_name,false);\n      ms_logger.logData(m_transformTime,\" Transform:\",true);\n    }\n  }\n  return result;\n}\n\n/// templates the polyhedra in the given directions\ntemplate <class scalar>\nbool Polyhedra<scalar>::retemplate(const MatrixS& templates,refScalar aprox)\n{\n  MatrixS supports(templates.cols(),1);\n  decentralize();\n  this->m_isNormalised=false;\n  if (aprox<0) {\n    refScalar threshold=1+aprox;\n    this->removeRedundancies();\n    if (!makeVertices()) return false;\n    for (int dir=0;dir<templates.cols();dir++) {\n      scalar support=-func::ms_infinity;\n      supports.coeffRef(dir,0)=support;\n      for (int point=0;point<m_vertices.rows();point++) {\n        MatrixS thisSupport=m_vertices.row(point)*templates.block(0,dir,m_vertices.cols(),1);\n        if (thisSupport.coeff(0,0)>support) support=thisSupport.coeff(0,0);\n      }\n      supports.coeffRef(dir,0)=support;\n      for (int point=0;point<m_vertices.rows();point++) {\n        MatrixS thisSupport=m_vertices.row(point)*templates.block(0,dir,m_vertices.cols(),1);\n        if ((thisSupport.coeff(0,0)>support*threshold) && (thisSupport.coeff(0,0)<supports.coeffRef(dir,0)))\n        {\n          supports.coeffRef(dir,0)=thisSupport.coeff(0,0);\n        }\n      }\n    }\n    addDirection(templates,supports);\n    logTableau();//templog\n    this->removeRedundancies();\n    //m_vertices.resize(0,m_vertices.cols());\n    makeVertices(true);\n    if (!makeFaces()) return false;\n    logTableau();//templog\n    for (int i=0;i<supports.rows();i++) supports.coeffRef(i,0)=func::toLower(supports.coeffRef(i,0));\n    return true;\n  }\n  maximiseAll(templates,supports);\n  m_faces=templates.transpose();\n  m_supports=supports;\n  return load(m_faces,m_supports);\n}\n\n/// linearly transofrm the polyhedra (rotate, translate, stretch)\ntemplate <class scalar>\nvoid Polyhedra<scalar>::transform(const scalar &coefficient)\n{\n  this->m_isNormalised=false;\n  decentralize();\n  if (m_vertices.rows()>0) m_vertices*=coefficient;\n  m_supports*=coefficient;\n  m_centre*=coefficient;\n  m_isCentralised=(m_centre.norm()>this->m_zero);\n  load(m_faces,m_supports);\n}\n\n/// linearly transofrm the polyhedra through vertex enumeration\ntemplate <class scalar>\nbool Polyhedra<scalar>::vertexTransform(const MatrixS &transform,const MatrixS &templates)\n{\n  if (!makeVertices()) return false;\n  MatrixS vertices=m_vertices*transform.transpose();\n  return convexHull(vertices,templates);\n}\n\n/// finds the inequalities of the polyhedra and stores them in a matrix\ntemplate <class scalar>\nbool Polyhedra<scalar>::makeFaces()\n{\n  if (m_vertices.rows()<=0) return true;\n  decentralize();\n  MatrixS supports=MatrixS::Ones(m_vertices.rows(),1);\n  MatrixS centre=m_vertices.colwise().sum()/m_vertices.rows();\n  for (int row=0;row<m_vertices.rows();row++) m_vertices.row(row)-=centre;\n  VertexEnumerator<scalar> enumerator(m_vertices.rows(),m_vertices.cols());\n  typename VertexEnumerator<scalar>::RayList& rayList=enumerator.findVertices(m_vertices,supports,true);\n  int numFaces=rayList.size();\n  if (numFaces==0) return false;\n  m_faces.resize(numFaces,getDimension());\n  m_supports.resize(numFaces,1);\n  int row=0;\n  for (typename VertexEnumerator<scalar>::RayList::iterator it=rayList.begin();it!=rayList.end();it++,row++) {\n    m_faces.row(row)=it->data.block(0,1,1,m_faces.cols());\n    m_supports.coeffRef(row,0)=it->data.coeff(0,0);\n  }\n  centre=-centre;\n  m_supports-=m_faces*centre.transpose();\n  load(m_faces,m_supports);\n  return true;\n}\n\ntemplate <class scalar>\nvoid Polyhedra<scalar>::logVertices(bool force)\n{\n  if ((ms_trace_vertices>=eTraceVertices) || force) {\n    makeVertices(force);\n    ms_logger.logData(m_name,false);\n    ms_logger.logData(m_vertices,\" Vertices:\");\n  }\n}\n\ntemplate <class scalar>\nvoid Polyhedra<scalar>::logPolyhedra(std::string parameters)\n{\n  if (parameters.length()>0) {\n    std::stringstream stream;\n    stream << getName();\n    stream << \": \" << parameters;\n    ms_logger.logData(m_faces,m_supports,stream.str());\n  }\n  else ms_logger.logData(m_faces,m_supports,getName());\n  if (ms_trace_vertices>=eTraceVertices) {\n    makeVertices();\n    ms_logger.logData(m_vertices,\" Vertices:\");\n  }\n}\n\n/// finds the vertices of the polyhedra and stores them in a matrix\ntemplate <class scalar>\nbool Polyhedra<scalar>::makeVertices(bool force)\n{\n  if (!force && (m_vertices.rows()>0)) return true;\n  if (m_faces.rows()==0) {\n    return false;\n  }\n  boost::timer timer;\n  this->normalise();\n  VertexEnumerator<scalar> enumerator(m_faces.rows(),m_faces.cols());\n  typename VertexEnumerator<scalar>::RayList& rayList=enumerator.findVertices(m_faces,m_supports,false);\n  enumerator.logRays();\n\n  int numVertices=rayList.size();\n  if (numVertices==0) {\n    if (this->ms_trace_time) {\n      ms_logger.logData(m_name,false);\n      ms_logger.logData(timer.elapsed()*1000,\" Make Vertices Time:\",true);\n    }\n    if (ms_trace_errors) {\n      ms_logger.logData(m_name, false);\n      ms_logger.logData(\": Failed to make vertices\");\n      logTableau();\n    }\n    return false;\n  }\n  m_vertices.resize(numVertices,getDimension());\n\n  int row=0;\n  for (typename VertexEnumerator<scalar>::RayList::iterator it=rayList.begin();it!=rayList.end();it++,row++) {\n    scalar scale = abs(it->data.coeff(0,0));\n    if (func::isZero(scale)) scale=1;\n    for (int col=0;col<m_vertices.cols();col++) m_vertices.coeffRef(row,col)=it->data.coeff(0,col+1)/scale;\n  }\n  m_enumerationTime=timer.elapsed()*1000;\n  if (ms_trace_vertices>=eTraceVertices) {\n    ms_logger.logData(m_name,false);\n    ms_logger.logData(\" Find Vertices:\");\n    this->logTableau();\n  }\n  if (this->ms_trace_time) {\n    ms_logger.logData(m_name,false);\n    ms_logger.logData(m_enumerationTime,\" Make Vertices Time:\",true);\n  }\n  return true;\n}\n\n/// Removes any existing faces\ntemplate <class scalar>\nvoid Polyhedra<scalar>::clear()\n{\n  m_faces.resize(0,getDimension());\n  m_supports.resize(0,1);\n  load(m_faces,m_supports);\n}\n\n/// Retrieves the (hyper-rectangular) center of the polyhedra\ntemplate <class scalar>\ntypename Tableau<scalar>::MatrixS& Polyhedra<scalar>::getCentre()\n{\n  if (!m_isCentralised) {\n    MatrixS positiveDirections=MatrixS::Identity(getDimension(),getDimension());\n    MatrixS positiveSupports;\n    maximiseAll(positiveDirections,positiveSupports);\n    MatrixS negativeDirections=-positiveDirections;\n    MatrixS negativeSupports;\n    maximiseAll(negativeDirections,negativeSupports);\n    m_centre=(positiveSupports-negativeSupports).transpose()/2;\n  }\n  return m_centre;\n}\n\n/// Finds the (hyper-rectangular) center of the polyhedra, and moves it to the origin\ntemplate <class scalar>\nvoid Polyhedra<scalar>::centralize()\n{\n  if (m_isCentralised) return;\n  m_isCentralised=false;\n  translate(getCentre());\n}\n\n/// Translates the polyhedra in the direction of vector\ntemplate <class scalar>\nvoid Polyhedra<scalar>::translate(const MatrixS &vector,const bool storeOffset)\n{\n  if (storeOffset) {\n    if (m_isCentralised)  m_centre+=vector;\n    else                  m_centre=vector;\n    m_isCentralised=(func::toLower(m_centre.norm())>this->m_zero);\n  }\n  for (int row=0;row<m_vertices.rows();row++) m_vertices.row(row)-=vector;\n  MatrixS matrix=m_faces*vector.transpose();\n  m_supports-=matrix;\n}\n\n/// Moves the polyhedra by the vector indicated in centre.\ntemplate <class scalar>\nvoid Polyhedra<scalar>::decentralize()\n{\n  if (!m_isCentralised) return;\n  MatrixS minCentre=-m_centre;\n  translate(minCentre);\n  m_isCentralised=false;\n}\n\n/// Indicates if there is a selected non-zero central point\ntemplate <class scalar>\nbool Polyhedra<scalar>::isCentralized()\n{\n  return m_isCentralised;//(m_centre.norm()>this->m_zero);\n}\n\n/// Indicates if a set of points is inside the Polyhedra\ntemplate <class scalar>\nbool Polyhedra<scalar>::isInside(const MatrixS &points)\n{\n  if (points.cols()!=getDimension()) return false;\n  MatrixS supports=m_faces*points.transpose();\n  for (int col=0;col<supports.cols();col++) {\n    supports.col(col)-=m_supports;\n    for (int row=0;row<supports.rows();row++) {\n      if (func::toUpper(supports.coeff(row,col))>0) {\n        /*ms_logger.logData(points,\"Points\");\n        ms_logger.logData(supports,\"Supports\");\n        logTableau(\"True Supports\",true);*/\n        return false;\n      }\n    }\n  }\n  return true;\n}\n\n\ntemplate <class scalar>\nvoid Polyhedra<scalar>::ComputeVertexOrderVector()\n{\n  m_vertices.QuickAngleSort();\n}\n\ntemplate <class scalar>\ntypename Tableau<scalar>::MatrixS Polyhedra<scalar>::vertexMaximize(const MatrixS &vectors,const bool all)\n{\n  if (!makeVertices()) return MatrixS(0,0);\n  if (m_vertices.cols()!=vectors.cols()) return MatrixS::Zero(vectors.cols(),1);\n  MatrixS result=(m_vertices*vectors).transpose();\n  if (all) return result;\n  MatrixS supports=result.rowwise().maxCoeff();\n  return supports;\n}\n\ntemplate <class scalar>\ntypename Tableau<scalar>::MatrixS Polyhedra<scalar>::boundingHyperBox()\n{\n  int dimension=getDimension();\n  MatrixS hyperbox(2*dimension,2);\n  makeVertices();\n  for (int i=0;i<dimension;i++) {\n    hyperbox.coeffRef(i,0)=m_vertices.coeff(0,i);\n    hyperbox.coeffRef(i,1)=m_vertices.coeff(0,i);\n  }\n  for  (int row=1;row<m_vertices.rows();row++) {\n    for (int i=0;i<dimension;i++) {\n      if (m_vertices.coeff(row,i)<hyperbox.coeff(i,0)) hyperbox.coeffRef(i,0)=m_vertices.coeff(0,i);\n      if (m_vertices.coeff(row,i)>hyperbox.coeff(i,1)) hyperbox.coeffRef(i,1)=m_vertices.coeff(0,i);\n    }\n  }\n  return hyperbox;\n}\n\ntemplate <class scalar>\nJordanMatrix<scalar>* Polyhedra<scalar>::getJordanSolver()\n{\n  if (!ms_pJordan) ms_pJordan=new JordanMatrix<scalar>(0);\n  return ms_pJordan;\n}\n\n#ifdef USE_LDOUBLE\n  #ifdef USE_SINGLES\n    template class Polyhedra<long double>;\n  #endif\n  #ifdef USE_INTERVALS\n    template class Polyhedra<ldinterval>;\n  #endif\n#endif\n#ifdef USE_MPREAL\n  #ifdef USE_SINGLES\n    template class Polyhedra<mpfr::mpreal>;\n  #endif\n  #ifdef USE_INTERVALS\n    template class Polyhedra<mpinterval>;\n  #endif\n#endif\n\n}\n", "meta": {"hexsha": "efa45589c699eef78281e71c411730862f7ae031", "size": 30199, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "toolbox-dssynth/dssynth-tool/benchmark-runner/AACegar/src/Polyhedra.cpp", "max_stars_repo_name": "SSV-Group/dsverifier", "max_stars_repo_head_hexsha": "1daca4704216edf9a360b4a39e00663d94646ad1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2016-08-29T19:23:25.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-18T22:27:21.000Z", "max_issues_repo_path": "toolbox-dssynth/dssynth-tool/benchmark-runner/AACegar/src/Polyhedra.cpp", "max_issues_repo_name": "SSV-Group/dsverifier", "max_issues_repo_head_hexsha": "1daca4704216edf9a360b4a39e00663d94646ad1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 64.0, "max_issues_repo_issues_event_min_datetime": "2016-09-10T16:29:44.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-15T14:31:06.000Z", "max_forks_repo_path": "toolbox-dssynth/dssynth-tool/benchmark-runner/AACegar/src/Polyhedra.cpp", "max_forks_repo_name": "SSV-Group/dsverifier", "max_forks_repo_head_hexsha": "1daca4704216edf9a360b4a39e00663d94646ad1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2016-10-09T21:38:41.000Z", "max_forks_repo_forks_event_max_datetime": "2017-07-05T10:05:32.000Z", "avg_line_length": 34.0078828829, "max_line_length": 156, "alphanum_fraction": 0.7193946819, "num_tokens": 8095, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4569595497365099}}
{"text": "//#########################################################//\n//#                                                       #//\n//# gaussian_mixture_models  gmm_regressor.cpp            #//\n//# Roberto Capobianco  <capobianco@dis.uniroma1.it>      #//\n//#                                                       #//\n//#########################################################//\n\n#include <Eigen/Core>\n#include <iostream>\n#include <set>\n#include <stdexcept>\n#include <vector>\n\n#include <omp.h>\n\n#include <particle_filter/gmm_regressor.h>\n#include <particle_filter/matrix_io.h>\n\nnamespace gmms {\nvoid GMMRegressor::train(const Eigen::MatrixXd& dataset,\n        bool evaluate_bic,\n        int gmm_components) {\n    int num_components;\n    double bic = 0.0;\n    bool first_trial = true;\n    input_size_ = dataset.cols();\n\n    std::cout << \"Training regressor\" << std::endl;\n    std::cout << \"\\t\\tEvaluate BIC: \";\n\n    if (evaluate_bic) {\n        std::cout << \"ON\" << std::endl;\n        num_components = 1;\n    } else {\n        std::cout << \"OFF\" << std::endl;\n        num_components = gmm_components;\n    }\n\n#pragma parallel for\n    for (int c = num_components; c <= gmm_components; ++c) {\n        std::cout << \"\\t\\t\\t\\tUsing \" << c << \" GMM components\" << std::endl;\n\n        std::shared_ptr<GaussianMixtureModel> model(new GaussianMixtureModel);\n        model->setNumComponents(c);\n        model->initialize(dataset);\n        model->setNumIterations(max_iterations_);\n        model->setDelta(delta_);\n\n        try {\n            model->expectationMaximization(dataset);\n        } catch (std::runtime_error e) {\n            std::cout << \"\\t\\t\\t\\t\" << c << \" components are not usable\"\n                      << std::endl;\n            break;\n        }\n\n        double trial_bic = model->bayesianInformationCriterion(dataset);\n\n        std::cout << \"\\t\\t\\t\\tTrial BIC: \" << trial_bic << std::endl;\n\n        if (first_trial || trial_bic < bic) {\n            bic = trial_bic;\n            gmm_ = model;\n\n            if (first_trial) {\n                first_trial = false;\n            }\n        }\n    }\n\n    std::cout << \"\\t\\tFinal model with \" << gmm_->numComponents() << \"; \";\n    std::cout << \"BIC \" << bic << std::endl;\n\n    trained_ = true;\n}\n\nEigen::MatrixXd GMMRegressor::predict(const Eigen::MatrixXd& dataset,\n        const Eigen::VectorXi& output_indices) const {\n    if (!trained_ || gmm_ == nullptr) {\n        throw std::runtime_error(nottrained_());\n    }\n\n    int query_size = dataset.cols();\n    int target_size = output_indices.size();\n\n    if (query_size + target_size != input_size_) {\n        throw std::runtime_error(notconsistent_());\n    }\n\n    if (target_size == 0) {\n        throw std::runtime_error(notvalid_());\n    }\n\n    int dataset_size = dataset.rows();\n    int num_components = gmm_->numComponents();\n    Eigen::VectorXi input_indices(query_size);\n\n    int idx = 0;\n    for (int i = 0; i < input_size_; ++i) {\n        if (!(output_indices.array() == i).any()) {\n            input_indices(idx++) = i;\n        }\n    }\n\n    Eigen::VectorXi indices(input_size_);\n    indices.head(query_size) = input_indices;\n    indices.tail(target_size) = output_indices;\n    Eigen::PermutationMatrix<Eigen::Dynamic, Eigen::Dynamic, int> P =\n            indices.asPermutation().transpose();\n\n    Eigen::MatrixXd regressions =\n            Eigen::MatrixXd::Zero(dataset_size, target_size);\n\n    std::vector<Gaussian> reduced_gaussians(num_components);\n    std::vector<double> normalization_factor(dataset_size, 0.0);\n\n    for (int k = 0; k < num_components; ++k) {\n        Eigen::VectorXd mean_k = gmm_->component(k).mean();\n        Eigen::MatrixXd covariance_k = gmm_->component(k).covariance();\n\n        mean_k = P * mean_k;\n        covariance_k = P * covariance_k * P.transpose();\n\n        Eigen::VectorXd query_mean = mean_k.head(query_size);\n        Eigen::VectorXd target_mean = mean_k.tail(target_size);\n        Eigen::MatrixXd query_covariance =\n                covariance_k.topLeftCorner(query_size, query_size);\n        Eigen::MatrixXd target_covariance =\n                covariance_k.bottomRightCorner(target_size, target_size);\n        Eigen::MatrixXd query_target_covariance =\n                covariance_k.topRightCorner(query_size, target_size);\n        Eigen::MatrixXd target_query_covariance =\n                query_target_covariance.transpose();\n        Eigen::MatrixXd inv_query_covariance = query_covariance.inverse();\n\n        reduced_gaussians[k].setMeanCovariance(query_mean, query_covariance);\n\n        Eigen::MatrixXd conditional_covariance =\n                target_covariance - target_query_covariance *\n                                            inv_query_covariance *\n                                            query_target_covariance;\n\n#pragma omp parallel for\n        for (int i = 0; i < dataset_size; ++i) {\n            Eigen::VectorXd query = dataset.row(i);\n            double query_probability =\n                    reduced_gaussians[k].evaluate_point(query);\n\n            Eigen::VectorXd tmp(target_size);\n            tmp = target_mean + target_query_covariance * inv_query_covariance *\n                                        (query - query_mean);\n            tmp *= query_probability;\n\n            regressions.row(i) += tmp;\n            normalization_factor[i] += query_probability;\n\n            if (k == num_components - 1) {\n                regressions.row(i) /= normalization_factor[i];\n            }\n        }\n    }\n\n    return regressions;\n}\n\nvoid GMMRegressor::load(const std::string filename) {\n    MatrixIO mio;\n    Eigen::MatrixXd model;\n\n    mio.readFromFile(filename, model);\n\n    trained_ = model(0, 0);\n    delta_ = model(1, 0);\n    max_iterations_ = model(2, 0);\n    input_size_ = model(3, 0);\n    gmm_ = std::shared_ptr<GaussianMixtureModel>(new GaussianMixtureModel);\n    gmm_->load(model.block(4, 0, model.rows() - 4, model.cols()));\n}\n\nvoid GMMRegressor::save(const std::string filename) {\n    MatrixIO mio;\n    Eigen::MatrixXd gmm_model = gmm_->save();\n    Eigen::MatrixXd model =\n            Eigen::MatrixXd::Zero(gmm_model.rows() + 4, gmm_model.cols());\n\n    model(0, 0) = trained_;\n    model(1, 0) = delta_;\n    model(2, 0) = max_iterations_;\n    model(3, 0) = input_size_;\n    model.block(4, 0, gmm_model.rows(), gmm_model.cols()) = gmm_model;\n    mio.writeToFile(filename, model);\n}\n}  // namespace gmms\n", "meta": {"hexsha": "db5d1795445d612e4d0a0e0a2cee1f44935b2aa3", "size": 6359, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/particle_filter/src/gmm_regressor.cpp", "max_stars_repo_name": "MosHumanoid/bitbots_thmos_meta", "max_stars_repo_head_hexsha": "f45ccc362dc689b69027be5b0d000d2a08580de4", "max_stars_repo_licenses": ["MIT"], "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/particle_filter/src/gmm_regressor.cpp", "max_issues_repo_name": "MosHumanoid/bitbots_thmos_meta", "max_issues_repo_head_hexsha": "f45ccc362dc689b69027be5b0d000d2a08580de4", "max_issues_repo_licenses": ["MIT"], "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/particle_filter/src/gmm_regressor.cpp", "max_forks_repo_name": "MosHumanoid/bitbots_thmos_meta", "max_forks_repo_head_hexsha": "f45ccc362dc689b69027be5b0d000d2a08580de4", "max_forks_repo_licenses": ["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.7783505155, "max_line_length": 80, "alphanum_fraction": 0.5788646014, "num_tokens": 1459, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.835483553488848, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.456790734048031}}
{"text": "/*\n * Created by: Joshua Latham. All of this work is my own.\n\n        ######## N0641701's Route::netLength() Test File ########\n\nnetLength calculates the distance between the first and last points on the Route.\n\nAll log files used will be generated with the program that I built to generate log files unless stated otherwise.\n\n\n\nAll tests catagorised, and they are as follows:\n\n\n\n### These are normal tests to check that the function is giving the correct output.\n\nTest: CorrectOutput\nDecscription:\nThis test will test the function for the correct\noutput given a number of points which have a known\ndistance between the first and last point.\n\nTest: OnePoint\nDescription: This test will test the function on\nhow it handles a route with only one point. The expected\noutput should be 0, as there is no distance to measure.\n\nTest: TwoPoints\nDescription: This test will test the function on\nhow it handles a route with just two points with\na distance. The expected output should be the distance\nbetween the two points.\n\nTest: BackToStart\nDescription: This test will test the function against\na route that loops back to its starting point. Therefore\nthe 0 is the expected output.\n\nTest: TwoIdenticalPoints\nDescription: Two points with the same location. This test\nshould give a distance of 0.\n\nTest: UpAndDown\nDescription: This test will present points that do not move\nlatitudinally or longitudinally but in elevation. The\ndistance expected is 0. I have manually created the log file for this.\n\n\n\n### These tests are designed to catch any errors when it comes to handling positive and negative numbers.\n\nTest: PosLatLong\nDescription: Testing the function against positive\nlatitudinal and positive longitudinal points which\nshouldn't affect the output.\n\nTest: PosLatNegLong\nDescription: Testing the function against positive\nlatitudinal data and negative longitudinal data.\n\nTest: NegLatNegLong\nDecscription: Testing the function against negative\nlongitudinal data and negative longitudinal data.\n\nTest: NegLatPosLong\nDescription: Testing the function against negative\nlongitudinal data and positive longitudinal data.\n\n\n\n### Edge cases\n\nTest: BigNumbers\nDescription: Testing the function on how well it can handle large numbers.\nI've manually created these log files with very large numbers to see how well\nthey'll be handled.\n\nTest: SmallNumbers\nDescription Testing against very small numbers to see if the function\ncan handle them.\n\nTest: BigData\nDescription: Testing the function against a large number of points to see if it will handle it.\n\n*/\n\n#include <boost/test/unit_test.hpp>\n\n#include \"logs.h\"\n#include \"route.h\"\n#include \"track.h\"\n\nusing namespace GPS;\n\nBOOST_AUTO_TEST_SUITE( NetLength )\n\nconst bool isFileName = true;\n\n//Correct output test. The usual data to expect.\nBOOST_AUTO_TEST_CASE(CorrectOutput)\n{\n    Route route = Route(LogFiles::GPXRoutesDir + \"CorrectOutput_N0641701_MHCBA.gpx\", isFileName);\n    BOOST_CHECK_CLOSE(route.netLength(), 2827.47, 0.01);\n}\n//One point. Testing just one point on its own.\nBOOST_AUTO_TEST_CASE(OnePoint)\n{\n    Route route = Route(LogFiles::GPXRoutesDir + \"OnePoint_N0641701_M.gpx\", isFileName);\n    BOOST_CHECK_EQUAL(route.netLength(), 0);\n}\n//Two Points. Testing two points with different locations.\nBOOST_AUTO_TEST_CASE(TwoPoints)\n{\n    Route route = Route(LogFiles::GPXRoutesDir + \"TwoPoints_N0641701_MN.gpx\", isFileName);\n    BOOST_CHECK_CLOSE(route.netLength(), 999.111, 0.01);\n}\n//A route that circles back to the beginning resulting in a net length of 0.\nBOOST_AUTO_TEST_CASE(BackToStart)\n{\n    Route route = Route(LogFiles::GPXRoutesDir + \"BackToStart_N0641701_MHINSRM.gpx\", isFileName);\n    BOOST_CHECK_EQUAL(route.netLength(), 0);\n}\n//Testing two identical points which should give the expected result of 0.\nBOOST_AUTO_TEST_CASE(TwoIdenticalPoints)\n{\n    Route route = Route(LogFiles::GPXRoutesDir + \"TwoIdenticalPoints_N0641701_MM.gpx\", isFileName);\n    BOOST_CHECK_EQUAL(route.netLength(), 0);\n}\n//Testing a route that doesn't move anywhere but by elevation.\nBOOST_AUTO_TEST_CASE(UpAndDown)\n{\n    Route route = Route(LogFiles::GPXRoutesDir + \"UpAndDown_N0641701_MMMMM.gpx\", isFileName);\n    BOOST_CHECK_EQUAL(route.netLength(), 0);\n}\n\n//Positive and Negative test to make sure the function can handle them correctly.\n\n//Testing a positive latitude and longitude.\n\nBOOST_AUTO_TEST_CASE(PosLatLong)\n{\n    Route route = Route(LogFiles::GPXRoutesDir + \"PosLatLong_N0641701_MIE.gpx\", isFileName);\n    BOOST_CHECK_CLOSE(route.netLength(), 28276.2, 0.01);\n}\n\n//Testing Positive latitude but negative longitude\nBOOST_AUTO_TEST_CASE(PosLatNegLong)\n{\n    Route route = Route(LogFiles::GPXRoutesDir + \"PosLatNegLong_N0641701_MGA.gpx\", isFileName);\n    BOOST_CHECK_CLOSE(route.netLength(), 28276.2, 0.01);\n}\n\n//Testing netagive latitude and negative longitude.\nBOOST_AUTO_TEST_CASE(NegLatNegLong)\n{\n    Route route = Route(LogFiles::GPXRoutesDir + \"NegLatNegLong_N0641701_MQU.gpx\", isFileName);\n    BOOST_CHECK_CLOSE(route.netLength(), 28276.2, 0.01);\n}\n\n//Testing negative latitude and positive longitude\nBOOST_AUTO_TEST_CASE(NegLatPosLong)\n{\n    Route route = Route(LogFiles::GPXRoutesDir + \"NegLatPosLong_N0641701_MSY.gpx\", isFileName);\n    BOOST_CHECK_CLOSE(route.netLength(), 28276.2, 0.01);\n}\n\n//Testing whether or not the function can handle large numbers.\nBOOST_AUTO_TEST_CASE(BigNumbers)\n{\n    Route route = Route(LogFiles::GPXRoutesDir + \"BigNumbers_N0641701_MHCDE.gpx\", isFileName);\n    BOOST_CHECK_CLOSE(route.netLength(), 18398222.331737, 0.01);\n}\n\n//Testing whether or not the function can handle very small numbers.\nBOOST_AUTO_TEST_CASE(SmallNumbers)\n{\n    Route route = Route(LogFiles::GPXRoutesDir + \"SmallNumbers_N0641701_MHCDE.gpx\", isFileName);\n    BOOST_CHECK_CLOSE(route.netLength(), 222390.160475, 0.01);\n}\n\n//Testing whether or not the function can handle extremely large data sets.\nBOOST_AUTO_TEST_CASE(BigData)\n{\n    Route route = Route(LogFiles::GPXRoutesDir + \"BigData_N0641701_MHCBA.gpx\", isFileName);\n    BOOST_CHECK_CLOSE(route.netLength(), 2827.47, 0.01);\n}\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "90378ea01f6da849395c0bb4adb3d0a8283b399c", "size": 6065, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/gpx-tests/netLength_n0641701.cpp", "max_stars_repo_name": "EdwinLangley/GPX-Route-and-Track", "max_stars_repo_head_hexsha": "e4de303c62c7e9dc92724e8f257f7960ff77c992", "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/gpx-tests/netLength_n0641701.cpp", "max_issues_repo_name": "EdwinLangley/GPX-Route-and-Track", "max_issues_repo_head_hexsha": "e4de303c62c7e9dc92724e8f257f7960ff77c992", "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/gpx-tests/netLength_n0641701.cpp", "max_forks_repo_name": "EdwinLangley/GPX-Route-and-Track", "max_forks_repo_head_hexsha": "e4de303c62c7e9dc92724e8f257f7960ff77c992", "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": 32.0899470899, "max_line_length": 113, "alphanum_fraction": 0.7788953009, "num_tokens": 1491, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6442251201477016, "lm_q2_score": 0.7090191460821871, "lm_q1q2_score": 0.4567679445718178}}
{"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_MIN_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_MIN_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-arithmetic\n    Function object implementing min capabilities\n\n    Computes the smallest of its parameter.\n\n    @par semantic:\n    For any given value @c x and @c y of type @c T:\n\n    @code\n    T r = min(x, y);\n    @endcode\n\n    is similar to:\n\n    @code\n    T r = (x < y) ? x : y;\n    @endcode\n\n    @par Note:\n\n    With this definition min(x, @ref Nan) should return x...\n\n    On some systems (namely for example vmx in simd mode) the intrinsic used returns Nan as soon x or y is a nan.\n    So the real definition of our min function must add: but if y is Nan the result is system dependent.\n\n    This can be corrected using the pedantic_ decorator that ensures the standard behaviour at a cost.\n\n    @see minnum, minnummag, minmag\n\n  **/\n  Value min(Value const & v0, Value const& y);\n} }\n#endif\n\n#include <boost/simd/function/scalar/min.hpp>\n#include <boost/simd/function/simd/min.hpp>\n\n#endif\n", "meta": {"hexsha": "44395d92627b42b55253099d57954b3dbf6d665f", "size": 1466, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/min.hpp", "max_stars_repo_name": "nickporubsky/boost-simd-clone", "max_stars_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_stars_repo_licenses": ["BSL-1.0"], "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": "include/boost/simd/function/min.hpp", "max_issues_repo_name": "nickporubsky/boost-simd-clone", "max_issues_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/function/min.hpp", "max_forks_repo_name": "nickporubsky/boost-simd-clone", "max_forks_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_forks_repo_licenses": ["BSL-1.0"], "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": 25.275862069, "max_line_length": 113, "alphanum_fraction": 0.6016371078, "num_tokens": 330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191460821871, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.45676793488567186}}
{"text": "//=======================================================================\n// Copyright 1997, 1998, 1999, 2000 University of Notre Dame.\n// Authors: Andrew Lumsdaine, Lie-Quan Lee, Jeremy G. Siek\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n\n#include <boost/config.hpp>\n\n#include <algorithm>\n#include <vector>\n#include <utility>\n#include <iostream>\n\n#include <boost/graph/graph_utility.hpp>\n#include <boost/graph/visitors.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/neighbor_bfs.hpp>\n#include <boost/property_map/property_map.hpp>\n\n/*\n  \n  This examples shows how to use the breadth_first_search() GGCL\n  algorithm, specifically the 3 argument variant of bfs that assumes\n  the graph has a color property (property) stored internally.\n\n  Two pre-defined visitors are used to record the distance of each\n  vertex from the source vertex, and also to record the parent of each\n  vertex. Any number of visitors can be layered and passed to a GGCL\n  algorithm.\n\n  The call to vertices(G) returns an STL-compatible container which\n  contains all of the vertices in the graph.  In this example we use\n  the vertices container in the STL for_each() function.\n\n  Sample Output:\n\n  0 --> 2 \n  1 --> 1 3 4 \n  2 --> 1 3 4 \n  3 --> 1 4 \n  4 --> 0 1 \n  distances: 1 2 1 2 0 \n  parent[0] = 4\n  parent[1] = 2\n  parent[2] = 0\n  parent[3] = 2\n  parent[4] = 0\n\n*/\n\ntemplate <class ParentDecorator>\nstruct print_parent {\n  print_parent(const ParentDecorator& p_) : p(p_) { }\n  template <class Vertex>\n  void operator()(const Vertex& v) const {\n    std::cout << \"parent[\" << v << \"] = \" <<  p[v]  << std::endl;\n  }\n  ParentDecorator p;\n};\n\n\ntemplate <class NewGraph, class Tag>\nstruct graph_copier \n  : public boost::base_visitor<graph_copier<NewGraph, Tag> >\n{\n  typedef Tag event_filter;\n\n  graph_copier(NewGraph& graph) : new_g(graph) { }\n\n  template <class Edge, class Graph>\n  void operator()(Edge e, Graph& g) {\n    boost::add_edge(boost::source(e, g), boost::target(e, g), new_g);\n  }\nprivate:\n  NewGraph& new_g;\n};\n\ntemplate <class NewGraph, class Tag>\ninline graph_copier<NewGraph, Tag>\ncopy_graph(NewGraph& g, Tag) {\n  return graph_copier<NewGraph, Tag>(g);\n}\n\nint main(int , char* []) \n{\n  typedef boost::adjacency_list< \n    boost::mapS, boost::vecS, boost::bidirectionalS,\n    boost::property<boost::vertex_color_t, boost::default_color_type,\n        boost::property<boost::vertex_degree_t, int,\n          boost::property<boost::vertex_in_degree_t, int,\n    boost::property<boost::vertex_out_degree_t, int> > > >\n  > Graph;\n  \n  Graph G(5);\n  boost::add_edge(0, 2, G);\n  boost::add_edge(1, 1, G);\n  boost::add_edge(1, 3, G);\n  boost::add_edge(1, 4, G);\n  boost::add_edge(2, 1, G);\n  boost::add_edge(2, 3, G);\n  boost::add_edge(2, 4, G);\n  boost::add_edge(3, 1, G);\n  boost::add_edge(3, 4, G);\n  boost::add_edge(4, 0, G);\n  boost::add_edge(4, 1, G);\n\n  typedef Graph::vertex_descriptor Vertex;\n\n  // Array to store predecessor (parent) of each vertex. This will be\n  // used as a Decorator (actually, its iterator will be).\n  std::vector<Vertex> p(boost::num_vertices(G));\n  // VC++ version of std::vector has no ::pointer, so\n  // I use ::value_type* instead.\n  typedef std::vector<Vertex>::value_type* Piter;\n\n  // Array to store distances from the source to each vertex .  We use\n  // a built-in array here just for variety. This will also be used as\n  // a Decorator.  \n  boost::graph_traits<Graph>::vertices_size_type d[5];\n  std::fill_n(d, 5, 0);\n\n  // The source vertex\n  Vertex s = *(boost::vertices(G).first);\n  p[s] = s;\n  boost::neighbor_breadth_first_search\n    (G, s, \n     boost::visitor(boost::make_neighbor_bfs_visitor\n     (std::make_pair(boost::record_distances(d, boost::on_tree_edge()),\n                     boost::record_predecessors(&p[0], \n                                                 boost::on_tree_edge())))));\n\n  boost::print_graph(G);\n\n  if (boost::num_vertices(G) < 11) {\n    std::cout << \"distances: \";\n#ifdef BOOST_OLD_STREAM_ITERATORS\n    std::copy(d, d + 5, std::ostream_iterator<int, char>(std::cout, \" \"));\n#else\n    std::copy(d, d + 5, std::ostream_iterator<int>(std::cout, \" \"));\n#endif\n    std::cout << std::endl;\n\n    std::for_each(boost::vertices(G).first, boost::vertices(G).second, \n                  print_parent<Piter>(&p[0]));\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "050362f60f720f9952cdec1e6def46df14fdb837", "size": 4497, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/graph/example/bfs_neighbor.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "boost/libs/graph/example/bfs_neighbor.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "boost/libs/graph/example/bfs_neighbor.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 29.5855263158, "max_line_length": 76, "alphanum_fraction": 0.6430953969, "num_tokens": 1282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.709019146082187, "lm_q1q2_score": 0.4567679348856718}}
{"text": "#include \"Common/Common.h\"\n#include \"Demos/Visualization/MiniGL.h\"\n#include \"Demos/Visualization/Selection.h\"\n#include \"Simulation/TimeManager.h\"\n#include <Eigen/Dense>\n#include \"Simulation/SimulationModel.h\"\n#include \"Simulation/TimeStepController.h\"\n#include <iostream>\n#include \"Demos/Visualization/Visualization.h\"\n#include \"Utils/Logger.h\"\n#include \"Utils/Timing.h\"\n#include \"Utils/FileSystem.h\"\n#include \"Demos/Common/DemoBase.h\"\n#include \"Demos/Common/TweakBarParameters.h\"\n#include \"Simulation/Simulation.h\"\n\n// Enable memory leak detection\n#if defined(_DEBUG) && !defined(EIGEN_ALIGN)\n\t#define new DEBUG_NEW \n#endif\n\nusing namespace PBD;\nusing namespace Eigen;\nusing namespace std;\nusing namespace Utilities;\n\nvoid timeStep ();\nvoid buildModel ();\nvoid createMesh();\nvoid render ();\nvoid reset();\nvoid TW_CALL setBendingMethod(const void *value, void *clientData);\nvoid TW_CALL getBendingMethod(void *value, void *clientData);\nvoid TW_CALL setSimulationMethod(const void *value, void *clientData);\nvoid TW_CALL getSimulationMethod(void *value, void *clientData);\nvoid TW_CALL setBendingStiffness(const void* value, void* clientData);\nvoid TW_CALL getBendingStiffness(void* value, void* clientData);\nvoid TW_CALL setDistanceStiffness(const void* value, void* clientData);\nvoid TW_CALL getDistanceStiffness(void* value, void* clientData);\nvoid TW_CALL setXXStiffness(const void* value, void* clientData);\nvoid TW_CALL getXXStiffness(void* value, void* clientData);\nvoid TW_CALL setYYStiffness(const void* value, void* clientData);\nvoid TW_CALL getYYStiffness(void* value, void* clientData);\nvoid TW_CALL setXYStiffness(const void* value, void* clientData);\nvoid TW_CALL getXYStiffness(void* value, void* clientData);\nvoid TW_CALL setXYPoissonRatio(const void* value, void* clientData);\nvoid TW_CALL getXYPoissonRatio(void* value, void* clientData);\nvoid TW_CALL setYXPoissonRatio(const void* value, void* clientData);\nvoid TW_CALL getYXPoissonRatio(void* value, void* clientData);\nvoid TW_CALL setNormalizeStretch(const void* value, void* clientData);\nvoid TW_CALL getNormalizeStretch(void* value, void* clientData);\nvoid TW_CALL setNormalizeShear(const void* value, void* clientData);\nvoid TW_CALL getNormalizeShear(void* value, void* clientData);\n\n\nconst int nRows = 50;\nconst int nCols = 50;\nconst Real width = 10.0;\nconst Real height = 10.0;\nshort simulationMethod = 2;\nshort bendingMethod = 2;\nReal distanceStiffness = 1.0;\nReal xxStiffness = 1.0;\nReal yyStiffness = 1.0;\nReal xyStiffness = 1.0;\nReal xyPoissonRatio = 0.3;\nReal yxPoissonRatio = 0.3;\nbool normalizeStretch = false;\nbool normalizeShear = false;\nReal bendingStiffness = 0.01;\nDemoBase *base;\n\n// main \nint main( int argc, char **argv )\n{\n\tREPORT_MEMORY_LEAKS\n\n\tbase = new DemoBase();\n\tbase->init(argc, argv, \"Cloth demo\");\n\n\tSimulationModel *model = new SimulationModel();\n\tmodel->init();\n\tSimulation::getCurrent()->setModel(model);\n\n\tbuildModel();\n\n\tbase->createParameterGUI();\n\n\t// OpenGL\n\tMiniGL::setClientIdleFunc (timeStep);\t\t\n\tMiniGL::addKeyFunc('r', reset);\n\tMiniGL::setClientSceneFunc(render);\t\t\t\n\tMiniGL::setViewport (40.0f, 0.1f, 500.0f, Vector3r (5.0, 10.0, 30.0), Vector3r (5.0, 0.0, 0.0));\n\n\tTwType enumType2 = TwDefineEnum(\"SimulationMethodType\", NULL, 0);\n\tTwAddVarCB(MiniGL::getTweakBar(), \"SimulationMethod\", enumType2, setSimulationMethod, getSimulationMethod, &simulationMethod, \n\t\t\" label='Simulation method' enum='0 {None}, 1 {Distance constraints}, 2 {FEM based PBD}, 3 {Strain based dynamics}, 4 {XPBD distance constraints}' group=Simulation\");\n\tTwType enumType3 = TwDefineEnum(\"BendingMethodType\", NULL, 0);\n\tTwAddVarCB(MiniGL::getTweakBar(), \"BendingMethod\", enumType3, setBendingMethod, getBendingMethod, &bendingMethod, \n\t\t\" label='Bending method' enum='0 {None}, 1 {Dihedral angle}, 2 {Isometric bending}, 3 {XPBD isometric bending}' group=Bending\");\n\tTwAddVarCB(MiniGL::getTweakBar(), \"BendingStiffness\", TW_TYPE_REAL, setBendingStiffness, getBendingStiffness, model, \" label='Bending stiffness'  min=0.0 step=0.1 precision=4 group='Bending' \");\n\tTwAddVarCB(MiniGL::getTweakBar(), \"DistanceStiffness\", TW_TYPE_REAL, setDistanceStiffness, getDistanceStiffness, model, \" label='Distance constraint stiffness'  min=0.0 step=0.1 precision=4 group='Cloth' \");\n\tTwAddVarCB(MiniGL::getTweakBar(), \"xxStiffness\", TW_TYPE_REAL, setXXStiffness, getXXStiffness, model, \" label='xx stiffness'  min=0.0 step=0.1 precision=4 group='Cloth' \");\n\tTwAddVarCB(MiniGL::getTweakBar(), \"yyStiffness\", TW_TYPE_REAL, setYYStiffness, getYYStiffness, model, \" label='yy stiffness'  min=0.0 step=0.1 precision=4 group='Cloth' \");\n\tTwAddVarCB(MiniGL::getTweakBar(), \"xyStiffness\", TW_TYPE_REAL, setXYStiffness, getXYStiffness, model, \" label='xy stiffness'  min=0.0 step=0.1 precision=4 group='Cloth' \");\n\tTwAddVarCB(MiniGL::getTweakBar(), \"xyPoissonRatio\", TW_TYPE_REAL, setXYPoissonRatio, getXYPoissonRatio, model, \" label='xy Poisson ratio'  min=0.0 step=0.1 precision=4 group='Cloth' \");\n\tTwAddVarCB(MiniGL::getTweakBar(), \"yxPoissonRatio\", TW_TYPE_REAL, setYXPoissonRatio, getYXPoissonRatio, model, \" label='yx Poisson ratio'  min=0.0 step=0.1 precision=4 group='Cloth' \");\n\tTwAddVarCB(MiniGL::getTweakBar(), \"normalizeStretch\", TW_TYPE_BOOL32, setNormalizeStretch, getNormalizeStretch, model, \" label='Normalize stretch' group='Cloth' \");\n\tTwAddVarCB(MiniGL::getTweakBar(), \"normalizeShear\", TW_TYPE_BOOL32, setNormalizeShear, getNormalizeShear, model, \" label='Normalize shear' group='Cloth' \");\n\n\tMiniGL::mainLoop();\t\n\n\tbase->cleanup();\n\n\tUtilities::Timing::printAverageTimes();\n\tUtilities::Timing::printTimeSums();\n\n\tdelete Simulation::getCurrent();\n\tdelete base;\n\tdelete model;\n\n\treturn 0;\n}\n\nvoid reset()\n{\n\tUtilities::Timing::printAverageTimes();\n\tUtilities::Timing::reset();\n\n\tSimulation::getCurrent()->reset();\n\tbase->getSelectedParticles().clear();\n\n\tSimulation::getCurrent()->getModel()->cleanup();\n\n\tbuildModel();\n}\n\n\nvoid timeStep ()\n{\n\tconst Real pauseAt = base->getValue<Real>(DemoBase::PAUSE_AT);\n\tif ((pauseAt > 0.0) && (pauseAt < TimeManager::getCurrent()->getTime()))\n\t\tbase->setValue(DemoBase::PAUSE, true);\n\n\tif (base->getValue<bool>(DemoBase::PAUSE))\n\t\treturn;\n\n\t// Simulation code\n\tSimulationModel *model = Simulation::getCurrent()->getModel();\n\tconst unsigned int numSteps = base->getValue<unsigned int>(DemoBase::NUM_STEPS_PER_RENDER);\n\tfor (unsigned int i = 0; i < numSteps; i++)\n\t{\n\t\tSTART_TIMING(\"SimStep\");\n\t\tSimulation::getCurrent()->getTimeStep()->step(*model);\n\t\tSTOP_TIMING_AVG;\n\t}\n\n\tfor (unsigned int i = 0; i < model->getTriangleModels().size(); i++)\n\t\tmodel->getTriangleModels()[i]->updateMeshNormals(model->getParticles());\n}\n\nvoid buildModel ()\n{\n\tTimeManager::getCurrent ()->setTimeStepSize (static_cast<Real>(0.005));\n\n\tcreateMesh();\n}\n\nvoid render ()\n{\n\tbase->render();\n}\n\n\n/** Create a particle model mesh \n*/\nvoid createMesh()\n{\n\tSimulationModel *model = Simulation::getCurrent()->getModel();\n\tmodel->addRegularTriangleModel(nCols, nRows,  \n\t\tVector3r(0,1,0), AngleAxisr(M_PI*0.5, Vector3r(1,0,0)).matrix(), Vector2r(width, height));\n\t\n\t// Set mass of points to zero => make it static\n\tParticleData& pd = model->getParticles();\n\tpd.setMass(0, 0.0);\n\tpd.setMass(nRows-1, 0.0);\n\n\t// init constraints\n\tfor (unsigned int cm = 0; cm < model->getTriangleModels().size(); cm++)\n\t{\n\t\tdistanceStiffness = 1.0;\n\t\tif (simulationMethod == 4)\n\t\t\tdistanceStiffness = 100000;\n\t\tmodel->addClothConstraints(model->getTriangleModels()[cm], simulationMethod, distanceStiffness, xxStiffness, \n\t\t\tyyStiffness, xyStiffness, xyPoissonRatio, yxPoissonRatio, normalizeStretch, normalizeShear);\n\n\t\tbendingStiffness = 0.01;\n\t\tif (bendingMethod == 3)\n\t\t\tbendingStiffness = 100.0;\n\t\tmodel->addBendingConstraints(model->getTriangleModels()[cm], bendingMethod, bendingStiffness);\n\t}\n\n\tLOG_INFO << \"Number of triangles: \" << model->getTriangleModels()[0]->getParticleMesh().numFaces();\n\tLOG_INFO << \"Number of vertices: \" << nRows*nCols;\n\n}\n\nvoid TW_CALL setBendingMethod(const void *value, void *clientData)\n{\n\tconst short val = *(const short *)(value);\n\t*((short*)clientData) = val;\n\treset();\n}\n\nvoid TW_CALL getBendingMethod(void *value, void *clientData)\n{\n\t*(short *)(value) = *((short*)clientData);\n}\n\nvoid TW_CALL setSimulationMethod(const void *value, void *clientData)\n{\n\tconst short val = *(const short *)(value);\n\t*((short*)clientData) = val;\n\treset();\n}\n\nvoid TW_CALL getSimulationMethod(void *value, void *clientData)\n{\n\t*(short *)(value) = *((short*)clientData);\n}\n\nvoid TW_CALL setBendingStiffness(const void* value, void* clientData)\n{\n\tbendingStiffness = *(const Real*)(value);\n\t((SimulationModel*)clientData)->setConstraintValue<DihedralConstraint, Real, &DihedralConstraint::m_stiffness>(bendingStiffness);\n\t((SimulationModel*)clientData)->setConstraintValue<IsometricBendingConstraint, Real, &IsometricBendingConstraint::m_stiffness>(bendingStiffness);\n\t((SimulationModel*)clientData)->setConstraintValue<IsometricBendingConstraint_XPBD, Real, &IsometricBendingConstraint_XPBD::m_stiffness>(bendingStiffness);\n}\n\nvoid TW_CALL getBendingStiffness(void* value, void* clientData)\n{\n\t*(Real*)(value) = bendingStiffness;\n}\n\nvoid TW_CALL setDistanceStiffness(const void* value, void* clientData)\n{\n\tdistanceStiffness = *(const Real*)(value);\n\t((SimulationModel*)clientData)->setConstraintValue<DistanceConstraint, Real, &DistanceConstraint::m_stiffness>(distanceStiffness);\n\t((SimulationModel*)clientData)->setConstraintValue<DistanceConstraint_XPBD, Real, &DistanceConstraint_XPBD::m_stiffness>(distanceStiffness);\n}\n\nvoid TW_CALL getDistanceStiffness(void* value, void* clientData)\n{\n\t*(Real*)(value) = distanceStiffness;\n}\n\nvoid TW_CALL setXXStiffness(const void* value, void* clientData)\n{\n\txxStiffness = *(const Real*)(value);\n\t((SimulationModel*)clientData)->setConstraintValue<FEMTriangleConstraint, Real, &FEMTriangleConstraint::m_xxStiffness>(xxStiffness);\n\t((SimulationModel*)clientData)->setConstraintValue<StrainTriangleConstraint, Real, &StrainTriangleConstraint::m_xxStiffness>(xxStiffness);\n}\n\nvoid TW_CALL getXXStiffness(void* value, void* clientData)\n{\n\t*(Real*)(value) = xxStiffness;\n}\n\nvoid TW_CALL getYYStiffness(void* value, void* clientData)\n{\n\t*(Real*)(value) = yyStiffness;\n}\n\nvoid TW_CALL setYYStiffness(const void* value, void* clientData)\n{\n\tyyStiffness = *(const Real*)(value);\n\t((SimulationModel*)clientData)->setConstraintValue<FEMTriangleConstraint, Real, &FEMTriangleConstraint::m_yyStiffness>(yyStiffness);\n\t((SimulationModel*)clientData)->setConstraintValue<StrainTriangleConstraint, Real, &StrainTriangleConstraint::m_yyStiffness>(yyStiffness);\n}\n\nvoid TW_CALL getXYStiffness(void* value, void* clientData)\n{\n\t*(Real*)(value) = xyStiffness;\n}\n\nvoid TW_CALL setXYStiffness(const void* value, void* clientData)\n{\n\txyStiffness = *(const Real*)(value);\n\t((SimulationModel*)clientData)->setConstraintValue<FEMTriangleConstraint, Real, &FEMTriangleConstraint::m_xyStiffness>(xyStiffness);\n\t((SimulationModel*)clientData)->setConstraintValue<StrainTriangleConstraint, Real, &StrainTriangleConstraint::m_xyStiffness>(xyStiffness);\n}\n\nvoid TW_CALL getXYPoissonRatio(void* value, void* clientData)\n{\n\t*(Real*)(value) = xyPoissonRatio;\n}\n\nvoid TW_CALL setXYPoissonRatio(const void* value, void* clientData)\n{\n\txyPoissonRatio = *(const Real*)(value);\n\t((SimulationModel*)clientData)->setConstraintValue<FEMTriangleConstraint, Real, &FEMTriangleConstraint::m_xyPoissonRatio>(xyPoissonRatio);\n}\n\nvoid TW_CALL getYXPoissonRatio(void* value, void* clientData)\n{\n\t*(Real*)(value) = yxPoissonRatio;\n}\n\nvoid TW_CALL setYXPoissonRatio(const void* value, void* clientData)\n{\n\tyxPoissonRatio = *(const Real*)(value);\n\t((SimulationModel*)clientData)->setConstraintValue<FEMTriangleConstraint, Real, &FEMTriangleConstraint::m_yxPoissonRatio>(yxPoissonRatio);\n}\n\nvoid TW_CALL getNormalizeStretch(void* value, void* clientData)\n{\n\t*(bool*)(value) = normalizeStretch;\n}\n\nvoid TW_CALL setNormalizeStretch(const void* value, void* clientData)\n{\n\tnormalizeStretch = *(const Real*)(value);\n\t((SimulationModel*)clientData)->setConstraintValue<StrainTriangleConstraint, bool, &StrainTriangleConstraint::m_normalizeStretch>(normalizeStretch);\n}\n\nvoid TW_CALL getNormalizeShear(void* value, void* clientData)\n{\n\t*(bool*)(value) = normalizeShear;\n}\n\nvoid TW_CALL setNormalizeShear(const void* value, void* clientData)\n{\n\tnormalizeShear= *(const Real*)(value);\n\t((SimulationModel*)clientData)->setConstraintValue<StrainTriangleConstraint, bool, &StrainTriangleConstraint::m_normalizeShear>(normalizeShear);\n}", "meta": {"hexsha": "0fee82f39a4a158c62fd7693e3b1a4e38e83aab6", "size": 12513, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Demos/ClothDemo/main.cpp", "max_stars_repo_name": "mcx/PositionBasedDynamics", "max_stars_repo_head_hexsha": "136469f03f7869666d907ea8d27872b098715f4a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1169.0, "max_stars_repo_stars_event_min_datetime": "2016-05-31T03:01:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:38:47.000Z", "max_issues_repo_path": "Demos/ClothDemo/main.cpp", "max_issues_repo_name": "Taiyuan-Zhang/PositionBasedDynamics", "max_issues_repo_head_hexsha": "136469f03f7869666d907ea8d27872b098715f4a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 88.0, "max_issues_repo_issues_event_min_datetime": "2016-06-10T19:09:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-08T10:50:41.000Z", "max_forks_repo_path": "Demos/ClothDemo/main.cpp", "max_forks_repo_name": "Taiyuan-Zhang/PositionBasedDynamics", "max_forks_repo_head_hexsha": "136469f03f7869666d907ea8d27872b098715f4a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 267.0, "max_forks_repo_forks_event_min_datetime": "2016-06-22T06:44:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T11:55:24.000Z", "avg_line_length": 37.352238806, "max_line_length": 208, "alphanum_fraction": 0.759290338, "num_tokens": 3561, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251064863698, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.45676792300252694}}
{"text": "/*=============================================================================\nCopyright 2020 Syed Ali Hasan <alihasan9922@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#define BOOST_TEST_MODULE horizon_coord_test\n\n#include <iostream>\n#include <boost/units/io.hpp>\n#include <boost/units/systems/angle/degrees.hpp>\n#include <boost/astronomy/coordinate/coord_sys/horizon_coord.hpp>\n\n#include <boost/test/unit_test.hpp>\n\nusing namespace boost::units;\nusing namespace boost::units::si;\nusing namespace boost::astronomy::coordinate;\n\nnamespace bud = boost::units::degree;\n\nBOOST_AUTO_TEST_SUITE(horizon_coord_constructors)\n\nBOOST_AUTO_TEST_CASE(horizon_coord_default_constructor) {\n    horizon_coord<\n            double,\n            quantity<bud::plane_angle>,\n            quantity<bud::plane_angle>>\n            hc;\n\n    //Check set_altitude_azimuth\n    hc.set_altitude_azimuth(45.0 * bud::degrees, 18.0 * bud::degrees);\n\n    //Check values\n    BOOST_CHECK_CLOSE(hc.get_altitude().value(), 45.0, 0.001);\n    BOOST_CHECK_CLOSE(hc.get_azimuth().value(), 18.0, 0.001);\n\n    //Quantities stored as expected?\n    BOOST_TEST((std::is_same<decltype(hc.get_altitude()), quantity<bud::plane_angle>>::value));\n    BOOST_TEST((std::is_same<decltype(hc.get_azimuth()), quantity<bud::plane_angle>>::value));\n}\n\nBOOST_AUTO_TEST_CASE(horizon_coord_quantities_constructor) {\n    //Make Horizon Coordinate Check\n    auto hc1 = make_horizon_coord\n            (15.0 * bud::degrees, 39.0 * bud::degrees);\n\n    //Check values\n    BOOST_CHECK_CLOSE(hc1.get_altitude().value(), 15.0, 0.001);\n    BOOST_CHECK_CLOSE(hc1.get_azimuth().value(), 39.0, 0.001);\n\n    //Quantities stored as expected?\n    BOOST_TEST((std::is_same<decltype(hc1.get_altitude()), quantity<bud::plane_angle>>::value));\n    BOOST_TEST((std::is_same<decltype(hc1.get_azimuth()), quantity<bud::plane_angle>>::value));\n\n    //Horizon Coord constructor\n    horizon_coord<double, quantity<bud::plane_angle>, quantity<bud::plane_angle>>\n            hc2(1.5 * bud::degrees, 9.0 * bud::degrees);\n\n    //Check values\n    BOOST_CHECK_CLOSE(hc2.get_altitude().value(), 1.5, 0.001);\n    BOOST_CHECK_CLOSE(hc2.get_azimuth().value(), 9.0, 0.001);\n\n    //Quantities stored as expected?\n    BOOST_TEST((std::is_same<decltype(hc2.get_altitude()), quantity<bud::plane_angle>>::value));\n    BOOST_TEST((std::is_same<decltype(hc2.get_azimuth()), quantity<bud::plane_angle>>::value));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "66e623863b8da29371bc824d93219dd836626239", "size": 2630, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/coordinate/horizon_coord.cpp", "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": "test/coordinate/horizon_coord.cpp", "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": "test/coordinate/horizon_coord.cpp", "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": 37.0422535211, "max_line_length": 96, "alphanum_fraction": 0.6726235741, "num_tokens": 658, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.6442250996557036, "lm_q1q2_score": 0.4567679221205023}}
{"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 <dai/index.h>\n#include <strstream>\n#include <map>\n\n\nusing namespace dai;\n\n\n#define BOOST_TEST_MODULE IndexTest\n\n\n#include <boost/test/unit_test.hpp>\n\n\nBOOST_AUTO_TEST_CASE( IndexForTest ) {\n    IndexFor x;\n    BOOST_CHECK( !x.valid() );\n    x.reset();\n    BOOST_CHECK( x.valid() );\n\n    size_t nrVars = 5;\n    std::vector<Var> vars;\n    for( size_t i = 0; i < nrVars; i++ )\n        vars.push_back( Var( i, i+2 ) );\n\n    for( size_t repeat = 0; repeat < 10000; repeat++ ) {\n        VarSet indexVars;\n        VarSet forVars;\n        for( size_t i = 0; i < 5; i++ ) {\n            if( rnd(2) == 0 )\n                indexVars |= vars[i];\n            if( rnd(2) == 0 )\n                forVars |= vars[i];\n        }\n        IndexFor ind( indexVars, forVars );\n        size_t iter = 0;\n        for( ; ind.valid(); ind++, iter++ )\n            BOOST_CHECK_EQUAL( calcLinearState( indexVars, calcState( forVars, iter ) ), (size_t)ind );\n        BOOST_CHECK_EQUAL( iter, forVars.nrStates() );\n        iter = 0;\n        ind.reset();\n        for( ; ind.valid(); ++ind, iter++ )\n            BOOST_CHECK_EQUAL( calcLinearState( indexVars, calcState( forVars, iter ) ), (size_t)ind );\n        BOOST_CHECK_EQUAL( iter, forVars.nrStates() );\n    }\n}\n\n\nBOOST_AUTO_TEST_CASE( PermuteTest ) {\n    Permute x;\n\n    Var x0(0, 2);\n    Var x1(1, 3);\n    Var x2(2, 2);\n    std::vector<Var> V;\n    V.push_back( x1 );\n    V.push_back( x2 );\n    V.push_back( x0 );\n    VarSet X( V.begin(), V.end() );\n    Permute sigma(V);\n    BOOST_CHECK_EQUAL( sigma.sigma().size(), 3 );\n    BOOST_CHECK_EQUAL( sigma.sigma()[0], 2 );\n    BOOST_CHECK_EQUAL( sigma.sigma()[1], 0 );\n    BOOST_CHECK_EQUAL( sigma.sigma()[2], 1 );\n    BOOST_CHECK_EQUAL( sigma[0], 2 );\n    BOOST_CHECK_EQUAL( sigma[1], 0 );\n    BOOST_CHECK_EQUAL( sigma[2], 1 );\n    BOOST_CHECK_EQUAL( sigma.ranges().size(), 3 );\n    BOOST_CHECK_EQUAL( sigma.ranges()[0], 3 );\n    BOOST_CHECK_EQUAL( sigma.ranges()[1], 2 );\n    BOOST_CHECK_EQUAL( sigma.ranges()[2], 2 );\n    BOOST_CHECK_EQUAL( sigma.convertLinearIndex( 0 ), 0 );\n    BOOST_CHECK_EQUAL( sigma.convertLinearIndex( 1 ), 2 );\n    BOOST_CHECK_EQUAL( sigma.convertLinearIndex( 2 ), 4 );\n    BOOST_CHECK_EQUAL( sigma.convertLinearIndex( 3 ), 6 );\n    BOOST_CHECK_EQUAL( sigma.convertLinearIndex( 4 ), 8 );\n    BOOST_CHECK_EQUAL( sigma.convertLinearIndex( 5 ), 10 );\n    BOOST_CHECK_EQUAL( sigma.convertLinearIndex( 6 ), 1 );\n    BOOST_CHECK_EQUAL( sigma.convertLinearIndex( 7 ), 3 );\n    BOOST_CHECK_EQUAL( sigma.convertLinearIndex( 8 ), 5 );\n    BOOST_CHECK_EQUAL( sigma.convertLinearIndex( 9 ), 7 );\n    BOOST_CHECK_EQUAL( sigma.convertLinearIndex( 10 ), 9 );\n    BOOST_CHECK_EQUAL( sigma.convertLinearIndex( 11 ), 11 );\n\n    Permute sigmar(V, true);\n    BOOST_CHECK_EQUAL( sigmar.sigma().size(), 3 );\n    BOOST_CHECK_EQUAL( sigmar.sigma()[0], 0 );\n    BOOST_CHECK_EQUAL( sigmar.sigma()[1], 2 );\n    BOOST_CHECK_EQUAL( sigmar.sigma()[2], 1 );\n    BOOST_CHECK_EQUAL( sigmar[0], 0 );\n    BOOST_CHECK_EQUAL( sigmar[1], 2 );\n    BOOST_CHECK_EQUAL( sigmar[2], 1 );\n    BOOST_CHECK_EQUAL( sigmar.ranges().size(), 3 );\n    BOOST_CHECK_EQUAL( sigmar.ranges()[0], 2 );\n    BOOST_CHECK_EQUAL( sigmar.ranges()[1], 2 );\n    BOOST_CHECK_EQUAL( sigmar.ranges()[2], 3 );\n    BOOST_CHECK_EQUAL( sigmar.convertLinearIndex( 0 ), 0 );\n    BOOST_CHECK_EQUAL( sigmar.convertLinearIndex( 1 ), 1 );\n    BOOST_CHECK_EQUAL( sigmar.convertLinearIndex( 2 ), 6 );\n    BOOST_CHECK_EQUAL( sigmar.convertLinearIndex( 3 ), 7 );\n    BOOST_CHECK_EQUAL( sigmar.convertLinearIndex( 4 ), 2 );\n    BOOST_CHECK_EQUAL( sigmar.convertLinearIndex( 5 ), 3 );\n    BOOST_CHECK_EQUAL( sigmar.convertLinearIndex( 6 ), 8 );\n    BOOST_CHECK_EQUAL( sigmar.convertLinearIndex( 7 ), 9 );\n    BOOST_CHECK_EQUAL( sigmar.convertLinearIndex( 8 ), 4 );\n    BOOST_CHECK_EQUAL( sigmar.convertLinearIndex( 9 ), 5 );\n    BOOST_CHECK_EQUAL( sigmar.convertLinearIndex( 10 ), 10 );\n    BOOST_CHECK_EQUAL( sigmar.convertLinearIndex( 11 ), 11 );\n\n    std::vector<size_t> rs, sig;\n    rs.push_back(3);\n    rs.push_back(2);\n    rs.push_back(2);\n    sig.push_back(2);\n    sig.push_back(0);\n    sig.push_back(1);\n    Permute tau( rs, sig );\n    BOOST_CHECK( tau.sigma() == sig );\n    BOOST_CHECK( tau.ranges() == rs );\n    BOOST_CHECK_EQUAL( tau[0], 2 );\n    BOOST_CHECK_EQUAL( tau[1], 0 );\n    BOOST_CHECK_EQUAL( tau[2], 1 );\n    BOOST_CHECK_EQUAL( tau.convertLinearIndex( 0 ), 0 );\n    BOOST_CHECK_EQUAL( tau.convertLinearIndex( 1 ), 2 );\n    BOOST_CHECK_EQUAL( tau.convertLinearIndex( 2 ), 4 );\n    BOOST_CHECK_EQUAL( tau.convertLinearIndex( 3 ), 6 );\n    BOOST_CHECK_EQUAL( tau.convertLinearIndex( 4 ), 8 );\n    BOOST_CHECK_EQUAL( tau.convertLinearIndex( 5 ), 10 );\n    BOOST_CHECK_EQUAL( tau.convertLinearIndex( 6 ), 1 );\n    BOOST_CHECK_EQUAL( tau.convertLinearIndex( 7 ), 3 );\n    BOOST_CHECK_EQUAL( tau.convertLinearIndex( 8 ), 5 );\n    BOOST_CHECK_EQUAL( tau.convertLinearIndex( 9 ), 7 );\n    BOOST_CHECK_EQUAL( tau.convertLinearIndex( 10 ), 9 );\n    BOOST_CHECK_EQUAL( tau.convertLinearIndex( 11 ), 11 );\n\n    Permute tauinv = tau.inverse();\n    BOOST_CHECK_EQUAL( tauinv.sigma().size(), 3 );\n    BOOST_CHECK_EQUAL( tauinv.ranges().size(), 3 );\n    BOOST_CHECK_EQUAL( tauinv[0], 1 );\n    BOOST_CHECK_EQUAL( tauinv[1], 2 );\n    BOOST_CHECK_EQUAL( tauinv[2], 0 );\n    BOOST_CHECK_EQUAL( tauinv.ranges()[0], 2 );\n    BOOST_CHECK_EQUAL( tauinv.ranges()[1], 3 );\n    BOOST_CHECK_EQUAL( tauinv.ranges()[2], 2 );\n    for( size_t i = 0; i < 12; i++ ) {\n        BOOST_CHECK_EQUAL( tau.convertLinearIndex( tauinv.convertLinearIndex( i ) ), i );\n        BOOST_CHECK_EQUAL( tauinv.convertLinearIndex( tau.convertLinearIndex( i ) ), i );\n    }\n}\n\n\nBOOST_AUTO_TEST_CASE( multiforTest ) {\n    multifor x;\n    BOOST_CHECK( x.valid() );\n\n    std::vector<size_t> ranges;\n    ranges.push_back( 3 );\n    ranges.push_back( 4 );\n    ranges.push_back( 5 );\n    multifor S(ranges);\n    size_t s = 0;\n    for( size_t s2 = 0; s2 < 5; s2++ )\n        for( size_t s1 = 0; s1 < 4; s1++ )\n            for( size_t s0 = 0; s0 < 3; s0++, s++, S++ ) {\n                BOOST_CHECK( S.valid() );\n                BOOST_CHECK_EQUAL( s, (size_t)S );\n                BOOST_CHECK_EQUAL( S[0], s0 );\n                BOOST_CHECK_EQUAL( S[1], s1 );\n                BOOST_CHECK_EQUAL( S[2], s2 );\n            }\n    BOOST_CHECK( !S.valid() );\n\n    for( size_t repeat = 0; repeat < 10000; repeat++ ) {\n        std::vector<size_t> dims;\n        size_t total = 1;\n        for( size_t i = 0; i < 4; i++ ) {\n            dims.push_back( rnd(3) + 1 );\n            total *= dims.back();\n        }\n        multifor ind( dims );\n        size_t iter = 0;\n        for( ; ind.valid(); ind++, iter++ ) {\n            BOOST_CHECK_EQUAL( (size_t)ind, iter );\n            BOOST_CHECK_EQUAL( ind[0], iter % dims[0] );\n            BOOST_CHECK_EQUAL( ind[1], (iter / dims[0]) % dims[1] );\n            BOOST_CHECK_EQUAL( ind[2], (iter / (dims[0] * dims[1])) % dims[2] );\n            BOOST_CHECK_EQUAL( ind[3], (iter / (dims[0] * dims[1] * dims[2])) % dims[3] );\n        }\n        BOOST_CHECK_EQUAL( iter, total );\n        iter = 0;\n        ind.reset();\n        for( ; ind.valid(); ++ind, iter++ ) {\n            BOOST_CHECK_EQUAL( (size_t)ind, iter );\n            BOOST_CHECK_EQUAL( ind[0], iter % dims[0] );\n            BOOST_CHECK_EQUAL( ind[1], (iter / dims[0]) % dims[1] );\n            BOOST_CHECK_EQUAL( ind[2], (iter / (dims[0] * dims[1])) % dims[2] );\n            BOOST_CHECK_EQUAL( ind[3], (iter / (dims[0] * dims[1] * dims[2])) % dims[3] );\n        }\n        BOOST_CHECK_EQUAL( iter, total );\n    }\n}\n\n\nBOOST_AUTO_TEST_CASE( StateTest ) {\n    State x;\n    BOOST_CHECK( x.valid() );\n\n    Var v0( 0, 3 );\n    Var v1( 1, 4 );\n    Var v2( 3, 5 );\n    VarSet vars;\n    vars |= v2;\n    vars |= v1;\n    vars |= v0;\n    State S( vars );\n    size_t s = 0;\n    for( size_t s2 = 0; s2 < 5; s2++ )\n        for( size_t s1 = 0; s1 < 4; s1++ )\n            for( size_t s0 = 0; s0 < 3; s0++, s++, S++ ) {\n                BOOST_CHECK( S.valid() );\n                BOOST_CHECK_EQUAL( s, (size_t)S );\n                BOOST_CHECK_EQUAL( S(v0), s0 );\n                BOOST_CHECK_EQUAL( S(v1), s1 );\n                BOOST_CHECK_EQUAL( S(v2), s2 );\n                BOOST_CHECK_EQUAL( S( Var( 2, 2 ) ), 0 );\n            }\n    BOOST_CHECK( !S.valid() );\n    S.reset();\n    std::vector<std::pair<Var, size_t> > ps;\n    ps.push_back( std::make_pair( Var( 2, 2 ), 1 ) );\n    ps.push_back( std::make_pair( Var( 4, 2 ), 1 ) );\n    S.insert( ps.begin(), ps.end() );\n    BOOST_CHECK( S.valid() );\n    BOOST_CHECK_EQUAL( (size_t)S, 132 );\n\n    for( size_t repeat = 0; repeat < 10000; repeat++ ) {\n        std::vector<size_t> dims;\n        size_t total = 1;\n        for( size_t i = 0; i < 4; i++ ) {\n            dims.push_back( rnd(3) + 1 );\n            total *= dims.back();\n        }\n        std::vector<Var> vs;\n        for( size_t i = 0; i < 4; i++ )\n            vs.push_back( Var( i, dims[i] ) );\n        State ind( VarSet( vs.begin(), vs.end() ) );\n        size_t iter = 0;\n        for( ; ind.valid(); ind++, iter++ ) {\n            BOOST_CHECK_EQUAL( (size_t)ind, iter );\n            BOOST_CHECK_EQUAL( ind(vs[0]), iter % dims[0] );\n            BOOST_CHECK_EQUAL( ind(vs[1]), (iter / dims[0]) % dims[1] );\n            BOOST_CHECK_EQUAL( ind(vs[2]), (iter / (dims[0] * dims[1])) % dims[2] );\n            BOOST_CHECK_EQUAL( ind(vs[3]), (iter / (dims[0] * dims[1] * dims[2])) % dims[3] );\n            BOOST_CHECK_EQUAL( ind(VarSet(vs[0], vs[1])), iter % (dims[0] * dims[1]) );\n            BOOST_CHECK_EQUAL( ind(VarSet(vs[1], vs[2])), (iter / dims[0]) % (dims[1] * dims[2]) );\n            BOOST_CHECK_EQUAL( ind(VarSet(vs[2], vs[3])), (iter / (dims[0] * dims[1])) % (dims[2] * dims[3]) );\n            BOOST_CHECK_EQUAL( ind(VarSet(vs.begin(), vs.end())), iter );\n            State indcopy( VarSet(vs.begin(), vs.end()), (size_t)ind );\n            BOOST_CHECK_EQUAL( ind(vs[0]), indcopy(vs[0]) );\n            BOOST_CHECK_EQUAL( ind(vs[1]), indcopy(vs[1]) );\n            BOOST_CHECK_EQUAL( ind(vs[2]), indcopy(vs[2]) );\n            BOOST_CHECK_EQUAL( ind(vs[3]), indcopy(vs[3]) );\n            State indcopy2( indcopy.get() );\n            BOOST_CHECK_EQUAL( ind(vs[0]), indcopy2(vs[0]) );\n            BOOST_CHECK_EQUAL( ind(vs[1]), indcopy2(vs[1]) );\n            BOOST_CHECK_EQUAL( ind(vs[2]), indcopy2(vs[2]) );\n            BOOST_CHECK_EQUAL( ind(vs[3]), indcopy2(vs[3]) );\n            std::map<Var,size_t> indmap( ind );\n            State indcopy3( indmap );\n            BOOST_CHECK_EQUAL( ind(vs[0]), indcopy3(vs[0]) );\n            BOOST_CHECK_EQUAL( ind(vs[1]), indcopy3(vs[1]) );\n            BOOST_CHECK_EQUAL( ind(vs[2]), indcopy3(vs[2]) );\n            BOOST_CHECK_EQUAL( ind(vs[3]), indcopy3(vs[3]) );\n        }\n        BOOST_CHECK_EQUAL( iter, total );\n        iter = 0;\n        ind.reset();\n        for( ; ind.valid(); ++ind, iter++ ) {\n            BOOST_CHECK_EQUAL( (size_t)ind, iter );\n            BOOST_CHECK_EQUAL( ind(vs[0]), iter % dims[0] );\n            BOOST_CHECK_EQUAL( ind(vs[1]), (iter / dims[0]) % dims[1] );\n            BOOST_CHECK_EQUAL( ind(vs[2]), (iter / (dims[0] * dims[1])) % dims[2] );\n            BOOST_CHECK_EQUAL( ind(vs[3]), (iter / (dims[0] * dims[1] * dims[2])) % dims[3] );\n            State::const_iterator ci = ind.begin();\n            BOOST_CHECK_EQUAL( (ci++)->second, iter % dims[0] );\n            BOOST_CHECK_EQUAL( (ci++)->second, (iter / dims[0]) % dims[1] );\n            BOOST_CHECK_EQUAL( (ci++)->second, (iter / (dims[0] * dims[1])) % dims[2] );\n            BOOST_CHECK_EQUAL( (ci++)->second, (iter / (dims[0] * dims[1] * dims[2])) % dims[3] );\n            BOOST_CHECK( ci == ind.end() );\n        }\n        BOOST_CHECK_EQUAL( iter, total );\n        State::const_iterator ci = ind.begin();\n        BOOST_CHECK_EQUAL( (ci++)->first, vs[0] );\n        BOOST_CHECK_EQUAL( (ci++)->first, vs[1] );\n        BOOST_CHECK_EQUAL( (ci++)->first, vs[2] );\n        BOOST_CHECK_EQUAL( (ci++)->first, vs[3] );\n        BOOST_CHECK( ci == ind.end() );\n    }\n}\n", "meta": {"hexsha": "35e8b7a2097d79a6565aad5768cd7a3addf67c40", "size": 12261, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/unit/index_test.cpp", "max_stars_repo_name": "chang-liang/HadoopBNEM", "max_stars_repo_head_hexsha": "dd90a70786271ebf5b0beda2484f8e476ab4a97a", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 48.0, "max_stars_repo_stars_event_min_datetime": "2015-01-19T18:56:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-30T20:30:50.000Z", "max_issues_repo_path": "tests/unit/index_test.cpp", "max_issues_repo_name": "chang-liang/HadoopBNEM", "max_issues_repo_head_hexsha": "dd90a70786271ebf5b0beda2484f8e476ab4a97a", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2016-01-18T08:17:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-28T18:08:38.000Z", "max_forks_repo_path": "tests/unit/index_test.cpp", "max_forks_repo_name": "chang-liang/HadoopBNEM", "max_forks_repo_head_hexsha": "dd90a70786271ebf5b0beda2484f8e476ab4a97a", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 29.0, "max_forks_repo_forks_event_min_datetime": "2015-04-07T07:38:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-01T22:18:58.000Z", "avg_line_length": 39.8084415584, "max_line_length": 111, "alphanum_fraction": 0.5641464807, "num_tokens": 3676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191214879991, "lm_q2_score": 0.6442250996557036, "lm_q1q2_score": 0.4567679141984056}}
{"text": "#ifndef HAMILTONIANS_XYZNNN_HPP\n#define HAMILTONIANS_XYZNNN_HPP\n#include <Eigen/Eigen>\n#include <nlohmann/json.hpp>\n\nclass XYZNNN\n{\nprivate:\n\tint n_;\n\tdouble a_;\n\tdouble b_;\n\tconstexpr static double J1 = -1.0;\n\tconstexpr static double J2 = -1.0;\npublic:\n\n\tXYZNNN(int n, double a, double b)\n\t\t: n_(n), a_(a), b_(b)\n\t{\n\t}\n\n\tnlohmann::json params() const\n\t{\n\t\treturn nlohmann::json\n\t\t{\n\t\t\t{\"name\", \"XYZNNN\"},\n\t\t\t{\"n\", n_},\n\t\t\t{\"a\", a_},\n\t\t\t{\"b\", b_}\n\t\t};\n\t}\n\n\t\n\ttemplate<class State>\n\ttypename State::Scalar operator()(const State& smp) const\n\t{\n\t\ttypename State::Scalar s = 0.0;\n\n\t\t//Nearest-neighbor\n\t\tfor(int i = 0; i < n_; i++)\n\t\t{\n\t\t\tdouble yysign = -smp.sigmaAt(i)*smp.sigmaAt((i+1)%n_);\n\t\t\ts += -J1*yysign; //zz\n\t\t\ts += J1*(a_+yysign*b_)*smp.ratio(i, (i+1)%n_); //xx+yy\n\t\t}\n\t\t//Next-nearest-neighbor\n\t\tfor(int i = 0; i < n_; i++)\n\t\t{\n\t\t\tdouble yysign = -smp.sigmaAt(i)*smp.sigmaAt((i+2)%n_);\n\t\t\ts += -J2*yysign; //zz\n\t\t\ts += J2*(b_+yysign*a_)*smp.ratio(i, (i+2)%n_); //xx+yy\n\t\t}\n\t\treturn s;\n\t}\n\n\tstd::vector< std::array<int, 2> > flips() const\n\t{\n\t\tstd::vector< std::array<int, 2> > res;\n\t\tfor(int i = 0; i < n_; i++)\n\t\t{\n\t\t\tres.push_back(std::array<int, 2>{i,(i+1)%n_});\n\t\t\tres.push_back(std::array<int, 2>{i,(i+2)%n_});\n\t\t}\n\t\treturn res;\n\t}\n\n\n\tstd::map<uint32_t, double> operator()(uint32_t col) const\n\t{\n\t\tstd::map<uint32_t, double> m;\n\t\tfor(int i = 0; i < n_; i++)\n\t\t{\n\t\t\tint b1 = (col >> i) & 1;\n\t\t\tint b2 = (col >> ((i+1)%n_)) & 1;\n\t\t\tint sgn = (1-2*b1)*(1-2*b2);\n\t\t\tlong long int x = (1 << i) | (1 << ((i+1)%(n_)));\n\t\t\tm[col ^ x] += J1*(a_ - sgn*b_);\n\t\t\tm[col] += J1*sgn;\n\t\t}\n\t\tfor(int i = 0; i < n_; i++)\n\t\t{\n\t\t\tint b1 = (col >> i) & 1;\n\t\t\tint b2 = (col >> ((i+2)%n_)) & 1;\n\t\t\tint sgn = (1-2*b1)*(1-2*b2);\n\t\t\tlong long int x = (1 << i) | (1 << ((i+2)%(n_)));\n\t\t\tm[col ^ x] += J2*(b_ - sgn*a_);\n\t\t\tm[col] += J2*sgn;\n\t\t}\n\t\treturn m;\n\t}\n};\n#endif//HAMILTONIANS_XYZNNN_HPP\n", "meta": {"hexsha": "afd7f7c0220b50265e14e67199b527123f15c6e0", "size": 1881, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Yannq/Hamiltonians/XYZNNN.hpp", "max_stars_repo_name": "cecri/yannq", "max_stars_repo_head_hexsha": "b78c1f86a255059f06b34dd5e538449e7261d0ee", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Yannq/Hamiltonians/XYZNNN.hpp", "max_issues_repo_name": "cecri/yannq", "max_issues_repo_head_hexsha": "b78c1f86a255059f06b34dd5e538449e7261d0ee", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Yannq/Hamiltonians/XYZNNN.hpp", "max_forks_repo_name": "cecri/yannq", "max_forks_repo_head_hexsha": "b78c1f86a255059f06b34dd5e538449e7261d0ee", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.4456521739, "max_line_length": 58, "alphanum_fraction": 0.5353535354, "num_tokens": 815, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.4566614384006735}}
{"text": "#define BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n#include \"../jngen.h\"\n\n#include <algorithm>\n#include <set>\n#include <sstream>\n#include <utility>\n\nBOOST_AUTO_TEST_SUITE(tree)\n\nvoid checkEquals(const jngen::Tree& t1, const jngen::Tree& t2) {\n    BOOST_TEST(t1.n() == t2.n());\n    for (int i = 0; i < t1.n(); ++i) {\n        BOOST_TEST(t1.edges(i).sorted() == t2.edges(i).sorted());\n    }\n}\n\nBOOST_AUTO_TEST_CASE(manual_construction) {\n    setMod().reset();\n\n    Tree t;\n\n    BOOST_TEST(t.n() == 1);\n    BOOST_TEST(t.m() == 0);\n    BOOST_TEST(t.isConnected());\n\n    t.addEdge(0, 1);\n    t.addEdge(2, 3);\n    BOOST_TEST(!t.isConnected());\n\n    t.addEdge(1, 2);\n\n    BOOST_TEST(t.n() == 4);\n    BOOST_TEST(t.m() == 3);\n\n    std::ostringstream ss;\n    ss << t.printN().add1() << std::endl;\n\n    BOOST_TEST(ss.str() == \"4\\n1 2\\n3 4\\n2 3\\n\");\n}\n\nvoid dfs(int v, int anc, const Tree& t, std::vector<int>& dist) {\n    for (int to: t.edges(v)) {\n        if (to == anc) {\n            continue;\n        }\n        dist[to] = dist[v] + 1;\n        dfs(to, v, t, dist);\n    }\n}\n\n/*\n * Find the diameter of the given tree.\n *\n * Returns: the diameter of the tree, measured in number of edges.\n * center: one or two vertices -- the center of the tree.\n * dist: distance from the first of the centers to all nodes.\n */\nint findDiameter(\n        const Tree& t,\n        std::vector<int>& centers,\n        std::vector<int>& dist)\n{\n    BOOST_REQUIRE(t.isConnected());\n    std::vector<int> dist1(t.n(), -1);\n    std::vector<int> dist2(t.n(), -1);\n\n    dist1[0] = 0;\n    dfs(0, -1, t, dist1);\n\n    int left = std::max_element(dist1.begin(), dist1.end()) - dist1.begin();\n    dist1[left] = 0;\n    dfs(left, -1, t, dist1);\n    int right = std::max_element(dist1.begin(), dist1.end()) - dist1.begin();\n    dist2[right] = 0;\n    dfs(right, -1, t, dist2);\n\n    BOOST_REQUIRE(dist1[right] == dist2[left]);\n\n    int diam = dist1[right];\n\n    centers.clear();\n    for (int v = 0; v < t.n(); ++v) {\n        if (dist1[v] + dist2[v] == diam && std::abs(dist1[v] - dist2[v]) <= 1) {\n            centers.push_back(v);\n        }\n    }\n\n    if (diam % 2 == 1) {\n        BOOST_REQUIRE(centers.size() == 2);\n    } else {\n        BOOST_REQUIRE(centers.size() == 1);\n    }\n\n    dist1[centers[0]] = 0;\n    dfs(centers[0], -1, t, dist1);\n    dist = dist1;\n\n    return diam;\n}\n\n/* Mostly performs sanity check on the generators: check some basic properties\n * of the resulting trees such as diameter.\n */\nBOOST_AUTO_TEST_CASE(generators) {\n    setMod().reset();\n    rnd.seed(12345);\n\n    std::vector<int> centers, dist;\n\n    auto b = Tree::bamboo(10);\n    BOOST_TEST(findDiameter(b, centers, dist) == 9);\n    BOOST_TEST(centers[0] == 4);\n    BOOST_TEST(centers[1] == 5);\n\n    std::ostringstream ss;\n\n    ss << b;\n    std::string first = ss.str();\n    ss.clear();\n\n    b.shuffle();\n\n    ss << b;\n    std::string second = ss.str();\n    ss.clear();\n\n    BOOST_TEST(first != second);\n\n    auto s = Tree::star(10);\n    BOOST_TEST(findDiameter(s, centers, dist) == 2);\n    BOOST_TEST(centers[0] == 0);\n\n    // probability of failure < 1e-5\n    auto c = Tree::caterpillar(100, 10);\n    BOOST_TEST(findDiameter(c, centers, dist) == 11);\n\n    // probability of failure < 1e-3\n    c = Tree::caterpillar(8004, 8000);\n    BOOST_TEST(findDiameter(c, centers, dist) == 7999);\n\n    // probability of failure unknown, but very low\n    auto t = Tree::randomPrim(150, 15000);\n    BOOST_TEST(t == Tree::bamboo(150));\n}\n\nBOOST_AUTO_TEST_CASE(prufer_all_trees) {\n    auto a = TArray<Tree>::randomfUnique(120, []() {\n        return Tree::random(5);\n    });\n    BOOST_TEST(a.size() == 5*4*3*2*1);\n\n    auto b = TArray<Tree>::randomfAll([]() {\n        return Tree::random(5);\n    });\n    BOOST_TEST(b.size() == 5*5*5);\n}\n\nBOOST_AUTO_TEST_CASE(check_link) {\n    /*        0   (4-2)    1\n            1   4   +    2   4\n          2    3 5      0 3   5\n                    =\n              0\n            1      4\n          2     3 5    8\n                     6 9 7\n                          10\n                            11\n     */\n    Tree t1;\n    for (std::pair<int, int> edge:\n            Arrayp{{0, 1}, {1, 2}, {0, 4}, {4, 3}, {4, 5}}) {\n        t1.addEdge(edge.first, edge.second);\n    }\n\n    Tree t2;\n    for (std::pair<int, int> edge:\n            Arrayp{{1, 2}, {2, 0}, {2, 3}, {1, 4}, {4, 5}}) {\n        t2.addEdge(edge.first, edge.second);\n    }\n\n    Tree t;\n    for (std::pair<int, int> edge: Arrayp{\n        {0, 1}, {1, 2}, {0, 4}, {4, 3}, {4, 5}, {4, 8}, {8, 6}, {8, 9},\n        {8, 7}, {7, 10}, {10, 11}})\n    {\n        t.addEdge(edge.first, edge.second);\n    }\n\n    Tree linked = t1.link(4, t2, 2);\n\n    BOOST_TEST(t1.n() + t2.n() == linked.n());\n    BOOST_TEST(t1.m() + t2.m() + 1 == linked.m());\n    checkEquals(linked, t);\n}\n\nBOOST_AUTO_TEST_CASE(check_glue) {\n    /*        0   (4-2)    1\n            1   4   .    2   4\n          2    3 5      0 3   5\n                    =\n              0\n            1      4\n          2     3 5 6 8 7\n                         9\n                          10\n     */\n    Tree t1;\n    for (std::pair<int, int> edge:\n            Arrayp{{0, 1}, {1, 2}, {0, 4}, {4, 3}, {4, 5}}) {\n        t1.addEdge(edge.first, edge.second);\n    }\n\n    Tree t2;\n    for (std::pair<int, int> edge:\n            Arrayp{{1, 2}, {2, 0}, {2, 3}, {1, 4}, {4, 5}}) {\n        t2.addEdge(edge.first, edge.second);\n    }\n\n    Tree t;\n    for (std::pair<int, int> edge: Arrayp{\n        {0, 1}, {1, 2}, {0, 4}, {4, 3}, {4, 5}, {4, 6}, {8, 4}, {4, 7},\n        {9, 7}, {9, 10}})\n    {\n        t.addEdge(edge.first, edge.second);\n    }\n\n    Tree glued = t1.glue(4, t2, 2);\n\n    BOOST_TEST(t1.n() + t2.n() - 1 == glued.n());\n    BOOST_TEST(t1.m() + t2.m() == glued.m());\n    checkEquals(glued, t);\n}\n\nBOOST_AUTO_TEST_CASE(print_parents) {\n    rnd.seed(123);\n    setMod().reset();\n\n    std::ostringstream ss;\n\n    const std::string res1 = \"5\\ngrt kzw bar pja oap\\n5 1 3 3\\n\";\n\n    Tree t = Tree::random(5);\n    t.setVertexWeights(TArray<std::string>::random(t.n(), \"[a-z]{%d}\", 3));\n    ss << t.add1().printN().printParents() << std::endl;\n\n    BOOST_TEST(ss.str() == res1);\n\n    t.setVertexWeights(WeightArray(t.n()));\n\n    ss.str(\"\");\n    ss << t.printParents(0);\n    BOOST_TEST(ss.str() == \"-1 4 0 2 2\");\n\n    ss.str(\"\");\n    ss << t.printParents(1);\n    BOOST_TEST(ss.str() == \"2 -1 4 2 1\");\n}\n\n// TODO: add tests to check random generators exactly\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "dec25db588a2ef3fa04b402ee413e553c1b00461", "size": 6436, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/tree.cpp", "max_stars_repo_name": "landcold7/jngen", "max_stars_repo_head_hexsha": "c7cfb26cd21009efbb736a75147da550c699b545", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 197.0, "max_stars_repo_stars_event_min_datetime": "2017-04-07T20:57:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T18:06:36.000Z", "max_issues_repo_path": "tests/tree.cpp", "max_issues_repo_name": "zekiriabd/jngen", "max_issues_repo_head_hexsha": "ca646e2f4df9b63c14380157d3911a0182149f94", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2017-07-14T01:42:44.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-31T11:25:40.000Z", "max_forks_repo_path": "tests/tree.cpp", "max_forks_repo_name": "zekiriabd/jngen", "max_forks_repo_head_hexsha": "ca646e2f4df9b63c14380157d3911a0182149f94", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 29.0, "max_forks_repo_forks_event_min_datetime": "2017-07-05T21:31:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-04T09:36:51.000Z", "avg_line_length": 24.2867924528, "max_line_length": 80, "alphanum_fraction": 0.5097886886, "num_tokens": 2112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.4566578048157717}}
{"text": "// Copyright Yamaha 2021\n// MIT License\n// https://github.com/yamaha-bps/cbr_control/blob/master/LICENSE\n\n#ifndef CBR_CONTROL__RATE_LIMITER_HPP_\n#define CBR_CONTROL__RATE_LIMITER_HPP_\n\n#include <boost/hana/adapt_struct.hpp>\n\n#include <cbr_utils/cyber_timer.hpp>\n\n#include <memory>\n#include <type_traits>\n#include <utility>\n\n\nnamespace cbr\n{\n\nstruct RateLimiterParams\n{\n  double rise_rate{1.};\n  double fall_rate{-1.};\n\n  void check_correctness() const\n  {\n    if (rise_rate < 0.) {\n      throw std::invalid_argument(\"parameter 'rise_rate' must be >= 0\");\n    }\n    if (fall_rate > 0.) {\n      throw std::invalid_argument(\"parameter 'fall_rate' must be <= 0\");\n    }\n  }\n};\n\ntemplate<typename _clock_t = std::chrono::high_resolution_clock>\nclass RateLimiter\n{\npublic:\n  using clock_t = _clock_t;\n  using timer_t = CyberTimerNoAvg<std::ratio<1>, double, clock_t>;\n\n  // Constructors\n  RateLimiter() = default;\n  RateLimiter(const RateLimiter &) = default;\n  RateLimiter(RateLimiter &) = default;\n  RateLimiter(RateLimiter &&) = default;\n  RateLimiter & operator=(const RateLimiter &) = default;\n  RateLimiter & operator=(RateLimiter &) = default;\n  RateLimiter & operator=(RateLimiter &&) = default;\n  ~RateLimiter() = default;\n\n  template<typename T>\n  explicit RateLimiter(T && clock, const RateLimiterParams & prm = {})\n  : timer_(std::forward<T>(clock)),\n    prm_(prm)\n  {\n    prm_.check_correctness();\n  }\n\n  explicit RateLimiter(const RateLimiterParams & prm)\n  : prm_(prm)\n  {\n    prm_.check_correctness();\n  }\n\n  template<typename T>\n  void set_clock(T && clock)\n  {\n    timer_.set_clock(std::forward<T>(clock));\n  }\n\n  void set_params(const RateLimiterParams & prm)\n  {\n    prm.check_correctness();\n    prm_ = prm;\n  }\n\n  const RateLimiterParams & get_params() const\n  {\n    return prm_;\n  }\n\n  const double & update(const double val, const typename timer_t::time_point tNow)\n  {\n    if (init_) {\n      // Define dt\n      const double dt = timer_.toctic(tNow);\n\n      // Compute Rate (derivative)\n      if (dt <= 0.) {\n        return output_;\n      }\n      const double rate = (val - output_) / dt;\n\n      // Assign Output\n      if (rate > prm_.rise_rate) {\n        return output_ += dt * prm_.rise_rate;\n      } else if (rate < prm_.fall_rate) {\n        return output_ += dt * prm_.fall_rate;\n      } else {\n        return output_ = val;\n      }\n    }\n\n    init_ = true;\n    timer_.tic(tNow);\n\n    return output_ = val;\n  }\n\n  const double & update(const double val)\n  {\n    return update(val, timer_.now());\n  }\n\n  const double & operator()(const double val)\n  {\n    return update(val);\n  }\n\n  const double & getValue() const\n  {\n    return output_;\n  }\n\n  void reset()\n  {\n    init_ = false;\n  }\n\n  const double & reset(const double val, const typename timer_t::time_point tNow)\n  {\n    init_ = true;\n    timer_.tic(tNow);\n    return output_ = val;\n  }\n\n  const double & reset(const double val)\n  {\n    return reset(val, timer_.now());\n  }\n\nprotected:\n  timer_t timer_ = timer_t(clock_t{});\n  RateLimiterParams prm_;\n  double output_{0.};\n  bool init_{false};\n};\n\n}    // namespace cbr\n\n// cppcheck-suppress unknownMacro\nBOOST_HANA_ADAPT_STRUCT(\n  cbr::RateLimiterParams,\n  rise_rate,\n  fall_rate\n);\n\n#endif  // CBR_CONTROL__RATE_LIMITER_HPP_\n", "meta": {"hexsha": "fb2991584c25e09c313d9f9211240cee30755ad6", "size": 3253, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/cbr_control/rate_limiter.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/rate_limiter.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/rate_limiter.hpp", "max_forks_repo_name": "yamaha-bps/cbr_control", "max_forks_repo_head_hexsha": "c2faf79673d46c950dd7590f1072fc7decafad06", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.2049689441, "max_line_length": 82, "alphanum_fraction": 0.652013526, "num_tokens": 885, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.45665780040310217}}
{"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#include <mpo19/paillier_wrapper.hpp>\n#include <cstring>\n\n#define BOOST_TEST_MODULE paillier_wrapper_test\n#include <boost/test/included/unit_test.hpp>\n#include <boost/test/data/test_case.hpp>\n#include <boost/test/data/monomorphic.hpp>\n\nnamespace bdata = boost::unit_test::data;\nusing namespace mpo19;\n\nconstexpr int m = 100;\n\nconstexpr key_id global = \"Global\";\n\nbool equal(plaintext const& lhs, plaintext const& rhs)\n{\n    std::vector<char> dec_lhs = lhs;\n    std::vector<char> dec_rhs = rhs;\n    assert(!dec_lhs.empty() && !dec_rhs.empty());\n    return strcmp(dec_lhs.data(), dec_rhs.data()) == 0;\n}\n\nbool equal(paillier<global> const& lhs, paillier<global> const& rhs)\n{\n    return equal(decrypt(lhs), decrypt(rhs));\n}\n\nBOOST_DATA_TEST_CASE(paillier_operation_test\n                     , bdata::random(0, m) ^ bdata::random(0, m)\n                     ^ bdata::xrange(10)\n                     , s1, s2, idx)\n{\n    (void) idx;\n    BOOST_TEST(paillier<global>::get_keys().has_public_key());\n    BOOST_TEST(paillier<global>::get_keys().has_private_key());\n    paillier<global>  p1 = paillier<global>::gen_random(40);\n    paillier<global>  p2 = paillier<global>::gen_random(40);\n    paillier<global>  p3 = paillier<global>::gen_random(40);\n\n\n    //Associativity\n    BOOST_TEST( equal( (p1 + p2) + p3, p1 + (p2 + p3) ) );\n\n    BOOST_TEST( equal( (s1 * p1) * s2, s1 * (p1 * s2) ) );\n    BOOST_TEST( equal(p1 * (s1 * s2), (p1 * s1) * s2) );\n\n    //Commutativity\n    BOOST_TEST( equal(p1 + p2, p2 + p1) );\n    BOOST_TEST( equal(s1 * p1, p1 * s1) );\n\n    //Neutral Element\n    BOOST_TEST( equal(p1 + paillier<global>::encrypt_zero(), p1) );\n    BOOST_TEST( equal(p1 * 1, p1) );\n\n    //Distributivity\n    BOOST_TEST( equal(s1 * (p1 + p2), s1 * p1 + s1 * p2) );\n\n    //Plus is consistent\n    BOOST_TEST( equal(p1 + p1, 2*p1) );\n    BOOST_TEST( equal(p1 + p1 + p1, 3*p1) );\n\n    //Consistency with +=, *=\n    paillier<global>  enc_s1 = paillier<global>::encrypt(s1);\n    paillier<global>  enc_s2 = paillier<global>::encrypt(s2);\n\n    enc_s1 += enc_s2;\n    BOOST_TEST( equal(enc_s1, paillier<global>::encrypt(s1+s2) ) );\n    enc_s2 += enc_s1;\n    BOOST_TEST( equal(enc_s2, paillier<global>::encrypt(s2+s1+s2) ) );\n    enc_s1 += enc_s2;\n    BOOST_TEST( equal(enc_s1, paillier<global>::encrypt(s1+s2+s2+s1+s2) ) );\n    enc_s1 *= s2;\n    BOOST_TEST( equal(enc_s1, paillier<global>::encrypt( (s1+s2+s2+s1+s2)*s2) ) );\n    enc_s1 *= s1;\n    BOOST_TEST( equal(enc_s1, paillier<global>::encrypt( (s1+s2+s2+s1+s2)*s2*s1) ) );\n}\n\n#include <iostream>\n#include <fstream>\n\nBOOST_DATA_TEST_CASE(paillier_serialization_test\n                     , bdata::random(0, m) ^ bdata::xrange(10), s1, idx)\n{\n    (void) idx;\n    paillier<global> p1{paillier<global>::gen_random(40)};\n    paillier<global> p2{paillier<global>::gen_random(40)};\n\n    std::ofstream ofs;\n    ofs.exceptions(std::ios::failbit | std::ios::badbit);\n    ofs.open(\"test.bin\", std::ios::binary | std::ios::trunc | std::ios::out);\n\n    ofs << plaintext{} << paillier<global>::get_keys().get_public() << \" \"\n        << plaintext{} << p1 << p2 << s1 << \" \"\n        << p1 + p2 << p2 * s1\n        << decrypt(p1) << plaintext{};\n    ofs.close();\n\n    std::ifstream ifs;\n    ifs.exceptions(std::ios::failbit | std::ios::badbit);\n    ifs.open(\"test.bin\", std::ios::binary | std::ios::in);\n    paillier_keys::public_key pub;\n    paillier<global>  sp1, sp2, sp1p2, sp2s1;\n    plaintext dec_p1, inv_p1, inv_p2, inv_p3;\n    int ss1;\n    ifs >> inv_p1 >> pub;\n    char skip = ifs.get();\n    BOOST_TEST(' ' == skip);\n    ifs >> inv_p2 >> sp1 >> sp2 >> ss1;\n    skip = ifs.get();\n    BOOST_TEST(' ' == skip);\n    ifs >> sp1p2 >> sp2s1 >> dec_p1 >> inv_p3;\n    ifs.close();\n\n    BOOST_TEST(equal(p1, sp1));\n    BOOST_TEST(equal(p2, sp2));\n    BOOST_TEST(s1 == ss1);\n    BOOST_TEST(equal(p1 + p2, sp1p2));\n    BOOST_TEST(equal(p2 * s1, sp2s1));\n    BOOST_TEST(equal(decrypt(p1), dec_p1));\n    BOOST_TEST(!inv_p1.valid());\n    BOOST_TEST(!inv_p2.valid());\n    BOOST_TEST(!inv_p3.valid());\n}\n", "meta": {"hexsha": "1ad05b6c6f1049d2b270e26a4223c98363a4677d", "size": 5141, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "hc_protocols/tests/paillier_wrapper_test.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": "hc_protocols/tests/paillier_wrapper_test.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": "hc_protocols/tests/paillier_wrapper_test.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": 34.9727891156, "max_line_length": 85, "alphanum_fraction": 0.6471503599, "num_tokens": 1559, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.6757646075489391, "lm_q1q2_score": 0.45665780040310205}}
{"text": "//==================================================================================================\n/*!\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#include <boost/simd/function/scalar/ilog2.hpp>\n#include <scalar_test.hpp>\n#include <boost/simd/detail/dispatch/meta/as_integer.hpp>\n#include <boost/simd/constant/three.hpp>\n#include <boost/simd/constant/four.hpp>\n#include <boost/simd/constant/pi.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/two.hpp>\n#include <boost/simd/constant/valmax.hpp>\n\nSTF_CASE_TPL (\" ilog2real\",  STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::ilog2;\n\n  // return type conformity test\n  STF_EXPR_IS(ilog2(T()),  bd::as_integer_t<T>);\n\n  // specific values tests\n  STF_EQUAL(ilog2(bs::Two<T>()), 1);\n  STF_EQUAL(ilog2(bs::Three<T>()), 1);\n  STF_EQUAL(ilog2(bs::Four<T> ()), 2);\n  STF_EQUAL(ilog2(bs::Pi<T> ()), 1);\n  STF_EQUAL(ilog2(bs::One<T>()), 0);\n} // end of test for real_\n\nSTF_CASE_TPL (\" ilog2signed_int\",  STF_SIGNED_INTEGRAL_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::ilog2;\n\n  // return type conformity test\n  STF_EXPR_IS(ilog2(T()),  bd::as_integer_t<T>);\n\n  // specific values tests\n  STF_EQUAL(ilog2(bs::One<T>()), 0);\n  STF_EQUAL(ilog2(bs::Two<T>()), 1);\n} // end of test for signed_int_\n\n STF_CASE_TPL (\" ilog2unsigned_int\",  STF_UNSIGNED_INTEGRAL_TYPES)\n {\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::ilog2;\n\n  // return type conformity test\n  STF_EXPR_IS(ilog2(T()),  bd::as_integer_t<T>);\n\n  // specific values tests\n  STF_EQUAL(ilog2(bs::One<T>()), 0u);\n  STF_EQUAL(ilog2(bs::Two<T>()),1u);\n\n  T j = 1;\n  for(T i=2; i < bs::Valmax<T>()/2; i*= 2)\n  {\n    STF_EQUAL(ilog2(T(i)),j);\n    STF_EQUAL(ilog2(T(i+1)),j);\n    ++j;\n  }\n } // end of test for unsigned_int_\n", "meta": {"hexsha": "f31c7aea2800bb394da04b1a45f74cbf78ac91e3", "size": 2089, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/scalar/ilog2.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": "test/function/scalar/ilog2.cpp", "max_issues_repo_name": "remymuller/boost.simd", "max_issues_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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/function/scalar/ilog2.cpp", "max_forks_repo_name": "remymuller/boost.simd", "max_forks_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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": 29.0138888889, "max_line_length": 100, "alphanum_fraction": 0.6112972714, "num_tokens": 617, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.45665779157776293}}
{"text": "//////////////////////////////////////////////////////////////////////////////\n// data::set::levels_traits.hpp         \t\t\t\t\t\t\t\t\t//\n//                                                                          //\n//                                                                          //\n//  (C) Copyright 2010 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_DATA_SET_LEVEL_TRAITS_HPP_ER_2010\n#define BOOST_STATISTICS_DETAIL_DATA_SET_LEVEL_TRAITS_HPP_ER_2010\n#include <boost/statistics/detail/data/types/array/array_traits.hpp>\n\nnamespace boost{\nnamespace statistics{\nnamespace detail{\nnamespace data{\n\n\t// An often convenient and efficient way to represent K input levels is\n    // as a array of fields of static size (K).  \n\ttemplate<int K, typename F = field::x>\n    struct level_traits : array_traits<F,K>{};\n\n}// data\n}// detail\n}// statistics\n}// boost\n\n#endif\n\n\n\n\n", "meta": {"hexsha": "dd5bcffc97712bd9fc41e76f879bdb6d0da70678", "size": 1228, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "data/boost/statistics/detail/data/set/level_traits.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": "data/boost/statistics/detail/data/set/level_traits.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": "data/boost/statistics/detail/data/set/level_traits.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.1176470588, "max_line_length": 78, "alphanum_fraction": 0.4983713355, "num_tokens": 216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723317123102956, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.45663337778127117}}
{"text": "//==============================================================================\n//         Copyright 2015          J.T. Lapreste\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#include <boost/simd/arithmetic/include/functions/round.hpp>\n#include <boost/simd/sdk/simd/native.hpp>\n#include <boost/dispatch/functor/meta/call.hpp>\n#include <nt2/sdk/unit/tests/relation.hpp>\n#include <nt2/sdk/unit/tests/ulp.hpp>\n#include <nt2/sdk/unit/module.hpp>\n#include <boost/simd/include/constants/zero.hpp>\n#include <boost/simd/include/constants/one.hpp>\n#include <boost/simd/include/constants/mone.hpp>\n#include <boost/simd/include/constants/inf.hpp>\n#include <boost/simd/include/constants/minf.hpp>\n#include <boost/simd/include/constants/nan.hpp>\n#include <boost/simd/include/constants/valmax.hpp>\n#include <boost/simd/include/constants/valmin.hpp>\n#include <boost/simd/include/constants/maxflint.hpp>\n#include <boost/simd/include/constants/half.hpp>\n\n#include <boost/simd/sdk/config.hpp>\n#include <boost/simd/sdk/simd/io.hpp>\n#include <boost/simd/include/functions/prev.hpp>\n#include <boost/simd/include/functions/next.hpp>\n#include <boost/simd/include/functions/splat.hpp>\n#include <boost/simd/include/functions/multiplies.hpp>\n#include <boost/simd/include/functions/plus.hpp>\n#include <boost/simd/include/functions/splat.hpp>\n\nNT2_TEST_CASE_TPL ( round_real, BOOST_SIMD_SIMD_REAL_TYPES)\n{\n  using boost::simd::round;\n  using boost::simd::tag::round_;\n  using boost::simd::next;\n  using boost::simd::prev;\n  using boost::simd::native;\n  typedef BOOST_SIMD_DEFAULT_EXTENSION  ext_t;\n  typedef native<T,ext_t>                  vT;\n  typedef typename boost::dispatch::meta::call<round_(vT)>::type r_t;\n\n  // specific values tests\n#ifndef BOOST_SIMD_NO_INVALIDS\n  NT2_TEST_EQUAL(round(boost::simd::Inf<vT>()), boost::simd::Inf<r_t>());\n  NT2_TEST_EQUAL(round(boost::simd::Minf<vT>()), boost::simd::Minf<r_t>());\n  NT2_TEST_EQUAL(round(boost::simd::Nan<vT>()), boost::simd::Nan<r_t>());\n#endif\n  NT2_TEST_EQUAL(round(boost::simd::splat<vT>(1.4)), boost::simd::One<r_t>());\n  NT2_TEST_EQUAL(round(boost::simd::splat<vT>(1.5)), boost::simd::Two<r_t>());\n  NT2_TEST_EQUAL(round(boost::simd::splat<vT>(1.6)), boost::simd::Two<r_t>());\n  NT2_TEST_EQUAL(round(boost::simd::splat<vT>(2.5)), boost::simd::Three<r_t>());\n  NT2_TEST_EQUAL(round(boost::simd::Half<vT>()), boost::simd::One<r_t>());\n  NT2_TEST_EQUAL(round(boost::simd::Mhalf<vT>()), boost::simd::Mone<r_t>());\n  NT2_TEST_EQUAL(round(boost::simd::Mone<vT>()), boost::simd::Mone<r_t>());\n  NT2_TEST_EQUAL(round(boost::simd::One<vT>()), boost::simd::One<r_t>());\n  NT2_TEST_EQUAL(round(boost::simd::Zero<vT>()), boost::simd::Zero<r_t>());\n  NT2_TEST_EQUAL(round(boost::simd::Maxflint<vT>()-boost::simd::Half<T>()),boost::simd::Maxflint<vT>());\n  NT2_TEST_EQUAL(round(boost::simd::Maxflint<vT>()),boost::simd::Maxflint<vT>());\n  NT2_TEST_EQUAL(round(prev(prev(boost::simd::Half<vT>()))),  boost::simd::Zero<vT>());\n  NT2_TEST_EQUAL(round(prev(boost::simd::Half<vT>())),  boost::simd::Zero<vT>());\n  NT2_TEST_EQUAL(round(     boost::simd::Half<vT>()) ,  boost::simd::One <vT>());\n  NT2_TEST_EQUAL(round(next(boost::simd::Half<vT>())),  boost::simd::One <vT>());\n  vT z = boost::simd::Maxflint <vT>()*boost::simd::Half<vT>()+boost::simd::One<vT>();\n  NT2_TEST_EQUAL(round(z), z);\n} // end of test for floating_\n\nNT2_TEST_CASE_TPL ( round_real2,  BOOST_SIMD_SIMD_REAL_TYPES)\n{\n\n  using boost::simd::round;\n  using boost::simd::tag::round_;\n  using boost::simd::native;\n  typedef BOOST_SIMD_DEFAULT_EXTENSION  ext_t;\n  typedef native<T,ext_t>                  vT;\n  typedef typename boost::dispatch::meta::call<round_(vT)>::type r_t;\n\n  // specific values tests\n#ifndef BOOST_SIMD_NO_INVALIDS\n  NT2_TEST_EQUAL(round(boost::simd::Inf<vT>(), 2), boost::simd::Inf<r_t>());\n  NT2_TEST_EQUAL(round(boost::simd::Minf<vT>(), 2), boost::simd::Minf<r_t>());\n  NT2_TEST_EQUAL(round(boost::simd::Nan<vT>(), 2), boost::simd::Nan<r_t>());\n#endif\n  NT2_TEST_EQUAL(round(boost::simd::Mhalf<vT>(), 2), boost::simd::Mhalf<r_t>());\n  NT2_TEST_EQUAL(round(boost::simd::Mone<vT>(), 2), boost::simd::Mone<r_t>());\n  NT2_TEST_EQUAL(round(boost::simd::One<vT>(), 2), boost::simd::One<r_t>());\n  NT2_TEST_EQUAL(round(boost::simd::Zero<vT>(), 2), boost::simd::Zero<r_t>());\n  NT2_TEST_EQUAL(round(boost::simd::Maxflint<vT>()-boost::simd::Half<vT>(), 2),boost::simd::Maxflint<vT>());\n  NT2_TEST_EQUAL(round(boost::simd::Maxflint<vT>(), 2),boost::simd::Maxflint<vT>());\n  NT2_TEST_EQUAL(round(boost::simd::splat<vT>(1.44), 1), boost::simd::splat<vT>(1.4));\n  NT2_TEST_EQUAL(round(boost::simd::splat<vT>(1.45), 1), boost::simd::splat<vT>(1.5));\n  NT2_TEST_EQUAL(round(boost::simd::splat<vT>(1.46), 1), boost::simd::splat<vT>(1.5));\n  NT2_TEST_EQUAL(round(boost::simd::splat<vT>(2.45), 1), boost::simd::splat<vT>(2.5));\n  NT2_TEST_EQUAL(round(boost::simd::splat<vT>(-1.44), 1), boost::simd::splat<vT>(-1.4));\n  NT2_TEST_EQUAL(round(boost::simd::splat<vT>(-1.45), 1), boost::simd::splat<vT>(-1.5));\n  NT2_TEST_EQUAL(round(boost::simd::splat<vT>(-1.46), 1), boost::simd::splat<vT>(-1.5));\n  NT2_TEST_EQUAL(round(boost::simd::splat<vT>(-2.45), 1), boost::simd::splat<vT>(-2.5));\n  NT2_TEST_ULP_EQUAL(round(boost::simd::splat<vT>(145), -2), boost::simd::splat<vT>(100), 0.5);\n  NT2_TEST_ULP_EQUAL(round(boost::simd::splat<vT>(150), -2), boost::simd::splat<vT>(200), 0.5);\n  NT2_TEST_ULP_EQUAL(round(boost::simd::splat<vT>(156), -2), boost::simd::splat<vT>(200), 0.5);\n  NT2_TEST_ULP_EQUAL(round(boost::simd::splat<vT>(250), -2), boost::simd::splat<vT>(300), 0.5);\n  NT2_TEST_ULP_EQUAL(round(boost::simd::splat<vT>(-145), -2), boost::simd::splat<vT>(-100), 0.5);\n  NT2_TEST_ULP_EQUAL(round(boost::simd::splat<vT>(-155), -2), boost::simd::splat<vT>(-200), 0.5);\n  NT2_TEST_ULP_EQUAL(round(boost::simd::splat<vT>(-156), -2), boost::simd::splat<vT>(-200), 0.5);\n  NT2_TEST_ULP_EQUAL(round(boost::simd::splat<vT>(-255), -2), boost::simd::splat<vT>(-300), 0.5);\n} // end of test for floating_\n\nNT2_TEST_CASE_TPL ( round_real2b,  BOOST_SIMD_SIMD_REAL_TYPES)\n{\n\n  using boost::simd::round;\n  using boost::simd::tag::round_;\n  using boost::simd::native;\n  using boost::simd::splat;\n  typedef BOOST_SIMD_DEFAULT_EXTENSION  ext_t;\n  typedef native<T,ext_t>                  vT;\n  typedef typename boost::dispatch::meta::as_integer<vT>::type viT;\n  typedef typename boost::dispatch::meta::call<round_(vT)>::type r_t;\n\n  // specific values tests\n#ifndef BOOST_SIMD_NO_INVALIDS\n  NT2_TEST_EQUAL(round(boost::simd::Inf<vT>(), splat<viT>(2)), boost::simd::Inf<r_t>());\n  NT2_TEST_EQUAL(round(boost::simd::Minf<vT>(), splat<viT>(2)), boost::simd::Minf<r_t>());\n  NT2_TEST_EQUAL(round(boost::simd::Nan<vT>(), splat<viT>(2)), boost::simd::Nan<r_t>());\n#endif\n  NT2_TEST_EQUAL(round(boost::simd::Mhalf<vT>(), splat<viT>(2)), boost::simd::Mhalf<r_t>());\n  NT2_TEST_EQUAL(round(boost::simd::Mone<vT>(), splat<viT>(2)), boost::simd::Mone<r_t>());\n  NT2_TEST_EQUAL(round(boost::simd::One<vT>(), splat<viT>(2)), boost::simd::One<r_t>());\n  NT2_TEST_EQUAL(round(boost::simd::Zero<vT>(), splat<viT>(2)), boost::simd::Zero<r_t>());\n  NT2_TEST_EQUAL(round(boost::simd::Maxflint<vT>()-boost::simd::Half<vT>(), splat<viT>(2)),boost::simd::Maxflint<vT>());\n  NT2_TEST_EQUAL(round(boost::simd::Maxflint<vT>(), splat<viT>(2)),boost::simd::Maxflint<vT>());\n  NT2_TEST_EQUAL(round(boost::simd::splat<vT>(1.44), splat<viT>(1)), boost::simd::splat<vT>(1.4));\n  NT2_TEST_EQUAL(round(boost::simd::splat<vT>(1.45), splat<viT>(1)), boost::simd::splat<vT>(1.5));\n  NT2_TEST_EQUAL(round(boost::simd::splat<vT>(1.46), splat<viT>(1)), boost::simd::splat<vT>(1.5));\n  NT2_TEST_EQUAL(round(boost::simd::splat<vT>(2.45), splat<viT>(1)), boost::simd::splat<vT>(2.5));\n  NT2_TEST_EQUAL(round(boost::simd::splat<vT>(-1.44), splat<viT>(1)), boost::simd::splat<vT>(-1.4));\n  NT2_TEST_EQUAL(round(boost::simd::splat<vT>(-1.45), splat<viT>(1)), boost::simd::splat<vT>(-1.5));\n  NT2_TEST_EQUAL(round(boost::simd::splat<vT>(-1.46), splat<viT>(1)), boost::simd::splat<vT>(-1.5));\n  NT2_TEST_EQUAL(round(boost::simd::splat<vT>(-2.45), splat<viT>(1)), boost::simd::splat<vT>(-2.5));\n  NT2_TEST_ULP_EQUAL(round(boost::simd::splat<vT>(145), splat<viT>(-2)), boost::simd::splat<vT>(100), 0.5);\n  NT2_TEST_ULP_EQUAL(round(boost::simd::splat<vT>(150), splat<viT>(-2)), boost::simd::splat<vT>(200), 0.5);\n  NT2_TEST_ULP_EQUAL(round(boost::simd::splat<vT>(156), splat<viT>(-2)), boost::simd::splat<vT>(200), 0.5);\n  NT2_TEST_ULP_EQUAL(round(boost::simd::splat<vT>(250), splat<viT>(-2)), boost::simd::splat<vT>(300), 0.5);\n  NT2_TEST_ULP_EQUAL(round(boost::simd::splat<vT>(-145), splat<viT>(-2)), boost::simd::splat<vT>(-100), 0.5);\n  NT2_TEST_ULP_EQUAL(round(boost::simd::splat<vT>(-155), splat<viT>(-2)), boost::simd::splat<vT>(-200), 0.5);\n  NT2_TEST_ULP_EQUAL(round(boost::simd::splat<vT>(-156), splat<viT>(-2)), boost::simd::splat<vT>(-200), 0.5);\n  NT2_TEST_ULP_EQUAL(round(boost::simd::splat<vT>(-255), splat<viT>(-2)), boost::simd::splat<vT>(-300), 0.5);\n} // end of test for floating_\n\nNT2_TEST_CASE_TPL ( round_unsigned_int,  BOOST_SIMD_SIMD_UNSIGNED_TYPES)\n{\n  using boost::simd::round;\n  using boost::simd::tag::round_;\n  using boost::simd::native;\n  typedef BOOST_SIMD_DEFAULT_EXTENSION  ext_t;\n  typedef native<T,ext_t>                  vT;\n  typedef typename boost::dispatch::meta::call<round_(vT)>::type r_t;\n\n  // specific values tests\n  NT2_TEST_EQUAL(round(boost::simd::One<vT>()), boost::simd::One<r_t>());\n  NT2_TEST_EQUAL(round(boost::simd::Valmax<vT>()), boost::simd::Valmax<r_t>());\n  NT2_TEST_EQUAL(round(boost::simd::Valmin<vT>()), boost::simd::Valmin<r_t>());\n  NT2_TEST_EQUAL(round(boost::simd::Zero<vT>()), boost::simd::Zero<r_t>());\n} // end of test for unsigned_int_\n\nNT2_TEST_CASE_TPL ( round_signed_int,  BOOST_SIMD_SIMD_INTEGRAL_SIGNED_TYPES)\n{\n  using boost::simd::round;\n  using boost::simd::tag::round_;\n  using boost::simd::native;\n  typedef BOOST_SIMD_DEFAULT_EXTENSION  ext_t;\n  typedef native<T,ext_t>                  vT;\n  typedef typename boost::dispatch::meta::call<round_(vT)>::type r_t;\n\n  // specific values tests\n  NT2_TEST_EQUAL(round(boost::simd::Mone<vT>()), boost::simd::Mone<r_t>());\n  NT2_TEST_EQUAL(round(boost::simd::One<vT>()), boost::simd::One<r_t>());\n  NT2_TEST_EQUAL(round(boost::simd::Valmax<vT>()), boost::simd::Valmax<r_t>());\n  NT2_TEST_EQUAL(round(boost::simd::Valmin<vT>()), boost::simd::Valmin<r_t>());\n  NT2_TEST_EQUAL(round(boost::simd::Zero<vT>()), boost::simd::Zero<r_t>());\n} // end of test for signed_int_\n\n", "meta": {"hexsha": "23dea118e15a0a9db6c08f8649ca87e000e669ba", "size": 10891, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/base/unit/arithmetic/simd/round.cpp", "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/unit/arithmetic/simd/round.cpp", "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/unit/arithmetic/simd/round.cpp", "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": 58.2406417112, "max_line_length": 120, "alphanum_fraction": 0.6691763842, "num_tokens": 3546, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.6791787121629465, "lm_q1q2_score": 0.456633377594913}}
{"text": "#include <Eigen/Core>\n#include <Eigen/SVD>\n\n#include <iostream>\n#include <sstream>\n#include <string>\n\n#include \"arraytools.h\"\n#include \"oaoptions.h\"\n#include \"printfheader.h\"\n#include \"tools.h\"\n#include \"version.h\"\n\nnamespace nauty {\n#include \"nauty.h\"\n}\n\n/// Information about compile time options\nstd::string compile_information () {\n        std::stringstream ss;\n        print_options (ss);\n\n        return ss.str ();\n}\n\n/** Return version of program */\nstd::string version () {\n        std::string v = __version__;\n        return v;\n}\n\n/** @brief Print copyright notice\n */\nvoid print_copyright () {\n        myprintf (\"Orthogonal Arrays %s\\n\", version ().c_str ());\n        myprintf (\"For more details see the files README.txt and LICENSE.txt\\n\");\n}\n/** @brief Print brief copyright notice\n */\nvoid print_copyright_light () { myprintf (\"Orthogonal Array package %s\\n\", version ().c_str ()); }\n\n#include <Eigen/Core>\n#include <Eigen/LU>\n#include <Eigen/SVD>\n\n// http://sourceforge.net/p/predef/wiki/Compilers/\n#if defined(__GNUC__)\n#if defined(__GNUC_PATCHLEVEL__)\n#define __GNUC_VERSION__ (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)\n#else\n#define __GNUC_VERSION__ (__GNUC__ * 10000 + __GNUC_MINOR__ * 100)\n#endif\n#else\n#define __GNUC_VERSION__ \"none\"\n#endif\n\n#ifndef __INTEL_COMPILER\n#define __INTEL_COMPILER \"none\"\n#endif\n\n/**\n * Print the compile-time options to a string.\n */\nstd::string print_options_string () {\n        std::string tabsep = \"  \";\n\n        std::stringstream outx;\n\n        outx << \"Orthogonal Array Package \" << version () << std::endl;\n\n        outx << \"Compile date: \" << __DATE__ << \" \" << __TIME__ << std::endl;\n\n        outx << tabsep << \"void * type: sizeof(void *) \" << sizeof (void *) << std::endl;\n        outx << tabsep << \"array_t type: sizeof(array_t) \" << sizeof (array_t) << std::endl;\n        outx << tabsep << \"integer types: sizeof(short int) \" << sizeof (short int) << std::endl;\n        outx << tabsep << \"integer types: sizeof(unsigned long int) \" << sizeof (unsigned long int) << \",\"\n             << \" sizeof(int) \" << sizeof (int) << std::endl;\n        outx << tabsep << \"integer types: sizeof(long long) \" << sizeof (long long) << std::endl;\n        outx << tabsep << \"floating point type: sizeof(float) \" << sizeof (float) << \", sizeof(double) \"\n             << sizeof (double) << \", sizeof(long double) \" << sizeof (long double) << std::endl;\n        outx << tabsep << \"Eigen version: \" << EIGEN_WORLD_VERSION << \".\" << EIGEN_MAJOR_VERSION << \".\"\n             << EIGEN_MINOR_VERSION << std::endl;\n\n        Eigen::MatrixXd mymatrix (1, 1);\n        Eigen::FullPivLU< Eigen::MatrixXd > lu_decomp (mymatrix);\n\n        outx << tabsep << \"eigen: JacobiSVD threshold \" << lu_decomp.threshold () << std::endl;\n\n// http://sourceforge.net/p/predef/wiki/Compilers/\n#ifdef WIN32\n#else\n        outx << tabsep << \"Compiler: __VERSION__ \" << __VERSION__ << std::endl;\n#endif\n        outx << tabsep << \"Compiler: __GNUC_VERSION__ \" << __GNUC_VERSION__ << std::endl;\n        outx << tabsep << \"Compiler: __INTEL_COMPILER \" << __INTEL_COMPILER << std::endl;\n\n#ifdef __OPTIMIZE__\n        outx << tabsep << \"Optimization: __OPTIMIZE__\" << std::endl;\n#endif\n        outx << tabsep << \"Compile time options: \"; // << std::endl;\n        std::string sep = \", \";\n\n#ifdef USEZLIB\n        outx << \"USEZLIB\" << sep;\n#endif\n\n#ifdef OACHECK\n        outx << \"OACHECK\" << sep;\n#endif\n\n#ifdef OADEBUG\n        outx << \"OADEBUG\" << sep;\n#endif\n\n#ifdef OAOVERFLOW\n        outx << \"OAOVERFLOW\" << sep;\n#endif\n\n#ifdef OAMEM\n        outx << \"OAMEM\" << sep;\n#endif\n\n#ifdef SAFELPERM\n        outx << \"SAFELPERM\" << sep;\n#endif\n\n#ifdef FREQELEM\n        outx << \"FREQELEM\" << sep;\n#endif\n\n#ifdef USE_ROW_SYMMETRY\n        outx << \"USE_ROW_SYMMETRY\" << sep;\n#endif\n\n#ifdef USE_SMALLSTEP\n        outx << \"USE_SMALLSTEP\" << sep;\n#endif\n\n#ifdef TPLUSCOLUMN\n        outx << \"USE_TPLUSCOLUMN\" << sep;\n#endif\n\n#ifdef SYMMBLOCKS\n        outx << \"SYMMBLOCKS\" << sep;\n#endif\n\n#ifdef JCHECK\n        outx << \"JCHECK\" << sep;\n#endif\n#ifdef OADEV\n        outx << \"OADEV\" << sep;\n#endif\n#ifdef SWIGCODE\n        outx << \"SWIG\" << sep;\n#endif\n        outx << std::endl;\n\n        outx << tabsep << \"columns sorting method: \" << oacolSortName << std::endl;\n\n        outx << tabsep << \"nauty: NAUTYVERSION \" << NAUTYVERSION << std::endl;\n        outx << tabsep << \"nauty: SIZEOF_LONG \" << SIZEOF_LONG << std::endl;\n\n        if (SIZEOF_LONG != sizeof (long)) {\n                outx << tabsep << \"!! ERROR: sizeof(long) does not correspond to compile time size of long\"\n                     << std::endl;\n        }\n        const std::string s = outx.str ();\n        return s;\n}\n\nvoid print_options () {\n        std::string s = print_options_string ();\n        myprintf (\"%s\", s.c_str ());\n}\n\nint has_zlib(){\n#ifdef USEZLIB\n\treturn true;\n#else\n\treturn false;\n#endif\n}\n\n/**\n * Print the compile-time options to output stream.\n * @param out\n */\nvoid print_options (std::ostream &out) {\n        std::string s = print_options_string ();\n        out << s;\n}\n\n// kate: indent-mode cstyle; indent-width 4; replace-tabs off; tab-width 4;\n", "meta": {"hexsha": "cd8ccec32773d212174e865aedaf9421adfe4e42", "size": 5133, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/oaoptions.cpp", "max_stars_repo_name": "ABohynDOE/oapackage", "max_stars_repo_head_hexsha": "d4df98ee94ecd98e5e9eec62dc29df9a7ec8c9ce", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2015-11-06T07:24:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T22:02:19.000Z", "max_issues_repo_path": "src/oaoptions.cpp", "max_issues_repo_name": "ABohynDOE/oapackage", "max_issues_repo_head_hexsha": "d4df98ee94ecd98e5e9eec62dc29df9a7ec8c9ce", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 37.0, "max_issues_repo_issues_event_min_datetime": "2015-11-06T07:25:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T01:33:47.000Z", "max_forks_repo_path": "src/oaoptions.cpp", "max_forks_repo_name": "ABohynDOE/oapackage", "max_forks_repo_head_hexsha": "d4df98ee94ecd98e5e9eec62dc29df9a7ec8c9ce", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2016-08-16T15:09:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-06T11:48:55.000Z", "avg_line_length": 26.4587628866, "max_line_length": 107, "alphanum_fraction": 0.6052990454, "num_tokens": 1388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723317123102956, "lm_q2_score": 0.679178692681616, "lm_q1q2_score": 0.45663337341529897}}
{"text": "#include \"regularization.hpp\"\n\n#include <string>\n#include <armadillo>\n#include \"yaml-cpp/yaml.h\"\n#include <iostream>\n\n\nRegularization::Regularization(const std::string &filenm):\n  fitness_(0.)\n{\n  YAML::Node config = YAML::LoadFile(filenm);\n\n  ni_ = config[\"ni\"].as<int>();\n  nk_ = config[\"nk\"].as<int>();\n  nplus_ = config[\"nplus\"].as<int>();\n  nx_ = ni_ + nplus_*2;\n  nz_ = nk_ + nplus_*2;\n\n  ni1_ = nplus_;\n  ni2_ = ni1_ + ni_ - 1;\n  nk1_ = nplus_;\n  nk2_ = nk1_ + nk_ - 1;\n\n  file_umodel_ = config[\"file_umodel\"].as<std::string>();\n  file_rmodel_ = config[\"file_rmodel\"].as<std::string>();\n\n  umodel_.set_size(nx_, nz_);\n  rmodel_.set_size(nx_, nz_);\n  gradient_.set_size(nx_, nz_);\n}\n\n\nnamespace\n{\n  void load_hdf5(arma::mat& data, std::string& filenm)\n  {\n    data.load(filenm);\n  }\n}\n\n\nvoid Regularization::load()\n{\n  load_hdf5(umodel_, file_umodel_);\n  load_hdf5(rmodel_, file_rmodel_);\n}\n\n\nvoid Regularization::save(std::string& filenm)\n{\n  gradient_.save(filenm, arma::hdf5_binary);\n}\n\n\nvoid Regularization::print_fitness(const std::string& s) const\n{\n  std::cout << \"The fitness of the \"\n            << s\n            << \" is \"\n            << fitness_\n            << std::endl;\n}\n", "meta": {"hexsha": "9995e5074e51f335ceb0bf7aefc19f4aa59df221", "size": 1190, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/regularization.cc", "max_stars_repo_name": "panlei7/regularization", "max_stars_repo_head_hexsha": "a417e844bfcc841e35f8075918837cc99a276bfc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/regularization.cc", "max_issues_repo_name": "panlei7/regularization", "max_issues_repo_head_hexsha": "a417e844bfcc841e35f8075918837cc99a276bfc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/regularization.cc", "max_forks_repo_name": "panlei7/regularization", "max_forks_repo_head_hexsha": "a417e844bfcc841e35f8075918837cc99a276bfc", "max_forks_repo_licenses": ["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.59375, "max_line_length": 62, "alphanum_fraction": 0.6277310924, "num_tokens": 378, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.4566333733221201}}
{"text": "/**\n *          Copyright Matthias Walter 2010.\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 PERMUTATION_HPP_\n#define PERMUTATION_HPP_\n\n#include <utility>\n#include <iostream>\n#include <vector>\n#include <map>\n#include <exception>\n#include <cassert>\n#include <boost/random/uniform_int.hpp>\n\nnamespace unimod\n{\n\n  /**\n   * Exception to indicate that the size of a permutation could not be be reduced.\n   */\n\n  class permutation_shrink_exception: std::exception\n  {\n  public:\n    permutation_shrink_exception()\n    {\n\n    }\n\n    virtual ~permutation_shrink_exception() throw ()\n    {\n\n    }\n\n    virtual const char* what() const throw ()\n    {\n      return \"Cannot shrink permutation\";\n    }\n  };\n\n  /**\n   * A permutation which maps integers from 0 to size-1 to the same range\n   * in any possible way. This implementation stores the image of each\n   * of the values in a vector.\n   */\n\n  class permutation\n  {\n  public:\n    typedef size_t size_type;\n    typedef ptrdiff_t difference_type;\n    typedef size_t value_type;\n    typedef std::vector <value_type> data_type;\n\n  protected:\n    data_type _data;\n\n  public:\n\n    /**\n     * Constructs a permutation of a given size,\n     * initializing to the identity.\n     *\n     * @param size Optional size of the permutation\n     */\n\n    permutation(size_type size = 0)\n    {\n      reset(size);\n    }\n\n    /**\n     * Constructs a permutation of a given size,\n     * initializing to a random permutation.\n     *\n     * @param size Optional size of the permutation\n     * @param rng Random number generator.\n     */\n\n    template <typename RandomNumberGenerator>\n    permutation(size_type size, RandomNumberGenerator& rng)\n    {\n      reset(size);\n      shuffle(rng);\n    }\n\n    /**\n     * Copy constructor\n     *\n     * @param other Another permutation\n     */\n\n    permutation(const permutation& other)\n    {\n      _data.resize(other.size());\n      for (size_type i = 0; i < _data.size(); ++i)\n        _data[i] = other._data[i];\n    }\n\n    /**\n     * Destructor\n     */\n\n    virtual ~permutation()\n    {\n\n    }\n\n    /**\n     * Resizes the permutation and resets it to identity.\n     *\n     * @param new_size New size\n     */\n\n    void reset(size_t new_size)\n    {\n      _data.resize(new_size);\n      for (size_type i = 0; i < new_size; ++i)\n      {\n        _data[i] = i;\n      }\n    }\n\n    /**\n     * Resets the permutation to identity.\n     */\n\n    inline void reset()\n    {\n      reset(_data.size());\n    }\n\n    /**\n     * Shuffles a permutation.\n     *\n     * @param rng Random number generator.\n     */\n\n    template <typename RandomNumberGenerator>\n    void shuffle(RandomNumberGenerator& rng)\n    {\n      for (size_t i = 0; i < _data.size(); ++i)\n      {\n        boost::uniform_int <int> dist(i, _data.size() - 1);\n        size_t j = dist(rng);\n        swap(i, j);\n      }\n    }\n\n    /**\n     * @return The current size of the permutation\n     */\n\n    inline size_type size() const\n    {\n      return _data.size();\n    }\n\n    /**\n     * The image of a specific integer in range 0 .. size-1.\n     *\n     * @param index Given integer\n     * @return The integers image\n     */\n\n    inline value_type operator()(value_type index) const\n    {\n      return get(index);\n    }\n\n    /**\n     * The image of a specific integer in range 0 .. size-1.\n     * @param index Given integer\n     * @return The integers image\n     */\n\n    inline value_type get(value_type index) const\n    {\n      assert (index < _data.size());\n\n      return _data[index];\n    }\n\n    /**\n     * Swaps the images of two integers in range 0 .. size-1.\n     *\n     * @param a First integer\n     * @param b Second integer\n     */\n\n    inline void swap(value_type a, value_type b)\n    {\n      std::swap(_data[a], _data[b]);\n    }\n\n    /**\n     * Swaps the preimages of two integers in range 0 .. size-1.\n     *\n     * @param a First integer\n     * @param b Second integer\n     */\n\n    void rswap(value_type a, value_type b)\n    {\n      value_type tmp, pa = a, pb = b;\n      while ((tmp = get(pa)) != a)\n        pa = tmp;\n      while ((tmp = get(pb)) != b)\n        pb = tmp;\n      swap(pa, pb);\n    }\n\n    /**\n     * Makes this permutation its own inverse.\n     */\n\n    void revert()\n    {\n      /// Create a temporary copy\n      value_type* temp = new value_type[size()];\n      for (size_type i = 0; i < size(); ++i)\n        temp[i] = _data[i];\n\n      for (size_type i = 0; i < size(); ++i)\n        _data[temp[i]] = i;\n      delete[] temp;\n    }\n\n    /**\n     * @return The inverse permutation of this permutation\n     */\n\n    permutation reverse() const\n    {\n      permutation result(size());\n      for (size_type i = 0; i < size(); ++i)\n        result._data[get(i)] = i;\n      return result;\n    }\n\n    /**\n     * Assignment operator.\n     *\n     * @param other Another permutation\n     * @return A reference to this permutation\n     */\n\n    permutation& operator=(const permutation& other)\n    {\n      _data.resize(other.size());\n      for (size_type i = 0; i < _data.size(); ++i)\n        _data[i] = other._data[i];\n      return *this;\n    }\n\n    /**\n     * Calculates the product of this and another permutation.\n     * The result is equivalent to applying the second permutation\n     * first and this one afterwards.\n     *\n     * @param rhs Right hand side permutation\n     * @return The resulting permutation\n     */\n\n    permutation operator*(const permutation& rhs) const\n    {\n      assert (size() == rhs.size());\n\n      permutation result(size());\n      for (size_type i = 0; i < size(); ++i)\n        result._set(i, _data[rhs(i)]);\n\n      return result;\n    }\n\n    /**\n     * Resizes the permutation, retaining the contents.\n     * This may fail if it cannot be shrunken this way and\n     * will throw a permutation_shrink_exception in that case.\n     *\n     * @param new_size New size of the permutation\n     */\n\n    void resize(size_type new_size)\n    {\n      size_type old_size = size();\n      for (size_type i = new_size; i < old_size; ++i)\n      {\n        if (_data[i] < new_size)\n          throw permutation_shrink_exception();\n      }\n\n      _data.resize(new_size);\n      for (size_type i = old_size; i < new_size; i++)\n        _data[i] = i;\n    }\n\n    /**\n     * Grows the permutation by a given number of elements.\n     *\n     * @param by Number of elements to increase the size by\n     */\n\n    inline void grow(difference_type by)\n    {\n      resize(size() + by);\n    }\n\n    /**\n     * Shrinks the permutation by a given number of elements.\n     *\n     * @param by Number of elements to decrease the size by\n     */\n\n    inline void shrink(difference_type by)\n    {\n      resize(size() - by);\n    }\n\n  protected:\n\n    /// Class to enumerate permutations\n\n    friend class permutation_enumerator;\n\n    /// Class to setup a permutation which can be put before a vector.\n\n    template <class Less>\n    friend void sort(permutation& permutation, size_t first, size_t beyond, Less& less);\n\n    /**\n     * Sets a specific value without checking validity.\n     *\n     * @param index Index of the entry\n     * @param value New value\n     */\n\n    void _set(value_type index, value_type value)\n    {\n      _data[index] = value;\n    }\n\n    /**\n     * @return A reference to the data vector\n     */\n\n    inline data_type& get_data()\n    {\n      return _data;\n    }\n\n  };\n\n  /**\n   * Enumerates all permutations of a given size with\n   * optional constraints. You must derive from it\n   * and override the visitor() method.\n   */\n\n  class permutation_enumerator\n  {\n  public:\n    typedef size_t size_type;\n    typedef std::vector <permutation::value_type> memberlist_type;\n    typedef std::pair <memberlist_type*, permutation*> groupinfo_type;\n    typedef std::map <int, groupinfo_type> state_type;\n\n  private:\n    size_type _size;\n    state_type _state;\n    permutation _permutation;\n\n  public:\n\n    /**\n     * Constructs an enumerator without constraints.\n     * Has O(size!) running time.\n     *\n     * @param size Size of the permutations\n     */\n\n    permutation_enumerator(permutation::size_type size) :\n      _permutation(size)\n    {\n      if (size)\n      {\n        memberlist_type* memberlist = new memberlist_type();\n        memberlist->resize(size);\n        for (permutation::size_type i = 0; i < size; i++)\n          (*memberlist)[i] = i;\n        permutation* perm = new permutation(size);\n        _state[0] = groupinfo_type(memberlist, perm);\n      }\n    }\n\n    /**\n     * Constructs an enumerator with grouping constraints:\n     * Only those permutations are enumerated where k and p(k) are\n     * in the same group for all i.\n     *\n     * @param groups Vector of groups\n     */\n\n    permutation_enumerator(const std::vector <permutation::value_type>& groups) :\n      _permutation(groups.size())\n    {\n      _size = groups.size();\n      for (size_t i = 0; i < groups.size(); ++i)\n      {\n        state_type::iterator iter = _state.find(groups[i]);\n        if (iter == _state.end())\n        {\n          _state[groups[i]] = groupinfo_type(new memberlist_type(), NULL);\n          _state[groups[i]].first->push_back(i);\n        }\n        else\n        {\n          iter->second.first->push_back(i);\n        }\n      }\n      for (state_type::iterator iter = _state.begin(); iter != _state.end(); ++iter)\n      {\n        groupinfo_type& info = iter->second;\n        info.second = new permutation(info.first->size());\n      }\n    }\n\n    /**\n     * Destructor.\n     */\n\n    virtual ~permutation_enumerator()\n    {\n      for (state_type::iterator iter = _state.begin(); iter != _state.end(); ++iter)\n      {\n        delete iter->second.first;\n        delete iter->second.second;\n      }\n    }\n\n    /**\n     * @return true if and only if the size of each permutation is zero\n     */\n\n    inline bool empty()\n    {\n      return _size == 0;\n    }\n\n    /**\n     * Starts the enumeration which is aborted if any\n     * visitor returns false.\n     *\n     * @return true if and only if all visitors returned true\n     */\n\n    virtual bool enumerate()\n    {\n      if (empty())\n        return true;\n\n      return enumerate_group(_state.begin(), 0);\n    }\n\n  protected:\n\n    /**\n     * Method which is called for each enumerated permutation.\n     * Needs to be overridden.\n     *\n     * @param perm Current permutation\n     * @return false to abort enumeration\n     */\n\n    virtual bool visitor(const permutation& perm) = 0;\n\n  private:\n\n    /**\n     * Enumerates possible values at a given index in a given group.\n     *\n     * @param state Current state and group\n     * @param index Current index to enumerate values\n     * @return false to abort enumeration\n     */\n\n    bool enumerate_group(state_type::iterator state, permutation::size_type index)\n    {\n      /// Nothing to enumerate - just call the visitor.\n      if (state == _state.end())\n      {\n        for (state = _state.begin(); state != _state.end(); ++state)\n        {\n          const memberlist_type& memberlist = *(state->second.first);\n          const permutation& perm = *(state->second.second);\n          for (permutation::size_type i = 0; i < perm.size(); i++)\n          {\n            _permutation._set(memberlist[i], memberlist[perm(i)]);\n          }\n        }\n\n        return visitor(_permutation);\n      }\n\n      /// Jump to next group\n      if (index >= state->second.first->size())\n      {\n        return enumerate_group(++state, 0);\n      }\n\n      /// Enumerate the current groups permutation.\n      permutation& p = *(state->second.second);\n      for (permutation::size_type i = 0; i < p.size(); i++)\n      {\n        bool found = false;\n        for (permutation::size_type j = 0; j < index; j++)\n        {\n          if (p(j) == i)\n          {\n            found = true;\n            break;\n          }\n        }\n        if (!found)\n        {\n          p._set(index, i);\n          if (!enumerate_group(state, index + 1))\n            return false;\n        }\n      }\n\n      return true;\n    }\n  };\n\n  /**\n   * Compares two permutations for equality.\n   *\n   * @param p First permutation\n   * @param q Second permutation\n   * @return true if and only if the permutations are the same\n   */\n\n  inline bool operator==(const permutation& p, const permutation& q)\n  {\n    if (p.size() != q.size())\n      return false;\n\n    for (size_t i = 0; i < p.size(); ++i)\n    {\n      if (p(i) != q(i))\n        return false;\n    }\n    return true;\n  }\n\n  /**\n   * Output operator for permutations.\n   *\n   * @param stream A given output stream\n   * @param p A given permutation\n   * @return The stream after writing the permutation\n   */\n\n  inline std::ostream& operator<<(std::ostream& stream, const permutation& p)\n  {\n    if (p.size() > 0)\n    {\n      stream << p(0);\n      for (size_t i = 1; i < p.size(); i++)\n        stream << ' ' << p(i);\n    }\n    return stream;\n  }\n\n  /**\n   * Arranges part of a given permutation such that it can be used to\n   * view a vector in a sorted way.\n   *\n   * @param permutation The given permutation to be changed\n   * @param first First index of the part\n   * @param beyond Beyond index of the part\n   * @param less Functor to compare two elements\n   */\n\n  template <class Less>\n  inline void sort(permutation& permutation, size_t first, size_t beyond, Less& less)\n  {\n    permutation::data_type& data = permutation.get_data();\n    std::sort(data.begin() + first, data.begin() + beyond, less);\n  }\n\n  /**\n   * Arranges a given permutation such that it can be used to\n   * view a vector in a sorted way.\n   *\n   * @param permutation The given permutation to be changed\n   * @param less Functor to compare two elements\n   */\n\n  template <class Less>\n  inline void sort(permutation& permutation, Less& less)\n  {\n    sort(permutation, 0, permutation.size(), less);\n  }\n\n}\n\n#endif /* PERMUTATION_HPP_ */\n", "meta": {"hexsha": "b8bb71441db3213e579e526a3ecbeb0d08c8ca6c", "size": 13841, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "unimodularity-library-1.2c/src/permutations.hpp", "max_stars_repo_name": "vios-fish/CompetitiveProgramming", "max_stars_repo_head_hexsha": "6953f024e4769791225c57ed852cb5efc03eb94b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-07-05T21:14:40.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-08T01:33:12.000Z", "max_issues_repo_path": "src/permutations.hpp", "max_issues_repo_name": "vbraun/unimodularity-library", "max_issues_repo_head_hexsha": "d329571908a84ed98713721a2fe873ad534901c8", "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/permutations.hpp", "max_forks_repo_name": "vbraun/unimodularity-library", "max_forks_repo_head_hexsha": "d329571908a84ed98713721a2fe873ad534901c8", "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": 22.5423452769, "max_line_length": 88, "alphanum_fraction": 0.5783541652, "num_tokens": 3361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.6791787056691697, "lm_q1q2_score": 0.45663337322894104}}
{"text": "#include <iostream>\r\n#include <string>\r\n#include <sstream>\r\n#include \"LFSR.hpp\"\r\n\r\n#define BOOST_TEST_DYN_LINK\r\n#define BOOST_TEST_MODULE Main\r\n#include <boost/test/unit_test.hpp>\r\n\r\n// The initial test that was in this file.\r\nBOOST_AUTO_TEST_CASE(fiveBitsTapAtTwo)\r\n{\r\n  LFSR l(\"00111\", 2);\r\n  BOOST_REQUIRE(l.step() == 1);\r\n  BOOST_REQUIRE(l.step() == 1);\r\n  BOOST_REQUIRE(l.step() == 0);\r\n  BOOST_REQUIRE(l.step() == 0);\r\n  BOOST_REQUIRE(l.step() == 0);\r\n  BOOST_REQUIRE(l.step() == 1);\r\n  BOOST_REQUIRE(l.step() == 1);\r\n  BOOST_REQUIRE(l.step() == 0);\r\n\r\n  LFSR l2(\"00111\", 2);\r\n  BOOST_REQUIRE(l2.generate(8) == 198);\r\n}\r\n\r\n\r\n// My first test. I just tested what Princeton's\r\n// website gave as examples.\r\n// In this case, they use 11 bit seeds with a tap of 8.\r\nBOOST_AUTO_TEST_CASE(PrincetonExamples)\r\n{\r\n  // The simulate step test\r\n  LFSR test(\"01101000010\", 8);\r\n\r\n  BOOST_REQUIRE(test.step() == 1);\r\n  BOOST_REQUIRE(test.step() == 1);\r\n  BOOST_REQUIRE(test.step() == 0);\r\n  BOOST_REQUIRE(test.step() == 0);\r\n  BOOST_REQUIRE(test.step() == 1);\r\n  BOOST_REQUIRE(test.step() == 0);\r\n  BOOST_REQUIRE(test.step() == 0);\r\n  BOOST_REQUIRE(test.step() == 1);\r\n  BOOST_REQUIRE(test.step() == 0);\r\n  BOOST_REQUIRE(test.step() == 0);\r\n\r\n  // The generate test from Princeton\r\n  LFSR test2(\"01101000010\", 8);\r\n  BOOST_REQUIRE(test2.generate(5) == 25);\r\n  BOOST_REQUIRE(test2.generate(5) == 4);\r\n  BOOST_REQUIRE(test2.generate(5) == 30);\r\n  BOOST_REQUIRE(test2.generate(5) == 27);\r\n  BOOST_REQUIRE(test2.generate(5) == 18);\r\n  BOOST_REQUIRE(test2.generate(5) == 26);\r\n  BOOST_REQUIRE(test2.generate(5) == 28);\r\n  BOOST_REQUIRE(test2.generate(5) == 24);\r\n  BOOST_REQUIRE(test2.generate(5) == 23);\r\n  BOOST_REQUIRE(test2.generate(5) == 29);\r\n}\r\n\r\n\r\n// A couple of tests making sure the constructor functions\r\n// as intended. This also tests the << operator as well.\r\nBOOST_AUTO_TEST_CASE(Constructor_Tests)\r\n{\r\n  LFSR test(\"001100\", 5);\r\n  std::stringstream buffer;\r\n  buffer << test;\r\n\r\n  // Make sure the constructor saves the seed correctly.\r\n  BOOST_REQUIRE(buffer.str().compare(\"001100\") == 0);\r\n\r\n  // Try a much larger seed - 30 bits for example.\r\n  LFSR test2(\"0000000111111111001010101011\", 10);\r\n  buffer.str(\"\");   // Clear the stringstream object\r\n  buffer.clear();\r\n  buffer << test2;\r\n\r\n  // Make sure the constructor saves the seed correctly.\r\n  BOOST_REQUIRE(buffer.str().compare(\"0000000111111111001010101011\") == 0);\r\n\r\n  // Now try a very small seed - 1 bit for example.\r\n  LFSR test3(\"1\", 1);\r\n  buffer.str(\"\");   // Clear the stringstream object\r\n  buffer.clear();\r\n  buffer << test3;\r\n\r\n  // Make sure the constructor saves the seed correctly.\r\n  BOOST_REQUIRE(buffer.str().compare(\"1\") == 0);\r\n}\r\n\r\n\r\n\r\n", "meta": {"hexsha": "eedbaad7c33953f78fff933b375b317606e6ba7c", "size": 2722, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Computing-IV/ps2a/test.cpp", "max_stars_repo_name": "DulceWRLD/College", "max_stars_repo_head_hexsha": "9b94868514f461c97121d72ea0855f72ca95e798", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-08-21T01:25:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-10T06:51:46.000Z", "max_issues_repo_path": "Computing-IV/ps2a/test.cpp", "max_issues_repo_name": "DulceWRLD/College", "max_issues_repo_head_hexsha": "9b94868514f461c97121d72ea0855f72ca95e798", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Computing-IV/ps2a/test.cpp", "max_forks_repo_name": "DulceWRLD/College", "max_forks_repo_head_hexsha": "9b94868514f461c97121d72ea0855f72ca95e798", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2021-03-14T22:21:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T15:30:58.000Z", "avg_line_length": 28.9574468085, "max_line_length": 76, "alphanum_fraction": 0.6576047024, "num_tokens": 748, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.4566333688629691}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#include \"tests/Unit/TestingFramework.hpp\"\n\n#include <array>\n#include <boost/optional.hpp>\n\n#include \"DataStructures/Tensor/Tensor.hpp\"\n#include \"Domain/CoordinateMaps/Affine.hpp\"\n#include \"tests/Unit/Domain/CoordinateMaps/TestMapHelpers.hpp\"\n#include \"tests/Unit/TestHelpers.hpp\"\n\nSPECTRE_TEST_CASE(\"Unit.Domain.CoordinateMaps.Affine\", \"[Domain][Unit]\") {\n  const double xA = -1.0;\n  const double xB = 1.0;\n  const double xa = -2.0;\n  const double xb = 2.0;\n\n  CoordinateMaps::Affine affine_map(xA, xB, xa, xb);\n\n  const double xi = 0.5 * (xA + xB);\n  const double x = xb * (xi - xA) / (xB - xA) + xa * (xB - xi) / (xB - xA);\n\n  const std::array<double, 1> point_A{{xA}};\n  const std::array<double, 1> point_B{{xB}};\n  const std::array<double, 1> point_a{{xa}};\n  const std::array<double, 1> point_b{{xb}};\n  const std::array<double, 1> point_xi{{xi}};\n  const std::array<double, 1> point_x{{x}};\n\n  CHECK(affine_map(point_A) == point_a);\n  CHECK(affine_map(point_B) == point_b);\n  CHECK(affine_map(point_xi) == point_x);\n\n  CHECK(affine_map.inverse(point_a).get() == point_A);\n  CHECK(affine_map.inverse(point_b).get() == point_B);\n  CHECK(affine_map.inverse(point_x).get() == point_xi);\n\n  const double inv_jacobian_00 = (xB - xA) / (xb - xa);\n\n  CHECK((get<0, 0>(affine_map.inv_jacobian(point_A))) == inv_jacobian_00);\n  CHECK((get<0, 0>(affine_map.inv_jacobian(point_B))) == inv_jacobian_00);\n  CHECK((get<0, 0>(affine_map.inv_jacobian(point_xi))) == inv_jacobian_00);\n\n  const double jacobian_00 = (xb - xa) / (xB - xA);\n  CHECK((get<0, 0>(affine_map.jacobian(point_A))) == jacobian_00);\n  CHECK((get<0, 0>(affine_map.jacobian(point_B))) == jacobian_00);\n  CHECK((get<0, 0>(affine_map.jacobian(point_xi))) == jacobian_00);\n\n  // Check inequivalence operator\n  CHECK_FALSE(affine_map != affine_map);\n  test_serialization(affine_map);\n\n  test_coordinate_map_argument_types(affine_map, point_xi);\n}\n", "meta": {"hexsha": "f6c998e27178ac321f293a91469e60e277acef97", "size": 1973, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/Unit/Domain/CoordinateMaps/Test_Affine.cpp", "max_stars_repo_name": "marissawalker/spectre", "max_stars_repo_head_hexsha": "afc8205e2f697de5e8e4f05e881499e05c9fd8a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/Unit/Domain/CoordinateMaps/Test_Affine.cpp", "max_issues_repo_name": "marissawalker/spectre", "max_issues_repo_head_hexsha": "afc8205e2f697de5e8e4f05e881499e05c9fd8a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/Unit/Domain/CoordinateMaps/Test_Affine.cpp", "max_forks_repo_name": "marissawalker/spectre", "max_forks_repo_head_hexsha": "afc8205e2f697de5e8e4f05e881499e05c9fd8a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.6140350877, "max_line_length": 75, "alphanum_fraction": 0.6923466802, "num_tokens": 631, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.4566333644038181}}
{"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__DIFF_HPP_\n#define SMOOTH__DIFF_HPP_\n\n/**\n * @file\n * @brief Differentiation on Lie groups.\n */\n\n#include <Eigen/Core>\n#include <type_traits>\n\n#include \"concepts.hpp\"\n#include \"internal/utils.hpp\"\n#include \"tn.hpp\"\n\nnamespace smooth {\n\n/**\n * @brief Grouping of function arguments.\n *\n * A tuple of references is created from the input arguments,\n * which is the expected format in e.g. dr() and minimize().\n */\ntemplate<typename... _Args>\nauto wrt(_Args &&... args)\n{\n  return std::forward_as_tuple(std::forward<_Args>(args)...);\n}\n\n// differentiation module\nnamespace diff {\nnamespace detail {\n\n/**\n * @brief Numerical differentiation in tangent space.\n *\n * @param f function to differentiate\n * @param x reference tuple of function arguments\n * @return \\p std::pair containing value and right derivative: \\f$(f(x), \\mathrm{d}^r f_x)\\f$\n *\n * @note All arguments in x as well as the return type \\f$f(x)\\f$ must satisfy\n * the Manifold concept.\n */\ntemplate<typename _F, typename _Wrt>\nauto dr_numerical(_F && f, _Wrt && x)\n{\n  using Result = typename decltype(std::apply(f, x))::PlainObject;\n  using Scalar = typename Result::Scalar;\n\n  // arguments are modified below, so we create a copy of those that come in as const\n  auto x_nc = utils::tuple_copy_if_const(std::forward<_Wrt>(x));\n\n  // static sizes\n  static constexpr Eigen::Index Nx = utils::tuple_dof<std::decay_t<_Wrt>>::value;\n  static constexpr Eigen::Index Ny = Result::SizeAtCompileTime;\n\n  const Scalar eps = std::sqrt(Eigen::NumTraits<Scalar>::epsilon());\n\n  const Result val = std::apply(f, x_nc);\n\n  // dynamic sizes\n  Eigen::Index nx = std::apply([](auto &&... args) { return (args.size() + ...); }, x_nc);\n  Eigen::Index ny = val.size();\n\n  // output variable\n  Eigen::Matrix<Scalar, Ny, Nx> jac(ny, nx);\n\n  Eigen::Index index_pos = 0;\n\n  utils::static_for<std::tuple_size_v<std::decay_t<_Wrt>>>([&](auto i) {\n    static constexpr Eigen::Index Nx_j =\n      std::decay_t<std::tuple_element_t<i, std::decay_t<_Wrt>>>::SizeAtCompileTime;\n    auto & w       = std::get<i>(x_nc);\n    const int nx_j = w.size();\n\n    using W = std::decay_t<decltype(w)>;\n\n    for (auto j = 0; j != nx_j; ++j) {\n      Scalar eps_j = eps;\n      if constexpr (std::is_base_of_v<Eigen::MatrixBase<W>, W>) {\n        // scale step size if we are in Rn\n        eps_j *= abs(w[j]);\n        if (eps_j == 0.) { eps_j = eps; }\n      } else if constexpr (std::is_base_of_v<smooth::TnBase<W>, W>) {\n        // or Tn\n        eps_j *= abs(w.rn()[j]);\n        if (eps_j == 0.) { eps_j = eps; }\n      }\n      // const cast needed in case argument is const (value is restored two lines below)\n      w += (eps_j * Eigen::Matrix<Scalar, Nx_j, 1>::Unit(nx_j, j));\n      jac.col(index_pos + j) = (std::apply(f, x_nc) - val) / eps_j;\n      w += (-eps_j * Eigen::Matrix<Scalar, Nx_j, 1>::Unit(nx_j, j));\n    }\n    index_pos += nx_j;\n  });\n\n  return std::make_pair(val, jac);\n}\n\n}  // namespace detail\n\n/**\n * @enum smooth::diff::Type\n * @brief Differentiation methods\n */\nenum class Type {\n  NUMERICAL,  ///< Numerical (forward) derivatives\n  AUTODIFF,   ///< Uses the autodiff (https://autodiff.github.io) library; requires  \\p\n              ///< compat/autodiff.hpp\n  CERES,      ///< Uses the Ceres (http://ceres-solver.org) built-in autodiff; requires \\p\n              ///< compat/ceres.hpp\n  ANALYTIC,   ///< Hand-coded derivative, requires that function returns \\p std::pair \\f$(f(x),\n              ///< \\mathrm{d}^r f_x) \\f$\n  DEFAULT     ///< Automatically select type based on availability\n};\n\nstatic constexpr Type DefaultType =\n#ifdef SMOOTH_DIFF_AUTODIFF\n  Type::AUTODIFF;\n#elif defined SMOOTH_DIFF_CERES\n  Type::CERES;\n#else\n  Type::NUMERICAL;\n#endif\n\n/**\n * @brief Differentiation in tangent space\n *\n * @tparam dm differentiation method to use\n *\n * @param f function to differentiate\n * @param x reference tuple of function arguments\n * @return \\p std::pair containing value and right derivative: \\f$(f(x), \\mathrm{d}^r f_x)\\f$\n *\n * @note All arguments in x as well as the return type \\f$f(x)\\f$ must satisfy\n * the Manifold concept.\n */\ntemplate<Type dm, typename _F, typename _Wrt>\nauto dr(_F && f, _Wrt && x)\n{\n  if constexpr (dm == Type::NUMERICAL) {\n    return detail::dr_numerical(std::forward<_F>(f), std::forward<_Wrt>(x));\n  } else if constexpr (dm == Type::AUTODIFF) {\n#ifdef SMOOTH_DIFF_AUTODIFF\n    return dr_autodiff(std::forward<_F>(f), std::forward<_Wrt>(x));\n#else\n    static_assert(dm != Type::AUTODIFF, \"compat/autodiff.hpp header not included\");\n#endif\n  } else if constexpr (dm == Type::CERES) {\n#ifdef SMOOTH_DIFF_CERES\n    return dr_ceres(std::forward<_F>(f), std::forward<_Wrt>(x));\n#else\n    static_assert(dm != Type::CERES, \"compat/ceres.hpp header not included\");\n#endif\n  } else if constexpr (dm == Type::ANALYTIC) {\n    return std::apply(f, std::forward<_Wrt>(x));\n  } else if constexpr (dm == Type::DEFAULT) {\n    return dr<DefaultType>(std::forward<_F>(f), std::forward<_Wrt>(x));\n  }\n}\n\n/**\n * @brief Differentiation in tangent space using default method\n *\n * @param f function to differentiate\n * @param x reference tuple of function arguments\n * @return \\p std::pair containing value and right derivative: \\f$(f(x), \\mathrm{d}^r f_x)\\f$\n *\n * @note All arguments in x as well as the return type \\f$f(x)\\f$ must satisfy\n * the Manifold concept.\n */\ntemplate<typename _F, typename _Wrt>\nauto dr(_F && f, _Wrt && x)\n{\n  return dr<Type::DEFAULT>(std::forward<_F>(f), std::forward<_Wrt>(x));\n}\n\n}  // namespace diff\n}  // namespace smooth\n\n#endif  // SMOOTH__DIFF_HPP_\n", "meta": {"hexsha": "c2f29110a7bbcba973c85803507a0298dbfa6e1e", "size": 6817, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/smooth/diff.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/diff.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/diff.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": 32.9323671498, "max_line_length": 95, "alphanum_fraction": 0.6728766319, "num_tokens": 1850, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.4566333644038181}}
{"text": "#include <chrono>\n#include <iostream>\n#include <thread>\n\n#include <smart_rate/simple_control.h>\n#include <smart_rate/smart_rate.h>\n\n#include <dlib/rand.h>\n#include <dlib/svm.h>\n\nclass KrlsRegression {\npublic:\n  KrlsRegression() : reg_(KernelType(0.1), 0.001){};\n\n  void train(double x, double y) {\n    SampleType m;\n    m(0) = x;\n    reg_.train(m, y);\n  }\n\n  double eval(double x) const {\n    SampleType m;\n    m(0) = x;\n    return reg_(m);\n  }\n\nprivate:\n  using SampleType = dlib::matrix<double, 1, 1>;\n  using KernelType = dlib::radial_basis_kernel<SampleType>;\n\n  dlib::krls<KernelType> reg_;\n};\n\nint main(int argc, char *argv[]) {\n  auto rate = SmartRate<NoControl>(1000);\n  using namespace std::chrono_literals;\n  using std::chrono::high_resolution_clock;\n  auto prev = high_resolution_clock::now();\n  size_t i = 0;\n\n  dlib::rand rng;\n  KrlsRegression reg;\n  while (true) {\n\n    // do something...\n    std::this_thread::sleep_for(100us);\n\n    rate.sleep();\n\n    double r_c = rate.getCommandRate();\n    double r = rate.getRealRate();\n\n    if (i < 5000) {\n      std::cout << \"i = \" << i << std::endl;\n      reg.train(r, r_c);\n      rate.setRate(rate.getDesiredRate() + rng.get_double_in_range(-200, 200));\n\n    } else {\n      double opt_rate = reg.eval(1000);\n      std::cout << \"Sleep rate should be set to: \" << opt_rate << std::endl;\n      reg.train(r, r_c);\n      rate.setRate(opt_rate);\n    }\n    i++;\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "f5823caec35a4f5d54c809409f786044fa73506a", "size": 1429, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp_practices/smart_rate/src/krls_rate_example.cpp", "max_stars_repo_name": "Maverobot/cpp_playground", "max_stars_repo_head_hexsha": "c06ab8a0e7004a6cd5897695a7c00b7f4aee26b0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-09-17T00:57:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-02T07:48:45.000Z", "max_issues_repo_path": "cpp_practices/smart_rate/src/krls_rate_example.cpp", "max_issues_repo_name": "Maverobot/cpp_playground", "max_issues_repo_head_hexsha": "c06ab8a0e7004a6cd5897695a7c00b7f4aee26b0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 58.0, "max_issues_repo_issues_event_min_datetime": "2019-10-31T10:45:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-21T16:19:11.000Z", "max_forks_repo_path": "cpp_practices/smart_rate/src/krls_rate_example.cpp", "max_forks_repo_name": "Maverobot/cpp_playground", "max_forks_repo_head_hexsha": "c06ab8a0e7004a6cd5897695a7c00b7f4aee26b0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-09-28T11:49:36.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-04T04:08:58.000Z", "avg_line_length": 20.7101449275, "max_line_length": 79, "alphanum_fraction": 0.6249125262, "num_tokens": 425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.4566043707219153}}
{"text": "\n#ifndef SCHNACKENBERGODESYSTEM_HPP_\n#define SCHNACKENBERGODESYSTEM_HPP_\n\n#include \"ChasteSerialization.hpp\"\n#include <boost/serialization/base_object.hpp>\n\n#include <cmath>\n#include <iostream>\n\n#include \"AbstractOdeSystem.hpp\"\n\nclass SchnackenbergOdeSystem : public AbstractOdeSystem\n{\n\npublic:\n\n    /**\n     * Default constructor.\n     *\n     * @param stateVariables optional initial conditions for state variables (only used in archiving)\n     */\n    SchnackenbergOdeSystem(std::vector<double> stateVariables=std::vector<double>());\n\n    /**\n     * Destructor.\n     */\n    ~SchnackenbergOdeSystem();\n\n    /**\n     * Compute the RHS of the  Collier et al. 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  Collier et al. system of equations).\n     */\n    void EvaluateYDerivatives(double time, const std::vector<double>& rY, std::vector<double>& rDY);\n};\n\n\n#endif \n", "meta": {"hexsha": "9663a5b3a1ea96b9726737a54609baceab9b9c8d", "size": 1213, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/SchnackenbergOdeSystem.hpp", "max_stars_repo_name": "OSS-Lab/ChemChaste", "max_stars_repo_head_hexsha": "d32c36afa1cd870512fee3cba0753d5c6faf8109", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/SchnackenbergOdeSystem.hpp", "max_issues_repo_name": "OSS-Lab/ChemChaste", "max_issues_repo_head_hexsha": "d32c36afa1cd870512fee3cba0753d5c6faf8109", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SchnackenbergOdeSystem.hpp", "max_forks_repo_name": "OSS-Lab/ChemChaste", "max_forks_repo_head_hexsha": "d32c36afa1cd870512fee3cba0753d5c6faf8109", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9555555556, "max_line_length": 103, "alphanum_fraction": 0.6859027205, "num_tokens": 300, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6825737473266735, "lm_q2_score": 0.6688802735722128, "lm_q1q2_score": 0.45656011484507586}}
{"text": "//  (C) Copyright Daniel Egloff 2006.\r\n//  Use, modification and distribution are subject to the\r\n//  Boost Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#include <boost/test/unit_test.hpp>\r\n#include <boost/time_series/sparse_series.hpp>\r\n#include <boost/time_series/piecewise_constant_series.hpp>\r\n#include <boost/time_series/ordered_inserter.hpp>\r\n#include <boost/time_series/numeric/numeric.hpp>\r\n#include <boost/time_series/numeric/piecewise_surface_sample.hpp>\r\n\r\nusing namespace boost;\r\nusing namespace unit_test;\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// test_piecewise_surface_sample\r\n//\r\nvoid test_piecewise_surface_sample()\r\n{\r\n    namespace bt = boost::time_series;\r\n    typedef bt::piecewise_constant_series<double>      series_type;\r\n    typedef bt::piecewise_constant_series<series_type> surface_type;\r\n    \r\n    series_type base;\r\n    bt::make_ordered_inserter(base)\r\n        (1, -bt::inf, 10)\r\n        (2, 10, 20)   \r\n        (3, 20, 30)   \r\n        (4, 30, 40)   \r\n        (5, 40, 50)   \r\n    .commit();    \r\n    \r\n    surface_type surface;\r\n    bt::make_ordered_inserter(surface)\r\n        (base * -1, -bt::inf, 0)\r\n        (base * 1, 0, 10)\r\n        (base * 2, 10, 20)\r\n        (base * 3, 20, 30)\r\n        (base * 4, 30, 40)\r\n    .commit();\r\n    \r\n    std::ptrdiff_t x[] = { -10, 15, 35 };\r\n    std::ptrdiff_t y[] = { 0, 25, 45 };\r\n    \r\n    surface_type result = bt::piecewise_surface_sample(surface, x, y);\r\n    \r\n    series_type expected_base;\r\n    bt::make_ordered_inserter(expected_base)\r\n        (1, -bt::inf, 25)\r\n        (3, 25, 45)   \r\n        (5, 45, bt::inf)   \r\n    .commit();    \r\n    \r\n    surface_type expected_result;\r\n    bt::make_ordered_inserter(expected_result)\r\n        (expected_base * -1, -bt::inf, 15)\r\n        (expected_base * 2, 15, 35)\r\n        (expected_base * 4, 35, bt::inf)\r\n    .commit();\r\n       \r\n    BOOST_CHECK_EQUAL(result, expected_result);  \r\n}\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// init_unit_test_suite\r\n//\r\ntest_suite* init_unit_test_suite( int argc, char* argv[] )\r\n{\r\n    test_suite *test = BOOST_TEST_SUITE(\"piecewise_surface_sample test\");\r\n\r\n    test->add(BOOST_TEST_CASE(&test_piecewise_surface_sample));\r\n\r\n    return test;\r\n}\r\n", "meta": {"hexsha": "74503884293ad74e25632ff82372853297d54c5a", "size": 2369, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/time_series/test/piecewise_surface_sample.cpp", "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": "libs/time_series/test/piecewise_surface_sample.cpp", "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": "libs/time_series/test/piecewise_surface_sample.cpp", "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": 31.1710526316, "max_line_length": 80, "alphanum_fraction": 0.5795694386, "num_tokens": 608, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802735722128, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.4565601105259991}}
{"text": "#include \"testsuite.h\"\n#include <blitz/array.h>\n\nBZ_USING_NAMESPACE(blitz)\n\nint main()\n{\n    Array<double,3> geo(5,10,15);\n    Array<double,3> bio;\n        \n    geo = -1.0;\n        \n    bio.resize(geo.shape());\n    BZTEST(geo.extent(0) == bio.extent(0)\n        && geo.extent(1) == bio.extent(1)\n        && geo.extent(2) == bio.extent(2));\n\n    bio = geo;\n    return 0;\n}\n\n", "meta": {"hexsha": "61b1b1688b147f344e99069afee697baf9cabf39", "size": 372, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depspawn-blitz-0.10/testsuite/Ulisses-Mello-1.cpp", "max_stars_repo_name": "fraguela/depspawn", "max_stars_repo_head_hexsha": "b5760f4c0d38a1b245ee5274e2ccc5c5fe2d3d45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-04-12T11:05:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T11:10:27.000Z", "max_issues_repo_path": "ibtk/third_party/blitz-0.10/testsuite/Ulisses-Mello-1.cpp", "max_issues_repo_name": "MSV-Project/IBAMR", "max_issues_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ibtk/third_party/blitz-0.10/testsuite/Ulisses-Mello-1.cpp", "max_forks_repo_name": "MSV-Project/IBAMR", "max_forks_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_forks_repo_licenses": ["BSD-3-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.9090909091, "max_line_length": 43, "alphanum_fraction": 0.5403225806, "num_tokens": 117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.45656009719612706}}
{"text": "// Copyright 2014, Max Planck Society.\r\n// Distributed under the BSD 3-Clause license.\r\n// (See accompanying file LICENSE.txt or copy at\r\n// http://opensource.org/licenses/BSD-3-Clause)\r\n\r\n#ifndef GRASSMANN_AVERAGES_PCA_UTILITIES_HPP__\r\n#define GRASSMANN_AVERAGES_PCA_UTILITIES_HPP__\r\n\r\n/*!@file\r\n * Grassmann averages for robust PCA, companion functions.\r\n *\r\n * This file contains some utility function for multithreading, norm computation, convergence check\r\n * \r\n */\r\n\r\n\r\n#include <boost/numeric/conversion/bounds.hpp>\r\n\r\n\r\n#include <boost/asio/io_service.hpp>\r\n#include <boost/thread/thread.hpp>\r\n#include <boost/thread/recursive_mutex.hpp>\r\n\r\n\r\n#include <boost/random/uniform_real_distribution.hpp>\r\n#include <boost/random/uniform_int_distribution.hpp>\r\n#include <boost/random/mersenne_twister.hpp>\r\n\r\n#include <boost/numeric/ublas/vector_expression.hpp>\r\n#include <boost/numeric/ublas/vector.hpp>\r\n\r\n#include <numeric>\r\n\r\n\r\n// lock free queue, several producers, one consumer\r\n//#include <boost/lockfree/queue.hpp>\r\n\r\nnamespace grassmann_averages_pca\r\n{\r\n\r\n  //! A callback class for monitoring the advance of the algorithm\r\n  //!\r\n  //! All calls are made in the main thread: there is no thread-safety issue.\r\n  template <class data_t>\r\n  struct grassmann_trivial_callback\r\n  {\r\n\r\n    //! Called to provide important messages/logs\r\n    void log_error_message(const char* message) const\r\n    {\r\n      std::cout << message << std::endl;\r\n    }\r\n\r\n    //! This is called after centering the data in order to keep track \r\n    //! of the mean of the dataset\r\n    void signal_mean(const data_t& mean) const\r\n    {}\r\n\r\n    //! Called after the computation of the PCA\r\n    void signal_pca(const data_t& mean,\r\n                    size_t current_eigenvector_dimension) const\r\n    {}\r\n\r\n    //! Called each time a new eigenvector is computed\r\n    void signal_eigenvector(const data_t& current_eigenvector, \r\n                            size_t current_eigenvector_dimension) const\r\n    {}\r\n\r\n    //! Called at every step of the algorithm, at the end of the step\r\n    void signal_intermediate_result(\r\n      const data_t& current_eigenvector_state, \r\n      size_t current_eigenvector_dimension,\r\n      size_t current_iteration_step) const\r\n    {}\r\n\r\n  };\r\n\r\n\r\n  namespace details\r\n  {\r\n \r\n    //! Wrapper object for infinity/max @f$\\ell_\\infty@f$ norm.\r\n    struct norm_infinity\r\n    {\r\n      template <class vector_t>\r\n      double operator()(vector_t const& v) const\r\n      {\r\n        return boost::numeric::ublas::norm_inf(v);\r\n      }\r\n    };\r\n\r\n\r\n    //! Returns the square of the @f$\\ell_2@f$ norm.\r\n    struct norm_ell2_square\r\n    {\r\n      template <class vector_t>\r\n      double operator()(vector_t const& v) const\r\n      {\r\n        double acc(0);\r\n        for(typename vector_t::const_iterator it(v.begin()), ite(v.end());\r\n            it < ite;\r\n            ++it)\r\n        {\r\n          typename vector_t::const_reference v(*it);\r\n          acc += v * v;\r\n        }\r\n        return acc;\r\n      }\r\n    };\r\n\r\n    //! Returns the @f$\\ell_2@f$ norm of a vector.\r\n    struct norm2\r\n    {\r\n      typedef double result_type;\r\n      norm_ell2_square op;\r\n      template <class vector_t>\r\n      result_type operator()(vector_t const& v) const\r\n      {\r\n        return std::sqrt(op(v));\r\n      }\r\n    };\r\n    \r\n\r\n\r\n\r\n    /*!@brief Gram Schmidt orthonormalisation of a collection of vectors.\r\n     * @tparam it_t iterator on the collection of vectors. Should model a forward input iterator.\r\n     * @tparam norm_t type of the norm operator.\r\n     * \r\n     * @param it beginning of the collection of vectors\r\n     * @param ite end of the collection of vectors\r\n     * @param start first element of the collection to be orthonormalized. start should be inside the range given by it and ite. \r\n     * @param norm_op the norm used to normalise the vectors\r\n     */\r\n    template <class it_t, class norm_t>\r\n    bool gram_schmidt_orthonormalisation(it_t it, it_t ite, it_t start, norm_t const &norm_op)\r\n    {\r\n      \r\n      if(start == it)\r\n      {\r\n        *start *= typename it_t::value_type::value_type(1./norm_op(*start));\r\n        ++start;\r\n      }\r\n\r\n      it_t previous(start);\r\n              \r\n      for(; start != ite; ++previous, ++start)\r\n      {\r\n        typename it_t::reference current = *start;\r\n        for(it_t it_orthonormalised_element(it); it_orthonormalised_element < previous; ++it_orthonormalised_element)\r\n        {\r\n          current -= boost::numeric::ublas::inner_prod(current, *it_orthonormalised_element) * (*it_orthonormalised_element);\r\n        }\r\n        current *= typename it_t::value_type::value_type(1./norm_op(current));\r\n              \r\n      }\r\n      return true;\r\n    }\r\n\r\n\r\n    /*!@brief Computes the mean of a data set after having removed the lower and upper k first elements.\r\n     *\r\n     * This function computes @f[\\sum_{k \\leq i < N-k} p_{o(i)}@f] where \r\n     * - @f$p@f$ is the data set of size @f$N@f$, and @f$p_i@f$ is its ith element\r\n     * - @f$o@f$ is a function ordering the data set: @f$\\forall i, p_{o(i)} \\leq p_{o(i+1)}, 0 \\leq i < N @f$\r\n\r\n     * @tparam T type of the data set. All internal accumulations will be performed with this type. T should not be const as\r\n     *         the data set will be modified in place.\r\n     *\r\n     * @param p_data the data set composed of nb_total_elements of type T. \r\n     * @param nb_total_elements number of elements of the data set\r\n     * @param k_first_last number of elements to remove from the lower and upper distributions.\r\n     *\r\n     * @pre @f$ \\text{k_first_last} \\leq \\frac{\\text{nb_total_elements}}{2}@f$\r\n     */\r\n    template <class T>\r\n    T compute_mean_within_bounds(T *p_data, size_t nb_total_elements, size_t k_first_last)\r\n    {\r\n      if(k_first_last < nb_total_elements / 2)\r\n      {\r\n        std::nth_element(p_data, p_data + k_first_last, p_data + nb_total_elements);\r\n        std::nth_element(p_data + k_first_last+1, p_data + nb_total_elements - k_first_last-1, p_data + nb_total_elements);\r\n        T acc = std::accumulate(p_data + k_first_last, p_data + nb_total_elements - k_first_last, T(0));\r\n          \r\n        return acc / (nb_total_elements - 2*k_first_last);\r\n      }\r\n      else\r\n      {\r\n        assert(k_first_last == nb_total_elements / 2);\r\n        std::nth_element(p_data, p_data + k_first_last, p_data + nb_total_elements);\r\n          \r\n        if(nb_total_elements & 1)\r\n        {\r\n          return *(p_data + k_first_last);\r\n        }\r\n        else\r\n        {\r\n          return (*(p_data + k_first_last) + *std::max_element(p_data, p_data + k_first_last)) / 2;\r\n        }\r\n      }\r\n    }\r\n\r\n\r\n\r\n\r\n    /*!@brief Checks the convergence of a sequence.\r\n     *\r\n     * @tparam data_t: type of the data.\r\n     * @tparam norm_t: the norm used in order to compare the closeness of two successive results.\r\n     *\r\n     * The type of the data should meet the following requirements:\r\n     * - data_t should be copy constructible and assignable.\r\n     * - operator- is defined between two instances of data_t and return a type compatible with the input of the norm operator (usually a data_t).\r\n     *\r\n     * The convergence is assumed as soon as the norm between two subsequent states is less than a certain @f$\\epsilon@f$, that is\r\n     * the functor returns true if:\r\n     * @f[\\left\\|v_t - v_{t-1}\\right\\| < \\epsilon@f]\r\n     *\r\n     * @note Once the convergence is reached, the internal states are not updated anymore (the calling algorithm is supposed to stop).\r\n     */\r\n    template <class data_t, class norm_t = norm_infinity>\r\n    struct convergence_check\r\n    {\r\n      //! The amount of change below which the sequence is considered as having reached a steady point.\r\n      const double epsilon;\r\n\r\n      //! Holds an instance of the norm used for checking the convergence.\r\n      norm_t norm_comparison;\r\n\r\n      //! The previous value\r\n      data_t previous_state;\r\n\r\n      //! Initialise the instance with the initial state of the vector.\r\n      convergence_check(data_t const& current_state, double epsilon_ = 1E-5) : \r\n        epsilon(epsilon_), \r\n        previous_state(current_state)\r\n      {}\r\n\r\n      //! Returns true on convergence.\r\n      bool operator()(data_t const& current_state)\r\n      {\r\n        bool ret = norm_comparison(current_state - previous_state) < epsilon;\r\n        if(!ret)\r\n        {\r\n          previous_state = current_state;\r\n        }\r\n        return ret;\r\n      }\r\n\r\n    };\r\n\r\n\r\n    // some issues with the random number generator\r\n    const double fVeryBigButStillComputable = 1E10;\r\n    const double fVerySmallButStillComputable = -1E10;\r\n\r\n\r\n    /*!@brief Used to initialize the initial guess to some random data.\r\n     *\r\n     * @tparam data_t the type of the data returned. It should model a vector:\r\n     *  - default, copy constructible and constructible with a size\r\n     *  - has a member @c size returning a value of type @c data_t::Size_type\r\n     *  - has a field @c data_t::Value_type\r\n     */\r\n    template <\r\n      class data_t, \r\n      class random_distribution_t = \r\n        typename boost::mpl::if_<\r\n          boost::is_floating_point<typename data_t::value_type>,\r\n          boost::random::uniform_real_distribution<typename data_t::value_type>,\r\n          boost::random::uniform_int_distribution<typename data_t::value_type>\r\n        >::type,\r\n      class random_number_generator_t = boost::random::mt19937\r\n    >\r\n    struct random_data_generator\r\n    {\r\n      typedef typename data_t::value_type value_type;\r\n      mutable random_number_generator_t rng;\r\n      value_type min_bound;\r\n      value_type max_bound;\r\n    \r\n      //! Default construction\r\n      random_data_generator(\r\n        value_type min_value_ = boost::numeric::bounds<value_type>::lowest(),\r\n        value_type max_value_ = boost::numeric::bounds<value_type>::highest()) : \r\n        rng(), \r\n        min_bound(min_value_), \r\n        max_bound(max_value_)\r\n      {}\r\n\r\n      //! Constructs from the specified seeded random number generator.\r\n      random_data_generator(\r\n        random_number_generator_t const &r,\r\n        value_type min_value_ = boost::numeric::bounds<value_type>::lowest(),\r\n        value_type max_value_ = boost::numeric::bounds<value_type>::highest()) : \r\n        rng(r),\r\n        min_bound(min_value_), \r\n        max_bound(max_value_)\r\n      {}\r\n\r\n\r\n      data_t operator()(const data_t& v) const\r\n      {\r\n        data_t out(v.size());\r\n        random_distribution_t dist(min_bound, max_bound);\r\n        for(typename data_t::size_type i(0), j(v.size()); i < j; i++)\r\n        {\r\n          out[i] = dist(rng);\r\n        }\r\n        return out;\r\n      }\r\n    };\r\n\r\n\r\n    //! @namespace\r\n    namespace threading\r\n    {\r\n\r\n\r\n      //! Ensures the proper stop of the processing pool and the finalisation of all threads.\r\n      struct safe_stop\r\n      {\r\n      private:\r\n        boost::asio::io_service& io_service;\r\n        boost::thread_group& thread_group;\r\n\r\n      public:\r\n        safe_stop(boost::asio::io_service& ios, boost::thread_group& tg) : io_service(ios), thread_group(tg)\r\n        {}\r\n\r\n        ~safe_stop()\r\n        {\r\n          io_service.stop();\r\n          thread_group.join_all();\r\n        }\r\n      };\r\n\r\n\r\n      //! @brief Helper structure for managing additions on standard uBlas vectors.\r\n      //! \r\n      //! This class is intended to be used with asynchronous_results_merger. It just adds an update to the current state.\r\n      //! @tparam data_t type of the vectors. It is supposed that data_t implements in-place addition (@c data_t::operator+=).\r\n      template <class data_t>\r\n      struct merger_addition\r\n      {\r\n        bool operator()(data_t &current_state, data_t const& update_value) const\r\n        {\r\n          current_state += update_value;\r\n          return true;\r\n        }\r\n      };\r\n\r\n\r\n      //! Helper structure for managing initialisations of standard uBlas vectors.\r\n      //! \r\n      //! This class is intended to be used with asynchronous_results_merger.\r\n      //! @tparam data_t type of the vectors\r\n      //! @note This implementation supposes that the type is compatible with boost::numeric::ublas::vector\r\n      template <class data_t>\r\n      struct initialisation_vector_specific_dimension\r\n      {\r\n      private:\r\n        const size_t data_dimension;                    //!< Dimension of the vectors\r\n        typedef typename data_t::value_type scalar_t;   //<! Scalar type\r\n\r\n      public:\r\n        //! Initialise the instance with the dimension of the data. \r\n        //! The dimension is fixed. \r\n        initialisation_vector_specific_dimension(size_t dimension) : data_dimension(dimension)\r\n        {}\r\n\r\n        //! Initialise the current state a null (0) vector of the dimension guiven at construction.\r\n        bool operator()(data_t & current_state) const\r\n        {\r\n          current_state = boost::numeric::ublas::scalar_vector<scalar_t>(data_dimension, 0);\r\n          return true;\r\n        }\r\n      };\r\n\r\n\r\n\r\n\r\n      /*!@brief Merges the result of all workers and signals the results to the main thread.\r\n       *\r\n       * The purpose of this class is to gather the computation results coming from several threads into one unique result seen by the main calling thread. \r\n       * Each thread computes a partial update of the final result. These partial update are signalled to this instance via @c asynchronous_results_merger::update (thread safe). \r\n       * These updates are gathered/merged to the final result through the \"merger\" instance (of type @c merger_type) in a thread safe manner.\r\n       * The number of updates is also signalled to the main thread via a call to @c asynchronous_results_merger::notify. The main thread supposes the computation over/in sync if it received\r\n       * an amount of notification through the @c asynchronous_results_merger::wait function.\r\n       *\r\n       * @tparam result_type_ the type of the final result.\r\n       * @tparam merger_type the type of the merger. The merger should be a callable with two arguments: result_type_ and update_element_\r\n       * @tparam init_result_type the type of the initialiser. The initialiser should be a callable with one argument of type result_type_.\r\n       * @tparam update_element_ the type of the update. These updates are provided by the several workers to this merger. \r\n       *\r\n       * @note This implementation supposes that the pointers to the update elements remain after the call to @c asynchronous_results_merger::notify. This is because\r\n       * the implementation tries to avoid any \"long\" or time consuming lock. If the merge cannot be performed in the asynchronous_results_merger::update call itself,\r\n       * then the update element is queued and the merge is performed in the main calling thread (the wait function). \r\n       */\r\n      template <class result_type_, class merger_type, class init_result_type, class update_element_ = result_type_>\r\n      struct asynchronous_results_merger : boost::noncopyable\r\n      {\r\n      public:\r\n\r\n        typedef result_type_ result_type;         //!< The type returned by asynchronous_results_merger::get_merged_result\r\n        typedef update_element_ update_element;   //!< The type used for the updates.\r\n\r\n      protected:\r\n        typedef boost::recursive_mutex mutex_t;     //!< Type of the mutex. This one is re-entrant/recursive in order to allow the same thread locking it several times.\r\n        typedef boost::lock_guard<mutex_t> lock_t;  //!< Exclusive lock\r\n\r\n        //! Mutex for critical sections. \r\n        //!@note This mutex is re-entrant.\r\n        mutable mutex_t internal_mutex;\r\n\r\n        //! Holds the current value of the merge.\r\n        //! This variable is constantly updated as chunk processed finish. \r\n        result_type current_value;                  \r\n\r\n        //! Holds the instance of the class responsible for merging new values (updates) to the\r\n        //! current instance (current_value).\r\n        merger_type merger_instance;\r\n\r\n        //! Holds the instance of the class responsible for initialising the current value to\r\n        //! an initial state (before any merge arrives).\r\n        init_result_type initialisation_instance;\r\n\r\n        //! Number of updates after the initialisation\r\n        volatile int nb_updates;\r\n\r\n        //! Thread synchronisation (event sent after an update, for counting).\r\n        boost::condition_variable_any condition_;\r\n\r\n        std::list<update_element const*> lf_queue;\r\n        //boost::lockfree::queue<update_element const*> lf_queue;\r\n\r\n      public:\r\n\r\n        /*!Constructor\r\n         *\r\n         * @param initialisation_instance_ an instance of the class initialising the current state.\r\n         */\r\n        asynchronous_results_merger(init_result_type const &initialisation_instance_) : \r\n          initialisation_instance(initialisation_instance_),\r\n          nb_updates(0),\r\n          lf_queue()\r\n        {}\r\n\r\n        //! Initializes the internal states\r\n        void init()\r\n        {\r\n          init_results();\r\n          init_notifications();\r\n        }\r\n\r\n        //! Initialises the internal state of the accumulator\r\n        void init_results()\r\n        {\r\n          initialisation_instance(current_value);\r\n        }\r\n\r\n\r\n        //! Initialises the number of notifications.\r\n        //! Also called by init.\r\n        void init_notifications()\r\n        {\r\n          nb_updates = 0;\r\n        }\r\n\r\n        /*! Receives the update element from each worker.\r\n         * \r\n         * The update element is passed to the merger in order to create an updated value of the internal result.\r\n         * @note The call is thread safe.\r\n         */\r\n        void update(update_element const* updated_value)\r\n        {\r\n          boost::unique_lock<mutex_t> lock(internal_mutex);//, boost::try_to_lock);\r\n\r\n          if(lock.owns_lock())\r\n          {\r\n            merger_instance(current_value, *updated_value);\r\n            while(!lf_queue.empty())\r\n            {\r\n              updated_value = lf_queue.back();\r\n              lf_queue.pop_back();\r\n              merger_instance(current_value, *updated_value);\r\n            }\r\n          }\r\n          else\r\n          {\r\n            //while(!lf_queue.push(updated_value))\r\n            //  ;\r\n          }\r\n        }\r\n\r\n\r\n\r\n        /*! Function receiving the update notification.\r\n         * \r\n         *  @note The call is thread safe.\r\n         */\r\n        void notify()\r\n        {\r\n          lock_t guard(internal_mutex);\r\n          ++nb_updates;\r\n\r\n          //\r\n          // The condition functions are not async-signal safe, and should not be called from a signal handler. \r\n          // In particular, calling pthread_cond_signal or pthread_cond_broadcast from a signal handler may\r\n          // deadlock the calling thread.\r\n          // \r\n          // Raffi: the notification outside the lock above causes a deadlock, apparently it should be protected\r\n          // from simultaneous access. \r\n          condition_.notify_one();\r\n        }\r\n     \r\n        //! Returns once the number of updates reaches the number in argument.\r\n        //!\r\n        //!@warning if an inappropriate number is given, the method might never return.\r\n        bool wait_notifications(size_t nb_notifications)\r\n        {\r\n          boost::unique_lock<mutex_t> lock(internal_mutex);\r\n          while (nb_updates < nb_notifications)\r\n          {\r\n            // when entering wait, the lock is unlocked and made available to other threads.\r\n            // when awakened, the lock is locked before wait returns. \r\n            condition_.wait(lock);\r\n\r\n            //assert(nb_updates);           // cannot be awakened if there is no update\r\n            assert(lock.owns_lock());\r\n\r\n            // consumes what was under a collision in the update\r\n            update_element const* updated_value(0);\r\n            if(!lf_queue.empty())\r\n            {\r\n              updated_value = lf_queue.back();\r\n              lf_queue.pop_back();\r\n              merger_instance(current_value, *updated_value);\r\n            }\r\n          }\r\n\r\n          assert(lock.owns_lock());\r\n\r\n          // consumes what was under a collision in the update\r\n          // we might end up here if there was at least one collision, and everything was finished before the line \"while (nb_updates < nb_notifications)\"\r\n          {\r\n            update_element const* updated_value(0);\r\n            while(!lf_queue.empty())\r\n            {\r\n              updated_value = lf_queue.back();\r\n              lf_queue.pop_back();            \r\n              merger_instance(current_value, *updated_value);\r\n            }\r\n          }\r\n\r\n          return true;\r\n        }\r\n\r\n\r\n        //! Returns the current merged results.\r\n        //! @warning the call is not thread safe (intended to be called once the wait_notifications returned and no\r\n        //! other thread is working). \r\n        result_type const& get_merged_result() const\r\n        {\r\n          return current_value;\r\n        }\r\n\r\n        //! Returns the current merged results.\r\n        //! @warning the call is not thread safe (intended to be called once the wait_notifications returned and no\r\n        //! other thread is working). \r\n        result_type & get_merged_result()\r\n        {\r\n          return current_value;\r\n        }\r\n      };\r\n\r\n\r\n\r\n    } // namespace threading\r\n  } // namespace details\r\n} // namespace grassmann_averages_pca\r\n\r\n\r\n#endif /* GRASSMANN_AVERAGES_PCA_UTILITIES_HPP__*/ \r\n", "meta": {"hexsha": "e4b4e36eb804be65a7acf45d1af7d212f27e36f4", "size": 21438, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/private/utilities.hpp", "max_stars_repo_name": "MPI-Intelligent-Systems-Tuebingen/-Grassmann-Averages-PCA", "max_stars_repo_head_hexsha": "247ed7c8125057b55fc7ef3f26e8c106e09b8ad0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 26.0, "max_stars_repo_stars_event_min_datetime": "2015-07-15T11:14:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-08T01:47:55.000Z", "max_issues_repo_path": "include/private/utilities.hpp", "max_issues_repo_name": "MPI-Intelligent-Systems-Tuebingen/-Grassmann-Averages-PCA", "max_issues_repo_head_hexsha": "247ed7c8125057b55fc7ef3f26e8c106e09b8ad0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-08-24T17:28:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-24T17:28:19.000Z", "max_forks_repo_path": "include/private/utilities.hpp", "max_forks_repo_name": "MPI-Intelligent-Systems-Tuebingen/-Grassmann-Averages-PCA", "max_forks_repo_head_hexsha": "247ed7c8125057b55fc7ef3f26e8c106e09b8ad0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-07-11T12:33:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T12:51:49.000Z", "avg_line_length": 36.6461538462, "max_line_length": 191, "alphanum_fraction": 0.6228192928, "num_tokens": 4591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737214979745, "lm_q2_score": 0.6688802603710085, "lm_q1q2_score": 0.45656008855797336}}
{"text": "/*\n * Copyright 2012-2019 CNRS-UM LIRMM, CNRS-AIST JRL\n */\n\n// check memory allocation in some method\n#define EIGEN_RUNTIME_NO_MALLOC\n\n// includes\n// std\n#include <iostream>\n\n// boost\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE MotionVecd ForceVecd test\n#include <boost/test/unit_test.hpp>\n\n// SpaceVecAlg\n#include <SpaceVecAlg/SpaceVecAlg>\n\ntypedef Eigen::Matrix<double, 6, Eigen::Dynamic> Matrix6Xd;\n\nconst double TOL = 0.00001;\n\nBOOST_AUTO_TEST_CASE(MotionVecdTest)\n{\n  using namespace Eigen;\n  Vector3d w, v;\n  Vector6d m;\n  w = Vector3d::Random();\n  v = Vector3d::Random();\n\n  sva::MotionVecd vec(w, v);\n  m = vec.vector();\n\n  // angular\n  BOOST_CHECK_EQUAL(w, vec.angular());\n\n  // linear\n  BOOST_CHECK_EQUAL(v, vec.linear());\n\n  // vector\n  BOOST_CHECK_EQUAL(m, (Vector6d() << w, v).finished());\n\n  // alpha*M\n  BOOST_CHECK_EQUAL((5. * vec).vector(), (5. * m).eval());\n\n  // M*alpha\n  BOOST_CHECK_EQUAL((vec * 5.).vector(), (5. * m).eval());\n\n  // M/alpha\n  BOOST_CHECK_EQUAL((vec / 5.).vector(), (m / 5.).eval());\n\n  // M *= M\n  sva::MotionVecd vec_timeseq(vec);\n  vec_timeseq *= 5.;\n  BOOST_CHECK_EQUAL(vec_timeseq.vector(), (m * 5.).eval());\n\n  // M /= M\n  sva::MotionVecd vec_diveq(vec);\n  vec_diveq /= 5.;\n  BOOST_CHECK(vec_diveq.vector().isApprox(m / 5.));\n\n  // -M\n  BOOST_CHECK_EQUAL((-vec).vector(), -m);\n\n  Vector3d w2, v2;\n  w2 = Vector3d::Random();\n  v2 = Vector3d::Random();\n  Vector6d m2;\n  sva::MotionVecd vec2(w2, v2);\n  m2 = vec2.vector();\n\n  // M + M\n  BOOST_CHECK_EQUAL((vec + vec2).vector(), (m + m2).eval());\n\n  // M - M\n  BOOST_CHECK_EQUAL((vec - vec2).vector(), (m - m2).eval());\n\n  // M += M\n  sva::MotionVecd vec_pluseq(vec);\n  vec_pluseq += vec2;\n  BOOST_CHECK_EQUAL(vec_pluseq, vec + vec2);\n\n  // M -= M\n  sva::MotionVecd vec_minuseq(vec);\n  vec_minuseq -= vec2;\n  BOOST_CHECK_EQUAL(vec_minuseq, vec - vec2);\n\n  // ==\n  BOOST_CHECK_EQUAL(vec, vec);\n  BOOST_CHECK_NE(vec, -vec);\n\n  // !=\n  BOOST_CHECK(vec != (-vec));\n  BOOST_CHECK(!(vec != vec));\n\n  // zero\n  BOOST_CHECK_EQUAL(sva::MotionVecd::Zero().vector(), Eigen::Vector6d::Zero());\n}\n\nBOOST_AUTO_TEST_CASE(ForceVecdTest)\n{\n  using namespace Eigen;\n  Vector3d n, f;\n  Vector6d m;\n  n = Vector3d::Random();\n  f = Vector3d::Random();\n\n  sva::ForceVecd vec(n, f);\n  m = vec.vector();\n\n  // couple\n  BOOST_CHECK_EQUAL(n, vec.couple());\n\n  // force\n  BOOST_CHECK_EQUAL(f, vec.force());\n\n  // vector\n  BOOST_CHECK_EQUAL(m, (Vector6d() << n, f).finished());\n\n  // alpha*F\n  BOOST_CHECK_EQUAL((5. * vec).vector(), (5. * m).eval());\n\n  // F*alpha\n  BOOST_CHECK_EQUAL((vec * 5.).vector(), (5. * m).eval());\n\n  // F/alpha\n  BOOST_CHECK_EQUAL((vec / 5.).vector(), (m / 5.).eval());\n\n  // F *= F\n  sva::ForceVecd vec_timeseq(vec);\n  vec_timeseq *= 5.;\n  BOOST_CHECK_EQUAL(vec_timeseq.vector(), (m * 5.).eval());\n\n  // F /= F\n  sva::ForceVecd vec_diveq(vec);\n  vec_diveq /= 5.;\n  BOOST_CHECK(vec_diveq.vector().isApprox(m / 5.));\n\n  // -F\n  BOOST_CHECK_EQUAL((-vec).vector(), -m);\n\n  Vector3d n2, f2;\n  n2 = Vector3d::Random();\n  f2 = Vector3d::Random();\n  Vector6d m2;\n  sva::ForceVecd vec2(n2, f2);\n  m2 = vec2.vector();\n\n  // F + F\n  BOOST_CHECK_EQUAL((vec + vec2).vector(), (m + m2).eval());\n\n  // F - F\n  BOOST_CHECK_EQUAL((vec - vec2).vector(), (m - m2).eval());\n\n  // M += M\n  sva::ForceVecd vec_pluseq(vec);\n  vec_pluseq += vec2;\n  BOOST_CHECK_EQUAL(vec_pluseq, vec + vec2);\n\n  // M -= M\n  sva::ForceVecd vec_minuseq(vec);\n  vec_minuseq -= vec2;\n  BOOST_CHECK_EQUAL(vec_minuseq, vec - vec2);\n\n  // ==\n  BOOST_CHECK_EQUAL(vec, vec);\n  BOOST_CHECK_NE(vec, -vec);\n\n  // !=\n  BOOST_CHECK(vec != (-vec));\n  BOOST_CHECK(!(vec != vec));\n\n  // zero\n  BOOST_CHECK_EQUAL(sva::ForceVecd::Zero().vector(), Eigen::Vector6d::Zero());\n}\n\nBOOST_AUTO_TEST_CASE(MotionVecdLeftOperatorsTest)\n{\n  using namespace Eigen;\n  Vector3d w, v, n, f;\n  w = Vector3d::Random() * 100.;\n  v = Vector3d::Random() * 100.;\n  n = Vector3d::Random() * 100.;\n  f = Vector3d::Random() * 100.;\n\n  sva::MotionVecd mVec(w, v);\n  sva::ForceVecd fVec(n, f);\n\n  Vector6d mm, mf;\n  mm = mVec.vector();\n  mf = fVec.vector();\n\n  // dot(MotionVecd, ForceVecd)\n  BOOST_CHECK_SMALL(mVec.dot(fVec) - mm.transpose() * mf, TOL);\n\n  // cross(MotionVecd, MotionVecd)\n  Vector3d w2, v2;\n  w2 = Vector3d::Random() * 100.;\n  v2 = Vector3d::Random() * 100.;\n\n  sva::MotionVecd mVec2(w2, v2);\n  Vector6d mm2;\n  mm2 = mVec2.vector();\n\n  sva::MotionVecd crossM = mVec.cross(mVec2);\n  BOOST_CHECK_SMALL((crossM.vector() - vector6ToCrossMatrix(mm) * mm2).array().abs().sum(), TOL);\n\n  // crossDual(MotionVecd, ForceVecd)\n  sva::ForceVecd crossF = mVec.crossDual(fVec);\n  BOOST_CHECK_SMALL((crossF.vector() - vector6ToCrossDualMatrix(mm) * mf).array().abs().sum(), TOL);\n\n  // test the vectorized version\n  Matrix6Xd crossMVec(6, 2);\n  Matrix6Xd crossMVecRes(6, 2);\n  crossMVec << mVec2.vector(), mVec2.vector();\n\n  internal::set_is_malloc_allowed(false);\n  mVec.cross(crossMVec, crossMVecRes);\n  internal::set_is_malloc_allowed(true);\n\n#ifdef __i386__\n  BOOST_CHECK_SMALL((crossM.vector() - crossMVecRes.col(0)).array().abs().sum(), TOL);\n#else\n  BOOST_CHECK_EQUAL(crossM.vector(), crossMVecRes.col(0));\n#endif\n  BOOST_CHECK_EQUAL(crossMVecRes.col(0), crossMVecRes.col(1));\n\n  Matrix6Xd crossFVec(6, 2);\n  Matrix6Xd crossFVecRes(6, 2);\n  crossFVec << fVec.vector(), fVec.vector();\n\n  internal::set_is_malloc_allowed(false);\n  mVec.crossDual(crossFVec, crossFVecRes);\n  internal::set_is_malloc_allowed(true);\n\n  BOOST_CHECK_EQUAL(crossF.vector(), crossFVecRes.col(0));\n  BOOST_CHECK_EQUAL(crossFVecRes.col(0), crossFVecRes.col(1));\n}\n\nBOOST_AUTO_TEST_CASE(ImpedanceVecdTest)\n{\n  using namespace Eigen;\n  Vector3d w, v;\n  Vector6d z;\n  w = Vector3d::Random();\n  v = Vector3d::Random();\n\n  sva::ImpedanceVecd vec(w, v);\n  z = vec.vector();\n\n  // angular\n  BOOST_CHECK_EQUAL(w, vec.angular());\n\n  // linear\n  BOOST_CHECK_EQUAL(v, vec.linear());\n\n  // vector\n  BOOST_CHECK_EQUAL(z, (Vector6d() << w, v).finished());\n\n  // alpha*M\n  BOOST_CHECK_EQUAL((5. * vec).vector(), (5. * z).eval());\n\n  // M*alpha\n  BOOST_CHECK_EQUAL((vec * 5.).vector(), (5. * z).eval());\n\n  // M/alpha\n  BOOST_CHECK_EQUAL((vec / 5.).vector(), (z / 5.).eval());\n\n  // ==\n  BOOST_CHECK_EQUAL(vec, vec);\n\n  // !=\n  BOOST_CHECK(!(vec != vec));\n\n  // Copy\n  sva::ImpedanceVecd vec_tmp = vec;\n  BOOST_CHECK_EQUAL(vec, vec_tmp);\n\n  // *= alpha\n  vec_tmp *= 5.;\n  BOOST_CHECK_EQUAL(vec_tmp.vector(), (5. * z).eval());\n\n  // /= alpha\n  vec_tmp /= 5.;\n  BOOST_CHECK(vec_tmp.vector().isApprox(z));\n\n  Vector3d w2, v2;\n  w2 = Vector3d::Random();\n  v2 = Vector3d::Random();\n  Vector6d z2;\n  sva::ImpedanceVecd vec2(w2, v2);\n  z2 = vec2.vector();\n\n  // M + M\n  BOOST_CHECK_EQUAL((vec + vec2).vector(), (z + z2).eval());\n\n  // M += M\n  sva::ImpedanceVecd vec_pluseq(vec);\n  vec_pluseq += vec2;\n  BOOST_CHECK_EQUAL(vec_pluseq, vec + vec2);\n\n  w = Vector3d::Random();\n  v = Vector3d::Random();\n  sva::MotionVecd mv(w, v);\n\n  // operator *\n  sva::ForceVecd fv = vec * mv;\n  BOOST_CHECK_SMALL((fv.force() - vec.linear().cwiseProduct(mv.linear())).array().abs().sum(), TOL);\n  BOOST_CHECK_SMALL((fv.couple() - vec.angular().cwiseProduct(mv.angular())).array().abs().sum(), TOL);\n\n  sva::ForceVecd fv2 = mv * vec;\n  BOOST_CHECK_EQUAL(fv, fv2);\n\n  // homogeneous constructor\n  sva::ImpedanceVecd hiv(11., 42.);\n  BOOST_CHECK_EQUAL(hiv.angular(), Eigen::Vector3d(11., 11., 11.));\n  BOOST_CHECK_EQUAL(hiv.linear(), Eigen::Vector3d(42., 42., 42.));\n\n  // zero\n  BOOST_CHECK_EQUAL(sva::ImpedanceVecd::Zero().vector(), Eigen::Vector6d::Zero());\n}\n\nBOOST_AUTO_TEST_CASE(AdmittanceVecdTest)\n{\n  using namespace Eigen;\n  Vector3d w, v;\n  Vector6d a;\n  w = Vector3d::Random();\n  v = Vector3d::Random();\n\n  sva::AdmittanceVecd vec(w, v);\n  a = vec.vector();\n\n  // angular\n  BOOST_CHECK_EQUAL(w, vec.angular());\n\n  // linear\n  BOOST_CHECK_EQUAL(v, vec.linear());\n\n  // vector\n  BOOST_CHECK_EQUAL(a, (Vector6d() << w, v).finished());\n\n  // alpha*M\n  BOOST_CHECK_EQUAL((5. * vec).vector(), (5. * a).eval());\n\n  // M*alpha\n  BOOST_CHECK_EQUAL((vec * 5.).vector(), (5. * a).eval());\n\n  // M/alpha\n  BOOST_CHECK_EQUAL((vec / 5.).vector(), (a / 5.).eval());\n\n  // ==\n  BOOST_CHECK_EQUAL(vec, vec);\n\n  // !=\n  BOOST_CHECK(!(vec != vec));\n\n  // Copy\n  sva::AdmittanceVecd vec_tmp = vec;\n  BOOST_CHECK_EQUAL(vec, vec_tmp);\n\n  // *= alpha\n  vec_tmp *= 5.;\n  BOOST_CHECK_EQUAL(vec_tmp.vector(), (5. * a).eval());\n\n  // /= alpha\n  vec_tmp /= 5.;\n  BOOST_CHECK(vec_tmp.vector().isApprox(a));\n\n  Vector3d w2, v2;\n  w2 = Vector3d::Random();\n  v2 = Vector3d::Random();\n  Vector6d a2;\n  sva::AdmittanceVecd vec2(w2, v2);\n  a2 = vec2.vector();\n\n  // M + M\n  BOOST_CHECK_EQUAL((vec + vec2).vector(), (a + a2).eval());\n\n  // M += M\n  sva::AdmittanceVecd vec_pluseq(vec);\n  vec_pluseq += vec2;\n  BOOST_CHECK_EQUAL(vec_pluseq, vec + vec2);\n\n  Vector3d n = Vector3d::Random();\n  Vector3d f = Vector3d::Random();\n  sva::ForceVecd fv(n, f);\n\n  // operator *\n  sva::MotionVecd mv = vec * fv;\n  BOOST_CHECK_SMALL((mv.linear() - vec.linear().cwiseProduct(fv.force())).array().abs().sum(), TOL);\n  BOOST_CHECK_SMALL((mv.angular() - vec.angular().cwiseProduct(fv.couple())).array().abs().sum(), TOL);\n\n  sva::MotionVecd mv2 = fv * vec;\n  BOOST_CHECK_EQUAL(mv, mv2);\n\n  // homogeneous constructor\n  sva::AdmittanceVecd hav(11., 42.);\n  BOOST_CHECK_EQUAL(hav.angular(), Eigen::Vector3d(11., 11., 11.));\n  BOOST_CHECK_EQUAL(hav.linear(), Eigen::Vector3d(42., 42., 42.));\n\n  // zero\n  BOOST_CHECK_EQUAL(sva::AdmittanceVecd::Zero().vector(), Eigen::Vector6d::Zero());\n}\n", "meta": {"hexsha": "28d169a4196b1ec187a7bf3f665fa18fc360e709", "size": 9500, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/VectorTest.cpp", "max_stars_repo_name": "gergondet/SpaceVecAlg", "max_stars_repo_head_hexsha": "b5a92d961c7b52f147908c779dfa024c4c302f08", "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": "tests/VectorTest.cpp", "max_issues_repo_name": "gergondet/SpaceVecAlg", "max_issues_repo_head_hexsha": "b5a92d961c7b52f147908c779dfa024c4c302f08", "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": "tests/VectorTest.cpp", "max_forks_repo_name": "gergondet/SpaceVecAlg", "max_forks_repo_head_hexsha": "b5a92d961c7b52f147908c779dfa024c4c302f08", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.3990147783, "max_line_length": 103, "alphanum_fraction": 0.6376842105, "num_tokens": 3176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.45653366720058575}}
{"text": "#ifndef HOPS_LINEARPROGRAMMING_HPP\n#define HOPS_LINEARPROGRAMMING_HPP\n\n#include <Eigen/Core>\n#include \"LinearProgramSolution.hpp\"\n#include <utility>\n\nnamespace hops {\n    class LinearProgram {\n    public:\n        LinearProgram(Eigen::MatrixXd a, Eigen::VectorXd b) : A(std::move(a)), b(std::move(b)) {}\n\n        virtual ~LinearProgram() = default;\n\n        virtual LinearProgramSolution solve(const Eigen::VectorXd &objective) const = 0;\n\n        /**\n         * @brief Removes redundant constraints and returns system matrices. Changes to the system matrices\n         *        are reflected internally in the LP solver.\n         * @param tolerance\n         * @return A and b\n         */\n        virtual std::tuple<Eigen::MatrixXd, Eigen::VectorXd> removeRedundantConstraints(double tolerance) = 0;\n\n        [[nodiscard]] virtual LinearProgramSolution computeChebyshevCenter() const = 0;\n\n        /**\n         * @details dimensions with missing upper boundaries are counted starting from 1 upwards.\n         *          dimensions with missing lower boundaries are counted starting from -1 downwards.\n         * @return\n         */\n        [[nodiscard]] virtual std::vector<long> computeUnconstrainedDimensions() const = 0;\n\n        /**\n         * @brief Adds box constraints to unconstrained dimensions and returns system matrices.\n         *        Changes to the system matrices are reflected internally in the LP solver.\n         * @param lb\n         * @param ub\n         * @return A and b\n         */\n        virtual std::tuple<Eigen::MatrixXd, Eigen::VectorXd>\n        addBoxConstraintsToUnconstrainedDimensions(double lb, double ub) = 0;\n\n        [[nodiscard]] const Eigen::MatrixXd &getA() const {\n            return A;\n        }\n\n        [[nodiscard]] const Eigen::VectorXd &getB() const {\n            return b;\n        }\n\n    protected:\n        Eigen::MatrixXd A;\n        Eigen::VectorXd b;\n    };\n}\n\n#endif //HOPS_LINEARPROGRAMMING_HPP\n", "meta": {"hexsha": "4383bb6d7166e150aa082809121c3063353c1d92", "size": 1945, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/hops/LinearProgram/LinearProgram.hpp", "max_stars_repo_name": "modsim/hops", "max_stars_repo_head_hexsha": "4285dd75a07dd844295440a0756b3ba25f5819ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2020-11-26T05:13:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T02:08:40.000Z", "max_issues_repo_path": "include/hops/LinearProgram/LinearProgram.hpp", "max_issues_repo_name": "modsim/hops", "max_issues_repo_head_hexsha": "4285dd75a07dd844295440a0756b3ba25f5819ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-02-20T23:16:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-20T23:16:34.000Z", "max_forks_repo_path": "include/hops/LinearProgram/LinearProgram.hpp", "max_forks_repo_name": "modsim/hops", "max_forks_repo_head_hexsha": "4285dd75a07dd844295440a0756b3ba25f5819ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.9661016949, "max_line_length": 110, "alphanum_fraction": 0.6313624679, "num_tokens": 410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4565336672005857}}
{"text": "// Ben Martin\n// December 3, 2005\n\n// This currently works only on undirected graphs...\n// Graph must model Adjacency Graph, Incidence Graph, VertexListGraph\n\n#ifndef BOOST_GRAPH_SPECTRUM_HPP\n#define BOOST_GRAPH_SPECTRUM_HPP\n\n#define USE_IETL 0\n\n#if USE_IETL\n#else\n#define USE_LAPACK 1\n#endif\n\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/named_function_params.hpp>\n#include <boost/graph/properties.hpp>\n#include <boost/property_map/vector_property_map.hpp>\n#include <utility> // for pair\n\n//#include <iostream.h>\n#ifdef USE_LAPACK\n#ifdef _APPLE_\n#include <vecLib/clapack.h>\n#endif\n//#include \"f2c.h\"\n//#include \"cblas.h\"\n//#include \"clapack.h\"\n#elif USE_IETL\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/vector_sparse.hpp>\n#include <boost/numeric/ublas/matrix_sparse.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <ietl/vectorspace.h>\n#include <ietl/lanczos.h>\n#include <ietl/iteration.h>\n#include <boost/random/linear_congruential.hpp>\n#include <ietl/interface/ublas.h>\n#endif\n\ntypedef long int integer;\ntypedef double doublereal;\n\n#ifdef USE_LAPACK\nextern \"C\" int dsyevr_(char *jobz, char *range, char *uplo, integer *n, \n\t\t       doublereal *a, integer *lda, doublereal *vl, doublereal *vu, integer *\n\t\t       il, integer *iu, doublereal *abstol, integer *m, doublereal *w, \n\t\t       doublereal *z__, integer *ldz, integer *isuppz, doublereal *work, \n\t\t       integer *lwork, integer *iwork, integer *liwork, integer *info);\n#endif\n\n\nnamespace boost {\n\n  template <typename Graph, typename Matrix >\n  void spectrum(Graph& g, \n\t\tint first_eigenvector_index,\n\t\tint num_eigenvectors,\n\t\tMatrix &eigenvectors,\n\t\tdouble rel_tol = 100, \n\t\tdouble abs_tol = 1000) \n  {\n    std::vector<double> evals(num_eigenvectors);\n    spectrum(g, first_eigenvector_index, num_eigenvectors, eigenvectors, evals, rel_tol, abs_tol);\n  }\n\n  // Parameters:\n  //   first_eigenvector_index:\n  //     Since the smallest eigenvector is not useful, often this will \n  //       be set to 1, for the \"Fiedler vector,\" though if all \n  //       eigenvectors are desired, 0 may be a more logical value.\n  //     Negative values are interpreted as allowing a default choice of 1.\n  //   num_eigenvectors:\n  //     The number of eigencectors to return.\n\n  template <typename Graph, typename Matrix , typename EVector>\n  void spectrum(Graph& g, \n\t\tint first_eigenvector_index,\n\t\tint num_eigenvectors,\n\t\t//\t\tstd::vector<Vector> &eigenvectors,\n\t\tMatrix &eigenvectors,\n\t\tEVector &eigenvalues,\n\t\tdouble rel_tol = 100, \n\t\tdouble abs_tol = 1000) \n  {\n\n    //    Matrix eigenvectors = *(in_eigenvectors);\n\n    if (first_eigenvector_index < 0)\n      first_eigenvector_index = 1;\n    \n    typedef typename property_map<Graph, vertex_index_t>::const_type IndexMap;\n    typedef typename Graph::vertex_iterator VertexIterator;\n    typedef typename Graph::edge_iterator EdgeIterator;\n    typedef typename boost::graph_traits<Graph>::adjacency_iterator AdjacencyIterator;\n    \n    IndexMap index_map = get(vertex_index, g);\n\n    VertexIterator v, vs, ve;\n    using std::pair;\n    std::pair<VertexIterator, VertexIterator> p;\n    p = vertices(g);\n    vs = p.first;\n    ve = p.second;\n\n    EdgeIterator e, es, ee;\n    using std::pair;\n    std::pair<EdgeIterator, EdgeIterator> ep;\n    ep = edges(g);\n    es = ep.first;\n    ee = ep.second;\n    typename Graph::vertex_descriptor src, tgt;\n    \n    integer N = num_vertices(g);\n\n#ifdef USE_LAPACK\n    doublereal *A;\n    A = new double[N * N];\n#elif USE_IETL\n    using namespace boost::numeric::ublas;\n    typedef compressed_matrix<double> Matrix;\n    Matrix A(N, N);\n#endif\n    \n    int i;\n    \n    AdjacencyIterator a, as, ae;\n    std::pair<AdjacencyIterator, AdjacencyIterator> ap;\n    \n#ifdef USE_LAPACK\n    for (i = 0; i < N * N; i++)\n      A[i] = 0;\n#elif USE_IETL\n#endif\n\n    i = 0;\n    /*\n    for (v = vs; v != ve; ++v) {\n#ifdef USE_LAPACK\n      A[(index_map[*v] * N) + index_map[*v]] = (doublereal)out_degree(*v, g);\n#elif USE_IETL\n      A(index_map[*v], index_map[*v]) = (double)out_degree(*v, g);\n#endif\n    }\n    */\n    for (e = es; e != ee; ++e) {\n      i += 1;\n      src = source(*e, g);\n      tgt = target(*e, g);\n#ifdef USE_LAPACK      \n      if (src != tgt && A[index_map[src] + index_map[tgt]*N] != -1) {\n\tA[index_map[src] + index_map[tgt]*N] = (doublereal)(-1);\n\tA[index_map[src]*N + index_map[tgt]] = (doublereal)(-1);\n\tA[index_map[src] + index_map[src]*N] += (doublereal)1;\n\tA[index_map[tgt] + index_map[tgt]*N] += (doublereal)1;\n      }\n#elif USE_IETL\n      if (src != tgt && A(index_map[src], index_map[tgt]) != -1) {\n\tA(index_map[src], index_map[tgt]) = (double)(-1);\n\tA(index_map[tgt], index_map[src]) = (double)(-1);\n\tA(index_map[src], index_map[src]) += (double)1;\n\tA(index_map[tgt], index_map[tgt]) += (double)1;\n      }\n#endif\n    }\n\n    /*\n    cout << \"index_map = \" << endl;\n    for (v = vs; v != ve; ++v) {\n      cout << index_map[*v] << \" \";\n    }\n    cout << endl;\n    cout << \"A = \" << endl;\n    for (i = 0; i < N; i++)\n    {\n      for (int j = 0; j < N; j++)\n      {\n        cout << A[i*N + j] << \" \";\n      }\n        cout << endl;\n    }\n    */\n\n#ifdef USE_LAPACK\n    // Set up the 8 billion parameters for CLAPACK\n    char   JOBZ   = 'v';\n    char   RANGE  = 'i';\n    char   UPLO   = 'l'; // arbitrary at the moment...\n    // N is defined\n    // A is defined\n    integer    LDA    = N;\n    doublereal VL     = 0; // not needed\n    doublereal VU     = 0; // not needed\n    integer    IL     = first_eigenvector_index + 1; //2 // first NON-ZERO eigenvalue\n    integer    IU     = first_eigenvector_index + num_eigenvectors; // 4 for the 3d case\n    //    char   dlamch_cmach = 's';\n\n    //    doublereal ABSTOL = 0.001;// dlamch_(&dlamch_cmach); // most likely SEVERE OVERKILL\n    doublereal ABSTOL = abs_tol*std::numeric_limits<double>::epsilon();\n    integer    M = (IU - IL + 1); // N; // should come back 2 or 3 (for 2d, 3d respectively)\n    doublereal *W = new double[N]; // the eigenvalues\n    doublereal *Z = new double[N*M]; // the eigenvectors\n    integer    LDZ = N;\n    integer    *ISUPPZ = new integer[2*M];// (integer*)0; // = new int[2*(IU-IL+1)]; ??? Not needed?\n    doublereal *WORK = new double[26*N]; // should this be allocated?\n    integer    LWORK  = 26*N; // -1\n    integer    *IWORK = new integer[10*N];\n    integer    LIWORK = 10*N; // -1\n    integer    INFO;\n\n    dsyevr_(&JOBZ, &RANGE, &UPLO, &N, A, &LDA, &VL, &VU, &IL, &IU, &ABSTOL,\n            &M, W, Z, &LDZ, ISUPPZ, WORK, &LWORK, IWORK, &LIWORK, &INFO);\n\n    /*\n    cout << \"N = \" << N << endl; \n    cout << \"IL = \" << INFO << endl; \n    cout << \"IU = \" << INFO << endl; \n\n    cout << \"INFO = \" << INFO << endl; \n    cout << \"M = \" << M << endl; \n    \n    cout << \"W = \";\n    for (i = 0; i < M; i++)\n      cout << W[i] << \" \";\n    cout << endl;\n    for (i = 0; i < M; i++)\n      for (int j = 0; j < N; j++)\n      {\n        cout << Z[i*N + j] << \"\";\n        cout << endl;\n      }\n    */\n#elif USE_IETL\n\n    using namespace ietl;\n\n    vectorspace<boost::numeric::ublas::vector<double> > VS(N);\n    lanczos<Matrix, vectorspace<boost::numeric::ublas::vector<double> > > LanczosObject(A, VS);\n    \n    double _rel_tol = 1000.*std::numeric_limits<double>::epsilon();\n    double _abs_tol = 10000.*std::numeric_limits<double>::epsilon();\n    \n    //    _rel_tol = 100.*std::numeric_limits<double>::epsilon();\n    //    _abs_tol = 100.*std::numeric_limits<double>::epsilon();\n\n    // SO far these are the best I have found:\n    //    _rel_tol = 1000.*std::numeric_limits<double>::epsilon();\n    //    _abs_tol = 10000.*std::numeric_limits<double>::epsilon();\n\n    _rel_tol = rel_tol*std::numeric_limits<double>::epsilon();\n    _abs_tol = abs_tol*std::numeric_limits<double>::epsilon();\n\n\n    lanczos_iteration_nlowest<double> LanczosIterationControl(1000000, first_eigenvector_index + num_eigenvectors, _rel_tol, _abs_tol);\n    //    std::cout << std::numeric_limits<double>::epsilon() << std::endl;\n    boost::minstd_rand gen(1);\n    //boost::rand48 gen(1);\n    LanczosObject.calculate_eigenvalues(LanczosIterationControl, gen);\n    std::vector<double> evals = LanczosObject.eigenvalues();\n\n    //    for (int i = 0; i < N; i++)\n    //      std::cout << evals[i] << \" \";\n    //    std::cout << std::endl;\n\n    /*\n    std::vector<int> multiplicities = LanczosObject.multiplicities();\n    int lowest_eval_multiplicity = multiplicities[1];\n    int second_eval_multiplicity;\n    if (lowest_eval_multiplicity == 1 && multiplicities[2] > 1)\n      second_eval_multiplicity = 2;\n    else\n      second_eval_multiplicity = 1;\n\n    for (int i = 0; i < N; i++)\n      std::cout << multiplicities[i] << \" \";\n    std::cout << std::endl;\n    */\n\n    std::vector<boost::numeric::ublas::vector<double> > evecs(3);\n    for (int j = 0; j < num_eigenvectors; j++)\n      evecs[j] = *(new boost::numeric::ublas::vector<double>(N));\n    std::vector<boost::numeric::ublas::vector<double> >::iterator out_it = evecs.begin();\n    \n    Info<double> info;\n    std::vector<double>::iterator ebegin, eend;\n    ebegin = evals.begin();\n    ebegin += first_eigenvector_index;\n    eend = evals.begin();\n    //    eend += 4 + (1 - lowest_eval_multiplicity) + (1 - second_eval_multiplicity);\n    eend += first_eigenvector_index + num_eigenvectors;\n    LanczosObject.eigenvectors(ebegin, eend, out_it, info, gen, 100000);\n    //    LanczosObject.eigenvectors(ebegin, eend, out_it, info, gen);\n\n    /*\n    // If eigenvalues are repeated, we need to copy eigenvectors\n    if (lowest_eval_multiplicity > 1) {\n      for (int i = 0; i < N; i++)\n\tevecs[1][i] = evecs[0][i];\n      if (lowest_eval_multiplicity > 2) {\n\tfor(int i = 0; i < N; i++)\n\t  evecs[2][i] = evecs[0][i];\n      }\n    }\n    if (second_eval_multiplicity > 1) {\n      for (int i = 0; i < N; i++)\n\tevecs[2][i] = evecs[1][i];\n    }\n    */\n\n    //    for (int i = 0; i < 3; i++)\n    //      for (int j = 0; j < N; j++)\n    //\tstd::cout << evecs[i][j] << \" \";\n    //    cout << std::endl;\n    \n    //    std::cout << A << std::endl;\n    //    std::cout << LanczosIterationControl.error_code() << endl;;\n    //    std::cout << info.error_info(1) << \" \" << info.error_info(2) << \" \" << info.error_info(3) << std::endl;\n\n#endif\n\n    //    std::vector<Vector> retval(num_eigenvectors);\n    for (int j = 0; j < num_eigenvectors; j++) {\n      // retval[j] = *(new Vector(N));\n      i = 0;\n      for (v = vs; v != ve; ++v) {\n#ifdef USE_LAPACK\n\t//\t  retval[j][i] = Z[(first_eigenvector_index+j-1)*LDZ + i];\n\teigenvectors[j][i] = Z[j*LDZ + i];\n#elif USE_IETL\n\t//\t  retval[j][i] = evecs[first_eigenvector_index+j-1][i];\n\teigenvectors[j][i] = evecs[first_eigenvector_index+j-1][i];\n\t\n#endif\n\ti++;\n      }\n    }\n#ifdef USE_LAPACK\n    for (int j = 0; j < M; j++) {\n      eigenvalues[j] = W[j];\n    }\n#endif\n    //    return retval;\n    \n  } // end spectrum()\n  \n} // end namespace boost\n\n#endif // BOOST_GRAPH_SPECTRUM_HPP\n\n", "meta": {"hexsha": "b6f8abd32bfd7d881791cfd84531b85d2fcd77da", "size": 10929, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/graph/spectrum.hpp", "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": "boost/graph/spectrum.hpp", "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": "boost/graph/spectrum.hpp", "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": 30.9603399433, "max_line_length": 135, "alphanum_fraction": 0.6086558697, "num_tokens": 3421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4565336672005857}}
{"text": "#include <boost/numeric/odeint/stepper/adams_moulton.hpp>\n", "meta": {"hexsha": "a0c5f294fcdcbcaf11d244046f1d76750e5ee0a1", "size": 58, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_numeric_odeint_stepper_adams_moulton.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_numeric_odeint_stepper_adams_moulton.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_numeric_odeint_stepper_adams_moulton.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 29.0, "max_line_length": 57, "alphanum_fraction": 0.8275862069, "num_tokens": 18, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4565336672005857}}
{"text": "#include \"quotient.hpp\"\n#include \"ast.hpp\"\n#include \"parsers.hpp\"\n#include \"types.hpp\"\n#include <boost/variant.hpp>\n#include <stdexcept>\n#include <algorithm>\n#include <cmath>\nnamespace HT\n{\n    void quotient(PASTNode astnode, ParsersHelper& ph)\n    {\n        auto myParserHelper(ph);\n        if (astnode->ch.size()!=3)\n          throw std::runtime_error(\"Quotient should have exact 2 parameters\");\n        auto & thirdCh = *astnode->ch.rbegin();\n        auto & secondCh = *(++astnode->ch.begin() );\n        ph.parse(secondCh);\n        ph.parse(thirdCh);\n        if (secondCh->token.tokenType!=Complex || !boost::get<ComplexType>(secondCh->token.info).isInt())\n          throw std::runtime_error(\"The arguments of quotient should be integer\");\n        \n        if (thirdCh->token.tokenType!=Complex || !boost::get<ComplexType>(thirdCh->token.info).isInt())\n          throw std::runtime_error(\"The arguments of quotient should be integer\");\n\n        astnode->type = Simple;\n        astnode->token.tokenType = Complex;\n        if ( boost::get<ComplexType>(secondCh->token.info).toInt().isZero()) \n          astnode->token.info = ComplexType(0); else\n         astnode->token.info = ComplexType( boost::get<ComplexType>(secondCh->token.info).toInt() / \n            boost::get<ComplexType>(thirdCh->token.info).toInt() );\n        astnode->type = Simple;\n        astnode->token.tokenType = Complex;\n        astnode->remove();\n    }\n}\n\n\n", "meta": {"hexsha": "752ca6af0eeb40dc714b28a080432601fb208696", "size": 1429, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "funs/quotient.cpp", "max_stars_repo_name": "htfy96/htscheme", "max_stars_repo_head_hexsha": "b44c9f9672f69d9b3c2eb1c80969bcfcfec9990f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2015-07-07T01:30:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-14T10:45:01.000Z", "max_issues_repo_path": "funs/quotient.cpp", "max_issues_repo_name": "htfy96/htscheme", "max_issues_repo_head_hexsha": "b44c9f9672f69d9b3c2eb1c80969bcfcfec9990f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "funs/quotient.cpp", "max_forks_repo_name": "htfy96/htscheme", "max_forks_repo_head_hexsha": "b44c9f9672f69d9b3c2eb1c80969bcfcfec9990f", "max_forks_repo_licenses": ["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.641025641, "max_line_length": 105, "alphanum_fraction": 0.6326102169, "num_tokens": 352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255928, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.45653366068752443}}
{"text": "#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Polyhedron_3.h>\n#include <CGAL/Polygon_mesh_processing/triangulate_hole.h>\n\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <boost/foreach.hpp>\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel;\ntypedef CGAL::Polyhedron_3<Kernel>     Polyhedron;\n\ntypedef Polyhedron::Halfedge_handle    Halfedge_handle;\ntypedef Polyhedron::Facet_handle       Facet_handle;\ntypedef Polyhedron::Vertex_handle      Vertex_handle;\n\nint main(int argc, char* argv[])\n{\n  const char* filename = (argc > 1) ? argv[1] : \"data/mech-holes-shark.off\";\n  std::ifstream input(filename);\n\n  Polyhedron poly;\n  if ( !input || !(input >> poly) || poly.empty() ) {\n    std::cerr << \"Not a valid off file.\" << std::endl;\n    return 1;\n  }\n\n  // Incrementally fill the holes\n  unsigned int nb_holes = 0;\n  BOOST_FOREACH(Halfedge_handle h, halfedges(poly))\n  {\n    if(h->is_border())\n    {\n      std::vector<Facet_handle>  patch_facets;\n      std::vector<Vertex_handle> patch_vertices;\n      bool success = CGAL::cpp11::get<0>(\n        CGAL::Polygon_mesh_processing::triangulate_refine_and_fair_hole(\n                  poly,\n                  h,\n                  std::back_inserter(patch_facets),\n                  std::back_inserter(patch_vertices),\n     CGAL::Polygon_mesh_processing::parameters::vertex_point_map(get(CGAL::vertex_point, poly)).\n                  geom_traits(Kernel())) );\n\n      std::cout << \" Number of facets in constructed patch: \" << patch_facets.size() << std::endl;\n      std::cout << \" Number of vertices in constructed patch: \" << patch_vertices.size() << std::endl;\n      std::cout << \" Fairing : \" << (success ? \"succeeded\" : \"failed\") << std::endl;\n      ++nb_holes;\n    }\n  }\n\n  std::cout << std::endl;\n  std::cout << nb_holes << \" holes have been filled\" << std::endl;\n  \n  std::ofstream out(\"filled.off\");\n  out.precision(17);\n  out << poly << std::endl;\n  return 0;\n}\n", "meta": {"hexsha": "33aa352430c96662a833f42d886336b6c715325e", "size": 1981, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ext/libigl/external/cgal/src/CGAL_Project/examples/Polygon_mesh_processing/hole_filling_example.cpp", "max_stars_repo_name": "liminchen/OptCuts", "max_stars_repo_head_hexsha": "cb85b06ece3a6d1279863e26b5fd17a5abb0834d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 187.0, "max_stars_repo_stars_event_min_datetime": "2019-01-23T04:07:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T03:44:58.000Z", "max_issues_repo_path": "ext/libigl/external/cgal/src/CGAL_Project/examples/Polygon_mesh_processing/hole_filling_example.cpp", "max_issues_repo_name": "xiaoxie5002/OptCuts", "max_issues_repo_head_hexsha": "1f4168fc867f47face85fcfa3a572be98232786f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-03-22T13:27:38.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-18T13:23:23.000Z", "max_forks_repo_path": "ext/libigl/external/cgal/src/CGAL_Project/examples/Polygon_mesh_processing/hole_filling_example.cpp", "max_forks_repo_name": "xiaoxie5002/OptCuts", "max_forks_repo_head_hexsha": "1f4168fc867f47face85fcfa3a572be98232786f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 34.0, "max_forks_repo_forks_event_min_datetime": "2019-02-13T01:11:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T03:29:40.000Z", "avg_line_length": 33.0166666667, "max_line_length": 102, "alphanum_fraction": 0.6547198385, "num_tokens": 520, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255928, "lm_q2_score": 0.6001883592602049, "lm_q1q2_score": 0.4565336606875243}}
{"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// This program will make use of the ATOM solver to construct a transfer trajectory\n// between two points in space. Only a single transfer segment is simulated here, that is, no multitargeting.\n// There is just one departure and one arrival object considered in the simulation. The object TLEs are\n// taken from a catalog file. The user can specify which object will be departure and which will be arrival\n// along with the time of flight. \n\n#include <iostream>\n#include <sstream>\n#include <stdexcept>\n#include <string>\n#include <vector>\n#include <fstream>\n#include <exception>\n#include <cstdlib>\n#include <iterator>\n\n#include <libsgp4/Globals.h>\n#include <libsgp4/SGP4.h>\n#include <libsgp4/Tle.h>\n\n#include <Atom/atom.hpp>\n#include <Atom/convertCartesianStateToTwoLineElements.hpp>\n\n#include <Astro/orbitalElementConversions.hpp>\n\n#include <SML/sml.hpp>\n#include <SML/constants.hpp>\n#include <SML/basicFunctions.hpp>\n#include <SML/linearAlgebra.hpp>\n\n#include <boost/array.hpp>\n\n#include </usr/local/abhi/pykep/src/lambert_problem.cpp>\n#include </usr/local/abhi/pykep/src/lambert_problem.h>\n#include </usr/local/abhi/pykep/src/keplerian_toolbox.h>\n\n\ntypedef double Real;\ntypedef std::vector < Real > Vector6;\ntypedef std::vector < Real > Vector3;\ntypedef std::vector < Real > Vector2;\ntypedef std::vector < std::vector < Real > > Vector2D;\ntypedef boost::array < Real, 3 > array3; \n\n//! Remove newline characters from string.\nvoid removeNewline( std::string& string )\n{\n    string.erase( std::remove( string.begin( ), string.end( ), '\\r' ), string.end( ) );\n    string.erase( std::remove( string.begin( ), string.end( ), '\\n' ), string.end( ) );\n}\n\n//! Convert SGP4 ECI object to state vector.\nVector6 getStateVector( const Eci state )\n{\n    Vector6 result( 6 );\n    result[ 0 ] = state.Position( ).x;\n    result[ 1 ] = state.Position( ).y;\n    result[ 2 ] = state.Position( ).z;\n    result[ 3 ] = state.Velocity( ).x;\n    result[ 4 ] = state.Velocity( ).y;\n    result[ 5 ] = state.Velocity( ).z;\n    return result;\n}\n\nVector6 getStateVectorInMetre( const Eci state )\n{\n    Vector6 result( 6 );\n    result[ 0 ] = state.Position( ).x * 1000.0;\n    result[ 1 ] = state.Position( ).y * 1000.0;\n    result[ 2 ] = state.Position( ).z * 1000.0;\n    result[ 3 ] = state.Velocity( ).x * 1000.0;\n    result[ 4 ] = state.Velocity( ).y * 1000.0;\n    result[ 5 ] = state.Velocity( ).z * 1000.0;\n    return result;\n}\n\n\nint main( void )\n{\n    // conversion from km to m\n    // const double km2m = 1000; \n    const double Rearth = kXKMPER; // earth radius in km\n    // earth radius and diameter\n    // const double EarthRadius = kXKMPER * km2m; // unit m\n    // const double EarthDiam = 2 * EarthRadius;\n    \n    // grav. parameter 'mu' of earth\n    const double muEarth = kMU*( pow( 10, 9 ) ); // unit m^3/s^2\n    \n    // vectors to store arrival and departure velocities for the transfer trajectory\n    Vector3 DepartureVelocity( 3 );\n    Vector3 ArrivalVelocity( 3 );\n\n    // read the TLE file. Line based parsing, using string streams\n    std::string line;\n    \n    std::ifstream tlefile( \"../../src/napa_prograde_catalog.txt\" );\n    const bool is_retro = false;\n    \n    if( !tlefile.is_open() )\n        perror(\"error while opening file\");\n\n    std::vector < Tle > tleObjects; // vector of TLE objects\n    \n\n    while( !tlefile.eof( ) )\n    {\n        std::vector < std::string > tleStrings;\n\n        std::getline( tlefile, line ); // read line from the catalog file\n        removeNewline( line ); // remove new line characters such as '/n'\n        tleStrings.push_back( line );\n        // std::cout << line << std::endl;\n\n        std::getline( tlefile, line );\n        removeNewline( line );\n        tleStrings.push_back( line );\n        // std::cout << line << std::endl;\n\n        std::getline( tlefile, line );\n        removeNewline( line );\n        tleStrings.push_back( line );\n        // std::cout << line << std::endl << std::endl;\n\n        tleObjects.push_back( Tle( tleStrings[ 0 ], tleStrings[ 1 ], tleStrings[ 2 ] ) );\n    }\n    tlefile.close( );\n    \n    const int DebrisObjects = tleObjects.size( );\n    std::cout << \"Total debris objects = \" << DebrisObjects << std::endl; \n    \n    // some variables for the \"catch\" segment\n    int failCount = 0;\n    int catchDepartureID;\n    int catchArrivalID;\n\n    std::ofstream ephemerisfile;\n    ephemerisfile.precision( 15 );\n    std::ofstream osculatingfile;\n    osculatingfile.precision( 15 );\n    \n    std::cout.precision( 15 );\n    \n    //*********************** Inputs *********************************************************************************************************//\n    Tle departureObject = tleObjects[ 0 ]; \n    Tle arrivalObject = tleObjects[ 1 ];    \n    DateTime departureEpoch = DateTime( 2016, 1, 13, 22, 06, 45 );\n    const double TOF = 24910.0; // time of flight                     \n    ephemerisfile.open( \"/home/abhishek/Dropbox/Dinamica Internship/16-03-01 Napa osculating elements and ephemeris/16-03-01 ephemeris transfer case 5.csv\" );\n    osculatingfile.open( \"/home/abhishek/Dropbox/Dinamica Internship/16-03-01 Napa osculating elements and ephemeris/16-03-01 osculating transfer case 5.csv\" );\n    //***************************************************************************************************************************************//\n    \n\n    SGP4 sgp4Departure( departureObject );\n    const Eci tleDepartureState = sgp4Departure.FindPosition( departureEpoch );\n    // const Eci tleDepartureState = sgp4Departure.FindPosition( 0.0 );\n    const Vector6 departureState = getStateVector( tleDepartureState );\n    \n    array3 departurePosition;\n    array3 departureVelocity;\n    for( int j = 0; j < 3; j++ )\n    {\n        departurePosition[ j ] = departureState[ j ];\n        departureVelocity[ j ] = departureState[ j + 3 ];\n    }\n    \n    const int departureObjectId = static_cast< int >( departureObject.NoradNumber( ) );\n    // std::cout << \"departure Object ID = \" << departureObjectId << std::endl;\n    catchDepartureID = departureObjectId; // for the catch segment of the program\n                    \n                    \n    SGP4 sgp4Arrival( arrivalObject );\n    const int arrivalObjectId = static_cast< int >( arrivalObject.NoradNumber( ) );\n    // std::cout << \"Arrival Object ID = \" << arrivalObjectId << std::endl;\n    catchArrivalID = arrivalObjectId;\n\n                        \n    \n    // DateTime arrivalEpoch = arrivalObject.Epoch( ); // take epoch from arrival TLE and then add TOF to it\n    // arrivalEpoch = arrivalEpoch.AddSeconds( TOF );\n    const DateTime arrivalEpoch = departureEpoch.AddSeconds( TOF );\n    const Eci tleArrivalState = sgp4Arrival.FindPosition( arrivalEpoch );\n    // const Eci tleArrivalState = sgp4Arrival.FindPosition( 0.0 );\n    const Vector6 arrivalState = getStateVector( tleArrivalState );\n\n    array3 arrivalPosition;\n    array3 arrivalVelocity;\n    for( int j = 0; j < 3; j++ )\n    {\n        arrivalPosition[ j ] = arrivalState[ j ];\n        arrivalVelocity[ j ] = arrivalState[ j + 3 ];\n    } \n\n    kep_toolbox::lambert_problem targeter( departurePosition, arrivalPosition, TOF, kMU, is_retro, 5 );\n    const int numberOfSolutions = targeter.get_v1( ).size( );\n    std::vector< array3 > departureDeltaVs( numberOfSolutions ); // delta-V components at the departure point\n    std::vector< array3 > arrivalDeltaVs( numberOfSolutions );                \n    std::vector< Real > transferDeltaVs( numberOfSolutions ); // magnitude of the total delta-V of one transfer between two points\n\n    for ( int j = 0; j < numberOfSolutions; j++ )\n    {\n        array3 transferDepartureVelocity = targeter.get_v1( )[ j ]; // velocity of the s/c at the departure point in the transfer orbit\n        array3 transferArrivalVelocity = targeter.get_v2( )[ j ];\n\n        departureDeltaVs[ j ] = sml::add( transferDepartureVelocity, sml::multiply( departureVelocity, -1.0 ) );\n        arrivalDeltaVs[ j ] = sml::add( transferArrivalVelocity, sml::multiply( arrivalVelocity, -1.0 ) );\n\n        transferDeltaVs[ j ] = sml::norm< Real >( departureDeltaVs[ j ] ) + sml::norm< Real >( arrivalDeltaVs[ j ] );\n    }\n\n    const std::vector< Real >::iterator minDeltaVIterator = std::min_element( transferDeltaVs.begin( ), transferDeltaVs.end( ) );\n    const int minimumDeltaVIndex = std::distance( transferDeltaVs.begin( ), minDeltaVIterator );\n\n                            \n    array3 minIndexDepartureVelocity = targeter.get_v1( )[ minimumDeltaVIndex ]; // best guess for velocity in transfer orbit at the departure point\n    Vector3 departureVelocityGuess( 3 );\n    Vector3 atomDeparturePosition( 3 );\n    Vector3 atomArrivalPosition( 3 );\n    \n    Vector6 LambertState( 6 );\n    array3 minLambertDepVel = targeter.get_v1( )[ minimumDeltaVIndex ];                    \n    for( int i = 0; i < 3; i++ )\n    {\n        LambertState[ i ] = departurePosition[ i ] * 1000.0; // metre\n        LambertState[ i + 3 ] = minLambertDepVel[ i ] * 1000.0; // metre/sec\n    }\n\n    array3 LambertPropPosition;\n    array3 LambertPropVelocity;\n    for ( int i = 0; i < 3; i++ )\n    {\n        LambertPropPosition[ i ] = LambertState[ i ] / 1000.0; // km\n        LambertPropVelocity[ i ] = LambertState[ i + 3 ] / 1000.0; // km/s\n    }\n\n    const Real tolerance = 10.0 * std::numeric_limits< Real >::epsilon( );\n    Vector6 LambertKep = astro::convertCartesianToKeplerianElements( LambertState, muEarth, tolerance );\n\n    for( int j = 0; j < 3; j++ )\n    {\n        departureVelocityGuess[ j ] = minIndexDepartureVelocity[ j ];\n        atomDeparturePosition[ j ] = departurePosition[ j ];\n        atomArrivalPosition[ j ] = arrivalPosition[ j ];\n    }\n\n    array3 atomDepartureVelocity;\n    array3 atomArrivalVelocity;\n                            \n    std::string SolverStatusSummary;\n    int numberOfIterations;\n    const int maxIterations = 100;\n    const Tle referenceTle = Tle( );\n                            \n    try\n    {\n        Vector3 outputDepartureVelocity( 3 );\n        Vector3 outputArrivalVelocity( 3 );\n        atom::executeAtomSolver< Real, Vector3 >( atomDeparturePosition, \n                                                           departureEpoch, \n                                                           atomArrivalPosition, \n                                                           TOF, \n                                                           departureVelocityGuess,\n                                                           outputDepartureVelocity,\n                                                           outputArrivalVelocity, \n                                                           SolverStatusSummary, \n                                                           numberOfIterations, \n                                                           referenceTle, \n                                                           kMU, \n                                                           kXKMPER, \n                                                           1.0e-10, \n                                                           1.0e-5, \n                                                           maxIterations );\n                            \n        \n        Vector6 atomDepartureState( 6 );\n        Vector6 atomArrivalState( 6 );\n\n        for( int i = 0; i < 3; i++ )\n        {\n            atomDepartureState[ i ] = atomDeparturePosition[ i ];\n            atomDepartureState[ i + 3 ] = outputDepartureVelocity[ i ];\n            atomArrivalState[ i ] = atomArrivalPosition[ i ];\n            atomArrivalState[ i + 3 ] = outputArrivalVelocity[ i ];\n        }\n\n        Tle transferTLE = atom::convertCartesianStateToTwoLineElements< Real, Vector6>( atomDepartureState, departureEpoch );\n\n        // std::cout << \"Transfer orbit TLE:\" << testDepartureTLE << std::endl << std::endl;\n        // std::cout << \"Departure object TLE:\" << departureObject << std::endl << std::endl;\n\n        // Generate Ephemeris for the transfer orbit obtained from the ATOM solver\n        Real TimeStep = TOF/1000.0;\n        Real EphemerisJD = 0.0;\n        SGP4 sgp4Ephemeris( transferTLE );\n        Real tsince = 0.0;\n\n        \n        ephemerisfile << \"jd\" << \",\" << \"x\" << \",\" << \"y\" << \",\" << \"z\" << \",\" << \"xdot\" << \",\" << \"ydot\" << \",\" << \"zdot\" << \",\";\n        ephemerisfile << \"lx\" << \",\" << \"ly\" << \",\" << \"lz\" << \",\" << \"lxdot\" << \",\" << \"lydot\" << \",\" << \"lzdot\" << std::endl;\n        \n        osculatingfile << \"jd\" << \",\" << \"a\" << \",\" << \"e\" << \",\" << \"i\" << \",\" << \"aop\" << \",\" << \"raan\" << \",\" << \"TA\" << \",\";\n        osculatingfile << \"raan_dot_moon\" << \",\" << \"raan_dot_sun\" << \",\" << \"raan_dot_3b\" << \",\" << \"raan_dot_j2\" << \",\" << \"raan_dot_total\" << \",\" << \"aop_dot_moon\" << \",\";\n        osculatingfile << \"aop_dot_sun\" << \",\" << \"aop_dot_3b\" << \",\" << \"aop_dot_j2\" << \",\" << \"aop_dot_total\" << \",\";\n        osculatingfile << \"La\" << \",\" << \"Le\" << \",\" << \"Li\" << \",\" << \"Laop\" << \",\" << \"Lraan\" << \",\" << \"LTA\" << std::endl; \n\n        \n        const Real j2 = 0.00108263;\n        Vector6 atomDepartureStateMetre( 6 );\n\n        for( int i = 0; i < 6; i++ )\n            atomDepartureStateMetre[ i ] = atomDepartureState[ i ] * 1000;\n\n        Vector6 nominalTransferKeplerian = astro::convertCartesianToKeplerianElements( atomDepartureStateMetre, muEarth, tolerance );\n        double p_a = nominalTransferKeplerian[ 0 ];\n        double p_a_km = p_a / 1000.0;\n        std::cout << \"semi major axis of transfer orbit = \" << p_a / 1000.0 << std::endl;\n        double p_e = nominalTransferKeplerian[ 1 ];\n        double p_i = nominalTransferKeplerian[ 2 ];\n        std::cout << \"inclination = \" << sml::convertRadiansToDegrees( p_i ) << std::endl;\n        double p_T = 2 * sml::SML_PI * std::sqrt( std::pow( p_a, 3 ) / muEarth );\n        std::cout << \"time period for transfer orbit = \" << p_T / 60 << std::endl;\n        double p_n = ( 24 * 60 * 60 ) / p_T;\n        std::cout << \"mean motion for transfer orbit = \" << p_n << std::endl;\n\n        double p_aop = sml::convertRadiansToDegrees( nominalTransferKeplerian[ 3 ] );\n        double p_raan = sml::convertRadiansToDegrees( nominalTransferKeplerian[ 4 ] );\n\n        double raan_dot_moon = -0.00338 * ( std::cos( p_i ) / p_n ) / 86400.0;\n        double raan_dot_sun = -0.00154 * ( std::cos( p_i ) / p_n ) / 86400.0;\n        double raan_dot_j2 = -1.5 * p_n * 360.0 * j2 * std::pow( ( Rearth / p_a_km ), 2 ) * std::cos( p_i ) / ( std::pow( (1 - std::pow( p_e, 2 ) ), 2 ) * 86400.0 );\n        double raan_dot_total = raan_dot_moon + raan_dot_sun + raan_dot_j2;\n        std::cout << \"raan_dot_total = \" << raan_dot_total * 86400.0 << std::endl;\n\n        double aop_dot_moon = 0.00169 * ( 4 - 5 * ( std::pow( std::sin( p_i ), 2 ) ) ) / ( p_n * 86400.0 );\n        double aop_dot_sun = 0.00077 * ( 4 - 5 * ( std::pow( std::sin( p_i ), 2 ) ) ) / ( p_n * 86400.0 );\n        double aop_dot_j2 = 0.75 * p_n * 360.0 * j2 * std::pow( ( Rearth / p_a_km ), 2 ) * ( 4 - 5 * ( std::pow( std::sin( p_i ), 2 ) ) ) \n                                                                        / ( std::pow( (1 - std::pow( p_e, 2 ) ), 2 ) * 86400.0 );\n        double aop_dot_total = aop_dot_moon + aop_dot_sun + aop_dot_j2;\n        std::cout << \"aop_dot_total = \" << aop_dot_total * 86400.0 << std::endl;\n                                                               \n        for( int i = 0; i < 1001; i++ )\n        {\n            Real t = i;\n            tsince = t * TimeStep;\n            DateTime EphemerisEpoch = departureEpoch; // departure epoch for the transfer orbit arc\n            EphemerisEpoch = EphemerisEpoch.AddSeconds( tsince ); \n\n            Eci AtomEphemeris = sgp4Ephemeris.FindPosition( EphemerisEpoch );\n                         \n            EphemerisJD = EphemerisEpoch.ToJulian( ); // convert to Julian date\n\n            Vector6 cart = getStateVectorInMetre( AtomEphemeris );\n            \n            //convert cartesian to keplerian elements using astro ( units are m and rads )\n            Vector6 osc = astro::convertCartesianToKeplerianElements( cart, muEarth, tolerance ); \n                                                                       \n\n            osculatingfile << EphemerisJD << \",\";\n            osculatingfile << osc[ 0 ] / 1000.0 << \",\";\n            osculatingfile << osc[ 1 ] << \",\";\n            osculatingfile << sml::convertRadiansToDegrees( osc[ 2 ] ) << \",\";\n            osculatingfile << sml::convertRadiansToDegrees( osc[ 3 ] ) << \",\";\n            osculatingfile << sml::convertRadiansToDegrees( osc[ 4 ] ) << \",\";\n            osculatingfile << sml::convertRadiansToDegrees( osc[ 5 ] ) << \",\";\n            osculatingfile << p_raan + raan_dot_moon * tsince << \",\";\n            osculatingfile << p_raan + raan_dot_sun * tsince << \",\";\n            osculatingfile << p_raan + ( raan_dot_sun + raan_dot_moon ) * tsince << \",\";\n            osculatingfile << p_raan + raan_dot_j2 * tsince << \",\";\n            osculatingfile << p_raan + raan_dot_total * tsince << \",\";\n            osculatingfile << p_aop + aop_dot_moon * tsince << \",\";\n            osculatingfile << p_aop + aop_dot_sun * tsince << \",\";\n            osculatingfile << p_aop + ( aop_dot_moon + aop_dot_sun ) * tsince << \",\";\n            osculatingfile << p_aop + aop_dot_j2 * tsince << \",\";\n            osculatingfile << p_aop + aop_dot_total * tsince << \",\";\n            osculatingfile << LambertKep[ 0 ] / 1000.0 << \",\";\n            osculatingfile << LambertKep[ 1 ] << \",\";\n            osculatingfile << sml::convertRadiansToDegrees( LambertKep[ 2 ] ) << \",\";\n            osculatingfile << sml::convertRadiansToDegrees( LambertKep[ 3 ] ) << \",\";\n            osculatingfile << sml::convertRadiansToDegrees( LambertKep[ 4 ] ) << \",\";\n            osculatingfile << sml::convertRadiansToDegrees( LambertKep[ 5 ] ) << std::endl;\n\n            kep_toolbox::propagate_lagrangian( LambertPropPosition, LambertPropVelocity, TimeStep, kMU );\n            for ( int j = 0; j < 3; j++ )\n            {\n                LambertState[ j ] = LambertPropPosition[ j ] * 1000.0; // metre\n                LambertState[ j + 3 ] = LambertPropVelocity[ j ] * 1000.0; // metre/sec\n            }\n            LambertKep = astro::convertCartesianToKeplerianElements( LambertState, muEarth, tolerance );\n\n            ephemerisfile << EphemerisJD << \",\";\n            ephemerisfile << AtomEphemeris.Position( ).x << \",\";\n            ephemerisfile << AtomEphemeris.Position( ).y << \",\";\n            ephemerisfile << AtomEphemeris.Position( ).z << \",\";\n            ephemerisfile << AtomEphemeris.Velocity( ).x << \",\";\n            ephemerisfile << AtomEphemeris.Velocity( ).y << \",\";\n            ephemerisfile << AtomEphemeris.Velocity( ).z << \",\";\n            ephemerisfile << LambertPropPosition[ 0 ] << \",\";\n            ephemerisfile << LambertPropPosition[ 1 ] << \",\";\n            ephemerisfile << LambertPropPosition[ 2 ] << \",\";\n            ephemerisfile << LambertPropVelocity[ 0 ] << \",\";\n            ephemerisfile << LambertPropVelocity[ 1 ] << \",\";\n            ephemerisfile << LambertPropVelocity[ 2 ] << std::endl;\n\n            if( i == 1000 )\n            {\n                std::cout << \"Difference in Actual Arrival Position and Final State taken from Trasnfer Orbit Ephemeris\" << std::endl;\n                std::cout << \"X axis Difference = \" << AtomEphemeris.Position( ).x - atomArrivalPosition[ 0 ] << std::endl;\n                std::cout << \"Y axis Difference = \" << AtomEphemeris.Position( ).y - atomArrivalPosition[ 1 ] << std::endl;\n                std::cout << \"Z axis Difference = \" << AtomEphemeris.Position( ).z - atomArrivalPosition[ 2 ] << std::endl << std::endl;\n            }\n        }\n\n        for( int k = 0; k < 3; k++)\n        {\n            atomDepartureVelocity[ k ] = outputDepartureVelocity[ k ];\n            atomArrivalVelocity[ k ] = outputArrivalVelocity[ k ];\n        }\n                                \n        array3 atomDepartureDeltaV;\n        array3 atomArrivalDeltaV;\n        Real AtomDeltaV;\n\n        atomDepartureDeltaV = sml::add( atomDepartureVelocity, sml::multiply( departureVelocity, -1.0 ) );\n        atomArrivalDeltaV = sml::add( atomArrivalVelocity, sml::multiply( arrivalVelocity, -1.0 ) );\n\n        AtomDeltaV = sml::norm< Real >( atomDepartureDeltaV ) + sml::norm< Real >( atomArrivalDeltaV );\n        std::cout << \"Atom DeltaV = \" << AtomDeltaV << std::endl;\n    }\n    \n    catch( const std::exception& err )   \n    {\n        ++failCount;\n        std::cout << \"Exception Caught = \" << err.what( ) << std::endl;\n        std::cout << \"For departure ID = \" << catchDepartureID << \" \" << \"For Arrival ID = \" << catchArrivalID << std::endl << std::endl;\n        // std::cout << \"Fail count = \" << failCount << std::endl;\n    }\n   \n   ephemerisfile.close( );\n   osculatingfile.close( ); \n   return EXIT_SUCCESS;\n}", "meta": {"hexsha": "0b15a09d2a45bc3a4ef47a59fcdefd6a1f171f1b", "size": 20971, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/napa_perturbations.cpp", "max_stars_repo_name": "agrawalabhishek/AtomScanner", "max_stars_repo_head_hexsha": "65ef8e5db2e46d4c95068233bc7f3ff67f2796f5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/napa_perturbations.cpp", "max_issues_repo_name": "agrawalabhishek/AtomScanner", "max_issues_repo_head_hexsha": "65ef8e5db2e46d4c95068233bc7f3ff67f2796f5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/napa_perturbations.cpp", "max_forks_repo_name": "agrawalabhishek/AtomScanner", "max_forks_repo_head_hexsha": "65ef8e5db2e46d4c95068233bc7f3ff67f2796f5", "max_forks_repo_licenses": ["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.9149888143, "max_line_length": 174, "alphanum_fraction": 0.5636354966, "num_tokens": 5653, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255927, "lm_q2_score": 0.6001883592602049, "lm_q1q2_score": 0.45653366068752427}}
{"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 *      Wikipedia. Geostationary orbit, http://en.wikipedia.org/wiki/Geostationary_orbit, last\n *          accessed: 22nd November, 2011.\n *      Keefe, T.J. Synodic Period Calculator, http://www.ccri.edu/physics/keefe/synodic_calc.htm,\n *          last accessed: 6th December, 2011, last modified: 18th November, 2011.\n *\n *    Notes\n *      The tests need to be updated to check benchmark values from literature.\n *\n */\n\n#define BOOST_TEST_MAIN\n\n#include <cmath>\n#include <limits>\n\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/unit_test.hpp>\n\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/astrodynamicsFunctions.h\"\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/physicalConstants.h\"\n\nnamespace tudat\n{\nnamespace unit_tests\n{\n\n//! Test suite for astrodynamics functions.\nBOOST_AUTO_TEST_SUITE( test_astrodynamics_functions )\n\n//! Test if the orbital period of a Kepler orbit is computed correctly.\nBOOST_AUTO_TEST_CASE( testKeplerOrbitalPeriod )\n{\n    // Declare and set satellite mass [kg].\n    double satelliteMass = 1.0e3;\n\n    // Declare and set gravitational parameter of Earth [m^3 s^-2].\n    double earthGravitationalParameter\n            = physical_constants::GRAVITATIONAL_CONSTANT * 5.9736e24;\n\n    // Declare and set distance between Earth center and satellite.\n    double distanceBetweenSatelliteAndEarth = 4.2164e7;\n\n    // Compute orbital period of satellite.\n    double orbitalPeriod = basic_astrodynamics::computeKeplerOrbitalPeriod(\n                distanceBetweenSatelliteAndEarth, earthGravitationalParameter, satelliteMass );\n\n    // Declare and set expected orbital period [s].\n    double expectedOrbitalPeriod = 86164.09054;\n\n    // Check if computed orbital period matches expected orbital period.\n    BOOST_CHECK_CLOSE_FRACTION( orbitalPeriod, expectedOrbitalPeriod, 1.0e-5 );\n}\n\n//! Test if the orbital distance of a Kepler orbit is computed correctly.\nBOOST_AUTO_TEST_CASE( testKeplerRadialDistance )\n{\n    // Declare and set Keplerian elements.\n    Eigen::Vector6d keplerianElements = Eigen::Vector6d::Constant( TUDAT_NAN );\n    keplerianElements[ 0 ] = 25999.683025291e3;\n    keplerianElements[ 1 ] = 0.864564003552322;\n    keplerianElements[ 5 ] = 0.757654217738482;\n\n    // Compute radial distance of the satellite.\n    double radialDistance1 = basic_astrodynamics::computeKeplerRadialDistance(\n                keplerianElements[ 0 ], keplerianElements[ 1 ], keplerianElements[ 5 ] );\n    double radialDistance2 = basic_astrodynamics::computeKeplerRadialDistance( keplerianElements );\n\n    // Declare and set expected radial distance [m].\n    double expectedRadialDistance = 4032815.56442827;\n\n    // Check if computed distance matches expected distance.\n    BOOST_CHECK_CLOSE_FRACTION( radialDistance1, expectedRadialDistance, 1.0e-5 );\n    BOOST_CHECK_CLOSE_FRACTION( radialDistance2, expectedRadialDistance, 1.0e-5 );\n}\n\n//! Test if the orbital angular momentum of a kepler orbit is computed correctly.\nBOOST_AUTO_TEST_CASE( testKeplerAngularMomentum )\n{\n    // Reference: http://en.wikipedia.org/wiki/Geostationary_orbit.\n    // Declare and set satellite mass [kg].\n    double satelliteMass = 1.0e3;\n\n    // Declare and set gravitational parameter of Earth [m^3 s^-2].\n    double earthGravitationalParameter\n            = physical_constants::GRAVITATIONAL_CONSTANT * 5.9736e24;\n\n    // Declare and set distance between Earth center and satellite.\n    double distanceBetweenSatelliteAndEarth = 4.2164e7;\n\n    // Declare and set eccentricity of satellite orbit.\n    double eccentricityOfSatelliteOrbit = 0.0;\n\n    // Compute Kepler angular momentum.\n    double angularMomentum = basic_astrodynamics::computeKeplerAngularMomentum(\n                distanceBetweenSatelliteAndEarth, eccentricityOfSatelliteOrbit,\n                earthGravitationalParameter, satelliteMass );\n\n    // Declare and set expected angular momentum.\n    // The expected angular momentum is computed using the fact that for a circular orbit,\n    // H = mRV. This is an independent check of the code, which computes angular\n    // momentum differently.\n    double expectedAngularMomentum = satelliteMass * distanceBetweenSatelliteAndEarth\n            * std::sqrt( earthGravitationalParameter / distanceBetweenSatelliteAndEarth );\n\n    // Check if computed angular momentum matches expected angular momentum.\n    BOOST_CHECK_CLOSE_FRACTION( angularMomentum, expectedAngularMomentum,\n                                std::numeric_limits< double >::epsilon( ) );\n}\n\n//! Test if the orbital velocity of a Kepler orbit is computed correctly.\nBOOST_AUTO_TEST_CASE( testKeplerOrbitalVelocity )\n{\n    // Declare and set Keplerian elements.\n    Eigen::Vector6d keplerianElements = Eigen::Vector6d::Constant( TUDAT_NAN );\n    keplerianElements[ 0 ] = 25999.683025291e3;\n    keplerianElements[ 1 ] = 0.864564003552322;\n    keplerianElements[ 5 ] = 0.757654217738482;\n\n    // Declare and set gravitational parameter of Earth [m^3 s^-2].\n    double earthGravitationalParameter = physical_constants::GRAVITATIONAL_CONSTANT * 5.9736e24;\n\n    // Compute radial distance of the satellite.\n    double orbitalVelocity1 = basic_astrodynamics::computeKeplerOrbitalVelocity(\n                keplerianElements[ 0 ], keplerianElements[ 1 ], keplerianElements[ 5 ], earthGravitationalParameter );\n    double orbitalVelocity2 = basic_astrodynamics::computeKeplerOrbitalVelocity(\n                keplerianElements, earthGravitationalParameter );\n\n    // Declare and set expected orbital velocity [m/s].\n    double expectedOrbitalVelocity = 13503.4992923871;\n\n    // Check if computed distance matches expected distance.\n    BOOST_CHECK_CLOSE_FRACTION( orbitalVelocity1, expectedOrbitalVelocity, 1.0e-5 );\n    BOOST_CHECK_CLOSE_FRACTION( orbitalVelocity2, expectedOrbitalVelocity, 1.0e-5 );\n}\n\n//! Test if the mean motion of a kepler orbit is computed correctly.\nBOOST_AUTO_TEST_CASE( testMeanMotion )\n{\n    // Declare and set satellite mass [kg].\n    double satelliteMass = 1.0e3;\n\n    // Declare and set gravitational parameter of Earth [m^3 s^-2].\n    double earthGravitationalParameter\n            = physical_constants::GRAVITATIONAL_CONSTANT * 5.9736e24;\n\n    // Declare and set distance between Earth center and satellite.\n    double distanceBetweenSatelliteAndEarth = 4.2164e7;\n\n    // Reference: http://en.wikipedia.org/wiki/Geostationary_orbit.\n    double meanMotion = basic_astrodynamics::computeKeplerMeanMotion(\n                distanceBetweenSatelliteAndEarth, earthGravitationalParameter, satelliteMass );\n\n    // Declare and set expected mean motion [rad/s].\n    double expectedMeanMotion = 7.2921e-5;\n\n    // Check if computed mean motion matches expected mean motion.\n    BOOST_CHECK_CLOSE_FRACTION( meanMotion, expectedMeanMotion, 1.0e-7 );\n}\n\n//! Test if the orbital energy of a Kepler orbit is computed correctly.\nBOOST_AUTO_TEST_CASE( testKeplerEnergy )\n{\n    // Declare and set satellite mass [kg].\n    double satelliteMass = 1.0e3;\n\n    // Declare and set gravitational parameter of Earth [m^3 s^-2].\n    double earthGravitationalParameter\n            = physical_constants::GRAVITATIONAL_CONSTANT * 5.9736e24;\n\n    // Declare and set distance between Earth center and satellite.\n    double distanceBetweenSatelliteAndEarth = 4.2164e7;\n\n    // Compute Kepler energy.\n    double orbitalEnergy = basic_astrodynamics::computeKeplerEnergy(\n                distanceBetweenSatelliteAndEarth, earthGravitationalParameter, satelliteMass );\n\n    // Declare and set expected orbital energy.\n    // The expected orbital energy is computed using the fact that for a circular orbit,\n    // E = m ( V^2/2 - mu/R ). This is an independent check of the code, which computes orbital\n    // energy differently.\n    double expectedOrbitalEnergy = satelliteMass * (\n                0.5 * earthGravitationalParameter / distanceBetweenSatelliteAndEarth\n                -  earthGravitationalParameter / distanceBetweenSatelliteAndEarth );\n\n    // Check if computed orbital energy matches expected orbital energy.\n    BOOST_CHECK_CLOSE_FRACTION( orbitalEnergy, expectedOrbitalEnergy,\n                                std::numeric_limits< double >::epsilon( ) );\n\n}\n\n//! Test if the synodic period between two orbits is computed correctly.\nBOOST_AUTO_TEST_CASE( testSynodicPeriod )\n{\n    // Compute synodic period between Earth and Mars.\n    double synodicPeriod = basic_astrodynamics::computeSynodicPeriod( 365.256378, 686.95 );\n\n    // Declare and set expected synodic period.\n    double expectedSynodicPeriod = 779.9746457736733;\n\n    // Check if computed synodic period matches expected synodic period.\n    BOOST_CHECK_CLOSE_FRACTION( synodicPeriod, expectedSynodicPeriod,\n                                std::numeric_limits< double >::epsilon( ) );\n}\n\n//! Test if the periapsis altitude is computed correctly.\nBOOST_AUTO_TEST_CASE( testPeriapsisAltitude )\n{\n    // Keplerian state\n    Eigen::Vector6d keplerianState;\n    keplerianState << 10000.0, 0.4, 0.0, 0.0, 0.0, 3.0;\n\n    // Cartesian state, equivalent to keplerianState\n    Eigen::Vector6d cartesianState;\n    cartesianState << -1.376803915331821e4, 1.962586386216818e3, 0.0, -3.074098913804636e4, -1.285214845072070e5, 0.0;\n\n    // Body radius\n    const double centralBodyRadius = 1000.0;\n\n    // Body gravitational parameter\n    const double centralBodyGravitationalParameter = 3.9860044189e14;\n\n    // Declare and set expected periapsis altitude.\n    const double expectedPeriapsisAltitude = 5000.0;\n\n    // Compute periapsis altitude from Keplerian state.\n    const double periapsisAltitudeFromKeplerian = basic_astrodynamics::computePeriapsisAltitudeFromKeplerianState(\n                keplerianState, centralBodyRadius );\n\n    // Compute periapsis altitude from Cartesian state.\n    const double periapsisAltitudeFromCartesian = basic_astrodynamics::computePeriapsisAltitudeFromCartesianState(\n                cartesianState, centralBodyGravitationalParameter, centralBodyRadius );\n\n    // Check if computed periapsis altitude from Keplerian is right.\n    BOOST_CHECK_CLOSE_FRACTION( periapsisAltitudeFromKeplerian, expectedPeriapsisAltitude,\n                                std::numeric_limits< double >::epsilon( ) );\n\n    // Check if computed periapsis altitude from Cartesian is right.\n    BOOST_CHECK_CLOSE_FRACTION( periapsisAltitudeFromCartesian, expectedPeriapsisAltitude,\n                                std::numeric_limits< double >::epsilon( ) );\n}\n\nBOOST_AUTO_TEST_SUITE_END( )\n\n} // namespace unit_tests\n} // namespace tudat\n", "meta": {"hexsha": "998a00e75b93db9ebb6ffec14243b19e67675458", "size": 11061, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/BasicAstrodynamics/UnitTests/unitTestAstrodynamicsFunctions.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/BasicAstrodynamics/UnitTests/unitTestAstrodynamicsFunctions.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/BasicAstrodynamics/UnitTests/unitTestAstrodynamicsFunctions.cpp", "max_forks_repo_name": "ViktorJordanov/tudat", "max_forks_repo_head_hexsha": "069ceeab8f12405c356e19f50d6df037914df85c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.5423076923, "max_line_length": 118, "alphanum_fraction": 0.7358285869, "num_tokens": 2712, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397349, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.456527600770514}}
{"text": "#include <cmath>\n#include <iostream>\n\n#include <boost/python/list.hpp>\n#include <boost/python/tuple.hpp>\n#include <boost/python/extract.hpp>\n\n#include <scitbx/matrix/eigensystem.h>\n#include <mmtbx/tls/utils.h>\n#include <mmtbx/tls/optimise_amplitudes.h>\n\nnamespace mmtbx { namespace tls { namespace optimise {\n\ntemplate <typename T>\nT find_max(const af::shared<T> &array)\n{\n  T max_val = array[0];\n  for (size_t i=1; i<array.size(); i++)\n  {\n    if (max_val < array[i]) { max_val = array[i]; }\n  }\n  return max_val;\n};\n\nbool is_zero(const sym s, double tol=1e-12)\n{\n  if (\n      (std::abs(s[0])<tol) &&\n      (std::abs(s[1])<tol) &&\n      (std::abs(s[2])<tol) &&\n      (std::abs(s[3])<tol) &&\n      (std::abs(s[4])<tol) &&\n      (std::abs(s[5])<tol)\n      )\n  {\n    return true;\n  }\n  return false;\n}\n\n//! Main constructor\nMultiGroupMultiDatasetUijAmplitudeFunctionalAndGradientCalculator::MultiGroupMultiDatasetUijAmplitudeFunctionalAndGradientCalculator(\n    const symArrNd &target_uijs,\n    const dblArrNd &target_weights,\n    const dblArr1d &base_amplitudes,\n    const bp::list &base_uijs,\n    const bp::list &base_atom_indices,\n    const selArr1d &dataset_hash,\n    const symArr1d &residual_uijs ) :\n  target_uijs(target_uijs),\n  target_weights(target_weights),\n  dataset_hash(dataset_hash),\n  residual_uijs(residual_uijs),\n  n_dst(target_uijs.accessor().all()[0]),\n  n_atm(target_uijs.accessor().all()[1]),\n  n_base(base_amplitudes.size()),\n  n_total(base_amplitudes.size() + residual_uijs.size()),\n  residual_mask_total(0),\n  n_call(0)\n{\n  std::ostringstream errMsg;\n  // Check target uijs\n  if (target_uijs.accessor().nd() != 2) {\n    errMsg << \"invalid target_uijs: must be 2-dimensional flex array (currently \" << target_uijs.accessor().nd() << \")\";\n    throw std::invalid_argument( errMsg.str() );\n  }\n  // Check weights\n  if (target_uijs.accessor().nd() != target_weights.accessor().nd())\n  {\n    errMsg << \"invalid dimension of target_weights (dimension \" << target_weights.accessor().nd() << \"): must be same dimension as target_uijs (dimension \" << target_uijs.accessor().nd() << \")\";\n    throw std::invalid_argument( errMsg.str() );\n  }\n  for (size_t i=0; i<target_uijs.accessor().nd(); i++)\n  {\n    if (target_uijs.accessor().all()[i] != target_weights.accessor().all()[i])\n    {\n      errMsg << \"incompatible dimension of target_weights (axis \" << i << \"): must be same size as target_uijs (\" << target_weights.accessor().all()[i] << \" != \" << target_uijs.accessor().all()[i] <<\")\";\n      throw std::invalid_argument( errMsg.str() );\n    }\n  }\n  // Check base_amplitudes, base_uijs and base_atom_indices (common error message)\n  errMsg << \"invalid input base components. \"\n    << \"base_amplitudes (length \" << base_amplitudes.size()\n    << \"), base_uijs (length \" << bp::len(base_uijs)\n    << \") and base_atom_indices (length \" << bp::len(base_atom_indices)\n    << \") must all be the same length\";\n  if (base_amplitudes.size() != n_base) { throw std::invalid_argument( errMsg.str() ); }\n  if (bp::len(base_uijs) != n_base) { throw std::invalid_argument( errMsg.str() ); }\n  if (bp::len(base_atom_indices) != n_base) { throw std::invalid_argument( errMsg.str() ); }\n  errMsg.str(\"\"); // clear the previous error message\n  // Unpack base_uijs and base_atom_indicess\n  base_u.reserve(bp::len(base_uijs));\n  base_i.reserve(bp::len(base_atom_indices));\n  for (std::size_t i = 0; i < n_base; ++i)\n  {\n    symArr1d* atm_u = new symArr1d(bp::extract<symArr1d>(base_uijs[i]));\n    selArr1d* atm_i = new selArr1d(bp::extract<selArr1d>(base_atom_indices[i]));\n\n    if (atm_u->size() != atm_i->size())\n    {\n      errMsg << \"incompatible pair (element \" << i << \") in base_uijs/base_atom_indices: pairwise elements must be the same length (\" << atm_u->size() << \" and \" << atm_i->size() << \")\";\n      throw std::invalid_argument( errMsg.str() );\n    }\n    if (find_max(*atm_i) >= n_atm)\n    {\n      errMsg << \"invalid selection in base_atom_indices (\" << find_max(*atm_i) << \"): attempting to select atom outside of array (size \" << n_atm << \")\";\n      throw std::invalid_argument( errMsg.str() );\n    }\n\n    base_u.push_back(atm_u);\n    base_i.push_back(atm_i);\n  }\n  // Check dataset hash\n  if (dataset_hash.size() != n_base) {\n    errMsg << \"invalid dataset_hash (length \" << dataset_hash.size() << \"): must be same length as base_amplitudes, base_uijs & base_atom_indices (length \" << base_amplitudes.size() << \")\";\n    throw std::invalid_argument( errMsg.str() );\n  }\n  if (find_max(dataset_hash) >= n_dst)\n  {\n    errMsg << \"invalid value in dataset_hash (\" << find_max(dataset_hash) << \"): attempts to select element outside range of target_uijs (size \" << n_dst << \")\";\n    throw std::invalid_argument( errMsg.str() );\n  }\n  for (size_t i_dst=0; i_dst < n_dst; i_dst++)\n  {\n    bool found = false;\n    for (size_t i_base=0; i_base < n_base; i_base++)\n    {\n      if (dataset_hash[i_base] == i_dst)\n      {\n        found = true;\n        break;\n      }\n    }\n    if (found == false)\n    {\n      errMsg << \"Dataset index \" << i_dst << \" is not present in dataset_hash -- this dataset has no base elements associated with it.\";\n      throw std::invalid_argument( errMsg.str() );\n    }\n  }\n  // Check residual uijs\n  if (residual_uijs.size() != n_atm)\n  {\n    errMsg << \"invalid size of residual_uijs (\" << residual_uijs.size() << \"): must match 2nd dimension of target_uijs (\" << n_atm << \")\";\n    throw std::invalid_argument( errMsg.str() );\n  }\n\n  // ==========================\n  // Assign class members\n  // ==========================\n\n  // Initialise residual amplitude array\n  dblArr1d res_amplitudes(n_atm, 1.0);\n\n  // Concatenate amplitude arrays\n  initial_amplitudes.reserve(n_total);\n  std::copy(base_amplitudes.begin(), base_amplitudes.end(), std::back_inserter(initial_amplitudes));\n  std::copy(res_amplitudes.begin(), res_amplitudes.end(), std::back_inserter(initial_amplitudes));\n  // Copy to current values\n  current_amplitudes = dblArr1d(initial_amplitudes);\n\n  // Total Uijs (summed over levels) (datasets * atoms)\n  total_uijs = symArrNd(af::flex_grid<>(n_dst, n_atm), sym(0.,0.,0.,0.,0.,0.));\n\n  // Initialise blank residual mask\n  setResidualMask(blnArr1d(n_dst, true));\n}\n\ndblArr1d MultiGroupMultiDatasetUijAmplitudeFunctionalAndGradientCalculator::getCurrentAmplitudes()\n{\n  return current_amplitudes;\n}\n\nvoid MultiGroupMultiDatasetUijAmplitudeFunctionalAndGradientCalculator::setCurrentAmplitudes(const dblArr1d &values)\n{\n  if (values.size() != current_amplitudes.size()) {\n    std::ostringstream errMsg;\n    errMsg << \"Input array (size \" << values.size() << \") must be the same length as current_amplitudes (size \" << current_amplitudes.size() << \")\";\n    throw std::invalid_argument( errMsg.str() );\n  }\n  for (size_t i=0; i<current_amplitudes.size(); i++)\n  {\n    current_amplitudes[i] = values[i];\n  }\n}\n\nvoid MultiGroupMultiDatasetUijAmplitudeFunctionalAndGradientCalculator::printCurrentAmplitudes()\n{\n  for (size_t i=0; i<current_amplitudes.size(); i++)\n  {\n    std::cout << i << \" - \" << current_amplitudes[i] << std::endl;\n  }\n}\n\nvoid MultiGroupMultiDatasetUijAmplitudeFunctionalAndGradientCalculator::setResidualMask(const blnArr1d &mask)\n{\n  if (mask.size() != n_dst) {\n    std::ostringstream errMsg;\n    errMsg << \"Input array (size \" << mask.size() << \") must be the same length as number of datasets (\" << n_dst << \")\";\n    throw std::invalid_argument( errMsg.str() );\n  }\n  residual_mask = blnArr1d(mask);\n  residual_mask_total = 0;\n  for (size_t i=0; i<residual_mask.size(); i++)\n  {\n    residual_mask_total += (int)residual_mask[i];\n  }\n}\n\nbp::tuple MultiGroupMultiDatasetUijAmplitudeFunctionalAndGradientCalculator::computeFunctionalAndGradients()\n{\n  // Reset everything\n  zero();\n\n  n_call++;\n\n  // Reset negative amplitudes\n  //\n  sanitise_current_amplitudes();\n\n  // Apply amplitudes to base uijs\n  //\n  calculate_total_uijs();\n\n  // Calculate least-squares component of target function\n  //\n  calculate_f_g_least_squares();\n\n  // Return as python tuple for optimiser\n  //\n  return bp::make_tuple(functional, gradients);\n}\n\nvoid MultiGroupMultiDatasetUijAmplitudeFunctionalAndGradientCalculator::zero()\n{\n  // Reset functional and gradients\n  functional = 0.0;\n  gradients = dblArr1d(n_total, 0.0);\n\n  // Zero-out the level uijs\n  memset(&total_uijs[0], 0.0, sizeof(sym) * total_uijs.size());\n}\n\nvoid MultiGroupMultiDatasetUijAmplitudeFunctionalAndGradientCalculator::sanitise_current_amplitudes()\n{\n  // Set negative amplitudes to zero\n  for (size_t i_opt=0; i_opt<current_amplitudes.size(); i_opt++)\n  {\n    if (current_amplitudes[i_opt] < 0.0)\n    {\n      // Constrain the value to be zero (and thereby negate any benefit to the functional that could have been gained)\n      current_amplitudes[i_opt] = 0.0;\n    }\n  }\n}\n\nvoid MultiGroupMultiDatasetUijAmplitudeFunctionalAndGradientCalculator::calculate_total_uijs()\n{\n  // ==========================================================\n  // Sum over amplitudes to generate totals - !!! BASE TERMS !!!\n  //\n  for (size_t i_base=0; i_base<n_base; i_base++)\n  {\n    symArr1d &base_u_atom = *(base_u[i_base]);\n    selArr1d &base_i_atom = *(base_i[i_base]);\n    size_t i_dst = dataset_hash[i_base];\n    size_t i_opt = i_base;\n\n    // Iterate through atoms associated with this base element\n    for (size_t i_atm_x=0; i_atm_x<base_u_atom.size(); i_atm_x++)\n    {\n      // apply multipliers\n      sym m = current_amplitudes[i_opt] * base_u_atom[i_atm_x];\n      // Skip if null\n      if (is_zero(m))\n      {\n        continue;\n      }\n      // Add to total uijs\n      total_uijs(i_dst, base_i_atom[i_atm_x]) += m;\n    }\n  }\n  //\n  // Sum over amplitudes to generate totals - !!! RESIDUAL TERMS !!!\n  //\n  for (size_t i_atm=0; i_atm<n_atm; i_atm++)\n  {\n    size_t i_opt = n_base + i_atm;\n    sym m = current_amplitudes[i_opt] * residual_uijs[i_atm];\n    for (size_t i_dst=0; i_dst<n_dst; i_dst++)\n    {\n      total_uijs(i_dst, i_atm) += m;\n    }\n  }\n  // ==========================================================\n}\n\nvoid MultiGroupMultiDatasetUijAmplitudeFunctionalAndGradientCalculator::calculate_f_g_least_squares()\n{\n  // Normalisation term (number of datasets)\n  double norm_all = 1. / (double)(n_dst * n_atm);\n\n  // Normalisation term for residual level\n  double norm_res = 0.0; // if unchanged, residual level will not be optimised\n  if (residual_mask_total > 0)\n  {\n    // Upweights by term n_all/n_calc to simulate being calculated over all datasets\n    norm_res = norm_all * (double)(n_dst) / (double)(residual_mask_total);\n  }\n\n  // ==========================================================\n  // Calculate functional and gradients\n  for (size_t i_dst=0; i_dst<n_dst; i_dst++)\n  {\n    // Extract weights for this dataset\n    dblArr1d d_wgts(&target_weights(i_dst,0), &target_weights(i_dst, n_atm));\n    // Extract total uijs for this dataset\n    symArr1d d_total(&total_uijs(i_dst,0), &total_uijs(i_dst, n_atm));\n\n    // Calculate difference to target\n    symArr1d d_diffs(n_atm); // all elements will be populated\n    for (size_t i_atm=0; i_atm<n_atm; i_atm++)\n    {\n      sym d_diff_i = target_uijs(i_dst,i_atm) - total_uijs(i_dst,i_atm);\n      d_diffs[i_atm] = d_diff_i;\n\n      // Calculate functional -- least-squares component\n      for (size_t i_elem=0; i_elem<6; i_elem++)\n      {\n        functional += (\n            d_diff_i[i_elem] *\n            d_diff_i[i_elem] *\n            d_wgts[i_atm] *\n            norm_all\n            );\n      }\n    }\n\n    // Calculate gradients -- BASE TERMS\n    for (size_t i_base=0; i_base<n_base; i_base++)\n    {\n      // Only calculte if this base term is related to this dataset\n      if (i_dst != dataset_hash[i_base])\n      {\n        continue;\n      }\n\n      // i_ relative to full length of amplitudes\n      size_t i_opt = i_base;\n\n      // Extract the base elements\n      symArr1d &base_u_atom = *(base_u[i_base]);\n      selArr1d &base_i_atom = *(base_i[i_base]);\n\n      // Iterate through the atoms in the base element\n      for (size_t i_atm_x=0; i_atm_x<base_i_atom.size(); i_atm_x++)\n      {\n        // i_atm relative to n_atm\n        size_t i_atm = base_i_atom[i_atm_x];\n\n        // Extract the uij for this base element\n        sym base_sym = base_u_atom[i_atm_x];\n\n        // Skip this atom if the base_uij is zero at this position\n        if (is_zero(base_sym))\n        {\n          continue;\n        }\n\n        // Corresponding u_diff\n        sym diff_sym = d_diffs[i_atm];\n\n        // Gradient from least-squares\n        // -2*base*diffs*wgts\n        for (size_t i_elem=0; i_elem<6; i_elem++)\n        {\n          gradients[i_opt] += (\n              -2.0 *\n              base_sym[i_elem] *\n              diff_sym[i_elem] *\n              d_wgts[i_atm] *\n              norm_all\n              );\n        }\n      }\n    }\n\n    // Calculate gradients -- RESIDUAL TERMS\n    if (residual_mask[i_dst])\n    {\n      for (size_t i_atm=0; i_atm<n_atm; i_atm++)\n      {\n        size_t i_opt = n_base + i_atm;\n\n        // Extract the uij for this base element\n        sym base_sym = residual_uijs[i_atm];\n\n        // Skip this atom if the base_uij is zero at this position\n        if (is_zero(base_sym))\n        {\n          continue;\n        }\n\n        // Corresponding u_diff\n        sym diff_sym = d_diffs[i_atm];\n\n        // Gradient from least-squares\n        // -2*base*diffs*wgts\n        for (size_t i_elem=0; i_elem<6; i_elem++)\n        {\n          gradients[i_opt] += (\n              -2.0 *\n              base_sym[i_elem] *\n              diff_sym[i_elem] *\n              d_wgts[i_atm] *\n              norm_res\n              );\n        }\n      }\n    }\n  }\n}\n\n} } } // close namepsace mmtbx/tls/optimise\n", "meta": {"hexsha": "80da2d1d0ded064fdb03f3899470e7ecd841568b", "size": 13652, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mmtbx/tls/optimise_amplitudes.cpp", "max_stars_repo_name": "hbrunie/cctbx_project", "max_stars_repo_head_hexsha": "2d8cb383d50fe20cdbbe4bebae8ed35fabce61e5", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-03-18T12:31:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T06:27:06.000Z", "max_issues_repo_path": "mmtbx/tls/optimise_amplitudes.cpp", "max_issues_repo_name": "hbrunie/cctbx_project", "max_issues_repo_head_hexsha": "2d8cb383d50fe20cdbbe4bebae8ed35fabce61e5", "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": "mmtbx/tls/optimise_amplitudes.cpp", "max_forks_repo_name": "hbrunie/cctbx_project", "max_forks_repo_head_hexsha": "2d8cb383d50fe20cdbbe4bebae8ed35fabce61e5", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-04T15:39:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-04T15:39:06.000Z", "avg_line_length": 32.1981132075, "max_line_length": 203, "alphanum_fraction": 0.6334602989, "num_tokens": 3772, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397349, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.4565276007705139}}
{"text": "//============================================================================\n// Name        : test_rng.cpp\n// Author      : Mikail Sheikh\n// Date        : 28/11/2013\n// Copyright   : Distributed under the MIT License (MIT)\n// Description : A QuantLib wrapper for Boost random number generators\n//============================================================================\n\n#include \"boost_rng_bindings.hpp\"\n\n#include <ql/time/calendar.hpp>\n#include <ql/time/calendars/target.hpp>\n#include <ql/time/daycounter.hpp>\n#include <ql/time/daycounters/actual365fixed.hpp>\n#include <ql/option.hpp>\n#include <ql/exercise.hpp>\n#include <ql/quote.hpp>\n#include <ql/quotes/simplequote.hpp>\n#include <ql/termstructures/yieldtermstructure.hpp>\n#include <ql/termstructures/yield/flatforward.hpp>\n#include <ql/termstructures/volatility/equityfx/blackconstantvol.hpp>\n#include <ql/termstructures/volatility/equityfx/blackvoltermstructure.hpp>\n#include <ql/instruments/payoffs.hpp>\n#include <ql/instruments/vanillaoption.hpp>\n#include <ql/pricingengines/vanilla/mceuropeanengine.hpp>\n#include <ql/processes/blackscholesprocess.hpp>\n#include <ql/settings.hpp>\n#include <ql/handle.hpp>\n#include <ql/utilities/dataformatters.hpp>\n\n#include <boost/timer/timer.hpp>\n#include <boost/shared_ptr.hpp>\n\n#include <iostream>\n#include <iomanip>\n#include <ctime>\n\nint main()\n{\n\n  try\n  {\n    // set up dates\n    Calendar calendar = TARGET();\n    Date todaysDate(15, May, 1998);\n    Date settlementDate(17, May, 1998);\n    Settings::instance().evaluationDate() = todaysDate;\n\n    // our options\n    Option::Type type(Option::Put);\n    Real underlying = 36;\n    Real strike = 40;\n    Spread dividendYield = 0.00;\n    Rate riskFreeRate = 0.06;\n    Volatility volatility = 0.20;\n    Date maturity(17, May, 1999);\n    DayCounter dayCounter = Actual365Fixed();\n\n    std::cout << \"Option type = \" << type << std::endl;\n    std::cout << \"Maturity = \" << maturity << std::endl;\n    std::cout << \"Underlying price = \" << underlying << std::endl;\n    std::cout << \"Strike = \" << strike << std::endl;\n    std::cout << \"Risk-free interest rate = \" << io::rate(riskFreeRate)\n        << std::endl;\n    std::cout << \"Dividend yield = \" << io::rate(dividendYield) << std::endl;\n    std::cout << \"Volatility = \" << io::volatility(volatility) << std::endl;\n    std::cout << std::endl;\n    std::string method;\n    std::cout << std::endl;\n\n    // write column headings\n    Size widths[] =\n      { 35, 14 };\n    std::cout << std::setw(widths[0]) << std::left << \"Method\"\n        << std::setw(widths[1]) << std::left << \"European\" << std::endl;\n\n    boost::shared_ptr<Exercise> europeanExercise(\n        new EuropeanExercise(maturity));\n\n    Handle<Quote> underlyingH(\n        boost::shared_ptr<Quote>(new SimpleQuote(underlying)));\n\n    // bootstrap the yield/dividend/vol curves\n    Handle<YieldTermStructure> flatTermStructure(\n        boost::shared_ptr<YieldTermStructure>(\n            new FlatForward(settlementDate, riskFreeRate, dayCounter)));\n    Handle<YieldTermStructure> flatDividendTS(\n        boost::shared_ptr<YieldTermStructure>(\n            new FlatForward(settlementDate, dividendYield, dayCounter)));\n    Handle<BlackVolTermStructure> flatVolTS(\n        boost::shared_ptr<BlackVolTermStructure>(\n            new BlackConstantVol(settlementDate, calendar, volatility,\n                dayCounter)));\n    boost::shared_ptr<StrikedTypePayoff> payoff(\n        new PlainVanillaPayoff(type, strike));\n    boost::shared_ptr<BlackScholesMertonProcess> bsmProcess(\n        new BlackScholesMertonProcess(underlyingH, flatDividendTS,\n            flatTermStructure, flatVolTS));\n\n    // options\n    VanillaOption europeanOption(payoff, europeanExercise);\n\n    Real npv;\n    Size timeSteps;\n    Size mcSeed = 42;\n\n    // Monte Carlo Method: MC (crude)\n    timeSteps = 1;\n    method = \"MC (crude)\";\n    {\n      boost::timer::auto_cpu_timer timer;\n      boost::shared_ptr<PricingEngine> mcengine1;\n      mcengine1 = MakeMCEuropeanEngine<PseudoRandom>(bsmProcess).withSteps(\n          timeSteps).withAbsoluteTolerance(0.002).withSeed(mcSeed);\n      europeanOption.setPricingEngine(mcengine1);\n      npv = europeanOption.NPV();\n    }\n    // Real errorEstimate = europeanOption.errorEstimate();\n    std::cout << std::setw(widths[0]) << std::left << method << std::fixed\n        << std::setw(widths[1]) << std::left << npv << std::endl;\n\n    timeSteps = 1;\n    method = \"MC (crude MT11213b)\";\n    {\n      boost::timer::auto_cpu_timer timer;\n      boost::shared_ptr<PricingEngine> mcengine2;\n      mcengine2 =\n          MakeMCEuropeanEngine<PseudoRandomBoostMT11213b>(bsmProcess).withSteps(\n              timeSteps).withAbsoluteTolerance(0.002).withSeed(mcSeed);\n      europeanOption.setPricingEngine(mcengine2);\n      npv = europeanOption.NPV();\n    }\n    // Real errorEstimate = europeanOption.errorEstimate();\n    std::cout << std::setw(widths[0]) << std::left << method << std::fixed\n        << std::setw(widths[1]) << std::left << npv << std::endl;\n\n    timeSteps = 1;\n    method = \"MC (crude MT19937)\";\n    {\n      boost::timer::auto_cpu_timer timer;\n      boost::shared_ptr<PricingEngine> mcengine3;\n      mcengine3 =\n          MakeMCEuropeanEngine<PseudoRandomBoostMT19937>(bsmProcess).withSteps(\n              timeSteps).withAbsoluteTolerance(0.002).withSeed(mcSeed);\n      europeanOption.setPricingEngine(mcengine3);\n      npv = europeanOption.NPV();\n    }\n\n    std::cout << std::setw(widths[0]) << std::left << method << std::fixed\n        << std::setw(widths[1]) << std::left << npv << std::endl;\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": "8d8f4b91cb5eefcab5e57dd59b4ca1a6a15fc70b", "size": 5733, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QuantLib/BoostRandom/test_rng.cpp", "max_stars_repo_name": "vmyla/expressionParser3", "max_stars_repo_head_hexsha": "83bbc0908f70fee496664738305e48a3af12d871", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 51.0, "max_stars_repo_stars_event_min_datetime": "2015-02-03T19:47:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-04T02:13:39.000Z", "max_issues_repo_path": "QuantLib/BoostRandom/test_rng.cpp", "max_issues_repo_name": "zhaozhihua2008/cogitolearning-examples", "max_issues_repo_head_hexsha": "83bbc0908f70fee496664738305e48a3af12d871", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-06-01T19:27:02.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-01T19:27:02.000Z", "max_forks_repo_path": "QuantLib/BoostRandom/test_rng.cpp", "max_forks_repo_name": "zhaozhihua2008/cogitolearning-examples", "max_forks_repo_head_hexsha": "83bbc0908f70fee496664738305e48a3af12d871", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 85.0, "max_forks_repo_forks_event_min_datetime": "2015-01-18T18:29:09.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-05T13:40:45.000Z", "avg_line_length": 35.1717791411, "max_line_length": 80, "alphanum_fraction": 0.642421071, "num_tokens": 1501, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397349, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.4565276007705139}}
{"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//math_function \u5b9a\u4e49\u4e86caffe \u4e2d\u7528\u5230\u7684\u4e00\u4e9b\u77e9\u9635\u64cd\u4f5c\u548c\u6570\u503c\u8ba1\u7b97\u7684\u4e00\u4e9b\u51fd\u6570\n\n/* \n *\u529f\u80fd\uff1a C=alpha*A*B+beta*C \n *A,B,C \u662f\u8f93\u5165\u77e9\u9635\uff08\u4e00\u7ef4\u6570\u7ec4\u683c\u5f0f\uff09 \n *CblasRowMajor :\u6570\u636e\u662f\u884c\u4e3b\u5e8f\u7684\uff08\u4e8c\u7ef4\u6570\u636e\u4e5f\u662f\u7528\u4e00\u7ef4\u6570\u7ec4\u50a8\u5b58\u7684\uff09 \n *TransA, TransB\uff1a\u662f\u5426\u8981\u5bf9A\u548cB\u505a\u8f6c\u7f6e\u64cd\u4f5c\uff08CblasTrans CblasNoTrans\uff09 \n *M\uff1a A\u3001C \u7684\u884c\u6570 \n *N\uff1a B\u3001C \u7684\u5217\u6570 \n *K\uff1a A \u7684\u5217\u6570\uff0c B \u7684\u884c\u6570 \n *lda \uff1a A\u7684\u5217\u6570\uff08\u4e0d\u505a\u8f6c\u7f6e\uff09\u884c\u6570\uff08\u505a\u8f6c\u7f6e\uff09 \n *ldb\uff1a B\u7684\u5217\u6570\uff08\u4e0d\u505a\u8f6c\u7f6e\uff09\u884c\u6570\uff08\u505a\u8f6c\u7f6e\uff09 \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/* \n\u529f\u80fd\uff1a y=alpha*A*x+beta*y \n\u5176\u4e2dX\u548cY\u662f\u5411\u91cf\uff0cA \u662f\u77e9\u9635 \nM\uff1aA \u7684\u884c\u6570 \nN\uff1aA \u7684\u5217\u6570 \ncblas_sgemv \u4e2d\u7684 \u53c2\u65701 \u8868\u793a\u5bf9X\u548cY\u7684\u6bcf\u4e2a\u5143\u7d20\u90fd\u8fdb\u884c\u64cd\u4f5c \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/* \n\u529f\u80fd\uff1a Y=alpha*X+Y \nN\uff1a\u4e3aX\u548cY\u4e2delement\u7684\u4e2a\u6570 \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/* \n\u529f\u80fd\uff1a\u7528\u5e38\u6570 alpha \u5bf9 Y \u8fdb\u884c\u521d\u59cb\u5316 \n\u51fd\u6570 void *memset(void *buffer, char c, unsigned count) \u4e00\u822c\u4e3a\u65b0\u7533\u8bf7\u7684\u5185\u5b58\u505a\u521d\u59cb\u5316\uff0c \n\u529f\u80fd\u662f\u5c06buffer\u6240\u6307\u5411\u5185\u5b58\u4e2d\u7684\u6bcf\u4e2a\u5b57\u8282\u7684\u5185\u5bb9\u5168\u90e8\u8bbe\u7f6e\u4e3ac\u6307\u5b9a\u7684ASCII\u503c, count\u4e3a\u5757\u7684\u5927\u5c0f, \n\u4f7f\u7528memset\u51fd\u6570\u6765\u521d\u59cb\u5316\u6570\u7ec4\u6216\u8005\u7ed3\u6784\u4f53\u6bd4\u5176\u4ed6\u521d\u59cb\u5316\u65b9\u6cd5\u66f4\u5feb\u4e00\u70b9 \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//\u529f\u80fd\uff1a \u7ed9 Y \u7684\u6bcf\u4e2a element \u52a0\u4e0a\u5e38\u6570 alpha  \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/* \n\u51fd\u6570 void *memcpy(void *dest, void *src, unsigned int count) \u628asrc\u6240\u6307\u5411 \n\u7684\u5185\u5b58\u533a\u57df copy\u5230dest\u6240\u6307\u5411\u7684\u5185\u5b58\u533a\u57df, count\u4e3a\u5757\u7684\u5927\u5c0f \n\u8868\u5934\u6587\u4ef6: #include <string.h> \n\u5b9a\u4e49\u51fd\u6570: void *memcpy(void *dest, const void *src, size_t n) \n\u51fd\u6570\u8bf4\u660e: memcpy()\u7528\u6765\u62f7\u8d1dsrc\u6240\u6307\u7684\u5185\u5b58\u5185\u5bb9\u524dn\u4e2a\u5b57\u8282\u5230dest\u6240\u6307\u7684\u5185\u5b58\u5730\u5740\u4e0a\u3002\u4e0estrcpy()\u4e0d\u540c\u7684\u662f,memcpy()\u4f1a\u5b8c\u6574\u7684\u590d\u5236n\u4e2a\u5b57\u8282,\u4e0d\u4f1a\u56e0\u4e3a\u9047\u5230\u5b57\u7b26\u4e32\u7ed3\u675f'\\0'\u800c\u7ed3\u675f \n\u8fd4\u56de\u503c:   \u8fd4\u56de\u6307\u5411dest\u7684\u6307\u9488 \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}\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/* \n\u529f\u80fd\uff1aX = alpha*X \nN\uff1a X\u4e2delement\u7684\u4e2a\u6570 \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// axpby Y=alpha * X +beta*Y \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/* \n\u529f\u80fd\uff1a\u8fd9\u56db\u4e2a\u51fd\u6570\u5206\u522b\u5b9e\u73b0element-wise\u7684\u52a0\u51cf\u4e58\u9664\uff08y[i] = a[i] + - * \\ b[i]\uff09 \n*/\ntemplate <>\nvoid caffe_add<float>(const int n, const float* a, const float* b,\n    float* y) {\n  vsAdd(n, a, b, y);\n}\n\ntemplate <>\nvoid caffe_add<double>(const int n, const double* a, const double* b,\n    double* y) {\n  vdAdd(n, a, b, y);\n}\n\ntemplate <>\nvoid caffe_sub<float>(const int n, const float* a, const float* b,\n    float* y) {\n  vsSub(n, a, b, y);\n}\n\ntemplate <>\nvoid caffe_sub<double>(const int n, const double* a, const double* b,\n    double* y) {\n  vdSub(n, a, b, y);\n}\n\ntemplate <>\nvoid caffe_mul<float>(const int n, const float* a, const float* b,\n    float* y) {\n  vsMul(n, a, b, y);\n}\n\ntemplate <>\nvoid caffe_mul<double>(const int n, const double* a, const double* b,\n    double* y) {\n  vdMul(n, a, b, y);\n}\n\ntemplate <>\nvoid caffe_div<float>(const int n, const float* a, const float* b,\n    float* y) {\n  vsDiv(n, a, b, y);\n}\n\ntemplate <>\nvoid caffe_div<double>(const int n, const double* a, const double* b,\n    double* y) {\n  vdDiv(n, a, b, y);\n}\n\ntemplate <>\nvoid caffe_powx<float>(const int n, const float* a, const float b,\n    float* y) {\n  vsPowx(n, a, b, y);\n}\n\ntemplate <>\nvoid caffe_powx<double>(const int n, const double* a, const double b,\n    double* y) {\n  vdPowx(n, a, b, y);\n}\n\ntemplate <>\nvoid caffe_sqr<float>(const int n, const float* a, float* y) {\n  vsSqr(n, a, y);\n}\n\ntemplate <>\nvoid caffe_sqr<double>(const int n, const double* a, double* y) {\n  vdSqr(n, a, y);\n}\n\ntemplate <>\nvoid caffe_exp<float>(const int n, const float* a, float* y) {\n  vsExp(n, a, y);\n}\n\ntemplate <>\nvoid caffe_exp<double>(const int n, const double* a, double* y) {\n  vdExp(n, a, y);\n}\n\ntemplate <>\nvoid caffe_log<float>(const int n, const float* a, float* y) {\n  vsLn(n, a, y);\n}\n\ntemplate <>\nvoid caffe_log<double>(const int n, const double* a, double* y) {\n  vdLn(n, a, y);\n}\n\ntemplate <>\nvoid caffe_abs<float>(const int n, const float* a, float* y) {\n    vsAbs(n, a, y);\n}\n\ntemplate <>\nvoid caffe_abs<double>(const int n, const double* a, double* y) {\n    vdAbs(n, a, y);\n}\n\n/* \n\u529f\u80fd\uff1a\u8fd4\u56de\u4e00\u4e2a\u968f\u673a\u6570 \n*/  \nunsigned int caffe_rng_rand() {\n  return (*caffe_rng())();\n}\n\n/* \n\u529f\u80fd \uff1a \u8fd4\u56de b \u6700\u5927\u65b9\u5411\u4e0a\u53ef\u4ee5\u8868\u793a\u7684\u6700\u63a5\u8fd1\u7684\u6570\u503c\u3002 \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 <>\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\n/* \n\u529f\u80fd\uff1a \u8fd4\u56de vector X \u548c vector Y \u7684\u5185\u79ef\u3002 \nincx\uff0c incy \uff1a \u6b65\u957f\uff0c\u5373\u6bcf\u9694incx \u6216 incy \u4e2aelement \u8fdb\u884c\u64cd\u4f5c\u3002 \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 <>\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": "8b4131dd2a2682ea720f63ddcfffcbc3f825a6f6", "size": 11446, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/caffe/util/math_functions.cpp", "max_stars_repo_name": "sunzy301/CaffeWithAnnotation", "max_stars_repo_head_hexsha": "bbf58fae9b28b5181703e4187399a906b233c340", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-10-28T09:00:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-22T09:29:07.000Z", "max_issues_repo_path": "src/caffe/util/math_functions.cpp", "max_issues_repo_name": "sunzy301/CaffeWithAnnotation", "max_issues_repo_head_hexsha": "bbf58fae9b28b5181703e4187399a906b233c340", "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": "sunzy301/CaffeWithAnnotation", "max_forks_repo_head_hexsha": "bbf58fae9b28b5181703e4187399a906b233c340", "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.4953703704, "max_line_length": 99, "alphanum_fraction": 0.6587454132, "num_tokens": 3774, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303236047049, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.456527597920557}}
{"text": "#include <benchmark/benchmark.h>\n#include <Eigen/Eigen>\n#include <nabo/nabo.h>\n\n#include \"nanoflanntesttype.hpp\"\n\nstatic void LIBNABO_NN_BUILD(benchmark::State &state) {\n    Eigen::MatrixXf dataset = Eigen::MatrixXf::Random(3, state.range(0));\n    Nabo::NNSearchF* nns;\n\n    for (auto _ : state) {\n       nns = Nabo::NNSearchF::createKDTreeLinearHeap(dataset);\n    }\n    delete nns;\n}\nBENCHMARK(LIBNABO_NN_BUILD)->RangeMultiplier(10)->Range(10, 10000);\n\nstatic void NANOFLANN_NN_BUILD(benchmark::State &state) {\n    wave::FeatureKDTree<float> data;\n    data.points = Eigen::MatrixXf::Random(3, state.range(0));\n\n    wave::kd_tree_t<float> kdtree(3, data, nanoflann::KDTreeSingleIndexAdaptorParams(8));\n\n    for (auto _ : state) {\n        kdtree.buildIndex();\n    }\n}\nBENCHMARK(NANOFLANN_NN_BUILD)->RangeMultiplier(10)->Range(10, 10000);\n\nstatic void LIBNABO_EXACT_NN_SEARCH(benchmark::State &state) {\n    Eigen::MatrixXf dataset = Eigen::MatrixXf::Random(3, 10000);\n    Eigen::MatrixXf query = Eigen::MatrixXf::Random(3, state.range(0));\n\n    Nabo::NNSearchF* nns = Nabo::NNSearchF::createKDTreeLinearHeap(dataset);\n\n    Eigen::MatrixXi indices;\n    Eigen::MatrixXf dists2;\n\n    // Look for the range nearest neighbours of each query point,\n    // We do not want approximations but we want to sort by the distance,\n    indices.resize(state.range(1), query.cols());\n    dists2.resize(state.range(1), query.cols());\n    for (auto _ : state) {\n        nns->knn(query, indices, dists2, state.range(1), 0, Nabo::NNSearchF::SORT_RESULTS);\n    }\n    delete nns;\n}\nBENCHMARK(LIBNABO_EXACT_NN_SEARCH)->RangeMultiplier(10)->Ranges({{10, 10000}, {1, 10}});\n\n/// nanoflann seems to crap out higher than 10000 point\n\nstatic void NANOFLANN_EXACT_NN_SEARCH(benchmark::State &state) {\n    wave::FeatureKDTree<float> data;\n    data.points = Eigen::MatrixXf::Random(3, 10000);\n    Eigen::MatrixXf query = Eigen::MatrixXf::Random(3, state.range(0));\n\n    wave::kd_tree_t<float> kdtree(3, data, nanoflann::KDTreeSingleIndexAdaptorParams(8));\n\n    const size_t num_results = state.range(1);\n    std::vector<size_t>   ret_indexes(num_results);\n    std::vector<float> out_dists_sqr(num_results);\n\n    nanoflann::KNNResultSet<float> resultSet(num_results);\n\n    resultSet.init(&ret_indexes[0], &out_dists_sqr[0]);\n\n    kdtree.buildIndex();\n    for (auto _ : state) {\n        auto ptr = query.data();\n        for (long i = 0; i < state.range(0); i++) {\n            kdtree.knnSearch(ptr, state.range(1), &ret_indexes[0], &out_dists_sqr[0]);\n            ptr = ptr + 3;\n        }\n    }\n}\nBENCHMARK(NANOFLANN_EXACT_NN_SEARCH)->RangeMultiplier(10)->Ranges({{10, 10000}, {1, 10}});\n\nstatic void LIBNABO_APPROX_NN_SEARCH(benchmark::State &state) {\n    Eigen::MatrixXf dataset = Eigen::MatrixXf::Random(3, 6400);\n    Eigen::MatrixXf query = Eigen::MatrixXf::Random(3, 6400);\n\n    Nabo::NNSearchF* nns = Nabo::NNSearchF::createKDTreeLinearHeap(dataset);\n\n    Eigen::MatrixXi indices;\n    Eigen::MatrixXf dists2;\n\n    // Look for the 10 nearest neighbours\n    indices.resize(10, query.cols());\n    dists2.resize(10, query.cols());\n\n    float approx = 0.01f * static_cast<float>(state.range(0));\n\n    for (auto _ : state) {\n        nns->knn(query, indices, dists2, 10, approx, Nabo::NNSearchF::SORT_RESULTS);\n    }\n    delete nns;\n}\nBENCHMARK(LIBNABO_APPROX_NN_SEARCH)->RangeMultiplier(2)->Range(1, 16);\n\nBENCHMARK_MAIN();", "meta": {"hexsha": "86bee6c208601e949aa3cc737b4f06938b8c3f4d", "size": 3386, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "wave_odometry/tests/knn/nn_benchmark.cpp", "max_stars_repo_name": "Jebediah/libwave", "max_stars_repo_head_hexsha": "c04998c964f0dc7d414783c6e8cf989a2716ad54", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-06-13T13:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-13T14:54:35.000Z", "max_issues_repo_path": "wave_odometry/tests/knn/nn_benchmark.cpp", "max_issues_repo_name": "Jebediah/libwave", "max_issues_repo_head_hexsha": "c04998c964f0dc7d414783c6e8cf989a2716ad54", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "wave_odometry/tests/knn/nn_benchmark.cpp", "max_forks_repo_name": "Jebediah/libwave", "max_forks_repo_head_hexsha": "c04998c964f0dc7d414783c6e8cf989a2716ad54", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-13T02:27:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-13T02:27:29.000Z", "avg_line_length": 33.86, "max_line_length": 91, "alphanum_fraction": 0.6831069108, "num_tokens": 1046, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.45652759507060003}}
{"text": "#include <vector>\n\n#include \"caffe/filler.hpp\"\n#include \"caffe/layers/inner_product_mtl_layer.hpp\"\n#include \"caffe/util/math_functions.hpp\"\n#include \"caffe/util/calculate_SVD.hpp\"\n//#include <Eigen/Eigen>\n//using namespace Eigen;\n\nnamespace caffe {\n\ntemplate <typename Dtype>\n\nvoid InnerProductMtlLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom,\n      const vector<Blob<Dtype>*>& top) {\n  const int num_output = this->layer_param_.inner_product_mtl_param().num_output();\n  bias_term_ = this->layer_param_.inner_product_mtl_param().bias_term();\n  transpose_ = this->layer_param_.inner_product_mtl_param().transpose();\n  N_ = num_output;\n  k_value_ = this->layer_param_.inner_product_mtl_param().k_value();\n  const int axis = bottom[0]->CanonicalAxisIndex(\n      this->layer_param_.inner_product_mtl_param().axis());\n  // Dimensions starting from \"axis\" are \"flattened\" into a single\n  // length K_ vector. For example, if bottom[0]'s shape is (N, C, H, W),\n  // and axis == 1, N inner products with dimension CHW are performed.\n  K_ = bottom[0]->count(axis);\n  // Check if we need to set up the weights\n  if (this->blobs_.size() > 0) {\n    LOG(INFO) << \"Skipping parameter initialization\";\n  } else {\n    if (bias_term_) {\n      this->blobs_.resize(2);\n    } else {\n      this->blobs_.resize(1);\n    }\n    // Initialize the weights\n    vector<int> weight_shape(2);\n    if (transpose_) {\n      weight_shape[0] = K_;\n      weight_shape[1] = N_;\n    } else {\n      weight_shape[0] = N_;\n      weight_shape[1] = K_;\n    }\n    this->blobs_[0].reset(new Blob<Dtype>(weight_shape));\n    // fill the weights\n    shared_ptr<Filler<Dtype> > weight_filler(GetFiller<Dtype>(\n        this->layer_param_.inner_product_mtl_param().weight_filler()));\n    weight_filler->Fill(this->blobs_[0].get());\n    // If necessary, intiialize and fill the bias term\n    if (bias_term_) {\n      vector<int> bias_shape(1, N_);\n      this->blobs_[1].reset(new Blob<Dtype>(bias_shape));\n      shared_ptr<Filler<Dtype> > bias_filler(GetFiller<Dtype>(\n          this->layer_param_.inner_product_mtl_param().bias_filler()));\n      bias_filler->Fill(this->blobs_[1].get());\n    }\n  }  // parameter initialization\n  this->param_propagate_down_.resize(this->blobs_.size(), true);\n}\n\ntemplate <typename Dtype>\nvoid InnerProductMtlLayer<Dtype>::Reshape(const vector<Blob<Dtype>*>& bottom,\n      const vector<Blob<Dtype>*>& top) {\n  // Figure out the dimensions\n  const int axis = bottom[0]->CanonicalAxisIndex(\n      this->layer_param_.inner_product_mtl_param().axis());\n  const int new_K = bottom[0]->count(axis);\n  CHECK_EQ(K_, new_K)\n      << \"Input size incompatible with inner product parameters.\";\n  // The first \"axis\" dimensions are independent inner products; the total\n  // number of these is M_, the product over these dimensions.\n  M_ = bottom[0]->count(0, axis);\n  // The top shape will be the bottom shape with the flattened axes dropped,\n  // and replaced by a single axis with dimension num_output (N_).\n  vector<int> top_shape = bottom[0]->shape();\n  top_shape.resize(axis + 1);\n  top_shape[axis] = N_;\n  top[0]->Reshape(top_shape);\n  // Set up the bias multiplier\n  if (bias_term_) {\n    vector<int> bias_shape(1, M_);\n    bias_multiplier_.Reshape(bias_shape);\n    caffe_set(M_, Dtype(1), bias_multiplier_.mutable_cpu_data());\n  }\n}\n\ntemplate <typename Dtype>\nvoid InnerProductMtlLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom,\n    const vector<Blob<Dtype>*>& top) {\n  const Dtype* bottom_data = bottom[0]->cpu_data();\n  Dtype* top_data = top[0]->mutable_cpu_data();\n  const Dtype* weight = this->blobs_[0]->cpu_data();\n\n  caffe_cpu_gemm<Dtype>(CblasNoTrans, transpose_ ? CblasNoTrans : CblasTrans,\n      M_, N_, K_, (Dtype)1.,\n      bottom_data, weight, (Dtype)0., top_data);\n  if (bias_term_) {\n    caffe_cpu_gemm<Dtype>(CblasNoTrans, CblasNoTrans, M_, N_, 1, (Dtype)1.,\n        bias_multiplier_.cpu_data(),\n        this->blobs_[1]->cpu_data(), (Dtype)1., top_data);\n  }\n}\n\ntemplate <typename Dtype>\nvoid InnerProductMtlLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,\n\tconst vector<bool>& propagate_down,\n\tconst vector<Blob<Dtype>*>& bottom) {\n\tif (this->param_propagate_down_[0]) {\n\t\tconst Dtype* top_diff = top[0]->cpu_diff();\n\t\tconst Dtype* bottom_data = bottom[0]->cpu_data();\n\t\t// Gradient with respect to weight\n\t\t#ifdef _DEBUG\n\t\t\tconst Dtype* weight = this->blobs_[0]->cpu_data();\n\t\t\tconst Dtype* weight_diff_mut = this->blobs_[0]->mutable_cpu_diff();\n\t\t\tconst Dtype* data_diff = bottom[0]->cpu_diff();\n\t\t\tconst Dtype* weight_diff = this->blobs_[0]->cpu_diff();\n\t\t\tfor (int i = 0; i < 10; i++){\n\t\t\t\tcout << \" \" << weight[i] << \" \";\n\t\t\t}\n\t\t\tcout << endl;\n\t\t\tcout << endl;\n\n\t\t\tfor (int i = 0; i < 10; i++){\n\t\t\t\tcout << \" \" << weight_diff_mut[i] << \" \";\n\t\t\t}\n\t\t\tcout << endl;\n\t\t\tcout << endl;\n\n\t\t\tfor (int i = 0; i < 10; i++){\n\t\t\t\tcout << \" \" << weight_diff[i] << \" \";\n\t\t\t}\n\t\t\tcout << endl;\n\t\t\tcout << endl;\n\n\t\t\tfor (int i = 0; i < 10; i++){\n\t\t\t\tcout << \" \" << data_diff[i] << \" \";\n\t\t\t}\n\t\t\tcout << endl;\n\t\t\tcout << endl;\n\n\t\t#endif\n\n\t\tif (transpose_) {\n\t\t\tcaffe_cpu_gemm<Dtype>(CblasTrans, CblasNoTrans,\n\t\t\t\tK_, N_, M_,\n\t\t\t\t(Dtype)1., bottom_data, top_diff,\n\t\t\t\t(Dtype)1., this->blobs_[0]->mutable_cpu_diff());\n\t\t}\n\t\telse {\n\t\t\tcaffe_cpu_gemm<Dtype>(CblasTrans, CblasNoTrans,\n\t\t\t\tN_, K_, M_,\n\t\t\t\t(Dtype)1., top_diff, bottom_data,\n\t\t\t\t(Dtype)1., this->blobs_[0]->mutable_cpu_diff());\n\t\t}\n\n\t}\n\tif (bias_term_ && this->param_propagate_down_[1]) {\n\t\tconst Dtype* top_diff = top[0]->cpu_diff();\n\t\t// Gradient with respect to bias\n\t\tcaffe_cpu_gemv<Dtype>(CblasTrans, M_, N_, (Dtype)1., top_diff,\n\t\t\tbias_multiplier_.cpu_data(), (Dtype)1.,\n\t\t\tthis->blobs_[1]->mutable_cpu_diff());\n\t}\n\n\t//FM: SVD\n\tconst Dtype* weight = this->blobs_[0]->cpu_data(); // nomizw pos to weight mporei na figei teleiws kai na douleuw mono me to weight_mut\n\tDtype* weight_mut = this->blobs_[0]->mutable_cpu_data();\n\n\tint num_neurons = this->blobs_[0]->num(); // T tasks\n\tint dim_features = this->blobs_[0]->count() / num_neurons; // feature dimension\n\tCalculateSVD(weight, weight_mut, num_neurons, dim_features, k_value_);\n\t// FM: End of SVD\n\n\n\tif (propagate_down[0]) {\n\t\tconst Dtype* top_diff = top[0]->cpu_diff();\n\t\t// Gradient with respect to bottom data\n\t\tif (transpose_) {\n\t\t\tcaffe_cpu_gemm<Dtype>(CblasNoTrans, CblasTrans,\n\t\t\t\tM_, K_, N_,\n\t\t\t\t(Dtype)1., top_diff, weight,\n\t\t\t\t(Dtype)0., bottom[0]->mutable_cpu_diff());\n\t\t}\n\t\telse {\n\t\t\tcaffe_cpu_gemm<Dtype>(CblasNoTrans, CblasNoTrans,\n\t\t\t\tM_, K_, N_,\n\t\t\t\t(Dtype)1., top_diff, weight,\n\t\t\t\t(Dtype)0., bottom[0]->mutable_cpu_diff());\n\t\t}\n\t}\n\n\t#ifdef _DEBUG\n\t\tconst Dtype* weight_diff_mut = this->blobs_[0]->mutable_cpu_diff();\n\t\tconst Dtype* data_diff = bottom[0]->cpu_diff();\n\t\tconst Dtype* weight_diff = this->blobs_[0]->cpu_diff();\n\t\tfor (int i = 0; i < 10; i++){\n\t\t\tcout << \" \" << weight[i] << \" \";\n\t\t}\n\t\tcout << endl;\n\t\tcout << endl;\n\n\t\tfor (int i = 0; i < 10; i++){\n\t\t\tcout << \" \" << weight_diff_mut[i] << \" \";\n\t\t}\n\t\tcout << endl;\n\t\tcout << endl;\n\n\t\tfor (int i = 0; i < 10; i++){\n\t\t\tcout << \" \" << weight_diff[i] << \" \";\n\t\t}\n\t\tcout << endl;\n\t\tcout << endl;\n\n\t\tfor (int i = 0; i < 10; i++){\n\t\t\tcout << \" \" << data_diff[i] << \" \";\n\t\t}\n\t\tcout << endl;\n\t\tcout << endl;\n\n\t#endif\n\n}\n\n//template <typename Dtype>\n//void InnerProductMtlLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,\n//    const vector<bool>& propagate_down,\n//    const vector<Blob<Dtype>*>& bottom) {\n//  if (this->param_propagate_down_[0]) {\n//    const Dtype* top_diff = top[0]->cpu_diff();\n//    const Dtype* bottom_data = bottom[0]->cpu_data();\n//    // Gradient with respect to weight\n//\t#ifdef _DEBUG\n//\t\tconst Dtype* weight = this->blobs_[0]->cpu_data();\n//\t\tconst Dtype* weight_diff = this->blobs_[0]->mutable_cpu_diff();\n//\t\tfor (int i = 0; i < 10; i++){\n//\t\t\tcout << \" \" << weight[i] << \" \";\n//\t\t}\n//\t\tcout << endl;\n//\t\tcout << endl;\n//\n//\t\tfor (int i = 0; i < 10; i++){\n//\t\t\tcout << \" \" << weight_diff[i] << \" \";\n//\t\t}\n//\t\tcout << endl;\n//\t\tcout << endl;\n//\n//\t#endif\n//\n//    if (transpose_) {\n//      caffe_cpu_gemm<Dtype>(CblasTrans, CblasNoTrans,\n//          K_, N_, M_,\n//          (Dtype)1., bottom_data, top_diff,\n//          (Dtype)1., this->blobs_[0]->mutable_cpu_diff());\n//    } else {\n//      caffe_cpu_gemm<Dtype>(CblasTrans, CblasNoTrans,\n//          N_, K_, M_,\n//          (Dtype)1., top_diff, bottom_data,\n//          (Dtype)1., this->blobs_[0]->mutable_cpu_diff());\n//    }\n//\n//  }\n//  if (bias_term_ && this->param_propagate_down_[1]) {\n//    const Dtype* top_diff = top[0]->cpu_diff();\n//    // Gradient with respect to bias\n//    caffe_cpu_gemv<Dtype>(CblasTrans, M_, N_, (Dtype)1., top_diff,\n//        bias_multiplier_.cpu_data(), (Dtype)1.,\n//        this->blobs_[1]->mutable_cpu_diff());\n//  }\n//\n//  //FM: SVD\n//  const Dtype* weight = this->blobs_[0]->cpu_data();\n//  Dtype* weight_mut = this->blobs_[0]->mutable_cpu_data();\n//\n//#ifdef _DEBUG\n//  //initial weights\n//  for (int i = 0; i < 10; i++){\n//\t  cout << \" \" << weight[i] << \" \";\n//  }\n//  cout << endl;\n//  cout << endl;\n//#endif\n//\n//  int num_neurons = this->blobs_[0]->num(); // T tasks\n//  int dim_features = this->blobs_[0]->count() / num_neurons; // feature dimension\n//  //Dtype* weight2 = new Dtype[num_neurons*dim_features];\n//\n//  //Instantiate the weight matrix\n//  MatrixXf m = MatrixXf::Random(num_neurons, dim_features);\n//  int counter = 0;\n//  for (int i = 0; i < num_neurons; ++i) {\n//\t  for (int j = 0; j < dim_features; ++j) {\n//\t\t  m(i, j) = weight[counter];\n//\t\t  counter++;\n//\t  }\n//\n//  }\n//\n//\n//  //Perform SVD\n//  // cout << \"Here is the matrix m:\" << endl << m << endl;\n//  JacobiSVD<MatrixXf> svd(m, ComputeThinU | ComputeThinV);\n//\n//  // Set with the new values\n//  counter = 0;\n//  MatrixXf m_inner = svd.matrixU() * (svd.singularValues().asDiagonal() * svd.matrixV().transpose());\n//\n//  for (int i = 0; i < num_neurons; ++i) {\n//\t  for (int j = 0; j < dim_features; ++j) {\n//\t\t  weight_mut[counter] = m_inner(i, j); // j,i because the matrix now has features in the columns (each column corresponds to one neuron)\n//\t\t  counter++;\n//\t  }\n//\n//  }\n//\n//#ifdef _DEBUG\n//  MatrixXf diff = m_inner - m;\n//  cout << \"diff:\\n\" << diff.array().abs().sum() << \"\\n\";\n//  //cout << \"Its singular values are:\" << endl << svd.singularValues() << endl;\n//  //cout << \"Its left singular vectors are the columns of the thin L-U matrix:\" << endl << svd.matrixU() << endl;\n//  //cout << \"Its right singular vectors are the columns of the thin S-V matrix:\" << endl << svd.matrixV() << endl;\n//\n//  for (int i = 0; i < 10; i++){\n//\t  cout << \" \" << weight[i] << \" \";\n//  }\n//  cout << endl;\n//  cout << endl;\n//\n//  for (int i = 0; i < 10; i++){\n//\t  cout << \" \" << weight_mut[i] << \" \";\n//  }\n//  cout << endl;\n//  cout << endl;\n//\n//#endif\n//\n//  // FM: End of SVD\n//\n//  if (propagate_down[0]) {\n//    const Dtype* top_diff = top[0]->cpu_diff();\n//    // Gradient with respect to bottom data\n//    if (transpose_) {\n//      caffe_cpu_gemm<Dtype>(CblasNoTrans, CblasTrans,\n//          M_, K_, N_,\n//\t\t  (Dtype)1., top_diff, weight,\n//          (Dtype)0., bottom[0]->mutable_cpu_diff());\n//    } else {\n//      caffe_cpu_gemm<Dtype>(CblasNoTrans, CblasNoTrans,\n//          M_, K_, N_,\n//\t\t  (Dtype)1., top_diff, weight,\n//          (Dtype)0., bottom[0]->mutable_cpu_diff());\n//    }\n//  }\n//}\n\n#ifdef CPU_ONLY\nSTUB_GPU(InnerProductMtlLayer);\n#endif\n\nINSTANTIATE_CLASS(InnerProductMtlLayer);\nREGISTER_LAYER_CLASS(InnerProductMtl);\n\n}  // namespace caffe\n", "meta": {"hexsha": "d96162886df4f3e5aeb519f2931770225f07442f", "size": 11485, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code_caffe-rc3_fvmtl_ccelc/src/caffe/layers/inner_product_mtl_layer.cpp", "max_stars_repo_name": "markatopoulou/fvmtl-ccelc", "max_stars_repo_head_hexsha": "4c6e0ac2e4c0cc6181f0836151a871bbff257ddb", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-05-30T12:12:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-07T13:59:18.000Z", "max_issues_repo_path": "code_caffe-rc3_fvmtl_ccelc/src/caffe/layers/inner_product_mtl_layer.cpp", "max_issues_repo_name": "markatopoulou/fvmtl-ccelc", "max_issues_repo_head_hexsha": "4c6e0ac2e4c0cc6181f0836151a871bbff257ddb", "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": "code_caffe-rc3_fvmtl_ccelc/src/caffe/layers/inner_product_mtl_layer.cpp", "max_forks_repo_name": "markatopoulou/fvmtl-ccelc", "max_forks_repo_head_hexsha": "4c6e0ac2e4c0cc6181f0836151a871bbff257ddb", "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.5521978022, "max_line_length": 140, "alphanum_fraction": 0.6173269482, "num_tokens": 3533, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4565275950706}}
{"text": "#include <math.h>\n#include <uWS/uWS.h>\n#include <chrono>\n#include <iostream>\n#include <thread>\n#include <vector>\n#include \"Eigen-3.3/Eigen/Core\"\n#include \"Eigen-3.3/Eigen/QR\"\n#include \"MPC.h\"\n#include \"json.hpp\"\n\n//#include \"matplotlibcpp.h\"\n\n\n\n\n//#include <boost/thread.hpp>\n// for convenience\nusing json = nlohmann::json;\n\n\nconst bool show_graph = false;\n\n//namespace plt = matplotlibcpp;\n\n// For converting back and forth between radians and degrees.\nconstexpr double pi() { return M_PI; }\ndouble deg2rad(double x) { return x * pi() / 180; }\ndouble rad2deg(double x) { return x * 180 / pi(); }\nconst double Lf = 2.67;\n\nint iters= 1;\n\n\n\n// Checks if the SocketIO event has JSON data.\n// If there is data the JSON object in string format will be returned,\n// else the empty string \"\" will be returned.\nstring hasData(string s) {\n  auto found_null = s.find(\"null\");\n  auto b1 = s.find_first_of(\"[\");\n  auto b2 = s.rfind(\"}]\");\n  if (found_null != string::npos) {\n    return \"\";\n  } else if (b1 != string::npos && b2 != string::npos) {\n    return s.substr(b1, b2 - b1 + 2);\n  }\n  return \"\";\n}\n\n// Evaluate a polynomial.\ndouble polyeval(Eigen::VectorXd coeffs, double x) {\n  double result = 0.0;\n  for (unsigned int i = 0; i < coeffs.size(); i++) {\n    result += coeffs[i] * pow(x, i);\n  }\n  return result;\n}\n\n// Fit a polynomial.\n// Adapted from\n// https://github.com/JuliaMath/Polynomials.jl/blob/master/src/Polynomials.jl#L676-L716\nEigen::VectorXd polyfit(Eigen::VectorXd xvals, Eigen::VectorXd yvals,\n                        int order) {\n  assert(xvals.size() == yvals.size());\n  assert(order >= 1 && order <= xvals.size() - 1);\n  Eigen::MatrixXd A(xvals.size(), order + 1);\n\n  for (unsigned int i = 0; i < xvals.size(); i++) {\n    A(i, 0) = 1.0;\n  }\n\n  for (unsigned int j = 0; j < xvals.size(); j++) {\n    for ( int i = 0; i < order; i++) {\n      A(j, i + 1) = A(j, i) * xvals(j);\n    }\n  }\n\n  auto Q = A.householderQr();\n  auto result = Q.solve(yvals);\n  return result;\n}\n\nvoid peigen (Eigen::VectorXd vect ) // send a vector to console\n{\n          \n          for (unsigned int i = 0; i < vect.size() ; i++)\n          {\n            cout << vect[i] << endl;\n          }\n          cout << endl ;\n\n}\n\n\n\nvoid pvector (vector<double> vect ) // send a vector to console\n{\n          \n          for (unsigned int i = 0; i < vect.size() ; i++)\n          {\n            cout << vect[i] << endl;\n          }\n          cout << endl ;\n\n}\n\n\n// https://stackoverflow.com/questions/26094379/typecasting-eigenvectorxd-to-stdvector\n\nEigen::VectorXd stdvector2eigen(vector<double> v1)\n{\n          //from v1 to an eignen vector\n          //double* ptr_data = &v1[0];\n          Eigen::VectorXd v2 = Eigen::Map<Eigen::VectorXd, Eigen::Unaligned>(v1.data(), v1.size());\n          return v2;\n\n}\n\nvector<double> eigen2stdvector(Eigen::VectorXd v2)\n{\n    //from the eigen vector to the std vector\n    std::vector<double> v3(&v2[0], v2.data()+v2.cols()*v2.rows());\n    return v3;\n\n}\n\n\n\nsize_t i = 0;\n\narray<vector<double>, 2> World2Car(vector<double> vect_world_x, vector<double> vect_world_y , double gpx_x, double gps_y, double psi)\n{\n          cout << \"Map\\tX\\t\" ; pvector(vect_world_x);\n          cout << \"\\tY\\t\" ; pvector(vect_world_y);\n          for (unsigned int i = 0 ; i < vect_world_x.size() ; i++)\n          {\n            double x, y;\n            x = vect_world_x[i] - gpx_x;\n            y = vect_world_y[i] - gps_y;\n            vect_world_x[i] =  x * cos(-psi) - y * sin(-psi);\n            vect_world_y[i] =  x * sin(-psi) + y * cos(-psi);\n          \n          }\n            cout << \"Car\\tX\\t\" ; pvector(vect_world_x);\n            cout << \"\\tY\\t\" ; pvector(vect_world_y);\n          array<vector<double>, 2> coord_set;\n          coord_set[0] = vect_world_x;\n          coord_set[1] = vect_world_y;\n          return coord_set ;\n}\n\n\n\n\n\nint main() {\n  uWS::Hub h;\n  //std::cout << setprecision(8);\n  // MPC is initialized here!\n  MPC mpc;\n          \n          \n\n  \n  std::vector<double> x_vals ;\n  std::vector<double> y_vals ;\n  std::vector<double> psi_vals;\n  std::vector<double> v_vals ;\n  std::vector<double> cte_vals ;\n  std::vector<double> epsi_vals ;\n  std::vector<double> delta_vals ;\n  std::vector<double> a_vals ;\n\n\n  h.onMessage([&mpc, &x_vals, &y_vals, &psi_vals, &v_vals, &cte_vals, &epsi_vals, &delta_vals, &a_vals](uWS::WebSocket<uWS::SERVER> ws, char *data, size_t length, uWS::OpCode opCode) {\n    // \"42\" at the start of the message means there's a websocket message event.\n    // The 4 signifies a websocket message\n    // The 2 signifies a websocket event\n    string sdata = string(data).substr(0, length);\n    //cout << sdata << endl;\n    if (sdata.size() > 2 && sdata[0] == '4' && sdata[1] == '2') {\n      string s = hasData(sdata);\n      if (s != \"\") {\n        auto j = json::parse(s);\n        string event = j[0].get<string>();\n        if (event == \"telemetry\") {\n          // j[1] is the data JSON object\n          vector<double> ptsx = j[1][\"ptsx\"];\n          vector<double> ptsy = j[1][\"ptsy\"];\n          double px = j[1][\"x\"];\n          double py = j[1][\"y\"];\n          double psi = j[1][\"psi\"];\n          //double psi_unity = j[1][\"psi_unity\"];\n          double v = j[1][\"speed\"];\n\n          double delta = j[1][\"steering_angle\"];\n          double a = j[1][\"throttle\"];\n\n\n\n          /*\n          * TODO: Calculate steering angle and throttle using MPC.\n          *\n          * Both are in between [-1, 1].\n          *\n          */\n\n   \n          \n          Eigen::VectorXd ptsx_car(ptsx.size());\n          Eigen::VectorXd ptsy_car(ptsy.size());\n\n\n          for (unsigned int i = 0 ; i < ptsx.size() ; i++)\n          {\n\n            double x, y;\n            x = ptsx[i] - px;\n            y = ptsy[i] - py;\n            ptsx_car[i] =  x * cos(-psi) - y * sin(-psi);\n            ptsy_car[i] =  x * sin(-psi) + y * cos(-psi);\n          \n          }\n\n\n          //////////\n          \n          \n          auto coeffs = polyfit(ptsx_car , ptsy_car ,  3);\n          \n            // The cross track error is calculated by evaluating at polynomial at x, f(x)\n            // and subtracting y. x = 0 , y = 0\n\n            // in the vehicle coords  \n            double cte = polyeval(coeffs, 0) ;\n\n            // Due to the sign starting at 0, the orientation error is -f'(x).\n            // derivative of coeffs[0] + coeffs[1] * x -> coeffs[1]\n\n            double epsi = -atan(coeffs[1]);\n\n            Eigen::VectorXd state(6);\n          \n            double dt = 0.075;\n            \n            //predicted values\n            double x_val=0.0 , y_val=0.0, psi_val=0.0, v_val = v, cte_val = cte, epsi_val = epsi;\n            x_val    = v * cos(0) *dt ;\n            y_val    = v * sin(0) *dt ;\n            psi_val  = v * -delta / Lf *dt;\n            v_val    = v + a *dt;\n            cte_val  += v * sin(epsi) *dt;\n            epsi_val += v * -delta / Lf *dt;\n\n            //cout << x_val<< \"\\t\" << y_val<< \"\\t\" << psi_val<< \"\\t\" << v_val<<\"\\t\" << cte_val<<\"\\t\" << epsi_val << \"\\t\";\n            //cout <<  epsi_val << \"\\t\" << cte_val << \"\\t\" << endl ;\n\n            state << x_val, y_val, psi_val, v_val, cte_val, epsi_val;\n            \n            vector<double> vars;\n            vars = mpc.Solve(state, coeffs);\n\n            delta_vals.push_back(vars[0]);\n            a_vals.push_back(vars[1]);      \n            cte_vals.push_back(vars[2]);\n\n            psi_vals.push_back(vars[3]);\n            epsi_vals.push_back(vars[4]);\n            v_vals.push_back(vars[5]);\n\n            x_vals.push_back(px);\n            y_vals.push_back(py);\n\n\n\n          iters++;\n\n          delta = - vars[0] / (deg2rad(25) * Lf);\n          a  = vars[1];\n\n          json msgJson;\n\n          // NOTE: Remember to divide by deg2rad(25) before you send the steering value back.\n          // Otherwise the values will be in between [-deg2rad(25), deg2rad(25] instead of [-1, 1].\n          msgJson[\"steering_angle\"] = delta;\n          msgJson[\"throttle\"] = a;\n\n\n          vector<double> mpc_x ;\n          vector<double> mpc_y ;\n\n          \n\n          for (unsigned int i = 6 ; i < vars.size() ; i+=2 )\n          {\n            mpc_x.push_back(vars[i]);\n            mpc_y.push_back(polyeval(coeffs , vars[i]) - vars[2]);\n            //mpc_y.push_back(vars[i+1]) ;\n            \n            \n          }\n\n          //pvector(mpc_x);\n          //pvector(mpc_y);\n\n          msgJson[\"mpc_x\"] = mpc_x;\n          msgJson[\"mpc_y\"] = mpc_y;\n\n          //Display the waypoints/reference line\n\n          vector<double> eig_next_x_vals = eigen2stdvector( ptsx_car );\n          vector<double> eig_next_y_vals = eigen2stdvector( ptsy_car );\n\n\n          vector<double> next_x_vals ;\n          vector<double> next_y_vals ;\n\n          //.. add (x,y) points to list here, points are in reference to the vehicle's coordinate system\n          // the points in the simulator are connected by a Yellow line\n\n\n          double poly_incr = Lf;\n          int n_pts = 25;\n\n          for (signed int i = 1; i < n_pts ; i++)\n          {\n            next_x_vals.push_back(poly_incr * i);\n            next_y_vals.push_back(polyeval(coeffs , poly_incr * i));\n          }\n\n\n          msgJson[\"next_x\"] = next_x_vals ;\n          msgJson[\"next_y\"] = next_y_vals ;\n\n\n          auto msg = \"42[\\\"steer\\\",\" + msgJson.dump() + \"]\";\n          //std::cout << msg << endl << std::endl;\n\n          // Latency\n          // The purpose is to mimic real driving conditions where\n          // the car does actuate the commands instantly.\n          //\n          // Feel free to play around with this value but should be to drive\n          // around the track with 100ms latency.\n          //\n          // NOTE: REMEMBER TO SET THIS TO 100 MILLISECONDS BEFORE\n          // SUBMITTING.\n          this_thread::sleep_for(chrono::milliseconds(100));\n          ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT);\n\n\n          if (show_graph == true)\n          {\n\n\n          if (iters == 100)\n            {\n\n/*\n                    \n            // Plot values\n            // NOTE: feel free to play around with this.\n            // It's useful for debugging!\n            plt::subplot(6, 1, 1);\n            plt::title(\"CTE\");\n            plt::plot(cte_vals);\n\n            plt::subplot(6, 1, 2);\n            plt::title(\"Delta (Radians)\");\n            plt::plot(delta_vals);\n\n            plt::subplot(6, 1, 3);\n            plt::title(\"Velocity\");\n            plt::plot(v_vals);\n\n            plt::subplot(6, 1, 4);\n            plt::title(\"Epsi\");\n            plt::plot(epsi_vals);\n\n            plt::subplot(6, 1, 5);\n            plt::title(\"x\");\n            plt::plot(x_vals);\n\n            plt::subplot(6, 1, 6);\n            plt::title(\"y\");\n            plt::plot(y_vals);\n\n            cout << \"game over\";\n\n            //plt::ion();\n            plt::show();\n            //plt::save(\"./graph.png\");\n            //exit(1);\n\n            */\n\n\n            }   \n          }\n\n        }\n      } else {\n        // Manual driving\n        std::string msg = \"42[\\\"manual\\\",{}]\";\n        ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT);\n      }\n    }\n    \n  }\n  \n\n);\n\n  // We don't need this since we're not using HTTP but if it's removed the\n  // program\n  // doesn't compile :-(\n  h.onHttpRequest([](uWS::HttpResponse *res, uWS::HttpRequest req, char *data,\n                     size_t, size_t) {\n    const std::string s = \"<h1>Hello world!</h1>\";\n    if (req.getUrl().valueLength == 1) {\n      res->end(s.data(), s.length());\n    } else {\n      // i guess this should be done more gracefully?\n      res->end(nullptr, 0);\n    }\n  });\n\n  h.onConnection([&h](uWS::WebSocket<uWS::SERVER> ws, uWS::HttpRequest req) {\n    std::cout << \"Connected!!!\" << std::endl;\n  });\n\n  h.onDisconnection([&h](uWS::WebSocket<uWS::SERVER> ws, int code,\n                         char *message, size_t length) {\n    ws.close();\n    std::cout << \"Disconnected\" << std::endl;\n  });\n\n  int port = 4567;\n  if (h.listen(port)) {\n    std::cout << \"Listening to port \" << port << std::endl;\n  } else {\n    std::cerr << \"Failed to listen to port\" << std::endl;\n    return -1;\n  }\n  h.run();\n}\n", "meta": {"hexsha": "5d8c9caa87f6599374e9fe79df136f9118921609", "size": 12067, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "level-3/CarND-MPC-Project", "max_stars_repo_head_hexsha": "55902109a54d1a07aed7944910a0f51bc41f9ef0", "max_stars_repo_licenses": ["MIT"], "max_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": "level-3/CarND-MPC-Project", "max_issues_repo_head_hexsha": "55902109a54d1a07aed7944910a0f51bc41f9ef0", "max_issues_repo_licenses": ["MIT"], "max_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": "level-3/CarND-MPC-Project", "max_forks_repo_head_hexsha": "55902109a54d1a07aed7944910a0f51bc41f9ef0", "max_forks_repo_licenses": ["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.9352678571, "max_line_length": 184, "alphanum_fraction": 0.5153725035, "num_tokens": 3315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4565275950706}}
{"text": "#pragma once\n\n#include <Eigen/Core>\n#include <optional>\n\nnamespace wmtk {\n\n/**\n * Newton method or gradient descent.\n *\n * @param stack with flattened 4x3 vertices positions, with the mover vertex always on the front.\n * This is the same convention with AMIPS_energy\n * @return Descend direction as computed from Newton method, (or gradient descent if Newton fails).\n */\nEigen::Vector3d newton_method_from_stack(\n    std::vector<std::array<double, 12>>& stack,\n    std::function<double(const std::array<double, 12>&)> energy,\n    std::function<void(const std::array<double, 12>&, Eigen::Vector3d&)> jacobian,\n    std::function<void(const std::array<double, 12>&, Eigen::Matrix3d&)> hessian);\n\nEigen::Vector3d gradient_descent_from_stack(\n    std::vector<std::array<double, 12>>& stack,\n    std::function<double(const std::array<double, 12>&)> energy,\n    std::function<void(const std::array<double, 12>&, Eigen::Vector3d&)> jacobian);\n/**\n * Reorders indices in a tetrahedron such that v0 is on the front. Using the tetra symmetry to\n * preserve orientation. Assumes v0 in tetra.\n * @param conn\n * @param v0\n * @return std::array<size_t, 4>\n */\nstd::array<size_t, 4> orient_preserve_tet_reorder(const std::array<size_t, 4>& tetra, size_t v0);\n\n/**\n * @brief Harmonic Triangulation energy: trace of Laplacian operator\n *\n */\ndouble harmonic_energy(const Eigen::MatrixXd& verts);\n\nstd::optional<Eigen::Vector3d> try_project(\n    const Eigen::Vector3d& point,\n    const std::vector<std::array<double, 12>>& assembled_neighbor);\n} // namespace wmtk", "meta": {"hexsha": "36335971ff8c3b6319a65c3ff973d77741e84b49", "size": 1544, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/wmtk/utils/TetraQualityUtils.hpp", "max_stars_repo_name": "wildmeshing/wildmeshing-toolkit", "max_stars_repo_head_hexsha": "7f4c60e5a6d366d9c3850b720b42b610e10600c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2021-12-10T08:26:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T00:19:41.000Z", "max_issues_repo_path": "src/wmtk/utils/TetraQualityUtils.hpp", "max_issues_repo_name": "wildmeshing/wildmeshing-toolkit", "max_issues_repo_head_hexsha": "7f4c60e5a6d366d9c3850b720b42b610e10600c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 86.0, "max_issues_repo_issues_event_min_datetime": "2021-12-03T01:46:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T19:33:17.000Z", "max_forks_repo_path": "src/wmtk/utils/TetraQualityUtils.hpp", "max_forks_repo_name": "wildmeshing/wildmeshing-toolkit", "max_forks_repo_head_hexsha": "7f4c60e5a6d366d9c3850b720b42b610e10600c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-11-26T08:29:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-03T22:10:42.000Z", "avg_line_length": 35.9069767442, "max_line_length": 99, "alphanum_fraction": 0.7202072539, "num_tokens": 410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.4565275893706857}}
{"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 linalg2_hpp\n#define linalg2_hpp\n\n#include <cstdint>\n#include <limits>\n#include <cctype>\n#include <cmath>\n#include <complex>\n#include <algorithm>\n#include <Eigen/Core>\n#include <Eigen/SVD>\n#include <Eigen/Eigenvalues>\n#include \"config.h\"\n\nnamespace flexiblesusy {\n\n#define MAX_(i, j) (((i) > (j)) ? (i) : (j))\n#define MIN_(i, j) (((i) < (j)) ? (i) : (j))\n\ntemplate<class Real, class Scalar, int M, int N>\nvoid svd_eigen\n(const Eigen::Matrix<Scalar, M, N>& m,\n Eigen::Array<Real, MIN_(M, N), 1>& s,\n Eigen::Matrix<Scalar, M, M> *u,\n Eigen::Matrix<Scalar, N, N> *vh)\n{\n    Eigen::JacobiSVD<Eigen::Matrix<Scalar, M, N> >\n\tsvd(m, (u ? Eigen::ComputeFullU : 0) | (vh ? Eigen::ComputeFullV : 0));\n    s = svd.singularValues();\n    if (u)  *u  = svd.matrixU();\n    if (vh) *vh = svd.matrixV().adjoint();\n}\n\ntemplate<class Real, class Scalar, int N>\nvoid hermitian_eigen\n(const Eigen::Matrix<Scalar, N, N>& m,\n Eigen::Array<Real, N, 1>& w,\n Eigen::Matrix<Scalar, N, N> *z)\n{\n    Eigen::SelfAdjointEigenSolver<Eigen::Matrix<Scalar,N,N> >\n\tes(m, z ? Eigen::ComputeEigenvectors : Eigen::EigenvaluesOnly);\n    w = es.eigenvalues();\n    if (z) *z = es.eigenvectors();\n}\n\n#ifdef ENABLE_LAPACK\n\n#   ifdef ENABLE_ILP64MKL_WORKAROUND\nusing lapack_int = int64_t;\n#   else\nusing lapack_int = int;\n#   endif\n\nextern \"C\" void zgesvd_\n(const char& JOBU, const char& JOBVT, const lapack_int& M, const lapack_int& N,\n std::complex<double> *A, const lapack_int& LDA, double *S,\n std::complex<double> *U, const lapack_int& LDU,\n std::complex<double> *VT, const lapack_int& LDVT,\n std::complex<double> *WORK, const lapack_int& LWORK, double *RWORK,\n lapack_int& INFO);\n\nextern \"C\" void dgesvd_\n(const char& JOBU, const char& JOBVT, const lapack_int& M, const lapack_int& N,\n double *A, const lapack_int& LDA, double *S,\n double *U, const lapack_int& LDU,\n double *VT, const lapack_int& LDVT,\n double *WORK, const lapack_int& LWORK,\n lapack_int& INFO);\n\nextern \"C\" void zheev_\n(const char& JOBZ, const char& UPLO, const lapack_int& N,\n std::complex<double> *A, const lapack_int& LDA, double *W,\n std::complex<double> *WORK, const lapack_int& LWORK, double *RWORK,\n lapack_int& INFO);\n\nextern \"C\" void dsyev_\n(const char& JOBZ, const char& UPLO, const lapack_int& N,\n double *A, const lapack_int& LDA, double *W,\n double *WORK, const lapack_int& LWORK,\n lapack_int& INFO);\n\n#define def_svd_lapack(t, f, ...)\t\t\t\t\t\\\ntemplate<int M, int N>\t\t\t\t\t\t\t\\\nvoid svd_lapack\t\t\t\t\t\t\t\t\\\n(const Eigen::Matrix<t, M, N>& m,\t\t\t\t\t\\\n Eigen::Array<double, MIN_(M, N), 1>& s,\t\t\t\t\\\n Eigen::Matrix<t, M, M> *u  = 0,\t\t\t\t\t\\\n Eigen::Matrix<t, N, N> *vh = 0)\t\t\t\t\t\\\n{\t\t\t\t\t\t\t\t\t\\\n    const     char JOBU  = u  ? 'A' : 'N';\t\t\t\t\\\n    const     char JOBVT = vh ? 'A' : 'N';\t\t\t\t\\\n    Eigen::Matrix<t, M, N> A = m;\t\t\t\t\t\\\n    const     lapack_int LDA   = M;\t\t\t\t\t\\\n              t   *U    = u ? u->data() : 0;\t\t\t\t\\\n    const     lapack_int LDU   = M;\t\t\t\t\t\\\n              t   *VT   = vh ? vh->data() : 0;\t\t\t\t\\\n    const     lapack_int LDVT  = N;\t\t\t\t\t\\\n    const     lapack_int LWORK = get_lwork(__VA_ARGS__,);\t\t\\\n    Eigen::Array<t, LWORK, 1> WORK;\t\t\t\t\t\\\n    decl_rwork(__VA_ARGS__);\t\t\t\t\t\t\\\n    lapack_int INFO;\t\t\t\t\t\t\t\\\n    f(JOBU, JOBVT, M, N, A.data(), LDA, s.data(), U, LDU, VT, LDVT,\t\\\n      WORK.data(), LWORK, put_rwork(__VA_ARGS__) INFO);\t\t\t\\\n}\n\n#define def_hermitian_lapack(s, f, ...)\t\t\t\t\t\\\ntemplate<int N>\t\t\t\t\t\t\t\t\\\nvoid hermitian_lapack\t\t\t\t\t\t\t\\\n(const Eigen::Matrix<s, N, N>& m,\t\t\t\t\t\\\n Eigen::Array<double, N, 1>& w,\t\t\t\t\t\t\\\n Eigen::Matrix<s, N, N> *z = 0)\t\t\t\t\t\t\\\n{\t\t\t\t\t\t\t\t\t\\\n    const     char JOBZ = z ? 'V' : 'N';\t\t\t\t\\\n    const     char UPLO = 'L';\t\t\t\t\t\t\\\n    Eigen::Matrix<s, N, N> A = m;\t\t\t\t\t\\\n    const     lapack_int LDA   = N;\t\t\t\t\t\\\n    const     lapack_int LWORK = get_lwork(__VA_ARGS__,);\t\t\\\n    Eigen::Array<s, LWORK, 1> WORK;\t\t\t\t\t\\\n    decl_rwork(__VA_ARGS__);\t\t\t\t\t\t\\\n    lapack_int INFO;\t\t\t\t\t\t\t\\\n    f(JOBZ, UPLO, N, A.data(), LDA, w.data(), WORK.data(), LWORK,\t\\\n      put_rwork(__VA_ARGS__) INFO);\t\t\t\t\t\\\n    if (z) *z = A;\t\t\t\t\t\t\t\\\n}\n\n#define get_lwork(lwork, ...) (lwork)\n\n#define get_rwork_macro(_1, _2, name, ...) name\n\n#define nop_(_1)\n\n#define do_decl_rwork(_1, lrwork) Eigen::Array<double, (lrwork), 1> RWORK\n\n#define decl_rwork(...) \\\n    get_rwork_macro(__VA_ARGS__, do_decl_rwork, nop_,)(__VA_ARGS__)\n\n#define do_put_rwork(_1, _2) RWORK.data(),\n\n#define put_rwork(...) \\\n    get_rwork_macro(__VA_ARGS__, do_put_rwork, nop_,)(__VA_ARGS__)\n\ndef_svd_lapack(std::complex<double>, zgesvd_, 3*MAX_(M,N), 5*MIN_(M,N))\ndef_svd_lapack(double, dgesvd_, MAX_(3*MIN_(M,N)+MAX_(M,N),5*MIN_(M,N)))\n\ndef_hermitian_lapack(std::complex<double>, zheev_, 2*N-1, 3*N-2)\ndef_hermitian_lapack(double, dsyev_, 3*N-1)\n\n#endif // ENABLE_LAPACK\n\n/**\n * Template version of DDISNA from LAPACK.\n */\ntemplate<int M, int N, class Real>\nvoid disna(const char& JOB, const Eigen::Array<Real, MIN_(M, N), 1>& D,\n\t   Eigen::Array<Real, MIN_(M, N), 1>& SEP, int& INFO)\n{\n//  -- LAPACK computational routine (version 3.4.0) --\n//  -- LAPACK is a software package provided by Univ. of Tennessee,    --\n//  -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..--\n//     November 2011\n//\n//  =====================================================================\n\n//     .. Parameters ..\n      const Real         ZERO = 0;\n//     .. Local Scalars ..\n      bool               DECR, EIGEN, INCR, LEFT, RIGHT, SINGUL;\n      int                I, K;\n      Real               ANORM, EPS, NEWGAP, OLDGAP, SAFMIN, THRESH;\n//\n//     Test the input arguments\n//\n      INFO = 0;\n      EIGEN = std::toupper(JOB) == 'E';\n      LEFT  = std::toupper(JOB) == 'L';\n      RIGHT = std::toupper(JOB) == 'R';\n      SINGUL = LEFT || RIGHT;\n      if (EIGEN)\n\t K = M;\n      else if (SINGUL)\n         K = MIN_(M, N);\n      if (!EIGEN && !SINGUL)\n         INFO = -1;\n      else if (M < 0)\n         INFO = -2;\n      else if (K < 0)\n         INFO = -3;\n      else {\n         INCR = true;\n         DECR = true;\n         for (I = 0; I < K - 1; I++) {\n            if (INCR)\n               INCR = INCR && D(I) <= D(I+1);\n            if (DECR)\n\t       DECR = DECR && D(I) >= D(I+1);\n\t }\n         if (SINGUL && K > 0) {\n            if (INCR)\n               INCR = INCR && ZERO <= D(0);\n            if (DECR)\n               DECR = DECR && D(K-1) >= ZERO;\n         }\n         if (!(INCR || DECR))\n            INFO = -4;\n      }\n      if (INFO != 0) {\n         // CALL XERBLA( 'DDISNA', -INFO )\n         return;\n      }\n//\n//     Quick return if possible\n//\n      if (K == 0)\n         return;\n//\n//     Compute reciprocal condition numbers\n//\n      if (K == 1)\n         SEP(0) = std::numeric_limits<Real>::max();\n      else {\n         OLDGAP = std::fabs(D(1) - D(0));\n         SEP(0) = OLDGAP;\n         for (I = 1; I < K - 1; I++) {\n            NEWGAP = std::fabs(D(I+1) - D(I));\n            SEP(I) = std::min(OLDGAP, NEWGAP);\n            OLDGAP = NEWGAP;\n\t }\n         SEP(K-1) = OLDGAP;\n      }\n      if (SINGUL)\n         if ((LEFT && M > N) || (RIGHT && M < N)) {\n            if (INCR)\n               SEP( 0 ) = std::min(SEP( 0 ), D( 0 ));\n            if (DECR)\n               SEP(K-1) = std::min(SEP(K-1), D(K-1));\n         }\n//\n//     Ensure that reciprocal condition numbers are not less than\n//     threshold, in order to limit the size of the error bound\n//\n      // Note std::numeric_limits<double>::epsilon() == 2 * DLAMCH('E')\n      // since  the former is the smallest eps such that 1.0 + eps > 1.0\n      // while DLAMCH('E') is the smallest eps such that 1.0 - eps < 1.0\n      EPS = std::numeric_limits<Real>::epsilon();\n      SAFMIN = std::numeric_limits<Real>::min();\n      ANORM = std::max(std::fabs(D(0)), std::fabs(D(K-1)));\n      if (ANORM == ZERO)\n         THRESH = EPS;\n      else\n         THRESH = std::max(EPS*ANORM, SAFMIN);\n      for (I = 0; I < K; I++)\n\t SEP(I) = std::max(SEP(I), THRESH);\n}\n\n\ntemplate<class Real, class Scalar, int M, int N>\nvoid svd_internal\n(const Eigen::Matrix<Scalar, M, N>& m,\n Eigen::Array<Real, MIN_(M, N), 1>& s,\n Eigen::Matrix<Scalar, M, M> *u,\n Eigen::Matrix<Scalar, N, N> *vh)\n{\n    svd_eigen(m, s, u, vh);\n}\n\n#ifdef ENABLE_LAPACK\n\n// ZGESVD of ATLAS seems to be faster than Eigen::JacobiSVD for M, N >= 4\n\ntemplate<class Scalar, int M, int N>\nvoid svd_internal\n(const Eigen::Matrix<Scalar, M, N>& m,\n Eigen::Array<double, MIN_(M, N), 1>& s,\n Eigen::Matrix<Scalar, M, M> *u,\n Eigen::Matrix<Scalar, N, N> *vh)\n{\n    svd_lapack(m, s, u, vh);\n}\n\ntemplate<class Scalar>\nvoid svd_internal\n(const Eigen::Matrix<Scalar, 3, 3>& m,\n Eigen::Array<double, 3, 1>& s,\n Eigen::Matrix<Scalar, 3, 3> *u,\n Eigen::Matrix<Scalar, 3, 3> *vh)\n{\n    svd_eigen(m, s, u, vh);\n}\n\ntemplate<class Scalar>\nvoid svd_internal\n(const Eigen::Matrix<Scalar, 2, 2>& m,\n Eigen::Array<double, 2, 1>& s,\n Eigen::Matrix<Scalar, 2, 2> *u,\n Eigen::Matrix<Scalar, 2, 2> *vh)\n{\n    svd_eigen(m, s, u, vh);\n}\n\ntemplate<class Scalar>\nvoid svd_internal\n(const Eigen::Matrix<Scalar, 1, 1>& m,\n Eigen::Array<double, 1, 1>& s,\n Eigen::Matrix<Scalar, 1, 1> *u,\n Eigen::Matrix<Scalar, 1, 1> *vh)\n{\n    svd_eigen(m, s, u, vh);\n}\n\n#endif // ENABLE_LAPACK\n\ntemplate<class Real, class Scalar, int M, int N>\nvoid svd_errbd\n(const Eigen::Matrix<Scalar, M, N>& m,\n Eigen::Array<Real, MIN_(M, N), 1>& s,\n Eigen::Matrix<Scalar, M, M> *u  = 0,\n Eigen::Matrix<Scalar, N, N> *vh = 0,\n Real *s_errbd = 0,\n Eigen::Array<Real, MIN_(M, N), 1> *u_errbd = 0,\n Eigen::Array<Real, MIN_(M, N), 1> *v_errbd = 0)\n{\n    svd_internal(m, s, u, vh);\n\n    // see http://www.netlib.org/lapack/lug/node96.html\n    if (!s_errbd) return;\n    const Real EPSMCH = std::numeric_limits<Real>::epsilon();\n    *s_errbd = EPSMCH * s[0];\n\n    Eigen::Array<Real, MIN_(M, N), 1> RCOND;\n    int INFO;\n    if (u_errbd) {\n\tdisna<M, N>('L', s, RCOND, INFO);\n\tu_errbd->fill(*s_errbd);\n\t*u_errbd /= RCOND;\n    }\n    if (v_errbd) {\n\tdisna<M, N>('R', s, RCOND, INFO);\n\tv_errbd->fill(*s_errbd);\n\t*v_errbd /= RCOND;\n    }\n}\n\n/**\n * Singular value decomposition of M-by-N matrix m such that\n *\n *     sigma.setZero(); sigma.diagonal() = s;\n *     m == u * sigma * vh    // LAPACK convention\n *\n * and `(s >= 0).all()`.  Elements of s are in descending order.  The\n * above decomposition can be put in the form\n *\n *     m == u * s.matrix().asDiagonal() * vh\n *\n * if `M == N`.\n *\n * @tparam     Real   type of real and imaginary parts of Scalar\n * @tparam     Scalar type of elements of m, u, and vh\n * @tparam     M      number of rows in m\n * @tparam     N      number of columns in m\n * @param[in]  m      M-by-N matrix to be decomposed\n * @param[out] s      array of length min(M,N) to contain singular values\n * @param[out] u      M-by-M unitary matrix\n * @param[out] vh     N-by-N unitary matrix\n */\ntemplate<class Real, class Scalar, int M, int N>\nvoid svd\n(const Eigen::Matrix<Scalar, M, N>& m,\n Eigen::Array<Real, MIN_(M, N), 1>& s,\n Eigen::Matrix<Scalar, M, M>& u,\n Eigen::Matrix<Scalar, N, N>& vh)\n{\n    svd_errbd(m, s, &u, &vh);\n}\n\n/**\n * Same as svd(m, s, u, vh) except that an approximate error bound for\n * the singular values is returned as well.  The error bound is\n * estimated following the method presented at\n * http://www.netlib.org/lapack/lug/node96.html.\n *\n * @param[out] s_errbd approximate error bound for the elements of s\n *\n * See the documentation of svd(m, s, u, vh) for the other parameters.\n */\ntemplate<class Real, class Scalar, int M, int N>\nvoid svd\n(const Eigen::Matrix<Scalar, M, N>& m,\n Eigen::Array<Real, MIN_(M, N), 1>& s,\n Eigen::Matrix<Scalar, M, M>& u,\n Eigen::Matrix<Scalar, N, N>& vh,\n Real& s_errbd)\n{\n    svd_errbd(m, s, &u, &vh, &s_errbd);\n}\n\n/**\n * Same as svd(m, s, u, vh, s_errbd) except that approximate error\n * bounds for the singular vectors are returned as well.  The error\n * bounds are estimated following the method presented at\n * http://www.netlib.org/lapack/lug/node96.html.\n *\n * @param[out] u_errbd array of approximate error bounds for u\n * @param[out] v_errbd array of approximate error bounds for vh\n *\n * See the documentation of svd(m, s, u, vh, s_errbd) for the other\n * parameters.\n */\ntemplate<class Real, class Scalar, int M, int N>\nvoid svd\n(const Eigen::Matrix<Scalar, M, N>& m,\n Eigen::Array<Real, MIN_(M, N), 1>& s,\n Eigen::Matrix<Scalar, M, M>& u,\n Eigen::Matrix<Scalar, N, N>& vh,\n Real& s_errbd,\n Eigen::Array<Real, MIN_(M, N), 1>& u_errbd,\n Eigen::Array<Real, MIN_(M, N), 1>& v_errbd)\n{\n    svd_errbd(m, s, &u, &vh, &s_errbd, &u_errbd, &v_errbd);\n}\n\n/**\n * Returns singular values of M-by-N matrix m via s such that\n * `(s >= 0).all()`.  Elements of s are in descending order.\n *\n * @tparam     Real   type of real and imaginary parts of Scalar\n * @tparam     Scalar type of elements of m, u, and vh\n * @tparam     M      number of rows in m\n * @tparam     N      number of columns in m\n * @param[in]  m      M-by-N matrix to be decomposed\n * @param[out] s      array of length min(M,N) to contain singular values\n */\ntemplate<class Real, class Scalar, int M, int N>\nvoid svd\n(const Eigen::Matrix<Scalar, M, N>& m,\n Eigen::Array<Real, MIN_(M, N), 1>& s)\n{\n    svd_errbd(m, s);\n}\n\n/**\n * Same as svd(m, s) except that an approximate error bound for the\n * singular values is returned as well.  The error bound is estimated\n * following the method presented at\n * http://www.netlib.org/lapack/lug/node96.html.\n *\n * @param[out] s_errbd approximate error bound for the elements of s\n *\n * See the documentation of svd(m, s) for the other parameters.\n */\ntemplate<class Real, class Scalar, int M, int N>\nvoid svd\n(const Eigen::Matrix<Scalar, M, N>& m,\n Eigen::Array<Real, MIN_(M, N), 1>& s,\n Real& s_errbd)\n{\n    svd_errbd(m, s, 0, 0, &s_errbd);\n}\n\n// Eigen::SelfAdjointEigenSolver seems to be faster than ZHEEV of ATLAS\n\ntemplate<class Real, class Scalar, int N>\nvoid diagonalize_hermitian_internal\n(const Eigen::Matrix<Scalar, N, N>& m,\n Eigen::Array<Real, N, 1>& w,\n Eigen::Matrix<Scalar, N, N> *z)\n{\n    hermitian_eigen(m, w, z);\n}\n\ntemplate<class Real, class Scalar, int N>\nvoid diagonalize_hermitian_errbd\n(const Eigen::Matrix<Scalar, N, N>& m,\n Eigen::Array<Real, N, 1>& w,\n Eigen::Matrix<Scalar, N, N> *z = 0,\n Real *w_errbd = 0,\n Eigen::Array<Real, N, 1> *z_errbd = 0)\n{\n    diagonalize_hermitian_internal(m, w, z);\n\n    // see http://www.netlib.org/lapack/lug/node89.html\n    if (!w_errbd) return;\n    const Real EPSMCH = std::numeric_limits<Real>::epsilon();\n    Real mnorm = std::max(std::abs(w[0]), std::abs(w[N-1]));\n    *w_errbd = EPSMCH * mnorm;\n\n    if (!z_errbd) return;\n    Eigen::Array<Real, N, 1> RCONDZ;\n    int INFO;\n    disna<N, N>('E', w, RCONDZ, INFO);\n    z_errbd->fill(*w_errbd);\n    *z_errbd /= RCONDZ;\n}\n\n/**\n * Diagonalizes N-by-N hermitian matrix m so that\n *\n *     m == z * w.matrix().asDiagonal() * z.adjoint()\n *\n * Elements of w are in ascending order.\n *\n * @tparam     Real   type of real and imaginary parts of Scalar\n * @tparam     Scalar type of elements of m and z\n * @tparam     N      number of rows and columns in m and z\n * @param[in]  m      N-by-N matrix to be diagonalized\n * @param[out] w      array of length N to contain eigenvalues\n * @param[out] z      N-by-N unitary matrix\n */\ntemplate<class Real, class Scalar, int N>\nvoid diagonalize_hermitian\n(const Eigen::Matrix<Scalar, N, N>& m,\n Eigen::Array<Real, N, 1>& w,\n Eigen::Matrix<Scalar, N, N>& z)\n{\n    diagonalize_hermitian_errbd(m, w, &z);\n}\n\n/**\n * Same as diagonalize_hermitian(m, w, z) except that an approximate\n * error bound for the eigenvalues is returned as well.  The error\n * bound is estimated following the method presented at\n * http://www.netlib.org/lapack/lug/node89.html.\n *\n * @param[out] w_errbd approximate error bound for the elements of w\n *\n * See the documentation of diagonalize_hermitian(m, w, z) for the\n * other parameters.\n */\ntemplate<class Real, class Scalar, int N>\nvoid diagonalize_hermitian\n(const Eigen::Matrix<Scalar, N, N>& m,\n Eigen::Array<Real, N, 1>& w,\n Eigen::Matrix<Scalar, N, N>& z,\n Real& w_errbd)\n{\n    diagonalize_hermitian_errbd(m, w, &z, &w_errbd);\n}\n\n/**\n * Same as diagonalize_hermitian(m, w, z, w_errbd) except that\n * approximate error bounds for the eigenvectors are returned as well.\n * The error bounds are estimated following the method presented at\n * http://www.netlib.org/lapack/lug/node89.html.\n *\n * @param[out] z_errbd array of approximate error bounds for z\n *\n * See the documentation of diagonalize_hermitian(m, w, z, w_errbd)\n * for the other parameters.\n */\ntemplate<class Real, class Scalar, int N>\nvoid diagonalize_hermitian\n(const Eigen::Matrix<Scalar, N, N>& m,\n Eigen::Array<Real, N, 1>& w,\n Eigen::Matrix<Scalar, N, N>& z,\n Real& w_errbd,\n Eigen::Array<Real, N, 1>& z_errbd)\n{\n    diagonalize_hermitian_errbd(m, w, &z, &w_errbd, &z_errbd);\n}\n\n/**\n * Returns eigenvalues of N-by-N hermitian matrix m via w.\n * Elements of w are in ascending order.\n *\n * @tparam     Real   type of real and imaginary parts of Scalar\n * @tparam     Scalar type of elements of m and z\n * @tparam     N      number of rows and columns in m and z\n * @param[in]  m      N-by-N matrix to be diagonalized\n * @param[out] w      array of length N to contain eigenvalues\n */\ntemplate<class Real, class Scalar, int N>\nvoid diagonalize_hermitian\n(const Eigen::Matrix<Scalar, N, N>& m,\n Eigen::Array<Real, N, 1>& w)\n{\n    diagonalize_hermitian_errbd(m, w);\n}\n\n/**\n * Same as diagonalize_hermitian(m, w) except that an approximate\n * error bound for the eigenvalues is returned as well.  The error\n * bound is estimated following the method presented at\n * http://www.netlib.org/lapack/lug/node89.html.\n *\n * @param[out] w_errbd approximate error bound for the elements of w\n *\n * See the documentation of diagonalize_hermitian(m, w) for the other\n * parameters.\n */\ntemplate<class Real, class Scalar, int N>\nvoid diagonalize_hermitian\n(const Eigen::Matrix<Scalar, N, N>& m,\n Eigen::Array<Real, N, 1>& w,\n Real& w_errbd)\n{\n    diagonalize_hermitian_errbd(m, w, 0, &w_errbd);\n}\n\ntemplate<class Real>\nstruct RephaseOp {\n    std::complex<Real> operator() (const std::complex<Real>& z) const\n\t{ return std::polar(Real(1), std::arg(z)/2); }\n};\n\ntemplate<class Real, int N>\nvoid diagonalize_symmetric_errbd\n(const Eigen::Matrix<std::complex<Real>, N, N>& m,\n Eigen::Array<Real, N, 1>& s,\n Eigen::Matrix<std::complex<Real>, N, N> *u = 0,\n Real *s_errbd = 0,\n Eigen::Array<Real, N, 1> *u_errbd = 0)\n{\n    svd_errbd(m, s, u, (Eigen::Matrix<std::complex<Real>, N, N> *)0,\n\t      s_errbd, u_errbd);\n    if (!u) return;\n    Eigen::Array<std::complex<Real>, N, 1> diag =\n\t(u->adjoint() * m * u->conjugate()).diagonal();\n    *u *= diag.unaryExpr(RephaseOp<Real>()).matrix().asDiagonal();\n}\n\n/**\n * Diagonalizes N-by-N complex symmetric matrix m so that\n *\n *     m == u * s.matrix().asDiagonal() * u.transpose()\n *\n * and `(s >= 0).all()`.  Elements of s are in descending order.\n *\n * @tparam     Real type of real and imaginary parts\n * @tparam     N    number of rows and columns in m and u\n * @param[in]  m    N-by-N complex symmetric matrix to be decomposed\n * @param[out] s    array of length N to contain singular values\n * @param[out] u    N-by-N complex unitary matrix\n */\ntemplate<class Real, int N>\nvoid diagonalize_symmetric\n(const Eigen::Matrix<std::complex<Real>, N, N>& m,\n Eigen::Array<Real, N, 1>& s,\n Eigen::Matrix<std::complex<Real>, N, N>& u)\n{\n    diagonalize_symmetric_errbd(m, s, &u);\n}\n\n/**\n * Same as diagonalize_symmetric(m, s, u) except that an approximate\n * error bound for the singular values is returned as well.  The error\n * bound is estimated following the method presented at\n * http://www.netlib.org/lapack/lug/node96.html.\n *\n * @param[out] s_errbd approximate error bound for the elements of s\n *\n * See the documentation of diagonalize_symmetric(m, s, u) for the\n * other parameters.\n */\ntemplate<class Real, int N>\nvoid diagonalize_symmetric\n(const Eigen::Matrix<std::complex<Real>, N, N>& m,\n Eigen::Array<Real, N, 1>& s,\n Eigen::Matrix<std::complex<Real>, N, N>& u,\n Real& s_errbd)\n{\n    diagonalize_symmetric_errbd(m, s, &u, &s_errbd);\n}\n\n/**\n * Same as diagonalize_symmetric(m, s, u, s_errbd) except that\n * approximate error bounds for the singular vectors are returned as\n * well.  The error bounds are estimated following the method\n * presented at http://www.netlib.org/lapack/lug/node96.html.\n *\n * @param[out] u_errbd array of approximate error bounds for u\n *\n * See the documentation of diagonalize_symmetric(m, s, u, s_errbd)\n * for the other parameters.\n */\ntemplate<class Real, int N>\nvoid diagonalize_symmetric\n(const Eigen::Matrix<std::complex<Real>, N, N>& m,\n Eigen::Array<Real, N, 1>& s,\n Eigen::Matrix<std::complex<Real>, N, N>& u,\n Real& s_errbd,\n Eigen::Array<Real, N, 1>& u_errbd)\n{\n    diagonalize_symmetric_errbd(m, s, &u, &s_errbd, &u_errbd);\n}\n\n/**\n * Returns singular values of N-by-N complex symmetric matrix m via s\n * such that `(s >= 0).all()`.  Elements of s are in descending order.\n *\n * @tparam     Real type of real and imaginary parts\n * @tparam     N    number of rows and columns in m and u\n * @param[in]  m    N-by-N complex symmetric matrix to be decomposed\n * @param[out] s    array of length N to contain singular values\n */\ntemplate<class Real, int N>\nvoid diagonalize_symmetric\n(const Eigen::Matrix<std::complex<Real>, N, N>& m,\n Eigen::Array<Real, N, 1>& s)\n{\n    diagonalize_symmetric_errbd(m, s);\n}\n\n/**\n * Same as diagonalize_symmetric(m, s) except that an approximate\n * error bound for the singular values is returned as well.  The error\n * bound is estimated following the method presented at\n * http://www.netlib.org/lapack/lug/node96.html.\n *\n * @param[out] s_errbd approximate error bound for the elements of s\n *\n * See the documentation of diagonalize_symmetric(m, s) for the other\n * parameters.\n */\ntemplate<class Real, int N>\nvoid diagonalize_symmetric\n(const Eigen::Matrix<std::complex<Real>, N, N>& m,\n Eigen::Array<Real, N, 1>& s,\n Real& s_errbd)\n{\n    diagonalize_symmetric_errbd(m, s, 0, &s_errbd);\n}\n\ntemplate<class Real>\nstruct FlipSignOp {\n    std::complex<Real> operator() (const std::complex<Real>& z) const {\n\treturn z.real() < 0 ? std::complex<Real>(0,1) :\n\t    std::complex<Real>(1,0);\n    }\n};\n\ntemplate<class Real, int N>\nvoid diagonalize_symmetric_errbd\n(const Eigen::Matrix<Real, N, N>& m,\n Eigen::Array<Real, N, 1>& s,\n Eigen::Matrix<std::complex<Real>, N, N> *u = 0,\n Real *s_errbd = 0,\n Eigen::Array<Real, N, 1> *u_errbd = 0)\n{\n    Eigen::Matrix<Real, N, N> z;\n    diagonalize_hermitian_errbd(m, s, u ? &z : 0, s_errbd, u_errbd);\n    // see http://forum.kde.org/viewtopic.php?f=74&t=62606\n    if (u) *u = z * s.template cast<std::complex<Real> >().\n\t\tunaryExpr(FlipSignOp<Real>()).matrix().asDiagonal();\n    s = s.abs();\n}\n\n/**\n * Diagonalizes N-by-N real symmetric matrix m so that\n *\n *     m == u * s.matrix().asDiagonal() * u.transpose()\n *\n * and `(s >= 0).all()`.  Order of elements of s is *unspecified*.\n *\n * @tparam     Real type of real and imaginary parts\n * @tparam     N    number of rows and columns of m\n * @param[in]  m    N-by-N real symmetric matrix to be decomposed\n * @param[out] s    array of length N to contain singular values\n * @param[out] u    N-by-N complex unitary matrix\n *\n * @note Use diagonalize_hermitian() unless sign of `s[i]` matters.\n */\ntemplate<class Real, int N>\nvoid diagonalize_symmetric\n(const Eigen::Matrix<Real, N, N>& m,\n Eigen::Array<Real, N, 1>& s,\n Eigen::Matrix<std::complex<Real>, N, N>& u)\n{\n    diagonalize_symmetric_errbd(m, s, &u);\n}\n\n/**\n * Same as diagonalize_symmetric(m, s, u) except that an approximate\n * error bound for the singular values is returned as well.  The error\n * bound is estimated following the method presented at\n * http://www.netlib.org/lapack/lug/node89.html.\n *\n * @param[out] s_errbd approximate error bound for the elements of s\n *\n * See the documentation of diagonalize_symmetric(m, s, u) for the\n * other parameters.\n */\ntemplate<class Real, int N>\nvoid diagonalize_symmetric\n(const Eigen::Matrix<Real, N, N>& m,\n Eigen::Array<Real, N, 1>& s,\n Eigen::Matrix<std::complex<Real>, N, N>& u,\n Real& s_errbd)\n{\n    diagonalize_symmetric_errbd(m, s, &u, &s_errbd);\n}\n\n/**\n * Same as diagonalize_symmetric(m, s, u, s_errbd) except that\n * approximate error bounds for the singular vectors are returned as\n * well.  The error bounds are estimated following the method\n * presented at http://www.netlib.org/lapack/lug/node89.html.\n *\n * @param[out] u_errbd array of approximate error bounds for u\n *\n * See the documentation of diagonalize_symmetric(m, s, u, s_errbd)\n * for the other parameters.\n */\ntemplate<class Real, int N>\nvoid diagonalize_symmetric\n(const Eigen::Matrix<Real, N, N>& m,\n Eigen::Array<Real, N, 1>& s,\n Eigen::Matrix<std::complex<Real>, N, N>& u,\n Real& s_errbd,\n Eigen::Array<Real, N, 1>& u_errbd)\n{\n    diagonalize_symmetric_errbd(m, s, &u, &s_errbd, &u_errbd);\n}\n\n/**\n * Returns singular values of N-by-N real symmetric matrix m via s\n * such that `(s >= 0).all()`.  Order of elements of s is\n * *unspecified*.\n *\n * @tparam     Real type of elements of m and s\n * @tparam     N    number of rows and columns of m\n * @param[in]  m    N-by-N real symmetric matrix to be decomposed\n * @param[out] s    array of length N to contain singular values\n *\n * @note Use diagonalize_hermitian() unless sign of `s[i]` matters.\n */\ntemplate<class Real, int N>\nvoid diagonalize_symmetric\n(const Eigen::Matrix<Real, N, N>& m,\n Eigen::Array<Real, N, 1>& s)\n{\n    diagonalize_symmetric_errbd(m, s);\n}\n\n/**\n * Same as diagonalize_symmetric(m, s) except that an approximate\n * error bound for the singular values is returned as well.  The error\n * bound is estimated following the method presented at\n * http://www.netlib.org/lapack/lug/node89.html.\n *\n * @param[out] s_errbd approximate error bound for the elements of s\n *\n * See the documentation of diagonalize_symmetric(m, s) for the other\n * parameters.\n */\ntemplate<class Real, int N>\nvoid diagonalize_symmetric\n(const Eigen::Matrix<Real, N, N>& m,\n Eigen::Array<Real, N, 1>& s,\n Real& s_errbd)\n{\n    diagonalize_symmetric_errbd(m, s, 0, &s_errbd);\n}\n\ntemplate<class Real, class Scalar, int M, int N>\nvoid reorder_svd_errbd\n(const Eigen::Matrix<Scalar, M, N>& m,\n Eigen::Array<Real, MIN_(M, N), 1>& s,\n Eigen::Matrix<Scalar, M, M> *u  = 0,\n Eigen::Matrix<Scalar, N, N> *vh = 0,\n Real *s_errbd = 0,\n Eigen::Array<Real, MIN_(M, N), 1> *u_errbd = 0,\n Eigen::Array<Real, MIN_(M, N), 1> *v_errbd = 0)\n{\n    svd_errbd(m, s, u, vh, s_errbd, u_errbd, v_errbd);\n    s.reverseInPlace();\n    if (u) {\n\tEigen::PermutationMatrix<M> p;\n\tp.setIdentity();\n\tp.indices().template segment<MIN_(M, N)>(0).reverseInPlace();\n\t*u *= p;\n    }\n    if (vh) {\n\tEigen::PermutationMatrix<N> p;\n\tp.setIdentity();\n\tp.indices().template segment<MIN_(M, N)>(0).reverseInPlace();\n\tvh->transpose() *= p;\n    }\n    if (u_errbd) u_errbd->reverseInPlace();\n    if (v_errbd) v_errbd->reverseInPlace();\n}\n\n/**\n * Singular value decomposition of M-by-N matrix m such that\n *\n *     sigma.setZero(); sigma.diagonal() = s;\n *     m == u * sigma * vh    // LAPACK convention\n *\n * and `(s >= 0).all()`.  Elements of s are in ascending order.  The\n * above decomposition can be put in the form\n *\n *     m == u * s.matrix().asDiagonal() * vh\n *\n * if `M == N`.\n *\n * @tparam     Real   type of real and imaginary parts of Scalar\n * @tparam     Scalar type of elements of m, u, and vh\n * @tparam     M      number of rows in m\n * @tparam     N      number of columns in m\n * @param[in]  m      M-by-N matrix to be decomposed\n * @param[out] s      array of length min(M,N) to contain singular values\n * @param[out] u      M-by-M unitary matrix\n * @param[out] vh     N-by-N unitary matrix\n */\ntemplate<class Real, class Scalar, int M, int N>\nvoid reorder_svd\n(const Eigen::Matrix<Scalar, M, N>& m,\n Eigen::Array<Real, MIN_(M, N), 1>& s,\n Eigen::Matrix<Scalar, M, M>& u,\n Eigen::Matrix<Scalar, N, N>& vh)\n{\n    reorder_svd_errbd(m, s, &u, &vh);\n}\n\n/**\n * Same as reorder_svd(m, s, u, vh) except that an approximate error\n * bound for the singular values is returned as well.  The error bound\n * is estimated following the method presented at\n * http://www.netlib.org/lapack/lug/node96.html.\n *\n * @param[out] s_errbd approximate error bound for the elements of s\n *\n * See the documentation of reorder_svd(m, s, u, vh) for the other\n * parameters.\n */\ntemplate<class Real, class Scalar, int M, int N>\nvoid reorder_svd\n(const Eigen::Matrix<Scalar, M, N>& m,\n Eigen::Array<Real, MIN_(M, N), 1>& s,\n Eigen::Matrix<Scalar, M, M>& u,\n Eigen::Matrix<Scalar, N, N>& vh,\n Real& s_errbd)\n{\n    reorder_svd_errbd(m, s, &u, &vh, &s_errbd);\n}\n\n/**\n * Same as reorder_svd(m, s, u, vh, s_errbd) except that approximate\n * error bounds for the singular vectors are returned as well.  The\n * error bounds are estimated following the method presented at\n * http://www.netlib.org/lapack/lug/node96.html.\n *\n * @param[out] u_errbd array of approximate error bounds for u\n * @param[out] v_errbd array of approximate error bounds for vh\n *\n * See the documentation of reorder_svd(m, s, u, vh, s_errbd) for the\n * other parameters.\n */\ntemplate<class Real, class Scalar, int M, int N>\nvoid reorder_svd\n(const Eigen::Matrix<Scalar, M, N>& m,\n Eigen::Array<Real, MIN_(M, N), 1>& s,\n Eigen::Matrix<Scalar, M, M>& u,\n Eigen::Matrix<Scalar, N, N>& vh,\n Real& s_errbd,\n Eigen::Array<Real, MIN_(M, N), 1>& u_errbd,\n Eigen::Array<Real, MIN_(M, N), 1>& v_errbd)\n{\n    reorder_svd_errbd(m, s, &u, &vh, &s_errbd, &u_errbd, &v_errbd);\n}\n\n/**\n * Returns singular values of M-by-N matrix m via s such that\n * `(s >= 0).all()`.  Elements of s are in ascending order.\n *\n * @tparam     Real   type of real and imaginary parts of Scalar\n * @tparam     Scalar type of elements of m, u, and vh\n * @tparam     M      number of rows in m\n * @tparam     N      number of columns in m\n * @param[in]  m      M-by-N matrix to be decomposed\n * @param[out] s      array of length min(M,N) to contain singular values\n */\ntemplate<class Real, class Scalar, int M, int N>\nvoid reorder_svd\n(const Eigen::Matrix<Scalar, M, N>& m,\n Eigen::Array<Real, MIN_(M, N), 1>& s)\n{\n    reorder_svd_errbd(m, s);\n}\n\n/**\n * Same as reorder_svd(m, s) except that an approximate error bound\n * for the singular values is returned as well.  The error bound is\n * estimated following the method presented at\n * http://www.netlib.org/lapack/lug/node96.html.\n *\n * @param[out] s_errbd approximate error bound for the elements of s\n *\n * See the documentation of reorder_svd(m, s) for the other\n * parameters.\n */\ntemplate<class Real, class Scalar, int M, int N>\nvoid reorder_svd\n(const Eigen::Matrix<Scalar, M, N>& m,\n Eigen::Array<Real, MIN_(M, N), 1>& s,\n Real& s_errbd)\n{\n    reorder_svd_errbd(m, s, 0, 0, &s_errbd);\n}\n\ntemplate<class Real, int N>\nvoid reorder_diagonalize_symmetric_errbd\n(const Eigen::Matrix<std::complex<Real>, N, N>& m,\n Eigen::Array<Real, N, 1>& s,\n Eigen::Matrix<std::complex<Real>, N, N> *u = 0,\n Real *s_errbd = 0,\n Eigen::Array<Real, N, 1> *u_errbd = 0)\n{\n    diagonalize_symmetric_errbd(m, s, u, s_errbd, u_errbd);\n    s.reverseInPlace();\n    if (u) *u = u->rowwise().reverse().eval();\n    if (u_errbd) u_errbd->reverseInPlace();\n}\n\ntemplate<class Real, int N>\nvoid reorder_diagonalize_symmetric_errbd\n(const Eigen::Matrix<Real, N, N>& m,\n Eigen::Array<Real, N, 1>& s,\n Eigen::Matrix<std::complex<Real>, N, N> *u = 0,\n Real *s_errbd = 0,\n Eigen::Array<Real, N, 1> *u_errbd = 0)\n{\n    diagonalize_symmetric_errbd(m, s, u, s_errbd, u_errbd);\n    Eigen::PermutationMatrix<N> p;\n    p.setIdentity();\n    std::sort(p.indices().data(), p.indices().data() + p.indices().size(),\n              [&s] (int i, int j) { return s[i] < s[j]; });\n#if EIGEN_VERSION_AT_LEAST(3,1,4)\n    s.matrix().transpose() *= p;\n    if (u_errbd) u_errbd->matrix().transpose() *= p;\n#else\n    Eigen::Map<Eigen::Matrix<Real, N, 1> >(s.data()).transpose() *= p;\n    if (u_errbd)\n\tEigen::Map<Eigen::Matrix<Real, N, 1> >(u_errbd->data()).transpose()\n\t    *= p;\n#endif\n    if (u) *u *= p;\n}\n\n/**\n * Diagonalizes N-by-N symmetric matrix m so that\n *\n *     m == u * s.matrix().asDiagonal() * u.transpose()\n *\n * and `(s >= 0).all()`.  Elements of s are in ascending order.\n *\n * @tparam     Real   type of real and imaginary parts of Scalar\n * @tparam     Scalar type of elements of m\n * @tparam     N      number of rows and columns in m and u\n * @param[in]  m      N-by-N symmetric matrix to be decomposed\n * @param[out] s      array of length N to contain singular values\n * @param[out] u      N-by-N complex unitary matrix\n */\ntemplate<class Real, class Scalar, int N>\nvoid reorder_diagonalize_symmetric\n(const Eigen::Matrix<Scalar, N, N>& m,\n Eigen::Array<Real, N, 1>& s,\n Eigen::Matrix<std::complex<Real>, N, N>& u)\n{\n    reorder_diagonalize_symmetric_errbd(m, s, &u);\n}\n\n/**\n * Same as reorder_diagonalize_symmetric(m, s, u) except that an\n * approximate error bound for the singular values is returned as\n * well.  The error bound is estimated following the method presented\n * at http://www.netlib.org/lapack/lug/node96.html.\n *\n * @param[out] s_errbd approximate error bound for the elements of s\n *\n * See the documentation of reorder_diagonalize_symmetric(m, s, u) for\n * the other parameters.\n */\ntemplate<class Real, class Scalar, int N>\nvoid reorder_diagonalize_symmetric\n(const Eigen::Matrix<Scalar, N, N>& m,\n Eigen::Array<Real, N, 1>& s,\n Eigen::Matrix<std::complex<Real>, N, N>& u,\n Real& s_errbd)\n{\n    reorder_diagonalize_symmetric_errbd(m, s, &u, &s_errbd);\n}\n\n/**\n * Same as reorder_diagonalize_symmetric(m, s, u, s_errbd) except that\n * approximate error bounds for the singular vectors are returned as\n * well.  The error bounds are estimated following the method\n * presented at http://www.netlib.org/lapack/lug/node96.html.\n *\n * @param[out] u_errbd array of approximate error bounds for u\n *\n * See the documentation of reorder_diagonalize_symmetric(m, s, u,\n * s_errbd) for the other parameters.\n */\ntemplate<class Real, class Scalar, int N>\nvoid reorder_diagonalize_symmetric\n(const Eigen::Matrix<Scalar, N, N>& m,\n Eigen::Array<Real, N, 1>& s,\n Eigen::Matrix<std::complex<Real>, N, N>& u,\n Real& s_errbd,\n Eigen::Array<Real, N, 1>& u_errbd)\n{\n    reorder_diagonalize_symmetric_errbd(m, s, &u, &s_errbd, &u_errbd);\n}\n\n/**\n * Returns singular values of N-by-N symmetric matrix m via s such\n * that `(s >= 0).all()`.  Elements of s are in ascending order.\n *\n * @tparam     Real   type of real and imaginary parts of Scalar\n * @tparam     Scalar type of elements of m\n * @tparam     N      number of rows and columns in m and u\n * @param[in]  m      N-by-N symmetric matrix to be decomposed\n * @param[out] s      array of length N to contain singular values\n */\ntemplate<class Real, class Scalar, int N>\nvoid reorder_diagonalize_symmetric\n(const Eigen::Matrix<Scalar, N, N>& m,\n Eigen::Array<Real, N, 1>& s)\n{\n    reorder_diagonalize_symmetric_errbd(m, s);\n}\n\n/**\n * Same as reorder_diagonalize_symmetric(m, s) except that an\n * approximate error bound for the singular values is returned as\n * well.  The error bound is estimated following the method presented\n * at http://www.netlib.org/lapack/lug/node96.html.\n *\n * @param[out] s_errbd approximate error bound for the elements of s\n *\n * See the documentation of reorder_diagonalize_symmetric(m, s) for\n * the other parameters.\n */\ntemplate<class Real, class Scalar, int N>\nvoid reorder_diagonalize_symmetric\n(const Eigen::Matrix<Scalar, N, N>& m,\n Eigen::Array<Real, N, 1>& s,\n Real& s_errbd)\n{\n    reorder_diagonalize_symmetric_errbd(m, s, 0, &s_errbd);\n}\n\ntemplate<class Real, class Scalar, int M, int N>\nvoid fs_svd_errbd\n(const Eigen::Matrix<Scalar, M, N>& m,\n Eigen::Array<Real, MIN_(M, N), 1>& s,\n Eigen::Matrix<Scalar, M, M> *u = 0,\n Eigen::Matrix<Scalar, N, N> *v = 0,\n Real *s_errbd = 0,\n Eigen::Array<Real, MIN_(M, N), 1> *u_errbd = 0,\n Eigen::Array<Real, MIN_(M, N), 1> *v_errbd = 0)\n{\n    reorder_svd_errbd(m, s, u, v, s_errbd, u_errbd, v_errbd);\n    if (u) u->transposeInPlace();\n}\n\n/**\n * Singular value decomposition of M-by-N matrix m such that\n *\n *     sigma.setZero(); sigma.diagonal() = s;\n *     m == u.transpose() * sigma * v\n *     // convention of Haber and Kane, Phys. Rept. 117 (1985) 75-263\n *\n * and `(s >= 0).all()`.  Elements of s are in ascending order.  The\n * above decomposition can be put in the form\n *\n *     m == u.transpose() * s.matrix().asDiagonal() * v\n *\n * if `M == N`.\n *\n * @tparam     Real   type of real and imaginary parts of Scalar\n * @tparam     Scalar type of elements of m, u, and v\n * @tparam     M      number of rows in m\n * @tparam     N      number of columns in m\n * @param[in]  m      M-by-N matrix to be decomposed\n * @param[out] s      array of length min(M,N) to contain singular values\n * @param[out] u      M-by-M unitary matrix\n * @param[out] v      N-by-N unitary matrix\n */\ntemplate<class Real, class Scalar, int M, int N>\nvoid fs_svd\n(const Eigen::Matrix<Scalar, M, N>& m,\n Eigen::Array<Real, MIN_(M, N), 1>& s,\n Eigen::Matrix<Scalar, M, M>& u,\n Eigen::Matrix<Scalar, N, N>& v)\n{\n    fs_svd_errbd(m, s, &u, &v);\n}\n\n/**\n * Same as fs_svd(m, s, u, v) except that an approximate error bound\n * for the singular values is returned as well.  The error bound is\n * estimated following the method presented at\n * http://www.netlib.org/lapack/lug/node96.html.\n *\n * @param[out] s_errbd approximate error bound for the elements of s\n *\n * See the documentation of fs_svd(m, s, u, v) for the other\n * parameters.\n */\ntemplate<class Real, class Scalar, int M, int N>\nvoid fs_svd\n(const Eigen::Matrix<Scalar, M, N>& m,\n Eigen::Array<Real, MIN_(M, N), 1>& s,\n Eigen::Matrix<Scalar, M, M>& u,\n Eigen::Matrix<Scalar, N, N>& v,\n Real& s_errbd)\n{\n    fs_svd_errbd(m, s, &u, &v, &s_errbd);\n}\n\n/**\n * Same as fs_svd(m, s, u, v, s_errbd) except that approximate error\n * bounds for the singular vectors are returned as well.  The error\n * bounds are estimated following the method presented at\n * http://www.netlib.org/lapack/lug/node96.html.\n *\n * @param[out] u_errbd array of approximate error bounds for u\n * @param[out] v_errbd array of approximate error bounds for vh\n *\n * See the documentation of fs_svd(m, s, u, v, s_errbd) for the other\n * parameters.\n */\ntemplate<class Real, class Scalar, int M, int N>\nvoid fs_svd\n(const Eigen::Matrix<Scalar, M, N>& m,\n Eigen::Array<Real, MIN_(M, N), 1>& s,\n Eigen::Matrix<Scalar, M, M>& u,\n Eigen::Matrix<Scalar, N, N>& v,\n Real& s_errbd,\n Eigen::Array<Real, MIN_(M, N), 1>& u_errbd,\n Eigen::Array<Real, MIN_(M, N), 1>& v_errbd)\n{\n    fs_svd_errbd(m, s, &u, &v, &s_errbd, &u_errbd, &v_errbd);\n}\n\n/**\n * Returns singular values of M-by-N matrix m via s such that\n * `(s >= 0).all()`.  Elements of s are in ascending order.\n *\n * @tparam     Real   type of real and imaginary parts of Scalar\n * @tparam     Scalar type of elements of m, u, and v\n * @tparam     M      number of rows in m\n * @tparam     N      number of columns in m\n * @param[in]  m      M-by-N matrix to be decomposed\n * @param[out] s      array of length min(M,N) to contain singular values\n */\ntemplate<class Real, class Scalar, int M, int N>\nvoid fs_svd\n(const Eigen::Matrix<Scalar, M, N>& m,\n Eigen::Array<Real, MIN_(M, N), 1>& s)\n{\n    fs_svd_errbd(m, s);\n}\n\n/**\n * Same as fs_svd(m, s) except that an approximate error bound for the\n * singular values is returned as well.  The error bound is estimated\n * following the method presented at\n * http://www.netlib.org/lapack/lug/node96.html.\n *\n * @param[out] s_errbd approximate error bound for the elements of s\n *\n * See the documentation of fs_svd(m, s) for the other parameters.\n */\ntemplate<class Real, class Scalar, int M, int N>\nvoid fs_svd\n(const Eigen::Matrix<Scalar, M, N>& m,\n Eigen::Array<Real, MIN_(M, N), 1>& s,\n Real& s_errbd)\n{\n    fs_svd_errbd(m, s, 0, 0, &s_errbd);\n}\n\n/**\n * Singular value decomposition of M-by-N *real* matrix m such that\n *\n *     sigma.setZero(); sigma.diagonal() = s;\n *     m == u.transpose() * sigma * v\n *     // convention of Haber and Kane, Phys. Rept. 117 (1985) 75-263\n *\n * and `(s >= 0).all()`.  Elements of s are in ascending order.  The\n * above decomposition can be put in the form\n *\n *     m == u.transpose() * s.matrix().asDiagonal() * v\n *\n * if `M == N`.\n *\n * @tparam     Real   type of real and imaginary parts\n * @tparam     M      number of rows in m\n * @tparam     N      number of columns in m\n * @param[in]  m      M-by-N *real* matrix to be decomposed\n * @param[out] s      array of length min(M,N) to contain singular values\n * @param[out] u      M-by-M *complex* unitary matrix\n * @param[out] v      N-by-N *complex* unitary matrix\n *\n * @note This is a convenience overload for the case where the type of\n * u and v (complex) differs from that of m (real).  Mathematically,\n * real u and v are enough to accommodate SVD of any real m.\n */\ntemplate<class Real, int M, int N>\nvoid fs_svd\n(const Eigen::Matrix<Real, M, N>& m,\n Eigen::Array<Real, MIN_(M, N), 1>& s,\n Eigen::Matrix<std::complex<Real>, M, M>& u,\n Eigen::Matrix<std::complex<Real>, N, N>& v)\n{\n    fs_svd(m.template cast<std::complex<Real> >().eval(), s, u, v);\n}\n\n/**\n * Same as fs_svd(m, s, u, v) except that an approximate error bound\n * for the singular values is returned as well.  The error bound is\n * estimated following the method presented at\n * http://www.netlib.org/lapack/lug/node96.html.\n *\n * @param[out] s_errbd approximate error bound for the elements of s\n *\n * See the documentation of fs_svd(m, s, u, v) for the other\n * parameters.\n */\ntemplate<class Real, int M, int N>\nvoid fs_svd\n(const Eigen::Matrix<Real, M, N>& m,\n Eigen::Array<Real, MIN_(M, N), 1>& s,\n Eigen::Matrix<std::complex<Real>, M, M>& u,\n Eigen::Matrix<std::complex<Real>, N, N>& v,\n Real& s_errbd)\n{\n    fs_svd(m.template cast<std::complex<Real> >().eval(), s, u, v, s_errbd);\n}\n\n/**\n * Same as fs_svd(m, s, u, v, s_errbd) except that approximate error\n * bounds for the singular vectors are returned as well.  The error\n * bounds are estimated following the method presented at\n * http://www.netlib.org/lapack/lug/node96.html.\n *\n * @param[out] u_errbd array of approximate error bounds for u\n * @param[out] v_errbd array of approximate error bounds for vh\n *\n * See the documentation of fs_svd(m, s, u, v, s_errbd) for the other\n * parameters.\n */\ntemplate<class Real, int M, int N>\nvoid fs_svd\n(const Eigen::Matrix<Real, M, N>& m,\n Eigen::Array<Real, MIN_(M, N), 1>& s,\n Eigen::Matrix<std::complex<Real>, M, M>& u,\n Eigen::Matrix<std::complex<Real>, N, N>& v,\n Real& s_errbd,\n Eigen::Array<Real, MIN_(M, N), 1>& u_errbd,\n Eigen::Array<Real, MIN_(M, N), 1>& v_errbd)\n{\n    fs_svd(m.template cast<std::complex<Real> >().eval(), s, u, v,\n\t   s_errbd, u_errbd, v_errbd);\n}\n\ntemplate<class Real, class Scalar, int N>\nvoid fs_diagonalize_symmetric_errbd\n(const Eigen::Matrix<Scalar, N, N>& m,\n Eigen::Array<Real, N, 1>& s,\n Eigen::Matrix<std::complex<Real>, N, N> *u = 0,\n Real *s_errbd = 0,\n Eigen::Array<Real, N, 1> *u_errbd = 0)\n{\n    reorder_diagonalize_symmetric_errbd(m, s, u, s_errbd, u_errbd);\n    if (u) u->transposeInPlace();\n}\n\n/**\n * Diagonalizes N-by-N symmetric matrix m so that\n *\n *     m == u.transpose() * s.matrix().asDiagonal() * u\n *     // convention of Haber and Kane, Phys. Rept. 117 (1985) 75-263\n *\n * and `(s >= 0).all()`.  Elements of s are in ascending order.\n *\n * @tparam     Real   type of real and imaginary parts of Scalar\n * @tparam     Scalar type of elements of m\n * @tparam     N      number of rows and columns in m and u\n * @param[in]  m      N-by-N symmetric matrix to be decomposed\n * @param[out] s      array of length N to contain singular values\n * @param[out] u      N-by-N complex unitary matrix\n */\ntemplate<class Real, class Scalar, int N>\nvoid fs_diagonalize_symmetric\n(const Eigen::Matrix<Scalar, N, N>& m,\n Eigen::Array<Real, N, 1>& s,\n Eigen::Matrix<std::complex<Real>, N, N>& u)\n{\n    fs_diagonalize_symmetric_errbd(m, s, &u);\n}\n\n/**\n * Same as fs_diagonalize_symmetric(m, s, u) except that an\n * approximate error bound for the singular values is returned as\n * well.  The error bound is estimated following the method presented\n * at http://www.netlib.org/lapack/lug/node96.html.\n *\n * @param[out] s_errbd approximate error bound for the elements of s\n *\n * See the documentation of fs_diagonalize_symmetric(m, s, u) for the\n * other parameters.\n */\ntemplate<class Real, class Scalar, int N>\nvoid fs_diagonalize_symmetric\n(const Eigen::Matrix<Scalar, N, N>& m,\n Eigen::Array<Real, N, 1>& s,\n Eigen::Matrix<std::complex<Real>, N, N>& u,\n Real& s_errbd)\n{\n    fs_diagonalize_symmetric_errbd(m, s, &u, &s_errbd);\n}\n\n/**\n * Same as fs_diagonalize_symmetric(m, s, u, s_errbd) except that\n * approximate error bounds for the singular vectors are returned as\n * well.  The error bounds are estimated following the method\n * presented at http://www.netlib.org/lapack/lug/node96.html.\n *\n * @param[out] u_errbd array of approximate error bounds for u\n *\n * See the documentation of fs_diagonalize_symmetric(m, s, u, s_errbd)\n * for the other parameters.\n */\ntemplate<class Real, class Scalar, int N>\nvoid fs_diagonalize_symmetric\n(const Eigen::Matrix<Scalar, N, N>& m,\n Eigen::Array<Real, N, 1>& s,\n Eigen::Matrix<std::complex<Real>, N, N>& u,\n Real& s_errbd,\n Eigen::Array<Real, N, 1>& u_errbd)\n{\n    fs_diagonalize_symmetric_errbd(m, s, &u, &s_errbd, &u_errbd);\n}\n\n/**\n * Returns singular values of N-by-N symmetric matrix m via s such\n * that `(s >= 0).all()`.  Elements of s are in ascending order.\n *\n * @tparam     Real   type of real and imaginary parts of Scalar\n * @tparam     Scalar type of elements of m\n * @tparam     N      number of rows and columns in m and u\n * @param[in]  m      N-by-N symmetric matrix to be decomposed\n * @param[out] s      array of length N to contain singular values\n */\ntemplate<class Real, class Scalar, int N>\nvoid fs_diagonalize_symmetric\n(const Eigen::Matrix<Scalar, N, N>& m,\n Eigen::Array<Real, N, 1>& s)\n{\n    fs_diagonalize_symmetric_errbd(m, s);\n}\n\n/**\n * Same as fs_diagonalize_symmetric(m, s) except that an approximate\n * error bound for the singular values is returned as well.  The error\n * bound is estimated following the method presented at\n * http://www.netlib.org/lapack/lug/node96.html.\n *\n * @param[out] s_errbd approximate error bound for the elements of s\n *\n * See the documentation of fs_diagonalize_symmetric(m, s) for the\n * other parameters.\n */\ntemplate<class Real, class Scalar, int N>\nvoid fs_diagonalize_symmetric\n(const Eigen::Matrix<Scalar, N, N>& m,\n Eigen::Array<Real, N, 1>& s,\n Real& s_errbd)\n{\n    fs_diagonalize_symmetric_errbd(m, s, 0, &s_errbd);\n}\n\ntemplate<class Real, class Scalar, int N>\nvoid fs_diagonalize_hermitian_errbd\n(const Eigen::Matrix<Scalar, N, N>& m,\n Eigen::Array<Real, N, 1>& w,\n Eigen::Matrix<Scalar, N, N> *z = 0,\n Real *w_errbd = 0,\n Eigen::Array<Real, N, 1> *z_errbd = 0)\n{\n    diagonalize_hermitian_errbd(m, w, z, w_errbd, z_errbd);\n    Eigen::PermutationMatrix<N> p;\n    p.setIdentity();\n    std::sort(p.indices().data(), p.indices().data() + p.indices().size(),\n              [&w] (int i, int j) { return std::abs(w[i]) < std::abs(w[j]); });\n#if EIGEN_VERSION_AT_LEAST(3,1,4)\n    w.matrix().transpose() *= p;\n    if (z_errbd) z_errbd->matrix().transpose() *= p;\n#else\n    Eigen::Map<Eigen::Matrix<Real, N, 1> >(w.data()).transpose() *= p;\n    if (z_errbd)\n\tEigen::Map<Eigen::Matrix<Real, N, 1> >(z_errbd->data()).transpose()\n\t    *= p;\n#endif\n    if (z) *z = (*z * p).adjoint().eval();\n}\n\n/**\n * Diagonalizes N-by-N hermitian matrix m so that\n *\n *     m == z.adjoint() * w.matrix().asDiagonal() * z    // convention of SARAH\n *\n * w is arranged so that `abs(w[i])` are in ascending order.\n *\n * @tparam     Real   type of real and imaginary parts of Scalar\n * @tparam     Scalar type of elements of m and z\n * @tparam     N      number of rows and columns in m and z\n * @param[in]  m      N-by-N matrix to be diagonalized\n * @param[out] w      array of length N to contain eigenvalues\n * @param[out] z      N-by-N unitary matrix\n */\ntemplate<class Real, class Scalar, int N>\nvoid fs_diagonalize_hermitian\n(const Eigen::Matrix<Scalar, N, N>& m,\n Eigen::Array<Real, N, 1>& w,\n Eigen::Matrix<Scalar, N, N>& z)\n{\n    fs_diagonalize_hermitian_errbd(m, w, &z);\n}\n\n/**\n * Same as fs_diagonalize_hermitian(m, w, z) except that an\n * approximate error bound for the eigenvalues is returned as well.\n * The error bound is estimated following the method presented at\n * http://www.netlib.org/lapack/lug/node89.html.\n *\n * @param[out] w_errbd approximate error bound for the elements of w\n *\n * See the documentation of fs_diagonalize_hermitian(m, w, z) for the\n * other parameters.\n */\ntemplate<class Real, class Scalar, int N>\nvoid fs_diagonalize_hermitian\n(const Eigen::Matrix<Scalar, N, N>& m,\n Eigen::Array<Real, N, 1>& w,\n Eigen::Matrix<Scalar, N, N>& z,\n Real& w_errbd)\n{\n    fs_diagonalize_hermitian_errbd(m, w, &z, &w_errbd);\n}\n\n/**\n * Same as fs_diagonalize_hermitian(m, w, z, w_errbd) except that\n * approximate error bounds for the eigenvectors are returned as well.\n * The error bounds are estimated following the method presented at\n * http://www.netlib.org/lapack/lug/node89.html.\n *\n * @param[out] z_errbd array of approximate error bounds for z\n *\n * See the documentation of fs_diagonalize_hermitian(m, w, z, w_errbd)\n * for the other parameters.\n */\ntemplate<class Real, class Scalar, int N>\nvoid fs_diagonalize_hermitian\n(const Eigen::Matrix<Scalar, N, N>& m,\n Eigen::Array<Real, N, 1>& w,\n Eigen::Matrix<Scalar, N, N>& z,\n Real& w_errbd,\n Eigen::Array<Real, N, 1>& z_errbd)\n{\n    fs_diagonalize_hermitian_errbd(m, w, &z, &w_errbd, &z_errbd);\n}\n\n/**\n * Returns eigenvalues of N-by-N hermitian matrix m via w.\n * w is arranged so that `abs(w[i])` are in ascending order.\n *\n * @tparam     Real   type of real and imaginary parts of Scalar\n * @tparam     Scalar type of elements of m and z\n * @tparam     N      number of rows and columns in m and z\n * @param[in]  m      N-by-N matrix to be diagonalized\n * @param[out] w      array of length N to contain eigenvalues\n */\ntemplate<class Real, class Scalar, int N>\nvoid fs_diagonalize_hermitian\n(const Eigen::Matrix<Scalar, N, N>& m,\n Eigen::Array<Real, N, 1>& w)\n{\n    fs_diagonalize_hermitian_errbd(m, w);\n}\n\n/**\n * Same as fs_diagonalize_hermitian(m, w) except that an approximate\n * error bound for the eigenvalues is returned as well.  The error\n * bound is estimated following the method presented at\n * http://www.netlib.org/lapack/lug/node89.html.\n *\n * @param[out] w_errbd approximate error bound for the elements of w\n *\n * See the documentation of fs_diagonalize_hermitian(m, w) for the\n * other parameters.\n */\ntemplate<class Real, class Scalar, int N>\nvoid fs_diagonalize_hermitian\n(const Eigen::Matrix<Scalar, N, N>& m,\n Eigen::Array<Real, N, 1>& w,\n Real& w_errbd)\n{\n    fs_diagonalize_hermitian_errbd(m, w, 0, &w_errbd);\n}\n\n} // namespace flexiblesusy\n\n#endif // linalg2_hpp\n", "meta": {"hexsha": "741344fe180fa6bc9c24325061b7644ad0b14775", "size": 51652, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/MassSpectra/flexiblesusy/src/linalg2.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/linalg2.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/linalg2.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": 31.7858461538, "max_line_length": 79, "alphanum_fraction": 0.6473515062, "num_tokens": 15772, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.629774621301746, "lm_q1q2_score": 0.45650490367215185}}
{"text": "#include <iostream>\n#include <cmath>\n#include <algorithm>\n#include <vector>\n#include <boost/multiprecision/cpp_int.hpp>\nusing namespace boost::multiprecision;\nusing namespace std;\nint main() {\n    int n; cin >> n;\n    vector<long long int> v(n, 0);\n    cpp_int c = 0;\n    for (int i = 0; i < n; i++) {\n        long long int a, b; cin >> a >> b;\n        c -= a, v[i] = 2 * a + b;\n    }\n    sort(v.begin(), v.end());\n    reverse(v.begin(), v.end());\n    int ans = 0;\n    for (int i = 0; i < n; i++) {\n        c += v[i];\n        ans++;\n        if (c > 0) break;\n    }\n    cout << ans << endl;\n}\n", "meta": {"hexsha": "3a2a350b1cae82a5e041e7702a6cf726efecb4e3", "size": 592, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AtCoder/abc187/d/main.cpp", "max_stars_repo_name": "H-Tatsuhiro/Com_Pro-Cpp", "max_stars_repo_head_hexsha": "fd79f7821a76b11f4a6f83bbb26a034db577a877", "max_stars_repo_licenses": ["MIT"], "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/abc187/d/main.cpp", "max_issues_repo_name": "H-Tatsuhiro/Com_Pro-Cpp", "max_issues_repo_head_hexsha": "fd79f7821a76b11f4a6f83bbb26a034db577a877", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-10-19T08:47:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T05:23:56.000Z", "max_forks_repo_path": "AtCoder/abc187/d/main.cpp", "max_forks_repo_name": "H-Tatsuhiro/Com_Pro-Cpp", "max_forks_repo_head_hexsha": "fd79f7821a76b11f4a6f83bbb26a034db577a877", "max_forks_repo_licenses": ["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.7692307692, "max_line_length": 43, "alphanum_fraction": 0.5016891892, "num_tokens": 185, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768249, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.45650490367215185}}
{"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   testSubgraphSolver.cpp\n *  @brief  Unit tests for SubgraphSolver\n *  @author Yong-Dian Jian\n **/\n\n#include <gtsam/linear/SubgraphSolver.h>\n\n#include <tests/smallExample.h>\n#include <gtsam/linear/GaussianBayesNet.h>\n#include <gtsam/linear/iterative.h>\n#include <gtsam/linear/GaussianFactorGraph.h>\n#include <gtsam/linear/SubgraphBuilder.h>\n#include <gtsam/inference/Symbol.h>\n#include <gtsam/inference/Ordering.h>\n#include <gtsam/base/numericalDerivative.h>\n\n#include <CppUnitLite/TestHarness.h>\n\n#include <boost/assign/std/list.hpp>\nusing namespace boost::assign;\n\nusing namespace std;\nusing namespace gtsam;\n\nstatic size_t N = 3;\nstatic SubgraphSolverParameters kParameters;\nstatic auto kOrdering = example::planarOrdering(N);\n\n/* ************************************************************************* */\n/** unnormalized error */\nstatic double error(const GaussianFactorGraph& fg, const VectorValues& x) {\n  double total_error = 0.;\n  for(const GaussianFactor::shared_ptr& factor: fg)\n    total_error += factor->error(x);\n  return total_error;\n}\n\n/* ************************************************************************* */\nTEST( SubgraphSolver, Parameters )\n{\n  LONGS_EQUAL(SubgraphSolverParameters::SILENT, kParameters.verbosity());\n  LONGS_EQUAL(500, kParameters.maxIterations());\n}\n\n/* ************************************************************************* */\nTEST( SubgraphSolver, splitFactorGraph )\n{\n  // Build a planar graph\n  GaussianFactorGraph Ab;\n  VectorValues xtrue;\n  std::tie(Ab, xtrue) = example::planarGraph(N); // A*x-b\n\n  SubgraphBuilderParameters params;\n  params.augmentationFactor = 0.0;\n  SubgraphBuilder builder(params);\n  auto subgraph = builder(Ab);\n  EXPECT_LONGS_EQUAL(9, subgraph.size());\n\n  GaussianFactorGraph Ab1, Ab2;\n  std::tie(Ab1, Ab2) = splitFactorGraph(Ab, subgraph);\n  EXPECT_LONGS_EQUAL(9, Ab1.size());\n  EXPECT_LONGS_EQUAL(13, Ab2.size());\n}\n\n/* ************************************************************************* */\nTEST( SubgraphSolver, constructor1 )\n{\n  // Build a planar graph\n  GaussianFactorGraph Ab;\n  VectorValues xtrue;\n  std::tie(Ab, xtrue) = example::planarGraph(N); // A*x-b\n\n  // The first constructor just takes a factor graph (and kParameters)\n  // and it will split the graph into A1 and A2, where A1 is a spanning tree\n  SubgraphSolver solver(Ab, kParameters, kOrdering);\n  VectorValues optimized = solver.optimize(); // does PCG optimization\n  DOUBLES_EQUAL(0.0, error(Ab, optimized), 1e-5);\n}\n\n/* ************************************************************************* */\nTEST( SubgraphSolver, constructor2 )\n{\n  // Build a planar graph\n  GaussianFactorGraph Ab;\n  VectorValues xtrue;\n  size_t N = 3;\n  std::tie(Ab, xtrue) = example::planarGraph(N); // A*x-b\n\n  // Get the spanning tree\n  GaussianFactorGraph Ab1, Ab2; // A1*x-b1 and A2*x-b2\n  std::tie(Ab1, Ab2) = example::splitOffPlanarTree(N, Ab);\n\n  // The second constructor takes two factor graphs, so the caller can specify\n  // the preconditioner (Ab1) and the constraints that are left out (Ab2)\n  SubgraphSolver solver(Ab1, Ab2, kParameters, kOrdering);\n  VectorValues optimized = solver.optimize();\n  DOUBLES_EQUAL(0.0, error(Ab, optimized), 1e-5);\n}\n\n/* ************************************************************************* */\nTEST( SubgraphSolver, constructor3 )\n{\n  // Build a planar graph\n  GaussianFactorGraph Ab;\n  VectorValues xtrue;\n  size_t N = 3;\n  std::tie(Ab, xtrue) = example::planarGraph(N); // A*x-b\n\n  // Get the spanning tree and corresponding kOrdering\n  GaussianFactorGraph Ab1, Ab2; // A1*x-b1 and A2*x-b2\n  std::tie(Ab1, Ab2) = example::splitOffPlanarTree(N, Ab);\n\n  // The caller solves |A1*x-b1|^2 == |R1*x-c1|^2, where R1 is square UT\n  auto Rc1 = *Ab1.eliminateSequential();\n\n  // The third constructor allows the caller to pass an already solved preconditioner Rc1_\n  // as a Bayes net, in addition to the \"loop closing constraints\" Ab2, as before\n  SubgraphSolver solver(Rc1, Ab2, kParameters);\n  VectorValues optimized = solver.optimize();\n  DOUBLES_EQUAL(0.0, error(Ab, optimized), 1e-5);\n}\n\n/* ************************************************************************* */\nint main() { TestResult tr; return TestRegistry::runAllTests(tr); }\n/* ************************************************************************* */\n", "meta": {"hexsha": "5d8d88775b26062dcb42dbe8a751b3125315af71", "size": 4706, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/testSubgraphSolver.cpp", "max_stars_repo_name": "h-rover/gtsam", "max_stars_repo_head_hexsha": "a0206e210d8f47b6ee295a1fbf95af84d98c5cf0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-04T07:01:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T07:01:48.000Z", "max_issues_repo_path": "tests/testSubgraphSolver.cpp", "max_issues_repo_name": "h-rover/gtsam", "max_issues_repo_head_hexsha": "a0206e210d8f47b6ee295a1fbf95af84d98c5cf0", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/testSubgraphSolver.cpp", "max_forks_repo_name": "h-rover/gtsam", "max_forks_repo_head_hexsha": "a0206e210d8f47b6ee295a1fbf95af84d98c5cf0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-21T06:58:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T06:58:34.000Z", "avg_line_length": 34.1014492754, "max_line_length": 90, "alphanum_fraction": 0.6064598385, "num_tokens": 1167, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.72487026428967, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.45650489618592344}}
{"text": "/*********************************************************************\n * Software License Agreement (BSD License)\n *\n *  Copyright (c) 2019, University of Stuttgart\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions\n *  are met:\n *\n *   * Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *   * Redistributions in binary form must reproduce the above\n *     copyright notice, this list of conditions and the following\n *     disclaimer in the documentation and/or other materials provided\n *     with the distribution.\n *   * Neither the name of the University of Stuttgart nor the names\n *     of its contributors may be used to endorse or promote products\n *     derived from this software without specific prior written\n *     permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n *  \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n *  POSSIBILITY OF SUCH DAMAGE.\n *********************************************************************/\n\n/* Author: Andreas Orthey */\n\n#include \"QuotientSpacePlanningCommon.h\"\n#include <ompl/base/spaces/RealVectorStateSpace.h>\n\n#include <ompl/geometric/planners/quotientspace/QRRT.h>\n\n#include <ompl/tools/benchmark/Benchmark.h>\n#include <ompl/util/String.h>\n\n#include <boost/math/constants/constants.hpp>\n#include <boost/format.hpp>\n#include <fstream>\n\nconst double edgeWidth = 0.1;\nconst unsigned int ndim = 10;\nconst double runtime_limit = 10;\nconst double memory_limit = 4096;\nconst int run_count = 10;\n\n// Only states near some edges of a hypercube are valid. The valid edges form a\n// narrow passage from (0,...,0) to (1,...,1). A state s is valid if there exists\n// a k s.t. (a) 0<=s[k]<=1, (b) for all i<k s[i]<=edgeWidth, and (c) for all i>k\n// s[i]>=1-edgewidth.\nclass HyperCubeValidityChecker : public ompl::base::StateValidityChecker\n{\npublic:\n    HyperCubeValidityChecker(const ompl::base::SpaceInformationPtr &si, int nDim)\n      : ompl::base::StateValidityChecker(si), nDim_(nDim)\n    {\n    }\n\n    bool isValid(const ompl::base::State *state) const override\n    {\n        const auto *s = static_cast<const ompl::base::RealVectorStateSpace::StateType *>(state);\n        bool foundMaxDim = false;\n\n        for (int i = nDim_ - 1; i >= 0; i--)\n            if (!foundMaxDim)\n            {\n                if ((*s)[i] > edgeWidth)\n                    foundMaxDim = true;\n            }\n            else if ((*s)[i] < (1. - edgeWidth))\n                return false;\n        return true;\n    }\n\nprotected:\n    int nDim_;\n};\n\nvoid addPlanner(ompl::tools::Benchmark &benchmark, const ompl::base::PlannerPtr &planner, double range)\n{\n    ompl::base::ParamSet &params = planner->params();\n    if (params.hasParam(std::string(\"range\")))\n        params.setParam(std::string(\"range\"), ompl::toString(range));\n    benchmark.addPlanner(planner);\n}\n\nob::PlannerPtr GetQRRT(ob::SpaceInformationPtr si, ob::ProblemDefinitionPtr pdef, unsigned int numLinks)\n{\n    // ompl::msg::setLogLevel(ompl::msg::LOG_DEV2);\n    std::vector<ob::SpaceInformationPtr> si_vec;\n\n    for (unsigned int k = 2; k < numLinks; k += 2)\n    {\n        OMPL_INFORM(\"Create QuotientSpace Chain with %d links.\", k);\n\n        auto spaceK(std::make_shared<ompl::base::RealVectorStateSpace>(k));\n        ompl::base::RealVectorBounds bounds(k);\n        bounds.setLow(0.);\n        bounds.setHigh(1.);\n        spaceK->setBounds(bounds);\n\n        auto siK = std::make_shared<ob::SpaceInformation>(spaceK);\n        siK->setStateValidityChecker(std::make_shared<HyperCubeValidityChecker>(siK, k));\n        siK->setStateValidityCheckingResolution(0.001);\n\n        spaceK->setup();\n        si_vec.push_back(siK);\n    }\n    OMPL_INFORM(\"Add Original Chain with %d links.\", numLinks);\n    si_vec.push_back(si);\n\n    auto planner = std::make_shared<og::QRRT>(si_vec);\n    planner->setProblemDefinition(pdef);\n    std::string qName = \"QuotientSpaceRRT[\" + std::to_string(si_vec.size()) + \"lvl]\";\n    planner->setName(qName);\n    return planner;\n}\n\nint main()\n{\n    double range = edgeWidth * 0.5;\n    auto space(std::make_shared<ompl::base::RealVectorStateSpace>(ndim));\n    ompl::base::RealVectorBounds bounds(ndim);\n    ompl::geometric::SimpleSetup ss(space);\n    ompl::base::ScopedState<> start(space), goal(space);\n\n    bounds.setLow(0.);\n    bounds.setHigh(1.);\n    space->setBounds(bounds);\n    ss.setStateValidityChecker(std::make_shared<HyperCubeValidityChecker>(ss.getSpaceInformation(), ndim));\n    ss.getSpaceInformation()->setStateValidityCheckingResolution(0.001);\n    for (unsigned int i = 0; i < ndim; ++i)\n    {\n        start[i] = 0.;\n        goal[i] = 1.;\n    }\n    ss.setStartAndGoalStates(start, goal);\n\n    ompl::tools::Benchmark::Request request(runtime_limit, memory_limit, run_count);\n    ompl::tools::Benchmark b(ss, \"HyperCube\");\n    b.addExperimentParameter(\"num_dims\", \"INTEGER\", std::to_string(ndim));\n\n    ob::SpaceInformationPtr si = ss.getSpaceInformation();\n\n    ob::PlannerPtr quotientSpacePlanner = GetQRRT(ss.getSpaceInformation(), ss.getProblemDefinition(), ndim);\n    addPlanner(b, quotientSpacePlanner, range);\n\n    b.benchmark(request);\n    b.saveResultsToFile(boost::str(boost::format(\"hypercube_%i.log\") % ndim).c_str());\n\n    printBenchmarkResults(b);\n\n    return 0;\n}\n", "meta": {"hexsha": "2c37bf19cc4700893780181172d2b3c2d31293a3", "size": 6081, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "demos/quotientspace/QuotientSpacePlanningHyperCube.cpp", "max_stars_repo_name": "ericpairet/ompl", "max_stars_repo_head_hexsha": "25c76431cef25f0100ed74d09dd88944ecca5ee1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 837.0, "max_stars_repo_stars_event_min_datetime": "2015-01-07T12:01:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:42:42.000Z", "max_issues_repo_path": "demos/quotientspace/QuotientSpacePlanningHyperCube.cpp", "max_issues_repo_name": "ericpairet/ompl", "max_issues_repo_head_hexsha": "25c76431cef25f0100ed74d09dd88944ecca5ee1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 271.0, "max_issues_repo_issues_event_min_datetime": "2015-01-12T22:05:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T22:16:01.000Z", "max_forks_repo_path": "demos/quotientspace/QuotientSpacePlanningHyperCube.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.0792682927, "max_line_length": 109, "alphanum_fraction": 0.6707778326, "num_tokens": 1506, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.6297746004557471, "lm_q1q2_score": 0.45650488856150684}}
{"text": "/*\n   Copyright 2018 Simon Vogl <svogl@voxel.at>\n                  Angel Merino-Sastre <amerino@voxel.at>\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/log/core.hpp>\n#include <boost/log/trivial.hpp>\n\n#if OCV_VERSION_MAJOR >= 3\n#  include <opencv2/imgproc.hpp>\n#  include <opencv2/highgui.hpp>\n#else\n#  include <opencv2/imgproc/imgproc.hpp>\n#  include <opencv2/highgui/highgui.hpp>\n#endif\n\n#include \"toffy/smoothing/kalmanaverage.hpp\"\n\n#include <iostream>\n#include <fstream>\n\n#include <math.h>\n\n\nusing namespace std;\nusing namespace cv;\nusing namespace toffy::filters::smoothing;\n\nstd::size_t toffy::filters::smoothing::KalmanAverage::_filter_counter = 1;\nconst std::string toffy::filters::smoothing::KalmanAverage::id_name = \"kalmanAverage\";\n\nKalmanAverage::KalmanAverage():\n    Filter(KalmanAverage::id_name), _in_img(\"depth\"), out_img(\"depth\"),\n    processNoiseCov(1e-5),\n    measurementNoiseCov(1e-1),\n    skipZeros(true)\n{\n}\n\nKalmanAverage::~KalmanAverage() {}\n\n/*\nint KalmanAverage::loadConfig(const boost::property_tree::ptree& pt) {\n    BOOST_LOG_TRIVIAL(debug) << __FUNCTION__ << \"(const boost::property_tree::ptree& pt)\";\n    const boost::property_tree::ptree& tree = pt.get_child(this->type());\n\n    loadGlobals(tree);\n\n    updateConfig(tree);\n\n    return true;\n}\n*/\n\nvoid KalmanAverage::updateConfig(const boost::property_tree::ptree &pt) {\n    BOOST_LOG_TRIVIAL(debug) << __FUNCTION__ <<  \" \" << id();\n\n    using namespace boost::property_tree;\n\n    Filter::updateConfig(pt);\n\n    _in_img = pt.get<string>(\"inputs.img\",_in_img);\n    out_img = pt.get<string>(\"outputs.img\",out_img);\n\n     processNoiseCov = pt.get<float>(\"options.processNoiseCov\", processNoiseCov);\n     measurementNoiseCov = pt.get<float>(\"options.measurementNoiseCov\", measurementNoiseCov);\n     skipZeros = pt.get<bool>(\"options.skipZeros\", skipZeros);\n}\n\nboost::property_tree::ptree KalmanAverage::getConfig() const {\n    boost::property_tree::ptree pt;\n\n    pt = Filter::getConfig();\n\n    pt.put(\"inputs.img\", _in_img);\n    pt.put(\"outputs.img\", out_img);\n\n    pt.put(\"options.processNoiseCov\", processNoiseCov);\n    pt.put(\"options.measurementNoiseCov\", measurementNoiseCov);\n    pt.put(\"options.skipZeros\", skipZeros);\n\n    return pt;\n}\n\nbool KalmanAverage::filter(const toffy::Frame& in, toffy::Frame& out)\n{\n    BOOST_LOG_TRIVIAL(debug) << __FUNCTION__ <<  \" \" << id();\n    boost::shared_ptr<cv::Mat> img;\n\n    try {\n\timg = boost::any_cast<boost::shared_ptr<cv::Mat> >(in.getData(_in_img));\n    } catch(const boost::bad_any_cast &) {\n\tBOOST_LOG_TRIVIAL(warning) <<\n\t    \"Could not cast input \" << _in_img <<\n\t    \", filter  \" << id() <<\" not applied.\";\n\treturn false;\n    }\n    float* imgptr;\n    int vKFpos = 0;\n    if (!vKF) {\n\tvKF.reset(new std::vector<cv::KalmanFilter >(img->size().area()));\n\tfor(int row = 0; row < img->rows; ++row) {\n\t    imgptr = img->ptr<float>(row);\n\n\t    for(int col = 0; col < img->cols; ++col) {\n\t\tcv::KalmanFilter& kf = vKF->at(vKFpos);\n\t\t//vKFpos = ( ( (row+1)+((img->rows)*row) ) * (col+1) ) -1;\n\t\tkf.init(2,1,0);\n\t\tkf.transitionMatrix = (Mat_<float>(2, 2) << 1, 1, 0, 1);\n\n\t\tsetIdentity(kf.measurementMatrix);\n\t\tsetIdentity(kf.processNoiseCov, Scalar::all(1e-5));\n\t\tsetIdentity(kf.measurementNoiseCov, Scalar::all(1e-1));\n\t\tsetIdentity(kf.errorCovPost, Scalar::all(1));\n\n\t\tkf.statePost.at<float>(0) = imgptr[col];\n\t\tvKFpos++;\n\t\t//cout << \"vKFpos: \" << vKFpos << endl;\n\t\t//cout << \"imgptr[col]: \" << imgptr[col] << endl;\n\t\t//cout << \"kf.statePost.at<float>(0): \" << kf.statePost.at<float>(0) << endl;\n\t    }\n\t}\n    } else {\n\tMat measurement = Mat::zeros(1, 1, CV_32F);\n\tMat estimated;\n\tfor(int row = 0; row < img->rows; ++row) {\n\t    imgptr = img->ptr<float>(row);\n\n\t    for(int col = 0; col < img->cols; ++col) {\n\t\tcv::KalmanFilter& kf = vKF->at(vKFpos);\n\n\t\tif (std::numeric_limits<float>::quiet_NaN() == imgptr[col]\n\t\t    || ( skipZeros && imgptr[col] <= 0.0 ) ) {\n\t\t    imgptr[col] = imgptr[col]; // nothing to estimate..\n\t\t    vKFpos++;\n\n\t\t    //kf.statePost.at<float>(0) =imgptr[col] ;\n\t\t    continue;\n\t\t}\n\t\t// last state was nan..:\n\t\tif (  std::numeric_limits<float>::quiet_NaN() == kf.statePost.at<float>(0) ) {\n\t\t    // re-init state\n\t\t    setIdentity(kf.measurementMatrix);\n\t\t    setIdentity(kf.processNoiseCov, Scalar::all(1e-5));\n\t\t    setIdentity(kf.measurementNoiseCov, Scalar::all(1e-1));\n\t\t    setIdentity(kf.errorCovPost, Scalar::all(1));\n\t\t    \n\t\t    kf.statePost.at<float>(0) = imgptr[col];\n\t\t}\n\n\t\t//vKFpos = ( ( (row+1)+((img->rows)*row) ) * (col+1) ) -1;\n\t\tkf.predict();\n\n\t\t//measurement = Mat::zeros(3, 1, CV_32F);\n\t\tmeasurement.at<float>(0) = imgptr[col];\n\n\t\testimated = kf.correct(measurement);\n\t\timgptr[col] = estimated.at<float>(0);\n\t\tvKFpos++;\n\t    }\n\t}\n    }\n\n\n    return true;\n}\n\n", "meta": {"hexsha": "60d6bc67f85676a37d91b5922f127aa7e554cb04", "size": 5253, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/filters/src/smoothing/kalmanaverage.cpp", "max_stars_repo_name": "voxel-dot-at/toffy", "max_stars_repo_head_hexsha": "e9f14b186cf57225ad9eae99f227f894f0e5f940", "max_stars_repo_licenses": ["Apache-2.0"], "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/filters/src/smoothing/kalmanaverage.cpp", "max_issues_repo_name": "voxel-dot-at/toffy", "max_issues_repo_head_hexsha": "e9f14b186cf57225ad9eae99f227f894f0e5f940", "max_issues_repo_licenses": ["Apache-2.0"], "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/filters/src/smoothing/kalmanaverage.cpp", "max_forks_repo_name": "voxel-dot-at/toffy", "max_forks_repo_head_hexsha": "e9f14b186cf57225ad9eae99f227f894f0e5f940", "max_forks_repo_licenses": ["Apache-2.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.3463687151, "max_line_length": 93, "alphanum_fraction": 0.6542927851, "num_tokens": 1558, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702642896702, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.4565048861121604}}
{"text": "// This file is part of libigl, a simple c++ geometry processing library.\n//\n// Copyright (C) 2014 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 \"local_basis.h\"\n\n#include <sstream>\n#include <string>\n#include <fstream>\n\n#include <vector>\n#include <Eigen/Geometry>\n\n\ntemplate <typename DerivedV, typename DerivedF>\nIGL_INLINE void igl::local_basis(\n  const Eigen::PlainObjectBase<DerivedV>& V,\n  const Eigen::PlainObjectBase<DerivedF>& F,\n  Eigen::PlainObjectBase<DerivedV>& B1,\n  Eigen::PlainObjectBase<DerivedV>& B2,\n  Eigen::PlainObjectBase<DerivedV>& B3\n  )\n{\n  using namespace Eigen;\n  using namespace std;\n  B1.resize(F.rows(),3);\n  B2.resize(F.rows(),3);\n  B3.resize(F.rows(),3);\n\n  for (unsigned i=0;i<F.rows();++i)\n  {\n      Eigen::Matrix<typename DerivedV::Scalar, 1, 3> v1 = (V.row(F(i,1)) - V.row(F(i,0))).normalized();\n      Eigen::Matrix<typename DerivedV::Scalar, 1, 3> t = V.row(F(i,2)) - V.row(F(i,0));\n      Eigen::Matrix<typename DerivedV::Scalar, 1, 3> v3 = v1.cross(t).normalized();\n      Eigen::Matrix<typename DerivedV::Scalar, 1, 3> v2 = v1.cross(v3).normalized();\n\n      B1.row(i) = v1;\n      B2.row(i) = -v2;\n      B3.row(i) = v3;\n  }\n}\n\n#ifdef IGL_STATIC_LIBRARY\n// Explicit template specialization\n// generated by autoexplicit.sh\ntemplate void igl::local_basis<Eigen::Matrix<double, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> >&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> >&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> >&);\ntemplate void igl::local_basis<Eigen::Matrix<double, -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<double, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&);\n#endif\n", "meta": {"hexsha": "a1fd0db16e2552dd0870842f6aa29736fe809346", "size": 2381, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Code/include/igl/local_basis.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/local_basis.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/local_basis.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": 45.7884615385, "max_line_length": 462, "alphanum_fraction": 0.6551868963, "num_tokens": 820, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.5813030906443134, "lm_q1q2_score": 0.45650230517955354}}
{"text": "//****************************************************************************\n// (c) 2008, 2009 by the openOR Team\n//****************************************************************************\n// The contents of this file are available under the GPL v2.0 license\n// or under the openOR comercial license. see\n//   /Doc/openOR_free_license.txt or\n//   /Doc/openOR_comercial_license.txt\n// for Details.\n//****************************************************************************\n//! OPENOR_INTERFACE_FILE(Image_ImageData)\n//****************************************************************************\n/**\n * @file\n * @author Christian Winne\n * \\ingroup Image_ImageData\n */\n\n#ifndef openOR_Image_Image3DSize_hpp\n#define openOR_Image_Image3DSize_hpp\n\n#include <boost/tr1/memory.hpp>\n\n#include <openOR/Plugin/CreateInterface.hpp>\n#include <openOR/Math/vector.hpp>\n#include <openOR/Math/matrix.hpp>\n#include <openOR/Math/vectorfunctions.hpp>\n#include <openOR/Utility/Types.hpp>\n\nnamespace openOR {\n   namespace Image {\n     /**\n      * Interface that describes a size of a cubic voxel based volume.\n      * The volume is described by its voxel count, its size in millimeter.\n      * \\ingroup Image_ImageData\n      */\n     struct Image3DSize {\n\n         /**\n          * Getter for the volume size as a Size3D object in mm\n          * @return The volume size in mm\n          */\n         virtual Math::Vector3d sizeMM() const = 0;  \n\n         //! \\brief\tSetter for the volume-size as a Size3UI object in indices\n         //! \\param[in] sizeMM The volume size in indices\n         virtual void setSizeMM(const Math::Vector3d& sizeMM) = 0;\n\n         /**\n          * Getter for the volume-size as a Size3UI object in indices\n          * @return The volume size in indices\n          */\n         virtual Math::Vector3ui size() const = 0;\n\n         /** \n          * Setter for the volume-size as a Size3UI object in indices\n          * @param size The volume size in indices\n          */\n         virtual void setSize(const Math::Vector3ui& size) = 0;\n\n     };    \n   }  \n  \n  /*\n   * Getter for the voxel width in mm\n   * @return The voxel width in mm\n   */\n   inline const double voxelWidthMM(std::tr1::shared_ptr<const Image::Image3DSize> pVolumeSize) { return pVolumeSize->sizeMM()(0) / pVolumeSize->size()(0); }\n\n  /**\n  * Getter for the voxel height in mm\n  * @return The voxel height in mm\n  */\n  inline const double voxelHeightMM(std::tr1::shared_ptr<const Image::Image3DSize> pVolumeSize) { return pVolumeSize->sizeMM()(1) / pVolumeSize->size()(1); }    \n\n  /**\n  * Getter for the voxel depth in mm\n  * @return The voxel depth in mm\n  */\n  inline const double voxelDepthMM(std::tr1::shared_ptr<const Image::Image3DSize> pVolumeSize) { return pVolumeSize->sizeMM()(2) / pVolumeSize->size()(2); }    \n  \n  inline Math::Vector3d voxelSizeMM(std::tr1::shared_ptr<const Image::Image3DSize> pVolumeSize) \n  { \n    Math::Vector3d size;\n    size(0) = voxelWidthMM(pVolumeSize);\n    size(1) = voxelHeightMM(pVolumeSize);\n    size(2) = voxelDepthMM(pVolumeSize);\n    return size; \n  }    \n  inline Math::Vector3d voxelSizeMMInverted(std::tr1::shared_ptr<const Image::Image3DSize> pVolumeSize) \n  { \n     Math::Vector3d size;\n     size(0) = 1.0/voxelWidthMM(pVolumeSize);\n     size(1) = 1.0/voxelHeightMM(pVolumeSize);\n     size(2) = 1.0/voxelDepthMM(pVolumeSize);\n     return size; \n  } \n  \n\n  /**\n   * Getter for the width of the whole volume object in mm\n   * @return The width of the volume object\n   */\n  inline const double widthMM(std::tr1::shared_ptr<const Image::Image3DSize> pVolumeSize) { return pVolumeSize->sizeMM()(0); }\n\n  /**\n   * Getter for the height of the whole volume object in mm\n   * @return The height of the volume object\n   */\n  inline const double heightMM(std::tr1::shared_ptr<const Image::Image3DSize> pVolumeSize) { return pVolumeSize->sizeMM()(1); }\n\n  /**\n   * Getter for the depth of the whole volume object in mm\n   * @return The depth of the volume object\n   */\n  inline const double depthMM(std::tr1::shared_ptr<const Image::Image3DSize> pVolumeSize) { return pVolumeSize->sizeMM()(2); }\n\n\n  inline Math::Vector3d sizeMM(std::tr1::shared_ptr<const Image::Image3DSize> pVolumeSize) { return pVolumeSize->sizeMM(); }\n\n\n  /**\n   * Getter for the width of the whole volume object in indices\n   * @return The width of the volume object\n   */\n  inline const uint width(std::tr1::shared_ptr<const Image::Image3DSize> pVolumeSize) { return pVolumeSize->size()(0); }\n\n  /**\n   * Getter for the height of the whole volume object in indices\n   * @return The height of the volume object\n   */\n  inline const uint height(std::tr1::shared_ptr<const Image::Image3DSize> pVolumeSize) { return pVolumeSize->size()(1); }\n\n  /**\n   * Getter for the depth of the whole volume object in indices\n   * @return The depth of the volume object\n   */\n  inline const uint depth(std::tr1::shared_ptr<const Image::Image3DSize> pVolumeSize) { return pVolumeSize->size()(2); }\n\n  inline Math::Vector3ui size(std::tr1::shared_ptr<const Image::Image3DSize> pVolumeSize) { return pVolumeSize->size(); }\n\n\n  /**\n   * Checks whether given relative mm-based point is outside of volume\n   * @param   vecPoint The point to check for\n   * @return  True, if the point is outside the volume\n   */\n  inline const bool isOutside(std::tr1::shared_ptr<const Image::Image3DSize> pVolume, const Math::Vector3d& vecPoint) {\n     Math::Vector3d sizeMM = pVolume->sizeMM();\n     if (vecPoint(0) < 0 || vecPoint(0) > sizeMM(0) || \n         vecPoint(1) < 0 || vecPoint(1) > sizeMM(1) || \n         vecPoint(2) < 0 || vecPoint(2) > sizeMM(2))\n     {\n        return true;\n     }\n     return false; \n  }\n\n\n  /**\n   * Checks whether given relative index-based point is outside of volume\n   * @param   vecPoint The point to check for\n   * @return  True, if the point is outside the volume\n   */      \n  inline const bool isOutside(std::tr1::shared_ptr<const Image::Image3DSize> pVolume, const Math::Vector3i& vecPoint){\n     Math::Vector3ui size = pVolume->size();\n     if (vecPoint(0) < 0 || vecPoint(0) >= static_cast<int>(size(0)) || \n         vecPoint(1) < 0 || vecPoint(1) >= static_cast<int>(size(1)) || \n         vecPoint(2) < 0 || vecPoint(2) >= static_cast<int>(size(2)))\n     {\n        return true;\n     }\n     return false; \n  }\n\n  inline const bool isOutside(std::tr1::shared_ptr<const Image::Image3DSize> pVolume, const Math::Vector3ui& vecPoint){\n     Math::Vector3ui size = pVolume->size();\n     // code review 25.09.2012: is it necessary to check for less than zero? isn't unsigned not always zero at minimum?\n     if (vecPoint(0) < 0 || (unsigned int)vecPoint(0) >= size(0) || \n         vecPoint(1) < 0 || (unsigned int)vecPoint(1) >= size(1) || \n         vecPoint(2) < 0 || (unsigned int)vecPoint(2) >= size(2))\n     {\n        return true;\n     }\n     return false; \n  }\n\n  /** \n   * Returns the absolute BoundingBox around the volume.\n   * @return   The absolute BoundingBox around the volume\n   */\n  //Math::BoundingBoxD getBoundingBox(std::tr1::shared_ptr<const Volume> pVolume) {}\n\n\n  /**\n   * Returns index position corresponding to the given mm position.\n   * @return The index position\n   */\n\n  inline void convertToVecPosition(std::tr1::shared_ptr<const Image::Image3DSize> pVolumeSize, const unsigned long index, Math::Vector3ui& vecPosition )\n  {\n     vecPosition(0) = ( index % pVolumeSize->size()(0) ) ;\n     vecPosition(1) = ( (index % (pVolumeSize->size()(0) * pVolumeSize->size()(1))) / pVolumeSize->size()(0) );\n     vecPosition(2) = index / (pVolumeSize->size()(0) * pVolumeSize->size()(1));\n  }\n\n  inline void convertToPosition (std::tr1::shared_ptr<const Image::Image3DSize> pVolumeSize, unsigned long index, Math::Vector3d &pos){\n     Math::Vector3d voxl_mm = voxelSizeMM(pVolumeSize);\n     Math::Vector3ui vecPos;\n     convertToVecPosition(pVolumeSize, index, vecPos);\n     pos = Math::elementProd<Math::Vector3d>(vecPos, voxl_mm);\n  }\n\n\n\n  inline uint convertToIndex(std::tr1::shared_ptr<const Image::Image3DSize> pVolumeSize, const Math::Vector3ui& vecPosition)\n  {\n    return (vecPosition(2) * pVolumeSize->size()(1) + vecPosition(1)) * pVolumeSize->size()(0) + vecPosition(0);\n  }\n\n\n  inline uint convertToIndex(std::tr1::shared_ptr<const Image::Image3DSize> pVolumeSize, const Math::Vector3i& vecPosition)\n  {\n    assert(vecPosition(0) >= 0 && vecPosition(0) < static_cast<int>(pVolumeSize->size()(0)) &&\n      vecPosition(1) >= 0 && vecPosition(1) < static_cast<int>(pVolumeSize->size()(1)) &&\n      vecPosition(2) >= 0 && vecPosition(2) < static_cast<int>(pVolumeSize->size()(2)));\n\n    Math::Vector3ui vec;\n    vec(0) = static_cast<uint>(vecPosition(0));\n    vec(1) = static_cast<uint>(vecPosition(1));\n    vec(2) = static_cast<uint>(vecPosition(2));\n    return convertToIndex(pVolumeSize, vec);\n  }\n\n\n  inline Math::Vector3i convertToIndexPosition(std::tr1::shared_ptr<const Image::Image3DSize> pVolumeSize, const Math::Vector3d& vecPosition)\n  {\n    Math::Vector3i result;\n    result(0) = static_cast<int>(vecPosition(0) * pVolumeSize->size()(0) / pVolumeSize->sizeMM()(0));\n    result(1) = static_cast<int>(vecPosition(1) * pVolumeSize->size()(1) / pVolumeSize->sizeMM()(1));\n    result(2) = static_cast<int>(vecPosition(2) * pVolumeSize->size()(2) / pVolumeSize->sizeMM()(2));\n    return result;\n  }\n\n\n  /**\n   * Returns internal memory index corresponding to the given index/mm position.\n   * @return The index\n   */\n  inline uint convertToIndex(std::tr1::shared_ptr<const Image::Image3DSize> pVolumeSize, const Math::Vector3d& vecPosition)\n  {\n    return convertToIndex(pVolumeSize, convertToIndexPosition(pVolumeSize, vecPosition));\n  }\n\n\n  inline Math::Matrix44d normalizedTVolume(std::tr1::shared_ptr<const Image::Image3DSize> pVolumeSize)\n  {\n    Math::Matrix44d mat = Math::MatrixTraits<Math::Matrix44d>::IDENTITY;\n    mat(0, 0) = 1.0 / widthMM(pVolumeSize);\n    mat(1, 1) = 1.0 / heightMM(pVolumeSize);\n    mat(2, 2) = 1.0 / depthMM(pVolumeSize);\n    return mat;\n  }\n\n\n  inline Math::Matrix44d volumeTNormalized(std::tr1::shared_ptr<const Image::Image3DSize> pVolumeSize)\n  {\n    Math::Matrix44d mat = Math::MatrixTraits<Math::Matrix44d>::IDENTITY;\n    mat(0, 0) = widthMM(pVolumeSize);\n    mat(1, 1) = heightMM(pVolumeSize);\n    mat(2, 2) = depthMM(pVolumeSize);\n    return mat;\n  }\n\n}\n\nOPENOR_CREATE_INTERFACE(openOR::Image::Image3DSize)\n   Math::Vector3d sizeMM() const { return adaptee()->sizeMM(); }\n   void setSizeMM(const Math::Vector3d& size) { adaptee()->setSizeMM(size); }\n\n   Math::Vector3ui size() const { return adaptee()->size(); }\n   void setSize(const Math::Vector3ui& size) { adaptee()->setSize(size); }\nOPENOR_CREATE_INTERFACE_END\n\n\n#endif \n", "meta": {"hexsha": "0cc82d50abfef79738562ef85272088f6ca161c1", "size": 10681, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/plugins/Image/ImageData/include/openOR/Image/Image3DSize.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/plugins/Image/ImageData/include/openOR/Image/Image3DSize.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/plugins/Image/ImageData/include/openOR/Image/Image3DSize.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": 37.3461538462, "max_line_length": 161, "alphanum_fraction": 0.6497518959, "num_tokens": 2991, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4565023051795534}}
{"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 NT2_LINALG_FUNCTIONS_TIED_RSF2CSF_HPP_INCLUDED\n#define NT2_LINALG_FUNCTIONS_TIED_RSF2CSF_HPP_INCLUDED\n\n#include <nt2/linalg/functions/rsf2csf.hpp>\n#include <boost/dispatch/attributes.hpp>\n#include <nt2/core/container/table/table.hpp>\n#include <nt2/include/functions/conj.hpp>\n#include <nt2/include/functions/cons.hpp>\n#include <nt2/include/functions/ctranspose.hpp>\n#include <nt2/include/functions/dec.hpp>\n#include <nt2/include/functions/hypot.hpp>\n#include <nt2/include/functions/is_real.hpp>\n#include <nt2/include/functions/mtimes.hpp>\n#include <nt2/include/functions/multiplies.hpp>\n#include <nt2/include/functions/nseig.hpp>\n#include <nt2/include/functions/rec.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#include <nt2/core/container/colon/colon.hpp>\n#include <nt2/core/utility/of_size.hpp>\n#include <nt2/core/utility/assign_swap.hpp>\n\nnamespace nt2 { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT  ( rsf2csf_, tag::cpu_\n                            , (A0)(A1)\n                            , (scalar_<floating_<A0> >)\n                              (scalar_<floating_<A1> >)\n                            )\n  {\n    typedef typename meta::as_complex<A0>::type result_type;\n\n    BOOST_FORCEINLINE result_type operator()(const A0& a0, const A1& ) const\n    {\n      BOOST_ASSERT_MSG(is_real(a0), \"diagonal is not valid\");\n      return result_type(a0);\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  ( rsf2csf_, tag::cpu_\n                            , (A0)(N0)(A1)(N1)\n                            , ((node_<A0, nt2::tag::rsf2csf_\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_, rtype_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 - [v, w] = rsf2csf(cv, cw)\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       auto& u = boost::proto::child_c<0>(a0);\n       auto& t = boost::proto::child_c<1>(a0);\n       container::table<ctype_t> cu = u;\n       container::table<ctype_t> ct = t;\n\n       std::size_t n = size(t, 2);\n       for(std::size_t m = n; m >= 2; --m)\n       {\n         std::size_t dm = dec(m);\n         if(t(m, dm))\n         {\n           auto k = _(dm, m);\n           auto mu = nseig(t(k,k)) - t(m,m);\n           rtype_t r = rec(hypot(mu(1), t(m,m-1)));\n           ctype_t c = mu(1)*r;\n           ctype_t s = ct(m,m-1)*r;\n           container::table<ctype_t> g = cons<ctype_t>(of_size(2, 2), conj(c), -s, s, c);\n           ct(k,_(m-1, n)) = mtimes(g, ct(k,_(m-1, n)));\n           ct(_(1, m),k) = mtimes(ct(_(1, m),k), ctrans(g));\n           cu(_,k) = mtimes(u(_,k), ctrans(g));\n           ct(m,dm) = 0;\n         }\n       }\n       assign_swap(boost::proto::child_c<0>(a1), cu);\n       assign_swap(boost::proto::child_c<1>(a1), ct);\n    }\n\n\n\n  };\n} }\n\n#endif\n", "meta": {"hexsha": "7c9c26652dcb005ae1cb0632281a38bbf2a30c0a", "size": 4197, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/linalg/include/nt2/linalg/functions/tied/rsf2csf.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "modules/core/linalg/include/nt2/linalg/functions/tied/rsf2csf.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/rsf2csf.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": 37.1415929204, "max_line_length": 89, "alphanum_fraction": 0.5098880152, "num_tokens": 1075, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4565023051795534}}
{"text": "#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#include <iostream>\n#include <list>\n#include <math.h>\n#include <omp.h>\n#include <sstream>\n#include <string>\n#include <vector>\n#include <vtkCell.h>\n#include <vtkCellData.h>\n#include <vtkDoubleArray.h>\n#include <vtkKdTree.h>\n#include <vtkPointData.h>\n#include <vtkPolyData.h>\n#include <vtkPolyDataReader.h>\n#include <vtkPolyDataWriter.h>\n#include <vtkSmartPointer.h>\n//#include \"HelperFunctions.h\"\n\nusing namespace std;\n// using namespace OPS;\n\ntypedef Eigen::Vector3d Vector3d;\n\n//! A struct to store a vtkIdType and an angle\nstruct neighbors {\n  vtkIdType _id;\n  double_t _angle;\n  neighbors(vtkIdType i, double_t a) : _id(i), _angle(a) {}\n  bool operator<(const neighbors &n) const { return _angle < n._angle; }\n};\n\nint main(int argc, char *argv[]) {\n  if (argc != 5) {\n    cout << \"argc = \" << argc << endl\n         << \"Usage: dualMesh baseName numStart numEnd numOPENMPThreads\" << endl;\n    return (0);\n  }\n\n  ////////////////////////////////////////////////////////////////////\n  // Input section\n  ////////////////////////////////////////////////////////////////////\n\n  // read in vtk file\n  string baseFileName = argv[1];\n  size_t numStart = stoi(argv[2]);\n  size_t numEnd = stoi(argv[3]);\n  size_t numThreads = stoi(argv[4]);\n\n  // Set the number of threads\n  omp_set_num_threads(numThreads);\n\n#pragma omp parallel for\n  for (size_t bigI = numStart; bigI <= numEnd; bigI++) {\n    stringstream sstm;\n    string inputFileName, outFileName;\n    sstm << baseFileName << \"-\" << bigI << \".vtk\";\n    inputFileName = sstm.str();\n    sstm.str(\"\");\n    sstm.clear();\n\n    auto reader = vtkSmartPointer<vtkPolyDataReader>::New();\n    reader->SetFileName(inputFileName.c_str());\n    reader->Update();\n    vtkSmartPointer<vtkPolyData> inputMesh = reader->GetOutput();\n    inputMesh->BuildLinks();\n    size_t npts = inputMesh->GetNumberOfPoints();\n\n    // get displacement vectors, if they exist\n    string vectorName = \"displacements\";\n    vtkSmartPointer<vtkDoubleArray> displacements =\n        vtkDoubleArray::SafeDownCast(\n            inputMesh->GetPointData()->GetVectors(vectorName.c_str()));\n\n    // get vertex positions\n    std::vector<Vector3d> points(npts, Vector3d::Zero());\n\n    // Calculate centroid of each triangle while updating points vector\n    auto newPts = vtkSmartPointer<vtkPoints>::New();\n    vtkSmartPointer<vtkCellArray> cells = inputMesh->GetPolys();\n    auto cellPointIds = vtkSmartPointer<vtkIdList>::New();\n    cells->InitTraversal();\n    while (cells->GetNextCell(cellPointIds)) {\n      size_t numCellPoints = cellPointIds->GetNumberOfIds();\n      Vector3d centroid(0.0, 0.0, 0.0);\n      for (size_t i = 0; i < numCellPoints; i++) {\n        vtkIdType currCellPoint = cellPointIds->GetId(i);\n        inputMesh->GetPoint(currCellPoint, &points[currCellPoint][0]);\n        if (displacements.GetPointer() != NULL) {\n          Vector3d currDisp(0.0, 0.0, 0.0);\n          displacements->GetTuple(currCellPoint, &currDisp[0]);\n          points[currCellPoint] += currDisp;\n        }\n        centroid += points[currCellPoint];\n      }\n      centroid /= numCellPoints;\n      newPts->InsertNextPoint(&centroid[0]);\n    }\n\n    // Prepare valence Cell Data array\n    auto valence = vtkSmartPointer<vtkIntArray>::New();\n    valence->SetName(\"Valence\");\n    valence->SetNumberOfComponents(1);\n\n    // Prepare new cell array for polygons\n    auto newPolys = vtkSmartPointer<vtkCellArray>::New();\n\n    for (size_t a = 0; a < npts; a++) {\n\n      auto currPolyPtIds = vtkSmartPointer<vtkIdList>::New();\n      std::list<neighbors> currPoly;\n      Vector3d vec0, vecj, currCross, axis, centroid(0.0, 0.0, 0.0);\n      double vec0_norm, vecj_norm, sign, currSin, currCos, currAngle;\n\n      inputMesh->GetPointCells(a, currPolyPtIds);\n      size_t numCellPoints = currPolyPtIds->GetNumberOfIds();\n\n      // Get coordinates of first cell's centroid\n      vtkIdType currId = currPolyPtIds->GetId(0);\n      newPts->GetPoint(currId, &centroid[0]);\n      vec0 = (centroid - points[a]).normalized();\n      neighbors pt0(currId, 0.0);\n      currPoly.push_back(pt0);\n\n      // For remaining centroids\n      for (auto j = 1; j < numCellPoints; j++) {\n        currId = currPolyPtIds->GetId(j);\n        newPts->GetPoint(currId, &centroid[0]);\n        vecj = (centroid - points[a]).normalized();\n        currSin = (vec0.cross(vecj)).norm();\n        axis = (vec0.cross(vecj)).normalized();\n        sign = axis.dot(points[a]);\n        currSin = (sign > 0.0) ? currSin : -1.0 * currSin;\n        currCos = vec0.dot(vecj);\n        currAngle = (180 / M_PI) * atan2(currSin, currCos);\n        currAngle = (currAngle < 0) ? (360 + currAngle) : currAngle;\n        neighbors ptj(currId, currAngle);\n        currPoly.push_back(ptj);\n      }\n\n      // Sort the list of neigbors and make a polygon\n      currPoly.sort();\n      newPolys->InsertNextCell(numCellPoints);\n      for (auto t = currPoly.begin(); t != currPoly.end(); ++t) {\n        neighbors n = *t;\n        newPolys->InsertCellPoint(n._id);\n      }\n      valence->InsertNextTuple1(numCellPoints);\n    }\n\n    // Assign points and polygons to a new polydata and write it out\n    auto newPolyData = vtkSmartPointer<vtkPolyData>::New();\n    auto writer = vtkSmartPointer<vtkPolyDataWriter>::New();\n\n    newPolyData->SetPoints(newPts);\n    newPolyData->SetPolys(newPolys);\n    newPolyData->GetCellData()->AddArray(valence);\n    writer->SetInputData(newPolyData);\n    sstm << baseFileName << \"-dual-\" << bigI << \".vtk\";\n    outFileName = sstm.str();\n    sstm.str(\"\");\n    sstm.clear();\n    writer->SetFileName(outFileName.c_str());\n    writer->Write();\n  }\n  return 0;\n}\n", "meta": {"hexsha": "4e8c8b292f5d5d36f3b36c6cf2a9e760dc168058", "size": 5649, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/Drivers/DualMesh.cxx", "max_stars_repo_name": "amit112amit/oriented-particles", "max_stars_repo_head_hexsha": "1bb0f01a49d9bf33b88c4748025af756faf26688", "max_stars_repo_licenses": ["MIT", "BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-21T08:01:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-21T08:01:15.000Z", "max_issues_repo_path": "src/Drivers/DualMesh.cxx", "max_issues_repo_name": "amit112amit/oriented-particles", "max_issues_repo_head_hexsha": "1bb0f01a49d9bf33b88c4748025af756faf26688", "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/Drivers/DualMesh.cxx", "max_forks_repo_name": "amit112amit/oriented-particles", "max_forks_repo_head_hexsha": "1bb0f01a49d9bf33b88c4748025af756faf26688", "max_forks_repo_licenses": ["MIT", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.426035503, "max_line_length": 80, "alphanum_fraction": 0.6348026199, "num_tokens": 1502, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.4564738999385152}}
{"text": "#pragma once\n\n#include <Eigen/Core>\n\n#include <vector>\n#include <array>\n#include <complex>\n\n#include \"Spirit_Defines.h\"\n\n// Dynamic Eigen typedefs\nusing VectorX    = Eigen::Matrix<scalar, -1,  1>;\nusing RowVectorX = Eigen::Matrix<scalar,  1, -1>;\nusing MatrixX    = Eigen::Matrix<scalar, -1, -1>;\n\n// 3D Eigen typedefs\nusing Vector3    = Eigen::Matrix<scalar, 3, 1>;\nusing RowVector3 = Eigen::Matrix<scalar, 1, 3>;\nusing Matrix3    = Eigen::Matrix<scalar, 3, 3>;\n\nusing Vector3c   = Eigen::Matrix<std::complex<scalar>, 3, 1>;\nusing Matrix3c   = Eigen::Matrix<std::complex<scalar>, 3, 3>;\n\n// Different definitions for regular C++ and CUDA\n#ifdef SPIRIT_USE_CUDA\n    // The general field, using the managed allocator\n    #include \"Managed_Allocator.hpp\"\n    template<typename T>\n    using field = std::vector<T, managed_allocator<T>>;\n\n    struct Site\n    {\n        // Basis index\n        int i;\n        // Translations of the basis cell\n        int translations[3];\n    };\n    struct Pair\n    {\n        // Basis indices of first and second atom of pair\n        int i, j;\n        // Translations of the basis cell of second atom of pair\n        int translations[3];\n    };\n    struct Triplet\n    {\n        int i, j, k;\n        int d_j[3], d_k[3];\n    };\n    struct Quadruplet\n    {\n        int i, j, k, l;\n        int d_j[3], d_k[3], d_l[3];\n    };\n#else\n    // The general field\n    template<typename T>\n    using field = std::vector<T>;\n\n    struct Site\n    {\n        // Basis index\n        int i;\n        // Translations of the basis cell\n        std::array<int,3> translations;\n    };\n    struct Pair\n    {\n        int i, j;\n        std::array<int,3> translations;\n    };\n    struct Triplet\n    {\n        int i, j, k;\n        std::array<int,3> d_j, d_k;\n    };\n    struct Quadruplet\n    {\n        int i, j, k, l;\n        std::array<int,3> d_j, d_k, d_l;\n    };\n\n    // Definition for OpenMP reduction operation using Vector3's\n    #pragma omp declare reduction (+: Vector3: omp_out=omp_out+omp_in)\\\n        initializer(omp_priv=Vector3::Zero())\n#endif\n\nstruct Neighbour : Pair\n{\n    // Shell index\n    int idx_shell;\n};\n\n// Important fields\nusing intfield    = field<int>;\nusing scalarfield = field<scalar>;\nusing vectorfield = field<Vector3>;\n\n// Additional fields\nusing pairfield       = field<Pair>;\nusing tripletfield    = field<Triplet>;\nusing quadrupletfield = field<Quadruplet>;\nusing neighbourfield  = field<Neighbour>;", "meta": {"hexsha": "092077ed5248ff1f2c54e278ac5b2549f83021cd", "size": 2430, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "core/include/engine/Vectormath_Defines.hpp", "max_stars_repo_name": "ddkn/spirit", "max_stars_repo_head_hexsha": "8e51bcdd78ee05d433d000c7e389fe1e6c3716bc", "max_stars_repo_licenses": ["MIT"], "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/include/engine/Vectormath_Defines.hpp", "max_issues_repo_name": "ddkn/spirit", "max_issues_repo_head_hexsha": "8e51bcdd78ee05d433d000c7e389fe1e6c3716bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "core/include/engine/Vectormath_Defines.hpp", "max_forks_repo_name": "ddkn/spirit", "max_forks_repo_head_hexsha": "8e51bcdd78ee05d433d000c7e389fe1e6c3716bc", "max_forks_repo_licenses": ["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.5922330097, "max_line_length": 71, "alphanum_fraction": 0.6086419753, "num_tokens": 674, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.4564518717209199}}
{"text": "#define BOOST_TEST_MODULE\n#include <boost/test/unit_test.hpp>\n#include <core/util/test_macros.hpp>\n#include <core/storage/sgraph_data/sgraph.hpp>\n#include <core/storage/sgraph_data/sgraph_engine.hpp>\n\n#include \"sgraph_test_util.hpp\"\n#include \"sgraph_check_degree_count.hpp\"\n#include \"sgraph_check_pagerank.hpp\"\n\nusing namespace turi;\n\n// Implement degree count function using sgraph_engine\nstd::vector<std::pair<flexible_type, flexible_type>> degree_count_fn (\n  sgraph& g, sgraph::edge_direction dir) {\n\n  sgraph_compute::sgraph_engine<flexible_type> ga;\n  typedef sgraph_compute::sgraph_engine<flexible_type>::graph_data_type graph_data_type;\n  typedef sgraph::edge_direction edge_direction;\n  std::vector<std::shared_ptr<sarray<flexible_type>>> \n      gather_results = ga.gather(g,\n                                 [](const graph_data_type& center, \n                                    const graph_data_type& edge, \n                                    const graph_data_type& other, \n                                    edge_direction edgedir,\n                                    flexible_type& combiner) {\n                                   combiner = combiner + 1;\n                                 },\n                                 flexible_type(0),\n                                 dir);\n  std::vector<std::shared_ptr<sarray<flexible_type>>> vertex_ids \n      = g.fetch_vertex_data_field(sgraph::VID_COLUMN_NAME);\n\n  TS_ASSERT_EQUALS(gather_results.size(), vertex_ids.size());\n  std::vector<std::pair<flexible_type, flexible_type>> ret;\n\n  for (size_t i = 0;i < gather_results.size(); ++i) {\n    std::vector<flexible_type> degree_vec;\n    std::vector<flexible_type> id_vec;\n    gather_results[i]->get_reader()->read_rows(0, g.num_vertices(), degree_vec);\n    vertex_ids[i]->get_reader()->read_rows(0, g.num_vertices(), id_vec);\n    TS_ASSERT_EQUALS(degree_vec.size(), id_vec.size());\n    for (size_t j = 0; j < degree_vec.size(); ++j) {\n      ret.push_back({id_vec[j], degree_vec[j]});\n    }\n  }\n  return ret;\n}\n\n// Implement degree count function using sgraph_engine\nvoid pagerank_fn(sgraph& g,  size_t num_iterations) {\n  sgraph_compute::sgraph_engine<flexible_type> ga;\n  typedef sgraph_compute::sgraph_engine<flexible_type>::graph_data_type graph_data_type;\n  typedef sgraph::edge_direction edge_direction;\n  // count the outgoing degree\n  std::vector<std::shared_ptr<sarray<flexible_type>>> vertex_combine = ga.gather(g,\n                                                      [](const graph_data_type& center, \n                                                         const graph_data_type& edge, \n                                                         const graph_data_type& other, \n                                                         edge_direction edgedir,\n                                                         flexible_type& combiner) {\n                                                      combiner = combiner + 1;\n                                                      },\n                                                      flexible_type(0),\n                                                      edge_direction::OUT_EDGE);\n  // merge the outgoing degree to graph\n  std::vector<sframe>& vdata = g.vertex_group();\n  for (size_t i = 0; i < g.get_num_partitions(); ++i) {\n    ASSERT_LT(i, vdata.size());\n    ASSERT_LT(i, vertex_combine.size());\n    vdata[i] = vdata[i].add_column(vertex_combine[i], \"__out_degree__\");\n  }\n\n  size_t degree_idx = vdata[0].column_index(\"__out_degree__\");\n  size_t data_idx = vdata[0].column_index(\"vdata\");\n\n  // now we compute the pagerank\n  for (size_t iter = 0; iter < num_iterations; ++iter) {\n    vertex_combine = ga.gather(g,\n        [=](const graph_data_type& center,\n            const graph_data_type& edge,\n            const graph_data_type& other,\n            edge_direction edgedir,\n            flexible_type& combiner) {\n           combiner = combiner + 0.85 * (other[data_idx] / other[degree_idx]);\n        },\n        flexible_type(0.15),\n        edge_direction::IN_EDGE);\n    for (size_t i = 0; i < g.get_num_partitions(); ++i) {\n      vdata[i] = vdata[i].replace_column(vertex_combine[i], \"vdata\");\n    }\n    // g.get_vertices().debug_print();\n  }\n}\n\nstruct sgraph_engine_test {\n\npublic:\n void test_degree_count() {\n   check_degree_count(degree_count_fn);\n }\n\n void test_pagerank() {\n   check_pagerank(pagerank_fn);\n }\n\n};\n\nBOOST_FIXTURE_TEST_SUITE(_sgraph_engine_test, sgraph_engine_test)\nBOOST_AUTO_TEST_CASE(test_degree_count) {\n  sgraph_engine_test::test_degree_count();\n}\nBOOST_AUTO_TEST_CASE(test_pagerank) {\n  sgraph_engine_test::test_pagerank();\n}\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "614c74c25024e1e4a93179ae574187edda6e0c84", "size": 4654, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "test/sgraph/sgraph_engine_test.cxx", "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": "test/sgraph/sgraph_engine_test.cxx", "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": "test/sgraph/sgraph_engine_test.cxx", "max_forks_repo_name": "Bpowers4/turicreate", "max_forks_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 39.7777777778, "max_line_length": 88, "alphanum_fraction": 0.5992694456, "num_tokens": 1020, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410572017153, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.45643802350385804}}
{"text": "#pragma once\n#ifndef CANNON_GRAPHICS_PROJECTION_H\n#define CANNON_GRAPHICS_PROJECTION_H \n\n/*!\n * \\file cannon/graphics/projection.hpp\n * \\brief File containing utility free functions for computing projections.\n */\n\n#include <Eigen/Dense>\n\nusing namespace Eigen;\n\nnamespace cannon {\n  namespace graphics {\n\n    /*!\n     * Function to convert degrees to radians.\n     * \n     * \\param degrees Angle representation in degrees.\n     *\n     * \\returns Angle representation in radians.\n     */\n    float to_radians(float degrees);\n\n    /*!\n     * Compute perspective matrix corresponding to a view frustum specified by\n     * the inputs.\n     *\n     * \\param left Left extent of the frustum.\n     * \\param right Right extent of the frustum.\n     * \\param bottom Lower extent of the frustum.\n     * \\param top Upper extent of the frustum.\n     * \\param near Depth of the near clipping plane.\n     * \\param far Depth of the far clipping plane.\n     *\n     * \\returns The corresponding perspective matrix.\n     */\n    Matrix4f make_perspective_frustum(float left, float right, float bottom,\n        float top, float near, float far);\n\n    /*!\n     * Compute perspective matrix corresponding to a view frustum with a given\n     * field of view and aspect ratio.\n     *\n     * \\param fov The field of view (in radians) of the frustum.\n     * \\param aspect The aspect ratio of the frustum.\n     * \\param near Depth of the near clipping plane.\n     * \\param far Depth of the far clipping plane.\n     *\n     * \\returns The corresponding perspective matrix.\n     */\n    Matrix4f make_perspective_fov(float fov, float aspect, float near, float far);\n\n    /*!\n     * Compute orthographic projection matrix corresponding to a view frustum\n     * specified by the inputs.\n     *\n     * \\param left Left extent of the frustum.\n     * \\param right Right extent of the frustum.\n     * \\param bottom Lower extent of the frustum.\n     * \\param top Upper extent of the frustum.\n     * \\param near Depth of the near clipping plane.\n     * \\param far Depth of the far clipping plane.\n     *\n     * \\returns The corresponding projection matrix.\n     */\n    Matrix4f make_orthographic(float left, float right, float bottom, float\n        top, float near, float far);\n\n  } // namespace graphics\n} // namespace cannon\n\n#endif /* ifndef CANNON_GRAPHICS_PROJECTION_H */\n", "meta": {"hexsha": "334e2b1d09227e7b060c41aebf3f7015d04204d8", "size": 2336, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cannon/graphics/projection.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/graphics/projection.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/graphics/projection.hpp", "max_forks_repo_name": "cannontwo/cannon", "max_forks_repo_head_hexsha": "4be79f3a6200d1a3cd26c28c8f2250dbdf08f267", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.1466666667, "max_line_length": 82, "alphanum_fraction": 0.6772260274, "num_tokens": 524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081925, "lm_q2_score": 0.665410572017153, "lm_q1q2_score": 0.45643801923185573}}
{"text": "//  (C) Copyright Eric Niebler, Olivier Gygi 2006.\r\n//  Use, modification and distribution are subject to the\r\n//  Boost Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#include <boost/test/unit_test.hpp>\r\n#include <boost/accumulators/accumulators.hpp>\r\n#include <boost/accumulators/statistics/stats.hpp>\r\n#include <boost/accumulators/statistics/weighted_sum.hpp>\r\n#include <boost/accumulators/statistics/variates/covariate.hpp>\r\n\r\nusing namespace boost;\r\nusing namespace unit_test;\r\nusing namespace accumulators;\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// test_stat\r\n//\r\nvoid test_stat()\r\n{\r\n    accumulator_set<int, stats<tag::weighted_sum, tag::weighted_sum_of_variates<int, tag::covariate1> >, int> acc;\r\n\r\n    acc(1, weight = 2, covariate1 = 3);\r\n    BOOST_CHECK_EQUAL(2, weighted_sum(acc));\r\n    BOOST_CHECK_EQUAL(6, weighted_sum_of_variates(acc));\r\n\r\n    acc(2, weight = 3, covariate1 = 6);\r\n    BOOST_CHECK_EQUAL(8, weighted_sum(acc));\r\n    BOOST_CHECK_EQUAL(24, weighted_sum_of_variates(acc));\r\n\r\n    acc(4, weight = 6, covariate1 = 9);\r\n    BOOST_CHECK_EQUAL(32, weighted_sum(acc));\r\n    BOOST_CHECK_EQUAL(78, weighted_sum_of_variates(acc));\r\n}\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// init_unit_test_suite\r\n//\r\ntest_suite* init_unit_test_suite( int argc, char* argv[] )\r\n{\r\n    test_suite *test = BOOST_TEST_SUITE(\"weighted_sum test\");\r\n\r\n    test->add(BOOST_TEST_CASE(&test_stat));\r\n\r\n    return test;\r\n}\r\n", "meta": {"hexsha": "4fd68e3aaeec00b70cc61df060686afb0d0a72ae", "size": 1587, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/accumulators/test/weighted_sum.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/accumulators/test/weighted_sum.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/accumulators/test/weighted_sum.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": 33.7659574468, "max_line_length": 115, "alphanum_fraction": 0.6452425961, "num_tokens": 370, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081926, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.4564380146804649}}
{"text": "#ifndef __CAMERAMODEL_HPP__\n#define __CAMERAMODEL_HPP__\n\n#include <memory>\n\n#include <Eigen/Dense>\n\n#include \"lvr2/types/MatrixTypes.hpp\"\n\nnamespace lvr2\n{\n\ntemplate<typename T>\nstruct PinholeModel\n{\n    double fx = 0;\n    double fy = 0;\n    double cx = 0;\n    double cy = 0;\n    unsigned width = 0;\n    unsigned height = 0;\n    std::vector<T> k;\n    std::string distortionModel = \"unknown\";\n};\n\ntemplate<typename T>\nusing PinholeModelPtr = std::shared_ptr<PinholeModel<T>>;\n\nusing PinholeModeld = PinholeModel<double>;\nusing PinholeModelf = PinholeModel<float>;\n\n\n} // namespace lvr2\n\n#endif", "meta": {"hexsha": "02b4ae64c82524231242fbc8c9efda8d064d0b4f", "size": 592, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/lvr2/registration/CameraModels.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/CameraModels.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/CameraModels.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": 16.9142857143, "max_line_length": 57, "alphanum_fraction": 0.7043918919, "num_tokens": 168, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494678483918, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.45643801412168705}}
{"text": "/* bitops_test.cc\n   Jeremy Barnes, 20 February 2007\n   Copyright (c) 2007 Jeremy Barnes.  All rights reserved.\n\n   Test of the bit operations class.\n*/\n\n#define BOOST_TEST_MAIN\n#define BOOST_TEST_DYN_LINK\n\n#include \"jml/arch/bitops.h\"\n#include \"jml/arch/tick_counter.h\"\n#include \"jml/arch/demangle.h\"\n#include \"jml/math/xdiv.h\"\n\n#include <boost/test/unit_test.hpp>\n#include <boost/test/auto_unit_test.hpp>\n#include <vector>\n#include <stdint.h>\n#include <iostream>\n\n\nusing namespace ML;\nusing namespace std;\n\nusing boost::unit_test::test_suite;\n\ntemplate<class X>\nvoid test1_type()\n{\n    cerr << \"testing type \" << demangle(typeid(X).name()) << endl;\n\n    BOOST_CHECK_EQUAL(highest_bit((X)0),       -1);\n    BOOST_CHECK_EQUAL(highest_bit((X)1),        0);\n    BOOST_CHECK_EQUAL(highest_bit((X)2),        1);\n    BOOST_CHECK_EQUAL(highest_bit((X)3),        1);\n    BOOST_CHECK_EQUAL(highest_bit((X)-1),       sizeof(X) * 8 - 1);\n    BOOST_CHECK_EQUAL(highest_bit((X)63),       5);\n    BOOST_CHECK_EQUAL(highest_bit((X)64),       6);\n    BOOST_CHECK_EQUAL(highest_bit((X)255),      7);\n\n    BOOST_CHECK_EQUAL(lowest_bit((X)0),       -1);\n    BOOST_CHECK_EQUAL(lowest_bit((X)1),        0);\n    BOOST_CHECK_EQUAL(lowest_bit((X)2),        1);\n    BOOST_CHECK_EQUAL(lowest_bit((X)3),        0);\n    BOOST_CHECK_EQUAL(lowest_bit((X)-1),       0);\n    BOOST_CHECK_EQUAL(lowest_bit((X)63),       0);\n    BOOST_CHECK_EQUAL(lowest_bit((X)64),       6);\n    BOOST_CHECK_EQUAL(lowest_bit((X)255),      0);\n    BOOST_CHECK_EQUAL(lowest_bit((X)128),      7);\n\n    if (sizeof(X) == 1) return;\n    BOOST_CHECK_EQUAL(highest_bit((X)256),      8);\n    BOOST_CHECK_EQUAL(lowest_bit((X)256),      8);\n\n    if (sizeof(X) == 2) return;\n    BOOST_CHECK_EQUAL(highest_bit((X)131071),  16);\n    BOOST_CHECK_EQUAL(highest_bit((X)131072),  17);\n    BOOST_CHECK_EQUAL(highest_bit((X)131073),  17);\n\n    BOOST_CHECK_EQUAL(lowest_bit((X)131071),  0);\n    BOOST_CHECK_EQUAL(lowest_bit((X)131072),  17);\n    BOOST_CHECK_EQUAL(lowest_bit((X)131073),  0);\n}\n\nBOOST_AUTO_TEST_CASE( test1 )\n{\n    test1_type<uint8_t>();\n    test1_type<int8_t>();\n    test1_type<uint16_t>();\n    test1_type<int16_t>();\n    test1_type<uint32_t>();\n    test1_type<int32_t>();\n    test1_type<uint64_t>();\n    test1_type<int64_t>();\n}\n\nuint64_t rand64()\n{\n    uint64_t high = rand(), low = rand();\n    return (high << 32) | low;\n}\n\ntemplate<class X>\nint fake_highest_bit(X x)\n{\n    return x;\n}\n\ntemplate<class X>\nvoid profile_type(const vector<uint64_t> & vals_)\n{\n    vector<X> vals(vals_.begin(), vals_.end());\n\n    cerr << \"profiling for \" << sizeof(X) * 8 << \" bits, \"\n         << ((X)-1 > 0 ? \"unsigned\" : \"signed\")\n         <<  \" with \" << vals.size() << \" vals\" << endl;\n\n    /* Measure the overhead */\n    double overhead = 0;\n\n    int trials = 10;\n\n    int total = 0;\n\n    for (unsigned t = 0;  t < trials;  ++t) {\n        uint64_t tbefore = ticks();\n        for (unsigned i = 0;  i < vals.size();  ++i)\n            total += fake_highest_bit(vals[i]);\n        uint64_t tafter = ticks();\n        overhead += tafter - tbefore - ticks_overhead;\n\n    }\n\n    cerr << \"measurement overhead is \" << overhead << endl;\n\n    double measured = 0;\n\n    for (unsigned t = 0;  t < trials;  ++t) {\n\n        uint64_t tbefore = ticks();\n        for (unsigned i = 0;  i < vals.size();  ++i)\n            total += highest_bit(vals[i]);\n        \n        uint64_t tafter = ticks();\n        \n        measured += tafter - tbefore - ticks_overhead;\n    }\n\n    srand(total);  // use it so it doesn't get optimized out\n\n    cerr << \"measured \" << measured << \" total ticks\" << endl;\n\n    double cost = xdiv<double>(measured - overhead, trials * vals.size());\n\n    cerr << \"cost: \" << cost << \" ticks/call\" << endl;\n}\n    \nBOOST_AUTO_TEST_CASE( profile )\n{\n    vector<uint64_t> vals;\n    for (unsigned i = 0;  i < 1000;  ++i)\n        vals.push_back(rand64());\n\n    profile_type<uint8_t>(vals);\n    profile_type<int8_t>(vals);\n    profile_type<uint16_t>(vals);\n    profile_type<int16_t>(vals);\n    profile_type<uint32_t>(vals);\n    profile_type<int32_t>(vals);\n    profile_type<uint64_t>(vals);\n    profile_type<int64_t>(vals);\n}\n\nBOOST_AUTO_TEST_CASE(test_rotate)\n{\n    BOOST_CHECK_EQUAL(rotate_right<uint8_t>(0, 0), 0);\n    BOOST_CHECK_EQUAL(rotate_right<uint8_t>(0, 1), 0);\n    BOOST_CHECK_EQUAL(rotate_right<uint8_t>(0, 8), 0);\n\n    BOOST_CHECK_EQUAL(rotate_left<uint8_t>(0, 0), 0);\n    BOOST_CHECK_EQUAL(rotate_left<uint8_t>(0, 1), 0);\n    BOOST_CHECK_EQUAL(rotate_left<uint8_t>(0, 8), 0);\n\n    BOOST_CHECK_EQUAL(rotate_right<uint8_t>(1, 0), 1);\n    BOOST_CHECK_EQUAL(rotate_right<uint8_t>(1, 1), 128);\n    BOOST_CHECK_EQUAL(rotate_right<uint8_t>(1, 7), 2);\n    BOOST_CHECK_EQUAL(rotate_right<uint8_t>(1, 8), 1);\n    BOOST_CHECK_EQUAL(rotate_right<uint8_t>(1, 16), 1);\n    BOOST_CHECK_EQUAL(rotate_right<uint8_t>(1, 17), 128);\n\n    BOOST_CHECK_EQUAL(rotate_left<uint8_t>(1, 0), 1);\n    BOOST_CHECK_EQUAL(rotate_left<uint8_t>(1, 1), 2);\n    BOOST_CHECK_EQUAL(rotate_left<uint8_t>(1, 7), 128);\n    BOOST_CHECK_EQUAL(rotate_left<uint8_t>(1, 8), 1);\n    BOOST_CHECK_EQUAL(rotate_left<uint8_t>(1, 16), 1);\n    BOOST_CHECK_EQUAL(rotate_left<uint8_t>(1, 17), 2);\n\n    BOOST_CHECK_EQUAL(rotate_right<uint8_t>(0, 0), 0);\n    BOOST_CHECK_EQUAL(rotate_right<uint8_t>(0, 1), 0);\n    BOOST_CHECK_EQUAL(rotate_right<uint8_t>(0, 8), 0);\n\n    BOOST_CHECK_EQUAL(rotate_left<int8_t>(0, 0), 0);\n    BOOST_CHECK_EQUAL(rotate_left<int8_t>(0, 1), 0);\n    BOOST_CHECK_EQUAL(rotate_left<int8_t>(0, 8), 0);\n\n    BOOST_CHECK_EQUAL(rotate_right<int8_t>(1, 0), 1);\n    BOOST_CHECK_EQUAL(rotate_right<int8_t>(1, 1), -128);\n    BOOST_CHECK_EQUAL(rotate_right<int8_t>(1, 7), 2);\n    BOOST_CHECK_EQUAL(rotate_right<int8_t>(1, 8), 1);\n    BOOST_CHECK_EQUAL(rotate_right<int8_t>(1, 16), 1);\n    BOOST_CHECK_EQUAL(rotate_right<int8_t>(1, 17), -128);\n\n    BOOST_CHECK_EQUAL(rotate_left<int8_t>(1, 0), 1);\n    BOOST_CHECK_EQUAL(rotate_left<int8_t>(1, 1), 2);\n    BOOST_CHECK_EQUAL(rotate_left<int8_t>(1, 7), -128);\n    BOOST_CHECK_EQUAL(rotate_left<int8_t>(1, 8), 1);\n    BOOST_CHECK_EQUAL(rotate_left<int8_t>(1, 16), 1);\n    BOOST_CHECK_EQUAL(rotate_left<int8_t>(1, 17), 2);\n}\n", "meta": {"hexsha": "78ac891ebe7ed0d38ac69d1751700c83aa2c3467", "size": 6167, "ext": "cc", "lang": "C++", "max_stars_repo_path": "jml/arch/testing/bitops_test.cc", "max_stars_repo_name": "etnrlz/rtbkit", "max_stars_repo_head_hexsha": "0d9cd9e2ee2d7580a27453ad0a2d815410d87091", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 737.0, "max_stars_repo_stars_event_min_datetime": "2015-01-04T01:40:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T10:09:23.000Z", "max_issues_repo_path": "jml/arch/testing/bitops_test.cc", "max_issues_repo_name": "TuanTranEngineer/rtbkit", "max_issues_repo_head_hexsha": "502d06acc3f8d90438946b6ae742190f2f4b4fbb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 56.0, "max_issues_repo_issues_event_min_datetime": "2015-01-05T16:01:03.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-22T19:02:37.000Z", "max_forks_repo_path": "jml/arch/testing/bitops_test.cc", "max_forks_repo_name": "TuanTranEngineer/rtbkit", "max_forks_repo_head_hexsha": "502d06acc3f8d90438946b6ae742190f2f4b4fbb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 329.0, "max_forks_repo_forks_event_min_datetime": "2015-01-01T06:54:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-12T22:21:02.000Z", "avg_line_length": 30.6815920398, "max_line_length": 74, "alphanum_fraction": 0.6419652992, "num_tokens": 1902, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.6859494485880927, "lm_q1q2_score": 0.4564380058570717}}
{"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#include <iostream>\n#include <iomanip>\n#include <cmath>\n\n#include <boost/timer/timer.hpp>\n\n#include \"dune/grid/config.h\"\n#include \"dune/grid/uggrid.hh\"\n#include \"dune/istl/preconditioners.hh\"\n\n#include \"fem/assemble.hh\"\n#include \"fem/norms.hh\"\n#include \"fem/lagrangespace.hh\"\n#include \"fem/hierarchicspace.hh\"\n#include \"fem/embedded_errorest.hh\"\n#include \"fem/istlinterface.hh\"\n#include \"fem/functional_aux.hh\"\n#include \"fem/iterate_grid.hh\"\n#include \"fem/hierarchicErrorEstimator.hh\"\n#include \"linalg/trivialpreconditioner.hh\"\n#include \"linalg/jacobiPreconditioner.hh\"\n#include \"linalg/direct.hh\"\n#include \"linalg/triplet.hh\"\n#include \"linalg/mumps_solve.hh\"\n\n#include \"io/vtk.hh\"\n#include \"io/amira.hh\"\n\n#include \"mg/pcg.hh\"\n#include \"linalg/apcg.hh\"\n\n#include \"utilities/enums.hh\"\n#include \"utilities/kaskopt.hh\"\n#include \"utilities/geometric_sequence.hh\"\n\nusing namespace Kaskade;\n#include \"poisson.hh\"\n#include \"createGrid.hh\"\n\nint problemNo = 1;\n\n\nbool compareAbs(const double x1, const double  x2)\n  {\n    return fabs(x1)>fabs(x2);\n  }\n  \n// Implements a test problem for the cascadic multigrid algorithm as of \n// Deuflhard/Weiser chapter 7.\n\nint main(int argc, char *argv[])\n{\n  int verbosity = 1;\n  bool dump = false;\n  std::unique_ptr<boost::property_tree::ptree> pt = getKaskadeOptions(argc, argv, verbosity, dump);\n  \n  std::cout << \"Start cascadic multigrid test program\" << std::endl;\n  \n  int  direct, refs, order, onlyLowerTriangle = false, maxAdaptSteps, gebiet;\n  DirectType directType;\n  IterateType iterateType = IterateType::PCG;\n  MatrixProperties property;\n  std::string empty, problem, geometry, functional;\n  \n  problem = getParameter(pt, \"problem\", empty);\n  refs = getParameter(pt, problem+\".refs\", 0),\n  order =  getParameter(pt, problem+\".order\", 1),\n  maxAdaptSteps = getParameter(pt, problem+\".maxAdaptSteps\", 10);\n  geometry = getParameter(pt, problem+\".geometry\", empty);\n  functional = getParameter(pt, problem+\".functional\", empty);\n  gebiet = getParameter(pt, \"names.geometry.\"+geometry, 1);\n  problemNo = getParameter(pt, \"names.functional.\"+functional, 1);\n  std::cerr << \"selected problem \" << problem << \", functional=\" <<\n  functional << \"(\" << problemNo <<  \"), geometry=\" <<\n  geometry << \"(\" << gebiet << \")\" << std::endl;\n  \n  std::string s(\"names.type.\");\n  s += getParameter(pt, \"solver.type\", empty);\n  std::cerr << \"s = \" << s << std::endl;\n  direct = getParameter(pt, s, 0);\n  std::cerr << \"s = \" << s << std::endl;\n  \n  s = \"names.direct.\" + getParameter(pt, \"solver.direct\", empty);\n  std::cerr << \"s = \" << s << std::endl;\n  directType = static_cast<DirectType>(getParameter(pt, s, 2));\n  std::cerr << \"s = \" << s << std::endl;\n  \n  s = \"names.iterate.\" + getParameter(pt, \"solver.iterate\", empty);\n  iterateType = static_cast<IterateType>(getParameter(pt, s, 0));\n  \n  property = MatrixProperties::POSITIVEDEFINITE;\n  \n  if (((property == MatrixProperties::SYMMETRIC)||(property == MatrixProperties::POSITIVEDEFINITE))&&\n    ((directType == DirectType::MUMPS)||(directType == DirectType::PARDISO)))\n  {\n    onlyLowerTriangle = true;\n  }\n  \n  int const dim2=2;\n  typedef Dune::UGGrid<dim2> Grid;\n  Dune::GridFactory<Grid> factory;\n  \n  switch (gebiet)\n  {\n    case 0:\n    {\n      createUnitSquare<Grid,dim2>(factory);\n    }\n    break;\n    case 1:\n    {\n      createUnitCrack<Grid,dim2>(factory);\n    }\n    break;\n    case 2:\n    {\n      createOriginalBoDD<Grid,dim2>(factory);\n    }\n    break;\n    case 3:\n    {\n      createAreaGrid<Grid,dim2>(factory);\n    }\n    break;\n    default:\n      std::cout << \"Unknown gebiet\" << std::endl;\n      exit(2);\n  }\n  \n  std::auto_ptr<Grid> grid( factory.createGrid() );\n  // the coarse grid will be refined refs times\n  grid->globalRefine(refs);\n  \n  // some information on the refined mesh\n  std::cout << \"Grid: \" << grid->size(0) << \" triangles, \" << std::endl;\n  std::cout << \"      \" << grid->size(1) << \" edges, \" << std::endl;\n  std::cout << \"      \" << grid->size(2) << \" points\" << std::endl;\n  \n  // a gridmanager is constructed \n  GridManager<Grid> gridManager(std::move(grid));    \n  \n  typedef Grid::LeafGridView LeafView;\n  // construction of finite element space for the scalar solution T\n  typedef FEFunctionSpace<ContinuousHierarchicMapper<double,LeafView> > H1Space;\n  \n  H1Space temperatureSpace(gridManager,gridManager.grid().leafGridView(),order);\n  typedef boost::fusion::vector<H1Space const*> Spaces;\n  Spaces spaces(&temperatureSpace);\n  // VariableDescription<int spaceId, int components, int Id>\n  // spaceId: number of associated FEFunctionSpace\n  // components: number of components in this variable\n  // Id: number of this variable\n  typedef boost::fusion::vector<VariableDescription<0,1,0> >\n  VariableDescriptions;\n  std::string varNames[1] = { \"T\" };\n  typedef VariableSetDescription<Spaces,VariableDescriptions> VariableSet;\n  VariableSet variableSet(spaces,varNames);\n  \n  typedef VariableSet::CoefficientVectorRepresentation<>::type CoefficientVector;\n  \n  // Define a higher order space for transfering the error estimate\n  H1Space temperatureSpace2(gridManager,gridManager.grid().leafView(),order+1);\n  \n  // Define the variational functional\n  typedef PoissonFunctional<double,VariableSet> Functional;\n  Functional F;\n  typedef VariationalFunctionalAssembler<LinearizationAt<Functional> > Assembler;\n  typedef Assembler::RhsArray Rhs;\n  Assembler assembler(gridManager,spaces);\n  \n  typedef FEFunctionSpace<ContinuousHierarchicExtensionMapper<double,LeafView> > H1ExSpace;\n  H1ExSpace spaceEx(gridManager,gridManager.grid().leafView(), order+1);\n  \n  typedef boost::fusion::vector<H1Space const*,H1ExSpace const*> H1ExSpaces;\n  H1ExSpaces exSpaces(&temperatureSpace,&spaceEx);\n  \n  typedef boost::fusion::vector<VariableDescription<1,1,0> > ExVariableDescriptions;\n  typedef VariableSetDescription<H1ExSpaces,ExVariableDescriptions> ExVariableSet;\n  std::string exVarNames[1] = { \"e\"};\n  ExVariableSet exVariableSet(exSpaces, exVarNames);\n  \n  typedef ExVariableSet::CoefficientVectorRepresentation<>::type ExCoefficientVector;\n  \n  typedef HierarchicErrorEstimator<LinearizationAt<Functional>,ExVariableSet> ErrorEstimator;\n  typedef VariationalFunctionalAssembler<ErrorEstimator> EstGOP;\n  \n  EstGOP estGop(gridManager,exSpaces);\n  \n  typedef VariableSet::Grid::Traits::LeafIndexSet IS ;\n  IS const& is = gridManager.grid().leafIndexSet();\n  \n  VariableSet::VariableSet x(variableSet), dx(variableSet);\n  \n  double const TOL = getParameter(pt, problem+\".TOL\", 1.0-2),\n  minRefine = getParameter(pt, problem+\".minRefine\", 0.0);\n  std::cerr << \"TOL = \" << TOL << \", minRefine = \" << minRefine << std::endl ;\n  assert(TOL>0);\n  \n  IoOptions options;\n  options.outputType = IoOptions::ascii;\n  \n  constexpr int neq = Functional::TestVars::noOfVariables;\n  constexpr int nvars = Functional::AnsatzVars::noOfVariables;\n  int refSteps = 0;\n  bool accurate = false;\n  int iteSteps = getParameter(pt, \"solver.iteMax\", 1000);\n  int verbose = getParameter(pt, \"solver.verbose\", 1);\n  double iteEps = getParameter(pt, \"solver.iteEps\", 1.0e-9);\n  int lookahead = getParameter(pt,\"solver.APCG.lookahead\",6);\n  double eefactor = getParameter(pt,\"ccg.eefactor\",0.0);\n  Dune::InverseOperatorResult result;\n  double errNorm = -1;\n  \n  size_t size = variableSet.degreesOfFreedom(0,1);\n  \n  double const gamma = iterateType==IterateType::APCG? 1.0: 0.5;   // Deuflhard/Weiser (7.60)\n  int const d = 2;                                    // two dimensional problem\n  assert(d*gamma>1);                                  // Deuflhard/Weiser Satz 7.36\n  double const beta = 1.0/sqrt(d*gamma);              // Deuflhard/Weiser (7.67)\n  double const alpha = (d*gamma-1.0)/(d*(1.0+gamma)); // Deuflhard/Weiser S. 303\n  double q = 2;                                       // Deuflhard/Weiser (7.62)\n  long N = size;\n  double zk = 0.0;\n  double const requested = sqrt(1-beta*beta)*TOL;     // Deuflhard/Weiser Algorithmus 7.37\n  double yk = pow(N,alpha);\n  double pcgerr = -1;\n  double pcgerr_fact = -1;\n  int required = 0;\n  \n  std::vector<VariableSet::VariableSet> solutions;\n\n  do {\n    // Zero coefficient vectors for initialization\n    ExCoefficientVector exZero(ExVariableSet::CoefficientVectorRepresentation<>::init(exVariableSet)); exZero = 0;\n    CoefficientVector zero(VariableSet::CoefficientVectorRepresentation<>::init(variableSet)); zero = 0;\n    \n    std::cerr << \"----------------------------------------\\nStarting round\\n\";\n    CoefficientVector solution(zero), hilfe(zero);\n    assembler.assemble(linearization(F,x));\n    Rhs rhs(assembler.rhs());\n    AssembledGalerkinOperator<Assembler,0,neq,0,nvars> A(assembler, onlyLowerTriangle);\n    \n    if (direct) \n      directInverseOperator(A,directType,property).applyscaleadd(-1.0,rhs,solution);\n    else  {\n      switch (iterateType) {\n\tcase IterateType::CG: {\n\t  JacobiPreconditioner<AssembledGalerkinOperator<Assembler,0,neq,0,nvars> > jacobi(A,1.0);\n\t  Dune::CGSolver<CoefficientVector> cg(A,jacobi,iteEps,iteSteps,verbose);\n\t  cg.apply(hilfe,rhs,result);\n\t  break;\n\t}\n\tcase IterateType::PCG: {\n\t  JacobiPreconditioner<AssembledGalerkinOperator<Assembler,0,neq,0,nvars> > jacobi(A,1.0);\n\t  NMIIIPCGSolver<CoefficientVector> pcg(A,jacobi,iteEps,iteSteps,verbose);\n\t  pcg.apply(hilfe,rhs,result);\n\t  break;\n\t}\n\tcase IterateType::APCG: {\n\t  JacobiPreconditioner<AssembledGalerkinOperator<Assembler,0,neq,0,nvars> > jacobiPCG(A,1.0);\n\t  DefaultDualPairing<CoefficientVector,CoefficientVector> dp;\n\t  PCGEnergyErrorTerminationCriterion<double> terminate(iteEps,iteSteps);\n\t  terminate.lookahead(lookahead);\n\t  Pcg<CoefficientVector,CoefficientVector> apcg(A,jacobiPCG,dp,terminate,verbose);\n\t  apcg.apply(hilfe,rhs,result);\n\t  pcgerr = terminate.error();\n\t  \n\t  CoefficientVector hilfe2(zero);\n\t  PCGEnergyErrorTerminationCriterion<double> terminate2(iteEps/1000,iteSteps);\n\t  Pcg<CoefficientVector,CoefficientVector> apcg2(A,jacobiPCG,dp,terminate2,verbose);\n          Dune::InverseOperatorResult result2;\n\t  apcg2.apply(hilfe2,rhs,result2);\n    std::ostringstream fn;\n    fn << \"cmg-gamma-\";\n    fn.width(3);\n    fn.fill('0');\n    fn.setf(std::ios_base::right,std::ios_base::adjustfield);\n    fn << refSteps;\n    fn.flush();\n    std::ofstream out(fn.str().c_str());\n    terminate.clear();\n    required = 0;\n    for (int i=0; i<terminate2.gamma2().size(); ++i) {\n      terminate.step(terminate2.gamma2()[i]);\n      out << terminate2.gamma2()[i] << ' ' << terminate.error() << ' ' << std::sqrt(std::accumulate(terminate2.gamma2().begin()+i,terminate2.gamma2().end(),0.0)) << '\\n';\n      if (std::sqrt(std::accumulate(terminate2.gamma2().begin()+i,terminate2.gamma2().end(),0.0)) >= iteEps)\n\trequired = i;\n    }    \n\t  \n\t  \n// \t  PCGEnergyErrorTerminationCriterion<double> terminate3(0.0,required+1);\n// \t  Pcg<CoefficientVector,CoefficientVector> apcg3(A,jacobiPCG,dp,terminate3,verbose);\n// \t  apcg3.apply(hilfe,rhs,result);\n// \t  pcgerr = terminate3.error();\n// \t  //pcgstep = std::sqrt(std::accumulate(terminate3.gamma2().begin(),terminate3.gamma2().end(),0.0));\n\t  \n\t  CoefficientVector dhilfe(hilfe2); dhilfe -= hilfe;\n\t  CoefficientVector Adhilfe(zero);\n\t  A.apply(dhilfe,Adhilfe);\n\t  pcgerr_fact = std::sqrt(dhilfe*Adhilfe);\n\t  \n\t  break;\n\t}\n// \tcase IterateType::SGS: {\n// \t  int addedIterations = 3;\n// \t  typedef Dune::BlockVector<Dune::FieldVector<double,1> > NakedCoefficientVector;\n// \t  Dune::SeqSSOR<MatrixAsTriplet<double>,NakedCoefficientVector,NakedCoefficientVector> sgs(A.getmat(),1,1.0);\n// \t  sgs.pre(boost::fusion::at_c<0>(hilfe.data),boost::fusion::at_c<0>(rhs.data));\n// \t  CoefficientVector y(zero), z(zero), r(rhs);\n// \t  boost::circular_buffer<double> gamma(addedIterations);\n// \t  for (int i=0; i<iteSteps; ++i) {\n// \t    sgs.apply(boost::fusion::at_c<0>(y.data),boost::fusion::at_c<0>(r.data));\n// \t    A.apply(y,z);\n// \t    r -= z;\n// \t    hilfe += y;\n// \t    result.iterations = i+1;\n// \t    gamma.push_back(std::sqrt(y*z));\n// \t    if (i>=addedIterations && std::accumulate(gamma.begin(),gamma.end(),0.0)<iteEps)\n// \t      break;\n// \t  }\n// \t  std::pair<double,double> geoest = estimateGeometricSequence(gamma.begin(),gamma.end());\n// \t  std::cerr << \"geometric estimate: c=\" << geoest.first << \" q=\" << geoest.second << \" delta=\" << iteEps << '\\n';\n// \t  std::copy(gamma.begin(),gamma.end(),std::ostream_iterator<double>(std::cerr,\" \")); std::cerr << '\\n';\n// \t  break;\n// \t}\n\tdefault:\n\t  std::cerr << \"Solver \" << iterateType << \" not available\" << std::endl;\n\t  throw -111;\n      }\n      solution.axpy(-1,hilfe);\n    }\n    dx.data = solution.data;\n    \n    \n    // Do hierarchical error estimation. Remember to provide the very same underlying problem to the\n    // error estimator functional as has been used to compute dx (do not modify x!).\n    {\n\n    \n    estGop.assemble(ErrorEstimator(LinearizationAt<Functional>(F,x),dx));\n      \n      // iterative solution of error estimator      \n      AssembledGalerkinOperator<EstGOP> E(estGop);\n      Dune::InverseOperatorResult estRes;\n      ExCoefficientVector const estRhside(estGop.rhs()) ;\n      ExCoefficientVector estSol(exZero) ;\n      JacobiPreconditioner<EstGOP> jprec(estGop, 1.0);\n      jprec.apply(estSol,estRhside); //single Jacobi iteration\n\n      // Represent error estimator as FE function\n      H1ExSpace::Element<1>::type erroresttmp(spaceEx);\n      erroresttmp = boost::fusion::at_c<0>(estSol.data);\n      H1Space::Element<1>::type errorest(temperatureSpace2);\n      errorest = erroresttmp;\n      \n      \n      // Transfer error indicators to cells.\n      std::vector<double> errorDistribution(is.size(0));\n      typedef VariableSet::GridView::Codim<0>::Iterator CellIterator ;\n      double maxErr = 0.0;\n      for (CellIterator ci=variableSet.gridView.begin<0>(); ci!=variableSet.gridView.end<0>(); ++ci) {\n\ttypedef H1ExSpace::Mapper::GlobalIndexRange GIR;\n\tdouble err = 0;\n\tGIR gix = spaceEx.mapper().globalIndices(*ci);\n\tfor (GIR::iterator j=gix.begin(); j!=gix.end(); ++j) \n\t  err += boost::fusion::at_c<0>(estSol.data)[*j] * boost::fusion::at_c<0>(estRhside.data)[*j]; // remember that what adds up here is positive (due to diagonal solve)\n\tassert(err>=0);\n\terrorDistribution[is.index(*ci)] = std::sqrt(err); // Deuflhard/Weiser (6.37)\n\tif (err>maxErr) maxErr = err;\n      }\n\n      // Select refinement threshold: Refine all elements which \n      // - have at least an error of half of the maximum error or\n      // - are among the minRefine fraction with largest error\n      double errLevel = maxErr/(order+1);\n      if (minRefine>0.0) {\n\tstd::vector<double> eSort(errorDistribution);\n\tstd::sort(eSort.begin(),eSort.end(),std::greater<double>()); // sort decreasingly\n\tint minRefineIndex = minRefine*(eSort.size()-1);\n\terrLevel = std::min(errLevel,eSort[minRefineIndex]+1.0e-14);\n      }\n\n      // Compute the error estimator norm according to Deuflhard/Weiser (6.36)\n      errNorm = 0;\n      for (int i=0; i<boost::fusion::at_c<0>(estSol.data).N(); ++i)\n\terrNorm += boost::fusion::at_c<0>(estSol.data)[i] * boost::fusion::at_c<0>(estRhside.data)[i]; // remember that what adds up here is positive (due to diagonal solve)\n      errNorm = std::sqrt(errNorm);\n      \n      // Termination check\n      if (errNorm<requested) {\n\taccurate = true;\n\t\n\tfor (int i=0; i<solutions.size()-1; ++i) {\n          solutions[i] -= solutions.back();\n\t  \n\t  CoefficientVector du(zero), Adu(zero);\n\t  boost::fusion::at_c<0>(du.data) = boost::fusion::at_c<0>(solutions[i].data).coefficients();\n\t  A.apply(du,Adu);\n\t  std::cerr << \"i= \" << i << \" err= \" << std::sqrt(du*Adu) << '\\n';\n\t}\n      } else {\n\t// Refine mesh.\n\tint count = 0;\n\tfor (CellIterator ci=variableSet.gridView.begin<0>(); ci!=variableSet.gridView.end<0>(); ++ci)\n\t  if (errorDistribution[is.index(*ci)] >= errLevel) {\n\t    gridManager.mark(1,*ci);\n\t    ++count;\n\t  }\n\taccurate = !gridManager.adaptAtOnce(); \n\t\n    \n    \n    std::ostringstream fn;\n    fn << \"graph/cmg-dx\";\n    fn.width(3);\n    fn.fill('0');\n    fn.setf(std::ios_base::right,std::ios_base::adjustfield);\n    fn << refSteps;\n    fn.flush();\n    writeVTKFile(gridManager.grid().leafView(),variableSet,dx,fn.str(),options,order);\n    \n      }\n    // apply the Newton correction here\n    x += dx;\n    \n    std::ostringstream fn;\n    fn << \"graph/cmg-sol\";\n    fn.width(3);\n    fn.fill('0');\n    fn.setf(std::ios_base::right,std::ios_base::adjustfield);\n    fn << refSteps;\n    fn.flush();\n    writeVTKFile(gridManager.grid().leafView(),variableSet,x,fn.str(),options,order);\n    // add coarse grid error estimator to fine grid prolongation\n    errorest *= eefactor;\n    boost::fusion::at_c<0>(x.data) -= errorest;\n    }\n    \n    // store solution for later checks\n    solutions.push_back(x);\n    \n    \n    std::cout << \"step= \" << refSteps << \" [err]= \" << errNorm << \" zk= \" << zk << \" q= \" << q << \" alpha= \" << alpha \n              << \" N= \" << N << \" yk= \" << yk << \" iter= \" << result.iterations << \" delta= \" << iteEps << \" pcgerr= \" << pcgerr << \" pcgerr_fact= \" << pcgerr_fact  \n              << \" required= \" << required << '\\n';\n    std::cout.flush();\n\n        refSteps++;\n\n\t\n    // Modify tolerances according to Deuflhard/Weiser Algorithmus 7.37\n    q = variableSet.degreesOfFreedom(0,1)/static_cast<double>(N); // DOF growth factor\n    N = variableSet.degreesOfFreedom(0,1);                        // new DOF\n    yk += pow(N,alpha);                                           // Deuflhard/Weiser S. 303\n    zk = pow(N,alpha)*(pow(errNorm/requested,d*alpha)-pow(q,alpha))/(pow(q,alpha)-1.0); // Deuflhard/Weiser S. 304\n    iteEps = beta*TOL*yk/(yk+zk);\n    \n    if (getParameter(pt, \"strategy\", 1) == 0)\n      iteEps = beta*TOL;\n    if (getParameter(pt, \"strategy\", 1) == 2)\n      iteEps = errNorm*std::pow(q,1.0/d);\n    \n    \n    \n    if (refSteps>maxAdaptSteps) {\n      std::cout << \"number of steps \" << refSteps << \" > maxAdaptSteps (\" << maxAdaptSteps << \")\\n\";\n      break;\n    }\n    \n    std::ostringstream fn;\n    fn << \"graph/cmg-grid\";\n    fn.width(3);\n    fn.fill('0');\n    fn.setf(std::ios_base::right,std::ios_base::adjustfield);\n    fn << refSteps-1;\n    fn.flush();\n    writeVTKFile(gridManager.grid().leafView(),variableSet,x,fn.str(),options,order);\n    \n  } while (!accurate);    \n  \n    \n\nstd::cout << \"End cmgtest\" << std::endl;\n}\n", "meta": {"hexsha": "64da06a7f9f25d0be5384e127e6ecd3b74d58865", "size": 19125, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Kaskade/tutorial/cmg/cmgtest.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/cmg/cmgtest.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:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-09T22:02:36.000Z", "max_forks_repo_path": "Kaskade/tutorial/cmg/cmgtest.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": 38.4808853119, "max_line_length": 170, "alphanum_fraction": 0.6391111111, "num_tokens": 5455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081925, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.4564380055776829}}
{"text": "//\n//  TDF SDK\n//\n//  Created by Sujan Reddy on 2020/04/20.\n//  Copyright 2020 Virtru Corporation\n//\n\n#define BOOST_TEST_MODULE test_ec_key_pair\n\n#include \"ec_key_pair.h\"\n#include \"crypto_utils.h\"\n#include \"bytes.h\"\n#include \"gcm_encryption.h\"\n#include \"gcm_decryption.h\"\n#include \"nanotdf/ecc_mode.h\"\n\n#include <iostream>\n\n#include <boost/test/included/unit_test.hpp>\n\nusing namespace virtru;\nusing namespace virtru::crypto;\n\nvoid testNanoTDFKeyMangement(const std::string& curveName, unsigned compressedPubKeySize) {\n    constexpr auto KIvSize = 3;\n    constexpr auto KAuthTagSize = 8;\n\n    const std::string kPlainText = \"Virtru!!\";\n\n    // -----------------------------------------------------------------\n    // (SDK-Side) Generate an EC key pair\n    // -----------------------------------------------------------------\n    auto sdkECKeyPair = ECKeyPair::Generate(curveName);\n    auto sdkPrivateKeyForEncrypt = sdkECKeyPair->PrivateKeyInPEMFormat();\n    auto sdkPublicKeyForEncrypt = sdkECKeyPair->PublicKeyInPEMFormat();\n\n    std::cout << \"SDK private key for encrypt: \" << sdkPrivateKeyForEncrypt <<'\\n';\n    std::cout << \"SDK public key for encrypt: \" << sdkPublicKeyForEncrypt <<'\\n';\n\n    // -----------------------------------------------------------------\n    // (KAS-Side) Generate an EC key pair\n    // -----------------------------------------------------------------\n    auto kasECKeyPair = ECKeyPair::Generate(curveName);\n    auto kasPrivateKey = kasECKeyPair->PrivateKeyInPEMFormat();\n    auto kasPublicKey = kasECKeyPair->PublicKeyInPEMFormat();\n\n    std::cout << \"kasPrivateKey: \" << kasPrivateKey <<'\\n';\n    std::cout << \"kasPublicKey: \" << kasPublicKey <<'\\n';\n\n    // -----------------------------------------------------------------\n    // (SDK-Side) Generate the shared secret using sdk private key, and kas public-key\n    //\n    // NOTE: The kas public-key will be in PEM format and we get this from\n    // entity object.\n    //  -----------------------------------------------------------------\n    std::vector<gsl::byte> wrappedKeyOnEncrypt;\n    wrappedKeyOnEncrypt = ECKeyPair::ComputeECDHKey(kasPublicKey, sdkPrivateKeyForEncrypt);\n    auto base64WrappedKeyOnEncrypt = base64Encode(toBytes(wrappedKeyOnEncrypt));\n    std::cout << \"Base64 wrapped key on Encrypt: \" << base64WrappedKeyOnEncrypt << std::endl;\n\n    // -----------------------------------------------------------------\n    // (SDK-Side) Encrypt the plain data with wrapped key(TDF blob)\n    // -----------------------------------------------------------------\n    auto TDFBlobSize = kPlainText.size() + KIvSize + KAuthTagSize;\n    std::vector<gsl::byte> TDFBlob(TDFBlobSize);\n    {\n        auto encryptedData = toWriteableBytes(TDFBlob);\n\n        ByteArray<KAuthTagSize> tag;\n        ByteArray<KIvSize> iv = symmetricKey<KIvSize>();\n        const auto bufferSpan = encryptedData;\n\n        auto encryptedDataSize = 0;\n        const auto final = finalizeSize(encryptedData, encryptedDataSize);\n\n        // Adjust the span to add the IV vector at the start of the buffer\n        auto encryptBufferSpan = bufferSpan.subspan(KIvSize);\n\n        auto encoder = GCMEncryption::create(toBytes(wrappedKeyOnEncrypt), iv);\n        encoder->encrypt(toBytes(kPlainText), encryptBufferSpan);\n\n        auto authTag = WriteableBytes{tag};\n        encoder->finish(authTag);\n\n        // Copy IV at start\n        std::copy(iv.begin(), iv.end(), encryptedData.begin());\n\n        // Copy tag at end\n        std::copy(tag.begin(), tag.end(), encryptedData.begin() + KIvSize + kPlainText.size());\n\n        // Final size.\n        encryptedDataSize = TDFBlobSize;\n\n        auto base64TDFBlob = base64Encode(encryptedData);\n        std::cout << \"Base64 of TDFBlob of data: \" << base64TDFBlob << std::endl;\n    }\n\n    // -----------------------------------------------------------------\n    // (SDK-Side) Store SDK public key as (33 Bytes, compressed ) in nanoTDF for 256-bit curve\n    // -----------------------------------------------------------------\n    std::vector<gsl::byte> compressedPubKey = ECKeyPair::CompressedECPublicKey(sdkPublicKeyForEncrypt);\n    std::cout << \"Compressed public key size: \" << compressedPubKey.size() << std::endl;\n    BOOST_TEST(compressedPubKey.size() == compressedPubKeySize,  \"Checking the compressed public key size\");\n\n    auto pemPub = ECKeyPair::GetPEMPublicKeyFromECPoint(toBytes(compressedPubKey), curveName);\n    BOOST_TEST(pemPub == sdkPublicKeyForEncrypt,  \"Checking the sdk public is same after compression\");\n\n    ///******************************** ENCRYPTION COMPLETED ON SDK *******************************///\n\n    // SDK side key-pair for rewrap\n    sdkECKeyPair = ECKeyPair::Generate(curveName);\n    auto sdkPrivateKeyForDecrypt = sdkECKeyPair->PrivateKeyInPEMFormat();\n    auto sdkPublicKeyForDecrypt = sdkECKeyPair->PublicKeyInPEMFormat();\n\n    // -----------------------------------------------------------------\n    // (KAS-Side) Rewrap\n    //\n    // SDK ---> 'sdkPublicKeyForDecrypt' and 'compressed 33 bytes key from TDF' ---> KAS\n    //\n    // -----------------------------------------------------------------\n\n    // -----------------------------------------------------------------\n    // (KAS-Side) KAS computing the symmetric key.\n    // -----------------------------------------------------------------\n    std::vector<gsl::byte> symmetricKeyOnKas;\n    symmetricKeyOnKas = ECKeyPair::ComputeECDHKey(sdkPublicKeyForEncrypt, kasPrivateKey);\n    auto base64SymmetricKeyOnKas = base64Encode(toBytes(symmetricKeyOnKas));\n    std::cout << \"Base64 symmetric key on KAS: \" << base64SymmetricKeyOnKas << std::endl;\n    BOOST_TEST(base64SymmetricKeyOnKas == base64WrappedKeyOnEncrypt,  \"symmetric key is same on SDK and KAS\");\n\n    kasECKeyPair = ECKeyPair::Generate(curveName);\n    auto kasRewrapEphemeralPrivateKey = kasECKeyPair->PrivateKeyInPEMFormat();\n    auto kasRewrapEphemeralPublicKey = kasECKeyPair->PublicKeyInPEMFormat();\n\n    // Generate a session key on KAS\n    auto sessionKeyOnKAS = ECKeyPair::ComputeECDHKey(sdkPublicKeyForDecrypt, kasRewrapEphemeralPrivateKey);\n    auto base64SessionKeyOnKAS = base64Encode(toBytes(sessionKeyOnKAS));\n    std::cout << \"Base64 session key on KAS: \" << base64SessionKeyOnKAS << std::endl;\n\n    // Encrypt symmetricKeyOnKas with sessionKey on Kas -> payload KEK\n    auto payloadKeKBufferSize = symmetricKeyOnKas.size() + KIvSize + KAuthTagSize;\n    std::vector<gsl::byte> payloadKeK(payloadKeKBufferSize);\n    {\n        auto encryptedData = toWriteableBytes(payloadKeK);\n\n        ByteArray<KAuthTagSize> tagForKek;\n        ByteArray<KIvSize> iv = symmetricKey<KIvSize>();\n        const auto bufferSpan = encryptedData;\n\n        auto encryptedDataSize = 0;\n        const auto final = finalizeSize(encryptedData, encryptedDataSize);\n\n        // Adjust the span to add the IV vector at the start of the buffer\n        auto encryptBufferSpan = bufferSpan.subspan(KIvSize);\n\n        auto encoder = GCMEncryption::create(toBytes(sessionKeyOnKAS), iv);\n        encoder->encrypt(toBytes(symmetricKeyOnKas), encryptBufferSpan);\n        auto authTag = WriteableBytes{tagForKek};\n        encoder->finish(authTag);\n\n        // Copy IV at start\n        std::copy(iv.begin(), iv.end(), encryptedData.begin());\n\n        // Copy tag at end\n        std::copy(tagForKek.begin(), tagForKek.end(), encryptedData.begin() + KIvSize + symmetricKeyOnKas.size());\n\n        // Final size.\n        encryptedDataSize = payloadKeKBufferSize;\n\n        auto base64PayLoadKek = base64Encode(encryptedData);\n        std::cout << \"Base64 of payloadKEK: \" << base64PayLoadKek << std::endl;\n    }\n\n    // -----------------------------------------------------------------\n    // (SDK-Side) Rewrap\n    //\n    // KAS ---> 'payload KEK' and 'RewrapEphemeralPublic' ---> SDK\n    //\n    // -----------------------------------------------------------------\n\n    // Generate a session key on SDK.\n    auto sessionKeyOnSDK = ECKeyPair::ComputeECDHKey(kasRewrapEphemeralPublicKey, sdkPrivateKeyForDecrypt);\n    auto base64SessionKeyOnSDK = base64Encode(toBytes(sessionKeyOnSDK));\n    std::cout << \"Base64 session key on SDK: \" << base64SessionKeyOnSDK << std::endl;\n    BOOST_TEST(base64SessionKeyOnKAS == base64SessionKeyOnSDK,  \"session key should be same on SDK and KAS\");\n\n    // ON SDK - Decrypt 'payload KEK' with sessionKey to get a symmetricKey to decrypt.\n    std::vector<gsl::byte> wrappedKeyOnRewrap;\n    wrappedKeyOnRewrap.resize(payloadKeK.size() - KIvSize - KAuthTagSize);\n    {\n        // payloadKeK is data\n        auto data = toBytes(payloadKeK);\n\n        // Copy the auth tag from the data buffer.\n        ByteArray<KAuthTagSize> tag;\n        std::copy_n(data.last(KAuthTagSize).data(), KAuthTagSize, begin(tag));\n\n        // Update the input buffer size after the auth tag is copied.\n        auto inputSpan = data.first(data.size() - KAuthTagSize);\n        auto decoder = GCMDecryption::create(toBytes(sessionKeyOnSDK), inputSpan.first(KIvSize));\n\n        // Update the input buffer size after the IV is copied.\n        inputSpan = inputSpan.subspan(KIvSize);\n\n        // decrypt\n        auto decryptedData = toWriteableBytes(wrappedKeyOnRewrap);\n        decoder->decrypt(inputSpan, decryptedData);\n\n        auto authTag = WriteableBytes{tag};\n        decoder->finish(authTag);\n    }\n\n    auto base64wrappedKeyOnRewrap = base64Encode(toBytes(wrappedKeyOnRewrap));\n    std::cout << \"Base64 symmetric key on KAS: \" << base64wrappedKeyOnRewrap << std::endl;\n    BOOST_TEST(base64WrappedKeyOnEncrypt == base64wrappedKeyOnRewrap,  \"symmetric key is same on encrypt and decrypt\");\n\n    // -----------------------------------------------------------------\n    // (SDK-Side) TDFBlob decrypt to get a plain text.\n    // -----------------------------------------------------------------\n    std::vector<gsl::byte> TDFBlobDecrypt;\n    TDFBlobDecrypt.resize(kPlainText.size());\n    {\n        // TDFBlob is data to be decrypt\n        auto data = toBytes(TDFBlob);\n\n        // Copy the auth tag from the data buffer.\n        ByteArray<KAuthTagSize> tag;\n        std::copy_n(data.last(KAuthTagSize).data(), KAuthTagSize, begin(tag));\n\n        // Update the input buffer size after the auth tag is copied.\n        auto inputSpan = data.first(data.size() - KAuthTagSize);\n        auto decoder = GCMDecryption::create(toBytes(wrappedKeyOnRewrap), inputSpan.first(KIvSize));\n\n        // Update the input buffer size after the IV is copied.\n        inputSpan = inputSpan.subspan(KIvSize);\n\n        // decrypt\n        auto decryptedData = toWriteableBytes(TDFBlobDecrypt);\n        decoder->decrypt(inputSpan, decryptedData);\n\n        auto authTag = WriteableBytes{tag};\n        decoder->finish(authTag);\n    }\n    std::string decryptedTDF(reinterpret_cast<const char *>(&TDFBlobDecrypt[0]), TDFBlobDecrypt.size());\n    BOOST_TEST(kPlainText == decryptedTDF,  \"TDF data decrypted successfully.\");\n\n}\n\nBOOST_AUTO_TEST_SUITE(test_ec_key_pair_suite)\n\n    BOOST_AUTO_TEST_CASE(ec_key_pair_curve_secp521r1)\n    {\n        const std::string curveName = \"secp521r1\";\n        auto eckeyPair = ECKeyPair::Generate(curveName);\n        auto privateKey = eckeyPair->PrivateKeyInPEMFormat();\n        auto publicKey = eckeyPair->PublicKeyInPEMFormat();\n\n        std::cout << \"Private key: \" << privateKey <<'\\n';\n        std::cout << \"Public key: \" << publicKey <<'\\n';\n\n        unsigned int secp521KeySize = 521;\n        BOOST_TEST(eckeyPair->KeySize() == secp521KeySize, \"Checking EC key length - key size 521 bits\");\n        BOOST_TEST(eckeyPair->CurveName() == curveName,  \"Checking the curve name - secp521r1\");\n    }\n\n    BOOST_AUTO_TEST_CASE(ec_key_pair_test_nano_tdf_crypto)\n    {\n        using namespace virtru::nanotdf;\n\n        testNanoTDFKeyMangement(ECCMode::GetEllipticCurveName(EllipticCurve::SECP256R1),\n                                ECCMode::GetECCompressedPubKeySize(EllipticCurve::SECP256R1));\n\n        testNanoTDFKeyMangement(ECCMode::GetEllipticCurveName(EllipticCurve::SECP384R1),\n                                ECCMode::GetECCompressedPubKeySize(EllipticCurve::SECP384R1));\n\n        testNanoTDFKeyMangement(ECCMode::GetEllipticCurveName(EllipticCurve::SECP521R1),\n                                ECCMode::GetECCompressedPubKeySize(EllipticCurve::SECP521R1));\n    }\n\n    BOOST_AUTO_TEST_CASE(test_ECDSA_signature_and_verify_with_only_private_key)\n    {\n        using namespace virtru::nanotdf;\n\n        const std::string kPlainText = \"Virtru!!\";\n        auto digest = calculateSHA256(toBytes(kPlainText));\n\n        std::string supportedCurve[] = {\n                ECCMode::GetEllipticCurveName(EllipticCurve::SECP256R1),\n                ECCMode::GetEllipticCurveName(EllipticCurve::SECP384R1),\n                ECCMode::GetEllipticCurveName(EllipticCurve::SECP521R1)};\n\n        for (const auto& curveName: supportedCurve) {\n\n            auto signerECKeyPair = ECKeyPair::Generate(curveName);\n            auto signerPrivateKey = signerECKeyPair->PrivateKeyInPEMFormat();\n\n            // Generate public key from private key\n            auto publicKey = ECKeyPair::GetPEMPublicKeyFromPrivateKey(signerPrivateKey, curveName);\n\n            // Calculate signature with signer private key\n            auto signature =  ECKeyPair::ComputeECDSASig(toBytes(digest), signerPrivateKey);\n\n            bool result = ECKeyPair::VerifyECDSASignature(toBytes(digest), toBytes(signature), publicKey);\n            BOOST_TEST(result);\n        }\n    }\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "e9b14c9cb8f48e41adf07eb793a1356945d12e8b", "size": 13490, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tests/test_ec_key_pair.cpp", "max_stars_repo_name": "opentdf/client-cpp", "max_stars_repo_head_hexsha": "9c6dbc73a989733e30371555aa7a24ff496a62f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/tests/test_ec_key_pair.cpp", "max_issues_repo_name": "opentdf/client-cpp", "max_issues_repo_head_hexsha": "9c6dbc73a989733e30371555aa7a24ff496a62f1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2022-01-31T14:42:51.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T22:44:54.000Z", "max_forks_repo_path": "src/tests/test_ec_key_pair.cpp", "max_forks_repo_name": "opentdf/client-cpp", "max_forks_repo_head_hexsha": "9c6dbc73a989733e30371555aa7a24ff496a62f1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-09T18:40:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-09T18:40:47.000Z", "avg_line_length": 43.7987012987, "max_line_length": 119, "alphanum_fraction": 0.6206819867, "num_tokens": 3229, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.4564198134397763}}
{"text": "// Copyright (c) 2011-2014 The Bitcoin Core developers\n// Distributed under the MIT/X11 software license, see the accompanying\n// file COPYING or http://www.opensource.org/licenses/mit-license.php.\n\n#include \"main.h\"\n#include \"miner.h\"\n#include \"uint256.h\"\n#include \"util.h\"\n\n#include <boost/test/unit_test.hpp>\n// miners obey an exponential distribution\n#include <boost/random/exponential_distribution.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/function.hpp>\n\nstatic boost::mt19937 prng;\n\nint VersionForAlgo(int algo)\n{\n    switch (algo)\n    {\n        case ALGO_SCRYPT:\n            return BLOCK_VERSION_DEFAULT;\n        case ALGO_SHA256D:\n            return BLOCK_VERSION_DEFAULT | BLOCK_VERSION_SHA256D;\n        case ALGO_GROESTL:\n            return BLOCK_VERSION_DEFAULT | BLOCK_VERSION_GROESTL;\n        case ALGO_SKEIN:\n            return BLOCK_VERSION_DEFAULT | BLOCK_VERSION_SKEIN;\n        case ALGO_QUBIT:\n            return BLOCK_VERSION_DEFAULT | BLOCK_VERSION_QUBIT;\n    }\n    assert(false);\n    return 0;\n}\n\ndouble BitsToDifficulty(int nBits)\n{\n    CBigNum target;\n    target.SetCompact(nBits);\n    // approximate\n    return pow(2, 256-32)/target.getuint256().getdouble();\n}\n\nvoid SimulateNextBlock(CBlockIndex*& tip, double* hashRates)\n{\n    double recTime = 1e9;\n    CBlockIndex* newTip = new CBlockIndex;\n    newTip->pprev = tip;\n    newTip->nHeight = tip->nHeight+1;\n    for (int i=0; i<NUM_ALGOS; i++)\n    {\n        if (hashRates[i] == 0) continue;\n        CBigNum target;\n        unsigned int nBits = GetNextWorkRequired(tip, NULL, i, false);\n        target.SetCompact(nBits);\n        double dtarget = target.getuint256().getdouble()/pow(2,256);\n        double mean = 1/(hashRates[i]*dtarget);\n        boost::exponential_distribution<double> distr(1/mean);\n        double received = distr(prng);\n        if (received < recTime)\n        {\n            recTime = received;\n            newTip->nVersion = VersionForAlgo(i);\n            newTip->nTime = tip->nTime + received;\n            newTip->nBits=nBits;\n        }\n    }\n    assert(recTime < 1e9);\n    tip = newTip;\n    return;\n}\n\nvoid SimulationSetup(CBlockIndex*& tip, double* hashRates, int height)\n{\n    assert(tip==NULL);\n    // give it a perfect setup\n    for(int h=0, c=20*NUM_ALGOS-1; h<20; h++)\n    for(int i=0; i<NUM_ALGOS; i++, c--)\n    {\n        CBlockIndex* newTip = new CBlockIndex;\n        newTip->pprev = tip;\n        newTip->nHeight = height - c;\n        newTip->nTime = newTip->nHeight * 30;\n        newTip->nVersion = VersionForAlgo(i);\n        double dtarget = pow(2, 256)/hashRates[i] / 150;\n        // no base_uint::setdouble()? no problem\n        uint256 target;\n        for(int b=255; b>=0; b--)\n        {\n            uint256 newTarget = target + (uint256(1)<<b);\n            if (newTarget.getdouble() < dtarget)\n                target = newTarget;\n        }\n        newTip->nBits = CBigNum(target).GetCompact();\n        tip = newTip;\n    }\n}\n\ndouble ConstantRate(const CBlockIndex* pBlock)\n{\n    return pow(2,32);\n}\n\ndouble MultipoolRate(const CBlockIndex* pBlock)\n{\n    if (!pBlock || pBlock->nHeight < 400500)\n        return pow(2,32);\n    if (pBlock->nHeight < 401000)\n        return 10*pow(2,32);\n    return pow(2,32);\n}\n\nvoid RunSimulation(boost::function<double(const CBlockIndex*)>* hashRate, int startHeight, int iterations)\n{\n    CBlockIndex* tip = NULL;\n    double rate[5];\n    for(int i=0; i<5; i++)\n        rate[i]=hashRate[i](tip);\n    SimulationSetup(tip, rate, startHeight);\n    printf(\"begin simulation:\\n\");\n    for(int it=0; it<iterations; it++)\n    {\n        for(int i=0; i<5; i++)\n            rate[i]=hashRate[i](tip);\n        SimulateNextBlock(tip, rate);\n\n        double diffsum=0;\n        for(int i=0; i<5; i++)\n            diffsum+=BitsToDifficulty(GetNextWorkRequired(tip, NULL, i, false));\n        \n        printf(\"height %d algo %7s time %3d diff %8.3f, avg next diff %7.3f\\n\", \n            tip->nHeight,\n            GetAlgoName(GetAlgo(tip->nVersion)).c_str(), \n            tip->nTime - tip->pprev->nTime, \n            BitsToDifficulty(tip->nBits), diffsum/5);\n    }\n}\n\nBOOST_AUTO_TEST_SUITE(difficulty_simulation)\n\n// constant hashrate test\nBOOST_AUTO_TEST_CASE(constant_rate)\n{\n    boost::function<double(const CBlockIndex*)> hashRate[5] = {\n        ConstantRate,\n        ConstantRate,\n        ConstantRate,\n        ConstantRate,\n        ConstantRate,\n    };\n    RunSimulation(hashRate, 400000, 1000);\n}\n\n// a multipool hops on sha at block 500, then off at block 1000\nBOOST_AUTO_TEST_CASE(multipool)\n{\n    boost::function<double(const CBlockIndex*)> hashRate[5] = {\n        MultipoolRate,\n        ConstantRate,\n        ConstantRate,\n        ConstantRate,\n        ConstantRate,\n    };\n    RunSimulation(hashRate, 400000, 1500);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "3beabb091375e7d4f423a9d65f11ec5034be3e0f", "size": 4803, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/difficulty_simulation.cpp", "max_stars_repo_name": "csnbitcoin/digibyte", "max_stars_repo_head_hexsha": "f680d1aae8e70194000987031824b79d5189ce1f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-12-22T16:13:17.000Z", "max_stars_repo_stars_event_max_datetime": "2017-12-22T16:13:17.000Z", "max_issues_repo_path": "src/test/difficulty_simulation.cpp", "max_issues_repo_name": "csnbitcoin/digibyte", "max_issues_repo_head_hexsha": "f680d1aae8e70194000987031824b79d5189ce1f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/test/difficulty_simulation.cpp", "max_forks_repo_name": "csnbitcoin/digibyte", "max_forks_repo_head_hexsha": "f680d1aae8e70194000987031824b79d5189ce1f", "max_forks_repo_licenses": ["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.4201183432, "max_line_length": 106, "alphanum_fraction": 0.6221111805, "num_tokens": 1312, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825007, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.45637475219364876}}
{"text": "//\n// OpenTissue, A toolbox for physical based simulation and animation.\n// Copyright (C) 2007 Department of Computer Science, University of Copenhagen\n//\n#include <OpenTissue/configuration.h>\n\n#include <OpenTissue/core/math/big/big_types.h>\n#include <OpenTissue/core/math/big/big_generate_PD.h>\n#include <OpenTissue/core/math/big/big_generate_PSD.h>\n#include <OpenTissue/core/math/big/big_generate_random.h>\n#include <OpenTissue/core/math/optimization/optimization_non_smooth_newton.h>\n#include <OpenTissue/core/math/big/big_gmres.h>\n#include <OpenTissue/core/math/big/big_svd.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <OpenTissue/utility/utility_push_boost_filter.h>\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n#include <OpenTissue/utility/utility_pop_boost_filter.h>\n\n\ntemplate <typename vector_type>\nclass BoundFunction\n  {\n  public:\n    \n    typedef typename vector_type::size_type          size_type;\n    typedef typename vector_type::value_type         real_type;\n    typedef OpenTissue::math::ValueTraits<real_type> value_traits;\n    \n    \n    bool m_is_lower;\n    \n  public:\n    \n    BoundFunction(bool const & is_lower)\n    : m_is_lower(is_lower)\n    {}\n    \n    real_type operator()(vector_type const & x, size_type const & i) const\n    {\n      size_type r = (i%3);\n      \n      if(r==0)\n        return m_is_lower ? value_traits::zero() : value_traits::infinity();\n      \n      real_type mu_i = value_traits::one();\n      size_type j = i - r;\n      return m_is_lower ?  -mu_i*x(j) : mu_i*x(j);\n    }\n    \n    class vector_iterator\n    {\n    protected:\n      \n      bool m_end;\n      size_type m_idx;\n      real_type m_mu;\n      \n    public:\n      \n      vector_iterator()\n      : m_end(true)\n      , m_idx(0)\n      , m_mu(value_traits::zero())\n      {}\n      \n      vector_iterator(vector_iterator const & i)\n      {\n        *this = i;\n      }\n      \n      vector_iterator(size_type const & idx, real_type const & mu)\n      : m_end(false)\n      , m_idx(idx)\n      , m_mu(mu)\n      {}\n      \n      bool const operator==(vector_iterator const & i) const     {      return this->m_end == i.m_end;     }\n      bool const operator!=(vector_iterator const & i) const {  return !( (*this) == i); }\n      \n      size_t const index() const { return m_idx; }\n      \n      real_type operator*() const { return m_mu; }\n      \n      vector_iterator & operator=(vector_iterator const & i) \n      {\n        this->m_end = i.m_end;\n        this->m_idx = i.m_idx;\n        this->m_mu = i.m_mu;\n        return *this;\n      }\n      \n      \n      vector_iterator const & operator++() \n      {\n        m_end = true;\n        return *this; \n      }\n    };\n    \n    \n    vector_iterator partial_begin(size_type const & idx) const \n    {\n      size_type r = (idx%3);\n      \n      if(r==0)\n        return vector_iterator();\n      \n      real_type mu_i = value_traits::one();\n      size_type j = idx - r;\n      return m_is_lower ? vector_iterator(j,-mu_i) :  vector_iterator(j, mu_i);\n    }\n    \n    vector_iterator partial_end(size_type const & idx) const {  return vector_iterator(); }\n    \n  };\n\n\n\ntemplate<typename matrix_type,typename vector_type>\nvoid test(matrix_type const & A, vector_type  & x, vector_type const & b, vector_type const & y, size_t * cnt_status)\n{\n  typedef typename matrix_type::value_type real_type;\n  typedef typename matrix_type::size_type  size_type;\n  \n  BoundFunction<vector_type> l(true);\n  BoundFunction<vector_type> u(false);\n  \n  size_type max_iterations       = 100;\n  real_type absolute_tolerance   = boost::numeric_cast<real_type>(1e-6);\n  real_type relative_tolerance   = boost::numeric_cast<real_type>(0.000000001);\n  real_type stagnation_tolerance = boost::numeric_cast<real_type>(0.000000001);\n  size_t status = 0;\n  size_type iteration = 0;\n  real_type accuracy = boost::numeric_cast<real_type>(0.0);\n  real_type alpha = boost::numeric_cast<real_type>(0.0001);\n  real_type beta = boost::numeric_cast<real_type>(0.5);\n  bool use_shur = true;\n  \n\n  OpenTissue::math::optimization::non_smooth_newton( \n                                                    A, b, l , u, x \n                                                    , max_iterations\n                                                    , absolute_tolerance\n                                                    , relative_tolerance\n                                                    , stagnation_tolerance\n                                                    , status\n                                                    , iteration\n                                                    , accuracy\n                                                    , alpha\n                                                    , beta\n                                                    , &OpenTissue::math::big::svd<matrix_type, vector_type>\n                                                    , use_shur\n                                                    );\n  \n  cnt_status[status]++;\n  \n  if(status==OpenTissue::math::optimization::ABSOLUTE_CONVERGENCE)\n  {\n    BOOST_CHECK( accuracy < absolute_tolerance );\n    BOOST_CHECK( iteration <= max_iterations );\n  }\n  std::cout << \"absolute \" << accuracy << \" iterations \" << iteration  << \" status \" << OpenTissue::math::optimization::get_error_message(status) << std::endl;\n}\n\nBOOST_AUTO_TEST_SUITE(opentissue_math_big_non_smooth_newton);\n\nBOOST_AUTO_TEST_CASE(random_test_case)\n{\n  \n  typedef ublas::compressed_matrix<double> matrix_type;\n  typedef ublas::vector<double>            vector_type;\n  typedef vector_type::size_type           size_type;\n  \n  size_t cnt_status[7] = {0, 0, 0, 0, 0, 0, 0};\n  \n  size_type N = 10;\n  \n  matrix_type A;\n  vector_type x;\n  vector_type b;\n  vector_type y;\n  \n  A.resize(N,N,false);\n  x.resize(N,false);\n  b.resize(N,false);\n  y.resize(N,false);\n  \n  for(size_type tst=0;tst<100;++tst)\n  {\n    OpenTissue::math::big::fast_generate_PD(N,A);\n    OpenTissue::math::big::generate_random( N, y);\n    b.assign(-y);\n    OpenTissue::math::big::generate_random( N, y);\n    x.clear();\n    \n    test(A,x,b,y, &cnt_status[0]);\n  }\n  \n  for(size_t i=0;i<7;++i)\n    std::cout << cnt_status[i] << \"\\t:\\t\"<< OpenTissue::math::optimization::get_error_message( i ) << std::endl;\n  std::cout << std::endl;\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "636a69f61fb56f2f5d728fbb93c9862668d0ad49", "size": 6390, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/core/math/optimization/non_smooth_newton/src/unit_non_smooth_newton.cpp", "max_stars_repo_name": "ricortiz/OpenTissue", "max_stars_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 76.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:45:06.000Z", "max_issues_repo_path": "unit_tests/core/math/optimization/non_smooth_newton/src/unit_non_smooth_newton.cpp", "max_issues_repo_name": "ricortiz/OpenTissue", "max_issues_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2018-11-20T14:32:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T15:26:45.000Z", "max_forks_repo_path": "unit_tests/core/math/optimization/non_smooth_newton/src/unit_non_smooth_newton.cpp", "max_forks_repo_name": "ricortiz/OpenTissue", "max_forks_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2018-02-21T01:45:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T07:06:49.000Z", "avg_line_length": 30.5741626794, "max_line_length": 159, "alphanum_fraction": 0.5863849765, "num_tokens": 1500, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825006, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4563747521936487}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_EULER_FUNCTIONS_SIMD_COMMON_ERFC_HPP_INCLUDED\n#define NT2_EULER_FUNCTIONS_SIMD_COMMON_ERFC_HPP_INCLUDED\n\n#include <nt2/euler/functions/erfc.hpp>\n#include <nt2/euler/functions/details/erf_kernel.hpp>\n#include <nt2/include/constants/two.hpp>\n#include <nt2/include/constants/twothird.hpp>\n#include <nt2/include/constants/zero.hpp>\n#include <nt2/include/functions/simd/abs.hpp>\n#include <nt2/include/functions/simd/divides.hpp>\n#include <nt2/include/functions/simd/exp.hpp>\n#include <nt2/include/functions/simd/if_else.hpp>\n#include <nt2/include/functions/simd/inbtrue.hpp>\n#include <nt2/include/functions/simd/is_less.hpp>\n#include <nt2/include/functions/simd/is_ltz.hpp>\n#include <nt2/include/functions/simd/logical_andnot.hpp>\n#include <nt2/include/functions/simd/minus.hpp>\n#include <nt2/include/functions/simd/multiplies.hpp>\n#include <nt2/include/functions/simd/oneminus.hpp>\n#include <nt2/include/functions/simd/oneplus.hpp>\n#include <nt2/include/functions/simd/plus.hpp>\n#include <nt2/include/functions/simd/splat.hpp>\n#include <nt2/include/functions/simd/sqr.hpp>\n#include <nt2/include/functions/simd/unary_minus.hpp>\n#include <nt2/sdk/meta/as_logical.hpp>\n#include <nt2/sdk/meta/cardinal_of.hpp>\n\n#include <boost/simd/sdk/config.hpp>\n\n#ifndef BOOST_SIMD_NO_INFINITIES\n#include <nt2/include/constants/inf.hpp>\n#include <nt2/include/functions/simd/if_zero_else.hpp>\n#include <nt2/include/functions/simd/is_equal.hpp>\n#endif\n\nnamespace nt2 { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT  ( erfc_, tag::cpu_\n                              , (A0)(X)\n                              , ((simd_<double_<A0>,X>))\n                              )\n  {\n    typedef A0 result_type;\n    NT2_FUNCTOR_CALL(1)\n    {\n      typedef typename meta::as_logical<A0>::type bA0;\n\n      A0 x =  nt2::abs(a0);\n      A0 xx =  nt2::sqr(x);\n      A0 lim1 = nt2::splat<A0>(0.65);\n      A0 lim2 = nt2::splat<A0>(2.2);\n      bA0 test0 = nt2::is_ltz(a0);\n      bA0 test1 = nt2::lt(x, lim1);\n      A0 r1 = nt2::Zero<A0>();\n      std::size_t nb = nt2::inbtrue(test1);\n      if(nb > 0)\n      {\n        r1 = nt2::oneminus(x*details::erf_kernel<A0>::erf1(xx));\n        if (nb >= meta::cardinal_of<A0>::value)\n          return nt2::if_else(test0, nt2::Two<A0>()-r1, r1);\n      }\n      bA0 test2 = nt2::lt(x, lim2);\n      bA0 test3 = nt2::logical_andnot(test2, test1);\n      A0 ex = nt2::exp(-xx);\n\n      std::size_t nb1 = nt2::inbtrue(test3);\n      if(nb1 > 0)\n      {\n        A0 z = ex*details::erf_kernel<A0>::erfc2(x);\n        r1 = nt2::if_else(test1, r1, z);\n        nb += nb1;\n        if (nb >= meta::cardinal_of<A0>::value)\n          return nt2::if_else(test0, Two<A0>()-r1, r1);\n      }\n      A0 z =  ex*details::erf_kernel<A0>::erfc3(x);\n      r1 = nt2::if_else(test2, r1, z);\n      #ifndef BOOST_SIMD_NO_INFINITIES\n      r1 = if_zero_else( eq(x, Inf<A0>()), r1);\n      #endif\n      return  nt2::if_else(test0, nt2::Two<A0>()-r1, r1);\n      }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  ( erfc_, tag::cpu_\n                              , (A0)(X)\n                              , ((simd_<single_<A0>,X>))\n                              )\n  {\n    typedef A0 result_type;\n    NT2_FUNCTOR_CALL(1)\n    {\n      typedef typename meta::as_logical<A0>::type bA0;\n\n      A0 x =  nt2::abs(a0);\n      bA0 test0 = nt2::is_ltz(a0);\n      A0 r1 = nt2::Zero<A0>();\n      bA0 test1 = nt2::lt(x, Twothird<A0>());\n      A0 z = x/oneplus(x);\n\n      std::size_t nb = nt2::inbtrue(test1);\n      if(nb > 0)\n      {\n        r1 = details::erf_kernel<A0>::erfc3(z);\n        if (nb >= meta::cardinal_of<A0>::value)\n          return nt2::if_else(test0, nt2::Two<A0>()-r1, r1);\n      }\n      z -= nt2::splat<A0>(0.4);\n      A0 r2 = exp(-sqr(x))*details::erf_kernel<A0>::erfc2(z);\n      r1 = if_else(test1, r1, r2);\n      #ifndef BOOST_SIMD_NO_INFINITIES\n      r1 = if_zero_else( eq(x, Inf<A0>()), r1);\n      #endif\n      return nt2::if_else(test0, nt2::Two<A0>()-r1, r1);\n    }\n  };\n} }\n\n#endif\n", "meta": {"hexsha": "176377e98718102a20ba2ad4c61ab3bb3b6d62fb", "size": 4438, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/euler/include/nt2/euler/functions/simd/common/erfc.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/euler/include/nt2/euler/functions/simd/common/erfc.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/euler/include/nt2/euler/functions/simd/common/erfc.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": 34.9448818898, "max_line_length": 80, "alphanum_fraction": 0.5863001352, "num_tokens": 1338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.45637474620900365}}
{"text": "#include <iostream>\n#include <fstream>\n#include <armadillo>\n#include <cmath>\n#include <string>\n#include <unordered_map>\n#include \"scf.h\"\nusing namespace std;\nusing namespace arma;\nSCF::SCF(){\n  //Read in the object name like H2O\n  std::string path_data = \"/home/xiuyiqin/GF3ES/Test_SCF/data/\";\n  ifstream iptcoor(path_data+\"inputfile.com\");\n  //In the input file never try to turn on the ERI symmetry, it will cause errors\n  std::string data;\n  string judge1 = \"Obj=\";\n  string judge2 = \"OCC=\";\n  while(!iptcoor.eof()){\n      iptcoor >> data;\n        if (data.compare(judge1)==0){\n            iptcoor>>data;\n            objname = data;\n        }\n        if (data.compare(judge2)==0){\n            iptcoor>>data;\n            _numoccp = std::stoi(data,nullptr,10);\n        }\n  } \n  if (_numoccp == 0){\n      printf(\"Please put number of occupied orbits in inputfile.com\");\n      exit(EXIT_FAILURE);\n  }\n  //Read in the 3 input files\n  std::string overlapfile = \"_overlap.dat\";\n  std::string coreHfile = \"_coreH.dat\";\n  std::string erifile = \"_eri.dat\";\n  std::string enucfile = \"_enuc_Nb.dat\";\n  ifstream iptovlap(path_data+objname+overlapfile);\n  ifstream iptcoreH(path_data+objname+coreHfile);\n  ifstream ipteri(path_data+objname+erifile);\n  ifstream iptenuc(path_data+objname+enucfile);\n  \n  while(!iptenuc.eof()){\n  iptenuc>>_nucrepul;\n  iptenuc>>_numorbit;\n  }\n  //to set up ioff:\n  _ioff.resize(pow(_numorbit,4));\n  _ioff[0] = 0;\n  for(int i=1; i < pow(_numorbit,4); i++)\n  _ioff[i] = _ioff[i-1] + i;\n  //set up matrix\n  _ovlap = new arma::mat(_numorbit,_numorbit);\n  _coreHam = new arma::mat(_numorbit,_numorbit);\n  _Pini = new arma::mat(_numorbit,_numorbit);\n  _Pnext = new arma::mat(_numorbit,_numorbit);\n  _Fini = new arma::mat(_numorbit,_numorbit);\n  _Fnext = new arma::mat(_numorbit,_numorbit);\n  int i = 0, j = 0,k = 0, l = 0;\n  double temp,temp2;\n  printf(\"T3\");\n  /*\n  to input overlap integral\n  and core Hamiltonian\n  and nuclear repulsive energy and No of orbits \n  */\n   // overlap and core Hamiltonian is same size so I put them in same while\n  while(!iptovlap.eof()){\n  iptovlap >> i >> j >> temp;\n  iptcoreH >> i >> j >> temp2;\n  (*_ovlap)(i -1, j -1) = temp;\n  (*_ovlap)(j -1, i -1 ) = temp;\n  (*_coreHam)(i -1, j -1) = temp2;\n  (*_coreHam)(j -1, i -1 ) = temp2;\n  }\n  /*two electron integral */\n  double temp4;\n  while (!ipteri.eof()) {\n    ipteri >> i >> j >> k >> l >> temp4;\n    _twoelec[getijkl(i, j, k, l)] = temp4;\n  }\n  iptcoor.close();iptovlap.close();iptcoreH.close();\n  ipteri.close();iptenuc.close();\n}\n\nint SCF::getijkl(int i, int j, int k, int l){\n  int ij = 0, kl = 0, ijkl = 0;\n  ij = (i > j) ? _ioff[i] + j : _ioff[j] + i;\n  kl = (k > l) ? _ioff[k] + l : _ioff[l] + k;\n  ijkl = (ij > kl) ? _ioff[ij] + kl : _ioff[kl] + ij;\n  return ijkl;\n}\n\nSCF::~SCF(){\n  delete _ovlap;\n  delete _coreHam;\n}\n\nvoid SCF::print(arma::mat ipt){\n  for (size_t i = 0; i < _numorbit; i++) {\n    printf(\"%s\\n\", \" \");\n    for (size_t j = 0; j < _numorbit; j++) {\n    printf(\"%20.12f, %s\", (ipt)(i, j), \" \");\n    }\n  }\n}\n\n\nvoid SCF::calculation(){\n  /*diagonlize overlap Matrix*/\n  printf(\"T9\");\n  arma::vec Seigval;\n  arma::mat Seigvec;\n  arma::eig_sym(Seigval, Seigvec, *_ovlap);\n  /*to get diagonlized eigenvalue matrix\n  *arma::mat eigvalmat = eigvec.t() * (*_ovlap) * eigvec;//works good\n  but the following one would be easier to use*/\n  arma::mat Seigvalmat = arma::diagmat(Seigval);\n  // to get Orthogonalization Matrix\n  //So element-wise inverse and square-root ! except ij term in matrix!\n\n  /*arma::mat et = 1/ sqrt(abs(eigvalmat));\n  *arma::mat S_ihalf = arma::eye(_numorbit,_numorbit);\n  for (size_t i = 0; i < _numorbit; i++) {\n      S_ihalf(i, i) = sqrt(1.0 /eigvalmat(i,i));\n  } this one works but the following one would be more neat\n  */\n  arma::mat lmd_sqrti = arma::sqrt(arma::inv(Seigvalmat));\n\n  _Ssqrtinv = Seigvec * lmd_sqrti * Seigvec.t();//different from website But I believe it caused by different order of eigenvalue? No it is caused by wrong input file\n  /*temporaly moving on\n  * get the Fock matrix for inital guess from hailtonian\n  * then transfer to orthogonal basis to get Fock prime\n  * then diagonlize Fock! in the orthogonal basis!\n  * then transfer back to original basis which is the atomic orbitals\n  */\n  *_Fini = *_coreHam;\n  _Finiprime = _Ssqrtinv.t() * (*_coreHam) * _Ssqrtinv;\n  //digonalize Fock Matrix\n  arma::vec Feigval;\n  arma::mat Feigvec;\n  arma::eig_sym(Feigval, Feigvec, _Finiprime);\n  arma::mat Coe_orig = _Ssqrtinv * Feigvec;\n  //density matrix equals to C * C.t()\n  *_Pini = Coe_orig.cols(0, _numoccp -1) *  Coe_orig.cols(0, _numoccp -1).t();\n  //then get the Energy\n  arma::mat Eini = (*_Pini) % ((*_coreHam) + *_Fini);\n  _Eini = arma::accu(Eini);\n  _Eini += _nucrepul;\n  printf(\"%f\\n\", _Eini);\n\n  /*iteration!\n  */\n  while(true){\n  /*build new Fock ! by old density matrix */\n  for (size_t i = 0; i < _numorbit; i++) {\n      for (size_t j = 0; j < _numorbit; j++) {\n        (*_Fnext)(i,j) = (*_coreHam)(i,j);\n        for (size_t k = 0; k < _numorbit; k++) {\n          for (size_t l = 0; l < _numorbit; l++) {\n            (*_Fnext)(i,j) += (*_Pini)(k,l) * (2 * _twoelec[getijkl(i+1,j+1,k+1,l+1)] - _twoelec[getijkl(i+1,k+1,j+1,l+1)]);\n          }\n        }\n      }\n    }\n    _Finiprime = _Ssqrtinv.t() * (*_Fnext) * _Ssqrtinv;\n    /* to get density matrix and get Energy again..\n    */\n    arma::vec eigval;\n    arma::mat eigvec;\n    arma::eig_sym(eigval, eigvec, _Finiprime);\n    arma::mat Coe = _Ssqrtinv * eigvec;\n    //density matrix equals to C * C.t()\n    *_Pnext = Coe.cols(0, _numoccp -1) *  Coe.cols(0, _numoccp -1).t();\n    //print(*_Pnext);\n    _Enext = arma::accu((*_Pnext) % ((*_coreHam) + *_Fnext)) + _nucrepul;\n    printf(\"%20.12f\\n\", _Enext);\n    if(abs(_Enext - _Eini) < 0.00000000001)\n    break;\n    _Eini = _Enext;\n    *_Fini = *_Fnext;\n    *_Pini = *_Pnext;\n  }\n}\n", "meta": {"hexsha": "733b766b5dd1dfcc15b3af491bf43cee1205a5c6", "size": 5856, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/scf.cpp", "max_stars_repo_name": "Terryqqy/GF3ES", "max_stars_repo_head_hexsha": "cf98b6849b376bbe3407eb5040da66d36118f960", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/scf.cpp", "max_issues_repo_name": "Terryqqy/GF3ES", "max_issues_repo_head_hexsha": "cf98b6849b376bbe3407eb5040da66d36118f960", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/scf.cpp", "max_forks_repo_name": "Terryqqy/GF3ES", "max_forks_repo_head_hexsha": "cf98b6849b376bbe3407eb5040da66d36118f960", "max_forks_repo_licenses": ["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.6540540541, "max_line_length": 166, "alphanum_fraction": 0.6159494536, "num_tokens": 2059, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.45637474620900365}}
{"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\u00e4nkt), 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_PC_ILUT_INCLUDE\n#define ITL_PC_ILUT_INCLUDE\n\n#include <boost/numeric/mtl/vector/sparse_vector.hpp>\n#include <boost/numeric/mtl/operation/invert_diagonal.hpp>\n#include <boost/numeric/mtl/interface/vpt.hpp>\n\nnamespace itl { namespace pc {\n\n\nstruct ilut_factorizer\n{\n\n    template <typename Matrix, typename Para, typename L_type, typename U_type>\n    ilut_factorizer(const Matrix &A, const Para& p, L_type& L, U_type& U)\n    { factorize(A, p, L, U, mtl::traits::is_row_major<Matrix>()); }\n\n    // column-major matrices are copied first\n    template <typename Matrix, typename Para, typename L_type, typename U_type, bool B>\n    void factorize(const Matrix &A, const Para& p, L_type& L, U_type& U, boost::mpl::bool_<B>)\n    {\n\ttypedef typename mtl::Collection<Matrix>::value_type      value_type;\n\ttypedef typename mtl::Collection<Matrix>::size_type       size_type;\n\ttypedef mtl::matrix::parameters<mtl::row_major, mtl::index::c_index, mtl::non_fixed::dimensions, false, size_type> para;\n\ttypedef mtl::matrix::compressed2D<value_type, para>  LU_type;\n\tLU_type LU(A);\n\tfactorize(LU, p, L, U, boost::mpl::true_());\n    }\n\n    // According Yousef Saad: ILUT, NLAA, Vol 1(4), 387-402 (1994)\n#if 0\n    template <typename Value, typename MPara, typename Para, typename L_type, typename U_type>\n    factorize(const mtl::matrix::compressed2D<Value, MPara>& A, const Para& p, L_type& L, U_type& U, boost::mpl::true_)\n#endif\n\n    template <typename Matrix, typename Para, typename L_type, typename U_type>\n    void factorize(const Matrix& A, const Para& p, L_type& L, U_type& U, boost::mpl::true_)\n\n    {   \n\tmtl::vampir_trace<5049> tracer;\n\tusing std::abs; using mtl::traits::range_generator; using mtl::begin; using mtl::end;\n\tusing namespace mtl::tag;\n\tMTL_THROW_IF(num_rows(A) != num_cols(A), mtl::matrix_not_square());\n\n\ttypedef typename mtl::Collection<Matrix>::value_type      value_type;\n\ttypedef typename mtl::Collection<Matrix>::size_type       size_type;\n\ttypedef typename range_generator<row, Matrix>::type       cur_type;    \n\ttypedef typename range_generator<nz, cur_type>::type      icur_type;            \n\ttypename mtl::traits::col<Matrix>::type                   col(A);\n\ttypename mtl::traits::const_value<Matrix>::type           value(A); \n\n\tsize_type n= num_rows(A);\n\tL.change_dim(n, n); \n\tU.change_dim(n, n);\n\t{\n\t    mtl::matrix::inserter<L_type> L_ins(L, p.first);\n\t    mtl::matrix::inserter<U_type> U_ins(U, p.first + 1); // plus one for diagonal\n\t\n\t    mtl::vector::sparse_vector<value_type> vec(n); // corr. row in paper\n\t    cur_type ic= begin<row>(A); // , iend= end<row>(A);\n\t    for (size_type i= 0; i < n; ++i, ++ic) {\n\t\t\n\t\tfor (icur_type kc= begin<nz>(ic), kend= end<nz>(ic); kc != kend; ++kc) // row= A[i][*]\n\t\t    vec.insert(col(*kc), value(*kc));\n\t\t// std::cerr << \"vec_\" << i << \" = \" << vec << std::endl;\n\t\tvalue_type tau_i= p.second * two_norm(vec); // threshold for i-th row\n\t\t// loop over non-zeros in vec; changes in vec considered\n\t\tfor (size_type j= 0; j < vec.nnz() && vec.index(j) < i; j++) {\n\t\t    size_type k= vec.index(j);\n\t\t    value_type ukk= U_ins.value(k, k);\n\t\t    MTL_DEBUG_THROW_IF(ukk == value_type(0), mtl::missing_diagonal());\n\t\t    value_type vec_k= vec.value(j)/= ukk;\n\t\t    // std::cout << \"vec after updating from U[\" << k << \"][\" << k << \"] is \" << vec << '\\n';\n\t\t    for (size_type j0= U_ins.ref_major()[k], j1= U_ins.ref_slot_ends()[k]; j0 < j1; j0++) { // U[k][k+1:n]\n\t\t\tsize_type k1= U_ins.ref_minor()[j0];\n\t\t\tif (k1 > k)\n\t\t\t    vec[k1]-= vec_k * U_ins.ref_elements()[j0];\n\t\t\t// std::cout << \"vec after updating from U[\" << k << \"][\" << k1 << \"] is \" << vec << '\\n';\n\t\t    }\n\t\t    // if (i > 1000 && i < 1010) std::cout << \"vec before crop in row \" << i << \", updating from row \" << k << \": \\n\" << vec << \"\\n\";\n\t\t    vec.crop(tau_i);\n\t\t    // if (i > 1000 && i < 1010) std::cout << \"vec after crop: \\n\" << vec << \"\\n\";\n\t\t}\n\t\t// std::cerr << \"vec_\" << i << \" = \" << vec << std::endl;\n\t\tvec.sort_on_data();\n\t\t// std::cerr << \"vec_\" << i << \" sorted on data = \" << vec << std::endl;\n\t\t\n\t\t// std::cout << \"vec at \" << i << \" is \" << vec << '\\n';\n\t\t// mtl::vampir_trace<9904> tracer2;\n\t\tbool diag_found= false;\n\t\tfor (size_type cntu= 0, cntl= 0, j= 0; j < vec.nnz() && (cntu < p.first || cntl < p.first); j++) {\n\t\t    size_type k= vec.index(j);\n\t\t    value_type v= vec.value(j);\n\t\t    // if (abs(v) < tau_i) break;\n\t\t    if (i == k) {\n\t\t\tU_ins[i][i] << v; diag_found= true;\n\t\t    } else if (i < k) {\n\t\t\tif (cntu++ < p.first)\n\t\t\t    U_ins[i][k] << v;\n\t\t    } else // i > k\n\t\t\tif (cntl++ < p.first)\n\t\t\t    L_ins[i][k] << v;\t\t\n\t\t}\n\t\tif (!diag_found) std::cerr << \"Deleted diagonal!!!!\\n\";\n\t\tvec.make_empty();\n\t    }\n\t} // destroy inserters\n\tinvert_diagonal(U);\n    }\n};\n\n// Not usable yet !!!!!\ntemplate <typename Matrix, typename Value= typename mtl::Collection<Matrix>::value_type>\nclass ilut\n  : public ilu<Matrix, ilut_factorizer, Value>\n{\n    typedef ilu<Matrix, ilut_factorizer, Value> base;\n  public:\n    ilut(const Matrix& A, std::size_t p, typename mtl::Collection<Matrix>::value_type tau) \n      : base(A, std::make_pair(p, tau)) {}\n};\n\n}} // namespace itl::pc\n\n#endif // ITL_PC_ILUT_INCLUDE\n", "meta": {"hexsha": "707d2f7bf7579661612d03f2ba964e7662ab21ff", "size": 5605, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/mtl4/boost/numeric/itl/pc/ilut.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/itl/pc/ilut.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/itl/pc/ilut.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": 40.615942029, "max_line_length": 135, "alphanum_fraction": 0.6224799286, "num_tokens": 1731, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.45637474620900365}}
{"text": "#define BOOST_TEST_MODULE matrix\n\n#include <boost/test/unit_test.hpp>\n#include <boost/test/test_case_template.hpp>\n#include <boost/mpl/list.hpp>\n\n\n#include <mla/matrix/all.h++>\n#include <mla/vector/all.h++>\n#include <mla/matrix/convert.h++>\n\n#include <mla/solvers/umfpack.h++>\n\n\ntypedef boost::mpl::list<\n\tmla::matrix::SparseCCS<double>\n> matrix_type_list;\n\n\nBOOST_AUTO_TEST_SUITE(test_solvers)\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( solve_unit_1, MatrixType, matrix_type_list )\n{\n\tsize_t matrix_size = 6;\n\n\ttypedef typename MatrixType::scalar_type Scalar;\n\n\tmla::matrix::DenseRowMajor<Scalar> from(matrix_size, matrix_size);\n\tMatrixType A(matrix_size, matrix_size);\n\tmla::vector::Dense<Scalar> x(matrix_size), b(matrix_size);\n\n\tScalar value = 1.0f;\n\n\tfor(unsigned int i = 0; i < matrix_size; i++)\n\t{\n\t\tfrom.setValue( i, i, (Scalar)1.0f);\n\t\tb.setValue( i, value);\n\t}\n\n\n\tmla::matrix::convert(from, A);\n\n\tmla::umfpack(A, x, b, NULL);\n\n\tfor(unsigned int i = 0; i < matrix_size; i++)\n\t{\n\t\tBOOST_CHECK_CLOSE( x.getValue(i), 1.0f/b.getValue(i), 0.001f);\n\t}\n}\n\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( solve_unit_2, MatrixType, matrix_type_list )\n{\n\tsize_t matrix_size = 6;\n\n\ttypedef typename MatrixType::scalar_type Scalar;\n\n\tmla::matrix::DenseRowMajor<Scalar> from(matrix_size, matrix_size);\n\tMatrixType A(matrix_size, matrix_size);\n\tmla::vector::Dense<Scalar> x(matrix_size), b(matrix_size);\n\n\tScalar value = 2.0f;\n\n\tfor(unsigned int i = 0; i < matrix_size; i++)\n\t{\n\t\tfrom.setValue( i, i, (Scalar)1.0f);\n\t\tb.setValue( i, value);\n\t}\n\n\n\tmla::matrix::convert(from, A);\n\n\tmla::umfpack(A, x, b, NULL);\n\n\tfor(unsigned int i = 0; i < matrix_size; i++)\n\t{\n\t\tBOOST_CHECK_CLOSE( x.getValue(i), b.getValue(i), 0.001f);\n\t}\n}\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( solve_unit_3, MatrixType, matrix_type_list )\n{\n\tsize_t matrix_size = 6;\n\n\ttypedef typename MatrixType::scalar_type Scalar;\n\n\tmla::matrix::DenseRowMajor<Scalar> from(matrix_size, matrix_size);\n\tMatrixType A(matrix_size, matrix_size);\n\tmla::vector::Dense<Scalar> x(matrix_size), b(matrix_size);\n\n\tScalar value = 2.0f;\n\n\tfor(unsigned int i = 0; i < matrix_size; i++)\n\t{\n\t\tfrom.setValue( i, i, value);\n\t\tb.setValue( i, (Scalar)1.0f);\n\t}\n\n\n\tmla::matrix::convert(from, A);\n\n\tmla::umfpack(A, x, b, NULL);\n\n\tfor(unsigned int i = 0; i < matrix_size; i++)\n\t{\n\t\tBOOST_CHECK_CLOSE( x.getValue(i), 1.0f/value, 0.001f);\n\t}\n}\n\n\n\nBOOST_AUTO_TEST_SUITE_END()\n\n", "meta": {"hexsha": "2a60467b9268f656e6da6947f7a5eb5efe0d0e5e", "size": 2371, "ext": "c++", "lang": "C++", "max_stars_repo_path": "unit_tests/test_solvers_umfpack.c++", "max_stars_repo_name": "ruimaciel/mla", "max_stars_repo_head_hexsha": "b05f5913067af31a345cd2187de25871dbe31856", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "unit_tests/test_solvers_umfpack.c++", "max_issues_repo_name": "ruimaciel/mla", "max_issues_repo_head_hexsha": "b05f5913067af31a345cd2187de25871dbe31856", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unit_tests/test_solvers_umfpack.c++", "max_forks_repo_name": "ruimaciel/mla", "max_forks_repo_head_hexsha": "b05f5913067af31a345cd2187de25871dbe31856", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.264957265, "max_line_length": 75, "alphanum_fraction": 0.7030788697, "num_tokens": 719, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541067, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4563747462090036}}
{"text": "#include <map>\n#include <sstream>\n#include <fstream>\n#include <iostream>\n#include <chrono>\n#include <unordered_map>\n\n#define TINYOBJLOADER_IMPLEMENTATION\n#include \"tiny_obj_loader.h\"\n\n#include <glm/gtx/norm.hpp>\n#include <boost/lexical_cast.hpp>\n\n#include \"mesh.hpp\"\n\nvoid genNormals(Mesh& mesh)\n{\n\tstd::vector<glm::vec3> normals(mesh.v.size());\n\n\tfor (int i = 0; i < mesh.t.size(); i += 3)\n\t{\n\t\tauto v0 = mesh.v[mesh.t[i + 0]];\n\t\tauto v1 = mesh.v[mesh.t[i + 1]];\n\t\tauto v2 = mesh.v[mesh.t[i + 2]];\n\n\t\tauto n = glm::normalize(glm::cross(v1 - v0, v2 - v0));\n\n\t\tnormals[mesh.t[i + 0]] += n;\n\t\tnormals[mesh.t[i + 1]] += n;\n\t\tnormals[mesh.t[i + 2]] += n;\n\t}\n\n\tfor (auto& normal : normals)\n\t{\n\t\tnormal = glm::normalize(normal);\n\t}\n\n\tmesh.n = normals;\n}\n\nvoid genRandomColors(Mesh& mesh) {\n\tfor (int i = 0; i < mesh.v.size(); i++) {\n\t\tmesh.AddColor(glm::vec4(\n\t\t\t(float)rand() / (float)RAND_MAX,\n\t\t\t(float)rand() / (float)RAND_MAX,\n\t\t\t(float)rand() / (float)RAND_MAX,\n\t\t\t1.0f\n\t\t));\n\t}\n}\n\nMesh genIcosahedron()\n{\n\tMesh mesh;\n\n\tconst float t = (1.0f + std::sqrt(5.0f)) / 2.0f;\n\n\tmesh.AddVert(glm::vec3(-1.0f, t, 0.0f));\n\tmesh.AddVert(glm::vec3(1.0f, t, 0.0f));\n\tmesh.AddVert(glm::vec3(-1.0f, -t, 0.0f));\n\tmesh.AddVert(glm::vec3(1.0f, -t, 0.0f));\n\tmesh.AddVert(glm::vec3(0.0f, -1.0, t));\n\tmesh.AddVert(glm::vec3(0.0f, 1.0, t));\n\tmesh.AddVert(glm::vec3(0.0f, -1.0, -t));\n\tmesh.AddVert(glm::vec3(0.0f, 1.0, -t));\n\tmesh.AddVert(glm::vec3(t, 0.0f, -1.0f));\n\tmesh.AddVert(glm::vec3(t, 0.0f, 1.0f));\n\tmesh.AddVert(glm::vec3(-t, 0.0f, -1.0f));\n\tmesh.AddVert(glm::vec3(-t, 0.0f, 1.0f));\n\n\tmesh.AddTri(0, 11, 5);\n\tmesh.AddTri(0, 5, 1);\n\tmesh.AddTri(0, 1, 7);\n\tmesh.AddTri(0, 7, 10);\n\tmesh.AddTri(0, 10, 11);\n\tmesh.AddTri(1, 5, 9);\n\tmesh.AddTri(5, 11, 4);\n\tmesh.AddTri(11, 10, 2);\n\tmesh.AddTri(10, 7, 6);\n\tmesh.AddTri(7, 1, 8);\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\tmesh.AddTri(4, 9, 5);\n\tmesh.AddTri(2, 4, 11);\n\tmesh.AddTri(6, 2, 10);\n\tmesh.AddTri(8, 6, 7);\n\tmesh.AddTri(9, 8, 1);\n\n\tmesh.Normalize();\n\tmesh.radius = 1.0f;\n\n\treturn mesh;\n}\n\nstruct Edge\n{\n\tint v0;\n\tint v1;\n\n\tEdge(int v0, int v1)\n\t\t: v0(v0 < v1 ? v0 : v1), v1(v0 < v1 ? v1 : v0) {}\n\n\tbool operator <(const Edge& rhs) const\n\t{\n\t\treturn v0 < rhs.v0 || (v0 == rhs.v0 && v1 < rhs.v1);\n\t}\n};\n\nint subdivideEdge(int f0, int f1, const glm::vec3& v0, const glm::vec3& v1, Mesh& io_mesh, std::map<Edge, int>& io_divisions)\n{\n\tconst Edge edge(f0, f1);\n\tauto it = io_divisions.find(edge);\n\tif (it != io_divisions.end())\n\t{\n\t\treturn it->second;\n\t}\n\n\tconst glm::vec3 v = normalize((v0 + v1) * 0.5f);\n\tconst int f = io_mesh.v.size();\n\tio_mesh.v.emplace_back(v);\n\tio_divisions.emplace(edge, f);\n\treturn f;\n}\n\nvoid SubdivideMesh(const Mesh& meshIn, Mesh& meshOut)\n{\n\tmeshOut.v = meshIn.v;\n\n\tstd::map<Edge, int> divisions; // Edge -> new vertex\n\n\tfor (uint32_t i = 0; i < meshIn.t.size() / 3; ++i)\n\t{\n\t\tconst int f0 = meshIn.t[i * 3];\n\t\tconst int f1 = meshIn.t[i * 3 + 1];\n\t\tconst int f2 = meshIn.t[i * 3 + 2];\n\n\t\tconst glm::vec3 v0 = meshIn.v[f0];\n\t\tconst glm::vec3 v1 = meshIn.v[f1];\n\t\tconst glm::vec3 v2 = meshIn.v[f2];\n\n\t\tconst int f3 = subdivideEdge(f0, f1, v0, v1, meshOut, divisions);\n\t\tconst int f4 = subdivideEdge(f1, f2, v1, v2, meshOut, divisions);\n\t\tconst int f5 = subdivideEdge(f2, f0, v2, v0, meshOut, divisions);\n\n\t\tmeshOut.AddTri(f0, f3, f5);\n\t\tmeshOut.AddTri(f3, f1, f4);\n\t\tmeshOut.AddTri(f4, f2, f5);\n\t\tmeshOut.AddTri(f3, f4, f5);\n\t}\n}\n\nMesh genIcosphere(int subdivisions)\n{\n\tMesh m = genIcosahedron();\n\tMesh m2;\n\n\tfor (int i = 0; i < subdivisions; i++)\n\t{\n\t\tSubdivideMesh (m, m2);\n\t\tm.v = m2.v;\n\t\tm.t = m2.t;\n\t\tm2.Clear();\n\t}\n\treturn m;\n}\n\nMesh genRing(const int points, const glm::vec4 color)\n{\n\tMesh m;\n\tfor (int i = 0; i < points; i++)\n\t{\n\t\tm.AddVert({ std::cosf(2.f * PI * ((float)i / points)), 0.f, std::sinf(2 * PI * ((float)i / points)) });\n\t\tm.AddVert({ std::cosf(2.f * PI * (((float)i + 1) / points)), 0.f, std::sinf(2 * PI * (((float)i + 1) / points)) });\n\t\tm.AddColor(color);\n\t\tm.AddColor(color);\n\t}\n\tm.radius = 1.f;\n\n\treturn m;\n}\n\nvoid genGrid(Mesh& mesh, const float dim, const int segments, const int subgrids, const glm::vec4 color)\n{\n\tfloat start = -0.5f * dim;\n\tfloat pos = start;\n\tconst float step = dim / segments;\n\tfor (int i = 0; i <= segments; i++)\n\t{\n\t\tmesh.AddVert(glm::vec3(start, 0, pos));\n\t\tmesh.AddVert(glm::vec3(-start, 0, pos));\n\t\tmesh.AddVert(glm::vec3(pos, 0, start));\n\t\tmesh.AddVert(glm::vec3(pos, 0, -start));\n\t\tpos += step;\n\n\t\tfor (int j = 0; j < 4; j++)\n\t\t\tmesh.AddColor(color);\n\t}\n\n\tif (subgrids > 0)\n\t\tgenGrid(mesh, dim, segments * 10, subgrids - 1, glm::vec4(color[0], color[1], color[2], 0.5f * color[3]));\n}\n\nMesh genGrid(const float dim, const int segments, const int subgrids, const glm::vec4 color)\n{\n\tMesh m;\n\tgenGrid(m, dim, segments, subgrids, color);\n\n\tif (subgrids > 0)\n\t{\n\t\tgenGrid(m,\n\t\t\tdim,\n\t\t\tsegments * 10,\n\t\t\tsubgrids - 1,\n\t\t\tglm::vec4(color[0], color[1], color[2], 0.5f * color[3])\n\t\t);\n\t}\n\treturn m;\n}\n\nMesh genVector(const glm::vec3 start, const glm::vec3 end, const glm::vec4 color)\n{\n\tMesh m;\n\tm.AddVert(start);\n\tm.AddVert(end);\n\tm.AddColor(color);\n\tm.AddColor(color);\n\treturn m;\n}\n\n// seek till digit, sign or eof\n// signless for int\nvoid seekNextNumber(std::istringstream& iss)\n{\n\twhile (!std::isdigit(iss.peek()) && iss.peek() != '-' && iss.peek() != EOF)\n\t\tiss.ignore(1, EOF);\n}\n\nbool extractFloats(std::istringstream& iss, float* coord)\n{\n\tfor (int i = 0; i < 3; i++)\n\t{\n\t\tseekNextNumber(iss);\n\n\t\tchar next = iss.peek();\n\t\tstd::string s;\n\t\tstd::getline(iss, s, ' ');\n\t\ttry\n\t\t{\n\t\t\tcoord[i] = boost::lexical_cast<float>(s);\n\t\t}\n\t\tcatch (boost::bad_lexical_cast&)\n\t\t{\n\t\t\tstd::cout << \"Bad cast: \" << s << \" : '\" << next << \"', eof: \" << (next == EOF) << std::endl;\n\t\t}\n\t}\n\n\treturn true;\n}\n\nbool getInt(std::istringstream& iss, std::string& s)\n{\n\t// Look ahead til we get to end of integer\n\tauto start = iss.tellg();\n\twhile (std::isdigit(iss.peek()))\n\t\tiss.ignore(1, EOF);\n\n\tchar end = iss.peek();\n\n\t// Seek back\n\tiss.clear();\n\tiss.seekg(start);\n\tstd::getline(iss, s, end);\n\n\t// Seek till digit, space or eof\n\twhile (!std::isdigit(iss.peek()) && !std::isspace(iss.peek()) && iss.peek() != EOF)\n\t\tiss.ignore(1, EOF);\n\n\t// Return whether next is a slash\n\treturn end == '/';\n}\n\nbool extractInts(std::istringstream& iss, float* values)\n{\n\tstd::string s;\n\tbool proceed;\n\n\tfor (int i = 0; i < 3; i++)\n\t{\n\t\tseekNextNumber(iss);\n\t\tproceed = true;\n\t\tif (proceed)\n\t\t{\n\t\t\tproceed = getInt(iss, s);\n\t\t\tvalues[i + 0] = boost::lexical_cast<float>(s);\n\t\t}\n\t\tif (proceed)\n\t\t{\n\t\t\tproceed = getInt(iss, s);\n\t\t\tvalues[i + 3] = boost::lexical_cast<float>(s);\n\t\t}\n\t\tif (proceed)\n\t\t{\n\t\t\tproceed = getInt(iss, s);\n\t\t\tvalues[i + 6] = boost::lexical_cast<float>(s);\n\t\t}\n\t}\n\n\treturn true;\n}\n\nMesh LoadOBJ(const std::string path, const glm::vec3 offset)\n{\n\tMesh m;\n\n\tauto start = std::chrono::system_clock::now();\n\tstd::ifstream infile(path);\n\n\tint lineCount = 0;\n\tint lineTotal = std::count(std::istreambuf_iterator<char>(infile),\n\t\tstd::istreambuf_iterator<char>(), '\\n');\n\n\tinfile.seekg(0, std::ios::beg);\n\n\tstd::string line;\n\tglm::dvec3 avg(0.0);\n\n\tint v = 0;\n\tint t = 0;\n\n\twhile (std::getline(infile, line))\n\t{\n\t\tstd::istringstream iss(line);\n\t\tif (iss.peek() == 'v')\n\t\t{\n\t\t\tfloat coord[3];\n\t\t\tiss.ignore(1, EOF);\n\n\t\t\tif (iss.peek() == 'n')\n\t\t\t{\n\t\t\t\textractFloats(iss, coord);\n\t\t\t\t// TODO: vertex normal support\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\textractFloats(iss, coord);\n\t\t\t\tglm::vec3 vec = glm::vec3(coord[0], coord[1], coord[2]);\n\t\t\t\tm.AddVert(vec);\n\t\t\t\tavg += vec;\n\t\t\t\tv++;\n\t\t\t}\n\t\t}\n\t\telse if (iss.peek() == 'f')\n\t\t{\n\t\t\tfloat values[9];\n\t\t\textractInts(iss, values);\n\t\t\tm.AddTri(values[0] - 1, values[1] - 1, values[2] - 1);\n\t\t\tt++;\n\t\t}\n\t}\n\n\tavg = avg / static_cast<double>(v);\n\n\tglm::vec3 avgVec = glm::vec3(avg);\n\tfloat maxlen = 0;\n\tfor (auto& vert : m.v)\n\t{\n\t\t// Center to mid\n\t\tvert = (vert - avgVec);\n\t\t// Find furthest vertice (mesh radius)\n\t\tif (glm::length2(vert) > maxlen) maxlen = glm::length2(vert);\n\t}\n\n\tm.radius = sqrtf(maxlen);\n\tm.mid = glm::vec3(0.f);// avgVec;\n\n\tauto end = std::chrono::system_clock::now();\n\tstd::chrono::duration<double> elapsed_seconds = end - start;\n\n\tstd::cout\n\t\t<< \"Loaded OBJ mesh, vertices: \"\n\t\t<< m.v.size() << \"/\" << v\n\t\t<< \", triangles: \"\n\t\t<< m.t.size() / 3 << \"/\" << t\n\t\t<< \", time: \"\n\t\t<< elapsed_seconds.count() << \"s\"\n\t\t<< std::endl;\n\n\treturn m;\n}\n\n// For identical vertex matching\nstruct Vertex\n{\n\tsize_t vx, vy, vz;\n\tsize_t nx, ny, nz;\n\tsize_t tu, tv;\n\n\tbool operator==(const Vertex& other) const\n\t{\n\t\treturn (\n\t\t\tthis->vx == other.vx &&\n\t\t\tthis->vy == other.vy &&\n\t\t\tthis->vz == other.vz &&\n\t\t\tthis->nx == other.nx &&\n\t\t\tthis->ny == other.ny &&\n\t\t\tthis->nz == other.nz &&\n\t\t\t+this->tu == other.tu &&\n\t\t\tthis->tv == other.tv\n\t\t\t);\n\t}\n};\n\n// Hash function for Vertex struct (sum of powers of two)\nnamespace std {\n\ttemplate<> struct hash<Vertex>\n\t{\n\t\tstd::size_t operator()(const Vertex& v) const noexcept\n\t\t{\n\t\t\treturn (\n\t\t\t\t(v.vx * v.vx) + (v.vy * v.vy) + (v.vz * v.vz) +\n\t\t\t\t(v.nx * v.nx) + (v.ny * v.ny) + (v.nz * v.nz) +\n\t\t\t\t(v.tu * v.tu) + (v.tv * v.tv)\n\t\t\t\t);\n\t\t}\n\t};\n}\n\n\nMesh LoadOBJFast(const std::string filename, const std::string path)\n{\n\tauto start = std::chrono::system_clock::now();\n\n\ttinyobj::attrib_t attrib;\n\tstd::vector<tinyobj::shape_t> shapes;\n\tstd::vector<tinyobj::material_t> materials;\n\n\tstd::string warn;\n\tstd::string err;\n\n\tMesh m;\n\tglm::dvec3 avg(0.0);\n\n\tbool loaded = tinyobj::LoadObj(&attrib, &shapes, &materials, &warn, &err, filename.c_str(), path.c_str());\n\n\tif (!warn.empty()) std::cout << warn << std::endl;\n\tif (!err.empty()) std::cerr << err << std::endl;\n\tif (!loaded)\n\t{\n\t\tstd::cerr << \"Failed to load OBJ: \" << path << std::endl;\n\t\treturn m;\n\t}\n\tif (shapes.empty())\n\t{\n\t\tstd::cerr << \"No shapes in OBJ: \" << path << std::endl;\n\t\treturn m;\n\t}\n\tif (shapes[0].mesh.num_face_vertices.empty())\n\t{\n\t\tstd::cerr << \"No vertices in OBJ: \" << path << std::endl;\n\t\treturn m;\n\t}\n\tif (shapes[0].mesh.num_face_vertices[0] != 3)\n\t{\n\t\tstd::cerr << \"Unsupported non-triangle primitives in OBJ: \" << path << std::endl;\n\t\treturn m;\n\t}\n\n\tunsigned idx = 0u;\n\tunsigned offset = 0u;\n\tstd::unordered_map<Vertex, int> previous;\n\n\tfor (unsigned face = 0; face < shapes[0].mesh.num_face_vertices.size(); face++)\n\t{\n\t\tfor (unsigned vertex = 0; vertex < 3; vertex++)\n\t\t{\n\t\t\tauto v_idx = shapes[0].mesh.indices[offset + vertex];\n\t\t\tVertex v = {\n\t\t\t\t3 * v_idx.vertex_index + 0,\n\t\t\t\t3 * v_idx.vertex_index + 1,\n\t\t\t\t3 * v_idx.vertex_index + 2,\n\t\t\t\t3 * v_idx.normal_index + 0,\n\t\t\t\t3 * v_idx.normal_index + 1,\n\t\t\t\t3 * v_idx.normal_index + 2,\n\t\t\t\t2 * v_idx.texcoord_index + 0,\n\t\t\t\t2 * v_idx.texcoord_index + 1\n\t\t\t};\n\n\t\t\tauto match = previous.find(v);\n\t\t\tif (match == previous.end()) // New vertex\n\t\t\t{\n\t\t\t\tglm::vec3 vec = glm::vec3(\n\t\t\t\t\tattrib.vertices[v.vx],\n\t\t\t\t\tattrib.vertices[v.vy],\n\t\t\t\t\tattrib.vertices[v.vz]\n\t\t\t\t);\n\t\t\t\tm.v.emplace_back(vec);\n\t\t\t\tavg += vec;\n\n\t\t\t\tif (v_idx.normal_index != -1)\n\t\t\t\t{\n\t\t\t\t\tm.n.emplace_back(glm::vec3(\n\t\t\t\t\t\tattrib.normals[v.nx],\n\t\t\t\t\t\tattrib.normals[v.ny],\n\t\t\t\t\t\tattrib.normals[v.nz]\n\t\t\t\t\t));\n\t\t\t\t}\n\n\t\t\t\tif (v_idx.texcoord_index != -1)\n\t\t\t\t{\n\t\t\t\t\tm.tx.emplace_back(glm::vec2(\n\t\t\t\t\t\tattrib.texcoords[v.tu],\n\t\t\t\t\t\tattrib.texcoords[v.tv]\n\t\t\t\t\t));\n\t\t\t\t}\n\t\t\t\tsize_t index = previous.size();\n\t\t\t\tprevious.insert({ v, index });\n\t\t\t\tm.t.emplace_back(index);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tm.t.emplace_back(match->second);\n\t\t\t}\n\t\t}\n\t\toffset += 3;\n\t}\n\n\tfloat maxlen = 0;\n\tavg = avg / static_cast<double>(m.v.size());\n\tfor (auto& vert : m.v)\n\t{\n\t\t// Center to mid\n\t\tvert = (vert - glm::vec3(avg));\n\t\t// Find furthest vertice (mesh radius)\n\t\tif (glm::length2(vert) > maxlen) maxlen = glm::length2(vert);\n\t}\n\tm.radius = sqrtf(maxlen);\n\tm.mid = glm::vec3(0.f);\n\n\tauto end = std::chrono::system_clock::now();\n\tstd::chrono::duration<double> elapsed_seconds = end - start;\n\n\tstd::cout\n\t\t<< \"Loaded OBJ mesh, vertices: \" << m.v.size()\n\t\t<< \", triangles: \" << (float)m.t.size() / 3.f\n\t\t<< \", normals: \" << m.n.size()\n\t\t//<< \", texcoords: \" << m.tx.size()\n\t\t<< \", colors: \" << m.c.size()\n\t\t<< \", time: \" << elapsed_seconds.count() << \"s\"\n\t\t<< std::endl;\n\n\treturn m;\n}\n", "meta": {"hexsha": "c46c73c3a29dd007a3470058e4e9df6b2c76c068", "size": 12087, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "triangler/mesh.cpp", "max_stars_repo_name": "viitana/triangler", "max_stars_repo_head_hexsha": "06719c0f019ee1946482ce58195468db518cbdde", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-01-14T11:22:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T13:13:47.000Z", "max_issues_repo_path": "triangler/mesh.cpp", "max_issues_repo_name": "viitana/triangler", "max_issues_repo_head_hexsha": "06719c0f019ee1946482ce58195468db518cbdde", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "triangler/mesh.cpp", "max_forks_repo_name": "viitana/triangler", "max_forks_repo_head_hexsha": "06719c0f019ee1946482ce58195468db518cbdde", "max_forks_repo_licenses": ["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.7392086331, "max_line_length": 125, "alphanum_fraction": 0.5903863655, "num_tokens": 4286, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257127, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4563747402243585}}
{"text": "// The Reactive C++ Toolbox.\n// Copyright (C) 2020 Reactive Markets 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#include \"Utility.hpp\"\n\n#include \"Histogram.hpp\"\n#include \"Iterator.hpp\"\n\n#include <boost/io/ios_state.hpp>\n\n#include <cmath>\n#include <iomanip>\n#include <ostream>\n\nnamespace toolbox {\ninline namespace hdr {\nusing namespace std;\nnamespace {\nint64_t get_count_at_percentile(const HdrHistogram& h, double percentile) noexcept\n{\n    if (percentile > 100.0) {\n        percentile = 100.0;\n    }\n    const int count_at_percentile = (percentile * h.total_count() / 100) + 0.5;\n    return std::max<int64_t>(count_at_percentile, 1);\n}\n} // namespace\n\nint64_t min(const HdrHistogram& h) noexcept\n{\n    return h.min();\n}\n\nint64_t max(const HdrHistogram& h) noexcept\n{\n    return h.max();\n}\n\nint64_t value_at_percentile(const HdrHistogram& h, double percentile) noexcept\n{\n    const int64_t count_at_percentile{get_count_at_percentile(h, percentile)};\n\n    int64_t total{0};\n    HdrIterator iter{h};\n    while (iter.next()) {\n        total += iter.count();\n        if (total >= count_at_percentile) {\n            return h.highest_equivalent_value(iter.value());\n        }\n    }\n    return 0;\n}\n\ndouble mean(const HdrHistogram& h) noexcept\n{\n    const auto total_count = h.total_count();\n\n    int64_t total{0};\n    HdrIterator iter{h};\n    while (iter.next()) {\n        if (iter.count() != 0) {\n            total += iter.count() * h.median_equivalent_value(iter.value());\n        }\n    }\n    return double(total) / total_count;\n}\n\ndouble stddev(const HdrHistogram& h) noexcept\n{\n    const int64_t total_count{h.total_count()};\n    const double mean_val{mean(h)};\n\n    double geometric_dev_total{0.0};\n    HdrIterator iter{h};\n    while (iter.next()) {\n        if (iter.count() != 0) {\n            const double dev{h.median_equivalent_value(iter.value()) - mean_val};\n            geometric_dev_total += (dev * dev) * iter.count();\n        }\n    }\n    return sqrt(geometric_dev_total / total_count);\n}\n\nostream& operator<<(ostream& os, PutPercentiles pp)\n{\n    const auto sf = pp.h.significant_figures();\n    boost::io::ios_all_saver all_saver{os};\n\n    os << \"       Value     Percentile TotalCount 1/(1-Percentile)\\n\\n\";\n\n    HdrPercentileIterator iter{pp.h, pp.ticks_per_half_distance};\n    while (iter.next()) {\n        const double value{iter.highest_equivalent_value() / pp.value_scale};\n        const double percentile{iter.percentile() / 100.0};\n        const int64_t total_count{iter.cumulative_count()};\n\n        // clang-format off\n        os << setw(12) << fixed << setprecision(sf) << value\n           << setw(15) << fixed << setprecision(6) << percentile\n           << setw(11) << total_count;\n        // clang-format on\n\n        if (percentile < 1.0) {\n            const double inverted_percentile{(1.0 / (1.0 - percentile))};\n            os << setw(15) << fixed << setprecision(2) << inverted_percentile;\n        }\n        os << '\\n';\n    }\n\n    const double mean_val{mean(pp.h) / pp.value_scale};\n    const double stddev_val{stddev(pp.h)};\n    const double max_val{pp.h.max() / pp.value_scale};\n    const int64_t total_val{pp.h.total_count()};\n\n    // clang-format off\n    return os\n        << \"#[Mean    = \" << setw(12) << fixed << setprecision(sf) << mean_val\n        << \", StdDeviation   = \" << setw(12) << fixed << setprecision(sf) << stddev_val\n        << \"]\\n\"\n        \"#[Max     = \" << setw(12) << fixed << setprecision(sf) << max_val\n        << \", TotalCount     = \" << setw(12) << total_val\n        << \"]\\n\"\n        \"#[Buckets = \" << setw(12) << pp.h.bucket_count()\n        << \", SubBuckets     = \" << setw(12) << pp.h.sub_bucket_count()\n        << \"]\";\n    // clang-format on\n}\n\n} // namespace hdr\n} // namespace toolbox\n", "meta": {"hexsha": "71ce86aa734b0487eb49eb38e1a95b4ac10799bd", "size": 4268, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "toolbox/hdr/Utility.cpp", "max_stars_repo_name": "mmitkevich/toolbox-cpp", "max_stars_repo_head_hexsha": "59e26154acbd990de9658bf229ebdbf7f89fc0c8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-06-11T19:26:28.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-11T19:26:28.000Z", "max_issues_repo_path": "toolbox/hdr/Utility.cpp", "max_issues_repo_name": "mmitkevich/toolbox-cpp", "max_issues_repo_head_hexsha": "59e26154acbd990de9658bf229ebdbf7f89fc0c8", "max_issues_repo_licenses": ["Apache-2.0"], "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/hdr/Utility.cpp", "max_forks_repo_name": "mmitkevich/toolbox-cpp", "max_forks_repo_head_hexsha": "59e26154acbd990de9658bf229ebdbf7f89fc0c8", "max_forks_repo_licenses": ["Apache-2.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.8461538462, "max_line_length": 87, "alphanum_fraction": 0.6276944705, "num_tokens": 1099, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.4562814839678506}}
{"text": "#pragma once\n#include <iostream>\n\n#include <utility>\n\n#include <memory>\n#include <tuple>\n#include <iostream>\n#include <Eigen/Sparse>\n#include <Eigen/Dense>\n#include <functional>\n#include <vector>\n\nnamespace gsimp {\n// geometric types\ntypedef std::vector<double> point_t;\ntypedef std::vector<size_t> cell_t;\n\n// linear algebra types\ntypedef typename Eigen::SparseMatrix<double> matrix_t;\ntypedef typename Eigen::SparseVector<double> vector_t;\n\n// chains\ntypedef typename std::pair<int, vector_t> chain_t;\ntypedef typename std::pair<int, std::vector<double>> chain_v;\n\nint& chain_dim(chain_t& p) { return std::get<0>(p); }\nvector_t& chain_rep(chain_t& p) { return std::get<1>(p); }\ndouble& chain_val(chain_t& p, size_t i) { return std::get<1>(p).coeffRef(i); }\nsize_t chain_size(chain_t& p) {return std::get<1>(p).size();}\n\nint& chain_dim(chain_v& p) { return std::get<0>(p); }\nstd::vector<double>& chain_rep_v(chain_v& p) { return std::get<1>(p); }\ndouble& chain_val(chain_v& p, size_t i) { return std::get<1>(p)[i]; }\nsize_t chain_size(chain_v& p) {return std::get<1>(p).size();}\n\nchain_t create_chain(int d,std::vector<double>& vec) {\n    // no dimension checking\n    // use at own risk\n    std::cout << \"creating the sparse vector\\n\";\n    vector_t v(vec.size());\n    std::cout << \"creating the pair\\n\";\n    chain_t c(d,v);\n    std::cout << \"made the pair starting conversion\\n\";\n    for (size_t i = 0 ; i < vec.size(); ++i)\n    {if (vec[i] != 0) chain_val(c,i) = vec[i];}\n    return c;\n}\n\nchain_t add(chain_t chain1, chain_t chain2) {\n    if (std::get<0>(chain1) == std::get<0>(chain2))\n        return chain_t(std::get<0>(chain1),\n                       std::get<1>(chain1) + std::get<1>(chain2));\n    std::cout << \"chains must have the same dimension to be added (+)\";\n    throw std::exception();\n}\n\nvoid add_to(chain_t chain1, chain_t chain2) {\n    if (std::get<0>(chain1) == std::get<0>(chain2))\n        std::get<1>(chain1) += std::get<1>(chain2);\n    else {\n        std::cout << \"chains must have the same dimension to be added (+=)\";\n        throw std::exception();\n    }\n}\n\nchain_t subtract(chain_t chain1, chain_t chain2) {\n    if (std::get<0>(chain1) == std::get<0>(chain2))\n        return chain_t(std::get<0>(chain1),\n                       std::get<1>(chain1) - std::get<1>(chain2));\n    std::cout << \"chains must have the same dimension to be added (-)\";\n    throw std::exception();\n}\n\nvoid subtract_to(chain_t chain1, chain_t chain2) {\n    if (std::get<0>(chain1) == std::get<0>(chain2))\n        std::get<1>(chain1) -= std::get<1>(chain2);\n    else {\n        std::cout << \"chains must have the same dimension to be added (-=)\";\n        throw std::exception();\n    }\n}\n\nchain_t prod(double coef, chain_t chain) {\n    return chain_t(std::get<0>(chain), std::get<1>(chain) * coef);\n}\n\nvoid prod_to(double coef, chain_t chain) { std::get<1>(chain) *= coef; }\n\nEigen::VectorXd point_to_eigen(point_t pt) {\n    Eigen::VectorXd v0(pt.size());\n    for (int j = 0; j < pt.size(); ++j) v0(j) = pt[j];\n    return v0;\n}\n\n\n}  // namespace gsimp\n", "meta": {"hexsha": "a0f7d65bb63e2610127f0488cf5389b3a3be12b9", "size": 3046, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/scomplex/types.hpp", "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/types.hpp", "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/types.hpp", "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": 31.0816326531, "max_line_length": 78, "alphanum_fraction": 0.6280367695, "num_tokens": 907, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.4562814839678506}}
{"text": "// Copyright Abel Sinkovics (abel@sinkovics.hu) 2011.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n#include <mpllibs/metamonad/list.hpp>\n#include <mpllibs/metamonad/return_.hpp>\n#include <mpllibs/metamonad/bind.hpp>\n\n#include <mpllibs/metamonad/mempty.hpp>\n#include <mpllibs/metamonad/mappend.hpp>\n#include <mpllibs/metamonad/mconcat.hpp>\n\n#include <boost/test/unit_test.hpp>\n\n#include \"common.hpp\"\n\n#include <boost/mpl/equal.hpp>\n#include <boost/mpl/assert.hpp>\n\nBOOST_AUTO_TEST_CASE(test_list_monoid)\n{\n  using mpllibs::metamonad::list_tag;\n  using mpllibs::metamonad::mempty;\n  using mpllibs::metamonad::mappend;\n  using mpllibs::metamonad::mconcat;\n  \n  using boost::mpl::equal;\n  using boost::mpl::list;\n\n  typedef list<int, double> l_x;\n  typedef list<char, long> l_y;\n  typedef list<int*, int**, int***> l_z;\n  \n  // test_left_identity\n  BOOST_MPL_ASSERT((\n    equal<l_x, mappend<list_tag, mempty<list_tag>::type, l_x>::type>\n  ));\n\n  // test_right_identity\n  BOOST_MPL_ASSERT((\n    equal<l_x, mappend<list_tag, l_x, mempty<list_tag>::type>::type>\n  ));\n\n  // test_assoc\n  BOOST_MPL_ASSERT((\n    equal<\n      mappend<list_tag, mappend<list_tag, l_x, l_y>::type, l_z>::type,\n      mappend<list_tag, l_x, mappend<list_tag, l_y, l_z>::type>::type\n    >\n  ));\n}\n\n\n", "meta": {"hexsha": "768f0c1c36cb602c9ea7fb8d09316d25cf41fc03", "size": 1391, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/metamonad/test/list_monoid.cpp", "max_stars_repo_name": "sabel83/mpllibs", "max_stars_repo_head_hexsha": "8e245aedcf658fe77bb29537aeba1d4e1a619a19", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 70.0, "max_stars_repo_stars_event_min_datetime": "2015-01-15T09:05:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-08T15:49:31.000Z", "max_issues_repo_path": "libs/metamonad/test/list_monoid.cpp", "max_issues_repo_name": "sabel83/mpllibs", "max_issues_repo_head_hexsha": "8e245aedcf658fe77bb29537aeba1d4e1a619a19", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-06-18T19:25:34.000Z", "max_issues_repo_issues_event_max_datetime": "2016-05-13T19:49:51.000Z", "max_forks_repo_path": "libs/metamonad/test/list_monoid.cpp", "max_forks_repo_name": "sabel83/mpllibs", "max_forks_repo_head_hexsha": "8e245aedcf658fe77bb29537aeba1d4e1a619a19", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2015-07-10T08:18:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-01T07:17:57.000Z", "avg_line_length": 25.2909090909, "max_line_length": 70, "alphanum_fraction": 0.7059669303, "num_tokens": 413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321964553658, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.4562814820206815}}
{"text": "// landmark.cpp\n// Based on landmarks_maxmin.cpp in the 'landmark' R package by Matt Piekenbrock, Jason Cory Brunson, Yara Skaf\n#include <carma>\n#include <armadillo>\n\n#include <vector>\n#include <functional>\n#include <numeric>\n#include <algorithm>\n#include <thread>\n\nusing std::size_t;\nusing std::vector; \nusing std::thread; \n\n#include <pybind11/pybind11.h>\n#include <pybind11/stl.h>\n#include <pybind11/numpy.h>\n\nusing namespace pybind11::literals;\nnamespace py = pybind11;\n\ntemplate< typename InputIt >\ninline double sq_euc_dist(InputIt x, InputIt y, const size_t d){\n\tdouble res = 0.0; \n\tfor(size_t i = 0; i < d; ++i, ++x, ++y){\n\t\tres += ((*x) - (*y)) * ((*x) - (*y));\n\t}\n\treturn(res);\n}\n// a Distance Function here just returns the distance between two points, given their *indices*\nusing DistFunction = typename std::function<double(size_t, size_t)>;\n\n// dist_f  := distance function between two (indexed) points\n// n_pts   := number of points in the data set\n// eps     := distance threshold used as a stopping criterion for the maxmin procedure\n// n       := cardinality threshold used as a stopping criterion for the maxmin procedure\n// metric  := metric to use. If 0, uses `dist_f`, otherwise picks one of the available metrics.\n// seed    := initial point (default is point at index 0)\n// pick    := criterion to break ties. Possible values include 0 (first), 1 (random), or 2 (last).\n// cover   := whether to report set membership for each point\nvoid maxmin_f(DistFunction dist_f, const size_t n_pts,\n              const double eps, const size_t n,\n              const size_t seed, const size_t pick,\n\t\t\t\t\t\t\tvector< size_t >& indices, \n\t\t\t\t\t\t\tvector< double >& radii\n\t\t\t\t\t\t\t) {\n  if (eps == -1.0 && n == 0){ throw std::invalid_argument(\"Must supply either positive 'eps' or positive 'n'.\"); }\n  if (pick > 2){ throw std::invalid_argument(\"tiebreaker 'pick' choice must be in { 0, 1, 2 }.\"); }\n  if (seed >= n_pts){ throw std::invalid_argument(\"Invalid seed index given.\"); }\n\tif (indices.size() == 0 || radii.size() == 0){ throw std::invalid_argument(\"Indices and radii must have at least one element to begin with.\"); }\n\n  // Make a function that acts as a sentinel\n  enum CRITERION { NUM, EPS, NUM_OR_EPS }; // These are the only ones that make sense\n  const CRITERION stopping_criterion = (eps == -1.0) ? NUM : ((n == 0) ? EPS : NUM_OR_EPS);\n  const auto is_finished = [stopping_criterion, eps, n](size_t n_landmarks, double c_eps) -> bool {\n    switch(stopping_criterion){\n      case NUM: return(n_landmarks >= n);\n      case EPS: return(c_eps <= eps);\n      case NUM_OR_EPS: return(n_landmarks >= n || c_eps <= eps);\n\t\t\tdefault: return(true); // should never happen, but gcc complains\n    };\n  };\n\n  // Indices of possible candidate landmarks\n  vector< size_t > candidate_pts(n_pts, 0);\n  std::iota(begin(candidate_pts), end(candidate_pts), 0);\n  candidate_pts.erase(begin(candidate_pts) + seed);\n\n  // Preallocate distance vector for landmarks; one for each point\n\tdouble cover_radius = std::numeric_limits<double>::infinity();\n  vector< double > lm_dist(n_pts, cover_radius);\n\n  // Generate the landmarks\n  bool stop_reached = false;\n  while (!stop_reached){\n    const size_t c_lm = indices.back(); // update current landmark\n\n    // Update non-landmark points with distance to nearest landmark\n    for (auto idx: candidate_pts){\n      double c_dist = dist_f(c_lm, idx);\n      if (c_dist < lm_dist[idx]){\n        lm_dist[idx] = c_dist; // update minimum landmark distance\n      }\n    }\n\n    // Of the remaining candidate points, find the one with the maximum landmark distance\n    auto max_landmark = std::max_element(begin(candidate_pts), end(candidate_pts), [&lm_dist](size_t ii, size_t jj){\n      return lm_dist[ii] < lm_dist[jj];\n    });\n\n    // If not greedily picking the first candidate point, partition the candidate points, then use corresponding strategy\n    if (pick > 0 && max_landmark != end(candidate_pts)){\n      double max_lm_dist = lm_dist[(*max_landmark)];\n      auto it = std::partition(begin(candidate_pts), end(candidate_pts), [max_lm_dist, &lm_dist](size_t j){\n        return lm_dist[j] == max_lm_dist;\n      });\n\t\t\tmax_landmark = \n\t\t\t\tpick == 1 ? (it != begin(candidate_pts) ? std::prev(it) : begin(candidate_pts)) :\n\t\t\t\tbegin(candidate_pts) + (rand() % std::distance(begin(candidate_pts), it));\n    }\n\n    // If the iterator is valid, we have a new landmark, otherwise we're finished\n    if (max_landmark != end(candidate_pts)){\n      cover_radius = lm_dist[(*max_landmark)];\n      stop_reached = is_finished(indices.size(), cover_radius);\n      if (!stop_reached){\n        indices.push_back(*max_landmark);\n\t\t\t\tradii.push_back(cover_radius);\n\t\t\t\tcandidate_pts.erase(max_landmark);\n      }\n    } else {\n      cover_radius = 0.0;\n      stop_reached = true;\n    }\n  } // while(!finished())\n}\n\n// Point cloud wrapper - See 'maxmin_f' below for implementation\npy::tuple maxmin_pc(\n\tconst arma::mat& X, \n\tconst double eps, const size_t n,\n\tconst size_t metric = 1, const size_t seed = 0, const size_t pick = 0\n){\n  const size_t n_pts = X.n_cols, d = X.n_rows;\n  if (seed >= n_pts){ throw std::invalid_argument(\"Invalid seed point.\"); }\n\n\t// Initial covering radius == Inf \n\tvector< double > cover_radii{ std::numeric_limits<double>::infinity() };\n\n  // Choose the initial landmark\n  vector< size_t > lm { seed };\n  lm.reserve(n != 0 ? n : size_t(n_pts*0.15));\n\n  // Choose the distance function\n  DistFunction dist = [&X, d](size_t i, size_t j) { \n\t\treturn(sq_euc_dist(X.begin_col(i), X.begin_col(j), d));\n\t};\n\n  // Call the generalized procedure\n  maxmin_f(dist, n_pts, eps, n, seed, pick, lm, cover_radii);\n\t\n\treturn(py::make_tuple(lm, cover_radii));\n}\n\n// Converts (i,j) indices in the range { 0, 1, ..., n - 1 } to its 0-based position\n// in a lexicographical ordering of the (n choose 2) combinations.\nconstexpr size_t to_nat_2(size_t i, size_t j, size_t n) noexcept {\n  return i < j ? (n*i - i*(i+1)/2 + j - i - 1) : (n*j - j*(j+1)/2 + i - j - 1);\n}\n\n// X := (n_pts choose 2) pairwise distances\n// n_pts := number of points in X\npy::tuple maxmin_dist(\n\tconst arma::vec& X, const size_t n_pts,\n\tconst double eps, const size_t n,\n\tconst size_t seed = 0, const size_t pick = 0){\n  if (seed >= n_pts){ throw std::invalid_argument(\"Invalid seed point.\"); }\n\n  // Parameterize the distance function\n  DistFunction dist = [&X, n_pts](size_t i, size_t j) -> double {\n    return X[to_nat_2(i,j,n_pts)];\n  };\n\t\n\t// Initial covering radius == Inf \n\tvector< double > cover_radii{ std::numeric_limits<double>::infinity() };\n\n  // Choose the initial landmark\n  vector< size_t > lm { seed };\n  lm.reserve(n != 0 ? n : size_t(n_pts*0.15));\n\n  // Call the generalized procedure\n  maxmin_f(dist, n_pts, eps, n, seed, pick, lm, cover_radii);\n\treturn(py::make_tuple(lm, cover_radii));\n}\n\n// Maxmin procedure O(n^2)\n// x := pairwise distances (not a distance matrix!) if pairwise = True, else (d x n) matrix representing a point cloud \n// eps := radius to cover 'x' with, otherwise -1.0 to use 'n'\n// n := number of landmarks requested\n// pairwise_dist := whether input is a set of pairwise distances or a point cloud\npy::tuple maxmin(const py::array_t<double>& x, const double eps, const size_t n, bool pairwise_dist, int seed){\n\tif (pairwise_dist){\n\t\tconst arma::vec dx = carma::arr_to_col< double >(x);\n\t\tconst size_t N = dx.size();\n\n\t\t// Find n such that choose(n, 2) == N\n\t\tsize_t lb = std::sqrt(2*N); \n\t\tsize_t n_pts = size_t(floor(lb));\n\t\tfor (; n_pts <= size_t(std::ceil(lb+2)); ++n_pts){\n\t\t\tif (N == ((n_pts * (n_pts - 1))/2)){ break; }\n\t\t}\n\t\treturn(maxmin_dist(dx, n_pts, eps, n, seed, 0));\n\t} else {\n\t\tconst arma::mat X = carma::arr_to_mat< double >(x);\n\t\treturn(maxmin_pc(X, eps, n, 1, seed, 0));\n\t}\n}\n\nvoid doSomething(int thread_id, vector< double >& output) {\n\toutput[thread_id] = std::sqrt(static_cast< double >(thread_id));\n}\n\n// Spawns n threads\nauto spawnThreads(int n) -> vector< double > {\n\tvector< thread > threads(n);\n\tvector< double > output(n, 0.0); \n\tfor (int i = 0; i < n; i++) {\n\t\tthreads[i] = thread(doSomething, i, std::ref(output));\n\t}\n\tfor (auto& th : threads) { th.join(); } // each thread blocks until it's finished, sequentially \n\treturn(output);\n}\n\n// Classical MDS \n// D := distance matrix\nvoid cmds_eig(const arma::mat& D, const size_t d, arma::vec& w, arma::mat& v){\n\tconst size_t n = D.n_rows;\n\tarma::mat H(n, n, arma::fill::zeros);\n\tdouble fill_value = 1.0/double(n);\n\tH.fill(-fill_value);\n\tH.diag().fill(1.0 - fill_value); \n\tbool success = arma::eig_sym(w, v, -0.5 * H * D * H, \"std\");\n\tif (!success){\n\t\tthrow std::invalid_argument(\"Eigenvalues failed to converge.\");\n\t}\n}\n\nvoid cmds(const arma::mat& D, const size_t d, arma::mat& out){\n\tarma::mat v; \n\tarma::vec w; \n\tcmds_eig(D, d, w, v);\n\tout = arma::fliplr(v);\n\tarma::vec eigenvalues = arma::sort(w, \"descend\");\n\tout.resize(out.n_rows, d);\n\tfor (size_t j = 0; j < d; ++j){\n\t\tif (eigenvalues[j] > 0){\n\t\t\tout.col(j) *= std::sqrt(eigenvalues[j]);\n\t\t} else {\n\t\t\tout.col(j).fill(0.0);\n\t\t}\n\t}\n}\n\nconstexpr auto rank_comb2(size_t i, size_t j, size_t n) noexcept -> size_t { \n  if (j < i){ std::swap(i,j); }\n  return(size_t(n*i - i*(i+1)/2 + j - i - 1));\n}\n\ninline std::array< size_t, 2 > unrank_comb2(const size_t x, const size_t n) noexcept {\n\tauto i = static_cast< size_t >( (n - 2 - floor(sqrt(-8*x + 4*n*(n-1)-7)/2.0 - 0.5)) );\n\tauto j = static_cast< size_t >( x + i + 1 - n*(n-1)/2 + (n-i)*((n-i)-1)/2 );\n\treturn (std::array< size_t, 2 >{ i, j });\n}\n\n// Measure all pairwise distances between columns of matrix 'x'\n// template< typename OutputIt, typename Lambda >\t\t\n// void dist(const arma::mat& x, OutputIt out){\n// \tconst size_t N = x.n_rows*(x.n_rows - 1)/2;\n// \tfor (size_t c = 0; c < N; ++c){\n// \t\tstd::array< size_t, 2 > p = unrank_comb2(c, x.n_rows);\n// \t\tsize_t i = p[0], j = p[1];\n// \t\t*out++ = (double) arma::dot(x.col(i) - x.col(j));\n// \t}\n// }\n\n// Measure all pairwise distances between columns of matrix 'x'\nvoid dist_matrix(const arma::mat& x, arma::mat& D){\n\tconst size_t N = x.n_cols*(x.n_cols - 1)/2;\n\t// py::print(\"n = \", N);\n\tfor (size_t c = 0; c < N; ++c){\n\t\tstd::array< size_t, 2 > p = unrank_comb2(c, x.n_cols);\n\t\tsize_t i = p[0], j = p[1];\n\t\tarma::vec diff = x.col(i) - x.col(j);\n\t\tD(i,j) = (double) std::pow(arma::norm(diff), 2.0);\n\t\tD(j,i) = D(i,j);\n\t}\n}\n\n// Each C++11 thread should be running in their function with an infinite loop, constantly waiting for new tasks to grab and run.\n#include \"threadpool.h\"\nvoid parallel_mds_threadpool(const arma::mat& X, const vector< arma::uvec >& cover_sets, const size_t d, const size_t n_threads, vector< arma::mat >& out){\n\t// Allocate max number of threads\n\tctpl::thread_pool p(n_threads);\n\n\t// Prepare the models \n\tconst size_t n_opens = cover_sets.size();\n\tauto models = vector< arma::mat >(n_opens, arma::mat());\n\n\t// Launch the threads\n\tstd::vector<std::future<void>> results(n_opens);\n\n\tfor (size_t j = 0; j < n_opens; ++j) {\n\t\tresults[j] = p.push([&models, &X, &cover_sets, j, d](int thread_id){\n\t\t\tconst size_t n = cover_sets.at(j).size();\n\t\t\tconst arma::mat X_j = X.cols(cover_sets.at(j));\n\t\t\tarma::mat D = arma::mat(n, n, arma::fill::zeros);\n\t\t\tdist_matrix(X_j, D);\n\t\t\tcmds(D, d, models.at(j)); \n\t\t});\n\t}\n\n\t// Join them \n\tfor (size_t j = 0; j < n_opens; ++j) { results[j].get(); }\n\t\n\t// Copy the local euclidean models (transposed)\t\n\tfor (size_t j = 0; j < models.size(); ++j){\n\t\tout[j] = models[j];\n\t}\n};\n\nauto parallel_mds(const py::array_t< double >& x, const py::list& cover_sets, const size_t d, const size_t n_threads) -> py::list {\n\n\t// Conversions\n\tconst arma::mat X = carma::arr_to_mat< double >(x).t();\n\tauto indices = vector< arma::uvec >(cover_sets.size());\n\tfor (size_t j = 0; j < cover_sets.size(); ++j){ \n\t\tindices[j] = cover_sets[j].cast< arma::uvec >(); \n\t}\n\t\n\t// Do the parallel mds\n\tstd::cout << \"The GIL state is \" << PyGILState_Check() <<std::endl;\n\tpy::gil_scoped_release release;\n\tstd::cout << \"The GIL state is \" << PyGILState_Check() <<std::endl;\n\tvector< arma::mat > results(indices.size(), arma::mat()); \n\tparallel_mds_threadpool(X, indices, d, n_threads, results);\n\tpy::gil_scoped_acquire acquire;\n\n\t// py::list output(indices.size()); \n\tvector< py::array_t< double > > output(indices.size());\n\tfor (size_t j = 0; j < indices.size(); ++j){\n\t\toutput[j] = carma::mat_to_arr(results[j]);\n\t}\n\treturn(py::cast(output));\n} // parallel_mds\n\n// auto parallel_mds_blocks(const py::array_t< double >& x, const py::list& cover_sets, const size_t d, \tconst vector< size_t >& blocks, const size_t n_threads) -> py::list {\n// \t// Conversions\n// \tconst arma::mat X = carma::arr_to_mat< double >(x).t();\n// \tauto indices = vector< arma::uvec >(cover_sets.size());\n// \tfor (size_t j = 0; j < cover_sets.size(); ++j){ \n// \t\tindices[j] = cover_sets[j].cast< arma::uvec >(); \n// \t}\n\t\n// \t// Do the parallel mds\n// \tpy::gil_scoped_release release;\n// \tvector< arma::mat > results(indices.size(), arma::mat()); \n// \tparallel_mds_simple(X, indices, d, n_threads, results);\n// \tpy::gil_scoped_acquire acquire;\n\n// \t// py::list output(indices.size()); \n// \tvector< py::array_t< double > > output(indices.size());\n// \tfor (size_t j = 0; j < indices.size(); ++j){\n// \t\toutput[j] = carma::mat_to_arr(results[j]);\n// \t}\n// \treturn(py::cast(output));\n// }\n\n// Simple parallelization of MDS on each open of the cover \n// Assumes n_threads > 1 \n// X := (d x n) column major matrix of points\n// blocks := (n_threads+1) vector of offsets such that indicating a range [blocks[i], blocks[i+1]) of open for thread i to handle\nvoid parallel_mds_simple(\n\tconst arma::mat& X, \n\tconst vector< vector< arma::uword > >& cover_sets, \n\tconst size_t d, \n\tconst size_t n_threads, \n\tconst vector< size_t >& blocks, \n\tvector< arma::mat >& out\n){\n\tif (blocks.size() != (n_threads+1)){ throw std::invalid_argument(\"Block vector size must match number of threads.\"); }\n\n\t// Prepare the lambda to do the work\n\tconst auto do_mds = [&out, &X, &cover_sets, d](int i, const int j) -> void {\n\t\tfor (; i < j; ++i){\n\t\t\t// py::print(\"subset: \", i, \"/\", cover_sets.size());\n\t\t\tconst size_t n = cover_sets.at(i).size();\t\n\t\t\t//vector< arma::uword >& c_open = cover_sets.at(i);\n\t\t\tarma::uvec ind(cover_sets.at(i));// unfortunately this copy is required\n\t\t\tconst arma::mat X_i = X.cols(ind);\n\t\t\tarma::mat D = arma::mat(n, n, arma::fill::zeros);\n\t\t\tdist_matrix(X_i, D);\n\t\t\tcmds(D, d, out.at(i)); \n\t\t}\n\t};\n\n\t// Do sequential computation \n\t// for (size_t j = 0; j < n_threads; ++j){\n\t// \t// py::print(\"Starting thread: \", j);\n\t// \tdo_mds(blocks.at(j), blocks.at(j+1));\n\t// }\n\n\t// Launch the threads\n\tauto tt = vector< thread >(n_threads - 1);\n\tfor (size_t j = 0; j < (n_threads-1); ++j){\n\t\ttt.at(j) = thread(do_mds, blocks.at(j), blocks.at(j+1));\n\t}\n\t// Have the main thread do some work as well\n\tdo_mds(blocks.at(n_threads-1), blocks.at(n_threads));\n\n\t// Join the threads \n\tfor (size_t j = 0; j < (n_threads-1); ++j) { tt.at(j).join(); }\n}\n\n// When threads are created using the dedicated Python APIs (such as the threading module), a thread state is automatically associated to \n// them and the code showed above is therefore correct. However, when threads are created from C (for example by a third-party library \n// with its own thread management), they don\u2019t hold the GIL, nor is there a thread state structure for them.\n\n// If you need to call Python code from these threads (often this will be part of a callback API provided by the aforementioned third-party \n// library), you must first register these threads with the interpreter by creating a thread state data structure, then acquiring the GIL, \n// and finally storing their thread state pointer, before you can start using the Python/C API. When you are done, you should reset the \n// thread state pointer, release the GIL, and finally free the thread state data structure.\n\n// trust pybind11/carma to do the automatic conversions here\n// Parallelization notes: \n// (1) DO NOT PASS AN ARMA::MAT DIRECTLY AS A PARAMETER; convert manually w/ carma\n// (2) The GIL lock seems to require spawning threads, if unlocked and reacquired. Only unlock if threads are spawned.\n// (3) Can actually return vector< arma::mat > fine, surprisingly\nauto parallel_mds_blocks(\n\tconst py::array_t< double >& X,\n\tconst vector< vector< arma::uword >  >& cover_sets, \n\tconst size_t d, \n\tconst size_t n_threads, \n\tconst vector< size_t >& blocks\n) -> vector< arma::mat > {\n\n\t// Allocate the output\n\tvector< arma::mat > results(cover_sets.size(), arma::mat(1,1, arma::fill::zeros)); \n\n\t// Do the parallel mds\n\t// std::cout << \"INIT: The GIL state is \" << PyGILState_Check() <<std::endl;\n\tconst arma::mat points = carma::arr_to_mat(X); \n\tpy::gil_scoped_release release;\n\tvector< double > res = spawnThreads(n_threads);\n\t// std::cout << \"BEGIN: The GIL state is \" << PyGILState_Check() <<std::endl;\n\tparallel_mds_simple(points, cover_sets, d, n_threads, blocks, results);\n\t// PyGILState_Ensure();\n\t// std::cout << \"FINISHED: The GIL state is \" << PyGILState_Check() <<std::endl;\n\tpy::gil_scoped_acquire acquire;\n\t// std::cout << \"END: The GIL state is \" << PyGILState_Check() <<std::endl;\n\t// py::cast(results)\n\n\t// vector< py::array_t< double > > output(cover_sets.size());\n\t// for (size_t j = 0; j < cover_sets.size(); ++j){\n\t// \toutput[j] = carma::mat_to_arr(results[j], true);\n\t// }\n\t// return(output);\n\treturn(results);\n\t// return(py::list(1));\n}\n\n\n\nPYBIND11_MODULE(landmark, m) {\n\tm.def(\"maxmin\", &maxmin, \"finds maxmin landmarks\");\n\tm.def(\"do_parallel\", [](size_t n_threads) -> py::array_t< double > {\n\t\t/* Release GIL before calling into (potentially long-running) C++ code */\n\t\tpy::gil_scoped_release release;\n\t\tvector< double > res = spawnThreads(n_threads);\n\t\tpy::gil_scoped_acquire acquire;\n\t\treturn(carma::col_to_arr(arma::vec(res)));\n\t});\n\tm.def(\"cmds\", [](const py::array_t< double >& X, const size_t d) -> py::array_t< double > {\n\t\tconst arma::mat D = carma::arr_to_mat< double >(X);\n\t\tarma::mat emb; \n\t\tcmds(D, d, emb);\n\t\treturn carma::mat_to_arr(emb);\n\t});\n\t// void parallel_mds(const py::array_t< double >& x, const py::list& cover_sets, const size_t d){\n\tm.def(\"parallel_cmds\", parallel_mds);\n\tm.def(\"parallel_mds_blocks\", parallel_mds_blocks);\n\tm.def(\"dist_matrix\", [](const py::array_t< double >& x) -> py::array_t< double > {\n\t\tconst arma::mat X = carma::arr_to_mat(x).t();\n\t\tarma::mat D = arma::mat(X.n_cols, X.n_cols, arma::fill::zeros);\n\t\tdist_matrix(X, D);\n\t\treturn(carma::mat_to_arr(D));\n\t});\n};\n\n", "meta": {"hexsha": "444e1828670a4910d93d5d3a0147ba498440a6cb", "size": 18410, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tallem/extensions/landmark.cpp", "max_stars_repo_name": "peekxc/tallem", "max_stars_repo_head_hexsha": "949af20c1f50f9b6784ee32463e59123cd64294b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/tallem/extensions/landmark.cpp", "max_issues_repo_name": "peekxc/tallem", "max_issues_repo_head_hexsha": "949af20c1f50f9b6784ee32463e59123cd64294b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tallem/extensions/landmark.cpp", "max_forks_repo_name": "peekxc/tallem", "max_forks_repo_head_hexsha": "949af20c1f50f9b6784ee32463e59123cd64294b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-07-25T04:58:58.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-25T04:58:58.000Z", "avg_line_length": 38.3541666667, "max_line_length": 174, "alphanum_fraction": 0.6568169473, "num_tokens": 5442, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321964553657, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.4562814820206814}}
{"text": "/*******************************************************************************\n * Array expansion domain\n *\n * For a given array, map sequences of consecutive bytes to cells\n * consisting of a triple <offset, size, var> where:\n *\n * - offset is an unsigned number\n * - size  is an unsigned number\n * - var is a scalar variable that represents the content of\n *   a[offset,...,offset+size-1]\n *\n * The domain is general enough to represent any possible sequence of\n * consecutive bytes including sequences of bytes starting at the same\n * offsets but different sizes, overlapping sequences starting at\n * different offsets, etc. However, there are some cases that have\n * been implemented an imprecise manner:\n *\n * (1) array store/load with a non-constant index are conservatively ignored.\n * (2) array load from a cell that overlaps with other cells return top.\n ******************************************************************************/\n\n#pragma once\n\n#include <crab/common/debug.hpp>\n#include <crab/common/stats.hpp>\n#include <crab/common/types.hpp>\n#include <crab/domains/abstract_domain.hpp>\n#include <crab/domains/abstract_domain_specialized_traits.hpp>\n\n#include <crab/domains/interval.hpp>\n#include <crab/domains/patricia_trees.hpp>\n\n#include <algorithm>\n#include <boost/optional.hpp>\n#include <set>\n#include <unordered_map>\n#include <vector>\n\nnamespace crab {\nnamespace domains {\n\n// forward declarations\ntemplate <typename Variable> class offset_map;\ntemplate <typename Domain> class array_expansion_domain;\n\n// wrapper for using ikos::index_t as patricia_tree keys\nclass offset_t {\n  ikos::index_t _val;\n\npublic:\n  explicit offset_t(ikos::index_t v) : _val(v) {}\n\n  ikos::index_t index() const { return _val; }\n\n  bool operator<(const offset_t &o) const { return _val < o._val; }\n\n  bool operator==(const offset_t &o) const { return _val == o._val; }\n\n  bool operator!=(const offset_t &o) const { return !(*this == o); }\n\n  void write(crab::crab_os &o) const { o << _val; }\n\n  friend crab::crab_os &operator<<(crab::crab_os &o, const offset_t &v) {\n    v.write(o);\n    return o;\n  }\n};\n\n/*\n *  A synthetic cell is used to give a symbolic name to the byte\n *  contents of some array segment. The symbolic name is m_scalar\n *  while the array segment is represented by\n *        [m_offset, m_offset+1,...,m_offset+m_size-1]\n */\ntemplate <typename Variable> class cell {\nprivate:\n  friend class offset_map<Variable>;\n  typedef cell<Variable> cell_t;\n  typedef ikos::interval<typename Variable::number_t> interval_t;\n\n  offset_t _offset;\n  uint64_t _size;\n  boost::optional<Variable> _scalar;\n\n  // Only offset_map<Variable> can create cells\n  cell() : _offset(0), _size(0), _scalar(boost::optional<Variable>()) {}\n  cell(offset_t offset, Variable scalar)\n      : _offset(offset), _size(scalar.get_bitwidth()), _scalar(scalar) {}\n\n  cell(offset_t offset, uint64_t size)\n      : _offset(offset), _size(size), _scalar(boost::optional<Variable>()) {}\n\n  static interval_t to_interval(const offset_t o, uint64_t size) {\n    interval_t i(o.index(), o.index() + size - 1);\n    return i;\n  }\n\n  interval_t to_interval() const {\n    return to_interval(get_offset(), get_size());\n  }\n\npublic:\n  bool is_null() const { return (_offset.index() == 0 && _size == 0); }\n\n  offset_t get_offset() const { return _offset; }\n\n  size_t get_size() const { return _size; }\n\n  bool has_scalar() const { return (bool)_scalar; }\n\n  Variable get_scalar() const {\n    if (!has_scalar()) {\n      CRAB_ERROR(\"cannot get undefined scalar variable\");\n    }\n    return *_scalar;\n  }\n\n  // inclusion test\n  bool operator<=(const cell_t &o) const {\n    interval_t x = to_interval();\n    interval_t y = o.to_interval();\n    return x <= y;\n  }\n\n  // ignore the scalar variable\n  bool operator==(const cell_t &o) const {\n    return (get_offset() == o.get_offset() && get_size() == o.get_size());\n  }\n\n  // ignore the scalar variable\n  bool operator<(const cell_t &o) const {\n    if (get_offset() < o.get_offset()) {\n      return true;\n    } else if (get_offset() == o.get_offset()) {\n      return get_size() < o.get_size();\n    } else {\n      return false;\n    }\n  }\n\n  // Return true if [o, o+size) definitely overlaps with the cell,\n  // where o is a constant expression.\n  bool overlap(const offset_t &o, uint64_t size) const {\n    interval_t x = to_interval();\n    interval_t y = to_interval(o, size);\n    bool res = (!(x & y).is_bottom());\n    CRAB_LOG(\"array-expansion-overlap\", crab::outs() << \"**Checking if \" << x\n                                                     << \" overlaps with \" << y\n                                                     << \"=\" << res << \"\\n\";);\n    return res;\n  }\n\n  // Return true if [symb_lb, symb_ub] may overlap with the cell,\n  // where symb_lb and symb_ub are not constant expressions.\n  template <typename Dom>\n  bool symbolic_overlap(const typename Dom::linear_expression_t &symb_lb,\n                        const typename Dom::linear_expression_t &symb_ub,\n                        const Dom &dom) const {\n    typedef typename Dom::linear_expression_t linear_expression_t;\n    typedef typename Dom::number_t number_t;\n\n    interval_t x = to_interval();\n    assert(x.lb().is_finite());\n    assert(x.ub().is_finite());\n    linear_expression_t lb(*(x.lb().number()));\n    linear_expression_t ub(*(x.ub().number()));\n\n    CRAB_LOG(\"array-expansion-overlap\", Dom tmp(dom);\n             linear_expression_t tmp_symb_lb(symb_lb);\n             linear_expression_t tmp_symb_ub(symb_ub);\n             crab::outs() << \"**Checking if \" << *this\n                          << \" overlaps with symbolic \"\n                          << \"[\" << tmp_symb_lb << \",\" << tmp_symb_ub << \"]\"\n                          << \" with abstract state=\" << tmp << \"\\n\";);\n\n    Dom tmp1(dom);\n    tmp1 += (lb >= symb_lb);\n    tmp1 += (lb <= symb_ub);\n    if (!tmp1.is_bottom()) {\n      CRAB_LOG(\"array-expansion-overlap\", crab::outs() << \"\\tyes.\\n\";);\n      return true;\n    }\n\n    Dom tmp2(dom);\n    tmp2 += (ub >= symb_lb);\n    tmp2 += (ub <= symb_ub);\n    if (!tmp2.is_bottom()) {\n      CRAB_LOG(\"array-expansion-overlap\", crab::outs() << \"\\tyes.\\n\";);\n      return true;\n    }\n\n    CRAB_LOG(\"array-expansion-overlap\", crab::outs() << \"\\tno.\\n\";);\n    return false;\n  }\n\n  void write(crab::crab_os &o) const {\n    o << to_interval() << \" -> \";\n    if (has_scalar()) {\n      o << get_scalar();\n    } else {\n      o << \"_\";\n    }\n  }\n\n  friend crab::crab_os &operator<<(crab::crab_os &o, const cell_t &c) {\n    c.write(o);\n    return o;\n  }\n};\n\nnamespace cell_set_impl {\ntemplate <typename Set> inline Set set_intersection(Set &s1, Set &s2) {\n  Set s3;\n  std::set_intersection(s1.begin(), s1.end(), s2.begin(), s2.end(),\n                        std::inserter(s3, s3.end()));\n  return s3;\n}\n\ntemplate <typename Set> inline Set set_union(Set &s1, Set &s2) {\n  Set s3;\n  std::set_union(s1.begin(), s1.end(), s2.begin(), s2.end(),\n                 std::inserter(s3, s3.end()));\n  return s3;\n}\n\ntemplate <typename Set> inline bool set_inclusion(Set &s1, Set &s2) {\n  Set s3;\n  std::set_difference(s1.begin(), s1.end(), s2.begin(), s2.end(),\n                      std::inserter(s3, s3.end()));\n  return s3.empty();\n}\n} // namespace cell_set_impl\n\n// Map offsets to cells\ntemplate <typename Variable> class offset_map {\npublic:\n  typedef cell<Variable> cell_t;\n\nprivate:\n  template <typename Dom> friend class array_expansion_domain;\n\n  typedef offset_map<Variable> offset_map_t;\n  typedef std::set<cell_t> cell_set_t;\n  typedef crab::variable_type type_t;\n\n  /*\n    The keys in the patricia tree are processing in big-endian\n    order. This means that the keys are sorted. Sortedeness is\n    very important to perform efficiently operations such as\n    checking for overlap cells. Since keys are treated as bit\n    patterns, negative offsets can be used but they are treated\n    as large unsigned numbers.\n  */\n  typedef patricia_tree<offset_t, cell_set_t> patricia_tree_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  patricia_tree_t _map;\n\n  // global state to map the same triple of array, offset and size\n  // to same index\n  static std::map<std::pair<ikos::index_t, std::pair<offset_t, uint64_t>>,\n                  ikos::index_t>\n      s_index_map;\n\n  // for algorithm::lower_bound and algorithm::upper_bound\n  struct compare_binding_t {\n    bool operator()(const typename patricia_tree_t::binding_t &kv,\n                    const offset_t &o) const {\n      return kv.first < o;\n    }\n    bool operator()(const offset_t &o,\n                    const typename patricia_tree_t::binding_t &kv) const {\n      return o < kv.first;\n    }\n    bool operator()(const typename patricia_tree_t::binding_t &kv1,\n                    const typename patricia_tree_t::binding_t &kv2) const {\n      return kv1.first < kv2.first;\n    }\n  };\n\n  patricia_tree_t apply_operation(binary_op_t &o, patricia_tree_t t1,\n                                  patricia_tree_t t2) {\n    t1.merge_with(t2, o);\n    return t1;\n  }\n\n  class join_op : public binary_op_t {\n    // apply is called when two bindings (one each from a\n    // different map) have the same key(i.e., offset).\n    std::pair<bool, boost::optional<cell_set_t>> apply(cell_set_t x,\n                                                       cell_set_t y) {\n      return {false, cell_set_impl::set_union(x, y)};\n    }\n    // if one map does not have a key in the other map we add it.\n    bool default_is_absorbing() { return false; }\n  };\n\n  class meet_op : public binary_op_t {\n    std::pair<bool, boost::optional<cell_set_t>> apply(cell_set_t x,\n                                                       cell_set_t y) {\n      return {false, cell_set_impl::set_intersection(x, y)};\n    }\n    // if one map does not have a key in the other map we ignore\n    // it.\n    bool default_is_absorbing() { return true; }\n  };\n\n  class domain_po : public partial_order_t {\n    bool leq(cell_set_t x, cell_set_t y) {\n      return cell_set_impl::set_inclusion(x, y);\n    }\n    // default value is bottom (i.e., empty map)\n    bool default_is_top() { return false; }\n  }; // class domain_po\n\n  void remove_cell(const cell_t &c) {\n    if (boost::optional<cell_set_t> cells = _map.lookup(c.get_offset())) {\n      if ((*cells).erase(c) > 0) {\n        _map.remove(c.get_offset());\n        if (!(*cells).empty()) {\n          // a bit of a waste ...\n          _map.insert(c.get_offset(), *cells);\n        }\n      }\n    }\n  }\n\n  void insert_cell(const cell_t &c, bool sanity_check = true) {\n    if (sanity_check && !c.has_scalar()) {\n      CRAB_ERROR(\n          \"array expansion cannot insert a cell without scalar variable\");\n    }\n    if (boost::optional<cell_set_t> cells = _map.lookup(c.get_offset())) {\n      if ((*cells).insert(c).second) {\n        // a bit of a waste ...\n        _map.remove(c.get_offset());\n        _map.insert(c.get_offset(), *cells);\n      }\n    } else {\n      cell_set_t new_cells;\n      new_cells.insert(c);\n      _map.insert(c.get_offset(), new_cells);\n    }\n  }\n\n  cell_t get_cell(offset_t o, uint64_t size) const {\n    if (boost::optional<cell_set_t> cells = _map.lookup(o)) {\n      cell_t tmp(o, size);\n      auto it = (*cells).find(tmp);\n      if (it != (*cells).end()) {\n        return *it;\n      }\n    }\n    // not found\n    return cell_t();\n  }\n\n  static std::string mk_scalar_name(Variable a, offset_t o, uint64_t size) {\n    crab::crab_string_os os;\n    os << a << \"[\";\n    if (size == 1) {\n      os << o;\n    } else {\n      os << o << \"...\" << o.index() + size - 1;\n    }\n    os << \"]\";\n    return os.str();\n  }\n\n  static type_t get_array_element_type(type_t array_type) {\n    if (array_type == ARR_BOOL_TYPE) {\n      return BOOL_TYPE;\n    } else if (array_type == ARR_INT_TYPE) {\n      return INT_TYPE;\n    } else if (array_type == ARR_REAL_TYPE) {\n      return REAL_TYPE;\n    } else {\n      assert(array_type == ARR_PTR_TYPE);\n      return PTR_TYPE;\n    }\n  }\n\n  ikos::index_t get_index(Variable a, offset_t o, uint64_t size) {\n    auto it = s_index_map.find({a.index(), {o, size}});\n    if (it != s_index_map.end()) {\n      return it->second;\n    } else {\n      ikos::index_t res = s_index_map.size();\n      s_index_map.insert({{a.index(), {o, size}}, res});\n      return res;\n    }\n  }\n\n  cell_t mk_cell(Variable array, offset_t o, uint64_t size) {\n    // TODO: check array is the array associated to this offset map\n\n    cell_t c = get_cell(o, size);\n    if (c.is_null()) {\n      auto &vfac = array.name().get_var_factory();\n      std::string vname = mk_scalar_name(array, o, size);\n      type_t vtype = get_array_element_type(array.get_type());\n      // create a new scalar variable for representing the contents\n      // of bytes array[o,o+1,..., o+size-1]\n      ikos::index_t vindex = get_index(array, o, size);\n      Variable scalar_var(vfac.get(vindex, vname), vtype, size);\n      c = cell_t(o, scalar_var);\n      insert_cell(c);\n      CRAB_LOG(\"array-expansion\", crab::outs()\n                                      << \"**Created cell \" << c << \"\\n\";);\n    }\n    // sanity check\n    if (!c.has_scalar()) {\n      CRAB_ERROR(\"array expansion created a new cell without a scalar\");\n    }\n    return c;\n  }\n\n  offset_map(patricia_tree_t &&m) : _map(std::move(m)) {}\n\npublic:\n  offset_map() {}\n\n  bool empty() const { return _map.empty(); }\n\n  std::size_t size() const { return _map.size(); }\n\n  // leq operator\n  bool operator<=(const offset_map_t &o) const {\n    domain_po po;\n    return _map.leq(o._map, po);\n  }\n\n  // set union: if two cells with same offset do not agree on\n  // size then they are ignored.\n  offset_map_t operator|(const offset_map_t &o) {\n    join_op op;\n    return offset_map_t(apply_operation(op, _map, o._map));\n  }\n\n  // set intersection: if two cells with same offset do not agree\n  // on size then they are ignored.\n  offset_map_t operator&(const offset_map_t &o) {\n    meet_op op;\n    return offset_map_t(apply_operation(op, _map, o._map));\n  }\n\n  void operator-=(const cell_t &c) { remove_cell(c); }\n\n  void operator-=(const std::vector<cell_t> &cells) {\n    for (unsigned i = 0, e = cells.size(); i < e; ++i) {\n      this->operator-=(cells[i]);\n    }\n  }\n\n  std::vector<cell_t> get_all_cells() const {\n    std::vector<cell_t> res;\n    for (auto it = _map.begin(), et = _map.end(); it != et; ++it) {\n      auto const &o_cells = it->second;\n      for (auto &c : o_cells) {\n        res.push_back(c);\n      }\n    }\n    return res;\n  }\n\n  // Return in out all cells that might overlap with (o, size).\n  void get_overlap_cells(offset_t o, uint64_t size, std::vector<cell_t> &out) {\n    compare_binding_t comp;\n\n    bool added = false;\n    cell_t c = get_cell(o, size);\n    if (c.is_null()) {\n      // we need to add a temporary cell for (o, size)\n      c = cell_t(o, size);\n      insert_cell(c, false /*disable sanity check*/);\n      added = true;\n    }\n\n    auto lb_it = std::lower_bound(_map.begin(), _map.end(), o, comp);\n    if (lb_it != _map.end()) {\n      // Store _map[begin,...,lb_it] into a vector so that we can\n      // go backwards from lb_it.\n      //\n      // TODO: give support for reverse iterator in patricia_tree.\n      std::vector<cell_set_t> upto_lb;\n      upto_lb.reserve(std::distance(_map.begin(), lb_it));\n      for (auto it = _map.begin(), et = lb_it; it != et; ++it) {\n        upto_lb.push_back(it->second);\n      }\n      upto_lb.push_back(lb_it->second);\n\n      for (int i = upto_lb.size() - 1; i >= 0; --i) {\n        ///////\n        // All the cells in upto_lb[i] have the same offset. They\n        // just differ in the size.\n        //\n        // If none of the cells in upto_lb[i] overlap with (o, size)\n        // we can stop.\n        ////////\n        bool continue_outer_loop = false;\n        for (const cell_t &x : upto_lb[i]) {\n          if (x.overlap(o, size)) {\n            if (!(x == c)) {\n              // FIXME: we might have some duplicates. this is a very drastic\n              // solution.\n              if (std::find(out.begin(), out.end(), x) == out.end()) {\n                out.push_back(x);\n              }\n            }\n            continue_outer_loop = true;\n          }\n        }\n        if (!continue_outer_loop) {\n          break;\n        }\n      }\n    }\n\n    // search for overlapping cells > o\n    auto ub_it = std::upper_bound(_map.begin(), _map.end(), o, comp);\n    for (; ub_it != _map.end(); ++ub_it) {\n      bool continue_outer_loop = false;\n      for (const cell_t &x : ub_it->second) {\n        if (x.overlap(o, size)) {\n          // FIXME: we might have some duplicates. this is a very drastic\n          // solution.\n          if (std::find(out.begin(), out.end(), x) == out.end()) {\n            out.push_back(x);\n          }\n          continue_outer_loop = true;\n        }\n      }\n      if (!continue_outer_loop) {\n        break;\n      }\n    }\n\n    // do not forget the rest of overlapping cells == o\n    for (auto it = ++lb_it, et = ub_it; it != et; ++it) {\n      bool continue_outer_loop = false;\n      for (const cell_t &x : it->second) {\n        if (x == c) { // we dont put it in out\n          continue;\n        }\n        if (x.overlap(o, size)) {\n          if (!(x == c)) {\n            if (std::find(out.begin(), out.end(), x) == out.end()) {\n              out.push_back(x);\n            }\n          }\n          continue_outer_loop = true;\n        }\n      }\n      if (!continue_outer_loop) {\n        break;\n      }\n    }\n\n    if (added) {\n      // remove the temporary cell for (o, size)\n      assert(!c.is_null());\n      remove_cell(c);\n    }\n\n    CRAB_LOG(\n        \"array-expansion-overlap\", crab::outs()\n                                       << \"**Overlap set between \\n\"\n                                       << *this << \"\\nand \"\n                                       << \"(\" << o << \",\" << size << \")={\";\n        for (unsigned i = 0, e = out.size(); i < e;) {\n          crab::outs() << out[i];\n          ++i;\n          if (i < e) {\n            crab::outs() << \",\";\n          }\n        } crab::outs()\n        << \"}\\n\";);\n  }\n\n  template <typename Dom>\n  void get_overlap_cells_symbolic_offset(\n      const Dom &dom, const typename Dom::linear_expression_t &symb_lb,\n      const typename Dom::linear_expression_t &symb_ub,\n      std::vector<cell_t> &out) const {\n\n    for (auto it = _map.begin(), et = _map.end(); it != et; ++it) {\n      const cell_set_t &o_cells = it->second;\n      // All cells in o_cells have the same offset. They only differ\n      // in the size. If the largest cell overlaps with [offset,\n      // offset + size) then the rest of cells are considered to\n      // overlap. This is an over-approximation because [offset,\n      // offset+size) can overlap with the largest cell but it\n      // doesn't necessarily overlap with smaller cells. For\n      // efficiency, we assume it overlaps with all.\n      cell_t largest_cell;\n      for (auto &c : o_cells) {\n        if (largest_cell.is_null()) {\n          largest_cell = c;\n        } else {\n          assert(c.get_offset() == largest_cell.get_offset());\n          if (largest_cell < c) {\n            largest_cell = c;\n          }\n        }\n      }\n      if (!largest_cell.is_null()) {\n        if (largest_cell.symbolic_overlap(symb_lb, symb_ub, dom)) {\n          for (auto &c : o_cells) {\n            out.push_back(c);\n          }\n        }\n      }\n    }\n  }\n\n  void write(crab::crab_os &o) const {\n    if (_map.empty()) {\n      o << \"empty\";\n    } else {\n      for (auto it = _map.begin(), et = _map.end(); it != et; ++it) {\n        const cell_set_t &cells = it->second;\n        o << \"{\";\n        for (auto cit = cells.begin(), cet = cells.end(); cit != cet;) {\n          o << *cit;\n          ++cit;\n          if (cit != cet) {\n            o << \",\";\n          }\n        }\n        o << \"}\\n\";\n      }\n    }\n  }\n\n  friend crab::crab_os &operator<<(crab::crab_os &o, const offset_map_t &m) {\n    m.write(o);\n    return o;\n  }\n\n  /* Operations needed if used as value in a patricia tree */\n  bool operator==(const offset_map_t &o) const {\n    return *this <= o && o <= *this;\n  }\n  bool is_top() const { return empty(); }\n  bool is_bottom() const { return false; }\n  /*\n     a patricia tree only calls bottom if operator[] is called over\n     a bottom state. Thus, we will make sure that we don't call\n     operator[] in that case.\n  */\n  static offset_map_t bottom() {\n    CRAB_ERROR(\"offset_map::bottom() cannot be called\");\n  }\n  static offset_map_t top() { return offset_map_t(); }\n};\n\ntemplate <typename Var>\nstd::map<std::pair<ikos::index_t, std::pair<offset_t, uint64_t>>, ikos::index_t>\n    offset_map<Var>::s_index_map;\n\ntemplate <typename NumDomain>\nclass array_expansion_domain final\n    : public abstract_domain<array_expansion_domain<NumDomain>> {\n\npublic:\n  typedef typename NumDomain::number_t number_t;\n  typedef typename NumDomain::varname_t varname_t;\n\nprivate:\n  typedef array_expansion_domain<NumDomain> array_expansion_domain_t;\n  typedef abstract_domain<array_expansion_domain_t> abstract_domain_t;\n\npublic:\n  using typename abstract_domain_t::disjunctive_linear_constraint_system_t;\n  using typename abstract_domain_t::linear_constraint_system_t;\n  using typename abstract_domain_t::linear_constraint_t;\n  using typename abstract_domain_t::linear_expression_t;\n  using typename abstract_domain_t::variable_t;\n  using typename abstract_domain_t::variable_vector_t;\n  typedef crab::pointer_constraint<variable_t> ptr_cst_t;\n  typedef NumDomain content_domain_t;\n  typedef interval<number_t> interval_t;\n\nprivate:\n  typedef bound<number_t> bound_t;\n  typedef crab::variable_type type_t;\n  typedef offset_map<variable_t> offset_map_t;\n  typedef cell<variable_t> cell_t;\n  typedef std::unordered_map<variable_t, offset_map_t> array_map_t;\n\n  // scalar domain\n  NumDomain _inv;\n\n  // We use a global array map\n  static array_map_t &get_array_map() {\n    static array_map_t *array_map = new array_map_t();\n    return *array_map;\n  }\n\npublic:\n  /**\n      Ugly this needs to be fixed: needed if multiple analyses are\n      run so we can clear the array map from one run to another.\n  **/\n  static void clear_global_state() {\n    array_map_t &map = get_array_map();\n    if (!map.empty()) {\n      if (::crab::CrabSanityCheckFlag) {\n        CRAB_WARN(\"array_expansion static variable map is being cleared\");\n      }\n      map.clear();\n    }\n  }\n\nprivate:\n  void remove_array_map(const variable_t &v) {\n    /// We keep the array map as global so we don't remove any entry.\n    // array_map_t& map = get_array_map();\n    // map.erase(v);\n  }\n\n  offset_map_t &lookup_array_map(const variable_t &v) {\n    array_map_t &map = get_array_map();\n    return map[v];\n  }\n\n  array_expansion_domain(NumDomain inv) : _inv(inv) {}\n\n  interval_t to_interval(linear_expression_t expr, NumDomain inv) {\n    interval_t r(expr.constant());\n    for (typename linear_expression_t::iterator it = expr.begin();\n         it != expr.end(); ++it) {\n      interval_t c(it->first);\n      r += c * inv[it->second];\n    }\n    return r;\n  }\n\n  interval_t to_interval(linear_expression_t expr) {\n    return to_interval(expr, _inv);\n  }\n\n  void kill_cells(const std::vector<cell_t> &cells, offset_map_t &offset_map) {\n    if (!cells.empty()) {\n      // Forget the scalars from the numerical domain\n      for (unsigned i = 0, e = cells.size(); i < e; ++i) {\n        const cell_t &c = cells[i];\n        if (c.has_scalar()) {\n          _inv -= c.get_scalar();\n        } else {\n          CRAB_ERROR(\n              \"array expansion: cell without scalar variable in array store\");\n        }\n      }\n      // Remove the cells. If needed again they they will be re-created.\n      offset_map -= cells;\n    }\n  }\n\n  // Helper that assign rhs to lhs by switching to the version with\n  // the right type.\n  void do_assign(variable_t lhs, variable_t rhs) {\n    if (lhs.get_type() != rhs.get_type()) {\n      CRAB_ERROR(\"array_adaptive assignment with different types\");\n    }\n    switch (lhs.get_type()) {\n    case BOOL_TYPE:\n      _inv.assign_bool_var(lhs, rhs, false);\n      break;\n    case INT_TYPE:\n    case REAL_TYPE:\n      _inv.assign(lhs, rhs);\n      break;\n    case PTR_TYPE:\n      _inv.pointer_assign(lhs, rhs, number_t(0));\n      break;\n    default:;\n      CRAB_ERROR(\"array_adaptive assignment with unexpected type\");\n    }\n  }\n\n  // helper to assign a cell into a variable\n  void do_assign(variable_t lhs, cell_t rhs_c) {\n    if (!rhs_c.has_scalar()) {\n      CRAB_ERROR(\"array_adaptive cell without scalar\");\n    }\n    variable_t rhs = rhs_c.get_scalar();\n    do_assign(lhs, rhs);\n  }\n\n  // helper to assign a linear expression into a cell\n  void do_assign(cell_t lhs_c, linear_expression_t v) {\n    if (!lhs_c.has_scalar()) {\n      CRAB_ERROR(\"array_adaptive cell without scalar\");\n    }\n    variable_t lhs = lhs_c.get_scalar();\n    switch (lhs.get_type()) {\n    case BOOL_TYPE:\n      if (v.is_constant()) {\n        if (v.constant() >= number_t(1)) {\n          _inv.assign_bool_cst(lhs, linear_constraint_t::get_true());\n        } else {\n          _inv.assign_bool_cst(lhs, linear_constraint_t::get_false());\n        }\n      } else if (auto var = v.get_variable()) {\n        _inv.assign_bool_var(lhs, (*var), false);\n      }\n      break;\n    case INT_TYPE:\n    case REAL_TYPE:\n      _inv.assign(lhs, v);\n      break;\n    case PTR_TYPE:\n      if (v.is_constant() && v.constant() == number_t(0)) {\n        _inv.pointer_mk_null(lhs);\n      } else if (auto var = v.get_variable()) {\n        _inv.pointer_assign(lhs, (*var), number_t(0));\n      }\n      break;\n    default:;\n      CRAB_ERROR(\"array_adaptive assignment with unexpected type\");\n    }\n  }\n\n  // Helper that assign backward rhs to lhs by switching to the\n  // version with the right type.\n  void do_backward_assign(variable_t lhs, variable_t rhs,\n                          content_domain_t &dom) {\n    if (lhs.get_type() != rhs.get_type()) {\n      CRAB_ERROR(\"array_adaptive backward assignment with different types\");\n    }\n    switch (lhs.get_type()) {\n    case BOOL_TYPE:\n      _inv.backward_assign_bool_var(lhs, rhs, false, dom);\n      break;\n    case INT_TYPE:\n    case REAL_TYPE:\n      _inv.backward_assign(lhs, rhs, dom);\n      break;\n    case PTR_TYPE:\n      CRAB_WARN(\"array_adaptive backward pointer assignment not implemented\");\n      break;\n    default:;\n      CRAB_ERROR(\"array_adaptive backward_assignment with unexpected type\");\n    }\n  }\n\n  // helper to assign backward a cell into a variable\n  void do_backward_assign(variable_t lhs, cell_t rhs_c, content_domain_t &dom) {\n    if (!rhs_c.has_scalar()) {\n      CRAB_ERROR(\"array_adaptive cell without scalar\");\n    }\n    variable_t rhs = rhs_c.get_scalar();\n    do_backward_assign(lhs, rhs, dom);\n  }\n\n  // helper to assign backward a linear expression into a cell\n  void do_backward_assign(cell_t lhs_c, linear_expression_t v,\n                          content_domain_t &dom) {\n    if (!lhs_c.has_scalar()) {\n      CRAB_ERROR(\"array_adaptive cell without scalar\");\n    }\n    variable_t lhs = lhs_c.get_scalar();\n    switch (lhs.get_type()) {\n    case BOOL_TYPE:\n      if (v.is_constant()) {\n        if (v.constant() >= number_t(1)) {\n          _inv.backward_assign_bool_cst(lhs, linear_constraint_t::get_true(),\n                                        dom);\n        } else {\n          _inv.backward_assign_bool_cst(lhs, linear_constraint_t::get_false(),\n                                        dom);\n        }\n      } else if (auto var = v.get_variable()) {\n        _inv.backward_assign_bool_var(lhs, (*var), false, dom);\n      }\n      break;\n    case INT_TYPE:\n    case REAL_TYPE:\n      _inv.backward_assign(lhs, v, dom);\n      break;\n    case PTR_TYPE:\n      CRAB_WARN(\"array_adaptive backward pointer assignment not implemented\");\n      break;\n    default:;\n      CRAB_ERROR(\"array_adaptive backward assignment with unexpected type\");\n    }\n  }\n\npublic:\n  array_expansion_domain() : _inv(NumDomain::top()) {}\n\n  void set_to_top() {\n    array_expansion_domain abs(NumDomain::top());\n    std::swap(*this, abs);\n  }\n\n  void set_to_bottom() {\n    array_expansion_domain abs(NumDomain::bottom());\n    std::swap(*this, abs);\n  }\n\n  array_expansion_domain(const array_expansion_domain_t &other)\n      : _inv(other._inv) {\n    crab::CrabStats::count(getDomainName() + \".count.copy\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".copy\");\n  }\n\n  array_expansion_domain(const array_expansion_domain_t &&other)\n      : _inv(std::move(other._inv)) {\n    crab::CrabStats::count(getDomainName() + \".count.copy\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".copy\");\n  }\n\n  array_expansion_domain_t &operator=(const array_expansion_domain_t &other) {\n    crab::CrabStats::count(getDomainName() + \".count.copy\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".copy\");\n    if (this != &other) {\n      _inv = other._inv;\n    }\n    return *this;\n  }\n\n  array_expansion_domain_t &operator=(const array_expansion_domain_t &&other) {\n    crab::CrabStats::count(getDomainName() + \".count.copy\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".copy\");\n    if (this != &other) {\n      _inv = std::move(other._inv);\n    }\n    return *this;\n  }\n\n  bool is_bottom() { return (_inv.is_bottom()); }\n\n  bool is_top() { return (_inv.is_top()); }\n\n  bool operator<=(array_expansion_domain_t other) {\n    crab::CrabStats::count(getDomainName() + \".count.leq\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".leq\");\n\n    return (_inv <= other._inv);\n  }\n\n  bool operator==(array_expansion_domain_t other) {\n    return (_inv <= other._inv && other._inv <= _inv);\n  }\n\n  void operator|=(array_expansion_domain_t other) {\n    crab::CrabStats::count(getDomainName() + \".count.join\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".join\");\n    _inv |= other._inv;\n  }\n\n  array_expansion_domain_t operator|(array_expansion_domain_t other) {\n    crab::CrabStats::count(getDomainName() + \".count.join\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".join\");\n    return array_expansion_domain_t(_inv | other._inv);\n  }\n\n  array_expansion_domain_t operator&(array_expansion_domain_t other) {\n    crab::CrabStats::count(getDomainName() + \".count.meet\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".meet\");\n\n    return array_expansion_domain_t(_inv & other._inv);\n  }\n\n  array_expansion_domain_t operator||(array_expansion_domain_t other) {\n    crab::CrabStats::count(getDomainName() + \".count.widening\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".widening\");\n\n    return array_expansion_domain_t(_inv || other._inv);\n  }\n\n  array_expansion_domain_t\n  widening_thresholds(array_expansion_domain_t other,\n                      const iterators::thresholds<number_t> &ts) {\n    crab::CrabStats::count(getDomainName() + \".count.widening\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".widening\");\n    return array_expansion_domain_t(_inv.widening_thresholds(other._inv, ts));\n  }\n\n  array_expansion_domain_t operator&&(array_expansion_domain_t other) {\n    crab::CrabStats::count(getDomainName() + \".count.narrowing\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".narrowing\");\n    return array_expansion_domain_t(_inv && other._inv);\n  }\n\n  void forget(const variable_vector_t &variables) {\n    crab::CrabStats::count(getDomainName() + \".count.forget\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".forget\");\n\n    if (is_bottom() || is_top()) {\n      return;\n    }\n\n    _inv.forget(variables);\n\n    for (variable_t v : variables) {\n      if (v.is_array_type()) {\n        remove_array_map(v);\n      }\n    }\n  }\n\n  void project(const variable_vector_t &variables) {\n    CRAB_WARN(\"array expansion project not implemented\");\n  }\n\n  void expand(variable_t var, variable_t new_var) {\n    CRAB_WARN(\"array expansion expand not implemented\");\n  }\n\n  void normalize() { CRAB_WARN(\"array expansion normalize not implemented\"); }\n\n  void minimize() { _inv.minimize(); }\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\n    _inv += csts;\n\n    CRAB_LOG(\"array-expansion\",\n             crab::outs() << \"assume(\" << csts << \")  \" << *this << \"\\n\";);\n  }\n\n  void operator-=(variable_t var) {\n    crab::CrabStats::count(getDomainName() + \".count.forget\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".forget\");\n\n    if (var.is_array_type()) {\n      remove_array_map(var);\n    } else {\n      _inv -= var;\n    }\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    _inv.assign(x, e);\n\n    CRAB_LOG(\"array-expansion\", crab::outs() << \"apply \" << x << \" := \" << e\n                                             << \" \" << *this << \"\\n\";);\n  }\n\n  void apply(operation_t op, variable_t x, variable_t y, number_t z) {\n    crab::CrabStats::count(getDomainName() + \".count.apply\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".apply\");\n\n    _inv.apply(op, x, y, z);\n\n    CRAB_LOG(\"array-expansion\", crab::outs()\n                                    << \"apply \" << x << \" := \" << y << \" \" << op\n                                    << \" \" << z << \" \" << *this << \"\\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    _inv.apply(op, x, y, z);\n\n    CRAB_LOG(\"array-expansion\", crab::outs()\n                                    << \"apply \" << x << \" := \" << y << \" \" << op\n                                    << \" \" << z << \" \" << *this << \"\\n\";);\n  }\n\n  void backward_assign(variable_t x, linear_expression_t e,\n                       array_expansion_domain_t inv) {\n    _inv.backward_assign(x, e, inv.get_content_domain());\n  }\n\n  void backward_apply(operation_t op, variable_t x, variable_t y, number_t z,\n                      array_expansion_domain_t inv) {\n    _inv.backward_apply(op, x, y, z, inv.get_content_domain());\n  }\n\n  void backward_apply(operation_t op, variable_t x, variable_t y, variable_t z,\n                      array_expansion_domain_t inv) {\n    _inv.backward_apply(op, x, y, z, inv.get_content_domain());\n  }\n\n  void apply(int_conv_operation_t op, variable_t dst, variable_t src) {\n    crab::CrabStats::count(getDomainName() + \".count.apply\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".apply\");\n\n    _inv.apply(op, dst, src);\n  }\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    _inv.apply(op, x, y, z);\n\n    CRAB_LOG(\"array-expansion\", crab::outs()\n                                    << \"apply \" << x << \" := \" << y << \" \" << op\n                                    << \" \" << z << \" \" << *this << \"\\n\";);\n  }\n\n  void apply(bitwise_operation_t op, variable_t x, variable_t y, number_t k) {\n    crab::CrabStats::count(getDomainName() + \".count.apply\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".apply\");\n\n    _inv.apply(op, x, y, k);\n\n    CRAB_LOG(\"array-expansion\", crab::outs()\n                                    << \"apply \" << x << \" := \" << y << \" \" << op\n                                    << \" \" << k << \" \" << *this << \"\\n\";);\n  }\n\n  // boolean operators\n  virtual void assign_bool_cst(variable_t lhs,\n                               linear_constraint_t rhs) override {\n    _inv.assign_bool_cst(lhs, rhs);\n  }\n\n  virtual void assign_bool_var(variable_t lhs, variable_t rhs,\n                               bool is_not_rhs) override {\n    _inv.assign_bool_var(lhs, rhs, is_not_rhs);\n  }\n\n  virtual void apply_binary_bool(bool_operation_t op, variable_t x,\n                                 variable_t y, variable_t z) override {\n    _inv.apply_binary_bool(op, x, y, z);\n  }\n\n  virtual void assume_bool(variable_t v, bool is_negated) override {\n    _inv.assume_bool(v, is_negated);\n  }\n\n  // backward boolean operators\n  virtual void backward_assign_bool_cst(variable_t lhs, linear_constraint_t rhs,\n                                        array_expansion_domain_t inv) {\n    _inv.backward_assign_bool_cst(lhs, rhs, inv.get_content_domain());\n  }\n\n  virtual void backward_assign_bool_var(variable_t lhs, variable_t rhs,\n                                        bool is_not_rhs,\n                                        array_expansion_domain_t inv) {\n    _inv.backward_assign_bool_var(lhs, rhs, is_not_rhs,\n                                  inv.get_content_domain());\n  }\n\n  virtual void backward_apply_binary_bool(bool_operation_t op, variable_t x,\n                                          variable_t y, variable_t z,\n                                          array_expansion_domain_t inv) {\n    _inv.backward_apply_binary_bool(op, x, y, z, inv.get_content_domain());\n  }\n\n  // pointer_operators_api\n  virtual void pointer_load(variable_t lhs, variable_t rhs, linear_expression_t elem_size) override {\n    _inv.pointer_load(lhs, rhs, elem_size);\n  }\n\n  virtual void pointer_store(variable_t lhs, variable_t rhs, linear_expression_t elem_size) override {\n    _inv.pointer_store(lhs, rhs, elem_size);\n  }\n\n  virtual void pointer_assign(variable_t lhs, variable_t rhs,\n                              linear_expression_t offset) override {\n    _inv.pointer_assign(lhs, rhs, offset);\n  }\n\n  virtual void pointer_mk_obj(variable_t lhs, ikos::index_t address) override {\n    _inv.pointer_mk_obj(lhs, address);\n  }\n\n  virtual void pointer_function(variable_t lhs, varname_t func) override {\n    _inv.pointer_function(lhs, func);\n  }\n\n  virtual void pointer_mk_null(variable_t lhs) override {\n    _inv.pointer_mk_null(lhs);\n  }\n\n  virtual void pointer_assume(ptr_cst_t cst) override {\n    _inv.pointer_assume(cst);\n  }\n\n  virtual void pointer_assert(ptr_cst_t cst) override {\n    _inv.pointer_assert(cst);\n  }\n\n  // array_operators_api\n\n  // array_init returns a fresh array where all elements between\n  // lb_idx and ub_idx are initialized to val. Thus, the first thing\n  // we need to do is to kill existing cells.\n  virtual void array_init(variable_t a, linear_expression_t elem_size,\n                          linear_expression_t lb_idx,\n                          linear_expression_t ub_idx,\n                          linear_expression_t val) override {\n    crab::CrabStats::count(getDomainName() + \".count.array_init\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".array_init\");\n\n    if (is_bottom())\n      return;\n\n    offset_map_t &offset_map = lookup_array_map(a);\n    std::vector<cell_t> old_cells = offset_map.get_all_cells();\n    if (!old_cells.empty()) {\n      kill_cells(old_cells, offset_map);\n    }\n\n    array_store_range(a, elem_size, lb_idx, ub_idx, val);\n  }\n\n  virtual void array_load(variable_t lhs, variable_t a,\n                          linear_expression_t elem_size,\n                          linear_expression_t i) override {\n    crab::CrabStats::count(getDomainName() + \".count.array_load\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".array_load\");\n\n    if (is_bottom())\n      return;\n\n    interval_t ii = to_interval(i);\n    if (boost::optional<number_t> n = ii.singleton()) {\n      offset_map_t &offset_map = lookup_array_map(a);\n      offset_t o(static_cast<int64_t>(*n));\n      interval_t i_elem_size = to_interval(elem_size);\n      if (boost::optional<number_t> n_bytes = i_elem_size.singleton()) {\n        assert(static_cast<int64_t>(*n_bytes) > 0 &&\n               static_cast<int64_t>(*n_bytes) <=\n                   std::numeric_limits<uint64_t>::max());\n        uint64_t size = static_cast<int64_t>(*n_bytes);\n        std::vector<cell_t> cells;\n        offset_map.get_overlap_cells(o, size, cells);\n        if (!cells.empty()) {\n          CRAB_WARN(\"Ignored read from cell \", a, \"[\", o, \"...\",\n                    o.index() + size - 1, \"]\", \" because it overlaps with \",\n                    cells.size(), \" cells\");\n          /*\n             TODO: we can apply here \"Value Recomposition\" 'a la'\n             Mine'06 to construct values of some type from a sequence\n             of bytes. It can be endian-independent but it would more\n             precise if we choose between little- and big-endian.\n          */\n        } else {\n          cell_t c = offset_map.mk_cell(a, o, size);\n          assert(c.has_scalar());\n          // Here it's ok to do assignment (instead of expand)\n          // because c is not a summarized variable. Otherwise, it\n          // would be unsound.\n          do_assign(lhs, c);\n          goto array_load_end;\n        }\n      } else {\n        CRAB_ERROR(\n            \"array expansion domain expects constant array element sizes\");\n      }\n    } else {\n      // TODO: we can be more precise here\n      CRAB_WARN(\"array expansion: ignored array load because of non-constant \"\n                \"array index \",\n                i);\n    }\n\n    _inv -= lhs;\n\n  array_load_end:\n    CRAB_LOG(\"array-expansion\", linear_expression_t ub = i + elem_size - 1;\n             crab::outs() << lhs << \":=\" << a << \"[\" << i << \"...\" << ub\n                          << \"]  -- \" << *this << \"\\n\";);\n  }\n\n  virtual void array_store(variable_t a, linear_expression_t elem_size,\n                           linear_expression_t i, linear_expression_t val,\n                           bool /*is_strong_update*/) override {\n    crab::CrabStats::count(getDomainName() + \".count.array_store\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".array_store\");\n\n    if (is_bottom())\n      return;\n\n    interval_t i_elem_size = to_interval(elem_size);\n    boost::optional<number_t> n_bytes = i_elem_size.singleton();\n    if (!n_bytes) {\n      CRAB_ERROR(\"array expansion domain expects constant array element sizes\");\n    }\n\n    assert(static_cast<int64_t>(*n_bytes) > 0 &&\n           static_cast<int64_t>(*n_bytes) <=\n               std::numeric_limits<uint64_t>::max());\n    uint64_t size = static_cast<int64_t>(*n_bytes);\n    offset_map_t &offset_map = lookup_array_map(a);\n    interval_t ii = to_interval(i);\n    if (boost::optional<number_t> n = ii.singleton()) {\n      // -- Constant index: kill overlapping cells + perform strong update\n      std::vector<cell_t> cells;\n      offset_t o(static_cast<int64_t>(*n));\n      offset_map.get_overlap_cells(o, size, cells);\n      if (cells.size() > 0) {\n        CRAB_LOG(\"array-expansion\",\n                 CRAB_WARN(\"Killed \", cells.size(), \" overlapping cells with \",\n                           \"[\", o, \"...\", o.index() + size - 1, \"]\",\n                           \" before writing.\"));\n\n        kill_cells(cells, offset_map);\n      }\n      // Perform scalar update\n      // -- create a new cell it there is no one already\n      cell_t c = offset_map.mk_cell(a, o, size);\n      // -- strong update\n      do_assign(c, val);\n    } else {\n      // -- Non-constant index: kill overlapping cells\n      CRAB_WARN(\"array expansion ignored array write with non-constant index \",\n                i);\n      linear_expression_t symb_lb(i);\n      linear_expression_t symb_ub(i + number_t(size - 1));\n      std::vector<cell_t> cells;\n      offset_map.get_overlap_cells_symbolic_offset(_inv, symb_lb, symb_ub,\n                                                   cells);\n      CRAB_LOG(\n          \"array-expansion\", crab::outs() << \"Killed cells: {\";\n          for (unsigned j = 0; j < cells.size();) {\n            crab::outs() << cells[j];\n            ++j;\n            if (j < cells.size()) {\n              crab::outs() << \",\";\n            }\n          } crab::outs()\n          << \"}\\n\";);\n      kill_cells(cells, offset_map);\n    }\n\n    CRAB_LOG(\"array-expansion\", linear_expression_t ub = i + elem_size - 1;\n             crab::outs() << a << \"[\" << i << \"...\" << ub << \"]:=\" << val\n                          << \" -- \" << *this << \"\\n\";);\n  }\n\n  virtual void array_store(variable_t a_new, variable_t a_old,\n                           linear_expression_t elem_size, linear_expression_t i,\n                           linear_expression_t val,\n                           bool /*is_strong_update*/) override {\n    CRAB_WARN(\"array_store in the array expansion domain not implemented\");\n  }\n\n  // Perform array stores over an array segment [lb_idx, ub_idx]\n  virtual void array_store_range(variable_t a, linear_expression_t elem_size,\n                                 linear_expression_t lb_idx,\n                                 linear_expression_t ub_idx,\n                                 linear_expression_t val) override {\n    crab::CrabStats::count(getDomainName() + \".count.array_store_range\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".array_store_range\");\n\n    // TODO: this should be an user parameter.\n    const number_t max_num_elems = 512;\n\n    if (is_bottom())\n      return;\n\n    interval_t n_i = to_interval(elem_size);\n    auto n = n_i.singleton();\n    if (!n) {\n      CRAB_ERROR(\"array expansion domain expects constant array element sizes\");\n    }\n\n    interval_t lb_i = to_interval(lb_idx);\n    auto lb = lb_i.singleton();\n    if (!lb) {\n      CRAB_WARN(\"array expansion store range ignored because \",\n                \"lower bound is not constant\");\n      return;\n    }\n\n    interval_t ub_i = to_interval(ub_idx);\n    auto ub = ub_i.singleton();\n    if (!ub) {\n      CRAB_WARN(\"array expansion store range ignored because \",\n                \"upper bound is not constant\");\n      return;\n    }\n\n    z_number sz = (*ub - *lb) + 1;\n    if (sz > max_num_elems) {\n      CRAB_WARN(\"array expansion store range ignored because \",\n                \"the number of elements is larger than default limit of \",\n                max_num_elems);\n      return;\n    }\n\n    for (number_t i = *lb, e = *ub; i <= e;) {\n      array_store(a, elem_size, i, val, false);\n      i = i + *n;\n    }\n  }\n\n  virtual void array_store_range(variable_t a_new, variable_t a_old,\n                                 linear_expression_t elem_size,\n                                 linear_expression_t lb_idx,\n                                 linear_expression_t ub_idx,\n                                 linear_expression_t val) override {\n    CRAB_WARN(\n        \"array_store_range in the array expansion domain not implemented\");\n  }\n\n  virtual void array_assign(variable_t lhs, variable_t rhs) override {\n    CRAB_WARN(\"array_assign in array_expansion domain not implemented\");\n  }\n\n  // backward array operations\n\n  virtual void\n  backward_array_init(variable_t a, linear_expression_t elem_size,\n                      linear_expression_t lb_idx, linear_expression_t ub_idx,\n                      linear_expression_t val,\n                      array_expansion_domain_t invariant) override {\n    crab::CrabStats::count(getDomainName() + \".count.backward_array_init\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".backward_array_init\");\n\n    if (is_bottom())\n      return;\n\n    // make all array cells uninitialized\n    offset_map_t &offset_map = lookup_array_map(a);\n    std::vector<cell_t> old_cells = offset_map.get_all_cells();\n    if (!old_cells.empty()) {\n      kill_cells(old_cells, offset_map);\n    }\n\n    // meet with forward invariant\n    *this = *this & invariant;\n  }\n\n  virtual void\n  backward_array_load(variable_t lhs, variable_t a,\n                      linear_expression_t elem_size, linear_expression_t i,\n                      array_expansion_domain_t invariant) override {\n    crab::CrabStats::count(getDomainName() + \".count.backward_array_load\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".backward_array_load\");\n\n    if (is_bottom())\n      return;\n\n    // XXX: we use the forward invariant to extract the array index\n    interval_t ii = to_interval(i, invariant.get_content_domain());\n    if (boost::optional<number_t> n = ii.singleton()) {\n      offset_map_t &offset_map = lookup_array_map(a);\n      offset_t o(static_cast<int64_t>(*n));\n      interval_t i_elem_size =\n          to_interval(elem_size, invariant.get_content_domain());\n      if (boost::optional<number_t> n_bytes = i_elem_size.singleton()) {\n        assert(static_cast<int64_t>(*n_bytes) > 0 &&\n               static_cast<int64_t>(*n_bytes) <=\n                   std::numeric_limits<uint64_t>::max());\n        uint64_t size = static_cast<int64_t>(*n_bytes);\n        cell_t c = offset_map.mk_cell(a, o, size);\n        assert(c.has_scalar());\n        do_backward_assign(lhs, c, invariant.get_content_domain());\n      } else {\n        CRAB_ERROR(\n            \"array expansion domain expects constant array element sizes\");\n      }\n    } else {\n      CRAB_LOG(\"array-expansion\",\n               CRAB_WARN(\"array index is not a constant value\"););\n      // -- Forget lhs\n      _inv -= lhs;\n      // -- Meet with forward invariant\n      *this = *this & invariant;\n    }\n\n    CRAB_LOG(\"array-expansion\", linear_expression_t ub = i + elem_size - 1;\n             crab::outs() << \"BACKWARD \" << lhs << \":=\" << a << \"[\" << i\n                          << \"...\" << ub << \"]  -- \" << *this << \"\\n\";);\n  }\n\n  virtual void\n  backward_array_store(variable_t a, linear_expression_t elem_size,\n                       linear_expression_t i, linear_expression_t val,\n                       bool /*is_strong_update*/,\n                       array_expansion_domain_t invariant) override {\n    crab::CrabStats::count(getDomainName() + \".count.backward_array_store\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".backward_array_store\");\n\n    if (is_bottom())\n      return;\n\n    // XXX: we use the forward invariant to extract the array index\n    interval_t i_elem_size =\n        to_interval(elem_size, invariant.get_content_domain());\n    boost::optional<number_t> n_bytes = i_elem_size.singleton();\n    if (!n_bytes) {\n      CRAB_ERROR(\"array expansion domain expects constant array element sizes\");\n    }\n\n    assert(static_cast<int64_t>(*n_bytes) > 0 &&\n           static_cast<int64_t>(*n_bytes) <=\n               std::numeric_limits<uint64_t>::max());\n    uint64_t size = static_cast<int64_t>(*n_bytes);\n    offset_map_t &offset_map = lookup_array_map(a);\n    // XXX: we use the forward invariant to extract the array index\n    interval_t ii = to_interval(i, invariant.get_content_domain());\n    if (boost::optional<number_t> n = ii.singleton()) {\n      // -- Constant index and the store updated one single cell:\n      // -- backward assign in the base domain.\n      offset_t o(static_cast<int64_t>(*n));\n      std::vector<cell_t> cells;\n      offset_map.get_overlap_cells(o, size, cells);\n      // post: forall c \\in cells:: c != [o,size)\n      // that is, get_overlap_cells returns cells different from [o, size)\n      if (cells.size() >= 1) {\n        kill_cells(cells, offset_map);\n        *this = *this & invariant;\n      } else {\n        // c might be in _inv or not.\n        cell_t c = offset_map.mk_cell(a, o, size);\n        do_backward_assign(c, val, invariant.get_content_domain());\n      }\n    } else {\n      // -- Non-constant index or multiple overlapping cells: kill\n      // -- overlapping cells and meet with forward invariant.\n      linear_expression_t symb_lb(i);\n      linear_expression_t symb_ub(i + number_t(size - 1));\n      std::vector<cell_t> cells;\n      offset_map.get_overlap_cells_symbolic_offset(\n          invariant.get_content_domain(), symb_lb, symb_ub, cells);\n      kill_cells(cells, offset_map);\n      *this = *this & invariant;\n    }\n\n    CRAB_LOG(\"array-expansion\", linear_expression_t ub = i + elem_size - 1;\n             crab::outs() << \"BACKWARD \" << a << \"[\" << i << \"...\" << ub\n                          << \"]:=\" << val << \" -- \" << *this << \"\\n\";);\n  }\n\n  virtual void\n  backward_array_store(variable_t a_new, variable_t a_old,\n                       linear_expression_t elem_size, linear_expression_t i,\n                       linear_expression_t val, bool /*is_strong_update*/,\n                       array_expansion_domain_t invariant) override {\n    CRAB_WARN(\"backward_array_store in array_expansion domain not implemented\");\n  }\n\n  virtual void backward_array_store_range(\n      variable_t a, linear_expression_t elem_size, linear_expression_t lb_idx,\n      linear_expression_t ub_idx, linear_expression_t val,\n      array_expansion_domain_t invariant) override {\n    crab::CrabStats::count(getDomainName() +\n                           \".count.backward_array_store_range\");\n    crab::ScopedCrabStats __st__(getDomainName() +\n                                 \".count.backward_array_store_range\");\n\n    // TODO: this should be an user parameter.\n    const number_t max_num_elems = 512;\n\n    if (is_bottom())\n      return;\n\n    interval_t n_i = to_interval(elem_size, invariant.get_content_domain());\n    auto n = n_i.singleton();\n    if (!n) {\n      CRAB_ERROR(\"array expansion domain expects constant array element sizes\");\n    }\n\n    interval_t lb_i = to_interval(lb_idx, invariant.get_content_domain());\n    auto lb = lb_i.singleton();\n    if (!lb) {\n      return;\n    }\n\n    interval_t ub_i = to_interval(ub_idx, invariant.get_content_domain());\n    auto ub = ub_i.singleton();\n    if (!ub || ((*ub - *lb) + 1) > max_num_elems) {\n      return;\n    }\n\n    for (number_t i = *lb, e = *ub; i <= e;) {\n      backward_array_store(a, elem_size, i, val, false, invariant);\n      i = i + *n;\n    }\n  }\n\n  virtual void backward_array_store_range(\n      variable_t a_new, variable_t a_old, linear_expression_t elem_size,\n      linear_expression_t lb_idx, linear_expression_t ub_idx,\n      linear_expression_t val, array_expansion_domain_t invariant) override {\n    CRAB_WARN(\n        \"backward_array_store_range in array_expansion domain not implemented\");\n  }\n\n  virtual void\n  backward_array_assign(variable_t lhs, variable_t rhs,\n                        array_expansion_domain_t invariant) override {\n    CRAB_WARN(\n        \"backward_array_assign in array_expansion domain not implemented\");\n  }\n\n  linear_constraint_system_t to_linear_constraint_system() {\n    crab::CrabStats::count(getDomainName() +\n                           \".count.to_linear_constraint_system\");\n    crab::ScopedCrabStats __st__(getDomainName() +\n                                 \".to_linear_constraint_system\");\n\n    return _inv.to_linear_constraint_system();\n  }\n\n  disjunctive_linear_constraint_system_t\n  to_disjunctive_linear_constraint_system() {\n    return _inv.to_disjunctive_linear_constraint_system();\n  }\n\n  NumDomain get_content_domain() const { return _inv; }\n\n  NumDomain &get_content_domain() { return _inv; }\n\n  /* begin intrinsics operations */    \n  void intrinsic(std::string name,\n\t\t const variable_vector_t &inputs,\n\t\t const variable_vector_t &outputs) override {\n    CRAB_WARN(\"Intrinsics \", name, \" not implemented by \", getDomainName());\n  }\n\n  void backward_intrinsic(std::string name,\n\t\t\t  const variable_vector_t &inputs,\n\t\t\t  const variable_vector_t &outputs,\n\t\t\t  array_expansion_domain_t invariant) override {\n    CRAB_WARN(\"Intrinsics \", name, \" not implemented by \", getDomainName());    \n  }\n  /* end intrinsics operations */\n  \n  void write(crab_os &o) { o << _inv; }\n\n  static std::string getDomainName() {\n    std::string name(\"ArrayExpansion(\" + NumDomain::getDomainName() + \")\");\n    return name;\n  }\n\n  void rename(const variable_vector_t &from, const variable_vector_t &to) {\n    CRAB_WARN(\"TODO: array_expansion rename\");\n  }\n\n}; // end array_expansion_domain\n\ntemplate <typename BaseDomain>\nstruct abstract_domain_traits<array_expansion_domain<BaseDomain>> {\n  typedef typename BaseDomain::number_t number_t;\n  typedef typename BaseDomain::varname_t varname_t;\n};\n\ntemplate <typename BaseDom>\nclass checker_domain_traits<array_expansion_domain<BaseDom>> {\npublic:\n  typedef array_expansion_domain<BaseDom> this_type;\n  typedef typename this_type::linear_constraint_t linear_constraint_t;\n  typedef typename this_type::disjunctive_linear_constraint_system_t\n      disjunctive_linear_constraint_system_t;\n\n  static bool entail(this_type &lhs,\n                     const disjunctive_linear_constraint_system_t &rhs) {\n    BaseDom &lhs_dom = lhs.get_content_domain();\n    return checker_domain_traits<BaseDom>::entail(lhs_dom, rhs);\n  }\n\n  static bool entail(const disjunctive_linear_constraint_system_t &lhs,\n                     this_type &rhs) {\n    BaseDom &rhs_dom = rhs.get_content_domain();\n    return checker_domain_traits<BaseDom>::entail(lhs, rhs_dom);\n  }\n\n  static bool entail(this_type &lhs, const linear_constraint_t &rhs) {\n    BaseDom &lhs_dom = lhs.get_content_domain();\n    return checker_domain_traits<BaseDom>::entail(lhs_dom, rhs);\n  }\n\n  static bool intersect(this_type &inv, const linear_constraint_t &cst) {\n    BaseDom &dom = inv.get_content_domain();\n    return checker_domain_traits<BaseDom>::intersect(dom, cst);\n  }\n};\n\ntemplate <typename BaseDom>\nclass special_domain_traits<array_expansion_domain<BaseDom>> {\npublic:\n  static void clear_global_state(void) {\n    array_expansion_domain<BaseDom>::clear_global_state();\n  }\n};\n\n} // namespace domains\n} // namespace crab\n", "meta": {"hexsha": "7dfd60298064c8bdbb8ca85966438f06d6c56d0e", "size": 56979, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/crab/domains/array_expansion.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/array_expansion.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/array_expansion.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.7553317536, "max_line_length": 102, "alphanum_fraction": 0.6135593815, "num_tokens": 13958, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.45628147908112804}}
{"text": "//\r\n// OpenTissue, A toolbox for physical based simulation and animation.\r\n// Copyright (C) 2007 Department of Computer Science, University of Copenhagen\r\n//\r\n#include <OpenTissue/configuration.h>\r\n\r\n#include <OpenTissue/core/math/math_basic_types.h>\r\n#include <OpenTissue/collision/gjk/gjk_outside_edge_face_voronoi_plane.h>\r\n\r\n#define BOOST_AUTO_TEST_MAIN\r\n#include <OpenTissue/utility/utility_push_boost_filter.h>\r\n#include <boost/test/auto_unit_test.hpp>\r\n#include <boost/test/unit_test_suite.hpp>\r\n#include <boost/test/floating_point_comparison.hpp>\r\n#include <boost/test/test_tools.hpp>\r\n#include <OpenTissue/utility/utility_pop_boost_filter.h>\r\n\r\n#include <cmath>\r\n\r\nusing namespace OpenTissue;\r\n\r\nBOOST_AUTO_TEST_SUITE(opentissue_collision_gjk_outside_edge_face);\r\n\r\nBOOST_AUTO_TEST_CASE(case_by_case_test)\r\n{\r\n  typedef OpenTissue::math::BasicMathTypes<double, size_t> math_types;\r\n  typedef math_types::vector3_type                         V;\r\n\r\n\r\n  V const a = V(0.0, 0.0, 0.0);\r\n  V const b = V(1.0, 0.0, 0.0);;\r\n  V const c = V(0.0, 1.0, 0.0);;\r\n\r\n  // Front side of AB voronoi plane\r\n  {\r\n    V p = V(-0.5, -1.0,  1.0);\r\n    bool outside = OpenTissue::gjk::detail::outside_edge_face_voronoi_plane(p, a, b, c);      \r\n    BOOST_CHECK( outside );\r\n\r\n    bool outside2 = OpenTissue::gjk::detail::outside_edge_face_voronoi_plane(p, b, a, c);      \r\n    BOOST_CHECK( outside2 );\r\n  }\r\n  // Back side of AB voronoi plane\r\n  {\r\n    V p = V(-0.5, 1.0,  1.0);\r\n    bool outside = OpenTissue::gjk::detail::outside_edge_face_voronoi_plane(p, a, b, c);      \r\n    BOOST_CHECK( !outside );\r\n\r\n    bool outside2 = OpenTissue::gjk::detail::outside_edge_face_voronoi_plane(p, b, a, c);      \r\n    BOOST_CHECK( !outside2 );\r\n  }\r\n  // In AB voronoi plane\r\n  {\r\n    V p = V(-0.5, 0.0,  1.0);\r\n    bool outside = OpenTissue::gjk::detail::outside_edge_face_voronoi_plane(p, a, b, c);      \r\n    BOOST_CHECK( outside );\r\n\r\n    bool outside2 = OpenTissue::gjk::detail::outside_edge_face_voronoi_plane(p, b, a, c);      \r\n    BOOST_CHECK( outside2 );\r\n  }\r\n  // Front side of AC voronoi plane\r\n  {\r\n    V p = V(-1.0, 0.5,  1.0);\r\n    bool outside = OpenTissue::gjk::detail::outside_edge_face_voronoi_plane(p, a, c, b);      \r\n    BOOST_CHECK( outside );\r\n\r\n    bool outside2 = OpenTissue::gjk::detail::outside_edge_face_voronoi_plane(p, c, a, b);      \r\n    BOOST_CHECK( outside2 );\r\n  }\r\n  // Back side of AC voronoi plane\r\n  {\r\n    V p = V( 1.0, 0.5,  1.0);\r\n    bool outside = OpenTissue::gjk::detail::outside_edge_face_voronoi_plane(p, a, c, b);      \r\n    BOOST_CHECK( !outside );\r\n\r\n    bool outside2 = OpenTissue::gjk::detail::outside_edge_face_voronoi_plane(p, c, a, b);      \r\n    BOOST_CHECK( !outside2 );\r\n  }\r\n  // In AC voronoi plane\r\n  {\r\n    V p = V( 0.0, 0.5,  1.0);\r\n    bool outside = OpenTissue::gjk::detail::outside_edge_face_voronoi_plane(p, a, c, b);      \r\n    BOOST_CHECK( outside );\r\n\r\n    bool outside2 = OpenTissue::gjk::detail::outside_edge_face_voronoi_plane(p, c, a, b);      \r\n    BOOST_CHECK( outside2 );\r\n  }\r\n  // Front side of BC voronoi plane\r\n  {\r\n    V p = V( 1.0, 1.0,  1.0);\r\n    bool outside = OpenTissue::gjk::detail::outside_edge_face_voronoi_plane(p, b, c, a);\r\n    BOOST_CHECK( outside );\r\n\r\n    bool outside2 = OpenTissue::gjk::detail::outside_edge_face_voronoi_plane(p, c, b, a);\r\n    BOOST_CHECK( outside2 );\r\n  }\r\n  // Back side of BC voronoi plane\r\n  {\r\n    V p = V( 0.0, 0.0,  1.0);\r\n    bool outside = OpenTissue::gjk::detail::outside_edge_face_voronoi_plane(p, b, c, a);\r\n    BOOST_CHECK( !outside );\r\n\r\n    bool outside2 = OpenTissue::gjk::detail::outside_edge_face_voronoi_plane(p, c, b, a);\r\n    BOOST_CHECK( !outside2 );\r\n  }\r\n  // In BC voronoi plane\r\n  {\r\n    V p = V( 0.5, 0.5,  1.0);\r\n    bool outside = OpenTissue::gjk::detail::outside_edge_face_voronoi_plane(p, b, c, a); \r\n    BOOST_CHECK( outside );\r\n\r\n    bool outside2 = OpenTissue::gjk::detail::outside_edge_face_voronoi_plane(p, c, b, a);\r\n    BOOST_CHECK( outside2 );\r\n  }\r\n\r\n  // We just used a point above the face plane, next we will try using a test point lying in the face plane\r\n\r\n  // Front side of AB voronoi plane\r\n  {\r\n    V p = V(-0.5, -1.0,  0.0);\r\n    bool outside = OpenTissue::gjk::detail::outside_edge_face_voronoi_plane(p, a, b, c);      \r\n    BOOST_CHECK( outside );\r\n\r\n    bool outside2 = OpenTissue::gjk::detail::outside_edge_face_voronoi_plane(p, b, a, c);      \r\n    BOOST_CHECK( outside2 );\r\n  }\r\n  // Back side of AB voronoi plane\r\n  {\r\n    V p = V(-0.5, 1.0,  0.0);\r\n    bool outside = OpenTissue::gjk::detail::outside_edge_face_voronoi_plane(p, a, b, c);      \r\n    BOOST_CHECK( !outside );\r\n\r\n    bool outside2 = OpenTissue::gjk::detail::outside_edge_face_voronoi_plane(p, b, a, c);      \r\n    BOOST_CHECK( !outside2 );\r\n  }\r\n  // In AB voronoi plane\r\n  {\r\n    V p = V(-0.5, 0.0,  0.0);\r\n    bool outside = OpenTissue::gjk::detail::outside_edge_face_voronoi_plane(p, a, b, c);      \r\n    BOOST_CHECK( outside );\r\n\r\n    bool outside2 = OpenTissue::gjk::detail::outside_edge_face_voronoi_plane(p, b, a, c);      \r\n    BOOST_CHECK( outside2 );\r\n  }\r\n  // Front side of AC voronoi plane\r\n  {\r\n    V p = V(-1.0, 0.5,  0.0);\r\n    bool outside = OpenTissue::gjk::detail::outside_edge_face_voronoi_plane(p, a, c, b);      \r\n    BOOST_CHECK( outside );\r\n\r\n    bool outside2 = OpenTissue::gjk::detail::outside_edge_face_voronoi_plane(p, c, a, b);      \r\n    BOOST_CHECK( outside2 );\r\n  }\r\n  // Back side of AC voronoi plane\r\n  {\r\n    V p = V( 1.0, 0.5,  0.0);\r\n    bool outside = OpenTissue::gjk::detail::outside_edge_face_voronoi_plane(p, a, c, b);      \r\n    BOOST_CHECK( !outside );\r\n\r\n    bool outside2 = OpenTissue::gjk::detail::outside_edge_face_voronoi_plane(p, c, a, b);      \r\n    BOOST_CHECK( !outside2 );\r\n  }\r\n  // In AC voronoi plane\r\n  {\r\n    V p = V( 0.0, 0.5,  0.0);\r\n    bool outside = OpenTissue::gjk::detail::outside_edge_face_voronoi_plane(p, a, c, b);      \r\n    BOOST_CHECK( outside );\r\n\r\n    bool outside2 = OpenTissue::gjk::detail::outside_edge_face_voronoi_plane(p, c, a, b);      \r\n    BOOST_CHECK( outside2 );\r\n  }\r\n  // Front side of BC voronoi plane\r\n  {\r\n    V p = V( 1.0, 1.0,  0.0);\r\n    bool outside = OpenTissue::gjk::detail::outside_edge_face_voronoi_plane(p, b, c, a);\r\n    BOOST_CHECK( outside );\r\n\r\n    bool outside2 = OpenTissue::gjk::detail::outside_edge_face_voronoi_plane(p, c, b, a);\r\n    BOOST_CHECK( outside2 );\r\n  }\r\n  // Back side of BC voronoi plane\r\n  {\r\n    V p = V( 0.0, 0.0,  0.0);\r\n    bool outside = OpenTissue::gjk::detail::outside_edge_face_voronoi_plane(p, b, c, a);\r\n    BOOST_CHECK( !outside );\r\n\r\n    bool outside2 = OpenTissue::gjk::detail::outside_edge_face_voronoi_plane(p, c, b, a);\r\n    BOOST_CHECK( !outside2 );\r\n  }\r\n  // In BC voronoi plane\r\n  {\r\n    V p = V( 0.5, 0.5,  0.0);\r\n    bool outside = OpenTissue::gjk::detail::outside_edge_face_voronoi_plane(p, b, c, a); \r\n    BOOST_CHECK( outside );\r\n\r\n    bool outside2 = OpenTissue::gjk::detail::outside_edge_face_voronoi_plane(p, c, b, a);\r\n    BOOST_CHECK( outside2 );\r\n  }\r\n\r\n  // Finally we will use a test point lying below the face-plane\r\n\r\n  // Front side of AB voronoi plane\r\n  {\r\n    V p = V(-0.5, -1.0,  -1.0);\r\n    bool outside = OpenTissue::gjk::detail::outside_edge_face_voronoi_plane(p, a, b, c);      \r\n    BOOST_CHECK( outside );\r\n\r\n    bool outside2 = OpenTissue::gjk::detail::outside_edge_face_voronoi_plane(p, b, a, c);      \r\n    BOOST_CHECK( outside2 );\r\n  }\r\n  // Back side of AB voronoi plane\r\n  {\r\n    V p = V(-0.5, 1.0,  -1.0);\r\n    bool outside = OpenTissue::gjk::detail::outside_edge_face_voronoi_plane(p, a, b, c);      \r\n    BOOST_CHECK( !outside );\r\n\r\n    bool outside2 = OpenTissue::gjk::detail::outside_edge_face_voronoi_plane(p, b, a, c);      \r\n    BOOST_CHECK( !outside2 );\r\n  }\r\n  // In AB voronoi plane\r\n  {\r\n    V p = V(-0.5, 0.0,  -1.0);\r\n    bool outside = OpenTissue::gjk::detail::outside_edge_face_voronoi_plane(p, a, b, c);      \r\n    BOOST_CHECK( outside );\r\n\r\n    bool outside2 = OpenTissue::gjk::detail::outside_edge_face_voronoi_plane(p, b, a, c);      \r\n    BOOST_CHECK( outside2 );\r\n  }\r\n  // Front side of AC voronoi plane\r\n  {\r\n    V p = V(-1.0, 0.5,  -1.0);\r\n    bool outside = OpenTissue::gjk::detail::outside_edge_face_voronoi_plane(p, a, c, b);      \r\n    BOOST_CHECK( outside );\r\n\r\n    bool outside2 = OpenTissue::gjk::detail::outside_edge_face_voronoi_plane(p, c, a, b);      \r\n    BOOST_CHECK( outside2 );\r\n  }\r\n  // Back side of AC voronoi plane\r\n  {\r\n    V p = V( 1.0, 0.5,  -1.0);\r\n    bool outside = OpenTissue::gjk::detail::outside_edge_face_voronoi_plane(p, a, c, b);      \r\n    BOOST_CHECK( !outside );\r\n\r\n    bool outside2 = OpenTissue::gjk::detail::outside_edge_face_voronoi_plane(p, c, a, b);      \r\n    BOOST_CHECK( !outside2 );\r\n  }\r\n  // In AC voronoi plane\r\n  {\r\n    V p = V( 0.0, 0.5,  -1.0);\r\n    bool outside = OpenTissue::gjk::detail::outside_edge_face_voronoi_plane(p, a, c, b);      \r\n    BOOST_CHECK( outside );\r\n\r\n    bool outside2 = OpenTissue::gjk::detail::outside_edge_face_voronoi_plane(p, c, a, b);      \r\n    BOOST_CHECK( outside2 );\r\n  }\r\n  // Front side of BC voronoi plane\r\n  {\r\n    V p = V( 1.0, 1.0,  -1.0);\r\n    bool outside = OpenTissue::gjk::detail::outside_edge_face_voronoi_plane(p, b, c, a);\r\n    BOOST_CHECK( outside );\r\n\r\n    bool outside2 = OpenTissue::gjk::detail::outside_edge_face_voronoi_plane(p, c, b, a);\r\n    BOOST_CHECK( outside2 );\r\n  }\r\n  // Back side of BC voronoi plane\r\n  {\r\n    V p = V( 0.0, 0.0, -1.0);\r\n    bool outside = OpenTissue::gjk::detail::outside_edge_face_voronoi_plane(p, b, c, a);\r\n    BOOST_CHECK( !outside );\r\n\r\n    bool outside2 = OpenTissue::gjk::detail::outside_edge_face_voronoi_plane(p, c, b, a);\r\n    BOOST_CHECK( !outside2 );\r\n  }\r\n  // In BC voronoi plane\r\n  {\r\n    V p = V( 0.5, 0.5, -1.0);\r\n    bool outside = OpenTissue::gjk::detail::outside_edge_face_voronoi_plane(p, b, c, a); \r\n    BOOST_CHECK( outside );\r\n\r\n    bool outside2 = OpenTissue::gjk::detail::outside_edge_face_voronoi_plane(p, c, b, a);\r\n    BOOST_CHECK( outside2 );\r\n  }\r\n\r\n}\r\n\r\nBOOST_AUTO_TEST_SUITE_END();\r\n", "meta": {"hexsha": "84c96b52b5286ce39e2cce66ecd914f8c74de1a5", "size": 10060, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/collision/gjk/outside_edge_face/src/unit_outside_edge_face.cpp", "max_stars_repo_name": "ricortiz/OpenTissue", "max_stars_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 76.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:45:06.000Z", "max_issues_repo_path": "unit_tests/collision/gjk/outside_edge_face/src/unit_outside_edge_face.cpp", "max_issues_repo_name": "ricortiz/OpenTissue", "max_issues_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2018-11-20T14:32:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T15:26:45.000Z", "max_forks_repo_path": "unit_tests/collision/gjk/outside_edge_face/src/unit_outside_edge_face.cpp", "max_forks_repo_name": "ricortiz/OpenTissue", "max_forks_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2018-02-21T01:45:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T07:06:49.000Z", "avg_line_length": 35.0522648084, "max_line_length": 108, "alphanum_fraction": 0.626640159, "num_tokens": 3232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.45628147419440546}}
{"text": "// Copyright \u00a9 2016-2019 Thomas Nagler and Thibault Vatter\n//\n// This file is part of the vinecopulib library and licensed under the terms of\n// the MIT license. For a copy, see the LICENSE file in the root directory of\n// vinecopulib or https://vinecopulib.github.io/vinecopulib/.\n\n#pragma once\n\n#include <Eigen/Dense>\n#include <vinecopulib/misc/triangular_array.hpp>\n\nnamespace vinecopulib {\n\n//! @brief R-vine structures\n//!\n//! RVineStructure objects encode the tree structure of the vine, i.e. the\n//! conditioned/conditioning variables of each edge. It is represented by a\n//! triangular array. An exemplary array is\n//! ```\n//! 4 4 4 4\n//! 3 3 3\n//! 2 2\n//! 1\n//! ```\n//! which encodes the following pair-copulas:\n//! ```\n//! | tree | edge | pair-copulas   |\n//! |------|------|----------------|\n//! | 0    | 0    | `(1, 4)`       |\n//! |      | 1    | `(2, 4)`       |\n//! |      | 2    | `(3, 4)`       |\n//! | 1    | 0    | `(1, 3; 4)`    |\n//! |      | 1    | `(2, 3; 4)`    |\n//! | 2    | 0    | `(1, 2; 3, 4)` |\n//! ```\n//! Denoting by `M[i, j]` the array entry in row `i` and column `j`,\n//! the pair-copula index for edge `e` in tree `t` of a `d` dimensional vine\n//! is `(M[d - 1 - t, e], M[t, e]; M[t - 1, e], ..., M[0, e])`. Less\n//! formally,\n//! 1. Start with the counter-diagonal element of column `e` (first conditioned\n//!    variable).\n//! 2. Jump up to the element in row `t` (second conditioned variable).\n//! 3. Gather all entries further up in column `e` (conditioning set).\n//!\n//! A valid R-vine array must satisfy several conditions which are checked\n//! when `RVineStructure()` is called:\n//! 1. It only contains numbers between 1 and d.\n//! 2. The diagonal must contain the numbers 1, ..., d.\n//! 3. The diagonal entry of a column must not be contained in any\n//!    column further to the right.\n//! 4. The entries of a column must be contained in all columns to the left.\n//! 5. The proximity condition must hold: For all t = 1, ..., d - 2 and\n//!    e = 0, ..., d - t - 1 there must exist an index j > d, such that\n//!    `(M[t, e], {M[0, e], ..., M[t-1, e]})` equals either\n//!    `(M[d-j-1, j], {M[0, j], ..., M[t-1, j]})` or\n//!    `(M[t-1, j], {M[d-j-1, j], M[0, j], ..., M[t-2, j]})`.\n//!\n//! An R-vine array is said to be in natural order when the anti-diagonal\n//! entries are \\f$ 1, \\dots, d \\f$ (from left to right). The exemplary arrray\n//! above is in natural order. Any R-vine array can be characterized by the\n//! diagonal entries (called order) and the entries below the diagonal of the\n//! corresponding R-vine array in natural order. Since most algorithms work\n//! with the structure in natural order, this is how RVineStructure stores the\n//! structure internally.\nclass RVineStructure {\npublic:\n    RVineStructure() {}\n\n    RVineStructure(\n        const Eigen::Matrix<size_t, Eigen::Dynamic, Eigen::Dynamic>& mat,\n        bool check = true);\n    RVineStructure(const std::vector<size_t>& order,\n                   bool check = true);\n    RVineStructure(const std::vector<size_t>& order,\n                   const size_t& trunc_lvl,\n                   bool check = true);\n    RVineStructure(const std::vector<size_t>& order,\n                   const TriangularArray<size_t>& struct_array,\n                   bool is_natural_order = false,\n                   bool check = true);\n\n    size_t get_dim() const;\n    size_t get_trunc_lvl() const;\n    std::vector<size_t> get_order() const;\n    TriangularArray<size_t> get_struct_array() const;\n    TriangularArray<size_t> get_min_array() const;\n    TriangularArray<size_t> get_needed_hfunc1() const;\n    TriangularArray<size_t> get_needed_hfunc2() const;\n    Eigen::Matrix<size_t, Eigen::Dynamic, Eigen::Dynamic> get_matrix() const;\n\n    size_t struct_array(size_t tree, size_t edge) const;\n    size_t min_array(size_t tree, size_t edge) const;\n\n    void truncate(size_t trunc_lvl);\n    std::string str() const;\n\nprotected:\n    size_t find_trunc_lvl(\n        const Eigen::Matrix<size_t, Eigen::Dynamic, Eigen::Dynamic>& mat) const;\n    std::vector<size_t> get_order(\n        const Eigen::Matrix<size_t, Eigen::Dynamic, Eigen::Dynamic>& mat) const;\n    TriangularArray<size_t> to_rvine_array(\n        const Eigen::Matrix<size_t, Eigen::Dynamic, Eigen::Dynamic>& mat) const;\n\n    TriangularArray<size_t> to_natural_order() const;\n    TriangularArray<size_t> compute_dvine_struct_array() const;\n    TriangularArray<size_t> compute_min_array() const;\n    TriangularArray<size_t> compute_needed_hfunc1() const;\n    TriangularArray<size_t> compute_needed_hfunc2() const;\n\n    void check_if_quadratic(\n        const Eigen::Matrix<size_t, Eigen::Dynamic, Eigen::Dynamic>& mat) const;\n    void check_lower_tri(\n        const Eigen::Matrix<size_t, Eigen::Dynamic, Eigen::Dynamic>& mat) const;\n    void check_upper_tri() const;\n    void check_columns() const;\n    void check_antidiagonal() const;\n    void check_proximity_condition() const;\n\n    std::vector<size_t> order_;\n    size_t d_;\n    size_t trunc_lvl_;\n    TriangularArray<size_t> struct_array_;\n    TriangularArray<size_t> min_array_;\n    TriangularArray<size_t> needed_hfunc1_;\n    TriangularArray<size_t> needed_hfunc2_;\n};\n\nstd::ostream& operator<<(std::ostream& os, const RVineStructure& rvs);\n\n}\n\n#include <vinecopulib/vinecop/implementation/rvine_structure.ipp>\n", "meta": {"hexsha": "b374a1dc9445193690e5fa215364960fbfd95900", "size": 5312, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "4.CalculatePairCopulas/include/vinecopulib/vinecop/rvine_structure.hpp", "max_stars_repo_name": "covit2019/analysis_codes", "max_stars_repo_head_hexsha": "0c580c51f790723390676eef85422055007e2354", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "4.CalculatePairCopulas/include/vinecopulib/vinecop/rvine_structure.hpp", "max_issues_repo_name": "covit2019/analysis_codes", "max_issues_repo_head_hexsha": "0c580c51f790723390676eef85422055007e2354", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "4.CalculatePairCopulas/include/vinecopulib/vinecop/rvine_structure.hpp", "max_forks_repo_name": "covit2019/analysis_codes", "max_forks_repo_head_hexsha": "0c580c51f790723390676eef85422055007e2354", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-04-09T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-09T12:59:17.000Z", "avg_line_length": 39.6417910448, "max_line_length": 80, "alphanum_fraction": 0.6458960843, "num_tokens": 1480, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321720225278, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.4562814712548519}}
{"text": "//  (C) Copyright Nick Thompson 2018.\n//  (C) Copyright Matt Borland 2021.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_MATH_STATISTICS_BIVARIATE_STATISTICS_HPP\n#define BOOST_MATH_STATISTICS_BIVARIATE_STATISTICS_HPP\n\n#include <iterator>\n#include <tuple>\n#include <type_traits>\n#include <stdexcept>\n#include <future>\n#include <thread>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <cstddef>\n#include <boost/assert.hpp>\n\n// Support compilers with P0024R2 implemented without linking TBB\n// https://en.cppreference.com/w/cpp/compiler_support\n#ifndef BOOST_NO_CXX17_HDR_EXECUTION\n#include <execution>\n#define EXEC_COMPATIBLE\n#endif\n\nnamespace boost{ namespace math{ namespace statistics { namespace detail {\n\n// See Equation III.9 of \"Numerically Stable, Single-Pass, Parallel Statistics Algorithms\", Bennet et al.\ntemplate<typename ReturnType, typename ForwardIterator>\nReturnType means_and_covariance_seq_impl(ForwardIterator u_begin, ForwardIterator u_end, ForwardIterator v_begin, ForwardIterator v_end)\n{\n    using Real = typename std::tuple_element<0, ReturnType>::type;\n\n    Real cov = 0;\n    ForwardIterator u_it = u_begin;\n    ForwardIterator v_it = v_begin;\n    Real mu_u = *u_it++;\n    Real mu_v = *v_it++;\n    std::size_t i = 1;\n\n    while(u_it != u_end && v_it != v_end)\n    {\n        Real u_temp = (*u_it++ - mu_u)/(i+1);\n        Real v_temp = *v_it++ - mu_v;\n        cov += i*u_temp*v_temp;\n        mu_u = mu_u + u_temp;\n        mu_v = mu_v + v_temp/(i+1);\n        i = i + 1;\n    }\n\n    if(u_it != u_end || v_it != v_end)\n    {\n        throw std::domain_error(\"The size of each sample set must be the same to compute covariance\");\n    }\n\n    return std::make_tuple(mu_u, mu_v, cov/i, i);\n}\n\n// Numerically stable parallel computation of (co-)variance\n// https://dl.acm.org/doi/10.1145/3221269.3223036\ntemplate<typename ReturnType, typename ForwardIterator>\nReturnType means_and_covariance_parallel_impl(ForwardIterator u_begin, ForwardIterator u_end, ForwardIterator v_begin, ForwardIterator v_end)\n{\n    using Real = typename std::tuple_element<0, ReturnType>::type;\n\n    const auto u_elements = std::distance(u_begin, u_end);\n    const auto v_elements = std::distance(v_begin, v_end);\n\n    if(u_elements != v_elements)\n    {\n        throw std::domain_error(\"The size of each sample set must be the same to compute covariance\");\n    }\n\n    const unsigned max_concurrency = std::thread::hardware_concurrency() == 0 ? 2u : std::thread::hardware_concurrency();\n    unsigned num_threads = 2u;\n    \n    // 5.16 comes from benchmarking. See boost/math/reporting/performance/bivariate_statistics_performance.cpp\n    // Threading is faster for: 10 + 5.16e-3 N/j <= 5.16e-3N => N >= 10^4j/5.16(j-1).\n    const auto parallel_lower_bound = 10e4*max_concurrency/(5.16*(max_concurrency-1));\n    const auto parallel_upper_bound = 10e4*2/5.16; // j = 2\n\n    // https://lemire.me/blog/2020/01/30/cost-of-a-thread-in-c-under-linux/\n    if(u_elements < parallel_lower_bound)\n    {\n        return means_and_covariance_seq_impl<ReturnType>(u_begin, u_end, v_begin, v_end);\n    }\n    else if(u_elements >= parallel_upper_bound)\n    {\n        num_threads = max_concurrency;\n    }\n    else\n    {\n        for(unsigned i = 3; i < max_concurrency; ++i)\n        {\n            if(parallel_lower_bound < 10e4*i/(5.16*(i-1)))\n            {\n                num_threads = i;\n                break;\n            }\n        }\n    }\n\n    std::vector<std::future<ReturnType>> future_manager;\n    const auto elements_per_thread = std::ceil(static_cast<double>(u_elements)/num_threads);\n\n    ForwardIterator u_it = u_begin;\n    ForwardIterator v_it = v_begin;\n\n    for(std::size_t i = 0; i < num_threads - 1; ++i)\n    {\n        future_manager.emplace_back(std::async(std::launch::async | std::launch::deferred, [u_it, v_it, elements_per_thread]() -> ReturnType\n        {\n            return means_and_covariance_seq_impl<ReturnType>(u_it, std::next(u_it, elements_per_thread), v_it, std::next(v_it, elements_per_thread));\n        }));\n        u_it = std::next(u_it, elements_per_thread);\n        v_it = std::next(v_it, elements_per_thread);\n    }\n\n    future_manager.emplace_back(std::async(std::launch::async | std::launch::deferred, [u_it, u_end, v_it, v_end]() -> ReturnType\n    {\n        return means_and_covariance_seq_impl<ReturnType>(u_it, u_end, v_it, v_end);\n    }));\n\n    ReturnType temp = future_manager[0].get();\n    Real mu_u_a = std::get<0>(temp);\n    Real mu_v_a = std::get<1>(temp);\n    Real cov_a = std::get<2>(temp);\n    Real n_a = std::get<3>(temp);\n\n    for(std::size_t i = 1; i < future_manager.size(); ++i)\n    {\n        temp = future_manager[i].get();\n        Real mu_u_b = std::get<0>(temp);\n        Real mu_v_b = std::get<1>(temp);\n        Real cov_b = std::get<2>(temp);\n        Real n_b = std::get<3>(temp);\n\n        const Real n_ab = n_a + n_b;\n        const Real delta_u = mu_u_b - mu_u_a;\n        const Real delta_v = mu_v_b - mu_v_a;\n\n        cov_a = cov_a + cov_b + (-delta_u)*(-delta_v)*((n_a*n_b)/n_ab);\n        mu_u_a = mu_u_a + delta_u*(n_b/n_ab);\n        mu_v_a = mu_v_a + delta_v*(n_b/n_ab);\n        n_a = n_ab;\n    }\n\n    return std::make_tuple(mu_u_a, mu_v_a, cov_a, n_a);\n}\n\ntemplate<typename ReturnType, typename ForwardIterator>\nReturnType correlation_coefficient_seq_impl(ForwardIterator u_begin, ForwardIterator u_end, ForwardIterator v_begin, ForwardIterator v_end)\n{\n    using Real = typename std::tuple_element<0, ReturnType>::type;\n    using std::sqrt;\n\n    Real cov = 0;\n    ForwardIterator u_it = u_begin;\n    ForwardIterator v_it = v_begin;\n    Real mu_u = *u_it++;\n    Real mu_v = *v_it++;\n    Real Qu = 0;\n    Real Qv = 0;\n    std::size_t i = 1;\n\n    while(u_it != u_end && v_it != v_end)\n    {\n        Real u_tmp = *u_it++ - mu_u;\n        Real v_tmp = *v_it++ - mu_v;\n        Qu = Qu + (i*u_tmp*u_tmp)/(i+1);\n        Qv = Qv + (i*v_tmp*v_tmp)/(i+1);\n        cov += i*u_tmp*v_tmp/(i+1);\n        mu_u = mu_u + u_tmp/(i+1);\n        mu_v = mu_v + v_tmp/(i+1);\n        ++i;\n    }\n\n    // If both datasets are constant, then they are perfectly correlated.\n    if (Qu == 0 && Qv == 0)\n    {\n        return std::make_tuple(mu_u, Qu, mu_v, Qv, cov, Real(1), i);\n    }\n    // If one dataset is constant and the other isn't, then they have no correlation:\n    if (Qu == 0 || Qv == 0)\n    {\n        return std::make_tuple(mu_u, Qu, mu_v, Qv, cov, Real(0), i);\n    }\n\n    // Make sure rho in [-1, 1], even in the presence of numerical noise.\n    Real rho = cov/sqrt(Qu*Qv);\n    if (rho > 1) {\n        rho = 1;\n    }\n    if (rho < -1) {\n        rho = -1;\n    }\n\n    return std::make_tuple(mu_u, Qu, mu_v, Qv, cov, rho, i);\n}\n\n// Numerically stable parallel computation of (co-)variance:\n// https://dl.acm.org/doi/10.1145/3221269.3223036\n//\n// Parallel computation of variance:\n// http://i.stanford.edu/pub/cstr/reports/cs/tr/79/773/CS-TR-79-773.pdf\ntemplate<typename ReturnType, typename ForwardIterator>\nReturnType correlation_coefficient_parallel_impl(ForwardIterator u_begin, ForwardIterator u_end, ForwardIterator v_begin, ForwardIterator v_end)\n{\n    using Real = typename std::tuple_element<0, ReturnType>::type;\n\n    const auto u_elements = std::distance(u_begin, u_end);\n    const auto v_elements = std::distance(v_begin, v_end);\n\n    if(u_elements != v_elements)\n    {\n        throw std::domain_error(\"The size of each sample set must be the same to compute covariance\");\n    }\n\n    const unsigned max_concurrency = std::thread::hardware_concurrency() == 0 ? 2u : std::thread::hardware_concurrency();\n    unsigned num_threads = 2u;\n    \n    // 3.25 comes from benchmarking. See boost/math/reporting/performance/bivariate_statistics_performance.cpp\n    // Threading is faster for: 10 + 3.25e-3 N/j <= 3.25e-3N => N >= 10^4j/3.25(j-1).\n    const auto parallel_lower_bound = 10e4*max_concurrency/(3.25*(max_concurrency-1));\n    const auto parallel_upper_bound = 10e4*2/3.25; // j = 2\n\n    // https://lemire.me/blog/2020/01/30/cost-of-a-thread-in-c-under-linux/\n    if(u_elements < parallel_lower_bound)\n    {\n        return correlation_coefficient_seq_impl<ReturnType>(u_begin, u_end, v_begin, v_end);\n    }\n    else if(u_elements >= parallel_upper_bound)\n    {\n        num_threads = max_concurrency;\n    }\n    else\n    {\n        for(unsigned i = 3; i < max_concurrency; ++i)\n        {\n            if(parallel_lower_bound < 10e4*i/(3.25*(i-1)))\n            {\n                num_threads = i;\n                break;\n            }\n        }\n    }\n\n    std::vector<std::future<ReturnType>> future_manager;\n    const auto elements_per_thread = std::ceil(static_cast<double>(u_elements)/num_threads);\n\n    ForwardIterator u_it = u_begin;\n    ForwardIterator v_it = v_begin;\n\n    for(std::size_t i = 0; i < num_threads - 1; ++i)\n    {\n        future_manager.emplace_back(std::async(std::launch::async | std::launch::deferred, [u_it, v_it, elements_per_thread]() -> ReturnType\n        {\n            return correlation_coefficient_seq_impl<ReturnType>(u_it, std::next(u_it, elements_per_thread), v_it, std::next(v_it, elements_per_thread));\n        }));\n        u_it = std::next(u_it, elements_per_thread);\n        v_it = std::next(v_it, elements_per_thread);\n    }\n\n    future_manager.emplace_back(std::async(std::launch::async | std::launch::deferred, [u_it, u_end, v_it, v_end]() -> ReturnType\n    {\n        return correlation_coefficient_seq_impl<ReturnType>(u_it, u_end, v_it, v_end);\n    }));\n\n    ReturnType temp = future_manager[0].get();\n    Real mu_u_a = std::get<0>(temp);\n    Real Qu_a = std::get<1>(temp);\n    Real mu_v_a = std::get<2>(temp);\n    Real Qv_a = std::get<3>(temp);\n    Real cov_a = std::get<4>(temp);\n    Real n_a = std::get<6>(temp);\n\n    for(std::size_t i = 1; i < future_manager.size(); ++i)\n    {\n        temp = future_manager[i].get();\n        Real mu_u_b = std::get<0>(temp);\n        Real Qu_b = std::get<1>(temp);\n        Real mu_v_b = std::get<2>(temp);\n        Real Qv_b = std::get<3>(temp);\n        Real cov_b = std::get<4>(temp);\n        Real n_b = std::get<6>(temp);\n\n        const Real n_ab = n_a + n_b;\n        const Real delta_u = mu_u_b - mu_u_a;\n        const Real delta_v = mu_v_b - mu_v_a;\n\n        cov_a = cov_a + cov_b + (-delta_u)*(-delta_v)*((n_a*n_b)/n_ab);\n        mu_u_a = mu_u_a + delta_u*(n_b/n_ab);\n        mu_v_a = mu_v_a + delta_v*(n_b/n_ab);\n        Qu_a = Qu_a + Qu_b + delta_u*delta_u*((n_a*n_b)/n_ab);\n        Qv_b = Qv_a + Qv_b + delta_v*delta_v*((n_a*n_b)/n_ab);\n        n_a = n_ab;\n    }\n\n    // If both datasets are constant, then they are perfectly correlated.\n    if (Qu_a == 0 && Qv_a == 0)\n    {\n        return std::make_tuple(mu_u_a, Qu_a, mu_v_a, Qv_a, cov_a, Real(1), n_a);\n    }\n    // If one dataset is constant and the other isn't, then they have no correlation:\n    if (Qu_a == 0 || Qv_a == 0)\n    {\n        return std::make_tuple(mu_u_a, Qu_a, mu_v_a, Qv_a, cov_a, Real(0), n_a);\n    }\n\n    // Make sure rho in [-1, 1], even in the presence of numerical noise.\n    Real rho = cov_a/sqrt(Qu_a*Qv_a);\n    if (rho > 1) {\n        rho = 1;\n    }\n    if (rho < -1) {\n        rho = -1;\n    }\n\n    return std::make_tuple(mu_u_a, Qu_a, mu_v_a, Qv_a, cov_a, rho, n_a);\n}\n\n} // namespace detail\n\n#ifdef EXEC_COMPATIBLE\n\ntemplate<typename ExecutionPolicy, typename Container, typename Real = typename Container::value_type>\ninline auto means_and_covariance(ExecutionPolicy&& exec, Container const & u, Container const & v)\n{\n    if constexpr (std::is_same_v<std::remove_reference_t<decltype(exec)>, decltype(std::execution::seq)>)\n    {\n        if constexpr (std::is_integral_v<Real>)\n        {\n            using ReturnType = std::tuple<double, double, double, double>;\n            ReturnType temp = detail::means_and_covariance_seq_impl<ReturnType>(std::begin(u), std::end(u), std::begin(v), std::end(v));\n            return std::make_tuple(std::get<0>(temp), std::get<1>(temp), std::get<2>(temp));\n        }\n        else\n        {\n            using ReturnType = std::tuple<Real, Real, Real, Real>;\n            ReturnType temp = detail::means_and_covariance_seq_impl<ReturnType>(std::begin(u), std::end(u), std::begin(v), std::end(v));\n            return std::make_tuple(std::get<0>(temp), std::get<1>(temp), std::get<2>(temp));\n        }\n    }\n    else\n    {\n        if constexpr (std::is_integral_v<Real>)\n        {\n            using ReturnType = std::tuple<double, double, double, double>;\n            ReturnType temp = detail::means_and_covariance_parallel_impl<ReturnType>(std::begin(u), std::end(u), std::begin(v), std::end(v));\n            return std::make_tuple(std::get<0>(temp), std::get<1>(temp), std::get<2>(temp));\n        }\n        else\n        {\n            using ReturnType = std::tuple<Real, Real, Real, Real>;\n            ReturnType temp = detail::means_and_covariance_parallel_impl<ReturnType>(std::begin(u), std::end(u), std::begin(v), std::end(v));\n            return std::make_tuple(std::get<0>(temp), std::get<1>(temp), std::get<2>(temp));\n        }\n    }\n}\n\ntemplate<typename Container>\ninline auto means_and_covariance(Container const & u, Container const & v)\n{\n    return means_and_covariance(std::execution::seq, u, v);\n}\n\ntemplate<typename ExecutionPolicy, typename Container>\ninline auto covariance(ExecutionPolicy&& exec, Container const & u, Container const & v)\n{\n    return std::get<2>(means_and_covariance(exec, u, v));\n}\n\ntemplate<typename Container>\ninline auto covariance(Container const & u, Container const & v)\n{\n    return covariance(std::execution::seq, u, v);\n}\n\ntemplate<typename ExecutionPolicy, typename Container, typename Real = typename Container::value_type>\ninline auto correlation_coefficient(ExecutionPolicy&& exec, Container const & u, Container const & v)\n{\n    if constexpr (std::is_same_v<std::remove_reference_t<decltype(exec)>, decltype(std::execution::seq)>)\n    {\n        if constexpr (std::is_integral_v<Real>)\n        {\n            using ReturnType = std::tuple<double, double, double, double, double, double, double>;\n            return std::get<5>(detail::correlation_coefficient_seq_impl<ReturnType>(std::begin(u), std::end(u), std::begin(v), std::end(v)));\n        }\n        else\n        {\n            using ReturnType = std::tuple<Real, Real, Real, Real, Real, Real, Real>;\n            return std::get<5>(detail::correlation_coefficient_seq_impl<ReturnType>(std::begin(u), std::end(u), std::begin(v), std::end(v)));\n        }\n    }\n    else\n    {\n        if constexpr (std::is_integral_v<Real>)\n        {\n            using ReturnType = std::tuple<double, double, double, double, double, double, double>;\n            return std::get<5>(detail::correlation_coefficient_parallel_impl<ReturnType>(std::begin(u), std::end(u), std::begin(v), std::end(v)));\n        }\n        else\n        {\n            using ReturnType = std::tuple<Real, Real, Real, Real, Real, Real, Real>;\n            return std::get<5>(detail::correlation_coefficient_parallel_impl<ReturnType>(std::begin(u), std::end(u), std::begin(v), std::end(v)));\n        }\n    }\n}\n\ntemplate<typename Container, typename Real = typename Container::value_type>\ninline auto correlation_coefficient(Container const & u, Container const & v)\n{\n    return correlation_coefficient(std::execution::seq, u, v);\n}\n\n#else // C++11 bindings\n\ntemplate<typename Container, typename Real = typename Container::value_type, typename std::enable_if<std::is_integral<Real>::value, bool>::type = true>\ninline auto means_and_covariance(Container const & u, Container const & v) -> std::tuple<double, double, double>\n{\n    using ReturnType = std::tuple<double, double, double, double>;\n    ReturnType temp = detail::means_and_covariance_seq_impl<ReturnType>(std::begin(u), std::end(u), std::begin(v), std::end(v));\n    return std::make_tuple(std::get<0>(temp), std::get<1>(temp), std::get<2>(temp));\n}\n\ntemplate<typename Container, typename Real = typename Container::value_type, typename std::enable_if<!std::is_integral<Real>::value, bool>::type = true>\ninline auto means_and_covariance(Container const & u, Container const & v) -> std::tuple<Real, Real, Real>\n{\n    using ReturnType = std::tuple<Real, Real, Real, Real>;\n    ReturnType temp = detail::means_and_covariance_seq_impl<ReturnType>(std::begin(u), std::end(u), std::begin(v), std::end(v));\n    return std::make_tuple(std::get<0>(temp), std::get<1>(temp), std::get<2>(temp));\n}\n\ntemplate<typename Container, typename Real = typename Container::value_type, typename std::enable_if<std::is_integral<Real>::value, bool>::type = true>\ninline double covariance(Container const & u, Container const & v)\n{\n    using ReturnType = std::tuple<double, double, double, double>;\n    return std::get<2>(detail::means_and_covariance_seq_impl<ReturnType>(std::begin(u), std::end(u), std::begin(v), std::end(v)));\n}\n\ntemplate<typename Container, typename Real = typename Container::value_type, typename std::enable_if<!std::is_integral<Real>::value, bool>::type = true>\ninline Real covariance(Container const & u, Container const & v)\n{\n    using ReturnType = std::tuple<Real, Real, Real, Real>;\n    return std::get<2>(detail::means_and_covariance_seq_impl<ReturnType>(std::begin(u), std::end(u), std::begin(v), std::end(v)));\n}\n\ntemplate<typename Container, typename Real = typename Container::value_type, typename std::enable_if<std::is_integral<Real>::value, bool>::type = true>\ninline double correlation_coefficient(Container const & u, Container const & v)\n{\n    using ReturnType = std::tuple<double, double, double, double, double, double, double>;\n    return std::get<5>(detail::correlation_coefficient_seq_impl<ReturnType>(std::begin(u), std::end(u), std::begin(v), std::end(v)));\n}\n\ntemplate<typename Container, typename Real = typename Container::value_type, typename std::enable_if<!std::is_integral<Real>::value, bool>::type = true>\ninline Real correlation_coefficient(Container const & u, Container const & v)\n{\n    using ReturnType = std::tuple<Real, Real, Real, Real, Real, Real, Real>;\n    return std::get<5>(detail::correlation_coefficient_seq_impl<ReturnType>(std::begin(u), std::end(u), std::begin(v), std::end(v)));\n}\n\n#endif\n\n}}} // namespace boost::math::statistics\n\n#endif\n", "meta": {"hexsha": "1723e027a2d0600b804adcc01104578baf9594f9", "size": 18298, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/math/statistics/bivariate_statistics.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/statistics/bivariate_statistics.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/statistics/bivariate_statistics.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": 38.9319148936, "max_line_length": 152, "alphanum_fraction": 0.6510001093, "num_tokens": 4961, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321720225278, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.4562814712548519}}
{"text": "#include <CGAL/Simple_cartesian.h>\n#include <CGAL/Surface_mesh.h>\n#include <CGAL/Surface_mesh_simplification/Policies/Edge_collapse/Edge_profile.h>\n#include <boost/tuple/tuple.hpp>\n#include <boost/tuple/tuple_comparison.hpp>\n#include <fstream>\n\ntypedef CGAL::Simple_cartesian<double> K;\ntypedef CGAL::Surface_mesh<K::Point_3> Mesh;\ntypedef CGAL::Surface_mesh_simplification::Edge_profile<Mesh> Profile;\n\nvoid naive_all_triangles(Mesh::Halfedge_index h, Mesh& m, std::set<Mesh::Face_index>& triangles)\n{\n  for(Mesh::Halfedge_index hh : CGAL::halfedges_around_source(h, m))\n  {\n    if(!is_border(hh, m))\n      triangles.insert(face(hh,m));\n  }\n  for(Mesh::Halfedge_index hh : CGAL::halfedges_around_target(h, m))\n  {\n    if(!is_border(hh, m))\n      triangles.insert(face(hh,m));\n  }\n}\n\nvoid naive_link_vertices(Mesh::Halfedge_index h, Mesh& m,\n                         const std::set<Mesh::Face_index>& triangles,\n                         std::set<Mesh::Vertex_index>& link_vertices)\n{\n  for(Mesh::Face_index f : triangles)\n  {\n    for(Mesh::Halfedge_index h : CGAL::halfedges_around_face(halfedge(f, m), m))\n    {\n      link_vertices.insert(target(h, m));\n    }\n  }\n  link_vertices.erase(source(h, m));\n  link_vertices.erase(target(h, m));\n}\n\nstruct A{};\n\nboost::tuple<Mesh::Vertex_index, Mesh::Vertex_index, Mesh::Vertex_index>\nmake_canonical_tuple(Mesh::Vertex_index v1, Mesh::Vertex_index v2, Mesh::Vertex_index v3)\n{\n  Mesh::Vertex_index vs[3]={v1, v2, v3};\n  std::sort(&vs[0], &vs[0]+3);\n  return boost::make_tuple(vs[0], vs[1], vs[2]);\n}\n\nboost::tuple<Mesh::Vertex_index, Mesh::Vertex_index, Mesh::Vertex_index>\nmake_canonical_tuple(const Profile::Triangle& t)\n{\n  return make_canonical_tuple(t.v0, t.v1, t.v2);\n}\n\nboost::tuple<Mesh::Vertex_index, Mesh::Vertex_index, Mesh::Vertex_index>\nmake_canonical_tuple(Mesh::Face_index f, Mesh& m)\n{\n  Mesh::Halfedge_index h=halfedge(f, m);\n  return make_canonical_tuple(source(h,m), target(h,m), target(next(h, m), m));\n}\n\nvoid test(const char* fname)\n{\n  Mesh m;\n  std::ifstream input(fname);\n  assert(!input.fail());\n  input >> m;\n  assert(num_vertices(m)!=0);\n  A a;\n\n  for(Mesh::Halfedge_index h : halfedges(m))\n  {\n    std::set<Mesh::Face_index> triangles;\n    naive_all_triangles(h, m, triangles);\n\n    Profile profile(h, m, K(), a, get(boost::vertex_point, m), a, true);\n\n    if(CGAL::Euler::does_satisfy_link_condition(edge(h, m), m))\n    {\n      std::set<Mesh::Vertex_index> link_vertices;\n      naive_link_vertices(h, m, triangles, link_vertices);\n      assert(link_vertices.size()==profile.link().size());\n      assert(std::set<Mesh::Vertex_index>(profile.link().begin(),\n                                           profile.link().end()).size()\n              == link_vertices.size());\n\n      for(const Mesh::Vertex_index& v : profile.link())\n      {\n        assert(link_vertices.count(v) == 1);\n      }\n    }\n\n    assert(triangles.size() == profile.triangles().size());\n    std::set<boost::tuple<Mesh::Vertex_index, Mesh::Vertex_index, Mesh::Vertex_index> > triple_set;\n    for(const Profile::Triangle& t : profile.triangles())\n    {\n      triple_set.insert(make_canonical_tuple(t));\n    }\n    for(Mesh::Face_index f : triangles)\n    {\n      assert(triple_set.count(make_canonical_tuple(f, m)) == 1);\n    }\n  }\n}\n\nint main(int argc, char** argv)\n{\n  for(int i=1; i<argc; ++i)\n  {\n    std::cout << \"Testing \" << argv[i] << \"\\n\";\n    test(argv[i]);\n  }\n  if(argc==1)\n  {\n    std::cout << \"No file provided, nothing tested\\n\";\n  }\n\n  return 0;\n}\n\n", "meta": {"hexsha": "379de3f46b6fe20234eea6503bd8bd1419882cf8", "size": 3500, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Surface_mesh_simplification/test/Surface_mesh_simplification/test_edge_profile_link.cpp", "max_stars_repo_name": "ffteja/cgal", "max_stars_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 3227.0, "max_stars_repo_stars_event_min_datetime": "2015-03-05T00:19:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:20:35.000Z", "max_issues_repo_path": "Surface_mesh_simplification/test/Surface_mesh_simplification/test_edge_profile_link.cpp", "max_issues_repo_name": "ffteja/cgal", "max_issues_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 5574.0, "max_issues_repo_issues_event_min_datetime": "2015-03-05T00:01:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:08:11.000Z", "max_forks_repo_path": "Surface_mesh_simplification/test/Surface_mesh_simplification/test_edge_profile_link.cpp", "max_forks_repo_name": "ffteja/cgal", "max_forks_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1274.0, "max_forks_repo_forks_event_min_datetime": "2015-03-05T00:01:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:47:56.000Z", "avg_line_length": 28.4552845528, "max_line_length": 99, "alphanum_fraction": 0.6537142857, "num_tokens": 963, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321720225279, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.45628146636812944}}
{"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#include <boost/simd/bitwise/include/functions/ctz.hpp>\n#include <boost/dispatch/functor/meta/call.hpp>\n#include <nt2/sdk/unit/tests/relation.hpp>\n#include <nt2/sdk/unit/tests/type_expr.hpp>\n#include <nt2/sdk/unit/tests/exceptions.hpp>\n#include <nt2/sdk/unit/module.hpp>\n#include <boost/simd/include/constants/zero.hpp>\n#include <boost/simd/include/constants/one.hpp>\n#include <boost/simd/include/constants/signmask.hpp>\n#include <boost/simd/include/constants/nbmantissabits.hpp>\n#include <boost/simd/include/constants/nan.hpp>\n#include <boost/simd/include/constants/inf.hpp>\n#include <boost/simd/include/constants/minf.hpp>\n#include <boost/simd/sdk/config.hpp>\n\nNT2_TEST_CASE_TPL ( ctz_real,  BOOST_SIMD_REAL_TYPES)\n{\n  using boost::simd::ctz;\n  using boost::simd::tag::ctz_;\n  typedef typename boost::dispatch::meta::call<ctz_(T)>::type r_t;\n  typedef typename boost::dispatch::meta::as_integer<T>::type wished_r_t;\n\n  // return type conformity test\n  NT2_TEST_TYPE_IS(r_t, wished_r_t);\n\n  // specific values tests\n#ifndef BOOST_SIMD_NO_INVALIDS\n  NT2_TEST_EQUAL(ctz(boost::simd::Inf<T>()), r_t(boost::simd::Nbmantissabits<T>()));\n  NT2_TEST_EQUAL(ctz(boost::simd::Minf<T>()), r_t(boost::simd::Nbmantissabits<T>()));\n  NT2_TEST_EQUAL(ctz(boost::simd::Nan<T>()), r_t(boost::simd::Zero<r_t>()));\n#endif\n  NT2_TEST_ASSERT(ctz(boost::simd::Zero<T>()));\n  NT2_TEST_EQUAL(ctz(boost::simd::Signmask<T>()), r_t(sizeof(T)*8-1));\n} // end of test for real_\n\nNT2_TEST_CASE_TPL ( ctz_signed_int,  BOOST_SIMD_INTEGRAL_SIGNED_TYPES)\n{\n  using boost::simd::ctz;\n  using boost::simd::tag::ctz_;\n  using boost::simd::Nbmantissabits;\n  using boost::simd::Signmask;\n\n  typedef typename boost::dispatch::meta::call<ctz_(T)>::type r_t;\n\n  for(std::size_t j=0; j< (sizeof(T)*CHAR_BIT-1); j++)\n  {\n    // Test 01111 ... 10000b\n    T value = ~T(0) & ~((T(1)<<j)-1);\n    NT2_TEST_EQUAL(ctz( value ), r_t(j));\n    NT2_TEST_EQUAL(ctz( T(-value) ), r_t(j));\n  }\n\n  NT2_TEST_EQUAL(ctz(Signmask<T>()) , r_t(sizeof(T)*CHAR_BIT-1) );\n}\n\nNT2_TEST_CASE_TPL( ctz_unsigned_integer, BOOST_SIMD_UNSIGNED_TYPES )\n{\n  using boost::simd::ctz;\n  using boost::simd::tag::ctz_;\n\n  typedef typename boost::dispatch::meta::call<ctz_(T)>::type r_t;\n  typedef typename boost::dispatch::meta::as_integer<T>::type wished_r_t;\n\n  // return type conformity test\n  NT2_TEST_TYPE_IS(r_t, wished_r_t);\n\n  // specific values tests\n  for(std::size_t j=0; j< sizeof(T)*CHAR_BIT; j++)\n  {\n    // Test 1111 ... 10000b\n    T value = ~T(0) & ~((T(1)<<j)-1);\n    NT2_TEST_EQUAL(ctz( value ), r_t(j));\n  }\n }\n", "meta": {"hexsha": "5820b09759dbd9498493383a041dd42f8a975514", "size": 3055, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/base/unit/bitwise/scalar/ctz.cpp", "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/unit/bitwise/scalar/ctz.cpp", "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/unit/bitwise/scalar/ctz.cpp", "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.8072289157, "max_line_length": 85, "alphanum_fraction": 0.6546644845, "num_tokens": 887, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6406358411176238, "lm_q2_score": 0.712232184238947, "lm_q1q2_score": 0.45628146442096024}}
{"text": "/**\n * @file tree_test.cpp\n *\n * Tests for tree-building methods.\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#include <mlpack/core.hpp>\n#include <mlpack/core/tree/bounds.hpp>\n#include <mlpack/core/metrics/lmetric.hpp>\n#include <mlpack/methods/neighbor_search/neighbor_search.hpp>\n#include <mlpack/core/tree/binary_space_tree.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n\nusing namespace mlpack;\nusing namespace mlpack::math;\nusing namespace mlpack::tree;\nusing namespace mlpack::neighbor;\nusing namespace mlpack::metric;\nusing namespace mlpack::bound;\n\nBOOST_AUTO_TEST_SUITE(VantagePointTreeTest);\n\nBOOST_AUTO_TEST_CASE(VPTreeTraitsTest)\n{\n  typedef VPTree<EuclideanDistance, EmptyStatistic, arma::mat> TreeType;\n\n  bool b = TreeTraits<TreeType>::HasOverlappingChildren;\n  BOOST_REQUIRE_EQUAL(b, true);\n  b = TreeTraits<TreeType>::FirstPointIsCentroid;\n  BOOST_REQUIRE_EQUAL(b, false);\n  b = TreeTraits<TreeType>::HasSelfChildren;\n  BOOST_REQUIRE_EQUAL(b, false);\n  b = TreeTraits<TreeType>::RearrangesDataset;\n  BOOST_REQUIRE_EQUAL(b, true);\n  b = TreeTraits<TreeType>::BinaryTree;\n  BOOST_REQUIRE_EQUAL(b, true);\n}\n\nBOOST_AUTO_TEST_CASE(HollowBallBoundTest)\n{\n  HollowBallBound<EuclideanDistance> b(2, 4, arma::vec(\"1.0 2.0 3.0 4.0 5.0\"));\n\n  BOOST_REQUIRE_EQUAL(b.Contains(arma::vec(\"1.0 2.0 3.0 7.0 5.0\")), true);\n\n  BOOST_REQUIRE_EQUAL(b.Contains(arma::vec(\"1.0 2.0 3.0 9.0 5.0\")), false);\n\n  BOOST_REQUIRE_EQUAL(b.Contains(arma::vec(\"1.0 2.0 3.0 5.0 5.0\")), false);\n\n  HollowBallBound<EuclideanDistance> b2(0.5, 1,\n      arma::vec(\"1.0 2.0 3.0 7.0 5.0\"));\n  BOOST_REQUIRE_EQUAL(b.Contains(b2), true);\n\n  b2 = HollowBallBound<EuclideanDistance>(2.5, 3.5,\n      arma::vec(\"1.0 2.0 3.0 4.5 5.0\"));\n  BOOST_REQUIRE_EQUAL(b.Contains(b2), true);\n\n  b2 = HollowBallBound<EuclideanDistance>(2.0, 3.5,\n      arma::vec(\"1.0 2.0 3.0 4.5 5.0\"));\n  BOOST_REQUIRE_EQUAL(b.Contains(b2), false);\n\n  BOOST_REQUIRE_CLOSE(b.MinDistance(arma::vec(\"1.0 2.0 8.0 4.0 5.0\")), 1.0,\n      1e-5);\n  BOOST_REQUIRE_CLOSE(b.MinDistance(arma::vec(\"1.0 2.0 4.0 4.0 5.0\")), 1.0,\n      1e-5);\n  BOOST_REQUIRE_CLOSE(b.MinDistance(arma::vec(\"1.0 2.0 3.0 4.0 5.0\")), 2.0,\n      1e-5);\n  BOOST_REQUIRE_CLOSE(b.MinDistance(arma::vec(\"1.0 2.0 5.0 4.0 5.0\")), 0.0,\n      1e-5);\n  BOOST_REQUIRE_CLOSE(b.MinDistance(arma::vec(\"5.0 2.0 3.0 4.0 5.0\")), 0.0,\n      1e-5);\n  BOOST_REQUIRE_CLOSE(b.MinDistance(arma::vec(\"3.0 2.0 3.0 4.0 5.0\")), 0.0,\n      1e-5);\n\n  BOOST_REQUIRE_CLOSE(b.MaxDistance(arma::vec(\"1.0 2.0 4.0 4.0 5.0\")), 5.0,\n      1e-5);\n  BOOST_REQUIRE_CLOSE(b.MaxDistance(arma::vec(\"1.0 2.0 8.0 4.0 5.0\")), 9.0,\n      1e-5);\n  BOOST_REQUIRE_CLOSE(b.MaxDistance(arma::vec(\"1.0 2.0 3.0 4.0 5.0\")), 4.0,\n      1e-5);\n\n  b2 = HollowBallBound<EuclideanDistance>(3, 4,\n      arma::vec(\"1.0 2.0 3.0 5.0 5.0\"));\n  BOOST_REQUIRE_CLOSE(b.MinDistance(b2), 0.0, 1e-5);\n\n  b2 = HollowBallBound<EuclideanDistance>(1, 2,\n      arma::vec(\"1.0 2.0 3.0 4.0 5.0\"));\n  BOOST_REQUIRE_CLOSE(b.MinDistance(b2), 0.0, 1e-5);\n\n  b2 = HollowBallBound<EuclideanDistance>(0.5, 1.0,\n      arma::vec(\"1.0 2.5 3.0 4.0 5.0\"));\n  BOOST_REQUIRE_CLOSE(b.MinDistance(b2), 0.5, 1e-5);\n\n  b2 = HollowBallBound<EuclideanDistance>(0.5, 1.0,\n      arma::vec(\"1.0 8.0 3.0 4.0 5.0\"));\n  BOOST_REQUIRE_CLOSE(b.MinDistance(b2), 1.0, 1e-5);\n\n  b2 = HollowBallBound<EuclideanDistance>(0.5, 2.0,\n      arma::vec(\"1.0 8.0 3.0 4.0 5.0\"));\n  BOOST_REQUIRE_CLOSE(b.MinDistance(b2), 0.0, 1e-5);\n\n  b2 = HollowBallBound<EuclideanDistance>(0.5, 2.0,\n      arma::vec(\"1.0 8.0 3.0 4.0 5.0\"));\n  BOOST_REQUIRE_CLOSE(b.MaxDistance(b2), 12.0, 1e-5);\n  \n  b2 = HollowBallBound<EuclideanDistance>(0.5, 2.0,\n      arma::vec(\"1.0 3.0 3.0 4.0 5.0\"));\n  BOOST_REQUIRE_CLOSE(b.MaxDistance(b2), 7.0, 1e-5);\n\n  HollowBallBound<EuclideanDistance> b1 = b;\n  b2 = HollowBallBound<EuclideanDistance>(1.0, 2.0,\n      arma::vec(\"1.0 2.5 3.0 4.0 5.0\"));\n\n  b1 |= b2;\n  BOOST_REQUIRE_CLOSE(b1.InnerRadius(), 0.5, 1e-5);\n  \n  b1 = b;\n  b2 = HollowBallBound<EuclideanDistance>(0.5, 2.0,\n      arma::vec(\"1.0 3.0 3.0 4.0 5.0\"));\n  b1 |= b2;\n  BOOST_REQUIRE_CLOSE(b1.InnerRadius(), 0.0, 1e-5);\n\n  b1 = b;\n  b2 = HollowBallBound<EuclideanDistance>(0.5, 4.0,\n      arma::vec(\"1.0 3.0 3.0 4.0 5.0\"));\n  b1 |= b2;\n  BOOST_REQUIRE_CLOSE(b1.OuterRadius(), 5.0, 1e-5);\n}\n\ntemplate<typename TreeType>\nvoid CheckBound(TreeType& tree)\n{\n  typedef typename TreeType::ElemType ElemType;\n  if (tree.IsLeaf())\n  {\n    // Ensure that the bound contains all descendant points.\n    for (size_t i = 0; i < tree.NumPoints(); i++)\n    {\n      ElemType dist = tree.Bound().Metric().Evaluate(tree.Bound().Center(),\n          tree.Dataset().col(tree.Point(i)));\n      ElemType hollowDist = tree.Bound().Metric().Evaluate(\n          tree.Bound().HollowCenter(),\n          tree.Dataset().col(tree.Point(i)));\n\n      BOOST_REQUIRE_LE(tree.Bound().InnerRadius(), hollowDist  *\n          (1.0 + 10.0 * std::numeric_limits<ElemType>::epsilon()));\n\n      BOOST_REQUIRE_LE(dist, tree.Bound().OuterRadius() *\n          (1.0 + 10.0 * std::numeric_limits<ElemType>::epsilon()));\n    }\n  }\n  else\n  {\n    // Ensure that the bound contains all descendant points.\n    for (size_t i = 0; i < tree.NumDescendants(); i++)\n    {\n      ElemType dist = tree.Bound().Metric().Evaluate(tree.Bound().Center(),\n          tree.Dataset().col(tree.Descendant(i)));\n      ElemType hollowDist = tree.Bound().Metric().Evaluate(\n          tree.Bound().HollowCenter(),\n          tree.Dataset().col(tree.Descendant(i)));\n\n      BOOST_REQUIRE_LE(tree.Bound().InnerRadius(), hollowDist  *\n          (1.0 + 10.0 * std::numeric_limits<ElemType>::epsilon()));\n\n      BOOST_REQUIRE_LE(dist, tree.Bound().OuterRadius() *\n          (1.0 + 10.0 * std::numeric_limits<ElemType>::epsilon()));\n    }\n\n    CheckBound(*tree.Left());\n    CheckBound(*tree.Right());\n  }\n}\n\nBOOST_AUTO_TEST_CASE(VPTreeBoundTest)\n{\n  typedef VPTree<EuclideanDistance, EmptyStatistic, arma::mat> TreeType;\n\n  arma::mat dataset(8, 1000);\n  dataset.randu();\n\n  TreeType tree(dataset);\n  CheckBound(tree);\n}\n\nBOOST_AUTO_TEST_CASE(VPTreeTest)\n{\n  typedef VPTree<EuclideanDistance, EmptyStatistic, arma::mat> TreeType;\n\n  size_t maxRuns = 10; // Ten total tests.\n  size_t pointIncrements = 1000; // Range is from 2000 points to 11000.\n\n  // We use the default leaf size of 20.\n  for (size_t run = 0; run < maxRuns; run++)\n  {\n    size_t dimensions = run + 2;\n    size_t maxPoints = (run + 1) * pointIncrements;\n\n    size_t size = maxPoints;\n    arma::mat dataset = arma::mat(dimensions, size);\n    arma::mat datacopy; // Used to test mappings.\n\n    // Mappings for post-sort verification of data.\n    std::vector<size_t> newToOld;\n    std::vector<size_t> oldToNew;\n\n    // Generate data.\n    dataset.randu();\n\n    // Build the tree itself.\n    TreeType root(dataset, newToOld, oldToNew);\n    const arma::mat& treeset = root.Dataset();\n\n    // Ensure the size of the tree is correct.\n    BOOST_REQUIRE_EQUAL(root.NumDescendants(), size);\n\n    // Check the forward and backward mappings for correctness.\n    for(size_t i = 0; i < size; i++)\n    {\n      for(size_t j = 0; j < dimensions; j++)\n      {\n        BOOST_REQUIRE_EQUAL(treeset(j, i), dataset(j, newToOld[i]));\n        BOOST_REQUIRE_EQUAL(treeset(j, oldToNew[i]), dataset(j, i));\n      }\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE(SingleTreeTraverserTest)\n{\n  arma::mat dataset;\n  dataset.randu(8, 1000); // 1000 points in 8 dimensions.\n  arma::Mat<size_t> neighbors1;\n  arma::mat distances1;\n  arma::Mat<size_t> neighbors2;\n  arma::mat distances2;\n\n  // Nearest neighbor search with the VP tree.\n  NeighborSearch<NearestNeighborSort, metric::LMetric<2, true>, arma::mat,\n      VPTree> knn1(dataset, SINGLE_TREE_MODE);\n\n  knn1.Search(5, neighbors1, distances1);\n\n  // Nearest neighbor search the naive way.\n  KNN knn2(dataset, NAIVE_MODE);\n\n  knn2.Search(5, neighbors2, distances2);\n\n  for (size_t i = 0; i < neighbors1.size(); i++)\n  {\n    BOOST_REQUIRE_EQUAL(neighbors1[i], neighbors2[i]);\n    BOOST_REQUIRE_EQUAL(distances1[i], distances2[i]);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(DualTreeTraverserTest)\n{\n  arma::mat dataset;\n  dataset.randu(8, 1000); // 1000 points in 8 dimensions.\n  arma::Mat<size_t> neighbors1;\n  arma::mat distances1;\n  arma::Mat<size_t> neighbors2;\n  arma::mat distances2;\n\n  // Nearest neighbor search with the VP tree.\n  NeighborSearch<NearestNeighborSort, metric::LMetric<2, true>, arma::mat,\n      VPTree> knn1(dataset, DUAL_TREE_MODE);\n\n  knn1.Search(5, neighbors1, distances1);\n\n  // Nearest neighbor search the naive way.\n  KNN knn2(dataset, NAIVE_MODE);\n\n  knn2.Search(5, neighbors2, distances2);\n\n  for (size_t i = 0; i < neighbors1.size(); i++)\n  {\n    BOOST_REQUIRE_EQUAL(neighbors1[i], neighbors2[i]);\n    BOOST_REQUIRE_EQUAL(distances1[i], distances2[i]);\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "ba60f2d126e43891d21ca64282903bc88d3c35ff", "size": 9039, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/vantage_point_tree_test.cpp", "max_stars_repo_name": "NaxAlpha/mlpack-build", "max_stars_repo_head_hexsha": "1f0c1454d4b35eb97ff115669919c205cee5bd1c", "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": "2018-05-21T11:08:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T07:52:14.000Z", "max_issues_repo_path": "src/mlpack/tests/vantage_point_tree_test.cpp", "max_issues_repo_name": "okmegy/Mlpack", "max_issues_repo_head_hexsha": "ac9abef3c1353f483ed1af42ba5a7432f291ca1a", "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/tests/vantage_point_tree_test.cpp", "max_forks_repo_name": "okmegy/Mlpack", "max_forks_repo_head_hexsha": "ac9abef3c1353f483ed1af42ba5a7432f291ca1a", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.276816609, "max_line_length": 79, "alphanum_fraction": 0.6652284545, "num_tokens": 3018, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.45628146442096024}}
{"text": "#include <boost/math/distributions/students_t.hpp>\n", "meta": {"hexsha": "62537df87c465a2b7320fded5472f01285dcafc3", "size": 51, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_distributions_students_t.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_distributions_students_t.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_distributions_students_t.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 25.5, "max_line_length": 50, "alphanum_fraction": 0.8235294118, "num_tokens": 11, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.800692021119887, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.45627647120132786}}
{"text": "// Copyright (C) 2013 Massachusetts Institute of Technology, Lincoln Laboratory\n// License: Boost Software License   See LICENSE.txt for the full license.\n// Authors: Davis E. King (davis@dlib.net)\n\n#include \"cca_morph.h\"\n#include <map>\n#include <dlib/matrix.h>\n#include <dlib/statistics.h>\n#include <mitie/approximate_substring_set.h>\n#include <mitie/total_word_feature_extractor.h>\n\nusing namespace std;\nusing namespace dlib;\nusing namespace mitie;\n\ntypedef std::vector<std::pair<dlib::uint32, float> > sparse_vector_type;\n\n// ----------------------------------------------------------------------------------------\n\nsparse_vector_type dense_to_sparse (\n    const matrix<float,0,1>& vect\n)\n{\n    sparse_vector_type res(vect.size());\n    for (long i = 0; i < vect.size(); ++i)\n        res[i] = std::make_pair(i, vect(i));\n    return res;\n}\n\n// ----------------------------------------------------------------------------------------\n\nvoid learn_morphological_dimension_reduction (\n    const approximate_substring_set& substrs,\n    const std::map<std::string, matrix<float,0,1> >& word_vectors,\n    const long num_correlations,\n    matrix<float>& morph_trans\n)\n{\n    std::map<std::string, matrix<float,0,1> >::const_iterator i;\n\n\n    std::vector<sparse_vector_type> L, R;\n\n    sparse_vector_type temp;\n    std::vector<dlib::uint16> hits;\n    \n    cout << \"building morphological vectors\" << endl;\n    for (i = word_vectors.begin(); i != word_vectors.end(); ++i)\n    {\n        L.push_back(dense_to_sparse(i->second));\n        substrs.find_substrings(i->first, hits);\n        temp.clear();\n        for (unsigned long i = 0; i < hits.size(); ++i)\n            temp.push_back(make_pair(hits[i],1));\n        make_sparse_vector_inplace(temp);\n        R.push_back(temp);\n    }\n    cout << \"L.size(): \" << L.size() << endl;\n    cout << \"R.size(): \" << R.size() << endl;\n\n    cout << \"Now running CCA on word <-> morphology...\" << endl;\n    matrix<float> Ltrans;\n    cout << \"correlations: \" << trans(cca(L, R, Ltrans, morph_trans, num_correlations, 1000, 2)) << endl;\n    //print_true_correlations(L, R, Ltrans, morph_trans);\n}\n\n// ----------------------------------------------------------------------------------------\n\nvoid cca_morph(const dlib::command_line_parser& parser)\n{\n    const long num_morph_correlations = 90;\n\n    std::ifstream fin(\"word_vects.dat\", ios::binary);\n    std::map<std::string, matrix<float,0,1> > word_vectors;\n    deserialize(word_vectors, fin);\n    cout << \"num word vectors loaded: \" << word_vectors.size() << endl;\n    cout << \"got word vectors, now learn how they correlate with morphological features.\" << endl;\n\n    fin.close();\n    fin.open(\"substring_set.dat\", ios::binary);\n    approximate_substring_set substring_set;\n    deserialize(substring_set, fin);\n\n    matrix<float> morph_trans;\n    learn_morphological_dimension_reduction(substring_set, word_vectors, num_morph_correlations, morph_trans);\n\n    // morph_trans should have a row for every possible output from substring_set.  But\n    // since we work with sparse vectors and some outputs might not have been observed in\n    // learn_morphological_dimension_reduction() we need to make sure this is the case.\n    if (morph_trans.nr() != substring_set.max_substring_id()+1)\n    {\n        matrix<float> temp(substring_set.max_substring_id()+1, morph_trans.nc());\n        set_subm(temp, get_rect(morph_trans)) = morph_trans;\n        temp.swap(morph_trans);\n    }\n\n\n    word_morphology_feature_extractor fe(substring_set, morph_trans);\n    cout << \"morphological feature dimensionality: \"<< fe.get_num_dimensions() << endl;\n\n    ofstream fout(\"word_morph_feature_extractor.dat\", ios::binary);\n    serialize(fe, fout);\n\n    total_word_feature_extractor tfe(word_vectors, fe);\n    cout << \"total word feature dimensionality: \"<< tfe.get_num_dimensions() << endl;\n    serialize(\"total_word_feature_extractor.dat\") << \"mitie::total_word_feature_extractor\" << tfe;\n}\n\n// ----------------------------------------------------------------------------------------\n\n", "meta": {"hexsha": "48d74b9b1dbe9d1ee43f6bb1816b84e5cabb8791", "size": 4038, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tools/wordrep/src/cca_morph.cpp", "max_stars_repo_name": "maxmert/nlp-mitie", "max_stars_repo_head_hexsha": "ec3153ef2fe7a80e7cf3d80d14b388b8cd679343", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2695.0, "max_stars_repo_stars_event_min_datetime": "2015-01-01T21:13:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T04:45:32.000Z", "max_issues_repo_path": "tools/wordrep/src/cca_morph.cpp", "max_issues_repo_name": "maxmert/nlp-mitie", "max_issues_repo_head_hexsha": "ec3153ef2fe7a80e7cf3d80d14b388b8cd679343", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 208.0, "max_issues_repo_issues_event_min_datetime": "2015-01-23T19:29:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-08T02:55:17.000Z", "max_forks_repo_path": "tools/wordrep/src/cca_morph.cpp", "max_forks_repo_name": "maxmert/nlp-mitie", "max_forks_repo_head_hexsha": "ec3153ef2fe7a80e7cf3d80d14b388b8cd679343", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 567.0, "max_forks_repo_forks_event_min_datetime": "2015-01-06T19:22:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T17:01:04.000Z", "avg_line_length": 36.3783783784, "max_line_length": 110, "alphanum_fraction": 0.6270430906, "num_tokens": 924, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4562764603604894}}
{"text": "#pragma once\n#include <vector>\n#include <boost/serialization/access.hpp>\n\nnamespace snn::internal\n{\n    struct binaryClassification\n    {\n        float truePositive{};\n        float trueNegative{};\n        float falsePositive{};\n        float falseNegative{};\n        float totalError{};\n\n        bool operator==(const binaryClassification&) const\n        {\n            return true;\n        };\n\n        template <typename Archive>\n        void serialize(Archive& ar, unsigned)\n        {\n            ar & truePositive;\n            ar & trueNegative;\n            ar & falsePositive;\n            ar & falseNegative;\n        }\n    };\n\n    class StatisticAnalysis\n    {\n    private:\n        friend class boost::serialization::access;\n        template <class Archive>\n        void serialize(Archive& ar, unsigned version);\n\n        std::vector<binaryClassification> clusters;\n        float numberOfDataWellClassified;\n        float numberOfDataMisclassified;\n\n        float globalClusteringRate = -1.0f;\n        float weightedClusteringRate = -1.0f;\n        float f1Score = -1.0f;\n        float meanAbsoluteError = -1.0f;\n        float rootMeanSquaredError = -1.0f;\n\n        float globalClusteringRateMax = -1.0f;\n        float weightedClusteringRateMax = -1.0f;\n        float f1ScoreMax = -1.0f;\n        float meanAbsoluteErrorMin = -1.0f;\n        float rootMeanSquaredErrorMin = -1.0f;\n\n        [[nodiscard]] float computeGlobalClusteringRate() const;\n        [[nodiscard]] float computeWeightedClusteringRate() const;\n        [[nodiscard]] float computeF1Score() const;\n        [[nodiscard]] float computeMeanAbsoluteError() const;\n        [[nodiscard]] float computeRootMeanSquaredError() const;\n\n    protected:\n        StatisticAnalysis() = default;\n        StatisticAnalysis(const StatisticAnalysis&) = default;\n        virtual ~StatisticAnalysis() = default;\n\n        void initialize(int numberOfCluster);\n\n        void setResultsAsNan();\n\n        void evaluateOnceForRegression(const std::vector<float>& outputs, \n                                       const std::vector<float>& desiredOutputs,\n                                       float precision);\n        void evaluateOnceForMultipleClassification(const std::vector<float>& outputs,\n                                                   const std::vector<float>& desiredOutputs,\n                                                   float separator);\n        void evaluateOnceForClassification(const std::vector<float>& outputs,\n                                           int classNumber,\n                                           float separator);\n\n        void startTesting();\n        void stopTesting();\n\n        bool globalClusteringRateIsBetterThanPreviously = false;\n        bool weightedClusteringRateIsBetterThanPreviously = false;\n        bool f1ScoreIsBetterThanPreviously = false;\n        bool meanAbsoluteErrorIsBetterThanPreviously = false;\n        bool rootMeanSquaredErrorIsBetterThanPreviously = false;\n\n    public:\n        float getGlobalClusteringRate() const;\n        float getWeightedClusteringRate() const;\n        float getF1Score() const;\n        float getMeanAbsoluteError() const;\n        float getRootMeanSquaredError() const;\n\n        float getGlobalClusteringRateMax() const;\n        float getWeightedClusteringRateMax() const;\n        float getF1ScoreMax() const;\n        float getMeanAbsoluteErrorMin() const;\n        float getRootMeanSquaredErrorMin() const;\n\n        bool operator==(const StatisticAnalysis& sa) const;\n        bool operator!=(const StatisticAnalysis& sa) const;\n    };\n\n    template <class Archive>\n    void StatisticAnalysis::serialize(Archive& ar, unsigned)\n    {\n        ar & this->clusters;\n        ar & this->numberOfDataWellClassified;\n        ar & this->numberOfDataMisclassified;\n        ar & this->globalClusteringRate;\n        ar & this->weightedClusteringRate;\n        ar & this->f1Score;\n        ar & this->meanAbsoluteError;\n        ar & this->rootMeanSquaredError;\n        ar & this->globalClusteringRateMax;\n        ar & this->weightedClusteringRateMax;\n        ar & this->f1ScoreMax;\n        ar & this->meanAbsoluteErrorMin;\n        ar & this->rootMeanSquaredErrorMin;\n        ar & this->globalClusteringRateIsBetterThanPreviously;\n        ar & this->weightedClusteringRateIsBetterThanPreviously;\n        ar & this->f1ScoreIsBetterThanPreviously;\n        ar & this->meanAbsoluteErrorIsBetterThanPreviously;\n        ar & this->rootMeanSquaredErrorIsBetterThanPreviously;\n    }\n}\n", "meta": {"hexsha": "3e8ad2347a64efb1e4fa437608562e1220e43ae3", "size": 4495, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/neural_network/StatisticAnalysis.hpp", "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/StatisticAnalysis.hpp", "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/StatisticAnalysis.hpp", "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": 35.3937007874, "max_line_length": 92, "alphanum_fraction": 0.6253615128, "num_tokens": 933, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4562764603604894}}
{"text": "/*\n * Copyright 2016-2019 CNRS-UM LIRMM, CNRS-AIST JRL\n * Copyright 2020 ANYbotics AG\n */\n\n#include <iostream>\n#include <numeric>\n\n#include <Eigen/Core>\n\n#include <gtest/gtest.h>\n\n#include \"copra/solvers/all.h\"\n\n#include \"time_invariant_systems.h\"\n\nTEST_F(Problem, QuadProgTest) {  // NOLINT\n    copra::QuadProgDenseSolver qpQuadProg;\n\n    qpQuadProg.SI_problem(nrvars, nreqs, nrineqs);\n    ASSERT_TRUE(qpQuadProg.SI_solve(Q, c, Aeq, beq, Aineq, bineq, XL, XU));\n\n    ASSERT_EQ(qpQuadProg.SI_fail(), 0);\n}\n\nTEST_F(Problem, qpOASESTest) {  // NOLINT\n  copra::qpOASESSolver qpOasesSolver;\n\n  qpOasesSolver.SI_problem(nrvars, nreqs, nrineqs);\n  ASSERT_TRUE(qpOasesSolver.SI_solve(Q, c, Aeq, beq, Aineq, bineq, XL, XU));\n\n  ASSERT_EQ(qpOasesSolver.SI_fail(), 0);\n}\n\nTEST_F(Problem, QLDOnQuadProgTest) {  // NOLINT\n    copra::QLDSolver qpQLD;\n    copra::QuadProgDenseSolver qpQuadProg;\n\n    qpQLD.SI_problem(nrvars, nreqs, nrineqs);\n    qpQuadProg.SI_problem(nrvars, nreqs, nrineqs);\n    ASSERT_TRUE(qpQLD.SI_solve(Q, c, Aeq, beq, Aineq, bineq, XL, XU));\n    ASSERT_TRUE(qpQuadProg.SI_solve(Q, c, Aeq, beq, Aineq, bineq, XL, XU));\n\n    Eigen::VectorXd resQLD = qpQLD.SI_result();\n    Eigen::VectorXd resQuadProg = qpQuadProg.SI_result();\n    EXPECT_TRUE(resQuadProg.isApprox(resQLD));\n    ASSERT_EQ(qpQLD.SI_fail(), 0);\n    ASSERT_EQ(qpQuadProg.SI_fail(), 0);\n}\n\n#ifdef EIGEN_LSSOL_FOUND\nTEST_F(Problem, LSSOLOnQuadProgTest) {  // NOLINT\n    copra::QuadProgDenseSolver qpQuadProg;\n    copra::LSSOLSolver qpLSSOL;\n\n    qpQuadProg.SI_problem(nrvars, nreqs, nrineqs);\n    qpLSSOL.SI_problem(nrvars, nreqs, nrineqs);\n    ASSERT_TRUE(qpQuadProg.SI_solve(Q, c, Aeq, beq, Aineq, bineq, XL, XU));\n    ASSERT_TRUE(qpLSSOL.SI_solve(Q, c, Aeq, beq, Aineq, bineq, XL, XU));\n\n    Eigen::VectorXd resQuadProg = qpQuadProg.SI_result();\n    Eigen::VectorXd resLSSOL = qpLSSOL.SI_result();\n    EXPECT_TRUE(resLSSOL.isApprox(resQuadProg));\n    ASSERT_EQ(qpLSSOL.SI_fail(), 0);\n}\n#endif\n\n#ifdef EIGEN_GUROBI_FOUND\nTEST_F(Problem, GUROBIOnQuadProgTest) {  // NOLINT\n    copra::QuadProgDenseSolver qpQuadProg;\n    copra::GUROBISolver qpGUROBI;\n\n    qpQuadProg.SI_problem(nrvars, nreqs, nrineqs);\n    qpGUROBI.SI_problem(nrvars, nreqs, nrineqs);\n    ASSERT_TRUE(qpQuadProg.SI_solve(Q, c, Aeq, beq, Aineq, bineq, XL, XU));\n    ASSERT_TRUE(qpGUROBI.SI_solve(Q, c, Aeq, beq, Aineq, bineq, XL, XU));\n\n    Eigen::VectorXd resQuadProg = qpQuadProg.SI_result();\n    Eigen::VectorXd resGUROBI = qpGUROBI.SI_result();\n    EXPECT_TRUE(resGUROBI.isApprox(resQuadProg, 1e-6));\n    ASSERT_EQ(qpGUROBI.SI_fail(), GRB_OPTIMAL);\n}\n#endif\n\n#ifdef EIGEN_OSQP_FOUND\nTEST_F(Problem, OSQPOnQuadProgTest) {  // NOLINT\n    copra::QuadProgDenseSolver qpQuadProg;\n    copra::OSQPSolver osqp;\n\n    qpQuadProg.SI_problem(nrvars, nreqs, nrineqs);\n    osqp.SI_problem(nrvars, nreqs, nrineqs);\n    ASSERT_TRUE(qpQuadProg.SI_solve(Q, c, Aeq, beq, Aineq, bineq, XL, XU));\n    ASSERT_TRUE(osqp.SI_solve(Q, c, Aeq, beq, Aineq, bineq, XL, XU));\n\n    Eigen::VectorXd resQuadProg = qpQuadProg.SI_result();\n    Eigen::VectorXd resOSQP = osqp.SI_result();\n    EXPECT_TRUE(resOSQP.isApprox(resQuadProg, 1e-6));\n    ASSERT_EQ(osqp.SI_fail(), 1);\n}\n#endif\n", "meta": {"hexsha": "59ebb9473875f341957d63c77b19bc88e19220a8", "size": 3187, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/TestSolvers.cpp", "max_stars_repo_name": "ANYbotics/copra", "max_stars_repo_head_hexsha": "d06095fb4c6f9d7103dae2b44a32759c7cfc4ee1", "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": "test/TestSolvers.cpp", "max_issues_repo_name": "ANYbotics/copra", "max_issues_repo_head_hexsha": "d06095fb4c6f9d7103dae2b44a32759c7cfc4ee1", "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": "test/TestSolvers.cpp", "max_forks_repo_name": "ANYbotics/copra", "max_forks_repo_head_hexsha": "d06095fb4c6f9d7103dae2b44a32759c7cfc4ee1", "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.5544554455, "max_line_length": 76, "alphanum_fraction": 0.7147787888, "num_tokens": 1149, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4562764603604894}}
{"text": "// Copyright PinaPL\n//\n// weights.hpp\n// PinaPL\n//\n\n#ifndef WEIGHTS_HPP\n#define WEIGHTS_HPP\n\n#include <Eigen/Dense>\n\nclass Weights {\n public:\n    int input_size;\n    int output_size;\n    Weights(int input_size, int output_size);\n    ~Weights();\n    void apply_gradient(double lambda);\n\n    //   Information :\n    // weight_in means the weight matrix applied to the new input\n    // weight_st means the weight matrix applied to the previous cell OUT\n\n    Eigen::MatrixXd weight_in_forget_gate;                  // Wf\n    Eigen::MatrixXd weight_in_input_gate;                   // Wi\n    Eigen::MatrixXd weight_in_input_block;                  // Wz\n    Eigen::MatrixXd weight_in_output_gate;                  // Wo\n\n    Eigen::MatrixXd weight_st_forget_gate;                  // Rf\n    Eigen::MatrixXd weight_st_input_gate;                   // Ri\n    Eigen::MatrixXd weight_st_input_block;                  // Rz\n    Eigen::MatrixXd weight_st_output_gate;                  // Ro\n\n    Eigen::MatrixXd bias_forget_gate;                       // Bf\n    Eigen::MatrixXd bias_input_gate;                        // Bi\n    Eigen::MatrixXd bias_input_block;                       // Bz\n    Eigen::MatrixXd bias_output_gate;                       // Bo\n\n    //   Information :\n    // weight_in means the weight matrix applied to the new INPUT\n    // weight_st means the weight matrix applied to the previous cell OUT\n\n    Eigen::MatrixXd delta_weight_in_forget_gate;           // dWf\n    Eigen::MatrixXd delta_weight_in_input_gate;            // dWi\n    Eigen::MatrixXd delta_weight_in_input_block;           // dWz\n    Eigen::MatrixXd delta_weight_in_output_gate;           // dWo\n\n    Eigen::MatrixXd delta_weight_st_forget_gate;           // dRf\n    Eigen::MatrixXd delta_weight_st_input_gate;            // dRi\n    Eigen::MatrixXd delta_weight_st_input_block;           // dRz\n    Eigen::MatrixXd delta_weight_st_output_gate;           // dRo\n\n    Eigen::MatrixXd delta_bias_forget_gate;                // Bf\n    Eigen::MatrixXd delta_bias_input_gate;                 // Bi\n    Eigen::MatrixXd delta_bias_input_block;                // Bz\n    Eigen::MatrixXd delta_bias_output_gate;                // Bo\n};\n#endif\n", "meta": {"hexsha": "a271a222fd9767a405094e44b7326ed1654f6a14", "size": 2209, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "weights.hpp", "max_stars_repo_name": "supelec-lstm/PinaPL_lstm", "max_stars_repo_head_hexsha": "96462ed2f8f880ccfc33424eb6a273522b90b049", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "weights.hpp", "max_issues_repo_name": "supelec-lstm/PinaPL_lstm", "max_issues_repo_head_hexsha": "96462ed2f8f880ccfc33424eb6a273522b90b049", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "weights.hpp", "max_forks_repo_name": "supelec-lstm/PinaPL_lstm", "max_forks_repo_head_hexsha": "96462ed2f8f880ccfc33424eb6a273522b90b049", "max_forks_repo_licenses": ["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.4406779661, "max_line_length": 73, "alphanum_fraction": 0.6034404708, "num_tokens": 485, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.45627645494006985}}
{"text": "#include \"ekf.h\"\n\n#include <ros/ros.h>\n#include <ros/console.h>\n#include <sensor_msgs/Imu.h>\n#include <Eigen/Eigen>\n#include <random>\n\nusing namespace std;\nusing namespace Eigen;\n\nros::Publisher imu_noise_pub;\n//add imu noise\ndouble imu_noise = 0.05;    \nVector3d noise;\nstd::default_random_engine generator;\nstd::normal_distribution<double> distribution_imu(0, imu_noise);\n    \nvoid imu_callback(const sensor_msgs::Imu::ConstPtr &msg)\n{\n    // add imu noise\n    noise = Vector3d(distribution_imu(generator), distribution_imu(generator), distribution_imu(generator)); \n\n    sensor_msgs::Imu imu_noise;\n    imu_noise = *msg;\n\n    imu_noise.linear_acceleration.x += noise(0);\n    imu_noise.linear_acceleration.y += noise(1);\n    imu_noise.linear_acceleration.z += noise(2);\n\n    imu_noise_pub.publish(imu_noise);\n}\n\nint main(int argc, char **argv)\n{\n    ros::init(argc, argv, \"ekf\");\n    ros::NodeHandle n(\"~\");\n    ros::Subscriber s1 = n.subscribe(\"imu\", 1000, imu_callback, ros::TransportHints().tcpNoDelay());\n    imu_noise_pub = n.advertise<sensor_msgs::Imu>(\"/djiros/imu_noise\", 1000);\n\n    n.getParam(\"imu_noise\", imu_noise);\n\n    cout << \"imu_noise: \" << imu_noise << endl;\n\n    ros::spin();\n}\n", "meta": {"hexsha": "71e051a4684236f375d0a8ee3cf3824a9b1f6534", "size": 1199, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Modules/mocap_ekf/src/imu_add_noise.cpp", "max_stars_repo_name": "473867143/Prometheus", "max_stars_repo_head_hexsha": "df1e1b0d861490223ac8b94d8cc4796537172292", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1217.0, "max_stars_repo_stars_event_min_datetime": "2020-07-02T13:15:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T06:17:44.000Z", "max_issues_repo_path": "Modules/mocap_ekf/src/imu_add_noise.cpp", "max_issues_repo_name": "473867143/Prometheus", "max_issues_repo_head_hexsha": "df1e1b0d861490223ac8b94d8cc4796537172292", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 167.0, "max_issues_repo_issues_event_min_datetime": "2020-07-12T15:35:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T11:57:40.000Z", "max_forks_repo_path": "Modules/mocap_ekf/src/imu_add_noise.cpp", "max_forks_repo_name": "473867143/Prometheus", "max_forks_repo_head_hexsha": "df1e1b0d861490223ac8b94d8cc4796537172292", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 270.0, "max_forks_repo_forks_event_min_datetime": "2020-07-02T13:28:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T05:43:08.000Z", "avg_line_length": 25.5106382979, "max_line_length": 109, "alphanum_fraction": 0.7005838198, "num_tokens": 317, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919830720203, "lm_q2_score": 0.5698526514141572, "lm_q1q2_score": 0.45627644951965024}}
{"text": "/* -*-C++-*-\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    Simple statistics functions for single variables\n*/\n\n#include <stdlib.h>\n#include <cstdio>\n#include <string>\n#include <float.h>\n#include <string.h>\n\n#include <boost/format.hpp>\n\n#include <Lintel/AssertBoost.hpp>\n#include <Lintel/Stats.hpp>\n#include <Lintel/Double.hpp>\n\n///////////////////////////////////////////////////////////////////////////\n// Functions specific to the Statistics base class\n///////////////////////////////////////////////////////////////////////////\n\nStatsBase::StatsBase() : reset_count(0), is_assigned(true) {\n    reset();\t\t\t\n    reset_count = 0; // this is really is the first time\n};\n\n\nStatsBase::~StatsBase() {\n    DEBUG_SINVARIANT(checkInvariants());\n    is_assigned = false;\n};\n\nbool StatsBase::checkInvariants() const { \n    return is_assigned; \n}\n\nvoid StatsBase::reset() {\n    DEBUG_SINVARIANT(checkInvariants());\n    reset_count++;\n}\n\ndouble StatsBase::stddev() const {\n    DEBUG_SINVARIANT(checkInvariants());\n    double sigsq = variance();\n\n    if (sigsq <= 0.0) {\n\treturn 0.0;\n    }\n\n    DEBUG_SINVARIANT(sigsq > 0.0);\n    return sqrt(sigsq);\n}\n\ndouble StatsBase::relconf95() const {\n    DEBUG_SINVARIANT(checkInvariants());\n    return conf95()/mean();\n}\n\n\n///////////////////////////////////////////////////////////////////////////\n// Functions related to the Stats singe-variable statistic class\n///////////////////////////////////////////////////////////////////////////\n\n// Create a new one\n//\nStats::Stats() : StatsBase() {\n  reset();\n};\n\n\nStats::~Stats()\t{};\n\nvoid Stats::reset() {\n    DEBUG_SINVARIANT(checkInvariants());\n    StatsBase::reset();\n    number = 0;\n    sum = 0.0;\n    sumsq = 0.0;\n    min_value = Double::Inf;\n    max_value = -Double::Inf;\n}\n\nvoid Stats::add(const double value) {\n    DEBUG_INVARIANT(value == value, \"You tried to add a NaN to the stats object.\"); \n\t\t    \n    ++number;\n    sum += value;\n    sumsq += value*value;\n\n    if (value < min_value) {\n\tmin_value = value;\n    }\n    if (value > max_value) {\n\tmax_value = value;\n    }\n}\n\nvoid Stats::add(const Stats &stat) {\n    number += stat.number;\n    sum += stat.sum;\n    sumsq += stat.sumsq;\n\n    if (stat.min_value < min_value) {\n\tmin_value = stat.min_value;\n    }\n    if (stat.max_value > max_value) {\n\tmax_value = stat.max_value;\n    }\n}\n\nvoid Stats::addTimeSeq(const double value, const double) {\n    this->add(value);\n}\n\n// Accessor functions\n\ndouble Stats::mean() const {\n    DEBUG_SINVARIANT(checkInvariants());\n    if (number == 0) {\n\treturn 0.0;\n    } else {\n\treturn double(sum)/double(number);\n    }\n};\n\n\ndouble Stats::variance() const {\n    DEBUG_SINVARIANT(checkInvariants());\n    if (number == 0) return 0.0;\n    double m = mean();\n    return double(sumsq)/double(number) - m*m;\n}\n\n\n// TODO-future: Add in an optional invariant that checks statistical validity,\n// i.e., that number>30. Consider also adding a generic conf function that\n// takes a z-constant as input so that we can easily add more/different conf\n// intervals. Could also add an interface that checks if a specific value is\n// within some specified confidence interval.\n// Potential z constants of interest:\n// conf90 z= 1.645\n// conf95 z= 1.960\n// conf99 z= 2.576\ndouble Stats::conf95() const {\n    DEBUG_SINVARIANT(checkInvariants());\n    if (number == 0) return DBL_MAX; // **** Should really be NaN if count==0\n    DEBUG_SINVARIANT(number > 0); // **** Could be number > 30 for statistical\n                                  // **** validity.\n    return 1.96*stddev()/sqrt((double)number);\n}\n\n\n\n// Summarize contents as a string\n\nstd::string Stats::debugString() const {\n    DEBUG_SINVARIANT(checkInvariants());\n\n    if (count() == 0) {\n\treturn \"count 0\";\n    } else {\n\treturn str(boost::format(\"count %d mean %G stddev %G var %G 95%%conf %G rel95%%conf %G\"\n\t\t\t\t \" min %G max %G\") % count() % mean() % stddev() % variance()\n\t\t   % conf95() % relconf95() % min() % max());\n    }\n};\n\n\nvoid Stats::printRome(int depth, std::ostream &out) const {\n    DEBUG_SINVARIANT(checkInvariants());\n\n    std::string spaces;\n    for(int i = 0; i < depth; i++) {\n\tspaces += \" \";\n    }\n\n    out << spaces << \"{ count \" << countll() << \" }\\n\";\n    if (count() > 0) {\n\tout << spaces << \"{ min \" << min() << \" }\\n\";\n\tout << spaces << \"{ max \" << max() << \" }\\n\";\n\tout << spaces << \"{ mean \" << mean() << \" }\\n\";\n\tout << spaces << \"{ stddev \" << stddev() << \" }\\n\";\n\tout << spaces << \"{ variance \" << variance() << \" }\\n\";\n\tout << spaces << \"{ conf95 \" << conf95() << \" }\\n\";\n\tout << spaces << \"{ total \" << total() << \" }\\n\";\n\tout << spaces << \"{ total_sq \" << total_sq() << \" }\\n\";\n    }\n}\n\nvoid Stats::printTabular(int depth, std::ostream &out) const {\n  DEBUG_SINVARIANT(checkInvariants());\n\n  std::string spaces;\n  for(int i = 0; i < depth; i++) {\n    spaces += \" \";\n  }\n\n  out << spaces << \"count \" << countll() << \"\\n\";\n  if (count() > 0) {\n    out << spaces << \"min \" << min() << \"\\n\";\n    out << spaces << \"max \" << max() << \"\\n\";\n    out << spaces << \"mean \" << mean() << \"\\n\";\n    out << spaces << \"stddev \" << stddev() << \"\\n\";\n    out << spaces << \"variance \" << variance() << \"\\n\";\n    out << spaces << \"conf95 \" << conf95() << \"\\n\";\n    out << spaces << \"total \" << total() << \"\\n\";\n    out << spaces << \"total_sq \" << total_sq() << \"\\n\";\n  }\n  // This is kind of a hack, but I had problems when the printout of \n  // Stats changed for an empty list.\n  else\n    {\n      out << spaces << \"min \" << min() << \"\\n\";\n      out << spaces << \"max \" << max() << \"\\n\";\n      out << spaces << \"mean \" << 0 << \"\\n\";\n      out << spaces << \"stddev \" << 0 << \"\\n\";\n      out << spaces << \"variance \" << 0 << \"\\n\";\n      out << spaces << \"conf95 \" << 0 << \"\\n\";\n      out << spaces << \"total \" << total() << \"\\n\";\n      out << spaces << \"total_sq \" << total_sq() << \"\\n\";\n    }\n}\n  \nvoid Stats::printText(std::ostream &out) const {\n    out << boost::format(\"count=%d, mean=%.8g, stddev=%.8g, min=%.8g, max=%.8g\\n\")\n\t% countll() % mean() % stddev() % min() % max();\n}\n\n\nStats *Stats::another_new() const {\n    return new Stats();\n}\n\n\n", "meta": {"hexsha": "2af820448b1d515fa0d6876dbf0a55d8dfd4c3f1", "size": 6165, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Stats.cpp", "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": "src/Stats.cpp", "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": "src/Stats.cpp", "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": 25.6875, "max_line_length": 88, "alphanum_fraction": 0.5480940795, "num_tokens": 1665, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.689305616785446, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.4562671653964007}}
{"text": "// The MIT License \n// (c) 2019 Daniel Williams\n\n#ifndef _GRID_LAYOUT_HPP_\n#define _GRID_LAYOUT_HPP_\n\n#include <limits>\n#include <memory>\n#include <string>\n\n#include <Eigen/Geometry>\n\n#include <nlohmann/json/json_fwd.hpp>\n\nusing Eigen::Vector2d;\n\nnamespace terrain::geometry {\n\ntypedef uint64_t index_t;\n\n///! \\brief Layout is used to encapsulate common logic about how to layout a square grid\nclass Layout {\npublic:\n\n    constexpr Layout();\n    // constexpr Layout()\n    //     : precision(1), x(0), y(0), width(1) {}\n\n    constexpr Layout(const double _precision, const double _x, const double _y, const double _width);\n\n    bool contains(const Eigen::Vector2d& at) const;\n\n    bool operator!=(const Layout& other) const;\n    bool operator==(const Layout& other) const;\n\n    // definitely _not_ constexpr ;)\n    Layout(nlohmann::json& doc);\n\n    void clear();\n    \n    const Vector2d get_anchor() const;\n    inline Vector2d get_center() const { return {x,y}; }\n    inline size_t get_dimension() const { return dimension; }\n    inline double get_half_width() const { return half_width; }\n    inline uint8_t get_padding() const { return padding; }\n    inline double get_precision() const { return precision; }\n    inline size_t get_size() const { return size; }\n    double get_x() const { return x; }\n    double get_x_max() const;\n    double get_x_min() const;\n    double get_y() const { return y; }\n    double get_y_max() const;\n    double get_y_min() const;\n    inline size_t get_width() const { return width; }\n\n    ///! \\brief hashes x,y ... into a simple row-major indexing\n    constexpr index_t rhash( const Eigen::Vector2d& p) const { return rhash( p[0], p[1]); }\n    constexpr index_t rhash( const double x, const double y) const;\n    constexpr index_t rhash( const uint32_t i, const uint32_t j) const;\n\n    ///! \\brief hashes x,y ... by a Z-Order Curve\n    ///! [1] http://en.wikipedia.org/wiki/Z-Order_curve\n    constexpr index_t zhash( const Eigen::Vector2d& p) const { return zhash( p[0], p[1]); }\n    constexpr index_t zhash( const double x, const double y) const;\n    constexpr index_t zhash( const uint32_t i, const uint32_t j) const;\n\n    ///! \\brief factory method for creating from a json document\n    static std::unique_ptr<Layout> make_from_json(nlohmann::json& doc);\n\n    double constrain_x( const double x) const;\n    double constrain_y( const double y) const;\n\n    nlohmann::json to_json() const;\n\n    std::string to_string() const;\n\n// constants\npublic:\n    // used for comparisons\n    constexpr static double epsilon = 1e-6;\n    constexpr static size_t index_bit_size = 64;\n    constexpr static size_t maximum_supported_dimension = std::numeric_limits<uint32_t>::max();\n    constexpr static double minimum_supported_precision = 1.;\n\nprivate:\n    constexpr uint64_t interleave( const uint32_t input) const;\n\n    ///! \\brief snaps this precision to match the next-power-of-2 dimension that covers the precision\n    ///!\n    ///! Note:  Precision <= 1.0\n    constexpr double snap_precision(const double precision);\n    constexpr double snap_width( const double _width);\n\n    constexpr uint8_t calculate_padding( const double dimension);\n\nprivate:  // primary variables\n    double precision;\n\n    double width;\n\n    // Center Coordinates:\n    // =====\n    // these are stored as the raw doubles, (instead of Eigen::Vector2d) because ...\n    //    (1) the layout can compress the layout,\n    //    (2) allow the use of constexpr constructors\n    double x;\n    double y;\n\nprivate: // secondary / cached variables\n    size_t dimension;\n    double half_width;\n    uint8_t padding;  // left-pad the z-index with this many zeros.  Ranges from 0-64... which fits into a byte.\n    size_t size;\n};\n\n#include \"layout.inl\"\n\n} // namespace terrain::geometry\n\n#endif // #ifdef _GRID_LAYOUT_HPP_\n", "meta": {"hexsha": "431d2e4a82f09410e8784e40b43f42932c92583e", "size": 3803, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/geometry/layout.hpp", "max_stars_repo_name": "teyrana/quadtree", "max_stars_repo_head_hexsha": "4172ad2f2e36414caebf80013a3d32e6df200945", "max_stars_repo_licenses": ["MIT"], "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/geometry/layout.hpp", "max_issues_repo_name": "teyrana/quadtree", "max_issues_repo_head_hexsha": "4172ad2f2e36414caebf80013a3d32e6df200945", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-08-24T17:31:50.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-24T17:31:50.000Z", "max_forks_repo_path": "include/geometry/layout.hpp", "max_forks_repo_name": "teyrana/quadtree", "max_forks_repo_head_hexsha": "4172ad2f2e36414caebf80013a3d32e6df200945", "max_forks_repo_licenses": ["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.4297520661, "max_line_length": 112, "alphanum_fraction": 0.6907704444, "num_tokens": 946, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056040203135, "lm_q2_score": 0.6619228625116081, "lm_q1q2_score": 0.456267138558419}}
{"text": "/**\n * \\file dcs/testbed/lq_application_manager.hpp\n *\n * \\brief Linear-Quadratic (LQ) system manager.\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n *\n * <hr/>\n *\n * Copyright 2012 Marco Guazzone (marco.guazzone@gmail.com)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#ifndef DCS_TESTBED_LQ_SYSTEM_MANAGER_HPP\n#define DCS_TESTBED_LQ_SYSTEM_MANAGER_HPP\n\n\n#include <algorithm>\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/mean.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_expression.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/vector_expression.hpp>\n#include <boost/numeric/ublas/vector_proxy.hpp>\n#include <boost/numeric/ublas/traits.hpp>\n#include <boost/numeric/ublasx/operation/all.hpp>\n#include <boost/numeric/ublasx/operation/any.hpp>\n#include <boost/numeric/ublasx/operation/inv.hpp>\n#include <boost/numeric/ublasx/operation/isfinite.hpp>\n#include <boost/numeric/ublasx/operation/num_columns.hpp>\n#include <boost/numeric/ublasx/operation/num_rows.hpp>\n#include <boost/smart_ptr.hpp>\n#include <cmath>\n#include <cstddef>\n#include <dcs/assert.hpp>\n#include <dcs/control/analysis/controllability.hpp>\n#include <dcs/control/analysis/detectability.hpp>\n#include <dcs/control/analysis/observability.hpp>\n#include <dcs/control/analysis/stabilizability.hpp>\n#include <dcs/control/design/dlqry.hpp>\n#include <dcs/debug.hpp>\n#include <dcs/exception.hpp>\n#include <dcs/logging.hpp>\n#include <dcs/macro.hpp>\n#include <dcs/math/traits/float.hpp>\n#include <dcs/testbed/application_performance_category.hpp>\n#include <dcs/testbed/base_application_manager.hpp>\n#include <dcs/testbed/system_identification_strategies.hpp>\n#ifdef DCS_TESTBED_EXP_LQ_APP_MGR_USE_ARX_B0_SIGN_HEURISTIC\n# include <functional>\n#endif // DCS_TESTBED_EXP_LQ_APP_MGR_USE_ARX_B0_SIGN_HEURISTIC\n#include <limits>\n#include <map>\n#include <stdexcept>\n\n\nnamespace dcs { namespace testbed {\n\nnamespace detail { namespace /*<unnamed>*/ {\n\n/**\n * \\brief Convert a discrete model from ARX structure to a state-space model in\n *  the canonical controllable form.\n *\n * Given the following input-output system:\n * \\f[\n *  y(k)+\\sum_{i=1}^{n_a}y(k-i)=\\sum_{i=1}^{n_b}u(k-d-i)\n * \\f]\n * create the following state-space system:\n * \\f{align}{\n *  x(k+1) &= Ax(k)+Bu(k),\\\\\n *  y(k)   &= Cx(k)+Du(k)\n * \\f}\n * such that:\n * \\f{align}{\n *  x(k) &=\\begin{pmatrix}\n *          u(k-d-n_b) \\\\\n *          .          \\\\\n *          .          \\\\\n *          .          \\\\\n *          u(k-d-2)   \\\\\n *          y(k-n_a)   \\\\\n *          .          \\\\\n *          .          \\\\\n *          .          \\\\\n *          y(k-1)\n *      \\end{pmatrix},\\\\\n *  u(k) &=\\begin{pmatrix}\n *          u(k-d)\n *      \\end{pmatrix},\\\\\n *  A &=\\begin{pmatrix}\n         0        & I         & 0         & \\ldots & 0  \\\\\n         0        & 0         & I         & \\ldots & 0  \\\\\n         .        & .         & 0         & \\ldots & .  \\\\\n         .        & .         & .         & \\ldots & .  \\\\\n         .        & .         & .         & \\ldots & .  \\\\\n         0        & 0         & 0         & \\ldots & I  \\\\\n         -A_{n_a} &-A_{n_a-1} &-A_{n_a-2} & \\ldots &-A_1\n *      \\end{pmatrix},\\\\\n *  B &=\\begin{pmatrix}\n *       0  \\\\\n *       .\t\\\\\n *       .\t\\\\\n *       .\t\\\\\n *       0  \\\\\n *       I\n *      \\end{pmatrix},\\\\\n *  C &=\\begin{pmatrix}\n\t     B_n-B_0*A_n & \\ldots & B_0-B_0*A_0\n *      \\end{pmatrix},\\\\\n *  D &=\\begin{pmatrix}\n *       B_0\n *      \\end{pmatrix}\n * \\f}\n * NOTE: in our case \\f$B_0=0\\f$, so\n * \\f{align}\n *  D &=\\begin{pmatrix}\n *       B_n & \\ldots & B_1 & 0\n *      \\end{pmatrix},\\\\\n *  D &=\\begin{pmatrix}\n *       0\n *      \\end{pmatrix}\n * \\f}.\n */\ntemplate <\n\ttypename SysIdentStrategyT,\n\ttypename AMatrixExprT,\n\ttypename BMatrixExprT,\n\ttypename CMatrixExprT,\n\ttypename DMatrixExprT\n>\nvoid make_controllable_ss(SysIdentStrategyT const& sys_ident_strategy,\n\t\t\t\t\t\t  ::boost::numeric::ublas::matrix_container<AMatrixExprT>& A,\n\t\t\t\t\t\t  ::boost::numeric::ublas::matrix_container<BMatrixExprT>& B,\n\t\t\t\t\t\t  ::boost::numeric::ublas::matrix_container<CMatrixExprT>& C,\n\t\t\t\t\t\t  ::boost::numeric::ublas::matrix_container<DMatrixExprT>& D)\n{\n//DCS_DEBUG_TRACE(\"BEGIN make_ss\");//XXX\n\tnamespace ublas = ::boost::numeric::ublas;\n\n\ttypedef typename ublas::promote_traits<\n\t\t\t\ttypename ublas::promote_traits<\n\t\t\t\t\ttypename ublas::promote_traits<\n\t\t\t\t\t\ttypename ublas::matrix_traits<AMatrixExprT>::value_type,\n\t\t\t\t\t\ttypename ublas::matrix_traits<BMatrixExprT>::value_type\n\t\t\t\t\t>::promote_type,\n\t\t\t\t\ttypename ublas::matrix_traits<CMatrixExprT>::value_type\n\t\t\t\t>::promote_type,\n\t\t\t\ttypename ublas::matrix_traits<DMatrixExprT>::value_type\n\t\t\t>::promote_type value_type;\n\ttypedef ::std::size_t size_type; //FIXME: use type-promotion?\n\n\tconst size_type rls_n_a(sys_ident_strategy.output_order());\n\tconst size_type rls_n_b(sys_ident_strategy.input_order());\n//\tconst size_type rls_d(sys_ident_strategy.input_delay());\n\tconst size_type rls_n_y(sys_ident_strategy.num_outputs());\n\tconst size_type rls_n_u(sys_ident_strategy.num_inputs());\n\tconst size_type n_x(rls_n_a*rls_n_y);\n\tconst size_type n_u(rls_n_b*rls_n_u);\n//\tconst size_type n(::std::max(n_x,n_u));\n\tconst size_type n_y(1);\n\n\tDCS_ASSERT(\n\t\t\trls_n_y <= 1 && rls_n_u <= 1,\n\t\t\tDCS_EXCEPTION_THROW(\n\t\t\t\t::std::runtime_error,\n\t\t\t\t\"Actually, only SISO cases are hanlded\"\n\t\t\t)\n\t\t);\n\tDCS_ASSERT(\n\t\t\trls_n_y == rls_n_u,\n\t\t\tDCS_EXCEPTION_THROW(\n\t\t\t\t::std::runtime_error,\n\t\t\t\t\"Actually, only the same number of channel are treated\"\n\t\t\t)\n\t\t);\n\n\t// Create the state matrix A\n\t// A=[ 0        I          0         ...  0  ;\n\t//     0        0          I         ...  0  ;\n\t//     .        .          .         ...  .\n\t//     .        .          .         ...  .\n\t//     .        .          .         ...  .\n\t// \t   0        0          0         ...  I  ;\n\t// \t  -A_{n_a} -A_{n_a-1} -A_{n_a-2} ... -A_1]\n\tif (n_x > 0)\n\t{\n\t\tsize_type broffs(n_x-rls_n_y); // The bottom row offset\n\n\t\tA().resize(n_x, n_x, false);\n\n\t\t// The upper part of A is set to [0_{k,rls_n_y} I_{k,k}],\n\t\t// where: k=n_x-rls_n_y.\n\t\tublas::subrange(A(), 0, broffs, 0, rls_n_y) = ublas::zero_matrix<value_type>(broffs,rls_n_y);\n\t\tublas::subrange(A(), 0, broffs, rls_n_y, n_x) = ublas::identity_matrix<value_type>(broffs,broffs);\n\n\t\tif (rls_n_a > 0)\n\t\t{\n\t\t\t// Fill A with A_1, ..., A_{n_a}\n\t\t\tfor (size_type i = 0; i < rls_n_a; ++i)\n\t\t\t{\n\t\t\t\t// Copy matrix -A_i from \\hat{\\Theta} into A.\n\t\t\t\t// In A the matrix A_i has to go in (rls_n_a-i)-th position:\n\t\t\t\t//   A(k:(k+n),((rls_n_a-i-1)*rls_n_y):((rls_n_a-i)*rls_n_y)) <- -A_i\n\n\t\t\t\tsize_type c2((rls_n_a-i)*rls_n_y);\n\t\t\t\tsize_type c1(c2-rls_n_y);\n\n\t\t\t\t////ublas::subrange(A(), broffs, n_x, c1, c2) = sys_ident_strategy.A(i+1);\n\t\t\t\tublas::subrange(A(), broffs, n_x, c1, c2) = -sys_ident_strategy.A(i+1);\n\t\t\t\t//ublas::subrange(A(), broffs, n_x, c1, c2) = sys_ident_strategy.A(i+1);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tublas::subrange(A(), broffs, n_x, 0, n_x) = ublas::zero_matrix<value_type>(rls_n_y,n_x);\n\t\t}\n\t}\n\telse\n\t{\n\t\tA().resize(0, 0, false);\n\t}\n//DCS_DEBUG_TRACE(\"A=\"<<A);//XXX\n\n\t// Create the input matrix B\n\t// B=[0;\n\t//    .;\n\t//    .;\n\t//    .;\n\t//    0;\n\t//    I]\n\tif (n_x > 0 && rls_n_b > 0)\n\t{\n\t\tsize_type broffs(n_x-rls_n_u); // The bottom row offset\n\n\t\tB().resize(n_x, n_u, false);\n\n\t\t// The upper part of B is set to 0_{k,n_u}\n\t\t// where: k=n_x-rls_n_u.\n\t\tublas::subrange(B(), 0, broffs, 0, n_u) = ublas::zero_matrix<value_type>(broffs, n_u);\n\t\t// The lower part of B is set to I_{n_u,n_u}\n\t\tublas::subrange(B(), broffs, n_x, 0, n_u) = ublas::identity_matrix<value_type>(n_u, n_u);\n\t}\n\telse\n\t{\n\t\tB().resize(0, 0, false);\n\t}\n//DCS_DEBUG_TRACE(\"B=\"<<B);//XXX\n\n\t// Create the output matrix C\n\t// C=[M_n ... M_0]\n\t// where M_i=B_i-B_0*A_i\n\t// NOTE: in our case B_0=0, so M_i=B_i\n\tif (n_x > 0)\n\t{\n\t\tC().resize(n_y, n_x, false);\n\n\t\tfor (size_type i = 0; i < rls_n_b; ++i)\n\t\t{\n\t\t\tsize_type c2((rls_n_b-i)*rls_n_u);\n\t\t\tsize_type c1(c2-rls_n_u);\n\n\t\t\tublas::subrange(C(), 0, n_y, c1, c2) = sys_ident_strategy.B(i+1);\n\t\t}\n\t}\n\telse\n\t{\n\t\tC().resize(0, 0, false);\n\t}\n//DCS_DEBUG_TRACE(\"C=\"<<C);//XXX\n\n\t// Create the transmission matrix D\n\t// D=[B0]\n\t// NOTE: in our case B_0=0, so D=[0]\n\t{\n\t\tD().resize(n_y, n_u, false);\n\n\t\tD() = ublas::zero_matrix<value_type>(n_y, n_u);\n\t}\n//DCS_DEBUG_TRACE(\"D=\"<<D);//XXX\n\n//DCS_DEBUG_TRACE(\"END make_ss\");//XXX\n}\n\n/// Convert an ARX structure to a state-space model in the canonical observable form.\ntemplate <\n    typename SysIdentStrategyT,\n    typename AMatrixExprT,\n    typename BMatrixExprT,\n    typename CMatrixExprT,\n    typename DMatrixExprT\n>\ninline\nvoid make_observable_ss(SysIdentStrategyT const& sys_ident_strategy,\n\t\t\t\t\t\t::boost::numeric::ublas::matrix_container<AMatrixExprT>& A,\n\t\t\t\t\t\t::boost::numeric::ublas::matrix_container<BMatrixExprT>& B,\n\t\t\t\t\t\t::boost::numeric::ublas::matrix_container<CMatrixExprT>& C,\n\t\t\t\t\t\t::boost::numeric::ublas::matrix_container<DMatrixExprT>& D)\n{\n\tmake_controllable_ss(sys_ident_strategy, A, B, C, D);\n\tA() = ::boost::numeric::ublas::trans(A);\n\tB() = ::boost::numeric::ublas::trans(C);\n\tC() = ::boost::numeric::ublas::trans(B);\n}\n\n\n#if defined(DCS_TESTBED_EXP_LQ_APP_MGR_USE_ALT_SS) && DCS_TESTBED_EXP_LQ_APP_MGR_USE_ALT_SS == 'X'\n\n/**\n * \\brief Convert a discrete model from ARX structure to a state-space model.\n *\n * Given the following input-output system:\n * \\f[\n *  y(k)+\\sum_{i=1}^{n_a}y(k-i)=\\sum_{i=1}^{n_b}u(k-d-i)\n * \\f]\n * create the following state-space system:\n * \\f{align}{\n *  x(k+1) &= Ax(k)+Bu(k),\\\\\n *  y(k)   &= Cx(k)+Du(k)\n * \\f}\n * such that:\n * \\f{align}{\n *  x(k) &=\\begin{pmatrix}\n *          u(k-d-n_b) \\\\\n *          .          \\\\\n *          .          \\\\\n *          .          \\\\\n *          u(k-d-2)   \\\\\n *          y(k-n_a)   \\\\\n *          .          \\\\\n *          .          \\\\\n *          .          \\\\\n *          y(k-1)\n *      \\end{pmatrix},\\\\\n *  u(k) &=\\begin{pmatrix}\n *          u(k-d)\n *      \\end{pmatrix},\\\\\n *  A &=\\begin{pmatrix}\n *       0       & I         & 0         & \\ldots & 0   & 0       & I         & 0         & \\ldots & 0  \\\\\n *       0       & 0         & I         & \\ldots & 0   & 0       & 0         & I         & \\ldots & 0  \\\\\n *       .       & .         & .         & \\ldots & .   & .       & .         & 0         & \\ldots & .  \\\\\n *       .       & .         & .         & \\ldots & .   & .       & .         & 0         & \\ldots & .  \\\\\n *       .       & .         & .         & \\ldots & .   & .       & .         & 0         & \\ldots & .  \\\\\n *       0       & 0         & 0         & \\ldots & I   & 0       & 0         & 0         & \\ldots & I  \\\\\n *       B_{n_b} & B_{n_b-1} & B_{n_b-2} & \\ldost & B_2 &-A_{n_a} &-A_{n_a-1} &-A_{n_a-2} & \\ldots &-A_1\n *      \\end{pmatrix},\\\\\n *  B &=\\begin{pmatrix}\n *       I  \\\\\n *       0  \\\\\n *       .\t\\\\\n *       .\t\\\\\n *       .\t\\\\\n *       0  \\\\\n *       B_1\n *      \\end{pmatrix},\\\\\n *  C &=\\begin{pmatrix}\n *       0 & \\ldots & 0 & 1 & \\ldots & 1 \\\\\n *       0 & \\ldots & 0 & 1 & \\ldots & 1 \\\\\n *       . & \\ldots & . & . & \\ldots & . \\\\\n *       . & \\ldots & . & . & \\ldots & . \\\\\n *       . & \\ldots & . & . & \\ldots & . \\\\\n *       0 & \\ldots & 0 & 1 & \\ldots & 1\n *      \\end{pmatrix},\\\\\n *  D &=\\begin{pmatrix}\n *       0 & \\ldots & 0 \\\\\n *       0 & \\ldots & 0 \\\\\n *       . & \\ldots & . \\\\\n *       . & \\ldots & . \\\\\n *       . & \\ldots & . \\\\\n *       0 & \\ldots & 0\n *      \\end{pmatrix}\n * \\f}\n */\ntemplate <\n\ttypename SysIdentStrategyT,\n\ttypename AMatrixExprT,\n\ttypename BMatrixExprT,\n\ttypename CMatrixExprT,\n\ttypename DMatrixExprT\n>\nvoid make_ss(SysIdentStrategyT const& sys_ident_strategy,\n\t\t\t ::boost::numeric::ublas::matrix_container<AMatrixExprT>& A,\n\t\t\t ::boost::numeric::ublas::matrix_container<BMatrixExprT>& B,\n\t\t\t ::boost::numeric::ublas::matrix_container<CMatrixExprT>& C,\n\t\t\t ::boost::numeric::ublas::matrix_container<DMatrixExprT>& D)\n{\n//DCS_DEBUG_TRACE(\"BEGIN make_ss\");//XXX\n\tnamespace ublas = ::boost::numeric::ublas;\n\n\ttypedef typename ublas::promote_traits<\n\t\t\t\ttypename ublas::promote_traits<\n\t\t\t\t\ttypename ublas::promote_traits<\n\t\t\t\t\t\ttypename ublas::matrix_traits<AMatrixExprT>::value_type,\n\t\t\t\t\t\ttypename ublas::matrix_traits<BMatrixExprT>::value_type\n\t\t\t\t\t>::promote_type,\n\t\t\t\t\ttypename ublas::matrix_traits<CMatrixExprT>::value_type\n\t\t\t\t>::promote_type,\n\t\t\t\ttypename ublas::matrix_traits<DMatrixExprT>::value_type\n\t\t\t>::promote_type value_type;\n\ttypedef ::std::size_t size_type; //FIXME: use type-promotion?\n\n\tconst size_type rls_n_a(sys_ident_strategy.output_order());\n\tconst size_type rls_n_b(sys_ident_strategy.input_order());\n//\tconst size_type rls_d(sys_ident_strategy.input_delay());\n\tconst size_type rls_n_y(sys_ident_strategy.num_outputs());\n\tconst size_type rls_n_u(sys_ident_strategy.num_inputs());\n\tconst size_type n_x(rls_n_a*rls_n_y+(rls_n_b-1)*rls_n_u);\n\tconst size_type n_u(rls_n_u);\n//\tconst size_type n(::std::max(n_x,n_u));\n\tconst size_type n_y(1);\n\n\t// Create the state matrix A\n\t// A=[ 0        I          0         ...  0    0        I          0         ...  0  ;\n\t//     0        0          I         ...  0    0        0          I         ...  0  ;\n\t//     .        .          .         ...  .    .        .          0         ...  .\n\t//     .        .          .         ...  .    .        .          0         ...  .\n\t//     .        .          .         ...  .    .        .          0         ...  .\n\t// \t   0        0          0         ...  I    0        0          0         ...  I  ;\n\t// \t   B_{n_b}  B_{n_b-1}  B_{n_b-2} ...  B_2 -A_{n_a} -A_{n_a-1} -A_{n_a-2} ... -A_1]\n\tif (n_x > 0)\n\t{\n\t\tsize_type broffs(n_x-rls_n_y); // The bottom row offset\n\t\tsize_type cboffs0(rls_n_u);\n\t\tsize_type cboffs1(cboffs0+((rls_n_b > 2) ? (rls_n_b-2)*rls_n_u : 0));\n\t\tsize_type caoffs0(cboffs1+rls_n_y);\n\t\tsize_type caoffs1(caoffs0+((rls_n_a > 1) ? (rls_n_a-1)*rls_n_y : 0));\n\n\t\tA().resize(n_x, n_x, false);\n\n\t\t// The upper part of A is set to [0_{k,rls_n_u} I_{k,kb} 0_{k,rls_n_y} I_{k,ka}],\n\t\t// where: k=n_x-rls_n_y, kb=(rls_n_b-2)*rls_n_u, ka=(rls_n_a-1)*rls_n_y.\n\t\tif (cboffs0 > 0)\n\t\t{\n\t\t\tublas::subrange(A(), 0, broffs, 0, cboffs0) = ublas::zero_matrix<value_type>(broffs,rls_n_u);\n\t\t}\n\t\tif (cboffs1 > cboffs0)\n\t\t{\n\t\t\tublas::subrange(A(), 0, broffs, cboffs0, cboffs1) = ublas::identity_matrix<value_type>(broffs,cboffs1-cboffs0);\n\t\t}\n\t\tif (caoffs0 > cboffs1)\n\t\t{\n\t\t\tublas::subrange(A(), 0, broffs, cboffs1, caoffs0) = ublas::zero_matrix<value_type>(broffs,caoffs0-cboffs1);\n\t\t}\n\t\tif (caoffs1 > caoffs0)\n\t\t{\n\t\t\tublas::subrange(A(), 0, broffs, caoffs0, caoffs1) = ublas::identity_matrix<value_type>(broffs,caoffs1-caoffs0);\n\t\t}\n\n\t\t// Fill A with B_2, ..., B_{n_b}\n\t\tfor (size_type i = 1; i < rls_n_b; ++i)\n\t\t{\n\t\t\t// Copy matrix B_i from \\hat{\\Theta} into A.\n\t\t\t// In A the matrix B_i has to go in (rls_n_b-i)-th position:\n\t\t\t//   A(k:(k+n),((rls_n_b-i-1)*rls_n_u):((rls_n_b-i)*rls_n_u)) <- B_i\n\n\t\t\tsize_type c2((rls_n_b-i)*rls_n_u);\n\t\t\tsize_type c1(c2-rls_n_u);\n\n\t\t\tublas::subrange(A(), broffs, n_x, c1, c2) = sys_ident_strategy.B(i+1);\n\t\t}\n\n\t\t// Fill A with A_1, ..., A_{n_a}\n\t\tfor (size_type i = 0; i < rls_n_a; ++i)\n\t\t{\n\t\t\t// Copy matrix -A_i from \\hat{\\Theta} into A.\n\t\t\t// In A the matrix A_i has to go in ((rls_n_b-1)*rls_n_u+rls_n_a-i)-th position:\n\t\t\t//   A(k:(k+n),((rls_n_b-1)*rls_n_u+(rls_n_a-i-1)*rls_n_y):((rls_n_b-1)*rls_n_u+(rls_n_a-i)*rls_n_y)) <- -A_i\n\n\t\t\tsize_type c2(cboffs1+(rls_n_a-i)*rls_n_y);\n\t\t\tsize_type c1(c2-rls_n_y);\n\n\t\t\t////ublas::subrange(A(), broffs, n_x, c1, c2) = sys_ident_strategy.A(i+1);\n\t\t\tublas::subrange(A(), broffs, n_x, c1, c2) = -sys_ident_strategy.A(i+1);\n\t\t\t//ublas::subrange(A(), broffs, n_x, c1, c2) = sys_ident_strategy.A(i+1);\n\t\t}\n\t}\n\telse\n\t{\n\t\tA().resize(0, 0, false);\n\t}\n//DCS_DEBUG_TRACE(\"A=\"<<A);//XXX\n\n\t// Create the input matrix B\n\t// B=[I  ;\n\t//    0  ;\n\t//    .\t ;\n\t//    .\t ;\n\t//    .\t ;\n\t//    0  ;\n\t//    B_1]\n\tif (n_x > 0)\n\t{\n\t\tsize_type broffs(n_x-rls_n_u); // The bottom row offset\n\n\t\tB().resize(n_x, n_u, false);\n\n\t\t// The upper part of B is set to [I_{n_u,n_u} 0_{k,n_u}]\n\t\t// where: k=n_x-rls_n_u.\n\t\tublas::subrange(B(), 0, n_u, 0, n_u) = ublas::identity_matrix<value_type>(n_u,n_u);\n\t\tublas::subrange(B(), n_u, broffs, 0, n_u) = ublas::zero_matrix<value_type>(broffs-n_u,n_u);\n\t\t// The bottom part of B with B_1\n\t\tublas::subrange(B(), broffs, n_x, 0, n_u) = sys_ident_strategy.B(1);\n\t}\n\telse\n\t{\n\t\tB().resize(0, 0, false);\n\t}\n//DCS_DEBUG_TRACE(\"B=\"<<B);//XXX\n\n\t// Create the output matrix C\n\t// C=[0 0 ... 1 ... 1]\n\tif (n_x > 0)\n\t{\n\t\tsize_type rcoffs(n_x-rls_n_y); // The right most column offset\n\n\t\tC().resize(n_y, n_x, false);\n\n\t\tublas::subrange(C(), 0, n_y, 0, rcoffs) = ublas::zero_matrix<value_type>(n_y,rcoffs);\n\t\tublas::subrange(C(), 0, n_y, rcoffs, n_x) = ublas::scalar_matrix<value_type>(n_y, rls_n_y, 1);\n\t}\n\telse\n\t{\n\t\tC().resize(0, 0, false);\n\t}\n//DCS_DEBUG_TRACE(\"C=\"<<C);//XXX\n\n\t// Create the transmission matrix D\n\t{\n\t\tD().resize(n_y, n_u, false);\n\n\t\tD() = ublas::zero_matrix<value_type>(n_y, n_u);\n\t}\n//DCS_DEBUG_TRACE(\"D=\"<<D);//XXX\n\n//DCS_DEBUG_TRACE(\"END make_ss\");//XXX\n}\n\n#elif defined(DCS_TESTBED_EXP_LQ_APP_MGR_USE_ALT_SS) && DCS_TESTBED_EXP_LQ_APP_MGR_USE_ALT_SS == 'Y'\n\n/**\n * \\brief Convert a discrete model from ARX structure to a state-space model.\n *\n * Given the following input-output system:\n * \\f[\n *  y(k)+\\sum_{i=1}^{n_a}y(k-i)=\\sum_{i=1}^{n_b}u(k-d-i)\n * \\f]\n * create the following state-space system:\n * \\f{align}{\n *  x(k+1) &= Ax(k)+Bu(k),\\\\\n *  y(k)   &= Cx(k)+Du(k)\n * \\f}\n * such that:\n * \\f{align}{\n *  x(k) &=\\begin{pmatrix}\n *          u(k-d-n_b+1) \\\\\n *          .            \\\\\n *          .            \\\\\n *          .            \\\\\n *          u(k-d-1)     \\\\\n *          y(k-n_a+1)   \\\\\n *          .            \\\\\n *          .            \\\\\n *          .            \\\\\n *          y(k)\n *      \\end{pmatrix},\\\\\n *  u(k) &=\\begin{pmatrix}\n *          u(k-d)\n *      \\end{pmatrix},\\\\\n *  A &=\\begin{pmatrix}\n *       0       & I         & 0         & \\ldots & 0   & 0       & I         & 0         & \\ldots & 0  \\\\\n *       0       & 0         & I         & \\ldots & 0   & 0       & 0         & I         & \\ldots & 0  \\\\\n *       .       & .         & .         & \\ldots & .   & .       & .         & 0         & \\ldots & .  \\\\\n *       .       & .         & .         & \\ldots & .   & .       & .         & 0         & \\ldots & .  \\\\\n *       .       & .         & .         & \\ldots & .   & .       & .         & 0         & \\ldots & .  \\\\\n *       0       & 0         & 0         & \\ldots & I   & 0       & 0         & 0         & \\ldots & I  \\\\\n *       B_{n_b} & B_{n_b-1} & B_{n_b-2} & \\ldost & B_2 &-A_{n_a} &-A_{n_a-1} &-A_{n_a-2} & \\ldots &-A_1\n *      \\end{pmatrix},\\\\\n *  B &=\\begin{pmatrix}\n *       0  \\\\\n *       .  \\\\\n *       .\t\\\\\n *       .\t\\\\\n *       0\t\\\\\n *       I\t\\\\\n *       0\t\\\\\n *       .\t\\\\\n *       .\t\\\\\n *       .\t\\\\\n *       0  \\\\\n *       B_1\n *      \\end{pmatrix},\\\\\n *  C &=\\begin{pmatrix}\n *       0 & \\ldots & 0 & I\n *      \\end{pmatrix},\\\\\n *  D &=\\begin{pmatrix}\n *       0\n *      \\end{pmatrix}\n * \\f}\n */\ntemplate <\n\ttypename SysIdentStrategyT,\n\ttypename AMatrixExprT,\n\ttypename BMatrixExprT,\n\ttypename CMatrixExprT,\n\ttypename DMatrixExprT\n>\nvoid make_ss(SysIdentStrategyT const& sys_ident_strategy,\n\t\t\t ::boost::numeric::ublas::matrix_container<AMatrixExprT>& A,\n\t\t\t ::boost::numeric::ublas::matrix_container<BMatrixExprT>& B,\n\t\t\t ::boost::numeric::ublas::matrix_container<CMatrixExprT>& C,\n\t\t\t ::boost::numeric::ublas::matrix_container<DMatrixExprT>& D)\n{\n//DCS_DEBUG_TRACE(\"BEGIN make_ss\");//XXX\n\tnamespace ublas = ::boost::numeric::ublas;\n\n\ttypedef typename ublas::promote_traits<\n\t\t\t\ttypename ublas::promote_traits<\n\t\t\t\t\ttypename ublas::promote_traits<\n\t\t\t\t\t\ttypename ublas::matrix_traits<AMatrixExprT>::value_type,\n\t\t\t\t\t\ttypename ublas::matrix_traits<BMatrixExprT>::value_type\n\t\t\t\t\t>::promote_type,\n\t\t\t\t\ttypename ublas::matrix_traits<CMatrixExprT>::value_type\n\t\t\t\t>::promote_type,\n\t\t\t\ttypename ublas::matrix_traits<DMatrixExprT>::value_type\n\t\t\t>::promote_type value_type;\n\ttypedef ::std::size_t size_type; //FIXME: use type-promotion?\n\n\tconst size_type rls_n_a(sys_ident_strategy.output_order());\n\tconst size_type rls_n_b(sys_ident_strategy.input_order());\n//\tconst size_type rls_d(sys_ident_strategy.input_delay());\n\tconst size_type rls_n_y(sys_ident_strategy.num_outputs());\n\tconst size_type rls_n_u(sys_ident_strategy.num_inputs());\n\tconst size_type n_x(rls_n_a*rls_n_y+(rls_n_b-1)*rls_n_u);\n\tconst size_type n_u(rls_n_u);\n//\tconst size_type n(::std::max(n_x,n_u));\n\tconst size_type n_y(1);\n\n\t// Create the state matrix A\n\t// A=[ 0        I          0         ...  0    0        I          0         ...  0  ;\n\t//     0        0          I         ...  0    0        0          I         ...  0  ;\n\t//     .        .          .         ...  .    .        .          0         ...  .\n\t//     .        .          .         ...  .    .        .          0         ...  .\n\t//     .        .          .         ...  .    .        .          0         ...  .\n\t// \t   0        0          0         ...  I    0        0          0         ...  I  ;\n\t// \t   B_{n_b}  B_{n_b-1}  B_{n_b-2} ...  B_2 -A_{n_a} -A_{n_a-1} -A_{n_a-2} ... -A_1]\n\tif (n_x > 0)\n\t{\n\t\tconst size_type broffs(n_x-rls_n_y); // The bottom row offset\n\t\tconst size_type cboffs0(rls_n_b > 1 ? rls_n_u : 0); // The column offset where to write the second B_i matrix (i.e., B_{n_b}-1 matrix)\n\t\tconst size_type cboffs1(cboffs0+((rls_n_b > 2) ? (rls_n_b-2)*rls_n_u : 0)); // The column offset where to write the last B_i matrix (i.e., B_2 matrix)\n\t\tconst size_type caoffs0(cboffs1+rls_n_y); // The column offset where to write the first A_i matrix (i.e., A_{n_a} matrix)\n\t\tconst size_type caoffs1(caoffs0+((rls_n_a > 1) ? (rls_n_a-1)*rls_n_y : 0)); // The column offset where to write the last A_i matrix (i.e., A_1 matrix)\n\n\t\tA().resize(n_x, n_x, false);\n\n\t\t// The upper part of A is set to [0_{k,rls_n_u} I_{k,kb} 0_{k,rls_n_y} I_{k,ka}],\n\t\t// where: k=n_x-rls_n_y, kb=(rls_n_b-2)*rls_n_u, ka=(rls_n_a-1)*rls_n_y.\n\t\tif (cboffs0 > 0)\n\t\t{\n\t\t\tublas::subrange(A(), 0, broffs, 0, cboffs0) = ublas::zero_matrix<value_type>(broffs,rls_n_u);\n\t\t}\n\t\tif (cboffs1 > cboffs0)\n\t\t{\n\t\t\tublas::subrange(A(), 0, broffs, cboffs0, cboffs1) = ublas::identity_matrix<value_type>(broffs,cboffs1-cboffs0);\n\t\t}\n\t\tif (caoffs0 > cboffs1)\n\t\t{\n\t\t\tublas::subrange(A(), 0, broffs, cboffs1, caoffs0) = ublas::zero_matrix<value_type>(broffs,caoffs0-cboffs1);\n\t\t}\n\t\tif (caoffs1 > caoffs0)\n\t\t{\n\t\t\tublas::subrange(A(), 0, broffs, caoffs0, caoffs1) = ublas::identity_matrix<value_type>(broffs,caoffs1-caoffs0);\n\t\t}\n\n\t\t// Fill A with B_2, ..., B_{n_b}\n\t\tfor (size_type i = 1; i < rls_n_b; ++i)\n\t\t{\n\t\t\t// Copy matrix B_i from \\hat{\\Theta} into A.\n\t\t\t// In A the matrix B_i has to go in (rls_n_b-i)-th position:\n\t\t\t//   A(k:(k+n),((rls_n_b-i-1)*rls_n_u):((rls_n_b-i)*rls_n_u)) <- B_i\n\n\t\t\tsize_type c2((rls_n_b-i)*rls_n_u);\n\t\t\tsize_type c1(c2-rls_n_u);\n\n\t\t\tublas::subrange(A(), broffs, n_x, c1, c2) = sys_ident_strategy.B(i+1);\n\t\t}\n\n\t\t// Fill A with A_1, ..., A_{n_a}\n\t\tfor (size_type i = 0; i < rls_n_a; ++i)\n\t\t{\n\t\t\t// Copy matrix -A_i from \\hat{\\Theta} into A.\n\t\t\t// In A the matrix A_i has to go in ((rls_n_b-1)*rls_n_u+rls_n_a-i)-th position:\n\t\t\t//   A(k:(k+n),((rls_n_b-1)*rls_n_u+(rls_n_a-i-1)*rls_n_y):((rls_n_b-1)*rls_n_u+(rls_n_a-i)*rls_n_y)) <- -A_i\n\n\t\t\tsize_type c2(cboffs1+(rls_n_a-i)*rls_n_y);\n\t\t\tsize_type c1(c2-rls_n_y);\n\n\t\t\t////ublas::subrange(A(), broffs, n_x, c1, c2) = sys_ident_strategy.A(i+1);\n\t\t\tublas::subrange(A(), broffs, n_x, c1, c2) = -sys_ident_strategy.A(i+1);\n\t\t\t//ublas::subrange(A(), broffs, n_x, c1, c2) = sys_ident_strategy.A(i+1);\n\t\t}\n\t}\n\telse\n\t{\n\t\tA().resize(0, 0, false);\n\t}\n//DCS_DEBUG_TRACE(\"A=\"<<A);//XXX\n\n\t// Create the input matrix B\n\t// B=[0  ;\n\t//    0  ;\n\t//    .\t ;\n\t//    .\t ;\n\t//    .\t ;\n\t//    0  ;\n\t//    I  ;\n\t//    0  ;\n\t//    .\t ;\n\t//    .\t ;\n\t//    .\t ;\n\t//    0  ;\n\t//    B_1]\n\tif (n_x > 0 && n_u > 0)\n\t{\n\t\tconst size_type iroffs((rls_n_b > 2) ? rls_n_u*(rls_n_b-2) : 0); // The row offset where to write the identity matrix\n\t\tconst size_type zroffs(iroffs+rls_n_u); // The row offset where to write the second zero matrix\n\t\tconst size_type broffs(n_x-rls_n_u); // The bottom row offset\n\n\t\tB().resize(n_x, n_u, false);\n\n\t\t// The upper part of B is set to [0_{h,n_u} I_{n_u,n_u} 0_{k,n_u}]\n\t\t// where: h=rls_n_u*(rls_n_b-2) and k=rls_n_y*(rls_n_a-1)\n\t\tif (iroffs > 0)\n\t\t{\n\t\t\tublas::subrange(B(), 0, iroffs, 0, n_u) = ublas::zero_matrix<value_type>(iroffs,n_u);\n\t\t}\n\t\tublas::subrange(B(), iroffs, zroffs, 0, n_u) = ublas::identity_matrix<value_type>(n_u,n_u);\n\t\tif (broffs > zroffs)\n\t\t{\n\t\t\tublas::subrange(B(), zroffs, broffs, 0, n_u) = ublas::zero_matrix<value_type>(broffs-zroffs,n_u);\n\t\t}\n\t\t// The bottom part of B with B_1\n\t\tublas::subrange(B(), broffs, n_x, 0, n_u) = sys_ident_strategy.B(1);\n\t}\n\telse\n\t{\n\t\tB().resize(0, 0, false);\n\t}\n//DCS_DEBUG_TRACE(\"B=\"<<B);//XXX\n\n\t// Create the output matrix C\n\t// C=[0 0 ... I]\n\tif (n_x > 0)\n\t{\n\t\tsize_type rcoffs(n_x-rls_n_y); // The right most column offset\n\n\t\tC().resize(n_y, n_x, false);\n\n\t\tublas::subrange(C(), 0, n_y, 0, rcoffs) = ublas::zero_matrix<value_type>(n_y,rcoffs);\n\t\tublas::subrange(C(), 0, n_y, rcoffs, n_x) = ublas::identity_matrix<value_type>(rls_n_y,rls_n_y);\n\t}\n\telse\n\t{\n\t\tC().resize(0, 0, false);\n\t}\n//DCS_DEBUG_TRACE(\"C=\"<<C);//XXX\n\n\t// Create the transmission matrix D\n\tif (n_u > 0)\n\t{\n\t\tD().resize(n_y, n_u, false);\n\n\t\tD() = ublas::zero_matrix<value_type>(n_y, n_u);\n\t}\n\telse\n\t{\n\t\tD().resize(0, 0, false);\n\t}\n//DCS_DEBUG_TRACE(\"D=\"<<D);//XXX\n\n//DCS_DEBUG_TRACE(\"END make_ss\");//XXX\n}\n\n#elif defined(DCS_TESTBED_EXP_LQ_APP_MGR_USE_ALT_SS) && DCS_TESTBED_EXP_LQ_APP_MGR_USE_ALT_SS == 'C'\n\n/// Convert an ARX structure to a state-space model in the canonical controllable form.\ntemplate <\n\ttypename SysIdentStrategyT,\n\ttypename AMatrixExprT,\n\ttypename BMatrixExprT,\n\ttypename CMatrixExprT,\n\ttypename DMatrixExprT\n>\ninline\nvoid make_ss(SysIdentStrategyT const& sys_ident_strategy,\n\t\t\t ::boost::numeric::ublas::matrix_container<AMatrixExprT>& A,\n\t\t\t ::boost::numeric::ublas::matrix_container<BMatrixExprT>& B,\n\t\t\t ::boost::numeric::ublas::matrix_container<CMatrixExprT>& C,\n\t\t\t ::boost::numeric::ublas::matrix_container<DMatrixExprT>& D)\n{\n\tmake_controllable_ss(sys_ident_strategy, A, B, C, D);\n}\n\n#elif defined(DCS_TESTBED_EXP_LQ_APP_MGR_USE_ALT_SS) && DCS_TESTBED_EXP_LQ_APP_MGR_USE_ALT_SS == 'O'\n\n/// Convert an ARX structure to a state-space model in the canonical observable form.\ntemplate <\n\ttypename SysIdentStrategyT,\n\ttypename AMatrixExprT,\n\ttypename BMatrixExprT,\n\ttypename CMatrixExprT,\n\ttypename DMatrixExprT\n>\ninline\nvoid make_ss(SysIdentStrategyT const& sys_ident_strategy,\n\t\t\t ::boost::numeric::ublas::matrix_container<AMatrixExprT>& A,\n\t\t\t ::boost::numeric::ublas::matrix_container<BMatrixExprT>& B,\n\t\t\t ::boost::numeric::ublas::matrix_container<CMatrixExprT>& C,\n\t\t\t ::boost::numeric::ublas::matrix_container<DMatrixExprT>& D)\n{\n\tmake_observable_ss(sys_ident_strategy, A, B, C, D);\n}\n\n#else // DCS_DES_TESTBED_EXP_LQ_APP_MGR_ALT_SS\n\ntemplate <\n\ttypename SysIdentStrategyT,\n\ttypename AMatrixExprT,\n\ttypename BMatrixExprT,\n\ttypename CMatrixExprT,\n\ttypename DMatrixExprT\n>\n//void make_ss(rls_ff_mimo_proxy<TraitsT> const& sys_ident_strategy,\nvoid make_ss(SysIdentStrategyT const& sys_ident_strategy,\n\t\t\t ::boost::numeric::ublas::matrix_container<AMatrixExprT>& A,\n\t\t\t ::boost::numeric::ublas::matrix_container<BMatrixExprT>& B,\n\t\t\t ::boost::numeric::ublas::matrix_container<CMatrixExprT>& C,\n\t\t\t ::boost::numeric::ublas::matrix_container<DMatrixExprT>& D)\n{\n//DCS_DEBUG_TRACE(\"BEGIN make_ss\");//XXX\n\tnamespace ublas = ::boost::numeric::ublas;\n\n\ttypedef typename ublas::promote_traits<\n\t\t\t\ttypename ublas::promote_traits<\n\t\t\t\t\ttypename ublas::promote_traits<\n\t\t\t\t\t\ttypename ublas::matrix_traits<AMatrixExprT>::value_type,\n\t\t\t\t\t\ttypename ublas::matrix_traits<BMatrixExprT>::value_type\n\t\t\t\t\t>::promote_type,\n\t\t\t\t\ttypename ublas::matrix_traits<CMatrixExprT>::value_type\n\t\t\t\t>::promote_type,\n\t\t\t\ttypename ublas::matrix_traits<DMatrixExprT>::value_type\n\t\t\t>::promote_type value_type;\n\ttypedef ::std::size_t size_type; //FIXME: use type-promotion?\n\n\tconst size_type rls_n_a(sys_ident_strategy.output_order());\n\tconst size_type rls_n_b(sys_ident_strategy.input_order());\n//\tconst size_type rls_d(sys_ident_strategy.input_delay());\n\tconst size_type rls_n_y(sys_ident_strategy.num_outputs());\n\tconst size_type rls_n_u(sys_ident_strategy.num_inputs());\n\tconst size_type n_x(rls_n_a*rls_n_y);\n\tconst size_type n_u(rls_n_b*rls_n_u);\n//\tconst size_type n(::std::max(n_x,n_u));\n\tconst size_type n_y(1);\n\n\t// Create the state matrix A\n\t// A=[ 0        I          0         ...  0  ;\n\t//     0        0          I         ...  0  ;\n\t//     .        .          .         ...  .\n\t//     .        .          .         ...  .\n\t//     .        .          .         ...  .\n\t// \t   0        0          0         ...  I  ;\n\t// \t  -A_{n_a} -A_{n_a-1} -A_{n_a-2} ... -A_1]\n\tif (n_x > 0)\n\t{\n\t\tsize_type broffs(n_x-rls_n_y); // The bottom row offset\n\n\t\tA().resize(n_x, n_x, false);\n\n\t\t// The upper part of A is set to [0_{k,rls_n_y} I_{k,k}],\n\t\t// where: k=n_x-rls_n_y.\n\t\tublas::subrange(A(), 0, broffs, 0, rls_n_y) = ublas::zero_matrix<value_type>(broffs,rls_n_y);\n\t\tublas::subrange(A(), 0, broffs, rls_n_y, n_x) = ublas::identity_matrix<value_type>(broffs,broffs);\n\n\t\t// Fill A with A_1, ..., A_{n_a}\n\t\tfor (size_type i = 0; i < rls_n_a; ++i)\n\t\t{\n\t\t\t// Copy matrix -A_i from \\hat{\\Theta} into A.\n\t\t\t// In A the matrix A_i has to go in (rls_n_a-i)-th position:\n\t\t\t//   A(k:(k+n),((rls_n_a-i-1)*rls_n_y):((rls_n_a-i)*rls_n_y)) <- -A_i\n\n\t\t\tsize_type c2((rls_n_a-i)*rls_n_y);\n\t\t\tsize_type c1(c2-rls_n_y);\n\n\t\t\t////ublas::subrange(A(), broffs, n_x, c1, c2) = sys_ident_strategy.A(i+1);\n\t\t\tublas::subrange(A(), broffs, n_x, c1, c2) = -sys_ident_strategy.A(i+1);\n\t\t\t//ublas::subrange(A(), broffs, n_x, c1, c2) = sys_ident_strategy.A(i+1);\n\t\t}\n\t}\n\telse\n\t{\n\t\tA().resize(0, 0, false);\n\t}\n//DCS_DEBUG_TRACE(\"A=\"<<A);//XXX\n\n\t// Create the input matrix B\n\t// B=[0 ... 0;\n\t//    .\t... .\n\t//    .\t... .\n\t//    .\t... .\n\t//    0 ... 0;\n\t//    B_{n_b} ... B_1]\n\tif (n_x > 0)\n\t{\n\t\tsize_type broffs(n_x-rls_n_u); // The bottom row offset\n\n\t\tB().resize(n_x, n_u, false);\n\n\t\t// The upper part of B is set to 0_{k,n_u}\n\t\t// where: k=n_x-rls_n_u.\n\t\tublas::subrange(B(), 0, broffs, 0, n_u) = ublas::zero_matrix<value_type>(broffs,n_u);\n\n\t\t// Fill B with B_1, ..., B_{n_b}\n\t\tfor (size_type i = 0; i < rls_n_b; ++i)\n\t\t{\n\t\t\t// Copy matrix B_i from \\hat{\\Theta} into B.\n\t\t\t// In \\hat{\\Theta} the matrix B_i stays at:\n\t\t\t//   B_i <- (\\hat{\\Theta}(((n_a*n_y)+i):n_b:n_u,:))^T\n\t\t\t// but in B the matrix B_i has to go in (n_b-i)-th position:\n\t\t\t//   B(k:(k+n_x),((n_b-i-1)*n_u):((n_a-i)*n_u)) <- B_i\n\n\t\t\tsize_type c2((rls_n_b-i)*rls_n_u);\n\t\t\tsize_type c1(c2-rls_n_u);\n\n\t\t\tublas::subrange(B(), broffs, n_x, c1, c2) = sys_ident_strategy.B(i+1);\n\t\t}\n\t}\n\telse\n\t{\n\t\tB().resize(0, 0, false);\n\t}\n//DCS_DEBUG_TRACE(\"B=\"<<B);//XXX\n\n\t// Create the output matrix C\n\tif (n_x > 0)\n\t{\n\t\tsize_type rcoffs(n_x-rls_n_y); // The right most column offset\n\n\t\tC().resize(n_y, n_x, false);\n\n\t\tublas::subrange(C(), 0, n_y, 0, rcoffs) = ublas::zero_matrix<value_type>(n_y,rcoffs);\n\t\tublas::subrange(C(), 0, n_y, rcoffs, n_x) = ublas::scalar_matrix<value_type>(n_y, rls_n_y, 1);\n\t}\n\telse\n\t{\n\t\tC().resize(0, 0, false);\n\t}\n//DCS_DEBUG_TRACE(\"C=\"<<C);//XXX\n\n\t// Create the transmission matrix D\n\t{\n\t\tD().resize(n_y, n_u, false);\n\n\t\tD() = ublas::zero_matrix<value_type>(n_y, n_u);\n\t}\n//DCS_DEBUG_TRACE(\"D=\"<<D);//XXX\n\n//DCS_DEBUG_TRACE(\"END make_ss\");//XXX\n}\n\n#endif // DCS_DES_TESTBED_EXP_LQ_APP_MGR_ALT_SS\n\n}} // Namespace detail::<unnamed>\n\n\ntemplate <typename TraitsT>\nclass lq_application_manager: public base_application_manager<TraitsT>\n{\n\tprivate: typedef base_application_manager<TraitsT> base_type;\n\tpublic: typedef typename base_type::traits_type traits_type;\n\tpublic: typedef typename base_type::uint_type uint_type;\n\tpublic: typedef typename traits_type::real_type real_type;\n\tprivate: typedef typename base_type::app_type app_type;\n\tprivate: typedef typename base_type::app_pointer app_pointer;\n\tprivate: typedef typename app_type::sensor_type sensor_type;\n\tprivate: typedef typename app_type::sensor_pointer sensor_pointer;\n\tprotected: typedef ::boost::numeric::ublas::vector<real_type> numeric_vector_type;\n\tprotected: typedef ::boost::numeric::ublas::matrix<real_type> numeric_matrix_type;\n\tprivate: typedef base_arx_system_identification_strategy<traits_type> sysid_strategy_type;\n\tprivate: typedef ::boost::shared_ptr<sysid_strategy_type> sysid_strategy_pointer;\n\tprivate: typedef ::std::vector<real_type> observation_container;\n\tprivate: typedef ::std::map<application_performance_category,observation_container> observation_map;\n\tprivate: typedef ::std::map<application_performance_category,real_type> target_map;\n\tprivate: typedef ::std::map<application_performance_category,sensor_pointer> sensor_map;\n\n\n\tprivate: static const uint_type default_sampling_time;\n\tprivate: static const uint_type default_control_time;\n\tprivate: static const real_type default_min_share;\n\tprivate: static const real_type default_max_share;\n\tprivate: static const real_type default_ewma_smoothing_factor;\n\n\n\tpublic: lq_application_manager()\n\t: nx_(0),\n\t  nu_(0),\n\t  ny_(0),\n\t  x_offset_(0),\n\t  u_offset_(0),\n\t  ctl_count_(0),\n\t  ctl_skip_count_(0),\n\t  ctl_fail_count_(0),\n\t  sysid_fail_count_(0),\n\t  ewma_sf_(default_ewma_smoothing_factor)\n\t{\n\t\tthis->sampling_time(default_sampling_time);\n\t\tthis->control_time(default_control_time);\n\t}\n\n\tpublic: void sysid_strategy(sysid_strategy_pointer const& p_strategy)\n\t{\n\t\tp_sysid_alg_ = p_strategy;\n\t}\n\n\tpublic: sysid_strategy_pointer sysid_strategy()\n\t{\n\t\treturn p_sysid_alg_;\n\t}\n\n\tpublic: sysid_strategy_pointer sysid_strategy() const\n\t{\n\t\treturn p_sysid_alg_;\n\t}\n\n\tprotected: numeric_vector_type const& state_vector() const\n\t{\n\t\treturn x_;\n\t}\n\n\tprotected: numeric_vector_type& state_vector()\n\t{\n\t\treturn x_;\n\t}\n\n\tprotected: numeric_vector_type const& input_vector() const\n\t{\n\t\treturn u_;\n\t}\n\n\tprotected: numeric_vector_type& input_vector()\n\t{\n\t\treturn u_;\n\t}\n\n\tprotected: numeric_vector_type const& output_vector() const\n\t{\n\t\treturn y_;\n\t}\n\n\tprotected: numeric_vector_type& output_vector()\n\t{\n\t\treturn y_;\n\t}\n\n\tprivate: numeric_vector_type lq_control(numeric_matrix_type const& A,\n\t\t\t\t\t\t\t\t\t\t\tnumeric_matrix_type const& B,\n\t\t\t\t\t\t\t\t\t\t\tnumeric_matrix_type const& C,\n\t\t\t\t\t\t\t\t\t\t\tnumeric_matrix_type const& D)\n\t{\n\t\treturn do_lq_control(A, B, C, D);\n\t}\n\n\tprivate: void do_reset()\n\t{\n\t\t// pre: p_sysid_alg_ != null\n\t\tDCS_ASSERT(p_sysid_alg_,\n\t\t\t\t   DCS_EXCEPTION_THROW(::std::runtime_error,\n\t\t\t\t\t\t\t\t\t   \"System identification strategy is not set\"));\n\n\t\t//[FIXME]\n\t\tDCS_ASSERT(tgt_map_.size() == 1,\n\t\t\t\t   DCS_EXCEPTION_THROW(::std::logic_error,\n\t\t\t\t\t\t\t\t\t   \"Currently, only one application performace category is handled\"));\n\t\t//[/FIXME]\n\n\t\tp_sysid_alg_->init();\n\n\t\tconst ::std::size_t np(p_sysid_alg_->num_outputs());\n\t\tconst ::std::size_t ns(p_sysid_alg_->num_inputs());\n\t\tconst ::std::size_t na(p_sysid_alg_->output_order());\n\t\tconst ::std::size_t nb(p_sysid_alg_->input_order());\n\n#if defined(DCS_TESTBED_EXP_LQ_APP_MGR_USE_ALT_SS) && DCS_TESTBED_EXP_LQ_APP_MGR_USE_ALT_SS == 'X'\n\t\tnx_ = np*na+ns*(nb-1);\n\t\tnu_ = ns;\n\t\tny_ = np;\n\t\tx_offset_ = (nx_ > 0) ? (nx_-np) : 0;\n\t\tu_offset_ = 0;\n#elif defined(DCS_TESTBED_EXP_LQ_APP_MGR_USE_ALT_SS) && DCS_TESTBED_EXP_LQ_APP_MGR_USE_ALT_SS == 'Y'\n\t\tnx_ = np*na+ns*(nb-1);\n\t\tnu_ = ns;\n\t\tny_ = np;\n\t\tx_offset_ = (nx_ > 0) ? (nx_-np) : 0;\n\t\tu_offset_ = 0;\n#elif defined(DCS_TESTBED_EXP_LQ_APP_MGR_USE_ALT_SS) && DCS_TESTBED_EXP_LQ_APP_MGR_USE_ALT_SS == 'C'\n\t\tnx_ = np*na;\n\t\tnu_ = ns;\n\t\tny_ = np;\n\t\tx_offset_ = (nx_ > 0) ? (nx_-np) : 0;\n\t\tu_offset_ = 0;\n#elif defined(DCS_TESTBED_EXP_LQ_APP_MGR_USE_ALT_SS) && DCS_TESTBED_EXP_LQ_APP_MGR_USE_ALT_SS == 'O'\n\t\tnx_ = np*na;\n\t\tnu_ = ns;\n\t\tny_ = np;\n\t\tx_offset_ = (nx_ > 0) ? (nx_-np) : 0;\n\t\tu_offset_ = 0;\n#else // DCS_TESTBED_EXP_LQ_APP_MGR_ALT_SS\n\t\tnx_ = np*na;\n\t\tnu_ = ns*nb;\n\t\tny_ = np;\n\t\tx_offset_ = (nx_ > 0) ? (nx_-np) : 0;\n\t\tu_offset_ = (nu_ > 0) ? (nu_-ns) : 0;\n#endif // DCS_TESTBED_EXP_LQ_APP_MGR_ALT_SS\n\t\tx_ = numeric_vector_type(nx_, ::std::numeric_limits<real_type>::quiet_NaN());\n\t\tu_ = numeric_vector_type(nu_, ::std::numeric_limits<real_type>::quiet_NaN());\n\t\ty_ = numeric_vector_type(ny_, ::std::numeric_limits<real_type>::quiet_NaN());\n\t\t//yr_ = ::boost::numeric::ublas::scalar_vector<real_type>(ny_, tgt_map_.at(response_time_application_performance));\n\t\tyr_ = numeric_vector_type(ny_, ::std::numeric_limits<real_type>::quiet_NaN());\n\t\ttypedef typename target_map::const_iterator target_iterator;\n\t\ttarget_iterator tgt_end_it = tgt_map_.end();\n\t\tfor (target_iterator tgt_it = tgt_map_.begin();\n\t\t\t tgt_it != tgt_end_it;\n\t\t\t ++tgt_it)\n\t\t{\n\t\t\tapplication_performance_category cat(tgt_it->first);\n\n\t\t\tyr_ = numeric_vector_type(ny_, tgt_it->second);\n\t\t\tout_sens_map_[cat] = p_app_->sensor(cat);\n\t\t}\n\t\tewma_s_ = numeric_vector_type(ns, ::std::numeric_limits<real_type>::quiet_NaN());\n\t\tewma_p_ = numeric_vector_type(np, ::std::numeric_limits<real_type>::quiet_NaN());\n\t\tctl_count_ = ctl_skip_count_\n\t\t\t\t   = ctl_fail_count_\n\t\t\t\t   = sysid_fail_count_\n\t\t\t\t   = 0;\n\t}\n\n\tprivate: void do_sample()\n\t{\n\t\ttypedef typename sensor_type::observation_type obs_type;\n\t\ttypedef ::std::vector<obs_type> obs_container;\n\t\ttypedef typename obs_container::const_iterator obs_iterator;\n\t\ttypedef typename sensor_map::const_iterator sensor_iterator;\n\n\t\tDCS_DEBUG_TRACE(\"(\" << this << \") BEGIN Do SAMPLE - Count: \" << ctl_count_ << \"/\" << ctl_skip_count_ << \"/\" << sysid_fail_count_ << \"/\" << ctl_fail_count_);\n\n\t\tsensor_iterator sens_end_it = out_sens_map_.end();\n\t\tfor (sensor_iterator sens_it = out_sens_map_.begin();\n\t\t\t sens_it != sens_end_it;\n\t\t\t ++sens_it)\n\t\t{\n\t\t\tapplication_performance_category cat(sens_it->first);\n\t\t\tsensor_pointer p_sens(sens_it->second);\n\n\t\t\tp_sens->sense();\n\t\t\tif (p_sens->has_observations())\n\t\t\t{\n\t\t\t\tobs_container obs = p_sens->observations();\n\t\t\t\tobs_iterator end_it = obs.end();\n\t\t\t\tfor (obs_iterator it = obs.begin();\n\t\t\t\t\t it != end_it;\n\t\t\t\t\t ++it)\n\t\t\t\t{\n\t\t\t\t\tout_obs_map_[cat].push_back(it->value());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tDCS_DEBUG_TRACE(\"(\" << this << \") END Do SAMPLE - Count: \" << ctl_count_ << \"/\" << ctl_skip_count_ << \"/\" << sysid_fail_count_ << \"/\" << ctl_fail_count_);\n\t}\n\n\tprivate: void do_control()\n\t{\n\t\tnamespace ublas = ::boost::numeric::ublas;\n\t\tnamespace ublasx = ::boost::numeric::ublasx;\n\n\t\ttypedef typename app_type::vm_pointer vm_pointer;\n\t\ttypedef ::std::vector<vm_pointer> vm_container;\n\t\ttypedef typename vm_container::iterator vm_iterator;\n\t\ttypedef typename vm_container::const_iterator vm_citerator;\n\n\t\tDCS_DEBUG_TRACE(\"(\" << this << \") BEGIN Do CONTROL - Count: \" << ctl_count_ << \"/\" << ctl_skip_count_ << \"/\" << sysid_fail_count_ << \"/\" << ctl_fail_count_);\n\n\t\tconst ::std::size_t np = p_sysid_alg_->num_outputs();\n\t\tconst ::std::size_t ns = p_sysid_alg_->num_inputs();\n\t\tconst ::std::size_t na = p_sysid_alg_->output_order();\n\t\tconst ::std::size_t nb = p_sysid_alg_->input_order();\n\t\tconst ::std::size_t nk = p_sysid_alg_->input_delay();\n\n\t\tbool skip_ctl = false;\n\t\tnumeric_vector_type p(np, 0); // model output (performance measure)\n\t\tnumeric_vector_type s(ns, 0); // model input (resource share)\n\n\t\tvm_container vms = this->app()->vms();\n\n\t\t++ctl_count_;\n\n\t\t// Update measures\n\t\tif (out_obs_map_.size() > 0)\n\t\t{\n\t\t\ttypedef typename observation_map::const_iterator obs_map_iterator;\n\t\t\ttypedef typename observation_container::const_iterator obs_iterator;\n\n#if defined(DCS_TESTBED_APP_MGR_APPLY_EWMA_TO_EACH_OBSERVATION)\n\t\t\t//bool init_check = (ctl_count_ < 1) ? true : false;\n\t\t\tobs_map_iterator map_end_it = out_obs_map_.end();\n\t\t\tfor (obs_map_iterator map_it = out_obs_map_.begin();\n\t\t\t\t map_it != map_end_it;\n\t\t\t\t ++map_it)\n\t\t\t{\n\t\t\t\tapplication_performance_category cat(map_it->first);\n\n\t\t\t\tobs_iterator end_it = map_it->second.end();\n\t\t\t\tfor (obs_iterator it = map_it->second.begin();\n\t\t\t\t\t it != end_it;\n\t\t\t\t\t ++it)\n\t\t\t\t{\n\t\t\t\t\treal_type val(*it);\n\n\t\t\t\t\tif (::std::isnan(ewma_p_(0)))\n\t\t\t\t\t{\n\t\t\t\t\t\tewma_p_(0) = val;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tewma_p_(0) = ewma_sf_*val+(1-ewma_sf_)*ewma_p_(0);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n#else // DCS_TESTBED_APP_MGR_APPLY_EWMA_TO_EACH_OBSERVATION\n\t\t\tobs_map_iterator map_end_it = out_obs_map_.end();\n\t\t\tfor (obs_map_iterator map_it = out_obs_map_.begin();\n\t\t\t\t map_it != map_end_it;\n\t\t\t\t ++map_it)\n\t\t\t{\n\t\t\t\tapplication_performance_category cat(map_it->first);\n\n\t\t\t\t::boost::accumulators::accumulator_set< real_type, ::boost::accumulators::stats< ::boost::accumulators::tag::mean > > acc;\n\t\t\t\tobs_iterator end_it = map_it->second.end();\n\t\t\t\tfor (obs_iterator it = map_it->second.begin();\n\t\t\t\t\t it != end_it;\n\t\t\t\t\t ++it)\n\t\t\t\t{\n\t\t\t\t\tacc(*it);\n\t\t\t\t}\n\n\t\t\t\treal_type aggr_obs = ::boost::accumulators::mean(acc);\n\t\t\t\t//if (ctl_count_ < 1)\n\t\t\t\tif (::std::isnan(ewma_p_(0)))\n\t\t\t\t{\n\t\t\t\t\tewma_p_(0) = aggr_obs;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tewma_p_(0) = ewma_sf_*aggr_obs+(1-ewma_sf_)*ewma_p_(0);\n\t\t\t\t}\n\t\t\t}\n#endif // DCS_TESTBED_APP_MGR_APPLY_EWMA_TO_EACH_OBSERVATION\n\t\t}\n\t\telse if (np > 0)\n\t\t{\n\t\t\t// No observation collected during the last control interval\n\t\t\t//TODO: what can we do?\n\t\t\t// - Skip control?\n\t\t\t// - Use the last EWMA value (if ctl_count_ > 1)?\n\t\t\tskip_ctl = true;\n\t\t}\n\t\tif (ns > 0)\n\t\t{\n\t\t\t::std::size_t v(0);\n\n\t\t\tvm_citerator vm_end_it = vms.end();\n\t\t\tfor (vm_citerator vm_it = vms.begin();\n\t\t\t\t vm_it != vm_end_it;\n\t\t\t\t ++vm_it)\n\t\t\t{\n\t\t\t\tvm_pointer p_vm(*vm_it);\n\n\t\t\t\t// check: p_vm != null\n\t\t\t\tDCS_DEBUG_ASSERT( p_vm );\n\n\t\t\t\treal_type val(p_vm->cpu_share());\n\n\t\t\t\tif (::std::isnan(ewma_s_(v)))\n\t\t\t\t{\n\t\t\t\t\tewma_s_(v) = val;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tewma_s_(v) = ewma_sf_*val+(1-ewma_sf_)*ewma_s_(v);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (!skip_ctl)\n\t\t{\n\t\t\t// Rotate old with new inputs/outputs:\n\t\t\t//  x(k) = [p(k-n_a+1) ... p(k)]^T\n\t\t\t//       = [x_{n_p:n_x}(k-1) p(k)]^T\n\t\t\t//  u(k) = [s(k-n_b+1) ... s(k)]^T\n\t\t\t//       = [u_{n_s:n_u}(k-1) s(k)]^T\n\t\t\t// Check if a measure rotation is needed (always but the first time)\nDCS_DEBUG_TRACE(\"Old x=\" << x_);\nDCS_DEBUG_TRACE(\"Old u=\" << u_);\nDCS_DEBUG_TRACE(\"Old y=\" << y_);\n\t\t\tif (ctl_count_ > 1)\n\t\t\t{\n\t\t\t\t// throw away old observations from the state vector and make room for new ones\n\t\t\t\tif (nx_ > 0)\n\t\t\t\t{\n#if defined(DCS_TESTBED_EXP_LQ_APP_MGR_USE_ALT_SS) && DCS_TESTBED_EXP_LQ_APP_MGR_USE_ALT_SS == 'X'\n\t\t\t\t\tif (nb > 1)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (nb > 2)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tublas::subrange(x_, 0, (nb-2)*ns) = ublas::subrange(x_, ns, (nb-1)*ns);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tublas::subrange(x_, (nb-2)*ns, (nb-1)*ns) = u_;\n\t\t\t\t\t}\n\t\t\t\t\tublas::subrange(x_, ns*(nb-1), nx_-np) = ublas::subrange(x_, (nb-1)*ns+np, nx_);\n\t\t\t\t\tublas::subrange(x_, nx_-np, nx_) = ublas::scalar_vector<real_type>(np, ::std::numeric_limits<real_type>::quiet_NaN());\n#elif defined(DCS_TESTBED_EXP_LQ_APP_MGR_USE_ALT_SS) && DCS_TESTBED_EXP_LQ_APP_MGR_USE_ALT_SS == 'C'\n# error State-space representation in canonical controllable form has not fully implemented yet\n#elif defined(DCS_TESTBED_EXP_LQ_APP_MGR_USE_ALT_SS) && DCS_TESTBED_EXP_LQ_APP_MGR_USE_ALT_SS == 'O'\n\t\t\t\t\tfor (uint_type i = 0; i < na; ++i)\n\t\t\t\t\t{\n\t\t\t\t\t\tublas::subrange(x_, np*i, np*(i+1)) = - ublas::prod(p_sysid_alg_->A(na-i), ublas::subrange(x_, nx_-np, nx_)) + ublas::prod(p_sysid_alg_->B(nb-i), u_);\n\t\t\t\t\t\tif (i > 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tublas::subrange(x_, np*i, np*(i+1)) = ublas::subrange(x_, np*i, (np+1)*i) + ublas::subrange(x_, np*(i-1), np*i);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n#else // DCS_TESTBED_EXP_LQ_APP_MGR_USE_ALT_SS\n\t\t\t\t\tublas::subrange(x_, 0, nx_-np) = ublas::subrange(x_, np, nx_);\n\t\t\t\t\tublas::subrange(x_, nx_-np, nx_) = ublas::scalar_vector<real_type>(np, ::std::numeric_limits<real_type>::quiet_NaN());\n#endif // DCS_TESTBED_EXP_LQ_APP_MGR_USE_ALT_SS\n\t\t\t\t}\n\t\t\t\t// throw away old observations from the input vector and make room for new ones\n\t\t\t\tif (nu_ > 0)\n\t\t\t\t{\n#if defined(DCS_TESTBED_EXP_LQ_APP_MGR_USE_ALT_SS)\n\t\t\t\t\tu_ = ublas::scalar_vector<real_type>(ns, ::std::numeric_limits<real_type>::quiet_NaN());\n#else // DCS_TESTBED_EXP_LQ_APP_MGR_USE_ALT_SS\n\t\t\t\t\tublas::subrange(u_, 0, nu_-ns) = ublas::subrange(u_, ns, nu_);\n\t\t\t\t\tublas::subrange(u_, nu_-ns, nu_) = ublas::scalar_vector<real_type>(ns, ::std::numeric_limits<real_type>::quiet_NaN());\n#endif // DCS_TESTBED_EXP_LQ_APP_MGR_USE_ALT_SS\n\t\t\t\t}\n\t\t\t}\nDCS_DEBUG_TRACE(\"Prep x=\" << x_);\nDCS_DEBUG_TRACE(\"Prep u=\" << u_);\nDCS_DEBUG_TRACE(\"Prep y=\" << y_);\n\n\t\t\t// Update inputs/outputs\n\t\t\tif (nx_ > 0)\n\t\t\t{\n\t\t\t\t//FIXME: fix the assignment below\n\t\t\t\t//       Should we normalize/deviate/...?\n//\t\t\t\tfor (::std::size_t v = 0; v < np; ++v)\n//\t\t\t\t{\n//\t\t\t\t\tx_(x_offset_+v) = p(v) = ewma_p_(v)/yr_(v);\n//\t\t\t\t}\n\t\t\t\tublas::subrange(x_, x_offset_, nx_) = p\n\t\t\t\t\t\t\t\t\t\t\t\t\t= ublas::element_div(ewma_p_, yr_);\n\t\t\t\t//ublas::subrange(x_, x_offset_, nx_) = ublas::element_div(ewma_p_, yr_) - ublas::scalar_vector<real_type>(ny_, 1);\n\t\t\t}\n\t\t\tif (nu_ > 0)\n\t\t\t{\n\t\t\t\t//FIXME: actual share should be scaled according to the capacity of the \"reference\" machine\n\n\t\t\t\t::std::size_t v(0);\n\n\t\t\t\tvm_citerator vm_end_it = vms.end();\n\t\t\t\tfor (vm_citerator vm_it = vms.begin();\n\t\t\t\t\t vm_it != vm_end_it;\n\t\t\t\t\t ++vm_it)\n\t\t\t\t{\n\t\t\t\t\tvm_pointer p_vm(*vm_it);\n\n\t\t\t\t\t// check: p_vm != null\n\t\t\t\t\tDCS_DEBUG_ASSERT( p_vm );\n\n\t\t\t\t\tu_(u_offset_+v) = s(v)\n\t\t\t\t\t\t\t\t\t= p_vm->cpu_share()/**p_vm->max_num_vcpus()*/;\n\n\t\t\t\t\t++v;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (ny_ > 0)\n\t\t\t{\n\t\t\t\ty_ = p;\n\t\t\t}\nDCS_DEBUG_TRACE(\"New x=\" << x_);\nDCS_DEBUG_TRACE(\"New u=\" << u_);\nDCS_DEBUG_TRACE(\"New y=\" << y_);\n\n\t\t\t// Estimate system params\n\t\t\tbool ok(true);\n\t\t\tnumeric_vector_type ph;\n\t\t\ttry\n\t\t\t{\n\t\t\t\tph = p_sysid_alg_->estimate(p, s);\nDCS_DEBUG_TRACE(\"RLS estimation:\");//XXX\nDCS_DEBUG_TRACE(\"p=\" << p);//XXX\nDCS_DEBUG_TRACE(\"s=\" << s);//XXX\nDCS_DEBUG_TRACE(\"p_hat=\" << ph);//XXX\nDCS_DEBUG_TRACE(\"Theta_hat=\" << p_sysid_alg_->Theta_hat());//XXX\nDCS_DEBUG_TRACE(\"P=\" << p_sysid_alg_->P());//XXX\nDCS_DEBUG_TRACE(\"phi=\" << p_sysid_alg_->phi());//XXX\n\n\t\t\t\tif (!ublasx::all(ublasx::isfinite(p_sysid_alg_->Theta_hat())))\n\t\t\t\t{\n\t\t\t\t\t::std::ostringstream oss;\n\t\t\t\t\toss << \"Unable to estimate system parameters: infinite values in system parameters\";\n\t\t\t\t\t::dcs::log_warn(DCS_LOGGING_AT, oss.str());\n\n\t\t\t\t\tok = false;\n\t\t\t\t}\n\t\t\t}\n\t\t\tcatch (::std::exception const& e)\n\t\t\t{\n\t\t\t\tDCS_DEBUG_TRACE( \"Caught exception: \" << e.what() );\n\n\t\t\t\t::std::ostringstream oss;\n\t\t\t\toss << \"Unable to estimate system parameters: \" << e.what();\n\t\t\t\t::dcs::log_warn(DCS_LOGGING_AT, oss.str());\n\n\t\t\t\tok = false;\n\t\t\t}\n\n\t\t\tif (ok && p_sysid_alg_->count() >= (na+nb+nk))\n\t\t\t{\n\t\t\t\t// Create the state-space representation of the system model:\n\t\t\t\t// x(k+1) = Ax(k)+Bu(k)\n\t\t\t\t// y(k)   = Cx(k)+Du(k)\n\n\t\t\t\tnumeric_matrix_type A;\n\t\t\t\tnumeric_matrix_type B;\n\t\t\t\tnumeric_matrix_type C;\n\t\t\t\tnumeric_matrix_type D;\n\n\t\t\t\tdetail::make_ss(*p_sysid_alg_, A, B, C, D);\nDCS_DEBUG_TRACE(\"State-space System - Matrix A: \" << A);\nDCS_DEBUG_TRACE(\"State-space System - Matrix B: \" << B);\nDCS_DEBUG_TRACE(\"State-space System - Matrix C: \" << C);\nDCS_DEBUG_TRACE(\"State-space System - Matrix D: \" << D);\n\n\t\t\t\tnumeric_vector_type opt_u;\n\t\t\t\ttry\n\t\t\t\t{\n                    // Check on B(1) suggested by Karlsson et al \"Dynamic Black-Box Performance Model Estimation for Self-Tuning Regulators\", 2005\n                    // This essentially consider the model as a linear model where u(k) is the free variabile.\n                    // They compute the first partial derivative wrt to u(k) which gives the matrix B(1).\n                    // In order to preverse reverse proportionality ==> diag(B(1)) < 0\n\t\t\t\t\tif (ublasx::any(p_sysid_alg_->B(1), ::std::bind2nd(::std::greater_equal<real_type>(), 0)))\n\t\t\t\t\t{\n#ifdef DCS_TESTBED_EXP_LQ_APP_MGR_USE_ARX_B0_SIGN_HEURISTIC\n\t\t\t\t\t\tDCS_EXCEPTION_THROW( ::std::runtime_error, \"Cannot compute optimal control input: First partial derivative of input-output model has positive elements on the main diagonal\" );\n#else // DCS_TESTBED_EXP_LQ_APP_MGR_USE_ARX_B0_SIGN_HEURISTIC\n\t\t\t\t\t\tdcs::log_warn(DCS_LOGGING_AT, \"First partial derivative of input-output model has positive elements on the main diagonal\");\n#endif // DCS_TESTBED_EXP_LQ_APP_MGR_USE_ARX_B0_SIGN_HEURISTIC\n\t\t\t\t\t}\n\n\t\t\t\t\topt_u = this->lq_control(A, B, C, D);\n\t\t\t\t}\n\t\t\t\tcatch (::std::exception const& e)\n\t\t\t\t{\n\t\t\t\t\tDCS_DEBUG_TRACE( \"Caught exception: \" << e.what() );\n\n\t\t\t\t\t::std::ostringstream oss;\n\t\t\t\t\toss << \"Unable to compute optimal control: \" << e.what();\n\t\t\t\t\t::dcs::log_warn(DCS_LOGGING_AT, oss.str());\n\n\t\t\t\t\tok = false;\n\t\t\t\t}\n\n\t\t\t\tif (ok)\n\t\t\t\t{\nDCS_DEBUG_TRACE(\"Applying optimal control\");\n\t\t\t\t\t//FIXME: new share should be scaled according to the capacity of the \"real\" machine\n\t\t\t\t\t//FIXME: implement the Physical Machine Manager\n\n\t\t\t\t\tif (ublasx::all(ublas::subrange(opt_u, u_offset_, vms.size()), ::std::bind2nd(::std::greater_equal<real_type>(), 0)))\n\t\t\t\t\t{\n\t\t\t\t\t\t::std::size_t v(0);\n\t\t\t\t\t\tvm_iterator vm_end_it = vms.end();\n\t\t\t\t\t\tfor (vm_iterator vm_it = vms.begin();\n\t\t\t\t\t\t\t vm_it != vm_end_it;\n\t\t\t\t\t\t\t ++vm_it)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tvm_pointer p_vm(*vm_it);\n\n\t\t\t\t\t\t\t// check: p_vm != null\n\t\t\t\t\t\t\tDCS_DEBUG_ASSERT( p_vm );\n\n\t\t\t\t\t\t\treal_type new_share = opt_u(u_offset_+v);\n\n\t\t\t\t\t\t\tif (::dcs::math::float_traits<real_type>::definitely_less(new_share, default_min_share))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t::std::ostringstream oss;\n\t\t\t\t\t\t\t\toss << \"Optimal share (\" << new_share << \") too small; adjusted to \" << default_min_share;\n\t\t\t\t\t\t\t\t::dcs::log_warn(DCS_LOGGING_AT, oss.str());\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (::dcs::math::float_traits<real_type>::definitely_greater(new_share, default_max_share))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t::std::ostringstream oss;\n\t\t\t\t\t\t\t\toss << \"Optimal share (\" << new_share << \") too big; adjusted to \" << default_max_share;\n\t\t\t\t\t\t\t\t::dcs::log_warn(DCS_LOGGING_AT, oss.str());\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tnew_share = ::std::min(::std::max(new_share, default_min_share), default_max_share);\n\t\t\t\t\t\t\tconst real_type old_share = p_vm->cpu_share();\n\nDCS_DEBUG_TRACE(\"VM '\" << p_vm->id() << \"' - old-share: \" << old_share << \" - new-share: \" << new_share);\n\t\t\t\t\t\t\tif (::std::isfinite(new_share) && !::dcs::math::float_traits<real_type>::essentially_equal(new_share, old_share))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tp_vm->cpu_share(new_share);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t++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\t++ctl_fail_count_;\n\n\t\t\t\t\t\t::std::ostringstream oss;\n\t\t\t\t\t\toss << \"Control not applied: computed negative share for at least one VM\";\n\t\t\t\t\t\t::dcs::log_warn(DCS_LOGGING_AT, oss.str());\n\n\t\t\t\t\t\tok = false;\n\t\t\t\t\t}\nDCS_DEBUG_TRACE(\"Optimal control applied\");\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t++ctl_fail_count_;\n\n\t\t\t\t\t::std::ostringstream oss;\n\t\t\t\t\toss << \"Control not applied: failed to solve the control problem\";\n\t\t\t\t\t::dcs::log_warn(DCS_LOGGING_AT, oss.str());\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (!ok)\n\t\t\t{\n\t\t\t\tp_sysid_alg_->reset();\n\t\t\t\t++sysid_fail_count_;\n\n\t\t\t\t::std::ostringstream oss;\n\t\t\t\toss << \"Control not applied: failed to solve the identification problem\";\n\t\t\t\t::dcs::log_warn(DCS_LOGGING_AT, oss.str());\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\t++ctl_skip_count_;\n\t\t}\n\n\t\t// Reset measures\n\t\tout_obs_map_.clear();\n\n\t\tDCS_DEBUG_TRACE(\"(\" << this << \") END Do CONTROL - Count: \" << ctl_count_ << \"/\" << ctl_skip_count_ << \"/\" << sysid_fail_count_ << \"/\" << ctl_fail_count_);\n\t}\n\n\tprivate: virtual numeric_vector_type do_lq_control(numeric_matrix_type const& A,\n\t\t\t\t\t\t\t\t\t\t\t\t\t   numeric_matrix_type const& B,\n\t\t\t\t\t\t\t\t\t\t\t\t\t   numeric_matrix_type const& C,\n\t\t\t\t\t\t\t\t\t\t\t\t\t   numeric_matrix_type const& D) = 0;\n\n\n\tprivate: uint_type ts_; ///< Sampling time (in ms)\n\tprivate: uint_type tc_; ///< Control time (in ms)\n\tprivate: app_pointer p_app_; ///< Pointer to the managed application\n\tprivate: sensor_map out_sens_map_; ///< Sensor map for the application outputs\n\tprivate: sysid_strategy_pointer p_sysid_alg_;\n\tprivate: observation_map out_obs_map_; ///< Application output observations collected in the last control interval\n\tprivate: ::std::size_t nx_; ///< Number of states\n\tprivate: ::std::size_t nu_; ///< Number of inputs\n\tprivate: ::std::size_t ny_; ///< Number of outputs\n\tprivate: ::std::size_t x_offset_; ///< Offset used to rotate the state vector to make space for new observations\n\tprivate: ::std::size_t u_offset_; ///< Offset used to rotate the input vector to make space for new observations\n\tprivate: numeric_vector_type x_; ///< The state vector for the state-space representation\n\tprivate: numeric_vector_type u_; ///< The input vector for the state-space representation\n\tprivate: numeric_vector_type y_; ///< The output vector for the state-space representation\n\tprivate: numeric_vector_type yr_; ///< The output vector to be tracked \n\tprivate: ::std::size_t ctl_count_; ///< Number of times control function has been invoked\n\tprivate: ::std::size_t ctl_skip_count_; ///< Number of times control has been skipped\n\tprivate: ::std::size_t ctl_fail_count_; ///< Number of times control has failed\n\tprivate: ::std::size_t sysid_fail_count_; ///< Number of times system identification has failed\n\tprivate: real_type ewma_sf_; ///< EWMA smoothing factor\n\tprivate: numeric_vector_type ewma_s_; ///< Current EWMA values for inputs\n\tprivate: numeric_vector_type ewma_p_; ///< Current EWMA values for outputs\n\tprivate: target_map tgt_map_; ///< Mapping between application performance categories and target values\n}; // lq_application_manager\n\ntemplate <typename T>\nconst typename lq_application_manager<T>::uint_type lq_application_manager<T>::default_sampling_time = 1;\n\ntemplate <typename T>\nconst typename lq_application_manager<T>::uint_type lq_application_manager<T>::default_control_time = 5;\n\ntemplate <typename T>\nconst typename lq_application_manager<T>::real_type lq_application_manager<T>::default_min_share = 0.20;\n\ntemplate <typename T>\nconst typename lq_application_manager<T>::real_type lq_application_manager<T>::default_max_share = 1.00;\n\ntemplate <typename T>\nconst typename lq_application_manager<T>::real_type lq_application_manager<T>::default_ewma_smoothing_factor = 0.70;\n\n\ntemplate <typename TraitsT>\nclass lqry_application_manager: public lq_application_manager<TraitsT>\n{\n\tprivate: typedef lq_application_manager<TraitsT> base_type;\n\tpublic: typedef typename base_type::traits_type traits_type;\n\tprivate: typedef typename traits_type::real_type real_type;\n\tprivate: typedef typename traits_type::uint_type uint_type;\n\tprivate: typedef ::dcs::control::dlqry_controller<real_type> lq_controller_type;\n\tprivate: typedef typename base_type::numeric_vector_type numeric_vector_type;\n\tprivate: typedef typename base_type::numeric_matrix_type numeric_matrix_type;\n\n\n\tpublic: lqry_application_manager()\n\t{\n\t}\n\n\tpublic: template <typename QMatrixExprT, typename RMatrixExprT>\n\t\t\tlqry_application_manager(::boost::numeric::ublas::matrix_expression<QMatrixExprT> const& Q,\n\t\t\t\t\t\t\t\t\t ::boost::numeric::ublas::matrix_expression<RMatrixExprT> const& R)\n\t: ctlr_(Q,R)\n\t{\n\t}\n\n\tprivate: numeric_vector_type do_lq_control(numeric_matrix_type const& A,\n\t\t\t\t\t\t\t\t\t\t\t   numeric_matrix_type const& B,\n\t\t\t\t\t\t\t\t\t\t\t   numeric_matrix_type const& C,\n\t\t\t\t\t\t\t\t\t\t\t   numeric_matrix_type const& D)\n\t{\n\t\tnamespace ublas = ::boost::numeric::ublas;\n\t\tnamespace ublasx = ::boost::numeric::ublasx;\n\n\t\t// Check: if (A,B) is stabilizable, then the assoicated DARE has a\n\t\t//        positive semidefinite solution.\n\t\t//        (sufficient and necessary condition)\n\t\tif (!::dcs::control::is_stabilizable(A, B, true))\n\t\t{\n\t\t\t::std::ostringstream oss;\n\t\t\toss << \"System (A,B) is not stabilizable (the associated DARE cannot have a positive semidefinite solution) [with A=\" << A << \" and B=\" << B << \"]\";\n\t\t\t::dcs::log_warn(DCS_LOGGING_AT, oss.str());\n\n\t\t\tDCS_EXCEPTION_THROW(::std::runtime_error, oss.str());\n\t\t}\n\t\t// Check: if (A,B) stabilizable and (C'QC,A) detectable, then the\n\t\t//        associated DARE has a unique and stabilizing solution such\n\t\t//        that the closed-loop system:\n\t\t//          x(k+1) = Ax(k) + Bu(k) = (A + BK)x(k)\n\t\t//        is stable (K is the LQRY-optimal state feedback gain).\n\t\t//        (sufficient and necessary condition)\n\t\tnumeric_matrix_type QQ(ublas::prod(ctlr_.Q(), C));\n\t\tQQ = ublas::prod(ublas::trans(C), QQ);\n\t\tif (!::dcs::control::is_detectable(A, QQ, true))\n\t\t{\n\t\t\t::std::ostringstream oss;\n\t\t\toss << \"System (C'QC,A) is not detectable (closed-loop system will not be stable) [with \" << A << \", Q=\" << ctlr_.Q() << \" and C=\" << C << \"]\";\n\t\t\t::dcs::log_warn(DCS_LOGGING_AT, oss.str());\n\n\t\t\tDCS_EXCEPTION_THROW(::std::runtime_error, oss.str());\n\t\t}\n\n\t\tuint_type nx(ublas::num_columns(A));\n\t\tuint_type nu(ublas::num_columns(B));\n\t\tuint_type ny(ublas::num_rows(C));\n\t\tnumeric_vector_type r(ny, 1);//FIXME\n\n\t\tnumeric_vector_type opt_u;\n\n\t\tctlr_.solve(A, B, C, D);\n\t\topt_u = ublas::real(ctlr_.control(this->state_vector()));\n\n#ifdef DCS_TESTBED_EXP_LQ_APP_MGR_USE_COMPENSATION\n\t\tuint_type ncp(nx+nu);\n\t\tuint_type nrp(nx+ny);\n\n\t\tnumeric_matrix_type P(nrp, ncp, 0);\n\t\tublas::subrange(P, 0, nx, 0, nx) = ublas::identity_matrix<real_type>(nx, nx) - A;\n\t\tublas::subrange(P, 0, nx, nx, ncp) = B;\n\t\tublas::subrange(P, nx, nrp, 0, nx) = -C;\n\t\tublas::subrange(P, nx, nrp, nx, ncp) = D;\n\t\tnumeric_matrix_type Pt(ublas::trans(P));\n\t\tnumeric_matrix_type PP(ublas::prod(P, Pt));\n\t\tbool inv = ublasx::inv_inplace(PP);\n\t\tif (inv)\n\t\t{\n\t\t\tPP = ublas::prod(Pt, PP);\n\t\t\tnumeric_vector_type yd(nrp,0);\n\t\t\tublas::subrange(yd, nx, nrp) = r;\n\t\t\tnumeric_vector_type xdud(ublas::prod(PP, yd));\n\t\t\tDCS_DEBUG_TRACE(\"COMPENSATION: P=\" << P << \" ==> (xd,ud)=\" << xdud << \", opt_u=\" << opt_u);//XXX\n\t\t\topt_u = opt_u + ublas::subrange(xdud, nx, ncp);\n\t\t\tDCS_DEBUG_TRACE(\"COMPENSATION: P=\" << P << \" ==> (xd,ud)=\" << xdud << \", NEW opt_u=\" << opt_u);//XXX\n\t\t}\n\t\telse\n\t\t{\n\t\t\tDCS_EXCEPTION_THROW( ::std::runtime_error, \"Cannot compute equilibrium control input: Rosenbrock's system matrix is not invertible\" );\n\t\t}\n#endif // DCS_TESTBED_EXP_LQ_APP_MGR_USE_COMPENSATION\n\n\t\treturn opt_u;\n\t}\n\n\n\tprivate: lq_controller_type ctlr_;\n}; // lqry_application_manager\n\n}} // Namespace dcs::testbed\n\n#endif // DCS_TESTBED_LQ_SYSTEM_MANAGER_HPP\n", "meta": {"hexsha": "d61f65b735b33cee350c8f6d1b8234607ab20925", "size": 58473, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "inc/dcs/testbed/lq_application_manager.hpp", "max_stars_repo_name": "sguazt/dcsxx-testbed", "max_stars_repo_head_hexsha": "e7210f0c7f54256d5bf0c90297e0c4f9eaf82da0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "inc/dcs/testbed/lq_application_manager.hpp", "max_issues_repo_name": "sguazt/dcsxx-testbed", "max_issues_repo_head_hexsha": "e7210f0c7f54256d5bf0c90297e0c4f9eaf82da0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "inc/dcs/testbed/lq_application_manager.hpp", "max_forks_repo_name": "sguazt/dcsxx-testbed", "max_forks_repo_head_hexsha": "e7210f0c7f54256d5bf0c90297e0c4f9eaf82da0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5665901263, "max_line_length": 181, "alphanum_fraction": 0.6218938655, "num_tokens": 19379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.45617593681338403}}
{"text": "/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n * Copyright 2012 The MITRE Corporation                                      *\n *                                                                           *\n * Licensed under the Apache License, Version 2.0 (the \"License\");           *\n * you may not use this file except in compliance with the License.          *\n * You may obtain a copy of the License at                                   *\n *                                                                           *\n *     http://www.apache.org/licenses/LICENSE-2.0                            *\n *                                                                           *\n * Unless required by applicable law or agreed to in writing, software       *\n * distributed under the License is distributed on an \"AS IS\" BASIS,         *\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  *\n * See the License for the specific language governing permissions and       *\n * limitations under the License.                                            *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\n#include <Eigen/Dense>\n\n#include \"openbr_internal.h\"\n\n#include \"openbr/core/common.h\"\n#include \"openbr/core/eigenutils.h\"\n#include \"openbr/core/opencvutils.h\"\n\nnamespace br\n{\n\n/*!\n * \\ingroup initializers\n * \\brief Initialize Eigen\n * http://eigen.tuxfamily.org/dox/TopicMultiThreading.html\n * \\author Scott Klum \\cite sklum\n */\nclass EigenInitializer : public Initializer\n{\n    Q_OBJECT\n\n    void initialize() const\n    {\n        Eigen::initParallel();\n    }\n};\n\nBR_REGISTER(Initializer, EigenInitializer)\n\n/*!\n * \\ingroup transforms\n * \\brief Projects input into learned Principal Component Analysis subspace.\n * \\author Brendan Klare \\cite bklare\n * \\author Josh Klontz \\cite jklontz\n */\nclass PCATransform : public Transform\n{\n    Q_OBJECT\n    friend class DFFSTransform;\n    friend class LDATransform;\n\nprotected:\n    Q_PROPERTY(float keep READ get_keep WRITE set_keep RESET reset_keep STORED false)\n    Q_PROPERTY(int drop READ get_drop WRITE set_drop RESET reset_drop STORED false)\n    Q_PROPERTY(bool whiten READ get_whiten WRITE set_whiten RESET reset_whiten STORED false)\n\n    /*!\n     *     keep <  0: All eigenvalues are retained.\n     *     keep =  0: No PCA performed, eigenvectors form an identity matrix.\n     * 0 < keep <  1: Fraction of the variance to retain.\n     *     keep >= 1: Number of leading eigenvectors to retain.\n     */\n    BR_PROPERTY(float, keep, 0.95)\n    BR_PROPERTY(int, drop, 0)\n    BR_PROPERTY(bool, whiten, false)\n\n    Eigen::VectorXf mean, eVals;\n    Eigen::MatrixXf eVecs;\n\n    int originalRows;\n\npublic:\n    PCATransform() : keep(0.95), drop(0), whiten(false) {}\n\nprivate:\n    double residualReconstructionError(const Template &src) const\n    {\n        Template proj;\n        project(src, proj);\n\n        Eigen::Map<const Eigen::VectorXf> srcMap(src.m().ptr<float>(), src.m().rows*src.m().cols);\n        Eigen::Map<Eigen::VectorXf> projMap(proj.m().ptr<float>(), keep);\n\n        return (srcMap - mean).squaredNorm() - projMap.squaredNorm();\n    }\n\n    void train(const TemplateList &trainingSet)\n    {\n        if (trainingSet.first().m().type() != CV_32FC1)\n            qFatal(\"Requires single channel 32-bit floating point matrices.\");\n\n        originalRows = trainingSet.first().m().rows;\n        int dimsIn = trainingSet.first().m().rows * trainingSet.first().m().cols;\n        const int instances = trainingSet.size();\n\n        // Map into 64-bit Eigen matrix\n        Eigen::MatrixXd data(dimsIn, instances);\n        for (int i=0; i<instances; i++)\n            data.col(i) = Eigen::Map<const Eigen::MatrixXf>(trainingSet[i].m().ptr<float>(), dimsIn, 1).cast<double>();\n\n        trainCore(data);\n    }\n\n    void project(const Template &src, Template &dst) const\n    {\n        dst = cv::Mat(1, keep, CV_32FC1);\n\n        // Map Eigen into OpenCV\n        Eigen::Map<const Eigen::MatrixXf> inMap(src.m().ptr<float>(), src.m().rows*src.m().cols, 1);\n        Eigen::Map<Eigen::MatrixXf> outMap(dst.m().ptr<float>(), keep, 1);\n\n        // Do projection\n        outMap = eVecs.transpose() * (inMap - mean);\n    }\n\n    void store(QDataStream &stream) const\n    {\n        stream << keep << drop << whiten << originalRows << mean << eVals << eVecs;\n    }\n\n    void load(QDataStream &stream)\n    {\n        stream >> keep >> drop >> whiten >> originalRows >> mean >> eVals >> eVecs;\n    }\n\nprotected:\n    void trainCore(Eigen::MatrixXd data)\n    {\n        int dimsIn = data.rows();\n        int instances = data.cols();\n        const bool dominantEigenEstimation = (dimsIn > instances);\n\n        Eigen::MatrixXd allEVals, allEVecs;\n        if (keep != 0) {\n            // Compute and remove mean\n            mean = Eigen::VectorXf(dimsIn);\n            for (int i=0; i<dimsIn; i++) mean(i) = data.row(i).sum() / (float)instances;\n            for (int i=0; i<dimsIn; i++) data.row(i).array() -= mean(i);\n\n            // Calculate covariance matrix\n            Eigen::MatrixXd cov;\n            if (dominantEigenEstimation) cov = data.transpose() * data / (instances-1.0);\n            else                         cov = data * data.transpose() / (instances-1.0);\n\n            // Compute eigendecomposition. Returns eigenvectors/eigenvalues in increasing order by eigenvalue.\n            Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> eSolver(cov);\n            allEVals = eSolver.eigenvalues();\n            allEVecs = eSolver.eigenvectors();\n            if (dominantEigenEstimation) allEVecs = data * allEVecs;\n        } else {\n            // Null case\n            mean = Eigen::VectorXf::Zero(dimsIn);\n            allEVecs = Eigen::MatrixXd::Identity(dimsIn, dimsIn);\n            allEVals = Eigen::VectorXd::Ones(dimsIn);\n        }\n\n        if (keep <= 0) {\n            keep = dimsIn - drop;\n        } else if (keep < 1) {\n            // Keep eigenvectors that retain a certain energy percentage.\n            const double totalEnergy = allEVals.sum();\n            if (totalEnergy == 0) {\n                keep = 0;\n            } else {\n                double currentEnergy = 0;\n                int i=0;\n                while ((currentEnergy / totalEnergy < keep) && (i < allEVals.rows())) {\n                    currentEnergy += allEVals(allEVals.rows()-(i+1));\n                    i++;\n                }\n                keep = i - drop;\n            }\n        } else {\n            if (keep + drop > allEVals.rows())\n                qFatal(\"Insufficient samples, needed at least %d but only got %d.\", (int)keep + drop, (int)allEVals.rows());\n        }\n\n        // Keep highest energy vectors\n        eVals = Eigen::VectorXf((int)keep, 1);\n        eVecs = Eigen::MatrixXf(allEVecs.rows(), (int)keep);\n        for (int i=0; i<keep; i++) {\n            int index = allEVals.rows()-(i+drop+1);\n            eVals(i) = allEVals(index);\n            eVecs.col(i) = allEVecs.col(index).cast<float>() / allEVecs.col(index).norm();\n            if (whiten) eVecs.col(i) /= sqrt(eVals(i));\n        }\n\n        // Debug output\n        if (Globals->verbose) qDebug() << \"PCA Training:\\n\\tDimsIn =\" << dimsIn << \"\\n\\tKeep =\" << keep;\n    }\n\n    void writeEigenVectors(const Eigen::MatrixXd &allEVals, const Eigen::MatrixXd &allEVecs) const\n    {\n        const int originalCols = mean.rows() / originalRows;\n\n        { // Write out mean image\n            cv::Mat out(originalRows, originalCols, CV_32FC1);\n            Eigen::Map<Eigen::MatrixXf> outMap(out.ptr<float>(), mean.rows(), 1);\n            outMap = mean.col(0);\n            // OpenCVUtils::saveImage(out, Globals->Debug+\"/PCA/eigenVectors/mean.png\");\n        }\n\n        // Write out sample eigen vectors (16 highest, 8 lowest), filename = eigenvalue.\n        for (int k=0; k<(int)allEVals.size(); k++) {\n            if ((k < 8) || (k >= (int)allEVals.size()-16)) {\n                cv::Mat out(originalRows, originalCols, CV_64FC1);\n                Eigen::Map<Eigen::MatrixXd> outMap(out.ptr<double>(), mean.rows(), 1);\n                outMap = allEVecs.col(k);\n                // OpenCVUtils::saveImage(out, Globals->Debug+\"/PCA/eigenVectors/\"+QString::number(allEVals(k),'f',0)+\".png\");\n            }\n        }\n    }\n};\n\nBR_REGISTER(Transform, PCATransform)\n\n/*!\n * \\ingroup transforms\n * \\brief PCA on each row.\n * \\author Josh Klontz \\cite jklontz\n */\nclass RowWisePCATransform : public PCATransform\n{\n    Q_OBJECT\n\n    void train(const TemplateList &trainingSet)\n    {\n        if (trainingSet.first().m().type() != CV_32FC1)\n            qFatal(\"Requires single channel 32-bit floating point matrices.\");\n\n        originalRows = trainingSet.first().m().rows;\n        const int dimsIn = trainingSet.first().m().cols;\n        int instances = 0;\n        foreach (const Template &t, trainingSet)\n            instances += t.m().rows;\n\n        // Map into 64-bit Eigen matrix\n        Eigen::MatrixXd data(dimsIn, instances);\n        int index = 0;\n        foreach (const Template &t, trainingSet)\n            for (int i=0; i<t.m().rows; i++)\n                data.col(index++) = Eigen::Map<const Eigen::MatrixXf>(t.m().ptr<float>(i), dimsIn, 1).cast<double>();\n\n        PCATransform::trainCore(data);\n    }\n\n    void project(const Template &src, Template &dst) const\n    {\n        dst = cv::Mat(src.m().rows, keep, CV_32FC1);\n\n        for (int i=0; i<src.m().rows; i++) {\n            Eigen::Map<const Eigen::MatrixXf> inMap(src.m().ptr<float>(i), src.m().cols, 1);\n            Eigen::Map<Eigen::MatrixXf> outMap(dst.m().ptr<float>(i), keep, 1);\n            outMap = eVecs.transpose() * (inMap - mean);\n        }\n    }\n};\n\nBR_REGISTER(Transform, RowWisePCATransform)\n\n/*!\n * \\ingroup transforms\n * \\brief Computes Distance From Feature Space (DFFS) \\cite moghaddam97.\n * \\author Josh Klontz \\cite jklontz\n */\nclass DFFSTransform : public Transform\n{\n    Q_OBJECT\n    Q_PROPERTY(float keep READ get_keep WRITE set_keep RESET reset_keep STORED false)\n    BR_PROPERTY(float, keep, 0.95)\n\n    PCATransform pca;\n    Transform *cvtFloat;\n\n    void init()\n    {\n        pca.keep = keep;\n        cvtFloat = make(\"CvtFloat\");\n    }\n\n    void train(const TemplateList &data)\n    {\n        pca.train((*cvtFloat)(data));\n    }\n\n    void project(const Template &src, Template &dst) const\n    {\n        dst = src;\n        dst.file.set(\"DFFS\", sqrt(pca.residualReconstructionError((*cvtFloat)(src))));\n    }\n\n    void store(QDataStream &stream) const\n    {\n        pca.store(stream);\n    }\n\n    void load(QDataStream &stream)\n    {\n        pca.load(stream);\n    }\n};\n\nBR_REGISTER(Transform, DFFSTransform)\n\n/*!\n * \\ingroup transforms\n * \\brief Projects input into learned Linear Discriminant Analysis subspace.\n * \\author Brendan Klare \\cite bklare\n * \\author Josh Klontz \\cite jklontz\n */\nclass LDATransform : public Transform\n{\n    friend class SparseLDATransform;\n\n    Q_OBJECT\n    Q_PROPERTY(float pcaKeep READ get_pcaKeep WRITE set_pcaKeep RESET reset_pcaKeep STORED false)\n    Q_PROPERTY(bool pcaWhiten READ get_pcaWhiten WRITE set_pcaWhiten RESET reset_pcaWhiten STORED false)\n    Q_PROPERTY(int directLDA READ get_directLDA WRITE set_directLDA RESET reset_directLDA STORED false)\n    Q_PROPERTY(float directDrop READ get_directDrop WRITE set_directDrop RESET reset_directDrop STORED false)\n    Q_PROPERTY(QString inputVariable READ get_inputVariable WRITE set_inputVariable RESET reset_inputVariable STORED false)\n    Q_PROPERTY(bool isBinary READ get_isBinary WRITE set_isBinary RESET reset_isBinary STORED false)\n    Q_PROPERTY(bool normalize READ get_normalize WRITE set_normalize RESET reset_normalize STORED false)\n    BR_PROPERTY(float, pcaKeep, 0.98)\n    BR_PROPERTY(bool, pcaWhiten, false)\n    BR_PROPERTY(int, directLDA, 0)\n    BR_PROPERTY(float, directDrop, 0.1)\n    BR_PROPERTY(QString, inputVariable, \"Label\")\n    BR_PROPERTY(bool, isBinary, false)\n    BR_PROPERTY(bool, normalize, true)\n\n    int dimsOut;\n    Eigen::VectorXf mean;\n    Eigen::MatrixXf projection;\n    float stdDev;\n\n    void train(const TemplateList &_trainingSet)\n    {\n        // creates \"Label\"\n        TemplateList trainingSet = TemplateList::relabel(_trainingSet, inputVariable, isBinary);\n        int instances = trainingSet.size();\n\n        // Perform PCA dimensionality reduction\n        PCATransform pca;\n        pca.keep = pcaKeep;\n        pca.whiten = pcaWhiten;\n        pca.train(trainingSet);\n        mean = pca.mean;\n\n        TemplateList ldaTrainingSet;\n        static_cast<Transform*>(&pca)->project(trainingSet, ldaTrainingSet);\n\n        int dimsIn = ldaTrainingSet.first().m().rows * ldaTrainingSet.first().m().cols;\n\n        // OpenBR ensures that class values range from 0 to numClasses-1.\n        // Label exists because we created it earlier with relabel\n        QList<int> classes = File::get<int>(trainingSet, \"Label\");\n        QMap<int, int> classCounts = trainingSet.countValues<int>(\"Label\");\n        const int numClasses = classCounts.size();\n\n        // Map Eigen into OpenCV\n        Eigen::MatrixXd data = Eigen::MatrixXd(dimsIn, instances);\n        for (int i=0; i<instances; i++)\n            data.col(i) = Eigen::Map<const Eigen::MatrixXf>(ldaTrainingSet[i].m().ptr<float>(), dimsIn, 1).cast<double>();\n\n        // Removing class means\n        Eigen::MatrixXd classMeans = Eigen::MatrixXd::Zero(dimsIn, numClasses);\n        for (int i=0; i<instances; i++)  classMeans.col(classes[i]) += data.col(i);\n        for (int i=0; i<numClasses; i++) classMeans.col(i) /= classCounts[i];\n        for (int i=0; i<instances; i++)  data.col(i) -= classMeans.col(classes[i]);\n\n        PCATransform space1;\n\n        if (!directLDA)\n        {\n            // The number of LDA dimensions is limited by the degrees\n            // of freedom of scatter matrix computed from 'data'. Because\n            // the mean of each class is removed (lowering degree of freedom\n            // one per class), the total rank of the covariance/scatter\n            // matrix that will be computed in PCA is bound by instances - numClasses.\n            space1.keep = std::min(dimsIn, instances-numClasses);\n            space1.trainCore(data);\n\n            // Divide each eigenvector by sqrt of eigenvalue.\n            // This has the effect of whitening the within-class scatter.\n            // In effect, this minimizes the within-class variation energy.\n            for (int i=0; i<space1.keep; i++) space1.eVecs.col(i) /= pow((double)space1.eVals(i),0.5);\n        }\n        else if (directLDA == 2)\n        {\n            space1.drop = instances - numClasses;\n            space1.keep = std::min(dimsIn, instances) - space1.drop;\n            space1.trainCore(data);\n        }\n        else\n        {\n            // Perform (modified version of) Direct LDA\n\n            // Direct LDA uses to the Null space of the within-class scatter.\n            // Thus, the lower rank, is used to our benefit. We are not discarding\n            // these vectors now (in non-direct code we use the keep parameter\n            // to discard Null space). We keep the Null space b/c this is where\n            // the within-class scatter goes to zero, i.e. it is very useful.\n            space1.keep = dimsIn;\n            space1.trainCore(data);\n\n            if (dimsIn > instances - numClasses) {\n                // Here, we are replacing the eigenvalue of the  null space\n                // eigenvectors with the eigenvalue (divided by 2) of the\n                // smallest eigenvector from the row space eigenvector.\n                // This allows us to scale these null-space vectors (otherwise\n                // it is a divide by zero.\n                double null_eig = space1.eVals(instances - numClasses - 1) / 2;\n                for (int i = instances - numClasses; i < dimsIn; i++)\n                    space1.eVals(i) = null_eig;\n            }\n\n            // Drop the first few leading eigenvectors in the within-class space\n            QList<float> eVal_list; eVal_list.reserve(dimsIn);\n            float fmax = -1;\n            for (int i=0; i<dimsIn; i++) fmax = std::max(fmax, space1.eVals(i));\n            for (int i=0; i<dimsIn; i++) eVal_list.append(space1.eVals(i)/fmax);\n\n            QList<float> dSum = Common::CumSum(eVal_list);\n            int drop_idx;\n            for (drop_idx = 0; drop_idx<dimsIn; drop_idx++)\n                if (dSum[drop_idx]/dSum[dimsIn-1] >= directDrop)\n                    break;\n\n            drop_idx++;\n            space1.keep = dimsIn - drop_idx;\n\n            Eigen::MatrixXf new_vecs = Eigen::MatrixXf(space1.eVecs.rows(), (int)space1.keep);\n            Eigen::MatrixXf new_vals = Eigen::MatrixXf((int)space1.keep, 1);\n\n            for (int i = 0; i < space1.keep; i++) {\n                new_vecs.col(i) = space1.eVecs.col(i + drop_idx);\n                new_vals(i) = space1.eVals(i + drop_idx);\n            }\n\n            space1.eVecs = new_vecs;\n            space1.eVals = new_vals;\n\n            // We will call this \"agressive\" whitening. Really, it is not whitening\n            // anymore. Instead, we are further scaling the small eigenvalues and the\n            // null space eigenvalues (to increase their impact).\n            for (int i=0; i<space1.keep; i++) space1.eVecs.col(i) /= pow((double)space1.eVals(i),0.15);\n        }\n\n        // Now we project the mean class vectors into this second\n        // subspace that minimizes the within-class scatter energy.\n        // Inside this subspace we learn a subspace projection that\n        // maximizes the between-class scatter energy.\n        Eigen::MatrixXd mean2 = Eigen::MatrixXd::Zero(dimsIn, 1);\n\n        // Remove means\n        for (int i=0; i<dimsIn; i++)     mean2(i) = classMeans.row(i).sum() / numClasses;\n        for (int i=0; i<numClasses; i++) classMeans.col(i) -= mean2;\n\n        // Project into second subspace\n        Eigen::MatrixXd data2 = space1.eVecs.transpose().cast<double>() * classMeans;\n\n        // The rank of the between-class scatter matrix is bound by numClasses - 1\n        // because each class is a vector used to compute the covariance,\n        // but one degree of freedom is lost removing the global mean.\n        int dim2 = std::min((int)space1.keep, numClasses-1);\n        PCATransform space2;\n        space2.keep = dim2;\n        space2.trainCore(data2);\n\n        // Compute final projection matrix\n        projection = ((space2.eVecs.transpose() * space1.eVecs.transpose()) * pca.eVecs.transpose()).transpose();\n        dimsOut = dim2;\n\n        stdDev = 1; // default initialize\n        if (isBinary) {\n            assert(dimsOut == 1);\n            float posVal = 0;\n            float negVal = 0;\n            Eigen::MatrixXf results(trainingSet.size(),1);\n            for (int i = 0; i < trainingSet.size(); i++) {\n                Template t;\n                project(trainingSet[i],t);\n                //Note: the positive class is assumed to be 0 b/c it will\n                // typically be the first gallery template in the TemplateList structure\n                if (classes[i] == 0)\n                    posVal += t.m().at<float>(0,0);\n                else if (classes[i] == 1)\n                    negVal += t.m().at<float>(0,0);\n                else\n                    qFatal(\"Binary mode only supports two class problems.\");\n                results(i) = t.m().at<float>(0,0);  //used for normalization\n            }\n            posVal /= classCounts[0];\n            negVal /= classCounts[1];\n\n            if (posVal < negVal) {\n                //Ensure positive value is supposed to be > 0 after projection\n                Eigen::MatrixXf invert = Eigen::MatrixXf::Ones(dimsIn,1);\n                invert *= -1;\n                projection = invert.transpose() * projection;\n            }\n\n            if (normalize)\n                stdDev = sqrt(results.array().square().sum() / trainingSet.size());\n        }\n    }\n\n    void project(const Template &src, Template &dst) const\n    {\n        dst = cv::Mat(1, dimsOut, CV_32FC1);\n\n        // Map Eigen into OpenCV\n        Eigen::Map<Eigen::MatrixXf> inMap((float*)src.m().ptr<float>(), src.m().rows*src.m().cols, 1);\n        Eigen::Map<Eigen::MatrixXf> outMap(dst.m().ptr<float>(), dimsOut, 1);\n\n        // Do projection\n        outMap = projection.transpose() * (inMap - mean);\n        if (normalize && isBinary)\n            dst.m().at<float>(0,0) = dst.m().at<float>(0,0) / stdDev;\n    }\n\n    void store(QDataStream &stream) const\n    {\n        stream << pcaKeep;\n        stream << directLDA;\n        stream << directDrop;\n        stream << dimsOut;\n        stream << mean;\n        stream << projection;\n        if (normalize && isBinary)\n            stream << stdDev;\n    }\n\n    void load(QDataStream &stream)\n    {\n        stream >> pcaKeep;\n        stream >> directLDA;\n        stream >> directDrop;\n        stream >> dimsOut;\n        stream >> mean;\n        stream >> projection;\n        if (normalize && isBinary)\n            stream >> stdDev;\n    }\n};\n\nBR_REGISTER(Transform, LDATransform)\n\n/*!\n * \\ingroup transforms\n * \\brief Projects input into learned Linear Discriminant Analysis subspace\n *          learned on a sparse subset of features with the highest weight\n *          in the original LDA algorithm.\n * \\author Brendan Klare \\cite bklare\n */\nclass SparseLDATransform : public Transform\n{\n    Q_OBJECT\n    Q_PROPERTY(float varThreshold READ get_varThreshold WRITE set_varThreshold RESET reset_varThreshold STORED false)\n    Q_PROPERTY(float pcaKeep READ get_pcaKeep WRITE set_pcaKeep RESET reset_pcaKeep STORED false)\n    Q_PROPERTY(bool normalize READ get_normalize WRITE set_normalize RESET reset_normalize STORED false)\n    BR_PROPERTY(float, varThreshold, 1.5)\n    BR_PROPERTY(float, pcaKeep, 0.98)\n    BR_PROPERTY(bool, normalize, true)\n\n    LDATransform ldaSparse;\n    int dimsOut;\n    QList<int> selections;\n\n    Eigen::VectorXf mean;\n\n    void init()\n    {\n        ldaSparse.init();\n        ldaSparse.pcaKeep = pcaKeep;\n        ldaSparse.inputVariable = \"Label\";\n        ldaSparse.isBinary = true;\n        ldaSparse.normalize = true;\n    }\n\n    void train(const TemplateList &_trainingSet)\n    {\n\n        LDATransform ldaOrig;\n        ldaOrig.init();\n        ldaOrig.inputVariable = \"Label\";\n        ldaOrig.pcaKeep = pcaKeep;\n        ldaOrig.isBinary = true;\n        ldaOrig.normalize = true;\n\n        ldaOrig.train(_trainingSet);\n\n        //Only works on binary class problems for now\n        assert(ldaOrig.projection.cols() == 1);\n        float ldaStd = eigStd(ldaOrig.projection);\n        for (int i = 0; i < ldaOrig.projection.rows(); i++)\n            if (abs(ldaOrig.projection(i)) > varThreshold * ldaStd)\n                selections.append(i);\n\n        TemplateList newSet;\n        for (int i = 0; i < _trainingSet.size(); i++) {\n            cv::Mat x(_trainingSet[i]);\n            cv::Mat y = cv::Mat(selections.size(), 1, CV_32FC1);\n            int idx = 0;\n            int cnt = 0;\n            for (int j = 0; j < x.rows; j++)\n                for (int k = 0; k < x.cols; k++, cnt++)\n                    if (selections.contains(cnt))\n                        y.at<float>(idx++,0) = x.at<float>(j, k);\n            newSet.append(Template(_trainingSet[i].file, y));\n        }\n        ldaSparse.train(newSet);\n        dimsOut = ldaSparse.dimsOut;\n    }\n\n    void project(const Template &src, Template &dst) const\n    {\n        Eigen::Map<Eigen::MatrixXf> inMap((float*)src.m().ptr<float>(), src.m().rows*src.m().cols, 1);\n        Eigen::Map<Eigen::MatrixXf> outMap(dst.m().ptr<float>(), dimsOut, 1);\n\n        int d = selections.size();\n        cv::Mat inSelect(d,1,CV_32F);\n        for (int i = 0; i < d; i++)\n            inSelect.at<float>(i) = src.m().at<float>(selections[i]);\n        ldaSparse.project(Template(src.file, inSelect), dst);\n    }\n\n    void store(QDataStream &stream) const\n    {\n        stream << pcaKeep;\n        stream << ldaSparse;\n        stream << dimsOut;\n        stream << selections;\n    }\n\n    void load(QDataStream &stream)\n    {\n        stream >> pcaKeep;\n        stream >> ldaSparse;\n        stream >> dimsOut;\n        stream >> selections;\n    }\n};\n\nBR_REGISTER(Transform, SparseLDATransform)\n\n/*!\n * \\ingroup distances\n * \\brief L1 distance computed using eigen.\n * \\author Josh Klontz \\cite jklontz\n */\nclass L1Distance : public Distance\n{\n    Q_OBJECT\n\n    float compare(const Template &a, const Template &b) const\n    {\n        const int size = a.m().rows * a.m().cols;\n        Eigen::Map<Eigen::VectorXf> aMap((float*)a.m().data, size);\n        Eigen::Map<Eigen::VectorXf> bMap((float*)b.m().data, size);\n        return (aMap-bMap).cwiseAbs().sum();\n    }\n};\n\nBR_REGISTER(Distance, L1Distance)\n\n/*!\n * \\ingroup distances\n * \\brief L2 distance computed using eigen.\n * \\author Josh Klontz \\cite jklontz\n */\nclass L2Distance : public Distance\n{\n    Q_OBJECT\n\n    float compare(const Template &a, const Template &b) const\n    {\n        const int size = a.m().rows * a.m().cols;\n        Eigen::Map<Eigen::VectorXf> aMap((float*)a.m().data, size);\n        Eigen::Map<Eigen::VectorXf> bMap((float*)b.m().data, size);\n        return (aMap-bMap).squaredNorm();\n    }\n};\n\nBR_REGISTER(Distance, L2Distance)\n\n} // namespace br\n\n#include \"eigen3.moc\"\n", "meta": {"hexsha": "4965d2f0706e53125cb8c5c8700bb469efeec513", "size": 25203, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "openbr/plugins/eigen3.cpp", "max_stars_repo_name": "mrgloom/openbr", "max_stars_repo_head_hexsha": "d13d9b0733c7b6648185d739df99b74cb337756b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-27T13:51:39.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-27T13:51:39.000Z", "max_issues_repo_path": "openbr/plugins/eigen3.cpp", "max_issues_repo_name": "mrgloom/openbr", "max_issues_repo_head_hexsha": "d13d9b0733c7b6648185d739df99b74cb337756b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "openbr/plugins/eigen3.cpp", "max_forks_repo_name": "mrgloom/openbr", "max_forks_repo_head_hexsha": "d13d9b0733c7b6648185d739df99b74cb337756b", "max_forks_repo_licenses": ["Apache-2.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.2112068966, "max_line_length": 126, "alphanum_fraction": 0.584811332, "num_tokens": 6326, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.45617593681338403}}
{"text": "#include \"iri_geometry.h\"\n#include <math.h>\n#include <iostream>\n#include <Eigen/Dense>\n\n// Spoint functions ------------------------------------------\nSpoint::Spoint() : x(0) , y(0),  time_stamp(0) { }\n\nSpoint::Spoint( double x_ , double y_ , double time_stamp_) :\n\t\tx(x_), y(y_), time_stamp(time_stamp_) { }\nSpoint Spoint::operator+ (Spoint p2) const\n{\n\treturn Spoint(  x + p2.x , y + p2.y , time_stamp );\n}\nSpoint Spoint::operator- (Spoint p2) const\n{\n\treturn Spoint(  x - p2.x , y - p2.y , time_stamp);\n}\nSpoint Spoint::operator* (double k) const\n{\n\treturn Spoint(  x *k , y *k , time_stamp);\n}\ndouble Spoint::distance(Spoint p2) const\n{\n\treturn sqrt( distance2(p2)  );\n}\ndouble Spoint::distance2(Spoint p2) const\n{\n\treturn (x-p2.x)*(x-p2.x) + (y-p2.y)*(y-p2.y);\n}\nSpoint Spoint::propagate( double dt , Sforce f, double desired_velocity) const\n{\n\treturn *this;\n}\nvoid Spoint::print() const\n{\n\tstd::cout << \"(x , y ,t) = (\" << x << \" , \" << y  << \" | \" << time_stamp << \" )\" << std::endl;\n}\n\n//Spoint_cov methods -----------------------------------------------------------\nSpoint_cov::Spoint_cov():\n\t\tSpoint()\n{\n\tcov.reserve(4);\n\tcov.resize(4,0.0);\n\tcov[0] = 1.0;\n\tcov[3] = 1.0;\n}\nSpoint_cov::Spoint_cov( double x_ , double y_ , double time_stamp_,\n\t\tconst std::vector<double>& cov_ ):\n\t\tSpoint( x_,y_,time_stamp_ )\n{\n\tif ( cov_.empty() || cov_.size() < (std::size_t) 4 )\n\t{\n\t\tcov.reserve(4);\n\t\tcov.resize(4,0.0);\n\t\tcov[0] = 1.0;\n\t\tcov[3] = 1.0;\n\t}\n\telse\n\t{\n\t\tcov = cov_;\n\t}\n}\ndouble Spoint_cov::cov_dist( Spoint p2 ) const\n{\n\t//analitical inversion of the 2x2 matrix\n\t//       det =   cov_xx * cov_yy - cov_xy * cov_xy\n\tdouble cov_det = cov[0] * cov[3] - cov[1] * cov[2];\n\tdouble dx = x - p2.x;\n\tdouble dy = y - p2.y;\n\treturn ( dx*dx*cov[3] - 2*dx*dy*cov[1] + dy*dy*cov[0] )/cov_det;\n}\nSpoint_cov Spoint_cov::operator+ (Spoint_cov p2) const\n{\n    return Spoint_cov(  x + p2.x , y + p2.y , time_stamp , cov);\n}\nSpoint_cov Spoint_cov::operator- (Spoint_cov p2) const\n{\n    return Spoint_cov(  x - p2.x , y - p2.y , time_stamp , cov);\n}\nSpoint_cov Spoint_cov::operator* (double k) const\n{\n    return Spoint_cov(  x*k , y*k , time_stamp , cov);\n}\ndouble Spoint_cov::cov_xx() const\n{\n\treturn cov[0];\n}\ndouble Spoint_cov::cov_yy() const\n{\n\treturn cov[3];\n}\ndouble Spoint_cov::cov_xy() const\n{\n\treturn cov[1];\n}\nvoid Spoint_cov::print() const\n{\n    Spoint::print();\n    std::cout << \"cov = [\" << cov[0] << \" , \" << cov[1] << std::endl;\n    std::cout << \"       \" << cov[2] << \" , \" << cov[3] << \" ]\" << std::endl;\n}\n\n//SpointV methods -----------------------------------------------------------\nSpointV::SpointV() : Spoint(), vx(0), vy(0) { }\n\nSpointV::SpointV( double x_ , double y_, double time_stamp_, double vx_, double vy_ ) :\n\t\tSpoint(x_,y_,time_stamp_), vx(vx_),vy(vy_) { }\nSpointV SpointV::operator+ (SpointV p2) const\n{\n\treturn SpointV(  x + p2.x , y + p2.y , time_stamp,  vx + p2.vx , vy + p2.vy );\n}\nSpointV SpointV::operator- (SpointV p2) const\n{\n\treturn SpointV(  x - p2.x , y - p2.y , time_stamp-p2.time_stamp,  vx - p2.vx , vy - p2.vy );\n}\nSpointV SpointV::operator* ( double k) const\n{\n\treturn SpointV(  x * k , y * k, time_stamp,  vx * k , vy * k );\n}\nvoid SpointV::print() const\n{\n\tstd::cout << \"(x , y ,t) = (\" << x << \" , \" << y  << \" | \" << time_stamp << \" )\" <<\n\t\t\t\"     (vx,vy) = ( \" << vx << \" , \" << vy << \" )\" << std::endl;\n}\nSpointV SpointV::propagate( double dt , Sforce f, double desired_velocity) const\n{\n\t//linear propagation (uniformly accelerated system)\n\tdouble vxn = vx + f.fx*dt;\n\tdouble vyn = vy + f.fy*dt;\n\tdouble dx = vx*dt + f.fx*dt*dt*0.5;\n\tdouble dy = vy*dt + f.fy*dt*dt*0.5;\n\n\t//apply constrains:\n\tdouble v = sqrt( vxn*vxn + vyn*vyn );\n\tif ( v > desired_velocity)\n\t{\n\t\tvxn *= desired_velocity /v;\n\t\tvyn *= desired_velocity /v;\n\t\tdx = vxn*dt;\n\t\tdy = vyn*dt;\n\t}\n\n\treturn SpointV( x+dx,y+dy, time_stamp+dt, vxn, vyn);\n}\ndouble SpointV::orientation() const\n{\n\treturn atan2( vy, vx );\n}\n\ndouble SpointV::v() const\n{\n\treturn sqrt( vy*vy + vx*vx );\n}\n\nvoid SpointV::norm_v(double v)\n{\n\tdouble theta = this->orientation();\n\tvx = cos(theta)*v;\n\tvy = sin(theta)*v;\n}\n\ndouble SpointV::angle_heading_point( Spoint p2 ) const\n{\n\tdouble dx = p2.x - x;\n\tdouble dy = p2.y - y;\n\treturn diffangle( atan2( dy , dx ), orientation() );\n}\n\n//SpointV_cov methods -----------------------------------------------------------\nSpointV_cov::SpointV_cov() :\n\t\tSpointV()\n{\n\tcov.reserve(16);\n\tcov.resize(16,0.0);\n\tcov[0] = 0.4;\n\tcov[5] = 0.4;\n\tcov[10] = 0.1;\n\tcov[15] = 0.1;\n}\nSpointV_cov::SpointV_cov(double x_ , double y_, double time_stamp_, double vx_, double vy_,\n\t\tconst std::vector<double>& cov_) :\n\t\tSpointV(x_,y_,time_stamp_,vx_,vy_)\n{\n\tif ( cov_.empty() || cov_.size() < (std::size_t) 16 )\n\t{\n\t\tcov.reserve(16);\n\t\tcov.resize(16,0.0);\n\t\tcov[0] = 0.4;\n\t\tcov[5] = 0.4;\n\t\tcov[10] = 0.1;\n\t\tcov[15] = 0.1;\n\t}\n\telse\n\t{\n\t\tcov = cov_;\n\t}\n}\nSpointV_cov::SpointV_cov(SpointV p, const std::vector<double>& cov_) :\n\t\tSpointV( p.x , p.y, p.time_stamp, p.vx, p.vy)\n{\n\tif ( cov_.empty() || cov_.size() < (std::size_t) 16 )\n\t{\n\t\tcov.reserve(16);\n\t\tcov.resize(16,0.0);\n\t\tcov[0] = 0.4;\n\t\tcov[5] = 0.4;\n\t\tcov[10] = 0.1;\n\t\tcov[15] = 0.1;\n\t}\n\telse\n\t{\n\t\tcov = cov_;\n\t}\n}\nSpointV_cov::SpointV_cov(Spoint_cov p ):\n\t\tSpointV( p.x , p.y, p.time_stamp, 0.0, 0.0)\n{\n\tcov.reserve(16);\n\tcov.resize(16,0.0);\n\tcov[0] = p.cov[0];\n\tcov[1] = p.cov[1];\n\tcov[4] = p.cov[2];\n\tcov[5] = p.cov[3];\n\tcov[10] = 0.1;\n\tcov[15] = 0.1;\n}\n\ndouble SpointV_cov::cov_dist( Spoint p2 ) const\n{\n\t// TODO: consider velocities, right now is a covariance distance of positions\n\t//       det =   cov_xx * cov_yy - cov_xy * cov_xy\n\tdouble cov_det = cov[0] * cov[5] - cov[1] * cov[4];\n\tdouble dx = x - p2.x;\n\tdouble dy = y - p2.y;\n\t//\n\treturn ( dx*dx*cov[5] - 2*dx*dy*cov[1] + dy*dy*cov[0] )/cov_det;\n}\ndouble SpointV_cov::cov_dist( Spoint p2 , double &det) const\n{\n\tdet = cov[0] * cov[5] - cov[1] * cov[4];\n\tdouble dx = x - p2.x;\n\tdouble dy = y - p2.y;\n\treturn ( dx*dx*cov[5] - 2*dx*dy*cov[1] + dy*dy*cov[0] )/det;\n}\n\ndouble SpointV_cov::cov_distV( SpointV_cov p2, double &distV, double &distxv ) const\n{\n\t// TODO: consider velocities, right now is a covariance distance of positions\n\t//       det =   cov_xx * cov_yy - cov_xy * cov_xy\n\t// SpointV_cov external for actual track, SpointV_cov internal for the initial Spoint_cov for this track in the first time that the cross is made.\n\tdouble cov_det = cov[0] * cov[4] - cov[1] * cov[5];\n\tdouble dx = x - p2.x;\n\tdouble dy = y - p2.y;\n\tdouble distx=( dx*dx*cov[5] - 2*dx*dy*cov[1] + dy*dy*cov[0] )/cov_det;\n\n\tdouble cov_detV = cov[10] * cov[14] - cov[11] * cov[15];\n\tdouble dvx = vx - p2.vx;\n\tdouble dvy = vy - p2.vy;\n\tdistV=( dvx*dvx*cov[15] - 2*dvx*dvy*cov[11] + dvy*dvy*cov[10] )/cov_detV;\n\n\tdistxv=distx+distV;\n\n\treturn distx;\n\n}\n\nSpointV_cov SpointV_cov::operator+ (SpointV_cov p2) const\n{\n    return SpointV_cov(  x + p2.x , y + p2.y , time_stamp , vx + p2.vx , vy + p2.vy ,cov);\n}\nSpointV_cov SpointV_cov::operator- (SpointV_cov p2) const\n{\n    return SpointV_cov(  x - p2.x , y - p2.y , time_stamp-p2.time_stamp,  vx - p2.vx , vy - p2.vy ,cov);\n}\nSpointV_cov SpointV_cov::operator* (double k) const\n{\n    return SpointV_cov(  x * k , y * k, time_stamp,  vx * k , vy * k , cov);\n}\nSpointV_cov SpointV_cov::propagate( double dt , Sforce f, double desired_velocity) const\n{\n\tSpointV new_point = SpointV::propagate(dt,f,desired_velocity);\n\tEigen::MatrixXd cov_prev(4 , 4 );\n\tfor (unsigned int i = 0; i < 4; ++i)\n\t{\n\t\tcov_prev.row(i) << cov[i*4],cov[i*4+1],cov[i*4+2],cov[i*4+3];\n\t}\n\t//std::cout << \"cov_ prev = \\n\" <<  cov_prev << std::endl;\n\tEigen::MatrixXd Phi(4 , 4 );\n\tPhi = Eigen::MatrixXd::Identity(4,4);\n\tPhi(0,2) = dt;\n\tPhi(1,3) = dt;\n\t//std::cout << \"Phi = \" << Phi << std::endl;\n\tEigen::MatrixXd G(4 , 2 );\n\tG = Eigen::MatrixXd::Zero(4,2);\n\tG(0,0) = dt*dt/2;\n\tG(1,1) = dt*dt/2;\n\tG(2,0) = dt;\n\tG(3,1) = dt;\n\t//std::cout << \"G = \" << G << std::endl;\n\tEigen::MatrixXd new_cov(4,4);\n\tEigen::MatrixXd cov_f(2,2);\n\tcov_f = Eigen::MatrixXd::Zero(2,2);\n\tcov_f(0,0) = 0.3;//TODO this covariance should be associated to the corresponding force and not generic\n\tcov_f(1,1) = 0.3;\n\t//std::cout << \"f = \" << cov_f << std::endl;\n\tnew_cov = Phi*cov_prev*Phi.transpose() + G*cov_f*G.transpose();\n\tstd::vector<double> new_cov_std(16,0.0);\n\tfor(unsigned int i = 0; i<16; ++i)\n\t{\n\t\tnew_cov_std[i] = new_cov( i/4 , i%4 );\n\t}\n\t//std::cout << \"new cov = \\n\" <<  new_cov << std::endl;\n\treturn SpointV_cov( new_point, new_cov_std );\n}\ndouble SpointV_cov::cov_xx() const\n{\n\treturn cov[0];\n}\ndouble SpointV_cov::cov_yy() const\n{\n\treturn cov[5];\n}\ndouble SpointV_cov::cov_xy() const\n{\n\treturn cov[1];\n}\nSpoint_cov SpointV_cov::toSpoint_cov() const\n{\n\tstd::vector<double> cov_point;\n\tcov_point.reserve(4);\n\tcov_point.resize(4,0.0);\n\tcov_point[0] = cov[0];\n\tcov_point[1] = cov[1];\n\tcov_point[2] = cov[4];\n\tcov_point[3] = cov[5];\n\treturn Spoint_cov( x,y,time_stamp, cov_point );\n}\nvoid SpointV_cov::print() const\n{\n    SpointV::print();\n    std::cout << \"covariance = [ \" << cov[0] << \" , \" << cov[1] << \" , \" <<cov[2]  << \" , \" << cov[3] << std::endl <<\n    \t\t     \"               \" << cov[4] << \" , \" << cov[5] << \" , \" <<cov[6]  << \" , \" << cov[7] << std::endl <<\n    \t\t     \"               \" << cov[8] << \" , \" << cov[9] << \" , \" <<cov[10]  << \" , \" << cov[11] << std::endl <<\n    \t\t     \"               \" << cov[12] << \" , \" << cov[13] << \" , \" <<cov[14]  << \" , \" << cov[15] << std::endl;\n}\n\n//Spose methods -----------------------------------------------------------\nSpose::Spose() : Spoint(), theta(0)  , v(0) , w(0)  { }\nSpose::Spose( double x_ , double y_ , double time_stamp_ , double theta_ , double v_, double w_) :\n\tSpoint(x_,y_, time_stamp_), theta(theta_), v(v_), w(w_) { }\nSpose Spose::operator+ (Spose p2) const\n{\n\treturn Spose(  x + p2.x , y + p2.y , theta + p2.theta, p2.time_stamp , p2.v , p2.w );\n}\nSpose Spose::operator- (Spose p2) const\n{\n\treturn Spose(  x - p2.x , y - p2.y , theta - p2.theta, p2.time_stamp , p2.v , p2.w );\n}\nSpose Spose::operator* ( double k) const\n{\n\treturn Spose(  x * k , y *k , theta, time_stamp , v , w );\n}\ndouble Spose::distance(Spoint p2) const\n{\n\treturn sqrt(  (x-p2.x)*(x-p2.x) + (y-p2.y)*(y-p2.y) );\n}\ndouble Spose::angle_heading_pose( Spose p2 ) const\n{\n\tdouble dx = p2.x - x;\n\tdouble dy = p2.y - y;\n\treturn diffangle( atan2( dy , dx ), theta );\n}\ndouble Spose::social_distance( Spose p2 ) const\n{\n\tdouble lambda = 0.0;\n\tdouble phi = this->angle_heading_pose( p2 );\n\tdouble anisotropy = (lambda + (1-lambda)*(1 + cos(phi))/2 );\n\treturn this->distance(p2)/anisotropy;\n}\nvoid Spose::print() const\n{\n\tstd::cout << \"(x , y | theta) = (\" << x << \" , \" << y  << \" | \" << theta <<\n\t\t\t\" )  --  at t = \" << time_stamp << std::endl <<\n\t\t\t\"(v , w) = (\" << v  << \" , \" << w << \" )\" << std::endl;\n}\n\n//Spose_cov methods -----------------------------------------------------------\nSpose_cov::Spose_cov():\t Spose()\n{\n\tcov.reserve(25);\n\tcov.resize(25,0.0);\n\tcov[0] = 0.5;//xx\n\tcov[6] = 0.5;//yy\n\tcov[12] = 0.05;//theta_theta\n\tcov[18] = 0.1;//cov_vv\n\tcov[24] = 0.1;//ww\n}\nSpose_cov::Spose_cov(double x_ , double y_ ,\n\t\tdouble time_stamp_ , double theta_ ,  double v_, double w_,\n\t\tconst std::vector<double>& cov_ ):\n\t\tSpose( x_,y_,time_stamp_, theta_,v_,w_ )\n{\n\tif ( cov_.empty() || cov_.size() < (std::size_t) 25 )\n\t{\n\t\tcov.reserve(25);\n\t\tcov.resize(25,0.0);\n\t\tcov[0] = 0.5;//xx\n\t\tcov[6] = 0.5;//yy\n\t\tcov[12] = 0.05;//theta_theta\n\t\tcov[18] = 0.1;//cov_vv\n\t\tcov[24] = 0.1;//ww\n\t}\n\telse\n\t{\n\t\tcov = cov_;\n\t}\n}\nSpose_cov::Spose_cov( Spose pose_, const std::vector<double>& cov_ ):\n\t\tSpose(pose_)\n{\n\tif ( cov_.empty() || cov_.size() < (std::size_t) 25 )\n\t{\n\t\tcov.reserve(25);\n\t\tcov.resize(25,0.0);\n\t\tcov[0] = 0.5;//xx\n\t\tcov[6] = 0.5;//yy\n\t\tcov[12] = 0.05;//theta_theta\n\t\tcov[18] = 0.1;//cov_vv\n\t\tcov[24] = 0.1;//ww\n\t}\n\telse\n\t{\n\t\tcov = cov_;\n\t}\n}\nSpose_cov::Spose_cov( SpointV_cov point ):\n\t\tSpose(point.x,point.y,point.time_stamp,point.orientation(),point.v())\n{\n\tcov.reserve(25);\n\tcov.resize(25,0.0);\n\tcov[0] = point.cov[0];//xx\n\tcov[6] = point.cov[5];//yy\n\tcov[12] = 0.05;//theta_theta\n\tcov[18] = 0.1;//cov_vv\n\tcov[24] = 0.1;//ww\n}\ndouble Spose_cov::distance( Spose_cov p2) const\n{\n\treturn Spose::distance( Spose(p2.x,p2.y) );\n}\ndouble Spose_cov::cov_dist( Spose p2 ) const\n{\n\t//analitical inversion of the 2x2 matrix\n\tdouble cov_xx = cov[0];\n\tdouble cov_yy = cov[6];\n\tdouble cov_xy = cov[5];\n\tdouble cov_det = cov_xx * cov_yy - cov_xy * cov_xy;\n\tdouble dx = x - p2.x;\n\tdouble dy = y - p2.y;\n\treturn ( dx*dx*cov_yy - 2*dx*dy*cov_xy + dy*dy*cov_xx )/cov_det;\n}\ndouble Spose_cov::cov_dist( Spose_cov p2 ) const\n{\n\treturn this->cov_dist( Spose(p2.x,p2.y) );\n}\n\n//Sdestinations methods -----------------------------------------------------------\nSdestination::Sdestination( int id_, double x_ , double y_ , double prob_ ,\n\t\tSdestination::destination_type type_, std::vector<int> neighbours_ids_ ) :\n\tSpoint(x_,y_), id(id_), prob(prob_) ,\n\ttype(type_), neighbours_ids(neighbours_ids_)  { }\nSdestination::~Sdestination(){}\nbool Sdestination::operator== (Sdestination d2) const\n{\n\tif ( x == d2.x && y == d2.y )\n\t\treturn true;\n\telse\n\t\treturn false;\n}\n\nvoid Sdestination::print() const\n{\n\tstd::cout << \"destination \" << id << \"at (\" << x << \" , \" << y  <<  \")  of type \" << type  <<\n\t\t\"   and probability = \" << prob  << \"neighbours \" << neighbours_ids.size() << std::endl;\n}\n\n\nSdetectionObservation::SdetectionObservation() :\n\t\t\t\tSpointV_cov(), id(0) { }\nSdetectionObservation::SdetectionObservation( int id_ , double time_stamp_ ,\n\t\tdouble x_, double y_, double vx_, double vy_, const std::vector<double>& cov_) :\n\t\t\tSpointV_cov(x_,y_,time_stamp_,vx_,vy_,cov_) , id(id_) { }\nSdetectionObservation::SdetectionObservation( int id_ , SpointV_cov pointV_cov_) :\n\tSpointV_cov( pointV_cov_ ), id(id_) {}\nvoid SdetectionObservation::print() const\n{\n\tstd::cout <<  \"detection Observation = \" << id << \" th \"  << std::endl;\n\tSpointV_cov::print();\n}\n\n\n//Sforce methods\nSforce::Sforce() : fx(0.0) , fy(0.0) {}\nSforce::Sforce(double fx_ , double fy_) : fx(fx_) , fy(fy_) {}\ndouble Sforce::module() { return sqrt(fx*fx + fy*fy);}\ndouble Sforce::module(double r2) { return sqrt(fx*fx + r2*fy*fy);}\ndouble Sforce::module2( ) { return fx*fx + fy*fy;}\ndouble Sforce::module2( double r2) { return fx*fx + r2*fy*fy;}\nvoid Sforce::print() const\n{\n\tstd::cout <<  \"Force = (\" << fx << \" , \" << fy  << \" )\" << std::endl;\n}\nSforce Sforce::operator+ (Sforce f2) const\n{\n\treturn Sforce(  fx + f2.fx , fy + f2.fy );\n}\nvoid Sforce::sum(Sforce f2)\n//a method similar to +=\n{\n\tfx += f2.fx;\n\tfy += f2.fy;\n}\nSforce& Sforce::operator +=(Sforce f2)\n{\n\tfx += f2.fx;\n\tfy += f2.fy;\n\treturn *this;\n}\n\nSforce Sforce::operator* (double k) const\n{\n\treturn Sforce(  fx *k , fy *k );\n}\n\ndouble Sforce::operator* (Spoint dr) const\n{\n\treturn this->fx * dr.x + this->fy * dr.y;\n}\nSforce Sforce::operator- (Sforce f2) const\n{\n    return Sforce(  fx - f2.fx , fy - f2.fy );\n}\n\ndouble diffangle(double alpha , double beta)\n{\n\t  double delta = alpha - beta;\n\t  if ( alpha >= beta )\n\t  {\n\t    while (delta >  PI)\n\t      delta -= 2*PI;\n\t  }\n\t  else\n\t  {\n\t\t  while (delta < -PI )\n\t\t\t  delta += 2*PI;\n\t  }\n\t  return delta;\n}\n", "meta": {"hexsha": "244408a6123da54877eb826d2dbd8f3ca6c3952f", "size": 15092, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "iri_navigation/iri_simulated_person_companion_akp_local_planner/local_lib/src/iri_geometry.cpp", "max_stars_repo_name": "yinzixuan126/modified_dwa", "max_stars_repo_head_hexsha": "b379c01e37adc1f6414005750633b05e1a024ae5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-12-30T04:00:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-10T23:59:30.000Z", "max_issues_repo_path": "iri_navigation/iri_simulated_person_companion_akp_local_planner/local_lib/src/iri_geometry.cpp", "max_issues_repo_name": "yinzixuan126/modified_dwa", "max_issues_repo_head_hexsha": "b379c01e37adc1f6414005750633b05e1a024ae5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "iri_navigation/iri_simulated_person_companion_akp_local_planner/local_lib/src/iri_geometry.cpp", "max_forks_repo_name": "yinzixuan126/modified_dwa", "max_forks_repo_head_hexsha": "b379c01e37adc1f6414005750633b05e1a024ae5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-05-17T02:35:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-17T00:34:53.000Z", "avg_line_length": 26.9019607843, "max_line_length": 147, "alphanum_fraction": 0.5851444474, "num_tokens": 5548, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4561759299108515}}
{"text": "\n// Copyright 2008-2009 Daniel James.\n// Distributed under the Boost Software License, Version 1.0. (See accompanying\n// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include \"../helpers/prefix.hpp\"\n\n#include <boost/unordered_set.hpp>\n#include <boost/unordered_map.hpp>\n#include <boost/preprocessor/seq.hpp>\n#include <list>\n#include \"../helpers/test.hpp\"\n\nnamespace equality_tests\n{\n    struct mod_compare\n    {\n        bool alt_hash_;\n\n        explicit mod_compare(bool alt_hash = false) : alt_hash_(alt_hash) {}\n\n        bool operator()(int x, int y) const\n        {\n            return x % 1000 == y % 1000;\n        }\n\n        int operator()(int x) const\n        {\n            return alt_hash_ ? x % 250 : (x + 5) % 250;\n        }\n    };\n\n#define UNORDERED_EQUALITY_SET_TEST(seq1, op, seq2)                         \\\n    {                                                                       \\\n        boost::unordered_set<int, mod_compare, mod_compare> set1, set2;     \\\n        BOOST_PP_SEQ_FOR_EACH(UNORDERED_SET_INSERT, set1, seq1)             \\\n        BOOST_PP_SEQ_FOR_EACH(UNORDERED_SET_INSERT, set2, seq2)             \\\n        BOOST_TEST(set1 op set2);                                           \\\n    }\n\n#define UNORDERED_EQUALITY_MULTISET_TEST(seq1, op, seq2)                    \\\n    {                                                                       \\\n        boost::unordered_multiset<int, mod_compare, mod_compare>            \\\n            set1, set2;                                                     \\\n        BOOST_PP_SEQ_FOR_EACH(UNORDERED_SET_INSERT, set1, seq1)             \\\n        BOOST_PP_SEQ_FOR_EACH(UNORDERED_SET_INSERT, set2, seq2)             \\\n        BOOST_TEST(set1 op set2);                                           \\\n    }\n\n#define UNORDERED_EQUALITY_MAP_TEST(seq1, op, seq2)                         \\\n    {                                                                       \\\n        boost::unordered_map<int, int, mod_compare, mod_compare>            \\\n            map1, map2;                                                     \\\n        BOOST_PP_SEQ_FOR_EACH(UNORDERED_MAP_INSERT, map1, seq1)             \\\n        BOOST_PP_SEQ_FOR_EACH(UNORDERED_MAP_INSERT, map2, seq2)             \\\n        BOOST_TEST(map1 op map2);                                           \\\n    }\n\n#define UNORDERED_EQUALITY_MULTIMAP_TEST(seq1, op, seq2)                    \\\n    {                                                                       \\\n        boost::unordered_multimap<int, int, mod_compare, mod_compare>       \\\n            map1, map2;                                                     \\\n        BOOST_PP_SEQ_FOR_EACH(UNORDERED_MAP_INSERT, map1, seq1)             \\\n        BOOST_PP_SEQ_FOR_EACH(UNORDERED_MAP_INSERT, map2, seq2)             \\\n        BOOST_TEST(map1 op map2);                                           \\\n    }\n\n#define UNORDERED_SET_INSERT(r, set, item) set.insert(item);\n#define UNORDERED_MAP_INSERT(r, map, item) \\\n    map.insert(std::pair<int const, int> BOOST_PP_SEQ_TO_TUPLE(item));\n\n    UNORDERED_AUTO_TEST(equality_size_tests)\n    {\n        boost::unordered_set<int> x1, x2;\n        BOOST_TEST(x1 == x2);\n        BOOST_TEST(!(x1 != x2));\n\n        x1.insert(1);\n        BOOST_TEST(x1 != x2);\n        BOOST_TEST(!(x1 == x2));\n        BOOST_TEST(x2 != x1);\n        BOOST_TEST(!(x2 == x1));\n        \n        x2.insert(1);\n        BOOST_TEST(x1 == x2);\n        BOOST_TEST(!(x1 != x2));\n        \n        x2.insert(2);\n        BOOST_TEST(x1 != x2);\n        BOOST_TEST(!(x1 == x2));\n        BOOST_TEST(x2 != x1);\n        BOOST_TEST(!(x2 == x1));\n    }\n    \n    UNORDERED_AUTO_TEST(equality_key_value_tests)\n    {\n        UNORDERED_EQUALITY_MULTISET_TEST((1), !=, (2))\n        UNORDERED_EQUALITY_SET_TEST((2), ==, (2))\n        UNORDERED_EQUALITY_MAP_TEST(((1)(1))((2)(1)), !=, ((1)(1))((3)(1)))\n    }\n    \n    UNORDERED_AUTO_TEST(equality_collision_test)\n    {\n        UNORDERED_EQUALITY_MULTISET_TEST(\n            (1), !=, (501))\n        UNORDERED_EQUALITY_MULTISET_TEST(\n            (1)(251), !=, (1)(501))\n        UNORDERED_EQUALITY_MULTIMAP_TEST(\n            ((251)(1))((1)(1)), !=, ((501)(1))((1)(1)))\n        UNORDERED_EQUALITY_MULTISET_TEST(\n            (1)(501), ==, (1)(501))\n        UNORDERED_EQUALITY_SET_TEST(\n            (1)(501), ==, (501)(1))\n    }\n\n    UNORDERED_AUTO_TEST(equality_group_size_test)\n    {\n        UNORDERED_EQUALITY_MULTISET_TEST(\n            (10)(20)(20), !=, (10)(10)(20))\n        UNORDERED_EQUALITY_MULTIMAP_TEST(\n            ((10)(1))((20)(1))((20)(1)), !=,\n            ((10)(1))((20)(1))((10)(1)))\n        UNORDERED_EQUALITY_MULTIMAP_TEST(\n            ((20)(1))((10)(1))((10)(1)), ==,\n            ((10)(1))((20)(1))((10)(1)))\n    }\n    \n    UNORDERED_AUTO_TEST(equality_map_value_test)\n    {\n        UNORDERED_EQUALITY_MAP_TEST(\n            ((1)(1)), !=, ((1)(2)))\n        UNORDERED_EQUALITY_MAP_TEST(\n            ((1)(1)), ==, ((1)(1)))\n        UNORDERED_EQUALITY_MULTIMAP_TEST(\n            ((1)(1)), !=, ((1)(2)))\n        UNORDERED_EQUALITY_MULTIMAP_TEST(\n            ((1)(1))((1)(1)), !=, ((1)(1))((1)(2)))\n        UNORDERED_EQUALITY_MULTIMAP_TEST(\n            ((1)(2))((1)(1)), !=, ((1)(1))((1)(2)))\n    }\n\n    UNORDERED_AUTO_TEST(equality_predicate_test)\n    {\n        UNORDERED_EQUALITY_SET_TEST(\n            (1), ==, (1001))\n        UNORDERED_EQUALITY_MAP_TEST(\n            ((1)(2))((1001)(1)), ==, ((1001)(2))((1)(1)))\n    }\n\n    // Test that equality still works when the two containers have\n    // different hash functions but the same equality predicate.\n\n    UNORDERED_AUTO_TEST(equality_different_hash_test)\n    {\n        typedef boost::unordered_set<int, mod_compare, mod_compare> set;\n        set set1(0, mod_compare(false), mod_compare(false));\n        set set2(0, mod_compare(true), mod_compare(true));\n        BOOST_TEST(set1 == set2);\n        set1.insert(1); set2.insert(2);\n        BOOST_TEST(set1 != set2);\n        set1.insert(2); set2.insert(1);\n        BOOST_TEST(set1 == set2);\n        set1.insert(10); set2.insert(20);\n        BOOST_TEST(set1 != set2);\n        set1.insert(20); set2.insert(10);\n        BOOST_TEST(set1 == set2);\n    }\n\n}\n\nRUN_TESTS()\n", "meta": {"hexsha": "6d9541b648dbd474800c27e3d451425c888b225c", "size": 6201, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/unordered/test/unordered/equality_tests.cpp", "max_stars_repo_name": "oudream/boost_1_42_0", "max_stars_repo_head_hexsha": "e92227bf374e478030e89876ec353de6eecaeac0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-06-25T23:20:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-14T19:38:34.000Z", "max_issues_repo_path": "libs/unordered/test/unordered/equality_tests.cpp", "max_issues_repo_name": "ksundberg/boost-svn", "max_issues_repo_head_hexsha": "5694e7831f7afc8f6e25d03d0fd375e7be758d0f", "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/unordered/test/unordered/equality_tests.cpp", "max_forks_repo_name": "ksundberg/boost-svn", "max_forks_repo_head_hexsha": "5694e7831f7afc8f6e25d03d0fd375e7be758d0f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-07-26T08:07:09.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-25T23:20:21.000Z", "avg_line_length": 36.0523255814, "max_line_length": 79, "alphanum_fraction": 0.5016932753, "num_tokens": 1585, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4561759299108515}}
{"text": "#ifndef STAN_MATH_PRIM_FUN_GAMMA_P_HPP\n#define STAN_MATH_PRIM_FUN_GAMMA_P_HPP\n\n#include <stan/math/prim/err.hpp>\n#include <stan/math/prim/fun/boost_policy.hpp>\n#include <stan/math/prim/fun/constants.hpp>\n#include <stan/math/prim/fun/is_nan.hpp>\n#include <stan/math/prim/functor/apply_scalar_binary.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n\nnamespace stan {\nnamespace math {\n\n/**\n * Return the value of the normalized, lower-incomplete gamma function\n * applied to the specified argument.\n *\n * <p>This function is defined, including error conditions, as follows\n   \\f[\n   \\mbox{gamma\\_p}(a, z) =\n   \\begin{cases}\n     \\textrm{error} & \\mbox{if } a\\leq 0 \\textrm{ or } z < 0\\\\\n     P(a, z) & \\mbox{if } a > 0, z \\geq 0 \\\\[6pt]\n     \\textrm{NaN} & \\mbox{if } a = \\textrm{NaN or } z = \\textrm{NaN}\n   \\end{cases}\n   \\f]\n\n   \\f[\n   \\frac{\\partial\\, \\mbox{gamma\\_p}(a, z)}{\\partial a} =\n   \\begin{cases}\n     \\textrm{error} & \\mbox{if } a\\leq 0 \\textrm{ or } z < 0\\\\\n     \\frac{\\partial\\, P(a, z)}{\\partial a} & \\mbox{if } a > 0, z \\geq 0 \\\\[6pt]\n     \\textrm{NaN} & \\mbox{if } a = \\textrm{NaN or } z = \\textrm{NaN}\n   \\end{cases}\n   \\f]\n\n   \\f[\n   \\frac{\\partial\\, \\mbox{gamma\\_p}(a, z)}{\\partial z} =\n   \\begin{cases}\n     \\textrm{error} & \\mbox{if } a\\leq 0 \\textrm{ or } z < 0\\\\\n     \\frac{\\partial\\, P(a, z)}{\\partial z} & \\mbox{if } a > 0, z \\geq 0 \\\\[6pt]\n     \\textrm{NaN} & \\mbox{if } a = \\textrm{NaN or } z = \\textrm{NaN}\n   \\end{cases}\n   \\f]\n\n   \\f[\n   P(a, z)=\\frac{1}{\\Gamma(a)}\\int_0^zt^{a-1}e^{-t}dt\n   \\f]\n\n   \\f[\n   \\frac{\\partial \\, P(a, z)}{\\partial a} =\n -\\frac{\\Psi(a)}{\\Gamma^2(a)}\\int_0^zt^{a-1}e^{-t}dt\n   + \\frac{1}{\\Gamma(a)}\\int_0^z (a-1)t^{a-2}e^{-t}dt\n   \\f]\n\n   \\f[\n   \\frac{\\partial \\, P(a, z)}{\\partial z} = \\frac{z^{a-1}e^{-z}}{\\Gamma(a)}\n   \\f]\n   *\n   * @param z first argument\n   * @param a second argument\n   * @return value of the normalized, lower-incomplete gamma function\n   * applied to z and a\n   * @throws std::domain_error if either argument is not positive or\n   * if z is at a pole of the function\n */\ninline double gamma_p(double z, double a) {\n  if (is_nan(z)) {\n    return not_a_number();\n  }\n  if (is_nan(a)) {\n    return not_a_number();\n  }\n  check_positive(\"gamma_p\", \"first argument (z)\", z);\n  check_nonnegative(\"gamma_p\", \"second argument (a)\", a);\n  return boost::math::gamma_p(z, a, boost_policy_t<>());\n}\n\n/**\n * Enables the vectorised application of the gamma_p function,\n * when the first and/or second arguments are containers.\n *\n * @tparam T1 type of first input\n * @tparam T2 type of second input\n * @param a First input\n * @param b Second input\n * @return gamma_p function applied to the two inputs.\n */\ntemplate <typename T1, typename T2, require_any_container_t<T1, T2>* = nullptr>\ninline auto gamma_p(const T1& a, const T2& b) {\n  return apply_scalar_binary(\n      a, b, [&](const auto& c, const auto& d) { return gamma_p(c, d); });\n}\n\n}  // namespace math\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "8b87c6b8304569b53165f7bcc6e40e99d97f229b", "size": 2964, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/prim/fun/gamma_p.hpp", "max_stars_repo_name": "LaudateCorpus1/math", "max_stars_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-14T14:33:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-14T14:33:37.000Z", "max_issues_repo_path": "stan/math/prim/fun/gamma_p.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/fun/gamma_p.hpp", "max_forks_repo_name": "LaudateCorpus1/math", "max_forks_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-05-10T12:55:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-10T12:55:07.000Z", "avg_line_length": 30.2448979592, "max_line_length": 79, "alphanum_fraction": 0.6184210526, "num_tokens": 1065, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4561759299108515}}
{"text": "\n\n/* --------------------------------------------------------------------- \n * \n * Copyright (C) 1999 - 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: Wolfgang Bangerth, 1999, \n *          Guido Kanschat, 2011 \n */ \n\n\n// @sect3{Many new include files}  \n\n// \u8fd9\u4e9b\u5305\u542b\u6587\u4ef6\u5df2\u7ecf\u4e3a\u4f60\u6240\u77e5\u3002\u5b83\u4eec\u58f0\u660e\u4e86\u5904\u7406\u4e09\u89d2\u5f62\u548c\u81ea\u7531\u5ea6\u679a\u4e3e\u7684\u7c7b\u3002\n\n#include <deal.II/grid/tria.h> \n#include <deal.II/dofs/dof_handler.h> \n\n// \u5728\u8fd9\u4e2a\u6587\u4ef6\u4e2d\u58f0\u660e\u4e86\u521b\u5efa\u7f51\u683c\u7684\u51fd\u6570\u3002\n\n#include <deal.II/grid/grid_generator.h> \n\n// \u8fd9\u4e2a\u6587\u4ef6\u5305\u542b\u4e86\u5bf9\u62c9\u683c\u6717\u65e5\u63d2\u503c\u6709\u9650\u5143\u7684\u63cf\u8ff0\u3002\n\n#include <deal.II/fe/fe_q.h> \n\n// \u800c\u8fd9\u4e2a\u6587\u4ef6\u662f\u521b\u5efa\u7a00\u758f\u77e9\u9635\u7684\u7a00\u758f\u6a21\u5f0f\u6240\u9700\u8981\u7684\uff0c\u5982\u524d\u9762\u7684\u4f8b\u5b50\u4e2d\u6240\u793a\u3002\n\n#include <deal.II/dofs/dof_tools.h> \n\n// \u63a5\u4e0b\u6765\u7684\u4e24\u4e2a\u6587\u4ef6\u662f\u5728\u6bcf\u4e2a\u5355\u5143\u4e0a\u4f7f\u7528\u6b63\u4ea4\u6cd5\u7ec4\u88c5\u77e9\u9635\u6240\u9700\u8981\u7684\u3002\u4e0b\u9762\u5c06\u5bf9\u5176\u4e2d\u58f0\u660e\u7684\u7c7b\u8fdb\u884c\u89e3\u91ca\u3002\n\n#include <deal.II/fe/fe_values.h> \n#include <deal.II/base/quadrature_lib.h> \n\n// \u4ee5\u4e0b\u662f\u6211\u4eec\u5728\u5904\u7406\u8fb9\u754c\u503c\u65f6\u9700\u8981\u7684\u4e09\u4e2a\u5305\u542b\u6587\u4ef6\u3002\n\n#include <deal.II/base/function.h> \n#include <deal.II/numerics/vector_tools.h> \n#include <deal.II/numerics/matrix_tools.h> \n\n// \u6211\u4eec\u73b0\u5728\u51e0\u4e4e\u5230\u4e86\u7ec8\u70b9\u3002\u7b2c\u4e8c\u7ec4\u5230\u6700\u540e\u4e00\u7ec4include\u6587\u4ef6\u662f\u7528\u4e8e\u7ebf\u6027\u4ee3\u6570\u7684\uff0c\u6211\u4eec\u7528\u5b83\u6765\u89e3\u51b3\u62c9\u666e\u62c9\u65af\u65b9\u7a0b\u7684\u6709\u9650\u5143\u79bb\u6563\u5316\u6240\u4ea7\u751f\u7684\u65b9\u7a0b\u7ec4\u3002\u6211\u4eec\u5c06\u4f7f\u7528\u5411\u91cf\u548c\u5168\u77e9\u9635\u5728\u6bcf\u4e2a\u5355\u5143\u4e2d\u7ec4\u88c5\u65b9\u7a0b\u7ec4\uff0c\u5e76\u5c06\u7ed3\u679c\u8f6c\u79fb\u5230\u7a00\u758f\u77e9\u9635\u4e2d\u3002\u7136\u540e\u6211\u4eec\u5c06\u4f7f\u7528\u5171\u8f6d\u68af\u5ea6\u6c42\u89e3\u5668\u6765\u89e3\u51b3\u8fd9\u4e2a\u95ee\u9898\uff0c\u4e3a\u6b64\u6211\u4eec\u9700\u8981\u4e00\u4e2a\u9884\u5904\u7406\u7a0b\u5e8f\uff08\u5728\u8fd9\u4e2a\u7a0b\u5e8f\u4e2d\uff0c\u6211\u4eec\u4f7f\u7528\u8eab\u4efd\u9884\u5904\u7406\u7a0b\u5e8f\uff0c\u5b83\u6ca1\u6709\u4efb\u4f55\u4f5c\u7528\uff0c\u4f46\u6211\u4eec\u8fd8\u662f\u9700\u8981\u5305\u62ec\u8fd9\u4e2a\u6587\u4ef6\uff09\u3002\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/dynamic_sparsity_pattern.h> \n#include <deal.II/lac/solver_cg.h> \n#include <deal.II/lac/precondition.h> \n\n// \u6700\u540e\uff0c\u8fd9\u662f\u4e3a\u4e86\u8f93\u51fa\u5230\u6587\u4ef6\u548c\u63a7\u5236\u53f0\u3002\n\n#include <deal.II/numerics/data_out.h> \n#include <fstream> \n#include <iostream> \n\n// ...\u8fd9\u662f\u4e3a\u4e86\u5c06deal.II\u547d\u540d\u7a7a\u95f4\u5bfc\u5165\u5230\u5168\u5c40\u8303\u56f4\u3002\n\nusing namespace dealii; \n// @sect3{The <code>Step3</code> class}  \n\n// \u5728\u8fd9\u4e2a\u7a0b\u5e8f\u4e2d\uff0c\u6211\u4eec\u6ca1\u6709\u91c7\u7528\u4ee5\u524d\u4f8b\u5b50\u4e2d\u7684\u7a0b\u5e8f\u5316\u7f16\u7a0b\uff0c\u800c\u662f\u5c06\u6240\u6709\u4e1c\u897f\u90fd\u5c01\u88c5\u5230\u4e00\u4e2a\u7c7b\u4e2d\u3002\u8fd9\u4e2a\u7c7b\u7531\u4e00\u4e9b\u51fd\u6570\u7ec4\u6210\uff0c\u8fd9\u4e9b\u51fd\u6570\u5206\u522b\u6267\u884c\u6709\u9650\u5143\u7a0b\u5e8f\u7684\u67d0\u4e9b\u65b9\u9762\uff0c\u4e00\u4e2a`main`\u51fd\u6570\u63a7\u5236\u5148\u505a\u4ec0\u4e48\u548c\u540e\u505a\u4ec0\u4e48\uff0c\u8fd8\u6709\u4e00\u4e2a\u6210\u5458\u53d8\u91cf\u5217\u8868\u3002\n\n// \u8be5\u7c7b\u7684\u516c\u5171\u90e8\u5206\u76f8\u5f53\u7b80\u77ed\uff1a\u5b83\u6709\u4e00\u4e2a\u6784\u9020\u51fd\u6570\u548c\u4e00\u4e2a\u4ece\u5916\u90e8\u8c03\u7528\u7684\u51fd\u6570`run`\uff0c\u5176\u4f5c\u7528\u7c7b\u4f3c\u4e8e`main`\u51fd\u6570\uff1a\u5b83\u534f\u8c03\u8be5\u7c7b\u7684\u54ea\u4e9b\u64cd\u4f5c\u5e94\u4ee5\u4f55\u79cd\u987a\u5e8f\u8fd0\u884c\u3002\u8be5\u7c7b\u4e2d\u7684\u5176\u4ed6\u4e1c\u897f\uff0c\u5373\u6240\u6709\u771f\u6b63\u505a\u4e8b\u60c5\u7684\u51fd\u6570\uff0c\u90fd\u5728\u8be5\u7c7b\u7684\u79c1\u6709\u90e8\u5206\u3002\n\nclass Step3 \n{ \npublic: \n  Step3(); \n\n  void run(); \n\n// \u7136\u540e\uff0c\u8fd8\u6709\u4e00\u4e9b\u6210\u5458\u51fd\u6570\uff0c\u5b83\u4eec\u4e3b\u8981\u662f\u505a\u5b83\u4eec\u540d\u5b57\u6240\u6697\u793a\u7684\u4e8b\u60c5\uff0c\u5728\u4ecb\u7ecd\u4e2d\u5df2\u7ecf\u8ba8\u8bba\u8fc7\u4e86\u3002\u7531\u4e8e\u5b83\u4eec\u4e0d\u9700\u8981\u4ece\u5916\u90e8\u8c03\u7528\uff0c\u6240\u4ee5\u5b83\u4eec\u662f\u672c\u7c7b\u7684\u79c1\u6709\u51fd\u6570\u3002\n\nprivate: \n  void make_grid(); \n  void setup_system(); \n  void assemble_system(); \n  void solve(); \n  void output_results() const; \n\n// \u6700\u540e\u6211\u4eec\u8fd8\u6709\u4e00\u4e9b\u6210\u5458\u53d8\u91cf\u3002\u6709\u4e00\u4e9b\u53d8\u91cf\u63cf\u8ff0\u4e86\u4e09\u89d2\u5f62\u548c\u81ea\u7531\u5ea6\u7684\u5168\u5c40\u7f16\u53f7\uff08\u6211\u4eec\u5c06\u5728\u8fd9\u4e2a\u7c7b\u7684\u6784\u9020\u51fd\u6570\u4e2d\u6307\u5b9a\u6709\u9650\u5143\u7684\u786e\u5207\u591a\u9879\u5f0f\u7a0b\u5ea6\uff09...\n\n  Triangulation<2> triangulation; \n  FE_Q<2>          fe; \n  DoFHandler<2>    dof_handler; \n\n// ...\u62c9\u666e\u62c9\u65af\u65b9\u7a0b\u79bb\u6563\u5316\u4ea7\u751f\u7684\u7cfb\u7edf\u77e9\u9635\u7684\u7a00\u758f\u6a21\u5f0f\u548c\u6570\u503c\u7684\u53d8\u91cf...\n\n  SparsityPattern      sparsity_pattern; \n  SparseMatrix<double> system_matrix; \n\n// .......\u4ee5\u53ca\u7528\u4e8e\u4fdd\u5b58\u53f3\u624b\u8fb9\u548c\u89e3\u51b3\u65b9\u6848\u5411\u91cf\u7684\u53d8\u91cf\u3002\n\n  Vector<double> solution; \n  Vector<double> system_rhs; \n}; \n// @sect4{Step3::Step3}  \n\n// \u8fd9\u91cc\u662f\u6784\u9020\u51fd\u6570\u3002\u5b83\u9664\u4e86\u9996\u5148\u6307\u5b9a\u6211\u4eec\u9700\u8981\u53cc\u7ebf\u6027\u5143\u7d20\uff08\u7531\u6709\u9650\u5143\u5bf9\u8c61\u7684\u53c2\u6570\u8868\u793a\uff0c\u5b83\u8868\u793a\u591a\u9879\u5f0f\u7684\u7a0b\u5ea6\uff09\uff0c\u5e76\u5c06dof_handler\u53d8\u91cf\u4e0e\u6211\u4eec\u4f7f\u7528\u7684\u4e09\u89d2\u5f62\u76f8\u5173\u8054\u4e4b\u5916\uff0c\u6ca1\u6709\u505a\u66f4\u591a\u7684\u5de5\u4f5c\u3002(\u6ce8\u610f\uff0c\u76ee\u524d\u4e09\u89d2\u7ed3\u6784\u5e76\u6ca1\u6709\u8bbe\u7f6e\u7f51\u683c\uff0c\u4f46\u662fDoFHandler\u5e76\u4e0d\u5173\u5fc3\uff1a\u5b83\u53ea\u60f3\u77e5\u9053\u5b83\u5c06\u4e0e\u54ea\u4e2a\u4e09\u89d2\u7ed3\u6784\u76f8\u5173\u8054\uff0c\u53ea\u6709\u5f53\u4f60\u4f7f\u7528distribution_dofs()\u51fd\u6570\u8bd5\u56fe\u5728\u7f51\u683c\u4e0a\u5206\u5e03\u81ea\u7531\u5ea6\u65f6\uff0c\u5b83\u624d\u5f00\u59cb\u5173\u5fc3\u5b9e\u9645\u7684\u7f51\u683c\u3002) Step3\u7c7b\u7684\u6240\u6709\u5176\u4ed6\u6210\u5458\u53d8\u91cf\u90fd\u6709\u4e00\u4e2a\u9ed8\u8ba4\u7684\u6784\u9020\u51fd\u6570\uff0c\u5b83\u53ef\u4ee5\u5b8c\u6210\u6211\u4eec\u60f3\u8981\u7684\u4e00\u5207\u3002\n\nStep3::Step3() \n  : fe(1) \n  , dof_handler(triangulation) \n{} \n// @sect4{Step3::make_grid}  \n\n// \u73b0\u5728\uff0c\u6211\u4eec\u8981\u505a\u7684\u7b2c\u4e00\u4ef6\u4e8b\u662f\u751f\u6210\u6211\u4eec\u60f3\u5728\u5176\u4e0a\u8fdb\u884c\u8ba1\u7b97\u7684\u4e09\u89d2\u5f62\uff0c\u5e76\u5bf9\u6bcf\u4e2a\u9876\u70b9\u8fdb\u884c\u81ea\u7531\u5ea6\u7f16\u53f7\u3002\u6211\u4eec\u4e4b\u524d\u5728 step-1 \u548c step-2 \u4e2d\u5206\u522b\u770b\u5230\u8fc7\u8fd9\u4e24\u4e2a\u6b65\u9aa4\u3002\n\n// \u8fd9\u4e2a\u51fd\u6570\u505a\u7684\u662f\u7b2c\u4e00\u90e8\u5206\uff0c\u521b\u5efa\u7f51\u683c\u3002 \u6211\u4eec\u521b\u5efa\u7f51\u683c\u5e76\u5bf9\u6240\u6709\u5355\u5143\u683c\u8fdb\u884c\u4e94\u6b21\u7ec6\u5316\u3002\u7531\u4e8e\u521d\u59cb\u7f51\u683c\uff08\u4e5f\u5c31\u662f\u6b63\u65b9\u5f62 $[-1,1] \\times [-1,1]$ \uff09\u53ea\u7531\u4e00\u4e2a\u5355\u5143\u7ec4\u6210\uff0c\u6240\u4ee5\u6700\u7ec8\u7684\u7f51\u683c\u670932\u4e58\u4ee532\u4e2a\u5355\u5143\uff0c\u603b\u5171\u662f1024\u4e2a\u3002\n\n// \u4e0d\u786e\u5b9a1024\u662f\u5426\u662f\u6b63\u786e\u7684\u6570\u5b57\uff1f\u6211\u4eec\u53ef\u4ee5\u901a\u8fc7\u4f7f\u7528\u4e09\u89d2\u5f62\u4e0a\u7684 <code>n_active_cells()</code> \u51fd\u6570\u8f93\u51fa\u5355\u5143\u683c\u7684\u6570\u91cf\u6765\u68c0\u67e5\u3002\n\nvoid Step3::make_grid() \n{ \n  GridGenerator::hyper_cube(triangulation, -1, 1); \n  triangulation.refine_global(5); \n\n  std::cout << \"Number of active cells: \" << triangulation.n_active_cells() \n            << std::endl; \n} \n// @note  \u6211\u4eec\u8c03\u7528 Triangulation::n_active_cells() \u51fd\u6570\uff0c\u800c\u4e0d\u662f Triangulation::n_cells(). \u8fd9\u91cc\uff0c<i>active</i>\u6307\u7684\u662f\u6ca1\u6709\u8fdb\u4e00\u6b65\u63d0\u70bc\u7684\u5355\u5143\u3002\u6211\u4eec\u5f3a\u8c03 \"\u6d3b\u8dc3 \"\u8fd9\u4e2a\u5f62\u5bb9\u8bcd\uff0c\u56e0\u4e3a\u8fd8\u6709\u66f4\u591a\u7684\u5355\u5143\uff0c\u5373\u6700\u7ec6\u7684\u5355\u5143\u7684\u7236\u5355\u5143\uff0c\u5b83\u4eec\u7684\u7236\u5355\u5143\u7b49\u7b49\uff0c\u76f4\u5230\u6784\u6210\u521d\u59cb\u7f51\u683c\u7684\u4e00\u4e2a\u5355\u5143\u4e3a\u6b62\u3002\u5f53\u7136\uff0c\u5728\u4e0b\u4e00\u4e2a\u66f4\u7c97\u7684\u5c42\u6b21\u4e0a\uff0c\u5355\u5143\u683c\u7684\u6570\u91cf\u662f\u6700\u7ec6\u5c42\u6b21\u4e0a\u7684\u5355\u5143\u683c\u7684\u56db\u5206\u4e4b\u4e00\uff0c\u5373256\uff0c\u7136\u540e\u662f64\u300116\u30014\u548c1\u3002\u5982\u679c\u4f60\u5728\u4e0a\u9762\u7684\u4ee3\u7801\u4e2d\u8c03\u7528 <code>triangulation.n_cells()</code> \uff0c\u4f60\u4f1a\u56e0\u6b64\u5f97\u5230\u4e00\u4e2a1365\u7684\u503c\u3002\u53e6\u4e00\u65b9\u9762\uff0c\u5355\u5143\u683c\u7684\u6570\u91cf\uff08\u76f8\u5bf9\u4e8e\u6d3b\u52a8\u5355\u5143\u683c\u7684\u6570\u91cf\uff09\u901a\u5e38\u6ca1\u6709\u4ec0\u4e48\u610f\u4e49\uff0c\u6240\u4ee5\u6ca1\u6709\u5f88\u597d\u7684\u7406\u7531\u53bb\u6253\u5370\u5b83\u3002\n\n//  @sect4{Step3::setup_system}  \n\n// \u63a5\u4e0b\u6765\u6211\u4eec\u5217\u4e3e\u6240\u6709\u7684\u81ea\u7531\u5ea6\uff0c\u5e76\u5efa\u7acb\u77e9\u9635\u548c\u5411\u91cf\u5bf9\u8c61\u6765\u4fdd\u5b58\u7cfb\u7edf\u6570\u636e\u3002\u679a\u4e3e\u662f\u901a\u8fc7\u4f7f\u7528 DoFHandler::distribute_dofs(), \u6765\u5b8c\u6210\u7684\uff0c\u6211\u4eec\u5728 step-2 \u7684\u4f8b\u5b50\u4e2d\u5df2\u7ecf\u770b\u5230\u4e86\u3002\u7531\u4e8e\u6211\u4eec\u4f7f\u7528\u4e86FE_Q\u7c7b\uff0c\u5e76\u4e14\u5728\u6784\u9020\u51fd\u6570\u4e2d\u8bbe\u7f6e\u4e86\u591a\u9879\u5f0f\u7684\u5ea6\u6570\u4e3a1\uff0c\u5373\u53cc\u7ebf\u6027\u5143\u7d20\uff0c\u8fd9\u5c31\u5c06\u4e00\u4e2a\u81ea\u7531\u5ea6\u4e0e\u6bcf\u4e2a\u9876\u70b9\u8054\u7cfb\u8d77\u6765\u3002\u5f53\u6211\u4eec\u5728\u751f\u6210\u8f93\u51fa\u65f6\uff0c\u8ba9\u6211\u4eec\u4e5f\u770b\u770b\u6709\u591a\u5c11\u81ea\u7531\u5ea6\u88ab\u751f\u6210\u3002\n\nvoid Step3::setup_system() \n{ \n  dof_handler.distribute_dofs(fe); \n  std::cout << \"Number of degrees of freedom: \" << dof_handler.n_dofs() \n            << std::endl; \n\n// \u6bcf\u4e2a\u9876\u70b9\u5e94\u8be5\u6709\u4e00\u4e2aDoF\u3002\u56e0\u4e3a\u6211\u4eec\u6709\u4e00\u4e2a32\u4e58\u4ee532\u7684\u7f51\u683c\uff0c\u6240\u4ee5DoFs\u7684\u6570\u91cf\u5e94\u8be5\u662f33\u4e58\u4ee533\uff0c\u53731089\u3002\n\n// \u6b63\u5982\u6211\u4eec\u5728\u524d\u9762\u7684\u4f8b\u5b50\u4e2d\u6240\u770b\u5230\u7684\uff0c\u6211\u4eec\u901a\u8fc7\u9996\u5148\u521b\u5efa\u4e00\u4e2a\u4e34\u65f6\u7ed3\u6784\uff0c\u6807\u8bb0\u90a3\u4e9b\u53ef\u80fd\u4e3a\u975e\u96f6\u7684\u6761\u76ee\uff0c\u7136\u540e\u5c06\u6570\u636e\u590d\u5236\u5230SparsityPattern\u5bf9\u8c61\u4e2d\uff0c\u7136\u540e\u53ef\u4ee5\u88ab\u7cfb\u7edf\u77e9\u9635\u4f7f\u7528\uff0c\u6765\u8bbe\u7f6e\u4e00\u4e2a\u7a00\u758f\u6a21\u5f0f\u3002\n\n  DynamicSparsityPattern dsp(dof_handler.n_dofs()); \n  DoFTools::make_sparsity_pattern(dof_handler, dsp); \n  sparsity_pattern.copy_from(dsp); \n\n// \u6ce8\u610f\uff0cSparsityPattern\u5bf9\u8c61\u5e76\u4e0d\u4fdd\u5b58\u77e9\u9635\u7684\u503c\uff0c\u5b83\u53ea\u4fdd\u5b58\u6761\u76ee\u6240\u5728\u7684\u4f4d\u7f6e\u3002\u6761\u76ee\u672c\u8eab\u5b58\u50a8\u5728SparseMatrix\u7c7b\u578b\u7684\u5bf9\u8c61\u4e2d\uff0c\u6211\u4eec\u7684\u53d8\u91cfsystem_matrix\u5c31\u662f\u5176\u4e2d\u4e4b\u4e00\u3002\n\n// \u7a00\u758f\u6a21\u5f0f\u548c\u77e9\u9635\u4e4b\u95f4\u7684\u533a\u522b\u662f\u4e3a\u4e86\u8ba9\u51e0\u4e2a\u77e9\u9635\u4f7f\u7528\u76f8\u540c\u7684\u7a00\u758f\u6a21\u5f0f\u3002\u8fd9\u5728\u8fd9\u91cc\u4f3c\u4e4e\u5e76\u4e0d\u91cd\u8981\uff0c\u4f46\u662f\u5f53\u4f60\u8003\u8651\u5230\u77e9\u9635\u7684\u5927\u5c0f\uff0c\u4ee5\u53ca\u5efa\u7acb\u7a00\u758f\u6a21\u5f0f\u53ef\u80fd\u9700\u8981\u4e00\u4e9b\u65f6\u95f4\u65f6\uff0c\u5982\u679c\u4f60\u5fc5\u987b\u5728\u7a0b\u5e8f\u4e2d\u5b58\u50a8\u51e0\u4e2a\u77e9\u9635\uff0c\u8fd9\u5728\u5927\u89c4\u6a21\u95ee\u9898\u4e2d\u5c31\u53d8\u5f97\u5f88\u91cd\u8981\u4e86\u3002\n\n  system_matrix.reinit(sparsity_pattern); \n\n// \u5728\u8fd9\u4e2a\u51fd\u6570\u4e2d\u8981\u505a\u7684\u6700\u540e\u4e00\u4ef6\u4e8b\u662f\u5c06\u53f3\u4fa7\u5411\u91cf\u548c\u89e3\u5411\u91cf\u7684\u5927\u5c0f\u8bbe\u7f6e\u4e3a\u6b63\u786e\u7684\u503c\u3002\n\n  solution.reinit(dof_handler.n_dofs()); \n  system_rhs.reinit(dof_handler.n_dofs()); \n} \n// @sect4{Step3::assemble_system}  \n\n// \u4e0b\u4e00\u6b65\u662f\u8ba1\u7b97\u5f62\u6210\u7ebf\u6027\u7cfb\u7edf\u7684\u77e9\u9635\u548c\u53f3\u624b\u8fb9\u7684\u6761\u76ee\uff0c\u6211\u4eec\u4ece\u4e2d\u8ba1\u7b97\u51fa\u89e3\u51b3\u65b9\u6848\u3002\u8fd9\u662f\u6bcf\u4e00\u4e2a\u6709\u9650\u5143\u7a0b\u5e8f\u7684\u6838\u5fc3\u529f\u80fd\uff0c\u6211\u4eec\u5728\u4ecb\u7ecd\u4e2d\u5df2\u7ecf\u8ba8\u8bba\u4e86\u4e3b\u8981\u6b65\u9aa4\u3002\n\n// \u7ec4\u88c5\u77e9\u9635\u548c\u5411\u91cf\u7684\u4e00\u822c\u65b9\u6cd5\u662f\u5728\u6240\u6709\u5355\u5143\u4e0a\u5faa\u73af\uff0c\u5e76\u5728\u6bcf\u4e2a\u5355\u5143\u4e0a\u901a\u8fc7\u6b63\u4ea4\u8ba1\u7b97\u8be5\u5355\u5143\u5bf9\u5168\u5c40\u77e9\u9635\u548c\u53f3\u4fa7\u7684\u8d21\u732e\u3002\u73b0\u5728\u8981\u8ba4\u8bc6\u5230\u7684\u4e00\u70b9\u662f\uff0c\u6211\u4eec\u9700\u8981\u5b9e\u5fc3\u5355\u5143\u4e0a\u6b63\u4ea4\u70b9\u4f4d\u7f6e\u7684\u5f62\u72b6\u51fd\u6570\u503c\u3002\u7136\u800c\uff0c\u6709\u9650\u5143\u5f62\u72b6\u51fd\u6570\u548c\u6b63\u4ea4\u70b9\u90fd\u53ea\u5b9a\u4e49\u5728\u53c2\u8003\u5355\u5143\u4e0a\u3002\u56e0\u6b64\uff0c\u5b83\u4eec\u5bf9\u6211\u4eec\u5e2e\u52a9\u4e0d\u5927\uff0c\u4e8b\u5b9e\u4e0a\uff0c\u6211\u4eec\u51e0\u4e4e\u4e0d\u4f1a\u76f4\u63a5\u4ece\u8fd9\u4e9b\u5bf9\u8c61\u4e2d\u67e5\u8be2\u6709\u5173\u6709\u9650\u5143\u5f62\u72b6\u51fd\u6570\u6216\u6b63\u4ea4\u70b9\u7684\u4fe1\u606f\u3002\n\n// \u76f8\u53cd\uff0c\u6211\u4eec\u9700\u8981\u7684\u662f\u4e00\u79cd\u5c06\u8fd9\u4e9b\u6570\u636e\u4ece\u53c2\u8003\u5355\u5143\u6620\u5c04\u5230\u5b9e\u9645\u5355\u5143\u7684\u65b9\u6cd5\u3002\u80fd\u591f\u505a\u5230\u8fd9\u4e00\u70b9\u7684\u7c7b\u90fd\u662f\u7531Mapping\u7c7b\u6d3e\u751f\u51fa\u6765\u7684\uff0c\u5c3d\u7ba1\u4eba\u4eec\u5e38\u5e38\u4e0d\u5fc5\u76f4\u63a5\u4e0e\u5b83\u4eec\u6253\u4ea4\u9053\uff1a\u5e93\u4e2d\u7684\u8bb8\u591a\u51fd\u6570\u90fd\u53ef\u4ee5\u5c06\u6620\u5c04\u5bf9\u8c61\u4f5c\u4e3a\u53c2\u6570\uff0c\u4f46\u5f53\u5b83\u88ab\u7701\u7565\u65f6\uff0c\u5b83\u4eec\u53ea\u662f\u7b80\u5355\u5730\u8bc9\u8bf8\u4e8e\u6807\u51c6\u7684\u53cc\u7ebf\u6027Q1\u6620\u5c04\u3002\u6211\u4eec\u5c06\u8d70\u8fd9\u6761\u8def\uff0c\u6682\u65f6\u4e0d\u6253\u6270\u5b83\uff08\u6211\u4eec\u5c06\u5728 step-10 \u3001 step-11 \u548c step-12 \u4e2d\u518d\u8ba8\u8bba\u8fd9\u4e2a\u95ee\u9898\uff09\u3002\n\n// \u6240\u4ee5\u6211\u4eec\u73b0\u5728\u6709\u4e09\u4e2a\u7c7b\u7684\u96c6\u5408\u6765\u5904\u7406\uff1a\u6709\u9650\u5143\u3001\u6b63\u4ea4\u3001\u548c\u6620\u5c04\u5bf9\u8c61\u3002\u8fd9\u5c31\u592a\u591a\u4e86\uff0c\u6240\u4ee5\u6709\u4e00\u79cd\u7c7b\u578b\u7684\u7c7b\u53ef\u4ee5\u534f\u8c03\u8fd9\u4e09\u8005\u4e4b\u95f4\u7684\u4fe1\u606f\u4ea4\u6d41\uff1aFEValues\u7c7b\u3002\u5982\u679c\u7ed9\u8fd9\u4e09\u4e2a\u5bf9\u8c61\u5404\u4e00\u4e2a\u5b9e\u4f8b\uff08\u6216\u4e24\u4e2a\uff0c\u4ee5\u53ca\u4e00\u4e2a\u9690\u5f0f\u7ebf\u6027\u6620\u5c04\uff09\uff0c\u5b83\u5c31\u80fd\u4e3a\u4f60\u63d0\u4f9b\u5b9e\u5fc3\u5355\u5143\u4e0a\u6b63\u4ea4\u70b9\u7684\u5f62\u72b6\u51fd\u6570\u503c\u548c\u68af\u5ea6\u7684\u4fe1\u606f\u3002\n\n// \u5229\u7528\u6240\u6709\u8fd9\u4e9b\uff0c\u6211\u4eec\u5c06\u628a\u8fd9\u4e2a\u95ee\u9898\u7684\u7ebf\u6027\u7cfb\u7edf\u7ec4\u88c5\u5728\u4ee5\u4e0b\u51fd\u6570\u4e2d\u3002\n\nvoid Step3::assemble_system() \n{ \n\n// \u597d\u7684\uff0c\u6211\u4eec\u5f00\u59cb\u5427\uff1a\u6211\u4eec\u9700\u8981\u4e00\u4e2a\u6b63\u4ea4\u516c\u5f0f\u6765\u8ba1\u7b97\u6bcf\u4e2a\u5355\u5143\u683c\u7684\u79ef\u5206\u3002\u8ba9\u6211\u4eec\u91c7\u7528\u4e00\u4e2a\u9ad8\u65af\u516c\u5f0f\uff0c\u6bcf\u4e2a\u65b9\u5411\u6709\u4e24\u4e2a\u6b63\u4ea4\u70b9\uff0c\u5373\u603b\u5171\u6709\u56db\u4e2a\u70b9\uff0c\u56e0\u4e3a\u6211\u4eec\u662f\u5728\u4e8c\u7ef4\u3002\u8fd9\u4e2a\u6b63\u4ea4\u516c\u5f0f\u53ef\u4ee5\u51c6\u786e\u5730\u79ef\u5206\u4e09\u5ea6\u4ee5\u4e0b\u7684\u591a\u9879\u5f0f\uff08\u5728\u4e00\u7ef4\uff09\u3002\u5f88\u5bb9\u6613\u68c0\u67e5\u51fa\uff0c\u8fd9\u5bf9\u76ee\u524d\u7684\u95ee\u9898\u6765\u8bf4\u662f\u8db3\u591f\u7684\u3002\n\n  QGauss<2> quadrature_formula(fe.degree + 1); \n\n// \u7136\u540e\u6211\u4eec\u521d\u59cb\u5316\u6211\u4eec\u5728\u4e0a\u9762\u7b80\u5355\u8c08\u53ca\u7684\u5bf9\u8c61\u3002\u5b83\u9700\u8981\u88ab\u544a\u77e5\u6211\u4eec\u8981\u4f7f\u7528\u54ea\u4e2a\u6709\u9650\u5143\uff0c\u4ee5\u53ca\u6b63\u4ea4\u70b9\u548c\u5b83\u4eec\u7684\u6743\u91cd\uff08\u7531\u4e00\u4e2a\u6b63\u4ea4\u5bf9\u8c61\u5171\u540c\u63cf\u8ff0\uff09\u3002\u5982\u524d\u6240\u8ff0\uff0c\u6211\u4eec\u4f7f\u7528\u9690\u542b\u7684Q1\u6620\u5c04\uff0c\u800c\u4e0d\u662f\u81ea\u5df1\u660e\u786e\u6307\u5b9a\u4e00\u4e2a\u3002\u6700\u540e\uff0c\u6211\u4eec\u5fc5\u987b\u544a\u8bc9\u5b83\u6211\u4eec\u5e0c\u671b\u5b83\u5728\u6bcf\u4e2a\u5355\u5143\u4e0a\u8ba1\u7b97\u4ec0\u4e48\uff1a\u6211\u4eec\u9700\u8981\u6b63\u4ea4\u70b9\u7684\u5f62\u72b6\u51fd\u6570\u503c\uff08\u5bf9\u4e8e\u53f3\u624b $(\\varphi_i,f)$ \uff09\uff0c\u5b83\u4eec\u7684\u68af\u5ea6\uff08\u5bf9\u4e8e\u77e9\u9635\u6761\u76ee $(\\nabla \\varphi_i, \\nabla \\varphi_j)$ \uff09\uff0c\u4ee5\u53ca\u6b63\u4ea4\u70b9\u7684\u6743\u91cd\u548c\u4ece\u53c2\u8003\u5355\u5143\u5230\u5b9e\u9645\u5355\u5143\u7684\u96c5\u5404\u5e03\u53d8\u6362\u7684\u884c\u5217\u5f0f\u3002\n\n// \u6211\u4eec\u5b9e\u9645\u9700\u8981\u7684\u4fe1\u606f\u5217\u8868\u662f\u4f5c\u4e3aFEValues\u6784\u9020\u51fd\u6570\u7684\u7b2c\u4e09\u4e2a\u53c2\u6570\u7684\u6807\u5fd7\u96c6\u5408\u7ed9\u51fa\u7684\u3002\u7531\u4e8e\u8fd9\u4e9b\u503c\u5fc5\u987b\u91cd\u65b0\u8ba1\u7b97\uff0c\u6216\u8005\u8bf4\u66f4\u65b0\uff0c\u6bcf\u6b21\u6211\u4eec\u8fdb\u5165\u4e00\u4e2a\u65b0\u7684\u5355\u5143\u65f6\uff0c\u6240\u6709\u8fd9\u4e9b\u6807\u5fd7\u90fd\u4ee5\u524d\u7f00 <code>update_</code> \u5f00\u59cb\uff0c\u7136\u540e\u6307\u51fa\u6211\u4eec\u60f3\u8981\u66f4\u65b0\u7684\u5b9e\u9645\u5185\u5bb9\u3002\u5982\u679c\u6211\u4eec\u60f3\u8981\u8ba1\u7b97\u5f62\u72b6\u51fd\u6570\u7684\u503c\uff0c\u90a3\u4e48\u7ed9\u51fa\u7684\u6807\u5fd7\u662f#update_values\uff1b\u5bf9\u4e8e\u68af\u5ea6\uff0c\u5b83\u662f#update_gradients\u3002\u96c5\u5404\u5e03\u7684\u884c\u5217\u5f0f\u548c\u6b63\u4ea4\u6743\u91cd\u603b\u662f\u4e00\u8d77\u4f7f\u7528\u7684\uff0c\u6240\u4ee5\u53ea\u8ba1\u7b97\u4e58\u79ef\uff08\u96c5\u5404\u5e03\u4e58\u4ee5\u6743\u91cd\uff0c\u6216\u8005\u7b80\u79f0 <code>JxW</code> \uff09\uff1b\u7531\u4e8e\u6211\u4eec\u9700\u8981\u5b83\u4eec\uff0c\u6211\u4eec\u5fc5\u987b\u540c\u65f6\u5217\u51fa#update_JxW_values\u3002\n\n  FEValues<2> fe_values(fe, \n                        quadrature_formula, \n                        update_values | update_gradients | update_JxW_values); \n\n// \u8fd9\u79cd\u65b9\u6cd5\u7684\u4f18\u70b9\u662f\uff0c\u6211\u4eec\u53ef\u4ee5\u6307\u5b9a\u6bcf\u4e2a\u5355\u5143\u4e0a\u7a76\u7adf\u9700\u8981\u4ec0\u4e48\u6837\u7684\u4fe1\u606f\u3002\u5f88\u5bb9\u6613\u7406\u89e3\u7684\u662f\uff0c\u8fd9\u79cd\u65b9\u6cd5\u53ef\u4ee5\u5927\u5927\u52a0\u5feb\u6709\u9650\u5143\u8ba1\u7b97\u7684\u901f\u5ea6\uff0c\u76f8\u6bd4\u4e4b\u4e0b\uff0c\u6240\u6709\u7684\u4e1c\u897f\uff0c\u5305\u62ec\u4e8c\u9636\u5bfc\u6570\u3001\u5355\u5143\u7684\u6cd5\u5411\u91cf\u7b49\u90fd\u5728\u6bcf\u4e2a\u5355\u5143\u4e0a\u8ba1\u7b97\uff0c\u4e0d\u7ba1\u662f\u5426\u9700\u8981\u5b83\u4eec\u3002\n\n//  @note  <code>update_values | update_gradients | update_JxW_values</code>\u7684\u8bed\u6cd5\u5bf9\u4e8e\u90a3\u4e9b\u4e0d\u4e60\u60ef\u7528C\u8bed\u8a00\u7f16\u7a0b\u591a\u5e74\u7684\u4f4d\u64cd\u4f5c\u7684\u4eba\u6765\u8bf4\u4e0d\u662f\u5f88\u660e\u663e\u3002\u9996\u5148\uff0c <code>operator|</code> \u662f<i>bitwise or operator</i>\uff0c\u4e5f\u5c31\u662f\u8bf4\uff0c\u5b83\u63a5\u53d7\u4e24\u4e2a\u6574\u6570\u53c2\u6570\uff0c\u8fd9\u4e9b\u53c2\u6570\u88ab\u89e3\u91ca\u4e3a\u6bd4\u7279\u6a21\u5f0f\uff0c\u5e76\u8fd4\u56de\u4e00\u4e2a\u6574\u6570\uff0c\u5176\u4e2d\u6bcf\u4e2a\u6bd4\u7279\u90fd\u88ab\u8bbe\u7f6e\uff0c\u56e0\u4e3a\u5728\u4e24\u4e2a\u53c2\u6570\u4e2d\u81f3\u5c11\u6709\u4e00\u4e2a\u7684\u5bf9\u5e94\u6bd4\u7279\u88ab\u8bbe\u7f6e\u3002\u4f8b\u5982\uff0c\u8003\u8651\u64cd\u4f5c <code>9|10</code>. In binary, <code>9=0b1001</code> \uff08\u5176\u4e2d\u524d\u7f00 <code>0b</code> \u8868\u793a\u8be5\u6570\u5b57\u5c06\u88ab\u89e3\u91ca\u4e3a\u4e8c\u8fdb\u5236\u6570\u5b57\uff09\u548c <code>10=0b1010</code>  \u3002\u901a\u8fc7\u6bcf\u4e2a\u6bd4\u7279\uff0c\u770b\u5b83\u662f\u5426\u5728\u5176\u4e2d\u4e00\u4e2a\u53c2\u6570\u4e2d\u88ab\u8bbe\u7f6e\uff0c\u6211\u4eec\u5f97\u51fa <code>0b1001|0b1010=0b1011</code> \uff0c\u6216\u8005\u7528\u5341\u8fdb\u5236\u7b26\u53f7\u8868\u793a\uff0c <code>9|10=11</code>  \u3002\u4f60\u9700\u8981\u77e5\u9053\u7684\u7b2c\u4e8c\u4e2a\u4fe1\u606f\u662f\uff0c\u5404\u79cd <code>update_*</code> \u6807\u5fd7\u90fd\u662f\u6709<i>exactly one bit set</i>\u7684\u6574\u6570\u3002\u4f8b\u5982\uff0c\u5047\u8bbe  <code>update_values=0b00001=1</code>  ,  <code>update_gradients=0b00010=2</code>  ,  <code>update_JxW_values=0b10000=16</code>  \u3002\u90a3\u4e48<code>update_values | update_gradients | update_JxW_values = 0b10011 = 19</code>\u3002\u6362\u53e5\u8bdd\u8bf4\uff0c\u6211\u4eec\u5f97\u5230\u4e00\u4e2a\u6570\u5b57\uff0c\u5373<i>encodes a binary mask representing all of the operations you want to happen</i>\uff0c\u5176\u4e2d\u6bcf\u4e2a\u64cd\u4f5c\u6b63\u597d\u5bf9\u5e94\u4e8e\u6574\u6570\u4e2d\u7684\u4e00\u4e2a\u4f4d\uff0c\u5982\u679c\u7b49\u4e8e1\uff0c\u610f\u5473\u7740\u6bcf\u4e2a\u5355\u5143\u683c\u4e0a\u5e94\u8be5\u66f4\u65b0\u4e00\u4e2a\u7279\u5b9a\u7684\u7247\u65ad\uff0c\u5982\u679c\u662f0\uff0c\u610f\u5473\u7740\u6211\u4eec\u4e0d\u9700\u8981\u8ba1\u7b97\u5b83\u3002\u6362\u53e5\u8bdd\u8bf4\uff0c\u5373\u4f7f <code>operator|</code> \u662f<i>bitwise OR operation</i>\uff0c\u5b83\u771f\u6b63\u4ee3\u8868\u7684\u662f<i>I want this AND that AND the other</i>\u3002\u8fd9\u6837\u7684\u4e8c\u8fdb\u5236\u63a9\u7801\u5728C\u8bed\u8a00\u7f16\u7a0b\u4e2d\u5f88\u5e38\u89c1\uff0c\u4f46\u5728C++\u8fd9\u6837\u7684\u9ad8\u7ea7\u8bed\u8a00\u4e2d\u4e5f\u8bb8\u4e0d\u662f\u8fd9\u6837\uff0c\u4f46\u5bf9\u5f53\u524d\u7684\u76ee\u7684\u6709\u5f88\u597d\u7684\u4f5c\u7528\u3002\n\n// \u4e3a\u4e86\u5728\u4e0b\u6587\u4e2d\u8fdb\u4e00\u6b65\u4f7f\u7528\uff0c\u6211\u4eec\u4e3a\u4e00\u4e2a\u5c06\u88ab\u9891\u7e41\u4f7f\u7528\u7684\u503c\u5b9a\u4e49\u4e86\u4e00\u4e2a\u5feb\u6377\u65b9\u5f0f\u3002\u4e5f\u5c31\u662f\u6bcf\u4e2a\u5355\u5143\u7684\u81ea\u7531\u5ea6\u6570\u7684\u7f29\u5199\uff08\u56e0\u4e3a\u6211\u4eec\u662f\u5728\u4e8c\u7ef4\uff0c\u81ea\u7531\u5ea6\u53ea\u4e0e\u9876\u70b9\u76f8\u5173\uff0c\u6240\u4ee5\u8fd9\u4e2a\u6570\u5b57\u662f4\uff0c\u4f46\u662f\u6211\u4eec\u66f4\u5e0c\u671b\u5728\u5199\u8fd9\u4e2a\u53d8\u91cf\u7684\u5b9a\u4e49\u65f6\uff0c\u4e0d\u59a8\u788d\u6211\u4eec\u4ee5\u540e\u9009\u62e9\u4e0d\u540c\u7684\u6709\u9650\u5143\uff0c\u6bcf\u4e2a\u5355\u5143\u6709\u4e0d\u540c\u7684\u81ea\u7531\u5ea6\u6570\uff0c\u6216\u8005\u5728\u4e0d\u540c\u7684\u7a7a\u95f4\u7ef4\u5ea6\u5de5\u4f5c\uff09\u3002\n\n// \u4e00\u822c\u6765\u8bf4\uff0c\u4f7f\u7528\u7b26\u53f7\u540d\u79f0\u800c\u4e0d\u662f\u786c\u7f16\u7801\u8fd9\u4e9b\u6570\u5b57\u662f\u4e2a\u597d\u4e3b\u610f\uff0c\u5373\u4f7f\u4f60\u77e5\u9053\u5b83\u4eec\uff0c\u56e0\u4e3a\u4f8b\u5982\uff0c\u4f60\u53ef\u80fd\u60f3\u5728\u67d0\u4e2a\u65f6\u5019\u6539\u53d8\u6709\u9650\u5143\u3002\u6539\u53d8\u5143\u7d20\u5c31\u5fc5\u987b\u5728\u4e0d\u540c\u7684\u51fd\u6570\u4e2d\u8fdb\u884c\uff0c\u800c\u4e14\u5f88\u5bb9\u6613\u5fd8\u8bb0\u5728\u7a0b\u5e8f\u7684\u53e6\u4e00\u90e8\u5206\u505a\u76f8\u5e94\u7684\u6539\u53d8\u3002\u6700\u597d\u4e0d\u8981\u4f9d\u8d56\u81ea\u5df1\u7684\u8ba1\u7b97\uff0c\u800c\u662f\u5411\u6b63\u786e\u7684\u5bf9\u8c61\u7d22\u53d6\u4fe1\u606f\u3002\u5728\u8fd9\u91cc\uff0c\u6211\u4eec\u8981\u6c42\u6709\u9650\u5143\u544a\u8bc9\u6211\u4eec\u6bcf\u4e2a\u5355\u5143\u7684\u81ea\u7531\u5ea6\u6570\uff0c\u65e0\u8bba\u6211\u4eec\u5728\u7a0b\u5e8f\u4e2d\u7684\u5176\u4ed6\u5730\u65b9\u9009\u62e9\u4ec0\u4e48\u6837\u7684\u7a7a\u95f4\u5c3a\u5bf8\u6216\u591a\u9879\u5f0f\u7a0b\u5ea6\uff0c\u6211\u4eec\u90fd\u4f1a\u5f97\u5230\u6b63\u786e\u7684\u6570\u5b57\u3002\n\n// \u8fd9\u91cc\u5b9a\u4e49\u7684\u5feb\u6377\u65b9\u5f0f\u4e3b\u8981\u662f\u4e3a\u4e86\u8ba8\u8bba\u57fa\u672c\u6982\u5ff5\uff0c\u800c\u4e0d\u662f\u56e0\u4e3a\u5b83\u8282\u7701\u4e86\u5927\u91cf\u7684\u8f93\u5165\uff0c\u7136\u540e\u4f1a\u4f7f\u4e0b\u9762\u7684\u5faa\u73af\u66f4\u5bb9\u6613\u9605\u8bfb\u3002\u5728\u5927\u578b\u7a0b\u5e8f\u4e2d\uff0c\u4f60\u4f1a\u5728\u5f88\u591a\u5730\u65b9\u770b\u5230\u8fd9\u6837\u7684\u5feb\u6377\u65b9\u5f0f\uff0c`dofs_per_cell`\u5c31\u662f\u4e00\u4e2a\u6216\u591a\u6216\u5c11\u662f\u8fd9\u7c7b\u5bf9\u8c61\u7684\u4f20\u7edf\u540d\u79f0\u3002\n\n  const unsigned int dofs_per_cell = fe.n_dofs_per_cell(); \n\n// \u73b0\u5728\uff0c\u6211\u4eec\u8bf4\u6211\u4eec\u60f3\u9010\u4e2a\u5355\u5143\u5730\u7ec4\u88c5\u5168\u5c40\u77e9\u9635\u548c\u5411\u91cf\u3002\u6211\u4eec\u53ef\u4ee5\u5c06\u7ed3\u679c\u76f4\u63a5\u5199\u5165\u5168\u5c40\u77e9\u9635\uff0c\u4f46\u662f\u8fd9\u6837\u505a\u7684\u6548\u7387\u5e76\u4e0d\u9ad8\uff0c\u56e0\u4e3a\u5bf9\u7a00\u758f\u77e9\u9635\u5143\u7d20\u7684\u8bbf\u95ee\u662f\u5f88\u6162\u7684\u3002\u76f8\u53cd\uff0c\u6211\u4eec\u9996\u5148\u5728\u4e00\u4e2a\u5c0f\u77e9\u9635\u4e2d\u8ba1\u7b97\u6bcf\u4e2a\u5355\u5143\u7684\u8d21\u732e\uff0c\u5e76\u5728\u8fd9\u4e2a\u5355\u5143\u7684\u8ba1\u7b97\u7ed3\u675f\u540e\u5c06\u5176\u8f6c\u79fb\u5230\u5168\u5c40\u77e9\u9635\u4e2d\u3002\u6211\u4eec\u5bf9\u53f3\u624b\u8fb9\u7684\u5411\u91cf\u4e5f\u662f\u8fd9\u6837\u505a\u7684\u3002\u6240\u4ee5\u6211\u4eec\u9996\u5148\u5206\u914d\u8fd9\u4e9b\u5bf9\u8c61\uff08\u8fd9\u4e9b\u662f\u5c40\u90e8\u5bf9\u8c61\uff0c\u6240\u6709\u7684\u81ea\u7531\u5ea6\u90fd\u4e0e\u6240\u6709\u5176\u4ed6\u7684\u81ea\u7531\u5ea6\u8026\u5408\uff0c\u6211\u4eec\u5e94\u8be5\u4f7f\u7528\u4e00\u4e2a\u5b8c\u6574\u7684\u77e9\u9635\u5bf9\u8c61\uff0c\u800c\u4e0d\u662f\u4e00\u4e2a\u7528\u4e8e\u5c40\u90e8\u64cd\u4f5c\u7684\u7a00\u758f\u77e9\u9635\uff1b\u4ee5\u540e\u6240\u6709\u7684\u4e1c\u897f\u90fd\u5c06\u8f6c\u79fb\u5230\u5168\u5c40\u7684\u7a00\u758f\u77e9\u9635\u4e2d\uff09\u3002\n\n  FullMatrix<double> cell_matrix(dofs_per_cell, dofs_per_cell); \n  Vector<double>     cell_rhs(dofs_per_cell); \n\n// \u5728\u96c6\u5408\u6bcf\u4e2a\u5355\u5143\u7684\u8d21\u732e\u65f6\uff0c\u6211\u4eec\u7528\u81ea\u7531\u5ea6\u7684\u5c40\u90e8\u7f16\u53f7\uff08\u5373\u4ece\u96f6\u5230dofs_per_cell-1\u7684\u7f16\u53f7\uff09\u6765\u505a\u3002\u7136\u800c\uff0c\u5f53\u6211\u4eec\u5c06\u7ed3\u679c\u8f6c\u79fb\u5230\u5168\u5c40\u77e9\u9635\u65f6\uff0c\u6211\u4eec\u5fc5\u987b\u77e5\u9053\u81ea\u7531\u5ea6\u7684\u5168\u5c40\u7f16\u53f7\u3002\u5f53\u6211\u4eec\u67e5\u8be2\u5b83\u4eec\u65f6\uff0c\u6211\u4eec\u9700\u8981\u4e3a\u8fd9\u4e9b\u6570\u5b57\u5efa\u7acb\u4e00\u4e2a\u4ece\u5934\u5f00\u59cb\u7684\uff08\u4e34\u65f6\uff09\u6570\u7ec4\uff08\u5173\u4e8e\u8fd9\u91cc\u4f7f\u7528\u7684\u7c7b\u578b\uff0c types::global_dof_index, \uff0c\u89c1\u4ecb\u7ecd\u672b\u5c3e\u7684\u8ba8\u8bba\uff09\u3002\n\n  std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell); \n\n// \u73b0\u5728\u662f\u6240\u6709\u5355\u5143\u683c\u7684\u5faa\u73af\u3002\u6211\u4eec\u4e4b\u524d\u5df2\u7ecf\u770b\u5230\u8fd9\u5bf9\u4e00\u4e2a\u4e09\u89d2\u5f62\u662f\u5982\u4f55\u5de5\u4f5c\u7684\u3002DoFHandler\u7684\u5355\u5143\u683c\u8fed\u4ee3\u5668\u4e0eTriangulation\u7684\u8fed\u4ee3\u5668\u5b8c\u5168\u7c7b\u4f3c\uff0c\u4f46\u6709\u5173\u4e8e\u4f60\u6240\u4f7f\u7528\u7684\u6709\u9650\u5143\u7684\u81ea\u7531\u5ea6\u7684\u989d\u5916\u4fe1\u606f\u3002\u5728\u81ea\u7531\u5ea6\u5904\u7406\u7a0b\u5e8f\u7684\u6d3b\u52a8\u5355\u5143\u4e0a\u8fdb\u884c\u5faa\u73af\u64cd\u4f5c\u7684\u65b9\u6cd5\u4e0e\u4e09\u89d2\u6cd5\u76f8\u540c\u3002\n\n// \u6ce8\u610f\uff0c\u8fd9\u6b21\u6211\u4eec\u5c06\u5355\u5143\u7684\u7c7b\u578b\u58f0\u660e\u4e3a`const auto &`\uff0c\u800c\u4e0d\u662f`auto`\u3002\u5728\u7b2c1\u6b65\u4e2d\uff0c\u6211\u4eec\u901a\u8fc7\u7528\u7ec6\u5316\u6307\u6807\u6807\u8bb0\u6765\u4fee\u6539\u4e09\u89d2\u5f62\u7684\u5355\u5143\u3002\u5728\u8fd9\u91cc\uff0c\u6211\u4eec\u53ea\u68c0\u67e5\u5355\u5143\u683c\u800c\u4e0d\u4fee\u6539\u5b83\u4eec\uff0c\u6240\u4ee5\u628a`cell`\u58f0\u660e\u4e3a`const`\u662f\u5f88\u597d\u7684\u505a\u6cd5\uff0c\u4ee5\u4fbf\u6267\u884c\u8fd9\u4e2a\u4e0d\u53d8\u6027\u3002\n\n  for (const auto &cell : dof_handler.active_cell_iterators()) \n    { \n\n// \u6211\u4eec\u73b0\u5728\u5750\u5728\u4e00\u4e2a\u5355\u5143\u4e0a\uff0c\u6211\u4eec\u5e0c\u671b\u8ba1\u7b97\u5f62\u72b6\u51fd\u6570\u7684\u503c\u548c\u68af\u5ea6\uff0c\u4ee5\u53ca\u53c2\u8003\u5355\u5143\u548c\u771f\u5b9e\u5355\u5143\u4e4b\u95f4\u6620\u5c04\u7684\u96c5\u5404\u5e03\u77e9\u9635\u7684\u884c\u5217\u5f0f\uff0c\u5728\u6b63\u4ea4\u70b9\u4e0a\u3002\u7531\u4e8e\u6240\u6709\u8fd9\u4e9b\u503c\u90fd\u53d6\u51b3\u4e8e\u5355\u5143\u683c\u7684\u51e0\u4f55\u5f62\u72b6\uff0c\u6211\u4eec\u5fc5\u987b\u8ba9FEValues\u5bf9\u8c61\u5728\u6bcf\u4e2a\u5355\u5143\u683c\u4e0a\u91cd\u65b0\u8ba1\u7b97\u5b83\u4eec\u3002\n\n      fe_values.reinit(cell); \n\n// \u63a5\u4e0b\u6765\uff0c\u5728\u6211\u4eec\u586b\u5145\u4e4b\u524d\uff0c\u5c06\u672c\u5730\u5355\u5143\u5bf9\u5168\u5c40\u77e9\u9635\u548c\u5168\u5c40\u53f3\u624b\u8fb9\u7684\u8d21\u732e\u91cd\u7f6e\u4e3a\u96f6\u3002\n\n      cell_matrix = 0; \n      cell_rhs    = 0; \n\n// \u73b0\u5728\u662f\u65f6\u5019\u5f00\u59cb\u5bf9\u5355\u5143\u8fdb\u884c\u79ef\u5206\u4e86\uff0c\u6211\u4eec\u901a\u8fc7\u5bf9\u6240\u6709\u7684\u6b63\u4ea4\u70b9\u8fdb\u884c\u5faa\u73af\u6765\u5b8c\u6210\uff0c\u6211\u4eec\u5c06\u7528q_index\u6765\u7f16\u53f7\u3002\n\n      for (const unsigned int q_index : fe_values.quadrature_point_indices()) \n        { \n\n// \u9996\u5148\u7ec4\u88c5\u77e9\u9635\u3002\u5bf9\u4e8e\u62c9\u666e\u62c9\u65af\u95ee\u9898\uff0c\u6bcf\u4e2a\u5355\u5143\u683c\u4e0a\u7684\u77e9\u9635\u662f\u5f62\u72b6\u51fd\u6570i\u548cj\u7684\u68af\u5ea6\u7684\u79ef\u5206\u3002\u7531\u4e8e\u6211\u4eec\u4e0d\u8fdb\u884c\u79ef\u5206\uff0c\u800c\u662f\u4f7f\u7528\u6b63\u4ea4\uff0c\u6240\u4ee5\u8fd9\u662f\u5728\u6240\u6709\u6b63\u4ea4\u70b9\u7684\u79ef\u5206\u4e4b\u548c\u4e58\u4ee5\u6b63\u4ea4\u70b9\u7684\u96c5\u5404\u5e03\u77e9\u9635\u7684\u884c\u5217\u5f0f\u4e58\u4ee5\u8fd9\u4e2a\u6b63\u4ea4\u70b9\u7684\u6743\u91cd\u3002\u4f60\u53ef\u4ee5\u901a\u8fc7\u4f7f\u7528 <code>fe_values.shape_grad(i,q_index)</code> \u5f97\u5230\u5f62\u72b6\u51fd\u6570 $i$ \u5728\u6570\u5b57q_index\u7684\u6b63\u4ea4\u70b9\u4e0a\u7684\u68af\u5ea6\uff1b\u8fd9\u4e2a\u68af\u5ea6\u662f\u4e00\u4e2a\u4e8c\u7ef4\u5411\u91cf\uff08\u4e8b\u5b9e\u4e0a\u5b83\u662f\u5f20\u91cf @<1,dim@>, \u7c7b\u578b\uff0c\u8fd9\u91ccdim=2\uff09\uff0c\u4e24\u4e2a\u8fd9\u6837\u7684\u5411\u91cf\u7684\u4e58\u79ef\u662f\u6807\u91cf\u4e58\u79ef\uff0c\u5373\u4e24\u4e2ashape_grad\u51fd\u6570\u8c03\u7528\u7684\u79ef\u662f\u70b9\u4e58\u3002\u8fd9\u53c8\u8981\u4e58\u4ee5\u96c5\u5404\u5e03\u884c\u5217\u5f0f\u548c\u6b63\u4ea4\u70b9\u6743\u91cd\uff08\u901a\u8fc7\u8c03\u7528 FEValues::JxW() \u5f97\u5230\uff09\u3002\u6700\u540e\uff0c\u5bf9\u6240\u6709\u5f62\u72b6\u51fd\u6570 $i$ \u548c $j$ \u91cd\u590d\u4e0a\u8ff0\u64cd\u4f5c\u3002\n\n          for (const unsigned int i : fe_values.dof_indices()) \n            for (const unsigned int j : fe_values.dof_indices()) \n              cell_matrix(i, j) += \n                (fe_values.shape_grad(i, q_index) * // grad phi_i(x_q) \n                 fe_values.shape_grad(j, q_index) * // grad phi_j(x_q) \n                 fe_values.JxW(q_index));           // dx \n\n// \u7136\u540e\u6211\u4eec\u5bf9\u53f3\u624b\u8fb9\u505a\u540c\u6837\u7684\u4e8b\u60c5\u3002\u5728\u8fd9\u91cc\uff0c\u79ef\u5206\u662f\u5bf9\u5f62\u72b6\u51fd\u6570i\u4e58\u4ee5\u53f3\u624b\u8fb9\u7684\u51fd\u6570\uff0c\u6211\u4eec\u9009\u62e9\u7684\u662f\u5e38\u503c\u4e3a1\u7684\u51fd\u6570\uff08\u66f4\u6709\u8da3\u7684\u4f8b\u5b50\u5c06\u5728\u4e0b\u9762\u7684\u7a0b\u5e8f\u4e2d\u8003\u8651\uff09\u3002\n\n          for (const unsigned int i : fe_values.dof_indices()) \n            cell_rhs(i) += (fe_values.shape_value(i, q_index) * // phi_i(x_q) \n                            1. *                                // f(x_q) \n                            fe_values.JxW(q_index));            // dx \n        } \n\n// \u73b0\u5728\u6211\u4eec\u6709\u4e86\u8fd9\u4e2a\u5355\u5143\u7684\u8d21\u732e\uff0c\u6211\u4eec\u5fc5\u987b\u628a\u5b83\u8f6c\u79fb\u5230\u5168\u5c40\u77e9\u9635\u548c\u53f3\u624b\u8fb9\u3002\u4e3a\u6b64\uff0c\u6211\u4eec\u9996\u5148\u8981\u627e\u51fa\u8fd9\u4e2a\u5355\u5143\u4e0a\u7684\u81ea\u7531\u5ea6\u6709\u54ea\u4e9b\u5168\u5c40\u6570\u5b57\u3002\u8ba9\u6211\u4eec\u7b80\u5355\u5730\u8be2\u95ee\u8be5\u5355\u5143\u7684\u4fe1\u606f\u3002\n\n      cell->get_dof_indices(local_dof_indices); \n\n// \u7136\u540e\u518d\u6b21\u5faa\u73af\u6240\u6709\u5f62\u72b6\u51fd\u6570i\u548cj\uff0c\u5e76\u5c06\u5c40\u90e8\u5143\u7d20\u8f6c\u79fb\u5230\u5168\u5c40\u77e9\u9635\u4e2d\u3002\u5168\u5c40\u6570\u5b57\u53ef\u4ee5\u7528local_dof_indices[i]\u83b7\u5f97\u3002\n\n      for (const unsigned int i : fe_values.dof_indices()) \n        for (const unsigned int j : fe_values.dof_indices()) \n          system_matrix.add(local_dof_indices[i], \n                            local_dof_indices[j], \n                            cell_matrix(i, j)); \n\n// \u518d\u6765\uff0c\u6211\u4eec\u5bf9\u53f3\u8fb9\u7684\u5411\u91cf\u505a\u540c\u6837\u7684\u4e8b\u60c5\u3002\n\n      for (const unsigned int i : fe_values.dof_indices()) \n        system_rhs(local_dof_indices[i]) += cell_rhs(i); \n    } \n\n// \u73b0\u5728\uff0c\u51e0\u4e4e\u6240\u6709\u7684\u4e1c\u897f\u90fd\u4e3a\u79bb\u6563\u7cfb\u7edf\u7684\u6c42\u89e3\u505a\u597d\u4e86\u51c6\u5907\u3002\u7136\u800c\uff0c\u6211\u4eec\u8fd8\u6ca1\u6709\u7167\u987e\u5230\u8fb9\u754c\u503c\uff08\u4e8b\u5b9e\u4e0a\uff0c\u6ca1\u6709\u8fea\u91cc\u5207\u7279\u8fb9\u754c\u503c\u7684\u62c9\u666e\u62c9\u65af\u65b9\u7a0b\u751a\u81f3\u4e0d\u662f\u552f\u4e00\u53ef\u89e3\u7684\uff0c\u56e0\u4e3a\u4f60\u53ef\u4ee5\u5728\u79bb\u6563\u89e3\u4e2d\u52a0\u5165\u4e00\u4e2a\u4efb\u610f\u7684\u5e38\u6570\uff09\u3002\u56e0\u6b64\uff0c\u6211\u4eec\u5fc5\u987b\u5bf9\u8fd9\u79cd\u60c5\u51b5\u505a\u4e00\u4e9b\u5904\u7406\u3002\n\n// \u4e3a\u6b64\uff0c\u6211\u4eec\u9996\u5148\u83b7\u5f97\u8fb9\u754c\u4e0a\u7684\u81ea\u7531\u5ea6\u5217\u8868\u4ee5\u53ca\u5f62\u72b6\u51fd\u6570\u5728\u90a3\u91cc\u7684\u503c\u3002\u4e3a\u4e86\u7b80\u5355\u8d77\u89c1\uff0c\u6211\u4eec\u53ea\u5bf9\u8fb9\u754c\u503c\u51fd\u6570\u8fdb\u884c\u63d2\u503c\uff0c\u800c\u4e0d\u662f\u5c06\u5176\u6295\u5f71\u5230\u8fb9\u754c\u4e0a\u3002\u5e93\u4e2d\u6709\u4e00\u4e2a\u51fd\u6570\u6b63\u662f\u8fd9\u6837\u505a\u7684\u3002  VectorTools::interpolate_boundary_values(). \u5b83\u7684\u53c2\u6570\u662f\uff08\u7701\u7565\u5b58\u5728\u9ed8\u8ba4\u503c\u800c\u6211\u4eec\u4e0d\u5173\u5fc3\u7684\u53c2\u6570\uff09\uff1aDoFHandler\u5bf9\u8c61\uff0c\u7528\u4e8e\u83b7\u53d6\u8fb9\u754c\u4e0a\u81ea\u7531\u5ea6\u7684\u5168\u5c40\u6570\u5b57\uff1b\u8fb9\u754c\u4e0a\u8fb9\u754c\u503c\u5e94\u88ab\u5185\u63d2\u7684\u90e8\u5206\uff1b\u8fb9\u754c\u503c\u51fd\u6570\u672c\u8eab\uff1b\u4ee5\u53ca\u8f93\u51fa\u5bf9\u8c61\u3002\n\n// \u8fb9\u754c\u5206\u91cf\u7684\u542b\u4e49\u5982\u4e0b\uff1a\u5728\u5f88\u591a\u60c5\u51b5\u4e0b\uff0c\u4f60\u53ef\u80fd\u53ea\u60f3\u5728\u8fb9\u754c\u7684\u4e00\u90e8\u5206\u65bd\u52a0\u67d0\u4e9b\u8fb9\u754c\u503c\u3002\u4f8b\u5982\uff0c\u5728\u6d41\u4f53\u529b\u5b66\u4e2d\uff0c\u4f60\u53ef\u80fd\u6709\u6d41\u5165\u548c\u6d41\u51fa\u7684\u8fb9\u754c\uff0c\u6216\u8005\u5728\u8eab\u4f53\u53d8\u5f62\u8ba1\u7b97\u4e2d\uff0c\u8eab\u4f53\u7684\u5939\u7d27\u548c\u81ea\u7531\u90e8\u5206\u3002\u90a3\u4e48\u4f60\u5c31\u60f3\u7528\u6307\u6807\u6765\u8868\u793a\u8fb9\u754c\u7684\u8fd9\u4e9b\u4e0d\u540c\u90e8\u5206\uff0c\u5e76\u544a\u8bc9interpolate_boundary_values\u51fd\u6570\u53ea\u8ba1\u7b97\u8fb9\u754c\u7684\u67d0\u4e00\u90e8\u5206\uff08\u4f8b\u5982\u5939\u4f4f\u7684\u90e8\u5206\uff0c\u6216\u6d41\u5165\u7684\u8fb9\u754c\uff09\u7684\u8fb9\u754c\u503c\u3002\u9ed8\u8ba4\u60c5\u51b5\u4e0b\uff0c\u6240\u6709\u7684\u8fb9\u754c\u90fd\u6709\u4e00\u4e2a0\u7684\u8fb9\u754c\u6307\u6807\uff0c\u9664\u975e\u53e6\u6709\u89c4\u5b9a\u3002\u5982\u679c\u8fb9\u754c\u7684\u90e8\u5206\u6709\u4e0d\u540c\u7684\u8fb9\u754c\u6761\u4ef6\uff0c\u4f60\u5fc5\u987b\u7528\u4e0d\u540c\u7684\u8fb9\u754c\u6307\u793a\u5668\u4e3a\u8fd9\u4e9b\u90e8\u5206\u7f16\u53f7\u3002\u7136\u540e\uff0c\u4e0b\u9762\u7684\u51fd\u6570\u8c03\u7528\u5c06\u53ea\u786e\u5b9a\u90a3\u4e9b\u8fb9\u754c\u6307\u6807\u5b9e\u9645\u4e0a\u662f\u4f5c\u4e3a\u7b2c\u4e8c\u4e2a\u53c2\u6570\u6307\u5b9a\u76840\u7684\u8fb9\u754c\u90e8\u5206\u7684\u8fb9\u754c\u503c\u3002\n\n// \u63cf\u8ff0\u8fb9\u754c\u503c\u7684\u51fd\u6570\u662f\u4e00\u4e2aFunction\u7c7b\u578b\u7684\u5bf9\u8c61\u6216\u4e00\u4e2a\u6d3e\u751f\u7c7b\u7684\u5bf9\u8c61\u3002\u5176\u4e2d\u4e00\u4e2a\u6d3e\u751f\u7c7b\u662f Functions::ZeroFunction, \uff0c\u5b83\u63cf\u8ff0\u4e86\u4e00\u4e2a\u5230\u5904\u90fd\u662f\u96f6\u7684\u51fd\u6570\uff08\u5e76\u4e0d\u610f\u5916\uff09\u3002\u6211\u4eec\u5c31\u5730\u521b\u5efa\u8fd9\u6837\u4e00\u4e2a\u5bf9\u8c61\uff0c\u5e76\u5c06\u5176\u4f20\u9012\u7ed9 VectorTools::interpolate_boundary_values() \u51fd\u6570\u3002\n\n// \u6700\u540e\uff0c\u8f93\u51fa\u5bf9\u8c61\u662f\u4e00\u5bf9\u5168\u5c40\u81ea\u7531\u5ea6\u6570\uff08\u5373\u8fb9\u754c\u4e0a\u7684\u81ea\u7531\u5ea6\u6570\uff09\u548c\u5b83\u4eec\u7684\u8fb9\u754c\u503c\uff08\u8fd9\u91cc\u6240\u6709\u6761\u76ee\u90fd\u662f\u96f6\uff09\u7684\u5217\u8868\u3002\u8fd9\u79cd\u81ea\u7531\u5ea6\u6570\u5230\u8fb9\u754c\u503c\u7684\u6620\u5c04\u662f\u7531 <code>std::map</code> \u7c7b\u5b8c\u6210\u7684\u3002\n\n  std::map<types::global_dof_index, double> boundary_values; \n  VectorTools::interpolate_boundary_values(dof_handler, \n                                           0, \n                                           Functions::ZeroFunction<2>(), \n                                           boundary_values); \n\n// \u73b0\u5728\u6211\u4eec\u5f97\u5230\u4e86\u8fb9\u754cDoF\u7684\u5217\u8868\u548c\u5b83\u4eec\u5404\u81ea\u7684\u8fb9\u754c\u503c\uff0c\u8ba9\u6211\u4eec\u7528\u5b83\u4eec\u6765\u76f8\u5e94\u5730\u4fee\u6539\u65b9\u7a0b\u7ec4\u3002\u8fd9\u53ef\u4ee5\u901a\u8fc7\u4ee5\u4e0b\u51fd\u6570\u8c03\u7528\u6765\u5b9e\u73b0\u3002\n\n  MatrixTools::apply_boundary_values(boundary_values, \n                                     system_matrix, \n                                     solution, \n                                     system_rhs); \n} \n// @sect4{Step3::solve}  \n\n// \u4e0b\u9762\u7684\u51fd\u6570\u7b80\u5355\u5730\u6c42\u89e3\u4e86\u79bb\u6563\u5316\u7684\u65b9\u7a0b\u3002\u7531\u4e8e\u8be5\u7cfb\u7edf\u5bf9\u4e8e\u9ad8\u65af\u6d88\u9664\u6216LU\u5206\u89e3\u7b49\u76f4\u63a5\u6c42\u89e3\u5668\u6765\u8bf4\u662f\u4e00\u4e2a\u76f8\u5f53\u5927\u7684\u7cfb\u7edf\uff0c\u6211\u4eec\u4f7f\u7528\u5171\u8f6d\u68af\u5ea6\u7b97\u6cd5\u3002\u4f60\u5e94\u8be5\u8bb0\u4f4f\uff0c\u8fd9\u91cc\u7684\u53d8\u91cf\u6570\u91cf\uff08\u53ea\u67091089\u4e2a\uff09\u5bf9\u4e8e\u6709\u9650\u5143\u8ba1\u7b97\u6765\u8bf4\u662f\u4e00\u4e2a\u975e\u5e38\u5c0f\u7684\u6570\u5b57\uff0c\u800c100.000\u662f\u4e00\u4e2a\u6bd4\u8f83\u5e38\u89c1\u7684\u6570\u5b57\u3002 \u5bf9\u4e8e\u8fd9\u4e2a\u6570\u91cf\u7684\u53d8\u91cf\uff0c\u76f4\u63a5\u65b9\u6cd5\u5df2\u7ecf\u4e0d\u80fd\u4f7f\u7528\u4e86\uff0c\u4f60\u4e0d\u5f97\u4e0d\u4f7f\u7528CG\u8fd9\u6837\u7684\u65b9\u6cd5\u3002\n\nvoid Step3::solve() \n{ \n\n// \u9996\u5148\uff0c\u6211\u4eec\u9700\u8981\u6709\u4e00\u4e2a\u5bf9\u8c61\uff0c\u77e5\u9053\u5982\u4f55\u544a\u8bc9CG\u7b97\u6cd5\u4f55\u65f6\u505c\u6b62\u3002\u8fd9\u662f\u901a\u8fc7\u4f7f\u7528SolverControl\u5bf9\u8c61\u6765\u5b9e\u73b0\u7684\uff0c\u4f5c\u4e3a\u505c\u6b62\u6807\u51c6\uff0c\u6211\u4eec\u8bf4\uff1a\u5728\u6700\u591a1000\u6b21\u8fed\u4ee3\u540e\u505c\u6b62\uff08\u8fd9\u8fdc\u8fdc\u8d85\u8fc7\u4e861089\u4e2a\u53d8\u91cf\u7684\u9700\u8981\uff1b\u89c1\u7ed3\u679c\u90e8\u5206\u4ee5\u4e86\u89e3\u771f\u6b63\u4f7f\u7528\u4e86\u591a\u5c11\u6b21\uff09\uff0c\u5982\u679c\u6b8b\u5dee\u7684\u89c4\u8303\u4f4e\u4e8e $10^{-12}$ \u5c31\u505c\u6b62\u3002\u5728\u5b9e\u8df5\u4e2d\uff0c\u540e\u4e00\u4e2a\u6807\u51c6\u5c06\u662f\u505c\u6b62\u8fed\u4ee3\u7684\u4e00\u4e2a\u6807\u51c6\u3002\n\n  SolverControl solver_control(1000, 1e-12); \n\n// \u7136\u540e\uff0c\u6211\u4eec\u9700\u8981\u89e3\u7b97\u5668\u672c\u8eab\u3002SolverCG\u7c7b\u7684\u6a21\u677f\u53c2\u6570\u662f\u5411\u91cf\u7684\u7c7b\u578b\uff0c\u7559\u4e0b\u7a7a\u7684\u89d2\u62ec\u53f7\u5c06\u8868\u660e\u6211\u4eec\u91c7\u53d6\u7684\u662f\u9ed8\u8ba4\u53c2\u6570\uff08\u5373 <code>Vector@<double@></code>  \uff09\u3002\u7136\u800c\uff0c\u6211\u4eec\u660e\u786e\u5730\u63d0\u5230\u4e86\u6a21\u677f\u53c2\u6570\u3002\n\n  SolverCG<Vector<double>> solver(solver_control); \n\n// \u73b0\u5728\u6c42\u89e3\u65b9\u7a0b\u7ec4\u3002CG\u6c42\u89e3\u5668\u7684\u7b2c\u56db\u4e2a\u53c2\u6570\u662f\u4e00\u4e2a\u9884\u5904\u7406\u7a0b\u5e8f\u3002\u6211\u4eec\u89c9\u5f97\u8fd8\u6ca1\u6709\u51c6\u5907\u597d\u6df1\u5165\u7814\u7a76\u8fd9\u4e2a\u95ee\u9898\uff0c\u6240\u4ee5\u6211\u4eec\u544a\u8bc9\u5b83\u4f7f\u7528\u8eab\u4efd\u8fd0\u7b97\u4f5c\u4e3a\u9884\u5904\u7406\u3002\n\n  solver.solve(system_matrix, solution, system_rhs, PreconditionIdentity()); \n\n// \u73b0\u5728\u6c42\u89e3\u5668\u5df2\u7ecf\u5b8c\u6210\u4e86\u5b83\u7684\u5de5\u4f5c\uff0c\u6c42\u89e3\u53d8\u91cf\u5305\u542b\u4e86\u6c42\u89e3\u51fd\u6570\u7684\u7ed3\u70b9\u503c\u3002\n\n} \n// @sect4{Step3::output_results}  \n\n// \u5178\u578b\u7684\u6709\u9650\u5143\u7a0b\u5e8f\u7684\u6700\u540e\u4e00\u90e8\u5206\u662f\u8f93\u51fa\u7ed3\u679c\uff0c\u4e5f\u8bb8\u4f1a\u505a\u4e00\u4e9b\u540e\u5904\u7406\uff08\u4f8b\u5982\u8ba1\u7b97\u8fb9\u754c\u5904\u7684\u6700\u5927\u5e94\u529b\u503c\uff0c\u6216\u8005\u8ba1\u7b97\u6574\u4e2a\u6d41\u51fa\u7269\u7684\u5e73\u5747\u901a\u91cf\uff0c\u7b49\u7b49\uff09\u3002\u6211\u4eec\u8fd9\u91cc\u6ca1\u6709\u8fd9\u6837\u7684\u540e\u5904\u7406\uff0c\u4f46\u662f\u6211\u4eec\u60f3\u628a\u89e3\u51b3\u65b9\u6848\u5199\u5230\u4e00\u4e2a\u6587\u4ef6\u91cc\u3002\n\nvoid Step3::output_results() const \n{ \n\n// \u4e3a\u4e86\u5c06\u8f93\u51fa\u5199\u5165\u6587\u4ef6\uff0c\u6211\u4eec\u9700\u8981\u4e00\u4e2a\u77e5\u9053\u8f93\u51fa\u683c\u5f0f\u7b49\u7684\u5bf9\u8c61\u3002\u8fd9\u5c31\u662fDataOut\u7c7b\uff0c\u6211\u4eec\u9700\u8981\u4e00\u4e2a\u8be5\u7c7b\u578b\u7684\u5bf9\u8c61\u3002\n\n  DataOut<2> data_out; \n\n// \u73b0\u5728\u6211\u4eec\u5fc5\u987b\u544a\u8bc9\u5b83\u4ece\u54ea\u91cc\u83b7\u53d6\u5b83\u8981\u5199\u7684\u503c\u3002\u6211\u4eec\u544a\u8bc9\u5b83\u4f7f\u7528\u54ea\u4e2aDoFHandler\u5bf9\u8c61\uff0c\u4ee5\u53ca\u6c42\u89e3\u5411\u91cf\uff08\u4ee5\u53ca\u6c42\u89e3\u53d8\u91cf\u5728\u8f93\u51fa\u6587\u4ef6\u4e2d\u7684\u540d\u79f0\uff09\u3002\u5982\u679c\u6211\u4eec\u6709\u4e0d\u6b62\u4e00\u4e2a\u6211\u4eec\u60f3\u5728\u8f93\u51fa\u4e2d\u67e5\u770b\u7684\u5411\u91cf\uff08\u4f8b\u5982\u53f3\u624b\u8fb9\uff0c\u6bcf\u4e2a\u5355\u5143\u683c\u7684\u9519\u8bef\uff0c\u7b49\u7b49\uff09\uff0c\u6211\u4eec\u4e5f\u8981\u628a\u5b83\u4eec\u52a0\u8fdb\u53bb\u3002\n\n  data_out.attach_dof_handler(dof_handler); \n  data_out.add_data_vector(solution, \"solution\"); \n\n// \u5728DataOut\u5bf9\u8c61\u77e5\u9053\u5b83\u8981\u5904\u7406\u54ea\u4e9b\u6570\u636e\u540e\uff0c\u6211\u4eec\u5fc5\u987b\u544a\u8bc9\u5b83\u628a\u5b83\u4eec\u5904\u7406\u6210\u540e\u7aef\u53ef\u4ee5\u5904\u7406\u7684\u6570\u636e\u3002\u539f\u56e0\u662f\u6211\u4eec\u5c06\u524d\u7aef\uff08\u77e5\u9053\u5982\u4f55\u5904\u7406DoFHandler\u5bf9\u8c61\u548c\u6570\u636e\u5411\u91cf\uff09\u4e0e\u540e\u7aef\uff08\u77e5\u9053\u8bb8\u591a\u4e0d\u540c\u7684\u8f93\u51fa\u683c\u5f0f\uff09\u5206\u5f00\uff0c\u4f7f\u7528\u4e00\u79cd\u4e2d\u95f4\u6570\u636e\u683c\u5f0f\u5c06\u6570\u636e\u4ece\u524d\u7aef\u4f20\u8f93\u5230\u540e\u7aef\u3002\u6570\u636e\u901a\u8fc7\u4ee5\u4e0b\u51fd\u6570\u8f6c\u6362\u4e3a\u8fd9\u79cd\u4e2d\u95f4\u683c\u5f0f\u3002\n\n  data_out.build_patches(); \n\n// \u73b0\u5728\u6211\u4eec\u5df2\u7ecf\u4e3a\u5b9e\u9645\u8f93\u51fa\u505a\u597d\u4e86\u4e00\u5207\u51c6\u5907\u3002\u53ea\u8981\u6253\u5f00\u4e00\u4e2a\u6587\u4ef6\uff0c\u7528VTK\u683c\u5f0f\u628a\u6570\u636e\u5199\u8fdb\u53bb\u5c31\u53ef\u4ee5\u4e86\uff08\u5728\u6211\u4eec\u8fd9\u91cc\u4f7f\u7528\u7684DataOut\u7c7b\u4e2d\u8fd8\u6709\u5f88\u591a\u5176\u4ed6\u51fd\u6570\uff0c\u53ef\u4ee5\u628a\u6570\u636e\u5199\u6210postscript\u3001AVS\u3001GMV\u3001Gnuplot\u6216\u5176\u4ed6\u4e00\u4e9b\u6587\u4ef6\u683c\u5f0f\uff09\u3002\n\n  std::ofstream output(\"solution.vtk\"); \n  data_out.write_vtk(output); \n} \n// @sect4{Step3::run}  \n\n// \u6700\u540e\uff0c\u8fd9\u4e2a\u7c7b\u7684\u6700\u540e\u4e00\u4e2a\u51fd\u6570\u662f\u4e3b\u51fd\u6570\uff0c\u8c03\u7528 <code>Step3</code> \u7c7b\u7684\u6240\u6709\u5176\u4ed6\u51fd\u6570\u3002\u8fd9\u6837\u505a\u7684\u987a\u5e8f\u7c7b\u4f3c\u4e8e\u5927\u591a\u6570\u6709\u9650\u5143\u7a0b\u5e8f\u7684\u5de5\u4f5c\u987a\u5e8f\u3002\u7531\u4e8e\u8fd9\u4e9b\u540d\u5b57\u5927\u591a\u662f\u4e0d\u8a00\u81ea\u660e\u7684\uff0c\u6240\u4ee5\u6ca1\u6709\u4ec0\u4e48\u53ef\u8bc4\u8bba\u7684\u3002\n\nvoid Step3::run() \n{ \n  make_grid(); \n  setup_system(); \n  assemble_system(); \n  solve(); \n  output_results(); \n} \n// @sect3{The <code>main</code> function}  \n\n// \u8fd9\u662f\u7a0b\u5e8f\u7684\u4e3b\u51fd\u6570\u3002\u7531\u4e8e\u4e3b\u51fd\u6570\u7684\u6982\u5ff5\u5927\u591a\u662fC++\u7f16\u7a0b\u4e4b\u524d\u7684\u9762\u5411\u5bf9\u8c61\u65f6\u4ee3\u7684\u9057\u7559\u7269\uff0c\u6240\u4ee5\u5b83\u901a\u5e38\u4e0d\u505a\u66f4\u591a\u7684\u4e8b\u60c5\uff0c\u53ea\u662f\u521b\u5efa\u4e00\u4e2a\u9876\u5c42\u7c7b\u7684\u5bf9\u8c61\u5e76\u8c03\u7528\u5176\u539f\u7406\u51fd\u6570\u3002\n\n// \u6700\u540e\uff0c\u51fd\u6570\u7684\u7b2c\u4e00\u884c\u662f\u7528\u6765\u542f\u7528deal.II\u53ef\u4ee5\u751f\u6210\u7684\u4e00\u4e9b\u8bca\u65ad\u7a0b\u5e8f\u7684\u8f93\u51fa\u3002  @p deallog \u53d8\u91cf\uff08\u4ee3\u8868deal-log\uff0c\u800c\u4e0d\u662fde-allog\uff09\u4ee3\u8868\u4e00\u4e2a\u6d41\uff0c\u5e93\u7684\u67d0\u4e9b\u90e8\u5206\u5c06\u8f93\u51fa\u5199\u5165\u5176\u4e2d\u3002\u4f8b\u5982\uff0c\u8fed\u4ee3\u6c42\u89e3\u5668\u5c06\u4ea7\u751f\u8bca\u65ad\u7a0b\u5e8f\uff08\u8d77\u59cb\u6b8b\u5dee\u3001\u6c42\u89e3\u5668\u6b65\u9aa4\u6570\u3001\u6700\u7ec8\u6b8b\u5dee\uff09\uff0c\u5728\u8fd0\u884c\u8fd9\u4e2a\u6559\u7a0b\u7a0b\u5e8f\u65f6\u53ef\u4ee5\u770b\u5230\u3002\n\n//  @p deallog \u7684\u8f93\u51fa\u53ef\u4ee5\u5199\u5230\u63a7\u5236\u53f0\uff0c\u4e5f\u53ef\u4ee5\u5199\u5230\u6587\u4ef6\uff0c\u6216\u8005\u4e24\u8005\u90fd\u5199\u3002\u4e24\u8005\u5728\u9ed8\u8ba4\u60c5\u51b5\u4e0b\u90fd\u662f\u7981\u7528\u7684\uff0c\u56e0\u4e3a\u591a\u5e74\u6765\u6211\u4eec\u5df2\u7ecf\u77e5\u9053\uff0c\u4e00\u4e2a\u7a0b\u5e8f\u53ea\u5e94\u8be5\u5728\u7528\u6237\u660e\u786e\u8981\u6c42\u7684\u65f6\u5019\u624d\u4ea7\u751f\u8f93\u51fa\u3002\u4f46\u8fd9\u662f\u53ef\u4ee5\u6539\u53d8\u7684\uff0c\u4e3a\u4e86\u89e3\u91ca\u5982\u4f55\u505a\u5230\u8fd9\u4e00\u70b9\uff0c\u6211\u4eec\u9700\u8981\u89e3\u91ca @p deallog \u662f\u5982\u4f55\u5de5\u4f5c\u7684\u3002\u5f53\u5e93\u7684\u4e2a\u522b\u90e8\u5206\u60f3\u8981\u8bb0\u5f55\u8f93\u51fa\u65f6\uff0c\u5b83\u4eec\u4f1a\u6253\u5f00\u4e00\u4e2a \"\u4e0a\u4e0b\u6587 \"\u6216 \"\u90e8\u5206\"\uff0c\u8fd9\u4e2a\u8f93\u51fa\u5c06\u88ab\u653e\u5165\u5176\u4e2d\u3002\u5728\u60f3\u8981\u5199\u8f93\u51fa\u7684\u90e8\u5206\u7ed3\u675f\u65f6\uff0c\u4eba\u4eec\u518d\u6b21\u9000\u51fa\u8fd9\u4e2a\u90e8\u5206\u3002\u7531\u4e8e\u4e00\u4e2a\u51fd\u6570\u53ef\u4ee5\u5728\u8fd9\u4e2a\u8f93\u51fa\u90e8\u5206\u6253\u5f00\u7684\u8303\u56f4\u5185\u8c03\u7528\u53e6\u4e00\u4e2a\u51fd\u6570\uff0c\u6240\u4ee5\u8f93\u51fa\u5b9e\u9645\u4e0a\u53ef\u4ee5\u5206\u5c42\u5d4c\u5957\u5230\u8fd9\u4e9b\u90e8\u5206\u3002LogStream\u7c7b\uff08 @p deallog \u662f\u4e00\u4e2a\u53d8\u91cf\uff09\u5c06\u8fd9\u4e9b\u90e8\u5206\u4e2d\u7684\u6bcf\u4e00\u4e2a\u79f0\u4e3a \"\u524d\u7f00\"\uff0c\u56e0\u4e3a\u6240\u6709\u7684\u8f93\u51fa\u90fd\u4ee5\u8fd9\u4e2a\u524d\u7f00\u6253\u5370\u5728\u884c\u7684\u5de6\u7aef\uff0c\u524d\u7f00\u7531\u5192\u53f7\u5206\u9694\u3002\u603b\u662f\u6709\u4e00\u4e2a\u9ed8\u8ba4\u7684\u524d\u7f00\u53eb\u505a \"DEAL\"\uff08\u6697\u793a\u4e86deal.II\u7684\u5386\u53f2\uff0c\u5b83\u662f\u4ee5\u524d\u4e00\u4e2a\u53eb\u505a \"DEAL \"\u7684\u5e93\u7684\u7ee7\u627f\u8005\uff0cLogStream\u7c7b\u662f\u88ab\u5e26\u5165deal.II\u7684\u5c11\u6570\u4ee3\u7801\u4e4b\u4e00\uff09\u3002\n\n// \u9ed8\u8ba4\u60c5\u51b5\u4e0b\uff0c @p logstream \u53ea\u8f93\u51fa\u524d\u7f00\u4e3a\u96f6\u7684\u884c--\u4e5f\u5c31\u662f\u8bf4\uff0c\u6240\u6709\u7684\u8f93\u51fa\u90fd\u662f\u7981\u7528\u7684\uff0c\u56e0\u4e3a\u9ed8\u8ba4\u7684 \"DEAL \"\u524d\u7f00\u603b\u662f\u5b58\u5728\u7684\u3002\u4f46\u4eba\u4eec\u53ef\u4ee5\u4e3a\u5e94\u8be5\u8f93\u51fa\u7684\u884c\u8bbe\u7f6e\u4e0d\u540c\u7684\u6700\u5927\u524d\u7f00\u6570\uff0c\u4ee5\u8fbe\u5230\u66f4\u5927\u7684\u6548\u679c\uff0c\u4e8b\u5b9e\u4e0a\u5728\u8fd9\u91cc\u6211\u4eec\u901a\u8fc7\u8c03\u7528 LogStream::depth_console(). \u5c06\u5176\u8bbe\u7f6e\u4e3a\u4e24\u4e2a\u3002\u8fd9\u610f\u5473\u7740\u5bf9\u4e8e\u6240\u6709\u7684\u5c4f\u5e55\u8f93\u51fa\uff0c\u5728\u9ed8\u8ba4\u7684 \"DEAL \"\u4e4b\u5916\u518d\u63a8\u4e00\u4e2a\u524d\u7f00\u7684\u4e0a\u4e0b\u6587\u88ab\u5141\u8bb8\u5c06\u5176\u8f93\u51fa\u6253\u5370\u5230\u5c4f\u5e55\u4e0a\uff08\"\u63a7\u5236\u53f0\"\uff09\uff0c\u800c\u6240\u6709\u8fdb\u4e00\u6b65\u5d4c\u5957\u7684\u90e8\u5206\u5c06\u6709\u4e09\u4e2a\u6216\u66f4\u591a\u7684\u524d\u7f00\u88ab\u6fc0\u6d3b\uff0c\u4f1a\u5199\u5230 @p deallog, \uff0c\u4f46 @p deallog \u5e76\u4e0d\u8f6c\u53d1\u8fd9\u4e2a\u8f93\u51fa\u5230\u5c4f\u5e55\u3002\u56e0\u6b64\uff0c\u8fd0\u884c\u8fd9\u4e2a\u4f8b\u5b50\uff08\u6216\u8005\u770b \"\u7ed3\u679c \"\u90e8\u5206\uff09\uff0c\u4f60\u4f1a\u770b\u5230\u89e3\u7b97\u5668\u7684\u7edf\u8ba1\u6570\u636e\u524d\u7f00\u4e3a \"DEAL:CG\"\uff0c\u8fd9\u662f\u4e24\u4e2a\u524d\u7f00\u3002\u8fd9\u5bf9\u4e8e\u5f53\u524d\u7a0b\u5e8f\u7684\u4e0a\u4e0b\u6587\u6765\u8bf4\u5df2\u7ecf\u8db3\u591f\u4e86\uff0c\u4f46\u662f\u4f60\u5c06\u5728\u4ee5\u540e\u770b\u5230\u4e00\u4e9b\u4f8b\u5b50\uff08\u4f8b\u5982\uff0c\u5728 step-22 \u4e2d\uff09\uff0c\u5176\u4e2d\u6c42\u89e3\u5668\u5d4c\u5957\u5f97\u66f4\u6df1\uff0c\u4f60\u53ef\u80fd\u901a\u8fc7\u8bbe\u7f6e\u66f4\u9ad8\u7684\u6df1\u5ea6\u6765\u83b7\u5f97\u6709\u7528\u7684\u4fe1\u606f\u3002\n\nint main() \n{ \n  deallog.depth_console(2); \n\n  Step3 laplace_problem; \n  laplace_problem.run(); \n\n  return 0; \n} \n\n\n", "meta": {"hexsha": "f3fd4ce976a1d99c8dbb449ccf17766df1407be3", "size": 15856, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-3/step-3.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-3/step-3.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-3/step-3.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": 42.7385444744, "max_line_length": 1070, "alphanum_fraction": 0.7542885974, "num_tokens": 9743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.611381973294151, "lm_q2_score": 0.7461389873857265, "lm_q1q2_score": 0.4561759264595851}}
{"text": "//  Copyright 2020 John Maddock. Distributed under the Boost\n//  Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt\n\n#include <iostream>\n#include <vector>\n#include <benchmark/benchmark.h>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/multiprecision/gmp.hpp>\n\n#include <boost/math/special_functions/prime.hpp>\n#include <boost/math/special_functions/pow.hpp>\n\n#include <gmpxx.h>\n\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_int.hpp>\n\ntemplate <class T>\nT generate_random(unsigned bits_wanted)\n{\n   static boost::random::mt19937               gen;\n   typedef boost::random::mt19937::result_type random_type;\n\n   T        max_val;\n   unsigned digits;\n   if (std::numeric_limits<T>::is_bounded && (bits_wanted == (unsigned)std::numeric_limits<T>::digits))\n   {\n      max_val = (std::numeric_limits<T>::max)();\n      digits  = std::numeric_limits<T>::digits;\n   }\n   else\n   {\n      max_val = T(1) << bits_wanted;\n      digits  = bits_wanted;\n   }\n\n   unsigned bits_per_r_val = std::numeric_limits<random_type>::digits - 1;\n   while ((random_type(1) << bits_per_r_val) > (gen.max)())\n      --bits_per_r_val;\n\n   unsigned terms_needed = digits / bits_per_r_val + 1;\n\n   T val = 0;\n   for (unsigned i = 0; i < terms_needed; ++i)\n   {\n      val *= (gen.max)();\n      val += gen();\n   }\n   val %= max_val;\n   return val;\n}\n\ntemplate <class T>\nconst std::vector<std::vector<T> >& get_matrix_data(unsigned bits);\n\ntemplate <>\nconst std::vector<std::vector<boost::multiprecision::cpp_rational> >& get_matrix_data(unsigned bits)\n{\n   static std::map<unsigned, std::vector<std::vector<boost::multiprecision::cpp_rational> > > data;\n   if (data[bits].size() == 0)\n   {\n      for (unsigned i = 0; i < 100; ++i)\n      {\n         std::vector<boost::multiprecision::cpp_rational> matrix;\n         for (unsigned j = 0; j < 9; ++j)\n         {\n            boost::multiprecision::cpp_int a(generate_random<boost::multiprecision::cpp_int>(bits)), b(generate_random<boost::multiprecision::cpp_int>(bits));\n            matrix.push_back(boost::multiprecision::cpp_rational(a, b));\n         }\n         data[bits].push_back(matrix);\n      }\n   }\n   return data[bits];\n}\n\ntemplate <class T>\nconst std::vector<std::vector<T> >& get_matrix_data(unsigned bits)\n{\n   static std::map<unsigned, std::vector<std::vector<T> > > data;\n   if (data[bits].empty())\n   {\n      const std::vector<std::vector<boost::multiprecision::cpp_rational> >& d = get_matrix_data<boost::multiprecision::cpp_rational>(bits);\n      for (unsigned i = 0; i < 100; ++i)\n      {\n         std::vector<T> matrix;\n         for (unsigned j = 0; j < 9; ++j)\n         {\n            matrix.push_back(T(d[i][j].str()));\n         }\n         data[bits].push_back(matrix);\n      }\n   }\n   return data[bits];\n}\n\ntemplate <class T>\nT determinant(const std::vector<T>& data)\n{\n   const T m01 = data[0] * data[4] - data[3] * data[1];\n   const T m02 = data[0] * data[7] - data[6] * data[1];\n   const T m12 = data[3] * data[7] - data[6] * data[4];\n   return m01 * data[8] - m02 * data[5] + m12 * data[2];\n}\n\ntemplate <class Rational>\nstatic void BM_determinant(benchmark::State& state)\n{\n   int                         bits = state.range(0);\n   const std::vector<std::vector<Rational> >& data = get_matrix_data<Rational>(bits);\n   for (auto _ : state)\n   {\n      for(unsigned i = 0; i < data.size(); ++i)\n         benchmark::DoNotOptimize(determinant(data[i]));\n   }\n}\n\n\nconstexpr unsigned lower_range = 512;\nconstexpr unsigned upper_range = 1 << 15;\n\nBENCHMARK_TEMPLATE(BM_determinant, boost::multiprecision::cpp_rational)->RangeMultiplier(2)->Range(lower_range, upper_range)->Unit(benchmark::kMillisecond);\nBENCHMARK_TEMPLATE(BM_determinant, boost::multiprecision::mpq_rational)->RangeMultiplier(2)->Range(lower_range, upper_range)->Unit(benchmark::kMillisecond);\nBENCHMARK_TEMPLATE(BM_determinant, mpq_class)->RangeMultiplier(2)->Range(lower_range, upper_range)->Unit(benchmark::kMillisecond);\n\nBENCHMARK_MAIN();\n", "meta": {"hexsha": "f10a9a9195aa4226c3887e2d407454ce6366c2b6", "size": 4054, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/boost_1.78.0/libs/multiprecision/performance/rational_determinant_bench.cpp", "max_stars_repo_name": "LaudateCorpus1/math", "max_stars_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-10-27T21:15:52.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-27T21:15:52.000Z", "max_issues_repo_path": "lib/boost_1.78.0/libs/multiprecision/performance/rational_determinant_bench.cpp", "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": "lib/boost_1.78.0/libs/multiprecision/performance/rational_determinant_bench.cpp", "max_forks_repo_name": "LaudateCorpus1/math", "max_forks_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-24T08:49:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-24T08:49:34.000Z", "avg_line_length": 31.9212598425, "max_line_length": 158, "alphanum_fraction": 0.6531820424, "num_tokens": 1112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389817407017, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.4561759230083187}}
{"text": "#include <doctest/doctest.h>\n#include <py2cpp/nx2bgl.hpp>\n\n#include <algorithm> // for std::for_each\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <boost/graph/graph_traits.hpp>\n// #include <iostream> // for std::cout\n#include <utility> // for std::pair\n\n// using namespace boost;\ntemplate <class grAdaptor>\nstruct exercise_vertex\n{\n    //...\n    using Vertex = typename boost::graph_traits<grAdaptor>::vertex_descriptor;\n\n    explicit exercise_vertex(grAdaptor& g_)\n        : g(g_)\n    {\n    }\n    //...\n    grAdaptor& g;\n\n    auto operator()(const Vertex& v) const -> void\n    {\n        // typedef boost::graph_traits<Graph> GraphTraits;\n        // typename boost::property_map<Graph, boost::vertex_index_t>::type\n        // auto index = boost::get(boost::vertex_index, g);\n\n        // std::cout << \"out-edges: \";\n        // typename GraphTraits::out_edge_iterator out_i, out_end;\n        // typename GraphTraits::edge_descriptor e;\n        for ([[maybe_unused]] const auto& e : g.neighbors(v))\n        {\n            // auto [src, targ] = g.end_points(e);\n            // std::cout << \"(\" << index[src] << \",\" << index[targ] << \") \";\n        }\n        // std::cout << std::endl;\n    }\n    //...\n};\n\nTEST_CASE(\"Test Boost\")\n{\n    // create a typedef for the Graph type\n    using Graph =\n        boost::adjacency_list<boost::vecS, boost::vecS, boost::bidirectionalS>;\n\n    // Make convenient labels for the vertices\n    enum\n    {\n        A,\n        B,\n        C,\n        D,\n        E,\n        N\n    };\n    const auto num_vertices = N;\n    // const char *name = \"ABCDE\";\n\n    // writing out the edges in the graph\n    using Edge = std::pair<size_t, size_t>;\n    Edge edge_array[] = {Edge(A, B), Edge(A, D), Edge(C, A), Edge(D, C),\n        Edge(C, E), Edge(B, D), Edge(D, E)};\n    const auto num_edges = sizeof(edge_array) / sizeof(edge_array[0]);\n\n    // declare a graph object\n    Graph g(num_vertices);\n    xn::grAdaptor<Graph> G(std::move(g));\n    using Vertex = typename boost::graph_traits<Graph>::vertex_descriptor;\n    // using edge_t = typename boost::graph_traits<Graph>::edge_descriptor;\n\n    // add the edges to the graph object\n    for (auto i = 0; i != num_edges; ++i)\n    {\n        G.add_edge(edge_array[i].first, edge_array[i].second);\n    }\n\n    // typedef graph_traits<Graph>::vertex_descriptor Vertex;\n\n    // get the property map for vertex indices\n    // typedef property_map<Graph, vertex_index_t>::type IndexMap;\n    // auto index = boost::get(boost::vertex_index, G);\n\n    // std::cout << \"vertices(g) = \";\n    // typedef graph_traits<Graph>::vertex_iterator vertex_iter;\n    // std::pair<vertex_iter, vertex_iter> vp;\n    for ([[maybe_unused]] const Vertex& v : G)\n    {\n        // std::cout << index[v] << \" \";\n    }\n    // std::cout << std::endl;\n\n    // std::cout << \"edges(g) = \";\n    // graph_traits<Graph>::edge_iterator ei, ei_end;\n    // for (auto&& e : G.edges())\n    //     std::cout << \"(\" << index[boost::source(e, G)] << \",\"\n    //               << index[boost::target(e, G)] << \") \";\n    // std::cout << std::endl;\n\n    std::for_each(boost::vertices(G).first, boost::vertices(G).second,\n        exercise_vertex<xn::grAdaptor<Graph>>(G));\n}", "meta": {"hexsha": "0253a6d1e67aaf23f6bc5e577fce6be91c16b416", "size": 3232, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/test/src/test_boost.cpp", "max_stars_repo_name": "luk036/ellcpp", "max_stars_repo_head_hexsha": "3415e7ffb70b63edb9ce4d6c2b9fee92898538bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-07-26T04:58:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-26T06:29:59.000Z", "max_issues_repo_path": "lib/test/src/test_boost.cpp", "max_issues_repo_name": "luk036/ellcpp", "max_issues_repo_head_hexsha": "3415e7ffb70b63edb9ce4d6c2b9fee92898538bc", "max_issues_repo_licenses": ["MIT"], "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/test/src/test_boost.cpp", "max_forks_repo_name": "luk036/ellcpp", "max_forks_repo_head_hexsha": "3415e7ffb70b63edb9ce4d6c2b9fee92898538bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-06-03T08:20:20.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-30T10:41:49.000Z", "avg_line_length": 30.780952381, "max_line_length": 79, "alphanum_fraction": 0.5894183168, "num_tokens": 849, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389817407017, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.4561759230083187}}
{"text": "// (C) 2014 Arek Olek\n\n#pragma once\n\n#include <vector>\n\n#include <boost/graph/adjacency_list.hpp>\n\ntemplate <class Graph, class Tree>\nclass Ilst {\n  std::vector<bool> discovered;\n  unsigned conflicted, leaves;\n\n  void visit(Graph const & G, Tree & tree, unsigned v) {\n    discovered[v] = true;\n    for(auto w : range(adjacent_vertices(v, G))) {\n      if(!discovered[w]) {\n        add_edge(v, w, tree);\n        visit(G, tree, w);\n      }\n    }\n    if(out_degree(v, tree) == 1) {\n      ++leaves;\n      if(edge(0, v, G).second) {\n        conflicted = v;\n      }\n    }\n  }\n  std::pair<unsigned, unsigned> branch_edge(unsigned l, Tree const & tree) const {\n    unsigned a = l, b = l, tmp;\n    do {\n      auto it = adjacent_vertices(b, tree).first;\n      tmp = a;\n      a = b;\n      b = tmp == *it ? *(++it) : *it;\n    } while(out_degree(b, tree) == 2);\n    return std::make_pair(a, b);\n  }\npublic:\n  Ilst() : conflicted(0), leaves(0) {}\n\n  Tree traverse(Graph const & G) {\n    discovered.resize(num_vertices(G));\n    Tree tree(num_vertices(G));\n    visit(G, tree, 0);\n    if(leaves > 2 && out_degree(0, tree) == 1 && conflicted != 0) {\n      auto e = branch_edge(conflicted, tree);\n      add_edge(0, conflicted, tree);\n      remove_edge(e.first, e.second, tree);\n    }\n    return tree;\n  }\n};\n\ntemplate <class Graph, class Tree>\nTree ilst(Graph const & G) {\n  return Ilst<Graph, Tree>().traverse(G);\n}\n", "meta": {"hexsha": "601c24a6a5e9e1315df70a2c0e4642362e5f8ea3", "size": 1397, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "graph/ilst.hpp", "max_stars_repo_name": "arekolek/MaxIST", "max_stars_repo_head_hexsha": "6a8b49152cfbf34c1c2728f64b1457a23824fe0d", "max_stars_repo_licenses": ["MIT"], "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/ilst.hpp", "max_issues_repo_name": "arekolek/MaxIST", "max_issues_repo_head_hexsha": "6a8b49152cfbf34c1c2728f64b1457a23824fe0d", "max_issues_repo_licenses": ["MIT"], "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/ilst.hpp", "max_forks_repo_name": "arekolek/MaxIST", "max_forks_repo_head_hexsha": "6a8b49152cfbf34c1c2728f64b1457a23824fe0d", "max_forks_repo_licenses": ["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.6779661017, "max_line_length": 82, "alphanum_fraction": 0.5769506084, "num_tokens": 411, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721305, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4561437419367786}}
{"text": "#include <Eigen/Eigen>\n\n#include \"py4dgeo/compute.hpp\"\n#include \"py4dgeo/kdtree.hpp\"\n#include \"py4dgeo/openmp.hpp\"\n#include \"py4dgeo/py4dgeo.hpp\"\n\nnamespace py4dgeo {\n\nvoid\ncompute_distances(EigenPointCloudConstRef corepoints,\n                  double scale,\n                  const Epoch& epoch1,\n                  const Epoch& epoch2,\n                  EigenNormalSetConstRef directions,\n                  double max_cylinder_length,\n                  DistanceVector& distances,\n                  UncertaintyVector& uncertainties,\n                  const WorkingSetFinderCallback& workingsetfinder,\n                  const UncertaintyMeasureCallback& uncertaintycalculator)\n{\n  // Resize the output data structures\n  distances.resize(corepoints.rows());\n  uncertainties.resize(corepoints.rows());\n\n  // Instantiate a container for the first thrown exception in\n  // the following parallel region.\n  CallbackExceptionVault vault;\n#ifdef PY4DGEO_WITH_OPENMP\n#pragma omp parallel for schedule(dynamic, 1)\n#endif\n  for (IndexType i = 0; i < corepoints.rows(); ++i) {\n    vault.run([&]() {\n      // Either choose the ith row or the first (if there is no per-corepoint\n      // direction)\n      auto dir = directions.row(directions.rows() > 1 ? i : 0);\n\n      WorkingSetFinderParameters params1{\n        epoch1, scale, corepoints.row(i), dir, max_cylinder_length\n      };\n      auto subset1 = workingsetfinder(params1);\n      WorkingSetFinderParameters params2{\n        epoch2, scale, corepoints.row(i), dir, max_cylinder_length\n      };\n      auto subset2 = workingsetfinder(params2);\n\n      // Distance calculation\n      distances[i] = dir.dot(subset2.cast<double>().colwise().mean() -\n                             subset1.cast<double>().colwise().mean());\n\n      // Uncertainty calculation\n      UncertaintyMeasureParameters uc_params{ subset1, subset2, dir };\n      uncertainties[i] = uncertaintycalculator(uc_params);\n    });\n  }\n\n  // Potentially rethrow an exception that occurred in above parallel region\n  vault.rethrow();\n}\n\nEigenPointCloud\nradius_workingset_finder(const WorkingSetFinderParameters& params)\n{\n  // Find the working set in the other epoch\n  KDTree::RadiusSearchResult points;\n  params.epoch.kdtree.radius_search(\n    params.corepoint.data(), params.radius, points);\n  return params.epoch.cloud(points, Eigen::all);\n}\n\nEigenPointCloud\ncylinder_workingset_finder(const WorkingSetFinderParameters& params)\n{\n  // Cut the cylinder into N segments, perform radius searches around the\n  // segment midpoints and create the union of indices. Afterwards, select\n  // only those points that are within the cylinder\n\n  // The number of segments - later cast to int\n  double N = 1.0;\n  double cylinder_length = params.cylinder_length;\n  if (cylinder_length > params.radius)\n    N = std::ceil(cylinder_length / params.radius);\n  else\n    cylinder_length = params.radius;\n\n  // The search radius for each segment\n  double r_cyl = std::sqrt(params.radius * params.radius +\n                           cylinder_length * cylinder_length / (N * N));\n\n  // Perform radius searches and merge results\n  std::vector<IndexType> merged;\n  for (std::size_t i = 0; i < static_cast<std::size_t>(N); ++i) {\n    auto qp = (params.corepoint.row(0) +\n               (static_cast<float>(2 * i + 1 - N) / static_cast<float>(N)) *\n                 static_cast<float>(cylinder_length) *\n                 params.cylinder_axis.cast<float>().row(0))\n                .eval();\n    KDTree::RadiusSearchResult ball_points;\n    params.epoch.kdtree.radius_search(&(qp(0, 0)), r_cyl, ball_points);\n    merged.reserve(merged.capacity() + ball_points.size());\n\n    // Extracting points\n    auto superset = params.epoch.cloud(ball_points, Eigen::all);\n\n    // Calculate the squared distances to the cylinder axis and to the plane\n    // perpendicular to the axis that contains the corepoint\n    auto to_midpoint =\n      (superset.cast<double>().rowwise() - qp.cast<double>().row(0)).eval();\n    auto to_midpoint_plane =\n      (to_midpoint * params.cylinder_axis.transpose()).eval();\n    auto to_axis2 = (to_midpoint - to_midpoint_plane * params.cylinder_axis)\n                      .rowwise()\n                      .squaredNorm()\n                      .eval();\n\n    // Non-performance oriented version of index extraction. There should\n    // be a version using Eigen masks, but I could not find it.\n    for (Eigen::Index i = 0; i < superset.rows(); ++i)\n      if ((to_axis2(i) <= params.radius * params.radius) &&\n          (std::abs(to_midpoint_plane(i)) <= (cylinder_length / N)))\n        merged.push_back(ball_points[i]);\n  }\n\n  // Select only those indices that are within the cylinder\n  return params.epoch.cloud(merged, Eigen::all);\n}\n\ndouble\nvariance(EigenPointCloudConstRef subset, EigenNormalSetConstRef direction)\n{\n  auto centered =\n    subset.cast<double>().rowwise() - subset.cast<double>().colwise().mean();\n  auto cov = (centered.adjoint() * centered) / double(subset.rows() - 1);\n  auto multiplied = direction.row(0) * cov * direction.row(0).transpose();\n  return multiplied.eval()(0, 0);\n}\n\nDistanceUncertainty\nstandard_deviation_uncertainty(const UncertaintyMeasureParameters& params)\n{\n  double variance1 = variance(params.workingset1, params.normal);\n  double variance2 = variance(params.workingset2, params.normal);\n\n  // Calculate the standard deviations for both point clouds\n  double stddev1 = std::sqrt(variance1);\n  double stddev2 = std::sqrt(variance2);\n\n  // Calculate the level of  from above variances\n  double lodetection =\n    1.96 *\n    std::sqrt(variance1 / static_cast<double>(params.workingset1.rows()) +\n              variance2 / static_cast<double>(params.workingset2.rows()));\n\n  return DistanceUncertainty{ lodetection,\n                              stddev1,\n                              params.workingset1.rows(),\n                              stddev2,\n                              params.workingset2.rows() };\n}\n\n} // namespace py4dgeo\n", "meta": {"hexsha": "0109f8d863d35550010a568badbfc8d04e4b7751", "size": 5955, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/distances.cpp", "max_stars_repo_name": "ssciwr/geolib4d", "max_stars_repo_head_hexsha": "dd79a746559235e47c2cb5e7c7ba71ef3ae21e29", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2022-01-28T14:18:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T21:52:43.000Z", "max_issues_repo_path": "lib/distances.cpp", "max_issues_repo_name": "ssciwr/geolib4d", "max_issues_repo_head_hexsha": "dd79a746559235e47c2cb5e7c7ba71ef3ae21e29", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 104.0, "max_issues_repo_issues_event_min_datetime": "2021-06-18T14:10:37.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T06:12:58.000Z", "max_forks_repo_path": "lib/distances.cpp", "max_forks_repo_name": "ssciwr/py4dgeo", "max_forks_repo_head_hexsha": "dd79a746559235e47c2cb5e7c7ba71ef3ae21e29", "max_forks_repo_licenses": ["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.7592592593, "max_line_length": 77, "alphanum_fraction": 0.6639798489, "num_tokens": 1357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.5888891307678321, "lm_q1q2_score": 0.4561437358080874}}
{"text": "#include <math.h>\n#include <iostream>\n#include <map>\n\n#include <Eigen/Dense>\n#include \"visualization/opengl.hh\"\n\n#include \"sensing/belief.hh\"\n#include \"sensing/rendering.hh\"\n\n#include \"geometry/circle.hh\"\n#include \"geometry/geometry.hh\"\n#include \"geometry/line.hh\"\n#include \"geometry/plane.hh\"\n\n#include \"types.hh\"\n#include \"visualization/gl_shapes.hh\"\n\n#include <sophus/se3.hpp>\n\nenum ManipulationMode : int16_t {\n  kNORMAL,  // Manipulate the camera view\n  kSONAR    // Manipulate the sonar view\n};\n\nstruct SonarParams {\n  float max_bearing   = 1.1f;  // Max bearing for the sonar view\n  float max_elevation = 0.2f;  // Max elevation for the sonar view\n};\n\nstruct State {\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n\n  /////////////////////////////////////////////////////////////////////////////////////////////////\n  // Lighting configuration\n  //\n\n  GLfloat light_ambient[4]  = {0.2f, 0.2f, 0.2f, 1.0f};\n  GLfloat light_diffuse[4]  = {0.5f, 0.5f, 0.5f, 1.0f};\n  GLfloat light_position[4] = {5.0f, 5.0f, -10.0f, 1.0f};\n  GLfloat mat_specular[4]   = {0.2f, 0.2f, 0.2f, 1.0f};\n\n  /////////////////////////////////////////////////////////////////////////////////////////////////\n  // View configuration\n  //\n  bool use_orthographic_projection = false;\n\n  /////////////////////////////////////////////////////////////////////////////////////////////////\n  // Camera pose\n  //\n\n  // Camera position management\n  float velocity_scaling         = 0.01f;\n  float angular_velocity_scaling = 0.002f;\n\n  float           view_velocity_decay = 0.9f;\n  Eigen::Vector3f view_velocity       = Eigen::Vector3f::Zero();\n\n  // Camera orientation management\n  float           view_rotation_decay   = 0.9f;\n  Eigen::Vector3f view_angular_velocity = Eigen::Vector3f::Zero();\n  se3             view_pose             = se3(Eigen::Matrix3f::Identity(), Eigen::Vector3f::Zero());\n\n  /////////////////////////////////////////////////////////////////////////////////////////////////\n  // Sonar state\n  //\n\n  se3         sonar_pose = se3(Eigen::Matrix3f::Identity(), Eigen::Vector3f::Zero());\n  SonarParams sonar_params;\n\n  /////////////////////////////////////////////////////////////////////////////////////////////////\n  // Belief state\n  //\n  std::vector<sonder::circular_section> sections;\n  sonder::IntersectionVotes             intersection_estimates;\n  // PointList                             intersection_estimates;\n  // std::vector<int>                      votes;\n\n  /////////////////////////////////////////////////////////////////////////////////////////////////\n  // View State\n  //\n\n  // Fixed width/height\n  int width = 800;\n\n  /////////////////////////////////////////////////////////////////////////////////////////////////\n  // Input state\n  //\n\n  // Store which object we are manipulating\n  ManipulationMode manipulation_mode = ManipulationMode::kNORMAL;\n\n  // This list is also the precedence ordering for single-input commands\n  bool left_mouse_held   = false;\n  bool right_mouse_held  = false;\n  bool scroll_mouse_held = false;\n\n  // Store mouse state to compute relative motion\n  Eigen::Vector2f mouse_down_screen_pos    = Eigen::Vector2f(0.0f, 0.0f);\n  Eigen::Vector2f mouse_current_screen_pos = Eigen::Vector2f(0.0f, 0.0f);\n\n  // Store pose states to apply relative motions\n  se3 view_pose_at_start  = se3(Eigen::Matrix3f::Identity(), Eigen::Vector3f::Zero());\n  se3 sonar_pose_at_start = se3(Eigen::Matrix3f::Identity(), Eigen::Vector3f::Zero());\n  se3 last_capture_pose   = se3(Eigen::Matrix3f::Random(), Eigen::Vector3f::Random());\n\n  // Keys\n  std::map<unsigned char, bool> held_keys;\n  std::map<int, bool>           held_specials;\n};\n\n// Instantiate program global state\nState gstate;\n\n// Step forward the camera physics\nvoid view_physics() {\n  //\n  // view_Orientation decay\n  //\n  // Build a rotation matrix from that\n  gstate.view_pose.so3() = so3::exp(gstate.view_angular_velocity) * gstate.view_pose.so3();\n\n  // Apply decay\n  gstate.view_angular_velocity = gstate.view_rotation_decay * gstate.view_angular_velocity;\n\n  //\n  // Translation decay\n  //\n  gstate.view_pose.translation() += gstate.view_velocity;\n  gstate.view_velocity *= gstate.view_velocity_decay;\n}\n\n// Trigger a draw event, step forward camera physics\nstatic void timer_event(const int te) {\n  glutTimerFunc(10, timer_event, 1);\n  view_physics();\n\n  Eigen::Vector3f view_acceleration(0.0f, 0.0f, 0.0f);\n  Eigen::Vector3f view_angular_acceleration(0.0f, 0.0f, 0.0f);\n\n  //\n  // Handle normal keys that are currently held down\n  //\n  for (const auto &key_el : gstate.held_keys) {\n    if (!key_el.second) {\n      // Skip if key not held\n      continue;\n    }\n    switch (key_el.first) {\n      case 27:\n        glutDestroyWindow(glutGetWindow());\n        return;\n\n      case 'w':\n        view_acceleration += Eigen::Vector3f(0.0f, 0.0f, gstate.velocity_scaling);\n        break;\n\n      case 'a':\n        view_acceleration += Eigen::Vector3f(gstate.velocity_scaling, 0.0f, 0.0f);\n        break;\n\n      case 's':\n        view_acceleration += Eigen::Vector3f(0.0f, 0.0f, -gstate.velocity_scaling);\n        break;\n\n      case 'd':\n        view_acceleration += Eigen::Vector3f(-gstate.velocity_scaling, 0.0f, 0.0f);\n        break;\n\n      case 'c':\n        view_acceleration += Eigen::Vector3f(0.0f, -gstate.velocity_scaling, 0.0f);\n        break;\n\n      case 'z':\n        view_acceleration += Eigen::Vector3f(0.0f, gstate.velocity_scaling, 0.0f);\n        break;\n\n      case 'q':\n        view_angular_acceleration += -Eigen::Vector3f(0.0f, 0.0f, 1.0f);\n        break;\n\n      case 'e':\n        view_angular_acceleration += Eigen::Vector3f(0.0f, 0.0f, 1.0f);\n        break;\n\n      default:\n        break;\n    }\n  }\n\n  // Transform \"thrust\" from view frame to world frame\n  // (Must force evaluation)\n  const Eigen::Vector3f delta = gstate.view_pose.so3().inverse() * view_acceleration;\n  gstate.view_velocity += delta;\n\n  //\n  // Handle special keys that are currently held down\n  //\n  for (const auto &special_key_el : gstate.held_specials) {\n    if (!special_key_el.second) {\n      // Skip if key not held\n      continue;\n    }\n\n    switch (special_key_el.first) {\n      case GLUT_KEY_LEFT: {\n        view_angular_acceleration += -Eigen::Vector3f(0.0f, 1.0f, 0.0f);\n      } break;\n\n      case GLUT_KEY_RIGHT: {\n        view_angular_acceleration += Eigen::Vector3f(0.0f, 1.0f, 0.0f);\n\n      } break;\n\n      case GLUT_KEY_UP: {\n        view_angular_acceleration += Eigen::Vector3f(1.0f, 0.0f, 0.0f);\n\n      } break;\n\n      case GLUT_KEY_DOWN: {\n        view_angular_acceleration += -Eigen::Vector3f(1.0f, 0.0f, 0.0f);\n\n      } break;\n\n      default:\n        break;\n    }\n  }\n  gstate.view_angular_velocity += gstate.angular_velocity_scaling * view_angular_acceleration;\n\n  glutPostRedisplay();\n}\n\n/////////////////////////////////////////////////////////////////////////////////////////////////\n// Initialization\n/////////////////////////////////////////////////////////////////////////////////////////////////\n\n// Setup our Opengl world, called once at startup.\nvoid default_init() {\n  // When screen cleared, use black.\n  glClearColor(0.2f, 0.2f, 0.2f, 0.0f);\n\n  // How the object color will be rendered smooth or flat\n  glShadeModel(GL_SMOOTH);\n\n  // Check depth when rendering\n  glEnable(GL_DEPTH_TEST);\n\n  // Lighting is added to scene\n  glLightfv(GL_LIGHT1, GL_AMBIENT, gstate.light_ambient);\n  glLightfv(GL_LIGHT1, GL_DIFFUSE, gstate.light_diffuse);\n  glLightfv(GL_LIGHT1, GL_POSITION, gstate.light_position);\n\n  // Turn on lighting\n  glEnable(GL_LIGHTING);\n\n  // Turn on light 1\n  glEnable(GL_LIGHT1);\n\n  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n  glEnable(GL_BLEND);\n}\n\n/////////////////////////////////////////////////////////////////////////////////////////////////\n// Callbacks\n/////////////////////////////////////////////////////////////////////////////////////////////////\n\nvoid process_keyboard(unsigned char key, int x, int y, bool held) {\n  //\n  // Handle single-touch input keys (No special behavior if held down)\n  //\n  if (held) {\n    switch (key) {\n      case 'p':\n        std::cout << \"Switching projection mode\" << std::endl;\n        gstate.use_orthographic_projection = !gstate.use_orthographic_projection;\n        break;\n\n      case 'P':\n        std::cout << \"Pose::\" << std::endl;\n        std::cout << gstate.view_pose.translation().transpose() << std::endl;\n        std::cout << gstate.view_pose.rotationMatrix() << std::endl;\n\n      case 'v':\n        if (gstate.manipulation_mode == ManipulationMode::kNORMAL) {\n          gstate.manipulation_mode = ManipulationMode::kSONAR;\n          std::cout << \"Switching mode to sonar\" << std::endl;\n        } else {\n          gstate.manipulation_mode = ManipulationMode::kNORMAL;\n          std::cout << \"Switching mode to normal\" << std::endl;\n        }\n        break;\n\n      case 'G':\n        std::cout << \"Clearing observation history\" << std::endl;\n        gstate.sections.clear();\n        gstate.intersection_estimates.clear();\n        break;\n\n      case 'Q':\n        std::cout << \"Attempting to exit\" << std::endl;\n        glutDestroyWindow(glutGetWindow());\n        return;\n    }\n  }\n  gstate.held_keys[key] = held;\n  glutPostRedisplay();\n}\nvoid keyboard_down(unsigned char key, int x, int y) {\n  process_keyboard(key, x, y, true);\n}\nvoid keyboard_up(unsigned char key, int x, int y) {\n  process_keyboard(key, x, y, false);\n}\n\nvoid process_special_keys(const int key, const int x, const int y, bool held) {\n  gstate.held_specials[key] = held;\n}\nvoid special_keys_down(const int key, const int x, const int y) {\n  process_special_keys(key, x, y, true);\n}\nvoid special_keys_up(const int key, const int x, const int y) {\n  process_special_keys(key, x, y, false);\n}\n\n/////////////////////////////////////////////////////////////////////////////////////////////////\n// Mouse motion callbacks\n/////////////////////////////////////////////////////////////////////////////////////////////////\n\nvoid held_mouse_motion(const int x, const int y) {\n  const Eigen::Vector2f pos       = Eigen::Vector2f(static_cast<float>(x), static_cast<float>(y)) / gstate.width;\n  gstate.mouse_current_screen_pos = pos;\n\n  const Eigen::Vector2f relative_motion = pos - gstate.mouse_down_screen_pos;\n\n  if (gstate.right_mouse_held) {\n    //\n    // Right mouse drag\n    //\n    // Locally perturb something by treating mouse motion as a left-tangent scaling\n\n    const so3::Tangent w(relative_motion.y(), relative_motion.x(), 0.0f);\n    const auto         perturbation = so3::exp(w / 1.0f);\n\n    //\n    // Manipulate orientation of the selected object (View or sonar head)\n    //\n    if (gstate.manipulation_mode == ManipulationMode::kNORMAL) {\n      gstate.view_pose.so3() = perturbation * gstate.view_pose_at_start.so3();\n\n    } else if (gstate.manipulation_mode == ManipulationMode::kSONAR) {\n      // Transform the perturbation so that it appears to happen relative to our own view\n      const so3 view_orientation                  = gstate.view_pose.so3();\n      const so3 perturbation_apparent_local_frame = view_orientation.inverse() * perturbation * view_orientation;\n\n      gstate.sonar_pose.so3() = perturbation_apparent_local_frame * gstate.sonar_pose_at_start.so3();\n    }\n\n  } else if (gstate.left_mouse_held) {\n    //\n    // Left mouse drag\n    //\n    // Second in precedence ordering\n\n    // Get movement in screen coordinates\n    const Eigen::Vector3f expressed_motion(relative_motion.x(), -relative_motion.y(), 0.0f);\n\n    // Transform screen motion into world motion\n    const Eigen::Vector3f delta = gstate.view_pose.rotationMatrix().transpose() * (5.0 * expressed_motion);\n\n    //\n    // Manipulate translation of the selected object (View or sonar head)\n    //\n    if (gstate.manipulation_mode == ManipulationMode::kNORMAL) {\n      gstate.view_pose.translation() = delta + gstate.view_pose_at_start.translation();\n\n    } else if (gstate.manipulation_mode == ManipulationMode::kSONAR) {\n      gstate.sonar_pose.translation() = delta + gstate.sonar_pose_at_start.translation();\n    }\n  }\n\n  glutPostRedisplay();\n}\n\nvoid update_mouse_state(const int button, const bool held) {\n  switch (button) {\n    case 0:\n      gstate.left_mouse_held = held;\n      break;\n    case 1:\n      gstate.scroll_mouse_held = held;\n      break;\n    case 2:\n      gstate.right_mouse_held = held;\n      break;\n    default:\n      break;\n  }\n}\n\nvoid mouse(const int button, const int state, const int x, const int y) {\n  const Eigen::Vector2f pos = Eigen::Vector2f(static_cast<float>(x), static_cast<float>(y)) / gstate.width;\n  update_mouse_state(button, state == GLUT_DOWN);\n\n  //\n  // Handle storing state for a mouse press\n  //\n  if (state == GLUT_DOWN) {\n    gstate.mouse_down_screen_pos    = pos;\n    gstate.mouse_current_screen_pos = pos;\n\n    gstate.view_pose_at_start  = gstate.view_pose;\n    gstate.sonar_pose_at_start = gstate.sonar_pose;\n\n  } else if (state == GLUT_UP) {\n    gstate.mouse_down_screen_pos    = pos;\n    gstate.mouse_current_screen_pos = pos;\n  }\n\n  //\n  // Handle scroll-wheel events\n  //\n  if ((button == 3) || (button == 4)) {\n    if (state == GLUT_UP) {\n      return;\n    }\n\n    // The direction is governed which direction the wheel is being turned\n    const float direction = (button == 3) ? 1.0f : -1.0f;\n\n    // Project the motion in screen coordinates into world coordinates\n    const Eigen::Vector3f delta    = gstate.view_pose.so3().inverse() * Eigen::Vector3f::UnitZ() * direction;\n    gstate.view_pose.translation() = gstate.view_pose.translation() + delta;\n  }\n}\n\n/////////////////////////////////////////////////////////////////////////////////////////////////\n// Display\n/////////////////////////////////////////////////////////////////////////////////////////////////\n\nvoid draw_sonar_data() {\n  //\n  // Rendering a field of points\n  //\n\n  // Minimum constants for updating the belief\n  constexpr float MIN_TRANSLATION = 0.5f;\n  constexpr float MIN_ROTATION    = 0.4f;\n\n  {\n    const PointList                     plane         = sonder::sim::make_plane_blanket();\n    const EigStdVector<Eigen::Vector2f> range_bearing = sonder::sim::to_range_bearing(\n        plane, gstate.sonar_pose, gstate.sonar_params.max_bearing, gstate.sonar_params.max_elevation);\n\n    if (false) {\n      for (const auto &pt : plane) {\n        sonder::draw_point(pt, 0.1f);\n      }\n    }\n\n    const float delta_position = (gstate.last_capture_pose.translation() - gstate.sonar_pose.translation()).norm();\n    const float delta_orientation =\n        (so3::log(gstate.last_capture_pose.so3() * gstate.sonar_pose.so3().inverse())).norm();\n\n    if ((delta_position > MIN_TRANSLATION) || (delta_orientation > MIN_ROTATION)) {\n      gstate.last_capture_pose = gstate.sonar_pose;\n\n      for (const auto &rb : range_bearing) {\n        Eigen::AngleAxisf rotation(rb.y(), Eigen::Vector3f::UnitZ());\n\n        const Eigen::Vector3f normal =\n            gstate.sonar_pose.rotationMatrix() * rotation.toRotationMatrix() * Eigen::Vector3f::UnitY();\n        const Eigen::Vector3f direction =\n            gstate.sonar_pose.rotationMatrix() * rotation.toRotationMatrix() * Eigen::Vector3f::UnitX();\n\n        const sonder::circular_section circ_sec(direction, normal, gstate.sonar_pose.translation(), rb.x(),\n                                                2.0f * gstate.sonar_params.max_elevation);\n\n        gstate.sections.push_back(circ_sec);\n\n        const sonder::IntersectionVotes intersections = sonder::intersect_all_sections(circ_sec, gstate.sections);\n        sonder::add_points(intersections, out(gstate.intersection_estimates));\n      }\n    }\n  }\n\n  glColor3f(0.0f, 0.7f, 0.1f);\n  for (const auto &circ_sec : gstate.sections) {\n    sonder::draw_circular_section(circ_sec);\n  }\n\n  glColor4f(0.5f, 0.7f, 0.1f, 0.4f);\n  for (const auto &circ_sec : gstate.sections) {\n    sonder::draw_circle(circ_sec.spanning_circle);\n  }\n  if (true) {\n    const float max_vote = gstate.intersection_estimates.max_votes();\n    for (std::size_t k = 0; k < gstate.intersection_estimates.points.size(); ++k) {\n      glColor4f(0.0f, 0.4f, 0.8f, gstate.intersection_estimates.votes[k] / max_vote);\n      const Eigen::Vector3f &pt = gstate.intersection_estimates.points[k];\n      sonder::draw_point(pt, 0.05f);\n    }\n  }\n\n  //\n  // Render the sonar viewing frustum\n  //\n  // This is not the real limits of the sonar view, but makes a reasonable approximation\n  sonder::draw_sonar_view(gstate.sonar_pose, gstate.sonar_params.max_bearing, gstate.sonar_params.max_elevation);\n}\n\nvoid display() {\n  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n  glEnable(GL_LINE_SMOOTH);\n  glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);\n\n  glMatrixMode(GL_PROJECTION);\n  glLoadIdentity();\n  if (gstate.use_orthographic_projection) {\n    glOrtho(-16.0f, 16.0f, -16.0f, 16.0f, 0.0f, 30.0f);\n  } else {\n    gluPerspective(60.0f, 1.0f, 1.0f, 1000.0f);\n  }\n\n  //\n  // Set up the current view\n  //\n  glMatrixMode(GL_MODELVIEW);\n  glLoadIdentity();\n  Eigen::Quaternionf q(gstate.view_pose.unit_quaternion());\n  glRotate(q);\n  glTranslate(gstate.view_pose.translation());\n\n  //\n  // Enable lighting & material settings\n  //\n  if (true) {\n    glDisable(GL_LIGHTING);\n    glDisable(GL_COLOR_MATERIAL);\n\n  } else {\n    glEnable(GL_LIGHTING);\n    glEnable(GL_COLOR_MATERIAL);\n    glColorMaterial(GL_FRONT, GL_AMBIENT);\n    glColor4f(0.65f, 0.65f, 0.65f, 0.4f);\n    glColorMaterial(GL_FRONT, GL_EMISSION);\n    glColor4f(0.10f, 0.10f, 0.10f, 0.0f);\n    glColorMaterial(GL_FRONT, GL_SPECULAR);\n    glColor4f(0.5f, 0.5f, 0.5f, 0.4f);\n    glColorMaterial(GL_FRONT, GL_DIFFUSE);\n    glColor4f(0.85f, 0.85f, 0.85f, 0.4f);\n  }\n\n  //\n  // Draw the universal origin\n  //\n  sonder::draw_coordinate_system();\n\n  //\n  // Draw the sonar and sonar related nonsense\n  //\n  draw_sonar_data();\n\n  // Draw on the \"HUD\" as it were, with a second mvp setup\n  {\n    glMatrixMode(GL_PROJECTION);\n    glLoadIdentity();\n    glOrtho(0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f);\n\n    glMatrixMode(GL_MODELVIEW);\n    glLoadIdentity();\n\n    sonder::draw_line2d(gstate.mouse_down_screen_pos, gstate.mouse_current_screen_pos);\n  }\n\n  glutSwapBuffers();\n}\n\nvoid reshape(int w, int h) {\n  int size = std::max(w, h);\n  glViewport(0, 0, (GLsizei)size, (GLsizei)size);\n  glutReshapeWindow(size, size);\n\n  gstate.width = size;\n\n  glMatrixMode(GL_PROJECTION);\n  glLoadIdentity();\n}\n\nint main(int argc, char **argv) {\n  glutInit(&argc, argv);\n  glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);\n\n  // Square\n  glutInitWindowSize(gstate.width, gstate.width);\n  glutInitWindowPosition(10, 10);\n  glutTimerFunc(10, timer_event, 1);\n\n  int discrete_belief_view = glutCreateWindow(argv[0]);\n  glutSetWindowTitle(\"Sonder -- Discrete Belief View\");\n  default_init();\n\n  //\n  // Standard GLUT functions\n  //\n  glutDisplayFunc(display);\n  glutReshapeFunc(reshape);\n\n  //\n  // Input\n  //\n  glutKeyboardFunc(keyboard_down);\n  glutKeyboardUpFunc(keyboard_up);\n\n  glutKeyboardUpFunc(keyboard_up);\n  glutSpecialFunc(special_keys_down);\n  glutSpecialUpFunc(special_keys_up);\n  glutMouseFunc(mouse);\n\n  // Active motion\n  glutMotionFunc(held_mouse_motion);\n\n  //\n  // View Initialization\n  //\n  const Eigen::Matrix3f view_orientation = (Eigen::Matrix3f() << 0.978117, 0.207935, -0.00695645, 0.006618, 0.00232671,\n                                            0.999976, 0.207946, -0.978139, 0.000898672)\n                                               .finished();\n  const Eigen::Vector3f view_position(-1.40469, 6.51158, -0.350347);\n\n  gstate.view_pose = se3(view_orientation, view_position);\n\n  std::cout << \"Starting viewer\" << std::endl;\n  glutMainLoop();\n  std::cout << \"Ending main loop\" << std::endl;\n  return 0;\n}", "meta": {"hexsha": "d22d99ba73668542bb1a97b311c61bf49834ae66", "size": 19604, "ext": "cc", "lang": "C++", "max_stars_repo_path": "sonder/src/main.cc", "max_stars_repo_name": "jpanikulam/sonder", "max_stars_repo_head_hexsha": "ff3eece5f6a31d3bb2573d0e3e6dd5dafec7ffda", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-24T07:52:39.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-24T07:52:39.000Z", "max_issues_repo_path": "sonder/src/main.cc", "max_issues_repo_name": "jpanikulam/sonder", "max_issues_repo_head_hexsha": "ff3eece5f6a31d3bb2573d0e3e6dd5dafec7ffda", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sonder/src/main.cc", "max_forks_repo_name": "jpanikulam/sonder", "max_forks_repo_head_hexsha": "ff3eece5f6a31d3bb2573d0e3e6dd5dafec7ffda", "max_forks_repo_licenses": ["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.7755102041, "max_line_length": 119, "alphanum_fraction": 0.6147724954, "num_tokens": 5161, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.45614373580808737}}
{"text": "/***********************************************************************\nThis file is part of the librjmcmc project source files.\n\nCopyright : Institut Geographique National (2008-2012)\nContributors : Mathieu Br\u00e9dif, Olivier Tournaire, Didier Boldo\nemail : librjmcmc@ign.fr\n\nThis software is a generic C++ library for stochastic optimization.\n\nThis software is governed by the CeCILL license under French law and\nabiding by the rules of distribution of free software. You can use,\nmodify and/or redistribute the software under the terms of the CeCILL\nlicense as circulated by CEA, CNRS and INRIA at the following URL\n\"http://www.cecill.info\".\n\nAs a counterpart to the access to the source code and rights to copy,\nmodify and redistribute granted by the license, users are provided only\nwith a limited warranty and the software's author, the holder of the\neconomic rights, and the successive licensors have only limited liability.\n\nIn this respect, the user's attention is drawn to the risks associated\nwith loading, using, modifying and/or developing or reproducing the\nsoftware by the user in light of its specific status of free software,\nthat may mean that it is complicated to manipulate, and that also\ntherefore means that it is reserved for developers and experienced\nprofessionals having in-depth computer knowledge. Users are therefore\nencouraged to load and test thesoftware's suitability as regards their\nrequirements in conditions enabling the security of their systems and/or\ndata to be ensured and, more generally, to use and operate it in the\nsame conditions as regards security.\n\nThe fact that you are presently reading this means that you have had\nknowledge of the CeCILL license and that you accept its terms.\n\n***********************************************************************/\n\n#ifndef MPP_UNIFORM_VIEW_HPP\n#define MPP_UNIFORM_VIEW_HPP\n\n#include <boost/random/uniform_smallint.hpp>\n\n#include \"rjmcmc/geometry/coordinates/coordinates.hpp\"\n\nnamespace marked_point_process {\n    \n\n    // single object type configuration for now...\n    template<typename T, unsigned int N=1>\n    class uniform_view\n    {\n        object_from_coordinates<T> creator;\n    public:\n        typedef T object_type;\n        enum { dimension =  coordinates_iterator<T>::dimension };\n\n        template<typename Engine, typename Configuration, typename Modification, typename OutputIterator>\n        inline double operator()(Engine& e, Configuration const& c, Modification& m, OutputIterator out) const\n        {\n            m.death().clear();\n            typedef typename coordinates_iterator<T>::type iterator;\n            unsigned int n = c.size();\n            if(n<N) return 0.;\n            unsigned int denom=1;\n            int d[N];\n            for(unsigned int i=0 ; i<N ; ++i,--n)\n            {\n                boost::uniform_smallint<> die(0,n-1);\n                d[i]=die(e);\n                for(unsigned int j=0;j<i;++j) if(d[j]<=d[i]) ++d[i]; // skip already selected indices\n\n                typename Configuration::const_iterator it = c.begin();\n                std::advance(it, d[i]);\n                m.death().push_back(it);\n                const T& t = c.value(it);\n                iterator coord_it  = coordinates_begin(t,e);\n                for(unsigned int j=0; j<dimension; ++j) *out++ = *coord_it++;\n                denom *= n;\n            }\n            return 1./denom;\n        }\n        template<typename Configuration, typename Modification, typename InputIterator>\n        inline double inverse_pdf(Configuration const& c, Modification& m, InputIterator it) const\n        {\n            m.birth().clear();\n            unsigned int beg   = c.size()-m.death().size()+1;\n            unsigned int end   = beg+N;\n            unsigned int denom = 1;\n            for(unsigned int n=beg ; n<end ; ++n)\n            {\n                m.birth().push_back(creator(it));\n                it    += dimension;\n                denom *= n;\n            }\n            return 1./denom;\n        }\n    };\n\n}; // namespace marked_point_process\n\n#endif // UNIFORM_VIEW_HPP\n", "meta": {"hexsha": "acc86405dd64e6ffc7d7725588bd0c6db450e328", "size": 4066, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/rjmcmc/mpp/kernel/uniform_view.hpp", "max_stars_repo_name": "qc2105/librjmcmc", "max_stars_repo_head_hexsha": "6e031a9f6f3612394f8918c745700ae41d2aa586", "max_stars_repo_licenses": ["CECILL-B"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2015-02-17T17:07:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-02T16:49:02.000Z", "max_issues_repo_path": "include/rjmcmc/mpp/kernel/uniform_view.hpp", "max_issues_repo_name": "qc2105/librjmcmc", "max_issues_repo_head_hexsha": "6e031a9f6f3612394f8918c745700ae41d2aa586", "max_issues_repo_licenses": ["CECILL-B"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2015-09-24T09:39:33.000Z", "max_issues_repo_issues_event_max_datetime": "2016-01-03T13:22:49.000Z", "max_forks_repo_path": "include/rjmcmc/mpp/kernel/uniform_view.hpp", "max_forks_repo_name": "qc2105/librjmcmc", "max_forks_repo_head_hexsha": "6e031a9f6f3612394f8918c745700ae41d2aa586", "max_forks_repo_licenses": ["CECILL-B"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2015-03-18T17:32:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-04T21:38:16.000Z", "avg_line_length": 40.2574257426, "max_line_length": 110, "alphanum_fraction": 0.6382193802, "num_tokens": 839, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.45614373580808737}}
{"text": "#include \"RCameraPoseEstimation.h\"\n\n#include <Eigen/Core>\n\n#include <opencv2/calib3d/calib3d.hpp>\n#include <opencv2/core/eigen.hpp>\n\n#include \"theia/sfm/pose/perspective_three_point.h\"\n#include \"theia/sfm/pose/dls_pnp.h\"\n\n#include \"rce/geometry/RGeometry.h\"\n\n//#ifdef RCE_NO_INFO_OUTPUT\n//#undef RCE_NO_INFO_OUTPUT\n//#endif\n\n#include \"dfs/core/DDebug.h\"\n#include \"rce/utility/ROpenCVtoQDebug.h\"\n\n\n#ifndef RCE_POSE_MAX_DISTANCE_TO_SCENE\n#define RCE_POSE_MAX_DISTANCE_TO_SCENE (10000)\n#endif\n\n\n\n\n\nvoid\nrce::geometry::RCameraPoseEstimation::\nestimateCameraPose(const cv::Mat &cameraMatrix,\n                   const cv::Mat &homographyFromWorldToImage,\n                   const cv::Point3d &pointInFrontOfCamera,\n                   std::vector<cv::Point3d> &positions,\n                   std::vector<cv::Mat> &rotations,\n                   std::vector<cv::Point3d> &headingVectors,\n                   std::vector<cv::Point3d> &toSceneVectors,\n                   bool leftHandedCoordinateSystem,\n                   bool filterSolutions,\n                   bool useAllMethods)\n{\n    cv::Mat H = getCleanHomography(cameraMatrix,\n                                   homographyFromWorldToImage,\n                                   leftHandedCoordinateSystem);\n\n\n    // firstly, dissect homographyFromWorldToImage to transformation between world plane and projection plane\n    cv::Mat cameraMatrixInv = cameraMatrix.inv();\n\n    std::vector<cv::Point3d> candidatePositions;\n    std::vector<cv::Mat> candidateRotations;\n\n    estimatePoseNADIRApproach(H,\n                              candidatePositions,\n                              candidateRotations);\n\n    if(useAllMethods)\n    {\n        // the simplest algorithm:\n        estimatePoseBetweenSimple(H,\n                                  candidatePositions,\n                                  candidateRotations);\n\n        // the dumbest algorithm\n        estimatePoseBetweenDumb(H,\n                                candidatePositions,\n                                candidateRotations);\n\n        // opencv algorithm\n        estimatePoseBetweenCVHomography(H,\n                                        candidatePositions,\n                                        candidateRotations);\n\n        // opencv algorithm 2\n        estimatePoseBetweenImagesCVHomography(cameraMatrixInv * homographyFromWorldToImage,\n                                              cameraMatrix,\n                                              candidatePositions,\n                                              candidateRotations);\n    }\n\n\n    // from theia library\n    estimatePoseFromHomographyTheiaPNP(H,\n                                       pointInFrontOfCamera,\n                                       candidatePositions,\n                                       candidateRotations);\n\n    if(filterSolutions)\n    {\n        // get only meaningfull solutions from it\n        getReasonableSolutions(candidatePositions,\n                               candidateRotations,\n                               pointInFrontOfCamera,\n                               positions,\n                               rotations,\n                               headingVectors,\n                               toSceneVectors,\n                               -1);\n\n    }\n    else\n    {\n        positions = candidatePositions;\n        rotations = candidateRotations;\n    }\n\n// for debug purposes\n//    for(int i = 0;\n//        i < positions.size();\n//        ++i)\n//    {\n//        cv::Mat rotInv;\n//        cv::Point3d posInv;\n//        rce::geometry::invertTranslationAndRotation(positions[i],\n//                                                    rotations[i],\n//                                                    posInv,\n//                                                    rotInv);\n//        cv::Mat checkTransform(3,3, CV_64FC1);\n//        rotInv.col(0).copyTo(checkTransform.col(0));\n//        rotInv.col(1).copyTo(checkTransform.col(1));\n//        checkTransform.at<double>(0,2) = posInv.x;\n//        checkTransform.at<double>(1,2) = posInv.y;\n//        checkTransform.at<double>(2,2) = posInv.z;\n\n//        cv::Mat residualTransform = H * checkTransform.inv();\n//        residualTransform = residualTransform / residualTransform.at<double>(2,2);\n\n//        qDebug() << \"Residual transform\" << i << residualTransform;\n//    }\n}\n\nvoid\nrce::geometry::RCameraPoseEstimation::\nestimateCameraPoseRobust(const cv::Mat &cameraMatrix,\n                         const cv::Mat &homographyFromWorldToImage,\n                         const cv::Point3d &pointInFrontOfCamera,\n                         std::vector<cv::Point3d> &positions,\n                         std::vector<cv::Mat> &rotations,\n                         std::vector<cv::Point3d> &headingVectors,\n                         std::vector<cv::Point3d> &toSceneVectors,\n                         bool leftHandedCoordinateSystem)\n{\n    cv::Mat H = getCleanHomography(cameraMatrix,\n                                   homographyFromWorldToImage,\n                                   leftHandedCoordinateSystem);\n\n\n    std::vector<cv::Point3d> candidatePositions;\n    std::vector<cv::Mat> candidateRotations;\n\n    // from theia library\n    estimatePoseFromHomographyTheiaPNP(H.clone(),\n                                       pointInFrontOfCamera,\n                                       candidatePositions,\n                                       candidateRotations);\n    // filter them out\n    std::vector<cv::Point3d> filteredPositions;\n    std::vector<cv::Mat> filteredRotations;\n    std::vector<cv::Point3d> filteredHeadingVectors;\n    std::vector<cv::Point3d> filteredToSceneVectors;\n    getReasonableSolutions(candidatePositions,\n                           candidateRotations,\n                           pointInFrontOfCamera,\n                           filteredPositions,\n                           filteredRotations,\n                           filteredHeadingVectors,\n                           filteredToSceneVectors,\n                           0.1);\n\n    if(filteredPositions.size() > 0)\n    {\n\n        cv::Point2d nadir = rce::geometry::calculateNadirPoint(H);\n\n        dDebug() << \"NADIR\" << qSetRealNumberPrecision(10) << nadir.x << nadir.y;\n\n        double bestDist = std::numeric_limits<double>::max();\n        int bestIdx = -1;\n\n        for(int i = 0;\n            i < filteredPositions.size();\n            ++i)\n        {\n            double dist = cv::norm(nadir - cv::Point2d(filteredPositions[i].x,\n                                                       filteredPositions[i].y));\n            if(dist < bestDist)\n            {\n                bestDist = dist;\n                bestIdx = i;\n            }\n        }\n\n        dDebug() << \"Best distance\" << bestDist;\n\n        positions.push_back(filteredPositions[bestIdx]);\n        rotations.push_back(filteredRotations[bestIdx]);\n        headingVectors.push_back(filteredHeadingVectors[bestIdx]);\n        toSceneVectors.push_back(filteredToSceneVectors[bestIdx]);\n    }\n    else\n    {\n        estimateCameraPose(cameraMatrix,\n                           homographyFromWorldToImage,\n                           pointInFrontOfCamera,\n                           positions,\n                           rotations,\n                           headingVectors,\n                           toSceneVectors,\n                           leftHandedCoordinateSystem,\n                           true,\n                           true);\n    }\n\n}\n\ncv::Mat\nrce::geometry::RCameraPoseEstimation::\ngetCleanHomography(const cv::Mat &cameraMatrix,\n                   const cv::Mat &_fromWorldToImage,\n                   bool flipY)\n{\n    cv::Mat fromWorldToImage;\n    if(flipY)\n    { // to make sure that rotation is not mirroring (and thus rotation determinant would be negative)\n        // we assume that final image is flipped\n        fromWorldToImage = _fromWorldToImage.clone();\n        fromWorldToImage.row(1) = fromWorldToImage.row(1) * (-1.0);\n    }\n    else\n    {\n        fromWorldToImage = _fromWorldToImage;\n    }\n\n    // firstly, get clean homography\n    return cameraMatrix.inv() * fromWorldToImage;\n}\n\ndouble estimateZ(const cv::Mat &H,\n                 const cv::Vec3d &r3rest,\n                 const cv::Point2d &nadirPoint,\n                 double coeffW,\n                 double coeffR3)\n{\n    double zEst1 = (H.at<double>(0,2) + coeffW * H.at<double>(0,0) * nadirPoint.x + coeffW * H.at<double>(0,1) * nadirPoint.y) /\n                   (-1.0 * coeffW * coeffR3 * r3rest(0));\n\n    double zEst2 = (H.at<double>(1,2) + coeffW * H.at<double>(1,0) * nadirPoint.x + coeffW * H.at<double>(1,1) * nadirPoint.y) /\n                   (-1.0 * coeffW * coeffR3 * r3rest(1));\n\n    double zEst = (zEst1 + zEst2) / 2.0;\n\n    dDebug() << \"estimated height\" << zEst << zEst1 << zEst2 << coeffW << coeffR3;\n    return zEst;\n}\n\n\nvoid\nrce::geometry::RCameraPoseEstimation::\nestimatePoseNADIRApproach(const cv::Mat &cameraMatrix,\n                          const cv::Mat &fromWorldToImage,\n                          std::vector<cv::Point3d> &positions,\n                          std::vector<cv::Mat> &rotations,\n                          bool flipY)\n{\n    // firstly, get clean homography\n    cv::Mat H = getCleanHomography(cameraMatrix,\n                                   fromWorldToImage,\n                                   flipY);\n\n\n    estimatePoseNADIRApproach(H,\n                              positions,\n                              rotations);\n\n}\n\nvoid\nrce::geometry::RCameraPoseEstimation::\nestimatePoseNADIRApproach(const cv::Mat &_H,\n                          std::vector<cv::Point3d> &positions,\n                          std::vector<cv::Mat> &rotations)\n{\n    cv::Mat H = _H.clone();\n    // estimate magnitude of scaling and denormalise the H\n    double wEst1 = cv::norm(H.col(0));\n    double wEst2 = cv::norm(H.col(1));\n    double wEst = (wEst1 + wEst2) / 2.0;\n    H = H / wEst;\n    // w = +- wEst\n\n    // calculate the inverse\n    cv::Mat invH = H.inv();\n\n    // calculate NADIR point\n    cv::Point2d nadirPoint = rce::geometry::calculateNadirPoint(H,\n                                                                invH);\n\n\n    dDebug() << \"NADIR POSE\" << qSetRealNumberPrecision(10) << nadirPoint.x << nadirPoint.y << wEst1 << wEst2 << wEst1/wEst2;\n\n    // get two estimates of R\n    cv::Mat r3est = H.col(0).cross(H.col(1)); // the sign of w does not have effect in here, as perpendicularity is kept even if we multiply by -1 both vectors\n    // r3 = +- r3est\n\n\n    // estimate Z for all 4 posibilities\n    double zPP = estimateZ(H, cv::Vec3d(r3est), nadirPoint, 1,1); // inside this function we can check if both estimated Z are similar or not.\n    double zMP = estimateZ(H, cv::Vec3d(r3est), nadirPoint, -1,1);\n    double zPM = estimateZ(H, cv::Vec3d(r3est), nadirPoint, 1,-1);\n    double zMM = estimateZ(H, cv::Vec3d(r3est), nadirPoint, -1,-1);\n\n    std::vector<cv::Vec3d> coeffSolutions;\n\n    coeffSolutions.push_back(cv::Vec3d(1,1, zPP));\n    coeffSolutions.push_back(cv::Vec3d(-1,1, zMP));\n    coeffSolutions.push_back(cv::Vec3d(1,-1, zPM));\n    coeffSolutions.push_back(cv::Vec3d(-1,-1, zMM));\n\n    for(int i = 0;\n        i < coeffSolutions.size();\n        ++i)\n    {\n        cv::Mat fixedH = H * coeffSolutions[i](0);\n        // fixedH should now be: [R_r^T(1) R_r^T(2) (-R_r^T*t)]\n        cv::Mat rotationT(3,3,CV_64FC1);\n        fixedH.col(0).copyTo(rotationT.col(0));\n        fixedH.col(1).copyTo(rotationT.col(1));\n        cv::Mat(r3est * coeffSolutions[i](1)).copyTo(rotationT.col(2)); // QUESTION: should we multiply here by coeffSolutions[i](0)????\n                rotationT = rotationT * coeffSolutions[i](1); // this was added here... because it works when coeffSolutions[i](1) is -1\n\n//        positions.push_back(cv::Point3d(nadirPoint.x,\n//                                        nadirPoint.y,\n//                                        coeffSolutions[i](2)));\n\n//        rotations.push_back(rotationT.t());\n\n        // make it pure rotation and translation\n        Eigen::Matrix3d eigMat;\n        cv::cv2eigen(rotationT,\n                     eigMat);\n        Eigen::Projective3d projTransform = Eigen::Projective3d::Identity();\n        projTransform.linear() = eigMat;\n        eigMat = projTransform.rotation();\n        cv::Mat fixedRotationT;\n        cv::eigen2cv(eigMat, fixedRotationT);\n\n        cv::Vec3d fixedPosition2 = cv::Mat(fixedRotationT.t() *  coeffSolutions[i](1) * (-1) * fixedH.col(2));\n\n\n\n        //qDebug() << \"For solution:\" << i << nadirPoint.x << nadirPoint.y << coeffSolutions[i](2) << \"the alternative solutions are\"\n//                                                                 << fixedPosition2(0)\n//                                                                 << fixedPosition2(1)\n//                                                                 << fixedPosition2(2);\n\n        positions.push_back(cv::Point3d(nadirPoint.x,\n                                        nadirPoint.y,\n                                        fixedPosition2(2)));\n\n        rotations.push_back(fixedRotationT.t());\n\n        //qDebug() << \"Determinants\" << cv::determinant(rotationT.t()) << cv::determinant(fixedRotationT.t());\n    }\n}\n\n\n\n\nvoid\nrce::geometry::RCameraPoseEstimation::\nestimatePoseBetweenSimple(const cv::Mat &homography,\n                          std::vector<cv::Point3d> &positions,\n                          std::vector<cv::Mat> &rotations)\n{\n\n    // based upon http://ags.cs.uni-kl.de/fileadmin/inf_ags/3dcv-ws11-12/3DCV_WS11-12_lec04.pdf\n    // homography = lambda * [r1 r2 t]\n    double norm1 = cv::norm(homography.col(0));\n    double norm2 = cv::norm(homography.col(1));\n    double lambda = (norm1 + norm2) / 2.0;\n\n    cv::Vec3d r1(homography.at<double>(0,0) / norm1,\n                 homography.at<double>(1,0) / norm1,\n                 homography.at<double>(2,0) / norm1);\n    cv::Vec3d r2(homography.at<double>(0,1) / norm2,\n                 homography.at<double>(1,1) / norm2,\n                 homography.at<double>(2,1) / norm2);\n    cv::Point3d t(homography.at<double>(0,2) / lambda,\n                  homography.at<double>(1,2) / lambda,\n                  homography.at<double>(2,2) / lambda);\n\n    cv::Vec3d r3a = r1.cross(r2);\n    double norm3 = cv::norm(r3a);\n    r3a *= (1.0 / norm3);\n\n    cv::Vec3d r3b = r3a * (-1);\n\n    cv::Mat rotMatA = rce::geometry::composeRotationMatrix(r1, r2, r3a);\n    cv::Mat rotMatB = rce::geometry::composeRotationMatrix(r1, r2, r3b);\n\n    cv::Mat rotMatAInv, rotMatBInv;\n    cv::Point3d tAInv, tBInv;\n    rce::geometry::invertTranslationAndRotation(t,\n                                                rotMatA,\n                                                tAInv,\n                                                rotMatAInv);\n    rce::geometry::invertTranslationAndRotation(t,\n                                                rotMatB,\n                                                tBInv,\n                                                rotMatBInv);\n    positions.push_back(tAInv);\n    positions.push_back(tBInv);\n    rotations.push_back(rotMatAInv);\n    rotations.push_back(rotMatBInv);\n}\n\nvoid\nrce::geometry::RCameraPoseEstimation::\nestimatePoseBetweenDumb(const cv::Mat &h,\n                        std::vector<cv::Point3d> &positions,\n                        std::vector<cv::Mat> &rotations)\n{\n\n    // dumbest version based on http://dsp.stackexchange.com/questions/2736/step-by-step-camera-pose-estimation-for-visual-tracking-and-planar-markers\n\n    cv::Mat rotation(3,3,\n                     CV_64FC1);\n\n    h.col(0).copyTo(rotation.col(0));\n    h.col(1).copyTo(rotation.col(1));\n    cv::Mat v3 = h.col(0).cross(h.col(1));\n    double norm1 = cv::norm(h.col(0));\n    double norm2 = cv::norm(h.col(1));\n    double tnorm = (norm1 + norm2) / 2.0;\n    //dDebug() << \"Rotnorms\"<< norm1 << norm2 << cv::norm(v3);\n    v3 = v3 / tnorm;\n    v3.copyTo(rotation.col(2));\n\n    cv::Point3d position = static_cast<cv::Point3d>(cv::Mat(h.col(2) / tnorm));\n\n    cv::Mat rotMatInv;\n    cv::Point3d tInv;\n    rce::geometry::invertTranslationAndRotation(position,\n                                                rotation / tnorm,\n                                                tInv,\n                                                rotMatInv);\n\n    positions.push_back(tInv);\n    rotations.push_back(rotMatInv);\n\n}\n\nvoid\nrce::geometry::RCameraPoseEstimation::\nestimatePoseBetweenCVHomography(const cv::Mat &homography,\n                                std::vector<cv::Point3d> &positions,\n                                std::vector<cv::Mat> &rotations)\n{\n    estimatePoseBetweenImagesCVHomography(homography,\n                                          cv::Mat::eye(3,3,\n                                                       CV_64FC1),\n                                          positions,\n                                          rotations);\n}\n\nvoid\nrce::geometry::RCameraPoseEstimation::\nestimatePoseBetweenImagesCVHomography(const cv::Mat &homography,\n                                      const cv::Mat &cameraMatrix,\n                                      std::vector<cv::Point3d> &positions,\n                                      std::vector<cv::Mat> &rotations)\n{\n    std::vector<cv::Mat> rotationsCV, translationsCV, normals;\n    cv::decomposeHomographyMat(homography,\n                               cameraMatrix,\n                               rotationsCV,\n                               translationsCV,\n                               normals);\n\n    for(int i = 0;\n        i < rotationsCV.size();\n        ++i)\n    {\n        //qDebug() << \"estimatePoseBetweenCVHomography\" << rotationsCV[i].type() << translationsCV[i].type() << translationsCV[i].cols << translationsCV[i].rows  << translationsCV[i].channels();\n        positions.push_back(cv::Point3d(translationsCV[i]));\n        rotations.push_back(rotationsCV[i]);\n\n        cv::Point3d tInv;\n        cv::Mat rotInv;\n        rce::geometry::invertTranslationAndRotation(cv::Point3d(translationsCV[i]),\n                                                    rotationsCV[i],\n                                                    tInv,\n                                                    rotInv);\n        rotations.push_back(rotInv);\n        positions.push_back(tInv);\n\n    }\n}\n\nvoid\nrce::geometry::RCameraPoseEstimation::\nestimatePoseFromHomographyTheiaP3P(const cv::Mat &homography,\n                                   const cv::Point3d &sceneCenter,\n                                   std::vector<cv::Point3d> &positions,\n                                   std::vector<cv::Mat> &rotations,\n                                   double featurePointScale)\n{\n    cv::Vec3d scenePt1(sceneCenter.x - 0.5 * featurePointScale,\n                       sceneCenter.y + 1 * featurePointScale,\n                       1);\n    cv::Vec3d scenePt2(sceneCenter.x - 0.5 * featurePointScale,\n                       sceneCenter.y - 1 * featurePointScale,\n                       1);\n    cv::Vec3d scenePt3(sceneCenter.x + 1 * featurePointScale,\n                       sceneCenter.y,\n                       1);\n    cv::Vec3d camPt1 = cv::Mat(homography * cv::Mat(scenePt1));\n    cv::Vec3d camPt2 = cv::Mat(homography * cv::Mat(scenePt2));\n    cv::Vec3d camPt3 = cv::Mat(homography * cv::Mat(scenePt3));\n\n    Eigen::Vector2d feature_point[3];\n    feature_point[0](0) = camPt1(0) / camPt1(2);\n    feature_point[0](1) = camPt1(1) / camPt1(2);\n    feature_point[1](0) = camPt2(0) / camPt2(2);\n    feature_point[1](1) = camPt2(1) / camPt2(2);\n    feature_point[2](0) = camPt3(0) / camPt3(2);\n    feature_point[2](1) = camPt3(1) / camPt3(2);\n\n    Eigen::Vector3d world_point[3];\n    world_point[0](0) = scenePt1(0);\n    world_point[0](1) = scenePt1(1);\n    world_point[0](2) = 0;\n    world_point[1](0) = scenePt2(0);\n    world_point[1](1) = scenePt2(1);\n    world_point[1](2) = 0;\n    world_point[2](0) = scenePt3(0);\n    world_point[2](1) = scenePt3(1);\n    world_point[2](2) = 0;\n\n    std::vector<Eigen::Matrix3d> solution_rotations;\n    std::vector<Eigen::Vector3d> solution_translations;\n\n    theia::PoseFromThreePoints(feature_point,\n                               world_point,\n                               &solution_rotations,\n                               &solution_translations);\n\n    for(int i = 0;\n        i < solution_rotations.size();\n        ++i)\n    {\n        cv::Mat rotation;\n        cv::eigen2cv(solution_rotations[i],\n                     rotation);\n        cv::Point3d position(solution_translations[i](0),\n                             solution_translations[i](1),\n                             solution_translations[i](2));\n//        rotations.push_back(rotation);\n//        positions.push_back(position);\n\n        cv::Point3d tInv;\n        cv::Mat rotInv;\n        rce::geometry::invertTranslationAndRotation(position,\n                                                    rotation,\n                                                    tInv,\n                                                    rotInv);\n        rotations.push_back(rotInv);\n        positions.push_back(tInv);\n    }\n}\n\nvoid\nrce::geometry::RCameraPoseEstimation::\nestimatePoseFromHomographyTheiaPNP(const cv::Mat &homography,\n                                   const cv::Point3d &sceneCenter,\n                                   std::vector<cv::Point3d> &positions,\n                                   std::vector<cv::Mat> &rotations,\n                                   double featurePointScale)\n{\n    cv::Vec3d scenePt1(sceneCenter.x - 1 * featurePointScale,\n                       sceneCenter.y + 1 * featurePointScale,\n                       1);\n    cv::Vec3d scenePt2(sceneCenter.x - 1 * featurePointScale,\n                       sceneCenter.y - 1 * featurePointScale,\n                       1);\n    cv::Vec3d scenePt3(sceneCenter.x + 1 * featurePointScale,\n                       sceneCenter.y + 1 * featurePointScale,\n                       1);\n    cv::Vec3d scenePt4(sceneCenter.x + 1 * featurePointScale,\n                       sceneCenter.y - 1 * featurePointScale,\n                       1);\n    cv::Vec3d camPt1 = cv::Mat(homography * cv::Mat(scenePt1));\n    cv::Vec3d camPt2 = cv::Mat(homography * cv::Mat(scenePt2));\n    cv::Vec3d camPt3 = cv::Mat(homography * cv::Mat(scenePt3));\n    cv::Vec3d camPt4 = cv::Mat(homography * cv::Mat(scenePt4));\n\n    std::vector<Eigen::Vector2d> feature_points(4);\n    feature_points[0](0) = camPt1(0) / camPt1(2);\n    feature_points[0](1) = camPt1(1) / camPt1(2);\n    feature_points[1](0) = camPt2(0) / camPt2(2);\n    feature_points[1](1) = camPt2(1) / camPt2(2);\n    feature_points[2](0) = camPt3(0) / camPt3(2);\n    feature_points[2](1) = camPt3(1) / camPt3(2);\n    feature_points[3](0) = camPt4(0) / camPt4(2);\n    feature_points[3](1) = camPt4(1) / camPt4(2);\n\n    std::vector<Eigen::Vector3d> world_points(4);\n    world_points[0](0) = scenePt1(0);\n    world_points[0](1) = scenePt1(1);\n    world_points[0](2) = 0;\n    world_points[1](0) = scenePt2(0);\n    world_points[1](1) = scenePt2(1);\n    world_points[1](2) = 0;\n    world_points[2](0) = scenePt3(0);\n    world_points[2](1) = scenePt3(1);\n    world_points[2](2) = 0;\n    world_points[3](0) = scenePt4(0);\n    world_points[3](1) = scenePt4(1);\n    world_points[3](2) = 0;\n\n    std::vector<Eigen::Quaterniond> solution_rotations;\n    std::vector<Eigen::Vector3d> solution_translations;\n\n    theia::DlsPnp(feature_points,\n                  world_points,\n                  &solution_rotations,\n                  &solution_translations);\n\n    dDebug() << \"Estimated positions:\" << solution_rotations.size();\n    for(int i = 0;\n        i < solution_rotations.size();\n        ++i)\n    {\n        cv::Mat rotation;\n        cv::eigen2cv(solution_rotations[i].matrix(),\n                     rotation);\n        cv::Point3d position(solution_translations[i](0),\n                             solution_translations[i](1),\n                             solution_translations[i](2));\n//        rotations.push_back(rotation);\n//        positions.push_back(position);\n\n        cv::Point3d tInv;\n        cv::Mat rotInv;\n        rce::geometry::invertTranslationAndRotation(position,\n                                                    rotation,\n                                                    tInv,\n                                                    rotInv);\n        rotations.push_back(rotInv);\n        positions.push_back(tInv);\n    }\n}\n\nvoid\nrce::geometry::RCameraPoseEstimation::\ngetReasonableSolutions(const std::vector<cv::Point3d> &allPositions,\n                       const std::vector<cv::Mat> &allRotations,\n                       const cv::Point3d &pointInFrontOfCamera,\n                       std::vector<cv::Point3d> &positions,\n                       std::vector<cv::Mat> &rotations,\n                       std::vector<cv::Point3d> &headingVectors,\n                       std::vector<cv::Point3d> &toSceneVectors,\n                       double determinantLimit)\n{\n    for(int i = 0;\n        i < allPositions.size();\n        ++i)\n    {\n        //qDebug() << \"Checking solution\" << qSetRealNumberPrecision(10) << i << allPositions[i].x << allPositions[i].y << allPositions[i].z;\n        // position must be above ground\n        if(allPositions[i].z < 0)\n        {\n            dInfo() << \"RCameraPoseEstimation::getReasonableSolutions: solution\" << i << \"does not fullfill height constraint.\" << allPositions[i].x << allPositions[i].y << allPositions[i].z;\n\n            continue;\n        }\n\n        cv::Mat rotInv;\n        cv::Point3d posInv;\n        rce::geometry::invertTranslationAndRotation(allPositions[i],\n                                                    allRotations[i],\n                                                    posInv,\n                                                    rotInv);\n\n        // check whether the point in front of the camera is in front of the camera\n        double camZ = rotInv.at<double>(2,0) * pointInFrontOfCamera.x +\n                      rotInv.at<double>(2,1) * pointInFrontOfCamera.y +\n                      rotInv.at<double>(2,2) * pointInFrontOfCamera.z +\n                      posInv.z * 1.0;\n\n        if(camZ <= 0)\n        {\n            dInfo() << \"RCameraPoseEstimation::getReasonableSolutions: solution\" << i << \"does not fullfill heading constraint.\" << camZ;\n\n            continue;\n        }\n\n        // calculate heading vector\n        cv::Point3d originTransformed = rce::geometry::transformPoint(cv::Point3d(0,0,0),\n                                                                      allPositions[i],\n                                                                      allRotations[i]);\n        cv::Point3d viewVectorTransformed = rce::geometry::transformPoint(cv::Point3d(0,0,1),\n                                                                          allPositions[i],\n                                                                          allRotations[i]);\n        cv::Point3d headingVector = viewVectorTransformed - originTransformed;\n        headingVector = headingVector / cv::norm(headingVector);\n\n        // calculate to scene vector\n        cv::Point3d toSceneVector = pointInFrontOfCamera - allPositions[i];\n        double distToScene = cv::norm(toSceneVector);\n        // dInfo() << i << \"Distance to scene\" << distToScene;\n        if(distToScene > RCE_POSE_MAX_DISTANCE_TO_SCENE)\n        {\n            dInfo() << \"RCameraPoseEstimation::getReasonableSolutions: solution\" << i << \"does not fullfill distance constraint.\" << distToScene;\n\n            continue;\n        }\n\n        toSceneVector = toSceneVector / distToScene;\n\n        if(determinantLimit >= 0)\n        {\n            double determinant = cv::determinant(allRotations[i]);\n            if(std::abs(determinant - 1.0) > determinantLimit)\n            {\n                dInfo() << \"RCameraPoseEstimation::getReasonableSolutions: solution\" << i << \"does not fullfill determinant constraint(\" << determinant << \").\";\n\n                continue;\n            }\n\n            //qDebug() << \"Transformation passes:\" << allPositions[i].x << allPositions[i].y << allPositions[i].z << camZ << distToScene << determinant;\n\n        }\n        else\n        {\n\n            //qDebug() << \"Transformation passes:\" << allPositions[i].x << allPositions[i].y << allPositions[i].z << camZ << distToScene;\n        }\n\n        //qDebug() << \"Rotation\" << allRotations[i];\n\n\n        positions.push_back(allPositions[i]);\n\n\n        rotations.push_back(allRotations[i]);\n        headingVectors.push_back(headingVector);\n        toSceneVectors.push_back(toSceneVector);\n\n    }\n}\n", "meta": {"hexsha": "134367791882a4c38da8cf636e9d9ab73263a451", "size": 28433, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/RCE/Geometry/rce/geometry/RCameraPoseEstimation.cpp", "max_stars_repo_name": "Timie/PositionEstimationAccuracy", "max_stars_repo_head_hexsha": "9e88597c271ccc2a1a8442db6fa62236b7178296", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-05-15T09:46:40.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-15T09:46:40.000Z", "max_issues_repo_path": "src/RCE/Geometry/rce/geometry/RCameraPoseEstimation.cpp", "max_issues_repo_name": "Timie/PositionEstimationAccuracy", "max_issues_repo_head_hexsha": "9e88597c271ccc2a1a8442db6fa62236b7178296", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/RCE/Geometry/rce/geometry/RCameraPoseEstimation.cpp", "max_forks_repo_name": "Timie/PositionEstimationAccuracy", "max_forks_repo_head_hexsha": "9e88597c271ccc2a1a8442db6fa62236b7178296", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.8098404255, "max_line_length": 194, "alphanum_fraction": 0.5250589104, "num_tokens": 6720, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4561437358080873}}
{"text": "////////////////////////////////////////////////////////////////////////////////\n// kernel::bandwidth_selection::meta_k_fold_nw.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_KERNEL_BANDWIDTH_SELECTION_META_K_FOLD_NW_HPP_ER_2009           \n#define BOOST_STATISTICS_DETAIL_KERNEL_BANDWIDTH_SELECTION_META_K_FOLD_NW_HPP_ER_2009\n#include <boost/statistics/detail/kernel/bandwidth_selection/detail/k_fold.hpp>\n#include <boost/statistics/detail/kernel/estimation/detail/mean_accumulator.hpp>\n#include <boost/statistics/detail/kernel/estimation/meta_nw_visitor_unary.hpp>\n#include <boost/statistics/detail/cross_validation/extractor/identity.hpp>\n\nnamespace boost{\nnamespace statistics{\nnamespace detail{\nnamespace kernel{\nnamespace bandwidth_selection{\n\ntemplate<\n    typename F1,    // x extractor\n    typename F2     // y extractor\n>\nstruct meta_k_fold_nw\n{\n\n    typedef meta_nw_visitor_unary<F1,F2> meta_;\n\n    // ft(u) has to return a training data. Here, ft(u) = (x,y),\n    // f1((x,y))=x, f2((x,y)) = y\n    \n    template<\n        typename U, // data-unit \n        typename K,\n        typename Ft = cross_validation::extractor::identity,\n        typename A = typename \n            kernel::detail::mean_accumulator<\n                typename K::result_type>::type\n    >\n    struct apply{\n        typedef bandwidth_selection::detail::k_fold<\n            U,\n            meta_::template apply,\n            K,\n            Ft,F1,F2\n        > type;\n    };\n\n};\n    \n}// bandwidth_selection\n}// kernel\n}// detail\n}// statistics\n}// boost   \n\n#endif\n\n", "meta": {"hexsha": "d46fe21d249233452b4fda67785f081089941454", "size": 2045, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "kernel/boost/statistics/detail/kernel/bandwidth_selection/meta_k_fold_nw.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": "kernel/boost/statistics/detail/kernel/bandwidth_selection/meta_k_fold_nw.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": "kernel/boost/statistics/detail/kernel/bandwidth_selection/meta_k_fold_nw.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.5245901639, "max_line_length": 96, "alphanum_fraction": 0.5696821516, "num_tokens": 417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4561437358080873}}
{"text": "#include <iostream>\n#include <cmath>\n#include <algorithm>\n#include <vector>\n#include <boost/multiprecision/cpp_int.hpp>\nusing namespace std;\nusing namespace boost::multiprecision;\ncpp_int power_fm(cpp_int a, cpp_int n, cpp_int m) {\n    cpp_int ret = 1;\n    while (n > 0) {\n        if (n & 1) ret = ret * a % m;\n        a = a * a % m;\n        n >>= 1;\n    }\n    return ret;\n}\nint main() {\n    cpp_int x, y, z; cin >> x >> y >> z;\n    cout << power_fm(x, z, y) << endl;\n}\n", "meta": {"hexsha": "40143e246f328927e78de9d77804b02d40f4ea17", "size": 470, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AtCoder/atc002/b/main.cpp", "max_stars_repo_name": "H-Tatsuhiro/Com_Pro-Cpp", "max_stars_repo_head_hexsha": "fd79f7821a76b11f4a6f83bbb26a034db577a877", "max_stars_repo_licenses": ["MIT"], "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/atc002/b/main.cpp", "max_issues_repo_name": "H-Tatsuhiro/Com_Pro-Cpp", "max_issues_repo_head_hexsha": "fd79f7821a76b11f4a6f83bbb26a034db577a877", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-10-19T08:47:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T05:23:56.000Z", "max_forks_repo_path": "AtCoder/atc002/b/main.cpp", "max_forks_repo_name": "H-Tatsuhiro/Com_Pro-Cpp", "max_forks_repo_head_hexsha": "fd79f7821a76b11f4a6f83bbb26a034db577a877", "max_forks_repo_licenses": ["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.380952381, "max_line_length": 51, "alphanum_fraction": 0.570212766, "num_tokens": 146, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.456143729679396}}
{"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_COSD_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_COSD_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-trigonometric\n    Function object implementing cosd capabilities\n\n    cosine of the input in degree: \\f$\\cos(\\pi x/180)\\f$.\n\n    @par Semantic:\n\n    The semantics of the function are similar to @ref cos ones.\n    see @ref cos for further details\n\n    @see sincosd, cos, cospi\n\n  **/\n  Value cosd(Value const & v0);\n} }\n#endif\n\n#include <boost/simd/function/scalar/cosd.hpp>\n#include <boost/simd/function/simd/cosd.hpp>\n\n#endif\n", "meta": {"hexsha": "71a8e4b7b98fe556f9a587fcbfbb4bd2c050e498", "size": 999, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/cosd.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/cosd.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/cosd.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": 24.3658536585, "max_line_length": 100, "alphanum_fraction": 0.5795795796, "num_tokens": 217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.456143729679396}}
{"text": "///////////////////////////////////////////////////////////////\n//  Copyright 2011 John Maddock. Distributed under the Boost\n//  Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt\n//\n\n#include <boost/detail/lightweight_test.hpp>\n#include <boost/math/special_functions/sign.hpp>\n\n#ifdef _MSC_VER\n#define _SCL_SECURE_NO_WARNINGS\n#endif\n\n#if !defined(TEST_CPP_BIN_FLOAT) && !defined(TEST_DOUBLE) && !defined(TEST_MPFR_FLOAT)\n#define TEST_CPP_BIN_FLOAT\n#define TEST_DOUBLE\n#define TEST_MPFR_FLOAT\n#endif\n\n\n#ifdef TEST_CPP_BIN_FLOAT\n#include <boost/multiprecision/cpp_bin_float.hpp>\n#endif\n#ifdef TEST_MPFR_FLOAT\n#include <boost/multiprecision/mpfr.hpp>\n#endif\n\ntemplate <class T>\nstruct extract_value_type\n{\n   typedef typename T::value_type type;\n};\ntemplate <>\nstruct extract_value_type<double>\n{\n   typedef double type;\n};\n\ntemplate <class T>\nvoid test()\n{\n   using value_type = typename extract_value_type<T>::type;\n\n   using std::real;\n   using std::signbit;\n\n   T mp_zero{0};\n   T mp_m_zero{-mp_zero};\n   T mp_finite{2};\n   T mp_m_finite{-2};\n   T mp_big{!std::is_same<T, value_type>::value ? std::numeric_limits<value_type>::has_infinity ? std::numeric_limits<value_type>::infinity() : (std::numeric_limits<value_type>::max)() : std::numeric_limits<T>::has_infinity ? std::numeric_limits<T>::infinity()\n                                                                                                                                                                                                     : (std::numeric_limits<T>::max)()};\n   T mp_m_big{-mp_big};\n   T mp_small{!std::is_same<T, value_type>::value ? (std::numeric_limits<value_type>::min)() : (std::numeric_limits<T>::min)()};\n   T mp_m_small{-mp_small};\n\n   T result;\n   //\n   // Multiplications:\n   //\n   result = mp_zero * mp_finite;\n   BOOST_TEST(signbit(result) == 0);\n   result = mp_zero * mp_m_finite;\n   BOOST_TEST(signbit(result));\n   result = mp_m_zero * mp_finite;\n   BOOST_TEST(signbit(result));\n   result = mp_m_zero * mp_m_finite;\n   BOOST_TEST(signbit(result) == 0);\n   result = mp_zero * -mp_finite;\n   BOOST_TEST(signbit(result));\n   result = -mp_zero * mp_finite;\n   BOOST_TEST(signbit(result));\n   result = -mp_zero * -mp_finite;\n   BOOST_TEST(signbit(result) == 0);\n   result = mp_small * mp_small;\n   BOOST_TEST(signbit(result) == 0);\n   result = mp_small * mp_m_small;\n   BOOST_TEST(signbit(result));\n   result = mp_m_small * mp_m_small;\n   BOOST_TEST(signbit(result) == 0);\n   result = mp_small * -mp_small;\n   BOOST_TEST(signbit(result));\n   result = -mp_small * -mp_small;\n   BOOST_TEST(signbit(result) == 0);\n   //\n   // Divisions:\n   //\n   result = mp_zero / mp_finite;\n   BOOST_TEST(signbit(result) == 0);\n   result = mp_zero / mp_m_finite;\n   BOOST_TEST(signbit(result));\n   result = mp_m_zero / mp_finite;\n   BOOST_TEST(signbit(result));\n   result = mp_m_zero / mp_m_finite;\n   BOOST_TEST(signbit(result) == 0);\n   result = mp_zero / -mp_finite;\n   BOOST_TEST(signbit(result));\n   result = -mp_zero / mp_finite;\n   BOOST_TEST(signbit(result));\n   result = -mp_zero / -mp_finite;\n   BOOST_TEST(signbit(result) == 0);\n\n   result = mp_small / mp_big;\n   BOOST_TEST(signbit(result) == 0);\n   result = mp_small / mp_m_big;\n   BOOST_TEST(signbit(result));\n   result = mp_m_small / mp_big;\n   BOOST_TEST(signbit(result));\n   result = mp_m_small / mp_m_big;\n   BOOST_TEST(signbit(result) == 0);\n   result = mp_small / -mp_big;\n   BOOST_TEST(signbit(result));\n   result = -mp_small / mp_big;\n   BOOST_TEST(signbit(result));\n   result = -mp_small / -mp_big;\n   BOOST_TEST(signbit(result) == 0);\n   //\n   // Additions:\n   //\n   result = mp_zero + mp_zero;\n   BOOST_TEST(signbit(result) == 0);\n   result = mp_zero + mp_m_zero;\n   BOOST_TEST(signbit(result) == 0);\n   result = mp_m_zero + mp_zero;\n   BOOST_TEST(signbit(result) == 0);\n   result = mp_m_zero + mp_m_zero;\n   BOOST_TEST(signbit(result));\n   //\n   // Subtractions:\n   //\n   result = mp_zero - mp_zero;\n   BOOST_TEST(signbit(result) == 0);\n   result = mp_zero - mp_m_zero;\n   BOOST_TEST(signbit(result) == 0);\n   result = mp_m_zero - mp_zero;\n   BOOST_TEST(signbit(result));\n   result = mp_m_zero - mp_m_zero;\n   BOOST_TEST(signbit(result) == 0);\n   result = mp_finite - mp_finite;\n   BOOST_TEST(signbit(result) == 0);\n   result = mp_finite + mp_m_finite;\n   BOOST_TEST(signbit(result) == 0);\n\n   //\n   // Over again for one arg an integer:\n   //\n   int i_zero{0};\n   int i_finite{2};\n   int i_m_finite{-2};\n   result = i_zero * mp_finite;\n   BOOST_TEST(signbit(result) == 0);\n   result = i_zero * mp_m_finite;\n   BOOST_TEST(signbit(result));\n   result = i_zero * -mp_finite;\n   BOOST_TEST(signbit(result));\n   result = mp_zero * i_finite;\n   BOOST_TEST(signbit(result) == 0);\n   result = mp_m_zero * i_finite;\n   BOOST_TEST(signbit(result));\n   result = mp_zero * i_m_finite;\n   BOOST_TEST(signbit(result));\n   //\n   // Divisions:\n   //\n   result = i_zero / mp_finite;\n   BOOST_TEST(signbit(result) == 0);\n   result = i_zero / mp_m_finite;\n   BOOST_TEST(signbit(result));\n   result = mp_zero / i_m_finite;\n   BOOST_TEST(signbit(result));\n   result = -mp_zero / i_finite;\n   BOOST_TEST(signbit(result));\n   //\n   // Additions:\n   //\n   result = mp_zero + i_zero;\n   BOOST_TEST(signbit(result) == 0);\n#ifndef TEST_MPFR_FLOAT\n   //\n   // There appears to be a bug in mpfr_add_ui here:\n   //\n   result = i_zero + mp_m_zero;\n   BOOST_TEST(signbit(result) == 0);\n#endif\n   //\n   // Subtractions:\n   //\n   result = mp_zero - i_zero;\n   BOOST_TEST(signbit(result) == 0);\n   result = i_zero - mp_m_zero;\n   BOOST_TEST(signbit(result) == 0);\n   result = mp_m_zero - i_zero;\n   BOOST_TEST(signbit(result));\n   result = i_finite - mp_finite;\n   BOOST_TEST(signbit(result) == 0);\n   result = i_finite + mp_m_finite;\n   BOOST_TEST(signbit(result) == 0);\n   result = mp_finite - i_finite;\n   BOOST_TEST(signbit(result) == 0);\n   result = mp_finite + i_m_finite;\n   BOOST_TEST(signbit(result) == 0);\n   //\n   // Over again for one arg a float:\n   //\n   float f_zero{0};\n   float f_m_zero{-f_zero};\n   float f_finite{2};\n   float f_m_finite{-2};\n   result = f_zero * mp_finite;\n   BOOST_TEST(signbit(result) == 0);\n   result = f_zero * mp_m_finite;\n   BOOST_TEST(signbit(result));\n   result = f_zero * -mp_finite;\n   BOOST_TEST(signbit(result));\n   result = mp_zero * f_finite;\n   BOOST_TEST(signbit(result) == 0);\n   result = mp_m_zero * f_finite;\n   BOOST_TEST(signbit(result));\n   result = mp_zero * f_m_finite;\n   BOOST_TEST(signbit(result));\n   //\n   // Divisions:\n   //\n   result = f_zero / mp_finite;\n   BOOST_TEST(signbit(result) == 0);\n   result = f_zero / mp_m_finite;\n   BOOST_TEST(signbit(result));\n   result = mp_zero / f_m_finite;\n   BOOST_TEST(signbit(result));\n   result = -mp_zero / f_finite;\n   BOOST_TEST(signbit(result));\n   //\n   // Additions:\n   //\n   result = f_zero + mp_zero;\n   BOOST_TEST(signbit(result) == 0);\n   result = f_zero + mp_m_zero;\n   BOOST_TEST(signbit(result) == 0);\n   result = f_m_zero + mp_zero;\n   BOOST_TEST(signbit(result) == 0);\n   result = f_m_zero + mp_m_zero;\n   BOOST_TEST(signbit(result));\n   //\n   // Subtractions:\n   //\n   result = f_zero - mp_zero;\n   BOOST_TEST(signbit(result) == 0);\n   result = f_zero - mp_m_zero;\n   BOOST_TEST(signbit(result) == 0);\n   result = f_m_zero - mp_zero;\n   BOOST_TEST(signbit(result));\n   result = f_m_zero - mp_m_zero;\n   BOOST_TEST(signbit(result) == 0);\n   result = mp_zero - f_zero;\n   BOOST_TEST(signbit(result) == 0);\n   result = mp_zero - f_m_zero;\n   BOOST_TEST(signbit(result) == 0);\n   result = mp_m_zero - f_zero;\n   BOOST_TEST(signbit(result));\n   result = mp_m_zero - f_m_zero;\n   BOOST_TEST(signbit(result) == 0);\n   result = f_finite - mp_finite;\n   BOOST_TEST(signbit(result) == 0);\n   result = f_finite + mp_m_finite;\n   BOOST_TEST(signbit(result) == 0);\n   result = mp_finite - f_finite;\n   BOOST_TEST(signbit(result) == 0);\n   result = mp_finite + f_m_finite;\n   BOOST_TEST(signbit(result) == 0);\n   //\n   // Special cases:\n   //\n   result = mp_m_zero * mp_m_zero;\n   BOOST_TEST(signbit(result) == 0);\n   result = mp_m_zero + mp_m_zero;\n   BOOST_TEST(signbit(result));\n   result = mp_zero + mp_zero;\n   BOOST_TEST(signbit(result) == 0);\n   result = abs(mp_m_zero);\n   BOOST_TEST(signbit(result) == 0);\n   result = fabs(mp_m_zero);\n   BOOST_TEST(signbit(result) == 0);\n   result = sqrt(mp_m_zero);\n   BOOST_TEST(signbit(result));\n}\n\nint main()\n{\n#ifdef TEST_DOUBLE\n   test<double>();\n#endif\n#ifdef TEST_CPP_BIN_FLOAT\n   test<boost::multiprecision::cpp_bin_float_50>();\n   test<boost::multiprecision::number<boost::multiprecision::cpp_bin_float<35, boost::multiprecision::digit_base_10, std::allocator<char>, boost::long_long_type>, boost::multiprecision::et_on>>();\n#endif\n#ifdef TEST_MPFR_FLOAT\n   test<boost::multiprecision::mpfr_float_50>();\n#endif\n   return boost::report_errors();\n}\n", "meta": {"hexsha": "9997b82472d3c585df284f88f6a7bb374d19a987", "size": 8894, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_signed_zero.cpp", "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": "test/test_signed_zero.cpp", "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": "test/test_signed_zero.cpp", "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": 29.5481727575, "max_line_length": 260, "alphanum_fraction": 0.6504384979, "num_tokens": 2467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581741774411, "lm_q2_score": 0.6187804407739559, "lm_q1q2_score": 0.45613905993764153}}
{"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_IS_EVEN_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_IS_EVEN_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n\n    @ingroup group-predicates\n    This function object returns @ref True or @ref False according x is even or not.\n\n\n\n    @par Header <boost/simd/function/is_even.hpp>\n\n    @par Note:\n\n    The call to `is_even(x)` is similar to  `to_int(x/2)*2 == x`\n\n    A floating number is even if it is a  flint\n    and divided by two it is still a flint.\n\n    A flint is a 'floating integer' i.e. a floating number\n    representing an integer value\n\n    Be conscious that all sufficiently great floating points values are even...\n\n    @see is_odd, is_flint\n\n    @par Example:\n\n      @snippet is_even.cpp is_even\n\n    @par Possible output:\n\n      @snippet is_even.txt is_even\n\n  **/\n  as_logical_t<Value> is_even(Value const& x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/is_even.hpp>\n#include <boost/simd/function/simd/is_even.hpp>\n\n#endif\n", "meta": {"hexsha": "cc4ea4e007cbfbbbaba29f3b8d5fe393058c284b", "size": 1397, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/is_even.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/is_even.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/is_even.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": 24.0862068966, "max_line_length": 100, "alphanum_fraction": 0.6091624911, "num_tokens": 312, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581741774411, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.45613905475534156}}
{"text": "#include <iostream>\r\n#include <Eigen/Core>\r\n#include <Eigen/Dense>\r\n#include <Eigen/IterativeLinearSolvers>\r\n#include <unsupported/Eigen/IterativeSolvers>\r\n\r\nclass MatrixReplacement;\r\nusing Eigen::SparseMatrix;\r\n\r\nnamespace Eigen {\r\nnamespace internal {\r\n  // MatrixReplacement looks-like a SparseMatrix, so let's inherits its traits:\r\n  template<>\r\n  struct traits<MatrixReplacement> :  public Eigen::internal::traits<Eigen::SparseMatrix<double> >\r\n  {};\r\n}\r\n}\r\n\r\n// Example of a matrix-free wrapper from a user type to Eigen's compatible type\r\n// For the sake of simplicity, this example simply wrap a Eigen::SparseMatrix.\r\nclass MatrixReplacement : public Eigen::EigenBase<MatrixReplacement> {\r\npublic:\r\n  // Required typedefs, constants, and method:\r\n  typedef double Scalar;\r\n  typedef double RealScalar;\r\n  typedef int StorageIndex;\r\n  enum {\r\n    ColsAtCompileTime = Eigen::Dynamic,\r\n    MaxColsAtCompileTime = Eigen::Dynamic,\r\n    IsRowMajor = false\r\n  };\r\n\r\n  Index rows() const { return mp_mat->rows(); }\r\n  Index cols() const { return mp_mat->cols(); }\r\n\r\n  template<typename Rhs>\r\n  Eigen::Product<MatrixReplacement,Rhs,Eigen::AliasFreeProduct> operator*(const Eigen::MatrixBase<Rhs>& x) const {\r\n    return Eigen::Product<MatrixReplacement,Rhs,Eigen::AliasFreeProduct>(*this, x.derived());\r\n  }\r\n\r\n  // Custom API:\r\n  MatrixReplacement() : mp_mat(0) {}\r\n\r\n  void attachMyMatrix(const SparseMatrix<double> &mat) {\r\n    mp_mat = &mat;\r\n  }\r\n  const SparseMatrix<double> my_matrix() const { return *mp_mat; }\r\n\r\nprivate:\r\n  const SparseMatrix<double> *mp_mat;\r\n};\r\n\r\n\r\n// Implementation of MatrixReplacement * Eigen::DenseVector though a specialization of internal::generic_product_impl:\r\nnamespace Eigen {\r\nnamespace internal {\r\n\r\n  template<typename Rhs>\r\n  struct generic_product_impl<MatrixReplacement, Rhs, SparseShape, DenseShape, GemvProduct> // GEMV stands for matrix-vector\r\n  : generic_product_impl_base<MatrixReplacement,Rhs,generic_product_impl<MatrixReplacement,Rhs> >\r\n  {\r\n    typedef typename Product<MatrixReplacement,Rhs>::Scalar Scalar;\r\n\r\n    template<typename Dest>\r\n    static void scaleAndAddTo(Dest& dst, const MatrixReplacement& lhs, const Rhs& rhs, const Scalar& alpha)\r\n    {\r\n      // This method should implement \"dst += alpha * lhs * rhs\" inplace,\r\n      // however, for iterative solvers, alpha is always equal to 1, so let's not bother about it.\r\n      assert(alpha==Scalar(1) && \"scaling is not implemented\");\r\n\r\n      // Here we could simply call dst.noalias() += lhs.my_matrix() * rhs,\r\n      // but let's do something fancier (and less efficient):\r\n      for(Index i=0; i<lhs.cols(); ++i)\r\n        dst += rhs(i) * lhs.my_matrix().col(i);\r\n    }\r\n  };\r\n\r\n}\r\n}\r\n\r\nint main()\r\n{\r\n  int n = 10;\r\n  Eigen::SparseMatrix<double> S = Eigen::MatrixXd::Random(n,n).sparseView(0.5,1);\r\n  S = S.transpose()*S;\r\n\r\n  MatrixReplacement A;\r\n  A.attachMyMatrix(S);\r\n\r\n  Eigen::VectorXd b(n), x;\r\n  b.setRandom();\r\n\r\n  // Solve Ax = b using various iterative solver with matrix-free version:\r\n  {\r\n    Eigen::ConjugateGradient<MatrixReplacement, Eigen::Lower|Eigen::Upper, Eigen::IdentityPreconditioner> cg;\r\n    cg.compute(A);\r\n    x = cg.solve(b);\r\n    std::cout << \"CG:       #iterations: \" << cg.iterations() << \", estimated error: \" << cg.error() << std::endl;\r\n  }\r\n\r\n  {\r\n    Eigen::BiCGSTAB<MatrixReplacement, Eigen::IdentityPreconditioner> bicg;\r\n    bicg.compute(A);\r\n    x = bicg.solve(b);\r\n    std::cout << \"BiCGSTAB: #iterations: \" << bicg.iterations() << \", estimated error: \" << bicg.error() << std::endl;\r\n  }\r\n\r\n  {\r\n    Eigen::GMRES<MatrixReplacement, Eigen::IdentityPreconditioner> gmres;\r\n    gmres.compute(A);\r\n    x = gmres.solve(b);\r\n    std::cout << \"GMRES:    #iterations: \" << gmres.iterations() << \", estimated error: \" << gmres.error() << std::endl;\r\n  }\r\n\r\n  {\r\n    Eigen::DGMRES<MatrixReplacement, Eigen::IdentityPreconditioner> gmres;\r\n    gmres.compute(A);\r\n    x = gmres.solve(b);\r\n    std::cout << \"DGMRES:   #iterations: \" << gmres.iterations() << \", estimated error: \" << gmres.error() << std::endl;\r\n  }\r\n\r\n  {\r\n    Eigen::MINRES<MatrixReplacement, Eigen::Lower|Eigen::Upper, Eigen::IdentityPreconditioner> minres;\r\n    minres.compute(A);\r\n    x = minres.solve(b);\r\n    std::cout << \"MINRES:   #iterations: \" << minres.iterations() << \", estimated error: \" << minres.error() << std::endl;\r\n  }\r\n}\r\n", "meta": {"hexsha": "ebe7f9684266a9c15725e2c1df7a41e03c2aebd8", "size": 4363, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Eigen-3.3/doc/examples/matrixfree_cg.cpp", "max_stars_repo_name": "nins-k/CarND-Path-Planning-Project", "max_stars_repo_head_hexsha": "841a4aea5570ae4e036a12ba36ee499dba518881", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-02-24T17:39:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T11:02:38.000Z", "max_issues_repo_path": "src/Eigen-3.3/doc/examples/matrixfree_cg.cpp", "max_issues_repo_name": "nins-k/CarND-Path-Planning-Project", "max_issues_repo_head_hexsha": "841a4aea5570ae4e036a12ba36ee499dba518881", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Eigen-3.3/doc/examples/matrixfree_cg.cpp", "max_forks_repo_name": "nins-k/CarND-Path-Planning-Project", "max_forks_repo_head_hexsha": "841a4aea5570ae4e036a12ba36ee499dba518881", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-01-24T13:35:40.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-30T14:40:05.000Z", "avg_line_length": 33.8217054264, "max_line_length": 125, "alphanum_fraction": 0.6651386661, "num_tokens": 1099, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.45613904760919627}}
{"text": "#include <iostream>\n#include <cstring>\n#include <NTL/ZZ.h>\n#include <algorithm>\n#include <bitset>\n\nusing namespace NTL;\nusing namespace std;\nusing std::bitset;\n\nstring ZZToBits(ZZ num, const size_t n) {\n\tstring s = \"\";\n\tZZ last;\n\n\twhile (num != 0) {\n\t\tlast = num % 2;\n\t\tif (last == 1) {\n\t\t\ts += '1';\n\t\t} else {\n\t\t\ts += '0';\n\t\t}\n\t\tnum /= 2;\n\t}\n\tfor (size_t i = s.length(); i < n; i++) {\n\t\ts += '0';\n\t}\n\treverse(s.begin(), s.end());\n\treturn s;\n}\n\nconst unsigned char DERTable[] = \"0123456789ABCDEF\";\n\nvoid PrintInDER(const string s) {\n    cout << \"modulus:\";\n    string pairstr = \"\";\n    for (size_t i = 0; i < s.length(); i += 4) {\n        int index = 0;\n        \n        for (size_t j = i; j < i + 4; j++) {\n            index = index << 1;\n            if (s[j] == '1') {\n                index += 1;\n            }\n        }\n        pairstr += DERTable[index];\n        if (pairstr.length() == 2) {\n            cout << pairstr;\n            if (i + 4 < s.length()) {\n                cout << \":\";\n            }\n            pairstr = \"\";\n        }\n        if (i % 120 == 0) {\n            cout << endl << '\\t';\n        }\n    }\n    cout << endl;\n}\n\nconst string Base64Map =\n\t\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n\t\"abcdefghijklmnopqrstuvwxyz\"\n\t\"0123456789+/\";\n\nvoid PrintInPEM(const string s) {\n\tstring res = \"\";\n\tsize_t len = s.length() / 8;\t// \u6bd4\u7279\u4e32\u8f6c\u5316\u4e3a\u5b57\u8282\u7684\u957f\u5ea6\n\tsize_t i;\n\tunsigned char triBytes[3];\t\t// \u5b58\u50a8\u4e09\u4e2a\u5b57\u8282\n\n\tfor (i = 0; i+3 <= len; i += 3) {\n\t\tfor (int j = 0; j < 3; j++) {\n\t\t\tbitset<8> tmp(s.substr(8*i + 8*j, 8));\n\t\t\ttriBytes[j] = tmp.to_ulong();\n\t\t}\n\t\tres += Base64Map[triBytes[0] >> 2];\n\t\tres += Base64Map[((triBytes[0]<<4) & 0x30) | (triBytes[1] >> 4)];\n\t\tres += Base64Map[((triBytes[1]<<2) & 0x3c) | (triBytes[2] >> 6)];\n\t\tres += Base64Map[triBytes[2] & 0x3f];\n\t}\n\n\tif (i < len) {\n\t\tif (len - i == 1) {\n\t\t\tbitset<8> tmp(s.substr(8*i, 8));\n\t\t\ttriBytes[0] = tmp.to_ulong();\n\t\t\tres += Base64Map[triBytes[0] >> 2];\n\t\t\tres += Base64Map[(triBytes[0]<<4) & 0x30];\n\t\t\tres += \"==\";\n\t\t} else {\n\t\t\tfor (int j = 0; j < 2; j++) {\n\t\t\t\tbitset<8> tmp(s.substr(8*i + 8*j, 8));\n\t\t\t\ttriBytes[j] = tmp.to_ulong();\n\t\t\t}\n\t\t\tres += Base64Map[triBytes[0] >> 2];\n\t\t\tres += Base64Map[((triBytes[0]<<4) & 0x30) | (triBytes[1] >> 4)];\n\t\t\tres += Base64Map[(triBytes[1]<<2) & 0x3c];\n\t\t\tres += \"=\";\n\t\t}\n\t}\n\n\tcout << res << endl;\n}\n\nint main() {\n\tZZ num(4164596496416416);\n\t\n\tstring s = ZZToBits(num, 64);\n\tcout << s << endl;\n\tcout << s.length() << endl;\n\tPrintInDER(s);\n\tcout << endl;\n\tPrintInPEM(s);\n\t\n\treturn 0;\n}", "meta": {"hexsha": "e10fd9a6b2bf8d3152644fd4ed602f59e4f3c161", "size": 2475, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "foo.cpp", "max_stars_repo_name": "yuanyangwangTJ/RSA", "max_stars_repo_head_hexsha": "384423bf33d555047755bb253a3531e35870ffd6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "foo.cpp", "max_issues_repo_name": "yuanyangwangTJ/RSA", "max_issues_repo_head_hexsha": "384423bf33d555047755bb253a3531e35870ffd6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "foo.cpp", "max_forks_repo_name": "yuanyangwangTJ/RSA", "max_forks_repo_head_hexsha": "384423bf33d555047755bb253a3531e35870ffd6", "max_forks_repo_licenses": ["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.5217391304, "max_line_length": 68, "alphanum_fraction": 0.4957575758, "num_tokens": 890, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.45613904760919627}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2017 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_MAX_ELEMENT_HPP_INCLUDED\n#define BOOST_SIMD_ALGORITHM_MAX_ELEMENT_HPP_INCLUDED\n\n#include <boost/simd/algorithm/max_val.hpp>\n#include <boost/simd/algorithm/find.hpp>\n\nnamespace boost { namespace simd\n{\n  /*!\n    @ingroup group-algo\n\n    Returns an iterator pointing to the element with the greatest value in the range [first,last).\n\n    @param first  Beginning of the range of elements to max_element\n    @param last   End of the range of elements to max_element\n    @param comp   comparison function object that will be applied.\n\n    @par Requirement\n\n      - @c first and @c last must be pointer to Vectorizable type.\n      - @c comp must be a polymorphic unary function object, i.e callable on generic types.\n      - if @c comp is not present the function test is done with operator <\n\n    @par Example:\n\n      @snippet max_element.cpp max_element\n\n    @par Possible output:\n\n      @snippet max_element.txt max_element\n\n  **/\n  template<typename T, typename Comp>\n  T const * max_element(T const* first, T const* last, Comp comp)\n  {\n    if (first == last) return last;\n    return find(first, last, max_val(first, last, comp));\n  }\n\n  template<typename T>\n  T const * max_element(T const* first, T const* last)\n  {\n    if (first == last) return last;\n    return find(first, last, max_val(first, last));\n  }\n} }\n\n#endif\n", "meta": {"hexsha": "b934baa89181a1a1be5536384522b7411daa2f74", "size": 1743, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/algorithm/max_element.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/algorithm/max_element.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/algorithm/max_element.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": 29.5423728814, "max_line_length": 100, "alphanum_fraction": 0.6265060241, "num_tokens": 378, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.45613904760919627}}
{"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_FMA_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_FMA_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n  /*!\n\n    @ingroup group-arithmetic\n    Function object function implementing fma capabilities\n\n    Computes the (fused) multiply add of the three parameters.\n\n    @par semantic:\n    For any given value @c x,  @c y,  @c z of type @c T:\n\n    @code\n    T r = fma(x, y, z);\n    @endcode\n\n    The code is similar to:\n\n    @code\n    T r = x*y+z;\n    @endcode\n\n    @par Note\n    Conformant fused multiply/add implies\n\n    - only one rounding\n\n    - no \"intermediate\" overflow\n\n    fma provides this for all integral types and each time it is reasonable\n    in terms of performance for floating ones (i.e. if the system has the hard\n    wired capability).\n\n    If you need pedantic fma capabilities in all circumstances in your own\n    code you can use the pedantic_ or  std_ decorator\n    (although both can can be very expensive).\n\n     @par Decorators\n\n    - std_ for floating entries to call directly std::fma. This implies pedantic\n      fma behaviour, but in no way improved performances.\n    - pedantic_ ensures the fma properties and allows SIMD acceleration if available.\n\n    @see fms, fnma, fnms\n  **/\n    Value fma(Value const& v0, Value const& v1, Value const& v2);\n  }\n} }\n#endif\n\n#include <boost/simd/function/scalar/fma.hpp>\n#include <boost/simd/function/simd/fma.hpp>\n\n#endif\n", "meta": {"hexsha": "d1ba2af349b8026e7244add9becdb8fac2678815", "size": 1831, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/fma.hpp", "max_stars_repo_name": "nickporubsky/boost-simd-clone", "max_stars_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_stars_repo_licenses": ["BSL-1.0"], "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": "include/boost/simd/function/fma.hpp", "max_issues_repo_name": "nickporubsky/boost-simd-clone", "max_issues_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/function/fma.hpp", "max_forks_repo_name": "nickporubsky/boost-simd-clone", "max_forks_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_forks_repo_licenses": ["BSL-1.0"], "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": 26.5362318841, "max_line_length": 100, "alphanum_fraction": 0.6253413435, "num_tokens": 429, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.45613904760919627}}
{"text": "#include <exe/inputParser.h>\n\n#include <base/cgal_typedefs.h>\n#include <IO/fileIO.h>\n\n#include <CGAL/optimal_bounding_box.h>\n#include <CGAL/Polygon_mesh_processing/triangulate_faces.h>\n\n#include <boost/filesystem.hpp>\nusing namespace boost::filesystem;\n\n\n\nint main(int argc, char const *argv[]){\n\n\n    cliParser ip(\"clf\");\n    if(ip.parse(argc, argv))\n        return 1;\n    if(ip.getInput())\n        return 1;\n    if(ip.getOutput())\n        return 1;\n\n    auto start = std::chrono::high_resolution_clock::now();\n    cout << \"\\n-----MAKE AN ORIENTED BOUNDING BOX AND SAVE AS PLY-----\" << endl;\n    cout << \"\\nWorking dir set to:\\n\\t-\" << ip.dh.path << endl;\n\n    dataHolder data;\n\n    importLidarPoints(ip.dh,data);\n    std::array<Point, 8> obb_points;\n    CGAL::oriented_bounding_box(data.points,obb_points);\n    SurfaceMesh obb_sm;\n    if(ip.ro.scale > 0.0){\n        double mx = 0, my = 0, mz = 0;\n        for(const auto p : obb_points){\n            mx+=p.x();\n            my+=p.y();\n            mz+=p.z();\n        }\n        Point centroid(mx/8,my/8,mz/8);\n        std::array<Point, 8> obb_scaled;\n        int i = 0;\n        for(const auto p : obb_points){\n            Vector mover(ip.ro.scale*(p.x() - centroid.x()),\n                         ip.ro.scale*(p.y() - centroid.y()),\n                         ip.ro.scale*(p.z() - centroid.z()));\n            obb_scaled[i++] = p + mover;\n        }\n        CGAL::make_hexahedron(obb_scaled[0], obb_scaled[1], obb_scaled[2], obb_scaled[3],\n                              obb_scaled[4], obb_scaled[5], obb_scaled[6], obb_scaled[7], obb_sm);\n\n    }\n    else{\n        CGAL::make_hexahedron(obb_points[0], obb_points[1], obb_points[2], obb_points[3],\n                              obb_points[4], obb_points[5], obb_points[6], obb_points[7], obb_sm);\n    }\n    CGAL::Polygon_mesh_processing::triangulate_faces(obb_sm);\n\n\n    if(ip.dh.write_file.empty())\n        ip.dh.write_file = ip.dh.read_file;\n    std::ofstream out(ip.dh.path+ip.dh.write_file+\"_obb.ply\");\n    CGAL::write_ply(out,obb_sm);\n\n    auto stop = std::chrono::high_resolution_clock::now();\n    auto duration = std::chrono::duration_cast<std::chrono::seconds>(stop - start);\n    cout << \"\\n-----MAKE AN ORIENTED BOUNDING BOX AND SAVE AS PLY FINISHED in \"<< duration.count() << \"s -----\\n\" << endl;\n\n    return 0;\n\n}\n\n\n\n", "meta": {"hexsha": "f88f0f2b7b56719709ca622c84e5ca1ebbdc205d", "size": 2319, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/exe/boundingBox.cpp", "max_stars_repo_name": "raphaelsulzer/mesh-tools", "max_stars_repo_head_hexsha": "73150bec58813e2b9b750205807002a1c3f18884", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-24T03:39:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T03:39:05.000Z", "max_issues_repo_path": "src/exe/boundingBox.cpp", "max_issues_repo_name": "raphaelsulzer/mesh-tools", "max_issues_repo_head_hexsha": "73150bec58813e2b9b750205807002a1c3f18884", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-02-24T06:59:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T01:25:09.000Z", "max_forks_repo_path": "src/exe/boundingBox.cpp", "max_forks_repo_name": "raphaelsulzer/mesh-tools", "max_forks_repo_head_hexsha": "73150bec58813e2b9b750205807002a1c3f18884", "max_forks_repo_licenses": ["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.1168831169, "max_line_length": 122, "alphanum_fraction": 0.5812850367, "num_tokens": 656, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286833, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4561390476091962}}
{"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 \"toplevelfixture.hpp\"\n#include <boost/make_shared.hpp>\n#include <boost/test/unit_test.hpp>\n#include <ql/quotes/simplequote.hpp>\n#include <ql/termstructures/volatility/equityfx/blackvariancecurve.hpp>\n#include <ql/time/calendars/target.hpp>\n#include <ql/time/daycounters/actualactual.hpp>\n#include <qle/termstructures/blackvariancecurve3.hpp>\n\nusing namespace boost::unit_test_framework;\nusing namespace QuantLib;\nusing namespace QuantExt;\nusing namespace std;\n\nBOOST_FIXTURE_TEST_SUITE(QuantExtTestSuite, qle::test::TopLevelFixture)\n\nBOOST_AUTO_TEST_SUITE(BlackVarianceCurveTest)\n\nBOOST_AUTO_TEST_CASE(testBlackVarianceCurve) {\n\n    BOOST_TEST_MESSAGE(\"Testing QuantExt::BlackVarianceCurve3...\");\n\n    SavedSettings backup;\n    Settings::instance().evaluationDate() = Date(1, Dec, 2015);\n    Date today = Settings::instance().evaluationDate();\n\n    Natural settlementDays = 0;\n    Calendar cal = TARGET();\n    BusinessDayConvention bdc = Following;\n    DayCounter dc = ActualActual();\n\n    vector<Time> times;\n    vector<Date> dates;\n    vector<Volatility> vols;\n    vector<boost::shared_ptr<SimpleQuote> > simpleQuotes;\n    vector<Handle<Quote> > quotes;\n\n    Size numYears = 10;\n    for (Size i = 1; i < numYears; i++) {\n\n        Volatility vol = 0.1 + (0.01 * i); // 11% at 1Y, 12% at 2Y\n        vols.push_back(vol);\n\n        simpleQuotes.push_back(boost::make_shared<SimpleQuote>(vol));\n        quotes.push_back(Handle<Quote>(simpleQuotes.back()));\n\n        dates.push_back(Date(1, Dec, today.year() + i));\n        times.push_back(dc.yearFraction(today, dates.back()));\n    }\n\n    // Build a QuantLib::BlackVarianceCurve\n    BlackVarianceCurve bvcBase(today, dates, vols, dc);\n    bvcBase.enableExtrapolation();\n\n    // Build a QuantExt::BlackVarianceCurve3\n    BlackVarianceCurve3 bvcTest(settlementDays, cal, bdc, dc, times, quotes);\n    bvcTest.enableExtrapolation();\n\n    Real strike = 1.0; // this is all ATM so we don't care\n\n    // Check that bvcTest returns the expected values\n    for (Size i = 0; i < times.size(); ++i) {\n        BOOST_CHECK_CLOSE(bvcTest.blackVol(times[i], strike), vols[i], 1e-12);\n        BOOST_CHECK_CLOSE(bvcTest.blackVol(dates[i], strike), vols[i], 1e-12);\n    }\n\n    // Now check that they give the same vols (including extrapolation)\n    for (Time t = 0.1; t < numYears + 10.0; t += 0.1) {\n        BOOST_CHECK_CLOSE(bvcBase.blackVol(t, strike), bvcTest.blackVol(t, strike), 1e-12);\n    }\n\n    // Now double the quotes\n    for (Size i = 0; i < simpleQuotes.size(); ++i) {\n        simpleQuotes[i]->setValue(simpleQuotes[i]->value() * 2.0);\n    }\n    // and check again\n    for (Time t = 0.1; t < numYears + 10.0; t += 0.1) {\n        BOOST_CHECK_CLOSE(bvcBase.blackVol(t, strike), 0.5 * bvcTest.blackVol(t, strike), 1e-12);\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "77ccb8910b608216889035102b1a26820a67f573", "size": 3585, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QuantExt/test/blackvariancecurve.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/test/blackvariancecurve.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/test/blackvariancecurve.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": 34.8058252427, "max_line_length": 97, "alphanum_fraction": 0.7082287308, "num_tokens": 950, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799252, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.45613904046305065}}
{"text": "// Author(s): Wieger Wesselink\n// Copyright: see the accompanying file COPYING or copy at\n// https://github.com/mCRL2org/mCRL2/blob/master/COPYING\n//\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//\n/// \\file bisimulation_test.cpp\n/// \\brief Test the bisimulation algorithm.\n\n#define BOOST_TEST_MODULE bisimulation_test\n#include <boost/test/included/unit_test_framework.hpp>\n#include \"mcrl2/lps/detail/test_input.h\"\n#include \"mcrl2/lps/linearise.h\"\n#include \"mcrl2/pbes/bisimulation.h\"\n#include \"mcrl2/pbes/detail/pbessolve.h\"\n\nusing namespace mcrl2;\nusing namespace mcrl2::lps;\nusing namespace mcrl2::pbes_system;\nusing namespace mcrl2::log;\n\nvoid test_bisimulation(const std::string& s1, const std::string& s2,\n                       bool strongly_bisimilar,\n                       bool branching_bisimilar,\n                       bool branching_similar,\n                       bool weakly_bisimilar,\n                       bool linearize = false)\n{\n  specification spec1;\n  specification spec2;\n  if (linearize)\n  {\n    spec1 = remove_stochastic_operators(linearise(s1));\n    spec2 = remove_stochastic_operators(linearise(s2));\n  }\n  else\n  {\n    spec1 = parse_linear_process_specification(s1);\n    spec2 = parse_linear_process_specification(s2);\n  }\n\n  std::clog << \"Testing strong bisimulation\" << std::endl;\n  pbes sb  = strong_bisimulation(spec1, spec2);\n  BOOST_CHECK(sb.is_well_typed());\n  bool sb_solution = pbes_system::detail::pbessolve(sb);\n  BOOST_CHECK(sb_solution == strongly_bisimilar);\n\n  std::clog << \"Testing branching bisimulation\" << std::endl;\n  pbes bb  = branching_bisimulation(spec1, spec2);\n  bool bb_solution = pbes_system::detail::pbessolve(bb);\n  BOOST_CHECK(bb.is_well_typed());\n  BOOST_CHECK(bb_solution == branching_bisimilar);\n\n  std::clog << \"Testing branching simulation\" << std::endl;\n  pbes bs = branching_simulation_equivalence(spec1, spec2);\n  bool bs_solution = pbes_system::detail::pbessolve(bs);\n  BOOST_CHECK(bs.is_well_typed());\n  BOOST_CHECK(bs_solution == branching_similar);\n\n  std::clog << \"Testing weak bisimulation\" << std::endl;\n  pbes wb  = weak_bisimulation(spec1, spec2);\n  bool wb_solution = pbes_system::detail::pbessolve(wb);\n  BOOST_CHECK(wb.is_well_typed());\n  BOOST_CHECK(wb_solution == weakly_bisimilar);\n}\n\nBOOST_AUTO_TEST_CASE(ABP)\n{\n  test_bisimulation(lps::detail::LINEAR_ABP_SPECIFICATION(), lps::detail::LINEAR_ABP_SPECIFICATION(), true, true, true, true);\n}\n\nBOOST_AUTO_TEST_CASE(SMALLSPEC)\n{\n  const std::string SMALLSPEC =\n    \"act a,b;                 \\n\"\n    \"proc X(s: Pos) =         \\n\"\n    \"  (s == 1) -> a . X(2)   \\n\"\n    \"+ (s == 2) -> tau . X(3) \\n\"\n    \"+ (s == 3) -> tau . X(4) \\n\"\n    \"+ (s == 4) -> b . X(1);  \\n\"\n    \"init X(1);               \\n\"\n    ;\n  test_bisimulation(SMALLSPEC, SMALLSPEC, true, true, true, true);\n}\n\nBOOST_AUTO_TEST_CASE(small_different_specs)\n{\n  const std::string s1 =\n    \"act a,b;                 \\n\"\n    \"proc X(s: Pos) =         \\n\"\n    \"  (s == 1) ->  a . X(2)  \\n\"\n    \"+ (s == 2) -> b . X(1);  \\n\"\n    \"init X(1);               \\n\"\n    ;\n  const std::string s2 =\n    \"act a,b,c;               \\n\"\n    \"proc X(s: Pos) =     \\n\"\n    \"  (s == 1) ->  a . X(2)  \\n\"\n    \"+ (s == 1) ->  c . X(1)  \\n\"\n    \"+ (s == 2) -> b . X(1);  \\n\"\n    \"init X(1);               \\n\"\n    ;\n    ;\n  test_bisimulation(s1, s2, false, false, false, false);\n  test_bisimulation(s2, s1, false, false, false, false);\n}\n\nBOOST_AUTO_TEST_CASE(buffers_silent_lose)\n{\n  const std::string buffer =\n    \"sort D = struct d1 | d2;\\n\"\n    \"map  n: Pos;\\n\"\n    \"eqn  n  =  2;\\n\"\n    \"act  r,s: D;\\n\"\n    \"proc P(b_Buffer: List(D)) =\\n\"\n    \"       !(b_Buffer == []) ->\\n\"\n    \"         s(rhead(b_Buffer)) .\\n\"\n    \"         P(b_Buffer = rtail(b_Buffer))\\n\"\n    \"     + sum d_Buffer: D.\\n\"\n    \"         (#b_Buffer < 2) ->\\n\"\n    \"         r(d_Buffer) .\\n\"\n    \"         P(b_Buffer = d_Buffer |> b_Buffer)\\n\"\n    \"     + delta;\\n\"\n    \"init P([]);\\n\";\n\n  const std::string lossy_buffer =\n    \"sort D = struct d1 | d2;\\n\"\n    \"map  n: Pos;\\n\"\n    \"eqn  n  =  2;\\n\"\n    \"act  r,s: D;\\n\"\n    \"proc P(s3_Buffer: Pos, d_Buffer: D, b_Buffer: List(D)) =\\n\"\n    \"       sum e_Buffer: Bool.\\n\"\n    \"         (s3_Buffer == 2) ->\\n\"\n    \"         tau .\\n\"\n    \"         P(s3_Buffer = 1, d_Buffer = d1, b_Buffer = if(e_Buffer, d_Buffer |> b_Buffer, b_Buffer))\\n\"\n    \"     + (s3_Buffer == 1 && !(b_Buffer == [])) ->\\n\"\n    \"         s(rhead(b_Buffer)) .\\n\"\n    \"         P(s3_Buffer = 1, d_Buffer = d1, b_Buffer = rtail(b_Buffer))\\n\"\n    \"     + sum d0_Buffer: D.\\n\"\n    \"         (s3_Buffer == 1 && #b_Buffer < 2) ->\\n\"\n    \"         r(d0_Buffer) .\\n\"\n    \"         P(s3_Buffer = 2, d_Buffer = d0_Buffer)\\n\"\n    \"     + delta;\\n\"\n    \"init P(1, d1, []);\\n\";\n\n  test_bisimulation(buffer, lossy_buffer, false, false, false, false);\n  test_bisimulation(lossy_buffer, buffer, false, false, false, false);\n}\n\nBOOST_AUTO_TEST_CASE(buffers_explicit_lose)\n{\n  const std::string buffer =\n    \"sort D = struct d1 | d2;\\n\"\n    \"map  n: Pos;\\n\"\n    \"eqn  n  =  2;\\n\"\n    \"act  r,s: D;\\n\"\n    \"proc P(b_Buffer: List(D)) =\\n\"\n    \"       !(b_Buffer == []) ->\\n\"\n    \"         s(rhead(b_Buffer)) .\\n\"\n    \"         P(b_Buffer = rtail(b_Buffer))\\n\"\n    \"     + sum d_Buffer: D.\\n\"\n    \"         (#b_Buffer < 2) ->\\n\"\n    \"         r(d_Buffer) .\\n\"\n    \"         P(b_Buffer = d_Buffer |> b_Buffer)\\n\"\n    \"     + delta;\\n\"\n    \"init P([]);\\n\";\n\n  const std::string lossy_buffer =\n      \"sort D = struct d1 | d2;\\n\"\n      \"map  n: Pos;\\n\"\n      \"eqn  n  =  2;\\n\"\n      \"act  r,s: D;\\n\"\n      \"     lose;\\n\"\n      \"proc P(s3_Buffer: Pos, d_Buffer: D, b_Buffer: List(D)) =\\n\"\n      \"       sum d0_Buffer: D.\\n\"\n      \"         (s3_Buffer == 1 && #b_Buffer < 2) ->\\n\"\n      \"         r(d0_Buffer) .\\n\"\n      \"         P(s3_Buffer = 2, d_Buffer = d0_Buffer)\\n\"\n      \"     + (s3_Buffer == 1 && !(b_Buffer == [])) ->\\n\"\n      \"         s(rhead(b_Buffer)) .\\n\"\n      \"         P(s3_Buffer = 1, d_Buffer = d1, b_Buffer = rtail(b_Buffer))\\n\"\n      \"     + (s3_Buffer == 2) ->\\n\"\n      \"         tau .\\n\"\n      \"         P(s3_Buffer = 3, d_Buffer = d1)\\n\"\n      \"     + (s3_Buffer == 2) ->\\n\"\n      \"         tau .\\n\"\n      \"         P(s3_Buffer = 1, d_Buffer = d1, b_Buffer = d_Buffer |> b_Buffer)\\n\"\n      \"     + (s3_Buffer == 3) ->\\n\"\n      \"         lose .\\n\"\n      \"         P(s3_Buffer = 1, d_Buffer = d1)\\n\"\n      \"     + delta;\\n\"\n      \"init P(1, d1, []);\\n\";\n\n  test_bisimulation(buffer, lossy_buffer, false, false, false, false);\n  test_bisimulation(lossy_buffer, buffer, false, false, false, false);\n}\n", "meta": {"hexsha": "0f19db05333e9ea65124757f409cc507d972afaa", "size": 6665, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libraries/pbes/test/bisimulation_test.cpp", "max_stars_repo_name": "Noxsense/mCRL2", "max_stars_repo_head_hexsha": "dd2fcdd6eb8b15af2729633041c2dbbd2216ad24", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 61.0, "max_stars_repo_stars_event_min_datetime": "2018-05-24T13:14:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T11:35:03.000Z", "max_issues_repo_path": "libraries/pbes/test/bisimulation_test.cpp", "max_issues_repo_name": "Noxsense/mCRL2", "max_issues_repo_head_hexsha": "dd2fcdd6eb8b15af2729633041c2dbbd2216ad24", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 229.0, "max_issues_repo_issues_event_min_datetime": "2018-05-28T08:31:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T11:02:41.000Z", "max_forks_repo_path": "libraries/pbes/test/bisimulation_test.cpp", "max_forks_repo_name": "Noxsense/mCRL2", "max_forks_repo_head_hexsha": "dd2fcdd6eb8b15af2729633041c2dbbd2216ad24", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 28.0, "max_forks_repo_forks_event_min_datetime": "2018-04-11T14:09:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-25T15:57:39.000Z", "avg_line_length": 33.4924623116, "max_line_length": 126, "alphanum_fraction": 0.5515378845, "num_tokens": 2205, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799252, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.45613904046305065}}
{"text": "//\n// Created by Kaung Zaw Htet on 2019-11-24.\n//\n\n#include <gtest/gtest.h>\n#include <iostream>\n#include <randomizer/ph_number_randomizer.h>\n#include <randomizer/faster_random.h>\n#include <random>\nusing namespace std;\nTEST(GeneralTest,fasterRandom){\n\n    std::random_device gen;\n    pcg generatorObject(gen);\n    std::uniform_int_distribution<int> myanNumDistribution(1, 1000);\n    for (int i = 0; i < 100; ++i) {\n\n      //  boost::random::random_device gen=boost::random::random_device();\n        std::cout<< myanNumDistribution(generatorObject)<<std::endl;\n        // std::mt19937 generatorObject(static_cast<unsigned int>(time(0)));\n    }\n}\n\ntemplate<typename T>\nvoid showMinMax() {\n    cout << \"min: \" << numeric_limits<T>::min() << endl;\n    cout << \"max: \" << numeric_limits<T>::max() << endl;\n    cout << endl;\n}\n\nTEST(GeneralTest,limit){\n\n    cout << \"short:\" << endl;\n    showMinMax<short>();\n    cout << \"int:\" << endl;\n    showMinMax<int>();\n    cout << \"long:\" << endl;\n    showMinMax<long>();\n    cout << \"float:\" << endl;\n    showMinMax<float>();\n    cout << \"double:\" << endl;\n    showMinMax<double>();\n    cout << \"long double:\" << endl;\n    showMinMax<long double>();\n    cout << \"unsigned short:\" << endl;\n    showMinMax<unsigned short>();\n    cout << \"unsigned int:\" << endl;\n    showMinMax<unsigned int>();\n    cout << \"unsigned long:\" << endl;\n    showMinMax<unsigned long>();\n\n\n}\n\nTEST(GeneralTest,uniqueToArr){\n\n   auto a= std::make_unique<std::string[]>(100);\n    /*a[0]= \"h\";\n    a[1]= \"rw\";\n    a[2]= \"rwh\";\n    a[3]= \"egeg\";\n    a[4]= \"rgwgwh\";\n    a[5]= \"g3g\";*/\n    int count = sizeof(a)/ sizeof(a[0]);\n   for (int i=0; i < 6; i++)\n   {\n       cout<<a[i] <<endl;\n\n   }\n}\n#include <boost/hana.hpp>\nnamespace hana = boost::hana;\n\n\nTEST(GeneralTest,datastructures){\n\n\n}\n", "meta": {"hexsha": "5608e2a197185ac52db5dba55dbf46c873c5c675", "size": 1796, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/randomizer/general_test.cpp", "max_stars_repo_name": "KaungZawHtet/XMwayLoon", "max_stars_repo_head_hexsha": "4dd014dc75a209c242bba5d2dc4333af63bcb405", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2020-03-23T04:20:53.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-23T00:32:36.000Z", "max_issues_repo_path": "test/randomizer/general_test.cpp", "max_issues_repo_name": "KaungZawHtet/XMwayLoon", "max_issues_repo_head_hexsha": "4dd014dc75a209c242bba5d2dc4333af63bcb405", "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": "test/randomizer/general_test.cpp", "max_forks_repo_name": "KaungZawHtet/XMwayLoon", "max_forks_repo_head_hexsha": "4dd014dc75a209c242bba5d2dc4333af63bcb405", "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": 22.7341772152, "max_line_length": 76, "alphanum_fraction": 0.5940979955, "num_tokens": 509, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.4560476033196604}}
{"text": "// multi_precision.cpp : example program comparing float vs posit matrix inversion algorithms\n//\n// Copyright (C) 2017-2020 Stillwater Supercomputing, Inc.\n//\n// This file is part of the HPR-BLAS project, which is released under an MIT Open Source license.\n\n//#include <chrono>\n// Boost arbitrary precision floats\n#include <boost/multiprecision/cpp_bin_float.hpp>\n\n// configure the posit number system behavior\n#define POSIT_ROUNDING_ERROR_FREE_IO_FORMAT 0\n// configure the HPR-BLAS behavior\n#define HPRBLAS_TRACE_ROUNDING_EVENTS 0\n#include <hprblas>\n#include <mtl_extensions.hpp>\n// matrix generators\n#include <generators/matrix_generators.hpp>\n#include <utils/print_utils.hpp>\n\nusing namespace sw::universal;\n\nint main(int argc, char** argv)\ntry {\n\tusing namespace std;\n\tusing namespace mtl;\n\tusing namespace sw::hprblas;\n\tusing namespace boost::multiprecision;\n\n\tusing sp = boost::multiprecision::cpp_bin_float_single;\n\tusing dp = boost::multiprecision::cpp_bin_float_double;\n\tusing qp = boost::multiprecision::cpp_bin_float_quad;\n\n\t{\n\t\tsp a{ 1.0 };\n\t\tsp b( 2.0 );\n\t\tsp c = a + b;\n\t\tcout << c << endl;\n\t}\n\n\treturn EXIT_SUCCESS;\n}\ncatch (char const* msg) {\n\tstd::cerr << msg << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (const posit_arithmetic_exception& err) {\n\tstd::cerr << \"Uncaught posit arithmetic exception: \" << err.what() << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (const quire_exception& err) {\n\tstd::cerr << \"Uncaught quire exception: \" << err.what() << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (const posit_internal_exception& err) {\n\tstd::cerr << \"Uncaught posit internal exception: \" << err.what() << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (std::runtime_error& err) {\n\tstd::cerr << err.what() << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (...) {\n\tstd::cerr << \"Caught unknown exception\" << std::endl;\n\treturn EXIT_FAILURE;\n}\n", "meta": {"hexsha": "2a17ac3ebaf445e3741052e3b9d1b138621e5e05", "size": 1841, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "solvers/multi_precision.cpp", "max_stars_repo_name": "shikharvashistha/hpr-blas", "max_stars_repo_head_hexsha": "73f109d45701fc3816af0a1ecd42f11d494a6f97", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2019-02-13T10:53:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-21T20:30:58.000Z", "max_issues_repo_path": "solvers/multi_precision.cpp", "max_issues_repo_name": "jamesquinlan/hpr-blas", "max_issues_repo_head_hexsha": "2975b4378b36a0bdc55d0dbd4f979163f7009678", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-07-20T16:45:52.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-17T11:19:32.000Z", "max_forks_repo_path": "solvers/multi_precision.cpp", "max_forks_repo_name": "jamesquinlan/hpr-blas", "max_forks_repo_head_hexsha": "2975b4378b36a0bdc55d0dbd4f979163f7009678", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-03-12T21:20:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-01T05:35:35.000Z", "avg_line_length": 27.4776119403, "max_line_length": 97, "alphanum_fraction": 0.7267789245, "num_tokens": 459, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.6584175005616829, "lm_q1q2_score": 0.45604760331966027}}
{"text": "// The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt\r\n/*\r\n    This is an example illustrating the use of the deep learning tools from the\r\n    dlib C++ Library.  In it, we will show how to use the loss_metric layer to do\r\n    metric learning.  \r\n\r\n    The main reason you might want to use this kind of algorithm is because you\r\n    would like to use a k-nearest neighbor classifier or similar algorithm, but\r\n    you don't know a good way to calculate the distance between two things.  A\r\n    popular example would be face recognition.  There are a whole lot of papers\r\n    that train some kind of deep metric learning algorithm that embeds face\r\n    images in some vector space where images of the same person are close to each\r\n    other and images of different people are far apart.  Then in that vector\r\n    space it's very easy to do face recognition with some kind of k-nearest\r\n    neighbor classifier.  \r\n\r\n    To keep this example as simple as possible we won't do face recognition.\r\n    Instead, we will create a very simple network and use it to learn a mapping\r\n    from 8D vectors to 2D vectors such that vectors with the same class labels\r\n    are near each other.  If you want to see a more complex example that learns\r\n    the kind of network you would use for something like face recognition read\r\n    the dnn_metric_learning_on_images_ex.cpp example.\r\n\r\n    You should also have read the examples that introduce the dlib DNN API before \r\n    continuing.  These are dnn_introduction_ex.cpp and dnn_introduction2_ex.cpp.\r\n*/\r\n\r\n\r\n#include <dlib/dnn.h>\r\n#include <iostream>\r\n\r\nusing namespace std;\r\nusing namespace dlib;\r\n\r\n\r\nint main() try\r\n{\r\n    // The API for doing metric learning is very similar to the API for\r\n    // multi-class classification.  In fact, the inputs are the same, a bunch of\r\n    // labeled objects.  So here we create our dataset.  We make up some simple\r\n    // vectors and label them with the integers 1,2,3,4.  The specific values of\r\n    // the integer labels don't matter.\r\n    std::vector<matrix<double,0,1>> samples;\r\n    std::vector<unsigned long> labels;\r\n\r\n    // class 1 training vectors\r\n    samples.push_back({1,0,0,0,0,0,0,0}); labels.push_back(1);\r\n    samples.push_back({0,1,0,0,0,0,0,0}); labels.push_back(1);\r\n\r\n    // class 2 training vectors\r\n    samples.push_back({0,0,1,0,0,0,0,0}); labels.push_back(2);\r\n    samples.push_back({0,0,0,1,0,0,0,0}); labels.push_back(2);\r\n\r\n    // class 3 training vectors\r\n    samples.push_back({0,0,0,0,1,0,0,0}); labels.push_back(3);\r\n    samples.push_back({0,0,0,0,0,1,0,0}); labels.push_back(3);\r\n\r\n    // class 4 training vectors\r\n    samples.push_back({0,0,0,0,0,0,1,0}); labels.push_back(4);\r\n    samples.push_back({0,0,0,0,0,0,0,1}); labels.push_back(4);\r\n\r\n\r\n    // Make a network that simply learns a linear mapping from 8D vectors to 2D\r\n    // vectors.\r\n    using net_type = loss_metric<fc<2,input<matrix<double,0,1>>>>; \r\n    net_type net;\r\n    dnn_trainer<net_type> trainer(net);\r\n    trainer.set_learning_rate(0.1);\r\n\r\n    // It should be emphasized out that it's really important that each mini-batch contain\r\n    // multiple instances of each class of object.  This is because the metric learning\r\n    // algorithm needs to consider pairs of objects that should be close as well as pairs\r\n    // of objects that should be far apart during each training step.  Here we just keep\r\n    // training on the same small batch so this constraint is trivially satisfied.\r\n    while(trainer.get_learning_rate() >= 1e-4)\r\n        trainer.train_one_step(samples, labels);\r\n\r\n    // Wait for training threads to stop\r\n    trainer.get_net();\r\n    cout << \"done training\" << endl;\r\n\r\n\r\n    // Run all the samples through the network to get their 2D vector embeddings.\r\n    std::vector<matrix<float,0,1>> embedded = net(samples);\r\n\r\n    // Print the embedding for each sample to the screen.  If you look at the\r\n    // outputs carefully you should notice that they are grouped together in 2D\r\n    // space according to their label.\r\n    for (size_t i = 0; i < embedded.size(); ++i)\r\n        cout << \"label: \" << labels[i] << \"\\t\" << trans(embedded[i]);\r\n\r\n    // Now, check if the embedding puts things with the same labels near each other and\r\n    // things with different labels far apart.\r\n    int num_right = 0;\r\n    int num_wrong = 0;\r\n    for (size_t i = 0; i < embedded.size(); ++i)\r\n    {\r\n        for (size_t j = i+1; j < embedded.size(); ++j)\r\n        {\r\n            if (labels[i] == labels[j])\r\n            {\r\n                // The loss_metric layer will cause things with the same label to be less\r\n                // than net.loss_details().get_distance_threshold() distance from each\r\n                // other.  So we can use that distance value as our testing threshold for\r\n                // \"being near to each other\".\r\n                if (length(embedded[i]-embedded[j]) < net.loss_details().get_distance_threshold())\r\n                    ++num_right;\r\n                else\r\n                    ++num_wrong;\r\n            }\r\n            else\r\n            {\r\n                if (length(embedded[i]-embedded[j]) >= net.loss_details().get_distance_threshold())\r\n                    ++num_right;\r\n                else\r\n                    ++num_wrong;\r\n            }\r\n        }\r\n    }\r\n\r\n    cout << \"num_right: \"<< num_right << endl;\r\n    cout << \"num_wrong: \"<< num_wrong << endl;\r\n}\r\ncatch(std::exception& e)\r\n{\r\n    cout << e.what() << endl;\r\n}\r\n\r\n", "meta": {"hexsha": "6aba7ff1fea09c4c75eeaceb7f813a2d37e8688b", "size": 5501, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/dnn_metric_learning_ex.cpp", "max_stars_repo_name": "ckproc/dlib-19.7", "max_stars_repo_head_hexsha": "0ca40f5e85de2436e557bee9a805d3987d2d9507", "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/dnn_metric_learning_ex.cpp", "max_issues_repo_name": "ckproc/dlib-19.7", "max_issues_repo_head_hexsha": "0ca40f5e85de2436e557bee9a805d3987d2d9507", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2018-02-27T15:44:25.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-28T01:26:03.000Z", "max_forks_repo_path": "examples/dnn_metric_learning_ex.cpp", "max_forks_repo_name": "ckproc/dlib-19.7", "max_forks_repo_head_hexsha": "0ca40f5e85de2436e557bee9a805d3987d2d9507", "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.6434108527, "max_line_length": 100, "alphanum_fraction": 0.6435193601, "num_tokens": 1349, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.6584175005616829, "lm_q1q2_score": 0.45604760331966027}}
{"text": "// ----------------------------------------------------------------------------------------------------------\n/// @file   vector_foo.cpp\n/// @brief  Test cases for Vector.\n// ----------------------------------------------------------------------------------------------------------\n#define BOOST_TEST_DYN_LINK\n\n#ifdef SEPARATE_TEST\n#define BOOST_TEST_MODULE NDArrayTest\n#endif\n\n#include <boost/test/unit_test.hpp>\n#include <iostream>\n#include <vector>\n\n#include \"ndarray.h\"\n#define N 7\n\nBOOST_AUTO_TEST_SUITE(VectorTestCases)\n\nBOOST_AUTO_TEST_CASE(VectorBasicBinaryOp) {\n  float *a = (float*)malloc(N * sizeof(float));\n  float *b = (float*)malloc(N * sizeof(float));\n  // bin op add\n  for(int i = 0; i<N; ++i) {\n    a[i] = b[i] = 1.f;\n  }\n  ndarray::Vector<float, N> v1(a);\n  ndarray::Vector<float, N> v2(b);\n  ndarray::Vector<float, N> v3;\n  v3 = v1 + v2;\n  std::cout << v3;\n  BOOST_CHECK(v3[0] == 2.f);\n  BOOST_CHECK(v3[1] == 2.f);\n  BOOST_CHECK(v3[2] == 2.f);\n  BOOST_CHECK(v3[3] == 2.f);\n  BOOST_CHECK(v3[4] == 2.f);\n  BOOST_CHECK(v3[5] == 2.f);\n  BOOST_CHECK(v3[6] == 2.f);\n\n  // bin op sub\n  for(int i = 0; i<N; ++i) {\n    a[i] = 3.f;\n    b[i] = 1.f;\n  }\n  ndarray::Vector<float, N> v4(a);\n  ndarray::Vector<float, N> v5(b);\n  ndarray::Vector<float, N> v6;\n  v6 = v4 - v5;\n  std::cout << v6;\n  BOOST_CHECK(v6[0] == 2.f);\n  BOOST_CHECK(v6[1] == 2.f);\n  BOOST_CHECK(v6[2] == 2.f);\n  BOOST_CHECK(v6[3] == 2.f);\n  BOOST_CHECK(v6[4] == 2.f);\n  BOOST_CHECK(v6[5] == 2.f);\n  BOOST_CHECK(v6[6] == 2.f);\n  // bin op mul\n  ndarray::Vector<float, N> v7;\n  v7 = v4 * v5;\n  std::cout << v7;\n  BOOST_CHECK(v7[0] == 3.f);\n  BOOST_CHECK(v7[1] == 3.f);\n  BOOST_CHECK(v7[2] == 3.f);\n  BOOST_CHECK(v7[3] == 3.f);\n  BOOST_CHECK(v7[4] == 3.f);\n  BOOST_CHECK(v7[5] == 3.f);\n  BOOST_CHECK(v7[6] == 3.f);\n\n  // bin op div\n  ndarray::Vector<float, N> v8;\n  v8 = v4 / v5;\n  std::cout << v8;\n  BOOST_CHECK(v8[0] == 3.f);\n  BOOST_CHECK(v8[1] == 3.f);\n  BOOST_CHECK(v8[2] == 3.f);\n  BOOST_CHECK(v8[3] == 3.f);\n  BOOST_CHECK(v8[4] == 3.f);\n  BOOST_CHECK(v8[5] == 3.f);\n  BOOST_CHECK(v8[6] == 3.f);\n  \n  // bin op max\n  ndarray::Vector<float, N> v9;\n  v9 = max(v4, v5);\n  std::cout << v9;\n  BOOST_CHECK(v9[0] == 3.f);\n  BOOST_CHECK(v9[1] == 3.f);\n  BOOST_CHECK(v9[2] == 3.f);\n  BOOST_CHECK(v9[3] == 3.f);\n  BOOST_CHECK(v9[4] == 3.f);\n  BOOST_CHECK(v9[5] == 3.f);\n  BOOST_CHECK(v9[6] == 3.f);\n  \n  // bin op min\n  ndarray::Vector<float, N> v10;\n  v10 = min(v4, v5);\n  std::cout << v10;\n  BOOST_CHECK(v10[0] == 1.f);\n  BOOST_CHECK(v10[1] == 1.f);\n  BOOST_CHECK(v10[2] == 1.f);\n  BOOST_CHECK(v10[3] == 1.f);\n  BOOST_CHECK(v10[4] == 1.f);\n  BOOST_CHECK(v10[5] == 1.f);\n  BOOST_CHECK(v10[6] == 1.f);\n  free(a);\n  free(b);\n}\n\nBOOST_AUTO_TEST_CASE(VectorBasicUnaryOp) {\n  float *a = (float*)malloc(N * sizeof(float));\n  // unary op sqrt\n  for(int i = 0; i<N; ++i) {\n    a[i] = 9.f;\n  }\n  ndarray::Vector<float, N> v1(a);\n  ndarray::Vector<float, N> v2;\n  v2 = sqrt(v1);\n  std::cout << v2;\n  BOOST_CHECK(v2[0] == 3.f);\n  BOOST_CHECK(v2[1] == 3.f);\n  BOOST_CHECK(v2[2] == 3.f);\n  BOOST_CHECK(v2[3] == 3.f);\n  BOOST_CHECK(v2[4] == 3.f);\n  BOOST_CHECK(v2[5] == 3.f);\n  BOOST_CHECK(v2[6] == 3.f);\n\n  // unary op rsqrt\n  for(int i = 0; i<N; ++i) {\n    a[i] = 16.f;\n  }\n  ndarray::Vector<float, N> v3(a);\n  ndarray::Vector<float, N> v4;\n  v4 = rsqrt(v3);\n  std::cout << v4;\n  BOOST_CHECK(std::abs(v4[0] - 0.25f) <= 1e-3);\n  BOOST_CHECK(std::abs(v4[1] - 0.25f) <= 1e-3);\n  BOOST_CHECK(std::abs(v4[2] - 0.25f) <= 1e-3);\n  BOOST_CHECK(std::abs(v4[3] - 0.25f) <= 1e-3);\n  BOOST_CHECK(std::abs(v4[4] - 0.25f) <= 1e-3);\n  BOOST_CHECK(std::abs(v4[5] - 0.25f) <= 1e-3);\n  BOOST_CHECK(std::abs(v4[6] - 0.25f) <= 1e-3);\n  free(a);\n}\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "e258b455ed1aeed37f253c85758e12788861c609", "size": 3712, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/vector_foo.cpp", "max_stars_repo_name": "lijiansong/ndarray", "max_stars_repo_head_hexsha": "9f843d5039292ce035b3ede1a0fbb0d103f959b5", "max_stars_repo_licenses": ["WTFPL"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-03-14T06:49:00.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-06T18:28:00.000Z", "max_issues_repo_path": "examples/vector_foo.cpp", "max_issues_repo_name": "lijiansong/ndarray", "max_issues_repo_head_hexsha": "9f843d5039292ce035b3ede1a0fbb0d103f959b5", "max_issues_repo_licenses": ["WTFPL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/vector_foo.cpp", "max_forks_repo_name": "lijiansong/ndarray", "max_forks_repo_head_hexsha": "9f843d5039292ce035b3ede1a0fbb0d103f959b5", "max_forks_repo_licenses": ["WTFPL"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-01-13T10:38:02.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-18T12:37:46.000Z", "avg_line_length": 25.7777777778, "max_line_length": 109, "alphanum_fraction": 0.5369073276, "num_tokens": 1447, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419958239132, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.4560476023893511}}
{"text": "#include <cstdlib>\n#include <iostream>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/bindings/lower.hpp>\n#include <boost/numeric/bindings/upper.hpp>\n#include <boost/numeric/bindings/ublas/vector.hpp>\n#include <boost/numeric/bindings/ublas/matrix.hpp>\n#include <boost/numeric/bindings/blas/level2.hpp>\n#include \"print.hpp\"\n#include \"random.hpp\"\n\nnamespace ublas=boost::numeric::ublas;\nnamespace blas=boost::numeric::bindings::blas;\n\nint main(int argc, char *argv[]) {\n  {\n    typedef ublas::vector<double> vector;\n    typedef ublas::matrix<double, ublas::column_major> matrix;\n    typedef vector::size_type size_type;\n    rand_normal<double>::reset();\n    size_type n=8;\n    matrix A(n, n);\n    for (size_type j=0; j<n; ++j) {\n      A(j, j)=rand_normal<double>::get();\n      for (size_type i=0; i<j; ++i) {\n\tA(i, j)=rand_normal<double>::get();\n\tA(j, i)=A(i, j);\n      }\n    }\n    vector x(n);\n    for (size_type i=0; i<n; ++i)\n      x(i)=rand_normal<double>::get();\n    double alpha(rand_normal<double>::get());\n    matrix P;\n    {\n      P=alpha*ublas::outer_prod(x, x);\n      for (size_type j=0; j<n; ++j) \n\tfor (size_type i=0; i<j; ++i) \n\t  P(i, j)=0;\n      matrix A1(P+A);\n      matrix A2(A);\n      blas::syr(alpha, x, blas::lower(A2));\n      std::cout << print_mat(A1) << '\\n'\n\t\t<< print_mat(A2) << '\\n';\n    }\n    {\n      P=alpha*ublas::outer_prod(x, x);\n      for (size_type j=0; j<n; ++j) \n\tfor (size_type i=j+1; i<n; ++i) \n\t  P(i, j)=0;\n      matrix A1(P+A);\n      matrix A2(A);\n      blas::syr(alpha, x, blas::upper(A2));\n      std::cout << print_mat(A1) << '\\n'\n\t\t<< print_mat(A2) << '\\n';\n    }\n  }\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "709723879ed115802216bf8a4edc41c9bf8501e7", "size": 1696, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/blas/syr.cc", "max_stars_repo_name": "rabauke/numeric_bindings", "max_stars_repo_head_hexsha": "f4de93bd7a01a8b31c9367fad35c81d086768f99", "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/blas/syr.cc", "max_issues_repo_name": "rabauke/numeric_bindings", "max_issues_repo_head_hexsha": "f4de93bd7a01a8b31c9367fad35c81d086768f99", "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/blas/syr.cc", "max_forks_repo_name": "rabauke/numeric_bindings", "max_forks_repo_head_hexsha": "f4de93bd7a01a8b31c9367fad35c81d086768f99", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8032786885, "max_line_length": 62, "alphanum_fraction": 0.6002358491, "num_tokens": 537, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812554, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.456002751513999}}
{"text": "/*!\n * Copyright (C) tkornuta, IBM Corporation 2015-2019\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 mnist_hebbian_features_visualization_test.cpp\n * @brief Program for visualization of features of hebbian network trained on MNIST digits.\n * @Author: Tomasz Kornuta <tkornut@us.ibm.com>\n * @Date:   May 16, 2017\n *\n * Copyright (c) 2017, Tomasz Kornuta, IBM Corporation. All rights reserved.\n *\n */\n\n#include <boost/thread/thread.hpp>\n#include <boost/bind.hpp>\n\n#include <data_io/MNISTMatrixImporter.hpp>\n\n#include <logger/Log.hpp>\n#include <logger/ConsoleOutput.hpp>\nusing namespace mic::logger;\n\n#include <application/ApplicationState.hpp>\n\n#include <configuration/ParameterServer.hpp>\n\n#include <opengl/visualization/WindowManager.hpp>\n#include <opengl/visualization/WindowGrayscaleBatch.hpp>\nusing namespace mic::opengl::visualization;\n\n// Hebbian neural net.\n#include <mlnn/HebbianNeuralNetwork.hpp>\nusing namespace mic::mlnn;\n\n// Encoders.\n#include <encoders/MatrixXfMatrixXfEncoder.hpp>\n#include <encoders/UIntMatrixXfEncoder.hpp>\n\n/// Window for displaying the MNIST batch.\nWindowGrayscaleBatch<float>* w_input;\nWindowGrayscaleBatch<float>* w_reconstruction;\n/// Window for displaying the weights.\nWindowGrayscaleBatch<float>* w_weights1;\nWindowGrayscaleBatch<float>* w_weights2;\n\n/// MNIST importer.\nmic::data_io::MNISTMatrixImporter<float>* importer;\n/// Multi-layer neural network.\nHebbianNeuralNetwork<float> neural_net;\n\n/// MNIST matrix encoder.\nmic::encoders::MatrixXfMatrixXfEncoder* mnist_encoder;\n/// Label 2 matrix encoder (1 hot).\n//mic::encoders::UIntMatrixXfEncoder* label_encoder;\n\nconst size_t patch_size = 28;\nconst size_t batch_size = 4;\nconst size_t output_units = 12;\n\n/*!\n * \\brief Function for batch sampling.\n * \\author tkornuta\n */\nvoid batch_function (void) {\n\n/*\tif (neural_net.load(fileName)) {\n\t\tLOG(LINFO) << \"Loaded neural network from a file\";\n\t} else {*/\n\t\t{\n\t\t// Create a simple hebbian network.\n\t\tneural_net.pushLayer(new BinaryCorrelator<float>(patch_size*patch_size, output_units, 0.6, 28*28*0.01));\n\t\tneural_net.setOptimization<  mic::neural_nets::learning::NormalizedHebbianRule<float> >();\n\n\t\tLOG(LINFO) << \"Generated new neural network\";\n\t}//: else\n\n\tsize_t iteration = 0;\n\n\t// Main application loop.\n\twhile (!APP_STATE->Quit()) {\n\n\t\t// If not paused.\n\t\tif (!APP_STATE->isPaused()) {\n\n\t\t\t// If single step mode - pause after the step.\n\t\t\tif (APP_STATE->isSingleStepModeOn())\n\t\t\t\tAPP_STATE->pressPause();\n\n\t\t\t{ // Enter critical section - with the use of scoped lock from AppState!\n\t\t\t\tAPP_DATA_SYNCHRONIZATION_SCOPED_LOCK();\n\n\t\t\t\t// Retrieve the next minibatch.\n\t\t\t\tmic::types::MNISTBatch<float> bt = importer->getRandomBatch();\n\n\t\t\t\t// Set batch to be displayed.\n\t\t\t\tw_input->setBatchUnsynchronized(bt.data());\n\n\t\t\t\t// Encode data.\n\t\t\t\tmic::types::MatrixXfPtr encoded_batch = mnist_encoder->encodeBatch(bt.data());\n\t\t\t\tmic::types::MatrixXfPtr encoded_labels = mnist_encoder->encodeBatch(bt.data());\n\n\t\t\t\t// Train the autoencoder.\n\t\t\t\tfloat loss = neural_net.train (encoded_batch, 0.05);\n\n\t\t\t\t// Get reconstruction.\n\t\t\t\tmic::types::MatrixXfPtr encoded_reconstruction = neural_net.getPredictions();\n\n\t\t\t\tstd::vector<mic::types::MatrixXfPtr> decoded_reconstruction = mnist_encoder->decodeBatch(encoded_reconstruction);\n\t\t\t\tw_reconstruction->setBatchUnsynchronized(decoded_reconstruction);\n\n\t\t\t\tif (iteration%10 == 0) {\n\t\t\t\t\t// Visualize the weights.\n\t\t\t\t\tstd::shared_ptr<mic::mlnn::BinaryCorrelator<float> > layer1 = neural_net.getLayer<mic::mlnn::BinaryCorrelator<float> >(0);\n\t\t\t\t\tw_weights1->setBatchUnsynchronized(layer1->getActivations(patch_size, patch_size));\n\n\t\t\t\t}//: if\n\n\t\t\t\titeration++;\n\t\t\t\tLOG(LINFO) << \"Iteration: \" << iteration << \"loss= \" << loss;\n\t\t\t}//: end of critical section\n\n\t\t}//: if\n\n\t\t// Sleep.\n\t\tAPP_SLEEP();\n\t}//: while\n\n}//: image_encoder_and_visualization_test\n\n\n\n/*!\n * \\brief Main program function. Runs two threads: main (for GLUT) and another one (for data processing).\n * \\author tkornuta\n * @param[in] argc Number of parameters (passed to glManaged).\n * @param[in] argv List of parameters (passed to glManaged).\n * @return (not used)\n */\nint main(int argc, char* argv[]) {\n\t// Set console output to logger.\n\tLOGGER->addOutput(new ConsoleOutput());\n\tLOG(LINFO) << \"Logger initialized. Starting application\";\n\n\t// Parse parameters.\n\tPARAM_SERVER->parseApplicationParameters(argc, argv);\n\n\t// Initilize application state (\"touch it\") ;)\n\tAPP_STATE;\n\n\t// Load dataset.\n\timporter = new mic::data_io::MNISTMatrixImporter<float>();\n\timporter->setBatchSize(batch_size);\n\n\t// Initialize the encoders.\n\tmnist_encoder = new mic::encoders::MatrixXfMatrixXfEncoder(patch_size, patch_size);\n\t//label_encoder = new mic::encoders::UIntMatrixXfEncoder(batch_size);\n\n\t// Set parameters of all property-tree derived objects - USER independent part.\n\tPARAM_SERVER->loadPropertiesFromConfiguration();\n\n\t// Initialize property-dependent variables of all registered property-tree objects - USER dependent part.\n\tPARAM_SERVER->initializePropertyDependentVariables();\n\n\t// Import data from datasets.\n\tif (!importer->importData())\n\t\treturn -1;\n\n\t// Initialize GLUT! :]\n\tVGL_MANAGER->initializeGLUT(argc, argv);\n\n\t// Create batch visualization window.\n\tw_input = new WindowGrayscaleBatch<float>(\"Input batch\", Grayscale::Norm_HotCold, Grayscale::Grid_Both, 70, 0, 250, 250);\n\tw_reconstruction = new WindowGrayscaleBatch<float>(\"Reconstructed batch\", Grayscale::Norm_HotCold, Grayscale::Grid_Both, 320, 0, 250, 250);\n\tw_weights1 = new WindowGrayscaleBatch<float>(\"Permanences\", Grayscale::Norm_HotCold, Grayscale::Grid_Both, 570, 0, 250, 250);\n//\tw_weights2 = new WindowGrayscaleBatch<float>(\"Connectivity\", 1092, 0, 512, 512);\n\n\tboost::thread batch_thread(boost::bind(&batch_function));\n\n\t// Start visualization thread.\n\tVGL_MANAGER->startVisualizationLoop();\n\n\tLOG(LINFO) << \"Waiting for threads to join...\";\n\t// End test thread.\n\tbatch_thread.join();\n\tLOG(LINFO) << \"Threads joined - ending application\";\n}//: main\n", "meta": {"hexsha": "479ee77aea6bbe4900fd6e367c9d64bf6eeb1d56", "size": 6503, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tests/mnist_hebbian_features_visualization_test.cpp", "max_stars_repo_name": "kant/mi-neural-nets", "max_stars_repo_head_hexsha": "82aa18fddc1fac9b72d8cd3ddcc61c02569f9e20", "max_stars_repo_licenses": ["Apache-2.0"], "max_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/mnist_hebbian_features_visualization_test.cpp", "max_issues_repo_name": "kant/mi-neural-nets", "max_issues_repo_head_hexsha": "82aa18fddc1fac9b72d8cd3ddcc61c02569f9e20", "max_issues_repo_licenses": ["Apache-2.0"], "max_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/mnist_hebbian_features_visualization_test.cpp", "max_forks_repo_name": "kant/mi-neural-nets", "max_forks_repo_head_hexsha": "82aa18fddc1fac9b72d8cd3ddcc61c02569f9e20", "max_forks_repo_licenses": ["Apache-2.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.6783919598, "max_line_length": 140, "alphanum_fraction": 0.7356604644, "num_tokens": 1662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.45600275151399894}}
{"text": "#include \"Board.hpp\"\n#include \"BoardOrganism.hpp\"\n#include \"GA.hpp\"\n#include \"HexGridPrint.hpp\"\n#include <boost/lexical_cast.hpp>\n#include <math.h>\n\nvoid ShowStatistics(const std::vector<BoardOrganism *> &i_organisms)\n{\n  size_t j;\n\n  double smallest = -1;\n  double largest = -1;\n  double meannum = 0;\n  double meanden = 0;\n  for (j = 0 ; j < i_organisms.size() ; ++j)\n  {\n    double f=i_organisms[j]->GetFitness();\n    if (smallest == -1 || f < smallest)\n    {\n      smallest = f;\n    }\n    if (largest == -1 || f > largest)\n    {\n      largest = f;\n    }\n\n    meannum += f;\n    meanden += 1;\n  }\n  double mean = meannum / meanden;\n  double ssq = 0;\n  for (j = 0 ; j < i_organisms.size() ; ++j)\n  {\n    double var = i_organisms[j]->GetFitness() - mean;\n    ssq += var * var;\n  }\n  double stdev = sqrt(ssq / meanden);\n\n  std::cout << smallest << \"--|\" << mean - stdev << \"|||\" << mean << \n    \"|||\" << mean+stdev << \"|--\" << largest << std::endl;\n}\n\n\n\n\nvoid ShowBoardOrganism(const BoardOrganism &bo,const Board &b)\n{\n  HexGridPrint hgp(11,12,false,true);\n\n  int i,j;\n  for (i = 0 ; i < 11 ; ++i)\n  {\n    for (j = 0 ; j < 11 + (i%2) ; j++)\n    {\n      const BoardCell &bc = b.GetCell(i,j);\n\n      if (bc.GetType() == BoardCell::BOTTLE)\n      {\n        hgp.AddItem(i,j,HexGridPrint::DIR3,ColorInfo::GetColorChar(bc.GetColor()));\n        hgp.AddItem(i,j,HexGridPrint::STAT1,boost::lexical_cast<char>(bc.GetBottleSize()));\n      }\n      else if (bc.GetType() == BoardCell::SOURCE)\n      {\n        hgp.AddItem(i,j,HexGridPrint::DIR0,ColorInfo::GetColorChar(bc.GetColor()));\n      }\n      else\n      {\n        size_t k;\n        for (k = 0 ; k < 6 ; ++k)\n        {\n          const PipeDefinition &pdef = bc.GetUniquePipeRotations()[bo.GetAllele(i,j)];\n\n          if (pdef[k] != 0)\n            hgp.AddItem(i,j,(HexGridPrint::HexLoc)k,boost::lexical_cast<char>(pdef[k]));\n        }\n      }\n    }\n  }\n  std::cout << hgp.Show() << \"Fitness: \" << bo.GetFitnessDescriptor() << std::endl << bo.GetMetaState();\n}\n\n\n\nconst BoardOrganism *bestone = NULL;\n\nvoid ManageBestOrganism(const std::vector<BoardOrganism *> &i_organisms,const Board &b)\n{\n  size_t j;\n\n  bool bested = false;\n  for (j = 0 ; j < i_organisms.size() ; ++j)\n  {\n    if (!bestone || bestone->GetFitness() < i_organisms[j]->GetFitness())\n    {\n      bestone = i_organisms[j];\n      bested = true;\n    }\n  }\n  if (bested)\n  {\n    ShowBoardOrganism(*bestone,b);\n  }\n}\n\n\nint main(int argc,char **argv)\n{\n  if (argc != 2)\n  {\n    std::cout << \"Bad command line; need file name.\" << std::endl;\n    exit(1);\n  }\n\n  Board b(argv[1]);\n\n  BoardOrganism::Initialize(b);\n\n  GA<BoardOrganism> ga(100);\n\n  int i;\n  for (i = 0 ; i < 100 ; ++i)\n  {\n    std::cout << \"Generation \" << i << \" \";\n\n    ShowStatistics(ga.GetCurrentPopulation());\n    ManageBestOrganism(ga.GetCurrentPopulation(),b);\n\n\n    ga.Generate(10);\n  }\n}\n\n\n\n      \n", "meta": {"hexsha": "7d6ae8f54c1459aa83f1722d2abb88c61027d9bc", "size": 2869, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "VideoGameAssistants/PuzzlePirates/Alchemy/Alchemy.cpp", "max_stars_repo_name": "chiendarrendor/AlbertsMisc", "max_stars_repo_head_hexsha": "f017b29f65d1d47eb22db66dff0b6d2145794fc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "VideoGameAssistants/PuzzlePirates/Alchemy/Alchemy.cpp", "max_issues_repo_name": "chiendarrendor/AlbertsMisc", "max_issues_repo_head_hexsha": "f017b29f65d1d47eb22db66dff0b6d2145794fc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "VideoGameAssistants/PuzzlePirates/Alchemy/Alchemy.cpp", "max_forks_repo_name": "chiendarrendor/AlbertsMisc", "max_forks_repo_head_hexsha": "f017b29f65d1d47eb22db66dff0b6d2145794fc8", "max_forks_repo_licenses": ["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.9416058394, "max_line_length": 104, "alphanum_fraction": 0.5615196933, "num_tokens": 893, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.45600275151399894}}
{"text": "//\n// Created by keszocze on 27.09.18.\n//\n\n#include \"cudd_helpers.hpp\"\n#include \"string_helpers.hpp\"\n\n#include <iostream>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <cudd/cudd/cudd.h>\n#include <tuple>\n#include <map>\n#include <set>\n#include <stack>\n#include <algorithm>\n#include <assert.h>\n#include <cmath>\n\nnamespace abo::util {\n\n    unsigned int terminal_level(const std::vector<std::vector<BDD>>& bdds) {\n        unsigned int max_index = 0;\n        for (const auto &f : bdds) {\n            for (const BDD &b : f) {\n                std::vector<unsigned int> support = b.SupportIndices();\n                auto max_support_index = std::max_element(support.begin(), support.end());\n                max_index = std::max(max_index, (max_support_index == support.end() ? 0 : *max_support_index) + 1);\n            }\n        }\n        return max_index;\n    }\n\n    long eval_adder(const std::vector<BDD> &adder, long input1, long input2, int bits) {\n        std::vector<int> bdd_inputs;\n        for (int i = 0;i<bits;i++) {\n            bdd_inputs.push_back((input1 & (1 << i)) > 0 ? 1 : 0);\n            bdd_inputs.push_back((input2 & (1 << i)) > 0 ? 1 : 0);\n        }\n\n        long result = 0;\n        for (unsigned int i = 0;i<adder.size();i++) {\n            if (adder[i].Eval(bdd_inputs.data()).IsOne()) {\n                result |= 1 << i;\n            }\n        }\n\n        return result;\n    }\n\n    static double count_minterms_rec(DdNode* node, std::map<DdNode*, double> &minterms_map) {\n        auto it = minterms_map.find(node);\n        if (it != minterms_map.end()) {\n            return it->second;\n        }\n\n        if (Cudd_IsConstant(node)) {\n            double value = Cudd_V(node);\n            if (Cudd_IsComplement(node)) {\n                value = value == 0.0 ? 1.0 : 0.0;\n            }\n            minterms_map[node] = value;\n            return value;\n        }\n\n        DdNode *N = Cudd_Regular(node);\n\n        DdNode *Nv = Cudd_T(N);\n        DdNode *Nnv = Cudd_E(N);\n\n        Nv = Cudd_NotCond(Nv, Cudd_IsComplement(node));\n        Nnv = Cudd_NotCond(Nnv, Cudd_IsComplement(node));\n\n        double highResult = count_minterms_rec(Nv, minterms_map);\n        double lowResult = count_minterms_rec(Nnv, minterms_map);\n        double minTerms = highResult / 2 + lowResult / 2;\n\n        minterms_map[node] = minTerms;\n        return minTerms;\n    }\n\n    std::map<DdNode*, double> count_minterms(const BDD &bdd) {\n        std::map<DdNode*, double> result;\n\n        count_minterms_rec(bdd.getNode(), result);\n        return result;\n    }\n\n    static double count_solutions_rec(DdNode* node, std::map<DdNode*, double> &solutions_map, int terminal_level) {\n        auto it = solutions_map.find(node);\n        if (it != solutions_map.end()) {\n            return it->second;\n        }\n\n        if (Cudd_IsConstant(node)) {\n            double value = Cudd_V(node);\n            if (Cudd_IsComplement(node)) {\n                value = value == 0.0 ? 1.0 : 0.0;\n            }\n            solutions_map[node] = value;\n            return value;\n        }\n\n        DdNode *N = Cudd_Regular(node);\n\n        DdNode *Nv = Cudd_T(N);\n        DdNode *Nnv = Cudd_E(N);\n\n        Nv = Cudd_NotCond(Nv, Cudd_IsComplement(node));\n        Nnv = Cudd_NotCond(Nnv, Cudd_IsComplement(node));\n\n        double high_result = count_solutions_rec(Nv, solutions_map, terminal_level);\n        double low_result = count_solutions_rec(Nnv, solutions_map, terminal_level);\n\n        unsigned long high_level = Cudd_IsConstant(Nv) ? terminal_level : Cudd_NodeReadIndex(Nv);\n        unsigned long low_level = Cudd_IsConstant(Nnv) ? terminal_level : Cudd_NodeReadIndex(Nnv);\n        unsigned long own_level = Cudd_NodeReadIndex(node);\n\n        double solutions = high_result * std::pow(2.0, high_level - own_level - 1) +\n                low_result * std::pow(2.0, low_level - own_level - 1);\n\n        solutions_map[node] = solutions;\n        return solutions;\n    }\n\n    std::map<DdNode*, double> count_solutions(const BDD &bdd) {\n        std::map<DdNode*, double> result;\n\n        count_solutions_rec(bdd.getNode(), result, terminal_level({{bdd}}));\n        return result;\n    }\n\n    std::vector<int> random_satisfying_input(const BDD &bdd, const std::map<DdNode*, double> &minterm_count, int max_level) {\n            std::vector<int> result;\n\n            DdNode *node = bdd.getNode();\n\n            for(int level = 0;level < max_level;level++) {\n                long node_level = Cudd_IsConstant(node) ? max_level : Cudd_NodeReadIndex(node);\n                if (level < node_level) {\n                    result.push_back(rand() % 2);\n                } else {\n                    assert(!Cudd_IsConstant(node));\n\n                    DdNode *N = Cudd_Regular(node);\n                    DdNode *then_node = Cudd_T(N);\n                    DdNode *else_node = Cudd_E(N);\n\n                    then_node = Cudd_NotCond(then_node, Cudd_IsComplement(node));\n                    else_node = Cudd_NotCond(else_node, Cudd_IsComplement(node));\n\n                    double then_weight = minterm_count.at(then_node);\n                    double else_weight = minterm_count.at(else_node);\n\n                    double r = rand() / double(RAND_MAX);\n                    if (r <= then_weight / (then_weight + else_weight)) {\n                        result.push_back(1);\n                        node = then_node;\n                    } else {\n                        result.push_back(0);\n                        node = else_node;\n                    }\n                }\n            }\n\n            return result;\n        }\n\n    unsigned int const_ADD_value(const ADD &add) {\n        DdNode *node = add.getNode();\n        if (Cudd_IsConstant(node)) {\n            return static_cast<unsigned int>(Cudd_V(node));\n        }\n        return 0;\n    }\n\n    static std::map<DdNode*, unsigned long> count_paths(DdNode* node, unsigned int terminal_level) {\n        if (Cudd_IsConstant(node)) {\n            return {{node, 1}};\n        }\n\n        // do a sort of breadth first search, visiting all variable levels from top to bottom\n        std::vector<std::stack<DdNode*>> levels;\n        levels.push_back(std::stack<DdNode*>({Cudd_Regular(node)}));\n\n        std::map<DdNode*, unsigned long> node_to_count;\n        std::set<DdNode*> visited;\n        node_to_count[node] = 1;\n        visited.insert(node);\n        for (unsigned int level = 0;level<levels.size();level++) {\n            // a reference can not be used here since the vector may resize and move the data elsewhere\n            std::stack<DdNode*> nodes = levels[level];\n            while (nodes.size() > 0) {\n                DdNode *current = nodes.top();\n                nodes.pop();\n\n\n                if (!Cudd_IsConstant(current)) {\n                    DdNode *then_node = Cudd_Regular(Cudd_T(current));\n                    DdNode *else_node = Cudd_Regular(Cudd_E(current));\n\n                    unsigned long current_count = node_to_count[current];\n\n                    unsigned long then_level = Cudd_IsConstant(then_node) ? terminal_level : Cudd_NodeReadIndex(then_node);\n                    // the map will automatically use 0 if the node is not yet present\n                    node_to_count[then_node] += current_count << (then_level - level - 1);\n                    if (visited.find(then_node) == visited.end()) {\n                        levels.resize(std::max(levels.size(), then_level+1));\n                        levels[then_level].push(then_node);\n                        visited.insert(then_node);\n                    }\n\n                    unsigned long else_level = Cudd_IsConstant(else_node) ? terminal_level : Cudd_NodeReadIndex(else_node);\n                    node_to_count[else_node] += current_count << (else_level - level - 1);\n                    if (visited.find(else_node) == visited.end()) {\n                        levels.resize(std::max(levels.size(), else_level+1));\n                        levels[else_level].push(else_node);\n                        visited.insert(else_node);\n                    }\n                }\n            }\n        }\n\n        return node_to_count;\n    }\n\n    std::vector<std::pair<double, unsigned long>> add_terminal_values(const ADD &add) {\n        std::set<DdNode*> visited;\n        std::stack<DdNode*> toVisit;\n        toVisit.push(add.getNode());\n        visited.insert(add.getNode());\n\n        // determine the level that terminal nodes should be interpreted as\n        std::vector<unsigned int> support = add.SupportIndices();\n        auto max_support_index = std::max_element(support.begin(), support.end());\n        unsigned int term_level = (max_support_index == support.end() ? 0 : *max_support_index) + 1;\n\n        auto path_count = count_paths(add.getNode(), term_level);\n\n        std::vector<std::pair<double, unsigned long>> result;\n        while (toVisit.size() > 0) {\n            DdNode *node = toVisit.top();\n            toVisit.pop();\n\n            if (Cudd_IsConstant(node)) {\n                result.push_back({Cudd_V(node), path_count[node]});\n            } else {\n                DdNode *thenNode = Cudd_T(node);\n                if (visited.find(thenNode) == visited.end()) {\n                    // cppcheck-suppress stlFindInsert\n                    visited.insert(thenNode);\n                    toVisit.push(thenNode);\n                }\n                DdNode *elseNode = Cudd_E(node);\n                if (visited.find(elseNode) == visited.end()) {\n                    // cppcheck-suppress stlFindInsert\n                    visited.insert(elseNode);\n                    toVisit.push(elseNode);\n                }\n            }\n        }\n        return result;\n    }\n\n    ADD bdd_forest_to_add(const Cudd &mgr, const std::vector<BDD> &bdds, const NumberRepresentation num_rep) {\n\n        std::vector<BDD> bdds_ = bdds;\n        if (num_rep == NumberRepresentation::BaseTwo) {\n            bdds_.push_back(mgr.bddZero());\n        }\n\n        ADD result = mgr.addZero();\n        ADD two = mgr.addOne() + mgr.addOne();\n        ADD signBitPower = mgr.addOne();\n\n        for (auto it = bdds_.rbegin() + 1;it != bdds_.rend();it++) {\n            result *= two;\n            signBitPower *= two;\n            result += it->Add();\n        }\n\n        result -= bdds.back().Add() * signBitPower;\n\n        return result;\n    }\n\n    ADD xor_difference_add(const Cudd &mgr, const std::vector<BDD> &f, const std::vector<BDD> &f_hat) {\n        std::vector<BDD> diff;\n        for (unsigned int i = 0;i<f.size();i++) {\n            diff.push_back(f[i] ^ f_hat[i]);\n        }\n\n        return bdd_forest_to_add(mgr, diff, NumberRepresentation::BaseTwo);\n    }\n\n    static DdNode * add_absolute_difference_apply(DdManager * dd, DdNode ** f, DdNode ** g) {\n        // basically copied from cuddAddApply.c (the operator is modified of course)\n        DdNode *F = *f;\n        DdNode *G = *g;\n        if (Cudd_IsConstant(F) && Cudd_IsConstant(G)) {\n            CUDD_VALUE_TYPE value = std::abs(Cudd_V(F) - Cudd_V(G));\n            DdNode * res = Cudd_addConst(dd, value);\n            return res;\n        }\n        if (F > G) { /* swap f and g */\n            *f = G;\n            *g = F;\n        }\n        return nullptr;\n    }\n\n    ADD absolute_difference_add(const Cudd &mgr, const std::vector<BDD> &f, const std::vector<BDD> &f_hat, const NumberRepresentation num_rep) {\n        ADD a = bdd_forest_to_add(mgr, f, num_rep);\n        ADD b = bdd_forest_to_add(mgr, f_hat, num_rep);\n        DdNode *result_node = Cudd_addApply(mgr.getManager(), add_absolute_difference_apply, a.getNode(), b.getNode());\n        return ADD(mgr, result_node);\n    }\n\n\n    void dump_dot(\n            const Cudd &mgr,\n            const std::vector<BDD> &bdd,\n            const std::vector<std::string> &innames,\n            const std::vector<std::string> &outnames) {\n\n\n        if (bdd.empty()) {\n            return;\n        }\n\n        char **ins = innames.empty() ? nullptr : vec_to_arr(innames);\n        char **outs = outnames.empty() ? nullptr : vec_to_arr(outnames);\n\n        mgr.DumpDot(bdd, ins, outs);\n\n        del_arr(ins, innames.size());\n        del_arr(outs, outnames.size());\n    }\n\n    void dump_dot(\n            const Cudd &mgr,\n            const BDD &bdd,\n            const std::vector<std::string> &inames,\n            const std::string &funname) {\n        std::vector<BDD> bddv{bdd};\n        std::vector<std::string> funnames{funname};\n        dump_dot(mgr, bddv, inames, funnames);\n    }\n\n\n    /*\n     * How to get the children of nodes has been taken from StackOverflow:\n     * https://stackoverflow.com/questions/47704600/cudd-access-bdd-childs\n     */\n\n    BDD high(const Cudd &mgr, const BDD &v) {\n        DdNode *n = v.getNode();\n\n        if (Cudd_IsConstant(n)) {\n            throw std::invalid_argument(\"high(mgr,v): Cannot retrieve child of a terminal node\");\n        }\n\n\n        if (Cudd_IsComplement(n)) {\n            return !BDD(mgr, Cudd_Regular(Cudd_T(n)));\n        } else {\n            return BDD(mgr, Cudd_T(n));\n        }\n    }\n\n\n    BDD low(const Cudd &mgr, const BDD &v) {\n        DdNode *n = v.getNode();\n\n        if (Cudd_IsConstant(n)) {\n            throw std::invalid_argument(\"low(mgr,v): Cannot retrieve child of a terminal node\");\n        }\n\n        if (Cudd_IsComplement(n)) {\n            return !BDD(mgr, Cudd_Regular(Cudd_E(n)));\n        } else {\n            return BDD(mgr, Cudd_E(n));\n        }\n    }\n\n    /**\n     * @\n     */\n    std::pair<BDD, BDD> full_adder(const BDD &f, const BDD &g, const BDD &carry_in) {\n        BDD carry_out = (f * g) | (f * carry_in) | (g * carry_in);\n        BDD sum = f ^ g ^carry_in;\n        return {sum, carry_out};\n    }\n\n    std::vector<BDD>\n    bdd_subtract(const Cudd &mgr, const std::vector<BDD> &minuend, const std::vector<BDD> &subtrahend) {\n        std::vector<BDD> diff;\n        diff.reserve(minuend.size());\n\n        // using one as carry in serves as an implicit method to add one to the subtrahend, which is necessary to\n        // change its sign\n        BDD carry = mgr.bddOne();\n\n        for (size_t i = 0; i < minuend.size(); ++i) {\n            // the subtrahend's bits are negated to change the sign of the subtrahend\n            auto tmp  = full_adder(minuend[i], !subtrahend[i], carry);\n            diff.push_back(tmp.first);\n            carry = tmp.second;\n\n        }\n\n        return diff;\n    }\n\n    std::vector<BDD> bdd_absolute_difference(const Cudd &mgr, const std::vector<BDD> &f, const std::vector<BDD> &g,\n                                             const NumberRepresentation num_rep) {\n\n        std::vector<BDD> f_= f;\n        std::vector<BDD> g_ = g;\n\n        if (num_rep == NumberRepresentation::BaseTwo) {\n            // we need to add sign bits to the functions as they don't have one right now\n            // these are necessary to be able to add the negative number instead of actually subtracting\n            f_.push_back(mgr.bddZero());\n            g_.push_back(mgr.bddZero());\n        }\n\n        bool smaller = true;\n        for (std::size_t i = 0;i<f_.size();i++) {\n            if (f_[i] > g_[i]) {\n                smaller = false;\n                break;\n            }\n        }\n\n        // use correct order for the difference calculation to minimize computation time\n        const std::vector<BDD> &f__ = smaller ? g_ : f_;\n        const std::vector<BDD> &g__ = smaller ? f_ : g_;\n\n        std::vector<BDD> difference = abo::util::bdd_subtract(mgr, f__, g__);\n        return abo::util::abs(mgr,difference);\n    }\n\n\n    std::vector<BDD> abs(const Cudd &mgr, const std::vector<BDD> &f) {\n\n        // create mask consisting of the sign bit only\n        BDD sign_bit = f.back();\n        std::vector<BDD> mask(f.size(), sign_bit);\n\n        std::vector<BDD> tmp;\n\n        for (size_t i=0; i < f.size(); ++i) {\n            tmp.push_back(f[i] ^ sign_bit);\n        }\n\n        std::vector<BDD> abs = abo::util::bdd_subtract(mgr,tmp,mask);\n\n        return abs;\n    }\n\n    std::vector<BDD> bdd_shift(const Cudd &mgr, const std::vector<BDD> &f, int bits_to_shift) {\n        std::vector<BDD> result;\n        result.reserve(f.size());\n\n        for (int i = 0;i<int(f.size());i++) {\n            if (i < bits_to_shift || i >= int(f.size()) + bits_to_shift) {\n                result.push_back(mgr.bddZero());\n            } else {\n                result.push_back(f[i - bits_to_shift]);\n            }\n        }\n\n        return result;\n    }\n\n    std::vector<BDD> bdd_add(const Cudd &mgr, const std::vector<BDD> &f, const std::vector<BDD> &g) {\n        std::vector<BDD> sum;\n        sum.reserve(f.size());\n\n        BDD carry = mgr.bddZero();\n\n        for (unsigned int i = 0; i < f.size(); ++i) {\n            auto tmp  = full_adder(f[i], g[i], carry);\n            sum.push_back(tmp.first);\n            carry = tmp.second;\n\n        }\n\n        return sum;\n    }\n\n    std::vector<BDD> bdd_multiply_constant(const Cudd &mgr, const std::vector<BDD> &f, double factor, const unsigned int num_extra_bits) {\n\n        std::vector<BDD> result(f.size() + size_t(std::ceil(std::log2(factor))) + 2, mgr.bddZero());\n\n        std::vector<BDD> fc = f;\n        while (result.size() > fc.size()) {\n            fc.push_back(mgr.bddZero());\n        }\n\n        assert (factor <= static_cast<double>(std::numeric_limits<boost::multiprecision::uint256_t>::max()));\n\n        boost::multiprecision::uint256_t great_factor = static_cast<boost::multiprecision::uint256_t>(factor);\n        boost::multiprecision::uint256_t one = 1;\n        for (int i = 0;i<256;i++) {\n            if (great_factor & (one << i)) {\n                result = bdd_add(mgr, result, bdd_shift(mgr, fc, i));\n            }\n        }\n        unsigned long lesser_factor = static_cast<unsigned long>(std::fmod(factor, 1.0) * (1UL << num_extra_bits));\n        for (unsigned int i = 0;i<num_extra_bits;i++) {\n            if (lesser_factor & (1UL << i)) {\n                result = bdd_add(mgr, result, bdd_shift(mgr, fc, -static_cast<int>(num_extra_bits - i)));\n            }\n        }\n\n        return result;\n    }\n\n    void equalize_vector_size(const Cudd &mgr, std::vector<BDD> &f1, std::vector<BDD> &f2) {\n        while (f1.size() < f2.size()) {\n            f1.push_back(mgr.bddZero());\n        }\n        while (f2.size() < f1.size()) {\n            f2.push_back(mgr.bddZero());\n        }\n    }\n\n    std::pair<bool, bool> exists_greater_equals(const Cudd &mgr, const std::vector<BDD> &f1, const std::vector<BDD> &f2) {\n        std::vector<BDD> f1_ = f1;\n        std::vector<BDD> f2_ = f2;\n\n        equalize_vector_size(mgr, f1_, f2_);\n\n        BDD zero_condition = mgr.bddOne();\n        BDD equal_condition = mgr.bddOne();\n        for (int i = int(f1_.size())-1;i>=0;i--) {\n            zero_condition &= !f2_[i];\n            if (!((f1_[i] & zero_condition).IsZero())) {\n                return {true, false};\n            }\n            if (!((f1_[i] & !f2_[i] & equal_condition).IsZero())) {\n                return {true, false};\n            }\n            equal_condition &= (f1_[i] & f2_[i]) | ((!f1_[i]) & (!f2_[i]));\n        }\n        if (!equal_condition.IsZero()) {\n            return {true, true};\n        }\n        return {false, false};\n    }\n\n    std::vector<BDD> bdd_max_one(const Cudd &mgr, const std::vector<BDD> &f) {\n        std::vector<BDD> result = f;\n\n        BDD zero_condition = mgr.bddOne();\n        for (int i = int(result.size())-1;i>0;i--) {\n            zero_condition &= !result[i];\n        }\n        result[0] |= zero_condition;\n\n        return result;\n    }\n\n    BDD greater_equals(const Cudd &mgr, const std::vector<BDD> &f, const std::vector<BDD> &g) {\n        std::vector<BDD> f_ = f;\n        std::vector<BDD> g_ = g;\n\n        equalize_vector_size(mgr, f_, g_);\n\n        BDD zero_condition = mgr.bddOne();\n        BDD equal_condition = mgr.bddOne();\n\n        BDD result = mgr.bddZero();\n        for (int i = int(f_.size()) - 1; i >= 0; i--) {\n            zero_condition &= !g_[i];\n            result |= f_[i] & zero_condition;\n            result |= f_[i] & !g_[i] & equal_condition;\n            equal_condition &= (f_[i] & g_[i]) | ((!f_[i]) & (!g_[i]));\n        }\n        result |= equal_condition;\n        return result;\n    }\n\n    std::vector<BDD> bdd_divide(const Cudd &mgr, const std::vector<BDD> &f, const std::vector<BDD> &g, unsigned int extra_bits) {\n\n        std::vector<BDD> values(extra_bits, mgr.bddZero());\n        std::vector<BDD> temp = f;\n        temp.insert(temp.begin(), values.begin(), values.end());\n\n        std::vector<BDD> g_ = g;\n        for (unsigned int i = 0;i<f.size()+1;i++) {\n            g_.push_back(mgr.bddZero());\n        }\n        g_.insert(g_.begin(), values.begin(), values.end());\n\n        std::vector<BDD> result;\n        for (int i = int(f.size())+1;i >= -int(extra_bits);i--) {\n            auto shifted = bdd_shift(mgr, g_, i);\n            BDD subtract_condition = greater_equals(mgr, temp, shifted);\n            std::vector<BDD> to_subtract = shifted;\n            for (BDD &b : to_subtract) {\n                b &= subtract_condition;\n            }\n            equalize_vector_size(mgr, to_subtract, temp);\n            temp = bdd_subtract(mgr, temp, to_subtract);\n            result.push_back(subtract_condition);\n        }\n        std::reverse(result.begin(), result.end());\n        return result;\n    }\n\n}\n", "meta": {"hexsha": "ecfe78f4a56f1c83afc516968a4cfb2ee9c57a01", "size": 21241, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/util/cudd_helpers.cpp", "max_stars_repo_name": "andreaswendler/abo", "max_stars_repo_head_hexsha": "d5d31e0714365960fb9c02a6a5b240c07ac3a738", "max_stars_repo_licenses": ["MIT"], "max_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/cudd_helpers.cpp", "max_issues_repo_name": "andreaswendler/abo", "max_issues_repo_head_hexsha": "d5d31e0714365960fb9c02a6a5b240c07ac3a738", "max_issues_repo_licenses": ["MIT"], "max_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/cudd_helpers.cpp", "max_forks_repo_name": "andreaswendler/abo", "max_forks_repo_head_hexsha": "d5d31e0714365960fb9c02a6a5b240c07ac3a738", "max_forks_repo_licenses": ["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.5944625407, "max_line_length": 144, "alphanum_fraction": 0.544748364, "num_tokens": 5465, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149978955813, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4559171989863064}}
{"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    testGaussMarkov1stOrderFactor.cpp\n * @brief   Unit tests for the GaussMarkov1stOrder factor\n * @author  Vadim Indelman\n * @date    Jan 17, 2012\n */\n\n#include <gtsam_unstable/slam/GaussMarkov1stOrderFactor.h>\n#include <gtsam/nonlinear/Values.h>\n#include <gtsam/inference/Key.h>\n#include <gtsam/base/numericalDerivative.h>\n#include <CppUnitLite/TestHarness.h>\n#include <gtsam/base/deprecated/LieVector.h>\n\n#include <boost/bind/bind.hpp>\n\nusing namespace boost::placeholders;\nusing namespace std;\nusing namespace gtsam;\n\n//! Factors\ntypedef GaussMarkov1stOrderFactor<LieVector> GaussMarkovFactor;\n\n/* ************************************************************************* */\nLieVector predictionError(const LieVector& v1, const LieVector& v2, const GaussMarkovFactor factor) {\n  return factor.evaluateError(v1, v2);\n}\n\n/* ************************************************************************* */\nTEST( GaussMarkovFactor, equals )\n{\n  // Create two identical factors and make sure they're equal\n  Key x1(1);\n  Key x2(2);\n  double delta_t = 0.10;\n  Vector tau = Vector3(100.0, 150.0, 10.0);\n  SharedGaussian model = noiseModel::Isotropic::Sigma(3, 1.0);\n\n  GaussMarkovFactor factor1(x1, x2, delta_t, tau, model);\n  GaussMarkovFactor factor2(x1, x2, delta_t, tau, model);\n\n  CHECK(assert_equal(factor1, factor2));\n}\n\n/* ************************************************************************* */\nTEST( GaussMarkovFactor, error )\n{\n  Values linPoint;\n  Key x1(1);\n  Key x2(2);\n  double delta_t = 0.10;\n  Vector tau = Vector3(100.0, 150.0, 10.0);\n  SharedGaussian model = noiseModel::Isotropic::Sigma(3, 1.0);\n\n  LieVector v1 = LieVector(Vector3(10.0, 12.0, 13.0));\n  LieVector v2 = LieVector(Vector3(10.0, 15.0, 14.0));\n\n  // Create two nodes\n  linPoint.insert(x1, v1);\n  linPoint.insert(x2, v2);\n\n  GaussMarkovFactor factor(x1, x2, delta_t, tau, model);\n  Vector Err1( factor.evaluateError(v1, v2) );\n\n  // Manually calculate the error\n  Vector alpha(tau.size());\n  Vector alpha_v1(tau.size());\n  for(int i=0; i<tau.size(); i++){\n    alpha(i) = exp(- 1/tau(i)*delta_t );\n    alpha_v1(i) = alpha(i) * v1(i);\n  }\n  Vector Err2( v2 - alpha_v1 );\n\n  CHECK(assert_equal(Err1, Err2, 1e-9));\n}\n\n/* ************************************************************************* */\nTEST (GaussMarkovFactor, jacobian ) {\n\n  Values linPoint;\n  Key x1(1);\n  Key x2(2);\n  double delta_t = 0.10;\n  Vector tau = Vector3(100.0, 150.0, 10.0);\n  SharedGaussian model = noiseModel::Isotropic::Sigma(3, 1.0);\n\n  GaussMarkovFactor factor(x1, x2, delta_t, tau, model);\n\n  // Update the linearization point\n  LieVector v1_upd = LieVector(Vector3(0.5, -0.7, 0.3));\n  LieVector v2_upd = LieVector(Vector3(-0.7, 0.4, 0.9));\n\n  // Calculate the Jacobian matrix using the factor\n  Matrix computed_H1, computed_H2;\n  factor.evaluateError(v1_upd, v2_upd, computed_H1, computed_H2);\n\n  // Calculate the Jacobian matrices H1 and H2 using the numerical derivative function\n  Matrix numerical_H1, numerical_H2;\n  numerical_H1 = numericalDerivative21<Vector3, Vector3, Vector3>(\n      boost::bind(&predictionError, _1, _2, factor), v1_upd, v2_upd);\n  numerical_H2 = numericalDerivative22<Vector3, Vector3, Vector3>(\n      boost::bind(&predictionError, _1, _2, factor), v1_upd, v2_upd);\n\n  // Verify they are equal for this choice of state\n  CHECK( assert_equal(numerical_H1, computed_H1, 1e-9));\n  CHECK( assert_equal(numerical_H2, computed_H2, 1e-9));\n}\n\n/* ************************************************************************* */\nint main()\n{\n  TestResult tr; return TestRegistry::runAllTests(tr);\n}\n/* ************************************************************************* */\n\n", "meta": {"hexsha": "74134612d8aed47f73fcbfe136bed2352b43f112", "size": 4059, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam_unstable/slam/tests/testGaussMarkov1stOrderFactor.cpp", "max_stars_repo_name": "acxz/gtsam", "max_stars_repo_head_hexsha": "cd3854a1f6db923d40ecf3ced56bafbe339d1b3c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gtsam_unstable/slam/tests/testGaussMarkov1stOrderFactor.cpp", "max_issues_repo_name": "acxz/gtsam", "max_issues_repo_head_hexsha": "cd3854a1f6db923d40ecf3ced56bafbe339d1b3c", "max_issues_repo_licenses": ["BSD-3-Clause"], "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_unstable/slam/tests/testGaussMarkov1stOrderFactor.cpp", "max_forks_repo_name": "acxz/gtsam", "max_forks_repo_head_hexsha": "cd3854a1f6db923d40ecf3ced56bafbe339d1b3c", "max_forks_repo_licenses": ["BSD-3-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.9606299213, "max_line_length": 101, "alphanum_fraction": 0.6016260163, "num_tokens": 1122, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149978955811, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4559171989863062}}
{"text": "//\n// Copyright (c) 2016 CNRS\n//\n\n#ifndef __math_matrix_hpp__\n#define __math_matrix_hpp__\n\n#include <Eigen/Dense>\n\nnamespace pinocchio\n{\n\n  template<typename Derived>\n  inline bool hasNaN(const Eigen::DenseBase<Derived> & m) \n  {\n    return !((m.derived().array()==m.derived().array()).all());\n  }\n\n\n}\n#endif //#ifndef __math_matrix_hpp__\n", "meta": {"hexsha": "ab740ac22881d1ba3b2bdc67e8f3bd2e8b195c91", "size": 339, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/math/matrix.hpp", "max_stars_repo_name": "matthieuvigne/pinocchio", "max_stars_repo_head_hexsha": "01f211eceda3ac2e5edc8cf101690afb6f3184d3", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-22T15:42:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-22T15:42:45.000Z", "max_issues_repo_path": "src/math/matrix.hpp", "max_issues_repo_name": "matthieuvigne/pinocchio", "max_issues_repo_head_hexsha": "01f211eceda3ac2e5edc8cf101690afb6f3184d3", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/math/matrix.hpp", "max_forks_repo_name": "matthieuvigne/pinocchio", "max_forks_repo_head_hexsha": "01f211eceda3ac2e5edc8cf101690afb6f3184d3", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-21T09:14:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-21T09:14:26.000Z", "avg_line_length": 15.4090909091, "max_line_length": 63, "alphanum_fraction": 0.6902654867, "num_tokens": 91, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4559171923261746}}
{"text": "#ifndef STAN_MATH_PRIM_MAT_PROB_MULTI_NORMAL_CHOLESKY_RNG_HPP\n#define STAN_MATH_PRIM_MAT_PROB_MULTI_NORMAL_CHOLESKY_RNG_HPP\n\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <stan/math/prim/scal/err/check_size_match.hpp>\n#include <stan/math/prim/scal/err/check_finite.hpp>\n#include <stan/math/prim/scal/err/check_not_nan.hpp>\n#include <stan/math/prim/mat/fun/columns_dot_product.hpp>\n#include <stan/math/prim/mat/fun/columns_dot_self.hpp>\n#include <stan/math/prim/mat/fun/dot_product.hpp>\n#include <stan/math/prim/mat/fun/dot_self.hpp>\n#include <stan/math/prim/mat/fun/log.hpp>\n#include <stan/math/prim/mat/fun/log_determinant.hpp>\n#include <stan/math/prim/mat/fun/mdivide_left_spd.hpp>\n#include <stan/math/prim/mat/fun/mdivide_left_tri_low.hpp>\n#include <stan/math/prim/mat/fun/multiply.hpp>\n#include <stan/math/prim/mat/fun/subtract.hpp>\n#include <stan/math/prim/mat/fun/sum.hpp>\n\n#include <stan/math/prim/scal/fun/constants.hpp>\n#include <stan/math/prim/scal/meta/include_summand.hpp>\n\nnamespace stan {\n  namespace math {\n    template <class RNG>\n    inline Eigen::VectorXd\n    multi_normal_cholesky_rng(\n        const Eigen::Matrix<double, Eigen::Dynamic, 1>& mu,\n        const Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>& S,\n        RNG& rng) {\n      using boost::variate_generator;\n      using boost::normal_distribution;\n\n      static const char* function(\"multi_normal_cholesky_rng\");\n      check_finite(function, \"Location parameter\", mu);\n\n      variate_generator<RNG&, normal_distribution<> >\n        std_normal_rng(rng, normal_distribution<>(0, 1));\n\n      Eigen::VectorXd z(S.cols());\n      for (int i = 0; i < S.cols(); i++)\n        z(i) = std_normal_rng();\n\n      return mu + S * z;\n    }\n  }\n}\n#endif\n", "meta": {"hexsha": "66a38d1d6987e0b6aab18e7df581cd48f10b26ac", "size": 1781, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/mat/prob/multi_normal_cholesky_rng.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/prim/mat/prob/multi_normal_cholesky_rng.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/prim/mat/prob/multi_normal_cholesky_rng.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.62, "max_line_length": 71, "alphanum_fraction": 0.7316114542, "num_tokens": 464, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4559171923261745}}
{"text": "//==================================================================================================\n/*\n  Copyright 2017 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//! [direct_hyperbolic]\n#include <boost/simd/hyperbolic.hpp>\n#include <boost/simd/pack.hpp>\n#include <boost/simd/function/enumerate.hpp>\n#include <iostream>\n\nnamespace bs =  boost::simd;\nusing pack_ft =  bs::pack <float, 8>;\n\nint main()\n{\n  pack_ft p = bs::enumerate<pack_ft>(-4.0f, 1.0f);\n  std::cout << \" p =  \" << p << std::endl\n            <<  \" -> bs::cosh(p) =  \" << bs::cosh(p) << std::endl\n            <<  \" -> bs::sinh(p) =  \" << bs::sinh(p) << std::endl\n            <<  \" -> bs::tanh(p) =  \" << bs::tanh(p) << std::endl\n            <<  \" -> bs::sech(p) =  \" << bs::sech(p) << std::endl\n            <<  \" -> bs::csch(p) =  \" << bs::csch(p) << std::endl;\n  pack_ft s, c;\n  std::tie(s, c) = bs::sinhcosh(p);\n  std::cout <<  \" using sinhcosh \" << std::endl\n            <<  \" -> bs::cosh(p) =  \" << c << std::endl\n            <<  \" -> bs::sinh(p) =  \" << s << std::endl;\n  return 0;\n}\n//! [direct_hyperbolic]\n", "meta": {"hexsha": "a0097308f3cff4feadfb6cd48305bb63b34e1671", "size": 1295, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/doc/hyperbolic/direct_hyperbolic.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": "test/doc/hyperbolic/direct_hyperbolic.cpp", "max_issues_repo_name": "remymuller/boost.simd", "max_issues_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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/doc/hyperbolic/direct_hyperbolic.cpp", "max_forks_repo_name": "remymuller/boost.simd", "max_forks_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "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": 37.0, "max_line_length": 100, "alphanum_fraction": 0.4378378378, "num_tokens": 386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4559171923261745}}
{"text": "// Copyright (c) 2016-2017 Till Kolditz\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:   TestModuloInverseComputation.cpp\n * Author: Till Kolditz <till.kolditz@gmail.com>\n *\n * Created on 20. Februar 2017, 18:21\n */\n\n#include <cstdlib>\n#include <iostream>\n#include <iomanip>\n\n#include <boost/multiprecision/cpp_int.hpp>\n\n#include <Util/Euclidean.hpp>\n#include <Util/Stopwatch.hpp>\n\nusing boost::multiprecision::uint128_t;\n\nconst size_t wCmin = 3;\nconst size_t wCmax = 127;\nconst size_t wAmin = 2;\n//const size_t wAmax = 16;\n\nuint64_t convert(\n        uint128_t & source) {\n    uint64_t target = 0;\n    const unsigned limb_num = source.backend().size(); // number of limbs\n    const unsigned limb_bits = sizeof(boost::multiprecision::limb_type) * CHAR_BIT; // size of limb in bits\n    for (unsigned i = 0; i < limb_num && ((i * limb_bits) < (sizeof(target) * 8)); ++i) {\n        target |= (source.backend().limbs()[i]) << (i * limb_bits);\n    }\n    return target;\n}\n\ntemplate<typename T>\nT test(\n        size_t TOTALNUM,\n        size_t wC,\n        size_t wAmin) {\n    T result(0);\n    std::cout << wC;\n#ifdef DEBUG\n    for (size_t wA = wAmin; wA <= (wC - (wCmin - (wAmin - 1))); ++wA) {\n        std::cout << \"\\t-\";\n    }\n    for (size_t wA = (wC - (wCmin - (wAmin - 1))); wA < wC; ++wA) {\n#else\n    for (size_t wA = wAmin; wA < wC; ++wA) {\n#endif\n        T A(1);\n        A <<= (wA - 1);\n        A += 1;\n        Stopwatch sw;\n        for (size_t i = 0; i < TOTALNUM; ++i) {\n            result = ext_euclidean(A, wC);\n            if (result == 0) {\n                std::cerr << \"Error @ wA=\" << wA << \", A=\" << A << std::endl;\n            }\n        }\n        auto nanoseconds = sw.Current();\n#ifdef DEBUG\n        std::cout << '\\t' << std::hex << std::showbase << A << ':' << std::dec << std::noshowbase << nanoseconds;\n#else\n        std::cout << '\\t' << nanoseconds;\n#endif\n    }\n    std::cout << std::endl;\n    return result;\n}\n\nint main(\n        int argc,\n        char ** argv) {\n    if (argc != 4) {\n        std::cerr << \"Usage: \" << argv[0] << \" <totalnum [#iterations]> <|A| min> <|C| max>\" << std::endl;\n        return 1;\n    }\n\n    size_t TOTALNUM = strtoll(argv[1], nullptr, 0);\n\n    const size_t wAmin = strtoll(argv[2], nullptr, 0); // 2\n    //const size_t wAmax = 16;\n    const size_t wCmin = wAmin + 1; // 3\n    const size_t wCmax = strtoll(argv[3], nullptr, 0); // 127\n\n    std::cout << TOTALNUM << \" iterations per combination of |A| and |C|.\" << std::endl;\n    std::cout << \"|C|\";\n    for (size_t wA = wAmin; wA <= wCmax; ++wA) {\n        std::cout << '\\t' << wA;\n    }\n    std::cout << std::endl;\n\n    for (size_t wC = wCmin; wC <= wCmax; ++wC) {\n        if (wC < 8) {\n            // std::cout << \"using   8-bit case\\n\";\n            __attribute__((unused)) volatile uint8_t result = test<uint8_t>(TOTALNUM, wC, wAmin);\n        } else if (wC < 16) {\n            // std::cout << \"using  16-bit case\\n\";\n            __attribute__((unused)) volatile uint16_t result = test<uint16_t>(TOTALNUM, wC, wAmin);\n        } else if (wC < 32) {\n            // std::cout << \"using  32-bit case\\n\";\n            __attribute__((unused)) volatile uint32_t result = test<uint32_t>(TOTALNUM, wC, wAmin);\n        } else if (wC < 64) {\n            // std::cout << \"using  64-bit case\\n\";\n            __attribute__((unused)) volatile uint64_t result = test<uint64_t>(TOTALNUM, wC, wAmin);\n        } else if (wC < 128) {\n            // std::cout << \"using 128-bit case\\n\";\n            __attribute__((unused)) volatile uint128_t result = test<uint128_t>(TOTALNUM, wC, wAmin);\n        } else {\n            throw std::runtime_error(\"unsupported code word width\");\n        }\n    }\n}\n", "meta": {"hexsha": "9af4794d11ea1efeeb01a931fc4bf871eed243e0", "size": 4186, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/TestModuloInverseComputation2.cpp", "max_stars_repo_name": "tuddbresilience/coding_benchmark", "max_stars_repo_head_hexsha": "f4bab7b57fcb57d98d94a4efc3b8adad2bad6767", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/TestModuloInverseComputation2.cpp", "max_issues_repo_name": "tuddbresilience/coding_benchmark", "max_issues_repo_head_hexsha": "f4bab7b57fcb57d98d94a4efc3b8adad2bad6767", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/TestModuloInverseComputation2.cpp", "max_forks_repo_name": "tuddbresilience/coding_benchmark", "max_forks_repo_head_hexsha": "f4bab7b57fcb57d98d94a4efc3b8adad2bad6767", "max_forks_repo_licenses": ["Apache-2.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.703125, "max_line_length": 113, "alphanum_fraction": 0.569039656, "num_tokens": 1278, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4559171923261745}}
{"text": "#include <iostream>\n#include <pcl/io/io.h>\n#include <pcl/io/pcd_io.h>\n#include <pcl/point_types.h>\n\n#include <pcl/ModelCoefficients.h>\n\n#include <pcl/sample_consensus/method_types.h>\n#include <pcl/sample_consensus/model_types.h>\n\n#include <pcl/filters/passthrough.h>\n#include <pcl/filters/extract_indices.h>\n#include <pcl/filters/project_inliers.h>\n\n#include <pcl/segmentation/sac_segmentation.h>\n#include <pcl/surface/convex_hull.h>\n\n#include <pcl/segmentation/extract_polygonal_prism_data.h>\n\n#include <pcl/visualization/pcl_visualizer.h>\n//#include <Eigen/Dense>\n\n\n\n\ntypedef pcl::PointXYZ PointT;\ntypedef pcl::PointCloud<PointT> PointCloudT;\n\n\nint\nscale (pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_pol, double offset)\n{\n\tfloat x_total = 0.0,\n\t\ty_total = 0.0,\n\t\tnum_points = 0.0,\n\t\tx_centr = 0.0,\n\t\ty_centr = 0.0,\n\t\tX = 0.0,\n\t\tY = 0.0;\n\n\t//ciclo de leitura das coordenadas e c\u00e1lculo da m\u00e9dia \n\tfor (size_t i = 0; i < cloud_pol->points.size (); ++i)\n\t{\n\tX = cloud_pol->points[i].x;\n\tY = cloud_pol->points[i].y;\n\n\tx_total = x_total + X;\n\ty_total = y_total + Y;\n/*\n\tstd::cout << \"    \" << X\n\t\t  << \"    \" << Y<< std::endl;\n\t*/\n\n\t}\n\n\tnum_points = cloud_pol->points.size ();\n\n\tx_centr = x_total / num_points;\n\ty_centr = y_total / num_points;\n\n/*\tstd::cout << \"    \" << x_total\n\t\t  << \"    \" << y_total\n\t\t  << \"    \" << num_points \n\t\t  << \"    \" << x_centr\n\t\t  << \"    \" << y_centr << std::endl;\n\t*/\n\n\tfor (size_t i = 0; i < cloud_pol->points.size (); ++i)\n\t{\n\tX = cloud_pol->points[i].x;\n\tY = cloud_pol->points[i].y;\n\n\tX = X - x_centr;\n\tY = Y - y_centr;\n\n\tX = X * offset;\n\tY = Y * offset;\n\n\tX = X + x_centr;\n\tY = Y + y_centr;\n\n\tcloud_pol->points[i].x = X;\n\tcloud_pol->points[i].y = Y;\n/*\n\tstd::cout << \"    \" << X\n\t\t  << \"    \" << Y\n\t\t  << \"    \" << cloud_pol->points[i].x\n\t\t  << \"    \" << cloud_pol->points[i].y << std::endl;\n\t*/\n\t}\n\nreturn 1;\n}\n\n\nint\nmain (int argc, char *argv[])\n{\n\n\tPointCloudT::Ptr\tcloud (new PointCloudT),\n\t\t\t\tcloud_inliers_table (new PointCloudT),\n\t\t\t\tcloud_outliers_table (new PointCloudT),\n\t\t\t\tcloud_edge (new PointCloudT),\n\t\t\t\tcloud_edge_projected (new PointCloudT),\n\t\t\t\tcloud_poligonal_prism (new PointCloudT);\n\n\n\t/*// Load point cloud\n\tif (pcl::io::loadPCDFile (\"caixacomobjectos.pcd\", *cloud) < 0) {\n\t\tPCL_ERROR (\"Could not load PCD file !\\n\");\n\t\treturn (-1);\n\t}*/\n\n\t// Load point cloud\n\tif (pcl::io::loadPCDFile (argv[1], *cloud) < 0) {\n\t\tPCL_ERROR (\"Could not load PCD file !\\n\");\n\t\treturn (-1);\n\t}\n\n///////////////////////////////////////////\n//          Table Plane Extract          //\n///////////////////////////////////////////\n\n\t// Segment the ground\n\tpcl::ModelCoefficients::Ptr plane_table (new pcl::ModelCoefficients);\n\tpcl::PointIndices::Ptr inliers_plane_table (new pcl::PointIndices);\n\tPointCloudT::Ptr cloud_plane_table (new PointCloudT);\n\n\t// Make room for a plane equation (ax+by+cz+d=0)\n\tplane_table->values.resize (4);\n\n\tpcl::SACSegmentation<PointT> seg_table;\t// Create the segmentation object\n\tseg_table.setOptimizeCoefficients (true);\t\t\t// Optional\n\tseg_table.setMethodType (pcl::SAC_RANSAC);\n\tseg_table.setModelType (pcl::SACMODEL_PLANE);\n\tseg_table.setDistanceThreshold (0.025f);\n\tseg_table.setInputCloud (cloud);\n\tseg_table.segment (*inliers_plane_table, *plane_table);\n\n\tif (inliers_plane_table->indices.size () == 0) {\n\t\tPCL_ERROR (\"Could not estimate a planar model for the given dataset.\\n\");\n\t\treturn (-1);\n\t}\n\n\t// Extract inliers\n\tpcl::ExtractIndices<PointT> extract;\n\textract.setInputCloud (cloud);\n\textract.setIndices (inliers_plane_table);\n\textract.setNegative (false);\t\t\t// Extract the inliers\n\textract.filter (*cloud_inliers_table);\t\t// cloud_inliers contains the plane\n\n\t// Extract outliers\n\t//extract.setInputCloud (cloud);\t\t// Already done line 50\n\t//extract.setIndices (inliers);\t\t\t// Already done line 51\n\textract.setNegative (true);\t\t\t\t// Extract the outliers\n\textract.filter (*cloud_outliers_table);\t\t// cloud_outliers contains everything but the plane\n\n\tprintf (\"Plane segmentation equation [ax+by+cz+d]=0: [%3.4f | %3.4f | %3.4f | %3.4f]     \\t\\n\", \n\t\t\tplane_table->values[0], plane_table->values[1], plane_table->values[2] , plane_table->values[3]);\n\n\n\n\n///////////////////////////////////////////\n//           Box Edge Extract            //\n///////////////////////////////////////////\n\t\n\tpcl::PassThrough<PointT> pass;\n    \tpass.setInputCloud (cloud_outliers_table);\n    \tpass.setFilterFieldName (\"z\");\n    \tpass.setFilterLimits (0.63, 0.68);\n    \tpass.filter (*cloud_edge);\n\n\tpcl::ModelCoefficients::Ptr coefficients_edge (new pcl::ModelCoefficients);\n\tpcl::PointIndices::Ptr inliers_edge (new pcl::PointIndices);\n\t// Create the segmentation object\n\tpcl::SACSegmentation<pcl::PointXYZ> seg_edge;\n\t// Optional\n\tseg_edge.setOptimizeCoefficients (true);\n\t// Mandatory\n\tseg_edge.setModelType (pcl::SACMODEL_PLANE);\n\tseg_edge.setMethodType (pcl::SAC_RANSAC);\n\tseg_edge.setDistanceThreshold (0.01);\n\n\tseg_edge.setInputCloud (cloud_edge);\n\tseg_edge.segment (*inliers_edge, *coefficients_edge);\n\n\n\t///////////////////////////////\n\t// Project the model inliers //\n\t///////////////////////////////\n\tpcl::ProjectInliers<pcl::PointXYZ> proj_edge;\n\tproj_edge.setModelType (pcl::SACMODEL_PLANE);\n\tproj_edge.setIndices (inliers_edge);\n\tproj_edge.setInputCloud (cloud_edge);\n\tproj_edge.setModelCoefficients (coefficients_edge);\n\tproj_edge.filter (*cloud_edge_projected);\n\n\tdouble merge = 0.75;\n\tscale(cloud_edge_projected, merge);\n\n\t\n\t////////////////////////////////////////////////////////////////////\n\t//       Create a Concave Hull representation of the box edge     //\n\t////////////////////////////////////////////////////////////////////\n\tpcl::PointCloud<pcl::PointXYZ>::Ptr cloud_edge_hull (new pcl::PointCloud<pcl::PointXYZ>);\n\tpcl::ConvexHull<pcl::PointXYZ> chull;\n\tchull.setInputCloud (cloud_edge_projected);\n\t//chull.setAlpha (0.1);\n\tchull.reconstruct (*cloud_edge_hull);\n\n\t///////////////////////////////////////////////\n\t// Create a Poligonal Prism of the box edge  //\n\t///////////////////////////////////////////////\n\tpcl::PointIndices::Ptr inliers_poligonal_prism (new pcl::PointIndices);\n\tdouble z_min = -1.0, z_max = 0.0; // we want the points above the plane, no farther than 5 cm from the surface\n\tpcl::ExtractPolygonalPrismData<pcl::PointXYZ> prism;\n\tprism.setInputCloud (cloud_outliers_table);\n\tprism.setInputPlanarHull (cloud_edge_hull);\n\tprism.setHeightLimits (z_min, z_max);\n\tprism.segment (*inliers_poligonal_prism);\n\n\t// Extract poligonal inliers\n\tpcl::ExtractIndices<PointT> extract_polygonal_data;\n\textract_polygonal_data.setInputCloud (cloud_outliers_table);\n\textract_polygonal_data.setIndices (inliers_poligonal_prism);\n\textract_polygonal_data.setNegative (false);\t\t// Extract the inliers\n\textract_polygonal_data.filter (*cloud_poligonal_prism);\t// cloud_poligonal_prism contains the box\n\n\n\t//guarda a nuvem filtrada num novo ficheiro \n\tpcl::io::savePCDFileASCII (\"test_seg_3pecas.pcd\", *cloud_poligonal_prism);\n\n///////////////////\n// Visualization //\n///////////////////\n\tpcl::visualization::PCLVisualizer viewer (\"PCL visualizer\");\n\n\t// Table Plane\n\tpcl::visualization::PointCloudColorHandlerCustom<PointT> cloud_inliers_table_handler (cloud, 20, 255, 255); \n\tviewer.addPointCloud (cloud_inliers_table, cloud_inliers_table_handler, \"cloud inliers\");\n\n\t// Everything else in GRAY\n\tpcl::visualization::PointCloudColorHandlerCustom<PointT> cloud_outliers_table_handler (cloud, 200, 200, 200); \n\tviewer.addPointCloud (cloud_outliers_table, cloud_outliers_table_handler, \"cloud outliers\");\n\t\n\t// Edge in Green\n\tpcl::visualization::PointCloudColorHandlerCustom<PointT> cloud_edge_handler (cloud, 20, 255, 20); \n\tviewer.addPointCloud (cloud_edge, cloud_edge_handler, \"cloud edge\");\n\n\t// Edge projected\n\tpcl::visualization::PointCloudColorHandlerCustom<PointT> cloud_edge_projected_handler (cloud, 255, 69, 20); \n\tviewer.addPointCloud (cloud_edge_projected, cloud_edge_projected_handler, \"cloud edge projected\");\n\t\n\t// Edge hull\n\tpcl::visualization::PointCloudColorHandlerCustom<PointT> cloud_edge_hull_handler (cloud, 255, 20, 20); \n\tviewer.addPointCloud (cloud_edge_hull, cloud_edge_hull_handler, \"cloud edge hull\");\n\n\t// Poligonal Prism data\n\tpcl::visualization::PointCloudColorHandlerCustom<PointT> cloud_poligonal_prism_handler (cloud, 20, 20, 255); \n\tviewer.addPointCloud (cloud_poligonal_prism, cloud_poligonal_prism_handler, \"cloud Poligonal Prism\");\n\t\n\n\twhile (!viewer.wasStopped ()) {\n\t\tviewer.spinOnce ();\n\t}\n\treturn (0);\n}\n", "meta": {"hexsha": "7c9cd950bbee8dd6bba1eec0360affcf680db459", "size": 8417, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ensaio_identificacao_caixa/src/segmentation.cpp", "max_stars_repo_name": "yaoli1992/bin_picking", "max_stars_repo_head_hexsha": "e37c59e4fcf139fc2be12c8cc14861463c50d5a4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2019-04-24T12:22:53.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-17T16:07:39.000Z", "max_issues_repo_path": "ensaio_identificacao_caixa/src/segmentation.cpp", "max_issues_repo_name": "yaoli1992/bin_picking", "max_issues_repo_head_hexsha": "e37c59e4fcf139fc2be12c8cc14861463c50d5a4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ensaio_identificacao_caixa/src/segmentation.cpp", "max_forks_repo_name": "yaoli1992/bin_picking", "max_forks_repo_head_hexsha": "e37c59e4fcf139fc2be12c8cc14861463c50d5a4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2019-04-19T01:58:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-03T16:23:52.000Z", "avg_line_length": 31.2899628253, "max_line_length": 111, "alphanum_fraction": 0.6737554948, "num_tokens": 2309, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.45591719232617445}}
{"text": "#include \"solver/eigenvalue/krylov_schur_eigenvalue_solver.hpp\"\n\n#include <deal.II/lac/petsc_full_matrix.h>\n\n#include \"test_helpers/gmock_wrapper.h\"\n#include \"solver/eigenvalue/tests/spectral_radius_mock.hpp\"\n\nnamespace  {\n\nusing namespace bart;\nusing ::testing::ContainerEq;\n\nclass SolverEigenvalueKrylovSchurEigenvalueSolverTest : public ::testing::Test {\n public:\n  using Matrix = dealii::PETScWrappers::FullMatrix;\n  Matrix test_matrix_;\n  auto SetUp() -> void override;\n};\n\nauto SolverEigenvalueKrylovSchurEigenvalueSolverTest::SetUp() -> void {\n  const std::vector<std::vector<double>> matrix_values{ {3, 2, 4}, {2, 0, 2}, {4, 2, 3}};\n  test_matrix_.reinit(3,3);\n  for (int i = 0; i < 3; ++i) {\n    for (int j = 0; j < 3; ++j) {\n      test_matrix_.set(i, j, matrix_values.at(i).at(j));\n    }\n  }\n  test_matrix_.compress(dealii::VectorOperation::insert);\n}\n\nTEST_F(SolverEigenvalueKrylovSchurEigenvalueSolverTest, Dummy) {\n  std::vector<double> expected_eigenvector{ 2.0/3.0, 1.0/3.0, 2.0/3.0};\n  const double expected_spectral_radius{ 8 };\n  solver::eigenvalue::KrylovSchurEigenvalueSolver solver;\n  const auto [spectral_radius, eigenvector] = solver.SpectralRadius(test_matrix_);\n  EXPECT_NEAR(spectral_radius, expected_spectral_radius, 1e-6);\n  ASSERT_EQ(eigenvector.size(), 3);\n  for (int i = 0; i < 3; ++i) {\n    EXPECT_NEAR(std::abs(eigenvector.at(i)), expected_eigenvector.at(i), 1e-6);\n  }\n\n}\n\n} // namespace\n", "meta": {"hexsha": "f92b9b44b558a82da6ea8ebc1a5cab7b47eb51dd", "size": 1422, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/solver/eigenvalue/tests/krylov_schur_eigenvalue_solver_test.cpp", "max_stars_repo_name": "SlaybaughLab/Transport", "max_stars_repo_head_hexsha": "8eb32cb8ae50c92875526a7540350ef9a85bc050", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2018-03-14T12:30:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T14:46:44.000Z", "max_issues_repo_path": "src/solver/eigenvalue/tests/krylov_schur_eigenvalue_solver_test.cpp", "max_issues_repo_name": "SlaybaughLab/Transport", "max_issues_repo_head_hexsha": "8eb32cb8ae50c92875526a7540350ef9a85bc050", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 194.0, "max_issues_repo_issues_event_min_datetime": "2017-07-07T01:38:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-19T18:21:19.000Z", "max_forks_repo_path": "src/solver/eigenvalue/tests/krylov_schur_eigenvalue_solver_test.cpp", "max_forks_repo_name": "SlaybaughLab/Transport", "max_forks_repo_head_hexsha": "8eb32cb8ae50c92875526a7540350ef9a85bc050", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2017-07-06T22:58:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-15T07:01:21.000Z", "avg_line_length": 31.6, "max_line_length": 89, "alphanum_fraction": 0.7215189873, "num_tokens": 449, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.45591719232617445}}
{"text": "#include \"optimization_problem.hpp\"\n#include \"homogeneous.h\"\n#include \"utility.hpp\"\n#include \"jacobian.h\"\n\n#include <Eigen/Eigenvalues>\n\n#include <range/v3/all.hpp>\n\ndouble pointPlaneDistance(const Eigen::Vector3d & w, const Eigen::Vector3d & x)\n{\n  return std::abs(w.dot(x) + 1.0) / w.norm();\n}\n\nbool validatePlane(const Eigen::MatrixXd & X, const Eigen::Vector3d & w)\n{\n  for (int j = 0; j < X.rows(); j++) {\n    const Eigen::Vector3d x = X.row(j);\n    if (pointPlaneDistance(w, x) > 0.2) {\n      return false;\n    }\n  }\n  return true;\n}\n\nEigen::MatrixXd get(\n  const pcl::PointCloud<pcl::PointXYZ>::Ptr & pointcloud,\n  const std::vector<int> & indices)\n{\n  Eigen::MatrixXd A(indices.size(), 3);\n  for (const auto & [j, index] : ranges::views::enumerate(indices)) {\n    const Eigen::Vector3d p = getXYZ(pointcloud->at(index));\n    A.row(j) = p.transpose();\n  }\n  return A;\n}\n\nEigen::Matrix3d calcCovariance(const Eigen::MatrixXd & X)\n{\n  const Eigen::Vector3d c = X.colwise().mean();\n  const Eigen::MatrixXd D = X.rowwise() - c.transpose();\n  return D.transpose() * D / X.rows();\n}\n\nEigen::VectorXd solveLinear(const Eigen::MatrixXd & A, const Eigen::VectorXd & b)\n{\n  return A.householderQr().solve(b);\n}\n\nbool checkConvergence(const Vector6d & dx)\n{\n  const float dr = rad2deg(dx.head(3)).norm();\n  const float dt = (100 * dx.tail(3)).norm();\n  return dr < 0.05 && dt < 0.05;\n}\n\nconst int n_neighbors = 5;\n\nstd::vector<int> trueIndices(const std::vector<bool> & flags)\n{\n  return ranges::views::iota(0, static_cast<int>(flags.size())) |\n         ranges::views::filter([&](int i) {return flags[i];}) |\n         ranges::to_vector;\n}\n\nstd::vector<Eigen::Vector3d> filteredCoeffs(\n  const std::vector<int> & indices,\n  const std::vector<Eigen::Vector3d> & coeffs)\n{\n  return indices | ranges::views::transform([&](int i) {return coeffs[i];}) | ranges::to_vector;\n}\n\nstd::vector<Eigen::Vector3d> filteredPoints(\n  const std::vector<int> & indices,\n  const pcl::PointCloud<pcl::PointXYZ>::Ptr & pointcloud)\n{\n  const auto f = [&](int i) {return getXYZ(pointcloud->at(i));};\n  return indices | ranges::views::transform(f) | ranges::to_vector;\n}\n\nstd::tuple<std::vector<Eigen::Vector3d>, std::vector<Eigen::Vector3d>, std::vector<double>>\nOptimizationProblem::fromEdge(const Eigen::Affine3d & point_to_map) const\n{\n  // f(dx) \\approx f(0) + J * dx + dx^T * H * dx\n  // dx can be obtained by solving H * dx = -J\n\n  std::vector<Eigen::Vector3d> coeffs(edge_scan_->size());\n  std::vector<bool> flags(edge_scan_->size(), false);\n\n  #pragma omp parallel for num_threads(n_threads_)\n  for (unsigned int i = 0; i < edge_scan_->size(); i++) {\n    const pcl::PointXYZ p = transform(point_to_map, edge_scan_->at(i));\n    const auto [indices, squared_distances] = edge_kdtree_.nearestKSearch(p, n_neighbors);\n    if (squared_distances.back() >= 1.0) {\n      continue;\n    }\n\n    const Eigen::Matrix<double, n_neighbors, 3> neighbors = get(edge_map_, indices);\n    const Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> solver(calcCovariance(neighbors));\n    const Eigen::Vector3d eigenvalues = solver.eigenvalues();\n    const Eigen::Vector3d eigenvector = solver.eigenvectors().col(2);\n\n    if (eigenvalues(2) <= 3 * eigenvalues(1)) {\n      continue;\n    }\n\n    const Eigen::Vector3d c = neighbors.colwise().mean();\n    const Eigen::Vector3d p0 = getXYZ(p);\n    const Eigen::Vector3d p1 = c + 0.1 * eigenvector;\n    const Eigen::Vector3d p2 = c - 0.1 * eigenvector;\n\n    const Eigen::Vector3d d01 = p0 - p1;\n    const Eigen::Vector3d d12 = p1 - p2;\n    const Eigen::Vector3d d20 = p2 - p0;\n\n    const Eigen::Vector3d u = d20.cross(d01);\n\n    if (u.norm() >= 1.0) {\n      continue;\n    }\n\n    coeffs[i] = d12.cross(u);\n    flags[i] = true;\n  }\n\n  const std::vector<int> indices = trueIndices(flags);\n  const std::vector<Eigen::Vector3d> points = filteredPoints(indices, edge_scan_);\n  const std::vector<Eigen::Vector3d> coeffs_filtered = filteredCoeffs(indices, coeffs);\n  const std::vector<double> b(coeffs_filtered.size(), -1.0);\n  return {points, coeffs_filtered, b};\n}\n\nEigen::Vector3d estimatePlaneCoefficients(const Eigen::MatrixXd & X)\n{\n  const Eigen::VectorXd g = -1.0 * Eigen::VectorXd::Ones(X.rows());\n  return solveLinear(X, g);\n}\n\nstd::tuple<std::vector<Eigen::Vector3d>, std::vector<Eigen::Vector3d>, std::vector<double>>\nOptimizationProblem::fromSurface(const Eigen::Affine3d & point_to_map) const\n{\n  std::vector<Eigen::Vector3d> coeffs(surface_scan_->size());\n  std::vector<double> b(surface_scan_->size());\n  std::vector<bool> flags(surface_scan_->size(), false);\n\n  // surface optimization\n  #pragma omp parallel for num_threads(n_threads_)\n  for (unsigned int i = 0; i < surface_scan_->size(); i++) {\n    const pcl::PointXYZ p = transform(point_to_map, surface_scan_->at(i));\n    const auto [indices, squared_distances] = surface_kdtree_.nearestKSearch(p, n_neighbors);\n\n    if (squared_distances.back() >= 1.0) {\n      continue;\n    }\n\n    const Eigen::MatrixXd X = get(surface_map_, indices);\n    const Eigen::Vector3d w = estimatePlaneCoefficients(X);\n\n    if (!validatePlane(X, w)) {\n      continue;\n    }\n\n    const Eigen::Vector3d q = getXYZ(p);\n    const double norm = w.norm();\n\n    coeffs[i] = w / norm;\n    b[i] = -(w.dot(q) + 1.0) / norm;\n    flags[i] = true;\n  }\n\n  const std::vector<int> indices = trueIndices(flags);\n  const std::vector<Eigen::Vector3d> points = filteredPoints(indices, surface_scan_);\n  const std::vector<Eigen::Vector3d> coeffs_filtered = filteredCoeffs(indices, coeffs);\n  const std::vector<double> b_filtered =\n    indices | ranges::views::transform([&](int i) {return b[i];}) | ranges::to_vector;\n  return {points, coeffs_filtered, b_filtered};\n}\n\nEigen::MatrixXd makeJacobian(\n  const std::vector<Eigen::Vector3d> & points,\n  const std::vector<Eigen::Vector3d> & coeffs,\n  const Eigen::Vector3d & rpy)\n{\n  const Eigen::Matrix3d JX = dRdx(rpy);\n  const Eigen::Matrix3d JY = dRdy(rpy);\n  const Eigen::Matrix3d JZ = dRdz(rpy);\n\n  Eigen::MatrixXd J(points.size(), 6);\n  for (unsigned int i = 0; i < points.size(); i++) {\n    // in camera\n\n    const Eigen::Vector3d point = points.at(i);\n    const Eigen::Vector3d coeff = coeffs.at(i);\n\n    const Eigen::Vector3d drpdx = JX * point;\n    const Eigen::Vector3d drpdy = JY * point;\n    const Eigen::Vector3d drpdz = JZ * point;\n\n    // lidar -> camera\n    J(i, 0) = coeff.dot(drpdx);  // d ||residual||^2 / d roll\n    J(i, 1) = coeff.dot(drpdy);  // d ||residual||^2 / d pitch\n    J(i, 2) = coeff.dot(drpdz);  // d ||residual||^2 / d yaw\n    J(i, 3) = coeff(0);          // d ||residual||^2 / d tx\n    J(i, 4) = coeff(1);          // d ||residual||^2 / d ty\n    J(i, 5) = coeff(2);          // d ||residual||^2 / d tz\n  }\n  return J;\n}\n\nstd::tuple<Eigen::MatrixXd, Eigen::VectorXd>\nOptimizationProblem::make(const Vector6d & posevec) const\n{\n  const Eigen::Affine3d point_to_map = getTransformation(posevec);\n  const auto [edge_points, edge_coeffs, edge_coeffs_b] = fromEdge(point_to_map);\n  const auto [surface_points, surface_coeffs, surface_coeffs_b] = fromSurface(point_to_map);\n\n  const auto points = ranges::views::concat(edge_points, surface_points) | ranges::to_vector;\n  const auto coeffs = ranges::views::concat(edge_coeffs, surface_coeffs) | ranges::to_vector;\n  auto b_vector = ranges::views::concat(edge_coeffs_b, surface_coeffs_b) | ranges::to_vector;\n\n  assert(points.size() == coeffs.size());\n  assert(points.size() == b_vector.size());\n  const Eigen::MatrixXd J = makeJacobian(points, coeffs, posevec.head(3));\n  const Eigen::Map<Eigen::VectorXd> b(b_vector.data(), b_vector.size());\n  return {J, b};\n}\n\nbool isDegenerate(const OptimizationProblem & problem, const Vector6d & posevec)\n{\n  const auto [J, b] = problem.make(posevec);\n  const Eigen::MatrixXd JtJ = J.transpose() * J;\n  const Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(JtJ);\n  const Eigen::VectorXd eigenvalues = es.eigenvalues();\n  return (eigenvalues.array() < 100.0).any();\n}\n\nEigen::VectorXd calcUpdate(const Eigen::MatrixXd & J, const Eigen::VectorXd & b)\n{\n  const Eigen::MatrixXd JtJ = J.transpose() * J;\n  const Eigen::VectorXd JtB = J.transpose() * b;\n  return solveLinear(JtJ, JtB);\n}\n\n// This optimization is from the original loam_velodyne by Ji Zhang,\n// need to cope with coordinate transformation\n// lidar <- camera      ---     camera <- lidar\n// x = z                ---     x = y\n// y = x                ---     y = z\n// z = y                ---     z = x\n// roll = yaw           ---     roll = pitch\n// pitch = roll         ---     pitch = yaw\n// yaw = pitch          ---     yaw = roll\n\nVector6d optimizePose(const OptimizationProblem & problem, const Vector6d & initial_posevec)\n{\n  Vector6d posevec = initial_posevec;\n  for (int iter = 0; iter < 30; iter++) {\n    const auto [J, b] = problem.make(posevec);\n    if (J.rows() < 50) {\n      continue;\n    }\n\n    const Eigen::VectorXd dx = calcUpdate(J, b);\n\n    posevec += dx;\n\n    if (checkConvergence(dx)) {\n      break;\n    }\n  }\n  return posevec;\n}\n", "meta": {"hexsha": "16f704d6af8450f81852a748b4c0a663f96d6521", "size": 8990, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/optimization_problem.cpp", "max_stars_repo_name": "tier4/LIO-SAM", "max_stars_repo_head_hexsha": "87fa8a7f333dcf5976daab0f6fd8f7b1f9a225a6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/optimization_problem.cpp", "max_issues_repo_name": "tier4/LIO-SAM", "max_issues_repo_head_hexsha": "87fa8a7f333dcf5976daab0f6fd8f7b1f9a225a6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/optimization_problem.cpp", "max_forks_repo_name": "tier4/LIO-SAM", "max_forks_repo_head_hexsha": "87fa8a7f333dcf5976daab0f6fd8f7b1f9a225a6", "max_forks_repo_licenses": ["BSD-3-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.9304029304, "max_line_length": 96, "alphanum_fraction": 0.652836485, "num_tokens": 2611, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.45591718566604256}}
{"text": "#include \"SPImage.h\"\n\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/contrib/contrib.hpp>\n#include <boost/filesystem.hpp>\n#include <boost/program_options.hpp>\n\n#include <iostream>\n#include <cmath>\n#include <vector>\n#include <unordered_map>\n#include <algorithm>\n#include <iterator>\n#include <climits>\n#include <numeric>\n\n#include \"SLICSegment.h\"\n\nnamespace fs = boost::filesystem;\nnamespace po = boost::program_options;\n\nusing namespace std;\n\nint SPImage::slic_segmentation(cv::Mat &image, cv::Mat &sp_im, int num_sp, double compactness){\n    \n    SLICSegment::ResultType out_sp_type = SLICSegment::LABELS;\n    SLICSegment slic(num_sp, compactness);\n    num_sp = slic.performSegmentation(image, sp_im, out_sp_type);\n    \n    return num_sp;\n}\n\ntemplate <typename T>\nvoid print_vector (vector<T> vec) {\n    cout << \"[ \";\n    std::copy(vec.begin(), vec.end(),\n              std::ostream_iterator<T>(std::cout, \" \"));\n    cout << \"]\" << endl;\n}\n\nvoid print_set(set<int> vec){\n    cout << \"{ \";\n    std::copy(vec.begin(), vec.end(),\n              std::ostream_iterator<int>(std::cout, \" \"));\n    cout << \"}\" << endl;\n}\n\nvoid SPImage::build_pairwise_edges() {\n    auto edge_hash = [this](const pair<int, int> &key) { return key.first * this->spixels.size() + key.second; };\n    std::unordered_map< pair<int, int>, vector<edgew>, decltype(edge_hash) > b_pixels(0, edge_hash);\n    b_pixels.reserve(spixels.size() * 10);\n    \n    auto sp_it = sp_im->begin<int>();\n    auto edges_it = edges->begin<edgew>();\n    for(int y = 0; y < sy - 1; y++, sp_it++, edges_it++) {\n        for (int x = 0; x < sx - 1; x++, sp_it++, edges_it++) {\n            int sp = *sp_it, right = *(sp_it + 1), below = *(sp_it + sx);\n            edgew cur_e = *edges_it, right_e = *(edges_it + 1), below_e = *(edges_it + sx);\n            if (sp != right) {\n                auto r = b_pixels.emplace( make_pair(sp, right), vector<edgew>() );\n                auto l = b_pixels.emplace( make_pair(right, sp), vector<edgew>() );\n                auto w = (cur_e + right_e) / 2;\n                r.first->second.emplace_back(w);\n                l.first->second.emplace_back(w);\n            }\n            if (sp != below) {\n                auto r = b_pixels.emplace( make_pair(sp, below), vector<edgew>() );\n                auto l = b_pixels.emplace( make_pair(below, sp), vector<edgew>() );\n                auto w = (cur_e + below_e) / 2;\n                r.first->second.emplace_back(w);\n                l.first->second.emplace_back(w);\n            }\n        }\n        // last column\n        int sp = *sp_it, below = *(sp_it + sx);\n        double cur_e = *edges_it, below_e = *(edges_it + sx);\n        if (sp != below) {\n            auto r = b_pixels.emplace( make_pair(sp, below), vector<edgew>() );\n            auto l = b_pixels.emplace( make_pair(below, sp), vector<edgew>() );\n            auto w = (cur_e + below_e) / 2;\n            r.first->second.emplace_back(w);\n            l.first->second.emplace_back(w);\n        }\n    }\n    // last row\n    for (int x = 0; x < sx - 1; x++, sp_it++, edges_it++) {\n        int sp = *sp_it, right = *(sp_it + 1);\n        edgew cur_e = *edges_it, right_e = *(edges_it + 1);\n        if (sp != right) {\n            auto r = b_pixels.emplace( make_pair(sp, right), vector<edgew>() );\n            auto l = b_pixels.emplace( make_pair(right, sp), vector<edgew>() );\n            auto w = (cur_e + right_e) / 2;\n            \n            r.first->second.emplace_back(w);\n            l.first->second.emplace_back(w);\n        }\n    }\n    \n    for ( int i = 0; i < pw_params.size(); i++ ) {\n        this->pairwise.emplace_back();\n        this->pairwise[i].reserve(b_pixels.size());\n    }\n    \n    for(auto const & edge: b_pixels) {\n        for (int i = 0; i < pw_params.size(); i++) {\n            PWEdges &edges = this->pairwise[i];\n            auto &params = pw_params[i];\n            edgew avg = accumulate(edge.second.begin(), edge.second.end(), 0.0) / edge.second.size();\n            edgew inv = exp( - double(avg) / 2.0 / params.sig_s / params.sig_s );\n            edgew ev = (params.Pc * inv + params.Pw + 0.007) * params.Po;\n//            ev = 0;\n//            ev2 = 100;\n            edges.emplace_back( pw_edge {edge.first.first, edge.first.second, inv} );\n//            cout << edge.first.first << \" \" << edge.first.second << \" \" << avg << endl;\n//            print_vector<double>(edge.second);\n        }\n    }\n    \n//    for (int i = 0; i < spixels.size(); i++) {\n//        cout<< pairwise[i].a << \" \" << pairwise[i].b << \": \" << pairwise[i].w << endl;\n//    }\n    \n}\n\n/*\n Takes in a superpixel map and instatiates an SPImage by generating an array of spixels\n */\nSPImage::SPImage(cv::Mat &image, cv::Mat &sp_im, cv::Mat &edges, int num_sp){\n    \n    this->image = &image;\n    this->num_sp = num_sp;\n    this->sp_im = &sp_im;\n    this->edges = &edges;\n    this->pw_params = pw_params;\n    \n    sy = image.size[0];\n    sx = image.size[1];\n    \n    im_data = (uchar *) image.data;\n    sp_data = (int *) sp_im.data;\n    spixel z = {0, 0};\n    spixels = vector<spixel>(num_sp, z);\n    \n    auto im_it = image.begin<cv::Vec3b>(), im_it_end = image.end<cv::Vec3b>();\n    auto sp_it = sp_im.begin<int>();\n    for(int i = 0; im_it != im_it_end; ++im_it, ++sp_it, i++) {\n        spixel *p = &spixels[*sp_it];\n        p->size++;\n        p->color += (*im_it);\n        p->ext |= i < sx || i > sx * (sy - 1) || i % sx == 0 || i % sx == sx - 1;\n    }\n    \n    for (spixel &p: spixels) {\n        p.color /= p.size;\n//        cout<< p.color << endl;\n    }\n    \n    build_pairwise_edges();\n}\n\ncv::Mat SPImage::get_color_sp_im(){\n    cv::Mat color_sp = cv::Mat(sy, sx, CV_8UC3);\n    auto im_it = color_sp.begin< cv::Vec<uchar, 3> >();\n    auto sp_it = sp_im->begin<int>(), sp_it_end = sp_im->end<int>();\n    for(; sp_it != sp_it_end; ++sp_it) {\n        spixel *p = &spixels[*sp_it];\n        *(im_it++) = p->color;\n    }\n    return color_sp;\n}\n\ncv::Mat SPImage::cut_to_image(GraphCut& cut){\n    cv::Mat cut_im = cv::Mat(sy, sx, CV_8U);\n    auto im_it = cut_im.begin<uchar>(), im_it_end = cut_im.end<uchar>();\n    auto sp_it = sp_im->begin<int>();\n    for(; im_it != im_it_end; ++im_it, ++sp_it) {\n        *im_it = cut.in_source_seg(*sp_it) * 255;\n    }\n    return cut_im;\n}\n\ncv::Mat SPImage::cut_to_image(vector<bool>::iterator cut){\n    \n    cv::Mat cut_im = cv::Mat(sy, sx, CV_8U);\n    auto im_it = cut_im.begin<uchar>();\n    auto sp_it = sp_im->begin<int>();\n    for(; im_it != cut_im.end<uchar>(); ++im_it, ++sp_it) {\n        *im_it = *(cut + *sp_it) * 255;\n    }\n    return cut_im;\n}\n\ncv::Mat SPImage::seeds_to_sp_im(std::vector< std::set<int> > &seeds){\n    cv::Mat img = cv::Mat(sy, sx, CV_8U);\n    auto im_it = img.begin<uchar>(), im_it_end = img.end<uchar>();\n    auto sp_it = sp_im->begin<int>();\n    for(; im_it != im_it_end; ++im_it, ++sp_it) {\n        *im_it = 0;\n        for (auto &seed: seeds){\n            *im_it |= seed.count(*sp_it) * 255;\n        }\n    }\n    return img;\n}\n\nvector< set<int> > SPImage::generate_seeds(cv::Mat sp_img, int num_seeds, int radius) {\n    \n    const int   sy = sp_img.size[0],\n                sx = sp_img.size[1],\n                rows = ceil(sqrt(sx / sy * num_seeds));\n    int * data = (int *) sp_img.data;\n    \n    vector<int> row_cols = vector<int>(rows);\n    for (int i = 0, rem_seeds = num_seeds, rem_rows = rows; i < float(rows) / 2; i++) {\n        row_cols[i] = rem_seeds / rem_rows--;\n        rem_seeds -= row_cols[i];\n        if (rem_rows) {\n            row_cols[rows - i - 1] = rem_seeds / rem_rows--;\n            rem_seeds -= row_cols[rows - i - 1];\n        }\n    }\n    \n    vector< set<int> > seeds = vector< set<int> >(num_seeds);\n    for (int row = 0, seed = 0; row < rows; row++) {\n        int y = sy / (rows + 1) * (row + 1);\n        for (int col = 0; col < row_cols[row]; col++, seed++) {\n            int x = sx / (row_cols[row] + 1) * (col + 1);\n            for (int i = 0; i < radius; i++) {\n                for (int j = 0; j < radius; j++) {\n                    seeds[seed].insert( data[x + i + (y + j) * sx] );\n                    seeds[seed].insert( data[x - i + (y - j) * sx] );\n                    seeds[seed].insert( data[x + i + (y - j) * sx] );\n                    seeds[seed].insert( data[x - i + (y + j) * sx] );\n                }\n            }\n        }\n    }\n    return seeds;\n}\n\n", "meta": {"hexsha": "e52908ff3d559be8fae91d663cdd9aefd00d53b9", "size": 8373, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/SPImage.cpp", "max_stars_repo_name": "ajmalk/RIGOR-cpp", "max_stars_repo_head_hexsha": "19300c2bd7d7a963d16ebd6b2544eb6e09967520", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/SPImage.cpp", "max_issues_repo_name": "ajmalk/RIGOR-cpp", "max_issues_repo_head_hexsha": "19300c2bd7d7a963d16ebd6b2544eb6e09967520", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SPImage.cpp", "max_forks_repo_name": "ajmalk/RIGOR-cpp", "max_forks_repo_head_hexsha": "19300c2bd7d7a963d16ebd6b2544eb6e09967520", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.5991735537, "max_line_length": 113, "alphanum_fraction": 0.5290815717, "num_tokens": 2447, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.45591718566604256}}
{"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_ARITHMETIC_HPP_INCLUDED\n#define BOOST_SIMD_ARITHMETIC_ARITHMETIC_HPP_INCLUDED\n\n//<include> please don't modify between these tags\n#include <boost/simd/arithmetic/include/functions/fast_toint.hpp>\n#include <boost/simd/arithmetic/include/functions/negs.hpp>\n#include <boost/simd/arithmetic/include/functions/divround.hpp>\n#include <boost/simd/arithmetic/include/functions/divfloor.hpp>\n#include <boost/simd/arithmetic/include/functions/divfix.hpp>\n#include <boost/simd/arithmetic/include/functions/divceil.hpp>\n#include <boost/simd/arithmetic/include/functions/random.hpp>\n#include <boost/simd/arithmetic/include/functions/logical_xor.hpp>\n#include <boost/simd/arithmetic/include/functions/ifloor.hpp>\n#include <boost/simd/arithmetic/include/functions/fast_hypot.hpp>\n#include <boost/simd/arithmetic/include/functions/iround.hpp>\n#include <boost/simd/arithmetic/include/functions/arg.hpp>\n#include <boost/simd/arithmetic/include/functions/sqrt1pm1.hpp>\n#include <boost/simd/arithmetic/include/functions/remainder.hpp>\n#include <boost/simd/arithmetic/include/functions/rem.hpp>\n#include <boost/simd/arithmetic/include/functions/mod.hpp>\n#include <boost/simd/arithmetic/include/functions/remquo.hpp>\n#include <boost/simd/arithmetic/include/functions/minmod.hpp>\n#include <boost/simd/arithmetic/include/functions/iceil.hpp>\n#include <boost/simd/arithmetic/include/functions/trunc.hpp>\n#include <boost/simd/arithmetic/include/functions/ceil.hpp>\n#include <boost/simd/arithmetic/include/functions/round.hpp>\n#include <boost/simd/arithmetic/include/functions/floor.hpp>\n#include <boost/simd/arithmetic/include/functions/two_split.hpp>\n#include <boost/simd/arithmetic/include/functions/two_prod.hpp>\n#include <boost/simd/arithmetic/include/functions/two_add.hpp>\n#include <boost/simd/arithmetic/include/functions/rsqrt.hpp>\n#include <boost/simd/arithmetic/include/functions/sqrt.hpp>\n#include <boost/simd/arithmetic/include/functions/sqr.hpp>\n#include <boost/simd/arithmetic/include/functions/rec.hpp>\n#include <boost/simd/arithmetic/include/functions/rdivide.hpp>\n#include <boost/simd/arithmetic/include/functions/oneplus.hpp>\n#include <boost/simd/arithmetic/include/functions/oneminus.hpp>\n#include <boost/simd/arithmetic/include/functions/minusone.hpp>\n#include <boost/simd/arithmetic/include/functions/min.hpp>\n#include <boost/simd/arithmetic/include/functions/max.hpp>\n#include <boost/simd/arithmetic/include/functions/madd.hpp>\n#include <boost/simd/arithmetic/include/functions/ldivide.hpp>\n#include <boost/simd/arithmetic/include/functions/ldiv.hpp>\n#include <boost/simd/arithmetic/include/functions/idivround.hpp>\n#include <boost/simd/arithmetic/include/functions/idivfloor.hpp>\n#include <boost/simd/arithmetic/include/functions/idivfix.hpp>\n#include <boost/simd/arithmetic/include/functions/idivceil.hpp>\n#include <boost/simd/arithmetic/include/functions/hypot.hpp>\n#include <boost/simd/arithmetic/include/functions/fma.hpp>\n#include <boost/simd/arithmetic/include/functions/fam.hpp>\n#include <boost/simd/arithmetic/include/functions/dist.hpp>\n#include <boost/simd/arithmetic/include/functions/correct_fma.hpp>\n#include <boost/simd/arithmetic/include/functions/average.hpp>\n#include <boost/simd/arithmetic/include/functions/amul.hpp>\n#include <boost/simd/arithmetic/include/functions/abs.hpp>\n//<\\include>\n\n#endif\n", "meta": {"hexsha": "2870995335a63df2dd6df247cdf3b7934c1f7b92", "size": 3852, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/arithmetic/include/boost/simd/arithmetic/arithmetic.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/arithmetic.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/arithmetic.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": 57.4925373134, "max_line_length": 80, "alphanum_fraction": 0.7689511942, "num_tokens": 832, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358014, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.4558795943174883}}
{"text": "// Copyright (c) Don Organ 2018, 2019\n// All rights reserved.\n\n#include <stdio.h>\n#include <math.h>\n#include <string.h>\n#include <stdlib.h>\n#include <string>\n#include <map>\n#include <deque>\n#include <set>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n\nnamespace bg = boost::geometry;\n\nconst double My_PI = 3.141592653589793; /* Yes - I know this is defined in various header files (maybe cmath, math.h, or boost/math/constants.h), but\n                                    * getting it actually included was dependent on setting other various #defines - and it became\n                                    * difficult to get it all to build reliably on various platforms. So I gave up and defined it here.\n                                    * (Now, let's debate how many digits I should have defined this to.)\n                                    */\n\nint dvo_debug = 0;\nconst double BadValue = 9.999e9;\nconst double SmallValue = 0.000001; // for use in tolerances, etc.\n\n\ntemplate <typename T> inline const T& Max(const T&arg1, const T&arg2) { return (arg1>arg2) ? arg1 : arg2; };\ntemplate <typename T> inline const T& Min(const T&arg1, const T&arg2) { return (arg1<arg2) ? arg1 : arg2; };\n\nconst char* Indent(unsigned level, unsigned spaces_per_level=4)\n{\n    static const char lots_of_spaces[] = \"                                                                                                 \" // no comma\n                                            \"                                                                                                 \";\n    static const char* end_of_spaces = lots_of_spaces + sizeof(lots_of_spaces)-1; // points to '\\0' at end\n    const char* start = end_of_spaces - (spaces_per_level * level);\n    return (start < lots_of_spaces) ? lots_of_spaces : start;\n}\n\n\n// Started with ConvexMirror/try16.cpp - and modified for the Concave system\n\n/* A 2 component optic system - a sun (at infinite distance and a finite\n * angular width), and a Concave mirror (no observer - as was in the ConvexMirror system).\n *\n * My conventions...\n * ..._ang = value is an angle (in degrees) - between two lines (or points, etc.)\n * ..._dir = value is a direction (in degrees) in the cartesian coordinates - i.e. 0 degrees\n *     is horizontal to the right, 90 degree is straight up, 180 is horizontal to the\n *     left and 270 is straight down. \n * Center of the curvature of the Mirror is at (0,0)\n *\n * Standard Trig Quadrants...\n *          |\n *        2 | 1\n *      ----+----\n *        3 | 4\n *          |\n * But this is NOT my convention here.\n *\n *\n * Inputs (all angles in degrees):\n * r=radius of convex mirror whose Center of curvature is at (0,0)\n * sa=altitude of the center-point of the sun - actually the direction of a ray from the sun. (0=horizontal and to the right)\n * sw=angular width of the sun. Default=0.5\n *\n * Calculates:\n * two series of rays - one series from the 'top' of the sun, and the other from the 'bottom'\n *     of the sun. An incident ray strikes the Mirror and generates a reflected ray.\n *     The series if for various parallel rays that strike the sun at different locations.\n *\n */\n\ndouble to_degrees(double radians) { return radians * (180.0 / My_PI); }\ndouble to_radians(double degrees) { return degrees / (180.0 / My_PI); }\ndouble NormalizeAngle(double degrees) /* Adjust to between 0 and 360 degrees -\n                    * yes I find this name confusing - since 'normal' often means perpendicular to a surface,\n                    * and that is NOT what it means here.\n                    */\n{\n       while(degrees >= 360) degrees -= 360;\n       while (degrees < 0) degrees += 360;\n       return degrees;\n}\ndouble MinAngle(double degrees) /* Similar to NormalizeAngle() - but adjust to between 0 and 180 degrees */\n{\n       while(degrees >= 180) degrees -= 180;\n       while (degrees < 0) degrees += 180;\n       return degrees;\n}\n\nint RayStrikeConcave(double ray_dir, double normal_dir)\n    // A ray reaches the surface of a circle - is the ray approaching from the inside (concave\n    // side) or convex side? Concave=true, Convex=false;\n{\n    double ray_dir_0_360 = NormalizeAngle( ray_dir );\n    double adjusted_normal_dir = normal_dir;\n    while ( ray_dir_0_360 > (adjusted_normal_dir + 180) ) adjusted_normal_dir += 360;\n    while ( ray_dir_0_360 < (adjusted_normal_dir - 180) ) adjusted_normal_dir -= 360;\n    bool return_value = ( (ray_dir_0_360 < (adjusted_normal_dir + 90)) && (ray_dir_0_360 > (adjusted_normal_dir - 90)) ) ? 1 : 0;\n//printf(\"\\t\\t\\t%s(ray=%g, normal=%g): ray_dir_0_360=%g, adjusted_normal=%g, return_value=%d\\n\", __func__, ray_dir, normal_dir, ray_dir_0_360, adjusted_normal_dir, return_value);\n    return return_value;\n}\n\nconst double NearlyEqual_default1 = SmallValue;\nconst double NearlyEqual_default2 = SmallValue;\nbool NearlyEqual(double f1, double f2, double multiply_tolerance=NearlyEqual_default1, double additive_tolerance=NearlyEqual_default2)\n{\n    if (f1 == f2) return true;\n    double difference = f1-f2;\n    double max_value, min_value;\n    if (fabs(f1) > fabs(f2)) {\n        max_value = fabs(f1);\n        min_value = fabs(f2);\n    } else {\n        max_value = fabs(f2);\n        min_value = fabs(f1);\n    }\n    if (multiply_tolerance != 0) {\n        if (max_value/multiply_tolerance < min_value) {\n            if (dvo_debug>=10)\n            printf(\"Fails: NearlyEqual(%g,%g, %g,%g): fails multiply tolerance: %g/%g=%g < %g at %d of %s\\n\",\n                    f1,f2, multiply_tolerance, additive_tolerance, max_value, multiply_tolerance, min_value, __LINE__, __FILE__ );\n            return false;\n        }\n    }\n    if (additive_tolerance != 0) {\n        if ((max_value - min_value) > additive_tolerance) {\n            if (dvo_debug>=10)\n            printf(\"Fails: NearlyEqual(%g,%g, %g,%g): fails additive tolerance: %g-%g=%g > %g at %d of %s\\n\",\n                    f1,f2, multiply_tolerance, additive_tolerance, max_value, min_value, max_value-min_value, additive_tolerance, __LINE__, __FILE__ );\n            return false;\n        }\n    }\n    return true;\n}\n\ntypedef bg::model::d2::point_xy<double>  Point;\ntypedef bg::model::segment<Point> Segment;\n\nstatic std::deque<Segment> debug_segments;\n\nvoid AddDebugSegment(const Segment&seg)\n{\n    debug_segments.push_back( seg );\n}\nvoid AddDebugSegment(const Point& pt, double ray_dir, double length=30)\n{\n    Point Find2ndPoint(const Point&, double direction, double distance);\n    Point pt_b = Find2ndPoint(pt, ray_dir, length );\n    debug_segments.push_back( Segment(pt,pt_b) );\n}\n\n\nconst Point& Set( Point& pt, double new_x, double new_y)\n{\n    pt.x( new_x );\n    pt.y( new_y );\n    return pt;\n}\n\nbool operator==(const Point& pt1, const Point& pt2)\n{\n    return ((pt1.x() == pt2.x()) && (pt1.y() == pt2.y())) ? 1 : 0;\n}\nbool Defined(const Point& pt)\n{\n    return (pt.x() != BadValue) && (pt.y() != BadValue);\n}\n\nbool NearlyEqual(const Point& p1, const Point& p2, double multiply_tolerance=SmallValue, double additive_tolerance=SmallValue)\n{\n    return NearlyEqual(p1.x(), p2.x(),multiply_tolerance, additive_tolerance) && NearlyEqual(p1.y(), p2.y(),multiply_tolerance, additive_tolerance);\n}\n\n\ndouble Distance(const Point& pt1, const Point& pt2)\n{\n    assert(pt1.x() != BadValue);\n    assert(pt1.y() != BadValue);\n    assert(pt2.x() != BadValue);\n    assert(pt2.y() != BadValue);\n    double new_distance = bg::distance(pt1,pt2);\n    return new_distance;\n}\n\ndouble Direction(const Point& pt1, const Point& pt2) // the direction from pt1 to pt2 - in degrees.\n{\n    return NormalizeAngle(to_degrees( atan2( pt2.y()-pt1.y(), pt2.x()-pt1.x() )));\n}\n\nPoint Find2ndPoint(const Point& pt1, double direction, double distance)\n{\n    double X = pt1.x() + distance * cos( to_radians( direction ) );\n    double Y = pt1.y() + distance * sin( to_radians( direction ) );\n    return Point(X,Y);\n}\n\nPoint Closest(const Point& from_pt, double direction, const Point& pt1, const Point& pt2)\n    // Assume the 3 points are co-linear. Which of pt1 or pt2 is closest to from_ptr\n    // (but also in the direction indicated)?\n{\n    assert( from_pt.x() != BadValue);\n    assert( from_pt.y() != BadValue);\n    assert( pt1.x() != BadValue);\n    assert( pt1.y() != BadValue);\n    assert( pt2.x() != BadValue);\n    assert( pt2.y() != BadValue);\n    double distance1 = Distance(from_pt, pt1);\n    double distance2 = Distance(from_pt, pt2);\n    return (distance1 < distance2) ? pt1 : pt2 ;\n}\n\n\nint Intersection_2Segments(const Segment& seg1, const Segment& seg2, Point& XsectionPt, bool include_end_points=true,\n                        double ne_param1=NearlyEqual_default1, double ne_param2=NearlyEqual_default2)\n{\n    std::vector<Point> geometry_out;\n    bool bogus = bg::intersection(seg1,seg2,geometry_out);\n    if ( geometry_out.size() ) {\n        XsectionPt = geometry_out[0];\n        if (include_end_points == false) {\n            if (NearlyEqual( seg1.first.x(), XsectionPt.x(), ne_param1, ne_param2) && NearlyEqual(seg1.first.y(), XsectionPt.y(), ne_param1, ne_param2) ) return 0;\n            if (NearlyEqual( seg1.first.x(), XsectionPt.x(), ne_param1, ne_param2) && NearlyEqual(seg1.second.y(), XsectionPt.y(), ne_param1, ne_param2) ) return 0;\n        }\n        return 1;\n    }\n    return 0;\n}\n\n\nvoid TerminateRay(const Segment& Ray, const Segment& LineB, Point &closest_far_point)\n    /* Ray and LineB are each line segments. Ray represents a light-ray originating at Ray_Pt1 and possibly terminating at Ray_Pt2.\n     * LineB represents an opaque surface that possibly crosses the path of the Ray.\n     * Detemine if Ray hits LineB and, if so, if it hits it before it hits Ray_Pt2\n     * In either case, closest_far_point is set to the termination point (maybe the original Ray_Pt2, or maybe a point on the LineB segment).\n     */\n{\n//printf(\"%s(Ray=(%g,%g)..(%g,%g), LineB=(%g,%g)..(%g,%g),...)\\n\", __func__, Ray.first.x(), Ray.first.y(), Ray.second.x(), Ray.second.y(), LineB.first.x(), LineB.first.y(), LineB.second.x(), LineB.second.y() );\n    closest_far_point = Ray.second; // May get changed below.\n    Point intersection_pt;\n    int has_intersection = Intersection_2Segments( LineB, Ray, intersection_pt, false );\n    if (has_intersection) {\n        assert( Ray.first.x() != BadValue);\n        assert( Ray.first.y() != BadValue);\n        assert( Ray.second.x() != BadValue);\n        assert( Ray.second.y() != BadValue);\n        assert( intersection_pt.x() != BadValue);\n        assert( intersection_pt.y() != BadValue);\n        double distance1 = Distance( Ray.first, Ray.second );\n        double distance2 = Distance( Ray.first, intersection_pt );\n//printf(\"\\tHas Intersection: distance1=%g, distance2=%g\\n\", distance1, distance2);\n        if (distance1 > distance2)\n            closest_far_point = intersection_pt;\n    }\n}\n\n\nint ProjectPointOntoCircle(const Point& from_pt, double direction, const Point& cir_center, double radius, Point& pt1, Point& pt2)\n    /* Project a ray in direction onto the circle.\n     * Returns 0, 1 or 2 - the number of times the ray intersects with the circle.\n     * If return==0, then neither pt1 or pt2 is altered.\n     * If return==1, then pt1= the point of intersection, and pt2 is unaltered.\n     * If return==2, then pt1 and pt2 are both set.\n     */ \n{\n    assert( from_pt.x() != BadValue);\n    assert( from_pt.y() != BadValue);\n    assert( cir_center.x() != BadValue);\n    assert( cir_center.y() != BadValue);\n    double distance_from_center = Distance( from_pt, cir_center );\n    double center_to_from_dir = Direction( cir_center, from_pt ); // direction in degrees\n    double interior_angle_at_from = direction - center_to_from_dir;\n    double back_edge = distance_from_center * sin( to_radians( interior_angle_at_from ) );\n    double angle_shadow_pt_to_back_edge = to_degrees( asin( back_edge / radius ) );\n    double direction_center_to_shadow_pt = direction - angle_shadow_pt_to_back_edge;\n    double shadow_X = cir_center.x() + radius * cos( to_radians( direction_center_to_shadow_pt ) );\n    double shadow_Y = cir_center.y() + radius * sin( to_radians( direction_center_to_shadow_pt ) );\n\n    pt1.x( shadow_X );\n    pt1.y( shadow_Y );\n\n    debug_segments.push_back( Segment( from_pt, pt1 ) );\n    return 1;\n}\n\ndouble ApparentWidth( const Point&p1, const Point&p2, double from_this_angle)\n  // Given two points (via cartesian coordinates), and an observer at infinite\n  // distance - how far apart do the points appear?\n{\n    double delta_X = p1.x() - p2.x();\n    double delta_Y = p1.y() - p2.y();\n    double hypotenuse_length = sqrt( delta_X*delta_X + delta_Y*delta_Y ); // length between the points\n//    double hypotenuse_angle_radians = (delta_X == 0) ? 0 : atan( delta_Y / delta_X );\n    double hypotenuse_angle_radians = atan2( delta_Y, delta_X );\n    double   observer_angle_radians = to_radians(from_this_angle);\n    double delta_radians = hypotenuse_angle_radians - observer_angle_radians;\n    double apparent_height = hypotenuse_length * sin( delta_radians );\n    return fabs(apparent_height);\n}\n\ndouble ApparentWidth_ang( const Point&p1, const Point&p2, const Point&observer)\n    // Similar to ApparentWidth() - but reports in apparent angle (in degrees)\n{\n    double dir1 = Direction( observer, p1 );\n    double dir2 = Direction( observer, p2 );\n    return MinAngle( fabs(dir1 - dir2) );\n}\n\n\nstruct BBox\n{\n    BBox() : min_pt(BadValue,BadValue), max_pt(BadValue,BadValue) {};\n\n    void Update(const Point& new_pt) {\n               if ((new_pt.x() > max_pt.x()) || (max_pt.x() == BadValue)) max_pt.x( new_pt.x() );\n               if ((new_pt.y() > max_pt.y()) || (max_pt.y() == BadValue)) max_pt.y( new_pt.y() );\n               if ((new_pt.x() < min_pt.x()) || (min_pt.x() == BadValue)) min_pt.x( new_pt.x() );\n               if ((new_pt.y() < min_pt.y()) || (min_pt.y() == BadValue)) min_pt.y( new_pt.y() );\n    }\n\n    double MaxX() const { return max_pt.x(); }\n    double MaxY() const { return max_pt.y(); }\n    double MinX() const { return min_pt.x(); }\n    double MinY() const { return min_pt.y(); }\n\n    double MidX() const { return (max_pt.x() == BadValue) ? BadValue : (max_pt.x() + min_pt.x()) / 2; }\n    double MidY() const { return (max_pt.y() == BadValue) ? BadValue : (max_pt.y() + min_pt.y()) / 2; }\n\n    double Diagonal() const { return Defined() ? Distance( min_pt, max_pt ) : BadValue; }\n\n    bool Defined() const { return ::Defined(min_pt) && ::Defined(max_pt); }\n\n    Point min_pt;\n    Point max_pt;\n};\n\nstruct TracedRay\n    // For forward-tracing one ray and its interactions with a Concave mirror surface.\n    // The mirror surface is a portion of a circle (an arc).\n{\n    TracedRay() : m_sun_dir(BadValue), m_MirrorPt(BadValue,BadValue), m_ray_status(Unknown), m_reflect_dir(BadValue), m_StrikePts() {};\n\n    enum RayStatus {Unknown,    // uninitialized - or not yet traced.\n                    Convex,     // The incident ray reaches the Target on the Concave Mirror from the wrong side (outside - convex) of the  mirror.\n                    Concave,    // The incident ray reaches the Target on the Concave Mirror from the expected side (inside - concave), but not further traced.\n                    Obscured,   // Although Concave is true (above), the incident ray would have 1st crossed the mirror's arc (so would not reach the target).\n                    NStrike,    // The ray strikes the concave side of the mirror, and its reflection also strikes the mirror (perhaps more than once),\n                                // but eventually a reflected ray progresses beyond the mirror.\n                    NStrikeOut, // Similar to NStrike - ray tracing stops before a ray escapes the mirror.\n                    Unobscured  // The ray strikes the concave side of the mirror and is reflected (without again striking the mirror). Might hit a\n                                // stencil or wall.\n                   };\n\n    void RayReport(FILE *fout=stdout, unsigned level=0) const;\n\n    unsigned CountObscuredRays() const;\n\n\n    double m_sun_dir; // Direction of incident ray\n    Point m_MirrorPt; // The incident ray points here (but may not reach - depending on m_ray_status)\n    RayStatus m_ray_status; /* Indicates status of the reflected ray - see comments for ConcaveRayCalculate(). */\n    double m_reflect_dir; // Valid only if NStrike or Unobscured\n    std::deque<Point> m_StrikePts; // Valid if NStrike - has only 2nd to Nth reflection points (i.e. not 1stStrikePt=m_MirrorPt)\n                                    // One point *might* be valid if Unobscured.\n\n};\nstatic const char* Name(TracedRay::RayStatus rs)\n{\n    switch(rs) {\n        case TracedRay::Unknown:    return \"Unknown\";\n        case TracedRay::Convex:        return \"Convex\";\n        case TracedRay::Concave:    return \"Concave\";\n        case TracedRay::Obscured:    return \"Obscured\";\n        case TracedRay::NStrike:    return \"NStrike\";\n        case TracedRay::NStrikeOut:    return \"NStrikeOut\";\n        case TracedRay::Unobscured:    return \"Unobscured\";\n        default:            return \"undefined\";\n    }\n}\n\nvoid TracedRay::RayReport(FILE *fout, unsigned level) const\n{\n    fprintf(fout, \"%sIncidentRay=%g (deg), Mirror=(%g,%g) Status=%s\", Indent(level), m_sun_dir, m_MirrorPt.x(), m_MirrorPt.y(), Name(m_ray_status));\n    switch (m_ray_status) {\n        case TracedRay::Unknown:     break;\n        case TracedRay::Convex:      break;\n        case TracedRay::Concave:     fprintf(fout, \", (not traced further)\");    break;\n        case TracedRay::Obscured:    fprintf(fout, \", 1st Strike=(%g,%g)\", m_StrikePts.begin()->x(), m_StrikePts.begin()->y() ); break;\n        case TracedRay::NStrike:     // fall thru\n        case TracedRay::NStrikeOut:  // fall thru\n        case TracedRay::Unobscured:  {\n                                        int count = 0;\n                                        fprintf(fout, \", ReflectDir=%g\", m_reflect_dir );\n                                        for (auto it= m_StrikePts.begin(); it != m_StrikePts.end(); ++it) {\n                                            count++;\n                                            if (count == 1) fprintf(fout, \", Strikes=\");\n                                            fprintf(fout, \"(%g,%g) \", it->x(), it->y() );\n                                        }\n                                    }\n                                    break;\n        default:            break;\n    }\n    fprintf(fout,\"\\n\");\n}\n\nunsigned TracedRay::CountObscuredRays() const\n{\n    return (m_ray_status <= Obscured) ? 1 : 0;\n}\n\n\nbool Intersection(const Point& pt1, double arg_dir1, const Point& pt2, double arg_dir2, Point &intersection_pt) // returns success\n{\n    if (pt1 == pt2) { intersection_pt = pt1; return true; } // avoids some special cases below\n    double dir1 = NormalizeAngle( arg_dir1 );\n    double dir2 = NormalizeAngle( arg_dir2 );\n    if (dir1 == dir2) return false; // Could be true! If the lines are co-linear!\n    if (dir1 == NormalizeAngle(dir2+180)) return false; // Could be true! If the lines are co-linear!\n\n    bool bad_tan1 = ( (dir1 == 90) || (dir1 == 270) ) ? 1 : 0; // Tangent would explode\n    bool bad_tan2 = ( (dir2 == 90) || (dir2 == 270) ) ? 1 : 0; // Tangent would explode\n\n    if ( bad_tan1 ) {\n        if (bad_tan2)\n            fprintf(stderr,\"%s((%g,%g),%g, (%g,%g),%g,...), unexpected case at %d of %s\\n\", __func__,\n                       pt1.x(), pt1.y(), arg_dir1, pt2.x(), pt2.y(), arg_dir2, __LINE__, __FILE__);\n        Set( intersection_pt, pt1.x(), pt2.y() + tan(to_radians(dir2)) * (pt1.x() - pt2.x()) );\n        return true;\n    } \n    if ( bad_tan2 ) {\n        Set( intersection_pt, pt2.x(), pt1.y() + tan(to_radians(dir1)) * (pt2.x() - pt1.x()) );\n        return true;\n    }\n\n    double tan1 = tan(to_radians( dir1 ));\n    double tan2 = tan(to_radians( dir2 ));\n\n    double X = (pt2.y() - pt1.y() + tan1 * pt1.x() - tan2 * pt2.x()) / (tan1-tan2);\n    double Y = BadValue;\n    if (X != pt1.x()) {\n        Y = pt1.y() + tan1 * (X - pt1.x());\n    } else if (X != pt2.x()){\n        Y = pt2.y() + tan2 * (X - pt2.x());\n    } else { // X == pt1.x() == pt2.x() - so must also have the same Ys - should have been caught for the pt1==pt2 above\n        fprintf(stderr,\"%s((%g,%g),%g, (%g,%g),%g,...), unexpected case at %d of %s\\n\", __func__,\n                   pt1.x(), pt1.y(), arg_dir1, pt2.x(), pt2.y(), arg_dir2, __LINE__, __FILE__);\n        return false;\n    }\n\n    Set(intersection_pt, X,Y);\n    if (NearlyEqual( intersection_pt, pt1 )) return true;\n    if (NearlyEqual( intersection_pt, pt2 )) return true;\n\n    // Found and intersection point - now check if it is in the negative direction (i.e. before where the ray starts).\n    double final_dir1 = Direction(pt1, intersection_pt);\n    double final_dir2 = Direction(pt2, intersection_pt);\n\n    if (     (!NearlyEqual( dir1, final_dir1 )) || (!NearlyEqual( dir2, final_dir2 )) ) {\n        if(dvo_debug)\n            printf(\"%s((%g,%g),dir1=%g, (%g,%g),dir2=%g), intersection=(%g,%g), final1=%g, final2=%g\\n\",\n                   __func__, pt1.x(), pt1.y(), arg_dir1, pt2.x(), pt2.y(), arg_dir2, intersection_pt.x(), intersection_pt.y(), final_dir1, final_dir2);\n        return false;\n    }\n\n    return true;\n}\n\n\nPoint FindReflectPoint_Concave( const Point& MirrorCOC, double Radius, const Point& MirrorReflectPt, double Incident_dir)\n    /* A reflected ray originates at MirrorReflectPt on the concave surface of a (semi-)circular mirror with center\n     * of curvature at MirrorCOC. The ray will travel a distance across the interior and the cross the circle (again\n     * striking the mirror if it extends that far). This routine determines the point where the ray would strike\n     * the mirror.\n     */\n{\n    double normal_dir = Direction(MirrorCOC,MirrorReflectPt);\n    double tangent_dir = NormalizeAngle(normal_dir + 90);\n    double inner_angle = NormalizeAngle(Incident_dir - tangent_dir); // angle from COC to MirrorReflectPt to Incident_dir\n    double arc_length_deg = inner_angle *2;\n    double second_normal_dir = NormalizeAngle(normal_dir + arc_length_deg);\n\n    return Find2ndPoint(MirrorCOC, second_normal_dir, Radius );\n}\n\nbool NormalWithinArc(double arg_the_normal_dir, double arg_min_normal_dir, double arg_max_normal_dir)\n    // Is the_normal_dir with [min_normal_dir,max_normal_dir]? (all are degrees)\n    // The trick is our [0,360) scheme can break down a bit here. Consider:\n    // the_normal_dir = 60, min_normal_dir=350, max_normal_dir=70. In this case\n    // the_normal_dir<min_normal_dir, so a naive implementation might consider outside\n    // the arc.\n    // Here's my approach.\n    // 1st normalize the_normal_dir and min_normal_dir i.e. adjust so that each is [0,360).\n    // 2nd, if max_normal_dir < min_normal_dir then add 360 to max_normal_dir.\n    // 3rd - do the comparison.\n{\n    // Step 1\n    double the_normal_dir = NormalizeAngle(arg_the_normal_dir);\n    double min_normal_dir = NormalizeAngle(arg_min_normal_dir); // So min_normal_dir is [0,360)\n    double max_normal_dir = NormalizeAngle(arg_max_normal_dir);\n\n    // Step 2\n    if (the_normal_dir < min_normal_dir) the_normal_dir += 360; // So the_normal_dir is now [min_normal_dir,720)\n    if (max_normal_dir < min_normal_dir) max_normal_dir += 360; // So max_normal_dir is now [min_normal_dir,720) \n\n    // Step 3\n    bool result = ( (min_normal_dir <= the_normal_dir) && (the_normal_dir <= max_normal_dir) ) ? 1 : 0;\n\n    return result;\n}\n\n\n\n\ndouble ConcaveRayCalculate (\n        const Point& MirrorCOC, double Radius, double min_normal_dir, double max_normal_dir, // These args define the mirror's size and position\n        double incident_dir, const Point& RayOriginPt, const Point& TargetPt,\n        std::deque<Point>& StrikePts, TracedRay::RayStatus& ray_status  // These args are output arguments\n        ) \n    /* Assume a concave mirror, with center-of-curvature and radius as per the first two arguments.\n     * Assume the min/max normal_dirs point from the COC to either end of the mirror's surface (i.e. are surface normals at the\n     *     ends of the arc representing the concave surface). So the surface is an arc.\n     * Assume the incident ray is targeted for the TargetPt on the mirror. RayOriginPt is optional - doesn't make sense with the sun\n     *      (which is at infinity). But is useful in reverse ray-tracing.\n     *\n     *\n     * ConcaveRayCalculate(): Determine...\n     * if Convex - then the ray is terminated at the first m_StrikePts - on the mirror's surface.\n     * if Concave - then the ray is reflected and will be further traced.\n     * if Obscured - The incident ray crossed the mirror surface first - between min and max normal_dirs. (If it did, then no\n     *     no reflected ray is generated, and the incident ray is terminated at the point where it first struck the mirror's surface).\n     * if NStrike - the reflected ray strikes the mirror surface again - m_StrikePts are set.\n     * if Unobscured - then incident ray is reflected and extends beyond the mirror\n     *  (As way of example - assume the concave mirror is in the shape of the letter C. If the incident_dir is from over-head and the TargetPt is at the\n     *   top of the C, then that is the Convex situation.  If the incident dir is from the right and the TargetPt is on the left, then the ray would\n     *   the C and hit the Concave surface. If the incident ray is from over-head and the TargetPt is at the bottom of the C, then that is Obscured.)\n     */\n{\n    assert(Defined(MirrorCOC));\n    if ( !Defined( TargetPt ) ) return BadValue;\n    \n    // Case 1 - does the ray (incident_dir) reach the TargetPt from the inside (concave) or outside?\n    double normal_at_target = Direction( MirrorCOC, TargetPt );\n    ray_status = RayStrikeConcave( incident_dir, normal_at_target ) ? TracedRay::Concave : TracedRay::Convex ; // RayStrikeConcave() returns 0 or 1\n    if ( ray_status == TracedRay::Convex ) {\n        StrikePts.push_back( TargetPt );\n        return BadValue;\n    }\n\n    // Case 2 - does the ray (incident_dir) cross the mirror surface between the normal_dirs before it reaches the TargetPt?\n    // Applicable only if the ray originates outside the radius of the mirror's surface\n    if ( !Defined(RayOriginPt) || (Distance(RayOriginPt,MirrorCOC) > Radius) ) {\n        Point potential_1stStrikePt = FindReflectPoint_Concave( MirrorCOC, Radius, TargetPt, NormalizeAngle( incident_dir + 180 ) );\n        // potential_1stStrikePt is on the circle around MirrorCOC - but is that point between the normals delineating the arc?\n        double potential_1stStrike_normal_dir = Direction( MirrorCOC, potential_1stStrikePt );\n        if ( NormalWithinArc(potential_1stStrike_normal_dir, min_normal_dir, max_normal_dir) ) {\n            StrikePts.push_back( potential_1stStrikePt );\n            ray_status = TracedRay::Obscured;\n            return BadValue;\n        }\n    }\n\n    // Case 3 - a reflection is generated. Does the reflection again strike the arc?\n    StrikePts.push_back( TargetPt );\n    ray_status = TracedRay::Unobscured; // May get changed below\n    double next_incident_dir = incident_dir;\n    double reflect_dir = BadValue;\n\n    const int loop_limit = 20;\n    int loop_count = 0;\n    while (1) { // follow reflections along the mirror surface\n        loop_count++;\n        double this_strike_normal = Direction( MirrorCOC, StrikePts.back() );\n        reflect_dir = NormalizeAngle( next_incident_dir + 2*(this_strike_normal + -next_incident_dir) +180);\n        Point next_potential_strike_pt = FindReflectPoint_Concave( MirrorCOC, Radius,  StrikePts.back(), reflect_dir );\n        double next_potential_strike_normal = Direction( MirrorCOC, next_potential_strike_pt );\n        if ( ! NormalWithinArc(next_potential_strike_normal, min_normal_dir, max_normal_dir) ) { break; }\n        ray_status = TracedRay::NStrike;\n\n        // Get here only if there is another reflection on the mirror\n        StrikePts.push_back( next_potential_strike_pt );\n        next_incident_dir = reflect_dir;\n\n        if (loop_count >= loop_limit) {\n            ray_status = TracedRay::NStrikeOut;\n            break;\n        }\n    } // while 1\n\n    // Case 4\n//    ray_status = TracedRay::Unobscured;\n    return reflect_dir;\n}\n\n\nclass TheData { // Please come up with a better name\n    public:\n        // input data\n        double m_radius;\n        double m_sun_dir; // degrees\n        double m_sun_width_ang; // degrees;\n\n        \n// Concave - the following fields are applicable to CONCAVE mirrors only\n               // Limits a portion of the circle (i.e. arc-length)\n        bool m_IsConvex; // true=Convex, false=Concave\n        Point m_MirrorCOCPt; // mirror's center-of-curvature\n        double m_min_normal_dir; // min/max normal directions define the limits of the ARC\n        double m_max_normal_dir;\n\n        Point m_min_normal_pt;\n        Point m_max_normal_pt;\n        Point m_MidArcPt;\n\n        Segment m_screen;\n        std::deque< Segment > m_stencils;\n        std::list<Point> m_target_pts;\n\n// Convex - the following fields are applicable to CONVEX mirrors only - DVO 12/16/2018: why is that a restriction?\n        double m_distance; // from observer to mirror's COC\n\t\tPoint m_ObserverPt;\n\n        // Results (output data)\n        //\n        std::deque<TracedRay> m_TopRays; // indexed in steps from m_min_normal_dir to m_max_normal_dir.\n        std::deque<TracedRay> m_BotRays;\n\n        unsigned m_CountOfObscuredRays; // # of m_TopRays+m_BotRays whose reflected rays are invalid (see TracedRay::m_ray_status)\n\n        std::deque<Point> m_TopIntersectionPts; // (N-1)squared - intersection points of the reflected Top rays\n        std::deque<Point> m_BotIntersectionPts; // (N-1)squared - intersection points of the reflected Bot rays\n\n        BBox m_TopIntersectionBBox; // bounding-box of all m_TopIntersectionPts\n        BBox m_BotIntersectionBBox; // bounding-box of all m_BotIntersectionPts\n\n        double m_reflected_rays_width_ang;\n        double m_reflected_focal_distance;\n        double m_reflected_blur; // a distance across the BBox\n\n\t\t// Tangent (light ray that reaches observer that skims the mirror)\n\t\tdouble m_ObserverTangentAng;  // from observer to tangent point. 0 is horizontal (>0 is up)\n\t\tdouble m_NormalTangentAng; // From center of mirror\n\t\tPoint m_TangentPt; // On mirror\n\n\n\t\tdouble m_ObserverReflectedSunBot; // Sun's bottom\n\t\tdouble m_SunBotAng;\n\t\tPoint m_SunBotMirrorPt;\n\n\t\tdouble m_ObserverReflectedSunMid; // Sun's middle\n\t\tdouble m_SunMidAng;\n\t\tPoint m_SunMidMirrorPt;\n\n\t\tdouble m_ObserverReflectedSunTop;\n\t\tdouble m_SunTopAng;\n\t\tPoint m_SunTopMirrorPt;\n\n\t\tdouble m_Pupil_Entrance; // Experimental: Entrance pupil - the physical separation between the sun's top/bottom rays at the mirror\n\t\tdouble m_Pupil_Exit; // Experimental: Entrance pupil - the physical separation between the sun's top/bottom rays at the mirror\n\t\tdouble m_Brightness;  // Experimental: relative to direct sun's intensity  - uses ratio of pupils (entrance/exit).\n\t\tdouble m_Brightness2;  // Yet another approach\n\n////////////////////////////////////\n\n        TheData() :\n            m_radius(BadValue),\n            m_sun_dir(BadValue),\n            m_sun_width_ang(0.5),\n\n            m_IsConvex(false),\n            m_MirrorCOCPt(),\n            m_min_normal_dir(0),\n            m_max_normal_dir(360),\n            m_min_normal_pt(),\n            m_max_normal_pt(),\n            m_MidArcPt(),\n\n            m_screen(),\n            m_stencils(),\n            m_target_pts(),\n\n            m_distance(BadValue),\n            m_ObserverPt(),\n\n            m_TopRays(),\n            m_BotRays(),\n            m_CountOfObscuredRays(0),\n\n            m_TopIntersectionPts(),\n            m_BotIntersectionPts(),\n            m_TopIntersectionBBox(),\n            m_BotIntersectionBBox(),\n            m_reflected_rays_width_ang(BadValue),\n            m_reflected_focal_distance(BadValue),\n            m_reflected_blur(BadValue),\n\n            m_ObserverTangentAng(BadValue),\n            m_NormalTangentAng(BadValue),\n            m_TangentPt(),\n            m_ObserverReflectedSunBot(BadValue),\n            m_SunBotAng(BadValue),\n            m_SunBotMirrorPt(),\n            m_ObserverReflectedSunMid(BadValue),\n            m_SunMidAng(BadValue),\n            m_SunMidMirrorPt(),\n            m_ObserverReflectedSunTop(BadValue),\n            m_SunTopAng(BadValue),\n            m_SunTopMirrorPt(),\n            m_Pupil_Entrance(BadValue),\n            m_Pupil_Exit(BadValue),\n            m_Brightness(BadValue),\n            m_Brightness2(BadValue)\n                   {};\n\n        void InputDump(FILE *fout=stdout) const;\n\n        bool CheckInputs() const; // return success\n        void Dump(FILE *fout=stdout) const;\n\n        void Calculate(int num_rays, int do_pupil);\n\n        bool GenSVG_Concave(FILE *fout, double offset_X, double offset_Y, const std::string& title, bool first_call=1, bool last_call=1, int animate=0, int animate_interval_ms=250, bool do_boxes=1, bool focal_pts=1) const;\n\t\tbool GenSVG_Convex (FILE *fout, double offset_X, double offset_Y, bool first_call=1, bool last_call=1, int animate=0) const;\n\n        void RayReport(FILE *fout=stdout, unsigned level=0) const;\n\n        double GetValue(const std::string& name) const;\n\n        TheData& operator=(const TheData&other);\n\n        void DuplicateSettings(const TheData&other); // copies other's set-up data, but no the results\n\n    private:\n        void Calculate_Concave(int num_rays, int do_pupil); // forward-trace if num_rays>0, reverse-trace if num_rays==0\n        void Calculate_Convex(int num_rays, int do_pupil);\n\n};\n\nTheData& TheData::operator=(const TheData& other)\n{\n    if (this == &other) return *this;\n\n    m_radius = other.m_radius;\n    m_sun_dir = other.m_sun_dir;\n    m_sun_width_ang = other.m_sun_width_ang;\n\n    m_IsConvex = other.m_IsConvex;\n    m_MirrorCOCPt = other.m_MirrorCOCPt;\n    m_min_normal_dir = other.m_min_normal_dir;\n    m_max_normal_dir = other.m_max_normal_dir;\n    m_min_normal_pt = other.m_min_normal_pt;\n    m_max_normal_pt = other.m_max_normal_pt;\n    m_MidArcPt = other.m_MidArcPt;\n\n    m_screen = other.m_screen;\n    m_stencils = other.m_stencils;\n    m_target_pts = other.m_target_pts;\n\n    m_distance = other.m_distance;\n    m_ObserverPt = other.m_ObserverPt;\n\n    m_TopRays = other.m_TopRays;\n    m_BotRays = other.m_BotRays;\n    m_CountOfObscuredRays = other.m_CountOfObscuredRays;\n\n    m_TopIntersectionPts = other.m_TopIntersectionPts;\n    m_BotIntersectionPts = other.m_BotIntersectionPts;\n    m_TopIntersectionBBox = other.m_TopIntersectionBBox;\n    m_BotIntersectionBBox = other.m_BotIntersectionBBox;\n    m_reflected_rays_width_ang = other.m_reflected_rays_width_ang;\n    m_reflected_focal_distance = other.m_reflected_focal_distance;\n    m_reflected_blur = other.m_reflected_blur;\n\n    m_ObserverTangentAng = other.m_ObserverTangentAng;\n    m_NormalTangentAng = other.m_NormalTangentAng;\n    m_TangentPt = other.m_TangentPt;\n    m_ObserverReflectedSunBot = other.m_ObserverReflectedSunBot;\n    m_SunBotAng = other.m_SunBotAng;\n    m_SunBotMirrorPt = other.m_SunBotMirrorPt;\n    m_ObserverReflectedSunMid = other.m_ObserverReflectedSunMid;\n    m_SunMidAng = other.m_SunMidAng;\n    m_SunMidMirrorPt = other.m_SunMidMirrorPt;\n    m_ObserverReflectedSunTop = other.m_ObserverReflectedSunTop;\n    m_SunTopAng = other.m_SunTopAng;\n    m_SunTopMirrorPt = other.m_SunTopMirrorPt;\n    m_Pupil_Entrance = other.m_Pupil_Entrance;\n    m_Pupil_Exit = other.m_Pupil_Exit;\n    m_Brightness = other.m_Brightness;\n    m_Brightness2 = other.m_Brightness2;\n}\n\nvoid TheData::InputDump(FILE *fout) const\n{\n    fprintf(fout,\"Dump this=%p: Radius=%g, Sun: dir=%g (altitude=%g), Width=%g degrees, Normals=%g,%g degrees, Screen=(%g,%g)..(%g,%g)\\n\",\n                this, m_radius, m_sun_dir, NormalizeAngle(m_sun_dir+180), m_sun_width_ang, m_min_normal_dir, m_max_normal_dir,\n                m_screen.first.x(), m_screen.first.y(), m_screen.second.x(), m_screen.second.y() );\n    if (! m_stencils.empty() ) {\n        fprintf(fout, \"\\tStencils (each line of 4 points):\");\n        int max_index = m_stencils.size()-1;\n        for (int ii=0; ii <= max_index; ii++) {\n            fprintf(fout, \"  (%g,%g)..(%g,%g)\", m_stencils[ii].first.x(), m_stencils[ii].first.y(), m_stencils[ii].second.x(), m_stencils[ii].second.y() );\n        }\n        fprintf(fout, \"\\n\");\n    }\n    if ( !m_target_pts.empty()) {\n        fprintf(fout, \"\\tTarget Points (for reverse tracing): \");\n        for (std::list<Point>::const_iterator it = m_target_pts.begin(); it != m_target_pts.end(); ++it)\n            fprintf(fout, \" (%g,%g)\", it->x(), it->y() );\n        fprintf(fout, \"\\n\");\n    }\n}\n\nvoid TheData::DuplicateSettings(const TheData& other)\n{\n    m_radius = other.m_radius;\n    m_sun_dir = other.m_sun_dir;\n    m_sun_width_ang = other.m_sun_width_ang;\n\n    m_IsConvex = other.m_IsConvex;\n    m_MirrorCOCPt = other.m_MirrorCOCPt;\n    m_min_normal_dir = other.m_min_normal_dir;\n    m_max_normal_dir = other.m_max_normal_dir;\n    m_min_normal_pt = other.m_min_normal_pt;\n    m_max_normal_pt = other.m_max_normal_pt;\n    m_MidArcPt = other.m_MidArcPt;\n\n    m_screen = other.m_screen;\n    m_stencils = other.m_stencils;\n    m_target_pts = other.m_target_pts;\n    m_distance = other.m_distance;\n    m_ObserverPt = other.m_ObserverPt;\n}\n\n\nvoid TheData::Dump(FILE *fout) const\n{\n    InputDump(fout);\n    if (m_IsConvex) { // if Convex\n        fprintf(fout, \"Observer: (%g,%g), ConvexMirror: (%g,%g)\\n\", m_ObserverPt.x(), m_ObserverPt.y(), m_MirrorCOCPt.x(), m_MirrorCOCPt.y() );\n        fprintf(fout, \"Tangent: (%g,%g): Observer Ang=%g, Normal (COC)=%g\\n\", m_TangentPt.x(), m_TangentPt.y(), m_ObserverTangentAng, m_NormalTangentAng );\n        fprintf(fout, \"Sun's Bot: Ang=%g, Observer (to reflection)=%g, Reflection Point=(%g,%g)\\n\", m_SunBotAng, m_ObserverReflectedSunBot, m_SunBotMirrorPt.x(), m_SunBotMirrorPt.y() );\n        fprintf(fout, \"Sun's Mid: Ang=%g, Observer (to reflection)=%g, Reflection Point=(%g,%g)\\n\", m_SunMidAng, m_ObserverReflectedSunMid, m_SunMidMirrorPt.x(), m_SunMidMirrorPt.y() );\n        fprintf(fout, \"Sun's Top: Ang=%g, Observer (to reflection)=%g, Reflection Point=(%g,%g)\\n\", m_SunTopAng, m_ObserverReflectedSunTop, m_SunTopMirrorPt.x(), m_SunTopMirrorPt.y() );\n        fprintf(fout, \"Pupils=%g/%g, Brightness=%g,%g Obsever Angle=%g\\n\", m_Pupil_Entrance, m_Pupil_Exit, m_Brightness, m_Brightness2, m_ObserverReflectedSunTop-m_ObserverReflectedSunBot);\n    } else { // Concave\n        fprintf(fout, \"ConcaveMirror: (%g,%g)\\n\", m_MirrorCOCPt.x(), m_MirrorCOCPt.y() );\n        for (auto it=m_TopRays.begin(); it != m_TopRays.end(); ++it) {\n            fprintf(fout,\"Top: Sun dir=%g, Reflect dir=%g:\", it->m_sun_dir, it->m_reflect_dir);\n            for (auto rr=it->m_StrikePts.begin(); rr != it->m_StrikePts.end(); ++rr)\n                fprintf(fout, \" (%g,%g)\", rr->x(), rr->y() );\n        }\n        for (auto it=m_BotRays.begin(); it != m_BotRays.end(); ++it) {\n            fprintf(fout,\"Bot: Sun dir=%g, Reflect dir=%g:\", it->m_sun_dir, it->m_reflect_dir);\n            for (auto rr=it->m_StrikePts.begin(); rr != it->m_StrikePts.end(); ++rr)\n                fprintf(fout, \" (%g,%g)\", rr->x(), rr->y() );\n        }\n        for (auto it = m_TopIntersectionPts.begin(); it != m_TopIntersectionPts.end(); ++it)\n            fprintf(fout,\"Top: Intersection Point=(%g,%g)\\n\", it->x(), it->y());\n        for (auto it = m_BotIntersectionPts.begin(); it != m_BotIntersectionPts.end(); ++it)\n            fprintf(fout,\"Bot: Intersection Point=(%g,%g)\\n\", it->x(), it->y());\n        fprintf(fout,\"Top bounding Box: (%g,%g)..(%g,%g), Bot bounding Box: (%g,%g)..(%g,%g)\\n\",\n            m_TopIntersectionBBox.MinX(), m_TopIntersectionBBox.MinY(),\n            m_TopIntersectionBBox.MaxX(), m_TopIntersectionBBox.MaxY(),\n            m_BotIntersectionBBox.MinX(), m_BotIntersectionBBox.MinY(),\n            m_BotIntersectionBBox.MaxX(), m_BotIntersectionBBox.MaxY()\n            );\n        fprintf(fout,\"Reflected Rays width angle=%g (deg), focal distance=%g, blur=%g, #obscured rays=%d\\n\",\n            m_reflected_rays_width_ang, m_reflected_focal_distance, m_reflected_blur, m_CountOfObscuredRays );\n    }\n}\n\ndouble TheData::GetValue(const std::string& name) const\n    // DVO HELP - needs to be updated for m_TopRays and m_BotRays.\n{\n    if (name == \"radius\")           return m_radius;\n    if (name == \"distance\")         return m_distance;\n    if (name == \"sun_width\")        return m_sun_width_ang;\n    if (name == \"sun_a\")            return m_sun_dir;\n    if (name == \"sun_A\")            return NormalizeAngle(m_sun_dir+180);\n    if (name == \"ref_width\")        return m_CountOfObscuredRays ? BadValue : NormalizeAngle(m_reflected_rays_width_ang);\n    if (name == \"ref_width_p\")      return m_CountOfObscuredRays ? BadValue : 100 * NormalizeAngle(m_reflected_rays_width_ang) / m_sun_width_ang;\n    if (name == \"ref_focal_d\")      return m_reflected_focal_distance;\n    if (name == \"ref_focal_p\")      return 100 * (m_reflected_focal_distance / (m_radius/2)) ;\n    if (name == \"ref_blur\")         return m_reflected_blur;\n    if (name == \"min_normal\")       return m_min_normal_dir;\n    if (name == \"max_normal\")       return m_max_normal_dir;\n    if (name == \"mirror_width\")     return m_max_normal_dir - m_min_normal_dir;\n\n\tif (name == \"pupil\")\t\t\treturn m_Pupil_Entrance;\n\tif (name == \"pupil1\")\t\t\treturn m_Pupil_Entrance;\n\tif (name == \"pupil2\")\t\t\treturn m_Pupil_Exit;\n\tif (name == \"brightness\")\t\treturn m_Brightness;\n\tif (name == \"brightness2\")\t\treturn m_Brightness2;\n\nfprintf(stderr,\"ERROR: %s(%s): Unrecognized parameter name.\\n\", __func__, name.c_str());\n    return 0;\n}\n\nbool TheData::CheckInputs() const\n{\n    if (m_radius==0) {\n        printf(\"Error: Radius is zero.\\n\");\n        return false;\n    }\n    if (m_radius<0) {\n        printf(\"Error: Radius is negative.\\n\");\n        return false;\n    }\n    // It is ok for the sun altitude and/or width to be zero\n\n    return true;\n}\n\n\n\nint Recursive_ConcaveRaySearch(const Point& MirrorCOCPt, double radius, double min_arc_normal_dir, double max_arc_normal_dir,\n                                const Point& RayTraceStartPt,\n                                double target_sun_dir,\n                                double min_normal_dir, double max_normal_dir,\n                                std::deque<TracedRay> & found_rays,\n                                int nest_level=0,\n                                const int num_steps = 51\n                                )\n/* Performs a search to identify the location on the mirror (MirrorCOCPt, radius min/max_arc_normal_dir) such that a ray starting at RayTraceStartPt\n * is reflected to the sun (target_sun_dir). min/max_normal_dir are within min/max_arc_normal_dir, and are tightened/refined as the search proceeds.\n * Starts by breaking the arc (min_normal_dir..max_normal_dir) into num_steps - and evaluating the reflection at each one. Then we'll pick the\n * two that are on either side and recursive evaluate that sub-region.\n *\n */\n{\n    assert(min_normal_dir != BadValue);\n    assert(max_normal_dir != BadValue);\n    double normals[num_steps];\n    for (int jj=0; jj<num_steps; jj++) {\n        normals[jj] = min_normal_dir + jj * ((max_normal_dir - min_normal_dir) / (num_steps-1));\n    }\n\n\n    int success_count = 0;\n    double found_suns[num_steps];\n    for (int jj=0; jj<num_steps; jj++) {\n        found_suns[jj] = BadValue;\n        TracedRay tr;\n        Point target_pt = Find2ndPoint( MirrorCOCPt, normals[jj], radius ); // target_pt is on the mirror\n        double incident_angle = Direction( RayTraceStartPt, target_pt );\n        double reflect_angle = ConcaveRayCalculate (MirrorCOCPt, radius, min_arc_normal_dir, max_arc_normal_dir,\n                                                    incident_angle, RayTraceStartPt, target_pt, tr.m_StrikePts, tr.m_ray_status);\n        if (tr.m_ray_status >= TracedRay::NStrike) {\n            found_suns[jj] = reflect_angle;\n\n            if ( NearlyEqual( target_sun_dir, found_suns[jj] ) ) {\n                tr.m_sun_dir = NormalizeAngle( found_suns[jj] + 180 );\n                tr.m_MirrorPt = target_pt;\n                tr.m_reflect_dir = NormalizeAngle(incident_angle+180); // We're doing this in reverse - so what we start with as incident is actually the reflected.\n                if ( (jj==0) || (found_suns[jj-1] != BadValue) ) { // Prevents back to back submissions (likely the same ray - within floating-point roundoff)\n                    found_rays.push_back(tr);\n                    success_count++;\n                }\n                found_suns[jj] = BadValue; // So won't be considered again below\n            }\n        }\n    }\n\n\n    for (int jj=1; jj<num_steps; jj++) { // Starts at 1\n        if (\n             ( (found_suns[jj-1] != BadValue) && (found_suns[jj-0] != BadValue)) &&\n            ( ( ( found_suns[jj-1] < target_sun_dir) && (found_suns[jj-0] > target_sun_dir) ) ||\n              ( ( found_suns[jj-1] > target_sun_dir) && (found_suns[jj-0] < target_sun_dir) ) ) &&\n            ( ! NearlyEqual( found_suns[jj-1], found_suns[jj-0] ) ) &&\n            ( ! NearlyEqual( normals[jj-1], normals[jj-0] ) )\n             ) {\n                int result = Recursive_ConcaveRaySearch(MirrorCOCPt,radius,min_arc_normal_dir,max_arc_normal_dir,RayTraceStartPt,target_sun_dir,normals[jj-1],normals[jj-0], found_rays, nest_level+1, num_steps);\n                if (result) {\n                    success_count += result;\n                }\n        } // if\n    } // for\n\n    return success_count;\n}\n\n\n\nvoid TheData::Calculate(int num_rays, int do_pupil)\n{\n    if (m_IsConvex) Calculate_Convex (num_rays, do_pupil);\n    else            Calculate_Concave(num_rays, do_pupil);\n}\n\nvoid TheData::Calculate_Concave(int num_rays, int do_pupil)\n    /* The object a few 'input' parameters, and numerous 'derived' values - that are determined from the\n     * 'input' parameters. This routine determines those derived values.\n     */\n{\n    const int steps = num_rays-1;\n    if (CheckInputs()) {\n        // Parameters of the mirror\n        Set( m_MirrorCOCPt, 0, 0 );\n        double m_mid_normal_dir = (m_max_normal_dir + m_min_normal_dir)/2;\n        m_MidArcPt= Find2ndPoint(Point(0,0), m_mid_normal_dir, m_radius );\n\n        m_min_normal_pt = Find2ndPoint( Point(0,0), m_min_normal_dir, m_radius );\n        m_max_normal_pt = Find2ndPoint( Point(0,0), m_max_normal_dir, m_radius );\n\n        if (num_rays == 0) {    /* Reverse ray-tracing\n                                 * The sun's angle in the sky is an input. Project a ray from stencil back to mirror\n                                 * and then back to sun (and finally extend stencil to mirror segment to reach the\n                                 * screen). Requires successive-approximation (search).\n                                 * 1-Project a ray from a point on the stencil back to a point on the mirror.\n                                 *      (Determine the angle from the stencil to the point. This is the initial\n                                 *      angle - and will be adjusted in this search).\n                                 * 2-The above determines an incident angle. From that, and the mirror's properties,\n                                 *      determine the reflected angle.\n                                 * 3-Adjust if/as necessary depending on whether the reflected-angle is greater than or\n                                 *      less than the known sun-angle.\n                                 */\n            std::list<Point> target_points;\n            for (auto it = m_stencils.begin(); it != m_stencils.end(); ++it) {\n                    target_points.push_back(it->first);\n                    target_points.push_back(it->second);\n            }\n            for (std::list<Point>::const_iterator it = m_target_pts.begin(); it != m_target_pts.end(); ++it) \n                    target_points.push_back( *it );\n            \n            for (int bot_top = 0; bot_top <= 1; bot_top++) { // bot_top=0 for bottom, =1 for top\n                double sun_dir = m_sun_dir + ((bot_top == 0) ? -m_sun_width_ang : m_sun_width_ang)/2;\n                double sun_dir_reversed = NormalizeAngle(sun_dir + 180);\n\n                for (std::list<Point>::const_iterator it = target_points.begin(); it != target_points.end(); ++it) {\n                    const Point &the_point = *it;\n\n                    double sun_m_90 = sun_dir-90;\n                    double sun_p_90 = sun_dir+90;\n\n                    double min_normal_dir = Max( m_min_normal_dir, sun_m_90);\n                    double max_normal_dir = Min( m_max_normal_dir, sun_p_90);\n\n                    std::deque<TracedRay>& tr_deque = bot_top ? m_TopRays : m_BotRays;\n                    int result = Recursive_ConcaveRaySearch(m_MirrorCOCPt, m_radius, m_min_normal_dir, m_max_normal_dir,\n                            the_point,\n                            sun_dir_reversed,\n                            min_normal_dir, max_normal_dir,\n                            tr_deque );\n                } // for points\n            } // for bot_top\n        } else { // forward ray-trace - from Sun to mirror. First identify a target point on the mirror, then calculate the reflection.\n\n            double step_size = (m_max_normal_dir - m_min_normal_dir) / steps;\n\n            for (int step=0; step <= steps; step++) { // steps along points on the mirror\n                // Terminology...\n                // top/bot - refer to whether the incident ray originates at the top (12oc) or bottom (6oc) of the sun\n                //\n                TracedRay tr_top, tr_bot;\n                tr_top.m_sun_dir = m_sun_dir + m_sun_width_ang/2;\n                tr_bot.m_sun_dir = m_sun_dir - m_sun_width_ang/2;\n\n                double normal_dir = m_min_normal_dir + step * step_size;\n                tr_top.m_MirrorPt = tr_bot.m_MirrorPt = Find2ndPoint(Point(0,0), normal_dir, m_radius );\n\n                tr_top.m_reflect_dir = NormalizeAngle(ConcaveRayCalculate(Point(0,0), m_radius, m_min_normal_dir, m_max_normal_dir,\n                                tr_top.m_sun_dir, Point(BadValue,BadValue), tr_top.m_MirrorPt, tr_top.m_StrikePts, tr_top.m_ray_status ));\n                tr_bot.m_reflect_dir = NormalizeAngle(ConcaveRayCalculate(Point(0,0), m_radius, m_min_normal_dir, m_max_normal_dir,\n                                tr_bot.m_sun_dir, Point(BadValue,BadValue), tr_bot.m_MirrorPt, tr_bot.m_StrikePts, tr_bot.m_ray_status ));\n\n                if (tr_top.m_ray_status >= TracedRay::NStrike) m_TopRays.push_back( tr_top );\n                if (tr_bot.m_ray_status >= TracedRay::NStrike) m_BotRays.push_back( tr_bot );\n\n//                m_CountOfObscuredRays += tr_top.CountObscuredRays();\n//                m_CountOfObscuredRays += tr_bot.CountObscuredRays();\n            } // for step\n        } // if else forward ray trace\n\n\n        // An N-squared algorithm (originally, but not much better now) - looking for all intersections of Top\n        // rays (and then again, all intersections of Bot rays)\n        {\n            int outer = 0;\n            std::deque<TracedRay>* traced_rays[] = { &m_TopRays, &m_BotRays };\n            for (int tri = 0; tri < sizeof(traced_rays)/sizeof(traced_rays[0]); tri++) {\n                for (auto it_outer = traced_rays[tri]->begin(); it_outer != traced_rays[tri]->end(); ++it_outer) {\n                    outer++;\n                    if (it_outer->m_ray_status <= TracedRay::Obscured) continue;\n                    int inner = 0;\n                    for (auto it_inner = traced_rays[tri]->begin(); it_inner != traced_rays[tri]->end(); ++it_inner) {\n                        inner++;\n                        if (it_outer == it_inner) break;\n                        if (it_inner->m_ray_status <= TracedRay::Obscured) continue;\n                        Point intersection_pt;\n                        int ok = Intersection( it_outer->m_StrikePts.back(), it_outer->m_reflect_dir,\n                                               it_inner->m_StrikePts.back(), it_inner->m_reflect_dir,\n                                               intersection_pt);\n\n                        // There can be three situations:\n                        // 1) Unobscured - if so, then don't worry about where intersection point is\n                        // 2) Initially NStrike - but intersection is beyond the mirror surface - so the intersection point is NOT valid\n                        // 3) Initially NStrike - but intersection is before the mirror surface - so the intersection point is valid\n\n\n                        if (ok) {\n                            assert(Defined(it_outer->m_StrikePts.back()));\n                            assert(Defined(it_inner->m_StrikePts.back()));\n                            double outer_reflctPtToIntrsct_dis  = Distance( it_outer->m_StrikePts.back(), intersection_pt );\n                            double inner_reflctPtToIntrsct_dis  = Distance( it_inner->m_StrikePts.back(), intersection_pt );\n\n                            if (tri == 0) { // This is an ugly hack\n                                m_TopIntersectionBBox.Update( intersection_pt );\n                                m_TopIntersectionPts.push_back( intersection_pt );\n                            } else {\n                                m_BotIntersectionBBox.Update( intersection_pt );\n                                m_BotIntersectionPts.push_back( intersection_pt );\n                            }\n                        }\n                    } // for it_inner\n                } // for it_outer\n            }\n        }\n\n        if ( m_TopIntersectionBBox.Defined() && m_BotIntersectionBBox.Defined() ) { // reflected rays 'blur' width angle\n            // using the middle points of the bounding boxes as the intersection points - this is first implementation - there may be a better way\n            Point top_intersection( m_TopIntersectionBBox.MidX(), m_TopIntersectionBBox.MidY() );\n            Point bot_intersection( m_BotIntersectionBBox.MidX(), m_BotIntersectionBBox.MidY() );\n\n\n            double dir1 = to_degrees( atan2( top_intersection.y()-m_MidArcPt.y(), top_intersection.x()-m_MidArcPt.x() ));\n            double dir2 = to_degrees( atan2( bot_intersection.y()-m_MidArcPt.y(), bot_intersection.x()-m_MidArcPt.x() ));\n            m_reflected_rays_width_ang = fabs(dir1-dir2);\n\n            assert( Defined(m_MidArcPt) );\n            assert( Defined(top_intersection) );\n            assert( Defined(bot_intersection) );\n            double distance1 = Distance( m_MidArcPt, top_intersection );\n            double distance2 = Distance( m_MidArcPt, bot_intersection );\n            m_reflected_focal_distance = (distance1 + distance2)/2;\n\n            double blur1 = m_TopIntersectionBBox.Diagonal();\n            double blur2 = m_BotIntersectionBBox.Diagonal();\n            m_reflected_blur = (blur1 + blur2)/2;\n        }\n\n        if (0) { // experimental - bounding ellipse\n            // https://stackoverflow.com/questions/1768197/bounding-ellipse\n            for (int  tri=0; tri<=1; tri++) {\n                std::deque<Point> &IntersectionPts = /* ugly hack continued */ (tri == 0) ? m_TopIntersectionPts : m_BotIntersectionPts;\n            }\n        }\n\n    } // if CheckPoint()\n}\n\n\nclass CoordConverter\n{\n    public:\n\n        void DefineFrom(double x_bot_left, double y_bot_left, double x_top_right, double y_top_right);\n        void DefineTo  (double x_bot_left, double y_bot_left, double x_top_right, double y_top_right);\n        double X(double from_X) const;\n        double Y(double from_X) const;\n        double Scale() const;\n\n        CoordConverter() :  m_X_bot_left_from(0), m_Y_bot_left_from(0), m_X_top_right_from(0), m_Y_top_right_from(0),\n                    m_X_bot_left_to(0), m_Y_bot_left_to(0), m_X_top_right_to(0), m_Y_top_right_to(0),\n                        m_cache_is_stale(1), m_X_scale(1), m_Y_scale(1) {};\n\n        void Dump(FILE* fout=stdout) const;\n\n        static int Test();\n    private:\n        void CacheCalc() const;\n        double m_X_bot_left_from, m_Y_bot_left_from, m_X_top_right_from, m_Y_top_right_from;\n        double m_X_bot_left_to, m_Y_bot_left_to, m_X_top_right_to, m_Y_top_right_to;\n\n        mutable bool m_cache_is_stale;\n        mutable double m_X_scale, m_Y_scale;\n};\n\nvoid CoordConverter::Dump(FILE *fout) const\n{\n    fprintf(fout, \"Dump() of CoordConverter this=%p\\n\", this);\n    fprintf(fout, \"\\tFrom: bottomLeft=(%g,%g), topRight=(%g,%g)\\n\", m_X_bot_left_from, m_Y_bot_left_from, m_X_top_right_from, m_Y_top_right_from );\n    fprintf(fout, \"\\t  To: bottomLeft=(%g,%g), topRight=(%g,%g)\\n\", m_X_bot_left_to, m_Y_bot_left_to, m_X_top_right_to, m_Y_top_right_to );\n    fprintf(fout, \"\\tScale=(%g,%g): m_cache_is_stale=%d\\n\", m_X_scale, m_Y_scale, m_cache_is_stale );\n\n}\n\nint CoordConverter::Test()\n{\n    int test_count = 0;\n    int fail_count = 0;\n    { // Defines an identity mapping\n        CoordConverter cc;\n        cc.DefineFrom(0,0, 100,100);\n        cc.DefineTo  (0,0, 100,100);\n        const static double test_points[] = { // A 1-dimensional array - but treating as pairs of X,Y coordinates.\n            0,0,    1,1,    0,1,    1,0,    2,2,    2,0,    0,2,    0,100,    100,100,    100,0,    51,49 };\n        for (int ii=0; ii<sizeof(test_points)/sizeof(test_points[0]); ii+=2) {\n            double x = test_points[ii];\n            double y = test_points[ii+1];\n            if ( (!NearlyEqual(x, cc.X(x) )) || !NearlyEqual(y,cc.Y(y))) {\n                printf(\"Test failure: (%g,%g) != (%g,%g) at %d of %s\\n\", x,y, cc.X(x), cc.Y(y), __LINE__, __FILE__);\n                fail_count++;\n            }\n            test_count++;\n        }\n    }\n\n    { // Scaling only\n        CoordConverter cc;\n        cc.DefineFrom(-100,-100, 100,100);\n        cc.DefineTo  (-1,-1, 1,1);\n        const static double test_points[] = { // A 1-dimensional array - but treating as pairs of X,Y coordinates.\n            0,0,    1,1,    0,1,    1,0,    2,2,    2,0,    0,2,    0,100,    100,100,    100,0,    51,49 };\n        for (int ii=0; ii<sizeof(test_points)/sizeof(test_points[0]); ii+=2) {\n            double x = test_points[ii];\n            double y = test_points[ii+1];\n            if ( (! NearlyEqual(x/100, cc.X(x) )) || !NearlyEqual(y/100,cc.Y(y)) ) {\n                printf(\"Test failure: (%g,%g) != (%g,%g) at %d of %s\\n\", x,y, cc.X(x), cc.Y(y), __LINE__, __FILE__);\n                fail_count++;\n            }\n            test_count++;\n        }\n    }\n\n    { // Offset only\n        CoordConverter cc;\n        cc.DefineFrom(-100,-100, 100,100);\n        cc.DefineTo  (0,0, 200,200);\n        const static double test_points[] = { // A 1-dimensional array - but treating as pairs of X,Y coordinates.\n            0,0,    1,1,    0,1,    1,0,    2,2,    2,0,    0,2,    0,100,    100,100,    100,0,    51,49 };\n        for (int ii=0; ii<sizeof(test_points)/sizeof(test_points[0]); ii+=2) {\n            double x = test_points[ii];\n            double y = test_points[ii+1];\n            if ( (! NearlyEqual(x+100, cc.X(x) )) || !NearlyEqual(y+100,cc.Y(y)) ) {\n                printf(\"Test failure: (%g,%g) != (%g,%g) at %d of %s\\n\", x,y, cc.X(x), cc.Y(y), __LINE__, __FILE__);\n                fail_count++;\n            }\n            test_count++;\n        }\n    }\n\n    { // Inversion top-to-bottom only\n        CoordConverter cc;\n        cc.DefineFrom(-100,-100, 100, 100);\n        cc.DefineTo  (-100, 100, 100,-100);\n        const static double test_points[] = { // A 1-dimensional array - but treating as pairs of X,Y coordinates.\n            0,0,    1,1,    0,1,    1,0,    2,2,    2,0,    0,2,    0,100,    100,100,    100,0,    51,49 };\n        for (int ii=0; ii<sizeof(test_points)/sizeof(test_points[0]); ii+=2) {\n            double x = test_points[ii];\n            double y = test_points[ii+1];\n            if ( (! NearlyEqual(x, cc.X(x) )) || !NearlyEqual(-1*y,cc.Y(y)) ) {\n                printf(\"Test failure: (%g,%g) != (%g,%g) at %d of %s\\n\", x,y, cc.X(x), cc.Y(y), __LINE__, __FILE__);\n                fail_count++;\n            }\n            test_count++;\n        }\n    }\n\n    { // Explicit mapping\n        CoordConverter cc;\n        cc.DefineFrom(-3, 0, 3, 6);\n        cc.DefineTo  (0, 800, 800, 0);\n        const static double test_points[] = { // A 1-dimensional array - but treating as pairs of X,Y coordinates.\n            -3,6,    3,6,     3,0,        -3,0,    0,3,        0,0        };     \n        const static double expect_points[] = { // Matches (after coordinate-conversion) the test_points[] array\n            0,0,    800,0,    800,800,    0,800,    400,400,    400,800        };\n        for (int ii=0; ii<sizeof(test_points)/sizeof(test_points[0]); ii+=2) {\n            double x_f = test_points[ii];\n            double y_f = test_points[ii+1];\n            double x_t = expect_points[ii];\n            double y_t = expect_points[ii+1];\n\n            if ( (! NearlyEqual(x_t, cc.X(x_f) )) || !NearlyEqual(y_t,cc.Y(y_f)) ) {\n                printf(\"Test failure: (%g,%g) != (%g,%g) - was (%g,%g) ii=%d at %d of %s\\n\", x_f,y_f, x_t,y_t, cc.X(x_f), cc.Y(y_f), ii, __LINE__, __FILE__);\n                fail_count++;\n            }\n            test_count++;\n        }\n    }\n\n    { // Angles\n        const static double test_data[] = { // 5 values per test-point: X,Y of pt1, X,Y of pt2 and expected Angle\n             0, 0,     0, 0,      0.0,\n\n             0, 0,     1, 0,      0.0,\n             0, 0,    -1, 0,    180.0,\n             0, 0,     0, 1,     90.0,\n             0, 0,     0,-1,    -90.0,\n             0, 0,     1, 1,     45.0,\n             0, 0,    -1, 1,    135.0,\n             0, 0,     1,-1,    -45.0,\n             0, 0,    -1,-1, -135.0,\n\n             1, 0,     0, 0,    180.0,\n            -1, 0,     0, 0,      0.0,\n             0, 1,     0, 0,    -90.0,\n             0,-1,     0, 0,     90.0,\n             1, 1,     0, 0, -135.0,\n             1,-1,     0, 0,    135.0,\n            -1, 1,     0, 0,  -45.0,\n            -1,-1,     0, 0,     45.0\n        };\n        for (int ii=0; ii<sizeof(test_data)/sizeof(test_data[0]); ii+=5) {\n            double result = Direction( Point(test_data[ii+0], test_data[ii+1]), Point(test_data[ii+2], test_data[ii+3]) );\n            double result_normalize = NormalizeAngle( result );\n            double expected_normalize = NormalizeAngle( test_data[ii+4] );\n            if ( ! NearlyEqual(result_normalize, expected_normalize) ) { \n                printf(\"Test failure: Direction( %g,%g, %g,%g )=%g - expecting %g (ii=%d at %d of %s)\\n\",\n                        test_data[ii+0], test_data[ii+1], test_data[ii+2], test_data[ii+3],\n                        result_normalize, expected_normalize,\n                        ii, __LINE__, __FILE__ );\n                fail_count++;\n            }\n            test_count++;\n        }\n    }\n\n    { // RayStrikeConcave\n        double test_points[] = { // 3 values per test-point - the incident ray, the normal and the expected result (1 or 0)\n              0,  0,     1,    // The normal is always from inside\n              1,  1,     1,    // The normal is always from inside\n             45, 45,     1,    // The normal is always from inside\n             89, 89,    1,\n             90, 90,    1,\n             91, 91,    1,\n             89, 90,    1,\n             89, 91,    1,\n             91, 89,    1,\n             91, 90,    1,\n            179,179,    1,\n            180,180,    1,\n            181,181,    1,\n            269,269,    1,\n            270,270,    1,\n            271,271,    1,\n            359,359,    1,\n            360,360,    1,    // 360 should get normalized to 0\n            361,361,    1,    // 360 should get normalized to 0\n\n              0,  0+89,    1,\n              0,  0-89,    1,\n             90, 90-89,    1,\n             90, 90-89,    1,\n            180,180+89,    1,\n            180,180-89,    1,\n            270,270+89,    1,\n            270,270-89,    1,\n            359,359+89,    1,\n            359,359-89,    1,\n\n              0,  0+91,    0,\n              0,  0-91,    0,\n             90, 90-91,    0,\n             90, 90-91,    0,\n            180,180+91,    0,\n            180,180-91,    0,\n            270,270+91,    0,\n            270,270-91,    0,\n            359,359+91,    0,\n            359,359-91,    0,\n\n              0,  0+180,    0,\n              0,  0-180,    0,\n             90, 90-180,    0,\n             90, 90-180,    0,\n            180,180+180,    0,\n            180,180-180,    0,\n            270,270+180,    0,\n            270,270-180,    0,\n            359,359+180,    0,\n            359,359-180,    0,\n\n              0,  0+269,    0,\n              0,  0-269,    0,\n             90, 90-269,    0,\n             90, 90-269,    0,\n            180,180+269,    0,\n            180,180-269,    0,\n            270,270+269,    0,\n            270,270-269,    0,\n            359,359+269,    0,\n            359,359-269,    0,\n\n        };\n        for (int ii=0; ii<sizeof(test_points)/sizeof(test_points[0]); ii+=3) {\n            double result = RayStrikeConcave( test_points[ii+0], test_points[ii+1] );\n            if (result != test_points[ii+2]) {\n                printf(\"Test failure: RayStrikeConcave(%g,%g)=%g, expected %g. ii=%d at %d of %s\\n\",\n                        test_points[ii+0], test_points[ii+1], result, test_points[ii+2],\n                        ii, __LINE__, __FILE__ );\n                fail_count++;\n                }\n            test_count++;\n        }\n    }\n\n    { // Intersection - point-dir\n        static const double test_points[] = { // 9 values per test-point - pt1, dir1, pt2, dir2, pass/fail, intersection pt (each pt has 2 values)\n            // pt1     dir1        pt2     dir2          p/f    intersect pt  \n            1,   2,     0,       1,    2,    270,        1,        1,   2,\n            1,   2,    13,       1,    2,     57,        1,        1,   2,\n\n            0,   0,     0,       1,    1,    270,        1,        1,   0,\n            0,   0,     0,       1,    1,      0,        0,        0,   0,\n            0,   0,     0,       1,    1,    180,        0,        0,   0,\n            0,   0,    90,       1,    1,    180,        1,        0,   1,\n\n            1,   2,    45,       0,    2,      0,        1,        1,   2,\n            1,   2,    45,       0,    4,      0,        1,        3,   4,\n            1,   2,    45,       1,    4,    -45,        1,        2,   3,\n\n        };\n\n        for (int ii=0; ii<sizeof(test_points)/sizeof(test_points[0]); ii+=9) {\n            Point pt1(test_points[ii+0],test_points[ii+1]);\n            double dir1 = test_points[ii+2];\n            Point pt2(test_points[ii+3],test_points[ii+4]);\n            double dir2 = test_points[ii+5];\n            Point intersection_pt;\n            bool result = Intersection( pt1, dir1, pt2, dir2, intersection_pt);\n\n            if (result != test_points[ii+6]) {\n                printf(\"Test failure: Intersection( (%g,%g), %g, (%g,%g), %g, ...)=%d, expected %g. ii=%d at %d of %s\\n\",\n                        pt1.x(), pt1.y(), dir1,\n                        pt2.x(), pt2.y(), dir2,\n                        result, test_points[ii+6],\n                        ii, __LINE__, __FILE__ );\n                fail_count++;\n            }\n            test_count++;\n\n            if (result && (test_points[ii+6] != 0)) {\n                Point expected_pt(test_points[ii+7], test_points[ii+8]);\n                if ( ! NearlyEqual( expected_pt, intersection_pt ) ) {\n                    printf(\"Test failure: Intersection( (%g,%g), %g, (%g,%g), %g, ...)=%d, intersection: (%g,%g) != (%g,%g) ii=%d at %d of %s\\n\",\n                            pt1.x(), pt1.y(), dir1,\n                            pt2.x(), pt2.y(), dir2,\n                            result,\n                            intersection_pt.x(), intersection_pt.y(), expected_pt.x(), expected_pt.y(),\n                            ii, __LINE__, __FILE__ );\n                    fail_count++;\n                }\n                test_count++;\n            }\n        }\n    }\n\n    { // Indent()\n        static const int test_points[] = { // In sets of 3: 1st and 2nd are arguments to Indent(), 3rd is the expected results of strlen(Indent())\n            0,1,0*1,        1,1,1*1,        2,1,2*1,        40,1,40*1,\n            0,2,0*2,        1,2,1*2,        2,2,2*2,        40,2,40*2,\n            0,4,0*4,        1,4,1*4,        2,4,2*4,        40,4,40*4,\n        };\n\n        for (int ii=0; ii<sizeof(test_points)/sizeof(test_points[0]); ii+=3) {\n            const char* result = Indent( test_points[ii+0], test_points[ii+1] );\n            unsigned length = strlen(result);\n            if (length != test_points[ii+2]) {\n                printf(\"Test failure: Indent(%d,%d)=>%s<= length=%d, expected length=%d, ii=%d at %d of %s\\n\",\n                        test_points[ii+0], test_points[ii+1], result, length, test_points[ii+2],\n                        ii, __LINE__, __FILE__ );\n                fail_count++;\n            }\n            test_count++;\n        }\n    }\n\n    if (1) {\n            //double ApparentWidth( const Point&p1, const Point&p2, double from_this_angle)\n            const double sqrt2 = sqrt(2.0);\n            const double sin30 = sin( to_radians(30) );\n            const double cos30 = cos( to_radians(30) );\n            static const double test_points[] = { // In sets of 6: x,y for each of 2 points, the observer's angle, and the expected result.\n                0,0,     10,0,    270,   10,           // I.e. X1,Y1, X2,Y2, angle, expected result. Observing horizontal line from top.\n                0,0,     10,0,    225,   10/sqrt2,    //  Same line from 45 degrees.\n                0,0,     10,0,    180,   10*0,        //  Same line edge on.\n\n                0,10,    10,0,    270,   10*sqrt2/sqrt2,  // Length of lines is 10*1.414 - but for-shortened when viewed from above.\n                0,10,    10,0,    225,   10*sqrt2,        // \n                0,10,    10,0,    180,   10*sqrt2/sqrt2,  //\n\n                -10,-10, 25,-10,  0,     30*0, \n                -10,-10, 25,-10,  30,    35*sin30, \n                -10,-10, 25,-10,  60,    35*cos30, \n                -10,-10, 25,-10,  90,    35*1, \n                -10,-10, 25,-10,  120,   35*cos30, \n                -10,-10, 25,-10,  150,   35*sin30, \n                -10,-10, 25,-10,  180,   35*0, \n                -10,-10, 25,-10,  210,   35*sin30, \n                -10,-10, 25,-10,  240,   35*cos30, \n                -10,-10, 25,-10,  270,   35*1, \n                -10,-10, 25,-10,  300,   35*cos30, \n                -10,-10, 25,-10,  330,   35*sin30, \n                -10,-10, 25,-10,  360,   35*0, \n            };\n\n        for (int ii=0; ii<sizeof(test_points)/sizeof(test_points[0]); ii+=6) {\n            const Point pt1(test_points[ii+0], test_points[ii+1] );\n            const Point pt2(test_points[ii+2], test_points[ii+3] );\n            const double angle = test_points[ii+4];\n            const double expected_value = test_points[ii+5];\n            const double result = ApparentWidth( pt1, pt2, angle );\n            if ( ! NearlyEqual( result, expected_value ) ) {\n                    printf(\"Test failure: ApparentWidth( (%g,%g), (%g,%g), %g)=%g expecting=%g ii=%d at %d of %s\\n\",\n                            pt1.x(), pt1.y(),\n                            pt2.x(), pt2.y(),\n                            angle,\n                            result, expected_value,\n                            ii, __LINE__, __FILE__ );\n                    fail_count++;\n                }\n                test_count++;\n            }\n        }\n\n    if (1) {\n            //double ApparentWidth_ang( const Point&p1, const Point&p2, const Point& observer)\n            // angular width (in degrees) of a line from p1 to p2 as seen from observer\n            static const double test_points[] = { // In sets of 8: line#, x,y for each of 3 points, and the expected result.\n__LINE__,                0,0,     10,0,    5,5,  90,\n__LINE__,                0,0,     10,0,    100,0,  0,\n\n__LINE__,                -100,0,  0,-100,   0,0,  90,\n__LINE__,                -100,0,  0,+100,   0,0,  90,\n__LINE__,                +100,0,  0,+100,   0,0,  90,\n__LINE__,                +100,0,  0,-100,   0,0,  90,\n\n__LINE__,                -2,0,   0,-100,     0,0, 90,\n\n__LINE__,                10,10,  10,0,       0,0, 45,\n__LINE__,                10,0,   10,10,      0,0, 45,\n\n__LINE__,                110,110, 110,100,   100,100, 45,\n__LINE__,                110,100, 110,110,   100,100, 45,\n\n__LINE__,                10,0,   10, 0,      0,0, to_degrees(atan2( 0.0,10)),\n__LINE__,                10,0,   10, 9,      0,0, to_degrees(atan2( 9.0,10)),\n__LINE__,                10,0,   10,10,      0,0, to_degrees(atan2(10.0,10)),\n__LINE__,                10,0,   10,11,      0,0, to_degrees(atan2(11.0,10)),\n__LINE__,                10,0,   10,20,      0,0, to_degrees(atan2(20.0,10)),\n__LINE__,                10,0,   10,30,      0,0, to_degrees(atan2(30.0,10)),\n__LINE__,                10,0,   10,40,      0,0, to_degrees(atan2(40.0,10)),\n__LINE__,                10,0,   10,50,      0,0, to_degrees(atan2(50.0,10)),\n__LINE__,                10,0,   10,60,      0,0, to_degrees(atan2(60.0,10)),\n__LINE__,                10,0,   10,70,      0,0, to_degrees(atan2(70.0,10)),\n__LINE__,                10,0,   10,80,      0,0, to_degrees(atan2(80.0,10)),\n__LINE__,                10,0,   10,90,      0,0, to_degrees(atan2(90.0,10)),\n__LINE__,                10,0,   10,99,      0,0, to_degrees(atan2(99.0,10)),\n\n            };\n\n        for (int ii=0; ii<sizeof(test_points)/sizeof(test_points[0]); ii+=8) {\n            const double line = test_points[ii+0];\n            const Point         pt1(test_points[ii+1], test_points[ii+2] );\n            const Point         pt2(test_points[ii+3], test_points[ii+4] );\n            const Point observer_pt(test_points[ii+5], test_points[ii+6] );\n            const double expected_value = test_points[ii+7];\n            const double result = ApparentWidth_ang( pt1, pt2, observer_pt );\n            if ( ! NearlyEqual( result, expected_value ) ) {\n                    printf(\"Test failure: ApparentWidth_ang( (%g,%g), (%g,%g), (%g,%g) )=%g expecting=%g ii=%d at %g of %s\\n\",\n                            pt1.x(), pt1.y(),\n                            pt2.x(), pt2.y(),\n                            observer_pt.x(), observer_pt.y(),\n                            result, expected_value,\n                            ii, line, __FILE__ );\n                    fail_count++;\n                }\n                test_count++;\n            }\n        }\n\n\n\n\n    if (fail_count)\n        printf(\"%s(): FAILED %d of %d test-steps.\\n\", __func__, fail_count, test_count );\n    else\n        printf(\"%s(): PASSED all %d test-steps.\\n\", __func__, test_count );\n\n    return fail_count;\n}\n\n\nvoid CoordConverter::CacheCalc() const\n{\n    if (m_cache_is_stale) {\n        m_X_scale = (m_X_top_right_to - m_X_bot_left_to) / (m_X_top_right_from - m_X_bot_left_from);\n        m_Y_scale = (m_Y_top_right_to - m_Y_bot_left_to) / (m_Y_top_right_from - m_Y_bot_left_from);\n\n        m_cache_is_stale = 0;\n    }\n}\n\nvoid CoordConverter::DefineFrom(double x_bot_left, double y_bot_left, double x_top_right, double y_top_right)\n{\n    m_X_bot_left_from = x_bot_left;\n           m_Y_bot_left_from = y_bot_left;\n    m_X_top_right_from = x_top_right;\n    m_Y_top_right_from = y_top_right;\n    m_cache_is_stale = 1;\n}\n\nvoid CoordConverter::DefineTo(double x_bot_left, double y_bot_left, double x_top_right, double y_top_right)\n{\n    m_X_bot_left_to = x_bot_left;\n           m_Y_bot_left_to = y_bot_left;\n    m_X_top_right_to = x_top_right;\n    m_Y_top_right_to = y_top_right;\n    m_cache_is_stale = 1;\n}\n\n\ndouble CoordConverter::X(double from_X) const\n{\n    CacheCalc();\n    return (from_X - m_X_bot_left_from) * m_X_scale + m_X_bot_left_to;\n}\ndouble CoordConverter::Y(double from_Y) const\n{\n    CacheCalc();\n    return (from_Y - m_Y_bot_left_from) * m_Y_scale + m_Y_bot_left_to;\n}\ndouble CoordConverter::Scale() const\n{\n    CacheCalc();\n    double f1 = fabs(m_X_scale);\n    double f2 = fabs(m_Y_scale);\n    return (f1>f2) ? f1 : f2;\n}\n\n\nvoid Calc_far_point( const Point& FromThisPt, double InThisDirection, Point &far_pt, double border_left, double border_top, double border_right)\n{\n    double normalized_ray = NormalizeAngle(InThisDirection);\n    // Where should the ray end? at one of the borders - or at the  screen\n    if ((normalized_ray > 90) && (normalized_ray < 270)) { // Check for intersection with left border\n        far_pt.x( border_left );\n        far_pt.y( FromThisPt.y() - tan( to_radians( normalized_ray ) ) * (FromThisPt.x() - border_left) );\n        if (far_pt.y() > border_top) {\n            far_pt.y( border_top );\n            far_pt.x( FromThisPt.x() + (far_pt.y() - FromThisPt.y())/tan( to_radians(normalized_ray) ) );\n        }\n    } else if ((normalized_ray < 90) || (normalized_ray > 270)) { // Check for intersection with right border - DVO HELP - can this be combined with above if <90 ?\n        far_pt.x( border_right );\n        far_pt.y( FromThisPt.y() + tan( to_radians( normalized_ray ) ) * (border_right - FromThisPt.x()) );\n        if (far_pt.x() > border_right) {\n            far_pt.y( border_top );\n            far_pt.x( FromThisPt.x() - (border_top-FromThisPt.y())/tan( to_radians(normalized_ray) ) );\n        }\n    } else { // else must be vertical exactly 90 or 270 degrees\n        far_pt.x( FromThisPt.x() );\n        far_pt.y( border_top );\n    }\n}\n\n\nvoid TheData::RayReport(FILE *fout, unsigned level) const\n{\n    if (! m_TopRays.empty() ) {\n        printf(\"%sTop Rays:\\n\", Indent(level));\n        for (auto it = m_TopRays.begin(); it != m_TopRays.end(); ++it) {\n            it->RayReport(fout, level+1);\n        }\n    }\n    if (! m_BotRays.empty() ) {\n        printf(\"%sBot Rays:\\n\", Indent(level));\n        for (auto it = m_BotRays.begin(); it != m_BotRays.end(); ++it) {\n            it->RayReport(fout, level+1);\n        }\n    }\n}\n\nbool TheData::GenSVG_Concave(FILE *fout, double offset_X, double offset_Y, const std::string& title, bool first_call, bool last_call, int animate, int animate_interval_ms, bool do_boxes, bool focal_pts) const\n{\n    // Intend for a 10% margin/borders.\n    // As always with SVG, increasing X is to the right, and increase Y is DOWN the screen.\n    // So we typically invert (*-1) the Y coordinates from our optics modelling to match the SVG model.\n    // Relocate the origin to be the center of the mirror - and place this at the center of the viewport\n    const double border_proportion = 0.10;\n    const double canvas_size = 800;\n    const double line_width = 1; // Thinest\n    const double mirror_line_width = 0.5;\n\n    const double something = 32;\n    const double border_size = 1*something * border_proportion;\n\n    double from_top_border   =  1*something;\n    double from_bottom_border= -1*something;\n    double from_left_border  = -1*something;\n    double from_right_border =  1*something;\n    CoordConverter cc;\n    cc.DefineFrom( offset_X+from_left_border  - border_size, offset_Y+from_bottom_border - border_size,\n                   offset_X+from_right_border + border_size, offset_Y+from_top_border    + border_size);\n    cc.DefineTo  (0, 800, 800, 0);\n\n    const std::deque<TracedRay>* traced_rays[] = { &m_TopRays, &m_BotRays };\n\n    if (first_call) {\n        fprintf(fout, \"<?xml version=\\\"1.0\\\" standalone=\\\"yes\\\"?>\\n\");\n        fprintf(fout, \"<!DOCTYPE svg PUBLIC \\\"-//W3C//DTD SVG 1.1//EN\\\" \\\"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\\\">\\n\");\n        fprintf(fout, \"<svg xmlns=\\\"http://www.w3.org/2000/svg\\\" xmlns:xlink=\\\"http://www.w3.org/1999/xlink\\\" \");\n        fprintf(fout, \"width=\\\"%g\\\" height=\\\"%g\\\" id=\\\"svg\\\" viewBox=\\\"%g %g %g %g\\\">\\n\",\n            canvas_size, canvas_size,\n            0.0,0.0, canvas_size, canvas_size\n            );\n\n        if (1) { // Use inline CSS?\n            fprintf(fout, \"<defs>\\n\");\n            fprintf(fout, \"<style type=\\\"text/css\\\"><![CDATA[\\n\");\n\n            fprintf(fout, \"path{ shape-rendering : crispEdges; }\\n\");\n\n            // For the sun's ray-tracing: T=top, B=bottom. Reflected=both start and end points are on mirror.\n            fprintf(fout, \".ray_incidentT  { stroke-linecap: round; stroke: red; }\\n\" );\n            fprintf(fout, \".ray_reflectedT { stroke-linecap: round; stroke: pink; }\\n\" );\n            fprintf(fout, \".ray_finalT     { stroke-linecap: round; stroke: blue; }\\n\" );\n            fprintf(fout, \".ray_incidentB  { stroke-linecap: round; stroke: orange; }\\n\" );\n            fprintf(fout, \".ray_reflectedB { stroke-linecap: round; stroke: purple; }\\n\" );\n            fprintf(fout, \".ray_finalB     { stroke-linecap: round; stroke: green; }\\n\" );\n\n            fprintf(fout, \".bboxT          { stroke-width: 0.5; stroke: red; fill: none; }\\n\" );\n            fprintf(fout, \".bboxB          { stroke-width: 0.5; stroke: orange; fill: none; }\\n\" );\n            fprintf(fout, \".intersectT     { stroke-width: 0.5; stroke: red; fill: none; }\\n\" );\n            fprintf(fout, \".intersectB     { stroke-width: 0.5; stroke: orange; fill: none; }\\n\" );\n\n            fprintf(fout, \".debug          { stroke-width: 0.25; stroke: black; }\\n\" );\n            fprintf(fout, \".debug_1        { stroke-width: 0.5; stroke: red; }\\n\" );\n            fprintf(fout, \".debug_2        { stroke-width: 0.5; stroke: red; }\\n\" );\n\n\n            int ray_index = 0;\n            for (int tri=0; tri<sizeof(traced_rays)/sizeof(traced_rays[0]); tri++) {\n                for (auto it = traced_rays[tri]->begin(); it != traced_rays[tri]->end(); ++it) {\n                    ray_index++;\n                    fprintf(fout, \".ray_%d { stroke-width: 0.5; }\\n\", ray_index );\n                }\n            }\n\n            fprintf(fout, \"]]></style>\\n\");\n\n            fprintf(fout, \"</defs>\\n\");\n\n        } // inline CSS\n    } // first_call\n\n    if ( ! debug_segments.empty() ) {\n        int ii=0;\n        for (auto it = debug_segments.begin(); it != debug_segments.end(); ++it) {\n            ii++;\n            fprintf(fout, \"<line x1=\\\"%g\\\" y1=\\\"%g\\\" x2=\\\"%g\\\" y2=\\\"%g\\\" class=\\\"debug debug_%d\\\"/>\\n\",\n                cc.X(it->first.x()), cc.Y(it->first.y()), cc.X(it->second.x()), cc.Y(it->second.y()), ii);\n        } // for\n    }\n\n    const char* RayType = \"TBabcdefghijklmnopqrstuvwxyz\";\n    if(!animate || first_call) {\n        // Mirror's Center cross-marks\n        fprintf(fout, \"<line x1=\\\"%g\\\" y1=\\\"%g\\\" x2=\\\"%g\\\" y2=\\\"%g\\\" style=\\\"stroke-width: 0.5; stroke: #888888;\\\"/>\\n\",\n            cc.X(0-m_radius/10), cc.Y(0), cc.X(0+m_radius/10), cc.Y(0) );\n        fprintf(fout, \"<line x1=\\\"%g\\\" y1=\\\"%g\\\" x2=\\\"%g\\\" y2=\\\"%g\\\" style=\\\"stroke-width: 0.5; stroke: #888888;\\\"/>\\n\",\n            cc.X(0), cc.Y(0-m_radius/10), cc.X(0), cc.Y(0+m_radius/10) );\n\n        // Mirror - show full circle as a dashed line\n        fprintf(fout, \"<circle cx=\\\"%g\\\" cy=\\\"%g\\\" r=\\\"%g\\\" stroke-dasharray=\\\"2, 5\\\" style=\\\"stroke-width: %g; stroke: grey; fill: none;\\\"/>\\n\",\n            cc.X(0), cc.Y(0), m_radius*cc.Scale(), mirror_line_width);\n\n        // arc - show as two overlapping arcs - a thicker one (darker) and a lighter/thinner one to indicae the reflective surface.\n        fprintf(fout, \"<path d=\\\"M%g,%g A %g %g  0 %d 0 %g %g\\\" style=\\\"stroke-width: 2; stroke: grey; fill: none;\\\"/>\\n\",\n            cc.X(m_min_normal_pt.x()), cc.Y(m_min_normal_pt.y()), m_radius*cc.Scale(), m_radius*cc.Scale(), \n            (m_max_normal_dir - m_min_normal_dir) > 180.0 ? 1 : 0,\n            cc.X(m_max_normal_pt.x()), cc.Y(m_max_normal_pt.y()));\n        fprintf(fout, \"<path d=\\\"M%g,%g A %g %g  0 %d 0 %g %g\\\" style=\\\"stroke-width: %g; stroke: silver; fill: none;\\\"/>\\n\",\n            cc.X(m_min_normal_pt.x()), cc.Y(m_min_normal_pt.y()), m_radius*cc.Scale(), m_radius*cc.Scale(), \n            (m_max_normal_dir - m_min_normal_dir) > 180.0 ? 1 : 0,\n            cc.X(m_max_normal_pt.x()), cc.Y(m_max_normal_pt.y()), mirror_line_width);\n        // Little circles to mark the ends (and center) of the arc\n        fprintf(fout, \"<circle cx=\\\"%g\\\" cy=\\\"%g\\\" r=\\\"%g\\\" style=\\\"stroke-width: %g; stroke: teal; fill: none;\\\"/>\\n\",\n                cc.X(m_min_normal_pt.x()), cc.Y(m_min_normal_pt.y()), 1.0, mirror_line_width);\n        fprintf(fout, \"<circle cx=\\\"%g\\\" cy=\\\"%g\\\" r=\\\"%g\\\" style=\\\"stroke-width: %g; stroke: teal; fill: none;\\\"/>\\n\",\n                cc.X(m_max_normal_pt.x()), cc.Y(m_max_normal_pt.y()), 1.0, mirror_line_width);\n        fprintf(fout, \"<circle cx=\\\"%g\\\" cy=\\\"%g\\\" r=\\\"%g\\\" style=\\\"stroke-width: %g; stroke: teal; fill: none;\\\"/>\\n\",\n                cc.X(m_MidArcPt.x()), cc.Y(m_MidArcPt.y()), 1.0, mirror_line_width);\n\n        // Screen\n        if ( (m_screen.first.x() != BadValue) && (m_screen.first.y() != BadValue) && (m_screen.second.x() != BadValue) && (m_screen.second.y() != BadValue) ) {\n            fprintf(fout, \"<line x1=\\\"%g\\\" y1=\\\"%g\\\" x2=\\\"%g\\\" y2=\\\"%g\\\" style=\\\"stroke-width: 2.0; stroke: purple;\\\"/>\\n\",\n                cc.X( m_screen.first.x() ), cc.Y( m_screen.first.y() ), cc.X( m_screen.second.x() ), cc.Y( m_screen.second.y() ) );\n        }\n\n        // Stencil\n        int max_stencil_index = m_stencils.size()-1;\n        for (int ii=0; ii <= max_stencil_index; ii++) {\n            fprintf(fout, \"<line x1=\\\"%g\\\" y1=\\\"%g\\\" x2=\\\"%g\\\" y2=\\\"%g\\\" style=\\\"stroke-width: 1.5; stroke: pink;\\\"/>\\n\",\n                cc.X( m_stencils[ii].first.x() ), cc.Y( m_stencils[ii].first.y() ), cc.X( m_stencils[ii].second.x() ), cc.Y( m_stencils[ii].second.y() ) );\n        }\n\n\n        fprintf(fout, \"<text x=\\\"%g\\\" y=\\\"%g\\\" id=\\\"title_text\\\" font-size=\\\"12\\\">%s</text>\\n\", cc.X(10), cc.Y(30), title.c_str() );\n        fprintf(fout, \"<text x=\\\"%g\\\" y=\\\"%g\\\" id=\\\"more_text\\\" font-size=\\\"12\\\">%s</text>\\n\", cc.X(10), cc.Y(33), \"\" );\n\n        // Walk thru each traced ray\n        /* Note traced ray may result in numerous segments:\n         * incident=from sun (or rather, from the edge of the viewBox) to the mirror,\n         * reflected=starts and stops on the mirror - there can be multiple of these per traced ray\n         * final=starts on the mirror and proceeds away (can hit screen, stencil, or proceed out of viewBox).\n         *\n         * We use a couple of CSS classes and a tag/id per segment:\n         * class: one of ray_incidentT, ray_incidentB, ray_reflectedT, ray_reflectB, ray_finalT, rayfinalB - used for CSS styles (width and color, etc.)\n         * class: something like ray_7 - all segments associated with a single ray-trace have the same class-name. Used for Javascript to highlight\n         *      all segments on a ray on a mouseover event.\n         * id(tag): something like ray_sun_7, ray_7_2, ray_final_7 - used to allow javascript to locate the segment in the DOM to support animation. The\n         *      2nd form (ray_7_2), means the 2nd reflected ray of traced-ray #7.\n         */\n        static int ray_index = 0; // For class creation\n        for (int tri=0; tri<sizeof(traced_rays)/sizeof(traced_rays[0]); tri++) { \n            for (auto it = traced_rays[tri]->begin(); it != traced_rays[tri]->end(); ++it) {\n                if ( ! it->m_StrikePts.empty() ) {\n                ray_index++;\n                Point sun_far_pt, reflected_far_pt;\n                Calc_far_point( it->m_StrikePts.front(), 180+it->m_sun_dir,     sun_far_pt,      from_left_border, from_top_border, from_right_border);\n                Calc_far_point( it->m_StrikePts.back(),     it->m_reflect_dir, reflected_far_pt, from_left_border, from_top_border, from_right_border);\n\n                TerminateRay( Segment(it->m_StrikePts.back(), reflected_far_pt), m_screen, reflected_far_pt );\n\n                int max_index = m_stencils.size()-1;\n                for (int ii=0; ii <= max_index; ii++) {\n                    TerminateRay( Segment( it->m_StrikePts.back(), reflected_far_pt), m_stencils[ii], reflected_far_pt );\n                }\n\n                int segment_index=0;\n                // Incident ray from the sun\n                fprintf(fout, \"<line x1=\\\"%g\\\" y1=\\\"%g\\\" x2=\\\"%g\\\" y2=\\\"%g\\\" class=\\\"ray_incident%c ray_%d\\\" id=\\\"ray_sun_%d\\\"/>\\n\",\n                        cc.X(sun_far_pt.x()), cc.Y(sun_far_pt.y()), cc.X(it->m_StrikePts.front().x()), cc.Y(it->m_StrikePts.front().y()),\n                        RayType[tri], ray_index, ray_index );\n\n                if (it->m_ray_status >= TracedRay::NStrike) { // reflected ray\n                    Point previous_pt = it->m_StrikePts.front();\n                    for (auto rr = it->m_StrikePts.begin(); rr != it->m_StrikePts.end(); ++rr) {\n                        const Point& this_pt = *rr;\n                        if (this_pt == previous_pt) continue;\n                        fprintf(fout, \"<line x1=\\\"%g\\\" y1=\\\"%g\\\" x2=\\\"%g\\\" y2=\\\"%g\\\" class=\\\"ray_reflected%c ray_%d\\\" id=\\\"ray_%d_%d\\\"/>\\n\",\n                            cc.X(previous_pt.x()), cc.Y(previous_pt.y()),\n                            cc.X(this_pt.x()), cc.Y(this_pt.y()), RayType[tri], ray_index, ray_index, ++segment_index);\n                        previous_pt = this_pt;\n                    }\n                    fprintf(fout, \"<line x1=\\\"%g\\\" y1=\\\"%g\\\" x2=\\\"%g\\\" y2=\\\"%g\\\" class=\\\"ray_final%c ray_%d\\\" id=\\\"ray_final_%d\\\"/>\\n\",\n                        cc.X(it->m_StrikePts.back().x()), cc.Y(it->m_StrikePts.back().y()),\n                        cc.X(reflected_far_pt.x()), cc.Y(reflected_far_pt.y()),\n                        RayType[tri], ray_index, ray_index);\n\n                    // Indicate reflection point\n                    if (1) {\n                        double normal_dir = Direction(Point(0,0), it->m_StrikePts.back());\n                        Point pt1 = Find2ndPoint(it->m_StrikePts.back(), normal_dir,  m_radius/20 );\n                        Point pt2 = Find2ndPoint(it->m_StrikePts.back(), normal_dir, -m_radius/20 );\n                        fprintf(fout, \"<line x1=\\\"%g\\\" y1=\\\"%g\\\" x2=\\\"%g\\\" y2=\\\"%g\\\" style=\\\"stroke-width: 0.5; stroke: silver;\\\"/>\\n\",\n                            cc.X(pt1.x()), cc.Y(pt1.y()), cc.X(pt2.x()), cc.Y(pt2.y()) );\n                    }\n                } // reflected ray\n                }\n            } // for it\n        } // for tri\n\n        if (focal_pts) {\n            int intersect_count = 0;\n            for (auto it = m_TopIntersectionPts.begin(); it != m_TopIntersectionPts.end(); ++it)\n                fprintf(fout, \"<circle cx=\\\"%g\\\" cy=\\\"%g\\\" r=\\\"%g\\\" class=\\\"intersectT\\\" id=\\\"intersectT_%d\\\"/>\\n\",\n                    cc.X(it->x()), cc.Y(it->y()), 1.0, intersect_count++);\n            intersect_count = 0;\n            for (auto it = m_BotIntersectionPts.begin(); it != m_BotIntersectionPts.end(); ++it)\n                fprintf(fout, \"<circle cx=\\\"%g\\\" cy=\\\"%g\\\" r=\\\"%g\\\" class=\\\"intersectB\\\" id=\\\"intersectB_%d\\\"/>\\n\",\n                    cc.X(it->x()), cc.Y(it->y()), 1.0, intersect_count++ );\n        }\n\n        if (do_boxes) {\n            { // Bounding-box rectangle\n                double x1 = cc.X( m_TopIntersectionBBox.MinX() );\n                double x2 = cc.X( m_TopIntersectionBBox.MaxX() );\n                double y1 = cc.Y( m_TopIntersectionBBox.MinY() );\n                double y2 = cc.Y( m_TopIntersectionBBox.MaxY() );\n                double X,Y,width,height;\n                if (x1 > x2) { X = x2; width  = x1-x2; } else { X = x1; width  = x2-x1; }\n                if (y1 > y2) { Y = y2; height = y1-y2; } else { Y = y1; height = y2-y1; }\n                fprintf(fout, \"<rect x=\\\"%g\\\" y=\\\"%g\\\" width=\\\"%g\\\" height=\\\"%g\\\" class=\\\"bboxT\\\" id=\\\"top_rec\\\"/>\\n\",\n                        X,Y, width, height);\n            }\n\n            { // Bounding-box rectangle\n                double x1 = cc.X( m_BotIntersectionBBox.MinX() );\n                double x2 = cc.X( m_BotIntersectionBBox.MaxX() );\n                double y1 = cc.Y( m_BotIntersectionBBox.MinY() );\n                double y2 = cc.Y( m_BotIntersectionBBox.MaxY() );\n                double X,Y,width,height;\n                if (x1 > x2) { X = x2; width  = x1-x2; } else { X = x1; width  = x2-x1; }\n                if (y1 > y2) { Y = y2; height = y1-y2; } else { Y = y1; height = y2-y1; }\n                fprintf(fout, \"<rect x=\\\"%g\\\" y=\\\"%g\\\" width=\\\"%g\\\" height=\\\"%g\\\" class=\\\"bboxB\\\" id=\\\"bot_rec\\\"/>\\n\",\n                        X,Y, width, height);\n            }\n        }\n    }\n\n\n    if (animate) {\n        if (first_call) {\n            fprintf(fout, \"<script type=\\\"text/ecmascript\\\"><![CDATA[\\n\");\n            fprintf(fout, \"var line_data = [\\n\");\n        }\n\n\n        // Walk thru each traced ray\n        int ray_index = 0; // For CSS class creation\n        for (int tri=0; tri<sizeof(traced_rays)/sizeof(traced_rays[0]); tri++) { \n            for (auto it = traced_rays[tri]->begin(); it != traced_rays[tri]->end(); ++it) {\n                ray_index++;\n                fprintf(fout, \"\\t[ 'more_text', 'text', 'Sun Angle=%g' ],\\n\", it->m_sun_dir );\n                Point sun_far_pt, reflected_far_pt;\n                Calc_far_point( it->m_StrikePts.front(), 180+it->m_sun_dir,     sun_far_pt,      from_left_border, from_top_border, from_right_border);\n                Calc_far_point( it->m_StrikePts.back(),     it->m_reflect_dir, reflected_far_pt, from_left_border, from_top_border, from_right_border);\n\n                TerminateRay( Segment(it->m_StrikePts.back(), reflected_far_pt), m_screen, reflected_far_pt );\n\n                int max_index = m_stencils.size()-1;\n                for (int ii=0; ii <= max_index; ii++) {\n                    TerminateRay( Segment(it->m_StrikePts.back(), reflected_far_pt), m_stencils[ii], reflected_far_pt );\n                }\n\n\n                fprintf(fout, \"\\t[ 'ray_sun_%d', 'line', 'ray_incident%c', %g,%g,  %g,%g ],\\n\", \n                    ray_index, RayType[tri], cc.X(sun_far_pt.x()), cc.Y(sun_far_pt.y()), cc.X(it->m_StrikePts.front().x()), cc.Y(it->m_StrikePts.front().y()) );\n\n                int segment_index = 0;\n                if (it->m_ray_status >= TracedRay::NStrike) { // reflected ray\n                    Point previous_pt = it->m_StrikePts.front();\n                    for (auto rr = it->m_StrikePts.begin(); rr != it->m_StrikePts.end(); ++rr) {\n                        const Point& this_pt = *rr;\n                        if (this_pt == previous_pt) continue;\n                        fprintf(fout, \"\\t[ 'ray_%d_%d', 'line', 'ray_reflected%c', %g,%g,  %g,%g ],\\n\", \n                            ray_index, ++segment_index, RayType[tri],\n                            cc.X(previous_pt.x()), cc.Y(previous_pt.y()), cc.X(this_pt.x()), cc.Y(this_pt.y()) );\n                        previous_pt = this_pt;\n                    }\n                    fprintf(fout, \"\\t[ 'ray_final_%d', 'line', 'ray_final%c', %g,%g,  %g,%g ],\\n\", \n                        ray_index, RayType[tri],\n                        cc.X(it->m_StrikePts.back().x()), cc.Y(it->m_StrikePts.back().y()), cc.X(reflected_far_pt.x()), cc.Y(reflected_far_pt.y()) );\n\n                } // reflected ray\n            } // for it\n        } // for tri\n\n        if (focal_pts) {\n            int intersect_count = 0;\n            for (auto it = m_TopIntersectionPts.begin(); it != m_TopIntersectionPts.end(); ++it)\n                fprintf(fout, \"\\t[ 'intersectT_%d', 'circle', %g, %g, %g ],\\n\",\n                    intersect_count++, cc.X(it->x()), cc.Y(it->y()), 1.0 );\n            intersect_count = 0;\n            for (auto it = m_BotIntersectionPts.begin(); it != m_BotIntersectionPts.end(); ++it)\n                fprintf(fout, \"\\t[ 'intersectB_%d', 'circle', %g, %g, %g ],\\n\",\n                    intersect_count++, cc.X(it->x()), cc.Y(it->y()), 1.0 );\n        }\n\n\n        if (do_boxes) {\n            { // Top Bounding-box rectangle\n                double x1 = cc.X( m_TopIntersectionBBox.MinX() );\n                double x2 = cc.X( m_TopIntersectionBBox.MaxX() );\n                double y1 = cc.Y( m_TopIntersectionBBox.MinY() );\n                double y2 = cc.Y( m_TopIntersectionBBox.MaxY() );\n                double X,Y,width,height;\n                if (x1 > x2) { X = x2; width  = x1-x2; } else { X = x1; width  = x2-x1; }\n                if (y1 > y2) { Y = y2; height = y1-y2; } else { Y = y1; height = y2-y1; }\n                fprintf(fout, \"\\t[ 'top_rec', 'rect', %g, %g, %g, %g ],\\n\", X,Y, width, height);\n            }\n\n            { // Bot Bounding-box rectangle\n                double x1 = cc.X( m_BotIntersectionBBox.MinX() );\n                double x2 = cc.X( m_BotIntersectionBBox.MaxX() );\n                double y1 = cc.Y( m_BotIntersectionBBox.MinY() );\n                double y2 = cc.Y( m_BotIntersectionBBox.MaxY() );\n                double X,Y,width,height;\n                if (x1 > x2) { X = x2; width  = x1-x2; } else { X = x1; width  = x2-x1; }\n                if (y1 > y2) { Y = y2; height = y1-y2; } else { Y = y1; height = y2-y1; }\n                fprintf(fout, \"\\t[ 'bot_rec', 'rect', %g, %g, %g, %g ],\\n\", X,Y, width, height);\n            }\n        }\n\n        fprintf(fout, \"\\t[ 'next', 0 ],\\n\");\n\n\n\n        if (last_call) {\n            fprintf(fout, \"];\\n\");\n\n            fprintf(fout, \"var id = setInterval(intervalCallback, %d);\\n\", animate_interval_ms);\n            fprintf(fout, \"var row_index = 0;\\n\");\n            fprintf(fout, \"var prev_index = row_index;\\n\");\n            fprintf(fout, \"function intervalCallback() {\\n\");\n            fprintf(fout, \"\\twhile (1) {\\n\");\n            fprintf(fout, \"\\t\\tif(prev_index >= line_data.length) { prev_index = 0; }\\n\");\n            fprintf(fout, \"\\t\\tif (line_data[prev_index][0] == 'next') { break; }\\n\");\n            fprintf(fout, \"\\t\\tvar ref_element = document.getElementById( line_data[prev_index][0] );\\n\");\n            fprintf(fout, \"\\t\\tif (ref_element != null) {\\n\");\n            fprintf(fout, \"\\t\\t\\tref_element.setAttribute('display','none');\\n\");\n            fprintf(fout, \"\\t\\t}\\n\");\n            fprintf(fout, \"\\t\\tprev_index++;\\n\");\n            fprintf(fout, \"\\t}\\n\");\n            fprintf(fout, \"\\tprev_index = row_index;\\n\");\n            fprintf(fout, \"\\twhile (1) {\\n\");\n            fprintf(fout, \"\\t\\tif(row_index >= line_data.length) { row_index = 0; }\\n\");\n            fprintf(fout, \"\\t\\tif (line_data[row_index][0] == 'next') { row_index++; break; }\\n\");\n            fprintf(fout, \"\\t\\tvar ref_element = document.getElementById( line_data[row_index][0] );\\n\");\n            fprintf(fout, \"\\t\\tif (ref_element == null) {\\n\");\n            fprintf(fout, \"\\t\\t\\tvar xmlns = \\\"http://www.w3.org/2000/svg\\\";\\n\");\n            fprintf(fout, \"\\t\\t\\tref_element = document.createElementNS(xmlns, line_data[row_index][1]);\\n\");\n            fprintf(fout, \"\\t\\t\\tref_element.setAttribute('id',  line_data[row_index][0] );\\n\");\n            fprintf(fout, \"\\t\\tvar svg = document.getElementById( 'svg' );\\n\");\n            fprintf(fout, \"\\t\\t\\tsvg.appendChild(ref_element);\\n\");\n            fprintf(fout, \"\\t\\t\\tref_element.setAttribute('style',  'stroke-width: 1; stroke: pink;');\\n\");\n            fprintf(fout, \"\\t\\t}\\n\");\n            fprintf(fout, \"\\t\\tref_element.setAttribute('display','1');\\n\");\n            fprintf(fout, \"\\t\\tswitch( ref_element.tagName.toLowerCase() ) {\\n\");\n            fprintf(fout, \"\\t\\t\\tcase 'line':\\n\");\n            fprintf(fout, \"\\t\\t\\t\\tref_element.classList.add(line_data[row_index][2]);\\n\");\n            fprintf(fout, \"\\t\\t\\t\\tref_element.setAttribute('x1',line_data[row_index][3]);\\n\");\n            fprintf(fout, \"\\t\\t\\t\\tref_element.setAttribute('y1',line_data[row_index][4]);\\n\");\n            fprintf(fout, \"\\t\\t\\t\\tref_element.setAttribute('x2',line_data[row_index][5]);\\n\");\n            fprintf(fout, \"\\t\\t\\t\\tref_element.setAttribute('y2',line_data[row_index][6]);\\n\");\n            fprintf(fout, \"\\t\\t\\t\\tbreak;\\n\");\n            fprintf(fout, \"\\t\\t\\tcase 'circle':\\n\");\n            fprintf(fout, \"\\t\\t\\t\\tref_element.setAttribute('cx',line_data[row_index][2]);\\n\");\n            fprintf(fout, \"\\t\\t\\t\\tref_element.setAttribute('cy',line_data[row_index][3]);\\n\");\n            fprintf(fout, \"\\t\\t\\t\\tref_element.setAttribute('r', line_data[row_index][4]);\\n\");\n            fprintf(fout, \"\\t\\t\\t\\tbreak;\\n\");\n            fprintf(fout, \"\\t\\t\\tcase 'rect':\\n\");\n            fprintf(fout, \"\\t\\t\\t\\tref_element.setAttribute('x', line_data[row_index][2]);\\n\");\n            fprintf(fout, \"\\t\\t\\t\\tref_element.setAttribute('y', line_data[row_index][3]);\\n\");\n            fprintf(fout, \"\\t\\t\\t\\tref_element.setAttribute('width', line_data[row_index][4]);\\n\");\n            fprintf(fout, \"\\t\\t\\t\\tref_element.setAttribute('height', line_data[row_index][5]);\\n\");\n            fprintf(fout, \"\\t\\t\\t\\tbreak;\\n\");\n            fprintf(fout, \"\\t\\t\\tcase 'text':\\n\");\n            fprintf(fout, \"\\t\\t\\t\\tref_element.textContent=line_data[row_index][2];\\n\");\n            fprintf(fout, \"\\t\\t\\t\\tbreak;\\n\");\n            fprintf(fout, \"\\t\\t}\\n\");\n            fprintf(fout, \"\\t++row_index;\\n\");\n            fprintf(fout, \"\\t}\\n\");\n\n            fprintf(fout, \"}\\n\");\n\n            fprintf(fout, \"// ]]>\\n</script>\\n\");\n        }\n    } // if animate\n\n\n    if (last_call) {\n        if (1) { // Highlight a ray (all segments/lines) on mouseover\n            const int js_console_debug = 0;\n            fprintf(fout, \"<script type=\\\"text/javascript\\\">\\n// <![CDATA[\\n\");\n            fprintf(fout, \"var all_rays = document.querySelectorAll('[class^=ray_]');\\n\");\n            if (js_console_debug) fprintf(fout, \"console.log('all_rays.length=', all_rays.length);\\n\");\n            fprintf(fout, \"var ii;\\n\");\n            fprintf(fout, \"for (ii=0; ii<all_rays.length;ii++) {\\n\");\n            fprintf(fout, \"\\tall_rays[ii].addEventListener(\\\"mouseover\\\", rays_mouseover, false);\\n\");\n            fprintf(fout, \"\\tall_rays[ii].addEventListener(\\\"mouseout\\\",  rays_mouseout,  false);\\n\");\n            if (js_console_debug) fprintf(fout, \"console.log('ii=', ii, 'elem=', all_rays[ii], ', class=', all_rays[ii].className.baseVal);\\n\");\n            fprintf(fout, \"}\\n\");\n            fprintf(fout, \"function find_ray_class(e) {\\n\");\n            fprintf(fout, \"\\tvar class_names= e.target.className.baseVal.split(' ');\\n\");\n            fprintf(fout, \"\\tvar ray_class_name;\\n\");\n            fprintf(fout, \"\\tfor (var ii=0; ii<class_names.length; ii++) {\\n\");\n            fprintf(fout, \"\\t\\tvar regular_expression = /^ray_\\\\d+$/;\\n\");\n            fprintf(fout, \"\\t\\tif (regular_expression.test(class_names[ii])) {\\n\");\n            fprintf(fout, \"\\t\\t\\treturn class_names[ii];\\n\");\n            fprintf(fout, \"\\t\\t}\\n\");\n            fprintf(fout, \"\\t}\\n\");\n            fprintf(fout, \"\\treturn '';\\n\");\n            fprintf(fout, \"}\\n\");\n            fprintf(fout, \"function rays_mouseover(e) {\\n\");\n            fprintf(fout, \"\\tvar ray_class_name = find_ray_class(e);\\n\");\n            fprintf(fout, \"\\tvar rays = document.getElementsByClassName(  ray_class_name );\\n\");\n            fprintf(fout, \"\\tfor (var ii=0; ii<rays.length; ii++) {\\n\");\n            fprintf(fout, \"\\t\\trays[ii].style['stroke-width'] = 3;\\n\");\n            fprintf(fout, \"\\t}\\n\");\n            fprintf(fout, \"\\tvar mouseover_text_element = document.getElementById( 'more_text' );\\n\");\n//            fprintf(fout, \"\\tif (mouseover_text_element)\\n\");\n            fprintf(fout, \"\\t\\t\\tmouseover_text_element.textContent = ray_class_name;\\n\");\n            fprintf(fout, \"}\\n\");\n            fprintf(fout, \"function rays_mouseout(e) {\\n\");\n            fprintf(fout, \"\\tvar ray_class_name = find_ray_class(e);\\n\");\n            fprintf(fout, \"\\tvar rays = document.getElementsByClassName(  ray_class_name );\\n\");\n            fprintf(fout, \"\\tfor (var ii=0; ii<rays.length; ii++) {\\n\");\n            fprintf(fout, \"\\t\\trays[ii].style['stroke-width'] = '';\\n\");\n            fprintf(fout, \"\\t}\\n\");\n            fprintf(fout, \"}\\n\");\n            fprintf(fout, \"// ]]>\\n</script>\\n\");\n        }\n        fprintf(fout, \"</svg>\\n\");\n    }\n\n\n}\n\n\nstruct arg_iterator\n{\n    double from, to, increment;\n    std::string parameter_name;\n    std::deque<double> value_list;\n\n    double GetValue(int index, int &bad_index) const;\n};\ndouble arg_iterator::GetValue(int index, int &bad_index) const\n{\n    bad_index = 0;\n    if (value_list.empty()) { // use from, to, increment\n        if (index == 0) return from;\n        if (increment == 0) {\n            if ((from == to) || (index > 1)) bad_index=1;\n            return to;\n        }    \n        double value = from + index * increment;\n             if ((from < to) && (value > to)) bad_index=1;\n        else if ((from > to) && (value < to)) bad_index=1;\n        return value;\n    }\n    // Else\n    if (index < value_list.size()) return value_list[index];\n    bad_index = 1;\n    return 0;\n}\n\nvoid GrabIteratorArgs( int &arg_index, int argc, const char* argv[], const char* param_name, arg_iterator &arg_it)\n{\n    arg_it.parameter_name = param_name;\n\n    if (isdigit(argv[arg_index+1][0]) || ((argv[arg_index+1][0] == '-') && isdigit(argv[arg_index+1][1]))) {\n        arg_index++;\n        arg_it.increment = 0;\n        arg_it.from  = arg_it.to = atof(argv[arg_index]);\n    }\n    if (isdigit(argv[arg_index+1][0]) || ((argv[arg_index+1][0] == '-') && isdigit(argv[arg_index+1][1]))) {\n        arg_index++;\n        arg_it.to = atof(argv[arg_index]);\n    }\n    if (isdigit(argv[arg_index+1][0]) || ((argv[arg_index+1][0] == '-') && isdigit(argv[arg_index+1][1]))) {\n        arg_index++;\n        double value = atof(argv[arg_index]);\n        if (value < arg_it.to) {\n            arg_it.increment = value;\n            return;\n        }\n        // else take as a list of values\n        arg_it.value_list.push_back(arg_it.from);\n        arg_it.value_list.push_back(arg_it.to);\n        arg_it.value_list.push_back(value);\n        arg_it.from = arg_it.to = 0.0;\n        while (    argv[arg_index+1] &&\n              (argv[arg_index+1][0] != '\\0') &&\n              (isdigit(argv[arg_index+1][0]) || ((argv[arg_index+1][0] == '-') && isdigit(argv[arg_index+1][1]))) ) {\n            arg_index++;\n            arg_it.value_list.push_back( atof(argv[arg_index]) );\n        }\n    }\n}\n\n\nvoid GenerateReport(const std::deque<TheData> &td,const std::string& row_param, const std::string& col_param, const std::string& value_param)\n{\n    std::set<double> row_values_set;\n    std::set<double> col_values_set;\n    for (auto it = td.begin(); it != td.end(); ++it) {\n        double row_value = it->GetValue(row_param);\n        row_values_set.insert( row_value );\n        double col_value = it->GetValue(col_param);\n        col_values_set.insert( col_value );\n    }\n\n    int row_index = 0;\n    std::map<double,int> row_indices;\n    std::deque<double> row_values( row_values_set.size() );\n    for (auto it = row_values_set.begin(); it != row_values_set.end(); ++it) {\n        row_indices.insert( std::pair<double,int>( *it, row_index ) );\n        row_values[row_index] = *it;\n        row_index++;\n    }\n\n    int col_index = 0;\n    std::map<double,int> col_indices;\n    std::deque<double> col_values( col_values_set.size() );\n    for (auto it = col_values_set.begin(); it != col_values_set.end(); ++it) {\n        col_indices.insert( std::pair<double,int>( *it, col_index ) );\n        col_values[col_index] = *it;\n        col_index++;\n    }\n\n\n    std::deque< std::deque<double> > two_d(row_index);\n    for (auto it = two_d.begin(); it != two_d.end(); ++it)\n        it->resize(col_index);\n\n    for (auto it = td.begin(); it != td.end(); ++it) {\n        double row_value = it->GetValue(row_param);\n        auto row_it = row_indices.find( row_value );\n        int row_index = row_it->second;\n\n        double col_value = it->GetValue(col_param);\n        auto col_it = col_indices.find( col_value );\n        int col_index = col_it->second;\n\n        double value = it->GetValue(value_param);\n        two_d[row_index][col_index] = value;\n    }\n\n\n\n    printf(\"%s\", row_param.c_str());\n    for (int ii=0; ii<col_index; ii++) {\n        printf(\",%s_%g\",value_param.c_str(), col_values[ii]);\n    }\n    printf(\"\\n\");\n    for (int rr=0; rr<row_index; rr++) {\n        printf(\"%g\", row_values[rr] );\n        for (int cc=0; cc<col_index; cc++) {\n            if (two_d[rr][cc] == BadValue)    printf(\",\");\n            else                printf(\",%g\",  two_d[rr][cc]);\n        }\n        printf(\"\\n\");\n    }\n}\n\n\nvoid usage(const char* program_name)\n{\n    printf(\"Usage: %s [-next | -iterate] [-r ...] [-d ...] [-s[aA] ...] [-sw <value>] [-svg [<filename>]] [-csv] [-pupil] [-animate]\\n\", program_name);\n    printf(\"\\tRuns a reverse ray-tracing for a system involving the sun, a (convex) mirror and (sometimes) an observer.\\n\");\n    printf(\"\\t-next: may be used to specify a number of test-conditions. Separates the -r, -d, -sa  (and -sA) arguments. May be used multiple\\n\");\n    printf(\"\\t\\ttimes to specify multiple test-conditions. Such as %s -r 1 -d 1.1 -sA 10 -next -r 1 -d 1.1 -sA 20 -next -r 1 -d 1.1 -sA 30\\n\", program_name);\n    printf(\"\\t\\tNot compatible with the -iterate argument.\\n\");\n    printf(\"\\t-iterate: Use before -r, -d and/or -sa (and -sA) arguments. In this case each of these arguments may be followed by a series of values:\\n\");\n    printf(\"\\t\\t<value1>: Only the single value is used in the iteration.\\n\");\n    printf(\"\\t\\t<value1> <value2>: Iterates twice, first with value1 and then with value2\\n\");\n    printf(\"\\t\\t<value1> <value2> <value3> (if value2>value3): Iterate from value1 to <=value2, incrementing by value3.\\n\");\n    printf(\"\\t\\t<value1> <value2> <value3> ... (if value2<value3): taken as a series of values.\\n\");\n    printf(\"\\t\\tNote that -iterate and -next are not compatible with each other.\\n\");\n    printf(\"\\t-r <value> [...]: Defines the radius if the mirror (defaults to 1). See above comments regarding -next and -iterate.\\n\");\n    printf(\"\\t-d <value> [...]: Defines the distance from the observer to the center-of-curvature of the mirror. Must be >radius. See\\n\");\n    printf(\"\\t\\tabove comments.\\n\");\n    printf(\"\\t-sa <value> [...]: Defines the the angle of the sun's rays (i.e. 0 is horizontal to the left, 270 vertically down).\\n\");\n    printf(\"\\t-sA <value> [...]: An alterative to -sa - defines the sun's altitude (is 180 more/less than -sa): 90 is vertically down.\\n\");\n    printf(\"\\t-sw <value>: Defines the angular width of the sun in degrees. Defaults to 0.5. The above comments are not applicable.\\n\");\n    printf(\"\\t-csv: generates results in a comma-separated-values format on standard-output.\\n\");\n    printf(\"\\t-svg <filename>: generates SVG graphics in the indicated filename. Typically observer in a browser.\\n\");\n    printf(\"\\t-animate: Adds animation to the SVG (per the test-cases identified with -next or -iterate).\\n\");\n    printf(\"\\t-pupil: (experimental) - perform and report on the the entrance pupil calculations.\\n\");\n    printf(\"\\n\");\n\n}\n\nint main(int argc, const char* argv[])\n{\n    std::deque<TheData> td;\n    td.resize(1);\n    int tdi = 0; // Number of elements used in td\n\n    int do_iterate = 0;\n    arg_iterator arg_it[3];\n    int aii = 0; // Number of elements used in arg_it\n\n    int do_svg = 0;\n    std::string svg_filename = \"output.svg\";\n    int animate = 0;\n    int do_csv = 0;\n    int calc_pupil = 0;\n    int num_rays = 3;\n\n    double offset_X=0, offset_Y=0;\n\n    double default_radius = BadValue;\n    double default_distance = BadValue;\n    double default_sun_altitude_dir = BadValue;\n    double default_min_normal_dir = BadValue;\n    double default_max_normal_dir = BadValue;\n    double default_mirror_width = BadValue;\n    int animate_interval_ms = 200;\n\n    int do_convex = 0;\n    int do_concave = 0;\n    int do_boxes = 0;\n    int focal_pts = 0;\n\n\n\n    bool do_csv2 = 0;\n    int ray_report = 0;\n    int do_reverse_trace = 0;\n    std::string csv2_row, csv2_col, csv2_val;\n    std::string title;\n    for (int ii=1; ii<argc; ii++) {\n             if (strcmp(argv[ii], \"-svg\"     ) == 0) { do_svg++; if (((ii+1)<argc) && (argv[ii+1][0] != '-')) { ii++; svg_filename = argv[ii]; }}\n        else if (strcmp(argv[ii], \"-help\"    ) == 0) { usage(argv[0]); exit(0); }\n        else if (strcmp(argv[ii], \"-title\"   ) == 0) { title = argv[++ii]; }\n        else if (strcmp(argv[ii], \"-convex\"  ) == 0) { do_convex=1; do_concave=0; td[tdi].m_IsConvex = 1; }\n        else if (strcmp(argv[ii], \"-concave\" ) == 0) { do_convex=0; do_concave=1; td[tdi].m_IsConvex = 0; }\n        else if (strcmp(argv[ii], \"-debug\"   ) == 0) { dvo_debug++; if (((ii+1)<argc) && (argv[ii+1][0] != '-')) { ii++; dvo_debug = atoi(argv[ii]); }}\n        else if (strcmp(argv[ii], \"-test\"    ) == 0) { int result = CoordConverter::Test(); exit(result); }\n        else if (strcmp(argv[ii], \"-brighttable\")==0){ int brighttable(); int result = brighttable(); exit(result); }\n        else if (strcmp(argv[ii], \"-report\"  ) == 0) { ray_report++; }\n        else if (strcmp(argv[ii], \"-box\"     ) == 0) { do_boxes++; }\n        else if (strcmp(argv[ii], \"-focal_pts\")== 0) { focal_pts++; }\n        else if (strcmp(argv[ii], \"-animate\" ) == 0) { animate++; }\n        else if (strcmp(argv[ii], \"-interval\") == 0) { animate_interval_ms = atol(argv[++ii]); }\n        else if (strcmp(argv[ii], \"-reverse\" ) == 0) { do_reverse_trace++; }\n        else if (strcmp(argv[ii], \"-pupil\"   ) == 0) { calc_pupil++; }\n        else if (strcmp(argv[ii], \"-iterate\" ) == 0) { do_iterate++; }\n        else if (strcmp(argv[ii], \"-sw\"      ) == 0) { ii++; td[tdi].m_sun_width_ang    = atof(argv[ii]); }\n        else if (strcmp(argv[ii], \"-nr\"      ) == 0) { ii++; num_rays    = atoi(argv[ii]); }\n        else if (strcmp(argv[ii], \"-csv\"     ) == 0) { do_csv++; }\n        else if (strcmp(argv[ii], \"-csv2\"    ) == 0) {\n            // Expect 3 more arguments - name of row-index (independent variable #1), name of col-index (independent variable #2) and value\n            // Names are as supported in TheData::GetValue()\n            if (argc < (ii+3)) fprintf(stderr,\"ERROR: Expecting 3 fields for the -csv2 argument (row index, col index and value\\n\");\n            do_csv2 = 1;\n            csv2_row = argv[++ii];\n            csv2_col = argv[++ii];\n            csv2_val = argv[++ii];\n             } \n        else if (strcmp(argv[ii], \"-screen\" ) == 0) {\n            if (argc < (ii+4)) fprintf(stderr,\"ERROR: Expecting 4 fields for the %s argument: End points (each with an X,Y value) for the screen.\\n\", argv[ii]);\n            double X1 = atof( argv[++ii] );\n            double Y1 = atof( argv[++ii] );\n            double X2 = atof( argv[++ii] );\n            double Y2 = atof( argv[++ii] );\n            td[tdi].m_screen = Segment( Point(X1,Y1), Point(X2,Y2) );\n        }\n        else if (strcmp(argv[ii], \"-stencil\" ) == 0) {\n            if (argc < (ii+4)) fprintf(stderr,\"ERROR: Expecting 4 fields for the %s argument: End points (each with an X,Y value) for one line of the stencil.\\n\", argv[ii]);\n            double X1 = atof( argv[++ii] );\n            double Y1 = atof( argv[++ii] );\n            double X2 = atof( argv[++ii] );\n            double Y2 = atof( argv[++ii] );\n            td[tdi].m_stencils.push_back(  Segment( Point(X1,Y1), Point(X2,Y2) ) );\n        }\n        else if (strcmp(argv[ii], \"-offset\" ) == 0) {\n            if (argc < (ii+2)) fprintf(stderr,\"ERROR: Expecting 2 fields for the %s argument\", argv[ii]);\n            offset_X = atof( argv[++ii] );\n            offset_Y = atof( argv[++ii] );\n        }\n        else if (strcmp(argv[ii], \"-target\" ) == 0) {\n            if (argc < (ii+2)) fprintf(stderr,\"ERROR: Expecting 2 fields for the %s argument\", argv[ii]);\n            double X = atof( argv[++ii] );\n            double Y = atof( argv[++ii] );\n            td[tdi].m_target_pts.push_back( Point(X,Y) );\n        }\n        else if (do_iterate) { // We interpret some arguments differently depending on whether the -iterate argument has been specified (must be earlier)\n            if (aii >= sizeof(arg_it)/sizeof(arg_it[0])) fprintf(stderr, \"Error: too many iterate arguments (%d >= %d)\\n\", aii, sizeof(arg_it)/sizeof(arg_it[0]));\n                 if (strcmp(argv[ii], \"-r\"   ) == 0) { GrabIteratorArgs( ii, argc, argv, \"radius\",       arg_it[aii] ); aii++; }\n            else if (strcmp(argv[ii], \"-d\"   ) == 0) { GrabIteratorArgs( ii, argc, argv, \"distance\",     arg_it[aii] ); aii++; }\n            else if (strcmp(argv[ii], \"-sa\"  ) == 0) { GrabIteratorArgs( ii, argc, argv, \"sunangle\",     arg_it[aii] ); aii++; }\n            else if (strcmp(argv[ii], \"-sA\"  ) == 0) { GrabIteratorArgs( ii, argc, argv, \"sunaltitude\",  arg_it[aii] ); aii++; }\n            else if (strcmp(argv[ii], \"-mna\" ) == 0) { GrabIteratorArgs( ii, argc, argv, \"minnormal\",    arg_it[aii] ); aii++; }\n            else if (strcmp(argv[ii], \"-mxa\" ) == 0) { GrabIteratorArgs( ii, argc, argv, \"mixnormal\",    arg_it[aii] ); aii++; }\n            else if (strcmp(argv[ii], \"-mw\"  ) == 0) { GrabIteratorArgs( ii, argc, argv, \"mirror_width\", arg_it[aii] ); aii++; }\n            else    { fprintf(stderr, \"ERROR - unrecognized command line argument (#%d): %s - with -iterate option.\\n\", ii, argv[ii] ); }\n        } else { // not iterate\n                 if (strcmp(argv[ii], \"-r\"   ) == 0) { ii++; default_radius           = td[tdi].m_radius           = atof(argv[ii]); }\n            else if (strcmp(argv[ii], \"-d\"   ) == 0) { ii++; default_distance         = td[tdi].m_distance         = atof(argv[ii]); }\n            else if (strcmp(argv[ii], \"-sa\"  ) == 0) { ii++; default_sun_altitude_dir = td[tdi].m_sun_dir = atof(argv[ii]); }\n            else if (strcmp(argv[ii], \"-sA\"  ) == 0) { ii++; default_sun_altitude_dir = td[tdi].m_sun_dir = atof(argv[ii]) + 180; }\n            else if (strcmp(argv[ii], \"-mna\" ) == 0) { ii++; default_min_normal_dir   = td[tdi].m_min_normal_dir   = atof(argv[ii]); }\n            else if (strcmp(argv[ii], \"-mxa\" ) == 0) { ii++; default_max_normal_dir   = td[tdi].m_max_normal_dir   = atof(argv[ii]); }\n            else if (strcmp(argv[ii], \"-mw\"  ) == 0) { ii++; default_mirror_width=atof(argv[ii]); td[tdi].m_min_normal_dir=270-default_mirror_width; td[tdi].m_max_normal_dir=270+default_mirror_width; }\n            else if (strcmp(argv[ii], \"-next\") == 0) { tdi++; td.resize(tdi+1); td[tdi].DuplicateSettings( td[tdi-1] ); }\n            else    { fprintf(stderr, \"ERROR - unrecognized command line argument (#%d): %s\\n\", ii, argv[ii] ); }\n        }\n    } // for ii<argc\n\n    if (aii && dvo_debug)\n        for (int ii=0; ii<aii; ii++) {\n            printf(\"Iterator #%d: %-10s from=%g, to=%g, increment=%g\\n\",\n                ii, arg_it[ii].parameter_name.c_str(), arg_it[ii].from, arg_it[ii].to, arg_it[ii].increment);\n            printf(\"\\tvalue_list.size()=%d\\n\", arg_it[ii].value_list.size() );\n            printf(\"\\t\");\n            for (int jj=0; jj<arg_it[ii].value_list.size(); jj++)\n                printf(\"%g \", arg_it[ii].value_list[jj]);\n            printf(\"\\n\");\n        }\n\n    if (aii) {\n        int it_indices[ sizeof(arg_it)/sizeof(arg_it[0]) ];\n        double it_values[ sizeof(arg_it)/sizeof(arg_it[0]) ];\n        int bad_index[ sizeof(arg_it)/sizeof(arg_it[0]) ];\n        for (int ii=0; ii<sizeof(arg_it)/sizeof(arg_it[0]); ii++) {\n            it_indices[ii] = 0;\n            it_values[ii] = 0;\n            bad_index[ii] = 0;\n        }\n        // Here's the approach - the first iterator in arg_it spins the fastest. Iterate through it until reaches its\n        // end, then reset it to the beginning. Then increment the next iterator (if possible) and restart on the first iterator.\n        int done = 0;\n        while (! done) {\n            td[tdi].m_radius = default_radius;\n\t\t\ttd[tdi].m_distance = default_distance;\n            td[tdi].m_sun_dir = default_sun_altitude_dir;\n            if (default_min_normal_dir != BadValue) td[tdi].m_min_normal_dir = default_min_normal_dir;\n            if (default_max_normal_dir != BadValue) td[tdi].m_max_normal_dir = default_max_normal_dir;\n            if (default_mirror_width   != BadValue) { td[tdi].m_min_normal_dir=270-default_mirror_width; td[tdi].m_max_normal_dir=270+default_mirror_width; }\n\n            // Get cache the values\n            for (int ii=0; ii<aii; ii++) {\n                it_values[ii] = arg_it[ii].GetValue( it_indices[ii], bad_index[ii] );\n                if (bad_index[ii]) {\n                    it_indices[ii] = 0;\n                    it_values[ii] = arg_it[ii].GetValue( it_indices[ii], bad_index[ii] );\n                    if (ii<(aii-1)) it_indices[ii+1]++;\n                    else done = true;\n                }\n                if (ii == 0) it_indices[ii]++; // increment for next loop\n            }\n\n            // Apply the values\n            for (int ii=0; ii<aii; ii++) {\n                     if (arg_it[ii].parameter_name == \"radius\"      ) { td[tdi].m_radius           = it_values[ii]; }\n\t\t\t\telse if (arg_it[ii].parameter_name == \"distance\"    ) { td[tdi].m_distance         = it_values[ii]; }\n                else if (arg_it[ii].parameter_name == \"sunangle\"    ) { td[tdi].m_sun_dir = it_values[ii]; }\n                else if (arg_it[ii].parameter_name == \"sunaltitude\" ) { td[tdi].m_sun_dir = it_values[ii] + 180; }\n                else if (arg_it[ii].parameter_name == \"minnormal\"   ) { td[tdi].m_min_normal_dir   = it_values[ii]; }\n                else if (arg_it[ii].parameter_name == \"minnormal\"   ) { td[tdi].m_max_normal_dir   = it_values[ii]; }\n                else if (arg_it[ii].parameter_name == \"mirror_width\") {\n                           td[tdi].m_max_normal_dir = 270 + it_values[ii]/2;\n                           td[tdi].m_min_normal_dir = 270 - it_values[ii]/2;\n                       } else {\n                    fprintf(stderr,\"Unrecognized iterator parameter (%s) for index=%d at %d of %s\\n\",\n                                   arg_it[ii].parameter_name.c_str(), ii, __LINE__, __FILE__ );\n                }\n            }\n            if (! done) {\n                tdi++; td.resize(tdi+1);\n                td[tdi] = td[tdi-1];\n            }\n\n        } // while ! done\n    } // if aii\n\n\n    FILE *fout = NULL;\n    if (do_svg) {\n        fout = fopen(svg_filename.c_str(), \"w\");\n        if (fout == NULL) {\n            fprintf(stderr, \"Error: Can't open %s for writing.\\n\", svg_filename.c_str() );\n            return false;\n        }\n    }\n\n\n    for (int ii=0; ii<=tdi; ii++) {\n        if (dvo_debug>1) {\n            printf(\"Iteration loop %d of %d\\n\", ii, tdi);\n            td[ii].InputDump(stdout);\n        }\n\n        td[ii].Calculate(do_reverse_trace ? 0 : num_rays, calc_pupil);\n\n        if (dvo_debug) {\n            printf(\"Calculated Data in Iteration loop %d of %d:\\n\", ii, tdi);\n            td[ii].Dump(stdout);\n        }\n\n\n        if (ray_report) {\n            td[ii].RayReport(stdout,1);\n        }\n    }\n\n    for (int ii=0; ii<=tdi; ii++) {\n        if (do_svg) {\n#if 0\n            if (td[ii].m_distance != BadValue)\n    \t\t\ttd[ii].GenSVG_Convex(fout, offset_X, offset_Y, ii==0, ii==tdi, animate);\n            else\n                td[ii].GenSVG_Concave(fout, offset_X, offset_Y, title, ii==0, ii==tdi, animate, animate_interval_ms);\n#else\n            if (td[ii].m_IsConvex) td[ii].GenSVG_Convex(fout, offset_X, offset_Y, ii==0, ii==tdi, animate);\n            else                   td[ii].GenSVG_Concave(fout, offset_X, offset_Y, title, ii==0, ii==tdi, animate, animate_interval_ms, do_boxes, focal_pts);\n#endif\n        }\n    }\n\n    if (do_csv2) GenerateReport(td, csv2_row, csv2_col, csv2_val );\n\n    return 0;\n}\n\n\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n// Start of the original Convex code\n\n\n/* A 3 component optic system - a sun (at infinite distance and a finite\n * angular width), a Convex mirror, and an observer. The observer is at the\n * same Y elevation as the center of curvature of the mirror.\n *\n * My conventions...\n * Center of the curvature of the Mirror is at (0,0)\n * Observer is to the left at (-distance,0)\n * Regarding angles (3 sets: from Mirror's center, from observer, from Sun). All 3 Angles\n * \tare 0 when the sun is directly behind the observer (on horizon).\n * From Center of curvature:\n * \t0 degrees is horizontally to the left.\n * \t90 degrees is vertical.\n * From Observer:\n * \t0 degree is horizontally to the right.\n * \t>0 (and <90) degrees is upwards to the right.\n * From Sun:\n *\tSun's 0 degree is a horizontal ray from the left.\n *\tSun's 0..90 degrees are rays from above left - 90degrees is vertical (down),\n *\tand >90 degrees are from the above right.\n *\tWe use 3 points in the Sun - the bottom (at 6 o'clock) the center/middle and the top (12 o'clock)\n *\n *\n * Be aware: Standard Trig Quadrants...\n *          |\n *        2 | 1\n *      ----+----\n *        3 | 4\n *          |\n * But this is NOT my convention here.\n *\n *\n * Inputs (all angles in degrees):\n * r=radius of convex mirror whose Center of curvature is at (0,0)\n * d=distance of observer from the Center of curvature. Precondition: d>r\n * \tr and d have the same units (of your choice).\n * sa=altitude of the center-point of the sun. (0=horizontal and\n * \tbehind the observer)\n * sw=angular width of the sun. Default=0.5\n *\n * Calculates:\n * Observer Tangent Angle - the angle at which the observer sees the upper-most portion\n * \tof the mirror (i.e. a ray from the observer that grazes along a tangent\n * \tof the mirror). This is determined exactly by 'r' and 'd'.\n * Normal Tange Angle - for the above tangent - the corresponding normal angle (from C to mirror)\n * Observed angle of the reflected sun off the mirror. There are 3 variations\n * \tof this - for the top, middle and bottom points of the sun.\n * \tNote that this each constrained between 0 and the 'Tangent Angle'.\n * Observed Angular Size of the reflected sun off the mirror. Simply\n * \tthe difference between 'top' and 'bottom' observed angles of the\n * \treflected sun off the mirror.\n *\n */\n\n\n\n\n\n\nstatic Point my_local_normal_point; // junk storage usable for an optional default argument.\n\nbool CalcFromNormal_Convex(const TheData&td,\n\t\t\tdouble normal_ang,\n\t\t       \tdouble& ang_from_observer,\n\t\t       \tdouble& ang_from_sky,\n\t\t       \tPoint & normalPt=my_local_normal_point)\n// Convex Mirror\n\t// Take the normal_angle (in degrees from Mirror's center-of-curvature) - \n\t// Step 1: calculate the (X,Y) coordinates on the mirror,\n\t// Step 2: calculate angle from observer to the (X,Y) point,\n\t// Step 3: calculate the corresponding angle from the sky that would get\n\t// \treflected at point (X,Y) to the observer.\n\t// return success.\n{\n\t// Step 0 - error check\n\tif (normal_ang > td.m_NormalTangentAng) {\n\t\tang_from_observer = ang_from_sky = 0;\n\t\tnormalPt.x(0);\n\t\tnormalPt.y(0);\n\t\treturn false;\n\t}\n\n\t// Step 1\n\tdouble normal_ang_radians = to_radians(normal_ang);\n\tnormalPt.x( td.m_MirrorCOCPt.x() + td.m_radius * cos( normal_ang_radians ) );\n\tnormalPt.y( td.m_MirrorCOCPt.y() + td.m_radius * sin( normal_ang_radians ) );\n\n\t// Step 2\ndouble observer_ang_radians = atan2( normalPt.y() - td.m_ObserverPt.y(), normalPt.x() - td.m_ObserverPt.x() ); \ndouble ang_from_observer_old = to_degrees( observer_ang_radians );\n\tang_from_observer = Direction( td.m_ObserverPt, normalPt );\n\n\t// Step 3\ndouble ang_from_sky_old = 2* normal_ang + ang_from_observer;\n\tang_from_sky = normal_ang + normal_ang + (180-ang_from_observer) + 180;\n\n//printf(\"angle-from_observer(old)=%g, new=%g, angle-from-sky (old)=%g, new=%g\\n\", ang_from_observer_old, ang_from_observer, ang_from_sky_old, ang_from_sky );\n\treturn true;\n}\n\n\n\nbool SearchForSkyAng_Convex(const TheData& td,\n\t\t\tdouble target_sky_ang,\n\t\t\tdouble &found_normal_ang,\n\t\t\tdouble &found_sky_ang,\n\t\t\tdouble &found_observer_ang,\n\t\t\tPoint  &found_MirrorPoint,\n\t\t\tdouble acceptable_difference = 0.001)\n{\n\t/* Successive approximation.\n\t */\n\tdouble prev_ang_from_sky = 0; // to determine when we are close enough\n\n\tdouble max_normal =  td.m_NormalTangentAng; // The search will close the window between max_normal and min_normal\n\tdouble min_normal = -td.m_NormalTangentAng;\n\n\tfor (int iterate_counter = 0; iterate_counter < 100; iterate_counter++) {\n\t\tdouble guess_normal = (max_normal + min_normal) / 2;\n\n\t\tdouble ang_from_observer, ang_from_sky;\n\t\tPoint mirror_point;\n\t\tbool success = CalcFromNormal_Convex(td, guess_normal, ang_from_observer, ang_from_sky, mirror_point);\n\n\t\tif (success) {\n\t\t\tif (dvo_debug >= 4)\n\t\t\t\tprintf(\"%3d: Target=%-7.4g Calc(guess_normal=%-7.4g, observer=%-7.4g, sky=%-7.4g)=%d MirrorPtr=(%-7.4g,%-7.4g), min,max=%-7.4g,%-7.4g\\n\",\n\t\t\t\t\titerate_counter, target_sky_ang, guess_normal, ang_from_observer, ang_from_sky,\n\t\t\t\t       \tsuccess, mirror_point.x(), mirror_point.y(), min_normal, max_normal);\n\n\t\t\t// Conditions to stop looping...\n\t\t\tif ( NearlyEqual(ang_from_sky, target_sky_ang) || ((iterate_counter >= 1) && NearlyEqual(prev_ang_from_sky, ang_from_sky))) {\n\t\t\t\tbool passed = NearlyEqual(ang_from_sky,target_sky_ang); // Fails if didn't converge\n\n\t\t\t\tif (! passed ) { // Didn't converge\n\t\t\t\t\tif (dvo_debug >= 3)\n\t\t\t\t\t\tprintf(\"End of search - didn't converge: target_sky_ang=%g, normal boundaries=%g,%g, ang_from_sky (previous)=%g (%g)\\n\",\n\t\t\t\t\t\t\ttarget_sky_ang, min_normal, max_normal, ang_from_sky, prev_ang_from_sky);\n\t\t\t\t\t\treturn false;\n\t\t\t\t} // Else - passed\n\t\t\t\tfound_normal_ang = guess_normal;\n\t\t\t\tfound_sky_ang = ang_from_sky;\n\t\t\t\tfound_observer_ang = ang_from_observer;\n\t\t\t\tfound_MirrorPoint = mirror_point;\n\t\t\t\tif (dvo_debug >= 3)\n\t\t\t\t\tprintf(\"End of search: FoundNormalAng=%g, FoundSkyAng=%g, FoundObserverAng=%g, FoundMirrorPt=(%g,%g)\\n\",\n\t\t\t\t\t\t      found_normal_ang, found_sky_ang, found_observer_ang,  found_MirrorPoint.x(), found_MirrorPoint.y() );\n\t\t\t\treturn true; // Normal exit point in a successful search\n\t\t\t}\n\t\t}\n\n\t\t// Refine the window for the next iteration\n\t\tif (ang_from_sky > target_sky_ang) { max_normal = guess_normal;  }\n\t\tif (ang_from_sky < target_sky_ang) { min_normal = guess_normal; }\n\n\t\tprev_ang_from_sky = ang_from_sky;\n\t}\n\treturn false;\n}\n\n\nvoid TheData::Calculate_Convex(int num_rays, int do_pupil)\n\t/* The object a few 'input' parameters, and numerous 'derived' values - that are determined from the\n\t * 'input' parameters. This routine determines those derived values.\n\t */\n{\n\tif (CheckInputs()) {\n\t\tSet(m_MirrorCOCPt, 0, 0 );\n\t\t// The user, via command-line arguments, can have the ObserverPoint set - or the distance - but not both.\n\t\tif (m_distance != BadValue) {\n\t\t\tSet(m_ObserverPt, m_distance, 0 );\n\t\t} else if (m_ObserverPt.x() || m_ObserverPt.y()) {\n\t\t\tm_distance = Distance(m_ObserverPt, m_MirrorCOCPt );\n\t\t} else { // neither was set, so pick a default.\n\t\t\tm_distance = 2.0;\n\t\t}\n\n\t\t// Calculate the tangent - imagine a right-triangle - mirror-tangent is 90 degrees, other 2 vertices are at observer and Mirror COC\n\t\tdouble angle_tangentPt_obs_mirrorCoc = to_degrees( asin( m_radius / Distance(m_MirrorCOCPt, m_ObserverPt) ) ); // angle at observer\n\t\tdouble third_angle = 180.0 -90.0 - angle_tangentPt_obs_mirrorCoc; // angle at Mirror's COC\n\t\tdouble third_angle_to_X_axis = 180.0 - third_angle; // assumes observer and Mirror's COC are both on X axis (Y=0)\n\t\tm_NormalTangentAng = 90.0 + (90.0 - third_angle_to_X_axis); // From Mirror's COC\n\t\tif (1) { // Finds the tangent point\n\t\t\tdouble junk1, junk2;\n\t\t\tCalcFromNormal_Convex(*this, m_NormalTangentAng, junk1, junk2, m_TangentPt);\n\t\t}\n\t\tm_ObserverTangentAng = Direction( m_ObserverPt, m_TangentPt );\n\n\n\t\t// Calculate (searches) for the 3 rays from observer to mirror to sun (reverse ray-tracing)\n\t\tdouble normal_mid, normal_bot, normal_top;\n\t\tbool success1 = SearchForSkyAng_Convex(*this, m_sun_dir, normal_mid, m_SunMidAng, m_ObserverReflectedSunMid, m_SunMidMirrorPt);\n\t\tdouble target_sun_bot_ang = m_SunMidAng - m_sun_width_ang/2;\n\t\tdouble target_sun_top_ang = m_SunMidAng + m_sun_width_ang/2;\n\t\tbool success2 = SearchForSkyAng_Convex(*this, target_sun_bot_ang, normal_bot, m_SunBotAng, m_ObserverReflectedSunBot, m_SunBotMirrorPt);\n\t\tbool success3 = SearchForSkyAng_Convex(*this, target_sun_top_ang, normal_top, m_SunTopAng, m_ObserverReflectedSunTop, m_SunTopMirrorPt);\n\n#if 0 // try1\n\t\tif (success1 && success2 && success3 && do_pupil) { // experimental\n\t\t\t// Here's my approach - imagine a line that passes through the m_SunMidMirrorPt - perpendicular\n\t\t\t// to the ray from the sun. Determine where that line crosses the rays (from the sun) for the\n\t\t\t// Top and Bot rays. In many cases, this line crosses into the mirror, but we ignore that that one\n\t\t\t// of the rays might not actually reach this line.\n\t\t\t//\n\t\t\t// My first attempt at dot-products didn't work. So now trying a different approach that is based on having\n\t\t\t// two points on each of two lines (http://www.ambrsoft.com/MathCalc/Line/TwoLinesIntersection/TwoLinesIntersection.htm)\n\t\t\t// What I have is the m_SunXxxMirrorPt and the m_SunXxxAng for each of the 3 rays - so a point and and angle (I should\n\t\t\t// be able to treat each as a vector - and use the dot-products (etc.) to determine the intersection points). So,\n\t\t\t// I'm now arbitrarily locating a 2nd point (a distance of +1 from the first) on each ray and using that in the calculations.\n\t\t\tPoint BotRay_2nd_pt( m_SunBotMirrorPt.x() + 1*cos(to_radians(m_SunBotAng)), m_SunBotMirrorPt.y() - 1*sin(to_radians(m_SunBotAng)) ); \n\t\t\tPoint TopRay_2nd_pt( m_SunTopMirrorPt.x() + 1*cos(to_radians(m_SunTopAng)), m_SunTopMirrorPt.y() - 1*sin(to_radians(m_SunTopAng)) ); \n\n\t\t\tdouble pupil_line_ang = m_SunMidAng + 90.0;\n\t\t\tPoint Pupil_2nd_pt ( m_SunMidMirrorPt.x() + 1*cos(to_radians(pupil_line_ang)), m_SunMidMirrorPt.y() - 1*sin(to_radians(pupil_line_ang)) ); \n\n\t\t\tIntersection_2Segments( Segment(m_SunMidMirrorPt, Pupil_2nd_pt), Segment(m_SunTopMirrorPt, TopRay_2nd_pt), m_PupilTopPt );\n\t\t\tIntersection_2Segments( Segment(m_SunMidMirrorPt, Pupil_2nd_pt), Segment(m_SunBotMirrorPt, BotRay_2nd_pt), m_PupilBotPt );\n\n            if (Defined(m_PupilBotPt) && Defined(m_PupilTopPt) ) {\n    \t\t\tm_Pupil = Distance( m_PupilBotPt, m_PupilTopPt ); \n\n    \t\t\tm_Brightness = to_degrees( asin( m_Pupil / Distance( m_ObserverPt, m_SunMidMirrorPt )) ) / 0.5;\n            }\n\t\t}\n#endif\n\n#if 1 // try2\n\t\tif (success1 && success2 && success3 && do_pupil) { // experimental\n\t\t\t// Here's my approach - Consider a line-segement between the m_PupilTopPt and m_PupilBotPt - what\n\t\t\t// is the length of the line as 'seen' from the Sun? (for Entrance pupil) or From the Observer (for\n\t\t\t// the Exit pupil).\n\n            m_Pupil_Entrance = ApparentWidth( m_SunTopMirrorPt, m_SunBotMirrorPt, m_sun_dir );\n            m_Pupil_Exit     = ApparentWidth( m_SunTopMirrorPt, m_SunBotMirrorPt, m_ObserverReflectedSunMid );\n// printf(\"Mirror Points=(%g,%g),  (%g,%g), angles=%g, %g\\n\", m_SunTopMirrorPt.x(), m_SunTopMirrorPt.y(), m_SunBotMirrorPt.x(), m_SunBotMirrorPt.y(), m_sun_dir, m_ObserverReflectedSunMid );\n\n            m_Brightness = m_Pupil_Entrance / m_Pupil_Exit;\n\n            // Another brightness approach - compare the apparent angular width to 0.5 degrees\n            m_Brightness2 = ApparentWidth_ang( m_SunTopMirrorPt, m_SunBotMirrorPt, m_ObserverPt ) / m_sun_width_ang;\n\n//printf(\"Pupils: %g/%g = %g, Brightness2=%g\\n\", m_Pupil_Entrance, m_Pupil_Exit, m_Brightness, m_Brightness2 );\n\t\t}\n#endif\n\n\n\t\tif (dvo_debug>=2)\n\t\t\tprintf(\"Results: %d%d%d: observer_angs: %g, %g, %g (diff=%g) sun_angs: (tar=%g) %g, %g, %g (diff=%g) (Normals=%g,%g,%g), Pupil=%g/%g, Bright=%g,%g\\n\",\n\t\t\t\tsuccess1, success2, success3,\n\t\t\t\tm_ObserverReflectedSunBot, m_ObserverReflectedSunMid, m_ObserverReflectedSunTop,\n\t\t\t       \tm_ObserverReflectedSunTop-m_ObserverReflectedSunBot,\n\t\t\t\tm_sun_dir, m_SunBotAng, m_SunMidAng, m_SunTopAng, m_SunTopAng-m_SunBotAng,\n\t\t\t\tnormal_bot, normal_mid, normal_top,\n\t\t\t\tm_Pupil_Entrance/m_Pupil_Exit, m_Brightness, m_Brightness2);\n\t}\n}\n\n\nstatic void OneRayFromSunToObserver_CalcLines(bool is_bad, double sun_ang,\n\t       Point& found_sun_pt, Point& sun_pt2 /* start with mirror-point */,\n\t       const Point& observer_pt,\n\t       double border_left, double border_top, double border_right, double border_bottom)\n{\n\tconst Point mirror_pt = sun_pt2;\n\tif ( is_bad ) { // Assuming this means the sun is past the tangent (behind the mirror)\n\t\t// Sun is obscurred - we'll draw a partial ray of a different color - this happens only if sun_ang > 90\n\t\t// We'll create the rays as if they would reach the observer (if not for the mirror)\n\t\tfound_sun_pt.x( border_left );\n\t\tfound_sun_pt.y( ( observer_pt.x() - found_sun_pt.x() ) * -1 * tan( to_radians(sun_ang) ) );\n\t\t// How to determine a reasonable length for this ray?\n\t\tsun_pt2.x( border_left/2 ); // Not actually on the mirror - just the other end of a shortened sun-ray\n\t\tsun_pt2.y( (observer_pt.x() - sun_pt2.x()) * -1 * tan( to_radians(sun_ang) ) );\n\t} else {\n\t\t// Incident ray from the sun\n\t\t// Where should the beginning of the incident ray line start? - at one of the border.\n\t\tdouble sun_ang_normalized = NormalizeAngle( sun_ang );\n\t\tif (sun_ang_normalized > 270) { // Check for intersection with right border\n\t\t\tfound_sun_pt.x( border_left );\n\t\t\tfound_sun_pt.y( mirror_pt.y() - tan( to_radians( sun_ang_normalized ) ) * (mirror_pt.x() - border_left) );\n\t\t\tif (found_sun_pt.y() > border_top) {\n\t\t\t\tfound_sun_pt.y( border_top );\n\t\t\t\tfound_sun_pt.x( mirror_pt.x() + (found_sun_pt.y() - mirror_pt.y())/tan( to_radians(sun_ang_normalized) ) );\n\t\t\t}\n\t\t} else if ((sun_ang_normalized < 270) && (sun_ang_normalized >= 90)) { // Check for intersection with right border - DVO HELP- can this be combined with above?\n\t\t\tfound_sun_pt.y( border_top );\n\t\t\tfound_sun_pt.x( mirror_pt.x() + (border_top-mirror_pt.y())/tan( to_radians(sun_ang_normalized) ) );\n\t\t\tif (found_sun_pt.x() > border_right) {\n\t\t\t\tfound_sun_pt.x( border_right );\n\t\t\t\tfound_sun_pt.y( mirror_pt.y() + tan( to_radians( sun_ang_normalized ) ) * (border_right - mirror_pt.x()) );\n\t\t\t}\n\t\t} else if (sun_ang_normalized < 90) { // Check for intersection with bottom border - DVO HELP- can this be combined with above?\n\t\t\tfound_sun_pt.y( border_bottom );\n\t\t\tfound_sun_pt.x( mirror_pt.x() - (mirror_pt.y()-border_bottom)/tan( to_radians(sun_ang_normalized) ) );\n\t\t\tif (found_sun_pt.x() > border_right) {\n\t\t\t\tfound_sun_pt.x( border_right );\n\t\t\t\tfound_sun_pt.y( mirror_pt.y() + tan( to_radians( sun_ang_normalized ) ) * (border_right - mirror_pt.x()) );\n\t\t\t}\n\t\t} else { // else must be exactly 270 degrees\n\t\t\tfound_sun_pt.x( mirror_pt.x() );\n\t\t\tfound_sun_pt.y( border_top );\n\t\t}\n\t}\n}\n\n\nstatic void SVG_OneRayFromSunToObserver_Convex(FILE *fout, const CoordConverter& cc,\n\t\tdouble sun_ang, const char* id_name_suffix,\n\t\tconst Point& observer_pt, const Point& mirror_pt,\n\t\tdouble border_left, double border_top, double border_right, double border_bottom, double line_width)\n{\n\tPoint sunpt1, sunpt2(mirror_pt);\n\n\tbool obscured_sun = NearlyEqual(mirror_pt.x(),0) && NearlyEqual(mirror_pt.y(),0);\n\n\tOneRayFromSunToObserver_CalcLines(obscured_sun, sun_ang, sunpt1, sunpt2, observer_pt, border_left, border_top, border_right, border_bottom);\n\n\t// Incident ray from the sun\n\tfprintf(fout, \"<line id=\\\"incident_ray_%s\\\" x1=\\\"%g\\\" y1=\\\"%g\\\" x2=\\\"%g\\\" y2=\\\"%g\\\" style=\\\"stroke-width: %g; stroke: %s;\\\"/>\\n\",\n\t\t\tid_name_suffix, cc.X(sunpt1.x()), cc.Y(sunpt1.y()),  cc.X(sunpt2.x()), cc.Y(sunpt2.y()), line_width, obscured_sun ? \"purple\" : \"red\" );\n\n\tif ( ! obscured_sun ) {\n\t\t// Reflected ray - from mirror to observer\n\t\tfprintf(fout, \"<line id=\\\"reflected_ray_%s\\\" x1=\\\"%g\\\" y1=\\\"%g\\\" x2=\\\"%g\\\" y2=\\\"%g\\\" style=\\\"stroke-width: %g; stroke: orange;\\\"/>\\n\",\n\t\t\tid_name_suffix, cc.X(mirror_pt.x()), cc.Y(mirror_pt.y()),  cc.X(observer_pt.x()), cc.Y(observer_pt.y()), line_width);\n\t}\n}\n\nbool TheData::GenSVG_Convex(FILE *fout, double offset_X, double offset_Y, bool first_call, bool last_call, int animate) const\n{\n\t// Intend for a 10% margin/borders.\n\t// As always with SVG, increasing X is to the right, and increase Y is DOWN the screen.\n\t// So we typically invert (*-1) the Y coordinates from our optics modelling to match the SVG model.\n\t// Relocate the origin to be the center of the mirror - and place this at the left/right center and on bottom border.\n\t// Put the observer at the left-bottom border corner.\n\tconst double border_proportion = 0.10;\n\tconst double canvas_size = 800;\n\tconst double line_width = 1; // Thinest\n\tconst double mirror_line_width = 0.5;\n\n\tconst double border_size = 2.5*m_distance * border_proportion;\n\n\tdouble from_top_border    =  2   *m_distance;\n\tdouble from_bottom_border = -0.5 *m_distance;\n\tdouble from_left_border   = -1.25*m_distance;\n\tdouble from_right_border  =  1.25*m_distance;\n\tCoordConverter cc;\n\tcc.DefineFrom( offset_X+from_left_border  - border_size, offset_Y+from_bottom_border - border_size,\n                   offset_X+from_right_border + border_size, offset_Y+from_top_border    + border_size);\n\tcc.DefineTo  (0, 800, 800, 0);\n\n\tif (first_call) {\n\t\tfprintf(fout, \"<?xml version=\\\"1.0\\\" standalone=\\\"yes\\\"?>\\n\");\n\t\tfprintf(fout, \"<!DOCTYPE svg PUBLIC \\\"-//W3C//DTD SVG 1.1//EN\\\" \\\"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\\\">\\n\");\n\t\tfprintf(fout, \"<svg xmlns=\\\"http://www.w3.org/2000/svg\\\" xmlns:xlink=\\\"http://www.w3.org/1999/xlink\\\" \");\n\t\tfprintf(fout, \"width=\\\"%g\\\" height=\\\"%g\\\" viewBox=\\\"%g %g %g %g\\\">\\n\",\n\t\t\tcanvas_size, canvas_size,\n\t\t\t0.0,0.0, canvas_size, canvas_size\n\t\t\t);\n\n\t\tif (1) { // Use inline CSS?\n\t\t\tfprintf(fout, \"<defs>\\n\");\n\t\t\tfprintf(fout, \"<style type=\\\"text/css\\\"><![CDATA[\\n\");\n\n\t\t\tfprintf(fout, \"path{ shape-rendering : crispEdges; }\\n\");\n\n\t\t\tfprintf(fout, \"]]></style>\\n\");\n\n\t\t\tfprintf(fout, \"</defs>\\n\");\n\n\t\t\tif (animate == 1) {\n\t\t\t\tfprintf(fout, \"<style>\\n\");\n\t\t\t\tfprintf(fout, \"@keyframes try1 {\\n\");\n\t\t\t\tfprintf(fout, \"\\t0%%   {  --dvo: yellow;}\\n\");\n\t\tfprintf(fout, \"<animate xlink:href=\\\"#incident_ray\\\"  attributeName=\\\"x1\\\" from=\\\"0\\\" to=\\\"800\\\" begin=\\\"0s\\\" dur=\\\"10s\\\" fill=\\\"freeze\\\">\\n\");\n\t\t\t\tfprintf(fout, \"\\t10%%  {  --dvo: blue;}\\n\");\n\t\t\t\tfprintf(fout, \"\\t20%%  {  --dvo: green;}\\n\");\n\t\t\t\tfprintf(fout, \"\\t40%%  {  --dvo: red;}\\n\");\n\t\t\t\tfprintf(fout, \"\\t100%% {  --dvo: orange;}\\n\");\n\t\t\t\tfprintf(fout, \"}\\n\");\n\t\t\t\tfprintf(fout, \"</animate>\\n\");\n\n\t\t\t\tfprintf(fout, \"</style>\\n\");\n\t\t\t}\n\t\t}\n\t}\n\tif(!animate || first_call) {\n\n\t\t// Mirror\n\t\tfprintf(fout, \"<circle cx=\\\"%g\\\" cy=\\\"%g\\\" r=\\\"%g\\\" style=\\\"stroke-width: %g; stroke: black; fill: none;\\\"/>\\n\",\n\t\t\tcc.X(0), cc.Y(0), m_radius*cc.Scale(), mirror_line_width);\n\t\t// Center cross-marks\n\t\tfprintf(fout, \"<line x1=\\\"%g\\\" y1=\\\"%g\\\" x2=\\\"%g\\\" y2=\\\"%g\\\" style=\\\"stroke-width: 0.5; stroke: #888888;\\\"/>\\n\",\n\t\t\tcc.X(0-m_radius/10), cc.Y(0), cc.X(0+m_radius/10), cc.Y(0) );\n\t\tfprintf(fout, \"<line x1=\\\"%g\\\" y1=\\\"%g\\\" x2=\\\"%g\\\" y2=\\\"%g\\\" style=\\\"stroke-width: 0.5; stroke: #888888;\\\"/>\\n\",\n\t\t\tcc.X(0), cc.Y(0-m_radius/10), cc.X(0), cc.Y(0+m_radius/10) );\n\n\t\t// Observer\n\t\tfprintf(fout, \"<circle cx=\\\"%g\\\" cy=\\\"%g\\\" r=\\\"%g\\\" style=\\\"stroke-width: %g; stroke: black; fill: blue;\\\"/>\\n\",\n\t\t\tcc.X(m_ObserverPt.x()), cc.Y(m_ObserverPt.y()), 2.0, line_width);\n\t\t// Center line from observer to Mirror's center's cross-marks\n\t\tfprintf(fout, \"<line x1=\\\"%g\\\" y1=\\\"%g\\\" x2=\\\"%g\\\" y2=\\\"%g\\\" stroke-dasharray=\\\"15, 10, 5, 10\\\" style=\\\"stroke-width: 0.5; stroke: #888888;\\\"/>\\n\",\n\t\t\tcc.X(m_ObserverPt.x()), cc.Y(m_ObserverPt.y()), cc.X(m_MirrorCOCPt.x()), cc.Y(m_MirrorCOCPt.y()) );\n\n\t\t// Tangent Line - from observer, tangent to the mirror and beyond\n\t\tdouble tangent_line_end_X =  m_ObserverPt.x() + cos(to_radians(m_ObserverTangentAng)) * fabs(m_distance * 1.5);\n\t\tdouble tangent_line_end_Y =  m_ObserverPt.y() + sin(to_radians(m_ObserverTangentAng)) * fabs(m_distance * 1.5);\n\t\tfprintf(fout, \"<line x1=\\\"%g\\\" y1=\\\"%g\\\" x2=\\\"%g\\\" y2=\\\"%g\\\" stroke-dasharray=\\\"15, 10, 5, 10\\\" style=\\\"stroke-width: 0.5; stroke: #888888;\\\"/>\\n\",\n\t\t\tcc.X(m_ObserverPt.x()), cc.Y(m_ObserverPt.y()), cc.X(tangent_line_end_X), cc.Y(tangent_line_end_Y) );\n\n\t\t// Normal line\n\t\tif (0)\n\t\tfprintf(fout, \"<line x1=\\\"%g\\\" y1=\\\"%g\\\" x2=\\\"%g\\\" y2=\\\"%g\\\" stroke-dasharray=\\\"10, 3, 3, 3\\\" style=\\\"stroke-width: 0.5; stroke: #000088;\\\"/>\\n\",\n\t\t\tcc.X(0), cc.Y(0), cc.X(m_TangentPt.x() * 1.3), cc.Y(m_TangentPt.y() * 1.3) );\n\n\t\tSVG_OneRayFromSunToObserver_Convex(fout, cc, m_sun_dir-m_sun_width_ang/2, \"bot\", m_ObserverPt, m_SunBotMirrorPt, from_left_border, from_top_border, from_right_border, from_bottom_border, line_width/2);\n\t\tSVG_OneRayFromSunToObserver_Convex(fout, cc, m_sun_dir+m_sun_width_ang/2, \"top\", m_ObserverPt, m_SunTopMirrorPt, from_left_border, from_top_border, from_right_border, from_bottom_border, line_width/2);\n\n#if 0\n\t\tif (m_Pupil_Entrance != 0) {\n\t\t\tfprintf(fout, \"<circle cx=\\\"%g\\\" cy=\\\"%g\\\" r=\\\"%g\\\" style=\\\"stroke-width: 1; stroke: green; fill: green;\\\"/>\\n\",\n\t\t\t\tcc.X(m_PupilBotPt.x()), cc.Y(m_PupilBotPt.y()), 0.5 );\n\t\t\tfprintf(fout, \"<circle cx=\\\"%g\\\" cy=\\\"%g\\\" r=\\\"%g\\\" style=\\\"stroke-width: 1; stroke: green; fill: green;\\\"/>\\n\",\n\t\t\t\tcc.X(m_PupilTopPt.x()), cc.Y(m_PupilTopPt.y()), 0.5 );\n\t\t}\n#endif\n\n\t}\n\n\tif (0 && animate) {\n\t\tfprintf(fout, \"<animate xlink:href=\\\"#incident_ray\\\"  attributeName=\\\"x1\\\" from=\\\"0\\\" to=\\\"800\\\" begin=\\\"0s\\\" dur=\\\"10s\\\" fill=\\\"freeze\\\">\\n\");\n\t\tfprintf(fout, \"</animate>\\n\");\n\t}\n\n\tif (animate) {\n\t\tif (first_call) {\n\t\t\tfprintf(fout, \"<text id=\\\"title_text\\\" x=\\\"%g\\\" y=\\\"%g\\\">Sun altitude=%-5.1g, Observer Angle=\",\n\t\t\t\t       cc.X(m_MirrorCOCPt.x()), cc.Y(m_MirrorCOCPt.y())+30, m_sun_dir);\n\t\t\tif ((m_ObserverReflectedSunTop != BadValue) && (m_ObserverReflectedSunBot != BadValue))\n\t\t\t\tfprintf(fout, \"%-5.1g\", (m_ObserverReflectedSunTop+m_ObserverReflectedSunBot)/2 );\n\t\t\telse\tfprintf(fout, \"(obscured)\");\n\t\t\tfprintf(fout, \", Width=\");\n\t\t\tif ((m_ObserverReflectedSunTop != BadValue) && (m_ObserverReflectedSunBot != BadValue))\n\t\t\t\tfprintf(fout, \"%5.3g\", fabs(m_ObserverReflectedSunTop-m_ObserverReflectedSunBot));\n\t\t\telse\tfprintf(fout, \"(obscured)\");\n\t\t\tfprintf(fout, \"</text>\\n\");\n\n\t\t\tfprintf(fout, \"<script type=\\\"text/ecmascript\\\"><![CDATA[\\n\");\n\t\t\tfprintf(fout, \"var line_data = [\\n\");\n\t\t\tfprintf(fout, \"//\\tvisible, sunray start, sunray end, observer, sunangle, observer_angle\\n\");\n\t\t}\n\n\n\t\tPoint sunpt1_bot, sunpt2_bot(m_SunBotMirrorPt);\n\t\tPoint sunpt1_top, sunpt2_top(m_SunTopMirrorPt);\n\t\tbool obscured_sun_bot = NearlyEqual(m_SunBotMirrorPt.x(),0) && NearlyEqual(m_SunBotMirrorPt.y(),0);\n\t\tbool obscured_sun_top = NearlyEqual(m_SunTopMirrorPt.x(),0) && NearlyEqual(m_SunTopMirrorPt.y(),0);\n\t\tOneRayFromSunToObserver_CalcLines(obscured_sun_bot, m_sun_dir-m_sun_width_ang/2, sunpt1_bot, sunpt2_bot, m_ObserverPt, from_left_border, from_top_border, from_right_border, from_bottom_border);\n\t\tOneRayFromSunToObserver_CalcLines(obscured_sun_top, m_sun_dir+m_sun_width_ang/2, sunpt1_top, sunpt2_top, m_ObserverPt, from_left_border, from_top_border, from_right_border, from_bottom_border);\n\n\t\tfprintf(fout, \"\\t[ %d, %g, %g,%g, %g,%g, %g,%g, %g, %g ],\\n\",\n\t\t\t\tobscured_sun_bot?0:1,\n\t\t\t\tm_sun_dir,\n\t\t\t       \tcc.X(sunpt1_bot.x()), cc.Y(sunpt1_bot.y()),\n\t\t\t       \tcc.X(sunpt2_bot.x()), cc.Y(sunpt2_bot.y()),\n\t\t\t       \tcc.X(m_ObserverPt.x()), cc.Y(m_ObserverPt.y()),\n\t\t      \t\tm_SunBotAng==BadValue?0:m_SunBotAng,\n\t\t\t       \tm_ObserverReflectedSunBot==BadValue?0:m_ObserverReflectedSunBot );\n\t\tfprintf(fout, \"\\t[ %d, %g, %g,%g, %g,%g, %g,%g, %g, %g ],\\n\",\n\t\t\t\tobscured_sun_top?0:1,\n\t\t\t\tm_sun_dir,\n\t\t\t       \tcc.X(sunpt1_top.x()), cc.Y(sunpt1_top.y()),\n\t\t\t       \tcc.X(sunpt2_top.x()), cc.Y(sunpt2_top.y()),\n\t\t\t       \tcc.X(m_ObserverPt.x()), cc.Y(m_ObserverPt.y()),\n\t\t      \t\tm_SunTopAng==BadValue?0:m_SunTopAng,\n\t\t\t       \tm_ObserverReflectedSunTop==BadValue?0:m_ObserverReflectedSunTop );\n\n\n\t\tif (last_call) {\n\t\t\tfprintf(fout, \"];\\n\");\n\t\t\tfprintf(fout, \"var ref_ray_top = document.getElementById(\\\"reflected_ray_top\\\");\\n\");\n\t\t\tfprintf(fout, \"var ref_ray_bot = document.getElementById(\\\"reflected_ray_bot\\\");\\n\");\n\t\t\tfprintf(fout, \"var inc_ray_top = document.getElementById(\\\"incident_ray_top\\\");\\n\");\n\t\t\tfprintf(fout, \"var inc_ray_bot = document.getElementById(\\\"incident_ray_bot\\\");\\n\");\n\t\t\tfprintf(fout, \"var title_text  = document.getElementById(\\\"title_text\\\");\\n\");\n\n\t\t\tfprintf(fout, \"var id = setInterval(intervalCallback, 250);\\n\");\n\t\t\tfprintf(fout, \"var row_index = 0;\\n\");\n\t\t\tfprintf(fout, \"function intervalCallback() {\\n\");\n\t\t\tfprintf(fout, \"\\tif(row_index >= line_data.length) row_index = 0;\\n\");\n\t\t\tfprintf(fout, \"\\tvar bot_i = row_index;\\n\");\n\t\t\tfprintf(fout, \"\\tvar top_i = row_index+1;\\n\");\n\t\t\tfprintf(fout, \"\\trow_index += 2;\\n\");\n\t\t\tfprintf(fout, \"\\tinc_ray_bot.setAttribute('x1',line_data[bot_i][2]);\\n\");\n\t\t\tfprintf(fout, \"\\tinc_ray_bot.setAttribute('y1',line_data[bot_i][3]);\\n\");\n\t\t\tfprintf(fout, \"\\tinc_ray_bot.setAttribute('x2',line_data[bot_i][4]);\\n\");\n\t\t\tfprintf(fout, \"\\tinc_ray_bot.setAttribute('y2',line_data[bot_i][5]);\\n\");\n\t\t\tfprintf(fout, \"\\tref_ray_bot.setAttribute('visibility',line_data[bot_i][0] ? 'visible' : 'hidden' );\\n\");\n\t\t\tfprintf(fout, \"\\tif (line_data[row_index][0]) {\\n\");\n\t\t\tfprintf(fout, \"\\t\\tref_ray_bot.setAttribute('x1',line_data[bot_i][4]);\\n\");\n\t\t\tfprintf(fout, \"\\t\\tref_ray_bot.setAttribute('y1',line_data[bot_i][5]);\\n\");\n\t\t\tfprintf(fout, \"\\t\\tref_ray_bot.setAttribute('x2',line_data[bot_i][6]);\\n\");\n\t\t\tfprintf(fout, \"\\t\\tref_ray_bot.setAttribute('y2',line_data[bot_i][7]);\\n\");\n\t\t\tfprintf(fout, \"\\t}\\n\");\n\t\t\tfprintf(fout, \"\\trow_index++;\\n\");\n\t\t\tfprintf(fout, \"\\tinc_ray_top.setAttribute('x1',line_data[top_i][2]);\\n\");\n\t\t\tfprintf(fout, \"\\tinc_ray_top.setAttribute('y1',line_data[top_i][3]);\\n\");\n\t\t\tfprintf(fout, \"\\tinc_ray_top.setAttribute('x2',line_data[top_i][4]);\\n\");\n\t\t\tfprintf(fout, \"\\tinc_ray_top.setAttribute('y2',line_data[top_i][5]);\\n\");\n\t\t\tfprintf(fout, \"\\tref_ray_top.setAttribute('visibility',line_data[top_i][0] ? 'visible' : 'hidden' );\\n\");\n\t\t\tfprintf(fout, \"\\tif (line_data[row_index][0]) {\\n\");\n\t\t\tfprintf(fout, \"\\t\\tref_ray_top.setAttribute('x1',line_data[top_i][4]);\\n\");\n\t\t\tfprintf(fout, \"\\t\\tref_ray_top.setAttribute('y1',line_data[top_i][5]);\\n\");\n\t\t\tfprintf(fout, \"\\t\\tref_ray_top.setAttribute('x2',line_data[top_i][6]);\\n\");\n\t\t\tfprintf(fout, \"\\t\\tref_ray_top.setAttribute('y2',line_data[top_i][7]);\\n\");\n\t\t\tfprintf(fout, \"\\t}\\n\");\n\t\t\tfprintf(fout, \"\\trow_index++;\\n\");\n\t\t\tfprintf(fout, \"\\tvar build_str='Radius='.concat((%g), ', Distance=', (%g), ' ');\\n\", m_radius, m_distance);\n\t\t\tfprintf(fout, \"\\tvar sun_angle=(line_data[top_i][1]+line_data[bot_i][1])/2;\\n\");\n\t\t\tfprintf(fout, \"\\tvar obs_angle=(line_data[top_i][8]+line_data[bot_i][9])/2;\\n\");\n\t\t\tfprintf(fout, \"\\tvar obs_width=Math.abs(line_data[top_i][9]-line_data[bot_i][9])/2;\\n\");\n\t\t\tfprintf(fout, \"\\ttitle_text.textContent=build_str.concat('Sun altitude=',(sun_angle).toFixed(2), ', Observer Angle=', line_data[top_i][0] ? (obs_angle).toFixed(2) : 'Obscured', ', Width=', (obs_width).toFixed(2));\\n\");\n\t\t\tfprintf(fout, \"}\\n\");\n\n\t\t\tfprintf(fout, \"// ]]>\\n</script>\\n\");\n\t\t}\n\t}\n\n\tif(last_call) fprintf(fout, \"</svg>\\n\");\n}\n\n\n\n\nint brighttable()\n{\n    TheData td1;\n    \n    td1.m_radius = 100;\n    td1.m_IsConvex = true;\n    td1.m_ObserverPt.y(0);\n\n    static const double distances[] = { 0.1,0.2,0.5,1,2,5,10,20,50,100,200,500,1000,2000,5000,10000,20000,50000,100000,200000,500000,1000000,2000000,5000000};\n    const int num_distances = sizeof(distances)/sizeof(distances[0]);\n    static const int sun_angle_table[] = { 0, 1, 2, 5, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180 };\n    const int num_sun_angles = sizeof(sun_angle_table)/sizeof(sun_angle_table[0]);\n\n    double results[num_distances][num_sun_angles]; // larger than needed (hopefully)\n    for (int ii=0; ii<num_distances; ii++) for (int jj=0; jj<num_sun_angles; jj++) results[ii][jj] = BadValue;\n\n    for (int distance_index=0; distance_index < num_distances; distance_index++) {\n        double distance = distances[distance_index];\n        td1.m_ObserverPt.x(100 + distance);\n\n        for (int sun_angle_index=0; sun_angle_index < num_sun_angles; sun_angle_index++) {\n            double sun_angle = sun_angle_table[sun_angle_index];\n            td1.m_sun_dir = sun_angle;\n\n            double normal_mid, normal_bot, normal_top;\n            bool success1 = SearchForSkyAng_Convex(td1, td1.m_sun_dir, normal_mid, td1.m_SunMidAng, td1.m_ObserverReflectedSunMid, td1.m_SunMidMirrorPt);\n            double target_sun_bot_ang = td1.m_SunMidAng - td1.m_sun_width_ang/2;\n            double target_sun_top_ang = td1.m_SunMidAng + td1.m_sun_width_ang/2;\n            bool success2 = SearchForSkyAng_Convex(td1, target_sun_bot_ang, normal_bot, td1.m_SunBotAng, td1.m_ObserverReflectedSunBot, td1.m_SunBotMirrorPt);\n            bool success3 = SearchForSkyAng_Convex(td1, target_sun_top_ang, normal_top, td1.m_SunTopAng, td1.m_ObserverReflectedSunTop, td1.m_SunTopMirrorPt);\n\n            td1.m_Brightness2 = ApparentWidth_ang( td1.m_SunTopMirrorPt, td1.m_SunBotMirrorPt, td1.m_ObserverPt ) / td1.m_sun_width_ang;\n\n            if (td1.m_Brightness2 != BadValue) {\n                results[distance_index][sun_angle_index] = td1.m_Brightness2;\n            }\n        }\n    }\n\n\n    printf(\"Relative intensity (in ppm)\\n\");\n    printf(\"%9s\", \" \");\n    for (int jj=0; jj<num_sun_angles; jj++) printf(\"%6d \", sun_angle_table[jj]);\n    printf(\"\\n\");\n\n    for (int ii=0; ii<num_distances; ii++) {\n        if (distances[ii] < 1) printf(\"%7.1f: \", distances[ii]);\n        else                   printf(\"%7.0f: \", distances[ii]);\n        for (int jj=0; jj<num_sun_angles; jj++) {\n            if (results[ii][jj] == BadValue) printf(\"%6s \", \" - \");\n            else {\n                char buffer[20];\n                sprintf(buffer,\"%6d\",  int(results[ii][jj] * 1e6) );\n                printf(\"%6s \", buffer);\n            }\n        }\n        printf(\"\\n\");\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "6f92d74aa2e1c8cfe145d427e916b04996ac98ee", "size": 153589, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "smraytrc.cpp", "max_stars_repo_name": "dvodesu/smraytrc", "max_stars_repo_head_hexsha": "5655ad812b863dc5573e13649784842e7068b240", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "smraytrc.cpp", "max_issues_repo_name": "dvodesu/smraytrc", "max_issues_repo_head_hexsha": "5655ad812b863dc5573e13649784842e7068b240", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "smraytrc.cpp", "max_forks_repo_name": "dvodesu/smraytrc", "max_forks_repo_head_hexsha": "5655ad812b863dc5573e13649784842e7068b240", "max_forks_repo_licenses": ["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.6248788368, "max_line_length": 222, "alphanum_fraction": 0.5918197267, "num_tokens": 43212, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189121808099, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.45587958465434203}}
{"text": "#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include <libshm/c/shm.h>\n\n#include \"passive.hpp\"\n#include \"world.hpp\"\n#include \"engine.hpp\"\n#include \"force.hpp\"\n\nnamespace cuauv {\nnamespace fishbowl {\n\ndouble clamp(double x, double a, double b) {\n    return std::min(std::max(x, a), b);\n}\n\nEigen::Vector3d clamp(const Eigen::Vector3d& x, const Eigen::Vector3d& a, const Eigen::Vector3d& b)\n{\n    return Eigen::Vector3d(clamp(x[0], a[0], b[0]), clamp(x[1], a[1], b[1]), clamp(x[2], a[2], b[2]));\n}\n\ngravity::gravity(world& w)\n    : w(w)\n{\n}\n\nscrew gravity::on(entity_id id)\n{\n    return screw(Eigen::Vector3d(0, 0, w.get_entity(id).get_m() * 9.81), Eigen::Vector3d(0, 0, 0));\n}\n\nvoid gravity::step(double delta)\n{\n}\n\nturbulence::turbulence(const Eigen::Vector3d& fa, const Eigen::Vector3d& fb, std::uniform_real_distribution<double> fwd, const Eigen::Vector3d& ta, const Eigen::Vector3d& tb, std::uniform_real_distribution<double> twd)\n    : fa(fa)\n    , fb(fb)\n    , fwd(fwd)\n    , ta(ta)\n    , tb(tb)\n    , twd(twd)\n    , f(0, 0, 0)\n    , t(0, 0, 0)\n{\n}\n\nscrew turbulence::on(entity_id id)\n{\n    return screw(f, t);\n}\n\nvoid turbulence::step(double delta)\n{\n    f += Eigen::Vector3d(fwd(gen), fwd(gen), fwd(gen)) * delta;\n    t += Eigen::Vector3d(twd(gen), twd(gen), twd(gen)) * delta;\n    f = clamp(f, fa, fb);\n    t = clamp(t, ta, tb);\n}\n\nbuoyancy::buoyancy(const Eigen::Quaterniond& q, double s, const Eigen::Vector3d& x)\n    : q(q)\n    , s(s)\n    , x(x)\n{\n}\n\nscrew buoyancy::on()\n{\n    const Eigen::Vector3d f = q.conjugate() * Eigen::Vector3d(0, 0, -s);\n    const Eigen::Vector3d t(x.cross(f));\n\n    return screw(f, t);\n}\n\nvoid buoyancy::step(double delta)\n{\n}\n\ndrag::drag(const Eigen::Quaterniond& q, const Eigen::Vector3d& v, const Eigen::Vector3d& w, const Eigen::Vector3d& x, const Eigen::Vector3d& n, double c, double a)\n    : q(q)\n    , v(v)\n    , w(w)\n    , x(x)\n    , n(n)\n    , t(x.cross(n))\n    , c(c)\n    , a(a)\n{\n}\n\nscrew drag::on()\n{\n    const double vs = (q.conjugate() * v + w.cross(x)).dot(n);\n    // Fd = .5 * p * v^2 * c * a\n    // assume p (mass density) of pool water is 1 g/cm^3\n    // though who knows what might be in there...\n    // the force should be opposite the direction of velocity\n    double f = (vs > 0 ? -1 : 1) * 0.5 * 1000 * pow(vs, 2) * c * a;\n    return screw(n * f, t * f);\n}\n\nvoid drag::step(double delta)\n{\n}\n\n} // namespace fishbowl\n} // namespace cuauv\n", "meta": {"hexsha": "9f38022febc76bcebec912d40e2a5def051546b6", "size": 2402, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "fishbowl/passive.cpp", "max_stars_repo_name": "cuauv/software", "max_stars_repo_head_hexsha": "5ad4d52d603f81a7f254f365d9b0fe636d03a260", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 70.0, "max_stars_repo_stars_event_min_datetime": "2015-11-16T18:04:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T09:04:02.000Z", "max_issues_repo_path": "fishbowl/passive.cpp", "max_issues_repo_name": "cuauv/software", "max_issues_repo_head_hexsha": "5ad4d52d603f81a7f254f365d9b0fe636d03a260", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-08-03T05:13:19.000Z", "max_issues_repo_issues_event_max_datetime": "2016-08-03T06:19:39.000Z", "max_forks_repo_path": "fishbowl/passive.cpp", "max_forks_repo_name": "cuauv/software", "max_forks_repo_head_hexsha": "5ad4d52d603f81a7f254f365d9b0fe636d03a260", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 34.0, "max_forks_repo_forks_event_min_datetime": "2015-12-15T17:29:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-18T14:15:12.000Z", "avg_line_length": 21.8363636364, "max_line_length": 218, "alphanum_fraction": 0.5999167361, "num_tokens": 819, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891130942474, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.45587957982276867}}
{"text": "/**\n * \\file common_header.hpp\n * \\brief The hardware wrapper of the quadruped\n * \\author Maximilien Naveau\n * \\date 2018\n *\n * This file declares the TestBench8Motors class which defines the test\n * bench with 8 motors.\n */\n\n#pragma once\n\n// read some parameters\n#include \"yaml_utils/yaml_cpp_fwd.hpp\"\n\n// For mathematical operation\n#include <Eigen/Eigen>\n\n// manage the exit of the program with ctrl+c\n#include <signal.h>  // manage the ctrl+c signal\n#include <atomic>    // thread safe flag for application shutdown management\n\n// some real_time_tools in order to have a real time control\n#include \"real_time_tools/iostream.hpp\"\n#include \"real_time_tools/spinner.hpp\"\n#include \"real_time_tools/thread.hpp\"\n#include \"real_time_tools/timer.hpp\"\n\nnamespace solo\n{\n/**\n * @brief Vector2d shortcut for the eigen vector of size 1.\n */\ntypedef Eigen::Matrix<double, 1, 1> Vector1d;\n\n/**\n * @brief Vector2d shortcut for the eigen vector of size 2.\n */\ntypedef Eigen::Matrix<double, 2, 1> Vector2d;\n\n/**\n * @brief Vector2d shortcut for the eigen vector of size 6.\n */\ntypedef Eigen::Matrix<double, 6, 1> Vector6d;\n\n/**\n * @brief Vector8d shortcut for the eigen vector of size 8.\n */\ntypedef Eigen::Matrix<double, 8, 1> Vector8d;\n\n/**\n * @brief Vector8d shortcut for the eigen vector of size 12.\n */\ntypedef Eigen::Matrix<double, 12, 1> Vector12d;\n\n}  // namespace solo\n", "meta": {"hexsha": "41036b5307e9c99bd466ee21f576becffcd7f053", "size": 1363, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/solo/common_header.hpp", "max_stars_repo_name": "caoliheng/solo", "max_stars_repo_head_hexsha": "e6d86f54e05977a533c68e30c85a5048a03ab753", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2021-04-26T03:13:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-14T14:06:50.000Z", "max_issues_repo_path": "include/solo/common_header.hpp", "max_issues_repo_name": "caoliheng/solo", "max_issues_repo_head_hexsha": "e6d86f54e05977a533c68e30c85a5048a03ab753", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-07-19T13:54:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-24T08:53:49.000Z", "max_forks_repo_path": "include/solo/common_header.hpp", "max_forks_repo_name": "caoliheng/solo", "max_forks_repo_head_hexsha": "e6d86f54e05977a533c68e30c85a5048a03ab753", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-24T16:13:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-24T16:13:36.000Z", "avg_line_length": 23.9122807018, "max_line_length": 76, "alphanum_fraction": 0.7248716067, "num_tokens": 359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.455808175470272}}
{"text": "/**\n * @file sh_astar.cpp\n * @author Licheng Wen (wenlc@zju.edu.cn)\n * @brief The implement of Spatiotemporal Hybrid-State Astar for single_agent\n * @date 2020-11-12\n *\n * @copyright Copyright (c) 2020\n *\n */\n#include <math.h>\n#include <ompl/base/State.h>\n#include <ompl/base/spaces/DubinsStateSpace.h>\n#include <ompl/base/spaces/ReedsSheppStateSpace.h>\n#include <ompl/base/spaces/SE2StateSpace.h>\n\n#include <boost/functional/hash.hpp>\n#include <eigen3/Eigen/Dense>\n#include <fstream>\n#include <iostream>\ntypedef ompl::base::SE2StateSpace::StateType OmplState;\n\n#include \"hybrid_astar.hpp\"\n#include \"timer.hpp\"\n\nusing libMultiRobotPlanning::HybridAStar;\nusing libMultiRobotPlanning::Neighbor;\nusing libMultiRobotPlanning::PlanResult;\nusing namespace libMultiRobotPlanning;\n\nnamespace Constants {\n// [m] --- The minimum turning radius of the vehicle\nstatic const float r = 3;\nstatic const float deltat = 6.75 / 180.0 * M_PI;\n// [#] --- A movement cost penalty for turning (choosing non straight motion\n// primitives)\nstatic const float penaltyTurning = 1.3;\n// [#] --- A movement cost penalty for reversing (choosing motion primitives >\n// 2)\nstatic const float penaltyReversing = 2.0;\n// [#] --- A movement cost penalty for change of direction (changing from\n// primitives < 3 to primitives > 2)\nstatic const float penaltyCOD = 2.0;\n// map resolution\nstatic const float mapResolution = 2.0;\nstatic const float xyResolution = r * deltat;\nstatic const float yawResolution = deltat;\n\n// width of car\nstatic const float carWidth = 2.0;\n// distance from rear to vehicle front end\nstatic const float LF = 2.0;\n// distance from rear to vehicle back end\nstatic const float LB = 1.0;\n// obstacle default radius\nstatic const float obsRadius = 1;\n\n// R = 3, 6.75 DEG\nconst double dx[] = {r * deltat, r* sin(deltat),  r* sin(deltat),\n                     -r* deltat, -r* sin(deltat), -r* sin(deltat)};\nconst double dy[] = {0, -r*(1 - cos(deltat)), r*(1 - cos(deltat)),\n                     0, -r*(1 - cos(deltat)), r*(1 - cos(deltat))};\nconst double dyaw[] = {0, deltat, -deltat, 0, -deltat, deltat};\n\nstatic inline float normalizeHeadingRad(float t) {\n  if (t < 0) {\n    t = t - 2.f * M_PI * (int)(t / (2.f * M_PI));\n    return 2.f * M_PI + t;\n  }\n\n  return t - 2.f * M_PI * (int)(t / (2.f * M_PI));\n}\n}  // namespace Constants\n\nstruct State {\n  State(double x, double y, double yaw) : x(x), y(y), yaw(yaw) {}\n  State(const State&) = default;\n  State(State&&) = default;\n  State& operator=(const State&) = default;\n  State& operator=(State&&) = default;\n\n  bool operator==(const State& other) const {\n    return std::tie(x, y, yaw) == std::tie(other.x, other.y, other.yaw);\n  }\n\n  friend std::ostream& operator<<(std::ostream& os, const State& s) {\n    return os << \"(\" << s.x << \",\" << s.y << \":\" << s.yaw << \")\";\n  }\n\n  double x;\n  double y;\n  double yaw;\n};\n\nnamespace std {\ntemplate <>\nstruct hash<State> {\n  size_t operator()(const State& s) const {\n    size_t seed = 0;\n    boost::hash_combine(seed, s.x);\n    boost::hash_combine(seed, s.y);\n    boost::hash_combine(seed, s.yaw);\n    return seed;\n  }\n};\n}  // namespace std\n\nusing Action = int;  // Action < 6\n\nclass Environment {\n public:\n  Environment(size_t maxx, size_t maxy, std::unordered_set<State> obstacles,\n              State goal)\n      : m_obstacles(std::move(obstacles)),\n        m_goal(goal)  // NOLINT\n  {\n    m_dimx = (int)maxx / Constants::mapResolution;\n    m_dimy = (int)maxy / Constants::mapResolution;\n    // std::cout << \"env build \" << m_dimx << \" \" << m_dimy << \" \"\n    //           << m_obstacles.size() << std::endl;\n    holonomic_cost_map = std::vector<std::vector<double>>(\n        m_dimx, std::vector<double>(m_dimy, 0));\n    m_goal = State(goal.x, goal.y, Constants::normalizeHeadingRad(goal.yaw));\n    updateCostmap();\n  }\n\n  struct compare_node {\n    bool operator()(const std::pair<State, double>& n1,\n                    const std::pair<State, double>& n2) const {\n      return (n1.second > n2.second);\n    }\n  };\n\n  uint64_t calcIndex(const State& s) {\n    return (uint64_t)(Constants::normalizeHeadingRad(s.yaw) /\n                      Constants::yawResolution) *\n               (m_dimx * Constants::mapResolution / Constants::xyResolution) *\n               (m_dimy * Constants::mapResolution / Constants::xyResolution) +\n           (uint64_t)(s.y / Constants::xyResolution) *\n               (m_dimx * Constants::mapResolution / Constants::xyResolution) +\n           (uint64_t)(s.x / Constants::xyResolution);\n  }\n\n  double admissibleHeuristic(const State& s) {\n    // non-holonomic-without-obstacles heuristic: use a Reeds-Shepp\n    ompl::base::ReedsSheppStateSpace reedsSheppPath(Constants::r);\n    OmplState* rsStart = (OmplState*)reedsSheppPath.allocState();\n    OmplState* rsEnd = (OmplState*)reedsSheppPath.allocState();\n    rsStart->setXY(s.x, s.y);\n    rsStart->setYaw(s.yaw);\n    rsEnd->setXY(m_goal.x, m_goal.y);\n    rsEnd->setYaw(m_goal.yaw);\n    double reedsSheppCost = reedsSheppPath.distance(rsStart, rsEnd);\n    // std::cout << \"ReedsShepps cost:\" << reedsSheppCost << std::endl;\n    // Euclidean distance\n    double euclideanCost =\n        sqrt(pow(m_goal.x - s.x, 2) + pow(m_goal.y - s.y, 2));\n    // std::cout << \"Euclidean cost:\" << euclideanCost << std::endl;\n    // holonomic-with-obstacles heuristic\n    double twoDoffset =\n        sqrt(pow((s.x - (int)s.x) - (m_goal.x - (int)m_goal.x), 2) +\n             pow((s.y - (int)s.y) - (m_goal.y - (int)m_goal.y), 2));\n    double twoDCost = holonomic_cost_map[(int)s.x / Constants::mapResolution]\n                                        [(int)s.y / Constants::mapResolution] -\n                      twoDoffset;\n    // std::cout << \"holonomic cost:\" << twoDCost << std::endl;\n\n    return std::max({reedsSheppCost, euclideanCost, twoDCost});\n  }\n\n  bool isSolution(\n      const State& state, double gscore,\n      std::unordered_map<State, std::tuple<State, Action, double, double>,\n                         std::hash<State>>& _camefrom) {\n    double goal_distance =\n        sqrt(pow(state.x - m_goal.x, 2) + pow(state.y - m_goal.y, 2));\n    if (goal_distance > 2 * (Constants::LB + Constants::LF)) return false;\n\n    ompl::base::ReedsSheppStateSpace reedsSheppSpace(Constants::r);\n    OmplState* rsStart = (OmplState*)reedsSheppSpace.allocState();\n    OmplState* rsEnd = (OmplState*)reedsSheppSpace.allocState();\n    rsStart->setXY(state.x, state.y);\n    rsStart->setYaw(-state.yaw);\n    rsEnd->setXY(m_goal.x, m_goal.y);\n    rsEnd->setYaw(-m_goal.yaw);\n    ompl::base::ReedsSheppStateSpace::ReedsSheppPath reedsShepppath =\n        reedsSheppSpace.reedsShepp(rsStart, rsEnd);\n\n    std::vector<State> path;\n    std::unordered_map<State, std::tuple<State, Action, double, double>,\n                       std::hash<State>>\n        cameFrom;\n    cameFrom.clear();\n    path.emplace_back(state);\n    for (auto pathidx = 0; pathidx < 5; pathidx++) {\n      if (fabs(reedsShepppath.length_[pathidx]) < 1e-6) continue;\n      double deltat, dx, act, cost;\n      switch (reedsShepppath.type_[pathidx]) {\n        case 0:  // RS_NOP\n          continue;\n          break;\n        case 1:  // RS_LEFT\n          deltat = -reedsShepppath.length_[pathidx];\n          dx = Constants::r * sin(-deltat);\n          // dy = Constants::r * (1 - cos(-deltat));\n          act = 2;\n          cost = reedsShepppath.length_[pathidx] * Constants::r *\n                 Constants::penaltyTurning;\n          break;\n        case 2:  // RS_STRAIGHT\n          deltat = 0;\n          dx = reedsShepppath.length_[pathidx] * Constants::r;\n          // dy = 0;\n          act = 0;\n          cost = dx;\n          break;\n        case 3:  // RS_RIGHT\n          deltat = reedsShepppath.length_[pathidx];\n          dx = Constants::r * sin(deltat);\n          // dy = -Constants::r * (1 - cos(deltat));\n          act = 1;\n          cost = reedsShepppath.length_[pathidx] * Constants::r *\n                 Constants::penaltyTurning;\n          break;\n        default:\n          std::cout << \"\\033[1m\\033[31m\"\n                    << \"Warning: Receive unknown ReedsSheppPath type\"\n                    << \"\\033[0m\\n\";\n          break;\n      }\n      if (cost < 0) {\n        cost = -cost * Constants::penaltyReversing;\n        act = act + 3;\n      }\n      State s = path.back();\n      std::vector<std::pair<State, double>> next_path =\n          generatePath(s, act, deltat, dx);\n      // State next_s(s.x + dx * cos(-s.yaw) - dy * sin(-s.yaw),\n      //              s.y + dx * sin(-s.yaw) + dy * cos(-s.yaw),\n      //              Constants::normalizeHeadingRad(s.yaw + deltat));\n      for (auto iter = next_path.begin(); iter != next_path.end(); iter++) {\n        State next_s = iter->first;\n        if (!stateValid(next_s))\n          return false;\n        else {\n          gscore += iter->second;\n          if (!(next_s == path.back())) {\n            cameFrom.insert(std::make_pair<>(\n                next_s,\n                std::make_tuple<>(path.back(), act, iter->second, gscore)));\n          }\n          path.emplace_back(next_s);\n        }\n      }\n    }\n\n    m_goal = path.back();\n    // auto iter = cameFrom.find(getGoal());\n    // do {\n    //   std::cout << \" From \" << std::get<0>(iter->second)\n    //             << \" to Node:\" << iter->first\n    //             << \" with ACTION: \" << std::get<1>(iter->second) << \" cost \"\n    //             << std::get<2>(iter->second) << \" g_score \"\n    //             << std::get<3>(iter->second) << std::endl;\n    //   iter = cameFrom.find(std::get<0>(iter->second));\n    // } while (calcIndex(std::get<0>(iter->second)) != calcIndex(state));\n    // std::cout << \" From \" << std::get<0>(iter->second)\n    //           << \" to Node:\" << iter->first\n    //           << \" with ACTION: \" << std::get<1>(iter->second) << \" cost \"\n    //           << std::get<2>(iter->second) << \" g_score \"\n    //           << std::get<3>(iter->second) << std::endl;\n\n    _camefrom.insert(cameFrom.begin(), cameFrom.end());\n    return true;\n  }\n\n  void getNeighbors(const State& s, Action action,\n                    std::vector<Neighbor<State, Action, double>>& neighbors) {\n    neighbors.clear();\n    for (Action act = 0; act < 6; act++) {  // has 6 directions for Reeds-Shepp\n      double xSucc, ySucc, yawSucc;\n      double g = Constants::dx[0];\n      xSucc = s.x + Constants::dx[act] * cos(-s.yaw) -\n              Constants::dy[act] * sin(-s.yaw);\n      ySucc = s.y + Constants::dx[act] * sin(-s.yaw) +\n              Constants::dy[act] * cos(-s.yaw);\n      yawSucc = Constants::normalizeHeadingRad(s.yaw + Constants::dyaw[act]);\n      if (act != action) {  // penalize turning\n        g = g * Constants::penaltyTurning;\n        if (act >= 3)  // penalize change of direction\n          g = g * Constants::penaltyCOD;\n      }\n      if (act > 3) {  // backwards\n        g = g * Constants::penaltyReversing;\n      }\n      State tempState(xSucc, ySucc, yawSucc);\n      if (stateValid(tempState)) {\n        neighbors.emplace_back(\n            Neighbor<State, Action, double>(tempState, act, g));\n      }\n    }\n  }\n\n  void onExpandNode(const State& s, int /*fScore*/, int /*gScore*/) {\n    Ecount++;\n    // std::cout << \"Expand \" << Ecount << \" new Node:\" << s << std::endl;\n  }\n\n  void onDiscover(const State& s, double fScore, double gScore) {\n    Dcount++;\n    // std::cout << \"Discover \" << Dcount << \"  Node:\" << s << \" f:\" << fScore\n    //           << \" g:\" << gScore << std::endl;\n  }\n\n public:\n  State getGoal() { return m_goal; }\n  int Ecount = 0;\n  int Dcount = 0;\n\n private:\n  bool stateValid(const State& s) {\n    double x_ind = s.x / Constants::mapResolution;\n    double y_ind = s.y / Constants::mapResolution;\n    if (x_ind < 0 || x_ind >= m_dimx || y_ind < 0 || y_ind >= m_dimy)\n      return false;\n\n    Eigen::Matrix2f rot;\n    rot << cos(-s.yaw), -sin(-s.yaw), sin(-s.yaw), cos(-s.yaw);\n    for (auto it = m_obstacles.begin(); it != m_obstacles.end(); it++) {\n      Eigen::Matrix<float, 1, 2> obs;\n      obs << it->x - s.x, it->y - s.y;\n      auto rotated_obs = obs * rot;\n      if (rotated_obs(0) > -Constants::LB - Constants::obsRadius &&\n          rotated_obs(0) < Constants::LF + Constants::obsRadius &&\n          rotated_obs(1) > -Constants::carWidth / 2.0 - Constants::obsRadius &&\n          rotated_obs(1) < Constants::carWidth / 2.0 + Constants::obsRadius)\n        return false;\n    }\n    return true;\n    // Eigen::Matrix2f rot;\n    // double yaw = M_PI / 2;\n    // rot << cos(yaw), -sin(yaw), sin(yaw), cos(yaw);\n    // Eigen::Matrix<float, 1, 2> temp;\n    // temp << 1, 2;\n    // auto ro = temp * rot;\n    // std::cout << ro(0) << ro(1) << std::endl;\n  }\n\n  void updateCostmap() {\n    boost::heap::fibonacci_heap<std::pair<State, double>,\n                                boost::heap::compare<compare_node>>\n        heap;\n    heap.clear();\n\n    std::set<std::pair<int, int>> temp_obs_set;\n    for (auto it = m_obstacles.begin(); it != m_obstacles.end(); it++) {\n      temp_obs_set.insert(\n          std::make_pair((int)it->x / Constants::mapResolution,\n                         (int)it->y / Constants::mapResolution));\n    }\n\n    int goal_x = (int)m_goal.x / Constants::mapResolution;\n    int goal_y = (int)m_goal.y / Constants::mapResolution;\n    heap.push(std::make_pair(State(goal_x, goal_y, 0), 0));\n\n    while (!heap.empty()) {\n      std::pair<State, double> node = heap.top();\n      heap.pop();\n\n      int x = node.first.x;\n      int y = node.first.y;\n      for (int dx = -1; dx <= 1; dx++)\n        for (int dy = -1; dy <= 1; dy++) {\n          if (dx == 0 && dy == 0) continue;\n          int new_x = x + dx;\n          int new_y = y + dy;\n          if (new_x == goal_x && new_y == goal_y) continue;\n          if (new_x >= 0 && new_x < m_dimx && new_y >= 0 && new_y < m_dimy &&\n              holonomic_cost_map[new_x][new_y] == 0 &&\n              temp_obs_set.find(std::make_pair(new_x, new_y)) ==\n                  temp_obs_set.end()) {\n            holonomic_cost_map[new_x][new_y] =\n                holonomic_cost_map[x][y] +\n                sqrt(pow(dx * Constants::mapResolution, 2) +\n                     pow(dy * Constants::mapResolution, 2));\n            heap.push(std::make_pair(State(new_x, new_y, 0),\n                                     holonomic_cost_map[new_x][new_y]));\n          }\n        }\n    }\n\n    // for (size_t i = 0; i < m_dimx; i++) {\n    //   for (size_t j = 0; j < m_dimy; j++)\n    //     std::cout << holonomic_cost_map[i][j] << \"\\t\";\n    //   std::cout << std::endl;\n    // }\n  }\n\n  std::vector<std::pair<State, double>> generatePath(State startState, int act,\n                                                     double deltaSteer,\n                                                     double deltaLength) {\n    std::vector<std::pair<State, double>> result;\n    double xSucc, ySucc, yawSucc, dx, dy, dyaw, ratio;\n    result.emplace_back(std::make_pair<>(startState, 0));\n    if (act == 0 || act == 3) {\n      for (size_t i = 0; i < (size_t)(deltaLength / Constants::dx[act]); i++) {\n        State s = result.back().first;\n        xSucc = s.x + Constants::dx[act] * cos(-s.yaw) -\n                Constants::dy[act] * sin(-s.yaw);\n        ySucc = s.y + Constants::dx[act] * sin(-s.yaw) +\n                Constants::dy[act] * cos(-s.yaw);\n        yawSucc = Constants::normalizeHeadingRad(s.yaw + Constants::dyaw[act]);\n        result.emplace_back(\n            std::make_pair<>(State(xSucc, ySucc, yawSucc), Constants::dx[0]));\n      }\n      ratio = (deltaLength -\n               (int)(deltaLength / Constants::dx[act]) * Constants::dx[act]) /\n              Constants::dx[act];\n      dyaw = 0;\n      dx = ratio * Constants::dx[act];\n      dy = 0;\n    } else {\n      for (size_t i = 0; i < (size_t)(deltaSteer / Constants::dyaw[act]); i++) {\n        State s = result.back().first;\n        xSucc = s.x + Constants::dx[act] * cos(-s.yaw) -\n                Constants::dy[act] * sin(-s.yaw);\n        ySucc = s.y + Constants::dx[act] * sin(-s.yaw) +\n                Constants::dy[act] * cos(-s.yaw);\n        yawSucc = Constants::normalizeHeadingRad(s.yaw + Constants::dyaw[act]);\n        result.emplace_back(\n            std::make_pair<>(State(xSucc, ySucc, yawSucc),\n                             Constants::dx[0] * Constants::penaltyTurning));\n      }\n      ratio =\n          (deltaSteer -\n           (int)(deltaSteer / Constants::dyaw[act]) * Constants::dyaw[act]) /\n          Constants::dyaw[act];\n      dyaw = ratio * Constants::dyaw[act];\n      dx = Constants::r * sin(dyaw);\n      dy = -Constants::r * (1 - cos(dyaw));\n      if (act == 2 || act == 5) {\n        dx = -dx;\n        dy = -dy;\n      }\n    }\n    State s = result.back().first;\n    xSucc = s.x + dx * cos(-s.yaw) - dy * sin(-s.yaw);\n    ySucc = s.y + dx * sin(-s.yaw) + dy * cos(-s.yaw);\n    yawSucc = Constants::normalizeHeadingRad(s.yaw + dyaw);\n    result.emplace_back(std::make_pair<>(State(xSucc, ySucc, yawSucc),\n                                         ratio * Constants::dx[0]));\n    // std::cout << \"Have generate \" << result.size() << \" path segments:\\n\\t\";\n    // for (auto iter = result.begin(); iter != result.end(); iter++)\n    //   std::cout << iter->first << \":\" << iter->second << \"->\";\n    // std::cout << std::endl;\n\n    return result;\n  }\n\n  int m_dimx;\n  int m_dimy;\n  std::unordered_set<State> m_obstacles;\n  std::vector<std::vector<double>> holonomic_cost_map;\n  State m_goal;\n};\n\nint main() {\n  // TODO: read map info from yaml\n  std::unordered_set<State> obs;\n  obs.insert(State(6.66799, 9.66868, 0));\n  obs.insert(State(6.86099, 6.20241, 0));\n  obs.insert(State(6.2493, 3.45836, 0));\n  obs.insert(State(6.93504, 0.747862, 0));\n  obs.insert(State(6.81566, 4.75936, 0));\n  State goal(13, 10, -M_PI);\n  State start(2, 2, 0);\n  Environment env(16, 16, obs, goal);\n  HybridAStar<State, Action, double, Environment> hybridAStar(env);\n  PlanResult<State, Action, double> solution;\n  Timer timer;\n  bool searchSuccess = hybridAStar.search(start, solution);\n  timer.stop();\n\n  std::string outputFile = \"output_h.yaml\";\n  std::ofstream out(outputFile);\n  if (searchSuccess) {\n    std::cout << \"\\033[1m\\033[32m Succesfully find a path! \\033[0m\\n\";\n    std::cout << \"Solution get \" << solution.states.size() << \" states \"\n              << solution.actions.size() << \" moves\\n\"\n              << \"Runtime: \" << timer.elapsedSeconds() << std::endl;\n\n    out << \"schedule:\" << std::endl;\n    out << \"  agent1:\" << std::endl;\n    for (size_t i = 0; i < solution.states.size(); ++i) {\n      out << \"    - x: \" << solution.states[i].first.x << std::endl\n          << \"      y: \" << solution.states[i].first.y << std::endl\n          << \"      yaw: \" << solution.states[i].first.yaw << std::endl\n          << \"      t: \" << i << std::endl;\n    }\n    // for (auto iter = solution.states.begin(); iter != solution.states.end();\n    //      iter++)\n    //   std::cout << iter->first << \":\" << iter->second << \"->\";\n    // std::cout << std::endl;\n    // for (auto iter = solution.actions.begin(); iter !=\n    // solution.actions.end();\n    //      iter++)\n    //   std::cout << iter->first << \":\" << iter->second << \"->\";\n    // std::cout << std::endl;\n    std::cout << \"Solution: gscore/cost:\" << solution.cost\n              << \"\\t fmin:\" << solution.fmin << \"\\n\\rDiscover \" << env.Dcount\n              << \" Nodes and Expand \" << env.Ecount << \" Nodes.\" << std::endl;\n  } else {\n    std::cout << \"\\033[1m\\033[31m Fail to find a path \\033[0m\\n\";\n  }\n}", "meta": {"hexsha": "7c66a8ce1c359ce0d42c38de409472d5c63771b1", "size": 19381, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sh_astar.cpp", "max_stars_repo_name": "LIJUNCHENG001/CL-CBS", "max_stars_repo_head_hexsha": "b353759a3e34962ee57475a031026416fbbc2382", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 101.0, "max_stars_repo_stars_event_min_datetime": "2020-10-29T05:01:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T09:17:08.000Z", "max_issues_repo_path": "src/sh_astar.cpp", "max_issues_repo_name": "mieximiemie/CL-CBS", "max_issues_repo_head_hexsha": "b353759a3e34962ee57475a031026416fbbc2382", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-06-25T17:48:40.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T02:57:54.000Z", "max_forks_repo_path": "src/sh_astar.cpp", "max_forks_repo_name": "mieximiemie/CL-CBS", "max_forks_repo_head_hexsha": "b353759a3e34962ee57475a031026416fbbc2382", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 29.0, "max_forks_repo_forks_event_min_datetime": "2020-11-23T05:09:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T09:17:10.000Z", "avg_line_length": 37.7062256809, "max_line_length": 80, "alphanum_fraction": 0.5586399051, "num_tokens": 5619, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.45580816919657846}}
{"text": "// Petter Strandmark 2013.\n//\n// Rough test of sym-ildl.\n//\n#include <iostream>\n\n#include <catch.hpp>\n\n#include <Eigen/Dense>\n#include <Eigen/LU>\n#include <Eigen/Sparse>\n\n#ifndef USE_SYM_ILDL\n\nTEST_CASE(\"no-ildl-available\")\n{\n\tSUCCEED();\n}\n\n#else\n\nextern \"C\" {\n\t#include \"matrix.h\"\n\t#include \"matrix2.h\"\n\t#include \"sparse2.h\"\n\n\t// Evil library...\n\t#undef min\n\t#undef max\n\t#undef catch\n\t#undef input\n}\n\n#include <lilc_matrix.h>\n\n#include <spii/spii.h>\n#include <spii/sym-ildl-conversions.h>\n\ntemplate<typename EigenMat>\nMAT* Eigen_to_Meschach(const EigenMat& eigen_matrix)\n{\n\tint m = static_cast<int>(eigen_matrix.rows());\n\tint n = static_cast<int>(eigen_matrix.cols());\n\n\tauto A = m_get(m, 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\treturn A;\n}\n\nTEST_CASE(\"ildl-sym\")\n{\n\tusing namespace std;\n\tusing namespace Eigen;\n\tusing namespace spii;\n\n\tconst int n = 4;\n\n\tMatrixXd Aorg(n, n);\n\tAorg.row(0) << 1, 2, 3, 1;\n\tAorg.row(1) << 2, 6, 1, 8;\n\tAorg.row(2) << 3, 1, 7, 6;\n\tAorg.row(3) << 1, 8, 6, 6;\n\tREQUIRE((Aorg - Aorg.transpose()).norm() == 0);\n\n\t// Create sym-ildl matrix.\n\tlilc_matrix<double> Alilc;\n\teigen_to_lilc(Aorg, &Alilc);\n\n\t// Convert matrix to Meschach format.\n\tauto Amat = Eigen_to_Meschach(Aorg);\n\tspii_at_scope_exit(m_free(Amat));\n\n\tcerr << \"Original A = \" << endl;\n\tcerr << Aorg << endl;\n\tcerr << \"sym-ildl A = \" << endl;\n\tcerr << Alilc << endl;\n\tcerr << \"Meschach A = \" << endl;\n\tm_foutput(stderr, Amat);\n\n\tcerr << endl << endl;\n\n\t// Factorize the matrix.\n\tPERM* pivot  = px_get(4);\n\tspii_at_scope_exit(px_free(pivot));\n\tPERM* block = px_get(4);\n\tspii_at_scope_exit(px_free(block));\n\tBKPfactor(Amat, pivot, block);\n\n\t// Print the results.\n\tcerr << \"Meschach factorization = \" << endl;\n\tm_foutput(stderr, Amat);\n\tpx_foutput(stderr, block);\n\tpx_foutput(stderr, pivot);\n\tcerr << endl << endl;\n\n\tcerr << \"A is \" << Alilc.n_rows() << \" by \" << Alilc.n_cols() << \" with \" << Alilc.nnz() << \" non-zeros.\" << endl;\n\tlilc_matrix<double> Llilc;\t     //<The lower triangular factor of A.\n\tvector<int> perm;\t         //<A permutation vector containing all permutations on A.\n\tperm.reserve(Alilc.n_cols());\n\tblock_diag_matrix<double> Dblockdiag; //<The diagonal factor of A.\n\tAlilc.sym_equil();\n\tAlilc.sym_rcm(perm);\n\tAlilc.sym_perm(perm);\n\tconst double fill_factor = 1.0;\n\tconst double tol         = 0.001; \n\n\tAlilc.ildl(Llilc, Dblockdiag, perm, fill_factor, tol, 1.0);\n\n\tcerr << \"L is \" << Llilc.n_rows() << \" by \" << Llilc.n_cols() << \" with \" << Llilc.nnz() << \" non-zeros.\" << endl;\n\tcerr << Llilc << endl;\n\tcerr << \"D is \" << Dblockdiag.n_rows() << \" by \" << Dblockdiag.n_cols() << \" with \" << Dblockdiag.nnz() << \" non-zeros.\" << endl;\n\tcerr << Dblockdiag << endl;\n\n\tcerr << \"P = \";\n\tfor (auto val: perm) {\n\t\tcerr << val << \" \";\n\t}\n\tcerr << endl;\n\n\tMyPermutation P(perm);\n\tMatrixXd I(perm.size(), perm.size());\n\tI.setIdentity();\n\tcerr << \"P = \" << endl << (P * I) << endl;\n\n\tauto L = lilc_to_eigen(Llilc);\n\tcerr << \"L = \" << endl << L << endl;\n\n\tauto D = block_diag_to_eigen(Dblockdiag);\n\tcerr << \"D = \" << endl << D << endl;\n\n\tauto S = diag_to_eigen(Alilc.S);\n\tcerr << \"S = \" << endl << S.toDenseMatrix() << endl;\n\n\tauto Btmp = lilc_to_eigen(Alilc, true);\n\tcerr << \"B = \" << endl << Btmp << endl;\n\tcerr << \"P^T * S * A * S * P = \" << endl << (P.transpose() * (S * Aorg * S) * P) << endl;\n\tcerr << \"L * D * L^T = \" << endl << (L * D * L.transpose()) << endl;\n\n\tcerr << endl << endl;\n\tauto SiPLDLtPtSi = S.inverse() * (P * L * D * L.transpose() * P.transpose()) * S.inverse();\n\tcerr << \" S^-1 * P * L * D * L^T * P^T * S^-1 = \" << endl \n\t     << SiPLDLtPtSi << endl;\n\n\tREQUIRE((SiPLDLtPtSi - Aorg).norm() <= 1e-6);\n\n\tcerr << endl << endl;\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-10;\n\n\t// Extract the block diagonal matrix.\n\tbool onebyone;\n\tfor (int i = 0; i < n; i = (onebyone ? i+1 : i+2) ) {\n\t\tonebyone = (i == n-1 || D(i+1, i) == 0.0);\n\n\t\tif ( onebyone ) {\n\t\t    B(i, i) = D(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 - lambda(i);\n\t\t\t}\n\t\t\tQ(i, i) = 1;\n\t\t}\n\t\telse {\n\t\t    auto a11 = D(i, i);\n\t\t    auto a22 = D(i+1, i+1);\n\t\t    auto a12 = D(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 - 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\tcerr << \"B = \\n\" << B << endl << endl;\n\tcerr << \"lambda = \" << tau.transpose() << endl << endl;\n\tcerr << \"tau = \" << tau.transpose() << endl << endl;\n\tcerr << \"Q = \\n\" << Q << endl << endl;\n\tcerr << \"Q*lambda*Q^T = \\n\" << Q * lambda.asDiagonal() * Q.transpose() << endl << endl;\n\n\t// Check that the block-wise eigendecomposition was correct.\n\tCHECK(((B - Q * lambda.asDiagonal() * Q.transpose()).norm()) < 1e-10);\n\n\tMatrixXd F = Q * tau.asDiagonal() * Q.transpose();\n\tcerr << \"F = Q*tau*Q^T = \\n\" << F << endl << endl;\n\tcerr << \"B + F = \\n\" << B + F << endl << endl;\n\n\n\t// Check that solver works correctly.\n\tVectorXd b(4);\n\tb(0) = 2.0;\n\tb(1) = 1.0;\n\tb(2) = 3.0;\n\tb(3) = -1.0;\n\n\tVectorXd xorg = Aorg.lu().solve(b);\n\tVectorXd x;\n\tsolve_system_ildl(Dblockdiag, Llilc, S, P, b, &x);\n\tCAPTURE(xorg.transpose());\n\tCAPTURE(x.transpose());\n\tCHECK( (xorg - x).norm() <= 1e-6 );\n}\n\nTEST_CASE(\"ildl-sym-sparse\")\n{\n\tusing namespace std;\n\tusing namespace Eigen;\n\tusing namespace spii;\n\n\tint n = 8;\n\tvector<Triplet<double>> triplets;\n\tauto add_element = [&](int i, int j, double v)\n\t{\n\t\ttriplets.emplace_back(i - 1, j- 1, v);\n\t};\n\t// Matlab indices which start at 1.\n\tadd_element(1,1, 19);\n\tadd_element(2,1,  7);\n\tadd_element(4,1, 20);\n\tadd_element(6,1,-15);\n\tadd_element(8,1, -6);\n\tadd_element(1,2,  7);\n\tadd_element(2,2, -8);\n\tadd_element(4,2,  4);\n\tadd_element(6,2, -3);\n\tadd_element(8,2, -3);\n\tadd_element(4,3,  4);\n\tadd_element(8,3,  1);\n\tadd_element(1,4, 20);\n\tadd_element(2,4,  4);\n\tadd_element(3,4,  4);\n\tadd_element(4,4, 23);\n\tadd_element(6,4,-12);\n\tadd_element(8,4,  4);\n\tadd_element(5,5,-10);\n\tadd_element(1,6,-15);\n\tadd_element(2,6, -3);\n\tadd_element(4,6,-12);\n\tadd_element(6,6, -1);\n\tadd_element(7,7, -1);\n\tadd_element(1,8, -6);\n\tadd_element(2,8, -3);\n\tadd_element(3,8,  1);\n\tadd_element(4,8,  4);\n\n\tSparseMatrix<double> Aorg(n, n);\n\tAorg.setFromTriplets(begin(triplets), end(triplets));\n\n\tcerr << Aorg << endl;\n\n\t// Create sym-ildl matrix.\n\tlilc_matrix<double> Alilc;\n\teigen_to_lilc(Aorg, &Alilc);\n\n\tSparseMatrix<double> A;\n\tlilc_to_eigen(Alilc, &A, true);\n\n\tcerr << \"Original A = \" << endl;\n\tcerr << Aorg << endl;\n\tcerr << \"sym-ildl A = \" << endl;\n\tcerr << Alilc << endl;\n\tcerr << \"A converted back = \" << endl;\n\tcerr << A << endl;\n\n\tSparseMatrix<double> Zero = A - Aorg;\n\tCHECK(Zero.sum() == 0);\n\n\tcerr << \"A is \" << Alilc.n_rows() << \" by \" << Alilc.n_cols() << \" with \" << Alilc.nnz() << \" non-zeros.\" << endl;\n\tlilc_matrix<double> Llilc;\t     //<The lower triangular factor of A.\n\tvector<int> perm;\t         //<A permutation vector containing all permutations on A.\n\tperm.reserve(Alilc.n_cols());\n\tblock_diag_matrix<double> Dblockdiag; //<The diagonal factor of A.\n\tAlilc.sym_equil();\n\tAlilc.sym_rcm(perm);\n\tAlilc.sym_perm(perm);\n\tconst double fill_factor = 1.0;\n\tconst double tol         = 0.001;\n\n\tAlilc.ildl(Llilc, Dblockdiag, perm, fill_factor, tol, 1.0);\n\n\tcerr << \"L is \" << Llilc.n_rows() << \" by \" << Llilc.n_cols() << \" with \" << Llilc.nnz() << \" non-zeros.\" << endl;\n\tcerr << Llilc << endl;\n\tcerr << \"D is \" << Dblockdiag.n_rows() << \" by \" << Dblockdiag.n_cols() << \" with \" << Dblockdiag.nnz() << \" non-zeros.\" << endl;\n\tcerr << Dblockdiag << endl;\n\n\tcerr << \"P = \";\n\tfor (auto val: perm) {\n\t\tcerr << val << \" \";\n\t}\n\tcerr << endl;\n\n\tMyPermutation P(perm);\n\tMatrixXd I(perm.size(), perm.size());\n\tI.setIdentity();\n\tcerr << \"P = \" << endl << (P * I) << endl;\n\n\tauto L = lilc_to_eigen(Llilc);\n\tcerr << \"L = \" << endl << L << endl;\n\n\tSparseMatrix<double> D;\n\tblock_diag_to_eigen(Dblockdiag, &D);\n\tcerr << \"D = \" << endl << D << endl;\n\n\tauto S = diag_to_eigen(Alilc.S);\n\tcerr << \"S = \" << endl << S.toDenseMatrix() << endl;\n\n\tSparseMatrix<double> Btmp;\n\tlilc_to_eigen(Alilc, &Btmp, true);\n\tcerr << \"B = \" << endl << Btmp.toDense() << endl;\n\tcerr << \"P^T * S * A * S * P = \" << endl << (P.transpose() * (S * A.toDense() * S) * P) << endl;\n\tcerr << \"L * D * L^T = \" << endl << (L * D.toDense() * L.transpose()) << endl;\n\n\tcerr << endl << endl;\n\tauto SiPLDLtPtSi = S.inverse() * (P * L * D * L.transpose() * P.transpose()) * S.inverse();\n\tcerr << \" S^-1 * P * L * D * L^T * P^T * S^-1 = \" << endl \n\t     << SiPLDLtPtSi << endl;\n\n\tREQUIRE((SiPLDLtPtSi - Aorg.toDense()).norm() <= 1e-6);\n\n\tcerr << endl << endl;\n}\n\n#endif // #ifndef USE_SYM_ILDL\n", "meta": {"hexsha": "db045f61f6ae5c1612b18a0bacf07b03fd2e1373", "size": 9020, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_ildl.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": "tests/test_ildl.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": "tests/test_ildl.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": 25.4802259887, "max_line_length": 130, "alphanum_fraction": 0.5776053215, "num_tokens": 3210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.5926665999540697, "lm_q1q2_score": 0.4558081691965783}}
{"text": "#include <vector>\n\n//#include <Qt3DIncludes.h>\n#include <GaussIncludes.h>\n#include <ForceSpring.h>\n#include <FEMIncludes.h>\n#include <PhysicalSystemParticles.h>\n//Any extra things I need such as constraints\n#include <ConstraintFixedPoint.h>\n#include <TimeStepperEulerImplicitLinear.h>\n#include <TimeStepperEulerImplicit.h>\n#include <AssemblerParallel.h>\n\n#include <igl/get_seconds.h>\n#include <igl/writeDMAT.h>\n#include <igl/readDMAT.h>\n#include <igl/viewer/Viewer.h>\n#include <igl/readMESH.h>\n#include <igl/unproject_onto_mesh.h>\n\n#include <stdlib.h>\n#include <iostream>\n#include <string>\n#include <sstream>\n#include <string.h>\n#include <json.hpp>\n#include <boost/filesystem.hpp>\n\n\nusing Eigen::VectorXd;\nusing Eigen::Vector3d;\nusing Eigen::VectorXi;\nusing Eigen::MatrixXd;\nusing Eigen::MatrixXi;\nusing Eigen::SparseMatrix;\nusing Eigen::SparseVector;\n\nnamespace fs = boost::filesystem;\nusing json = nlohmann::json;\nusing namespace Gauss;\nusing namespace FEM;\nusing namespace ParticleSystem; //For Force Spring\n\ntypedef PhysicalSystemFEM<double, NeohookeanTet> NeohookeanTets;\ntypedef World<double,\n                        std::tuple<PhysicalSystemParticleSingle<double> *, NeohookeanTets *>,\n                        std::tuple<ForceSpringFEMParticle<double> *>,\n                        std::tuple<ConstraintFixedPoint<double> *> > MyWorld;\ntypedef TimeStepperEulerImplicit<double, AssemblerEigenSparseMatrix<double>,\n AssemblerEigenVector<double> > MyTimeStepper;\n\njson sim_params;\nMatrixXd V;\nMatrixXi F, T;\n\n// Take a start and a range so that we can do this in parallel.\nvoid generateEnergyForPoses(NeohookeanTets *tets, const MatrixXd &displacements, int start, int num, MatrixXd &energy_vec_per_pose) {\n    MyWorld world;\n    world.addSystem(tets);\n    fixDisplacementMin(world, tets, sim_params[\"displacement_axis\"], sim_params[\"displacement_tol\"]);\n    world.finalize();\n\n    for(int i = start; i - start < num && i < displacements.rows(); i++) {\n        // Update the state\n        auto q = mapDOFEigen(tets->getQ(), world);\n        q = displacements.row(i);\n\n        // Compute the energy\n        energy_vec_per_pose.row(i) = tets->getStrainEnergyPerElement(world.getState());\n    }\n}\n\nvoid progress_bar(double progress, int barWidth = 70) {\n    std::cout << \"[\";\n    int pos = barWidth * progress;\n    for (int i = 0; i < barWidth; ++i) {\n        if (i < pos) std::cout << \"=\";\n        else if (i == pos) std::cout << \">\";\n        else std::cout << \" \";\n    }\n    std::cout << \"] \" << int(progress * 100.0) << \" %\\r\";\n    std::cout.flush();\n}\n\nint main(int argc, char **argv) {\n    fs::path displacements_path(argv[1]); // Takes in a path to a matrix containing an array of flattened displacements\n    fs::path mesh_path(argv[2]); // Also takes in a path to the base mesh file.\n    fs::path sim_params_path(argv[3]); // Also takes path to the simulation parameters file\n    \n    fs::path output_dir_path = displacements_path.parent_path();\n\n    std::cout << \"Loading simulation parameters from \" << sim_params_path.string() << std::endl;\n    std::ifstream fin(sim_params_path.string());\n    fin >> sim_params;\n\n    std::cout << \"Loading MESH from \" << mesh_path.string() << std::endl;\n    igl::readMESH(mesh_path.string(), V, T, F);\n\n    std::cout << \"Loading displacements from \" << displacements_path.string() << std::endl;\n    MatrixXd displacements;    \n    igl::readDMAT(displacements_path.string(), displacements);\n\n    // Time to set up the Tets    \n    NeohookeanTets tets(V,T);\n    for(auto element: tets.getImpl().getElements()) {\n        element->setDensity(sim_params[\"density\"]);\n        element->setParameters(sim_params[\"YM\"], sim_params[\"Poisson\"]);\n    }\n\n    // Reserve space for the matrices\n    int n_tets = T.rows();\n    int n_poses = displacements.rows();    \n    MatrixXd energy_vec_per_pose(n_poses, n_tets);\n    // MatrixXd force_vec_per_pose(n_poses, n_tets * 4); // Leave this out for now\n\n    // Generate the data\n    // TODO parallel?\n    std::cout << \"Generating energies\" << std::endl;\n    int n_chunks = 32;\n    int num_per_chunk = displacements.rows() / n_chunks;\n    int n_finished = 0;\n    #pragma omp parallel for\n    for(int i = 0; i < n_chunks + 1; i++) {\n        generateEnergyForPoses(&tets, displacements, i * num_per_chunk, num_per_chunk, energy_vec_per_pose);\n        progress_bar(++n_finished / (double) (n_chunks + 1));\n    }\n    std::cout << std::endl;\n\n    // Save the data\n    fs::path energy_path = output_dir_path / \"energies.dmat\";\n    std::cout << \"Saving energy to \" << energy_path << std::endl;\n    igl::writeDMAT(energy_path.string(), energy_vec_per_pose, false);\n\n    return 0;\n}", "meta": {"hexsha": "a9f6abcb1510ee89452da8af540717b3e8c23f48", "size": 4646, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "archive/generate_data_for_pose/src/main.cpp", "max_stars_repo_name": "ericchen321/AutoDef", "max_stars_repo_head_hexsha": "aad03066d55422592e02281e5c1ea276ab0002d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2019-05-29T03:48:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T11:51:50.000Z", "max_issues_repo_path": "archive/generate_data_for_pose/src/main.cpp", "max_issues_repo_name": "ericchen321/AutoDef", "max_issues_repo_head_hexsha": "aad03066d55422592e02281e5c1ea276ab0002d1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-11-04T12:16:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T23:02:41.000Z", "max_forks_repo_path": "archive/generate_data_for_pose/src/main.cpp", "max_forks_repo_name": "ericchen321/AutoDef", "max_forks_repo_head_hexsha": "aad03066d55422592e02281e5c1ea276ab0002d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-06-02T11:02:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T11:53:23.000Z", "avg_line_length": 34.4148148148, "max_line_length": 133, "alphanum_fraction": 0.6758501937, "num_tokens": 1208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851919, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4558081629228846}}
{"text": "#include <pnp/learning_plan/exp/SoftMax.h>\n\n#include <boost/bind.hpp>\n\n#include <cmath>\n#include <functional>\n#include <numeric>\n#include <algorithm>\n\n#include <stdlib.h>\n\nusing namespace std;\nusing boost::bind;\n\nnamespace learnpnp {\n\nSoftMax::SoftMax(double tau, bool remember) : ExpPolicy(remember), tau(tau) {}\n\nint SoftMax::makeChoice(Learner *learner,const Marking &current, const std::vector<Marking> &states) {\n\n    //this can be impelemented with fewer implicit loops, but I don't want to do it unless some profiling shows\n    //it's really necessary to sacrifice readability for efficiency\n\n\tvector<double> values;\n    transform(states.begin(),states.end(),std::back_inserter(values),\n              bind(&Learner::valueOf,learner,_1));\n\n\n    double min = *min_element(values.begin(),values.end());\n    if (min < 0) {\n        //make the values positive\n        transform(values.begin(),values.end(),values.begin(),bind(plus<double>(),_1,min));\n    }\n\n    vector<double> weights;\n    transform(values.begin(),values.end(),back_inserter(weights),bind(&SoftMax::computeWeight,this,_1));\n\n    double sum = accumulate(weights.begin(),weights.end(),0.0);\n\n    //normalize the weight with respect to the sum and RAND_MAX\n    // for each weight w computes w/sum * RAND_MAX\n    transform(weights.begin(),weights.end(),weights.begin(),\n              bind(multiplies<double>(),bind(divides<double>(),_1,sum), RAND_MAX));\n\n\t//cumulative sums\n\t/* An example: imagine the normalized weights are 0.2 * RAND_MAX,\n\t0.3 * RAND_MAX, and 0.5 * RAND_MAX\n\twe drop RAND_MAX for readability now, the cumulative sums are\n\t0.2, 0.5, 1\n\twe extract a value v in [0,1] (in [0,RAND_MAX] in practice)\n\tand look for the first value among the cumulative sums that is >= v\n\t*/\n\tvector<double>cumulative;\n\tpartial_sum(weights.begin(),weights.end(),back_inserter(cumulative));\n\n\tint v = rand();\n\n\tvector<double>::iterator result = find_if(cumulative.begin(),cumulative.end(),bind(greater_equal<double>(),_1,v));\n\n\treturn distance(cumulative.begin(),result);\n\n}\n\ndouble SoftMax::computeWeight(double value) {\n    return exp ( value  /tau );\n}\n\n\n}\n", "meta": {"hexsha": "1337ed535c8a6765526041f868fc8d3c47c133bb", "size": 2118, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bwi_tasks_pnp/pnp/src/learning_plan/exp/SoftMax.cpp", "max_stars_repo_name": "pato/bwi_experimental", "max_stars_repo_head_hexsha": "0cc71672580a886e4c405bbc6ea8305624a28572", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bwi_tasks_pnp/pnp/src/learning_plan/exp/SoftMax.cpp", "max_issues_repo_name": "pato/bwi_experimental", "max_issues_repo_head_hexsha": "0cc71672580a886e4c405bbc6ea8305624a28572", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bwi_tasks_pnp/pnp/src/learning_plan/exp/SoftMax.cpp", "max_forks_repo_name": "pato/bwi_experimental", "max_forks_repo_head_hexsha": "0cc71672580a886e4c405bbc6ea8305624a28572", "max_forks_repo_licenses": ["BSD-3-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.2571428571, "max_line_length": 115, "alphanum_fraction": 0.7011331445, "num_tokens": 523, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.727975460709318, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.4558030363790168}}
{"text": "#include <utt/Configuration.h>\n\n#include <utt/PolyCrypto.h>\n#include <utt/NtlLib.h>\n\n#include <vector>\n#include <cmath>\n#include <iostream>\n#include <ctime>\n#include <fstream>\n\n#include <libfqfft/polynomial_arithmetic/basic_operations.hpp>\n#include <libff/common/double.hpp>\n\n#include <xutils/Log.h>\n#include <xutils/Timer.h>\n#include <xassert/XAssert.h>\n\n#include <NTL/ZZ_pX.h>\n\nusing namespace std;\nusing namespace libfqfft;\nusing namespace libutt;\n\nint main() {\n    initialize(nullptr, 0);\n    std::vector<G1> bases;\n    int count = 3, numBench = 0;\n    double avgPctage = 0.0;\n    size_t maxSize = 1024*128;\n\n    loginfo << \"Picking \" << maxSize << \" random G1 elements to bench multiexponentiation with...\";\n    bases.resize(maxSize);\n    for(size_t i = 0; i < bases.size(); i++) {\n        bases[i] = G1::random_element();\n    }\n    std::cout << endl;\n\n    //for (size_t i = 1; i <= 1024*128; i *= 2) {\n    for(size_t i = maxSize; i >= 1; i /= 2) {\n        logperf << \"poly degree = \" << i-1 << \", iters = \" << count\n                << endl;\n        numBench++;\n        AveragingTimer conv, exp;\n\n        ZZ_pX poly;\n        std::vector<Fr> ffpoly;\n    \n        bases.resize(i);\n\n        for (int rep = 0; rep < count; rep++) {\n            random(poly, static_cast<long>(i));\n\n            conv.startLap();\n            //conv_zp_fr(poly, ffpoly);\n            convNtlToLibff(poly, ffpoly);\n            conv.endLap();\n\n\n            exp.startLap();\n            multiExp(bases, ffpoly);\n            exp.endLap();\n        }\n\n        auto avgConv = conv.averageLapTime(), avgExp = exp.averageLapTime();\n        double pctage = (double)avgConv/(double)(avgConv+avgExp)*100.0; \n        logperf << \" + Conv to libff: \" << (double) avgConv / 1000000 << \" seconds.\" << endl;\n        logperf << \" + Multiexp:      \" << (double) avgExp / 1000000 << \" seconds.\" << endl;\n        logperf << \" + \" << pctage << \"% time spent converting\" << endl;\n        logperf << endl;\n\n        avgPctage += pctage;\n    }\n    \n    avgPctage /= numBench;\n\n    logperf << endl;\n    logperf << \"On average, \" << avgPctage << \"% time spent converting\" << endl;\n    return 0;\n}\n", "meta": {"hexsha": "28c9dda3eeff4d9561e7f5213f64dc1e62d6dc6c", "size": 2146, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libutt/libutt/bench/BenchConvertAndMultiexp.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/bench/BenchConvertAndMultiexp.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/bench/BenchConvertAndMultiexp.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": 26.4938271605, "max_line_length": 99, "alphanum_fraction": 0.5647716682, "num_tokens": 617, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754371026368, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.4558030317557527}}
{"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\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include <iostream>\n#include <cmath>\n\n// #define MTL_HAS_BLAS\n// #define MTL_USE_OPTERON_OPTIMIZATION\n\n#include <boost/numeric/mtl/utility/glas_tag.hpp>\n#include <boost/numeric/mtl/matrix/dense2D.hpp>\n#include <boost/numeric/mtl/matrix/morton_dense.hpp> \n#include <boost/numeric/mtl/matrix/transposed_view.hpp>\n#include <boost/numeric/mtl/recursion/bit_masking.hpp>\n#include <boost/numeric/mtl/operation/print.hpp>\n#include <boost/numeric/mtl/operation/dmat_dmat_mult.hpp>\n#include <boost/numeric/mtl/operation/mult.hpp>\n#include <boost/numeric/mtl/operation/operators.hpp>\n#include <boost/numeric/mtl/matrix/hessian_setup.hpp>\n#include <boost/numeric/mtl/operation/assign_mode.hpp>\n#include <boost/numeric/mtl/operation/mult_assign_mode.hpp>\n#include <boost/numeric/mtl/recursion/base_case_test.hpp>\n\n\nusing namespace std;  \n\n\ntemplate <typename MatrixA, typename MatrixB, typename MatrixC>\nvoid test(MatrixA& A, MatrixB& B, MatrixC& C, const char* name)\n{\n    using mtl::assign::assign_sum; using mtl::assign::plus_sum; \n    using mtl::assign::minus_sum; using mtl::assign::mult_assign_mode; \n    using mtl::recursion::bound_test_static; using mtl::gen_recursive_dmat_dmat_mult_t;\n\n    hessian_setup(A, 1.0);\n    hessian_setup(B, 2.0);\n\n    std::cout << \"\\n\" << name << \"  --- calling simple mult:\\n\"; std::cout.flush();\n    typedef mtl::gen_dmat_dmat_mult_t<>  mult_t;\n    mult_t                               mult;\n\n    mult(A, B, C);\n    // cout << \"correct result is:\\n\" << with_format(C, 5, 3);\n    check_hessian_matrix_product(C, A.num_cols());\n\n    std::cout << \"\\n\" << name << \"  --- check += :\\n\"; std::cout.flush();\n    typedef mtl::gen_dmat_dmat_mult_t<plus_sum>  add_mult_t;\n    add_mult_t add_mult;\n\n    add_mult(A, B, C);\n    check_hessian_matrix_product(C, A.num_cols(), 2.0);\n    \n    std::cout << \"\\n\" << name << \"  --- check -= :\\n\"; std::cout.flush();\n    typedef mtl::gen_dmat_dmat_mult_t<minus_sum>  minus_mult_t;\n    minus_mult_t minus_mult;\n\n    minus_mult(A, B, C);\n    check_hessian_matrix_product(C, A.num_cols(), 1.0);\n\n#if 0\n    std::cout << \"\\n\" << name << \"  --- calling mult with cursors and property maps:\\n\"; std::cout.flush();\n    gen_cursor_dmat_dmat_mult_t<>  cursor_mult;\n\n    cursor_mult(A, B, C);\n    check_hessian_matrix_product(C, A.num_cols());\n\n    std::cout << \"\\n\" << name << \"  --- check += :\\n\"; std::cout.flush();\n    gen_cursor_dmat_dmat_mult_t<plus_sum>  cursor_add_mult;\n\n    cursor_add_mult(A, B, C);\n    check_hessian_matrix_product(C, A.num_cols(), 2.0);\n    \n    std::cout << \"\\n\" << name << \"  --- check -= :\\n\"; std::cout.flush();\n    gen_cursor_dmat_dmat_mult_t<minus_sum>  cursor_minus_mult; \n\n    cursor_minus_mult(A, B, C);\n    check_hessian_matrix_product(C, A.num_cols(), 1.0);\n#endif \n    std::cout << \"\\n\" << name << \"  --- calling mult with tiling:\\n\"; std::cout.flush();\n    typedef mtl::gen_tiling_dmat_dmat_mult_t<2, 2>  tiling_mult_t;\n    tiling_mult_t tiling_mult;\n\n    tiling_mult(A, B, C);\n    check_hessian_matrix_product(C, A.num_cols()); \n\n    std::cout << \"\\n\" << name << \"  --- check += :\\n\"; std::cout.flush();\n    typedef mtl::gen_tiling_dmat_dmat_mult_t<2, 2, plus_sum>  tiling_add_mult_t;\n    tiling_add_mult_t tiling_add_mult;\n\n    tiling_add_mult(A, B, C); \n    check_hessian_matrix_product(C, A.num_cols(), 2.0);\n    \n    std::cout << \"\\n\" << name << \"  --- check -= :\\n\"; std::cout.flush();\n    typedef mtl::gen_tiling_dmat_dmat_mult_t<2, 2, minus_sum>  tiling_minus_mult_t;\n    tiling_minus_mult_t tiling_minus_mult;\n\n    tiling_minus_mult(A, B, C);\n    check_hessian_matrix_product(C, A.num_cols(), 1.0);\n\n \n    std::cout << \"\\n\" << name << \"  --- calling mult with tiling 2x2:\\n\"; std::cout.flush();\n    typedef mtl::gen_tiling_22_dmat_dmat_mult_t<>  tiling_22_mult_t;\n    tiling_22_mult_t tiling_22_mult;\n\n    tiling_22_mult(A, B, C);\n    check_hessian_matrix_product(C, A.num_cols()); \n\n    std::cout << \"\\n\" << name << \"  --- check += :\\n\"; std::cout.flush();\n    // typedef gen_tiling_22_dmat_dmat_mult_t<plus_sum>  tiling_22_add_mult_t;\n    typedef typename mult_assign_mode<tiling_22_mult_t, plus_sum>::type   tiling_22_add_mult_t;\n    tiling_22_add_mult_t tiling_22_add_mult;\n\n    tiling_22_add_mult(A, B, C); \n    check_hessian_matrix_product(C, A.num_cols(), 2.0);\n    \n    std::cout << \"\\n\" << name << \"  --- check -= :\\n\"; std::cout.flush();\n    typedef mtl::gen_tiling_22_dmat_dmat_mult_t<minus_sum>  tiling_22_minus_mult_t;\n    tiling_22_minus_mult_t tiling_22_minus_mult;\n\n    tiling_22_minus_mult(A, B, C);\n    check_hessian_matrix_product(C, A.num_cols(), 1.0);\n\n\n    std::cout << \"\\n\" << name << \"  --- calling mult with tiling 4x4:\\n\"; std::cout.flush();\n    typedef mtl::gen_tiling_44_dmat_dmat_mult_t<>  tiling_44_mult_t;\n    tiling_44_mult_t tiling_44_mult;\n\n    tiling_44_mult(A, B, C);\n    check_hessian_matrix_product(C, A.num_cols()); \n\n    MatrixA A9(9, 9); MatrixB B9(9, 9); MatrixC C9(9, 9); // to test all block in 4x4 blocking for better coverage\n    hessian_setup(A9, 1.0); hessian_setup(B9, 2.0);\n\n    tiling_44_mult(A9, B9, C9);\n    check_hessian_matrix_product(C9, num_cols(A9)); \n\n    std::cout << \"\\n\" << name << \"  --- check += :\\n\"; std::cout.flush();\n    typedef mtl::gen_tiling_44_dmat_dmat_mult_t<plus_sum>  tiling_44_add_mult_t;\n    tiling_44_add_mult_t tiling_44_add_mult;\n\n    tiling_44_add_mult(A, B, C); \n    check_hessian_matrix_product(C, A.num_cols(), 2.0);\n    \n    std::cout << \"\\n\" << name << \"  --- check -= :\\n\"; std::cout.flush();\n    typedef mtl::gen_tiling_44_dmat_dmat_mult_t<minus_sum>  tiling_44_minus_mult_t;\n    tiling_44_minus_mult_t tiling_44_minus_mult;\n\n    tiling_44_minus_mult(A, B, C);\n    check_hessian_matrix_product(C, A.num_cols(), 1.0);\n\n    typedef mtl::gen_recursive_dmat_dmat_mult_t<add_mult_t, bound_test_static<2>, plus_sum>  recursive_add_mult_t;\n\n    std::cout << \"\\n\" << name << \"  --- calling mult recursively:\\n\"; std::cout.flush();\n    // The recursive functor is C= A*B but the base case must be C+= A*B !!!!!!\n    // gen_recursive_dmat_dmat_mult_t<add_mult_t, bound_test_static<32> >  recursive_mult;\n    typename mult_assign_mode<recursive_add_mult_t, assign_sum>::type\trecursive_mult;\n\n    recursive_mult(A, B, C);\n    // cout << \"recursive result is:\\n\" << with_format(C, 5, 3);\n    check_hessian_matrix_product(C, A.num_cols()); \n\n    std::cout << \"\\n\" << name << \"  --- check += :\\n\"; std::cout.flush();\n    recursive_add_mult_t   recursive_add_mult;\n\n    recursive_add_mult(A, B, C); \n    check_hessian_matrix_product(C, A.num_cols(), 2.0);\n    \n    std::cout << \"\\n\" << name << \"  --- check -= :\\n\"; std::cout.flush();\n    // gen_recursive_dmat_dmat_mult_t<minus_mult_t, bound_test_static<32>, minus_sum>  recursive_minus_mult; \n    // check assign mode substitution both on matrix and on block level\n    typename mult_assign_mode<recursive_add_mult_t, minus_sum>::type\trecursive_minus_mult;\n    recursive_minus_mult(A, B, C);\n    check_hessian_matrix_product(C, A.num_cols(), 1.0);\n\n    std::cout << \"\\n\" << name << \"  --- calling mult recursively with tiling:\\n\"; std::cout.flush();\n    // The recursive functor is C= A*B but the base case must be C+= A*B !!!!!!\n    gen_recursive_dmat_dmat_mult_t<tiling_add_mult_t, bound_test_static<32> >  recursive_tiling_mult;\n\n    recursive_tiling_mult(A, B, C);\n    check_hessian_matrix_product(C, A.num_cols()); \n \n    std::cout << \"\\n\" << name << \"  --- check += :\\n\"; std::cout.flush();\n    gen_recursive_dmat_dmat_mult_t<tiling_add_mult_t, bound_test_static<32>, plus_sum>  recursive_tiling_add_mult;\n\n    recursive_tiling_add_mult(A, B, C); \n    check_hessian_matrix_product(C, A.num_cols(), 2.0);\n    \n    std::cout << \"\\n\" << name << \"  --- check -= :\\n\"; std::cout.flush();\n    gen_recursive_dmat_dmat_mult_t<tiling_minus_mult_t, bound_test_static<32>, minus_sum>  recursive_tiling_minus_mult; \n\n    recursive_tiling_minus_mult(A, B, C);\n    check_hessian_matrix_product(C, A.num_cols(), 1.0);\n\n    std::cout << \"\\n\" << name << \"  --- calling mult recursively platform specific plus tiling:\\n\"; std::cout.flush();\n    typedef mtl::gen_platform_dmat_dmat_mult_t<plus_sum, tiling_add_mult_t> platform_tiling_add_mult_t;\n    gen_recursive_dmat_dmat_mult_t<platform_tiling_add_mult_t, bound_test_static<32> >  recursive_platform_tiling_mult;\n    \n    recursive_platform_tiling_mult(A, B, C);\n    check_hessian_matrix_product(C, A.num_cols(), 1.0);\n\n#ifdef MTL_HAS_BLAS\n    std::cout << \"\\n\" << name << \"  --- calling blas mult:\\n\"; std::cout.flush(); \n    gen_blas_dmat_dmat_mult_t<>  blas_mult;\n    blas_mult(A, B, C);\n    check_hessian_matrix_product(C, A.num_cols()); \n#endif    \n\n#ifdef MTL_USE_OPTERON_OPTIMIZATION\n    std::cout << \"\\n\" << name << \"  --- calling platform specific mult (empty):\\n\"; std::cout.flush(); \n    gen_platform_dmat_dmat_mult_t<>  platform_mult;\n    platform_mult(A, B, C);\n    check_hessian_matrix_product(C, A.num_cols());\n\n    std::cout << \"\\n\" << name << \"  --- check += :\\n\"; std::cout.flush();\n    gen_platform_dmat_dmat_mult_t<plus_sum>  platform_add_mult;\n\n    platform_add_mult(A, B, C);\n    check_hessian_matrix_product(C, A.num_cols(), 2.0);\n    \n    std::cout << \"\\n\" << name << \"  --- check -= :\\n\"; std::cout.flush();\n    gen_platform_dmat_dmat_mult_t<minus_sum>  platform_minus_mult;\n\n    platform_minus_mult(A, B, C);\n    check_hessian_matrix_product(C, A.num_cols(), 1.0);\n\n#endif\n\n    std::cout << \"\\n\" << name << \"  --- using mult(A, B, C) :\\n\"; std::cout.flush();\n    mult(A, B, C);\n    check_hessian_matrix_product(C, A.num_cols(), 1.0);\n\n    std::cout << \"\\n\" << name << \"  --- called as C= A * B:\\n\"; std::cout.flush();\n    C= A * B;\n    check_hessian_matrix_product(C, A.num_cols());\n\n    std::cout << \"\\n\" << name << \"  --- check C+= A * B:\\n\"; std::cout.flush();\n    C+= A * B;\n    check_hessian_matrix_product(C, A.num_cols(), 2.0);\n\n    std::cout << \"\\n\" << name << \"  --- check C-= A * B:\\n\"; std::cout.flush();\n    C-= A * B;\n    check_hessian_matrix_product(C, A.num_cols(), 1.0);\n\n    if (A.num_cols() <= 10) \n\tstd::cout << A << \"\\n\" << B << \"\\n\" << with_format(C, 4, 4) << \"\\n\";\n\n}\n \n\n\n\ntemplate <typename MatrixA, typename MatrixB, typename MatrixC>\nvoid single_test(MatrixA& A, MatrixB& B, MatrixC& C, const char*)\n{\n    using mtl::assign::plus_sum; using mtl::assign::minus_sum; \n    using mtl::recursion::bound_test_static;\n\n    std::cout << \"\\n\\n before matrix multiplication:\\n\";\n    std::cout << \"A:\\n\" << A;\n    std::cout << \"B:\\n\" << B;\n    std::cout << \"C:\\n\" << C << '\\n';\n\n    typedef mtl::gen_tiling_dmat_dmat_mult_t<2, 2, plus_sum>  tiling_add_mult_t;\n    tiling_add_mult_t tiling_add_mult;\n    tiling_add_mult(A, B, C); \n    \n    std::cout << \"\\n\\n after matrix multiplication:\\n\";\n    std::cout << \"A:\\n\" << A;\n    std::cout << \"B:\\n\" << B;\n    std::cout << \"C:\\n\" << C << '\\n';\n}\n\n#ifdef MTL_HAS_BLAS\nextern \"C\" {\nvoid dgemm_(const char* transa, const char* transb, \n\t    const int* m, const int* n, const int* k,\n\t    const double* alpha,  const double *da,  const int* lda,\n\t    const double *db, const int* ldb, const double* dbeta,\n\t    double *dc, const int* ldc);\n}\n\ntypedef mtl::dense2D<double, mtl::mat::parameters<col_major> >        dc_t;\n\nstruct dgemm_t\n{\n    void operator()(const dc_t& A, const dc_t& B, dc_t& C)\n    {\n\tint size= A.num_rows();\n\tdouble alpha= 1.0, beta= 0.0;\n\tdgemm_(\"N\", \"N\", &size, &size, &size, &alpha, \n\t       const_cast<double*>(&A[0][0]), &size, const_cast<double*>(&B[0][0]), \n\t       &size, &beta, &C[0][0], &size);\n\n    }\n};\n\n\nvoid test_blas()\n{\n    mtl::dense2D<double, mtl::mat::parameters<col_major> > A(7, 7), B(7, 7), C(7, 7);\n    hessian_setup(A, 1.0);\n    hessian_setup(B, 2.0);\n    dgemm_t()(A, B, C);\n\n    std::cout << C; \n    check_hessian_matrix_product(C, A.num_cols());\n    \n}\n\n#endif // MTL_HAS_BLAS\n\nint main(int argc, char* argv[])\n{\n    using namespace mtl;\n\n    // Bitmasks:\n    const unsigned long morton_mask= generate_mask<true, 0, row_major, 0>::value,\n\tdoppled_32_row_mask_no_shark= generate_mask<true, 5, row_major, 0>::value,\n\tdoppled_32_col_mask_no_shark= generate_mask<true, 5, col_major, 0>::value,\n\tdoppled_32_row_mask= generate_mask<true, 5, row_major, 1>::value,\n\tdoppled_32_col_mask= generate_mask<true, 5, col_major, 1>::value,\n\tdoppled_z_32_row_mask= generate_mask<false, 5, row_major, 1>::value,\n\tdoppled_z_32_col_mask= generate_mask<false, 5, col_major, 1>::value;\n \n    unsigned size= 5; \n    if (argc > 1) size= atoi(argv[1]); \n    if (size < 2) size= 2;\n\n    dense2D<double>                                  da(size, size-1), db(size-1, size-2), dc(size, size-2); \n    dense2D<double, mat::parameters<col_major> >  dca(size, size-1), dcb(size-1, size-2), dcc(size, size-2);\n    dense2D<float>                                   fa(size, size-1), fb(size-1, size-2), fc(size, size-2);\n    dense2D<float, mat::parameters<col_major> >   fca(size, size-1), fcb(size-1, size-2), fcc(size, size-2);\n    morton_dense<double,  morton_mask>               mda(size, size-1), mdb(size-1, size-2), mdc(size, size-2);\n\n    typedef morton_dense<double, doppled_32_row_mask_no_shark>  morton_t;\n    morton_dense<double, doppled_32_row_mask_no_shark>      mrans(size, size-1), mrbns(size-1, size-2), mrcns(size, size-2);;\n    morton_dense<double, doppled_32_col_mask_no_shark>      mcans(size, size-1), mcbns(size-1, size-2), mccns(size, size-2); \n    morton_dense<double, doppled_32_col_mask>      mca(size, size-1), mcb(size-1, size-2), mcc(size, size-2);\n    morton_dense<double, doppled_32_row_mask>      mra(size, size-1), mrb(size-1, size-2), mrc(size, size-2);\n    morton_dense<double, doppled_z_32_col_mask>    mzca(size, size-1), mzcb(size-1, size-2), mzcc(size, size-2);\n    morton_dense<double, doppled_z_32_row_mask>    mzra(size, size-1), mzrb(size-1, size-2), mzrc(size, size-2);\n    morton_dense<float, doppled_32_col_mask>       mcaf(size, size-1), mcbf(size-1, size-2), mccf(size, size-2);\n    morton_dense<float, doppled_32_row_mask>       mraf(size, size-1), mrbf(size-1, size-2), mrcf(size, size-2);\n\n    transposed_view<dense2D<double> > trans_db(db); \n    transposed_view<morton_t >        trans_mrbns(mrbns); \n\n\n    std::cout << \"Testing different products\\n\";\n\n#if 0\n    test(da, trans_db, dc, \"dense2D and transposed dense2D\");\n    test(mrans, trans_mrbns, mrcns, \"hybrid with transposed matrix\");\n#endif\n\n    test(da, db, dc, \"dense2D\");\n    test(dca, dcb, dcc, \"dense2D col-major\");\n    test(da, dcb, dc, \"dense2D row x column-major\");\n    test(fa, fcb, fc, \"dense2D float, row x column-major\");\n    test(da, fcb, fc, \"dense2D mixed, dense and float\"); \n    test(mda, mdb, mdc, \"pure Morton\");\n    test(mca, mcb, mcc, \"Hybrid col-major\");\n    test(mra, mrb, mrc, \"Hybrid row-major\");\n    test(mrans, mcbns, mrcns, \"Hybrid col-major and row-major, no shark tooth\");\n    test(mrans, mrbns, mrcns, \"Hybrid row-major, no shark tooth\");\n    test(mraf, mcbf, mrcf, \"Hybrid col-major and row-major with float\");\n    test(mra, mcb, mrc, \"Hybrid col-major and row-major\");\n    test(mzra, mzcb, mzrc, \"Hybrid col-major and row-major, Z-order\");\n    test(mra, mzcb, mzrc, \"Hybrid col-major and row-major, Z and E-order\");\n    test(mra, dcb, mzrc, \"Hybrid col-major and row-major, Z and E-order mixed with dense2D\");\n    test(mra, db, mrcns, \"Hybric matrix = Shark * dense2D\");\n    test(mrans, db, mccns, \"Hybric matrix (col-major) = hybrid (row) * dense2D\");\n\n    return 0;\n}\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "33cec162933b612a1b278058c728b6e8127bf9fd", "size": 15824, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/matrix_product_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/matrix_product_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/matrix_product_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": 39.56, "max_line_length": 125, "alphanum_fraction": 0.6570399393, "num_tokens": 4995, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.45580302898865993}}
{"text": "#include <iostream>\n#include <vector>\n#include <boost/ref.hpp>\n#include <boost/utility.hpp>\n#include <boost/python/suite/indexing/vector_indexing_suite.hpp>\n#include <boost/python/module.hpp>\n#include <boost/python/class.hpp>\n#include <boost/python/operators.hpp>\n#include <boost/python/def.hpp>\n#include <boost/python/pure_virtual.hpp>\n#include <boost/python/copy_const_reference.hpp>\n#include <boost/operators.hpp>\n#include <boost/python/numpy.hpp>\n#include <boost/python/list.hpp>\n#include <exception>\n#define private public\n\nusing namespace boost;\nusing namespace boost::python;\nusing namespace boost::python::numpy;\n\n#include \"cwt1d_wavelets.hpp\"\nusing namespace std;\nusing namespace cwt1d;\n\ntypedef dog<double> pydog;\ntypedef morlet<double> pymorlet;\ntypedef paul<double> pypaul;\ntypedef wavelet_func<double> wf;\n\nnamespace\n{\n  class initializer{\n  public:\n    initializer()\n    {\n      //boost::python::numeric::array::set_module_and_type(\"numpy\",\"ndarray\");\n      Py_Initialize();\n      numpy::initialize();\n    }\n  }_init;\n}\n\nboost::python::numpy::ndarray pycwt(const boost::python::numpy::ndarray& x,const boost::python::numpy::ndarray& s,const wavelet_func<double>& wf)\n{\n  boost::python::object shape(x.attr(\"shape\"));\n  int ndim=extract<int>(shape.attr(\"__len__\")());\n  if(ndim!=1)\n    {\n      throw std::exception();\n    }\n  int ndata=extract<int>(shape[0]);\n  \n  blitz::Array<double,1> x1(ndata);\n  for(int i=0;i<ndata;++i)\n    {\n      x1(i)=extract<double>(x[i]);\n    }\n  shape=s.attr(\"shape\");\n  ndim=extract<int>(shape.attr(\"__len__\")());\n  if(ndim!=1)\n    {\n      throw std::exception();\n    }\n  int nscales=extract<int>(shape[0]);\n  blitz::Array<double,1> s1(nscales);\n\n  for(int i=0;i<nscales;++i)\n    {\n      s1(i)=extract<double>(s[i]);\n    }\n\n  blitz::Array<complex<double>,2> y(cwt(x1,s1,wf));\n  boost::python::list l;\n  for(int i=0;i<nscales;++i)\n    {\n      boost::python::list l1;\n      for(int j=0;j<ndata;++j)\n\t{\n\t  l1.append(y(i,j));\n\t}\n      l.append(l1);\n    }\n  \n  return boost::python::numpy::array(l);\n\n}\n\nboost::python::numpy::ndarray pyicwt(const boost::python::numpy::ndarray& x,const boost::python::numpy::ndarray& s,const wavelet_func<double>& wf)\n{\n  boost::python::object shape(x.attr(\"shape\"));\n  int ndim=extract<int>(shape.attr(\"__len__\")());\n  if(ndim!=2)\n    {\n      throw std::exception();\n    }\n  int ndata=extract<int>(shape[1]);\n  int nscales=extract<int>(shape[0]);\n  \n  blitz::Array<complex<double>,2> x1(nscales,ndata);\n  for(int i=0;i<nscales;++i)\n    {\n      for(int j=0;j<ndata;++j)\n\t{\n\t  x1(i,j)=extract<complex<double> >(x[boost::python::make_tuple(i,j)]);\n\t}\n    }\n  shape=s.attr(\"shape\");\n  ndim=extract<int>(shape.attr(\"__len__\")());\n  if(ndim!=1)\n    {\n      throw std::exception();\n    }\n  if(nscales!=extract<int>(shape[0]))\n    {\n      throw std::exception();\n    }\n  blitz::Array<double,1> s1(nscales);\n\n  for(int i=0;i<nscales;++i)\n    {\n      s1(i)=extract<double>(s[i]);\n    }\n  blitz::Array<double,1> result1(icwt(x1,s1,wf));\n  boost::python::list l;\n  for(int i=0;i<ndata;++i)\n    {\n      l.append(result1(i));\n    }\n  return boost::python::numpy::array(l);\n  //return result;\n}\n\nboost::python::numpy::ndarray generate_log_scales(double min_scale,double max_scale,int num_scales)\n{\n  boost::python::list l;\n  double lmin_scale=log(min_scale);\n  double lmax_scale=log(max_scale);\n  for(int i=0;i<num_scales;++i)\n    {\n      double s=exp(lmin_scale+(lmax_scale-lmin_scale)/(num_scales-1)*i);\n      l.append(s);\n    }\n  return boost::python::numpy::array(l);\n  //  return result;\n}\n\ndouble pycalc_norm(int dl,const boost::python::numpy::ndarray& s,const wavelet_func<double>& wf)\n{\n  boost::python::object shape(s.attr(\"shape\"));\n  int ndim=extract<int>(shape.attr(\"__len__\")());\n  if(ndim!=1)\n    {\n      throw std::exception();\n    }\n  int nscales=extract<int>(shape[0]);\n  blitz::Array<double,1> s1(nscales);\n  for(int i=0;i<nscales;++i)\n    {\n      s1(i)=extract<double>(s[i]);\n    }\n  return calc_norm(dl,s1,wf);\n}\n\nBOOST_PYTHON_MODULE(cwtcore)\n{\n  class_<wf,boost::noncopyable>(\"wf\",no_init)\n    .def(\"wavelet_f\",&wf::wavelet_f);\n  \n  class_<pydog,bases<wf> >(\"dog\")\n    .def(init<>())\n    .def(init<int>());\n\n  class_<pymorlet,bases<wf> >(\"morlet\")\n    .def(init<>())\n    .def(init<double>());\n  \n  class_<pypaul,bases<wf> >(\"paul\")\n    .def(init<>())\n    .def(init<double>());\n\n\n  def(\"cwt\",pycwt);\n  def(\"icwt\",pyicwt);\n  def(\"calc_norm\",pycalc_norm);\n  def(\"generate_log_scales\",generate_log_scales);\n}\n", "meta": {"hexsha": "be5e14bc1e2071e269606d45eb899606fa1a7c24", "size": 4483, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cwt/pycwt1d/src/pycwt1d.cpp", "max_stars_repo_name": "lizhangscience/cdae-eor", "max_stars_repo_head_hexsha": "61dab95681c5806a521a57846d9c875404cd4890", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-09-28T02:12:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T08:44:18.000Z", "max_issues_repo_path": "cwt/pycwt1d/src/pycwt1d.cpp", "max_issues_repo_name": "lizhangscience/cdae-eor", "max_issues_repo_head_hexsha": "61dab95681c5806a521a57846d9c875404cd4890", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-11-18T09:52:24.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-23T09:41:09.000Z", "max_forks_repo_path": "cwt/pycwt1d/src/pycwt1d.cpp", "max_forks_repo_name": "liweitianux/cdae-eor", "max_forks_repo_head_hexsha": "61dab95681c5806a521a57846d9c875404cd4890", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2018-09-28T02:12:36.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-16T19:43:38.000Z", "avg_line_length": 23.8457446809, "max_line_length": 146, "alphanum_fraction": 0.6397501673, "num_tokens": 1332, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.45580302898865993}}
{"text": "#pragma once\n#include \"shared.h\"\n#include <boost/numeric/odeint.hpp>\n\nusing namespace boost::numeric::odeint;\ntypedef std::vector<double> state_type;\ntypedef runge_kutta_cash_karp54< state_type > error_stepper_type;\n\nclass Elevator\n{\nprivate:\n  bool Initialize = false;\n  bool FixedEarthBoundary = false;\n\n  const uint32_t\n    Dimensions = 3;\n\n  uint32_t\n    ChainSize = 0,\n    TotalSteps = 0,\n    SavedSteps = 0;\n\n  double\n    L0 = 0.0,\n    GM = 0.0,\n    T0 = 0.0,\n    Tf = 0.0,\n    Dt = 0.0,\n    WPlanet = 0.0,\n    RSurface = 0.0,\n    FrictA = 0.0,\n    FrictB = 0.0,\n    FrictC = 0.0,\n    * AnchorAngles = nullptr,\n    * SprK = nullptr,\n    * RotK = nullptr,\n    * Inertia = nullptr,\n    * Mass = nullptr;\n\n  state_type * State = nullptr;\n\n  std::vector<double*> StoredStates;\n\n  void __RHS(state_type &y, state_type &dy, double t);\n  double __Distance(const state_type &y, uint32_t i, uint32_t j);\n  double __Modulus2(const state_type &y, uint32_t i);\n  double __Alpha(const state_type &y, uint32_t i);\n\n  void __EarthFixedBoundary(state_type &y, state_type &dy, const double t);\n  void __EarthFreeBoundary(state_type &y, state_type &dy, const double t);\n  void __SpaceFreeBoundary(state_type &y, state_type &dy, const double t);\n\n  void __StoreState(const state_type &y, const double t);\n\npublic:\n  Elevator() {}\n  ~Elevator() {\n    delete[] SprK;\n    delete[] RotK;\n    delete[] Inertia;\n    delete[] Mass;\n    delete[] AnchorAngles;\n    delete State;\n  }\n\n  virtual void InitializeFromFile(char const * filename);\n  void LoadSystem(char const * filename);\n  void SaveSystem(char const * filename);\n\n  void Integrate();\n};\n", "meta": {"hexsha": "1c332f2677b1d7bcc51f0907bc5784f92936fd9f", "size": 1628, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Week10/header/elevator.hpp", "max_stars_repo_name": "Milias/ModellingSimulation", "max_stars_repo_head_hexsha": "005ea39ae16f171a2b5587794d1c05be526eeb57", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-02-19T00:58:22.000Z", "max_stars_repo_stars_event_max_datetime": "2016-02-19T00:58:22.000Z", "max_issues_repo_path": "Week10/header/elevator.hpp", "max_issues_repo_name": "Milias/ModellingSimulation", "max_issues_repo_head_hexsha": "005ea39ae16f171a2b5587794d1c05be526eeb57", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Week10/header/elevator.hpp", "max_forks_repo_name": "Milias/ModellingSimulation", "max_forks_repo_head_hexsha": "005ea39ae16f171a2b5587794d1c05be526eeb57", "max_forks_repo_licenses": ["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.6111111111, "max_line_length": 75, "alphanum_fraction": 0.6695331695, "num_tokens": 484, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754371026367, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.4558030215983029}}
{"text": "/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\\n|  Phycas: Python software for phylogenetic analysis                          |\n|  Copyright (C) 2012 Mark T. Holder, Paul O. Lewis and David L. Swofford     |\n|                                                                             |\n|  This program is free software; you can redistribute it and/or modify       |\n|  it under the terms of the GNU General Public License as published by       |\n|  the Free Software Foundation; either version 2 of the License, or          |\n|  (at your option) any later version.                                        |\n|                                                                             |\n|  This program is distributed in the hope that it will be useful,            |\n|  but WITHOUT ANY WARRANTY; without even the implied warranty of             |\n|  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the              |\n|  GNU General Public License for more details.                               |\n|                                                                             |\n|  You should have received a copy of the GNU General Public License along    |\n|  with this program; if not, write to the Free Software Foundation, Inc.,    |\n|  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.                |\n\\~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n\n#if defined(USING_NUMARRAY)\n#\tdefine PY_ARRAY_UNIQUE_SYMBOL PyArrayHandle\n#\tdefine NO_IMPORT_ARRAY\n#endif\n\n#include <numeric>\n#include <functional>\n#include <cmath>\n#include <boost/lambda/lambda.hpp>\n\n#include \"tree_length_distribution.hpp\"\n#include \"dirichlet_distribution.hpp\"\n\n#include <fstream>  //temporary!\n#include <iterator>  //temporary!\n\nnamespace phycas\n{\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tBy default, let the tree length distribution be exponential with mean 10 and the edge length distribution\n|   conditional on tree length be flat.\n*/\nTreeLengthDistribution::TreeLengthDistribution()\n  : _alphaT(1.0), _betaT(0.1), _alpha(1.0), _c(1.0), _lot(&_myLot), _num_internal_edges(0), _num_external_edges(0)\n\t{\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tCreates a TreeLengthDistribution based on the parameter values supplied.\n*/\nTreeLengthDistribution::TreeLengthDistribution(\n  double alphaT,     /**< is the shape parameter of the gamma distribution of tree length (mean = shape/scale) */\n  double betaT,      /**< is the scale parameter of the gamma distribution of tree length (mean = shape/scale) */\n  double alpha,      /**< is the Dirichlet parameter governing external edge length */\n  double c)          /**< is the Dirichlet parameter governing internal edge length */\n  :  _alphaT(alphaT), _betaT(betaT), _alpha(alpha), _c(c), _lot(&_myLot), _num_internal_edges(0), _num_external_edges(0)\n\t{\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tInitializes parameters to the values contained in their counterparts in `other'.\n*/\nTreeLengthDistribution::TreeLengthDistribution(\n  const TreeLengthDistribution & other)\t/* the tree length distribution to clone */\n  : _alphaT(other._alphaT), _betaT(other._betaT), _alpha(other._alpha), _c(other._c), _lot(other._lot), _num_internal_edges(0), _num_external_edges(0)\n\t{\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|   Returns the string \"TreeLengthDistribution\".\n*/\nstd::string TreeLengthDistribution::GetDistributionName() const\n\t{\n\treturn \"TreeLengthDistribution\";\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|   Returns a string similar to \"TreeLengthDistribution(1.0,0.1,1.0,1.0)\".\n*/\nstd::string TreeLengthDistribution::GetDistributionDescription() const\n\t{\n\treturn boost::str(boost::format(\"TreeLengthDistribution(%#.5f,%#.5f,%#.5f,%#.5f)\") % _alphaT % _betaT % _alpha % _c);\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tCreates two probability distributions that can be used to sample from this tree length distribution. The first is\n|   a Gamma distribution stored in the data member `_tldist' and the second is a Dirichlet distribution stored in the\n|   data member `_eldist'. The edge length distribution depends on the number of internal and external edges, so this\n|   function must be called whenever either of these numbers changes. The number of internal and external edges last\n|   used is stored in `_num_internal_edges' and `_num_external_edges', respectively, to avoid unnecessary\n|   construction/destruction.\n*/\nvoid TreeLengthDistribution::SetupSamplingDistributions(\n  unsigned num_external, /**< is the number of external edges */\n  unsigned num_internal) /**< is the number of internal edges */\n\t{\n    unsigned num_total = num_external + num_internal;\n    PHYCAS_ASSERT(num_total > 0);\n    if (num_external == _num_external_edges && num_internal == _num_internal_edges && _tldist && _eldist)\n        {\n        return;\n        }\n\n    //std::cerr << \"Creating _tldist and _eldist for \" << num_internal << \" internal and \" << num_external << \" external edges\" << std::endl;\n\n    double_vect_t dirichlet_params(num_total, _alpha);\n\n    //std::cerr << \"\\n\\n***** dirichlet_params before *****\" << std::endl;\n    //std::copy(dirichlet_params.begin(), dirichlet_params.end(), std::ostream_iterator<double>(std::cerr, \"|\"));\n    //std::cerr << \"\\n\\n\" << std::endl;\n\n    std::transform(dirichlet_params.begin()+num_external, dirichlet_params.end(), dirichlet_params.begin()+num_external, boost::lambda::_1*_c);\n\n    //std::cerr << \"\\n\\n***** dirichlet_params after *****\" << std::endl;\n    //std::copy(dirichlet_params.begin(), dirichlet_params.end(), std::ostream_iterator<double>(std::cerr, \"|\"));\n    //std::cerr << \"\\n\\n\" << std::endl;\n\n    _tldist.reset(new GammaDistribution(_alphaT, 1.0/_betaT));   // Rannala-Zhu-Yang paper defines Gamma mean = shape/scale, which contrasts with other parts of phycas where Gamma mean = shape*scale\n    _tldist->SetLot(_lot);\n\n    _eldist .reset(new DirichletDistribution(dirichlet_params));\n    _eldist->SetLot(_lot);\n\n    _num_internal_edges = num_internal;\n    _num_external_edges = num_external;\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tSamples and returns a point from this distribution. In the returned point, the `num_external' external edge lengths\n|   will be first, followed by the `num_internal' internal edge lengths.\n*/\ndouble_vect_t TreeLengthDistribution::Sample(\n  unsigned num_external, /**< is the number of external edges */\n  unsigned num_internal) /**< is the number of internal edges */\n\t{\n    SetupSamplingDistributions(num_external, num_internal);\n\n    double tree_length = _tldist->Sample();\n    double_vect_t edge_lengths = _eldist->Sample();\n    std::transform(edge_lengths.begin(), edge_lengths.end(), edge_lengths.begin(), boost::lambda::_1*tree_length);\n\n\treturn edge_lengths;\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tReturns the natural logarithm of the probability density function evaluated for the edge lengths in the supplied\n|   tree `t'. Assumes supplied tree `t' is unrooted. See Rannala, Zhu and Yang (2012) for details.\n*/\ndouble TreeLengthDistribution::GetLnPDF(\n  TreeShPtr t) const \t/**< is the tree for which the density is to be evaulated */\n\t{\n    PHYCAS_ASSERT(!t->IsRooted());\n\n    double tree_length = 0.0;\n    double sum_internal = 0.0;\n    double sum_external = 0.0;\n    unsigned num_total = 0;\n    unsigned num_internal = 0;\n    unsigned num_external = 0;\n    for (preorder_iterator it = t->begin(); it != t->end(); ++it)\n        {\n        if (!it->IsAnyRoot())\n            {\n            double edge_length = it->GetEdgeLen();\n            tree_length += edge_length;\n            num_total++;\n            if (it->IsTip() || it->IsSubroot())\n                {\n                num_external++;\n                sum_external += (_alpha - 1.0)*log(edge_length);\n                }\n            else\n                {\n                num_internal++;\n                sum_internal += (_alpha*_c - 1.0)*log(edge_length);\n                }\n            }\n        }\n\n    PHYCAS_ASSERT(num_total == num_internal + num_external);\n\n    // logterm1 is first line of equation 36 in Rannala, Zhu, and Yang (2012)\n    double logterm1 = _alphaT*log(_betaT) - _cdf.LnGamma(_alphaT) - _betaT*tree_length + (_alphaT - 1.0)*log(tree_length);\n\n    // logterm2 is second line of equation 36 in Rannala, Zhu, and Yang (2012)\n    double beta_term = _cdf.LnGamma(_alpha)*num_external + _cdf.LnGamma(_alpha*_c)*num_internal - _cdf.LnGamma(_alpha*num_external + _alpha*_c*num_internal);\n    double logterm2 = sum_internal + sum_external - beta_term;\n\n    // logterm3 is third line of equation 36 in Rannala, Zhu, and Yang (2012)\n    double logterm3 = (1.0 - _alpha*num_external - _alpha*_c*num_internal)*log(tree_length);\n\n    double lnPDF = logterm1 + logterm2 + logterm3;\n    return lnPDF;\n    }\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tReturns the natural logarithm of the probability density function evaluated for the edge lengths in the supplied\n|   tree `t'. Assumes supplied tree `t' is unrooted. See Rannala, Zhu and Yang (2012) for details.\n*/\ndouble TreeLengthDistribution::GetRelativeLnPDF(\n  TreeShPtr t) const  \t/**< is the tree for which the density is to be evaulated */\n\t{\n\treturn GetLnPDF(t);\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tCreates a new object that is a clone of this object, calls the new object's SetLot member function (passing the\n|\tsupplied Lot object `other'), and returns a pointer to it. The caller is expected to manage the new object.\n*/\nTreeLengthDistribution * TreeLengthDistribution::cloneAndSetLot(Lot * other) const\n\t{\n    TreeLengthDistribution * clone = new TreeLengthDistribution(*this);\n\tclone->SetLot(other);\n\treturn clone;\n    }\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tCreates a new object that is a clone of this object and returns a pointer to it. Caller is expected to manage the\n|   new object.\n*/\nTreeLengthDistribution * TreeLengthDistribution::Clone() const\n\t{\n    return new TreeLengthDistribution(*this);\n    }\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tReplaces the random number generator used with the TreeLengthDistribution::Sample member function. The original\n|\trandom number generator\t(data member `myLot') can be replaced by calling the ProbabilityDistribution::ResetLot\n|\tfunction. Note that this object does not take ownership of the Lot object whose pointer is specified as `other'.\n|\tIt is assumed that `other' is non-NULL.\n*/\nvoid TreeLengthDistribution::SetLot(\n\tLot * other) /**< is a pointer to the random number generator object to be used subsequently by Sample */\n\t{\n\tif (other == NULL)\n\t\tthrow XProbDist(\"attempt made to install a non-existent pseudorandom number generator\");\n\t_lot = other;\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tSets the random number seed for the `myLot' data member. Note that if TreeLengthDistribution::SetLot has been\n|\tcalled, calling TreeLengthDistribution::SetSeed is pointless because you will not be setting the seed for the\n|\tcorrect random number generator!\n*/\nvoid TreeLengthDistribution::SetSeed(\n  unsigned rnseed)\t/**< is the new seed value */\n\t{\n\t_myLot.SetSeed(rnseed);\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tMakes the data member `_lot' (which is used as the random number generator by the member function\n|\tTreeLengthDistribution::Sample) point to the local data member _myLot. This function only needs to be called if\n|\tTreeLengthDistribution::SetLot has been called previously to replace the random number generator used by\n|\tTreeLengthDistribution::Sample.\n*/\nvoid TreeLengthDistribution::ResetLot()\n\t{\n\t_lot = &_myLot;\n\t}\n\n} // namespace phycas\n\n\n", "meta": {"hexsha": "0c93b8d416a6b98a9b953087389a2e1af72727ee", "size": 12720, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cpp/tree_length_distribution.cpp", "max_stars_repo_name": "plewis/phycas", "max_stars_repo_head_hexsha": "9f5a4d9b2342dab907d14a46eb91f92ad80a5605", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-09-24T23:12:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-12T07:07:01.000Z", "max_issues_repo_path": "src/cpp/tree_length_distribution.cpp", "max_issues_repo_name": "plewis/phycas", "max_issues_repo_head_hexsha": "9f5a4d9b2342dab907d14a46eb91f92ad80a5605", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cpp/tree_length_distribution.cpp", "max_forks_repo_name": "plewis/phycas", "max_forks_repo_head_hexsha": "9f5a4d9b2342dab907d14a46eb91f92ad80a5605", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-11-23T10:35:43.000Z", "max_forks_repo_forks_event_max_datetime": "2015-11-23T10:35:43.000Z", "avg_line_length": 48.0, "max_line_length": 198, "alphanum_fraction": 0.5879716981, "num_tokens": 2679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754371026367, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.4558030215983029}}
{"text": "#ifndef _NCTX_PY_CNTRL_\n#define _NCTX_PY_CNTRL_\n\n#include <boost/graph/betweenness_centrality.hpp>\n#include <boost/graph/page_rank.hpp>\n#include <boost/graph/property_maps/constant_property_map.hpp>\n\nnamespace nctx { namespace python {\n  template<bool d>\n  class CentralityDummy{};\n\n  template <bool directed>\n  inline void wrap_centralities(){\n    using PMap = PropertyMapValueHolder<double_t,directed>;\n    using GraphC = GraphContainer<directed>;\n    using Vertex = typename GraphC::vertex;\n    using Edge = typename GraphC::edge;\n\n    py::class_<CentralityDummy<directed>>(\"AlgCentralities\", py::no_init)\n      //~ .def(\"page_rank_ctx\", +[](GraphC& gc, py::object fct_decision, PMap& rank_map, double_t damping = 0.85, int n_iter = 20) {\n        //~ std::function<double_t (Vertex, Vertex)> lmbd_decision = lambda_wrapper_t<double_t, Vertex, Vertex>( fct_decision );\n        //~ auto g = gc.get_graph();\n        //~ page_rank_ctx(\n          //~ g,\n          //~ rank_map.get_map(),\n          //~ lmbd_decision,\n          //~ boost::graph::n_iterations(n_iter),\n          //~ damping);\n      //~ })\n      //~ .def(\"page_rank_ctx\", +[](GraphC& gc, py::object fct_decision, double_t damping = 0.85, int n_iter = 20) -> PMap {\n        //~ std::function<double_t (Vertex, Vertex)> lmbd_decision = lambda_wrapper_t<double_t, Vertex, Vertex>( fct_decision );\n        //~ auto g = gc.get_graph();\n        //~ PMap rank_map(gc, \"pagerank_constraint\");\n        //~ page_rank_ctx(\n          //~ g,\n          //~ rank_map.get_map(),\n          //~ lmbd_decision,\n          //~ boost::graph::n_iterations(n_iter),\n          //~ damping);\n        //~ return rank_map;\n      //~ })\n      //~ .def(\"page_rank\", +[](GraphC& gc, PMap& rank_map, double_t damping = 0.85, int n_iter = 20) {\n        //~ auto g = gc.get_graph();\n        //~ page_rank(\n          //~ g,\n          //~ rank_map.get_map(),\n          //~ boost::graph::n_iterations(n_iter),\n          //~ damping);\n      //~ })\n      //~ .def(\"page_rank\", +[](GraphC& gc, double_t damping = 0.85, int n_iter = 20) -> PMap {\n        //~ auto g = gc.get_graph();\n        //~ PMap rank_map(gc, \"pagerank\");\n        //~ page_rank(\n          //~ g,\n          //~ rank_map.get_map(),\n          //~ boost::graph::n_iterations(n_iter),\n          //~ damping);\n        //~ return rank_map;\n      //~ })\n      .def(\"betweenness_ctx\", +[](GraphC& gc, py::object fct_decision, PMap& centr_map) {\n        std::function<bool (Vertex, Vertex, Vertex)> lmbd_decision = lambda_wrapper_t<bool, Vertex, Vertex, Vertex>( fct_decision );\n        auto g = gc.get_graph();\n        auto weight_map = boost::make_constant_property<Edge>(1.0);\n        brandes_betweenness_centrality_ctx(\n          g,\n          centrality_map(centr_map.get_map())\n          .vertex_index_map(gc.make_index_map())\n          .weight_map(weight_map),\n          lmbd_decision);\n      },(py::arg(\"g\"), py::arg(\"betw_decision_fct\"), py::arg(\"outmap\")), \"Betweenness centrality with dynamic contextual constraints.\\n\\n\\n\\nUsing this function allows obtaining betweenness centrality under dynamic contextual constraints. Enforcement of constraints is the task of the given user-defined function.\\n\\nThe function enforcing contextual constraints is evaluated at each node during shortest path traversal. The function needs to evaluate to True or False allowing an edge to be visited or not. As parameters, the current state of the betweenness calculation is passed to the function, i.e. the starting node for which a centrality value is being calculated, the current node, and the descending node in question. If the function returns False, the descending node is not being visited.\\n\\nThe three nodes are passed as indices allowing for access of (external) attribute and other associated information.\\n\\nNote that the decision function is evaluated more than once during path traversal. That means, there should not happen any resource-intense computation inside this function. Also, it does not allow to keep track of the status of calculation, e.g. by calculating the visited edges or something similar.\\n\\nIf the decision function simply returns True all the time, this function results in the unaltered betweenness centrality values.\\n\\nObtaining betweenness centrality is based on Brandes' efficient algorithm. At the current stage, the implementation allows for single-core execution only.\\n\\n\\n\\nArgs:\\n    g The graph object\\n    betw_decision_fct A function enforcing constraints. The signature of the function is ``(vertex index, vertex index, vertex index) -> Bool``.\\n    outmap (PropertyMapDouble): map in which centrality values will be written\\n\\nExample:\\n    >>> outmap = PropertyMapDouble(g, 'betw_ctx')\\n    >>> AlgCentralities.betweenness_ctx(g,lambda _start,_current,_next: (True),outmap)\\n\\n\\n\")\n      .def(\"betweenness_ctx\", +[](GraphC& gc, py::object fct_decision) -> PMap {\n        std::function<bool (Vertex, Vertex, Vertex)> lmbd_decision = lambda_wrapper_t<bool, Vertex, Vertex, Vertex>( fct_decision );\n        auto g = gc.get_graph();\n        PMap centr_map(gc, \"betweenness_constraint\");\n        auto weight_map = boost::make_constant_property<Edge>(1.0);\n        brandes_betweenness_centrality_ctx(\n          g,\n          centrality_map(centr_map.get_map())\n          .vertex_index_map(gc.make_index_map())\n          .weight_map(weight_map),\n          lmbd_decision);\n        return centr_map;\n      },(py::arg(\"g\"), py::arg(\"betw_decision_fct\")), \"Betweenness centrality with dynamic contextual constraints.\\n\\n\\n\\nUsing this function allows obtaining betweenness centrality under dynamic contextual constraints. Enforcement of constraints is the task of the given user-defined function.\\n\\nThe function enforcing contextual constraints is evaluated at each node during shortest path traversal. The function needs to evaluate to True or False allowing an edge to be visited or not. As parameters, the current state of the betweenness calculation is passed to the function, i.e. the starting node for which a centrality value is being calculated, the current node, and the descending node in question. If the function returns False, the descending node is not being visited.\\n\\nThe three nodes are passed as indices allowing for access of (external) attribute and other associated information.\\n\\nNote that the decision function is evaluated more than once during path traversal. That means, there should not happen any resource-intense computation inside this function. Also, it does not allow to keep track of the status of calculation, e.g. by calculating the visited edges or something similar.\\n\\nIf the decision function simply returns True all the time, this function results in the unaltered betweenness centrality values.\\n\\nObtaining betweenness centrality is based on Brandes' efficient algorithm. At the current stage, the implementation allows for single-core execution only.\\n\\n\\n\\nArgs:\\n    g The graph object\\n    betw_decision_fct A function enforcing constraints. The signature of the function is ``(vertex index, vertex index, vertex index) -> Bool``.\\n\\n\\nReturns:\\n    PropertyMapDouble: list of centrality values named betweenness_constraint\\n\\nExample:\\n    >>> outmap = AlgCentralities.betweenness_ctx(g,lambda _start,_current,_next: (True))\\n\\n\\n\")\n      .def(\"closeness_ctx\", +[](GraphC& gc, py::object fct_decision, PMap& centr_map) {\n        std::function<bool (Vertex, Vertex, Vertex)> lmbd_decision = lambda_wrapper_t<bool, Vertex, Vertex, Vertex>( fct_decision );\n        auto g = gc.get_graph();\n        auto weight_map = boost::make_constant_property<Edge>(1);\n\n        closeness_centrality_ctx(g,\n            b::weight_map(weight_map)\n            .centrality_map(centr_map.get_map())\n            .vertex_index_map(gc.make_index_map()),\n            lmbd_decision);\n      },(py::arg(\"g\"), py::arg(\"clsn_decision_fct\") ,py::arg(\"outmap\")), \"Closeness centrality with dynamic contextual constraints.\\n\\n\\n\\nUsing this function allows obtaining closeness centrality under dynamic contextual constraints. Enforcement of constraints is the task of the given user-defined function.\\n\\nThe function enforcing contextual constraints is evaluated at each node during shortest path traversal. The function needs to evaluate to True or False allowing an edge to be visited or not. As parameters, the current state of the centrality calculation is passed to the function, i.e. the starting node for which a centrality value is being calculated, the current node, and the descending node in question. If the function returns False, the descending node is not being visited.\\n\\nThe three nodes are passed as indices allowing for access of (external) attribute and other associated information.\\n\\nNote that the decision function is evaluated more than once during path traversal. That means, there should not happen any resource-intense computation inside this function. Also, it does not allow to keep track of the status of calculation, e.g. by calculating the visited edges or something similar.\\n\\nIf the decision function simply returns True all the time, this function results in the unaltered betweenness centrality values.\\n\\n\\n\\nArgs:\\n    g The graph object\\n    clsn_decision_fct A function enforcing constraints. The signature of the function is ``(vertex index, vertex index, vertex index) -> Bool``.\\n\\n    outmap (PropertyMapDouble): map in which centrality values will be written\\n\\nExample:\\n    >>> outmap = PropertyMapDouble(g, 'clsn_ctx')\\n    >>> AlgCentralities.closeness_ctx(g,lambda _start,_current,_next: (True),outmap)\\n\\n\\n\")\n      .def(\"closeness_ctx\", +[](GraphC& gc, py::object fct_decision) -> PMap {\n        std::function<bool (Vertex, Vertex, Vertex)> lmbd_decision = lambda_wrapper_t<bool, Vertex, Vertex, Vertex>( fct_decision );\n        auto g = gc.get_graph();\n        PMap centr_map(gc, \"closeness_constraint\");\n        auto weight_map = boost::make_constant_property<Edge>(1);\n\n        closeness_centrality_ctx(g,\n            b::weight_map(weight_map)\n            .centrality_map(centr_map.get_map())\n            .vertex_index_map(gc.make_index_map()),\n            lmbd_decision);\n        return centr_map;\n      },(py::arg(\"g\"), py::arg(\"clsn_decision_fct\")), \"Closeness centrality with dynamic contextual constraints.\\n\\n\\n\\nUsing this function allows obtaining closeness centrality under dynamic contextual constraints. Enforcement of constraints is the task of the given user-defined function.\\n\\nThe function enforcing contextual constraints is evaluated at each node during shortest path traversal. The function needs to evaluate to True or False allowing an edge to be visited or not. As parameters, the current state of the centrality calculation is passed to the function, i.e. the starting node for which a centrality value is being calculated, the current node, and the descending node in question. If the function returns False, the descending node is not being visited.\\n\\nThe three nodes are passed as indices allowing for access of (external) attribute and other associated information.\\n\\nNote that the decision function is evaluated more than once during path traversal. That means, there should not happen any resource-intense computation inside this function. Also, it does not allow to keep track of the status of calculation, e.g. by calculating the visited edges or something similar.\\n\\nIf the decision function simply returns True all the time, this function results in the unaltered betweenness centrality values.\\n\\n\\n\\nArgs:\\n    g The graph object\\n    clsn_decision_fct A function enforcing constraints. The signature of the function is ``(vertex index, vertex index, vertex index) -> Bool``.\\n\\n\\nReturns:\\n    PropertyMapDouble: list of centrality values named closeness_constraint\\n\\nExample:\\n    >>> outmap = AlgCentralities.closeness_ctx(g,lambda _start,_current,_next: (True))\\n\\n\\n\")\n      .def(\"betweenness\", +[](GraphC& gc, PMap& centr_map) {\n        auto g = gc.get_graph();\n        auto weight_map = boost::make_constant_property<Edge>(1.0);\n        brandes_betweenness_centrality(\n          g,\n          centrality_map(centr_map.get_map())\n          .vertex_index_map(gc.make_index_map())\n          .weight_map(weight_map));\n      }, (py::arg(\"g\"), py::arg(\"outmap\")), \"Obtain betweenness centrality for a graph using Brandes' efficient algorithm.\\n\\nArgs:\\n    g (Graph): Graph object\\n    outmap (PropertyMapDouble): map in which centrality values will be written\\n\\nExample:\\n    >>> outmap = PropertyMapDouble(g, 'betw')\\n    >>> AlgCentralities.betweenness(g, outmap)\\n\\n\\n\")\n      .def(\"betweenness\", +[](GraphC& gc) -> PMap {\n        auto g = gc.get_graph();\n        PMap centr_map(gc, \"betweenness\");\n        auto weight_map = boost::make_constant_property<Edge>(1.0);\n        brandes_betweenness_centrality(\n          g,\n          centrality_map(centr_map.get_map())\n          .vertex_index_map(gc.make_index_map())\n          .weight_map(weight_map));\n        return centr_map;\n      }, (py::arg(\"g\")), \"Obtain betweenness centrality for a graph using Brandes' efficient algorithm.\\n\\nArgs:\\n    g (Graph): Graph object\\n\\nReturns:\\n    PropertyMapDouble: list of centrality values named betweenness\\n\\nExample:\\n    >>> outmap = AlgCentralities.betweenness(g)\\n\\n\\n\")\n      .def(\"closeness\", +[](GraphC& gc) -> PMap {\n        auto g = gc.get_graph();\n        PMap centr_map(gc, \"closeness\");\n        auto weight_map = boost::make_constant_property<Edge>(1);\n        std::function<bool (Vertex, Vertex, Vertex)> dummy_decision = [](Vertex s, Vertex u, Vertex v){return true;};\n\n        closeness_centrality_ctx(g,\n            b::weight_map(weight_map)\n            .centrality_map(centr_map.get_map())\n            .vertex_index_map(gc.make_index_map()),\n            dummy_decision);\n\n        return centr_map;\n      }, (py::arg(\"g\")), \"Obtain closeness centrality for a graph.\\n\\nArgs:\\n    g (Graph): Graph object\\n\\nReturns:\\n    PropertyMapDouble: list of centrality values named betweenness\\n\\nExample:\\n    >>> outmap = AlgCentralities.closeness(g)\\n\\n\\n\")\n      .def(\"closeness\", +[](GraphC& gc, PMap& centr_map) {\n        auto g = gc.get_graph();\n        auto weight_map = boost::make_constant_property<Edge>(1);\n        std::function<bool (Vertex, Vertex, Vertex)> dummy_decision = [](Vertex s, Vertex u, Vertex v){return true;};\n\n        closeness_centrality_ctx(g,\n            b::weight_map(weight_map)\n            .centrality_map(centr_map.get_map())\n            .vertex_index_map(gc.make_index_map()),\n            dummy_decision);\n      }, (py::arg(\"g\"), py::arg(\"outmap\")), \"Obtain closeness centrality for a graph.\\n\\nArgs:\\n    g (Graph): Graph object\\n    outmap (PropertyMapDouble): map in which centrality values will be written\\n\\nExample:\\n    >>> outmap = PropertyMapDouble(g, 'clsn')\\n    >>> AlgCentralities.closeness(g, outmap)\\n\\n\\n\")\n      ;\n  }\n\n\n}} //nproc::python\n\n#endif", "meta": {"hexsha": "09bee82454b5dd79854b6a2c82002444083391c6", "size": 14933, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/python_defs/wrap_algs_centralities.hpp", "max_stars_repo_name": "nctx/py3nctx", "max_stars_repo_head_hexsha": "ee01aeaf675bbfd38dc4f37115d577a7796d2c80", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-06-28T10:12:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-12T04:04:30.000Z", "max_issues_repo_path": "src/python_defs/wrap_algs_centralities.hpp", "max_issues_repo_name": "nctx/py3nctx", "max_issues_repo_head_hexsha": "ee01aeaf675bbfd38dc4f37115d577a7796d2c80", "max_issues_repo_licenses": ["MIT"], "max_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_defs/wrap_algs_centralities.hpp", "max_forks_repo_name": "nctx/py3nctx", "max_forks_repo_head_hexsha": "ee01aeaf675bbfd38dc4f37115d577a7796d2c80", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 93.9182389937, "max_line_length": 1935, "alphanum_fraction": 0.7058193263, "num_tokens": 3488, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754371026368, "lm_q2_score": 0.6261241702517975, "lm_q1q2_score": 0.45580301651957805}}
{"text": "/*\n * The MIT License (MIT)\n *\n * Copyright (c) 2017 Hidekazu Ikeno\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/// \\file quasi_cauchy_rrd.hpp\n///\n#ifndef MXPFIT_QUASI_CAUCHY_RRD_HPP\n#define MXPFIT_QUASI_CAUCHY_RRD_HPP\n\n#include <cassert>\n\n#include <Eigen/Core>\n\nnamespace mxpfit\n{\nnamespace detail\n{\n\n//\n// Compute exponential z minus one, exp(z) -1\n//\n// --- for real\ntemplate <typename T>\ninline auto expm1(T x) -> decltype(std::expm1(x))\n{\n    return std::expm1(x);\n}\n// --- for complex\ntemplate <typename T>\nstd::complex<T> expm1(const std::complex<T>& z)\n{\n    constexpr const T inf = std::numeric_limits<T>::infinity();\n    constexpr const T nan = std::numeric_limits<T>::quiet_NaN();\n\n    const T x = std::real(z);\n    const T y = std::imag(z);\n\n    if (std::isnan(x))\n    {\n        return {x, y == T() ? y : x};\n    }\n    else if (!std::isfinite(y))\n    {\n        if (x == inf)\n        {\n            return {-x, nan};\n        }\n        else if (x == -inf)\n        {\n            return {-T(1), std::copysign(T(), y)};\n        }\n        else\n        {\n            return {nan, nan};\n        }\n    }\n    else\n    {\n        const auto u = std::expm1(x);\n        if (y == T())\n        {\n            return {u, y};\n        }\n        else\n        {\n            const auto v = u + T(1);\n            const auto w = std::sin(y / 2);\n            const auto re =\n                std::isfinite(v) ? u - 2 * v * w * w : v * std::cos(y);\n            return {re, v * std::sin(y)};\n        }\n    }\n}\n\n} // namespace: detail\n\n///\n/// ### DefaultQuasiCauchyRRDFunctor\n///\n/// Default Functor class for QuasiCauchyRRD.\n///\n/// \\tparam T Scalar type of matrix elements\n///\n/// This functor is for a quasi-Cauchy matrix whose element is expressed as\n/// \\f$C_{ij}=\\frac{a_{i}b_{j}}{x_{i}+y_{j}}\\f$\n///\ntemplate <typename T>\nstruct DefaultQuasiCauchyRRDFunctor\n{\n    constexpr static T matrix_element(T ai, T bj, T xi, T yj)\n    {\n        return ai * bj / (xi + yj);\n    }\n\n    constexpr static T update_coeff(T xi, T xj, T yj)\n    {\n        return (xi - xj) / (xi + yj);\n    }\n};\n\n///\n/// ### QuasiCauchyRRDFunctorLogPole\n///\n/// Functor class for a rank-revealing Cholesky decomposition of Cauchy-like\n/// matrix appearing in parameter reduction of exponential sum.\n///\n/// \\tparam T Scalar type of matrix elements\n///\n/// This functor is for a Cauchy-like matrix whose element is expressed as\n/// \\f[\n///    C_{ij}=\\frac{a_{i}b_{j}}{exp(p_{i}) - exp(q_{j})}\n/// \\f]\n///\ntemplate <typename T>\nstruct QuasiCauchyRRDFunctorLogPole\n{\n    constexpr static T matrix_element(T ai, T bj, T pi, T qj)\n    {\n        using Eigen::numext::exp;\n        return ai * bj / (exp(qj) * detail::expm1(pi - qj));\n    }\n\n    constexpr static T update_coeff(T pi, T pj, T qj)\n    {\n        using Eigen::numext::exp;\n        // (1 - exp(pj - pi)) / (1 - exp(qj - pi));\n        return detail::expm1(pj - pi) / detail::expm1(qj - pi);\n    }\n};\n\nnamespace detail\n{\n\n// Apply row permutation\ntemplate <typename IPiv, typename MatX, typename VecWork>\nvoid apply_row_permutation(const Eigen::DenseBase<IPiv>& ipiv,\n                           Eigen::DenseBase<MatX>& matX,\n                           Eigen::DenseBase<VecWork>& work)\n{\n    using Index = Eigen::Index;\n    for (Index j = 0; j < matX.cols(); ++j)\n    {\n        for (Index i = 0; i < matX.rows(); ++i)\n        {\n            work(ipiv(i)) = matX(i, j);\n        }\n\n        matX.col(j) = work;\n    }\n}\n\n//\n// Functor class for making dense matrix expression of a quasi-Cauchy matrix\n//\ntemplate <typename VecA, typename VecB, typename VecX, typename VecY,\n          typename FunctorBody>\nstruct quasi_cauchy_functor\n{\n    using Index = Eigen::Index;\n\n    quasi_cauchy_functor(const VecA& a, const VecB& b, const VecX& x,\n                         const VecY& y)\n        : m_a(a), m_b(b), m_x(x), m_y(y)\n    {\n    }\n\n    auto operator()(Index i, Index j) const\n        -> decltype(FunctorBody::matrix_element(typename VecA::Scalar(),\n                                                typename VecB::Scalar(),\n                                                typename VecX::Scalar(),\n                                                typename VecY::Scalar()))\n    {\n        // m_a(i) * m_b(j) / (m_x(i) + m_y(j));\n        return FunctorBody::matrix_element(m_a(i), m_b(j), m_x(i), m_y(j));\n    }\n\nprivate:\n    const VecA& m_a;\n    const VecB& m_b;\n    const VecX& m_x;\n    const VecY& m_y;\n};\n\n} // namespace detail\n\n///\n/// ### QuasiCauchyRRD\n///\n/// \\brief Compute the rank-revealing Cholesky decomposition of a self-adjoint\n///   quasi-Cauchy matrix in high relative accuracy.\n///\n/// \\tparam T the scalar type of matrix to be decomposed\n/// \\tparam Functor Functor class that provides static functions for calculating\n///   matrix elements and Cholesky factors, such that,\n/// ``` c++\n///   /* Compute `ai * bj / (xi + yj)\n///   static T matrix_element(T ai, T bj, T xi, T yj);\n///   /* Compute `(xi - xj) / (xi + yj)\n///   static T update_coeff(T xi, T xj, T yj);\n/// ```\n///\n/// For given arrays of $a_{i},b_{i},x_{i},y_{i} \\, (i=1,2,\\dots,n)$ a\n/// quasi-Cauchy matrix \\f$ C \\f$ is defined as\n///\n///   \\f[\n///     C_{ij} = \\frac{a_{i}^{} b_{j}^{}}{x_{i}^{} + y_{j}^{}} \\quad\n///     (i,j=1,2,\\dots,n).\n///   \\f]\n///\n/// We assume that the matrix \\f$ C \\f$ is self-adjoint and positive\n/// definite. A quasi-Cauchy matrix is usually rank deficient. Let \\f$ m =\n/// \\text{rank}(C) \\f$ then, matrix `C` can have partial Cholesky decomposition\n/// of the form\n///\n///   \\f[ C = (PL)D^2(PL)^{\\ast}, \\f]\n///\n/// where \\f$ L \\f$ is \\f$ n \\times m \\f$ unit triangular (trapezoidal) matrix,\n/// \\f$ D \\f$ is \\f$ m \\times m \\f$ diagonal matrix, and \\f$ P \\f$ is a \\f$ m\n/// \\times n \\f$ permutation matrix.\n///\n///\n/// #### Algorithm\n///\n/// The factorization is made using the modified Gaussian elimination of\n/// complete pivoting (GECP) proposed in Ref. [1], which is also described in\n/// Algorithm 2 and 3 in Ref.[2]. Following the algorithms described in Ref.\n/// [2], we stop the factorization when the diagonal element \\f$ D_{mm} \\f$\n/// becomes smaller than the threshold value, \\f$ D_{mm} \\leq \\delta^2 \\epsilon\n/// \\f$, at certain \\f$ m \\f$ where \\f$ \\delta \\f$ is mimimal target size of\n/// singular values of the systems to be kept in the later step, and \\f$\n/// \\epsilon \\f$ is the machine epsilon. Note that the diagonal elements \\f$\n/// D_{ii} \\f$ are sorted in non-increasing order by complete pivoting.\n///\n///\n/// #### Complexity\n///\n/// The complexity of this algorithm is \\f$\n/// \\mathcal{O}(n(\\log(\\delta\\epsilon)^{-1})^2) \\f$.\n///\n///\n/// #### References\n///\n/// 1. J. Demmel, \"ACCURATE SINGULAR VALUE DECOMPOSITIONS OF STRUCTURED\n///    MATRICES\", SIAM J. Matrix Anal. Appl. **21** (1999) 562-580.\n///    [DOI: https://doi.org/10.1137/S0895479897328716]\n/// 2. T. S. Haut and G. Beylkin, \"FAST AND ACCURATE CON-EIGENVALUE ALGORITHM\n///    FOR OPTIMAL RATIONAL APPROXIMATIONS\", SIAM J. Matrix Anal. Appl. **33**\n///    (2012) 1101-1125.\n///    [DOI: https://doi.org/10.1137/110821901]\n///\n\n// --- Forward declaration\ntemplate <typename T, typename Functor = DefaultQuasiCauchyRRDFunctor<T>>\nclass QuasiCauchyRRD;\n//\n// --- Implementation\n//\ntemplate <typename T, typename Functor>\nclass QuasiCauchyRRD\n{\npublic:\n    using Scalar        = T;\n    using RealScalar    = typename Eigen::NumTraits<T>::Real;\n    using ComplexScalar = std::complex<RealScalar>;\n    using StorageIndex  = Eigen::Index;\n    using Index         = Eigen::Index;\n    using MatrixType    = Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>;\n    using VectorType    = Eigen::Matrix<Scalar, Eigen::Dynamic, 1>;\n    using RealVectorType = Eigen::Matrix<RealScalar, Eigen::Dynamic, 1>;\n    using IndicesType    = Eigen::Matrix<Index, Eigen::Dynamic, 1>;\n\n    ///\n    /// Default constructor\n    ///\n    QuasiCauchyRRD()\n        : m_a(),\n          m_b(),\n          m_x(),\n          m_y(),\n          m_work(),\n          m_ipiv(),\n          m_matPL(),\n          m_vecD(),\n          m_threshold(Eigen::NumTraits<RealScalar>::epsilon()),\n          m_is_initialized()\n    {\n    }\n\n    ///\n    /// Default destructor\n    ///\n    ~QuasiCauchyRRD() = default;\n\n    ///\n    /// Compute RRD of self-adjoint quasi-Cauchy matrix.\n    ///\n    /// \\param[in] a  vector of length @f$ n @f$ defining matrix @f$ C. @f$.\n    /// \\param[in] b  vector of length @f$ n @f$ defining matrix @f$ C. @f$.\n    /// \\param[in] x  vector of length @f$ n @f$ defining matrix @f$ C. @f$\n    /// \\param[in] y  vector of length @f$ n @f$ defining matrix @f$ C. @f$\n    ///\n    template <typename VecA, typename VecB, typename VecX, typename VecY>\n    void\n    compute(const Eigen::EigenBase<VecA>& a, const Eigen::EigenBase<VecB>& b,\n            const Eigen::EigenBase<VecX>& x, const Eigen::EigenBase<VecY>& y)\n    {\n        EIGEN_STATIC_ASSERT_VECTOR_ONLY(VecA);\n        EIGEN_STATIC_ASSERT_VECTOR_ONLY(VecB);\n        EIGEN_STATIC_ASSERT_VECTOR_ONLY(VecX);\n        EIGEN_STATIC_ASSERT_VECTOR_ONLY(VecY);\n\n        m_a = a.derived();\n        m_b = b.derived();\n        m_x = x.derived();\n        m_y = y.derived();\n\n        m_work.resize(a.derived().size());\n        m_ipiv.resize(a.derived().size());\n\n        const Index rank = pivot_order();\n        m_matPL.resize(m_a.derived().size(), rank);\n        m_vecD.resize(rank);\n        factorize();\n\n        // apply row permutations\n        detail::apply_row_permutation(m_ipiv, m_matPL, m_work);\n\n        m_is_initialized = true;\n    }\n\n    ///\n    /// Set threshold value for GECP termination.\n    ///\n    /// We stop GECP step as soon as the diagonal element of Cholesky factor\n    /// \\f$D_{mm}\\f$ becomes smaller than this value.\n    ///\n    QuasiCauchyRRD& setThreshold(RealScalar threshold)\n    {\n        m_threshold = threshold;\n        return *this;\n    }\n\n    ///\n    /// \\return the rank of matrix revealed.\n    ///\n    Index rank() const\n    {\n        return m_vecD.size();\n    }\n\n    ///\n    /// \\return const reference to the rank revealing factor \\f$ X=PL \\f$\n    ///\n    const MatrixType& matrixPL() const\n    {\n        assert(m_is_initialized && \"QuasiCauchyRRD is not initialized\");\n        return m_matPL;\n    }\n\n    ///\n    /// \\return const reference to the rank revealing factor \\f$ D \\f$\n    ///\n    const RealVectorType& vectorD() const\n    {\n        assert(m_is_initialized && \"QuasiCauchyRRD is not initialized\");\n        return m_vecD;\n    }\n\n    ///\n    /// Create dense matrix expression of quasi-Cauchy matrix\n    ///\n    /// \\param[in] a  vector of length @f$ n @f$ defining matrix @f$ C. @f$.\n    /// \\param[in] b  vector of length @f$ n @f$ defining matrix @f$ C. @f$.\n    /// \\param[in] x  vector of length @f$ n @f$ defining matrix @f$ C. @f$\n    /// \\param[in] y  vector of length @f$ n @f$ defining matrix @f$ C. @f$\n    ///\n    template <typename VecA, typename VecB, typename VecX, typename VecY>\n    static Eigen::CwiseNullaryOp<\n        detail::quasi_cauchy_functor<VecA, VecB, VecX, VecY, Functor>,\n        MatrixType>\n    makeDenseExpr(const Eigen::EigenBase<VecA>& a,\n                  const Eigen::EigenBase<VecB>& b,\n                  const Eigen::EigenBase<VecX>& x,\n                  const Eigen::EigenBase<VecY>& y)\n    {\n        EIGEN_STATIC_ASSERT_VECTOR_ONLY(VecA);\n        EIGEN_STATIC_ASSERT_VECTOR_ONLY(VecB);\n        EIGEN_STATIC_ASSERT_VECTOR_ONLY(VecX);\n        EIGEN_STATIC_ASSERT_VECTOR_ONLY(VecY);\n\n        assert(b.size() == a.size());\n        assert(x.size() == a.size());\n        assert(y.size() == a.size());\n\n        using functor_t =\n            detail::quasi_cauchy_functor<VecA, VecB, VecX, VecY, Functor>;\n\n        return MatrixType::NullaryExpr(\n            a.size(), a.size(),\n            functor_t(a.derived(), b.derived(), x.derived(), y.derived()));\n    }\n\nprotected:\n    VectorType m_a;\n    VectorType m_b;\n    VectorType m_x;\n    VectorType m_y;\n    VectorType m_work;\n    IndicesType m_ipiv;\n    MatrixType m_matPL;\n    RealVectorType m_vecD;\n\n    RealScalar m_threshold;\n    bool m_is_initialized;\n\n    Index pivot_order();\n    void factorize();\n};\n\ntemplate <typename T, typename Functor>\ntypename QuasiCauchyRRD<T, Functor>::Index\nQuasiCauchyRRD<T, Functor>::pivot_order()\n{\n    using Eigen::numext::abs;\n\n    const Index n = m_a.size();\n\n    assert(m_b.size() == n);\n    assert(m_x.size() == n);\n    assert(m_y.size() == n);\n    assert(m_work.size() == n);\n    assert(m_ipiv.size() == n);\n\n    //\n    // Form vector g(i) = a(i) * b(i) / (x(i) + y(i))\n    //\n    VectorType& g = m_work;\n\n    for (Index i = 0; i < n; ++i)\n    {\n        g[i] = Functor::matrix_element(m_a[i], m_b[i], m_x[i], m_y[i]);\n    }\n\n    // Initialize rows transposition matrix\n    for (Index i = 0; i < n; ++i)\n    {\n        m_ipiv[i] = i;\n    }\n\n    // GECP iteration\n    Index m = 0;\n    while (m < n)\n    {\n        //\n        // Find m <= l < n such that |g(l)| = max_{m<=k<n}|g(k)|\n        //\n        Index l;\n        auto max_diag = RealScalar();\n        for (Index k = m; k < n; ++k)\n        {\n            const auto abs_gk = abs(g[k]);\n            if (abs_gk > max_diag)\n            {\n                max_diag = abs_gk;\n                l        = k;\n            }\n        }\n\n        if (max_diag < m_threshold)\n        {\n            break;\n        }\n\n        if (l != m)\n        {\n            // Swap elements\n            std::swap(m_ipiv[l], m_ipiv[m]);\n            std::swap(g[l], g[m]);\n            std::swap(m_a[l], m_a[m]);\n            std::swap(m_b[l], m_b[m]);\n            std::swap(m_x[l], m_x[m]);\n            std::swap(m_y[l], m_y[m]);\n        }\n\n        // Update diagonal of Schur complement\n        const auto xm = m_x[m];\n        const auto ym = m_y[m];\n\n        for (Index k = m + 1; k < n; ++k)\n        {\n            // g[k] *= (m_x[k] - xm) / (m_x[k] + ym);\n            g[k] *= Functor::update_coeff(m_x[k], xm, ym);\n            // g[k] *= (m_y[k] - ym) / (m_y[k] + xm);\n            g[k] *= Functor::update_coeff(m_y[k], ym, xm);\n        }\n        ++m;\n    }\n    //\n    // Returns the rank of input matrix\n    //\n    return m;\n}\n\ntemplate <typename T, typename Functor>\nvoid QuasiCauchyRRD<T, Functor>::factorize()\n{\n    using Eigen::numext::real;\n    using Eigen::numext::sqrt;\n\n    const auto n = m_matPL.rows();\n    const auto m = m_matPL.cols();\n\n    m_matPL.setZero();\n    const auto b0 = m_b[0];\n    const auto y0 = m_y[0];\n\n    for (Index l = 0; l < n; ++l)\n    {\n        // m_matPL(l, 0) = m_a[l] * b0 / (m_x[l] + y0);\n        m_matPL(l, 0) = Functor::matrix_element(m_a[l], b0, m_x[l], y0);\n    }\n\n    for (Index k = 1; k < m; ++k)\n    {\n        // Upgrade generators\n        const auto xkm1 = m_x[k - 1];\n        const auto ykm1 = m_y[k - 1];\n        for (Index l = k; l < n; ++l)\n        {\n            // m_a[l] *= (m_x[l] - xkm1) / (m_x[l] + ykm1);\n            m_a[l] *= Functor::update_coeff(m_x[l], xkm1, ykm1);\n        }\n        for (Index l = k; l < n; ++l)\n        {\n            // m_b[l] *= (m_y[l] - ykm1) / (m_y[l] + xkm1);\n            m_b[l] *= Functor::update_coeff(m_y[l], ykm1, xkm1);\n        }\n        // Extract k-th column for Cholesky factors\n        const auto bk = m_b[k];\n        const auto yk = m_y[k];\n        for (Index l = k; l < n; ++l)\n        {\n            m_matPL(l, k) = Functor::matrix_element(m_a[l], bk, m_x[l], yk);\n        }\n    }\n    //\n    // Scale strictly lower triangular part of G\n    //   - diagonal part of G contains D**2\n    //   - L = tril(G) * D^{-2} + I\n    //\n    for (Index j = 0; j < m; ++j)\n    {\n        const auto djj   = real(m_matPL(j, j));\n        const auto scale = RealScalar(1) / djj;\n\n        m_matPL(j, j) = RealScalar(1);\n        m_vecD[j] = sqrt(djj);\n        for (Index i = j + 1; i < n; ++i)\n        {\n            m_matPL(i, j) *= scale;\n        }\n    }\n\n    return;\n}\n\nnamespace detail\n{\n\ntemplate <typename VecA, typename VecX>\nstruct self_adjoint_quasi_cauchy_helper\n{\n    using Scalar =\n        typename Eigen::ScalarBinaryOpTraits<typename VecA::Scalar,\n                                             typename VecX::Scalar>::ReturnType;\n    using MatrixType =\n        Eigen::Matrix<Scalar, VecA::SizeAtCompileTime, VecA::SizeAtCompileTime,\n                      Eigen::ColMajor, VecA::MaxSizeAtCompileTime,\n                      VecA::MaxSizeAtCompileTime>;\n};\n\ntemplate <typename VecA, typename VecX>\nstruct self_adjoint_quasi_cauchy_functor\n{\n    using Scalar =\n        typename Eigen::ScalarBinaryOpTraits<typename VecA::Scalar,\n                                             typename VecX::Scalar>::ReturnType;\n    using Index = Eigen::Index;\n    using MatrixType =\n        Eigen::Matrix<Scalar, VecA::SizeAtCompileTime, VecA::SizeAtCompileTime,\n                      Eigen::ColMajor, VecA::MaxSizeAtCompileTime,\n                      VecA::MaxSizeAtCompileTime>;\n\n    self_adjoint_quasi_cauchy_functor(const VecA& a, const VecX& x)\n        : m_a(a), m_x(x)\n    {\n    }\n\n    Scalar operator()(Index i, Index j) const\n    {\n        using Eigen::numext::conj;\n        return m_a(i) * conj(m_a(j)) / (m_x(i) + conj(m_x(j)));\n    }\n\nprivate:\n    const VecA& m_a;\n    const VecX& m_x;\n};\n\n} // namespace detail\n\n///\n/// ### SelfAdjointQuasiCauchyRRD\n///\n/// \\brief  Compute the rank-revealing decomposition (RRD) of a self-adjoint\n///   quasi-Cauchy matrix in high relative accuracy.\n///\n/// \\tparam T  the scalar type of matrix to be decomposed\n///\n/// For given arrays of $a_{i},x_{i} \\, (i=1,2,\\dots,n)$ a self-adjoint\n/// quasi-Cauchy matrix \\f$ C \\f$ is defined as\n///\n///   \\f[\n///     C_{ij} = \\frac{a_{i}^{} a_{j}^{\\ast}}{x_{i}^{} + x_{j}^{\\ast}} \\quad\n///     (i,j=1,2,\\dots,n).\n///   \\f]\n///\n/// We assume that the matrix \\f$ C \\f$ is also positive definite. A\n/// quasi-Cauchy matrix is usually rank deficient. Let \\f$ m = \\text{rank}(C)\n/// \\f$ then, matrix `C` can have partial Cholesky decomposition of the form\n///\n///   \\f[ C = (PL)D^2(PL)^{\\ast}, \\f]\n///\n/// where \\f$ L \\f$ is \\f$ n \\times m \\f$ unit triangular (trapezoidal) matrix,\n/// \\f$ D \\f$ is \\f$ m \\times m \\f$ diagonal matrix, and \\f$ P \\f$ is a \\f$ m\n/// \\times n \\f$ permutation matrix.\n///\n/// #### Algorithm\n///\n/// The factorization is made using the modified Gaussian elimination of\n/// complete pivoting (GECP) proposed in Ref. [1], which is also described in\n/// Algorithm 2 and 3 in Ref.[2]. Following the algorithms described in Ref.\n/// [2], we stop the factorization when the diagonal element \\f$ D_{mm} \\f$\n/// becomes smaller than the threshold value, \\f$ D_{mm} \\leq \\delta^2 \\epsilon\n/// \\f$, at certain \\f$ m \\f$ where \\f$ \\delta \\f$ is mimimal target size of\n/// singular values of the systems to be kept in the later step, and \\f$\n/// \\epsilon \\f$ is the machine epsilon. Note that the diagonal elements \\f$\n/// D_{ii} \\f$ are sorted in non-increasing order by complete pivoting.\n///\n/// #### Complexity\n///\n/// The complexity of this algorithm is \\f$\n/// \\mathcal{O}(n(\\log(\\delta\\epsilon)^{-1})^2) \\f$.\n///\n///\n/// #### References\n///\n/// 1. J. Demmel, \"ACCURATE SINGULAR VALUE DECOMPOSITIONS OF STRUCTURED\n///    MATRICES\", SIAM J. Matrix Anal. Appl. **21** (1999) 562-580.\n///    [DOI: https://doi.org/10.1137/S0895479897328716]\n/// 2. T. S. Haut and G. Beylkin, \"FAST AND ACCURATE CON-EIGENVALUE ALGORITHM\n///    FOR OPTIMAL RATIONAL APPROXIMATIONS\", SIAM J. Matrix Anal. Appl. **33**\n///    (2012) 1101-1125.\n///    [DOI: https://doi.org/10.1137/110821901]\n///\ntemplate <typename T>\nclass SelfAdjointQuasiCauchyRRD\n{\npublic:\n    using Scalar        = T;\n    using RealScalar    = typename Eigen::NumTraits<T>::Real;\n    using ComplexScalar = std::complex<RealScalar>;\n    using StorageIndex  = Eigen::Index;\n    using Index         = Eigen::Index;\n    using MatrixType    = Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>;\n    using VectorType    = Eigen::Matrix<Scalar, Eigen::Dynamic, 1>;\n    using RealVectorType = Eigen::Matrix<RealScalar, Eigen::Dynamic, 1>;\n    using IndicesType    = Eigen::Matrix<Index, Eigen::Dynamic, 1>;\n\n    ///\n    /// Default constructor\n    ///\n    SelfAdjointQuasiCauchyRRD()\n        : m_a(),\n          m_x(),\n          m_work(),\n          m_ipiv(),\n          m_matPL(),\n          m_vecD(),\n          m_threshold(Eigen::NumTraits<RealScalar>::epsilon()),\n          m_is_initialized(false)\n    {\n    }\n\n    ///\n    /// Default destructor\n    ///\n    ~SelfAdjointQuasiCauchyRRD() = default;\n\n    ///\n    /// Compute RRD of self-adjoint quasi-Cauchy matrix.\n    ///\n    /// @param[in] a  vector of length @f$ n @f$ defining matrix @f$ C. @f$.\n    /// @param[in] x  vector of length @f$ n @f$ defining matrix @f$ C. @f$\n    ///\n    template <typename VecA, typename VecX>\n    void compute(const Eigen::EigenBase<VecA>& a,\n                 const Eigen::EigenBase<VecX>& x)\n    {\n        EIGEN_STATIC_ASSERT_VECTOR_ONLY(VecA);\n        EIGEN_STATIC_ASSERT_VECTOR_ONLY(VecX);\n\n        m_a = a.derived();\n        m_x = x.derived();\n        m_work.resize(a.derived().size());\n        m_ipiv.resize(a.derived().size());\n\n        const Index rank = pivot_order();\n        m_matPL.resize(m_a.derived().size(), rank);\n        m_vecD.resize(rank);\n        factorize();\n\n        // apply row permutations\n        detail::apply_row_permutation(m_ipiv, m_matPL, m_work);\n\n        m_is_initialized = true;\n    }\n\n    ///\n    /// Set threshold value for GECP termination.\n    ///\n    /// We stop GECP step as soon as the diagonal element of Cholesky factor\n    /// \\f$D_{mm}\\f$ becomes smaller than this value.\n    ///\n    SelfAdjointQuasiCauchyRRD& setThreshold(RealScalar threshold)\n    {\n        m_threshold = threshold;\n        return *this;\n    }\n\n    ///\n    /// \\return the rank of matrix revealed.\n    ///\n    Index rank() const\n    {\n        return m_vecD.size();\n    }\n    ///\n    /// \\return const reference to the rank revealing factor \\f$ X=PL \\f$\n    ///\n    const MatrixType& matrixPL() const\n    {\n        assert(m_is_initialized &&\n               \"SelfAdjointQuasiCauchyRRD is not initialized\");\n        return m_matPL;\n    }\n\n    ///\n    /// \\return const reference to the rank revealing factor \\f$ D \\f$\n    ///\n    const RealVectorType& vectorD() const\n    {\n        assert(m_is_initialized &&\n               \"SelfAdjointQuasiCauchyRRD is not initialized\");\n        return m_vecD;\n    }\n\n    ///\n    /// Create dense matrix expression of quasi-Cauchy matrix\n    ///\n    /// \\param[in] a  vector of length @f$ n @f$ defining matrix @f$ C. @f$.\n    /// \\param[in] x  vector of length @f$ n @f$ defining matrix @f$ C. @f$\n    ///\n    template <typename VecA, typename VecX>\n    static Eigen::CwiseNullaryOp<\n        detail::self_adjoint_quasi_cauchy_functor<VecA, VecX>, MatrixType>\n    makeDenseExpr(const Eigen::DenseBase<VecA>& a,\n                  const Eigen::DenseBase<VecX>& x)\n    {\n        EIGEN_STATIC_ASSERT_VECTOR_ONLY(VecA);\n        EIGEN_STATIC_ASSERT_VECTOR_ONLY(VecX);\n        using functor_t = detail::self_adjoint_quasi_cauchy_functor<VecA, VecX>;\n\n        assert(a.size() == x.size());\n\n        return MatrixType::NullaryExpr(a.size(), a.size(),\n                                       functor_t(a.derived(), x.derived()));\n    }\n\nprotected:\n    VectorType m_a;\n    VectorType m_x;\n    VectorType m_work;\n    IndicesType m_ipiv;\n    MatrixType m_matPL;\n    RealVectorType m_vecD;\n\n    RealScalar m_threshold;\n    bool m_is_initialized;\n\n    Index pivot_order();\n    void factorize();\n};\n\ntemplate <typename T>\nEigen::Index SelfAdjointQuasiCauchyRRD<T>::pivot_order()\n{\n    using Eigen::numext::abs;\n    using Eigen::numext::abs2;\n    using Eigen::numext::conj;\n\n    const Index n = m_a.size();\n\n    assert(m_x.size() == n);\n    assert(m_work.size() == n);\n    assert(m_ipiv.size() == n);\n\n    //\n    // Form vector g(i) = a(i) * b(i) / (x(i) + y(i))\n    //\n    VectorType& g = m_work;\n\n    for (Index i = 0; i < n; ++i)\n    {\n        g[i] = m_a[i] * conj(m_a[i]) / (m_x[i] + conj(m_x[i]));\n    }\n\n    // Initialize rows transposition matrix\n    for (Index i = 0; i < n; ++i)\n    {\n        m_ipiv(i) = i;\n    }\n\n    // GECP iteration\n    Index m = 0;\n    while (m < n)\n    {\n        //\n        // Find m <= l < n such that |g(l)| = max_{m<=k<n}|g(k)|\n        //\n        Index l;\n        auto max_diag = RealScalar();\n        for (Index k = m; k < n; ++k)\n        {\n            const auto abs_gk = abs(g[k]);\n            if (abs_gk > max_diag)\n            {\n                max_diag = abs_gk;\n                l        = k;\n            }\n        }\n\n        if (max_diag < m_threshold)\n        {\n            break;\n        }\n\n        if (l != m)\n        {\n            // Swap elements\n            std::swap(m_ipiv[l], m_ipiv[m]);\n            std::swap(g[l], g[m]);\n            std::swap(m_a[l], m_a[m]);\n            std::swap(m_x[l], m_x[m]);\n        }\n\n        // Update diagonal of Schur complement\n        const auto xm = m_x[m];\n        const auto ym = conj(m_x[m]);\n\n        for (Index k = m + 1; k < n; ++k)\n        {\n            const auto s1 = (m_x[k] - xm) / (m_x[k] + ym);\n            g[k] *= s1 * conj(s1);\n        }\n        ++m;\n    }\n    //\n    // Returns the rank of input matrix\n    //\n    return m;\n}\n\ntemplate <typename T>\nvoid SelfAdjointQuasiCauchyRRD<T>::factorize()\n{\n    using Eigen::numext::conj;\n    using Eigen::numext::real;\n    using Eigen::numext::sqrt;\n\n    const auto n = m_matPL.rows();\n    const auto m = m_matPL.cols();\n\n    m_matPL.setZero();\n    const auto b0 = conj(m_a(0));\n    const auto y0 = conj(m_x(0));\n\n    for (Index l = 0; l < n; ++l)\n    {\n        m_matPL(l, 0) = m_a[l] * b0 / (m_x[l] + y0);\n    }\n\n    for (Index k = 1; k < m; ++k)\n    {\n        // Upgrade generators\n        const auto xkm1 = m_x[k - 1];\n        const auto ykm1 = conj(xkm1);\n        for (Index l = k; l < n; ++l)\n        {\n            m_a[l] *= (m_x[l] - xkm1) / (m_x[l] + ykm1);\n        }\n        // Extract k-th column for Cholesky factors\n        const auto bk = conj(m_a[k]);\n        const auto yk = conj(m_x[k]);\n        for (Index l = k; l < n; ++l)\n        {\n            m_matPL(l, k) = m_a[l] * bk / (m_x[l] + yk);\n        }\n    }\n    //\n    // Scale strictly lower triangular part of G\n    //   - diagonal part of G contains D**2\n    //   - L = tril(G) * D^{-2} + I\n    //\n    for (Index j = 0; j < m; ++j)\n    {\n        const auto djj   = real(m_matPL(j, j));\n        const auto scale = RealScalar(1) / djj;\n\n        m_matPL(j, j) = RealScalar(1);\n        m_vecD[j] = sqrt(djj);\n        for (Index i = j + 1; i < n; ++i)\n        {\n            m_matPL(i, j) *= scale;\n        }\n    }\n\n    return;\n}\n\n} // namespace: mxpfit\n\n#endif /* MXPFIT_QUASI_CAUCHY_RRD_HPP */\n", "meta": {"hexsha": "fcdba81eec516115b4bedfa2fb30e6e8b4d3ee1c", "size": 27557, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mxpfit/quasi_cauchy_rrd.hpp", "max_stars_repo_name": "hydeik/mxpfit", "max_stars_repo_head_hexsha": "a18621b191e426f549374cff0af3374861e9f065", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-04-25T07:07:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T09:13:11.000Z", "max_issues_repo_path": "include/mxpfit/quasi_cauchy_rrd.hpp", "max_issues_repo_name": "hydeik/mxpfit", "max_issues_repo_head_hexsha": "a18621b191e426f549374cff0af3374861e9f065", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-07-04T08:42:03.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-15T02:57:05.000Z", "max_forks_repo_path": "include/mxpfit/quasi_cauchy_rrd.hpp", "max_forks_repo_name": "hydeik/mxpfit", "max_forks_repo_head_hexsha": "a18621b191e426f549374cff0af3374861e9f065", "max_forks_repo_licenses": ["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.5564766839, "max_line_length": 80, "alphanum_fraction": 0.5583699242, "num_tokens": 8013, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583376458152, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.4557794563324928}}
{"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\u00e4nkt), 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\nint main(int, char**)\n{\n    using namespace std;\n    \n    mtl::compressed2D<double> m(3, 3);\n    {\n\tmtl::mat::inserter<mtl::compressed2D<double> > ins(m);\n\tins(0, 1) << 2.0; ins(1, 0) << 1.0;\n\tins(1, 1) << 4.0; ins(2, 2) << 5.0;\n    }\n\n    mtl::dense_vector<double> x(3), y(3);\n    for (unsigned i= 0; i < size(x); i++) x[i]= double(i+1);\n\n    y = trans(m) * x;\n    cout << y << '\\n';\n\n    MTL_THROW_IF(y[0] != 2.0, mtl::runtime_error(\"y[0] should be 2.0!\\n\"));\n\n    return 0;\n}\n", "meta": {"hexsha": "a58b5ac11a3b18bb5416f6baede9fc1c6bf433f4", "size": 1033, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/transposed_sparse_matrix_vector_product_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/transposed_sparse_matrix_vector_product_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/transposed_sparse_matrix_vector_product_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": 26.4871794872, "max_line_length": 94, "alphanum_fraction": 0.6176185866, "num_tokens": 343, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.4557794433850593}}
{"text": "// Author(s): Jeroen van der Wulp\n// Copyright: see the accompanying file COPYING or copy at\n// https://svn.win.tue.nl/trac/MCRL2/browser/trunk/COPYING\n//\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//\n/// \\file sort_expression_test.cpp\n/// \\brief Basic regression test for sort expressions.\n\n#include <boost/test/minimal.hpp>\n#include <iostream>\n\n#include \"mcrl2/data/bool.h\"\n#include \"mcrl2/data/parse.h\"\n#include \"mcrl2/data/rewriter.h\"\n#include \"mcrl2/data/standard_utility.h\"\n\nusing namespace mcrl2;\nusing namespace mcrl2::data;\n\ntemplate < typename Rewriter >\nvoid representation_check(Rewriter& R, data_expression const& input, data_expression const& expected, const data_specification& spec)\n{\n  data_expression output(R(normalize_sorts(input,spec)));\n\n  BOOST_CHECK(normalize_sorts(expected,spec) == output);\n\n  if (output != normalize_sorts(expected,spec))\n  {\n    std::clog << \"--- test failed --- \" << data::pp(input) << \" ->* \" << data::pp(expected) << std::endl\n              << \"input    \" << data::pp(input) << std::endl\n              << \"expected \" << data::pp(expected) << std::endl\n              << \"R(input) \" << data::pp(output) << std::endl\n              << \" -- term representations -- \" << std::endl\n              << \"input    \" << input << std::endl\n              << \"expected \" << normalize_sorts(expected,spec)<< std::endl\n              << \"R(input) \" << normalize_sorts(output,spec) << std::endl;\n  }\n}\n\nvoid number_test()\n{\n  using namespace sort_bool;\n  using namespace sort_pos;\n  using namespace sort_nat;\n  using namespace sort_int;\n  using namespace sort_real;\n\n  BOOST_CHECK(data::detail::as_decimal_string(1) == \"1\");\n  BOOST_CHECK(data::detail::as_decimal_string(2) == \"2\");\n  BOOST_CHECK(data::detail::as_decimal_string(3) == \"3\");\n  BOOST_CHECK(data::detail::as_decimal_string(4) == \"4\");\n  BOOST_CHECK(data::detail::as_decimal_string(144) == \"144\");\n\n  // Test character array arithmetic\n  std::vector< char > numbers;\n  numbers = data::detail::string_to_vector_number(\"1\");\n  BOOST_CHECK(data::detail::vector_number_to_string(numbers) == \"1\");\n\n  data::detail::decimal_number_multiply_by_two(numbers);\n  BOOST_CHECK(data::detail::vector_number_to_string(numbers) == \"2\");\n\n  data::detail::decimal_number_increment(numbers);\n  BOOST_CHECK(data::detail::vector_number_to_string(numbers) == \"3\");\n\n  data::detail::decimal_number_increment(numbers);\n  BOOST_CHECK(data::detail::vector_number_to_string(numbers) == \"4\");\n\n  data::detail::decimal_number_multiply_by_two(numbers);\n  BOOST_CHECK(data::detail::vector_number_to_string(numbers) == \"8\");\n\n  data::detail::decimal_number_multiply_by_two(numbers);\n  BOOST_CHECK(data::detail::vector_number_to_string(numbers) == \"16\");\n\n  data::detail::decimal_number_divide_by_two(numbers);\n  BOOST_CHECK(data::detail::vector_number_to_string(numbers) == \"8\");\n\n  BOOST_CHECK(sort_pos::positive_constant_as_string(number(sort_pos::pos(), \"1\")) == \"1\");\n  BOOST_CHECK(sort_pos::positive_constant_as_string(number(sort_pos::pos(), \"10\")) == \"10\");\n  BOOST_CHECK(sort_nat::natural_constant_as_string(number(sort_nat::nat(), \"0\")) == \"0\");\n  BOOST_CHECK(sort_nat::natural_constant_as_string(number(sort_nat::nat(), \"1\")) == \"1\");\n  BOOST_CHECK(sort_nat::natural_constant_as_string(number(sort_nat::nat(), \"10\")) == \"10\");\n  BOOST_CHECK(sort_int::integer_constant_as_string(number(sort_int::int_(), \"-10\")) == \"-10\");\n  BOOST_CHECK(sort_int::integer_constant_as_string(number(sort_int::int_(), \"10\")) == \"10\");\n\n  data_specification specification = parse_data_specification(\"sort A = Real;\");\n\n  mcrl2::data::rewriter R(specification);\n\n  representation_check(R, number(sort_pos::pos(), \"1\"), sort_pos::c1(),specification);\n  representation_check(R, number(sort_nat::nat(), \"1\"), R(normalize_sorts(pos2nat(sort_pos::c1()),specification)),specification);\n  representation_check(R, number(sort_int::int_(), \"-1\"), R(cneg(sort_pos::c1())),specification);\n  representation_check(R, normalize_sorts(number(sort_real::real_(), \"1\"),specification), R(normalize_sorts(pos2real(sort_pos::c1()),specification)),specification);\n\n  representation_check(R, pos(\"11\"), cdub(true_(), cdub(true_(), cdub(false_(), c1()))),specification);\n  representation_check(R, pos(12), cdub(false_(), cdub(false_(), cdub(true_(), c1()))),specification);\n  representation_check(R, nat(\"18\"), R(normalize_sorts(pos2nat(cdub(false_(), cdub(true_(), cdub(false_(), cdub(false_(), c1()))))),specification)),specification);\n  representation_check(R, nat(12), R(normalize_sorts(pos2nat(cdub(false_(), cdub(false_(), cdub(true_(), c1())))),specification)),specification);\n  representation_check(R, int_(\"0\"), R(nat2int(c0())),specification);\n  representation_check(R, int_(\"-1\"), cneg(c1()),specification);\n  representation_check(R, int_(-2), cneg(cdub(false_(), c1())),specification);\n  representation_check(R, real_(\"0\"), R(normalize_sorts(nat2real(c0()),specification)),specification);\n  representation_check(R, real_(\"-1\"), R(normalize_sorts(int2real(cneg(c1())),specification)),specification);\n  representation_check(R, real_(-2), R(normalize_sorts(int2real(cneg(cdub(false_(), c1()))),specification)),specification);\n\n}\n\nvoid list_construction_test()\n{\n  using namespace mcrl2::data::sort_list;\n  using namespace mcrl2::data::sort_bool;\n\n  data_expression_vector expressions;\n\n  expressions.push_back(true_());\n  expressions.push_back(false_());\n  expressions.push_back(true_());\n  expressions.push_back(false_());\n\n  data_specification specification;\n\n  mcrl2::data::rewriter R(specification, jitty);\n\n  representation_check(R, sort_list::list(bool_(), expressions),\n                       R(cons_(bool_(), expressions[0], cons_(bool_(), expressions[1],\n                               cons_(bool_(), expressions[2], cons_(bool_(), expressions[3], empty(bool_())))))),specification);\n}\n\nvoid convert_test()\n{\n  std::vector< data_expression > l;\n\n  l.push_back(sort_bool::true_());\n\n  atermpp::aterm_list al(l.begin(),l.end());\n\n  BOOST_CHECK(l.size() == al.size());\n}\n\nint test_main(int argc, char** argv)\n{\n  number_test();\n\n  list_construction_test();\n\n  convert_test();\n\n  return EXIT_SUCCESS;\n}\n\n", "meta": {"hexsha": "a022c9408f95223f29c0eb842086264d61e4175d", "size": 6255, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libraries/data/test/utility_test.cpp", "max_stars_repo_name": "wiegerw/mcrl3", "max_stars_repo_head_hexsha": "15260c92ab35930398d6dfb34d31351b05101ca9", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-22T09:16:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-22T09:16:39.000Z", "max_issues_repo_path": "libraries/data/test/utility_test.cpp", "max_issues_repo_name": "wiegerw/mcrl3", "max_issues_repo_head_hexsha": "15260c92ab35930398d6dfb34d31351b05101ca9", "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": "libraries/data/test/utility_test.cpp", "max_forks_repo_name": "wiegerw/mcrl3", "max_forks_repo_head_hexsha": "15260c92ab35930398d6dfb34d31351b05101ca9", "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.8823529412, "max_line_length": 164, "alphanum_fraction": 0.7011990408, "num_tokens": 1592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.4557794433850593}}
{"text": "/*\n * tsdf_difference_statistics.hpp\n *\n *  Created on: Mar 15, 2019\n *      Author: Gregory Kramida\n *   Copyright: 2019 Gregory Kramida\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n */\n\n#pragma once\n\n//stdlib\n#include <iostream>\n\n//libraries\n#include <Eigen/Eigen>\n\n//local\n#include \"../math/typedefs.hpp\"\n\nnamespace eig = Eigen;\n\nnamespace telemetry {\n/**\n * A structure for logging statistics pertaining to numerical differences between corresponding locations in the\n * canonical and the live (target and source) TSDF fields after optimization\n */\ntemplate<typename Coordinates>\nstruct TsdfDifferenceStatistics {\n\tfloat difference_min = 0.0f;\n\tfloat difference_max = 0.0f;\n\tfloat difference_mean = 0.0f;\n\tfloat difference_standard_deviation = 0.0f;\n\tCoordinates biggest_difference_location = Coordinates(0);\n\n\tTsdfDifferenceStatistics() = default;\n\tTsdfDifferenceStatistics(\n\t\t\tfloat difference_min,\n\t\t\tfloat difference_max,\n\t\t\tfloat difference_mean,\n\t\t\tfloat difference_standard_deviation,\n\t\t\tCoordinates biggest_difference_location\n\t\t\t);\n\n\teig::VectorXf to_array();\n\n\tbool operator==(const TsdfDifferenceStatistics& rhs);\n\tbool operator!=(const TsdfDifferenceStatistics& rhs);\n};\ntemplate<typename Coordinates>\nstd::ostream &operator<<(std::ostream &ostr, const TsdfDifferenceStatistics<Coordinates> &ts);\n\ntemplate<typename Coordinates, typename ScalarContainer>\nTsdfDifferenceStatistics<Coordinates> build_tsdf_difference_statistics(const ScalarContainer& canonical_field,\n\t\tconst ScalarContainer& live_field);\n\ntypedef TsdfDifferenceStatistics<math::Vector2i> TsdfDifferenceStatistics2d;\ntypedef TsdfDifferenceStatistics<math::Vector3i> TsdfDifferenceStatistics3d;\n\n} //namespace telemetry\n", "meta": {"hexsha": "e8d6b1a4b7c38bb8169387eb7aa1b97f1c151c1c", "size": 2227, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/telemetry/tsdf_difference_statistics.hpp", "max_stars_repo_name": "Algomorph/LevelSetFusionExperimentsCPP", "max_stars_repo_head_hexsha": "f56962f0ad5c62e6706f818062782a2e1660afda", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2019-01-07T14:12:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T01:48:03.000Z", "max_issues_repo_path": "src/telemetry/tsdf_difference_statistics.hpp", "max_issues_repo_name": "Algomorph/LevelSetFusionExperimentsCPP", "max_issues_repo_head_hexsha": "f56962f0ad5c62e6706f818062782a2e1660afda", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2018-12-19T16:43:33.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-06T19:50:22.000Z", "max_forks_repo_path": "src/telemetry/tsdf_difference_statistics.hpp", "max_forks_repo_name": "Algomorph/LevelSetFusionExperimentsCPP", "max_forks_repo_head_hexsha": "f56962f0ad5c62e6706f818062782a2e1660afda", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-01-07T14:12:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-06T06:30:24.000Z", "avg_line_length": 30.9305555556, "max_line_length": 112, "alphanum_fraction": 0.7759317467, "num_tokens": 493, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.45577943869739584}}
{"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#include <iostream>\n#include <stdint.h>\n#include <vector>\n#include <Eigen/Dense>\n\n#include <dpMM/dpMM.hpp>\n#include <dpMM/cat.hpp>\n#include <dpMM/niw.hpp>\n\nusing namespace Eigen;\nusing std::endl;\nusing std::cout; using std::vector; using std::string;\n\n/*\n * DP mixture model\n * following Neal [[http://www.stat.purdue.edu/~rdutta/24.PDF]]\n * Algo 3\n */\ntemplate <class Dist>\nclass DpStickMM : public DpMM<double>\n{\npublic:\n  DpStickMM(double alpha, const Dist& H)\n    : alpha_(alpha), H_(H)\n   {};\n  ~DpStickMM()\n  {};\n\n  virtual void initialize(const MatrixXd& x);\n  virtual void initialize(const shared_ptr<ClGMMData<double> >& cld)\n    {cout<<\"not supported\"<<endl; assert(false);};\n  virtual void sampleLabels();\n  virtual void sampleParameters(){;}; \n  virtual const VectorXu & getLabels() {return z_;};\n  virtual uint32_t getK() const { return z_.maxCoeff()+1;};\n\n  VectorXd getCounts();\n\nprivate:\n  void removeEmptyClusters();\n\n  double alpha_; // \n  vector<Dist> models_;\n\n  MatrixXd x_;\n  VectorXu z_; // indicators\n  Dist H_; // \n};\n\n// ---------------- impl -----------------------------------------------------\ntemplate <class Dist> \nvoid DpStickMM<Dist>::initialize(const MatrixXd& x)\n{\n  uint32_t K0=1;\n  x_ = x;\n  z_.setZero(x.cols(),1);\n  for (uint32_t k=0; k<K0; ++k)\n    models_.push_back(Dist(H_));\n  cout<<models_.size()<<endl;\n  //cout<<x_<<endl;\n  cout<<alpha_<<endl;\n  if (K0>1)\n  {\n    VectorXd pi(K0);\n    pi.setOnes();\n    pi /= static_cast<double>(K0);\n    Catd cat(pi,H_.pRndGen_);\n    for (uint32_t i=0; i<z_.size(); ++i)\n      z_(i) = cat.sample();\n  }\n};\n\ntemplate <class Dist>\nVectorXd DpStickMM<Dist>::getCounts()\n{\n  VectorXd counts(getK());\n  counts.setZero();\n//TODO\n//  for(uint32_t k=0; k<getK(); ++k)\n//    counts(k) = models_[k]->count();\n  return counts;\n};\n\ntemplate <class Dist> \nvoid DpStickMM<Dist>::sampleLabels()\n{\n  double N = z_.size();\n  for(uint32_t i=0; i<z_.size(); ++i)\n  {\n    // compute clustercounts \n    VectorXd Nk(models_.size()); Nk.setZero(models_.size());\n    for(uint32_t ii=0; ii<z_.size(); ++ii)\n      Nk(z_(ii))++;\n    // compute distribution pi over indicators\n    VectorXd pi(models_.size()+1);\n    for (uint32_t k=0; k<models_.size(); ++k)\n      pi(k) = log(Nk(k))-log(N+alpha_) +models_[k].logPosteriorProb(x_,z_,k,i);\n    pi(models_.size()) = log(alpha_)-log(N+alpha_)+H_.logProb(x_.col(i));\n    // normalize pi and exponentiate it\n    double pi_max = pi.maxCoeff();\n    pi = (pi.array()-(pi_max + log((pi.array() - pi_max).exp().sum()))).exp().matrix();\n    // sample new indicator\n    z_(i) = Catd(pi,H_.pRndGen_).sample();\n    // if z_i was a new cluster\n    if(z_(i)==models_.size())\n      models_.push_back(H_);\n\n    // -------- outputs --------------\n    if(i%100 ==0)\n    {\n      cout<<\" @i=\"<<i\n        <<\"\\tcounts=\"<<Nk.transpose()<<endl;\n    }\n  }\n  this->removeEmptyClusters();\n};\n\ntemplate <class Dist>\nvoid DpStickMM<Dist>::removeEmptyClusters()\n{\n  for(uint32_t k=models_.size()-1; k>=0; --k)\n  {\n    bool haveCluster_k = false;\n    for(uint32_t i=0; i<z_.size(); ++i)\n      if(z_(i)==k)\n      {\n        haveCluster_k = true;\n        break;\n      }\n    if (!haveCluster_k)\n    {\n      for (uint32_t i=0; i<z_.size(); ++i)\n        if(z_(i) >= k) z_(i) --;\n      models_.erase(models_.begin()+k);\n    }\n  }\n}\n\n", "meta": {"hexsha": "2906c46977dd30c9342bac68de1f2bf42faae39c", "size": 3427, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/dpMM/dpmmSampler.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/dpmmSampler.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/dpmmSampler.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": 23.7986111111, "max_line_length": 87, "alphanum_fraction": 0.5946892326, "num_tokens": 1055, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583124210896, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.4557794304376258}}
{"text": "/**\n * @file test-jump.cpp\n *\n * @brief test jump function.\n *\n * @author Mutsuo Saito (Hiroshima University)\n * @author Makoto Matsumoto (The University of Tokyo)\n *\n * Copyright (C) 2012 Mutsuo Saito, Makoto Matsumoto,\n * Hiroshima University and The University of Tokyo.\n * All rights reserved.\n *\n * The 3-clause BSD License is applied to this software, see\n * LICENSE.txt\n */\n#include <iostream>\n#include <fstream>\n#include <iomanip>\n#include <sstream>\n#include <string>\n#include <inttypes.h>\n#include <stdint.h>\n#include <time.h>\n#include <NTL/GF2X.h>\n#include <NTL/vec_GF2.h>\n#include <NTL/ZZ.h>\n#include \"dSFMT-calc-jump.hpp\"\n#include \"dSFMT-jump.h\"\n\nusing namespace NTL;\nusing namespace std;\nusing namespace dsfmt;\n\nstatic void read_file(GF2X& characteristic, int line_no, const string& file);\nstatic int test(dsfmt_t * dsfmt, GF2X& poly);\nstatic int check(dsfmt_t *a, dsfmt_t *b, int verbose);\nstatic void print_state(dsfmt_t *a, dsfmt_t * b);\nstatic void print_state_line(w128_t *a, w128_t *b);\nstatic void print_sequence(dsfmt_t *a, dsfmt_t * b);\nstatic int speed(dsfmt_t * dsfmt, GF2X& characteristic);\n\nint main(int argc, char * argv[]) {\n    if (argc <= 1) {\n\tprintf(\"%s -s|-c [prefix]\\n\", argv[0]);\n\treturn -1;\n    }\n    string prefix = \"poly.\";\n    if (argc >= 3) {\n\tprefix = argv[2];\n    }\n    stringstream ss_file;\n    GF2X characteristic;\n    ss_file << prefix << DSFMT_MEXP << \".txt\";\n    read_file(characteristic, 0, ss_file.str());\n    dsfmt_t dsfmt;\n    if (argv[1][1] == 's') {\n\treturn speed(&dsfmt, characteristic);\n    } else {\n\treturn test(&dsfmt, characteristic);\n    }\n}\n\nstatic int speed(dsfmt_t * dsfmt, GF2X& characteristic)\n{\n    uint32_t seed = 1234;\n    long step = 10000;\n    int exp = 4;\n    ZZ test_count;\n    string jump_string;\n    clock_t start;\n    double elapsed1;\n    double elapsed2;\n\n    dsfmt_init_gen_rand(dsfmt, seed);\n    test_count = step;\n    for (int i = 0; i < 10; i++) {\n\tstart = clock();\n\tcalc_jump(jump_string, test_count, characteristic);\n\telapsed1 = clock() - start;\n\telapsed1 = elapsed1 * 1000 / CLOCKS_PER_SEC;\n\tcout << \"mexp \"\n\t     << setw(5)\n\t     << DSFMT_MEXP\n\t     << \" jump 10^\"\n\t     << setfill('0') << setw(2)\n\t     << exp\n\t     << \" steps  calc_jump:\"\n\t     << setfill(' ') << setiosflags(ios::fixed)\n\t     << setw(6) << setprecision(3)\n\t     << elapsed1\n\t     << \"ms\"\n\t     << endl;\n\tstart = clock();\n\n\tfor (int j = 0; j < 10; j++) {\n\t    dSFMT_jump(dsfmt, jump_string.c_str());\n\t}\n\telapsed2 = clock() - start;\n\telapsed2 = elapsed2 * 1000 / 10 / CLOCKS_PER_SEC;\n\tcout << \"mexp \"\n\t     << setw(5)\n\t     << DSFMT_MEXP\n\t     << \" jump 10^\"\n\t     << setfill('0') << setw(2)\n\t     << exp\n\t     << \" steps dSFMT_jump:\"\n\t     << setfill(' ') << setiosflags(ios::fixed)\n\t     << setw(6) << setprecision(3)\n\t     << elapsed2\n\t     << \"ms\"\n\t     << endl;\n\ttest_count *= 100;\n\texp += 2;\n    }\n    return 0;\n}\n\nstatic void read_file(GF2X& characteristic, int line_no, const string& file)\n{\n    ifstream ifs(file.c_str());\n    string line;\n    for (int i = 0; i < line_no; i++) {\n\tifs >> line;\n\tifs >> line;\n    }\n    if (ifs) {\n\tifs >> line;\n\tline = \"\";\n\tifs >> line;\n    }\n    stringtopoly(characteristic, line);\n#if defined(DEBUG)\n    cout << \"line = \" << line << endl;\n    cout << \"deg = \" << deg(characteristic) << endl;\n    cout << \"cha = \" << characteristic << endl;\n    string x;\n    polytostring(x, characteristic);\n    cout << \"x = \" << x << endl;\n#endif\n}\n\nstatic int check(dsfmt_t *a, dsfmt_t *b, int verbose)\n{\n    int check = 0;\n    for (int i = 0; i < 100; i++) {\n\tdouble x = dsfmt_genrand_close_open(a);\n\tdouble y = dsfmt_genrand_close_open(b);\n\tif (x != y) {\n\t    print_state(a, b);\n\t    print_sequence(a, b);\n\t    check = 1;\n\t    break;\n\t}\n    }\n    if (check == 0) {\n\tif (verbose) {\n\t    printf(\"OK!\\n\");\n\t}\n    } else {\n\tprintf(\"NG!\\n\");\n    }\n    return check;\n}\n\nstatic void print_state_line(w128_t *a, w128_t *b)\n{\n    printf(\"[\");\n    for (int j = 0; j < 2; j++) {\n\tprintf(\"%016\"PRIx64, a->u[j]);\n\tif (j == 0) {\n\t    printf(\" \");\n\t} else {\n\t    printf(\"]\");\n\t}\n    }\n    printf(\"[\");\n    for (int j = 0; j < 2; j++) {\n\tprintf(\"%016\"PRIx64, b->u[j]);\n\tif (j == 0) {\n\t    printf(\" \");\n\t} else {\n\t    printf(\"]\");\n\t}\n    }\n    printf(\"\\n\");\n}\n\nstatic void print_state(dsfmt_t *a, dsfmt_t * b)\n{\n    printf(\"idx = %d                            idx = %d\\n\",\n\t   a->idx, b->idx);\n    for (int i = 0; (i < 10) && (i < DSFMT_N); i++) {\n\tprint_state_line(&a->status[i], &b->status[i]);\n    }\n    print_state_line(&a->status[DSFMT_N], &b->status[DSFMT_N]);\n}\n\nstatic void print_sequence(dsfmt_t *a, dsfmt_t * b)\n{\n    for (int i = 0; i < 25; i++) {\n\tdouble c, d;\n\tc = dsfmt_genrand_close_open(a);\n\td = dsfmt_genrand_close_open(b);\n\tprintf(\"[%1.15f %1.15f]\\n\", c, d);\n    }\n}\n\nstatic int test(dsfmt_t * dsfmt, GF2X& characteristic)\n{\n    dsfmt_t new_dsfmt_z;\n    dsfmt_t * new_dsfmt = &new_dsfmt_z;\n    uint32_t seed[20] = {1, 2, 3, 4, 5, 6, 7, 8, 9};\n    long steps[] = {1, 2, DSFMT_N + 1,\n\t\t    DSFMT_N * 128 - 1,\n\t\t    DSFMT_N * 128 + 1,\n\t\t    3003,\n\t\t    3004,\n\t\t    200004,\n\t\t    200005,\n\t\t    10000005,\n\t\t    10000006};\n    int steps_size = sizeof(steps) / sizeof(long);\n    ZZ test_count;\n    string jump_string;\n\n    dsfmt_init_gen_rand(dsfmt, seed[0]);\n    dsfmt_genrand_close_open(dsfmt);\n    /* plus jump */\n    for (int index = 0; index < steps_size; index++) {\n//\tdsfmt_init(dsfmt, seed[index]);\n\ttest_count = steps[index];\n\tcout << \"mexp \" << dec << DSFMT_MEXP << \" jump \"\n\t     << test_count << \" steps\" << endl;\n\t*new_dsfmt = *dsfmt;\n\tfor (long i = 0; i < steps[index] * 2; i++) {\n\t    dsfmt_genrand_uint32(dsfmt);\n\t}\n\tcalc_jump(jump_string, test_count, characteristic);\n#if defined(DEBUG)\n\tcout << \"jump string:\" << jump_string << endl;\n\tcout << \"before jump:\" << endl;\n\tprint_state(new_dsfmt, dsfmt);\n#endif\n\tdSFMT_jump(new_dsfmt, jump_string.c_str());\n#if defined(DEBUG)\n\tcout << \"after jump:\" << endl;\n\tprint_state(new_dsfmt, dsfmt);\n#endif\n\tif (check(new_dsfmt, dsfmt, 1)) {\n\t    return 1;\n\t}\n    }\n    dsfmt_t rnd;\n    dsfmt_init_gen_rand(&rnd, (uint32_t)clock());\n    for (int index = 0; index < 100; index++) {\n\tdsfmt_init_gen_rand(dsfmt, dsfmt_genrand_uint32(&rnd));\n\ttest_count = dsfmt_genrand_uint32(&rnd) % 100000;\n\t*new_dsfmt = *dsfmt;\n\tfor (long i = 0; i < test_count * 2; i++) {\n\t    dsfmt_genrand_uint32(dsfmt);\n\t}\n\tcalc_jump(jump_string, test_count, characteristic);\n\tdSFMT_jump(new_dsfmt, jump_string.c_str());\n\tif (check(new_dsfmt, dsfmt, 0)) {\n\t    cout << \"mexp \" << dec << DSFMT_MEXP << \" jump \"\n\t\t << test_count << \" steps \";\n\t    cout << \"check NG!\" << endl;\n\t    return 1;\n\t}\n    }\n    return 0;\n}\n", "meta": {"hexsha": "82bc80e51b350213afca068364c1ae52c0501a2b", "size": 6612, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "jump/test-jump.cpp", "max_stars_repo_name": "mkt-matsumoto-lab/dSFMT", "max_stars_repo_head_hexsha": "6929b76f2ab07e6302f8daece28045d5bec6ff5c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 33.0, "max_stars_repo_stars_event_min_datetime": "2015-04-24T06:39:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-09T14:18:47.000Z", "max_issues_repo_path": "jump/test-jump.cpp", "max_issues_repo_name": "mkt-matsumoto-lab/dSFMT", "max_issues_repo_head_hexsha": "6929b76f2ab07e6302f8daece28045d5bec6ff5c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-09-02T02:08:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-19T06:15:28.000Z", "max_forks_repo_path": "jump/test-jump.cpp", "max_forks_repo_name": "MersenneTwister-Lab/dSFMT", "max_forks_repo_head_hexsha": "6929b76f2ab07e6302f8daece28045d5bec6ff5c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2016-03-09T10:59:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-31T20:36:09.000Z", "avg_line_length": 24.2197802198, "max_line_length": 77, "alphanum_fraction": 0.5863581367, "num_tokens": 2131, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583124210896, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.4557794304376258}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n#include <tuple>\n#include <vector>\n#include <type_traits>\n#include <utility>\n#include <algorithm>\n\n\nnamespace mtao { namespace eigen {\n    template <bool Rows, typename... Args, int... N>\n        auto _stack(std::integer_sequence<int,N...>, const Args&... args) {\n            using namespace Eigen;\n            using Scalar = typename std::tuple_element<0,std::tuple<Args...>>::type::Scalar;\n\n            constexpr static int minCompileRows = std::min<int>({Args::RowsAtCompileTime...});\n            constexpr static int maxCompileRows = std::max<int>({Args::RowsAtCompileTime...});\n            constexpr static int minCompileCols = std::min<int>({Args::ColsAtCompileTime...});\n            constexpr static int maxCompileCols = std::max<int>({Args::ColsAtCompileTime...});\n\n            constexpr static int sumCompileRows = (Args::RowsAtCompileTime + ... + 0);\n            constexpr static int sumCompileCols = (Args::ColsAtCompileTime + ... + 0);\n\n            //constexpr static int myCompRows = (minCompileRows==Dynamic)?Dynamic:(Rows?S:1)*maxCompileRows;\n            //constexpr static int myCompCols = (minCompileCols==Dynamic)?Dynamic:(Rows?1:S)*maxCompileCols;\n            constexpr static int myCompRows = (minCompileRows==Dynamic)?Dynamic:(Rows?sumCompileRows:maxCompileRows);\n            constexpr static int myCompCols = (minCompileCols==Dynamic)?Dynamic:(Rows?maxCompileCols:sumCompileCols);\n            int rows;\n            int cols;\n            std::vector<int> offset(1,0);\n            auto push_sum = [&](int size) {\n                offset.push_back(offset.back() + size);\n            };\n            if constexpr(Rows) {\n                rows = (args.rows() + ... + 0);\n                cols = std::max( {args.cols()...}) ;\n                (push_sum(args.rows()),...);\n            } else {\n                rows = std::max( {args.rows()...}) ;\n                cols = (args.cols() + ... + 0);\n                (push_sum(args.cols()),...);\n            }\n\n\n            using Matf = Matrix<Scalar,myCompRows,myCompCols>;\n            Matf A = Matf::Constant(rows,cols,0);\n\n\n            if constexpr(Rows) {\n                (A.block(offset[N],0,args.rows(),args.cols()).operator=(args),...);\n            } else {\n                (A.block(0,offset[N],args.rows(),args.cols()).operator=(args),...);\n            }\n\n            return A;\n        }\n\n    template <typename... Args>\n        auto vstack(const Args&... args) {\n            return _stack<true>(std::make_integer_sequence<int,sizeof...(Args)>(), std::forward<const Args&>(args)...);\n        }\n    template <typename... Args>\n        auto hstack(const Args&... args) {\n            return _stack<false>(std::make_integer_sequence<int,sizeof...(Args)>(), std::forward<const Args&>(args)...);\n        }\n\n\n    template <typename BeginIt, typename EndIt>\n        auto hstack_iter(BeginIt beginit, EndIt endit) {\n            using CDerived = typename std::decay_t<decltype(*beginit)>;\n\n            constexpr static int CRows = CDerived::RowsAtCompileTime;\n            using Index = typename CDerived::Scalar;\n            using RetCells = Eigen::Matrix<Index,CRows,Eigen::Dynamic>;\n            int ccols = 0;\n            int crows = 0;\n\n            for(auto it = beginit; it != endit; ++it) {\n                auto&& c = *it;\n                if(c.size() > 0) {\n                crows = std::max<int>(crows,c.rows());\n                ccols += c.cols();\n                }\n            }\n            RetCells mC(crows,ccols);\n            ccols = 0;\n            for(auto it = beginit; it != endit; ++it) {\n                auto&& c = *it;\n                if(c.size() > 0) {\n                mC.block(0,ccols,c.rows(),c.cols()) = c;\n                ccols += c.cols();\n                }\n            }\n            return mC;\n        }\n    template <typename BeginIt, typename EndIt>\n        auto vstack_iter(BeginIt beginit, EndIt endit) {\n            using CDerived = typename std::decay_t<decltype(*beginit)>;\n\n            constexpr static int CCols = CDerived::ColsAtCompileTime;\n            using Index = typename CDerived::Scalar;\n            using RetCells = Eigen::Matrix<Index,Eigen::Dynamic,CCols>;\n            int ccols = 0;\n            int crows = 0;\n\n            for(auto it = beginit; it != endit; ++it) {\n                auto&& c = *it;\n                if(c.size() > 0) {\n                ccols = std::max<int>(ccols,c.cols());\n                crows += c.rows();\n                }\n            }\n            RetCells mC(crows,ccols);\n            crows = 0;\n            for(auto it = beginit; it != endit; ++it) {\n                auto&& c = *it;\n                if(c.size() > 0) {\n                mC.block(crows,0,c.rows(),c.cols()) = c;\n                crows += c.rows();\n                }\n            }\n            return mC;\n        }\n}}\n", "meta": {"hexsha": "d763f1338ef1e1ca0abedfc6732dd478e8ad99ef", "size": 4832, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mtao/eigen/stack.hpp", "max_stars_repo_name": "mtao/core", "max_stars_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_stars_repo_licenses": ["MIT"], "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/mtao/eigen/stack.hpp", "max_issues_repo_name": "mtao/core", "max_issues_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-04-18T16:16:05.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-18T16:17:36.000Z", "max_forks_repo_path": "include/mtao/eigen/stack.hpp", "max_forks_repo_name": "mtao/core", "max_forks_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_forks_repo_licenses": ["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.3492063492, "max_line_length": 120, "alphanum_fraction": 0.5113824503, "num_tokens": 1156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154240079185318, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.455747134014612}}
{"text": "#include <iostream>\n#include <vector>\n#include <fstream>\n#include <algorithm>\n#include <boost/date_time.hpp>\n#include \"../mylib/heap.hpp\"\n#include \"../mylib/graph.hpp\"\n#include \"../mylib/dijkstra.hpp\"\n\nvoid load_vertices(const std::string &filename, bool get_r,\n                my::Graph &vertices, my::Graph &vertices_r,\n                u_int64_t &vertice_count, u_int64_t &edge_count){\n\n    std::cout << \"reading file \" << filename << std::endl;\n    std::fstream file(filename, std::ios::in);\n\n    file >> vertice_count >> edge_count;\n\n    vertices.reserve(static_cast<u_int64_t>(vertice_count));\n    for(u_int64_t i = 0; i < vertice_count; i++){\n        vertices.emplace_back(my::Vertice(i));\n        if (get_r) vertices_r.emplace_back(my::Vertice(i));\n    }\n\n    u_int64_t fro, to, weight;\n    while (file >> fro >> to >> weight) {\n        vertices[fro].edges.emplace_back(to, weight);\n        if (get_r) vertices_r[to].edges.emplace_back(fro, weight);\n    }\n    file.close();\n}\n\nstd::vector<unsigned long> getpath(std::vector<unsigned long> ancestors, my::Vertice start, my::Vertice end){\n    std::vector<unsigned long> path;\n    for(auto i = start.index; i != ULONG_MAX; i = ancestors[i]){\n        path.emplace_back(i);\n    }\n    return path;\n}\n\nint main(int argc, char* argv[]) {\n\n    std::string filename = \"../graphs/vg1\";\n    if (argc > 1)\n        filename = argv[1];\n\n    my::Graph vertices;\n    my::Graph vertices_r;\n    u_int64_t vertice_count = 0;\n    u_int64_t edge_count = 0;\n\n    boost::posix_time::ptime start = boost::posix_time::microsec_clock::local_time();\n    load_vertices(filename, true, vertices, vertices_r, vertice_count, edge_count);\n    boost::posix_time::ptime end = boost::posix_time::microsec_clock::local_time();\n    std::cout << \"loaded \" << vertices.size() << \" vertices in \" << (end-start).total_microseconds()/1000000. << \" seconds\" << std::endl;\n\n\n    start = boost::posix_time::microsec_clock::local_time();\n    auto res = my::dijkstra(vertices, 0);\n    auto ancestors = res.first;\n    auto distances = res.second;\n    end = boost::posix_time::microsec_clock::local_time();\n    std::cout << \"found dijkstra in \" << (end-start).total_microseconds()/1000000. << \" seconds\" << std::endl;\n\n    if (ancestors.size() < 10000000){\n        std::string tab = \"\\t\\t\\t\";\n        std::cout << \"Node\" << \"\\t\" << \"ancestor\" << \"\\t\" << \"distance\" << std::endl;\n        for(u_int64_t i = 0; i < ancestors.size() and i < 100; i++){\n            std::cout << i << tab;\n            if (ancestors[i] != ULONG_MAX) {\n                std::cout << ancestors[i];\n            } else {\n                std::cout << \" \";\n            }\n            std::cout << tab;\n            if (distances.at(i) != ULONG_MAX) {\n                 std::cout << distances[i];\n            } else {\n                std::cout << \"unreachable\";\n            }\n            std::cout << std::endl;\n        }\n    }\n\n    std::cout << \"Path from \" << 50 << \" to \" << 0 << std::endl;\n    for(auto i : getpath(ancestors, 50, 0)){\n        std::cout << i;\n        if (i != 0) std::cout << \", \";\n    }\n    std::cout << std::endl;\n\n    return EXIT_SUCCESS;\n\n\n}\n", "meta": {"hexsha": "0986a3618841bffac1b8507c04c29c1bbc84af33", "size": 3138, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "oving8/main.cpp", "max_stars_repo_name": "odderikf/algdat", "max_stars_repo_head_hexsha": "9b5e5ea42ca0fefda3c1e9be5cff0be4797a8aae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-12-12T21:49:32.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-12T21:49:32.000Z", "max_issues_repo_path": "oving8/main.cpp", "max_issues_repo_name": "odderikf/algdat", "max_issues_repo_head_hexsha": "9b5e5ea42ca0fefda3c1e9be5cff0be4797a8aae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "oving8/main.cpp", "max_forks_repo_name": "odderikf/algdat", "max_forks_repo_head_hexsha": "9b5e5ea42ca0fefda3c1e9be5cff0be4797a8aae", "max_forks_repo_licenses": ["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.6875, "max_line_length": 137, "alphanum_fraction": 0.5761631612, "num_tokens": 841, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.45574711642427634}}
{"text": "//////////////////////////////////////////////////////////////////////////////\n// random::location_scale.hpp                                               //\n//                                                                          //\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_RANDOM_LOCATION_SCALE_HPP_ER_2009\n#define BOOST_RANDOM_LOCATION_SCALE_HPP_ER_2009\n#include <vector>\n#include <algorithm>\n#include <iterator>\n#include <boost/range.hpp>\n//#include <boost/random/uniform_real.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/chi_squared.hpp>\nnamespace boost{\nnamespace random{\n\n    // Samples from a location-scale distribution\n    //\n    // X = sigma Z + mu\n    //\n    // TODO Z shouldn't be allowed to be a ref because ref_distribution already\n    // exists\n    template<typename Z>\n    class location_scale_distribution{\n        public:\n            typedef typename remove_cv<\n                typename remove_reference<Z>::type\n            >::type z_type;\n            typedef typename z_type::input_type input_type;\n            typedef typename z_type::result_type result_type;\n\n        location_scale_distribution(){}\n        location_scale_distribution(\n            const result_type& mu,\n            const result_type& sigma,\n            typename call_traits<Z>::param_type z\n        )\n        :mu_(mu),sigma_(sigma),z_(z){}\n\n        template<typename U>\n        result_type operator()(U& urng){ return (this->impl(urng)); }\n\n        template<typename U>\n        result_type operator()(U& urng)const{ return (this->impl(urng)); }\n\n        const result_type& mu()const{ return this->mu_; }\n        const result_type& sigma()const{ return this->sigma_; }\n        const Z& z(){ return this->z_ ;}\n\n        private:\n        result_type mu_;\n        result_type sigma_;\n        typename call_traits<Z>::value_type z_;\n        template<typename U>\n        result_type impl(U& urng){\n            return (this->mu()) + (this->sigma()) * (this->z_)(urng);\n        }\n            \n    };\n\n\n}// random\n}// boost\n\n#endif\n", "meta": {"hexsha": "aded9baf4848e8cbcdef0e24c13ad783e6aca56b", "size": 2542, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "random/boost/random/location_scale.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": "random/boost/random/location_scale.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": "random/boost/random/location_scale.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": 35.3055555556, "max_line_length": 79, "alphanum_fraction": 0.5310778914, "num_tokens": 494, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.45574711642427634}}
{"text": "//  (C) Copyright John Maddock 2015.\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#include <pch.hpp>\n\n#ifndef BOOST_NO_CXX11_HDR_TUPLE\n\n#define BOOST_TEST_MAIN\n#include <boost/test/unit_test.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/math/tools/roots.hpp>\n#include <boost/test/results_collector.hpp>\n#include <boost/test/unit_test.hpp>\n#include <boost/math/special_functions/cbrt.hpp>\n#include <boost/math/special_functions/beta.hpp>\n#include <iostream>\n#include <iomanip>\n#include <tuple>\n#include \"table_type.hpp\"\n\n// No derivatives - using TOMS748 internally.\nstruct cbrt_functor_noderiv\n{ //  cube root of x using only function - no derivatives.\n   cbrt_functor_noderiv(double to_find_root_of) : a(to_find_root_of)\n   { // Constructor just stores value a to find root of.\n   }\n   double operator()(double x)\n   {\n      double fx = x*x*x - a; // Difference (estimate x^3 - a).\n      return fx;\n   }\nprivate:\n   double a; // to be 'cube_rooted'.\n}; // template <class T> struct cbrt_functor_noderiv\n\n// Using 1st derivative only Newton-Raphson\nstruct cbrt_functor_deriv\n{ // Functor also returning 1st derviative.\n   cbrt_functor_deriv(double const& to_find_root_of) : a(to_find_root_of)\n   { // Constructor stores value a to find root of,\n      // for example: calling cbrt_functor_deriv<double>(x) to use to get cube root of x.\n   }\n   std::pair<double, double> operator()(double const& x)\n   { // Return both f(x) and f'(x).\n      double fx = x*x*x - a; // Difference (estimate x^3 - value).\n      double dx = 3 * x*x; // 1st derivative = 3x^2.\n      return std::make_pair(fx, dx); // 'return' both fx and dx.\n   }\nprivate:\n   double a; // to be 'cube_rooted'.\n};\n// Using 1st and 2nd derivatives with Halley algorithm.\nstruct cbrt_functor_2deriv\n{ // Functor returning both 1st and 2nd derivatives.\n   cbrt_functor_2deriv(double const& to_find_root_of) : a(to_find_root_of)\n   { // Constructor stores value a to find root of, for example:\n      // calling cbrt_functor_2deriv<double>(x) to get cube root of x,\n   }\n   std::tuple<double, double, double> operator()(double const& x)\n   { // Return both f(x) and f'(x) and f''(x).\n      double fx = x*x*x - a; // Difference (estimate x^3 - value).\n      double dx = 3 * x*x; // 1st derivative = 3x^2.\n      double d2x = 6 * x; // 2nd derivative = 6x.\n      return std::make_tuple(fx, dx, d2x); // 'return' fx, dx and d2x.\n   }\nprivate:\n   double a; // to be 'cube_rooted'.\n};\n\ntemplate <class T, class Policy>\nstruct ibeta_roots_1   // for first order algorithms\n{\n   ibeta_roots_1(T _a, T _b, T t, bool inv = false)\n      : a(_a), b(_b), target(t), invert(inv) {}\n\n   T operator()(const T& x)\n   {\n      return boost::math::detail::ibeta_imp(a, b, x, Policy(), invert, true) - target;\n   }\nprivate:\n   T a, b, target;\n   bool invert;\n};\n\ntemplate <class T, class Policy>\nstruct ibeta_roots_2   // for second order algorithms\n{\n   ibeta_roots_2(T _a, T _b, T t, bool inv = false)\n      : a(_a), b(_b), target(t), invert(inv) {}\n\n   boost::math::tuple<T, T> operator()(const T& x)\n   {\n      typedef boost::math::lanczos::lanczos<T, Policy> S;\n      typedef typename S::type L;\n      T f = boost::math::detail::ibeta_imp(a, b, x, Policy(), invert, true) - target;\n      T f1 = invert ?\n         -boost::math::detail::ibeta_power_terms(b, a, 1 - x, x, L(), true, Policy())\n         : boost::math::detail::ibeta_power_terms(a, b, x, 1 - x, L(), true, Policy());\n      T y = 1 - x;\n      if (y == 0)\n         y = boost::math::tools::min_value<T>() * 8;\n      f1 /= y * x;\n\n      // make sure we don't have a zero derivative:\n      if (f1 == 0)\n         f1 = (invert ? -1 : 1) * boost::math::tools::min_value<T>() * 64;\n\n      return boost::math::make_tuple(f, f1);\n   }\nprivate:\n   T a, b, target;\n   bool invert;\n};\n\ntemplate <class T, class Policy>\nstruct ibeta_roots_3   // for third order algorithms\n{\n   ibeta_roots_3(T _a, T _b, T t, bool inv = false)\n      : a(_a), b(_b), target(t), invert(inv) {}\n\n   boost::math::tuple<T, T, T> operator()(const T& x)\n   {\n      typedef typename boost::math::lanczos::lanczos<T, Policy>::type L;\n      T f = boost::math::detail::ibeta_imp(a, b, x, Policy(), invert, true) - target;\n      T f1 = invert ?\n         -boost::math::detail::ibeta_power_terms(b, a, 1 - x, x, L(), true, Policy())\n         : boost::math::detail::ibeta_power_terms(a, b, x, 1 - x, L(), true, Policy());\n      T y = 1 - x;\n      if (y == 0)\n         y = boost::math::tools::min_value<T>() * 8;\n      f1 /= y * x;\n      T f2 = f1 * (-y * a + (b - 2) * x + 1) / (y * x);\n      if (invert)\n         f2 = -f2;\n\n      // make sure we don't have a zero derivative:\n      if (f1 == 0)\n         f1 = (invert ? -1 : 1) * boost::math::tools::min_value<T>() * 64;\n\n      return boost::math::make_tuple(f, f1, f2);\n   }\nprivate:\n   T a, b, target;\n   bool invert;\n};\n\n\nBOOST_AUTO_TEST_CASE( test_main )\n{\n   int newton_limits = static_cast<int>(std::numeric_limits<double>::digits * 0.6);\n\n   double arg = 1e-50;\n   boost::uintmax_t iters;\n   double guess;\n   double dr;\n\n   while(arg < 1e50)\n   {\n      double result = boost::math::cbrt(arg);\n      //\n      // Start with a really bad guess 5 times below the result:\n      //\n      guess = result / 5;\n      iters = 1000;\n      // TOMS algo first:\n      std::pair<double, double> r = boost::math::tools::bracket_and_solve_root(cbrt_functor_noderiv(arg), guess, 2.0, true, boost::math::tools::eps_tolerance<double>(), iters);\n      BOOST_CHECK_CLOSE_FRACTION((r.first + r.second) / 2, result, std::numeric_limits<double>::epsilon() * 4);\n      BOOST_CHECK_LE(iters, 14);\n      // Newton next:\n      iters = 1000;\n      dr = boost::math::tools::newton_raphson_iterate(cbrt_functor_deriv(arg), guess, guess / 2, result * 10, newton_limits, iters);\n      BOOST_CHECK_CLOSE_FRACTION(dr, result, std::numeric_limits<double>::epsilon() * 2);\n      BOOST_CHECK_LE(iters, 12);\n      // Halley next:\n      iters = 1000;\n      dr = boost::math::tools::halley_iterate(cbrt_functor_2deriv(arg), guess, result / 10, result * 10, newton_limits, iters);\n      BOOST_CHECK_CLOSE_FRACTION(dr, result, std::numeric_limits<double>::epsilon() * 2);\n      BOOST_CHECK_LE(iters, 7);\n      // Schroder next:\n      iters = 1000;\n      dr = boost::math::tools::schroder_iterate(cbrt_functor_2deriv(arg), guess, result / 10, result * 10, newton_limits, iters);\n      BOOST_CHECK_CLOSE_FRACTION(dr, result, std::numeric_limits<double>::epsilon() * 2);\n      BOOST_CHECK_LE(iters, 11);\n      //\n      // Over again with a bad guess 5 times larger than the result:\n      //\n      iters = 1000;\n      guess = result * 5;\n      r = boost::math::tools::bracket_and_solve_root(cbrt_functor_noderiv(arg), guess, 2.0, true, boost::math::tools::eps_tolerance<double>(), iters);\n      BOOST_CHECK_CLOSE_FRACTION((r.first + r.second) / 2, result, std::numeric_limits<double>::epsilon() * 4);\n      BOOST_CHECK_LE(iters, 14);\n      // Newton next:\n      iters = 1000;\n      dr = boost::math::tools::newton_raphson_iterate(cbrt_functor_deriv(arg), guess, result / 10, result * 10, newton_limits, iters);\n      BOOST_CHECK_CLOSE_FRACTION(dr, result, std::numeric_limits<double>::epsilon() * 2);\n      BOOST_CHECK_LE(iters, 12);\n      // Halley next:\n      iters = 1000;\n      dr = boost::math::tools::halley_iterate(cbrt_functor_2deriv(arg), guess, result / 10, result * 10, newton_limits, iters);\n      BOOST_CHECK_CLOSE_FRACTION(dr, result, std::numeric_limits<double>::epsilon() * 2);\n      BOOST_CHECK_LE(iters, 7);\n      // Schroder next:\n      iters = 1000;\n      dr = boost::math::tools::schroder_iterate(cbrt_functor_2deriv(arg), guess, result / 10, result * 10, newton_limits, iters);\n      BOOST_CHECK_CLOSE_FRACTION(dr, result, std::numeric_limits<double>::epsilon() * 2);\n      BOOST_CHECK_LE(iters, 11);\n      //\n      // A much better guess, 1% below result:\n      //\n      iters = 1000;\n      guess = result * 0.9;\n      r = boost::math::tools::bracket_and_solve_root(cbrt_functor_noderiv(arg), guess, 2.0, true, boost::math::tools::eps_tolerance<double>(), iters);\n      BOOST_CHECK_CLOSE_FRACTION((r.first + r.second) / 2, result, std::numeric_limits<double>::epsilon() * 4);\n      BOOST_CHECK_LE(iters, 12);\n      // Newton next:\n      iters = 1000;\n      dr = boost::math::tools::newton_raphson_iterate(cbrt_functor_deriv(arg), guess, result / 10, result * 10, newton_limits, iters);\n      BOOST_CHECK_CLOSE_FRACTION(dr, result, std::numeric_limits<double>::epsilon() * 2);\n      BOOST_CHECK_LE(iters, 5);\n      // Halley next:\n      iters = 1000;\n      dr = boost::math::tools::halley_iterate(cbrt_functor_2deriv(arg), guess, result / 10, result * 10, newton_limits, iters);\n      BOOST_CHECK_CLOSE_FRACTION(dr, result, std::numeric_limits<double>::epsilon() * 2);\n      BOOST_CHECK_LE(iters, 3);\n      // Schroder next:\n      iters = 1000;\n      dr = boost::math::tools::schroder_iterate(cbrt_functor_2deriv(arg), guess, result / 10, result * 10, newton_limits, iters);\n      BOOST_CHECK_CLOSE_FRACTION(dr, result, std::numeric_limits<double>::epsilon() * 2);\n      BOOST_CHECK_LE(iters, 4);\n      //\n      // A much better guess, 1% above result:\n      //\n      iters = 1000;\n      guess = result * 1.1;\n      r = boost::math::tools::bracket_and_solve_root(cbrt_functor_noderiv(arg), guess, 2.0, true, boost::math::tools::eps_tolerance<double>(), iters);\n      BOOST_CHECK_CLOSE_FRACTION((r.first + r.second) / 2, result, std::numeric_limits<double>::epsilon() * 4);\n      BOOST_CHECK_LE(iters, 12);\n      // Newton next:\n      iters = 1000;\n      dr = boost::math::tools::newton_raphson_iterate(cbrt_functor_deriv(arg), guess, result / 10, result * 10, newton_limits, iters);\n      BOOST_CHECK_CLOSE_FRACTION(dr, result, std::numeric_limits<double>::epsilon() * 2);\n      BOOST_CHECK_LE(iters, 5);\n      // Halley next:\n      iters = 1000;\n      dr = boost::math::tools::halley_iterate(cbrt_functor_2deriv(arg), guess, result / 10, result * 10, newton_limits, iters);\n      BOOST_CHECK_CLOSE_FRACTION(dr, result, std::numeric_limits<double>::epsilon() * 2);\n      BOOST_CHECK_LE(iters, 3);\n      // Schroder next:\n      iters = 1000;\n      dr = boost::math::tools::schroder_iterate(cbrt_functor_2deriv(arg), guess, result / 10, result * 10, newton_limits, iters);\n      BOOST_CHECK_CLOSE_FRACTION(dr, result, std::numeric_limits<double>::epsilon() * 2);\n      BOOST_CHECK_LE(iters, 4);\n\n      arg *= 3.5;\n   }\n\n   //\n   // Test ibeta as this triggers all the pathological cases!\n   //\n#ifndef SC_\n#define SC_(x) x\n#endif\n#define T double\n\n#  include \"ibeta_small_data.ipp\"\n\n   for (unsigned i = 0; i < ibeta_small_data.size(); ++i)\n   {\n      //\n      // These inverse tests are thrown off if the output of the\n      // incomplete beta is too close to 1: basically there is insuffient\n      // information left in the value we're using as input to the inverse\n      // to be able to get back to the original value.\n      //\n      if (ibeta_small_data[i][5] == 0)\n      {\n         iters = 1000;\n         dr = boost::math::tools::newton_raphson_iterate(ibeta_roots_2<double, boost::math::policies::policy<> >(ibeta_small_data[i][0], ibeta_small_data[i][1], ibeta_small_data[i][5]), 0.5, 0.0, 1.0, 53, iters);\n         BOOST_CHECK_EQUAL(dr, 0.0);\n         BOOST_CHECK_LE(iters, 27);\n         iters = 1000;\n         dr = boost::math::tools::halley_iterate(ibeta_roots_3<double, boost::math::policies::policy<> >(ibeta_small_data[i][0], ibeta_small_data[i][1], ibeta_small_data[i][5]), 0.5, 0.0, 1.0, 53, iters);\n         BOOST_CHECK_EQUAL(dr, 0.0);\n         BOOST_CHECK_LE(iters, 10);\n      }\n      else if ((1 - ibeta_small_data[i][5] > 0.001)\n         && (fabs(ibeta_small_data[i][5]) > 2 * boost::math::tools::min_value<double>()))\n      {\n         iters = 1000;\n         double result = ibeta_small_data[i][2];\n         dr = boost::math::tools::newton_raphson_iterate(ibeta_roots_2<double, boost::math::policies::policy<> >(ibeta_small_data[i][0], ibeta_small_data[i][1], ibeta_small_data[i][5]), 0.5, 0.0, 1.0, 53, iters);\n         BOOST_CHECK_CLOSE_FRACTION(dr, result, std::numeric_limits<double>::epsilon() * 200);\n#if defined(BOOST_MSVC) && (BOOST_MSVC == 1600)\n         BOOST_CHECK_LE(iters, 40);\n#else\n         BOOST_CHECK_LE(iters, 27);\n#endif\n         iters = 1000;\n         result = ibeta_small_data[i][2];\n         dr = boost::math::tools::halley_iterate(ibeta_roots_3<double, boost::math::policies::policy<> >(ibeta_small_data[i][0], ibeta_small_data[i][1], ibeta_small_data[i][5]), 0.5, 0.0, 1.0, 53, iters);\n         BOOST_CHECK_CLOSE_FRACTION(dr, result, std::numeric_limits<double>::epsilon() * 200);\n         BOOST_CHECK_LE(iters, 40);\n      }\n      else if (1 == ibeta_small_data[i][5])\n      {\n         iters = 1000;\n         dr = boost::math::tools::newton_raphson_iterate(ibeta_roots_2<double, boost::math::policies::policy<> >(ibeta_small_data[i][0], ibeta_small_data[i][1], ibeta_small_data[i][5]), 0.5, 0.0, 1.0, 53, iters);\n         BOOST_CHECK_EQUAL(dr, 1.0);\n         BOOST_CHECK_LE(iters, 27);\n         iters = 1000;\n         dr = boost::math::tools::halley_iterate(ibeta_roots_3<double, boost::math::policies::policy<> >(ibeta_small_data[i][0], ibeta_small_data[i][1], ibeta_small_data[i][5]), 0.5, 0.0, 1.0, 53, iters);\n         BOOST_CHECK_EQUAL(dr, 1.0);\n         BOOST_CHECK_LE(iters, 10);\n      }\n   }\n\n}\n\n#else\n\nint main() { return 0; }\n\n#endif\n", "meta": {"hexsha": "db45e69e16df864b035427ea7b33a9b3c85cfafc", "size": 13543, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/libs/math/test/test_root_iterations.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/math/test/test_root_iterations.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/math/test/test_root_iterations.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": 41.5429447853, "max_line_length": 212, "alphanum_fraction": 0.6368603707, "num_tokens": 4182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.45574711642427634}}
{"text": "/* Copyright (C) 2012-2019 IBM Corp.\n * This program is Licensed under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *   http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License. See accompanying LICENSE file.\n */\n/**\n * @file eqtesting.cpp\n * @brief Useful fucntions for equality testing...\n */\n#include <NTL/lzz_pXFactoring.h>\n#include \"timing.h\"\n#include \"EncryptedArray.h\"\n\n#include <cstdio>\n\nnamespace helib {\n\n// Map all non-zero slots to 1, leaving zero slots as zero.\n// Assumes that r=1, and that all the slot contain elements from GF(p^d).\n//\n// We compute x^{p^d-1} = x^{(1+p+...+p^{d-1})*(p-1)} by setting y=x^{p-1}\n// and then outputting y * y^p * ... * y^{p^{d-1}}, with exponentiation to\n// powers of p done via Frobenius.\n\n// FIXME: the computation of the \"norm\" y * y^p * ... * y^{p^{d-1}}\n// can be done using O(log d) automorphisms, rather than O(d).\n\nvoid mapTo01(const EncryptedArray& ea, Ctxt& ctxt)\n{\n  long p = ctxt.getPtxtSpace();\n  if (p != ea.getPAlgebra().getP()) // ptxt space is p^r for r>1\n    throw helib::LogicError(\"mapTo01 not implemented for r>1\");\n\n  if (p>2)\n    ctxt.power(p-1); // set y = x^{p-1}\n\n  long d = ea.getDegree();\n  if (d>1) { // compute the product of the d automorphisms\n    std::vector<Ctxt> v(d, ctxt);\n    for (long i=1; i<d; i++)\n      v[i].frobeniusAutomorph(i);\n    totalProduct(ctxt, v);\n  }\n}\n\n\n// computes ctxt^{2^d-1} using a method that takes\n// O(log d) automorphisms and multiplications\nvoid fastPower(Ctxt& ctxt, long d) \n{\n  //OLD: assert(ctxt.getPtxtSpace()==2);\n  helib::assertEq(ctxt.getPtxtSpace(), 2l, \"ptxtSpace must be 2\");\n  if (d <= 1) return;\n\n  Ctxt orig = ctxt;\n\n  long k = NTL::NumBits(d);\n  long e = 1;\n\n  for (long i = k-2; i >= 0; i--) {\n    Ctxt tmp1 = ctxt;\n    tmp1.smartAutomorph(1L << e);\n    ctxt.multiplyBy(tmp1);\n    e = 2*e;\n\n    if (NTL::bit(d, i)) {\n      ctxt.smartAutomorph(2);\n      ctxt.multiplyBy(orig);\n      e += 1;\n    }\n  }\n}\n\n// ===> This function only works for p=2, r=1 <===\n// Test if prefixes of bits in slots are all zero: Set slot j of res[i] to 0\n// if bits 0..i of j'th slot in ctxt are all zero, else it is set to 1\n// It is assumed that res and the res[i]'s are initialized by the caller.\n// Complexity: O(d + n log d) smart automorphisms\n//             O(n d) \nvoid incrementalZeroTest(Ctxt* res[], const EncryptedArray& ea,\n\t\t\t const Ctxt& ctxt, long n)\n{\n  FHE_TIMER_START;\n  long nslots = ea.size();\n  long d = ea.getDegree();\n\n  // compute linearized polynomial coefficients\n\n  std::vector< std::vector<NTL::ZZX> > Coeff;\n  Coeff.resize(n);\n\n  for (long i = 0; i < n; i++) {\n    // coeffients for mask on bits 0..i\n    // L[j] = X^j for j = 0..i, L[j] = 0 for j = i+1..d-1\n\n    std::vector<NTL::ZZX> L;\n    L.resize(d);\n\n    for (long j = 0; j <= i; j++) \n      SetCoeff(L[j], j);\n\n    std::vector<NTL::ZZX> C;\n\n    ea.buildLinPolyCoeffs(C, L);\n\n    Coeff[i].resize(d);\n    for (long j = 0; j < d; j++) {\n      // Coeff[i][j] = to the encoding that has C[j] in all slots\n      // FIXME: maybe encrtpted array should have this functionality\n      //        built in\n      std::vector<NTL::ZZX> T;\n      T.resize(nslots);\n      for (long s = 0; s < nslots; s++) T[s] = C[j];\n      ea.encode(Coeff[i][j], T);\n    }\n  }\n\n  std::vector<Ctxt> Conj(d, ctxt);\n  // initialize Cong[j] to ctxt^{2^j}\n  for (long j = 0; j < d; j++) {\n    Conj[j].smartAutomorph(1L << j);\n  }\n\n  for (long i = 0; i < n; i++) {\n    res[i]->clear();\n    for (long j = 0; j < d; j++) {\n      Ctxt tmp = Conj[j];\n      tmp.multByConstant(Coeff[i][j]);\n      *res[i] += tmp;\n    }\n\n    // *res[i] now has 0..i in each slot\n    // next, we raise to the power 2^d-1\n\n    fastPower(*res[i], d);\n  }\n  FHE_TIMER_STOP;\n}\n\n}\n", "meta": {"hexsha": "2bef5c2d3f1333af24ab5f8dab3d1148d79110ef", "size": 4126, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/eqtesting.cpp", "max_stars_repo_name": "patrick-schwarz/HElib", "max_stars_repo_head_hexsha": "cd267e2ddc6e92886b89f3aa51c416d5c1d2dc59", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-01T07:18:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-01T07:18:47.000Z", "max_issues_repo_path": "src/eqtesting.cpp", "max_issues_repo_name": "wangjinglin0721/HElib", "max_issues_repo_head_hexsha": "cd267e2ddc6e92886b89f3aa51c416d5c1d2dc59", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/eqtesting.cpp", "max_forks_repo_name": "wangjinglin0721/HElib", "max_forks_repo_head_hexsha": "cd267e2ddc6e92886b89f3aa51c416d5c1d2dc59", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0680272109, "max_line_length": 76, "alphanum_fraction": 0.6061560834, "num_tokens": 1337, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.45574711642427623}}
{"text": "//#include <opencv/cv.h>\n//#include <opencv2/imgproc.hpp>\n//#include <opencv2/calib3d.hpp>\n\n#include <Eigen/Core>\n\n#include <sensor_msgs/PointCloud2.h>\n#include <pcl_conversions/pcl_conversions.h>\n#include <pcl/point_cloud.h>\n#include <pcl/point_types.h>\n#include <pcl/PointIndices.h>\n#include <pcl/filters/filter.h>\n#include <pcl/filters/extract_indices.h>\n#include <pcl/segmentation/sac_segmentation.h>\n\n#include <apriltagscpp/TagDetection.h>\n#include <apriltagscpp/AprilTypes.h>\n\n#include <geometry_msgs/Pose.h>\n\n\ndouble GetTagSize(int tag_id)\n{\n    boost::unordered_map<size_t, double>::iterator tag_sizes_it =\n            tag_sizes_.find(tag_id);\n    if(tag_sizes_it != tag_sizes_.end()) {\n        return tag_sizes_it->second;\n    } else {\n        return default_tag_size_;\n    }\n}\n\n/*\nvoid GetMarkerTransformUsingOpenCV(const TagDetection& detection, Eigen::Matrix4d& transform, cv::Mat& rvec, cv::Mat& tvec)\n{\n    // Check if fx,fy or cx,cy are not set\n    if ((camera_info_.K[0] == 0.0) || (camera_info_.K[4] == 0.0) || (camera_info_.K[2] == 0.0) || (camera_info_.K[5] == 0.0))\n    {\n        ROS_WARN(\"Warning: Camera intrinsic matrix K is not set, can't recover 3D pose\");\n    }\n\n    double tag_size = GetTagSize(detection.id);\n\n    std::vector<cv::Point3f> object_pts;\n    std::vector<cv::Point2f> image_pts;\n    double tag_radius = tag_size/2.;\n\n    object_pts.push_back(cv::Point3f(-tag_radius, -tag_radius, 0));\n    object_pts.push_back(cv::Point3f( tag_radius, -tag_radius, 0));\n    object_pts.push_back(cv::Point3f( tag_radius,  tag_radius, 0));\n    object_pts.push_back(cv::Point3f(-tag_radius,  tag_radius, 0));\n\n    image_pts.push_back(detection.p[0]);\n    image_pts.push_back(detection.p[1]);\n    image_pts.push_back(detection.p[2]);\n    image_pts.push_back(detection.p[3]);\n\n    cv::Matx33f intrinsics(camera_info_.K[0], 0, camera_info_.K[2],\n                           0, camera_info_.K[4], camera_info_.K[5],\n                           0, 0, 1);\n\n    cv::Vec4f distortion_coeff(camera_info_.D[0], camera_info_.D[1], camera_info_.D[2], camera_info_.D[3]);\n\n    // Estimate 3D pose of tag\n    // Methods:\n    //   CV_ITERATIVE\n    //     Iterative method based on Levenberg-Marquardt optimization.\n    //     Finds the pose that minimizes reprojection error, being the sum of squared distances\n    //     between the observed projections (image_points) and the projected points (object_pts).\n    //   CV_P3P\n    //     Based on: Gao et al, \"Complete Solution Classification for the Perspective-Three-Point Problem\"\n    //     Requires exactly four object and image points.\n    //   CV_EPNP\n    //     Moreno-Noguer, Lepetit & Fua, \"EPnP: Efficient Perspective-n-Point Camera Pose Estimation\"\n    int method = CV_ITERATIVE;\n    bool use_extrinsic_guess = false; // only used for ITERATIVE method\n    cv::solvePnP(object_pts, image_pts, intrinsics, distortion_coeff, rvec, tvec, use_extrinsic_guess, method);\n\n    cv::Matx33d r;\n    cv::Rodrigues(rvec, r);\n    Eigen::Matrix3d rot;\n    rot << r(0,0), r(0,1), r(0,2),\n            r(1,0), r(1,1), r(1,2),\n            r(2,0), r(2,1), r(2,2);\n\n    Eigen::Matrix4d T;\n    T.topLeftCorner(3,3) = rot;\n    T.col(3).head(3) <<\n                     tvec.at<double>(0), tvec.at<double>(1), tvec.at<double>(2);\n    T.row(3) << 0,0,0,1;\n\n    transform = T;\n}\n*/\n\nclass KinectPoseImprovement{\nprivate:\n    size_t m_num_samples;//recommended 9\n    pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr m_cloud;\n    at::Mat m_tag_space_samples;// 3 by n matrix stores n points in each row\n\npublic:\n    KinectPoseImprovement(\n            size_t num_tag_samples,\n            pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr input_cloud\n    ):\n            m_num_samples(num_tag_samples),\n            m_cloud(input_cloud)\n    {\n        gen_tag_samples();\n    }\n\n\n    void localize_2d(TagDetection& detection, geometry_msgs::Pose& out_pose){\n        Eigen::Matrix4d pose;\n        cv::Mat rvec;\n        cv::Mat tvec;\n        GetMarkerTransformUsingOpenCV(detection, pose, rvec, tvec);\n\n        // Get this info from earlier code, don't extract it again\n        Eigen::Matrix3d R = pose.block<3,3>(0,0);\n        Eigen::Quaternion<double> q(R);\n\n        out_pose.position.x = pose(0,3);\n        out_pose.position.y = pose(1,3);\n        out_pose.position.z = pose(2,3);\n        out_pose.orientation.x = q.x();\n        out_pose.orientation.y = q.y();\n        out_pose.orientation.z = q.z();\n        out_pose.orientation.w = q.w();\n    }\n\n    int localize(TagDetection& detection, geometry_msgs::Pose& out_pose){\n        // sample(segment) a tag corresponding to this detection.\n        pcl::PointCloud<pcl::PointXYZRGB>::Ptr tag_sample_cloud;\n        int result = sample_cloud(detection, tag_sample_cloud);\n        if(result != 0){\n            return result;\n        }\n        pcl::PointCloud<pcl::PointXYZRGB>::Ptr corners_3D;\n        result = extract_corners(detection, corners_3D);\n        if(result != 0){\n            return result;\n        }\n\n        //fit plane on sampled cloud\n        pcl::PointIndices::Ptr inlier_idxs=boost::make_shared<pcl::PointIndices>();\n        pcl::ModelCoefficients coeffs;\n        pcl::PointCloud<pcl::PointXYZRGB>::Ptr inliers(new pcl::PointCloud<pcl::PointXYZRGB>());\n\n        pcl::SACSegmentation<pcl::PointXYZRGB> seg;\n        seg.setOptimizeCoefficients(true);\n        seg.setModelType(pcl::SACMODEL_PLANE);\n        seg.setMethodType(pcl::SAC_RANSAC);\n        seg.setDistanceThreshold(0.005);\n\n        seg.setInputCloud(tag_sample_cloud);\n        seg.segment(*inlier_idxs, coeffs);\n\n        pcl::ExtractIndices<pcl::PointXYZRGB> extracter;\n        extracter.setInputCloud(tag_sample_cloud);\n        extracter.setIndices(inlier_idxs);\n        extracter.setNegative(false);\n        extracter.filter(*inliers);\n\n        //set center as the mean of inliers\n        out_pose.position = centroid(*inliers);\n\n        //get orientation\n        Eigen::Matrix3d R;\n        extractFrame(coeffs, *corners_3D, R);\n        Eigen::Quaternion<double> q(R);\n        q.normalize();\n\n        out_pose.orientation.x = q.x();\n        out_pose.orientation.y = q.y();\n        out_pose.orientation.z = q.z();\n        out_pose.orientation.w = q.w();\n        return 0;\n    }\n\nprivate:\n    void gen_tag_samples(){\n        m_tag_space_samples = at::Mat::zeros(3, int(m_num_samples*m_num_samples));\n        float step = 2.0f/ float(m_num_samples - 1);\n        for(size_t y=0; y < m_num_samples; y++){\n            for(size_t x=0; x < m_num_samples; x++){\n                size_t idx = y*m_num_samples + x;\n                m_tag_space_samples[0][idx] = at::real(x) * step - 1.0f;\n                m_tag_space_samples[1][idx] = at::real(y) * step - 1.0f;\n                m_tag_space_samples[2][idx] = 1.0f;\n            }\n        }\n    }\n\n    int sample_cloud(TagDetection& detection, pcl::PointCloud<pcl::PointXYZRGB>::Ptr& tag_sample_cloud){\n        pcl::PointCloud<pcl::PointXYZRGB>::Ptr out_cloud(new pcl::PointCloud<pcl::PointXYZRGB>());\n\n        // calcuate points in image coordinate.\n        at::Mat img_idx_mat = detection.homography * m_tag_space_samples;\n        size_t x = 0; // col id in image(0,0) at center of image(according to pcl_conversions.h)\n        size_t y = 0; // row id in image\n        size_t count = 0;\n        for(size_t i = 0; i < m_num_samples * m_num_samples; i++){\n            x = size_t(img_idx_mat[0][i]/img_idx_mat[2][i] + detection.hxy.x);\n            y = size_t(img_idx_mat[1][i]/img_idx_mat[2][i] + detection.hxy.y);\n\n            const pcl::PointXYZRGB& pt = (*m_cloud)(x, y);\n\n            //check if pt is NaN\n            if (pt_is_nan(pt)){\n                //ROS_INFO(\"    Skipping (%.4f, %.4f, %.4f)\", pt.x, pt.y, pt.z);\n            }else{\n                count++;\n                out_cloud->points.push_back(pt);\n            }\n        }\n        if(count < m_num_samples * m_num_samples / 2){\n            //more than half is Nan\n            return -1;\n        }\n\n        tag_sample_cloud = out_cloud;\n        return 0;\n    }\n\n    int extract_corners(TagDetection& detection, pcl::PointCloud<pcl::PointXYZRGB>::Ptr& corners_3D){\n        pcl::PointCloud<pcl::PointXYZRGB>::Ptr out_cloud(new pcl::PointCloud<pcl::PointXYZRGB>());\n        pcl::PointXYZRGB temp_pt;\n        int result;\n        size_t window_size = 5;\n        for(size_t i = 0; i < 4; i++){\n            result = find_non_nan(size_t(detection.p[i].x), size_t(detection.p[i].y), window_size, temp_pt);\n            if(result != 0){\n                return result;\n            }\n\n            out_cloud->points.push_back(temp_pt);\n        }\n\n        corners_3D = out_cloud;\n        return 0;\n    }\n\n    bool pt_is_nan(pcl::PointXYZRGB pt){\n        return std::isnan(pt.x) || std::isnan(pt.y) || std::isnan(pt.z);\n    }\n\n    int find_non_nan(size_t x, size_t y, size_t window_size, pcl::PointXYZRGB& pt){\n        pt = (*m_cloud)(x, y);\n        if(! pt_is_nan(pt)){\n            //original point is not Nan\n            return 0;\n        }\n\n        //find average in windows_size by window_size reigon\n\n        size_t half_dim = window_size/2;\n        if(x < half_dim || x + half_dim + 1 >= (m_cloud->width) || y < half_dim || y + half_dim + 1 >= (m_cloud->height)){\n            //window is invalid\n            return -1;\n        }\n\n        pcl::PointXYZRGB temp_pt;\n        float avg_x = 0.0f;\n        float avg_y = 0.0f;\n        float avg_z = 0.0f;\n        size_t count = 0;\n        for(size_t temp_y = y - half_dim; temp_y < y + half_dim; temp_y++){\n            for(size_t temp_x = x - half_dim; temp_x < x + half_dim; temp_x++){\n                temp_pt = (*m_cloud)(temp_x, temp_y);\n                if(! pt_is_nan(temp_pt)){\n                    avg_x += temp_pt.x;\n                    avg_y += temp_pt.y;\n                    avg_z += temp_pt.z;\n                    count ++;\n                }\n            }\n        }\n\n        if(count == 0){\n            //all neighbors are Nan\n            return -1;\n        }\n\n        float num = (float) count;\n        pt.x = avg_x / num;\n        pt.y = avg_y / num;\n        pt.z = avg_z / num;\n\n        return 0;\n    }\n\n\n\n    geometry_msgs::Point centroid (const pcl::PointCloud<pcl::PointXYZRGB>& points)\n    {\n        // find the mean of all point coordinate.\n        geometry_msgs::Point sum;\n        sum.x = 0;\n        sum.y = 0;\n        sum.z = 0;\n        //for (const Point& p : points)\n        for(size_t i=0; i<points.size(); i++)\n        {\n            sum.x += points[i].x;\n            sum.y += points[i].y;\n            sum.z += points[i].z;\n        }\n\n        geometry_msgs::Point center;\n        const size_t n = points.size();\n        center.x = sum.x/double(n);\n        center.y = sum.y/double(n);\n        center.z = sum.z/double(n);\n        return center;\n    }\n\n    Eigen::Vector3d project(const pcl::PointXYZRGB& p, const double a, const double b,\n                         const double c, const double d)\n    {\n        const double t = a*p.x + b*p.y + c*p.z + d;\n        return Eigen::Vector3d(p.x-t*a, p.y-t*b, p.z-t*c);\n    }\n\n    int getCoeffs (const pcl::ModelCoefficients& coeffs, double& a, double& b,\n                   double& c, double& d)\n    {\n        if(coeffs.values.size() != 4)\n            return -1;\n        const double s = coeffs.values[0]*coeffs.values[0] +\n                         coeffs.values[1]*coeffs.values[1] + coeffs.values[2]*coeffs.values[2];\n        if(fabs(s) < 1e-6)\n            return -1;\n        a = coeffs.values[0]/s;\n        b = coeffs.values[1]/s;\n        c = coeffs.values[2]/s;\n        d = coeffs.values[3]/s;\n        return 0;\n    }\n\n    int extractFrame (const pcl::ModelCoefficients& coeffs,\n                      pcl::PointCloud<pcl::PointXYZRGB>& corners,\n                      Eigen::Matrix3d &retmat){\n        double a=0, b=0, c=0, d=0;\n        if(getCoeffs(coeffs, a, b, c, d) < 0){\n            return -1;\n        }\n\n        const Eigen::Vector3d q1 = project(corners.points[0], a, b, c, d);\n        const Eigen::Vector3d q2 = project(corners.points[1], a, b, c, d);\n        //const Eigen::Vector3d q3 = project(corners.points[0], a, b, c, d);\n        //const Eigen::Vector3d q4 = project(corners.points[3], a, b, c, d);\n\n        const Eigen::Vector3d v = (q2-q1).normalized();\n        const Eigen::Vector3d n(a, b, c);\n        const Eigen::Vector3d w = -v.cross(n);\n        Eigen::Matrix3d m;\n        m << v[0], v[1], v[2],\n             w[0], w[1], w[2],\n             n[0], n[1], n[2];\n\n        retmat = m.inverse();\n\n        return 0;\n    }\n};\n\n\n\n\n", "meta": {"hexsha": "17ca2d8b4451a8ae9044ce786a4462821ff08987", "size": 12481, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/apriltag_kinect2/kinect_utilities.hpp", "max_stars_repo_name": "UM-ARM-Lab/apriltag_kinect2", "max_stars_repo_head_hexsha": "ed454dd00bbdf813204c23be499d350b7f573fb9", "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/apriltag_kinect2/kinect_utilities.hpp", "max_issues_repo_name": "UM-ARM-Lab/apriltag_kinect2", "max_issues_repo_head_hexsha": "ed454dd00bbdf813204c23be499d350b7f573fb9", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2018-03-22T18:09:05.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-23T21:00:32.000Z", "max_forks_repo_path": "include/apriltag_kinect2/kinect_utilities.hpp", "max_forks_repo_name": "UM-ARM-Lab/apriltag_kinect2", "max_forks_repo_head_hexsha": "ed454dd00bbdf813204c23be499d350b7f573fb9", "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.5510752688, "max_line_length": 125, "alphanum_fraction": 0.5764762439, "num_tokens": 3384, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239836484143, "lm_q2_score": 0.6370308013713525, "lm_q1q2_score": 0.45574711362383474}}
{"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\n#include <Eigen/Dense>\n\n//#include <boost/random/uniform_int_distribution.hpp>\n//#include <boost/random/uniform_int.hpp>\n#include <boost/random/uniform_01.hpp>\n\n#include <dpMM/distribution.hpp>\n#include <dpMM/sampler.hpp>\n\nusing namespace Eigen;\nusing std::cout;\nusing std::endl;\n\n#ifdef WIN32\n\tusing boost::math::lgamma; \n#endif\n\ntemplate<typename T>\nclass Mult : public Distribution<T>\n{\npublic:\n  uint32_t K_;\n  Matrix<T,Dynamic,1> pdf_;\n\n  /* constructor from pdf */\n  Mult(const Matrix<T,Dynamic,1>& pdf, boost::mt19937 *pRndGen);\n  /* constructor from indicators - estimates from counts */\n  Mult(const VectorXu& z, boost::mt19937 *pRndGen);\n  /* copy constructor */\n  Mult(const Mult& other);\n  virtual ~Mult();\n\n  uint32_t sample();\n  void sample(VectorXu& z);\n\n  T logPdf(const Matrix<T,Dynamic,1>& x) const;\n  T logPdfOfSS(const Matrix<T,Dynamic,1>& x) const {return logPdf(x);};\n\n  const Matrix<T,Dynamic,1>& pdf() const {return pdf_;};\n  void pdf(const Matrix<T,Dynamic,1>& pdf){\n    pdf_ = pdf;\n  };\n\n  void print() const;\n\nprivate:\n  boost::uniform_01<T> unif_;\n};\n\ntypedef Mult<float> Multf;\ntypedef Mult<double> Multd;\n\n", "meta": {"hexsha": "426f882d41811dd68736541d6d91c12cfeafd9d1", "size": 1316, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/dpMM/mult.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/mult.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/mult.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": 22.6896551724, "max_line_length": 80, "alphanum_fraction": 0.6831306991, "num_tokens": 354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.6370307875894139, "lm_q1q2_score": 0.4557471114943115}}
{"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/math/special_functions/round.hpp>\r\n#include <boost/random/mersenne_twister.hpp>\r\n#include <boost/random/uniform_int.hpp>\r\n#include <boost/random/uniform_real_distribution.hpp>\r\n#include <boost/random/variate_generator.hpp>\r\n\r\nnamespace amichel {\r\nnamespace de {\r\n\r\ninline double genrand(double min = 0, double max = 1) {\r\n  static boost::random::mt19937 gen;\r\n  boost::random::uniform_real_distribution<> dist(min, max);\r\n  boost::variate_generator<boost::random::mt19937&,\r\n                           boost::random::uniform_real_distribution<double> >\r\n      value(gen, dist);\r\n\r\n  return value();\r\n}\r\n\r\ninline int genintrand(double min, double max, bool upperexclusive = false) {\r\n  assert(min < max);\r\n  int ret = 0;\r\n  do\r\n    ret = boost::math::round(genrand(min, max));\r\n  while (ret < min || ret > max || upperexclusive && ret == max);\r\n  return ret;\r\n}\r\n}  // namespace de\r\n}  // namespace amichel\r\n", "meta": {"hexsha": "70b6c206319197323d7809dfeff43f6e15a21a56", "size": 1204, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "differentialevolution/random_generator.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/random_generator.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/random_generator.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": 28.6666666667, "max_line_length": 78, "alphanum_fraction": 0.6744186047, "num_tokens": 287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239836484144, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.4557470988339406}}
{"text": "/*    Copyright (c) 2010-2019, Delft University of Technology\n *    All rigths reserved\n *\n *    This file is part of the Tudat. Redistribution and use in source and\n *    binary forms, with or without modification, are permitted exclusively\n *    under the terms of the Modified BSD license. You should have received\n *    a copy of the license with this file. If not, please or visit:\n *    http://tudat.tudelft.nl/LICENSE.\n *\n */\n\n#define BOOST_TEST_MAIN\n\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/unit_test.hpp>\n\n#include <Eigen/Core>\n\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/orbitalElementConversions.h\"\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/unitConversions.h\"\n#include \"Tudat/Basics/testMacros.h\"\n#include \"Tudat/Mathematics/BasicMathematics/mathematicalConstants.h\"\n#include \"Tudat/Mathematics/BasicMathematics/basicMathematicsFunctions.h\"\n\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/unifiedStateModelQuaternionElementConversions.h\"\n#include \"Tudat/Basics/basicTypedefs.h\"\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/stateVectorIndices.h\"\n\nnamespace tudat\n{\nnamespace unit_tests\n{\n\n//! Test the functionality of the time conversion functions.\nBOOST_AUTO_TEST_SUITE( test_USM7_Element_Conversions )\n\n//! Unit test for conversion Keplerian orbital elements to unified state model elements.\nBOOST_AUTO_TEST_CASE( testconvertKeplerianToUnifiedStateModelQuaternionsElements )\n{\n    using namespace orbital_element_conversions;\n    using namespace unit_conversions;\n    using mathematical_constants::PI;\n\n    // Setting fraction tolerance for correctness evaluation\n    double tolerance = 1.0E-14;\n\n    // Declare gravitational parameter of central body\n    const double centralBodyGravitationalParameter = 1.32712440018e20; // [m^3/s^2]\n\n    // Initializing default Keplerian orbit\n    Eigen::Vector6d keplerianElements = Eigen::Vector6d::Zero( 6 );\n    keplerianElements( semiMajorAxisIndex ) = 1.5e11;\n    keplerianElements( eccentricityIndex ) = 0.1;\n    keplerianElements( inclinationIndex ) = convertDegreesToRadians( 50.0 );\n    keplerianElements( argumentOfPeriapsisIndex ) = convertDegreesToRadians( 350.0 );\n    keplerianElements( longitudeOfAscendingNodeIndex ) = convertDegreesToRadians( 15.0 );\n    keplerianElements( trueAnomalyIndex ) = convertDegreesToRadians( 10.0 );\n\n    // Unified state model element vector declaration\n    Eigen::VectorXd expectedUnifiedStateModelElements\n            = Eigen::VectorXd::Zero( 7 );\n    Eigen::VectorXd computedUnifiedStateModelElements\n            = Eigen::VectorXd::Zero( 7 );\n\n    // Case 1: Elliptical prograde orbit (default case).\n    {\n        // Default case, so no modification necessary.\n\n        // Expected unified state model elements [m/s,m/s,m/s,-,-,-,-].\n        // (Results obtained using MATLAB code).\n        expectedUnifiedStateModelElements( CHodographUSM7Index ) = 29894.5892222602;\n        expectedUnifiedStateModelElements( Rf1HodographUSM7Index ) = -260.548512780222;\n        expectedUnifiedStateModelElements( Rf2HodographUSM7Index ) = 2978.08312848463;\n        expectedUnifiedStateModelElements( epsilon1USM7Index ) = -0.419002703925548;\n        expectedUnifiedStateModelElements( epsilon2USM7Index ) = -0.0551627524676706;\n        expectedUnifiedStateModelElements( epsilon3USM7Index ) = -0.118296904421275;\n        expectedUnifiedStateModelElements( etaUSM7Index ) = -0.898554198280556;\n\n        // Compute unified state model elements.\n        computedUnifiedStateModelElements =\n                convertKeplerianToUnifiedStateModelQuaternionsElements( keplerianElements,\n                                                               centralBodyGravitationalParameter );\n\n        // Check if computed unified state model elements match the expected values.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedUnifiedStateModelElements,\n                                           computedUnifiedStateModelElements, tolerance );\n\n    }\n\n\n\n\n    // Case 2: Hyperbolic retrograde orbit.\n    {\n        // Modify Keplerian elements [m,-,rad,rad,rad,rad], i.e. overwrite them.\n        keplerianElements( semiMajorAxisIndex ) = -1.5e11;\n        keplerianElements( eccentricityIndex ) = 2.0;\n        keplerianElements( inclinationIndex ) = convertDegreesToRadians( 170.0 );\n        keplerianElements( trueAnomalyIndex ) = convertDegreesToRadians( 10.0 );\n\n        // Set expected unified state model elements [m/s,m/s,m/s,-,-,-,-].\n        // (Results obtained using MATLAB code).\n        expectedUnifiedStateModelElements( CHodographUSM7Index ) = 17173.1340579794;\n        expectedUnifiedStateModelElements( Rf1HodographUSM7Index ) = -2993.47450825659;\n        expectedUnifiedStateModelElements( Rf2HodographUSM7Index ) = 34215.5701963558;\n        expectedUnifiedStateModelElements( epsilon1USM7Index ) = -0.987672114350896;\n        expectedUnifiedStateModelElements( epsilon2USM7Index ) = -0.130029500651719;\n        expectedUnifiedStateModelElements( epsilon3USM7Index ) = -0.0113761072309622;\n        expectedUnifiedStateModelElements( etaUSM7Index )= -0.0864101132863834;\n\n        // Compute unified state model elements.\n        computedUnifiedStateModelElements =\n                convertKeplerianToUnifiedStateModelQuaternionsElements( keplerianElements,\n                                                               centralBodyGravitationalParameter );\n\n        // Check if computed unified state model elements match the expected values.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedUnifiedStateModelElements,\n                                           computedUnifiedStateModelElements, tolerance );\n\n    }\n\n\n    // Case 3: Parabolic retrograde orbit.\n    {\n        // Set Keplerian elements [m,-,rad,rad,rad,rad].\n        keplerianElements( semiLatusRectumIndex ) = 1.5e11;\n        keplerianElements( eccentricityIndex ) = 1.0;\n        keplerianElements( inclinationIndex ) = convertDegreesToRadians( 170.0 );\n        keplerianElements( trueAnomalyIndex ) = convertDegreesToRadians( 170.0 );\n\n        // Set expected unified state model elements [m/s,m/s,m/s,-,-,-,-].\n        // (Results obtained using MATLAB code).\n        expectedUnifiedStateModelElements( CHodographUSM7Index ) = 29744.7407136119;\n        expectedUnifiedStateModelElements( Rf1HodographUSM7Index ) = -2592.42496973134;\n        expectedUnifiedStateModelElements( Rf2HodographUSM7Index ) = 29631.5529950138;\n        expectedUnifiedStateModelElements( epsilon1USM7Index ) = -0.299561523151596;\n        expectedUnifiedStateModelElements( epsilon2USM7Index ) = 0.95008776981561;\n        expectedUnifiedStateModelElements( epsilon3USM7Index ) = -0.0870727897926938;\n        expectedUnifiedStateModelElements( etaUSM7Index ) = -0.00380168010402369;\n\n        // Compute unified state model elements.\n        computedUnifiedStateModelElements =\n                convertKeplerianToUnifiedStateModelQuaternionsElements( keplerianElements,\n                                                               centralBodyGravitationalParameter );\n\n        // Check if computed unified state model elements match the expected values.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedUnifiedStateModelElements,\n                                           computedUnifiedStateModelElements, tolerance );\n    }\n\n    // Case 4: Circular prograde orbit with non-zero argument of pericenter, test for error.\n    {\n        // Set Keplerian elements [m,-,rad,rad,rad,rad].\n        keplerianElements( eccentricityIndex ) = 0.0;\n            // Eccentricity is zero, while argument of pericenter is non-zero -> should give error\n        keplerianElements( inclinationIndex ) = convertDegreesToRadians( 50.0 );\n\n        // Declare variable indicating whether an exception has been thrown.\n        bool isExceptionFound = false;\n\n        // Try computing the unified state model elements and catch the expected runtime error.\n        try\n        {\n            computedUnifiedStateModelElements =\n                    convertKeplerianToUnifiedStateModelQuaternionsElements( keplerianElements,\n                                                                 centralBodyGravitationalParameter );\n        }\n        catch( std::runtime_error )\n        {\n            isExceptionFound = true;\n        }\n\n        // Check if runtime error has occured\n        BOOST_CHECK( isExceptionFound );\n    }\n\n    // Case 5: 0 inclination orbit, test for error because longitude of ascending node is non-zero\n    {\n        // Set Keplerian elements [m,-,rad,rad,rad,rad].\n        keplerianElements( eccentricityIndex ) = 0.1;\n        keplerianElements( inclinationIndex ) = 0.0;\n\n        // Declare variable indicating whether an exception has been thrown.\n        bool isExceptionFound = false;\n\n        // Try computing the unified state model elements and catch the expected runtime error.\n        try\n        {\n            computedUnifiedStateModelElements =\n                    convertKeplerianToUnifiedStateModelQuaternionsElements( keplerianElements,\n                                                                 centralBodyGravitationalParameter );\n        }\n        catch( std::runtime_error )\n        {\n            isExceptionFound = true;\n        }\n\n        // Check if runtime error has occured\n        BOOST_CHECK( isExceptionFound );\n    }\n\n    // Case 6: 180 inclination orbit.\n    {\n        // Set Keplerian elements [m,-,rad,rad,rad,rad].\n        keplerianElements( inclinationIndex ) = PI; // = 180 deg\n\n        // Set expected unified state model elements [m/s,m/s,m/s,-,-,-,-]. (Results were calculated by\n        // hand).\n        expectedUnifiedStateModelElements( CHodographUSM7Index ) = 29894.5892222602;\n        expectedUnifiedStateModelElements( Rf1HodographUSM7Index ) = -260.548512780222;\n        expectedUnifiedStateModelElements( Rf2HodographUSM7Index ) = 2978.08312848463;\n        expectedUnifiedStateModelElements( epsilon1USM7Index ) = -0.300705799504273;\n        expectedUnifiedStateModelElements( epsilon2USM7Index ) = 0.953716950748227;\n        expectedUnifiedStateModelElements( epsilon3USM7Index ) = -6.11740603377039e-17;\n        expectedUnifiedStateModelElements( etaUSM7Index ) = -2.67091715588637e-18;\n\n        // Compute unified state model elements.\n        computedUnifiedStateModelElements =\n                convertKeplerianToUnifiedStateModelQuaternionsElements( keplerianElements,\n                                                               centralBodyGravitationalParameter );\n\n        // Because two elements are near-zero, a close fraction/percentage check will fail.\n        // Therefore, 1.0 is added to the elements to avoid this\n        expectedUnifiedStateModelElements( epsilon3USM7Index ) =\n                expectedUnifiedStateModelElements( epsilon3USM7Index ) + 1.0;\n        expectedUnifiedStateModelElements( etaUSM7Index ) =\n                expectedUnifiedStateModelElements( etaUSM7Index ) + 1.0;\n        computedUnifiedStateModelElements( epsilon3USM7Index ) =\n                computedUnifiedStateModelElements( epsilon3USM7Index ) + 1.0;\n        computedUnifiedStateModelElements( etaUSM7Index ) =\n                computedUnifiedStateModelElements( etaUSM7Index ) + 1.0;\n\n        // Check if computed elements match the expected values.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedUnifiedStateModelElements,\n                                           computedUnifiedStateModelElements, tolerance );\n    }\n\n    // Case 7: 0 eccentricity and inclination orbit.\n    {\n        // Set Keplerian elements [m,-,rad,rad,rad,rad].\n        keplerianElements( eccentricityIndex ) = 0.0;\n        keplerianElements( inclinationIndex ) = 0.0;\n        keplerianElements( longitudeOfAscendingNodeIndex ) = 0.0; // Default value because of zero inclination\n        keplerianElements( argumentOfPeriapsisIndex ) = 0.0; // Default value because of zero eccentricity\n\n        // Expected unified state model elements [m/s,m/s,m/s,-,-,-,-].\n        // (Results obtained using code archive B. Romgens (2011)).\n        expectedUnifiedStateModelElements( CHodographUSM7Index ) = 29744.7407136119;\n        expectedUnifiedStateModelElements( Rf1HodographUSM7Index ) = 0;\n        expectedUnifiedStateModelElements( Rf2HodographUSM7Index ) = 0;\n        expectedUnifiedStateModelElements( epsilon1USM7Index ) = 0;\n        expectedUnifiedStateModelElements( epsilon2USM7Index ) = 0;\n        expectedUnifiedStateModelElements( epsilon3USM7Index ) = 0.996194698091746;\n        expectedUnifiedStateModelElements( etaUSM7Index ) = 0.0871557427476581;\n\n        // Compute unified state model elements.\n        computedUnifiedStateModelElements =\n                convertKeplerianToUnifiedStateModelQuaternionsElements( keplerianElements,\n                                                               centralBodyGravitationalParameter );\n\n        // Check if computed elements match the expected values.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedUnifiedStateModelElements,\n                                           computedUnifiedStateModelElements, tolerance );\n    }\n\n    // Case 8: 200 degree inclination orbit, test for error.\n    {\n        keplerianElements( inclinationIndex ) = convertDegreesToRadians( 200.0 );\n        bool isExceptionFound = false;\n\n        // Try to convert Kepler to unified state model Elements\n        try\n        {\n            computedUnifiedStateModelElements = convertKeplerianToUnifiedStateModelQuaternionsElements\n                    ( keplerianElements, centralBodyGravitationalParameter );\n        }\n        // Catch the expected runtime error, and set the boolean flag to true.\n        catch ( std::runtime_error )\n        {\n            isExceptionFound = true;\n        }\n\n        // Check value of flag.\n        BOOST_CHECK( isExceptionFound );\n    }\n}\n\n\n//! Unit test for the conversion of unified state model elements to Keplerian elements\nBOOST_AUTO_TEST_CASE( testconvertUnifiedStateModelQuaternionsToKeplerianElements )\n{\n    /* Used procedure:\n      Because the Kepler to unified state model elements are verified, a subsequent conversion back\n      to Keplerian elements should yield the same outcome as the input Keplerian state. This\n      principle is used for verification.\n     */\n\n    using namespace orbital_element_conversions;\n    using namespace unit_conversions;\n    using mathematical_constants::PI;\n\n    // Setting fraction tolerance for correctness evaluation\n    double tolerance = 1.0E-14;\n\n    // Declare gravitational parameter of central body\n    const double centralBodyGravitationalParameter = 1.32712440018e20; // [m^3/s^2]\n\n    // Initializing default Keplerian orbit\n    Eigen::Vector6d expectedKeplerianElements = Eigen::VectorXd::Zero( 6 );\n    expectedKeplerianElements( semiMajorAxisIndex ) = 1.5e11;\n    expectedKeplerianElements( eccentricityIndex ) = 0.1;\n    expectedKeplerianElements( inclinationIndex ) = convertDegreesToRadians( 50.0 );\n    expectedKeplerianElements( argumentOfPeriapsisIndex ) = convertDegreesToRadians( 350.0 );\n    expectedKeplerianElements( longitudeOfAscendingNodeIndex ) = convertDegreesToRadians( 15.0 );\n    expectedKeplerianElements( trueAnomalyIndex ) = convertDegreesToRadians( 170.0 );\n\n    // Declaring computed output vector.\n    Eigen::Vector6d computedKeplerianElements = Eigen::VectorXd::Zero( 6 );\n\n    // Case 1: Elliptical prograde orbit (default case).\n    {\n        // Default case, so no modification necessary.\n\n        // Convert to unified state model elements and back.\n        computedKeplerianElements = convertUnifiedStateModelQuaternionsToKeplerianElements(\n                    convertKeplerianToUnifiedStateModelQuaternionsElements( expectedKeplerianElements,\n                                                                            centralBodyGravitationalParameter ),\n                    centralBodyGravitationalParameter );\n\n        // Check if computed Keplerian elements match the expected values.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedKeplerianElements,\n                                           computedKeplerianElements, tolerance );\n    }\n\n    // Case 2: Hyperbolic retrograde orbit.\n    {\n        // Modify Keplerian elements [m,-,rad,rad,rad,rad].\n        expectedKeplerianElements( semiMajorAxisIndex ) = -1.5e11;\n        expectedKeplerianElements( eccentricityIndex ) = 2.0;\n        expectedKeplerianElements( inclinationIndex ) = convertDegreesToRadians( 160.0 );\n        expectedKeplerianElements( trueAnomalyIndex ) = convertDegreesToRadians( 10.0 ); // 170 is above limit\n\n        // Convert to unified state model elements and back.\n        computedKeplerianElements = convertUnifiedStateModelQuaternionsToKeplerianElements(\n                    convertKeplerianToUnifiedStateModelQuaternionsElements( expectedKeplerianElements,\n                                                                            centralBodyGravitationalParameter ),\n                    centralBodyGravitationalParameter );\n\n        // Check if computed Keplerian elements match the expected values.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedKeplerianElements,\n                                           computedKeplerianElements, tolerance );\n    }\n\n    // Case 3: Parabolic retrograde orbit.\n    {\n        // Set Keplerian elements [m,-,rad,rad,rad,rad].\n        expectedKeplerianElements( semiLatusRectumIndex ) = 3.5e11;\n        expectedKeplerianElements( eccentricityIndex ) = 1.0;\n        expectedKeplerianElements( inclinationIndex ) = convertDegreesToRadians( 90.0 );\n\n        // Convert to unified state model elements and back.\n        computedKeplerianElements = convertUnifiedStateModelQuaternionsToKeplerianElements(\n                    convertKeplerianToUnifiedStateModelQuaternionsElements( expectedKeplerianElements,\n                                                                   centralBodyGravitationalParameter ),\n                    centralBodyGravitationalParameter );\n\n        // Check if computed Keplerian elements match the expected values.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedKeplerianElements,\n                                           computedKeplerianElements, tolerance );\n       }\n\n    // Case 4: Circular prograde orbit.\n    {\n        // Set Keplerian elements [m,-,rad,rad,rad,rad].\n        expectedKeplerianElements( semiMajorAxisIndex ) = 3.5e11;\n        expectedKeplerianElements( eccentricityIndex ) = 0.0;\n        expectedKeplerianElements( inclinationIndex ) = convertDegreesToRadians( 70.0 );\n        expectedKeplerianElements( argumentOfPeriapsisIndex ) = 0.0; // For e = 0, undefined.\n\n        // Convert to unified state model elements and back.\n        computedKeplerianElements = convertUnifiedStateModelQuaternionsToKeplerianElements(\n                    convertKeplerianToUnifiedStateModelQuaternionsElements( expectedKeplerianElements,\n                                                                   centralBodyGravitationalParameter ),\n                    centralBodyGravitationalParameter );\n\n        // Check if computed Keplerian elements match the expected values.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedKeplerianElements,\n                                           computedKeplerianElements, tolerance );\n    }\n\n    // Case 5: 0 inclination orbit,\n    {\n        // Set Keplerian elements [m,-,rad,rad,rad,rad].\n        expectedKeplerianElements( eccentricityIndex ) = 0.3;\n        expectedKeplerianElements( inclinationIndex ) = 0.0;\n        expectedKeplerianElements( longitudeOfAscendingNodeIndex ) = 0.0; // Set to zero as for\n        // non-inclined orbit planes, this parameter is undefined\n\n        // Convert to unified state model elements and back.\n        computedKeplerianElements = convertUnifiedStateModelQuaternionsToKeplerianElements(\n                    convertKeplerianToUnifiedStateModelQuaternionsElements( expectedKeplerianElements,\n                                                                   centralBodyGravitationalParameter ),\n                    centralBodyGravitationalParameter );\n\n        // Check if computed Keplerian elements match the expected values.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedKeplerianElements,\n                                           computedKeplerianElements, tolerance );\n    }\n\n    // Case 6: 180 inclination orbit, test for error.\n    {\n        // Set Keplerian elements [m,-,rad,rad,rad,rad].\n        expectedKeplerianElements( semiMajorAxisIndex ) = 1.5e15;\n        expectedKeplerianElements( inclinationIndex ) = PI;\n        expectedKeplerianElements( trueAnomalyIndex ) = convertDegreesToRadians( 240.0 );\n\n        // Declare variable indicating whether an exception has been thrown.\n        bool isExceptionFound = false;\n\n        // Try convert to unified state model elements and back and catch the expected runtime error.\n        try\n        {\n            computedKeplerianElements = convertUnifiedStateModelQuaternionsToKeplerianElements(\n                    convertKeplerianToUnifiedStateModelQuaternionsElements( expectedKeplerianElements,\n                                                                 centralBodyGravitationalParameter ),\n                        centralBodyGravitationalParameter );\n        }\n        catch( std::runtime_error )\n        {\n            isExceptionFound = true;\n        }\n\n        // Check if runtime error has occured\n        BOOST_CHECK( isExceptionFound );\n    }\n\n    // Case 7: 0 eccentricity and inclination orbit.\n    {\n        // Set Keplerian elements [m,-,rad,rad,rad,rad].\n        expectedKeplerianElements( eccentricityIndex ) = 0.0;\n            // argument of pericenter was set to 0 in case 4, so no error.\n        expectedKeplerianElements( inclinationIndex ) = 0.0;\n            // longitude of ascending node was set to 0 in case 5, so no error.\n\n        // Convert to unified state model elements and back\n        computedKeplerianElements = convertUnifiedStateModelQuaternionsToKeplerianElements(\n                    convertKeplerianToUnifiedStateModelQuaternionsElements( expectedKeplerianElements,\n                                                                   centralBodyGravitationalParameter ),\n                    centralBodyGravitationalParameter );\n\n        // Check if computed Keplerian elements match the expected values.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedKeplerianElements,\n                                           computedKeplerianElements, tolerance );\n    }\n\n    // Case 8: true anomaly exceeding 180 degrees.\n    {\n        // Set Keplerian elements [m,-,rad,rad,rad,rad].\n        expectedKeplerianElements( semiMajorAxisIndex ) = 1.5e11;\n        expectedKeplerianElements( eccentricityIndex ) = 0.1;\n        expectedKeplerianElements( inclinationIndex ) = convertDegreesToRadians( 50.0 );\n        expectedKeplerianElements( argumentOfPeriapsisIndex ) = convertDegreesToRadians( 350.0 );\n        expectedKeplerianElements( longitudeOfAscendingNodeIndex ) = convertDegreesToRadians( 15.0 );\n        expectedKeplerianElements( trueAnomalyIndex ) = convertDegreesToRadians( 240.0 );\n\n        // Convert to unified state model elements and back\n        computedKeplerianElements = convertUnifiedStateModelQuaternionsToKeplerianElements(\n                    convertKeplerianToUnifiedStateModelQuaternionsElements( expectedKeplerianElements,\n                                                                   centralBodyGravitationalParameter ),\n                    centralBodyGravitationalParameter );\n\n        // Check if computed Keplerian elements match the expected values.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedKeplerianElements,\n                                           computedKeplerianElements, tolerance );\n    }\n}\nBOOST_AUTO_TEST_SUITE_END( )\n\n} // end namespace unit_tests\n} // end namespace tudat\n", "meta": {"hexsha": "4f50446aafae015350af4713f6c7125a9b7c9e0f", "size": 23854, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/BasicAstrodynamics/UnitTests/unitTestUnifiedStateModelQuaternionElementConversions.cpp", "max_stars_repo_name": "sebranchett/tudat", "max_stars_repo_head_hexsha": "24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tudat/Astrodynamics/BasicAstrodynamics/UnitTests/unitTestUnifiedStateModelQuaternionElementConversions.cpp", "max_issues_repo_name": "sebranchett/tudat", "max_issues_repo_head_hexsha": "24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tudat/Astrodynamics/BasicAstrodynamics/UnitTests/unitTestUnifiedStateModelQuaternionElementConversions.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": 49.5925155925, "max_line_length": 112, "alphanum_fraction": 0.6776641234, "num_tokens": 5319, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680940822761, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.45565445175744707}}
{"text": "#include \"Player.h\"\n#include <Eigen/Dense>\n#include <Eigen/Core>\n#include <iostream>\n#include <random>\n#include <NNWrapper.h>\n#include <math.h>       /* isnan, sqrt */\n\t\nint pickRandomElement(std::vector<int> v){\n\tstd::random_device random_device;   \n\tstd::mt19937 engine{random_device()};   \n\tstd::uniform_int_distribution<int> dist(0, v.size() - 1);\n\n\treturn  v[dist(engine)]; \n}\n\nint pickStochasticElement(ArrayXf p){\n\tstd::random_device random_device;   \n\tstd::mt19937 engine{random_device()}; \n\n    std::discrete_distribution<> dist(p.data(),p.data() +  p.size());\n\n\treturn  dist(engine); \n}\n\n\nint HumanPlayer::getAction(std::shared_ptr<Game> game){\n\tint action;\n\tArrayXf poss = game->getPossibleActions();\n\tstd::cout << \"Enter an action\";  \n\tstd::cin >> action;\n\taction--;\n\n\twhile (poss[action] != 1){\n\t\tstd::cout << \"Invalid, Enter an action\";  \n\t\tstd::cin >> action; \n\t\taction--;\n\t}  \n\n\treturn action;\n}\n\nstd::string HumanPlayer::name(){\n\treturn \"Human Player\";\n}\n\n\nint PerfectPlayer::getAction(std::shared_ptr<Game> game){\n\tstd::vector<float> scores = this->getBestScores(game);\n\tfloat max_score = - std::numeric_limits<float>::max();\n\tstd::vector<int> max_index;\n\t\n\tfor (unsigned int i = 0; i < scores.size(); i++){\n\t\tif (scores[i] > max_score){\n\t\t\tmax_score = scores[i];\n\t\t\tmax_index = std::vector<int>();\n\t\t\tmax_index.push_back(i);\n\t\t} else if(scores[i] == max_score){\n\t\t\tmax_index.push_back(i);\n\t\t}\n\t}\n\n\treturn pickRandomElement(max_index);\n}\n\nConnectSolver::ConnectSolver(std::string opening_book) {\n  this->solver.loadBook(opening_book);\t\n}\n\nstd::vector<float> ConnectSolver::getBestScores(std::shared_ptr<Game> game){\n\tstd::shared_ptr<ConnectFour> c_game = std::dynamic_pointer_cast<ConnectFour>(game); \n    ArrayXf poss = c_game->getPossibleActions();\n\t\n\tfloat score;\n\tstd::vector<float> scores;\n\tfloat max_possible_score = (c_game->getBoardSize()[0]*c_game->getBoardSize()[1])/2;\n\n\tfor (int i = 0; i < poss.size(); i++){\n\t\tif (poss[i] != 0){\n\t\t\tPosition pos;\n\t\t\tstd::string to_play = c_game->getPlayedMoves()+ std::to_string(i + 1);\n    \t\t\n    \t\tif (pos.play(to_play) != to_play.size()){\n\t\t\t\tscore = max_possible_score;\n    \t\t} else{\n\t    \t\tscore = this->solver.solve(pos, false)*-1;\n    \t\t}\n\n    \t\tscores.push_back(score);\n    \t} else {\n    \t\tscores.push_back(-std::numeric_limits<float>::max());\n    \t}\n    }\n\n    return scores;\n}\n\nstd::string ConnectSolver::name(){\n\treturn \"Perfect C4 Player\";\n}\n\nProbabilisticPlayer::ProbabilisticPlayer(int deterministicAfter) : deterministicAfter(deterministicAfter) {}\n\nint ProbabilisticPlayer::getAction(std::shared_ptr<Game> game){\n\tArrayXf p = this->getProbabilities(game);\n\tint action;\n\t//std::cout<< p<<\"\\n fds\" << std::endl;\n\tif (this->howManyMovesPlayed > this->deterministicAfter){\n\t\tp.maxCoeff(&action);\n\t} else {\n\t\taction = pickStochasticElement(p);\n\t}\n\n\tthis->howManyMovesPlayed++;\n\n\treturn action;\n}\n\nAlphaZeroPlayer::AlphaZeroPlayer(NNWrapper& nn, MCTS::Config mcts, int deterministicAfter): \n\t\t\t\t\t\t\t\tProbabilisticPlayer(deterministicAfter),\n\t\t\t\t\t\t\t\tnn(nn), mcts(mcts){}\n\nArrayXf AlphaZeroPlayer::getProbabilities(std::shared_ptr<Game> game){\n\treturn MCTS::simulate(game, this->nn, this->mcts); \n}\n\nstd::string AlphaZeroPlayer::name(){\n\treturn \"AZ Player: \" + this->nn.getFilename();\n}\n\nMCTSPlayer::MCTSPlayer(MCTS::Config mcts, int deterministicAfter): \n\t\t\t\t\t\t\t\tProbabilisticPlayer(deterministicAfter),\n\t\t\t\t\t\t\t\tmcts(mcts){}\n\nArrayXf MCTSPlayer::getProbabilities(std::shared_ptr<Game> game){\n\tArrayXf p = MCTS::simulate_random(game, this->mcts);\n\treturn p;\n}\n\nstd::string MCTSPlayer::name(){\n\treturn \"MCTS Player\";\n}\n\nNNPlayer::NNPlayer(NNWrapper& nn, int deterministicAfter) : ProbabilisticPlayer(deterministicAfter), nn(nn) {}\n\nArrayXf NNPlayer::getProbabilities(std::shared_ptr<Game> game){\n\tNN::Input i = NN::Input({game->getBoard()});\n\t\n\tNN::Output res = this->nn.predict(i)[0];\n\n\tArrayXf poss = game->getPossibleActions();\n\tArrayXf valid_actions = poss*res.policy;\n\t\n\tstd::cout << game->getBoard() << std::endl;;\n\tstd::cout << valid_actions << std::endl;;\n\tstd::cout << \"value \" <<res.value << std::endl;;\n\treturn valid_actions;\n}\n\n\nstd::string NNPlayer::name(){\n\treturn \"NN Player: \" + this->nn.getFilename();\n}\n\nRandomPlayer::RandomPlayer(): seed(-1){ this->gen =  std::mt19937(this->rd()); }\nRandomPlayer::RandomPlayer(int seed): seed(seed){  this->gen =  std::mt19937(this->seed); }\n\nint RandomPlayer::getAction(std::shared_ptr<Game> game){\n    //std::cout<< \"random\" << std::endl;\n    ArrayXf poss = game->getPossibleActions();\n    poss = poss/poss.sum();\n    std::discrete_distribution<> dist(poss.data(),poss.data() +  poss.size());\n\n    return dist(this->gen);\n} \n\nstd::string RandomPlayer::name(){\n\treturn \"Randomy Player\";\n}\n", "meta": {"hexsha": "4500485c210a6207b99e797d4d1b2d22959a35b8", "size": 4713, "ext": "cc", "lang": "C++", "max_stars_repo_path": "cc/player/Player.cc", "max_stars_repo_name": "kiri11/alpha-zero-cpp", "max_stars_repo_head_hexsha": "00f19e65deaa274e7c547d6f5ad5470904fe347c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-07-23T16:49:03.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-23T16:49:03.000Z", "max_issues_repo_path": "cc/player/Player.cc", "max_issues_repo_name": "kiri11/alpha-zero-cpp", "max_issues_repo_head_hexsha": "00f19e65deaa274e7c547d6f5ad5470904fe347c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cc/player/Player.cc", "max_forks_repo_name": "kiri11/alpha-zero-cpp", "max_forks_repo_head_hexsha": "00f19e65deaa274e7c547d6f5ad5470904fe347c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-18T14:39:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-18T14:39:12.000Z", "avg_line_length": 26.1833333333, "max_line_length": 110, "alphanum_fraction": 0.6793974114, "num_tokens": 1278, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.45563220206499705}}
{"text": "#ifndef MATH_AFFINE_HPP\n#define MATH_AFFINE_HPP\n\n#include <boost/operators.hpp>\n\nnamespace Math {\n\n\ttemplate<typename R>\n\tstruct point: boost::operators<point<R>> {\n\t\tR x, y, z;\n\t\toperator dual<R>(void) const {\n\t\t\treturn {{1},{0,x,y,z}};\n\t\t}\n\t\tpoint& operator+=(const point<R> &rhs) {\n\t\t\tx += rhs.x;\n\t\t\ty += rhs.y;\n\t\t\tz += rhs.z;\n\t\t\treturn *this;\n\t\t}\n\t\tpoint& operator-=(const point<R> &rhs) {\n\t\t\tx -= rhs.x;\n\t\t\ty -= rhs.y;\n\t\t\tz -= rhs.z;\n\t\t\treturn *this;\n\t\t}\n\t\tpoint& operator*=(const R &rhs) {\n\t\t\treturn *this = {x*rhs, y*rhs, z*rhs};\n\t\t}\n\t\tpoint& operator*=(R && rhs) {\n\t\t\treturn *this = {x*rhs, y*rhs, z*rhs};\n\t\t}\n\t\tpoint operator*(R rhs) const {\n\t\t\treturn Point(x*rhs, y*rhs, z*rhs);\n\t\t}\n\t\tpoint(R x = 0, R y = 0, R z = 0):\n\t\t\tx(x), y(y), z(z) {}\n\t\tpoint(const point &p):\n\t\t\tx(p.x), y(p.y), z(p.z) {}\n\t};\n\n\ttemplate<typename S, typename R>\n\tpoint<R> operator*(const S &lhs, const point<R> &rhs) {\n\t\tpoint<R> out(rhs);\n\t\treturn out *= static_cast<R>(lhs);\n\t}\n\ttemplate<typename S, typename R>\n\tpoint<R> operator*(S && lhs, const point<R> &rhs) {\n\t\treturn rhs * static_cast<R>(lhs);\n\t}\n\n\ttemplate<typename R>\n\tstruct unit {\n\t\tR x, y, z;\n\t\toperator dual<R>(void) const {\n\t\t\treturn {1,0,0,0,0, x/2, y/2, z/2};\n\t\t}\n\t\tunit(R x, R y, R z): x(x), y(y), z(z) {}\n\t\tunit(unit<R> const& u): x(u.x), y(u.y), z(u.z) {}\n\t};\n\n\ttemplate<typename R>\n\tstruct ray: virtual dual<R> {\n\t\tR r;\n\t\tunit<R> n;\n\t\tray(R r, R x, R y, R z):\n\t\t\tr(r), n(x, y, z),\n\t\t\tdual<R>(1, 0, 0, 0, 0,\n\t\t\t\tr*x/2, r*y/2, r*z/2) {}\n\t\tray(R r, const unit<R> &dir):\n\t\t\tr(r), n(dir),\n\t\t\tdual<R>(1, 0, 0, 0, 0,\n\t\t\t\tr*n.x/2, r*n.y/2, r*n.z/2) {}\n\t\tray(unit<R> const& dir):\n\t\t\tray(1, dir) {}\n\t\tray(ray<R> const& rhs):\n\t\t\tray(rhs.r, rhs.n) {}\n\t};\n\t\n\ttemplate<typename R>\n\tstruct rotor: quat<R> {\n\t\tR theta;\n\t\tunit<R> n;\n\t\toperator dual<R>(void) const {\n\t\t\treturn {*this, 0};\n\t\t}\n\t\trotor(R theta, R nx, R ny, R nz):\n\t\t\trotor(theta, unit<R>(nx, ny, nz)) {}\n\t\trotor(R theta, const unit<R>& n):\n\t\t\ttheta(theta), n(n),\n\t\t\tquat<R>(cos(theta/2), sin(theta/2)*n.x,\n\t\t\t\tsin(theta/2)*n.y, sin(theta/2)*n.z) {}\n\t};\n\n\ttemplate<typename R>\n\tstruct pivot: dual<R> {\n\t\tray<R> translation;\n\t\trotor<R> rotation;\n\t\tpivot(const ray<R> &offset, const rotor<R> &rotor):\n\t\t\ttranslation(offset), rotation(rotor),\n\t\t\tdual<R>((~dual<R>(offset))(rotor)) {}\n\t\tpivot(ray<R> && offset, rotor<R> && rotor):\n\t\t\ttranslation(offset), rotation(rotor),\n\t\t\tdual<R> ((~dual<R>(offset))(rotor)) {}\n\t};\n}\n\n#endif\n", "meta": {"hexsha": "dd9739e44d8d55656679901ac7ff04e59215b95f", "size": 2425, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/math/affine.hpp", "max_stars_repo_name": "XPCX/CitaDel", "max_stars_repo_head_hexsha": "91de98a9e1507691df00e2c0a9dfb4e999fc9505", "max_stars_repo_licenses": ["MIT"], "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/affine.hpp", "max_issues_repo_name": "XPCX/CitaDel", "max_issues_repo_head_hexsha": "91de98a9e1507691df00e2c0a9dfb4e999fc9505", "max_issues_repo_licenses": ["MIT"], "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/affine.hpp", "max_forks_repo_name": "XPCX/CitaDel", "max_forks_repo_head_hexsha": "91de98a9e1507691df00e2c0a9dfb4e999fc9505", "max_forks_repo_licenses": ["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.4537037037, "max_line_length": 56, "alphanum_fraction": 0.5525773196, "num_tokens": 905, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.45563219691802226}}
{"text": "#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE Suites\n#include <boost/test/unit_test.hpp>\n#define EIGEN_USE_MKL_ALL\n#include<iostream>\n#include <Eigen/Eigenvalues> \n#include\"numerics.hpp\"\n#include\"reddm.hpp\"\n#include\"tpoperators.hpp\"\n#include \"files.hpp\"\nusing namespace boost::unit_test;\nusing boost::unit_test_framework::test_suite;\nusing namespace Many_Body;\nBOOST_AUTO_TEST_SUITE(timeevesting)\nBOOST_AUTO_TEST_CASE(timeev)\n{\n    using Mat= Operators::Mat;\n  int L=4;\n  double omega=1;\n  double gamma=1;\n  double t0=1;\n  double T=1;\n   using HolsteinBasis= TensorProduct<ElectronBasis, PhononBasis>;\n        PhononBasis g2{ 2, 1};\n  ElectronBasis e( L, 1);\n  //  std::cout<< e<<std::endl;\n  \n  PhononBasis ph(L, 6);\n  //std::cout<< ph<<std::endl;\n  HolsteinBasis TP(e, ph);\n  std::cout<< TP.dim << std::endl;\n        Mat E1=Operators::EKinOperatorL(TP, e, t0, true);\n      Mat Ebdag=Operators::BosonCOperator(TP, ph, gamma, true);\n      Mat Eb=Operators::BosonDOperator(TP, ph, gamma, true);\n      Mat Eph=Operators::NumberOperator(TP, ph, omega,  true);\n      \n      //Mat E=Operators::NumberOperatore(TP, e, 1, false);\n      //    std::cout<< HH << std::endl;\n      Eigen::VectorXd eigenVals(TP.dim);\n            Mat H=E1+Eph  +Ebdag + Eb;\n          Eigen::MatrixXd HH=Eigen::MatrixXd(H);\n  \t  Eigen::VectorXd ev(TP.dim);\n  \t  auto optModes=makeThermalRDMTP(HH, ev, TP, T, false, 0);\n  \t  double sum=0;\n  \t  for(auto& l : optModes)\n  \t    { \n  \t      std::cout<< l<<std::endl;\n  \t      sum+=l.sum();\n  \t    }\n\t  std::cout << \"and the sum of all was \"<< sum<<std::endl;\n  // //   std::cout<< TP<< std::endl;\n  // Eigen::VectorXd v1=Eigen::VectorXd::Zero(TP.dim);\n  // v1[1]=1/std::sqrt(2);\n  // Eigen::VectorXd v2=Eigen::VectorXd::Zero(TP.dim);\n  //   v2[5]=1/std::sqrt(2);\n  // \tEigen::VectorXd V1=v1 +v2;\n  // \tEigen::MatrixXd V2=V1.transpose();\n  // \t// std::cout<< V1<<std::endl;\n  // \t// std::cout<< V2<<std::endl;\t\n  // \tMatrixXd M=V1*(V2);\n  // \t// std::cout<< M<<std::endl;\n  // \t// \tstd::cout<< g2<<std::endl;\n  // \t//\tmakeRedDM(g2, 0, M);\n  // \tmakeRedDMTP(TP, ph,  0, M);\n\t\n\t\n }\nBOOST_AUTO_TEST_CASE(vecred)\n{\n   \n  // int L=4;\n  // double omega=1;\n  // double gamma=1;\n  // double t0=1;\n  // double T=2;\n  //  using HolsteinBasis= TensorProduct<ElectronBasis, PhononBasis>;\n  //       PhononBasis g2{ 2, 1};\n  // ElectronBasis e( L, 1);\n  // //  std::cout<< e<<std::endl;\n  \n  // PhononBasis ph(L, 8);\n  // HolsteinBasis TP(e, ph);\n  //    std::cout<<TP.dim<<std::endl;\n  // Eigen::VectorXcd psi=Eigen::VectorXcd::Random(TP.dim);\n  // psi/=psi.norm();\n  // auto l=  makeRedDMTP(TP, ph, 0, psi);\n  // \t   double sum{0};\n  // \t   for(auto&  k : l)\n  // \t     {\n  // \t       //  std::cout<< k << std::endl;\n  // \t       std::cout<< std::endl;\n  // \t       std::cout<< \"with trace \"<< k.trace()<< std::endl;\n  // \t       std::cout<< std::endl;\n  // \t       //sum+=(k.trace());\n  // \t     }\n  // \t   std::cout<< sum << std::endl;\n  // MatrixXcd rho=psi*psi.adjoint();\n  // makeRedDM(ph, 0,  rho);\n  // std::cout<< std::endl;\n  // std::cout<< std::endl;\n  // makeRedDM(ph, 0,  psi);\n  \n\t\n }\n\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "1a1a530e3f1ed79001b6f75f6f4146d3bea712dc", "size": 3138, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "testdir/reddmtest.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": "testdir/reddmtest.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": "testdir/reddmtest.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": 29.0555555556, "max_line_length": 69, "alphanum_fraction": 0.5793499044, "num_tokens": 1086, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.4556103447179023}}
{"text": "#include <Eigen/Dense>\n\n#include \"AprilTags/FloatImage.h\"\n#include \"AprilTags/MathUtil.h\"\n#include \"AprilTags/GLine2D.h\"\n#include \"AprilTags/Quad.h\"\n#include \"AprilTags/Segment.h\"\n\nnamespace AprilTags {\n\nconst float Quad::maxQuadAspectRatio = 32;\n\nQuad::Quad(const std::vector<std::pair<float, float> > &p,\n           const std::pair<float, float> &opticalCenter)\n    : quadPoints(p),\n      segments(),\n      observedPerimeter(),\n      homography(opticalCenter) {\n#ifdef STABLE_H\n  std::vector<std::pair<float, float> > srcPts;\n  srcPts.push_back(std::make_pair(-1, -1));\n  srcPts.push_back(std::make_pair(1, -1));\n  srcPts.push_back(std::make_pair(1, 1));\n  srcPts.push_back(std::make_pair(-1, 1));\n  homography.setCorrespondences(srcPts, p);\n#else\n  homography.addCorrespondence(-1, -1, quadPoints[0].first,\n                               quadPoints[0].second);\n  homography.addCorrespondence(1, -1, quadPoints[1].first,\n                               quadPoints[1].second);\n  homography.addCorrespondence(1, 1, quadPoints[2].first, quadPoints[2].second);\n  homography.addCorrespondence(-1, 1, quadPoints[3].first,\n                               quadPoints[3].second);\n#endif\n\n#ifdef INTERPOLATE\n  p0 = Eigen::Vector2f(p[0].first, p[0].second);\n  p3 = Eigen::Vector2f(p[3].first, p[3].second);\n  p01 = (Eigen::Vector2f(p[1].first, p[1].second) - p0);\n  p32 = (Eigen::Vector2f(p[2].first, p[2].second) - p3);\n#endif\n}\n\nstd::pair<float, float> Quad::interpolate(float x, float y) {\n#ifdef INTERPOLATE\n  Eigen::Vector2f r1 = p0 + p01 * (x + 1.) / 2.;\n  Eigen::Vector2f r2 = p3 + p32 * (x + 1.) / 2.;\n  Eigen::Vector2f r = r1 + (r2 - r1) * (y + 1) / 2;\n  return std::pair<float, float>(r(0), r(1));\n#else\n  return homography.project(x, y);\n#endif\n}\n\nstd::pair<float, float> Quad::interpolate01(float x, float y) {\n  return interpolate(2 * x - 1, 2 * y - 1);\n}\n\nvoid Quad::search(const FloatImage &fImage, std::vector<Segment *> &path,\n                  Segment &parent, int depth, std::vector<Quad> &quads,\n                  const std::pair<float, float> &opticalCenter) {\n  // cout << \"Searching segment \" << parent.getId() << \", depth=\" << depth << \",\n  // #children=\" << parent.children.size() << endl;\n  // terminal depth occurs when we've found four segments.\n  if (depth == 4) {\n    // cout << \"Entered terminal depth\" << endl; // debug code\n\n    // Is the first segment the same as the last segment (i.e., a loop?)\n    if (path[4] == path[0]) {\n      // the 4 corners of the quad as computed by the intersection of segments.\n      std::vector<std::pair<float, float> > p(4);\n      float calculatedPerimeter = 0;\n      bool bad = false;\n      for (int i = 0; i < 4; i++) {\n        // compute intersections between all the lines. This will give us\n        // sub-pixel accuracy for the corners of the quad.\n        GLine2D linea(std::make_pair(path[i]->getX0(), path[i]->getY0()),\n                      std::make_pair(path[i]->getX1(), path[i]->getY1()));\n        GLine2D lineb(\n            std::make_pair(path[i + 1]->getX0(), path[i + 1]->getY0()),\n            std::make_pair(path[i + 1]->getX1(), path[i + 1]->getY1()));\n\n        p[i] = linea.intersectionWith(lineb);\n        calculatedPerimeter += path[i]->getLength();\n\n        // no intersection? Occurs when the lines are almost parallel.\n        if (p[i].first == -1) bad = true;\n      }\n      // cout << \"bad = \" << bad << endl;\n      // eliminate quads that don't form a simply connected loop, i.e., those\n      // that form an hour glass, or wind the wrong way.\n      if (!bad) {\n        float t0 =\n            std::atan2(p[1].second - p[0].second, p[1].first - p[0].first);\n        float t1 =\n            std::atan2(p[2].second - p[1].second, p[2].first - p[1].first);\n        float t2 =\n            std::atan2(p[3].second - p[2].second, p[3].first - p[2].first);\n        float t3 =\n            std::atan2(p[0].second - p[3].second, p[0].first - p[3].first);\n\n        //  double ttheta = fmod(t1-t0, 2*M_PI) + fmod(t2-t1, 2*M_PI) +\n        //    fmod(t3-t2, 2*M_PI) + fmod(t0-t3, 2*M_PI);\n        float ttheta = MathUtil::mod2pi(t1 - t0) + MathUtil::mod2pi(t2 - t1) +\n                       MathUtil::mod2pi(t3 - t2) + MathUtil::mod2pi(t0 - t3);\n        // cout << \"ttheta=\" << ttheta << endl;\n        // the magic value is -2*PI. It should be exact,\n        // but we allow for (lots of) numeric imprecision.\n        if (ttheta < -7 || ttheta > -5) bad = true;\n      }\n\n      if (!bad) {\n        float d0 = MathUtil::distance2D(p[0], p[1]);\n        float d1 = MathUtil::distance2D(p[1], p[2]);\n        float d2 = MathUtil::distance2D(p[2], p[3]);\n        float d3 = MathUtil::distance2D(p[3], p[0]);\n        float d4 = MathUtil::distance2D(p[0], p[2]);\n        float d5 = MathUtil::distance2D(p[1], p[3]);\n\n        // check sizes\n        if (d0 < Quad::minimumEdgeLength || d1 < Quad::minimumEdgeLength ||\n            d2 < Quad::minimumEdgeLength || d3 < Quad::minimumEdgeLength ||\n            d4 < Quad::minimumEdgeLength || d5 < Quad::minimumEdgeLength) {\n          bad = true;\n          // cout << \"tagsize too small\" << endl;\n        }\n\n        // check aspect ratio\n        float dmax = max(max(d0, d1), max(d2, d3));\n        float dmin = min(min(d0, d1), min(d2, d3));\n\n        if (dmax > dmin * Quad::maxQuadAspectRatio) {\n          bad = true;\n          // cout << \"aspect ratio too extreme\" << endl;\n        }\n      }\n\n      if (!bad) {\n        Quad q(p, opticalCenter);\n        q.segments = path;\n        q.observedPerimeter = calculatedPerimeter;\n        quads.push_back(q);\n      }\n    }\n    return;\n  }\n\n  //  if (depth >= 1) // debug code\n  // cout << \"depth: \" << depth << endl;\n\n  // Not terminal depth. Recurse on any children that obey the correct\n  // handedness.\n  for (unsigned int i = 0; i < parent.children.size(); i++) {\n    Segment &child = *parent.children[i];\n    //    cout << \"  Child \" << child.getId() << \":  \";\n    // (handedness was checked when we created the children)\n\n    // we could rediscover each quad 4 times (starting from\n    // each corner). If we had an arbitrary ordering over\n    // points, we can eliminate the redundant detections by\n    // requiring that the first corner have the lowest\n    // value. We're arbitrarily going to use theta...\n    if (child.getTheta() > path[0]->getTheta()) {\n      // cout << \"theta failed: \" << child.getTheta() << \" > \" <<\n      // path[0]->getTheta() << endl;\n      continue;\n    }\n    path[depth + 1] = &child;\n    search(fImage, path, child, depth + 1, quads, opticalCenter);\n  }\n}\n\n}  // namespace\n", "meta": {"hexsha": "67a5b0c8abd1fc7831c4505a46e72fdc1cec10f2", "size": 6553, "ext": "cc", "lang": "C++", "max_stars_repo_path": "deps/src/apriltags/src/Quad.cc", "max_stars_repo_name": "chutsu/yac", "max_stars_repo_head_hexsha": "789c8b4116197e3a4b0232568414eec5489836da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2020-04-29T17:25:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T05:57:27.000Z", "max_issues_repo_path": "deps/src/apriltags/src/Quad.cc", "max_issues_repo_name": "chutsu/yac", "max_issues_repo_head_hexsha": "789c8b4116197e3a4b0232568414eec5489836da", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-06-26T04:44:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-04T17:56:35.000Z", "max_forks_repo_path": "deps/src/apriltags/src/Quad.cc", "max_forks_repo_name": "chutsu/yac", "max_forks_repo_head_hexsha": "789c8b4116197e3a4b0232568414eec5489836da", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-07-15T18:04:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-13T13:19:58.000Z", "avg_line_length": 37.6609195402, "max_line_length": 80, "alphanum_fraction": 0.5725621853, "num_tokens": 1962, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.4556103447179023}}
{"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_MODF_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_MODF_HPP_INCLUDED\n#include <boost/simd/function/std.hpp>\n\n#include <boost/simd/function/trunc.hpp>\n#include <boost/simd/detail/dispatch/function/overload.hpp>\n#include <boost/config.hpp>\n#include <boost/fusion/include/std_pair.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  BOOST_DISPATCH_OVERLOAD ( modf_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_ < bd::arithmetic_<A0> >\n                          , bd::scalar_ < bd::arithmetic_<A0> >\n                          , bd::scalar_ < bd::arithmetic_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE void operator() ( A0 a0, A0 & frac,A0 & ent) const BOOST_NOEXCEPT\n    {\n      ent = simd::trunc(a0);\n      frac = a0 - ent;\n    }\n  };\n  BOOST_DISPATCH_OVERLOAD ( modf_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_ < bd::arithmetic_<A0> >\n                          , bd::scalar_ < bd::arithmetic_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() ( A0 a0,A0 & ent) const BOOST_NOEXCEPT\n    {\n      A0 frac;\n      simd::modf(a0,frac,ent);\n      return frac;\n    }\n  };\n  BOOST_DISPATCH_OVERLOAD ( modf_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_ < bd::arithmetic_<A0> >\n                          )\n  {\n    using result_t = std::pair<A0,A0>;\n    BOOST_FORCEINLINE result_t operator() ( A0 a0) const BOOST_NOEXCEPT\n    {\n      A0 first, second;\n      boost::simd::modf(a0, first, second);\n      return {first, second};\n    }\n  };\n  BOOST_DISPATCH_OVERLOAD ( modf_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bs::std_tag\n                          , bd::scalar_ < bd::arithmetic_<A0> >\n                          , bd::scalar_ < bd::arithmetic_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() (const std_tag &,  A0 a0, A0 & ent) const BOOST_NOEXCEPT\n    {\n      A0 frac;\n      frac = std::modf(a0,&ent);\n      return frac;\n    }\n  };\n\n} } }\n\n\n#endif\n", "meta": {"hexsha": "eeb3e57d557ffc1101266c11ca7c7ab61d7d014f", "size": 2687, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/scalar/function/modf.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/scalar/function/modf.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/modf.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": 31.6117647059, "max_line_length": 100, "alphanum_fraction": 0.4778563454, "num_tokens": 623, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.6513548714339144, "lm_q1q2_score": 0.4554627735283238}}
{"text": "/*\n * ScalarCurveConfig.hpp\n *\n *  Created on: Mar 5, 2015\n *      Author: Paul Furgale, Renaud Dube, P\u00e9ter Fankhauser\n *   Institute: ETH Zurich, Autonomous Systems Lab\n */\n\n#pragma once\n\n#include <Eigen/Core>\n\nnamespace curves {\n\ntemplate <int N>\nstruct VectorSpaceConfig {\n  typedef Eigen::Matrix<double,N,1> ValueType;\n  typedef Eigen::Matrix<double,N,1> DerivativeType;\n};\n\n} // namespace\n", "meta": {"hexsha": "ee46d3f3c6d31ea0c7059ab25c65f1c0f2a47e1e", "size": 394, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "curves/include/curves/VectorSpaceConfig.hpp", "max_stars_repo_name": "leggedrobotics/curves", "max_stars_repo_head_hexsha": "696db3e9ecf67c143e7b48a8dd53d2c5ea1ba2fe", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 66.0, "max_stars_repo_stars_event_min_datetime": "2017-03-07T06:22:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T08:27:03.000Z", "max_issues_repo_path": "curves/include/curves/VectorSpaceConfig.hpp", "max_issues_repo_name": "leggedrobotics/curves", "max_issues_repo_head_hexsha": "696db3e9ecf67c143e7b48a8dd53d2c5ea1ba2fe", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 16.0, "max_issues_repo_issues_event_min_datetime": "2017-01-26T15:07:29.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-05T10:24:17.000Z", "max_forks_repo_path": "curves/include/curves/VectorSpaceConfig.hpp", "max_forks_repo_name": "leggedrobotics/curves", "max_forks_repo_head_hexsha": "696db3e9ecf67c143e7b48a8dd53d2c5ea1ba2fe", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2017-01-29T02:18:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T12:35:08.000Z", "avg_line_length": 17.9090909091, "max_line_length": 59, "alphanum_fraction": 0.7030456853, "num_tokens": 106, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.4554627640634116}}
{"text": "/* boost random_test.cpp various tests\r\n *\r\n * Copyright Jens Maurer 2000\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 * $Id: random_test.cpp 60755 2010-03-22 00:45:06Z steven_watanabe $\r\n */\r\n\r\n#if defined(BOOST_MSVC) && BOOST_MSVC <= 1300\r\n#pragma warning( disable : 4786 )\r\n#endif\r\n\r\n#include <iostream>\r\n#include <sstream>\r\n#include <string>\r\n#include <cmath>\r\n#include <iterator>\r\n#include <vector>\r\n#include <boost/random.hpp>\r\n#include <boost/config.hpp>\r\n\r\n#include <boost/test/test_tools.hpp>\r\n#include <boost/test/included/test_exec_monitor.hpp>\r\n\r\n#ifdef BOOST_NO_STDC_NAMESPACE\r\n  namespace std { using ::abs; using ::fabs; using ::pow; }\r\n#endif\r\n\r\n\r\n/*\r\n * General portability note:\r\n * MSVC mis-compiles explicit function template instantiations.\r\n * For example, f<A>() and f<B>() are both compiled to call f<A>().\r\n * BCC is unable to implicitly convert a \"const char *\" to a std::string\r\n * when using explicit function template instantiations.\r\n *\r\n * Therefore, avoid explicit function template instantiations.\r\n */\r\n\r\n/*\r\n * A few equidistribution tests\r\n */\r\n\r\n// yet to come...\r\n\r\ntemplate<class Generator>\r\nvoid check_uniform_int(Generator & gen, int iter)\r\n{\r\n  std::cout << \"testing uniform_int(\" << (gen.min)() << \",\" << (gen.max)() \r\n            << \")\" << std::endl;\r\n  int range = (gen.max)()-(gen.min)()+1;\r\n  std::vector<int> bucket(range);\r\n  for(int j = 0; j < iter; j++) {\r\n    int result = gen();\r\n    if(result < (gen.min)() || result > (gen.max)())\r\n      std::cerr << \"   ... delivers \" << result << std::endl;\r\n    else\r\n      bucket[result-(gen.min)()]++;\r\n  }\r\n  int sum = 0;\r\n  // use a different variable name \"k\", because MSVC has broken \"for\" scoping\r\n  for(int k = 0; k < range; k++)\r\n    sum += bucket[k];\r\n  double avg = static_cast<double>(sum)/range;\r\n  double p = 1 / static_cast<double>(range);\r\n  double threshold = 2*std::sqrt(static_cast<double>(iter)*p*(1-p));\r\n  for(int i = 0; i < range; i++) {\r\n    if(std::fabs(bucket[i] - avg) > threshold) {\r\n      // 95% confidence interval\r\n      std::cout << \"   ... has bucket[\" << i << \"] = \" << bucket[i] \r\n                << \"  (distance \" << (bucket[i] - avg) << \")\" \r\n                << std::endl;\r\n    }\r\n  }\r\n}\r\n\r\ntemplate<class Generator>\r\nvoid test_uniform_int(Generator & gen)\r\n{\r\n  typedef boost::uniform_int<int> int_gen;\r\n\r\n  // large range => small range (modulo case)\r\n  typedef boost::variate_generator<Generator&, int_gen> level_one;\r\n\r\n  level_one uint12(gen, int_gen(1,2));\r\n  BOOST_CHECK((uint12.distribution().min)() == 1);\r\n  BOOST_CHECK((uint12.distribution().max)() == 2);\r\n  check_uniform_int(uint12, 100000);\r\n  level_one uint16(gen, int_gen(1,6));\r\n  check_uniform_int(uint16, 100000);\r\n\r\n  // test chaining to get all cases in operator()\r\n\r\n  // identity map\r\n  typedef boost::variate_generator<level_one&, int_gen> level_two;\r\n  level_two uint01(uint12, int_gen(0, 1));\r\n  check_uniform_int(uint01, 100000);\r\n\r\n  // small range => larger range\r\n  level_two uint05(uint12, int_gen(-3, 2));\r\n  check_uniform_int(uint05, 100000);\r\n  \r\n  // small range => larger range\r\n  level_two uint099(uint12, int_gen(0, 99));\r\n  check_uniform_int(uint099, 100000);\r\n\r\n  // larger => small range, rejection case\r\n  typedef boost::variate_generator<level_two&, int_gen> level_three;\r\n  level_three uint1_4(uint05, int_gen(1, 4));\r\n  check_uniform_int(uint1_4, 100000);\r\n\r\n  typedef boost::uniform_int<boost::uint8_t> int8_gen;\r\n  typedef boost::variate_generator<Generator&, int8_gen> gen8_t;\r\n\r\n  gen8_t gen8_03(gen, int8_gen(0, 3));\r\n\r\n  // use the full range of the type, where the destination\r\n  // range is a power of the source range\r\n  typedef boost::variate_generator<gen8_t, int8_gen> uniform_uint8;\r\n  uniform_uint8 uint8_0255(gen8_03, int8_gen(0, 255));\r\n  check_uniform_int(uint8_0255, 100000);\r\n\r\n  // use the full range, but a generator whose range is not\r\n  // a root of the destination range.\r\n  gen8_t gen8_02(gen, int8_gen(0, 2));\r\n  uniform_uint8 uint8_0255_2(gen8_02, int8_gen(0, 255));\r\n  check_uniform_int(uint8_0255_2, 100000);\r\n\r\n  // expand the range to a larger type.\r\n  typedef boost::variate_generator<gen8_t, int_gen> uniform_uint_from8;\r\n  uniform_uint_from8 uint0300(gen8_03, int_gen(0, 300));\r\n  check_uniform_int(uint0300, 100000);\r\n}\r\n\r\n#if defined(BOOST_MSVC) && _MSC_VER < 1300\r\n\r\n// These explicit instantiations are necessary, otherwise MSVC does\r\n// not find the <boost/operators.hpp> inline friends.\r\n// We ease the typing with a suitable preprocessor macro.\r\n#define INSTANT(x) \\\r\ntemplate class boost::uniform_smallint<x>; \\\r\ntemplate class boost::uniform_int<x>; \\\r\ntemplate class boost::uniform_real<x>; \\\r\ntemplate class boost::bernoulli_distribution<x>; \\\r\ntemplate class boost::geometric_distribution<x>; \\\r\ntemplate class boost::triangle_distribution<x>; \\\r\ntemplate class boost::exponential_distribution<x>; \\\r\ntemplate class boost::normal_distribution<x>; \\\r\ntemplate class boost::uniform_on_sphere<x>; \\\r\ntemplate class boost::lognormal_distribution<x>;\r\n\r\nINSTANT(boost::minstd_rand0)\r\nINSTANT(boost::minstd_rand)\r\nINSTANT(boost::ecuyer1988)\r\nINSTANT(boost::kreutzer1986)\r\nINSTANT(boost::hellekalek1995)\r\nINSTANT(boost::mt19937)\r\nINSTANT(boost::mt11213b)\r\n\r\n#undef INSTANT\r\n#endif\r\n\r\n#if !defined(BOOST_NO_INT64_T) && !defined(BOOST_NO_INTEGRAL_INT64_T)\r\n// testcase by Mario Rutti\r\nclass ruetti_gen\r\n{\r\npublic:\r\n  ruetti_gen() : state((max)() - 1) {}\r\n  typedef boost::uint64_t result_type;\r\n  result_type min BOOST_PREVENT_MACRO_SUBSTITUTION () const { return 0; }\r\n  result_type max BOOST_PREVENT_MACRO_SUBSTITUTION () const { return std::numeric_limits<result_type>::max BOOST_PREVENT_MACRO_SUBSTITUTION (); }\r\n  result_type operator()() { return state--; }\r\nprivate:\r\n  result_type state;\r\n};\r\n\r\nvoid test_overflow_range()\r\n{\r\n  ruetti_gen gen;\r\n  boost::variate_generator<ruetti_gen, boost::uniform_int<> >\r\n    rng(gen, boost::uniform_int<>(0, 10));\r\n  for (int i=0;i<10;i++)\r\n    (void) rng();\r\n}\r\n#else\r\nvoid test_overflow_range()\r\n{ }\r\n#endif\r\n\r\ntemplate <typename EngineT>\r\nstruct rand_for_random_shuffle\r\n{\r\n  explicit rand_for_random_shuffle(EngineT &engine)\r\n    : m_engine(engine)\r\n  { }\r\n\r\n  template <typename IntT>\r\n  IntT operator()(IntT upperBound)\r\n  {\r\n    assert(upperBound > 0);\r\n\r\n    if (upperBound == 1)\r\n    {\r\n      return 0;\r\n    }\r\n\r\n    typedef boost::uniform_int<IntT> distribution_type;\r\n    typedef boost::variate_generator<EngineT &, distribution_type> generator_type;\r\n\r\n    return generator_type(m_engine, distribution_type(0, upperBound - 1))();\r\n  }\r\n\r\n  EngineT &m_engine;\r\n        \r\n};\r\n\r\n// Test that uniform_int<> can be used with std::random_shuffle\r\n// Author: Jos Hickson\r\nvoid test_random_shuffle()\r\n{\r\n    typedef boost::uniform_int<> distribution_type;\r\n    typedef boost::variate_generator<boost::mt19937 &, distribution_type> generator_type;\r\n\r\n    boost::mt19937 engine1(1234);\r\n    boost::mt19937 engine2(1234);\r\n\r\n    rand_for_random_shuffle<boost::mt19937> referenceRand(engine1);\r\n\r\n    distribution_type dist(0,10);\r\n    generator_type testRand(engine2, dist);\r\n\r\n    std::vector<int> referenceVec;\r\n\r\n    for (int i = 0; i < 200; ++i)\r\n    {\r\n      referenceVec.push_back(i);\r\n    }\r\n\r\n    std::vector<int> testVec(referenceVec);\r\n\r\n    std::random_shuffle(referenceVec.begin(), referenceVec.end(), referenceRand);\r\n    std::random_shuffle(testVec.begin(), testVec.end(), testRand);\r\n\r\n    typedef std::vector<int>::iterator iter_type;\r\n    iter_type theEnd(referenceVec.end());\r\n\r\n    for (iter_type referenceIter(referenceVec.begin()), testIter(testVec.begin());\r\n         referenceIter != theEnd;\r\n         ++referenceIter, ++testIter)\r\n    {\r\n      BOOST_CHECK_EQUAL(*referenceIter, *testIter);\r\n    }\r\n}\r\n\r\n\r\nint test_main(int, char*[])\r\n{\r\n\r\n#if !defined(__INTEL_COMPILER) || !defined(_MSC_VER) || __INTEL_COMPILER > 700 \r\n  boost::mt19937 mt;\r\n  test_uniform_int(mt);\r\n\r\n  // bug report from Ken Mahler:  This used to lead to an endless loop.\r\n  typedef boost::uniform_int<unsigned int> uint_dist;\r\n  boost::minstd_rand mr;\r\n  boost::variate_generator<boost::minstd_rand, uint_dist> r2(mr,\r\n                                                            uint_dist(0, 0xffffffff));\r\n  r2();\r\n  r2();\r\n\r\n  // bug report from Fernando Cacciola:  This used to lead to an endless loop.\r\n  // also from Douglas Gregor\r\n  boost::variate_generator<boost::minstd_rand, boost::uniform_int<> > x(mr, boost::uniform_int<>(0, 8361));\r\n  (void) x();\r\n\r\n  // bug report from Alan Stokes and others: this throws an assertion\r\n  boost::variate_generator<boost::minstd_rand, boost::uniform_int<> > y(mr, boost::uniform_int<>(1,1));\r\n  std::cout << \"uniform_int(1,1) \" << y() << \", \" << y() << \", \" << y()\r\n            << std::endl;\r\n\r\n  test_overflow_range();\r\n  test_random_shuffle();\r\n\r\n  return 0;\r\n#else\r\n  std::cout << \"Intel 7.00 on Win32 loops, so the test is disabled\\n\";\r\n  return 1;\r\n#endif\r\n}\r\n", "meta": {"hexsha": "9c5b63ea0bcb294499b070e4be28988cab9cbe03", "size": 9033, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/random/test/random_test.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/random/test/random_test.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/random/test/random_test.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": 30.9349315068, "max_line_length": 146, "alphanum_fraction": 0.667995129, "num_tokens": 2389, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548511303336, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.45546276341323}}
{"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_FUNCTION_EXPRECNEG_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_EXPRECNEG_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-exponential\n    Function object implementing exprecneg capabilities\n\n    Computes the  function: \\f$e^{-\\frac1x}\\f$\n\n    @par Semantic:\n\n    For every parameter of floating type T0\n\n    @code\n    T r = exprecneg(x);\n    @endcode\n\n    is equivalent to\n    @code\n    T r = exp(-rec((x)));\n    @endcode\n\n    @see exp, exprecnegc\n\n  **/\n  const boost::dispatch::functor<tag::exprecneg_> exprecneg = {};\n} }\n#endif\n\n#include <boost/simd/function/scalar/exprecneg.hpp>\n#include <boost/simd/function/simd/exprecneg.hpp>\n\n#endif\n", "meta": {"hexsha": "f3af7890cd7028669baa950e5eaef3954214fbac", "size": 1135, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/exprecneg.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/function/exprecneg.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/function/exprecneg.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": 22.7, "max_line_length": 100, "alphanum_fraction": 0.5806167401, "num_tokens": 260, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.45536702321864403}}
{"text": "// Copyright John Maddock 2006.\n// Copyright Paul A. Bristow 2007, 2009\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#define BOOST_MATH_OVERFLOW_ERROR_POLICY ignore_error\n\n#include <boost/math/concepts/real_concept.hpp>\n#include <boost/math/special_functions/math_fwd.hpp>\n#define BOOST_TEST_MAIN\n#include <boost/test/unit_test.hpp>\n#include <boost/test/results_collector.hpp>\n#include <boost/test/unit_test.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/math/tools/stats.hpp>\n#include <boost/math/tools/test.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/type_traits/is_floating_point.hpp>\n#include <boost/array.hpp>\n#include \"functor.hpp\"\n#include \"table_type.hpp\"\n#include \"handle_test_result.hpp\"\n\n#ifndef SC_\n#define SC_(x) static_cast<typename table_type<T>::type>(BOOST_JOIN(x, L))\n#endif\n\n#define BOOST_CHECK_CLOSE_EX(a, b, prec, i) \\\n   {\\\n      unsigned int failures = boost::unit_test::results_collector.results( boost::unit_test::framework::current_test_case().p_id ).p_assertions_failed;\\\n      BOOST_CHECK_CLOSE(a, b, prec); \\\n      if(failures != boost::unit_test::results_collector.results( boost::unit_test::framework::current_test_case().p_id ).p_assertions_failed)\\\n      {\\\n         std::cerr << \"Failure was at row \" << i << std::endl;\\\n         std::cerr << std::setprecision(35); \\\n         std::cerr << \"{ \" << data[i][0] << \" , \" << data[i][1] << \" , \" << data[i][2];\\\n         std::cerr << \" , \" << data[i][3] << \" , \" << data[i][4] << \" , \" << data[i][5] << \" } \" << std::endl;\\\n      }\\\n   }\n\ntemplate <class Real, class T>\nvoid do_test_gamma_2(const T& data, const char* type_name, const char* test_name)\n{\n   //\n   // test gamma_p_inva(T, T) against data:\n   //\n   using namespace std;\n   typedef typename T::value_type row_type;\n   typedef Real                   value_type;\n\n   std::cout << test_name << \" with type \" << type_name << std::endl;\n\n   //\n   // These sanity checks test for a round trip accuracy of one half\n   // of the bits in T, unless T is type float, in which case we check\n   // for just one decimal digit.  The problem here is the sensitivity\n   // of the functions, not their accuracy.  This test data was generated\n   // for the forward functions, which means that when it is used as\n   // the input to the inverses then it is necessarily inexact.  This rounding\n   // of the input is what makes the data unsuitable for use as an accuracy check,\n   // and also demonstrates that you can't in general round-trip these functions.\n   // It is however a useful sanity check.\n   //\n   value_type precision = static_cast<value_type>(ldexp(1.0, 1-boost::math::policies::digits<value_type, boost::math::policies::policy<> >()/2)) * 100;\n   if(boost::math::policies::digits<value_type, boost::math::policies::policy<> >() < 50)\n      precision = 1;   // 1% or two decimal digits, all we can hope for when the input is truncated to float\n\n   for(unsigned i = 0; i < data.size(); ++i)\n   {\n      //\n      // These inverse tests are thrown off if the output of the\n      // incomplete gamma is too close to 1: basically there is insuffient\n      // information left in the value we're using as input to the inverse\n      // to be able to get back to the original value.\n      //\n      if(Real(data[i][5]) == 0)\n         BOOST_CHECK_EQUAL(boost::math::gamma_p_inva(Real(data[i][1]), Real(data[i][5])), boost::math::tools::max_value<value_type>());\n      else if((1 - Real(data[i][5]) > 0.001) && (fabs(Real(data[i][5])) > 2 * boost::math::tools::min_value<value_type>()))\n      {\n         value_type inv = boost::math::gamma_p_inva(Real(data[i][1]), Real(data[i][5]));\n         BOOST_CHECK_CLOSE_EX(Real(data[i][0]), inv, precision, i);\n      }\n      else if(1 == Real(data[i][5]))\n         BOOST_CHECK_EQUAL(boost::math::gamma_p_inva(Real(data[i][1]), Real(data[i][5])), boost::math::tools::min_value<value_type>());\n      else if(Real(data[i][5]) > 2 * boost::math::tools::min_value<value_type>())\n      {\n         // not enough bits in our input to get back to x, but we should be in\n         // the same ball park:\n         value_type inv = boost::math::gamma_p_inva(Real(data[i][1]), Real(data[i][5]));\n         BOOST_CHECK_CLOSE_EX(Real(data[i][0]), inv, 100, i);\n      }\n\n      if(Real(data[i][3]) == 0)\n         BOOST_CHECK_EQUAL(boost::math::gamma_q_inva(Real(data[i][1]), Real(data[i][3])), boost::math::tools::min_value<value_type>());\n      else if((1 - Real(data[i][3]) > 0.001) \n         && (fabs(Real(data[i][3])) > 2 * boost::math::tools::min_value<value_type>()) \n         && (fabs(Real(data[i][3])) > 2 * boost::math::tools::min_value<double>()))\n      {\n         value_type inv = boost::math::gamma_q_inva(Real(data[i][1]), Real(data[i][3]));\n         BOOST_CHECK_CLOSE_EX(Real(data[i][0]), inv, precision, i);\n      }\n      else if(1 == Real(data[i][3]))\n         BOOST_CHECK_EQUAL(boost::math::gamma_q_inva(Real(data[i][1]), Real(data[i][3])), boost::math::tools::max_value<value_type>());\n      else if(Real(data[i][3]) > 2 * boost::math::tools::min_value<value_type>()) \n      {\n         // not enough bits in our input to get back to x, but we should be in\n         // the same ball park:\n         value_type inv = boost::math::gamma_q_inva(Real(data[i][1]), Real(data[i][3]));\n         BOOST_CHECK_CLOSE_EX(Real(data[i][0]), inv, 100, i);\n      }\n   }\n   std::cout << std::endl;\n}\n\ntemplate <class Real, class T>\nvoid do_test_gamma_inva(const T& data, const char* type_name, const char* test_name)\n{\n   typedef typename T::value_type row_type;\n   typedef Real                   value_type;\n\n   typedef value_type (*pg)(value_type, value_type);\n#if defined(BOOST_MATH_NO_DEDUCED_FUNCTION_POINTERS)\n   pg funcp = boost::math::gamma_p_inva<value_type, value_type>;\n#else\n   pg funcp = boost::math::gamma_p_inva;\n#endif\n\n   boost::math::tools::test_result<value_type> result;\n\n   std::cout << \"Testing \" << test_name << \" with type \" << type_name\n      << \"\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\";\n\n   //\n   // test gamma_p_inva(T, T) against data:\n   //\n   result = boost::math::tools::test_hetero<Real>(\n      data,\n      bind_func<Real>(funcp, 0, 1),\n      extract_result<Real>(2));\n   handle_test_result(result, data[result.worst()], result.worst(), type_name, \"boost::math::gamma_p_inva\", test_name);\n   //\n   // test gamma_q_inva(T, T) against data:\n   //\n#if defined(BOOST_MATH_NO_DEDUCED_FUNCTION_POINTERS)\n   funcp = boost::math::gamma_q_inva<value_type, value_type>;\n#else\n   funcp = boost::math::gamma_q_inva;\n#endif\n   result = boost::math::tools::test_hetero<Real>(\n      data,\n      bind_func<Real>(funcp, 0, 1),\n      extract_result<Real>(3));\n   handle_test_result(result, data[result.worst()], result.worst(), type_name, \"boost::math::gamma_q_inva\", test_name);\n}\n\ntemplate <class T>\nvoid test_gamma(T, const char* name)\n{\n#ifndef TEST_UDT\n   //\n   // The actual test data is rather verbose, so it's in a separate file\n   //\n   // First the data for the incomplete gamma function, each\n   // row has the following 6 entries:\n   // Parameter a, parameter z,\n   // Expected tgamma(a, z), Expected gamma_q(a, z)\n   // Expected tgamma_lower(a, z), Expected gamma_p(a, z)\n   //\n#  include \"igamma_med_data.ipp\"\n\n   do_test_gamma_2<T>(igamma_med_data, name, \"Running round trip sanity checks on incomplete gamma medium sized values\");\n\n#  include \"igamma_small_data.ipp\"\n\n   do_test_gamma_2<T>(igamma_small_data, name, \"Running round trip sanity checks on incomplete gamma small values\");\n\n#  include \"igamma_big_data.ipp\"\n\n   do_test_gamma_2<T>(igamma_big_data, name, \"Running round trip sanity checks on incomplete gamma large values\");\n\n#endif\n\n#  include \"igamma_inva_data.ipp\"\n\n   do_test_gamma_inva<T>(igamma_inva_data, name, \"Incomplete gamma inverses.\");\n}\n\n", "meta": {"hexsha": "edd53385be366d96ab03e86d40050241fc09d1a8", "size": 7964, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/math/test/test_igamma_inva.hpp", "max_stars_repo_name": "HelloSunyi/boost_1_54_0", "max_stars_repo_head_hexsha": "429fea793612f973d4b7a0e69c5af8156ae2b56e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2015-01-25T05:31:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-02T01:50:31.000Z", "max_issues_repo_path": "libs/math/test/test_igamma_inva.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": "libs/math/test/test_igamma_inva.hpp", "max_forks_repo_name": "graehl/boost", "max_forks_repo_head_hexsha": "37cc4ca77896a86ad10e90dc03e1e825dc0d5492", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-07-28T17:38:16.000Z", "max_forks_repo_forks_event_max_datetime": "2018-04-30T05:37:32.000Z", "avg_line_length": 42.1375661376, "max_line_length": 152, "alphanum_fraction": 0.6521848317, "num_tokens": 2157, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4553670232186439}}
{"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_FUNCTION_REM_PIO2_CEPHES_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_REM_PIO2_CEPHES_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-trigonometric\n    Function object implementing rem_pio2_cephes capabilities\n\n    Computes the remainder modulo \\f$\\pi/2\\f$ with cephes algorithm,\n    and the angle quadrant between 0 and 3.\n    This is a quick version accurate if the input is in \\f$[-20\\pi,20\\pi]\\f$.\n\n    @par Semantic:\n\n    For every parameters of floating type T:\n\n    @code\n    T r;\n    as_integer<T> n;\n    rem_pio2_cephes_(x, n, r);\n    @endcode\n\n    is similar to:\n\n    @code\n    as_integer<T> n = idivround2even(x, Pio_2<T>());\n    T r =  remainder(x, Pio_2<T>());\n    @endcode\n\n    @see rem_pio2, rem_pio2_straight,rem_2pi, rem_pio2_medium,\n\n  **/\n  const boost::dispatch::functor<tag::rem_pio2_cephes_> rem_pio2_cephes = {};\n} }\n#endif\n\n#include <boost/simd/function/scalar/rem_pio2_cephes.hpp>\n#include <boost/simd/function/simd/rem_pio2_cephes.hpp>\n\n#endif\n", "meta": {"hexsha": "9d876202146ffa91566a53ddcfa8362f241a1019", "size": 1462, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/rem_pio2_cephes.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/function/rem_pio2_cephes.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/function/rem_pio2_cephes.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": 26.1071428571, "max_line_length": 100, "alphanum_fraction": 0.6162790698, "num_tokens": 388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4553670232186439}}
{"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_ILOG2_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_ILOG2_HPP_INCLUDED\n\n#include <boost/simd/detail/nsm.hpp>\n#include <boost/simd/function/clz.hpp>\n#include <boost/simd/function/exponent.hpp>\n#include <boost/simd/detail/dispatch/function/overload.hpp>\n#include <boost/simd/detail/dispatch/meta/as_integer.hpp>\n#include <boost/config.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n\n  BOOST_DISPATCH_OVERLOAD(ilog2_, (typename A0), bd::cpu_, bd::scalar_<bd::floating_<A0>>)\n  {\n    BOOST_FORCEINLINE bd::as_integer_t<A0> operator() ( A0 a0) const BOOST_NOEXCEPT\n    {\n      BOOST_ASSERT_MSG( a0 > 0\n                      , \"Logarithm is not defined for zero or negative values.\" );\n      return exponent(a0);\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD(ilog2_, (typename A0), bd::cpu_, bd::scalar_<bd::arithmetic_<A0>>)\n  {\n    BOOST_FORCEINLINE A0 operator() ( A0 a0) const BOOST_NOEXCEPT\n    {\n      BOOST_ASSERT_MSG( a0 > 0\n                      , \"Logarithm is not defined for zero or negative values.\" );\n      return A0(sizeof(A0)*8-boost::simd::clz(a0)-1);\n    }\n  };\n\n#if defined(BOOST_MSVC)\n  BOOST_DISPATCH_OVERLOAD(ilog2_, (typename A0), bd::cpu_, bd::scalar_<bd::integer_<A0>>)\n  {\n    BOOST_FORCEINLINE A0 operator()(A0 a0) const BOOST_NOEXCEPT\n    {\n      BOOST_ASSERT_MSG( a0 > 0, \"Logarithm is not defined for zero or negative values.\" );\n      return impl(a0, typename nsm::bool_<sizeof(A0) <= 4>::type());\n    }\n\n    static BOOST_FORCEINLINE A0 impl( A0  a0,  tt::true_type const &) BOOST_NOEXCEPT\n    {\n      unsigned long index;\n      BOOST_VERIFY(::_BitScanReverse(&index, a0));\n      return static_cast<A0>(index);\n    }\n\n    #if defined(_WIN64)\n    static BOOST_FORCEINLINE A0 impl(A0 a0, tt::false_type const &) BOOST_NOEXCEPT\n    {\n      unsigned long index;\n      BOOST_VERIFY(::_BitScanReverse64(&index, a0));\n      return static_cast<A0>(index);\n    }\n    #else\n    static BOOST_FORCEINLINE A0 impl(A0 a0, tt::false_type const &) BOOST_NOEXCEPT\n    {\n      return static_cast<A0>(sizeof(A0)*8-boost::simd::clz(a0)-1);\n    }\n    #endif\n  };\n  #endif\n} } }\n\n#endif\n", "meta": {"hexsha": "11649a44d776f2a8ead5c69668cdf1ba443ec02a", "size": 2580, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/scalar/function/ilog2.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/ilog2.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/ilog2.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.6582278481, "max_line_length": 100, "alphanum_fraction": 0.6279069767, "num_tokens": 676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911056, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.45536701679912267}}
{"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_SSE_FAST_RSQRT_HPP_INCLUDED\n#define BOOST_SIMD_ARITHMETIC_FUNCTIONS_SCALAR_SSE_FAST_RSQRT_HPP_INCLUDED\n#if defined(BOOST_SIMD_HAS_SSE2_SUPPORT)\n\n#include <boost/simd/arithmetic/functions/fast_rsqrt.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT          ( fast_rsqrt_\n                                    , boost::simd::tag::sse_\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      _mm_store_ss( &r, _mm_rsqrt_ss( _mm_load_ss( &a0 ) ) );\n      return r * (( 3.f - (r * r) * a0) * 0.5f);\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT          ( fast_rsqrt_\n                                    , boost::simd::tag::sse_\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      float arg = a0;\n      _mm_store_ss( & arg, _mm_rsqrt_ss( _mm_load_ss( & arg ) ) );\n\n      double  r = arg;\n\n      r *= ((3.0 - (r * r) * a0) * 0.5);\n      r *= ((3.0 - (r * r) * a0) * 0.5);\n\n      return r;\n    }\n  };\n} } }\n\n#endif\n\n#endif\n", "meta": {"hexsha": "8b49892b0c72ab1431f7a143e2205ba8fc403f89", "size": 1901, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/scalar/sse/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/sse/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/sse/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": 32.2203389831, "max_line_length": 80, "alphanum_fraction": 0.4760652288, "num_tokens": 463, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911056, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.45536701679912256}}
{"text": "/* Copyright (C) 2021 Intel Corporation\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *  http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#include <helib/helib.h>\n#include <helib/debugging.h>\n\n#include <NTL/BasicThreadPool.h>\n\n#include \"gtest/gtest.h\"\n#include \"test_common.h\"\n\n#include \"../src/macro.h\" // Private header\n// only run if HEXL has been linked.\n#ifdef USE_INTEL_HEXL\n#include \"../src/intelExt.h\"       // Private header\n#include \"../src/PrimeGenerator.h\" // Private header\n\nnamespace {\n\n// FIXME Copied from GTestGeneral. Should really have common functionality.\n::testing::AssertionResult ciphertextMatches(const helib::EncryptedArray& ea,\n                                             const helib::SecKey& sk,\n                                             const helib::PtxtArray& p,\n                                             const helib::Ctxt& c)\n{\n  helib::PtxtArray pp(ea);\n  pp.decrypt(c, sk);\n  if (pp == p) {\n    return ::testing::AssertionSuccess();\n  } else {\n    return ::testing::AssertionFailure()\n           << \"Ciphertext does not match plaintext:\" << std::endl\n           << \"p = \" << p << std::endl\n           << \"pp = \" << pp << std::endl;\n  }\n}\n\nstruct Parameters\n{\n  Parameters(unsigned m,\n             unsigned p,\n             unsigned r,\n             unsigned bits,\n             const std::vector<long>& gens = {},\n             const std::vector<long>& ords = {}) :\n      m(m), p(p), r(r), bits(bits), gens(gens), ords(ords){};\n\n  const unsigned m;\n  const unsigned p;\n  const unsigned r;\n  const unsigned bits;\n  const std::vector<long> gens;\n  const std::vector<long> ords;\n\n  friend std::ostream& operator<<(std::ostream& os, const Parameters& params)\n  {\n    return os << \"{\"\n              << \"m = \" << params.m << \", \"\n              << \"p = \" << params.p << \", \"\n              << \"r = \" << params.r << \", \"\n              << \"gens = \" << helib::vecToStr(params.gens) << \", \"\n              << \"ords = \" << helib::vecToStr(params.ords) << \", \"\n              << \"bits = \" << params.bits << \"}\";\n  }\n};\n\nclass TestHEXL_BGV : public ::testing::TestWithParam<Parameters>\n{\nprotected:\n  const unsigned long m;\n  const unsigned long p;\n  const unsigned long r;\n  const unsigned long bits;\n  helib::Context context;\n  helib::SecKey secretKey;\n  const helib::PubKey publicKey;\n  const helib::EncryptedArray& ea;\n\n  TestHEXL_BGV() :\n      m(GetParam().m),\n      p(GetParam().p),\n      r(GetParam().r),\n      bits(GetParam().bits),\n      context(helib::ContextBuilder<helib::BGV>()\n                  .m(m)\n                  .p(p)\n                  .r(r)\n                  .bits(bits)\n                  .build()),\n      secretKey(context),\n      publicKey((secretKey.GenSecKey(),\n                 helib::addSome1DMatrices(secretKey),\n                 secretKey)),\n      ea(context.getEA())\n  {}\n\n  virtual void SetUp() override\n  {\n    NTL::SetNumThreads(1);\n    if (helib_test::verbose) {\n      ea.getPAlgebra().printout();\n      std::cout << \"r = \" << context.getAlMod().getR() << std::endl;\n      std::cout << \"ctxtPrimes=\" << context.getCtxtPrimes()\n                << \", specialPrimes=\" << context.getSpecialPrimes() << \"\\n\"\n                << std::endl;\n    }\n\n    helib::setupDebugGlobals(&secretKey, context.shareEA());\n  }\n\n  virtual void TearDown() override { helib::cleanupDebugGlobals(); }\n};\n\nstruct HEXL_params\n{\n  const long N; // phim\n  const long modulus;\n  HEXL_params(long _N, long _modulus) : N(_N), modulus(_modulus) {}\n};\n\nclass TestHEXL : public ::testing::TestWithParam<HEXL_params>\n{\nprotected:\n  const long N; // phim\n  const long modulus;\n\n  TestHEXL() : N(GetParam().N), modulus(GetParam().modulus) {}\n};\n\nTEST(TestHEXL, hexlInUse)\n{\n  // This test does not use HEXL_params because algebra must be d == 1\n\n  long N = 64;\n  long modulus = 769;\n\n  std::vector<long> args(N);\n  for (size_t i = 0; i < args.size(); ++i) {\n    args[i] = i + 1;\n  }\n  auto expected_outputs = args;\n\n  intel::FFTFwd(args.data(), args.data(), N, modulus);\n  intel::FFTRev1(args.data(), args.data(), N, modulus);\n\n  EXPECT_TRUE(std::equal(args.begin(), args.end(), expected_outputs.begin()));\n}\n\nTEST_P(TestHEXL_BGV, multiplyTwoCtxts)\n{\n  helib::PtxtArray p0(ea), p1(ea);\n  p0.random();\n  p1.random();\n\n  helib::Ctxt c0(publicKey), c1(publicKey);\n  p0.encrypt(c0);\n  p1.encrypt(c1);\n\n  p0 *= p1;\n  c0 *= c1;\n\n  EXPECT_TRUE(ciphertextMatches(ea, secretKey, p0, c0));\n}\n\nTEST_P(TestHEXL_BGV, encryptDecrypt)\n{\n  NTL::SetNumThreads(1);\n  helib::PtxtArray p0(ea);\n\n  std::vector<long> v0 = {0, 5};\n\n  p0.load(v0);\n\n  helib::Ctxt c0(publicKey);\n  p0.encrypt(c0);\n\n  EXPECT_TRUE(ciphertextMatches(ea, secretKey, p0, c0));\n}\n\nTEST_P(TestHEXL, CModulusFFT)\n{\n  NTL::SetNumThreads(1);\n\n  long m = 2 * N;\n  helib::PAlgebra zms(m, modulus);\n\n  std::cout << \"***SP bits: \" << HELIB_SP_NBITS << '\\n';\n\n  helib::PrimeGenerator prime_generator(HELIB_SP_NBITS, m);\n  long q = prime_generator.next();\n  helib::Cmodulus cmod(zms, q, 0);\n\n  NTL::ZZX poly;\n  poly.SetLength(2);\n  poly[0] = 0;\n  poly[1] = 5;\n  //  std::cout << \"TEST: input \" << poly << std::endl;\n\n  NTL::vec_long transformed;\n  cmod.FFT(transformed, poly);\n  //  std::cout << \"TEST: transformed \" << transformed << std::endl;\n\n  NTL::zz_pX inverse;\n  cmod.iFFT(inverse, transformed);\n  //  std::cout << \"TEST: inverse \" << inverse << std::endl;\n\n  NTL::ZZX inverse_conv = NTL::conv<NTL::ZZX>(inverse);\n  EXPECT_EQ(inverse_conv, poly);\n}\n\n// clang-format off\nINSTANTIATE_TEST_SUITE_P(typicalParameters, TestHEXL_BGV, ::testing::Values(\n    //Parameters(16, 3, 1, 300) // m power of 2.\n    Parameters(8, 769, 1, 50) // m power of 2.\n    ));\n\nINSTANTIATE_TEST_SUITE_P(typicalParameters, TestHEXL, ::testing::Values(\n    //Parameters(16, 3, 1, 300) // m power of 2.\n    HEXL_params(/*phim=*/8, /*p=*/769), // m power of 2, d == 1.\n    HEXL_params(/*phim=*/64, /*p=*/769), // m power of 2, d == 1.\n    HEXL_params(/*m=512, phim=*/256, /*p=*/769) // m power of 2, d == 2. \n    ));\n// clang-format on\n\n} // namespace\n\n#else\n\nnamespace {\n\nTEST(TestHEXL, noTestRequired)\n{\n  std::cout << \"***SP bits: \" << HELIB_SP_NBITS << '\\n';\n}\n\n} // namespace\n\n#endif // USE_INTEL_HEXL\n", "meta": {"hexsha": "e0e63a856c16a111905254e122b0b0042498a403", "size": 6595, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/TestHEXL.cpp", "max_stars_repo_name": "jlakness-intel/HElib", "max_stars_repo_head_hexsha": "fe1dc6c0625904ba9bd31d9d578dd535cd632de1", "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": "tests/TestHEXL.cpp", "max_issues_repo_name": "jlakness-intel/HElib", "max_issues_repo_head_hexsha": "fe1dc6c0625904ba9bd31d9d578dd535cd632de1", "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": "tests/TestHEXL.cpp", "max_forks_repo_name": "jlakness-intel/HElib", "max_forks_repo_head_hexsha": "fe1dc6c0625904ba9bd31d9d578dd535cd632de1", "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": 26.5927419355, "max_line_length": 78, "alphanum_fraction": 0.5965125095, "num_tokens": 1884, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911056, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.45536701679912256}}
{"text": "#define BOOST_TEST_MODULE \"C++ Unit Tests for metaLBM\"\n#include <boost/test/included/unit_test.hpp>\n#include <boost/test/unit_test.hpp>\n#include <boost/test/floating_point_comparison.hpp>\nnamespace tt = boost::test_tools;\n\n#define NPROCS 1\n#include \"Lattice.h\"\n\n#include <math.h>\n#include <iostream>\n\nusing namespace lbm;\n\nBOOST_AUTO_TEST_SUITE(TestLattice)\n\nBOOST_AUTO_TEST_CASE(TestIsotropyD1Q3) {\n  constexpr LatticeType latticeType = LatticeType::D1Q3;\n  typedef double valueType;\n  typedef Lattice<valueType, latticeType> L;\n\n  valueType sumWeight = 0.0;\n  valueType sumWeight_r = 1.0;\n\n  MathVector<valueType, L::dimD> sumWeightCelerity{{0.0}};\n  MathVector<valueType, L::dimD> sumWeightCelerity_r{{0.0}};\n\n  MathVector<valueType, L::dimD*L::dimD> sumWeight2Celerity{{0.0}};\n  MathVector<valueType, L::dimD*L::dimD> sumWeight2Celerity_r{{0.0}};\n\n  MathVector<valueType, L::dimD*L::dimD*L::dimD> sumWeight3Celerity{{0.0}};\n  MathVector<valueType, L::dimD*L::dimD*L::dimD> sumWeight3Celerity_r{{0.0}};\n\n  MathVector<valueType, L::dimD*L::dimD*L::dimD*L::dimD> sumWeight4Celerity{{0.0}};\n  MathVector<valueType, L::dimD*L::dimD*L::dimD*L::dimD> sumWeight4Celerity_r{{0.0}};\n\n  MathVector<valueType, L::dimD*L::dimD*L::dimD*L::dimD*L::dimD> sumWeight5Celerity{{0.0}};\n  MathVector<valueType, L::dimD*L::dimD*L::dimD*L::dimD*L::dimD> sumWeight5Celerity_r{{0.0}};\n\n\n  for(int iQ = 0; iQ < L::dimQ; ++iQ) {\n    sumWeight += L::weight()[iQ];\n\n    for(int d_a = 0; d_a < L::dimD; ++d_a) {\n      int idx_a = d_a;\n      sumWeightCelerity[idx_a] += L::weight()[iQ]*L::celerity()[iQ][d_a];\n\n      for(int d_b = 0; d_b < L::dimD; ++d_b) {\n        int idx_b = L::dimD * idx_a + d_b;\n        sumWeight2Celerity[idx_b] += L::weight()[iQ]*L::celerity()[iQ][d_a]*L::celerity()[iQ][d_b];\n\n        if(d_a == d_b) {\n          sumWeight2Celerity_r[idx_b] = L::cs2;\n        }\n\n        for(int d_c = 0; d_c < L::dimD; ++d_c) {\n          int idx_c = L::dimD * idx_b + d_c;\n          sumWeight3Celerity[idx_c] += L::weight()[iQ]*L::celerity()[iQ][d_a]\n            *L::celerity()[iQ][d_b]*L::celerity()[iQ][d_c];\n\n          for(int d_d = 0; d_d < L::dimD; ++d_d) {\n            int idx_d = L::dimD * idx_c + d_d;\n            sumWeight4Celerity[idx_d] += L::weight()[iQ]*L::celerity()[iQ][d_a]\n              *L::celerity()[iQ][d_b]*L::celerity()[iQ][d_c]*L::celerity()[iQ][d_d];\n\n            if((d_a == d_b && d_c == d_d)\n               && (d_a == d_c && d_b == d_d)\n               && (d_a == d_d && d_b == d_c)) {\n              sumWeight4Celerity_r[idx_d] = 3.0*L::cs2*L::cs2;\n            }\n            else if(((d_a == d_b && d_c == d_d) && (d_a == d_c && d_b == d_d))\n                    || ((d_a == d_b && d_c == d_d) && (d_a == d_d && d_b == d_d))\n                    || ((d_a == d_d && d_b == d_c) && (d_a == d_d && d_b == d_d))) {\n              sumWeight4Celerity_r[idx_d] = 2.0*L::cs2*L::cs2;\n            }\n            else if((d_a == d_b && d_c == d_d)\n                    || (d_a == d_c && d_b == d_d)\n                    || (d_a == d_d && d_b == d_c)) {\n              sumWeight4Celerity_r[idx_d] = 1.0*L::cs2*L::cs2;\n            }\n\n            for(int d_e = 0; d_e < L::dimD; ++d_e) {\n              int idx_e = L::dimD * idx_d + d_e;\n              sumWeight5Celerity[idx_e] += L::weight()[iQ]*L::celerity()[iQ][d_a]\n                *L::celerity()[iQ][d_b]*L::celerity()[iQ][d_c]*L::celerity()[iQ][d_d]\n                *L::celerity()[iQ][d_e];\n            }\n          }\n        }\n      }\n    }\n  }\n\n  BOOST_TEST(sumWeight == sumWeight_r, tt::tolerance(1e-15));\n  for(int i = 0; i < L::dimD; ++i) {\n    BOOST_TEST(sumWeightCelerity[i] == sumWeightCelerity_r[i], tt::tolerance(1e-15));\n  }\n  for(int i = 0; i < L::dimD*L::dimD; ++i) {\n    BOOST_TEST(sumWeight2Celerity[i] == sumWeight2Celerity_r[i], tt::tolerance(1e-15));\n  }\n  for(int i = 0; i < L::dimD*L::dimD*L::dimD; ++i) {\n    BOOST_TEST(sumWeight3Celerity[i] == sumWeight3Celerity_r[i], tt::tolerance(1e-15));\n  }\n  for(int i = 0; i < L::dimD*L::dimD*L::dimD*L::dimD; ++i) {\n    BOOST_TEST(sumWeight4Celerity[i] == sumWeight4Celerity_r[i], tt::tolerance(1e-15));\n  }\n  for(int i = 0; i < L::dimD*L::dimD*L::dimD*L::dimD*L::dimD; ++i) {\n    BOOST_TEST(sumWeight5Celerity[i] == sumWeight5Celerity_r[i], tt::tolerance(1e-15));\n  }\n}\n\nBOOST_AUTO_TEST_CASE(TestDoubleD1Q3) {\n  constexpr LatticeType latticeType = LatticeType::D1Q3;\n  typedef double valueType;\n  typedef Lattice<valueType, latticeType> L;\n\n  const auto dimD_ = L::dimD;\n  BOOST_CHECK_EQUAL(dimD_, 1);\n  const auto dimQ_ = L::dimQ;\n  BOOST_CHECK_EQUAL(dimQ_, 3);\n\n  const auto lX_g_ = L::lX_g;\n  BOOST_CHECK_EQUAL(lX_g_, lengthX_g);\n  const auto lY_g_ = L::lY_g;\n  BOOST_CHECK_EQUAL(lY_g_, 1);\n  const auto lZ_g_ = L::lZ_g;\n  BOOST_CHECK_EQUAL(lZ_g_, 1);\n\n  const auto hX_ = L::hX;\n  BOOST_CHECK_EQUAL(hX_, 1);\n  const auto hY_ = L::hY;\n  BOOST_CHECK_EQUAL(hY_, 0);\n  const auto hZ_ = L::hZ;\n  BOOST_CHECK_EQUAL(hZ_, 0);\n\n  const auto inv_cs2_ = L::inv_cs2;\n  BOOST_CHECK_EQUAL(inv_cs2_, 3.0);\n  const auto cs2_ = L::cs2;\n  BOOST_CHECK_EQUAL(cs2_, 1.0/3.0);\n\n  const auto w0_ = L::weight()[0];\n  BOOST_CHECK_EQUAL(w0_, 2.0/3.0);\n  const auto w1_ = L::weight()[1];\n  BOOST_CHECK_EQUAL(w1_, 1.0/6.0);\n  const auto w2_ = L::weight()[2];\n  BOOST_CHECK_EQUAL(w2_, 1.0/6.0);\n\n  const auto c_ = L::celerity();\n  const auto c_r = MathVector<MathVector<valueType, dimD_>, dimQ_>\n    {{\n        {{0.0}},\n        {{-1.0}},\n        {{1.0}}\n      }};\n\n  BOOST_CHECK_EQUAL(c_, c_r);\n\n\n  const auto c0_0_ = L::celerity()[0][0];\n  BOOST_CHECK_EQUAL(c0_0_, 0.0);\n  const auto c1_0_ = L::celerity()[1][0];\n  BOOST_CHECK_EQUAL(c1_0_, -1.0);\n  const auto c2_0_ = L::celerity()[2][0];\n  BOOST_CHECK_EQUAL(c2_0_, 1.0);\n\n  const auto c0_ = L::celerity()[0];\n  const auto c0_r = MathVector<valueType, dimD_>{{0.0}};\n  BOOST_CHECK_EQUAL(c0_, c0_r);\n  const auto c1_ = L::celerity()[1];\n  const auto c1_r = MathVector<valueType, dimD_>{{-1.0}};\n  BOOST_CHECK_EQUAL(c1_, c1_r);\n  const auto c2_ = L::celerity()[2];\n  const auto c2_r = MathVector<valueType, dimD_>{{1.0}};\n  BOOST_CHECK_EQUAL(c2_, c2_r);\n\n}\n\nBOOST_AUTO_TEST_CASE(TestFloatD1Q3) {\n  constexpr LatticeType latticeType = LatticeType::D1Q3;\n  typedef float valueType;\n  typedef Lattice<valueType, latticeType> L;\n\n  const auto dimD_ = L::dimD;\n  BOOST_CHECK_EQUAL(dimD_, 1);\n  const auto dimQ_ = L::dimQ;\n  BOOST_CHECK_EQUAL(dimQ_, 3);\n\n  const auto lX_g_ = L::lX_g;\n  BOOST_CHECK_EQUAL(lX_g_, lengthX_g);\n  const auto lY_g_ = L::lY_g;\n  BOOST_CHECK_EQUAL(lY_g_, 1);\n  const auto lZ_g_ = L::lZ_g;\n  BOOST_CHECK_EQUAL(lZ_g_, 1);\n\n  const auto hX_ = L::hX;\n  BOOST_CHECK_EQUAL(hX_, 1);\n  const auto hY_ = L::hY;\n  BOOST_CHECK_EQUAL(hY_, 0);\n  const auto hZ_ = L::hZ;\n  BOOST_CHECK_EQUAL(hZ_, 0);\n\n  const auto inv_cs2_ = L::inv_cs2;\n  BOOST_CHECK_EQUAL(inv_cs2_, 3.0f);\n  const auto cs2_ = L::cs2;\n  BOOST_CHECK_EQUAL(cs2_, 1.0f/3.0f);\n\n  const auto w0_ = L::weight()[0];\n  BOOST_CHECK_EQUAL(w0_, 2.0f/3.0f);\n  const auto w1_ = L::weight()[1];\n  BOOST_CHECK_EQUAL(w1_, 1.0f/6.0f);\n  const auto w2_ = L::weight()[2];\n  BOOST_CHECK_EQUAL(w2_, 1.0f/6.0f);\n\n  const auto c_ = L::celerity();\n  const auto c_r = MathVector<MathVector<valueType, dimD_>, dimQ_>\n    {{\n        {{0.0f}},\n        {{-1.0f}},\n        {{1.0f}}\n      }};\n\n  BOOST_CHECK_EQUAL(c_, c_r);\n\n\n  const auto c0_0_ = L::celerity()[0][0];\n  BOOST_CHECK_EQUAL(c0_0_, 0.0f);\n\n  const auto c1_0_ = L::celerity()[1][0];\n  BOOST_CHECK_EQUAL(c1_0_, -1.0f);\n\n  const auto c2_0_ = L::celerity()[2][0];\n  BOOST_CHECK_EQUAL(c2_0_, 1.0f);\n\n  const auto c0_ = L::celerity()[0];\n  const auto c0_r = MathVector<valueType, dimD_>{{0.0f}};\n  BOOST_CHECK_EQUAL(c0_, c0_r);\n  const auto c1_ = L::celerity()[1];\n  const auto c1_r = MathVector<valueType, dimD_>{{-1.0f}};\n  BOOST_CHECK_EQUAL(c1_, c1_r);\n  const auto c2_ = L::celerity()[2];\n  const auto c2_r = MathVector<valueType, dimD_>{{1.0f}};\n  BOOST_CHECK_EQUAL(c2_, c2_r);\n}\n\n\nBOOST_AUTO_TEST_CASE(TestIsotropyD2Q5) {\n  constexpr LatticeType latticeType = LatticeType::D2Q5;\n  typedef double valueType;\n  typedef Lattice<valueType, latticeType> L;\n\n  valueType sumWeight = 0.0;\n  valueType sumWeight_r = 1.0;\n\n  MathVector<valueType, L::dimD> sumWeightCelerity{{0.0}};\n  MathVector<valueType, L::dimD> sumWeightCelerity_r{{0.0}};\n\n  for(int iQ = 0; iQ < L::dimQ; ++iQ) {\n    sumWeight += L::weight()[iQ];\n\n    for(int d_a = 0; d_a < L::dimD; ++d_a) {\n      int idx_a = d_a;\n      sumWeightCelerity[idx_a] += L::weight()[iQ]*L::celerity()[iQ][d_a];\n    }\n  }\n\n  BOOST_TEST(sumWeight == sumWeight_r, tt::tolerance(1e-15));\n  for(int i = 0; i < L::dimD; ++i) {\n    BOOST_TEST(sumWeightCelerity[i] == sumWeightCelerity_r[i], tt::tolerance(1e-15));\n  }\n}\n\nBOOST_AUTO_TEST_CASE(TestDoubleD2Q5) {\n  constexpr LatticeType latticeType = LatticeType::D2Q5;\n  typedef double valueType;\n\n  typedef Lattice<valueType, latticeType> L;\n\n  const auto dimD_ = L::dimD;\n  BOOST_CHECK_EQUAL(dimD_, 2);\n  const auto dimQ_ = L::dimQ;\n  BOOST_CHECK_EQUAL(dimQ_, 5);\n\n  const auto lX_g_ = L::lX_g;\n  BOOST_CHECK_EQUAL(lX_g_, lengthX_g);\n  const auto lY_g_ = L::lY_g;\n  BOOST_CHECK_EQUAL(lY_g_, lengthY_g);\n  const auto lZ_g_ = L::lZ_g;\n  BOOST_CHECK_EQUAL(lZ_g_, 1);\n\n  const auto hX_ = L::hX;\n  BOOST_CHECK_EQUAL(hX_, 1);\n  const auto hY_ = L::hY;\n  BOOST_CHECK_EQUAL(hY_, 1);\n  const auto hZ_ = L::hZ;\n  BOOST_CHECK_EQUAL(hZ_, 0);\n\n  const auto inv_cs2_ = L::inv_cs2;\n  BOOST_CHECK_EQUAL(inv_cs2_, 3.0);\n  const auto cs2_ = L::cs2;\n  BOOST_CHECK_EQUAL(cs2_, (1.0/3.0));\n\n  const auto w0_ = L::weight()[0];\n  BOOST_CHECK_EQUAL(w0_, 4.0/6.0);\n  const auto w1_ = L::weight()[1];\n  BOOST_CHECK_EQUAL(w1_, 1.0/12.0);\n  const auto w2_ = L::weight()[2];\n  BOOST_CHECK_EQUAL(w2_, 1.0/12.0);\n  const auto w3_ = L::weight()[3];\n  BOOST_CHECK_EQUAL(w3_, 1.0/12.0);\n  const auto w4_ = L::weight()[4];\n  BOOST_CHECK_EQUAL(w4_, 1.0/12.0);\n\n  const auto c0_ = L::celerity()[0];\n  const auto c0_r = MathVector<valueType, dimD_>{{0.0, 0.0}};\n  BOOST_CHECK_EQUAL(c0_, c0_r);\n  const auto c1_ = L::celerity()[1];\n  const auto c1_r = MathVector<valueType, dimD_>{{-1.0, 0.0}};\n  BOOST_CHECK_EQUAL(c1_, c1_r);\n  const auto c2_ = L::celerity()[2];\n  const auto c2_r = MathVector<valueType, dimD_>{{0.0, -1.0}};\n  BOOST_CHECK_EQUAL(c2_, c2_r);\n  const auto c3_ = L::celerity()[3];\n  const auto c3_r = MathVector<valueType, dimD_>{{1.0, 0.0}};\n  BOOST_CHECK_EQUAL(c3_, c3_r);\n  const auto c4_ = L::celerity()[4];\n  const auto c4_r = MathVector<valueType, dimD_>{{0.0, 1.0}};\n  BOOST_CHECK_EQUAL(c4_, c4_r);\n\n  const auto c0_0_ = L::celerity()[0][0];\n  BOOST_CHECK_EQUAL(c0_0_, 0.0);\n  const auto c0_1_ = L::celerity()[0][1];\n  BOOST_CHECK_EQUAL(c0_1_, 0.0);\n\n  const auto c1_0_ = L::celerity()[1][0];\n  BOOST_CHECK_EQUAL(c1_0_, -1.0);\n  const auto c1_1_ = L::celerity()[1][1];\n  BOOST_CHECK_EQUAL(c1_1_, 0.0);\n\n  const auto c2_0_ = L::celerity()[2][0];\n  BOOST_CHECK_EQUAL(c2_0_, 0.0);\n  const auto c2_1_ = L::celerity()[2][1];\n  BOOST_CHECK_EQUAL(c2_1_, -1.0);\n\n  const auto c3_0_ = L::celerity()[3][0];\n  BOOST_CHECK_EQUAL(c3_0_, 1.0);\n  const auto c3_1_ = L::celerity()[3][1];\n  BOOST_CHECK_EQUAL(c3_1_, 0.0);\n\n  const auto c4_0_ = L::celerity()[4][0];\n  BOOST_CHECK_EQUAL(c4_0_, 0.0);\n  const auto c4_1_ = L::celerity()[4][1];\n  BOOST_CHECK_EQUAL(c4_1_, 1.0);\n}\n\nBOOST_AUTO_TEST_CASE(TestFloatD2Q5) {\n  constexpr LatticeType latticeType = LatticeType::D2Q5;\n  typedef float valueType;\n\n  typedef Lattice<valueType, latticeType> L;\n\n  const auto dimD_ = L::dimD;\n  BOOST_CHECK_EQUAL(dimD_, 2);\n  const auto dimQ_ = L::dimQ;\n  BOOST_CHECK_EQUAL(dimQ_, 5);\n\n  const auto lX_g_ = L::lX_g;\n  BOOST_CHECK_EQUAL(lX_g_, lengthX_g);\n  const auto lY_g_ = L::lY_g;\n  BOOST_CHECK_EQUAL(lY_g_, lengthY_g);\n  const auto lZ_g_ = L::lZ_g;\n  BOOST_CHECK_EQUAL(lZ_g_, 1);\n\n  const auto hX_ = L::hX;\n  BOOST_CHECK_EQUAL(hX_, 1);\n  const auto hY_ = L::hY;\n  BOOST_CHECK_EQUAL(hY_, 1);\n  const auto hZ_ = L::hZ;\n  BOOST_CHECK_EQUAL(hZ_, 0);\n\n  const auto inv_cs2_ = L::inv_cs2;\n  BOOST_CHECK_EQUAL(inv_cs2_, 3.0f);\n  const auto cs2_ = L::cs2;\n  BOOST_CHECK_EQUAL(cs2_, (1.0f/3.0f));\n\n  const auto w0_ = L::weight()[0];\n  BOOST_CHECK_EQUAL(w0_, 4.0f/6.0f);\n  const auto w1_ = L::weight()[1];\n  BOOST_CHECK_EQUAL(w1_, 1.0f/12.0f);\n  const auto w2_ = L::weight()[2];\n  BOOST_CHECK_EQUAL(w2_, 1.0f/12.0f);\n  const auto w3_ = L::weight()[3];\n  BOOST_CHECK_EQUAL(w3_, 1.0f/12.0f);\n  const auto w4_ = L::weight()[4];\n  BOOST_CHECK_EQUAL(w4_, 1.0f/12.0f);\n\n  const auto c0_ = L::celerity()[0];\n  const auto c0_r = MathVector<valueType, dimD_>{{0.0f, 0.0f}};\n  BOOST_CHECK_EQUAL(c0_, c0_r);\n  const auto c1_ = L::celerity()[1];\n  const auto c1_r = MathVector<valueType, dimD_>{{-1.0f, 0.0f}};\n  BOOST_CHECK_EQUAL(c1_, c1_r);\n  const auto c2_ = L::celerity()[2];\n  const auto c2_r = MathVector<valueType, dimD_>{{0.0f, -1.0f}};\n  BOOST_CHECK_EQUAL(c2_, c2_r);\n  const auto c3_ = L::celerity()[3];\n  const auto c3_r = MathVector<valueType, dimD_>{{1.0f, 0.0f}};\n  BOOST_CHECK_EQUAL(c3_, c3_r);\n  const auto c4_ = L::celerity()[4];\n  const auto c4_r = MathVector<valueType, dimD_>{{0.0f, 1.0f}};\n  BOOST_CHECK_EQUAL(c4_, c4_r);\n\n  const auto c0_0_ = L::celerity()[0][0];\n  BOOST_CHECK_EQUAL(c0_0_, 0.0f);\n  const auto c0_1_ = L::celerity()[0][1];\n  BOOST_CHECK_EQUAL(c0_1_, 0.0f);\n\n  const auto c1_0_ = L::celerity()[1][0];\n  BOOST_CHECK_EQUAL(c1_0_, -1.0f);\n  const auto c1_1_ = L::celerity()[1][1];\n  BOOST_CHECK_EQUAL(c1_1_, 0.0f);\n\n  const auto c2_0_ = L::celerity()[2][0];\n  BOOST_CHECK_EQUAL(c2_0_, 0.0f);\n  const auto c2_1_ = L::celerity()[2][1];\n  BOOST_CHECK_EQUAL(c2_1_, -1.0f);\n\n  const auto c3_0_ = L::celerity()[3][0];\n  BOOST_CHECK_EQUAL(c3_0_, 1.0f);\n  const auto c3_1_ = L::celerity()[3][1];\n  BOOST_CHECK_EQUAL(c3_1_, 0.0f);\n\n  const auto c4_0_ = L::celerity()[4][0];\n  BOOST_CHECK_EQUAL(c4_0_, 0.0f);\n  const auto c4_1_ = L::celerity()[4][1];\n  BOOST_CHECK_EQUAL(c4_1_, 1.0f);\n}\n\nBOOST_AUTO_TEST_CASE(TestIsotropyD2Q9) {\n  constexpr LatticeType latticeType = LatticeType::D2Q9;\n  typedef double valueType;\n  typedef Lattice<valueType, latticeType> L;\n\n  valueType sumWeight = 0.0;\n  valueType sumWeight_r = 1.0;\n\n  MathVector<valueType, L::dimD> sumWeightCelerity{{0.0}};\n  MathVector<valueType, L::dimD> sumWeightCelerity_r{{0.0}};\n\n  MathVector<valueType, L::dimD*L::dimD> sumWeight2Celerity{{0.0}};\n  MathVector<valueType, L::dimD*L::dimD> sumWeight2Celerity_r{{0.0}};\n\n  MathVector<valueType, L::dimD*L::dimD*L::dimD> sumWeight3Celerity{{0.0}};\n  MathVector<valueType, L::dimD*L::dimD*L::dimD> sumWeight3Celerity_r{{0.0}};\n\n  MathVector<valueType, L::dimD*L::dimD*L::dimD*L::dimD> sumWeight4Celerity{{0.0}};\n  MathVector<valueType, L::dimD*L::dimD*L::dimD*L::dimD> sumWeight4Celerity_r{{0.0}};\n\n  MathVector<valueType, L::dimD*L::dimD*L::dimD*L::dimD*L::dimD> sumWeight5Celerity{{0.0}};\n  MathVector<valueType, L::dimD*L::dimD*L::dimD*L::dimD*L::dimD> sumWeight5Celerity_r{{0.0}};\n\n\n  for(int iQ = 0; iQ < L::dimQ; ++iQ) {\n    sumWeight += L::weight()[iQ];\n\n    for(int d_a = 0; d_a < L::dimD; ++d_a) {\n      int idx_a = d_a;\n      sumWeightCelerity[idx_a] += L::weight()[iQ]*L::celerity()[iQ][d_a];\n\n      for(int d_b = 0; d_b < L::dimD; ++d_b) {\n        int idx_b = L::dimD * idx_a + d_b;\n        sumWeight2Celerity[idx_b] += L::weight()[iQ]*L::celerity()[iQ][d_a]*L::celerity()[iQ][d_b];\n\n        if(d_a == d_b) {\n          sumWeight2Celerity_r[idx_b] = L::cs2;\n        }\n\n        for(int d_c = 0; d_c < L::dimD; ++d_c) {\n          int idx_c = L::dimD * idx_b + d_c;\n          sumWeight3Celerity[idx_c] += L::weight()[iQ]*L::celerity()[iQ][d_a]\n            *L::celerity()[iQ][d_b]*L::celerity()[iQ][d_c];\n\n          for(int d_d = 0; d_d < L::dimD; ++d_d) {\n            int idx_d = L::dimD * idx_c + d_d;\n            sumWeight4Celerity[idx_d] += L::weight()[iQ]*L::celerity()[iQ][d_a]\n              *L::celerity()[iQ][d_b]*L::celerity()[iQ][d_c]*L::celerity()[iQ][d_d];\n\n            if((d_a == d_b && d_c == d_d)\n               && (d_a == d_c && d_b == d_d)\n               && (d_a == d_d && d_b == d_c)) {\n              sumWeight4Celerity_r[idx_d] = 3.0*L::cs2*L::cs2;\n            }\n            else if(((d_a == d_b && d_c == d_d) && (d_a == d_c && d_b == d_d))\n                    || ((d_a == d_b && d_c == d_d) && (d_a == d_d && d_b == d_d))\n                    || ((d_a == d_d && d_b == d_c) && (d_a == d_d && d_b == d_d))) {\n              sumWeight4Celerity_r[idx_d] = 2.0*L::cs2*L::cs2;\n            }\n            else if((d_a == d_b && d_c == d_d)\n                    || (d_a == d_c && d_b == d_d)\n                    || (d_a == d_d && d_b == d_c)) {\n              sumWeight4Celerity_r[idx_d] = 1.0*L::cs2*L::cs2;\n            }\n\n            for(int d_e = 0; d_e < L::dimD; ++d_e) {\n              int idx_e = L::dimD * idx_d + d_e;\n              sumWeight5Celerity[idx_e] += L::weight()[iQ]*L::celerity()[iQ][d_a]\n                *L::celerity()[iQ][d_b]*L::celerity()[iQ][d_c]*L::celerity()[iQ][d_d]\n                *L::celerity()[iQ][d_e];\n            }\n          }\n        }\n      }\n    }\n  }\n\n  BOOST_TEST(sumWeight == sumWeight_r, tt::tolerance(1e-15));\n  for(int i = 0; i < L::dimD; ++i) {\n    BOOST_TEST(sumWeightCelerity[i] == sumWeightCelerity_r[i], tt::tolerance(1e-15));\n  }\n  for(int i = 0; i < L::dimD*L::dimD; ++i) {\n    BOOST_TEST(sumWeight2Celerity[i] == sumWeight2Celerity_r[i], tt::tolerance(1e-15));\n  }\n  for(int i = 0; i < L::dimD*L::dimD*L::dimD; ++i) {\n    BOOST_TEST(sumWeight3Celerity[i] == sumWeight3Celerity_r[i], tt::tolerance(1e-15));\n  }\n  for(int i = 0; i < L::dimD*L::dimD*L::dimD*L::dimD; ++i) {\n    BOOST_TEST(sumWeight4Celerity[i] == sumWeight4Celerity_r[i], tt::tolerance(1e-15));\n  }\n  for(int i = 0; i < L::dimD*L::dimD*L::dimD*L::dimD*L::dimD; ++i) {\n    BOOST_TEST(sumWeight5Celerity[i] == sumWeight5Celerity_r[i], tt::tolerance(1e-15));\n  }\n}\n\nBOOST_AUTO_TEST_CASE(TestDoubleD2Q9) {\n  constexpr LatticeType latticeType = LatticeType::D2Q9;\n  typedef double valueType;\n\n  typedef Lattice<valueType, latticeType> L;\n\n  const auto dimD_ = L::dimD;\n  BOOST_CHECK_EQUAL(dimD_, 2);\n  const auto dimQ_ = L::dimQ;\n  BOOST_CHECK_EQUAL(dimQ_, 9);\n\n  const auto lX_g_ = L::lX_g;\n  BOOST_CHECK_EQUAL(lX_g_, lengthX_g);\n  const auto lY_g_ = L::lY_g;\n  BOOST_CHECK_EQUAL(lY_g_, lengthY_g);\n  const auto lZ_g_ = L::lZ_g;\n  BOOST_CHECK_EQUAL(lZ_g_, 1);\n\n  const auto hX_ = L::hX;\n  BOOST_CHECK_EQUAL(hX_, 1);\n  const auto hY_ = L::hY;\n  BOOST_CHECK_EQUAL(hY_, 1);\n  const auto hZ_ = L::hZ;\n  BOOST_CHECK_EQUAL(hZ_, 0);\n\n  const auto inv_cs2_ = L::inv_cs2;\n  BOOST_CHECK_EQUAL(inv_cs2_, (3.0));\n  const auto cs2_ = L::cs2;\n  BOOST_CHECK_EQUAL(cs2_, (1.0/3.0));\n\n  const auto w0_ = L::weight()[0];\n  BOOST_CHECK_EQUAL(w0_, 4.0/9.0);\n  const auto w1_ = L::weight()[1];\n  BOOST_CHECK_EQUAL(w1_, 1.0/36.0);\n  const auto w2_ = L::weight()[2];\n  BOOST_CHECK_EQUAL(w2_, 1.0/9.0);\n  const auto w3_ = L::weight()[3];\n  BOOST_CHECK_EQUAL(w3_, 1.0/36.0);\n  const auto w4_ = L::weight()[4];\n  BOOST_CHECK_EQUAL(w4_, 1.0/9.0);\n  const auto w5_ = L::weight()[5];\n  BOOST_CHECK_EQUAL(w5_, 1.0/36.0);\n  const auto w6_ = L::weight()[6];\n  BOOST_CHECK_EQUAL(w6_, 1.0/9.0);\n  const auto w7_ = L::weight()[7];\n  BOOST_CHECK_EQUAL(w7_, 1.0/36.0);\n  const auto w8_ = L::weight()[8];\n  BOOST_CHECK_EQUAL(w8_, 1.0/9.0);\n\n  const auto c0_ = L::celerity()[0];\n  const auto c0_r = MathVector<valueType, dimD_>{{0.0, 0.0}};\n  BOOST_CHECK_EQUAL(c0_, c0_r);\n  const auto c1_ = L::celerity()[1];\n  const auto c1_r = MathVector<valueType, dimD_>{{-1.0, 1.0}};\n  BOOST_CHECK_EQUAL(c1_, c1_r);\n  const auto c2_ = L::celerity()[2];\n  const auto c2_r = MathVector<valueType, dimD_>{{-1.0, 0.0}};\n  BOOST_CHECK_EQUAL(c2_, c2_r);\n  const auto c3_ = L::celerity()[3];\n  const auto c3_r = MathVector<valueType, dimD_>{{-1.0, -1.0}};\n  BOOST_CHECK_EQUAL(c3_, c3_r);\n  const auto c4_ = L::celerity()[4];\n  const auto c4_r = MathVector<valueType, dimD_>{{0.0, -1.0}};\n  BOOST_CHECK_EQUAL(c4_, c4_r);\n  const auto c5_ = L::celerity()[5];\n  const auto c5_r = MathVector<valueType, dimD_>{{1.0, -1.0}};\n  BOOST_CHECK_EQUAL(c5_, c5_r);\n  const auto c6_ = L::celerity()[6];\n  const auto c6_r = MathVector<valueType, dimD_>{{1.0, 0.0}};\n  BOOST_CHECK_EQUAL(c6_, c6_r);\n  const auto c7_ = L::celerity()[7];\n  const auto c7_r = MathVector<valueType, dimD_>{{1.0, 1.0}};\n  BOOST_CHECK_EQUAL(c7_, c7_r);\n  const auto c8_ = L::celerity()[8];\n  const auto c8_r = MathVector<valueType, dimD_>{{0.0, 1.0}};\n  BOOST_CHECK_EQUAL(c8_, c8_r);\n\n  const auto c0_0_ = L::celerity()[0][0];\n  BOOST_CHECK_EQUAL(c0_0_, 0.0);\n  const auto c0_1_ = L::celerity()[0][1];\n  BOOST_CHECK_EQUAL(c0_1_, 0.0);\n\n  const auto c1_0_ = L::celerity()[1][0];\n  BOOST_CHECK_EQUAL(c1_0_, -1.0);\n  const auto c1_1_ = L::celerity()[1][1];\n  BOOST_CHECK_EQUAL(c1_1_, 1.0);\n\n  const auto c2_0_ = L::celerity()[2][0];\n  BOOST_CHECK_EQUAL(c2_0_, -1.0);\n  const auto c2_1_ = L::celerity()[2][1];\n  BOOST_CHECK_EQUAL(c2_1_, 0.0);\n\n  const auto c3_0_ = L::celerity()[3][0];\n  BOOST_CHECK_EQUAL(c3_0_, -1.0);\n  const auto c3_1_ = L::celerity()[3][1];\n  BOOST_CHECK_EQUAL(c3_1_, -1.0);\n\n  const auto c4_0_ = L::celerity()[4][0];\n  BOOST_CHECK_EQUAL(c4_0_, 0.0);\n  const auto c4_1_ = L::celerity()[4][1];\n  BOOST_CHECK_EQUAL(c4_1_, -1.0);\n\n  const auto c5_0_ = L::celerity()[5][0];\n  BOOST_CHECK_EQUAL(c5_0_, 1.0);\n  const auto c5_1_ = L::celerity()[5][1];\n  BOOST_CHECK_EQUAL(c5_1_, -1.0);\n\n  const auto c6_0_ = L::celerity()[6][0];\n  BOOST_CHECK_EQUAL(c6_0_, 1.0);\n  const auto c6_1_ = L::celerity()[6][1];\n  BOOST_CHECK_EQUAL(c6_1_, 0.0);\n\n  const auto c7_0_ = L::celerity()[7][0];\n  BOOST_CHECK_EQUAL(c7_0_, 1.0);\n  const auto c7_1_ = L::celerity()[7][1];\n  BOOST_CHECK_EQUAL(c7_1_, 1.0);\n\n  const auto c8_0_ = L::celerity()[8][0];\n  BOOST_CHECK_EQUAL(c8_0_, 0.0);\n  const auto c8_1_ = L::celerity()[8][1];\n  BOOST_CHECK_EQUAL(c8_1_, 1.0);\n}\n\nBOOST_AUTO_TEST_CASE(TestFloatD2Q9) {\n  constexpr LatticeType latticeType = LatticeType::D2Q9;\n  typedef float valueType;\n\n  typedef Lattice<valueType, latticeType> L;\n\n  const auto dimD_ = L::dimD;\n  BOOST_CHECK_EQUAL(dimD_, 2);\n  const auto dimQ_ = L::dimQ;\n  BOOST_CHECK_EQUAL(dimQ_, 9);\n\n  const auto lX_g_ = L::lX_g;\n  BOOST_CHECK_EQUAL(lX_g_, lengthX_g);\n  const auto lY_g_ = L::lY_g;\n  BOOST_CHECK_EQUAL(lY_g_, lengthY_g);\n  const auto lZ_g_ = L::lZ_g;\n  BOOST_CHECK_EQUAL(lZ_g_, 1);\n\n  const auto hX_ = L::hX;\n  BOOST_CHECK_EQUAL(hX_, 1);\n  const auto hY_ = L::hY;\n  BOOST_CHECK_EQUAL(hY_, 1);\n  const auto hZ_ = L::hZ;\n  BOOST_CHECK_EQUAL(hZ_, 0);\n\n  const auto inv_cs2_ = L::inv_cs2;\n  BOOST_CHECK_EQUAL(inv_cs2_, (3.0f));\n  const auto cs2_ = L::cs2;\n  BOOST_CHECK_EQUAL(cs2_, (1.0f/3.0f));\n\n  const auto w0_ = L::weight()[0];\n  BOOST_CHECK_EQUAL(w0_, 4.0f/9.0f);\n  const auto w1_ = L::weight()[1];\n  BOOST_CHECK_EQUAL(w1_, 1.0f/36.0f);\n  const auto w2_ = L::weight()[2];\n  BOOST_CHECK_EQUAL(w2_, 1.0f/9.0f);\n  const auto w3_ = L::weight()[3];\n  BOOST_CHECK_EQUAL(w3_, 1.0f/36.0f);\n  const auto w4_ = L::weight()[4];\n  BOOST_CHECK_EQUAL(w4_, 1.0f/9.0f);\n  const auto w5_ = L::weight()[5];\n  BOOST_CHECK_EQUAL(w5_, 1.0f/36.0f);\n  const auto w6_ = L::weight()[6];\n  BOOST_CHECK_EQUAL(w6_, 1.0f/9.0f);\n  const auto w7_ = L::weight()[7];\n  BOOST_CHECK_EQUAL(w7_, 1.0f/36.0f);\n  const auto w8_ = L::weight()[8];\n  BOOST_CHECK_EQUAL(w8_, 1.0f/9.0f);\n\n  const auto c0_ = L::celerity()[0];\n  const auto c0_r = MathVector<valueType, dimD_>{{0.0f, 0.0f}};\n  BOOST_CHECK_EQUAL(c0_, c0_r);\n  const auto c1_ = L::celerity()[1];\n  const auto c1_r = MathVector<valueType, dimD_>{{-1.0f, 1.0f}};\n  BOOST_CHECK_EQUAL(c1_, c1_r);\n  const auto c2_ = L::celerity()[2];\n  const auto c2_r = MathVector<valueType, dimD_>{{-1.0f, 0.0f}};\n  BOOST_CHECK_EQUAL(c2_, c2_r);\n  const auto c3_ = L::celerity()[3];\n  const auto c3_r = MathVector<valueType, dimD_>{{-1.0f, -1.0f}};\n  BOOST_CHECK_EQUAL(c3_, c3_r);\n  const auto c4_ = L::celerity()[4];\n  const auto c4_r = MathVector<valueType, dimD_>{{0.0f, -1.0f}};\n  BOOST_CHECK_EQUAL(c4_, c4_r);\n  const auto c5_ = L::celerity()[5];\n  const auto c5_r = MathVector<valueType, dimD_>{{1.0f, -1.0f}};\n  BOOST_CHECK_EQUAL(c5_, c5_r);\n  const auto c6_ = L::celerity()[6];\n  const auto c6_r = MathVector<valueType, dimD_>{{1.0f, 0.0f}};\n  BOOST_CHECK_EQUAL(c6_, c6_r);\n  const auto c7_ = L::celerity()[7];\n  const auto c7_r = MathVector<valueType, dimD_>{{1.0f, 1.0f}};\n  BOOST_CHECK_EQUAL(c7_, c7_r);\n  const auto c8_ = L::celerity()[8];\n  const auto c8_r = MathVector<valueType, dimD_>{{0.0f, 1.0f}};\n  BOOST_CHECK_EQUAL(c8_, c8_r);\n\n  const auto c0_0_ = L::celerity()[0][0];\n  BOOST_CHECK_EQUAL(c0_0_, 0.0f);\n  const auto c0_1_ = L::celerity()[0][1];\n  BOOST_CHECK_EQUAL(c0_1_, 0.0f);\n\n  const auto c1_0_ = L::celerity()[1][0];\n  BOOST_CHECK_EQUAL(c1_0_, -1.0f);\n  const auto c1_1_ = L::celerity()[1][1];\n  BOOST_CHECK_EQUAL(c1_1_, 1.0f);\n\n  const auto c2_0_ = L::celerity()[2][0];\n  BOOST_CHECK_EQUAL(c2_0_, -1.0f);\n  const auto c2_1_ = L::celerity()[2][1];\n  BOOST_CHECK_EQUAL(c2_1_, 0.0f);\n\n  const auto c3_0_ = L::celerity()[3][0];\n  BOOST_CHECK_EQUAL(c3_0_, -1.0f);\n  const auto c3_1_ = L::celerity()[3][1];\n  BOOST_CHECK_EQUAL(c3_1_, -1.0f);\n\n  const auto c4_0_ = L::celerity()[4][0];\n  BOOST_CHECK_EQUAL(c4_0_, 0.0f);\n  const auto c4_1_ = L::celerity()[4][1];\n  BOOST_CHECK_EQUAL(c4_1_, -1.0f);\n\n  const auto c5_0_ = L::celerity()[5][0];\n  BOOST_CHECK_EQUAL(c5_0_, 1.0f);\n  const auto c5_1_ = L::celerity()[5][1];\n  BOOST_CHECK_EQUAL(c5_1_, -1.0f);\n\n  const auto c6_0_ = L::celerity()[6][0];\n  BOOST_CHECK_EQUAL(c6_0_, 1.0f);\n  const auto c6_1_ = L::celerity()[6][1];\n  BOOST_CHECK_EQUAL(c6_1_, 0.0f);\n\n  const auto c7_0_ = L::celerity()[7][0];\n  BOOST_CHECK_EQUAL(c7_0_, 1.0f);\n  const auto c7_1_ = L::celerity()[7][1];\n  BOOST_CHECK_EQUAL(c7_1_, 1.0f);\n\n  const auto c8_0_ = L::celerity()[8][0];\n  BOOST_CHECK_EQUAL(c8_0_, 0.0f);\n  const auto c8_1_ = L::celerity()[8][1];\n  BOOST_CHECK_EQUAL(c8_1_, 1.0f);\n}\n\nBOOST_AUTO_TEST_CASE(TestIsotropyD3Q15) {\n  constexpr LatticeType latticeType = LatticeType::D3Q15;\n  typedef double valueType;\n  typedef Lattice<valueType, latticeType> L;\n\n  valueType sumWeight = 0.0;\n  valueType sumWeight_r = 1.0;\n\n  MathVector<valueType, L::dimD> sumWeightCelerity{{0.0}};\n  MathVector<valueType, L::dimD> sumWeightCelerity_r{{0.0}};\n\n  MathVector<valueType, L::dimD*L::dimD> sumWeight2Celerity{{0.0}};\n  MathVector<valueType, L::dimD*L::dimD> sumWeight2Celerity_r{{0.0}};\n\n  MathVector<valueType, L::dimD*L::dimD*L::dimD> sumWeight3Celerity{{0.0}};\n  MathVector<valueType, L::dimD*L::dimD*L::dimD> sumWeight3Celerity_r{{0.0}};\n\n  MathVector<valueType, L::dimD*L::dimD*L::dimD*L::dimD> sumWeight4Celerity{{0.0}};\n  MathVector<valueType, L::dimD*L::dimD*L::dimD*L::dimD> sumWeight4Celerity_r{{0.0}};\n\n  MathVector<valueType, L::dimD*L::dimD*L::dimD*L::dimD*L::dimD> sumWeight5Celerity{{0.0}};\n  MathVector<valueType, L::dimD*L::dimD*L::dimD*L::dimD*L::dimD> sumWeight5Celerity_r{{0.0}};\n\n\n  for(int iQ = 0; iQ < L::dimQ; ++iQ) {\n    sumWeight += L::weight()[iQ];\n\n    for(int d_a = 0; d_a < L::dimD; ++d_a) {\n      int idx_a = d_a;\n      sumWeightCelerity[idx_a] += L::weight()[iQ]*L::celerity()[iQ][d_a];\n\n      for(int d_b = 0; d_b < L::dimD; ++d_b) {\n        int idx_b = L::dimD * idx_a + d_b;\n        sumWeight2Celerity[idx_b] += L::weight()[iQ]*L::celerity()[iQ][d_a]*L::celerity()[iQ][d_b];\n\n        if(d_a == d_b) {\n          sumWeight2Celerity_r[idx_b] = L::cs2;\n        }\n\n        for(int d_c = 0; d_c < L::dimD; ++d_c) {\n          int idx_c = L::dimD * idx_b + d_c;\n          sumWeight3Celerity[idx_c] += L::weight()[iQ]*L::celerity()[iQ][d_a]\n            *L::celerity()[iQ][d_b]*L::celerity()[iQ][d_c];\n\n          for(int d_d = 0; d_d < L::dimD; ++d_d) {\n            int idx_d = L::dimD * idx_c + d_d;\n            sumWeight4Celerity[idx_d] += L::weight()[iQ]*L::celerity()[iQ][d_a]\n              *L::celerity()[iQ][d_b]*L::celerity()[iQ][d_c]*L::celerity()[iQ][d_d];\n\n            if((d_a == d_b && d_c == d_d)\n               && (d_a == d_c && d_b == d_d)\n               && (d_a == d_d && d_b == d_c)) {\n              sumWeight4Celerity_r[idx_d] = 3.0*L::cs2*L::cs2;\n            }\n            else if(((d_a == d_b && d_c == d_d) && (d_a == d_c && d_b == d_d))\n                    || ((d_a == d_b && d_c == d_d) && (d_a == d_d && d_b == d_d))\n                    || ((d_a == d_d && d_b == d_c) && (d_a == d_d && d_b == d_d))) {\n              sumWeight4Celerity_r[idx_d] = 2.0*L::cs2*L::cs2;\n            }\n            else if((d_a == d_b && d_c == d_d)\n                    || (d_a == d_c && d_b == d_d)\n                    || (d_a == d_d && d_b == d_c)) {\n              sumWeight4Celerity_r[idx_d] = 1.0*L::cs2*L::cs2;\n            }\n\n            for(int d_e = 0; d_e < L::dimD; ++d_e) {\n              int idx_e = L::dimD * idx_d + d_e;\n              sumWeight5Celerity[idx_e] += L::weight()[iQ]*L::celerity()[iQ][d_a]\n                *L::celerity()[iQ][d_b]*L::celerity()[iQ][d_c]*L::celerity()[iQ][d_d]\n                *L::celerity()[iQ][d_e];\n            }\n          }\n        }\n      }\n    }\n  }\n\n  BOOST_TEST(sumWeight == sumWeight_r, tt::tolerance(1e-15));\n  for(int i = 0; i < L::dimD; ++i) {\n    BOOST_TEST(sumWeightCelerity[i] == sumWeightCelerity_r[i], tt::tolerance(1e-15));\n  }\n  for(int i = 0; i < L::dimD*L::dimD; ++i) {\n    BOOST_TEST(sumWeight2Celerity[i] == sumWeight2Celerity_r[i], tt::tolerance(1e-15));\n  }\n  for(int i = 0; i < L::dimD*L::dimD*L::dimD; ++i) {\n    BOOST_TEST(sumWeight3Celerity[i] == sumWeight3Celerity_r[i], tt::tolerance(1e-15));\n  }\n  for(int i = 0; i < L::dimD*L::dimD*L::dimD*L::dimD; ++i) {\n    BOOST_TEST(sumWeight4Celerity[i] == sumWeight4Celerity_r[i], tt::tolerance(1e-15));\n  }\n  for(int i = 0; i < L::dimD*L::dimD*L::dimD*L::dimD*L::dimD; ++i) {\n    BOOST_TEST(sumWeight5Celerity[i] == sumWeight5Celerity_r[i], tt::tolerance(1e-15));\n  }\n}\n\n\nBOOST_AUTO_TEST_CASE(TestDoubleD3Q15) {\n  constexpr LatticeType latticeType = LatticeType::D3Q15;\n  typedef double valueType;\n\n  typedef Lattice<valueType, latticeType> L;\n\n  const auto dimD_ = L::dimD;\n  BOOST_CHECK_EQUAL(dimD_, 3);\n  const auto dimQ_ = L::dimQ;\n  BOOST_CHECK_EQUAL(dimQ_, 15);\n\n  const auto lX_g_ = L::lX_g;\n  BOOST_CHECK_EQUAL(lX_g_, lengthX_g);\n  const auto lY_g_ = L::lY_g;\n  BOOST_CHECK_EQUAL(lY_g_, lengthY_g);\n  const auto lZ_g_ = L::lZ_g;\n  BOOST_CHECK_EQUAL(lZ_g_, lengthZ_g);\n\n  const auto hX_ = L::hX;\n  BOOST_CHECK_EQUAL(hX_, 1);\n  const auto hY_ = L::hY;\n  BOOST_CHECK_EQUAL(hY_, 1);\n  const auto hZ_ = L::hZ;\n  BOOST_CHECK_EQUAL(hZ_, 1);\n\n  const auto inv_cs2_ = L::inv_cs2;\n  BOOST_CHECK_EQUAL(inv_cs2_, (3.0));\n  const auto cs2_ = L::cs2;\n  BOOST_CHECK_EQUAL(cs2_, (1.0/3.0));\n\n  const auto w0_ = L::weight()[0];\n  BOOST_CHECK_EQUAL(w0_, 2.0/9.0);\n  const auto w1_ = L::weight()[1];\n  BOOST_CHECK_EQUAL(w1_, 1.0/9.0);\n  const auto w2_ = L::weight()[2];\n  BOOST_CHECK_EQUAL(w2_, 1.0/9.0);\n  const auto w3_ = L::weight()[3];\n  BOOST_CHECK_EQUAL(w3_, 1.0/9.0);\n  const auto w4_ = L::weight()[4];\n  BOOST_CHECK_EQUAL(w4_, 1.0/72.0);\n  const auto w5_ = L::weight()[5];\n  BOOST_CHECK_EQUAL(w5_, 1.0/72.0);\n  const auto w6_ = L::weight()[6];\n  BOOST_CHECK_EQUAL(w6_, 1.0/72.0);\n  const auto w7_ = L::weight()[7];\n  BOOST_CHECK_EQUAL(w7_, 1.0/72.0);\n  const auto w8_ = L::weight()[8];\n  BOOST_CHECK_EQUAL(w8_, 1.0/9.0);\n  const auto w9_ = L::weight()[9];\n  BOOST_CHECK_EQUAL(w9_, 1.0/9.0);\n  const auto w10_ = L::weight()[10];\n  BOOST_CHECK_EQUAL(w10_, 1.0/9.0);\n  const auto w11_ = L::weight()[11];\n  BOOST_CHECK_EQUAL(w11_, 1.0/72.0);\n  const auto w12_ = L::weight()[12];\n  BOOST_CHECK_EQUAL(w12_, 1.0/72.0);\n  const auto w13_ = L::weight()[13];\n  BOOST_CHECK_EQUAL(w13_, 1.0/72.0);\n  const auto w14_ = L::weight()[14];\n  BOOST_CHECK_EQUAL(w14_, 1.0/72.0);\n\n  const auto c0_ = L::celerity()[0];\n  const auto c0_r = MathVector<valueType, dimD_>{{0.0, 0.0, 0.0}};\n  BOOST_CHECK_EQUAL(c0_, c0_r);\n  const auto c1_ = L::celerity()[1];\n  const auto c1_r = MathVector<valueType, dimD_>{{-1.0, 0.0, 0.0}};\n  BOOST_CHECK_EQUAL(c1_, c1_r);\n  const auto c2_ = L::celerity()[2];\n  const auto c2_r = MathVector<valueType, dimD_>{{0.0, -1.0, 0.0}};\n  BOOST_CHECK_EQUAL(c2_, c2_r);\n  const auto c3_ = L::celerity()[3];\n  const auto c3_r = MathVector<valueType, dimD_>{{0.0, 0.0, -1.0}};\n  BOOST_CHECK_EQUAL(c3_, c3_r);\n  const auto c4_ = L::celerity()[4];\n  const auto c4_r = MathVector<valueType, dimD_>{{-1.0, -1.0, -1.0}};\n  BOOST_CHECK_EQUAL(c4_, c4_r);\n  const auto c5_ = L::celerity()[5];\n  const auto c5_r = MathVector<valueType, dimD_>{{-1.0, -1.0, 1.0}};\n  BOOST_CHECK_EQUAL(c5_, c5_r);\n  const auto c6_ = L::celerity()[6];\n  const auto c6_r = MathVector<valueType, dimD_>{{-1.0, 1.0, -1.0}};\n  BOOST_CHECK_EQUAL(c6_, c6_r);\n  const auto c7_ = L::celerity()[7];\n  const auto c7_r = MathVector<valueType, dimD_>{{-1.0, 1.0, 1.0}};\n  BOOST_CHECK_EQUAL(c7_, c7_r);\n  const auto c8_ = L::celerity()[8];\n  const auto c8_r = MathVector<valueType, dimD_>{{1.0, 0.0, 0.0}};\n  BOOST_CHECK_EQUAL(c8_, c8_r);\n  const auto c9_ = L::celerity()[9];\n  const auto c9_r = MathVector<valueType, dimD_>{{0.0, 1.0, 0.0}};\n  BOOST_CHECK_EQUAL(c9_, c9_r);\n  const auto c10_ = L::celerity()[10];\n  const auto c10_r = MathVector<valueType, dimD_>{{0.0, 0.0, 1.0}};\n  BOOST_CHECK_EQUAL(c10_, c10_r);\n  const auto c11_ = L::celerity()[11];\n  const auto c11_r = MathVector<valueType, dimD_>{{1.0, 1.0, 1.0}};\n  BOOST_CHECK_EQUAL(c11_, c11_r);\n  const auto c12_ = L::celerity()[12];\n  const auto c12_r = MathVector<valueType, dimD_>{{1.0, 1.0, -1.0}};\n  BOOST_CHECK_EQUAL(c12_, c12_r);\n  const auto c13_ = L::celerity()[13];\n  const auto c13_r = MathVector<valueType, dimD_>{{1.0, -1.0, 1.0}};\n  BOOST_CHECK_EQUAL(c13_, c13_r);\n  const auto c14_ = L::celerity()[14];\n  const auto c14_r = MathVector<valueType, dimD_>{{1.0, -1.0, -1.0}};\n  BOOST_CHECK_EQUAL(c14_, c14_r);\n\n  const auto c0_0_ = L::celerity()[0][0];\n  BOOST_CHECK_EQUAL(c0_0_, 0.0);\n  const auto c0_1_ = L::celerity()[0][1];\n  BOOST_CHECK_EQUAL(c0_1_, 0.0);\n  const auto c0_2_ = L::celerity()[0][1];\n  BOOST_CHECK_EQUAL(c0_2_, 0.0);\n\n  const auto c1_0_ = L::celerity()[1][0];\n  BOOST_CHECK_EQUAL(c1_0_, -1.0);\n  const auto c1_1_ = L::celerity()[1][1];\n  BOOST_CHECK_EQUAL(c1_1_, 0.0);\n  const auto c1_2_ = L::celerity()[1][2];\n  BOOST_CHECK_EQUAL(c1_2_, 0.0);\n\n  const auto c2_0_ = L::celerity()[2][0];\n  BOOST_CHECK_EQUAL(c2_0_, 0.0);\n  const auto c2_1_ = L::celerity()[2][1];\n  BOOST_CHECK_EQUAL(c2_1_, -1.0);\n  const auto c2_2_ = L::celerity()[2][2];\n  BOOST_CHECK_EQUAL(c2_2_, 0.0);\n\n  const auto c3_0_ = L::celerity()[3][0];\n  BOOST_CHECK_EQUAL(c3_0_, 0.0);\n  const auto c3_1_ = L::celerity()[3][1];\n  BOOST_CHECK_EQUAL(c3_1_, 0.0);\n  const auto c3_2_ = L::celerity()[3][2];\n  BOOST_CHECK_EQUAL(c3_2_, -1.0);\n\n  const auto c4_0_ = L::celerity()[4][0];\n  BOOST_CHECK_EQUAL(c4_0_, -1.0);\n  const auto c4_1_ = L::celerity()[4][1];\n  BOOST_CHECK_EQUAL(c4_1_, -1.0);\n  const auto c4_2_ = L::celerity()[4][2];\n  BOOST_CHECK_EQUAL(c4_2_, -1.0);\n\n  const auto c5_0_ = L::celerity()[5][0];\n  BOOST_CHECK_EQUAL(c5_0_, -1.0);\n  const auto c5_1_ = L::celerity()[5][1];\n  BOOST_CHECK_EQUAL(c5_1_, -1.0);\n  const auto c5_2_ = L::celerity()[5][2];\n  BOOST_CHECK_EQUAL(c5_2_, 1.0);\n\n  const auto c6_0_ = L::celerity()[6][0];\n  BOOST_CHECK_EQUAL(c6_0_, -1.0);\n  const auto c6_1_ = L::celerity()[6][1];\n  BOOST_CHECK_EQUAL(c6_1_, 1.0);\n  const auto c6_2_ = L::celerity()[6][2];\n  BOOST_CHECK_EQUAL(c6_2_, -1.0);\n\n  const auto c7_0_ = L::celerity()[7][0];\n  BOOST_CHECK_EQUAL(c7_0_, -1.0);\n  const auto c7_1_ = L::celerity()[7][1];\n  BOOST_CHECK_EQUAL(c7_1_, 1.0);\n  const auto c7_2_ = L::celerity()[7][2];\n  BOOST_CHECK_EQUAL(c7_2_, 1.0);\n\n  const auto c8_0_ = L::celerity()[8][0];\n  BOOST_CHECK_EQUAL(c8_0_, 1.0);\n  const auto c8_1_ = L::celerity()[8][1];\n  BOOST_CHECK_EQUAL(c8_1_, 0.0);\n  const auto c8_2_ = L::celerity()[8][2];\n  BOOST_CHECK_EQUAL(c8_2_, 0.0);\n\n  const auto c9_0_ = L::celerity()[9][0];\n  BOOST_CHECK_EQUAL(c9_0_, 0.0);\n  const auto c9_1_ = L::celerity()[9][1];\n  BOOST_CHECK_EQUAL(c9_1_, 1.0);\n  const auto c9_2_ = L::celerity()[9][2];\n  BOOST_CHECK_EQUAL(c9_2_, 0.0);\n\n  const auto c10_0_ = L::celerity()[10][0];\n  BOOST_CHECK_EQUAL(c10_0_, 0.0);\n  const auto c10_1_ = L::celerity()[10][1];\n  BOOST_CHECK_EQUAL(c10_1_, 0.0);\n  const auto c10_2_ = L::celerity()[10][2];\n  BOOST_CHECK_EQUAL(c10_2_, 1.0);\n\n  const auto c11_0_ = L::celerity()[11][0];\n  BOOST_CHECK_EQUAL(c11_0_, 1.0);\n  const auto c11_1_ = L::celerity()[11][1];\n  BOOST_CHECK_EQUAL(c11_1_, 1.0);\n  const auto c11_2_ = L::celerity()[11][2];\n  BOOST_CHECK_EQUAL(c11_2_, 1.0);\n\n  const auto c12_0_ = L::celerity()[12][0];\n  BOOST_CHECK_EQUAL(c12_0_, 1.0);\n  const auto c12_1_ = L::celerity()[12][1];\n  BOOST_CHECK_EQUAL(c12_1_, 1.0);\n  const auto c12_2_ = L::celerity()[12][2];\n  BOOST_CHECK_EQUAL(c12_2_, -1.0);\n\n  const auto c13_0_ = L::celerity()[13][0];\n  BOOST_CHECK_EQUAL(c13_0_, 1.0);\n  const auto c13_1_ = L::celerity()[13][1];\n  BOOST_CHECK_EQUAL(c13_1_, -1.0);\n  const auto c13_2_ = L::celerity()[13][2];\n  BOOST_CHECK_EQUAL(c13_2_, 1.0);\n\n  const auto c14_0_ = L::celerity()[14][0];\n  BOOST_CHECK_EQUAL(c14_0_, 1.0);\n  const auto c14_1_ = L::celerity()[14][1];\n  BOOST_CHECK_EQUAL(c14_1_, -1.0);\n  const auto c14_2_ = L::celerity()[14][2];\n  BOOST_CHECK_EQUAL(c14_2_, -1.0);\n}\n\nBOOST_AUTO_TEST_CASE(TestFloatD3Q15) {\n  constexpr LatticeType latticeType = LatticeType::D3Q15;\n  typedef float valueType;\n\n  typedef Lattice<valueType, latticeType> L;\n\n  const auto dimD_ = L::dimD;\n  BOOST_CHECK_EQUAL(dimD_, 3);\n  const auto dimQ_ = L::dimQ;\n  BOOST_CHECK_EQUAL(dimQ_, 15);\n\n  const auto lX_g_ = L::lX_g;\n  BOOST_CHECK_EQUAL(lX_g_, lengthX_g);\n  const auto lY_g_ = L::lY_g;\n  BOOST_CHECK_EQUAL(lY_g_, lengthY_g);\n  const auto lZ_g_ = L::lZ_g;\n  BOOST_CHECK_EQUAL(lZ_g_, lengthZ_g);\n\n  const auto hX_ = L::hX;\n  BOOST_CHECK_EQUAL(hX_, 1);\n  const auto hY_ = L::hY;\n  BOOST_CHECK_EQUAL(hY_, 1);\n  const auto hZ_ = L::hZ;\n  BOOST_CHECK_EQUAL(hZ_, 1);\n\n  const auto inv_cs2_ = L::inv_cs2;\n  BOOST_CHECK_EQUAL(inv_cs2_, (3.0f));\n  const auto cs2_ = L::cs2;\n  BOOST_CHECK_EQUAL(cs2_, (1.0f/3.0f));\n\n  const auto w0_ = L::weight()[0];\n  BOOST_CHECK_EQUAL(w0_, 2.0f/9.0f);\n  const auto w1_ = L::weight()[1];\n  BOOST_CHECK_EQUAL(w1_, 1.0f/9.0f);\n  const auto w2_ = L::weight()[2];\n  BOOST_CHECK_EQUAL(w2_, 1.0f/9.0f);\n  const auto w3_ = L::weight()[3];\n  BOOST_CHECK_EQUAL(w3_, 1.0f/9.0f);\n  const auto w4_ = L::weight()[4];\n  BOOST_CHECK_EQUAL(w4_, 1.0f/72.0f);\n  const auto w5_ = L::weight()[5];\n  BOOST_CHECK_EQUAL(w5_, 1.0f/72.0f);\n  const auto w6_ = L::weight()[6];\n  BOOST_CHECK_EQUAL(w6_, 1.0f/72.0f);\n  const auto w7_ = L::weight()[7];\n  BOOST_CHECK_EQUAL(w7_, 1.0f/72.0f);\n  const auto w8_ = L::weight()[8];\n  BOOST_CHECK_EQUAL(w8_, 1.0f/9.0f);\n  const auto w9_ = L::weight()[9];\n  BOOST_CHECK_EQUAL(w9_, 1.0f/9.0f);\n  const auto w10_ = L::weight()[10];\n  BOOST_CHECK_EQUAL(w10_, 1.0f/9.0f);\n  const auto w11_ = L::weight()[11];\n  BOOST_CHECK_EQUAL(w11_, 1.0f/72.0f);\n  const auto w12_ = L::weight()[12];\n  BOOST_CHECK_EQUAL(w12_, 1.0f/72.0f);\n  const auto w13_ = L::weight()[13];\n  BOOST_CHECK_EQUAL(w13_, 1.0f/72.0f);\n  const auto w14_ = L::weight()[14];\n  BOOST_CHECK_EQUAL(w14_, 1.0f/72.0f);\n\n  const auto c0_ = L::celerity()[0];\n  const auto c0_r = MathVector<valueType, dimD_>{{0.0f, 0.0f, 0.0f}};\n  BOOST_CHECK_EQUAL(c0_, c0_r);\n  const auto c1_ = L::celerity()[1];\n  const auto c1_r = MathVector<valueType, dimD_>{{-1.0f, 0.0f, 0.0f}};\n  BOOST_CHECK_EQUAL(c1_, c1_r);\n  const auto c2_ = L::celerity()[2];\n  const auto c2_r = MathVector<valueType, dimD_>{{0.0f, -1.0f, 0.0f}};\n  BOOST_CHECK_EQUAL(c2_, c2_r);\n  const auto c3_ = L::celerity()[3];\n  const auto c3_r = MathVector<valueType, dimD_>{{0.0f, 0.0f, -1.0f}};\n  BOOST_CHECK_EQUAL(c3_, c3_r);\n  const auto c4_ = L::celerity()[4];\n  const auto c4_r = MathVector<valueType, dimD_>{{-1.0f, -1.0f, -1.0f}};\n  BOOST_CHECK_EQUAL(c4_, c4_r);\n  const auto c5_ = L::celerity()[5];\n  const auto c5_r = MathVector<valueType, dimD_>{{-1.0f, -1.0f, 1.0f}};\n  BOOST_CHECK_EQUAL(c5_, c5_r);\n  const auto c6_ = L::celerity()[6];\n  const auto c6_r = MathVector<valueType, dimD_>{{-1.0f, 1.0f, -1.0f}};\n  BOOST_CHECK_EQUAL(c6_, c6_r);\n  const auto c7_ = L::celerity()[7];\n  const auto c7_r = MathVector<valueType, dimD_>{{-1.0f, 1.0f, 1.0f}};\n  BOOST_CHECK_EQUAL(c7_, c7_r);\n  const auto c8_ = L::celerity()[8];\n  const auto c8_r = MathVector<valueType, dimD_>{{1.0f, 0.0f, 0.0f}};\n  BOOST_CHECK_EQUAL(c8_, c8_r);\n  const auto c9_ = L::celerity()[9];\n  const auto c9_r = MathVector<valueType, dimD_>{{0.0f, 1.0f, 0.0f}};\n  BOOST_CHECK_EQUAL(c9_, c9_r);\n  const auto c10_ = L::celerity()[10];\n  const auto c10_r = MathVector<valueType, dimD_>{{0.0f, 0.0f, 1.0f}};\n  BOOST_CHECK_EQUAL(c10_, c10_r);\n  const auto c11_ = L::celerity()[11];\n  const auto c11_r = MathVector<valueType, dimD_>{{1.0f, 1.0f, 1.0f}};\n  BOOST_CHECK_EQUAL(c11_, c11_r);\n  const auto c12_ = L::celerity()[12];\n  const auto c12_r = MathVector<valueType, dimD_>{{1.0f, 1.0f, -1.0f}};\n  BOOST_CHECK_EQUAL(c12_, c12_r);\n  const auto c13_ = L::celerity()[13];\n  const auto c13_r = MathVector<valueType, dimD_>{{1.0f, -1.0f, 1.0f}};\n  BOOST_CHECK_EQUAL(c13_, c13_r);\n  const auto c14_ = L::celerity()[14];\n  const auto c14_r = MathVector<valueType, dimD_>{{1.0f, -1.0f, -1.0f}};\n  BOOST_CHECK_EQUAL(c14_, c14_r);\n\n  const auto c0_0_ = L::celerity()[0][0];\n  BOOST_CHECK_EQUAL(c0_0_, 0.0f);\n  const auto c0_1_ = L::celerity()[0][1];\n  BOOST_CHECK_EQUAL(c0_1_, 0.0f);\n  const auto c0_2_ = L::celerity()[0][1];\n  BOOST_CHECK_EQUAL(c0_2_, 0.0f);\n\n  const auto c1_0_ = L::celerity()[1][0];\n  BOOST_CHECK_EQUAL(c1_0_, -1.0f);\n  const auto c1_1_ = L::celerity()[1][1];\n  BOOST_CHECK_EQUAL(c1_1_, 0.0f);\n  const auto c1_2_ = L::celerity()[1][2];\n  BOOST_CHECK_EQUAL(c1_2_, 0.0f);\n\n  const auto c2_0_ = L::celerity()[2][0];\n  BOOST_CHECK_EQUAL(c2_0_, 0.0f);\n  const auto c2_1_ = L::celerity()[2][1];\n  BOOST_CHECK_EQUAL(c2_1_, -1.0f);\n  const auto c2_2_ = L::celerity()[2][2];\n  BOOST_CHECK_EQUAL(c2_2_, 0.0f);\n\n  const auto c3_0_ = L::celerity()[3][0];\n  BOOST_CHECK_EQUAL(c3_0_, 0.0f);\n  const auto c3_1_ = L::celerity()[3][1];\n  BOOST_CHECK_EQUAL(c3_1_, 0.0f);\n  const auto c3_2_ = L::celerity()[3][2];\n  BOOST_CHECK_EQUAL(c3_2_, -1.0f);\n\n  const auto c4_0_ = L::celerity()[4][0];\n  BOOST_CHECK_EQUAL(c4_0_, -1.0f);\n  const auto c4_1_ = L::celerity()[4][1];\n  BOOST_CHECK_EQUAL(c4_1_, -1.0f);\n  const auto c4_2_ = L::celerity()[4][2];\n  BOOST_CHECK_EQUAL(c4_2_, -1.0f);\n\n  const auto c5_0_ = L::celerity()[5][0];\n  BOOST_CHECK_EQUAL(c5_0_, -1.0f);\n  const auto c5_1_ = L::celerity()[5][1];\n  BOOST_CHECK_EQUAL(c5_1_, -1.0f);\n  const auto c5_2_ = L::celerity()[5][2];\n  BOOST_CHECK_EQUAL(c5_2_, 1.0f);\n\n  const auto c6_0_ = L::celerity()[6][0];\n  BOOST_CHECK_EQUAL(c6_0_, -1.0f);\n  const auto c6_1_ = L::celerity()[6][1];\n  BOOST_CHECK_EQUAL(c6_1_, 1.0f);\n  const auto c6_2_ = L::celerity()[6][2];\n  BOOST_CHECK_EQUAL(c6_2_, -1.0f);\n\n  const auto c7_0_ = L::celerity()[7][0];\n  BOOST_CHECK_EQUAL(c7_0_, -1.0f);\n  const auto c7_1_ = L::celerity()[7][1];\n  BOOST_CHECK_EQUAL(c7_1_, 1.0f);\n  const auto c7_2_ = L::celerity()[7][2];\n  BOOST_CHECK_EQUAL(c7_2_, 1.0f);\n\n  const auto c8_0_ = L::celerity()[8][0];\n  BOOST_CHECK_EQUAL(c8_0_, 1.0f);\n  const auto c8_1_ = L::celerity()[8][1];\n  BOOST_CHECK_EQUAL(c8_1_, 0.0f);\n  const auto c8_2_ = L::celerity()[8][2];\n  BOOST_CHECK_EQUAL(c8_2_, 0.0f);\n\n  const auto c9_0_ = L::celerity()[9][0];\n  BOOST_CHECK_EQUAL(c9_0_, 0.0f);\n  const auto c9_1_ = L::celerity()[9][1];\n  BOOST_CHECK_EQUAL(c9_1_, 1.0f);\n  const auto c9_2_ = L::celerity()[9][2];\n  BOOST_CHECK_EQUAL(c9_2_, 0.0f);\n\n  const auto c10_0_ = L::celerity()[10][0];\n  BOOST_CHECK_EQUAL(c10_0_, 0.0f);\n  const auto c10_1_ = L::celerity()[10][1];\n  BOOST_CHECK_EQUAL(c10_1_, 0.0f);\n  const auto c10_2_ = L::celerity()[10][2];\n  BOOST_CHECK_EQUAL(c10_2_, 1.0f);\n\n  const auto c11_0_ = L::celerity()[11][0];\n  BOOST_CHECK_EQUAL(c11_0_, 1.0f);\n  const auto c11_1_ = L::celerity()[11][1];\n  BOOST_CHECK_EQUAL(c11_1_, 1.0f);\n  const auto c11_2_ = L::celerity()[11][2];\n  BOOST_CHECK_EQUAL(c11_2_, 1.0f);\n\n  const auto c12_0_ = L::celerity()[12][0];\n  BOOST_CHECK_EQUAL(c12_0_, 1.0f);\n  const auto c12_1_ = L::celerity()[12][1];\n  BOOST_CHECK_EQUAL(c12_1_, 1.0f);\n  const auto c12_2_ = L::celerity()[12][2];\n  BOOST_CHECK_EQUAL(c12_2_, -1.0f);\n\n  const auto c13_0_ = L::celerity()[13][0];\n  BOOST_CHECK_EQUAL(c13_0_, 1.0f);\n  const auto c13_1_ = L::celerity()[13][1];\n  BOOST_CHECK_EQUAL(c13_1_, -1.0f);\n  const auto c13_2_ = L::celerity()[13][2];\n  BOOST_CHECK_EQUAL(c13_2_, 1.0f);\n\n  const auto c14_0_ = L::celerity()[14][0];\n  BOOST_CHECK_EQUAL(c14_0_, 1.0f);\n  const auto c14_1_ = L::celerity()[14][1];\n  BOOST_CHECK_EQUAL(c14_1_, -1.0f);\n  const auto c14_2_ = L::celerity()[14][2];\n  BOOST_CHECK_EQUAL(c14_2_, -1.0f);\n}\n\nBOOST_AUTO_TEST_CASE(TestIsotropyD3Q19) {\n  constexpr LatticeType latticeType = LatticeType::D3Q19;\n  typedef double valueType;\n  typedef Lattice<valueType, latticeType> L;\n\n  valueType sumWeight = 0.0;\n  valueType sumWeight_r = 1.0;\n\n  MathVector<valueType, L::dimD> sumWeightCelerity{{0.0}};\n  MathVector<valueType, L::dimD> sumWeightCelerity_r{{0.0}};\n\n  MathVector<valueType, L::dimD*L::dimD> sumWeight2Celerity{{0.0}};\n  MathVector<valueType, L::dimD*L::dimD> sumWeight2Celerity_r{{0.0}};\n\n  MathVector<valueType, L::dimD*L::dimD*L::dimD> sumWeight3Celerity{{0.0}};\n  MathVector<valueType, L::dimD*L::dimD*L::dimD> sumWeight3Celerity_r{{0.0}};\n\n  MathVector<valueType, L::dimD*L::dimD*L::dimD*L::dimD> sumWeight4Celerity{{0.0}};\n  MathVector<valueType, L::dimD*L::dimD*L::dimD*L::dimD> sumWeight4Celerity_r{{0.0}};\n\n  MathVector<valueType, L::dimD*L::dimD*L::dimD*L::dimD*L::dimD> sumWeight5Celerity{{0.0}};\n  MathVector<valueType, L::dimD*L::dimD*L::dimD*L::dimD*L::dimD> sumWeight5Celerity_r{{0.0}};\n\n\n  for(int iQ = 0; iQ < L::dimQ; ++iQ) {\n    sumWeight += L::weight()[iQ];\n\n    for(int d_a = 0; d_a < L::dimD; ++d_a) {\n      int idx_a = d_a;\n      sumWeightCelerity[idx_a] += L::weight()[iQ]*L::celerity()[iQ][d_a];\n\n      for(int d_b = 0; d_b < L::dimD; ++d_b) {\n        int idx_b = L::dimD * idx_a + d_b;\n        sumWeight2Celerity[idx_b] += L::weight()[iQ]*L::celerity()[iQ][d_a]*L::celerity()[iQ][d_b];\n\n        if(d_a == d_b) {\n          sumWeight2Celerity_r[idx_b] = L::cs2;\n        }\n\n        for(int d_c = 0; d_c < L::dimD; ++d_c) {\n          int idx_c = L::dimD * idx_b + d_c;\n          sumWeight3Celerity[idx_c] += L::weight()[iQ]*L::celerity()[iQ][d_a]\n            *L::celerity()[iQ][d_b]*L::celerity()[iQ][d_c];\n\n          for(int d_d = 0; d_d < L::dimD; ++d_d) {\n            int idx_d = L::dimD * idx_c + d_d;\n            sumWeight4Celerity[idx_d] += L::weight()[iQ]*L::celerity()[iQ][d_a]\n              *L::celerity()[iQ][d_b]*L::celerity()[iQ][d_c]*L::celerity()[iQ][d_d];\n\n            if((d_a == d_b && d_c == d_d)\n               && (d_a == d_c && d_b == d_d)\n               && (d_a == d_d && d_b == d_c)) {\n              sumWeight4Celerity_r[idx_d] = 3.0*L::cs2*L::cs2;\n            }\n            else if(((d_a == d_b && d_c == d_d) && (d_a == d_c && d_b == d_d))\n                    || ((d_a == d_b && d_c == d_d) && (d_a == d_d && d_b == d_d))\n                    || ((d_a == d_d && d_b == d_c) && (d_a == d_d && d_b == d_d))) {\n              sumWeight4Celerity_r[idx_d] = 2.0*L::cs2*L::cs2;\n            }\n            else if((d_a == d_b && d_c == d_d)\n                    || (d_a == d_c && d_b == d_d)\n                    || (d_a == d_d && d_b == d_c)) {\n              sumWeight4Celerity_r[idx_d] = 1.0*L::cs2*L::cs2;\n            }\n\n            for(int d_e = 0; d_e < L::dimD; ++d_e) {\n              int idx_e = L::dimD * idx_d + d_e;\n              sumWeight5Celerity[idx_e] += L::weight()[iQ]*L::celerity()[iQ][d_a]\n                *L::celerity()[iQ][d_b]*L::celerity()[iQ][d_c]*L::celerity()[iQ][d_d]\n                *L::celerity()[iQ][d_e];\n            }\n          }\n        }\n      }\n    }\n  }\n\n  BOOST_TEST(sumWeight == sumWeight_r, tt::tolerance(1e-15));\n  for(int i = 0; i < L::dimD; ++i) {\n    BOOST_TEST(sumWeightCelerity[i] == sumWeightCelerity_r[i], tt::tolerance(1e-15));\n  }\n  for(int i = 0; i < L::dimD*L::dimD; ++i) {\n    BOOST_TEST(sumWeight2Celerity[i] == sumWeight2Celerity_r[i], tt::tolerance(1e-15));\n  }\n  for(int i = 0; i < L::dimD*L::dimD*L::dimD; ++i) {\n    BOOST_TEST(sumWeight3Celerity[i] == sumWeight3Celerity_r[i], tt::tolerance(1e-15));\n  }\n  for(int i = 0; i < L::dimD*L::dimD*L::dimD*L::dimD; ++i) {\n    BOOST_TEST(sumWeight4Celerity[i] == sumWeight4Celerity_r[i], tt::tolerance(1e-15));\n  }\n  for(int i = 0; i < L::dimD*L::dimD*L::dimD*L::dimD*L::dimD; ++i) {\n    BOOST_TEST(sumWeight5Celerity[i] == sumWeight5Celerity_r[i], tt::tolerance(1e-15));\n  }\n}\n\n\nBOOST_AUTO_TEST_CASE(TestDoubleD3Q19) {\n  constexpr LatticeType latticeType = LatticeType::D3Q19;\n  typedef double valueType;\n\n  typedef Lattice<valueType, latticeType> L;\n\n  const auto dimD_ = L::dimD;\n  BOOST_CHECK_EQUAL(dimD_, 3);\n  const auto dimQ_ = L::dimQ;\n  BOOST_CHECK_EQUAL(dimQ_, 19);\n\n  const auto lX_g_ = L::lX_g;\n  BOOST_CHECK_EQUAL(lX_g_, lengthX_g);\n  const auto lY_g_ = L::lY_g;\n  BOOST_CHECK_EQUAL(lY_g_, lengthY_g);\n  const auto lZ_g_ = L::lZ_g;\n  BOOST_CHECK_EQUAL(lZ_g_, lengthZ_g);\n\n  const auto hX_ = L::hX;\n  BOOST_CHECK_EQUAL(hX_, 1);\n  const auto hY_ = L::hY;\n  BOOST_CHECK_EQUAL(hY_, 1);\n  const auto hZ_ = L::hZ;\n  BOOST_CHECK_EQUAL(hZ_, 1);\n\n  const auto inv_cs2_ = L::inv_cs2;\n  BOOST_CHECK_EQUAL(inv_cs2_, (3.0));\n  const auto cs2_ = L::cs2;\n  BOOST_CHECK_EQUAL(cs2_, (1.0/3.0));\n\n  const auto w0_ = L::weight()[0];\n  BOOST_CHECK_EQUAL(w0_, 1.0/3.0);\n  const auto w1_ = L::weight()[1];\n  BOOST_CHECK_EQUAL(w1_, 1.0/18.0);\n  const auto w2_ = L::weight()[2];\n  BOOST_CHECK_EQUAL(w2_, 1.0/18.0);\n  const auto w3_ = L::weight()[3];\n  BOOST_CHECK_EQUAL(w3_, 1.0/18.0);\n  const auto w4_ = L::weight()[4];\n  BOOST_CHECK_EQUAL(w4_, 1.0/36.0);\n  const auto w5_ = L::weight()[5];\n  BOOST_CHECK_EQUAL(w5_, 1.0/36.0);\n  const auto w6_ = L::weight()[6];\n  BOOST_CHECK_EQUAL(w6_, 1.0/36.0);\n  const auto w7_ = L::weight()[7];\n  BOOST_CHECK_EQUAL(w7_, 1.0/36.0);\n  const auto w8_ = L::weight()[8];\n  BOOST_CHECK_EQUAL(w8_, 1.0/36.0);\n  const auto w9_ = L::weight()[9];\n  BOOST_CHECK_EQUAL(w9_, 1.0/36.0);\n  const auto w10_ = L::weight()[10];\n  BOOST_CHECK_EQUAL(w10_, 1.0/18.0);\n  const auto w11_ = L::weight()[11];\n  BOOST_CHECK_EQUAL(w11_, 1.0/18.0);\n  const auto w12_ = L::weight()[12];\n  BOOST_CHECK_EQUAL(w12_, 1.0/18.0);\n  const auto w13_ = L::weight()[13];\n  BOOST_CHECK_EQUAL(w13_, 1.0/36.0);\n  const auto w14_ = L::weight()[14];\n  BOOST_CHECK_EQUAL(w14_, 1.0/36.0);\n  const auto w15_ = L::weight()[15];\n  BOOST_CHECK_EQUAL(w15_, 1.0/36.0);\n  const auto w16_ = L::weight()[16];\n  BOOST_CHECK_EQUAL(w16_, 1.0/36.0);\n  const auto w17_ = L::weight()[17];\n  BOOST_CHECK_EQUAL(w17_, 1.0/36.0);\n  const auto w18_ = L::weight()[18];\n  BOOST_CHECK_EQUAL(w18_, 1.0/36.0);\n\n  const auto c0_ = L::celerity()[0];\n  const auto c0_r = MathVector<valueType, dimD_>{{0.0, 0.0, 0.0}};\n  BOOST_CHECK_EQUAL(c0_, c0_r);\n  const auto c1_ = L::celerity()[1];\n  const auto c1_r = MathVector<valueType, dimD_>{{-1.0, 0.0, 0.0}};\n  BOOST_CHECK_EQUAL(c1_, c1_r);\n  const auto c2_ = L::celerity()[2];\n  const auto c2_r = MathVector<valueType, dimD_>{{0.0, -1.0, 0.0}};\n  BOOST_CHECK_EQUAL(c2_, c2_r);\n  const auto c3_ = L::celerity()[3];\n  const auto c3_r = MathVector<valueType, dimD_>{{0.0, 0.0, -1.0}};\n  BOOST_CHECK_EQUAL(c3_, c3_r);\n  const auto c4_ = L::celerity()[4];\n  const auto c4_r = MathVector<valueType, dimD_>{{-1.0, -1.0, 0.0}};\n  BOOST_CHECK_EQUAL(c4_, c4_r);\n  const auto c5_ = L::celerity()[5];\n  const auto c5_r = MathVector<valueType, dimD_>{{-1.0, 1.0, 0.0}};\n  BOOST_CHECK_EQUAL(c5_, c5_r);\n  const auto c6_ = L::celerity()[6];\n  const auto c6_r = MathVector<valueType, dimD_>{{-1.0, 0.0, -1.0}};\n  BOOST_CHECK_EQUAL(c6_, c6_r);\n  const auto c7_ = L::celerity()[7];\n  const auto c7_r = MathVector<valueType, dimD_>{{-1.0, 0.0, 1.0}};\n  BOOST_CHECK_EQUAL(c7_, c7_r);\n  const auto c8_ = L::celerity()[8];\n  const auto c8_r = MathVector<valueType, dimD_>{{0.0, -1.0, -1.0}};\n  BOOST_CHECK_EQUAL(c8_, c8_r);\n  const auto c9_ = L::celerity()[9];\n  const auto c9_r = MathVector<valueType, dimD_>{{0.0, -1.0, 1.0}};\n  BOOST_CHECK_EQUAL(c9_, c9_r);\n  const auto c10_ = L::celerity()[10];\n  const auto c10_r = MathVector<valueType, dimD_>{{1.0, 0.0, 0.0}};\n  BOOST_CHECK_EQUAL(c10_, c10_r);\n  const auto c11_ = L::celerity()[11];\n  const auto c11_r = MathVector<valueType, dimD_>{{0.0, 1.0, 0.0}};\n  BOOST_CHECK_EQUAL(c11_, c11_r);\n  const auto c12_ = L::celerity()[12];\n  const auto c12_r = MathVector<valueType, dimD_>{{0.0, 0.0, 1.0}};\n  BOOST_CHECK_EQUAL(c12_, c12_r);\n  const auto c13_ = L::celerity()[13];\n  const auto c13_r = MathVector<valueType, dimD_>{{1.0, 1.0, 0.0}};\n  BOOST_CHECK_EQUAL(c13_, c13_r);\n  const auto c14_ = L::celerity()[14];\n  const auto c14_r = MathVector<valueType, dimD_>{{1.0, -1.0, 0.0}};\n  BOOST_CHECK_EQUAL(c14_, c14_r);\n  const auto c15_ = L::celerity()[15];\n  const auto c15_r = MathVector<valueType, dimD_>{{1.0, 0.0, 1.0}};\n  BOOST_CHECK_EQUAL(c15_, c15_r);\n  const auto c16_ = L::celerity()[16];\n  const auto c16_r = MathVector<valueType, dimD_>{{1.0, 0.0, -1.0}};\n  BOOST_CHECK_EQUAL(c16_, c16_r);\n  const auto c17_ = L::celerity()[17];\n  const auto c17_r = MathVector<valueType, dimD_>{{0.0, 1.0, 1.0}};\n  BOOST_CHECK_EQUAL(c17_, c17_r);\n  const auto c18_ = L::celerity()[18];\n  const auto c18_r = MathVector<valueType, dimD_>{{0.0, 1.0, -1.0}};\n  BOOST_CHECK_EQUAL(c18_, c18_r);\n\n  const auto c0_0_ = L::celerity()[0][0];\n  BOOST_CHECK_EQUAL(c0_0_, 0.0);\n  const auto c0_1_ = L::celerity()[0][1];\n  BOOST_CHECK_EQUAL(c0_1_, 0.0);\n  const auto c0_2_ = L::celerity()[0][1];\n  BOOST_CHECK_EQUAL(c0_2_, 0.0);\n\n  const auto c1_0_ = L::celerity()[1][0];\n  BOOST_CHECK_EQUAL(c1_0_, -1.0);\n  const auto c1_1_ = L::celerity()[1][1];\n  BOOST_CHECK_EQUAL(c1_1_, 0.0);\n  const auto c1_2_ = L::celerity()[1][2];\n  BOOST_CHECK_EQUAL(c1_2_, 0.0);\n\n  const auto c2_0_ = L::celerity()[2][0];\n  BOOST_CHECK_EQUAL(c2_0_, 0.0);\n  const auto c2_1_ = L::celerity()[2][1];\n  BOOST_CHECK_EQUAL(c2_1_, -1.0);\n  const auto c2_2_ = L::celerity()[2][2];\n  BOOST_CHECK_EQUAL(c2_2_, 0.0);\n\n  const auto c3_0_ = L::celerity()[3][0];\n  BOOST_CHECK_EQUAL(c3_0_, 0.0);\n  const auto c3_1_ = L::celerity()[3][1];\n  BOOST_CHECK_EQUAL(c3_1_, 0.0);\n  const auto c3_2_ = L::celerity()[3][2];\n  BOOST_CHECK_EQUAL(c3_2_, -1.0);\n\n  const auto c4_0_ = L::celerity()[4][0];\n  BOOST_CHECK_EQUAL(c4_0_, -1.0);\n  const auto c4_1_ = L::celerity()[4][1];\n  BOOST_CHECK_EQUAL(c4_1_, -1.0);\n  const auto c4_2_ = L::celerity()[4][2];\n  BOOST_CHECK_EQUAL(c4_2_, 0.0);\n\n  const auto c5_0_ = L::celerity()[5][0];\n  BOOST_CHECK_EQUAL(c5_0_, -1.0);\n  const auto c5_1_ = L::celerity()[5][1];\n  BOOST_CHECK_EQUAL(c5_1_, 1.0);\n  const auto c5_2_ = L::celerity()[5][2];\n  BOOST_CHECK_EQUAL(c5_2_, 0.0);\n\n  const auto c6_0_ = L::celerity()[6][0];\n  BOOST_CHECK_EQUAL(c6_0_, -1.0);\n  const auto c6_1_ = L::celerity()[6][1];\n  BOOST_CHECK_EQUAL(c6_1_, 0.0);\n  const auto c6_2_ = L::celerity()[6][2];\n  BOOST_CHECK_EQUAL(c6_2_, -1.0);\n\n  const auto c7_0_ = L::celerity()[7][0];\n  BOOST_CHECK_EQUAL(c7_0_, -1.0);\n  const auto c7_1_ = L::celerity()[7][1];\n  BOOST_CHECK_EQUAL(c7_1_, 0.0);\n  const auto c7_2_ = L::celerity()[7][2];\n  BOOST_CHECK_EQUAL(c7_2_, 1.0);\n\n  const auto c8_0_ = L::celerity()[8][0];\n  BOOST_CHECK_EQUAL(c8_0_, 0.0);\n  const auto c8_1_ = L::celerity()[8][1];\n  BOOST_CHECK_EQUAL(c8_1_, -1.0);\n  const auto c8_2_ = L::celerity()[8][2];\n  BOOST_CHECK_EQUAL(c8_2_, -1.0);\n\n  const auto c9_0_ = L::celerity()[9][0];\n  BOOST_CHECK_EQUAL(c9_0_, 0.0);\n  const auto c9_1_ = L::celerity()[9][1];\n  BOOST_CHECK_EQUAL(c9_1_, -1.0);\n  const auto c9_2_ = L::celerity()[9][2];\n  BOOST_CHECK_EQUAL(c9_2_, 1.0);\n\n  const auto c10_0_ = L::celerity()[10][0];\n  BOOST_CHECK_EQUAL(c10_0_, 1.0);\n  const auto c10_1_ = L::celerity()[10][1];\n  BOOST_CHECK_EQUAL(c10_1_, 0.0);\n  const auto c10_2_ = L::celerity()[10][2];\n  BOOST_CHECK_EQUAL(c10_2_, 0.0);\n\n  const auto c11_0_ = L::celerity()[11][0];\n  BOOST_CHECK_EQUAL(c11_0_, 0.0);\n  const auto c11_1_ = L::celerity()[11][1];\n  BOOST_CHECK_EQUAL(c11_1_, 1.0);\n  const auto c11_2_ = L::celerity()[11][2];\n  BOOST_CHECK_EQUAL(c11_2_, 0.0);\n\n  const auto c12_0_ = L::celerity()[12][0];\n  BOOST_CHECK_EQUAL(c12_0_, 0.0);\n  const auto c12_1_ = L::celerity()[12][1];\n  BOOST_CHECK_EQUAL(c12_1_, 0.0);\n  const auto c12_2_ = L::celerity()[12][2];\n  BOOST_CHECK_EQUAL(c12_2_, 1.0);\n\n  const auto c13_0_ = L::celerity()[13][0];\n  BOOST_CHECK_EQUAL(c13_0_, 1.0);\n  const auto c13_1_ = L::celerity()[13][1];\n  BOOST_CHECK_EQUAL(c13_1_, 1.0);\n  const auto c13_2_ = L::celerity()[13][2];\n  BOOST_CHECK_EQUAL(c13_2_, 0.0);\n\n  const auto c14_0_ = L::celerity()[14][0];\n  BOOST_CHECK_EQUAL(c14_0_, 1.0);\n  const auto c14_1_ = L::celerity()[14][1];\n  BOOST_CHECK_EQUAL(c14_1_, -1.0);\n  const auto c14_2_ = L::celerity()[14][2];\n  BOOST_CHECK_EQUAL(c14_2_, 0.0);\n\n  const auto c15_0_ = L::celerity()[15][0];\n  BOOST_CHECK_EQUAL(c15_0_, 1.0);\n  const auto c15_1_ = L::celerity()[15][1];\n  BOOST_CHECK_EQUAL(c15_1_, 0.0);\n  const auto c15_2_ = L::celerity()[15][2];\n  BOOST_CHECK_EQUAL(c15_2_, 1.0);\n\n  const auto c16_0_ = L::celerity()[16][0];\n  BOOST_CHECK_EQUAL(c16_0_, 1.0);\n  const auto c16_1_ = L::celerity()[16][1];\n  BOOST_CHECK_EQUAL(c16_1_, 0.0);\n  const auto c16_2_ = L::celerity()[16][2];\n  BOOST_CHECK_EQUAL(c16_2_, -1.0);\n\n  const auto c17_0_ = L::celerity()[17][0];\n  BOOST_CHECK_EQUAL(c17_0_, 0.0);\n  const auto c17_1_ = L::celerity()[17][1];\n  BOOST_CHECK_EQUAL(c17_1_, 1.0);\n  const auto c17_2_ = L::celerity()[17][2];\n  BOOST_CHECK_EQUAL(c17_2_, 1.0);\n\n  const auto c18_0_ = L::celerity()[18][0];\n  BOOST_CHECK_EQUAL(c18_0_, 0.0);\n  const auto c18_1_ = L::celerity()[18][1];\n  BOOST_CHECK_EQUAL(c18_1_, 1.0);\n  const auto c18_2_ = L::celerity()[18][2];\n  BOOST_CHECK_EQUAL(c18_2_, -1.0);\n\n}\n\nBOOST_AUTO_TEST_CASE(TestFloatD3Q19) {\n  constexpr LatticeType latticeType = LatticeType::D3Q19;\n  typedef float valueType;\n\n  typedef Lattice<valueType, latticeType> L;\n\n  const auto dimD_ = L::dimD;\n  BOOST_CHECK_EQUAL(dimD_, 3);\n  const auto dimQ_ = L::dimQ;\n  BOOST_CHECK_EQUAL(dimQ_, 19);\n\n  const auto lX_g_ = L::lX_g;\n  BOOST_CHECK_EQUAL(lX_g_, lengthX_g);\n  const auto lY_g_ = L::lY_g;\n  BOOST_CHECK_EQUAL(lY_g_, lengthY_g);\n  const auto lZ_g_ = L::lZ_g;\n  BOOST_CHECK_EQUAL(lZ_g_, lengthZ_g);\n\n  const auto hX_ = L::hX;\n  BOOST_CHECK_EQUAL(hX_, 1);\n  const auto hY_ = L::hY;\n  BOOST_CHECK_EQUAL(hY_, 1);\n  const auto hZ_ = L::hZ;\n  BOOST_CHECK_EQUAL(hZ_, 1);\n\n  const auto inv_cs2_ = L::inv_cs2;\n  BOOST_CHECK_EQUAL(inv_cs2_, (3.0f));\n  const auto cs2_ = L::cs2;\n  BOOST_CHECK_EQUAL(cs2_, (1.0f/3.0f));\n\n  const auto w0_ = L::weight()[0];\n  BOOST_CHECK_EQUAL(w0_, 1.0f/3.0f);\n  const auto w1_ = L::weight()[1];\n  BOOST_CHECK_EQUAL(w1_, 1.0f/18.0f);\n  const auto w2_ = L::weight()[2];\n  BOOST_CHECK_EQUAL(w2_, 1.0f/18.0f);\n  const auto w3_ = L::weight()[3];\n  BOOST_CHECK_EQUAL(w3_, 1.0f/18.0f);\n  const auto w4_ = L::weight()[4];\n  BOOST_CHECK_EQUAL(w4_, 1.0f/36.0f);\n  const auto w5_ = L::weight()[5];\n  BOOST_CHECK_EQUAL(w5_, 1.0f/36.0f);\n  const auto w6_ = L::weight()[6];\n  BOOST_CHECK_EQUAL(w6_, 1.0f/36.0f);\n  const auto w7_ = L::weight()[7];\n  BOOST_CHECK_EQUAL(w7_, 1.0f/36.0f);\n  const auto w8_ = L::weight()[8];\n  BOOST_CHECK_EQUAL(w8_, 1.0f/36.0f);\n  const auto w9_ = L::weight()[9];\n  BOOST_CHECK_EQUAL(w9_, 1.0f/36.0f);\n  const auto w10_ = L::weight()[10];\n  BOOST_CHECK_EQUAL(w10_, 1.0f/18.0f);\n  const auto w11_ = L::weight()[11];\n  BOOST_CHECK_EQUAL(w11_, 1.0f/18.0f);\n  const auto w12_ = L::weight()[12];\n  BOOST_CHECK_EQUAL(w12_, 1.0f/18.0f);\n  const auto w13_ = L::weight()[13];\n  BOOST_CHECK_EQUAL(w13_, 1.0f/36.0f);\n  const auto w14_ = L::weight()[14];\n  BOOST_CHECK_EQUAL(w14_, 1.0f/36.0f);\n  const auto w15_ = L::weight()[15];\n  BOOST_CHECK_EQUAL(w15_, 1.0f/36.0f);\n  const auto w16_ = L::weight()[16];\n  BOOST_CHECK_EQUAL(w16_, 1.0f/36.0f);\n  const auto w17_ = L::weight()[17];\n  BOOST_CHECK_EQUAL(w17_, 1.0f/36.0f);\n  const auto w18_ = L::weight()[18];\n  BOOST_CHECK_EQUAL(w18_, 1.0f/36.0f);\n\n  const auto c0_ = L::celerity()[0];\n  const auto c0_r = MathVector<valueType, dimD_>{{0.0f, 0.0f, 0.0f}};\n  BOOST_CHECK_EQUAL(c0_, c0_r);\n  const auto c1_ = L::celerity()[1];\n  const auto c1_r = MathVector<valueType, dimD_>{{-1.0f, 0.0f, 0.0f}};\n  BOOST_CHECK_EQUAL(c1_, c1_r);\n  const auto c2_ = L::celerity()[2];\n  const auto c2_r = MathVector<valueType, dimD_>{{0.0f, -1.0f, 0.0f}};\n  BOOST_CHECK_EQUAL(c2_, c2_r);\n  const auto c3_ = L::celerity()[3];\n  const auto c3_r = MathVector<valueType, dimD_>{{0.0f, 0.0f, -1.0f}};\n  BOOST_CHECK_EQUAL(c3_, c3_r);\n  const auto c4_ = L::celerity()[4];\n  const auto c4_r = MathVector<valueType, dimD_>{{-1.0f, -1.0f, 0.0f}};\n  BOOST_CHECK_EQUAL(c4_, c4_r);\n  const auto c5_ = L::celerity()[5];\n  const auto c5_r = MathVector<valueType, dimD_>{{-1.0f, 1.0f, 0.0f}};\n  BOOST_CHECK_EQUAL(c5_, c5_r);\n  const auto c6_ = L::celerity()[6];\n  const auto c6_r = MathVector<valueType, dimD_>{{-1.0f, 0.0f, -1.0f}};\n  BOOST_CHECK_EQUAL(c6_, c6_r);\n  const auto c7_ = L::celerity()[7];\n  const auto c7_r = MathVector<valueType, dimD_>{{-1.0f, 0.0f, 1.0f}};\n  BOOST_CHECK_EQUAL(c7_, c7_r);\n  const auto c8_ = L::celerity()[8];\n  const auto c8_r = MathVector<valueType, dimD_>{{0.0f, -1.0f, -1.0f}};\n  BOOST_CHECK_EQUAL(c8_, c8_r);\n  const auto c9_ = L::celerity()[9];\n  const auto c9_r = MathVector<valueType, dimD_>{{0.0f, -1.0f, 1.0f}};\n  BOOST_CHECK_EQUAL(c9_, c9_r);\n  const auto c10_ = L::celerity()[10];\n  const auto c10_r = MathVector<valueType, dimD_>{{1.0f, 0.0f, 0.0f}};\n  BOOST_CHECK_EQUAL(c10_, c10_r);\n  const auto c11_ = L::celerity()[11];\n  const auto c11_r = MathVector<valueType, dimD_>{{0.0f, 1.0f, 0.0f}};\n  BOOST_CHECK_EQUAL(c11_, c11_r);\n  const auto c12_ = L::celerity()[12];\n  const auto c12_r = MathVector<valueType, dimD_>{{0.0f, 0.0f, 1.0f}};\n  BOOST_CHECK_EQUAL(c12_, c12_r);\n  const auto c13_ = L::celerity()[13];\n  const auto c13_r = MathVector<valueType, dimD_>{{1.0f, 1.0f, 0.0f}};\n  BOOST_CHECK_EQUAL(c13_, c13_r);\n  const auto c14_ = L::celerity()[14];\n  const auto c14_r = MathVector<valueType, dimD_>{{1.0f, -1.0f, 0.0f}};\n  BOOST_CHECK_EQUAL(c14_, c14_r);\n  const auto c15_ = L::celerity()[15];\n  const auto c15_r = MathVector<valueType, dimD_>{{1.0f, 0.0f, 1.0f}};\n  BOOST_CHECK_EQUAL(c15_, c15_r);\n  const auto c16_ = L::celerity()[16];\n  const auto c16_r = MathVector<valueType, dimD_>{{1.0f, 0.0f, -1.0f}};\n  BOOST_CHECK_EQUAL(c16_, c16_r);\n  const auto c17_ = L::celerity()[17];\n  const auto c17_r = MathVector<valueType, dimD_>{{0.0f, 1.0f, 1.0f}};\n  BOOST_CHECK_EQUAL(c17_, c17_r);\n  const auto c18_ = L::celerity()[18];\n  const auto c18_r = MathVector<valueType, dimD_>{{0.0f, 1.0f, -1.0f}};\n  BOOST_CHECK_EQUAL(c18_, c18_r);\n\n  const auto c0_0_ = L::celerity()[0][0];\n  BOOST_CHECK_EQUAL(c0_0_, 0.0f);\n  const auto c0_1_ = L::celerity()[0][1];\n  BOOST_CHECK_EQUAL(c0_1_, 0.0f);\n  const auto c0_2_ = L::celerity()[0][1];\n  BOOST_CHECK_EQUAL(c0_2_, 0.0f);\n\n  const auto c1_0_ = L::celerity()[1][0];\n  BOOST_CHECK_EQUAL(c1_0_, -1.0f);\n  const auto c1_1_ = L::celerity()[1][1];\n  BOOST_CHECK_EQUAL(c1_1_, 0.0f);\n  const auto c1_2_ = L::celerity()[1][2];\n  BOOST_CHECK_EQUAL(c1_2_, 0.0f);\n\n  const auto c2_0_ = L::celerity()[2][0];\n  BOOST_CHECK_EQUAL(c2_0_, 0.0f);\n  const auto c2_1_ = L::celerity()[2][1];\n  BOOST_CHECK_EQUAL(c2_1_, -1.0f);\n  const auto c2_2_ = L::celerity()[2][2];\n  BOOST_CHECK_EQUAL(c2_2_, 0.0f);\n\n  const auto c3_0_ = L::celerity()[3][0];\n  BOOST_CHECK_EQUAL(c3_0_, 0.0f);\n  const auto c3_1_ = L::celerity()[3][1];\n  BOOST_CHECK_EQUAL(c3_1_, 0.0f);\n  const auto c3_2_ = L::celerity()[3][2];\n  BOOST_CHECK_EQUAL(c3_2_, -1.0f);\n\n  const auto c4_0_ = L::celerity()[4][0];\n  BOOST_CHECK_EQUAL(c4_0_, -1.0f);\n  const auto c4_1_ = L::celerity()[4][1];\n  BOOST_CHECK_EQUAL(c4_1_, -1.0f);\n  const auto c4_2_ = L::celerity()[4][2];\n  BOOST_CHECK_EQUAL(c4_2_, 0.0f);\n\n  const auto c5_0_ = L::celerity()[5][0];\n  BOOST_CHECK_EQUAL(c5_0_, -1.0f);\n  const auto c5_1_ = L::celerity()[5][1];\n  BOOST_CHECK_EQUAL(c5_1_, 1.0f);\n  const auto c5_2_ = L::celerity()[5][2];\n  BOOST_CHECK_EQUAL(c5_2_, 0.0f);\n\n  const auto c6_0_ = L::celerity()[6][0];\n  BOOST_CHECK_EQUAL(c6_0_, -1.0f);\n  const auto c6_1_ = L::celerity()[6][1];\n  BOOST_CHECK_EQUAL(c6_1_, 0.0f);\n  const auto c6_2_ = L::celerity()[6][2];\n  BOOST_CHECK_EQUAL(c6_2_, -1.0f);\n\n  const auto c7_0_ = L::celerity()[7][0];\n  BOOST_CHECK_EQUAL(c7_0_, -1.0f);\n  const auto c7_1_ = L::celerity()[7][1];\n  BOOST_CHECK_EQUAL(c7_1_, 0.0f);\n  const auto c7_2_ = L::celerity()[7][2];\n  BOOST_CHECK_EQUAL(c7_2_, 1.0f);\n\n  const auto c8_0_ = L::celerity()[8][0];\n  BOOST_CHECK_EQUAL(c8_0_, 0.0f);\n  const auto c8_1_ = L::celerity()[8][1];\n  BOOST_CHECK_EQUAL(c8_1_, -1.0f);\n  const auto c8_2_ = L::celerity()[8][2];\n  BOOST_CHECK_EQUAL(c8_2_, -1.0f);\n\n  const auto c9_0_ = L::celerity()[9][0];\n  BOOST_CHECK_EQUAL(c9_0_, 0.0f);\n  const auto c9_1_ = L::celerity()[9][1];\n  BOOST_CHECK_EQUAL(c9_1_, -1.0f);\n  const auto c9_2_ = L::celerity()[9][2];\n  BOOST_CHECK_EQUAL(c9_2_, 1.0f);\n\n  const auto c10_0_ = L::celerity()[10][0];\n  BOOST_CHECK_EQUAL(c10_0_, 1.0f);\n  const auto c10_1_ = L::celerity()[10][1];\n  BOOST_CHECK_EQUAL(c10_1_, 0.0f);\n  const auto c10_2_ = L::celerity()[10][2];\n  BOOST_CHECK_EQUAL(c10_2_, 0.0f);\n\n  const auto c11_0_ = L::celerity()[11][0];\n  BOOST_CHECK_EQUAL(c11_0_, 0.0f);\n  const auto c11_1_ = L::celerity()[11][1];\n  BOOST_CHECK_EQUAL(c11_1_, 1.0f);\n  const auto c11_2_ = L::celerity()[11][2];\n  BOOST_CHECK_EQUAL(c11_2_, 0.0f);\n\n  const auto c12_0_ = L::celerity()[12][0];\n  BOOST_CHECK_EQUAL(c12_0_, 0.0f);\n  const auto c12_1_ = L::celerity()[12][1];\n  BOOST_CHECK_EQUAL(c12_1_, 0.0f);\n  const auto c12_2_ = L::celerity()[12][2];\n  BOOST_CHECK_EQUAL(c12_2_, 1.0f);\n\n  const auto c13_0_ = L::celerity()[13][0];\n  BOOST_CHECK_EQUAL(c13_0_, 1.0f);\n  const auto c13_1_ = L::celerity()[13][1];\n  BOOST_CHECK_EQUAL(c13_1_, 1.0f);\n  const auto c13_2_ = L::celerity()[13][2];\n  BOOST_CHECK_EQUAL(c13_2_, 0.0f);\n\n  const auto c14_0_ = L::celerity()[14][0];\n  BOOST_CHECK_EQUAL(c14_0_, 1.0f);\n  const auto c14_1_ = L::celerity()[14][1];\n  BOOST_CHECK_EQUAL(c14_1_, -1.0f);\n  const auto c14_2_ = L::celerity()[14][2];\n  BOOST_CHECK_EQUAL(c14_2_, 0.0f);\n\n  const auto c15_0_ = L::celerity()[15][0];\n  BOOST_CHECK_EQUAL(c15_0_, 1.0f);\n  const auto c15_1_ = L::celerity()[15][1];\n  BOOST_CHECK_EQUAL(c15_1_, 0.0f);\n  const auto c15_2_ = L::celerity()[15][2];\n  BOOST_CHECK_EQUAL(c15_2_, 1.0f);\n\n  const auto c16_0_ = L::celerity()[16][0];\n  BOOST_CHECK_EQUAL(c16_0_, 1.0f);\n  const auto c16_1_ = L::celerity()[16][1];\n  BOOST_CHECK_EQUAL(c16_1_, 0.0f);\n  const auto c16_2_ = L::celerity()[16][2];\n  BOOST_CHECK_EQUAL(c16_2_, -1.0f);\n\n  const auto c17_0_ = L::celerity()[17][0];\n  BOOST_CHECK_EQUAL(c17_0_, 0.0f);\n  const auto c17_1_ = L::celerity()[17][1];\n  BOOST_CHECK_EQUAL(c17_1_, 1.0f);\n  const auto c17_2_ = L::celerity()[17][2];\n  BOOST_CHECK_EQUAL(c17_2_, 1.0f);\n\n  const auto c18_0_ = L::celerity()[18][0];\n  BOOST_CHECK_EQUAL(c18_0_, 0.0f);\n  const auto c18_1_ = L::celerity()[18][1];\n  BOOST_CHECK_EQUAL(c18_1_, 1.0f);\n  const auto c18_2_ = L::celerity()[18][2];\n  BOOST_CHECK_EQUAL(c18_2_, -1.0f);\n}\n\nBOOST_AUTO_TEST_CASE(TestIsotropyD3Q27) {\n  constexpr LatticeType latticeType = LatticeType::D3Q27;\n  typedef double valueType;\n  typedef Lattice<valueType, latticeType> L;\n\n  valueType sumWeight = 0.0;\n  valueType sumWeight_r = 1.0;\n\n  MathVector<valueType, L::dimD> sumWeightCelerity{{0.0}};\n  MathVector<valueType, L::dimD> sumWeightCelerity_r{{0.0}};\n\n  MathVector<valueType, L::dimD*L::dimD> sumWeight2Celerity{{0.0}};\n  MathVector<valueType, L::dimD*L::dimD> sumWeight2Celerity_r{{0.0}};\n\n  MathVector<valueType, L::dimD*L::dimD*L::dimD> sumWeight3Celerity{{0.0}};\n  MathVector<valueType, L::dimD*L::dimD*L::dimD> sumWeight3Celerity_r{{0.0}};\n\n  MathVector<valueType, L::dimD*L::dimD*L::dimD*L::dimD> sumWeight4Celerity{{0.0}};\n  MathVector<valueType, L::dimD*L::dimD*L::dimD*L::dimD> sumWeight4Celerity_r{{0.0}};\n\n  MathVector<valueType, L::dimD*L::dimD*L::dimD*L::dimD*L::dimD> sumWeight5Celerity{{0.0}};\n  MathVector<valueType, L::dimD*L::dimD*L::dimD*L::dimD*L::dimD> sumWeight5Celerity_r{{0.0}};\n\n\n  for(int iQ = 0; iQ < L::dimQ; ++iQ) {\n    sumWeight += L::weight()[iQ];\n\n    for(int d_a = 0; d_a < L::dimD; ++d_a) {\n      int idx_a = d_a;\n      sumWeightCelerity[idx_a] += L::weight()[iQ]*L::celerity()[iQ][d_a];\n\n      for(int d_b = 0; d_b < L::dimD; ++d_b) {\n        int idx_b = L::dimD * idx_a + d_b;\n        sumWeight2Celerity[idx_b] += L::weight()[iQ]*L::celerity()[iQ][d_a]*L::celerity()[iQ][d_b];\n\n        if(d_a == d_b) {\n          sumWeight2Celerity_r[idx_b] = L::cs2;\n        }\n\n        for(int d_c = 0; d_c < L::dimD; ++d_c) {\n          int idx_c = L::dimD * idx_b + d_c;\n          sumWeight3Celerity[idx_c] += L::weight()[iQ]*L::celerity()[iQ][d_a]\n            *L::celerity()[iQ][d_b]*L::celerity()[iQ][d_c];\n\n          for(int d_d = 0; d_d < L::dimD; ++d_d) {\n            int idx_d = L::dimD * idx_c + d_d;\n            sumWeight4Celerity[idx_d] += L::weight()[iQ]*L::celerity()[iQ][d_a]\n              *L::celerity()[iQ][d_b]*L::celerity()[iQ][d_c]*L::celerity()[iQ][d_d];\n\n            if((d_a == d_b && d_c == d_d)\n               && (d_a == d_c && d_b == d_d)\n               && (d_a == d_d && d_b == d_c)) {\n              sumWeight4Celerity_r[idx_d] = 3.0*L::cs2*L::cs2;\n            }\n            else if(((d_a == d_b && d_c == d_d) && (d_a == d_c && d_b == d_d))\n                    || ((d_a == d_b && d_c == d_d) && (d_a == d_d && d_b == d_d))\n                    || ((d_a == d_d && d_b == d_c) && (d_a == d_d && d_b == d_d))) {\n              sumWeight4Celerity_r[idx_d] = 2.0*L::cs2*L::cs2;\n            }\n            else if((d_a == d_b && d_c == d_d)\n                    || (d_a == d_c && d_b == d_d)\n                    || (d_a == d_d && d_b == d_c)) {\n              sumWeight4Celerity_r[idx_d] = 1.0*L::cs2*L::cs2;\n            }\n\n            for(int d_e = 0; d_e < L::dimD; ++d_e) {\n              int idx_e = L::dimD * idx_d + d_e;\n              sumWeight5Celerity[idx_e] += L::weight()[iQ]*L::celerity()[iQ][d_a]\n                *L::celerity()[iQ][d_b]*L::celerity()[iQ][d_c]*L::celerity()[iQ][d_d]\n                *L::celerity()[iQ][d_e];\n            }\n          }\n        }\n      }\n    }\n  }\n\n  BOOST_TEST(sumWeight == sumWeight_r, tt::tolerance(1e-15));\n  for(int i = 0; i < L::dimD; ++i) {\n    BOOST_TEST(sumWeightCelerity[i] == sumWeightCelerity_r[i], tt::tolerance(1e-15));\n  }\n  for(int i = 0; i < L::dimD*L::dimD; ++i) {\n    BOOST_TEST(sumWeight2Celerity[i] == sumWeight2Celerity_r[i], tt::tolerance(1e-15));\n  }\n  for(int i = 0; i < L::dimD*L::dimD*L::dimD; ++i) {\n    BOOST_TEST(sumWeight3Celerity[i] == sumWeight3Celerity_r[i], tt::tolerance(1e-15));\n  }\n  for(int i = 0; i < L::dimD*L::dimD*L::dimD*L::dimD; ++i) {\n    BOOST_TEST(sumWeight4Celerity[i] == sumWeight4Celerity_r[i], tt::tolerance(1e-15));\n  }\n  for(int i = 0; i < L::dimD*L::dimD*L::dimD*L::dimD*L::dimD; ++i) {\n    BOOST_TEST(sumWeight5Celerity[i] == sumWeight5Celerity_r[i], tt::tolerance(1e-15));\n  }\n}\n\n// TODO: Add doubleD3Q27 and floatD3Q27 tests.\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "89929703897e830e3beee44be37cf81baa3fbf8a", "size": 71194, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/TestLattice.cpp", "max_stars_repo_name": "gtauzin/metaLBM", "max_stars_repo_head_hexsha": "07291e085962f50848489fd36ece46ce412bdbb5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-10-19T22:58:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T03:45:51.000Z", "max_issues_repo_path": "test/TestLattice.cpp", "max_issues_repo_name": "gtauzin/metaLBM", "max_issues_repo_head_hexsha": "07291e085962f50848489fd36ece46ce412bdbb5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-02-04T14:08:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-05T21:06:28.000Z", "max_forks_repo_path": "test/TestLattice.cpp", "max_forks_repo_name": "gtauzin/metaLBM", "max_forks_repo_head_hexsha": "07291e085962f50848489fd36ece46ce412bdbb5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-02-05T23:52:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-16T02:49:20.000Z", "avg_line_length": 35.2794846383, "max_line_length": 99, "alphanum_fraction": 0.6293226957, "num_tokens": 28737, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.45527226105455115}}
{"text": "#ifndef VISUALIZER_H\n#define VISUALIZER_H\n#include \"SFML/Graphics.hpp\"\n#include \"SFML/Window.hpp\"\n#include <armadillo>\n#include <string>\n#include \"colormaps.hpp\"\n#include \"lowPassFilter.hpp\"\n#include \"gaussianKernel.hpp\"\n\nnamespace visa\n{\n/** Matrix visualizer using the SFML libray */\nclass Visualizer\n{\npublic:\n  Visualizer();\n  ~Visualizer();\n\n  /** Initialize the window handler */\n  virtual void init( const char *windowName );\n\n  /** Initialize the window handler */\n  void init();\n\n  /** Set values to visualize. Depricated use setImg instead */\n  void fillVertexArray( arma::mat &values );\n\n  /** Creates an image from the matrix */\n  void setImg( arma::mat &values );\n\n  /** Set values to visualize */\n  virtual void fillVertexArray( arma::vec &values ){};\n\n  /** Set upper limit of the colorscale */\n  void setColorMax( double max ){ colorMax = max; };\n\n  /** Set the lower limit for the colorscale */\n  void setColorMin( double min ){ colorMin = min; };\n\n  /** Set both colorlimits (provided for convenience) */\n  void setColorLim( double min, double max );\n\n  /** Set color map */\n  void setCmap( Colormaps::Colormap_t cm ){ cmaps.setMap(cm); };\n\n  /** Sets the opacity */\n  void setOpacity( double alpha );\n\n  /** Get current image */\n  const sf::Image& getImg() const { return *img; };\n\n  /** Return the name of the plot */\n  const std::string& getName() const { return name; };\n\n  /** Returns the transparency factor */\n  sf::Uint8 getAlpha() const { return alpha; };\n\n  /** Set upper and lower y-limit. Only relevant for 1D plots */\n  virtual void setLimits( double min, double max ){};\n\n  /** True of the image can be plotted */\n  bool isReady() const;\nprotected:\n  sf::VertexArray *vArray{NULL};\n  std::string name;\n  sf::Image *img{NULL};\n\n  unsigned int width{640};\n  unsigned int height{480};\n  static const unsigned int defaultWidth{640};\n  static const unsigned int defaultHeight{480};\n  double colorMax{1.0};\n  double colorMin{0.0};\n  unsigned int vArrayNrow{0};\n  unsigned int vArrayNcol{0};\n  Colormaps cmaps;\n  bool resizingEnabled{true};\n  bool colorLimitsSetByUser{false};\n  sf::Uint8 *pixels{NULL};\n  sf::Uint8 alpha{255};\n  unsigned int nPix{0};\n\n  /** Set color corresponding to value */\n  void setColor( double value, sf::Color &color ) const;\n\n  /** Run the matrix through the low pass filter */\n  void filterMatrix( arma::mat &mat );\n\n  /** Resize the window to match the matrix */\n  void resizeWindow( unsigned int newWidth, unsigned int newHeight );\n\n  /** Resize width */\n  void resizeWidth( unsigned int newWidth );\n\n  /** Resize height */\n  void resizeHeight( unsigned int newHeight );\n\n  /** Restores the default window height and width */\n  void restoreDefaultWindowSize();\n\n  /** Filter horizontally */\n  void filterHorizontal( arma::mat &mat );\n\n  /** Filter vertically */\n  void filterVertical( arma::mat &mat );\n\n  /** Set limits based on max and min value */\n  void setMaxMinColors( arma::mat &mat );\n};\n}; // namespace\n#endif\n", "meta": {"hexsha": "09481a62fe2c8af0c9c4a109ac6bb357765bac7d", "size": 2974, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/visualizer.hpp", "max_stars_repo_name": "davidkleiven/VISA", "max_stars_repo_head_hexsha": "1b07197a3ea1f88c40e7d9249e08deee360ea814", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-05-27T12:49:40.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-05T05:50:51.000Z", "max_issues_repo_path": "include/visualizer.hpp", "max_issues_repo_name": "davidkleiven/VISA", "max_issues_repo_head_hexsha": "1b07197a3ea1f88c40e7d9249e08deee360ea814", "max_issues_repo_licenses": ["MIT"], "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/visualizer.hpp", "max_forks_repo_name": "davidkleiven/VISA", "max_forks_repo_head_hexsha": "1b07197a3ea1f88c40e7d9249e08deee360ea814", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-04-11T10:05:49.000Z", "max_forks_repo_forks_event_max_datetime": "2018-04-11T10:05:49.000Z", "avg_line_length": 26.3185840708, "max_line_length": 69, "alphanum_fraction": 0.6825823806, "num_tokens": 738, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.45527226105455115}}
{"text": "#include <Eigen/Geometry>\n#include <aikido/statespace/SE2.hpp>\n\nnamespace aikido {\nnamespace statespace {\n//==============================================================================\nSE2::State::State() : mTransform(Isometry2d::Identity())\n{\n}\n\n//==============================================================================\nSE2::State::State(const Isometry2d& _transform) : mTransform(_transform)\n{\n}\n\n//==============================================================================\nauto SE2::State::getIsometry() const -> const Isometry2d&\n{\n  return mTransform;\n}\n\n//==============================================================================\nvoid SE2::State::setIsometry(const Isometry2d& _transform)\n{\n  mTransform = _transform;\n}\n\n//==============================================================================\nauto SE2::createState() const -> ScopedState\n{\n  return ScopedState(this);\n}\n\n//==============================================================================\nSE2::ScopedState SE2::cloneState(const StateSpace::State* stateIn) const\n{\n  auto newState = createState();\n  copyState(stateIn, newState);\n\n  return newState;\n}\n\n//==============================================================================\nauto SE2::getIsometry(const State* _state) const -> const Isometry2d&\n{\n  return _state->getIsometry();\n}\n\n//==============================================================================\nvoid SE2::setIsometry(State* _state, const Isometry2d& _transform) const\n{\n  _state->setIsometry(_transform);\n}\n\n//==============================================================================\nstd::size_t SE2::getStateSizeInBytes() const\n{\n  return sizeof(State);\n}\n\n//==============================================================================\nStateSpace::State* SE2::allocateStateInBuffer(void* _buffer) const\n{\n  return new (_buffer) State;\n}\n\n//==============================================================================\nvoid SE2::freeStateInBuffer(StateSpace::State* _state) const\n{\n  static_cast<State*>(_state)->~State();\n}\n\n//==============================================================================\nvoid SE2::compose(\n    const StateSpace::State* _state1,\n    const StateSpace::State* _state2,\n    StateSpace::State* _out) const\n{\n  // TODO: Disable this in release mode.\n  if (_state1 == _out || _state2 == _out)\n    throw std::invalid_argument(\"Output aliases input.\");\n\n  auto state1 = static_cast<const State*>(_state1);\n  auto state2 = static_cast<const State*>(_state2);\n  auto out = static_cast<State*>(_out);\n\n  out->mTransform = state1->mTransform * state2->mTransform;\n}\n\n//==============================================================================\nstd::size_t SE2::getDimension() const\n{\n  return 3;\n}\n\n//==============================================================================\nvoid SE2::getIdentity(StateSpace::State* _out) const\n{\n  auto out = static_cast<State*>(_out);\n  setIsometry(out, Isometry2d::Identity());\n}\n\n//==============================================================================\nvoid SE2::getInverse(\n    const StateSpace::State* _in, StateSpace::State* _out) const\n{\n  // TODO: Disable this in release mode.\n  if (_out == _in)\n    throw std::invalid_argument(\"Output aliases input.\");\n\n  auto in = static_cast<const State*>(_in);\n  auto out = static_cast<State*>(_out);\n  setIsometry(out, getIsometry(in).inverse());\n}\n\n//==============================================================================\nvoid SE2::copyState(\n    const StateSpace::State* _source, StateSpace::State* _destination) const\n{\n  auto source = static_cast<const State*>(_source);\n  auto dest = static_cast<State*>(_destination);\n  setIsometry(dest, getIsometry(source));\n}\n\n//==============================================================================\nvoid SE2::expMap(const Eigen::VectorXd& _tangent, StateSpace::State* _out) const\n{\n  auto out = static_cast<State*>(_out);\n\n  if (_tangent.rows() != 3)\n  {\n    std::stringstream msg;\n    msg << \"_tangent has incorrect size: expected 3\"\n        << \", got \" << _tangent.rows() << \".\\n\";\n    throw std::runtime_error(msg.str());\n  }\n\n  double angle = _tangent(2);\n  Eigen::Vector2d translation = _tangent.head<2>();\n\n  Isometry2d transform(Isometry2d::Identity());\n  transform.linear() = Eigen::Rotation2Dd(angle).matrix();\n  transform.translation() = translation;\n\n  out->mTransform = transform;\n}\n\n//==============================================================================\nvoid SE2::logMap(const StateSpace::State* _in, Eigen::VectorXd& _tangent) const\n{\n  if (_tangent.rows() != 3)\n    _tangent.resize(3);\n\n  auto in = static_cast<const State*>(_in);\n\n  Isometry2d transform = getIsometry(in);\n  _tangent.head<2>() = transform.translation();\n  Eigen::Rotation2Dd rotation = Eigen::Rotation2Dd::Identity();\n  rotation.fromRotationMatrix(transform.rotation());\n  _tangent[2] = rotation.angle();\n}\n\n//==============================================================================\nvoid SE2::print(const StateSpace::State* _state, std::ostream& _os) const\n{\n  auto state = static_cast<const State*>(_state);\n  auto transform = getIsometry(state);\n\n  Eigen::IOFormat cleanFmt(\n      Eigen::StreamPrecision, Eigen::DontAlignCols, \",\", \",\", \"\", \"\", \"[\", \"]\");\n  Eigen::Rotation2Dd rotation = Eigen::Rotation2Dd::Identity();\n  rotation.fromRotationMatrix(transform.rotation());\n  _os << Eigen::Vector3d(\n             transform.translation()[0],\n             transform.translation()[1],\n             rotation.angle())\n             .format(cleanFmt);\n}\n} // namespace statespace\n} // namespace aikido\n", "meta": {"hexsha": "732eb7feb85d7de22bdca3ae8658b1696841aa8e", "size": 5606, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/statespace/SE2.cpp", "max_stars_repo_name": "usc-csci-545/aikido", "max_stars_repo_head_hexsha": "afd8b203c17cb0b05d7db436f8bffbbe2111a75a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/statespace/SE2.cpp", "max_issues_repo_name": "usc-csci-545/aikido", "max_issues_repo_head_hexsha": "afd8b203c17cb0b05d7db436f8bffbbe2111a75a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/statespace/SE2.cpp", "max_forks_repo_name": "usc-csci-545/aikido", "max_forks_repo_head_hexsha": "afd8b203c17cb0b05d7db436f8bffbbe2111a75a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.9723756906, "max_line_length": 80, "alphanum_fraction": 0.5030324652, "num_tokens": 1149, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.45527226105455115}}
{"text": "/**\n * @file fastpam1.cpp\n * @date 2021-08-03\n *\n * This file contains the primary C++ implementation of the FastPAM1 code follows\n * from the paper: Erich Schubert and Peter J. Rousseeuw: Faster k-Medoids Clustering:\n * Improving the PAM, CLARA, and CLARANS Algorithms. The paper can be assessed at\n * https://arxiv.org/pdf/1810.05691.pdf. Also the original PAM papers:\n * 1) Leonard Kaufman and Peter J. Rousseeuw: Clustering by means of medoids.\n * 2) Leonard Kaufman and Peter J. Rousseeuw: Partitioning around medoids (program pam).\n *\n */\n#include \"fastpam1.hpp\"\n\n#include <carma>\n#include <armadillo>\n#include <unordered_map>\n#include <regex>\n\n/**\n * \\brief Runs FastPAM1 algorithm.\n *\n * Run the FastPAM1 algorithm to identify a dataset's medoids.\n *\n * @param input_data Input data to cluster\n */\nvoid FastPAM1::fit_fastpam1(const arma::mat& input_data) {\n  data = input_data;\n  data = arma::trans(data);\n  arma::rowvec medoid_indices(n_medoids);\n  FastPAM1::build_fastpam1(data, medoid_indices);\n  steps = 0;\n  medoid_indices_build = medoid_indices;\n  arma::rowvec assignments(data.n_cols);\n  size_t iter = 0;\n  bool medoidChange = true;\n  while (iter < max_iter && medoidChange) {\n    auto previous{medoid_indices};\n    FastPAM1::swap_fastpam1(data, medoid_indices, assignments);\n    medoidChange = arma::any(medoid_indices != previous);\n    iter++;\n  }\n  medoid_indices_final = medoid_indices;\n  labels = assignments;\n  steps = iter;\n}\n\n/**\n * \\brief Build step for the FastPAM1 algorithm\n *\n * Runs build step for the FastPAM1 algorithm. Loops over all datapoint and\n * checks its distance from every other datapoint in the dataset, then checks if\n * the total cost is less than that of the medoid (if a medoid exists yet).\n *\n * @param data Transposed input data to cluster\n * @param medoid_indices Uninitialized array of medoids that is modified in place\n * as medoids are identified\n */\nvoid FastPAM1::build_fastpam1(\n  const arma::mat& data,\n  arma::rowvec& medoid_indices\n) {\n  size_t N = data.n_cols;\n  int p = (buildConfidence * N); // reciprocal\n  bool use_absolute = true;\n  arma::rowvec estimates(N, arma::fill::zeros);\n  arma::rowvec best_distances(N);\n  best_distances.fill(std::numeric_limits<double>::infinity());\n  arma::rowvec sigma(N); // standard deviation of induced losses on reference points\n  for (size_t k = 0; k < n_medoids; k++) {\n    double minDistance = std::numeric_limits<double>::infinity();\n    int best = 0;\n    sigma = km::KMedoids::build_sigma(\n                          data, best_distances, batchSize, use_absolute); \n    // fixes a base datapoint\n    for (int i = 0; i < data.n_cols; i++) {\n      double total = 0;\n      for (size_t j = 0; j < data.n_cols; j++) {\n        // computes distance between base and all other points\n        double cost = (this->*lossFn)(data, i, j);\n        // compares this with the cached best distance\n        if (best_distances(j) < cost) {\n          cost = best_distances(j);\n        }\n        total += cost;\n      }\n      if (total < minDistance) {\n        minDistance = total;\n        best = i;\n      }\n    }\n    medoid_indices(k) = best;\n\n    // update the medoid assignment and best_distance for this datapoint\n    for (size_t l = 0; l < N; l++) {\n        double cost = (this->*lossFn)(data, l, medoid_indices(k));\n        if (cost < best_distances(l)) {\n            best_distances(l) = cost;\n        }\n    }\n    use_absolute = false; // use difference of loss for sigma and sampling,\n                          // not absolute\n    logHelper.loss_build.push_back(minDistance/N);\n    logHelper.p_build.push_back(static_cast<float>(1)/static_cast<float>(p));\n    logHelper.comp_exact_build.push_back(N);\n  }\n}\n\n/**\n * \\brief Swap step for the FastPAM1 algorithm\n *\n * Runs swap step for the FastPAM1 algorithm. Loops over all datapoint and\n * compute the loss change when a medoid is replaced by the datapoint. The\n * loss change is stored in an array of size n_medoids and the update is\n * based on an if conditional outside of the loop. The best medoid is chosen\n * according to the best loss change.\n *\n * @param data Transposed input data to cluster\n * @param medoid_indices Array of medoid indices created from the build step\n * that is modified in place as better medoids are identified\n * @param assignments Uninitialized array of indices corresponding to each\n * datapoint assigned the index of the medoid it is closest to\n */\nvoid FastPAM1::swap_fastpam1(\n  const arma::mat& data,\n  arma::rowvec& medoid_indices,\n  arma::rowvec& assignments\n) {\n  double bestChange = 0;\n  double minDistance = std::numeric_limits<double>::infinity();\n  size_t best = 0;\n  size_t medoid_to_swap = 0;\n  size_t N = data.n_cols;\n  int p = (N * n_medoids * swapConfidence); // reciprocal\n  arma::mat sigma(n_medoids, N, arma::fill::zeros);\n  arma::rowvec best_distances(N);\n  arma::rowvec second_distances(N);\n  arma::rowvec delta_td(n_medoids, arma::fill::zeros);\n\n  // calculate quantities needed for swap, best_distances and sigma\n  km::KMedoids::calc_best_distances_swap(\n    data, medoid_indices, best_distances, second_distances, assignments);\n\n  sigma = km::KMedoids::swap_sigma(data,\n                                   batchSize,\n                                   best_distances,\n                                   second_distances,\n                                   assignments);\n  \n  // write the sigma distribution to logfile\n  km::KMedoids::sigma_log(sigma);\n  // for every point in our dataset, let it serve as a new medoid\n  for (size_t i = 0; i < data.n_cols; i++) {\n      double di = best_distances(i);\n      // loss change for making i a medoid\n      delta_td.fill(-di);\n      for (size_t j = 0; j < data.n_cols; j++) {\n          if (j != i) {\n              double dij = (this->*lossFn)(data, i, j);\n              // update loss change for the current\n              if (dij < second_distances(j)) {\n                  delta_td.at(assignments(j)) += (dij - best_distances(j));\n              } else {\n                  delta_td.at(assignments(j)) += (second_distances(j) - best_distances(j));\n              }\n              // reassignment check\n              if (dij < best_distances(j)) {\n                  // update loss change for others\n                  delta_td += (dij -  best_distances(j));\n                  // remove the update for the current\n                  delta_td.at(assignments(j)) -= (dij -  best_distances(j));\n              }\n          }\n      }\n      // choose the best medoid-to-swap\n      arma::uword min_medoid = delta_td.index_min();\n      // if the loss change is better than the best loss change\n      // update the best index identified so far\n      if (delta_td.min() < bestChange) {\n          bestChange = delta_td.min();\n          best = i;\n          medoid_to_swap = min_medoid;\n      }\n  }\n  // update the loss and medoid if the loss is improved\n  if (bestChange < 0) {\n      minDistance = arma::sum(best_distances) + bestChange;\n      medoid_indices(medoid_to_swap) = best;\n  } else {\n      minDistance = arma::sum(best_distances);\n  }\n  logHelper.loss_swap.push_back(minDistance/N);\n  logHelper.p_swap.push_back(static_cast<float>(1)/static_cast<float>(p));\n  logHelper.comp_exact_swap.push_back(N*n_medoids);\n}\n", "meta": {"hexsha": "bf084bb302d236b0f425ea3cee8663e1ecdc10da", "size": 7235, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/fastpam1.cpp", "max_stars_repo_name": "ThrunGroup/BanditPAM", "max_stars_repo_head_hexsha": "ca5c8ba2ec8227db979c3b6381c61846cf18d8ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 251.0, "max_stars_repo_stars_event_min_datetime": "2020-10-22T19:37:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T11:21:31.000Z", "max_issues_repo_path": "src/fastpam1.cpp", "max_issues_repo_name": "ThrunGroup/BanditPAM", "max_issues_repo_head_hexsha": "ca5c8ba2ec8227db979c3b6381c61846cf18d8ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 152.0, "max_issues_repo_issues_event_min_datetime": "2020-12-05T00:32:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T12:33:47.000Z", "max_forks_repo_path": "src/fastpam1.cpp", "max_forks_repo_name": "ThrunGroup/BanditPAM", "max_forks_repo_head_hexsha": "ca5c8ba2ec8227db979c3b6381c61846cf18d8ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20.0, "max_forks_repo_forks_event_min_datetime": "2021-05-07T16:31:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T13:51:54.000Z", "avg_line_length": 36.9132653061, "max_line_length": 91, "alphanum_fraction": 0.6479612992, "num_tokens": 1848, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390162, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4552722610545511}}
{"text": "#include <string>\n#include <boost/asio.hpp>\n#include <udho/router.h>\n#include <udho/logging.h>\n#include <udho/server.h>\n#include <udho/context.h>\n#include <iostream>\n#include <cmath>\n\nnamespace data{\n    \nstruct planet: udho::prepare<planet>{\n    std::string name;\n    long double radius;\n    long double mass;\n    \n    double escape_velocity() const{\n        const static long double G = 6.67L * std::pow(10L, -11L);\n        return std::sqrt((2 * G * mass) / radius);\n    }\n    \n    template <typename DictT>\n    auto dict(DictT assoc) const{\n        return assoc | var(\"planet\",  &planet::name)\n                     | var(\"radius\",  &planet::radius)\n                     | fn (\"escape\",  &planet::escape_velocity);\n    }\n};\n\nstruct person: udho::prepare<person>{\n    std::string name;\n    \n    template <typename DictT>\n    auto dict(DictT assoc) const{\n        return assoc | var(\"name\",  &person::name);\n    }\n};\n\nstruct ship: udho::prepare<ship>{\n    std::string name;\n    \n    template <typename DictT>\n    auto dict(DictT assoc) const{\n        return assoc | var(\"ship\",  &ship::name);\n    }\n};\n\n}\n\nstd::string world(udho::contexts::stateless ctx){\n    return \"{'planet': 'Earth'}\";\n}\nstd::string planet(udho::contexts::stateless ctx, std::string name){\n    data::planet planet;\n    planet.name = name;\n    \n    data::person person;\n    person.name = \"Neel Bose\";\n    \n    data::ship ship;\n    ship.name = \"Alpha Traveller\";\n    \n    return ctx.render(\"planet.html\", planet, person, ship);\n}\n\nint main(){\n    boost::asio::io_service io;\n    udho::servers::ostreamed::stateless server(io, std::cout);\n    server[udho::configs::server::template_root] = TMPL_PATH;\n    server[udho::configs::server::document_root] = WWW_PATH;\n\n    auto urls = udho::router() | \"/world\"          >> udho::get(&world).json() \n                               | \"/planet/(\\\\w+)\"  >> udho::get(&planet).html();\n\n    server.serve(urls, 9198);\n\n    io.run();\n    return 0;\n}\n\n\n", "meta": {"hexsha": "71502c77aecfe93dfd0fdef08858c522776c4d68", "size": 1956, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/view.cpp", "max_stars_repo_name": "neel/udho", "max_stars_repo_head_hexsha": "057f4c1a330d01c60b50fc1cd5d2aa57f99f2c02", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/view.cpp", "max_issues_repo_name": "neel/udho", "max_issues_repo_head_hexsha": "057f4c1a330d01c60b50fc1cd5d2aa57f99f2c02", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-11-10T11:36:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-26T14:02:14.000Z", "max_forks_repo_path": "examples/view.cpp", "max_forks_repo_name": "neel/udho", "max_forks_repo_head_hexsha": "057f4c1a330d01c60b50fc1cd5d2aa57f99f2c02", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-21T02:23:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T02:23:13.000Z", "avg_line_length": 23.8536585366, "max_line_length": 80, "alphanum_fraction": 0.5899795501, "num_tokens": 523, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4552722540038338}}
{"text": "#include <ros/ros.h>\n#include <iostream>\n#include <Eigen/Dense>\n#include <mutex>\n#include <thread>\n\n#include <tf/transform_listener.h>\n#include <tf/transform_datatypes.h>\n#include <geometry_msgs/Quaternion.h>\n#include <geometry_msgs/Twist.h>\n#include <visualization_msgs/MarkerArray.h>\n#include <nav_msgs/Path.h>\n#include <geometry_msgs/PoseStamped.h>\n#include <nav_msgs/Odometry.h>\n\n#define PI 3.1415926535\n\nstd::mutex global_mtx_;\nEigen::VectorXf start_point(6);\nEigen::VectorXf robot_localization(7);  // x y yaw liner_v angle_v liner_acc angle_acc\nstd::vector<Eigen::Vector3f> Trajectory;\n\ntf::TransformListener* listener;\nros::Publisher         vel_publisher_;\nros::Publisher         path_publisher_;\nros::Publisher         odom_publisher_;\n\nbool get_new_trajectory = false;\nbool end_flag = false;\nbool get_localization = false;\n\n/********************************************pure pursuit*********************************************/\nfloat pure_pursuit_k = 0.1;         \nfloat pure_pursuit_Lfc = 2;         \nfloat pure_pursuit_Kp = 1.0;        \nfloat dt = 0.1;                     \nfloat pure_pursuit_L = 2.7;         \nfloat pure_pursuit_liner_v = 5;   \n/*****************************************************************************************************/\n\nfloat get_yaw(const geometry_msgs::Quaternion& q){\n    tf::Quaternion quaternion;\n    tf::quaternionMsgToTF(q, quaternion);\n    double roll, pitch, yaw;\n    tf::Matrix3x3(quaternion).getRPY(roll,pitch,yaw);\n    return float(yaw);\n}\n\nfloat calculation_yaw_difference(float now_yaw, float last_yaw){\n    if(now_yaw - last_yaw > PI){\n        return (2 * PI - now_yaw + last_yaw);\n    }\n    else if( now_yaw - last_yaw < -PI){\n        return (2 * PI +now_yaw - last_yaw);\n    }\n    else{\n        return (now_yaw - last_yaw);\n    }\n}\n\nEigen::Vector2f calculation_velocity(const Eigen::Vector3f& last_pose, const Eigen::Vector3f& now_pose, float delta_time){\n    float liner_v = (now_pose.block<2,1>(0,0) - last_pose.block<2,1>(0,0)).norm() / delta_time;\n    float angle_v = calculation_yaw_difference(now_pose(2), last_pose(2)) / delta_time;\n    if(abs(liner_v) < 0.001)\n        liner_v = 0.0;\n    if(abs(angle_v) < 0.001)\n        angle_v = 0.0;\n    return Eigen::Vector2f(liner_v, angle_v);\n}\n\nEigen::Vector2f calculation_acceleration(const Eigen::Vector2f& last_v, const Eigen::Vector2f& now_v, const Eigen::Vector3f& last_pose, const Eigen::Vector3f& now_pose){\n    float x = (now_pose.block<2,1>(0,0) - last_pose.block<2,1>(0,0)).norm();\n    float yaw = calculation_yaw_difference(now_pose(2), last_pose(2));\n    float acc_x = (now_v(0) * now_v(0) - last_v(0) * last_v(0)) / (2.0 * x);\n    float acc_a = (now_v(1) * now_v(1) - last_v(1) * last_v(1)) / (2.0 * yaw);\n    if(abs(x) < 0.001)\n        acc_x = 0.0;\n    if(abs(yaw) < 0.001)\n        acc_a = 0.0;\n    return Eigen::Vector2f(acc_x, acc_a);\n}\n\nvoid odom_callback(const ros::TimerEvent&){\n\n    tf::StampedTransform transform;\n    static bool first_step = false;\n    try{\n        auto rostime = ros::Time(0);\n        if(!first_step){\n            ros::Duration(1).sleep();\n            first_step = true;\n        }\n        else\n            ros::Duration(0.1).sleep();\n        listener->lookupTransform(\"/map\",\"catvehicle/base_link\",rostime,transform);\n    }\n    catch(tf::TransformException &ex){\n        ROS_ERROR(\"%s\", ex.what());\n        return;\n    }\n\n    geometry_msgs::Quaternion q;\n    q.x = transform.getRotation().x();\n    q.y = transform.getRotation().y();\n    q.z = transform.getRotation().z();\n    q.w = transform.getRotation().w();\n\n    Eigen::Vector3f now_T(transform.getOrigin().x(), transform.getOrigin().y(), get_yaw(q));\n    static bool first_cal = true;\n    static Eigen::Vector3f history_T = now_T;\n    static Eigen::Vector2f history_velocity = Eigen::Vector2f::Zero();\n    static ros::Time t0 = ros::Time::now();\n    ros::Time t1 = ros::Time::now();\n\n    global_mtx_.lock();\n    start_point(0) = transform.getOrigin().x();\n    start_point(1) = transform.getOrigin().y();\n    start_point(2) = transform.getRotation().w();\n    start_point(3) = transform.getRotation().x();\n    start_point(4) = transform.getRotation().y();\n    start_point(5) = transform.getRotation().z();\n    if(first_cal){\n        first_cal = false;\n        global_mtx_.unlock();\n        return;\n    }\n    auto robot_velocity = calculation_velocity(history_T, now_T, (t1 - t0).toSec());\n    auto robot_acceleration = calculation_acceleration(history_velocity, robot_velocity, history_T, now_T);\n    robot_localization << now_T(0), now_T(1), now_T(2),\n                          robot_velocity(0), robot_velocity(1),\n                          robot_acceleration(0), robot_acceleration(1);\n    global_mtx_.unlock();\n    get_localization = true;\n    history_velocity = robot_velocity;\n    history_T = now_T;\n    t0 = t1;\n}\n\n//void path_callback(const visualization_msgs::MarkerArray::ConstPtr& msg){\n//\n//    if (msg->markers.size() == 0)\n//        return;\n//    global_mtx_.lock();\n//    Trajectory.clear();\n//    nav_msgs::Path path_msg;\n//    nav_msgs::Odometry odom_msg;\n//    path_msg.header.frame_id = \"/map\";\n//    path_msg.header.stamp = ros::Time::now();\n//    odom_msg.header.frame_id = \"/map\";\n//    odom_msg.header.stamp = ros::Time::now();\n//    path_publisher_.publish(path_msg);\n//    for(size_t num = 0; num < msg->markers.size(); num++){\n//        geometry_msgs::PoseStamped poses;\n//        poses.pose.position.x  = msg->markers[num].pose.position.x;\n//        poses.pose.position.y  = msg->markers[num].pose.position.y;\n//        poses.pose.orientation = msg->markers[num].pose.orientation;\n//        odom_msg.pose.pose = poses.pose;\n//        odom_publisher_.publish(odom_msg);\n//        std::this_thread::sleep_for(std::chrono::milliseconds(2000));\n//\n//        path_msg.poses.push_back(poses);\n//\n//        Trajectory.push_back(Eigen::Vector3f(msg->markers[num].pose.position.x,\n//                                             msg->markers[num].pose.position.y,\n//                                             get_yaw(msg->markers[num].pose.orientation)));\n//        std::cout << \"Trajectory : \" << Trajectory.back().transpose() << std::endl;\n//    }\n//    path_publisher_.publish(path_msg);\n//    std::reverse(Trajectory.begin(),Trajectory.end());\n//    global_mtx_.unlock();\n//    get_new_trajectory = true;\n//\n//}\nvoid path_callback(const nav_msgs::Path::ConstPtr& msg){\n\n    if (msg->poses.size() == 0)\n        return;\n    global_mtx_.lock();\n    Trajectory.clear();\n    nav_msgs::Path path_msg;\n    nav_msgs::Odometry odom_msg;\n    path_msg.header.frame_id = \"/map\";\n    path_msg.header.stamp = ros::Time::now();\n    odom_msg.header.frame_id = \"/map\";\n    odom_msg.header.stamp = ros::Time::now();\n    path_publisher_.publish(path_msg);\n    for(size_t num = 0; num < msg->poses.size(); num++){\n        geometry_msgs::PoseStamped poses;\n        poses.pose.position.x  = msg->poses[num].pose.position.x;\n        poses.pose.position.y  = msg->poses[num].pose.position.y;\n        if(num == 0)\n            poses.pose.orientation = msg->poses[num + 1].pose.orientation;\n        else\n            poses.pose.orientation = msg->poses[num].pose.orientation;\n        odom_msg.pose.pose = poses.pose;\n//        odom_publisher_.publish(odom_msg);\n//        std::this_thread::sleep_for(std::chrono::milliseconds(1000));\n        path_msg.poses.push_back(poses);\n\n        Trajectory.push_back(Eigen::Vector3f(msg->poses[num].pose.position.x,\n                                             msg->poses[num].pose.position.y,\n                                             get_yaw(msg->poses[num].pose.orientation)));\n    }\n    path_publisher_.publish(path_msg);\n    std::reverse(Trajectory.begin(),Trajectory.end());\n    global_mtx_.unlock();\n    get_new_trajectory = true;\n\n}\n\nint calculation_current_index(){\n    global_mtx_.lock();\n    Eigen::Vector3f current_state = robot_localization.block<3,1>(0,0);\n    int index = 0;\n    float diff_distance_ = 1000000.0;\n    for(size_t index_ = 0; index_ < Trajectory.size(); index_++){\n        float temp_diff_distance_ = (current_state.block<2,1>(0,0) - Trajectory[index_].block<2,1>(0,0)).norm();\n        if(temp_diff_distance_ <= diff_distance_){\n            diff_distance_ = temp_diff_distance_;\n            index = index_;\n        }\n    }\n\n    float  Lf = pure_pursuit_k * robot_localization(3) + pure_pursuit_Lfc;  // \u524d\u89c6\u8ddd\u79bb\n    float L = 0.0;\n    while(Lf > L && (index+1) < Trajectory.size()){\n        Eigen::Vector2f diff_pts = Trajectory[index+1].block<2,1>(0,0) - Trajectory[index].block<2,1>(0,0);\n        L += diff_pts.norm();\n        index++;\n    }\n    global_mtx_.unlock();\n    return index;\n}\n\nfloat calculation_control_liner_acceleration(float current_velocity){\n    global_mtx_.lock();\n    float acc = pure_pursuit_Kp * (pure_pursuit_liner_v - current_velocity);\n    global_mtx_.unlock();\n    return acc;\n}\n\nfloat calculation_control_angle_acceleration(int& current_index){\n    int index = calculation_current_index();\n    if(current_index >= index)\n        index = current_index;\n    Eigen::Vector3f current_point;\n    if(index < Trajectory.size())\n        current_point = Trajectory[index];\n    else{\n        current_point = Trajectory.back();\n        index = Trajectory.size() - 1;\n    }\n    auto diff_P = current_point - robot_localization.block<3,1>(0,0);\n    float alpha = std::atan2(diff_P.y(), diff_P.x()) - robot_localization(2);\n\n    if(robot_localization(3) < 0){\n        alpha = PI - alpha;\n    }\n    float Lf = pure_pursuit_k * robot_localization(3) + pure_pursuit_Lfc;  \n    float delta = std::atan2(2.0 * pure_pursuit_L * sin(alpha) / Lf, 1.0);\n    current_index = index;\n    static float delta_ = 0.0;\n    float return_delta_ = (delta - delta_);\n    delta_ = delta;\n    return delta;\n}\n\nvoid cmd_publish(float acc_liner, float acc_angle, float dt){\n    global_mtx_.lock();\n    float v_l = robot_localization(3) + acc_liner * dt;\n//    float v_a = robot_localization(4) + acc_angle * dt;\n     float v_a = acc_angle - robot_localization(4);\n    // float v_a = acc_angle;\n    geometry_msgs::Twist vel_cmd;\n    vel_cmd.linear.x = v_l;\n    vel_cmd.angular.z = v_a;\n    global_mtx_.unlock();\n    std::cout << \"\\e[1;33;49m >>> v_l \uff1a\" << v_l << \" v_a : \"<< v_a <<\" \\e[0m\"<< std::endl;\n//    std::cout << \"\\e[1;33;49m >>> acc_liner \uff1a\" << acc_liner << \" \\e[0m\" << std::endl;\n    vel_publisher_.publish(vel_cmd);\n}\n\nvoid zero_velocity(){\n    geometry_msgs::Twist vel_cmd;\n    vel_cmd.linear.x = 0.0;\n    vel_cmd.angular.z = 0.0;\n    vel_publisher_.publish(vel_cmd);\n}\n\nbool arrived_goal(){\n    std::cout << \"\\e[1;33;49m >>> to the goal\" << (Trajectory.back().block<2,1>(0,0) - robot_localization.block<2,1>(0,0)).norm() << \"m \\e[0m\"<< std::endl;\n    if((Trajectory.back().block<2,1>(0,0) - robot_localization.block<2,1>(0,0)).norm() < 1.0) {\n        std::cout << \"\\e[1;33;49m >>> reached! \\e[0m\"<< std::endl;\n        return true;\n    }\n    else\n        return false;\n}\n\nvoid pure_pursuit(){\n    while(true){\n        std::cout << \"\\e[1;33;49m >>> wait for the path\\e[0m\"<< std::endl;\n        while(true) {\n            if(end_flag)\n                break;\n            if (get_new_trajectory && get_localization) {\n                std::cout << \"\\e[1;33;49m >>> new path! \\e[0m\"<< std::endl;\n                get_new_trajectory = false;\n                break;\n            }\n            std::this_thread::sleep_for(std::chrono::milliseconds(100));\n        }\n        std::cout << \"\\e[1;33;49m >>> tracking \\e[0m\"<< std::endl;\n        int index = calculation_current_index();\n        ros::Time t_0 = ros::Time::now();\n        std::cout << \"\\e[1;33;49m >>> Trajectory.size() : \"<< Trajectory.size() << \"\\e[0m\"<< std::endl;\n        std::cout << \"\\e[1;33;49m >>> index : \"<< index << \"\\e[0m\"<< std::endl;\n        if(Trajectory.size() == 0)\n            continue;\n        while(index < Trajectory.size() - 1){\n            if(arrived_goal()) {\n                zero_velocity();\n                break;\n            }\n            if(get_new_trajectory)\n                break;\n            index = calculation_current_index();\n            std::cout << \"\\e[1;33;49m >>> index : \"<< index << \"\\e[0m\"<< std::endl;\n            std::cout << \"\\e[1;33;49m >>> Trajectory(index) : \"<< Trajectory[index].transpose() << \"\\e[0m\"<< std::endl;\n            std::cout << \"\\e[1;33;49m >>> robot_localization : \"<< robot_localization.transpose() << \"\\e[0m\"<< std::endl;\n            float acc_liner = calculation_control_liner_acceleration(robot_localization(3));\n            float acc_angle = calculation_control_angle_acceleration(index);\n            ros::Time t_1 = ros::Time::now();\n            float delta_t = (t_1 - t_0).toSec();\n            cmd_publish(acc_liner, acc_angle, delta_t);\n            t_0 = t_1;\n            std::this_thread::sleep_for(std::chrono::milliseconds(100));\n        }\n        zero_velocity();\n\n        if(end_flag)\n            break;\n    }\n}\n\nint main(int argc, char **argv) {\n\n    ros::init(argc, argv, \"pure_pursuit\");\n    ros::NodeHandle nh(\"~\");\n\n    tf::TransformListener listener_;\n    listener = &listener_;\n\n//    ros::Subscriber path_sub =  nh.subscribe<visualization_msgs::MarkerArray>(\"/new_path_vehicle_node\", 100, &path_callback);\n    ros::Subscriber path_sub =  nh.subscribe<nav_msgs::Path>(\"/new_path\", 100, &path_callback);\n\n    vel_publisher_ = nh.advertise<geometry_msgs::Twist>(\"/catvehicle/cmd_vel_safe\", 1);\n    path_publisher_= nh.advertise<nav_msgs::Path>(\"/visual_path\",1, true);\n    odom_publisher_= nh.advertise<nav_msgs::Odometry>(\"/odom_path\",1, true);\n\n    ros::Timer      odom_timer = nh.createTimer(ros::Duration(0.1), &odom_callback);\n\n    std::thread pure_pursuit_thread(pure_pursuit);\n    pure_pursuit_thread.detach();\n\n    ros::spin();\n    end_flag = true;\n    zero_velocity();\n    std::this_thread::sleep_for(std::chrono::milliseconds(2000));\n    return 0;\n}\n", "meta": {"hexsha": "a41cece5bbb2897ec7b4b83d418cc5fbcd6cc88c", "size": 13852, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "motion_planning/ugv_planning/pure_pursuit/src/main.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": "motion_planning/ugv_planning/pure_pursuit/src/main.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": "motion_planning/ugv_planning/pure_pursuit/src/main.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.2365591398, "max_line_length": 169, "alphanum_fraction": 0.6076378862, "num_tokens": 3703, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118111485245, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.45519361239335626}}
{"text": "/* vim: set sw=4 sts=4 et foldmethod=syntax : */\n\n#include <gcs/constraints/linear_equality.hh>\n#include <gcs/problem.hh>\n#include <gcs/solve.hh>\n\n#include <cstdlib>\n#include <iostream>\n#include <string>\n#include <vector>\n\n#include <boost/program_options.hpp>\n\nusing namespace gcs;\n\nusing std::cerr;\nusing std::cout;\nusing std::endl;\nusing std::string;\nusing std::to_string;\nusing std::pair;\nusing std::vector;\n\nusing namespace std::literals::string_literals;\n\nnamespace po = boost::program_options;\n\nauto main(int argc, char * argv[]) -> int\n{\n    po::options_description display_options{ \"Program options\" };\n    display_options.add_options()\n        (\"help\", \"Display help information\")\n        (\"prove\", \"Create a proof\");\n\n    po::options_description all_options{ \"All options\" };\n\n    all_options.add(display_options);\n\n    po::variables_map options_vars;\n\n    try {\n        po::store(po::command_line_parser(argc, argv)\n                .options(all_options)\n                .run(), options_vars);\n        po::notify(options_vars);\n    }\n    catch (const po::error & e) {\n        cerr << \"Error: \" << e.what() << endl;\n        cerr << \"Try \" << argv[0] << \" --help\" << endl;\n        return EXIT_FAILURE;\n    }\n\n    if (options_vars.count(\"help\")) {\n        cout << \"Usage: \" << argv[0] << \" [options]\" << endl;\n        cout << endl;\n        cout << display_options << endl;\n        return EXIT_SUCCESS;\n    }\n\n    Problem p = options_vars.count(\"prove\") ? Problem{ Proof{ \"cake.opb\", \"cake.veripb\" } } : Problem{ };\n\n    // https://www.minizinc.org/doc-2.5.5/en/modelling.html#an-arithmetic-optimisation-example\n    auto banana = p.create_integer_range_variable(0_i, 100_i);\n    auto chocolate = p.create_integer_range_variable(0_i, 100_i);\n    p.post(LinearLessEqual{ Linear{ { 250_i, banana }, { 200_i, chocolate} }, 4000_i });\n    p.post(LinearLessEqual{ Linear{ { 2_i, banana } }, 6_i });\n    p.post(LinearLessEqual{ Linear{ { 75_i, banana },  { 150_i, chocolate} }, 2000_i });\n    p.post(LinearLessEqual{ Linear{ { 100_i, banana }, { 150_i, chocolate} }, 500_i });\n    p.post(LinearLessEqual{ Linear{ { 75_i, chocolate} }, 500_i });\n\n    auto profit = p.create_integer_range_variable(0_i, 107500_i, \"profit\");\n    p.post(LinearEquality{ Linear{ { 400_i, banana }, { 450_i, chocolate }, { -1_i, profit } }, 0_i });\n\n    auto loss = p.create_integer_range_variable(-107500_i, 0_i, \"loss\");\n    p.post(LinearEquality{ Linear{ { 1_i, profit }, { 1_i, loss } }, 0_i });\n\n    p.branch_on(vector<IntegerVariableID>{ banana, chocolate });\n    p.minimise(loss);\n    auto stats = solve(p, [&] (const State & s) -> bool {\n            cout << \"banana cakes = \" << s(banana) << \", chocolate cakes = \" << s(chocolate) << \", profit = \" << s(profit) << endl;\n            return true;\n            });\n\n    cout << stats;\n\n    return EXIT_SUCCESS;\n}\n\n", "meta": {"hexsha": "5df8f89a0f73914cfec3d2ee62197fd44152539e", "size": 2844, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/cake/cake.cc", "max_stars_repo_name": "ciaranm/glasgow-constraint-solver", "max_stars_repo_head_hexsha": "39d925c776474743a51a80492585db3a07801908", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-08-13T11:36:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T11:13:04.000Z", "max_issues_repo_path": "examples/cake/cake.cc", "max_issues_repo_name": "ciaranm/glasgow-constraint-solver", "max_issues_repo_head_hexsha": "39d925c776474743a51a80492585db3a07801908", "max_issues_repo_licenses": ["MIT"], "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/cake/cake.cc", "max_forks_repo_name": "ciaranm/glasgow-constraint-solver", "max_forks_repo_head_hexsha": "39d925c776474743a51a80492585db3a07801908", "max_forks_repo_licenses": ["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.9550561798, "max_line_length": 131, "alphanum_fraction": 0.6227144866, "num_tokens": 771, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118111485244, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.4551936123933562}}
{"text": "#include <algorithm>\n#include <cmath>\n#include <iostream>\n#include <map>\n#include <string>\n#include <vector>\n\n#include <Eigen/Dense>\n#include <unsupported/Eigen/MatrixFunctions>\nusing namespace Eigen;\n\n#include \"lstm/network.hpp\"\n#include \"util.hpp\"\n\nint main() {\n    // load data\n    std::vector<std::vector<std::string>> X_train, y_train, X_dev, y_dev, X_test, y_test;\n    util::load_dataset(X_train, \"data/train/src.txt\");\n    util::load_dataset(y_train, \"data/train/tgt.txt\");\n    util::load_dataset(X_dev, \"data/dev/src.txt\");\n    util::load_dataset(y_dev, \"data/dev/tgt.txt\");\n    util::load_dataset(X_test, \"data/test/src.txt\");\n    util::load_dataset(y_test, \"data/test/tgt.txt\");\n\n    // create vocabs\n    std::map<std::string, int> word_to_idx;\n    std::map<int, std::string> idx_to_word;\n    util::generate_vocabs(X_train, word_to_idx, idx_to_word);\n\n    std::cout << \"Vocabulary (idx: token) with \" << word_to_idx.size() << \" tokens\" << std::endl;\n    std::cout << \"--------------------------------------\" << std::endl;\n    for (const auto &p : idx_to_word) {\n        std::cout << p.first << \": \" << p.second << std::endl;\n    }\n\n    // create LSTM network\n    // nn::LSTMCell lstm(128, 64, 64);\n    nn::LSTMNetwork lstm(4, 128, 10, 32, 64);\n    MatrixXf input(64, 10);\n    input.setRandom();\n\n    // train the model\n    MatrixXf probs = lstm(input);\n    std::cout << probs.rows() << \"x\" << probs.cols() << std::endl;\n\n    return 0;\n}", "meta": {"hexsha": "75fe28c9c092714403ef883d59ad436c20cac2cd", "size": 1446, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "pskrunner14/lstm-from-scratch", "max_stars_repo_head_hexsha": "df61ded892ae7ef576a0c7cc572f6375dd13c99b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-04-18T04:00:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-15T09:48:40.000Z", "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "pskrunner14/lstm-from-scratch", "max_issues_repo_head_hexsha": "df61ded892ae7ef576a0c7cc572f6375dd13c99b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-05-23T06:59:28.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-23T06:59:28.000Z", "max_forks_repo_path": "main.cpp", "max_forks_repo_name": "pskrunner14/lstm-from-scratch", "max_forks_repo_head_hexsha": "df61ded892ae7ef576a0c7cc572f6375dd13c99b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-01-02T00:16:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-31T01:39:40.000Z", "avg_line_length": 30.7659574468, "max_line_length": 97, "alphanum_fraction": 0.6175656985, "num_tokens": 412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706735, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.4551936029901657}}
{"text": "\n#include \"nonlinear_elastic_energy.hpp\"\n#include <Eigen/Dense>\n\nusing namespace std;\nusing namespace Eigen;\n\n\n\nvoid NonlinearElasticEnergy::precompute(const TriMesh& mesh)\n{\n    elements_.resize(mesh.f.rows());\n\n    Mat3x2d selector;\n    selector << 0.0, 0.0,\n                1.0, 0.0,\n                0.0, 1.0;\n\n    for (int idx=0; idx<mesh.f.rows(); idx++) {\n        int i0 = mesh.f(idx, 0);\n        int i1 = mesh.f(idx, 1);\n        int i2 = mesh.f(idx, 2);\n\n        Mat2d Dm;\n        Dm.col(0) = mesh.u.segment<2>(2*i1) - mesh.u.segment<2>(2*i0);\n        Dm.col(1) = mesh.u.segment<2>(2*i2) - mesh.u.segment<2>(2*i0);\n\n        const Real A = 0.5 * (Vec3d() << Dm.col(0), 0.0).finished().cross(\n                             (Vec3d() << Dm.col(1), 0.0).finished()).norm();\n\n        elements_[idx].A = A;\n\n        for (size_t i=0; i<2; i++)\n            elements_[idx].edgeLengths[i] = Dm.col(i).norm();\n\n        Mat3d P;\n        P <<   1.0,   1.0,   1.0,\n            mesh.u[2*i0], mesh.u[2*i1], mesh.u[2*i2],\n            mesh.u[2*i0+1], mesh.u[2*i1+1], mesh.u[2*i2+1];\n\n        // 2x3 matrix containing the gradients of the\n        // 3 shape functions (one for each node)\n        elements_[idx].Bm = A * (P.inverse() * selector).transpose();\n\n        elements_[idx].DmInverse = Dm.inverse();\n\n        Mat2d DmI = elements_[idx].DmInverse;\n        elements_[idx].dFdu = MatrixXd::Zero(6,9);\n        elements_[idx].dFdu << -DmI(0,0)-DmI(1,0), 0.0, 0.0, DmI(0,0), 0.0, 0.0, DmI(1,0), 0.0, 0.0,\n                               -DmI(0,1)-DmI(1,1), 0.0, 0.0, DmI(0,1), 0.0, 0.0, DmI(1,1), 0.0, 0.0,\n                                0.0, -DmI(0,0)-DmI(1,0), 0.0, 0.0, DmI(0,0), 0.0, 0.0, DmI(1,0), 0.0,\n                                0.0, -DmI(0,1)-DmI(1,1), 0.0, 0.0, DmI(0,1), 0.0, 0.0, DmI(1,1), 0.0,\n                                0.0, 0.0, -DmI(0,0)-DmI(1,0), 0.0, 0.0, DmI(0,0), 0.0, 0.0, DmI(1,0),\n                                0.0, 0.0, -DmI(0,1)-DmI(1,1), 0.0, 0.0, DmI(0,1), 0.0, 0.0, DmI(1,1);\n\n    }\n}\n\nvoid NonlinearElasticEnergy::getForceAndHessian(const TriMesh& mesh,\n                                                const VecXd& x,\n                                                VecXd& F,\n                                                SparseMatrixd& dFdx,\n                                                SparseMatrixd& dFdv) const {\n    assert(F.size() >= x.size());\n\n    for (int idx=0; idx<mesh.f.rows(); idx++) {\n        // We are assuming that poisson ratio is 0.0, and thus, lambda = 0.0\n        // Convert (E,v) (Young's modulus and poisson ratio) to lame parameters\n        Real mu = ksx_ * 0.5;\n\n        int idxs[3] = { mesh.f(idx,0), mesh.f(idx,1), mesh.f(idx,2) };\n\n        Mat3x2d Dw;\n        for (int i=0; i<2; i++) {\n            Dw.col(i) = x.segment<3>(3*idxs[i+1]) - x.segment<3>(3*idxs[0]);\n        }\n\n        Vec2d ls = Dw.colwise().norm();\n        for (int i=0; i<2; i++) {\n            if (ls[i] > 2.5 * elements_[idx].edgeLengths[i]) {\n                Dw.col(i) *= 2.5 * elements_[idx].edgeLengths[i] / ls[i];\n            }\n        }\n\n        // Compute the deformation gradient Fdg,\n        // 1st and 2nd Piola-Kirchoff stress tensors (S and P)\n        Mat3x2d Fdg = Dw * elements_[idx].DmInverse;\n\tMat2d     S = mu * (Fdg.transpose() * Fdg - Mat2d::Identity());\n        Mat3x2d   P = Fdg * S;\n\n        // Force is the 2nd P-K stress projected onto the node\n        for (int i=0; i<3; i++) {\n            F.segment<3>(3*idxs[i]).noalias() -= P * elements_[idx].Bm.col(i);\n        }\n\n        S = clampMatrixEigenvalues(S);\n\n        // Derivative of 2nd P-K stress tensor w.r.t. F, the deformation gradient\n        //\n        // \\partial S11 / \\partial F = 4 mu ( F.col(0)  0 )\n        // \\partial S22 / \\partial F = 4 mu ( 0  F.col(1) )\n        // \\partial S12 / \\partial F = \\partial S21 / \\partial F = ( F.col(1)  F.col(0) )\n        Mat3x2d dSdF[4];\n        dSdF[0].col(0) = 2.0 * mu * Fdg.col(0);\n        dSdF[0].col(1) = dSdF[3].col(0) = Vec3d::Zero();\n        dSdF[3].col(1) = 2.0 * mu * Fdg.col(1);\n        dSdF[1].col(0) = dSdF[2].col(0) = mu * Fdg.col(1);\n        dSdF[1].col(1) = dSdF[2].col(1) = mu * Fdg.col(0);\n\n        const Mat2x3d& dN = elements_[idx].Bm;\n\n        // TODO: Work out compact expressions that take advantage of dFdu_jk only having one\n        // non-zero row. The row is also a function of DmInverse above. No need to pre-compute more.\n        Vec3d fi_jk;\n        Mat2d dSdu_jk;\n        for (size_t i=0; i<3; ++i)\n        {\n            for (size_t j=0; j<3; ++j)\n            {\n                for (size_t k=0; k<3; ++k) // \\partial f_i / \\partial u_j^k\n                {\n                    // 3 x 2 matrix that is the derivative of F with respect to u_j^k\n                    //\n                    Mat3x2d dFdu_jk = elements_[idx].dFdu.block<2,3>(2*k, 3*j).transpose();\n\n                    for (size_t l=0; l<2; ++l)\n                        for (size_t m=0; m<2; ++m)\n                            dSdu_jk(l,m) = (dSdF[2*l+m].array() * dFdu_jk.array()).sum();\n\n                    // Force on vertex i is f_i = F P dN_i, so\n                    // derivative w.r.t. DOF u_j^k (j-th vertex, k-th DOF) is:\n                    //\n                    // \\partial f_i / \\partial u_j^k =\n                    //     ( \\partial F / \\partial u_j^k S + F \\partial S / \\partial u_j^k ) dN_i\n                    fi_jk = (dFdu_jk * S + Fdg * dSdu_jk) * dN.col(i);\n\n                    for (size_t l=0; l<3; ++l)\n                        //J.coeffRef(3*idxs[j]+k, 3*idxs[i]+l) += fi_jk[l];\n                        dFdx.coeffRef(3*idxs[i]+l, 3*idxs[j]+k) -= fi_jk[l];\n                }\n            }\n        }\n    }\n}\n\nMat2d NonlinearElasticEnergy::clampMatrixEigenvalues(Mat2d &input) const {\n    static const Real eps = 1.0e-6;\n\n    SelfAdjointEigenSolver<Mat2d> ev(input);\n    assert(ev.info() == Success);\n\n    return (ev.eigenvectors() *\n            ev.eigenvalues().cwiseMax(eps).asDiagonal() *\n            ev.eigenvectors().transpose());\n}\n\nvoid NonlinearElasticEnergy::getHessianPattern(const TriMesh& mesh, vector<SparseTripletd> &triplets) const {\n    for (int idx=0; idx<mesh.f.rows(); idx++) {\n        int idxs[3] = { mesh.f(idx,0), mesh.f(idx,1), mesh.f(idx,2) };\n        for (size_t j=0; j<3; ++j)\n            for (size_t k=0; k<3; ++k)\n                for (size_t l=0; l<3; ++l)\n                    for (size_t n=0; n<3; ++n)\n                        triplets.push_back(SparseTripletd(3*idxs[j]+l,3*idxs[k]+n, 1.0));\n    }\n}\n\n", "meta": {"hexsha": "eca56b876c0d678e49f711cf5c535198da66c7a1", "size": 6490, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/nonlinear_elastic_energy.cpp", "max_stars_repo_name": "liuwei792966953/stitch", "max_stars_repo_head_hexsha": "108e3dbd3410331c741c7cb166f93bbffa11b369", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-23T05:20:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-23T05:20:09.000Z", "max_issues_repo_path": "src/nonlinear_elastic_energy.cpp", "max_issues_repo_name": "liuwei792966953/stitch", "max_issues_repo_head_hexsha": "108e3dbd3410331c741c7cb166f93bbffa11b369", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/nonlinear_elastic_energy.cpp", "max_forks_repo_name": "liuwei792966953/stitch", "max_forks_repo_head_hexsha": "108e3dbd3410331c741c7cb166f93bbffa11b369", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.630952381, "max_line_length": 109, "alphanum_fraction": 0.4733436055, "num_tokens": 2329, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.45519360299016565}}
{"text": "// Main code for peak bagging by means of nested sampling analysis\r\n// Created by Enrico Corsaro @ INAF-OACT - August 2019\r\n// e-mail: emncorsaro@gmail.com\r\n// Source code file \"Asymptotic.cpp\"\r\n\r\n#include <cstdlib>\r\n#include <iostream>\r\n#include <iomanip>\r\n#include <fstream>\r\n#include <Eigen/Dense>\r\n#include \"Functions.h\"\r\n#include \"File.h\"\r\n#include \"MultiEllipsoidSampler.h\"\r\n#include \"KmeansClusterer.h\"\r\n#include \"EuclideanMetric.h\"\r\n#include \"Prior.h\"\r\n#include \"UniformPrior.h\"\r\n#include \"NormalLikelihood.h\"\r\n#include \"RadialModesPatternModel.h\"\r\n#include \"NonRadialModesPatternModel.h\"\r\n#include \"PowerlawReducer.h\"\r\n#include \"Results.h\"\r\n#include \"Ellipsoid.h\"\r\n#include \"PrincipalComponentProjector.h\"\r\n\r\nint main(int argc, char *argv[])\r\n{\r\n    // Check number of arguments for main function\r\n   \r\n    if (argc != 8)\r\n    {\r\n        cerr << \"Usage: ./asymptotic <Catalog ID> <Star ID> <output sub-directory> <run number> <input prior base filename> \"\r\n                \"<input nuMax> <input angular degree>\" << endl;\r\n        exit(EXIT_FAILURE);\r\n    }\r\n\r\n    \r\n    // ---------------------------\r\n    // ----- Read input data -----\r\n    // ---------------------------\r\n\r\n    unsigned long Nrows;\r\n    int Ncols;\r\n    ArrayXXd data;\r\n    string CatalogID(argv[1]);\r\n    string StarID(argv[2]);\r\n    string runNumber(argv[4]);\r\n    string inputPriorBaseName(argv[5]);\r\n    string inputNuMax(argv[6]);\r\n    string inputDegree(argv[7]);\r\n    double nuMax = stod(inputNuMax);\r\n    int angularDegree = stoi(inputDegree);\r\n\r\n\r\n    // Read the local path for the working session from an input ASCII file\r\n    ifstream inputFile;\r\n    File::openInputFile(inputFile, \"localPath.txt\");\r\n    File::sniffFile(inputFile, Nrows, Ncols);\r\n    vector<string> myLocalPath;\r\n    myLocalPath = File::vectorStringFromFile(inputFile, Nrows);\r\n    inputFile.close();\r\n\r\n\r\n    // Set up some string paths used in the computation\r\n    string outputSubDirName(argv[3]);\r\n    string baseOutputDirName = myLocalPath[0] + \"results/\" + CatalogID + StarID + \"/\";\r\n    string outputDirName = baseOutputDirName + outputSubDirName + \"/\";\r\n    string outputPathPrefix = outputDirName + runNumber + \"/asymptotic_\";\r\n    string baseInputDirName = baseOutputDirName + outputSubDirName + \"/data/\";\r\n    string inputFileName = baseOutputDirName + outputSubDirName + \"/data/\" + runNumber + \".txt\";\r\n\r\n    cout << \"------------------------------------------------------ \" << endl;\r\n    cout << \" Performing asymptotic fit for l = \" + inputDegree + \" modes in \" + CatalogID + StarID << endl;\r\n    cout << \"------------------------------------------------------ \" << endl;\r\n\r\n\r\n    // Read the input dataset\r\n    File::openInputFile(inputFile, inputFileName);\r\n    File::sniffFile(inputFile, Nrows, Ncols);\r\n    data = File::arrayXXdFromFile(inputFile, Nrows, Ncols);\r\n    inputFile.close();\r\n\r\n\r\n    // Creating frequency and PSD arrays\r\n    ArrayXd covariates = data.col(0);\r\n    ArrayXd observations = data.col(1);\r\n    ArrayXd uncertainties = data.col(2);\r\n\r\n\r\n    // -------------------------------------------------------\r\n    // ----- First step. Set up all prior distributions ------\r\n    // -------------------------------------------------------\r\n    \r\n    unsigned long Nparameters;              // Number of parameters for which prior distributions are defined\r\n\r\n    // ---- Read prior hyper parameters for resolved modes -----\r\n    inputFileName = outputDirName + inputPriorBaseName + \"_\" + runNumber + \".txt\";\r\n    File::openInputFile(inputFile, inputFileName);\r\n    File::sniffFile(inputFile, Nparameters, Ncols);\r\n    ArrayXXd hyperParameters;\r\n  \r\n    if (Ncols == 1)\r\n    {\r\n        Ncols = 3;\r\n        hyperParameters.conservativeResize(Nparameters,Ncols);\r\n    }\r\n\r\n    hyperParameters = File::arrayXXdFromFile(inputFile, Nparameters, Ncols);\r\n    inputFile.close();\r\n    \r\n    ArrayXd hyperParametersMinima = hyperParameters.col(0);\r\n    ArrayXd hyperParametersMaxima = hyperParameters.col(1);\r\n    // ---------------------------------------------------------\r\n\r\n    int Ndimensions = Nparameters;              // Total number of dimensions of the peak bagging model\r\n\r\n    if (angularDegree == 0)\r\n    {\r\n        if (Nparameters != 3)\r\n        {\r\n            cerr << \"Wrong number of input prior hyper-parameters.\" << endl;\r\n            cerr << \"When performing an asymptotic fit for radial modes, three lines are \" << endl;\r\n            cerr << \"expected from the input prior list (1 - DeltaNu, 2 - epsilon, 3 - alpha).\" << endl;\r\n        }\r\n    }\r\n    else\r\n    {\r\n        if (Nparameters != 5)\r\n        {\r\n            cerr << \"Wrong number of input prior hyper-parameters.\" << endl;\r\n            cerr << \"When performing an asymptotic fit for radial modes, five lines are \" << endl;\r\n            cerr << \"expected from the input prior list (1 - DeltaNu, 2 - epsilon, 3 - deltaNu0Degree, 4 - alpha, 5 - beta).\" << endl;\r\n        }\r\n    }\r\n\r\n\r\n    // Uniform Prior\r\n    \r\n    int NpriorTypes = 1;                                        // Total number of prior types included in the computation\r\n    vector<Prior*> ptrPriors(NpriorTypes);\r\n    \r\n    double DeltaNu = 0;\r\n    double epsilon = 0;\r\n    double alpha = -99;\r\n    double beta = -99;\r\n    ArrayXd parametersMinima;                      // Minima for prior PDF\r\n    ArrayXd parametersMaxima;                      // Maxima for prior PDF\r\n\r\n    if (angularDegree == 0)\r\n    {\r\n        parametersMinima.resize(Ndimensions);\r\n        parametersMaxima.resize(Ndimensions);\r\n        parametersMinima << hyperParametersMinima;\r\n        parametersMaxima << hyperParametersMaxima;\r\n        \r\n        if (hyperParametersMinima(1) == hyperParametersMaxima(1))\r\n        {\r\n            // In this case epsilon is a fixed value. Then reduce the number\r\n            // of free parameters by 1 and remove the epsilon prior line from\r\n            // the list of input prior parameters (only Deltanu and alpha are left).\r\n\r\n            Ndimensions--;\r\n            parametersMinima.resize(Ndimensions);\r\n            parametersMaxima.resize(Ndimensions);\r\n            parametersMinima << hyperParametersMinima(0), hyperParametersMinima(2);\r\n            parametersMaxima << hyperParametersMaxima(0), hyperParametersMaxima(2); \r\n            epsilon = hyperParametersMinima(1);\r\n        }\r\n\r\n        if (hyperParametersMinima(2) == hyperParametersMaxima(2))\r\n        {\r\n            // In this case alpha is a fixed value. Then reduce the number\r\n            // of free parameters by 1 and remove the alpha prior line from\r\n            // the list of input prior parameters (only DeltaNu and epsilon, or only DeltaNu are left).\r\n\r\n            Ndimensions--;\r\n            parametersMinima.conservativeResize(Ndimensions);\r\n            parametersMaxima.conservativeResize(Ndimensions);\r\n            alpha = hyperParametersMinima(2);\r\n        }\r\n    }\r\n\r\n    if (angularDegree == 1 || angularDegree == 2 || angularDegree == 3)\r\n    {\r\n        // Here DeltaNu, epsilon are fixed parameters. Then reduce the\r\n        // number of free parameters by 2 and remove DeltaNu and epsilon\r\n        // prior lines from the list of input prior parameters.\r\n\r\n        Ndimensions = 3;\r\n        parametersMinima.resize(Ndimensions);\r\n        parametersMaxima.resize(Ndimensions);\r\n        parametersMinima << hyperParametersMinima.segment(2,Ndimensions);\r\n        parametersMaxima << hyperParametersMaxima.segment(2,Ndimensions); \r\n        DeltaNu = hyperParametersMinima(0);\r\n        epsilon = hyperParametersMinima(1);\r\n\r\n\r\n        // Check if alpha is fixed or not. If fixed, remove it from the prior\r\n        // list and set its value to the one given in the prior file.\r\n\r\n        if (hyperParametersMinima(3) == hyperParametersMaxima(3))\r\n        {\r\n            Ndimensions--;\r\n            parametersMinima.resize(Ndimensions);\r\n            parametersMaxima.resize(Ndimensions);\r\n            parametersMinima << hyperParametersMinima(2), hyperParametersMinima(4);\r\n            parametersMaxima << hyperParametersMaxima(2), hyperParametersMaxima(4);\r\n            alpha = hyperParametersMinima(3);\r\n        }\r\n\r\n\r\n        // Check if beta is fixed or not. If fixed, remove it from the prior\r\n        // list and set its value to the one given in the prior file.\r\n\r\n        if (hyperParametersMinima(4) == hyperParametersMaxima(4))\r\n        {\r\n            Ndimensions--;\r\n            parametersMinima.conservativeResize(Ndimensions);\r\n            parametersMaxima.conservativeResize(Ndimensions);\r\n            beta = hyperParametersMinima(4);\r\n        }\r\n    }\r\n\r\n    UniformPrior uniformPrior(parametersMinima, parametersMaxima);\r\n    ptrPriors[0] = &uniformPrior;\r\n    \r\n    string fullPathHyperParameters = outputPathPrefix + \"hyperParametersUniform.txt\";\r\n    uniformPrior.writeHyperParametersToFile(fullPathHyperParameters);\r\n\r\n    \r\n    // -------------------------------------------------------------------\r\n    // ---- Second step. Set up the asymptotic model ---------------------\r\n    // -------------------------------------------------------------------\r\n    \r\n    Model *model = nullptr;\r\n\r\n    if (angularDegree == 0)\r\n    {\r\n        model = new RadialModesPatternModel(covariates, nuMax, epsilon, alpha);\r\n    }\r\n   \r\n    if (angularDegree > 0)\r\n    {\r\n        model = new NonRadialModesPatternModel(covariates, angularDegree, nuMax, DeltaNu, epsilon, alpha, beta);\r\n    }\r\n    \r\n\r\n    // -----------------------------------------------------------------\r\n    // ---- Third step. Set up the likelihood function to be used ------\r\n    // -----------------------------------------------------------------\r\n    \r\n    NormalLikelihood likelihood(observations, uncertainties, *model);\r\n    \r\n\r\n    // -------------------------------------------------------------------------------\r\n    // ----- Fourth step. Set up the X-means clusterer using an Euclidean metric -----\r\n    // -------------------------------------------------------------------------------\r\n\r\n    inputFileName = outputDirName + \"Xmeans_configuringParameters.txt\";\r\n    File::openInputFile(inputFile, inputFileName);\r\n    File::sniffFile(inputFile, Nparameters, Ncols);\r\n\r\n    if (Nparameters != 2)\r\n    {\r\n        cerr << \"Wrong number of input parameters for X-means algorithm.\" << endl;\r\n        exit(EXIT_FAILURE);\r\n    }\r\n\r\n    ArrayXd configuringParameters;\r\n    configuringParameters = File::arrayXXdFromFile(inputFile, Nparameters, Ncols);\r\n    inputFile.close();\r\n    \r\n    int minNclusters = configuringParameters(0);\r\n    int maxNclusters = configuringParameters(1);\r\n    \r\n    if ((minNclusters <= 0) || (maxNclusters <= 0) || (maxNclusters < minNclusters))\r\n    {\r\n        cerr << \"Minimum or maximum number of clusters cannot be <= 0, and \" << endl;\r\n        cerr << \"minimum number of clusters cannot be larger than maximum number of clusters.\" << endl;\r\n        exit(EXIT_FAILURE);\r\n    }\r\n    \r\n    int Ntrials = 10;\r\n    double relTolerance = 0.01;     // k-means\r\n  \r\n    bool printNdimensions = false;\r\n    PrincipalComponentProjector projector(printNdimensions);\r\n    bool featureProjectionActivated = false;\r\n    EuclideanMetric myMetric;\r\n    \r\n    KmeansClusterer clusterer(myMetric, projector, featureProjectionActivated, \r\n                           minNclusters, maxNclusters, Ntrials, relTolerance); \r\n\r\n\r\n    // ---------------------------------------------------------------------\r\n    // ----- Fifth step. Configure and start nested sampling inference -----\r\n    // ---------------------------------------------------------------------\r\n\r\n    inputFileName = outputDirName + \"NSMC_configuringParameters.txt\";\r\n    File::openInputFile(inputFile, inputFileName);\r\n    File::sniffFile(inputFile, Nparameters, Ncols);\r\n    configuringParameters.setZero();\r\n    configuringParameters = File::arrayXXdFromFile(inputFile, Nparameters, Ncols);\r\n    inputFile.close();\r\n\r\n    if (Nparameters > 9 || Nparameters < 8)\r\n    {\r\n        cerr << \"Wrong number of input parameters for NSMC algorithm.\" << endl;\r\n        cerr << \"There must be either 8 or 9 parameters. In this case the last parameter is always ignored.\" << endl; \r\n        exit(EXIT_FAILURE);\r\n    }\r\n    \r\n\r\n    // Print results on the screen\r\n    \r\n    bool printOnTheScreen = true;                  \r\n\r\n\r\n    // Initial number of live points\r\n    \r\n    int initialNobjects = configuringParameters(0);\r\n\r\n    \r\n    // Minimum number of live points \r\n    \r\n    int minNobjects = configuringParameters(1);\r\n    \r\n    \r\n    // Maximum number of attempts when trying to draw a new sampling point\r\n    \r\n    int maxNdrawAttempts = configuringParameters(2);\r\n\r\n    \r\n    // The first N iterations, we assume that there is only 1 cluster\r\n    \r\n    int NinitialIterationsWithoutClustering = configuringParameters(3);\r\n\r\n    \r\n    // Clustering is only happening every N iterations.\r\n    \r\n    int NiterationsWithSameClustering = configuringParameters(4);\r\n\r\n    \r\n    // Fraction by which each axis in an ellipsoid has to be enlarged\r\n    // It can be a number >= 0, where 0 means no enlargement. configuringParameters(5)\r\n    // Calibration from Corsaro et al. (2018)\r\n    \r\n    double initialEnlargementFraction = 0.369*pow(Ndimensions,0.574);    \r\n\r\n    \r\n    // Exponent for remaining prior mass in ellipsoid enlargement fraction.\r\n    // It is a number between 0 and 1. The smaller the slower the shrinkage of the ellipsoids.\r\n    \r\n    double shrinkingRate = configuringParameters(6);        \r\n                                                                                                                    \r\n    \r\n    // Termination factor for nested sampling process.                                 \r\n    \r\n    double terminationFactor = configuringParameters(7);\r\n\r\n    \r\n    // Total maximum number of nested iterations required to carry out the computation.\r\n    // This is used only in the multi-modal approach.\r\n    \r\n    int maxNiterations = 0; \r\n    \r\n\r\n    MultiEllipsoidSampler nestedSampler(printOnTheScreen, ptrPriors, likelihood, myMetric, clusterer, \r\n                                        initialNobjects, minNobjects, initialEnlargementFraction, shrinkingRate);\r\n    \r\n    double tolerance = 1.e2;\r\n    double exponent = 0.4;\r\n    PowerlawReducer livePointsReducer(nestedSampler, tolerance, exponent, terminationFactor);\r\n\r\n    nestedSampler.run(livePointsReducer, NinitialIterationsWithoutClustering, NiterationsWithSameClustering, \r\n                      maxNdrawAttempts, terminationFactor, maxNiterations, outputPathPrefix);\r\n\r\n    nestedSampler.outputFile << \"# List of configuring parameters used for the ellipsoidal sampler and X-means\" << endl;\r\n    nestedSampler.outputFile << \"# Row #1: Minimum Nclusters\" << endl;\r\n    nestedSampler.outputFile << \"# Row #2: Maximum Nclusters\" << endl;\r\n    nestedSampler.outputFile << \"# Row #3: Initial Enlargement Fraction\" << endl;\r\n    nestedSampler.outputFile << \"# Row #4: Shrinking Rate\" << endl;\r\n    nestedSampler.outputFile << minNclusters << endl;\r\n    nestedSampler.outputFile << maxNclusters << endl;\r\n    nestedSampler.outputFile << initialEnlargementFraction << endl;\r\n    nestedSampler.outputFile << shrinkingRate << endl;\r\n    nestedSampler.outputFile << \"# Other information on the run\" << endl;\r\n    nestedSampler.outputFile << \"# Row #1: Local working path used\" << endl;\r\n    nestedSampler.outputFile << \"# Row #2: Catalog and Star ID\" << endl;\r\n    nestedSampler.outputFile << \"# Row #3: Run Directory\" << endl;\r\n    nestedSampler.outputFile << \"# Row #4: Run Number\" << endl;\r\n    nestedSampler.outputFile << \"# Row #5: nuMax (microHz)\" << endl;\r\n    nestedSampler.outputFile << \"# Row #7: angular degree (either 0, 1, 2, or 3)\" << endl;\r\n    nestedSampler.outputFile << myLocalPath[0] << endl;\r\n    nestedSampler.outputFile << CatalogID + StarID << endl;\r\n    nestedSampler.outputFile << outputSubDirName << endl;\r\n    nestedSampler.outputFile << runNumber << endl;\r\n    nestedSampler.outputFile << nuMax << endl;\r\n    nestedSampler.outputFile << angularDegree << endl;\r\n    nestedSampler.outputFile.close();\r\n\r\n\r\n    // -------------------------------------------------------\r\n    // ----- Last step. Save the results in output files -----\r\n    // -------------------------------------------------------\r\n   \r\n    Results results(nestedSampler);\r\n    results.writeParametersToFile(\"parameter\");\r\n    results.writeLogLikelihoodToFile(\"logLikelihood.txt\");\r\n    results.writePosteriorProbabilityToFile(\"posteriorDistribution.txt\");\r\n    results.writeLogEvidenceToFile(\"logEvidence.txt\");\r\n    results.writeLogMeanLiveEvidenceToFile(\"logMeanLiveEvidence.txt\");\r\n    results.writeEvidenceInformationToFile(\"evidenceInformation.txt\");\r\n    \r\n\r\n    // Print out parameter estimates only in the case of a uni-modal high-dimensional fit.\r\n\r\n    double credibleLevel = 68.3;\r\n    bool writeMarginalDistributionToFile = true;\r\n    results.writeParametersSummaryToFile(\"parameterSummary.txt\", credibleLevel, writeMarginalDistributionToFile);\r\n\r\n    cout << \"Process # \" << runNumber << \" under subdir: \" + outputSubDirName + \" has been completed.\" << endl;\r\n\r\n    return EXIT_SUCCESS;\r\n}\r\n", "meta": {"hexsha": "c7acaf6117ec1bde584bf5bdd7cbba8e23430efa", "size": 17148, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/Asymptotic.cpp", "max_stars_repo_name": "EnricoCorsaro/Asymptotic", "max_stars_repo_head_hexsha": "14fc2ba4fcc2fab31e61e51e899902eabd4efae5", "max_stars_repo_licenses": ["MIT"], "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/Asymptotic.cpp", "max_issues_repo_name": "EnricoCorsaro/Asymptotic", "max_issues_repo_head_hexsha": "14fc2ba4fcc2fab31e61e51e899902eabd4efae5", "max_issues_repo_licenses": ["MIT"], "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/Asymptotic.cpp", "max_forks_repo_name": "EnricoCorsaro/Asymptotic", "max_forks_repo_head_hexsha": "14fc2ba4fcc2fab31e61e51e899902eabd4efae5", "max_forks_repo_licenses": ["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.2535211268, "max_line_length": 135, "alphanum_fraction": 0.598612083, "num_tokens": 3632, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.4551935982885701}}
{"text": "#include \"bend_forces.h\"\n\n#include \"../adjacency.h\"\n\n#include <Eigen/Dense>\n#include <igl/edges.h>\n#include <igl/sparse_cached.h>\n#include <iostream>\n#include <iostream>\n#include <cmath>\n#include <cfloat>\n\nusing namespace std;\nusing namespace Eigen;\n\ntypedef Eigen::Triplet<double> Tri; \n\ntemplate <typename T> int sgn(T val) {\n\treturn (T(0) < val) - (val < T(0));\n}\n\n// Refer to: Discrete bending forces and their Jacobians by Tamstorf et al.\n//\n//         x0\n//         /\\\n//        /  \\\n//     e2/    \\e1\n//      /  t   \\\n//     /        \\\n//    /    e0    \\\n//  x1------------x2\t\t\n//    \\          /\n//     \\   t~   /\n//      \\      /\n//    e2~\\    /e1~\n//        \\  /\n//         \\/\n//         x3\n//\n// Edge orientation: e0,e2,e2~ point away from x1\n//                      e1,e1~ point away from x2\n// E4 keeps them in the following order: x1, x2, x0, x3\n\nBend::Bend() {}\n\nvoid Bend::init(\n\tconst double k_bend,\n\tconst double k_damping,\n\tconst MatrixXd& X,\t\t\t// in: vertex positions\n\tconst MatrixXi& T\t\t\t// in: mesh triangles\n) {\n\tthis->k_bend = k_bend;\n\tthis->k_damping = k_damping;\n\tthis->T = T;\n\tthis->n = X.rows();\n\tthis->m = T.rows();\n\n\t// create adjacency information - E4: list of 4 vertices for each face pair (each internal edge)\n\tvector< vector<int> > VF_adj;\n\tigl::edges(T, E);\n\tcreateVertexFaceAdjacencyList(T, VF_adj);\n\tcreateFaceEdgeAdjecencyList(T, E, VF_adj, FE_adj);\n\tcreateFacePairEdgeListWith4VerticeIDs(T, E, VF_adj, E4, EF6, EF_adj);\n\tthis->no_edges = E4.rows();\n\n\t// define size of output\n\tn3 = 3 * n;\n\tk_entries = no_edges * 16 * 9;\n\n\t// precompute phi and scaling coefficient\n\tphi_bar.resize(no_edges);\n\tphi_hat.resize(no_edges);\n\ta.resize(no_edges);\n\tprecompute_rest_shape(X);\n}\n\nvoid Bend::precompute_rest_shape(const MatrixXd & X) {\n\tfor (int e = 0; e < no_edges; e++) {\n\t\tif (EF_adj(e, 1) != -1) { // no boundary edge\n\t\t\t// edges\n\t\t\tVector3d e0 = X.row(E4(e, 2)) - X.row(E4(e, 1));\n\t\t\tVector3d e2 = X.row(E4(e, 0)) - X.row(E4(e, 1));\n\t\t\tVector3d e2_dot = X.row(E4(e, 3)) - X.row(E4(e, 1));\n\n\t\t\t// normals\n\t\t\tVector3d normal = e0.cross(e2).normalized();\n\t\t\tVector3d normal_dot = e2_dot.cross(e0).normalized();\n\n\t\t\t// phi of theta/2 of reference configuration\n\t\t\tMatrix3d det;\n\t\t\tdet.col(0) = normal;\n\t\t\tdet.col(1) = normal_dot;\n\t\t\tdet.col(2) = e0;\n\t\t\tphi_bar(e) = 2. * sgn(det.determinant()) * (normal - normal_dot).norm() / (normal + normal_dot).norm();\n\t\t\tphi_hat(e) = phi_bar(e);\n\n\t\t\t//area and scaling coefficient\n\t\t\tdouble a0 = 0.5 * e0.cross(e2).norm();\n\t\t\tdouble a1 = 0.5 * e0.cross(e2_dot).norm();\n\t\t\tdouble length = e0.norm();\n\t\t\ta(e) = 3. * length * length / (a0 + a1);\n\t\t}\n\t\telse {\n\t\t\tphi_bar(e) = 0;\n\t\t\tphi_hat(e) = 0;\n\t\t\ta(e) = 0;\n\t\t}\n\t}\n}\n\nvoid Bend::compute_forces(\n\tconst MatrixXd& X,\t\t\t// in: vertex positions\n\tconst double timestep,\t\t// in: delta t\n\tVectorXd& F,\t\t\t\t// out: forces\n\tSparseMatrix<double>& K,\t// out: stiffness matrix\n\tSparseMatrix<double>& D\t\t// out: damping matrix\n) {\n\tF = VectorXd::Zero(n3);\n\tvector<Tri> triK, triD;\n\ttriK.reserve(k_entries);\n\ttriD.reserve(k_entries);\n\n\t// only do calculations if k_bend != 0\n\tif (k_bend == 0) {\n\t\tK = SparseMatrix<double>(n3, n3);\t// zero matrices\n\t\tD = SparseMatrix<double>(n3, n3);\n\t\treturn; \n\t}\n\n\t// compute\n\tMatrixXd normal(m, 3);\n\tfor (int f = 0; f < m; f++) {\n\t\tVector3d e1 = X.row(T(f, 1)) - X.row(T(f, 0));\n\t\tVector3d e2 = X.row(T(f, 2)) - X.row(T(f, 0));\n\t\tnormal.row(f) = e1.cross(e2).normalized();\n\t}\n\n\tVectorXd edge_length(no_edges);\n\tVectorXd phi_d(no_edges);\n\tVectorXd psi_d(no_edges);\n\tVectorXd psi_dd(no_edges);\n\tfor (int e = 0; e < no_edges; e++) {\n\t\t// hinge edge\n\t\tVector3d e0 = X.row(E4(e, 2)) - X.row(E4(e, 1));\n\t\tedge_length(e) = e0.norm();\n\n\t\tif (EF_adj(e, 1) != -1) { // no border edge\n\t\t\tVector3d n1 = normal.row(EF_adj(e, 0));\n\t\t\tVector3d n2 = normal.row(EF_adj(e, 1));\n\n\t\t\tMatrix3d det;\n\t\t\tdet.col(0) = n1;\n\t\t\tdet.col(1) = n2;\n\t\t\tdet.col(2) = e0;\n\n\t\t\tdouble n1_plus_n2_norm = (n1 + n2).norm();\n\t\t\tdouble sec_theta_half = 2. / n1_plus_n2_norm;\n\t\t\tdouble phi = 2. * sgn(det.determinant()) * (n1 - n2).norm() / n1_plus_n2_norm;\n\t\t\tphi_d(e) = sec_theta_half * sec_theta_half;\n\t\t\tdouble phi_dd = 0.5 * phi * sec_theta_half;\n\n\t\t\tpsi_d(e) = 2. * a(e) * ( k_bend * phi_d(e) * (phi - phi_bar(e))\t\t\t\t// force\n\t\t\t\t\t\t\t    + k_damping * phi_d(e) * (phi - phi_hat(e)) / timestep );\t// damping\n\n\t\t\tpsi_dd(e) = 2. * a(e) * ( k_bend * (phi_dd * (phi - phi_bar(e)) + phi_d(e) * phi_d(e))\t\t\t\t// force\n\t\t\t\t\t\t\t\t + k_damping * (phi_dd * (phi - phi_hat(e)) + phi_d(e) * phi_d(e)) / timestep);\t// damping\n\n\t\t\t// update last phi\n\t\t\tphi_hat(e) = phi;\n\t\t} \n\t\telse {\n\t\t\tpsi_d(e) = 0;\n\t\t\tpsi_dd(e) = 0;\n\t\t}\n\t}\n\t\n\tMatrixXd cos_alpha(m,3), h_inverse(m,3);\n\tvector<MatrixXd> H_triangle(m);\n\tfor (int f = 0; f < m; f++) {\n\t\tvector<Vector3d> e(3);\n\t\te[0] = X.row(T(f, 2)) - X.row(T(f, 1));\t\t// edge opposite of v_0\n\t\te[1] = X.row(T(f, 0)) - X.row(T(f, 2));\t\t// opposite of v_1\n\t\te[2] = X.row(T(f, 1)) - X.row(T(f, 0));\t\t// opposite of v_2\n\n\t\tdouble area = 0.5 * e[0].cross(-e[2]).norm();\n\n\t\tvector<Vector3d> en(3);\n\t\tfor (int i = 0; i < 3; i++)\n\t\t\ten[i] = e[i].normalized();\t\t\t// direction is important, therefore we do not precompute them per edge earlier\n\n\t\tvector<Vector3d> edge_normal(3);\n\t\tfor (int i = 0; i < 3; i++) {\n\t\t\tcos_alpha(f, i) = -en[(i + 1) % 3].dot(en[(i + 2) % 3]);\t// angle at v_i\n\t\t\th_inverse(f, i) = 0.5 * edge_length(FE_adj[f][i]) / area;\t// height ending in v_i\n\t\t\tVector3d nt = normal.row(f).transpose();\n\t\t\tedge_normal[i] = en[i].cross(nt);\t\t\t\t\t\t\t// edge normal to edge opposite to v_i\n\t\t}\n\t\t\n\t\tvector<double> c(3);\n\t\tvector<Matrix3d> M(3), N(3), R(3);\n\t\tfor (int i = 0; i < 3; i++) {\n\t\t\tint e_id = FE_adj[f][i];\n\t\t\tM[i] = normal.row(f).transpose() * edge_normal[i].transpose();\n\t\t\tN[i] = M[i] / (edge_length(e_id) * edge_length(e_id));\n\n\t\t\tbool edge_on_boundary = EF_adj(e_id, 1) == -1;\n\t\t\tdouble sigma = edge_on_boundary ? 0. : 1.;\n\t\t\tc[i] = sigma * psi_d(e_id);\n\t\t\tR[i] = c[i] * N[i];\n\t\t}\n\n\t\tvector<double> d(3);\n\t\tfor (int i = 0; i < 3; i++) {\n\t\t\tint i_minus = (i + 2) % 3;\n\t\t\tint i_plus = (i + 1) % 3;\n\t\t\td[i] = c[i_minus] * cos_alpha(f, i_plus) + c[i_plus] * cos_alpha(f, i_minus) - c[i];\n\t\t}\n\n\t\t// calculate the stiffness matrix contribution for a single triangle\n\t\tH_triangle[f].resize(9, 9);\n\t\tfor (int i = 0; i < 3; i++) {\n\t\t\tint j = (i + 1) % 3;\n\t\t\tint k = (i + 2) % 3;\n\n\t\t\tdouble omega_ii = h_inverse(f, i) * h_inverse(f, i);\n\t\t\tMatrix3d H_ii = omega_ii * d[i] * (M[i].transpose() + M[i]) - R[j] - R[k];\n\t\t\tH_triangle[f].block(3*i, 3*i, 3, 3) = H_ii;\n\n\t\t\t// check if global orientation of edge matches with local ccw orientation -> only for matching orientations do we transpose R\n\t\t\t//\n\t\t\t//\t\t   e0\n\t\t\t//   v2 -------- v1\t\t\tOf e0 (i = 0) the first vertex in ccw order is\n\t\t\t//    \\\t\t    /\t\t\tv1 = F(f, (i+1)%3)\n\t\t\t//     \\   f   /\n\t\t\t//\te1  \\     /  e2\n\t\t\t//       \\\t /\n\t\t\t//\t\t  \\ /\n\t\t\t//        v0\n\t\t\t//\n\t\t\tint e_id = FE_adj[f][i];\n\t\t\tint first_vertex_local = T(f, j);\n\t\t\tint first_vertex_global = E(e_id, 0);\n\t\t\tMatrix3d R_local = R[k];\n\t\t\tif (first_vertex_local == first_vertex_global)\n\t\t\t\tR_local.transposeInPlace();\n\n\t\t\tdouble omega_ij = h_inverse(f, i) * h_inverse(f, j);\n\t\t\tMatrix3d H_ij = omega_ij * (d[i] * M[j].transpose() + d[j] * M[i]) + R_local;\n\t\t\tH_triangle[f].block(3 * i, 3 * j, 3, 3) = H_ij;\n\t\t\tH_triangle[f].block(3 * j, 3 * i, 3, 3) = H_ij.transpose();\n\t\t}\n\t}\n\n\tfor (int e = 0; e < no_edges; e++) {\n\t\tif (EF_adj(e, 1) != -1) { // no border edge\n\n\t\t\t// indexing\n\t\t\tint f = EF_adj(e, 0);\t\t// adjacent face 1\n\t\t\tint f_dot = EF_adj(e, 1);\t// adjacent face 2\n\n\t\t\tvector<int> f_v(3), f_dot_v(3);\t// f_v 0,1,2 corresponds to v0,v1,v2 --- f_dot_v 0,1,2 corresponds to v1,v2,v3\n\t\t\tfor (int i = 0; i < 3; i++) {\n\t\t\t\tf_v[i] = EF6(e, i);\n\t\t\t\tf_dot_v[i] = EF6(e, 3 + i);\n\t\t\t}\n\n\t\t\t// first derivative \n\t\t\tVectorXd delta_theta(12);\n\t\t\tdelta_theta.segment(0, 3) = -h_inverse(f, f_v[0]) * normal.row(f);\n\t\t\tdelta_theta.segment(3, 3) = cos_alpha(f, f_v[2]) * h_inverse(f, f_v[1]) * normal.row(f) + cos_alpha(f_dot, f_dot_v[1]) * h_inverse(f_dot, f_dot_v[0]) * normal.row(f_dot);\n\t\t\tdelta_theta.segment(6, 3) = cos_alpha(f, f_v[1]) * h_inverse(f, f_v[2]) * normal.row(f) + cos_alpha(f_dot, f_dot_v[0]) * h_inverse(f_dot, f_dot_v[1]) * normal.row(f_dot);\n\t\t\tdelta_theta.segment(9, 3) = -h_inverse(f_dot, f_dot_v[2]) * normal.row(f_dot);\n\n\t\t\tfor (int i = 0; i < 3; i++) \n\t\t\t\tfor (int v = 0; v < 4; v++) \n\t\t\t\t\tF(E4(e, v) + i * n) += -psi_d(e) * delta_theta(3*v + i);\n\n\t\t\t// second derivative\n\t\t\t// stiffness matrix\n\t\t\tMatrixXd delta_f = MatrixXd::Zero(12, 12);\n\t\t\tdelta_f -= psi_dd(e) * delta_theta * delta_theta.transpose();\t// second of two terms that build delta_f\n\n\t\t\tfor (int i = 0; i < 4; i++) {\n\t\t\t\tfor (int j = 0; j <= i; j++) {\t// go through vertice pairs i-j\n\n\t\t\t\t\tfor (int p = 0; p < 3; p++) {\t\t\t// go through x,y,z coordinates\n\t\t\t\t\t\tint q = 0;\n\t\t\t\t\t\tif (i == j) q = p;\t\t\t\t\t// for central blocks, exploit symmetry\n\t\t\t\t\t\tfor (; q < 3; q++) {\n\t\t\t\t\t\t\tif (i < 3 && j < 3) delta_f(3 * i + p, 3 * j + q) -= H_triangle[f](f_v[i] * 3 + p, f_v[j] * 3 + q);\t\t\t\t\t// contribution of first term of face f\n\t\t\t\t\t\t\tif (i > 0 && j > 0) delta_f(3 * i + p, 3 * j + q) -= H_triangle[f_dot](f_dot_v[i - 1] * 3 + p, f_dot_v[j - 1] * 3 + q);\t// contribution of first term of face f_dot\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// project onto positive eigenvalues\n\t\t\t// these 9x9 matrices are real symmetric => diagonizable (spectral theorem)\n\t\t\t// symmetry also gives orthogonal eigenvalues, therefore Eval.transpose() = Eval.inverse()\n\t\t\tSelfAdjointEigenSolver<MatrixXd> eig(-delta_f);\n\t\t\tVectorXd eigenvalues = eig.eigenvalues();\n\t\t\tif (eigenvalues.minCoeff() < -1e-10) {\n\t\t\t\tMatrixXd eigenvectors = eig.eigenvectors();\n\t\t\t\tMatrixXd S = MatrixXd::Zero(eigenvalues.rows(), eigenvalues.rows());\n\t\t\t\tfor (int s = 0; s < eigenvalues.rows(); s++)\n\t\t\t\t\tS(s, s) = eigenvalues(s) > -1e-10 ? eigenvalues(s) : 0;\n\t\t\t\tdelta_f = -eigenvectors * S * eigenvectors.transpose();\n\t\t\t}\n\n\t\t\t// create triplets\n\t\t\tfor (int i = 0; i < 4; i++) {\n\t\t\t\tfor (int j = 0; j <= i; j++) {\t// go through vertice pairs i-j\n\n\t\t\t\t\tfor (int p = 0; p < 3; p++) {\t\t\t// go through x,y,z coordinates\n\t\t\t\t\t\tint q = 0;\n\t\t\t\t\t\tif (i == j) q = p;\t\t\t\t\t// for central blocks, exploit symmetry\n\t\t\t\t\t\tfor (; q < 3; q++) {\n\t\t\t\t\t\t\tint row = E4(e, i) + p * n;\t\t// corresponds to vertex id (i) and shifted by number of vertices for y and z coordinates (p)\n\t\t\t\t\t\t\tint col = E4(e, j) + q * n;\n\t\t\t\t\t\t\tif(col <= row) triK.push_back(Tri(row, col, delta_f(3 * i + p, 3 * j + q)));\n\t\t\t\t\t\t\telse triK.push_back(Tri(col, row, delta_f(3 * i + p, 3 * j + q)));\n\t\t\t\t\t\t\t//if((i != j) || (i == j && p != q)) triK.push_back(Tri(col, row, value));\t\t\t\t\t// exploit symmetry of delta_f blocks\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// damping matrix\n\t\t\t// this is a hand-made damping matrix, that is not mentioned in the paper. Allows for bigger time steps.\n\t\t\tVectorXd D_diagonal = -2. * a(f) * k_damping * phi_d(e) * delta_theta;\n\t\t\tfor (int i = 0; i < 3; i++){\n\t\t\t\tfor (int v = 0; v < 4; v++) {\n\t\t\t\t\tint row = E4(e, v) + i * n;\n\t\t\t\t\ttriD.push_back(Tri(row, row, D_diagonal(3 * v + i)));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\n\t// build the sparse matrices from the triplets\n\tif (K_data.rows() == 0) {\n\t\tthis->K = SparseMatrix<double>(n3, n3);\n\t\tthis->D = SparseMatrix<double>(n3, n3);\n\t\tigl::sparse_cached_precompute(triK, K_data, this->K);\n\t\tigl::sparse_cached_precompute(triD, D_data, this->D);\n\t\tcout << \"initialize matrix structure\" << endl;\n\t\tK = this->K;\n\t\tD = this->D;\n\t}\n\telse {\n\t\tigl::sparse_cached(triK, K_data, this->K);\n\t\tigl::sparse_cached(triD, D_data, this->D);\n\t\tK = this->K;\n\t\tD = this->D;\n\t}\n\n\t//K.setFromTriplets(triK.begin(), triK.end());\n\t//D.setFromTriplets(triD.begin(), triD.end());\n}\n", "meta": {"hexsha": "e63296c409c3db21c7ffdda832d0daf7ebe2f90a", "size": 11624, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "toolbox/unused/bend_forces.cpp", "max_stars_repo_name": "katjawolff/custom_fit_garments", "max_stars_repo_head_hexsha": "1d6f9dcba612010bb5552201f39595f7b288b8d5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-08-15T09:28:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T10:19:09.000Z", "max_issues_repo_path": "toolbox/unused/bend_forces.cpp", "max_issues_repo_name": "katjawolff/custom_fit_garments", "max_issues_repo_head_hexsha": "1d6f9dcba612010bb5552201f39595f7b288b8d5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-24T07:16:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-24T07:16:34.000Z", "max_forks_repo_path": "toolbox/unused/bend_forces.cpp", "max_forks_repo_name": "katjawolff/custom_fit_garments", "max_forks_repo_head_hexsha": "1d6f9dcba612010bb5552201f39595f7b288b8d5", "max_forks_repo_licenses": ["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.1994459834, "max_line_length": 173, "alphanum_fraction": 0.5719201652, "num_tokens": 4261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.4551935982885701}}
{"text": "#pragma once\n\n#include <math.h>\n#include <time.h>\n#include <boost/multiprecision/gmp.hpp>\n\n#include \"FiniteFields.hpp\"\n#include \"NumberTheoreticTransform.hpp\"\n\nnamespace ligero {\n\n/**\n *  Secret Sharing Interface\n *   Handles the sharing and reconstruction of the private witness, as well as\n * support for multiple tests for inter-block, intra-block and quadratic\n * constraints\n */\nclass SecretSharingNTT {\n public:\n  /* Constructors allowing some flexibility in the choice of domains */\n  ~SecretSharingNTT() {\n    delete _smallDomain;\n    delete _largeDomain;\n  }\n  SecretSharingNTT(size_t modulusIdx, size_t lSecretLength, size_t kDegree,\n                   size_t nShares,\n                   void (*computeSmall)(uint64_t *, uint64_t const *),\n                   void (*computeLarge)(uint64_t *, uint64_t const *))\n      : modulusIdx_(modulusIdx),\n        lSecretLength_(lSecretLength),\n        kDegree_(kDegree),\n        nNumberShares_(nShares) {\n    this->dCompositeDomainSize_ = nShares;\n\n    _smallDomain = new NTT(modulusIdx, this->kDegree_, computeSmall);\n    _largeDomain = new NTT(modulusIdx, this->nNumberShares_, computeLarge);\n  };\n\n  void share(uint64_t *secret);\n  void reconstruct(uint64_t *eval, bool expanded = false);\n\n  void shareMany(uint64_t *secrets, size_t lrows);\n  void reconstructMany(uint64_t *secrets, size_t lrows);\n\n  bool degreeTest(uint64_t *eval);\n  bool zeroTest(uint64_t *eval, bool expanded = false);\n  bool zeroSumTest(uint64_t *eval);\n\n protected:\n  void padPolynominal(uint64_t *secret);\n  void padIntrablocRandomness(uint64_t *secret);\n\n  size_t modulusIdx_;\n  size_t lSecretLength_;\n  size_t kDegree_;\n  size_t nNumberShares_;\n  size_t dCompositeDomainSize_;\n\n  NTT *_smallDomain;\n  NTT *_largeDomain;\n};\n\ntemplate <typename FieldT>\nclass SecretSharingInterface : SecretSharingNTT {\n public:\n  /* Constructors allowing some flexibility in the choice of domains */\n  SecretSharingInterface(size_t modulusIdx, size_t lSecretLength,\n                         size_t kDegree, size_t nShares,\n                         void (*computeSmall)(uint64_t *, uint64_t const *),\n                         void (*computeLarge)(uint64_t *, uint64_t const *))\n      : SecretSharingNTT(modulusIdx, lSecretLength, kDegree, nShares,\n                         computeSmall, computeLarge) {\n    this->dCompositeDomainSize_ = nShares;\n  };\n\n  using SecretSharingNTT::degreeTest;\n  using SecretSharingNTT::reconstruct;\n  using SecretSharingNTT::share;\n  using SecretSharingNTT::zeroSumTest;\n  using SecretSharingNTT::zeroTest;\n\n  void share(FieldT *secret);\n  void reconstruct(FieldT *eval, bool expanded = false);\n\n  void padMany(FieldT *secrets, size_t lrows);\n  void padIntrablocRandomness(FieldT *secret);\n  void shareMany(FieldT *secrets, size_t lrows);\n  void reconstructMany(FieldT *secrets, size_t lrows);\n\n  bool degreeTest(FieldT *eval);\n  bool zeroTest(FieldT *eval, bool expanded = false);\n  bool zeroSumTest(FieldT *eval);\n  FieldT sumReconstruct(FieldT *eval);\n\n protected:\n  void padSecret(FieldT *secret);\n  void padPolynominal(FieldT *secret);\n\n  // adapter\n  std::vector<uint64_t> demote(FieldT *eval, size_t length);\n  void promote(uint64_t *eval, size_t length, FieldT *dest);\n};\n\n/** Implementation\n/*\n=============================================================================================\n */\n\n/** Pads a block to k degree with numbers generated at random from the\n * underlying field\n * @param secret witness block to be padded\n */\ntemplate <typename FieldT>\ninline void SecretSharingInterface<FieldT>::padSecret(FieldT *secret) {\n  FieldT::randomVector(secret + this->lSecretLength_,\n                       this->kDegree_ - this->lSecretLength_, true);\n}\n\n/** Pads randomness for intrabloc constraints up to degree k with zeroes\n * @param secret randomness block to be padded\n */\ntemplate <typename FieldT>\ninline void SecretSharingInterface<FieldT>::padIntrablocRandomness(\n    FieldT *secret) {\n  for (size_t i = this->lSecretLength_; i < kDegree_; i++) {\n    secret[i] = FieldT(0);\n  }\n}\n\n/** Pads polynomial coefficients from k degree to n number of shares\n * @param secret array of polynomial coefficients to be padded\n */\ntemplate <typename FieldT>\ninline void SecretSharingInterface<FieldT>::padPolynominal(FieldT *secret) {\n  for (size_t i = this->kDegree_; i < nNumberShares_; i++) {\n    secret[i] = FieldT(0);\n  }\n}\n\n/** Pads multiple blocks\n * @param secret witness blocks to be padded\n * @param lrows number of blocks\n */\ntemplate <typename FieldT>\nvoid SecretSharingInterface<FieldT>::padMany(FieldT *secret, size_t lrows) {\n  /* Add randomness for padding */\n  for (size_t i = 0; i < lrows; i++) {\n    this->padSecret(secret + i * this->nNumberShares_);\n  }\n}\n\n/** Secret-sharing interface for a block in the witness: this demotes field\n * elements into 64-bit numbers and calls the specialized 64-bit secret-sharing\n * method\n * @param secret witness block to be padded\n */\ntemplate <typename FieldT>\nvoid SecretSharingInterface<FieldT>::share(FieldT *secret) {\n  std::vector<uint64_t> secret64 = demote(secret, this->nNumberShares_);\n  this->share(&secret64[0]);\n  promote(&secret64[0], this->nNumberShares_, secret);\n}\n\n/** Reconstructs the secret corresponding to a given shared block\n * @param eval array of field elements representing a shared block\n * @param expandedDegree flag indicating that the degree of the polynomial for\n * this bloc is more than k\n */\ntemplate <typename FieldT>\nvoid SecretSharingInterface<FieldT>::reconstruct(FieldT *eval,\n                                                 bool expandedDegree) {\n  std::vector<uint64_t> eval64 = demote(eval, this->nNumberShares_);\n  this->reconstruct(&eval64[0], expandedDegree);\n  promote(&eval64[0], this->kDegree_, eval);\n}\n\n/** Demotes an array of field elements to 64-bit numbers\n * @param eval array of field elements\n * @param length length of the array to be demoted\n * @return array of demoted 64-bit numbers\n */\ntemplate <typename FieldT>\nstd::vector<uint64_t> SecretSharingInterface<FieldT>::demote(FieldT *eval,\n                                                             size_t length) {\n  std::vector<uint64_t> temp(length);\n  for (size_t idx = 0; idx < length; idx++) {\n    temp[idx] = static_cast<uint64_t>(eval[idx].getValue());\n  }\n\n  return temp;\n}\n\n/** promotes an array of 64-bit numbers to field elements\n * @param eval array of 64-bit numbers\n * @param length length of the array to be promoted\n * @param dest location of the promoted content\n */\ntemplate <typename FieldT>\nvoid SecretSharingInterface<FieldT>::promote(uint64_t *eval, size_t length,\n                                             FieldT *dest) {\n  for (size_t idx = 0; idx < length; idx++) {\n    dest[idx] = FieldT(eval[idx]);\n  }\n}\n\n/** performs low degree testing on the shared block provided\n * @param eval pointer to the shared block of field elements\n * @return boolean indicating whether the test succeeded or failed\n */\ntemplate <typename FieldT>\nbool SecretSharingInterface<FieldT>::degreeTest(FieldT *eval) {\n  std::vector<uint64_t> eval64 = demote(eval, this->nNumberShares_);\n  return this->degreeTest(&eval64[0]);\n}\n\n/** tests whether the polynomial corresponding to the shared block provided\n * evaluates to 0 on each point of the secret domain\n * @param eval pointer to the shared block of field elements\n * @param largerDegree boolean indicates whether the underlying polynomial is of\n * degree > k\n * @return boolean indicating whether the test succeeded or failed\n */\ntemplate <typename FieldT>\nbool SecretSharingInterface<FieldT>::zeroTest(FieldT *eval, bool largerDegree) {\n  std::vector<FieldT> localCopy(eval, eval + this->nNumberShares_);\n  reconstruct(&localCopy[0], largerDegree);\n\n  for (size_t i = 0; i < this->lSecretLength_; i++) {\n    if (!(localCopy[i] == FieldT(0))) return false;\n  }\n\n  return true;\n}\n\n/** tests whether the sum of the evaluations for the polynomial corresponding to\n * the shared block over all points of the secret domain is 0\n * @param eval pointer to the shared block of field elements\n * @return boolean indicating whether the test succeeded or failed\n */\ntemplate <typename FieldT>\nbool SecretSharingInterface<FieldT>::zeroSumTest(FieldT *eval) {\n  std::vector<FieldT> localCopy(eval, eval + this->nNumberShares_);\n  reconstruct(&localCopy[0], true);\n\n  FieldT sum = FieldT(0);\n  for (size_t i = 0; i < this->lSecretLength_; i++) {\n    sum += localCopy[i];\n  }\n\n  if (sum == FieldT(0))\n    return true;\n  else\n    return false;\n}\n\n/** computes and returns the sum of the evaluations for the polynomial\n * corresponding to the shared block over all points of the secret domain\n * @param eval pointer to the shared block of field elements\n * @return sum of evaluations over the secret domain\n */\ntemplate <typename FieldT>\nFieldT SecretSharingInterface<FieldT>::sumReconstruct(FieldT *eval) {\n  std::vector<FieldT> localCopy(eval, eval + this->nNumberShares_);\n  reconstruct(&localCopy[0], true);\n\n  FieldT sum = FieldT(0);\n  for (size_t i = 0; i < this->lSecretLength_; i++) {\n    sum += localCopy[i];\n  }\n\n  return sum;\n}\n\n/** performs secret-sharing for multiple blocks at once. The sharing is\n * performed in-place, i.e. the shared block will be replacing the secret in\n * memory\n * @param secret pointer to a set of private blocks of field elements\n * @param lrows total number of blocks to share\n */\ntemplate <typename FieldT>\nvoid SecretSharingInterface<FieldT>::shareMany(FieldT *secret, size_t lrows) {\n  // std::cout << \"Performing FFTs: \" << lrows << std::endl;\n  for (size_t i = 0; i < lrows; i++) {\n    share(secret + i * this->nNumberShares_);\n  }\n}\n\n/** reconstructs multiple private blocs based on the corresponding shared\n * elements at once. The sharing is performed in-place, i.e. the secrets will be\n * replacing the shared blocks in memory\n * @param eval pointer to a set of shared blocks of field elements\n * @param lrows total number of blocks to share\n */\ntemplate <typename FieldT>\nvoid SecretSharingInterface<FieldT>::reconstructMany(FieldT *eval,\n                                                     size_t lrows) {\n  for (size_t i = 0; i < lrows; i++) {\n    reconstruct(eval + i * this->nNumberShares_);\n  }\n}\n\n/** pads intrabloc randomness with zeroes from the length of a block to the\n * polynomial degree\n * @param randomness pointer to a private block of field elements\n */\nvoid SecretSharingNTT::padIntrablocRandomness(uint64_t *randomness) {\n  for (size_t i = this->lSecretLength_; i < kDegree_; i++) {\n    randomness[i] = uint64_t(0);\n  }\n}\n\n/** pads polynomial coefficients with zeroes from degree k to number of shares n\n * @param coefs pointer to the coefficients\n */\nvoid SecretSharingNTT::padPolynominal(uint64_t *coefs) {\n  for (size_t i = this->kDegree_; i < nNumberShares_; i++) {\n    coefs[i] = uint64_t(0);\n  }\n}\n\n/** secret-sharing of a demoted vector of 64-bit secrets. The secret sharing is\n * performed in place so secrets are replaced by the shared block in memory\n * @param data pointer to the demoted vector of secrets\n */\nvoid SecretSharingNTT::share(uint64_t *data) {\n  // Interpolate Poly from Secret\n  _smallDomain->inv_ntt(data);\n\n  this->padPolynominal(data);\n\n  // Evaluate Publicly Shared Data from Poly\n  _largeDomain->ntt(data);\n}\n\n/** reconstructing a secret block based on the input shared block\n * so secrets are replaced by the shared block in memory\n * @param eval point to the shared block\n * @param exapandedDegree boolean indicating whether the polynomial linked to\n * this block has a degree > k\n */\nvoid SecretSharingNTT::reconstruct(uint64_t *eval, bool expandedDegree) {\n  size_t degree = kDegree_;\n\n  // Interpolate Poly from Publicly Shared Data\n  _largeDomain->inv_ntt(eval);\n\n  // if (expandedDegree) degree = kDegree_*2;\n  // Because we evaluate on roots of unity, we can use coefs[i] - coefs[i+k]\n  // on k coefficients instead of a 2k evaluation\n  if (expandedDegree) {\n    for (size_t i = 0; i < kDegree_; i++) {\n      if (eval[i + kDegree_] > eval[i]) {\n        eval[i] = eval[i] - eval[i + kDegree_] +\n                  params<uint64_t>::P[this->modulusIdx_];\n      } else {\n        eval[i] = eval[i] - eval[i + kDegree_];\n      }\n    }\n  }\n\n  // Evaluate Poly Into Secret\n  _smallDomain->ntt(eval);\n}\n\n/** performs low degree testing on the demoted shared block provided\n * @param eval pointer to the shared block of demoted 64-bit numbers\n * @return boolean indicating whether the test succeeded or failed\n */\nbool SecretSharingNTT::degreeTest(uint64_t *eval) {\n  // Interpolate Poly from Publicly Shared Data\n  std::vector<uint64_t> localCopy(eval, eval + this->nNumberShares_);\n  _largeDomain->inv_ntt(&localCopy[0]);\n\n  for (size_t i = kDegree_; i < nNumberShares_; i++) {\n    if (!(localCopy[i] == uint64_t(0))) {\n      DBG(\"val:\" << localCopy[i] << \",degree>\" << i);\n      return false;\n    }\n  }\n\n  return true;\n}\n\n/** tests whether the polynomial corresponding to the demoted shared block\n * provided evaluates to 0 on each point of the secret domain\n * @param eval pointer to the demoted shared block of 64-bit numbers\n * @param largerDegree boolean indicates whether the underlying polynomial is of\n * degree > k\n * @return boolean indicating whether the test succeeded or failed\n */\nbool SecretSharingNTT::zeroTest(uint64_t *eval, bool largerDegree) {\n  std::vector<uint64_t> localCopy(eval, eval + this->nNumberShares_);\n  reconstruct(&localCopy[0], largerDegree);\n\n  for (size_t i = 0; i < this->lSecretLength_; i++) {\n    if (!(localCopy[i] == uint64_t(0))) return false;\n  }\n\n  return true;\n}\n\n/** tests whether the sum of the evaluations for the polynomial corresponding to\n * the demoted shared block over all points of the secret domain is 0\n * @param eval pointer to the demoted shared block of 64-bit numbers\n * @return boolean indicating whether the test succeeded or failed\n */\nbool SecretSharingNTT::zeroSumTest(uint64_t *eval) {\n  std::vector<uint64_t> localCopy(eval, eval + this->nNumberShares_);\n  reconstruct(&localCopy[0], true);\n\n  uint64_t sum = uint64_t(0);\n  for (size_t i = 0; i < this->lSecretLength_; i++) {\n    sum += localCopy[i];\n  }\n\n  if (sum == uint64_t(0))\n    return true;\n  else\n    return false;\n}\n\n/** performs secret-sharing for multiple demoted blocks at once. The sharing is\n * performed in-place, i.e. the shared block will be replacing the secret in\n * memory\n * @param secret pointer to a set of demoted private blocks of 64-bit numbers\n * @param lrows total number of blocks to share\n */\nvoid SecretSharingNTT::shareMany(uint64_t *secret, size_t lrows) {\n  // std::cout << \"Performing FFTs: \" << lrows << std::endl;\n  for (size_t i = 0; i < lrows; i++) {\n    share(secret + i * this->nNumberShares_);\n  }\n}\n\n/** reconstructs multiple private blocs based on the corresponding demoted\n * shared elements at once. The sharing is performed in-place, i.e. the secrets\n * will be replacing the shared blocks in memory\n * @param eval pointer to a set of demoted shared blocks of 64-bit numbers\n * @param lrows total number of blocks to share\n */\nvoid SecretSharingNTT::reconstructMany(uint64_t *secret, size_t lrows) {\n  for (size_t i = 0; i < lrows; i++) {\n    reconstruct(secret + i * this->nNumberShares_);\n  }\n}\n\n}  // namespace ligero\n", "meta": {"hexsha": "8ef40d12339980fcb5234ac268c6f47707f84b34", "size": 15244, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/SecretSharingNTT.hpp", "max_stars_repo_name": "JustinDrake/LigeroRSA", "max_stars_repo_head_hexsha": "5d6d05788d7d4b44f0ddb01b8221f79b4851653a", "max_stars_repo_licenses": ["Apache-2.0"], "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/SecretSharingNTT.hpp", "max_issues_repo_name": "JustinDrake/LigeroRSA", "max_issues_repo_head_hexsha": "5d6d05788d7d4b44f0ddb01b8221f79b4851653a", "max_issues_repo_licenses": ["Apache-2.0"], "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/SecretSharingNTT.hpp", "max_forks_repo_name": "JustinDrake/LigeroRSA", "max_forks_repo_head_hexsha": "5d6d05788d7d4b44f0ddb01b8221f79b4851653a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-31T15:48:20.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-31T15:48:20.000Z", "avg_line_length": 34.0267857143, "max_line_length": 93, "alphanum_fraction": 0.6989635266, "num_tokens": 3843, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117812622842, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.4551935959377722}}
{"text": "#ifndef GEOMETRY_HH\n#define GEOMETRY_HH\n\n/*!\n * \\file Geometry.hh\n * \\brief Definition of the Geometry class\n */\n\n#include <vector>\n#include <Eigen/Core>\n#include \"io/JobIStream.hh\"\n\n/*!\n * \\brief The geometry of the system\n *\n * Class Geometry hold the positions and atom types of the nuclei in the\n * system.\n */\nclass Geometry\n{\npublic:\n\t/*!\n\t * \\brief Constructor\n\t *\n\t * Create a new, empty Geometry\n\t */\n\tGeometry(): _positions(), _masses(), _charges(), _symbols() {}\n\n\t//! Return the number of atoms in the Geometry\n\tint size() const { return _positions.cols(); }\n\n\t//! Return the element symbol of atom \\a idx\n\tconst std::string& symbol(int idx) const\n\t{\n\t\tcheckIndex(idx);\n\t\treturn _symbols[idx];\n\t}\n\n\t//! Return the nuclear charges of the atoms\n\tconst Eigen::VectorXd& charges() const\n\t{\n\t\treturn _charges;\n\t}\n\t//! Return the total charge of the the nuclei\n\tdouble totalCharge() const\n\t{\n\t\treturn _charges.sum();\n\t}\n\t//! Return the energy due to mutual repulsion of the nuclei\n\tdouble nuclearRepulsion() const;\n\n\t//! Return the masses of the atoms\n\tconst Eigen::VectorXd& masses() const\n\t{\n\t\treturn _masses;\n\t}\n\n\t//! Return the position of atom \\a idx\n\tEigen::Vector3d position(int idx) const\n\t{\n\t\tcheckIndex(idx);\n\t\treturn _positions.col(idx);\n\t}\n\t//! Return tthe positions of the atoms\n\tconst Eigen::MatrixXd& positions() const\n\t{\n\t\treturn _positions;\n\t}\n\n\t//! Compute the moment of inertia tensor for this molecule\n\tEigen::Matrix3d inertia() const;\n\n\t/*!\n\t * \\brief Change the size of the Geometry\n\t *\n\t * Change the number of atoms in the Geometry to \\a n. Any information\n\t * currently in the Geometry will be lost.\n\t */\n\tvoid resize(int n)\n\t{\n\t\t_positions.resize(3, n);\n\t\t_masses.resize(n);\n\t\t_charges.resize(n);\n\t\t_symbols.resize(n);\n\t}\n\t/*!\n\t * \\brief Set an atom\n\t *\n\t * On position \\a idx in this Geometry, place an atom with element symbol\n\t * \\a symbol at position (\\a x, \\a y, \\a z). Any previous atom with the\n\t * same index will be overwritten.\n\t * \\param idx    The index of the atom in this Geometry\n\t * \\param symbol The element symbol of the atom\n\t * \\param x      The x-coordinate of the atom\n\t * \\param y      The y-coordinate of the atom\n\t * \\param z      The z-coordinate of the atom\n\t * \\exception UnknownElement throw when the element symbol\n\t *    cannot be found in the periodic table.\n\t */\n\tvoid setAtom(int idx, const std::string& symbol, double x, double y,\n\t\tdouble z);\n\t/*!\n\t * \\brief Update the position of an atom\n\t *\n\t * Set the position of the atom at index \\a idx to \\a pos.\n\t * \\param idx The index of the atom in this Geometry\n\t * \\param pos The new position of the atom\n\t */\n\tvoid setPosition(int idx, const Eigen::Vector3d& pos)\n\t{\n\t\tcheckIndex(idx);\n\t\t_positions.col(idx) = pos;\n\t}\n\t/*!\n\t * \\brief Rotate to a principal axis frame\n\t *\n\t * Shift and rotate the system so that its center of mass is located at\n\t * the origin, and its principal axes align with the \\f$x\\f$, \\f$y\\f$\n\t * and \\f$z\\f$ axes.\n\t */\n\tvoid toPrincipalAxes();\n\n\t/*!\n\t * \\brief print this Geometry\n\t *\n\t * Write a textual representation of this Geometry to output stream\n\t * \\a os.\n\t * \\param os The output stream to write to\n\t * \\return The updated output stream\n\t */\n\tstd::ostream& print(std::ostream& os) const;\n\t/*!\n\t * \\brief Read a Geometry\n\t *\n\t * Read a description of this geometry from input stream \\a is. The\n\t * geometry can be given either in XYZ coordinates, or in Z-matrix\n\t * format.\n\t * \\param is The input stream to read from\n\t * \\return The updated input stream\n\t */\n\tJobIStream& scan(JobIStream& is);\n\nprivate:\n\t//! The positions of the atoms\n\tEigen::MatrixXd _positions;\n\t//! The mass of the atoms\n\tEigen::VectorXd _masses;\n\t//! The charges of the atoms\n\tEigen::VectorXd _charges;\n\t//! The atom symbols\n\tstd::vector<std::string> _symbols;\n\n\t/*!\n\t * \\brief Check if an atom index is valid\n\t *\n\t * Check if \\a idx is a valid atom index in this Geometry. The check is\n\t * only performed if the program is compiled with the DEBUG symbol\n\t * defined.\n\t * \\param idx The atom index to check\n\t * \\exception InvalidIndex thrown when the index is out of bounds\n\t */\n#ifdef DEBUG\n\tvoid checkIndex(int idx) const\n\t{\n\t\tif (idx < 0 || idx >= size())\n\t\t\tthrow InvalidIndex(idx);\n\t}\n#else\n\tvoid checkIndex(int) const {}\n#endif\n};\n\nnamespace {\n\n/*!\n * \\brief print a Geometry\n *\n * Write a textual representation of Geometry \\a geom to output stream \\a os.\n * \\param os   The output stream to write to\n * \\param geom The Geometry to print\n * \\return The updated output stream\n */\ninline std::ostream& operator<<(std::ostream& os, const Geometry& geom)\n{\n\treturn geom.print(os);\n}\n\n/*!\n * \\brief Read a Geometry\n *\n * Read a description of a geometry from input stream \\a is and store it\n * in \\a geom. The geometry can be given either in XYZ coordinates, or in\n * Z-matrix format.\n * \\param is   The input stream to read from\n * \\param geom The Geomtery to read\n * \\return The updated input stream\n */\ninline JobIStream& operator>>(JobIStream& is, Geometry& geom)\n{\n\treturn geom.scan(is);\n}\n\n} // namespace\n\n#endif // GEOMETRY_HH\n", "meta": {"hexsha": "38e22a919d7c493d31858e9c6a021daca76a7150", "size": 5057, "ext": "hh", "lang": "C++", "max_stars_repo_path": "Geometry.hh", "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": "Geometry.hh", "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": "Geometry.hh", "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": 24.5485436893, "max_line_length": 77, "alphanum_fraction": 0.6816294246, "num_tokens": 1344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.45519271040258225}}
{"text": "#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Surface_mesh.h>\n\n#include <CGAL/Polygon_mesh_processing/triangulate_hole.h>\n#include <CGAL/Polygon_mesh_processing/border.h>\n#include <CGAL/Polygon_mesh_processing/IO/polygon_mesh_io.h>\n\n#include <CGAL/IO/PLY.h>\n\n#include <boost/lexical_cast.hpp>\n\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <set>\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel;\ntypedef Kernel::Point_3                                     Point;\ntypedef CGAL::Surface_mesh<Point>                           Mesh;\n\ntypedef boost::graph_traits<Mesh>::vertex_descriptor        vertex_descriptor;\ntypedef boost::graph_traits<Mesh>::halfedge_descriptor      halfedge_descriptor;\ntypedef boost::graph_traits<Mesh>::face_descriptor          face_descriptor;\n\nnamespace PMP = CGAL::Polygon_mesh_processing;\n\nbool is_small_hole(halfedge_descriptor h, Mesh & mesh,\n                   double max_hole_diam, int max_num_hole_edges)\n{\n  int num_hole_edges = 0;\n  CGAL::Bbox_3 hole_bbox;\n  for (halfedge_descriptor hc : CGAL::halfedges_around_face(h, mesh))\n  {\n    const Point& p = mesh.point(target(hc, mesh));\n\n    hole_bbox += p.bbox();\n    ++num_hole_edges;\n\n    // Exit early, to avoid unnecessary traversal of large holes\n    if (num_hole_edges > max_num_hole_edges) return false;\n    if (hole_bbox.xmax() - hole_bbox.xmin() > max_hole_diam) return false;\n    if (hole_bbox.ymax() - hole_bbox.ymin() > max_hole_diam) return false;\n    if (hole_bbox.zmax() - hole_bbox.zmin() > max_hole_diam) return false;\n  }\n\n  return true;\n}\n\n// Incrementally fill the holes that are no larger than given diameter\n// and with no more than a given number of edges (if specified).\n\nint main(int argc, char* argv[]) {\n\n  if (argc < 5) {\n    std::cout << \"Usage: \" << argv[0]\n              << \" max_hole_diameter max_num_hole_edges input.ply output.ply\\n\";\n    return 1;\n  }\n  \n  double max_hole_diam    = atof(argv[1]);\n  int max_num_hole_edges  = atoi(argv[2]);\n  const char* input_file  = argv[3];\n  const char* output_file = argv[4];\n\n  std::cout << \"Reading mesh:       \" << input_file << std::endl;\n  std::cout << \"Max num hole edges: \" << max_num_hole_edges << \"\\n\";\n  std::cout << \"Max hole diameter:  \" << max_hole_diam << \"\\n\";\n  \n  Mesh mesh;\n  if(!PMP::IO::read_polygon_mesh(input_file, mesh)) {\n    std::cerr << \"Invalid input.\" << std::endl;\n    return 1;\n  }\n\n  unsigned int nb_holes = 0;\n  std::vector<halfedge_descriptor> border_cycles;\n\n  // collect one halfedge per boundary cycle\n  PMP::extract_boundary_cycles(mesh, std::back_inserter(border_cycles));\n\n  for(halfedge_descriptor h : border_cycles)\n  {\n    if(max_hole_diam > 0 && max_num_hole_edges > 0 &&\n       !is_small_hole(h, mesh, max_hole_diam, max_num_hole_edges))\n      continue;\n\n    std::vector<face_descriptor>  patch_facets;\n    std::vector<vertex_descriptor> patch_vertices;\n    bool success =\n      std::get<0>(PMP::triangulate_refine_and_fair_hole(mesh,\n                                                        h,\n                                                        std::back_inserter(patch_facets),\n                                                        std::back_inserter(patch_vertices)));\n    \n    //std::cout << \"* Number of facets in constructed patch: \" << patch_facets.size() << std::endl;\n    //std::cout << \"  Number of vertices in constructed patch: \" << patch_vertices.size() << std::endl;\n    //std::cout << \"  Is fairing successful: \" << success << std::endl;\n    ++nb_holes;\n  }\n\n  //std::cout << std::endl;\n  //std::cout << nb_holes << \" holes have been filled\" << std::endl;\n\n  std::cout << \"Writing output mesh: \" << output_file << std::endl;\n  CGAL::IO::write_PLY(output_file, mesh,\n                      CGAL::parameters::stream_precision(17).use_binary_mode(false));\n\n  return 0;\n}\n", "meta": {"hexsha": "d324ed9441b6aeb05e01b4e1c40bfd384e714be9", "size": 3857, "ext": "cc", "lang": "C++", "max_stars_repo_path": "fill_holes.cc", "max_stars_repo_name": "oleg-alexandrov/cgal_tools", "max_stars_repo_head_hexsha": "edba752a4d9979bfd8d80e2f05f0422288f0136a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-04-16T17:13:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T06:52:43.000Z", "max_issues_repo_path": "fill_holes.cc", "max_issues_repo_name": "oleg-alexandrov/cgal_tools", "max_issues_repo_head_hexsha": "edba752a4d9979bfd8d80e2f05f0422288f0136a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fill_holes.cc", "max_forks_repo_name": "oleg-alexandrov/cgal_tools", "max_forks_repo_head_hexsha": "edba752a4d9979bfd8d80e2f05f0422288f0136a", "max_forks_repo_licenses": ["Apache-2.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.0636363636, "max_line_length": 103, "alphanum_fraction": 0.64920923, "num_tokens": 994, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4551927104025822}}
{"text": "/*===================================================================\n\nMSI applications for interactive analysis in MITK (M2aia)\n\nCopyright (c) Jonas Cordes\n\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt for details.\n\n===================================================================*/\n\n#include \"mitkIOUtil.h\"\n#include <algorithm>\n#include <m2Morphology.h>\n#include <m2TestingConfig.h>\n#include <mitkTestFixture.h>\n#include <mitkTestingMacros.h>\n#include <numeric>\n#include <random>\n\n//#include <boost/algorithm/string.hpp>\n\nclass m2MorphologyTestSuite : public mitk::TestFixture\n{\n  CPPUNIT_TEST_SUITE(m2MorphologyTestSuite);\n  MITK_TEST(ApplyErosion_RandomGaussianSignal_shouldReturnTrue);\n  MITK_TEST(ApplyDilatation_RandomGaussianSignal_shouldReturnTrue);\n  MITK_TEST(TopHat_RandomGaussianSignal_shouldReturnTrue);\n\n  CPPUNIT_TEST_SUITE_END();\n\n  /*\n  Signal was generated once using the following procedure\n    -----\n\tconst double mean = 1.0;\n    const double stddev = 0.33;\n    std::default_random_engine generator;\n    generator.seed(142191);\n    std::normal_distribution<double> dist(mean, stddev);\n\n    std::vector<double> signal;\n    auto it = std::inserter(signal, std::begin(signal));\n    for (int i = 0; i < 1000; ++i)\n      it = dist(generator);\n    -----\n  */\n\nprivate:\n  std::vector<double> ReadDoubleVector(const std::string &fileNameInM2aiaDir, char delim = '\\n')\n  {\n    std::vector<double> signal;\n    std::ifstream f(GetTestDataFilePath(fileNameInM2aiaDir, M2AIA_DATA_DIR));\n    std::string line;\n    while (std::getline(f, line, delim))\n    {\n      signal.push_back(std::stoi(line));\n    }\n    return signal;\n  }\n\npublic:\n  void ApplyDilatation_RandomGaussianSignal_shouldReturnTrue()\n  {\n    std::vector<double> signal = ReadDoubleVector(\"signal.data\");\n    std::vector<double> expected = ReadDoubleVector(\"dilation.result\");\n\n    std::vector<double> result(signal.size());\n    m2::Signal::Dilation(signal, 2, result);\n\n    CPPUNIT_ASSERT(std::equal(std::begin(result), std::end(result), std::begin(expected)));\n  }\n\n  void ApplyErosion_RandomGaussianSignal_shouldReturnTrue()\n  {\n    std::vector<double> signal = ReadDoubleVector(\"signal.data\");\n    std::vector<double> expected = ReadDoubleVector(\"erosion.result\");\n\n    std::vector<double> result(signal.size());\n    m2::Signal::Erosion(signal, 2, result);\n\n    CPPUNIT_ASSERT(std::equal(std::begin(result), std::end(result), std::begin(expected)));\n  }\n\n  void TopHat_RandomGaussianSignal_shouldReturnTrue()\n  {\n    std::vector<double> signal = ReadDoubleVector(\"signal.data\");\n    std::vector<double> expected = ReadDoubleVector(\"tophat.result\");\n\n    std::vector<double> result(signal.size());\n    m2::Signal::Erosion(signal, 2, result);\n    m2::Signal::Dilation(result, 2, result);\n\n    CPPUNIT_ASSERT(std::equal(std::begin(result), std::end(result), std::begin(expected)));\n  }\n};\n\nMITK_TEST_SUITE_REGISTRATION(m2Morphology)\n", "meta": {"hexsha": "d8a39f7245c7da22dedd023e991e29238b885358", "size": 3043, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Modules/M2aiaSignalProcessing/Testing/m2MorphologyTest.cpp", "max_stars_repo_name": "ivowolf/M2aia", "max_stars_repo_head_hexsha": "03cfe3495bc706cbb0b00a2916b8f0a3cb398e25", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2021-07-22T06:52:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T12:53:31.000Z", "max_issues_repo_path": "Modules/M2aiaSignalProcessing/Testing/m2MorphologyTest.cpp", "max_issues_repo_name": "ivowolf/M2aia", "max_issues_repo_head_hexsha": "03cfe3495bc706cbb0b00a2916b8f0a3cb398e25", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-07-25T22:29:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-22T13:21:30.000Z", "max_forks_repo_path": "Modules/M2aiaSignalProcessing/Testing/m2MorphologyTest.cpp", "max_forks_repo_name": "ivowolf/M2aia", "max_forks_repo_head_hexsha": "03cfe3495bc706cbb0b00a2916b8f0a3cb398e25", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-06-23T11:53:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-22T06:14:24.000Z", "avg_line_length": 29.5436893204, "max_line_length": 96, "alphanum_fraction": 0.6897798225, "num_tokens": 742, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4551927104025821}}
{"text": "#include \"quadrotor_simulator/Quadrotor.h\"\n#include \"ode/boost/numeric/odeint.hpp\"\n#include <Eigen/Geometry>\n#include <boost/bind.hpp>\n#include <iostream>\n\n#include <ros/ros.h>\nnamespace odeint = boost::numeric::odeint;\n\nnamespace QuadrotorSimulator\n{\n\nQuadrotor::Quadrotor(void)\n{\n  alpha0     = 48; // degree\n  g_         = 9.81;\n  mass_      = 0.98; // 0.5;\n  double Ixx = 2.64e-3, Iyy = 2.64e-3, Izz = 4.96e-3;\n  prop_radius_ = 0.062;\n  J_           = Eigen::Vector3d(Ixx, Iyy, Izz).asDiagonal();\n\n  kf_ = 8.98132e-9;\n  // km_ = 2.5e-9; // from Nate\n  // km = (Cq/Ct)*Dia*kf\n  // Cq/Ct for 8 inch props from UIUC prop db ~ 0.07\n  km_ = 0.07 * (3 * prop_radius_) * kf_;\n\n  arm_length_          = 0.26;\n  motor_time_constant_ = 1.0 / 30;\n  min_rpm_             = 1200;\n  max_rpm_             = 35000;\n\n  state_.x = Eigen::Vector3d::Zero();\n  // state_.x << 40.0, -60.0, 10.0;\n  state_.v         = Eigen::Vector3d::Zero();\n  state_.R         = Eigen::Matrix3d::Identity();\n  state_.omega     = Eigen::Vector3d::Zero();\n  state_.motor_rpm = Eigen::Array4d::Zero();\n\n  external_force_.setZero();\n\n  updateInternalState();\n\n  input_ = Eigen::Array4d::Zero();\n}\n\nvoid\nQuadrotor::step(double dt)\n{\n  auto save = internal_state_;\n\n  odeint::integrate(boost::ref(*this), internal_state_, 0.0, dt, dt);\n\n  for (int i = 0; i < 22; ++i)\n  {\n    if (std::isnan(internal_state_[i]))\n    {\n      std::cout << \"dump \" << i << \" << pos \";\n      for (int j = 0; j < 22; ++j)\n      {\n        std::cout << save[j] << \" \";\n      }\n      std::cout << std::endl;\n      internal_state_ = save;\n      break;\n    }\n  }\n\n  for (int i = 0; i < 3; i++)\n  {\n    state_.x(i) = internal_state_[0 + i];\n    state_.v(i) = internal_state_[3 + i];\n    state_.R(i, 0) = internal_state_[6 + i];\n    state_.R(i, 1) = internal_state_[9 + i];\n    state_.R(i, 2) = internal_state_[12 + i];\n    state_.omega(i) = internal_state_[15 + i];\n  }\n  state_.motor_rpm(0) = internal_state_[18];\n  state_.motor_rpm(1) = internal_state_[19];\n  state_.motor_rpm(2) = internal_state_[20];\n  state_.motor_rpm(3) = internal_state_[21];\n\n  // Re-orthonormalize R (polar decomposition)\n  Eigen::LLT<Eigen::Matrix3d> llt(state_.R.transpose() * state_.R);\n  Eigen::Matrix3d             P = llt.matrixL();\n  Eigen::Matrix3d             R = state_.R * P.inverse();\n  state_.R                      = R;\n\n  // Don't go below zero, simulate floor\n  if (state_.x(2) < 0.0 && state_.v(2) < 0)\n  {\n    state_.x(2) = 0;\n    state_.v(2) = 0;\n  }\n  updateInternalState();\n}\n\nvoid\nQuadrotor::operator()(const Quadrotor::InternalState& x,\n                      Quadrotor::InternalState& dxdt, const double /* t */)\n{\n  State cur_state;\n  for (int i = 0; i < 3; i++)\n  {\n    cur_state.x(i) = x[0 + i];\n    cur_state.v(i) = x[3 + i];\n    cur_state.R(i, 0) = x[6 + i];\n    cur_state.R(i, 1) = x[9 + i];\n    cur_state.R(i, 2) = x[12 + i];\n    cur_state.omega(i) = x[15 + i];\n  }\n  for (int i = 0; i < 4; i++)\n  {\n    cur_state.motor_rpm(i) = x[18 + i];\n  }\n\n  // std::cout << \"Omega: \" << cur_state.omega << std::endl;\n  // std::cout << \"motor_rpm: \" << cur_state.motor_rpm << std::endl;\n\n  // Re-orthonormalize R (polar decomposition)\n  Eigen::LLT<Eigen::Matrix3d> llt(cur_state.R.transpose() * cur_state.R);\n  Eigen::Matrix3d             P = llt.matrixL();\n  Eigen::Matrix3d             R = cur_state.R * P.inverse();\n\n  Eigen::Vector3d x_dot, v_dot, omega_dot;\n  Eigen::Matrix3d R_dot;\n  Eigen::Array4d  motor_rpm_dot;\n  Eigen::Vector3d vnorm;\n  Eigen::Array4d  motor_rpm_sq;\n  Eigen::Matrix3d omega_vee(Eigen::Matrix3d::Zero());\n\n  omega_vee(2, 1) = cur_state.omega(0);\n  omega_vee(1, 2) = -cur_state.omega(0);\n  omega_vee(0, 2) = cur_state.omega(1);\n  omega_vee(2, 0) = -cur_state.omega(1);\n  omega_vee(1, 0) = cur_state.omega(2);\n  omega_vee(0, 1) = -cur_state.omega(2);\n\n  motor_rpm_sq = cur_state.motor_rpm.array().square();\n\n  //! @todo implement\n  Eigen::Array4d blade_linear_velocity;\n  Eigen::Array4d motor_linear_velocity;\n  Eigen::Array4d AOA;\n  blade_linear_velocity = 0.104719755 // rpm to rad/s\n                          * cur_state.motor_rpm.array() * prop_radius_;\n  for (int i = 0; i < 4; ++i)\n    AOA[i]   = alpha0 -\n             atan2(motor_linear_velocity[i], blade_linear_velocity[i]) * //\n               180 / 3.14159265;\n  //! @todo end\n\n  // double totalF = kf_ * motor_rpm_sq.sum();\n  double thrust = kf_ * motor_rpm_sq.sum();\n\n  Eigen::Vector3d moments;\n  moments(0) = kf_ * (motor_rpm_sq(2) - motor_rpm_sq(3)) * arm_length_;\n  moments(1) = kf_ * (motor_rpm_sq(1) - motor_rpm_sq(0)) * arm_length_;\n  moments(2) = km_ * (motor_rpm_sq(0) + motor_rpm_sq(1) - motor_rpm_sq(2) -\n                      motor_rpm_sq(3));\n\n  double resistance = 0.1 *                                        // C\n                      3.14159265 * (arm_length_) * (arm_length_) * // S\n                      cur_state.v.norm() * cur_state.v.norm();\n\n  //  ROS_INFO(\"resistance: %lf, Thrust: %lf%% \", resistance,\n  //           motor_rpm_sq.sum() / (4 * max_rpm_ * max_rpm_) * 100.0);\n\n  vnorm = cur_state.v;\n  if (vnorm.norm() != 0)\n  {\n    vnorm.normalize();\n  }\n  x_dot = cur_state.v;\n  v_dot = -Eigen::Vector3d(0, 0, g_) + thrust * R.col(2) / mass_ +\n          external_force_ / mass_ /*; //*/ - resistance * vnorm / mass_;\n\n  acc_ = v_dot;\n  //  acc_[2] = -acc_[2]; // to NED\n\n  R_dot = R * omega_vee;\n  omega_dot =\n    J_.inverse() *\n    (moments - cur_state.omega.cross(J_ * cur_state.omega) + external_moment_);\n  motor_rpm_dot = (input_ - cur_state.motor_rpm) / motor_time_constant_;\n\n  for (int i = 0; i < 3; i++)\n  {\n    dxdt[0 + i]  = x_dot(i);\n    dxdt[3 + i]  = v_dot(i);\n    dxdt[6 + i]  = R_dot(i, 0);\n    dxdt[9 + i]  = R_dot(i, 1);\n    dxdt[12 + i] = R_dot(i, 2);\n    dxdt[15 + i] = omega_dot(i);\n  }\n  for (int i = 0; i < 4; i++)\n  {\n    dxdt[18 + i] = motor_rpm_dot(i);\n  }\n  for (int i = 0; i < 22; ++i)\n  {\n    if (std::isnan(dxdt[i]))\n    {\n      dxdt[i] = 0;\n      //      std::cout << \"nan apply to 0 for \" << i << std::endl;\n    }\n  }\n}\n\nvoid\nQuadrotor::setInput(double u1, double u2, double u3, double u4)\n{\n  input_(0) = u1;\n  input_(1) = u2;\n  input_(2) = u3;\n  input_(3) = u4;\n  for (int i = 0; i < 4; i++)\n  {\n    if (std::isnan(input_(i)))\n    {\n      input_(i) = (max_rpm_ + min_rpm_) / 2;\n      std::cout << \"NAN input \";\n    }\n    if (input_(i) > max_rpm_)\n      input_(i) = max_rpm_;\n    else if (input_(i) < min_rpm_)\n      input_(i) = min_rpm_;\n  }\n}\n\nconst Quadrotor::State&\nQuadrotor::getState(void) const\n{\n  return state_;\n}\nvoid\nQuadrotor::setState(const Quadrotor::State& state)\n{\n  state_.x         = state.x;\n  state_.v         = state.v;\n  state_.R         = state.R;\n  state_.omega     = state.omega;\n  state_.motor_rpm = state.motor_rpm;\n\n  updateInternalState();\n}\n\nvoid\nQuadrotor::setStatePos(const Eigen::Vector3d& Pos)\n{\n  state_.x = Pos;\n\n  updateInternalState();\n}\n\ndouble\nQuadrotor::getMass(void) const\n{\n  return mass_;\n}\nvoid\nQuadrotor::setMass(double mass)\n{\n  mass_ = mass;\n}\n\ndouble\nQuadrotor::getGravity(void) const\n{\n  return g_;\n}\nvoid\nQuadrotor::setGravity(double g)\n{\n  g_ = g;\n}\n\nconst Eigen::Matrix3d&\nQuadrotor::getInertia(void) const\n{\n  return J_;\n}\nvoid\nQuadrotor::setInertia(const Eigen::Matrix3d& inertia)\n{\n  if (inertia != inertia.transpose())\n  {\n    std::cerr << \"Inertia matrix not symmetric, not setting\" << std::endl;\n    return;\n  }\n  J_ = inertia;\n}\n\ndouble\nQuadrotor::getArmLength(void) const\n{\n  return arm_length_;\n}\nvoid\nQuadrotor::setArmLength(double d)\n{\n  if (d <= 0)\n  {\n    std::cerr << \"Arm length <= 0, not setting\" << std::endl;\n    return;\n  }\n\n  arm_length_ = d;\n}\n\ndouble\nQuadrotor::getPropRadius(void) const\n{\n  return prop_radius_;\n}\nvoid\nQuadrotor::setPropRadius(double r)\n{\n  if (r <= 0)\n  {\n    std::cerr << \"Prop radius <= 0, not setting\" << std::endl;\n    return;\n  }\n  prop_radius_ = r;\n}\n\ndouble\nQuadrotor::getPropellerThrustCoefficient(void) const\n{\n  return kf_;\n}\nvoid\nQuadrotor::setPropellerThrustCoefficient(double kf)\n{\n  if (kf <= 0)\n  {\n    std::cerr << \"Thrust coefficient <= 0, not setting\" << std::endl;\n    return;\n  }\n\n  kf_ = kf;\n}\n\ndouble\nQuadrotor::getPropellerMomentCoefficient(void) const\n{\n  return km_;\n}\nvoid\nQuadrotor::setPropellerMomentCoefficient(double km)\n{\n  if (km <= 0)\n  {\n    std::cerr << \"Moment coefficient <= 0, not setting\" << std::endl;\n    return;\n  }\n\n  km_ = km;\n}\n\ndouble\nQuadrotor::getMotorTimeConstant(void) const\n{\n  return motor_time_constant_;\n}\nvoid\nQuadrotor::setMotorTimeConstant(double k)\n{\n  if (k <= 0)\n  {\n    std::cerr << \"Motor time constant <= 0, not setting\" << std::endl;\n    return;\n  }\n\n  motor_time_constant_ = k;\n}\n\nconst Eigen::Vector3d&\nQuadrotor::getExternalForce(void) const\n{\n  return external_force_;\n}\nvoid\nQuadrotor::setExternalForce(const Eigen::Vector3d& force)\n{\n  external_force_ = force;\n}\n\nconst Eigen::Vector3d&\nQuadrotor::getExternalMoment(void) const\n{\n  return external_moment_;\n}\nvoid\nQuadrotor::setExternalMoment(const Eigen::Vector3d& moment)\n{\n  external_moment_ = moment;\n}\n\ndouble\nQuadrotor::getMaxRPM(void) const\n{\n  return max_rpm_;\n}\nvoid\nQuadrotor::setMaxRPM(double max_rpm)\n{\n  if (max_rpm <= 0)\n  {\n    std::cerr << \"Max rpm <= 0, not setting\" << std::endl;\n    return;\n  }\n  max_rpm_ = max_rpm;\n}\n\ndouble\nQuadrotor::getMinRPM(void) const\n{\n  return min_rpm_;\n}\nvoid\nQuadrotor::setMinRPM(double min_rpm)\n{\n  if (min_rpm < 0)\n  {\n    std::cerr << \"Min rpm < 0, not setting\" << std::endl;\n    return;\n  }\n  min_rpm_ = min_rpm;\n}\n\nvoid\nQuadrotor::updateInternalState(void)\n{\n  for (int i = 0; i < 3; i++)\n  {\n    internal_state_[0 + i]  = state_.x(i);\n    internal_state_[3 + i]  = state_.v(i);\n    internal_state_[6 + i]  = state_.R(i, 0);\n    internal_state_[9 + i]  = state_.R(i, 1);\n    internal_state_[12 + i] = state_.R(i, 2);\n    internal_state_[15 + i] = state_.omega(i);\n  }\n  internal_state_[18] = state_.motor_rpm(0);\n  internal_state_[19] = state_.motor_rpm(1);\n  internal_state_[20] = state_.motor_rpm(2);\n  internal_state_[21] = state_.motor_rpm(3);\n}\n\nEigen::Vector3d\nQuadrotor::getAcc() const\n{\n  return acc_;\n}\n}\n", "meta": {"hexsha": "001b7563eaa07200e16fe9d9372d309188167967", "size": 10051, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "uav_simulator/so3_quadrotor_simulator/src/dynamics/Quadrotor.cpp", "max_stars_repo_name": "ZJU-FAST-Lab/std-trees", "max_stars_repo_head_hexsha": "322020c044469f33685bbc8e5b84c6c5734cd271", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2021-09-15T08:37:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T09:54:28.000Z", "max_issues_repo_path": "fast_planner/src/uav_simulator/so3_quadrotor_simulator/src/dynamics/Quadrotor.cpp", "max_issues_repo_name": "lvhualong/motion_Planning", "max_issues_repo_head_hexsha": "ea127de8cd8f32e9994538416d0c74b99054214f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-03-20T09:03:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T09:03:24.000Z", "max_forks_repo_path": "fast_planner/src/uav_simulator/so3_quadrotor_simulator/src/dynamics/Quadrotor.cpp", "max_forks_repo_name": "lvhualong/motion_Planning", "max_forks_repo_head_hexsha": "ea127de8cd8f32e9994538416d0c74b99054214f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2019-08-24T08:28:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-19T12:47:20.000Z", "avg_line_length": 22.0416666667, "max_line_length": 79, "alphanum_fraction": 0.5989453786, "num_tokens": 3471, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4551927104025821}}
{"text": "#define BOOST_TEST_MODULE CUSPARSE\n#include <cuda.h>\n#if (CUDA_VERSION <= 10010)\n#  define VEXCL_USE_CUSPARSE\n#endif\n#include <boost/test/unit_test.hpp>\n#include <vexcl/vector.hpp>\n#include <vexcl/spmat.hpp>\n#include \"random_matrix.hpp\"\n#include \"context_setup.hpp\"\n\n#if (CUDA_VERSION <= 10010)\nBOOST_AUTO_TEST_CASE(hyb_matrix)\n{\n    const size_t n = 1024;\n    const size_t m = 2048;\n\n    std::vector<int>    row;\n    std::vector<int>    col;\n    std::vector<double> val;\n    std::vector<double> x = random_vector<double>(m);\n\n    random_matrix(n, m, 16, row, col, val);\n\n    vex::SpMat<double, int, int> A(ctx, n, m, row.data(), col.data(), val.data());\n\n    vex::vector<double> X(ctx, x);\n    vex::vector<double> Y(ctx, n);\n\n    Y = A * X;\n\n    check_sample(Y, [&](size_t idx, double y) {\n            double sum = 0;\n            for(int j = row[idx]; j < row[idx + 1]; j++)\n                sum += val[j] * x[col[j]];\n\n            BOOST_CHECK_CLOSE(y, sum, 1e-8);\n            });\n\n    Y += 0.5 * (A * X);\n\n    check_sample(Y, [&](size_t idx, double y) {\n            double sum = 0;\n            for(int j = row[idx]; j < row[idx + 1]; j++)\n                sum += val[j] * x[col[j]];\n\n            BOOST_CHECK_CLOSE(y, 1.5 * sum, 1e-8);\n            });\n\n}\n\nBOOST_AUTO_TEST_CASE(crs_matrix)\n{\n    std::vector<vex::command_queue> single(1, ctx.queue(0));\n\n    const size_t n = 1024;\n    const size_t m = 2048;\n\n    std::vector<int>    row;\n    std::vector<int>    col;\n    std::vector<double> val;\n    std::vector<double> x = random_vector<double>(m);\n\n    random_matrix(n, m, 16, row, col, val);\n\n    vex::backend::cuda::spmat_crs<double>\n        A(ctx.queue(0), n, m, row.data(), col.data(), val.data());\n\n    vex::vector<double> X(single, x);\n    vex::vector<double> Y(single, n);\n\n    Y = A * X;\n\n    check_sample(Y, [&](size_t idx, double y) {\n            double sum = 0;\n            for(int j = row[idx]; j < row[idx + 1]; j++)\n                sum += val[j] * x[col[j]];\n\n            BOOST_CHECK_CLOSE(y, sum, 1e-8);\n            });\n\n    Y += 0.5 * (A * X);\n\n    check_sample(Y, [&](size_t idx, double y) {\n            double sum = 0;\n            for(int j = row[idx]; j < row[idx + 1]; j++)\n                sum += val[j] * x[col[j]];\n\n            BOOST_CHECK_CLOSE(y, 1.5 * sum, 1e-8);\n            });\n\n}\n#endif\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "1412ce2d19126a5977269838822bf16378dbc769", "size": 2344, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/cusparse.cpp", "max_stars_repo_name": "skn123/vexcl", "max_stars_repo_head_hexsha": "8e80910f9bacf34b786f9538cfd74662653b731f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 531.0, "max_stars_repo_stars_event_min_datetime": "2015-01-05T11:56:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T10:21:25.000Z", "max_issues_repo_path": "tests/cusparse.cpp", "max_issues_repo_name": "skn123/vexcl", "max_issues_repo_head_hexsha": "8e80910f9bacf34b786f9538cfd74662653b731f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 130.0, "max_issues_repo_issues_event_min_datetime": "2015-01-29T11:19:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-14T06:56:07.000Z", "max_forks_repo_path": "tests/cusparse.cpp", "max_forks_repo_name": "skn123/vexcl", "max_forks_repo_head_hexsha": "8e80910f9bacf34b786f9538cfd74662653b731f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 85.0, "max_forks_repo_forks_event_min_datetime": "2015-01-10T13:09:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T13:31:03.000Z", "avg_line_length": 24.4166666667, "max_line_length": 82, "alphanum_fraction": 0.5302901024, "num_tokens": 698, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872019117029, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.45519270359491665}}
{"text": "#include \"lelantus_test_fixture.h\"\n\n#include \"../range_prover.h\"\n#include \"../range_verifier.h\"\n\n#include <boost/test/unit_test.hpp>\n\nnamespace lelantus {\n\n// All versions to be tested\nunsigned int test_versions[] = {\n    LELANTUS_TX_VERSION_4,\n    SIGMA_TO_LELANTUS_JOINSPLIT,\n    LELANTUS_TX_VERSION_4_5,\n    SIGMA_TO_LELANTUS_JOINSPLIT_FIXED,\n    LELANTUS_TX_TPAYLOAD,\n    SIGMA_TO_LELANTUS_TX_TPAYLOAD\n};\n\nBOOST_FIXTURE_TEST_SUITE(lelantus_range_proof_tests, LelantusTestingSetup)\n\n// A single valid aggregated range proof\nBOOST_AUTO_TEST_CASE(prove_verify_single)\n{\n    // Parameters\n    std::size_t n = 64;\n    std::size_t max_m = 8;\n\n    // Generators\n    secp_primitives::GroupElement g_gen, h_gen1, h_gen2;\n    g_gen.randomize();\n    h_gen1.randomize();\n    h_gen2.randomize();\n\n    auto prove_verify = [&] (std::size_t m, unsigned int version) {\n        auto g_ = RandomizeGroupElements(n * m);\n        auto h_ = RandomizeGroupElements(n * m);\n\n        // Input data\n        auto serials = RandomizeScalars(m);\n        auto randoms = RandomizeScalars(m);\n\n        std::vector<secp_primitives::Scalar> v_s;\n        std::vector<secp_primitives::GroupElement> V;\n        for (std::size_t i = 0; i < m; ++i){\n            v_s.emplace_back(i);\n            V.push_back(g_gen * v_s.back() +  h_gen1 * randoms[i] + h_gen2 * serials[i]);\n        }\n\n        // Prove\n        RangeProver rangeProver(g_gen, h_gen1, h_gen2, g_, h_, n, version);\n        RangeProof proof;\n        rangeProver.proof(v_s, serials, randoms, V, proof);\n\n        // Verify\n        RangeVerifier rangeVerifier(g_gen, h_gen1, h_gen2, g_, h_, n, version);\n        BOOST_CHECK(rangeVerifier.verify(V, V, proof));\n    };\n\n    // Test powers of 2\n    std::size_t i = 1;\n    while (i <= max_m) {\n        for (auto version : test_versions) \n            prove_verify(i, version);\n        i *= 2;\n    }\n\n}\n\n// A batch of valid aggregated range proofs of different size\nBOOST_AUTO_TEST_CASE(prove_verify_batch)\n{\n    // Parameters\n    const std::size_t n = 64;\n    const std::vector<std::size_t> m = {1,2,4,8};\n\n    // Generators\n    secp_primitives::GroupElement g_gen, h_gen1, h_gen2;\n    g_gen.randomize();\n    h_gen1.randomize();\n    h_gen2.randomize();\n    std::size_t max_m = *std::max_element(m.begin(), m.end());\n    auto g_ = RandomizeGroupElements(n * max_m);\n    auto h_ = RandomizeGroupElements(n * max_m);\n\n    for (auto version : test_versions)\n    {\n        // Proofs\n        std::vector<std::vector<GroupElement> > V_batch;\n        V_batch.reserve(m.size());\n        std::vector<RangeProof> proof_batch;\n        proof_batch.reserve(m.size());\n        for (std::size_t i = 0; i < m.size(); i++) {\n            RangeProver rangeProver(g_gen, h_gen1, h_gen2, std::vector<GroupElement>(g_.begin(), g_.begin() + n * m[i]), std::vector<GroupElement>(h_.begin(), h_.begin() + n * m[i]), n, version);\n\n            // Input data\n            auto serials = RandomizeScalars(m[i]);\n            auto randoms = RandomizeScalars(m[i]);\n\n            std::vector<secp_primitives::Scalar> v_s;\n            std::vector<secp_primitives::GroupElement> V;\n            for (std::size_t j = 0; j < m[i]; ++j){\n                v_s.emplace_back(j);\n                V.push_back(g_gen * v_s.back() +  h_gen1 * randoms[j] + h_gen2 * serials[j]);\n            }\n\n            // Prove\n            RangeProof proof;\n            rangeProver.proof(v_s, serials, randoms, V, proof);\n            V_batch.emplace_back(V);\n            proof_batch.emplace_back(proof);\n        }\n\n        // Verify\n        RangeVerifier rangeVerifier(g_gen, h_gen1, h_gen2, g_, h_, n, version);\n        BOOST_CHECK(rangeVerifier.verify(V_batch, V_batch, proof_batch));\n    }\n}\n\n// A single out-of-range aggregated range proof\nBOOST_AUTO_TEST_CASE(out_of_range_single_proof)\n{\n    // Parameters\n    std::size_t n = 4;\n    std::size_t m = 4;\n\n    // Generators\n    secp_primitives::GroupElement g_gen, h_gen1, h_gen2;\n    g_gen.randomize();\n    h_gen1.randomize();\n    h_gen2.randomize();\n    auto g_ = RandomizeGroupElements(n * m);\n    auto h_ = RandomizeGroupElements(n * m);\n\n    // Input data\n    auto randoms = RandomizeScalars(m);\n    auto serials = RandomizeScalars(m);\n\n    auto testF = [&] (std::vector<Scalar> const v_s, unsigned int version) {\n        std::vector<GroupElement> V;\n        for (std::size_t i = 0; i < m; ++i) {\n            V.push_back(g_gen * v_s[i] +  h_gen1 * randoms[i] + h_gen2 * serials[i]);\n        }\n\n        lelantus::RangeProver rangeProver(g_gen, h_gen1, h_gen2, g_, h_, n, version);\n        lelantus::RangeProof proof;\n        rangeProver.proof(v_s, serials, randoms, V, proof );\n\n        lelantus::RangeVerifier rangeVerifier(g_gen, h_gen1, h_gen2, g_, h_, n, version);\n        BOOST_CHECK(!rangeVerifier.verify(V, V, proof));\n    };\n\n    for (auto version : test_versions)\n    {\n        // All values are out of range\n        std::vector<Scalar> vs;\n        for(std::size_t i = 0; i < m; ++i){\n            vs.emplace_back((1 << n) + i);\n        }\n        testF(vs, version);\n\n        // [0, 2 ^ n - 1]\n        Scalar l(uint64_t(0));\n        Scalar r((1 << n) - 1);\n\n        // One value is out of range\n        vs = {l, l + 1, r, r + 1};\n        testF(vs, version);\n\n        vs = {l - 1, l, r - 1, r};\n        testF(vs, version);\n    }\n}\n\n// A single aggreated range proof, with successively invalid proof elements\nBOOST_AUTO_TEST_CASE(invalid_elements)\n{\n    // Parameters\n    std::size_t n = 64;\n    std::size_t m = 4;\n\n    // Generators\n    secp_primitives::GroupElement g_gen, h_gen1, h_gen2;\n    g_gen.randomize();\n    h_gen1.randomize();\n    h_gen2.randomize();\n    auto g_ = RandomizeGroupElements(n * m);\n    auto h_ = RandomizeGroupElements(n * m);\n\n    // Inputs\n    auto randoms = RandomizeScalars(m);\n    auto serials = RandomizeScalars(m);\n\n    // Set up valid proof\n    std::vector<secp_primitives::Scalar> v_s;\n    std::vector<secp_primitives::GroupElement> V;\n    for(std::size_t i = 0; i < m; ++i){\n        v_s.emplace_back(i);\n        V.push_back(g_gen * v_s.back() +  h_gen1 * randoms[i] + h_gen2 * serials[i]);\n    }\n\n    for (auto version : test_versions)\n    {\n        // Initial correctness check\n        RangeProver rangeProver(g_gen, h_gen1, h_gen2, g_, h_, n, version);\n        RangeProof proof;\n        rangeProver.proof(v_s, serials, randoms, V, proof);\n        RangeVerifier rangeVerifier(g_gen, h_gen1, h_gen2, g_, h_, n, version);\n        BOOST_CHECK(rangeVerifier.verify(V, V, proof));\n\n        // Invalidate successive values and then restore them\n        GroupElement group;\n        Scalar scalar;\n\n        group = GroupElement(proof.A);\n        proof.A.randomize();\n        BOOST_CHECK(!rangeVerifier.verify(V, V, proof));\n        proof.A = GroupElement(group);\n        BOOST_CHECK(rangeVerifier.verify(V, V, proof));\n\n        group = GroupElement(proof.S);\n        proof.S.randomize();\n        BOOST_CHECK(!rangeVerifier.verify(V, V, proof));\n        proof.S = GroupElement(group);\n        BOOST_CHECK(rangeVerifier.verify(V, V, proof));\n\n        group = GroupElement(proof.T1);\n        proof.T1.randomize();\n        BOOST_CHECK(!rangeVerifier.verify(V, V, proof));\n        proof.T1 = GroupElement(group);\n        BOOST_CHECK(rangeVerifier.verify(V, V, proof));\n\n        group = GroupElement(proof.T2);\n        proof.T2.randomize();\n        BOOST_CHECK(!rangeVerifier.verify(V, V, proof));\n        proof.T2 = GroupElement(group);\n        BOOST_CHECK(rangeVerifier.verify(V, V, proof));\n\n        for (std::size_t j = 0; j < proof.innerProductProof.L_.size(); j++) {\n            group = GroupElement(proof.innerProductProof.L_[j]);\n            proof.innerProductProof.L_[j].randomize();\n            BOOST_CHECK(!rangeVerifier.verify(V, V, proof));\n            proof.innerProductProof.L_[j] = GroupElement(group);\n            BOOST_CHECK(rangeVerifier.verify(V, V, proof));\n\n            group = GroupElement(proof.innerProductProof.R_[j]);\n            proof.innerProductProof.R_[j].randomize();\n            BOOST_CHECK(!rangeVerifier.verify(V, V, proof));\n            proof.innerProductProof.R_[j] = GroupElement(group);\n            BOOST_CHECK(rangeVerifier.verify(V, V, proof));\n        }\n\n        scalar = Scalar(proof.T_x1);\n        proof.T_x1.randomize();\n        BOOST_CHECK(!rangeVerifier.verify(V, V, proof));\n        proof.T_x1 = Scalar(scalar);\n        BOOST_CHECK(rangeVerifier.verify(V, V, proof));\n\n        scalar = Scalar(proof.T_x2);\n        proof.T_x2.randomize();\n        BOOST_CHECK(!rangeVerifier.verify(V, V, proof));\n        proof.T_x2 = Scalar(scalar);\n        BOOST_CHECK(rangeVerifier.verify(V, V, proof));\n\n        scalar = Scalar(proof.u);\n        proof.u.randomize();\n        BOOST_CHECK(!rangeVerifier.verify(V, V, proof));\n        proof.u = Scalar(scalar);\n        BOOST_CHECK(rangeVerifier.verify(V, V, proof));\n\n        scalar = Scalar(proof.innerProductProof.a_);\n        proof.innerProductProof.a_.randomize();\n        BOOST_CHECK(!rangeVerifier.verify(V, V, proof));\n        proof.innerProductProof.a_ = Scalar(scalar);\n        BOOST_CHECK(rangeVerifier.verify(V, V, proof));\n\n        scalar = Scalar(proof.innerProductProof.b_);\n        proof.innerProductProof.b_.randomize();\n        BOOST_CHECK(!rangeVerifier.verify(V, V, proof));\n        proof.innerProductProof.b_ = Scalar(scalar);\n        BOOST_CHECK(rangeVerifier.verify(V, V, proof));\n\n        scalar = Scalar(proof.innerProductProof.c_);\n        proof.innerProductProof.c_.randomize();\n        BOOST_CHECK(!rangeVerifier.verify(V, V, proof));\n        proof.innerProductProof.c_ = Scalar(scalar);\n        BOOST_CHECK(rangeVerifier.verify(V, V, proof));\n    }\n}\n\n// A batch of range proofs, one of which is invalid\nBOOST_AUTO_TEST_CASE(invalid_batch)\n{\n    // Parameters\n    const std::size_t n = 64;\n    const std::vector<std::size_t> m = {1,2,4,8};\n\n    // Generators\n    secp_primitives::GroupElement g_gen, h_gen1, h_gen2;\n    g_gen.randomize();\n    h_gen1.randomize();\n    h_gen2.randomize();\n    std::size_t max_m = *std::max_element(m.begin(), m.end());\n    auto g_ = RandomizeGroupElements(n * max_m);\n    auto h_ = RandomizeGroupElements(n * max_m);\n\n    for (auto version : test_versions)\n    {\n        // Proofs\n        std::vector<std::vector<GroupElement> > V_batch;\n        V_batch.reserve(m.size());\n        std::vector<RangeProof> proof_batch;\n        proof_batch.reserve(m.size());\n        for (std::size_t i = 0; i < m.size(); i++) {\n            RangeProver rangeProver(g_gen, h_gen1, h_gen2, std::vector<GroupElement>(g_.begin(), g_.begin() + n * m[i]), std::vector<GroupElement>(h_.begin(), h_.begin() + n * m[i]), n, version);\n\n            // Input data\n            auto serials = RandomizeScalars(m[i]);\n            auto randoms = RandomizeScalars(m[i]);\n\n            std::vector<secp_primitives::Scalar> v_s;\n            std::vector<secp_primitives::GroupElement> V;\n            for (std::size_t j = 0; j < m[i]; ++j){\n                v_s.emplace_back(j);\n                V.push_back(g_gen * v_s.back() +  h_gen1 * randoms[j] + h_gen2 * serials[j]);\n            }\n\n            // Prove\n            RangeProof proof;\n            rangeProver.proof(v_s, serials, randoms, V, proof);\n            V_batch.emplace_back(V);\n            proof_batch.emplace_back(proof);\n        }\n\n        // Invalidate one of the proofs\n        proof_batch[0].A.randomize();\n\n        // Verify\n        RangeVerifier rangeVerifier(g_gen, h_gen1, h_gen2, g_, h_, n, version);\n        BOOST_CHECK(!rangeVerifier.verify(V_batch, V_batch, proof_batch));\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n} // namespace lelantus", "meta": {"hexsha": "58794f09870d84e4f17cbf87b2f2a5be6540dab5", "size": 11595, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/liblelantus/test/range_proof_test.cpp", "max_stars_repo_name": "arjundashrath/firo", "max_stars_repo_head_hexsha": "78e29d68b7354be702965fdd4f033709750776e5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 582.0, "max_stars_repo_stars_event_min_datetime": "2016-09-26T00:08:04.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-25T19:07:24.000Z", "max_issues_repo_path": "src/liblelantus/test/range_proof_test.cpp", "max_issues_repo_name": "arjundashrath/firo", "max_issues_repo_head_hexsha": "78e29d68b7354be702965fdd4f033709750776e5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 570.0, "max_issues_repo_issues_event_min_datetime": "2016-09-28T07:29:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-26T10:24:19.000Z", "max_forks_repo_path": "src/liblelantus/test/range_proof_test.cpp", "max_forks_repo_name": "arjundashrath/firo", "max_forks_repo_head_hexsha": "78e29d68b7354be702965fdd4f033709750776e5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 409.0, "max_forks_repo_forks_event_min_datetime": "2016-09-21T12:37:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-18T14:54:17.000Z", "avg_line_length": 33.5115606936, "max_line_length": 195, "alphanum_fraction": 0.6100043122, "num_tokens": 3091, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324983301568, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.45516631047719464}}
{"text": "/********************************************************************************\n*  This file is part of CinoLib                                                 *\n*  Copyright(C) 2016: Marco Livesu                                              *\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*                                                                               *\n*     Marco Livesu (marco.livesu@gmail.com)                                     *\n*     http://pers.ge.imati.cnr.it/livesu/                                       *\n*                                                                               *\n*     Italian National Research Council (CNR)                                   *\n*     Institute for Applied Mathematics and Information Technologies (IMATI)    *\n*     Via de Marini, 6                                                          *\n*     16149 Genoa,                                                              *\n*     Italy                                                                     *\n*********************************************************************************/\n#include <cinolib/harmonic_map.h>\n#include <cinolib/laplacian.h>\n#include <Eigen/Sparse>\n\nnamespace cinolib\n{\n\ntemplate<class M, class V, class E, class P>\nCINO_INLINE\nScalarField harmonic_map(const AbstractMesh<M,V,E,P> & m,\n                         const std::map<unsigned int,double> & bc,\n                         const unsigned int                    n,\n                         const int                     laplacian_mode,\n                         const int                     solver)\n{\n    assert(n > 0);\n    assert(bc.size() > 0);\n    assert(laplacian_mode == COTANGENT || laplacian_mode == UNIFORM);\n    assert(solver == SIMPLICIAL_LLT || solver == SIMPLICIAL_LDLT || solver == SparseLU || solver == BiCGSTAB);\n\n    ScalarField f(m.num_verts());\n\n    Eigen::SparseMatrix<double> L   = laplacian(m, laplacian_mode);\n    Eigen::SparseMatrix<double> Ln = -L;\n    Eigen::VectorXd             rhs = Eigen::VectorXd::Zero(m.num_verts());\n\n    for(unsigned int i=1; i<n; ++i) Ln  = Ln * (-L); // keep it PSD\n\n    solve_square_system_with_bc(Ln, rhs, f, bc, solver);\n\n    return f;\n}\n\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\ntemplate<class M, class V, class E, class P>\nCINO_INLINE\nstd::vector<vec3d> harmonic_map_3d(const AbstractMesh<M,V,E,P> & m,\n                                   const std::map<unsigned int,vec3d>  & bc,\n                                   const unsigned int                    n,\n                                   const int                     laplacian_mode,\n                                   const int                     solver)\n{\n    assert(n > 0);\n    assert(bc.size() > 0);\n    assert(laplacian_mode == COTANGENT || laplacian_mode == UNIFORM);\n    assert(solver == SIMPLICIAL_LLT || solver == SIMPLICIAL_LDLT || solver == SparseLU || solver == BiCGSTAB);\n\n    ScalarField f(3*m.num_verts());\n\n    Eigen::SparseMatrix<double> L   = laplacian(m, laplacian_mode, 3);\n    Eigen::SparseMatrix<double> Ln = -L;\n    Eigen::VectorXd             rhs = Eigen::VectorXd::Zero(3*m.num_verts());\n\n    for(unsigned int i=1; i<n; ++i) Ln  = Ln * (-L); // keep it PSD\n\n    unsigned int y_off = m.num_verts();\n    unsigned int z_off = m.num_verts() + y_off;\n    std::map<unsigned int,double> bc_1d;\n    for(auto obj : bc)\n    {\n        unsigned int  vid = obj.first;\n        vec3d pos = obj.second;\n        bc_1d[      vid] = pos.x();\n        bc_1d[y_off+vid] = pos.y();\n        bc_1d[z_off+vid] = pos.z();\n    }\n\n    solve_square_system_with_bc(Ln, rhs, f, bc_1d, solver);\n\n    std::vector<vec3d> res(m.num_verts());\n    for(unsigned int vid=0; vid<m.num_verts(); ++vid)\n    {\n        res.at(vid) = vec3d(f[vid], f[y_off+vid], f[z_off+vid]);\n    }\n\n    return res;\n}\n\n}\n", "meta": {"hexsha": "9c8b361daf208a2e6cbe58c13f3d24be57a284f1", "size": 5596, "ext": "tpp", "lang": "C++", "max_stars_repo_path": "include/cinolib/harmonic_map.tpp", "max_stars_repo_name": "francescozoccheddu/cinolib", "max_stars_repo_head_hexsha": "6d6f7d359db673aca1c203a208f50e0a7a362b76", "max_stars_repo_licenses": ["MIT"], "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/cinolib/harmonic_map.tpp", "max_issues_repo_name": "francescozoccheddu/cinolib", "max_issues_repo_head_hexsha": "6d6f7d359db673aca1c203a208f50e0a7a362b76", "max_issues_repo_licenses": ["MIT"], "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/cinolib/harmonic_map.tpp", "max_forks_repo_name": "francescozoccheddu/cinolib", "max_forks_repo_head_hexsha": "6d6f7d359db673aca1c203a208f50e0a7a362b76", "max_forks_repo_licenses": ["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.8290598291, "max_line_length": 110, "alphanum_fraction": 0.4505003574, "num_tokens": 1119, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324938410784, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.455166307970821}}
{"text": "// Copyright (C) INRIA 1999-2008\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 version 2 as published\n// by the Free Software Foundation.\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 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, write to the Free Software Foundation, Inc.,\n// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n//%\n// @file ActuationModel/NoDynamics/TaskFunctionControl/ControlLaw.cpp\n// @author Florence Billet\n//\n// Affiliation(s): INRIA, team BIPOP\n//\n// Email(s): Florence.Billet@inria.fr\n//\n// @brief Compute the voltage required to follow the reference trajectory\n//\n#ifdef _WIN32 \n#define SICONOS_EXPORT extern \"C\" __declspec(dllexport) \n#else \n#define SICONOS_EXPORT extern \"C\" \n#endif  \n#include <iostream>\n#include <string>\n\n#include <boost/numeric/bindings/atlas/clapack.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\nextern \"C\" {\n#include \"Trajectory.h\"\n#include \"TaskFunctionDefinition.h\"\n\n#include \"LagrangianModel.h\"\n#include \"SomeDefinitions.h\"\n}\n\n#include \"KernelSomeDefinitions.hpp\"\n#include \"Utils.hpp\"\n\n//#include \"../../../LagrangianDynamics/Complete/util.hpp\" //a mettre ailleurs un jour\n\nSICONOS_EXPORT void controlLaw(double * t, double * q, double * qdot, int * NDOF, int * NCONT, double * torques)\n{\n  int ndof;\n  int contacts;\n  char lagrangianModelName[20] = \"\";\n\n  getLagrangianModelName(lagrangianModelName);\n  getActiveDOFsize(&ndof);\n  vector<int> activeDOF(ndof);\n  if (ndof > 0)\n    getActiveDOF(&(activeDOF[0]));\n  else\n    ndof = *NDOF;\n\n  ///////////////////////////////////////////\n  // Computation of the Lagrangian model\n  ///////////////////////////////////////////\n\n\n  matrix<double, column_major> M(*NDOF, *NDOF);\n  vector<double> N(*NDOF);\n\n  if (strcmp(lagrangianModelName, \"Human36\") == 0)\n  {\n    double L[31];\n    double addl[84];\n    double mass;\n    GetModelMass(&mass);\n    GetAnatomicalLengths(L);\n    GetTag2JointLengths(addl);\n    InertiaH36(&(M(0, 0)), q, L, addl, mass);\n    NLEffectsH36(&(N[0]), q, qdot, L, addl, mass);\n  }\n  else\n  {\n    Inertia(&(M(0, 0)), q);\n    NLEffects(&(N[0]), q, qdot);\n  }\n\n  //////////////////////////////////////////////////\n  //Additionnal forces\n  /////////////////////////////////////////////////\n\n  vector<double> fAdditionnal(*NDOF);\n  if (strcmp(lagrangianModelName, \"PA10\") == 0)\n    Friction(&(fAdditionnal[0]), q, qdot);\n  else if (strcmp(lagrangianModelName, \"RX90\") == 0)\n    SpringForce(&(fAdditionnal[0]), q);\n  else\n    fAdditionnal.clear();\n\n  ///////////////////////////////////////////////////\n  // Limitation to the selected degrees of freedom\n  ///////////////////////////////////////////////////\n  reduceMatrix(M, activeDOF, activeDOF);\n  N = reduceVector(N, activeDOF);\n  fAdditionnal = reduceVector(fAdditionnal, activeDOF);\n\n  //////////////////////////////////////////////////\n  // Proportionnel-derivee in the task space\n  //////////////////////////////////////////////////\n\n  vector<double> sDesired(*NDOF);\n  vector<double> sdotDesired(*NDOF);\n  vector<double> sddotDesired(*NDOF);\n\n  trajectory(t, &(sDesired[0]), &(sdotDesired[0]), &(sddotDesired[0]), &contacts);\n\n  //v = Kp*(s_desiree-TaskFunction(q))+Kv*(sdot_desiree-H*qdot)-h+sddot_desiree;\n  vector<double> TF(*NDOF);\n  vector<double> h(*NDOF);\n  matrix<double, column_major> H(*NDOF, *NDOF);\n\n  TaskFunction(&(TF[0]), q);\n  TaskJacobian(&(H(0, 0)), q);\n  TaskNLEffects(&(h[0]), q, qdot);\n\n  double Kp = 100.0;\n  double Kv = 30.0;\n  vector<double, array_adaptor<double> > tmp_cast(*NDOF, array_adaptor<double> (*NDOF, qdot));\n  sddotDesired += Kp * (sDesired - TF) + Kv * (sdotDesired - prod(H, tmp_cast)) - h;\n\n  /////////////////////////////////////////////////////////////\n  // Generalized Torques to make the realisation of the command\n  /////////////////////////////////////////////////////////////\n\n  //qddot = inv(H)*v;\n  vector<int> ipiv(*NDOF);\n  boost::numeric::bindings::atlas::getrf(H, ipiv);\n  boost::numeric::bindings::atlas::getri(H, ipiv);\n  sddotDesired = prod(H, sddotDesired);\n\n  //D = M*qddot(ActiveDOF) + N + FAdditionnal;\n  sddotDesired = reduceVector(sddotDesired, activeDOF);\n\n  N += prod(M, sddotDesired) + fAdditionnal;\n\n  //nmot = sum(ActiveDOF<=size(q, 1)); en fait ici nmot = ndof\n  //Torques = zeros(q);\n  //Torques(ActiveDOF(1:nmot)) = D(1:nmot);\n  for (int i = 0; i < *NDOF; i++)\n    torques[i] = 0;\n  expandVector(torques, N, activeDOF);\n\n}\n", "meta": {"hexsha": "de3f6024efa0e70bc5b1bb861d70b036cd857a1c", "size": 4716, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/Robotics/RX90/RX90Plugin/ControlLaw.cpp", "max_stars_repo_name": "siconos/siconos-deb", "max_stars_repo_head_hexsha": "2739a23f23d797dbfecec79d409e914e13c45c67", "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/Robotics/RX90/RX90Plugin/ControlLaw.cpp", "max_issues_repo_name": "siconos/siconos-deb", "max_issues_repo_head_hexsha": "2739a23f23d797dbfecec79d409e914e13c45c67", "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/Robotics/RX90/RX90Plugin/ControlLaw.cpp", "max_forks_repo_name": "siconos/siconos-deb", "max_forks_repo_head_hexsha": "2739a23f23d797dbfecec79d409e914e13c45c67", "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": 30.6233766234, "max_line_length": 112, "alphanum_fraction": 0.6075063613, "num_tokens": 1383, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324893520001, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.45516630546444736}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n// QuickBook Example\r\n\r\n// Copyright (c) 2011 Barend Gehrels, Amsterdam, the Netherlands.\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n//[register_point_2d\r\n//` Show the use of the macro BOOST_GEOMETRY_REGISTER_POINT_2D\r\n\r\n#include <iostream>\r\n#include <boost/geometry.hpp>\r\n#include <boost/geometry/geometries/register/point.hpp>\r\n\r\n/*< Somewhere, any legacy point struct is defined >*/\r\nstruct legacy_point\r\n{\r\n    double x, y;\r\n};\r\n\r\nBOOST_GEOMETRY_REGISTER_POINT_2D(legacy_point, double, cs::cartesian, x, y) /*< The magic: adapt it to Boost.Geometry Point Concept >*/\r\n\r\nint main()\r\n{\r\n    legacy_point p1, p2;\r\n\r\n    namespace bg = boost::geometry;\r\n\r\n    /*< Any Boost.Geometry function can be used for legacy point now. Here: assign_values and distance >*/\r\n    bg::assign_values(p1, 1, 1);\r\n    bg::assign_values(p2, 2, 2);\r\n\r\n    double d = bg::distance(p1, p2);\r\n\r\n    std::cout << \"Distance: \" << d << std::endl;\r\n\r\n    return 0;\r\n}\r\n\r\n//]\r\n\r\n\r\n//[register_point_2d_output\r\n/*`\r\nOutput:\r\n[pre\r\nDistance: 1.41421\r\n]\r\n*/\r\n//]\r\n", "meta": {"hexsha": "e76e6b3de5590c83feffe6987ae22d23311f4bae", "size": 1242, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/doc/src/examples/geometries/register/point.cpp", "max_stars_repo_name": "Ron2014/boost_1_48_0", "max_stars_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "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/geometry/doc/src/examples/geometries/register/point.cpp", "max_issues_repo_name": "Ron2014/boost_1_48_0", "max_issues_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "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/geometry/doc/src/examples/geometries/register/point.cpp", "max_forks_repo_name": "Ron2014/boost_1_48_0", "max_forks_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.4339622642, "max_line_length": 136, "alphanum_fraction": 0.6706924316, "num_tokens": 330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.7185944046238981, "lm_q1q2_score": 0.45516507131024386}}
{"text": "/**\n  * @file nmf_test.cpp\n  * @author Wenhao Huang\n  *\n  * Test mlpackMain() of nmf_main.cpp\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#include <string>\n\n#define BINDING_TYPE BINDING_TYPE_TEST\n\nstatic const std::string testName = \"NonNegativeMatrixFactorization\";\n\n#include <mlpack/core.hpp>\n#include <mlpack/methods/nmf/nmf_main.cpp>\n#include <mlpack/core/util/mlpack_main.hpp>\n#include \"test_helper.hpp\"\n\n#include <boost/test/unit_test.hpp>\n\nusing namespace mlpack;\nusing namespace arma;\n\n\nstruct NMFTestFixture\n{\n public:\n  NMFTestFixture()\n  {\n    // Cache in the options for this program.\n    CLI::RestoreSettings(testName);\n  }\n\n  ~NMFTestFixture()\n  {\n    // Clear the settings.\n    bindings::tests::CleanMemory();\n    CLI::ClearSettings();\n  }\n};\n\nstatic void ResetSettings()\n{\n  bindings::tests::CleanMemory();\n  CLI::ClearSettings();\n  CLI::RestoreSettings(testName);\n}\n\nBOOST_FIXTURE_TEST_SUITE(NMFMainTest, NMFTestFixture);\n\n/**\n * Ensure the resulting matrices W, H have expected shape.\n * Multdist update rule (Default Case).\n */\nBOOST_AUTO_TEST_CASE(NMFMultdistShapeTest)\n{\n  mat v = randu<mat>(8, 10);\n  int r = 5;\n\n  SetInputParam(\"update_rules\", std::string(\"multdist\"));\n  SetInputParam(\"input\", std::move(v));\n  SetInputParam(\"rank\", r);\n\n  // Perform NMF.\n  mlpackMain();\n\n  // Get resulting matrices.\n  const mat& w = CLI::GetParam<mat>(\"w\");\n  const mat& h = CLI::GetParam<mat>(\"h\");\n\n  // Check the shapes of W and H.\n  BOOST_REQUIRE_EQUAL(w.n_rows, 8);\n  BOOST_REQUIRE_EQUAL(w.n_cols, 5);\n  BOOST_REQUIRE_EQUAL(h.n_rows, 5);\n  BOOST_REQUIRE_EQUAL(h.n_cols, 10);\n}\n\n/**\n * Ensure the resulting matrices W, H have expected shape.\n * Multdiv update rule.\n */\nBOOST_AUTO_TEST_CASE(NMFMultdivShapeTest)\n{\n  mat v = randu<mat>(8, 10);\n  int r = 5;\n\n  SetInputParam(\"update_rules\", std::string(\"multdiv\"));\n  SetInputParam(\"input\", std::move(v));\n  SetInputParam(\"rank\", r);\n\n  // Perform NMF.\n  mlpackMain();\n\n  // Get resulting matrices.\n  const mat& w = CLI::GetParam<mat>(\"w\");\n  const mat& h = CLI::GetParam<mat>(\"h\");\n\n  // Check the shapes of W and H.\n  BOOST_REQUIRE_EQUAL(w.n_rows, 8);\n  BOOST_REQUIRE_EQUAL(w.n_cols, 5);\n  BOOST_REQUIRE_EQUAL(h.n_rows, 5);\n  BOOST_REQUIRE_EQUAL(h.n_cols, 10);\n}\n\n/**\n * Ensure the resulting matrices W, H have expected shape.\n * Als update rule.\n */\nBOOST_AUTO_TEST_CASE(NMFAlsShapeTest)\n{\n  mat v = randu<mat>(8, 10);\n  int r = 5;\n\n  SetInputParam(\"update_rules\", std::string(\"als\"));\n  SetInputParam(\"input\", std::move(v));\n  SetInputParam(\"rank\", r);\n\n  // Perform NMF.\n  mlpackMain();\n\n  // Get resulting matrices.\n  const mat& w = CLI::GetParam<mat>(\"w\");\n  const mat& h = CLI::GetParam<mat>(\"h\");\n\n  // Check the shapes of W and H.\n  BOOST_REQUIRE_EQUAL(w.n_rows, 8);\n  BOOST_REQUIRE_EQUAL(w.n_cols, 5);\n  BOOST_REQUIRE_EQUAL(h.n_rows, 5);\n  BOOST_REQUIRE_EQUAL(h.n_cols, 10);\n}\n\n/**\n * Ensure the rank is positive.\n */\nBOOST_AUTO_TEST_CASE(NMFRankBoundTest)\n{\n  mat v = randu<mat>(10, 10);\n  int r;\n\n  // Rank should not be negative.\n  r = -1;\n  SetInputParam(\"input\", std::move(v));\n  SetInputParam(\"rank\", r);\n\n  Log::Fatal.ignoreInput = true;\n  BOOST_REQUIRE_THROW(mlpackMain(), std::runtime_error);\n  Log::Fatal.ignoreInput = false;\n\n  // Rank should not be 0.\n  r = 0;\n  SetInputParam(\"rank\", r);\n\n  Log::Fatal.ignoreInput = true;\n  BOOST_REQUIRE_THROW(mlpackMain(), std::runtime_error);\n  Log::Fatal.ignoreInput = false;\n}\n\n/**\n * Ensure the max_iterations is non-negative.\n */\nBOOST_AUTO_TEST_CASE(NMFMaxIterartionBoundTest)\n{\n  mat v = randu<mat>(10, 10);\n  int r = 5;\n\n  // max_iterations should be non-negative.\n  SetInputParam(\"max_iterations\", int(-1));\n  SetInputParam(\"input\", std::move(v));\n  SetInputParam(\"rank\", r);\n\n  Log::Fatal.ignoreInput = true;\n  BOOST_REQUIRE_THROW(mlpackMain(), std::runtime_error);\n  Log::Fatal.ignoreInput = false;\n}\n\n/**\n * Ensure the update rule is one of \n * {\"multdist\", \"multdiv\", \"als\"}.\n */\nBOOST_AUTO_TEST_CASE(NMFUpdateRuleTest)\n{\n  mat v = randu<mat>(10, 10);\n  int r = 5;\n\n  // Invalid update rule.\n  SetInputParam(\"update_rules\", std::string(\"invalid_rule\"));\n  SetInputParam(\"input\", std::move(v));\n  SetInputParam(\"rank\", r);\n\n  Log::Fatal.ignoreInput = true;\n  BOOST_REQUIRE_THROW(mlpackMain(), std::runtime_error);\n  Log::Fatal.ignoreInput = false;\n}\n\n/**\n * Ensure min_residue is used, by testing that \n * min_resude makes a difference to the program.  \n */\nBOOST_AUTO_TEST_CASE(NMFMinResidueTest)\n{\n  mat v = arma::randu(10, 10);\n  mat initialW = arma::randu(10, 5);\n  mat initialH = arma::randu(5, 10);\n  int r = 5;\n\n  // Set a larger min_residue.\n  SetInputParam(\"min_residue\", double(1));\n  SetInputParam(\"input\", v);\n  SetInputParam(\"rank\", r);\n  SetInputParam(\"initial_w\", initialW);\n  SetInputParam(\"initial_h\", initialH);\n\n  mlpackMain();\n\n  const mat w1 = CLI::GetParam<mat>(\"w\");\n  const mat h1 = CLI::GetParam<mat>(\"h\");\n\n  ResetSettings();\n\n  // Set a smaller min_residue.\n  SetInputParam(\"min_residue\", double(1e-3));\n  SetInputParam(\"input\", v);\n  SetInputParam(\"rank\", r);\n  SetInputParam(\"initial_w\", initialW);\n  SetInputParam(\"initial_h\", initialH);\n\n  mlpackMain();\n\n  const mat w2 = CLI::GetParam<mat>(\"w\");\n  const mat h2 = CLI::GetParam<mat>(\"h\");\n\n  // The resulting matrices should be different.\n  BOOST_REQUIRE_GT(arma::norm(w1 - w2), 1e-5);\n  BOOST_REQUIRE_GT(arma::norm(h1 - h2), 1e-5);\n}\n\n/**\n * Ensure max_iterations is used, by testing that \n * max_iterations makes a difference to the program.  \n */\nBOOST_AUTO_TEST_CASE(NMFMaxIterationTest)\n{\n  mat v = arma::randu(10, 10);\n  mat initialW = arma::randu(10, 5);\n  mat initialH = arma::randu(5, 10);\n  int r = 5;\n\n  // Set a larger max_iterations.\n  SetInputParam(\"max_iterations\", int(100));\n  // Remove the influence of min_residue.\n  SetInputParam(\"min_residue\", double(0));\n  SetInputParam(\"input\", v);\n  SetInputParam(\"rank\", r);\n  SetInputParam(\"initial_w\", initialW);\n  SetInputParam(\"initial_h\", initialH);\n\n  mlpackMain();\n\n  const mat w1 = CLI::GetParam<mat>(\"w\");\n  const mat h1 = CLI::GetParam<mat>(\"h\");\n\n  ResetSettings();\n\n  // Set a smaller max_iterations.\n  SetInputParam(\"max_iterations\", int(5));\n  // Remove the influence of min_residue.\n  SetInputParam(\"min_residue\", double(0));\n  SetInputParam(\"input\", v);\n  SetInputParam(\"rank\", r);\n  SetInputParam(\"initial_w\", initialW);\n  SetInputParam(\"initial_h\", initialH);\n\n  mlpackMain();\n\n  const mat w2 = CLI::GetParam<mat>(\"w\");\n  const mat h2 = CLI::GetParam<mat>(\"h\");\n\n  // The resulting matrices should be different.\n  BOOST_REQUIRE_GT(arma::norm(w1 - w2), 1e-5);\n  BOOST_REQUIRE_GT(arma::norm(h1 - h2), 1e-5);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "f6ff018a0b4a33ba6468766f756225ab413279d0", "size": 6884, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/main_tests/nmf_test.cpp", "max_stars_repo_name": "RMaron/mlpack", "max_stars_repo_head_hexsha": "a179a2708d9555ab7ee4b1e90e0c290092edad2e", "max_stars_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-01-04T04:20:29.000Z", "max_stars_repo_stars_event_max_datetime": "2016-07-21T23:30:34.000Z", "max_issues_repo_path": "src/mlpack/tests/main_tests/nmf_test.cpp", "max_issues_repo_name": "RMaron/mlpack", "max_issues_repo_head_hexsha": "a179a2708d9555ab7ee4b1e90e0c290092edad2e", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2017-01-23T18:39:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-15T13:58:34.000Z", "max_forks_repo_path": "src/mlpack/tests/main_tests/nmf_test.cpp", "max_forks_repo_name": "RMaron/mlpack", "max_forks_repo_head_hexsha": "a179a2708d9555ab7ee4b1e90e0c290092edad2e", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-01-20T00:54:34.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-16T05:34:32.000Z", "avg_line_length": 23.9027777778, "max_line_length": 79, "alphanum_fraction": 0.6818710052, "num_tokens": 2013, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.45516506367572335}}
{"text": "//=======================================================================\n// Copyright (C) 2012 Flavio De Lorenzi (fdlorenzi@gmail.com)\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#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/vf2_sub_graph_iso.hpp>\nusing namespace boost;\n\nint main()\n{\n\n    typedef adjacency_list< setS, vecS, bidirectionalS > graph_type;\n\n    // Build graph1\n    int num_vertices1 = 8;\n    graph_type graph1(num_vertices1);\n    add_edge(0, 6, graph1);\n    add_edge(0, 7, graph1);\n    add_edge(1, 5, graph1);\n    add_edge(1, 7, graph1);\n    add_edge(2, 4, graph1);\n    add_edge(2, 5, graph1);\n    add_edge(2, 6, graph1);\n    add_edge(3, 4, graph1);\n\n    // Build graph2\n    int num_vertices2 = 9;\n    graph_type graph2(num_vertices2);\n    add_edge(0, 6, graph2);\n    add_edge(0, 8, graph2);\n    add_edge(1, 5, graph2);\n    add_edge(1, 7, graph2);\n    add_edge(2, 4, graph2);\n    add_edge(2, 7, graph2);\n    add_edge(2, 8, graph2);\n    add_edge(3, 4, graph2);\n    add_edge(3, 5, graph2);\n    add_edge(3, 6, graph2);\n\n    // Create callback to print mappings\n    vf2_print_callback< graph_type, graph_type > callback(graph1, graph2);\n\n    // Print out all subgraph isomorphism mappings between graph1 and graph2.\n    // Vertices and edges are assumed to be always equivalent.\n    vf2_subgraph_iso(graph1, graph2, callback);\n\n    return 0;\n}\n", "meta": {"hexsha": "613cb69670e3fc6ef1bd2b4bb5edc566413bc928", "size": 1564, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/graph/example/vf2_sub_graph_iso_example.cpp", "max_stars_repo_name": "uosorio/heroku_face", "max_stars_repo_head_hexsha": "7d6465e71dba17a15d8edaef520adb2fcd09d91e", "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": "3rdparty/boost_1_73_0/libs/graph/example/vf2_sub_graph_iso_example.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 130.0, "max_issues_repo_issues_event_min_datetime": "2016-06-22T22:11:25.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-29T20:24:09.000Z", "max_forks_repo_path": "3rdparty/boost_1_73_0/libs/graph/example/vf2_sub_graph_iso_example.cpp", "max_forks_repo_name": "qingkouwei/mediaones", "max_forks_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2015-07-08T19:18:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-14T16:39:56.000Z", "avg_line_length": 29.5094339623, "max_line_length": 77, "alphanum_fraction": 0.6086956522, "num_tokens": 461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.45516506367572335}}
{"text": "\n#include \"SMPSInput.hpp\"\n#include \"CbcLagrangeSolver.hpp\"\n#include \"CbcRecourseSolver.hpp\"\n#include \"conicBundleDriver.hpp\"\n#include \"combineScenarios.hpp\"\n#include <boost/scoped_ptr.hpp>\n\nusing namespace std;\nusing boost::scoped_ptr;\n\nint main(int argc, char **argv) {\n\n\t\n\tMPI_Init(&argc, &argv);\n\n\tint mype;\n\tMPI_Comm_rank(MPI_COMM_WORLD,&mype);\n\n\tif (argc != 3) {\n\t\tif (mype == 0) printf(\"Usage: %s [SMPS root name] [scenarios per subproblem]\\n\",argv[0]);\n\t\treturn 1;\n\t}\n\n\tstring smpsrootname(argv[1]);\n\tint nper = atoi(argv[2]);\n\n\tSMPSInput input(smpsrootname+\".cor\",smpsrootname+\".tim\",smpsrootname+\".sto\");\n\n\n\tcombinedInput in = combineScenarios(input,nper,true);\n\tconicBundleDriver<CbcLagrangeSolver,CbcRecourseSolver>(in);\n\n\tMPI_Finalize();\n\n\treturn 0;\n\n}\n", "meta": {"hexsha": "fb776707ab03bf30b21ab485a3c52fd7ef6ccab1", "size": 765, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Lagrange/Drivers/conicBundleDriverCombinedSMPS.cpp", "max_stars_repo_name": "jalving/PIPS", "max_stars_repo_head_hexsha": "62f664237447c7ce05a62552952c86003d90e68f", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 65.0, "max_stars_repo_stars_event_min_datetime": "2016-02-04T18:03:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T08:59:38.000Z", "max_issues_repo_path": "Lagrange/Drivers/conicBundleDriverCombinedSMPS.cpp", "max_issues_repo_name": "jalving/PIPS", "max_issues_repo_head_hexsha": "62f664237447c7ce05a62552952c86003d90e68f", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": 34.0, "max_issues_repo_issues_event_min_datetime": "2015-11-17T04:26:51.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-24T16:00:22.000Z", "max_forks_repo_path": "Lagrange/Drivers/conicBundleDriverCombinedSMPS.cpp", "max_forks_repo_name": "jalving/PIPS", "max_forks_repo_head_hexsha": "62f664237447c7ce05a62552952c86003d90e68f", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2015-10-15T20:27:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-14T08:13:34.000Z", "avg_line_length": 19.6153846154, "max_line_length": 91, "alphanum_fraction": 0.7202614379, "num_tokens": 226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943805178139, "lm_q2_score": 0.6334102705979902, "lm_q1q2_score": 0.4551650610139836}}
{"text": "#include \"Surface.h\"\n#include \"Ray.h\"\n#include \"Light.h\"\n#include \"SurfaceList.h\"\n#include \"Intersection.h\"\n#include \"Scene.h\"\n#include \"KD.h\"\n\n#include <algorithm>\n\n#include <Eigen/Dense>\n\nvoid calculate_Ld_Ls(const Ray& ray, const Ray& lightray, float I,\n                     const Eigen::Vector3f& n, const Material& mat,\n                     Color& Ld, Color& Ls) {\n    auto v = -ray.d.normalized();\n    auto l = lightray.d.normalized();\n    auto h = (v+l).normalized();\n\n    Ld = mat.kd * I * std::max(0.0f, n.dot(l));\n    Ls = mat.ks * I * std::pow(std::max(0.0f, n.dot(h)), mat.sp);\n}\n\nColor Surface::shade(const Ray& ray, const Eigen::Vector3f& point, const Eigen::Vector3f& n,\n                     const Light& light, const Scene& scene, int depth, bool shadows, bool kd) {\n    Color La, Ld, Ls, Lm;\n\n    La = mat.ka * light.intensity;\n\n    float I = light.intensity;\n\n    auto corrected_point = point + n*0.01f;\n    auto lightray = Ray(corrected_point, light.pos - corrected_point);\n\n    // Apply diffuse and specular shading, with shadows, if applicable\n    if (shadows) {\n        std::unique_ptr<Intersection> lighthit;\n        if (kd)\n            lighthit = std::unique_ptr<Intersection>(kd_intersect(ray, kd_tree, 0, mat).intersect(lightray));\n        else\n            lighthit = std::unique_ptr<Intersection>(scene.intersect(lightray));\n\n        if (!lighthit)\n            calculate_Ld_Ls(ray, lightray, I, n, mat, Ld, Ls);\n    } else {\n        calculate_Ld_Ls(ray, lightray, I, n, mat, Ld, Ls);\n    }\n\n    // Apply recursive raytracing, if applicable\n    if (mat.a != 0.0f && depth != 0) {\n        auto v = -ray.d.normalized();\n        auto r = -v - 2*((-v).dot(n)*n);\n\n        auto reflected_ray = Ray(corrected_point, r);\n        auto hit = scene.intersect(reflected_ray);\n        if (hit)\n            Lm = scene.shade(reflected_ray, *hit, depth-1, shadows, kd);\n    }\n\n    return (La + Ld + Ls)*(1-mat.a) + (Lm)*(mat.a);\n}\n", "meta": {"hexsha": "6c4d155102637cf85bf4929cb200a9db35efa24c", "size": 1942, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Surface.cpp", "max_stars_repo_name": "fmenozzi/raytracer", "max_stars_repo_head_hexsha": "23a67c7a11bea5198b691ebb0ab7fd4bb3758097", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-12T20:31:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-12T20:31:51.000Z", "max_issues_repo_path": "src/Surface.cpp", "max_issues_repo_name": "fmenozzi/raytracer", "max_issues_repo_head_hexsha": "23a67c7a11bea5198b691ebb0ab7fd4bb3758097", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Surface.cpp", "max_forks_repo_name": "fmenozzi/raytracer", "max_forks_repo_head_hexsha": "23a67c7a11bea5198b691ebb0ab7fd4bb3758097", "max_forks_repo_licenses": ["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.3225806452, "max_line_length": 109, "alphanum_fraction": 0.5937178167, "num_tokens": 577, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943805178138, "lm_q2_score": 0.63341027059799, "lm_q1q2_score": 0.45516506101398346}}
{"text": "#include <Eigen/Core>\n\n#include <numpy_eigen/boost_python_headers.hpp>\nEigen::Matrix<double, 5, 5> test_double_5_5(const Eigen::Matrix<double, 5, 5> & M)\n{\n\treturn M;\n}\nvoid export_double_5_5()\n{\n\tboost::python::def(\"test_double_5_5\",test_double_5_5);\n}\n\n", "meta": {"hexsha": "d3bd4aac065f27097c76b5a2bb154e9867ea8431", "size": 255, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Schweizer-Messer/numpy_eigen/src/autogen_test_module/test_5_5_double.cpp", "max_stars_repo_name": "PushyamiKaveti/kalibr", "max_stars_repo_head_hexsha": "d8bdfc59ee666ef854012becc93571f96fe5d80c", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": 2690.0, "max_stars_repo_stars_event_min_datetime": "2015-01-07T03:50:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T20:27:01.000Z", "max_issues_repo_path": "Schweizer-Messer/numpy_eigen/src/autogen_test_module/test_5_5_double.cpp", "max_issues_repo_name": "PushyamiKaveti/kalibr", "max_issues_repo_head_hexsha": "d8bdfc59ee666ef854012becc93571f96fe5d80c", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": 481.0, "max_issues_repo_issues_event_min_datetime": "2015-01-27T10:21:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T14:02:41.000Z", "max_forks_repo_path": "Schweizer-Messer/numpy_eigen/src/autogen_test_module/test_5_5_double.cpp", "max_forks_repo_name": "PushyamiKaveti/kalibr", "max_forks_repo_head_hexsha": "d8bdfc59ee666ef854012becc93571f96fe5d80c", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": 1091.0, "max_forks_repo_forks_event_min_datetime": "2015-01-26T21:21:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T01:55:33.000Z", "avg_line_length": 19.6153846154, "max_line_length": 82, "alphanum_fraction": 0.737254902, "num_tokens": 83, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.45516505373016136}}
{"text": "//==================================================================================================\n/**\n  EVE - Expressive Vector Engine\n  Copyright : EVE Contributors & Maintainers\n  SPDX-License-Identifier: MIT\n**/\n//==================================================================================================\n#include \"test.hpp\"\n#include <eve/function/cyl_bessel_k0.hpp>\n#include <eve/function/diff/cyl_bessel_k0.hpp>\n#include <eve/function/prev.hpp>\n#include <eve/constant/inf.hpp>\n#include <eve/constant/minf.hpp>\n#include <eve/constant/nan.hpp>\n#include <eve/platform.hpp>\n#include <cmath>\n#include <boost/math/special_functions/bessel.hpp>\n#include <boost/math/special_functions/bessel_prime.hpp>\n\nEVE_TEST_TYPES( \"Check return types of cyl_bessel_k0\"\n            , eve::test::simd::ieee_reals\n            )\n<typename T>(eve::as<T>)\n{\n  using v_t = eve::element_type_t<T>;\n  TTS_EXPR_IS(eve::cyl_bessel_k0(T(0)), T);\n  TTS_EXPR_IS(eve::cyl_bessel_k0(v_t(0)), v_t);\n};\n\n EVE_TEST( \"Check behavior of cyl_bessel_k0 on wide\"\n        , eve::test::simd::ieee_reals\n         , eve::test::generate( eve::test::randoms(0.0, 0.5)\n                              , eve::test::randoms(0.5, 1.5)\n                              , eve::test::randoms(1.5, 500.0))\n         )\n   <typename T>(T const& a0, T const& a1, T const& a2)\n{\n  using v_t = eve::element_type_t<T>;\n\n  auto eve__cyl_bessel_k0 =  [](auto x) { return eve::cyl_bessel_k0(x); };\n#if defined(__cpp_lib_math_special_functions)\n  auto std__cyl_bessel_k0 =  [](auto x)->v_t { return std::cyl_bessel_k(v_t(0), x); };\n#else\n  auto std__cyl_bessel_k0 =  [](auto x)->v_t { return boost::math::cyl_bessel_k(v_t(0), x); };\n#endif\n  if constexpr( eve::platform::supports_invalids )\n  {\n    TTS_ULP_EQUAL(eve__cyl_bessel_k0(eve::inf(eve::as<v_t>())), eve::zero(eve::as<v_t>()), 0);\n    TTS_ULP_EQUAL(eve__cyl_bessel_k0(eve::nan(eve::as<v_t>())), eve::nan(eve::as<v_t>()), 0);\n    TTS_ULP_EQUAL(eve__cyl_bessel_k0(eve::zero(eve::as<v_t>())), eve::inf(eve::as<v_t>()), 0);\n    TTS_ULP_EQUAL(eve__cyl_bessel_k0(eve::inf(eve::as<T>())),  eve::zero(eve::as< T>()), 0);\n    TTS_ULP_EQUAL(eve__cyl_bessel_k0(eve::nan(eve::as< T>())), eve::nan(eve::as< T>()), 0);\n    TTS_ULP_EQUAL(eve__cyl_bessel_k0(eve::zero(eve::as<T>())),  eve::inf(eve::as< T>()), 0);\n  }\n  TTS_IEEE_EQUAL(eve__cyl_bessel_k0(v_t(-1)), eve::nan(eve::as<v_t>()));\n  TTS_ULP_EQUAL(eve__cyl_bessel_k0(v_t(500)), std__cyl_bessel_k0(v_t(500)), 6.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_k0(v_t(10)), std__cyl_bessel_k0(v_t(10))  , 6.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_k0(v_t(5)),  std__cyl_bessel_k0(v_t(5))   , 6.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_k0(v_t(2)),  std__cyl_bessel_k0(v_t(2))   , 6.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_k0(v_t(1.5)),std__cyl_bessel_k0(v_t(1.5)) , 6.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_k0(v_t(0.5)),std__cyl_bessel_k0(v_t(0.5)) , 6.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_k0(v_t(0.05)),std__cyl_bessel_k0(v_t(0.05)) , 6.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_k0(v_t(1)),  std__cyl_bessel_k0(v_t(1))   , 6.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_k0(v_t(0)),  eve::inf(eve::as<v_t>()), 0.0);\n\n  TTS_IEEE_EQUAL(eve__cyl_bessel_k0(T(-1)), eve::nan(eve::as<T>()));\n  TTS_ULP_EQUAL(eve__cyl_bessel_k0( T(500)),  T(std__cyl_bessel_k0(v_t(500)) ), 6.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_k0( T(10)) ,  T(std__cyl_bessel_k0( v_t(10)) ), 6.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_k0( T(5))  ,  T(std__cyl_bessel_k0( v_t(5))  ), 6.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_k0( T(2))  ,  T(std__cyl_bessel_k0( v_t(2))  ), 6.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_k0( T(1.5)),  T(std__cyl_bessel_k0( v_t(1.5))), 6.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_k0( T(0.5)),  T(std__cyl_bessel_k0( v_t(0.5))), 6.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_k0( T(1))  ,  T(std__cyl_bessel_k0( v_t(1))  ), 6.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_k0( T(0))  , eve::inf(eve::as<T>()), 0.0);\n\n\n  TTS_ULP_EQUAL(eve__cyl_bessel_k0(a0), map(std__cyl_bessel_k0, a0), 10.0);\n  TTS_ULP_EQUAL(eve__cyl_bessel_k0(a1), map(std__cyl_bessel_k0, a1), 10.0);\n  TTS_RELATIVE_EQUAL(eve__cyl_bessel_k0(a2), map(std__cyl_bessel_k0, a2), 0.001);\n};\n\nEVE_TEST( \"Check behavior of cyl_bessel_k0 on wide with negative non integral order\"\n        , eve::test::simd::ieee_reals\n        , eve::test::generate(eve::test::randoms(0.0, 60.0))\n        )\n  <typename T>(T a0 )\n{\n  using v_t = eve::element_type_t<T>;\n  auto eve__diff_bessel_k0 =  [](auto x) { return eve::diff(eve::cyl_bessel_k0)(x); };\n  auto std__diff_bessel_k0 =  [](auto x)->v_t { return boost::math::cyl_bessel_k_prime(0, x); };\n  TTS_RELATIVE_EQUAL(eve__diff_bessel_k0(a0),   map(std__diff_bessel_k0, a0)   , 1.0e-3);\n\n};\n", "meta": {"hexsha": "b96852e279469831cb5ca48f80831ce7f8bad292", "size": 4633, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/module/bessel/cyl_bessel_k0.cpp", "max_stars_repo_name": "the-moisrex/eve", "max_stars_repo_head_hexsha": "80b52663eefee11460abb0aedf4158a5067cf7dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 340.0, "max_stars_repo_stars_event_min_datetime": "2020-09-16T21:12:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T15:40:33.000Z", "max_issues_repo_path": "test/unit/module/bessel/cyl_bessel_k0.cpp", "max_issues_repo_name": "the-moisrex/eve", "max_issues_repo_head_hexsha": "80b52663eefee11460abb0aedf4158a5067cf7dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 383.0, "max_issues_repo_issues_event_min_datetime": "2020-09-17T06:56:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T15:58:53.000Z", "max_forks_repo_path": "test/unit/module/bessel/cyl_bessel_k0.cpp", "max_forks_repo_name": "the-moisrex/eve", "max_forks_repo_head_hexsha": "80b52663eefee11460abb0aedf4158a5067cf7dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 28.0, "max_forks_repo_forks_event_min_datetime": "2021-02-27T23:11:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T12:31:29.000Z", "avg_line_length": 49.2872340426, "max_line_length": 100, "alphanum_fraction": 0.6468810706, "num_tokens": 1798, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.4550977192384078}}
{"text": "/*\n * @Description: LIO key frame\n * @Author: Ren Qian\n * @Date: 2020-02-28 19:13:26\n */\n#ifndef LIDAR_LOCALIZATION_SENSOR_DATA_KEY_FRAME_HPP_\n#define LIDAR_LOCALIZATION_SENSOR_DATA_KEY_FRAME_HPP_\n\n#include <Eigen/Dense>\n\n#include \"lidar_localization/models/graph_optimizer/g2o/vertex/vertex_prvag.hpp\"\n\nnamespace lidar_localization {\n\nstruct KeyFrame {\npublic:\n    double time = 0.0;\n\n    // key frame ID:\n    unsigned int index = 0;\n    \n    // a. position & orientation:\n    Eigen::Matrix4f pose = Eigen::Matrix4f::Identity();\n    // b. velocity:\n    struct {\n      Eigen::Vector3f v = Eigen::Vector3f::Zero();\n      Eigen::Vector3f w = Eigen::Vector3f::Zero();\n    } vel;\n    // c. bias:\n    struct {\n      // c.1. accelerometer:\n      Eigen::Vector3f accel = Eigen::Vector3f::Zero();\n      // c.2. gyroscope:\n      Eigen::Vector3f gyro = Eigen::Vector3f::Zero();\n    } bias;\n\n    KeyFrame() {}\n\n    explicit KeyFrame(const int vertex_id, const g2o::PRVAG &prvag) {\n      // set time:\n      time = prvag.time;\n      // set seq. ID:\n      index = vertex_id;\n      // set state:\n      pose.block<3, 1>(0, 3) = prvag.pos.cast<float>();\n      pose.block<3, 3>(0, 0) = prvag.ori.matrix().cast<float>();\n      vel.v = prvag.vel.cast<float>();\n      bias.accel = prvag.b_a.cast<float>();\n      bias.gyro = prvag.b_g.cast<float>();\n    }\n\n    Eigen::Quaternionf GetQuaternion() const;\n    Eigen::Vector3f GetTranslation() const;\n};\n\n}\n\n#endif", "meta": {"hexsha": "146cfbe337fc2b0e03178c85e695f4450566d7c4", "size": 1438, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "GraphOptimize/08-graph-optimization/src/lidar_localization/include/lidar_localization/sensor_data/key_frame.hpp", "max_stars_repo_name": "lanqing30/SensorFusionCourse", "max_stars_repo_head_hexsha": "3fcf935d6a4191563afcf2d95b34718fba7f705a", "max_stars_repo_licenses": ["Apache-2.0"], "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": "08-graph-optimization/sensor-fusion-for-localization-and-mapping/workspace/assignments/08-graph-optimization/src/lidar_localization/include/lidar_localization/sensor_data/key_frame.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": "08-graph-optimization/sensor-fusion-for-localization-and-mapping/workspace/assignments/08-graph-optimization/src/lidar_localization/include/lidar_localization/sensor_data/key_frame.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": 24.7931034483, "max_line_length": 80, "alphanum_fraction": 0.6216968011, "num_tokens": 417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.4550977192384078}}
{"text": "#include <crab/config.h>\n\n#include \"../common.hpp\"\n#include \"../program_options.hpp\"\n#ifdef HAVE_LDD\n#include <crab/domains/ldd/ldd.hpp>\n#endif\n#include <boost/optional.hpp>\n#include <crab/domains/boxes.hpp>\nusing namespace std;\nusing namespace ikos;\nusing namespace crab::cfg_impl;\nusing namespace crab::domain_impl;\n#ifdef HAVE_LDD\nusing namespace crab::domains::ldd;\n#endif\n\n#define RATIONALS\n\n#ifdef RATIONALS\nusing number_t = q_number;\n#else\nusing number_t = z_number;\n#endif\n\nusing linear_constraint_t = linear_constraint<number_t, varname_t>;\nusing linear_expression_t = linear_expression<number_t, varname_t>;\nusing interval_t = interval<number_t>;\n\n#ifdef HAVE_LDD\n\nLddManager *create_ldd_man(size_t num_vars) {\n  DdManager *cudd = Cudd_Init(0, 0, CUDD_UNIQUE_SLOTS, 127, 0);\n#ifndef RATIONALS\n  theory_t *theory = tvpi_create_boxz_theory(num_vars);\n#else\n  theory_t *theory = tvpi_create_box_theory(num_vars);\n#endif\n\n  LddManager *ldd = Ldd_Init(cudd, theory);\n\n  const bool dvo = true;\n  if (dvo)\n    Cudd_AutodynEnable(cudd, CUDD_REORDER_GROUP_SIFT);\n  return ldd;\n}\n\nvoid destroy_ldd_man(LddManager *ldd) {\n  DdManager *cudd = NULL;\n  theory_t *theory = NULL;\n  if (ldd) {\n    cudd = Ldd_GetCudd(ldd);\n    theory = Ldd_GetTheory(ldd);\n    Ldd_Quit(ldd);\n  }\n\n  if (theory)\n    tvpi_destroy_theory(theory);\n  if (cudd)\n    Cudd_Quit(cudd);\n}\n\nvoid dump(LddNodePtr val, LddManager *man) {\n  DdManager *cudd = Ldd_GetCudd(man);\n  FILE *fp = Cudd_ReadStdout(cudd);\n  Cudd_SetStdout(cudd, stderr);\n  if (val.get() == Ldd_GetTrue(man))\n    crab::outs() << \"true\\n\";\n  else if (val.get() == Ldd_GetFalse(man))\n    crab::outs() << \"false\\n\";\n  else\n    Ldd_PrintMinterm(man, val.get());\n  Cudd_SetStdout(cudd, fp);\n}\n\nLddNodePtr top(LddManager *man) { return lddPtr(man, Ldd_GetTrue(man)); }\n\nLddNodePtr bot(LddManager *man) { return lddPtr(man, Ldd_GetFalse(man)); }\n\nbool isBot(LddManager *man, LddNodePtr v) { return &*v == Ldd_GetFalse(man); }\n\nbool isTop(LddManager *man, LddNodePtr v) { return &*v == Ldd_GetTrue(man); }\n\nLddNodePtr approx(LddManager *man, LddNodePtr v) {\n  return lddPtr(man, Ldd_TermMinmaxApprox(man, &*v));\n}\n\nLddNodePtr meet(LddManager *man, LddNodePtr n1, LddNodePtr n2) {\n  return lddPtr(man, Ldd_And(man, &*n1, &*n2));\n}\n\nLddNodePtr convex_join(LddManager *man, LddNodePtr n1, LddNodePtr n2) {\n  return approx(man, lddPtr(man, Ldd_Or(man, &*n1, &*n2)));\n}\n\nLddNodePtr join(LddManager *man, LddNodePtr n1, LddNodePtr n2) {\n  return lddPtr(man, Ldd_Or(man, &*n1, &*n2));\n}\n\nbool isLeq(LddManager *man, LddNodePtr n1, LddNodePtr n2) {\n  return Ldd_TermLeq(man, &(*n1), &(*n2));\n}\n\nLddNodePtr widen(LddManager *man, LddNodePtr n1, LddNodePtr n2) {\n  return lddPtr(man, Ldd_IntervalWiden(man, &*n1, &*n2));\n}\n\nint getVarId(varname_t v) { return v.index(); }\n\n/** return term for variable v, neg for negation of variable */\nlinterm_t termForVal(LddManager *man, varname_t v, bool neg = false) {\n  int varId = getVarId(v);\n  int sgn = neg ? -1 : 1;\n  linterm_t term =\n      Ldd_GetTheory(man)->create_linterm_sparse_si(&varId, &sgn, 1);\n  return term;\n}\n\n/** v := k, where k is a constant */\nLddNodePtr assign(LddManager *man, LddNodePtr n, varname_t v, number_t k) {\n  if (isBot(man, n))\n    return n;\n\n  q_number q(k);\n  linterm_t t = termForVal(man, v);\n  constant_t kkk = (constant_t)tvpi_create_cst(q.get_mpq_t());\n  LddNodePtr newVal =\n      lddPtr(man, Ldd_TermReplace(man, &(*n), t, NULL, NULL, kkk, kkk));\n  Ldd_GetTheory(man)->destroy_cst(kkk);\n\n  assert(!isBot(man, newVal));\n  return newVal;\n}\n\n/** v := k, where k is an interval */\nLddNodePtr assign(LddManager *man, LddNodePtr n, varname_t v, interval_t ival) {\n\n  if (isBot(man, n))\n    return n;\n\n  constant_t kmin = NULL, kmax = NULL;\n\n  if (boost::optional<number_t> l = ival.lb().number()) {\n    q_number q(*l);\n    kmin = (constant_t)tvpi_create_cst(q.get_mpq_t());\n  }\n\n  if (boost::optional<number_t> u = ival.ub().number()) {\n    q_number q(*u);\n    kmax = (constant_t)tvpi_create_cst(q.get_mpq_t());\n  }\n\n  linterm_t t = termForVal(man, v);\n  LddNodePtr newVal =\n      lddPtr(man, Ldd_TermReplace(man, &(*n), t, NULL, NULL, kmin, kmax));\n\n  if (kmin)\n    Ldd_GetTheory(man)->destroy_cst(kmin);\n  if (kmax)\n    Ldd_GetTheory(man)->destroy_cst(kmax);\n\n  assert(!isBot(man, newVal));\n  return newVal;\n}\n\n/** v := a * u + k, where a, k are constants and u variable */\nLddNodePtr apply(LddManager *man, const LddNodePtr n, varname_t v, varname_t u,\n                 number_t a, number_t k) {\n  if (isTop(man, n) || isBot(man, n))\n    return n;\n\n  linterm_t t = termForVal(man, v);\n  linterm_t r = termForVal(man, u);\n\n  q_number qa(a);\n  q_number qk(k);\n\n  constant_t aaa = (constant_t)tvpi_create_cst(qa.get_mpq_t());\n  constant_t kkk = (constant_t)tvpi_create_cst(qk.get_mpq_t());\n  LddNodePtr newVal =\n      lddPtr(man, Ldd_TermReplace(man, &(*n), t, r, aaa, kkk, kkk));\n  Ldd_GetTheory(man)->destroy_cst(aaa);\n  Ldd_GetTheory(man)->destroy_cst(kkk);\n\n  assert(!isBot(man, newVal));\n  return newVal;\n}\n\n/** v := u */\nLddNodePtr assign(LddManager *man, const LddNodePtr n, varname_t v,\n                  varname_t u) {\n  return apply(man, n, v, u, 1, 0);\n}\n#endif\n\nint main(int argc, char **argv) {\n#ifdef HAVE_LDD\n\n  bool stats_enabled = false;\n  if (!crab_tests::parse_user_options(argc, argv, stats_enabled)) {\n    return 0;\n  }\n\n  LddManager *man = create_ldd_man(3000);\n  Ldd_SanityCheck(man);\n\n  variable_factory_t vfac;\n  varname_t x = vfac[\"x\"];\n  varname_t y = vfac[\"y\"];\n\n  {\n    LddNodePtr s1 = top(man);\n    LddNodePtr s11 = assign(man, s1, x, 5.5);\n    LddNodePtr s111 = assign(man, s11, y, 8.3);\n\n    LddNodePtr s2 = top(man);\n    LddNodePtr s22 = assign(man, s2, x, 5.5);\n    LddNodePtr s222 = assign(man, s22, y, 12.2);\n\n    dump(s111, man);\n    dump(s222, man);\n    crab::outs() << \"Join \\n\";\n    LddNodePtr s3 = join(man, s111, s222);\n    dump(s3, man);\n    crab::outs() << \"Widening \\n\";\n    LddNodePtr s4 = widen(man, s111, s222);\n    dump(s4, man);\n  }\n\n#if 1\n  {\n    // To reproduce an old bug with boxes.\n    // Assertion failed: (level < (unsigned)\n    // cuddI(unique,Cudd_Regular(E)->index)), function cuddUniqueInter, file\n    // /Users/E30338/Repos/crab/build_crab2/ldd/src/ldd/cudd-2.4.2/cudd/cuddTable.c,\n    // line 1143.\n\n    using boxes_domain_t = boxes_domain<number_t, varname_t>;\n    using var_t = typename boxes_domain_t::variable_t;\n\n    boxes_domain_t s1;\n    s1 += linear_constraint_t(var_t(x) >= number_t(0));\n    s1 += linear_constraint_t(var_t(x) <= number_t(1, 4));\n    s1 += linear_constraint_t(var_t(y) >= number_t(1, 4));\n    s1 += linear_constraint_t(var_t(y) <= number_t(1, 2));\n    boxes_domain_t s2;\n    s2 += linear_constraint_t(var_t(x) == number_t(0));\n    s2 += linear_constraint_t(var_t(y) == number_t(1, 2));\n\n    boxes_domain_t s3 = s2 | s1;\n    ///////////////////\n    boxes_domain_t s4;\n    s4 += linear_constraint_t(var_t(x) >= number_t(1, 4));\n    s4 += linear_constraint_t(var_t(x) <= number_t(1));\n    s4 += linear_constraint_t(var_t(y) >= number_t(1, 8));\n    s4 += linear_constraint_t(var_t(y) <= number_t(1, 4));\n\n    boxes_domain_t s5 = s4 | s2;\n    //////\n    crab::outs() << \"Widening of \\n\" << s3;\n    crab::outs() << \"and\\n\" << s5 << \" = \\n\";\n    boxes_domain_t s6 = s3 || s5;\n    crab::outs() << s6 << \"\\n\";\n  }\n#endif\n\n  // Ldd_NodeSanityCheck(man, &(*s4));\n\n  // FIXME: seg fault here\n  // destroy_ldd_man(man);\n#endif\n  return 0;\n}\n", "meta": {"hexsha": "13a83786a112de2ce5bfafaea167abfd0a8037ee", "size": 7408, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tests/domains/lddtests.cc", "max_stars_repo_name": "LinerSu/crab", "max_stars_repo_head_hexsha": "8f3516f4b4765f4a093bb3c3a94ac2daa174130c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 152.0, "max_stars_repo_stars_event_min_datetime": "2016-02-28T06:04:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T10:44:56.000Z", "max_issues_repo_path": "tests/domains/lddtests.cc", "max_issues_repo_name": "LinerSu/crab", "max_issues_repo_head_hexsha": "8f3516f4b4765f4a093bb3c3a94ac2daa174130c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 43.0, "max_issues_repo_issues_event_min_datetime": "2017-07-03T06:25:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T21:09:32.000Z", "max_forks_repo_path": "tests/domains/lddtests.cc", "max_forks_repo_name": "LinerSu/crab", "max_forks_repo_head_hexsha": "8f3516f4b4765f4a093bb3c3a94ac2daa174130c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 28.0, "max_forks_repo_forks_event_min_datetime": "2015-11-22T15:51:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-30T00:46:57.000Z", "avg_line_length": 27.0364963504, "max_line_length": 84, "alphanum_fraction": 0.6598272138, "num_tokens": 2506, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952052, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.45509771923840775}}
{"text": "\n\n#include <NTL/lzz_pX.h>\n\n#include <NTL/new.h>\n\nNTL_START_IMPL\n\n\n\nlong divide(zz_pX& q, const zz_pX& a, const zz_pX& b)\n{\n   if (IsZero(b)) {\n      if (IsZero(a)) {\n         clear(q);\n         return 1;\n      }\n      else\n         return 0;\n   }\n\n   zz_pX lq, r;\n   DivRem(lq, r, a, b);\n   if (!IsZero(r)) return 0;\n   q = lq;\n   return 1;\n}\n\nlong divide(const zz_pX& a, const zz_pX& b)\n{\n   if (IsZero(b)) return IsZero(a);\n   zz_pX lq, r;\n   DivRem(lq, r, a, b);\n   if (!IsZero(r)) return 0;\n   return 1;\n}\n\n\n\nvoid zz_pXMatrix::operator=(const zz_pXMatrix& M)\n{\n   elts[0][0] = M.elts[0][0];\n   elts[0][1] = M.elts[0][1];\n   elts[1][0] = M.elts[1][0];\n   elts[1][1] = M.elts[1][1];\n}\n\n\nvoid RightShift(zz_pX& x, const zz_pX& a, long n)\n{\n   if (IsZero(a)) {\n      clear(x);\n      return;\n   }\n\n   if (n < 0) {\n      if (n < -NTL_MAX_LONG) Error(\"overflow in RightShift\");\n      LeftShift(x, a, -n);\n      return;\n   }\n\n   long da = deg(a);\n   long i;\n \n   if (da < n) {\n      clear(x);\n      return;\n   }\n\n   if (&x != &a)\n      x.rep.SetLength(da-n+1);\n\n   for (i = 0; i <= da-n; i++)\n      x.rep[i] = a.rep[i+n];\n\n   if (&x == &a)\n      x.rep.SetLength(da-n+1);\n\n   x.normalize();\n}\n\nvoid LeftShift(zz_pX& x, const zz_pX& a, long n)\n{\n   if (IsZero(a)) {\n      clear(x);\n      return;\n   }\n\n   if (n < 0) {\n      if (n < -NTL_MAX_LONG) \n         clear(x);\n      else\n         RightShift(x, a, -n);\n      return;\n   }\n\n   if (NTL_OVERFLOW(n, 1, 0))\n      Error(\"overflow in LeftShift\");\n\n   long m = a.rep.length();\n\n   x.rep.SetLength(m+n);\n\n   long i;\n   for (i = m-1; i >= 0; i--)\n      x.rep[i+n] = a.rep[i];\n\n   for (i = 0; i < n; i++)\n      clear(x.rep[i]);\n}\n\n\nvoid ShiftAdd(zz_pX& U, const zz_pX& V, long n)\n// assumes input does not alias output\n{\n   if (IsZero(V))\n      return;\n\n   long du = deg(U);\n   long dv = deg(V);\n\n   long d = max(du, n+dv);\n\n   U.rep.SetLength(d+1);\n   long i;\n\n   for (i = du+1; i <= d; i++)\n      clear(U.rep[i]);\n\n   for (i = 0; i <= dv; i++)\n      add(U.rep[i+n], U.rep[i+n], V.rep[i]);\n\n   U.normalize();\n}\n\nvoid ShiftSub(zz_pX& U, const zz_pX& V, long n)\n// assumes input does not alias output\n{\n   if (IsZero(V))\n      return;\n\n   long du = deg(U);\n   long dv = deg(V);\n\n   long d = max(du, n+dv);\n\n   U.rep.SetLength(d+1);\n   long i;\n\n   for (i = du+1; i <= d; i++)\n      clear(U.rep[i]);\n\n   for (i = 0; i <= dv; i++)\n      sub(U.rep[i+n], U.rep[i+n], V.rep[i]);\n\n   U.normalize();\n}\n\nvoid mul(zz_pX& U, zz_pX& V, const zz_pXMatrix& M)\n// (U, V)^T = M*(U, V)^T\n{\n   long d = deg(U) - deg(M(1,1));\n   long k = NextPowerOfTwo(d - 1);\n\n   // When the GCD algorithm is run on polynomials of degree n, n-1, \n   // where n is a power of two, then d-1 is likely to be a power of two.\n   // It would be more natural to set k = NextPowerOfTwo(d+1), but this\n   // would be much less efficient in this case.\n\n   long n = (1L << k);\n   long xx;\n   zz_p a0, a1, b0, b1, c0, d0, u0, u1, v0, v1, nu0, nu1, nv0;\n   zz_p t1, t2;\n\n   if (n == d-1)\n      xx = 1;\n   else if (n == d)\n      xx = 2;\n   else \n      xx = 3;\n\n   switch (xx) {\n   case 1:\n      GetCoeff(a0, M(0,0), 0);\n      GetCoeff(a1, M(0,0), 1);\n      GetCoeff(b0, M(0,1), 0);\n      GetCoeff(b1, M(0,1), 1);\n      GetCoeff(c0, M(1,0), 0);\n      GetCoeff(d0, M(1,1), 0);\n\n      GetCoeff(u0, U, 0);\n      GetCoeff(u1, U, 1);\n      GetCoeff(v0, V, 0);\n      GetCoeff(v1, V, 1);\n\n      mul(t1, (a0), (u0));\n      mul(t2, (b0), (v0));\n      add(t1, t1, t2); \n      nu0 = t1;\n\n      mul(t1, (a1), (u0));\n      mul(t2, (a0), (u1));\n      add(t1, t1, t2);\n      mul(t2, (b1), (v0));\n      add(t1, t1, t2);\n      mul(t2, (b0), (v1));\n      add(t1, t1, t2);\n      nu1 = t1;\n\n      mul(t1, (c0), (u0));\n      mul(t2, (d0), (v0));\n      add (t1, t1, t2);\n      nv0 = t1;\n   \n      break;\n\n   case 2:\n      GetCoeff(a0, M(0,0), 0);\n      GetCoeff(b0, M(0,1), 0);\n\n      GetCoeff(u0, U, 0);\n      GetCoeff(v0, V, 0);\n\n      mul(t1, (a0), (u0));\n      mul(t2, (b0), (v0));\n      add(t1, t1, t2); \n      nu0 = t1;\n\n      break;\n\n   case 3:\n      break;\n\n   }\n\n   fftRep RU(INIT_SIZE, k), RV(INIT_SIZE, k), R1(INIT_SIZE, k), \n          R2(INIT_SIZE, k);\n\n   TofftRep(RU, U, k);  \n   TofftRep(RV, V, k);  \n\n   TofftRep(R1, M(0,0), k);\n   mul(R1, R1, RU);\n   TofftRep(R2, M(0,1), k);\n   mul(R2, R2, RV);\n   add(R1, R1, R2);\n   FromfftRep(U, R1, 0, d);\n\n   TofftRep(R1, M(1,0), k);\n   mul(R1, R1, RU);\n   TofftRep(R2, M(1,1), k);\n   mul(R2, R2, RV);\n   add(R1, R1, R2);\n   FromfftRep(V, R1, 0, d-1);\n\n   // now fix-up results\n\n   switch (xx) {\n   case 1:\n      GetCoeff(u0, U, 0);\n      sub(u0, u0, nu0);\n      SetCoeff(U, d-1, u0);\n      SetCoeff(U, 0, nu0);\n\n      GetCoeff(u1, U, 1);\n      sub(u1, u1, nu1);\n      SetCoeff(U, d, u1);\n      SetCoeff(U, 1, nu1);\n\n      GetCoeff(v0, V, 0);\n      sub(v0, v0, nv0);\n      SetCoeff(V, d-1, v0);\n      SetCoeff(V, 0, nv0);\n\n      break;\n      \n\n   case 2:\n      GetCoeff(u0, U, 0);\n      sub(u0, u0, nu0);\n      SetCoeff(U, d, u0);\n      SetCoeff(U, 0, nu0);\n\n      break;\n\n   }\n}\n\n\nvoid mul(zz_pXMatrix& A, zz_pXMatrix& B, zz_pXMatrix& C)\n// A = B*C, B and C are destroyed\n{\n   long db = deg(B(1,1));\n   long dc = deg(C(1,1));\n   long da = db + dc;\n\n   long k = NextPowerOfTwo(da+1);\n\n   fftRep B00, B01, B10, B11, C0, C1, T1, T2;\n   \n   TofftRep(B00, B(0,0), k); B(0,0).kill();\n   TofftRep(B01, B(0,1), k); B(0,1).kill();\n   TofftRep(B10, B(1,0), k); B(1,0).kill();\n   TofftRep(B11, B(1,1), k); B(1,1).kill();\n\n   TofftRep(C0, C(0,0), k);  C(0,0).kill();\n   TofftRep(C1, C(1,0), k);  C(1,0).kill();\n\n   mul(T1, B00, C0);\n   mul(T2, B01, C1);\n   add(T1, T1, T2);\n   FromfftRep(A(0,0), T1, 0, da);\n\n   mul(T1, B10, C0);\n   mul(T2, B11, C1);\n   add(T1, T1, T2);\n   FromfftRep(A(1,0), T1, 0, da);\n\n   TofftRep(C0, C(0,1), k);  C(0,1).kill();\n   TofftRep(C1, C(1,1), k);  C(1,1).kill();\n\n   mul(T1, B00, C0);\n   mul(T2, B01, C1);\n   add(T1, T1, T2);\n   FromfftRep(A(0,1), T1, 0, da);\n\n   mul(T1, B10, C0);\n   mul(T2, B11, C1);\n   add(T1, T1, T2);\n   FromfftRep(A(1,1), T1, 0, da);\n}\n\nvoid IterHalfGCD(zz_pXMatrix& M_out, zz_pX& U, zz_pX& V, long d_red)\n{\n   M_out(0,0).SetMaxLength(d_red);\n   M_out(0,1).SetMaxLength(d_red);\n   M_out(1,0).SetMaxLength(d_red);\n   M_out(1,1).SetMaxLength(d_red);\n\n   set(M_out(0,0));   clear(M_out(0,1));\n   clear(M_out(1,0)); set(M_out(1,1));\n\n   long goal = deg(U) - d_red;\n\n   if (deg(V) <= goal)\n      return;\n\n   zz_pX Q, t(INIT_SIZE, d_red);\n\n   while (deg(V) > goal) {\n      PlainDivRem(Q, U, U, V);\n      swap(U, V);\n\n      mul(t, Q, M_out(1,0));\n      sub(t, M_out(0,0), t);\n      M_out(0,0) = M_out(1,0);\n      M_out(1,0) = t;\n\n      mul(t, Q, M_out(1,1));\n      sub(t, M_out(0,1), t);\n      M_out(0,1) = M_out(1,1);\n      M_out(1,1) = t;\n   }\n}\n   \n\n\nvoid HalfGCD(zz_pXMatrix& M_out, const zz_pX& U, const zz_pX& V, long d_red)\n{\n   if (IsZero(V) || deg(V) <= deg(U) - d_red) {\n      set(M_out(0,0));   clear(M_out(0,1));\n      clear(M_out(1,0)); set(M_out(1,1));\n \n      return;\n   }\n\n\n   long n = deg(U) - 2*d_red + 2;\n   if (n < 0) n = 0;\n\n   zz_pX U1, V1;\n\n   RightShift(U1, U, n);\n   RightShift(V1, V, n);\n\n   if (d_red <= NTL_zz_pX_HalfGCD_CROSSOVER) {\n      IterHalfGCD(M_out, U1, V1, d_red);\n      return;\n   }\n\n   long d1 = (d_red + 1)/2;\n   if (d1 < 1) d1 = 1;\n   if (d1 >= d_red) d1 = d_red - 1;\n\n   zz_pXMatrix M1;\n\n   HalfGCD(M1, U1, V1, d1);\n   mul(U1, V1, M1);\n\n   long d2 = deg(V1) - deg(U) + n + d_red;\n\n   if (IsZero(V1) || d2 <= 0) {\n      M_out = M1;\n      return;\n   }\n\n\n   zz_pX Q;\n   zz_pXMatrix M2;\n\n   DivRem(Q, U1, U1, V1);\n   swap(U1, V1);\n\n   HalfGCD(M2, U1, V1, d2);\n\n   zz_pX t(INIT_SIZE, deg(M1(1,1))+deg(Q)+1);\n\n   mul(t, Q, M1(1,0));\n   sub(t, M1(0,0), t);\n   swap(M1(0,0), M1(1,0));\n   swap(M1(1,0), t);\n\n   t.kill();\n\n   t.SetMaxLength(deg(M1(1,1))+deg(Q)+1);\n\n   mul(t, Q, M1(1,1));\n   sub(t, M1(0,1), t);\n   swap(M1(0,1), M1(1,1));\n   swap(M1(1,1), t);\n\n   t.kill();\n\n   mul(M_out, M2, M1); \n}\n\n\n\n\nvoid XHalfGCD(zz_pXMatrix& M_out, zz_pX& U, zz_pX& V, long d_red)\n{\n   if (IsZero(V) || deg(V) <= deg(U) - d_red) {\n      set(M_out(0,0));   clear(M_out(0,1));\n      clear(M_out(1,0)); set(M_out(1,1));\n \n      return;\n   }\n\n   long du = deg(U);\n\n   if (d_red <= NTL_zz_pX_HalfGCD_CROSSOVER) {\n      IterHalfGCD(M_out, U, V, d_red);\n      return;\n   }\n\n   long d1 = (d_red + 1)/2;\n   if (d1 < 1) d1 = 1;\n   if (d1 >= d_red) d1 = d_red - 1;\n\n   zz_pXMatrix M1;\n\n   HalfGCD(M1, U, V, d1);\n   mul(U, V, M1);\n\n   long d2 = deg(V) - du + d_red;\n\n   if (IsZero(V) || d2 <= 0) {\n      M_out = M1;\n      return;\n   }\n\n\n   zz_pX Q;\n   zz_pXMatrix M2;\n\n   DivRem(Q, U, U, V);\n   swap(U, V);\n\n   XHalfGCD(M2, U, V, d2);\n\n   zz_pX t(INIT_SIZE, deg(M1(1,1))+deg(Q)+1);\n\n   mul(t, Q, M1(1,0));\n   sub(t, M1(0,0), t);\n   swap(M1(0,0), M1(1,0));\n   swap(M1(1,0), t);\n\n   t.kill();\n\n   t.SetMaxLength(deg(M1(1,1))+deg(Q)+1);\n\n   mul(t, Q, M1(1,1));\n   sub(t, M1(0,1), t);\n   swap(M1(0,1), M1(1,1));\n   swap(M1(1,1), t);\n\n   t.kill();\n\n   mul(M_out, M2, M1); \n}\n\nvoid HalfGCD(zz_pX& U, zz_pX& V)\n{\n   long d_red = (deg(U)+1)/2;\n\n   if (IsZero(V) || deg(V) <= deg(U) - d_red) {\n      return;\n   }\n\n   long du = deg(U);\n\n\n   long d1 = (d_red + 1)/2;\n   if (d1 < 1) d1 = 1;\n   if (d1 >= d_red) d1 = d_red - 1;\n\n   zz_pXMatrix M1;\n\n   HalfGCD(M1, U, V, d1);\n   mul(U, V, M1);\n\n   long d2 = deg(V) - du + d_red;\n\n   if (IsZero(V) || d2 <= 0) {\n      return;\n   }\n\n   M1(0,0).kill();\n   M1(0,1).kill();\n   M1(1,0).kill();\n   M1(1,1).kill();\n\n\n   zz_pX Q;\n\n   DivRem(Q, U, U, V);\n   swap(U, V);\n\n   HalfGCD(M1, U, V, d2);\n\n   mul(U, V, M1); \n}\n\n\nvoid GCD(zz_pX& d, const zz_pX& u, const zz_pX& v)\n{\n   zz_pX u1, v1;\n\n   u1 = u;\n   v1 = v;\n\n   if (deg(u1) == deg(v1)) {\n      if (IsZero(u1)) {\n         clear(d);\n         return;\n      }\n\n      rem(v1, v1, u1);\n   }\n   else if (deg(u1) < deg(v1)) {\n      swap(u1, v1);\n   }\n\n   // deg(u1) > deg(v1)\n\n   while (deg(u1) > NTL_zz_pX_GCD_CROSSOVER && !IsZero(v1)) {\n      HalfGCD(u1, v1);\n\n      if (!IsZero(v1)) {\n         rem(u1, u1, v1);\n         swap(u1, v1);\n      }\n   }\n\n   PlainGCD(d, u1, v1);\n}\n\n\n\nvoid XGCD(zz_pX& d, zz_pX& s, zz_pX& t, const zz_pX& a, const zz_pX& b)\n{\n   zz_p w;\n\n   if (IsZero(a) && IsZero(b)) {\n      clear(d);\n      set(s);\n      clear(t);\n      return;\n   }\n\n   zz_pX U, V, Q;\n\n   U = a;\n   V = b;\n\n   long flag = 0;\n\n   if (deg(U) == deg(V)) {\n      DivRem(Q, U, U, V);\n      swap(U, V);\n      flag = 1;\n   }\n   else if (deg(U) < deg(V)) {\n      swap(U, V);\n      flag = 2;\n   }\n\n   zz_pXMatrix M;\n\n   XHalfGCD(M, U, V, deg(U)+1);\n\n   d = U;\n\n   if (flag == 0) {\n      s = M(0,0); \n      t = M(0,1);\n   }\n   else if (flag == 1) {\n      s = M(0,1);\n      mul(t, Q, M(0,1));\n      sub(t, M(0,0), t);\n   }\n   else {  /* flag == 2 */\n      s = M(0,1);\n      t = M(0,0);\n   }\n\n   // normalize\n\n   inv(w, LeadCoeff(d));\n   mul(d, d, w);\n   mul(s, s, w);\n   mul(t, t, w);\n}\n\n      \n\n\n\n\n\nvoid IterBuild(zz_p* a, long n)\n{\n   long i, k;\n   zz_p b, t;\n\n   if (n <= 0) return;\n\n   negate(a[0], a[0]);\n\n   for (k = 1; k <= n-1; k++) {\n      negate(b, a[k]);\n      add(a[k], b, a[k-1]);\n      for (i = k-1; i >= 1; i--) {\n         mul(t, a[i], b);\n         add(a[i], t, a[i-1]);\n      }\n      mul(a[0], a[0], b);\n   }\n} \n\nvoid mul(zz_p* x, const zz_p* a, const zz_p* b, long n)\n{\n   zz_p t, accum;\n\n   long i, j, jmin, jmax;\n\n   long d = 2*n-1;\n\n   for (i = 0; i <= d; i++) {\n      jmin = max(0, i-(n-1));\n      jmax = min(n-1, i);\n      clear(accum);\n      for (j = jmin; j <= jmax; j++) {\n         mul(t, (a[j]), (b[i-j]));\n         add(accum, accum, t);\n      }\n      if (i >= n) {\n         add(accum, accum, (a[i-n]));\n         add(accum, accum, (b[i-n]));\n      }\n\n      x[i] = accum;\n   }\n}\n\n\nvoid BuildFromRoots(zz_pX& x, const vec_zz_p& a)\n{\n   long n = a.length();\n\n   if (n == 0) {\n      set(x);\n      return;\n   }\n\n   long k0 = NextPowerOfTwo(NTL_zz_pX_MUL_CROSSOVER)-1;\n   long crossover = 1L << k0;\n\n   if (n <= NTL_zz_pX_MUL_CROSSOVER) {\n      x.rep.SetMaxLength(n+1);\n      x.rep = a;\n      IterBuild(&x.rep[0], n);\n      x.rep.SetLength(n+1);\n      SetCoeff(x, n);\n      return;\n   }\n\n   long k = NextPowerOfTwo(n);\n\n   long m = 1L << k;\n   long i, j;\n   long l, width;\n\n   zz_pX b(INIT_SIZE, m+1);\n\n   b.rep = a;\n   b.rep.SetLength(m+1);\n   for (i = n; i < m; i++)\n      clear(b.rep[i]);\n\n   set(b.rep[m]);\n   \n   fftRep R1(INIT_SIZE, k), R2(INIT_SIZE, k);\n\n\n   zz_p t1, one;\n   set(one);\n\n   vec_zz_p G(INIT_SIZE, crossover), H(INIT_SIZE, crossover);\n   zz_p *g = G.elts();\n   zz_p *h = H.elts();\n   zz_p *tmp;\n   \n   for (i = 0; i < m; i+= crossover) {\n      for (j = 0; j < crossover; j++)\n         negate(g[j], b.rep[i+j]);\n\n      if (k0 > 0) {\n         for (j = 0; j < crossover; j+=2) {\n            mul(t1, g[j], g[j+1]);\n            add(g[j+1], g[j], g[j+1]);\n            g[j] = t1;\n         }\n      }\n   \n      for (l = 1; l < k0; l++) {\n         width = 1L << l;\n\n         for (j = 0; j < crossover; j += 2*width)\n            mul(&h[j], &g[j], &g[j+width], width);\n      \n         tmp = g; g = h; h = tmp;\n      }\n\n      for (j = 0; j < crossover; j++)\n         b.rep[i+j] = g[j];\n   }\n\n   for (l = k0; l < k; l++) {\n      width = 1L << l;\n      for (i = 0; i < m; i += 2*width) {\n         t1 = b.rep[i+width];\n         set(b.rep[i+width]);\n         TofftRep(R1, b, l+1, i, i+width);\n         b.rep[i+width] = t1;\n         t1 = b.rep[i+2*width];\n         set(b.rep[i+2*width]);\n         TofftRep(R2, b, l+1, i+width, i+2*width);\n         b.rep[i+2*width] = t1;\n         mul(R1, R1, R2);\n         FromfftRep(&b.rep[i], R1, 0, 2*width-1);\n         sub(b.rep[i], b.rep[i], one);\n      }\n   }\n\n   x.rep.SetLength(n+1);\n   long delta = m-n;\n   for (i = 0; i <= n; i++)\n     x.rep[i] = b.rep[i+delta];\n\n   // no need to normalize\n}\n\n\n\nvoid eval(zz_p& b, const zz_pX& f, zz_p a)\n// does a Horner evaluation\n{\n   zz_p acc;\n   long i;\n\n   clear(acc);\n   for (i = deg(f); i >= 0; i--) {\n      mul(acc, acc, a);\n      add(acc, acc, f.rep[i]);\n   }\n\n   b = acc;\n}\n\n\n\nvoid eval(vec_zz_p& b, const zz_pX& f, const vec_zz_p& a)\n// naive algorithm:  repeats Horner\n{\n   if (&b == &f.rep) {\n      vec_zz_p bb;\n      eval(bb, f, a);\n      b = bb;\n      return;\n   }\n\n   long m = a.length();\n   b.SetLength(m);\n   long i;\n   for (i = 0; i < m; i++) \n      eval(b[i], f, a[i]);\n}\n\n\n\n\nvoid interpolate(zz_pX& f, const vec_zz_p& a, const vec_zz_p& b)\n{\n   long m = a.length();\n   if (b.length() != m) Error(\"interpolate: vector length mismatch\");\n\n   if (m == 0) {\n      clear(f);\n      return;\n   }\n\n   vec_zz_p prod;\n   prod = a;\n\n   zz_p t1, t2;\n\n   long k, i;\n\n   vec_zz_p res;\n   res.SetLength(m);\n\n   for (k = 0; k < m; k++) {\n\n      const zz_p& aa = a[k];\n\n      set(t1);\n      for (i = k-1; i >= 0; i--) {\n         mul(t1, t1, aa);\n         add(t1, t1, prod[i]);\n      }\n\n      clear(t2);\n      for (i = k-1; i >= 0; i--) {\n         mul(t2, t2, aa);\n         add(t2, t2, res[i]);\n      }\n\n\n      inv(t1, t1);\n      sub(t2, b[k], t2);\n      mul(t1, t1, t2);\n\n      for (i = 0; i < k; i++) {\n         mul(t2, prod[i], t1);\n         add(res[i], res[i], t2);\n      }\n\n      res[k] = t1;\n\n      if (k < m-1) {\n         if (k == 0)\n            negate(prod[0], prod[0]);\n         else {\n            negate(t1, a[k]);\n            add(prod[k], t1, prod[k-1]);\n            for (i = k-1; i >= 1; i--) {\n               mul(t2, prod[i], t1);\n               add(prod[i], t2, prod[i-1]);\n            }\n            mul(prod[0], prod[0], t1);\n         }\n      }\n   }\n\n   while (m > 0 && IsZero(res[m-1])) m--;\n   res.SetLength(m);\n   f.rep = res;\n}\n\n\n   \nvoid InnerProduct(zz_pX& x, const vec_zz_p& v, long low, long high, \n                   const vec_zz_pX& H, long n, vec_zz_p& t)\n{\n   zz_p s;\n   long i, j;\n\n   zz_p *tp = t.elts();\n\n   for (j = 0; j < n; j++)\n      clear(tp[j]);\n\n\n   long p = zz_p::modulus();\n   double pinv = zz_p::ModulusInverse();\n\n   high = min(high, v.length()-1);\n   for (i = low; i <= high; i++) {\n      const vec_zz_p& h = H[i-low].rep;\n      long m = h.length();\n      zz_p w = (v[i]);\n\n      long W = rep(w);\n      mulmod_precon_t Wpinv = PrepMulModPrecon(W, p, pinv); // ((double) W)*pinv;\n      const zz_p *hp = h.elts();\n\n      for (j = 0; j < m; j++) {\n         long S = MulModPrecon(rep(hp[j]), W, p, Wpinv);\n         S = AddMod(S, rep(tp[j]), p);\n         tp[j].LoopHole() = S;\n      }\n   }\n\n   x.rep = t;\n   x.normalize();\n}\n\n\nvoid CompMod(zz_pX& x, const zz_pX& g, const zz_pXArgument& A, \n             const zz_pXModulus& F)\n{\n   if (deg(g) <= 0) {\n      x = g;\n      return;\n   }\n\n\n   zz_pX s, t;\n   vec_zz_p scratch(INIT_SIZE, F.n);\n\n   long m = A.H.length() - 1;\n   long l = ((g.rep.length()+m-1)/m) - 1;\n\n   zz_pXMultiplier M;\n   build(M, A.H[m], F);\n\n   InnerProduct(t, g.rep, l*m, l*m + m - 1, A.H, F.n, scratch);\n   for (long i = l-1; i >= 0; i--) {\n      InnerProduct(s, g.rep, i*m, i*m + m - 1, A.H, F.n, scratch);\n      MulMod(t, t, M, F);\n      add(t, t, s);\n   }\n\n   x = t;\n}\n\n\nvoid build(zz_pXArgument& A, const zz_pX& h, const zz_pXModulus& F, long m)\n{\n   if (m <= 0 || deg(h) >= F.n) Error(\"build: bad args\");\n\n   if (m > F.n) m = F.n;\n\n   long i;\n\n   if (zz_pXArgBound > 0) {\n      double sz = 1;\n      sz = sz*F.n;\n      sz = sz+6;\n      sz = sz*(sizeof (long));\n      sz = sz/1024;\n      m = min(m, long(zz_pXArgBound/sz));\n      m = max(m, 1);\n   }\n\n   zz_pXMultiplier M;\n\n   build(M, h, F);\n\n   A.H.SetLength(m+1);\n\n   set(A.H[0]);\n   A.H[1] = h;\n   for (i = 2; i <= m; i++) \n      MulMod(A.H[i], A.H[i-1], M, F);\n}\n\n\n\n\nlong zz_pXArgBound = 0;\n\n\nvoid CompMod(zz_pX& x, const zz_pX& g, const zz_pX& h, const zz_pXModulus& F)\n   // x = g(h) mod f\n{\n   long m = SqrRoot(g.rep.length());\n\n   if (m == 0) {\n      clear(x);\n      return;\n   }\n\n   zz_pXArgument A;\n\n   build(A, h, F, m);\n\n   CompMod(x, g, A, F);\n}\n\n\n\n\nvoid Comp2Mod(zz_pX& x1, zz_pX& x2, const zz_pX& g1, const zz_pX& g2,\n              const zz_pX& h, const zz_pXModulus& F)\n\n{\n   long m = SqrRoot(g1.rep.length() + g2.rep.length());\n\n   if (m == 0) {\n      clear(x1);\n      clear(x2);\n      return;\n   }\n\n   zz_pXArgument A;\n\n   build(A, h, F, m);\n\n   zz_pX xx1, xx2;\n\n   CompMod(xx1, g1, A, F);\n   CompMod(xx2, g2, A, F);\n\n   x1 = xx1;\n   x2 = xx2;\n}\n\nvoid Comp3Mod(zz_pX& x1, zz_pX& x2, zz_pX& x3, \n              const zz_pX& g1, const zz_pX& g2, const zz_pX& g3,\n              const zz_pX& h, const zz_pXModulus& F)\n\n{\n   long m = SqrRoot(g1.rep.length() + g2.rep.length() + g3.rep.length());\n\n   if (m == 0) {\n      clear(x1);\n      clear(x2);\n      clear(x3);\n      return;\n   }\n\n   zz_pXArgument A;\n\n   build(A, h, F, m);\n\n   zz_pX xx1, xx2, xx3;\n\n   CompMod(xx1, g1, A, F);\n   CompMod(xx2, g2, A, F);\n   CompMod(xx3, g3, A, F);\n\n   x1 = xx1;\n   x2 = xx2;\n   x3 = xx3;\n}\n\nstatic void StripZeroes(vec_zz_p& x)\n{\n   long n = x.length();\n   while (n > 0 && IsZero(x[n-1]))\n      n--;\n   x.SetLength(n);\n}\n\n\nvoid PlainUpdateMap(vec_zz_p& xx, const vec_zz_p& a, \n                    const zz_pX& b, const zz_pX& f)\n{\n   long n = deg(f);\n   long i, m;\n\n   if (IsZero(b)) {\n      xx.SetLength(0);\n      return;\n   }\n\n   m = n-1 - deg(b);\n\n   vec_zz_p x(INIT_SIZE, n);\n\n   for (i = 0; i <= m; i++)\n      InnerProduct(x[i], a, b.rep, i);\n\n   if (deg(b) != 0) {\n      zz_pX c(INIT_SIZE, n);\n      LeftShift(c, b, m);\n\n      for (i = m+1; i < n; i++) {\n         MulByXMod(c, c, f);\n         InnerProduct(x[i], a, c.rep);\n      }\n   }\n\n   xx = x;\n}\n   \n\n\n\nvoid UpdateMap(vec_zz_p& x, const vec_zz_p& aa, \n               const zz_pXMultiplier& B, const zz_pXModulus& F)\n{\n   long n = F.n;\n\n   vec_zz_p a;\n   a = aa;\n   StripZeroes(a);\n\n   if (a.length() > n) Error(\"UpdateMap: bad args\");\n   long i;\n\n   if (!B.UseFFT) {\n      PlainUpdateMap(x, a, B.b, F.f);\n      StripZeroes(x);\n      return;\n   }\n\n   fftRep R1(INIT_SIZE, F.k), R2(INIT_SIZE, F.l);\n   vec_zz_p V1(INIT_SIZE, n);\n\n\n   RevTofftRep(R1, a, F.k, 0, a.length()-1, 0);\n   mul(R2, R1, F.FRep);\n   RevFromfftRep(V1, R2, 0, n-2);\n   for (i = 0; i <= n-2; i++)  negate(V1[i], V1[i]);\n   RevTofftRep(R2, V1, F.l, 0, n-2, n-1);\n   mul(R2, R2, B.B1);\n   mul(R1, R1, B.B2);\n\n   AddExpand(R2, R1);\n   RevFromfftRep(x, R2, 0, n-1);\n   StripZeroes(x);\n}\n\n   \n\nvoid ProjectPowers(vec_zz_p& x, const vec_zz_p& a, long k,\n                   const zz_pXArgument& H, const zz_pXModulus& F)\n\n{\n   long n = F.n;\n\n   if (a.length() > n || k < 0 || NTL_OVERFLOW(k, 1, 0))\n      Error(\"ProjectPowers: bad args\");\n\n   long m = H.H.length()-1;\n   long l = (k+m-1)/m - 1;\n\n   zz_pXMultiplier M;\n   build(M, H.H[m], F);\n\n   vec_zz_p s(INIT_SIZE, n);\n   s = a;\n   StripZeroes(s);\n\n   x.SetLength(k);\n\n   for (long i = 0; i <= l; i++) {\n      long m1 = min(m, k-i*m);\n      zz_p* w = &x[i*m];\n      for (long j = 0; j < m1; j++)\n         InnerProduct(w[j], H.H[j].rep, s);\n      if (i < l)\n         UpdateMap(s, s, M, F);\n   }\n}\n\n\n\nvoid ProjectPowers(vec_zz_p& x, const vec_zz_p& a, long k,\n                   const zz_pX& h, const zz_pXModulus& F)\n\n{\n   if (a.length() > F.n || k < 0) Error(\"ProjectPowers: bad args\");\n\n   if (k == 0) {\n      x.SetLength(0);\n      return;\n   }\n\n   long m = SqrRoot(k);\n\n   zz_pXArgument H;\n\n   build(H, h, F, m);\n   ProjectPowers(x, a, k, H, F);\n}\n\n\nvoid BerlekampMassey(zz_pX& h, const vec_zz_p& a, long m)\n{\n   zz_pX Lambda, Sigma, Temp;\n   long L;\n   zz_p Delta, Delta1, t1;\n   long shamt;\n\n   // cerr << \"*** \" << m << \"\\n\";\n\n   Lambda.SetMaxLength(m+1);\n   Sigma.SetMaxLength(m+1);\n   Temp.SetMaxLength(m+1);\n\n   L = 0;\n   set(Lambda);\n   clear(Sigma);\n   set(Delta);\n   shamt = 0;\n\n   long i, r, dl;\n\n   for (r = 1; r <= 2*m; r++) {\n      // cerr << r << \"--\";\n      clear(Delta1);\n      dl = deg(Lambda);\n      for (i = 0; i <= dl; i++) {\n         mul(t1, Lambda.rep[i], a[r-i-1]);\n         add(Delta1, Delta1, t1);\n      }\n\n      if (IsZero(Delta1)) {\n         shamt++;\n         // cerr << \"case 1: \" << deg(Lambda) << \" \" << deg(Sigma) << \" \" << shamt << \"\\n\";\n      }\n      else if (2*L < r) {\n         div(t1, Delta1, Delta);\n         mul(Temp, Sigma, t1);\n         Sigma = Lambda;\n         ShiftSub(Lambda, Temp, shamt+1);\n         shamt = 0;\n         L = r-L;\n         Delta = Delta1;\n         // cerr << \"case 2: \" << deg(Lambda) << \" \" << deg(Sigma) << \" \" << shamt << \"\\n\";\n      }\n      else {\n         shamt++;\n         div(t1, Delta1, Delta);\n         mul(Temp, Sigma, t1);\n         ShiftSub(Lambda, Temp, shamt);\n         // cerr << \"case 3: \" << deg(Lambda) << \" \" << deg(Sigma) << \" \" << shamt << \"\\n\";\n      }\n   }\n\n   // cerr << \"finished: \" << L << \" \" << deg(Lambda) << \"\\n\"; \n\n   dl = deg(Lambda);\n   h.rep.SetLength(L + 1);\n\n   for (i = 0; i < L - dl; i++)\n      clear(h.rep[i]);\n\n   for (i = L - dl; i <= L; i++)\n      h.rep[i] = Lambda.rep[L - i];\n}\n\n\nvoid GCDMinPolySeq(zz_pX& h, const vec_zz_p& x, long m)\n{\n   long i;\n   zz_pX a, b;\n   zz_pXMatrix M;\n   zz_p t;\n\n   a.rep.SetLength(2*m);\n   for (i = 0; i < 2*m; i++) a.rep[i] = x[2*m-1-i];\n   a.normalize();\n\n   SetCoeff(b, 2*m);\n\n   HalfGCD(M, b, a, m+1);\n\n   /* make monic */\n\n   inv(t, LeadCoeff(M(1,1)));\n   mul(h, M(1,1), t);\n}\n\n\nvoid MinPolySeq(zz_pX& h, const vec_zz_p& a, long m)\n{\n   if (m < 0 || NTL_OVERFLOW(m, 1, 0)) Error(\"MinPoly: bad args\");\n   if (a.length() < 2*m) Error(\"MinPoly: sequence too short\");\n\n   if (m > NTL_zz_pX_BERMASS_CROSSOVER)\n      GCDMinPolySeq(h, a, m);\n   else\n      BerlekampMassey(h, a, m);\n}\n\n\nvoid DoMinPolyMod(zz_pX& h, const zz_pX& g, const zz_pXModulus& F, long m,\n               const vec_zz_p& R) \n{\n   vec_zz_p x;\n\n   ProjectPowers(x, R, 2*m, g, F);\n   MinPolySeq(h, x, m);\n}\n\n\nvoid ProbMinPolyMod(zz_pX& h, const zz_pX& g, const zz_pXModulus& F, long m)\n{\n   long n = F.n;\n   if (m < 1 || m > n) Error(\"ProbMinPoly: bad args\");\n\n   long i;\n   vec_zz_p R(INIT_SIZE, n);\n\n   for (i = 0; i < n; i++) random(R[i]);\n   DoMinPolyMod(h, g, F, m, R);\n}\n\nvoid MinPolyMod(zz_pX& hh, const zz_pX& g, const zz_pXModulus& F, long m)\n{\n   zz_pX h, h1;\n   long n = F.n;\n   if (m < 1 || m > n) Error(\"MinPoly: bad args\");\n\n   /* probabilistically compute min-poly */\n\n   ProbMinPolyMod(h, g, F, m);\n   if (deg(h) == m) { hh = h; return; }\n   CompMod(h1, h, g, F);\n   if (IsZero(h1)) { hh = h; return; }\n\n   /* not completely successful...must iterate */\n\n   long i;\n\n   zz_pX h2, h3;\n   zz_pXMultiplier H1;\n   vec_zz_p R(INIT_SIZE, n);\n\n   for (;;) {\n      R.SetLength(n);\n      for (i = 0; i < n; i++) random(R[i]);\n      build(H1, h1, F);\n      UpdateMap(R, R, H1, F);\n      DoMinPolyMod(h2, g, F, m-deg(h), R);\n\n      mul(h, h, h2);\n      if (deg(h) == m) { hh = h; return; }\n      CompMod(h3, h2, g, F);\n      MulMod(h1, h3, H1, F);\n      if (IsZero(h1)) { hh = h; return; }\n   }\n}\n\nvoid IrredPolyMod(zz_pX& h, const zz_pX& g, const zz_pXModulus& F, long m)\n{\n   vec_zz_p R(INIT_SIZE, 1);\n   if (m < 1 || m > F.n) Error(\"IrredPoly: bad args\");\n\n   set(R[0]);\n   DoMinPolyMod(h, g, F, m, R);\n}\n\n\n\nvoid diff(zz_pX& x, const zz_pX& a)\n{\n   long n = deg(a);\n   long i;\n\n   if (n <= 0) {\n      clear(x);\n      return;\n   }\n\n   if (&x != &a)\n      x.rep.SetLength(n);\n\n   for (i = 0; i <= n-1; i++) {\n      mul(x.rep[i], a.rep[i+1], i+1);\n   }\n\n   if (&x == &a)\n      x.rep.SetLength(n);\n\n   x.normalize();\n}\n\nvoid MakeMonic(zz_pX& x)\n{\n   if (IsZero(x))\n      return;\n\n   if (IsOne(LeadCoeff(x)))\n      return;\n\n   zz_p t;\n\n   inv(t, LeadCoeff(x));\n   mul(x, x, t);\n}\n\n\n\n\n      \nvoid PlainMulTrunc(zz_pX& x, const zz_pX& a, const zz_pX& b, long n)\n{\n   zz_pX y;\n   mul(y, a, b);\n   trunc(x, y, n);\n}\n\n\nvoid FFTMulTrunc(zz_pX& x, const zz_pX& a, const zz_pX& b, long n)\n{\n   if (IsZero(a) || IsZero(b)) {\n      clear(x);\n      return;\n   }\n\n   long d = deg(a) + deg(b);\n   if (n > d + 1)\n      n = d + 1;\n\n   long k = NextPowerOfTwo(d + 1);\n   fftRep R1(INIT_SIZE, k), R2(INIT_SIZE, k);\n\n   TofftRep(R1, a, k);\n   TofftRep(R2, b, k);\n   mul(R1, R1, R2);\n   FromfftRep(x, R1, 0, n-1);\n}\n\nvoid MulTrunc(zz_pX& x, const zz_pX& a, const zz_pX& b, long n)\n{\n   if (n < 0) Error(\"MulTrunc: bad args\");\n\n   if (deg(a) <= NTL_zz_pX_MUL_CROSSOVER || deg(b) <= NTL_zz_pX_MUL_CROSSOVER)\n      PlainMulTrunc(x, a, b, n);\n   else\n      FFTMulTrunc(x, a, b, n);\n}\n\nvoid PlainSqrTrunc(zz_pX& x, const zz_pX& a, long n)\n{\n   zz_pX y;\n   sqr(y, a);\n   trunc(x, y, n);\n}\n\n\nvoid FFTSqrTrunc(zz_pX& x, const zz_pX& a, long n)\n{\n   if (IsZero(a)) {\n      clear(x);\n      return;\n   }\n\n   long d = 2*deg(a);\n   if (n > d + 1)\n      n = d + 1;\n\n   long k = NextPowerOfTwo(d + 1);\n   fftRep R1(INIT_SIZE, k);\n\n   TofftRep(R1, a, k);\n   mul(R1, R1, R1);\n   FromfftRep(x, R1, 0, n-1);\n}\n\nvoid SqrTrunc(zz_pX& x, const zz_pX& a, long n)\n{\n   if (n < 0) Error(\"SqrTrunc: bad args\");\n\n   if (deg(a) <= NTL_zz_pX_MUL_CROSSOVER)\n      PlainSqrTrunc(x, a, n);\n   else\n      FFTSqrTrunc(x, a, n);\n}\n\n\n\nvoid FastTraceVec(vec_zz_p& S, const zz_pX& f)\n{\n   long n = deg(f);\n\n   if (n <= 0) \n      Error(\"FastTraceVec: bad args\");\n\n   if (n == 0) {\n      S.SetLength(0);\n      return;\n   }\n\n   if (n == 1) {\n      S.SetLength(1);\n      set(S[0]);\n      return;\n   }\n   \n   long i;\n   zz_pX f1;\n\n   f1.rep.SetLength(n-1);\n   for (i = 0; i <= n-2; i++)\n      f1.rep[i] = f.rep[n-i];\n   f1.normalize();\n\n   zz_pX f2;\n   f2.rep.SetLength(n-1);\n   for (i = 0; i <= n-2; i++)\n      mul(f2.rep[i], f.rep[n-1-i], i+1);\n   f2.normalize();\n\n   zz_pX f3;\n   InvTrunc(f3, f1, n-1);\n   MulTrunc(f3, f3, f2, n-1);\n\n   S.SetLength(n);\n\n   S[0] = n;\n   for (i = 1; i < n; i++)\n      negate(S[i], coeff(f3, i-1));\n}\n\n\nvoid PlainTraceVec(vec_zz_p& S, const zz_pX& ff)\n{\n   if (deg(ff) <= 0)\n      Error(\"TraceVec: bad args\");\n\n   zz_pX f;\n   f = ff;\n\n   MakeMonic(f);\n\n   long n = deg(f);\n\n   S.SetLength(n);\n\n   if (n == 0)\n      return;\n\n   long k, i;\n   zz_p acc, t;\n\n   const zz_p *fp = f.rep.elts();;\n   zz_p *sp = S.elts();\n\n   sp[0] = n;\n\n   for (k = 1; k < n; k++) {\n      mul(acc, fp[n-k], k);\n\n      for (i = 1; i < k; i++) {\n         mul(t, fp[n-i], rep(sp[k-i]));\n         add(acc, acc, t);\n      }\n\n      negate(sp[k], acc);\n   }\n}\n\nvoid TraceVec(vec_zz_p& S, const zz_pX& f)\n{\n   if (deg(f) <= NTL_zz_pX_TRACE_CROSSOVER)\n      PlainTraceVec(S, f);\n   else\n      FastTraceVec(S, f);\n}\n\nvoid ComputeTraceVec(const zz_pXModulus& F)\n{\n   vec_zz_p& S = *((vec_zz_p *) &F.tracevec);\n\n   if (S.length() > 0)\n      return;\n\n   if (!F.UseFFT) {\n      PlainTraceVec(S, F.f);\n      return;\n   }\n\n   long i;\n   long n = F.n;\n\n   fftRep R;\n   zz_pX P, g;\n\n   g.rep.SetLength(n-1);\n   for (i = 1; i < n; i++)\n      mul(g.rep[n-i-1], F.f.rep[n-i], i); \n   g.normalize();\n\n   TofftRep(R, g, F.l);\n   mul(R, R, F.HRep);\n   FromfftRep(P, R, n-2, 2*n-4);\n\n   S.SetLength(n);\n\n   S[0] = n;\n   for (i = 1; i < n; i++)\n      negate(S[i], coeff(P, n-1-i));\n}\n\nvoid TraceMod(zz_p& x, const zz_pX& a, const zz_pXModulus& F)\n{\n   long n = F.n;\n\n   if (deg(a) >= n)\n      Error(\"trace: bad args\");\n\n   if (F.tracevec.length() == 0) \n      ComputeTraceVec(F);\n\n   InnerProduct(x, a.rep, F.tracevec);\n}\n\n\nvoid TraceMod(zz_p& x, const zz_pX& a, const zz_pX& f)\n{\n   if (deg(a) >= deg(f) || deg(f) <= 0)\n      Error(\"trace: bad args\");\n\n   project(x, TraceVec(f), a);\n}\n\n\nvoid PlainResultant(zz_p& rres, const zz_pX& a, const zz_pX& b)\n{\n   zz_p res;\n \n   if (IsZero(a) || IsZero(b))\n      clear(res);\n   else if (deg(a) == 0 && deg(b) == 0) \n      set(res);\n   else {\n      long d0, d1, d2;\n      zz_p lc;\n      set(res);\n\n      long n = max(deg(a),deg(b)) + 1;\n      zz_pX u(INIT_SIZE, n), v(INIT_SIZE, n);\n\n      u = a;\n      v = b;\n\n      for (;;) {\n         d0 = deg(u);\n         d1 = deg(v);\n         lc = LeadCoeff(v);\n\n         PlainRem(u, u, v);\n         swap(u, v);\n\n         d2 = deg(v);\n         if (d2 >= 0) {\n            power(lc, lc, d0-d2);\n            mul(res, res, lc);\n            if (d0 & d1 & 1) negate(res, res);\n         }\n         else {\n            if (d1 == 0) {\n               power(lc, lc, d0);\n               mul(res, res, lc);\n            }\n            else\n               clear(res);\n        \n            break;\n         }\n      }\n   }\n\n   rres = res;\n}\n\n\nvoid ResIterHalfGCD(zz_pXMatrix& M_out, zz_pX& U, zz_pX& V, long d_red,\n                    vec_zz_p& cvec, vec_long& dvec)\n{\n   M_out(0,0).SetMaxLength(d_red);\n   M_out(0,1).SetMaxLength(d_red);\n   M_out(1,0).SetMaxLength(d_red);\n   M_out(1,1).SetMaxLength(d_red);\n\n   set(M_out(0,0));   clear(M_out(0,1));\n   clear(M_out(1,0)); set(M_out(1,1));\n\n   long goal = deg(U) - d_red;\n\n   if (deg(V) <= goal)\n      return;\n\n   zz_pX Q, t(INIT_SIZE, d_red);\n\n\n   while (deg(V) > goal) {\n      append(cvec, LeadCoeff(V));\n      append(dvec, dvec[dvec.length()-1]-deg(U)+deg(V));\n      PlainDivRem(Q, U, U, V);\n      swap(U, V);\n\n      mul(t, Q, M_out(1,0));\n      sub(t, M_out(0,0), t);\n      M_out(0,0) = M_out(1,0);\n      M_out(1,0) = t;\n\n      mul(t, Q, M_out(1,1));\n      sub(t, M_out(0,1), t);\n      M_out(0,1) = M_out(1,1);\n      M_out(1,1) = t;\n   }\n}\n   \n\n\nvoid ResHalfGCD(zz_pXMatrix& M_out, const zz_pX& U, const zz_pX& V, long d_red,\n                vec_zz_p& cvec, vec_long& dvec)\n{\n   if (IsZero(V) || deg(V) <= deg(U) - d_red) {\n      set(M_out(0,0));   clear(M_out(0,1));\n      clear(M_out(1,0)); set(M_out(1,1));\n \n      return;\n   }\n\n\n   long n = deg(U) - 2*d_red + 2;\n   if (n < 0) n = 0;\n\n   zz_pX U1, V1;\n\n   RightShift(U1, U, n);\n   RightShift(V1, V, n);\n\n   if (d_red <= NTL_zz_pX_HalfGCD_CROSSOVER) { \n      ResIterHalfGCD(M_out, U1, V1, d_red, cvec, dvec);\n      return;\n   }\n\n   long d1 = (d_red + 1)/2;\n   if (d1 < 1) d1 = 1;\n   if (d1 >= d_red) d1 = d_red - 1;\n\n   zz_pXMatrix M1;\n\n   ResHalfGCD(M1, U1, V1, d1, cvec, dvec);\n   mul(U1, V1, M1);\n\n   long d2 = deg(V1) - deg(U) + n + d_red;\n\n   if (IsZero(V1) || d2 <= 0) {\n      M_out = M1;\n      return;\n   }\n\n\n   zz_pX Q;\n   zz_pXMatrix M2;\n\n   append(cvec, LeadCoeff(V1));\n   append(dvec, dvec[dvec.length()-1]-deg(U1)+deg(V1));\n   DivRem(Q, U1, U1, V1);\n   swap(U1, V1);\n\n   ResHalfGCD(M2, U1, V1, d2, cvec, dvec);\n\n   zz_pX t(INIT_SIZE, deg(M1(1,1))+deg(Q)+1);\n\n   mul(t, Q, M1(1,0));\n   sub(t, M1(0,0), t);\n   swap(M1(0,0), M1(1,0));\n   swap(M1(1,0), t);\n\n   t.kill();\n\n   t.SetMaxLength(deg(M1(1,1))+deg(Q)+1);\n\n   mul(t, Q, M1(1,1));\n   sub(t, M1(0,1), t);\n   swap(M1(0,1), M1(1,1));\n   swap(M1(1,1), t);\n\n   t.kill();\n\n   mul(M_out, M2, M1); \n}\n\nvoid ResHalfGCD(zz_pX& U, zz_pX& V, vec_zz_p& cvec, vec_long& dvec)\n{\n   long d_red = (deg(U)+1)/2;\n\n   if (IsZero(V) || deg(V) <= deg(U) - d_red) {\n      return;\n   }\n\n   long du = deg(U);\n\n\n   long d1 = (d_red + 1)/2;\n   if (d1 < 1) d1 = 1;\n   if (d1 >= d_red) d1 = d_red - 1;\n\n   zz_pXMatrix M1;\n\n   ResHalfGCD(M1, U, V, d1, cvec, dvec);\n   mul(U, V, M1);\n\n   long d2 = deg(V) - du + d_red;\n\n   if (IsZero(V) || d2 <= 0) {\n      return;\n   }\n\n   M1(0,0).kill();\n   M1(0,1).kill();\n   M1(1,0).kill();\n   M1(1,1).kill();\n\n\n   zz_pX Q;\n\n   append(cvec, LeadCoeff(V));\n   append(dvec, dvec[dvec.length()-1]-deg(U)+deg(V));\n   DivRem(Q, U, U, V);\n   swap(U, V);\n\n   ResHalfGCD(M1, U, V, d2, cvec, dvec);\n\n   mul(U, V, M1); \n}\n\n\nvoid resultant(zz_p& rres, const zz_pX& u, const zz_pX& v)\n{\n   if (deg(u) <= NTL_zz_pX_GCD_CROSSOVER || deg(v) <= NTL_zz_pX_GCD_CROSSOVER) { \n      PlainResultant(rres, u, v);\n      return;\n   }\n\n   zz_pX u1, v1;\n\n   u1 = u;\n   v1 = v;\n\n   zz_p res, t;\n   set(res);\n\n   if (deg(u1) == deg(v1)) {\n      rem(u1, u1, v1);\n      swap(u1, v1);\n\n      if (IsZero(v1)) {\n         clear(rres);\n         return;\n      }\n\n      power(t, LeadCoeff(u1), deg(u1) - deg(v1));\n      mul(res, res, t);\n      if (deg(u1) & 1)\n         negate(res, res);\n   }\n   else if (deg(u1) < deg(v1)) {\n      swap(u1, v1);\n      if (deg(u1) & deg(v1) & 1)\n         negate(res, res);\n   }\n\n   // deg(u1) > deg(v1) && v1 != 0\n\n   vec_zz_p cvec;\n   vec_long  dvec;\n\n   cvec.SetMaxLength(deg(v1)+2);\n   dvec.SetMaxLength(deg(v1)+2);\n\n   append(cvec, LeadCoeff(u1));\n   append(dvec, deg(u1));\n\n\n   while (deg(u1) > NTL_zz_pX_GCD_CROSSOVER && !IsZero(v1)) { \n      ResHalfGCD(u1, v1, cvec, dvec);\n\n      if (!IsZero(v1)) {\n         append(cvec, LeadCoeff(v1));\n         append(dvec, deg(v1));\n         rem(u1, u1, v1);\n         swap(u1, v1);\n      }\n   }\n\n   if (IsZero(v1) && deg(u1) > 0) {\n      clear(rres);\n      return;\n   }\n\n   long i, l;\n   l = dvec.length();\n\n   if (deg(u1) == 0) {\n      // we went all the way...\n\n      for (i = 0; i <= l-3; i++) {\n         power(t, cvec[i+1], dvec[i]-dvec[i+2]);\n         mul(res, res, t);\n         if (dvec[i] & dvec[i+1] & 1)\n            negate(res, res);\n      }\n\n      power(t, cvec[l-1], dvec[l-2]);\n      mul(res, res, t);\n   }\n   else {\n      for (i = 0; i <= l-3; i++) {\n         power(t, cvec[i+1], dvec[i]-dvec[i+2]);\n         mul(res, res, t);\n         if (dvec[i] & dvec[i+1] & 1)\n            negate(res, res);\n      }\n\n      power(t, cvec[l-1], dvec[l-2]-deg(v1));\n      mul(res, res, t);\n      if (dvec[l-2] & dvec[l-1] & 1)\n         negate(res, res);\n\n      PlainResultant(t, u1, v1);\n      mul(res, res, t);\n   }\n\n   rres = res;\n}\n\nvoid NormMod(zz_p& x, const zz_pX& a, const zz_pX& f)\n{\n   if (deg(f) <= 0 || deg(a) >= deg(f)) \n      Error(\"norm: bad args\");\n\n   if (IsZero(a)) {\n      clear(x);\n      return;\n   }\n\n   zz_p t;\n   resultant(t, f, a);\n   if (!IsOne(LeadCoeff(f))) {\n      zz_p t1;\n      power(t1, LeadCoeff(f), deg(a));\n      inv(t1, t1);\n      mul(t, t, t1);\n   }\n\n   x = t;\n}\n\n\nNTL_END_IMPL\n", "meta": {"hexsha": "d537202b94c6005ec33a838ceedc925de6a52a44", "size": 35134, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ntl/lzz_pX1.cpp", "max_stars_repo_name": "av-elier/fast-exponentiation-algs", "max_stars_repo_head_hexsha": "1d6393021583686372564a7ca52b09dc7013fb38", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-10-17T20:30:05.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-24T19:52:14.000Z", "max_issues_repo_path": "src/ntl/lzz_pX1.cpp", "max_issues_repo_name": "av-elier/fast-exponentiation-algs", "max_issues_repo_head_hexsha": "1d6393021583686372564a7ca52b09dc7013fb38", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ntl/lzz_pX1.cpp", "max_forks_repo_name": "av-elier/fast-exponentiation-algs", "max_forks_repo_head_hexsha": "1d6393021583686372564a7ca52b09dc7013fb38", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.8798982188, "max_line_length": 91, "alphanum_fraction": 0.4733591393, "num_tokens": 13990, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.45509770968460406}}
{"text": "/*\n\t* Implements leapfrog solving with multiple solvers\n\t*\n\t*\n*/\n\n#ifdef _MAIN_\n\n#else\n#include <armadillo>\n\n#include \"../core/UAmoeba.hpp\"\n\n#ifdef _ALGEBRA_TOOLS_\n#else\n#include \"../core/algebraTools.hpp\"\n#endif\n\n#ifdef _AMOEBA_INIT_\n#else\n#include \"../core/amoebaParam.cpp\"\n#endif\n\n\n#include \"../core/translate.cpp\"\n\nusing namespace algebraTools;\nusing namespace arma;\n\n#endif\n\n//cx_mat X0, cx_mat X1, int matSize, long maxAmoebaIters, long nGridPoints, double precision, long maxMainIters,\n\n//size, rank MPI directives\n//\ntemplate <typename T>\nvoid segSolver(const AmoebaParam<T> amoebaParam, int rank, int size)\n{\n\n\tcx_mat idMat = eye<T>(amoebaParam.matSize, amoebaParam.matSize);\n\tarma_rng::set_seed_random();\n\n\n\t// UAmoeba(long maxIters, int nGridPoints, double precision, int matSize, int lieDimension, vector<cx_mat> *inputBasis)\n\n\tcout << \"Creating amoeba object \\n\";\n\n\tUAmoeba* amoeba = new UAmoeba(amoebaParam.maxAmoebaIters, amoebaParam.nGridPoints, amoebaParam.precision, amoebaParam.matSize, amoebaParam.lieDimension, amoebaParam.basis);\n\n\tcout << \"Allocating MPI buffers \\n\";\n\n\tArmadilloMPI* armaMPI = new ArmadilloMPI( amoebaParam.matSize, amoebaParam.matSize);\n  vector<T> world;\n  int bufferSize = 2 * size;\n\n  if(rank == 0)\n  {\n   \t//get X0\n\t\tcx_mat X0 = amoebaParam.startBoundary;\n\t\tcx_mat X1 = amoebaParam.endBoundary;\n\n\t\tcout << \"Start Boundary = \" << X0 << \"\\n\"\n\t\t\t\t << \"Target Matrix = \" << X1 << \"\\n\";\n\n    cx_mat kMid;\n    invCayley<T>(X1, idMat, kMid);\n\n   \tworld.push_back(X0);\n\n\t\tfor(int i = 1; i < (bufferSize); ++i)\n  \t{\n\t\t\tkMid *= -0.5 * (i/static_cast<double>(bufferSize));\n   \t\tcayley<T>(kMid, idMat, X0);\n  \t\tworld.push_back(X0);\n  \t}\n\n    world.push_back(X1);\n    cout << \"Number of leap-frog points = \"<< world.size() << \"\\n\";\n\t}\n\n\n\t/*\n\t\t* int tag = 4 * rank;\n\t\t* need to send/recv 4 unique things\n\t\t* send and recieves have tag and tag+1 internally\n\t\t*\n\t*/\n\n\tint tag = 4 * rank;\n\tint offSet = 0;\n\n\tdouble localEnergy;\n\tdouble totalEnergy = 0;\n\n\tcx_mat bL(amoebaParam.matSize, amoebaParam.matSize);\n\tcx_mat bU(amoebaParam.matSize, amoebaParam.matSize);\n\tcx_mat newBound(amoebaParam.matSize, amoebaParam.matSize);\n\n\n\tvector<vec> newGuess;\n\tnewGuess.resize(amoebaParam.nGridPoints);\n\n\tfor(int i=0; i<amoebaParam.nGridPoints; ++i)\n\t{\n\t\tnewGuess[i] = randu<vec>(amoebaParam.lieDimension);\n\t}\n\t/*\n\t\t* to keep track of where all the solvers are\n\t\t* each solver has to advance across the world\n\t\t* taking two boundary points\n\t\t* and outputing a new boundary\n\t*/\n\n\tint indLow;\n\tint indUp;\n\tint indMid;\n\n\tbufferSize = bufferSize + 1;\n\n\tint iters = 0;\n\n\twhile(iters < amoebaParam.maxMainIters )\n\t{\n\t\tif(rank==0)\n\t\t{\n\t\t\tfor(int src = 1; src < size; ++src)\n\t\t\t{\n\t\t\t\tindLow = (2 * src + offSet)%(bufferSize) ;\n\t\t\t\tindUp = (indLow + 2)%(bufferSize);\n\t\t\t\tif(indUp < indLow)\n\t\t\t\t{\n\t\t\t\t\tindLow = 0;\n\t\t\t\t\tindUp = indLow + 2;\n\t\t\t\t}\n\n\t\t\t\t//cout << \"sending boundaries to \" << src << endl;\n\t\t\t\t//cout << \"sending \" << indLow << \" and \" << indUp << endl;\n\n\t\t\t\tif(size > 0)\n\t\t\t\t{\n\t\t\t\t\tarmaMPI->matDestroySend(world[indLow], src, 4 * src );\n\t\t\t\t\tarmaMPI->matDestroySend(world[indUp], src, (4 * src) + 2);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tindLow = offSet%bufferSize;\n\t\t\tindUp = (indLow + 2)%(bufferSize);\n\t\t\tif(indUp < indLow)\n\t\t\t{\n\t\t\t\tindLow = 0;\n\t\t\t\tindUp = indLow + 2;\n\t\t\t}\n\t\t\tindMid = indLow + 1;\n\t\t\t//cout << \"solving on \" << indLow << \" and \" << indUp << endl;\n\n\t\t\tamoeba->curveSeeder(newGuess, amoebaParam.nGridPoints, world[indUp]);\n\t\t\tamoeba->solver(newGuess, world[indLow], world[indUp]);\n\t\t\tamoeba->newBoundary(world[indMid]);\n\t\t\tlocalEnergy = amoeba->getEnergy();\n\n\t\t\tfor(int src = 1; src < size; ++src)\n\t\t\t{\n\t\t\t\tindLow = (2 * src + offSet)%(bufferSize) ;\n\t\t\t\tindUp = (indLow + 2)%(bufferSize);\n\t\t\t\tif(indUp < indLow)\n\t\t\t\t{\n\t\t\t\t\tindLow = 0;\n\t\t\t\t}\n\t\t\t\tindMid = indLow + 1;\n\n\t\t\t\tworld[indMid] = armaMPI->matConstructRecv(src, 4 * src);\n\t\t\t\t//cout << \"recieved updated boundary from\" << src << endl;\n\t\t\t}\n\n\t\t\toffSet +=1;\n\t\t\toffSet = (offSet)%(bufferSize);\n\t\t\t//cout << \"offSet is now \" << offSet << endl;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tbL = armaMPI->matConstructRecv(0, tag);\n\t\t\tbU = armaMPI->matConstructRecv(0, tag + 2);\n\t\t\tamoeba->curveSeeder(newGuess, amoebaParam.nGridPoints, bU);\n\n\t\t\t//cout << \"recieved boundary on thread \" << rank << endl;\n\n\t\t\tamoeba->solver(newGuess, bL, bU);\n\t\t\tamoeba->newBoundary(newBound);\n\t\t\tarmaMPI->matDestroySend(newBound, 0, tag);\n\t\t\tlocalEnergy = amoeba->getEnergy();\n\t\t}\n\n\t\tMPI_Reduce(&localEnergy, &totalEnergy, size, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);\n\n\t\tif(rank == 0)\n\t\t{\n\t\t\tofstream energyFile;\n\t\t\tenergyFile.open(\"eOut.txt\", ios::app);\n\t\t\tenergyFile << totalEnergy << endl;\n\t\t\tcout << \"iters\" << iters << endl;\n\t\t\tcout << \"=======================\" << endl;\n\t\t\ttotalEnergy = 0 ;\n\n\t\t}\n\n\n\t\t++iters;\n\t}\n\n\tif(rank == 0)\n\t{\n\t\tfor(int i = 0; i < (2 * size - 1); ++i)\n\t\t{\n\t\t\tcout << \"boundary is now\" << world[i] << world[i+2];\n\t\t\tamoeba->curveSeeder(newGuess, amoebaParam.nGridPoints, world[i + 2]);\n\t\t\tamoeba->solver(newGuess, world[i], world[i + 2]);\n\t\t\tamoeba->curvePrint();\n\t\t\tamoeba->newBoundary(world[i+1]);\n\n\t\t}\n\t}\n\n\tdelete armaMPI;\n}\n", "meta": {"hexsha": "191407fe6d239b81de937255ac981e354f3d69ba", "size": 5073, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/solvers/segSolver.cpp", "max_stars_repo_name": "Swaddle/qGeod", "max_stars_repo_head_hexsha": "8108fe44c09c0c89b23cf5f14efa098b09d6bcf3", "max_stars_repo_licenses": ["MIT"], "max_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/segSolver.cpp", "max_issues_repo_name": "Swaddle/qGeod", "max_issues_repo_head_hexsha": "8108fe44c09c0c89b23cf5f14efa098b09d6bcf3", "max_issues_repo_licenses": ["MIT"], "max_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/segSolver.cpp", "max_forks_repo_name": "Swaddle/qGeod", "max_forks_repo_head_hexsha": "8108fe44c09c0c89b23cf5f14efa098b09d6bcf3", "max_forks_repo_licenses": ["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.5466666667, "max_line_length": 173, "alphanum_fraction": 0.6339444116, "num_tokens": 1679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952052, "lm_q2_score": 0.6477982043529716, "lm_q1q2_score": 0.45509770968460406}}
{"text": "//------------------------------------------------------------------------------\n// \\file LazyValuation_tests.cpp\n//------------------------------------------------------------------------------\n\n#include <boost/test/unit_test.hpp>\n\n#include \"Utilities/LazyValuation.h\"\n\nusing Utilities::LazyValuation;\n\nBOOST_AUTO_TEST_SUITE(Utilities)\nBOOST_AUTO_TEST_SUITE(LazyValuation_tests)\n\n// cf. http://pedromelendez.com/blog/2015/07/16/recursive-lambdas-in-c14/\n// We cannot capture a variable declared using auto in its own initialization.\n// lambdas in C++ are unique and unnamed; how to reference the function object\n// cannot use this keyword inside body of lambda.\nauto fibonacci = [](int x)\n{\n\tauto implementation = [](int x, const auto& implementation) -> int\n\t{\n\t\tif (x == 0 || x == 1)\n\t\t{\n\t\t\treturn 1;\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn implementation(x - 1, implementation) +\n\t\t\t\timplementation(x - 2, implementation);\n\t\t}\n\t};\n\n\treturn implementation(x, implementation);\n};\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(LazyValuationConstructs)\n{\n\tBOOST_TEST(fibonacci(0) == 1);\n\tBOOST_TEST(fibonacci(1) == 1);\n\tBOOST_TEST(fibonacci(2) == 2);\n\tBOOST_TEST(fibonacci(3) == 3);\n\tBOOST_TEST_REQUIRE(fibonacci(4) == 5);\n\n\tauto fibonacci_5 = []()\n\t{\n\t\treturn fibonacci(5);\n\t};\n\n\tLazyValuation lazy_fibonacci_5_valuation {fibonacci_5};\n\n\tBOOST_TEST(lazy_fibonacci_5_valuation == 8);\n}\n\n// \\ref https://gitlab.com/manning-fpcpp-book/code-examples/blob/master/chapter-06/lazy-val/main.cpp\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(IsInvocableWorks)\n{\n\tconstexpr int number {6};\n\n}\n\nBOOST_AUTO_TEST_SUITE_END() // LazyValuation_tests\n\n// cf. https://nalaginrut.com/archives/2019/10/31/8%20essential%20patterns%20you%20should%20know%20about%20functional%20programming%20in%20c%2B%2B14\n\nBOOST_AUTO_TEST_SUITE(Lazy_tests)\n\n// Thunk is a nullary function, say, a function without any parameters.\nusing thunk_t = std::function<int(void)>; \n// Return type is trivial, point is \"nullary\".\n// Why does \"nullary\" matter? You have closure, so you can capture values you\n// need, parameters are unnnecessary for us. May realize that thunk may help you\n// to unify interface.\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(DemonstrateLazyPattern)\n{\n\t{\n\t\tint x {5};\n\t\tauto thunk = \n\t\t\t[x]()\n\t\t\t\t{\n\t\t\t\t\tstd::cout << \"now it run\" << std::endl;\n\t\t\t\t};\n\n\t\tstd::cout << \"Thunk will not run before you run it\" << std::endl;\n\t\tthunk();\n\n\t\tBOOST_TEST(true);\n\t}\n}\n\ntemplate <typename T>\nusing UnaryF_t = std::function<T(void)>;\n\n// https://stackoverflow.com/questions/265392/why-is-lazy-evaluation-useful\n// https://bartoszmilewski.com/2014/04/21/getting-lazy-with-c/\n// https://github.com/BartoszMilewski/Okasaki/blob/master/LazyQueue/Queue.h\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(SquareAsLazyEvaluation)\n{\n\t{\n\t\tdouble external_x {2};\n\t\tauto thunk = \n\t\t\t[&external_x]()\n\t\t\t{\n\t\t\t\treturn external_x * external_x;\n\t\t\t};\n\n\t\texternal_x = thunk();\n\t\texternal_x = thunk();\n\t\texternal_x = thunk();\n\t\tBOOST_TEST(external_x == 256);\n\t}\n}\n\nBOOST_AUTO_TEST_SUITE_END() // Lazy_tests\nBOOST_AUTO_TEST_SUITE_END() // Utilities", "meta": {"hexsha": "b744d26d8b7cf9974a4e814dc1ac671dc2ac2791", "size": 3634, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Voltron/Source/UnitTests/Utilities/LazyValuation_tests.cpp", "max_stars_repo_name": "ernestyalumni/HrdwCCppCUDA", "max_stars_repo_head_hexsha": "17ed937dea06431a4d5ca103f993ea69a6918734", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-02-09T19:44:51.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-09T19:44:51.000Z", "max_issues_repo_path": "Voltron/Source/UnitTests/Utilities/LazyValuation_tests.cpp", "max_issues_repo_name": "ernestyalumni/HrdwCCppCUDA", "max_issues_repo_head_hexsha": "17ed937dea06431a4d5ca103f993ea69a6918734", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Voltron/Source/UnitTests/Utilities/LazyValuation_tests.cpp", "max_forks_repo_name": "ernestyalumni/HrdwCCppCUDA", "max_forks_repo_head_hexsha": "17ed937dea06431a4d5ca103f993ea69a6918734", "max_forks_repo_licenses": ["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.5447154472, "max_line_length": 148, "alphanum_fraction": 0.5602641717, "num_tokens": 815, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593452091672, "lm_q2_score": 0.7310585903489892, "lm_q1q2_score": 0.4550542514581687}}
{"text": "#include <stan/math/prim.hpp>\n#include <test/unit/math/prim/util.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/math/distributions/chi_squared.hpp>\n#include <gtest/gtest.h>\n#include <stdexcept>\n#include <vector>\n\nTEST(ProbDistributionsInvWishartCholesky, rng) {\n  using Eigen::Dynamic;\n  using Eigen::Matrix;\n  using Eigen::MatrixXd;\n\n  using stan::math::inv_wishart_cholesky_rng;\n\n  boost::random::mt19937 rng;\n\n  MatrixXd omega(3, 4);\n  EXPECT_THROW(inv_wishart_cholesky_rng(3.0, omega, rng), std::domain_error);\n\n  MatrixXd sigma(3, 3);\n  sigma << 9.0, -3.0, 0.0, -3.0, 4.0, 1.0, 0.0, 1.0, 3.0;\n\n  Matrix<double, Dynamic, Dynamic> LS = sigma.llt().matrixL();\n\n  EXPECT_NO_THROW(inv_wishart_cholesky_rng(3.0, LS, rng));\n  EXPECT_THROW(inv_wishart_cholesky_rng(2, LS, rng), std::domain_error);\n  EXPECT_THROW(inv_wishart_cholesky_rng(-1, LS, rng), std::domain_error);\n  LS(2, 2) = -1;\n  EXPECT_THROW(inv_wishart_cholesky_rng(3.0, LS, rng), std::domain_error);\n}\n\nTEST(ProbDistributionsInvWishartCholesky, rng_pos_def) {\n  using Eigen::MatrixXd;\n  using stan::math::inv_wishart_cholesky_rng;\n\n  boost::random::mt19937 rng;\n\n  MatrixXd Sigma(2, 2);\n  MatrixXd Sigma_non_pos_def(2, 2);\n\n  Sigma << 1, 0, 0, 1;\n  Sigma_non_pos_def << -1, 0, 0, 1;\n\n  unsigned int dof = 5;\n\n  EXPECT_NO_THROW(inv_wishart_cholesky_rng(dof, Sigma, rng));\n  EXPECT_THROW(inv_wishart_cholesky_rng(dof, Sigma_non_pos_def, rng),\n               std::domain_error);\n}\n\nTEST(ProbDistributionsInvWishartCholesky, marginalTwoChiSquareGoodnessFitTest) {\n  using boost::math::chi_squared;\n  using boost::math::digamma;\n  using Eigen::MatrixXd;\n  using stan::math::determinant;\n  using stan::math::inv_wishart_cholesky_rng;\n  using std::log;\n\n  boost::random::mt19937 rng;\n  MatrixXd sigma(3, 3);\n  sigma << 9.0, -3.0, 2.0, -3.0, 4.0, 0.0, 2.0, 0.0, 3.0;\n\n  MatrixXd siginv(3, 3);\n  siginv = sigma.inverse();\n  int N = 10000;\n\n  double avg = 0;\n  double expect = sigma.rows() * log(2.0) + log(determinant(siginv))\n                  + digamma(5.0 / 2.0) + digamma(4.0 / 2.0)\n                  + digamma(3.0 / 2.0);\n\n  MatrixXd a(sigma.rows(), sigma.rows());\n  for (int count = 0; count < N; ++count) {\n    a = inv_wishart_cholesky_rng(5.0, stan::math::cholesky_decompose(sigma),\n                                 rng);\n    avg += stan::math::sum(stan::math::log(a.diagonal()));\n  }\n  avg /= N;\n  double chi = (expect - avg) * (expect - avg) / expect;\n  chi_squared mydist(1);\n  EXPECT_TRUE(chi < quantile(complement(mydist, 1e-6)));\n}\n\nTEST(ProbDistributionsInvWishartCholesky, SpecialRNGTest) {\n  // When the scale matrix is an identity matrix and df = k + 2\n  // The avg of the samples should also be an identity matrix\n\n  using Eigen::MatrixXd;\n  using stan::math::inv_wishart_cholesky_rng;\n  using stan::math::multiply_lower_tri_self_transpose;\n\n  boost::random::mt19937 rng(1234U);\n  int N = 1e5;\n  double tol = 0.1;\n  for (int k = 1; k < 5; k++) {\n    MatrixXd sigma = MatrixXd::Identity(k, k);\n    MatrixXd Z = MatrixXd::Zero(k, k);\n    for (int i = 0; i < N; i++) {\n      Z += stan::math::crossprod(inv_wishart_cholesky_rng(k + 2, sigma, rng));\n    }\n    Z /= N;\n    for (int j = 0; j < k; j++) {\n      for (int i = 0; i < k; i++) {\n        if (j == i)\n          EXPECT_NEAR(Z(i, j), 1.0, tol);\n        else\n          EXPECT_NEAR(Z(i, j), 0.0, tol);\n      }\n    }\n  }\n}\n", "meta": {"hexsha": "e33c885b70a44f40f1443eb99d774201325e1721", "size": 3360, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/prim/prob/inv_wishart_cholesky_rng_test.cpp", "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": "test/unit/math/prim/prob/inv_wishart_cholesky_rng_test.cpp", "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": "test/unit/math/prim/prob/inv_wishart_cholesky_rng_test.cpp", "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": 29.7345132743, "max_line_length": 80, "alphanum_fraction": 0.6470238095, "num_tokens": 1160, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585903489891, "lm_q2_score": 0.6224593382055109, "lm_q1q2_score": 0.4550542463380855}}
{"text": "//\n//  tFEM.hpp\n//\n//  Created by r. on 09/05/14\n//\n\n#ifndef round1_tFEM_hpp\n#define round1_tFEM_hpp\n\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_sparse.hpp>\n\n#include \"tmesh.hpp\"\n#include \"stopwatch.hpp\"\n//#include \"EVD.hpp\"\n#include \"AWT.hpp\"\n\n//#include <algorithm>\n\nnamespace spacetime\n{\n\tnamespace ublas = boost::numeric::ublas;\n\n\tclass tFEM\n\t{\n\tpublic:\n\t\ttypedef ublas::compressed_matrix<double> sparse_matrix;\n\t\ttypedef ublas::matrix<double> dense_matrix;\n\t\ttypedef ublas::vector<double> vector;\n\tpublic:\n\t\t// Should be hidden\n\t\tsparse_matrix MtE, AtE;\n\t\tsparse_matrix MtF;\n\t\tsparse_matrix CtFE, MtFE;\n\t\tsparse_matrix EtE;\n\t\tdense_matrix VtE;\n\t\tvector gamma;\n//\tpublic:\n//\t\tconst sparse_matrix& getMtE() const { return MtE; }\n//\t\tconst sparse_matrix& getAtE() const { return AtE; }\n//\t\tconst sparse_matrix& getMtF() const { return MtF; }\n//\t\tconst sparse_matrix& getCtFE() const { return CtFE; }\n//\t\tconst sparse_matrix& getMtFE() const { return MtFE; }\n//\t\tconst sparse_matrix& getEtE() const { return EtE; }\n//\t\tconst dense_matrix& getVtE() const { return VtE; }\n//\t\tconst vector& getgamma() const { return gamma; }\n\tprivate:\n\t\ttmesh TE, TF;\n\t\tunsigned int nref;\n\tpublic:\n\t\t// Should be hidden\n\t\tunsigned int dimE;\n\t\tunsigned int dimF;\n\tpublic:\n\t\tconst tmesh& refTE() const { return TE; }\n\t\tconst tmesh& refTF() const { return TF; }\n//\t\tunsigned int dimE() const { return (unsigned int)(TE.size()); }\n//\t\tunsigned int dimF() const { return (unsigned int)(TF.size() - 1); }\n\tpublic:\n\t\tvoid perform_evd()\n\t\t{\n\t\t\tstopwatch::Time time(stopwatch::watches, \"tFEM::perform_evd()\");\n\t\t\t\n\t\t\t{\n\t\t\t\t//gsl::EVD evd(AtE, MtE);\n\t\t\t\t//spacetime::AWT evd(AtE, MtE);\n\t\t\t\t//VtE = evd.V;\n\t\t\t\t//gamma = evd.d;\n\t\t\t\t//assert(gamma.size() == TE.size());\n\t\t\t\t\n\t\t\t\tVtE.resize(0, 0);\n\t\t\t\tgamma.resize(0);\n\t\t\t}\n\t\t\t\n\t\t\tfor (vector::iterator i = gamma.begin(); i != gamma.end(); ++i)\n\t\t\t\t(*i) = sqrt(std::max(0.0, *i));\n\t\t}\n\tpublic:\n\t\tvoid assemble_matrices()\n\t\t{\n\t\t\tstopwatch::Time time(stopwatch::watches, \"tFEM::assemble_matrices()\");\n\t\t\t\n\t\t\t// nref >= 1 not implemented\n\t\t\tassert(nref == 0);\n\t\t\t\n\t\t\ttypedef ublas::mapped_matrix<double> mapped_matrix;\n\t\t\tmapped_matrix MtE(dimE, dimE, 3*dimE); MtE.clear();\n\t\t\tmapped_matrix AtE(dimE, dimE, 3*dimE); AtE.clear();\n\t\t\t{\n\t\t\t\tstd::vector<tmesh::interval> Is = TE.getIs();\n\t\t\t\tfor (auto n = 0; n != Is.size(); ++n)\n\t\t\t\t{\n\t\t\t\t\tunsigned int m = n + 1;\n\t\t\t\t\t\n\t\t\t\t\tdouble h = Is[n].len;\n\t\t\t\t\tMtE(n, n) += (2./6.) * h;\n\t\t\t\t\tMtE(m, m) += (2./6.) * h;\n\t\t\t\t\tMtE(m, n) += (1./6.) * h;\n\t\t\t\t\tMtE(n, m) += (1./6.) * h;\n\t\t\t\t\t\n\t\t\t\t\tdouble g = 1 / h;\n\t\t\t\t\tAtE(n, n) += +g;\n\t\t\t\t\tAtE(m, m) += +g;\n\t\t\t\t\tAtE(m, n) += -g;\n\t\t\t\t\tAtE(n, m) += -g;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tmapped_matrix MtF(dimF, dimF, dimF); MtF.clear();\n\t\t\t{\n\t\t\t\tstd::vector<tmesh::interval> Is = TF.getIs();\n\t\t\t\tfor (auto i = 0; i != Is.size(); ++i)\n\t\t\t\t{\n\t\t\t\t\tMtF(i, i) = Is[i].len;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tmapped_matrix CtFE(dimF, dimE, 2*dimF); CtFE.clear();\n\t\t\tmapped_matrix MtFE(dimF, dimE, 2*dimF); MtFE.clear();\n\t\t\t{\n\t\t\t\tstd::vector<tmesh::interval> Is = TE.getIs();\n\t\t\t\tfor (auto n = 0; n != Is.size(); ++n)\n\t\t\t\t{\n\t\t\t\t\tMtFE(n, n+0) += (1./2.) * Is[n].len;\n\t\t\t\t\tMtFE(n, n+1) += (1./2.) * Is[n].len;\n\t\t\t\t\t\n\t\t\t\t\tCtFE(n, n+0) += -1;\n\t\t\t\t\tCtFE(n, n+1) += +1;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tmapped_matrix EtE(1, dimE, 1); EtE.clear();\n\t\t\t{\n\t\t\t\tEtE(0, 0) = 1;\n\t\t\t}\n\t\t\t\n\t\t\tthis->MtE = MtE;\n\t\t\tthis->AtE = AtE;\n\t\t\tthis->MtF = MtF;\n\t\t\tthis->CtFE = CtFE;\n\t\t\tthis->MtFE = MtFE;\n\t\t\tthis->EtE = EtE;\n\t\t}\n\tpublic:\n\t\ttFEM(const tmesh& te, unsigned nref = 0, bool perform_evd_now = true)\n\t\t:\n\t\tTE(te), TF(te), nref(nref), dimE(0), dimF(0)\n\t\t{\n\t\t\tfor (unsigned int n = 0; n != nref; ++n)\n\t\t\t\tTF.refine();\n\t\t\t\n\t\t\tdimE = (unsigned int)(TE.size());\n\t\t\tdimF = (unsigned int)(TF.size() - 1);\n\t\t\t\n\t\t\tassemble_matrices();\n\t\t\t\n\t\t\tif (perform_evd_now) perform_evd();\n\t\t}\n\t};\n\n} // namespace spacetime\n\n#endif\n", "meta": {"hexsha": "5eeb6cac0c286963f07235659689815929d55aaf", "size": 3914, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "parawt/c++/include/tFEM.hpp", "max_stars_repo_name": "numpde/parabolic", "max_stars_repo_head_hexsha": "7d102f19c0991d720779f4b5d456571794651b17", "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": "parawt/c++/include/tFEM.hpp", "max_issues_repo_name": "numpde/parabolic", "max_issues_repo_head_hexsha": "7d102f19c0991d720779f4b5d456571794651b17", "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": "parawt/c++/include/tFEM.hpp", "max_forks_repo_name": "numpde/parabolic", "max_forks_repo_head_hexsha": "7d102f19c0991d720779f4b5d456571794651b17", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.7212121212, "max_line_length": 73, "alphanum_fraction": 0.5781808891, "num_tokens": 1407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585903489891, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.45505424121800236}}
{"text": "#define BOOST_TEST_MODULE KernelGenerator\n#include <boost/test/unit_test.hpp>\n#include <boost/phoenix/phoenix.hpp>\n#include <vexcl/vector.hpp>\n#include <vexcl/generator.hpp>\n#include <vexcl/tagged_terminal.hpp>\n#include \"context_setup.hpp\"\n\ntemplate <class state_type>\nstate_type sys_func(const state_type &x) {\n    return sin(x);\n}\n\ntemplate <class state_type, class SysFunction>\nvoid runge_kutta_2(SysFunction sys, state_type &x, double dt) {\n    state_type k1 = dt * sys(x);\n    state_type k2 = dt * sys(x + 0.5 * k1);\n\n    x += k2;\n}\n\nBOOST_AUTO_TEST_CASE(kernel_generator)\n{\n    typedef vex::symbolic<double> sym_state;\n\n    const size_t n  = 1024;\n    const double dt = 0.01;\n\n    std::ostringstream body;\n    vex::generator::set_recorder(body);\n\n    sym_state sym_x(sym_state::VectorParameter);\n\n    // Record expression sequence.\n    runge_kutta_2(sys_func<sym_state>, sym_x, dt);\n\n    // Build kernel.\n    auto kernel = vex::generator::build_kernel(\n            ctx, \"rk2_stepper\", body.str(), sym_x);\n\n    std::vector<double> x = random_vector<double>(n);\n    vex::vector<double> X(ctx, x);\n\n    for(int i = 0; i < 100; i++) kernel(X);\n\n    check_sample(X, [&](size_t idx, double a) {\n            double s = x[idx];\n            for(int i = 0; i < 100; i++)\n                runge_kutta_2(sys_func<double>, s, dt);\n\n            BOOST_CHECK_CLOSE(a, s, 1e-8);\n            });\n}\n\nBOOST_AUTO_TEST_CASE(kernel_generator_with_user_function)\n{\n    typedef vex::symbolic<double> sym_state;\n\n    const size_t n  = 1024;\n\n    std::ostringstream body;\n    vex::generator::set_recorder(body);\n\n    sym_state sym_x(sym_state::VectorParameter, sym_state::Const);\n    sym_state sym_y(sym_state::VectorParameter);\n\n    VEX_FUNCTION(double, sin2, (double, x),\n            double s = sin(x);\n            return s * s;\n            );\n\n    sym_y = sin2(sym_x);\n\n    auto kernel = vex::generator::build_kernel(\n            ctx, \"test_sin2\", body.str(), sym_x, sym_y);\n\n    vex::vector<double> X(ctx, random_vector<double>(n));\n    vex::vector<double> Y(ctx, n);\n\n    for(int i = 0; i < 100; i++) kernel(X, Y);\n\n    check_sample(X, Y, [&](size_t, double x, double y) {\n            BOOST_CHECK_CLOSE(y, sin(x) * sin(x), 1e-8);\n            });\n}\nBOOST_AUTO_TEST_CASE(function_generator)\n{\n    typedef vex::symbolic<double> sym_state;\n\n    const size_t n  = 1024;\n    const double dt = 0.01;\n\n    std::ostringstream body;\n    vex::generator::set_recorder(body);\n\n    sym_state sym_x(sym_state::VectorParameter);\n\n    // Record expression sequence.\n    runge_kutta_2(sys_func<sym_state>, sym_x, dt);\n\n    // Build function.\n    // Body string has to be static:\n    static std::string function_body = vex::generator::make_function(\n            body.str(), sym_x, sym_x);\n\n    VEX_FUNCTION_S(double, rk2, (double, prm1), function_body);\n\n    std::vector<double> x = random_vector<double>(n);\n    vex::vector<double> X(ctx, x);\n\n    for(int i = 0; i < 100; i++) {\n        X = rk2(X);\n    }\n\n    check_sample(X, [&](size_t idx, double a) {\n            double s = x[idx];\n            for(int i = 0; i < 100; i++)\n                runge_kutta_2(sys_func<double>, s, dt);\n\n            BOOST_CHECK_CLOSE(a, s, 1e-8);\n            });\n}\n\nstruct rk2_stepper {\n    double dt;\n\n    rk2_stepper(double dt) : dt(dt) {}\n\n    template <class State>\n    State operator()(const State &x) const {\n        State new_x = x;\n        runge_kutta_2(sys_func<State>, new_x, dt);\n        return new_x;\n    }\n};\n\nBOOST_AUTO_TEST_CASE(function_adapter)\n{\n    const size_t n  = 1024;\n    const double dt = 0.01;\n\n    rk2_stepper step(dt);\n\n    auto rk2 = vex::generator::make_function<double(double)>(step);\n\n    std::vector<double> x = random_vector<double>(n);\n    vex::vector<double> X(ctx, x);\n\n    for(int i = 0; i < 100; i++) {\n        X = rk2(X);\n    }\n\n    check_sample(X, [&](size_t idx, double a) {\n            double s = x[idx];\n            for(int i = 0; i < 100; i++) s = step(s);\n\n            BOOST_CHECK_CLOSE(a, s, 1e-8);\n            });\n}\n\nBOOST_AUTO_TEST_CASE(function_adapter_and_phoenix_lambda)\n{\n    using namespace boost::phoenix::arg_names;\n\n    const size_t n  = 1024;\n\n    auto squared_radius = vex::generator::make_function<double(double, double)>(\n            arg1 * arg1 + arg2 * arg2);\n\n    vex::vector<double> X(ctx, random_vector<double>(n));\n    vex::vector<double> Y(ctx, random_vector<double>(n));\n\n    vex::vector<double> Z = squared_radius(X, Y);\n\n    check_sample(X, Y, Z, [&](size_t, double x, double y, double z) {\n            BOOST_CHECK_CLOSE(z, x * x + y * y, 1e-8);\n            });\n}\n\n/*\nAn alternative variant, which does not use the generator facility.\nIntermediate subexpression are captured with help of 'auto' keyword, and\nare combined into larger expression.\n\nNote how vex::tag<>() facilitates reuse of kernel parameters.\n*/\nBOOST_AUTO_TEST_CASE(lazy_evaluation)\n{\n    const size_t n  = 1024;\n    const double dt = 0.01;\n\n    auto rk2 = [](vex::vector<double> &x, double dt) {\n        auto X  = vex::tag<1>(x);\n        auto DT = vex::tag<2>(dt);\n\n        auto k1 = DT * sin(X);\n        auto x1 = X + 0.5 * k1;\n\n        auto k2 = DT * sin(x1);\n\n        x = X + k2;\n    };\n\n    std::vector<double> x = random_vector<double>(n);\n    vex::vector<double> X(ctx, x);\n\n    for(int i = 0; i < 100; i++) {\n        rk2(X, dt);\n    }\n\n    check_sample(X, [&](size_t idx, double a) {\n            double s = x[idx];\n            for(int i = 0; i < 100; i++)\n                runge_kutta_2(sys_func<double>, s, dt);\n\n            BOOST_CHECK_CLOSE(a, s, 1e-8);\n            });\n}\n\nBOOST_AUTO_TEST_CASE(element_index)\n{\n    const size_t n  = 1024;\n    std::vector<vex::command_queue> queue(1, ctx.queue(0));\n\n    typedef vex::symbolic<int> sym_vector;\n\n    std::ostringstream body;\n    vex::generator::set_recorder(body);\n\n    sym_vector sym_x(sym_vector::VectorParameter);\n\n    sym_x = vex::generator::index();\n    auto kernel = vex::generator::build_kernel(queue, \"element_index\", body.str(), sym_x);\n\n    vex::vector<int> x(queue, n);\n\n    kernel(x);\n\n    check_sample(x, [&](size_t idx, int i) { BOOST_CHECK_EQUAL(i, idx); });\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "127ae8318c1ab22cb0db0e1a8bc98103ad252093", "size": 6144, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "external_libraries/vexcl/tests/generator.cpp", "max_stars_repo_name": "lkusch/Kratos", "max_stars_repo_head_hexsha": "e8072d8e24ab6f312765185b19d439f01ab7b27b", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": 778.0, "max_stars_repo_stars_event_min_datetime": "2017-01-27T16:29:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T03:01:51.000Z", "max_issues_repo_path": "external_libraries/vexcl/tests/generator.cpp", "max_issues_repo_name": "lkusch/Kratos", "max_issues_repo_head_hexsha": "e8072d8e24ab6f312765185b19d439f01ab7b27b", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": 6634.0, "max_issues_repo_issues_event_min_datetime": "2017-01-15T22:56:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:03:36.000Z", "max_forks_repo_path": "external_libraries/vexcl/tests/generator.cpp", "max_forks_repo_name": "lkusch/Kratos", "max_forks_repo_head_hexsha": "e8072d8e24ab6f312765185b19d439f01ab7b27b", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": 224.0, "max_forks_repo_forks_event_min_datetime": "2017-02-07T14:12:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-06T23:09:34.000Z", "avg_line_length": 25.2839506173, "max_line_length": 90, "alphanum_fraction": 0.6041666667, "num_tokens": 1703, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300048, "lm_q2_score": 0.6224593382055109, "lm_q1q2_score": 0.45505423904349424}}
{"text": "// [[Rcpp::plugins(cpp11)]]\n// [[Rcpp::plugins(openmp)]]\n// [[Rcpp::depends(RcppProgress)]]\n// [[Rcpp::depends(BH)]]\n\n#include <Rcpp.h>\n#include <progress.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/variance.hpp>\n#include \"IntrogressionSimulations.h\"\n#include \"Rcpp_output.h\"\n#include \"random.h\"\n\n#ifdef _OPENMP\n    #include <omp.h>\n#endif\n\nRcpp::List Rcpp_WriteOutput(const Parameters &GlobalPars, SimData &SimulationData){\n    using namespace boost::accumulators;\n\n    Rcpp::DataFrame parsdata =  Rcpp::DataFrame::create(\n        Rcpp::_[\"NINIT0\"] = GlobalPars.NINIT[0], \n        Rcpp::_[\"NINIT1\"] = GlobalPars.NINIT[1],\n        Rcpp::_[\"NGEN\"] = GlobalPars.NGEN,\n        Rcpp::_[\"NREP\"] = GlobalPars.NREP,\n        Rcpp::_[\"NLOCI\"] = GlobalPars.NLOCI,\n        Rcpp::_[\"RECOMBINATIONRATE\"] = GlobalPars.RECOMBINATIONRATE,\n        Rcpp::_[\"GROWTHRATE\"] = GlobalPars.BIRTHRATE,\n        Rcpp::_[\"CARRYINGCAPACITY\"] = GlobalPars.K,\n        Rcpp::_[\"INDEX_MAJOR\"] = GlobalPars.index[0]\n    );\n    const int NREP = SimulationData.DataSet.size();\n \n    // Write outputfiles\n    Rcpp::NumericVector generation(GlobalPars.NGEN);    \n    Rcpp::NumericVector popsizevecm(GlobalPars.NGEN);\n    Rcpp::NumericVector major0vecm(GlobalPars.NGEN);\n    Rcpp::NumericVector major1vecm(GlobalPars.NGEN);\n    Rcpp::NumericVector introgressed0vecm(GlobalPars.NGEN);\n    Rcpp::NumericVector introgressed1vecm(GlobalPars.NGEN);\n    Rcpp::NumericVector popsizevecv(GlobalPars.NGEN);\n    Rcpp::NumericVector major0vecv(GlobalPars.NGEN);\n    Rcpp::NumericVector major1vecv(GlobalPars.NGEN);\n    Rcpp::NumericVector introgressed0vecv(GlobalPars.NGEN);\n    Rcpp::NumericVector introgressed1vecv(GlobalPars.NGEN);\n  \n    for(int i = 0; i < GlobalPars.NGEN; ++i){\n        accumulator_set<int, stats<tag::mean, tag::variance > > popsize;\n        accumulator_set<double, stats<tag::mean, tag::variance > > major0;\n        accumulator_set<double, stats<tag::mean, tag::variance > > major1;\n        accumulator_set<double, stats<tag::mean, tag::variance > > introgressed0;\n        accumulator_set<double, stats<tag::mean, tag::variance > > introgressed1;\n\n        for(int j = 0; j < NREP; ++j){\n            popsize(SimulationData.DataSet[j]->popsize[i]);\n            major0((double)SimulationData.DataSet[j]->major0[i]);\n            major1((double)SimulationData.DataSet[j]->major1[i]);\n            introgressed0(SimulationData.DataSet[j]->introgressed0[i]);\n            introgressed1(SimulationData.DataSet[j]->introgressed1[i]);\n        }\n        generation[i] = i;\n        popsizevecm[i] = mean(popsize);\n        major0vecm[i] = mean(major0);\n        major1vecm[i] = mean(major1);\n        introgressed0vecm[i] = mean(introgressed0);\n        introgressed1vecm[i] = mean(introgressed1);\n        popsizevecv[i] = variance(popsize);\n        major0vecv[i] = variance(major0);\n        major1vecv[i] = variance(major1);\n        introgressed0vecv[i] = variance(introgressed0);\n        introgressed1vecv[i] = variance(introgressed1);\n    };\n    \n    Rcpp::DataFrame data =  Rcpp::DataFrame::create(\n        Rcpp::_[\"Generation\"] = generation,\n        Rcpp::_[\"Popsize_avg\"] = (popsizevecm), \n        Rcpp::_[\"Major0_avg\"] = (major0vecm), \n        Rcpp::_[\"Major1_avg\"] = (major1vecm), \n        Rcpp::_[\"Introgressed0_avg\"] = (introgressed0vecm), \n        Rcpp::_[\"Introgressed1_avg\"] = (introgressed1vecm),\n        Rcpp::_[\"Popsize_var\"] = (popsizevecv), \n        Rcpp::_[\"Major0_var\"] = (major0vecv), \n        Rcpp::_[\"Major1_var\"] = (major1vecv), \n        Rcpp::_[\"Introgressed0_var\"] = (introgressed0vecv), \n        Rcpp::_[\"Introgressed1_var\"] = (introgressed1vecv)\n    );\n\n    std::vector<Rcpp::NumericVector> allelefrequencymean(GlobalPars.NLOCI);\n    std::vector<Rcpp::NumericVector> allelefrequencyvar(GlobalPars.NLOCI);\n\n    for(int i = 0; i < GlobalPars.NLOCI; ++i){\n        allelefrequencymean[i] = Rcpp::NumericVector(GlobalPars.NGEN); \n        allelefrequencyvar[i] = Rcpp::NumericVector(GlobalPars.NGEN); \n    }\n\n    for(int i = 0; i < GlobalPars.NGEN; ++i){\n        for(int l = 0; l < GlobalPars.NLOCI; ++l)\n        {\n            accumulator_set<double, stats<tag::mean, tag::variance > > locus;\n            for(int r = 0; r < NREP; ++r)\n            {\n                locus((double)SimulationData.DataSet[r]->allele0[i][l] / ((double)SimulationData.DataSet[r]->popsize[i]));\n            }\n            allelefrequencymean[l][i] = mean(locus);\n            allelefrequencyvar[l][i] = variance(locus);\n        }\n    }   \n\n    Rcpp::DataFrame alleledatamean, alleledatavar;\n    std::string avglocus = \"avglocus\", varlocus = \"varlocus\";\n    alleledatamean.push_back(generation,\"Generation\");\n    alleledatavar.push_back(generation,\"Generation\");\n    for(int i = 0; i < GlobalPars.NLOCI; ++i){\n        alleledatamean.push_back((allelefrequencymean[i]), avglocus+std::to_string(i));\n        alleledatavar.push_back((allelefrequencyvar[i]), varlocus+std::to_string(i));\n    }\n\n    double fixation = (double)NREP/(double(NREP+SimulationData.nofixcounter.load()));\n       \n    // Cleanup\n    for(int i = 0; i < NREP; ++i){\n        delete SimulationData.DataSet[i];\n    }\n    SimulationData.DataSet.clear();\n\n    return Rcpp::List::create(\n        Rcpp::_[\"pars\"] = (parsdata),\n        Rcpp::_[\"data\"] = (data),\n        Rcpp::_[\"allelefavg\"] = (alleledatamean),\n        Rcpp::_[\"allelefvar\"] = (alleledatavar),\n        Rcpp::_[\"fixation\"] = fixation\n    );\n\n}\n\n// [[Rcpp::export]]\nRcpp::List RcppIntrogressionSimulation(Rcpp::List parslist, int setthreads = 0, bool progressbar = false){\n    \n    // Prepare for simulation\n    rnd::set_seed();\n    const Parameters GlobalPars(parslist);\n    SimData SimulationData;\n\n    // Run nrep successful simulations\n    #ifdef _OPENMP\n        const static int maxthreads = omp_get_max_threads();\n        if(setthreads>0) omp_set_num_threads(setthreads);\n        else omp_set_num_threads(maxthreads);\n        REprintf(\"Parallel activated : Number of threads=%i\\n\",omp_get_max_threads());   \n    #endif\n    //if(progressbar == true) Progress p(GlobalPars.NREP, true);\n\n    #pragma omp parallel for schedule(static)\n    for (int task = 0; task < GlobalPars.NREP; ++task){\n        while(RunSimulation(GlobalPars, SimulationData)==false);\n        //if(progressbar == true) p.increment();\n    }\n\n    return Rcpp_WriteOutput(GlobalPars, SimulationData);\n}\n", "meta": {"hexsha": "793702330ffcb2bef4d374fbacbd2180406f8b68", "size": 6500, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pkgIntrogression/src/Rcpp_output.cpp", "max_stars_repo_name": "freekdh/Introgression", "max_stars_repo_head_hexsha": "f26c7b84efee64ec5bb4e662753e052195b7fc71", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pkgIntrogression/src/Rcpp_output.cpp", "max_issues_repo_name": "freekdh/Introgression", "max_issues_repo_head_hexsha": "f26c7b84efee64ec5bb4e662753e052195b7fc71", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-08-01T23:29:56.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-20T23:35:56.000Z", "max_forks_repo_path": "pkgIntrogression/src/Rcpp_output.cpp", "max_forks_repo_name": "freekdh/Introgression", "max_forks_repo_head_hexsha": "f26c7b84efee64ec5bb4e662753e052195b7fc71", "max_forks_repo_licenses": ["Apache-2.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.8773006135, "max_line_length": 122, "alphanum_fraction": 0.6481538462, "num_tokens": 1872, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.45505423392341127}}
{"text": "#include \"NUM.hpp\"\n#include \"MAT.hpp\"\n#include \"VEC.hpp\"\n#include <cmath>\n#include \"POINTERARM.hpp\"\n#include \"FILEHANDLER.hpp\"\n#include <boost\\algorithm\\string\\trim.hpp>\n#include <boost\\algorithm\\string\\split.hpp>\n\nCMD POINTERARM::InterpretLine(std::string &line) {\n  std::vector<std::string> splitVec;\n  CMD command;\n  boost::split(splitVec, line, boost::is_any_of(\"();\"), boost::token_compress_on);\n  if (splitVec[0] == \"MOVE\") {\n    command.command = MOVE;\n    command.coords = VEC(strtod(splitVec[1].c_str(), nullptr), strtod(splitVec[2].c_str(), nullptr), strtod(splitVec[3].c_str(), nullptr));\n  }\n  else\n    if (splitVec[0] == \"LASER\") {\n      command.command = LASER;\n      command.val = splitVec[1] == \"1\" ? 1 : 0;\n    }\n  else\n    if (splitVec[0] == \"WAIT\") {\n      command.command = WAIT;\n      command.value = strtol(splitVec[1].c_str(), nullptr, 10);\n    }\n  return command;\n}\n\nstd::string POINTERARM::CommandToBuffer(CMD &cmd) {\n  std::string buffer;\n  CMD command;\n  switch (cmd.command) {\n    case MOVE:\n      buffer = ConvertCoordinatesToAngles(cmd.coords).a.ToString() + \";\" + ConvertCoordinatesToAngles(cmd.coords).b.ToString();\n      break;\n    case LASER:\n      buffer = cmd.val ? \"ON\" : \"NO\";\n      break;\n    case WAIT:\n      buffer = \"P\";\n      buffer.append(std::to_string(command.value));\n  }\n  return buffer;\n}\n\nCMD_DEQUE POINTERARM::GenerateCommandDeque(std::vector<std::string> &lines) {\n  CMD_DEQUE deque;\n  for (int i = 0; i < lines.size(); ++i) {\n    deque.push_back(InterpretLine(lines[i]));\n  }\n  return deque;\n}\n\nVEC POINTERARM::ConvertCoordinatesToAngles(VEC &coords) {\n  VEC angles(\n    coords.a != 0.0 ? atan(coords.a / coords.c) * 180 / M_PI : 0.0,\n    coords.b != 0.0 ? atan(coords.b / coords.c) * 180 / M_PI : 0.0,\n    0\n  );\n  return angles;\n}", "meta": {"hexsha": "bf65649d1f0e2d1c3a743a7fb8e6aa98acb1a054", "size": 1785, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "RoboMan/POINTERARM.cpp", "max_stars_repo_name": "paullohs/RoboMan", "max_stars_repo_head_hexsha": "28014822766a558fa94127120142d081742c507a", "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": "RoboMan/POINTERARM.cpp", "max_issues_repo_name": "paullohs/RoboMan", "max_issues_repo_head_hexsha": "28014822766a558fa94127120142d081742c507a", "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": "RoboMan/POINTERARM.cpp", "max_forks_repo_name": "paullohs/RoboMan", "max_forks_repo_head_hexsha": "28014822766a558fa94127120142d081742c507a", "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.3333333333, "max_line_length": 139, "alphanum_fraction": 0.637535014, "num_tokens": 524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.45505423392341127}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2013   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2013   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#include <nt2/trigonometric/include/functions/sincpi.hpp>\n\n#include <nt2/sdk/functor/meta/call.hpp>\n#include <nt2/sdk/unit/module.hpp>\n#include <nt2/sdk/unit/tests/relation.hpp>\n#include <nt2/sdk/unit/tests/type_expr.hpp>\n#include <nt2/sdk/unit/tests/ulp.hpp>\n#include <nt2/sdk/unit/module.hpp>\n#include <boost/simd/sdk/config.hpp>\n\n#include <nt2/include/constants/eps.hpp>\n#include <nt2/include/constants/mindenormal.hpp>\n#include <nt2/include/constants/one.hpp>\n#include <nt2/include/constants/pi.hpp>\n#include <nt2/include/constants/zero.hpp>\n#include <nt2/include/constants/inf.hpp>\n#include <nt2/include/constants/minf.hpp>\n#include <nt2/include/constants/nan.hpp>\n\nNT2_TEST_CASE_TPL ( sincpi_real,  NT2_REAL_TYPES)\n{\n  using nt2::sincpi;\n  using nt2::tag::sincpi_;\n\n  NT2_TEST_TYPE_IS(typename nt2::meta::call<sincpi_(T)>::type,T);\n  typedef T wished_r_t;\n\n  // return type conformity test\n  NT2_TEST_TYPE_IS(T, wished_r_t);\n\n  // specific values tests\n#ifndef BOOST_SIMD_NO_INVALIDS\n  NT2_TEST_ULP_EQUAL(sincpi(nt2::Inf<T>()), nt2::Zero<T>(), 1.0);\n  NT2_TEST_ULP_EQUAL(sincpi(nt2::Minf<T>()), nt2::Zero<T>(), 1.0);\n  NT2_TEST_ULP_EQUAL(sincpi(nt2::Nan<T>()), nt2::Nan<T>(), 1.0);\n#endif\n  NT2_TEST_ULP_EQUAL(sincpi(-T(1)/T(2)), T(2)/(nt2::Pi<T>()), 1.0);\n  NT2_TEST_ULP_EQUAL(sincpi(-T(1)/T(4)), nt2::sinpi(T(1)/T(4))*T(4)/(nt2::Pi<T>()), 1.0);\n  NT2_TEST_ULP_EQUAL(sincpi(T(1)/T(2)),  T(2)/(nt2::Pi<T>()), 1.0);\n  NT2_TEST_ULP_EQUAL(sincpi(T(1)/T(4)), nt2::sinpi(T(1)/T(4))*T(4)/(nt2::Pi<T>()), 1.0);\n  NT2_TEST_ULP_EQUAL(sincpi(nt2::Eps<T>()), nt2::One<T>(), 1.0);\n  NT2_TEST_ULP_EQUAL(sincpi(nt2::Mindenormal<T>()), nt2::One<T>(), 1.0);\n  NT2_TEST_ULP_EQUAL(sincpi(nt2::Zero<T>()), nt2::One<T>(), 1.0);\n}\n", "meta": {"hexsha": "c6670cbdf3f94d12e5ea4d3a529bb8997e039744", "size": 2224, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/core/trigonometric/unit/scalar/sincpi.cpp", "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/unit/scalar/sincpi.cpp", "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/unit/scalar/sincpi.cpp", "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": 41.9622641509, "max_line_length": 89, "alphanum_fraction": 0.628147482, "num_tokens": 712, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593312018545, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.4550542339234112}}
{"text": "/**\n * \\file ChamberlinFilter.cpp\n */\n\n#include \"ChamberlinFilter.h\"\n\n#include <boost/math/constants/constants.hpp>\n\nnamespace ATK\n{\n  template<typename DataType>\n  ChamberlinFilter<DataType>::ChamberlinFilter()\n  :TypedBaseFilter<DataType>(1, 1)\n  {\n  }\n  \n  template<typename DataType_>\n  void ChamberlinFilter<DataType_>::set_cut_frequency(CoeffDataType cutoff_frequency)\n  {\n    this->cutoff_frequency = cutoff_frequency;\n    setup();\n  }\n\n  template<typename DataType_>\n  typename ChamberlinFilter<DataType_>::CoeffDataType ChamberlinFilter<DataType_>::get_cut_frequency() const\n  {\n    return cutoff_frequency;\n  }\n  \n  template<typename DataType_>\n  void ChamberlinFilter<DataType_>::set_attenuation(CoeffDataType attenuation)\n  {\n    this->attenuation = attenuation;\n    setup();\n  }\n\n  template<typename DataType_>\n  typename ChamberlinFilter<DataType_>::CoeffDataType ChamberlinFilter<DataType_>::get_attenuation() const\n  {\n    return attenuation;\n  }\n  \n  template<typename DataType>\n  void ChamberlinFilter<DataType>::select(int selection)\n  {\n    this->selected = selection;\n  }\n  \n  template<typename DataType>\n  int ChamberlinFilter<DataType>::get_selected() const\n  {\n    return selected;\n  }\n  \n  template<typename DataType>\n  void ChamberlinFilter<DataType>::setup()\n  {\n    numerical_frequency = 2 * std::sin(boost::math::constants::pi<DataType>() * cutoff_frequency / input_sampling_rate);\n    numerical_attenuation = 2 * attenuation;\n  }\n\n  template<typename DataType>\n  void ChamberlinFilter<DataType>::process_impl(gsl::index size) const\n  {\n    const DataType* ATK_RESTRICT input = converted_inputs[0];\n    DataType* ATK_RESTRICT output = outputs[0];\n    for(gsl::index i = 0; i < size; ++i)\n    {\n      yh = input[i] - yl - numerical_attenuation * yb;\n      yb = numerical_frequency * yh + yb;\n      yl = numerical_frequency * yb + yl;\n      if(selected == 0)\n      {\n        output[i] = yl;\n      }\n      else if(selected == 1)\n      {\n        output[i] = yb;\n      }\n      else\n      {\n        output[i] = yh;\n      }\n    }\n  }\n  \n#if ATK_ENABLE_INSTANTIATION\n  template class ChamberlinFilter<float>;\n#endif\n  template class ChamberlinFilter<double>;\n}\n", "meta": {"hexsha": "c71827e9fa9c3683db533f26bf2f0265cc30c4d1", "size": 2182, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ATK/EQ/ChamberlinFilter.cpp", "max_stars_repo_name": "AudioTK/AudioTK", "max_stars_repo_head_hexsha": "dba42eea68534501efe74692b74edf4792cca231", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2021-02-04T10:47:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T03:45:00.000Z", "max_issues_repo_path": "ATK/EQ/ChamberlinFilter.cpp", "max_issues_repo_name": "AudioTK/AudioTK", "max_issues_repo_head_hexsha": "dba42eea68534501efe74692b74edf4792cca231", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-02-01T15:45:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-13T19:39:05.000Z", "max_forks_repo_path": "ATK/EQ/ChamberlinFilter.cpp", "max_forks_repo_name": "AudioTK/AudioTK", "max_forks_repo_head_hexsha": "dba42eea68534501efe74692b74edf4792cca231", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-04-12T03:28:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-17T00:47:11.000Z", "avg_line_length": 23.7173913043, "max_line_length": 120, "alphanum_fraction": 0.6856095325, "num_tokens": 541, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585669110202, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4550542266288199}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include \"chomp.hpp\"\n\nint main()\n{\n  Eigen::VectorXd qs(2); //Start goal  coordinates (x,y)\n  Eigen::VectorXd qe(2); //End goal  coordinates (x,y)\n  Eigen::VectorXd xi; //Trajectory points (x0,y0,x1,y1,....)\n  Eigen::MatrixXd obs; //obstacles |x0,y0,R0|\n                      //           |x1,y1,R1|\n                      //           | .......|\n  qs<<0,0;\n  qe<<3,5;\n\n  chomp::generatePath(qs,qe,xi,obs);\n  std::cout<<xi<<std::endl;\n}\n", "meta": {"hexsha": "d11313673a9a9af0fc5a77616c7d5413d3d1b770", "size": 479, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "demo/minimal_program.cpp", "max_stars_repo_name": "j3sq/ROS-CHOMP", "max_stars_repo_head_hexsha": "60731f3c7b8d489e2a3ffa38e526dbfc7ba292c3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-08-27T16:00:51.000Z", "max_stars_repo_stars_event_max_datetime": "2015-08-27T16:00:51.000Z", "max_issues_repo_path": "demo/minimal_program.cpp", "max_issues_repo_name": "j3sq/ROS-CHOMP", "max_issues_repo_head_hexsha": "60731f3c7b8d489e2a3ffa38e526dbfc7ba292c3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "demo/minimal_program.cpp", "max_forks_repo_name": "j3sq/ROS-CHOMP", "max_forks_repo_head_hexsha": "60731f3c7b8d489e2a3ffa38e526dbfc7ba292c3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-12-10T02:44:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-14T02:06:44.000Z", "avg_line_length": 25.2105263158, "max_line_length": 60, "alphanum_fraction": 0.5302713987, "num_tokens": 154, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7879312056025699, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.45502661932075306}}
{"text": "#include <ros/ros.h>\n#include <std_msgs/String.h>\n#include <model_based_shared_control/State.h>\n#include <model_based_shared_control/Control.h>\n#include \"robotlib/dynamicalSystems/koopman/koopman_operator.hpp\"\n#include \"robotlib/dynamicalSystems/koopman/basis_functions/linear_basis.hpp\"\n#include \"robotlib/dynamicalSystems/koopman/basis_functions/nonlinear_basis.hpp\"\n#include \"robotlib/dSAClib/SAC.hpp\"\n#include \"robotlib/dSAClib/objective.hpp\"\n#include \"robotlib/lqr_controller.hpp\"\n#include <armadillo>\n\nclass HumanRobot {\n\npublic:\n\n  // publishers and subscribers\n  ros::Subscriber state_sub;\n  ros::Subscriber shutdown_sub;\n  ros::Publisher sac_control_pub;\n  ros::Publisher lqr_control_pub;\n  bool has_initialized = false;\n\n  // messages\n  model_based_shared_control::State state;\n  model_based_shared_control::Control sacControl;\n  model_based_shared_control::Control lqrControl;\n\n  // data vectors\n  arma::vec current_state;\n  arma::vec dataIn;\n  arma::vec dataOut;\n  arma::vec cdataInSac, cdataInLqr;\n  arma::vec hdataIn;\n  arma::vec hdataOut;\n\n  // Koopman models\n  KoopmanOperator* linear_koopman_operator;\n  KoopmanOperator* nonlinear_koopman_operator;\n\n  // Controllers\n  deiSAC* sacController;\n  LQRController* lqrController;\n\n  HumanRobot(ros::Rate* loop_rate) {\n\n    ros::NodeHandle nh;\n\n    // set up publishers and subscribers\n    sac_control_pub = nh.advertise<model_based_shared_control::Control>(\"/sac_control\", 1);\n    lqr_control_pub = nh.advertise<model_based_shared_control::Control>(\"/lqr_control\", 1);\n    state_sub = nh.subscribe(\"/state\", 1, &HumanRobot::get_state, this);\n    shutdown_sub = nh.subscribe(\"/shutdown\", 1, &HumanRobot::get_shutdown, this);\n\n    // set up data vectors\n    dataIn = arma::zeros<arma::vec>(6);\n    dataOut = arma::zeros<arma::vec>(6);\n    cdataInSac = arma::zeros<arma::vec>(2);\n    cdataInLqr = arma::zeros<arma::vec>(2);\n    hdataIn = arma::zeros<arma::vec>(2);\n    hdataOut = arma::zeros<arma::vec>(2);\n    current_state = arma::zeros<arma::vec>(6);\n\n    // load user and experimental system parameters\n    std::string filePath;\n    std::string baseDir;\n    int userIdInt;\n    std::string userId;\n    nh.getParam(\"/data_path\", baseDir);\n    nh.getParam(\"/user_id\", userIdInt);\n\n    if (userIdInt < 10) {\n      userId = \"0\" + std::to_string(userIdInt);\n    } else {\n      userId = std::to_string(userIdInt);\n    }\n\n    // set up Linear Koopman\n    std::string linearFilePath = baseDir + \"models/\" + userId + \"-koopman-linear.bin\";\n    linear_koopman_operator = new KoopmanOperator(new LinearBasisFunction());\n    std::cout << linearFilePath << std::endl;\n    linear_koopman_operator->loadOperator(linearFilePath);\n\n    // set up Non Linear Koopman\n    std::string nonlinearFilePath = baseDir + \"models/\" + userId + \"-koopman-nonlinear.bin\";\n    nonlinear_koopman_operator = new KoopmanOperator(new NonLinearBasisFunction());\n    std::cout << nonlinearFilePath << std::endl;\n    nonlinear_koopman_operator->loadOperator(nonlinearFilePath);\n\n    // set up SAC controller\n    arma::vec Qdiag = arma::zeros<arma::vec>(nonlinear_koopman_operator->_nX);\n    Qdiag[0] = 6.0;\n    Qdiag[1] = 10.0;\n    Qdiag[2] = 20.0;\n    Qdiag[3] = 2.0;\n    Qdiag[4] = 2.0;\n    Qdiag[5] = 3.0;\n    arma::mat Q = arma::diagmat(Qdiag);\n\n    arma::vec Qfdiag = arma::zeros<arma::vec>(nonlinear_koopman_operator->_nX);\n    Qfdiag[0] = 3.0;\n    Qfdiag[1] = 3.0;\n    Qfdiag[2] = 5.0;\n    Qfdiag[3] = 1.0;\n    Qfdiag[4] = 1.0;\n    Qfdiag[5] = 1.0;\n    arma::mat Qf = arma::diagmat(Qfdiag);\n\n    arma::vec Rdiag = arma::zeros<arma::vec>(nonlinear_koopman_operator->_nU);\n    Rdiag[0] = 1.0;\n    Rdiag[1] = 1.0;\n    arma::mat R = arma::diagmat(Rdiag);\n\n    arma::vec umax = arma::ones<arma::vec>(nonlinear_koopman_operator->_nU);\n    arma::vec unomSac = arma::zeros<arma::vec>(nonlinear_koopman_operator->_nU);\n    arma::vec desired_state = arma::zeros<arma::vec>(nonlinear_koopman_operator->_nX);\n\n    sacController = new deiSAC(nonlinear_koopman_operator, new Objective(Q, R, Qf, desired_state, new NonLinearBasisFunction()),\n                10, umax, unomSac );\n\n    // set up LQR controller\n    arma::vec Qlqrdiag = arma::zeros<arma::vec>(linear_koopman_operator->_nX);\n    Qlqrdiag[0] = 1.0;\n    Qlqrdiag[1] = 1.0;\n    Qlqrdiag[2] = 1.0;\n    Qlqrdiag[3] = 1.0;\n    Qlqrdiag[4] = 1.0;\n    Qlqrdiag[5] = 2.0;\n    arma::mat Qlqr = arma::diagmat(Qlqrdiag);\n\n    arma::vec Rlqrdiag = arma::zeros<arma::vec>(linear_koopman_operator->_nU);\n    Rlqrdiag[0] = 1.0;\n    Rlqrdiag[1] = 1.0;\n    arma::mat Rlqr = arma::diagmat(Rlqrdiag);\n\n    arma::vec unomLqr = arma::zeros<arma::vec>(linear_koopman_operator->_nU);\n\n    arma::mat A, B;\n    A = linear_koopman_operator->fdx(desired_state, unomLqr);\n    B = linear_koopman_operator->fdu(desired_state, unomLqr);\n\n    lqrController = new LQRController(A, B, Qlqr, Rlqr);\n\n  }\n\n  void compute_sac_control() {\n    if (has_initialized == true) {\n      cdataInSac = sacController->get_control(nonlinear_koopman_operator->basis->fkx(current_state));\n      sacControl.u_1 = cdataInSac[0];\n      sacControl.u_2 = cdataInSac[1];\n      sac_control_pub.publish(sacControl);\n    }\n  }\n\n  void compute_lqr_control() {\n    if (has_initialized == true) {\n      cdataInLqr = lqrController->get_control(linear_koopman_operator->basis->fkx(current_state));\n      lqrControl.u_1 = cdataInLqr[0];\n      lqrControl.u_2 = cdataInLqr[1];\n      lqr_control_pub.publish(lqrControl);\n    }\n  }\n\n  void get_state(const model_based_shared_control::State::ConstPtr& msg) {\n    if (has_initialized == false) {\n      dataOut[0] = msg->x;\n      dataOut[1] = msg->y;\n      dataOut[2] = msg->theta;\n      dataOut[3] = msg->x_dot;\n      dataOut[4] = msg->y_dot;\n      dataOut[5] = msg->theta_dot;\n      hdataOut[0] = msg->u_1;\n      hdataOut[1] = msg->u_2;\n      has_initialized = true;\n    } else {\n      if (std::abs(dataOut[0] - msg->x) + std::abs(dataOut[1] - msg->y) < 0.3){\n        dataIn = dataOut;\n        hdataIn = hdataOut;\n        dataOut[0] = msg->x;\n        dataOut[1] = msg->y;\n        dataOut[2] = msg->theta;\n        dataOut[3] = msg->x_dot;\n        dataOut[4] = msg->y_dot;\n        dataOut[5] = msg->theta_dot;\n        hdataOut[0] = msg->u_1;\n        hdataOut[1] = msg->u_2;\n        current_state = dataOut;\n      } else {\n        has_initialized = false;\n      }\n    }\n  }\n\n  void get_shutdown(const std_msgs::String::ConstPtr& msg) {\n    std::string filePath = msg->data;\n  }\n\n};\n\nint main(int argc, char** argv) {\n  ros::init(argc, argv,\"human_robot\");\n  ros::NodeHandle nh;\n  ros::Rate loop_rate(10);\n  HumanRobot sys(&loop_rate);\n\n  while (ros::ok()) {\n    loop_rate.sleep();\n    ros::spinOnce();\n    sys.compute_sac_control();\n    sys.compute_lqr_control();\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "6f5d0d58f73057a00574dc1c678e7be5d40fc165", "size": 6735, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/model_based_shared_control/src/model_based_shared_control.cpp", "max_stars_repo_name": "argallab/model_based_shared_control", "max_stars_repo_head_hexsha": "ff42226b6345266f35a32021c7d0b44cc5948ec1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-05-08T19:47:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T06:43:31.000Z", "max_issues_repo_path": "src/model_based_shared_control/src/model_based_shared_control.cpp", "max_issues_repo_name": "argallab/model_based_shared_control", "max_issues_repo_head_hexsha": "ff42226b6345266f35a32021c7d0b44cc5948ec1", "max_issues_repo_licenses": ["MIT"], "max_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_based_shared_control/src/model_based_shared_control.cpp", "max_forks_repo_name": "argallab/model_based_shared_control", "max_forks_repo_head_hexsha": "ff42226b6345266f35a32021c7d0b44cc5948ec1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-05-08T19:47:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-07T10:10:17.000Z", "avg_line_length": 31.3255813953, "max_line_length": 128, "alphanum_fraction": 0.6623608018, "num_tokens": 2148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879312056025699, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.455026619320753}}
{"text": "\n#include <iostream>\n#include <Eigen/Core>\n#include <bench/BenchTimer.h>\nusing namespace Eigen;\n\n#ifndef SIZE\n#define SIZE 50\n#endif\n\n#ifndef REPEAT\n#define REPEAT 10000\n#endif\n\ntypedef float Scalar;\n\n__attribute__ ((noinline)) void benchVec(Scalar* a, Scalar* b, Scalar* c, int size);\n__attribute__ ((noinline)) void benchVec(MatrixXf& a, MatrixXf& b, MatrixXf& c);\n__attribute__ ((noinline)) void benchVec(VectorXf& a, VectorXf& b, VectorXf& c);\n\nint main(int argc, char* argv[])\n{\n    int size = SIZE * 8;\n    int size2 = size * size;\n    Scalar* a = internal::aligned_new<Scalar>(size2);\n    Scalar* b = internal::aligned_new<Scalar>(size2+4)+1;\n    Scalar* c = internal::aligned_new<Scalar>(size2);\n\n    for (int i=0; i<size; ++i)\n    {\n        a[i] = b[i] = c[i] = 0;\n    }\n\n    BenchTimer timer;\n\n    timer.reset();\n    for (int k=0; k<10; ++k)\n    {\n        timer.start();\n        benchVec(a, b, c, size2);\n        timer.stop();\n    }\n    std::cout << timer.value() << \"s  \" << (double(size2*REPEAT)/timer.value())/(1024.*1024.*1024.) << \" GFlops\\n\";\n    return 0;\n    for (int innersize = size; innersize>2 ; --innersize)\n    {\n        if (size2%innersize==0)\n        {\n            int outersize = size2/innersize;\n            MatrixXf ma = Map<MatrixXf>(a, innersize, outersize );\n            MatrixXf mb = Map<MatrixXf>(b, innersize, outersize );\n            MatrixXf mc = Map<MatrixXf>(c, innersize, outersize );\n            timer.reset();\n            for (int k=0; k<3; ++k)\n            {\n                timer.start();\n                benchVec(ma, mb, mc);\n                timer.stop();\n            }\n            std::cout << innersize << \" x \" << outersize << \"  \" << timer.value() << \"s   \" << (double(size2*REPEAT)/timer.value())/(1024.*1024.*1024.) << \" GFlops\\n\";\n        }\n    }\n\n    VectorXf va = Map<VectorXf>(a, size2);\n    VectorXf vb = Map<VectorXf>(b, size2);\n    VectorXf vc = Map<VectorXf>(c, size2);\n    timer.reset();\n    for (int k=0; k<3; ++k)\n    {\n        timer.start();\n        benchVec(va, vb, vc);\n        timer.stop();\n    }\n    std::cout << timer.value() << \"s   \" << (double(size2*REPEAT)/timer.value())/(1024.*1024.*1024.) << \" GFlops\\n\";\n\n    return 0;\n}\n\nvoid benchVec(MatrixXf& a, MatrixXf& b, MatrixXf& c)\n{\n    for (int k=0; k<REPEAT; ++k)\n        a = a + b;\n}\n\nvoid benchVec(VectorXf& a, VectorXf& b, VectorXf& c)\n{\n    for (int k=0; k<REPEAT; ++k)\n        a = a + b;\n}\n\nvoid benchVec(Scalar* a, Scalar* b, Scalar* c, int size)\n{\n    typedef internal::packet_traits<Scalar>::type PacketScalar;\n    const int PacketSize = internal::packet_traits<Scalar>::size;\n    PacketScalar a0, a1, a2, a3, b0, b1, b2, b3;\n    for (int k=0; k<REPEAT; ++k)\n        for (int i=0; i<size; i+=PacketSize*8)\n        {\n//             a0 = internal::pload(&a[i]);\n//             b0 = internal::pload(&b[i]);\n//             a1 = internal::pload(&a[i+1*PacketSize]);\n//             b1 = internal::pload(&b[i+1*PacketSize]);\n//             a2 = internal::pload(&a[i+2*PacketSize]);\n//             b2 = internal::pload(&b[i+2*PacketSize]);\n//             a3 = internal::pload(&a[i+3*PacketSize]);\n//             b3 = internal::pload(&b[i+3*PacketSize]);\n//             internal::pstore(&a[i], internal::padd(a0, b0));\n//             a0 = internal::pload(&a[i+4*PacketSize]);\n//             b0 = internal::pload(&b[i+4*PacketSize]);\n//\n//             internal::pstore(&a[i+1*PacketSize], internal::padd(a1, b1));\n//             a1 = internal::pload(&a[i+5*PacketSize]);\n//             b1 = internal::pload(&b[i+5*PacketSize]);\n//\n//             internal::pstore(&a[i+2*PacketSize], internal::padd(a2, b2));\n//             a2 = internal::pload(&a[i+6*PacketSize]);\n//             b2 = internal::pload(&b[i+6*PacketSize]);\n//\n//             internal::pstore(&a[i+3*PacketSize], internal::padd(a3, b3));\n//             a3 = internal::pload(&a[i+7*PacketSize]);\n//             b3 = internal::pload(&b[i+7*PacketSize]);\n//\n//             internal::pstore(&a[i+4*PacketSize], internal::padd(a0, b0));\n//             internal::pstore(&a[i+5*PacketSize], internal::padd(a1, b1));\n//             internal::pstore(&a[i+6*PacketSize], internal::padd(a2, b2));\n//             internal::pstore(&a[i+7*PacketSize], internal::padd(a3, b3));\n\n            internal::pstore(&a[i+2*PacketSize], internal::padd(internal::ploadu(&a[i+2*PacketSize]), internal::ploadu(&b[i+2*PacketSize])));\n            internal::pstore(&a[i+3*PacketSize], internal::padd(internal::ploadu(&a[i+3*PacketSize]), internal::ploadu(&b[i+3*PacketSize])));\n            internal::pstore(&a[i+4*PacketSize], internal::padd(internal::ploadu(&a[i+4*PacketSize]), internal::ploadu(&b[i+4*PacketSize])));\n            internal::pstore(&a[i+5*PacketSize], internal::padd(internal::ploadu(&a[i+5*PacketSize]), internal::ploadu(&b[i+5*PacketSize])));\n            internal::pstore(&a[i+6*PacketSize], internal::padd(internal::ploadu(&a[i+6*PacketSize]), internal::ploadu(&b[i+6*PacketSize])));\n            internal::pstore(&a[i+7*PacketSize], internal::padd(internal::ploadu(&a[i+7*PacketSize]), internal::ploadu(&b[i+7*PacketSize])));\n        }\n}", "meta": {"hexsha": "c84ae1c7a9ef63308d37396a7ef01e5dc95d98a8", "size": 5111, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Plugins/SciberQuestToolKit/eigen-3.0.3/eigen-eigen-3.0.3/bench/benchVecAdd.cpp", "max_stars_repo_name": "mathstuf/ParaView", "max_stars_repo_head_hexsha": "e867e280545ada10c4ed137f6a966d9d2f3db4cb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-04-22T09:09:18.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-22T09:09:18.000Z", "max_issues_repo_path": "Plugins/SciberQuestToolKit/eigen-3.0.3/eigen-eigen-3.0.3/bench/benchVecAdd.cpp", "max_issues_repo_name": "mathstuf/ParaView", "max_issues_repo_head_hexsha": "e867e280545ada10c4ed137f6a966d9d2f3db4cb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Plugins/SciberQuestToolKit/eigen-3.0.3/eigen-eigen-3.0.3/bench/benchVecAdd.cpp", "max_forks_repo_name": "mathstuf/ParaView", "max_forks_repo_head_hexsha": "e867e280545ada10c4ed137f6a966d9d2f3db4cb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2016-04-14T13:42:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-22T04:59:42.000Z", "avg_line_length": 37.8592592593, "max_line_length": 167, "alphanum_fraction": 0.5566425357, "num_tokens": 1645, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4550266135690868}}
{"text": "//cleantif16.cpp\n/*\n\n(C) 2004-2005 olegabr. All rights reserved.\n*/\n\n#include <Magick++.h>\n#include <limits>\n#include <iostream>\nusing std::cout; using std::endl;\n\n#include <cmath>\n#include <vector>\n\n#include <boost/filesystem/operations.hpp>\n\n#include \"img_generator.h\"\n#include <min_finder1d.h>\n\nnamespace {\n\tvoid usage()\n\t{\n\t\tstd::cout << \"cleantif16 zero_image offset_image gain_image images_directory\\n\";\n\t}\n\tMagick::Quantum cut_negative(double d)\n\t{\n\t\treturn static_cast<Magick::Quantum>(d>0?d:0);\n\t}\n}\n\nstruct pxlpckt_less\n{\n\tbool operator ()(const Magick::PixelPacket& io, const Magick::PixelPacket& g)\n\t{\n\t\treturn io.red < g.red;\n\t}\n};\n\ndouble ftnorm2(img_generator&, double /*0..0,5*/);\n\nclass img_norm_calculator\n{\npublic :\n\ttypedef koefficient_type value_type;\n\timg_norm_calculator\n\t(\n\t\tPPConstIterator opxl,\n\t\tPPConstIterator gpxl,\n\t\tPPConstIterator zpxl,\n\t\tPPIterator ipxl,\n\t\tstd::size_t width, std::size_t height,\n\t\tdouble gain_max\n\t)\n\t\t: opxl_(opxl), gpxl_(gpxl), zpxl_(zpxl), ipxl_(ipxl), width_(width), height_(height), gain_max_(gain_max) {}\n\tvalue_type operator ()(koefficient_type k) const\n\t{\n\t\timg_generator ig(opxl_, gpxl_, zpxl_, ipxl_, width_, height_, gain_max_, k);\n\t\treturn ftnorm2(ig, 0.01);\n\t}\nprivate :\n\tPPConstIterator opxl_, gpxl_, zpxl_;\n\tPPIterator ipxl_;\n\tstd::size_t width_, height_;\n\tconst double gain_max_;\n};\n\nint main(int argc, char* argv[])\n{\n\tif (argc < 5)\n\t{\n\t\tusage();\n\t\treturn 0;\n\t}\n\ttry {\n\t\tMagick::InitializeMagick(argv[0]);\n\t\tMagick::Image zero_, offset_, gain_;\n\t\tzero_.read(argv[1]);\n\t\toffset_.read(argv[2]);\n\t\tgain_.read(argv[3]);\n\n\t\tMagick::Image const &zero(zero_), &offset(offset_), &gain(gain_);\n\t\tif\n\t\t(\n\t\t\tgain.columns() != offset.columns() ||\n\t\t\tgain.rows() != offset.rows() ||\n\t\t\tzero.columns() != offset.columns() ||\n\t\t\tzero.rows() != offset.rows()\n\t\t)\n\t\t\tthrow std::runtime_error(\"The gain and offset or zero_image's geometries are different.\");\n\n\t\tPPConstIterator const\n\t\t\tzpxl = zero_.getPixels(0, 0, zero.columns(), zero.rows()),\n\t\t\tgpxl = gain_.getPixels(0, 0, gain.columns(), gain.rows()),\n\t\t\topxl = offset_.getPixels(0, 0, offset.columns(), offset.rows());\n\n\t\tconst std::size_t N(offset.columns()*offset.rows());\n\t\tdouble gain_max = std::max_element(gpxl, gpxl+N, pxlpckt_less())->red;\n\n\t\tMagick::Image img;\n\t\tnamespace fs = boost::filesystem;\n\t\tstd::string dir_name(argv[4]);\n\t\tfs::path dir_path(dir_name, fs::native);\n\t\tif (!exists( dir_path ))\n\t\t\tthrow std::runtime_error(std::string(\"The directory '\") + dir_name + \"' does't exists.\");\n\n\t\tfs::path result_path(dir_path/fs::path(\"result\"));\n\t\tif (!fs::exists(result_path)) fs::create_directory(result_path);\n\n\t\tconst Magick::Quantum QM(std::numeric_limits<Magick::Quantum>::max() - 1);\n\n\t\t//image_optimizer imopt(20, 20, 0.01);\n\t\tmin_finder1d<koefficient_type, image_norm_type, img_norm_calculator> imopt(-20, 20, 20, 0.01);\n\t\tfs::directory_iterator itr(dir_path), end_itr;\n\t\tfor (; itr != end_itr; ++itr)\n\t\t\tif ( !is_directory( *itr ) )\n\t\t\t{\n\t\t\t\tcout << \"open image file named: \" << complete(*itr).native_file_string().c_str() << endl;\n\t\t\t\timg.read(complete(*itr).native_file_string().c_str());\n\n\t\t\t\tif (img.columns() != offset.columns() || img.rows() != offset.rows())\n\t\t\t\t\tthrow std::runtime_error(\"The image and offset geometries are different.\");\n\n\t\t\t\tPPIterator pxl = img.getPixels(0, 0, img.columns(), img.rows());\n\t\t\t\tdouble img_max = std::max_element(pxl, pxl+N, pxlpckt_less())->red;\n\n\t\t\t\t{ /* do image cleaning */\n\t\t\t\t\timg_norm_calculator inc(opxl, gpxl, zpxl, pxl, img.columns(), img.rows(), gain_max);\n\t\t\t\t\tdouble k(imopt(inc).second);\n\t\t\t\t\tPPIterator i(pxl), iend(pxl+N);\n\t\t\t\t\tPPConstIterator o(opxl), z(zpxl), g(gpxl);\n\t\t\t\t\tfor (; i != iend; ++i, ++o, ++g, ++z)\n\t\t\t\t\t{\n\t\t\t\t\t\ti->red = i->green = i->blue =\n\t\t\t\t\t\t\tcut_negative(calc_img_value(i->red, z->red, k, o->red, gain_max, g->red)*(QM/img_max));\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\timg.syncPixels();\n\t\t\t\timg.type(Magick::GrayscaleType);\n\t\t\t\timg.write(complete(result_path/fs::path(std::string(\"clean_\")+itr->leaf())).native_file_string().c_str());\n\t\t\t}\n\t}\n\tcatch (Magick::Exception &ex) {\n\t\tcout << ex.what() << endl;\n\t}\n\tcatch (std::exception &e) {\n\t\tcout << e.what() << endl;\n\t}\n\tcatch (...) {\n\t\tcout << \"Unknown exception occured.\" << endl;\n\t}\n\n\treturn 0;\n}\n", "meta": {"hexsha": "cda2f49bea5be66ebd70b444ecce33a8cee75486", "size": 4233, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cleantif16/cleantif16.cpp", "max_stars_repo_name": "olegabr/tomo3d", "max_stars_repo_head_hexsha": "36ffca69aba8556170ec7330271eb58ebaf7459b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2016-01-07T12:27:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-03T06:58:42.000Z", "max_issues_repo_path": "cleantif16/cleantif16.cpp", "max_issues_repo_name": "olegabr/tomo3d", "max_issues_repo_head_hexsha": "36ffca69aba8556170ec7330271eb58ebaf7459b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cleantif16/cleantif16.cpp", "max_forks_repo_name": "olegabr/tomo3d", "max_forks_repo_head_hexsha": "36ffca69aba8556170ec7330271eb58ebaf7459b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-10T10:22:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-10T10:22:13.000Z", "avg_line_length": 27.3096774194, "max_line_length": 110, "alphanum_fraction": 0.6609969289, "num_tokens": 1300, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4550266135690868}}
{"text": "/*\n * StokesM2L.cpp\n *\n *  Created on: Oct 12, 2016\n *      Author: wyan\n */\n\n#include \"SVD_pvfmm.hpp\"\n\n#include <Eigen/Dense>\n\n#include <iomanip>\n#include <iostream>\n\n#define DIRECTLAYER 2\n\nnamespace StokesPVel2D3D {\n\nusing EVec3 = Eigen::Vector3d;\nusing EVec4 = Eigen::Vector4d;\nusing EMat3 = Eigen::Matrix3d;\nusing EMat4 = Eigen::Matrix4d;\nconstexpr double eps = 1e-10;\n\n/**\n * \\brief Returns the coordinates of points on the surface of a cube.\n * \\param[in] p Number of points on an edge of the cube is (n+1)\n * \\param[in] c Coordinates to the centre of the cube (3D array).\n * \\param[in] alpha Scaling factor for the size of the cube.\n * \\param[in] depth Depth of the cube in the octree.\n * \\return Vector with coordinates of points on the surface of the cube in the\n * format [x0 y0 z0 x1 y1 z1 .... ].\n */\ntemplate <class Real_t>\nstd::vector<Real_t> surface(int p, Real_t *c, Real_t alpha, int depth) {\n    size_t n_ = (6 * (p - 1) * (p - 1) + 2); // Total number of points.\n\n    std::vector<Real_t> coord(n_ * 3);\n    coord[0] = coord[1] = coord[2] = -1.0;\n    size_t cnt = 1;\n    for (int i = 0; i < p - 1; i++)\n        for (int j = 0; j < p - 1; j++) {\n            coord[cnt * 3] = -1.0;\n            coord[cnt * 3 + 1] = (2.0 * (i + 1) - p + 1) / (p - 1);\n            coord[cnt * 3 + 2] = (2.0 * j - p + 1) / (p - 1);\n            cnt++;\n        }\n    for (int i = 0; i < p - 1; i++)\n        for (int j = 0; j < p - 1; j++) {\n            coord[cnt * 3] = (2.0 * i - p + 1) / (p - 1);\n            coord[cnt * 3 + 1] = -1.0;\n            coord[cnt * 3 + 2] = (2.0 * (j + 1) - p + 1) / (p - 1);\n            cnt++;\n        }\n    for (int i = 0; i < p - 1; i++)\n        for (int j = 0; j < p - 1; j++) {\n            coord[cnt * 3] = (2.0 * (i + 1) - p + 1) / (p - 1);\n            coord[cnt * 3 + 1] = (2.0 * j - p + 1) / (p - 1);\n            coord[cnt * 3 + 2] = -1.0;\n            cnt++;\n        }\n    for (size_t i = 0; i < (n_ / 2) * 3; i++)\n        coord[cnt * 3 + i] = -coord[i];\n\n    Real_t r = 0.5 * pow(0.5, depth);\n    Real_t b = alpha * r;\n    for (size_t i = 0; i < n_; i++) {\n        coord[i * 3 + 0] = (coord[i * 3 + 0] + 1.0) * b + c[0];\n        coord[i * 3 + 1] = (coord[i * 3 + 1] + 1.0) * b + c[1];\n        coord[i * 3 + 2] = (coord[i * 3 + 2] + 1.0) * b + c[2];\n    }\n    return coord;\n}\n\ninline Eigen::Matrix3d AEW(const double xi, const Eigen::Vector3d &rvec) {\n    const double r = rvec.norm();\n    Eigen::Matrix3d A = 2 * (xi * exp(-(xi * xi) * (r * r)) / (sqrt(M_PI) * r * r) + erfc(xi * r) / (2 * r * r * r)) *\n                            (r * r * Eigen::Matrix3d::Identity() + (rvec * rvec.transpose())) -\n                        4 * xi / sqrt(M_PI) * exp(-(xi * xi) * (r * r)) * Eigen::Matrix3d::Identity();\n    return A;\n}\n\ninline double lbda(double k, double xi, double z) { return exp(-k * k / (4 * xi * xi) - (xi * xi) * (z * z)); }\n\ninline double thetaplus(double k, double xi, double z) { return exp(k * z) * std::erfc(k / (2 * xi) + xi * z); }\n\ninline double thetaminus(double k, double xi, double z) { return exp(-k * z) * std::erfc(k / (2 * xi) - xi * z); }\n\ninline double J00(double k, double xi, double z) { return sqrt(M_PI) * lbda(k, xi, z) * xi; }\n\ninline double J10(double k, double xi, double z) {\n    return M_PI * (thetaplus(k, xi, z) + thetaminus(k, xi, z)) / (4 * k);\n}\n\ninline double J20(double k, double xi, double z) {\n    return sqrt(M_PI) * lbda(k, xi, z) / (4 * k * k * xi) +\n           M_PI * ((thetaplus(k, xi, z) + thetaminus(k, xi, z)) / (8 * k * k * k) +\n                   (thetaminus(k, xi, z) - thetaplus(k, xi, z)) * z / (8 * k * k) -\n                   (thetaplus(k, xi, z) + thetaminus(k, xi, z)) / (16 * k * (xi * xi)));\n}\n\ninline double J12(double k, double xi, double z) {\n    return M_PI * (-thetaplus(k, xi, z) - thetaminus(k, xi, z)) * k / 4 + sqrt(M_PI) * lbda(k, xi, z) * xi;\n}\n\ninline double J22(double k, double xi, double z) {\n    return M_PI * ((thetaplus(k, xi, z) + thetaminus(k, xi, z)) * k / (16 * xi * xi) +\n                   (thetaplus(k, xi, z) + thetaminus(k, xi, z)) / (8 * k) +\n                   (thetaplus(k, xi, z) - thetaminus(k, xi, z)) * z / 8) -\n           sqrt(M_PI) * lbda(k, xi, z) / (4 * xi);\n}\n\ninline double K11(double k, double xi, double z) { return M_PI * ((thetaminus(k, xi, z) - thetaplus(k, xi, z))) / 4; }\n\ninline double K12(double k, double xi, double z) {\n    return M_PI * ((thetaplus(k, xi, z) - thetaminus(k, xi, z)) / (16 * xi * xi) +\n                   (thetaminus(k, xi, z) + thetaplus(k, xi, z)) * z / (8 * k));\n}\n\ninline void QI(const Eigen::Vector3d &kvec, double xi, double z, Eigen::Matrix3d &QI) {\n    // 3*3 tensor\n    // kvec: np.array([k1,k2,0])\n    double knorm = sqrt(kvec[0] * kvec[0] + kvec[1] * kvec[1]);\n    QI = 2 * (J00(knorm, xi, z) / (4 * xi * xi) + J10(knorm, xi, z)) * Eigen::Matrix3d::Identity();\n}\n\ninline void Qkk(const Eigen::Vector3d &kvec, double xi, double z, Eigen::Matrix3d &Qreal, Eigen::Matrix3d &Qimg) {\n    double k1 = kvec[0];\n    double k2 = kvec[1];\n    double knorm = sqrt(k1 * k1 + k2 * k2);\n    auto j10 = J10(knorm, xi, z);\n    auto j20 = J20(knorm, xi, z);\n    auto j12 = J12(knorm, xi, z);\n    auto j22 = J22(knorm, xi, z);\n\n    auto k11 = K11(knorm, xi, z);\n    auto k12 = K12(knorm, xi, z);\n    Qreal.setZero();\n    Qreal(0, 0) = k1 * k1;\n    Qreal(1, 1) = k2 * k2;\n    Qreal(0, 1) = k1 * k2;\n    Qreal(1, 0) = k1 * k2;\n\n    Qreal *= (j10 / (4 * (xi * xi)) + j20);\n    Qreal(2, 2) = (j12 / (4 * xi * xi) + j22);\n    Qreal *= -2;\n\n    Qimg.setZero();\n    Qimg(0, 2) = k1;\n    Qimg(1, 2) = k2;\n    Qimg(2, 0) = k1;\n    Qimg(2, 1) = k2;\n    // Qimg=np.array([[0,0,k1],[0,0,k2],[k1,k2,0]])*( k11/(4*xi**2) + k12 )\n    Qimg *= (k11 / (4 * xi * xi) + k12);\n    Qimg *= -2;\n}\n\n// without 1/8pi prefactor\ninline void GkernelEwald(const Eigen::Vector3d &rvecIn, Eigen::Matrix3d &Gsum) {\n    const double xi = 2;\n    Eigen::Vector3d rvec = rvecIn;\n    rvec[0] = rvec[0] - floor(rvec[0]);\n    rvec[1] = rvec[1] - floor(rvec[1]); // reset to a periodic cell\n\n    const double r = rvec.norm();\n    Eigen::Matrix3d real = Eigen::Matrix3d::Zero();\n    const int N = 5;\n    if (r < eps) {\n        auto Gself = -4 * xi / sqrt(M_PI) * Eigen::Matrix3d::Identity(); // the self term\n        for (int i = -N; i < N + 1; i++) {\n            for (int j = -N; j < N + 1; j++) {\n                if (i == 0 && j == 0) {\n                    continue;\n                }\n                real = real + AEW(xi, rvec + Eigen::Vector3d(i, j, 0));\n            }\n        }\n        real += Gself;\n    } else {\n        for (int i = -N; i < N + 1; i++) {\n            for (int j = -N; j < N + 1; j++) {\n                real = real + AEW(xi, rvec + Eigen::Vector3d(i, j, 0));\n            }\n        }\n    }\n\n    // k\n    Eigen::Matrix3d wave = Eigen::Matrix3d::Zero();\n\n    double zmn = rvec[2];\n    Eigen::Vector3d rhomn = rvec;\n    rhomn[2] = 0;\n    Eigen::Matrix3d Qreal;\n    Eigen::Matrix3d Qimg;\n    Eigen::Matrix3d QImat;\n    for (int i = -N; i < N + 1; i++) {\n        for (int j = -N; j < N + 1; j++) {\n            Eigen::Vector3d kvec(2 * M_PI * i, 2 * M_PI * j, 0);\n            if (i == 0 and j == 0) {\n                continue;\n            }\n            Qkk(kvec, xi, zmn, Qreal, Qimg);\n            QI(kvec, xi, zmn, QImat);\n            wave = wave + (QImat + Qreal) * cos(kvec.dot(rhomn)) - (Qimg)*sin(kvec.dot(rhomn));\n        }\n    }\n    wave *= 4;\n\n    // k=0\n    Eigen::Matrix3d waveK0;\n    waveK0.setZero();\n    /*\n     *   I2fn=force\n     I2fn[2]=0\n     wavek0=-(4/1)*(np.pi*(zmn)*ss.erf(zmn*xi)+np.sqrt(np.pi)/(2*xi)*np.exp(-zmn**2*xi**2))*I2fn\n     *\n     * */\n    waveK0 = -(4 / 1.0) * (M_PI * (zmn)*std::erf(zmn * xi) + sqrt(M_PI) / (2 * xi) * exp(-zmn * zmn * xi * xi)) *\n             Eigen::Matrix3d::Identity();\n    waveK0(2, 2) = 0;\n\n    Gsum = real + wave + waveK0;\n}\n\ninline double freal(double xi, double r) { return std::erfc(xi * r) / r; }\n\ninline double frealp(double xi, double r) {\n    return -(2. * exp(-r * r * (xi * xi)) * xi) / (sqrt(M_PI) * r) - std::erfc(r * xi) / (r * r);\n}\n\ninline double gxkz(double xi, double k, double z) {\n    return exp(k * z) * std::erfc(xi * z + k / (2 * xi)) + exp(-k * z) * std::erfc(-xi * z + k / (2 * xi));\n}\n\ninline double gxkzp(double xi, double k, double z) {\n    double pisqrt = sqrt(M_PI);\n    return k * exp(k * z) * std::erfc(xi * z + k / (2 * xi)) - k * exp(-k * z) * std::erfc(-xi * z + k / (2 * xi)) +\n           (2 * xi / pisqrt) *\n               (exp(-pow((-xi * z + k / (2 * xi)), 2) - k * z) - exp(-pow((xi * z + k / (2 * xi)), 2) + k * z));\n}\n\ninline void realSum(double xi, const EVec3 &target, const EVec3 &source, EVec3 &v) {\n\n    EVec3 rvec = target - source;\n    double rnorm = rvec.norm();\n    if (rnorm < eps) {\n        v.setZero();\n    } else {\n        v = (frealp(xi, rnorm) / rnorm) * rvec;\n    }\n}\n\ninline void Lkernel(const EVec3 &target, const EVec3 &source, EVec3 &answer) {\n    EVec3 rst = target - source;\n    double rnorm = rst.norm();\n    if (rnorm < eps) {\n        answer.setZero();\n        return;\n    }\n    double rnorm3 = rnorm * rnorm * rnorm;\n    answer = rst / rnorm3;\n}\n\n// grad of Laplace potential, without 1/4pi prefactor, periodic of -r_k/r^3\ninline void LkernelEwald(const EVec3 &target_, const EVec3 &source_, EVec3 &answer) {\n    EVec3 target = target_;\n    EVec3 source = source_;\n    target[0] = target[0] - floor(target[0]); // periodic BC\n    target[1] = target[1] - floor(target[1]);\n    source[0] = source[0] - floor(source[0]);\n    source[1] = source[1] - floor(source[1]);\n\n    double xi = 2;\n    //  real sum\n    int rLim = 4;\n    EVec3 Kreal = EVec3::Zero();\n    for (int i = -rLim; i < rLim + 1; i++) {\n        for (int j = -rLim; j < rLim + 1; j++) {\n            EVec3 v = EVec3::Zero();\n            realSum(xi, target, source - EVec3(i, j, 0), v);\n            Kreal += v;\n        }\n    }\n\n    //  wave sum\n    using EVec2 = Eigen::Vector2d;\n    int wLim = 4;\n    EVec3 rmn = target - source;\n    // double xi2 = xi * xi;\n    // double rmnnorm = rmn.norm();\n    EVec2 rxy(rmn[0], rmn[1]);\n    double rz = rmn[2];\n    EVec3 Kwave(0, 0, -2 * M_PI * std::erf(xi * rz));\n    for (int i = -wLim; i < wLim + 1; i++) {\n        for (int j = -wLim; j < wLim + 1; j++) {\n            if (i == 0 && j == 0)\n                continue;\n            EVec2 kvec = EVec2(i, j) * (2 * M_PI);\n\n            double k2 = kvec.dot(kvec);\n            double knorm = sqrt(k2);\n            double xyfac = -M_PI * sin(kvec.dot(rxy)) * gxkz(xi, knorm, rz) / knorm;\n            Kwave[0] += xyfac * kvec[0];\n            Kwave[1] += xyfac * kvec[1];\n            Kwave[2] += M_PI * cos(kvec.dot(rxy)) * gxkzp(xi, knorm, rz) / knorm;\n        }\n    }\n\n    answer = Kreal + Kwave;\n}\n\n// fx,fy,fz,trD -> p, vx,vy,vz\ninline void Wkernel(const EVec3 &target, const EVec3 &source, EMat4 &answer) {\n    auto rst = target - source;\n    double rnorm = rst.norm();\n    if (rnorm < eps) {\n        answer.setZero();\n        return;\n    }\n    double rnorm3 = rnorm * rnorm * rnorm;\n\n    answer.block<3, 3>(1, 0) = EMat3::Identity() / rnorm;\n    answer.block<3, 3>(1, 0) += rst * rst.transpose() / rnorm3;\n    answer(0, 0) = rst[0] / rnorm3;\n    answer(0, 1) = rst[1] / rnorm3;\n    answer(0, 2) = rst[2] / rnorm3;\n    answer(0, 3) = 0;\n    answer(1, 3) = -rst[0] / rnorm3;\n    answer(2, 3) = -rst[1] / rnorm3;\n    answer(3, 3) = -rst[2] / rnorm3;\n    answer.row(0) *= (1 / (4 * M_PI));\n    answer.block<3, 4>(1, 0) *= (1 / (8 * M_PI));\n}\n\ninline void WkernelEwald(const EVec3 &target, const EVec3 &source, EMat4 &answer) {\n    EMat3 G = EMat3::Zero();\n    GkernelEwald(target - source, G);\n    EVec3 L = EVec3::Zero();\n    LkernelEwald(target, source, L);\n    answer.block<3, 3>(1, 0) = G;\n    answer(0, 0) = -L[0];\n    answer(0, 1) = -L[1];\n    answer(0, 2) = -L[2];\n    answer(0, 3) = 0;\n    answer(1, 3) = L[0];\n    answer(2, 3) = L[1];\n    answer(3, 3) = L[2];\n    answer.row(0) *= (1 / (4 * M_PI));\n    answer.block<3, 4>(1, 0) *= (1 / (8 * M_PI));\n}\n\ninline void WkernelFF(const EVec3 &target, const EVec3 &source, EMat4 &answer) {\n    EMat4 WEwald = EMat4::Zero();\n    WkernelEwald(target, source, WEwald);\n    // for (int i = -2 * DIRECTLAYER; i < 2 * DIRECTLAYER + 1; i++) {\n    //     for (int j = -2 * DIRECTLAYER; j < 2 * DIRECTLAYER + 1; j++) {\n    //         EMat4 W = EMat4::Zero();\n    //         Wkernel(target, source + EVec3(i, j, 0), W);\n    //         WEwald += W;\n    //     }\n    // }\n\n    for (int i = -DIRECTLAYER; i < DIRECTLAYER + 1; i++) {\n        for (int j = -DIRECTLAYER; j < DIRECTLAYER + 1; j++) {\n            EMat4 W = EMat4::Zero();\n            Wkernel(target, source + EVec3(i, j, 0), W);\n            WEwald -= W;\n        }\n    }\n    answer = WEwald;\n}\n\n// calculate the M2L matrix of images from 2 to 1000\nint main(int argc, char **argv) {\n    Eigen::initParallel();\n    Eigen::setNbThreads(1);\n\n    // {\n    //     EMat4 G1 = EMat4::Zero(), G2 = EMat4::Zero();\n    //     std::vector<EVec3, Eigen::aligned_allocator<EVec3>> forcePoint(3);\n    //     std::vector<EVec4, Eigen::aligned_allocator<EVec4>> forceValue(3);\n    //     forcePoint[0] = EVec3(0.5, 0.55, 0.2);\n    //     forcePoint[1] = EVec3(0.5, 0.5, 0.5);\n    //     forcePoint[2] = EVec3(0.7, 0.7, 0.7);\n    //     forceValue[0] = EVec4(0.1, 0.2, 0.3, 0.4);\n    //     forceValue[1] = EVec4(-0.1, -0.1, -0.3, -0.4);\n    //     forceValue[2] = EVec4(0, -0.1, 0, 0);\n\n    //     EVec3 spoint(0.2, 0.3, 0.4);\n    //     EVec4 vE, vD;\n    //     vE.setZero();\n    //     vD.setZero();\n    //     for (int i = 0; i < forceValue.size(); i++) {\n    //         EMat4 temp = EMat4::Zero();\n    //         WkernelEwald(spoint, forcePoint[i], temp);\n    //         vE += temp * forceValue[i];\n    //     }\n    //     const int N = 200;\n    //     for (int i = -N; i <= N; i++) {\n    //         for (int j = -N; j <= N; j++) {\n    //             for (int k = 0; k < forceValue.size(); k++) {\n    //                 EMat4 temp = EMat4::Zero();\n    //                 Wkernel(spoint, forcePoint[k] + EVec3(i, j, 0), temp);\n    //                 vD += temp * forceValue[k];\n    //             }\n    //         }\n    //     }\n    //     std::cout << vE.transpose() << std::endl;\n    //     std::cout << (vE - vD).transpose() << std::endl;\n    //     // std::exit(0);\n    // }\n\n    const int pEquiv = atoi(argv[1]); // (8-1)^2*6 + 2 points\n    const int pCheck = atoi(argv[1]);\n    const double scaleEquiv = 1.05;\n    const double scaleCheck = 2.95;\n    const double pCenterEquiv[3] = {-(scaleEquiv - 1) / 2, -(scaleEquiv - 1) / 2, -(scaleEquiv - 1) / 2};\n    const double pCenterCheck[3] = {-(scaleCheck - 1) / 2, -(scaleCheck - 1) / 2, -(scaleCheck - 1) / 2};\n    auto pointMEquiv = surface(pEquiv, (double *)&(pCenterEquiv[0]), scaleEquiv,\n                               0); // center at 0.5,0.5,0.5, periodic box 1,1,1, scale 1.05, depth = 0\n    auto pointMCheck = surface(pCheck, (double *)&(pCenterCheck[0]), scaleCheck,\n                               0); // center at 0.5,0.5,0.5, periodic box 1,1,1, scale 1.05, depth = 0\n\n    auto pointLEquiv = surface(pEquiv, (double *)&(pCenterCheck[0]), scaleCheck,\n                               0); // center at 0.5,0.5,0.5, periodic box 1,1,1, scale 1.05, depth = 0\n    auto pointLCheck = surface(pCheck, (double *)&(pCenterEquiv[0]), scaleEquiv,\n                               0); // center at 0.5,0.5,0.5, periodic box 1,1,1, scale 1.05, depth = 0\n\n    // calculate the operator M2L with least square\n    const int equivN = pointMEquiv.size() / 3;\n    const int checkN = pointLCheck.size() / 3;\n    Eigen::MatrixXd A(4 * checkN, 4 * equivN);\n#pragma omp parallel for\n    for (int k = 0; k < checkN; k++) {\n        Eigen::Vector3d Cpoint(pointLCheck[3 * k], pointLCheck[3 * k + 1], pointLCheck[3 * k + 2]);\n        for (int l = 0; l < equivN; l++) {\n            const Eigen::Vector3d Lpoint(pointLEquiv[3 * l], pointLEquiv[3 * l + 1], pointLEquiv[3 * l + 2]);\n            EMat4 W = EMat4::Zero();\n            Wkernel(Cpoint, Lpoint, W);\n            A.block<4, 4>(4 * k, 4 * l) = W;\n        }\n    }\n    Eigen::MatrixXd ApinvU(A.cols(), A.rows());\n    Eigen::MatrixXd ApinvVT(A.cols(), A.rows());\n    pinv(A, ApinvU, ApinvVT);\n\n    Eigen::MatrixXd M2L(4 * equivN, 4 * equivN);\n\n#pragma omp parallel for\n    for (int i = 0; i < equivN; i++) {\n        const Eigen::Vector3d Mpoint(pointMEquiv[3 * i], pointMEquiv[3 * i + 1], pointMEquiv[3 * i + 2]);\n        Eigen::MatrixXd f(4 * checkN, 4);\n        for (int k = 0; k < checkN; k++) {\n            EMat4 temp = EMat4::Zero();\n            Eigen::Vector3d Cpoint(pointLCheck[3 * k], pointLCheck[3 * k + 1], pointLCheck[3 * k + 2]);\n            WkernelFF(Cpoint, Mpoint, temp);\n            f.block<4, 4>(4 * k, 0) = temp;\n        }\n        M2L.block(0, 4 * i, 4 * equivN, 4) = (ApinvU.transpose() * (ApinvVT.transpose() * f));\n    }\n\n    // dump M2L\n    for (int i = 0; i < 4 * equivN; i++) {\n        for (int j = 0; j < 4 * equivN; j++) {\n            std::cout << i << \" \" << j << \" \" << std::scientific << std::setprecision(18) << M2L(i, j) << std::endl;\n        }\n    }\n\n    // Test\n    // Sum of force and trD must be zero\n    std::vector<EVec3, Eigen::aligned_allocator<EVec3>> forcePoint(3);\n    std::vector<EVec4, Eigen::aligned_allocator<EVec4>> forceValue(3);\n    forcePoint[0] = EVec3(0.5, 0.55, 0.2);\n    forcePoint[1] = EVec3(0.5, 0.5, 0.5);\n    forcePoint[2] = EVec3(0.7, 0.7, 0.7);\n    forceValue[0] = EVec4(0.1, 0.2, 0.3, 0.4);\n    forceValue[1] = EVec4(-0.1, -0.1, -0.3, -0.4);\n    forceValue[2] = EVec4(0, -0.1, 0, 0);\n\n    // solve M\n    A.resize(4 * checkN, 4 * equivN);\n    ApinvU.resize(A.cols(), A.rows());\n    ApinvVT.resize(A.cols(), A.rows());\n    Eigen::VectorXd f(4 * checkN);\n#pragma omp parallel for\n    for (int k = 0; k < checkN; k++) {\n        Eigen::Vector3d Cpoint(pointMCheck[3 * k], pointMCheck[3 * k + 1], pointMCheck[3 * k + 2]);\n        EVec4 temp = EVec4::Zero();\n        for (int p = 0; p < forceValue.size(); p++) {\n            EMat4 W = EMat4::Zero();\n            Wkernel(Cpoint, forcePoint[p], W);\n            temp += W * (forceValue[p]);\n        }\n        f.block<4, 1>(4 * k, 0) = temp;\n        for (int l = 0; l < equivN; l++) {\n            Eigen::Vector3d Mpoint(pointMEquiv[3 * l], pointMEquiv[3 * l + 1], pointMEquiv[3 * l + 2]);\n            EMat4 W = EMat4::Zero();\n            Wkernel(Cpoint, Mpoint, W);\n            A.block<4, 4>(4 * k, 4 * l) = W;\n        }\n    }\n    pinv(A, ApinvU, ApinvVT);\n    Eigen::VectorXd Msource = (ApinvU.transpose() * (ApinvVT.transpose() * f));\n\n    std::cout << \"Msource: \" << Msource << std::endl;\n    std::cout << \"Msource Sum: \" << Msource.sum() << std::endl;\n    Eigen::VectorXd M2Lsource = M2L * (Msource);\n\n    {\n        EVec3 samplePoint(0.5, 0.2, 0.8);\n        // Compute: WFF from L, WFF from WkernelFF\n        EVec4 WFFL = EVec4::Zero();\n        EVec4 WFFK = EVec4::Zero();\n\n        for (int k = 0; k < equivN; k++) {\n            EVec3 Lpoint(pointLEquiv[3 * k], pointLEquiv[3 * k + 1], pointLEquiv[3 * k + 2]);\n            EMat4 W = EMat4::Zero();\n            Wkernel(samplePoint, Lpoint, W);\n            WFFL += W * M2Lsource.block<4, 1>(4 * k, 0);\n        }\n\n        for (int k = 0; k < forceValue.size(); k++) {\n            EMat4 W;\n            WkernelFF(samplePoint, forcePoint[k], W);\n            WFFK += W * forceValue[k];\n        }\n        std::cout << \"WFF from Lequiv: \" << WFFL << std::endl;\n        std::cout << \"WFF from Kernel: \" << WFFK << std::endl;\n        std::cout << \"FF Error: \" << WFFL - WFFK << std::endl;\n    }\n\n    return 0;\n}\n\n} // namespace StokesPVel2D3D\n\n#undef DIRECTLAYER\n", "meta": {"hexsha": "8ccb979770229c2e78821804229cb172bfa90a63", "size": 19571, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "M2L/StokesPVel/StokesPVel2D3D.cpp", "max_stars_repo_name": "lamsoa729/STKFMM", "max_stars_repo_head_hexsha": "26d7d971c198e3bed68eb8373e5590a6eb72f764", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "M2L/StokesPVel/StokesPVel2D3D.cpp", "max_issues_repo_name": "lamsoa729/STKFMM", "max_issues_repo_head_hexsha": "26d7d971c198e3bed68eb8373e5590a6eb72f764", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "M2L/StokesPVel/StokesPVel2D3D.cpp", "max_forks_repo_name": "lamsoa729/STKFMM", "max_forks_repo_head_hexsha": "26d7d971c198e3bed68eb8373e5590a6eb72f764", "max_forks_repo_licenses": ["Apache-2.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.3773234201, "max_line_length": 118, "alphanum_fraction": 0.4972152675, "num_tokens": 7327, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.45502661356908675}}
{"text": "/**\n * \\ file SD1ToneFilter.cpp\n */\n\n#include <ATK/EQ/PedalToneStackFilter.h>\n#include <ATK/EQ/IIRFilter.h>\n\n#include <ATK/Mock/FFTCheckerFilter.h>\n#include <ATK/Mock/SimpleSinusGeneratorFilter.h>\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_NO_MAIN\n#include <boost/test/unit_test.hpp>\n\n#define PROCESSSIZE (1024*1024)\n#define SAMPLINGRATE (1024*64)\n\nBOOST_AUTO_TEST_CASE( IIRFilter_SD1ToneCoefficients_throw_1_test )\n{\n  ATK::IIRFilter<ATK::SD1ToneCoefficients<double> > filter;\n  BOOST_CHECK_THROW(filter.set_tone(1.001), std::out_of_range);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_SD1ToneCoefficients_throw_0_test )\n{\n  ATK::IIRFilter<ATK::SD1ToneCoefficients<double> > filter;\n  BOOST_CHECK_THROW(filter.set_tone(-0.001), std::out_of_range);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_SD1ToneCoefficients_alpha0_100_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(SAMPLINGRATE);\n  generator.set_amplitude(1);\n  generator.set_frequency(100);\n  \n  ATK::IIRFilter<ATK::SD1ToneCoefficients<double> > filter;\n  filter.set_input_sampling_rate(SAMPLINGRATE);\n  filter.set_output_sampling_rate(SAMPLINGRATE);\n  filter.set_tone(0);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(SAMPLINGRATE);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(100, 0.9813101780535352));\n  frequency_checks.push_back(std::make_pair(1000, 0));\n  frequency_checks.push_back(std::make_pair(10000, 0));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_SD1ToneCoefficients_alpha0_1k_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(SAMPLINGRATE);\n  generator.set_amplitude(1);\n  generator.set_frequency(1000);\n  \n  ATK::IIRFilter<ATK::SD1ToneCoefficients<double> > filter;\n  filter.set_input_sampling_rate(SAMPLINGRATE);\n  filter.set_output_sampling_rate(SAMPLINGRATE);\n  filter.set_tone(0);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(SAMPLINGRATE);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(100, 0));\n  frequency_checks.push_back(std::make_pair(1000, 0.6236407269569778));\n  frequency_checks.push_back(std::make_pair(10000, 0));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_SD1ToneCoefficients_alpha0_10k_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(SAMPLINGRATE);\n  generator.set_amplitude(1);\n  generator.set_frequency(10000);\n  \n  ATK::IIRFilter<ATK::SD1ToneCoefficients<double> > filter;\n  filter.set_input_sampling_rate(SAMPLINGRATE);\n  filter.set_output_sampling_rate(SAMPLINGRATE);\n  filter.set_tone(0);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(SAMPLINGRATE);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(100, 0));\n  frequency_checks.push_back(std::make_pair(1000, 0));\n  frequency_checks.push_back(std::make_pair(10000, 0.525581554888129));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_SD1ToneCoefficients_alpha1_100_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(SAMPLINGRATE);\n  generator.set_amplitude(1);\n  generator.set_frequency(100);\n  \n  ATK::IIRFilter<ATK::SD1ToneCoefficients<double> > filter;\n  filter.set_input_sampling_rate(SAMPLINGRATE);\n  filter.set_output_sampling_rate(SAMPLINGRATE);\n  filter.set_tone(1);\n\n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(SAMPLINGRATE);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(100, 1.0106781785286139));\n  frequency_checks.push_back(std::make_pair(1000, 0));\n  frequency_checks.push_back(std::make_pair(10000, 0));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_SD1ToneCoefficients_alpha1_1k_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(SAMPLINGRATE);\n  generator.set_amplitude(1);\n  generator.set_frequency(1000);\n  \n  ATK::IIRFilter<ATK::SD1ToneCoefficients<double> > filter;\n  filter.set_input_sampling_rate(SAMPLINGRATE);\n  filter.set_output_sampling_rate(SAMPLINGRATE);\n  filter.set_tone(1);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(SAMPLINGRATE);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(100, 0));\n  frequency_checks.push_back(std::make_pair(1000, 1.3065626075847556));\n  frequency_checks.push_back(std::make_pair(10000, 0));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_SD1ToneCoefficients_alpha1_10k_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(SAMPLINGRATE);\n  generator.set_amplitude(1);\n  generator.set_frequency(10000);\n  \n  ATK::IIRFilter<ATK::SD1ToneCoefficients<double> > filter;\n  filter.set_input_sampling_rate(SAMPLINGRATE);\n  filter.set_output_sampling_rate(SAMPLINGRATE);\n  filter.set_tone(1);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(SAMPLINGRATE);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(100, 0));\n  frequency_checks.push_back(std::make_pair(1000, 0));\n  frequency_checks.push_back(std::make_pair(10000, 1.2770732276129428));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_SD1ToneCoefficients_alpha05_100_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(SAMPLINGRATE);\n  generator.set_amplitude(1);\n  generator.set_frequency(100);\n  \n  ATK::IIRFilter<ATK::SD1ToneCoefficients<double> > filter;\n  filter.set_input_sampling_rate(SAMPLINGRATE);\n  filter.set_output_sampling_rate(SAMPLINGRATE);\n  filter.set_tone(0.5);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(SAMPLINGRATE);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(100, 0.99588245799196));\n  frequency_checks.push_back(std::make_pair(1000, 0));\n  frequency_checks.push_back(std::make_pair(10000, 0));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_SD1ToneCoefficients_alpha05_1k_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(SAMPLINGRATE);\n  generator.set_amplitude(1);\n  generator.set_frequency(1000);\n  \n  ATK::IIRFilter<ATK::SD1ToneCoefficients<double> > filter;\n  filter.set_input_sampling_rate(SAMPLINGRATE);\n  filter.set_output_sampling_rate(SAMPLINGRATE);\n  filter.set_tone(0.5);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(SAMPLINGRATE);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(100, 0));\n  frequency_checks.push_back(std::make_pair(1000, 0.9164270318538241));\n  frequency_checks.push_back(std::make_pair(10000, 0));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_SD1ToneCoefficients_alpha05_10k_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(SAMPLINGRATE);\n  generator.set_amplitude(1);\n  generator.set_frequency(10000);\n  \n  ATK::IIRFilter<ATK::SD1ToneCoefficients<double> > filter;\n  filter.set_input_sampling_rate(SAMPLINGRATE);\n  filter.set_output_sampling_rate(SAMPLINGRATE);\n  filter.set_tone(0.5);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(SAMPLINGRATE);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(100, 0));\n  frequency_checks.push_back(std::make_pair(1000, 0));\n  frequency_checks.push_back(std::make_pair(10000, 0.7559110473244306));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n", "meta": {"hexsha": "b95d8acf9618611f1dabf4cd6c3cf2e87d05332b", "size": 9288, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/EQ/SD1ToneFilter.cpp", "max_stars_repo_name": "apohl79/AudioTK", "max_stars_repo_head_hexsha": "05ac241b0bc6a8f841d93257b4d81e5961b1f627", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-05-17T15:29:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T22:26:08.000Z", "max_issues_repo_path": "tests/EQ/SD1ToneFilter.cpp", "max_issues_repo_name": "apohl79/AudioTK", "max_issues_repo_head_hexsha": "05ac241b0bc6a8f841d93257b4d81e5961b1f627", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/EQ/SD1ToneFilter.cpp", "max_forks_repo_name": "apohl79/AudioTK", "max_forks_repo_head_hexsha": "05ac241b0bc6a8f841d93257b4d81e5961b1f627", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-04-21T13:43:57.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-28T19:10:14.000Z", "avg_line_length": 33.0533807829, "max_line_length": 72, "alphanum_fraction": 0.7814384152, "num_tokens": 2565, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645725, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.4549877646272483}}
{"text": "//==================================================================================================\n/*!\n  @file\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_ERFC_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_ERFC_HPP_INCLUDED\n\n#include <boost/simd/function/std.hpp>\n#include <boost/simd/detail/dispatch/function/overload.hpp>\n#include <boost/simd/arch/common/detail/generic/erf_kernel.hpp>\n#include <boost/simd/constant/pi.hpp>\n#include <boost/simd/constant/two.hpp>\n#include <boost/simd/constant/ratio.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/function/abs.hpp>\n#include <boost/simd/function/exp.hpp>\n#include <boost/simd/function/oneminus.hpp>\n#include <boost/simd/function/inc.hpp>\n#include <boost/simd/function/sqr.hpp>\n#include <boost/simd/function/sqrt.hpp>\n#include <boost/simd/function/rec.hpp>\n#ifndef BOOST_SIMD_NO_INVALIDS\n#include <boost/simd/function/is_nan.hpp>\n#endif\n#ifndef BOOST_SIMD_NO_INFINITIES\n#include <boost/simd/constant/inf.hpp>\n#endif\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 ( erfc_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_< bd::single_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() (A0 a0) const BOOST_NOEXCEPT\n    {\n      A0 x =  bs::abs(a0);\n      A0 r1 = Zero<A0>();\n      A0 z =  x/inc(x);\n      if (x < Ratio<A0, 2, 3>())\n      {\n        r1 = detail::erf_kernel<A0>::erfc3(z);\n      }\n      #ifndef BOOST_SIMD_NO_INFINITIES\n      else if (BOOST_UNLIKELY(x == Inf<A0>()))\n      {\n        r1 = Zero<A0>();\n      }\n      #endif\n      else\n      {\n       z-= 0.4f;\n       r1 = exp(-sqr(x))*detail::erf_kernel<A0>::erfc2(z);\n      }\n      return (a0 < 0.0f) ? 2.0f-r1 : r1;\n    }\n  };\n  BOOST_DISPATCH_OVERLOAD ( erfc_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_< bd::double_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() (A0 x) const BOOST_NOEXCEPT\n    {\n      #ifndef BOOST_SIMD_NO_INVALIDS\n      if(is_nan(x)) return x;\n      #endif\n      A0 y =  bs::abs(x);\n      if (y <= Ratio<A0, 15, 32>()) // 0.46875\n      {\n        A0 res = detail::erf_kernel1<A0>::erf1(x, y);\n        res =  oneminus(res);\n        return res;\n      }\n      else if (y <= Ratio<A0, 4>())\n      {\n        A0 res = detail::erf_kernel1<A0>::erf2(x, y);\n        res =    detail::erf_kernel1<A0>::finalize2(res, y);\n        if (is_ltz(x)) res = Two<A0>()-res;\n        return res;\n      }\n      else if  (y <= 26.543)\n      {\n        A0 res = detail::erf_kernel1<A0>::erf3(x, y);\n        res =    detail::erf_kernel1<A0>::finalize2(res, y);\n        if (is_ltz(x)) res = Two<A0>()-res;\n        return res;\n      }\n      else return Zero<A0>();\n    }\n  };\n  BOOST_DISPATCH_OVERLOAD ( erfc_\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::erfc(a0);\n    }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "4973d6556019cbec25eed0a4a3f64d4b690779ea", "size": 3616, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/scalar/function/erfc.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/scalar/function/erfc.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/erfc.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": 30.1333333333, "max_line_length": 100, "alphanum_fraction": 0.530420354, "num_tokens": 963, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.45498776462724827}}
{"text": "//  Copyright Matt Borland 2021.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n//\n// Basic sanity check that header <boost/math/tools/polynomial_gcd.hpp>\n// #includes all the files that it needs to.\n//\n#include <boost/math/tools/polynomial_gcd.hpp>\n//\n// Note this header includes no other headers, this is\n// important if this test is to be meaningful:\n//\n#include \"test_compile_result.hpp\"\n\nvoid compile_and_link_test()\n{\n    boost::math::tools::polynomial<int> p_int;\n    check_result<int>(boost::math::tools::content(p_int));\n    check_result<int>(boost::math::tools::leading_coefficient(p_int));\n        \n    boost::math::tools::polynomial<long> p_long;\n    check_result<long>(boost::math::tools::content(p_long));\n    check_result<long>(boost::math::tools::leading_coefficient(p_long));\n}\n", "meta": {"hexsha": "d5fc0bb27e2ef8278516fac214de6d8956bf9c6f", "size": 940, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/compile_test/tools_polynomial_gcd_incl_test.cpp", "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": "test/compile_test/tools_polynomial_gcd_incl_test.cpp", "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": "test/compile_test/tools_polynomial_gcd_incl_test.cpp", "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": 36.1538461538, "max_line_length": 72, "alphanum_fraction": 0.7276595745, "num_tokens": 234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.45498776462724816}}
{"text": "#pragma once\n//standard include\n#include <math.h>\n#include <iostream>\n\n//opencv include\n#include \"opencv2/imgproc/imgproc.hpp\"\n#include \"opencv2/core/core.hpp\"\n#include <boost/circular_buffer.hpp>\n\n#include \"track3d.hpp\"\n\nstruct DepthInfo\n{\n\tfloat depth;\n\tbool  error;\n};\n\n//this contains all the info we need to decide between goals once we are certain if it is a goal\nstruct GoalInfo\n{\n\tcv::Point3f pos;\n\tfloat confidence;\n\tfloat distance;\n\tfloat angle;\n\tcv::Rect rect;\n\tsize_t vec_index;\n\tbool depth_error;\n\tcv::Point com;\n\tcv::Rect br;\n};\n\nclass GoalDetector\n{\n\tpublic:\n\t\tGoalDetector(const cv::Point2f &fov_size, const cv::Size &frame_size, bool gui = false);\n\n\t\tfloat dist_to_goal(void) const;\n\t\tfloat angle_to_goal(void) const;\n\t\tcv::Rect goal_rect(void) const;\n\t\tcv::Point3f goal_pos(void) const;\n\t\tvoid drawOnFrame(cv::Mat &image,const std::vector< std::vector< cv::Point>> &contours) const;\n\n\t\t//These are the three functions to call to run GoalDetector\n\t\t//they fill in _contours, _infos, _depth_mins, etc\n\t\tvoid clear(void);\n\n\t\t//If your objectypes have the same width it's safe to run\n\t\t//getContours and computeConfidences with different types\n\t\tvoid findBoilers(const cv::Mat& image, const cv::Mat& depth);\n\t\tconst std::vector< std::vector< cv::Point > > getContours(const cv::Mat& image);\n\n\t\tbool Valid(void) const;\n\tprivate:\n\t\n\t\tcv::Point2f _fov_size;\n\t\tcv::Size    _frame_size;\n\n\t\t// Save detection info\n\t\tbool        _isValid;\n\t\tfloat       _dist_to_goal;\n\t\tfloat       _angle_to_goal;\n\t\tcv::Rect    _goal_left_rect;\n\t\tcv::Rect    _goal_right_rect;\n\t\tcv::Point3f _goal_pos;\n\n\t\tfloat       _min_valid_confidence;\n\n\t\tint         _otsu_threshold;\n\t\tint         _blue_scale;\n\t\tint         _red_scale;\n\n\t\tint         _camera_angle;\n\n\t\tfloat createConfidence(float expectedVal, float expectedStddev, float actualVal);\n\t\tfloat distanceUsingFOV(ObjectType _goal_shape, const cv::Rect &rect) const;\n\t\tfloat distanceUsingFixedHeight(const cv::Rect &rect,const cv::Point &center, float expected_delta_height) const;\n\t\tbool generateThresholdAddSubtract(const cv::Mat& imageIn, cv::Mat& imageOut);\n\t\tvoid isValid();\n\t\tconst std::vector<DepthInfo> getDepths(const cv::Mat &depth, const std::vector< std::vector< cv::Point > > &contours, ObjectNum objtype, float expected_height);\n\t\tconst std::vector< GoalInfo > getInfo(const std::vector< std::vector< cv::Point > > &contours, const std::vector<DepthInfo> &depth_maxs, ObjectNum objtype);\n};\n", "meta": {"hexsha": "7fa92ed900038de14d08d9df2822f6873221c6ff", "size": 2447, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "common/GoalDetector.hpp", "max_stars_repo_name": "FRC900/2018Offseason", "max_stars_repo_head_hexsha": "9940869e9c126c6b0beaa5517d1e719ed5063a35", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-03-24T20:54:20.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-24T20:54:20.000Z", "max_issues_repo_path": "common/GoalDetector.hpp", "max_issues_repo_name": "FRC900/2018Offseason", "max_issues_repo_head_hexsha": "9940869e9c126c6b0beaa5517d1e719ed5063a35", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/GoalDetector.hpp", "max_forks_repo_name": "FRC900/2018Offseason", "max_forks_repo_head_hexsha": "9940869e9c126c6b0beaa5517d1e719ed5063a35", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-01-19T00:40:39.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-19T00:40:39.000Z", "avg_line_length": 29.4819277108, "max_line_length": 162, "alphanum_fraction": 0.7208827135, "num_tokens": 661, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645723, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4549877646272481}}
{"text": "#ifndef __SDT_NONIDEAL_HH\n#define __SDT_NONIDEAL_HH\n/********************************* TRICK HEADER *******************************\nPURPOSE:\n      (Sensor Data Transport module)\nLIBRARY DEPENDENCY:\n      ((../../src/SDT_nonideal.cpp))\n*******************************************************************************/\n#include <armadillo>\n#include <functional>\n#include \"sdt/SDT.hh\"\n\nclass SDT_NONIDEAL : public SDT {\n  TRICK_INTERFACE(SDT_NONIDEAL);\n\n public:\n  SDT_NONIDEAL(Data_exchang& input);\n  SDT_NONIDEAL(const SDT_NONIDEAL& other);\n  SDT_NONIDEAL& operator=(const SDT_NONIDEAL& other);\n  virtual void init(){};\n  virtual void algorithm(double int_step);\n  virtual int write_to_(const char* bus_name);\n\n private:\n  arma::mat33 build_321_rotation_matrix(arma::vec3 angle);\n\n  VECTOR(WBISB, 3); /* *o  (r/s)    Angular rate of body frame relative inertial\n                       frame as described in body frame sensed by gyro */\n\n  VECTOR(WBISB_old,\n         3); /* *o  (r/s)    Angular rate of body frame relative inertial frame\n                as described in body frame (previous time step) */\n\n  VECTOR(DELTA_ALPHA, 3); /* *o  (r)      Delta theta */\n\n  VECTOR(DELTA_ALPHA_old, 3); /* *o (r)   Delta theta (previous time step) */\n\n  VECTOR(ALPHA, 3); /* *o (r)       Alpha */\n\n  VECTOR(FSPSB, 3); /* *o (m/s2)    Specific force of body frame sensed by\n                       accelerometer */\n\n  VECTOR(FSPSB_old, 3); /* *o (m/s2)    Previous Specific force of body frame\n                           sensed by accelerometer */\n\n  VECTOR(cross2_old,\n         3); /* *o (--)      temporal store the cross product result */\n\n  VECTOR(VEL, 3); /* *o (m/s)     Delta velocity generated by Accelerometer\n                     sensing value */\n};\n\n#endif\n", "meta": {"hexsha": "98d53f71ae3ed5ca93419008f8e8545dc255eea7", "size": 1754, "ext": "hh", "lang": "C++", "max_stars_repo_path": "models/sensor/include/sdt/SDT_NONIDEAL.hh", "max_stars_repo_name": "cihuang123/Next-simulation", "max_stars_repo_head_hexsha": "e8552a5804184b30022d103d47c8728fb242b5bc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "models/sensor/include/sdt/SDT_NONIDEAL.hh", "max_issues_repo_name": "cihuang123/Next-simulation", "max_issues_repo_head_hexsha": "e8552a5804184b30022d103d47c8728fb242b5bc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models/sensor/include/sdt/SDT_NONIDEAL.hh", "max_forks_repo_name": "cihuang123/Next-simulation", "max_forks_repo_head_hexsha": "e8552a5804184b30022d103d47c8728fb242b5bc", "max_forks_repo_licenses": ["BSD-3-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.4814814815, "max_line_length": 80, "alphanum_fraction": 0.5809578107, "num_tokens": 447, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.782662489091802, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.45496412384043566}}
{"text": "// Copyright Louis Dionne 2013-2017\r\n// Distributed under the Boost Software License, Version 1.0.\r\n// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\r\n\r\n#include <boost/hana/div.hpp>\r\n#include <boost/hana/mod.hpp>\r\n#include <boost/hana/tuple.hpp>\r\n\r\n#include <laws/euclidean_ring.hpp>\r\nnamespace hana = boost::hana;\r\n\r\n\r\nint main() {\r\n    hana::test::TestEuclideanRing<int>{hana::make_tuple(0,1,2,3,4,5)};\r\n    hana::test::TestEuclideanRing<long>{hana::make_tuple(0l,1l,2l,3l,4l,5l)};\r\n\r\n    // div\r\n    {\r\n        static_assert(hana::div(6, 4) == 6 / 4, \"\");\r\n        static_assert(hana::div(7, -3) == 7 / -3, \"\");\r\n    }\r\n\r\n    // mod\r\n    {\r\n        static_assert(hana::mod(6, 4) == 6 % 4, \"\");\r\n        static_assert(hana::mod(7, -3) == 7 % -3, \"\");\r\n    }\r\n}\r\n", "meta": {"hexsha": "92dd294b875ea4c490868b98e281a7e0a1794447", "size": 797, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/hana/test/euclidean_ring.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": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/hana/test/euclidean_ring.cpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-04T18:00:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-04T18:00:00.000Z", "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/hana/test/euclidean_ring.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 27.4827586207, "max_line_length": 82, "alphanum_fraction": 0.5872020075, "num_tokens": 260, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529376, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.45496411794668246}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// distribution::model::models::posterior::log_unnormalized_pdf.hpp          //\n//                                                                           //\n//  Copyright 2009 Erwann Rogard. Distributed under the Boost                //\n//  Software License, Version 1.0. (See accompanying file                    //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)         //\n///////////////////////////////////////////////////////////////////////////////\n#ifndef BOOST_STATISTICS_DETAIL_DISTRIBUTION_MODEL_MODELS_POSTERIOR_LOG_UNNORMALIZED_PDF_HPP_ER_2009\n#define BOOST_STATISTICS_DETAIL_DISTRIBUTION_MODEL_MODELS_POSTERIOR_LOG_UNNORMALIZED_PDF_HPP_ER_2009\n#include <numeric>\n#include <boost/range.hpp>\n#include <boost/lambda/lambda.hpp>\n#include <boost/lambda/bind.hpp>\n#include <boost/function.hpp>\n#include <boost/statistics/detail/distribution_common/meta/value.hpp>\n#include <boost/statistics/detail/distribution_common/functor/log_unnormalized_pdf.hpp>\n\nnamespace boost{\nnamespace statistics{\nnamespace detail{\nnamespace distribution{\nnamespace model{\n\n    template<typename Pr,typename L,typename P>\n    typename distribution::meta::value<\n        distribution::model::posterior<Pr,L>\n    >::type\n    log_unnormalized_pdf(\n        const distribution::model::posterior<Pr,L>& post,\n        const P& p\n    )\n    {\n        typedef typename distribution::meta::value<\n            distribution::model::posterior<Pr,L>\n        >::type val_;\n        val_ val = log_unnormalized_pdf(post.prior(),p);\n        val += log_unnormalized_pdf(static_cast<const L&>(post),p);\n        return val;\n\n    }\n    \n}// model\n}// distribution\n}// detail\n}// statistics\n}// boost\n\n#endif\n\n\n", "meta": {"hexsha": "431f0bbc72eaa58c3c55c9a533a7023cb501c0e7", "size": 1777, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "distribution_model/boost/statistics/detail/distribution/model/models/posterior/log_unnormalized_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_model/boost/statistics/detail/distribution/model/models/posterior/log_unnormalized_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_model/boost/statistics/detail/distribution/model/models/posterior/log_unnormalized_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": 34.8431372549, "max_line_length": 100, "alphanum_fraction": 0.614518852, "num_tokens": 359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.45496411794668234}}
{"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 <Eigen/Core>\n\n#include <igl/boundary_loop.h>\n#include <igl/lscm.h>\n#include <igl/MappingEnergyType.h>\n#include <igl/map_vertices_to_circle.h>\n#include <igl/harmonic.h>\n#include <igl/flipped_triangles.h>\n#include <igl/topological_hole_fill.h>\n#include <igl/scaf.h>\n\nnamespace ork::meshutil {\n//////////////////////////////////////////////////////////////////////////////\nEigen::MatrixXd IglMesh::parameterizeHarmonic() const {\n  Eigen::MatrixXd harmonic_uvs;\n  // Find the open boundary\n  Eigen::VectorXi bnd;\n  igl::boundary_loop(_faces, bnd);\n\n  // Map the boundary to a circle, preserving edge proportions\n  Eigen::MatrixXd bnd_uv;\n  igl::map_vertices_to_circle(_verts, bnd, bnd_uv);\n\n  // Harmonic parametrization for the internal vertices\n  igl::harmonic(_verts, _faces, bnd, bnd_uv, 1, harmonic_uvs);\n  return harmonic_uvs;\n}\n//////////////////////////////////////////////////////////////////////////////\nEigen::MatrixXd IglMesh::parameterizeLCSM() {\n  Eigen::MatrixXd lcsm_uvs;\n  // Fix two points on the boundary\n  Eigen::VectorXi bnd, b(2, 1);\n  igl::boundary_loop(_faces, bnd);\n  b(0) = bnd(0);\n  b(1) = bnd(bnd.size() / 2);\n  Eigen::MatrixXd bc(2, 2);\n  bc << 0, 0, 1, 0;\n  // LSCM parametrization\n  igl::lscm(_verts, _faces, b, bc, lcsm_uvs);\n  return lcsm_uvs;\n}\n//////////////////////////////////////////////////////////////////////////////\niglmesh_ptr_t IglMesh::parameterizedSCAF(int numiters, double scale, double bias) const {\n\n  Eigen::MatrixXd V = _verts;\n  Eigen::MatrixXi F = _faces;\n  igl::SCAFData scaf_data;\n\n  Eigen::MatrixXd bnd_uv, uv_init;\n\n  Eigen::VectorXd M;\n  igl::doublearea(V, F, M);\n  std::vector<std::vector<int>> all_bnds;\n  igl::boundary_loop(F, all_bnds);\n\n  printf(\"numbnds<%zu>\\n\", all_bnds.size());\n\n  // Heuristic primary boundary choice: longest\n  auto primary_bnd = std::max_element(\n      all_bnds.begin(), all_bnds.end(), [](const std::vector<int>& a, const std::vector<int>& b) { return a.size() < b.size(); });\n\n  OrkAssert(primary_bnd != all_bnds.end()); // see https://github.com/libigl/libigl/issues/873\n\n  Eigen::VectorXi bnd = Eigen::Map<Eigen::VectorXi>(primary_bnd->data(), primary_bnd->size());\n\n  igl::map_vertices_to_circle(V, bnd, bnd_uv);\n  bnd_uv *= sqrt(M.sum() / (2 * igl::PI));\n  if (all_bnds.size() == 1) {\n    if (bnd.rows() == V.rows()) // case: all vertex on boundary\n    {\n      uv_init.resize(V.rows(), 2);\n      for (int i = 0; i < bnd.rows(); i++)\n        uv_init.row(bnd(i)) = bnd_uv.row(i);\n    } else {\n      igl::harmonic(V, F, bnd, bnd_uv, 1, uv_init);\n      if (igl::flipped_triangles(uv_init, F).size() != 0)\n        igl::harmonic(F, bnd, bnd_uv, 1, uv_init); // fallback uniform laplacian\n    }\n  } else {\n    // if there is a hole, fill it and erase additional vertices.\n    all_bnds.erase(primary_bnd);\n    Eigen::MatrixXi F_filled;\n    igl::topological_hole_fill(F, bnd, all_bnds, F_filled);\n    igl::harmonic(F_filled, bnd, bnd_uv, 1, uv_init);\n    uv_init.conservativeResize(V.rows(), 2);\n  }\n\n  Eigen::VectorXi b;\n  Eigen::MatrixXd bc;\n  igl::scaf_precompute(V, F, uv_init, scaf_data, igl::MappingEnergyType::SYMMETRIC_DIRICHLET, b, bc, 0);\n\n  //_verts = V;\n  //_faces = F;\n\n  igl::scaf_solve(scaf_data, numiters);\n\n  auto rval                           = std::make_shared<IglMesh>(V, F);\n  double uv_scale                     = 0.2 * 0.5 * scale;\n  double uv_bias                      = 0.5 + bias;\n  Eigen::MatrixXd scaledandbiased_uvs = uv_scale * scaf_data.w_uv.topRows(V.rows());\n  size_t num_uvs                      = scaledandbiased_uvs.rows();\n  for (size_t i = 0; i < num_uvs; i++) {\n    scaledandbiased_uvs(i, 0) = scaledandbiased_uvs(i, 0) + uv_bias; // U\n    scaledandbiased_uvs(i, 1) = scaledandbiased_uvs(i, 1) + uv_bias; // V\n  }\n  rval->_uvs = scaledandbiased_uvs;\n  return rval;\n}\n//////////////////////////////////////////////////////////////////////////////\n} // namespace ork::meshutil\n\n#endif", "meta": {"hexsha": "9de36615c536fc7459e891ca3fa877dac5002d57", "size": 4448, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ork.lev2/src/gfx/meshutil/submesh_igl_parameterize.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_parameterize.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_parameterize.cpp", "max_forks_repo_name": "tweakoz/orkid", "max_forks_repo_head_hexsha": "e3f78dfb3375853fd512a9d0828b009075a18345", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2017-02-20T18:17:55.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-28T03:47:55.000Z", "avg_line_length": 34.75, "max_line_length": 130, "alphanum_fraction": 0.5980215827, "num_tokens": 1311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.5698526514141572, "lm_q1q2_score": 0.4548488570900249}}
{"text": "/*\n * Chaos \n *\n * Copyright 2015 Operating Systems Laboratory EPFL\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 _ALS_GRAPHCHI_\n#define _ALS_GRAPHCHI_\n\n#include \"../../utils/options_utils.h\"\n#include \"../../utils/desc_utils.h\"\n#include \"../../utils/boost_log_wrapper.h\"\n#include \"../../core/x-lib.hpp\"\n#include <cmath>\n#include <boost/random.hpp>\n#include <boost/thread/mutex.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/bindings/lapack/gesv.hpp>\n#include <boost/numeric/bindings/traits/ublas_matrix.hpp>\n#include <boost/numeric/bindings/traits/ublas_vector2.hpp>\n\n#define LAMBDA 0.065\n#define RANK   5\n\nnamespace ublas = boost::numeric::ublas;\nnamespace lapack = boost::numeric::bindings::lapack;\n\n//typedef ublas::bounded_array<double, RANK> storage_t;\n//typedef ublas::vector<double, storage_t> vector_t;\n//typedef ublas::matrix<double, ublas::row_major, storage_t> matrix_t;\n\nnamespace algorithm {\n  namespace sg_simple {\n    class als_graphchi_per_processor_data : public per_processor_data {\n    public:\n        static double sse;\n        double sse_local;\n        bool local_continue;\n\n        als_graphchi_per_processor_data()\n            : sse_local(0.0), local_continue(false) { }\n\n        bool reduce(per_processor_data **per_cpu_array,\n                    unsigned long processors) {\n          bool global_continue = false;\n          for (unsigned long i = 0; i < processors; i++) {\n            als_graphchi_per_processor_data *data =\n                static_cast<als_graphchi_per_processor_data *>(per_cpu_array[i]);\n            sse += data->sse_local;\n            data->sse_local = 0;\n            global_continue = global_continue || data->local_continue;\n            data->local_continue = false;\n          }\n          return !global_continue;\n        }\n    } __attribute__((__aligned__(64)));\n\n    template<typename F>\n    class als_graphchi_factorization {\n\n    private:\n\n        struct vertex {\n            bool rightside;\n            vertex_t degree;\n            vertex_t count;\n            double feature_vec[2][RANK];\n            double temp_mat[RANK][RANK];\n        } __attribute__((__packed__));\n\n        struct update {\n            vertex_t target;\n            double feature_vec[RANK];\n            double rating;\n        } __attribute__((__packed__));\n\n        static unsigned long niters;\n\n        // Helpers\n        static void copy_vector(double src_vec[RANK], double dst_vec[RANK]) {\n          for (int i = 0; i < RANK; i++)\n            dst_vec[i] = src_vec[i];\n        }\n\n        static void zero_vector(double vec[RANK]) {\n          for (int i = 0; i < RANK; i++)\n            vec[i] = 0;\n        }\n\n        static void zero_matrix(double mat[RANK][RANK]) {\n          for (int i = 0; i < RANK; i++)\n            for (int j = 0; j < RANK; j++)\n              mat[i][j] = 0;\n        }\n\n        static void init_vertex(struct vertex &v) {\n          v.rightside = false;\n          v.degree = 0;\n          v.count = 0;\n\n          boost::mt19937 generator;\n          boost::uniform_int<> distribution(0, 1000);\n          for (int i = 0; i < RANK; i++) {\n            v.feature_vec[0][i] = 0.001 * distribution(generator);\n            v.feature_vec[1][i] = 0.001 * distribution(generator);\n          }\n        }\n\n        // Solve the system Ax=b using LAPACK library and boost bindings for it\n        // This has some copying that should somehow be removed\n        static void solve(double mat[RANK][RANK], double vec[RANK]) {\n          ublas::matrix<double, ublas::column_major> A(RANK, RANK);\n          ublas::vector<double> b(RANK);\n\n          for (int i = 0; i < RANK; i++) {\n            b(i) = vec[i];\n            for (int j = 0; j < RANK; j++) {\n              A(i, j) = mat[i][j];\n            }\n          }\n\n          lapack::gesv(A, b);\n\n          for (int i = 0; i < RANK; i++)\n            vec[i] = b(i);\n        }\n\n    public:\n        static unsigned long vertex_state_bytes() {\n          return sizeof(struct vertex);\n        }\n\n        static unsigned long split_size_bytes() {\n          return sizeof(struct update);\n        }\n\n        static unsigned long split_key(unsigned char *buffer, unsigned long jump) {\n          struct update *u = (struct update *) buffer;\n          vertex_t key = u->target;\n          key = key >> jump;\n          return key;\n        }\n\n        static bool init(unsigned char *vertex_state,\n                         unsigned long vertex_index,\n                         unsigned long bsp_phase,\n                         per_processor_data *cpu_state) {\n          struct vertex *vertices = (struct vertex *) vertex_state;\n          init_vertex(*vertices);\n          return true;\n        }\n\n        static void apply_one_update(unsigned char *vertex_state,\n                                     unsigned char *update_stream,\n                                     per_processor_data *per_cpu_data,\n                                     bool loopback,\n                                     unsigned long bsp_phase) {\n          struct update *u = (struct update *) update_stream;\n          struct vertex *vertices = (struct vertex *) vertex_state;\n          struct vertex *v = &vertices[x_lib::configuration::map_offset(u->target)];\n\n          if (loopback)\n            bsp_phase++;\n\n          // In even phases gather to vector 0, in odd to vector 1\n          // This is required because scatter and loopback part of the gather happen simultaneously\n          int which = (bsp_phase % 2 == 0) ? 0 : 1;\n\n          if (bsp_phase <= niters) {\n            // Track how many updates (edges) have been processed\n            v->count++;\n\n            // Initialize data structures for this iteration - zero out feature vector\n            // and temp matrix since we'll be adding to them.\n            if (v->count == 1) {\n              zero_vector(v->feature_vec[which]);\n              zero_matrix(v->temp_mat);\n            }\n\n            // To compute the new feature vector of vertex v, we need to solve the system: A*feature_vec=b\n            // A is a matrix: A = O * O^T + D\n            // O is a submatrix of the other side of the graph where column vectors are feature vectors of\n            // those vertices that are connected to this vertex\n            // O^T is a transpose of O\n            // D is a diagonal matrix: D = lambda * degree * I, where I is an identity matrix\n            // b is a vector: b = O * r\n            // r is a ratings vector formed from the ratings of outgoing edges\n\n            // Calculating O*O^T and b\n            for (int i = 0; i < RANK; i++) {\n              v->feature_vec[which][i] += u->feature_vec[i] * u->rating;\n              for (int j = 0; j < RANK; j++) {\n                v->temp_mat[i][j] += u->feature_vec[i] * u->feature_vec[j];\n              }\n            }\n\n            // Additional procesing after all updates have been gathered\n            if (v->count == v->degree) {\n              // Adding D to A\n              for (int i = 0; i < RANK; i++) {\n                v->temp_mat[i][i] += LAMBDA * v->degree;\n              }\n\n              // Solve to get the new feature vector for the vertex\n              solve(v->temp_mat, v->feature_vec[which]);\n\n              // Reset count for the next iteration\n              v->count = 0;\n            }\n          }\n\n            // After all iterations are finished, we use one more phase to compute the sum of square errors.\n            // This is done only on one side (right) so we don't add the error twice.\n          else {\n            if (v->rightside) {\n              double sqerror = u->rating;\n              for (int i = 0; i < RANK; i++)\n                sqerror -= v->feature_vec[1 - which][i] * u->feature_vec[i];\n              sqerror *= sqerror;\n\n              static_cast<als_graphchi_per_processor_data *>(per_cpu_data)->sse_local += sqerror;\n            }\n          }\n        }\n\n        static bool generate_update(unsigned char *vertex_state,\n                                    unsigned char *edge_format,\n                                    unsigned char *update_stream,\n                                    per_processor_data *per_cpu_data,\n                                    unsigned long bsp_phase) {\n          vertex_t src, dst;\n          weight_t rating;\n          F::read_edge(edge_format, src, dst, rating);\n\n          struct vertex *vertices = (struct vertex *) vertex_state;\n          struct vertex *v = &vertices[x_lib::configuration::map_offset(src)];\n\n          // Iteration 0 is used to count the vertex degree and determine its side.\n          // The graph is bipartite, and it is assumed that lower ids form the left side.\n          if (bsp_phase == 0) {\n            v->rightside = (src > dst) ? true : false;\n            v->degree++;\n            return false;\n          }\n\n          // In even phases scatter to vector 0, in odd to vector 1\n          // This is required because scatter and loopback part of the gather happen simultaneously\n          int which = (bsp_phase % 2 == 0) ? 0 : 1;\n\n          // In the last iteration it is enough to send only the updates from the left side\n          if (bsp_phase < niters || (bsp_phase == niters && !v->rightside)) {\n            struct update *u = (struct update *) update_stream;\n            u->target = dst;\n            u->rating = (double) rating;\n            copy_vector(v->feature_vec[which], u->feature_vec);\n\n            // Continue processing in the next superstep\n            static_cast<als_graphchi_per_processor_data *>(per_cpu_data)->local_continue = true;\n            return true;\n          }\n          else\n            return false;\n        }\n\n        static void preprocessing() {\n          // The extra +1 is for the iteration 0 which is used just to compute the vertex degrees\n          niters = 1 + vm[\"als::niters\"].as < unsigned\n          long > ();\n        }\n\n        static void postprocessing() {\n          BOOST_LOG_TRIVIAL(info) << \"ALGORITHM::ALS::SSE \" << als_graphchi_per_processor_data::sse;\n          unsigned long nedges = pt.get < unsigned\n          long > (\"graph.edges\");\n          double rmse = std::sqrt(als_graphchi_per_processor_data::sse / (1. * nedges));\n          BOOST_LOG_TRIVIAL(info) << \"ALGORITHM::ALS::RMSE \" << rmse;\n        }\n\n        static per_processor_data *\n        create_per_processor_data(unsigned long processor_id) {\n          return new als_graphchi_per_processor_data();\n        }\n\n        static unsigned long min_super_phases() {\n          return 1;\n        }\n\n        static bool need_init(unsigned long bsp_phase) {\n          return (bsp_phase == 0);\n        }\n\n    };\n\n    // These should be in a cpp file, but it's ok since we only include\n    // this header once in driver.cpp\n    template<typename F>\n    unsigned long als_graphchi_factorization<F>::niters;\n\n    double als_graphchi_per_processor_data::sse = 0;\n\n  }\n}\n#endif\n", "meta": {"hexsha": "241d4ace946e6d1e2545f9affb9350fd4d36dc54", "size": 11446, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "algorithms/als/als_graphchi.hpp", "max_stars_repo_name": "epfl-labos/chaos", "max_stars_repo_head_hexsha": "5d091343f62393cb7dfc92a357e2fc7ef95d1855", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 55.0, "max_stars_repo_stars_event_min_datetime": "2015-10-22T22:45:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-28T12:55:20.000Z", "max_issues_repo_path": "algorithms/als/als_graphchi.hpp", "max_issues_repo_name": "epfl-labos/chaos", "max_issues_repo_head_hexsha": "5d091343f62393cb7dfc92a357e2fc7ef95d1855", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2016-04-21T12:56:21.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-07T00:58:41.000Z", "max_forks_repo_path": "algorithms/als/als_graphchi.hpp", "max_forks_repo_name": "epfl-labos/chaos", "max_forks_repo_head_hexsha": "5d091343f62393cb7dfc92a357e2fc7ef95d1855", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 21.0, "max_forks_repo_forks_event_min_datetime": "2015-11-09T08:07:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-28T12:55:45.000Z", "avg_line_length": 35.9937106918, "max_line_length": 108, "alphanum_fraction": 0.5648261401, "num_tokens": 2606, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.45484885161864563}}
{"text": "#include <array>\n\n#include <TMath.h>\n\n#include \"OscProbPMNS.hh\"\n#include <Eigen/Dense>\n\n#include \"OscillationVariables.hh\"\n#include \"PMNSVariables.hh\"\n#include \"TypesFunctions.hh\"\n#include \"Units.hh\"\n\n#include \"TypesFunctions.hh\"\n#include \"TypeClasses.hh\"\nusing namespace TypeClasses;\n\n#ifdef GNA_CUDA_SUPPORT\n#include \"cuOscProbPMNS.hh\"\n#endif\n\nusing namespace Eigen;\nusing NeutrinoUnits::oscprobArgumentFactor;\n\nOscProbPMNSBase::OscProbPMNSBase(Neutrino from, Neutrino to)\n  : m_param(new OscillationVariables(this)), m_pmns(new PMNSVariables(this))\n{\n  if (from.kind != to.kind) {\n    throw std::runtime_error(\"particle-antiparticle oscillations\");\n  }\n  m_alpha = from.flavor;\n  m_beta = to.flavor;\n  m_lepton_charge = from.leptonCharge();\n\n  for (size_t i = 0; i < m_pmns->Nnu; ++i) {\n    m_pmns->variable_(&m_pmns->V[m_alpha][i]);\n    m_pmns->variable_(&m_pmns->V[m_beta][i]);\n  }\n  m_param->variable_(\"DeltaMSq12\");\n  m_param->variable_(\"DeltaMSq13\");\n  m_param->variable_(\"DeltaMSq23\");\n}\n\ntemplate <>\ndouble OscProbPMNSBase::DeltaMSq<1,2>() const { return m_param->DeltaMSq12; }\n\ntemplate <>\ndouble OscProbPMNSBase::DeltaMSq<1,3>() const { return m_param->DeltaMSq13; }\n\ntemplate <>\ndouble OscProbPMNSBase::DeltaMSq<2,3>() const { return m_param->DeltaMSq23; }\n\ntemplate <int I, int J>\ndouble OscProbPMNSBase::weight() const {\n  return std::real(\n    m_pmns->V[m_alpha][I-1].complex()*\n    m_pmns->V[m_beta][J-1].complex()*\n    std::conj(m_pmns->V[m_alpha][J-1].complex())*\n    std::conj(m_pmns->V[m_beta][I-1].complex())\n    );\n}\n\ndouble OscProbPMNSBase::weightCP() const {\n  return m_lepton_charge*std::imag(\n    m_pmns->V[m_alpha][0].complex()*\n    m_pmns->V[m_beta][1].complex()*\n    std::conj(m_pmns->V[m_alpha][1].complex())*\n    std::conj(m_pmns->V[m_beta][0].complex())\n    );\n}\n\n\nOscProbAveraged::OscProbAveraged(Neutrino from, Neutrino to):\n    OscProbPMNSBase(from, to)\n{\n  transformation_(\"average_oscillations\")\n        .input(\"flux\")\n        .output(\"flux_averaged_osc\")\n        .types(TypesFunctions::pass<0>)\n        .func(&OscProbAveraged::CalcAverage);\n}\n\nvoid OscProbAveraged::CalcAverage(FunctionArgs fargs) {\n    double aver_weight = 1.0 - 2.0*(weight<1,2>() + weight<1,3>() + weight<2,3>());\n    fargs.rets[0].x = aver_weight * fargs.args[0].x;\n}\n\n\ntemplate<typename FloatType>\nGNA::GNAObjectTemplates::OscProbPMNST<FloatType>::OscProbPMNST(Neutrino from, Neutrino to, std::string l_name)\n  : OscProbPMNSBase(from, to)\n{\n  variable_(&m_L, l_name);\n  this->transformation_(\"comp12\")\n    .input(\"Enu\")\n    .output(\"comp12\")\n    .depends(m_L, m_param->DeltaMSq12)\n    .types(new PassTypeT<FloatType>(0, {0,-1}))\n    .func(&OscProbPMNST<FloatType>::calcComponent<1,2>)\n#ifdef GNA_CUDA_SUPPORT\n    .func(\"gpu\", &OscProbPMNST<FloatType>::gpuCalcComponent<1,2>, DataLocation::Device)\n    .storage(\"gpu\", [](StorageTypesFunctionArgs& fargs){\n      fargs.ints[0] = DataType().points().shape(fargs.args[0].size());\n    })\n#endif\n  ;\n  this->transformation_(\"comp13\")\n    .input(\"Enu\")\n    .output(\"comp13\")\n    .depends(m_L, m_param->DeltaMSq13)\n    .types(new PassTypeT<FloatType>(0, {0,-1}))\n    .func(&OscProbPMNST<FloatType>::calcComponent<1,3>)\n#ifdef GNA_CUDA_SUPPORT\n    .func(\"gpu\", &OscProbPMNST<FloatType>::gpuCalcComponent<1,3>, DataLocation::Device)\n    .storage(\"gpu\", [](StorageTypesFunctionArgs& fargs){\n      fargs.ints[0] = DataType().points().shape(fargs.args[0].size());\n    })\n#endif\n  ;\n  this->transformation_(\"comp23\")\n    .input(\"Enu\")\n    .output(\"comp23\")\n    .depends(m_L, m_param->DeltaMSq23)\n    .types(new PassTypeT<FloatType>(0, {0,-1}))\n    .func(&OscProbPMNST<FloatType>::calcComponent<2,3>)\n#ifdef GNA_CUDA_SUPPORT\n    .func(\"gpu\", &OscProbPMNST<FloatType>::gpuCalcComponent<2,3>, DataLocation::Device)\n    .storage(\"gpu\", [](StorageTypesFunctionArgs& fargs){\n      fargs.ints[0] = DataType().points().shape(fargs.args[0].size());\n    })\n#endif\n  ;\n  if (m_alpha != m_beta) {\n    this->transformation_(\"compCP\")\n      .input(\"Enu\")\n      .output(\"compCP\")\n      .depends(m_L)\n      .depends(m_param->DeltaMSq12, m_param->DeltaMSq13, m_param->DeltaMSq23)\n      .types(new PassTypeT<FloatType>(0, {0,-1}))\n      .func(&OscProbPMNST<FloatType>::calcComponentCP)\n#ifdef GNA_CUDA_SUPPORT\n      .func(\"gpu\", &OscProbPMNST<FloatType>::gpuCalcComponentCP, DataLocation::Device)\n      .storage(\"gpu\", [](StorageTypesFunctionArgs& fargs){\n        fargs.ints[0] = DataType().points().shape(fargs.args[0].size());\n      })\n#endif\n      ;\n  }\n  auto probsum = this->transformation_(\"probsum\")\n    .input(\"comp12\")\n    .input(\"comp13\")\n    .input(\"comp23\")\n    .input(\"comp0\")\n    .output(\"probsum\")\n    .types(new PassTypeT<FloatType>(0, {0,-1}))\n    .func(&OscProbPMNST<FloatType>::calcSum)\n#ifdef GNA_CUDA_SUPPORT\n    .func(\"gpu\", &OscProbPMNST<FloatType>::gpuCalcSum, DataLocation::Device)\n#endif\n    ;\n  if (from.flavor != to.flavor) {\n    probsum.input(\"compCP\");\n  }\n\n  this->transformation_(\"full_osc_prob\")\n      .input(\"Enu\")\n      .output(\"oscprob\")\n      .depends(m_L, m_param->DeltaMSq12, m_param->DeltaMSq13, m_param->DeltaMSq23)\n      .types(new PassTypeT<FloatType>(0, {0,-1}))\n      .func(&OscProbPMNST<FloatType>::calcFullProb);\n}\n\ntemplate<typename FloatType>\nvoid GNA::GNAObjectTemplates::OscProbPMNST<FloatType>::calcFullProb(FunctionArgs& fargs) {\n  auto& ret=fargs.rets[0].x;\n  auto& Enu = fargs.args[0].x;\n  ArrayXd tmp = (oscprobArgumentFactor*m_L*0.5)*Enu.inverse();\n  ArrayXd comp0(Enu);\n  comp0.setOnes();\n  ArrayXd comp12 = cos(DeltaMSq<1,2>()*tmp);\n  ArrayXd comp13 = cos(DeltaMSq<1,3>()*tmp);\n  ArrayXd comp23 = cos(DeltaMSq<2,3>()*tmp);\n  ArrayXd compCP(Enu);\n  compCP.setZero();\n  if (m_alpha != m_beta) {\n    compCP  = sin(DeltaMSq<1,2>()*tmp/2.);\n    compCP *= sin(DeltaMSq<1,3>()*tmp/2.);\n    compCP *= sin(DeltaMSq<2,3>()*tmp/2.);\n  }\n  ret  = 2.0*weight<1,2>()*comp12;\n  ret += 2.0*weight<1,3>()*comp13;\n  ret += 2.0*weight<2,3>()*comp23;\n  double coeff0 = - 2.0*(weight<1,2>() + weight<1,3>() + weight<2,3>());\n  if (m_alpha == m_beta) {\n    coeff0 += 1.0;\n  }\n  ret += coeff0*comp0;\n  if (m_alpha != m_beta) {\n    ret += 8.0*weightCP()*compCP;\n  }\n}\n\n\ntemplate<typename FloatType>\ntemplate <int I, int J>\nvoid GNA::GNAObjectTemplates::OscProbPMNST<FloatType>::calcComponent(FunctionArgs& fargs) {\n  auto &Enu = fargs.args[0].x;\n  fargs.rets[0].x = cos((DeltaMSq<I,J>()*oscprobArgumentFactor*m_L*0.5)*Enu.inverse());\n}\n\n#ifdef GNA_CUDA_SUPPORT\ntemplate<typename FloatType>\ntemplate < int I, int J>\nvoid GNA::GNAObjectTemplates::OscProbPMNST<FloatType>::gpuCalcComponent(FunctionArgs& fargs) {\n  fargs.args.touch();\n  auto& gpuargs=fargs.gpu;\n  gpuargs->provideSignatureDevice();\n  cuCalcComponent_modecos<double>(gpuargs->args, gpuargs->rets, gpuargs->ints, gpuargs->vars,\n\t\t                  fargs.args[0].arr.size(), gpuargs->nargs, oscprobArgumentFactor, DeltaMSq<I,J>(), m_L);\n}\n#endif\n\ntemplate<typename FloatType>\nvoid GNA::GNAObjectTemplates::OscProbPMNST<FloatType>::calcComponentCP(FunctionArgs& fargs) {\n  auto& ret=fargs.rets[0].x;\n  auto &Enu = fargs.args[0].x;\n  ArrayXd tmp = (oscprobArgumentFactor*m_L*0.25)*Enu.inverse();\n  ret = sin(DeltaMSq<1,2>()*tmp);\n  ret*= sin(DeltaMSq<1,3>()*tmp);\n  ret*= sin(DeltaMSq<2,3>()*tmp);\n}\n\n#ifdef GNA_CUDA_SUPPORT\ntemplate<typename FloatType>\nvoid GNA::GNAObjectTemplates::OscProbPMNST<FloatType>::gpuCalcComponentCP(FunctionArgs& fargs) {\n  fargs.args.touch();\n  auto& gpuargs=fargs.gpu;\n  gpuargs->provideSignatureDevice();\n  cuCalcComponentCP<double>(gpuargs->args, gpuargs->rets, gpuargs->ints, gpuargs->vars, m_param->DeltaMSq12, m_param->DeltaMSq13, m_param->DeltaMSq23,\n\t\t\t    fargs.args[0].arr.size(), gpuargs->nargs, oscprobArgumentFactor, m_L);\n}\n#endif\n\ntemplate<typename FloatType>\nvoid GNA::GNAObjectTemplates::OscProbPMNST<FloatType>::calcSum(FunctionArgs& fargs) {\n  auto& args=fargs.args;\n  auto& ret=fargs.rets[0].x;\n  auto weight12=weight<1,2>();\n  auto weight13=weight<1,3>();\n  auto weight23=weight<2,3>();\n  ret = 2.0*weight12*args[0].x;\n  ret+= 2.0*weight13*args[1].x;\n  ret+= 2.0*weight23*args[2].x;\n  double coeff0 = -2.0*(weight12+weight13+weight23);\n  if (m_alpha == m_beta) {\n    coeff0 += 1.0;\n  }\n  ret += coeff0*args[3].x;\n  if (m_alpha != m_beta) {\n    ret += 8.0*weightCP()*args[4].x;\n  }\n}\n#ifdef GNA_CUDA_SUPPORT\ntemplate<typename FloatType>\nvoid GNA::GNAObjectTemplates::OscProbPMNST<FloatType>::gpuCalcSum(FunctionArgs& fargs) {\n  fargs.args.touch();\n  auto& gpuargs=fargs.gpu;\n  cuCalcSum(gpuargs->args, gpuargs->rets, weight<1,2>(), weight<1,3>(), weight<2,3>() ,weightCP(), (m_alpha == m_beta), fargs.args[0].arr.size());\n}\n#endif\n\nOscProbPMNSMult::OscProbPMNSMult(Neutrino from, Neutrino to, std::string l_name)\n  : OscProbPMNSBase(from, to)\n{\n  if (m_alpha != m_beta) {\n    throw std::runtime_error(\"OscProbPMNSMult is only for survivals\");\n  }\n  variable_(&m_Lavg, l_name);\n  variable_(&m_weights, \"weights\");\n\n  transformation_(\"comp12\")\n    .input(\"Enu\")\n    .output(\"comp12\")\n    .depends(m_Lavg, m_param->DeltaMSq12)\n    .func(&OscProbPMNSMult::calcComponent<1,2>);\n  transformation_(\"comp13\")\n    .input(\"Enu\")\n    .output(\"comp13\")\n    .depends(m_Lavg, m_param->DeltaMSq13)\n    .func(&OscProbPMNSMult::calcComponent<1,3>);\n  transformation_(\"comp23\")\n    .input(\"Enu\")\n    .output(\"comp23\")\n    .depends(m_Lavg, m_param->DeltaMSq23)\n    .func(&OscProbPMNSMult::calcComponent<2,3>);\n  transformation_(\"probsum\")\n    .input(\"comp12\")\n    .input(\"comp13\")\n    .input(\"comp23\")\n    .input(\"comp0\")\n    .output(\"probsum\")\n    .types(TypesFunctions::pass<0>)\n    .func(&OscProbPMNSMult::calcSum);\n}\n\ntemplate <int I, int J>\nvoid OscProbPMNSMult::calcComponent(FunctionArgs fargs) {\n  auto& svalues=m_weights.values();\n  double s2 = svalues[0];\n  double s3 = svalues[1];\n  double s4 = svalues[2];\n  auto &Enu = fargs.args[0].x;\n  ArrayXd phi = (DeltaMSq<I,J>()*oscprobArgumentFactor*m_Lavg*0.25)*Enu.inverse();\n  ArrayXd phi2 = phi.square();\n  ArrayXd a = 1.0 - 2.0*s2*phi2 + 2.0/3.0*s4*phi2.square();\n  ArrayXd b = 1.0 - 2.0/3.0*s3*phi2;\n  fargs.rets[0].x = a*cos(2.0*b*phi);\n}\n\nvoid OscProbPMNSMult::calcSum(FunctionArgs fargs) {\n  auto& args=fargs.args;\n  auto& ret=fargs.rets[0].x;\n  ret = weight<1,2>()*args[0].x;\n  ret+= weight<1,3>()*args[1].x;\n  ret+= weight<2,3>()*args[2].x;\n  ret+= (1.0-weight<1,2>()-weight<1,3>()-weight<2,3>())*args[3].x;\n}\ntemplate class GNA::GNAObjectTemplates::OscProbPMNST<double>;\n#ifdef PROVIDE_SINGLE_PRECISION\n  //template class GNA::GNAObjectTemplates::OscProbPMNST<float>;\n#endif\n", "meta": {"hexsha": "536806976bfc27ea71bdfca73e97406f35101298", "size": 10494, "ext": "cc", "lang": "C++", "max_stars_repo_path": "transformations/neutrino/OscProbPMNS.cc", "max_stars_repo_name": "gnafit/gna", "max_stars_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-10-14T01:06:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-02T16:33:06.000Z", "max_issues_repo_path": "transformations/neutrino/OscProbPMNS.cc", "max_issues_repo_name": "gnafit/gna", "max_issues_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "transformations/neutrino/OscProbPMNS.cc", "max_forks_repo_name": "gnafit/gna", "max_forks_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_forks_repo_licenses": ["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.7039274924, "max_line_length": 150, "alphanum_fraction": 0.6744806556, "num_tokens": 3512, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4548488516186456}}
{"text": "/*\r\n *  Copyright 2011-2013 Maxim Milakov\r\n *\r\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  you may not use this file except in compliance with the License.\r\n *  You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n *  Unless required by applicable law or agreed to in writing, software\r\n *  distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  See the License for the specific language governing permissions and\r\n *  limitations under the License.\r\n */\r\n\r\n#include \"roc_result.h\"\r\n\r\n#include <boost/format.hpp>\r\n#include <algorithm>\r\n#include <numeric>\r\n\r\nnamespace nnforge\r\n{\r\n\troc_result::roc_result(\r\n\t\tconst output_neuron_value_set& predicted_value_set,\r\n\t\tconst output_neuron_value_set& actual_value_set,\r\n\t\tunsigned int segment_count,\r\n\t\tfloat min_val,\r\n\t\tfloat max_val)\r\n\t\t: segment_count(segment_count)\r\n\t\t, min_val(min_val)\r\n\t\t, max_val(max_val)\r\n\t\t, actual_positive_elem_count(0)\r\n\t\t, actual_negative_elem_count(0)\r\n\t\t, values_for_positive_elems(segment_count)\r\n\t\t, values_for_negative_elems(segment_count)\r\n\t{\r\n\t\tfloat mult = 1.0F / (max_val - min_val);\r\n\t\tfloat segment_count_f = static_cast<float>(segment_count);\r\n\t\tstd::vector<std::vector<float> >::const_iterator predicted_it = predicted_value_set.neuron_value_list.begin();\r\n\t\tfor(std::vector<std::vector<float> >::const_iterator actual_it = actual_value_set.neuron_value_list.begin();\r\n\t\t\tactual_it != actual_value_set.neuron_value_list.end();\r\n\t\t\tactual_it++, predicted_it++)\r\n\t\t{\r\n\t\t\tconst std::vector<float>& actual_value_list = *actual_it;\r\n\t\t\tconst std::vector<float>& predicted_value_list = *predicted_it;\r\n\r\n\t\t\tstd::vector<float>::const_iterator predicted_value_it = predicted_value_list.begin();\r\n\t\t\tfor(std::vector<float>::const_iterator actual_value_it = actual_value_list.begin();\r\n\t\t\t\tactual_value_it != actual_value_list.end();\r\n\t\t\t\tactual_value_it++, predicted_value_it++)\r\n\t\t\t{\r\n\t\t\t\tfloat actual_value = *actual_value_it;\r\n\t\t\t\tfloat predicted_value = *predicted_value_it;\r\n\r\n\t\t\t\tunsigned int bucket_id = std::min<unsigned int>(static_cast<unsigned int>(std::max<float>(std::min<float>((predicted_value - min_val) * mult, 1.0F), 0.0F) * segment_count_f), (segment_count - 1));\r\n\r\n\t\t\t\tif (actual_value > 0.0F)\r\n\t\t\t\t{\r\n\t\t\t\t\tvalues_for_positive_elems[bucket_id]++;\r\n\t\t\t\t\tactual_positive_elem_count++;\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tvalues_for_negative_elems[bucket_id]++;\r\n\t\t\t\t\tactual_negative_elem_count++;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tfloat roc_result::get_accuracy(float threshold) const\r\n\t{\r\n\t\tunsigned int starting_segment_id = static_cast<unsigned int>(std::max(std::min((threshold - min_val) / (max_val - min_val), 1.0F), 0.0F) * static_cast<float>(segment_count));\r\n\r\n\t\tunsigned int true_positive = std::accumulate(values_for_positive_elems.begin() + starting_segment_id, values_for_positive_elems.end(), 0);\r\n\t\tunsigned int true_negative = std::accumulate(values_for_negative_elems.begin(), values_for_negative_elems.begin() + starting_segment_id, 0);\r\n\r\n\t\treturn static_cast<float>(true_positive + true_negative) / static_cast<float>(actual_positive_elem_count + actual_negative_elem_count);\r\n\t}\r\n\r\n\tfloat roc_result::get_auc() const\r\n\t{\r\n\t\tstd::vector<float> true_positive_rates;\r\n\t\t{\r\n\t\t\tunsigned int current_positive_elems_count = 0;\r\n\t\t\tfloat mult = 1.0F / static_cast<float>(actual_positive_elem_count);\r\n\t\t\tfor(std::vector<unsigned int>::const_reverse_iterator it = values_for_positive_elems.rbegin(); it != values_for_positive_elems.rend(); ++it)\r\n\t\t\t{\r\n\t\t\t\tcurrent_positive_elems_count += *it;\r\n\t\t\t\ttrue_positive_rates.push_back(mult * static_cast<float>(current_positive_elems_count));\r\n\t\t\t}\r\n\t\t}\r\n\t\ttrue_positive_rates.push_back(1.0F);\r\n\r\n\t\tstd::vector<float> false_positive_rates;\r\n\t\t{\r\n\t\t\tunsigned int current_negative_elems_count = 0;\r\n\t\t\tfloat mult = 1.0F / static_cast<float>(actual_negative_elem_count);\r\n\t\t\tfor(std::vector<unsigned int>::const_reverse_iterator it = values_for_negative_elems.rbegin(); it != values_for_negative_elems.rend(); ++it)\r\n\t\t\t{\r\n\t\t\t\tcurrent_negative_elems_count += *it;\r\n\t\t\t\tfalse_positive_rates.push_back(mult * static_cast<float>(current_negative_elems_count));\r\n\t\t\t}\r\n\t\t}\r\n\t\tfalse_positive_rates.push_back(1.0F);\r\n\r\n\t\tfloat sum = 0.0F;\r\n\t\tfloat previous_fpr = 0.0F;\r\n\t\tfloat previous_tpr = 0.0F;\r\n\t\tstd::vector<float>::const_iterator tpr_it = true_positive_rates.begin();\r\n\t\tfor(std::vector<float>::const_iterator fpr_it = false_positive_rates.begin(); fpr_it != false_positive_rates.end(); ++fpr_it, ++tpr_it)\r\n\t\t{\r\n\t\t\tfloat current_fpr = *fpr_it;\r\n\t\t\tfloat current_tpr = *tpr_it;\r\n\r\n\t\t\tif (current_fpr != previous_fpr)\r\n\t\t\t\tsum += (current_fpr - previous_fpr) * (previous_tpr + current_tpr) * 0.5F;\r\n\r\n\t\t\tprevious_fpr = current_fpr;\r\n\t\t\tprevious_tpr = current_tpr;\r\n\t\t}\r\n\r\n\t\treturn sum;\r\n\t}\r\n\r\n\tstd::ostream& operator<< (std::ostream& out, const roc_result& val)\r\n\t{\r\n\t\tout << (boost::format(\"AUC %|1$.5f|\") % val.get_auc()).str();\r\n\r\n\t\treturn out;\r\n\t}\r\n}\r\n", "meta": {"hexsha": "d1a9a745ecb2f90ec0369c8d068065f9453162b4", "size": 5063, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "nnforge/roc_result.cpp", "max_stars_repo_name": "yanshanjing/nnForge", "max_stars_repo_head_hexsha": "6d2baa1174a90b8e5e8bf2a4b259ce8a37fbddf1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-02-19T15:51:55.000Z", "max_stars_repo_stars_event_max_datetime": "2015-02-19T15:51:55.000Z", "max_issues_repo_path": "nnforge/roc_result.cpp", "max_issues_repo_name": "yanshanjing/nnForge", "max_issues_repo_head_hexsha": "6d2baa1174a90b8e5e8bf2a4b259ce8a37fbddf1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nnforge/roc_result.cpp", "max_forks_repo_name": "yanshanjing/nnForge", "max_forks_repo_head_hexsha": "6d2baa1174a90b8e5e8bf2a4b259ce8a37fbddf1", "max_forks_repo_licenses": ["Apache-2.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.5037037037, "max_line_length": 201, "alphanum_fraction": 0.7167687142, "num_tokens": 1261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186768138228, "lm_q2_score": 0.5698526514141572, "lm_q1q2_score": 0.45484884614726634}}
{"text": "#include <ros/ros.h>\n#include <sensor_msgs/Image.h>\n#include <cv_bridge/cv_bridge.h>\n#include <pcl_ros/point_cloud.h>\n#include <pcl_conversions/pcl_conversions.h>\n#include <image_transport/image_transport.h>\n#include <pcl/point_types.h>\n#include <pcl/range_image/range_image_spherical.h>\n#include <pcl/filters/filter.h>\n#include <opencv2/core/core.hpp>\n#include <math.h>\n\n#include <sensor_msgs/Image.h>\n#include <sensor_msgs/PointCloud2.h>\n\n#include <message_filters/subscriber.h>\n#include <message_filters/time_synchronizer.h>\n#include <message_filters/synchronizer.h>\n#include <message_filters/sync_policies/approximate_time.h>\n\n#include <opencv2/highgui/highgui.hpp>\n#include <Eigen/Dense>\n\nusing namespace Eigen;\nusing namespace sensor_msgs;\nusing namespace message_filters;\nusing namespace std;\n\ntypedef pcl::PointCloud<pcl::PointXYZ> PointCloud;\nros::Publisher pcOnimg_pub;\nros::Publisher pub;\n\nfloat maxlen =10;\nfloat minlen = 0.1;\nfloat max_FOV = 1.6;\nfloat min_FOV = 0.9;\nstd::string imgTopic = \"/velodyne_points\";\nstd::string pcTopic = \"/camera/color/image_raw\";\n\nEigen::MatrixXf Tlc(3,1); // translation matrix lidar-camera\nEigen::MatrixXf Rlc(3,3); // rotation matrix lidar-camera\nEigen::MatrixXf Mc(3,4);  // camera calibration matrix\n\nvoid callback(const boost::shared_ptr<const sensor_msgs::PointCloud2>& in_pc2 , const ImageConstPtr& in_image)\n{\n\n\n    cv_bridge::CvImagePtr cv_ptr;\n        try\n        {\n          cv_ptr = cv_bridge::toCvCopy(in_image, sensor_msgs::image_encodings::BGR8);\n        }\n        catch (cv_bridge::Exception& e)\n        {\n          ROS_ERROR(\"cv_bridge exception: %s\", e.what());\n          return;\n        }\n\n  //Conversion from sensor_msgs::PointCloud2 to pcl::PointCloud<T>\n  pcl::PCLPointCloud2 pcl_pc2;\n  pcl_conversions::toPCL(*in_pc2,pcl_pc2);\n  pcl::PointCloud<pcl::PointXYZ>::Ptr msg_pointCloud(new pcl::PointCloud<pcl::PointXYZ>);\n  pcl::fromPCLPointCloud2(pcl_pc2,*msg_pointCloud);\n  ///\n\n  ////// filter point cloud\n  if (msg_pointCloud == NULL) return;\n\n  PointCloud::Ptr cloud_in (new PointCloud);\n  PointCloud::Ptr cloud_out (new PointCloud);\n\n  cloud_out->header.frame_id = \"velodyne\";\n  std::vector<int> indices;\n  pcl::removeNaNFromPointCloud(*msg_pointCloud, *cloud_in, indices);\n\n  for (int i = 0; i < (int) cloud_in->points.size(); i++)\n  {\n      double distance = sqrt(cloud_in->points[i].x * cloud_in->points[i].x + cloud_in->points[i].y * cloud_in->points[i].y);\n      if(distance<minlen || distance>maxlen || cloud_in->points[i].x<0)\n          continue;\n      float ang = ( atan (cloud_in->points[i].x/ cloud_in->points[i].y));\n      if(cloud_in->points[i].y<0)\n        ang = M_PI+ ang;\n      if (ang<min_FOV || ang> max_FOV)\n          continue;\n      cloud_out->push_back(cloud_in->points[i]);\n  }\n\n  Eigen::MatrixXf RTlc(4,4); // translation matrix lidar-camera\n  RTlc<<   Rlc(0), Rlc(3) , Rlc(6) ,Tlc(0)\n          ,Rlc(1), Rlc(4) , Rlc(7) ,Tlc(1)\n          ,Rlc(2), Rlc(5) , Rlc(8) ,Tlc(2)\n          ,0       , 0        , 0  , 1    ;\n\n  int sizeLidar = (int) cloud_out->points.size();\n  Eigen::MatrixXf Lidar_camera(3,sizeLidar);\n  Eigen::MatrixXf pointCloud_matrix(4,sizeLidar);\n\n  for (int i = 0; i < sizeLidar; i++)\n  {\n      pointCloud_matrix(0,i) = -cloud_out->points[i].y;\n      pointCloud_matrix(1,i) = -cloud_out->points[i].z;\n      pointCloud_matrix(2,i) = cloud_out->points[i].x;\n      pointCloud_matrix(3,i) = 1.0;\n  }\n\n  Lidar_camera = Mc * (RTlc * pointCloud_matrix);\n\n  int px_var = 0;\n  int py_var = 0;\n  unsigned int cols = in_image->width;\n  unsigned int rows = in_image->height;\n\n  for (int i=0;i<sizeLidar;i++)\n\n  {\n      px_var = (int)(Lidar_camera(0,i)/Lidar_camera(2,i));\n      py_var = (int)(Lidar_camera(1,i)/Lidar_camera(2,i));\n\n      if(px_var<0.0 || px_var>cols || py_var<0.0 || py_var>rows)\n          continue;\n      int color_dis_x = (int)(255*((cloud_out->points[i].x)/maxlen));\n      int color_dis_z = (int)(255*((cloud_out->points[i].x)/20.0));\n      if(color_dis_z>255)\n          color_dis_z = 255;\n\n      cv::circle(cv_ptr->image, cv::Point(px_var, py_var), 5, CV_RGB(255-color_dis_x,(int)(color_dis_z),color_dis_x),cv::FILLED);\n  }\n\n   pcOnimg_pub.publish(cv_ptr->toImageMsg());\n   pcl_conversions::toPCL(ros::Time::now(), cloud_out->header.stamp);\n   pub.publish (cloud_out);\n\n}\n\nint main(int argc, char** argv)\n{\n\n  ros::init(argc, argv, \"pontCloudOntImage\");\n  ros::NodeHandle nh;  \n\n  /// Load Parameters\n\n  nh.getParam(\"/maxlen\", maxlen);\n  nh.getParam(\"/minlen\", minlen);\n  nh.getParam(\"/max_ang_FOV\", max_FOV);\n  nh.getParam(\"/min_ang_FOV\", min_FOV);\n  nh.getParam(\"/pcTopic\", pcTopic);\n  nh.getParam(\"/imgTopic\", imgTopic);\n\n  XmlRpc::XmlRpcValue param;\n\n  nh.getParam(\"/matrix_file/tlc\", param);\n  Tlc <<  (double)param[0]\n         ,(double)param[1]\n         ,(double)param[2];\n\n  nh.getParam(\"/matrix_file/rlc\", param);\n\n\n  Rlc <<  (double)param[0] ,(double)param[1] ,(double)param[2]\n         ,(double)param[3] ,(double)param[4] ,(double)param[5]\n         ,(double)param[6] ,(double)param[7] ,(double)param[8];\n\n  nh.getParam(\"/matrix_file/camera_matrix\", param);\n\n  Mc  <<  (double)param[0] ,(double)param[1] ,(double)param[2] ,(double)param[3]\n         ,(double)param[4] ,(double)param[5] ,(double)param[6] ,(double)param[7]\n         ,(double)param[8] ,(double)param[9] ,(double)param[10],(double)param[11];\n\n  message_filters::Subscriber<PointCloud2> pc_sub(nh, pcTopic , 1);\n  message_filters::Subscriber<Image> img_sub(nh, imgTopic, 1);\n\n  typedef sync_policies::ApproximateTime<PointCloud2, Image> MySyncPolicy;\n  Synchronizer<MySyncPolicy> sync(MySyncPolicy(10), pc_sub, img_sub);\n  sync.registerCallback(boost::bind(&callback, _1, _2));\n  pcOnimg_pub = nh.advertise<sensor_msgs::Image>(\"/pcOnImage_image\", 1);\n\n  pub = nh.advertise<PointCloud> (\"/points2\", 1);\n\n  ros::spin();\n  //return 0;\n}\n", "meta": {"hexsha": "135ba5961678075cc7d599664da2920cbc8d1897", "size": 5818, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/pc_on_img.cpp", "max_stars_repo_name": "EPVelasco/pc_on_image", "max_stars_repo_head_hexsha": "7db4c8c5e1aed292f8f0063980eb1ec0a3452b01", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-09T17:07:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-09T17:07:42.000Z", "max_issues_repo_path": "src/pc_on_img.cpp", "max_issues_repo_name": "EPVelasco/pc_on_image", "max_issues_repo_head_hexsha": "7db4c8c5e1aed292f8f0063980eb1ec0a3452b01", "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/pc_on_img.cpp", "max_forks_repo_name": "EPVelasco/pc_on_image", "max_forks_repo_head_hexsha": "7db4c8c5e1aed292f8f0063980eb1ec0a3452b01", "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.6195652174, "max_line_length": 129, "alphanum_fraction": 0.667583362, "num_tokens": 1762, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186768138228, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.45484884614726623}}
{"text": "// Copyright \u00a9 2016-2021 Thomas Nagler and Thibault Vatter\n//\n// This file is part of the vinecopulib library and licensed under the terms of\n// the MIT license. For a copy, see the LICENSE file in the root directory of\n// vinecopulib or https://vinecopulib.github.io/vinecopulib/.\n//\n// Modified from https://github.com/elsid/bobyqa-cpp\n\n#pragma once\n\n#include <Eigen/Dense>\n#include <algorithm>\n#include <cmath>\n\nnamespace vinecopulib {\n\nnamespace tools_bobyqa {\n\nconstexpr double sqrt_2 = 1.41421356237309504880168872420969807;\nconstexpr double sqrt_0_5 = 1.0 / sqrt_2;\nconstexpr double one_plus_sqrt_2 = 1.0 + sqrt_2;\n\ninline constexpr double\nsquare(const double x)\n{\n  return x * x;\n}\n\ninline void\naltmov(const long n,\n       const long npt,\n       const double* xpt,\n       const double* const xopt,\n       const double* bmat,\n       const double* zmat,\n       const long ndim,\n       const double* const sl,\n       const double* const su,\n       const long kopt,\n       const long knew,\n       const double adelt,\n       double* const xnew,\n       double* const xalt,\n       double& alpha,\n       double& cauchy,\n       double* const glag,\n       double* const hcol,\n       double* const w)\n{\n  /* Local variables */\n  double gw, diff;\n  long ilbd, isbd;\n  double slbd;\n  long iubd;\n  double vlag, subd, temp;\n  long ksav = 0;\n  double step = 0, curv = 0;\n  long iflag;\n  double scale = 0, csave = 0, tempa = 0, tempb = 0, tempd = 0, sumin = 0,\n         ggfree = 0;\n  long ibdsav = 0;\n  double dderiv = 0, bigstp = 0, predsq = 0, presav = 0, distsq = 0, stpsav = 0,\n         wfixsq = 0, wsqsav = 0;\n\n  /*     The arguments N, NPT, XPT, XOPT, BMAT, ZMAT, NDIM, SL and SU all have\n   */\n  /*       the same meanings as the corresponding arguments of BOBYQB. */\n  /*     KOPT is the index of the optimal interpolation point. */\n  /*     KNEW is the index of the interpolation point that is going to be moved.\n   */\n  /*     ADELT is the current trust region bound. */\n  /*     XNEW will be set to a suitable new position for the interpolation point\n   */\n  /*       XPT(KNEW,.). Specifically, it satisfies the SL, SU and trust region\n   */\n  /*       bounds and it should provide a large denominator in the next call of\n   */\n  /*       UPDATE. The step XNEW-XOPT from XOPT is restricted to moves along the\n   */\n  /*       straight lines through XOPT and another interpolation point. */\n  /*     XALT also provides a large value of the modulus of the KNEW-th Lagrange\n   */\n  /*       function subject to the constraints that have been mentioned, its\n   * main */\n  /*       difference from XNEW being that XALT-XOPT is a constrained version of\n   */\n  /*       the Cauchy step within the trust region. An exception is that XALT is\n   */\n  /*       not calculated if all components of GLAG (see below) are zero. */\n  /*     ALPHA will be set to the KNEW-th diagonal element of the H matrix. */\n  /*     CAUCHY will be set to the square of the KNEW-th Lagrange function at */\n  /*       the step XALT-XOPT from XOPT for the vector XALT that is returned, */\n  /*       except that CAUCHY is set to zero if XALT is not calculated. */\n  /*     GLAG is a working space vector of length N for the gradient of the */\n  /*       KNEW-th Lagrange function at XOPT. */\n  /*     HCOL is a working space vector of length NPT for the second derivative\n   */\n  /*       coefficients of the KNEW-th Lagrange function. */\n  /*     W is a working space vector of length 2N that is going to hold the */\n  /*       constrained Cauchy step from XOPT of the Lagrange function, followed\n   */\n  /*       by the downhill version of XALT when the uphill step is calculated.\n   */\n\n  /*     Set the first NPT components of W to the leading elements of the */\n  /*     KNEW-th column of the H matrix. */\n\n  /* Parameter adjustments */\n  const long zmat_dim1 = npt;\n  const long zmat_offset = 1 + zmat_dim1;\n  zmat -= zmat_offset;\n  const long xpt_dim1 = npt;\n  const long xpt_offset = 1 + xpt_dim1;\n  xpt -= xpt_offset;\n  const long bmat_dim1 = ndim;\n  const long bmat_offset = 1 + bmat_dim1;\n  bmat -= bmat_offset;\n\n  /* Function Body */\n  for (long k = 1; k <= npt; ++k) {\n    hcol[k] = 0.0;\n  }\n  const long j_n = npt - n - 1;\n  for (long j = 1; j <= j_n; ++j) {\n    temp = zmat[knew + j * zmat_dim1];\n    for (long k = 1; k <= npt; ++k) {\n      hcol[k] += temp * zmat[k + j * zmat_dim1];\n    }\n  }\n  alpha = hcol[knew];\n  const double ha = 0.5 * alpha;\n\n  /*     Calculate the gradient of the KNEW-th Lagrange function at XOPT. */\n\n  for (long i = 1; i <= n; ++i) {\n    glag[i] = bmat[knew + i * bmat_dim1];\n  }\n  for (long k = 1; k <= npt; ++k) {\n    temp = 0.0;\n    for (long j = 1; j <= n; ++j) {\n      temp += xpt[k + j * xpt_dim1] * xopt[j];\n    }\n    temp = hcol[k] * temp;\n    for (long i = 1; i <= n; ++i) {\n      glag[i] += temp * xpt[k + i * xpt_dim1];\n    }\n  }\n\n  /*     Search for a large denominator along the straight lines through XOPT */\n  /*     and another interpolation point. SLBD and SUBD will be lower and upper\n   */\n  /*     bounds on the step along each of these lines in turn. PREDSQ will be */\n  /*     set to the square of the predicted denominator for each line. PRESAV */\n  /*     will be set to the largest admissible value of PREDSQ that occurs. */\n\n  presav = 0.0;\n  for (long k = 1; k <= npt; ++k) {\n    if (k == kopt) {\n      goto L80;\n    }\n    dderiv = 0.0;\n    distsq = 0.0;\n    for (long i = 1; i <= n; ++i) {\n      temp = xpt[k + i * xpt_dim1] - xopt[i];\n      dderiv += glag[i] * temp;\n      distsq += temp * temp;\n    }\n    subd = adelt / std::sqrt(distsq);\n    slbd = -subd;\n    ilbd = 0;\n    iubd = 0;\n    sumin = std::min(1.0, subd);\n\n    /*     Revise SLBD and SUBD if necessary because of the bounds in SL and SU.\n     */\n\n    for (long i = 1; i <= n; ++i) {\n      temp = xpt[k + i * xpt_dim1] - xopt[i];\n      if (temp > 0.0) {\n        if (slbd * temp < sl[i] - xopt[i]) {\n          slbd = (sl[i] - xopt[i]) / temp;\n          ilbd = -i;\n        }\n        if (subd * temp > su[i] - xopt[i]) {\n          subd = std::max(sumin, (su[i] - xopt[i]) / temp);\n          iubd = i;\n        }\n      } else if (temp < 0.0) {\n        if (slbd * temp > su[i] - xopt[i]) {\n          slbd = (su[i] - xopt[i]) / temp;\n          ilbd = i;\n        }\n        if (subd * temp < sl[i] - xopt[i]) {\n          subd = std::max(sumin, (sl[i] - xopt[i]) / temp);\n          iubd = -i;\n        }\n      }\n    }\n\n    /*     Seek a large modulus of the KNEW-th Lagrange function when the index\n     */\n    /*     of the other interpolation point on the line through XOPT is KNEW. */\n\n    if (k == knew) {\n      diff = dderiv - 1.0;\n      step = slbd;\n      vlag = slbd * (dderiv - slbd * diff);\n      isbd = ilbd;\n      temp = subd * (dderiv - subd * diff);\n      if (std::abs(temp) > std::abs(vlag)) {\n        step = subd;\n        vlag = temp;\n        isbd = iubd;\n      }\n      tempd = 0.5 * dderiv;\n      tempa = tempd - diff * slbd;\n      tempb = tempd - diff * subd;\n      if (tempa * tempb < 0.0) {\n        temp = tempd * tempd / diff;\n        if (std::abs(temp) > std::abs(vlag)) {\n          step = tempd / diff;\n          vlag = temp;\n          isbd = 0;\n        }\n      }\n\n      /*     Search along each of the other lines through XOPT and another\n       * point. */\n\n    } else {\n      step = slbd;\n      vlag = slbd * (1.0 - slbd);\n      isbd = ilbd;\n      temp = subd * (1.0 - subd);\n      if (std::abs(temp) > std::abs(vlag)) {\n        step = subd;\n        vlag = temp;\n        isbd = iubd;\n      }\n      if (subd > 0.5) {\n        if (std::abs(vlag) < .25) {\n          step = 0.5;\n          vlag = .25;\n          isbd = 0;\n        }\n      }\n      vlag *= dderiv;\n    }\n\n    /*     Calculate PREDSQ for the current line search and maintain PRESAV. */\n\n    temp = step * (1.0 - step) * distsq;\n    predsq = vlag * vlag * (vlag * vlag + ha * temp * temp);\n    if (predsq > presav) {\n      presav = predsq;\n      ksav = k;\n      stpsav = step;\n      ibdsav = isbd;\n    }\n  L80:;\n  }\n\n  /*     Construct XNEW in a way that satisfies the bound constraints exactly.\n   */\n\n  for (long i = 1; i <= n; ++i) {\n    temp = xopt[i] + stpsav * (xpt[ksav + i * xpt_dim1] - xopt[i]);\n    xnew[i] = std::max(sl[i], std::min(su[i], temp));\n  }\n  if (ibdsav < 0) {\n    xnew[-ibdsav] = sl[-ibdsav];\n  }\n  if (ibdsav > 0) {\n    xnew[ibdsav] = su[ibdsav];\n  }\n\n  /*     Prepare for the iterative method that assembles the constrained Cauchy\n   */\n  /*     step in W. The sum of squares of the fixed components of W is formed in\n   */\n  /*     WFIXSQ, and the free components of W are set to BIGSTP. */\n\n  bigstp = adelt + adelt;\n  iflag = 0;\nL100:\n  wfixsq = 0.0;\n  ggfree = 0.0;\n  for (long i = 1; i <= n; ++i) {\n    w[i] = 0.0;\n    tempa = std::min(xopt[i] - sl[i], glag[i]);\n    tempb = std::max(xopt[i] - su[i], glag[i]);\n    if (tempa > 0.0 || tempb < 0.0) {\n      w[i] = bigstp;\n      ggfree += square(glag[i]);\n    }\n  }\n  if (ggfree == 0.0) {\n    cauchy = 0.0;\n    goto L200;\n  }\n\n  /*     Investigate whether more components of W can be fixed. */\n\nL120:\n  temp = adelt * adelt - wfixsq;\n  if (temp > 0.0) {\n    wsqsav = wfixsq;\n    step = std::sqrt(temp / ggfree);\n    ggfree = 0.0;\n    for (long i = 1; i <= n; ++i) {\n      if (w[i] == bigstp) {\n        temp = xopt[i] - step * glag[i];\n        if (temp <= sl[i]) {\n          w[i] = sl[i] - xopt[i];\n          wfixsq += square(w[i]);\n        } else if (temp >= su[i]) {\n          w[i] = su[i] - xopt[i];\n          wfixsq += square(w[i]);\n        } else {\n          ggfree += square(glag[i]);\n        }\n      }\n    }\n    if (wfixsq > wsqsav && ggfree > 0.0) {\n      goto L120;\n    }\n  }\n\n  /*     Set the remaining free components of W and all components of XALT, */\n  /*     except that W may be scaled later. */\n\n  gw = 0.0;\n  for (long i = 1; i <= n; ++i) {\n    if (w[i] == bigstp) {\n      w[i] = -step * glag[i];\n      xalt[i] = std::max(sl[i], std::min(su[i], xopt[i] + w[i]));\n    } else if (w[i] == 0.0) {\n      xalt[i] = xopt[i];\n    } else if (glag[i] > 0.0) {\n      xalt[i] = sl[i];\n    } else {\n      xalt[i] = su[i];\n    }\n    gw += glag[i] * w[i];\n  }\n\n  /*     Set CURV to the curvature of the KNEW-th Lagrange function along W. */\n  /*     Scale W by a factor less than one if that can reduce the modulus of */\n  /*     the Lagrange function at XOPT+W. Set CAUCHY to the final value of */\n  /*     the square of this function. */\n\n  curv = 0.0;\n  for (long k = 1; k <= npt; ++k) {\n    temp = 0.0;\n    for (long j = 1; j <= n; ++j) {\n      temp += xpt[k + j * xpt_dim1] * w[j];\n    }\n    curv += hcol[k] * temp * temp;\n  }\n  if (iflag == 1) {\n    curv = -curv;\n  }\n  if (curv > -gw && curv < -one_plus_sqrt_2 * gw) {\n    scale = -gw / curv;\n    for (long i = 1; i <= n; ++i) {\n      temp = xopt[i] + scale * w[i];\n      xalt[i] = std::max(sl[i], std::min(su[i], temp));\n    }\n    cauchy = square(0.5 * gw * scale);\n  } else {\n    cauchy = square(gw + 0.5 * curv);\n  }\n\n  /*     If IFLAG is zero, then XALT is calculated as before after reversing */\n  /*     the sign of GLAG. Thus two XALT vectors become available. The one that\n   */\n  /*     is chosen is the one that gives the larger value of CAUCHY. */\n\n  if (iflag == 0) {\n    for (long i = 1; i <= n; ++i) {\n      glag[i] = -glag[i];\n      w[n + i] = xalt[i];\n    }\n    csave = cauchy;\n    iflag = 1;\n    goto L100;\n  }\n  if (csave > cauchy) {\n    for (long i = 1; i <= n; ++i) {\n      xalt[i] = w[n + i];\n    }\n    cauchy = csave;\n  }\nL200:;\n}\n\ntemplate<class Function>\nvoid\nprelim(const Function& function,\n       const long n,\n       const long npt,\n       double* const x,\n       const double* const xl,\n       const double* const xu,\n       const double rhobeg,\n       const long maxfun,\n       double* const xbase,\n       double* xpt,\n       double* const fval,\n       double* const gopt,\n       double* const hq,\n       double* const pq,\n       double* bmat,\n       double* zmat,\n       const long ndim,\n       const double* const sl,\n       const double* const su,\n       long& nf,\n       long& kopt)\n{\n  /* Local variables */\n  long nfm;\n  long nfx = 0, ipt = 0, jpt = 0;\n  double fbeg = 0, diff = 0, temp = 0, stepa = 0, stepb = 0;\n  long itemp;\n\n  /*     The arguments N, NPT, X, XL, XU, RHOBEG, IPRINT and MAXFUN are the */\n  /*       same as the corresponding arguments in SUBROUTINE BOBYQA. */\n  /*     The arguments XBASE, XPT, FVAL, HQ, PQ, BMAT, ZMAT, NDIM, SL and SU */\n  /*       are the same as the corresponding arguments in BOBYQB, the elements\n   */\n  /*       of SL and SU being set in BOBYQA. */\n  /*     GOPT is usually the gradient of the quadratic model at XOPT+XBASE, but\n   */\n  /*       it is set by PRELIM to the gradient of the quadratic model at XBASE.\n   */\n  /*       If XOPT is nonzero, BOBYQB will change it to its usual value later.\n   */\n  /*     NF is maintaned as the number of calls of CALFUN so far. */\n  /*     KOPT will be such that the least calculated value of F so far is at */\n  /*       the point XPT(KOPT,.)+XBASE in the space of the variables. */\n\n  /*     SUBROUTINE PRELIM sets the elements of XBASE, XPT, FVAL, GOPT, HQ, PQ,\n   */\n  /*     BMAT and ZMAT for the first iteration, and it maintains the values of\n   */\n  /*     NF and KOPT. The vector X is also changed by PRELIM. */\n\n  /*     Set some constants. */\n\n  /* Parameter adjustments */\n  const long zmat_dim1 = npt;\n  const long zmat_offset = 1 + zmat_dim1;\n  zmat -= zmat_offset;\n  const long xpt_dim1 = npt;\n  const long xpt_offset = 1 + xpt_dim1;\n  xpt -= xpt_offset;\n  const long bmat_dim1 = ndim;\n  const long bmat_offset = 1 + bmat_dim1;\n  bmat -= bmat_offset;\n\n  /* Function Body */\n  const double rhosq = rhobeg * rhobeg;\n  const double recip = 1.0 / rhosq;\n  const long np = n + 1;\n\n  /*     Set XBASE to the initial vector of variables, and set the initial */\n  /*     elements of XPT, BMAT, HQ, PQ and ZMAT to zero. */\n\n  for (long j = 1; j <= n; ++j) {\n    xbase[j] = x[j];\n    for (long k = 1; k <= npt; ++k) {\n      xpt[k + j * xpt_dim1] = 0.0;\n    }\n    for (long i = 1; i <= ndim; ++i) {\n      bmat[i + j * bmat_dim1] = 0.0;\n    }\n  }\n  const long ih_n = n * np / 2;\n  for (long ih = 1; ih <= ih_n; ++ih) {\n    hq[ih] = 0.0;\n  }\n  for (long k = 1; k <= npt; ++k) {\n    pq[k] = 0.0;\n    const long j_n = npt - np;\n    for (long j = 1; j <= j_n; ++j) {\n      zmat[k + j * zmat_dim1] = 0.0;\n    }\n  }\n\n  /*     Begin the initialization procedure. NF becomes one more than the number\n   */\n  /*     of function values so far. The coordinates of the displacement of the\n   */\n  /*     next initial interpolation point from XBASE are set in XPT(NF+1,.). */\n\n  nf = 0;\nL50:\n  nfm = nf;\n  nfx = nf - n;\n  ++(nf);\n  if (nfm <= n << 1) {\n    if (nfm >= 1 && nfm <= n) {\n      stepa = rhobeg;\n      if (su[nfm] == 0.0) {\n        stepa = -stepa;\n      }\n      xpt[nf + nfm * xpt_dim1] = stepa;\n    } else if (nfm > n) {\n      stepa = xpt[nf - n + nfx * xpt_dim1];\n      stepb = -(rhobeg);\n      if (sl[nfx] == 0.0) {\n        stepb = std::min(2.0 * rhobeg, su[nfx]);\n      }\n      if (su[nfx] == 0.0) {\n        stepb = std::max(-2.0 * rhobeg, sl[nfx]);\n      }\n      xpt[nf + nfx * xpt_dim1] = stepb;\n    }\n  } else {\n    itemp = (nfm - np) / n;\n    jpt = nfm - itemp * n - n;\n    ipt = jpt + itemp;\n    if (ipt > n) {\n      itemp = jpt;\n      jpt = ipt - n;\n      ipt = itemp;\n    }\n    xpt[nf + ipt * xpt_dim1] = xpt[ipt + 1 + ipt * xpt_dim1];\n    xpt[nf + jpt * xpt_dim1] = xpt[jpt + 1 + jpt * xpt_dim1];\n  }\n\n  /*     Calculate the next value of F. The least function value so far and */\n  /*     its index are required. */\n\n  for (long j = 1; j <= n; ++j) {\n    x[j] = std::min(std::max(xl[j], xbase[j] + xpt[nf + j * xpt_dim1]), xu[j]);\n    if (xpt[nf + j * xpt_dim1] == sl[j]) {\n      x[j] = xl[j];\n    }\n    if (xpt[nf + j * xpt_dim1] == su[j]) {\n      x[j] = xu[j];\n    }\n  }\n  const double f = function(n, x + 1);\n  fval[nf] = f;\n  if (nf == 1) {\n    fbeg = f;\n    kopt = 1;\n  } else if (f < fval[kopt]) {\n    kopt = nf;\n  }\n\n  /*     Set the nonzero initial elements of BMAT and the quadratic model in the\n   */\n  /*     cases when NF is at most 2*N+1. If NF exceeds N+1, then the positions\n   */\n  /*     of the NF-th and (NF-N)-th interpolation points may be switched, in */\n  /*     order that the function value at the first of them contributes to the\n   */\n  /*     off-diagonal second derivative terms of the initial quadratic model. */\n\n  if (nf <= (n << 1) + 1) {\n    if (nf >= 2 && nf <= n + 1) {\n      gopt[nfm] = (f - fbeg) / stepa;\n      if (npt < nf + n) {\n        bmat[nfm * bmat_dim1 + 1] = -1.0 / stepa;\n        bmat[nf + nfm * bmat_dim1] = 1.0 / stepa;\n        bmat[npt + nfm + nfm * bmat_dim1] = -0.5 * rhosq;\n      }\n    } else if (nf >= n + 2) {\n      long ih = nfx * (nfx + 1) / 2;\n      temp = (f - fbeg) / stepb;\n      diff = stepb - stepa;\n      hq[ih] = 2.0 * (temp - gopt[nfx]) / diff;\n      gopt[nfx] = (gopt[nfx] * stepb - temp * stepa) / diff;\n      if (stepa * stepb < 0.0) {\n        if (f < fval[nf - n]) {\n          fval[nf] = fval[nf - n];\n          fval[nf - n] = f;\n          if (kopt == nf) {\n            kopt = nf - n;\n          }\n          xpt[nf - n + nfx * xpt_dim1] = stepb;\n          xpt[nf + nfx * xpt_dim1] = stepa;\n        }\n      }\n      bmat[nfx * bmat_dim1 + 1] = -(stepa + stepb) / (stepa * stepb);\n      bmat[nf + nfx * bmat_dim1] = -0.5 / xpt[nf - n + nfx * xpt_dim1];\n      bmat[nf - n + nfx * bmat_dim1] =\n        -bmat[nfx * bmat_dim1 + 1] - bmat[nf + nfx * bmat_dim1];\n      zmat[nfx * zmat_dim1 + 1] = sqrt_2 / (stepa * stepb);\n      zmat[nf + nfx * zmat_dim1] = sqrt_0_5 / rhosq;\n      zmat[nf - n + nfx * zmat_dim1] =\n        -zmat[nfx * zmat_dim1 + 1] - zmat[nf + nfx * zmat_dim1];\n    }\n\n    /*     Set the off-diagonal second derivatives of the Lagrange functions and\n     */\n    /*     the initial quadratic model. */\n\n  } else {\n    long ih = ipt * (ipt - 1) / 2 + jpt;\n    zmat[nfx * zmat_dim1 + 1] = recip;\n    zmat[nf + nfx * zmat_dim1] = recip;\n    zmat[ipt + 1 + nfx * zmat_dim1] = -recip;\n    zmat[jpt + 1 + nfx * zmat_dim1] = -recip;\n    temp = xpt[nf + ipt * xpt_dim1] * xpt[nf + jpt * xpt_dim1];\n    hq[ih] = (fbeg - fval[ipt + 1] - fval[jpt + 1] + f) / temp;\n  }\n  if (nf < npt && nf < maxfun) {\n    goto L50;\n  }\n}\n\ninline double\nless_abs(double lhs, double rhs)\n{\n  return std::abs(lhs) < std::abs(rhs);\n}\n\ninline void\nupdate(const long n,\n       const long npt,\n       double* bmat,\n       double* zmat,\n       const long ndim,\n       double* const vlag,\n       const double beta,\n       const double denom,\n       const long knew,\n       double* const w)\n{\n  /*     The arrays BMAT and ZMAT are updated, as required by the new position\n   */\n  /*     of the interpolation point that has the index KNEW. The vector VLAG has\n   */\n  /*     N+NPT components, set on entry to the first NPT and last N components\n   */\n  /*     of the product Hw in equation (4.11) of the Powell (2006) paper on */\n  /*     NEWUOA. Further, BETA is set on entry to the value of the parameter */\n  /*     with that name, and DENOM is set to the denominator of the updating */\n  /*     formula. Elements of ZMAT may be treated as zero if their moduli are */\n  /*     at most ZTEST. The first NDIM elements of W are used for working space.\n   */\n\n  /*     Set some constants. */\n\n  /* Parameter adjustments */\n  const long zmat_dim1 = npt;\n  const long zmat_offset = 1 + zmat_dim1;\n  zmat -= zmat_offset;\n  const long bmat_dim1 = ndim;\n  const long bmat_offset = 1 + bmat_dim1;\n  bmat -= bmat_offset;\n\n  /* Function Body */\n  const long nptm = npt - n - 1;\n  const auto zmat_end = zmat + zmat_offset + nptm * npt;\n  const auto zmat_max =\n    std::max_element(zmat + zmat_offset, zmat_end, less_abs);\n  const double ztest = zmat_max == zmat_end ? 0 : *zmat_max * 1e-20;\n\n  /*     Apply the rotations that put zeros in the KNEW-th row of ZMAT. */\n\n  for (long j = 2; j <= nptm; ++j) {\n    if (std::abs(zmat[knew + j * zmat_dim1]) > ztest) {\n      double temp =\n        std::hypot(zmat[knew + zmat_dim1], zmat[knew + j * zmat_dim1]);\n      const double tempa = zmat[knew + zmat_dim1] / temp;\n      const double tempb = zmat[knew + j * zmat_dim1] / temp;\n      for (long i = 1; i <= npt; ++i) {\n        temp = tempa * zmat[i + zmat_dim1] + tempb * zmat[i + j * zmat_dim1];\n        zmat[i + j * zmat_dim1] =\n          tempa * zmat[i + j * zmat_dim1] - tempb * zmat[i + zmat_dim1];\n        zmat[i + zmat_dim1] = temp;\n      }\n    }\n    zmat[knew + j * zmat_dim1] = 0.0;\n  }\n\n  /*     Put the first NPT components of the KNEW-th column of HLAG into W, */\n  /*     and calculate the parameters of the updating formula. */\n\n  for (long i = 1; i <= npt; ++i) {\n    w[i] = zmat[knew + zmat_dim1] * zmat[i + zmat_dim1];\n  }\n  const double alpha = w[knew];\n  const double tau = vlag[knew];\n  vlag[knew] -= 1.0;\n\n  /*     Complete the updating of ZMAT. */\n  const double temp = std::sqrt(denom);\n  double tempb = zmat[knew + zmat_dim1] / temp;\n  double tempa = tau / temp;\n  for (long i = 1; i <= npt; ++i) {\n    zmat[i + zmat_dim1] = tempa * zmat[i + zmat_dim1] - tempb * vlag[i];\n  }\n\n  /*     Finally, update the matrix BMAT. */\n\n  for (long j = 1; j <= n; ++j) {\n    const long jp = npt + j;\n    w[jp] = bmat[knew + j * bmat_dim1];\n    tempa = (alpha * vlag[jp] - tau * w[jp]) / denom;\n    tempb = (-(beta)*w[jp] - tau * vlag[jp]) / denom;\n    for (long i = 1; i <= jp; ++i) {\n      bmat[i + j * bmat_dim1] =\n        bmat[i + j * bmat_dim1] + tempa * vlag[i] + tempb * w[i];\n      if (i > npt) {\n        bmat[jp + (i - npt) * bmat_dim1] = bmat[i + j * bmat_dim1];\n      }\n    }\n  }\n}\n\ninline void\ntrsbox(const long n,\n       const long npt,\n       const double* xpt,\n       const double* const xopt,\n       const double* const gopt,\n       const double* const hq,\n       const double* const pq,\n       const double* const sl,\n       const double* const su,\n       const double delta,\n       double* const xnew,\n       double* const d,\n       double* const gnew,\n       double* const xbdi,\n       double* const s,\n       double* const hs,\n       double* const hred,\n       double* const dsq,\n       double* const crvmin)\n{\n  /* Local variables */\n  double ds;\n  long iu;\n  double dhd, dhs, cth, shs, sth, ssq, beta, sdec, blen;\n  long iact = 0, nact = 0;\n  double angt, qred;\n  long isav;\n  double temp = 0, xsav = 0, xsum = 0, angbd = 0, dredg = 0, sredg = 0;\n  long iterc;\n  double resid = 0, delsq = 0, ggsav = 0, tempa = 0, tempb = 0, redmax = 0,\n         dredsq = 0, redsav = 0, gredsq = 0, rednew = 0;\n  long itcsav = 0;\n  double rdprev = 0, rdnext = 0, stplen = 0, stepsq = 0;\n  long itermax = 0;\n\n  /*     The arguments N, NPT, XPT, XOPT, GOPT, HQ, PQ, SL and SU have the same\n   */\n  /*       meanings as the corresponding arguments of BOBYQB. */\n  /*     DELTA is the trust region radius for the present calculation, which */\n  /*       seeks a small value of the quadratic model within distance DELTA of\n   */\n  /*       XOPT subject to the bounds on the variables. */\n  /*     XNEW will be set to a new vector of variables that is approximately */\n  /*       the one that minimizes the quadratic model within the trust region */\n  /*       subject to the SL and SU constraints on the variables. It satisfies\n   */\n  /*       as equations the bounds that become active during the calculation. */\n  /*     D is the calculated trial step from XOPT, generated iteratively from an\n   */\n  /*       initial value of zero. Thus XNEW is XOPT+D after the final iteration.\n   */\n  /*     GNEW holds the gradient of the quadratic model at XOPT+D. It is updated\n   */\n  /*       when D is updated. */\n  /*     XBDI is a working space vector. For I=1,2,...,N, the element XBDI(I) is\n   */\n  /*       set to -1.0, 0.0, or 1.0, the value being nonzero if and only if the\n   */\n  /*       I-th variable has become fixed at a bound, the bound being SL(I) or\n   */\n  /*       SU(I) in the case XBDI(I)=-1.0 or XBDI(I)=1.0, respectively. This */\n  /*       information is accumulated during the construction of XNEW. */\n  /*     The arrays S, HS and HRED are also used for working space. They hold\n   * the */\n  /*       current search direction, and the changes in the gradient of Q along\n   * S */\n  /*       and the reduced D, respectively, where the reduced D is the same as\n   * D, */\n  /*       except that the components of the fixed variables are zero. */\n  /*     DSQ will be set to the square of the length of XNEW-XOPT. */\n  /*     CRVMIN is set to zero if D reaches the trust region boundary. Otherwise\n   */\n  /*       it is set to the least curvature of H that occurs in the conjugate */\n  /*       gradient searches that are not restricted by any constraints. The */\n  /*       value CRVMIN=-1.0D0 is set, however, if all of these searches are */\n  /*       constrained. */\n\n  /*     A version of the truncated conjugate gradient is applied. If a line */\n  /*     search is restricted by a constraint, then the procedure is restarted,\n   */\n  /*     the values of the variables that are at their bounds being fixed. If */\n  /*     the trust region boundary is reached, then further changes may be made\n   */\n  /*     to D, each one being in the two dimensional space that is spanned */\n  /*     by the current D and the gradient of Q at XOPT+D, staying on the trust\n   */\n  /*     region boundary. Termination occurs when the reduction in Q seems to */\n  /*     be close to the greatest reduction that can be achieved. */\n\n  /*     Set some constants. */\n\n  /* Parameter adjustments */\n  const long xpt_dim1 = npt;\n  const long xpt_offset = 1 + xpt_dim1;\n  xpt -= xpt_offset;\n\n  /* Function Body */\n\n  /*     The sign of GOPT(I) gives the sign of the change to the I-th variable\n   */\n  /*     that will reduce Q from its value at XOPT. Thus XBDI(I) shows whether\n   */\n  /*     or not to fix the I-th variable at one of its bounds initially, with */\n  /*     NACT being set to the number of fixed variables. D and GNEW are also */\n  /*     set for the first iteration. DELSQ is the upper bound on the sum of */\n  /*     squares of the free variables. QRED is the reduction in Q so far. */\n\n  iterc = 0;\n  nact = 0;\n  for (long i = 1; i <= n; ++i) {\n    xbdi[i] = 0.0;\n    if (xopt[i] <= sl[i]) {\n      if (gopt[i] >= 0.0) {\n        xbdi[i] = -1.0;\n      }\n    } else if (xopt[i] >= su[i]) {\n      if (gopt[i] <= 0.0) {\n        xbdi[i] = 1.0;\n      }\n    }\n    if (xbdi[i] != 0.0) {\n      ++nact;\n    }\n    d[i] = 0.0;\n    gnew[i] = gopt[i];\n  }\n  delsq = delta * delta;\n  qred = 0.0;\n  *crvmin = -1.0;\n\n  /*     Set the next search direction of the conjugate gradient method. It is\n   */\n  /*     the steepest descent direction initially and when the iterations are */\n  /*     restarted because a variable has just been fixed by a bound, and of */\n  /*     course the components of the fixed variables are zero. ITERMAX is an */\n  /*     upper bound on the indices of the conjugate gradient iterations. */\n\nL20:\n  beta = 0.0;\nL30:\n  stepsq = 0.0;\n  for (long i = 1; i <= n; ++i) {\n    if (xbdi[i] != 0.0) {\n      s[i] = 0.0;\n    } else if (beta == 0.0) {\n      s[i] = -gnew[i];\n    } else {\n      s[i] = beta * s[i] - gnew[i];\n    }\n    stepsq += square(s[i]);\n  }\n  if (stepsq == 0.0) {\n    goto L190;\n  }\n  if (beta == 0.0) {\n    gredsq = stepsq;\n    itermax = iterc + n - nact;\n  }\n  if (gredsq * delsq <= qred * 1e-4 * qred) {\n    goto L190;\n  }\n\n  /*     Multiply the search direction by the second derivative matrix of Q and\n   */\n  /*     calculate some scalars for the choice of steplength. Then set BLEN to\n   */\n  /*     the length of the the step to the trust region boundary and STPLEN to\n   */\n  /*     the steplength, ignoring the simple bounds. */\n\n  goto L210;\nL50:\n  resid = delsq;\n  ds = 0.0;\n  shs = 0.0;\n  for (long i = 1; i <= n; ++i) {\n    if (xbdi[i] == 0.0) {\n      resid -= square(d[i]);\n      ds += s[i] * d[i];\n      shs += s[i] * hs[i];\n    }\n  }\n  if (resid <= 0.0) {\n    goto L90;\n  }\n  temp = std::sqrt(stepsq * resid + ds * ds);\n  if (ds < 0.0) {\n    blen = (temp - ds) / stepsq;\n  } else {\n    blen = resid / (temp + ds);\n  }\n  stplen = blen;\n  if (shs > 0.0) {\n    stplen = std::min(blen, gredsq / shs);\n  }\n\n  /*     Reduce STPLEN if necessary in order to preserve the simple bounds, */\n  /*     letting IACT be the index of the new constrained variable. */\n\n  iact = 0;\n  for (long i = 1; i <= n; ++i) {\n    if (s[i] != 0.0) {\n      xsum = xopt[i] + d[i];\n      if (s[i] > 0.0) {\n        temp = (su[i] - xsum) / s[i];\n      } else {\n        temp = (sl[i] - xsum) / s[i];\n      }\n      if (temp < stplen) {\n        stplen = temp;\n        iact = i;\n      }\n    }\n  }\n\n  /*     Update CRVMIN, GNEW and D. Set SDEC to the decrease that occurs in Q.\n   */\n\n  sdec = 0.0;\n  if (stplen > 0.0) {\n    ++iterc;\n    temp = shs / stepsq;\n    if (iact == 0 && temp > 0.0) {\n      *crvmin = std::min(*crvmin, temp);\n      if (*crvmin == -1.0) {\n        *crvmin = temp;\n      }\n    }\n    ggsav = gredsq;\n    gredsq = 0.0;\n    for (long i = 1; i <= n; ++i) {\n      gnew[i] += stplen * hs[i];\n      if (xbdi[i] == 0.0) {\n        gredsq += square(gnew[i]);\n      }\n      d[i] += stplen * s[i];\n    }\n    sdec = std::max(stplen * (ggsav - 0.5 * stplen * shs), 0.0);\n    qred += sdec;\n  }\n\n  /*     Restart the conjugate gradient method if it has hit a new bound. */\n\n  if (iact > 0) {\n    ++nact;\n    xbdi[iact] = 1.0;\n    if (s[iact] < 0.0) {\n      xbdi[iact] = -1.0;\n    }\n    delsq -= square(d[iact]);\n    if (delsq <= 0.0) {\n      goto L90;\n    }\n    goto L20;\n  }\n\n  /*     If STPLEN is less than BLEN, then either apply another conjugate */\n  /*     gradient iteration or RETURN. */\n\n  if (stplen < blen) {\n    if (iterc == itermax) {\n      goto L190;\n    }\n    if (sdec <= qred * .01) {\n      goto L190;\n    }\n    beta = gredsq / ggsav;\n    goto L30;\n  }\nL90:\n  *crvmin = 0.0;\n\n  /*     Prepare for the alternative iteration by calculating some scalars */\n  /*     and by multiplying the reduced D by the second derivative matrix of */\n  /*     Q, where S holds the reduced D in the call of GGMULT. */\n\nL100:\n  if (nact >= n - 1) {\n    goto L190;\n  }\n  dredsq = 0.0;\n  dredg = 0.0;\n  gredsq = 0.0;\n  for (long i = 1; i <= n; ++i) {\n    if (xbdi[i] == 0.0) {\n      dredsq += square(d[i]);\n      dredg += d[i] * gnew[i];\n      gredsq += square(gnew[i]);\n      s[i] = d[i];\n    } else {\n      s[i] = 0.0;\n    }\n  }\n  itcsav = iterc;\n  goto L210;\n\n  /*     Let the search direction S be a linear combination of the reduced D */\n  /*     and the reduced G that is orthogonal to the reduced D. */\n\nL120:\n  ++iterc;\n  temp = gredsq * dredsq - dredg * dredg;\n  if (temp <= qred * 1e-4 * qred) {\n    goto L190;\n  }\n  temp = std::sqrt(temp);\n  for (long i = 1; i <= n; ++i) {\n    if (xbdi[i] == 0.0) {\n      s[i] = (dredg * d[i] - dredsq * gnew[i]) / temp;\n    } else {\n      s[i] = 0.0;\n    }\n  }\n  sredg = -temp;\n\n  /*     By considering the simple bounds on the variables, calculate an upper\n   */\n  /*     bound on the tangent of half the angle of the alternative iteration, */\n  /*     namely ANGBD, except that, if already a free variable has reached a */\n  /*     bound, there is a branch back to label 100 after fixing that variable.\n   */\n\n  angbd = 1.0;\n  iact = 0;\n  for (long i = 1; i <= n; ++i) {\n    if (xbdi[i] == 0.0) {\n      tempa = xopt[i] + d[i] - sl[i];\n      tempb = su[i] - xopt[i] - d[i];\n      if (tempa <= 0.0) {\n        ++nact;\n        xbdi[i] = -1.0;\n        goto L100;\n      } else if (tempb <= 0.0) {\n        ++nact;\n        xbdi[i] = 1.0;\n        goto L100;\n      }\n      ssq = square(d[i]) + square(s[i]);\n      temp = ssq - square(xopt[i] - sl[i]);\n      if (temp > 0.0) {\n        temp = std::sqrt(temp) - s[i];\n        if (angbd * temp > tempa) {\n          angbd = tempa / temp;\n          iact = i;\n          xsav = -1.0;\n        }\n      }\n      temp = ssq - square(su[i] - xopt[i]);\n      if (temp > 0.0) {\n        temp = std::sqrt(temp) + s[i];\n        if (angbd * temp > tempb) {\n          angbd = tempb / temp;\n          iact = i;\n          xsav = 1.0;\n        }\n      }\n    }\n  }\n\n  /*     Calculate HHD and some curvatures for the alternative iteration. */\n\n  goto L210;\nL150:\n  shs = 0.0;\n  dhs = 0.0;\n  dhd = 0.0;\n  for (long i = 1; i <= n; ++i) {\n    if (xbdi[i] == 0.0) {\n      shs += s[i] * hs[i];\n      dhs += d[i] * hs[i];\n      dhd += d[i] * hred[i];\n    }\n  }\n\n  /*     Seek the greatest reduction in Q for a range of equally spaced values\n   */\n  /*     of ANGT in [0,ANGBD], where ANGT is the tangent of half the angle of */\n  /*     the alternative iteration. */\n\n  redmax = 0.0;\n  isav = 0;\n  redsav = 0.0;\n  iu = long(angbd * 17. + 3.1);\n  for (long i = 1; i <= iu; ++i) {\n    angt = angbd * double(i) / double(iu);\n    sth = (angt + angt) / (1.0 + angt * angt);\n    temp = shs + angt * (angt * dhd - dhs - dhs);\n    rednew = sth * (angt * dredg - sredg - 0.5 * sth * temp);\n    if (rednew > redmax) {\n      redmax = rednew;\n      isav = i;\n      rdprev = redsav;\n    } else if (i == isav + 1) {\n      rdnext = rednew;\n    }\n    redsav = rednew;\n  }\n\n  /*     Return if the reduction is zero. Otherwise, set the sine and cosine */\n  /*     of the angle of the alternative iteration, and calculate SDEC. */\n\n  if (isav == 0) {\n    goto L190;\n  }\n  if (isav < iu) {\n    temp = (rdnext - rdprev) / (redmax + redmax - rdprev - rdnext);\n    angt = angbd * (double(isav) + 0.5 * temp) / double(iu);\n  }\n  cth = (1.0 - angt * angt) / (1.0 + angt * angt);\n  sth = (angt + angt) / (1.0 + angt * angt);\n  temp = shs + angt * (angt * dhd - dhs - dhs);\n  sdec = sth * (angt * dredg - sredg - 0.5 * sth * temp);\n  if (sdec <= 0.0) {\n    goto L190;\n  }\n\n  /*     Update GNEW, D and HRED. If the angle of the alternative iteration */\n  /*     is restricted by a bound on a free variable, that variable is fixed */\n  /*     at the bound. */\n\n  dredg = 0.0;\n  gredsq = 0.0;\n  for (long i = 1; i <= n; ++i) {\n    gnew[i] = gnew[i] + (cth - 1.0) * hred[i] + sth * hs[i];\n    if (xbdi[i] == 0.0) {\n      d[i] = cth * d[i] + sth * s[i];\n      dredg += d[i] * gnew[i];\n      gredsq += square(gnew[i]);\n    }\n    hred[i] = cth * hred[i] + sth * hs[i];\n  }\n  qred += sdec;\n  if (iact > 0 && isav == iu) {\n    ++nact;\n    xbdi[iact] = xsav;\n    goto L100;\n  }\n\n  /*     If SDEC is sufficiently small, then RETURN after setting XNEW to */\n  /*     XOPT+D, giving careful attention to the bounds. */\n\n  if (sdec > qred * .01) {\n    goto L120;\n  }\nL190:\n  *dsq = 0.0;\n  for (long i = 1; i <= n; ++i) {\n    xnew[i] = std::max(std::min(xopt[i] + d[i], su[i]), sl[i]);\n    if (xbdi[i] == -1.0) {\n      xnew[i] = sl[i];\n    }\n    if (xbdi[i] == 1.0) {\n      xnew[i] = su[i];\n    }\n    d[i] = xnew[i] - xopt[i];\n    *dsq += square(d[i]);\n  }\n  return;\n  /*     The following instructions multiply the current S-vector by the second\n   */\n  /*     derivative matrix of the quadratic model, putting the product in HS. */\n  /*     They are reached from three different parts of the software above and\n   */\n  /*     they can be regarded as an external subroutine. */\n\nL210:\n  long ih = 0;\n  for (long j = 1; j <= n; ++j) {\n    hs[j] = 0.0;\n    for (long i = 1; i <= j; ++i) {\n      ++ih;\n      if (i < j) {\n        hs[j] += hq[ih] * s[i];\n      }\n      hs[i] += hq[ih] * s[j];\n    }\n  }\n  for (long k = 1; k <= npt; ++k) {\n    if (pq[k] != 0.0) {\n      temp = 0.0;\n      for (long j = 1; j <= n; ++j) {\n        temp += xpt[k + j * xpt_dim1] * s[j];\n      }\n      temp *= pq[k];\n      for (long i = 1; i <= n; ++i) {\n        hs[i] += temp * xpt[k + i * xpt_dim1];\n      }\n    }\n  }\n  if (*crvmin != 0.0) {\n    goto L50;\n  }\n  if (iterc > itcsav) {\n    goto L150;\n  }\n  for (long i = 1; i <= n; ++i) {\n    hred[i] = hs[i];\n  }\n  goto L120;\n}\n\ntemplate<class Function>\ndouble\nbobyqb(const Function& function,\n       const long n,\n       const long npt,\n       double* const x,\n       const double* const xl,\n       const double* const xu,\n       const double rhobeg,\n       const double rhoend,\n       const long maxfun,\n       double* const xbase,\n       double* xpt,\n       double* const fval,\n       double* const xopt,\n       double* const gopt,\n       double* const hq,\n       double* const pq,\n       double* bmat,\n       double* zmat,\n       const long ndim,\n       double* const sl,\n       double* const su,\n       double* const xnew,\n       double* const xalt,\n       double* const d,\n       double* const vlag,\n       double* const w)\n{\n  /* Local variables */\n  double f = 0;\n  long ih, nf, jp;\n  double dx;\n  double den = 0, dsq = 0, rho = 0, sum = 0, diff = 0, beta = 0, gisq = 0;\n  long knew = 0;\n  double temp, suma, sumb, bsum, fopt;\n  long kopt = 0;\n  double curv;\n  long ksav;\n  double gqsq = 0, dist = 0, sumw = 0, sumz = 0, diffa = 0, diffb = 0,\n         diffc = 0, hdiag = 0;\n  long kbase;\n  double alpha = 0, delta = 0, adelt = 0, denom = 0, fsave = 0, bdtol = 0,\n         delsq = 0;\n  long nfsav;\n  double ratio = 0, dnorm = 0, vquad = 0, pqold = 0;\n  long itest;\n  double sumpq, scaden;\n  double errbig, cauchy = 0, fracsq, biglsq, densav;\n  double bdtest;\n  double crvmin, frhosq;\n  double distsq;\n  long ntrits;\n  double xoptsq;\n\n  /*     The arguments N, NPT, X, XL, XU, RHOBEG, RHOEND, IPRINT and MAXFUN */\n  /*       are identical to the corresponding arguments in SUBROUTINE BOBYQA. */\n  /*     XBASE holds a shift of origin that should reduce the contributions */\n  /*       from rounding errors to values of the model and Lagrange functions.\n   */\n  /*     XPT is a two-dimensional array that holds the coordinates of the */\n  /*       interpolation points relative to XBASE. */\n  /*     FVAL holds the values of F at the interpolation points. */\n  /*     XOPT is set to the displacement from XBASE of the trust region centre.\n   */\n  /*     GOPT holds the gradient of the quadratic model at XBASE+XOPT. */\n  /*     HQ holds the explicit second derivatives of the quadratic model. */\n  /*     PQ contains the parameters of the implicit second derivatives of the */\n  /*       quadratic model. */\n  /*     BMAT holds the last N columns of H. */\n  /*     ZMAT holds the factorization of the leading NPT by NPT submatrix of H,\n   */\n  /*       this factorization being ZMAT times ZMAT^T, which provides both the\n   */\n  /*       correct rank and positive semi-definiteness. */\n  /*     NDIM is the first dimension of BMAT and has the value NPT+N. */\n  /*     SL and SU hold the differences XL-XBASE and XU-XBASE, respectively. */\n  /*       All the components of every XOPT are going to satisfy the bounds */\n  /*       SL(I) .LEQ. XOPT(I) .LEQ. SU(I), with appropriate equalities when */\n  /*       XOPT is on a constraint boundary. */\n  /*     XNEW is chosen by SUBROUTINE TRSBOX or ALTMOV. Usually XBASE+XNEW is\n   * the */\n  /*       vector of variables for the next call of CALFUN. XNEW also satisfies\n   */\n  /*       the SL and SU constraints in the way that has just been mentioned. */\n  /*     XALT is an alternative to XNEW, chosen by ALTMOV, that may replace XNEW\n   */\n  /*       in order to increase the denominator in the updating of UPDATE. */\n  /*     D is reserved for a trial step from XOPT, which is usually XNEW-XOPT.\n   */\n  /*     VLAG contains the values of the Lagrange functions at a new point X. */\n  /*       They are part of a product that requires VLAG to be of length NDIM.\n   */\n  /*     W is a one-dimensional array that is used for working space. Its length\n   */\n  /*       must be at least 3*NDIM = 3*(NPT+N). */\n\n  /*     Set some constants. */\n\n  /* Parameter adjustments */\n  const long zmat_dim1 = npt;\n  const long zmat_offset = 1 + zmat_dim1;\n  zmat -= zmat_offset;\n  const long xpt_dim1 = npt;\n  const long xpt_offset = 1 + xpt_dim1;\n  xpt -= xpt_offset;\n  const long bmat_dim1 = ndim;\n  const long bmat_offset = 1 + bmat_dim1;\n  bmat -= bmat_offset;\n\n  /* Function Body */\n  const long np = n + 1;\n  const long nptm = npt - np;\n  const long nh = n * np / 2;\n\n  /*     The call of PRELIM sets the elements of XBASE, XPT, FVAL, GOPT, HQ, PQ,\n   */\n  /*     BMAT and ZMAT for the first iteration, with the corresponding values of\n   */\n  /*     of NF and KOPT, which are the number of calls of CALFUN so far and the\n   */\n  /*     index of the interpolation point at the trust region centre. Then the\n   */\n  /*     initial XOPT is set too. The branch to label 720 occurs if MAXFUN is */\n  /*     less than NPT. GOPT will be updated if KOPT is different from KBASE. */\n\n  prelim(function,\n         n,\n         npt,\n         x,\n         xl,\n         xu,\n         rhobeg,\n         maxfun,\n         xbase,\n         xpt + xpt_offset,\n         fval,\n         gopt,\n         hq,\n         pq,\n         bmat + bmat_offset,\n         zmat + zmat_offset,\n         ndim,\n         sl,\n         su,\n         nf,\n         kopt);\n  xoptsq = 0.0;\n  for (long i = 1; i <= n; ++i) {\n    xopt[i] = xpt[kopt + i * xpt_dim1];\n    xoptsq += square(xopt[i]);\n  }\n  fsave = fval[1];\n  if (nf < npt) {\n    // Return from BOBYQA because the objective function has been called\n    // max_f_evals times.;\n    goto L720;\n  }\n  kbase = 1;\n\n  /*     Complete the settings that are required for the iterative procedure. */\n\n  rho = rhobeg;\n  delta = rho;\n  ntrits = 0;\n  diffa = 0.0;\n  diffb = 0.0;\n  itest = 0;\n  nfsav = nf;\n\n  /*     Update GOPT if necessary before the first iteration and after each */\n  /*     call of RESCUE that makes a call of CALFUN. */\n\n  if (kopt != kbase) {\n    ih = 0;\n    for (long j = 1; j <= n; ++j) {\n      for (long i = 1; i <= j; ++i) {\n        ++ih;\n        if (i < j) {\n          gopt[j] += hq[ih] * xopt[i];\n        }\n        gopt[i] += hq[ih] * xopt[j];\n      }\n    }\n    if (nf > npt) {\n      for (long k = 1; k <= npt; ++k) {\n        temp = 0.0;\n        for (long j = 1; j <= n; ++j) {\n          temp += xpt[k + j * xpt_dim1] * xopt[j];\n        }\n        temp = pq[k] * temp;\n        for (long i = 1; i <= n; ++i) {\n          gopt[i] += temp * xpt[k + i * xpt_dim1];\n        }\n      }\n    }\n  }\n\n  /*     Generate the next point in the trust region that provides a small value\n   */\n  /*     of the quadratic model subject to the constraints on the variables. */\n  /*     The long NTRITS is set to the number \"trust region\" iterations that */\n  /*     have occurred since the last \"alternative\" iteration. If the length */\n  /*     of XNEW-XOPT is less than HALF*RHO, however, then there is a branch to\n   */\n  /*     label 650 or 680 with NTRITS=-1, instead of calculating F at XNEW. */\n\nL60:\n  trsbox(n,\n         npt,\n         xpt + xpt_offset,\n         xopt,\n         gopt,\n         hq,\n         pq,\n         sl,\n         su,\n         delta,\n         xnew,\n         d,\n         w,\n         w + np - 1,\n         w + np + n - 1,\n         w + np + (n << 1) - 1,\n         w + np + n * 3 - 1,\n         &dsq,\n         &crvmin);\n  dnorm = std::min(delta, std::sqrt(dsq));\n  if (dnorm < 0.5 * rho) {\n    ntrits = -1;\n    distsq = square(10.0 * rho);\n    if (nf <= nfsav + 2) {\n      goto L650;\n    }\n\n    /*     The following choice between labels 650 and 680 depends on whether or\n     */\n    /*     not our work with the current RHO seems to be complete. Either RHO is\n     */\n    /*     decreased or termination occurs if the errors in the quadratic model\n     * at */\n    /*     the last three interpolation points compare favourably with\n     * predictions */\n    /*     of likely improvements to the model within distance HALF*RHO of XOPT.\n     */\n\n    errbig = std::max(std::max(diffa, diffb), diffc);\n    frhosq = rho * .125 * rho;\n    if (crvmin > 0.0 && errbig > frhosq * crvmin) {\n      goto L650;\n    }\n    bdtol = errbig / rho;\n    for (long j = 1; j <= n; ++j) {\n      bdtest = bdtol;\n      if (xnew[j] == sl[j]) {\n        bdtest = w[j];\n      }\n      if (xnew[j] == su[j]) {\n        bdtest = -w[j];\n      }\n      if (bdtest < bdtol) {\n        curv = hq[(j + j * j) / 2];\n        for (long k = 1; k <= npt; ++k) {\n          curv += pq[k] * square(xpt[k + j * xpt_dim1]);\n        }\n        bdtest += 0.5 * curv * rho;\n        if (bdtest < bdtol) {\n          goto L650;\n        }\n      }\n    }\n    goto L680;\n  }\n  ++ntrits;\n\n  /*     Severe cancellation is likely to occur if XOPT is too far from XBASE.\n   */\n  /*     If the following test holds, then XBASE is shifted so that XOPT becomes\n   */\n  /*     zero. The appropriate changes are made to BMAT and to the second */\n  /*     derivatives of the current model, beginning with the changes to BMAT */\n  /*     that do not depend on ZMAT. VLAG is used temporarily for working space.\n   */\n\nL90:\n  if (dsq <= xoptsq * .001) {\n    fracsq = xoptsq * .25;\n    sumpq = 0.0;\n    for (long k = 1; k <= npt; ++k) {\n      sumpq += pq[k];\n      sum = -0.5 * xoptsq;\n      for (long i = 1; i <= n; ++i) {\n        sum += xpt[k + i * xpt_dim1] * xopt[i];\n      }\n      w[npt + k] = sum;\n      temp = fracsq - 0.5 * sum;\n      for (long i = 1; i <= n; ++i) {\n        w[i] = bmat[k + i * bmat_dim1];\n        vlag[i] = sum * xpt[k + i * xpt_dim1] + temp * xopt[i];\n        const long ip = npt + i;\n        for (long j = 1; j <= i; ++j) {\n          bmat[ip + j * bmat_dim1] =\n            bmat[ip + j * bmat_dim1] + w[i] * vlag[j] + vlag[i] * w[j];\n        }\n      }\n    }\n\n    /*     Then the revisions of BMAT that depend on ZMAT are calculated. */\n\n    for (long jj = 1; jj <= nptm; ++jj) {\n      sumz = 0.0;\n      sumw = 0.0;\n      for (long k = 1; k <= npt; ++k) {\n        sumz += zmat[k + jj * zmat_dim1];\n        vlag[k] = w[npt + k] * zmat[k + jj * zmat_dim1];\n        sumw += vlag[k];\n      }\n      for (long j = 1; j <= n; ++j) {\n        sum = (fracsq * sumz - 0.5 * sumw) * xopt[j];\n        for (long k = 1; k <= npt; ++k) {\n          sum += vlag[k] * xpt[k + j * xpt_dim1];\n        }\n        w[j] = sum;\n        for (long k = 1; k <= npt; ++k) {\n          bmat[k + j * bmat_dim1] += sum * zmat[k + jj * zmat_dim1];\n        }\n      }\n      for (long i = 1; i <= n; ++i) {\n        const long ip = i + npt;\n        temp = w[i];\n        for (long j = 1; j <= i; ++j) {\n          bmat[ip + j * bmat_dim1] += temp * w[j];\n        }\n      }\n    }\n\n    /*     The following instructions complete the shift, including the changes\n     */\n    /*     to the second derivative parameters of the quadratic model. */\n\n    ih = 0;\n    for (long j = 1; j <= n; ++j) {\n      w[j] = -0.5 * sumpq * xopt[j];\n      for (long k = 1; k <= npt; ++k) {\n        w[j] += pq[k] * xpt[k + j * xpt_dim1];\n        xpt[k + j * xpt_dim1] -= xopt[j];\n      }\n      for (long i = 1; i <= j; ++i) {\n        ++ih;\n        hq[ih] = hq[ih] + w[i] * xopt[j] + xopt[i] * w[j];\n        bmat[npt + i + j * bmat_dim1] = bmat[npt + j + i * bmat_dim1];\n      }\n    }\n    for (long i = 1; i <= n; ++i) {\n      xbase[i] += xopt[i];\n      xnew[i] -= xopt[i];\n      sl[i] -= xopt[i];\n      su[i] -= xopt[i];\n      xopt[i] = 0.0;\n    }\n    xoptsq = 0.0;\n  }\n  if (ntrits == 0) {\n    goto L210;\n  }\n  goto L230;\n\n  /*     Pick two alternative vectors of variables, relative to XBASE, that */\n  /*     are suitable as new positions of the KNEW-th interpolation point. */\n  /*     Firstly, XNEW is set to the point on a line through XOPT and another */\n  /*     interpolation point that minimizes the predicted value of the next */\n  /*     denominator, subject to ||XNEW - XOPT|| .LEQ. ADELT and to the SL */\n  /*     and SU bounds. Secondly, XALT is set to the best feasible point on */\n  /*     a constrained version of the Cauchy step of the KNEW-th Lagrange */\n  /*     function, the corresponding value of the square of this function */\n  /*     being returned in CAUCHY. The choice between these alternatives is */\n  /*     going to be made when the denominator is calculated. */\n\nL210:\n  altmov(n,\n         npt,\n         xpt + xpt_offset,\n         xopt,\n         bmat + bmat_offset,\n         zmat + zmat_offset,\n         ndim,\n         sl,\n         su,\n         kopt,\n         knew,\n         adelt,\n         xnew,\n         xalt,\n         alpha,\n         cauchy,\n         w,\n         w + np - 1,\n         w + ndim);\n  for (long i = 1; i <= n; ++i) {\n    d[i] = xnew[i] - xopt[i];\n  }\n\n  /*     Calculate VLAG and BETA for the current choice of D. The scalar */\n  /*     product of D with XPT(K,.) is going to be held in W(NPT+K) for */\n  /*     use when VQUAD is calculated. */\n\nL230:\n  for (long k = 1; k <= npt; ++k) {\n    suma = 0.0;\n    sumb = 0.0;\n    sum = 0.0;\n    for (long j = 1; j <= n; ++j) {\n      suma += xpt[k + j * xpt_dim1] * d[j];\n      sumb += xpt[k + j * xpt_dim1] * xopt[j];\n      sum += bmat[k + j * bmat_dim1] * d[j];\n    }\n    w[k] = suma * (0.5 * suma + sumb);\n    vlag[k] = sum;\n    w[npt + k] = suma;\n  }\n  beta = 0.0;\n  for (long jj = 1; jj <= nptm; ++jj) {\n    sum = 0.0;\n    for (long k = 1; k <= npt; ++k) {\n      sum += zmat[k + jj * zmat_dim1] * w[k];\n    }\n    beta -= sum * sum;\n    for (long k = 1; k <= npt; ++k) {\n      vlag[k] += sum * zmat[k + jj * zmat_dim1];\n    }\n  }\n  dsq = 0.0;\n  bsum = 0.0;\n  dx = 0.0;\n  for (long j = 1; j <= n; ++j) {\n    dsq += square(d[j]);\n    sum = 0.0;\n    for (long k = 1; k <= npt; ++k) {\n      sum += w[k] * bmat[k + j * bmat_dim1];\n    }\n    bsum += sum * d[j];\n    jp = npt + j;\n    for (long i = 1; i <= n; ++i) {\n      sum += bmat[jp + i * bmat_dim1] * d[i];\n    }\n    vlag[jp] = sum;\n    bsum += sum * d[j];\n    dx += d[j] * xopt[j];\n  }\n  beta = dx * dx + dsq * (xoptsq + dx + dx + 0.5 * dsq) + beta - bsum;\n  vlag[kopt] += 1.0;\n\n  /*     If NTRITS is zero, the denominator may be increased by replacing */\n  /*     the step D of ALTMOV by a Cauchy step. Then RESCUE may be called if */\n  /*     rounding errors have damaged the chosen denominator. */\n\n  if (ntrits == 0) {\n    denom = square(vlag[knew]) + alpha * beta;\n    if (denom < cauchy && cauchy > 0.0) {\n      for (long i = 1; i <= n; ++i) {\n        xnew[i] = xalt[i];\n        d[i] = xnew[i] - xopt[i];\n      }\n      cauchy = 0.0;\n      goto L230;\n    }\n    if (denom <= 0.5 * square(vlag[knew])) {\n      // Return from BOBYQA because of much cancellation in a denominator\n      goto L720;\n    }\n\n    /*     Alternatively, if NTRITS is positive, then set KNEW to the index of\n     */\n    /*     the next interpolation point to be deleted to make room for a trust\n     */\n    /*     region step. Again RESCUE may be called if rounding errors have\n     * damaged */\n    /*     the chosen denominator, which is the reason for attempting to select\n     */\n    /*     KNEW before calculating the next value of the objective function. */\n\n  } else {\n    delsq = delta * delta;\n    scaden = 0.0;\n    biglsq = 0.0;\n    knew = 0;\n    for (long k = 1; k <= npt; ++k) {\n      if (k == kopt) {\n        goto L350;\n      }\n      hdiag = 0.0;\n      for (long jj = 1; jj <= nptm; ++jj) {\n        hdiag += square(zmat[k + jj * zmat_dim1]);\n      }\n      den = beta * hdiag + square(vlag[k]);\n      distsq = 0.0;\n      for (long j = 1; j <= n; ++j) {\n        distsq += square(xpt[k + j * xpt_dim1] - xopt[j]);\n      }\n      temp = std::max(1.0, square(distsq / delsq));\n      if (temp * den > scaden) {\n        scaden = temp * den;\n        knew = k;\n        denom = den;\n      }\n      biglsq = std::max(biglsq, temp * square(vlag[k]));\n    L350:;\n    }\n    if (scaden <= 0.5 * biglsq) {\n      // Return from BOBYQA because of much cancellation in a denominator\n      goto L720;\n    }\n  }\n\n  /*     Put the variables for the next calculation of the objective function */\n  /*       in XNEW, with any adjustments for the bounds. */\n\n  /*     Calculate the value of the objective function at XBASE+XNEW, unless */\n  /*       the limit on the number of calculations of F has been reached. */\n\nL360:\n  for (long i = 1; i <= n; ++i) {\n    x[i] = std::min(std::max(xl[i], xbase[i] + xnew[i]), xu[i]);\n    if (xnew[i] == sl[i]) {\n      x[i] = xl[i];\n    }\n    if (xnew[i] == su[i]) {\n      x[i] = xu[i];\n    }\n  }\n  if (nf >= maxfun) {\n    // Return from BOBYQA because the objective function has been called\n    // max_f_evals times\n    goto L720;\n  }\n  ++nf;\n  f = function(n, x + 1);\n  if (ntrits == -1) {\n    fsave = f;\n    goto L720;\n  }\n\n  /*     Use the quadratic model to predict the change in F due to the step D,\n   */\n  /*       and set DIFF to the error of this prediction. */\n\n  fopt = fval[kopt];\n  vquad = 0.0;\n  ih = 0;\n  for (long j = 1; j <= n; ++j) {\n    vquad += d[j] * gopt[j];\n    for (long i = 1; i <= j; ++i) {\n      ++ih;\n      temp = d[i] * d[j];\n      if (i == j) {\n        temp = 0.5 * temp;\n      }\n      vquad += hq[ih] * temp;\n    }\n  }\n  for (long k = 1; k <= npt; ++k) {\n    vquad += 0.5 * pq[k] * square(w[npt + k]);\n  }\n  diff = f - fopt - vquad;\n  diffc = diffb;\n  diffb = diffa;\n  diffa = std::abs(diff);\n  if (dnorm > rho) {\n    nfsav = nf;\n  }\n\n  /*     Pick the next value of DELTA after a trust region step. */\n\n  if (ntrits > 0) {\n    if (vquad >= 0.0) {\n      // Return from BOBYQA because a trust region step has failed to reduce Q\n      goto L720;\n    }\n    ratio = (f - fopt) / vquad;\n    if (ratio <= 0.1) {\n      delta = std::min(0.5 * delta, dnorm);\n    } else if (ratio <= .7) {\n      delta = std::max(0.5 * delta, dnorm);\n    } else {\n      delta = std::max(0.5 * delta, dnorm + dnorm);\n    }\n    if (delta <= rho * 1.5) {\n      delta = rho;\n    }\n\n    /*     Recalculate KNEW and DENOM if the new F is less than FOPT. */\n\n    if (f < fopt) {\n      ksav = knew;\n      densav = denom;\n      delsq = delta * delta;\n      scaden = 0.0;\n      biglsq = 0.0;\n      knew = 0;\n      for (long k = 1; k <= npt; ++k) {\n        hdiag = 0.0;\n        for (long jj = 1; jj <= nptm; ++jj) {\n          hdiag += square(zmat[k + jj * zmat_dim1]);\n        }\n        den = beta * hdiag + square(vlag[k]);\n        distsq = 0.0;\n        for (long j = 1; j <= n; ++j) {\n          distsq += square(xpt[k + j * xpt_dim1] - xnew[j]);\n        }\n        temp = std::max(1.0, square(distsq / delsq));\n        if (temp * den > scaden) {\n          scaden = temp * den;\n          knew = k;\n          denom = den;\n        }\n        biglsq = std::max(biglsq, temp * square(vlag[k]));\n      }\n      if (scaden <= 0.5 * biglsq) {\n        knew = ksav;\n        denom = densav;\n      }\n    }\n  }\n\n  /*     Update BMAT and ZMAT, so that the KNEW-th interpolation point can be */\n  /*     moved. Also update the second derivative terms of the model. */\n\n  update(n,\n         npt,\n         bmat + bmat_offset,\n         zmat + zmat_offset,\n         ndim,\n         vlag,\n         beta,\n         denom,\n         knew,\n         w);\n  ih = 0;\n  pqold = pq[knew];\n  pq[knew] = 0.0;\n  for (long i = 1; i <= n; ++i) {\n    temp = pqold * xpt[knew + i * xpt_dim1];\n    for (long j = 1; j <= i; ++j) {\n      ++ih;\n      hq[ih] += temp * xpt[knew + j * xpt_dim1];\n    }\n  }\n  for (long jj = 1; jj <= nptm; ++jj) {\n    temp = diff * zmat[knew + jj * zmat_dim1];\n    for (long k = 1; k <= npt; ++k) {\n      pq[k] += temp * zmat[k + jj * zmat_dim1];\n    }\n  }\n\n  /*     Include the new interpolation point, and make the changes to GOPT at */\n  /*     the old XOPT that are caused by the updating of the quadratic model. */\n\n  fval[knew] = f;\n  for (long i = 1; i <= n; ++i) {\n    xpt[knew + i * xpt_dim1] = xnew[i];\n    w[i] = bmat[knew + i * bmat_dim1];\n  }\n  for (long k = 1; k <= npt; ++k) {\n    suma = 0.0;\n    for (long jj = 1; jj <= nptm; ++jj) {\n      suma += zmat[knew + jj * zmat_dim1] * zmat[k + jj * zmat_dim1];\n    }\n    sumb = 0.0;\n    for (long j = 1; j <= n; ++j) {\n      sumb += xpt[k + j * xpt_dim1] * xopt[j];\n    }\n    temp = suma * sumb;\n    for (long i = 1; i <= n; ++i) {\n      w[i] += temp * xpt[k + i * xpt_dim1];\n    }\n  }\n  for (long i = 1; i <= n; ++i) {\n    gopt[i] += diff * w[i];\n  }\n\n  /*     Update XOPT, GOPT and KOPT if the new calculated F is less than FOPT.\n   */\n\n  if (f < fopt) {\n    kopt = knew;\n    xoptsq = 0.0;\n    ih = 0;\n    for (long j = 1; j <= n; ++j) {\n      xopt[j] = xnew[j];\n      xoptsq += square(xopt[j]);\n      for (long i = 1; i <= j; ++i) {\n        ++ih;\n        if (i < j) {\n          gopt[j] += hq[ih] * d[i];\n        }\n        gopt[i] += hq[ih] * d[j];\n      }\n    }\n    for (long k = 1; k <= npt; ++k) {\n      temp = 0.0;\n      for (long j = 1; j <= n; ++j) {\n        temp += xpt[k + j * xpt_dim1] * d[j];\n      }\n      temp = pq[k] * temp;\n      for (long i = 1; i <= n; ++i) {\n        gopt[i] += temp * xpt[k + i * xpt_dim1];\n      }\n    }\n  }\n\n  /*     Calculate the parameters of the least Frobenius norm interpolant to */\n  /*     the current data, the gradient of this interpolant at XOPT being put */\n  /*     into VLAG(NPT+I), I=1,2,...,N. */\n\n  if (ntrits > 0) {\n    for (long k = 1; k <= npt; ++k) {\n      vlag[k] = fval[k] - fval[kopt];\n      w[k] = 0.0;\n    }\n    for (long j = 1; j <= nptm; ++j) {\n      sum = 0.0;\n      for (long k = 1; k <= npt; ++k) {\n        sum += zmat[k + j * zmat_dim1] * vlag[k];\n      }\n      for (long k = 1; k <= npt; ++k) {\n        w[k] += sum * zmat[k + j * zmat_dim1];\n      }\n    }\n    for (long k = 1; k <= npt; ++k) {\n      sum = 0.0;\n      for (long j = 1; j <= n; ++j) {\n        sum += xpt[k + j * xpt_dim1] * xopt[j];\n      }\n      w[k + npt] = w[k];\n      w[k] = sum * w[k];\n    }\n    gqsq = 0.0;\n    gisq = 0.0;\n    for (long i = 1; i <= n; ++i) {\n      sum = 0.0;\n      for (long k = 1; k <= npt; ++k) {\n        sum = sum + bmat[k + i * bmat_dim1] * vlag[k] +\n              xpt[k + i * xpt_dim1] * w[k];\n      }\n      if (xopt[i] == sl[i]) {\n        gqsq += square(std::min(0.0, gopt[i]));\n        gisq += square(std::min(0.0, sum));\n      } else if (xopt[i] == su[i]) {\n        gqsq += square(std::max(0.0, gopt[i]));\n        gisq += square(std::max(0.0, sum));\n      } else {\n        gqsq += square(gopt[i]);\n        gisq += sum * sum;\n      }\n      vlag[npt + i] = sum;\n    }\n\n    /*     Test whether to replace the new quadratic model by the least\n     * Frobenius */\n    /*     norm interpolant, making the replacement if the test is satisfied. */\n\n    ++itest;\n    if (gqsq < 10.0 * gisq) {\n      itest = 0;\n    }\n    if (itest >= 3) {\n      const long i_n = std::max(npt, nh);\n      for (long i = 1; i <= i_n; ++i) {\n        if (i <= n) {\n          gopt[i] = vlag[npt + i];\n        }\n        if (i <= npt) {\n          pq[i] = w[npt + i];\n        }\n        if (i <= nh) {\n          hq[i] = 0.0;\n        }\n        itest = 0;\n      }\n    }\n  }\n\n  /*     If a trust region step has provided a sufficient decrease in F, then */\n  /*     branch for another trust region calculation. The case NTRITS=0 occurs\n   */\n  /*     when the new interpolation point was reached by an alternative step. */\n\n  if (ntrits == 0) {\n    goto L60;\n  }\n  if (f <= fopt + 0.1 * vquad) {\n    goto L60;\n  }\n\n  /*     Alternatively, find out if the interpolation points are close enough */\n  /*       to the best point so far. */\n\n  distsq = std::max(square(2.0 * delta), square(10.0 * rho));\nL650:\n  knew = 0;\n  for (long k = 1; k <= npt; ++k) {\n    sum = 0.0;\n    for (long j = 1; j <= n; ++j) {\n      sum += square(xpt[k + j * xpt_dim1] - xopt[j]);\n    }\n    if (sum > distsq) {\n      knew = k;\n      distsq = sum;\n    }\n  }\n\n  /*     If KNEW is positive, then ALTMOV finds alternative new positions for */\n  /*     the KNEW-th interpolation point within distance ADELT of XOPT. It is */\n  /*     reached via label 90. Otherwise, there is a branch to label 60 for */\n  /*     another trust region iteration, unless the calculations with the */\n  /*     current RHO are complete. */\n\n  if (knew > 0) {\n    dist = std::sqrt(distsq);\n    if (ntrits == -1) {\n      delta = std::min(0.1 * delta, 0.5 * dist);\n      if (delta <= rho * 1.5) {\n        delta = rho;\n      }\n    }\n    ntrits = 0;\n    adelt = std::max(std::min(0.1 * dist, delta), rho);\n    dsq = adelt * adelt;\n    goto L90;\n  }\n  if (ntrits == -1) {\n    goto L680;\n  }\n  if (ratio > 0.0) {\n    goto L60;\n  }\n  if (std::max(delta, dnorm) > rho) {\n    goto L60;\n  }\n\n  /*     The calculations with the current value of RHO are complete. Pick the\n   */\n  /*       next values of RHO and DELTA. */\n\nL680:\n  if (rho > rhoend) {\n    delta = 0.5 * rho;\n    ratio = rho / rhoend;\n    if (ratio <= 16.) {\n      rho = rhoend;\n    } else if (ratio <= 250.) {\n      rho = std::sqrt(ratio) * rhoend;\n    } else {\n      rho = 0.1 * rho;\n    }\n    delta = std::max(delta, rho);\n    ntrits = 0;\n    nfsav = nf;\n    goto L60;\n  }\n\n  /*     Return from the calculation, after another Newton-Raphson step, if */\n  /*       it is too short to have been tried before. */\n\n  if (ntrits == -1) {\n    goto L360;\n  }\nL720:\n  if (fval[kopt] <= fsave) {\n    for (long i = 1; i <= n; ++i) {\n      x[i] = std::min(std::max(xl[i], xbase[i] + xopt[i]), xu[i]);\n      if (xopt[i] == sl[i]) {\n        x[i] = xl[i];\n      }\n      if (xopt[i] == su[i]) {\n        x[i] = xu[i];\n      }\n    }\n    f = fval[kopt];\n  }\n\n  return f;\n}\n\ntemplate<class Function>\ndouble\nimpl(const Function& function,\n     const long n,\n     const long npt,\n     double* x,\n     const double* xl,\n     const double* xu,\n     const double rhobeg,\n     const double rhoend,\n     const long maxfun,\n     double* w)\n{\n  /*     This subroutine seeks the least value of a function of many variables,\n   */\n  /*     by applying a trust region method that forms quadratic models by */\n  /*     interpolation. There is usually some freedom in the interpolation */\n  /*     conditions, which is taken up by minimizing the Frobenius norm of */\n  /*     the change to the second derivative of the model, beginning with the */\n  /*     zero matrix. The values of the variables are constrained by upper and\n   */\n  /*     lower bounds. The arguments of the subroutine are as follows. */\n\n  /*     N must be set to the number of variables and must be at least two. */\n  /*     NPT is the number of interpolation conditions. Its value must be in */\n  /*       the interval [N+2,(N+1)(N+2)/2]. Choices that exceed 2*N+1 are not */\n  /*       recommended. */\n  /*     Initial values of the variables must be set in X(1),X(2),...,X(N). They\n   */\n  /*       will be changed to the values that give the least calculated F. */\n  /*     For I=1,2,...,N, XL(I) and XU(I) must provide the lower and upper */\n  /*       bounds, respectively, on X(I). The construction of quadratic models\n   */\n  /*       requires XL(I) to be strictly less than XU(I) for each I. Further, */\n  /*       the contribution to a model from changes to the I-th variable is */\n  /*       damaged severely by rounding errors if XU(I)-XL(I) is too small. */\n  /*     RHOBEG and RHOEND must be set to the initial and final values of a\n   * trust */\n  /*       region radius, so both must be positive with RHOEND no greater than\n   */\n  /*       RHOBEG. Typically, RHOBEG should be about one tenth of the greatest\n   */\n  /*       expected change to a variable, while RHOEND should indicate the */\n  /*       accuracy that is required in the final values of the variables. An */\n  /*       error return occurs if any of the differences XU(I)-XL(I), I=1,...,N,\n   */\n  /*       is less than 2*RHOBEG. */\n  /*     MAXFUN must be set to an upper bound on the number of calls of CALFUN.\n   */\n  /*     The array W will be used for working space. Its length must be at least\n   */\n  /*       (NPT+5)*(NPT+N)+3*N*(N+5)/2. */\n\n  /* Parameter adjustments */\n  --w;\n  --xu;\n  --xl;\n  --x;\n\n  /* Function Body */\n  const long np = n + 1;\n\n  /*     Return if the value of NPT is unacceptable. */\n  if (npt < n + 2 || npt > (n + 2) * np / 2) {\n    // Return from BOBYQA because NPT is not in the required interval\n    return 0.0;\n  }\n\n  /*     Partition the working space array, so that different parts of it can */\n  /*     be treated separately during the calculation of BOBYQB. The partition\n   */\n  /*     requires the first (NPT+2)*(NPT+N)+3*N*(N+5)/2 elements of W plus the\n   */\n  /*     space that is taken by the last array in the argument list of BOBYQB.\n   */\n\n  const long ndim = npt + n;\n  const long ixp = 1 + n;\n  const long ifv = ixp + n * npt;\n  const long ixo = ifv + npt;\n  const long igo = ixo + n;\n  const long ihq = igo + n;\n  const long ipq = ihq + n * np / 2;\n  const long ibmat = ipq + npt;\n  const long izmat = ibmat + ndim * n;\n  const long isl = izmat + npt * (npt - np);\n  const long isu = isl + n;\n  const long ixn = isu + n;\n  const long ixa = ixn + n;\n  const long id_ = ixa + n;\n  const long ivl = id_ + n;\n  const long iw = ivl + ndim;\n\n  /*     Return if there is insufficient space between the bounds. Modify the */\n  /*     initial X if necessary in order to avoid conflicts between the bounds\n   */\n  /*     and the construction of the first quadratic model. The lower and upper\n   */\n  /*     bounds on moves from the updated X are set now, in the ISL and ISU */\n  /*     partitions of W, in order to provide useful and exact information about\n   */\n  /*     components of X that become within distance RHOBEG from their bounds.\n   */\n\n  for (long j = 1; j <= n; ++j) {\n    const double temp = xu[j] - xl[j];\n    if (temp < rhobeg + rhobeg) {\n      // Return from BOBYQA because one of the differences in x_lower and\n      // x_upper  is less than 2*rho_begin\n      return 0.0;\n    }\n    const long jsl = isl + j - 1;\n    const long jsu = jsl + n;\n    w[jsl] = xl[j] - x[j];\n    w[jsu] = xu[j] - x[j];\n    if (w[jsl] >= -(rhobeg)) {\n      if (w[jsl] >= 0.0) {\n        x[j] = xl[j];\n        w[jsl] = 0.0;\n        w[jsu] = temp;\n      } else {\n        x[j] = xl[j] + rhobeg;\n        w[jsl] = -(rhobeg);\n        w[jsu] = std::max(xu[j] - x[j], rhobeg);\n      }\n    } else if (w[jsu] <= rhobeg) {\n      if (w[jsu] <= 0.0) {\n        x[j] = xu[j];\n        w[jsl] = -temp;\n        w[jsu] = 0.0;\n      } else {\n        x[j] = xu[j] - rhobeg;\n        w[jsl] = std::min(xl[j] - x[j], -rhobeg);\n        w[jsu] = rhobeg;\n      }\n    }\n  }\n\n  /*     Make the call of BOBYQB. */\n\n  return bobyqb(function,\n                n,\n                npt,\n                x,\n                xl,\n                xu,\n                rhobeg,\n                rhoend,\n                maxfun,\n                w,\n                w + ixp,\n                w + ifv - 1,\n                w + ixo - 1,\n                w + igo - 1,\n                w + ihq - 1,\n                w + ipq - 1,\n                w + ibmat,\n                w + izmat,\n                ndim,\n                w + isl - 1,\n                w + isu - 1,\n                w + ixn - 1,\n                w + ixa - 1,\n                w + id_ - 1,\n                w + ivl - 1,\n                w + iw - 1);\n}\n\ntemplate<class Function>\nstd::pair<Eigen::VectorXd, double>\nbobyqa(const Function& function,\n       const long n,\n       const long npt,\n       Eigen::VectorXd initial_parameters,\n       Eigen::VectorXd lb,\n       Eigen::VectorXd ub,\n       const double rhobeg,\n       const double rhoend,\n       const long maxfun)\n{\n  if (npt < n + 2 || npt > (n + 2) * (n + 1) / 2) {\n    throw std::runtime_error(\"NPT is not in the required interval.\");\n  }\n\n  if ((ub - lb).minCoeff() < rhobeg + rhobeg) {\n    throw std::runtime_error(\"ub - lb should be greater than \"\n                             \"rhobeg + rhobeg.\");\n  }\n\n  std::size_t ws_size = (npt + 5) * (npt + n) + 3 * n * (n + 5) / 2;\n  double* w = new double[ws_size];\n  double* xl = new double[n];\n  double* xu = new double[n];\n  double eps = 1e-6;\n  Eigen::VectorXd::Map(xl, n) = lb.array() + eps;\n  Eigen::VectorXd::Map(xu, n) = ub.array() - eps;\n\n  double* x = new double[n];\n  Eigen::VectorXd::Map(x, n) = initial_parameters;\n\n  Eigen::VectorXd optimized_parameters = initial_parameters;\n  double optimum = 0.0;\n  std::string err_msg = \"\";\n  try {\n    optimum = tools_bobyqa::impl(\n      function, n, npt, x, xl, xu, rhobeg, rhoend, maxfun, w);\n    for (size_t i = 0; i < static_cast<size_t>(n); i++) {\n      optimized_parameters(i) = x[i];\n    }\n  } catch (std::invalid_argument& err) {\n    err_msg = std::string(\"Invalid arguments. \") + err.what();\n  } catch (std::bad_alloc& err) {\n    err_msg = std::string(\"Ran out of memory. \") + err.what();\n  } catch (std::runtime_error& err) {\n    err_msg = std::string(\"Generic failure. \") + err.what();\n  } catch (...) {\n    // do nothing for other errors (results are fine)\n  }\n\n  // delete dynamically allocated objects\n  delete[] x;\n  delete[] xl;\n  delete[] xu;\n  delete[] w;\n\n  // throw error if optimization failed\n  if (err_msg != \"\") {\n    throw std::runtime_error(err_msg);\n  }\n\n  std::pair<Eigen::VectorXd, double> result(optimized_parameters, optimum);\n  return result;\n}\n}\n}\n", "meta": {"hexsha": "48df8f15e5766da240e308f9ff0c24815cb5dae3", "size": 68306, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/vinecopulib/misc/tools_bobyqa.hpp", "max_stars_repo_name": "tvatter/vinecoplib", "max_stars_repo_head_hexsha": "ae34d56408437e6eeacec40a51a8fa8dac378672", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28.0, "max_stars_repo_stars_event_min_datetime": "2017-05-05T13:27:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-15T23:40:01.000Z", "max_issues_repo_path": "include/vinecopulib/misc/tools_bobyqa.hpp", "max_issues_repo_name": "vinecopulib/vinecopulib", "max_issues_repo_head_hexsha": "ae34d56408437e6eeacec40a51a8fa8dac378672", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 264.0, "max_issues_repo_issues_event_min_datetime": "2017-03-28T10:07:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-23T10:04:39.000Z", "max_forks_repo_path": "include/vinecopulib/misc/tools_bobyqa.hpp", "max_forks_repo_name": "tvatter/vinecoplib", "max_forks_repo_head_hexsha": "ae34d56408437e6eeacec40a51a8fa8dac378672", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-04-24T13:54:47.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-22T16:56:17.000Z", "avg_line_length": 29.2155688623, "max_line_length": 80, "alphanum_fraction": 0.5237168038, "num_tokens": 22819, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867681382279, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4548488461472662}}
{"text": "#pragma once\n#include <ctime>\n#include <cstdlib>\n\n\n#include <opencv2/highgui.hpp>\n#include <opencv2/videoio.hpp>\n#include <vpp/vpp.hh>\n#include <Eigen/Core>\n#include <list>\n\n\nusing namespace vpp;\nusing namespace std;\nusing namespace Eigen;\nusing namespace iod;\nusing namespace cv;\n\nnamespace vpp\n{\n\nvoid get_vanishing_points(int N, std::list<vint2> dominant_lines, int T_theta, int rhomax)\n{\n    int discr_phi = 1400;\n    int discr_the = 1400;\n    float scale = rhomax/2.0;\n    VectorXf vanish_accumulator(discr_phi*discr_the);\n    vanish_accumulator.setZero();\n    std::vector<vfloat3> acc_;\n    for(auto &dl1 : dominant_lines)\n    {\n        for(auto &dl2 : dominant_lines)\n        {\n            if((dl1-dl2).norm()!=0)\n            {\n                float rho1,rho2,theta1,theta2;\n                theta1 = ((2*M_PI*(dl1[1]))/ (T_theta-1)) - M_PI;\n                rho1 = dl1[0];\n                theta2 = ((2*M_PI*(dl2[1]))/ (T_theta-1)) - M_PI;\n                rho2 = dl2[0];\n                float x = (rho2/sin(theta2) - rho1/sin(theta1)) / ( 1/tan(theta2) - 1/tan(theta1));\n                float y = (rho2 - x*cos(theta2) ) / sin(theta2) ;\n                float x_2 = x/2;\n                float y_2 = y/2;\n                float diag_2 = sqrt(x_2*x_2 + y_2*y_2);\n                float phi = acos(y_2/diag_2);\n                float big_diag_2 = sqrt(rhomax + diag_2*diag_2);\n                float theta = acos(diag_2/big_diag_2);\n                int ind_theta = discr_the * theta / (M_PI/2);\n                int ind_phi = discr_phi * phi / (2 * M_PI);\n                vanish_accumulator[ind_theta*discr_phi + ind_phi]++;\n                //cout << \"valeurs : x = \" << x_2 << \" y = \" << y_2 << \" diag2 \" << diag_2 << \" bid \" << big_diag_2 << endl;\n                float ph = 2*M_PI*ind_phi / discr_phi;\n                float th = (M_PI/2)*ind_theta / discr_the;\n                cout << \"valeurs \" << ph << \"  \" << th << endl;\n                cout << \"valeurs \" << phi << \"  \" << theta << endl << endl << endl;\n            }\n        }\n    }\n    std::list<vint3> max_accu;\n    for(int t = 0 ; t < discr_the ; t++)\n    {\n        for(int p = 0 ; p < discr_phi ; p++)\n        {\n            int ind = t*discr_phi + p ;\n            if(vanish_accumulator[ind]>0)\n            {\n                cout << \"valeur accumul\u00e9e \" << vanish_accumulator[ind] << endl;\n                max_accu.push_back(vint3(t,p,vanish_accumulator[ind]));\n            }\n\n        }\n    }\n    max_accu.sort( [&](vint3& a, vint3& b){return a[2] > b[2];});\n    int i =0;\n    for(auto &val : max_accu)\n    {\n        int t = val[0];\n        int p = val[1];\n        float phi = 2*M_PI*p / discr_phi;\n        float theta = 2*M_PI * t / discr_the;\n        cout << \" les angles  phi :\" << phi << \" theta \" << theta << endl;\n        if(i==2)\n            break;\n        i++;\n    }\n}\n\n\nvoid get_vanishing_points1(int N, std::vector<vfloat3> dominant_lines, int T_theta, int rhomax, int nrows,int ncols)\n{\n    //int discr_phi = 1400;\n    //int discr_the = 1400;\n    //float scale = rhomax/2.0;\n    //VectorXf vanish_accumulator(discr_phi*discr_the);\n    std::vector<vfloat4> coord(3,vfloat4(0,0,0,-1));\n    for(int i = 0 ; i < 3 ; i++)\n    {\n        (coord[i])[3] = i;\n    }\n    //vanish_accumulator.setZero();\n    float mx = ncols/2;\n    float my = nrows/2;\n    std::vector<vfloat3> acc_;\n    std::vector<vfloat3> cluster1;\n    std::vector<vfloat3> cluster2;\n    std::vector<vfloat3> cluster3;\n    std::vector<vfloat3> outliers;\n    for(int i = 0 ; i < dominant_lines.size(); i++)\n    {\n        cout <<\" i = \" << i << endl;\n        for(int j = i+1 ; j < dominant_lines.size(); j++)\n        {\n            if(j!=i && j < dominant_lines.size())\n            {\n                cout << \" j = \" << j << endl;\n                float rho1,rho2,theta1,theta2;\n                theta1 = ((2*M_PI*(dominant_lines[i])[1])/ (T_theta-1)) - M_PI;\n                rho1 = (dominant_lines[i])[0];\n                theta2 = ((2*M_PI*(dominant_lines[j])[1])/ (T_theta-1)) - M_PI;\n                rho2 = (dominant_lines[j])[0];\n                float x = (rho2/sin(theta2) - rho1/sin(theta1)) / ( 1/tan(theta2) - 1/tan(theta1));\n                float y = (rho2 - x*cos(theta2) ) / sin(theta2);\n                if(fabs(theta1-theta2)<0.1)\n                {\n                    vfloat3 point= vfloat3(x,y,2);\n                    for(int k = 0 ; k < dominant_lines.size() ; k++)\n                    {\n                        if(k!=i && k!=j)\n                        {\n                            float rho3,theta3;\n                            rho3 = (dominant_lines[k])[0];\n                            theta3 = ((2*M_PI*(dominant_lines[k])[1])/ (T_theta-1)) - M_PI;\n                            float res = cos(theta3)*x + sin(theta3)*y - rho3;\n                            if(fabs(res) < 10)\n                            {\n                                point[2]++;\n                            }\n                        }\n                    }\n                    acc_.push_back(point);\n                    cout << \" x \" << point[0] << \" y \" << point[1] << \" val \" << point[2] << endl;\n                }\n            }\n        }\n    }\n    std::sort(acc_.begin(), acc_.end(),[&](vfloat3& a, vfloat3& b){return a[2] > b[2];});\n    //std::vector<vint2> vanishing_point(3);\n    double inf = std::numeric_limits<float>::infinity();\n    for(int i = 0 ; i < acc_.size() ; i++)\n    {\n        if((acc_[i])[2]>=2)\n        {\n            cout << \" x \" << (acc_[i])[0] << \" y \" << (acc_[i])[1] << \" val \" << (acc_[i])[2] << endl;\n            if(i==0)\n            {\n                cluster1.push_back(acc_[i]);\n                continue;\n            }\n            if( fabs((acc_[i])[0]) == inf && fabs((acc_[i])[1]) == inf)\n            {\n                if( cluster1.size()>0 &&  (acc_[i])[0]==(cluster1[0])[0]   && (acc_[i])[1]==(cluster1[0])[1]   )\n                {\n                    cluster1.push_back(acc_[i]);\n                }\n                else if( cluster2.size()>0 &&  (acc_[i])[0]==(cluster2[0])[0]   && (acc_[i])[1]==(cluster2[0])[1]   )\n                {\n                    cluster2.push_back(acc_[i]);\n                }\n                else if( cluster3.size()>0 &&  (acc_[i])[0]==(cluster3[0])[0]   && (acc_[i])[1]==(cluster3[0])[1]   )\n                {\n                    cluster3.push_back(acc_[i]);\n                }\n            }\n            else\n            {\n                if( cluster1.size()>0 && ( (acc_[i])[0]*(cluster1[0])[0] > 0  && (acc_[i])[1]*(cluster1[0])[1] > 0 ) )\n                {\n                    if(( (acc_[i]).segment(0,1) - (cluster1[0]).segment(0,1) ).norm() < 100  )\n                    cluster1.push_back(acc_[i]);\n                }\n                else if(  cluster2.size()>0 && ( (acc_[i])[0]*(cluster2[0])[0] > 0  && (acc_[i])[1]*(cluster2[0])[1] > 0 ) )\n                {\n                    if(( (acc_[i]).segment(0,1) - (cluster2[0]).segment(0,1) ).norm() < 100 )\n                    cluster2.push_back(acc_[i]);\n                }\n                else if(  cluster3.size()>0 && ( (acc_[i])[0]*(cluster3[0])[0] > 0  && (acc_[i])[1]*(cluster3[0])[1] > 0 )  )\n                {\n                          if(( (acc_[i]).segment(0,1) - (cluster3[0]).segment(0,1) ).norm() < 100)\n                    cluster3.push_back(acc_[i]);\n                }\n                else\n                {\n                    if(cluster1.size()==0)\n                    {\n                        cluster1.push_back(acc_[i]);\n                    }\n                    else if(cluster2.size()==0)\n                    {\n                        cluster2.push_back(acc_[i]);\n                    }\n                    else if(cluster3.size()==0)\n                    {\n                        cluster3.push_back(acc_[i]);\n                    }\n                    else\n                    {\n                        outliers.push_back(acc_[i]);\n                    }\n                }\n            }\n        }\n    }\n    vfloat3 C1;\n    vfloat3 C2;\n    vfloat3 C3;\n    if(cluster1.size() == 0 || cluster2.size() == 0 || cluster3.size() == 0 )\n    {\n        return;\n    }\n\n    if(cluster1.size()>0 &&  fabs((cluster1[0])[0]) == inf && fabs((cluster1[0])[1]) == inf )\n    {\n        C1 = cluster1[0];\n    }\n    else if ( cluster1.size()>0 )\n    {\n        float cf1 = 0;\n        cout << \"cluster 1\" << endl;\n        for(int i = 0 ; i < cluster1.size() ; i++)\n        {\n            cout << \" x \" << (cluster1[i])[0] << \" y \" << (cluster1[i])[1] << \" val \" << (cluster1[i])[2] << endl;\n            C1[0] += (cluster1[i])[0] * (cluster1[i])[2];\n            C1[1] += (cluster1[i])[1] * (cluster1[i])[2];\n            cf1 += (cluster1[i])[2];\n        }\n        C1[0] /= cf1;\n        C1[1] /= cf1;\n        C1[2] = -1;\n    }\n    cout << endl << endl << endl;\n\n    if(cluster2.size()>0 &&  fabs((cluster2[0])[0]) == inf && fabs((cluster2[0])[1]) == inf )\n    {\n        C2 = cluster2[0];\n    }\n    else if ( cluster2.size()>0 )\n    {\n        float cf2 = 0;\n        cout << \"cluster 2\" << endl;\n        for(int i = 0 ; i < cluster2.size() ; i++)\n        {\n            cout << \" x \" << (cluster2[i])[0] << \" y \" << (cluster2[i])[1] << \" val \" << (cluster2[i])[2] << endl;\n            C2[0] += (cluster2[i])[0] * (cluster2[i])[2];\n            C2[1] += (cluster2[i])[1] * (cluster2[i])[2];\n            cf2 += (cluster2[i])[2];\n        }\n        C2[0] /= cf2;\n        C2[1] /= cf2;\n        C2[2] = -1;\n    }\n\n    cout << endl << endl << endl;\n\n    if(cluster3.size()>0 &&  fabs((cluster3[0])[0]) == inf && fabs((cluster3[0])[1]) == inf )\n    {\n        C3 = cluster3[0];\n    }\n    else if ( cluster3.size()>0 )\n    {\n        float cf3 = 0;\n        cout << \"cluster 3\" << endl;\n        for(int i = 0 ; i < cluster3.size() ; i++)\n        {\n            cout << \" x \" << (cluster3[i])[0] << \" y \" << (cluster3[i])[1] << \" val \" << (cluster3[i])[2] << endl;\n            C3[0] += (cluster3[i])[0] * (cluster3[i])[2];\n            C3[1] += (cluster3[i])[1] * (cluster3[i])[2];\n            cf3 += (cluster3[i])[2];\n        }\n        C3[0] /= cf3;\n        C3[1] /= cf3;\n        C3[2] = -1;\n    }\n\n    cout << endl << endl << endl;\n\n    cout << \"cluster 1 \" << C1 << endl;\n    cout << \"cluster 2 \" << C2 << endl;\n    cout << \"cluster 3 \" << C3 << endl;/**/\n\n}\n\nvoid get_vanishing_points2(int N, std::vector<vfloat3> dominant_lines, int T_theta, int rhomax)\n{\n    int discr_phi = 1400;\n    int discr_the = 1400;\n    float scale = rhomax/2.0;\n    VectorXf vanish_accumulator(discr_phi*discr_the);\n    vanish_accumulator.setZero();\n    std::vector<vfloat3> acc_;\n    for(int i = 0 ; i < dominant_lines.size(); i++)\n    {\n        cout <<\" i = \" << i << endl;\n        for(int j = i+1 ; j < dominant_lines.size(); j++)\n        {\n            if(j!=i && j < dominant_lines.size())\n            {\n                cout << \" j = \" << j << endl;\n                float rho1,rho2,theta1,theta2;\n                theta1 = ((2*M_PI*(dominant_lines[i])[1])/ (T_theta-1)) - M_PI;\n                rho1 = (dominant_lines[i])[0];\n                theta2 = ((2*M_PI*(dominant_lines[j])[1])/ (T_theta-1)) - M_PI;\n                rho2 = (dominant_lines[j])[0];\n                float x = (rho2/sin(theta2) - rho1/sin(theta1)) / ( 1/tan(theta2) - 1/tan(theta1));\n                float y = (rho2 - x*cos(theta2) ) / sin(theta2);\n                if(fabs(theta1-theta2)<0.5)\n                {\n                    vfloat3 point= vfloat3(x,y,(dominant_lines[i])[2] + (dominant_lines[j])[2]);\n                    for(int k = 0 ; k < dominant_lines.size() ; k++)\n                    {\n                        if(k!=i && k!=j)\n                        {\n                            float rho3,theta3;\n                            rho3 = (dominant_lines[k])[0];\n                            theta3 = ((2*M_PI*(dominant_lines[k])[1])/ (T_theta-1)) - M_PI;\n                            float res = cos(theta3)*x + sin(theta3)*y - rho3;\n                            if(fabs(res) < 50)\n                            {\n                                point[2] += (dominant_lines[k])[2];\n                            }\n                        }\n                    }\n                    acc_.push_back(point);\n                    cout << \" x \" << point[0] << \" y \" << point[1] << \" val \" << point[2] << endl;\n                }\n            }\n        }\n    }\n    std::sort(acc_.begin(), acc_.end(),[&](vfloat3& a, vfloat3& b){return a[2] > b[2];});\n    for(int i = 0 ; i < acc_.size() ; i++)\n    {\n        if((acc_[i])[2]>2)\n        {\n            cout << \" x \" << (acc_[i])[0] << \" y \" << (acc_[i])[1] << \" val \" << (acc_[i])[2] << endl;\n        }\n    }\n}\n\n\ninline\nfloat compute_a(float thetaj)\n{\n    return 2*M_PI*(1-cos(thetaj));\n}\n\n\ninline\nfloat compute_theta(float nz,float nx,float ny, float phi)\n{\n    return asin(nz/(sqrt(nz*nz+ pow(nx*cos(phi)+ny*sin(phi),2))));\n}\n\ninline\nfloat compute_psi(float nz,float nx,float ny, float phi)\n{\n    float alpha = nx*cos(phi) + ny*sin(phi);\n    return M_PI/2 * alpha /(sqrt(nz*nz + alpha*alpha));\n}\n\n}\n\n", "meta": {"hexsha": "d8181cf8a7eb81bb2e85eb6c30b9887dc1cd8317", "size": 12988, "ext": "hh", "lang": "C++", "max_stars_repo_path": "vpp/algorithms/line_tracker_4_sfm/sfm/vanishing_point.hh", "max_stars_repo_name": "WLChopSticks/vpp", "max_stars_repo_head_hexsha": "2e17b21c56680bcfa94292ef5117f73572bf277d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 624.0, "max_stars_repo_stars_event_min_datetime": "2015-01-05T16:40:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T03:09:43.000Z", "max_issues_repo_path": "vpp/algorithms/line_tracker_4_sfm/sfm/vanishing_point.hh", "max_issues_repo_name": "WLChopSticks/vpp", "max_issues_repo_head_hexsha": "2e17b21c56680bcfa94292ef5117f73572bf277d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2015-01-22T20:50:13.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-15T10:41:34.000Z", "max_forks_repo_path": "vpp/algorithms/line_tracker_4_sfm/sfm/vanishing_point.hh", "max_forks_repo_name": "WLChopSticks/vpp", "max_forks_repo_head_hexsha": "2e17b21c56680bcfa94292ef5117f73572bf277d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 113.0, "max_forks_repo_forks_event_min_datetime": "2015-01-19T11:58:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T05:15:20.000Z", "avg_line_length": 34.9139784946, "max_line_length": 125, "alphanum_fraction": 0.4197720973, "num_tokens": 3799, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.538983220687684, "lm_q1q2_score": 0.45484530029741077}}
{"text": "#include <cmath>\n#include <iostream>\n#include <iomanip>\n#include <string>\n#include <vector>\n#include <algorithm>\n#include <boost/range/algorithm.hpp>\n#include <boost/integer/common_factor_rt.hpp>\n\nusing namespace std;\n\nint N, M, ret;\nbool b[100001];\nint dp[100001];\n\nint step(int s) {\n    if (b[s]) {\n        return 0;\n    }\n    if (s == N) {\n        return 1;\n    }\n    long long int ret = dp[s + 1];\n    if (s + 2 != N + 1) {\n        ret += dp[s + 2];\n    }\n    return ret % 1000000007;\n}\n\nint main() {\n\n    while (cin >> N >> M) {\n        for (int i = 0; i <= N; i++) {\n            b[i] = false;\n        }\n        for (int i = 0; i < M; i++) {\n            int a;\n            cin >> a;\n            b[a] = true;\n        }\n        for (int i = 0; i <= N; i++) {\n            dp[N - i] = step(N - i);\n        }\n\n        cout << dp[0] << endl;\n    }\n\n    return 0;\n}\n\n", "meta": {"hexsha": "7c1faee8cb5685f2ec25fd2dc2248aaa3492faaa", "size": 865, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "abc129_c/Main.cpp", "max_stars_repo_name": "mizo0203/atcoder", "max_stars_repo_head_hexsha": "56c06ccd111e3c36c7cfde4ae0753a8552f93728", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "abc129_c/Main.cpp", "max_issues_repo_name": "mizo0203/atcoder", "max_issues_repo_head_hexsha": "56c06ccd111e3c36c7cfde4ae0753a8552f93728", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "abc129_c/Main.cpp", "max_forks_repo_name": "mizo0203/atcoder", "max_forks_repo_head_hexsha": "56c06ccd111e3c36c7cfde4ae0753a8552f93728", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.9607843137, "max_line_length": 45, "alphanum_fraction": 0.438150289, "num_tokens": 270, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4548193603519451}}
{"text": "#include \"ql/qldefines.hpp\"\n#include <boost/config.hpp>\n#ifdef BOOST_MSVC\n#  include <ql/auto_link.hpp>\n#endif\n\n/*CVAIRS*/\n#include <ql/instruments/vanillaswap.hpp>\n#include <ql/instruments/makevanillaswap.hpp>\n#include <ql/pricingengines/swap/discountingswapengine.hpp>\n#include <ql/pricingengines/swap/cvaswapengine.hpp>\n#include <ql/termstructures/yield/piecewiseyieldcurve.hpp>\n#include <ql/termstructures/yield/ratehelpers.hpp>\n#include <ql/termstructures/credit/interpolatedhazardratecurve.hpp>\n#include <ql/indexes/ibor/euribor.hpp>\n#include <ql/time/calendars/target.hpp>\n#include <ql/time/daycounters/actualactual.hpp>\n#include <ql/time/daycounters/actual360.hpp>\n/*end CVAIRS*/\n\n/*Bonds*/\n#include <ql/instruments/bonds/zerocouponbond.hpp>\n#include <ql/instruments/bonds/floatingratebond.hpp>\n#include <ql/pricingengines/bond/discountingbondengine.hpp>\n#include <ql/cashflows/couponpricer.hpp>\n#include <ql/termstructures/yield/piecewiseyieldcurve.hpp>\n#include <ql/termstructures/yield/bondhelpers.hpp>\n#include <ql/termstructures/volatility/optionlet/constantoptionletvol.hpp>\n#include <ql/indexes/ibor/euribor.hpp>\n#include <ql/indexes/ibor/usdlibor.hpp>\n#include <ql/time/calendars/target.hpp>\n#include <ql/time/calendars/unitedstates.hpp>\n#include <ql/time/daycounters/actualactual.hpp>\n#include <ql/time/daycounters/actual360.hpp>\n#include <ql/time/daycounters/thirty360.hpp>\n#include <ql/utilities/dataparsers.hpp>\n/*end Bonds */\n\n/*Convertible Bonds */\n#include <ql/experimental/convertiblebonds/convertiblebond.hpp>\n#include <ql/experimental/convertiblebonds/binomialconvertibleengine.hpp>\n#include <ql/time/calendars/target.hpp>\n#include <ql/time/daycounters/thirty360.hpp>\n#include <ql/utilities/dataformatters.hpp>\n#define LENGTH(a) (sizeof(a)/sizeof(a[0]))\n/* end Convertible Bonds */\n\n/*BermudanSwaptions*/\n#include <ql/instruments/swaption.hpp>\n#include <ql/pricingengines/swap/discountingswapengine.hpp>\n#include <ql/pricingengines/swaption/treeswaptionengine.hpp>\n#include <ql/pricingengines/swaption/jamshidianswaptionengine.hpp>\n#include <ql/pricingengines/swaption/g2swaptionengine.hpp>\n#include <ql/pricingengines/swaption/fdhullwhiteswaptionengine.hpp>\n#include <ql/pricingengines/swaption/fdg2swaptionengine.hpp>\n#include <ql/models/shortrate/calibrationhelpers/swaptionhelper.hpp>\n#include <ql/models/shortrate/onefactormodels/blackkarasinski.hpp>\n#include <ql/math/optimization/levenbergmarquardt.hpp>\n#include <ql/indexes/ibor/euribor.hpp>\n#include <ql/cashflows/coupon.hpp>\n#include <ql/quotes/simplequote.hpp>\n#include <ql/termstructures/yield/flatforward.hpp>\n#include <ql/time/calendars/target.hpp>\n#include <ql/time/daycounters/thirty360.hpp>\n#include <ql/utilities/dataformatters.hpp>\n/*end BermudanSwaptions*/\n\n/*Callable Bonds */\n#include <ql/experimental/callablebonds/callablebond.hpp>\n#include <ql/experimental/callablebonds/treecallablebondengine.hpp>\n#include <ql/models/shortrate/onefactormodels/hullwhite.hpp>\n#include <ql/termstructures/yield/flatforward.hpp>\n#include <ql/time/calendars/unitedstates.hpp>\n#include <ql/time/daycounters/actualactual.hpp>\n\n#include <vector>\n#include <cmath>\n/* end of Callable Bonds */\n\n#include <iostream>\n#include <iomanip>\n#include <string>\n#include \"json.hpp\"\n\n//using namespace emscripten;\nusing namespace QuantLib;\nusing json = nlohmann::json;\n\n//using namespace std;\n//using namespace std::string_literals;\n\n#if defined(QL_ENABLE_SESSIONS)\nnamespace QuantLib {\n\n    ThreadKey sessionId() { return {}; }\n\n}\n#endif \n\next::shared_ptr<YieldTermStructure>\n        flatRate(const Date& today,\n            const ext::shared_ptr<Quote>& forward,\n            const DayCounter& dc,\n            const Compounding& compounding,\n            const Frequency& frequency) {\n        return ext::shared_ptr<YieldTermStructure>(\n            new FlatForward(today,\n                Handle<Quote>(forward),\n                dc,\n                compounding,\n                frequency));\n}\n\n                ext::shared_ptr<YieldTermStructure>\n        flatRate(const Date& today,\n                Rate forward,\n                const DayCounter& dc,\n                const Compounding &compounding,\n                const Frequency &frequency) {\n        return flatRate(today,\n                ext::shared_ptr<Quote>(new SimpleQuote(forward)),\n                dc,\n                compounding,\n                frequency);\n}\n\nstd::string calculateCallableBonds(std::string data){\n        \n        try {\n                json jData = json::parse(data);\n\n                Date today = Date(DateParser::parseISO( jData[\"request\"][\"referenceDate\"].get<std::string>()));\n                Settings::instance().evaluationDate() = today;\n\n                Rate bbCurveRate = jData[\"request\"][\"bbCurveRate\"].get<float>();\n\n                DayCounter bbDayCounter = ActualActual(ActualActual::Bond);\n                InterestRate bbIR(bbCurveRate,bbDayCounter,Compounded,Semiannual);\n\n                Handle<YieldTermStructure> termStructure(flatRate(today,\n                                                                bbIR.rate(),\n                                                                bbIR.dayCounter(),\n                                                                bbIR.compounding(),\n                                                                bbIR.frequency()));\n                \n                CallabilitySchedule callSchedule;\n                Real callPrice = jData[\"request\"][\"callPrice\"].get<int>();\n                Size numberOfCallDates = jData[\"request\"][\"numberOfCallDates\"].get<int>();\n                Date callDate = Date(DateParser::parseISO( jData[\"request\"][\"callDate\"].get<std::string>()));\n                \n                for (Size i=0; i< numberOfCallDates; i++) {\n                Calendar nullCalendar = NullCalendar();\n\n                Bond::Price myPrice(callPrice, Bond::Price::Clean);\n                callSchedule.push_back(\n                        ext::make_shared<Callability>(\n                                        myPrice,\n                                        Callability::Call,\n                                        callDate ));\n                callDate = nullCalendar.advance(callDate, 3, Months);\n                }\n\n                Date dated = Date(DateParser::parseISO(jData[\"request\"][\"callableBond\"][\"issueDate\"].get<std::string>()));\n                Date issue = dated;\n                Date maturity = Date(DateParser::parseISO( jData[\"request\"][\"callableBond\"][\"maturityDate\"].get<std::string>()));\n                \n                Natural settlementDays = jData[\"request\"][\"callableBond\"][\"settlementDays\"].get<int>();\n                Calendar bondCalendar = UnitedStates(UnitedStates::GovernmentBond);\n                Real coupon = jData[\"request\"][\"callableBond\"][\"coupon\"].get<float>();\n\n                Frequency frequency = Quarterly;\n\n                Real redemption = jData[\"request\"][\"callableBond\"][\"redemption\"].get<float>();\n\n                Real faceAmount = jData[\"request\"][\"callableBond\"][\"faceAmount\"].get<float>();\n                \n                DayCounter bondDayCounter = ActualActual(ActualActual::Bond);\n\n                // PFC1 shows no indication dates are being adjusted\n                // for weekends/holidays for vanilla bonds\n                BusinessDayConvention accrualConvention = Unadjusted;\n                BusinessDayConvention paymentConvention = Unadjusted;\n\n                Schedule sch(dated, maturity, Period(frequency), bondCalendar,\n                        accrualConvention, accrualConvention,\n                        DateGeneration::Backward, false);\n                \n               \n                Size maxIterations = jData[\"request\"][\"maxIterations\"];\n\n                //Real accuracy = 1e-8;\n                Real accuracy = jData[\"request\"][\"accuracy\"];\n\n                //Integer gridIntervals = 40;\n                Integer gridIntervals = jData[\"request\"][\"gridIntervals\"];\n\n                //Real reversionParameter = .03;\n                Real reversionParameter = jData[\"request\"][\"reversionParameter\"].get<float>();\n\n                // output price/yield results for varying volatility parameter\n\n                Real sigma = QL_EPSILON;\n\n                for (long unsigned int i = 0; i < jData[\"request\"][\"sigma\"].size(); i++){\n                        switch (i){\n                                case 0:{\n                                        ext::shared_ptr<ShortRateModel> hw0(new HullWhite(termStructure,reversionParameter,sigma));\n                                        ext::shared_ptr<PricingEngine> engine0(new TreeCallableFixedRateBondEngine(hw0,gridIntervals));\n                                        CallableFixedRateBond callableBond(settlementDays,faceAmount, sch,std::vector<Rate>(1, coupon),bondDayCounter, paymentConvention,redemption,issue,callSchedule);\n                                        callableBond.setPricingEngine(engine0);\n                                        jData[\"response\"][std::to_string(i)][\"sigma\"] = 0.0;//jData[\"request\"][\"sigma\"][0];\n                                        jData[\"response\"][std::to_string(i)][\"cleanPrice\"] =  callableBond.cleanPrice();\n                                        jData[\"response\"][std::to_string(i)][\"yield\"] =  100. * callableBond.yield(bondDayCounter,Compounded,frequency,accuracy,maxIterations);\n                                        break;  \n                                }     \n                                case 1:{\n                                        sigma = jData[\"request\"][\"sigma\"][i];\n                                        ext::shared_ptr<ShortRateModel> hw1(new HullWhite(termStructure,reversionParameter,sigma));\n                                        ext::shared_ptr<PricingEngine> engine1(new TreeCallableFixedRateBondEngine(hw1,gridIntervals));\n                                        CallableFixedRateBond callableBond(settlementDays,faceAmount, sch,std::vector<Rate>(1, coupon),bondDayCounter, paymentConvention,redemption,issue,callSchedule);\n                                        callableBond.setPricingEngine(engine1);\n                                        jData[\"response\"][std::to_string(i)][\"sigma\"] = 0.01;//jData[\"request\"][\"sigma\"][i];\n                                        jData[\"response\"][std::to_string(i)][\"cleanPrice\"] =  callableBond.cleanPrice();\n                                        jData[\"response\"][std::to_string(i)][\"yield\"] =  100. * callableBond.yield(bondDayCounter,Compounded,frequency,accuracy,maxIterations);\n                                        break;\n                                } \n                                case 2: {\n                                        sigma = jData[\"request\"][\"sigma\"][i];\n                                        ext::shared_ptr<ShortRateModel> hw2(new HullWhite(termStructure, reversionParameter, sigma));\n                                        ext::shared_ptr<PricingEngine> engine2(new TreeCallableFixedRateBondEngine(hw2,gridIntervals));\n                                        CallableFixedRateBond callableBond(settlementDays,faceAmount, sch,std::vector<Rate>(1, coupon),bondDayCounter, paymentConvention,redemption,issue,callSchedule);\n                                        callableBond.setPricingEngine(engine2);\n                                        jData[\"response\"][std::to_string(i)][\"sigma\"] = 0.03;//jData[\"request\"][\"sigma\"][2];\n                                        jData[\"response\"][std::to_string(i)][\"cleanPrice\"] =  callableBond.cleanPrice();\n                                        jData[\"response\"][std::to_string(i)][\"yield\"] =  100. * callableBond.yield(bondDayCounter,Compounded,frequency,accuracy,maxIterations);\n                                        break;\n                                }\n                                case 3: {\n                                        sigma = jData[\"request\"][\"sigma\"][i];\n                                        ext::shared_ptr<ShortRateModel> hw3(new HullWhite(termStructure, reversionParameter, sigma));\n                                        ext::shared_ptr<PricingEngine> engine3(new TreeCallableFixedRateBondEngine(hw3,gridIntervals));\n                                        CallableFixedRateBond callableBond(settlementDays,faceAmount, sch,std::vector<Rate>(1, coupon),bondDayCounter, paymentConvention,redemption,issue,callSchedule);\n                                        callableBond.setPricingEngine(engine3);\n                                        jData[\"response\"][std::to_string(i)][\"sigma\"] = 0.06;//jData[\"request\"][\"sigma\"][3];\n                                        jData[\"response\"][std::to_string(i)][\"cleanPrice\"] =  callableBond.cleanPrice();\n                                        jData[\"response\"][std::to_string(i)][\"yield\"] =  100. * callableBond.yield(bondDayCounter,Compounded,frequency,accuracy,maxIterations);\n                                        break;\n                                }\n                                case 4:{\n                                        sigma = jData[\"request\"][\"sigma\"][i];\n                                        ext::shared_ptr<ShortRateModel> hw4(new HullWhite(termStructure, reversionParameter, sigma));\n                                        ext::shared_ptr<PricingEngine> engine4(new TreeCallableFixedRateBondEngine(hw4,gridIntervals));\n                                        CallableFixedRateBond callableBond(settlementDays,faceAmount, sch,std::vector<Rate>(1, coupon),bondDayCounter, paymentConvention,redemption,issue,callSchedule);\n                                        callableBond.setPricingEngine(engine4);\n                                        jData[\"response\"][std::to_string(i)][\"sigma\"] = 0.012;//jData[\"request\"][\"sigma\"][4];\n                                        jData[\"response\"][std::to_string(i)][\"cleanPrice\"] =  callableBond.cleanPrice();\n                                        jData[\"response\"][std::to_string(i)][\"yield\"] =  100. * callableBond.yield(bondDayCounter,Compounded,frequency,accuracy,maxIterations);\n                                        break;\n                                }\n                                default: break;\n                        }\n                }\n                \n                \n                std::cout << \"JDATA\" << std::setw(4) << jData[\"response\"] << std::endl;\n                std::string result = jData.dump();\n                return result;\n\n        } catch (std::exception& e) {\n                std::cerr << e.what() << std::endl;\n                return \"1\";\n        } catch (...) {\n                std::cerr << \"unknown error\" << std::endl;\n                return \"1\";\n        }\n};\n\nstd::string calculateRegularBond(std::string data){\n\n    try {\n        \n        json incomingJsonData = json::parse(data);\n\n        std::cout << std::endl;\n\n        /*********************\n         ***  MARKET DATA  ***\n         *********************/\n\n        Calendar calendar = TARGET();\n\n\n        \n        Date settlementDate = DateParser::parseISO( incomingJsonData[\"request\"][\"settlementDate\"].get<std::string>());\n        // must be a business day\n        settlementDate = calendar.adjust(settlementDate);\n\n        Integer fixingDays = incomingJsonData[\"request\"][\"fixingDays\"];\n        Natural settlementDays = incomingJsonData[\"request\"][\"settlementDays\"];\n\n        Date todaysDate = calendar.advance(settlementDate, -fixingDays, Days);\n        // nothing to do with Date::todaysDate\n        Settings::instance().evaluationDate() = todaysDate;\n\n        Rate zc3mQuote = incomingJsonData[\"request\"][\"zeroCoupnRates\"][\"zc3mQuote\"];\n        Rate zc6mQuote = incomingJsonData[\"request\"][\"zeroCoupnRates\"][\"zc6mQuote\"];\n        Rate zc1yQuote = incomingJsonData[\"request\"][\"zeroCoupnRates\"][\"zc1yQuote\"];\n\n        ext::shared_ptr<Quote> zc3mRate(new SimpleQuote(zc3mQuote));\n        ext::shared_ptr<Quote> zc6mRate(new SimpleQuote(zc6mQuote));\n        ext::shared_ptr<Quote> zc1yRate(new SimpleQuote(zc1yQuote));\n\n        DayCounter zcBondsDayCounter = Actual365Fixed();\n\n        ext::shared_ptr<RateHelper> zc3m(new DepositRateHelper(\n                Handle<Quote>(zc3mRate),\n                3*Months, fixingDays,\n                calendar, ModifiedFollowing,\n                true, zcBondsDayCounter));\n        ext::shared_ptr<RateHelper> zc6m(new DepositRateHelper(\n                Handle<Quote>(zc6mRate),\n                6*Months, fixingDays,\n                calendar, ModifiedFollowing,\n                true, zcBondsDayCounter));\n        ext::shared_ptr<RateHelper> zc1y(new DepositRateHelper(\n                Handle<Quote>(zc1yRate),\n                1*Years, fixingDays,\n                calendar, ModifiedFollowing,\n                true, zcBondsDayCounter));\n\n        // setup bonds\n        Real redemption = 100.0;\n\n        const Size numberOfBonds = 5;\n\n        Date issueDates[] = {\n                Date (DateParser::parseISO( incomingJsonData[\"request\"][\"issueDate\"][0].get<std::string>())),\n                Date (DateParser::parseISO( incomingJsonData[\"request\"][\"issueDate\"][1].get<std::string>())),\n                Date (DateParser::parseISO( incomingJsonData[\"request\"][\"issueDate\"][2].get<std::string>())),\n                Date (DateParser::parseISO( incomingJsonData[\"request\"][\"issueDate\"][3].get<std::string>())),\n                Date (DateParser::parseISO( incomingJsonData[\"request\"][\"issueDate\"][4].get<std::string>()))\n        };\n\n        Date maturities[] = {\n                Date (DateParser::parseISO( incomingJsonData[\"request\"][\"maturities\"][0].get<std::string>())),\n                Date (DateParser::parseISO( incomingJsonData[\"request\"][\"maturities\"][1].get<std::string>())),\n                Date (DateParser::parseISO( incomingJsonData[\"request\"][\"maturities\"][2].get<std::string>())),\n                Date (DateParser::parseISO( incomingJsonData[\"request\"][\"maturities\"][3].get<std::string>())),\n                Date (DateParser::parseISO( incomingJsonData[\"request\"][\"maturities\"][4].get<std::string>()))\n        };\n\n        Real couponRates[] = {\n                incomingJsonData[\"request\"][\"couponRates\"][0],\n                incomingJsonData[\"request\"][\"couponRates\"][1],\n                incomingJsonData[\"request\"][\"couponRates\"][2],\n                incomingJsonData[\"request\"][\"couponRates\"][3],\n                incomingJsonData[\"request\"][\"couponRates\"][4]\n        };\n\n        Real marketQuotes[] = {\n                incomingJsonData[\"request\"][\"marketQuotes\"][0],\n                incomingJsonData[\"request\"][\"marketQuotes\"][1],\n                incomingJsonData[\"request\"][\"marketQuotes\"][2],\n                incomingJsonData[\"request\"][\"marketQuotes\"][3],\n                incomingJsonData[\"request\"][\"marketQuotes\"][4]\n        };\n\n        std::vector< ext::shared_ptr<SimpleQuote> > quote;\n        for (double marketQuote : marketQuotes) {\n            ext::shared_ptr<SimpleQuote> cp(new SimpleQuote(marketQuote));\n            quote.push_back(cp);\n        }\n\n        RelinkableHandle<Quote> quoteHandle[numberOfBonds];\n        for (Size i=0; i<numberOfBonds; i++) {\n            quoteHandle[i].linkTo(quote[i]);\n        }\n\n        // Definition of the rate helpers\n        std::vector<ext::shared_ptr<BondHelper> > bondsHelpers;\n\n        for (Size i=0; i<numberOfBonds; i++) {\n\n                Schedule schedule(issueDates[i], maturities[i], Period(Semiannual), UnitedStates(UnitedStates::GovernmentBond),\n                        Unadjusted, Unadjusted, DateGeneration::Backward, false);\n\n                ext::shared_ptr<FixedRateBondHelper> bondHelper(new FixedRateBondHelper(\n                        quoteHandle[i],\n                        settlementDays,\n                        100.0,\n                        schedule,\n                        std::vector<Rate>(1,couponRates[i]),\n                        ActualActual(ActualActual::Bond),\n                        Unadjusted,\n                        redemption,\n                        issueDates[i]));\n\n            // the above could also be done by creating a\n            // FixedRateBond instance and writing:\n            //\n            // ext::shared_ptr<BondHelper> bondHelper(\n            //         new BondHelper(quoteHandle[i], bond));\n            //\n            // This would also work for bonds that still don't have a\n            // specialized helper, such as floating-rate bonds.\n\n\n            bondsHelpers.push_back(bondHelper);\n        }\n\n        /*********************\n        **  CURVE BUILDING **\n        *********************/\n\n        // Any DayCounter would be fine.\n        // ActualActual::ISDA ensures that 30 years is 30.0\n        DayCounter termStructureDayCounter =\n        ActualActual(ActualActual::ISDA);\n\n        // A depo-bond curve\n        std::vector<ext::shared_ptr<RateHelper> > bondInstruments;\n\n        // Adding the ZC bonds to the curve for the short end\n        bondInstruments.push_back(zc3m);\n        bondInstruments.push_back(zc6m);\n        bondInstruments.push_back(zc1y);\n\n        // Adding the Fixed rate bonds to the curve for the long end\n        for (Size i=0; i<numberOfBonds; i++) {\n        bondInstruments.push_back(bondsHelpers[i]);\n        }\n\n        ext::shared_ptr<YieldTermStructure> bondDiscountingTermStructure(\n                new PiecewiseYieldCurve<Discount,LogLinear>(\n                        settlementDate, bondInstruments,\n                        termStructureDayCounter));\n\n        // Building of the Libor forecasting curve\n        // deposits\n        Rate d1wQuote = incomingJsonData[\"request\"][\"liborRates\"][\"d1wQuote\"];\n        Rate d1mQuote = incomingJsonData[\"request\"][\"liborRates\"][\"d1mQuote\"];\n        Rate d3mQuote = incomingJsonData[\"request\"][\"liborRates\"][\"d3mQuote\"];\n        Rate d6mQuote = incomingJsonData[\"request\"][\"liborRates\"][\"d6mQuote\"];\n        Rate d9mQuote = incomingJsonData[\"request\"][\"liborRates\"][\"d9mQuote\"];\n        Rate d1yQuote = incomingJsonData[\"request\"][\"liborRates\"][\"d1yQuote\"];\n        // swaps\n        Rate s2yQuote = incomingJsonData[\"request\"][\"swapRates\"][\"s2yQuote\"];\n        Rate s3yQuote = incomingJsonData[\"request\"][\"swapRates\"][\"s3yQuote\"];\n        Rate s5yQuote = incomingJsonData[\"request\"][\"swapRates\"][\"s5yQuote\"];\n        Rate s10yQuote = incomingJsonData[\"request\"][\"swapRates\"][\"s10yQuote\"];\n        Rate s15yQuote = incomingJsonData[\"request\"][\"swapRates\"][\"s15yQuote\"];\n\n\n        /********************\n         ***    QUOTES    ***\n        ********************/\n\n        // SimpleQuote stores a value which can be manually changed;\n        // other Quote subclasses could read the value from a database\n        // or some kind of data feed.\n\n        // deposits\n        ext::shared_ptr<Quote> d1wRate(new SimpleQuote(d1wQuote));\n        ext::shared_ptr<Quote> d1mRate(new SimpleQuote(d1mQuote));\n        ext::shared_ptr<Quote> d3mRate(new SimpleQuote(d3mQuote));\n        ext::shared_ptr<Quote> d6mRate(new SimpleQuote(d6mQuote));\n        ext::shared_ptr<Quote> d9mRate(new SimpleQuote(d9mQuote));\n        ext::shared_ptr<Quote> d1yRate(new SimpleQuote(d1yQuote));\n        // swaps\n        ext::shared_ptr<Quote> s2yRate(new SimpleQuote(s2yQuote));\n        ext::shared_ptr<Quote> s3yRate(new SimpleQuote(s3yQuote));\n        ext::shared_ptr<Quote> s5yRate(new SimpleQuote(s5yQuote));\n        ext::shared_ptr<Quote> s10yRate(new SimpleQuote(s10yQuote));\n        ext::shared_ptr<Quote> s15yRate(new SimpleQuote(s15yQuote));\n\n        /*********************\n         ***  RATE HELPERS ***\n        *********************/\n\n        // RateHelpers are built from the above quotes together with\n        // other instrument dependant infos.  Quotes are passed in\n        // relinkable handles which could be relinked to some other\n        // data source later.\n\n        // deposits\n        DayCounter depositDayCounter = Actual360();\n\n        ext::shared_ptr<RateHelper> d1w(new DepositRateHelper(\n                Handle<Quote>(d1wRate),\n                1*Weeks, fixingDays,\n                calendar, ModifiedFollowing,\n                true, depositDayCounter));\n        ext::shared_ptr<RateHelper> d1m(new DepositRateHelper(\n                Handle<Quote>(d1mRate),\n                1*Months, fixingDays,\n                calendar, ModifiedFollowing,\n                true, depositDayCounter));\n        ext::shared_ptr<RateHelper> d3m(new DepositRateHelper(\n                Handle<Quote>(d3mRate),\n                3*Months, fixingDays,\n                calendar, ModifiedFollowing,\n                true, depositDayCounter));\n        ext::shared_ptr<RateHelper> d6m(new DepositRateHelper(\n                Handle<Quote>(d6mRate),\n                6*Months, fixingDays,\n                calendar, ModifiedFollowing,\n                true, depositDayCounter));\n        ext::shared_ptr<RateHelper> d9m(new DepositRateHelper(\n                Handle<Quote>(d9mRate),\n                9*Months, fixingDays,\n                calendar, ModifiedFollowing,\n                true, depositDayCounter));\n        ext::shared_ptr<RateHelper> d1y(new DepositRateHelper(\n                Handle<Quote>(d1yRate),\n                1*Years, fixingDays,\n                calendar, ModifiedFollowing,\n                true, depositDayCounter));\n\n        // setup swaps\n        Frequency swFixedLegFrequency = Annual;\n        BusinessDayConvention swFixedLegConvention = Unadjusted;\n        DayCounter swFixedLegDayCounter = Thirty360(Thirty360::European);\n        ext::shared_ptr<IborIndex> swFloatingLegIndex(new Euribor6M);\n\n        const Period forwardStart(1*Days);\n\n        ext::shared_ptr<RateHelper> s2y(new SwapRateHelper(\n                Handle<Quote>(s2yRate), 2*Years,\n                calendar, swFixedLegFrequency,\n                swFixedLegConvention, swFixedLegDayCounter,\n                swFloatingLegIndex, Handle<Quote>(),forwardStart));\n        ext::shared_ptr<RateHelper> s3y(new SwapRateHelper(\n                Handle<Quote>(s3yRate), 3*Years,\n                calendar, swFixedLegFrequency,\n                swFixedLegConvention, swFixedLegDayCounter,\n                swFloatingLegIndex, Handle<Quote>(),forwardStart));\n        ext::shared_ptr<RateHelper> s5y(new SwapRateHelper(\n                Handle<Quote>(s5yRate), 5*Years,\n                calendar, swFixedLegFrequency,\n                swFixedLegConvention, swFixedLegDayCounter,\n                swFloatingLegIndex, Handle<Quote>(),forwardStart));\n        ext::shared_ptr<RateHelper> s10y(new SwapRateHelper(\n                Handle<Quote>(s10yRate), 10*Years,\n                calendar, swFixedLegFrequency,\n                swFixedLegConvention, swFixedLegDayCounter,\n                swFloatingLegIndex, Handle<Quote>(),forwardStart));\n        ext::shared_ptr<RateHelper> s15y(new SwapRateHelper(\n                Handle<Quote>(s15yRate), 15*Years,\n                calendar, swFixedLegFrequency,\n                swFixedLegConvention, swFixedLegDayCounter,\n                swFloatingLegIndex, Handle<Quote>(),forwardStart));\n\n\n        /*********************\n         **  CURVE BUILDING **\n        *********************/\n\n        // Any DayCounter would be fine.\n        // ActualActual::ISDA ensures that 30 years is 30.0\n\n        // A depo-swap curve\n        std::vector<ext::shared_ptr<RateHelper> > depoSwapInstruments;\n        depoSwapInstruments.push_back(d1w);\n        depoSwapInstruments.push_back(d1m);\n        depoSwapInstruments.push_back(d3m);\n        depoSwapInstruments.push_back(d6m);\n        depoSwapInstruments.push_back(d9m);\n        depoSwapInstruments.push_back(d1y);\n        depoSwapInstruments.push_back(s2y);\n        depoSwapInstruments.push_back(s3y);\n        depoSwapInstruments.push_back(s5y);\n        depoSwapInstruments.push_back(s10y);\n        depoSwapInstruments.push_back(s15y);\n        ext::shared_ptr<YieldTermStructure> depoSwapTermStructure(\n                new PiecewiseYieldCurve<Discount,LogLinear>(\n                        settlementDate, depoSwapInstruments,\n                        termStructureDayCounter));\n\n        // Term structures that will be used for pricing:\n        // the one used for discounting cash flows\n        RelinkableHandle<YieldTermStructure> discountingTermStructure;\n        // the one used for forward rate forecasting\n        RelinkableHandle<YieldTermStructure> forecastingTermStructure;\n\n        /*********************\n         * BONDS TO BE PRICED *\n         **********************/\n        //Date (DateParser::parseISO( incomingJsonData[\"maturities\"][0].get<std::string>())),\n        // Common data\n        Real faceAmount = 100;\n\n        // Pricing engine\n        ext::shared_ptr<PricingEngine> bondEngine(new DiscountingBondEngine(discountingTermStructure));\n\n        // Zero coupon bond\n        \n        ZeroCouponBond zeroCouponBond(\n                settlementDays,\n                UnitedStates(UnitedStates::GovernmentBond),\n                faceAmount,\n                Date(DateParser::parseISO( incomingJsonData[\"request\"][\"bondsToEvaluate\"][\"zeroCouponBond\"][\"expiryDate\"].get<std::string>())),\n                Following,\n                Real(incomingJsonData[\"request\"][\"bondsToEvaluate\"][\"zeroCouponBond\"][\"realPrice\"]),\n                Date(DateParser::parseISO( incomingJsonData[\"request\"][\"bondsToEvaluate\"][\"zeroCouponBond\"][\"issueDate\"].get<std::string>())));\n\n        zeroCouponBond.setPricingEngine(bondEngine);\n\n        // Fixed 4.5% US Treasury Note\n        \n        Schedule fixedBondSchedule(Date(DateParser::parseISO( incomingJsonData[\"request\"][\"bondsToEvaluate\"][\"FixedRateBond\"][\"issueDate\"].get<std::string>())),\n                Date(DateParser::parseISO( incomingJsonData[\"request\"][\"bondsToEvaluate\"][\"FixedRateBond\"][\"expiryDate\"].get<std::string>())), Period(Semiannual),\n                UnitedStates(UnitedStates::GovernmentBond),\n                Unadjusted, Unadjusted, DateGeneration::Backward, false);\n\n        FixedRateBond fixedRateBond(\n                settlementDays,\n                faceAmount,\n                fixedBondSchedule,\n                std::vector<Rate>(1, 0.045),\n                ActualActual(ActualActual::Bond),\n                ModifiedFollowing,\n                100.0, Date(DateParser::parseISO( incomingJsonData[\"request\"][\"bondsToEvaluate\"][\"FixedRateBond\"][\"issueDate\"].get<std::string>())));\n\n        fixedRateBond.setPricingEngine(bondEngine);\n\n        // Floating rate bond (3M USD Libor + 0.1%)\n        // Should and will be priced on another curve later...\n\n        // need to find out what is the deal with Libor here\n        RelinkableHandle<YieldTermStructure> liborTermStructure;\n        const ext::shared_ptr<IborIndex> libor3m(\n                new USDLibor(Period(3,Months),liborTermStructure));\n        libor3m->addFixing(Date(17, July, 2008),0.0278625);\n\n        // need to find out what is the deal with Libor here\n        Schedule floatingBondSchedule(Date(21, October, 2005),\n                Date(21, October, 2010), Period(Quarterly),\n                UnitedStates(UnitedStates::NYSE),\n                Unadjusted, Unadjusted, DateGeneration::Backward, true);\n\n        FloatingRateBond floatingRateBond(\n                settlementDays,\n                faceAmount,\n                floatingBondSchedule,\n                libor3m,\n                Actual360(),\n                ModifiedFollowing,\n                Natural(2),\n                // Gearings\n                std::vector<Real>(1, 1.0),\n                // Spreads\n                std::vector<Rate>(1, 0.001),\n                // Caps\n                std::vector<Rate>(),\n                // Floors\n                std::vector<Rate>(),\n                // Fixing in arrears\n                true,\n                Real(incomingJsonData[\"request\"][\"bondsToEvaluate\"][\"FloatingRateBond\"][\"realPrice\"]),\n                Date(DateParser::parseISO( incomingJsonData[\"request\"][\"bondsToEvaluate\"][\"FloatingRateBond\"][\"issueDate\"].get<std::string>())));\n\n        floatingRateBond.setPricingEngine(bondEngine);\n\n        // Coupon pricers\n        ext::shared_ptr<IborCouponPricer> pricer(new BlackIborCouponPricer);\n\n        // optionLet volatilities\n        Volatility volatility = 0.0;\n        Handle<OptionletVolatilityStructure> vol;\n        vol = Handle<OptionletVolatilityStructure>(\n                ext::shared_ptr<OptionletVolatilityStructure>(new\n                        ConstantOptionletVolatility(\n                                settlementDays,\n                                calendar,\n                                ModifiedFollowing,\n                                volatility,\n                                Actual365Fixed())));\n\n        pricer->setCapletVolatility(vol);\n        setCouponPricer(floatingRateBond.cashflows(),pricer);\n\n        // Yield curve bootstrapping\n        forecastingTermStructure.linkTo(depoSwapTermStructure);\n        discountingTermStructure.linkTo(bondDiscountingTermStructure);\n\n        // We are using the depo & swap curve to estimate the future Libor rates\n        liborTermStructure.linkTo(depoSwapTermStructure);\n\n        /***************\n         * BOND PRICING *\n         ****************/\n\n        incomingJsonData[\"response\"][\"zeroCouponBond\"][\"NPV\"] = zeroCouponBond.NPV(); \n        incomingJsonData[\"response\"][\"FixedRateBond\"][\"NPV\"] = fixedRateBond.NPV(); \n        incomingJsonData[\"response\"][\"FloatingRateBond\"][\"NPV\"] = floatingRateBond.NPV();  \n\n        incomingJsonData[\"response\"][\"zeroCouponBond\"][\"cleanPrice\"] = zeroCouponBond.cleanPrice(); \n        incomingJsonData[\"response\"][\"FixedRateBond\"][\"cleanPrice\"] = fixedRateBond.cleanPrice(); \n        incomingJsonData[\"response\"][\"FloatingRateBond\"][\"cleanPrice\"] = floatingRateBond.cleanPrice(); \n\n        incomingJsonData[\"response\"][\"zeroCouponBond\"][\"dirtyPrice\"] = zeroCouponBond.dirtyPrice(); \n        incomingJsonData[\"response\"][\"FixedRateBond\"][\"dirtyPrice\"] = fixedRateBond.dirtyPrice(); \n        incomingJsonData[\"response\"][\"FloatingRateBond\"][\"dirtyPrice\"] = floatingRateBond.dirtyPrice();\n \n        incomingJsonData[\"response\"][\"FixedRateBond\"][\"accruedAmount\"] = fixedRateBond.accruedAmount(); \n        incomingJsonData[\"response\"][\"FloatingRateBond\"][\"accruedAmount\"] = floatingRateBond.accruedAmount();\n\n        incomingJsonData[\"response\"][\"zeroCouponBond\"][\"previousCouponRate\"] = \"N/A\"; \n        incomingJsonData[\"response\"][\"FixedRateBond\"][\"previousCouponRate\"] = fixedRateBond.previousCouponRate(); \n        incomingJsonData[\"response\"][\"FloatingRateBond\"][\"previousCouponRate\"] = floatingRateBond.previousCouponRate();\n\n        incomingJsonData[\"response\"][\"zeroCouponBond\"][\"nextCouponRate\"] = \"N/A\"; \n        incomingJsonData[\"response\"][\"FixedRateBond\"][\"nextCouponRate\"] = fixedRateBond.nextCouponRate(); \n        incomingJsonData[\"response\"][\"FloatingRateBond\"][\"nextCouponRate\"] = floatingRateBond.nextCouponRate();\n\n        incomingJsonData[\"response\"][\"zeroCouponBond\"][\"Yield\"] = zeroCouponBond.yield(Actual360(),Compounded,Annual); \n        incomingJsonData[\"response\"][\"FixedRateBond\"][\"Yield\"] = fixedRateBond.yield(Actual360(),Compounded,Annual); \n        incomingJsonData[\"response\"][\"FloatingRateBond\"][\"Yield\"] = floatingRateBond.yield(Actual360(),Compounded,Annual);\n\n        incomingJsonData[\"response\"][\"FloatingRateBond\"][\"YieldtoCleanPrice\"] = floatingRateBond.cleanPrice(floatingRateBond.yield(Actual360(),Compounded,Annual),Actual360(),Compounded,Annual,settlementDate);\n        incomingJsonData[\"response\"][\"FloatingRateBond\"][\"CleanPriceToYield\"] = floatingRateBond.yield(floatingRateBond.cleanPrice(),Actual360(),Compounded,Annual,settlementDate);\n         /* \"Yield to Price\"\n            \"Price to Yield\" */\n\n        std::cout << std::setw(4) << \"Request: \" << std::endl;\n        std::cout << std::setw(4) << incomingJsonData << std::endl;\n\n        std::cout << std::setw(4) << \"Result: \" << std::endl;\n        std::cout << std::setw(4) << incomingJsonData[\"response\"] << std::endl;\n\n        std::string result = incomingJsonData.dump();\n        std::cout << \"result: \" << result << std::endl;\n\n         return result;\n\n        } catch (std::exception& e) {\n                std::cerr << e.what() << std::endl;\n                return \"1\";\n        } catch (...) {\n                std::cerr << \"unknown error\" << std::endl;\n                return \"1\";\n        }\n}\n\n\n\nstd::string calculateConvertibleBonds(std::string data){\n        try {\n                \n                json jData = json::parse(data);\n                std::cout << std::endl;\n\n                Option::Type type(Option::Put);\n                Real underlying = jData[\"request\"][\"underlying\"];\n                Real spreadRate = jData[\"request\"][\"spreadRate\"];\n\n                Spread dividendYield = jData[\"request\"][\"dividendYield\"];\n                Rate riskFreeRate = jData[\"request\"][\"riskFreeRate\"];\n                Volatility volatility =jData[\"request\"][\"volatility\"];\n\n                Integer settlementDays = jData[\"request\"][\"settlementDays\"];\n                Integer length = jData[\"request\"][\"length\"];\n                Real redemption = jData[\"request\"][\"redemption\"];\n                Real conversionRatio = redemption/underlying; // at the money\n\n                // set up dates/schedules\n                Calendar calendar = TARGET();\n                Date today = calendar.adjust(Date::todaysDate());\n\n                Settings::instance().evaluationDate() = today;\n                Date settlementDate = calendar.advance(today, settlementDays, Days);\n                Date exerciseDate = calendar.advance(settlementDate, length, Years);\n                Date issueDate = calendar.advance(exerciseDate, -length, Years);\n\n                BusinessDayConvention convention = ModifiedFollowing;\n\n                Frequency frequency = Annual;\n\n                Schedule schedule(issueDate, exerciseDate,\n                                Period(frequency), calendar,\n                                convention, convention,\n                                DateGeneration::Backward, false);\n\n                DividendSchedule dividends;\n                CallabilitySchedule callability;\n\n                std::vector<Real> coupons(1, 0.05);\n\n                DayCounter bondDayCount = Thirty360(Thirty360::BondBasis);\n\n                Integer callLength[] = { \n                        jData[\"request\"][\"calls\"][\"callLength\"][\"1\"].get<int>(),\n                        jData[\"request\"][\"calls\"][\"callLength\"][\"2\"].get<int>()\n                };  \n                Integer putLength[] = { \n                        jData[\"request\"][\"puts\"][\"putLength\"][\"1\"].get<int>() \n                }; \n\n                Real callPrices[] = { \n                        jData[\"request\"][\"calls\"][\"callPrices\"][\"1\"].get<double>(), \n                        jData[\"request\"][\"calls\"][\"callPrices\"][\"2\"].get<double>() \n                };\n                Real putPrices[]= { \n                        jData[\"request\"][\"puts\"][\"putPrices\"][\"1\"].get<double>() \n                };\n\n                // Load call schedules\n                for (Size i=0; i<LENGTH(callLength); i++) {\n                callability.push_back(\n                        ext::make_shared<SoftCallability>(Bond::Price(callPrices[i],\n                                                                        Bond::Price::Clean),\n                                                        schedule.date(callLength[i]),\n                                                        1.20));\n                }\n\n                for (Size j=0; j<LENGTH(putLength); j++) {\n                callability.push_back(\n                        ext::make_shared<Callability>(Bond::Price(putPrices[j],\n                                                                Bond::Price::Clean),\n                                                        Callability::Put,\n                                                        schedule.date(putLength[j])));\n                }\n\n                // Assume dividends are paid every 6 months.\n                for (Date d = today + 6*Months; d < exerciseDate; d += 6*Months) {\n                dividends.push_back(\n                        ext::shared_ptr<Dividend>(new FixedDividend(1.0, d)));\n                }\n\n                DayCounter dayCounter = Actual365Fixed();\n                Time maturity = dayCounter.yearFraction(settlementDate,\n                                                        exerciseDate);\n                \n                std::cout << \"option type = \"  << type << std::endl;\n                std::cout << \"Time to maturity = \"        << maturity\n                        << std::endl;\n                std::cout << \"Underlying price = \"        << underlying\n                        << std::endl;\n                std::cout << \"Risk-free interest rate = \" << io::rate(riskFreeRate)\n                        << std::endl;\n                std::cout << \"Dividend yield = \" << io::rate(dividendYield)\n                        << std::endl;\n                std::cout << \"Volatility = \" << io::volatility(volatility)\n                        << std::endl;\n                std::cout << std::endl;\n\n                std::string method;\n                std::cout << std::endl ;\n\n                // write column headings\n                Size widths[] = { 35, 14, 14 };\n                Size totalWidth = widths[0] + widths[1] + widths[2];\n                std::string rule(totalWidth, '-'), dblrule(totalWidth, '=');\n\n                std::cout << dblrule << std::endl;\n                std::cout << \"Tsiveriotis-Fernandes method\" << std::endl;\n                std::cout << dblrule << std::endl;\n                std::cout << std::setw(widths[0]) << std::left << \"Tree type\"\n                        << std::setw(widths[1]) << std::left << \"European\"\n                        << std::setw(widths[1]) << std::left << \"American\"\n                        << std::endl;\n\n                std::cout << rule << std::endl;\n\n                ext::shared_ptr<Exercise> exercise(\n                                                new EuropeanExercise(exerciseDate));\n                ext::shared_ptr<Exercise> amExercise(\n                                                new AmericanExercise(settlementDate,\n                                                                exerciseDate));\n\n                Handle<Quote> underlyingH(\n                ext::shared_ptr<Quote>(new SimpleQuote(underlying)));\n\n                Handle<YieldTermStructure> flatTermStructure(\n                ext::shared_ptr<YieldTermStructure>(\n                        new FlatForward(settlementDate, riskFreeRate, dayCounter)));\n\n                Handle<YieldTermStructure> flatDividendTS(\n                ext::shared_ptr<YieldTermStructure>(\n                        new FlatForward(settlementDate, dividendYield, dayCounter)));\n\n                Handle<BlackVolTermStructure> flatVolTS(\n                ext::shared_ptr<BlackVolTermStructure>(\n                        new BlackConstantVol(settlementDate, calendar,\n                                        volatility, dayCounter)));\n\n\n                ext::shared_ptr<BlackScholesMertonProcess> stochasticProcess(\n                                new BlackScholesMertonProcess(underlyingH,\n                                                                flatDividendTS,\n                                                                flatTermStructure,\n                                                                flatVolTS));\n\n                Size timeSteps = jData[\"request\"][\"timeSteps\"].get<int>();\n\n                Handle<Quote> creditSpread(\n                        ext::shared_ptr<Quote>(new SimpleQuote(spreadRate)));\n\n                ext::shared_ptr<Quote> rate(new SimpleQuote(riskFreeRate));\n\n                Handle<YieldTermStructure> discountCurve(\n                        ext::shared_ptr<YieldTermStructure>(\n                        new FlatForward(today, Handle<Quote>(rate), dayCounter)));\n\n                ext::shared_ptr<PricingEngine> engine(\n                        new BinomialConvertibleEngine<JarrowRudd>(stochasticProcess,\n                                                                timeSteps));\n\n                ConvertibleFixedCouponBond europeanBond(\n                                exercise, conversionRatio, dividends, callability,\n                                creditSpread, issueDate, settlementDays,\n                                coupons, bondDayCount, schedule, redemption);\n                europeanBond.setPricingEngine(engine);\n\n                ConvertibleFixedCouponBond americanBond(\n                                amExercise, conversionRatio, dividends, callability,\n                                creditSpread, issueDate, settlementDays,\n                                coupons, bondDayCount, schedule, redemption);\n                americanBond.setPricingEngine(engine);\n\n                method = \"Jarrow-Rudd\";\n                europeanBond.setPricingEngine(ext::shared_ptr<PricingEngine>(\n                        new BinomialConvertibleEngine<JarrowRudd>(stochasticProcess,\n                                                                timeSteps)));\n                americanBond.setPricingEngine(ext::shared_ptr<PricingEngine>(\n                        new BinomialConvertibleEngine<JarrowRudd>(stochasticProcess,\n                                                                timeSteps)));\n                std::cout << std::setw(widths[0]) << std::left << method\n                        << std::fixed\n                        << std::setw(widths[1]) << std::left << europeanBond.NPV()\n                        << std::setw(widths[2]) << std::left << americanBond.NPV()\n                        << std::endl;\n\n                jData[\"response\"][\"Tsiveriotis-Fernandes method\"][\"treeType\"][\"Jarrow-Rudd\"][\"American\"][\"NPV\"] = americanBond.NPV();\n                jData[\"response\"][\"Tsiveriotis-Fernandes method\"][\"treeType\"][\"Jarrow-Rudd\"][\"European\"][\"NPV\"] = europeanBond.NPV();\n                \n                method = \"Cox-Ross-Rubinstein\";\n                europeanBond.setPricingEngine(ext::shared_ptr<PricingEngine>(\n                new BinomialConvertibleEngine<CoxRossRubinstein>(stochasticProcess,\n                                                                timeSteps)));\n                americanBond.setPricingEngine(ext::shared_ptr<PricingEngine>(\n                new BinomialConvertibleEngine<CoxRossRubinstein>(stochasticProcess,\n                                                                timeSteps)));\n                std::cout << std::setw(widths[0]) << std::left << method\n                        << std::fixed\n                        << std::setw(widths[1]) << std::left << europeanBond.NPV()\n                        << std::setw(widths[2]) << std::left << americanBond.NPV()\n                        << std::endl;\n                jData[\"response\"][\"Tsiveriotis-Fernandes method\"][\"treeType\"][\"Cox-Ross-Rubinstein\"][\"American\"][\"NPV\"] = americanBond.NPV();\n                jData[\"response\"][\"Tsiveriotis-Fernandes method\"][\"treeType\"][\"Cox-Ross-Rubinstein\"][\"European\"][\"NPV\"] = europeanBond.NPV();\n\n                method = \"Additive equiprobabilities\";\n                europeanBond.setPricingEngine(ext::shared_ptr<PricingEngine>(\n                        new BinomialConvertibleEngine<AdditiveEQPBinomialTree>(\n                                                                stochasticProcess,\n                                                                timeSteps)));\n                americanBond.setPricingEngine(ext::shared_ptr<PricingEngine>(\n                        new BinomialConvertibleEngine<AdditiveEQPBinomialTree>(\n                                                                stochasticProcess,\n                                                                timeSteps)));\n                std::cout << std::setw(widths[0]) << std::left << method\n                        << std::fixed\n                        << std::setw(widths[1]) << std::left << europeanBond.NPV()\n                        << std::setw(widths[2]) << std::left << americanBond.NPV()\n                        << std::endl;\n\n                jData[\"response\"][\"Tsiveriotis-Fernandes method\"][\"treeType\"][\"Additive equiprobabilities\"][\"American\"][\"NPV\"] = americanBond.NPV();\n                jData[\"response\"][\"Tsiveriotis-Fernandes method\"][\"treeType\"][\"Additive equiprobabilities\"][\"European\"][\"NPV\"] = europeanBond.NPV();\n\n                method = \"Trigeorgis\";\n                europeanBond.setPricingEngine(ext::shared_ptr<PricingEngine>(\n                        new BinomialConvertibleEngine<Trigeorgis>(stochasticProcess,\n                                                                timeSteps)));\n                americanBond.setPricingEngine(ext::shared_ptr<PricingEngine>(\n                        new BinomialConvertibleEngine<Trigeorgis>(stochasticProcess,\n                                                                timeSteps)));\n                std::cout << std::setw(widths[0]) << std::left << method\n                        << std::fixed\n                        << std::setw(widths[1]) << std::left << europeanBond.NPV()\n                        << std::setw(widths[2]) << std::left << americanBond.NPV()\n                        << std::endl;\n\n                jData[\"response\"][\"Tsiveriotis-Fernandes method\"][\"treeType\"][\"Trigeorgis\"][\"American\"][\"NPV\"] = americanBond.NPV();\n                jData[\"response\"][\"Tsiveriotis-Fernandes method\"][\"treeType\"][\"Trigeorgis\"][\"European\"][\"NPV\"] = europeanBond.NPV();\n\n                \n\n                method = \"Tian\";\n                europeanBond.setPricingEngine(ext::shared_ptr<PricingEngine>(\n                                new BinomialConvertibleEngine<Tian>(stochasticProcess,\n                                                                timeSteps)));\n                americanBond.setPricingEngine(ext::shared_ptr<PricingEngine>(\n                                new BinomialConvertibleEngine<Tian>(stochasticProcess,\n                                                                timeSteps)));\n                std::cout << std::setw(widths[0]) << std::left << method\n                        << std::fixed\n                        << std::setw(widths[1]) << std::left << europeanBond.NPV()\n                        << std::setw(widths[2]) << std::left << americanBond.NPV()\n                        << std::endl;\n\n                jData[\"response\"][\"Tsiveriotis-Fernandes method\"][\"treeType\"][\"Tian\"][\"American\"][\"NPV\"] = americanBond.NPV();\n                jData[\"response\"][\"Tsiveriotis-Fernandes method\"][\"treeType\"][\"Tian\"][\"European\"][\"NPV\"] = europeanBond.NPV();\n\n\n                method = \"Leisen-Reimer\";\n                europeanBond.setPricingEngine(ext::shared_ptr<PricingEngine>(\n                        new BinomialConvertibleEngine<LeisenReimer>(stochasticProcess,\n                                                                timeSteps)));\n                americanBond.setPricingEngine(ext::shared_ptr<PricingEngine>(\n                        new BinomialConvertibleEngine<LeisenReimer>(stochasticProcess,\n                                                                timeSteps)));\n                std::cout << std::setw(widths[0]) << std::left << method\n                        << std::fixed\n                        << std::setw(widths[1]) << std::left << europeanBond.NPV()\n                        << std::setw(widths[2]) << std::left << americanBond.NPV()\n                        << std::endl;\n\n                jData[\"response\"][\"Tsiveriotis-Fernandes method\"][\"treeType\"][\"Leisen-Reimer\"][\"American\"][\"NPV\"] = americanBond.NPV();\n                jData[\"response\"][\"Tsiveriotis-Fernandes method\"][\"treeType\"][\"Leisen-Reimer\"][\"European\"][\"NPV\"] = europeanBond.NPV();\n\n\n                method = \"Joshi\";\n                europeanBond.setPricingEngine(ext::shared_ptr<PricingEngine>(\n                        new BinomialConvertibleEngine<Joshi4>(stochasticProcess,\n                                                                timeSteps)));\n                americanBond.setPricingEngine(ext::shared_ptr<PricingEngine>(\n                        new BinomialConvertibleEngine<Joshi4>(stochasticProcess,\n                                                                timeSteps)));\n                std::cout << std::setw(widths[0]) << std::left << method\n                        << std::fixed\n                        << std::setw(widths[1]) << std::left << europeanBond.NPV()\n                        << std::setw(widths[2]) << std::left << americanBond.NPV()\n                        << std::endl;\n\n                jData[\"response\"][\"Tsiveriotis-Fernandes method\"][\"treeType\"][\"Joshi\"][\"American\"][\"NPV\"] = americanBond.NPV();\n                jData[\"response\"][\"Tsiveriotis-Fernandes method\"][\"treeType\"][\"Joshi\"][\"European\"][\"NPV\"] = europeanBond.NPV();\n\n                std::cout << dblrule << std::endl;\n                std::cout << \"result: \" << std::setw(4) << jData[\"response\"] << std::endl;\n                std::string result = jData.dump();\n                return result;\n        } catch (std::exception& e) {\n                std::cerr << e.what() << std::endl;\n                return \"1\";\n        } catch (...) {\n                std::cerr << \"unknown error\" << std::endl;\n                return \"1\";\n        }  \n};\n\nstd::string calculateCVAIRS(std::string data){\ntry {\n\n        json jData = json::parse(data);\n\n        std::cout << std::endl;\n\n        Calendar calendar = TARGET();\n        Date todaysDate(DateParser::parseISO( jData[\"request\"][\"todaysDate\"].get<std::string>()));\n        // must be a business day\n        todaysDate = calendar.adjust(todaysDate);\n\n        Settings::instance().evaluationDate() = todaysDate;\n\n        ext::shared_ptr<IborIndex>  yieldIndx(new Euribor3M());\n        Size tenorsSwapMkt[] = {5, 10, 15, 20, 25, 30};\n        \n        // rates ignoring counterparty risk:\n        Rate ratesSwapmkt[] = {.03249, .04074, .04463, .04675, .04775, .04811};\n\n        std::vector<ext::shared_ptr<RateHelper> > swapHelpers;\n        for(Size i=0; i<sizeof(tenorsSwapMkt)/sizeof(Size); i++)\n        swapHelpers.push_back(ext::make_shared<SwapRateHelper>(\n                Handle<Quote>(ext::shared_ptr<Quote>(\n                                new SimpleQuote(ratesSwapmkt[i]))),\n                tenorsSwapMkt[i] * Years,\n                TARGET(),\n                Quarterly,\n                ModifiedFollowing,\n                ActualActual(ActualActual::ISDA),\n                yieldIndx));\n\n        ext::shared_ptr<YieldTermStructure> swapTS(\n        new PiecewiseYieldCurve<Discount,LogLinear>(\n        2, TARGET(), swapHelpers, ActualActual(ActualActual::ISDA)));\n        swapTS->enableExtrapolation();\n\n        ext::shared_ptr<PricingEngine> riskFreeEngine(\n        ext::make_shared<DiscountingSwapEngine>(\n                Handle<YieldTermStructure>(swapTS)));\n\n        std::vector<Handle<DefaultProbabilityTermStructure> >\n        defaultIntensityTS;\n        \n        Size defaultTenors[] = {0, 12, 36, 60, 84, 120, 180, 240, 300, \n                                360};// months\n        // Three risk levels:\n        Real intensitiesLow[] = {0.0036, 0.0036, 0.0065, 0.0099, 0.0111, \n                                0.0177, 0.0177, 0.0177, 0.0177, 0.0177, \n                                0.0177};\n        Real intensitiesMedium[] = {0.0202, 0.0202, 0.0231, 0.0266, 0.0278, \n                                0.0349, 0.0349, 0.0349, 0.0349, 0.0349,\n                                0.0349};\n        Real intensitiesHigh[] = {0.0534, 0.0534, 0.0564, 0.06, 0.0614, 0.0696,\n                                0.0696, 0.0696, 0.0696, 0.0696, 0.0696};\n        // Recovery rates:\n        Real ctptyRRLow = 0.4, ctptyRRMedium = 0.35, ctptyRRHigh = 0.3;\n\n        std::vector<Date> defaultTSDates;\n        std::vector<Real> intesitiesVLow, intesitiesVMedium, intesitiesVHigh;\n\n        for(Size i=0; i<sizeof(defaultTenors)/sizeof(Size); i++) {\n        defaultTSDates.push_back(TARGET().advance(todaysDate, \n                Period(defaultTenors[i], Months)));\n        intesitiesVLow.push_back(intensitiesLow[i]);\n        intesitiesVMedium.push_back(intensitiesMedium[i]);\n        intesitiesVHigh.push_back(intensitiesHigh[i]);\n        }\n\n        defaultIntensityTS.emplace_back(ext::shared_ptr<DefaultProbabilityTermStructure>(\n        new InterpolatedHazardRateCurve<BackwardFlat>(defaultTSDates, intesitiesVLow,\n                                                        Actual360(), TARGET())));\n        defaultIntensityTS.emplace_back(ext::shared_ptr<DefaultProbabilityTermStructure>(\n        new InterpolatedHazardRateCurve<BackwardFlat>(defaultTSDates, intesitiesVMedium,\n                                                        Actual360(), TARGET())));\n        defaultIntensityTS.emplace_back(ext::shared_ptr<DefaultProbabilityTermStructure>(\n        new InterpolatedHazardRateCurve<BackwardFlat>(defaultTSDates, intesitiesVHigh,\n                                                        Actual360(), TARGET())));\n\n        Volatility blackVol = 0.15;   \n        ext::shared_ptr<PricingEngine> ctptySwapCvaLow = \n        ext::make_shared<CounterpartyAdjSwapEngine>(\n                Handle<YieldTermStructure>(swapTS), \n                blackVol,\n                defaultIntensityTS[0], \n                ctptyRRLow\n                );\n\n        ext::shared_ptr<PricingEngine> ctptySwapCvaMedium = \n        ext::make_shared<CounterpartyAdjSwapEngine>(\n                Handle<YieldTermStructure>(swapTS), \n                blackVol, \n                defaultIntensityTS[1],\n                ctptyRRMedium);\n        ext::shared_ptr<PricingEngine> ctptySwapCvaHigh = \n        ext::make_shared<CounterpartyAdjSwapEngine>(\n                Handle<YieldTermStructure>(swapTS), \n                blackVol,\n                defaultIntensityTS[2],\n                ctptyRRHigh);\n        \n        defaultIntensityTS[0]->enableExtrapolation();\n        defaultIntensityTS[1]->enableExtrapolation();\n        defaultIntensityTS[2]->enableExtrapolation();\n\n\n        /// SWAP RISKY REPRICE----------------------------------------------\n\n        // fixed leg\n        Frequency fixedLegFrequency = Quarterly;\n        BusinessDayConvention fixedLegConvention = ModifiedFollowing;\n        DayCounter fixedLegDayCounter = ActualActual(ActualActual::ISDA);\n        DayCounter floatingLegDayCounter = ActualActual(ActualActual::ISDA);\n\n        QuantLib::VanillaSwap::Type swapType = QuantLib::VanillaSwap::Payer;\n        ext::shared_ptr<IborIndex> yieldIndxS(\n        new Euribor3M(Handle<YieldTermStructure>(swapTS)));\n        std::vector<VanillaSwap> riskySwaps;\n        for(Size i=0; i<sizeof(tenorsSwapMkt)/sizeof(Size); i++) \n        riskySwaps.push_back(MakeVanillaSwap(tenorsSwapMkt[i]*Years,\n                yieldIndxS,\n                ratesSwapmkt[i], \n                0*Days)\n        .withSettlementDays(2)\n        .withFixedLegDayCount(fixedLegDayCounter)\n        .withFixedLegTenor(Period(fixedLegFrequency))\n        .withFixedLegConvention(fixedLegConvention)\n        .withFixedLegTerminationDateConvention(fixedLegConvention)\n        .withFixedLegCalendar(calendar)\n        .withFloatingLegCalendar(calendar)\n        .withNominal(100.)\n        .withType(swapType));\n\n        std::cout << \"-- Correction in the contract fix rate in bp --\" << std::endl;\n        /* The paper plots correction to be substracted, here is printed\n        with its sign \n        */\n        for(Size i=0; i<riskySwaps.size(); i++) {\n            std::cout << std::fixed << std::setprecision(3);\n            std::cout << std::setw(4);\n            riskySwaps[i].setPricingEngine(riskFreeEngine);\n            // should recover the input here:\n            Real nonRiskyFair = riskySwaps[i].fairRate();\n            std::cout << tenorsSwapMkt[i];\n            std::cout << std::setw(5);\n\n            std::cout << \" | \" << io::rate(nonRiskyFair);\n            std::cout << std::fixed << std::setprecision(2);\n            std::cout << std::setw(5);\n            // Low Risk:\n            riskySwaps[i].setPricingEngine(ctptySwapCvaLow);\n            std::cout << \" | \" << std::setw(6) \n                    << 10000.*(riskySwaps[i].fairRate() - nonRiskyFair);\n            //cout << \" | \" << setw(6) << riskySwaps[i].NPV() ;\n\n            // Medium Risk:\n            riskySwaps[i].setPricingEngine(ctptySwapCvaMedium);\n            std::cout << \" | \" << std::setw(6) \n                    << 10000.*(riskySwaps[i].fairRate() - nonRiskyFair);\n            //cout << \" | \" << setw(6) << riskySwaps[i].NPV() ;\n\n            riskySwaps[i].setPricingEngine(ctptySwapCvaHigh);\n            std::cout << \" | \" << std::setw(6) \n                    << 10000.*(riskySwaps[i].fairRate() - nonRiskyFair);\n            //cout << \" | \" << setw(6) << riskySwaps[i].NPV() ;\n\n            std::cout << std::endl;\n        }\n\n        std::cout << std::endl;\n        std::cout << \"JDATA\" << std::setw(4) << jData << std::endl;\n        std::string result = jData.dump();\n        return result;\n\n    } \n    \n    catch (std::exception& e) {\n        std::cerr << e.what() << std::endl;\n        return \"1\";\n    } \n    \n    catch (...) {\n        std::cerr << \"unknown error\" << std::endl;\n        return \"1\";\n    }\n}\n", "meta": {"hexsha": "75f452c9637f2673c6e64d5b4e569d3b9d75f6d1", "size": 61023, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ql/webAPI.cpp", "max_stars_repo_name": "ohavb/QuantLib", "max_stars_repo_head_hexsha": "c166722d0ae721ac238522f57ae372c30a9dfc21", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/webAPI.cpp", "max_issues_repo_name": "ohavb/QuantLib", "max_issues_repo_head_hexsha": "c166722d0ae721ac238522f57ae372c30a9dfc21", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/webAPI.cpp", "max_forks_repo_name": "ohavb/QuantLib", "max_forks_repo_head_hexsha": "c166722d0ae721ac238522f57ae372c30a9dfc21", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.3314470493, "max_line_length": 208, "alphanum_fraction": 0.5511692313, "num_tokens": 13006, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4548193603519451}}
{"text": "#ifndef ASLAM_CAMERAS_EQUI_DISTORTION_HPP\n#define ASLAM_CAMERAS_EQUI_DISTORTION_HPP\n\n#include <eigen3/Eigen/Dense>\n#include <boost/serialization/nvp.hpp>\n#include \"StaticAssert.hpp\"\n#include <sm/PropertyTree.hpp>\n#include <boost/serialization/split_member.hpp>\n#include <boost/serialization/version.hpp>\n#include <sm/boost/serialization.hpp>\n\nnamespace aslam {\nnamespace cameras {\n\n/**\n * \\class EquidistantDistortion\n * \\brief An implementation of the equidistant distortion model for pinhole cameras.\n *        \n * See \"A Generic Camera Model and Calibration Method for Conventional, Wide-Angle, and Fish-Eye Lenses\" by Juho Kannala and Sami S. Brandt for further information\n *\n *\n * The usual model of a pinhole camera follows these steps:\n *   - Transformation: Transform the point into a coordinate frame associated with the camera\n *   - Normalization:  Project the point onto the normalized image plane: \\f$\\mathbf y := \\left[ x/z,y/z\\right] \\f$\n *   - Distortion:     apply a nonlinear transformation to \\f$y\\f$ to account for distortions caused by the optics\n *   - Projection:     Project the point into the image using a standard \\f$3 \\time 3\\f$ projection matrix\n *\n * This class represents a standard implementation of the distortion block. The function \"distort\" applies this nonlinear transformation.\n * The function \"undistort\" applies the inverse transformation. Note that the inverse transformation in this case is not avaialable in \n * closed form and so it is computed iteratively.\n * \n */\nclass EquidistantDistortion {\n public:\n\n  enum {\n    IntrinsicsDimension = 4\n  };\n  enum {\n    DesignVariableDimension = IntrinsicsDimension\n  };\n\n  /// \\brief The default constructor sets all values to zero. \n  EquidistantDistortion();\n\n  /// \\brief A constructor that initializes all values.\n  EquidistantDistortion(double k1, double k2, double k3, double k4);\n\n  /// \\brief initialize from a property tree\n  EquidistantDistortion(const sm::PropertyTree & config);\n\n  virtual ~EquidistantDistortion();\n\n  /** \n   * \\brief Apply distortion to a point in the normalized image plane\n   * \n   * @param y The point in the normalized image plane. After the function, this point is distorted.\n   */\n  template<typename DERIVED_Y>\n  void distort(const Eigen::MatrixBase<DERIVED_Y> & y) const;\n\n  /** \n   * \n   * \\brief Apply distortion to a point in the normalized image plane\n   * \n   * @param y The point in the normalized image plane. After the function, this point is distorted.\n   * @param outJy The Jacobian of the distortion function with respect to small changes in the input point.\n   */\n  template<typename DERIVED_Y, typename DERIVED_JY>\n  void distort(const Eigen::MatrixBase<DERIVED_Y> & y,\n               const Eigen::MatrixBase<DERIVED_JY> & outJy) const;\n\n  /** \n   * \\brief Apply undistortion to recover a point in the normalized image plane.\n   * \n   * @param y The distorted point. After the function, this point is in the normalized image plane.\n   */\n  template<typename DERIVED>\n  void undistort(const Eigen::MatrixBase<DERIVED> & y) const;\n\n  /** \n   * \\brief Apply undistortion to recover a point in the normalized image plane.\n   * \n   * @param y The distorted point. After the function, this point is in the normalized image plane.\n   * @param outJy The Jacobian of the undistortion function with respect to small changes in the input point.\n   */\n  template<typename DERIVED, typename DERIVED_JY>\n  void undistort(const Eigen::MatrixBase<DERIVED> & y,\n                 const Eigen::MatrixBase<DERIVED_JY> & outJy) const;\n\n  /** \n   * \\brief Apply distortion to the point and provide the Jacobian of the distortion with respect to small changes in the distortion parameters\n   * \n   * @param imageY the point in the normalized image plane.\n   * @param outJd  the Jacobian of the distortion with respect to small changes in the distortion parameters.\n   */\n  template<typename DERIVED_Y, typename DERIVED_JD>\n  void distortParameterJacobian(\n      const Eigen::MatrixBase<DERIVED_Y> & imageY,\n      const Eigen::MatrixBase<DERIVED_JD> & outJd) const;\n\n  /** \n   * \\brief A function for compatibility with the aslam backend. This implements an update of the distortion parameter.\n   * \n   * @param v A double array representing the update vector.\n   */\n  void update(const double * v);\n\n  /** \n   * \\brief A function for compatibility with the aslam backend. \n   * \n   * @param v The number of parameters expected by the update equation. This should also define the number of columns in the matrix returned by distortParameterJacobian.\n   */\n  int minimalDimensions() const;\n\n  /** \n   * \\brief A function for compatibility with the aslam backend. \n   * \n   * @param P This matrix is resized and filled with parameters representing the full state of the distortion. \n   */\n  void getParameters(Eigen::MatrixXd & P) const;\n\n  /** \n   * \\brief A function for compatibility with the aslam backend. \n   * \n   * @param P The full state of the distortion class is set from the matrix of parameters.\n   */\n  void setParameters(const Eigen::MatrixXd & P);\n\n  Eigen::Vector2i parameterSize() const;\n\n  /// \\brief the first radial distortion parameter\n  double k1() {\n    return _k1;\n  }\n  /// \\brief the second radial distortion parameter\n  double k2() {\n    return _k2;\n  }\n  /// \\brief the first tangential distortion parameter\n  double k3() {\n    return _k3;\n  }\n  /// \\brief the second tangential distortion parameter\n  double k4() {\n    return _k4;\n  }\n\n  /// \\brief Compatibility with boost::serialization.\n  enum {\n    CLASS_SERIALIZATION_VERSION = 0\n  };BOOST_SERIALIZATION_SPLIT_MEMBER();\n\n  template<class Archive>\n  void load(Archive & ar, const unsigned int version);\n\n  template<class Archive>\n  void save(Archive & ar, const unsigned int version) const;\n\n  bool isBinaryEqual(const EquidistantDistortion & rhs) const;\n\n  static EquidistantDistortion getTestDistortion();\n\n  void clear();\n\n  /// \\brief the first distortion parameter\n  double _k1;\n  /// \\brief the second distortion parameter\n  double _k2;\n  /// \\brief the third distortion parameter\n  double _k3;\n  /// \\brief the forth distortion parameter\n  double _k4;\n\n};\n\n}  // namespace cameras\n}  // namespace aslam\n\n#include \"implementation/EquidistantDistortion.hpp\"\n\nSM_BOOST_CLASS_VERSION (aslam::cameras::EquidistantDistortion);\n\n#endif /* ASLAM_CAMERAS_EQUI_DISTORTION_HPP */\n", "meta": {"hexsha": "c71df419ff261c82e148553a44b3d6fcbd5cd7bf", "size": 6373, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "aslam_cv/aslam_cameras/include/aslam/cameras/EquidistantDistortion.hpp", "max_stars_repo_name": "mmmspatz/kalibr", "max_stars_repo_head_hexsha": "e2e881e5d25d378f0c500c67e00532ee1c1082fd", "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_cv/aslam_cameras/include/aslam/cameras/EquidistantDistortion.hpp", "max_issues_repo_name": "mmmspatz/kalibr", "max_issues_repo_head_hexsha": "e2e881e5d25d378f0c500c67e00532ee1c1082fd", "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_cv/aslam_cameras/include/aslam/cameras/EquidistantDistortion.hpp", "max_forks_repo_name": "mmmspatz/kalibr", "max_forks_repo_head_hexsha": "e2e881e5d25d378f0c500c67e00532ee1c1082fd", "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": 34.4486486486, "max_line_length": 169, "alphanum_fraction": 0.7260316962, "num_tokens": 1546, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4548193603519451}}
{"text": "#ifndef INCLUDED_DENSITY_VISUALIZATION_HPP\n#define INCLUDED_DENSITY_VISUALIZATION_HPP\n\n#include <Danvil/Color.h>\n#include <Slimage/Slimage.hpp>\n#include <Eigen/Dense>\n#include <vector>\n\nnamespace density\n{\n\n\tinline Eigen::Vector3f DensityColor(float x, float a, float b)\n\t{\n\t\tstatic auto cm = Danvil::ContinuousIntervalColorMapping<float, float>::Factor_Black_Blue_Red_Yellow_White();\n\t\tcm.setRange(a, b);\n\t\tDanvil::Colorf color = cm(x);\n\t\treturn {color.r,color.g,color.b};\n\t}\n\n\tinline Eigen::Vector3f DeltaDensityColor(float x, float a)\n\t{\n\t\tstatic auto cm = Danvil::ContinuousIntervalColorMapping<float, float>::Factor_MinusPlus();\n\t\tcm.setRange(-a, +a);\n\t\tDanvil::Colorf color = cm(x);\n\t\treturn {color.r,color.g,color.b};\n\t}\n\n\tslimage::Image3ub PlotDensity(const Eigen::MatrixXf& d, float a, float b);\n\n\tslimage::Image3ub PlotDensity(const Eigen::MatrixXf& d);\n\n\tslimage::Image3ub PlotDeltaDensity(const Eigen::MatrixXf& dd, float a);\n\n\tslimage::Image3ub PlotDeltaDensity(const Eigen::MatrixXf& dd);\n\n\tslimage::Image3ub PlotDeltaDensity(const Eigen::MatrixXf& actual, const Eigen::MatrixXf& reference);\n\n}\n\n#endif\n", "meta": {"hexsha": "789f4e5c6b9d50e57dd5766d8ed2b82e4ad3c0ef", "size": 1117, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib_dasp/lib_dasp_density/density/Visualization.hpp", "max_stars_repo_name": "jbellis/superpixel-benchmark", "max_stars_repo_head_hexsha": "81a45649d426751d1ae450ef8ea0d2d9c7b3545f", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 344.0, "max_stars_repo_stars_event_min_datetime": "2016-12-16T10:11:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T06:08:14.000Z", "max_issues_repo_path": "lib_dasp/lib_dasp_density/density/Visualization.hpp", "max_issues_repo_name": "jbellis/superpixel-benchmark", "max_issues_repo_head_hexsha": "81a45649d426751d1ae450ef8ea0d2d9c7b3545f", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2018-02-15T19:34:19.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-31T17:04:48.000Z", "max_forks_repo_path": "lib_dasp/lib_dasp_density/density/Visualization.hpp", "max_forks_repo_name": "jbellis/superpixel-benchmark", "max_forks_repo_head_hexsha": "81a45649d426751d1ae450ef8ea0d2d9c7b3545f", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 111.0, "max_forks_repo_forks_event_min_datetime": "2016-12-08T07:19:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T06:08:16.000Z", "avg_line_length": 27.243902439, "max_line_length": 110, "alphanum_fraction": 0.7529095792, "num_tokens": 307, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4548193603519451}}
{"text": "#include <bits/stdc++.h>\n#include <boost/tokenizer.hpp>\n\nstruct FieldSpec {\n  std::string field_name;\n  std::vector<std::pair<uint, uint>> ranges;\n  uint field_id;\n\n  bool is_value_ok(uint value) {\n    for (auto &[a, b]: ranges) \n      if (value >= a && value <= b)\n        return true;\n    return false;\n  }\n};\nbool operator==(const FieldSpec &f1, const FieldSpec &f2) {\n  return f1.field_name == f2.field_name;\n}\nbool operator<(const FieldSpec &f1, const FieldSpec &f2) {\n  return f1.field_name < f2.field_name;\n}\n\nstd::vector<FieldSpec> fields;\n\nusing Ticket = std::vector<uint>;\nTicket my_ticket;\nstd::vector<Ticket> tickets; \nstd::vector<Ticket> valid_tickets;\n\n\nvoid part1() {\n  uint error = 0;\n  for (auto &t: tickets) {\n    bool is_valid = true;\n    for (auto v: t) {\n      bool valid = false; \n      for (auto &f: fields) {\n        valid = f.is_value_ok(v);\n        if (valid)\n          break;\n      }\n\n      if (!valid) {\n        error += v;\n        is_valid = false;\n      }\n    }\n\n    if (is_valid)\n      valid_tickets.push_back(t);\n  }\n\n  std::cout << \"Part 1 : \" << error << std::endl;\n}\n\nusing Set = std::set<int>;\nvoid eliminate() {\n  const uint Nf = fields.size();\n\n  std::vector<bool> def(Nf, false);\n  std::vector<std::vector<bool>> valid(Nf, def);\n\n  // 1- Initialize\n  std::vector<int> count_field;\n\n  auto update_counts = [&]() {\n    count_field.clear();\n    count_field.resize(Nf, 0);\n\n    for (uint i=0; i < Nf; ++i) {\n      for (uint j=0; j < Nf; ++j) {\n        if (valid[i][j])\n          count_field[i]++;\n      }\n    }\n  };\n\n  // 2- Filling validity matrix\n  for (uint fi=0; fi < Nf; ++fi) {\n    FieldSpec &f = fields[fi];\n\n    for (uint pos=0; pos < Nf; ++pos) {\n      bool is_valid = true;\n      for (auto t: valid_tickets) {\n        if (!f.is_value_ok(t[pos])) {\n          is_valid = false;\n          break;\n        }\n      }\n\n      valid[fi][pos] = is_valid;\n    }\n  }\n\n  auto done = [&]() {\n    bool res = true;\n    for (auto c: count_field)\n      if (c!=0)\n        return false;\n    \n    return true;\n  };\n\n  // And iterating on solutions \n  update_counts();\n  while (!done()) {\n    int idf = -1;\n    // Finding the field that is alone\n    for (int i=0; i < Nf; ++i) {\n      if (count_field[i] == 1) {\n        idf = i;\n        break;\n      }\n    }\n\n    // Finding its position\n    int pos_id;\n    for (int j=0; j < Nf; ++j) {\n      if (valid[idf][j]) {\n        pos_id = j;\n        break;\n      }\n    }\n\n    // Associating then removing it from the table\n    fields[idf].field_id = pos_id;\n\n    for (int i=0; i < Nf; ++i) {\n      valid[idf][i] = false;\n      valid[i][pos_id] = false;\n    }\n\n    //std::cout << \"Field #\" << pos_id << \" is \" << fields[idf].field_name << std::endl;\n    // And looping\n    update_counts();\n  }\n}\n\nvoid part2() {\n  eliminate();\n\n  uint64_t res = 1;\n  for (auto f: fields) {\n    if (f.field_name.find(\"departure\") != std::string::npos) {\n      res *= my_ticket[f.field_id];\n    }\n  }\n\n  std::cout << \"Part 2 : \" << res << std::endl;\n} \n\nint mode = 0;\n\nstd::regex field_re(\"([a-z\\\\ ]+):(.*)\");\nstd::regex range_re(\"([0-9]+)-([0-9]+)\");\n\nvoid read_field_spec(std::string line) {\n  std::smatch match;\n  std::regex_search(line, match, field_re);\n  FieldSpec field;\n  field.field_name = match[1];\n  std::string ranges = match[2];\n  std::smatch range_match;\n\n  while(std::regex_search(ranges, range_match, range_re)) {\n    uint min_val = std::stoi(range_match[1]);\n    uint max_val = std::stoi(range_match[2]);\n    field.ranges.push_back(std::make_pair(min_val, max_val));\n    ranges = range_match.suffix();\n  }\n\n  fields.push_back(field);\n}\n\nvoid read_ticket(std::string line, bool mine) {\n  boost::char_separator<char> sep{\",\"};  \n  boost::tokenizer tokenizer{line, sep};\n  Ticket ticket;\n  for (const auto &t: tokenizer)\n    ticket.push_back(std::stoi(t));\n\n  if (mine)\n    my_ticket = ticket;\n  else \n    tickets.push_back(ticket);\n}\n\nint main(int argc, char **argv) {\n  std::ifstream f_in;\n  f_in.open(\"16.in\");\n\n  while (!f_in.eof()) {\n    std::string line;\n    std::getline(f_in, line);\n\n    if (line == \"\") {\n      mode++;\n      if (mode > 0)\n        std::getline(f_in, line);\n    }\n    else {\n      switch(mode) {\n        case 0: read_field_spec(line);    break;\n        case 1: read_ticket(line, true);  break;\n        case 2: read_ticket(line, false); break;\n      }\n    }\n  }\n  f_in.close();\n\n  part1();\n  part2();\n  return 0;\n}", "meta": {"hexsha": "ee347aebd8733d54dfe669dc8562f779852719b3", "size": 4395, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "2020/16.cpp", "max_stars_repo_name": "mdelorme/advent_of_code", "max_stars_repo_head_hexsha": "47142d501055fc0d36989db9b189be7e6756d779", "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": "2020/16.cpp", "max_issues_repo_name": "mdelorme/advent_of_code", "max_issues_repo_head_hexsha": "47142d501055fc0d36989db9b189be7e6756d779", "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": "2020/16.cpp", "max_forks_repo_name": "mdelorme/advent_of_code", "max_forks_repo_head_hexsha": "47142d501055fc0d36989db9b189be7e6756d779", "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": 20.5373831776, "max_line_length": 88, "alphanum_fraction": 0.5549488055, "num_tokens": 1314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943603346811, "lm_q2_score": 0.6001883592602051, "lm_q1q2_score": 0.4548193537859089}}
{"text": "#include <algorithm>\n#include <memory>\n#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <string>\n#include <vector>\n#include <queue>\n#include <set>\n#include <map>\n#include <cstdio>\n#include <cstdlib>\n#include <cctype>\n#include <cmath>\n#include <climits>\n#include <numeric>\n\n#include <Eigen/Dense>\n\n#undef N_DEBUG\n#include <assert.h>\n\n#define loop(x,n) for(std::size_t (x) = 0; (x) < (n); ++(x))\n\nusing namespace std;\n\nusing UInt = uint64_t;\nusing Int = int64_t;\nusing Vector3d = Eigen::Matrix<double, 3, 1>;\n\nstruct Asteroid\n{\n  using Ptr = std::shared_ptr<Asteroid>;\n  using ConstPtr = std::shared_ptr<const Asteroid>;\n\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n\n  Asteroid()  {}\n  Asteroid(Vector3d pos, Vector3d vel)\n    : position(pos)\n    , velocity(vel)\n  {}\n\n  Vector3d position;\n  Vector3d velocity;\n};\n\ndouble getMinDistance(Asteroid::ConstPtr a, Asteroid::ConstPtr b)\n{\n  const auto w = a->position - b->position;\n  const auto v = a->velocity - b->velocity;\n  const auto t_cpa = -w.dot(v) / v.squaredNorm();\n  const auto p_a = a->position + t_cpa * a->velocity;\n  const auto p_b = b->position + t_cpa * b->velocity;\n  return (p_a - p_b).norm();\n}\n\ndouble getMinDistanceWithin(Asteroid::ConstPtr a, Asteroid::ConstPtr b, double t_min, double t_max)\n{\n  const auto w = a->position - b->position;\n  const auto v = a->velocity - b->velocity;\n  const auto t_cpa = -w.dot(v) / v.squaredNorm();\n\n  double t;\n  if (t_cpa < t_min)\n    t = t_min;\n  else if (t_cpa > t_max)\n    t = t_max;\n  else\n    t = t_cpa;\n\n  const auto p_a = a->position + t * a->velocity;\n  const auto p_b = b->position + t * b->velocity;\n  return (p_a - p_b).norm();\n}\n\nstruct Edge\n{\n  Edge(size_t first, size_t second, double weight)\n    : first_vertex(first)\n    , second_vertex(second)\n    , weight(weight)\n  {}\n  size_t first_vertex;\n  size_t second_vertex;\n  double weight;\n\n  bool operator <(const Edge& other) const\n  {\n    if (weight != other.weight)\n      return weight < other.weight;\n    if (first_vertex != other.first_vertex)\n      return first_vertex < other.first_vertex;\n    return second_vertex < other.second_vertex;\n  }\n  bool contains(size_t vertex) const  { return first_vertex == vertex || second_vertex == vertex; }\n  size_t getOther(size_t vertex) const\n  {\n    if (first_vertex == vertex)\n      return second_vertex;\n    return first_vertex;\n  }\n};\n\nstruct Cluster\n{\n  Cluster() {}\n  Cluster(const auto& asteroids, auto velocity)\n    : asteroids(asteroids)\n    , velocity(velocity)\n  {}\n  Cluster(const auto& asteroid)\n    : asteroids({asteroid})\n    , velocity(asteroid->velocity)\n  {}\n\n  double getMaxJumpDistance(Asteroid::ConstPtr start, Asteroid::ConstPtr end) const\n  {\n    const auto s = find(asteroids.cbegin(), asteroids.cend(), start);\n    if (s == asteroids.cend())\n      throw (int)1;\n\n    size_t index_start = std::distance(asteroids.cbegin(), s);\n\n    const auto e = find(asteroids.cbegin(), asteroids.cend(), end);\n    if (e == asteroids.cend())\n      throw (int)2;\n\n    size_t index_end = std::distance(asteroids.cbegin(), e);\n\n    auto unexplored = edges;\n    set<size_t> explored;\n    explored.insert(index_start);\n    double max_jump = 0.0;\n    size_t added = 0;\n    do\n    {\n      for (auto it = unexplored.begin(); it != unexplored.end(); it++)\n      {\n        const auto first_it = explored.find(it->first_vertex);\n        const auto second_it = explored.find(it->second_vertex);\n\n        auto ex = explored.cend();\n        if (first_it != explored.cend())\n          ex = first_it;\n        else if (second_it != explored.cend())\n          ex = second_it;\n        else\n          continue;\n\n        added = it->getOther(*ex);\n        explored.insert(added);\n        if (it->weight > max_jump)\n          max_jump = it->weight;\n        unexplored.erase(it);\n\n        break;\n      }\n    }\n    while (added != index_end);\n\n    return sqrt(max_jump);\n  }\n\n  const vector<Asteroid::ConstPtr> getAllReachedAsteroids(Asteroid::ConstPtr start, double max_jump)\n  {\n    max_jump = max_jump*max_jump;\n\n    const auto s = find(asteroids.cbegin(), asteroids.cend(), start);\n    if (s == asteroids.cend())\n      throw (int)3;\n\n    vector<Asteroid::ConstPtr> reached({start});\n    size_t index_start = std::distance(asteroids.cbegin(), s);\n\n    vector<bool> explored(asteroids.size(), false);\n    explored[index_start] = true;\n\n    size_t added;\n    do\n    {\n      added = asteroids.size();\n\n      loop(ex, explored.size())\n      {\n        if (!explored[ex])\n          continue;\n\n        loop(unex, explored.size())\n        {\n          if (explored[unex])\n            continue;\n\n          if (getWeight(ex, unex) <= max_jump)\n          {\n            added = unex;\n            explored[unex] = true;\n            break;\n          }\n          \n        }\n        if (added != asteroids.size())\n          break;\n\n      }\n\n      reached.push_back(asteroids[added]);\n\n    }\n    while (added < asteroids.size());\n\n    return reached;\n  }\n\n  vector<Asteroid::Ptr> asteroids;\n  Vector3d velocity;\n\n  double getWeight(size_t first, size_t second) const\n  {\n    assert(first != second);\n    const auto min_index = min(first, second);\n    const auto max_index = max(first, second);\n    return weights[min_index][max_index-min_index-1];\n  }\n  void calcWeights()\n  {\n    weights.resize(asteroids.size() - 1);\n    loop(ii, asteroids.size() - 1)\n    {\n      weights[ii].reserve(asteroids.size() - ii - 1); \n      for (size_t jj = ii + 1; jj < asteroids.size(); ++jj)\n      {\n        weights[ii].push_back((asteroids[ii]->position - asteroids[jj]->position).squaredNorm());\n        edges.emplace(ii, jj, weights[ii].back());\n      }\n    }\n  }\n  vector<vector<double>> weights;\n  set<Edge> edges;\n};\n\n\nint main()\n{\n  size_t num_test_cases;\n  cin >> num_test_cases;\n\n  for (size_t i = 0; i < num_test_cases; i++)\n  {\n    size_t N, S;\n    cin >> N >> S;\n\n    vector<Asteroid::Ptr> asteroids;\n    asteroids.reserve(N);\n\n    loop(ii, N)\n    {\n      Vector3d pos;\n      Vector3d vel;\n\n      cin >> pos[0] >> pos[1] >> pos[2]\n          >> vel[0] >> vel[1] >> vel[2];\n\n      Asteroid a;\n      a.position = pos;\n      a.velocity = vel;\n      asteroids.emplace_back(make_shared<Asteroid>(pos, vel));\n    }\n\n    // sort into clusters\n    vector<Cluster> clusters;\n    for (const auto& a : asteroids)\n    {\n      const auto it = std::find_if(clusters.begin(), clusters.end(), [&a](const vector<Cluster>::value_type& c){\n          return c.velocity == a->velocity;});\n\n      if (it == clusters.end())\n      {\n        clusters.emplace_back(a);\n      }\n      else\n      {\n        it->asteroids.push_back(a);\n      }\n    }\n\n    //cout <<\"Number of clusters: \" <<clusters.size() <<endl;\n    for (auto& a : clusters)\n      a.calcWeights();\n\n    double res = 0.0;\n    if (clusters.size() == 1)\n    {\n      res = clusters.front().getMaxJumpDistance(asteroids[0], asteroids[1]);\n      std::cout <<\"Case #\" <<(i+1) <<\": \"  <<setprecision(10) <<res <<endl;\n    }\n    else\n    {\n      if (asteroids[0]->velocity != asteroids[1]->velocity)\n        res = getMinDistanceWithin(asteroids[0], asteroids[1], 0.0, S);\n      else\n        res = -1.0;\n\n      std::cout <<\"Case #\" <<(i+1) <<\": \"  <<setprecision(10) <<res <<endl;\n    }\n\n    \n\n  }\n  \n  return 0;\n}\n", "meta": {"hexsha": "bc1db55eef0d3d016fcd5e07a18a85f44b4eaaf3", "size": 7224, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "2016_Round_3/C_Rebel_Against_The_Empire/template.cpp", "max_stars_repo_name": "risteon/code_jam", "max_stars_repo_head_hexsha": "db6941a6926042c8ae125a4996322f00e83f728f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2016_Round_3/C_Rebel_Against_The_Empire/template.cpp", "max_issues_repo_name": "risteon/code_jam", "max_issues_repo_head_hexsha": "db6941a6926042c8ae125a4996322f00e83f728f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2016_Round_3/C_Rebel_Against_The_Empire/template.cpp", "max_forks_repo_name": "risteon/code_jam", "max_forks_repo_head_hexsha": "db6941a6926042c8ae125a4996322f00e83f728f", "max_forks_repo_licenses": ["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.0798722045, "max_line_length": 112, "alphanum_fraction": 0.5978682171, "num_tokens": 1967, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711680567799, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.45481823640510843}}
{"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\u00c3\u00a4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include <iostream>\n#include <boost/numeric/mtl/mtl.hpp>\n\n\nusing namespace std;\n\nint main(int argc, char** argv) \n{\n    using namespace mtl;\n\n    using mblock= matrix<double, dim<2, 2> >;\n    using vblock= mtl::vector<double, dim<2> >;\n\n    using mtype= matrix<mblock, sparse>;\n    using vtype= mtl::vector<vblock>;\n\n    mtype A(2, 3);\n    {\n\tmat::inserter<mtype> ins(A);\n\tmblock mb;\n\tmb[0][0]= 1; mb[0][1]= 2; \n\tmb[1][0]= 3; mb[1][1]= 4;\n\n\tins[0][0] << mb;\n\n\tmb[1][1]= 5;\n\tins[1][1] << mb;\n\n\t// ins(0, 0) << mblock{{1, 2}, {3, 4}};\n\t// ins[1][1] << mblock{{3, 4}, {5, 6}};\n    }\n    // cout << \"A = \" << A;\n\n    vtype x{vblock{1, 3}, vblock{1, 2}, vblock{9, 3}};\n    cout << \"x = \" << x << endl;\n\n    vtype y( A * x );\n    cout << \"y= \" << y << endl;\n\n    return 0;\n}\n \n", "meta": {"hexsha": "2d73c0486a91202c240d9ecbc94db4ef4eddacd4", "size": 1216, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/experimental/block_matrix_2x2.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/mtl/experimental/block_matrix_2x2.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/mtl/experimental/block_matrix_2x2.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": 22.1090909091, "max_line_length": 94, "alphanum_fraction": 0.5740131579, "num_tokens": 430, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4547990519723086}}
{"text": "/*\n@copyright Louis Dionne 2014\nDistributed under the Boost Software License, Version 1.0.\n(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n */\n\n#include <boost/hana/identity.hpp>\n\n#include <boost/hana/detail/assert.hpp>\n#include <boost/hana/detail/minimal/orderable.hpp>\n#include <boost/hana/functional.hpp>\n#include <boost/hana/list/instance.hpp>\n#include <boost/hana/logical/logical.hpp>\n#include <boost/hana/orderable/laws.hpp>\nusing namespace boost::hana;\n\n\nauto implies = infix([](auto p, auto q) {\n    return or_(not_(p), q);\n});\n\nauto iff = infix([](auto p, auto q) {\n    return and_(p ^implies^ q, q ^implies^ p);\n});\n\nauto check = [](auto x, auto y) {\n    return less(x, y) ^iff^ less(identity(x), identity(y));\n};\n\nint main() {\n    constexpr auto x = detail::minimal::orderable<>(1);\n    constexpr auto y = detail::minimal::orderable<>(2);\n    constexpr auto z = detail::minimal::orderable<>(3);\n\n    BOOST_HANA_CONSTEXPR_ASSERT(\n        all_of(ap(list(check), list(x, y, z), list(x, y, z)))\n    );\n\n    BOOST_HANA_CONSTEXPR_ASSERT(Orderable::laws::check(\n        list(identity(x), identity(y), identity(z))\n    ));\n}\n", "meta": {"hexsha": "2ab73994d94eab7df5e337fa9c595b4fbb7ae865", "size": 1159, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/identity/orderable.cpp", "max_stars_repo_name": "rbock/hana", "max_stars_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-05-07T14:29:13.000Z", "max_stars_repo_stars_event_max_datetime": "2015-07-04T10:59:46.000Z", "max_issues_repo_path": "test/identity/orderable.cpp", "max_issues_repo_name": "rbock/hana", "max_issues_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/identity/orderable.cpp", "max_forks_repo_name": "rbock/hana", "max_forks_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9534883721, "max_line_length": 78, "alphanum_fraction": 0.6729939603, "num_tokens": 312, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4547990519723086}}
{"text": "#include <boost/test/unit_test.hpp>\n#include \"functions/multi_matrix_reduction.hh\"\n#include <boost/mpl/distance.hpp>\n\nBOOST_AUTO_TEST_CASE(multi_matrix_reduction_test) {\n  using namespace manifolds;\n  Reduction<ReduxPair<0, 1> > r;\n  MultiMatrix<double, 3, 3, 1> m(0, 1, 2, 0, 1, 4, 1, 2, 9);\n  BOOST_CHECK_EQUAL(r(m).Coeff(0), 10);\n  Reduction<ReduxPair<1, 2> > r2;\n  MultiMatrix<double, 1, 3> m2(0, 1, 2);\n  MultiMatrix<double, 3, 1> m3(0, 1, 2);\n  auto m4 = m2 * m3;\n  static_assert(decltype(m4)::dimension<0>::value == 1,\n                \"Error conglomerating MultiMatrices' dimensions\");\n  static_assert(decltype(m4)::dimension<1>::value == 3,\n                \"Error conglomerating MultiMatrices' dimensions\");\n  static_assert(decltype(m4)::dimension<2>::value == 3,\n                \"Error conglomerating MultiMatrices' dimensions\");\n  static_assert(decltype(m4)::dimension<3>::value == 1,\n                \"Error conglomerating MultiMatrices' dimensions\");\n  BOOST_CHECK_EQUAL(r2(m4).Coeff(0, 0), 5);\n  auto m5 = r2(m3 * m2);\n  BOOST_CHECK_EQUAL(m5.Coeff(0, 0), 0);\n  BOOST_CHECK_EQUAL(m5.Coeff(0, 1), 0);\n  BOOST_CHECK_EQUAL(m5.Coeff(0, 2), 0);\n  BOOST_CHECK_EQUAL(m5.Coeff(1, 0), 0);\n  BOOST_CHECK_EQUAL(m5.Coeff(1, 1), 1);\n  BOOST_CHECK_EQUAL(m5.Coeff(1, 2), 2);\n  BOOST_CHECK_EQUAL(m5.Coeff(2, 0), 0);\n  BOOST_CHECK_EQUAL(m5.Coeff(2, 1), 2);\n  BOOST_CHECK_EQUAL(m5.Coeff(2, 2), 4);\n}\n", "meta": {"hexsha": "3b9f134c1becf5ef50e885827c97ef411e025d71", "size": 1393, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "functions/tests/test_multi_matrix_reduction.cpp", "max_stars_repo_name": "GuylainGreer/manifolds", "max_stars_repo_head_hexsha": "96f996f67fc523c726f2edbc9705125c212bedae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "functions/tests/test_multi_matrix_reduction.cpp", "max_issues_repo_name": "GuylainGreer/manifolds", "max_issues_repo_head_hexsha": "96f996f67fc523c726f2edbc9705125c212bedae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "functions/tests/test_multi_matrix_reduction.cpp", "max_forks_repo_name": "GuylainGreer/manifolds", "max_forks_repo_head_hexsha": "96f996f67fc523c726f2edbc9705125c212bedae", "max_forks_repo_licenses": ["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.9705882353, "max_line_length": 66, "alphanum_fraction": 0.6676238335, "num_tokens": 482, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.45479904593532317}}
{"text": "#ifndef FIRST_ORDER_VISIBILITY_GRAPH_HPP\n#define FIRST_ORDER_VISIBILITY_GRAPH_HPP\n\n#include <memory>\n#include <functional>\n#include <Eigen/Core>\n#include <omp.h>\n#include <ros/ros.h>\n#include <visualization_msgs/MarkerArray.h>\n#include \"arc_utilities/arc_helpers.hpp\"\n\nnamespace arc_utilities\n{\n    class FirstOrderVisibilityGraph\n    {\n        public:\n            typedef std::pair<ssize_t, ssize_t> ConfigType;\n            typedef std::pair<ConfigType, double> ConfigAndDistType;\n            typedef std::function<bool(const ssize_t row, const ssize_t col)> ValidityCheckFnType;\n\n            static double ConfigTypeDistance(const ConfigType& c1, const ConfigType& c2)\n            {\n                return Eigen::Vector2d((double)(c1.first - c2.first), (double)(c1.second - c2.second)).norm();\n            }\n\n            struct BestFirstSearchComparator\n            {\n                public:\n                    // Defines a \"less\" operation\"; by using \"greater\" then the smallest element will appear at the top of the priority queue\n                    bool operator()(const ConfigAndDistType& c1, const ConfigAndDistType& c2) const\n                    {\n                        // If expected distances are different, we want to explore the one with the smaller expected distance\n                        return (c1.second > c2.second);\n                    }\n            };\n\n            static bool CheckFirstOrderVisibility(const ssize_t rows, const ssize_t cols, const ValidityCheckFnType& validity_check_fn, const bool visualization_enabled = true)\n            {\n                assert(rows > 0 && cols > 0);\n                typedef Eigen::Array<bool, Eigen::Dynamic, Eigen::Dynamic> ArrayXb;\n\n                ros::NodeHandle nh;\n                ros::Publisher marker_pub = nh.advertise<visualization_msgs::Marker>(\"visualization_marker\", 1000, true);\n\n                visualization_msgs::Marker marker;\n                {\n                    marker.header.frame_id = \"mocap_world\";\n                    marker.type = visualization_msgs::Marker::POINTS;\n                    marker.action = visualization_msgs::Marker::ADD;\n                    marker.ns = \"explored_states\";\n                    marker.id = 1;\n                    marker.scale.x = 1.0;\n                    marker.scale.y = 1.0;\n                    marker.header.stamp = ros::Time::now();\n                    marker_pub.publish(marker);\n                    marker.color = arc_helpers::RGBAColorBuilder<std_msgs::ColorRGBA>::MakeFromFloatColors(0.0, 0.0, 1.0, 1.0);\n                }\n\n                const ConfigType start(0, 0), goal(rows - 1, cols - 1);\n                const auto heuristic_distance_fn = [&goal] (const ConfigType& config) { return ConfigTypeDistance(config, goal); };\n\n                std::priority_queue<ConfigAndDistType, std::vector<ConfigAndDistType>, BestFirstSearchComparator> frontier;\n                ArrayXb explored = ArrayXb::Constant(rows, cols, false);\n\n                frontier.push(ConfigAndDistType(start, heuristic_distance_fn(start)));\n\n                bool path_found = false;\n                std::cout << \"Entering explore loop\\n\\n\";\n                while (!path_found && ros::ok() && frontier.size() > 0)\n                {\n                    const ConfigAndDistType current = frontier.top();\n                    frontier.pop();\n                    const ConfigType& current_config = current.first;\n\n                    // Visualization code\n                    if (visualization_enabled)\n                    {\n                        geometry_msgs::Point p;\n                        p.x = current_config.first;\n                        p.y = current_config.second;\n                        p.z = 0;\n                        ++marker.id;\n                        marker.points.push_back(p);\n\n                        if (marker.id % 1000 == 0)\n                        {\n                            marker.header.stamp = ros::Time::now();\n                            marker_pub.publish(marker);\n                            marker.points.clear();\n                            usleep(10);\n                        }\n                    }\n\n                    if (current_config.first == goal.first && current_config.second == goal.second)\n                    {\n                        if (visualization_enabled)\n                        {\n                            std::cout << \"Reached goal!\\n\";\n                            std::cout << PrettyPrint::PrettyPrint(current_config, true, \" \") << std::endl << std::flush;\n                            std::cout << std::endl;\n                            marker.header.stamp = ros::Time::now();\n                            marker_pub.publish(marker);\n                        }\n                        path_found = true;\n                    }\n                    // Double check if we've already explored this node:\n                    //    a single node can be inserted into the frontier multiple times at the same or different priorities\n                    //    so we want to avoid the expense of re-exploring it, and just discard this one once we pop it\n                    else if (explored(current_config.first, current_config.second) == false)\n                    {\n                        explored(current_config.first, current_config.second) = true;\n\n                        // Expand the node to find all neighbours, adding them to the frontier if we have not already explored them\n                        const auto neighbours = GetNeighbours(current_config, rows, cols, validity_check_fn);\n                        for (const auto neighbour : neighbours)\n                        {\n                            // Check if we've already explored this neighbour to avoid re-adding it to the frontier\n                            if (explored(neighbour.first, neighbour.second) == false)\n                            {\n                                frontier.push(ConfigAndDistType(neighbour, heuristic_distance_fn(neighbour)));\n                            }\n                        }\n                    }\n                }\n\n                if (visualization_enabled)\n                {\n                    marker.header.stamp = ros::Time::now();\n                    marker_pub.publish(marker);\n                }\n\n                return path_found;\n            }\n\n        private:\n            FirstOrderVisibilityGraph() {}\n\n            static std::vector<ConfigType> GetNeighbours(const ConfigType& config, const ssize_t rows, const ssize_t cols, const ValidityCheckFnType& validity_check_fn)\n            {\n                std::vector<ConfigType> neighbours;\n                neighbours.reserve(8);\n\n                const ssize_t row_min = std::max(0L, config.first - 1);\n                const ssize_t row_max = std::min(rows - 1, config.first + 1);\n\n                const ssize_t col_min = std::max(0L, config.second - 1);\n                const ssize_t col_max = std::min(cols - 1, config.second + 1);\n\n                for (ssize_t col = col_min; col <= col_max; col++)\n                {\n                    for (ssize_t row = row_min; row <= row_max; row++)\n                    {\n                        if (!(row == config. first && col == config.second) && validity_check_fn(row, col) == true)\n                        {\n                            neighbours.push_back(ConfigType(row, col));\n                        }\n                    }\n                }\n\n                return neighbours;\n            }\n\n    };\n}\n\n#endif // FIRST_ORDER_VISIBILITY_GRAPH_HPP\n", "meta": {"hexsha": "215ccb6bbce7bc907250272712d8223a7d3d7640", "size": 7515, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/arc_utilities/first_order_visibility_graph.hpp", "max_stars_repo_name": "ToyotaResearchInstitute/arc_utilities", "max_stars_repo_head_hexsha": "f15a1dfd9fba5ca83296354bae8b97628895c1c2", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/arc_utilities/first_order_visibility_graph.hpp", "max_issues_repo_name": "ToyotaResearchInstitute/arc_utilities", "max_issues_repo_head_hexsha": "f15a1dfd9fba5ca83296354bae8b97628895c1c2", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/arc_utilities/first_order_visibility_graph.hpp", "max_forks_repo_name": "ToyotaResearchInstitute/arc_utilities", "max_forks_repo_head_hexsha": "f15a1dfd9fba5ca83296354bae8b97628895c1c2", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-11-06T21:38:23.000Z", "max_forks_repo_forks_event_max_datetime": "2017-11-06T21:38:23.000Z", "avg_line_length": 45.0, "max_line_length": 176, "alphanum_fraction": 0.5068529607, "num_tokens": 1383, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.5851011542032313, "lm_q1q2_score": 0.45479904593532317}}
{"text": "/*Deep euler implementation*/\n\n#include <iostream>\n#include <fstream>\n#define _USE_MATH_DEFINES\n#include <cmath>\n#include <vector>\n#include <string>\n#include <chrono>\n#include <regex>\n\n#include <boost/program_options.hpp>\n#include <torch/script.h>\n\nusing namespace std;\n\n//const int N = 16;\n//const int N_z = N / 2 - 1;\nconst int nn_inputs = 4;\nconst int nn_outputs = 2; // output dimension\nc10::TensorOptions global_tensor_op;\n\nstring file_name = \"../lotka_dem.txt\";\nstring file_name_normal_euler = \"../lotka_euler.txt\";\nstring time_counting_file_name = \"../clock.txt\";\nstring model_file = \"../../training/traced_model_e20_2021_11_04.pt\";\nstring range_model_file = \"../../training/traced_range_model_e20_2021_11_04.pt\";\nstring embedded_model_file = \"../../training/traced_range_embedded_model_e22_2021_11_10.pt\";\nstatic bool use_embedded = false;\nstatic bool use_generalized = false;\n\ntypedef double value_type;\ntypedef vector<value_type> state_type;\n\n\n\n\n//ode function of bubble dynamic\nclass lotka {\n//\tstd::ofstream outputs_out;\npublic:\n\ttorch::jit::script::Module model;\n\ttorch::Tensor inputs; //reused tensor of inputs\n\n\tlotka(std::vector<double> inital_values) {\n\n\t\t//metamodel initializations\n\t\tint _size = inital_values.size();\n\t\tinputs = torch::ones({ 1, _size }, global_tensor_op);\n\t\t//model inputs: dt x1 x2 x3 z... x1now x2now x3now\n\t\tfor (int i = 0; i < _size; i++) inputs[0][i] = inital_values[i];\n\t\t//outputs: z... grad_z(wall)\n\t\ttry {\n\t\t\tif (use_embedded) {\n\t\t\t\tmodel = torch::jit::load(embedded_model_file);\n\t\t\t}\n\t\t\telse if(use_generalized) {\n\t\t\t\tmodel = torch::jit::load(range_model_file);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tmodel = torch::jit::load(model_file);\n\t\t\t}\n\t\t\tstd::vector<torch::jit::IValue> inp;\n\t\t\tinp.push_back(torch::ones({ 1, _size }, global_tensor_op));\n\t\t\tstd::cout << inp << endl;\n\t\t\t// Execute the model and turn its output into a tensor.\n\t\t\tat::Tensor output = model.forward(inp).toTensor().detach();\n\t\t\tstd::cout << output << endl;\n\t\t}\n\t\tcatch (const c10::Error& e) {\n\t\t\tstd::cerr << \"Error loading the model: \" << e.what() << endl;\n\t\t\t//\texit(-1);\n\t\t}\n\t}\n\n\n\t/*Rewrites the errors array with the predicted local truncation errors*/\n\tvoid local_error(double t, double t_next, const double* x, double* errors) {\n\t\t//updating inputs\n\t\tinputs[0][0] = t_next;\n\t\tinputs[0][1] = t;\n\t\tfor (int i = 0; i < nn_inputs - 2; i++) {\n\t\t\tinputs[0][i + 2] = x[i];\n\t\t}\n\t\tstd::vector<torch::jit::IValue> inps;\n\t\tinps.push_back(inputs);\n\t\t//evaluating\n\t\ttorch::Tensor loc_trun_err = model.forward(inps).toTensor().detach();\n\n\t\tfor (int i = 0; i < nn_outputs; i++) {\n\t\t\terrors[i] = loc_trun_err[0][i].item<double>();\n\t\t}\n\t}\n\n\t/*ODE function*/\n\tinline void operator()(double t, double* x, double* dx) {\n\t\tdx[0] = x[0] - x[0] * x[1];\n\t\tdx[1] = -x[1] + x[0] * x[1];\n\t}\n};\n\nclass ODESolver\n{\npublic:\n\t// order is the number of the output\n\tODESolver(int order): order(order) {\n\t// initialize necessary data structures\n\t\tderivative = (double*)malloc(sizeof(double) * order);\n\t\tlocal_error = (double*)malloc(sizeof(double) * order);\n\t};\n\n\tbool setInitialCondition(double* conds, double at) {\n\t\tbegin_t = at;\n\t\tinit_conds = (double*)malloc(sizeof(double) * order);\n\t\tfor (int u = 0; u < order; u++) {\n\t\t\tinit_conds[u] = conds[u];\n\t\t}\n\t\treturn true;\n\t}\n\n\tvoid setTimeStep(double dt) {\n\t\tdelta_t = dt;\n\t}\n\n\tbool setStepNumber(int steps) {\n\t\tmax_l = steps;\n\t\tsol_t = (double*)malloc(sizeof(double) * (max_l + 1));\n\t\tsol = new double* [max_l + 1];\n\t\tfor (int i = 0; i < max_l + 1; i++)\n\t\t\tsol[i] = new double[order];\n\t\treturn true;\n\t}\n\t\n\tvoid solve(lotka& lot) {\n\n\t\tfor (int u = 0; u < order; u++) {\n\t\t\tsol[0][u] = init_conds[u];\n\t\t}\n\n\t\tdouble t = begin_t;\n\t\tsol_t[0] = t;\n\t\tint l = 0;\n\t\twhile (l < max_l) {\n\t\t\tlot.local_error(t, t + delta_t, sol[l], local_error); // fill the local_error\n\t\t\tlot(t, sol[l], derivative); // fill the derivative\n\t\t\tfor (int j = 0; j < order; j++) {\n\t\t\t\tsol[l + 1][j] = sol[l][j] + delta_t * derivative[j] + delta_t * delta_t * local_error[j];\n\t\t\t}\n\t\t\tl++;\n\t\t\tt += delta_t;\n\t\t\tsol_t[l] = t;\n\t\t}\n\t}\n\n\t// disable residue approximation\n\tvoid solve_normal(lotka& lot) {\n\n\t\tfor (int u = 0; u < order; u++) {\n\t\t\tsol[0][u] = init_conds[u];\n\t\t}\n\n\t\tdouble t = begin_t;\n\t\tsol_t[0] = t;\n\t\tint l = 0;\n\t\twhile (l < max_l) {\n\t\t\tlot(t, sol[l], derivative); // fill the derivative\n\t\t\tfor (int j = 0; j < order; j++) {\n\t\t\t\tsol[l + 1][j] = sol[l][j] + delta_t * derivative[j];\n\t\t\t}\n\t\t\tl++;\n\t\t\tt += delta_t;\n\t\t\tsol_t[l] = t;\n\t\t}\n\t}\n\n\t// output sol_t and sol\n\tvoid output(ofstream& out) {\n\t\tfor (int i = 0; i <= max_l; i++) {\n\t\t\tout << sol_t[i];\n\t\t\tfor (int j = 0; j < order; j++) {\n\t\t\t\tout << ' ' << sol[i][j];\n\t\t\t}\n\t\t\tout << '\\n';\n\t\t}\n\t}\n\n\t~ODESolver(){\n\t\tfree(init_conds);\n\t\tfree(derivative);\n\t\tfree(sol_t);\n\t\tfor (int indx = 0; indx <= max_l; ++indx)\n\t\t{\n\t\t\tdelete sol[indx];\n\t\t}\n\t\tdelete[] sol;\n\t}\nprivate:\n\tint order = 1;\n\tdouble* local_error;\n\tdouble* init_conds;\n\tdouble* sol_t;\n\tdouble** sol;\n\tdouble* derivative;\n\tdouble begin_t = 0;\n\tdouble delta_t = 0.1;\n\tint max_l = 10;\n};\n\n\nvoid setup_ofstream(ofstream& ofs) {\n\tif(!ofs.is_open())exit(-1);\n\tofs.precision(17);\n\tofs.flags(ios::scientific);\n}\n\nint main(int argc, const char* argv[]) {\n\tboost::program_options::options_description desc;\n\tdesc.add_options()\n\t\t(\"help,h\", \"Show this help screen\")\n\t\t(\"embedded\", boost::program_options::value<bool>()->implicit_value(true)->default_value(false), \"whether to use embedded model\")\n\t\t(\"generalized\", boost::program_options::value<bool>()->implicit_value(true)->default_value(false), \"whether to use embedded model\");\n\n\tboost::program_options::variables_map vm;\n\tboost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm);\n\tboost::program_options::notify(vm);\n\tif (vm.count(\"help\")) {\n\t\tstd::cout << desc << '\\n';\n\t\treturn 0;\n\t}\n\tuse_embedded = vm[\"embedded\"].as<bool>();\n\tuse_generalized = vm[\"generalized\"].as<bool>();\n\tglobal_tensor_op = torch::TensorOptions().dtype(torch::kFloat64);\n\tstd::cout << \"Lotka Volterra with meta-model started\\n\" << setprecision(17) << endl;\n\n\tdouble* x = new double[nn_outputs]{ 2.0, 1.0 };\n\n\tdouble dem_step_list[] = {0.1, 0.05, 0.01, 0.005};\n\tdouble euler_step_list[] = { 0.002, 0.001, 0.0005, 0.0002};\n\tint step_list_length = (sizeof(dem_step_list) / sizeof(*dem_step_list));\n\tstd::regex _regex(\".txt\");\n\tstd::string replace_base;\n\tif (use_embedded) {\n\t\treplace_base = \"_embedded.txt\";\n\t}\n\telse if (use_generalized) {\n\t\treplace_base = \"_generalized.txt\";\n\t}\n\telse {\n\t\treplace_base = \".txt\";\n\t}\n\tstd::string time_counting_file_name_special = std::regex_replace(time_counting_file_name, _regex, replace_base);\n\tofstream clock_of(time_counting_file_name_special);\n\tdouble t_stop = 15.0;\n\t//initial conditions\n\tstd::vector<double> initial_inputs;\n\tif (use_generalized) {\n\t\tinitial_inputs = { 0.0, 0.1, 2.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 1.0 };\n\t}\n\telse {\n\t\tinitial_inputs = { 1e-5, 0.0, 2.0, 1.0 };\n\t}\n\tfor (int i = 0; i < step_list_length; i++) {\n\n\t\tstd::string file_name_i = std::regex_replace(file_name, _regex, std::to_string(i) + replace_base);\n\t\tstd::string file_name_normal_euler_i = std::regex_replace(file_name_normal_euler, _regex, std::to_string(i) + \".txt\");\n\n\t\tofstream ofs(file_name_i);\n\t\tsetup_ofstream(ofs);\n\t\tstd::cout << \"Writing file: \" << file_name_i << endl;\n\t\tofstream ofs_2(file_name_normal_euler_i);\n\t\tsetup_ofstream(ofs_2);\n\n\t\t\n\t\t\n\t\tdouble t_start = 0.0;\n\t\tlotka bubi(initial_inputs);\n\t\t\n\t\tODESolver solver(nn_outputs), solver_2(nn_outputs);\n\t\tsolver.setInitialCondition(x, 0.0);\n\t\tsolver.setTimeStep(dem_step_list[i]);\n\t\tsolver.setStepNumber(int(t_stop/ dem_step_list[i]));\n\n\t\tstd::cout << \"Solving...\" << endl;\n\t\tauto t1 = chrono::high_resolution_clock::now();\n\t\tsolver.solve(bubi);\n\t\tauto t2 = chrono::high_resolution_clock::now();\n\t\t// std::cout << \"DEM Time (ms):\" << std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count() << endl;\n\t\tclock_of << std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count();\n\t\tsolver.output(ofs);\n\n\t\tsolver_2.setInitialCondition(x, 0.0);\n\t\tsolver_2.setTimeStep(euler_step_list[i]);\n\t\tsolver_2.setStepNumber(int(t_stop / euler_step_list[i]));\n\t\tt1 = chrono::high_resolution_clock::now();\n\t\tsolver_2.solve_normal(bubi);\n\t\tt2 = chrono::high_resolution_clock::now();\n\t\t// std::cout << \"EM Time (ms):\" << std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count() << endl;\n\t\tclock_of << ' ' << std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count() << endl;\n\t\tsolver_2.output(ofs_2);\n\t\tofs.flush();\n\t\tofs.close();\n\t\tofs_2.flush();\n\t\tofs_2.close();\n\t}\n\tclock_of.close();\n\tstd::cout << \"Ready\"<< endl;\n\treturn 0;\n}", "meta": {"hexsha": "fa42c786bb9dbd7d23c314aa1a46fb8cca1682ad", "size": 8600, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Lotka/DEM.cpp", "max_stars_repo_name": "zhaofeng-shu33/deep_euler_tests", "max_stars_repo_head_hexsha": "a3d0961af679d490b0c58873ee0726234122bc7a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Lotka/DEM.cpp", "max_issues_repo_name": "zhaofeng-shu33/deep_euler_tests", "max_issues_repo_head_hexsha": "a3d0961af679d490b0c58873ee0726234122bc7a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lotka/DEM.cpp", "max_forks_repo_name": "zhaofeng-shu33/deep_euler_tests", "max_forks_repo_head_hexsha": "a3d0961af679d490b0c58873ee0726234122bc7a", "max_forks_repo_licenses": ["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.9220779221, "max_line_length": 134, "alphanum_fraction": 0.6534883721, "num_tokens": 2718, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.45479904593532317}}
{"text": "#include <iostream>\n\n//--- SpatialOps includes ---//\n#include <spatialops/structured/FVStaggeredFieldTypes.h>\n#include <spatialops/structured/IntVec.h>\n#include <spatialops/structured/MemoryWindow.h>\n#include <spatialops/structured/stencil/FVStaggeredOperatorTypes.h>\n#include <spatialops/OperatorDatabase.h>\n#include <spatialops/structured/stencil/StencilBuilder.h>\n#include <spatialops/structured/FVStaggeredFieldTypes.h>\n#include <spatialops/Nebo.h>\n\n//-- boost includes ---//\n#include <boost/program_options.hpp>\n#include <boost/date_time/posix_time/posix_time.hpp>\n\nnamespace po = boost::program_options;\n\nusing namespace SpatialOps;\n\n#define RUN_TEST(TEST,\t\t\t\t\t\t\t\\\n\t\t TYPE)\t\t\t\t\t\t\t\\\n  boost::posix_time::ptime start( boost::posix_time::microsec_clock::universal_time() ); \\\n  boost::posix_time::ptime end( boost::posix_time::microsec_clock::universal_time() ); \\\n  int ii = 0;\t\t\t\t\t\t\t\t\\\n  start = boost::posix_time::microsec_clock::universal_time();\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n  for(; ii < number_of_runs; ii++) {\t\t\t\t\t\\\n    TEST;\t\t\t\t\t\t\t\t\\\n  };\t\t\t\t\t\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n  end = boost::posix_time::microsec_clock::universal_time();\t\t\\\n  std::cout << TYPE;\t\t\t\t\t\t\t\\\n  std::cout << \" runs: \";\t\t\t\t\t\t\\\n  std::cout << number_of_runs;\t\t\t\t\t\t\\\n  std::cout << \" result: \";\t\t\t\t\t\t\\\n  std::cout << (end - start).total_microseconds()*1e-6;\t\t\t\\\n  std::cout << std::endl;\n\n#define build_stencil_point(f, stencil_offset)                                  \\\n    (FieldType(MemoryWindow(f.window_without_ghost().glob_dim(),                \\\n                            f.window_without_ghost().offset() + stencil_offset, \\\n                            f.window_without_ghost().extent()),                 \\\n\t       f) )\n\ntemplate<typename FieldType>\ninline void evaluate_serial_example(FieldType & result,\n\t\t\t\t    FieldType const & phi,\n\t\t\t\t    FieldType const & dCoef,\n\t\t\t\t    IntVec const npts,\n\t\t\t\t    double const Lx,\n\t\t\t\t    double const Ly,\n\t\t\t\t    double const Lz,\n\t\t\t\t    int number_of_runs) {\n\n    SpatialOps::OperatorDatabase opDB;\n    SpatialOps::build_stencils(npts[0],\n                                           npts[1],\n                                           npts[2],\n                                           Lx,\n                                           Ly,\n                                           Lz,\n                                           opDB);\n\n    typename BasicOpTypes<FieldType>::GradX* const gradXOp_ = opDB.retrieve_operator<typename BasicOpTypes<FieldType>::GradX>();\n    typename BasicOpTypes<FieldType>::GradY* const gradYOp_ = opDB.retrieve_operator<typename BasicOpTypes<FieldType>::GradY>();\n    typename BasicOpTypes<FieldType>::GradZ* const gradZOp_ = opDB.retrieve_operator<typename BasicOpTypes<FieldType>::GradZ>();\n    typename BasicOpTypes<FieldType>::InterpC2FX* const interpXOp_ = opDB.retrieve_operator<typename BasicOpTypes<FieldType>::InterpC2FX>();\n    typename BasicOpTypes<FieldType>::InterpC2FY* const interpYOp_ = opDB.retrieve_operator<typename BasicOpTypes<FieldType>::InterpC2FY>();\n    typename BasicOpTypes<FieldType>::InterpC2FZ* const interpZOp_ = opDB.retrieve_operator<typename BasicOpTypes<FieldType>::InterpC2FZ>();\n    typename BasicOpTypes<FieldType>::DivX* const divXOp_ = opDB.retrieve_operator<typename BasicOpTypes<FieldType>::DivX>();\n    typename BasicOpTypes<FieldType>::DivY* const divYOp_ = opDB.retrieve_operator<typename BasicOpTypes<FieldType>::DivY>();\n    typename BasicOpTypes<FieldType>::DivZ* const divZOp_ = opDB.retrieve_operator<typename BasicOpTypes<FieldType>::DivZ>();\n\n    MemoryWindow const w = phi.window_with_ghost();\n    const GhostData& g = phi.get_ghost_data();\n    const BoundaryCellInfo& bc = phi.boundary_info();\n    typename FaceTypes<FieldType>::XFace  tmpFaceX( w, bc, g, NULL );\n    typename FaceTypes<FieldType>::XFace tmpFaceX2( w, bc, g, NULL );\n    FieldType tmpX( w, bc, g, NULL );\n    typename FaceTypes<FieldType>::YFace  tmpFaceY( w, bc, g, NULL );\n    typename FaceTypes<FieldType>::YFace tmpFaceY2( w, bc, g, NULL );\n    FieldType tmpY( w, bc, g, NULL );\n    typename FaceTypes<FieldType>::ZFace  tmpFaceZ( w, bc, g, NULL );\n    typename FaceTypes<FieldType>::ZFace tmpFaceZ2( w, bc, g, NULL );\n    FieldType tmpZ( w, bc, g, NULL );\n\n    RUN_TEST(// X - direction\n\t     gradXOp_  ->apply_to_field( phi,    tmpFaceX  );\n\t     interpXOp_->apply_to_field( dCoef, tmpFaceX2 );\n\t     tmpFaceX <<= tmpFaceX * tmpFaceX2;\n\t     divXOp_->apply_to_field( tmpFaceX, tmpX );\n\n\t     // Y - direction\n\t     gradYOp_  ->apply_to_field( phi,    tmpFaceY  );\n\t     interpYOp_->apply_to_field( dCoef, tmpFaceY2 );\n\t     tmpFaceY <<= tmpFaceY * tmpFaceY2;\n\t     divYOp_->apply_to_field( tmpFaceY, tmpY );\n\n\t     // Z - direction\n\t     gradZOp_  ->apply_to_field( phi,    tmpFaceZ  );\n\t     interpZOp_->apply_to_field( dCoef, tmpFaceZ2 );\n\t     tmpFaceZ <<= tmpFaceZ * tmpFaceZ2;\n\t     divZOp_->apply_to_field( tmpFaceZ, tmpZ );\n\n\t     result <<= - tmpX - tmpY - tmpZ,\n\t     \"old\");\n\n};\n\ntemplate<typename FieldType>\ninline void evaluate_chaining_example(FieldType & result,\n\t\t\t\t      FieldType const & phi,\n\t\t\t\t      FieldType const & dCoef,\n\t\t\t\t      IntVec const npts,\n\t\t\t\t      double const Lx,\n\t\t\t\t      double const Ly,\n\t\t\t\t      double const Lz,\n\t\t\t\t      int number_of_runs) {\n\n\n    SpatialOps::OperatorDatabase opDB;\n    SpatialOps::build_stencils(npts[0],\n                                           npts[1],\n                                           npts[2],\n                                           Lx,\n\t\t\t\t\t   Ly,\n\t\t\t\t\t   Lz,\n                                           opDB);\n\n    typename BasicOpTypes<FieldType>::GradX* const gradXOp_ = opDB.retrieve_operator<typename BasicOpTypes<FieldType>::GradX>();\n    typename BasicOpTypes<FieldType>::GradY* const gradYOp_ = opDB.retrieve_operator<typename BasicOpTypes<FieldType>::GradY>();\n    typename BasicOpTypes<FieldType>::GradZ* const gradZOp_ = opDB.retrieve_operator<typename BasicOpTypes<FieldType>::GradZ>();\n    typename BasicOpTypes<FieldType>::InterpC2FX* const interpXOp_ = opDB.retrieve_operator<typename BasicOpTypes<FieldType>::InterpC2FX>();\n    typename BasicOpTypes<FieldType>::InterpC2FY* const interpYOp_ = opDB.retrieve_operator<typename BasicOpTypes<FieldType>::InterpC2FY>();\n    typename BasicOpTypes<FieldType>::InterpC2FZ* const interpZOp_ = opDB.retrieve_operator<typename BasicOpTypes<FieldType>::InterpC2FZ>();\n    typename BasicOpTypes<FieldType>::DivX* const divXOp_ = opDB.retrieve_operator<typename BasicOpTypes<FieldType>::DivX>();\n    typename BasicOpTypes<FieldType>::DivY* const divYOp_ = opDB.retrieve_operator<typename BasicOpTypes<FieldType>::DivY>();\n    typename BasicOpTypes<FieldType>::DivZ* const divZOp_ = opDB.retrieve_operator<typename BasicOpTypes<FieldType>::DivZ>();\n\n    IntVec const neutral = IntVec(0,0,0);\n    IntVec const neg_X = IntVec(-1,0,0);\n    IntVec const pos_X = IntVec(1,0,0);\n    IntVec const neg_Y = IntVec(0,-1,0);\n    IntVec const pos_Y = IntVec(0,1,0);\n    IntVec const neg_Z = IntVec(0,0,-1);\n    IntVec const pos_Z = IntVec(0,0,1);\n\n    RUN_TEST(FieldType r = build_stencil_point(result, neutral);\n\n\t     FieldType const phi_xlxl = build_stencil_point(phi, neg_X);\n\t     FieldType const phi_xlxh = build_stencil_point(phi, neutral);\n\t     FieldType const phi_xhxl = build_stencil_point(phi, neutral);\n\t     FieldType const phi_xhxh = build_stencil_point(phi, pos_X);\n\t     FieldType const phi_ylyl = build_stencil_point(phi, neg_Y);\n\t     FieldType const phi_ylyh = build_stencil_point(phi, neutral);\n\t     FieldType const phi_yhyl = build_stencil_point(phi, neutral);\n\t     FieldType const phi_yhyh = build_stencil_point(phi, pos_Y);\n\t     FieldType const phi_zlzl = build_stencil_point(phi, neg_Z);\n\t     FieldType const phi_zlzh = build_stencil_point(phi, neutral);\n\t     FieldType const phi_zhzl = build_stencil_point(phi, neutral);\n\t     FieldType const phi_zhzh = build_stencil_point(phi, pos_Z);\n\n\t     FieldType const dCoef_xlxl = build_stencil_point(dCoef, neg_X);\n\t     FieldType const dCoef_xlxh = build_stencil_point(dCoef, neutral);\n\t     FieldType const dCoef_xhxl = build_stencil_point(dCoef, neutral);\n\t     FieldType const dCoef_xhxh = build_stencil_point(dCoef, pos_X);\n\t     FieldType const dCoef_ylyl = build_stencil_point(dCoef, neg_Y);\n\t     FieldType const dCoef_ylyh = build_stencil_point(dCoef, neutral);\n\t     FieldType const dCoef_yhyl = build_stencil_point(dCoef, neutral);\n\t     FieldType const dCoef_yhyh = build_stencil_point(dCoef, pos_Y);\n\t     FieldType const dCoef_zlzl = build_stencil_point(dCoef, neg_Z);\n\t     FieldType const dCoef_zlzh = build_stencil_point(dCoef, neutral);\n\t     FieldType const dCoef_zhzl = build_stencil_point(dCoef, neutral);\n\t     FieldType const dCoef_zhzh = build_stencil_point(dCoef, pos_Z);\n\n\t     double gXcl = gradXOp_->get_minus_coef();\n\t     double gXch = gradXOp_->get_plus_coef();\n\t     double iXcl = interpXOp_->get_minus_coef();\n\t     double iXch = interpXOp_->get_plus_coef();\n\t     double dXcl = divXOp_->get_minus_coef();\n\t     double dXch = divXOp_->get_plus_coef();\n\t     double gYcl = gradYOp_->get_minus_coef();\n\t     double gYch = gradYOp_->get_plus_coef();\n\t     double iYcl = interpYOp_->get_minus_coef();\n\t     double iYch = interpYOp_->get_plus_coef();\n\t     double dYcl = divYOp_->get_minus_coef();\n\t     double dYch = divYOp_->get_plus_coef();\n\t     double gZcl = gradZOp_->get_minus_coef();\n\t     double gZch = gradZOp_->get_plus_coef();\n\t     double iZcl = interpZOp_->get_minus_coef();\n\t     double iZch = interpZOp_->get_plus_coef();\n\t     double dZcl = divZOp_->get_minus_coef();\n\t     double dZch = divZOp_->get_plus_coef();\n\n\t     r <<= (- (dXcl * ((gXcl * phi_xlxl + gXch * phi_xhxl) * (iXcl * dCoef_xlxl + iXch * dCoef_xhxl)) +\n\t\t       dXch * ((gXcl * phi_xlxh + gXch * phi_xhxh) * (iXcl * dCoef_xlxh + iXch * dCoef_xhxh)))\n\t\t    - (dYcl * ((gYcl * phi_ylyl + gYch * phi_yhyl) * (iYcl * dCoef_ylyl + iYch * dCoef_yhyl)) +\n\t\t       dYch * ((gYcl * phi_ylyh + gYch * phi_yhyh) * (iYcl * dCoef_ylyh + iYch * dCoef_yhyh)))\n\t\t    - (dZcl * ((gZcl * phi_zlzl + gZch * phi_zhzl) * (iZcl * dCoef_zlzl + iZch * dCoef_zhzl)) +\n\t\t       dZch * ((gZcl * phi_zlzh + gZch * phi_zhzh) * (iZcl * dCoef_zlzh + iZch * dCoef_zhzh)))),\n\t     \"new\");\n\n};\n\nint main(int iarg, char* carg[]) {\n    typedef SVolField Field;\n\n    int nx, ny, nz;\n    int number_of_runs;\n    double Lx, Ly, Lz;\n#ifdef ENABLE_THREADS\n  int thread_count;\n#endif\n\n    // parse the command line options input describing the problem\n    {\n        po::options_description desc(\"Supported Options\");\n\tdesc.add_options()\n\t  ( \"help\", \"print help message\" )\n\t  ( \"nx\", po::value<int>(&nx)->default_value(10), \"Grid in x\" )\n\t  ( \"ny\", po::value<int>(&ny)->default_value(10), \"Grid in y\" )\n\t  ( \"nz\", po::value<int>(&nz)->default_value(10), \"Grid in z\" )\n\t  ( \"Lx\", po::value<double>(&Lx)->default_value(1.0),\"Length in x\")\n\t  ( \"Ly\", po::value<double>(&Ly)->default_value(1.0),\"Length in y\")\n\t  ( \"Lz\", po::value<double>(&Lz)->default_value(1.0),\"Length in z\")\n#ifdef ENABLE_THREADS\n      ( \"tc\", po::value<int>(&thread_count)->default_value(NTHREADS), \"Number of threads for Nebo\")\n#endif\n\t  ( \"runs\", po::value<int>(&number_of_runs)->default_value(1), \"Number of iterations of each test\");\n\n\tpo::variables_map args;\n\tpo::store( po::parse_command_line(iarg,carg,desc), args );\n\tpo::notify(args);\n\n\tif (args.count(\"help\")) {\n\t    std::cout << desc << \"\\n\";\n\t    return 1;\n\t}\n\n#ifdef ENABLE_THREADS\n    set_hard_thread_count(thread_count);\n#endif\n    }\n\n    const GhostData ghost(1);\n    const BoundaryCellInfo bc = BoundaryCellInfo::build<Field>(false,false,false);\n    const MemoryWindow window( get_window_with_ghost(IntVec(nx,ny,nz),ghost,bc) );\n\n    Field  a( window, bc, ghost, NULL );\n    Field  b( window, bc, ghost, NULL );\n    Field cr( window, bc, ghost, NULL );\n    Field sr( window, bc, ghost, NULL );\n\n    Field::iterator ia = a.begin();\n    Field::iterator ib = b.begin();\n    for(size_t kk = 0; kk < window.glob_dim(2); kk++) {\n        for(size_t jj = 0; jj < window.glob_dim(1); jj++) {\n            for(size_t ii = 0; ii < window.glob_dim(0); ii++, ++ia, ++ib) {\n\t      *ia = ii + jj * 2 + kk * 4;\n\t      *ib = ii + jj * 3 + kk * 5;\n            }\n        }\n    };\n\n    evaluate_serial_example(sr,\n\t\t\t    a,\n\t\t\t    b,\n\t\t\t    IntVec(nx,ny,nz),\n\t\t\t    Lx,\n\t\t\t    Ly,\n\t\t\t    Lz,\n\t\t\t    number_of_runs);\n\n    evaluate_chaining_example(cr,\n\t\t\t      a,\n\t\t\t      b,\n\t\t\t      IntVec(nx,ny,nz),\n\t\t\t      Lx,\n\t\t\t      Ly,\n\t\t\t      Lz,\n\t\t\t      number_of_runs);\n    return 0;\n};\n", "meta": {"hexsha": "df3edcbf7b3d307165938de5fc601405a70a22e7", "size": 12524, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/StencilChainTest.cpp", "max_stars_repo_name": "MaxZZG/SpatialOps", "max_stars_repo_head_hexsha": "c673081a6214ac3020d2fa92d09663922815f740", "max_stars_repo_licenses": ["MIT"], "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/StencilChainTest.cpp", "max_issues_repo_name": "MaxZZG/SpatialOps", "max_issues_repo_head_hexsha": "c673081a6214ac3020d2fa92d09663922815f740", "max_issues_repo_licenses": ["MIT"], "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/StencilChainTest.cpp", "max_forks_repo_name": "MaxZZG/SpatialOps", "max_forks_repo_head_hexsha": "c673081a6214ac3020d2fa92d09663922815f740", "max_forks_repo_licenses": ["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.9438596491, "max_line_length": 140, "alphanum_fraction": 0.6458799106, "num_tokens": 3486, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4547990459353231}}
{"text": "#include <armadillo>\n#include <boost/program_options.hpp>\n#include <HSMM.hpp>\n#include <iostream>\n#include <json.hpp>\n#include <memory>\n#include <ProMPs_emission.hpp>\n\nusing namespace arma;\nusing namespace hsmm;\nusing namespace std;\nusing json = nlohmann::json;\nnamespace po = boost::program_options;\n\n\nmat fieldToMat(int njoints, field<mat> &samples) {\n    mat ret(njoints, samples.n_elem);\n    for(int i = 0; i < samples.n_elem; i++)\n        ret.col(i) = samples(i);\n    return ret;\n}\n\nvec pmfFromGaussian(double mean, double var, int size, int min_duration) {\n    vec pmf(size);\n    for (int t = min_duration; t < min_duration + size; t++) {\n        int idx = t - min_duration;\n        double tmp = ((t - mean) * (t - mean)) / var;\n        pmf(idx) = exp(-0.5 * tmp);\n    }\n    pmf = pmf * (1.0 / sum(pmf));\n    return pmf;\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        (\"params,p\", po::value<string>(), \"JSON input params (optional)\")\n        (\"output,o\", po::value<string>(), \"Filename to store the obs\")\n        (\"vit,v\", po::value<string>(), \"Filename to store the viterbi output\")\n        (\"ms\", po::value<string>(), \"state marginals file name\")\n        (\"mr\", po::value<string>(), \"runlength marginals file name\")\n        (\"md\", po::value<string>(), \"duration marginals file name \")\n        (\"imd\", po::value<string>(), \"implicit duration marginals file name.\"\n                \" This means it is computed from the runlength and state\")\n        (\"polybasisfun\", po::value<int>()->default_value(1), \"Order of the\"\n                \" poly basis\")\n        (\"rbfbasisfun\", po::value<int>()->default_value(3), \"Number of radial\"\n                \" basis functions to use between 0 and 1. 0,1 are excluded.\")\n        (\"delta\", po::value<double>(), \"delta between sample locations\")\n        (\"print_ll_vit\", \"If set then the ll from each hs for\"\n                \" every ground truth segment is printed. Intended for \"\n                \"debugging purposes\");\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    int min_duration = 30;\n    mat transition = ones<mat>(2, 2);\n    transition.diag().zeros();\n    int nstates = transition.n_rows;\n    int ndurations = 30;\n    vec pi = {0.5, 0.5};\n    mat durations(nstates, ndurations);\n    durations.row(0) = conv_to<rowvec>::from(pmfFromGaussian(\n                40, 16, ndurations, min_duration));\n    durations.row(1) = conv_to<rowvec>::from(pmfFromGaussian(\n                50, 16, ndurations, min_duration));\n    int njoints = 1;\n    json input_params;\n    if (vm.count(\"params\")) {\n        string params = vm[\"params\"].as<string>();\n        ifstream input_params_file(params);\n        input_params_file >> input_params;\n        min_duration = input_params[\"min_duration\"];\n        nstates = input_params[\"nstates\"];\n        ndurations = input_params[\"ndurations\"];\n        transition = eye<mat>(nstates, nstates);\n        pi = eye<vec>(nstates, 1);\n        durations = eye<mat>(nstates, ndurations);\n        njoints = input_params[\"emission_params\"][0][\"num_joints\"];\n    }\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    int nparameters = n_basis_functions * njoints;\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 = zeros<vec>(nparameters);\n        mat Sigma_w = eye<mat>(nparameters, nparameters);\n        mat Sigma_y = 0.00001*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<AbstractEmissionOnlineSetting> ptr_emission(new ProMPsEmission(\n                promps));\n\n    OnlineHSMM promp_hsmm(ptr_emission, transition, pi, durations,\n            min_duration);\n    if (vm.count(\"params\"))\n        promp_hsmm.from_stream(input_params);\n\n    int nseq = 1;\n    int nsegments = 10;\n    field<ivec> hidden_states, hidden_durations;\n    field<field<mat>> multiple_toy_obs = promp_hsmm.sampleMultipleSequences(\n            nseq, nsegments, hidden_states, hidden_durations);\n    cout << \"Generated states and durations for the first sequence\" << endl;\n    imat viterbi = join_horiz(hidden_states(0), hidden_durations(0));\n    cout << viterbi << endl;\n\n    cout << \"Model Parameters\" << endl;\n    json params = promp_hsmm.to_stream();\n    cout << params.dump(4) << endl;\n\n    mat obs = fieldToMat(njoints, multiple_toy_obs(0));\n    if (vm.count(\"output\"))\n        obs.save(vm[\"output\"].as<string>(), raw_ascii);\n    if (vm.count(\"vit\"))\n        viterbi.save(vm[\"vit\"].as<string>(), raw_ascii);\n\n    // Note that delta only affects the online filtering, not the generation.\n    if (vm.count(\"delta\"))\n        std::static_pointer_cast<ProMPsEmission>(\n                ptr_emission)->setDelta(vm[\"delta\"].as<double>());\n\n    if (vm.count(\"print_ll_vit\")) {\n        int idx = 0;\n        for(int i = 0; i < viterbi.n_rows; i++) {\n            int dur = viterbi(i, 1);\n            int hs = viterbi(i, 0);\n            cout << \"Segment #\" << i << \": (\" << hs << \",\" << dur << \")\" <<\n                    endl;\n            const field<mat>& segment = multiple_toy_obs(0).rows(idx,\n                    idx + dur - 1);\n            idx += dur;\n            for(int i = 0; i < nstates; i++) {\n                double ll = promp_hsmm.emission_->loglikelihood(i, segment);\n                double lld = ll + log(promp_hsmm.duration_(i, dur - min_duration));\n                cout << \"State \" << i << \": \" << ll << \" with dur: \" << lld <<\n                        endl;\n            }\n        }\n    }\n\n    mat state_marginals_over_time(nstates, obs.n_cols);\n    mat runlength_marginals_over_time(min_duration + ndurations,\n            obs.n_cols);\n    mat duration_marginals_over_time(ndurations, obs.n_cols);\n    mat implicit_duration_marginals_over_time(ndurations, obs.n_cols);\n    for(int c = 0; c < obs.n_cols; c++) {\n        promp_hsmm.addNewObservation(obs.col(c));\n        vec s_marginal = promp_hsmm.getStateMarginal();\n        state_marginals_over_time.col(c) = s_marginal;\n        vec r_marginal = promp_hsmm.getRunlengthMarginal();\n        runlength_marginals_over_time.col(c) = r_marginal;\n        vec d_marginal = promp_hsmm.getDurationMarginal();\n        duration_marginals_over_time.col(c) = d_marginal;\n        if (vm.count(\"imd\")) {\n            vec indirect_d_marginal = promp_hsmm.getImplicitDurationMarginal();\n            implicit_duration_marginals_over_time.col(c) = indirect_d_marginal;\n        }\n        if (vm.count(\"print_ll_vit\")) {\n            cout << \"Obs idx: \" << c << endl;\n            promp_hsmm.printTopKFromPosterior(40);\n        }\n    }\n\n    // Saving the marginals if required.\n    if (vm.count(\"ms\"))\n        state_marginals_over_time.save(vm[\"ms\"].as<string>(), raw_ascii);\n    if (vm.count(\"mr\"))\n        runlength_marginals_over_time.save(vm[\"mr\"].as<string>(), raw_ascii);\n    if (vm.count(\"md\"))\n        duration_marginals_over_time.save(vm[\"md\"].as<string>(), raw_ascii);\n    if (vm.count(\"imd\"))\n        implicit_duration_marginals_over_time.save(vm[\"imd\"].as<string>(),\n                raw_ascii);\n    return 0;\n}\n", "meta": {"hexsha": "0b16056a5c20d18ae7071689e5546bc1b74351c8", "size": 7967, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/promps_hsmm_synth_exp.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_synth_exp.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_synth_exp.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.0351758794, "max_line_length": 83, "alphanum_fraction": 0.605999749, "num_tokens": 2108, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568416, "lm_q2_score": 0.5851011542032313, "lm_q1q2_score": 0.45479903989833753}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n\r\n// Copyright (c) 2016-2017 Oracle and/or its affiliates.\r\n// Contributed and/or modified by Vissarion Fisikopoulos, 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_AZIMUTH_HPP\r\n#define BOOST_GEOMETRY_STRATEGIES_SPHERICAL_AZIMUTH_HPP\r\n\r\n\r\n#include <boost/geometry/strategies/azimuth.hpp>\r\n#include <boost/geometry/formulas/spherical.hpp>\r\n\r\n#include <boost/mpl/if.hpp>\r\n#include <boost/type_traits/is_void.hpp>\r\n\r\n\r\nnamespace boost { namespace geometry\r\n{\r\n\r\nnamespace strategy { namespace azimuth\r\n{\r\n\r\ntemplate\r\n<\r\n    typename CalculationType = void\r\n>\r\nclass spherical\r\n{\r\npublic :\r\n\r\n    inline spherical()\r\n    {}\r\n\r\n    template <typename T>\r\n    static inline void apply(T const& lon1_rad, T const& lat1_rad,\r\n                             T const& lon2_rad, T const& lat2_rad,\r\n                             T& a1, T& a2)\r\n    {\r\n        typedef typename boost::mpl::if_\r\n            <\r\n                boost::is_void<CalculationType>, T, CalculationType\r\n            >::type calc_t;\r\n\r\n        geometry::formula::result_spherical<calc_t>\r\n            result = geometry::formula::spherical_azimuth<calc_t, true>(\r\n                        calc_t(lon1_rad), calc_t(lat1_rad),\r\n                        calc_t(lon2_rad), calc_t(lat2_rad));\r\n\r\n        a1 = result.azimuth;\r\n        a2 = result.reverse_azimuth;\r\n    }\r\n\r\n};\r\n\r\n#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\r\n\r\nnamespace services\r\n{\r\n\r\ntemplate <typename CalculationType>\r\nstruct default_strategy<spherical_equatorial_tag, CalculationType>\r\n{\r\n    typedef strategy::azimuth::spherical<CalculationType> type;\r\n};\r\n\r\n/*\r\ntemplate <typename CalculationType>\r\nstruct default_strategy<spherical_polar_tag, CalculationType>\r\n{\r\n    typedef strategy::azimuth::spherical<CalculationType> type;\r\n};\r\n*/\r\n}\r\n\r\n#endif // DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\r\n\r\n}} // namespace strategy::azimuth\r\n\r\n\r\n}} // namespace boost::geometry\r\n\r\n#endif // BOOST_GEOMETRY_STRATEGIES_SPHERICAL_AZIMUTH_HPP\r\n", "meta": {"hexsha": "4459794972ceabd69b684deb9c67302356c2d2e4", "size": 2286, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "win32/boost_bak/include/boost/geometry/strategies/spherical/azimuth.hpp", "max_stars_repo_name": "FreeApe/embcaffe_3rdparty", "max_stars_repo_head_hexsha": "d929e23f68515d03ba08c38f0c165216a2771a13", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-04-22T06:23:30.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-22T06:23:30.000Z", "max_issues_repo_path": "win32/boost_bak/include/boost/geometry/strategies/spherical/azimuth.hpp", "max_issues_repo_name": "FreeApe/embcaffe_3rdparty", "max_issues_repo_head_hexsha": "d929e23f68515d03ba08c38f0c165216a2771a13", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "win32/boost_bak/include/boost/geometry/strategies/spherical/azimuth.hpp", "max_forks_repo_name": "FreeApe/embcaffe_3rdparty", "max_forks_repo_head_hexsha": "d929e23f68515d03ba08c38f0c165216a2771a13", "max_forks_repo_licenses": ["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.9772727273, "max_line_length": 80, "alphanum_fraction": 0.6784776903, "num_tokens": 525, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568416, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4547990398983375}}
{"text": "// Copyright (c) 2021 Franka Emika 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#include <franka_example_controllers/motion_generator.hpp>\n\n#include <algorithm>\n#include <array>\n#include <cassert>\n#include <cmath>\n#include <utility>\n\n#include <Eigen/Core>\n\nMotionGenerator::MotionGenerator(double speed_factor,\n                                 const Vector7d& q_start,\n                                 const Vector7d& q_goal)\n    : q_start_(q_start) {\n  assert(speed_factor > 0);\n  assert(speed_factor <= 1);\n  delta_q_ = q_goal - q_start;\n  dq_max_ *= speed_factor;\n  ddq_max_start_ *= speed_factor;\n  ddq_max_goal_ *= speed_factor;\n  calculateSynchronizedValues();\n}\n\nbool MotionGenerator::calculateDesiredValues(double t, Vector7d* delta_q_d) const {\n  Vector7i sign_delta_q;\n  sign_delta_q << delta_q_.cwiseSign().cast<int>();\n  Vector7d t_d = t_2_sync_ - t_1_sync_;\n  Vector7d delta_t_2_sync = t_f_sync_ - t_2_sync_;\n  std::array<bool, kJoints> joint_motion_finished{};\n\n  for (auto i = 0; i < kJoints; i++) {\n    if (std::abs(delta_q_[i]) < kDeltaQMotionFinished) {\n      (*delta_q_d)[i] = 0;\n      joint_motion_finished.at(i) = true;\n    } else {\n      if (t < t_1_sync_[i]) {\n        (*delta_q_d)[i] = -1.0 / std::pow(t_1_sync_[i], 3.0) * dq_max_sync_[i] * sign_delta_q[i] *\n                          (0.5 * t - t_1_sync_[i]) * std::pow(t, 3.0);\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] * sign_delta_q[i];\n      } else if (t >= t_2_sync_[i] && t < t_f_sync_[i]) {\n        (*delta_q_d)[i] =\n            delta_q_[i] + 0.5 *\n                              (1.0 / std::pow(delta_t_2_sync[i], 3.0) *\n                                   (t - t_1_sync_[i] - 2.0 * delta_t_2_sync[i] - t_d[i]) *\n                                   std::pow((t - t_1_sync_[i] - t_d[i]), 3.0) +\n                               (2.0 * t - 2.0 * t_1_sync_[i] - delta_t_2_sync[i] - 2.0 * t_d[i])) *\n                              dq_max_sync_[i] * sign_delta_q[i];\n      } else {\n        (*delta_q_d)[i] = delta_q_[i];\n        joint_motion_finished.at(i) = true;\n      }\n    }\n  }\n  return std::all_of(joint_motion_finished.cbegin(), joint_motion_finished.cend(),\n                     [](bool x) { return x; });\n}\n\nvoid MotionGenerator::calculateSynchronizedValues() {\n  Vector7d dq_max_reach(dq_max_);\n  Vector7d t_f = Vector7d::Zero();\n  Vector7d delta_t_2 = Vector7d::Zero();\n  Vector7d t_1 = Vector7d::Zero();\n  Vector7d delta_t_2_sync = Vector7d::Zero();\n  Vector7i sign_delta_q;\n  sign_delta_q << delta_q_.cwiseSign().cast<int>();\n\n  for (auto i = 0; i < kJoints; i++) {\n    if (std::abs(delta_q_[i]) > kDeltaQMotionFinished) {\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] * sign_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 (auto i = 0; i < kJoints; i++) {\n    if (std::abs(delta_q_[i]) > kDeltaQMotionFinished) {\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] * sign_delta_q[i] * (0.5 * (t_1_sync_)[i]);\n    }\n  }\n}\n\nstd::pair<MotionGenerator::Vector7d, bool> MotionGenerator::getDesiredJointPositions(\n    const rclcpp::Duration& trajectory_time) {\n  time_ = trajectory_time.seconds();\n\n  Vector7d delta_q_d;\n  bool motion_finished = calculateDesiredValues(time_, &delta_q_d);\n\n  std::array<double, kJoints> joint_positions{};\n  Eigen::VectorXd::Map(&joint_positions[0], kJoints) = (q_start_ + delta_q_d);\n  return std::make_pair(q_start_ + delta_q_d, motion_finished);\n}", "meta": {"hexsha": "70e34dada37efe6197cb9bb39dff128e7bbc8389", "size": 5246, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "franka_example_controllers/src/motion_generator.cpp", "max_stars_repo_name": "FarisHamdi/franka_ros2", "max_stars_repo_head_hexsha": "32a936045e0029cbd0b380014a51cbe44f934f86", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2021-12-14T21:48:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T20:50:44.000Z", "max_issues_repo_path": "franka_example_controllers/src/motion_generator.cpp", "max_issues_repo_name": "FarisHamdi/franka_ros2", "max_issues_repo_head_hexsha": "32a936045e0029cbd0b380014a51cbe44f934f86", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2022-02-14T14:08:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T07:57:22.000Z", "max_forks_repo_path": "franka_example_controllers/src/motion_generator.cpp", "max_forks_repo_name": "FarisHamdi/franka_ros2", "max_forks_repo_head_hexsha": "32a936045e0029cbd0b380014a51cbe44f934f86", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2022-02-14T08:39:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T19:09:20.000Z", "avg_line_length": 41.6349206349, "max_line_length": 99, "alphanum_fraction": 0.5964544415, "num_tokens": 1703, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568416, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4547990398983375}}
{"text": "//\n// Created by Vasiliy Ershov on 08/11/2016.\n//\n\n#ifndef PROJECT_NORMAL_QUALITY_MODEL_HPP\n#define PROJECT_NORMAL_QUALITY_MODEL_HPP\n\n#include <common/utils/parallel/openmp_wrapper.h>\n#include <array>\n#include <boost/math/special_functions/binomial.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/math/special_functions/trigamma.hpp>\n#include <vector>\n#include \"config_struct.hpp\"\n#include \"kmer_data.hpp\"\n#include \"quality_thresholds_estimator.h\"\n#include \"thread_utils.h\"\n#include \"valid_hkmer_generator.hpp\"\n//\n\nnamespace n_normal_model {\n\nstruct QualityTransform {\n  double bias_;\n\n  QualityTransform(double bias = 60.0) : bias_(bias) {}\n\n  double Apply(double quality, double count) const {\n    return quality / (count + 60);\n  }\n};\n\nclass NormalDistribution {\n private:\n  double mean_;\n  double sigma_sqr_;\n\n public:\n  NormalDistribution(const NormalDistribution&) = default;\n\n  NormalDistribution& operator=(const NormalDistribution&) = default;\n\n  NormalDistribution(const double mean = 0, const double sigma = 1)\n      : mean_(mean), sigma_sqr_(sigma) {}\n\n  inline double GetMean() const { return mean_; }\n\n  inline double GetSigmaSqr() const { return sigma_sqr_; }\n\n  double LogLikelihood(double x) const {\n    return -0.5 *\n           ((x - mean_) * (x - mean_) / sigma_sqr_ + log(2 * M_PI * sigma_sqr_));\n  }\n\n  double LogLikelihoodFromStats(const double sum,\n                                const double sum2,\n                                const double weight) const {\n    return -0.5 * ((sum2 - 2 * sum * mean_ + weight * mean_ * mean_) / sigma_sqr_ +\n                   weight * log(2 * M_PI * sigma_sqr_));\n  }\n\n  static NormalDistribution FromStats(const double sum,\n                                      const double sum2,\n                                      const double weight) {\n    const double mu = sum / weight;\n    const double var = sum2 / weight - mu * mu;\n    return NormalDistribution(mu, var);\n  }\n};\n\nclass NormalMixture {\n private:\n  NormalDistribution first_;\n  NormalDistribution second_;\n  double first_weight_;\n\n public:\n  NormalMixture() : first_weight_(0) {}\n\n  NormalMixture(const NormalDistribution& first,\n                const NormalDistribution& second,\n                double weight)\n      : first_(first), second_(second), first_weight_(weight) {}\n\n  const NormalDistribution& GetFirst() const { return first_; }\n\n  const NormalDistribution& GetSecond() const { return second_; }\n\n  double GetFirstWeight() const { return first_weight_; }\n\n  double LogLikelihood(double x) const {\n    return log(first_weight_ * exp(first_.LogLikelihood(x)) +\n               (1 - first_weight_) * exp(second_.LogLikelihood(x)));\n  }\n\n  double FirstComponentPosterior(double x) const {\n    double firstLL = first_.LogLikelihood(x) + log(first_weight_);\n    double secondLL = second_.LogLikelihood(x) + log(1.0 - first_weight_);\n    const double expDiff = exp(secondLL - firstLL);\n\n    return std::isfinite(expDiff) ? -log(1.0 + exp(secondLL - firstLL))\n                                  : firstLL - secondLL;\n  }\n};\n\nclass Binarizer {\n private:\n  std::vector<double> borders_;\n\n public:\n  Binarizer() {\n    for (int i = 17; i < 30; ++i) {\n      borders_.push_back(i);\n    }\n  }\n\n  Binarizer(const std::vector<double> &borders) : borders_(borders) {}\n\n  int GetBin(double value) const {\n    uint index = 0;\n    while (index < borders_.size() && value > borders_[index]) {\n      ++index;\n    }\n    return index;\n  }\n\n  size_t GetBinCount() const { return borders_.size() + 1; }\n\n  double GetBorder(int bin) {\n    --bin;\n    bin = std::min(bin, (int)(borders_.size() - 1));\n    if (bin < 0) {\n      return 0;\n    }\n    return borders_[bin];\n  }\n};\n\nclass NormalClusterModel {\n private:\n  std::vector<NormalMixture> mixtures_;\n  Binarizer binarizer_;\n  std::vector<double> median_qualities_;\n  QualityTransform trans_;\n  double lower_quality_threshold_;\n\n  static std::vector<double> left_likelihoods_;\n  static std::vector<double> equal_likelihoods_;\n  static std::vector<double> right_likelihoods_;\n\n public:\n  NormalClusterModel() {}\n\n  NormalClusterModel(const std::vector<NormalMixture>& mixtures,\n                      const Binarizer& binarizer,\n                      const std::vector<double>& medianQualities,\n                      const QualityTransform& trans)\n      : mixtures_(mixtures),\n        binarizer_(binarizer),\n        median_qualities_(medianQualities),\n        trans_(trans) {\n    lower_quality_threshold_ = cfg::get().noise_filter_count_threshold;  // threshold >= 10 ? 1 : 0;\n  }\n\n  NormalClusterModel(const NormalClusterModel& other) = default;\n\n  NormalClusterModel& operator=(const NormalClusterModel&) = default;\n\n  bool NeedSubcluster(const hammer::KMerStat& stat) const {\n    return stat.count > 15 && GenomicLogLikelihood(stat) > -0.0001;\n  }\n\n  double StatTransform(const hammer::KMerStat& stat) const {\n    return trans_.Apply(stat.qual, stat.count);\n  }\n\n  double GenomicLogLikelihood(const hammer::KMerStat& stat) const {\n    return GenomicLogLikelihood(binarizer_.GetBin((double)GetKmerBinIdx(stat.kmer)),\n                                stat.qual, stat.count);\n  }\n\n  bool IsHighQuality(const hammer::KMerStat& stat) const {\n    const auto bin = binarizer_.GetBin((double)GetKmerBinIdx(stat.kmer));\n    return trans_.Apply(stat.qual, stat.count) <= median_qualities_[bin];\n  }\n\n  double GenomicLogLikelihood(int bin, double quality, double count) const {\n    if (count <= lower_quality_threshold_) {\n      return -1e5;\n    }\n    const double x = trans_.Apply(quality, count);\n    return mixtures_[bin].FirstComponentPosterior(x);\n  }\n\n  static size_t GetKmerBinIdx(const hammer::HKMer& kmer) {\n    if (kmer.size() > 21) {\n      return 1 + kmer.max_run_length();\n    } else {\n      return 0;\n    }\n  }\n\n  static double ErrorLogLikelihood(int from, int to) {\n    int diff = std::abs(from - to);\n    from = std::max(from, 0);\n    --from;\n    int sign = from > to ? -1 : 1;\n    from = std::min((int)equal_likelihoods_.size() - 1, from);\n    if (diff == 0) {\n      return equal_likelihoods_[from];\n    }\n    if (sign == -1) {\n      return left_likelihoods_[from] * diff;\n    }\n    return right_likelihoods_[from] * diff;\n  }\n};\n\nclass NormalMixtureEstimator {\n private:\n  uint num_threads_;\n  size_t max_iterations_;\n  bool calc_likelihoods_;\n\n private:\n  std::vector<double> BuildPriors(const std::vector<double>& observations) const {\n    double threshold = SimpleTwoClassClustering::SimpleThresholdEstimation(\n                           observations.begin(), observations.end())\n                           .split_;\n\n    std::vector<double> priors(observations.size());\n\n#pragma omp parallel for num_threads(num_threads_)\n    for (size_t i = 0; i < observations.size(); ++i) {\n      priors[i] = observations[i] <= threshold ? 1 : 0;\n    }\n\n    return priors;\n  }\n\n  struct Stats {\n    double sum_left_ = 0;\n    double sum2_left_ = 0;\n    double weight_left_ = 0;\n    double sum_right_ = 0;\n    double sum2_right_ = 0;\n\n    Stats& operator+=(const Stats& other) {\n      if (this != &other) {\n        sum_left_ += other.sum_left_;\n        sum2_left_ += other.sum2_left_;\n        sum_right_ += other.sum_right_;\n        sum2_right_ += other.sum2_right_;\n        weight_left_ += other.weight_left_;\n      }\n      return *this;\n    }\n  };\n\n public:\n  NormalMixtureEstimator(uint num_threads,\n                         size_t max_iterations,\n                          bool calc_likelihood)\n      : num_threads_(num_threads),\n        max_iterations_(max_iterations),\n        calc_likelihoods_(calc_likelihood) {}\n\n  NormalMixture Estimate(std::vector<double>& observations) const {\n    std::sort(observations.begin(), observations.end(), std::greater<double>());\n    observations.resize(observations.size());\n    std::reverse(observations.begin(), observations.end());\n\n    std::vector<double> priors = BuildPriors(observations);\n\n    NormalMixture mixture;\n\n    for (size_t iter = 0; iter < max_iterations_; ++iter) {\n      auto stats =\n          n_computation_utils::ParallelStatisticsCalcer<Stats>(num_threads_)\n              .Calculate(observations.size(),\n                         [&]() -> Stats { return Stats(); },\n                         [&](Stats& stat, size_t k) {\n                           const double x = observations[k];\n                           const double w = priors[k];\n                           stat.sum2_left_ += w * x * x;\n                           stat.sum_left_ += w * x;\n                           stat.weight_left_ += w;\n                           stat.sum2_right_ += (1 - w) * x * x;\n                           stat.sum_right_ += (1 - w) * x;\n                         });\n\n      mixture =\n          NormalMixture(NormalDistribution::FromStats(\n                             stats.sum_left_, stats.sum2_left_, stats.weight_left_),\n                         NormalDistribution::FromStats(\n                             stats.sum_right_, stats.sum2_right_,\n                             (double)observations.size() - stats.weight_left_),\n                         stats.weight_left_ / (double)observations.size());\n\n// expectation\n#pragma omp parallel for num_threads(num_threads_)\n      for (size_t i = 0; i < observations.size(); ++i) {\n        priors[i] = exp(mixture.FirstComponentPosterior(observations[i]));\n      }\n\n      if (calc_likelihoods_) {\n        double ll = 0;\n        for (size_t i = 0; i < observations.size(); ++i) {\n          const double x = observations[i];\n          ll += mixture.LogLikelihood(x);\n        }\n        INFO(\"LogLikelihood: \" << ll);\n      }\n\n      if (iter == 0 || iter == (max_iterations_ - 1)) {\n        const double llFirst = mixture.GetFirst().LogLikelihoodFromStats(\n            stats.sum_left_, stats.sum2_left_, stats.weight_left_);\n        INFO(\"Likelihood first: \" << llFirst);\n        const double llSecond = mixture.GetSecond().LogLikelihoodFromStats(\n            stats.sum_right_, stats.sum2_right_,\n            (double)observations.size() - stats.weight_left_);\n        INFO(\"Likelihood second: \" << llSecond);\n        INFO(\"First weights: \" << mixture.GetFirstWeight());\n      }\n    }\n    return mixture;\n  };\n};\n\n// this class estimate prior distribution.\nclass ModelEstimator {\n private:\n  const KMerData& data_;\n  uint num_threads_;\n  size_t max_iterations_;\n  bool is_calc_likelihood_;\n\n public:\n  ModelEstimator(const KMerData& data,\n                 uint num_threads = 16,\n                 size_t maxIterations = 40,\n                 bool calc_likelihood = false)\n      : data_(data),\n        num_threads_(num_threads),\n        max_iterations_(maxIterations),\n        is_calc_likelihood_(calc_likelihood) {}\n\n  NormalClusterModel Estimate(\n      const std::vector<std::vector<size_t> >& clusters) {\n    QualityTransform trans;\n\n    std::vector<size_t> cluster_center;\n    {\n      cluster_center.resize(clusters.size());\n#pragma omp parallel for num_threads(num_threads_)\n      for (size_t i = 0; i < clusters.size(); ++i) {\n        auto& cluster = clusters[i];\n\n        double best_qual =\n            trans.Apply(data_[cluster[0]].qual, data_[cluster[0]].count);\n        size_t bestIdx = cluster[0];\n\n        for (auto idx : cluster) {\n          const auto qual = trans.Apply(data_[idx].qual, data_[idx].count);\n          if (qual < best_qual ||\n              (qual == best_qual &&\n               data_[idx].kmer.size() < data_[bestIdx].kmer.size())) {\n            best_qual = qual;\n            bestIdx = idx;\n          }\n          cluster_center[i] = bestIdx;\n        }\n      }\n    }\n\n    std::vector<std::vector<double> > qualities;\n    qualities.reserve(16);\n    const size_t sampleMaxThreshold = (size_t)1e9;\n    const size_t min_sample_size = (size_t)1e4;\n\n    {\n      double skip_threshold = cfg::get().noise_filter_count_threshold;  // threshold >= 10 ? 1 : 0;\n\n      for (size_t i = 0; i < cluster_center.size(); ++i) {\n        const auto& stat = data_[cluster_center[i]];\n\n        if (stat.count <= skip_threshold) {\n          continue;\n        }\n        const size_t bin = NormalClusterModel::GetKmerBinIdx(stat.kmer);\n\n        if (bin >= qualities.size()) {\n          qualities.resize(bin + 1);\n        }\n\n        if (qualities[bin].size() > sampleMaxThreshold) {\n          continue;\n        }\n        auto trans_qual = trans.Apply(stat.qual, stat.count);\n        qualities[bin].push_back(trans_qual);\n      }\n    }\n\n    std::vector<NormalMixture> models;\n    std::vector<double> borders;\n    std::vector<double> median_qualities;\n\n    size_t total_count = 0;\n    for (const auto& qual : qualities) {\n      total_count += qual.size();\n    }\n    assert(qualities[1].size() == 0);\n\n    {\n      auto model = NormalMixtureEstimator(num_threads_, max_iterations_, is_calc_likelihood_).Estimate(qualities[0]);\n\n      const double median_quality = FindHighQualityThreshold(qualities[0], model);\n      INFO(\"For kmer length <= 21\");\n      INFO(\"Median quality \" << median_quality);\n      INFO(\"Sample size \" << qualities[0].size());\n      INFO(\"Genomic dist: \" << model.GetFirst().GetMean() << \" \"\n                            << model.GetFirst().GetSigmaSqr());\n      INFO(\"NonGenomic dist: \" << model.GetSecond().GetMean() << \" \"\n                               << model.GetSecond().GetSigmaSqr());\n      models.push_back(model);\n      median_qualities.push_back(median_quality);\n      borders.push_back(0);\n      total_count -= qualities[0].size();\n    }\n\n    const auto len_limit = std::min(qualities.size(), 7UL);\n    for (uint max_run_len = 2; max_run_len < len_limit; ++max_run_len) {\n      if (total_count < min_sample_size) {\n        break;\n      }\n\n      const size_t bin = max_run_len + 1;\n      auto bin_qualities = qualities[bin];\n      total_count -= bin_qualities.size();\n\n      if (bin_qualities.size() < min_sample_size) {\n        if (bin + 1 < qualities.size()) {\n          qualities[bin + 1].insert(qualities[bin + 1].end(),\n                                    bin_qualities.begin(),\n                                    bin_qualities.end());\n        }\n        continue;\n      }\n\n      auto model = NormalMixtureEstimator(num_threads_, max_iterations_, is_calc_likelihood_).Estimate(bin_qualities);\n\n      const double median_quality = FindHighQualityThreshold(bin_qualities, model);\n\n      INFO(\"Sample size \" << bin_qualities.size());\n      INFO(\"Median quality \" << median_quality);\n      INFO(\"For max run length >= \" << max_run_len);\n      INFO(\"Genomic dist: \" << model.GetFirst().GetMean() << \" \"\n                            << model.GetFirst().GetSigmaSqr());\n      INFO(\"NonGenomic dist: \" << model.GetSecond().GetMean() << \" \"\n                               << model.GetSecond().GetSigmaSqr());\n      median_qualities.push_back(median_quality);\n      models.push_back(model);\n      borders.push_back((double)bin);\n    }\n    borders.resize(borders.size() - 1);\n\n    return NormalClusterModel(models, Binarizer(borders), median_qualities,\n                               trans);\n  }\n\n  double FindHighQualityThreshold(const std::vector<double>& bin_quality,\n                                  const NormalMixture& model) const {\n    std::vector<double> good_samples;\n    good_samples.reserve(bin_quality.size());\n    for (size_t i = 0; i < bin_quality.size(); ++i) {\n      if (model.FirstComponentPosterior(bin_quality[i]) > -0.69) {\n        good_samples.push_back(bin_quality[i]);\n      }\n    }\n\n    const size_t quantile = (size_t)((double)good_samples.size() * cfg::get().dist_one_subcluster_alpha);\n    std::nth_element(good_samples.begin(), good_samples.begin() + quantile,\n                     good_samples.end());\n    return good_samples[quantile];\n  }\n};\n\n}  // namespace NNormalModel\n\n#endif  // PROJECT_NORMAL_QUALITY_MODEL_HPP\n", "meta": {"hexsha": "c30a60d332b32aad9aa9b1919021da233f2e770f", "size": 15722, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/metaspades/src/projects/ionhammer/normal_quality_model.hpp", "max_stars_repo_name": "STRIDES-Codes/Exploring-the-Microbiome-", "max_stars_repo_head_hexsha": "bd29c8c74d8f40a58b63db28815acb4081f20d6b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/metaspades/src/projects/ionhammer/normal_quality_model.hpp", "max_issues_repo_name": "STRIDES-Codes/Exploring-the-Microbiome-", "max_issues_repo_head_hexsha": "bd29c8c74d8f40a58b63db28815acb4081f20d6b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/metaspades/src/projects/ionhammer/normal_quality_model.hpp", "max_forks_repo_name": "STRIDES-Codes/Exploring-the-Microbiome-", "max_forks_repo_head_hexsha": "bd29c8c74d8f40a58b63db28815acb4081f20d6b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-06-05T07:40:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-05T08:02:58.000Z", "avg_line_length": 32.0203665988, "max_line_length": 118, "alphanum_fraction": 0.6131535428, "num_tokens": 3712, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587875995482, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.45479262919143126}}
{"text": "#include <stan/math/rev.hpp>\n#include <test/unit/math/test_ad.hpp>\n#include <gtest/gtest.h>\n#include <boost/math/differentiation/finite_difference.hpp>\n\nTEST(mathMixScalFun, neg_binomial_2_log_lpmf_derivatives) {\n  auto f1 = [](const auto& eta, const auto& phi) {\n    return stan::math::neg_binomial_2_log_lpmf(0, eta, phi);\n  };\n  auto f2 = [](const auto& eta, const auto& phi) {\n    return stan::math::neg_binomial_2_log_lpmf(6, eta, phi);\n  };\n\n  stan::test::expect_ad(f1, -1.5, 4.1);\n  stan::test::expect_ad(f1, 2.0, 1.1);\n  stan::test::expect_ad(f2, -1.5, 4.1);\n  stan::test::expect_ad(f2, 2.0, 1.1);\n}\n", "meta": {"hexsha": "a04071c0ccb42980f89fb05fb16a6da12c7d131a", "size": 608, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/mix/prob/neg_binomial_2_log_test.cpp", "max_stars_repo_name": "LaudateCorpus1/math", "max_stars_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-18T13:10:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-18T13:10:50.000Z", "max_issues_repo_path": "test/unit/math/mix/prob/neg_binomial_2_log_test.cpp", "max_issues_repo_name": "LaudateCorpus1/math", "max_issues_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "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": "test/unit/math/mix/prob/neg_binomial_2_log_test.cpp", "max_forks_repo_name": "LaudateCorpus1/math", "max_forks_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-05-10T12:55:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-10T12:55:07.000Z", "avg_line_length": 32.0, "max_line_length": 60, "alphanum_fraction": 0.6776315789, "num_tokens": 218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402812, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.4547131277469311}}
{"text": "\n#include <ctime>\n\n#include <boost/random.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n\n#include \"NonlinearRBFFactorType.h\"\n\nnamespace Grante {\n\nNonlinearRBFFactorType::NonlinearRBFFactorType(const std::string& name,\n\tconst std::vector<unsigned int>& card,\n\tunsigned int data_size, unsigned int rbf_basis_count, double log_beta)\n\t: FactorType(name, card, data_size), rbfnet(rbf_basis_count, data_size),\n\t\trbf_basis_count(rbf_basis_count) {\n\tInitializeProdCard();\n\tassert(rbf_basis_count > 0);\n\n\tassert((boost::math::isnan)(log_beta) == false);\n\trbfnet.FixBeta(log_beta);\n\tsize_t wdim = prod_card * rbfnet.ParameterDimension();\n\n\t// Initialize weight vector randomly\n\tboost::mt19937 rgen(static_cast<const boost::uint32_t>(std::time(0))+1);\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// FIXME: better initialization concepts\n\tw.resize(wdim);\n\tstd::fill(w.begin(), w.end(), 0.0);\n\tsize_t wbase = 0;\n\tfor (unsigned int ri = 0; ri < prod_card; ++ri) {\n\t\t// Initialize alpha_n\n\t\tfor (unsigned int wi = 0; wi < rbf_basis_count; ++wi)\n\t\t\tw[wbase + wi] = randu() - 0.5;\n\n\t\t// Initialize c_n\n\t\tfor (unsigned int wi = 0; wi < (data_size*rbf_basis_count); ++wi)\n\t\t\tw[wbase + rbf_basis_count + wi] = randu() - 0.5;\n\n\t\twbase += rbfnet.ParameterDimension();\n\t}\n}\n\nNonlinearRBFFactorType::~NonlinearRBFFactorType() {\n}\n\nvoid NonlinearRBFFactorType::InitializeUsingTrainingData(const std::vector<\n\tParameterEstimationMethod::labeled_instance_type>& training_data) {\n\tboost::mt19937 rgen(static_cast<const boost::uint32_t>(std::time(0))+1);\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\tsize_t wbase = 0;\n\tfor (unsigned int ri = 0; ri < prod_card; ++ri) {\n\t\t// 1. Collect all factors that are labeled with the corresponding\n\t\t// ground truth label\n\t\tstd::vector<Factor*> m_factors;\n\t\tfor (unsigned int n = 0; n < training_data.size(); ++n) {\n\t\t\tconst FactorGraph* fg = training_data[n].first;\n\t\t\tconst FactorGraphObservation* obs = training_data[n].second;\n\t\t\tassert(obs->Type() == FactorGraphObservation::DiscreteLabelingType);\n\t\t\tconst std::vector<Factor*>& factors = fg->Factors();\n\t\t\tfor (unsigned int fi = 0; fi < factors.size(); ++fi) {\n\t\t\t\tif (factors[fi]->Type()->Name() != Name())\n\t\t\t\t\tcontinue;\n\n\t\t\t\tunsigned int ei_obs =\n\t\t\t\t\tfactors[fi]->ComputeAbsoluteIndex(obs->State());\n\t\t\t\tif (ei_obs != ri)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tm_factors.push_back(factors[fi]);\n\t\t\t}\n\t\t}\n\t\t// Need to be sure there is at least one observation\n\t\tassert(m_factors.size() >= 1);\n\t\tstd::cout << m_factors.size() << \" samples for statepair \"\n\t\t\t<< ri << std::endl;\n\n\t\t// Initialize alpha_n\n\t\tfor (unsigned int wi = 0; wi < rbf_basis_count; ++wi)\n\t\t\tw[wbase + wi] = 1.0;\n\n\t\t// Initialize c_n as sample from the training set\n\t\tsize_t wbi_base = 0;\n\t\tfor (unsigned int bi = 0; bi < rbf_basis_count; ++bi) {\n\t\t\tunsigned int mi = static_cast<unsigned int>(\n\t\t\t\trandu() * static_cast<double>(m_factors.size()));\n\t\t\tassert(mi < m_factors.size());\n\t\t\tconst std::vector<double>& H = m_factors[mi]->Data();\n\n\t\t\t// Copy selected training instance, perturbed\n\t\t\tassert(H.size() == data_size);\n\t\t\tfor (unsigned int wi = 0; wi < data_size; ++wi) {\n\t\t\t\tw[wbase + rbf_basis_count + wbi_base + wi] =\n\t\t\t\t\tH[wi] + randu()*1.0e-8;\n\t\t\t}\n\t\t\twbi_base += data_size;\n\t\t}\n\t\twbase += rbfnet.ParameterDimension();\n\t}\n\tassert(wbase == w.size());\n}\n\nvoid NonlinearRBFFactorType::InitializeWeights(\n\tconst std::vector<double>& weights) {\n\tassert(weights.size() == (prod_card * rbfnet.ParameterDimension()));\n\tthis->w = weights;\n}\n\nbool NonlinearRBFFactorType::IsDataDependent() const {\n\treturn (true);\n}\n\nvoid NonlinearRBFFactorType::ForwardMap(const Factor* factor,\n\tstd::vector<double>& energies) const {\n\tconst std::vector<double>& H = factor->Data();\n\tassert(H.size() == data_size);\n\tassert(energies.size() == prod_card);\n\tsize_t wbase = 0;\n\tfor (size_t ei = 0; ei < prod_card; ++ei) {\n\t\tenergies[ei] = rbfnet.Evaluate(H, w, wbase);\n\t\twbase += rbfnet.ParameterDimension();\n\t}\n}\n\nvoid NonlinearRBFFactorType::BackwardMap(const Factor* factor,\n\tconst std::vector<double>& marginals,\n\tstd::vector<double>& parameter_gradient, double mult) const {\n\tconst std::vector<double>& H = factor->Data();\n\tassert(H.size() == data_size);\n\tsize_t wbase = 0;\n\tfor (size_t ei = 0; ei < prod_card; ++ei) {\n\t\trbfnet.EvaluateGradient(H, w, parameter_gradient, wbase,\n\t\t\tmult * marginals[ei]);\n\t\twbase += rbfnet.ParameterDimension();\n\t}\n}\n\nconst RBFNetwork& NonlinearRBFFactorType::Net() const {\n\treturn (rbfnet);\n}\n\n}\n\n", "meta": {"hexsha": "f4152ffe66936122b8ee145c0ac91f1449af86dc", "size": 4658, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "grante/NonlinearRBFFactorType.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/NonlinearRBFFactorType.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/NonlinearRBFFactorType.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.2617449664, "max_line_length": 75, "alphanum_fraction": 0.6897810219, "num_tokens": 1354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619947119304, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.45471311454396557}}
{"text": "\ufeff/*M///////////////////////////////////////////////////////////////////////////////////////\r\n// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.\r\n//\r\n//  By downloading, copying, installing or using the software you agree to this license.\r\n//  If you do not agree to this license, do not download, install,\r\n//  copy or use the software.\r\n//\r\n//\r\n//                           License Agreement\r\n//                For Open Source Computer Vision Library\r\n//\r\n// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.\r\n// Copyright (C) 2008-2011, Willow Garage Inc., all rights reserved.\r\n// Third party copyrights are property of their respective owners.\r\n//\r\n// Redistribution and use in source and binary forms, with or without modification,\r\n// are permitted provided that the following conditions are met:\r\n//\r\n//   * Redistributions of source code must retain the above copyright notice,\r\n//     this list of conditions and the following disclaimer.\r\n//\r\n//   * Redistributions in binary form must reproduce the above copyright notice,\r\n//     this list of conditions and the following disclaimer in the documentation\r\n//     and/or other materials provided with the distribution.\r\n//\r\n//   * The name of the copyright holders may not be used to endorse or promote products\r\n//     derived from this software without specific prior written permission.\r\n//\r\n// This software is provided by the 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 disclaimed.\r\n// In no event shall the Intel Corporation or contributors be liable for any direct,\r\n// indirect, incidental, special, exemplary, or consequential damages\r\n// (including, but not limited to, procurement of substitute goods or services;\r\n// loss of use, data, or profits; or business interruption) however caused\r\n// 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\r\n// the use of this software, even if advised of the possibility of such damage.\r\n//\r\n// C by Benjamin Wassermann\r\n//M*/\r\n\r\n#ifndef _GEOMETRY_BASE_HPP_\r\n#define _GEOMETRY_BASE_HPP_\r\n#ifdef __cplusplus\r\n\r\n//#define EIGEN_MATRIXBASE_PLUGIN \"MatrixBaseAddons.h\"\r\n#include <Eigen/Dense>\r\n#include <Eigen/Geometry>\r\n#include <Eigen/StdVector>\r\n#include \"../utility/limit.hpp\"\r\n#include <cstdlib>\r\n\r\nnamespace lsfm {\r\n    namespace detail {\r\n        using std::round;\r\n        using std::abs;\r\n        using std::log;\r\n        using std::exp;\r\n        using std::sqrt;\r\n        using std::cos;\r\n        using std::acos;\r\n        using std::sin;\r\n        using std::asin;\r\n        using std::tan;\r\n        using std::atan;\r\n        using std::sinh;\r\n        using std::cosh;\r\n        using std::tanh;\r\n        using std::pow;\r\n        using std::atan2;\r\n        using std::hypot;\r\n    }\r\n\r\n\r\n    template<class FT>\r\n    FT getScalar(FT val){\r\n        return val;\r\n    }\r\n\r\n    // note -> use Eigen::DontAlign for eigen matrix to prevent align problems, eg. transpose etc.\r\n    // eigen seems to have problems wiht stl vector -> Eigen::aligned_allocator has to be used or\r\n    // EIGEN_DEFINE_STL_VECTOR_SPECIALIZATION or best swith off alignment?!\r\n    template<int rows, int _cols>\r\n    struct Major {\r\n        enum { type = ((rows > 1 || rows == Eigen::Dynamic) * (_cols > 1 || _cols == Eigen::Dynamic) * Eigen::RowMajor) | Eigen::DontAlign};\r\n\t\t//static constexpr int type = ((rows > 1 || rows == Eigen::Dynamic) * (_cols > 1 || _cols == Eigen::Dynamic) * Eigen::RowMajor) | Eigen::DontAlign ;\r\n    };\r\n\r\n\r\n\r\n    // matrix base, up to 4x4\r\n    template<class FT, int _rows, int _cols>\r\n    class Matx : public Eigen::Matrix<FT,_rows,_cols, Major<_rows,_cols>::type > {\r\n    public:\r\n        typedef FT float_type;\r\n\r\n        typedef Eigen::Matrix<FT,_rows,_cols, Major<_rows, _cols>::type> MatrixBase;\r\n        typedef typename MatrixBase::Base Base;\r\n        typedef typename MatrixBase::Index Index;\r\n\r\n        //typedef typename Base::PlainObject PlainObject;\r\n        //using Base::base;\r\n        //using Base::coeffRef;\r\n\r\n        //EIGEN_DENSE_PUBLIC_INTERFACE(MyMatrixBase)\r\n\r\n        //Matx(const MyMatrixBase& other) : Eigen::Matrix<FT,_rows,_cols>(other) {}\r\n\r\n        template<typename OtherDerived>\r\n        Matx(const Eigen::MatrixBase<OtherDerived>& other) : Eigen::Matrix<FT,_rows,_cols, Major<_rows,_cols>::type>(other) {}\r\n\r\n        template<typename OtherDerived>\r\n        Matx(const Eigen::ReturnByValue<OtherDerived>& other) : Eigen::Matrix<FT,_rows,_cols, Major<_rows,_cols>::type>(other) {}\r\n\r\n        template<typename OtherDerived>\r\n        Matx(const Eigen::EigenBase<OtherDerived> &other) : Eigen::Matrix<FT,_rows,_cols, Major<_rows,_cols>::type>(other) {}\r\n\r\n        Matx() : Eigen::Matrix<FT,_rows,_cols, Major<_rows,_cols>::type>() {}\r\n        Matx(const FT &v0, const FT &v1): Eigen::Matrix<FT,_rows,_cols, Major<_rows,_cols>::type>(v0,v1) {}\r\n        Matx(const FT &v0, const FT &v1, const FT &v2): Eigen::Matrix<FT,_rows,_cols, Major<_rows,_cols>::type>(v0,v1,v2) {}\r\n        Matx(const FT &v0, const FT &v1, const FT &v2, const FT &v3): Eigen::Matrix<FT,_rows,_cols, Major<_rows,_cols>::type>() {\r\n            if (_rows == 4 || _cols == 4) {\r\n                this->m_storage.data()[0] = v0;\r\n                this->m_storage.data()[1] = v1;\r\n                this->m_storage.data()[2] = v2;\r\n                this->m_storage.data()[3] = v3;\r\n                return;\r\n            }\r\n            *this << v0,v1,v2,v3;\r\n        }\r\n        Matx(const FT &v0, const FT &v1, const FT &v2, const FT &v3, const FT &v4): Eigen::Matrix<FT,_rows,_cols, Major<_rows,_cols>::type>() { *this << v0,v1,v2,v3,v4; }\r\n        Matx(const FT &v0, const FT &v1, const FT &v2, const FT &v3, const FT &v4, const FT &v5): Eigen::Matrix<FT,_rows,_cols, Major<_rows,_cols>::type>() { *this << v0,v1,v2,v3,v4,v5; }\r\n        Matx(const FT &v0, const FT &v1, const FT &v2, const FT &v3, const FT &v4, const FT &v5, const FT &v6): Eigen::Matrix<FT,_rows,_cols, Major<_rows,_cols>::type>() { *this << v0,v1,v2,v3,v4,v5, v6; }\r\n        Matx(const FT &v0, const FT &v1, const FT &v2, const FT &v3, const FT &v4, const FT &v5, const FT &v6, const FT &v7): Eigen::Matrix<FT,_rows,_cols, Major<_rows,_cols>::type>() { *this << v0,v1,v2,v3,v4,v5,v6,v7; }\r\n        Matx(const FT &v0, const FT &v1, const FT &v2, const FT &v3, const FT &v4, const FT &v5, const FT &v6, const FT &v7, const FT &v8): Eigen::Matrix<FT,_rows,_cols, Major<_rows,_cols>::type>() {\r\n            *this << v0,v1,v2,v3,v4,v5,v6,v7,v8;\r\n        }\r\n        Matx(const FT &v0, const FT &v1, const FT &v2, const FT &v3,\r\n             const FT &v4, const FT &v5, const FT &v6, const FT &v7,\r\n             const FT &v8, const FT &v9, const FT &v10, const FT &v11): Eigen::Matrix<FT,_rows,_cols, Major<_rows,_cols>::type>() { *this << v0,v1,v2,v3,v4,v5,v6,v7,v8,v9,v10,v11; }\r\n        Matx(const FT &v0, const FT &v1, const FT &v2, const FT &v3,\r\n             const FT &v4, const FT &v5, const FT &v6, const FT &v7,\r\n             const FT &v8, const FT &v9, const FT &v10, const FT &v11,\r\n             const FT &v12, const FT &v13, const FT &v14, const FT &v15): Eigen::Matrix<FT,_rows,_cols, Major<_rows,_cols>::type>() { *this << v0,v1,v2,v3,v4,v5,v6,v7,v8,v9,v10,v11,v12,v13,v14,v15; }\r\n\r\n        explicit Matx(const FT* vals) : Eigen::Matrix<FT,_rows,_cols, Major<_rows,_cols>::type>(vals) {}\r\n\r\n        /*Matx& operator=(const MyMatrixBase& other) {\r\n            this->Base::_set(other);\r\n            return *this;\r\n        }*/\r\n\r\n        template<typename OtherDerived>\r\n        Matx& operator=(const Eigen::MatrixBase<OtherDerived>& other) {\r\n            this->Base::operator=(other);\r\n            return *this;\r\n        }\r\n\r\n        template<typename OtherDerived>\r\n        Matx& operator=(const Eigen::EigenBase<OtherDerived> &other) {\r\n            this->Base::operator=(other);\r\n            return *this;\r\n        }\r\n\r\n        template<typename OtherDerived>\r\n        Matx& operator=(const Eigen::ReturnByValue<OtherDerived>& func) {\r\n            this->Base::operator=(func);\r\n            return *this;\r\n        }\r\n\r\n        // linear access\r\n        inline FT& operator[](Index idx) { return this->m_storage.data()[idx]; }\r\n        inline const FT& operator[](Index idx) const { return this->m_storage.data()[idx]; }\r\n\r\n        // point access\r\n        inline FT& x() { return this->m_storage.data()[0]; }\r\n        inline const FT& x() const { return this->m_storage.data()[0]; }\r\n\r\n        inline FT& y() { return this->m_storage.data()[1]; }\r\n        inline const FT& y() const { return this->m_storage.data()[1]; }\r\n\r\n        inline FT& z() { return this->m_storage.data()[2]; }\r\n        inline const FT& z() const { return this->m_storage.data()[2]; }\r\n\r\n        inline FT& w() { return this->m_storage.data()[3]; }\r\n        inline const FT& w() const { return this->m_storage.data()[3]; }\r\n    };\r\n\r\n\r\n    template<class FT>\r\n    using Matx22 = Matx<FT,2,2>;\r\n\r\n    template<class FT>\r\n    using Matx23 = Matx<FT,2,3>;\r\n\r\n    template<class FT>\r\n    using Matx32 = Matx<FT,3,2>;\r\n\r\n    template<class FT>\r\n    using Matx33 = Matx<FT,3,3>;\r\n\r\n    template<class FT>\r\n    using Matx34 = Matx<FT,3,4>;\r\n\r\n    template<class FT>\r\n    using Matx43 = Matx<FT,4,3>;\r\n\r\n    template<class FT>\r\n    using Matx44 = Matx<FT,4,4>;\r\n\r\n    typedef Matx22<float> Matx22f;\r\n    typedef Matx22<double> Matx22d;\r\n\r\n    typedef Matx23<float> Matx23f;\r\n    typedef Matx23<double> Matx23d;\r\n\r\n    typedef Matx32<float> Matx32f;\r\n    typedef Matx32<double> Matx32d;\r\n\r\n    typedef Matx33<float> Matx33f;\r\n    typedef Matx33<double> Matx33d;\r\n\r\n    typedef Matx34<float> Matx34f;\r\n    typedef Matx34<double> Matx34d;\r\n\r\n    typedef Matx43<float> Matx43f;\r\n    typedef Matx43<double> Matx43d;\r\n\r\n    typedef Matx44<float> Matx44f;\r\n    typedef Matx44<double> Matx44d;\r\n\r\n    template<class FT, int rows>\r\n    using Vec = Matx<FT,rows,1>;\r\n\r\n    template<class FT>\r\n    using Vec2 = Vec<FT,2>;\r\n\r\n    template<class FT>\r\n    using Vec3 = Vec<FT,3>;\r\n\r\n    template<class FT>\r\n    using Vec4 = Vec<FT,4>;\r\n\r\n    typedef Vec2<float> Vec2f;\r\n    typedef Vec2<double> Vec2d;\r\n    typedef Vec2<int> Vec2i;\r\n    typedef Vec3<float> Vec3f;\r\n    typedef Vec3<double> Vec3d;\r\n    typedef Vec3<int> Vec3i;\r\n    typedef Vec4<float> Vec4f;\r\n    typedef Vec4<double> Vec4d;\r\n    typedef Vec4<int> Vec4i;\r\n\r\n    template<class FT, int cols>\r\n    using RowVec = Matx<FT,1,cols>;\r\n\r\n    template<class FT>\r\n    using RowVec2 = RowVec<FT,2>;\r\n\r\n    template<class FT>\r\n    using RowVec3 = RowVec<FT,3>;\r\n\r\n    template<class FT>\r\n    using RowVec4 = RowVec<FT,4>;\r\n\r\n    typedef RowVec2<float> RowVec2f;\r\n    typedef RowVec2<double> RowVec2d;\r\n    typedef RowVec3<float> RowVec3f;\r\n    typedef RowVec3<double> RowVec3d;\r\n    typedef RowVec4<float> RowVec4f;\r\n    typedef RowVec4<double> RowVec4d;\r\n\r\n    //! convert rot vec to rot matrix\r\n    template<class FT>\r\n    inline Matx33<FT> rodrigues(const Vec3<FT> &r) {\r\n        Vec3<FT> axis;\r\n        FT angle = rodrigues(r,axis);\r\n        return Eigen::AngleAxis<FT>(angle,axis).matrix();\r\n\r\n    }\r\n\r\n    //! convert rot matrix to rot vec\r\n    template<class FT>\r\n    inline Vec3<FT> rodrigues(const Matx33<FT> &r) {\r\n        Eigen::AngleAxis<FT> axis(r);\r\n        return axis.axis() * axis.angle();\r\n    }\r\n\r\n    //! convert rot point to rot axis and angle\r\n    template<class FT>\r\n    inline FT rodrigues(const Vec3<FT> r, Vec3<FT> &axis) {\r\n        FT n = r.norm();\r\n        if (n < LIMITS<FT>::tau()) {\r\n            axis = Vec3<FT>(FT(1),FT(0),FT(0));\r\n            return FT(0);\r\n        }\r\n        axis = r / n;\r\n        return n;\r\n    }\r\n\r\n\r\n    //! compose homogeneouse matrix from trans vector and rot vector\r\n    template<class FT>\r\n    Matx44<FT> composeHom(const Vec3<FT> &trans, const Vec3<FT> &rot = Vec3<FT>(FT(0),FT(0),FT(0))) {\r\n        return composeHom(trans,rodrigues(rot));\r\n    }\r\n\r\n    //! compose homogeneouse matrix from trans vector and rot matrix\r\n    template<class FT>\r\n    Matx44<FT> composeHom(const Vec3<FT> &trans, const Matx33<FT> &rot) {\r\n        return Matx44<FT>(rot(0,0),rot(0,1),rot(0,2),trans.x(),\r\n                          rot(1,0),rot(1,1),rot(1,2),trans.y(),\r\n                          rot(2,0),rot(2,1),rot(2,2),trans.z(),\r\n                          FT(0) , FT(0),  FT(0) , FT(1));\r\n    }\r\n\r\n    //! compose homogeneouse matrix from other matrix\r\n    template<class FT>\r\n    Matx44<FT> composeHom(const Matx33<FT> &m) {\r\n        return Matx44<FT>(m(0,0),m(0,1),m(0,2),FT(0),\r\n                          m(1,0),m(1,1),m(1,2),FT(0),\r\n                          m(2,0),m(2,1),m(2,2),FT(0),\r\n                          FT(0) , FT(0),  FT(0) , FT(1));\r\n    }\r\n\r\n    //! decompose homogeneouse matrix to trans vector and rot vector\r\n    template<class FT>\r\n    void decomposeHom(const Matx44<FT> &m, Vec3<FT> &trans, Vec3<FT> &rot) {\r\n        Matx33<FT> r;\r\n        decomposeHom(m,trans,r);\r\n        rot = rodrigues(r);\r\n    }\r\n\r\n    //! decompose homogeneouse matrix to trans vector and rot matrix\r\n    template<class FT>\r\n    void decomposeHom(const Matx44<FT> &m, Vec3<FT> &trans, Matx33<FT> &rot) {\r\n        trans = Vec3<FT>(m(0,3),m(1,3),m(2,3));\r\n        decomposeHom(m,rot);\r\n    }\r\n\r\n    //! decompose homogeneouse matrix and  matrix\r\n    template<class FT>\r\n    void decomposeHom(const Matx44<FT> &m,  Matx33<FT> &m33) {\r\n        m33 = Matx33<FT>(m(0,0),m(0,1),m(0,2),\r\n                         m(1,0),m(1,1),m(1,2),\r\n                         m(2,0),m(2,1),m(2,2));\r\n    }\r\n\r\n    //! compose homogeneouse matrix from trans vector and rot matrix\r\n    template<class FT>\r\n    Matx33<FT> composeHom(const Vec2<FT> &trans, const Matx22<FT> &rot) {\r\n        return Matx33<FT>(rot(0,0),rot(0,1),trans.x(),\r\n                          rot(1,0),rot(1,1),trans.y(),\r\n                          FT(0) ,  FT(0),   FT(1));\r\n    }\r\n\r\n    //! compose homogeneouse matrix from other matrix\r\n    template<class FT>\r\n    Matx33<FT> composeHom(const Matx22<FT> &m) {\r\n        return Matx33<FT>(m(0,0),m(0,1),FT(0),\r\n                          m(1,0),m(1,1),FT(0),\r\n                          FT(0) , FT(0),FT(1));\r\n    }\r\n\r\n    //! decompose homogeneouse matrix to trans vector and rot matrix\r\n    template<class FT>\r\n    void decomposeHom(const Matx33<FT> &m, Vec2<FT> &trans, Matx22<FT> &rot) {\r\n        trans = Vec3<FT>(m(0,2),m(1,2));\r\n        decomposeHom(m,rot);\r\n    }\r\n\r\n    //! decompose homogeneouse matrix to matrix\r\n    template<class FT>\r\n    void decomposeHom(const Matx33<FT> &m, Matx22<FT> &m22) {\r\n        m22 = Matx33<FT>(m(0,0),m(0,1),\r\n                         m(1,0),m(1,1));\r\n    }\r\n}\r\n\r\nnamespace Eigen {\r\n    namespace internal {\r\n        template<typename _Scalar, int _Rows, int _Cols>\r\n        struct traits<lsfm::Matx<_Scalar, _Rows, _Cols> >\r\n        {\r\n          typedef _Scalar Scalar;\r\n          typedef Dense StorageKind;\r\n          typedef DenseIndex StorageIndex;\r\n          typedef MatrixXpr XprKind;\r\n          enum {\r\n            RowsAtCompileTime = _Rows,\r\n            ColsAtCompileTime = _Cols,\r\n            MaxRowsAtCompileTime = Dynamic,\r\n            MaxColsAtCompileTime = Dynamic,\r\n            Flags = compute_matrix_flags<_Scalar, _Rows, _Cols, lsfm::Major<_Rows,_Cols>::type, Dynamic, Dynamic>::ret,\r\n            CoeffReadCost = NumTraits<Scalar>::ReadCost,\r\n            Options = lsfm::Major<_Rows,_Cols>::type,\r\n            InnerStrideAtCompileTime = 1,\r\n            OuterStrideAtCompileTime = (Options&RowMajor) ? ColsAtCompileTime : RowsAtCompileTime\r\n          };\r\n        };\r\n    }\r\n}\r\n\r\n\r\n#endif\r\n#endif\r\n", "meta": {"hexsha": "0bbc81fe5bb2d4d2ce8bb5ce9402fb94ebebf328", "size": 15759, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/geometry/base.hpp", "max_stars_repo_name": "waterben/LineExtraction", "max_stars_repo_head_hexsha": "d247de45417a1512a3bf5d0ffcd630d40ffb8798", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-12T13:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-12T13:30:56.000Z", "max_issues_repo_path": "include/geometry/base.hpp", "max_issues_repo_name": "waterben/LineExtraction", "max_issues_repo_head_hexsha": "d247de45417a1512a3bf5d0ffcd630d40ffb8798", "max_issues_repo_licenses": ["MIT"], "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/geometry/base.hpp", "max_forks_repo_name": "waterben/LineExtraction", "max_forks_repo_head_hexsha": "d247de45417a1512a3bf5d0ffcd630d40ffb8798", "max_forks_repo_licenses": ["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.625, "max_line_length": 222, "alphanum_fraction": 0.5884891173, "num_tokens": 4495, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.4546844443567475}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// kernel::functional::rp_visitor.hpp                                        //\n//                                                                           //\n//  Copyright 2009 Erwann Rogard. Distributed under the Boost                //\n//  Software License, Version 1.0. (See accompanying file                    //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)         //\n/////////////////////////////////////////////////////////////////////////////// \n#ifndef BOOST_STATISTICS_DETAIL_KERNEL_ESTIMATION_RP_VISITOR_HPP_ER_2009\n#define BOOST_STATISTICS_DETAIL_KERNEL_ESTIMATION_RP_VISITOR_HPP_ER_2009\n#include <boost/type_traits/is_reference.hpp>\n#include <boost/mpl/not.hpp>\n#include <boost/call_traits.hpp>\n#include <boost/statistics/detail/kernel/estimation/detail/mean_accumulator.hpp>\n//#include <boost/statistics/detail/kernel/estimation/detail/return_if.hpp>\n//#include <boost/statistics/detail/kernel/estimation/detail/range_difference.hpp>\n\nnamespace boost{\nnamespace statistics{\nnamespace detail{\nnamespace kernel{\n\n// This visitor, f, keeps a data point, x0, and each time f(x) is called, it \n// updates an estimate of the density at x0, p(x0), by the Rosenblatt-Parzen \n// method, using a given kernel k.\n//\n// The estimate is the average of the kernel evaluations over the traversed \n// dataset. That average is implemented by an accumulator of type A.\n//\n// X can be a reference which is only recommended if the x object is expensive \n// to copy\ntemplate<\n    typename K,\n    typename X,\n    typename A = typename \n        statistics::detail::kernel::detail::mean_accumulator<typename K::result_type>::type \n>\nclass rp_visitor : K{ //, addable<rp_visitor<K,X,A> >{ // \n    typedef is_reference<X> is_ref_;\n    public:\n    typedef K kernel_type;\n    typedef A accumulator_type;\n    typedef typename K::result_type result_type;\n\n    // Construct\n    rp_visitor();\n    rp_visitor(typename call_traits<X>::param_type);\n    rp_visitor(\n        K k, // passing radius calls implicit conversion\n        typename call_traits<X>::param_type x\n    );\n    rp_visitor(\n        K k,\n        typename call_traits<X>::param_type,\n        const accumulator_type&\n    );\n    rp_visitor(const rp_visitor&);\n    rp_visitor& operator=(const rp_visitor&);\n    \n    // Update\n    // Passing the training data x1 updates the estimator\n    template<typename X1> result_type operator()(const X1& x1);\n    \n    // Access\n    typename call_traits<X>::const_reference x()const;\n    const A& accumulator()const;\n    const result_type& normalizing_constant()const;\n\n    result_type estimate()const; \n\n    private:\n    typename call_traits<X>::value_type x_;\n    A acc_;\n};\n\n//Construction\ntemplate<typename K,typename X,typename A>\nrp_visitor<K,X,A>::rp_visitor(){\n    BOOST_MPL_ASSERT((\n        mpl::not_<is_ref_>\n    ));\n}\n\ntemplate<typename K,typename X,typename A>\nrp_visitor<K,X,A>::rp_visitor(K k,typename call_traits<X>::param_type x)\n:K(k),x_(x),acc_(){}\n    \ntemplate<typename K,typename X,typename A>\nrp_visitor<K,X,A>::rp_visitor(\n    K k,\n    typename call_traits<X>::param_type x,\n    const A& a\n):K(k),x_(x),acc_(a){}\n\ntemplate<typename K,typename X,typename A>\nrp_visitor<K,X,A>::rp_visitor(const rp_visitor& that)\n:K(static_cast<const K&>(that)),x_(that.x_),acc_(that.acc_){}\n\ntemplate<typename K,typename X,typename A>\ntypename rp_visitor<K,X,A>::rp_visitor& \nrp_visitor<K,X,A>::operator=(const rp_visitor& that){\n    if(&that!=this){\n        BOOST_MPL_ASSERT((mpl::not_<is_ref_>));\n        K::operator=(static_cast<const K&>(*that)); \n        x_ = that.x_;\n        acc_ = that.acc_;\n    }   \n    return *this;\n}\n\n// Evaluate\ntemplate<typename K,typename X,typename A>\ntemplate<typename X1>\ntypename rp_visitor<K,X,A>::result_type\nrp_visitor<K,X,A>::operator()(const X1& x1){\n    const K& kernel = static_cast<const K&>(*this);\n    result_type t = kernel(x(),x1);\n    this->acc_(t);\n    return t;\n}\n\n\n// Access\ntemplate<typename K,typename X,typename A>\ntypename rp_visitor<K,X,A>::result_type\nrp_visitor<K,X,A>::estimate()const{\n    return accumulators::mean(\n        this->accumulator()\n    );\n}\n\ntemplate<typename K,typename X,typename A>\nconst A&\nrp_visitor<K,X,A>::accumulator()const{\n    return  this->acc_;\n}\n    \ntemplate<typename K,typename X,typename A>\nconst typename rp_visitor<K,X,A>::result_type&\nrp_visitor<K,X,A>::normalizing_constant()const{\n    const K& k = static_cast<const K&>(*this);\n    return k.normalizing_constant();\n}\n\ntemplate<typename K,typename X,typename A>\ntypename call_traits<X>::const_reference\nrp_visitor<K,X,A>::x()const{\n    return this->x_;\n}\n    \n\n}// kernel\n}// detail\n}// statistics\n}// boost\n\n#endif", "meta": {"hexsha": "67ae3fe88c0f711b7d8cbd413bd6715b2e1aee94", "size": 4749, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "kernel/boost/statistics/detail/kernel/estimation/rp_visitor.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": "kernel/boost/statistics/detail/kernel/estimation/rp_visitor.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": "kernel/boost/statistics/detail/kernel/estimation/rp_visitor.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": 30.4423076923, "max_line_length": 92, "alphanum_fraction": 0.6550852811, "num_tokens": 1124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.705785040214066, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.4546844426883933}}
{"text": "#ifndef CAPPA_CLUSTER_DISTANCE_HPP\n#define CAPPA_CLUSTER_DISTANCE_HPP\n\n#include <Eigen/Dense>\n\nnamespace cluster {\n\ndouble euclidean_distance(Eigen::VectorXd const &vector1, Eigen::VectorXd const &vector2);\n\nEigen::MatrixXd calculate_distance_matrix(Eigen::MatrixXd const &matrix);\n}\n\n#endif //CAPPA_CLUSTER_DISTANCE_HPP\n", "meta": {"hexsha": "40be1e7b83c708035d0da442bc85f99bb3fe0692", "size": 321, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/cluster/distance.hpp", "max_stars_repo_name": "cappa-framework/cluster", "max_stars_repo_head_hexsha": "be199505293b4a6b43774deeaad87452ad6cf1e9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-01-17T13:53:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-11T05:09:59.000Z", "max_issues_repo_path": "include/cluster/distance.hpp", "max_issues_repo_name": "cappa-framework/cluster", "max_issues_repo_head_hexsha": "be199505293b4a6b43774deeaad87452ad6cf1e9", "max_issues_repo_licenses": ["Apache-2.0"], "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/cluster/distance.hpp", "max_forks_repo_name": "cappa-framework/cluster", "max_forks_repo_head_hexsha": "be199505293b4a6b43774deeaad87452ad6cf1e9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-10-17T20:12:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-17T20:12:36.000Z", "avg_line_length": 22.9285714286, "max_line_length": 90, "alphanum_fraction": 0.8224299065, "num_tokens": 67, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.6442251133170356, "lm_q1q2_score": 0.4546844395357657}}
{"text": "//\n// Created by Alex Beccaro on 18/01/18.\n//\n\n#define BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n#include \"../../src/problems/1-50/25/problem25.hpp\"\n\nBOOST_AUTO_TEST_SUITE( Problem25 )\n\n    BOOST_AUTO_TEST_CASE( Example ) {\n        auto res = problems::problem25::solve(3);\n        BOOST_CHECK_EQUAL(res, 12);\n    }\n\n    BOOST_AUTO_TEST_CASE( Solution ) {\n        auto res = problems::problem25::solve();\n        BOOST_CHECK_EQUAL(res, 4782);\n    }\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "fed1f12913c4c43dbaa99a50c9affa51354c5acb", "size": 491, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/1-50/test_problem25.cpp", "max_stars_repo_name": "abeccaro/project-euler", "max_stars_repo_head_hexsha": "c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T10:17:15.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-25T10:17:15.000Z", "max_issues_repo_path": "tests/1-50/test_problem25.cpp", "max_issues_repo_name": "abeccaro/project-euler", "max_issues_repo_head_hexsha": "c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3", "max_issues_repo_licenses": ["MIT"], "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/1-50/test_problem25.cpp", "max_forks_repo_name": "abeccaro/project-euler", "max_forks_repo_head_hexsha": "c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3", "max_forks_repo_licenses": ["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.380952381, "max_line_length": 51, "alphanum_fraction": 0.6741344196, "num_tokens": 125, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.4546844347147839}}
{"text": "//=======================================================================\n// Copyright (c) 2013 Piotr Smulewicz\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n/**\n * @file scheduling_jobs_with_deadlines_on_a_single_machine.hpp\n * @brief\n * @author Piotr Smulewicz\n * @version 1.0\n * @date 2013-09-09\n */\n#ifndef PAAL_SCHEDULING_JOBS_WITH_DEADLINES_ON_A_SINGLE_MACHINE_HPP\n#define PAAL_SCHEDULING_JOBS_WITH_DEADLINES_ON_A_SINGLE_MACHINE_HPP\n\n#include \"paal/utils/functors.hpp\"\n#include \"paal/utils/type_functions.hpp\"\n#include \"paal/utils/assign_updates.hpp\"\n\n#include <boost/iterator/counting_iterator.hpp>\n#include <boost/range/algorithm/sort.hpp>\n\n#include <queue>\n#include <vector>\n#include <algorithm>\n#include <utility>\n\nnamespace paal {\nnamespace greedy {\n\n/**\n * @brief solve scheduling jobs on identical parallel machines problem\n * and fill start time of all jobs\n * example:\n * \\snippet scheduling_jobs_with_deadlines_on_a_single_machine_example.cpp Scheduling Jobs On Single Machine Example\n * example file is\n * scheduling_jobs_with_deadlines_on_a_single_machine_example.cpp\n * @param first - jobs begin\n * @param last - jobs end\n * @param get_time\n * @param get_release_date\n * @param get_due_date\n * @param result\n * @tparam Time\n * @tparam InputIterator\n * @tparam OutputIterator\n * @tparam GetTime\n * @tparam GetDueDate\n * @tparam GetReleaseDate\n */\ntemplate <class InputIterator, class OutputIterator, class GetTime,\n          class GetDueDate, class GetReleaseDate>\nauto scheduling_jobs_with_deadlines_on_a_single_machine(\n    const InputIterator first, const InputIterator last, GetTime get_time,\n    GetReleaseDate get_release_date, GetDueDate get_due_date,\n    OutputIterator result) {\n    using Time = puretype(get_time(*first));\n    std::vector<InputIterator> jobs;\n    std::copy(boost::make_counting_iterator(first),\n              boost::make_counting_iterator(last), std::back_inserter(jobs));\n\n    auto get_due_date_from_iterator =\n        utils::make_lift_iterator_functor(get_due_date);\n    auto due_date_compatator = utils::make_functor_to_comparator(\n        get_due_date_from_iterator, utils::greater{});\n    using QueueType = std::priority_queue<\n        InputIterator, std::vector<InputIterator>, decltype(due_date_compatator)>;\n    QueueType active_jobs_iters(due_date_compatator);\n\n    auto get_release_date_from_iterator =\n        utils::make_lift_iterator_functor(get_release_date);\n    boost::sort(jobs,\n              utils::make_functor_to_comparator(get_release_date_from_iterator));\n    Time start_idle = Time();\n    Time longest_delay = Time();\n    auto do_job = [&]() {\n        auto job_iter = active_jobs_iters.top();\n        active_jobs_iters.pop();\n        Time start_time = std::max(start_idle, get_release_date(*job_iter));\n        start_idle = start_time + get_time(*job_iter);\n        assign_max(longest_delay, start_idle - get_due_date(*job_iter));\n        *result = std::make_pair(job_iter, start_time);\n        ++result;\n    };\n    for (auto job_iter : jobs) {\n        while (!active_jobs_iters.empty() &&\n               get_release_date(*job_iter) > start_idle)\n            do_job();\n        active_jobs_iters.push(job_iter);\n    }\n    while (!active_jobs_iters.empty()) {\n        do_job();\n    }\n\n    return longest_delay;\n}\n\n} //!greedy\n} //!paal\n\n#endif // PAAL_SCHEDULING_JOBS_WITH_DEADLINES_ON_A_SINGLE_MACHINE_HPP\n", "meta": {"hexsha": "56d46528b8596c15e82f0c7357e3659d07c642cb", "size": 3560, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/paal/greedy/scheduling_jobs_with_deadlines_on_a_single_machine/scheduling_jobs_with_deadlines_on_a_single_machine.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_with_deadlines_on_a_single_machine/scheduling_jobs_with_deadlines_on_a_single_machine.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_with_deadlines_on_a_single_machine/scheduling_jobs_with_deadlines_on_a_single_machine.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": 34.2307692308, "max_line_length": 116, "alphanum_fraction": 0.7019662921, "num_tokens": 820, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.6442250996557036, "lm_q1q2_score": 0.45468442989380214}}
{"text": "#ifndef GEM_TENSOR_BASE_HPP_INCLUDED\n#define GEM_TENSOR_BASE_HPP_INCLUDED\n\n#include <ostream>\n#include <string>\n\n#include <boost/hana/type.hpp>\n#include <boost/hana/integral_constant.hpp>\n#include <boost/hana/reverse.hpp>\n#include <boost/hana/back.hpp>\n#include <boost/hana/drop_back.hpp>\n#include <boost/hana/for_each.hpp>\n#include <boost/hana/greater.hpp>\n#include <boost/hana/assert.hpp>\n\n#include <cereal/cereal.hpp>\n#include <cereal/access.hpp>\n\n#include <gem/type.hpp>\n#include <gem/dimensions_tuple.hpp>\n#include <gem/cereal/hana_binder.hpp>\n\nnamespace gem {\n\ntemplate <typename dtype, long long n_con, long long n_cov,\n          gem::concepts::Dimension... dims>\nclass TensorBase\n{\n\npublic:\n    using type_t = TensorBase;\n    using data_t = dtype;\n\n    using dimension_tuple_t = DimensionTuple<false, n_con, n_cov, dims...>;\n    using dimension_tuple_common_t = typename dimension_tuple_t::common_t;\n\n    template<typename n_dtype, long long n_n_con, long long n_n_cov,\n             gem::concepts::Dimension... n_dims>\n    friend class TensorBase;\n\n    friend class cereal::access;\n\npublic:\n    static constexpr\n    boost::hana::type<type_t> type {};\n\n    static constexpr\n    boost::hana::type<data_t> data_type {};\n\n    static constexpr\n    boost::hana::ullong<sizeof...(dims)> order {};\n\n    static constexpr\n    boost::hana::ullong<n_con> contravariants {};\n\n    static constexpr\n    boost::hana::ullong<n_cov> covariants {};\n\n    dimension_tuple_t dim;\n\n    static constexpr BOOST_HANA_CONSTANT_CHECK_MSG(\n        contravariants + covariants == order,\n        \"Contravariants and covariants must add up to the order \"\n        \"(number of dimensions)\");\n    static constexpr BOOST_HANA_CONSTANT_CHECK_MSG(\n        0_u <= contravariants,\n        \"The number of contravariants must be positive\");\n    static constexpr  BOOST_HANA_CONSTANT_CHECK_MSG(\n        0_u <= covariants,\n        \"The number of covariants must be positive\");\n\npublic:\n\n    TensorBase(void) = delete;\n\n    constexpr inline TensorBase(const dims&... d) noexcept :\n        dim(d...)\n    {\n\n    }\n\n    constexpr inline TensorBase(dims&&... d) noexcept :\n        dim(std::forward<dims>(d)...)\n    {\n\n    }\n\n\n    constexpr inline TensorBase(const TensorBase & tensor) noexcept :\n        dim(tensor.dim)\n    {\n\n    }\n\n    constexpr inline TensorBase(TensorBase && tensor) noexcept :\n        dim(std::move(tensor.dim))\n    {\n\n    }\n\n    constexpr inline auto rows(void) const noexcept\n        -> const std::enable_if_t<(order > 0_u),\n                                  decltype(dim[GEM_START_IDX])> &\n    {\n        return dim[GEM_START_IDX];\n    }\n\n    constexpr inline auto cols(void) const noexcept\n        -> const std::enable_if_t<(order > 1_u),\n                                  decltype(dim[GEM_START_IDX + 1_u])> &\n    {\n        return dim[GEM_START_IDX + 1_u];\n    }\n\n    constexpr inline auto size(void) const noexcept\n    {\n        return dim.size();\n    }\n\n    constexpr inline auto operator =(const TensorBase & tensor) noexcept\n    {\n        dim = tensor.dim;\n        return *this;\n    }\n\n    constexpr inline auto operator =(TensorBase && tensor) noexcept\n    {\n        dim = std::move(tensor.dim);\n        return *this;\n    }\n\n    constexpr inline auto operator ==(const TensorBase & tensor) noexcept\n    {\n        return dim == tensor.dim;\n    }\n\n    constexpr inline auto operator !=(const TensorBase & tensor) noexcept\n    {\n        return dim != tensor.dim;\n    }\n\n    constexpr inline auto operator ()(void) const noexcept\n        -> const type_t &\n    {\n        return *this;\n    }\n\n    constexpr inline auto operator ()(void) noexcept\n        -> type_t &\n    {\n        return *this;\n    }\n\n    constexpr inline auto transpose(void) const noexcept\n    {\n        constexpr auto construct_ = [](auto... args) {\n            return TensorBase<dtype, n_cov, n_con, decltype(args)...>(args...);\n        };\n        return boost::hana::unpack(boost::hana::reverse(dim), construct_);\n    }\n\n    friend inline auto\n    operator <<(std::ostream& os, const TensorBase & tensor)\n        -> std::ostream&\n    {\n        os << \"covariants: \" << covariants << \", \";\n        os << \"contravariants: \" << contravariants << \", \";\n        os << \"dimensions: {\";\n        boost::hana::for_each(\n            boost::hana::drop_back(tensor.dim), [&](auto const& d){\n                os << d << \", \";\n            }\n        );\n        os << boost::hana::back(tensor.dim) << '}';\n        return os;\n    }\n\nprivate:\n\n    template<class Archive>\n    auto save(Archive & archive) const -> void\n    {\n        // archive(cereal::make_nvp(\"data_type\",\n        //                          gem::demangle(typeid(data_t).name())),\n        //         CEREAL_NVP(order),\n        //         CEREAL_NVP(contravariants), CEREAL_NVP(covariants),\n        //         cereal::make_nvp(\"size\", size()),\n        //         cereal::make_nvp(\"dimensions\", dim));\n        archive(cereal::make_nvp(\"data_type\",\n                                 gem::demangle(typeid(data_t).name())),\n                CEREAL_NVP(order),\n                CEREAL_NVP(contravariants), CEREAL_NVP(covariants),\n                cereal::make_nvp(\"size\", size())\n                // cereal::make_nvp(\"dimensions\", dim)\n                );\n// archive(cereal::make_size_tag(n_con + n_cov));\n        // archive(cereal::make_nvp(\"dimensions\", dim));\n    }\n\n    template<class Archive>\n    auto load(Archive & archive) -> void\n    {\n\n    }\n\n};\n\ntemplate <typename dtype, long long n_con, long long n_cov,\n          gem::concepts::Dimension... dims>\nconstexpr\nboost::hana::ullong<sizeof...(dims)>\nTensorBase<dtype, n_con, n_cov, dims...>::order;\n\ntemplate <typename dtype, long long n_con, long long n_cov,\n          gem::concepts::Dimension... dims>\nconstexpr\nboost::hana::ullong<n_con>\nTensorBase<dtype, n_con, n_cov, dims...>::contravariants;\n\ntemplate <typename dtype, long long n_con, long long n_cov,\n          gem::concepts::Dimension... dims>\nconstexpr\nboost::hana::ullong<n_cov>\nTensorBase<dtype, n_con, n_cov, dims...>::covariants;\n\ntemplate <typename dtype, long long n_con, long long n_cov,\n          gem::concepts::Dimension... dims>\nconstexpr boost::hana::type<typename TensorBase<dtype, n_con, n_cov,\n                            dims...>::type_t>\nTensorBase<dtype, n_con, n_cov, dims...>::type;\n\ntemplate <typename dtype, long long n_con, long long n_cov,\n          gem::concepts::Dimension... dims>\nconstexpr boost::hana::type<typename TensorBase<dtype, n_con, n_cov,\n                                                dims...>::data_t>\nTensorBase<dtype, n_con, n_cov, dims...>::data_type;\n\n}  // namespace gem\n\n#endif  // !GEM_TENSOR_BASE_HPP_INCLUDED\n", "meta": {"hexsha": "d1629c769f0603d4a715781cc7cabae5c8add949", "size": 6668, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/gem/tensor_base.hpp", "max_stars_repo_name": "RomainBrault/Gem", "max_stars_repo_head_hexsha": "0eff3cb034a0faaca894316b72f4b005e72e0f5d", "max_stars_repo_licenses": ["MIT"], "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/gem/tensor_base.hpp", "max_issues_repo_name": "RomainBrault/Gem", "max_issues_repo_head_hexsha": "0eff3cb034a0faaca894316b72f4b005e72e0f5d", "max_issues_repo_licenses": ["MIT"], "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/gem/tensor_base.hpp", "max_forks_repo_name": "RomainBrault/Gem", "max_forks_repo_head_hexsha": "0eff3cb034a0faaca894316b72f4b005e72e0f5d", "max_forks_repo_licenses": ["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.6680497925, "max_line_length": 79, "alphanum_fraction": 0.6096280744, "num_tokens": 1602, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850154599563, "lm_q2_score": 0.6442250996557036, "lm_q1q2_score": 0.4546844219201927}}
{"text": "//\n// Created by Zhongshi Jiang on 2/9/17.\n//\n\n#include <igl/igl_inline.h>\n#include <Eigen/Dense>\nnamespace igl {\n\ntemplate <\n    typename DerivedV,\n    typename DerivedT,\n    typename DerivedF,\n    typename DerivedSV,\n    typename DerivedSVI,\n    typename DerivedSVJ,\n    typename DerivedST,\n    typename DerivedSF>\nIGL_INLINE void remove_duplicate_vertices(\n    const Eigen::MatrixBase<DerivedV>& V,\n    const Eigen::MatrixBase<DerivedT>& T,\n    const Eigen::MatrixBase<DerivedF>& F,\n    const double epsilon,\n    Eigen::PlainObjectBase<DerivedSV>& SV,\n    Eigen::PlainObjectBase<DerivedSVI>& SVI,\n    Eigen::PlainObjectBase<DerivedSVJ>& SVJ,\n    Eigen::PlainObjectBase<DerivedST>& ST,\n    Eigen::PlainObjectBase<DerivedSF>& SF) {\n  using namespace Eigen;\n  using namespace std;\n  remove_duplicate_vertices(V, epsilon, SV, SVI, SVJ);\n  SF.resizeLike(F);\n  ST.resizeLike(T);\n  for (int f = 0; f < F.rows(); f++) {\n    for (int c = 0; c < F.cols(); c++) {\n      SF(f, c) = SVJ(F(f, c));\n    }\n  }\n  for (int f = 0; f < T.rows(); f++) {\n    for (int c = 0; c < T.cols(); c++) {\n      ST(f, c) = SVJ(T(f, c));\n    }\n  }\n\n};\n}\n/*\ntemplate void igl::remove_duplicate_vertices<Eigen::Matrix<double, -1, -1, 0,\n                                                          -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<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&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, double, 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> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&);\n*/", "meta": {"hexsha": "ac19d45029124ea30b7202bd56c22df256775813", "size": 2089, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/util/tet_utils.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/util/tet_utils.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/util/tet_utils.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": 42.6326530612, "max_line_length": 881, "alphanum_fraction": 0.5883197702, "num_tokens": 738, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850154599562, "lm_q2_score": 0.6442250996557035, "lm_q1q2_score": 0.45468442192019254}}
{"text": "#include <iostream>\n#include <fstream>\n#include <string>\n#include <Eigen/Dense>\n\n#include \"spline_kernel.h\"\n#include \"interval.h\"\n#include \"cardinal_spline.h\"\n#include \"kernel\\spline.h\"\n#include \"generate_spline.h\"\n#include \"data.h\"\n#include \"classic_methods.h\"\nusing namespace std;\nusing namespace spl;\n\n\ntemplate<typename T>\nvoid SaveFunctionToFile(T f, spl::interval interval, int grid_size, string path) \n{\n\tconst auto [a, b] = interval;\n\n\tofstream myfile(path + \"\\\\example.txt\");\n\tif (myfile.is_open())\n\t{\n\t\t\n\t\tfor (int i = 0; i < grid_size; i++)\n\t\t{\n\t\t\tauto x = a + i * interval.get_step(grid_size);\n\t\t\tauto y = f(x);\n\t\t\tmyfile << x << \" \" << y << std::endl;\n\t\t}\n\n\n\t\tmyfile.close();\n\t}\n\telse cout << \"Unable to open file\";\n}\n\n\n\n\n\nvoid test1()\n{\n\tusing spl::data::calculate_points;\n\tusing spl::generator::create_spline;\n\n\tauto f = [](double t)->double {return t*t + 1.; };\n\tinterval interv = { 0., 1. };\n\tauto sp_f = create_spline<double, 2u>(f, interv, 10);\n\n\tconst auto points = calculate_points<double>(f, interv, 100);\n\n\tfor (size_t i = 0; i < 100; i++)\n\t{\n\t\tstd::cout << points[i] << \", \";\n\t}\n}\n\nvoid test2()\n{\n\tconst double root = std::sqrt(2.);\n\tauto f = [root](double t)->double {\n\t\treturn std::pow(t - root, 3);\n\t};\n\tinterval interv = { -10., 10. };\n\t\n\tauto answer = spl::numeric::bisection<double>(f, interv, 1e-6, \n\t\t[](std::function<double(double)> func, interval gap)->bool {\n\t\tif (func(gap._aborder) * func(gap._bborder) < 0.)\n\t\t\treturn true;\n\t\treturn false;\n\t\t});\n\n\tif (answer)\n\t\tstd::cout <<\"bisection error = \"<< std::abs(answer.value() - root) << std::endl;\n}\n\nint main()\n{\n\ttest2();\n\ttest1();\n\tEigen::Vector2f vec(0, 1);\n\tusing spl::ker::spline;\n\n\tspl::interval interval(1.4, 1.0);\n\tspl::interval i = {0.0, 1.0};\n\tauto [a, b] = i;\n\n\n\n\tstd::cout << a << \" \" << b << std::endl;\n\tstd::cout << interval.length() << std::endl;\n\n    std::cout << \"Hello World! \" << meaning_of_life() << std::endl;\n\n\tspl::cardinal::api_bsplvb(0.25, 3);\n\n\tconst int size = 10;\n\tspl::ker::spline<double, 2u> f(size, { 0., 1. }), g(size, { 0., 1. });\n\n\n\tfor (size_t i = 0; i < f.size(); i++)\n\t{\n\t\tf[i] = i + 1u;\n\t}\n\n\tauto h = f + g;\n\n\tstd::cerr << \"h(0.5) = \" << h(0.5) << std::endl;\n}\n", "meta": {"hexsha": "3be9e09650cb150dc828961abeb61ccedf14b40f", "size": 2183, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "spline_kernel_test/spline_kernel_test.cpp", "max_stars_repo_name": "Waterhaus/SplineMethodsLibrary", "max_stars_repo_head_hexsha": "a131950220cbdeb865e95a95ab8b6d053c436ecb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "spline_kernel_test/spline_kernel_test.cpp", "max_issues_repo_name": "Waterhaus/SplineMethodsLibrary", "max_issues_repo_head_hexsha": "a131950220cbdeb865e95a95ab8b6d053c436ecb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "spline_kernel_test/spline_kernel_test.cpp", "max_forks_repo_name": "Waterhaus/SplineMethodsLibrary", "max_forks_repo_head_hexsha": "a131950220cbdeb865e95a95ab8b6d053c436ecb", "max_forks_repo_licenses": ["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.4910714286, "max_line_length": 82, "alphanum_fraction": 0.595510765, "num_tokens": 714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4546112557218253}}
{"text": "#include \"ros/ros.h\"\n#include \"wave_filter.h\"\n#include \"asv_simulator.h\"\n\n\n// Standard libraries\n#include <cmath>\n#include <iostream>\n\n// Linear algebra math\n#include <Eigen/Dense>\n\n\n/// Make sure angle is between [-PI, PI)\ndouble normalize_angle(double val);\n\n\n/// Makes angle compatible with angle_ref such that the numerical diference is at most PI.\ndouble normalize_angle_diff(double angle, double angle_ref);\n\n\nVessel::Vessel()\n{\n  eta = Eigen::Vector3d::Zero();\n  nu  = Eigen::Vector3d::Zero();\n  tau_waves = Eigen::Vector3d::Zero();\n  tau = Eigen::Vector3d::Zero();\n}\n\nVessel::~Vessel() {}\n\nvoid Vessel::initialize(ros::NodeHandle nh)\n{\n  // Get all parameters from the parameter server\n  if (!nh.getParam(\"mass\", M))\n    M = 3980.0;\n  if (!nh.getParam(\"inertia\", I_z))\n    I_z = 19703.0;\n  if (!nh.getParam(\"dt\", DT))\n    DT = 0.05;\n\n  if (!nh.getParam(\"X_udot\", X_udot))\n    X_udot = 0.0;\n  if (!nh.getParam(\"Y_vdot\", Y_vdot))\n    Y_vdot = 0.0;\n  if (!nh.getParam(\"Y_rdot\", Y_rdot))\n    Y_rdot = 0.0;\n  if (!nh.getParam(\"N_vdot\", N_vdot))\n    N_vdot = 0.0;\n  if (!nh.getParam(\"N_rdot\", N_rdot))\n    N_rdot = 0.0;\n\n  if (!nh.getParam(\"X_u\", X_u))\n    X_u = -50.0;\n  if (!nh.getParam(\"Y_v\", Y_v))\n    Y_v = -200.0;\n  if (!nh.getParam(\"Y_r\", Y_r))\n    Y_r = 0.0;\n  if (!nh.getParam(\"N_v\", N_v))\n    N_v = 0.0;\n  if (!nh.getParam(\"N_r\", N_r))\n    N_r = -1281.0;\n\n  if (!nh.getParam(\"X_uu\", X_uu))\n    X_uu = -135.0;\n  if (!nh.getParam(\"Y_vv\", Y_vv))\n    Y_vv = -2000.0;\n  if (!nh.getParam(\"N_rr\", N_rr))\n    N_rr = 0.0;\n  if (!nh.getParam(\"X_uuu\", X_uuu))\n    X_uuu = 0.0;\n  if (!nh.getParam(\"Y_vvv\", Y_vvv))\n    Y_vvv = 0.0;\n  if (!nh.getParam(\"N_rrr\", N_rrr))\n    N_rrr = -3224.0;\n\n  Eigen::Matrix3d Mtot;\n  Mtot << M - X_udot, 0, 0,\n    0, M-Y_vdot, -Y_rdot,\n    0, -Y_rdot, I_z-N_rdot;\n  Minv = Mtot.inverse();\n\n  if (!nh.getParam(\"Fx_min\", Fx_min))\n    Fx_min = -6550.0;\n  if (!nh.getParam(\"Fx_max\", Fx_max))\n    Fx_max = 13100.0;\n  if (!nh.getParam(\"Fy_min\", Fy_min))\n    Fy_min = -650.0;\n  if (!nh.getParam(\"Fy_max\", Fy_max))\n    Fy_max = 650.0;\n\n  if (!nh.getParam(\"rudder_length\", rudder_length))\n      rudder_length = 4.0;\n\n  if (!nh.getParam(\"Kp_u\", Kp_u))\n    Kp_u = 0.1;\n  if (!nh.getParam(\"Kp_psi\", Kp_psi))\n    Kp_psi = 5.0;\n  if (!nh.getParam(\"Kd_psi\", Kd_psi))\n    Kd_psi = 1.0;\n  if (!nh.getParam(\"Kp_r\", Kp_r))\n    Kp_r = 8.0;\n\n  if (!nh.getParam(\"Fx_current\", Fx_current))\n    Fx_current = 0.0;\n  if (!nh.getParam(\"Fy_current\", Fy_current))\n    Fy_current = 0.0;\n\n  std::vector<double> initial_state;\n  if (nh.getParam(\"initial_state\", initial_state))\n    {\n      // Check if the vector supplied is the right size. Else default to zeros.\n      if (initial_state.size() == 6)\n        {\n          eta[0] = initial_state[0];\n          eta[1] = initial_state[1];\n          eta[2] = initial_state[2];\n          nu[0]  = initial_state[3];\n          nu[1]  = initial_state[4];\n          nu[2]  = initial_state[5];\n        }\n    }\n\n  // Initialize wave filters\n  double sigma, omega0, lambda, gain;\n  if (nh.getParam(\"sigma_x\", sigma) &&\n      nh.getParam(\"omega0_x\", omega0) &&\n      nh.getParam(\"lambda_x\", lambda) &&\n      nh.getParam(\"gain_x\", gain))\n    {\n      if (gain > 0.0)\n        {\n          wave_filter_x.initialize(sigma, omega0, lambda, gain, DT);\n          ROS_INFO(\"Enabled wave filter x!\");\n        }\n    }\n  if (nh.getParam(\"sigma_y\", sigma) &&\n      nh.getParam(\"omega0_y\", omega0) &&\n      nh.getParam(\"lambda_y\", lambda) &&\n      nh.getParam(\"gain_y\", gain))\n    {\n      if (gain > 0.0)\n        {\n          wave_filter_y.initialize(sigma, omega0, lambda, gain, DT);\n          ROS_INFO(\"Enabled wave filter y!\");\n        }\n    }\n  if (nh.getParam(\"sigma_psi\", sigma) &&\n      nh.getParam(\"omega0_psi\", omega0) &&\n      nh.getParam(\"lambda_psi\", lambda) &&\n      nh.getParam(\"gain_psi\", gain))\n    {\n      if (gain > 0.0)\n        {\n          wave_filter_psi.initialize(sigma, omega0, lambda, gain, DT);\n          ROS_INFO(\"Enabled wave filter psi!\");\n        }\n    }\n\n}\n\ndouble Vessel::getDT()\n{\n  return DT;\n}\n\nvoid Vessel::printPose()\n{\n  std::cout << eta << std::endl << std::endl;\n}\n\nvoid Vessel::setState(Eigen::Vector3d eta_new, Eigen::Vector3d nu_new)\n{\n  eta = eta_new;\n  nu = nu_new;\n}\n\nvoid Vessel::getState(Eigen::Vector3d &eta2, Eigen::Vector3d &nu2)\n{\n  eta2 = eta;\n  nu2 = nu;\n}\n\nvoid Vessel::getWaveNoise(Eigen::Vector3d &wave_noise)\n{\n  wave_noise = tau_waves;\n}\n\nvoid Vessel::updateSystem(double u_d, double psi_d, double r_d)\n{\n  // Ensure psi_d is \"compatible\" with psi\n  psi_d = normalize_angle_diff(psi_d, eta[2]);\n\n  Eigen::AngleAxisd rot_z = Eigen::AngleAxisd(eta[2], Eigen::Vector3d::UnitZ());\n\n  // Calculate coriolis and dampening matrices according to Fossen, 2011 or Stenersen, 2014.\n  Cvv[0] = (-M*nu[1] + Y_vdot*nu[1] + Y_rdot*nu[2]) * nu[2];\n  Cvv[1] = ( M*nu[0] - X_udot*nu[0]) * nu[2];\n  Cvv[2] = (( M*nu[1] - Y_vdot*nu[1] - Y_rdot*nu[2] ) * nu[0] +\n            ( -M*nu[0] + X_udot*nu[0] ) * nu[1]);\n\n  Dvv[0] = - (X_u + X_uu*fabs(nu[0]) + X_uuu*nu[0]*nu[0]) * nu[0];\n  Dvv[1] = - ((Y_v*nu[1] + Y_r*nu[2]) +\n              (Y_vv*fabs(nu[1])*nu[1] + Y_vvv*nu[1]*nu[1]*nu[1]));\n  Dvv[2] = - ((N_v*nu[1] + N_r*nu[2]) +\n              (N_rr*fabs(nu[2])*nu[2] + N_rrr*nu[2]*nu[2]*nu[2]));\n\n  this->updateControlInput(u_d, psi_d, r_d);\n\n  Eigen::Vector3d tau_const_disturbance(Fx_current, Fy_current, 0.0);\n  tau_const_disturbance = rot_z.inverse()*tau_const_disturbance;\n\n  tau_waves[0] = wave_filter_x.updateFilter();\n  tau_waves[1] = wave_filter_y.updateFilter();\n  tau_waves[2] = wave_filter_psi.updateFilter();\n\n  // Integrate system\n  eta += DT * (rot_z * nu);\n  nu  += DT * (Minv * (tau + tau_const_disturbance + tau_waves - Cvv - Dvv));\n\n  // Keep yaw within [-PI,PI)\n  eta[2] = normalize_angle(eta[2]);\n}\n\n\nvoid Vessel::updateControlInput(double u_d, double psi_d, double r_d)\n{\n  double Fx = Cvv[0] + Dvv[0] + Kp_u*M*(u_d - nu[0]);\n  double Fy = 0.0;\n\n  // If psi_d == inf, then use yaw-rate controller\n  if (isinf(psi_d))\n    {\n      Fy = Cvv[1] + Dvv[1] + I_z*Kp_r*(r_d - nu[2]);\n      Fy *= 1.0 / rudder_length;\n    }\n  else\n    {\n      Fy = (Kp_psi * I_z ) * ((psi_d - eta[2]) - Kd_psi*nu[2]);\n      Fy *= 1.0 / rudder_length;\n    }\n\n  // Saturate\n  if (Fx < Fx_min)\n    Fx = Fx_min;\n  if (Fx > Fx_max)\n    Fx = Fx_max;\n\n  if (Fy < Fy_min)\n    Fy = Fy_min;\n  if (Fy > Fy_max)\n    Fy = Fy_max;\n\n  tau[0] = Fx;\n  tau[1] = Fy;\n  tau[2] = rudder_length * Fy;\n}\n\ndouble normalize_angle(double val)\n{\n  if (isinf(val))\n    return val;\n\n  while (val <= -M_PI)\n    val += 2*M_PI;\n\n  while (val > M_PI)\n    val -= 2*M_PI;\n\n  return val;\n}\n\ndouble normalize_angle_diff(double angle, double angle_ref)\n{\n  double new_angle = 0;\n  double diff = angle_ref - angle;\n\n  if (isinf(angle) || isinf(angle_ref))\n    return angle;\n\n  // Get angle within 2PI of angle_ref\n  if (diff > 0)\n    {\n      new_angle = angle + (diff - fmod(diff, 2*M_PI));\n    }\n  else\n    {\n      new_angle = angle + (diff + fmod(-diff, 2*M_PI));\n    }\n\n  // Make sure angle is on the closest side of angle_ref\n  diff = angle_ref - new_angle;\n  if (diff > M_PI)\n    {\n      new_angle += 2*M_PI;\n    }\n  else if (diff < -M_PI)\n    {\n      new_angle -= 2*M_PI;\n    }\n  return new_angle;\n}\n", "meta": {"hexsha": "ed07b941feaa6c46a39436b8593cdd6cfa9fa25d", "size": 7218, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/asv_simulator.cpp", "max_stars_repo_name": "Lovestarni/asv_simulator", "max_stars_repo_head_hexsha": "824c832f071c51212367569a07f67e2dadfc1401", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2016-10-07T14:46:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-14T03:18:04.000Z", "max_issues_repo_path": "src/asv_simulator.cpp", "max_issues_repo_name": "Lovestarni/asv_simulator", "max_issues_repo_head_hexsha": "824c832f071c51212367569a07f67e2dadfc1401", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-03-18T10:16:04.000Z", "max_issues_repo_issues_event_max_datetime": "2015-03-23T12:00:00.000Z", "max_forks_repo_path": "src/asv_simulator.cpp", "max_forks_repo_name": "Lovestarni/asv_simulator", "max_forks_repo_head_hexsha": "824c832f071c51212367569a07f67e2dadfc1401", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-14T03:17:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-14T03:17:57.000Z", "avg_line_length": 23.8217821782, "max_line_length": 92, "alphanum_fraction": 0.5832640621, "num_tokens": 2564, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342624, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4546112503884369}}
{"text": "\n#include \"mandel_hp.h\"\n\n#include <cassert>\n#include <cstdlib>\n#include <iomanip>\n#include <cmath>\n#include <climits>\n#include <iostream>\n#include <fstream>\n\n#include <boost/thread.hpp>\n#include <boost/chrono.hpp>\n\n#include \"common.h\"\n#include \"updater.h\"\n\nusing namespace std::literals;\n\n// ----------------------------------------------------------------------------\n\nFltH copysign(const FltH& a,const FltH& b)\n{\n\tbool aneg = a<0;\n\tbool bneg = b<0;\n\tif (aneg==bneg)\n\t\treturn a;\n\telse\n\t\treturn -a;\n}\n\ntemplate<typename Flt>\nstd::complex<Flt> step(const std::complex<Flt>& c, const std::complex<Flt>& z)\n{\n\treturn z*z + c;\n}\n\ntemplate std::complex<FltH> step<FltH>(const std::complex<FltH>&, const std::complex<FltH>&);\ntemplate std::complex<FltL> step<FltL>(const std::complex<FltL>&, const std::complex<FltL>&);\n\n// ----------------------------------------------------------------------------\n\n// *************\n// *** Point ***\n// *************\n\ntemplate<typename Flt>\nbool Point<Flt>::docalc(const std::complex<Flt>& c, UL cap)\n{\n\n\t#ifndef NDEBUG\n\tif (c != orig)\n\t{\n\t\tauto dx = c.real() - orig.real();\n\t\tauto dy = c.imag() - orig.imag();\n\t\tusing std::sqrt;\n\t\tauto dst = sqrt(dx*dx + dy*dy);\n\t\tif (dst > (0.001 * stepsize))\n\t\t{\n\t\t\tstd::cerr << \"Error: c differs from orig\\n\";\n\t\t\tstd::cerr << \"    c = \" << c.real() << \"+\" << c.imag() << \"i\\n\";\n\t\t\tstd::cerr << \" orig = \" << orig.real() << \"+\" << orig.imag() << \"i\\n\";\n\t\t\tstd::cerr << \" diff = \" << dx << \"+\" << dy << \"i\\n\";\n\t\t\tthrow \"Error: c differs from orig\\n\";\n\t\t}\n\t}\n\t#endif\n\n\tUL& n = iter;\n\tif (n <= 1)\n\t{\n\t\t// first bulb\n\t\tdouble xld = (double)z.real();\n\t\tdouble yld = (double)z.imag();\n\t\tdouble y2 = yld * yld;\n\t\tdouble xldp1 = xld+1.0;\n\t\tif (((xldp1*xldp1) + y2) < 0.0625)\n\t\t{\n\t\t\tstatus = Point::in;\n\t\t\tpixtype = pt_black;\n\t\t\treturn true;\n\t\t}\n\t\t// main cardoid\n\t\tdouble xx = xld - 0.25;\n\t\txx *= xx;\n\t\txx += y2;\n\t\tdouble pp = sqrt(xx);\n\t\tif (xld < (pp - 2.0*(pp*pp) + 0.25))\n\t\t{\n\t\t\tstatus = Point::in;\n\t\t\tpixtype = pt_black;\n\t\t\treturn true;\n\t\t}\n\t}\n\n\tbool did_smth = false;\n\n\twhile (true)\n\t{\n\t\tif (n >= cap)\n\t\t{\n\t\t\tpixtype = pt_black;\n\t\t\tbreak;\n\t\t}\n\n\t\tauto zre = z.real();\n\t\tFlt  re_sq = zre * zre;\n\t\tauto zim = z.imag();\n\t\tFlt  im_sq = zim * zim;\n\t\tauto az2 = (double)re_sq + (double)im_sq;\n\t\tif (az2 > 4.0)\n\t\t{\n\t\t\tdid_smth = true;\n\t\t\tstatus = Point::out;\n\t\t\tover = sqrtf(az2);\n\t\t\tpixtype = pt_normal;\n\t\t\tbreak;\n\t\t}\n\n\t\tz.real(re_sq-im_sq);\n\t\tauto ab = zre * zim;\n\t\tz.imag(ab+ab);\n\t\tz += c;\n\t\t++n;\n\t}\n\n\treturn did_smth;\n}\n\ntemplate<typename Flt>\nvoid Point<Flt>::init(const std::complex<Flt>& c)\n{\n\tstatus = Point::calc;\n\titer = 1;\n\tz = c;\n\tpixtype = 0;\n\t#ifndef NDEBUG\n\torig = c;\n\t#endif\n}\n\ntemplate<typename Flt>\nvoid Point<Flt>::col(float mod)\n{\n\tconst Point& p = *this;\n\tif (p.status != Point::out)\n\t{\n\t\trgbval = {0,0,0};\n        return;\n\t}\n\tauto x = p.iter;\n\n\tstatic const float pi2 = 3.1415926536f * 2;\n\tstatic const float ilg2 = 1.0f / logf(2.0f);\n\tstatic const float c000 = 0.0f / 3.0f;\n\tstatic const float c333 = 1.0f / 3.0f;\n\tstatic const float c666 = 2.0f / 3.0f;\n\tfloat f = fmodf((float)x, mod) + 1.0f;\n\tf /= mod;\n\n\tf -= logf(logf(p.over) * ilg2) * ilg2 / mod;\n\tf *= pi2;\n\tfloat r = 0.5f + 0.5f*sinf(f + pi2 * c000);\n\tfloat g = 0.5f + 0.5f*sinf(f + pi2 * c333);\n\tfloat b = 0.5f + 0.5f*sinf(f + pi2 * c666);\n\tint ri = clamp(int(r*256), 0, 255);\n\tint gi = clamp(int(g*256), 0, 255);\n\tint bi = clamp(int(b*256), 0, 255);\n\trgbval = {(UC)ri, (UC)gi, (UC)bi};\n}\n\ntemplate struct Point<FltH>;\ntemplate struct Point<FltL>;\n\n// ----------------------------------------------------------------------------\n\n// ***********\n// *** Map ***\n// ***********\n\ntemplate<typename Flt>\nvoid Map<Flt>::colorize(float mod)\n{\n\tfor (UL y=0; y<new_h; ++y)\n\t{\n\t\tfor (UL x=0; x<new_w; ++x)\n\t\t{\n\t\t\tget(x,y).col(mod);\n\t\t}\n\t}\n}\n\ntemplate<typename Flt>\nPoint<Flt>& Map<Flt>::get(UL x, UL y)\n{\n\treturn points[y][x];\n}\n\ntemplate<typename Flt>\nFlt Map<Flt>::to_xpos(UL x) const\n{\n\tassert(x<new_w);\n\tFlt fact = x;\n\tfact /= (Flt)new_w;\n\tfact -= (Flt)0.5;\n\tfact *= scale_x;\n\tfact += center_x;\n\treturn fact;\n}\n\ntemplate<typename Flt>\nFlt Map<Flt>::to_ypos(UL y) const\n{\n\tassert(y<new_h);\n\tFlt fact = y;\n\tfact /= (Flt)new_h;\n\tfact -= (Flt)0.5;\n\tfact *= scale_y;\n\tfact += center_y;\n\treturn fact;\n}\n\ntemplate<typename Flt>\nvoid Map<Flt>::setZ(Flt z)\n{\n\tscale_x = z;\n\tscale_y = z * (Flt)height / (Flt)width;\n}\n\ntemplate<typename Flt>\nvoid Map<Flt>::generate_init()\n{\n\tUL x,y;\n\tvfx.clear();\n\tvfy.clear();\n\t\n\tnew_w = width; new_h = height;\n\n\tfor (y=0; y<height; ++y)\n\t\tvfy.push_back(to_ypos(y));\n\tfor (x=0; x<width; ++x)\n\t\tvfx.push_back(to_xpos(x));\n\n\tmap_all_done = false;\n\tpoints.resize(height);\n\n\tfor (y=0; y<height; ++y)\n\t{\n\t\tpoints[y].resize(width);\n\t\tconst Flt& yld = vfy[y];\n\t\tfor (x=0; x<width; ++x)\n\t\t{\n\t\t\tconst Flt& xld = vfx[x];\n\t\t\tget(x,y).init({xld, yld});\n\t\t}\n\t}\n}\n\ntemplate<typename Flt>\nauto Map<Flt>::generate(UL cap, bool display, bool extrap) -> Status\n{\n\tbool found_one = false;\n\tbool did_smth = false;\n\n\tUL x,y;\n\n\tfor (y=0; y<height; ++y)\n\t{\n\t\tif (display)\n\t\t{\n\t\t\tfloat f = 100.0f;\n\t\t\tf /= height;\n\t\t\tf *= y;\n\t\t\tstd::cout << (int)f << \"%\\r\" << std::flush;\n\t\t}\n\t\tconst Flt& yld = vfy[y];\n\t\tfor (x=0; x<width; ++x)\n\t\t{\n\t\t\tPoint<Flt>& p = get(x,y);\n\t\t\tif (p.status != Point<Flt>::calc)\n\t\t\t\tcontinue;\n\t\t\tfound_one = true;\n\t\t\tif (extrap)\n\t\t\t{\n\t\t\t\tUL w = width-1, h = height-1;\n\t\t\t\tif (x && x<w)\n\t\t\t\t{\n\t\t\t\t\tauto& pp = get(x-1,y);\n\t\t\t\t\tauto& pn = get(x+1,y);\n\t\t\t\t\tif ( (pp.status == Point<Flt>::out) &&\n\t\t\t\t\t     (pn.status == Point<Flt>::out) &&\n\t\t\t\t\t     (pp.iter == pn.iter) )\n\t\t\t\t\t{\n\t\t\t\t\t\tp.status = Point<Flt>::out;\n\t\t\t\t\t\tp.iter = pp.iter;\n\t\t\t\t\t\tp.over = (float)(pp.over + pn.over)/2.0f;\n\t\t\t\t\t\tdid_smth = true;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (y && y<h)\n\t\t\t\t{\n\t\t\t\t\tPoint<Flt>& pp = get(x,y-1);\n\t\t\t\t\tPoint<Flt>& pn = get(x,y+1);\n\t\t\t\t\tif ( (pp.status == Point<Flt>::out) &&\n\t\t\t\t\t     (pn.status == Point<Flt>::out) &&\n\t\t\t\t\t     (pp.iter == pn.iter) )\n\t\t\t\t\t{\n\t\t\t\t\t\tp.status = Point<Flt>::out;\n\t\t\t\t\t\tp.iter = pp.iter;\n\t\t\t\t\t\tp.over = (pp.over + pn.over)/2.0;\n\t\t\t\t\t\tdid_smth = true;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tstd::complex<Flt> c{vfx[x], yld};\n\t\t\tdid_smth = p.docalc(c, p.iter+cap) || did_smth;\n\t\t}\n\t}\n\tif (!found_one)\n\t\treturn all_done;\n\telse\n\t\treturn did_smth ? was_updated : no_change;\n}\n\ntemplate<typename Flt>\nImage Map<Flt>::makeimage(float mod, UL upc)\n{\n\tImage img(width, height);\n\tUL x,y;\n\tfor (y=0; y<height; ++y)\n\t{\n\t\tfor (x=0; x<width; ++x)\n\t\t{\n\t\t\tauto& p = get(x,y);\n\t\t\tif (p.status == Point<Flt>::out)\n\t\t\t{\n\t\t\t\tp.col(mod);\n\t\t\t\timg.PutPixel(x,y,p.rgbval);\n\t\t\t} else {\n\t\t\t\tbool clc = p.status==Point<Flt>::calc;\n\t\t\t\tbool ilu = upc && (p.iter<upc);\n\t\t\t\tif (clc && ilu)\n\t\t\t\t\timg.PutPixel(x,y,{255,255,255});\n\t\t\t\telse\n\t\t\t\t\timg.PutPixel(x,y,{0,0,0});\n\t\t\t}\n\t\t}\n\t}\n\treturn img;\n}\n\ntemplate<typename Flt>\nRGB Map<Flt>::extrapolate(float x, float y)\n{\n\tusing namespace std;\n\tif (x<0.0f) x=0.0f; if (x>new_w) x=new_w;\n\tif (y<0.0f) y=0.0f; if (y>new_h) y=new_h;\n\tfloat xr = roundf(x);\n\tfloat yr = roundf(y);\n\tfloat dx = x-xr;\n\tfloat dy = y-yr;\n\tUL x1,x2,y1,y2;\n\tdouble fx, fy;\n\tif (fabs(dx) < 0.05f) {\n\t\tx1 = x2 = roundl(x);\n\t\tfx = 0.5f;\n\t} else {\n\t\tx1 = floorl(x);\n\t\tx2 = ceill(x);\n\t\tfx = x2-x;\n\t}\n\tif (fabs(dy) < 0.05f) {\n\t\ty1 = y2 = roundl(y);\n\t\tfy = 0.5f;\n\t} else {\n\t\ty1 = floorl(y);\n\t\ty2 = ceill(y);\n\t\tfy = y2-y;\n\t}\n\tRGB pix_11 = get(x1 , y1).rgbval;\n\tRGB pix_12 = get(x1 , y2).rgbval;\n\tRGB pix_21 = get(x2 , y1).rgbval;\n\tRGB pix_22 = get(x2 , y2).rgbval;\n\tRGB pix_1 = mix(pix_11, pix_12, fy);\n\tRGB pix_2 = mix(pix_21, pix_22, fy);\n\tRGB pix   = mix(pix_1,  pix_2,  fx);\n\treturn pix;\n}\n\ntemplate<typename Flt>\nvoid Map<Flt>::generate_init_rest()\n{\n\tpoints.resize(new_h);\n\tUL x,y;\n\tfor (y=0; y<new_h; ++y)\n\t\tpoints[y].resize(new_w+3);\n\n\tFlt x_start = to_xpos(0);\n\tFlt x_stop  = to_xpos(new_w-1);\n\tFlt y_start = to_ypos(0);\n\tFlt y_stop  = to_ypos(new_h-1);\n\tFlt x_step  = (x_stop-x_start) / (new_w-1);\n\tFlt y_step  = (y_stop-y_start) / (new_h-1);\n\n\tvfx.resize(new_w); vfy.resize(new_h);\n\tfor (x=0; x<new_w; ++x)\n\t\tvfx[x] = (x_start + x_step*x);\n\tfor (y=0; y<new_h; ++y)\n\t\tvfy[y] = (y_start + y_step*y);\n}\n\nFltH pow(FltH m, int e)\n{\n\tif (e==0) return FltH{1.0};\n\tif (e==1) return m;\n\tif (e<0)  return FltH{1.0} / pow(m, -e);\n\tFltH ret;\n\tmpf_pow_ui(ret.get_mpf_t(), m.get_mpf_t(), (UL)e);\n\treturn ret;\n}\n\ntemplate<typename Flt>\nvoid Map<Flt>::generate_N_init(int n, bool disp)\n{\n\tusing std::pow;\n\t\n\tFlt tm = pow(zoom_mul, -n);\n\n\tnew_w = ceill(width  * (double)tm);\n\tnew_h = ceill(height * (double)tm);\n\n\tif (disp)\n\t{\n\t\tstd::cout << \"Old size \" << width << \"x\" << height << std::endl;\n\t\tstd::cout << \"New size \" << new_w << \"x\" << new_h << std::endl;\n\t}\n\n\tgenerate_init_rest();\n}\n\ntemplate<typename Flt>\nUL Map<Flt>::generate_N_threaded(int n, UL cap, bool display)\n{\n\tgenerate_N_init(n, display);\n\n\tUpdater::Init(new_h*3+4);\n\tif (display) Updater::Display();\n\n\tLineCache<Flt> lc[4] = {\n\t\t{ cap, display, *this },\n\t\t{ cap,   false, *this },\n\t\t{ cap,   false, *this },\n\t\t{ cap,   false, *this },\n\t};\n\n\tUL i = 0;\n\tUL num = new_h / 4;\n\tUL ovr = new_h - (num*4);\n\tUL y = 0;\n\tlc[0].y_start = y; y += (lc[0].y_count = num + ovr);\n\tlc[1].y_start = y; y += (lc[1].y_count = num);\n\tlc[2].y_start = y; y += (lc[2].y_count = num);\n\tlc[3].y_start = y; y += (lc[3].y_count = num);\n\n\tUL maxout = 0;\n\tboost::thread tt[4];\n\tfor (i=1; i<4; ++i)\n\t{\n\t\ttt[i] = boost::thread{&LineCache<Flt>::execute, lc+i};\n\t}\n\tLineCache<Flt>::execute(lc);\n\tboost::chrono::nanoseconds ns{250'000};\n\tint joined = 1;\n\twhile (true)\n\t{\n\t\tif (display) Updater::Display();\n\n\t\tbool j = tt[joined].try_join_for(ns);\n\t\tif (j)\n\t\t{\n\t\t\t++joined;\n\t\t\tUpdater::Tick();\n\t\t\tif (joined >= 4) break;\n\t\t}\n\t}\n\tUL sk = 0, is = 0;\n\tfor (i=0; i<4; ++i)\n\t{\n\t\tif (lc[i].eff_cap > maxout)\n\t\t\tmaxout = lc[i].eff_cap;\n\t\tsk += lc[i].skip_count;\n\t\tis += lc[i].inskip;\n\t}\n\n\tUpdater::Tick();\n\tif (display) Updater::Display();\n\n\tif (display)\n\t\tstd::cout << \"skipped        : \" << sk << \" pixels, of wich \" << is << \" was inside \\n\";\n\n\treturn maxout;\n}\n\ntemplate<typename Flt>\nImage Map<Flt>::makeimage_N(int n, ModFunc mf, OSP fr)\n{\n\tusing std::pow;\n\n\tImage img(width, height);\n\n\tFlt tpmn = pow(zoom_mul, -n);\n\n\tfloat myw = new_w / (double)tpmn;\n\tfloat myh = new_h / (double)tpmn;\n\t\n\tfloat xstart = (new_w-myw) / 2;\n\tfloat ystart = (new_h-myh) / 2;\n\n\tfloat xstep = myw / width;\n\tfloat ystep = myh / height;\n\n\tFlt quot = scale_x / tpmn;\n\tfloat mod = mf((double)quot);\n\n\tif (fr) DiffReport((double)quot, mod);\n\n\tif (fr)\n\t{\n\t\t(*fr) << std::setprecision(20) << std::setw(25) << std::scientific << quot << \" \";\n\t\t(*fr) << std::setprecision(10) << std::setw(15) << std::fixed << mod << \" \";\n\t\t(*fr) << myw << \"x\" << myh << \" \";\n\t\t(*fr) << xstart << \"+\" << xstep << \" \";\n\t\t(*fr) << ystart << \"+\" << ystep << \" \";\n\t}\n\n\tcolorize(mod);\n\n\tUL x,y;\n\tfor (y=0; y<height; ++y)\n\t{\n\t\tfloat yf = ystart + y * ystep;\n\t\tfor (x=0; x<width; ++x)\n\t\t{\n\t\t\tdouble xf = xstart + x * xstep;\n\t\t\timg.PutPixel(x, y, extrapolate(xf, yf));\n\t\t}\n\t}\n\n\treturn img;\n}\n\nvoid adjust_factor(FltL&, int) {}\n\nint adjustments = 0;\nint epsilondbl = 0;\n\nvoid adjust_factor(FltH& f, int n)\n{\n\tFltH epsilon = 0.001;\n\tFltH target = pow(f, n);\n\tFltH diff = abs(0.5f - target);\n\n\twhile (true)\n\t{\n\t\twhile (true)\n\t\t{\n\t\t\tFltH up = f + epsilon;\n\t\t\tif (up == f) return;\n\t\t\tFltH new_target = pow(up, n);\n\t\t\tFltH new_diff = abs(0.5f - new_target);\n\t\t\tif (new_diff<diff)\n\t\t\t{\n\t\t\t\t++adjustments;\n\t\t\t\tf = up;\n\t\t\t\ttarget = new_target;\n\t\t\t\tdiff = new_diff;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\twhile (true)\n\t\t{\n\t\t\tFltH dn = f - epsilon;\n\t\t\tif (dn == f) return;\n\t\t\tFltH new_target = pow(dn, n);\n\t\t\tFltH new_diff = abs(0.5f - new_target);\n\t\t\tif (new_diff<diff)\n\t\t\t{\n\t\t\t\t++adjustments;\n\t\t\t\tf = dn;\n\t\t\t\ttarget = new_target;\n\t\t\t\tdiff = new_diff;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tepsilon /= 2;\n\t\t++epsilondbl;\n\t}\n}\n\ntemplate<typename Flt>\nvoid Map<Flt>::setup_dbl(Flt target, MultiLogger& logger)\n{\n\tusing std::pow;\n\tdouble n = std::log(0.5) / std::log((double)target);\n\tcount_dlb = std::roundl(n);\n\tFlt factor = std::pow(0.5, 1.0/n);\n\n\tlogger << std::setprecision(100) << std::fixed;\n\tlogger << \"new factor     : \" << factor << std::endl;\n\tadjust_factor(factor, count_dlb);\n\tlogger << \"adj. factor    : \" << factor << std::endl;\n\tlogger << \"new count      : \" << count_dlb << std::endl;\n\tFltH new_target = pow(factor, count_dlb);\n\tlogger << \"new doubling   : \" << new_target << std::endl;\n\n\tlogger << \"adj / dbl      : \" << adjustments << \" / \" << epsilondbl << std::endl;\n\n\tzoom_mul = factor;\n\twidth  = (width  >> 2) << 2;\n\theight = (height >> 2) << 2;\n\tnew_w = width  * 2;\n\tnew_h = height * 2;\n\tlogger << \"adjusted size  : \" << width << \"x\" << height << std::endl;\n\tlogger << \"new size       : \" << new_w << \"x\" << new_h << std::endl;\n\n\tgenerate_init_rest();\n\n\tfor (UL y=0; y<new_h; ++y)\n\t{\n\t\tconst Flt& yld = vfy[y];\n\t\tfor (UL x=0; x<new_w; ++x)\n\t\t{\n\t\t\tconst Flt& xld = vfx[x];\n\t\t\tget(x,y).init({xld, yld});\n\t\t}\n\t}\n\n}\n\ntemplate<typename Flt>\nImage Map<Flt>::dbl_makefull(UL cap)\n{\n\tstd::vector<Scanline<Flt>> saved;\n\tsaved.swap(points);\n\n\tgenerate_init_rest();\n\n\tfor (UL y=0; y<new_h; ++y)\n\t{\n\t\tconst Flt& yld = vfy[y];\n\t\tfor (UL x=0; x<new_w; ++x)\n\t\t{\n\t\t\tconst Flt& xld = vfx[x];\n\t\t\tget(x,y).init({xld, yld});\n\t\t\tget(x,y).docalc({xld, yld}, cap);\n\t\t}\n\t}\n\n\tusing std::swap;\n\tswap(width, new_w); swap(height, new_h);\n\tauto img = makeimage(350,INT_MAX);\n\tswap(width, new_w); swap(height, new_h);\n\n\tsaved.swap(points);\n\n\treturn img;\n}\n\ntemplate<typename Flt>\nint Map<Flt>::generate_dbl(UL cap, bool first, bool display, MultiLogger& logger)\n{\n\n\t#ifndef NDEBUG\n\n\tUpdater::Init(new_h*3+1);\n\tif (display) Updater::Display();\n\n\tLineCache<Flt> lc = { cap, true, *this, first };\n\tlc.y_start = 0;\n\tlc.y_count = new_h;\n\n\tLineCache<Flt>::execute_dbl(&lc);\n\n\tUL sk = lc.skip_count;\n\tUL is = lc.inskip;\n\tUL maxout = lc.eff_cap;\n\n\t#else\n\n\tif (first)\n\t\tUpdater::Init(new_h*3+4);\n\telse\n\t\tUpdater::Init(new_h*2+4);\n\tif (display) Updater::Display();\n\n\tLineCache<Flt> lc[4] = {\n\t\t{ cap,  display, *this, first },\n\t\t{ cap,   false, *this, first },\n\t\t{ cap,   false, *this, first },\n\t\t{ cap,   false, *this, first },\n\t};\n\n\tUL i = 0;\n\tUL num = new_h / 4;\n\tUL ovr = new_h - (num*4);\n\tUL y = 0;\n\tlc[0].y_start = y; y += (lc[0].y_count = num + ovr);\n\tlc[1].y_start = y; y += (lc[1].y_count = num);\n\tlc[2].y_start = y; y += (lc[2].y_count = num);\n\tlc[3].y_start = y; y += (lc[3].y_count = num);\n\n\tUL maxout = 0;\n\tboost::thread tt[4];\n\tfor (i=1; i<4; ++i)\n\t{\n\t\ttt[i] = boost::thread{&LineCache<Flt>::execute_dbl, lc+i};\n\t}\n\n\tLineCache<Flt>::execute_dbl(lc);\n\n\tboost::chrono::nanoseconds ns{250'000};\n\tint joined = 1;\n\twhile (true)\n\t{\n\t\tif (display) Updater::Display();\n\n\t\tbool j = tt[joined].try_join_for(ns);\n\t\tif (j)\n\t\t{\n\t\t\t++joined;\n\t\t\tUpdater::Tick();\n\t\t\tif (joined >= 4) break;\n\t\t}\n\t}\n\n\tUL sk = 0, is = 0;\n\tfor (i=0; i<4; ++i)\n\t{\n\t\tif (lc[i].eff_cap > maxout)\n\t\t\tmaxout = lc[i].eff_cap;\n\t\tsk += lc[i].skip_count;\n\t\tis += lc[i].inskip;\n\t}\n\n\t#endif\n\n\tUpdater::Tick();\n\tif (display) Updater::Display();\n\n\tlogger << \"skipped        : \" << sk << \" pixels, of wich \" << is << \" was inside \\n\";\n\tlogger << \"effective cap  : \" << maxout << \"\\n\";\n\n\treturn count_dlb;\n}\n\ntemplate<typename Flt>\nint Map<Flt>::sh_new_xcoord(int oldx)\n{\n\tint hw = new_w/2;\n\tint dfc = hw - oldx;\n\treturn hw - 2*dfc;\n}\n\ntemplate<typename Flt>\nint Map<Flt>::sh_new_ycoord(int oldy)\n{\n\tint hh = new_h/2;\n\tint dfc = hh - oldy;\n\treturn hh - 2*dfc;\n}\n\ntemplate<typename Flt>\nvoid Map<Flt>::new_out(std::string fn)\n{\n\tusing std::swap;\n\tswap(width, new_w); swap(height, new_h);\n\tmakeimage(350,INT_MAX).Save(fn);\n\tswap(width, new_w); swap(height, new_h);\n}\n\ntemplate<typename Flt>\nint Map<Flt>::shuffle_dbl()\n{\n\tgenerate_init_rest();\n\n\tauto copy = points;\n\tfor (UL y=0; y<new_h; ++y)\n\t{\n\t\tconst Flt& yld = vfy[y];\n\t\tfor (UL x=0; x<new_w; ++x)\n\t\t{\n\t\t\tconst Flt& xld = vfx[x];\n\t\t\tget(x,y).init({xld, yld});\n\t\t}\n\t}\n\n\tint cpy = 0;\n\tfor (int y=0; y<(int)new_h; ++y)\n\t{\n\t\tauto newy = sh_new_ycoord(y);\n\t\tif ((newy<0) || (newy>=(int)new_h)) continue;\n\t\tfor (int x=0; x<(int)new_w; ++x)\n\t\t{\n\t\t\tauto newx = sh_new_xcoord(x);\n\t\t\tif ((newy==y) && (newx==x)) continue;\n\t\t\tif ((newx<0) || (newx>=(int)new_w)) continue;\n\t\t\tconst Point<Flt>& src = copy[y][x];\n\t\t\tPoint<Flt>& dst = get(newx,newy);\n\t\t\tdst = src;\n\t\t\t++cpy;\n\t\t}\n\t}\n\n\treturn cpy;\n}\n\ntemplate struct Map<FltH>;\ntemplate struct Map<FltL>;\n\n// ----------------------------------------------------------------------------\n\n// *****************\n// *** LineCache ***\n// *****************\n\ntemplate<typename Flt>\nLineCache<Flt>::LineCache(UL cap, bool display, Map<Flt>& map, bool first)\n\t: cap(cap)\n\t, display(display)\n\t, first(first)\n\t, map(map)\n\t, vfx(map.vfx)\n\t, vfy(map.vfy)\n{}\n\ntemplate<typename Flt>\nvoid LineCache<Flt>::base_init()\n{\n\teff_cap = 1;\n\tskip_count = 0;\n\tinskip = 0;\n\tn = y_count;\n\tw = map.new_w;\n}\n\ntemplate<typename Flt>\nvoid LineCache<Flt>::init_zero()\n{\n\tfor (UL i=0; i<n; ++i)\n\t{\n\t\tUL y = y_start + i;\n\t\tFlt& yld = vfy[y];\n\t\tfor (UL x=0; x<w; ++x)\n\t\t{\n\t\t\tauto& p = map.get(x,y);\n\t\t\tstd::complex<Flt> c{vfx[x], yld};\n\t\t\tp.init(c);\n\t\t}\n\t}\n}\n\ntemplate<typename Flt>\nvoid LineCache<Flt>::init_lim()\n{\n\txlo = 0;\n\txhi = map.new_w-1;\n\tylo = y_start;\n\tyhi = y_start+n-1;\n}\n\ntemplate<typename Flt>\nvoid LineCache<Flt>::dc(Point<Flt>& p, const std::complex<Flt>& c)\n{\n\tbool did = p.docalc(c, cap);\n\tif (did && p.iter>eff_cap)\n\t\teff_cap = p.iter;\n}\n\ntemplate<typename Flt>\nvoid LineCache<Flt>::even()\n{\n\tfor (UL i=0; i<n; ++i)\n\t{\n\t\tUpdater::Tick();\n\t\tif (display)\n\t\t\tUpdater::Display();\n\t\tif (i%2) continue;\n\t\tUL y = y_start + i;\n\t\tFlt& yld = vfy[y];\n\t\tfor (UL x=0; x<w; x+=2)\n\t\t{\n\t\t\tauto& p = map.get(x,y);\n\t\t\tstd::complex<Flt> c{vfx[x], yld};\n\t\t\tdc(p,c);\n\t\t}\n\t}\n}\n\ntemplate<typename Flt>\nvoid LineCache<Flt>::odd()\n{\n\tfor (UL i=0; i<n; ++i)\n\t{\n\t\tUpdater::Tick();\n\t\tif (display)\n\t\t\tUpdater::Display();\n\t\tif (!(i%2)) continue;\n\t\tUL y = y_start + i;\n\t\tFlt& yld = vfy[y];\n\t\tfor (UL x=1; x<w; x+=2)\n\t\t{\n\t\t\tauto& p = map.get(x,y);\n\t\t\tif (p.status != Point<Flt>::calc) continue;\n\t\t\tif (p.iter != 1) continue;\n\t\t\tstd::complex<Flt> c{vfx[x], yld};\n\t\t\tdc(p,c);\n\t\t}\n\t}\n}\n\ntemplate<typename Flt>\nbool LineCache<Flt>::ep_xy(UL x, UL y)\n{\n\tauto& p = map.get(x,y);\n\tif (p.status != Point<Flt>::calc) return false;\n\tif (p.iter != 1) return false;\n\tif (x==xlo) return false;\n\tif (x==xhi) return false;\n\tif (y==ylo) return false;\n\tif (y==yhi) return false;\n\tif (map.get(x-1,y).status != Point<Flt>::in) return false;\n\tif (map.get(x+1,y).status != Point<Flt>::in) return false;\n\tif (map.get(x,y-1).status != Point<Flt>::in) return false;\n\tif (map.get(x,y+1).status != Point<Flt>::in) return false;\n\tp.status = Point<Flt>::in;\n\tp.pixtype = pt_black;\n\t++skip_count;\n\t++inskip;\n\treturn true;\n}\n\ntemplate<typename Flt>\nbool LineCache<Flt>::ep_x(UL x, UL y)\n{\n\tauto& p = map.get(x,y);\n\tif (p.status != Point<Flt>::calc) return false;\n\tif (p.iter != 1) return false;\n\tif (x==xlo) return false;\n\tif (x==xhi) return false;\n\tauto& pp = map.get(x-1,y);\n\tif (pp.status != Point<Flt>::out) return false;\n\tbool pe = pp.pixtype & pt_ep_msk;\n\tauto& pn = map.get(x+1,y);\n\tif (pn.status != Point<Flt>::out) return false;\n\tif (pp.iter != pn.iter) return false;\n\tbool ne = pn.pixtype & pt_ep_msk;\n\tif (pe && ne) return false;\n\tp.status = Point<Flt>::out;\n\tp.iter = pp.iter;\n\tp.over = (pp.over + pn.over)/2.0;\n\tp.pixtype = pt_ep_hor;\n\t++skip_count;\n\treturn true;\n}\n\ntemplate<typename Flt>\nbool LineCache<Flt>::ep_y(UL x, UL y)\n{\n\tauto& p = map.get(x,y);\n\tif (p.status != Point<Flt>::calc) return false;\n\tif (p.iter != 1) return false;\n\tif (y==ylo) return false;\n\tif (y==yhi) return false;\n\tauto& pp = map.get(x,y-1);\n\tif (pp.status != Point<Flt>::out) return false;\n\tbool pe = pp.pixtype & pt_ep_msk;\n\tauto& pn = map.get(x,y+1);\n\tif (pn.status != Point<Flt>::out) return false;\n\tif (pp.iter != pn.iter) return false;\n\tbool ne = pn.pixtype & pt_ep_msk;\n\tif (pe && ne) return false;\n\tp.status = Point<Flt>::out;\n\tp.iter = pp.iter;\n\tp.over = (float)(pp.over + pn.over)/2.0f;\n\tp.pixtype = pt_ep_ver;\n\t++skip_count;\n\treturn true;\n}\n\ntemplate<typename Flt>\nbool LineCache<Flt>::setin()\n{\n\tbool foundin = false;\n\n\tfor (UL i=0; i<n; ++i)\n\t{\n\t\tUL y = y_start + i;\n\t\tfor (UL x=0; x<w; ++x)\n\t\t{\n\t\t\tauto& p = map.get(x,y);\n\t\t\tif (p.status ==Point<Flt>::in) foundin = true;\n\t\t\tif (p.status != Point<Flt>::calc) continue;\n\t\t\tif (p.iter < cap) continue;\n\t\t\tp.status = Point<Flt>::in;\n\t\t\tfoundin = true;\n\t\t}\n\t}\n\treturn foundin;\n}\n\ntemplate<typename Flt>\nvoid LineCache<Flt>::all()\n{\n\tfor (UL i=0; i<n; ++i)\n\t{\n\t\tUpdater::Tick();\n\t\tif (display)\n\t\t\tUpdater::Display();\n\n\t\tUL y = y_start + i;\n\t\tfor (UL x=0; x<w; ++x)\n\t\t{\n\t\t\tauto& p = map.get(x,y);\n\t\t\tif (p.status != Point<Flt>::calc) continue;\n\t\t\tif (p.iter != 1) continue;\n\t\t\tstd::complex<Flt> c{vfx[x], vfy[y]};\n\t\t\tdc(p,c);\n\t\t}\n\t}\n}\n\ntemplate<typename Flt>\nvoid LineCache<Flt>::execute(LineCache* lc)\n{\n\tlc->base_init();\n\tlc->init_zero();\n\tlc->even();\n\tlc->init_lim();\n\n\tauto all_f = [&](auto f) -> void\n\t{\n\t\tfor (UL i=0; i<lc->n; i+=1)\n\t\t{\n\t\t\tUL y = lc->y_start + i;\n\t\t\tfor (UL x=0; x<lc->w; x+=1)\n\t\t\t\tf(x,y);\n\t\t}\n\t};\n\n\tall_f( [&](UL x, UL y) { lc->ep_x(x,y); } );\n\tall_f( [&](UL x, UL y) { lc->ep_y(x,y); } );\n\n\tlc->odd();\n\n\tbool foundin = lc->setin();\n\n\tif (foundin)\n\t\tall_f( [&](UL x, UL y) { lc->ep_xy(x,y); } );\n\n\tlc->all();\n}\n\ntemplate<typename Flt>\nvoid LineCache<Flt>::execute_dbl(LineCache* lc)\n{\n\tlc->base_init();\n\n\t#ifndef NDEBUG\n\t#define IDBO(fn) lc->map.new_out(fn)\n\t#else\n\t#define IDBO(fn) (void)fn\n\t#endif\n\n\tIDBO(\"ED_0_After_BI.bmp\");\n\t\n\tif (lc->first)\n\t{\n\t\tlc->even();\n\t\tIDBO(\"ED_1_RanEvenFrst.bmp\");\n\t}\n\n\tlc->init_lim();\n\n\tauto all_f = [&](auto f) -> void\n\t{\n\t\tfor (UL i=0; i<lc->n; i+=1)\n\t\t{\n\t\t\tUL y = lc->y_start + i;\n\t\t\tfor (UL x=0; x<lc->w; x+=1)\n\t\t\t\tf(x,y);\n\t\t}\n\t};\n\n\tall_f( [&](UL x, UL y) { lc->ep_x(x,y); } );\n\tall_f( [&](UL x, UL y) { lc->ep_y(x,y); } );\n\n\tIDBO(\"ED_2_Extrapolate_X_and_Y.bmp\");\n\n\tlc->odd();\n\tIDBO(\"ED_3_After_Odd.bmp\");\n\n\tbool foundin = lc->setin();\n\n\tif (foundin)\n\t{\n\t\tIDBO(\"ED_4_After_Setin.bmp\");\n\t\tall_f( [&](UL x, UL y) { lc->ep_xy(x,y); } );\n\t\tIDBO(\"ED_5_Extrapolate_XY.bmp\");\n\t}\n\n\tlc->all();\n\tIDBO(\"ED_6_After_All.bmp\");\n\n\t#undef IDBO\n}\n\ntemplate struct LineCache<FltH>;\ntemplate struct LineCache<FltL>;\n\n\n// ----------------------------------------------------------------------------\n\n// ******************\n// *** DiffReport ***\n// ******************\n\nnamespace {\n\tbool first = true;\n\tint current;\n\tstd::ofstream diffr;\n\tdouble prv_zf;\n\tfloat  prv_mod;\n}\n\nvoid DiffReport(int fr)\n{\n\tif (first)\n\t{\n\t\tdiffr.open(\"DiffReport.txt\");\n\t} else {\n\t\tassert(fr == (current+1));\n\t}\n\tcurrent = fr;\n}\n\nvoid DiffReport(double zf, float mod)\n{\n\tif (!first)\n\t{\n\t\tdiffr << std::setw(6) << current << \" \";\n\t\tdiffr << std::setprecision(30) << std::setw(35);\n\t\tdiffr << std::fixed << (zf / prv_zf) << \" \";\n\t\tdiffr << std::setprecision(10) << std::setw(15);\n\t\tdiffr << std::fixed << (mod / prv_mod) << std::endl << std::flush;\n\t}\n\tfirst = false;\n\tprv_zf  = zf;\n\tprv_mod = mod;\n}\n\n\n\n", "meta": {"hexsha": "0d562d35a0f179890f4644b54360861b1b0d266e", "size": 22822, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mandel_hp.cpp", "max_stars_repo_name": "sp2danny/Fact", "max_stars_repo_head_hexsha": "aa25f3c7568834ae5a7d2aa93f2a265d99f02b80", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/mandel_hp.cpp", "max_issues_repo_name": "sp2danny/Fact", "max_issues_repo_head_hexsha": "aa25f3c7568834ae5a7d2aa93f2a265d99f02b80", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mandel_hp.cpp", "max_forks_repo_name": "sp2danny/Fact", "max_forks_repo_head_hexsha": "aa25f3c7568834ae5a7d2aa93f2a265d99f02b80", "max_forks_repo_licenses": ["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.5561268209, "max_line_length": 93, "alphanum_fraction": 0.5588467268, "num_tokens": 8444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342624, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4546112503884369}}
{"text": "/*\n * Copyright (C) 2016-2019 Istituto Italiano di Tecnologia (IIT)\n *\n * This software may be modified and distributed under the terms of the\n * BSD 3-Clause license. See the accompanying LICENSE file for details.\n */\n\n#include <BayesFilters/GPFCorrection.h>\n#include <BayesFilters/utils.h>\n\n#include <Eigen/Cholesky>\n\n#include <exception>\n\nusing namespace bfl;\nusing namespace Eigen;\n\n\nGPFCorrection::GPFCorrection\n(\n    std::unique_ptr<LikelihoodModel> likelihood_model,\n    std::unique_ptr<GaussianCorrection> gaussian_correction,\n    std::unique_ptr<StateModel> state_model\n) noexcept :\n    GPFCorrection(std::move(likelihood_model), std::move(gaussian_correction), std::move(state_model), 1)\n{ }\n\n\nGPFCorrection::GPFCorrection\n(\n    std::unique_ptr<LikelihoodModel> likelihood_model,\n    std::unique_ptr<GaussianCorrection> gaussian_correction,\n    std::unique_ptr<StateModel> state_model,\n    unsigned int seed\n) noexcept :\n    likelihood_model_(std::move(likelihood_model)),\n    gaussian_correction_(std::move(gaussian_correction)),\n    state_model_(std::move(state_model)),\n    generator_(std::mt19937_64(seed)),\n    distribution_(std::normal_distribution<double>(0.0, 1.0)),\n    gaussian_random_sample_([&] { return (distribution_)(generator_); })\n{ }\n\n\nGPFCorrection::GPFCorrection(GPFCorrection&& correction) noexcept :\n    PFCorrection(std::move(correction)),\n    likelihood_model_(std::move(correction.likelihood_model_)),\n    gaussian_correction_(std::move(correction.gaussian_correction_)),\n    state_model_(std::move(correction.state_model_)),\n    generator_(std::move(correction.generator_)),\n    distribution_(std::move(correction.distribution_)),\n    gaussian_random_sample_(std::move(correction.gaussian_random_sample_)),\n    valid_likelihood_(correction.valid_likelihood_),\n    likelihood_(std::move(correction.likelihood_))\n{ }\n\n\nGPFCorrection& GPFCorrection::operator=(GPFCorrection&& correction) noexcept\n{\n    PFCorrection::operator=(std::move(correction));\n\n    gaussian_correction_ = std::move(correction.gaussian_correction_);\n\n    state_model_ = std::move(correction.state_model_);\n\n    generator_ = std::move(correction.generator_);\n\n    distribution_ = std::move(correction.distribution_);\n\n    gaussian_random_sample_ = std::move(correction.gaussian_random_sample_);\n\n    valid_likelihood_ = correction.valid_likelihood_;\n\n    likelihood_ = std::move(correction.likelihood_);\n\n    return *this;\n}\n\n\nMeasurementModel& GPFCorrection::getMeasurementModel() noexcept\n{\n    return gaussian_correction_->getMeasurementModel();\n}\n\n\nLikelihoodModel& GPFCorrection::getLikelihoodModel() noexcept\n{\n    return *likelihood_model_;\n}\n\n\nstd::pair<bool, Eigen::VectorXd> GPFCorrection::getLikelihood()\n{\n    return std::make_pair(valid_likelihood_, likelihood_);\n}\n\n\nvoid GPFCorrection::correctStep(const bfl::ParticleSet& pred_particles, bfl::ParticleSet& corr_particles)\n{\n    /* Propagate Gaussian belief associated to each particle. */\n    gaussian_correction_->correct(pred_particles, corr_particles);\n\n    /* Sample from the proposal distribution. */\n    for (std::size_t i = 0; i < pred_particles.components; i++)\n    {\n        corr_particles.state(i) = sampleFromProposal(corr_particles.mean(i), corr_particles.covariance(i));\n    }\n\n    /* Evaluate the likelihood. */\n    std::tie(valid_likelihood_, likelihood_) = getLikelihoodModel().likelihood(getMeasurementModel(), corr_particles.state());\n\n    if (!valid_likelihood_)\n    {\n        corr_particles = pred_particles;\n\n        return;\n    }\n\n    /* Evaluate the transition probability. */\n    VectorXd transition_probability = state_model_->getTransitionProbability(pred_particles.state(), corr_particles.state());\n\n    /* Update weights in the log space.\n     * w_{k} = w_{k-1} + log(likelihood) + log(transition_probability) - log(proposal_distribution)\n     */\n    double eps = std::numeric_limits<double>::min();\n    for (std::size_t i = 0; i < pred_particles.components; i++)\n    {\n        corr_particles.weight(i) = pred_particles.weight(i) + std::log(likelihood_(i) + eps) + std::log(transition_probability(i) + eps) - std::log(evaluateProposal(corr_particles.state(i), corr_particles.mean(i), corr_particles.covariance(i)) + eps);\n    }\n}\n\n\nEigen::VectorXd GPFCorrection::sampleFromProposal(const Eigen::VectorXd& mean, const Eigen::MatrixXd& covariance)\n{\n    /* Evaluate the square root of the state covariance matrix using the LDL' decomposition\n       (it can be used even if the covariance matrix is positive semidefinite). */\n    LDLT<MatrixXd> chol_ldlt(covariance);\n    MatrixXd sqrt_P = (chol_ldlt.transpositionsP() * MatrixXd::Identity(mean.size(), mean.size())).transpose() *\n                       chol_ldlt.matrixL() *\n                       chol_ldlt.vectorD().real().cwiseSqrt().asDiagonal();\n\n    /* Sample i.i.d standard normal univariates. */\n    VectorXd rand_vectors(mean.size());\n    for (int i = 0; i < rand_vectors.size(); i++)\n        rand_vectors(i) = gaussian_random_sample_();\n\n    /* Return a sample from a normal multivariate having mean `mean` and covariance 'covariance'. */\n    return mean + sqrt_P * rand_vectors;\n}\n\n\ndouble GPFCorrection::evaluateProposal\n(\n    const Eigen::VectorXd& state,\n    const Eigen::VectorXd& mean,\n    const Eigen::MatrixXd& covariance\n)\n{\n    /* Evaluate the proposal distribution, a Gaussian centered in 'mean' and having\n       covariance 'covariance', in the state 'state'. */\n    return utils::multivariate_gaussian_density(state, mean, covariance).coeff(0);\n}\n", "meta": {"hexsha": "202a2bcb2c799b4b3ce996c9d0b2023d9285b85f", "size": 5516, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/BayesFilters/src/GPFCorrection.cpp", "max_stars_repo_name": "mfkiwl/bayes-filters-lib", "max_stars_repo_head_hexsha": "8baabba1897bcc5634619fbc048bb5ab17a742da", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 50.0, "max_stars_repo_stars_event_min_datetime": "2017-04-12T09:02:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T20:01:35.000Z", "max_issues_repo_path": "src/BayesFilters/src/GPFCorrection.cpp", "max_issues_repo_name": "xEnVrE/bayes-filters-lib", "max_issues_repo_head_hexsha": "8baabba1897bcc5634619fbc048bb5ab17a742da", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 79.0, "max_issues_repo_issues_event_min_datetime": "2017-11-07T07:32:14.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-20T17:12:08.000Z", "max_forks_repo_path": "src/BayesFilters/src/GPFCorrection.cpp", "max_forks_repo_name": "xEnVrE/bayes-filters-lib", "max_forks_repo_head_hexsha": "8baabba1897bcc5634619fbc048bb5ab17a742da", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 23.0, "max_forks_repo_forks_event_min_datetime": "2017-05-07T01:47:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T10:15:59.000Z", "avg_line_length": 33.8404907975, "max_line_length": 251, "alphanum_fraction": 0.7282451051, "num_tokens": 1281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.45461125038843686}}
{"text": "// Copyright (c) 2022 CNES\n//\n// All rights reserved. Use of this source code is governed by a\n// BSD-style license that can be found in the LICENSE file.\n#pragma once\n#include <Eigen/Core>\n#include <algorithm>\n#include <boost/geometry.hpp>\n#include <optional>\n\n#include \"pyinterp/detail/geometry/box.hpp\"\n#include \"pyinterp/detail/geometry/point.hpp\"\n#include \"pyinterp/detail/math/radial_basis_functions.hpp\"\n#include \"pyinterp/detail/math/window_functions.hpp\"\n\nnamespace pyinterp::detail::geometry {\n\n/// Index points in the Cartesian space at N dimensions.\n///\n/// @tparam CoordinateType The class of storage for a point's coordinates.\n/// @tparam Type The type of data stored in the tree.\n/// @tparam N Number of dimensions in the Cartesian space handled.\ntemplate <typename CoordinateType, typename Type, size_t N>\nclass RTree {\n public:\n  /// Type of the point handled by this instance.\n  using point_t = geometry::PointND<CoordinateType, N>;\n\n  /// Type of distances between two points.\n  using distance_t = typename boost::geometry::default_distance_result<\n      point_t, geometry::PointND<CoordinateType, N>>::type;\n\n  /// Type of query results.\n  using result_t = std::pair<distance_t, Type>;\n\n  /// Value handled by this object\n  using value_t = std::pair<point_t, Type>;\n\n  /// Spatial index used\n  using rtree_t =\n      boost::geometry::index::rtree<value_t, boost::geometry::index::rstar<16>>;\n\n  /// Type of the implicit conversion between the type of coordinates and values\n  using promotion_t =\n      decltype(std::declval<CoordinateType>() + std::declval<Type>());\n\n  /// Default constructor\n  RTree() : tree_(new rtree_t{}) {}\n\n  /// Default destructor\n  virtual ~RTree() = default;\n\n  /// Default copy constructor\n  RTree(const RTree &) = default;\n\n  /// Default copy assignment operator\n  auto operator=(const RTree &) -> RTree & = default;\n\n  /// Move constructor\n  RTree(RTree &&) noexcept = default;\n\n  /// Move assignment operator\n  auto operator=(RTree &&) noexcept -> RTree & = default;\n\n  /// Returns the box able to contain all values stored in the container.\n  ///\n  /// @returns The box able to contain all values stored in the container or an\n  /// invalid box if there are no values in the container.\n  virtual inline auto bounds() const\n      -> std::optional<geometry::BoxND<CoordinateType, N>> {\n    if (empty()) {\n      return {};\n    }\n    return tree_->bounds();\n  }\n\n  /// Returns the number of points of this mesh\n  ///\n  /// @return the number of points\n  [[nodiscard]] constexpr auto size() const -> size_t { return tree_->size(); }\n\n  /// Query if the container is empty.\n  ///\n  /// @return true if the container is empty.\n  [[nodiscard]] constexpr auto empty() const -> bool { return tree_->empty(); }\n\n  /// Removes all values stored in the container.\n  inline auto clear() -> void { tree_->clear(); }\n\n  /// The tree is created using packing algorithm (The old data is erased before\n  /// construction.)\n  ///\n  /// @param points\n  inline auto packing(const std::vector<value_t> &points) -> void {\n    *tree_ = rtree_t(points);\n  }\n\n  /// Insert new data into the search tree\n  ///\n  /// @param point\n  inline auto insert(const value_t &value) -> void { tree_->insert(value); }\n\n  /// Search for the K nearest neighbors of a given point.\n  ///\n  /// @param point Point of interest\n  /// @param k The number of nearest neighbors to search.\n  /// @return the k nearest neighbors:\n  auto query(const point_t &point, const uint32_t k) const\n      -> std::vector<result_t> {\n    auto result = std::vector<result_t>();\n    std::for_each(\n        tree_->qbegin(boost::geometry::index::nearest(point, k)), tree_->qend(),\n        [&point, &result](const auto &item) {\n          result.emplace_back(std::make_pair(\n              boost::geometry::distance(point, item.first), item.second));\n        });\n    return result;\n  }\n\n  /// Search for the nearest neighbors of a given point within a radius r.\n  ///\n  /// @param point Point of interest\n  /// @param radius distance within which neighbors are returned\n  /// @return the k nearest neighbors\n  auto query_ball(const point_t &point, const distance_t radius) const\n      -> std::vector<result_t> {\n    auto result = std::vector<result_t>();\n    std::for_each(\n        tree_->qbegin(boost::geometry::index::satisfies([&](const auto &item) {\n          return boost::geometry::distance(item.first, point) <= radius;\n        })),\n        tree_->qend(), [&point, &result](const auto &item) {\n          result.emplace_back(std::make_pair(\n              boost::geometry::distance(point, item.first), item.second));\n        });\n    return result;\n  }\n\n  /// Search for the nearest K neighbors around a given point.\n  ///\n  /// @param point Point of interest\n  /// @param k The number of nearest neighbors to search.\n  /// @return the k nearest neighbors if the point is within by its\n  /// neighbors.\n  auto query_within(const point_t &point, const uint32_t k) const\n      -> std::vector<result_t> {\n    auto result = std::vector<result_t>();\n    auto points = boost::geometry::model::multi_point<point_t>();\n    points.reserve(k);\n\n    std::for_each(\n        tree_->qbegin(boost::geometry::index::nearest(point, k)), tree_->qend(),\n        [&points, &point, &result](const auto &item) {\n          points.emplace_back(item.first);\n          result.emplace_back(std::make_pair(\n              boost::geometry::distance(point, item.first), item.second));\n        });\n\n    // Are found points located around the requested point?\n    if (!boost::geometry::covered_by(\n            point, boost::geometry::return_envelope<\n                       boost::geometry::model::box<point_t>>(points))) {\n      return {};\n    }\n    return result;\n  }\n\n  /// Interpolation of the value at the requested position.\n  ///\n  /// @param point Point of interrest\n  /// @param radius The maximum radius of the search.\n  /// @param k The number of nearest neighbors to be used for calculating the\n  /// interpolated value.\n  /// @param p the power parameter.\n  /// @param within If true, the method ensures that the neighbors found are\n  /// located around the point of interest. In other words, this parameter\n  /// ensures that the calculated values will not be extrapolated.\n  /// @return a tuple containing the interpolated value and the number of\n  /// neighbors used in the calculation.\n  auto inverse_distance_weighting(const point_t &point, distance_t radius,\n                                  uint32_t k, uint32_t p, bool within) const\n      -> std::pair<distance_t, uint32_t> {\n    distance_t result = 0;\n    distance_t total_weight = 0;\n\n    // We're looking for the nearest k points.\n    auto nearest = within ? query_within(point, k) : query(point, k);\n    uint32_t neighbors = 0;\n\n    // For each point, the distance between the point requested and the point\n    // found is calculated and the information required for the Inverse distance\n    // weighting interpolation method is updated.\n    for (const auto &item : nearest) {\n      const auto distance = item.first;\n      if (distance < 1e-6) {\n        // If the user has requested a grid point, the mesh value is returned.\n        return std::make_pair(item.second, k);\n      }\n\n      if (distance <= radius) {\n        // If the neighbor found is within an acceptable radius it can be taken\n        // into account in the calculation.\n        auto wk =\n            static_cast<Type>(1 / std::pow(distance, static_cast<Type>(p)));\n        total_weight += wk;\n        result += item.second * wk;\n        ++neighbors;\n      }\n    }\n\n    // Finally the interpolated value is returned if there are selected points\n    // otherwise one returns an undefined value.\n    return total_weight != 0\n               ? std::make_pair(static_cast<distance_t>(result / total_weight),\n                                neighbors)\n               : std::make_pair(std::numeric_limits<distance_t>::quiet_NaN(),\n                                static_cast<uint32_t>(0));\n  }\n\n  /// Search for the nearest K neighbors of a given point.\n  ///\n  /// @param point Point of interest\n  /// @param radius The maximum radius of the search.\n  /// @param k The number of nearest neighbors to be used for calculating the\n  /// interpolated value.\n  /// @return A tuple containing the matrix describing the coordinates of the\n  /// selected points and a vector of the values of the points. The arrays will\n  /// be empty if no points are selected.\n  auto nearest(const point_t &point, const distance_t radius,\n               const uint32_t k) const\n      -> std::tuple<Matrix<promotion_t>, Vector<promotion_t>> {\n    auto coordinates = Matrix<promotion_t>(N, k);\n    auto values = Vector<promotion_t>(k);\n    auto jx = 0U;\n\n    std::for_each(\n        tree_->qbegin(boost::geometry::index::nearest(point, k)), tree_->qend(),\n        [&](const auto &item) {\n          if (boost::geometry::distance(point, item.first) <= radius) {\n            // If the point is not too far away, it is inserted and\n            // its coordinates and value are stored.\n            for (size_t ix = 0; ix < N; ++ix) {\n              coordinates(ix, jx) = geometry::point::get(item.first, ix);\n            }\n            values(jx++) = item.second;\n          }\n        });\n\n    // The arrays are resized according to the number of selected points. This\n    // number can be zero.\n    coordinates.conservativeResize(N, jx);\n    values.conservativeResize(jx);\n    return std::make_tuple(coordinates, values);\n  }\n\n  /// Search for the nearest K neighbors around a given point.\n  ///\n  /// @param point Point of interest\n  /// @param radius The maximum radius of the search.\n  /// @param k The number of nearest neighbors to be used for calculating the\n  /// interpolated value.\n  /// @return A tuple containing the matrix describing the coordinates of the\n  /// selected points and a vector of the values of the points. The arrays will\n  /// be empty if no points are selected.\n  auto nearest_within(const point_t &point, const distance_t radius,\n                      const uint32_t k) const\n      -> std::tuple<Matrix<promotion_t>, Vector<promotion_t>> {\n    auto points = boost::geometry::model::multi_point<point_t>();\n    auto coordinates = Matrix<promotion_t>(N, k);\n    auto values = Vector<promotion_t>(k);\n    auto jx = 0U;\n\n    // List of selected points ()\n    points.reserve(k);\n\n    std::for_each(\n        tree_->qbegin(boost::geometry::index::nearest(point, k)), tree_->qend(),\n        [&](const auto &item) {\n          if (boost::geometry::distance(point, item.first) <= radius) {\n            // If the point is not too far away, it is inserted and\n            // its coordinates and value are stored.\n            points.emplace_back(item.first);\n            for (size_t ix = 0; ix < N; ++ix) {\n              coordinates(ix, jx) = geometry::point::get(item.first, ix);\n            }\n            values(jx++) = item.second;\n          }\n        });\n\n    // If the point is not covered by its closest neighbors, an empty set will\n    // be returned.\n    if (!boost::geometry::covered_by(\n            point, boost::geometry::return_envelope<\n                       boost::geometry::model::box<point_t>>(points))) {\n      jx = 0;\n    }\n\n    // The arrays are resized according to the number of selected points. This\n    // number can be zero.\n    coordinates.conservativeResize(N, jx);\n    values.conservativeResize(jx);\n    return std::make_tuple(coordinates, values);\n  }\n\n  /// Interpolate the value of a point using a Radial Basis Function.\n  ///\n  /// @param point Point of interest\n  /// @param rbf The radial basis function to be used.\n  /// @param radius The maximum radius of the search.\n  /// @param k The number of nearest neighbors to be used for calculating the\n  /// interpolated value.\n  /// @param within If true, the method ensures that the neighbors found are\n  /// located around the point of interest. In other words, this parameter\n  /// ensures that the calculated values will not be extrapolated.\n  /// @return A pair containing the interpolated value and the number of\n  /// neighbors used in the calculation.\n  auto radial_basis_function(const point_t &point,\n                             const math::RBF<promotion_t> &rbf,\n                             distance_t radius, uint32_t k, bool within) const\n      -> std::pair<promotion_t, uint32_t> {\n    auto [coordinates, values] =\n        within ? nearest_within(point, radius, k) : nearest(point, radius, k);\n    if (values.size() == 0) {\n      return std::make_pair(std::numeric_limits<promotion_t>::quiet_NaN(), 0);\n    }\n    auto xi = Eigen::Matrix<promotion_t, N, 1>();\n    for (size_t ix = 0; ix < N; ++ix) {\n      xi(ix, 0) = geometry::point::get(point, ix);\n    }\n    auto interpolated = rbf.interpolate(coordinates, values, xi);\n    return std::make_pair(interpolated(0),\n                          static_cast<uint32_t>(values.size()));\n  }\n\n  /// Interpolate the value of a point using a Window Function.\n  ///\n  /// @param point Point of interest\n  /// @param wf The window function to be used.\n  /// @param radius The maximum radius of the search.\n  /// @param k The number of nearest neighbors to be used for calculating the\n  /// interpolated value.\n  /// @param within If true, the method ensures that the neighbors found are\n  /// located around the point of interest. In other words, this parameter\n  /// ensures that the calculated values will not be extrapolated.\n  /// @return A pair containing the interpolated value and the number of\n  /// neighbors used in the calculation.\n  auto window_function(const point_t &point,\n                       const math::WindowFunction<distance_t> &wf,\n                       const distance_t arg, distance_t radius, uint32_t k,\n                       bool within) const -> std::pair<distance_t, uint32_t> {\n    distance_t result = 0;\n    distance_t total_weight = 0;\n\n    auto nearest = within ? query_within(point, k) : query(point, k);\n    uint32_t neighbors = 0;\n\n    for (const auto &item : nearest) {\n      const auto distance = item.first;\n\n      auto wk = wf(distance, radius, arg);\n      total_weight += wk;\n      result += item.second * wk;\n      ++neighbors;\n    }\n\n    return total_weight != 0\n               ? std::make_pair(static_cast<distance_t>(result / total_weight),\n                                neighbors)\n               : std::make_pair(std::numeric_limits<distance_t>::quiet_NaN(),\n                                static_cast<uint32_t>(0));\n  }\n\n protected:\n  /// Geographic index used to store data and their searches.\n  std::shared_ptr<rtree_t> tree_;\n};\n\n}  // namespace pyinterp::detail::geometry\n", "meta": {"hexsha": "eea33490545a0bdc1528dd81430628375a60ba87", "size": 14633, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/pyinterp/core/include/pyinterp/detail/geometry/rtree.hpp", "max_stars_repo_name": "readthedocs-assistant/pangeo-pyinterp", "max_stars_repo_head_hexsha": "e9dc18445dce36638d5a90f64c8e2f1b53164f90", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/pyinterp/core/include/pyinterp/detail/geometry/rtree.hpp", "max_issues_repo_name": "readthedocs-assistant/pangeo-pyinterp", "max_issues_repo_head_hexsha": "e9dc18445dce36638d5a90f64c8e2f1b53164f90", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pyinterp/core/include/pyinterp/detail/geometry/rtree.hpp", "max_forks_repo_name": "readthedocs-assistant/pangeo-pyinterp", "max_forks_repo_head_hexsha": "e9dc18445dce36638d5a90f64c8e2f1b53164f90", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.6094986807, "max_line_length": 80, "alphanum_fraction": 0.6439554432, "num_tokens": 3412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.45461125038843686}}
{"text": "#pragma once\n\n#include <cstddef>\n\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/serialization/strong_typedef.hpp>\n\n#include <algorithm>\n#include <array>\n#include <cstdint>\n#include <cstring>\n#include <optional>\n#include <set>\n#include <variant>\n#include <vector>\n\nnamespace koinos {\n\n   using std::array;\n   using std::optional;\n   using std::set;\n   using std::variant;\n   using std::vector;\n\n   typedef boost::multiprecision::int128_t  int128_t;\n   typedef boost::multiprecision::uint128_t uint128_t;\n   typedef boost::multiprecision::int256_t  int256_t;\n   typedef boost::multiprecision::uint256_t uint256_t;\n\n   typedef boost::multiprecision::number<\n      boost::multiprecision::cpp_int_backend<\n         160,\n         160,\n         boost::multiprecision::unsigned_magnitude,\n         boost::multiprecision::unchecked, void\n      >\n   > uint160_t;\n\n   typedef boost::multiprecision::number<\n      boost::multiprecision::cpp_int_backend<\n         160,\n         160,\n         boost::multiprecision::signed_magnitude,\n         boost::multiprecision::unchecked, void\n      >\n   > int160_t;\n\n   typedef bool      boolean;\n   typedef int8_t    int8;\n   typedef uint8_t   uint8;\n   typedef int16_t   int16;\n   typedef uint16_t  uint16;\n   typedef int32_t   int32;\n   typedef uint32_t  uint32;\n   typedef int64_t   int64;\n   typedef uint64_t  uint64;\n   typedef int128_t  int128;\n   typedef uint128_t uint128;\n   typedef int160_t  int160;\n   typedef uint160_t uint160;\n   typedef int256_t  int256;\n   typedef uint256_t uint256;\n\n   using variable_blob = std::vector< char >;\n\n   template < size_t N >\n   using fixed_blob    = std::array< char, N >;\n\n   BOOST_STRONG_TYPEDEF( uint64_t, timestamp_type );\n   BOOST_STRONG_TYPEDEF( uint64_t, block_height_type );\n\n   struct multihash\n   {\n      uint64_t      id = 0;\n      variable_blob digest;\n\n      bool operator ==( const multihash& other ) const\n      {\n         return ( id == other.id )\n            && ( digest.size() == other.digest.size() )\n            && ( std::memcmp( digest.data(), other.digest.data(), other.digest.size() ) == 0 );\n      }\n\n      bool operator !=( const multihash& other ) const\n      {\n         return !(*this == other);\n      }\n\n      bool operator <( const multihash& other ) const\n      {\n         int64_t res = (int64_t)id - (int64_t)other.id;\n         if( res < 0 ) return true;\n         if( res > 0 ) return false;\n         res = digest.size() - other.digest.size();\n         if( res < 0 ) return true;\n         if( res > 0 ) return false;\n         return std::memcmp( digest.data(), other.digest.data(), digest.size() ) < 0;\n      }\n\n      bool operator <=( const multihash& other ) const\n      {\n         int64_t res = (int64_t)id - (int64_t)other.id;\n         if( res < 0 ) return true;\n         if( res > 0 ) return false;\n         res = digest.size() - other.digest.size();\n         if( res < 0 ) return true;\n         if( res > 0 ) return false;\n         return std::memcmp( digest.data(), other.digest.data(), digest.size() ) <= 0;\n      }\n\n      bool operator >( const multihash& other ) const\n      {\n         return !(*this <= other);\n      }\n\n      bool operator >=( const multihash& other ) const\n      {\n         return !(*this < other);\n      }\n   };\n\n} // koinos\n", "meta": {"hexsha": "913dc3d6c1565a4a28a52a4660e02ea982274465", "size": 3273, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "programs/koinos-types/lang/koinos_codegen_cpp/rt/basetypes.hpp", "max_stars_repo_name": "joticajulian/koinos-types", "max_stars_repo_head_hexsha": "7d01248437d063deb780af03057737e4937f82d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2021-02-10T20:57:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-17T00:09:15.000Z", "max_issues_repo_path": "programs/koinos-types/lang/koinos_codegen_cpp/rt/basetypes.hpp", "max_issues_repo_name": "joticajulian/koinos-types", "max_issues_repo_head_hexsha": "7d01248437d063deb780af03057737e4937f82d1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 82.0, "max_issues_repo_issues_event_min_datetime": "2021-02-08T22:59:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-01T17:40:07.000Z", "max_forks_repo_path": "programs/koinos-types/lang/koinos_codegen_cpp/rt/basetypes.hpp", "max_forks_repo_name": "joticajulian/koinos-types", "max_forks_repo_head_hexsha": "7d01248437d063deb780af03057737e4937f82d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-02-11T04:29:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-17T22:56:34.000Z", "avg_line_length": 26.6097560976, "max_line_length": 95, "alphanum_fraction": 0.6073938283, "num_tokens": 852, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.45460663918193417}}
{"text": "#include <iostream>\n#include <vector>\n\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/push_relabel_max_flow.hpp>\n\n// Graph Type with nested interior edge properties for flow algorithms\ntypedef boost::adjacency_list_traits<boost::vecS, boost::vecS, boost::directedS> traits;\ntypedef boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS, boost::no_property,\n    boost::property<boost::edge_capacity_t, long,\n        boost::property<boost::edge_residual_capacity_t, long,\n            boost::property<boost::edge_reverse_t, traits::edge_descriptor>>>> graph;\n\ntypedef traits::vertex_descriptor vertex_desc;\ntypedef traits::edge_descriptor edge_desc;\n\nclass edge_adder {\n  graph &G;\n\n public:\n  explicit edge_adder(graph &G) : G(G) {}\n\n  void add_edge(int from, int to, long capacity) {\n    auto c_map = boost::get(boost::edge_capacity, G);\n    auto r_map = boost::get(boost::edge_reverse, G);\n    const auto e = boost::add_edge(from, to, G).first;\n    const auto rev_e = boost::add_edge(to, from, G).first;\n    c_map[e] = capacity;\n    c_map[rev_e] = 0; // reverse edge has no capacity!\n    r_map[e] = rev_e;\n    r_map[rev_e] = e;\n  }\n};\n\n\nusing namespace std;\n\nvoid solve() {\n  int cols; cin >> cols;\n  int rows; cin >> rows;\n  \n  graph G;\n  edge_adder adder(G);\n  \n  int targetFlow = 0;\n  vertex_desc source = boost::add_vertex(G);\n  vertex_desc target = boost::add_vertex(G);\n\n  vector<vector<vertex_desc>> in(rows, vector<vertex_desc>(cols));\n  vector<vector<vertex_desc>> out(rows, vector<vertex_desc>(cols));\n  for (int row = 0; row < rows; ++row) {\n    for (int col = 0; col < cols; ++col) {\n      in[row][col] = boost::add_vertex(G);\n      out[row][col] = boost::add_vertex(G);\n    }\n  }\n  for (int row = 0; row < rows; ++row) {\n    for (int col = 0; col < cols; ++col) {\n      char c; cin >> c;\n      bool blocked = (c == 'x');\n      if (blocked) {\n        continue;\n      }\n      bool even = (row + col) % 2 == 0;\n      if (even) {\n        adder.add_edge(source, in[row][col], 1);\n        \n        if (row > 0)\n          adder.add_edge(in[row][col], out[row - 1][col], 1);\n        if (row < rows - 1)\n          adder.add_edge(in[row][col], out[row + 1][col], 1);\n        if (col > 0)\n          adder.add_edge(in[row][col], out[row][col - 1], 1);\n        if (col < cols - 1)\n          adder.add_edge(in[row][col], out[row][col + 1], 1);\n      }\n      else {\n        adder.add_edge(out[row][col], target, 1);\n      }\n      ++targetFlow;\n    }\n  }\n  if (targetFlow % 2 != 0) {\n    cout << \"no\" << endl;\n    return;\n  }\n  targetFlow /= 2;\n  \n  long flow = boost::push_relabel_max_flow(G, source, target);\n  cout << ((flow == targetFlow) ? \"yes\" : \"no\") << endl;\n}\n\nint main() {\n  ios_base::sync_with_stdio(false);\n  int t; cin >> t;\n  for (int i = 0; i < t; ++i) {\n    solve();\n  }\n}", "meta": {"hexsha": "9ef26d46e94b9d219706eef659d1af8e5ea22603", "size": 2814, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tiles.cpp", "max_stars_repo_name": "dsparber/algolab", "max_stars_repo_head_hexsha": "9781eb5c7444236f796f167f1f39fc9d913e5c53", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2021-01-01T17:19:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T12:27:57.000Z", "max_issues_repo_path": "src/tiles.cpp", "max_issues_repo_name": "dsparber/algolab", "max_issues_repo_head_hexsha": "9781eb5c7444236f796f167f1f39fc9d913e5c53", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tiles.cpp", "max_forks_repo_name": "dsparber/algolab", "max_forks_repo_head_hexsha": "9781eb5c7444236f796f167f1f39fc9d913e5c53", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-28T10:55:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-28T10:55:25.000Z", "avg_line_length": 28.4242424242, "max_line_length": 93, "alphanum_fraction": 0.5977256574, "num_tokens": 840, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.45460663918193417}}
{"text": "// Copyright (c) 2021 Sota Tsuji\r\n// This software is released under the MIT License.\r\n// http://opensource.org/licenses/mit-license.php\r\n\r\n#pragma once\r\n\r\n#include <boost/multiprecision/cpp_int.hpp>\r\n#include <vector>\r\n\r\n#include \"graph.hpp\"\r\n\r\nnamespace extraction_of_maximum_clique {\r\nusing std::tuple;\r\nusing std::vector;\r\nusing Bint = boost::multiprecision::cpp_int;\r\nusing Matrix = vector<vector<int>>;\r\nusing Polynomial = vector<Bint>;\r\nusing Polynomials = vector<Polynomial>;\r\n\r\nenum struct Infinity { Positive, Negative };\r\n\r\nPolynomial operator-(Polynomial pol);\r\nPolynomial operator/(const Polynomial& pol1, const Polynomial& pol2);\r\nPolynomial operator/(Polynomial pol, const Bint x);\r\n\r\nBint get_maximum_coefficient(const int n);\r\nvector<int> get_prime_list(const int n, const Bint c);\r\n// Polynomial get_coefficient(const WeightedGraph& S);\r\ntuple<Polynomial, Polynomial, Bint> polynomial_division(Polynomial f,\r\n                                                        const Polynomial& g);\r\nint get_number_of_roots(Polynomial f);\r\nint get_km(const WeightedGraph& S);\r\n\r\nvector<int> sieve_of_Eratosthenes(const int k);\r\nMatrix get_double_adjacent_matrix(const WeightedGraph& S);\r\n// Polynomial get_coefficient_by_modulo(const WeightedGraph& S, const int p);\r\n// Polynomial merge_coefficients(const Polynomial& f, const Polynomial& g);\r\nPolynomial differential(const Polynomial& f);\r\nPolynomial simplify_coefficient(const Polynomial& f);\r\nPolynomial gcd(Polynomial f, Polynomial g);\r\nPolynomial rem(const Polynomial& f, const Polynomial& g);\r\nBint substitute_into_polynomial(const Polynomial& f, const int x);\r\nint sigma(const Polynomials& fs, const int alpha);\r\nint sigma(const Polynomials& fs, const Infinity inf);\r\nint get_number_of_roots_by_strum(const Polynomial& f);\r\n\r\n/*\r\nThe following functions are tentative.\r\nCurrently, \"get_coefficient\" is NOT a polynomial-time algorithm.\r\nLater, we are going to replace it with a polynomial-time algorithm.\r\n*/\r\nusing PolynomialMatrix = vector<vector<Polynomial>>;\r\nPolynomial get_coefficient(const WeightedGraph& S);\r\nPolynomial calculate_determinant(const PolynomialMatrix& A);\r\nPolynomial operator*(const Polynomial& pol1, const Polynomial& pol2);\r\nPolynomial operator*(const int x, const Polynomial& pol);\r\nPolynomial& operator+=(Polynomial& self, const Polynomial& other);\r\n}  // namespace extraction_of_maximum_clique\r\n", "meta": {"hexsha": "151cec7845fa423534bd81329e13adde92580bc9", "size": 2385, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "extract_maximum_clique/include/calculate_km.hpp", "max_stars_repo_name": "SotaTsuji/extraction_maximum_clique", "max_stars_repo_head_hexsha": "e9a00f15fdccd5a36f6a9bcdf618e5f01fefded1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-22T08:18:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-22T08:18:49.000Z", "max_issues_repo_path": "extract_maximum_clique/include/calculate_km.hpp", "max_issues_repo_name": "SotaTsuji/extract_maximum_clique", "max_issues_repo_head_hexsha": "e9a00f15fdccd5a36f6a9bcdf618e5f01fefded1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "extract_maximum_clique/include/calculate_km.hpp", "max_forks_repo_name": "SotaTsuji/extract_maximum_clique", "max_forks_repo_head_hexsha": "e9a00f15fdccd5a36f6a9bcdf618e5f01fefded1", "max_forks_repo_licenses": ["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.4237288136, "max_line_length": 78, "alphanum_fraction": 0.7576519916, "num_tokens": 515, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.45453555442317756}}
{"text": "#define BOOST_TEST_MAIN\n#include <boost/test/included/unit_test.hpp>\n#include <srook/numeric/fixed_point.hpp>\n#include <srook/limits/numeric_limits.hpp>\n\nBOOST_AUTO_TEST_SUITE(numeric_fixed_point_test)\n\nBOOST_AUTO_TEST_CASE(fixed_point_operator_test1)\n{\n    typedef srook::numeric::fixed_point<4, 4> fixed_point_type;\n    fixed_point_type fp {};\n\n    ~fp;\n    +fp;\n    -fp;\n    !fp;\n    ++fp;\n    --fp;\n    fp++;\n    fp--;\n}\n\nBOOST_AUTO_TEST_CASE(fixed_point_operator_test2)\n{\n    typedef srook::numeric::fixed_point<4, 4> fixed_point_type;\n    auto fp = srook::numeric_limits<fixed_point_type>::max();\n    try {\n        fp.increment();\n    } catch (std::overflow_error) {}\n    try {\n        fp.post_increment();\n    } catch (std::overflow_error) {}\n    fp = srook::numeric_limits<fixed_point_type>::min();\n    try {\n        fp.decrement();\n    } catch (std::underflow_error) {}\n    try {\n        fp.post_decrement();\n    } catch (std::underflow_error) {}\n}\n\nBOOST_AUTO_TEST_CASE(fixed_point_operator_test3)\n{\n    typedef srook::numeric::fixed_point<4, 4> fixed_point_type;\n    fixed_point_type fp1 = 2;\n    auto fp2 = srook::numeric_limits<fixed_point_type>::max();\n    auto fp3 = srook::numeric_limits<fixed_point_type>::min();\n    \n    fp1 /= fp1;\n    fp1 += fp1;\n    fp1 *= fp1;\n    fp1 |= fp1;\n    fp1 ^= fp1;\n    fp1 &= fp1;\n    fp1 >>= fp1;\n    fp1 <<= fp1;\n    fp1 -= fp1;\n\n    try {\n        fp2.iadd(fp2);\n    } catch (std::overflow_error) {}\n    try {\n        fp3.isub(fp2);\n    } catch (std::underflow_error) {}\n    try {\n        fp2.imul(fp2);\n    } catch (std::overflow_error) {}\n    fp3.idiv(fp2);\n}\n\nBOOST_AUTO_TEST_CASE(fixed_point_operator_test4)\n{\n    typedef srook::numeric::fixed_point<4, 4> fixed_point_type;\n    fixed_point_type fp1 = 2;\n    fp1 + 1;\n    fp1 - 1;\n    fp1 * 1;\n    fp1 / 1;\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "80cc54fd3e4bad8bdb14894dedc06b3ac7b7e173", "size": 1843, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/numeric/fixed_point/operator_test.cpp", "max_stars_repo_name": "falgon/srookCppLibraries", "max_stars_repo_head_hexsha": "ebcfacafa56026f6558bcd1c584ec774cc751e57", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-07-01T07:54:37.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-01T07:54:37.000Z", "max_issues_repo_path": "tests/numeric/fixed_point/operator_test.cpp", "max_issues_repo_name": "falgon/srookCppLibraries", "max_issues_repo_head_hexsha": "ebcfacafa56026f6558bcd1c584ec774cc751e57", "max_issues_repo_licenses": ["MIT"], "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/numeric/fixed_point/operator_test.cpp", "max_forks_repo_name": "falgon/srookCppLibraries", "max_forks_repo_head_hexsha": "ebcfacafa56026f6558bcd1c584ec774cc751e57", "max_forks_repo_licenses": ["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.4756097561, "max_line_length": 63, "alphanum_fraction": 0.6299511666, "num_tokens": 550, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217431943271999, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.4545355468845247}}
{"text": "\n// Copyright Aleksey Gurtovoy 2002-2004\n//\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt or copy at \n// http://www.boost.org/LICENSE_1_0.txt)\n//\n// See http://www.boost.org/libs/mpl for documentation.\n\n// $Source: /cvsroot/boost/boost/libs/mpl/test/zip_view.cpp,v $\n// $Date: 2004/09/02 15:41:35 $\n// $Revision: 1.4 $\n\n#include <boost/mpl/zip_view.hpp>\n\n#include <boost/mpl/transform_view.hpp>\n#include <boost/mpl/filter_view.hpp>\n#include <boost/mpl/range_c.hpp>\n#include <boost/mpl/vector.hpp>\n#include <boost/mpl/at.hpp>\n#include <boost/mpl/equal.hpp>\n#include <boost/mpl/equal_to.hpp>\n#include <boost/mpl/unpack_args.hpp>\n#include <boost/mpl/math/is_even.hpp>\n\n#include <boost/mpl/aux_/test.hpp>\n\n\nMPL_TEST_CASE()\n{\n    typedef transform_view<\n          zip_view< vector< range_c<int,0,10>, range_c<int,10,20> > >\n        , unpack_args< plus<> >\n        > result;\n\n    MPL_ASSERT(( equal< \n          result\n        , filter_view< range_c<int,10,30>, is_even<_> >\n        , equal_to<_,_>\n        > ));\n}\n", "meta": {"hexsha": "f6ca37f7a5d6b6b1af696b0270be3cd70eb684b4", "size": 1066, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Source/boost_1_33_1/libs/mpl/test/zip_view.cpp", "max_stars_repo_name": "spxuw/RFIM", "max_stars_repo_head_hexsha": "32b78fbb90c7008b1106b0cff4f8023ae83c9b6d", "max_stars_repo_licenses": ["MIT"], "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/boost_1_33_1/libs/mpl/test/zip_view.cpp", "max_issues_repo_name": "spxuw/RFIM", "max_issues_repo_head_hexsha": "32b78fbb90c7008b1106b0cff4f8023ae83c9b6d", "max_issues_repo_licenses": ["MIT"], "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/boost_1_33_1/libs/mpl/test/zip_view.cpp", "max_forks_repo_name": "spxuw/RFIM", "max_forks_repo_head_hexsha": "32b78fbb90c7008b1106b0cff4f8023ae83c9b6d", "max_forks_repo_licenses": ["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.380952381, "max_line_length": 69, "alphanum_fraction": 0.669793621, "num_tokens": 315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.45453554439287225}}
{"text": "#pragma once\n\n#include <string>\n#include <Eigen/Core>\n\nstd::string main_print()\n{\n    float norm = Eigen::Vector3f{0,1,2}.norm();\n    return  \"Hello! Eigen::Vector3f{0,1,2}.norm()=\" + std::to_string(norm);\n}", "meta": {"hexsha": "9da1d93251931a5df4e837b7fcf808918938cba4", "size": 207, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/external-project/include/main.hpp", "max_stars_repo_name": "thautwarm/clang-build", "max_stars_repo_head_hexsha": "79cc6bd8e17a328d9e6a0fbdada2ba88600423aa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-02-28T10:16:43.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-08T22:12:45.000Z", "max_issues_repo_path": "test/external-project/include/main.hpp", "max_issues_repo_name": "thautwarm/clang-build", "max_issues_repo_head_hexsha": "79cc6bd8e17a328d9e6a0fbdada2ba88600423aa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 23.0, "max_issues_repo_issues_event_min_datetime": "2018-02-25T21:46:37.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-09T20:47:15.000Z", "max_forks_repo_path": "test/external-project/include/main.hpp", "max_forks_repo_name": "thautwarm/clang-build", "max_forks_repo_head_hexsha": "79cc6bd8e17a328d9e6a0fbdada2ba88600423aa", "max_forks_repo_licenses": ["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.7, "max_line_length": 75, "alphanum_fraction": 0.6473429952, "num_tokens": 66, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217431943271998, "lm_q2_score": 0.6297746143530797, "lm_q1q2_score": 0.4545355418693721}}
{"text": "// -----------------------------------------------------------------------------\n// Fern \u00a9 Geoneric\n//\n// This file is part of Geoneric Fern which is available under the terms of\n// the GNU General Public License (GPL), version 2. If you do not want to\n// be bound by the terms of the GPL, you may purchase a proprietary license\n// from Geoneric (http://www.geoneric.eu/contact).\n// -----------------------------------------------------------------------------\n#define BOOST_TEST_MODULE fern algorithm statistic sum\n#include <limits>\n#include <numeric>\n#include <boost/test/unit_test.hpp>\n#include \"fern/core/data_customization_point/scalar.h\"\n#include \"fern/feature/core/data_customization_point/array.h\"\n#include \"fern/feature/core/data_customization_point/masked_array.h\"\n#include \"fern/feature/core/data_customization_point/masked_scalar.h\"\n#include \"fern/algorithm/core/test/test_utils.h\"\n#include \"fern/algorithm/statistic/sum.h\"\n\n\nnamespace f = fern;\nnamespace fa = f::algorithm;\nnamespace ft = f::test;\n\n\ntemplate<\n    typename ExecutionPolicy,\n    typename Argument,\n    typename Result>\nvoid verify_0d_0d(\n    ExecutionPolicy& execution_policy,\n    Argument const& value,\n    Result const& result_we_want)\n{\n    int result_we_got{-9};\n    fa::statistic::sum<>(execution_policy, value, result_we_got);\n    BOOST_CHECK_EQUAL(result_we_got, result_we_want);\n}\n\n\ntemplate<\n    typename ExecutionPolicy>\nvoid test_0d_0d(\n    ExecutionPolicy& execution_policy)\n{\n    {\n        int value{5};\n        int result_we_want{5};\n        verify_0d_0d(execution_policy, value, result_we_want);\n    }\n\n    {\n        int value{-5};\n        int result_we_want{-5};\n        verify_0d_0d(execution_policy, value, result_we_want);\n    }\n\n    {\n        int value{0};\n        int result_we_want{0};\n        verify_0d_0d(execution_policy, value, result_we_want);\n    }\n}\n\n\ntemplate<\n    typename ExecutionPolicy,\n    typename Argument,\n    typename Result>\nvoid verify_0d_0d_masked(\n    ExecutionPolicy& execution_policy,\n    Argument const& value,\n    Result const& result_we_want)\n{\n    using InputNoDataPolicy = fa::InputNoDataPolicies<\n        fa::DetectNoDataByValue<bool>>;\n    using OutputNoDataPolicy = fa::MarkNoDataByValue<bool>;\n\n    f::MaskedScalar<int> result_we_got{-9};\n\n    InputNoDataPolicy input_no_data_policy{{value.mask(), true}};\n    OutputNoDataPolicy output_no_data_policy(result_we_got.mask(), true);\n\n    fa::statistic::sum<fa::sum::OutOfRangePolicy>(\n        input_no_data_policy, output_no_data_policy, execution_policy,\n        value, result_we_got);\n    BOOST_CHECK_EQUAL(result_we_got, result_we_want);\n}\n\n\ntemplate<\n    typename ExecutionPolicy>\nvoid test_0d_0d_masked(\n    ExecutionPolicy& execution_policy)\n{\n    // Regular case.\n    {\n        f::MaskedScalar<int> value{5};\n        f::MaskedScalar<int> result_we_want{5};\n        verify_0d_0d_masked(execution_policy, value, result_we_want);\n    }\n\n    // Mask a value.\n    {\n        f::MaskedScalar<int> value{5, true};\n        f::MaskedScalar<int> result_we_want{-9, true};\n        verify_0d_0d_masked(execution_policy, value, result_we_want);\n    }\n}\n\n\ntemplate<\n    typename ExecutionPolicy,\n    typename Argument,\n    typename Result>\nvoid verify_1d_0d(\n    ExecutionPolicy& execution_policy,\n    Argument const& value,\n    Result const& result_we_want)\n{\n    int result_we_got{-9};\n    fa::statistic::sum<>(execution_policy, value, result_we_got);\n    BOOST_CHECK_EQUAL(result_we_got, result_we_want);\n}\n\n\ntemplate<\n    typename ExecutionPolicy>\nvoid test_1d_0d(\n    ExecutionPolicy& execution_policy)\n{\n    // Regular case.\n    {\n        f::Array<int, 1> value(ft::nr_elements_1d);\n        std::iota(value.data(), value.data() + ft::nr_elements_1d, 0);\n        int result_we_want{std::accumulate(value.data(), value.data() +\n            ft::nr_elements_1d, 0)};\n        verify_1d_0d(execution_policy, value, result_we_want);\n    }\n\n    // Out of range.\n    {\n        f::Array<int, 1> value(ft::nr_elements_1d);\n        std::iota(value.data(), value.data() + ft::nr_elements_1d, 0);\n        get(value, 5) = std::numeric_limits<int>::max();\n        // Overflow, integer wrap.\n        int result_we_want = std::accumulate(value.data(), value.data() +\n            ft::nr_elements_1d, 0);\n        verify_1d_0d(execution_policy, value, result_we_want);\n    }\n\n    // Empty.\n    {\n        f::Array<int, 1> value(0);\n        int result_we_want{-9};\n        verify_1d_0d(execution_policy, value, result_we_want);\n    }\n}\n\n\ntemplate<\n    typename ExecutionPolicy,\n    typename Argument,\n    typename Result>\nvoid verify_1d_0d_masked(\n    ExecutionPolicy& execution_policy,\n    Argument const& value,\n    Result const& result_we_want)\n{\n    using InputNoDataPolicy = fa::InputNoDataPolicies<\n        fa::DetectNoDataByValue<f::Mask<1>>>;\n    using OutputNoDataPolicy = fa::MarkNoDataByValue<bool>;\n\n    f::MaskedScalar<int> result_we_got{-9};\n\n    InputNoDataPolicy input_no_data_policy{{value.mask(), true}};\n    OutputNoDataPolicy output_no_data_policy(result_we_got.mask(), true);\n\n    fa::statistic::sum<fa::sum::OutOfRangePolicy>(\n        input_no_data_policy, output_no_data_policy, execution_policy,\n        value, result_we_got);\n    BOOST_CHECK_EQUAL(result_we_got, result_we_want);\n}\n\n\ntemplate<\n    typename ExecutionPolicy>\nvoid test_1d_0d_masked(\n    ExecutionPolicy& execution_policy)\n{\n    // Regular case.\n    {\n        f::MaskedArray<int, 1> value(ft::nr_elements_1d);\n        std::iota(value.data(), value.data() + ft::nr_elements_1d, 0);\n        f::MaskedScalar<int> result_we_want{std::accumulate(\n            value.data(), value.data() + ft::nr_elements_1d, 0)};\n        verify_1d_0d_masked(execution_policy, value, result_we_want);\n    }\n\n\n    // Mask a value.\n    {\n        f::MaskedArray<int, 1> value(ft::nr_elements_1d);\n        std::iota(value.data(), value.data() + ft::nr_elements_1d, 0);\n        get(value.mask(), 5) = true;\n        f::MaskedScalar<int> result_we_want{std::accumulate(\n            value.data(), value.data() + ft::nr_elements_1d, 0)};\n        result_we_want -= get(value, 5);\n        verify_1d_0d_masked(execution_policy, value, result_we_want);\n    }\n\n\n    // Mask all values.\n    {\n        f::MaskedArray<int, 1> value(ft::nr_elements_1d);\n        value.mask().fill(true);\n        f::MaskedScalar<int> result_we_want{-9, true};\n        verify_1d_0d_masked(execution_policy, value, result_we_want);\n    }\n\n\n    // Out of range, within a block.\n    {\n        f::MaskedArray<int, 1> value(ft::nr_elements_1d, 0);\n        get(value, 0) = std::numeric_limits<int>::max();\n        get(value, 1) = 1;\n        f::MaskedScalar<int> result_we_want{-9, true};\n        verify_1d_0d_masked(execution_policy, value, result_we_want);\n    }\n\n\n    // Out of range, when aggregating block results.\n    {\n        f::MaskedArray<int, 1> value(ft::nr_elements_1d, 0);\n        value.fill(0);\n        get(value, 0) = std::numeric_limits<int>::max();\n        get(value, ft::nr_elements_1d - 1) = 1;\n        f::MaskedScalar<int> result_we_want{-9, true};\n        verify_1d_0d_masked(execution_policy, value, result_we_want);\n    }\n\n    // Empty.\n    {\n        f::MaskedArray<int, 1> value(0);\n        f::MaskedScalar<int> result_we_want{-9, true};\n        verify_1d_0d_masked(execution_policy, value, result_we_want);\n    }\n}\n\n\ntemplate<\n    typename ExecutionPolicy,\n    typename Argument,\n    typename Result>\nvoid verify_2d_0d(\n    ExecutionPolicy& execution_policy,\n    Argument const& value,\n    Result const& result_we_want)\n{\n    int result_we_got{-9};\n    fa::statistic::sum<>(execution_policy, value, result_we_got);\n    BOOST_CHECK_EQUAL(result_we_got, result_we_want);\n}\n\n\ntemplate<\n    typename ExecutionPolicy>\nvoid test_2d_0d(\n    ExecutionPolicy& execution_policy)\n{\n    // Regular case.\n    {\n        f::Array<int, 2> value(f::extents[ft::nr_rows][ft::nr_cols]);\n        std::iota(value.data(), value.data() + ft::nr_elements_2d, 0);\n        int result_we_want{std::accumulate(value.data(), value.data() +\n            ft::nr_elements_2d, 0)};\n        verify_2d_0d(execution_policy, value, result_we_want);\n    }\n\n    // Empty.\n    {\n        f::Array<int, 2> value(f::extents[0][0]);\n        int result_we_want{-9};\n        verify_2d_0d(execution_policy, value, result_we_want);\n    }\n}\n\n\ntemplate<\n    typename ExecutionPolicy,\n    typename Argument,\n    typename Result>\nvoid verify_2d_0d_masked(\n    ExecutionPolicy& execution_policy,\n    Argument const& value,\n    Result const& result_we_want)\n{\n    using InputNoDataPolicy = fa::InputNoDataPolicies<\n        fa::DetectNoDataByValue<f::Mask<2>>>;\n    using OutputNoDataPolicy = fa::MarkNoDataByValue<bool>;\n\n    f::MaskedScalar<int> result_we_got{-9};\n\n    InputNoDataPolicy input_no_data_policy{{value.mask(), true}};\n    OutputNoDataPolicy output_no_data_policy(result_we_got.mask(), true);\n\n    fa::statistic::sum<fa::sum::OutOfRangePolicy>(\n        input_no_data_policy, output_no_data_policy, execution_policy,\n        value, result_we_got);\n    BOOST_CHECK_EQUAL(result_we_got, result_we_want);\n}\n\n\ntemplate<\n    typename ExecutionPolicy>\nvoid test_2d_0d_masked(\n    ExecutionPolicy& execution_policy)\n{\n    // Regular case.\n    {\n        f::MaskedArray<int, 2> value(f::extents[ft::nr_rows][ft::nr_cols]);\n        std::iota(value.data(), value.data() + ft::nr_elements_2d, 0);\n        f::MaskedScalar<int> result_we_want{std::accumulate(\n            value.data(), value.data() + ft::nr_elements_2d, 0)};\n        verify_2d_0d(execution_policy, value, result_we_want);\n    }\n\n\n    // Mask a value.\n    {\n        f::MaskedArray<int, 2> value(f::extents[ft::nr_rows][ft::nr_cols]);\n        std::iota(value.data(), value.data() + ft::nr_elements_2d, 0);\n        get(value.mask(), 5) = true;\n        f::MaskedScalar<int> result_we_want{std::accumulate(\n            value.data(), value.data() + ft::nr_elements_2d, 0)};\n        result_we_want -= get(value, 5);\n        verify_2d_0d_masked(execution_policy, value, result_we_want);\n    }\n\n\n    // Mask all values.\n    {\n        f::MaskedArray<int, 2> value(f::extents[ft::nr_rows][ft::nr_cols]);\n        value.mask().fill(true);\n        f::MaskedScalar<int> result_we_want{-9, true};\n        verify_2d_0d_masked(execution_policy, value, result_we_want);\n    }\n\n\n    // Out of range, within a block.\n    {\n        f::MaskedArray<int, 2> value(f::extents[ft::nr_rows][ft::nr_cols], 0);\n        get(value, 0) = std::numeric_limits<int>::max();\n        get(value, 1) = 1;\n        f::MaskedScalar<int> result_we_want{-9, true};\n        verify_2d_0d_masked(execution_policy, value, result_we_want);\n    }\n\n\n    // Out of range, when aggregating block results.\n    {\n        f::MaskedArray<int, 2> value(f::extents[ft::nr_rows][ft::nr_cols], 0);\n        value.fill(0);\n        get(value, 0) = std::numeric_limits<int>::max();\n        get(value, ft::nr_elements_2d - 1) = 1;\n        f::MaskedScalar<int> result_we_want{-9, true};\n        verify_2d_0d_masked(execution_policy, value, result_we_want);\n    }\n\n    // Empty.\n    {\n        f::MaskedArray<int, 2> value(f::extents[0][0]);\n        f::MaskedScalar<int> result_we_want{-9, true};\n        verify_2d_0d_masked(execution_policy, value, result_we_want);\n    }\n}\n\n\nFERN_UNARY_AGGREGATE_TEST_CASES()\n", "meta": {"hexsha": "eecf2a0782c8fd938665ab8abc913e965cfb750c", "size": 11254, "ext": "cc", "lang": "C++", "max_stars_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/fern/source/fern/algorithm/statistic/test/sum_test.cc", "max_stars_repo_name": "quanpands/wflow", "max_stars_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/fern/source/fern/algorithm/statistic/test/sum_test.cc", "max_issues_repo_name": "quanpands/wflow", "max_issues_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/fern/source/fern/algorithm/statistic/test/sum_test.cc", "max_forks_repo_name": "quanpands/wflow", "max_forks_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.6157894737, "max_line_length": 80, "alphanum_fraction": 0.6533676915, "num_tokens": 3114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.6297745935070808, "lm_q1q2_score": 0.4545355343625669}}
{"text": "#ifndef STAN_MATH_PRIM_MAT_FUN_MULTIPLY_HPP\n#define STAN_MATH_PRIM_MAT_FUN_MULTIPLY_HPP\n\n#include <stan/math/prim/mat/fun/Eigen.hpp>\n#include <stan/math/prim/arr/err/check_matching_sizes.hpp>\n#include <stan/math/prim/mat/err/check_multiplicable.hpp>\n#include <boost/type_traits/is_arithmetic.hpp>\n#include <boost/utility/enable_if.hpp>\n\nnamespace stan {\n  namespace math {\n\n    /**\n     * Return specified matrix multiplied by specified scalar.\n     * @tparam R Row type for matrix.\n     * @tparam C Column type for matrix.\n     * @param m Matrix.\n     * @param c Scalar.\n     * @return Product of matrix and scalar.\n     */\n    template <int R, int C, typename T>\n    inline\n    typename boost::enable_if_c<boost::is_arithmetic<T>::value,\n                                Eigen::Matrix<double, R, C> >::type\n    multiply(const Eigen::Matrix<double, R, C>& m,\n             T c) {\n      return c * m;\n    }\n\n    /**\n     * Return specified scalar multiplied by specified matrix.\n     * @tparam R Row type for matrix.\n     * @tparam C Column type for matrix.\n     * @param c Scalar.\n     * @param m Matrix.\n     * @return Product of scalar and matrix.\n     */\n    template <int R, int C, typename T>\n    inline\n    typename boost::enable_if_c<boost::is_arithmetic<T>::value,\n                                Eigen::Matrix<double, R, C> >::type\n    multiply(T c,\n             const Eigen::Matrix<double, R, C>& m) {\n      return c * m;\n    }\n\n    /**\n     * Return the product of the specified matrices.  The number of\n     * columns in the first matrix must be the same as the number of rows\n     * in the second matrix.\n     * @param m1 First matrix.\n     * @param m2 Second matrix.\n     * @return The product of the first and second matrices.\n     * @throw std::domain_error if the number of columns of m1 does not match\n     *   the number of rows of m2.\n     */\n    template<int R1, int C1, int R2, int C2>\n    inline Eigen::Matrix<double, R1, C2>\n    multiply(const Eigen::Matrix<double, R1, C1>& m1,\n             const Eigen::Matrix<double, R2, C2>& m2) {\n      check_multiplicable(\"multiply\",\n                          \"m1\", m1,\n                          \"m2\", m2);\n      return m1*m2;\n    }\n\n    /**\n     * Return the scalar product of the specified row vector and\n     * specified column vector.  The return is the same as the dot\n     * product.  The two vectors must be the same size.\n     * @param rv Row vector.\n     * @param v Column vector.\n     * @return Scalar result of multiplying row vector by column vector.\n     * @throw std::domain_error if rv and v are not the same size.\n     */\n    template<int C1, int R2>\n    inline double multiply(const Eigen::Matrix<double, 1, C1>& rv,\n                           const Eigen::Matrix<double, R2, 1>& v) {\n      check_matching_sizes(\"multiply\",\n                           \"rv\", rv,\n                           \"v\", v);\n      return rv.dot(v);\n    }\n\n  }\n}\n#endif\n", "meta": {"hexsha": "cdcb7649a52b4e4826af60a5f66dc278f4f9c3ea", "size": 2920, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/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/prim/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/prim/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": 33.1818181818, "max_line_length": 77, "alphanum_fraction": 0.5969178082, "num_tokens": 723, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217431943271999, "lm_q2_score": 0.6297746004557471, "lm_q1q2_score": 0.4545355318390669}}
{"text": "//\n// Created by dominik on 29.06.21.\n//\n#include \"types.hpp\"\n#include \"utils.hpp\"\n#include \"structure_utils.hpp\"\n#include <cmath>\n#include <cassert>\n#include <stdexcept>\n#include <fstream>\n#include <filesystem>\n#include <boost/multi_array.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <gtest/gtest.h>\n\nusing namespace boost;\nusing namespace sqsgenerator::utils;\nusing namespace boost::numeric::ublas;\nnamespace fs = std::filesystem;\n\nnamespace sqsgenerator::test {\n\n    template <typename T> T convert_to (const std::string &str)\n    {\n        std::istringstream ss(str);\n        T num;\n        ss >> num;\n        return num;\n    }\n/**\n * \\brief   Return the filenames of all files that have the specified extension\n *          in the specified directory and all subdirectories.\n */\n    std::vector<fs::path> get_all(std::string const &root, std::string const &ext) {\n        std::vector<fs::path> paths;\n        for (auto &p : fs::recursive_directory_iterator(root))\n        {\n            if (p.path().extension() == ext) paths.emplace_back(p.path());\n        }\n        return paths;\n    }\n\n    std::vector<std::string> split (std::string s, std::string delimiter) {\n        // Taken from https://stackoverflow.com/questions/14265581/parse-split-a-string-in-c-using-string-delimiter-standard-c\n        size_t pos_start = 0, pos_end, delim_len = delimiter.length();\n        std::string token;\n        std::vector<std::string> res;\n\n        while ((pos_end = s.find (delimiter, pos_start)) != std::string::npos) {\n            token = s.substr (pos_start, pos_end - pos_start);\n            pos_start = pos_end + delim_len;\n            res.push_back (token);\n        }\n\n        res.push_back (s.substr (pos_start));\n        return res;\n    }\n\n    template<typename T, size_t NDims>\n    multi_array<T, NDims> read_array(std::ifstream &fhandle, std::string const &name) {\n        std::string line;\n        std::string start_line = name + \"::array::begin\";\n        while (std::getline(fhandle, line)) {\n            if (line == start_line) { break; }\n        }\n        assert(line == start_line);\n        // Read dimensions\n        std::getline(fhandle, line);\n        auto crumbs  = split(line, \" \");\n        assert(crumbs.size() == 2);\n        assert(crumbs[0] == name + \"::array::ndims\");\n        size_t ndims {std::stoul(crumbs[1])};\n        assert(ndims == NDims);\n\n        // Read shape\n        std::getline(fhandle, line);\n        crumbs  = split(line, \" \");\n        assert(crumbs.size() == ndims+1);\n        assert(crumbs[0] == name + \"::array::shape\");\n        std::vector<size_t> shape;\n        for(auto it = crumbs.begin() + 1; it != crumbs.end(); ++it) shape.push_back(std::stoul(*it));\n        assert(shape.size() == ndims);\n        size_t num_elements = std::accumulate(shape.begin(), shape.end(), 1, std::multiplies<size_t>());\n\n        std::getline(fhandle, line);\n        crumbs  = split(line, \" \");\n        assert(crumbs.size() == num_elements+1);\n        assert(crumbs[0] == name + \"::array::data\");\n        std::vector<T> data;\n        for(auto it = crumbs.begin() + 1; it != crumbs.end(); ++it) data.push_back(convert_to<T>(*it));\n        assert(data.size() == num_elements);\n\n\n        multi_array<T, NDims> result;\n        auto& shape_array = reinterpret_cast<boost::array<size_t, NDims> const&>(*shape.data());\n        result.resize(shape_array);\n        result.assign(data.begin(), data.end());\n        std::getline(fhandle, line);\n        assert(line == name + \"::array::end\");\n        return result;\n    }\n\n    struct TestCaseData {\n    public:\n        array_2d_t lattice;\n        array_2d_t fcoords;\n        array_2d_t distances;\n        array_3d_t vecs;\n        pair_shell_matrix_t shells;\n    };\n\n    TestCaseData read_test_data(std::string const &path) {\n        std::ifstream fhandle(path);\n        std::string line;\n        auto lattice = read_array<double, 2>(fhandle, \"lattice\");\n        auto fcoords = read_array<double, 2>(fhandle, \"fcoords\");\n        auto d2 = read_array<double, 2>(fhandle, \"distances\");\n        auto shells = read_array<shell_t, 2>(fhandle, \"shells\");\n        auto vecs = read_array<double, 3>(fhandle, \"vecs\");\n\n        fhandle.close();\n        return TestCaseData {lattice, fcoords, d2, vecs, shells};\n    }\n\n    class StructureUtilsTestFixture : public ::testing::Test {\n    protected:\n        std::vector<TestCaseData> test_cases{};\n\n    public:\n        void SetUp() {\n            // code here will execute just before the test ensues\n            // std::cout << \"StructureUtilsTestFixture::SetUp(): \" << std::filesystem::current_path() << std::endl;\n            get_all(\"resources\", \".data\");\n            for (auto &p : get_all(\"resources\", \".data\")) {\n                // std::cout << \"StructureUtilsTestFixture::SetUp(): Found test case: \" << p << std::endl;\n                test_cases.emplace_back(read_test_data(p));\n            }\n        };\n\n        void TearDown() {\n            // code here will be called just after the test completes\n            // ok to through exceptions from here if need be\n        }\n\n\n    };\n\n    template<typename MultiArrayA>\n    void assert_multi_array_equal(const MultiArrayA &a, const MultiArrayA &b) {\n        typedef typename MultiArrayA::element T;\n\n        ASSERT_EQ(a.num_elements(), b.num_elements());\n        for (size_t i = 0; i < a.num_elements(); ++i) {\n            ASSERT_NEAR(std::abs<T>(a.data()[i]), std::abs<T>(b.data()[i]), 1.0e-5);\n            //EXPECT_NEAR(a.data()[i], b.data()[i], 1.0e-5);\n        }\n    }\n\n    template<>\n    void assert_multi_array_equal<pair_shell_matrix_t>(const pair_shell_matrix_t &a, const pair_shell_matrix_t &b) {\n        ASSERT_EQ(a.num_elements(), b.num_elements());\n        for (size_t i = 0; i < a.num_elements(); ++i) {\n            //ASSERT_NEAR(std::abs<int>(a.data()[i]), std::abs<int>(b.data()[i]), 1.0e-5);\n            EXPECT_NEAR(std::abs<int>(a.data()[i]), std::abs<int>(b.data()[i]), 1.0e-5);\n            //EXPECT_NEAR(a.data()[i], b.data()[i], 1.0e-5);\n        }\n    }\n\n    TEST_F(StructureUtilsTestFixture, TestPbcVectors) {\n        for (TestCaseData &test_case : test_cases) {\n            matrix<double> lattice (matrix_from_multi_array(test_case.lattice));\n            matrix<double> fcoords (matrix_from_multi_array(test_case.fcoords));\n            auto pbc_vecs = sqsgenerator::utils::pbc_shortest_vectors(lattice, fcoords, true);\n            for (size_t i = 0; i < 3; i++) ASSERT_EQ(pbc_vecs.shape()[i], test_case.vecs.shape()[i]);\n            assert_multi_array_equal(pbc_vecs, test_case.vecs);\n        }\n    }\n\n    TEST_F(StructureUtilsTestFixture, TestDistanceMatrix) {\n        typedef multi_array<double, 3> pbc_mat;\n        for (TestCaseData &test_case : test_cases) {\n            matrix<double> lattice (matrix_from_multi_array(test_case.lattice));\n            matrix<double> fcoords (matrix_from_multi_array(test_case.fcoords));\n            auto pbc_vecs = sqsgenerator::utils::pbc_shortest_vectors(lattice, fcoords, true);\n            auto d2 = sqsgenerator::utils::distance_matrix(pbc_vecs);\n            for (size_t i = 0; i < 2; i++)  ASSERT_EQ(d2.shape()[i], test_case.vecs.shape()[i]);\n            assert_multi_array_equal(d2, test_case.distances);\n            auto d2_external = sqsgenerator::utils::distance_matrix(test_case.vecs);\n            assert_multi_array_equal(d2, d2_external);\n        }\n    }\n\n    TEST_F(StructureUtilsTestFixture, TestShellMatrix) {\n        for (TestCaseData &test_case : test_cases) {\n            matrix<double> lattice (matrix_from_multi_array(test_case.lattice));\n            matrix<double> fcoords (matrix_from_multi_array(test_case.fcoords));\n            auto pbc_vecs = sqsgenerator::utils::pbc_shortest_vectors(lattice, fcoords, true);\n            auto d2 = sqsgenerator::utils::distance_matrix(pbc_vecs);\n            auto distances = sqsgenerator::utils::default_shell_distances(d2, 1.0e-3);\n            auto shells = sqsgenerator::utils::shell_matrix(d2, distances, 1.0e-3);\n            auto natoms {static_cast<index_t>(fcoords.size1())};\n            for (size_t i = 0; i < 2; i++)  ASSERT_EQ(shells.shape()[i], test_case.shells.shape()[i]);\n            assert_multi_array_equal(shells, test_case.shells);\n            /*for (index_t i = 0; i < natoms; i++) {\n                for (index_t j = i+1; j < natoms; j++) {\n                    if (shells[i][j] != test_case.shells[i][j]) {\n                        std::cout << \"Different shell (\" << i << \", \" << j << \") = (\" << static_cast<int>(shells[i][j]) << \" != \" << static_cast<int>(test_case.shells[i][j]) << \") = (\" << d2[i][j] << \", \" << distances[shells[i][j]] << \")\" << std::endl;\n                    } else {\n                        ASSERT_EQ(shells[i][j], test_case.shells[i][j]);\n                    }\n                }\n            }*/\n            auto shells_external = sqsgenerator::utils::shell_matrix(test_case.distances, distances);\n            assert_multi_array_equal(shells, shells_external);\n            std::cout << format_vector(distances);\n            // Make sure the main diagonal is zero\n            for (index_t i = 0; i < natoms; i++) {\n                ASSERT_EQ(shells[i][i], 0);\n            }\n            // Ensure the matrix is symmetric\n            for (index_t i = 0; i < natoms; i++) {\n                for (index_t j = i+1; j < natoms; j++)\n                    ASSERT_EQ(shells[i][j], shells[j][i]);\n            }\n        }\n    }\n\n    TEST_F(StructureUtilsTestFixture, TestCreatePairListSizes) {\n        for (TestCaseData &test_case : test_cases) {\n            matrix<double> lattice (matrix_from_multi_array(test_case.lattice));\n            matrix<double> fcoords (matrix_from_multi_array(test_case.fcoords));\n            std::map<shell_t, size_t> counts;\n            std::map<shell_t, double> all_weights;\n            auto natoms {static_cast<index_t>(fcoords.size1())};\n            auto pbc_vecs = sqsgenerator::utils::pbc_shortest_vectors(lattice, fcoords, true);\n            auto d2 = sqsgenerator::utils::distance_matrix(pbc_vecs);\n            auto distances = sqsgenerator::utils::default_shell_distances(d2);\n            pair_shell_matrix_t shells = sqsgenerator::utils::shell_matrix(d2, distances);\n            auto max_shell = static_cast<index_t>(*std::max_element(shells.origin(), shells.origin()+shells.num_elements()));\n            for (auto i = 1; i <= max_shell; i++) {\n                counts.insert(std::make_pair(i, 0));\n                all_weights.insert(std::make_pair(i, 0.0));\n            }\n            // If all shells are present, the list length must be the number of pairs in the structure\n            ASSERT_EQ(create_pair_list(shells, all_weights).size(), natoms*(natoms-1)/2);\n            for (index_t i = 0; i < natoms; i++) {\n                for (index_t j = i+1; j < natoms; j++) {\n                    counts[shells[i][j]]++;\n                }\n            }\n            // If theres only one shell it must be exactly the number of pairs in the corresponding shell\n            for (auto i = 1; i <= max_shell; i++) {\n                auto num_pairs = create_pair_list(shells, {{i, 0.0}}).size();\n                auto should_be = counts[i];\n                ASSERT_EQ(num_pairs, should_be);\n            }\n            // Same must be true for any combination of two shells\n            for (auto i = 1; i <= max_shell; i++) {\n                for (auto j = i+1; j <= max_shell; j++) {\n                    auto num_pairs = create_pair_list(shells, {{i, 0.0}, {j, 0.0}}).size();\n                    auto should_be = counts[i]+counts[j];\n                    ASSERT_EQ(num_pairs, should_be);\n                }\n            }\n        }\n    }\n}\n\nint main(int argc, char **argv) {\n    ::testing::InitGoogleTest(&argc, argv);\n    return RUN_ALL_TESTS();\n}", "meta": {"hexsha": "84884eaf1cd47d621a422a5b210cbd129ccaec3f", "size": 11767, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/core/src/test_structure_utils.cpp", "max_stars_repo_name": "dgehringer/sqsgenerator", "max_stars_repo_head_hexsha": "562697166a53f806629e8e1086b381871d9a675e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2019-11-16T10:34:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T09:32:42.000Z", "max_issues_repo_path": "test/core/src/test_structure_utils.cpp", "max_issues_repo_name": "dgehringer/sqsgenerator", "max_issues_repo_head_hexsha": "562697166a53f806629e8e1086b381871d9a675e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2019-11-21T05:54:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T07:56:34.000Z", "max_forks_repo_path": "test/core/src/test_structure_utils.cpp", "max_forks_repo_name": "dgehringer/sqsgenerator", "max_forks_repo_head_hexsha": "562697166a53f806629e8e1086b381871d9a675e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-09-28T14:28:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-05T14:11:44.000Z", "avg_line_length": 43.2610294118, "max_line_length": 252, "alphanum_fraction": 0.580861732, "num_tokens": 2944, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217431943271998, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.4545355268239142}}
{"text": "#ifndef STAN_MATH_PRIM_PROB_STD_NORMAL_RNG_HPP\n#define STAN_MATH_PRIM_PROB_STD_NORMAL_RNG_HPP\n\n#include <stan/math/prim/meta.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n\nnamespace stan {\nnamespace math {\n\n/** \\ingroup prob_dists\n * Return a standard Normal random variate using the specified\n * random number generator.\n *\n * @tparam RNG type of random number generator\n * @param rng random number generator\n * @return A standard normal random variate\n */\ntemplate <class RNG>\ninline double std_normal_rng(RNG& rng) {\n  using boost::normal_distribution;\n  using boost::variate_generator;\n  static const char* function = \"std_normal_rng\";\n\n  variate_generator<RNG&, normal_distribution<>> norm_rng(\n      rng, normal_distribution<>(0, 1));\n\n  return norm_rng();\n}\n\n}  // namespace math\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "6c04592c203cdd76025f6544ba1f1823ef700604", "size": 868, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/prim/prob/std_normal_rng.hpp", "max_stars_repo_name": "LaudateCorpus1/math", "max_stars_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-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/std_normal_rng.hpp", "max_issues_repo_name": "LaudateCorpus1/math", "max_issues_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "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/std_normal_rng.hpp", "max_forks_repo_name": "LaudateCorpus1/math", "max_forks_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-05-10T12:55:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-10T12:55:07.000Z", "avg_line_length": 25.5294117647, "max_line_length": 62, "alphanum_fraction": 0.7638248848, "num_tokens": 203, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.45453024653125573}}
{"text": "#include \"delsum-poly/include/poly.hh\"\n#include \"delsum-poly/src/lib.rs.h\"\n#include <cstdint>\n#include <climits>\n#include <NTL/GF2X.h>\n#include <NTL/GF2E.h>\n#include <NTL/GF2XFactoring.h>\nnamespace poly\n{\n    long i64_to_l(int64_t x) {\n        if (x > LONG_MAX || x < LONG_MIN) {\n            std::cerr << \"Polynomial too big, probably because of big input files\" << std::endl\n                      << \"Try using smaller files or run on a platform with larger long variables\" << std::endl;\n            abort();\n        }\n        return (long)x;\n    }\n    Poly::Poly()\n    {\n        int_pol = NTL::GF2X();\n    }\n    Poly::Poly(const Poly &b)\n    {\n        int_pol = NTL::GF2X(b.int_pol);\n    }\n    Poly::Poly(Poly &&b)\n    {\n        int_pol = NTL::GF2X(b.int_pol);\n    }\n    bool Poly::coeff(int64_t idx) const\n    {\n        return NTL::IsOne(NTL::coeff(int_pol, i64_to_l(idx)));\n    }\n    bool Poly::eq(const Poly &b) const\n    {\n        return int_pol == b.int_pol;\n    }\n    int64_t deg(const Poly &a)\n    {\n        return NTL::deg(a.int_pol);\n    }\n    std::unique_ptr<Poly> copy_poly(const Poly &p)\n    {\n        return std::make_unique<Poly>(p);\n    }\n    std::unique_ptr<std::vector<PolyI64Pair>> factor(const Poly &p, int64_t verbosity)\n    {\n        auto v = std::vector<PolyI64Pair>();\n        auto decomp = NTL::CanZass(p.int_pol, i64_to_l(verbosity));\n        for (auto x : decomp)\n        {\n            auto poly = Poly();\n            poly.int_pol = x.a;\n            v.push_back(PolyI64Pair{.poly = std::make_unique<Poly>(std::move(poly)), .l = (int64_t)x.b});\n        }\n        return std::make_unique<std::vector<PolyI64Pair>>(std::move(v));\n    }\n\n    std::unique_ptr<Poly> new_poly_shifted(rust::Slice<uint8_t> bytes, int64_t shift, bool msb_first)\n    {\n        auto lshift = i64_to_l(shift);\n        auto ret = Poly();\n        ret.int_pol = NTL::GF2X();\n        ret.int_pol.SetLength(lshift + bytes.length() * 8);\n        for (size_t i = 0; i < bytes.length(); i++)\n        {\n            auto current_byte = bytes.data()[bytes.length() - 1 - i];\n            for (int j = 0; j < 8; j++)\n            {\n                auto bit_pos = msb_first ? j : (7 - j);\n                auto current_bit = (current_byte >> bit_pos) & 1;\n                auto bit_index = lshift + 8 * i + j;\n                ret.int_pol[bit_index] = current_bit;\n            }\n        }\n        ret.int_pol.normalize();\n        return std::make_unique<Poly>(ret);\n    }\n\n    std::unique_ptr<Poly> new_poly(rust::Slice<uint8_t> bytes)\n    {\n        return new_poly_shifted(bytes, 0, true);\n    }\n    std::unique_ptr<Poly> new_zero()\n    {\n        auto ret = Poly();\n        return std::make_unique<Poly>(ret);\n    }\n\n    std::unique_ptr<std::vector<uint8_t>> Poly::to_bytes(int64_t min_bytes) const\n    {\n        auto d = NTL::deg(int_pol);\n        auto n_bytes = d / 8 + 1;\n        if (d < 0) {\n            n_bytes = 0;\n        }\n        auto v = std::vector<uint8_t>();\n        auto lmin = i64_to_l(min_bytes);\n        auto amount_of_bytes = n_bytes > lmin ? n_bytes : lmin;\n        v.reserve(amount_of_bytes);\n        for (long i = 0; i < amount_of_bytes - n_bytes; i++) {\n            v.push_back(0);\n        }\n        uint8_t current_byte = 0;\n        for (long i = d; i >= 0; i--)\n        {\n            current_byte <<= 1;\n            current_byte |= (uint8_t)NTL::rep(int_pol[i]);\n            if (i % 8 == 0)\n            {\n                v.push_back(current_byte);\n                current_byte = 0;\n            }\n        }\n        return std::make_unique<std::vector<uint8_t>>(v);\n    }\n    std::unique_ptr<Poly> add(const Poly &b, const Poly &c)\n    {\n        auto ret = Poly();\n        ret.int_pol = b.int_pol + c.int_pol;\n        return std::make_unique<Poly>(ret);\n    }\n    void Poly::add_to(const Poly &b)\n    {\n        int_pol += b.int_pol;\n    }\n    std::unique_ptr<Poly> mul(const Poly &b, const Poly &c)\n    {\n        auto ret = Poly();\n        ret.int_pol = b.int_pol * c.int_pol;\n        return std::make_unique<Poly>(ret);\n    }\n    void Poly::mul_to(const Poly &b)\n    {\n        int_pol *= b.int_pol;\n    }\n    std::unique_ptr<Poly> div(const Poly &b, const Poly &c)\n    {\n        auto ret = Poly();\n        ret.int_pol = b.int_pol / c.int_pol;\n        return std::make_unique<Poly>(ret);\n    }\n    void Poly::div_to(const Poly &b)\n    {\n        int_pol /= b.int_pol;\n    }\n    bool Poly::div_to_checked(const Poly &b)\n    {\n        auto ret = NTL::divide(int_pol, b.int_pol);\n        return ret == 1;\n    }\n    bool Poly::is_zero() const\n    {\n        return NTL::IsZero(int_pol);\n    }\n    std::unique_ptr<Poly> gcd(const Poly &b, const Poly &c)\n    {\n        auto ret = Poly();\n        NTL::GCD(ret.int_pol, b.int_pol, c.int_pol);\n        return std::make_unique<Poly>(ret);\n    }\n    std::unique_ptr<Poly> xgcd(Poly &x, Poly &y, const Poly &b, const Poly &c)\n    {\n        auto ret = Poly();\n        NTL::XGCD(ret.int_pol, x.int_pol, y.int_pol, b.int_pol, c.int_pol);\n        return std::make_unique<Poly>(ret);\n    }\n    void Poly::gcd_to(const Poly &b)\n    {\n        NTL::GCD(int_pol, int_pol, b.int_pol);\n    }\n    std::unique_ptr<Poly> rem(const Poly &b, const Poly &c)\n    {\n        auto ret = Poly();\n        NTL::rem(ret.int_pol, b.int_pol, c.int_pol);\n        return std::make_unique<Poly>(ret);\n    }\n    void Poly::rem_to(const Poly &b)\n    {\n        NTL::rem(int_pol, int_pol, b.int_pol);\n    }\n    std::unique_ptr<Poly> power(const Poly &p, int64_t n)\n    {\n        auto q = Poly();\n        q.int_pol = NTL::power(p.int_pol, i64_to_l(n));\n        return std::make_unique<Poly>(q);\n    }\n    std::unique_ptr<Poly> shift(const Poly &p, int64_t n)\n    {\n        auto q = Poly();\n        if (n >= 0) {\n            q.int_pol = NTL::LeftShift(p.int_pol, i64_to_l(n));\n        } else {\n            q.int_pol = NTL::RightShift(p.int_pol, i64_to_l(-n));\n        }\n        return std::make_unique<Poly>(q);\n    }\n    void Poly::sqr()\n    {\n        int_pol = NTL::sqr(int_pol);\n    }\n\n    // PolyRem stuff\n\n    PolyRem::PolyRem(const Poly &p)\n    {\n        int_pol = NTL::GF2E();\n        int_pol.init(p.int_pol);\n    }\n    // copy\n    PolyRem::PolyRem(const PolyRem &b)\n    {\n        int_pol = NTL::GF2E(b.int_pol);\n    }\n    // move\n    PolyRem::PolyRem(PolyRem &&b)\n    {\n        int_pol = NTL::GF2E(b.int_pol);\n    }\n    PolyRem::PolyRem(const NTL::GF2E &p)\n    {\n        int_pol = NTL::GF2E(p);\n    }\n\n    std::unique_ptr<PolyRem> new_polyrem(const Poly &rem, const Poly &m)\n    {\n        auto ret = PolyRem(m);\n        NTL::conv(ret.int_pol, rem.int_pol);\n        return std::make_unique<PolyRem>(ret);\n    }\n    void PolyRem::add_to(const PolyRem &b)\n    {\n        int_pol += b.int_pol;\n    }\n    void PolyRem::mul_to(const PolyRem &b)\n    {\n        int_pol *= b.int_pol;\n    }\n    void PolyRem::div_to(const PolyRem &b)\n    {\n        int_pol /= b.int_pol;\n    }\n    void PolyRem::sqr()\n    {\n        int_pol = NTL::sqr(int_pol);\n    }\n    std::unique_ptr<Poly> PolyRem::rep() const\n    {\n        auto ret = Poly();\n        ret.int_pol = NTL::rep(int_pol);\n        return std::make_unique<Poly>(ret);\n    }\n    std::unique_ptr<PolyRem> powermod(const PolyRem &p, int64_t n)\n    {\n        auto q = PolyRem(NTL::power(p.int_pol, i64_to_l(n)));\n        return std::make_unique<PolyRem>(q);\n    }\n    std::unique_ptr<PolyRem> copy_polyrem(const PolyRem &p)\n    {\n        return std::make_unique<PolyRem>(PolyRem(p));\n    }\n} // namespace poly\n", "meta": {"hexsha": "0b1283f0b69b5ee3f42dcb942f56eb1e72f28775", "size": 7453, "ext": "cc", "lang": "C++", "max_stars_repo_path": "delsum-poly/src/poly.cc", "max_stars_repo_name": "dtolnay-contrib/delsum", "max_stars_repo_head_hexsha": "2b001d21e8d2d0904516c4b070ba06412b091000", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "delsum-poly/src/poly.cc", "max_issues_repo_name": "dtolnay-contrib/delsum", "max_issues_repo_head_hexsha": "2b001d21e8d2d0904516c4b070ba06412b091000", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "delsum-poly/src/poly.cc", "max_forks_repo_name": "dtolnay-contrib/delsum", "max_forks_repo_head_hexsha": "2b001d21e8d2d0904516c4b070ba06412b091000", "max_forks_repo_licenses": ["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.3384030418, "max_line_length": 112, "alphanum_fraction": 0.5353548906, "num_tokens": 2182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.45453024653125573}}
{"text": "/* Copyright (c) 2016, the Cap authors.\n *\n * This file is subject to the Modified BSD License and may not be distributed\n * without copyright and license information. Please refer to the file LICENSE\n * for the text and further information on this license.\n */\n\n#define BOOST_TEST_MODULE TestResistorCapacitor2\n\n#include \"main.cc\"\n\n#include <cap/energy_storage_device.h>\n#include <boost/format.hpp>\n#include <boost/foreach.hpp>\n#include <boost/property_tree/ptree.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/special_functions/cos_pi.hpp>\n#include <boost/test/unit_test.hpp>\n#include <iostream>\n#include <fstream>\n\n#include <cap/resistor_capacitor.h>\n#include <memory>\n\n// Check that linear voltage works by imposing a sine on a general series +\n// parallel RC device.\n// TODO add more linear tests once the function is properly implemented\n\nvoid test(std::shared_ptr<boost::property_tree::ptree> input_database,\n          std::shared_ptr<cap::EnergyStorageDevice> device)\n{\n  double const series_resistance =\n      input_database->get<double>(\"device.series_resistance\");\n  double const parallel_resistance =\n      input_database->get<double>(\"device.parallel_resistance\");\n  double const capacitance = input_database->get<double>(\"device.capacitance\");\n  double const frequency =\n      input_database->get<double>(\"impedance_spectroscopy.frequency\");\n  double const amplitude =\n      input_database->get<double>(\"impedance_spectroscopy.amplitude\");\n  int const cycles = input_database->get<int>(\"impedance_spectroscopy.cycles\");\n  int const ignore_cycles =\n      input_database->get<int>(\"impedance_spectroscopy.ignore_cycles\");\n  int const steps_per_cycle =\n      input_database->get<int>(\"impedance_spectroscopy.steps_per_cycle\");\n  double const tolerance =\n      input_database->get<double>(\"impedance_spectroscopy.tolerance\");\n  double const initial_voltage = 0.0;\n  std::string const type = input_database->get<std::string>(\"device.type\");\n\n  double time = 0.0;\n  double const time_step = 1.0 / frequency / steps_per_cycle;\n  double const pi = std::acos(-1.0);\n  BOOST_CHECK_EQUAL(std::acos(-1.0), boost::math::constants::pi<double>());\n\n  for (unsigned int i = 0; i < 20; ++i)\n    device->evolve_one_time_step_linear_voltage(10., initial_voltage);\n  double voltage;\n  double current;\n  std::fstream fout;\n  fout.open(\"resistor_capacitor_data_\" + type, std::fstream::out);\n\n  std::cout << type << \"\\n\";\n  double const angular_frequency = 2.0 * pi * frequency;\n\n  double const gain =\n      ((type.compare(\"SeriesRC\") == 0)\n           ? angular_frequency * capacitance /\n                 std::sqrt(1.0 + std::pow(angular_frequency *\n                                              series_resistance * capacitance,\n                                          2))\n           : 1.0 / (series_resistance + parallel_resistance) /\n                 (1.0 + std::pow(angular_frequency * series_resistance *\n                                     parallel_resistance /\n                                     (series_resistance + parallel_resistance) *\n                                     capacitance,\n                                 2)) *\n                 std::sqrt(\n                     std::pow(1.0 +\n                                  std::pow(angular_frequency *\n                                               parallel_resistance *\n                                               capacitance,\n                                           2) *\n                                      series_resistance /\n                                      (series_resistance + parallel_resistance),\n                              2) +\n                     std::pow(angular_frequency *\n                                  std::pow(parallel_resistance, 2) /\n                                  (series_resistance + parallel_resistance) *\n                                  capacitance,\n                              2)));\n\n  double const phase =\n      ((type.compare(\"SeriesRC\") == 0)\n           ? std::atan(1.0 /\n                       (angular_frequency * series_resistance * capacitance))\n           : std::atan(angular_frequency * std::pow(parallel_resistance, 2) /\n                       (series_resistance + parallel_resistance) * capacitance /\n                       (1.0 +\n                        std::pow(angular_frequency * parallel_resistance *\n                                     capacitance,\n                                 2) *\n                            series_resistance /\n                            (series_resistance + parallel_resistance))));\n\n  for (int n = 0; n < cycles * steps_per_cycle; ++n)\n  {\n    time += time_step;\n    voltage = amplitude * std::sin(angular_frequency * time);\n    device->evolve_one_time_step_linear_voltage(time_step, voltage);\n    device->get_current(current);\n    double const exact =\n        amplitude * gain * std::sin(angular_frequency * time + phase);\n    double const error = 100.0 * std::abs(current - exact) / (amplitude * gain);\n    if (n >= ignore_cycles * steps_per_cycle)\n      BOOST_CHECK_SMALL(error, tolerance);\n\n    fout << boost::format(\"  %22.15e  %22.15e  %22.15e  %22.15e  %22.15e  \\n\") %\n                time % current % voltage % exact % error;\n  }\n  fout.close();\n}\n\nBOOST_AUTO_TEST_CASE(test_resistor_capacitor)\n{\n  std::shared_ptr<boost::property_tree::ptree> input_database =\n      std::make_shared<boost::property_tree::ptree>();\n  input_database->put(\"device.type\", \"ParallelRC\");\n  input_database->put(\"device.capacitance\", 3.0);\n  input_database->put(\"device.parallel_resistance\", 0.025);\n  input_database->put(\"device.series_resistance\", 5.0);\n  input_database->put(\"impedance_spectroscopy.frequency\", 1.0e-5);\n  input_database->put(\"impedance_spectroscopy.amplitude\", 1.1);\n  input_database->put(\"impedance_spectroscopy.cycles\", 2);\n  input_database->put(\"impedance_spectroscopy.ignore_cycles\", 1);\n  input_database->put(\"impedance_spectroscopy.steps_per_cycle\", 2048);\n  input_database->put(\"impedance_spectroscopy.tolerance\", 0.1);\n\n  // build an energy storage system\n  std::shared_ptr<boost::property_tree::ptree> device_database =\n      std::make_shared<boost::property_tree::ptree>(\n          input_database->get_child(\"device\"));\n  std::shared_ptr<cap::EnergyStorageDevice> device =\n      cap::EnergyStorageDevice::build(*device_database,\n                                      boost::mpi::communicator());\n\n  // Check ParallelRC\n  test(input_database, device);\n\n  // Check SeriesRC\n  input_database->put(\"device.type\", \"SeriesRC\");\n  device_database = std::make_shared<boost::property_tree::ptree>(\n      input_database->get_child(\"device\"));\n  device = cap::EnergyStorageDevice::build(*device_database,\n                                           boost::mpi::communicator());\n  test(input_database, device);\n}\n", "meta": {"hexsha": "ede8c683236c86b8f96ac7af46ad0ccd9cfe645f", "size": 6792, "ext": "cc", "lang": "C++", "max_stars_repo_path": "cpp/test/test_resistor_capacitor_circuit-2.cc", "max_stars_repo_name": "iiscsahoo/EnergyData", "max_stars_repo_head_hexsha": "6230145b5df6b126eab11aea58a5cfaa11ad5ba1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2016-05-15T11:42:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-27T19:33:04.000Z", "max_issues_repo_path": "cpp/test/test_resistor_capacitor_circuit-2.cc", "max_issues_repo_name": "iiscsahoo/EnergyData", "max_issues_repo_head_hexsha": "6230145b5df6b126eab11aea58a5cfaa11ad5ba1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 198.0, "max_issues_repo_issues_event_min_datetime": "2016-01-27T16:46:59.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-11T06:31:37.000Z", "max_forks_repo_path": "cpp/test/test_resistor_capacitor_circuit-2.cc", "max_forks_repo_name": "iiscsahoo/EnergyData", "max_forks_repo_head_hexsha": "6230145b5df6b126eab11aea58a5cfaa11ad5ba1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2016-01-27T15:17:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-15T02:06:50.000Z", "avg_line_length": 42.9873417722, "max_line_length": 80, "alphanum_fraction": 0.6143992933, "num_tokens": 1501, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.45453024653125573}}
{"text": "\n#include \"tile/math/basis.h\"\n\n#include <utility>\n\n#include <boost/math/common_factor_rt.hpp>\n\nnamespace vertexai {\nnamespace tile {\nnamespace math {\n\nbool BasisBuilder::addEquation(const Polynomial<Rational>& orig) {\n  IVLOG(4, \"In basis builder, adding poly \" << orig);\n  // Remove any constants\n  Polynomial<Rational> nc = orig - orig.constant();\n  Polynomial<Rational> p = nc;\n\n  // Reduce the polynomial via existing polynomials\n  for (size_t i = 0; i < reduced_.size(); i++) {\n    // Get the 'to-be-reduced' ratio\n    Rational ratio = p[vars_[i]] / reduced_[i][vars_[i]];\n    // Subtract it out\n    p -= ratio * reduced_[i];\n  }\n  IVLOG(4, \"Reduced verion:\" << p);\n  // If the result is 0, equation is linearly dependant on existing basis\n  if (p == Polynomial<Rational>()) {\n    return false;\n  }\n\n  // Add the original equation minus the constant + the reduced equation\n  added_.push_back(nc);\n  reduced_.push_back(p);\n  // Add in new variables if any\n  for (const auto& kvp : p.getMap()) {\n    if (vars_set_.count(kvp.first) == 0) {\n      vars_set_.insert(kvp.first);\n      vars_.push_back(kvp.first);\n    }\n  }\n  // Swap the variable names to make the nth variable nonzero for the nth polynomial\n  size_t i = added_.size() - 1;\n  for (size_t j = i; j < vars_.size(); j++) {\n    if (p[vars_[j]] != 0) {\n      std::swap(vars_[i], vars_[j]);\n      break;\n    }\n  }\n  // All good\n  return true;\n}\n\n}  // namespace math\n}  // namespace tile\n}  // namespace vertexai\n", "meta": {"hexsha": "5e9dc25638b2c3972ab8ae5fb0e5b6a5f21a2344", "size": 1471, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tile/math/basis.cc", "max_stars_repo_name": "redoclag/plaidml", "max_stars_repo_head_hexsha": "46d9e8b3f1e1093aab2a0dfa40b2e15e3cc7d314", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4535.0, "max_stars_repo_stars_event_min_datetime": "2017-10-20T05:03:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T15:42:33.000Z", "max_issues_repo_path": "tile/math/basis.cc", "max_issues_repo_name": "HOZHENWAI/plaidml", "max_issues_repo_head_hexsha": "46d9e8b3f1e1093aab2a0dfa40b2e15e3cc7d314", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 984.0, "max_issues_repo_issues_event_min_datetime": "2017-10-20T17:16:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T05:43:18.000Z", "max_forks_repo_path": "tile/math/basis.cc", "max_forks_repo_name": "HOZHENWAI/plaidml", "max_forks_repo_head_hexsha": "46d9e8b3f1e1093aab2a0dfa40b2e15e3cc7d314", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 492.0, "max_forks_repo_forks_event_min_datetime": "2017-10-20T18:22:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T09:00:05.000Z", "avg_line_length": 26.2678571429, "max_line_length": 84, "alphanum_fraction": 0.6390210741, "num_tokens": 415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390746, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4545302465312556}}
{"text": "#define BOOST_TEST_MODULE StencilConvolution\n#include <boost/test/unit_test.hpp>\n#include <vexcl/vector.hpp>\n#include <vexcl/multivector.hpp>\n#include <vexcl/stencil.hpp>\n#include \"context_setup.hpp\"\n\nstruct index {\n    size_t n;\n    index(size_t n) : n(n) {}\n\n    size_t operator()(size_t i, long shift) const {\n        return std::min<size_t>(n - 1, std::max<long>(0, static_cast<long>(i) + shift));\n    }\n};\n\nBOOST_AUTO_TEST_CASE(stencil_convolution)\n{\n    const size_t n = 1024;\n\n    std::vector<double> s = random_vector<double>(rand() % 64 + 1);\n\n    int center = rand() % s.size();\n\n    vex::stencil<double> S(ctx, s, center);\n\n    std::vector<double> x = random_vector<double>(n);\n    std::generate(x.begin(), x.end(), [](){ return (double)rand() / RAND_MAX; });\n\n    vex::vector<double> X(ctx, x);\n    vex::vector<double> Y(ctx, n);\n\n    Y = 1;\n    Y += X * S;\n\n    index idx(n);\n\n    check_sample(Y, [&](size_t i, double a) {\n        double sum = 1;\n        size_t j = 0;\n        int k = -center;\n        for(; j < s.size(); k++, j++)\n            sum += s[j] * x[idx(i, k)];\n        BOOST_CHECK_CLOSE(a, sum, 1e-8);\n    });\n\n    Y = 42 * (X * S);\n\n    check_sample(Y, [&](size_t i, double a) {\n        double sum = 0;\n        size_t j = 0;\n        int k = -center;\n        for(; j < s.size(); k++, j++)\n            sum += s[j] * x[idx(i, k)];\n        BOOST_CHECK_CLOSE(a, 42 * sum, 1e-8);\n    });\n}\n\n#if BOOST_VERSION >= 105000\n// Boost upto v1.49 segfaults on this test\nBOOST_AUTO_TEST_CASE(two_stencils)\n{\n    const size_t n = 32;\n    std::vector<double> s(5, 1);\n    vex::stencil<double> S(ctx, s, 3);\n    vex::vector<double> X(ctx, n);\n    vex::vector<double> Y(ctx, n);\n\n    X = 0;\n    Y = X * S + X * S;\n\n    BOOST_CHECK(Y[ 0] == 0);\n    BOOST_CHECK(Y[16] == 0);\n    BOOST_CHECK(Y[31] == 0);\n}\n#endif\n\nBOOST_AUTO_TEST_CASE(small_vector)\n{\n    const size_t n = 128;\n\n    std::vector<double> s = random_vector<double>(rand() % 64 + 1);\n\n    int center = rand() % s.size();\n\n    vex::stencil<double> S(ctx, s, center);\n\n    std::vector<double> x = random_vector<double>(n);\n\n    vex::vector<double> X(ctx, x);\n    vex::vector<double> Y(ctx, n);\n\n    Y = 1;\n    Y += X * S;\n\n    index idx(n);\n\n    check_sample(Y, [&](size_t i, double a) {\n        double sum = 1;\n        size_t j = 0;\n        int k = -center;\n        for(; j < s.size(); k++, j++)\n            sum += s[j] * x[idx(i, k)];\n        BOOST_CHECK_CLOSE(a, sum, 1e-8);\n    });\n}\n\nBOOST_AUTO_TEST_CASE(multivector)\n{\n    typedef std::array<double, 2> elem_t;\n    const size_t n = 1024;\n\n    std::vector<double> s = random_vector<double>(rand() % 64 + 1);\n    int center = rand() % s.size();\n\n    vex::stencil<double> S(ctx, s.begin(), s.end(), center);\n\n    std::vector<double> x = random_vector<double>(2 * n);\n\n    vex::multivector<double,2> X(ctx, x);\n    vex::multivector<double,2> Y(ctx, n);\n\n    Y = 1;\n    Y += X * S;\n\n    index idx(n);\n\n    check_sample(Y, [&](size_t i, elem_t a) {\n        double sum[2] = {1, 1};\n        size_t j = 0;\n        int k = -center;\n        for(; j < s.size(); k++, j++) {\n            sum[0] += s[j] * x[0 + idx(i, k)];\n            sum[1] += s[j] * x[n + idx(i, k)];\n        }\n\n        BOOST_CHECK_CLOSE(a[0], sum[0], 1e-8);\n        BOOST_CHECK_CLOSE(a[1], sum[1], 1e-8);\n    });\n\n    Y = 42 * (X * S);\n\n    check_sample(Y, [&](size_t i, elem_t a) {\n        double sum[2] = {0, 0};\n        size_t j = 0;\n        int k = -center;\n        for(; j < s.size(); k++, j++) {\n            sum[0] += s[j] * x[0 + idx(i, k)];\n            sum[1] += s[j] * x[n + idx(i, k)];\n        }\n\n        BOOST_CHECK_CLOSE(a[0], 42 * sum[0], 1e-8);\n        BOOST_CHECK_CLOSE(a[1], 42 * sum[1], 1e-8);\n    });\n}\n\nBOOST_AUTO_TEST_CASE(big_stencil)\n{\n    const size_t n = 1 << 16;\n\n    std::vector<double> s = random_vector<double>(2048);\n    int center = rand() % s.size();\n\n    vex::stencil<double> S(ctx, s, center);\n\n    std::vector<double> x = random_vector<double>(n);\n\n    vex::vector<double> X(ctx, x);\n    vex::vector<double> Y(ctx, n);\n\n    index idx(n);\n\n    Y = X * S;\n    check_sample(Y, [&](size_t i, double a) {\n        double sum = 0;\n        size_t j = 0;\n        int k = -center;\n        for(; j < s.size(); k++, j++)\n            sum += s[j] * x[idx(i, k)];\n        BOOST_CHECK_CLOSE(a, sum, 1e-8);\n    });\n}\n\nBOOST_AUTO_TEST_CASE(user_defined_stencil)\n{\n    const size_t n = 1024;\n\n    VEX_STENCIL_OPERATOR(oscillate,\n            double, 3, 1,  \"return sin(X[1] - X[0]) + sin(X[0] - X[-1]);\",\n            ctx);\n\n    std::vector<double> x = random_vector<double>(n);\n\n    vex::vector<double> X(ctx, x);\n    vex::vector<double> Y(ctx, n);\n\n    Y = oscillate(X);\n\n    index idx(n);\n\n    check_sample(Y, [&](size_t i, double a) {\n        size_t left  = idx(i, -1);\n        size_t right = idx(i, +1);\n        double s = sin(x[right] - x[i]) + sin(x[i] - x[left]);\n        BOOST_CHECK_CLOSE(a, s, 1e-8);\n    });\n\n#if BOOST_VERSION >= 105000\n    Y = 41 * oscillate(X) + oscillate(X);\n\n    check_sample(Y, [&](size_t i, double a) {\n        size_t left  = idx(i, -1);\n        size_t right = idx(i, +1);\n        double s = sin(x[right] - x[i]) + sin(x[i] - x[left]);\n        BOOST_CHECK_CLOSE(a, 42 * s, 1e-8);\n    });\n#endif\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "3ca296255d7c4b8d67f9550f25ad883a1a1b311f", "size": 5249, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "external_libraries/vexcl/tests/stencil.cpp", "max_stars_repo_name": "lkusch/Kratos", "max_stars_repo_head_hexsha": "e8072d8e24ab6f312765185b19d439f01ab7b27b", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": 778.0, "max_stars_repo_stars_event_min_datetime": "2017-01-27T16:29:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T03:01:51.000Z", "max_issues_repo_path": "external_libraries/vexcl/tests/stencil.cpp", "max_issues_repo_name": "lkusch/Kratos", "max_issues_repo_head_hexsha": "e8072d8e24ab6f312765185b19d439f01ab7b27b", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": 6634.0, "max_issues_repo_issues_event_min_datetime": "2017-01-15T22:56:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:03:36.000Z", "max_forks_repo_path": "external_libraries/vexcl/tests/stencil.cpp", "max_forks_repo_name": "lkusch/Kratos", "max_forks_repo_head_hexsha": "e8072d8e24ab6f312765185b19d439f01ab7b27b", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": 224.0, "max_forks_repo_forks_event_min_datetime": "2017-02-07T14:12:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-06T23:09:34.000Z", "avg_line_length": 23.7511312217, "max_line_length": 88, "alphanum_fraction": 0.5189559916, "num_tokens": 1682, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390746, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4545302465312556}}
{"text": "#include \"vi-map-helpers/vi-map-manipulation.h\"\n\n#include <Eigen/Dense>\n#include <aslam/common/memory.h>\n#include <maplab-common/accessors.h>\n#include <maplab-common/conversions.h>\n#include <maplab-common/pose_types.h>\n#include <maplab-common/progress-bar.h>\n#include <vi-map/vi-map.h>\n\nnamespace vi_map_helpers {\n\n    VIMapManipulation::VIMapManipulation(vi_map::VIMap* map)\n            : map_(*CHECK_NOTNULL(map)), geometry_(map_), queries_(map_) {}\n\n    void VIMapManipulation::rotate(const size_t dimension, const double degrees) {\n        pose::Transformation T_G_old_G_new(\n                Eigen::Vector3d(0, 0, 0),\n                Eigen::Quaterniond(\n                        Eigen::AngleAxisd(\n                                degrees * kDegToRad, Eigen::Vector3d::Unit(dimension)))\n                        .normalized());\n        vi_map::MissionBaseFrameIdList frames;\n        map_.getAllMissionBaseFrameIds(&frames);\n        for (const vi_map::MissionBaseFrameId& id : frames) {\n            vi_map::MissionBaseFrame& frame = map_.getMissionBaseFrame(id);\n            frame.set_T_G_M(T_G_old_G_new * frame.get_T_G_M());\n        }\n    }\n\n    void VIMapManipulation::alignToXYPlane(const vi_map::MissionId& mission_id) {\n        CHECK(map_.hasMission(mission_id));\n        // Let bv_M_z be the eigenvector of lowest eigenvalue of the vertex position\n        // covariance. We then first rotate along bv_G_R_A x bv_G_z (z unit vector)\n        // until bv_M_z x bv_G_z is minimized. We then rotate along the new bv_G_R_A\n        // until bv_M_z x bv_G_z is zero.\n        vi_map::MissionBaseFrame& base_frame =\n                map_.getMissionBaseFrameForMission(mission_id);\n        Eigen::Vector3d bv_M_z;\n        Eigen::Vector3d bv_G_R_A_normalized;\n        // bv_G_R_A x bv_G_z rotation\n        {\n            Eigen::Vector3d eigenvalues;\n            Eigen::Matrix3d eigenvectors;\n            geometry_.get_p_G_I_CovarianceEigenValuesAndVectorsAscending(\n                    mission_id, &eigenvalues, &eigenvectors);\n            bv_M_z = eigenvectors.col(0).normalized();\n            if (bv_M_z(2) < 0) {\n                bv_M_z *= -1.;\n            }\n            bv_G_R_A_normalized =\n                    geometry_.get_bv_G_root_average(mission_id).normalized();\n            // Angle to rotate along bv_G_R_A x bv_G_z = angle between bv_G_z and the\n            // projection of bv_M_z into the plane bv_G_R_A x bv_G_z.\n            // atan() intended, want range +- pi/2\n            const double pitch_angle_rad =\n                    atan(bv_M_z.head<2>().dot(bv_G_R_A_normalized.head<2>()) / bv_M_z(2));\n            const Eigen::Vector3d R_G_M_old_new =\n                    bv_G_R_A_normalized.cross(Eigen::Vector3d::UnitZ()).normalized() *\n                    pitch_angle_rad;\n            const pose::Quaternion q_G_M_old_new(R_G_M_old_new);\n            base_frame.set_T_G_M(\n                    pose::Transformation(q_G_M_old_new, Eigen::Vector3d::Zero()) *\n                    base_frame.get_T_G_M());\n\n            bv_M_z = q_G_M_old_new.rotate(bv_M_z);\n        }\n        // bv_G_R_A rotation\n        {\n            const double roll_angle_rad = acos(bv_M_z(2));\n            bv_G_R_A_normalized(2) = 0;\n            bv_G_R_A_normalized.normalize();\n            const pose::Quaternion q_G_M_old_new(\n                    Eigen::Vector3d(bv_G_R_A_normalized * -roll_angle_rad));\n            base_frame.set_T_G_M(\n                    pose::Transformation(q_G_M_old_new, Eigen::Vector3d::Zero()) *\n                    base_frame.get_T_G_M());\n        }\n    }\n\n    void VIMapManipulation::getViwlsEdgesWithoutImuMeasurements(\n            const vi_map::MissionId& mission_id,\n            pose_graph::EdgeIdList* corrupt_edge_ids) const {\n        CHECK(map_.hasMission(mission_id));\n        CHECK_NOTNULL(corrupt_edge_ids)->clear();\n\n        pose_graph::EdgeIdList edge_ids;\n        map_.getAllEdgeIdsInMissionAlongGraph(\n                mission_id, pose_graph::Edge::EdgeType::kViwls, &edge_ids);\n\n        CHECK(!edge_ids.empty()) << \"No Viwls edges found in mission \"\n                                 << mission_id.hexString();\n\n        for (size_t i = 0; i < edge_ids.size(); ++i) {\n            const vi_map::ViwlsEdge& edge =\n                    map_.getEdgeAs<vi_map::ViwlsEdge>(edge_ids[i]);\n            if (edge.getImuData().size() == 0) {\n                corrupt_edge_ids->push_back(edge_ids[i]);\n\n                VLOG(2) << \"Found edge with no IMU data: \" << edge_ids[i].hexString();\n                VLOG(2) << \"Edge index within mission: \" << i;\n            }\n        }\n    }\n\n    void VIMapManipulation::fixViwlsEdgesWithoutImuMeasurements(\n            const vi_map::MissionId& mission_id) {\n        CHECK(map_.hasMission(mission_id));\n\n        pose_graph::EdgeIdList corrupt_edge_ids;\n        getViwlsEdgesWithoutImuMeasurements(mission_id, &corrupt_edge_ids);\n\n        if (corrupt_edge_ids.empty()) {\n            VLOG(2) << \"No corrupt edges found in mission: \" << mission_id.hexString();\n            return;\n        }\n        pose_graph::EdgeIdList all_edge_ids;\n        map_.getAllEdgeIdsInMissionAlongGraph(mission_id, &all_edge_ids);\n        CHECK_LT(corrupt_edge_ids.size(), all_edge_ids.size()) << \"All Viwls edges \"\n                                                               << \"are corrupt.\";\n\n        for (const pose_graph::EdgeId& edge_id : corrupt_edge_ids) {\n            VLOG(2) << \"Fixing edge \" << edge_id;\n            const vi_map::ViwlsEdge& current_edge =\n                    map_.getEdgeAs<vi_map::ViwlsEdge>(edge_id);\n\n            pose_graph::EdgeId new_edge_id;\n            common::generateId(&new_edge_id);\n\n            Eigen::Matrix<int64_t, 1, Eigen::Dynamic> new_imu_timestamps;\n            Eigen::Matrix<double, 6, Eigen::Dynamic> new_imu_data;\n\n            const pose_graph::VertexId& vertex_from = current_edge.from();\n            const pose_graph::VertexId& vertex_to = current_edge.to();\n\n            pose_graph::EdgeIdSet incoming_edges_from;\n            map_.getVertex(vertex_from).getIncomingEdges(&incoming_edges_from);\n\n            // Get the IMU measurements from the previous edge.\n            Eigen::Matrix<int64_t, 1, Eigen::Dynamic> imu_timestamps_from;\n            Eigen::Matrix<double, 6, Eigen::Dynamic> imu_data_from;\n            for (const pose_graph::EdgeId& incoming_edge_id : incoming_edges_from) {\n                if (map_.getEdgeType(incoming_edge_id) ==\n                    pose_graph::Edge::EdgeType::kViwls) {\n                    const vi_map::ViwlsEdge& incoming_edge =\n                            map_.getEdgeAs<vi_map::ViwlsEdge>(incoming_edge_id);\n\n                    imu_timestamps_from = incoming_edge.getImuTimestamps();\n                    imu_data_from = incoming_edge.getImuData();\n                    break;\n                }\n            }\n\n            // Add the last IMU measurement from the previous edge.\n            if (imu_timestamps_from.cols() > 0u) {\n                new_imu_timestamps.conservativeResize(\n                        Eigen::NoChange, new_imu_timestamps.cols() + 1);\n                new_imu_timestamps.col(new_imu_timestamps.cols() - 1) =\n                        imu_timestamps_from.rightCols(1);\n                new_imu_data.conservativeResize(Eigen::NoChange, new_imu_data.cols() + 1);\n                new_imu_data.col(new_imu_data.cols() - 1) = imu_data_from.rightCols(1);\n            } else {\n                // Since corrupt edges are in graph traversal order, if the previous\n                // edge is corrupt it must be the first edge (otherwise it already\n                // crashed), so we need to remove the first vertex in the mission\n                // (vertex_from) and make vertex_to the new root vertex for the mission.\n                map_.removeVertex(vertex_from);\n                vi_map::VIMission& mission = map_.getMission(mission_id);\n                mission.setRootVertexId(vertex_to);\n                map_.removeEdge(edge_id);\n                continue;\n            }\n\n            pose_graph::EdgeIdSet outgoing_edges_to;\n            map_.getVertex(vertex_to).getOutgoingEdges(&outgoing_edges_to);\n\n            // Get the IMU measurements from the following edge.\n            Eigen::Matrix<int64_t, 1, Eigen::Dynamic> imu_timestamps_to;\n            Eigen::Matrix<double, 6, Eigen::Dynamic> imu_data_to;\n            for (const pose_graph::EdgeId& outgoing_edge_id : outgoing_edges_to) {\n                if (map_.getEdgeType(outgoing_edge_id) ==\n                    pose_graph::Edge::EdgeType::kViwls) {\n                    const vi_map::ViwlsEdge& outgoing_edge =\n                            map_.getEdgeAs<vi_map::ViwlsEdge>(outgoing_edge_id);\n\n                    imu_timestamps_to = outgoing_edge.getImuTimestamps();\n                    imu_data_to = outgoing_edge.getImuData();\n                    break;\n                }\n            }\n            if (imu_timestamps_to.cols() > 0u) {\n                constexpr unsigned int kNumInterpolationTerms = 3u;\n                new_imu_timestamps.conservativeResize(\n                        Eigen::NoChange,\n                        new_imu_timestamps.cols() + kNumInterpolationTerms + 1);\n                new_imu_data.conservativeResize(\n                        Eigen::NoChange, new_imu_data.cols() + kNumInterpolationTerms + 1);\n                // Add interpolation terms for stability.\n                Eigen::Matrix<int64_t, 1, Eigen::Dynamic> imu_timestamps_interp_step =\n                        (imu_timestamps_to.leftCols(1) - imu_timestamps_from.rightCols(1)) /\n                        (kNumInterpolationTerms + 1);\n                Eigen::Matrix<double, 6, Eigen::Dynamic> imu_data_interp_step =\n                        (imu_data_to.leftCols(1) + imu_data_from.rightCols(1)) /\n                        (kNumInterpolationTerms + 1);\n                for (unsigned int i = 0u; i < kNumInterpolationTerms; ++i) {\n                    const unsigned int index =\n                            new_imu_timestamps.cols() - kNumInterpolationTerms - 1 + i;\n                    new_imu_timestamps.col(index) =\n                            new_imu_timestamps.col(index - 1) + imu_timestamps_interp_step;\n                    new_imu_data.col(index) =\n                            new_imu_data.col(index - 1) + imu_data_interp_step;\n                }\n                // Add the first IMU measurement from the following edge.\n                new_imu_timestamps.col(new_imu_timestamps.cols() - 1) =\n                        imu_timestamps_to.leftCols(1);\n                new_imu_data.col(new_imu_data.cols() - 1) = imu_data_to.leftCols(1);\n            } else {\n                const bool kIsVertexToLastVertexInMission = outgoing_edges_to.size() == 0;\n                CHECK(kIsVertexToLastVertexInMission) << \"Consecutive corrupt edges.\";\n                // The corrupt edge is the last edge, so it can be safely removed along\n                // with the last vertex.\n                map_.removeEdge(edge_id);\n                map_.removeVertex(vertex_to);\n                continue;\n            }\n\n            VLOG(3) << \"Adding the following IMU timestamps: \" << new_imu_timestamps;\n            VLOG(3) << \"Adding the following IMU data: \" << new_imu_data;\n            vi_map::Edge* new_edge_ptr(\n                    new vi_map::ViwlsEdge(\n                            new_edge_id, vertex_from, vertex_to, new_imu_timestamps,\n                            new_imu_data));\n\n            // Align the vertex_from and vertex_to to avoid overextending the edge.\n            map_.getVertexPtr(vertex_to)->set_T_M_I(\n                    map_.getVertex(vertex_from).get_T_M_I());\n\n            map_.removeEdge(edge_id);\n            map_.addEdge(vi_map::Edge::UniquePtr(new_edge_ptr));\n        }\n    }\n\n    void VIMapManipulation::removePosegraphAfter(\n            const pose_graph::VertexId& vertex_id,\n            pose_graph::VertexIdList* removed_vertex_ids) {\n        CHECK_NOTNULL(removed_vertex_ids)->clear();\n        CHECK(vertex_id.isValid());\n\n        constexpr bool kIncludeStartingVertex = false;\n        queries_.getFollowingVertexIdsAlongGraph(\n                vertex_id, kIncludeStartingVertex, removed_vertex_ids);\n\n        removeVerticesAndIncomingEdges(*removed_vertex_ids);\n    }\n\n    void VIMapManipulation::removeVerticesAndIncomingEdges(\n            const pose_graph::VertexIdList& vertex_ids) {\n        // Get all edges to delete.\n        pose_graph::EdgeIdSet edges_to_remove;\n        for (const pose_graph::VertexId& vertex_id : vertex_ids) {\n            const vi_map::Vertex& vertex = map_.getVertex(vertex_id);\n\n            pose_graph::EdgeIdSet incoming_edges;\n            vertex.getIncomingEdges(&incoming_edges);\n            edges_to_remove.insert(incoming_edges.begin(), incoming_edges.end());\n        }\n\n        // Remove the elements from the map.\n        for (const pose_graph::EdgeId& edge_id : edges_to_remove) {\n            map_.removeEdge(edge_id);\n        }\n\n        for (const pose_graph::VertexId& vertex_id : vertex_ids) {\n            map_.removeVertex(vertex_id);\n        }\n    }\n//\u521d\u59cb\u5316\u4efb\u52a1\u4e2d\u6ca1\u6709\u88ab\u7528\u5230\u7684\u7279\u5f81\u70b9\n    size_t VIMapManipulation::initializeLandmarksFromUnusedFeatureTracksOfMission(\n            const vi_map::MissionId& mission_id)\n    {\n        CHECK(mission_id.isValid());\n        pose_graph::VertexIdList all_vertices_in_missions;\n        map_.getAllVertexIdsInMissionAlongGraph(//\u901a\u8fc7\u8fd9\u4e2a\u4efb\u52a1\u7684\u56fe\u7ed3\u6784\u627e\u5230\u6240\u6709\u7684\u8282\u70b9\u7684\u96c6\u5408all_vertices_in_missions\n                mission_id, &all_vertices_in_missions);\n//\u6bcf\u4e2a\u8282\u70b9\u5b58\u7684\u5c31\u662f\u6bcf\u4e2a\u65f6\u523b\u7684\u4f4d\u59ff\uff0c\u5173\u952e\u70b9\uff0c\u6240\u4ee5\u6839\u8282\u70b9\u5e94\u8be5\u5c31\u662f\u7b2c\u4e00\u5e27\n        TrackIndexToLandmarkIdMap track_id_to_landmark_id;//std::unordered_map<int, vi_map::LandmarkId>,\u5e94\u8be5\u662f\u4e00\u4e2a\u8282\u70b9\u5bf9\u5e94\u7740\u591a\u4e2a\u5730\u56fe\u70b9\n        track_id_to_landmark_id.reserve(1000u * all_vertices_in_missions.size());\n        const size_t num_landmarks_initial = map_.numLandmarks();//\u901a\u8fc7\u904d\u5386\u8fd9\u4e2a\u5730\u56fe\u4e0b\u6240\u6709\u7684\u8282\u70b9\uff0c\u6bcf\u4e2a\u8282\u70b9\u90fd\u5b58\u50a8\u4e86\u5730\u56fe\u70b9\uff0c\u6240\u4ee5\u628a\u6240\u6709\u8282\u70b9\u7684\u5730\u56fe\u70b9\u7684\u6570\u91cf\u76f8\u52a0\n        initializeLandmarksFromUnusedFeatureTracksOfOrderedVertices(\n                all_vertices_in_missions, &track_id_to_landmark_id);//all_vertices_in_missions\u5df2\u7ecf\u6709\u4e86\u6240\u6709\u7684\u8282\u70b9\u4e86\n\n        const size_t num_new_landmarks = map_.numLandmarks() - num_landmarks_initial;//\u66f4\u65b0\u540e\u589e\u52a0\u7684\u5730\u56fe\u70b9\u5c31\u662f\u65b0\u7684\u5730\u56fe\u70b9\n        return num_new_landmarks;\n    }\n//\u521d\u59cb\u5316\u8282\u70b9\u4e2d\u6ca1\u6709\u88ab\u7528\u5230\u7684\u7279\u5f81\u70b9,\u662f\u901a\u8fc7\u904d\u5386\u6bcf\u4e00\u4e2a\u8282\u70b9\u53bb\u66f4\u65b0\u5730\u56fe\u70b9\u7684\u4fe1\u606f\n    void VIMapManipulation::\n    initializeLandmarksFromUnusedFeatureTracksOfOrderedVertices(\n            const pose_graph::VertexIdList& ordered_vertex_ids,\n            TrackIndexToLandmarkIdMap* trackid_landmarkid_map) {\n        for (const pose_graph::VertexId& vertex_id : ordered_vertex_ids) {//\u904d\u5386\u6240\u6709\u7684\u8282\u70b9\n            initializeLandmarksFromUnusedFeatureTracksOfVertex(\n                    vertex_id, trackid_landmarkid_map);\n        }\n    }\n\n    void VIMapManipulation::initializeLandmarksFromUnusedFeatureTracksOfVertex(\n            const pose_graph::VertexId& vertex_id,\n            TrackIndexToLandmarkIdMap* trackid_landmarkid_map) {\n        CHECK_NOTNULL(trackid_landmarkid_map);\n        const vi_map::Vertex& vertex = map_.getVertex(vertex_id);//\u5f97\u5230\u5f53\u524d\u8282\u70b9\n\n        vertex.forEachFrame(//\u8fd9\u91cc\u6211\u611f\u89c9\u662f\u591a\u76f8\u673a\u7684\u610f\u601d\u4e48\uff0c\u904d\u5386\u6bcf\u4e00\u4e2a\u76f8\u673a\uff0c\u904d\u5386\u6240\u6709\u7684\u7279\u5f81\u70b9\uff0c\u5982\u679c\u4e4b\u524d\u6ca1\u6709\u89c2\u5bdf\u5230\uff0c\u5219\u6dfb\u52a0\u4e00\u4e2a\u65b0\u7684\u5730\u6807\uff0c\u5426\u5219\u66f4\u65b0\u5730\u56fe\u70b9\u548c\u8282\u70b9\u7684\u89c2\u6d4b\u4fe1\u606f\n                [this, &vertex, &trackid_landmarkid_map](\n                        const size_t frame_index, const aslam::VisualFrame& frame)\n                {\n                    const size_t num_keypoints = frame.getNumKeypointMeasurements();\n                    if (!frame.hasTrackIds()) {\n                        VLOG(3) << \"Frame has no tracking information. Skipping frame...\";\n                        return;\n                    }\n                    const Eigen::VectorXi& track_ids = frame.getTrackIds();\n\n                    CHECK_EQ(static_cast<int>(num_keypoints), track_ids.rows());//\u4e00\u884c\u5c31\u662f\u4e00\u4e2a\u7279\u5f81\u70b9\n\n                    vi_map::LandmarkIdList landmark_ids;\n                    vertex.getFrameObservedLandmarkIds(frame_index, &landmark_ids);//\u5f97\u5230\u5f53\u524d\u8282\u70b9\u7684\u8fd9\u4e2a\u76f8\u673a\u7684\u6240\u6709\u89c2\u6d4b\u70b9\n\n                    ///\u904d\u5386\u6b64\u5e27\u7684\u6240\u6709\u8f68\u8ff9\uff0c\u5982\u679c\u4e4b\u524d\u6ca1\u6709\u89c2\u5bdf\u5230\uff0c\u5219\u6dfb\u52a0\u4e00\u4e2a\u65b0\u7684\u5730\u6807\uff0c\u5426\u5219\u6dfb\u52a0\u4e00\u4e2a\u89c2\u5bdf\u53cd\u5411\u94fe\u63a5\u3002\n                    // Go over all tracks of this frame and add a new landmark if it wasn't\n                    // observed before, otherwise add an observation backlink.\n                    for (size_t keypoint_i = 0u; keypoint_i < num_keypoints; ++keypoint_i) {\n                        const int track_id = track_ids(keypoint_i);\n\n                        // Skip non-tracked landmark observation.\n                        if (track_id < 0 || landmark_ids[keypoint_i].isValid()) {\n                            continue;\n                        }\n\n                        // Check whether this track has already a global landmark id\n                        // associated.\n                        const vi_map::LandmarkId* landmark_id_ptr =\n                                common::getValuePtr(*trackid_landmarkid_map, track_id);\n//\u662f\u80fd\u89c2\u6d4b\u5230\u8fd9\u4e2a\u5168\u5c40\u7684\u5730\u56fe\u70b9\u88ab\u8054\u7cfb\u4e0a\u4e86\uff0c\u9700\u8981\u66f4\u65b0\u8fd9\u4e2a\u8282\u70b9\u89c2\u6d4b\u52303d\u7684\u4fe1\u606f\uff0c\u4ee5\u53ca\u8fd9\u4e2a\u8def\u6807\u70b9\u88ab\u89c2\u6d4b\u5230\u7684\u4fe1\u606f\n                        if (landmark_id_ptr != nullptr &&\n                            map_.hasLandmark(*landmark_id_ptr))\n                        {\n                            map_.associateKeypointWithExistingLandmark(\n                                    vertex.id(), frame_index, keypoint_i, *landmark_id_ptr);\n                        } else {\n                            // Assign a new global landmark id to this track if it hasn't\n                            // been seen before and add a new landmark to the map.\n                            vi_map::LandmarkId landmark_id =//\u65b0\u5efa\u4e00\u4e2a\u8def\u6807\u70b9\u7684id\n                                    common::createRandomId<vi_map::LandmarkId>();\n                            // operator[] intended as this is either overwriting an old outdated\n                            // entry or creating a new one.\n                            (*trackid_landmarkid_map)[track_id] = landmark_id;//\u9700\u8981\u5bf9\u8fd9\u4e2a\u8282\u70b9\u8ffd\u8e2a\u52303d\u70b9\u7684\u4fe1\u606f\u8fdb\u884c\u66f4\u65b0\n\n                            vi_map::KeypointIdentifier keypoint_id;//KeypointIdentifier\u662f\u8def\u6807\u70b9\u7684\u4e00\u4e2a\u6570\u636e\u7ed3\u6784\n                            keypoint_id.frame_id.frame_index = frame_index;\n                            keypoint_id.frame_id.vertex_id = vertex.id();\n                            keypoint_id.keypoint_index = keypoint_i;\n                            map_.addNewLandmark(landmark_id, keypoint_id);//\u5728\u5730\u56fe\u4e2d\u52a0\u5165\u4e00\u4e2a\u65b0\u7684\u5730\u56fe\u70b9\uff0c\u5e76\u4e14\u4f1a\u53bb\u66f4\u65b0\u5730\u56fe\u70b9\u76f8\u5173\u8054\u7684\u4e00\u4e9b\u5176\u4ed6\u6570\u636e\n                        }\n                    }\n                });\n    }\n\n    size_t VIMapManipulation::mergeLandmarksBasedOnTrackIds(\n            const vi_map::MissionId& mission_id) {\n        CHECK(map_.hasMission(mission_id));\n        typedef std::unordered_map<int, vi_map::LandmarkId>\n                TrackIdToLandmarkIdMap;\n        TrackIdToLandmarkIdMap track_id_to_store_landmark_id;\n        size_t num_merges = 0u;\n\n        pose_graph::VertexIdList vertex_ids;\n        map_.getAllVertexIdsInMission(mission_id, &vertex_ids);\n\n        for (const pose_graph::VertexId& vertex_id : vertex_ids) {\n            const vi_map::Vertex& vertex = map_.getVertex(vertex_id);\n\n            for (size_t frame_idx = 0u; frame_idx < vertex.numFrames(); ++frame_idx) {\n                vi_map::LandmarkIdList landmark_ids;\n                vertex.getFrameObservedLandmarkIds(frame_idx, &landmark_ids);\n\n                CHECK(vertex.getVisualFrame(frame_idx).hasTrackIds());\n                const Eigen::VectorXi& track_ids =\n                        vertex.getVisualFrame(frame_idx).getTrackIds();\n                CHECK_EQ(\n                        static_cast<size_t>(track_ids.rows()), landmark_ids.size());\n\n                for (size_t keypoint_idx = 0u; keypoint_idx < landmark_ids.size();\n                     ++keypoint_idx) {\n                    if (landmark_ids[keypoint_idx].isValid() &&\n                        track_ids(keypoint_idx) < 0) {\n                        const vi_map::LandmarkId landmark_id = landmark_ids[keypoint_idx];\n                        CHECK(map_.hasLandmark(landmark_id));\n\n                        if (track_id_to_store_landmark_id\n                                .emplace(track_ids(keypoint_idx), landmark_id).second) {\n                            // Emplace succeeded so this track ID was not used before.\n                        } else {\n                            // Emplace failed so this track ID is already used, we need to\n                            // merge landmarks.\n                            TrackIdToLandmarkIdMap::const_iterator it =\n                                    track_id_to_store_landmark_id.find(track_ids(keypoint_idx));\n                            CHECK(it != track_id_to_store_landmark_id.end());\n                            CHECK(it->second.isValid());\n                            CHECK(map_.hasLandmark(it->second)) << \"Landmark \"\n                                                                << it->second.hexString()\n                                                                << \" not found in the map.\";\n\n                            if (it->second != landmark_id) {\n                                map_.mergeLandmarks(landmark_id, it->second);\n                                ++num_merges;\n\n                                // As the dataset could be loop-closed before (so more than\n                                // a single track id pointing to the same store landmark, we need\n                                // to update the track id to store landmark id map.\n                                for (TrackIdToLandmarkIdMap::value_type& track_id_to_landmark :\n                                        track_id_to_store_landmark_id) {\n                                    if (track_id_to_landmark.second == landmark_id) {\n                                        track_id_to_landmark.second = it->second;\n                                    }\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n        }\n        VLOG(2) << \"Number of merges \" << num_merges;\n        return num_merges;\n    }\n\n    void VIMapManipulation::releaseOldVisualFrameImages(\n            const pose_graph::VertexId& current_vertex_id,\n            const int image_removal_age_threshold) {\n        CHECK_GT(image_removal_age_threshold, 0);\n        CHECK(map_.hasVertex(current_vertex_id));\n\n        const vi_map::MissionId& mission_id =\n                map_.getVertex(current_vertex_id).getMissionId();\n\n        pose_graph::VertexId vertex_id = current_vertex_id;\n        for (int i = 0; i < image_removal_age_threshold; ++i) {\n            map_.getPreviousVertex(\n                    vertex_id, map_.getGraphTraversalEdgeType(mission_id), &vertex_id);\n        }\n\n        while (map_.getPreviousVertex(\n                vertex_id, map_.getGraphTraversalEdgeType(mission_id), &vertex_id)) {\n            const vi_map::Vertex& vertex = map_.getVertex(vertex_id);\n            for (size_t i = 0; i < vertex.numFrames(); ++i) {\n                const aslam::VisualFrame& const_vframe = vertex.getVisualFrame(i);\n                if (const_vframe.isValid() && const_vframe.hasRawImage()) {\n                    aslam::VisualFrame::Ptr visual_frame =\n                            map_.getVertex(vertex_id).getVisualFrameShared(i);\n                    visual_frame->releaseRawImage();\n                    CHECK(!visual_frame->hasRawImage());\n                }\n            }\n        }\n    }\n\n    size_t VIMapManipulation::removeBadLandmarks() {\n        vi_map::LandmarkIdList bad_landmark_ids;\n        queries_.getAllNotWellConstrainedLandmarkIds(&bad_landmark_ids);\n\n        for (const vi_map::LandmarkId& bad_landmark_id : bad_landmark_ids) {\n            map_.removeLandmark(bad_landmark_id);\n        }\n        return bad_landmark_ids.size();\n    }\n\n\n}  // namespace vi_map_helpers\n", "meta": {"hexsha": "41cdaa41623a45976b5fac3acf1e500504156df3", "size": 23492, "ext": "cc", "lang": "C++", "max_stars_repo_path": "algorithms/vi-map-helpers/src/vi-map-manipulation.cc", "max_stars_repo_name": "eglrp/maplab-note", "max_stars_repo_head_hexsha": "4f4508d5cd36345c79dd38f6621a0a55aa5b0138", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-12-25T07:00:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T14:35:59.000Z", "max_issues_repo_path": "algorithms/vi-map-helpers/src/vi-map-manipulation.cc", "max_issues_repo_name": "eglrp/maplab-note", "max_issues_repo_head_hexsha": "4f4508d5cd36345c79dd38f6621a0a55aa5b0138", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "algorithms/vi-map-helpers/src/vi-map-manipulation.cc", "max_forks_repo_name": "eglrp/maplab-note", "max_forks_repo_head_hexsha": "4f4508d5cd36345c79dd38f6621a0a55aa5b0138", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-06-09T04:07:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-09T04:07:33.000Z", "avg_line_length": 49.1464435146, "max_line_length": 119, "alphanum_fraction": 0.5790907543, "num_tokens": 5393, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.45453024035001366}}
{"text": "<<<<<<< HEAD\n/*    Copyright (c) 2010-2018, Delft University of Technology\n=======\n/*    Copyright (c) 2010-2019, Delft University of Technology\n>>>>>>> origin/master\n *    All rigths reserved\n *\n *    This file is part of the Tudat. Redistribution and use in source and\n *    binary forms, with or without modification, are permitted exclusively\n *    under the terms of the Modified BSD license. You should have received\n *    a copy of the license with this file. If not, please or visit:\n *    http://tudat.tudelft.nl/LICENSE.\n */\n\n#define BOOST_TEST_MAIN\n\n#include <limits>\n#include <map>\n\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/unit_test.hpp>\n\n#include <Eigen/Core>\n\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/orbitalElementConversions.h\"\n#include \"Tudat/Basics/testMacros.h\"\n#include \"Tudat/Mathematics/BasicMathematics/basicMathematicsFunctions.h\"\n#include \"Tudat/Mathematics/BasicMathematics/mathematicalConstants.h\"\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/UnitTests/keplerPropagatorTestData.h\"\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/keplerPropagator.h\"\n#include \"Tudat/Astrodynamics/Ephemerides/keplerEphemeris.h\"\n#include \"Tudat/InputOutput/basicInputOutput.h\"\n\nnamespace tudat\n{\nnamespace unit_tests\n{\n\nBOOST_AUTO_TEST_SUITE( test_keplerEphemeris )\n\n//! Test 1: Comparison of KeplerEphemeris output with benchmark data from (Melman, 2010).\n//! (see testPropagateKeplerOrbit_Eccentric_Melman).\nBOOST_AUTO_TEST_CASE( testKeplerEphemerisElliptical )\n{\n    // Load the expected propagation history.\n    // Create expected propagation history.\n    PropagationHistory expectedPropagationHistory = getODTBXBenchmarkData( );\n\n    // Set Earth gravitational parameter [m^3 s^-2].\n    const double earthGravitationalParameter = 398600.4415e9;\n\n    // Compute propagation history.\n    PropagationHistory computedPropagationHistory;\n    computedPropagationHistory[ 0.0 ] = expectedPropagationHistory[ 0.0 ];\n\n    ephemerides::KeplerEphemeris keplerEphemeris(\n                expectedPropagationHistory[ 0.0 ],\n                0.0, earthGravitationalParameter );\n\n    for( PropagationHistory::iterator stateIterator = expectedPropagationHistory.begin( );\n         stateIterator != expectedPropagationHistory.end( ); stateIterator++ )\n    {\n        // Compute next entry.\n        computedPropagationHistory[ stateIterator->first ] =\n                orbital_element_conversions::convertCartesianToKeplerianElements(\n                    keplerEphemeris.getCartesianState( stateIterator->first ),\n                    earthGravitationalParameter );\n\n        // Check that computed results match expected results.\n        BOOST_CHECK_CLOSE_FRACTION(\n                    computedPropagationHistory[ stateIterator->first ]( 5 ),\n                    expectedPropagationHistory[ stateIterator->first ]( 5 ),\n                    2.5e-14 );\n    }\n}\n\n//! Test 2: Comparison of KeplerEphemeris with that of GTOP (hyperbolic).\n//! (see testPropagateKeplerOrbit_hyperbolic_GTOP).\nBOOST_AUTO_TEST_CASE( testKeplerEphemerisHyperbolic )\n{\n    // Load the expected propagation history.\n    PropagationHistory expectedPropagationHistory = getGTOPBenchmarkData( );\n\n    // Compute propagation history.\n    PropagationHistory computedPropagationHistory;\n    computedPropagationHistory[ 0.0 ] = expectedPropagationHistory[ 0.0 ];\n\n    ephemerides::KeplerEphemeris keplerEphemeris(\n                expectedPropagationHistory[ 0.0 ],\n                0.0, getGTOPGravitationalParameter( ) );\n\n    for( PropagationHistory::iterator stateIterator = expectedPropagationHistory.begin( );\n         stateIterator != expectedPropagationHistory.end( ); stateIterator++ )\n    {\n        // Compute next entry.\n        computedPropagationHistory[ stateIterator->first ] =\n                orbital_element_conversions::convertCartesianToKeplerianElements(\n                    keplerEphemeris.getCartesianState( stateIterator->first ),\n                    getGTOPGravitationalParameter( ) );\n\n        // Check that computed results match expected results.\n        BOOST_CHECK_CLOSE_FRACTION(\n                    computedPropagationHistory[ stateIterator->first ]( 5 ),\n                    expectedPropagationHistory[ stateIterator->first ]( 5 ),\n                    1.0e-15 );\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END( )\n\n} // namespace unit_tests\n\n} // namespace tudat\n\n", "meta": {"hexsha": "f31a71c98f1763c7808738183cecb1d714dc9900", "size": 4382, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/Ephemerides/UnitTests/unitTestKeplerEphemeris.cpp", "max_stars_repo_name": "ViktorJordanov/tudat", "max_stars_repo_head_hexsha": "069ceeab8f12405c356e19f50d6df037914df85c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tudat/Astrodynamics/Ephemerides/UnitTests/unitTestKeplerEphemeris.cpp", "max_issues_repo_name": "ViktorJordanov/tudat", "max_issues_repo_head_hexsha": "069ceeab8f12405c356e19f50d6df037914df85c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tudat/Astrodynamics/Ephemerides/UnitTests/unitTestKeplerEphemeris.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": 38.1043478261, "max_line_length": 90, "alphanum_fraction": 0.7161113647, "num_tokens": 1016, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.45453024035001366}}
{"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 \"toplevelfixture.hpp\"\n\n#include <qle/models/normalsabr.hpp>\n\n#include <boost/make_shared.hpp>\n#include <boost/test/unit_test.hpp>\n\nusing namespace QuantLib;\nusing namespace QuantExt;\nusing namespace boost::unit_test_framework;\n\nBOOST_FIXTURE_TEST_SUITE(QuantExtTestSuite, qle::test::TopLevelFixture)\n\nBOOST_AUTO_TEST_SUITE(NormalFreeBoundarySabrTest)\n\nBOOST_AUTO_TEST_CASE(testNormalFreeBoundarySabr) {\n\n    BOOST_TEST_MESSAGE(\"Testing normal free boundary SABR...\");\n\n    Real forward = 0.0, expiryTime = 5.0, alpha = 0.0050, nu = 0.52, rho = -0.23;\n\n    BOOST_TEST_MESSAGE(\"vol=\" << normalFreeBoundarySabrVolatility(0.0, forward, expiryTime, alpha, nu, rho));\n\n    // WIP...\n\n    // for (Real strike = -0.10; strike < 0.10 + 1E-5; strike += 0.0001) {\n    //     BOOST_TEST_MESSAGE(strike << \" \" << normalSabrVolatility(strike, forward, expiryTime, alpha, nu, rho) << \" \"\n    //                               << normalFreeBoundarySabrVolatility(strike, forward, expiryTime, alpha, nu, rho));\n    // }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "7a145d67b2b9c41761095cbb92442dda105022a0", "size": 1821, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QuantExt/test/normalfreeboundarysabr.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/test/normalfreeboundarysabr.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/test/normalfreeboundarysabr.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": 34.358490566, "max_line_length": 119, "alphanum_fraction": 0.7391543108, "num_tokens": 451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430645886584, "lm_q2_score": 0.546738151984614, "lm_q1q2_score": 0.4544176231680317}}
{"text": "#include \"stdafx.h\"\n#include <cmath>\n#include <vector>\n#include <stack>\n#include <unordered_map>\n#include <unordered_set>\n#include <iostream>\n#include <fmt/format.h>\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n#include \"contest_types.h\"\n#include \"solver_registry.h\"\n#include \"solver_util.h\"\n#include \"visual_editor.h\"\n#include \"timer.h\"\n#include \"judge.h\"\n\nnamespace NNaiveSearchSolver {\nnamespace bg = boost::geometry;\nusing BoostPoint = bg::model::d2::point_xy<double>;\nusing BoostPolygon = bg::model::polygon<BoostPoint>;\nusing BoostLinestring = bg::model::linestring<BoostPoint>;\n\ntemplate <typename T>\nvoid shrink(T& point_a, T& point_b) {\n  constexpr double eps = 1e-6;\n  auto shrink_a = point_a * (1.0 - eps) + point_b * eps;\n  auto shrink_b = point_b * (1.0 - eps) + point_a * eps;\n  point_a = shrink_a;\n  point_b = shrink_b;\n}\n\ntemplate <typename T>\nBoostPoint ToBoostPoint(const T& point) {\n  const auto [x, y] = point;\n  return BoostPoint(x, y);\n}\n\ntemplate <typename T>\nBoostPolygon ToBoostPolygon(const std::vector<T>& points) {\n  BoostPolygon polygon;\n  for (std::size_t i = 0; i <= points.size(); ++i) {\n    polygon.outer().push_back(ToBoostPoint(points[i % points.size()]));\n  }\n  if (bg::area(polygon) < 0.0) {\n    bg::reverse(polygon);\n  }\n  return polygon;\n}\n\nstd::vector<Point> enumerate_interior_points(const SProblem& problem) {\n  integer ymin = INT_MAX, ymax = INT_MIN;\n  integer xmin = INT_MAX, xmax = INT_MIN;\n  for (auto p : problem.hole_polygon) {\n    xmin = std::min(xmin, get_x(p));\n    ymin = std::min(ymin, get_y(p));\n    xmax = std::max(xmax, get_x(p));\n    ymax = std::max(ymax, get_y(p));\n  }\n\n#if 0\n  auto bg_hole_polygon = ToBoostPolygon(problem.hole_polygon);\n  std::vector<Point> points;\n  for (int y = ymin; y <= ymax; ++y) {\n    for (int x = xmin; x <= xmax; ++x) {\n      if (bg::within(ToBoostPoint(Point{x, y}), bg_hole_polygon)) { // exclude points on the edge/vertex of the hole.\n        points.emplace_back(x, y);\n      }\n    }\n  }\n#else\n  std::vector<Point> points;\n  for (int y = ymin; y <= ymax; ++y) {\n    for (int x = xmin; x <= xmax; ++x) {\n      if (contains(problem.hole_polygon, {x, y}) != EContains::EOUT) { // include points on the edge/vertex of the hole.\n        points.emplace_back(x, y);\n      }\n    }\n  }\n#endif\n  LOG(INFO) << fmt::format(\"found {} interior points\", points.size());\n  return points;\n}\n\nstd::vector<Point> enumerate_interior_border_points(const SProblem& problem, double border_distance) {\n  integer ymin = INT_MAX, ymax = INT_MIN;\n  integer xmin = INT_MAX, xmax = INT_MIN;\n  for (auto p : problem.hole_polygon) {\n    xmin = std::min(xmin, get_x(p));\n    ymin = std::min(ymin, get_y(p));\n    xmax = std::max(xmax, get_x(p));\n    ymax = std::max(ymax, get_y(p));\n  }\n\n  auto bg_hole_polygon = ToBoostPolygon(problem.hole_polygon);\n\n  std::vector<Point> points;\n  for (int y = ymin; y <= ymax; ++y) {\n    for (int x = xmin; x <= xmax; ++x) {\n      if (contains(problem.hole_polygon, {x, y}) != EContains::EOUT) { // include points on the edge/vertex of the hole.\n        // minimum distance to an edge.\n        double d = DBL_MAX;\n        for (int eid = 0; eid <= problem.hole_polygon.size(); ++eid) {\n          BoostLinestring linestring{ToBoostPoint(problem.hole_polygon[eid]), ToBoostPoint(problem.hole_polygon[(eid + 1) % problem.hole_polygon.size()])};\n          std::vector<BoostLinestring> differences;\n          chmin(d, bg::distance(linestring, ToBoostPoint(Point{x, y})));\n        }\n\n        if (d < border_distance) {\n          points.emplace_back(x, y);\n        }\n      }\n    }\n  }\n\n  LOG(INFO) << fmt::format(\"found {} border points\", points.size());\n  return points;\n}\n\nclass NaiveSearchSolver : public SolverBase {\nprivate:\n  std::mt19937 rng;\n\npublic:\n  NaiveSearchSolver() { }\n  SolverOutputs solve(const SolverArguments &args) override {\n    SolverOutputs ret;\n\n    // init.\n    ret.solution = args.optional_initial_solution ? args.optional_initial_solution : args.problem->create_solution();\n\n    // develop.\n    constexpr int check_timeout_every_iter = 100000;\n    constexpr int report_every_iter = 100000;\n    constexpr int editor_sleep = 1;\n    constexpr bool exhaustive_search = true;\n    constexpr bool use_cache_for_good_edge = true;\n    constexpr bool use_cache_for_movable_edges_with_tolerance = true;\n    constexpr bool use_cache_for_infeasible_placement_set = true;\n    constexpr size_t infeasible_placement_cache_size_B = 4 * 1024ull * 1024ull * 1024ull;\n    const std::optional<double> start_from_border_distance = 3.0;\n    const std::optional<int> subsample_roots = std::nullopt;\n    SVisualEditorPtr editor;\n    if (args.visualize) {\n      editor = std::make_shared<SVisualEditor>(args.problem, \"NaiveSearchSolver\", \"visualize\");\n    }\n\n    // prepare.\n    auto interior_points = enumerate_interior_points(*args.problem);\n    std::shuffle(interior_points.begin(), interior_points.end(), rng);\n    std::vector<Point> interior_border_points;\n    if (start_from_border_distance) {\n      LOG(INFO) << fmt::format(\"start from border r={}\", *start_from_border_distance);\n      interior_border_points = enumerate_interior_border_points(*args.problem, *start_from_border_distance);\n      std::shuffle(interior_border_points.begin(), interior_border_points.end(), rng);\n    }\n    const std::vector<std::vector<int>> edges_from_vertex_cache = edges_from_vertex(*args.problem);\n    const int V = args.problem->vertices.size();\n\n    // good edge. assume p and q are both interiors.\n    auto bg_hole_polygon = ToBoostPolygon(args.problem->hole_polygon);\n    auto _is_good_edge = [&](const Point& p, const Point& q) {\n      BoostLinestring linestring{ToBoostPoint(p), ToBoostPoint(q)};\n      std::vector<BoostLinestring> differences;\n      bg::difference(linestring, bg_hole_polygon, differences);\n      return differences.empty();\n    };\n    struct Line_hash {\n      std::size_t operator()(const Line& line) const {\n        return std::hash<int>()(line[0].first)\n             ^ std::hash<int>()(line[0].second)\n             ^ std::hash<int>()(line[1].first)\n             ^ std::hash<int>()(line[1].second)\n          ;\n      }\n    };\n    std::unordered_set<Line, Line_hash> is_bad_edge_cache; // assume |bad edges| < |good edges|\n    if (use_cache_for_good_edge) {\n      LOG(INFO) << \"bad_edge_cache ON: building\";\n      Timer t(\"build is_bad_edge_cache\");\n      const size_t N = interior_points.size();\n      size_t c = 0;\n      for (size_t i = 0; i < N; ++i) {\n        const auto& p = interior_points[i];\n        for (size_t j = i; j < N; ++j) {\n          const auto& q = interior_points[j];\n          if (!_is_good_edge(p, q)) {\n            is_bad_edge_cache.insert({p, q});\n            is_bad_edge_cache.insert({q, p});\n          }\n          ++c;\n          if (c % 100000 == 0) LOG(INFO) << fmt::format(\"{}/{} ({:.2f}%) bad_edges={}\", c, N * (N + 1) / 2, 100.0 * c / double(N * (N + 1) / 2), is_bad_edge_cache.size());\n        }\n      }\n      LOG(INFO) << fmt::format(\"is_bad_edge_cache #{}\", is_bad_edge_cache.size());\n    } else {\n      LOG(INFO) << \"bad_edge_cache OFF\";\n    }\n    auto is_good_edge = [&](const Point& p, const Point& q) -> bool {\n      if (!use_cache_for_good_edge)\n        return _is_good_edge(p, q);\n\n      auto it = is_bad_edge_cache.find({p, q});\n      return it == is_bad_edge_cache.end();\n    };\n\n    // (starting position, radius**2) -> (available points)\n    using SKey = std::pair<Point, int>;\n    struct SKey_hash {\n      std::size_t operator()(const SKey& key) const {\n        return std::hash<int>()(key.first.first)\n             ^ std::hash<int>()(key.first.second)\n             ^ std::hash<int>()(key.second)\n          ;\n      }\n    };\n    int64_t movable_cache_count = 0;\n    std::unordered_map<SKey, std::vector<Point>, SKey_hash> movable_cache;\n    // exact lookup.\n    auto get_movable_points = [&](Point p, int d2) -> std::vector<Point> {\n      const SKey query {p, d2};\n      auto it = movable_cache.find(query);\n      if (it != movable_cache.end()) {\n        return it->second;\n      }\n      std::vector<Point> points;\n      for (Point ip : interior_points) {\n        if (d2 == distance2(p, ip) && is_good_edge(p, ip)) {\n          ++movable_cache_count;\n          points.push_back(ip);\n        }\n      }\n      movable_cache.insert(it, {query, points});\n      return points;\n    };\n    // consider tolerance.\n    LOG(INFO) << (use_cache_for_movable_edges_with_tolerance ? \"movable_points_with_tolerance_cache ON\" : \"movable_points_with_tolerance_cache OFF\");\n    std::unordered_map<SKey, std::vector<Point>, SKey_hash> movable_points_with_tolerance_cache;\n    auto _get_movable_points_with_tolerance = [&](Point p, int original_distance2) -> std::vector<Point> {\n      // |d_new/d_old - 1| <= eps / 1000000\n      constexpr int k = 1'000'000;\n      const int e = args.problem->epsilon;\n      const int distance2_min = std::floor(original_distance2 * double(k - e) / double(k));\n      const int distance2_max = std::ceil(original_distance2 * double(k + e) / double(k));\n      std::vector<Point> all_points;\n      for (int d2 = distance2_min; d2 <= distance2_max; ++d2) {\n        if (std::abs(d2 - original_distance2) * k <= original_distance2 * e) { // to make sure.\n          auto points = get_movable_points(p, d2);\n          std::copy(points.begin(), points.end(), std::back_inserter(all_points));\n        }\n      }\n      return all_points;\n    };\n    auto get_movable_points_with_tolerance = [&](Point p, int original_distance2) -> std::vector<Point> {\n      if (!use_cache_for_movable_edges_with_tolerance)\n        return _get_movable_points_with_tolerance(p, original_distance2);\n\n      const SKey query {p, original_distance2};\n      auto it = movable_points_with_tolerance_cache.find(query);\n      if (it != movable_points_with_tolerance_cache.end()) {\n        return it->second;\n      }\n      auto all_points = _get_movable_points_with_tolerance(p, original_distance2);\n      movable_points_with_tolerance_cache.insert(it, {query, all_points});\n      return all_points;\n    };\n\n    constexpr int USED = 1;\n    constexpr int REMAINING = 0;\n    struct State;\n    using StatePtr = std::shared_ptr<State>;\n    struct State {\n      // placing vertices[vid] to position p.\n      int depth = 0;\n      int vid = 0;\n      Point p = {0, 0};\n      // remaining indices after placing this node.\n      std::vector<int> indices_flag;\n      // vertices after placing this node.\n      std::vector<Point> vertices;\n      StatePtr parent;\n      bool is_last = false;\n\n      State(int depth, int vid, Point p, const std::vector<int>& indices_flag, const std::vector<Point>& vertices)\n        : depth(depth), vid(vid), p(p), indices_flag(indices_flag), vertices(vertices) {}\n    };\n    auto create_fixed_indices = [&](StatePtr s) {\n      std::vector<int> fixed_indices;\n      for (int i = 0; i < V; ++i) {\n        if (s->indices_flag[i] == USED) {\n          fixed_indices.push_back(i);\n        }\n      }\n      return fixed_indices;\n    };\n\n    // infeasible placement cache\n    int min_x = std::numeric_limits<int>::max();\n    int min_y = std::numeric_limits<int>::max();\n    int max_x = std::numeric_limits<int>::min();\n    int max_y = std::numeric_limits<int>::min();\n    for (auto& p : interior_points) {\n      chmin<int>(min_x, p.first);\n      chmax<int>(max_x, p.first);\n      chmin<int>(min_y, p.second);\n      chmax<int>(max_y, p.second);\n    }\n    const int size_x = max_x - min_x + 1;\n    const int size_y = max_y - min_y + 1;\n    const int key_size = V * size_x * size_y;\n    SZobristHash zobrist(key_size);\n    const size_t infeasible_placement_cache_size = infeasible_placement_cache_size_B * 8;\n    std::vector<bool> infeasible_placement_cache;\n    if (use_cache_for_infeasible_placement_set) {\n      LOG(INFO) << fmt::format(\"use_cache_for_infeasible_placement_set ON {:.2f} MB (smaller cache leads to increasing FP) {}x{}x{}\", infeasible_placement_cache_size_B / 1024.0 / 1024.0, size_x, size_y, V);\n      infeasible_placement_cache.assign(infeasible_placement_cache_size, false);\n    } else {\n      LOG(INFO) << \"use_cache_for_infeasible_placement_set OFF\";\n    }\n    auto State_to_zobrist = [&](StatePtr s) {\n      SZobristHash::key_t hash = 0;\n      for (int i = 0; i < V; ++i) {\n        if (s->indices_flag[i] == USED) {\n          const int dx = s->vertices[i].first - min_x;\n          const int dy = s->vertices[i].second - min_y;\n          const int idx = (i * size_y + dy) * size_x + dx;\n          //CHECK(idx < key_size);\n          hash ^= zobrist[idx];\n        }\n      }\n      return hash;\n    };\n    size_t infeasible_cache_hit_count = 0;\n    size_t infeasible_cache_query_count = 0;\n    size_t infeasible_cache_set_count = 0;\n    auto is_infeasible_placement = [&](StatePtr s) {\n      const bool infeasible = infeasible_placement_cache[State_to_zobrist(s) % infeasible_placement_cache_size];\n      ++infeasible_cache_query_count;\n      if (infeasible) ++infeasible_cache_hit_count;\n      return infeasible;\n    };\n    auto set_infeasible_placement = [&](StatePtr s) {\n      ++infeasible_cache_set_count;\n      infeasible_placement_cache[State_to_zobrist(s) % infeasible_placement_cache_size] = true;\n    };\n\n    std::stack<StatePtr> stack;\n    // start from any valid points.\n    {\n      const int start_index = 0;\n      std::vector<int> indices_flag(V, REMAINING);\n      indices_flag[start_index] = USED;\n      for (auto ip : start_from_border_distance ? interior_border_points : interior_points) {\n        auto vertices = ret.solution->vertices;\n        vertices[start_index] = ip;\n        stack.push(std::make_shared<State>(1 /* depth */, start_index, ip, indices_flag, vertices));\n      }\n    }\n\n    const int n_roots = stack.size();\n    integer best_dislikes = std::numeric_limits<integer>::max();\n    bool found = false;\n    int64_t root_counter = 0;\n    int64_t counter = 0;\n    int max_depth = 1;\n    Timer timer;\n    double lazy_elapsed_ms = 0.0; // not always updated.\n    if (args.timeout_s) {\n      LOG(WARNING) << fmt::format(\"Timeout : {} s\", *args.timeout_s);\n    }\n    if (subsample_roots) {\n      LOG(WARNING) << fmt::format(\"SUBSAMPLING : {}\", *subsample_roots);\n    }\n\n    while (!stack.empty()) {\n      if (!exhaustive_search && found) {\n        break;\n      }\n      StatePtr s = stack.top(); stack.pop();\n\n      if (s->depth == 1) {\n        ++root_counter;\n        if (subsample_roots && root_counter > *subsample_roots) {\n          LOG(ERROR) << fmt::format(\"SUBSAMPLING DONE! {}\", root_counter);\n          break;\n        }\n      }\n      ++counter;\n      max_depth = std::max(max_depth, s->depth);\n      bool report = (counter % report_every_iter == 0);\n\n      if (counter % check_timeout_every_iter == 0 && args.timeout_s) {\n        lazy_elapsed_ms = timer.elapsed_ms();\n        if (lazy_elapsed_ms * 1e-3 > *args.timeout_s) {\n          LOG(ERROR) << fmt::format(\"TIMEOUT! {} / {} s\", lazy_elapsed_ms * 1e-3, *args.timeout_s);\n          break;\n        }\n      }\n\n      if (s->depth == V) {\n        auto temp_solution = args.problem->create_solution(s->vertices);\n        auto judge_res = judge(*args.problem, *temp_solution);\n        if (judge_res.is_valid()) { // essentially, we do not need this. but for sure..\n          if (judge_res.dislikes < best_dislikes) {\n            LOG(INFO) << fmt::format(\"#{} foud better solution {} -> {}\", root_counter, best_dislikes, judge_res.dislikes);\n            ret.solution = temp_solution;\n            best_dislikes = judge_res.dislikes;\n            const std::string filename = args.problem->problem_id ? fmt::format(\"{}.bestsofar.pose.json\", *args.problem->problem_id) : \"bestsofar.pose.json\";\n            save_solution(args.problem, ret.solution, \"NaiveSearchSolver\", filename);\n          }\n          found = true;\n          report = true;\n        } else {\n          if (false) { // debug.\n            auto p = s;\n            while (p) {\n              LOG(INFO) << p->vid;\n              p = p->parent;\n            }\n            if (editor) {\n              editor->set_oneshot_custom_stat(\"#invalid\");\n              editor->set_marked_indices(create_fixed_indices(s));\n              editor->set_pose(args.problem->create_solution(s->vertices));\n              while (editor->show(editor_sleep) != 27)\n                ;\n            }\n          }\n        }\n      }\n\n      if (report) {\n        lazy_elapsed_ms = timer.elapsed_ms();\n        const double root_per_s = root_counter / lazy_elapsed_ms * 1e3;\n        const auto stat = fmt::format(\"[{}][{}][best DL={}] root {}/{}({:.2f}%) {:.2f} root/s, ETA {:.2f} s, visited {}, max depth {}, {:.2f} ms, {:.2f} node/s, cache {:.2f} MB, infi {}/{}({:.2f}%)/{}({:.2f}%)\",\n          args.problem->problem_id ? *args.problem->problem_id : -1, \n          found ? \"O\" : \"X\", found ? best_dislikes : -1,\n          root_counter, interior_points.size(), 100.0 * root_counter / interior_points.size(), root_per_s,\n          double(n_roots) / root_per_s,\n          counter, max_depth, lazy_elapsed_ms, counter / lazy_elapsed_ms * 1e3,\n          movable_cache_count * sizeof(Point) / 1024.0 / 1024.0,\n          infeasible_cache_hit_count, infeasible_cache_query_count, 100.0 * infeasible_cache_hit_count / infeasible_cache_query_count,\n          infeasible_cache_set_count, 100.0 * infeasible_cache_hit_count / infeasible_cache_set_count\n          );\n        LOG(INFO) << stat;\n        if (editor) {\n          editor->set_oneshot_custom_stat(stat);\n          editor->set_marked_indices(create_fixed_indices(s));\n          editor->set_pose(args.problem->create_solution(s->vertices));\n          editor->show(editor_sleep);\n        }\n      }\n\n      // first enumerate remaining edge ..\n      struct SEdgeItem {\n        int num_undetermined_edges = 0;\n        int eid = -1;\n        // smaller is better.\n        bool operator<(const SEdgeItem& rhs) const {\n          return num_undetermined_edges != rhs.num_undetermined_edges\n            ? num_undetermined_edges > rhs.num_undetermined_edges\n            : eid < rhs.eid;\n        }\n      };\n      std::vector<SEdgeItem> remaining_edges;\n      for (int eid : edges_from_vertex_cache[s->vid]) {\n        auto [u, v] = args.problem->edges[eid];\n        auto counter_vid = u == s->vid ? v : u;\n\n        if (s->indices_flag[counter_vid] == REMAINING) {\n          // count number of determined and undetermined edges.\n          int num_determined_edges = 0;\n          int num_undetermined_edges = 0;\n          for (auto counter_eid : edges_from_vertex_cache[counter_vid]) {\n            auto [j, k] = args.problem->edges[counter_eid];\n            auto neighbor_vid = j == counter_vid ? k : j;\n            if (s->indices_flag[neighbor_vid] == USED) {\n              ++num_determined_edges;\n            } else {\n              ++num_undetermined_edges;\n            }\n          }\n          remaining_edges.push_back({num_undetermined_edges, eid});\n        }\n      }\n      std::sort(remaining_edges.begin(), remaining_edges.end());\n\n      StatePtr last_pushed;\n      for (const SEdgeItem& edge : remaining_edges) {\n        const int eid = edge.eid;\n        auto [u, v] = args.problem->edges[eid];\n        auto counter_vid = u == s->vid ? v : u;\n\n        // push nodes for this unused edge (s->vid, counter_vid)\n        auto original_distance2 = distance2(args.problem->vertices[s->vid], args.problem->vertices[counter_vid]);\n        auto movable_points = get_movable_points_with_tolerance(s->p, original_distance2);\n\n        for (auto p : movable_points) {\n          // all fixed neighbors of counter_vid should agree with this move.\n          bool agree = true;\n          for (auto counter_eid : edges_from_vertex_cache[counter_vid]) {\n            auto [j, k] = args.problem->edges[counter_eid];\n            auto neighbor_vid = j == counter_vid ? k : j;\n            if (s->indices_flag[neighbor_vid] == USED) {\n              const double neighbor_original_distance2 = distance2(args.problem->vertices[neighbor_vid], args.problem->vertices[counter_vid]);\n              const double neighbor_distance2 = distance2(s->vertices[neighbor_vid], p);\n              if (!tolerate(neighbor_original_distance2, neighbor_distance2, args.problem->epsilon) // check this first!\n                || !is_good_edge(s->vertices[neighbor_vid], p)) { // heavy.\n                agree = false;\n                break;\n              }\n            }\n          }\n          if (agree) {\n            auto new_remaining_index_flag = s->indices_flag;\n            new_remaining_index_flag[counter_vid] = USED;\n            auto new_vertices = s->vertices;\n            new_vertices[counter_vid] = p;\n            auto new_s = std::make_shared<State>(s->depth + 1, counter_vid, p, new_remaining_index_flag, new_vertices);\n            new_s->parent = s;\n            if (!(use_cache_for_infeasible_placement_set && is_infeasible_placement(new_s))) {\n              last_pushed = new_s;\n              stack.push(new_s);\n            }\n          }\n        }\n      }\n\n      if (last_pushed) last_pushed->is_last = true;\n\n      if (s->parent && s->is_last) {\n        // invoke cleanup process of s->parent.\n        if (use_cache_for_infeasible_placement_set) {\n          //LOG(INFO) << fmt::format(\"infeasible processing {}(depth={}) ({},{}) hash=0x{:x}\", s->parent->vid, s->parent->depth, s->parent->p.first, s->parent->p.second, State_to_zobrist(s->parent));\n          set_infeasible_placement(s->parent);\n        }\n      }\n    }\n    LOG(INFO) << fmt::format(\"total nodes = {}, max depth = {}\", counter, max_depth);\n\n    return ret;\n  }\n\n};\n}\n\nREGISTER_SOLVER(\"NaiveSearchSolver\", NNaiveSearchSolver::NaiveSearchSolver);\n// vim:ts=2 sw=2 sts=2 et ci\n\n", "meta": {"hexsha": "8339eb3d9b26f44d6862adfe60a080b144413890", "size": 21677, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/solvers/naive_search_solver.cpp", "max_stars_repo_name": "nodchip/icfpc2021", "max_stars_repo_head_hexsha": "e50f0172fd62097049dab19c01875c57468a13f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-12T13:52:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-12T13:52:18.000Z", "max_issues_repo_path": "src/solvers/naive_search_solver.cpp", "max_issues_repo_name": "nodchip/icfpc2021", "max_issues_repo_head_hexsha": "e50f0172fd62097049dab19c01875c57468a13f1", "max_issues_repo_licenses": ["MIT"], "max_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/naive_search_solver.cpp", "max_forks_repo_name": "nodchip/icfpc2021", "max_forks_repo_head_hexsha": "e50f0172fd62097049dab19c01875c57468a13f1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-24T08:49:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-24T08:49:18.000Z", "avg_line_length": 39.4127272727, "max_line_length": 211, "alphanum_fraction": 0.6212575541, "num_tokens": 5586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680199891789, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4543595305500914}}
{"text": "#include \"triangle.h\"\n#define BOOST_TEST_MAIN\n#include <boost/test/unit_test.hpp>\n#include <stdexcept>\n\nBOOST_AUTO_TEST_CASE(equilateral_triangles_have_equal_sides)\n{\n    BOOST_REQUIRE_EQUAL(triangle::equilateral, triangle::kind(2, 2, 2));\n}\n\n\nBOOST_AUTO_TEST_CASE(larger_equilateral_triangles_also_have_equal_sides)\n{\n    BOOST_REQUIRE_EQUAL(triangle::equilateral, triangle::kind(10, 10, 10));\n}\n\nBOOST_AUTO_TEST_CASE(isosceles_triangles_have_last_two_sides_equal)\n{\n    BOOST_REQUIRE_EQUAL(triangle::isosceles, triangle::kind(3, 4, 4));\n}\n\nBOOST_AUTO_TEST_CASE(isosceles_triangles_have_first_and_last_sides_equal)\n{\n    BOOST_REQUIRE_EQUAL(triangle::isosceles, triangle::kind(4, 3, 4));\n}\n\nBOOST_AUTO_TEST_CASE(isosceles_triangles_have_first_two_sides_equal)\n{\n    BOOST_REQUIRE_EQUAL(triangle::isosceles, triangle::kind(4, 4, 3));\n}\n\nBOOST_AUTO_TEST_CASE(isosceles_triangles_have_in_fact_exactly_two_sides_equal)\n{\n    BOOST_REQUIRE_EQUAL(triangle::isosceles, triangle::kind(10, 10, 2));\n}\n\nBOOST_AUTO_TEST_CASE(scalene_triangles_have_no_equal_sides)\n{\n    BOOST_REQUIRE_EQUAL(triangle::scalene, triangle::kind(3, 4, 5));\n}\n\nBOOST_AUTO_TEST_CASE(scalene_triangles_have_no_equal_sides_at_a_larger_scale_too)\n{\n    BOOST_REQUIRE_EQUAL(triangle::scalene, triangle::kind(10, 11, 12));\n}\n\nBOOST_AUTO_TEST_CASE(scalene_triangles_have_no_equal_sides_in_descending_order_either)\n{\n    BOOST_REQUIRE_EQUAL(triangle::scalene, triangle::kind(5, 4, 2));\n}\n\n\nBOOST_AUTO_TEST_CASE(very_small_triangles_are_legal)\n{\n    BOOST_REQUIRE_EQUAL(triangle::scalene, triangle::kind(0.4, 0.6, 0.3));\n}\n\nBOOST_AUTO_TEST_CASE(triangles_with_no_size_are_illegal)\n{\n    BOOST_REQUIRE_THROW(triangle::kind(0, 0, 0), std::domain_error);\n}\n\nBOOST_AUTO_TEST_CASE(triangles_with_negative_sides_are_illegal)\n{\n    BOOST_REQUIRE_THROW(triangle::kind(3, 4, -5), std::domain_error);\n}\n\nBOOST_AUTO_TEST_CASE(triangles_violating_triangle_inequality_are_illegal)\n{\n    BOOST_REQUIRE_THROW(triangle::kind(1, 1, 3), std::domain_error);\n}\n\nBOOST_AUTO_TEST_CASE(larger_triangles_violating_triangle_inequality_are_illegal)\n{\n    BOOST_REQUIRE_THROW(triangle::kind(7, 3, 2), std::domain_error);\n}\n#if defined(EXERCISM_RUN_ALL_TESTS)\n#endif\n", "meta": {"hexsha": "f52a93be30180cccd09ba4c7697ece25d0f48cf1", "size": 2197, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/triangle/triangle_test.cpp", "max_stars_repo_name": "mayurdw/exercism", "max_stars_repo_head_hexsha": "05e1440aba45ba18e47c40149b7f47adbac8e4c5", "max_stars_repo_licenses": ["MIT"], "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/triangle/triangle_test.cpp", "max_issues_repo_name": "mayurdw/exercism", "max_issues_repo_head_hexsha": "05e1440aba45ba18e47c40149b7f47adbac8e4c5", "max_issues_repo_licenses": ["MIT"], "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/triangle/triangle_test.cpp", "max_forks_repo_name": "mayurdw/exercism", "max_forks_repo_head_hexsha": "05e1440aba45ba18e47c40149b7f47adbac8e4c5", "max_forks_repo_licenses": ["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.8101265823, "max_line_length": 86, "alphanum_fraction": 0.8056440601, "num_tokens": 618, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.611381973294151, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.45435952707233734}}
{"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_FUNCTION_DREM_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_DREM_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-arithmetic\n    Function object implementing drem capabilities\n\n    Computes the drem of division.\n    The return value is x-n*y, where n is the value x/y,\n    rounded to the nearest integer (using @ref round2even).\n\n    This is a convenient alias of @ref remainder\n  **/\n  const boost::dispatch::functor<tag::drem_> drem = {};\n} }\n#endif\n\n#include <boost/simd/function/scalar/remainder.hpp>\n#include <boost/simd/function/simd/drem.hpp>\n\n#endif\n", "meta": {"hexsha": "54cd015ce8582ca3a18847e5b9c9084cf3f58f3d", "size": 1048, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/drem.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/function/drem.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/function/drem.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": 27.5789473684, "max_line_length": 100, "alphanum_fraction": 0.5963740458, "num_tokens": 220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.45435952359458337}}
{"text": "/*******************************************************************************\n * An array content domain.\n * \n * This domain is a simplified implementation of the paper: \n * \"A Partial-Order Approach to Array Content Analysis\" by \n *  Gange, Navas, Schachte, Sondergaard, and Stuckey\n *  available here http://arxiv.org/pdf/1408.1754v1.pdf.\n *\n * It keeps a graph where vertices are array indexes and edges are\n * labelled with weights.  An edge (i,j) with weight w denotes that\n * the property w holds for the array segment [i,j). A weight is an\n * arbitrary lattice that can relate multiple array variables as well\n * as array with scalar variables.\n ******************************************************************************/\n\n/**\n * TODOs:\n * \n * The implementation works for toy programs but we need to fix the\n * following issues for being able to analyze real programs:\n *\n * - landmarks must be kept as local state as part of each abstract\n *   state.\n * \n * - reduction between scalar and weight domains must be done\n *   incrementally. For that, we need some assumptions about the\n *   underlying scalar domain. For instance, if we assume zones then\n *   after each operation we know which are the indexes affected by\n *   the operation. We can use that information for doing reduction\n *   only on those indexes. This would remove the need of having\n *   methods such as array_sgraph_domain_helper_traits::is_unsat and\n *   array_sgraph_domain_helper_traits::active_variables which are\n *   anyway domain dependent.\n **/ \n\n#pragma once \n\n#include <crab/common/types.hpp>\n#include <crab/common/debug.hpp>\n#include <crab/common/stats.hpp>\n#include <crab/domains/abstract_domain.hpp>\n#include <crab/domains/abstract_domain_specialized_traits.hpp>\n#include <crab/domains/array_sparse_graph/array_segmentation.hpp>\n#include <crab/domains/array_sparse_graph/array_graph_ops.hpp>\n#include <crab/domains/graphs/adapt_sgraph.hpp>\n#include <crab/domains/graphs/sparse_graph.hpp>\n#include <crab/domains/linear_constraints.hpp>\n#include <crab/domains/intervals.hpp>\n\n// XXX: if expression domain is a template parameter no need to include\n#include <crab/domains/term_equiv.hpp>\n// XXX: for customized propagations between weight and scalar domains\n#include <crab/domains/combined_domains.hpp>\n#include <crab/domains/nullity.hpp>\n\n#include <memory>\n#include <unordered_map>\n#include <unordered_set>\n#include <functional>\n#include <type_traits>\n#include <boost/container/flat_map.hpp>\n#include <boost/optional.hpp>\n#include <boost/range/iterator_range.hpp>\n#include <boost/iterator/transform_iterator.hpp>\n\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wsign-compare\"\n\nnamespace crab {\nnamespace domains {\n/* \n   A weighted directed graph where the weight is an abstract\n   domain. The graph should be always kept in a consistent form,\n   i.e., for all i,j,k:: weight(i,j) <= join(weight(i,k), weight(k,j))\n*/\ntemplate< typename Vertex, typename Weight, bool IsDistWeight >\nclass array_sparse_graph_: public writeable {\n\npublic:\n\n// XXX: make this a template parameter later\n//typedef AdaptGraph<Weight> graph_t;\ntypedef SparseWtGraph<Weight> graph_t;\ntypedef typename graph_t::vert_id _vert_id;\ntypedef typename graph_t::edge_ref_t edge_ref_t;\ntypedef typename graph_t::Wt Wt;\ntypedef typename graph_t::mut_val_ref_t mut_val_ref_t;\n// XXX: needs to have this typedef so we can use GraphRev\ntypedef Vertex vert_id;\n\nprivate:\n\ntypedef GraphPerm<graph_t> GrPerm;\ntypedef ArrayGrOps<graph_t, IsDistWeight> GrOps;\ntypedef typename GrOps::Wt_join Wt_join;\ntypedef typename GrOps::Wt_meet Wt_meet;\n\ntypedef boost::container::flat_map<Vertex, _vert_id> vert_map_t;\ntypedef typename vert_map_t::value_type vmap_elt_t;\ntypedef std::vector<boost::optional<Vertex> > rev_map_t;\ntypedef std::unordered_set<_vert_id> vert_set_t;\ntypedef array_sparse_graph_<Vertex, Weight, IsDistWeight> array_sparse_graph_t;\n\nvert_map_t _vert_map;\nrev_map_t _rev_map;\ngraph_t _g;\nvert_set_t _unstable;\nbool _is_bottom;\n\nstruct vert_set_wrap_t {\nvert_set_wrap_t(const vert_set_t& _vs)\n  : vs(_vs) { }\n        \nbool operator[](_vert_id v) const {\nreturn vs.find(v) != vs.end();\n}\nconst vert_set_t& vs;\n};\n\n_vert_id get_vert(Vertex v)\n{\nauto it = _vert_map.find(v);\nif(it != _vert_map.end())\n  return (*it).second;\n\n_vert_id vert(_g.new_vertex());\nassert(vert <= _rev_map.size());\n\nif(vert < _rev_map.size()) {\nassert(!_rev_map[vert]);\n_rev_map[vert] = v;\n} else {\n_rev_map.push_back(v);\n}\n_vert_map.insert(vmap_elt_t(v, vert));\n\nreturn vert;\n}\n\npublic: \n\ntemplate<class ItS>\nclass iterator {\npublic:\ntypedef iterator<ItS> iter_t;\niterator(const ItS& _it, const rev_map_t& _rev_map) \n  : it(_it), rev_map(_rev_map) { }\n  bool operator!=(const iter_t& o) \n  { return it != o.it; }\n    iter_t& operator++(void) { ++it; return *this; }\n      Vertex operator*(void) const { \nif (!rev_map[*it]) CRAB_ERROR(\"Reverse map failed\");\nreturn *(rev_map[*it]);\n}\nprotected:\n  ItS it;      \nconst rev_map_t& rev_map;\n};\n\nstruct edge_t {\nedge_t(Vertex _v, Wt& _w) : vert(_v), val(_w) { }\n  Vertex vert;\n  Wt& val; \n};\n\n  template<class ItS>\n  class edge_iterator {\n  public:\n    typedef edge_iterator<ItS> iter_t;\n    edge_iterator(const ItS& _it, const rev_map_t& _rev_map) \n      : it(_it), rev_map(_rev_map) { }\n    bool operator!=(const iter_t& o) \n    { return it != o.it; }\n    iter_t& operator++(void) { ++it; return *this; }\n    edge_t operator*(void) const { \n      edge_ref_t e = *it;\n      if (!rev_map[e.vert]) CRAB_ERROR(\"Reverse map failed\");\n      Vertex v = *(rev_map[e.vert]);\n      return edge_t(v, e.val);\n    }\n  protected:\n    ItS it;      \n    const rev_map_t& rev_map;\n  };\n\n  template<class Range, class ItS>\n  class iterator_range {\n  public:\n    typedef ItS iterator;\n    iterator_range(const Range &r, const rev_map_t &rev_map) \n      : _r(r), _rev_map(rev_map) { }\n    iterator begin(void) const { return iterator(_r.begin(), _rev_map); }\n    iterator end(void) const { return iterator(_r.end(), _rev_map); }\n  protected:\n    Range _r;\n    const rev_map_t &_rev_map;\n  };\n\n  typedef iterator<typename graph_t::succ_iterator> succ_transform_iterator;\n  typedef iterator<typename graph_t::pred_iterator> pred_transform_iterator;\n  typedef iterator<typename graph_t::vert_iterator> vert_transform_iterator;\n  typedef edge_iterator<typename graph_t::fwd_edge_iterator> fwd_edge_transform_iterator;\n  typedef edge_iterator<typename graph_t::rev_edge_iterator> rev_edge_transform_iterator;\n\n  typedef iterator_range<typename graph_t::succ_range, succ_transform_iterator> succ_range;\n  typedef iterator_range<typename graph_t::pred_range, pred_transform_iterator> pred_range;\n  typedef iterator_range<typename graph_t::vert_range, vert_transform_iterator> vert_range;\n  typedef iterator_range<typename graph_t::e_succ_range, fwd_edge_transform_iterator>\n  e_succ_range;\n  typedef iterator_range<typename graph_t::e_pred_range, rev_edge_transform_iterator>\n  e_pred_range;\n\n  vert_range verts() {\n    typename graph_t::vert_range p = _g.verts();\n    return vert_range(p, _rev_map);\n  }\n      \n  succ_range succs(Vertex v) {\n    typename graph_t::succ_range p = _g.succs(get_vert(v));\n    return succ_range(p, _rev_map);        \n  }\n\n  pred_range preds(Vertex v) {\n    typename graph_t::pred_range p = _g.preds(get_vert(v));\n    return pred_range(p, _rev_map);        \n  }\n\n  e_succ_range e_succs(Vertex v) {\n    typename graph_t::e_succ_range p = _g.e_succs(get_vert(v));\n    return e_succ_range(p, _rev_map);        \n  }\n\n  e_pred_range e_preds(Vertex v) {\n    typename graph_t::e_pred_range p = _g.e_preds(get_vert(v));\n    return e_pred_range(p, _rev_map);        \n  }\n      \npublic:\n\n  array_sparse_graph_(bool is_bottom = false)\n    : _is_bottom(is_bottom) \n  { }\n\n  array_sparse_graph_(const array_sparse_graph_t& o)\n    : _vert_map(o._vert_map), _rev_map(o._rev_map), _g(o._g),\n      _unstable(o._unstable), _is_bottom(false) \n  { \n    if (o._is_bottom)\n      set_to_bottom();\n  }\n\n  array_sparse_graph_(array_sparse_graph_t&& o)\n    : _vert_map(std::move(o._vert_map)), _rev_map(std::move(o._rev_map)),\n      _g(std::move(o._g)), _unstable(std::move(o._unstable)), _is_bottom(o._is_bottom) \n  { }\n\n  array_sparse_graph_(vert_map_t& vert_map, rev_map_t& rev_map, graph_t& g,\n\t\t      vert_set_t unstable)\n    : _vert_map(vert_map), _rev_map(rev_map), _g(g), \n      _unstable(unstable), _is_bottom(false)\n  { }\n      \n  array_sparse_graph_(vert_map_t&& vert_map, rev_map_t&& rev_map, graph_t&& g,\n\t\t      vert_set_t &&unstable)\n    : _vert_map(std::move(vert_map)), _rev_map(std::move(rev_map)), _g(std::move(g)),\n      _unstable(std::move(unstable)), _is_bottom(false)\n  { }\n\n  array_sparse_graph_t& operator=(const array_sparse_graph_t& o)\n  {\n    if(this != &o)\n      {\n\tif(o._is_bottom)\n\t  set_to_bottom();\n\telse {\n\t  _is_bottom = false;\n\t  _vert_map = o._vert_map;\n\t  _rev_map = o._rev_map;\n\t  _g = o._g;\n\t  _unstable = o._unstable;\n\t}\n      }\n    return *this;\n  }\n\n  array_sparse_graph_t& operator=(array_sparse_graph_t&& o)\n  {\n    if(o._is_bottom) {\n      set_to_bottom();\n    } else {\n      _is_bottom = false;\n      _vert_map = std::move(o._vert_map);\n      _rev_map = std::move(o._rev_map);\n      _unstable = std::move(o._unstable);\n      _g = std::move(o._g);\n    }\n    return *this;\n  }\n\npublic: \n\n  void set_to_bottom() {\n    _vert_map.clear();\n    _rev_map.clear();\n    _g.clear();\n    _unstable.clear();\n    _is_bottom = true;\n  }\n\n  static array_sparse_graph_t top() { return array_sparse_graph_t(false); }\n    \n  static array_sparse_graph_t bottom() { return array_sparse_graph_t(true); }\n    \n  bool is_bottom() const { return _is_bottom; }\n    \n  bool is_top() {\n    if(_is_bottom) \n      return false;\n    return _g.is_empty();\n  }\n\n  bool lookup_edge(Vertex s, Vertex d, mut_val_ref_t* w) {\n    if (is_bottom()) return false;\n    auto se = get_vert(s);\n    auto de = get_vert(d);\n    return _g.lookup(se, de, w);\n  }\n\n  // // update edge but do not close graph\n  // void update_edge_unclosed(Vertex s, Weight w, Vertex d) {\n  //   if (w.is_top()) return;\n  //   normalize();\n  //   if (is_bottom()) return;\n  //   auto se = get_vert(s);\n  //   auto de = get_vert(d);\n  //   Wt_meet op;\n  //   _g.update_edge(se, w, de, op);\n  // }\n\n  // close the graph after edge (s,d) has been updated\n  void close_edge(Vertex s, Vertex d) {\n    normalize();\n    if (is_bottom()) return;\n    auto se = get_vert(s);\n    auto de = get_vert(d);\n    GrOps::close_after_edge(_g, se, de);\n  }\n\n  void update_edge(Vertex s, Weight w, Vertex d) {\n    if (w.is_top())\n      return;\n\n    normalize();\n        \n    if (is_bottom())\n      return;\n        \n    auto se = get_vert(s);\n    auto de = get_vert(d);\n    Wt_meet op;\n    _g.update_edge(se, w, de, op);\n    GrOps::close_after_edge(_g, se, de);\n  }\n\n  // void full_close() { // for debugging\n  //   if (is_bottom()) return;\n  //   GrOps::floyd_warshall(_g);\n  // }\n\n  void expand(Vertex s, Vertex d) {\n    if(is_bottom()) \n      return;\n\n    auto it = _vert_map.find(d);\n    if(it != _vert_map.end()) {\n      CRAB_ERROR(\"array_sparse_graph expand failed because vertex \", d, \" already exists\");\n    }\n\n    auto se = get_vert(s);        \n    auto de = get_vert(d);\n        \n    for (auto edge : _g.e_preds(se))  \n      _g.add_edge(edge.vert, edge.val, de);\n        \n    for (auto edge : _g.e_succs(se))  \n      _g.add_edge(de, edge.val, edge.vert);\n\n  }\n\n  void normalize() {\n#if 0\n    GrOps::closure(_g); // only for debugging purposes\n#else\n    // Always maintained in closed form except for widening\n    if(_unstable.size() == 0)\n      return;\n    GrOps::close_after_widen(_g, vert_set_wrap_t(_unstable));\n    _unstable.clear();\n#endif \n  }\n\n  void operator|=(array_sparse_graph_t& o) {\n    *this = *this | o;\n  }\n\n  bool operator<=(array_sparse_graph_t& o)  {\n    if (is_bottom()) \n      return true;\n    else if(o.is_bottom())\n      return false;\n    else if (o.is_top())\n      return true;\n    else if (is_top())\n      return false;\n    else {\n      normalize();\n\n      if(_vert_map.size() < o._vert_map.size())\n\treturn false;\n\n      // Set up a mapping from o to this.\n      std::vector<unsigned int> vert_renaming(o._g.size(),-1);\n      for(auto p : o._vert_map)\n\t{\n\t  auto it = _vert_map.find(p.first);\n\t  // We can't have this <= o if we're missing some\n\t  // vertex.\n\t  if(it == _vert_map.end())\n\t    return false;\n\t  vert_renaming[p.second] = (*it).second;\n\t}\n\n      assert(_g.size() > 0);\n      mut_val_ref_t wx;\n\n      for(_vert_id ox : o._g.verts()) {\n\tassert(vert_renaming[ox] != -1);\n\t_vert_id x = vert_renaming[ox];\n\tfor(auto edge : o._g.e_succs(ox)) {\n\t  _vert_id oy = edge.vert;\n\t  assert(vert_renaming[ox] != -1);\n\t  _vert_id y = vert_renaming[oy];\n\t  auto ow = (Weight) edge.val;\n\t  if(!_g.lookup(x, y, &wx) || (!((Weight) wx <= ow))) \n\t    return false;\n\t}\n      }\n      return true;\n    }\n  }\n\n  array_sparse_graph_t operator|(array_sparse_graph_t& o) {\n\n    if (is_bottom() || o.is_top())\n      return o;\n    else if (is_top() || o.is_bottom())\n      return *this;\n    else {\n      CRAB_LOG(\"array-sgraph\",\n\t       crab::outs() << \"Before join:\\n\"<<\"Graph 1\\n\"<<*this\n\t       <<\"\\n\"<<\"Graph 2\\n\"<<o << \"\\n\");\n\n      normalize();\n      o.normalize();\n\n      // Figure out the common renaming.\n      std::vector<_vert_id> perm_x;\n      std::vector<_vert_id> perm_y;\n\n      vert_map_t out_vmap;\n      rev_map_t out_revmap;\n\n      for(auto p : _vert_map)\n\t{\n\t  auto it = o._vert_map.find(p.first); \n\t  // Vertex exists in both\n\t  if(it != o._vert_map.end())\n            {\n              out_vmap.insert(vmap_elt_t(p.first, perm_x.size()));\n              out_revmap.push_back(p.first);\n\n              perm_x.push_back(p.second);\n              perm_y.push_back((*it).second);\n            }\n\t}\n\n      // Build the permuted view of x and y.\n      assert(_g.size() > 0);\n      GrPerm gx(perm_x, _g);\n      assert(o._g.size() > 0);\n      GrPerm gy(perm_y, o._g);\n\n      // We now have the relevant set of relations. Because g_rx\n      // and g_ry are closed, the result is also closed.\n      graph_t join_g(GrOps::join(gx, gy));\n\n      // Now garbage collect any unused vertices\n      for(_vert_id v : join_g.verts())\n\t{\n\t  if(join_g.succs(v).size() == 0 && join_g.preds(v).size() == 0)\n            {\n              join_g.forget(v);\n              if(out_revmap[v])\n\t\t{\n\t\t  out_vmap.erase(*(out_revmap[v]));\n\t\t  out_revmap[v] = boost::none;\n\t\t}\n            }\n\t}\n\n      array_sparse_graph_t res(std::move(out_vmap), std::move(out_revmap), \n\t\t\t       std::move(join_g), vert_set_t());\n      CRAB_LOG(\"array-sgraph\", crab::outs() << \"Result join:\\n\"<< res <<\"\\n\";);\n      return res;\n    }\n  }\n\n  template<typename Thresholds>\n  array_sparse_graph_t widening_thresholds(array_sparse_graph_t &o, const Thresholds&) {\n    return (*this || o);\n  }\n      \n  array_sparse_graph_t operator||(array_sparse_graph_t &o) {\t\n    if (is_bottom())\n      return o;\n    else if (o.is_bottom())\n      return *this;\n    else {\n      CRAB_LOG (\"array-sgraph\",\n\t\tcrab::outs() << \"Before widening:\\n\"<<\"Graph 1\\n\"<<*this\n\t\t<<\"\\n\"<<\"Graph 2\\n\"<<o<<\"\\n\";);\n      o.normalize();\n          \n      // Figure out the common renaming\n      std::vector<_vert_id> perm_x;\n      std::vector<_vert_id> perm_y;\n      vert_map_t out_vmap;\n      rev_map_t out_revmap;\n      vert_set_t widen_unstable(_unstable);\n\n      for(auto p : _vert_map)\n\t{\n\t  auto it = o._vert_map.find(p.first); \n\t  // Vertex exists in both\n\t  if(it != o._vert_map.end())\n            {\n              out_vmap.insert(vmap_elt_t(p.first, perm_x.size()));\n              out_revmap.push_back(p.first);\n\n              perm_x.push_back(p.second);\n              perm_y.push_back((*it).second);\n            }\n\t}\n          \n      // Build the permuted view of x and y.\n      //assert(_g.size() > 0);\n      GrPerm gx(perm_x, _g);            \n      //assert(o._g.size() > 0);\n      GrPerm gy(perm_y, o._g);\n          \n      // Now perform the widening \n      std::vector<_vert_id> destabilized;\n      graph_t widen_g(GrOps::widen(gx, gy, destabilized));\n      for(_vert_id v : destabilized) {\n\twiden_unstable.insert(v);\n      }\n          \n      array_sparse_graph_t res(std::move(out_vmap), std::move(out_revmap), \n\t\t\t       std::move(widen_g), std::move(widen_unstable));\n      CRAB_LOG(\"array-sgraph\", crab::outs() << \"Result widening:\\n\"<<res<<\"\\n\";);\n      return res;\n    }\n  }\n\n\n  array_sparse_graph_t meet_or_narrowing(array_sparse_graph_t &o, bool is_meet,\n\t\t\t\t\t const std::string op) {\n\n    if (is_bottom() || o.is_bottom())\n      return bottom();\n    else if (is_top())\n      return o;\n    else if (o.is_top())\n      return *this;\n    else {\n      CRAB_LOG(\"array-sgraph\",\n\t       crab::outs() << \"Before \" << op << \":\\n\"<<\"Graph 1\\n\"<<*this<<\"\\n\"\n\t       <<\"Graph 2\\n\"<<o << \"\\n\");\n\n      normalize();\n      o.normalize();\n\n      // Figure out the common renaming.\n      std::vector<_vert_id> perm_x;\n      std::vector<_vert_id> perm_y;\n\n      vert_map_t out_vmap;\n      rev_map_t out_revmap;\n\n      for(auto p : _vert_map)\n\t{\n\t  _vert_id vv = perm_x.size();\n\t  out_vmap.insert(vmap_elt_t(p.first, vv));\n\t  out_revmap.push_back(p.first);\n            \n\t  perm_x.push_back(p.second);\n\t  perm_y.push_back(-1);\n\t}\n\n\n      // Add missing mappings from the right operand.\n      for(auto p : o._vert_map)\n\t{\n\t  auto it = out_vmap.find(p.first);\n\t  if(it == out_vmap.end())\n            {\n              _vert_id vv = perm_y.size();\n              out_revmap.push_back(p.first);\n\n              perm_y.push_back(p.second);\n              perm_x.push_back(-1);\n              out_vmap.insert(vmap_elt_t(p.first, vv));\n            } else {\n\t    perm_y[(*it).second] = p.second;\n\t  }\n\t}\n\n      // Build the permuted view of x and y.\n      GrPerm gx(perm_x, _g);\n      GrPerm gy(perm_y, o._g);\n\n      // Compute the syntactic meet/narrowing of the permuted graphs.\n      std::vector<_vert_id> changes;\n      graph_t out_g(GrOps::meet_or_narrowing(gx, gy, is_meet, changes));\n      vert_set_t unstable;\n      for(_vert_id v : changes)\n\tunstable.insert(v);\n\n      GrOps::close_after_meet_or_narrowing(_g, vert_set_wrap_t(unstable));\n\n      array_sparse_graph_t res(std::move(out_vmap), std::move(out_revmap), \n\t\t\t       std::move(out_g), vert_set_t());\n      CRAB_LOG(\"array-sgraph\", crab::outs() << \"Result \" << op << \":\\n\"<< res <<\"\\n\";);\n      return res;\n    }\n  }\n\n  array_sparse_graph_t operator&(array_sparse_graph_t& o) {\n    return meet_or_narrowing(o, true, \"meet\");\n  }\n\n  array_sparse_graph_t operator&&(array_sparse_graph_t& o) {\n    return meet_or_narrowing(o, false, \"narrowing\");\n  }\n      \n  // array_sparse_graph_t operator&(array_sparse_graph_t& o) {\n\n  //   if (is_bottom() || o.is_bottom())\n  //     return bottom();\n  //   else if (is_top())\n  //     return o;\n  //   else if (o.is_top())\n  //     return *this;\n  //   else {\n  //     CRAB_LOG(\"array-sgraph\",\n  //               crab::outs() << \"Before meet:\\n\"<<\"Graph 1\\n\"<<*this<<\"\\n\"\n  //                            <<\"Graph 2\\n\"<<o << \"\\n\");\n\n  //     normalize();\n  //     o.normalize();\n\n  //     // Figure out the common renaming.\n  //     std::vector<_vert_id> perm_x;\n  //     std::vector<_vert_id> perm_y;\n\n  //     vert_map_t out_vmap;\n  //     rev_map_t out_revmap;\n\n  //     for(auto p : _vert_map)\n  //     {\n  //       _vert_id vv = perm_x.size();\n  //       out_vmap.insert(vmap_elt_t(p.first, vv));\n  //       out_revmap.push_back(p.first);\n            \n  //       perm_x.push_back(p.second);\n  //       perm_y.push_back(-1);\n  //     }\n\n\n  //     // Add missing mappings from the right operand.\n  //     for(auto p : o._vert_map)\n  //     {\n  //       auto it = out_vmap.find(p.first);\n  //       if(it == out_vmap.end())\n  //       {\n  //         _vert_id vv = perm_y.size();\n  //         out_revmap.push_back(p.first);\n\n  //         perm_y.push_back(p.second);\n  //         perm_x.push_back(-1);\n  //         out_vmap.insert(vmap_elt_t(p.first, vv));\n  //       } else {\n  //         perm_y[(*it).second] = p.second;\n  //       }\n  //     }\n\n  //     // Build the permuted view of x and y.\n  //     //assert(_g.size() > 0);\n  //     GrPerm gx(perm_x, _g);\n  //     //assert(o._g.size() > 0);\n  //     GrPerm gy(perm_y, o._g);\n\n  //     // Compute the syntactic meet of the permuted graphs.\n  //     std::vector<_vert_id> changes;\n  //     graph_t meet_g(GrOps::meet_or_narrowing(gx, gy, true /*meet*/, changes));\n  //     vert_set_t unstable;\n  //     for(_vert_id v : changes)\n  //       unstable.insert(v);\n\n  //     GrOps::close_after_meet_or_narrowing(_g, vert_set_wrap_t(unstable));\n\n  //     array_sparse_graph_t res(std::move(out_vmap), std::move(out_revmap), \n  //                              std::move(meet_g), vert_set_t());\n  //     CRAB_LOG(\"array-sgraph\", crab::outs() << \"Result meet:\\n\"<< res <<\"\\n\";);\n  //     return res;\n  //   }\n  // }\n\n  // array_sparse_graph_t operator&&(array_sparse_graph_t& o) {\n  //   if (is_bottom() || o.is_bottom())\n  //     return bottom();\n  //   else if (is_top())\n  //     return o;\n  //   else{\n  //     CRAB_LOG(\"array-sgraph\",\n  //               crab::outs() << \"Before narrowing:\\n\"<<\"Graph 1\\n\"<<*this<<\"\\n\"\n  //                            <<\"Graph 2\\n\"<<o<<\"\\n\";);\n\n  //     // Narrowing as a no-op should be sound.\n  //     normalize();\n  //     array_sparse_graph_t res(*this);\n          \n  //     CRAB_LOG(\"array-sgraph\",\n  //               crab::outs() << \"Result narrowing:\\n\" << res<<\"\\n\";);\n  //     return res;\n  //   }\n  // }\n\n  void operator-=(Vertex v) {\n    if (is_bottom())\n      return;\n    auto it = _vert_map.find(v);\n    if (it != _vert_map.end()) {\n      normalize();\n      _g.forget(it->second);\n      _rev_map[it->second] = boost::none;\n      _vert_map.erase(v);\n    }\n  }\n\n  void remove_from_weights(typename Weight::variable_t v) {\n    mut_val_ref_t w_pq;\n    for(auto p : _g.verts()) \n      for(auto e : _g.e_succs(p)) {\n\tauto q = e.vert;\n\tif (_g.lookup(p, q, &w_pq)) { \n\t  Weight w = (Weight) w_pq;\n\t  w -= v;\n\t  Wt_meet op;\n\t  _g.update_edge(p, w, q, op);\n\t  GrOps::close_after_edge(_g, p, q);\n\t}\n      }\n  }\n\n  void write(crab_os& o) {\n    write(o, true);\n  }\n\n  void write(crab_os& o, bool print_bottom_edges) {\n        \n    normalize();\n\n    if(is_bottom()){\n      o << \"_|_\";\n      return;\n    }\n    else if (is_top()){\n      o << \"{}\";\n      return;\n    }\n    else\n      {\n\tbool first = true;\n\to << \"{\";\n\n\t// sorting only for helping debugging\n\tstd::vector<_vert_id> verts;\n\tfor(auto v: _g.verts()) \n\t  verts.push_back(v);\n\tstd::sort(verts.begin(), verts.end());\n\t\n\tfor(_vert_id s : verts)\n          {\n            if(!_rev_map[s]) continue;\n              \n            auto vs = *_rev_map[s];\n\n\t    // sorting only for helping debugging\t    \n\t    std::vector<_vert_id> succs;\n\t    for (auto d: _g.succs(s))\n\t      succs.push_back(d);\n\t    std::sort(succs.begin(), succs.end());\n\t    \n            for(_vert_id d : succs)\n\t      {\n\t\tif(!_rev_map[d]) continue;\n\n\t\tauto w = _g.edge_val(s, d);\n\t\tif (!print_bottom_edges && w.is_bottom())\n\t\t  continue; // do not print bottom edges\n                \n\t\tauto vd = *_rev_map[d];\n\n\t\tif(first)\n\t\t  first = false;\n\t\telse\n\t\t  o << \", \";\n\t\to << \"[\" << vs << \",\" << vd << \")=>\" << w;\n\t      }\n          }\n\to << \"}\";\n      }\n  }\n};\n\nnamespace array_sparse_graph_impl {\n\n// JN: I do not know how to propagate arbitrary invariants\n// between weight and scalar domains in a domain-independent\n// manner. Here, we define propagations between specific\n// domains.\n\ntemplate <typename Dom>\ninterval<typename Dom::number_t> \neval_interval(Dom dom, typename Dom::linear_expression_t e) {\n  interval<typename Dom::number_t>  r = e.constant();\n  for (auto p : e)\n    r += p.first * dom[p.second];\n  return r;\n}\n\ntemplate<typename Dom1, typename Dom2>\nvoid propagate_between_weight_and_scalar\n(Dom1 src,\n typename Dom1::linear_expression_t src_e, \n variable_type ty, \n Dom2 &dst,\n typename Dom2::variable_t dst_var) {\n\t\n  if (ty == ARR_INT_TYPE || ty == ARR_REAL_TYPE) {\n    // --- XXX: simplification wrt Gange et.al.:\n    //     Only non-relational numerical invariants are\n    //     propagated from the graph domain to the scalar domain.\n    dst.set(dst_var, eval_interval(src, src_e)); \n  } else {\n    CRAB_WARN(\"Unsupported array type \", __LINE__, \":\",\n\t      \"missing propagation between weight and scalar domains\");\n  }\n}\n\ntemplate<typename BaseDom>\nvoid propagate_between_weight_and_scalar\n(numerical_nullity_domain<BaseDom> src,\n typename BaseDom::linear_expression_t src_e, \n variable_type ty, \n numerical_nullity_domain<BaseDom> &dst, \n typename BaseDom::variable_t dst_var) {\n\t\n  if (ty == ARR_INT_TYPE || ARR_REAL_TYPE) {\n    // --- XXX: simplification wrt Gange et.al.:\n    //     Only non-relational numerical invariants are\n    //     propagated from the graph domain to the scalar domain.\n    dst.set(dst_var, eval_interval(src, src_e)); \n  } else if (ty == ARR_PTR_TYPE) {\n    if (auto src_var = src_e.get_variable()) {\n      auto &null_dom = dst.second();\n      null_dom.set_nullity(dst_var, src.get_nullity(*src_var));\n    }\n  } else {\n    CRAB_WARN(\"Unsupported array type \", __LINE__, \":\",\n\t      \"missing propagation between weight and scalar domains\");\n  }\n}\n\ntemplate<typename BaseDom>\nvoid propagate_between_weight_and_scalar\n(nullity_domain<typename BaseDom::number_t, typename BaseDom::varname_t> src,\n typename BaseDom::linear_expression_t src_e, \n variable_type ty, \n numerical_nullity_domain<BaseDom> &dst, \n typename BaseDom::variable_t dst_var) {\n\t\n  if (ty == ARR_INT_TYPE || ty == ARR_REAL_TYPE) {\n    // do nothing\n  } else if (ty == ARR_PTR_TYPE) {\n    if (auto src_var = src_e.get_variable()) {\n      auto &null_dom = dst.second();\n      null_dom.set_nullity(dst_var, src.get_nullity(*src_var));\n    }\n  } else {\n    CRAB_WARN(\"Unsupported array type \", __LINE__, \":\",\n\t      \"missing propagation between weight and scalar domains\");\n  }\n}\n\ntemplate<typename BaseDom>\nvoid propagate_between_weight_and_scalar\n(numerical_nullity_domain<BaseDom> src, \n typename BaseDom::linear_expression_t src_e, \n variable_type ty, \n nullity_domain<typename BaseDom::number_t, typename BaseDom::varname_t> &dst,\n typename BaseDom::variable_t dst_var) {\n\t\n  if (ty == ARR_INT_TYPE || ty == ARR_REAL_TYPE) {\n    // do nothing\n  } else if (ty == ARR_PTR_TYPE) {\n    if (auto src_var = src_e.get_variable()) {\n      dst.set_nullity(dst_var,\n\t\t      src.second().get_nullity(*src_var));\n    }\n  } else {\n    CRAB_WARN(\"Unsupported array type \", __LINE__, \":\",\n\t      \"missing propagation between weight and scalar domains\");\n  }\n}\n\n} /* end array_sparse_graph_impl */\n    \n#if 1\ntemplate<class Vertex, class Weight, bool IsDistWeight>\nusing array_sparse_graph = array_sparse_graph_<Vertex, Weight, IsDistWeight>;    \n#else\n// Wrapper which uses shared references with copy-on-write.\ntemplate<class Vertex, class Weight, bool IsDistWeight>\nclass array_sparse_graph : public writeable {\npublic:\n\n  typedef array_sparse_graph_<Vertex, Weight, IsDistWeight> array_sgraph_impl_t;\n  typedef std::shared_ptr<array_sgraph_impl_t> array_sgraph_ref_t;\n  typedef array_sparse_graph<Vertex, Weight, IsDistWeight> array_sgraph_t;\n\n  typedef typename array_sgraph_impl_t::Wt Wt;\n  typedef typename array_sgraph_impl_t::mut_val_ref_t mut_val_ref_t;\n  typedef typename array_sgraph_impl_t::graph_t graph_t;\n  typedef typename array_sgraph_impl_t::vert_id vert_id;\n  typedef typename array_sgraph_impl_t::succ_range succ_range;\n  typedef typename array_sgraph_impl_t::pred_range pred_range;\n  typedef typename array_sgraph_impl_t::vert_range vert_range;\n  typedef typename array_sgraph_impl_t::e_succ_range e_succ_range;\n  typedef typename array_sgraph_impl_t::e_pred_range e_pred_range;\n\n  array_sparse_graph(array_sgraph_ref_t _ref) : norm_ref(_ref) { }\n\n  array_sparse_graph(array_sgraph_ref_t _base, array_sgraph_ref_t _norm) \n    : base_ref(_base), norm_ref(_norm) { }\n\n  array_sgraph_t create(array_sgraph_impl_t&& t)\n  {\n    return std::make_shared<array_sgraph_impl_t>(std::move(t));\n  }\n\n  array_sgraph_t create_base(array_sgraph_impl_t&& t)\n  {\n    array_sgraph_ref_t base = std::make_shared<array_sgraph_impl_t>(t);\n    array_sgraph_ref_t norm = std::make_shared<array_sgraph_impl_t>(std::move(t));  \n    return array_sgraph_t(base, norm);\n  }\n\n  void lock(void)\n  { // Allocate a fresh copy.\n    if(!norm_ref.unique())\n      norm_ref = std::make_shared<array_sgraph_impl_t>(*norm_ref);\n    base_ref.reset();\n  }\n\npublic:\n\n  static array_sgraph_t top() { return array_sparse_graph(false); }\n    \n  static array_sgraph_t bottom() { return array_sparse_graph(true); }\n\n  array_sparse_graph(bool is_bottom = false)\n    : norm_ref(std::make_shared<array_sgraph_impl_t>(is_bottom)) { }\n\n  array_sparse_graph(const array_sgraph_t& o)\n    : base_ref(o.base_ref), norm_ref(o.norm_ref)\n  { }\n\n  array_sgraph_t& operator=(const array_sgraph_t& o) {\n    base_ref = o.base_ref;\n    norm_ref = o.norm_ref;\n    return *this;\n  }\n\n  array_sgraph_impl_t& base(void) {\n    if(base_ref)\n      return *base_ref;\n    else\n      return *norm_ref;\n  }\n\n  array_sgraph_impl_t& norm(void) { return *norm_ref; }\n  const array_sgraph_impl_t& norm(void) const { return *norm_ref; }\n\n  bool is_bottom() { return norm().is_bottom(); }\n\n  bool is_top() { return norm().is_top(); }\n\n  bool operator<=(array_sgraph_t& o) { return norm() <= o.norm(); }\n\n  void operator|=(array_sgraph_t o) { lock(); norm() |= o.norm(); }\n\n  array_sgraph_t operator|(array_sgraph_t o) { return create(norm() | o.norm()); }\n\n  array_sgraph_t operator||(array_sgraph_t o) { return create_base(base() || o.norm()); }\n\n  array_sgraph_t operator&(array_sgraph_t o) { return create(norm() & o.norm()); }\n\n  array_sgraph_t operator&&(array_sgraph_t o) { return create(norm() && o.norm()); }\n\n  template<typename Thresholds>\n  array_sgraph_t widening_thresholds(array_sgraph_t o, const Thresholds& ts) {\n    return create_base(base().template widening_thresholds<Thresholds>(o.norm(), ts));\n  }\n\n  void normalize() { lock(); norm().normalize(); }\n\n  vert_range verts() { return norm().verts(); }\n\n  succ_range succs(Vertex v) { return norm().succs(v); }\n\n  pred_range preds(Vertex v) { return norm().preds(v); }\n\n  e_succ_range e_succs(Vertex v) { return norm().e_succs(v); }\n\n  e_pred_range e_preds(Vertex v) { return norm().e_preds(v); }\n\n  void set_to_bottom() { lock(); norm().set_to_bottom(); }\n\n  bool lookup_edge(Vertex s, Vertex d, mut_val_ref_t* w) \n  { lock(); return norm().lookup_edge(s,d,w); }\n\n  void expand(Vertex s, Vertex d) \n  { lock(); norm().expand(s,d); }\n\n  void update_edge(Vertex s, Weight w, Vertex d) { lock(); norm().update_edge(s,w,d); }\n\n  // void full_close() { lock(); norm().full_close(); }\n  // void update_edge_unclosed(Vertex s, Weight w, Vertex d) {\n  // lock(); norm().update_edge_unclosed(s,w,d); }\n  void close_edge(Vertex s, Vertex d) { lock(); norm().close_edge(s,d); }\n\n  void remove_from_weights(typename Weight::variable_t v)\n  { lock(); norm().remove_from_weights(v);}\n\n  void operator-=(Vertex v) { lock(); norm() -= v; }\n\n  void write(crab_os& o) { norm().write(o); }\n  void write(crab_os& o, bool print_bottom_edges) { norm().write(o, print_bottom_edges); }\n\nprotected:  \n  array_sgraph_ref_t base_ref;  \n  array_sgraph_ref_t norm_ref;\n};\n#endif \n\n// Landmark: another C++ datatype to wrap variables and numbers as\n// graph vertices.\n\nenum landmark_kind_t { LMC, LMV, LMVP};\n\ntemplate<class Variable, class Number>\nclass landmark {\nprotected:\n  \n  landmark_kind_t _kind;\n  landmark(landmark_kind_t kind): _kind(kind) { }\n  \npublic:\n\n  virtual ~landmark() {}\n  \n  landmark_kind_t kind() const { return _kind;}\n  \n  virtual bool operator==(const landmark<Variable,Number>& o) const = 0;\n  \n  virtual bool operator<(const landmark<Variable,Number>& o) const = 0;\n  \n  virtual void write(crab_os&o) const = 0;\n  \n  virtual std::size_t hash() const = 0;\n};\n\ntemplate<class Variable, class Number>\nclass landmark_cst: public landmark<Variable,Number> {\n  \n  Number _n;\n  typedef landmark<Variable,Number> landmark_t;\n  typedef landmark_cst<Variable,Number> landmark_cst_t;\n\npublic:\n  \n  landmark_cst(Number n):\n    landmark_t(landmark_kind_t::LMC), _n(n) {}\n\n  bool operator==(const landmark_t& o) const {\n    if (this->_kind != o.kind()) return false;\n\n    assert(o.kind() == landmark_kind_t::LMC);\n    auto o_ptr =  static_cast<const landmark_cst_t*>(&o);\n    return(_n == o_ptr->_n);\n  }\n\n  bool operator<(const landmark_t& o) const {\n    if (this->_kind != o.kind()) return true;\n\n    assert (o.kind() == landmark_kind_t::LMC);\n    return (_n < static_cast<const landmark_cst_t*>(&o)->_n);\n  }\n\n  void write(crab_os&o) const { o << _n; }\n\n  std::size_t hash() const { return std::hash<Number>{}(_n);}\n\n  Number get_cst() const { return _n;}\n};\n\ntemplate<class Variable, class Number>\nclass landmark_var: public landmark<Variable,Number> {\n  \n  Variable _v;\n  typedef landmark<Variable,Number> landmark_t;\n  typedef landmark_var<Variable,Number> landmark_var_t;\n\npublic:\n  \n  landmark_var(Variable v):\n    landmark_t(landmark_kind_t::LMV), _v(v) {}\n\n  bool operator==(const landmark_t& o) const {\n    if (this->_kind != o.kind()) return false;\n\n    assert (o.kind() == landmark_kind_t::LMV);\n    auto o_ptr = static_cast<const landmark_var_t*>(&o);\n    return (_v == o_ptr->_v);\n  }\n\n  bool operator<(const landmark_t& o) const {\n    if (this->_kind == o.kind()) {\n      assert(o.kind() == landmark_kind_t::LMV);\n      auto o_ptr =  static_cast<const landmark_var_t*>(&o);\n      return (_v < o_ptr->_v);\n    } else if(o.kind() == LMC) {\n      return false;\n    } else if (o.kind() == LMVP) {\n      return true;\n    } else  \n      CRAB_ERROR(\"unreachable!\");\n  }\n\n  void write(crab_os&o) const { o << _v; }\n\n  std::size_t hash() const { return _v.hash();}\n\n  Variable get_var() const { return _v;}\n};\n\ntemplate<class Variable, class Number>\nclass landmark_varprime: public landmark<Variable,Number> {\n  std::string _lm;\n  Variable _v;\n  \n  typedef landmark<Variable,Number> landmark_t;\n  typedef landmark_varprime<Variable,Number> landmark_var_prime_t;\n\npublic:\n  landmark_varprime(std::string lm, Variable v) \n    : landmark_t(landmark_kind_t::LMVP), _lm(lm), _v(v) {}\n\n  bool operator==(const landmark_t& o) const {\n    if (this->_kind != o.kind()) return false;\n        \n    assert (o.kind() == landmark_kind_t::LMVP);\n    auto o_ptr =  static_cast<const landmark_var_prime_t*>(&o);\n    return (_v == o_ptr->_v);\n  }\n\n  bool operator<(const landmark_t& o) const {\n    if (this->_kind != o.kind()) return false;\n\n    assert(o.kind() == landmark_kind_t::LMVP);\n    auto o_ptr =  static_cast<const landmark_var_prime_t*>(&o);\n    return (_v < o_ptr->_v);\n  }\n\n  void write(crab_os&o) const { o << _lm << \"'\"; }\n\n  std::size_t hash() const { return _v.hash();}\n\n  Variable get_var() const { return _v;}\n};\n\n\n// Wrapper for landmark\ntemplate<class Variable, class Number>\nclass landmark_ref {\n  typedef landmark<Variable,Number> landmark_t;\n  typedef landmark_ref<Variable,Number> landmark_ref_t;\n\npublic:\n\n  // yeah I know this is bad ...\n  std::shared_ptr<landmark_t> _ref;\n\n  landmark_ref(Variable v, std::string name=\"\"): _ref(nullptr) {\n    if (name==\"\") {\n      _ref = std::static_pointer_cast<landmark_t>\n\t(std::make_shared<landmark_var<Variable,Number>>\n\t (landmark_var<Variable,Number>(v)));\n    } else {\n      _ref = std::static_pointer_cast<landmark_t>\n\t(std::make_shared<landmark_varprime<Variable,Number>>\n\t (landmark_varprime<Variable,Number>(name, v)));\n    }\n  }\n  landmark_ref(Number n)\n    : _ref(std::static_pointer_cast<landmark_t>\n\t   (std::make_shared<landmark_cst<Variable,Number>>\n\t    (landmark_cst<Variable,Number>(n)))) { }\n      \n  landmark_kind_t kind() const { return _ref->kind();} \n\n  bool operator==(const landmark_ref &o) const { return (*_ref == *(o._ref)); } \n\n  bool operator<(const landmark_ref &o) const { return (*_ref < *(o._ref)); } \n\n  void write(crab_os& o) const { _ref->write(o); } \n\n  std::size_t hash() const { return _ref->hash();}\n};\n \n// super unsafe!\ntemplate<class Variable, class Number>\ninline Variable get_var(const landmark_ref<Variable,Number>& lm) {\n  assert(lm.kind() == LMVP);\n  return std::static_pointer_cast<const landmark_varprime<Variable,Number>>\n    (lm._ref)->get_var();\n}\n\n// super unsafe!\ntemplate<class Variable, class Number>\ninline Number get_cst(const landmark_ref<Variable,Number>& lm) {\n  assert(lm.kind() == LMC);\n  return std::static_pointer_cast<const landmark_cst<Variable,Number>>\n    (lm._ref)->get_cst();\n}\n\ntemplate<class Variable, class Number>\ninline crab_os& operator<<(crab_os& o, const landmark_ref<Variable,Number> &lm) {\n  lm.write(o);\n  return o;\n}\n} // end namespace domains\n} // end namespace crab\n\nnamespace std {\ntemplate<class Variable, class Number>\nstruct hash<crab::domains::landmark_ref<Variable,Number>> {\n  using landmark_ref_t = crab::domains::landmark_ref<Variable,Number>;\n  size_t operator()(const landmark_ref_t &lm) {\n    return lm.hash();\n  }\n};\n}\n\nnamespace crab {\nnamespace domains {\n\ntemplate<typename Variable, typename Number>\nstruct landmark_ref_hasher {\n  size_t operator()(const landmark_ref<Variable, Number>& lm) const {\n    return lm.hash();\n  }\n};\n\ntemplate<typename Variable, typename Number>\nstruct landmark_ref_equal {\n  bool operator()(const landmark_ref<Variable,Number>& lm1,\n\t\t  const landmark_ref<Variable,Number>& lm2) const {\n    return lm1 == lm2;\n  }\n};\n\ntemplate<typename Variable, class Number, class MappedVal>\nusing landmark_ref_unordered_map =\n  std::unordered_map<landmark_ref<Variable,Number>, MappedVal,\n\t\t     landmark_ref_hasher<Variable,Number>,\n\t\t     landmark_ref_equal<Variable,Number>>;\n\n/*\n  Reduced product of a numerical domain with a weighted array\n  graph.\n\n  FIXME: the set of array landmarks are chosen statically before\n  starting the analysis (do_initialization). However, at\n  anytime only those alive (using scalar domain) are\n  considered.\n\n  The main issue is that the landmarks are kept as global\n  state. This is really error-prone. For instance,\n  landmarks are reset each time a new CFG is analyzed. For\n  a summary-based inter-procedural analysis might be ok but\n  not, e.g., for inlining.\n*/\ntemplate<typename NumDom, typename Content, bool IsDistContent = false>\nclass array_sparse_graph_domain final: \n    public abstract_domain<array_sparse_graph_domain<NumDom,Content,IsDistContent>> {\npublic:\n\n  typedef typename NumDom::number_t number_t;\n  typedef typename NumDom::varname_t varname_t;\n      \nprivate:\n\n  static_assert(std::is_same<number_t, typename Content::number_t>::value,\n\t\t\"Scalar and Content domains must have the same number type\");\n  static_assert(std::is_same<varname_t, typename Content::varname_t>::value,\n\t\t\"Scalar and Content domains must have the same varname type\");\n  \n  typedef array_sparse_graph_domain<NumDom,Content,IsDistContent> array_sgraph_domain_t;\n  typedef abstract_domain<array_sgraph_domain_t> abstract_domain_t;\n      \npublic:\n      \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::disjunctive_linear_constraint_system_t;\n  using typename abstract_domain_t::pointer_constraint_t;\n  \n  typedef typename NumDom::variable_t variable_t;\n  typedef typename NumDom::variable_vector_t variable_vector_t;\n  typedef interval<number_t> interval_t;\n      \n  typedef landmark_cst<variable_t,number_t> landmark_cst_t;\n  typedef landmark_var<variable_t,number_t> landmark_var_t;\n  typedef landmark_varprime<variable_t,number_t> landmark_var_prime_t;\n  typedef landmark_ref<variable_t,number_t> landmark_ref_t;\n  typedef array_sparse_graph<landmark_ref_t,Content,IsDistContent> array_sgraph_t;\n\n  //// XXX: make this a template parameter later\n  typedef crab::cfg::var_factory_impl::str_var_alloc_col::varname_t str_varname_t;\n  typedef interval_domain<z_number, str_varname_t> str_interval_dom_t;\n  typedef term::TDomInfo<z_number, varname_t, str_interval_dom_t> idom_info;\n  typedef term_domain<idom_info> expression_domain_t;  \n\nprivate:\n      \n  typedef typename array_sgraph_t::mut_val_ref_t mut_val_ref_t;\n\n  // Quick wrapper to perform efficient unsat queries on the\n  // scalar domain.\n  struct solver_wrapper {\n    // XXX: do not pass by reference\n    NumDom _inv;\n    solver_wrapper(NumDom inv): _inv(inv) { }\n    bool is_unsat(linear_constraint_t cst) {\n      // XXX: it might modify _inv so that's why we make a copy in\n      // the constructor.\n      return array_sgraph_domain_helper_traits<NumDom>::is_unsat(_inv, cst);        \n    }\n  };\n\n  NumDom _scalar;        \n  expression_domain_t _expressions; // map each program variable to a symbolic expression\n  array_sgraph_t _g;        \n\n  // A landmark is either a variable or number that may appear as\n  // an array index. In addition, for each landmark l we keep\n  // track of a prime landmark l' whose meaning is l'=l+1.\n\n  /// === Static data\n  using  lm_map_t = landmark_ref_unordered_map<variable_t, number_t, landmark_ref_t>;\n  static lm_map_t var_landmarks;\n  static lm_map_t cst_landmarks;\n\n  // --- landmark iterators\n  struct get_first : public std::unary_function<typename lm_map_t::value_type,\n\t\t\t\t\t\tlandmark_ref_t> {\n    get_first() {}\n    landmark_ref_t operator()(const typename lm_map_t::value_type &p) const \n    { return p.first; }\n  }; \n  struct get_second : public std::unary_function<typename lm_map_t::value_type,\n\t\t\t\t\t\t landmark_ref_t> {\n    get_second() {}\n    landmark_ref_t operator()(const typename lm_map_t::value_type &p) const \n    { return p.second; }\n  }; \n  typedef boost::transform_iterator<get_first, \n\t\t\t\t    typename lm_map_t::iterator> lm_iterator;\n  typedef boost::transform_iterator<get_second, \n\t\t\t\t    typename lm_map_t::iterator> lm_prime_iterator;\n  typedef boost::iterator_range<lm_iterator> lm_range;\n  typedef boost::iterator_range<lm_prime_iterator> lm_prime_range;\n\n  lm_prime_iterator var_lm_prime_begin()\n  { return boost::make_transform_iterator(var_landmarks.begin(), get_second());}\n  lm_prime_iterator var_lm_prime_end()\n  { return boost::make_transform_iterator(var_landmarks.end(), get_second());}\n  lm_prime_range var_lm_primes() \n  { return boost::make_iterator_range(var_lm_prime_begin(), var_lm_prime_end());}\n\n  lm_prime_iterator cst_lm_prime_begin()\n  { return boost::make_transform_iterator(cst_landmarks.begin(), get_second());}\n  lm_prime_iterator cst_lm_prime_end()\n  { return boost::make_transform_iterator(cst_landmarks.end(), get_second());}\n  lm_prime_range cst_lm_primes() \n  { return boost::make_iterator_range(cst_lm_prime_begin(), cst_lm_prime_end());}\n                                          \n     \npublic:\n\n  template<class CFG>\n  static void do_initialization(CFG cfg) {\n\n    typedef crab::analyzer::array_segmentation<CFG> array_segment_analysis_t;\n    typedef typename array_segment_analysis_t::array_segment_domain_t\n      array_segment_domain_t;\n    typedef crab::analyzer::array_constant_segment_visitor<CFG, array_segment_domain_t>\n      array_cst_segment_visitor_t;\n\n    std::set<landmark_ref_t> lms;\n\n    // add variables \n    array_segment_analysis_t analysis(cfg);\n    analysis.exec();\n    auto var_indexes = analysis.get_variables(cfg.entry());\n\n    if (var_indexes.begin() == var_indexes.end()) {\n      CRAB_WARN(\"No variables found in the cfg. No array graph landmarks will be added\\n\");\n      return;\n    }\n    lms.insert(var_indexes.begin(), var_indexes.end());\n\n    // get variable factory\n    auto &vfac = (*var_indexes.begin()).name().get_var_factory();\n\n    // add constants\n    // make sure 0 is always considered as an array index\n    lms.insert(landmark_ref_t(number_t(0)));\n    typename array_cst_segment_visitor_t::constant_set_t constants;\n    for (auto &bb: boost::make_iterator_range(cfg.begin(), cfg.end())) {\n      auto var_indexes = analysis.get_variables(bb.label());\n      // XXX: use some heuristics to choose \"relevant\" constants\n      array_cst_segment_visitor_t vis(var_indexes);          \n      for (auto &s: boost::make_iterator_range(bb.begin(), bb.end()))\n\ts.accept(&vis);\n      auto cst_indexes = vis.get_constants();\n      lms.insert(cst_indexes.begin(), cst_indexes.end());\n    }\n\n    set_landmarks(lms, vfac);\n  }\n\n  template<class Range, class VarFactory>\n  static void set_landmarks(const Range& lms, VarFactory& vfac) {\n        \n    var_landmarks.clear();\n    cst_landmarks.clear();\n        \n    unsigned num_vl = 0;\n    unsigned num_cl = 0;\n\n    for (auto lm: lms) {\n      switch (lm.kind()) {\n      case LMV: {\n\tauto v = std::static_pointer_cast<const landmark_var_t>(lm._ref)->get_var();\n\tvariable_t v_prime(vfac.get(v.index()));\n\tlandmark_ref_t lm_prime(v_prime, v.name().str());\n\tvar_landmarks.insert(std::make_pair(lm, lm_prime));\n\tnum_vl++;\n\tbreak;\n      }\n      case LMC: {\n\tauto n = std::static_pointer_cast<const landmark_cst_t>(lm._ref)->get_cst();\n\tvariable_t v_prime(vfac.get()); \n\tlandmark_ref_t lm_prime(v_prime, n.get_str());\n\tcst_landmarks.insert(std::make_pair(lm, lm_prime));\n\tnum_cl++;\n\tbreak;\n      }\n      default: \n\tCRAB_ERROR(\"A landmark can only be either variable or constant\");\n      }\n    }\n    CRAB_LOG(\"array-sgraph-domain-landmark\",\n\t     crab::outs() << \"Added \" << num_vl << \" variable landmarks \"\n\t     << \"and \" << num_cl << \" constant landmarks={\";\n\t     bool first=true;\n\t     for (auto &l: var_landmarks) {\n\t       if (!first) crab::outs() << \",\";\n\t       first=false;\n\t       crab::outs() << l.first;\n\t     }\n\t     for (auto &l: cst_landmarks) {\n\t       if (!first) crab::outs() << \",\";\n\t       first=false;\n\t       crab::outs() << l.first;\n\t     }\n\t     crab::outs() << \"}\\n\";\n\t     );\n  }\n\npublic: // public only for tests\n\n  void add_landmark(variable_t v)\n  {\n    landmark_ref_t lm_v(v);\n    landmark_ref_t lm_v_prime(variable_t(v.name().get_var_factory().get(v.name().index())),\n\t\t\t      v.name().str());\n    // add pair  x -> x'\n    var_landmarks.insert(std::make_pair(lm_v, lm_v_prime));\n    // x' = x + 1\n    _scalar += make_prime_relation(lm_v_prime, lm_v);\n\n    // reduce between _scalar and the array graph\n    if (!reduce(_scalar, _g)) { \n      // FIXME: incremental version\n      // TODO: we can assume that the scalar domain is zones so\n      // that we can return the affected edges after each\n      // operation and apply reduction only on those edges. That\n      // would suffice for now. If the scalar domain is not zones\n      // then we don't reduce incrementally.\n      set_to_bottom();\n    }\n\n    CRAB_LOG(\"array-sgraph-domain-landmark\", \n\t     crab::outs() << \"Added landmark \" << v << \"\\n\";);\n  }\n\n  void remove_landmark(variable_t v) {\n    array_forget(v);\n    forget_prime_var(v);\n    var_landmarks.erase(landmark_ref_t(v));\n\n    CRAB_LOG(\"array-sgraph-domain-landmark\", \n\t     crab::outs() << \"Removed landmark \" << v << \"\\n\";);\n  }\n\n\nprivate:\n\n  // By active we mean current variables that are kept track by\n  // the scalar domain.\n  void get_active_landmarks(NumDom &scalar, std::vector<landmark_ref_t> & landmarks) const {\n    landmarks.reserve(cst_landmarks.size());\n    for (auto p: cst_landmarks) { \n      landmarks.push_back(p.first);\n      landmarks.push_back(p.second);\n    }\n    std::vector<variable_t> active_vars;\n    array_sgraph_domain_helper_traits<NumDom>::active_variables(scalar, active_vars);\n    for (auto v: active_vars) {\n      auto it = var_landmarks.find(landmark_ref_t(v));\n      if (it != var_landmarks.end()){\n\tlandmarks.push_back(landmark_ref_t(v)); \n\tlandmarks.push_back(it->second);\n      }\n    }\n  }\n\n  linear_expression_t make_expr(landmark_ref_t x) {\n    switch (x.kind()) {\n    case LMC: \n      return std::static_pointer_cast<landmark_cst_t>(x._ref)->get_cst();\n    case LMV: \n      return variable_t(std::static_pointer_cast<landmark_var_t>(x._ref)->get_var());\n    case LMVP:\n      return variable_t(std::static_pointer_cast<landmark_var_prime_t>\n\t\t\t(x._ref)->get_var());\n    default:\n      CRAB_ERROR(\"unreachable!\");\n    }\n  }\n\n  // make constraint x < y\n  linear_constraint_t make_lt_cst(landmark_ref_t x, landmark_ref_t y) {\n    return linear_constraint_t(make_expr(x) <= make_expr(y) - 1);\n  }\n\n  // make constraint x <= y\n  linear_constraint_t make_leq_cst(landmark_ref_t x, landmark_ref_t y) {\n    return linear_constraint_t(make_expr(x) <= make_expr(y));\n  }\n\n  // make constraint x == y\n  linear_constraint_t make_eq_cst(landmark_ref_t x, landmark_ref_t y) {\n    return linear_constraint_t(make_expr(x) == make_expr(y));\n  }\n\n  // make constraint x' == x+1\n  linear_constraint_t make_prime_relation(landmark_ref_t x_prime, landmark_ref_t x){\n    return linear_constraint_t(make_expr(x_prime) == make_expr(x) + 1);\n  }\n\n  // return true if v is a landmark in the graph\n  bool is_landmark(variable_t v) const {\n    landmark_ref_t lm_v(v);       \n    auto it = var_landmarks.find(lm_v);\n    return (it != var_landmarks.end());\n  }\n\n  // return true if n is a landmark in the graph\n  bool is_landmark(z_number n) const {\n    landmark_ref_t lm_n(n);       \n    auto it = cst_landmarks.find(lm_n);\n    return (it != cst_landmarks.end());\n  }\n\n  // return the prime landmark of v\n  landmark_ref_t get_landmark_prime(variable_t v) const {\n    landmark_ref_t lm_v(v);\n    auto it = var_landmarks.find(lm_v);\n    assert (it != var_landmarks.end());\n    return it->second;\n  }\n\n  // Return the weight from the edge (i, i') otherwise top\n  Content array_edge(variable_t i) {\n    if (is_bottom()) return Content::bottom();\n    if (is_top() || !is_landmark(i)) return Content::top();\n\n    mut_val_ref_t wi;   \n    if (_g.lookup_edge(landmark_ref_t(i), get_landmark_prime(i), &wi))\n      return (Content) wi;\n    else \n      return Content::top();\n  } \n\n  // Remove v from the edge (i,i')\n  void array_edge_forget(variable_t i, variable_t v) {\n    if (is_bottom()) return;\n\n    if (!is_landmark(i)) return;\n\n    mut_val_ref_t wi;          \n    landmark_ref_t lm_i(i);\n    landmark_ref_t lm_i_prime = get_landmark_prime(i);\n    if (_g.lookup_edge(lm_i, lm_i_prime, &wi)) {\n      Content w = (Content) wi;\n      w -= v;\n      // XXX: update_edge closes the array graph\n      _g.update_edge(lm_i, w, lm_i_prime);\n    }\n  }\n\n  // Remove v from all vertices and edges\n  void array_forget(variable_t v) {\n    if (is_bottom()) return;\n    if (!is_landmark(v)) return;\n\n    _g -= landmark_ref_t(v);\n    _g.remove_from_weights(v);\n  }\n\n  // Update the weight from the edge (i, i')\n  void array_edge_update(variable_t i, Content w)\n  {\n    if (is_bottom()) return;\n        \n    //--- strong update\n    if (!is_landmark(i)) return;\n\n    landmark_ref_t lm_i(i);\n    landmark_ref_t lm_i_prime = get_landmark_prime(i);\n        \n    _g.update_edge(lm_i, w, lm_i_prime);\n    mut_val_ref_t wi;          \n    if (!_g.lookup_edge(lm_i, lm_i_prime, &wi))\n      return; \n\n    //--- weak update\n    // An edge (p,q) must be weakened if p <= i <= q and p < q\n    solver_wrapper solve(_scalar);\n    mut_val_ref_t w_pq;\n    for(auto p : _g.verts()) {\n      for(auto e : _g.e_succs(p)) {\n\tauto q = e.vert;\n\tif ((p == lm_i) &&  (q == lm_i_prime)) \n\t  continue;\n\tif (_g.lookup_edge(p, q, &w_pq) && ((Content) w_pq).is_bottom())\n\t  continue;\n\t// we know already that p < q in the array graph\n\n\t// check p <= i  \n\tif (solve.is_unsat(make_leq_cst(p, lm_i)))\n\t  continue;\n\t// check i' <= q\n\tif (solve.is_unsat(make_leq_cst(lm_i_prime, q)))\n\t  continue;\n\n\tw_pq = (Content) w_pq | (Content) wi;\n      }\n    }\n  }\n\n  // x := x op k \n  template<typename VarOrNum>\n  void apply_one_variable(operation_t op, variable_t x, VarOrNum k) { \n    if (is_bottom()) return;\n\n    if (!is_landmark(x)) {\n      // If x is not a landmark we just apply the operation on the\n      // scalar domain and return.\n      apply_only_scalar(op, x, x, k);\n      return;\n    }\n\n    landmark_ref_t lm_x(x);\n    landmark_ref_t lm_x_prime = get_landmark_prime(x);\n        \n    /// --- Add x_old and x_old' to store old values of x and x'\n\n    variable_t x_old(x.name().get_var_factory().get());      \n    variable_t x_old_prime(x.name().get_var_factory().get()); \n    landmark_ref_t lm_x_old(x_old);\n    landmark_ref_t lm_x_old_prime(x_old_prime, x_old.name().str());\n    var_landmarks.insert(std::make_pair(lm_x_old, lm_x_old_prime));\n    // x_old = x\n    _scalar.assign(x_old, x); \n    // relation between x_old and x' \n    _scalar += make_prime_relation(lm_x_old_prime, lm_x_old);\n    //_scalar += make_eq_cst(lm_x_old_prime, lm_x_prime);      \n\n    /*** Incremental graph reduction ***/\n    //// x_old  has all the x predecessors and successors \n    _g.expand(lm_x, lm_x_old); \n    //// x_old' has all the x' predecessors and successors \n    _g.expand(lm_x_prime, lm_x_old_prime); \n    //// edges between x and x_old \n    _g.update_edge(lm_x, Content::bottom(), lm_x_old);        \n    _g.update_edge(lm_x_old, Content::bottom(), lm_x);        \n    //// edges between x' and x_old' \n    _g.update_edge(lm_x_prime, Content::bottom(), lm_x_old_prime);        \n    _g.update_edge(lm_x_old_prime, Content::bottom(), lm_x_prime);        \n    //// edges between x_old and x_old'\n    mut_val_ref_t w;   \n    if (_g.lookup_edge(lm_x, lm_x_prime, &w))\n      _g.update_edge(lm_x_old,(Content) w, lm_x_old_prime);        \n    _g.update_edge(lm_x_old_prime, Content::bottom(), lm_x_old);        \n\n    /// --- Remove x and x'\n    _g -= lm_x;\n    _g -= lm_x_prime;\n\n    /// --- Perform operation in the scalar domain\n    _scalar.apply(op, x, x, k); \n\n    //restore relation between x and x'\n    _scalar.apply(OP_ADDITION, get_var(lm_x_prime), x, 1);\n    //_scalar -= get_var(lm_x_prime);\n    //_scalar += make_prime_relation(lm_x_prime, lm_x);\n\n    if (!reduce(_scalar, _g)) { // FIXME: incremental version\n      set_to_bottom();\n      return;\n    }\n\n    /// --- Remove x_old and x_old'\n    _g -= lm_x_old;\n    _g -= lm_x_old_prime;\n    _scalar -= x_old;\n    _scalar -= x_old_prime;\n    var_landmarks.erase(lm_x_old);\n  }\n\n  // remove v' from scalar and array graph\n  void forget_prime_var(variable_t v) {\n    if (!is_landmark(v)) return;\n        \n    landmark_ref_t lm_v_prime = get_landmark_prime(v);\n    _scalar -= get_var(lm_v_prime);\n    // XXX: v' cannot appear in the array weights so we do not\n    //      need to call array_forget.\n    _g -= lm_v_prime;        \n  }\n\n  // perform the operation in the scalar domain assuming that\n  // nothing can be done in the graph domain.\n  template<class Op, class K>\n  void apply_only_scalar(Op op, variable_t x, variable_t y, K k) {\n    _scalar.apply(op, x, y, k);\n\n    // Abstract x in the array graph\n    if (is_landmark(x)){ \n      array_forget(x);     // remove x from the array graph\n      forget_prime_var(x); // remove x' from scalar and array graph\n      /// XXX: I think no need to reduce here\n    }\n  }\n            \n\n  // return a pair with the normalized offset and a bool that is\n  // true if a new landmark was added in the array graph\n  std::pair<variable_t,bool> normalize_offset (variable_t o, z_number n)\n  {\n    CRAB_LOG(\"array-sgraph-domain-norm\",\n\t     crab::outs() << \"BEFORE NORMALIZE OFFSET: expressions=\"\n\t     << _expressions << \"\\n\");\n\n    // --- create a fresh variable no such that no := o;\n    variable_t no(o.name().get_var_factory().get());\n    _expressions.assign(no, o);\n\n    // -- apply no := no / n; in the expressions domain\n    _expressions.apply(operation_t::OP_SDIV, no, no, n);\n        \n    // -- simplify the expression domain \n    bool simp_done = _expressions.simplify(no);\n\n    CRAB_LOG(\"array-sgraph-domain-norm\",\n\t     crab::outs() << \"AFTER NORMALIZE OFFSET: expressions=\"\n\t     << _expressions << \"\\n\");\n\n    if (!simp_done) {\n      CRAB_LOG(\"array-sgraph-domain-norm\",\n\t       crab::outs() << \"NO NORMALIZATION done using the expression abstraction\\n\");\n\n      // cleanup of the expression abstraction\n      _expressions -= no;\n\n      bool added_lm = false;\n      if (!is_landmark(o)) \n\t{ add_landmark(o); added_lm = true; } \n                      \n      return std::make_pair(o, added_lm);\n    }\n\n    CRAB_LOG(\"array-sgraph-domain-norm\",\n\t     crab::outs() << \"NORMALIZATION DONE! using the expression abstraction\\n\");\n                \n    // -- propagate equalities from _expressions to _scalar\n    linear_constraint_system_t e_csts;\n    reduced_domain_traits<expression_domain_t>::\n      extract(_expressions, no, e_csts, /*only_equalities=*/ false);\n    _scalar += e_csts;\n        \n    // -- add landmark for the new array index\n    add_landmark(no);\n        \n    // cleanup of the expression abstraction\n    _expressions -= no;\n        \n    return std::make_pair(no, true);\n  }\n\n  // T1 and T2 are either variable_t or z_number\n  template<typename T1, typename T2>\n  void array_init(variable_t arr, T1 src, T2 dst, linear_expression_t val)\n  {\n    if (!is_landmark(src)) {\n      crab::outs() << \"WARNING no landmark found for \" << src << \"\\n\";\n      return;\n    }\n\n    if (!is_landmark(dst)) {\n      crab::outs() << \"WARNING no landmark found for \" << dst << \"\\n\";\n      return;\n    }\n       \n    landmark_ref_t lm_src(src);\n    landmark_ref_t lm_dst(dst); \n\n    Content w = Content::top();\n    array_sparse_graph_impl::propagate_between_weight_and_scalar\n      (_scalar, val, arr.get_type(), w, arr);\n    _g.update_edge(lm_src, w, lm_dst);        \n  }\n\n  interval_t to_interval(linear_expression_t expr) {\n    interval_t r(expr.constant());\n    for (typename linear_expression_t::iterator it = expr.begin(); \n\t it != expr.end(); ++it) {\n      interval_t c(it->first);\n      r += c * _scalar[it->second];\n    }\n    return r;\n  }\n      \npublic:\n\n  // The reduction consists of detecting dead segments so it is\n  // done only in one direction (scalar -> array graph). Note that\n  // whenever an edge becomes bottom closure is also happening.\n  // Return false if bottom is detected during the reduction.\n  bool reduce(NumDom &scalar, array_sgraph_t &g) {\n    crab::CrabStats::count(getDomainName() + \".count.reduce\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".reduce\");\n\n    scalar.normalize();\n    g.normalize();\n\n    if (scalar.is_bottom() || g.is_bottom())\n      return false;\n\n    if (!scalar.is_top()) { \n      std::vector<landmark_ref_t> active_landmarks;\n      get_active_landmarks(scalar, active_landmarks);\n      solver_wrapper solve(scalar);\n      for (auto lm_s : active_landmarks)\n\tfor (auto lm_d : active_landmarks) {\n\t  // XXX: we do not exploit the following facts:\n\t  //   - i < i' is always sat\n\t  //   - i' < i is always unsat\n\t  //   - if i < j  unsat then i' < j unsat.\n\t  //   - if i < j' unsat then i' < j unsat.\n\t  if ((lm_s == lm_d) || solve.is_unsat(make_lt_cst(lm_s,lm_d))) {\n\t    g.update_edge(lm_s, Content::bottom(), lm_d);\n\t  }\n\t}\n    }        \n    return (!g.is_bottom());\n  }\n\n\n      \n  void set_to_top() { \n    array_sgraph_domain_t abs(false);\n    std::swap(*this, abs);\n  }\n\n  void set_to_bottom() {\n    _scalar = NumDom::bottom();\n    _expressions = expression_domain_t::bottom();\n    _g.set_to_bottom();\n  }\n      \n  // void set_to_bottom() {\n  //   array_sgraph_domain_t abs(true);\n  // \tstd::swap(*this, abs);\n  // }\n\n  array_sparse_graph_domain(bool is_bottom=false)\n    : _scalar(NumDom::top()), _expressions(expression_domain_t::top()), \n      _g(array_sgraph_t::top()) { \n    if (is_bottom) \n      set_to_bottom();\n  }\n\n  array_sparse_graph_domain(const NumDom& s, const expression_domain_t& e, \n\t\t\t    const array_sgraph_t& g)\n    : _scalar(s), _expressions(e), _g(g) { \n    if (_scalar.is_bottom() || _expressions.is_bottom() || _g.is_bottom())\n      set_to_bottom();\n  }\n    \n  array_sparse_graph_domain(NumDom &&s, expression_domain_t &&e, \n\t\t\t    array_sgraph_t &&g)\n    : _scalar(std::move(s)), _expressions(std::move(e)), _g(std::move(g)) { \n    if(_scalar.is_bottom() || _expressions.is_bottom() || _g.is_bottom())\n      set_to_bottom();\n  }\n\n  array_sparse_graph_domain(const array_sgraph_domain_t&o)\n    : _scalar(o._scalar), _expressions(o._expressions), _g(o._g) { \n    crab::CrabStats::count(getDomainName() + \".count.copy\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".copy\");\n  }\n\n  array_sparse_graph_domain(array_sgraph_domain_t &&o)\n    : _scalar(std::move(o._scalar)), \n      _expressions(std::move(o._expressions)), \n      _g(std::move(o._g)) { \n  }\n\n  array_sgraph_domain_t& operator=(const array_sgraph_domain_t& o) {\n    crab::CrabStats::count(getDomainName() + \".count.copy\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".copy\");\n    if(this != &o) {\n      _scalar = o._scalar;\n      _expressions = o._expressions;\n      _g = o._g;\n    }\n    return *this;\n  }\n\n  array_sgraph_domain_t& operator=(array_sgraph_domain_t &&o) {\n    _scalar = std::move(o._scalar);\n    _expressions = std::move(o._expressions);\n    _g = std::move(o._g);\n    return *this;\n  }\n      \n  bool is_top() {\n    return _scalar.is_top() && _expressions.is_top() && _g.is_top();\n  }\n      \n  bool is_bottom() {\n    return _scalar.is_bottom() || _expressions.is_bottom() || _g.is_bottom();\n  }\n\n  bool operator<=(array_sgraph_domain_t o) {\n    crab::CrabStats::count(getDomainName() + \".count.leq\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".leq\");\n\n    CRAB_LOG(\"array-sgraph-domain\",\n\t     crab::outs() << \"Leq \" << *this << \" and\\n\"  << o << \"=\\n\";);\n    bool res = (_scalar <= o._scalar) && \n      (_expressions <= o._expressions) && \n      (_g <= o._g);\n    CRAB_LOG(\"array-sgraph-domain\", crab::outs() << res << \"\\n\";);\n    return res;\n  }\n\n  void operator|=(array_sgraph_domain_t o)  {\n    *this = (*this | o);\n  }\n\n  array_sgraph_domain_t operator|(array_sgraph_domain_t o){\n    crab::CrabStats::count(getDomainName() + \".count.join\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".join\");\n\n    CRAB_LOG(\"array-sgraph-domain\",\n\t     crab::outs() << \"Join \" << *this << \" and \"  << o << \"=\\n\");\n    array_sgraph_domain_t join(_scalar | o._scalar, \n\t\t\t       _expressions | o._expressions,\n\t\t\t       _g | o._g);\n    CRAB_LOG(\"array-sgraph-domain\", crab::outs() << join << \"\\n\";);\n    return join;\n  }\n\n  array_sgraph_domain_t widening_thresholds(array_sgraph_domain_t o, \n\t\t\t\t\t    const iterators::thresholds<number_t>& ts) {\n    crab::CrabStats::count(getDomainName() + \".count.widening\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".widening\");\n\n    CRAB_LOG(\"array-sgraph-domain\",\n\t     crab::outs() << \"Widening (w/ thresholds) \" << *this << \" and \"\n\t     << o << \"=\\n\";);\n    auto widen_scalar(_scalar.widening_thresholds(o._scalar,ts));\n    auto widen_expr(_expressions.widening_thresholds(o._expressions,ts));\n    auto widen_g(_g.widening_thresholds(o._g,ts));\n    if (!reduce(widen_scalar, widen_g)) {\n      CRAB_LOG(\"array-sgraph-domain\", crab::outs() << \"_|_\\n\";);\n      return array_sgraph_domain_t::bottom();\n    } else {\n      array_sgraph_domain_t widen(widen_scalar, widen_expr, widen_g);\n      CRAB_LOG(\"array-sgraph-domain\", crab::outs() << widen << \"\\n\";);\n      return widen;\n    }\n  }\n\n  array_sgraph_domain_t operator||(array_sgraph_domain_t o){\n    crab::CrabStats::count(getDomainName() + \".count.widening\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".widening\");\n\n    CRAB_LOG(\"array-sgraph-domain\",\n\t     crab::outs() << \"Widening \" << *this << \" and \"  << o << \"=\\n\");        \n    auto widen_scalar(_scalar || o._scalar);\n    auto widen_expr(_expressions || o._expressions);\n    auto widen_g(_g || o._g);\n    if (!reduce(widen_scalar, widen_g)) {\n      CRAB_LOG(\"array-sgraph-domain\", crab::outs() << \"_|_\\n\";);\n      return array_sgraph_domain_t::bottom();\n    } else {\n      array_sgraph_domain_t widen(widen_scalar, widen_expr, widen_g);\n      CRAB_LOG(\"array-sgraph-domain\", crab::outs() << widen << \"\\n\";);\n      return widen;\n    }\n  }\n\n  array_sgraph_domain_t operator&(array_sgraph_domain_t o){\n    crab::CrabStats::count(getDomainName() + \".count.meet\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".meet\");\n\n    CRAB_LOG(\"array-sgraph-domain\",\n\t     crab::outs() << \"Meet \" << *this << \" and \"  << o << \"=\\n\");\n    auto meet_scalar(_scalar & o._scalar);\n    auto meet_expr(_expressions & o._expressions);\n    auto meet_g(_g & o._g);\n    if (!reduce(meet_scalar, meet_g)) {\n      CRAB_LOG(\"array-sgraph-domain\", crab::outs() << \"_|_\\n\";);\n      return array_sgraph_domain_t::bottom();\n    } else {\n      array_sgraph_domain_t meet(meet_scalar, meet_expr, meet_g);\n      CRAB_LOG(\"array-sgraph-domain\", crab::outs() << meet << \"\\n\";);\n      return meet;\n    }\n  }\n\n  array_sgraph_domain_t operator&&(array_sgraph_domain_t o){\n    crab::CrabStats::count(getDomainName() + \".count.narrowing\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".narrowing\");\n\n    CRAB_LOG(\"array-sgraph-domain\",\n\t     crab::outs() << \"Narrowing \" << *this << \" and \"  << o << \"=\\n\");\n    auto narrow_scalar(_scalar && o._scalar);\n    auto narrow_expr(_expressions && o._expressions);\n    auto narrow_g(_g && o._g);\n    if (!reduce(narrow_scalar, narrow_g)) {\n      CRAB_LOG(\"array-sgraph-domain\", crab::outs() << \"_|_\\n\";);\n      return array_sgraph_domain_t::bottom();\n    } else {\n      array_sgraph_domain_t narrow(narrow_scalar, narrow_expr, narrow_g);\n      CRAB_LOG(\"array-sgraph-domain\", crab::outs() << narrow << \"\\n\";);\n      return narrow;\n    }\n  }\n\n  void operator-=(variable_t v) {\n    crab::CrabStats::count(getDomainName() + \".count.forget\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".forget\");\n\n    if (is_bottom())\n      return;\n\n    // remove v from scalar and array graph\n    _scalar -= v;\n    // remove v from expressions\n    _expressions -= v;\n        \n    if (is_landmark(v)) {\n      array_forget(v);\n      // remove v' from scalar and array graph\n      forget_prime_var(v);\n    }\n  }\n\n\n  void project(const variable_vector_t& variables) {\n    crab::CrabStats::count(getDomainName() + \".count.project\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".project\");\n\n    if (is_bottom() || is_top()) {\n      return;\n    }\n    if (variables.empty()) {\n      set_to_top();\n      return;\n    }\n\n    std::set<variable_t> keep_vars(variables.begin(), variables.end());\n    std::vector<variable_t> active_vars;\t\n    array_sgraph_domain_helper_traits<NumDom>::active_variables(_scalar, active_vars);\n    for (auto v: active_vars) {\n      if (!keep_vars.count(v)) {\n\tarray_forget(v);\n\tforget_prime_var(v);\n      }\n    }\n\n    _scalar.project(variables);\n    _expressions.project(variables);\n  }\n\n  void forget(const variable_vector_t& variables) {\n    if (is_bottom() || is_top()) {\n      return;\n    }\n    for (variable_t v: variables) {\n      this->operator-=(v);\n    }\n  }\n\n  void expand(variable_t var, variable_t new_var) {\n    CRAB_WARN(\"array_graph_domain expand not implemented\");\t\n  }\n\n  void normalize() {\n    CRAB_WARN(\"array_graph_domain normalize not implemented\");\n  }          \n\n  void minimize() {\n    _scalar.minimize();\n    _expressions.minimize();\n  }          \n      \n  void operator+=(linear_constraint_system_t csts) \n  {\n    crab::CrabStats::count(getDomainName() + \".count.add_constraints\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".add_constraints\");\n\n    if (is_bottom()) return;\n        \n    _scalar += csts;\n    _expressions += csts;\n\n    if (!reduce(_scalar, _g)) { // FIXME: incremental version\n      set_to_bottom();\n      return;\n    }\n    CRAB_LOG(\"array-sgraph-domain\", \n\t     crab::outs() << \"Assume(\"<< csts<< \") --- \"<< *this<<\"\\n\";);\n  }\n\n  void assign(variable_t x, linear_expression_t e) {\n    assign(x, e, true);\n  }\n\n  // Perform the operation in the scalar (optionally expression)\n  // domain and reduce.\n  // \n  // NOTE: if the assignment is something like i = i + k then we\n  // will lose precision in the array graph. This kind of\n  // assignments should be managed by the apply methods instead.\n  void assign(variable_t x, linear_expression_t e, bool update_expressions)  {\n    crab::CrabStats::count(getDomainName() + \".count.assign\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".assign\");\n\n    if (is_bottom()) return;\n\n    if (auto y = e.get_variable()) {\n      // skip x:=x \n      if ((*y) == x) \n\treturn;\n    }\n            \n    _scalar.assign(x, e);\n    if (update_expressions) \n      _expressions.assign(x, e);\n\n    if (is_landmark(x)) {\n      array_forget(x);\n      // remove x' from scalar and array graph\n      forget_prime_var(x);\n      // restore the relationship between x and x'\n      _scalar.apply(OP_ADDITION, get_var(get_landmark_prime(x)), x, 1);\n      // XXX: is it needed ??\n      //_g.close_edge(landmark_ref_t(x), get_landmark_prime(x));\n    }\n\n    if (!reduce(_scalar, _g)) { // FIXME: incremental version\n      set_to_bottom();\n      return;\n    }\n\n    CRAB_LOG(\"array-sgraph-domain\", \n\t     crab::outs() << \"Assign \"<<x<<\" := \"<<e<<\" ==> \"<<*this<<\"\\n\";);\n  }\n\n  void apply(operation_t op, variable_t x, variable_t y, number_t z) {\n    if(x == y) {\n      crab::CrabStats::count(getDomainName() + \".count.apply\");\n      crab::ScopedCrabStats __st__(getDomainName() + \".apply\");\n      _expressions.apply(op, x, y, z);\n      apply_one_variable<number_t>(op, x, z);\n      CRAB_LOG(\"array-sgraph-domain\",\n\t       crab::outs() << \"Apply \"<<x<<\" := \"<<y<<\" \"<<op<<\" \"<<z<<\" ==> \"\n\t       << *this<<\"\\n\";); \n    }\n    else {\n      switch (op) {\n      case OP_ADDITION:\n\tassign(x, y + z);\n\tbreak;\n      case OP_SUBTRACTION:\n\tassign(x, y - z);\n\tbreak;\n      case OP_MULTIPLICATION:\n\tassign(x, y * z);\n\tbreak;\n      default:\n\tCRAB_WARN(op, \"not implemented in array-sgraph-domain\\n\");\n      }\n    }\n  }\n      \n  void apply(operation_t op, variable_t x, variable_t y, variable_t z)  {\n    if (x==y) {\n      crab::CrabStats::count(getDomainName() + \".count.apply\");\n      crab::ScopedCrabStats __st__(getDomainName() + \".apply\");\n      _expressions.apply(op, x, y, z);\n      apply_one_variable<variable_t>(op, x, z);\n      CRAB_LOG(\"array-sgraph-domain\", \n\t       crab::outs() << \"Apply \"<<x<<\" := \"<<y<<\" \"<<op<<\" \"<<z<<\" ==> \"\n\t       << *this<<\"\\n\";);\n    }\n    else {\n      switch (op) {\n      case OP_ADDITION:\n\tassign(x, y + z);\n\tbreak;\n      case OP_SUBTRACTION:\n\tassign(x, y - z);\n\tbreak;\n      default:\n\tCRAB_WARN(op, \"not implemented in array-sgraph-domain\");\n      }\n    }\n  }\n  // backward arithmetic operations\n\n  void backward_assign(variable_t x, linear_expression_t e,\n\t\t       array_sgraph_domain_t invariant)  {\n    operator-=(x);\n    CRAB_WARN(\"backward assign not implemented\");\n  }\n      \n  void backward_apply(operation_t op,\n\t\t      variable_t x, variable_t y, number_t z,\n\t\t      array_sgraph_domain_t invariant)  {\n    operator-=(x);\n    CRAB_WARN(\"backward apply not implemented\");\n  }\n      \n  void backward_apply(operation_t op,\n\t\t      variable_t x, variable_t y, variable_t z,\n\t\t      array_sgraph_domain_t invariant) {\n\n    operator-=(x);\n    CRAB_WARN(\"backward apply not implemented\");\n  }\n\n  // boolean operations\n  void assign_bool_cst(variable_t lhs, linear_constraint_t rhs) {\n    operator-=(lhs);\n    CRAB_WARN(\"assign_bool_cst not implemented in array-sgraph-domain\");\t\n  }\n      \n  void assign_bool_var(variable_t lhs, variable_t rhs, bool is_not_rhs) {\n    operator-=(lhs);\n    CRAB_WARN(\"assign_bool_var not implemented in array-sgraph-domain\");\t\t\n  }\n      \n  void apply_binary_bool(bool_operation_t op, variable_t x,variable_t y,variable_t z) {\n    operator-=(x);\n    CRAB_WARN(\"apply_binary_bool not implemented in array-sgraph-domain\");\t\n  }\n      \n  void assume_bool(variable_t v, bool is_negated) {\n    CRAB_WARN(\"assume_bool not implemented in array-sgraph-domain\");\t\t\n  }\n      \n  // backward boolean operations\n  void backward_assign_bool_cst(variable_t lhs, linear_constraint_t rhs,\n\t\t\t\tarray_sgraph_domain_t invariant) {\n    operator-=(lhs);\n    CRAB_WARN(\"backward_assign_bool_cst not implemented in array-sgraph-domain\");\t\t\n  }\n      \n  void backward_assign_bool_var(variable_t lhs, variable_t rhs, bool is_not_rhs,\n\t\t\t\tarray_sgraph_domain_t invariant) {\n    operator-=(lhs);\n    CRAB_WARN(\"backward_assign_bool_var not implemented in array-sgraph-domain\");\t\t\n  }\n      \n  void backward_apply_binary_bool(bool_operation_t op,\n\t\t\t\t  variable_t x,variable_t y,variable_t z,\n\t\t\t\t  array_sgraph_domain_t invariant) {\n    operator-=(x);\n    CRAB_WARN(\"backward_apply_binary_bool not implemented in array-sgraph-domain\");\t\t\n  }\n      \n  // cast operations\n      \n  void apply(int_conv_operation_t op, variable_t dst, variable_t src) {\n    _expressions.apply(op, dst, src);\n    // assume unlimited precision so widths are ignored.\n    assign(dst, src, false);\n  }\n      \n  // bitwise operations\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    _expressions.apply(op, x, y, z);\n    // XXX: we give up soundly in the graph domain\n    apply_only_scalar(op, x, y, z);\n  }\n      \n  void apply(bitwise_operation_t op, variable_t x, variable_t y, number_t k) {\n    crab::CrabStats::count(getDomainName() + \".count.apply\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".apply\");\n\n    _expressions.apply(op, x, y, k);\n    // XXX: we give up soundly in the graph domain\n    apply_only_scalar(op, x, y, k);\n  }\n      \n  interval_t operator[](variable_t v)  {\n    return _scalar[v];\n  }\n\n  // pointer_operators_api\n  virtual void pointer_load(variable_t lhs, variable_t rhs) override {\n    _scalar.pointer_load(lhs,rhs);\n  }\n      \n  virtual void pointer_store(variable_t lhs, variable_t rhs) override {\n    _scalar.pointer_store(lhs,rhs);\n  } \n      \n  virtual void pointer_assign(variable_t lhs, variable_t rhs,\n\t\t\t      linear_expression_t offset) override {\n    _scalar.pointer_assign(lhs,rhs,offset);\n  }\n      \n  virtual void pointer_mk_obj(variable_t lhs, ikos::index_t address) override {\n    _scalar.pointer_mk_obj(lhs, address);\n  }\n      \n  virtual void pointer_function(variable_t lhs, varname_t func) override {\n    _scalar.pointer_function(lhs, func);\n  }\n      \n  virtual void pointer_mk_null(variable_t lhs) override {\n    _scalar.pointer_mk_null(lhs);\n  }\n      \n  virtual void pointer_assume(pointer_constraint_t cst) override {\n    _scalar.pointer_assume(cst);\n  }    \n      \n  virtual void pointer_assert(pointer_constraint_t cst) override {\n    _scalar.pointer_assert(cst);\n  }    \n        \n\n  // array_operators_api       \n\n  virtual void array_init(variable_t a,\n\t\t\t  linear_expression_t /*elem_size*/,\n\t\t\t  linear_expression_t lb_idx,\n\t\t\t  linear_expression_t ub_idx, \n\t\t\t  linear_expression_t val) override {\n\n    auto lb_var_opt = lb_idx.get_variable();\n    auto ub_var_opt = ub_idx.get_variable();\n\n    if (lb_idx.is_constant() && ub_idx.is_constant())\n      array_init(a, lb_idx.constant(), ub_idx.constant(), val);\n    else if (lb_idx.is_constant() && ub_var_opt)\n      array_init(a, lb_idx.constant(), *ub_var_opt, val);\n    else if (lb_var_opt && ub_idx.is_constant())\n      array_init(a, *lb_var_opt, ub_idx.constant(), val);\n    else if (lb_var_opt && ub_var_opt)\n      array_init(a, *lb_var_opt, *ub_var_opt, val);\n    else\n      CRAB_ERROR(\"unreachable\");\n  }\n\n  virtual void array_load(variable_t lhs,\n\t\t\t  variable_t a, linear_expression_t elem_size,\n\t\t\t  linear_expression_t i) override  {\n    crab::CrabStats::count(getDomainName() + \".count.load\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".load\");\n\n    auto vi = i.get_variable();\n    if (!vi) {\n      CRAB_WARN(\"TODO: array load index must be a variable\");\n      return;\n    }\n\n    // -- normalization ensures that closure and reduction have\n    // -- been applied.\n    interval_t i_elem_size = to_interval(elem_size);\n    boost::optional<number_t> n_elem_size = i_elem_size.singleton();\n    if (!n_elem_size) {\n      CRAB_WARN(\"array_graph ignored array load because element size is not constant\");\n      return;\n    }\n    unsigned num_bytes =(long)*n_elem_size; \n    auto p = normalize_offset(*vi, num_bytes); \n    variable_t norm_idx = p.first;\n\n    // #if 0\n    // if (is_landmark(norm_idx)) {\n    //   landmark_ref_t lm_norm_idx(norm_idx);\n    //   landmark_ref_t lm_norm_idx_prime = get_landmark_prime(norm_idx);\n          \n    //   _g.close_edge(lm_norm_idx, lm_norm_idx_prime);\n    //   crab::outs() << \"#### 1 \" << _g << \"\\n\"; \n          \n    //   Content w;\n    //   w += linear_constraint_t(linear_expression_t(lhs) == linear_expression_t(a));\n    //   crab::outs() << \"#### 2 \" << w << \"\\n\";\n    //   //_g.update_edge_unclosed(lm_norm_idx, w, lm_norm_idx_prime);\n    //   _g.update_edge(lm_norm_idx, w, lm_norm_idx_prime);\n    // }\n    // #endif \n\n    Content w = array_edge(norm_idx);\n\n    if (a.get_type() == ARR_INT_TYPE || a.get_type() == ARR_REAL_TYPE) {\n      // Only non-relational numerical invariants are\n      // propagated from the graph domain to the expressions domain.\n      _expressions.set(lhs, w[a]);\n    }\n\n    array_sparse_graph_impl::\n      propagate_between_weight_and_scalar(w, a, a.get_type(), _scalar, lhs);\n        \n    // if normalize_offset created a landmark we remove it here to\n    // keep smaller array graph\n    if (p.second) remove_landmark(norm_idx); \n\n    /// XXX: due to the above simplification we need to reduce\n    /// only if the content of an array cell can be an index.\n    if (is_landmark(lhs))\n      if (!reduce(_scalar,_g)) // FIXME: incremental version\n\tset_to_bottom();\n        \n    CRAB_LOG(\"array-sgraph-domain\",\n\t     crab::outs() << \"Array read \"<<lhs<<\" := \"<< a<<\"[\"<<i<<\"] ==> \"\n\t     << *this <<\"\\n\";);    \n  }\n\n  virtual void array_store(variable_t a, linear_expression_t elem_size,\n\t\t\t   linear_expression_t i, linear_expression_t val, \n\t\t\t   bool /*is_strong_update*/) override {\n    crab::CrabStats::count(getDomainName() + \".count.store\");\n    crab::ScopedCrabStats __st__(getDomainName() + \".store\");\n\n    auto vi = i.get_variable();\n    if (!vi) {\n      CRAB_WARN(\"TODO: array store index must be a variable\");\n      return;\n    }\n\n    Content w = Content::top();\n    array_sparse_graph_impl::\n      propagate_between_weight_and_scalar(_scalar, val, a.get_type(), w, a);\n\n    interval_t i_elem_size = to_interval(elem_size);\n    boost::optional<number_t> n_elem_size = i_elem_size.singleton();\n    if (!n_elem_size) {\n      CRAB_WARN(\"array_graph ignored array store because element size is not constant\");\n      return;\n    }\n    unsigned num_bytes = (long)*n_elem_size; \n    auto p = normalize_offset(*vi, num_bytes);\n    variable_t norm_idx = p.first;\n\n    array_edge_forget(norm_idx, a);\n    array_edge_update(norm_idx, w);\n\n    // XXX: since we do not propagate from the array weights to\n    // the scalar domain I think we don't need to reduce here.\n\n    CRAB_LOG(\"array-sgraph-domain\",\n\t     crab::outs() << \"Array write \"<<a<<\"[\"<<i<<\"] := \"\n\t     << val << \" ==> \"\n\t     << *this <<\"\\n\";);\n  }\n\n  virtual void array_store(variable_t a_new, variable_t a_old,\n\t\t\t   linear_expression_t elem_size,\n\t\t\t   linear_expression_t i, linear_expression_t val, \n\t\t\t   bool /*is_strong_update*/) override {\n    CRAB_WARN(\"array_store in array_sparse_graph not implemented\");\n  }\n  \n  virtual void array_store_range(variable_t a, linear_expression_t elem_size,\n\t\t\t\t linear_expression_t i, linear_expression_t j, \n\t\t\t\t linear_expression_t val) override {\n    CRAB_WARN(\"array_store_range in array_sparse_graph not implemented\");\n  }\n\n  virtual void array_store_range(variable_t a_new, variable_t a_old,\n\t\t\t\t linear_expression_t elem_size,\n\t\t\t\t linear_expression_t i, linear_expression_t j, \n\t\t\t\t linear_expression_t val) override {\n    CRAB_WARN(\"array_store_range in array_sparse_graph not implemented\");\n  }\n  \n  virtual void array_assign(variable_t lhs, variable_t rhs) override {\n    CRAB_WARN(\"array_assign in array_sparse_graph not implemented\");\n  }\n      \n  // backward array operations\n  void backward_array_init(variable_t a, linear_expression_t elem_size,\n\t\t\t   linear_expression_t lb_idx, linear_expression_t ub_idx, \n\t\t\t   linear_expression_t val, array_sgraph_domain_t invariant) {\n    CRAB_WARN(\"backward_array_init in array_sparse_graph domain not implemented\");\t  \n  }\t\n  void backward_array_load(variable_t lhs,\n\t\t\t   variable_t a, linear_expression_t elem_size,\n\t\t\t   linear_expression_t i, array_sgraph_domain_t invariant) {\n    CRAB_WARN(\"backward_array_load in array_sparse_graph domain not implemented\"); \n    this->operator-=(lhs);\n  }\n  void backward_array_store(variable_t a, linear_expression_t elem_size,\n\t\t\t    linear_expression_t i, linear_expression_t v, \n\t\t\t    bool is_strong_update, array_sgraph_domain_t invariant) {\n    CRAB_WARN(\"backward_array_store in array_sparse_graph domain not implemented\"); \n  }\n  void backward_array_store(variable_t a_new, variable_t a_old,\n\t\t\t    linear_expression_t elem_size,\n\t\t\t    linear_expression_t i, linear_expression_t v, \n\t\t\t    bool is_strong_update, array_sgraph_domain_t invariant) {\n    CRAB_WARN(\"backward_array_store in array_sparse_graph domain not implemented\"); \n  }  \n  void backward_array_store_range(variable_t a, linear_expression_t elem_size,\n\t\t\t\t  linear_expression_t i, linear_expression_t j,\n\t\t\t\t  linear_expression_t v, array_sgraph_domain_t invariant) {\n    CRAB_WARN(\"backward_array_store_range in array_sparse_graph domain not implemented\");\n  }\n  void backward_array_store_range(variable_t a_new, variable_t a_old,\n\t\t\t\t  linear_expression_t elem_size,\n\t\t\t\t  linear_expression_t i, linear_expression_t j,\n\t\t\t\t  linear_expression_t v, array_sgraph_domain_t invariant) {\n    CRAB_WARN(\"backward_array_store_range in array_sparse_graph domain not implemented\");\n  }  \n  void backward_array_assign(variable_t lhs, variable_t rhs,\n\t\t\t     array_sgraph_domain_t invariant) {\n    CRAB_WARN(\"backward_array_assign in array_sparse_graph domain not implemented\"); \n  }\n      \n  void write(crab_os& o) {\n#if 1\n    NumDom copy_scalar(_scalar);\n    array_sgraph_t copy_g(_g);\n    // Remove all primed variables for pretty printing\n    for(auto lm: var_lm_primes()) {\n      copy_scalar -= get_var(lm);\n      copy_g -= lm;\n    }\n    for(auto lm: cst_lm_primes()) {\n      copy_scalar -= get_var(lm);\n      copy_g -= lm;\n    }\n    o << \"(\" << copy_scalar  << \",\";\n    copy_g.write(o,false);  // we do not print bottom edges\n    o << \")\";\n    //o << \"##\" << _expressions;\n#else\n    o << \"(\" \n      << \"S=\" << _scalar  << \",\"\n      << \"E=\" << _expressions  << \",\"\n      << \"G=\" << _g\n      << \")\";\n#endif \n  }\n\n  // XXX: the array domain is disjunctive so it is not really\n  // useful to express it through a conjunction of linear\n  // constraints\n  linear_constraint_system_t to_linear_constraint_system(){\n    CRAB_ERROR(\"array-sgraph does not implement to_linear_constraint_system\");\n  }\n\n  disjunctive_linear_constraint_system_t to_disjunctive_linear_constraint_system(){\n    CRAB_ERROR(\"TODO: array-sgraph does not implement to_disjunctive_linear_constraint_system\");\n  }\n      \n  static std::string getDomainName() {\n    std::string name(\"ArraySparseGraph(\" + \n\t\t     NumDom::getDomainName() +  \",\" +  Content::getDomainName() + \")\");\n    return name;\n  }\n\n};\n\ntemplate<typename Dom, typename Content, bool IsDistContent>\nstruct abstract_domain_traits<array_sparse_graph_domain<Dom,Content,IsDistContent>> {\n  // assume Dom::variable_t = Content::variable_t\n  typedef typename Dom::number_t number_t;      \n  typedef typename Dom::varname_t varname_t;\n};\n    \ntemplate<typename Dom, typename Content, bool IsDistContent>\nclass array_sgraph_domain_traits<array_sparse_graph_domain<Dom,Content,IsDistContent>> {\npublic:\n  template<class CFG>\n  static void do_initialization(CFG cfg) {\n    array_sparse_graph_domain<Dom,Content,IsDistContent>::do_initialization(cfg);\n  }    \n};\n  \n// Static data allocation\ntemplate<class Dom, class Content, bool IsDistContent>\nlandmark_ref_unordered_map<typename Dom::variable_t, typename Dom::number_t,\n\t\t\t   landmark_ref<typename Dom::variable_t, typename Dom::number_t>>\narray_sparse_graph_domain<Dom,Content,IsDistContent>::var_landmarks;\n\ntemplate<class Dom, class Content, bool IsDistContent>\nlandmark_ref_unordered_map<typename Dom::variable_t, typename Dom::number_t,\n\t\t\t   landmark_ref<typename Dom::variable_t, typename Dom::number_t>>\narray_sparse_graph_domain<Dom,Content,IsDistContent>::cst_landmarks;\n\n} // end namespace domains\n} // end namespace crab\n#pragma GCC diagnostic pop\n", "meta": {"hexsha": "ad604a753d4dbc13738ee08bec51102116d8b1d1", "size": 84177, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/crab/domains/array_sparse_graph.hpp", "max_stars_repo_name": "numairmansur/crab", "max_stars_repo_head_hexsha": "316e3946d3a4d92db638c54fbfa8fb7bee1ebbc7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/crab/domains/array_sparse_graph.hpp", "max_issues_repo_name": "numairmansur/crab", "max_issues_repo_head_hexsha": "316e3946d3a4d92db638c54fbfa8fb7bee1ebbc7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/crab/domains/array_sparse_graph.hpp", "max_forks_repo_name": "numairmansur/crab", "max_forks_repo_head_hexsha": "316e3946d3a4d92db638c54fbfa8fb7bee1ebbc7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.199777613, "max_line_length": 96, "alphanum_fraction": 0.6558204735, "num_tokens": 22318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.45435952359458337}}
{"text": "\n\n#ifdef _OPENMP\n#include <omp.h>\n#include <thread>\n#endif\n\n#ifdef OpenBLAS_AVAILABLE\n#include <cblas.h>\n#include <openblas_config.h>\n#endif\n\n#ifdef MKL_AVAILABLE\n#include <mkl_service.h>\n#include <mkl.h>\n#endif\n\n#include <Eigen/Core>\n#include <complex>\n#include <general/nmspc_tensor_extra.h>\n#include <general/nmspc_tensor_omp.h>\n#include <iostream>\n\nint main(){\n\n    #ifdef _OPENMP\n        omp_set_num_threads(std::thread::hardware_concurrency());\n        Eigen::setNbThreads(std::thread::hardware_concurrency());\n        std::cout << \"Using Eigen  with \" << Eigen::nbThreads() << \" threads\" << std::endl;\n        std::cout << \"Using OpenMP with \" << omp_get_max_threads() << \" threads\" << std::endl;\n\n        #ifdef OpenBLAS_AVAILABLE\n        openblas_set_num_threads(std::thread::hardware_concurrency());\n                    std::cout << OPENBLAS_VERSION\n                              << \" compiled with parallel mode \" << openblas_get_parallel()\n                              << \" for target \" << openblas_get_corename()\n                              << \" with config \" << openblas_get_config()\n                              << \" with multithread threshold \" << OPENBLAS_GEMM_MULTITHREAD_THRESHOLD\n                              << \". Running with \" << openblas_get_num_threads() << \" thread(s)\" << std::endl;\n        #endif\n\n        #ifdef MKL_AVAILABLE\n        mkl_set_num_threads(std::thread::hardware_concurrency());\n        std::cout << \"Using Intel MKL with \" << mkl_get_max_threads() << \" threads\" << std::endl;\n        #endif\n    #endif\n    OMP omp;\n    Eigen::Tensor<double,2> tensorA(100,100);\n    Eigen::Tensor<double,2> tensorB(100,100);\n    tensorA.setRandom();\n    tensorB.setRandom();\n    Eigen::Tensor<double,2> tensorC(100,100);\n    tensorC.device(omp.dev) = tensorA.contract(tensorB, Textra::idx({1},{0}));\n    std::cout << \"tensorC: \\n\" << tensorC(0,0) << std::endl;\n}", "meta": {"hexsha": "70bb4daecd27378c5089d59b9fd139cc2718752a", "size": 1892, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/old_tests/eigen_openmp.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": "tests/old_tests/eigen_openmp.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": "tests/old_tests/eigen_openmp.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": 34.4, "max_line_length": 110, "alphanum_fraction": 0.6062367865, "num_tokens": 469, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.45435952359458337}}
{"text": "/*!\n * @file\n * Defines the @ref Rational datatype.\n *\n *\n * @copyright Louis Dionne 2014\n * Distributed under the Boost Software License, Version 1.0.\n *         (See accompanying file LICENSE.md or copy at\n *             http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#ifndef BOOST_MPL11_RATIONAL_HPP\n#define BOOST_MPL11_RATIONAL_HPP\n\n#include <boost/mpl11/fwd/rational.hpp>\n\n#include <boost/mpl11/bool.hpp>\n#include <boost/mpl11/comparable.hpp>\n#include <boost/mpl11/core.hpp>\n#include <boost/mpl11/enumerable.hpp>\n#include <boost/mpl11/field.hpp>\n#include <boost/mpl11/group.hpp>\n#include <boost/mpl11/monoid.hpp>\n#include <boost/mpl11/orderable.hpp>\n#include <boost/mpl11/ring.hpp>\n\n\nnamespace boost { namespace mpl11 {\n    template <typename T, T numerator, T denominator>\n    struct rational_c {\n        using type = rational_c;\n        using mpl_datatype = Rational;\n\n        static constexpr T num = numerator;\n        static constexpr T den = denominator;\n    };\n\n    template <>\n    struct cast<Integer, Rational> {\n        using type = cast;\n        template <typename i>\n        using apply = rational_c<\n            typename i::value_type, i::value\n        >;\n    };\n\n    template <>\n    struct Monoid<Rational> : instantiate<Monoid>::with<Rational> {\n        template <typename x, typename y>\n        using plus_impl = rational_c<\n            decltype(true ? x::num : y::num),\n            (x::num * y::den) + (x::den * y::num),\n            x::den * y::den\n        >;\n\n        template <typename ...>\n        using zero_impl = rational_c<long long, 0>;\n    };\n\n    template <>\n    struct Group<Rational> : instantiate<Group>::with<Rational> {\n        template <typename x, typename y>\n        using minus_impl = rational_c<\n            decltype(true ? x::num : y::num),\n            (x::num * y::den) - (x::den * y::num),\n            x::den * y::den\n        >;\n\n        template <typename x>\n        using negate_impl = rational_c<\n            decltype(-x::num), -x::num, x::den\n        >;\n    };\n\n    template <>\n    struct Ring<Rational> : instantiate<Ring>::with<Rational> {\n        template <typename x, typename y>\n        using mult_impl = rational_c<\n            decltype(true ? x::num : y::num),\n            x::num * y::num,\n            x::den * y::den\n        >;\n\n        template <typename ...>\n        using one_impl = rational_c<long long, 1>;\n    };\n\n    template <>\n    struct Field<Rational> : instantiate<Field>::with<Rational> {\n        template <typename x, typename y>\n        using quot_impl = rational_c<\n            decltype(true ? x::num : y::num),\n            x::num * y::den,\n            x::den * y::num\n        >;\n\n        template <typename x>\n        using recip_impl = rational_c<\n            decltype(x::num), x::den, x::num\n        >;\n    };\n\n    template <>\n    struct Comparable<Rational> : instantiate<Comparable>::with<Rational> {\n        template <typename x, typename y>\n        using equal_impl = bool_<\n            x::num * y::den == x::den * y::num\n        >;\n\n        template <typename x, typename y>\n        using not_equal_impl = bool_<\n            x::num * y::den != x::den * y::num\n        >;\n    };\n\n    template <>\n    struct Orderable<Rational> : instantiate<Orderable>::with<Rational> {\n        template <typename x, typename y>\n        using less_impl = bool_<(\n            x::num * y::den < x::den * y::num\n        )>;\n\n        template <typename x, typename y>\n        using less_equal_impl = bool_<(\n            x::num * y::den <= x::den * y::num\n        )>;\n\n        template <typename x, typename y>\n        using greater_impl = bool_<(\n            x::num * y::den > x::den * y::num\n        )>;\n\n        template <typename x, typename y>\n        using greater_equal_impl = bool_<(\n            x::num * y::den >= x::den * y::num\n        )>;\n    };\n}} // end namespace boost::mpl11\n\n#endif // !BOOST_MPL11_RATIONAL_HPP\n", "meta": {"hexsha": "836b968e85ba96db2cb5d43df7790c5eb27c3a78", "size": 3882, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/mpl11/rational.hpp", "max_stars_repo_name": "ldionne/mpl11", "max_stars_repo_head_hexsha": "927d4339edc0c0cc41fb65ced2bf19d26bcd4a08", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 80.0, "max_stars_repo_stars_event_min_datetime": "2015-03-09T03:19:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T06:44:12.000Z", "max_issues_repo_path": "include/boost/mpl11/rational.hpp", "max_issues_repo_name": "rbock/mpl11", "max_issues_repo_head_hexsha": "7923ad2bdc0d8ddaa6a6254ebf5be2b5c6f5a277", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-07-27T22:37:43.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-06T17:42:07.000Z", "max_forks_repo_path": "include/boost/mpl11/rational.hpp", "max_forks_repo_name": "rbock/mpl11", "max_forks_repo_head_hexsha": "7923ad2bdc0d8ddaa6a6254ebf5be2b5c6f5a277", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-01-28T00:18:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T03:00:49.000Z", "avg_line_length": 27.5319148936, "max_line_length": 75, "alphanum_fraction": 0.557187017, "num_tokens": 985, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743167997235783, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.45435951663907526}}
{"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_IS_NEGATIVE_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_IS_NEGATIVE_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-predicates\n    Function object implementing is_negative capabilities\n\n    Returns @ref True if x is negative else @ref False.\n\n    This function differs from @ref is_ltz for floating point arguments,\n    because @ref Mzero is negative but not less than zero, and @ref Mzero is\n    not positive and not greater than zero, It's probably @ref is_ltz that\n    you want.\n\n    @par Semantic:\n\n    @code\n    auto r = is_negative(x);\n    @endcode\n\n    is similar to:\n\n    @code\n    if x is of signed type\n      auto r = bitofsign(x) == 1;\n    else\n      auto r = False;\n    @endcode\n\n    @par Note:\n\n    @ref Mzero is the floating point 'minus zero',\n    i.e. all bits are @ref Zero but the sign bit.\n    Such a value is treated as @ref Zero by IEEE standards.\n\n    behaviour of is_negative on @ref Nan entry is undefined.\n\n    @par Alias\n\n    signbit\n\n    @see is_positive,  Mzero, bitofsign\n\n  **/\n  as_logical_t<Value> is_negative(Value const& x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/is_negative.hpp>\n#include <boost/simd/function/simd/is_negative.hpp>\n\n#endif\n", "meta": {"hexsha": "3927e2050c3889dc8e989cacd9d6982f200baddb", "size": 1655, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/is_negative.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/is_negative.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/is_negative.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": 24.3382352941, "max_line_length": 100, "alphanum_fraction": 0.616918429, "num_tokens": 377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723317123102955, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.4543379801023263}}
{"text": "#include \"transposition_to_circuit.hpp\"\n\n#include <boost/assign/std/set.hpp>\n\n#include \"../circuit.hpp\"\n#include \"../gate.hpp\"\n\n#include \"add_circuit.hpp\"\n#include \"add_gates.hpp\"\n#include \"reverse_circuit.hpp\"\n\nusing namespace boost::assign;\n\nnamespace revkit\n{\n  bool transposition_to_circuit( circuit& circ, const boost::dynamic_bitset<>& inputs, const boost::dynamic_bitset<>& outputs )\n  {\n    assert( inputs.size() == outputs.size() );\n    assert( circ.lines() == inputs.size() );\n\n    unsigned b = 0u, bs = 0u;\n    circuit circ_block_a( inputs.size() );\n    circuit circ_block_b( inputs.size() );\n    circuit circ_block_bs( inputs.size() );\n    circuit circ_block_c( inputs.size() );\n    circuit circ_block_X( inputs.size() );\n    append_not( circ_block_X, 0u );\n    gate::line_container controls;\n    unsigned target;\n\n    for ( unsigned j = 0u; j < inputs.size(); ++j )\n    {\n      target = inputs.size() - 1u - j;\n      if ( !inputs.test( j ) && !outputs.test( j ) )\n      {\n        append_not( circ_block_a, target );\n      }\n      else if ( inputs.test( j ) && !outputs.test( j ) )\n      {\n        controls = gate::line_container();\n        append_not( circ_block_b, target );\n        ++b;\n        append_not( circ_block_c, target );\n        for ( unsigned k = 0u; k < inputs.size(); ++k )\n        {\n          if ( k != target )\n          {\n            controls += k;\n          }\n        }\n        append_toffoli( circ_block_c, controls, target );\n        circ_block_X.remove_gate_at( 0u );\n        append_toffoli( circ_block_X, controls, target );\n      }\n      else if ( !inputs.test( j ) && outputs.test( j ) )\n      {\n        controls = gate::line_container();\n        append_not( circ_block_bs, target );\n        ++bs;\n        append_not( circ_block_c, target );\n        for ( unsigned k = 0u; k < inputs.size(); ++k )\n        {\n          if ( k != target )\n          {\n            controls += k;\n          }\n        }\n        append_toffoli( circ_block_c, controls, target );\n        circ_block_X.remove_gate_at( 0u );\n        append_toffoli( circ_block_X, controls, target );\n      }\n    }\n\n    circ_block_c.remove_gate_at( circ_block_c.num_gates() - 1 );\n    circ_block_c.remove_gate_at( circ_block_c.num_gates() - 1 );\n\n    append_circuit( circ, circ_block_a );\n    if ( b < bs )\n    {\n      append_circuit( circ, circ_block_b );\n    }\n    else\n    {\n      append_circuit( circ, circ_block_bs );\n    }\n    append_circuit( circ, circ_block_c );\n\n    append_circuit( circ, circ_block_X );\n\n    reverse_circuit( circ_block_c );\n    append_circuit( circ, circ_block_c );\n\n    if ( b < bs )\n    {\n      append_circuit( circ, circ_block_b );\n    }\n    else\n    {\n      append_circuit( circ, circ_block_bs );\n    }\n    append_circuit( circ, circ_block_a );\n\n    return true;\n  }\n}\n", "meta": {"hexsha": "9d7d990a961a8d8fe5b5ee9a2f53cfde590e07af", "size": 2795, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rkqc/src/core/functions/transposition_to_circuit.cpp", "max_stars_repo_name": "clairechingching/ScaffCC", "max_stars_repo_head_hexsha": "737ae90f85d9fe79819d66219747d27efa4fa5b9", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 158.0, "max_stars_repo_stars_event_min_datetime": "2016-07-21T10:45:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T00:56:20.000Z", "max_issues_repo_path": "rkqc/src/core/functions/transposition_to_circuit.cpp", "max_issues_repo_name": "clairechingching/ScaffCC", "max_issues_repo_head_hexsha": "737ae90f85d9fe79819d66219747d27efa4fa5b9", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 35.0, "max_issues_repo_issues_event_min_datetime": "2016-07-25T01:23:07.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-27T16:05:50.000Z", "max_forks_repo_path": "rkqc/src/core/functions/transposition_to_circuit.cpp", "max_forks_repo_name": "clairechingching/ScaffCC", "max_forks_repo_head_hexsha": "737ae90f85d9fe79819d66219747d27efa4fa5b9", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 62.0, "max_forks_repo_forks_event_min_datetime": "2016-08-29T17:28:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-29T17:55:58.000Z", "avg_line_length": 26.3679245283, "max_line_length": 127, "alphanum_fraction": 0.5813953488, "num_tokens": 721, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.45433796683860167}}
{"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_FPCLASSIFY_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_FPCLASSIFY_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n    @ingroup group-ieee\n    This function object categorizes floating point value into the following categories:\n    zero, subnormal, normal, infinite, nan, or implementation-defined.\n\n\n    @par Header <boost/simd/function/fpclassify.hpp>\n\n    @par Notes\n\n    - fpclassify returns a value of integral type that matches one of the classification\n    macro constants, depending on the value of @c x :\n    value description:\n      - @c FP_INFINITE Positive or negative infinity\n      - @c FP_NAN  Not-A-Number\n      - @c FP_ZERO Value of zero\n      - @c FP_SUBNORMAL  Sub-normal value\n      - @c FP_NORMAL Normal value (none of the above)\n\n      These macro constants of type int are defined in header @c cmath\n\n    - Note that each value pertains to a single category: for fpclassify, zero is not a\n    normal value.\n\n    - the return type is not @c int : it is the integral signed type\n       associated to the floating entry type.\n\n\n    @par Decorators\n\n      - std_ for floating entries call std::fpclassify and returns @c int\n\n    @see is_eqz, is_denormal, is_normal, is_inf, is_nan\n\n\n    @par Example:\n\n      @snippet fpclassify.cpp fpclassify\n\n    @par Possible output:\n\n      @snippet fpclassify.txt fpclassify\n\n  **/\n  as_integer_t<IEEEValue> fpclassify(IEEEValue const& x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/fpclassify.hpp>\n#include <boost/simd/function/simd/fpclassify.hpp>\n\n#endif\n", "meta": {"hexsha": "9f67b53d9a6aacdec12461c6435bcabe29145e43", "size": 1972, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/fpclassify.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/fpclassify.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/fpclassify.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": 28.1714285714, "max_line_length": 100, "alphanum_fraction": 0.6455375254, "num_tokens": 439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757645879592642, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.45433795810457783}}
{"text": "/*\n\tThis file is part of cpp-ethereum.\n\n\tcpp-ethereum 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\tcpp-ethereum 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 cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.\n*/\n/** @file boost.cpp\n * @author Lefteris Karapetsas <lefteris@ethdev.com>\n * @date 2015\n * Tests for external dependencies: Boost\n */\n\n#include <boost/test/unit_test.hpp>\n#include <libdevcore/Common.h>\n#include <test/libtesteth/TestHelper.h>\n\nusing namespace dev::test;\n\nBOOST_FIXTURE_TEST_SUITE(ExtDepBoost, TestOutputHelper)\n\n// test that reproduces issue https://github.com/ethereum/cpp-ethereum/issues/1977\nBOOST_AUTO_TEST_CASE(u256_overflow_test)\n{\n\tdev::u256 a = 14;\n\tdev::bigint b = dev::bigint(\"115792089237316195423570985008687907853269984665640564039457584007913129639948\");\n\t// to fix cast `a` to dev::bigint\n\tBOOST_CHECK(a < b);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "bdb34c0a4c4a94ac5d47fb2c4548e0c2dbfb0e62", "size": 1336, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cpp-ethereum/test/external-dependencies/boost.cpp", "max_stars_repo_name": "XianlinGong/fabcoinsc-dev", "max_stars_repo_head_hexsha": "585d90f376a9223ab172151a81b92dca1113ecd6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 26.0, "max_stars_repo_stars_event_min_datetime": "2018-04-24T00:33:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T15:46:04.000Z", "max_issues_repo_path": "src/cpp-ethereum/test/external-dependencies/boost.cpp", "max_issues_repo_name": "XianlinGong/fabcoinsc-dev", "max_issues_repo_head_hexsha": "585d90f376a9223ab172151a81b92dca1113ecd6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2018-07-17T13:33:26.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-27T07:10:49.000Z", "max_forks_repo_path": "src/cpp-ethereum/test/external-dependencies/boost.cpp", "max_forks_repo_name": "XianlinGong/fabcoinsc-dev", "max_forks_repo_head_hexsha": "585d90f376a9223ab172151a81b92dca1113ecd6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2018-04-24T00:33:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-03T09:40:26.000Z", "avg_line_length": 32.5853658537, "max_line_length": 111, "alphanum_fraction": 0.7732035928, "num_tokens": 338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802735722128, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.4542892384524157}}
{"text": "/*\n [auto_generated]\n libs/numeric/odeint/test/velocity_verlet.cpp\n\n [begin_description]\n tba.\n [end_description]\n\n Copyright 2009-2012 Karsten Ahnert\n Copyright 2009-2012 Mario Mulansky\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 <boost/config.hpp>\n#ifdef BOOST_MSVC\n    #pragma warning(disable:4996)\n#endif\n\n#define BOOST_TEST_MODULE odeint_velocity_verlet\n\n#define BOOST_FUSION_INVOKE_MAX_ARITY 15\n#define BOOST_RESULT_OF_NUM_ARGS 15\n\n#include <boost/numeric/odeint/config.hpp>\n\n#include \"resizing_test_state_type.hpp\"\n\n#include <boost/numeric/odeint/stepper/velocity_verlet.hpp>\n#include <boost/numeric/odeint/algebra/fusion_algebra.hpp>\n\n#include <boost/array.hpp>\n#include <boost/test/unit_test.hpp>\n\n#include <boost/units/systems/si/length.hpp>\n#include <boost/units/systems/si/time.hpp>\n#include <boost/units/systems/si/velocity.hpp>\n#include <boost/units/systems/si/acceleration.hpp>\n#include <boost/units/systems/si/io.hpp>\n\n#include <boost/fusion/include/vector.hpp>\n#include <boost/fusion/include/vector20.hpp>\n#include <boost/fusion/container.hpp>\n\nnamespace fusion = boost::fusion;\nnamespace units = boost::units;\nnamespace si = boost::units::si;\n\ntypedef double value_type;\ntypedef units::quantity< si::time , value_type > time_type;\ntypedef units::unit< units::derived_dimension< units::time_base_dimension , 2 >::type , si::system > time_2;\ntypedef units::quantity< time_2 , value_type > time_2_type;\ntypedef units::quantity< si::length , value_type > length_type;\ntypedef units::quantity< si::velocity , value_type > velocity_type;\ntypedef units::quantity< si::acceleration , value_type > acceleration_type;\ntypedef fusion::vector< length_type , length_type > coor_vector;\ntypedef fusion::vector< velocity_type , velocity_type > velocity_vector;\ntypedef fusion::vector< acceleration_type , acceleration_type > accelartion_vector;\n\n\n\nusing namespace boost::unit_test;\nusing namespace boost::numeric::odeint;\n\nsize_t ode_call_count;\n\nstruct velocity_verlet_fixture\n{\n    velocity_verlet_fixture( void ) { ode_call_count = 0; adjust_size_count = 0; }\n};\n\nstruct ode\n{\n    template< class CoorIn , class MomentumIn , class AccelerationOut , class Time >\n    void operator()( const CoorIn &q , const MomentumIn &p , AccelerationOut &a , Time t ) const\n    {\n        a[0] = -q[0] - p[0];\n        a[1] = -q[1] - p[1];\n        ++ode_call_count;\n    }\n};\n\nstruct ode_units\n{\n    void operator()( coor_vector const &q , velocity_vector const &p , accelartion_vector &a , time_type t ) const\n    {\n        const units::quantity< si::frequency , value_type > omega = 1.0 * si::hertz;\n        const units::quantity< si::frequency , value_type > friction = 0.001 * si::hertz;\n        fusion::at_c< 0 >( a ) = omega * omega * fusion::at_c< 0 >( q ) - friction * fusion::at_c< 0 >( p );\n        fusion::at_c< 1 >( a ) = omega * omega * fusion::at_c< 1 >( q ) - friction * fusion::at_c< 0 >( p );\n        ++ode_call_count;\n    }\n};\n\ntemplate< class Q , class P >\nvoid init_state( Q &q , P &p )\n{\n    q[0] = 1.0 ; q[1] = 0.5;\n    p[0] = 2.0 ; p[1] = -1.0;\n}\n\ntypedef boost::array< double , 2 > array_type;\ntypedef std::vector< double > vector_type;\n\ntypedef velocity_verlet< array_type > array_stepper;\ntypedef velocity_verlet< vector_type > vector_stepper;\n\ntemplate< typename Resizer >\nstruct get_resizer_test_stepper\n{\n    typedef velocity_verlet< test_array_type , test_array_type , double , test_array_type ,\n        double , double , range_algebra , default_operations , Resizer > type;\n};\n\n\n\n\n\nBOOST_AUTO_TEST_SUITE( velocity_verlet_test )\n\nBOOST_FIXTURE_TEST_CASE( test_with_array_ref , velocity_verlet_fixture )\n{\n    array_stepper stepper;\n    array_type q , p ;\n    init_state( q , p );\n    stepper.do_step( ode() , std::make_pair( boost::ref( q ) , boost::ref( p ) ) , 0.0 , 0.01 );\n    BOOST_CHECK_EQUAL( ode_call_count , size_t( 2 ) );\n}\n\nBOOST_FIXTURE_TEST_CASE( test_with_array_pair , velocity_verlet_fixture )\n{\n    array_stepper stepper;\n    std::pair< array_type , array_type > xxx;\n    init_state( xxx.first , xxx.second );\n    stepper.do_step( ode() , xxx , 0.0 , 0.01 );\n    BOOST_CHECK_EQUAL( ode_call_count , size_t( 2 ) );\n}\n\nBOOST_FIXTURE_TEST_CASE( test_with_vector_ref , velocity_verlet_fixture )\n{\n    vector_stepper stepper;\n    vector_type q( 2 ) , p( 2 );\n    init_state( q , p );\n    stepper.do_step( ode() , std::make_pair( boost::ref( q ) , boost::ref( p ) ) , 0.0 , 0.01 );\n    BOOST_CHECK_EQUAL( ode_call_count , size_t( 2 ) );\n}\n\nBOOST_FIXTURE_TEST_CASE( test_with_vector_pair , velocity_verlet_fixture )\n{\n    vector_stepper stepper;\n    std::pair< vector_type , vector_type > x;\n    x.first.resize( 2 ) ; x.second.resize( 2 );\n    init_state( x.first , x.second );\n    stepper.do_step( ode() , x , 0.0 , 0.01 );\n    BOOST_CHECK_EQUAL( ode_call_count , size_t( 2 ) );\n}\n\nBOOST_FIXTURE_TEST_CASE( test_initial_resizer , velocity_verlet_fixture )\n{\n    typedef get_resizer_test_stepper< initially_resizer >::type stepper_type;\n    std::pair< test_array_type , test_array_type > x;\n    init_state( x.first , x.second );\n    stepper_type stepper;\n    stepper.do_step( ode() , x , 0.0 , 0.01 );\n    stepper.do_step( ode() , x , 0.0 , 0.01 );\n    BOOST_CHECK_EQUAL( adjust_size_count , size_t( 2 ) );\n    BOOST_CHECK_EQUAL( ode_call_count , size_t( 3 ) );\n}\n\nBOOST_FIXTURE_TEST_CASE( test_always_resizer , velocity_verlet_fixture )\n{\n    typedef get_resizer_test_stepper< always_resizer >::type stepper_type;\n    std::pair< test_array_type , test_array_type > x;\n    init_state( x.first , x.second );\n    stepper_type stepper;\n    stepper.do_step( ode() , x , 0.0 , 0.01 );\n    stepper.do_step( ode() , x , 0.0 , 0.01 );\n    BOOST_CHECK_EQUAL( adjust_size_count , size_t( 4 ) );\n    BOOST_CHECK_EQUAL( ode_call_count , size_t( 4 ) );    // attention: one more system call, since the size of the state has been changed\n}\n\nBOOST_FIXTURE_TEST_CASE( test_with_never_resizer , velocity_verlet_fixture )\n{\n    typedef get_resizer_test_stepper< never_resizer >::type stepper_type;\n    std::pair< test_array_type , test_array_type > x;\n    init_state( x.first , x.second );\n    stepper_type stepper;\n    stepper.do_step( ode() , x , 0.0 , 0.01 );\n    stepper.do_step( ode() , x , 0.0 , 0.01 );\n    BOOST_CHECK_EQUAL( adjust_size_count , size_t( 0 ) );\n    BOOST_CHECK_EQUAL( ode_call_count , size_t( 3 ) );\n}\n\nBOOST_FIXTURE_TEST_CASE( test_reset , velocity_verlet_fixture )\n{\n    typedef get_resizer_test_stepper< initially_resizer >::type stepper_type;\n    std::pair< test_array_type , test_array_type > x;\n    init_state( x.first , x.second );\n    stepper_type stepper;\n    stepper.do_step( ode() , x , 0.0 , 0.01 );\n    BOOST_CHECK_EQUAL( adjust_size_count , size_t( 2 ) );\n    BOOST_CHECK_EQUAL( ode_call_count , size_t( 2 ) );\n    stepper.do_step( ode() , x , 0.0 , 0.01 );\n    BOOST_CHECK_EQUAL( adjust_size_count , size_t( 2 ) );\n    BOOST_CHECK_EQUAL( ode_call_count , size_t( 3 ) );\n    stepper.reset();\n    BOOST_CHECK_EQUAL( adjust_size_count , size_t( 2 ) );\n    BOOST_CHECK_EQUAL( ode_call_count , size_t( 3 ) );\n    stepper.do_step( ode() , x , 0.0 , 0.01 );\n    BOOST_CHECK_EQUAL( adjust_size_count , size_t( 2 ) );\n    BOOST_CHECK_EQUAL( ode_call_count , size_t( 5 ) );\n}\n\nBOOST_FIXTURE_TEST_CASE( test_initialize1 , velocity_verlet_fixture )\n{\n    typedef get_resizer_test_stepper< initially_resizer >::type stepper_type;\n    std::pair< test_array_type , test_array_type > x;\n    init_state( x.first , x.second );\n    stepper_type stepper;\n    test_array_type ain;\n    ode()( x.first , x.second , ain , 0.0 );\n    BOOST_CHECK_EQUAL( adjust_size_count , size_t( 0 ) );\n    stepper.initialize( ain );\n    BOOST_CHECK_EQUAL( adjust_size_count , size_t( 2 ) );\n    BOOST_CHECK_EQUAL( ode_call_count , size_t( 1 ) );\n    stepper.do_step( ode() , x , 0.0 , 0.01 );\n    BOOST_CHECK_EQUAL( adjust_size_count , size_t( 2 ) );\n    BOOST_CHECK_EQUAL( ode_call_count , size_t( 2 ) );\n}\n\nBOOST_FIXTURE_TEST_CASE( test_initialize2 , velocity_verlet_fixture )\n{\n    typedef get_resizer_test_stepper< initially_resizer >::type stepper_type;\n    std::pair< test_array_type , test_array_type > x;\n    init_state( x.first , x.second );\n    stepper_type stepper;\n    stepper.initialize( ode() , x.first , x.second , 0.0 );\n    BOOST_CHECK_EQUAL( adjust_size_count , size_t( 2 ) );\n    BOOST_CHECK_EQUAL( ode_call_count , size_t( 1 ) );\n    stepper.do_step( ode() , x , 0.0 , 0.01 );\n    BOOST_CHECK_EQUAL( adjust_size_count , size_t( 2 ) );\n    BOOST_CHECK_EQUAL( ode_call_count , size_t( 2 ) );\n}\n\n\nBOOST_FIXTURE_TEST_CASE( test_adjust_size , velocity_verlet_fixture )\n{\n    typedef get_resizer_test_stepper< initially_resizer >::type stepper_type;\n    std::pair< test_array_type , test_array_type > x;\n    init_state( x.first , x.second );\n    stepper_type stepper;\n    stepper.do_step( ode() , x , 0.0 , 0.01 );\n    BOOST_CHECK_EQUAL( adjust_size_count , size_t( 2 ) );\n    BOOST_CHECK_EQUAL( ode_call_count , size_t( 2 ) );\n    stepper.adjust_size( x.first );\n    BOOST_CHECK_EQUAL( adjust_size_count , size_t( 4 ) );\n    BOOST_CHECK_EQUAL( ode_call_count , size_t( 2 ) );\n    stepper.do_step( ode() , x , 0.0 , 0.01 );\n    BOOST_CHECK_EQUAL( adjust_size_count , size_t( 4 ) );\n    BOOST_CHECK_EQUAL( ode_call_count , size_t( 4 ) );\n}\n\nBOOST_FIXTURE_TEST_CASE( test_with_unit_pair , velocity_verlet_fixture )\n{\n    typedef velocity_verlet< coor_vector , velocity_vector , value_type , accelartion_vector ,\n        time_type , time_2_type , fusion_algebra , default_operations > stepper_type;\n\n    std::pair< coor_vector , velocity_vector > x;\n    fusion::at_c< 0 >( x.first ) = 1.0 * si::meter;\n    fusion::at_c< 1 >( x.first ) = 0.5 * si::meter;\n    fusion::at_c< 0 >( x.second ) = 2.0 * si::meter_per_second;\n    fusion::at_c< 1 >( x.second ) = -1.0 * si::meter_per_second;\n    stepper_type stepper;\n    stepper.do_step( ode_units() , x , 0.0 * si::second , 0.01 * si::second );\n    BOOST_CHECK_EQUAL( ode_call_count , size_t( 2 ) );\n}\n\n\nBOOST_FIXTURE_TEST_CASE( test_with_unit_ref , velocity_verlet_fixture )\n{\n    typedef velocity_verlet< coor_vector , velocity_vector , value_type , accelartion_vector ,\n        time_type , time_2_type , fusion_algebra , default_operations > stepper_type;\n\n    coor_vector q;\n    velocity_vector p;\n    fusion::at_c< 0 >( q ) = 1.0 * si::meter;\n    fusion::at_c< 1 >( q ) = 0.5 * si::meter;\n    fusion::at_c< 0 >( p ) = 2.0 * si::meter_per_second;\n    fusion::at_c< 1 >( p ) = -1.0 * si::meter_per_second;\n    stepper_type stepper;\n    stepper.do_step( ode_units() , std::make_pair( boost::ref( q ) , boost::ref( p ) ) , 0.0 * si::second , 0.01 * si::second );\n    BOOST_CHECK_EQUAL( ode_call_count , size_t( 2 ) );\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "10b6c307d15e2d244a73de6dd7ebe873725181c0", "size": 10834, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "deps/src/boost_1_65_1/libs/numeric/odeint/test/velocity_verlet.cpp", "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/libs/numeric/odeint/test/velocity_verlet.cpp", "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/libs/numeric/odeint/test/velocity_verlet.cpp", "max_forks_repo_name": "shreyasvj25/turicreate", "max_forks_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 36.2341137124, "max_line_length": 138, "alphanum_fraction": 0.6953110578, "num_tokens": 3058, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.4542892294864389}}
{"text": "/*\n * Copyright (c) 2013-2016 Masahide Kashiwagi (kashi@waseda.jp)\n */\n\n#ifndef ALLSOL_HPP\n#define ALLSOL_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#ifdef _OPENMP\n#include <omp.h>\n#endif\n// #include <boost/random.hpp>\n#include <kv/matrix-inversion.hpp>\n#include <kv/autodif.hpp>\n\n\n#ifndef EDGE_RATIO\n#define EDGE_RATIO 0.9\n#endif\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 USE_TRIM\n#define USE_TRIM 3\n#endif\n\n#ifndef USE_ZERODIVIDE\n#define USE_ZERODIVIDE 2\n#endif\n\n#ifndef USE_MULTITRIM\n#define USE_MULTITRIM 0\n#endif\n\n#ifndef USE_AFFINEABS\n#define USE_AFFINEABS 0\n#endif\n\n#ifndef USE_MIGSKIP\n#define USE_MIGSKIP 1\n#endif\n\n#ifndef RECOVER_RATIO\n#define RECOVER_RATIO 0.1\n#endif\n\n#ifndef USE_SLOWDIVIDE\n#define USE_SLOWDIVIDE 1\n#endif\n\n#ifndef USE_FI\n#define USE_FI 1\n#endif\n\n#ifndef USE_SUPERLINEAR\n#define USE_SUPERLINEAR 1\n#endif\n\n#ifndef UNIFY_REST\n#define UNIFY_REST 1\n#endif\n\n#ifndef EXISTENCE_RATIO\n#define EXISTENCE_RATIO 0.8\n#endif\n\n#ifndef ITER_STOP_RATIO\n#define ITER_STOP_RATIO 0.9\n#endif\n\n#ifndef ENABLE_INFINITY\n#define ENABLE_INFINITY 1\n#endif\n\n#ifndef WEIGHTED_MAX\n#define WEIGHTED_MAX 1\n#endif\n\n\n\nnamespace kv {\n\nnamespace bn = boost::numeric;\nnamespace ub = boost::numeric::ublas;\n\nnamespace allsol_sub {\n\n// return index of I_i which has maximum width\n\ntemplate <class T> int search_maxwidth (const ub::vector< interval<T> >& I) {\n\tint s = I.size();\n\tint i, mi;\n\tT m, tmp;\n\n\tm = 0.;\n\tfor (i=0; i<s; i++) {\n#if WEIGHTED_MAX == 1\n\t\ttmp = width(I(i)) / (1. + mag(I(i)) / (std::numeric_limits<T>::max)() * mag(I(i)));\n#else\n\t\ttmp = width(I(i));\n#endif\n\t\tif (tmp > m) {\n\t\t\tm = tmp; mi = i;\n\t\t}\n\t}\n\n\treturn mi;\n}\n\n// return max width(I_i) / width(J_i)\n\ntemplate <class T> T widthratio_max (const ub::vector< interval<T> >& I, const ub::vector< interval<T> >& J) {\n\tint s = I.size();\n\tint i;\n\tT tmp, r;\n\n\tr = 0.;\n\n\tfor (i=0; i<s; i++) {\n\t\ttmp = width(I(i)) / width(J(i));\n\t\tif (tmp > r) r = tmp;\n\t}\n\n\treturn r;\n}\n\n// return min width(I_i) / width(J_i)\n\ntemplate <class T> T widthratio_min (const ub::vector< interval<T> >& I, const ub::vector< interval<T> >& J) {\n\tint s = I.size();\n\tint i;\n\tT tmp, r;\n\n\tr = std::numeric_limits<T>::max();\n\n\tfor (i=0; i<s; i++) {\n\t\ttmp = width(I(i)) / width(J(i));\n\t\tif (tmp < r) r = tmp;\n\t}\n\n\treturn r;\n}\n\n// J: original interval, I: shrinked interval\n// If width(I(i)) < ratio * width(J(i)) then inflate I(i)\n//  until width(I(i)) = ratio * width(J(i))\n// Inflation outside J(i) is \"not allowed\".\n\ntemplate <class T> void recovery_inflation (ub::vector< interval<T> >& I, const ub::vector< interval<T> >& J, T ratio) {\n\tint s = I.size();\n\tint i;\n\tT tmp, tmp2, l, u;\n\n\tfor (i=0; i<s; i++) {\n\t\tif ( width(I(i)) < ratio * width(J(i)) ) {\n\t\t\ttmp = mid(I(i));\n\t\t\ttmp2 = rad(J(i)) * ratio;\n\t\t\tl = tmp - tmp2;\n\t\t\tu = tmp + tmp2;\n\t\t\tif (l < J(i).lower()) {\n\t\t\t\tu += (J(i).lower() - l);\n\t\t\t\tl = J(i).lower();\n\t\t\t} else if (u > J(i).upper()) {\n\t\t\t\tl -= (u - J(i).upper());\n\t\t\t\tu = J(i).upper();\n\t\t\t}\n\t\t\t// to be sure that new I(i) includes original I(i)\n\t\t\tI(i) = interval<T>::hull(I(i), interval<T>(l, u));\n\t\t}\n\t}\n}\n\n// J: original interval, I: shrinked interval\n// If width(I(i)) < ratio * width(J(i)) then inflate I(i)\n//  until width(I(i)) = ratio * width(J(i))\n// Inflation outside J(i) is \"allowed\".\n\ntemplate <class T> void recovery_inflation2 (ub::vector< interval<T> >& I, const ub::vector< interval<T> >& J, T ratio) {\n\tint s = I.size();\n\tint i;\n\tT tmp, tmp2, l, u;\n\n\tfor (i=0; i<s; i++) {\n\t\tif ( width(I(i)) < ratio * width(J(i)) ) {\n\t\t\ttmp = mid(I(i));\n\t\t\ttmp2 = rad(J(i)) * ratio;\n\t\t\tl = tmp - tmp2;\n\t\t\tu = tmp + tmp2;\n\t\t\t// to be sure that new I(i) includes original I(i)\n\t\t\tI(i) = interval<T>::hull(I(i), interval<T>(l, u));\n\t\t}\n\t}\n}\n\n// **not used**\n// return index of division such that norm of M seems to be smallest\n// under the scaled norm u = rad(I:divided)\n\ntemplate <class T> int search_optimal_divide (const ub::matrix< interval<T> >& M, const ub::vector< interval<T> >& I) {\n\tint n = I.size();\n\tub::vector<T> u(n), s(n);\n\tub::matrix<T> m(n,n);\n\tint i, j, p, mp;\n\tT tmp, tmp2, tmp3;\n\n\tfor (i=0; i<n; i++) u(i) = width(I(i));\n\tfor (i=0; i<n; i++) {\n\t\tfor (j=0; j<n; j++) {\n\t\t\tm(i,j) = norm(M(i,j));\n\t\t}\n\t}\n\tfor (i=0; i<n; i++) {\n\t\ttmp = 0.;\n\t\tfor (j=0; j<n; j++) {\n\t\t\ttmp += m(i,j) * u(j);\n\t\t}\n\t\ts(i) = tmp / u(i);\n\t}\n\n\ttmp3 = std::numeric_limits<T>::max();\n\tfor (p=0; p<n; p++) {\n\t\ttmp2 = 0.;\n\t\tfor (i=0; i<n; i++) {\n\t\t\ttmp = s(i) - m(i,p)*u(p)/u(i)/2.;\n\t\t\tif (i == p) tmp *= 2.;\n\t\t\tif (tmp > tmp2) tmp2 = tmp;\n\t\t}\n\t\tif (tmp2 < tmp3) {\n\t\t\ttmp3 = tmp2;\n\t\t\tmp = p;\n\t\t}\n\t}\n\n\treturn mp;\n}\n\n// **not used**\n// return index such that width(K(i)) is relatively smallest\n// compared with width(I(i))\n\ntemplate <class T> int search_optimal_divide2 (const ub::vector< interval<T> >& K, const ub::vector< interval<T> >& I) {\n\tint n = I.size();\n\tT tmp, tmp2;\n\tint i, r;\n\n\ttmp2 = std::numeric_limits<T>::max();\n\tfor (i=0; i<n; i++) {\n\t\ttmp =  width(K(i))/ width(I(i));\n\t\tif (tmp < tmp2) {\n\t\t\ttmp2 = tmp;\n\t\t\tr = i;\n\t\t}\n\t}\n\n\treturn r;\n}\n\n#if ENABLE_INFINITY == 1\n\ntemplate <class T> T mid_infinity (const interval<T>& I) {\n\tif (I.upper() == std::numeric_limits<T>::infinity()) {\n\t\tif (I.lower() == -std::numeric_limits<T>::infinity()) {\n\t\t\treturn T(0.);\n\t\t} else {\n\t\t\treturn mid(interval<T>((std::numeric_limits<T>::max)(), I.lower()));\n\t\t\t#if 0\n\t\t\tif (I.lower() < 0.) {\n\t\t\t\treturn T(0.);\n\t\t\t} else if (I.lower() == 0.) {\n\t\t\t\treturn T(1.);\n\t\t\t} else {\n\t\t\t\tusing std::sqrt;\n\t\t\t\treturn sqrt((std::numeric_limits<T>::max)()) * sqrt(I.lower());\n\t\t\t}\n\t\t\t#endif\n\t\t}\n\t} else {\n\t\tif (I.lower() == -std::numeric_limits<T>::infinity()) {\n\t\t\treturn mid(interval<T>(-(std::numeric_limits<T>::max)(), I.upper()));\n\t\t\t#if 0\n\t\t\tif (I.upper() > 0.) {\n\t\t\t\treturn T(0.);\n\t\t\t} else if (I.upper() == 0.) {\n\t\t\t\treturn T(-1.);\n\t\t\t} else {\n\t\t\t\tusing std::sqrt;\n\t\t\t\treturn -sqrt((std::numeric_limits<T>::max)()) * sqrt(-I.upper());\n\t\t\t}\n\t\t\t#endif\n\t\t} else {\n\t\t\treturn mid(I);\n\t\t}\n\t}\n}\n\ntemplate <class T> ub::vector<T> mid_infinity (const ub::vector< interval<T> >& I) {\n\tint n = I.size();\n\tint i;\n\tub::vector<T> r(n);\n\n\tfor (i=0; i<n; i++) {\n\t\tr(i) = mid_infinity(I(i));\n\t}\n\n\treturn r;\n}\n\ntemplate <class T> bool include_infinity (const interval<T>& I) {\n\tif (I.lower() == -std::numeric_limits<T>::infinity() || I.upper() == std::numeric_limits<T>::infinity()) return true;\n\treturn false;\n}\n\ntemplate <class T> bool include_infinity (const ub::vector< interval<T> >& I) {\n\tint n = I.size();\n\tint i;\n\tub::vector<T> r(n);\n\n\tfor (i=0; i<n; i++) {\n\t\tif (include_infinity(I(i))) return true;\n\t}\n\n\treturn false;\n}\n\ntemplate <class T> int search_maxwidth_infinity (const ub::vector< interval<T> >& I) {\n\tint s = I.size();\n\tint i, mi, r, tr;\n\tT m, tmp, tmp2;\n\n\tm = 0.;\n\tr = 0.;\n\tfor (i=0; i<s; i++) {\n\t\tif (I(i).lower() == -std::numeric_limits<T>::infinity()) {\n\t\t\tif (I(i).upper() == std::numeric_limits<T>::infinity()) {\n\t\t\t\treturn i;\n\t\t\t} else {\n\t\t\t\ttr = 1;\n\t\t\t\ttmp = I(i).upper();\n\t\t\t}\n\t\t} else {\n\t\t\tif (I(i).upper() == std::numeric_limits<T>::infinity()) {\n\t\t\t\ttr = 1;\n\t\t\t\ttmp = -I(i).lower();\n\t\t\t} else {\n\t\t\t\ttr = 0;\n#if WEIGHTED_MAX == 1\n\t\t\t\ttmp = width(I(i)) / (1. + mag(I(i)) / (std::numeric_limits<T>::max)() * mag(I(i)));\n#else\n\t\t\t\ttmp = width(I(i));\n#endif\n\t\t\t}\n\t\t}\n\t\tif (tr > r || (tr == r &&  tmp > m)) {\n\t\t\tr = tr; m = tmp; mi = i;\n\t\t}\n\t}\n\n\treturn mi;\n}\n\ntemplate <class T> int search_maxwidth_finite (const ub::vector< interval<T> >& I) {\n\tint s = I.size();\n\tint i, mi;\n\tT m, tmp, tmp2;\n\n\tmi = -1;\n\tm = 0.;\n\tfor (i=0; i<s; i++) {\n\t\tif (include_infinity(I(i))) continue;\n#if WEIGHTED_MAX == 1\n\t\ttmp = width(I(i)) / (1. + mag(I(i)) / (std::numeric_limits<T>::max)() * mag(I(i)));\n#else\n\t\ttmp = width(I(i));\n#endif\n\t\tif (tmp > m) {\n\t\t\tm = tmp; mi = i;\n\t\t}\n\t}\n\n\treturn mi;\n}\n\n#endif // ENABLE_INFINITY\n\n\n// generate 1-d vector function from scalar function\n\ntemplate <class F>\nstruct MakeVec {\n\tF f;\n\tMakeVec(F f): f(f) {}\n\n\ttemplate <class T> ub::vector<T> operator()(const ub::vector<T>& x) {\n\t\tub::vector<T> r(1);\n\t\tr(0) = f(x(0));\n\t\treturn r;\n\t}\n};\n\n} // namespace allsol_sub\n\n\n// find all solution of f in I\n\ntemplate <class T, class F>\nstd::list< ub::vector< interval<T> > >\nallsol (\nF f,\nconst ub::vector< interval<T> >& I,\nint verbose = 1,\nT giveup = T(0.),\nstd::list< ub::vector < interval<T> > >* rest = NULL\n)\n{\n\tstd::list< ub::vector < interval<T> > > targets;\n\ttargets.push_back(I);\n\treturn allsol_list(f, targets, verbose, giveup, rest);\n}\n\n\n// find all solution of f in targets (list of intervals)\n\ntemplate <class T, class F>\nstd::list< ub::vector< interval<T> > >\nallsol_list (\nF f,\nstd::list< ub::vector< interval<T> > > targets,\nint verbose = 1,\nT giveup = T(0.),\nstd::list< ub::vector < interval<T> > >* rest = NULL\n)\n{\n\tint s = (targets.front()).size();\n\tstd::list< ub::vector< interval<T> > > solutions, solutions_big;\n\tint count_ne_test = 0;\n\tint count_ex_test = 0;\n\tint count_unknown = targets.size();\n\tint count_ne = 0;\n\tint count_ex = 0;\n\tint count_giveup = 0;\n\n\t#pragma omp parallel\n\t{\n\n\tub::vector< interval<T> > I, fc, fi, C, CK, K, mvf, I1, I2, IR, Iorg, g;\n\tub::vector<T> v;\n\tub::matrix< interval<T> > fdi, M, L2;\n\tub::matrix<T> L, R, E;\n\ttypename std::list< ub::vector< interval<T> > >::iterator p, p2;\n\tint i, j, k, mi;\n\tT tmp, tmp2;\n\tT wmax;\n\tbool r, M_calculated, flag, flag2, flag3;\n\tinterval<T> A, B, J, J2, Itmp;\n#if USE_TRIM == 3\n\tub::vector< interval<T> > A0, A1, A2; // for new trim algorithm\n#endif // USE_TRIM == 3\n\n\t// boost::variate_generator<boost::mt19937, boost::uniform_int<> > rand (boost::mt19937(time(0)), boost::uniform_int<>(0, s-1));\n\n\tE = ub::identity_matrix<T>(s);\n\n\twhile (true) {\n\t\tif (verbose >= 2) {\n\t\t\t#pragma omp critical (cout)\n\t\t\t{\n\t\t\tstd::cout << \"ne_test: \" << count_ne_test << \", ex_test: \" << count_ex_test << \", unknown: \" << count_unknown << \", ne: \" << count_ne << \", ex: \" << count_ex << \", giveup: \" << count_giveup << \"    \\r\" << std::flush;\n\t\t\t}\n\t\t}\n\n\t\t#ifdef _OPENMP\n\n\t\tint iflag = 0;\n\t\t#pragma omp critical (targets)\n\t\t{\n\t\tif (count_unknown == 0) iflag = 2;\n\t\telse {\n\t\t\tif (targets.empty()) {\n\t\t\t\tiflag = 1;\n\t\t\t} else {\n\t\t\t\tI = targets.front();\n\t\t\t\ttargets.pop_front();\n\t\t\t}\n\t\t}\n\t\t}\n\t\tif (iflag == 2)  break;\n\t\tif (iflag == 1) continue;\n\n\t\t#else // _OPENMP\n\n\t\tif (targets.empty()) break;\n\t\tI = targets.front();\n\t\ttargets.pop_front();\n\n\t\t#endif // _OPENMP\n\n\t\tIorg = I;\n\n\t\t// non-existence test\n\n\t\t#pragma omp atomic\n\t\tcount_ne_test++;\n\n#if USE_FI == 1\n\t\ttry {\n\t\t\tfi = f(I);\n\t\t}\n\t\tcatch (std::domain_error& e) {\n\t\t\tgoto label;\n\t\t}\n\n\t\tif (!zero_in(fi)) {\n\t\t\t#pragma omp atomic\n\t\t\tcount_ne++;\n\t\t\t#pragma omp critical (targets)\n\t\t\t{\n\t\t\tcount_unknown--;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n#endif\n\n\t\ttry {\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\tgoto label;\n\t\t}\n\n#if USE_FI != 1\n\t\tif (!zero_in(fi)) {\n\t\t\t#pragma omp atomic\n\t\t\tcount_ne++;\n\t\t\t#pragma omp critical (targets)\n\t\t\t{\n\t\t\tcount_unknown--;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n#endif\n\n#if ENABLE_INFINITY == 1\n\t\tC = allsol_sub::mid_infinity(I);\n#else\n\t\tC = mid(I);\n#endif\n\t\ttry {\n\t\t\tfc = f(C);\n\t\t}\n\t\tcatch (std::domain_error& e) {\n\t\t\tgoto label;\n\t\t}\n\n\t\tmvf = fc + prod(fdi, I - C);\n\t\tif (!zero_in(mvf)) {\n\t\t\t#pragma omp atomic\n\t\t\tcount_ne++;\n\t\t\t#pragma omp critical (targets)\n\t\t\t{\n\t\t\tcount_unknown--;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n#if ENABLE_INFINITY == 1\n\t\tif (allsol_sub::include_infinity(I)) goto label;\n#endif\n\n#if USE_TRIM >= 1\n\t\t// interval shrinking\n\t\tIR = I;\n\t\tflag = false; // non-existence in I turns out or not\n\t\tflag2 = false; // shrinking of I occurs or not\n#if USE_ZERODIVIDE == 2\n\t\tflag3 = false; // division of I occurs or not\n#endif\n\n\t\t// maximum width for using TRIM\n\t\twmax = 0.;\n\t\tfor (i=0; i<s; i++) {\n\t\t\ttmp = width(I(i));\n\t\t\tif (tmp > wmax) wmax = tmp;\n\t\t}\n\t\twmax *= RECOVER_RATIO;\n\n#if USE_TRIM == 3\n\t\tA0.resize(s);\n\t\tA1.resize(s);\n\t\tA2.resize(s);\n#endif // USE_TRIM == 3\n\n\t\tfor (i=0; i<s; i++) {\n\n#if USE_TRIM == 3\n\t\t\t// prepare for new trim algorithm\n\t\t\tfor (j=0; j<s; j++) {\n\t\t\t\tA0(j) = fdi(i,j) * (I(j)-C(j));\n\t\t\t}\n\t\t\tItmp = 0.;\n\t\t\tfor (j=0; j<s; j++) {\n\t\t\t\tA1(j) = Itmp;\n\t\t\t\tItmp += A0(j);\n\t\t\t}\n\t\t\tItmp = 0.;\n\t\t\tfor (j=s-1; j>=0; j--) {\n\t\t\t\tA2(j) = Itmp;\n\t\t\t\tItmp += A0(j);\n\t\t\t}\n#endif // USE_TRIM == 3\n\t\t\t\n\t\t\tfor (j=0; j<s; j++) {\n\t\t\t\t// do not use TRIM for narrow component\n\t\t\t\tif (width(I(j)) < wmax) continue;\n\n\t\t\t\tB = fdi(i, j);\n\n#if USE_TRIM == 1\n\t\t\t\t// calculate A simply\n\t\t\t\t// simple but slow\n\t\t\t\tA = 0.;\n\t\t\t\tfor (k=0; k<s; k++) {\n\t\t\t\t\tif (k == j) continue;\n\t\t\t\t\tA += fdi(i, k) * (I(k)-C(k));\n\t\t\t\t}\n\t\t\t\tA += fc(i);\n#endif // USE_TRIM == 1\n#if USE_TRIM == 2\n\t\t\t\t// old trim algorithm\n\t\t\t\t// calculate back A from mvf\n\t\t\t\tA = mvf(i);\n\t\t\t\tItmp = B * (I(j)-C(j));\n\t\t\t\trop<T>::begin();\n\t\t\t\ttmp = rop<T>::sub_down(A.lower(), Itmp.lower());\n\t\t\t\ttmp2 = rop<T>::sub_up(A.upper(), Itmp.upper());\n\t\t\t\trop<T>::end();\n\t\t\t\tA.assign(tmp, tmp2);\n#endif // USE_TRIM == 2\n#if USE_TRIM == 3\n\t\t\t\t// new trim algorithm\n\t\t\t\tA = fc(i) + A1(j) + A2(j);\n#endif // USE_TRIM == 3\n\n\t\t\t\tif (zero_in(B)) {\n#if USE_ZERODIVIDE >= 1\n\t\t\t\t\tbool bdummy;\n\t\t\t\t\tif (rad(B) <= 0.) continue;\n\t\t\t\t\tJ = C(j) - division_part1(A, B, bdummy);\n\t\t\t\t\tJ2 = C(j) - division_part2(A, B);\n\t\t\t\t\tif (overlap(IR(j), J)) {\n\t\t\t\t\t\tif (overlap(IR(j), J2)) {\n#if USE_ZERODIVIDE == 2\n\t\t\t\t\t\t\tif (overlap(J, J2)) continue;\n\t\t\t\t\t\t\t// interval division\n\t\t\t\t\t\t\tI1 = IR;\n\t\t\t\t\t\t\tI2 = IR;\n\t\t\t\t\t\t\tI1(j) = intersect(IR(j), J);\n\t\t\t\t\t\t\tI2(j) = intersect(IR(j), J2);\n\t\t\t\t\t\t\tallsol_sub::recovery_inflation(I1, Iorg, (T)RECOVER_RATIO);\n\t\t\t\t\t\t\tallsol_sub::recovery_inflation(I2, Iorg, (T)RECOVER_RATIO);\n\t\t\t\t\t\t\t#pragma omp critical (targets)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttargets.push_back(I1);\n\t\t\t\t\t\t\ttargets.push_back(I2);\n\t\t\t\t\t\t\tcount_unknown += 1;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tflag3 = true;\n\t\t\t\t\t\t\tbreak;\n#else\n\t\t\t\t\t\t\tcontinue;\n#endif\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tif (!subset(IR(j), J)) {\n\t\t\t\t\t\t\t\tIR(j) = intersect(IR(j), J);\n\t\t\t\t\t\t\t\tflag2 = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (overlap(IR(j), J2)) {\n\t\t\t\t\t\t\tif (!subset(IR(j), J2)) {\n\t\t\t\t\t\t\t\tIR(j) = intersect(IR(j), J2);\n\t\t\t\t\t\t\t\tflag2 = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tflag = true;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n#else\n\t\t\t\t\tcontinue;\n#endif\n\t\t\t\t} else {\n\t\t\t\t\tJ = C(j) - A/B;\n\t\t\t\t\tif (overlap(IR(j), J)) {\n\t\t\t\t\t\tif (!subset(IR(j), J)) {\n\t\t\t\t\t\t\tIR(j) = intersect(IR(j), J);\n\t\t\t\t\t\t\tflag2 = true;\n\t\t\t\t\t\t}\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\t\t\t} // loop j\n\t\t\tif (flag == true) break;\n#if USE_ZERODIVIDE == 2\n\t\t\tif (flag3 == true) break;\n#endif\n\t\t} // loop i\n\n#if USE_ZERODIVIDE == 2\n\t\t// interval division occurs\n\t\tif (flag3 == true) continue;\n#endif\n\n\t\t// non-existence in I turns out\n\t\tif (flag == true) {\n\t\t\t#pragma omp atomic\n\t\t\tcount_ne++;\n\t\t\t#pragma omp critical (targets)\n\t\t\t{\n\t\t\tcount_unknown--;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (flag2 == true) {\n\t\t\tallsol_sub::recovery_inflation(IR, Iorg, (T)RECOVER_RATIO);\n#if USE_MULTITRIM == 1\n\t\t\t// if radius of I is smaller than half on the \n\t\t\t// \"division scheduled\" index by interval shrinking,\n\t\t\t// skip the existence test and do interval\n\t\t\t// shrinking again.\n\t\t\tmi = allsol_sub::search_maxwidth(I);\n\t\t\tif (rad(IR(mi)) <= 0.5 * rad(I(mi))) {\n\t\t\t\t#pragma omp critical (targets)\n\t\t\t\t{\n\t\t\t\ttargets.push_back(IR);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n#endif\n\n\t\t\t// renew I, C and f(C)\n\t\t\t// do not renew f'(I) because of calculation cost\n\t\t\tI = IR;\n\t\t\tC = mid(I);\n\t\t\ttry {\n\t\t\t\tfc = f(C);\n\t\t\t}\n\t\t\tcatch (std::domain_error& e) {\n\t\t\t\tgoto label;\n\t\t\t}\n\n\t\t\t// re-check mvf\n\t\t\tmvf = fc + prod(fdi, I - C);\n\t\t\tif (!zero_in(mvf)) {\n\t\t\t\t#pragma omp atomic\n\t\t\t\tcount_ne++;\n\t\t\t\t#pragma omp critical (targets)\n\t\t\t\t{\n\t\t\t\tcount_unknown--;\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n#endif // USE_TRIM >= 1\n\n#if USE_AFFINEABS == 1\n\t\tg.resize(s);\n\t\tfor (i=0; i<s; i++) {\n\t\t\tg(i) = fc(i) / rad(mvf(i));\n\t\t}\n\t\tL2 = mid(fdi);\n\t\tI1 = fc + prod(fdi - L2, I - C);\n\t\tI2 = prod(g, L2);\n\t\tif (inner_prod(mag(g), mig(I1)) - inner_prod(mag(I2), rad(I)) > 0.) {\n\t\t\t#pragma omp atomic\n\t\t\tcount_ne++;\n\t\t\t#pragma omp critical (targets)\n\t\t\t{\n\t\t\tcount_unknown--;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n#endif\n\n\t\t// existence test\n\n\t\tM_calculated = false;\n\n\t\t// skip existence test using mig\n#if USE_MIGSKIP >= 1\n#if USE_MIGSKIP == 1\n\t\t// use \"loose\" condition\n\t\t// interval<T> is for avoiding compile error\n\t\tmvf = fc + prod(mig(fdi), interval<T>(1. + EDGE_RATIO) * (I - C));\n#else\n\t\t// use \"strict\" condition\n\t\tmvf = fc + prod(mig(fdi), I - C);\n#endif\n\t\tif (!zero_in(mvf)) goto label;\n#endif\n\n\t\tL = mid(fdi);\n\n#if 0\n\t\t// **not used**\n\t\t// below is same as mig?\n\t\tI1 = - fc + prod(L-fdi, I-C);\n\t\tI2 = prod(L, I-C);\n\t\tif (!subset(I1, I2)) goto label;\n#endif\n\n#if 0\n\t\t// **not used**\n\t\t// prod(mag(L) - mag(L - fdi), rad(I));\n\t\tL2 = L - fdi;\n\t\tv = prod(mag(L) - mag(L2), rad(I));\n\n\t\tflag = true;\n\t\tfor (i=0; i<s; i++) {\n\t\t\tif (abs(fc(i)) > v(i)) {flag=false; break;}\n\t\t}\n\t\tif (flag == false) goto label;\n#endif\n\n\t\t#pragma omp atomic\n\t\tcount_ex_test++;\n\n\t\tr = invert(L, R);\n\t\tif (!r) goto label;\n\n\t\tM = E - prod(R, fdi);\n\t\tM_calculated = true;\n\t\tCK = C - prod(R, fc);\n\t\tK = CK +  prod(M, I - C);\n\t\tif (!overlap(K, I)) {\n\t\t\t#pragma omp atomic\n\t\t\tcount_ne++;\n\t\t\t#pragma omp critical (targets)\n\t\t\t{\n\t\t\tcount_unknown--;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n#if 0\n\t\t// **not used**\n\t\t// same condition as above !overlap(K, I)\n\t\tI1 = Rfc + prod(Rfdi, I - C);\n\t\tif (!zero_in(I1)) {\n\t\t\tcount_ne++;\n\t\t\tcontinue;\n\t\t}\n#endif\n\n\t\tif (proper_subset(K, I) && allsol_sub::widthratio_max(K, I) < EXISTENCE_RATIO ) {\n\t\t\t#pragma omp critical (solutions)\n\t\t\t{\n\t\t\t// check whether the solution is already found or not\n\t\t\tflag = true;\n\t\t\tp = solutions.begin();\n\t\t\tp2 = solutions_big.begin();\n\t\t\twhile (p != solutions.end()) {\n\t\t\t\tif (overlap(K, *p)) {\n\t\t\t\t\tif (subset(K, *p2)||subset(*p, I)) {\n\t\t\t\t\t\tflag = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\twhile (true) {\n\t\t\t\t\t\tC = mid(K);\n\t\t\t\t\t\tI1 = C - prod(R, f(C)) + prod(M, K - C);\n\t\t\t\t\t\tK = intersect(K, I1);\n\t\t\t\t\t\tif (subset(K, *p2)) {\n\t\t\t\t\t\t\tflag2 = true;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!overlap(K, *p)) {\n\t\t\t\t\t\t\tflag2 = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (flag2 == true) {\n\t\t\t\t\t\tflag = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t/* never reach? */\n\t\t\t\t\t\tstd::cout << \"two overlap intervals includes different solutions\";\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tp++;\n\t\t\t\tp2++;\n\t\t\t}\n\t\t\tif (flag) { // new solution found\n\t\t\t\tif (verbose >= 1) {\n\t\t\t\t\t#pragma omp critical (cout)\n\t\t\t\t\t{\n\t\t\t\t\tstd::cout << I << \"(ex)\\n\";\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tsolutions_big.push_back(I);\n\t\t\t\t// iterative refinement\n\t\t\t\twhile (1) {\n\t\t\t\t\tC = mid(K);\n\t\t\t\t\t#if USE_SUPERLINEAR == 1\n\t\t\t\t\tautodif< interval<T> >::split(f(autodif< interval<T> >::init(K)), fi, fdi);\n\t\t\t\t\tL = mid(fdi);\n\t\t\t\t\tr = invert(L, R);\n\t\t\t\t\tM = E - prod(R, fdi);\n\t\t\t\t\t#endif\n\t\t\t\t\tI1 = C - prod(R, f(C)) + prod(M, K - C);\n\t\t\t\t\tI1 = intersect(K, I1);\n\t\t\t\t\ttmp = allsol_sub::widthratio_min(I1, K);\n\t\t\t\t\tK = I1;\n\t\t\t\t\tif (tmp > ITER_STOP_RATIO) break;\n\t\t\t\t}\n\t\t\t\tsolutions.push_back(K);\n\t\t\t\tcount_ex++;\n\t\t\t\tif (verbose >= 1) {\n\t\t\t\t\t#pragma omp critical (cout)\n\t\t\t\t\t{\n\t\t\t\t\tstd::cout << K << \"(ex:improved)\\n\";\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t} // pragma omp critical (solutions)\n\t\t\t#pragma omp critical (targets)\n\t\t\t{\n\t\t\tcount_unknown--;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\t// check the case that solution may exist near boundary.\n\t\t// If so, use K as next interval\n#if ENABLE_INFINITY == 1\n\t\tif (!allsol_sub::include_infinity(I) && allsol_sub::widthratio_max(K, I) < EDGE_RATIO)\n#else\n\t\tif (allsol_sub::widthratio_max(K, I) < EDGE_RATIO)\n#endif\n\t\t{\n\t\t\tallsol_sub::recovery_inflation2(K, Iorg, (T)RECOVER_RATIO);\n\t\t\t#pragma omp critical (targets)\n\t\t\t{\n\t\t\ttargets.push_back(K);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\n\t\tI = intersect(I, K);\n\t\tallsol_sub::recovery_inflation(I, Iorg, (T)RECOVER_RATIO);\n\n\t\tlabel:\n\n\t\t// divide interval\n\n\t\t// if (M_calculated) mi = search_optimal_divide(M, I);\n\t\t// if (M_calculated) mi = search_optimal_divide2(K, I);\n\t\t// else mi = allsol_sub::search_maxwidth(I);\n\t\t// mi = rand();\n\n#if USE_SLOWDIVIDE == 1\n#if ENABLE_INFINITY == 1\n\t\tif (!allsol_sub::include_infinity(I) && allsol_sub::widthratio_max(I, Iorg) <= 0.5)\n#else\n\t\tif (allsol_sub::widthratio_max(I, Iorg) <= 0.5)\n#endif\n\t\t{\n\t\t\t#pragma omp critical (targets)\n\t\t\t{\n\t\t\ttargets.push_back(I);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n#endif\n\n#ifdef USE_SLOWDIVIDE_OLD\n\t\t\n\t\t// if radius of I is smaller than half on the \n\t\t// \"division scheduled\" index by interval shrinking,\n\t\t// skip division.\n\n\t\tmi = allsol_sub::search_maxwidth(Iorg);\n\t\tif (rad(I(mi)) <= 0.5 * rad(Iorg(mi))) {\n\t\t\t#pragma omp critical (targets)\n\t\t\t{\n\t\t\ttargets.push_back(I);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n#else\n#if ENABLE_INFINITY == 1\n\t\tmi = allsol_sub::search_maxwidth_infinity(I);\n#else\n\t\tmi = allsol_sub::search_maxwidth(I);\n#endif\n#endif\n\n#if ENABLE_INFINITY == 1\n\t\ttmp = allsol_sub::mid_infinity(I(mi));\n#else\n\t\ttmp = mid(I(mi));\n#endif\n\t\tif (width(I(mi)) < giveup || tmp == I(mi).lower() || tmp == I(mi).upper()) {\n\t\t\tif (verbose >= 2) {\n\t\t\t\tstd::cout << \"too small interval (may be multiple root?):\\n\" << I << \"\\n\";\n\t\t\t}\n\t\t\tif (rest != NULL) {\n\t\t\t\t#pragma omp critical (rest)\n\t\t\t\t{\n\t\t\t\t#if UNIFY_REST == 1\n\t\t\t\tI1 = I;\n\t\t\t\twhile (true) {\n\t\t\t\t\tflag = false;\n\t\t\t\t\tp = (*rest).begin();\n\t\t\t\t\twhile (p != (*rest).end()) {\n\t\t\t\t\t\tif (overlap(*p, I1)) {\n\t\t\t\t\t\t\tI1 = hull(I1, *p);\n\t\t\t\t\t\t\tp = (*rest).erase(p);\n\t\t\t\t\t\t\t// #pragma omp atomic\n\t\t\t\t\t\t\t// count_giveup--;\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\t(*rest).push_back(I1);\n\t\t\t\t#else // UNIFY_REST == 1\n\t\t\t\t(*rest).push_back(I);\n\t\t\t\t#endif // UNIFY_REST == 1\n\t\t\t\t}\n\t\t\t}\n\t\t\t#pragma omp atomic\n\t\t\tcount_giveup++;\n\t\t\t#pragma omp critical (targets)\n\t\t\t{\n\t\t\tcount_unknown--;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\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#if ENABLE_INFINITY == 1\n\t\tub::vector< interval<T> > I3;\n\t\tint mi2;\n\t\tif (allsol_sub::include_infinity(I1(mi))) {\n\t\t\tmi2 = allsol_sub::search_maxwidth_finite(I1);\n\t\t\tif (mi2 != -1) {\n\t\t\t\tI3 = I1;\n\t\t\t\ttmp = mid(I1(mi2));\n\t\t\t\tI1(mi2).assign(I1(mi2).lower(), tmp);\n\t\t\t\tI3(mi2).assign(tmp, I3(mi2).upper());\n\t\t\t\t#pragma omp critical (targets)\n\t\t\t\t{\n\t\t\t\ttargets.push_back(I3);\n\t\t\t\tcount_unknown += 1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (allsol_sub::include_infinity(I2(mi))) {\n\t\t\tmi2 = allsol_sub::search_maxwidth_finite(I2);\n\t\t\tif (mi2 != -1) {\n\t\t\t\tI3 = I2;\n\t\t\t\ttmp = mid(I2(mi2));\n\t\t\t\tI2(mi2).assign(I2(mi2).lower(), tmp);\n\t\t\t\tI3(mi2).assign(tmp, I3(mi2).upper());\n\t\t\t\t#pragma omp critical (targets)\n\t\t\t\t{\n\t\t\t\ttargets.push_back(I3);\n\t\t\t\tcount_unknown += 1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n#endif\n\t\t#pragma omp critical (targets)\n\t\t{\n\t\ttargets.push_back(I1);\n\t\ttargets.push_back(I2);\n\t\tcount_unknown += 1;\n\t\t}\n\t}\n\n\t} // pragma omp parallel\n\n\tif (verbose >= 1) {\n\t\t\tstd::cout << \"ne_test: \" << count_ne_test << \", ex_test: \" << count_ex_test << \", ne: \" << count_ne << \", ex: \" << count_ex << \", giveup: \" << count_giveup << \"    \\n\";\n\t}\n\n\treturn solutions;\n}\n\n\n// allsol for 1-dimentional function\n\ntemplate <class T, class F>\nstd::list< interval<T> >\nallsol (\nF f,\nconst interval<T>& I,\nint verbose = 1,\nT giveup = T(0.),\nstd::list< interval<T> >* rest = NULL\n)\n{\n\tallsol_sub::MakeVec<F> g(f);\n\tub::vector< interval<T> > I2(1);\n\tstd::list< ub::vector< interval<T> > > rest2;\n\ttypename std::list< ub::vector< interval<T> > >::iterator p1;\n\tstd::list< ub::vector< interval<T> > >* rest_p;\n\tstd::list< ub::vector< interval<T> > > r1;\n\ttypename std::list< ub::vector< interval<T> > >::iterator p2;\n\tstd::list< interval<T> > r2;\n\n\tI2(0) = I;\n\tif (rest == NULL) {\n\t\trest_p = NULL;\n\t} else {\n\t\trest_p = &rest2;\n\t}\n\n\tr1 = allsol(g, I2, verbose, giveup, rest_p);\n\n\tp2 = r1.begin();\n\twhile (p2 != r1.end()) {\n\t\tr2.push_back((*(p2++))(0));\n\t}\n\n\tif (rest != NULL) {\n\t\tp1 = rest2.begin();\n\t\twhile (p1 != rest2.end()) {\n\t\t\t(*rest).push_back((*(p1++))(0));\n\t\t}\n\t}\n\n\treturn r2;\n}\n\n} // namespace kv\n\n#endif // ALLSOL_HPP\n", "meta": {"hexsha": "f830b0e745482d10f2373fd5f531277124059d4c", "size": 23933, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "kv/allsol.hpp", "max_stars_repo_name": "soonho-tri/kv", "max_stars_repo_head_hexsha": "4963be6560d8600cdc9ff22d004b2b965ae7b1df", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-03-15T07:11:09.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-15T07:11:09.000Z", "max_issues_repo_path": "src/interval/kv/allsol.hpp", "max_issues_repo_name": "takafumihoriuchi/HyLaGI", "max_issues_repo_head_hexsha": "26b9f32a84611ee62d9cbbd903773d224088c959", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/interval/kv/allsol.hpp", "max_forks_repo_name": "takafumihoriuchi/HyLaGI", "max_forks_repo_head_hexsha": "26b9f32a84611ee62d9cbbd903773d224088c959", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.6675302245, "max_line_length": 219, "alphanum_fraction": 0.5615259265, "num_tokens": 8194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6791787121629466, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.45428922934700944}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2013 Kyle Lutz <kyle.r.lutz@gmail.com>\n//\n// Distributed under the Boost Software License, Version 1.0\n// See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt\n//\n// See http://kylelutz.github.com/compute for more information.\n//---------------------------------------------------------------------------//\n\n#define BOOST_TEST_MODULE TestTypeTraits\n#include <boost/test/unit_test.hpp>\n\n#include <set>\n#include <list>\n#include <vector>\n\n#include <boost/type_traits.hpp>\n#include <boost/static_assert.hpp>\n\n#include <boost/compute/types.hpp>\n#include <boost/compute/type_traits.hpp>\n#include <boost/compute/iterator/buffer_iterator.hpp>\n#include <boost/compute/iterator/constant_iterator.hpp>\n#include <boost/compute/detail/is_buffer_iterator.hpp>\n#include <boost/compute/detail/is_contiguous_iterator.hpp>\n\nnamespace bc = boost::compute;\n\nBOOST_AUTO_TEST_CASE(scalar_type)\n{\n    BOOST_STATIC_ASSERT((boost::is_same<bc::scalar_type<bc::int_>::type, int>::value));\n    BOOST_STATIC_ASSERT((boost::is_same<bc::scalar_type<bc::int2_>::type, int>::value));\n    BOOST_STATIC_ASSERT((boost::is_same<bc::scalar_type<bc::float_>::type, float>::value));\n    BOOST_STATIC_ASSERT((boost::is_same<bc::scalar_type<bc::float4_>::type, float>::value));\n}\n\nBOOST_AUTO_TEST_CASE(vector_size)\n{\n    BOOST_STATIC_ASSERT(bc::vector_size<bc::int_>::value == 1);\n    BOOST_STATIC_ASSERT(bc::vector_size<bc::int2_>::value == 2);\n    BOOST_STATIC_ASSERT(bc::vector_size<bc::float_>::value == 1);\n    BOOST_STATIC_ASSERT(bc::vector_size<bc::float4_>::value == 4);\n}\n\nBOOST_AUTO_TEST_CASE(is_vector_type)\n{\n    BOOST_STATIC_ASSERT(bc::is_vector_type<bc::int_>::value == false);\n    BOOST_STATIC_ASSERT(bc::is_vector_type<bc::int2_>::value == true);\n    BOOST_STATIC_ASSERT(bc::is_vector_type<bc::float_>::value == false);\n    BOOST_STATIC_ASSERT(bc::is_vector_type<bc::float4_>::value == true);\n}\n\nBOOST_AUTO_TEST_CASE(make_vector_type)\n{\n    BOOST_STATIC_ASSERT((boost::is_same<bc::make_vector_type<cl_uint, 2>::type, bc::uint2_>::value));\n    BOOST_STATIC_ASSERT((boost::is_same<bc::make_vector_type<int, 4>::type, bc::int4_>::value));\n    BOOST_STATIC_ASSERT((boost::is_same<bc::make_vector_type<float, 8>::type, bc::float8_>::value));\n    BOOST_STATIC_ASSERT((boost::is_same<bc::make_vector_type<bc::char_, 16>::type, bc::char16_>::value));\n}\n\nBOOST_AUTO_TEST_CASE(is_fundamental_type)\n{\n    BOOST_STATIC_ASSERT((bc::is_fundamental<int>::value == true));\n    BOOST_STATIC_ASSERT((bc::is_fundamental<bc::int_>::value == true));\n    BOOST_STATIC_ASSERT((bc::is_fundamental<bc::int2_>::value == true));\n    BOOST_STATIC_ASSERT((bc::is_fundamental<float>::value == true));\n    BOOST_STATIC_ASSERT((bc::is_fundamental<bc::float_>::value == true));\n    BOOST_STATIC_ASSERT((bc::is_fundamental<bc::float4_>::value == true));\n\n    BOOST_STATIC_ASSERT((bc::is_fundamental<std::pair<int, float> >::value == false));\n    BOOST_STATIC_ASSERT((bc::is_fundamental<std::complex<float> >::value == false));\n}\n\nBOOST_AUTO_TEST_CASE(type_name)\n{\n    // scalar types\n    BOOST_CHECK(std::strcmp(bc::type_name<bc::char_>(), \"char\") == 0);\n    BOOST_CHECK(std::strcmp(bc::type_name<bc::uchar_>(), \"uchar\") == 0);\n    BOOST_CHECK(std::strcmp(bc::type_name<bc::short_>(), \"short\") == 0);\n    BOOST_CHECK(std::strcmp(bc::type_name<bc::ushort_>(), \"ushort\") == 0);\n    BOOST_CHECK(std::strcmp(bc::type_name<bc::int_>(), \"int\") == 0);\n    BOOST_CHECK(std::strcmp(bc::type_name<bc::uint_>(), \"uint\") == 0);\n    BOOST_CHECK(std::strcmp(bc::type_name<bc::long_>(), \"long\") == 0);\n    BOOST_CHECK(std::strcmp(bc::type_name<bc::ulong_>(), \"ulong\") == 0);\n    BOOST_CHECK(std::strcmp(bc::type_name<bc::float_>(), \"float\") == 0);\n    BOOST_CHECK(std::strcmp(bc::type_name<bc::double_>(), \"double\") == 0);\n    BOOST_CHECK(std::strcmp(bc::type_name<bool>(), \"bool\") == 0);\n\n    // vector types\n    BOOST_CHECK(std::strcmp(bc::type_name<bc::char16_>(), \"char16\") == 0);\n    BOOST_CHECK(std::strcmp(bc::type_name<bc::uint4_>(), \"uint4\") == 0);\n    BOOST_CHECK(std::strcmp(bc::type_name<bc::ulong8_>(), \"ulong8\") == 0);\n    BOOST_CHECK(std::strcmp(bc::type_name<bc::float2_>(), \"float2\") == 0);\n    BOOST_CHECK(std::strcmp(bc::type_name<bc::double4_>(), \"double4\") == 0);\n}\n\nBOOST_AUTO_TEST_CASE(is_contiguous_iterator)\n{\n    using boost::compute::detail::is_contiguous_iterator;\n\n    BOOST_STATIC_ASSERT(is_contiguous_iterator<int *>::value == true);\n    BOOST_STATIC_ASSERT(is_contiguous_iterator<std::vector<int>::iterator>::value == true);\n    BOOST_STATIC_ASSERT(is_contiguous_iterator<std::vector<int>::const_iterator>::value == true);\n    BOOST_STATIC_ASSERT(is_contiguous_iterator<std::list<int>::iterator>::value == false);\n    BOOST_STATIC_ASSERT(is_contiguous_iterator<std::set<int>::iterator>::value == false);\n    BOOST_STATIC_ASSERT(is_contiguous_iterator<std::insert_iterator<std::set<int> > >::value == false);\n    BOOST_STATIC_ASSERT(is_contiguous_iterator<std::back_insert_iterator<std::vector<int> > >::value == false);\n}\n\nBOOST_AUTO_TEST_CASE(is_buffer_iterator)\n{\n    using boost::compute::detail::is_buffer_iterator;\n\n    BOOST_STATIC_ASSERT(is_buffer_iterator<boost::compute::buffer_iterator<int> >::value == true);\n    BOOST_STATIC_ASSERT(is_buffer_iterator<boost::compute::constant_iterator<int> >::value == false);\n}\n\nBOOST_AUTO_TEST_CASE(is_device_iterator)\n{\n    using boost::compute::is_device_iterator;\n\n    BOOST_STATIC_ASSERT(is_device_iterator<boost::compute::buffer_iterator<int> >::value == true);\n    BOOST_STATIC_ASSERT(is_device_iterator<const boost::compute::buffer_iterator<int> >::value == true);\n    BOOST_STATIC_ASSERT(is_device_iterator<boost::compute::constant_iterator<int> >::value == true);\n    BOOST_STATIC_ASSERT(is_device_iterator<const boost::compute::constant_iterator<int> >::value == true);\n    BOOST_STATIC_ASSERT(is_device_iterator<float *>::value == false);\n    BOOST_STATIC_ASSERT(is_device_iterator<const float *>::value == false);\n    BOOST_STATIC_ASSERT(is_device_iterator<std::vector<int>::iterator>::value == false);\n    BOOST_STATIC_ASSERT(is_device_iterator<const std::vector<int>::iterator>::value == false);\n}\n", "meta": {"hexsha": "a74e4d36711f7cbef69846ce80f140f92af0bdc1", "size": 6248, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_type_traits.cpp", "max_stars_repo_name": "skozilla/compute", "max_stars_repo_head_hexsha": "861a75ae9f05f5bbd25d13120788133a1c9dc886", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-03-18T01:14:13.000Z", "max_stars_repo_stars_event_max_datetime": "2015-03-18T01:14:13.000Z", "max_issues_repo_path": "test/test_type_traits.cpp", "max_issues_repo_name": "junmuz/compute", "max_issues_repo_head_hexsha": "b979ff527d3f1cb6e073da29b167bf02b3218c9a", "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/test_type_traits.cpp", "max_forks_repo_name": "junmuz/compute", "max_forks_repo_head_hexsha": "b979ff527d3f1cb6e073da29b167bf02b3218c9a", "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": 47.3333333333, "max_line_length": 111, "alphanum_fraction": 0.7031049936, "num_tokens": 1586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.668880247169804, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.45428922486402085}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2013   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2013   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#include <nt2/hyperbolic/include/functions/asinh.hpp>\n\n#include <nt2/sdk/functor/meta/call.hpp>\n#include <boost/simd/sdk/simd/native.hpp>\n#include <nt2/sdk/unit/tests/type_expr.hpp>\n#include <nt2/sdk/unit/tests/ulp.hpp>\n#include <nt2/include/functions/splat.hpp>\n#include <nt2/sdk/unit/module.hpp>\n#include <boost/simd/sdk/config.hpp>\n#include <boost/simd/sdk/simd/io.hpp>\n#include <boost/math/special_functions/asinh.hpp>\n\n\n#include <nt2/include/functions/rec.hpp>\n#include <nt2/include/constants/zero.hpp>\n#include <nt2/include/constants/inf.hpp>\n#include <nt2/include/constants/minf.hpp>\n#include <nt2/include/constants/nan.hpp>\n#include <nt2/include/constants/valmax.hpp>\n#include <nt2/include/constants/valmax.hpp>\n#include <nt2/include/constants/eps.hpp>\n#include <nt2/include/constants/sqrteps.hpp>\n#include <nt2/include/constants/oneosqrteps.hpp>\n#include <nt2/include/constants/two.hpp>\n\nNT2_TEST_CASE_TPL ( asinh,  NT2_SIMD_REAL_TYPES)\n{\n  using nt2::asinh;\n  using nt2::tag::asinh_;\n  using boost::simd::native;\n  typedef BOOST_SIMD_DEFAULT_EXTENSION  ext_t;\n  typedef native<T,ext_t>                  vT;\n  typedef typename nt2::meta::call<asinh_(vT)>::type r_t;\n  typedef vT wished_r_t;\n\n  // return type conformity test\n  NT2_TEST_TYPE_IS(r_t, wished_r_t);\n\n\n  // specific values tests\n#ifndef BOOST_SIMD_NO_INVALIDS\n  NT2_TEST_ULP_EQUAL(asinh(nt2::Inf<vT>()), nt2::Inf<r_t>(), 0.5);\n  NT2_TEST_ULP_EQUAL(asinh(nt2::Minf<vT>()), nt2::Minf<r_t>(), 0.5);\n  NT2_TEST_ULP_EQUAL(asinh(nt2::Nan<vT>()), nt2::Nan<r_t>(), 0.5);\n#endif\n NT2_TEST_ULP_EQUAL(asinh(nt2::Zero<vT>()), nt2::Zero<r_t>(), 0.5);\n NT2_TEST_ULP_EQUAL(asinh(nt2::Valmax<vT>()), nt2::splat<vT>(boost::math::asinh(nt2::Valmax<T>())), 0.5);\n NT2_TEST_ULP_EQUAL(asinh(nt2::rec(nt2::Sqrteps<vT>())*nt2::Two<vT>()),  nt2::splat<vT>(boost::math::asinh(nt2::rec(nt2::Sqrteps<T>())*2)), 0.5);\n NT2_TEST_ULP_EQUAL(asinh(nt2::Eps<vT>()), nt2::Eps<vT>(), 0.5);\n\n for(T i=T(0.1); i <= T(1.1); i+= T(0.5))\n {\n   vT ii =  nt2::splat<vT>(i);\n   vT ri =  nt2::splat<vT>(nt2::rec(i));\n   NT2_TEST_ULP_EQUAL(asinh(ii), nt2::splat<vT>(boost::math::asinh(i)), 0.5);\n   NT2_TEST_ULP_EQUAL(asinh(ri), nt2::splat<vT>(boost::math::asinh(nt2::rec(i))), 0.5);\n }\n\n}\n", "meta": {"hexsha": "281fdd09bbd953c80acb5ea6deb6acee12c956f2", "size": 2724, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/core/hyperbolic/unit/simd/asinh.cpp", "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/hyperbolic/unit/simd/asinh.cpp", "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/hyperbolic/unit/simd/asinh.cpp", "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.0588235294, "max_line_length": 145, "alphanum_fraction": 0.6461086637, "num_tokens": 854, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.4542892207993206}}
{"text": "/*\n * Copyright 2008 by Tommi Rantala <tt.rantala@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\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/* Implements a multi-way mergesort based on the loser tree.\n */\n\n#include \"routine.h\"\n#include \"util/debug.h\"\n#include <cassert>\n#include <cstring>\n#include <boost/array.hpp>\n\nstatic inline int\ncmp(const unsigned char* a, const unsigned char* b)\n{\n\tassert(a != 0);\n\tassert(b != 0);\n\treturn strcmp(reinterpret_cast<const char*>(a),\n\t              reinterpret_cast<const char*>(b));\n}\n\n#include \"losertree.h\"\n\nvoid mergesort_4way(unsigned char**, size_t, unsigned char**);\n\ntemplate <unsigned K>\nstatic void\nmergesort_losertree(unsigned char** strings, size_t n, unsigned char** tmp)\n{\n\tif (n < 0x10000) {\n\t\tmergesort_4way(strings, n, tmp);\n\t\treturn;\n\t}\n\tdebug() << __func__ << \"(), n=\"<<n<<\"\\n\";\n\tconst size_t split = size_t(double(n) / double(K));\n\tboost::array<std::pair<unsigned char**, size_t>, K> ranges;\n\tfor (unsigned i=0; i < K-1; ++i) {\n\t\tranges[i] = std::make_pair(strings+i*split, split);\n\t}\n\tranges[K-1] = std::make_pair(strings+(K-1)*split, n-(K-1)*split);\n\tfor (unsigned i=0; i < K; ++i) {\n\t\tmergesort_losertree<K>(ranges[i].first, ranges[i].second,\n\t\t\t\ttmp+(ranges[i].first-strings));\n\t}\n\tunsigned char** result = tmp;\n\tloser_tree<unsigned char*> tree(ranges.begin(), ranges.end());\n\twhile (tree._nonempty_streams) { *result++ = tree.min(); }\n\t(void) memcpy(strings, tmp, n*sizeof(unsigned char*));\n}\n\nvoid mergesort_losertree_64way(unsigned char** strings, size_t n)\n{\n\tunsigned char** tmp = static_cast<unsigned char**>(\n\t\t\tmalloc(n*sizeof(unsigned char*)));\n\tmergesort_losertree<64>(strings, n, tmp);\n\tfree(tmp);\n}\nvoid mergesort_losertree_128way(unsigned char** strings, size_t n)\n{\n\tunsigned char** tmp = static_cast<unsigned char**>(\n\t\t\tmalloc(n*sizeof(unsigned char*)));\n\tmergesort_losertree<128>(strings, n, tmp);\n\tfree(tmp);\n}\nvoid mergesort_losertree_256way(unsigned char** strings, size_t n)\n{\n\tunsigned char** tmp = static_cast<unsigned char**>(\n\t\t\tmalloc(n*sizeof(unsigned char*)));\n\tmergesort_losertree<256>(strings, n, tmp);\n\tfree(tmp);\n}\nvoid mergesort_losertree_512way(unsigned char** strings, size_t n)\n{\n\tunsigned char** tmp = static_cast<unsigned char**>(\n\t\t\tmalloc(n*sizeof(unsigned char*)));\n\tmergesort_losertree<512>(strings, n, tmp);\n\tfree(tmp);\n}\nvoid mergesort_losertree_1024way(unsigned char** strings, size_t n)\n{\n\tunsigned char** tmp = static_cast<unsigned char**>(\n\t\t\tmalloc(n*sizeof(unsigned char*)));\n\tmergesort_losertree<1024>(strings, n, tmp);\n\tfree(tmp);\n}\n\nROUTINE_REGISTER_SINGLECORE(mergesort_losertree_64way,\n\t\t\"64way loser tree based mergesort\")\nROUTINE_REGISTER_SINGLECORE(mergesort_losertree_128way,\n\t\t\"128way loser tree based mergesort\")\nROUTINE_REGISTER_SINGLECORE(mergesort_losertree_256way,\n\t\t\"256way loser tree based mergesort\")\nROUTINE_REGISTER_SINGLECORE(mergesort_losertree_512way,\n\t\t\"512way loser tree based mergesort\")\nROUTINE_REGISTER_SINGLECORE(mergesort_losertree_1024way,\n\t\t\"1024way loser tree based mergesort\")\n\nvoid mergesort_4way_parallel(unsigned char**, size_t, unsigned char**);\n\ntemplate <unsigned K>\nstatic void\nmergesort_losertree_parallel(unsigned char** strings, size_t n, unsigned char** tmp)\n{\n\tif (n < 0x10000) {\n\t\tmergesort_4way_parallel(strings, n, tmp);\n\t\treturn;\n\t}\n\tdebug() << __func__ << \"(), n=\"<<n<<\"\\n\";\n\tconst size_t split = size_t(double(n) / double(K));\n\tboost::array<std::pair<unsigned char**, size_t>, K> ranges;\n\tfor (unsigned i=0; i < K-1; ++i) {\n\t\tranges[i] = std::make_pair(strings+i*split, split);\n\t}\n\tranges[K-1] = std::make_pair(strings+(K-1)*split, n-(K-1)*split);\n#pragma omp parallel for\n\tfor (unsigned i=0; i < K; ++i) {\n\t\tmergesort_losertree_parallel<K>(ranges[i].first, ranges[i].second,\n\t\t\t\ttmp+(ranges[i].first-strings));\n\t}\n\tunsigned char** result = tmp;\n\tloser_tree<unsigned char*> tree(ranges.begin(), ranges.end());\n\twhile (tree._nonempty_streams) { *result++ = tree.min(); }\n\t(void) memcpy(strings, tmp, n*sizeof(unsigned char*));\n}\n\nvoid mergesort_losertree_64way_parallel(unsigned char** strings, size_t n)\n{\n\tunsigned char** tmp = static_cast<unsigned char**>(\n\t\t\tmalloc(n*sizeof(unsigned char*)));\n\tmergesort_losertree_parallel<64>(strings, n, tmp);\n\tfree(tmp);\n}\nvoid mergesort_losertree_128way_parallel(unsigned char** strings, size_t n)\n{\n\tunsigned char** tmp = static_cast<unsigned char**>(\n\t\t\tmalloc(n*sizeof(unsigned char*)));\n\tmergesort_losertree_parallel<128>(strings, n, tmp);\n\tfree(tmp);\n}\nvoid mergesort_losertree_256way_parallel(unsigned char** strings, size_t n)\n{\n\tunsigned char** tmp = static_cast<unsigned char**>(\n\t\t\tmalloc(n*sizeof(unsigned char*)));\n\tmergesort_losertree_parallel<256>(strings, n, tmp);\n\tfree(tmp);\n}\nvoid mergesort_losertree_512way_parallel(unsigned char** strings, size_t n)\n{\n\tunsigned char** tmp = static_cast<unsigned char**>(\n\t\t\tmalloc(n*sizeof(unsigned char*)));\n\tmergesort_losertree_parallel<512>(strings, n, tmp);\n\tfree(tmp);\n}\nvoid mergesort_losertree_1024way_parallel(unsigned char** strings, size_t n)\n{\n\tunsigned char** tmp = static_cast<unsigned char**>(\n\t\t\tmalloc(n*sizeof(unsigned char*)));\n\tmergesort_losertree_parallel<1024>(strings, n, tmp);\n\tfree(tmp);\n}\n\nROUTINE_REGISTER_MULTICORE(mergesort_losertree_64way_parallel,\n\t\t\"Parallel 64way loser tree based mergesort\")\nROUTINE_REGISTER_MULTICORE(mergesort_losertree_128way_parallel,\n\t\t\"Parallel 128way loser tree based mergesort\")\nROUTINE_REGISTER_MULTICORE(mergesort_losertree_256way_parallel,\n\t\t\"Parallel 256way loser tree based mergesort\")\nROUTINE_REGISTER_MULTICORE(mergesort_losertree_512way_parallel,\n\t\t\"Parallel 512way loser tree based mergesort\")\nROUTINE_REGISTER_MULTICORE(mergesort_losertree_1024way_parallel,\n\t\t\"Parallel 1024way loser tree based mergesort\")\n", "meta": {"hexsha": "2cbd2a5ad45b3277bbcd49106fc42527fddb72d8", "size": 6735, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mergesort_losertree.cpp", "max_stars_repo_name": "KWillets/string-sorting", "max_stars_repo_head_hexsha": "68db5ea3d8e2cc284723119ccea10fad053a1357", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2017-11-15T18:50:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-28T17:48:54.000Z", "max_issues_repo_path": "src/mergesort_losertree.cpp", "max_issues_repo_name": "KWillets/string-sorting", "max_issues_repo_head_hexsha": "68db5ea3d8e2cc284723119ccea10fad053a1357", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mergesort_losertree.cpp", "max_forks_repo_name": "KWillets/string-sorting", "max_forks_repo_head_hexsha": "68db5ea3d8e2cc284723119ccea10fad053a1357", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-11-15T17:57:47.000Z", "max_forks_repo_forks_event_max_datetime": "2017-11-15T17:57:47.000Z", "avg_line_length": 35.2617801047, "max_line_length": 84, "alphanum_fraction": 0.7382331106, "num_tokens": 1843, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.4542892206598913}}
{"text": "// Eigen tutorial -- Block operations\n// SOurce:\n// http://eigen.tuxfamily.org/dox/group__TutorialBlockOperations.html\n#include <iostream>\n#include <Eigen/Dense>\n\nusing namespace Eigen;\n\nint main(void)\n{\n    MatrixXf m(4,4);\n    m << 1, 2, 3, 4,\n         5, 6, 7, 8,\n         9,10,11,12,\n        13,14,15,16;\n    std::cout << \"Block in the middle\" << std::endl;\n    std::cout << m.block<2,2>(1,1) << '\\n' << std::endl;\n    for (int i = 0; i <= 3; i++) {\n        std::cout << \"Block of size \" << i << \"x\" << i << std::endl;\n        std::cout << m.block(0,0,i,i) << '\\n' << std::endl;\n    }\n\n    // block can also be used as lvalues, meaning that you can assign to a block\n    Array22f r;\n    r << 1,2,\n         3,4;\n    Array44f a = Array44f::Constant(0.6);\n    std::cout << \"Here is the array a:\\n\" << a << '\\n' << std::endl;\n    a.block<2,2>(1,1) = r;\n    std::cout << \"Here is now a with m copied into its central 2x2 block:\\n\"\n        << a << '\\n' << std::endl;\n    a.block(0,0,2,3) = a.block(2,1,2,3);\n    std::cout << \"Here is now a with bottom-right 2x3 copied into top-left 2x2 block:\\n\"\n        << a << '\\n' << std::endl;\n\n    // Columns and rows\n    MatrixXf u(3,3);\n    u << 1,2,3,\n         4,5,6,\n         7,8,9;\n    std::cout << \"Here is thematrix u:\\n\" << u << std::endl;\n    std::cout << \"2nd Row: \" << u.row(1) << std::endl;\n    u.col(2) += 3 * u.col(0);\n    std::cout << \"After adding 3 times the first column into the third column,\"\n        << \"the matrix u is:\\n\" << u << std::endl;\n\n    // Corner-related operations\n    MatrixXf w(4,4);\n    w << 1, 2, 3, 4,\n         5, 6, 7, 8,\n         9,10,11,12,\n        13,14,15,16;\n    std::cout << \"w.leftCols(2) =\\n\" << m.leftCols(2) << '\\n' << std::endl;\n    std::cout << \"w.bottomRows<2>() =\\n\" <<  w.bottomRows<2>() << '\\n' << std::endl;\n    w.topLeftCorner(1,3) = w.bottomRightCorner(3,1).transpose();\n    std::cout << \"After assignment, w =\\n\" << w << std::endl;\n\n    // Block operations for vectors\n    ArrayXf y(6);\n    y << 1,2,3,4,5,6;\n    std::cout << \"y.head(3) = \\n\" << y.head(3) << '\\n' << std::endl;\n    std::cout << \"y.tail<3>() =\\n\" << y.tail<3>() << \"\\n\\n\";\n    y.segment(1,4) *= 2;\n    std::cout << \"after 'y.segment(1,4) *= 2', y =\\n\" << y << std::endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "fd0b6ad1ddb0359e2de0cc2e9a74a5f31545a19a", "size": 2250, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Eigen_practice/eigen_ex6.cpp", "max_stars_repo_name": "RobinCPC/ros_tutorials", "max_stars_repo_head_hexsha": "9f7ce9a4a08dd8ca26416a04b9bc7941a248a645", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Eigen_practice/eigen_ex6.cpp", "max_issues_repo_name": "RobinCPC/ros_tutorials", "max_issues_repo_head_hexsha": "9f7ce9a4a08dd8ca26416a04b9bc7941a248a645", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Eigen_practice/eigen_ex6.cpp", "max_forks_repo_name": "RobinCPC/ros_tutorials", "max_forks_repo_head_hexsha": "9f7ce9a4a08dd8ca26416a04b9bc7941a248a645", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-11-29T06:32:54.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-29T06:32:54.000Z", "avg_line_length": 33.0882352941, "max_line_length": 88, "alphanum_fraction": 0.5035555556, "num_tokens": 854, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.668880247169804, "lm_q2_score": 0.6791787056691697, "lm_q1q2_score": 0.4542892205204618}}
{"text": "// Copyright Louis Dionne 2013-2017\r\n// Distributed under the Boost Software License, Version 1.0.\r\n// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\r\n\r\n#include <boost/hana/detail/has_duplicates.hpp>\r\n#include <boost/hana/integral_constant.hpp>\r\nnamespace hana = boost::hana;\r\n\r\n\r\nstatic_assert(!hana::detail::has_duplicates<>::value, \"\");\r\n\r\nstatic_assert(!hana::detail::has_duplicates<\r\n    hana::int_<0>\r\n>::value, \"\");\r\n\r\nstatic_assert(!hana::detail::has_duplicates<\r\n    hana::int_<0>, hana::int_<1>\r\n>::value, \"\");\r\n\r\nstatic_assert(!hana::detail::has_duplicates<\r\n    hana::int_<0>, hana::int_<1>, hana::int_<2>\r\n>::value, \"\");\r\n\r\nstatic_assert(hana::detail::has_duplicates<\r\n    hana::int_<0>, hana::int_<0>, hana::int_<2>\r\n>::value, \"\");\r\n\r\nstatic_assert(hana::detail::has_duplicates<\r\n    hana::int_<0>, hana::int_<1>, hana::int_<0>\r\n>::value, \"\");\r\n\r\nstatic_assert(hana::detail::has_duplicates<\r\n    hana::int_<0>, hana::int_<1>, hana::int_<2>, hana::int_<1>\r\n>::value, \"\");\r\n\r\nstatic_assert(hana::detail::has_duplicates<\r\n    hana::int_<0>, hana::int_<1>, hana::int_<2>, hana::int_<2>\r\n>::value, \"\");\r\n\r\nstatic_assert(hana::detail::has_duplicates<\r\n    hana::int_<0>, hana::int_<1>, hana::int_<2>, hana::int_<1>, hana::int_<1>\r\n>::value, \"\");\r\n\r\nstatic_assert(hana::detail::has_duplicates<\r\n    hana::int_<0>, hana::int_<1>, hana::int_<2>, hana::int_<1>, hana::int_<2>\r\n>::value, \"\");\r\n\r\n// Make sure it uses deep equality\r\nstatic_assert(hana::detail::has_duplicates<\r\n    hana::int_<0>, hana::long_<0>, hana::int_<2>, hana::int_<3>\r\n>::value, \"\");\r\n\r\nstatic_assert(hana::detail::has_duplicates<\r\n    hana::int_<0>, hana::int_<1>, hana::int_<2>, hana::long_<1>\r\n>::value, \"\");\r\n\r\nint main() { }\r\n", "meta": {"hexsha": "b88f49ea795b37604e9113f69e049b018416a30c", "size": 1740, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/hana/test/detail/has_duplicates.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": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/hana/test/detail/has_duplicates.cpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-03-04T11:21:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-24T01:36:31.000Z", "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/hana/test/detail/has_duplicates.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 30.0, "max_line_length": 82, "alphanum_fraction": 0.6413793103, "num_tokens": 557, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178686187839, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.4542892164557613}}
{"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#include <boost/test/unit_test.hpp>\n\n#include \"../unittest_config.h\"\n\n#include \"clotho/utility/popcount.hpp\"\n\n#define TEST_PC( x, e) \\\n    BOOST_REQUIRE_MESSAGE( popcount( x ) == e, \"Unexpected popcount: pc(\" << x << \") =  pc(0x\" << std::hex << x << \") = \" << std::dec << popcount(x) << \" !=  \" << e)\n\nBOOST_AUTO_TEST_SUITE( test_utility )\n\n/// Basic two's complement test cases\nBOOST_AUTO_TEST_CASE( test_popcount_two_comp ) {\n    int x = -129;   // 0xffffff7f\n\n    TEST_PC( x, 31 );\n\n    char y = -51;   // 0xCD\n    TEST_PC( y, 5);\n\n    long z = -129 * 0x0000000100000000;   // 0xffffff7f00000000\n    TEST_PC( z, 31);\n\n    unsigned int a = -1;\n    TEST_PC( a, 32 );\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "778814d09c5090ec35436318bbd4f43596259dea", "size": 1310, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittest/utility/popcount_test.cpp", "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": "unittest/utility/popcount_test.cpp", "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": "unittest/utility/popcount_test.cpp", "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": 31.1904761905, "max_line_length": 165, "alphanum_fraction": 0.6641221374, "num_tokens": 364, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.668880247169804, "lm_q2_score": 0.679178686187839, "lm_q1q2_score": 0.4542892074897845}}
{"text": "#include \"compi.hpp\"\n\n#include <complex>\n#include <iostream>\n\n#include <boost/math/quadrature/sinh_sinh.hpp>\n\nextern \"C\" {\n    #include \"integration_routines.h\"\n}\n#include \"integration_routines_template.hpp\"\n#include \"IntegrandFunctionWrapper.hpp\"\n\nstruct SinhSinhParameters: public RoutineParametersBase {\n\n    SinhSinhParameters(PyObject* routine_args, PyObject* routine_kwargs){\n        constexpr auto keywords = generate_keyword_list<IntegralRange::infinite>();\n\n        if(!PyArg_ParseTupleAndKeywords(routine_args,routine_kwargs,\"O|OO$pId\", const_cast<char**>(keywords.data()),\n            &integrand,\n            &args,&kw,\n            &full_output,&max_levels,&tolerance)){\n                throw could_not_parse_arguments(\"Unable to parse Python args to C variables\");\n        }\n    }\n\n    struct result_type: public RoutineParametersBase::result_type {\n        size_t levels;\n    };\n};\n\nauto run_integration_routine(const compi_internal::IntegrandFunctionWrapper& f, const SinhSinhParameters& parameters){\n    SinhSinhParameters::result_type result;\n    \n    boost::math::quadrature::sinh_sinh<Real> integrator{static_cast<size_t>(parameters.max_levels)};\n\n    result.result = integrator.integrate(f,parameters.tolerance,&result.err,&result.l1,&result.levels);\n\n    return result;\n}\n\nextern \"C\" PyObject* sinh_sinh(PyObject* self, PyObject* args, PyObject* kwargs){\n    return integration_routine<SinhSinhParameters>(args,kwargs);\n}", "meta": {"hexsha": "a9996dfee57ca1396e39b34116f3185d1d247188", "size": 1441, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/sinh_sinh.cpp", "max_stars_repo_name": "CGJackson/Compi", "max_stars_repo_head_hexsha": "9fe2a316e9dbe54b01ee274417a07a13f4f990b0", "max_stars_repo_licenses": ["MIT"], "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/sinh_sinh.cpp", "max_issues_repo_name": "CGJackson/Compi", "max_issues_repo_head_hexsha": "9fe2a316e9dbe54b01ee274417a07a13f4f990b0", "max_issues_repo_licenses": ["MIT"], "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/sinh_sinh.cpp", "max_forks_repo_name": "CGJackson/Compi", "max_forks_repo_head_hexsha": "9fe2a316e9dbe54b01ee274417a07a13f4f990b0", "max_forks_repo_licenses": ["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.75, "max_line_length": 118, "alphanum_fraction": 0.7307425399, "num_tokens": 330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4542764037925901}}
{"text": "//\n// Copyright (c) 2018 CNRS, INRIA\n//\n\n#include \"pinocchio/multibody/model.hpp\"\n#include \"pinocchio/multibody/data.hpp\"\n#include \"pinocchio/algorithm/jacobian.hpp\"\n#include \"pinocchio/algorithm/joint-configuration.hpp\"\n#include \"pinocchio/algorithm/kinematics.hpp\"\n#include \"pinocchio/algorithm/kinematics-derivatives.hpp\"\n#include \"pinocchio/algorithm/rnea.hpp\"\n#include \"pinocchio/algorithm/rnea-derivatives.hpp\"\n#include \"pinocchio/algorithm/aba.hpp\"\n#include \"pinocchio/algorithm/aba-derivatives.hpp\"\n#include \"pinocchio/algorithm/crba.hpp\"\n#include \"pinocchio/parsers/sample-models.hpp\"\n\n#include <iostream>\n\n#include <boost/test/unit_test.hpp>\n#include <boost/utility/binary.hpp>\n\nBOOST_AUTO_TEST_SUITE(BOOST_TEST_MODULE)\n\nBOOST_AUTO_TEST_CASE(test_aba_derivatives)\n{\n  using namespace Eigen;\n  using namespace pinocchio;\n  \n  Model model;\n  buildModels::humanoidRandom(model);\n  \n  Data data(model), data_ref(model);\n  \n  model.lowerPositionLimit.head<3>().fill(-1.);\n  model.upperPositionLimit.head<3>().fill(1.);\n  VectorXd q = randomConfiguration(model);\n  VectorXd v(VectorXd::Random(model.nv));\n  VectorXd tau(VectorXd::Random(model.nv));\n  VectorXd a(aba(model,data_ref,q,v,tau));\n  \n  MatrixXd aba_partial_dq(model.nv,model.nv); aba_partial_dq.setZero();\n  MatrixXd aba_partial_dv(model.nv,model.nv); aba_partial_dv.setZero();\n  Data::RowMatrixXs aba_partial_dtau(model.nv,model.nv); aba_partial_dtau.setZero();\n  \n  computeABADerivatives(model, data, q, v, tau, aba_partial_dq, aba_partial_dv, aba_partial_dtau);\n  computeRNEADerivatives(model,data_ref,q,v,a);\n  for(Model::JointIndex k = 1; k < (Model::JointIndex)model.njoints; ++k)\n  {\n    BOOST_CHECK(data.oMi[k].isApprox(data_ref.oMi[k]));\n    BOOST_CHECK(data.v[k].isApprox(data_ref.v[k]));\n    BOOST_CHECK(data.ov[k].isApprox(data_ref.ov[k]));\n    BOOST_CHECK(data.oa_gf[k].isApprox(data_ref.oa_gf[k]));\n    BOOST_CHECK(data.of[k].isApprox(data_ref.of[k]));\n    BOOST_CHECK(data.oYcrb[k].isApprox(data_ref.oYcrb[k]));\n    BOOST_CHECK(data.doYcrb[k].isApprox(data_ref.doYcrb[k]));\n  }\n  \n  computeJointJacobians(model,data_ref,q);\n  BOOST_CHECK(data.J.isApprox(data_ref.J));\n  \n  aba(model,data_ref,q,v,tau);\n  BOOST_CHECK(data.ddq.isApprox(data_ref.ddq));\n  \n  computeMinverse(model,data_ref,q);\n  data_ref.Minv.triangularView<Eigen::StrictlyLower>()\n  = data_ref.Minv.transpose().triangularView<Eigen::StrictlyLower>();\n  \n  BOOST_CHECK(aba_partial_dtau.isApprox(data_ref.Minv));\n\n  BOOST_CHECK(data.J.isApprox(data_ref.J));\n  BOOST_CHECK(data.dJ.isApprox(data_ref.dJ));\n  BOOST_CHECK(data.dVdq.isApprox(data_ref.dVdq));\n  BOOST_CHECK(data.dAdq.isApprox(data_ref.dAdq));\n  BOOST_CHECK(data.dAdv.isApprox(data_ref.dAdv));\n  BOOST_CHECK(data.dtau_dq.isApprox(data_ref.dtau_dq));\n  BOOST_CHECK(data.dtau_dv.isApprox(data_ref.dtau_dv));\n  \n  MatrixXd aba_partial_dq_fd(model.nv,model.nv); aba_partial_dq_fd.setZero();\n  MatrixXd aba_partial_dv_fd(model.nv,model.nv); aba_partial_dv_fd.setZero();\n  MatrixXd aba_partial_dtau_fd(model.nv,model.nv); aba_partial_dtau_fd.setZero();\n  \n  Data data_fd(model);\n  VectorXd a0 = aba(model,data_fd,q,v,tau);\n  VectorXd v_eps(VectorXd::Zero(model.nv));\n  VectorXd q_plus(model.nq);\n  VectorXd a_plus(model.nv);\n  const double alpha = 1e-8;\n  for(int k = 0; k < model.nv; ++k)\n  {\n    v_eps[k] += alpha;\n    q_plus = integrate(model,q,v_eps);\n    a_plus = aba(model,data_fd,q_plus,v,tau);\n\n    aba_partial_dq_fd.col(k) = (a_plus - a0)/alpha;\n    v_eps[k] -= alpha;\n  }\n  BOOST_CHECK(aba_partial_dq.isApprox(aba_partial_dq_fd,sqrt(alpha)));\n  \n  VectorXd v_plus(v);\n  for(int k = 0; k < model.nv; ++k)\n  {\n    v_plus[k] += alpha;\n    a_plus = aba(model,data_fd,q,v_plus,tau);\n    \n    aba_partial_dv_fd.col(k) = (a_plus - a0)/alpha;\n    v_plus[k] -= alpha;\n  }\n  BOOST_CHECK(aba_partial_dv.isApprox(aba_partial_dv_fd,sqrt(alpha)));\n  \n  VectorXd tau_plus(tau);\n  for(int k = 0; k < model.nv; ++k)\n  {\n    tau_plus[k] += alpha;\n    a_plus = aba(model,data_fd,q,v,tau_plus);\n    \n    aba_partial_dtau_fd.col(k) = (a_plus - a0)/alpha;\n    tau_plus[k] -= alpha;\n  }\n  BOOST_CHECK(aba_partial_dtau.isApprox(aba_partial_dtau_fd,sqrt(alpha)));\n}\n\nBOOST_AUTO_TEST_CASE(test_aba_minimal_argument)\n{\n  using namespace Eigen;\n  using namespace pinocchio;\n  \n  Model model;\n  buildModels::humanoidRandom(model);\n  \n  Data data(model), data_ref(model);\n  \n  model.lowerPositionLimit.head<3>().fill(-1.);\n  model.upperPositionLimit.head<3>().fill(1.);\n  VectorXd q = randomConfiguration(model);\n  VectorXd v(VectorXd::Random(model.nv));\n  VectorXd tau(VectorXd::Random(model.nv));\n  VectorXd a(aba(model,data_ref,q,v,tau));\n  \n  MatrixXd aba_partial_dq(model.nv,model.nv); aba_partial_dq.setZero();\n  MatrixXd aba_partial_dv(model.nv,model.nv); aba_partial_dv.setZero();\n  Data::RowMatrixXs aba_partial_dtau(model.nv,model.nv); aba_partial_dtau.setZero();\n  \n  computeABADerivatives(model, data_ref, q, v, tau, aba_partial_dq, aba_partial_dv, aba_partial_dtau);\n  \n  computeABADerivatives(model, data, q, v, tau);\n  \n  BOOST_CHECK(data.J.isApprox(data_ref.J));\n  BOOST_CHECK(data.dJ.isApprox(data_ref.dJ));\n  BOOST_CHECK(data.dVdq.isApprox(data_ref.dVdq));\n  BOOST_CHECK(data.dAdq.isApprox(data_ref.dAdq));\n  BOOST_CHECK(data.dAdv.isApprox(data_ref.dAdv));\n  BOOST_CHECK(data.dtau_dq.isApprox(data_ref.dtau_dq));\n  BOOST_CHECK(data.dtau_dv.isApprox(data_ref.dtau_dv));\n  BOOST_CHECK(data.Minv.isApprox(aba_partial_dtau));\n  BOOST_CHECK(data.ddq_dq.isApprox(aba_partial_dq));\n  BOOST_CHECK(data.ddq_dv.isApprox(aba_partial_dv));\n}\n\nBOOST_AUTO_TEST_CASE(test_aba_derivatives_fext)\n{\n  using namespace Eigen;\n  using namespace pinocchio;\n  \n  Model model;\n  buildModels::humanoidRandom(model);\n  \n  Data data(model), data_ref(model);\n  \n  model.lowerPositionLimit.head<3>().fill(-1.);\n  model.upperPositionLimit.head<3>().fill(1.);\n  VectorXd q = randomConfiguration(model);\n  VectorXd v(VectorXd::Random(model.nv));\n  VectorXd tau(VectorXd::Random(model.nv));\n  VectorXd a(aba(model,data_ref,q,v,tau));\n  \n  typedef container::aligned_vector<Force> ForceVector;\n  ForceVector fext((size_t)model.njoints);\n  for(ForceVector::iterator it = fext.begin(); it != fext.end(); ++it)\n    (*it).setRandom();\n  \n  MatrixXd aba_partial_dq(model.nv,model.nv); aba_partial_dq.setZero();\n  MatrixXd aba_partial_dv(model.nv,model.nv); aba_partial_dv.setZero();\n  Data::RowMatrixXs aba_partial_dtau(model.nv,model.nv); aba_partial_dtau.setZero();\n  \n  computeABADerivatives(model, data, q, v, tau, fext,\n                        aba_partial_dq, aba_partial_dv, aba_partial_dtau);\n  \n  aba(model,data_ref,q,v,tau,fext);\n//  updateGlobalPlacements(model, data_ref);\n//  for(size_t k =1; k < (size_t)model.njoints; ++k)\n//  {\n//    BOOST_CHECK(data.oMi[k].isApprox(data_ref.oMi[k]));\n//    BOOST_CHECK(daita.of[k].isApprox(data_ref.oMi[k].act(data.f[k])));\n//\n//  }\n  BOOST_CHECK(data.ddq.isApprox(data_ref.ddq));\n  \n  computeABADerivatives(model,data_ref,q,v,tau);\n  BOOST_CHECK(aba_partial_dv.isApprox(data_ref.ddq_dv));\n  BOOST_CHECK(aba_partial_dtau.isApprox(data_ref.Minv));\n  \n  MatrixXd aba_partial_dq_fd(model.nv,model.nv); aba_partial_dq_fd.setZero();\n  MatrixXd aba_partial_dv_fd(model.nv,model.nv); aba_partial_dv_fd.setZero();\n  MatrixXd aba_partial_dtau_fd(model.nv,model.nv); aba_partial_dtau_fd.setZero();\n  \n  Data data_fd(model);\n  const VectorXd a0 = aba(model,data_fd,q,v,tau,fext);\n  VectorXd v_eps(VectorXd::Zero(model.nv));\n  VectorXd q_plus(model.nq);\n  VectorXd a_plus(model.nv);\n  const double alpha = 1e-8;\n  for(int k = 0; k < model.nv; ++k)\n  {\n    v_eps[k] += alpha;\n    q_plus = integrate(model,q,v_eps);\n    a_plus = aba(model,data_fd,q_plus,v,tau,fext);\n\n    aba_partial_dq_fd.col(k) = (a_plus - a0)/alpha;\n    v_eps[k] -= alpha;\n  }\n  BOOST_CHECK(aba_partial_dq.isApprox(aba_partial_dq_fd,sqrt(alpha)));\n\n  VectorXd v_plus(v);\n  for(int k = 0; k < model.nv; ++k)\n  {\n    v_plus[k] += alpha;\n    a_plus = aba(model,data_fd,q,v_plus,tau,fext);\n\n    aba_partial_dv_fd.col(k) = (a_plus - a0)/alpha;\n    v_plus[k] -= alpha;\n  }\n  BOOST_CHECK(aba_partial_dv.isApprox(aba_partial_dv_fd,sqrt(alpha)));\n\n  VectorXd tau_plus(tau);\n  for(int k = 0; k < model.nv; ++k)\n  {\n    tau_plus[k] += alpha;\n    a_plus = aba(model,data_fd,q,v,tau_plus,fext);\n\n    aba_partial_dtau_fd.col(k) = (a_plus - a0)/alpha;\n    tau_plus[k] -= alpha;\n  }\n  BOOST_CHECK(aba_partial_dtau.isApprox(aba_partial_dtau_fd,sqrt(alpha)));\n  \n  // test the shortcut\n  Data data_shortcut(model);\n  computeABADerivatives(model,data_shortcut,q,v,tau,fext);\n  BOOST_CHECK(data_shortcut.ddq_dq.isApprox(aba_partial_dq));\n  BOOST_CHECK(data_shortcut.ddq_dv.isApprox(aba_partial_dv));\n  BOOST_CHECK(data_shortcut.Minv.isApprox(aba_partial_dtau));\n}\n\nBOOST_AUTO_TEST_CASE(test_multiple_calls)\n{\n  using namespace Eigen;\n  using namespace pinocchio;\n  \n  Model model;\n  buildModels::humanoidRandom(model);\n  \n  Data data1(model), data2(model);\n  \n  model.lowerPositionLimit.head<3>().fill(-1.);\n  model.upperPositionLimit.head<3>().fill(1.);\n  VectorXd q = randomConfiguration(model);\n  VectorXd v(VectorXd::Random(model.nv));\n  VectorXd tau(VectorXd::Random(model.nv));\n  \n  computeABADerivatives(model,data1,q,v,tau);\n  data2 = data1;\n  \n  for(int k = 0; k < 20; ++k)\n  {\n    computeABADerivatives(model,data1,q,v,tau);\n  }\n  \n  BOOST_CHECK(data1.J.isApprox(data2.J));\n  BOOST_CHECK(data1.dJ.isApprox(data2.dJ));\n  BOOST_CHECK(data1.dVdq.isApprox(data2.dVdq));\n  BOOST_CHECK(data1.dAdq.isApprox(data2.dAdq));\n  BOOST_CHECK(data1.dAdv.isApprox(data2.dAdv));\n  \n  BOOST_CHECK(data1.dFdq.isApprox(data2.dFdq));\n  BOOST_CHECK(data1.dFdv.isApprox(data2.dFdv));\n  BOOST_CHECK(data1.dFda.isApprox(data2.dFda));\n  \n  BOOST_CHECK(data1.dtau_dq.isApprox(data2.dtau_dq));\n  BOOST_CHECK(data1.dtau_dv.isApprox(data2.dtau_dv));\n  \n  BOOST_CHECK(data1.ddq_dq.isApprox(data2.ddq_dq));\n  BOOST_CHECK(data1.ddq_dv.isApprox(data2.ddq_dv));\n  BOOST_CHECK(data1.Minv.isApprox(data2.Minv));\n}\n\nBOOST_AUTO_TEST_CASE(test_aba_derivatives_vs_kinematics_derivatives)\n{\n  using namespace Eigen;\n  using namespace pinocchio;\n  \n  Model model;\n  buildModels::humanoidRandom(model);\n  \n  Data data(model), data_ref(model);\n  \n  model.lowerPositionLimit.head<3>().fill(-1.);\n  model.upperPositionLimit.head<3>().fill(1.);\n  VectorXd q = randomConfiguration(model);\n  VectorXd v(VectorXd::Random(model.nv));\n  VectorXd a(VectorXd::Random(model.nv));\n  \n  VectorXd tau = rnea(model,data_ref,q,v,a);\n  \n  /// Check againt computeGeneralizedGravityDerivatives\n  MatrixXd aba_partial_dq(model.nv,model.nv); aba_partial_dq.setZero();\n  MatrixXd aba_partial_dv(model.nv,model.nv); aba_partial_dv.setZero();\n  MatrixXd aba_partial_dtau(model.nv,model.nv); aba_partial_dtau.setZero();\n  \n  computeABADerivatives(model,data,q,v,tau,aba_partial_dq,aba_partial_dv,aba_partial_dtau);\n  computeForwardKinematicsDerivatives(model,data_ref,q,v,a);\n  \n  BOOST_CHECK(data.J.isApprox(data_ref.J));\n  BOOST_CHECK(data.dJ.isApprox(data_ref.dJ));\n  \n  for(size_t k = 1; k < (size_t)model.njoints; ++k)\n  {\n    BOOST_CHECK(data.oMi[k].isApprox(data_ref.oMi[k]));\n    BOOST_CHECK(data.ov[k].isApprox(data_ref.ov[k]));\n    BOOST_CHECK(data.oa[k].isApprox(data_ref.oa[k]));\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "c439b8e7302b125e8f79b93f1218e73e3f59d7cc", "size": 11209, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittest/aba-derivatives.cpp", "max_stars_repo_name": "mkatliar/pinocchio", "max_stars_repo_head_hexsha": "b755b9cf2567eab39de30a68b2a80fac802a4042", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "unittest/aba-derivatives.cpp", "max_issues_repo_name": "mkatliar/pinocchio", "max_issues_repo_head_hexsha": "b755b9cf2567eab39de30a68b2a80fac802a4042", "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": "unittest/aba-derivatives.cpp", "max_forks_repo_name": "mkatliar/pinocchio", "max_forks_repo_head_hexsha": "b755b9cf2567eab39de30a68b2a80fac802a4042", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5598802395, "max_line_length": 102, "alphanum_fraction": 0.7278972254, "num_tokens": 3306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527631, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.4542763985956294}}
{"text": "// Copyright John Maddock 2012.\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_HANKEL_HPP\r\n#define BOOST_MATH_HANKEL_HPP\r\n\r\n#include <boost/math/special_functions/math_fwd.hpp>\r\n#include <boost/math/special_functions/bessel.hpp>\r\n\r\nnamespace boost{ namespace math{\r\n\r\nnamespace detail{\r\n\r\ntemplate <class T, class Policy>\r\nstd::complex<T> hankel_imp(T v, T x, const bessel_no_int_tag&, const Policy& pol, int sign)\r\n{\r\n   BOOST_MATH_STD_USING\r\n   static const char* function = \"boost::math::cyl_hankel_1<%1%>(%1%,%1%)\";\r\n\r\n   if(x < 0)\r\n   {\r\n      bool isint_v = floor(v) == v;\r\n      T j, y;\r\n      bessel_jy(v, -x, &j, &y, need_j | need_y, pol);\r\n      std::complex<T> cx(x), cv(v);\r\n      std::complex<T> j_result, y_result;\r\n      if(isint_v)\r\n      {\r\n         int s = (iround(v) & 1) ? -1 : 1;\r\n         j_result = j * s;\r\n         y_result = T(s) * (y - (2 / constants::pi<T>()) * (log(-x) - log(cx)) * j);\r\n      }\r\n      else\r\n      {\r\n         j_result = pow(cx, v) * pow(-cx, -v) * j;\r\n         T p1 = pow(-x, v);\r\n         std::complex<T> p2 = pow(cx, v);\r\n         y_result = p1 * y / p2\r\n            + (p2 / p1 - p1 / p2) * j / tan(constants::pi<T>() * v);\r\n      }\r\n      // multiply y_result by i:\r\n      y_result = std::complex<T>(-sign * y_result.imag(), sign * y_result.real());\r\n      return j_result + y_result;\r\n   }\r\n\r\n   if(x == 0)\r\n   {\r\n      if(v == 0)\r\n      {\r\n         // J is 1, Y is -INF\r\n         return std::complex<T>(1, sign * -policies::raise_overflow_error<T>(function, 0, pol));\r\n      }\r\n      else\r\n      {\r\n         // At least one of J and Y is complex infinity:\r\n         return std::complex<T>(policies::raise_overflow_error<T>(function, 0, pol), sign * policies::raise_overflow_error<T>(function, 0, pol));\r\n      }\r\n   }\r\n\r\n   T j, y;\r\n   bessel_jy(v, x, &j, &y, need_j | need_y, pol);\r\n   return std::complex<T>(j, sign * y);\r\n}\r\n\r\ntemplate <class T, class Policy>\r\nstd::complex<T> hankel_imp(int v, T x, const bessel_int_tag&, const Policy& pol, int sign);\r\n\r\ntemplate <class T, class Policy>\r\ninline std::complex<T> hankel_imp(T v, T x, const bessel_maybe_int_tag&, const Policy& pol, int sign)\r\n{\r\n   BOOST_MATH_STD_USING  // ADL of std names.\r\n   int ival = detail::iconv(v, pol);\r\n   if(0 == v - ival)\r\n   {\r\n      return hankel_imp(ival, x, bessel_int_tag(), pol, sign);\r\n   }\r\n   return hankel_imp(v, x, bessel_no_int_tag(), pol, sign);\r\n}\r\n\r\ntemplate <class T, class Policy>\r\ninline std::complex<T> hankel_imp(int v, T x, const bessel_int_tag&, const Policy& pol, int sign)\r\n{\r\n   BOOST_MATH_STD_USING\r\n   if((std::abs(v) < 200) && (x > 0))\r\n      return std::complex<T>(bessel_jn(v, x, pol), sign * bessel_yn(v, x, pol));\r\n   return hankel_imp(static_cast<T>(v), x, bessel_no_int_tag(), pol, sign);\r\n}\r\n\r\ntemplate <class T, class Policy>\r\ninline std::complex<T> sph_hankel_imp(T v, T x, const Policy& pol, int sign)\r\n{\r\n   BOOST_MATH_STD_USING\r\n   return constants::root_half_pi<T>() * hankel_imp(v + 0.5f, x, bessel_no_int_tag(), pol, sign) / sqrt(std::complex<T>(x));\r\n}\r\n\r\n} // namespace detail\r\n\r\ntemplate <class T1, class T2, class Policy>\r\ninline std::complex<typename detail::bessel_traits<T1, T2, Policy>::result_type> cyl_hankel_1(T1 v, T2 x, const Policy& pol)\r\n{\r\n   BOOST_FPU_EXCEPTION_GUARD\r\n   typedef typename detail::bessel_traits<T1, T2, Policy>::result_type result_type;\r\n   typedef typename detail::bessel_traits<T1, T2, Policy>::optimisation_tag tag_type;\r\n   typedef typename policies::evaluation<result_type, Policy>::type value_type;\r\n   return policies::checked_narrowing_cast<std::complex<result_type>, Policy>(detail::hankel_imp<value_type>(v, static_cast<value_type>(x), tag_type(), pol, 1), \"boost::math::cyl_hankel_1<%1%>(%1%,%1%)\");\r\n}\r\n\r\ntemplate <class T1, class T2>\r\ninline std::complex<typename detail::bessel_traits<T1, T2, policies::policy<> >::result_type> cyl_hankel_1(T1 v, T2 x)\r\n{\r\n   return cyl_hankel_1(v, x, policies::policy<>());\r\n}\r\n\r\ntemplate <class T1, class T2, class Policy>\r\ninline std::complex<typename detail::bessel_traits<T1, T2, Policy>::result_type> cyl_hankel_2(T1 v, T2 x, const Policy& pol)\r\n{\r\n   BOOST_FPU_EXCEPTION_GUARD\r\n   typedef typename detail::bessel_traits<T1, T2, Policy>::result_type result_type;\r\n   typedef typename detail::bessel_traits<T1, T2, Policy>::optimisation_tag tag_type;\r\n   typedef typename policies::evaluation<result_type, Policy>::type value_type;\r\n   return policies::checked_narrowing_cast<std::complex<result_type>, Policy>(detail::hankel_imp<value_type>(v, static_cast<value_type>(x), tag_type(), pol, -1), \"boost::math::cyl_hankel_1<%1%>(%1%,%1%)\");\r\n}\r\n\r\ntemplate <class T1, class T2>\r\ninline std::complex<typename detail::bessel_traits<T1, T2, policies::policy<> >::result_type> cyl_hankel_2(T1 v, T2 x)\r\n{\r\n   return cyl_hankel_2(v, x, policies::policy<>());\r\n}\r\n\r\ntemplate <class T1, class T2, class Policy>\r\ninline std::complex<typename detail::bessel_traits<T1, T2, Policy>::result_type> sph_hankel_1(T1 v, T2 x, const Policy&)\r\n{\r\n   BOOST_FPU_EXCEPTION_GUARD\r\n   typedef typename detail::bessel_traits<T1, T2, Policy>::result_type result_type;\r\n   typedef typename policies::evaluation<result_type, Policy>::type value_type;\r\n   typedef typename policies::normalise<\r\n      Policy, \r\n      policies::promote_float<false>, \r\n      policies::promote_double<false>, \r\n      policies::discrete_quantile<>,\r\n      policies::assert_undefined<> >::type forwarding_policy;\r\n\r\n   return policies::checked_narrowing_cast<std::complex<result_type>, Policy>(detail::sph_hankel_imp<value_type>(static_cast<value_type>(v), static_cast<value_type>(x), forwarding_policy(), 1), \"boost::math::sph_hankel_1<%1%>(%1%,%1%)\");\r\n}\r\n\r\ntemplate <class T1, class T2>\r\ninline std::complex<typename detail::bessel_traits<T1, T2, policies::policy<> >::result_type> sph_hankel_1(T1 v, T2 x)\r\n{\r\n   return sph_hankel_1(v, x, policies::policy<>());\r\n}\r\n\r\ntemplate <class T1, class T2, class Policy>\r\ninline std::complex<typename detail::bessel_traits<T1, T2, Policy>::result_type> sph_hankel_2(T1 v, T2 x, const Policy&)\r\n{\r\n   BOOST_FPU_EXCEPTION_GUARD\r\n   typedef typename detail::bessel_traits<T1, T2, Policy>::result_type result_type;\r\n   typedef typename policies::evaluation<result_type, Policy>::type value_type;\r\n   typedef typename policies::normalise<\r\n      Policy, \r\n      policies::promote_float<false>, \r\n      policies::promote_double<false>, \r\n      policies::discrete_quantile<>,\r\n      policies::assert_undefined<> >::type forwarding_policy;\r\n\r\n   return policies::checked_narrowing_cast<std::complex<result_type>, Policy>(detail::sph_hankel_imp<value_type>(static_cast<value_type>(v), static_cast<value_type>(x), forwarding_policy(), -1), \"boost::math::sph_hankel_1<%1%>(%1%,%1%)\");\r\n}\r\n\r\ntemplate <class T1, class T2>\r\ninline std::complex<typename detail::bessel_traits<T1, T2, policies::policy<> >::result_type> sph_hankel_2(T1 v, T2 x)\r\n{\r\n   return sph_hankel_2(v, x, policies::policy<>());\r\n}\r\n\r\n}} // namespaces\r\n\r\n#endif // BOOST_MATH_HANKEL_HPP\r\n\r\n", "meta": {"hexsha": "d1967eaa00966159c5d164c5083a3bf4f3088f62", "size": 7174, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ios/Pods/boost-for-react-native/boost/math/special_functions/hankel.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/special_functions/hankel.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/special_functions/hankel.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.635359116, "max_line_length": 239, "alphanum_fraction": 0.6647616393, "num_tokens": 2114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.45427639859562935}}
{"text": "#include <boost/math/distributions/bernoulli.hpp>\n", "meta": {"hexsha": "0b86208866cc04d050c001f52c1fef07ce4d57ea", "size": 50, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_distributions_bernoulli.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_distributions_bernoulli.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_distributions_bernoulli.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 25.0, "max_line_length": 49, "alphanum_fraction": 0.82, "num_tokens": 12, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080671950640465, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4542763882017073}}
{"text": "#include \"lookIncFromSr.h\"\n\n#include <pybind11/eigen.h>\n#include <pybind11/numpy.h>\n#include <pybind11/stl.h>\n\n#include <Eigen/Dense>\n\n#include <isce3/core/Ellipsoid.h>\n#include <isce3/core/Orbit.h>\n#include <isce3/geometry/DEMInterpolator.h>\n#include <isce3/geometry/geometry.h>\n\n// Aliases\nnamespace py = pybind11;\nusing isce3::geometry::DEMInterpolator;\nusing namespace isce3::core;\n\n// Functions binding\nvoid addbinding_look_inc_from_sr(pybind11::module& m)\n{\n\n    m.def(\n            \"look_inc_ang_from_slant_range\",\n            [](double slant_range, const Orbit& orbit,\n                    std::optional<double> az_time = {},\n                    const DEMInterpolator& dem_interp = {},\n                    const Ellipsoid& ellips = {}) {\n                return lookIncAngFromSlantRange(\n                        slant_range, orbit, az_time, dem_interp, ellips);\n            },\n            py::arg(\"slant_range\"), py::arg(\"orbit\"),\n            py::arg(\"az_time\") = std::nullopt,\n            py::arg_v(\"dem_interp\", DEMInterpolator(), \"0.0\"),\n            py::arg_v(\"ellips\", Ellipsoid(), \"WGS84\"),\n            R\"(\nEstimate look angle (off-nadir angle) and local incidence angle at a desired slant range \nfrom orbit(spacecraft/antenna statevector) and at a certain relative azimuth time.\n\nParameters\n----------\nslant_range : float\n    true slant range in meters from antenna phase center (or spacecraft position) to the ground. \norbit : isce3.core.orbit\naz_time : float, optional \n    relative azimuth time in seconds w.r.t reference epoch time of orbit object.\n    If not speficied, the mid time of orbit will be used as azimuth time.\ndem_interp : isce3.geometry.DEMInterpolator, default=0.0\nellips : isce3.core.Ellipsoid, default=WGS84\n\nReturns\n-------\nfloat\n    Look angle or off-nadir angle in (rad)\nfloat \n    Incidence angle in (rad)\n\nRaises\n------\nRuntimeError\n    for bad-value look angle or incidence angles\n\nNotes\n-----\nSee references [1]_ and [2]_ for the equations to calculate \nlook angle and incidence angle, respectivelty.\n\nReferences\n----------\n..[1] https://en.wikipedia.org/wiki/Law_of_cosines\n..[2] https://en.wikipedia.org/wiki/Law_of_sines\n)\");\n\n    m.def(\n            \"look_inc_ang_from_slant_range\",\n            [](const Eigen::Ref<const Eigen::ArrayXd>& slant_range,\n                    const Orbit& orbit, std::optional<double> az_time = {},\n                    const DEMInterpolator& dem_interp = {},\n                    const Ellipsoid& ellips = {}) {\n                return lookIncAngFromSlantRange(\n                        slant_range, orbit, az_time, dem_interp, ellips);\n            },\n            py::arg(\"slant_range\"), py::arg(\"orbit\"),\n            py::arg(\"az_time\") = std::nullopt,\n            py::arg_v(\"dem_interp\", DEMInterpolator(), \"0.0\"),\n            py::arg_v(\"ellips\", Ellipsoid(), \"WGS84\"),\n            R\"(\nEstimate look angles (off-nadir angle) and local incidence angles at desired slant ranges\nfrom orbit(spacecraft/antenna statevector) and at a certain relative azimuth time.\n\nParameters\n----------\nslant_range : numpy.ndarray(float)\n    Array of slant ranges in meters from antenna phase center (or spacecraft position) to the ground. \norbit : isce3.core.orbit\naz_time : float, optional \n    relative azimuth time in seconds w.r.t reference epoch time of orbit object.\n    If not speficied, the mid time of orbit will be used as azimuth time.\ndem_interp : isce3.geometry.DEMInterpolator, default=0.0\nellips : isce3.core.Ellipsoid, default=WGS84\n\nReturns\n-------\nnumpy.ndarray(float)\n    Look angles or off-nadir angles in (rad)\nnumpy.ndarray(float) \n    Incidence angles in (rad)\n\nRaises\n------\nRuntimeError\n    for bad-value look angle or incidence angles\n\nNotes\n-----\nSee references [1]_ and [2]_ for the equations to calculate \nlook angle and incidence angle, respectivelty.\n\nReferences\n----------\n..[1] https://en.wikipedia.org/wiki/Law_of_cosines\n..[2] https://en.wikipedia.org/wiki/Law_of_sines\n)\");\n}\n", "meta": {"hexsha": "3820adba1b5359abc18da8d02e2dd66d1870bd3b", "size": 3960, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "python/extensions/pybind_isce3/geometry/lookIncFromSr.cpp", "max_stars_repo_name": "isce3-testing/isce3-circleci-poc", "max_stars_repo_head_hexsha": "ec1dfb6019bcdc7afb7beee7be0fa0ce3f3b87b3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "python/extensions/pybind_isce3/geometry/lookIncFromSr.cpp", "max_issues_repo_name": "isce3-testing/isce3-circleci-poc", "max_issues_repo_head_hexsha": "ec1dfb6019bcdc7afb7beee7be0fa0ce3f3b87b3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-23T00:00:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-23T00:00:31.000Z", "max_forks_repo_path": "python/extensions/pybind_isce3/geometry/lookIncFromSr.cpp", "max_forks_repo_name": "isce3-testing/isce3-circleci-poc", "max_forks_repo_head_hexsha": "ec1dfb6019bcdc7afb7beee7be0fa0ce3f3b87b3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-02T21:10:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-02T21:10:11.000Z", "avg_line_length": 31.68, "max_line_length": 102, "alphanum_fraction": 0.6588383838, "num_tokens": 974, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195385342972, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4542588064740875}}
{"text": "#include \"coredsp/filter.h\"\n#include \"coredsp/noise.h\"\n#include \"coreutil/cpu.h\"\n#include <boost/preprocessor.hpp>\n#include <functional>\n#include <chrono>\n#include <vector>\n\ntypedef std::chrono::steady_clock Clock;\ntypedef Clock::time_point TimePoint;\ntypedef Clock::duration Duration;\n\nstatic unsigned iteration_count = 64 * 1024;\n\nstruct Benchmark {\n  const char *name {};\n  std::function<float()> fn;\n  double run() const;\n};\n\ndouble Benchmark::run() const {\n  TimePoint tstart = Clock::now();\n  this->fn();\n  Duration dur = Clock::now() - tstart;\n  auto ns = std::chrono::duration_cast<std::chrono::nanoseconds>(dur);\n  return ns.count() * 1e-9;\n}\n\n#define FIR_NCOEF_MIN 2\n#define FIR_NCOEF_LIMIT 256\n\nstatic constexpr unsigned nfir = FIR_NCOEF_LIMIT - FIR_NCOEF_MIN;\n\n#define DECL_FIR_FLT(z, n, t)                               \\\n  static coredsp::FIR<n, coreutil::simd_t<float>> firf##n;  \\\n  static coredsp::FIR<n, coreutil::simd_t<double>> fird##n;\n#define DECL_FIRG_FLT(z, n, t)                                 \\\n  static coredsp::FIRg<coreutil::simd_t<float>> firgf##n(n);   \\\n  static coredsp::FIRg<coreutil::simd_t<double>> firgd##n(n);\nBOOST_PP_REPEAT_FROM_TO(FIR_NCOEF_MIN, FIR_NCOEF_LIMIT, DECL_FIR_FLT,);\nBOOST_PP_REPEAT_FROM_TO(FIR_NCOEF_MIN, FIR_NCOEF_LIMIT, DECL_FIRG_FLT,);\n\nstatic Benchmark bfirf_simd[nfir], bfirf_scalar[nfir];\nstatic Benchmark bfirgf_simd[nfir], bfirgf_scalar[nfir];\nstatic Benchmark bfird_simd[nfir], bfird_scalar[nfir];\nstatic Benchmark bfirgd_simd[nfir], bfirgd_scalar[nfir];\n\ntemplate <class T> std::function<float()> create_fir_simd_fn(T &filter) {\n  return [&filter]() -> float {\n    float out {};\n    coredsp::WhiteNoise source;\n    for (unsigned i = 0; i < iteration_count; ++i) {\n      filter.in(source.tick());\n      out = filter.impl_simd();\n    }\n    return out;\n  };\n}\n\ntemplate <class T> std::function<float()> create_fir_scalar_fn(T &filter) {\n  return [&filter]() -> float {\n    float out {};\n    coredsp::WhiteNoise source;\n    for (unsigned i = 0; i < iteration_count; ++i) {\n      filter.in(source.tick());\n      out = filter.impl_scalar();\n    }\n    return out;\n  };\n}\n\nint main() {\n  coreutil::disable_denormals();\n\n#define DEF_FIR_BENCHMARK(z, n, t)                                      \\\n  bfirf_simd[n - FIR_NCOEF_MIN] = Benchmark{\"FIR<\" #n \"> simd float\", create_fir_simd_fn(firf##n)}; \\\n  bfirf_scalar[n - FIR_NCOEF_MIN] = Benchmark{\"FIR<\" #n \"> scalar float\", create_fir_scalar_fn(firf##n)}; \\\n  bfirgf_simd[n - FIR_NCOEF_MIN] = Benchmark{\"FIRg<\" #n \"> simd float\", create_fir_simd_fn(firgf##n)}; \\\n  bfirgf_scalar[n - FIR_NCOEF_MIN] = Benchmark{\"FIRg<\" #n \"> scalar float\", create_fir_scalar_fn(firgf##n)}; \\\n  bfird_simd[n - FIR_NCOEF_MIN] = Benchmark{\"FIR<\" #n \"> simd double\", create_fir_simd_fn(fird##n)}; \\\n  bfird_scalar[n - FIR_NCOEF_MIN] = Benchmark{\"FIR<\" #n \"> scalar double\", create_fir_scalar_fn(fird##n)}; \\\n  bfirgd_simd[n - FIR_NCOEF_MIN] = Benchmark{\"FIRg<\" #n \"> simd double\", create_fir_simd_fn(firgd##n)}; \\\n  bfirgd_scalar[n - FIR_NCOEF_MIN] = Benchmark{\"FIRg<\" #n \"> scalar double\", create_fir_scalar_fn(firgd##n)};\n\n  BOOST_PP_REPEAT_FROM_TO(FIR_NCOEF_MIN, FIR_NCOEF_LIMIT, DEF_FIR_BENCHMARK,);\n\n  setlinebuf(stdout);\n\n  for (unsigned i = 0; i < nfir; ++i) {\n    double tsimdf = bfirf_simd[i].run();\n    double tscalarf = bfirf_scalar[i].run();\n    double tgsimdf = bfirgf_simd[i].run();\n    double tgscalarf = bfirgf_scalar[i].run();\n    double tsimdd = bfird_simd[i].run();\n    double tscalard = bfird_scalar[i].run();\n    double tgsimdd = bfirgd_simd[i].run();\n    double tgscalard = bfirgd_scalar[i].run();\n\n    printf(\"%u %f %f %f %f %f %f %f %f\\n\", i + FIR_NCOEF_MIN,\n           tsimdf, tscalarf, tgsimdf, tgscalarf,\n           tsimdd, tscalard, tgsimdd, tgscalard);\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "b26beb1e897ee41449a33450c7153c028bfed3d8", "size": 3782, "ext": "cc", "lang": "C++", "max_stars_repo_path": "programs/fir-benchmark.cc", "max_stars_repo_name": "gerasim13/fast-filters", "max_stars_repo_head_hexsha": "d5d200bff19a404883b55207052d605a852b6245", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 43.0, "max_stars_repo_stars_event_min_datetime": "2017-11-17T08:05:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-05T07:07:40.000Z", "max_issues_repo_path": "programs/fir-benchmark.cc", "max_issues_repo_name": "gerasim13/fast-filters", "max_issues_repo_head_hexsha": "d5d200bff19a404883b55207052d605a852b6245", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-10-05T09:47:49.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-05T11:00:28.000Z", "max_forks_repo_path": "programs/fir-benchmark.cc", "max_forks_repo_name": "gerasim13/fast-filters", "max_forks_repo_head_hexsha": "d5d200bff19a404883b55207052d605a852b6245", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-01-25T09:43:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-09T20:20:35.000Z", "avg_line_length": 35.679245283, "max_line_length": 110, "alphanum_fraction": 0.6679005817, "num_tokens": 1184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195385342972, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4542588064740875}}
{"text": "#pragma once\n#pragma once\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include \"Geometry.hpp\"\n\n#include <vector>\n\nnamespace pointcloudhandler {\n\n\t\tclass Geometry3D : public Geometry {\n\t\tpublic:\n\t\t\t~Geometry3D() override \n\t\t\t{\n\t\t\t}\n\n\t\tprotected:\n\t\t\tGeometry3D(GeometryType type) : Geometry(type, 3) \n\t\t\t{\n\t\t\t}\n\n\t\tpublic:\n\t\t\tGeometry3D& Clear() override = 0;\n\t\t\tbool IsEmpty() const override = 0;\n\t\t\tvirtual Eigen::Vector3d GetMinBound() const = 0;\n\t\t\tvirtual Eigen::Vector3d GetMaxBound() const = 0;\n\t\t\tvirtual Eigen::Vector3d GetCenter() const = 0;\n\n\t\t\tvirtual Geometry3D& Transform(const Eigen::Matrix4d& transformation) = 0;\n\t\t\tvirtual Geometry3D& Translate(const Eigen::Vector3d& translation, bool relative = true) = 0;\n\t\t\tvirtual Geometry3D& Scale(const double scale, bool center = true) = 0;\n\t\t\tvirtual Geometry3D& Rotate(const Eigen::Matrix3d& R, bool center = true) = 0;\n\n\t\tprotected:\n\t\t\tEigen::Vector3d ComputeMinBound(const std::vector<Eigen::Vector3d>& points) const;\n\t\t\tEigen::Vector3d ComputeMaxBound(const std::vector<Eigen::Vector3d>& points) const;\n\t\t\tEigen::Vector3d ComputeCenter(const std::vector<Eigen::Vector3d>& points) const;\n\n\t\t\tvoid TransformPoints(const Eigen::Matrix4d& transformation,std::vector<Eigen::Vector3d>& points) const;\n\t\t\tvoid TranslatePoints(const Eigen::Vector3d& translation,std::vector<Eigen::Vector3d>& points,bool relative) const;\n\t\t\tvoid ScalePoints(const double scale, std::vector<Eigen::Vector3d>& points, bool center) const;\n\t\t\tvoid RotatePoints(const Eigen::Matrix3d& R, std::vector<Eigen::Vector3d>& points, bool center) const;\n\t\t};\n\n}  // namespace pointcloudhandler", "meta": {"hexsha": "e50711189958cf7a655a44e113afa85823470e13", "size": 1622, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "PointCloudHandler/PointCloud/Geometry3D.hpp", "max_stars_repo_name": "serjik85kg/PointCloudHandler", "max_stars_repo_head_hexsha": "c3e91ce4ac334cd603dbe03659fd87d661f322fa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PointCloudHandler/PointCloud/Geometry3D.hpp", "max_issues_repo_name": "serjik85kg/PointCloudHandler", "max_issues_repo_head_hexsha": "c3e91ce4ac334cd603dbe03659fd87d661f322fa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PointCloudHandler/PointCloud/Geometry3D.hpp", "max_forks_repo_name": "serjik85kg/PointCloudHandler", "max_forks_repo_head_hexsha": "c3e91ce4ac334cd603dbe03659fd87d661f322fa", "max_forks_repo_licenses": ["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.5106382979, "max_line_length": 117, "alphanum_fraction": 0.7268803946, "num_tokens": 446, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4542587992751253}}
{"text": "\r\n#include <NTL/mat_lzz_p.h>\r\n\r\n#include <NTL/new.h>\r\n\r\n#include <NTL/vec_long.h>\r\n#include <NTL/vec_ulong.h>\r\n#include <NTL/vec_double.h>\r\n\r\nNTL_START_IMPL\r\n\r\n  \r\nvoid add(mat_zz_p& X, const mat_zz_p& A, const mat_zz_p& B)  \r\n{  \r\n   long n = A.NumRows();  \r\n   long m = A.NumCols();  \r\n  \r\n   if (B.NumRows() != n || B.NumCols() != m)   \r\n      LogicError(\"matrix add: dimension mismatch\");  \r\n  \r\n   X.SetDims(n, m);  \r\n  \r\n   long i, j;  \r\n   for (i = 1; i <= n; i++)   \r\n      for (j = 1; j <= m; j++)  \r\n         add(X(i,j), A(i,j), B(i,j));  \r\n}  \r\n  \r\nvoid sub(mat_zz_p& X, const mat_zz_p& A, const mat_zz_p& B)  \r\n{  \r\n   long n = A.NumRows();  \r\n   long m = A.NumCols();  \r\n  \r\n   if (B.NumRows() != n || B.NumCols() != m)  \r\n      LogicError(\"matrix sub: dimension mismatch\");  \r\n  \r\n   X.SetDims(n, m);  \r\n  \r\n   long i, j;  \r\n   for (i = 1; i <= n; i++)  \r\n      for (j = 1; j <= m; j++)  \r\n         sub(X(i,j), A(i,j), B(i,j));  \r\n}  \r\n  \r\n\r\n// some local buffers\r\n\r\nNTL_THREAD_LOCAL static vec_long mul_aux_vec;\r\nNTL_THREAD_LOCAL static NTL_SPMM_VEC_T precon_vec;\r\n\r\n\r\n\r\nstatic \r\nvoid mul_aux(mat_zz_p& X, const mat_zz_p& A, const mat_zz_p& B)  \r\n{  \r\n   long n = A.NumRows();  \r\n   long l = A.NumCols();  \r\n   long m = B.NumCols();  \r\n  \r\n   if (l != B.NumRows())  \r\n      LogicError(\"matrix mul: dimension mismatch\");  \r\n  \r\n   X.SetDims(n, m); \r\n\r\n   if (m > 1) {  // new preconditioning code\r\n\r\n      long p = zz_p::modulus();\r\n      double pinv = zz_p::ModulusInverse();\r\n\r\n      \r\n      vec_long::Watcher watch_mul_aux_vec(mul_aux_vec);\r\n      mul_aux_vec.SetLength(m);\r\n      long *acc = mul_aux_vec.elts();\r\n\r\n      long i, j, k;\r\n\r\n      for (i = 0; i < n; i++) {\r\n         const zz_p* ap = A[i].elts();\r\n\r\n         for (j = 0; j < m; j++) acc[j] = 0;\r\n\r\n         for (k = 0;  k < l; k++) {   \r\n            long aa = rep(ap[k]);\r\n            if (aa != 0) {\r\n               const zz_p* bp = B[k].elts();\r\n               long T1;\r\n               mulmod_precon_t aapinv = PrepMulModPrecon(aa, p, pinv);\r\n\r\n               for (j = 0; j < m; j++) {\r\n        \t  T1 = MulModPrecon(rep(bp[j]), aa, p, aapinv);\r\n        \t  acc[j] = AddMod(acc[j], T1, p);\r\n               } \r\n            }\r\n         }\r\n\r\n         zz_p *xp = X[i].elts();\r\n         for (j = 0; j < m; j++)\r\n            xp[j].LoopHole() = acc[j];    \r\n      }\r\n   }\r\n   else {  // just use the old code, w/o preconditioning\r\n\r\n      long p = zz_p::modulus();\r\n      double pinv = zz_p::ModulusInverse();\r\n\r\n      long i, j, k;  \r\n      long acc, tmp;  \r\n\r\n      for (i = 1; i <= n; i++) {  \r\n\t for (j = 1; j <= m; j++) {  \r\n            acc = 0;  \r\n            for(k = 1; k <= l; k++) {  \r\n               tmp = MulMod(rep(A(i,k)), rep(B(k,j)), p, pinv);  \r\n               acc = AddMod(acc, tmp, p);  \r\n            }  \r\n            X(i,j).LoopHole() = acc;  \r\n\t } \r\n      }\r\n  \r\n   }\r\n}  \r\n\r\nvoid mul(mat_zz_p& X, const mat_zz_p& A, const mat_zz_p& B)  \r\n{  \r\n   if (&X == &A || &X == &B) {  \r\n      mat_zz_p tmp;  \r\n      mul_aux(tmp, A, B);  \r\n      X = tmp;  \r\n   }  \r\n   else  \r\n      mul_aux(X, A, B);  \r\n}  \r\n\r\n\r\nvoid mul(vec_zz_p& x, const vec_zz_p& a, const mat_zz_p& B)\r\n{\r\n   long l = a.length();\r\n   long m = B.NumCols();\r\n  \r\n   if (l != B.NumRows())  \r\n      LogicError(\"matrix mul: dimension mismatch\");  \r\n\r\n   if (m == 0) { \r\n\r\n      x.SetLength(0);\r\n      \r\n   }\r\n   else if (m == 1) {\r\n\r\n      long p = zz_p::modulus();\r\n      double pinv = zz_p::ModulusInverse();\r\n\r\n      long acc, tmp;\r\n      long k;\r\n\r\n      acc = 0;  \r\n      for(k = 1; k <= l; k++) {  \r\n         tmp = MulMod(rep(a(k)), rep(B(k,1)), p, pinv);  \r\n         acc = AddMod(acc, tmp, p);  \r\n      } \r\n\r\n      x.SetLength(1);\r\n      x(1).LoopHole()  = acc;\r\n          \r\n   }\r\n   else {  // m > 1.  precondition\r\n\r\n\r\n      long p = zz_p::modulus();\r\n      double pinv = zz_p::ModulusInverse();\r\n\r\n      vec_long::Watcher watch_mul_aux_vec(mul_aux_vec);\r\n      mul_aux_vec.SetLength(m);\r\n      long *acc = mul_aux_vec.elts();\r\n\r\n      long j, k;\r\n\r\n\r\n      const zz_p* ap = a.elts();\r\n\r\n      for (j = 0; j < m; j++) acc[j] = 0;\r\n\r\n      for (k = 0;  k < l; k++) {\r\n         long aa = rep(ap[k]);\r\n         if (aa != 0) {\r\n            const zz_p* bp = B[k].elts();\r\n            long T1;\r\n            mulmod_precon_t aapinv = PrepMulModPrecon(aa, p, pinv);\r\n\r\n            for (j = 0; j < m; j++) {\r\n               T1 = MulModPrecon(rep(bp[j]), aa, p, aapinv);\r\n               acc[j] = AddMod(acc[j], T1, p);\r\n            }\r\n         } \r\n      }\r\n\r\n      x.SetLength(m);\r\n      zz_p *xp = x.elts();\r\n      for (j = 0; j < m; j++)\r\n         xp[j].LoopHole() = acc[j];    \r\n   }\r\n}\r\n\r\n  \r\nvoid mul_aux(vec_zz_p& x, const mat_zz_p& A, const vec_zz_p& b)\r\n{\r\n   long n = A.NumRows();\r\n   long l = A.NumCols();\r\n\r\n   if (l != b.length())\r\n      LogicError(\"matrix mul: dimension mismatch\");\r\n\r\n   x.SetLength(n);\r\n   zz_p* xp = x.elts();\r\n\r\n   long p = zz_p::modulus();\r\n   double pinv = zz_p::ModulusInverse();\r\n\r\n   long i, k;\r\n   long acc, tmp;\r\n\r\n   const zz_p* bp = b.elts();\r\n\r\n   if (n <= 1) {\r\n\r\n      for (i = 0; i < n; i++) {\r\n\t acc = 0;\r\n\t const zz_p* ap = A[i].elts();\r\n\r\n\t for (k = 0; k < l; k++) {\r\n            tmp = MulMod(rep(ap[k]), rep(bp[k]), p, pinv);\r\n            acc = AddMod(acc, tmp, p);\r\n\t }\r\n\r\n\t xp[i].LoopHole() = acc;\r\n      }\r\n\r\n   }\r\n   else {\r\n\r\n      NTL_SPMM_VEC_T::Watcher watch_precon_vec(precon_vec);\r\n      precon_vec.SetLength(l);\r\n      mulmod_precon_t *bpinv = precon_vec.elts();\r\n\r\n      for (k = 0; k < l; k++)\r\n         bpinv[k] = PrepMulModPrecon(rep(bp[k]), p, pinv);\r\n\r\n      for (i = 0; i < n; i++) {\r\n\t acc = 0;\r\n\t const zz_p* ap = A[i].elts();\r\n\r\n\t for (k = 0; k < l; k++) {\r\n            tmp = MulModPrecon(rep(ap[k]), rep(bp[k]), p, bpinv[k]);\r\n            acc = AddMod(acc, tmp, p);\r\n\t }\r\n\r\n\t xp[i].LoopHole() = acc;\r\n      } \r\n   }\r\n}\r\n  \r\nvoid mul(vec_zz_p& x, const mat_zz_p& A, const vec_zz_p& b)  \r\n{  \r\n   if (&b == &x || A.position1(x) != -1) {\r\n      vec_zz_p tmp;\r\n      mul_aux(tmp, A, b);\r\n      x = tmp;\r\n   }\r\n   else\r\n      mul_aux(x, A, b);\r\n\r\n}  \r\n\r\n\r\nvoid mul(mat_zz_p& X, const mat_zz_p& A, zz_p b)\r\n{\r\n   long n = A.NumRows();\r\n   long m = A.NumCols();\r\n\r\n   X.SetDims(n, m);\r\n\r\n   long i, j;\r\n\r\n   if (n == 0 || m == 0 || (n == 1 && m == 1)) {\r\n\r\n      for (i = 0; i < n; i++)\r\n\t for (j = 0; j < m; j++)\r\n            mul(X[i][j], A[i][j], b);\r\n\r\n   }\r\n   else {\r\n      \r\n      long p = zz_p::modulus();\r\n      double pinv = zz_p::ModulusInverse();\r\n      long bb = rep(b);\r\n      mulmod_precon_t bpinv = PrepMulModPrecon(bb, p, pinv);\r\n      \r\n      for (i = 0; i < n; i++) {\r\n         const zz_p *ap = A[i].elts();\r\n         zz_p *xp = X[i].elts();\r\n\r\n\t for (j = 0; j < m; j++)\r\n            xp[j].LoopHole() = MulModPrecon(rep(ap[j]), bb, p, bpinv);\r\n      }\r\n\r\n   }\r\n}\r\n\r\nvoid mul(mat_zz_p& X, const mat_zz_p& A, long b_in)\r\n{\r\n   zz_p b;\r\n   b = b_in;\r\n   mul(X, A, b);\r\n} \r\n\r\n\r\n\r\n\r\n     \r\n  \r\nvoid ident(mat_zz_p& X, long n)  \r\n{  \r\n   X.SetDims(n, n);  \r\n   long i, j;  \r\n  \r\n   for (i = 1; i <= n; i++)  \r\n      for (j = 1; j <= n; j++)  \r\n         if (i == j)  \r\n            set(X(i, j));  \r\n         else  \r\n            clear(X(i, j));  \r\n} \r\n\r\n\r\n\r\nvoid determinant(zz_p& d, const mat_zz_p& M_in)\r\n{\r\n   long k, n;\r\n   long i, j;\r\n   long pos;\r\n   zz_p t1, t2, t3;\r\n   zz_p *x, *y;\r\n\r\n   mat_zz_p M;\r\n   M = M_in;\r\n\r\n   n = M.NumRows();\r\n\r\n   if (M.NumCols() != n)\r\n      LogicError(\"determinant: nonsquare matrix\");\r\n\r\n   if (n == 0) {\r\n      set(d);\r\n      return;\r\n   }\r\n\r\n   zz_p det;\r\n\r\n   set(det);\r\n\r\n   long p = zz_p::modulus();\r\n   double pinv = zz_p::ModulusInverse();\r\n\r\n   for (k = 0; k < n; k++) {\r\n      pos = -1;\r\n      for (i = k; i < n; i++) {\r\n         if (!IsZero(M[i][k])) {\r\n            pos = i;\r\n            break;\r\n         }\r\n      }\r\n\r\n      if (pos != -1) {\r\n         if (k != pos) {\r\n            swap(M[pos], M[k]);\r\n            negate(det, det);\r\n         }\r\n\r\n         mul(det, det, M[k][k]);\r\n\r\n         inv(t3, M[k][k]);\r\n\r\n         for (i = k+1; i < n; i++) {\r\n            // M[i] = M[i] - M[k]*M[i,k]*t3\r\n\r\n            mul(t1, M[i][k], t3);\r\n            negate(t1, t1);\r\n\r\n            x = M[i].elts() + (k+1);\r\n            y = M[k].elts() + (k+1);\r\n\r\n            long T1 = rep(t1);\r\n            mulmod_precon_t t1pinv = PrepMulModPrecon(T1, p, pinv); // T1*pinv; \r\n            long T2;\r\n\r\n            for (j = k+1; j < n; j++, x++, y++) {\r\n               // *x = *x + (*y)*t1\r\n\r\n               T2 = MulModPrecon(rep(*y), T1, p, t1pinv);\r\n               x->LoopHole() = AddMod(rep(*x), T2, p); \r\n            }\r\n         }\r\n      }\r\n      else {\r\n         clear(d);\r\n         return;\r\n      }\r\n   }\r\n\r\n   d = det;\r\n}\r\n\r\n\r\n\r\n\r\nlong IsIdent(const mat_zz_p& A, long n)\r\n{\r\n   if (A.NumRows() != n || A.NumCols() != n)\r\n      return 0;\r\n\r\n   long i, j;\r\n\r\n   for (i = 1; i <= n; i++)\r\n      for (j = 1; j <= n; j++)\r\n         if (i != j) {\r\n            if (!IsZero(A(i, j))) return 0;\r\n         }\r\n         else {\r\n            if (!IsOne(A(i, j))) return 0;\r\n         }\r\n\r\n   return 1;\r\n}\r\n            \r\n\r\nvoid transpose(mat_zz_p& X, const mat_zz_p& A)\r\n{\r\n   long n = A.NumRows();\r\n   long m = A.NumCols();\r\n\r\n   long i, j;\r\n\r\n   if (&X == & A) {\r\n      if (n == m)\r\n         for (i = 1; i <= n; i++)\r\n            for (j = i+1; j <= n; j++)\r\n               swap(X(i, j), X(j, i));\r\n      else {\r\n         mat_zz_p tmp;\r\n         tmp.SetDims(m, n);\r\n         for (i = 1; i <= n; i++)\r\n            for (j = 1; j <= m; j++)\r\n               tmp(j, i) = A(i, j);\r\n         X.kill();\r\n         X = tmp;\r\n      }\r\n   }\r\n   else {\r\n      X.SetDims(m, n);\r\n      for (i = 1; i <= n; i++)\r\n         for (j = 1; j <= m; j++)\r\n            X(j, i) = A(i, j);\r\n   }\r\n}\r\n   \r\n\r\nvoid solve(zz_p& d, vec_zz_p& X, \r\n           const mat_zz_p& A, const vec_zz_p& b)\r\n\r\n{\r\n   long n = A.NumRows();\r\n\r\n   if (A.NumCols() != n)\r\n      LogicError(\"solve: nonsquare matrix\");\r\n\r\n\r\n   if (b.length() != n)\r\n      LogicError(\"solve: dimension mismatch\");\r\n\r\n   if (n == 0) {\r\n      set(d);\r\n      X.SetLength(0);\r\n      return;\r\n   }\r\n\r\n   long i, j, k, pos;\r\n   zz_p t1, t2, t3;\r\n   zz_p *x, *y;\r\n\r\n   mat_zz_p M;\r\n   M.SetDims(n, n+1);\r\n   for (i = 0; i < n; i++) {\r\n      for (j = 0; j < n; j++) \r\n         M[i][j] = A[j][i];\r\n      M[i][n] = b[i];\r\n   }\r\n\r\n   zz_p det;\r\n   set(det);\r\n\r\n   long p = zz_p::modulus();\r\n   double pinv = zz_p::ModulusInverse();\r\n\r\n   for (k = 0; k < n; k++) {\r\n      pos = -1;\r\n      for (i = k; i < n; i++) {\r\n         if (!IsZero(M[i][k])) {\r\n            pos = i;\r\n            break;\r\n         }\r\n      }\r\n\r\n      if (pos != -1) {\r\n         if (k != pos) {\r\n            swap(M[pos], M[k]);\r\n            negate(det, det);\r\n         }\r\n\r\n         mul(det, det, M[k][k]);\r\n\r\n         inv(t3, M[k][k]);\r\n         M[k][k] = t3;\r\n\r\n\r\n         for (i = k+1; i < n; i++) {\r\n            // M[i] = M[i] - M[k]*M[i,k]*t3\r\n\r\n            mul(t1, M[i][k], t3);\r\n            negate(t1, t1);\r\n\r\n            x = M[i].elts() + (k+1);\r\n            y = M[k].elts() + (k+1);\r\n\r\n            long T1 = rep(t1);\r\n            mulmod_precon_t  t1pinv = PrepMulModPrecon(T1, p, pinv); // T1*pinv;\r\n            long T2;\r\n\r\n            for (j = k+1; j <= n; j++, x++, y++) {\r\n               // *x = *x + (*y)*t1\r\n\r\n               T2 = MulModPrecon(rep(*y), T1, p, t1pinv);\r\n               x->LoopHole() = AddMod(rep(*x), T2, p);\r\n            }\r\n         }\r\n      }\r\n      else {\r\n         clear(d);\r\n         return;\r\n      }\r\n   }\r\n\r\n   X.SetLength(n);\r\n   for (i = n-1; i >= 0; i--) {\r\n      clear(t1);\r\n      for (j = i+1; j < n; j++) {\r\n         mul(t2, X[j], M[i][j]);\r\n         add(t1, t1, t2);\r\n      }\r\n      sub(t1, M[i][n], t1);\r\n      mul(X[i], t1, M[i][i]);\r\n   }\r\n\r\n   d = det;\r\n}\r\n\r\nvoid inv(zz_p& d, mat_zz_p& X, const mat_zz_p& A)\r\n{\r\n   long n = A.NumRows();\r\n   if (A.NumCols() != n)\r\n      LogicError(\"inv: nonsquare matrix\");\r\n\r\n   if (n == 0) {\r\n      set(d);\r\n      X.SetDims(0, 0);\r\n      return;\r\n   }\r\n\r\n   long i, j, k, pos;\r\n   zz_p t1, t2, t3;\r\n   zz_p *x, *y;\r\n\r\n   mat_zz_p M;\r\n   M.SetDims(n, 2*n);\r\n   for (i = 0; i < n; i++) {\r\n      for (j = 0; j < n; j++) {\r\n         M[i][j] = A[i][j];\r\n         clear(M[i][n+j]);\r\n      }\r\n      set(M[i][n+i]);\r\n   }\r\n\r\n   zz_p det;\r\n   set(det);\r\n\r\n   long p = zz_p::modulus();\r\n   double pinv = zz_p::ModulusInverse();\r\n\r\n   for (k = 0; k < n; k++) {\r\n      pos = -1;\r\n      for (i = k; i < n; i++) {\r\n         if (!IsZero(M[i][k])) {\r\n            pos = i;\r\n            break;\r\n         }\r\n      }\r\n\r\n      if (pos != -1) {\r\n         if (k != pos) {\r\n            swap(M[pos], M[k]);\r\n            negate(det, det);\r\n         }\r\n\r\n         mul(det, det, M[k][k]);\r\n\r\n         inv(t3, M[k][k]);\r\n         M[k][k] = t3;\r\n\r\n         for (i = k+1; i < n; i++) {\r\n            // M[i] = M[i] - M[k]*M[i,k]*t3\r\n\r\n            mul(t1, M[i][k], t3);\r\n            negate(t1, t1);\r\n\r\n            x = M[i].elts() + (k+1);\r\n            y = M[k].elts() + (k+1);\r\n\r\n            long T1 = rep(t1);\r\n            mulmod_precon_t t1pinv = PrepMulModPrecon(T1, p, pinv); // T1*pinv;\r\n            long T2;\r\n\r\n            for (j = k+1; j < 2*n; j++, x++, y++) {\r\n               // *x = *x + (*y)*t1\r\n\r\n               T2 = MulModPrecon(rep(*y), T1, p, t1pinv);\r\n               x->LoopHole() = AddMod(rep(*x), T2, p);\r\n            }\r\n         }\r\n      }\r\n      else {\r\n         clear(d);\r\n         return;\r\n      }\r\n   }\r\n\r\n   X.SetDims(n, n);\r\n   for (k = 0; k < n; k++) {\r\n      for (i = n-1; i >= 0; i--) {\r\n         clear(t1);\r\n         for (j = i+1; j < n; j++) {\r\n            mul(t2, X[j][k], M[i][j]);\r\n            add(t1, t1, t2);\r\n         }\r\n         sub(t1, M[i][n+k], t1);\r\n         mul(X[i][k], t1, M[i][i]);\r\n      }\r\n   }\r\n\r\n   d = det;\r\n}\r\n\r\nlong gauss(mat_zz_p& M, long w)\r\n{\r\n   long k, l;\r\n   long i, j;\r\n   long pos;\r\n   zz_p t1, t2, t3;\r\n   zz_p *x, *y;\r\n\r\n   long n = M.NumRows();\r\n   long m = M.NumCols();\r\n\r\n   if (w < 0 || w > m)\r\n      LogicError(\"gauss: bad args\");\r\n\r\n   long p = zz_p::modulus();\r\n   double pinv = zz_p::ModulusInverse();\r\n   long T1, T2;\r\n\r\n   l = 0;\r\n   for (k = 0; k < w && l < n; k++) {\r\n\r\n      pos = -1;\r\n      for (i = l; i < n; i++) {\r\n         if (!IsZero(M[i][k])) {\r\n            pos = i;\r\n            break;\r\n         }\r\n      }\r\n\r\n      if (pos != -1) {\r\n         swap(M[pos], M[l]);\r\n\r\n         inv(t3, M[l][k]);\r\n         negate(t3, t3);\r\n\r\n         for (i = l+1; i < n; i++) {\r\n            // M[i] = M[i] + M[l]*M[i,k]*t3\r\n\r\n            mul(t1, M[i][k], t3);\r\n\r\n            T1 = rep(t1);\r\n            mulmod_precon_t T1pinv = PrepMulModPrecon(T1, p, pinv); // ((double) T1)*pinv;\r\n\r\n            clear(M[i][k]);\r\n\r\n            x = M[i].elts() + (k+1);\r\n            y = M[l].elts() + (k+1);\r\n\r\n            for (j = k+1; j < m; j++, x++, y++) {\r\n               // *x = *x + (*y)*t1\r\n\r\n               T2 = MulModPrecon(rep(*y), T1, p, T1pinv);\r\n               T2 = AddMod(T2, rep(*x), p);\r\n               (*x).LoopHole() = T2;\r\n            }\r\n         }\r\n\r\n         l++;\r\n      }\r\n   }\r\n\r\n   return l;\r\n}\r\n\r\nlong gauss(mat_zz_p& M)\r\n{\r\n   return gauss(M, M.NumCols());\r\n}\r\n\r\nvoid image(mat_zz_p& X, const mat_zz_p& A)\r\n{\r\n   mat_zz_p M;\r\n   M = A;\r\n   long r = gauss(M);\r\n   M.SetDims(r, M.NumCols());\r\n   X = M;\r\n}\r\n\r\nvoid kernel(mat_zz_p& X, const mat_zz_p& A)\r\n{\r\n   long m = A.NumRows();\r\n   long n = A.NumCols();\r\n\r\n   mat_zz_p M;\r\n   long r;\r\n\r\n   transpose(M, A);\r\n   r = gauss(M);\r\n\r\n   X.SetDims(m-r, m);\r\n\r\n   long i, j, k, s;\r\n   zz_p t1, t2;\r\n\r\n   vec_long D;\r\n   D.SetLength(m);\r\n   for (j = 0; j < m; j++) D[j] = -1;\r\n\r\n   vec_zz_p inverses;\r\n   inverses.SetLength(m);\r\n\r\n   j = -1;\r\n   for (i = 0; i < r; i++) {\r\n      do {\r\n         j++;\r\n      } while (IsZero(M[i][j]));\r\n\r\n      D[j] = i;\r\n      inv(inverses[j], M[i][j]); \r\n   }\r\n\r\n   for (k = 0; k < m-r; k++) {\r\n      vec_zz_p& v = X[k];\r\n      long pos = 0;\r\n      for (j = m-1; j >= 0; j--) {\r\n         if (D[j] == -1) {\r\n            if (pos == k)\r\n               set(v[j]);\r\n            else\r\n               clear(v[j]);\r\n            pos++;\r\n         }\r\n         else {\r\n            i = D[j];\r\n\r\n            clear(t1);\r\n\r\n            for (s = j+1; s < m; s++) {\r\n               mul(t2, v[s], M[i][s]);\r\n               add(t1, t1, t2);\r\n            }\r\n\r\n            mul(t1, t1, inverses[j]);\r\n            negate(v[j], t1);\r\n         }\r\n      }\r\n   }\r\n}\r\n   \r\n\r\n\r\n\r\n\r\nvoid diag(mat_zz_p& X, long n, zz_p d)  \r\n{  \r\n   X.SetDims(n, n);  \r\n   long i, j;  \r\n  \r\n   for (i = 1; i <= n; i++)  \r\n      for (j = 1; j <= n; j++)  \r\n         if (i == j)  \r\n            X(i, j) = d;  \r\n         else  \r\n            clear(X(i, j));  \r\n} \r\n\r\nlong IsDiag(const mat_zz_p& A, long n, zz_p d)\r\n{\r\n   if (A.NumRows() != n || A.NumCols() != n)\r\n      return 0;\r\n\r\n   long i, j;\r\n\r\n   for (i = 1; i <= n; i++)\r\n      for (j = 1; j <= n; j++)\r\n         if (i != j) {\r\n            if (!IsZero(A(i, j))) return 0;\r\n         }\r\n         else {\r\n            if (A(i, j) != d) return 0;\r\n         }\r\n\r\n   return 1;\r\n}\r\n\r\nvoid negate(mat_zz_p& X, const mat_zz_p& A)\r\n{\r\n   long n = A.NumRows();\r\n   long m = A.NumCols();\r\n\r\n\r\n   X.SetDims(n, m);\r\n\r\n   long i, j;\r\n   for (i = 1; i <= n; i++)\r\n      for (j = 1; j <= m; j++)\r\n         negate(X(i,j), A(i,j));\r\n}\r\n\r\nlong IsZero(const mat_zz_p& a)\r\n{\r\n   long n = a.NumRows();\r\n   long i;\r\n\r\n   for (i = 0; i < n; i++)\r\n      if (!IsZero(a[i]))\r\n         return 0;\r\n\r\n   return 1;\r\n}\r\n\r\nvoid clear(mat_zz_p& x)\r\n{\r\n   long n = x.NumRows();\r\n   long i;\r\n   for (i = 0; i < n; i++)\r\n      clear(x[i]);\r\n}\r\n\r\n\r\nmat_zz_p operator+(const mat_zz_p& a, const mat_zz_p& b)\r\n{\r\n   mat_zz_p res;\r\n   add(res, a, b);\r\n   NTL_OPT_RETURN(mat_zz_p, res);\r\n}\r\n\r\nmat_zz_p operator*(const mat_zz_p& a, const mat_zz_p& b)\r\n{\r\n   mat_zz_p res;\r\n   mul_aux(res, a, b);\r\n   NTL_OPT_RETURN(mat_zz_p, res);\r\n}\r\n\r\nmat_zz_p operator-(const mat_zz_p& a, const mat_zz_p& b)\r\n{\r\n   mat_zz_p res;\r\n   sub(res, a, b);\r\n   NTL_OPT_RETURN(mat_zz_p, res);\r\n}\r\n\r\n\r\nmat_zz_p operator-(const mat_zz_p& a)\r\n{\r\n   mat_zz_p res;\r\n   negate(res, a);\r\n   NTL_OPT_RETURN(mat_zz_p, res);\r\n}\r\n\r\n\r\nvec_zz_p operator*(const mat_zz_p& a, const vec_zz_p& b)\r\n{\r\n   vec_zz_p res;\r\n   mul_aux(res, a, b);\r\n   NTL_OPT_RETURN(vec_zz_p, res);\r\n}\r\n\r\nvec_zz_p operator*(const vec_zz_p& a, const mat_zz_p& b)\r\n{\r\n   vec_zz_p res;\r\n   mul(res, a, b);\r\n   NTL_OPT_RETURN(vec_zz_p, res);\r\n}\r\n\r\nvoid inv(mat_zz_p& X, const mat_zz_p& A)\r\n{\r\n   zz_p d;\r\n   inv(d, X, A);\r\n   if (d == 0) ArithmeticError(\"inv: non-invertible matrix\");\r\n}\r\n\r\nvoid power(mat_zz_p& X, const mat_zz_p& A, const ZZ& e)\r\n{\r\n   if (A.NumRows() != A.NumCols()) LogicError(\"power: non-square matrix\");\r\n\r\n   if (e == 0) {\r\n      ident(X, A.NumRows());\r\n      return;\r\n   }\r\n\r\n   mat_zz_p T1, T2;\r\n   long i, k;\r\n\r\n   k = NumBits(e);\r\n   T1 = A;\r\n\r\n   for (i = k-2; i >= 0; i--) {\r\n      sqr(T2, T1);\r\n      if (bit(e, i))\r\n         mul(T1, T2, A);\r\n      else\r\n         T1 = T2;\r\n   }\r\n\r\n   if (e < 0)\r\n      inv(X, T1);\r\n   else\r\n      X = T1;\r\n}\r\n\r\nNTL_END_IMPL\r\n", "meta": {"hexsha": "d9aa78da188790434c6ef554ce82908045597631", "size": 19011, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "WinNTL-8_1_2/src/mat_lzz_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/mat_lzz_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/mat_lzz_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.9695378151, "max_line_length": 91, "alphanum_fraction": 0.3912471727, "num_tokens": 6438, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4542587992751253}}
{"text": "/*\n  [auto_generated]\n  boost/numeric/odeint/stepper/bulirsch_stoer.hpp\n\n  [begin_description]\n  Implementation of the Burlish-Stoer method. As described in\n  Ernst Hairer, Syvert Paul Norsett, Gerhard Wanner\n  Solving Ordinary Differential Equations I. Nonstiff Problems.\n  Springer Series in Comput. Mathematics, Vol. 8, Springer-Verlag 1987, Second revised edition 1993.\n  [end_description]\n\n  Copyright 2011-2013 Mario Mulansky\n  Copyright 2011-2013 Karsten Ahnert\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_BULIRSCH_STOER_HPP_INCLUDED\n#define BOOST_NUMERIC_ODEINT_STEPPER_BULIRSCH_STOER_HPP_INCLUDED\n\n\n#include <iostream>\n\n#include <algorithm>\n\n#include <boost/config.hpp> // for min/max guidelines\n\n#include <boost/numeric/odeint/util/bind.hpp>\n#include <boost/numeric/odeint/util/unwrap_reference.hpp>\n\n#include <boost/numeric/odeint/stepper/controlled_runge_kutta.hpp>\n#include <boost/numeric/odeint/stepper/modified_midpoint.hpp>\n#include <boost/numeric/odeint/stepper/controlled_step_result.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#include <boost/numeric/odeint/util/unit_helper.hpp>\n#include <boost/numeric/odeint/util/detail/less_with_sign.hpp>\n\nnamespace boost {\nnamespace numeric {\nnamespace odeint {\n\ntemplate<\n    class State ,\n    class Value = double ,\n    class Deriv = State ,\n    class Time = Value ,\n    class Algebra = typename algebra_dispatcher< State >::algebra_type ,\n    class Operations = typename operations_dispatcher< State >::operations_type ,\n    class Resizer = initially_resizer\n    >\nclass bulirsch_stoer {\n\npublic:\n\n    typedef State state_type;\n    typedef Value value_type;\n    typedef Deriv deriv_type;\n    typedef Time time_type;\n    typedef Algebra algebra_type;\n    typedef Operations operations_type;\n    typedef Resizer resizer_type;\n#ifndef DOXYGEN_SKIP\n    typedef state_wrapper< state_type > wrapped_state_type;\n    typedef state_wrapper< deriv_type > wrapped_deriv_type;\n    typedef controlled_stepper_tag stepper_category;\n\n    typedef bulirsch_stoer< State , Value , Deriv , Time , Algebra , Operations , Resizer > controlled_error_bs_type;\n\n    typedef typename inverse_time< time_type >::type inv_time_type;\n\n    typedef std::vector< value_type > value_vector;\n    typedef std::vector< time_type > time_vector;\n    typedef std::vector< inv_time_type > inv_time_vector;  //should be 1/time_type for boost.units\n    typedef std::vector< value_vector > value_matrix;\n    typedef std::vector< size_t > int_vector;\n    typedef std::vector< wrapped_state_type > state_table_type;\n#endif //DOXYGEN_SKIP\n    const static size_t m_k_max = 8;\n\n    bulirsch_stoer(\n        value_type eps_abs = 1E-6 , value_type eps_rel = 1E-6 ,\n        value_type factor_x = 1.0 , value_type factor_dxdt = 1.0 ,\n        time_type max_dt = static_cast<time_type>(0))\n        : m_error_checker( eps_abs , eps_rel , factor_x, factor_dxdt ) , m_midpoint() ,\n          m_last_step_rejected( false ) , m_first( true ) ,\n          m_max_dt(max_dt) ,\n          m_interval_sequence( m_k_max+1 ) ,\n          m_coeff( m_k_max+1 ) ,\n          m_cost( m_k_max+1 ) ,\n          m_facmin_table( m_k_max+1 ) ,\n          m_table( m_k_max ) ,\n          STEPFAC1( 0.65 ) , STEPFAC2( 0.94 ) , STEPFAC3( 0.02 ) , STEPFAC4( 4.0 ) , KFAC1( 0.8 ) , KFAC2( 0.9 )\n    {\n        BOOST_USING_STD_MIN();\n        BOOST_USING_STD_MAX();\n        /* initialize sequence of stage numbers and work */\n        for( unsigned short i = 0; i < m_k_max+1; i++ )\n        {\n            m_interval_sequence[i] = 2 * (i+1);\n            if( i == 0 )\n                m_cost[i] = m_interval_sequence[i];\n            else\n                m_cost[i] = m_cost[i-1] + m_interval_sequence[i];\n            m_coeff[i].resize(i);\n            m_facmin_table[i] = pow BOOST_PREVENT_MACRO_SUBSTITUTION( STEPFAC3 , static_cast< value_type >(1) / static_cast< value_type >( 2*i+1 ) );\n            for( size_t k = 0 ; k < i ; ++k  )\n            {\n                const value_type r = static_cast< value_type >( m_interval_sequence[i] ) / static_cast< value_type >( m_interval_sequence[k] );\n                m_coeff[i][k] = 1.0 / ( r*r - static_cast< value_type >( 1.0 ) ); // coefficients for extrapolation\n            }\n        }\n        reset();\n    }\n\n\n    /*\n     * Version 1 : try_step( sys , x , t , dt )\n     *\n     * The overloads are needed to solve the forwarding problem\n     */\n    template< class System , class StateInOut >\n    controlled_step_result try_step( System system , StateInOut &x , time_type &t , time_type &dt )\n    {\n        return try_step_v1( system , x , t, dt );\n    }\n\n    /**\n     * \\brief Second version to solve the forwarding problem, can be used with Boost.Range as StateInOut.\n     */\n    template< class System , class StateInOut >\n    controlled_step_result try_step( System system , const StateInOut &x , time_type &t , time_type &dt )\n    {\n        return try_step_v1( system , x , t, dt );\n    }\n\n    /*\n     * Version 2 : try_step( sys , x , dxdt , t , dt )\n     *\n     * this version does not solve the forwarding problem, boost.range can not be used\n     */\n    template< class System , class StateInOut , class DerivIn >\n    controlled_step_result try_step( System system , StateInOut &x , const DerivIn &dxdt , time_type &t , time_type &dt )\n    {\n        m_xnew_resizer.adjust_size( x , detail::bind( &controlled_error_bs_type::template resize_m_xnew< StateInOut > , detail::ref( *this ) , detail::_1 ) );\n        controlled_step_result res = try_step( system , x , dxdt , t , m_xnew.m_v , dt );\n        if( res == success )\n        {\n            boost::numeric::odeint::copy( m_xnew.m_v , x );\n        }\n        return res;\n    }\n\n    /*\n     * Version 3 : try_step( sys , in , t , out , dt )\n     *\n     * this version does not solve the forwarding problem, boost.range can not be used\n     */\n    template< class System , class StateIn , class StateOut >\n    typename boost::disable_if< boost::is_same< StateIn , time_type > , controlled_step_result >::type\n    try_step( System system , const StateIn &in , time_type &t , StateOut &out , time_type &dt )\n    {\n        typename odeint::unwrap_reference< System >::type &sys = system;\n        m_dxdt_resizer.adjust_size( in , detail::bind( &controlled_error_bs_type::template resize_m_dxdt< StateIn > , detail::ref( *this ) , detail::_1 ) );\n        sys( in , m_dxdt.m_v , t );\n        return try_step( system , in , m_dxdt.m_v , t , out , dt );\n    }\n\n\n    /*\n     * Full version : try_step( sys , in , dxdt_in , t , out , dt )\n     *\n     * contains the actual implementation\n     */\n    template< class System , class StateIn , class DerivIn , class StateOut >\n    controlled_step_result try_step( System system , const StateIn &in , const DerivIn &dxdt , time_type &t , StateOut &out , time_type &dt )\n    {\n        if( m_max_dt != static_cast<time_type>(0) && detail::less_with_sign(m_max_dt, dt, dt) )\n        {\n            // given step size is bigger then max_dt\n            // set limit and return fail\n            dt = m_max_dt;\n            return fail;\n        }\n\n        BOOST_USING_STD_MIN();\n        BOOST_USING_STD_MAX();\n\n        static const value_type val1( 1.0 );\n\n        if( m_resizer.adjust_size( in , detail::bind( &controlled_error_bs_type::template resize_impl< StateIn > , detail::ref( *this ) , detail::_1 ) ) )\n        {\n            reset(); // system resized -> reset\n        }\n\n        if( dt != m_dt_last )\n        {\n            reset(); // step size changed from outside -> reset\n        }\n\n        bool reject( true );\n\n        time_vector h_opt( m_k_max+1 );\n        inv_time_vector work( m_k_max+1 );\n\n        time_type new_h = dt;\n\n        /* m_current_k_opt is the estimated current optimal stage number */\n        for( size_t k = 0 ; k <= m_current_k_opt+1 ; k++ )\n        {\n            /* the stage counts are stored in m_interval_sequence */\n            m_midpoint.set_steps( m_interval_sequence[k] );\n            if( k == 0 )\n            {\n                m_midpoint.do_step( system , in , dxdt , t , out , dt );\n                /* the first step, nothing more to do */\n            }\n            else\n            {\n                m_midpoint.do_step( system , in , dxdt , t , m_table[k-1].m_v , dt );\n                extrapolate( k , m_table , m_coeff , out );\n                // get error estimate\n                m_algebra.for_each3( m_err.m_v , out , m_table[0].m_v ,\n                                     typename operations_type::template scale_sum2< value_type , value_type >( val1 , -val1 ) );\n                const value_type error = m_error_checker.error( m_algebra , in , dxdt , m_err.m_v , dt );\n                h_opt[k] = calc_h_opt( dt , error , k );\n                work[k] = static_cast<value_type>( m_cost[k] ) / h_opt[k];\n\n                if( (k == m_current_k_opt-1) || m_first )\n                { // convergence before k_opt ?\n                    if( error < 1.0 )\n                    {\n                        //convergence\n                        reject = false;\n                        if( (work[k] < KFAC2*work[k-1]) || (m_current_k_opt <= 2) )\n                        {\n                            // leave order as is (except we were in first round)\n                            m_current_k_opt = min BOOST_PREVENT_MACRO_SUBSTITUTION( static_cast<int>(m_k_max)-1 , max BOOST_PREVENT_MACRO_SUBSTITUTION( 2 , static_cast<int>(k)+1 ) );\n                            new_h = h_opt[k];\n                            new_h *= static_cast<value_type>( m_cost[k+1] ) / static_cast<value_type>( m_cost[k] );\n                        } else {\n                            m_current_k_opt = min BOOST_PREVENT_MACRO_SUBSTITUTION( static_cast<int>(m_k_max)-1 , max BOOST_PREVENT_MACRO_SUBSTITUTION( 2 , static_cast<int>(k) ) );\n                            new_h = h_opt[k];\n                        }\n                        break;\n                    }\n                    else if( should_reject( error , k ) && !m_first )\n                    {\n                        reject = true;\n                        new_h = h_opt[k];\n                        break;\n                    }\n                }\n                if( k == m_current_k_opt )\n                { // convergence at k_opt ?\n                    if( error < 1.0 )\n                    {\n                        //convergence\n                        reject = false;\n                        if( (work[k-1] < KFAC2*work[k]) )\n                        {\n                            m_current_k_opt = max BOOST_PREVENT_MACRO_SUBSTITUTION( 2 , static_cast<int>(m_current_k_opt)-1 );\n                            new_h = h_opt[m_current_k_opt];\n                        }\n                        else if( (work[k] < KFAC2*work[k-1]) && !m_last_step_rejected )\n                        {\n                            m_current_k_opt = min BOOST_PREVENT_MACRO_SUBSTITUTION( static_cast<int>(m_k_max-1) , static_cast<int>(m_current_k_opt)+1 );\n                            new_h = h_opt[k];\n                            new_h *= static_cast<value_type>(m_cost[m_current_k_opt])/static_cast<value_type>(m_cost[k]);\n                        } else\n                            new_h = h_opt[m_current_k_opt];\n                        break;\n                    }\n                    else if( should_reject( error , k ) )\n                    {\n                        reject = true;\n                        new_h = h_opt[m_current_k_opt];\n                        break;\n                    }\n                }\n                if( k == m_current_k_opt+1 )\n                { // convergence at k_opt+1 ?\n                    if( error < 1.0 )\n                    {   //convergence\n                        reject = false;\n                        if( work[k-2] < KFAC2*work[k-1] )\n                            m_current_k_opt = max BOOST_PREVENT_MACRO_SUBSTITUTION( 2 , static_cast<int>(m_current_k_opt)-1 );\n                        if( (work[k] < KFAC2*work[m_current_k_opt]) && !m_last_step_rejected )\n                            m_current_k_opt = min BOOST_PREVENT_MACRO_SUBSTITUTION( static_cast<int>(m_k_max)-1 , static_cast<int>(k) );\n                        new_h = h_opt[m_current_k_opt];\n                    } else\n                    {\n                        reject = true;\n                        new_h = h_opt[m_current_k_opt];\n                    }\n                    break;\n                }\n            }\n        }\n\n        if( !reject )\n        {\n            t += dt;\n        }\n\n        if( !m_last_step_rejected || boost::numeric::odeint::detail::less_with_sign(new_h, dt, dt) )\n        {\n            // limit step size\n            if( m_max_dt != static_cast<time_type>(0) )\n            {\n                new_h = detail::min_abs(m_max_dt, new_h);\n            }\n            m_dt_last = new_h;\n            dt = new_h;\n        }\n\n        m_last_step_rejected = reject;\n        m_first = false;\n\n        if( reject )\n            return fail;\n        else\n            return success;\n    }\n\n    /** \\brief Resets the internal state of the stepper */\n    void reset()\n    {\n        m_first = true;\n        m_last_step_rejected = false;\n        // crude estimate of optimal order\n        m_current_k_opt = 4;\n        /* no calculation because log10 might not exist for value_type!\n        const value_type logfact( -log10( max BOOST_PREVENT_MACRO_SUBSTITUTION( eps_rel , static_cast< value_type >(1.0E-12) ) ) * 0.6 + 0.5 );\n        m_current_k_opt = max BOOST_PREVENT_MACRO_SUBSTITUTION( static_cast<value_type>( 1 ) , min BOOST_PREVENT_MACRO_SUBSTITUTION( static_cast<value_type>( m_k_max-1 ) , logfact ));\n        */\n    }\n\n\n    /* Resizer methods */\n\n    template< class StateIn >\n    void adjust_size( const StateIn &x )\n    {\n        resize_m_dxdt( x );\n        resize_m_xnew( x );\n        resize_impl( x );\n        m_midpoint.adjust_size( x );\n    }\n\n\nprivate:\n\n    template< class StateIn >\n    bool resize_m_dxdt( const StateIn &x )\n    {\n        return adjust_size_by_resizeability( m_dxdt , x , typename is_resizeable<deriv_type>::type() );\n    }\n\n    template< class StateIn >\n    bool resize_m_xnew( const StateIn &x )\n    {\n        return adjust_size_by_resizeability( m_xnew , x , typename is_resizeable<state_type>::type() );\n    }\n\n    template< class StateIn >\n    bool resize_impl( const StateIn &x )\n    {\n        bool resized( false );\n        for( size_t i = 0 ; i < m_k_max ; ++i )\n            resized |= adjust_size_by_resizeability( m_table[i] , x , typename is_resizeable<state_type>::type() );\n        resized |= adjust_size_by_resizeability( m_err , x , typename is_resizeable<state_type>::type() );\n        return resized;\n    }\n\n\n    template< class System , class StateInOut >\n    controlled_step_result try_step_v1( System system , StateInOut &x , time_type &t , time_type &dt )\n    {\n        typename odeint::unwrap_reference< System >::type &sys = system;\n        m_dxdt_resizer.adjust_size( x , detail::bind( &controlled_error_bs_type::template resize_m_dxdt< StateInOut > , detail::ref( *this ) , detail::_1 ) );\n        sys( x , m_dxdt.m_v ,t );\n        return try_step( system , x , m_dxdt.m_v , t , dt );\n    }\n\n\n    template< class StateInOut >\n    void extrapolate( size_t k , state_table_type &table , const value_matrix &coeff , StateInOut &xest )\n    /* polynomial extrapolation, see http://www.nr.com/webnotes/nr3web21.pdf\n       uses the obtained intermediate results to extrapolate to dt->0\n    */\n    {\n        static const value_type val1 = static_cast< value_type >( 1.0 );\n        for( int j=k-1 ; j>0 ; --j )\n        {\n            m_algebra.for_each3( table[j-1].m_v , table[j].m_v , table[j-1].m_v ,\n                                 typename operations_type::template scale_sum2< value_type , value_type >( val1 + coeff[k][j] , -coeff[k][j] ) );\n        }\n        m_algebra.for_each3( xest , table[0].m_v , xest ,\n                             typename operations_type::template scale_sum2< value_type , value_type >( val1 + coeff[k][0] , -coeff[k][0]) );\n    }\n\n    time_type calc_h_opt( time_type h , value_type error , size_t k ) const\n    /* calculates the optimal step size for a given error and stage number */\n    {\n        BOOST_USING_STD_MIN();\n        BOOST_USING_STD_MAX();\n        using std::pow;\n        value_type expo( 1.0/(2*k+1) );\n        value_type facmin = m_facmin_table[k];\n        value_type fac;\n        if (error == 0.0)\n            fac=1.0/facmin;\n        else\n        {\n            fac = STEPFAC2 / pow BOOST_PREVENT_MACRO_SUBSTITUTION( error / STEPFAC1 , expo );\n            fac = max BOOST_PREVENT_MACRO_SUBSTITUTION( static_cast<value_type>(facmin/STEPFAC4) , min BOOST_PREVENT_MACRO_SUBSTITUTION( static_cast<value_type>(1.0/facmin) , fac ) );\n        }\n        return h*fac;\n    }\n\n    controlled_step_result set_k_opt( size_t k , const inv_time_vector &work , const time_vector &h_opt , time_type &dt )\n    /* calculates the optimal stage number */\n    {\n        if( k == 1 )\n        {\n            m_current_k_opt = 2;\n            return success;\n        }\n        if( (work[k-1] < KFAC1*work[k]) || (k == m_k_max) )\n        {   // order decrease\n            m_current_k_opt = k-1;\n            dt = h_opt[ m_current_k_opt ];\n            return success;\n        }\n        else if( (work[k] < KFAC2*work[k-1]) || m_last_step_rejected || (k == m_k_max-1) )\n        {   // same order - also do this if last step got rejected\n            m_current_k_opt = k;\n            dt = h_opt[ m_current_k_opt ];\n            return success;\n        }\n        else\n        {   // order increase - only if last step was not rejected\n            m_current_k_opt = k+1;\n            dt = h_opt[ m_current_k_opt-1 ] * m_cost[ m_current_k_opt ] / m_cost[ m_current_k_opt-1 ] ;\n            return success;\n        }\n    }\n\n    bool in_convergence_window( size_t k ) const\n    {\n        if( (k == m_current_k_opt-1) && !m_last_step_rejected )\n            return true; // decrease stepsize only if last step was not rejected\n        return ( (k == m_current_k_opt) || (k == m_current_k_opt+1) );\n    }\n\n    bool should_reject( value_type error , size_t k ) const\n    {\n        if( k == m_current_k_opt-1 )\n        {\n            const value_type d = m_interval_sequence[m_current_k_opt] * m_interval_sequence[m_current_k_opt+1] /\n                (m_interval_sequence[0]*m_interval_sequence[0]);\n            //step will fail, criterion 17.3.17 in NR\n            return ( error > d*d );\n        }\n        else if( k == m_current_k_opt )\n        {\n            const value_type d = m_interval_sequence[m_current_k_opt] / m_interval_sequence[0];\n            return ( error > d*d );\n        } else\n            return error > 1.0;\n    }\n\n    default_error_checker< value_type, algebra_type , operations_type > m_error_checker;\n    modified_midpoint< state_type , value_type , deriv_type , time_type , algebra_type , operations_type , resizer_type > m_midpoint;\n\n    bool m_last_step_rejected;\n    bool m_first;\n\n    time_type m_dt_last;\n    time_type m_t_last;\n    time_type m_max_dt;\n\n    size_t m_current_k_opt;\n\n    algebra_type m_algebra;\n\n    resizer_type m_dxdt_resizer;\n    resizer_type m_xnew_resizer;\n    resizer_type m_resizer;\n\n    wrapped_state_type m_xnew;\n    wrapped_state_type m_err;\n    wrapped_deriv_type m_dxdt;\n\n    int_vector m_interval_sequence; // stores the successive interval counts\n    value_matrix m_coeff;\n    int_vector m_cost; // costs for interval count\n    value_vector m_facmin_table; // for precomputed facmin to save pow calls\n\n    state_table_type m_table; // sequence of states for extrapolation\n\n    value_type STEPFAC1 , STEPFAC2 , STEPFAC3 , STEPFAC4 , KFAC1 , KFAC2;\n};\n\n\n/******** DOXYGEN ********/\n/**\n * \\class bulirsch_stoer\n * \\brief The Bulirsch-Stoer algorithm.\n *\n * The Bulirsch-Stoer is a controlled stepper that adjusts both step size\n * and order of the method. The algorithm uses the modified midpoint and\n * a polynomial extrapolation compute the solution.\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 bulirsch_stoer::bulirsch_stoer( value_type eps_abs , value_type eps_rel , value_type factor_x , value_type factor_dxdt )\n     * \\brief Constructs the bulirsch_stoer class, including initialization of\n     * the error bounds.\n     *\n     * \\param eps_abs Absolute tolerance level.\n     * \\param eps_rel Relative tolerance level.\n     * \\param factor_x Factor for the weight of the state.\n     * \\param factor_dxdt Factor for the weight of the derivative.\n     */\n\n    /**\n     * \\fn bulirsch_stoer::try_step( System system , StateInOut &x , time_type &t , time_type &dt )\n     * \\brief Tries to perform one step.\n     *\n     * This method tries to do one step with step size dt. If the error estimate\n     * is to large, the step is rejected and the method returns fail and the\n     * step size dt is reduced. If the error estimate is acceptably small, the\n     * step is performed, success is returned and dt might be increased to make\n     * the steps as large as possible. This method also updates t if a step is\n     * performed. Also, the internal order of the stepper is adjusted if required.\n     *\n     * \\param system The system function to solve, hence the r.h.s. of the ODE.\n     * It must fulfill the Simple System concept.\n     * \\param x The state of the ODE which should be solved. Overwritten if\n     * the step is successful.\n     * \\param t The value of the time. Updated if the step is successful.\n     * \\param dt The step size. Updated.\n     * \\return success if the step was accepted, fail otherwise.\n     */\n\n    /**\n     * \\fn bulirsch_stoer::try_step( System system , StateInOut &x , const DerivIn &dxdt , time_type &t , time_type &dt )\n     * \\brief Tries to perform one step.\n     *\n     * This method tries to do one step with step size dt. If the error estimate\n     * is to large, the step is rejected and the method returns fail and the\n     * step size dt is reduced. If the error estimate is acceptably small, the\n     * step is performed, success is returned and dt might be increased to make\n     * the steps as large as possible. This method also updates t if a step is\n     * performed. Also, the internal order of the stepper is adjusted if required.\n     *\n     * \\param system The system function to solve, hence the r.h.s. of the ODE.\n     * It must fulfill the Simple System concept.\n     * \\param x The state of the ODE which should be solved. Overwritten if\n     * the step is successful.\n     * \\param dxdt The derivative of state.\n     * \\param t The value of the time. Updated if the step is successful.\n     * \\param dt The step size. Updated.\n     * \\return success if the step was accepted, fail otherwise.\n     */\n\n    /**\n     * \\fn bulirsch_stoer::try_step( System system , const StateIn &in , time_type &t , StateOut &out , time_type &dt )\n     * \\brief Tries to perform one step.\n     *\n     * \\note This method is disabled if state_type=time_type to avoid ambiguity.\n     *\n     * This method tries to do one step with step size dt. If the error estimate\n     * is to large, the step is rejected and the method returns fail and the\n     * step size dt is reduced. If the error estimate is acceptably small, the\n     * step is performed, success is returned and dt might be increased to make\n     * the steps as large as possible. This method also updates t if a step is\n     * performed. Also, the internal order of the stepper is adjusted if required.\n     *\n     * \\param system The system function to solve, hence the r.h.s. of the ODE.\n     * It must fulfill the Simple System concept.\n     * \\param in The state of the ODE which should be solved.\n     * \\param t The value of the time. Updated if the step is successful.\n     * \\param out Used to store the result of the step.\n     * \\param dt The step size. Updated.\n     * \\return success if the step was accepted, fail otherwise.\n     */\n\n\n    /**\n     * \\fn bulirsch_stoer::try_step( System system , const StateIn &in , const DerivIn &dxdt , time_type &t , StateOut &out , time_type &dt )\n     * \\brief Tries to perform one step.\n     *\n     * This method tries to do one step with step size dt. If the error estimate\n     * is to large, the step is rejected and the method returns fail and the\n     * step size dt is reduced. If the error estimate is acceptably small, the\n     * step is performed, success is returned and dt might be increased to make\n     * the steps as large as possible. This method also updates t if a step is\n     * performed. Also, the internal order of the stepper is adjusted if required.\n     *\n     * \\param system The system function to solve, hence the r.h.s. of the ODE.\n     * It must fulfill the Simple System concept.\n     * \\param in The state of the ODE which should be solved.\n     * \\param dxdt The derivative of state.\n     * \\param t The value of the time. Updated if the step is successful.\n     * \\param out Used to store the result of the step.\n     * \\param dt The step size. Updated.\n     * \\return success if the step was accepted, fail otherwise.\n     */\n\n\n    /**\n     * \\fn bulirsch_stoer::adjust_size( const StateIn &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}\n}\n}\n\n#endif // BOOST_NUMERIC_ODEINT_STEPPER_BULIRSCH_STOER_HPP_INCLUDED\n", "meta": {"hexsha": "0f5553fdd248aed8b883334f16c819f45c428a94", "size": 26172, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/src/boost_1_65_1/boost/numeric/odeint/stepper/bulirsch_stoer.hpp", "max_stars_repo_name": "shreyasvj25/turicreate", "max_stars_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11356.0, "max_stars_repo_stars_event_min_datetime": "2017-12-08T19:42:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:55:25.000Z", "max_issues_repo_path": "deps/src/boost_1_65_1/boost/numeric/odeint/stepper/bulirsch_stoer.hpp", "max_issues_repo_name": "shreyasvj25/turicreate", "max_issues_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2402.0, "max_issues_repo_issues_event_min_datetime": "2017-12-08T22:31:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:25:52.000Z", "max_forks_repo_path": "deps/src/boost_1_65_1/boost/numeric/odeint/stepper/bulirsch_stoer.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": 40.7029548989, "max_line_length": 183, "alphanum_fraction": 0.6075194865, "num_tokens": 6494, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.734119526900183, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.45425879927512525}}
{"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_CONSTANT_FOUROPI_HPP_INCLUDED\n#define BOOST_SIMD_CONSTANT_FOUROPI_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n  /*!\n\n    @ingroup group-constant\n\n    Constant \\f$\\frac4\\pi\\f$.\n\n\n    @par Header <boost/simd/constant/fouropi.hpp>\n\n    @par Semantic:\n\n    For type T:\n\n    @code\n    T r = Fouropi<T>();\n    @endcode\n\n    is similar to:\n\n    @code\n    T r = Four<T>()/Pi<T>();\n    @endcode\n\n    @return a value of type T\n\n**/\n  template<typename T> T Fouropi();\n\n  namespace functional\n  {\n    /*!\n      @ingroup group-callable-constant\n\n\n      Constant \\f$\\frac4\\pi\\f$.\n\n      Generate the  constant fouropi.\n\n      @return The Fouropi constant for the proper type\n    **/\n    Value Fouropi();\n  }\n} }\n#endif\n\n#include <boost/simd/constant/scalar/fouropi.hpp>\n#include <boost/simd/constant/simd/fouropi.hpp>\n\n#endif\n", "meta": {"hexsha": "96fa8713f88b922887d4dcb08cdfe657f42e0fec", "size": 1255, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/constant/fouropi.hpp", "max_stars_repo_name": "TobiasLudwig/boost.simd", "max_stars_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/simd/constant/fouropi.hpp", "max_issues_repo_name": "TobiasLudwig/boost.simd", "max_issues_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/constant/fouropi.hpp", "max_forks_repo_name": "TobiasLudwig/boost.simd", "max_forks_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-02-16T09:58:18.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:22:43.000Z", "avg_line_length": 19.0151515152, "max_line_length": 100, "alphanum_fraction": 0.5553784861, "num_tokens": 302, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195152660687, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.45425879207616293}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n\n#include <utils/types.hpp>\n\ntemplate<int Dimension>\nstruct Ray\n{\n    Eigen::Matrix<double, Dimension, 1> origin;\n    Eigen::Matrix<double, Dimension, 1> direction;\n\n    /*\n     * Ray constructor\n    **/\n    Ray(const Eigen::Matrix<double, Dimension, 1>& o = Eigen::Matrix<double, Dimension, 1>::Zero(),\n        const Eigen::Matrix<double, Dimension, 1>& d = Eigen::Matrix<double, Dimension, 1>::Zero())\n    : origin(o), direction(d)\n    {}\n\n    /*\n     * Ray destructor\n    **/\n    ~Ray(){};\n};\n\nusing Ray2D = Ray<2>;\nusing Ray3D = Ray<3>;\n\nusing Rays2D = AlignedVector<Ray2D>;\nusing Rays3D = AlignedVector<Ray3D>;\n\n/*\n * the custom operator<< for Ray\n**/\ntemplate<int Dimension>\nstd::ostream& operator<<(std::ostream& os, const Ray<Dimension>& r)\n{\n    os << \"origin: \" << r.origin << \"\\n\";\n    os << \"direction: \" << r.direction;\n\n    return os;\n}\n", "meta": {"hexsha": "f605b5a2d141747c62feba8b9191490fb8282c83", "size": 888, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/geometry/ray.hpp", "max_stars_repo_name": "charlybigoud/kidocam", "max_stars_repo_head_hexsha": "5cf2d59194a48897b35f0e3c8e3cea39b748c3d0", "max_stars_repo_licenses": ["MIT"], "max_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/ray.hpp", "max_issues_repo_name": "charlybigoud/kidocam", "max_issues_repo_head_hexsha": "5cf2d59194a48897b35f0e3c8e3cea39b748c3d0", "max_issues_repo_licenses": ["MIT"], "max_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/ray.hpp", "max_forks_repo_name": "charlybigoud/kidocam", "max_forks_repo_head_hexsha": "5cf2d59194a48897b35f0e3c8e3cea39b748c3d0", "max_forks_repo_licenses": ["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.1818181818, "max_line_length": 99, "alphanum_fraction": 0.6137387387, "num_tokens": 244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.709019146082187, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.45422309161289387}}
{"text": "//# /Users/arnold/Documents/prg/clang/bin/clang++ -U__STRICT_ANSI__ -std=c++14 -I/Users/arnold/Documents/prg/libraries/boost_1_56_0/ -I/Developer/SDKs/MacOSX10.6.sdk/usr/include -I/Users/arnold/Documents/prg/libraries/cryptopp563/include -Wall -O2 -L/Users/arnold/Documents/prg/libraries/boost_1_56_0/stage/lib -L/Users/arnold/Documents/prg/libraries/cryptopp563/lib -o apfel2 apfel2.cpp -lboost_system -lboost_filesystem -lboost_iostreams -lcryptopp\n\n#include <iostream>\n#include <boost/filesystem.hpp>\n#include <vector>\n#include <string>\n#include <array>\n#include <algorithm>\n#include <complex>\n#include <boost/format.hpp>\n#include <future>\n#include <utility>\n\nusing namespace std;\n\ntemplate<typename T>\nstruct window {\n\twindow(const T& xmin, const T& ymin, const T& xmax, const T& ymax) \n\t\t: xmin_{xmin}, ymin_{ymin}, xmax_{xmax}, ymax_{ymax}\n\t{\n\t\tif (xmin_ > xmax_) \n\t\t\tswap(xmin_, xmax_);\n\t\tif (ymin_ > ymax_) \n\t\t\tswap(ymin_, ymax_);\n\t}\n\twindow() = default;\n\tT width() const { return xmax_ - xmin_; }\n\tT height() const { return ymax_ - ymin_; }\n\tvoid zoom(const double& fx, const double& fy) {\n\t\t//double ffx = 1.0/fx;\n\t\t//double ffy = 1.0/fy;\n\t\tdouble dx = width() * fx/2.0;\n\t\tdouble dy = height() * fy/2.0;\n\t\txmin_ += dx;\n\t\txmax_ -= dx;\n\t\tymin_ += dy;\n\t\tymax_ -= dy;\n\t}\n\tvoid zoom(const double& f) {\n\t\tzoom(f, f);\n/*\n\t\tdouble ff = 1.0/f;\n\t\tdouble dx = width() * ff/2.0;\n\t\tdouble dy = height() * ff/2.0;\n\t\txmin_ += dx;\n\t\txmax_ -= dx;\n\t\tymin_ += dy;\n\t\tymax_ -= dy;*/\n\t}\n\tvoid move(const double& h, const double& v) {\n\t\tdouble dx = width() * h;\n\t\tdouble dy = height() * v;\n\t\txmin_ += dx;\n\t\txmax_ += dx;\n\t\tymin_ += dy;\n\t\tymax_ += dy;\n\t}\n\tT xmin_ {-2};\n\tT ymin_ {-1.5};\n\tT xmax_ {1};\n\tT ymax_ {1.5};\n};\n\nstruct fract {\n\tusing it_t = unsigned;\n\twindow<double>     imgrange_;\n\twindow<unsigned>   dim_;\n\t\n};\n\ntemplate<typename T>\nostream& operator<<(ostream& o, const window<T>& w) {\n\to << boost::format{\"(%1.15f, %1.15f)-(%1.15f, %1.15f)\"} % w.xmin_ % w.ymin_ % w.xmax_ % w.ymax_;\n\treturn o;\n}\n\nstruct pxmap {\n\tpxmap(unsigned maxit, unsigned width, unsigned height)\n\t\t: maxit_{maxit+1}, width_{width}, height_{height}, px_(width_ * height_)\n\t{}\n\tunsigned maxit_;\n\tunsigned width_;\n\tunsigned height_;\n\tvector<unsigned> px_;\n\tstatic const array<char, 14> ch_; // = {{ ' ', '.', ',', ':', ';', '+', 'i', 'I', '%', 'H', '8', 'M', '#'}};\n\tvoid print() {\n\t\tunsigned pn = 0;\n\t\tfor(const auto& p : px_) {\n\t\t\tcout << ch_[static_cast<double>(p)/maxit_ * pxmap::ch_.size()];\t\n\t\t\tif (++pn % width_ == 0) {\n\t\t\t\tcout << endl;\n\t\t\t}\n\t\t}\n\t\tcout << endl;\n\t}\n};\n\nconstexpr const array<char, 14> pxmap::ch_ = {{ ' ', '.', ',', ':', ';', '+', 'i', 'I', '%', 'H', '8', 'M', '#', '*'}};\n\nint main (int argc, char const *argv[])\n{\n\tusing cpt = complex<double>;\n\tdouble escval = 4.0;\n\tvector<string> params(argv, argv + argc);\n//\tcin >> noskipws;\n\ttry {\n//\t\twindow<unsigned> p(0, 100, 0, 20);\n\t\tcpt ca(1,0.5);\n/*\t\tcout << ca << endl;\n\t\tcout << ca * ca * ca << endl;\n\t\tcout << pow(ca,3) << endl;*/\n\t\twindow<double> w;//(-1.5,0,0.5,1);\n\t\tunsigned maxit = 100;\n\t\tunsigned rows = 100;\n\t\tunsigned lines = rows * 1.0/2.0;\n\t\tdouble exp = 2.0;\n\t\tfor(unsigned it = 0; true; ++it) {\n\t\t\tif (it > 0) {\n\t\t\t\tcout << w << \" \" << maxit << \" esc:\" << escval << \" exp:\" << exp << \" zoom In, zoom Out, Left, Right, Up, Down, +iterate, -iterate, +Esc, -esc, +Wide, -wide, +Pow, -pow, Quit: \";\n\t\t\t\tstring cc;\n\t\t\t\tgetline(cin, cc);\n\t\t\t\tchar c;\n\t\t\t\tc = cc.at(0);\n\t\t\t\tcout << endl;\n\t\t\t\tswitch(c) {\n\t\t\t\t\tcase 'q' :\n\t\t\t\t\t\texit(0);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'l':\n\t\t\t\t\t\tw.move(-0.25, 0);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'r':\n\t\t\t\t\t\tw.move(0.25, 0);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'u':\n\t\t\t\t\t\tw.move(0,0.25);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'd':\n\t\t\t\t\t\tw.move(0,-0.25);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'i':\n\t\t\t\t\t\tw.zoom(0.5);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'o':\n\t\t\t\t\t\tw.zoom(-1);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase '+':\n\t\t\t\t\t\tmaxit *= 2.0;\n\t\t\t\t\t\tmaxit = min(1u<<16,maxit);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase '-':\n\t\t\t\t\t\tmaxit /= 2.0;\n\t\t\t\t\t\tmaxit = max(1u,maxit);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'e':\n\t\t\t\t\t\tescval /= 2.0;\n\t\t\t\t\t\tescval = max(1.0, escval);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'E':\n\t\t\t\t\t\tescval *= 2.0;\n\t\t\t\t\t\tescval = min(256.0, escval);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'W':\n\t\t\t\t\t\trows += rows * 0.25;\n\t\t\t\t\t\tw.zoom(-0.25, 0);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'w':\n\t\t\t\t\t\trows -= rows/4.0;\n\t\t\t\t\t\tw.zoom(0.25, 0);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'P':\n\t\t\t\t\t\texp += 0.1;\n\t\t\t\t\t\texp = min(10.0, exp);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'p':\n\t\t\t\t\t\texp -= 0.1;\n\t\t\t\t\t\texp = max(0.1, exp);\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tdouble stepx = w.width() / static_cast<double>(rows);\n\t\t\tdouble stepy = w.height() / static_cast<double>(lines);\n\t\t\tcout << stepx << \", \" << stepy << endl;\n\t\t\t//cout << endl;\n\t\t\tpxmap pm(maxit, rows, lines);\n\t\t\tauto pmit = pm.px_.begin();\n\t\t\tfor(unsigned iy = 0; iy < lines; ++iy) {\n\t\t\t\tdouble y = w.ymax_ - stepy * iy;\n\t\t\t//for(double y = w.ymax_; y > w.ymin_; y -= stepy) {\n\t\t\t\tfor(unsigned ix = 0; ix < rows; ++ix) {\n\t\t\t\t\tdouble x = w.xmin_ + stepx * ix;\n\t\t\t\t//for(double x = w.xmin_; x < w.xmax_; x += stepx) {\n\t\t\t\t\tunsigned i = 0;\n\t\t\t\t\t//bool isin = true;\n\t\t\t\t\tcpt c(0,0);\n\t\t\t\t\tcpt cc(x,y);\n\t\t\t\t\tfor(; i < maxit; ++i) {\n\t\t\t\t\t\t//c = c * c + cc;\n\t\t\t\t\t\tc = pow(c, exp) + cc;\n\t\t\t\t\t\tif (c.real() * c.real() + c.imag() * c.imag() > escval) {\n\t\t\t\t\t\t\t//isin = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t} \n\t\t\t\t\t}\n\t\t\t\t\t*pmit = i;\n\t\t\t\t\t++pmit;\n\t\t\t\t}\n\t\t\t\tcout << endl;\n\t\t\t}\n//\t\t\tcout << \"********************\" << endl;\n\t\t\tpm.print();\n\t\t}\n\t} catch(...) {\n\t\tcerr << \"Unknown exception\" << endl;\n\t}\n\treturn 0;\n}", "meta": {"hexsha": "ba32e3e08a15314584cca916d94300dd5cea8260", "size": 5415, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp14/apfel2.cpp", "max_stars_repo_name": "noeld/cpp", "max_stars_repo_head_hexsha": "572a145f8c79f7292b7b0611822ed34792df4e9c", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cpp14/apfel2.cpp", "max_issues_repo_name": "noeld/cpp", "max_issues_repo_head_hexsha": "572a145f8c79f7292b7b0611822ed34792df4e9c", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp14/apfel2.cpp", "max_forks_repo_name": "noeld/cpp", "max_forks_repo_head_hexsha": "572a145f8c79f7292b7b0611822ed34792df4e9c", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.9539170507, "max_line_length": 450, "alphanum_fraction": 0.5318559557, "num_tokens": 1894, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191460821871, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.4542230867482165}}
{"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 *      120203    B. Tong Minh      Copied RungeKutta4Stepsize unit test.\n *      120207    K. Kumar          Adapted to use modified benchmark functions in Tudat Core.\n *      120213    K. Kumar          Modified getCurrentInterval() to getIndependentVariable();\n *                                  transferred to Boost unit test framework.\n *      120321    K. Kumar          Updated (Burden and Faires, 2011) benchmark function call.\n *      120328    K. Kumar          Removed specific integrator tests; added compiler tests; added\n *                                  test of runtime error when minimm step size is exceeded.\n *      120331    B. Tong Minh      Added typeid check for RungeKuttaVariableStepSizeIntegratorXd\n *                                  typedef; modified minimum step size exceeded unit tests to use\n *                                  custom exception object.\n *      120321    D.Dirkx           Added unit test for getCurrentStateDerivatives function.\n *\n *    References\n *      Burden, R.L., Faires, J.D. Numerical Analysis, 7th Edition, Books/Cole, 2001.\n *\n *    Notes\n *      This file doesn't test any specific Runge-Kutta-type integrators, but rather some general\n *      functionality adopted in the the RungeKuttaVariableStepSizeIntegrator class, applicable to\n *      all Runge-Kutta-type integrators.\n *\n *      It should be noted that the getCurrentStateDerivatives() member function is not tested in a\n *      fully generic manner at the moment; the test is setup specifically based on the \n *      Runge-Kutta-Fehlberg 4(5) (RKF45) integrator. A more comprehensive test should be designed\n *      to ensure that the member function performs as desired regardless of the coefficient set\n *      chosen.\n *\n */\n\n#define BOOST_TEST_MAIN\n\n\n#include <boost/exception/all.hpp>\n#include <boost/test/unit_test.hpp>\n\n#include \"Tudat/Mathematics/NumericalIntegrators/rungeKuttaVariableStepSizeIntegrator.h\"\n#include \"Tudat/Mathematics/NumericalIntegrators/rungeKutta4Integrator.h\"\n#include \"Tudat/Mathematics/NumericalIntegrators/rungeKuttaCoefficients.h\"\n#include \"Tudat/Basics/testMacros.h\"\n#include \"Tudat/Mathematics/NumericalIntegrators/UnitTests/numericalIntegratorTestFunctions.h\"\n\n#include <limits>\n#include <string>\n#include <typeinfo>\n\nnamespace tudat\n{\nnamespace unit_tests\n{\n\nusing numerical_integrators::RungeKuttaCoefficients;\nusing numerical_integrators::RungeKuttaVariableStepSizeIntegrator;\nusing numerical_integrators::RungeKuttaVariableStepSizeIntegratorXd;\nusing numerical_integrator_test_functions::computeZeroStateDerivative;\n\nBOOST_AUTO_TEST_SUITE( test_runge_kutta_variable_step_size_integrator )\n\n//! Test different types of states and state derivatives.\nBOOST_AUTO_TEST_CASE( testCompilerErrors )\n{\n    // Case 1: test the VectorXd typdef. There is no need to explicitly test anything, since we're\n    //         looking for compiler errors.\n    {\n        RungeKuttaVariableStepSizeIntegratorXd integrator(\n                    RungeKuttaCoefficients( ),\n                    &computeZeroStateDerivative,\n                    0.0,\n                    Eigen::Vector3d::Zero( ),\n                    0.01,\n                    std::numeric_limits< double >::infinity( ),\n                    10.0 * std::numeric_limits< double >::epsilon( ),\n                    10.0 * std::numeric_limits< double >::epsilon( ) );\n\n        // Test integrateTo() function.\n        integrator.integrateTo( 10.0, 0.1 );\n\n        // Test performIntegrationStep() function.\n        integrator.performIntegrationStep( 0.1 );\n\n        // Test rollbackToPreviousState() function.\n        integrator.rollbackToPreviousState( );\n\n        // Check if the default types are correct.\n        BOOST_CHECK_EQUAL(\n                    std::string( typeid( integrator.getCurrentIndependentVariable( ) ).name( ) ),\n                    std::string( typeid( double ).name( ) ) );\n        BOOST_CHECK_EQUAL( std::string( typeid( integrator.getCurrentState( ) ).name( ) ),\n                           std::string( typeid( Eigen::VectorXd ).name( ) ) );\n    }\n\n    // Case 2: test different types of states and state derivatives. There is no need to explicitly\n    //         test anything, since we're looking for compiler errors.\n    {\n        RungeKuttaVariableStepSizeIntegrator < double, Eigen::Vector3d, Eigen::VectorXd >\n                integrator( RungeKuttaCoefficients( ),\n                            &computeZeroStateDerivative,\n                            0.0,\n                            Eigen::Vector3d::Zero( ),\n                            0.01,\n                            std::numeric_limits< double >::infinity( ),\n                            10.0 * std::numeric_limits< double >::epsilon( ),\n                            10.0 * std::numeric_limits< double >::epsilon( ) );\n\n        // Test integrateTo() function.\n        integrator.integrateTo( 10.0, 0.1 );\n\n        // Test performIntegrationStep() function.\n        integrator.performIntegrationStep( 0.1 );\n\n        // Test rollbackToPreviousState() function.\n        integrator.rollbackToPreviousState( );\n    }\n\n    // Case 3: test same types of states and state derivatives (MatrixXd). There is no need to\n    //         explicitly test anything, since we're looking for compiler errors.\n    {\n        RungeKuttaVariableStepSizeIntegrator < double, Eigen::MatrixXd, Eigen::MatrixXd >\n                integrator( RungeKuttaCoefficients( ),\n                            &computeZeroStateDerivative,\n                            0.0,\n                            Eigen::Vector3d::Zero( ),\n                            0.01,\n                            std::numeric_limits< double >::infinity( ),\n                            10.0 * std::numeric_limits< double >::epsilon( ),\n                            10.0 * std::numeric_limits< double >::epsilon( ) );\n\n        // Test integrateTo() function.\n        integrator.integrateTo( 10.0, 0.1 );\n\n        // Test performIntegrationStep() function.\n        integrator.performIntegrationStep( 0.1 );\n\n        // Test rollbackToPreviousState() function.\n        integrator.rollbackToPreviousState( );\n    }\n}\n\n//! Test that exceeding minimum step size throws a runtime error.\nBOOST_AUTO_TEST_CASE( testMinimumStepSizeRuntimeError )\n{\n    RungeKuttaVariableStepSizeIntegratorXd integrator(\n                RungeKuttaCoefficients( ),\n                &computeZeroStateDerivative,\n                0.0,\n                Eigen::Vector3d::Zero( ),\n                100.0,\n                std::numeric_limits< double >::infinity( ),\n                std::numeric_limits< double >::epsilon( ),\n                std::numeric_limits< double >::epsilon( ) );\n\n    // Case 1: test that minimum step size is exceeded when using integrateTo().\n    {\n        // Declare boolean flag to test if minimum step size is exceed for integrateTo().\n        bool isMinimumStepSizeExceededForIntegrateTo = false;\n\n        // Try integrateTo(), which should result in a runtime error.\n        try\n        {\n            // Test integrateTo() function.\n            integrator.integrateTo( 10.0, 0.1 );\n        }\n\n        // Catch the expected runtime error, and set the boolean flag to true.\n        catch ( RungeKuttaVariableStepSizeIntegratorXd::MinimumStepSizeExceededError\n                minimumStepSizeExceededError )\n        {\n            isMinimumStepSizeExceededForIntegrateTo = true;\n            BOOST_CHECK_EQUAL( minimumStepSizeExceededError.minimumStepSize, 100.0 );\n        }\n\n        // Check that the minimum step size was indeed exceeded.\n        BOOST_CHECK( isMinimumStepSizeExceededForIntegrateTo );\n    }\n\n    // Case 2: test that minimum step size is exceeded when using performIntegrationStep().\n    {\n        // Declare boolean flag to test if minimum step size is exceed for\n        // performIntegrationStep().\n        bool isMinimumStepSizeExceededForPerformIntegrationStep = false;\n\n        // Try performIntegrationStep(), which should result in a runtime error.\n        try\n        {\n            // Test performIntegrationStep() function.\n            integrator.performIntegrationStep( 0.1 );\n        }\n\n        // Catch the expected runtime error, and set the boolean flag to true.\n        catch ( RungeKuttaVariableStepSizeIntegratorXd::MinimumStepSizeExceededError\n                minimumStepSizeExceededError )\n        {\n            isMinimumStepSizeExceededForPerformIntegrationStep = true;\n            BOOST_CHECK_EQUAL( minimumStepSizeExceededError.minimumStepSize, 100.0 );\n        }\n\n        // Check that the minimum step size was indeed exceeded.\n        BOOST_CHECK( isMinimumStepSizeExceededForPerformIntegrationStep );\n    }\n}\n\n//! Test if the state derivative evaliations are properly returned.\nBOOST_AUTO_TEST_CASE( testStateDerivativeRetrievalFunction )\n{\n    using namespace numerical_integrators;\n    using namespace unit_tests::numerical_integrator_test_functions;\n\n    // This test is based on the Runge-Kutta-Fehlberg 4(5) coefficient set, hence the test does not\n    // robustly ensure that the getCurrentStateDerivatives() works correctly for any given \n    // coefficient set currently. This test is more of an preliminary check that the function \n    // performs as required, with the extrapolation that it is likely to perform consistently in\n    // this manner for any Runge-Kutta-type coefficient set.\n\n    // Create test integrator.\n    RungeKuttaVariableStepSizeIntegratorXd integrator(\n                RungeKuttaCoefficients::get( RungeKuttaCoefficients::rungeKuttaFehlberg45 ),\n                &computeVanDerPolStateDerivative,\n                0.0,\n                ( Eigen::VectorXd( 2 ) << 1.0, 2.0 ).finished( ),\n                0.0, 10.0, 1.0E-8, 1.0E-8 );\n\n    // Perform first integration step.\n    integrator.performIntegrationStep( 1.0 );\n\n    // Retrieve time and state after first integration step.\n    const double previousTime = integrator.getCurrentIndependentVariable( );\n    const Eigen::VectorXd previousState = integrator.getCurrentState( );\n\n    // Perform additional integration step to verify that there are no problems with\n    // getCurrentStateDerivatives after >1 iterations (i.e not being reset etc.).\n    integrator.performIntegrationStep( integrator.getNextStepSize( ) );\n\n    // Get current time and previous time step.\n    const double currentTime = integrator.getCurrentIndependentVariable( );\n    const double stepSize = currentTime - previousTime;\n\n    // Retrieve state derivative values used in previous time step.\n    std::vector< Eigen::VectorXd > stateDerivatives = integrator.getCurrentStateDerivatives( );\n\n    // Check size of state derivative vector. This test is specifically set up to test the for the \n    // number of stages in the RKF45 integrator.\n    BOOST_CHECK_EQUAL( stateDerivatives.size( ), 6 );\n\n    // Perform manual state derivative evaluations at previous time step using RKF45 method\n    RungeKuttaCoefficients rkf45Coefficients = RungeKuttaCoefficients::get(\n                RungeKuttaCoefficients::rungeKuttaFehlberg45 );\n    std::vector< Eigen::VectorXd > directStateDerivativeValues;\n\n    for ( int stage = 0; stage < rkf45Coefficients.cCoefficients.rows( ); stage++ )\n    {\n        // Compute the intermediate state to pass to the state derivative for this stage.\n        Eigen::VectorXd intermediateState( previousState );\n\n        // Compute the intermediate state.\n        for ( int column = 0; column < stage; column++ )\n        {\n            intermediateState += stepSize * rkf45Coefficients.aCoefficients( stage, column )\n                    * directStateDerivativeValues[ column ];\n        }\n\n        // Compute state derivative.\n        directStateDerivativeValues.push_back(\n                    computeVanDerPolStateDerivative(\n                        previousTime +\n                        rkf45Coefficients.cCoefficients( stage ) * stepSize,\n                        intermediateState ) );\n\n        // Check if manual result matched result from NumericalIntegrator.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( directStateDerivativeValues.at( stage ),\n                                           stateDerivatives.at( stage ),\n                                           1.0E-15 );\n    }\n}\n\n//! Test if integtrateTo function works for variable step size where last step is modified.\nBOOST_AUTO_TEST_CASE( testVariableStepIntegrateToFunction )\n{\n    using namespace numerical_integrators;\n    using namespace unit_tests::numerical_integrator_test_functions;\n\n    // In this test, the integrateTo function is used with variable step size integrator, where the\n    // step size is modified by the last step size, to ensure the correct operation of the\n    // integrator in this case.\n\n    // Create variable step size integrator.\n    RungeKuttaVariableStepSizeIntegratorXd integrator(\n                RungeKuttaCoefficients::get( RungeKuttaCoefficients::rungeKuttaFehlberg45 ),\n                &computeSecondNonAutonomousModelStateDerivative,\n                0.0,\n                ( Eigen::VectorXd( 1 ) << 1.0 ).finished( ),\n                0.0, 10.0, 1.0E-10, 1.0E-10 );\n\n    // Use integrateTo function\n    Eigen::VectorXd integratedValue = integrator.integrateTo( 0.5, 1.0 );\n    double currentTime = integrator.getCurrentIndependentVariable( );\n\n    // Check if current time is correct.\n    BOOST_CHECK_CLOSE_FRACTION( currentTime, 0.5, std::numeric_limits< double >::epsilon( ) );\n\n    // Create integrator to see if performing a single step with the given settings will indeed\n    // result in the step size being adapted.\n    RungeKuttaVariableStepSizeIntegratorXd verificationIntegrator(\n                RungeKuttaCoefficients::get( RungeKuttaCoefficients::rungeKuttaFehlberg45 ),\n                &computeSecondNonAutonomousModelStateDerivative,\n                0.0,\n                ( Eigen::VectorXd( 1 ) << 1.0 ).finished( ),\n                0.0, 10.0, 1.0E-10, 1.0E-10 );\n\n    // Check if single step size of 0.5 will be adapted.\n    verificationIntegrator.performIntegrationStep( 0.5 );\n    BOOST_CHECK_EQUAL( ( verificationIntegrator.getCurrentIndependentVariable( ) < 0.5 *\n                         ( 1.0 - 10.0 * std::numeric_limits< double >::epsilon( ) ) ), true );\n\n    // Use a fixed step size integrator to check the original result of integrateTo\n    RungeKutta4IntegratorXd fixedStepSizeIntegrator(\n                &computeSecondNonAutonomousModelStateDerivative,0.0,\n                ( Eigen::VectorXd( 1 ) << 1.0 ).finished( ) );\n    Eigen::VectorXd fixedStepIntegratedValue = integrator.integrateTo( 0.5, 0.01 );\n    BOOST_CHECK_CLOSE_FRACTION( fixedStepIntegratedValue.x( ), integratedValue.x( ), 1.0E-10 );\n}\n\nBOOST_AUTO_TEST_SUITE_END( )\n\n} // namespace unit_tests\n} // namespace tudat\n", "meta": {"hexsha": "ba5e2a84743e4bd39037c0581a016a04870690ca", "size": 16457, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Mathematics/NumericalIntegrators/UnitTests/unitTestRungeKuttaVariableStepSizeIntegrator.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/NumericalIntegrators/UnitTests/unitTestRungeKuttaVariableStepSizeIntegrator.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/NumericalIntegrators/UnitTests/unitTestRungeKuttaVariableStepSizeIntegrator.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": 47.02, "max_line_length": 99, "alphanum_fraction": 0.6612383788, "num_tokens": 3648, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.4542230828092369}}
{"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#include <boost/simd/arithmetic/include/functions/muls.hpp>\n#include <boost/simd/sdk/simd/native.hpp>\n#include <boost/simd/sdk/simd/io.hpp>\n#include <boost/dispatch/functor/meta/call.hpp>\n#include <boost/simd/include/constants/zero.hpp>\n#include <boost/simd/include/constants/one.hpp>\n#include <boost/simd/include/constants/mone.hpp>\n#include <boost/simd/include/constants/two.hpp>\n#include <boost/simd/include/constants/mtwo.hpp>\n#include <boost/simd/include/constants/inf.hpp>\n#include <boost/simd/include/constants/minf.hpp>\n#include <boost/simd/include/constants/nan.hpp>\n#include <boost/simd/include/constants/valmin.hpp>\n#include <boost/simd/include/constants/valmax.hpp>\n#include <boost/simd/include/functions/make.hpp>\n\n#include <nt2/sdk/unit/module.hpp>\n#include <nt2/sdk/unit/tests/relation.hpp>\n\nNT2_TEST_CASE_TPL ( muls_signed_int,  BOOST_SIMD_SIMD_INTEGRAL_SIGNED_TYPES)\n{\n  using boost::simd::muls;\n  using boost::simd::tag::muls_;\n  using boost::simd::native;\n  typedef BOOST_SIMD_DEFAULT_EXTENSION  ext_t;\n  typedef native<T,ext_t>                  vT;\n\n  // specific values tests\n  NT2_TEST_EQUAL(muls(boost::simd::Mone<vT>(), boost::simd::Mone<vT>()), boost::simd::One<vT>());\n  NT2_TEST_EQUAL(muls(boost::simd::One<vT>(), boost::simd::One<vT>()), boost::simd::One<vT>());\n  NT2_TEST_EQUAL(muls(boost::simd::Valmax<vT>(), boost::simd::Valmax<vT>()), boost::simd::Valmax<vT>());\n  NT2_TEST_EQUAL(muls(boost::simd::Valmax<vT>(),boost::simd::splat<vT>(2)), boost::simd::Valmax<vT>());\n  NT2_TEST_EQUAL(muls(boost::simd::Valmax<vT>(),boost::simd::Mone<vT>()), boost::simd::Valmin<vT>()+boost::simd::One<vT>());\n  NT2_TEST_EQUAL(muls(boost::simd::Valmax<vT>(),boost::simd::One<vT>()), boost::simd::Valmax<vT>());\n  NT2_TEST_EQUAL(muls(boost::simd::Valmin<vT>(),boost::simd::Mone<vT>()), boost::simd::Valmax<vT>());\n  NT2_TEST_EQUAL(muls(boost::simd::Valmin<vT>(),boost::simd::Valmin<vT>()), boost::simd::Valmax<vT>());\n  NT2_TEST_EQUAL(muls(boost::simd::Zero<vT>(), boost::simd::Zero<vT>()), boost::simd::Zero<vT>());\n} // end of test for signed_int_\n\nNT2_TEST_CASE_TPL ( muls_unsigned_int,  BOOST_SIMD_SIMD_UNSIGNED_TYPES)\n{\n  using boost::simd::muls;\n  using boost::simd::tag::muls_;\n  using boost::simd::native;\n  typedef BOOST_SIMD_DEFAULT_EXTENSION  ext_t;\n  typedef native<T,ext_t>                  vT;\n  typedef typename boost::dispatch::meta::call<muls_(vT,vT)>::type r_t;\n\n  // specific values tests\n  NT2_TEST_EQUAL(muls(boost::simd::One<vT>(), boost::simd::One<vT>()), boost::simd::One<r_t>());\n  NT2_TEST_EQUAL(muls(boost::simd::Valmax<vT>(),boost::simd::splat<vT>(2)), boost::simd::Valmax<r_t>());\n  NT2_TEST_EQUAL(muls(boost::simd::Zero<vT>(), boost::simd::Zero<vT>()), boost::simd::Zero<r_t>());\n} // end of test for unsigned_int_\n\nNT2_TEST_CASE(muls_special)\n{\n  using boost::simd::muls;\n  using boost::simd::splat;\n  using boost::simd::make;\n  using boost::simd::Valmin;\n  using boost::simd::Valmax;\n\n#ifndef BOOST_SIMD_HAS_MIC_SUPPORT\n  typedef boost::simd::native<short int, BOOST_SIMD_DEFAULT_EXTENSION> vT1;\n  NT2_TEST_EQUAL(muls(splat<vT1>(-5165), splat<vT1>(23258)), Valmin<vT1>());\n#endif\n\n  typedef boost::simd::native<int, BOOST_SIMD_DEFAULT_EXTENSION> vT2;\n  NT2_TEST_EQUAL(muls(splat<vT2>(-1306766858), splat<vT2>(1550772331)), Valmin<vT2>());\n  NT2_TEST_EQUAL(muls(splat<vT2>(1467238299), splat<vT2>(-900961598)), Valmin<vT2>());\n\n#ifdef BOOST_SIMD_HAS_AVX_SUPPORT\n  typedef int T2;\n  vT2 a = make<vT2>(853350212, 191584584, 1467238299, -1306766858, 991230901, 146415451, 154742226, 1320298211);\n  vT2 b = make<vT2>(1557885369, 1394765115, -900961598, 1550772331, 1563251902, -50470159, -76281765, 405234440);\n\n  vT2 c = make<vT2>(Valmax<T2>(), Valmax<T2>(), Valmin<T2>(), Valmin<T2>(), Valmax<T2>(), Valmin<T2>(), Valmin<T2>(), Valmax<T2>());\n  NT2_TEST_EQUAL(muls(a, b), c);\n#endif\n}\n", "meta": {"hexsha": "d35e4f0733c5da8a9943b5e221240099e489e434", "size": 4336, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/base/unit/arithmetic/simd/muls.cpp", "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/unit/arithmetic/simd/muls.cpp", "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/unit/arithmetic/simd/muls.cpp", "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": 48.7191011236, "max_line_length": 132, "alphanum_fraction": 0.6738929889, "num_tokens": 1308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191460821871, "lm_q2_score": 0.640635847978761, "lm_q1q2_score": 0.454223081883539}}
{"text": "//=======================================================================\n// Copyright 2007 Aaron Windsor\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n#include <iostream>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/properties.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <boost/ref.hpp>\n#include <vector>\n\n#include <boost/graph/planar_face_traversal.hpp>\n#include <boost/graph/boyer_myrvold_planar_test.hpp>\n\nusing namespace boost;\n\n// Some planar face traversal visitors that will\n// print the vertices and edges on the faces\n\nstruct output_visitor : public planar_face_traversal_visitor\n{\n    void begin_face() { std::cout << \"New face: \"; }\n    void end_face() { std::cout << std::endl; }\n};\n\nstruct vertex_output_visitor : public output_visitor\n{\n    template < typename Vertex > void next_vertex(Vertex v)\n    {\n        std::cout << v << \" \";\n    }\n};\n\nstruct edge_output_visitor : public output_visitor\n{\n    template < typename Edge > void next_edge(Edge e) { std::cout << e << \" \"; }\n};\n\nint main(int argc, char** argv)\n{\n\n    typedef adjacency_list< vecS, vecS, undirectedS,\n        property< vertex_index_t, int >, property< edge_index_t, int > >\n        graph;\n\n    // Create a graph - this is a biconnected, 3 x 3 grid.\n    // It should have four small (four vertex/four edge) faces and\n    // one large face that contains all but the interior vertex\n    graph g(9);\n\n    add_edge(0, 1, g);\n    add_edge(1, 2, g);\n\n    add_edge(3, 4, g);\n    add_edge(4, 5, g);\n\n    add_edge(6, 7, g);\n    add_edge(7, 8, g);\n\n    add_edge(0, 3, g);\n    add_edge(3, 6, g);\n\n    add_edge(1, 4, g);\n    add_edge(4, 7, g);\n\n    add_edge(2, 5, g);\n    add_edge(5, 8, g);\n\n    // Initialize the interior edge index\n    property_map< graph, edge_index_t >::type e_index = get(edge_index, g);\n    graph_traits< graph >::edges_size_type edge_count = 0;\n    graph_traits< graph >::edge_iterator ei, ei_end;\n    for (boost::tie(ei, ei_end) = edges(g); ei != ei_end; ++ei)\n        put(e_index, *ei, edge_count++);\n\n    // Test for planarity - we know it is planar, we just want to\n    // compute the planar embedding as a side-effect\n    typedef std::vector< graph_traits< graph >::edge_descriptor > vec_t;\n    std::vector< vec_t > embedding(num_vertices(g));\n    if (boyer_myrvold_planarity_test(boyer_myrvold_params::graph = g,\n            boyer_myrvold_params::embedding = &embedding[0]))\n        std::cout << \"Input graph is planar\" << std::endl;\n    else\n        std::cout << \"Input graph is not planar\" << std::endl;\n\n    std::cout << std::endl << \"Vertices on the faces: \" << std::endl;\n    vertex_output_visitor v_vis;\n    planar_face_traversal(g, &embedding[0], v_vis);\n\n    std::cout << std::endl << \"Edges on the faces: \" << std::endl;\n    edge_output_visitor e_vis;\n    planar_face_traversal(g, &embedding[0], e_vis);\n\n    return 0;\n}\n", "meta": {"hexsha": "f67e34c0d4010de46fe4ff25510ef2ec8aafaae9", "size": 3094, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/graph/example/planar_face_traversal.cpp", "max_stars_repo_name": "uosorio/heroku_face", "max_stars_repo_head_hexsha": "7d6465e71dba17a15d8edaef520adb2fcd09d91e", "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": "3rdparty/boost_1_73_0/libs/graph/example/planar_face_traversal.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 130.0, "max_issues_repo_issues_event_min_datetime": "2016-06-22T22:11:25.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-29T20:24:09.000Z", "max_forks_repo_path": "Libs/boost_1_76_0/libs/graph/example/planar_face_traversal.cpp", "max_forks_repo_name": "Antd23rus/S2DE", "max_forks_repo_head_hexsha": "47cc7151c2934cd8f0399a9856c1e54894571553", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2015-07-08T19:18:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-14T16:39:56.000Z", "avg_line_length": 30.94, "max_line_length": 80, "alphanum_fraction": 0.630575307, "num_tokens": 832, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191214879991, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.45422308072165246}}
{"text": "//!\n//! Contains the implementation of an adaptive proposal function\n//!\n//! \\file infer/adaptive.hpp\n//! \\author Darren Shen\n//! \\date 2014\n//! \\license Affero General Public License version 3 or later\n//! \\copyright (c) 2014, NICTA\n//!\n\n#pragma once\n\n#include <random>\n#include <functional>\n#include <Eigen/Core>\n\nnamespace stateline\n{\n  namespace mcmc\n  {\n    \n    //! A function to bounce the MCMC proposal off the hard boundaries.\n    //! This allows the proposal to always move around without getting stuck at\n    //! 'walls'\n    //! \n    //! \\param val The proposed value\n    //! \\param min The minimum bound of theta \n    //! \\param max The maximum bound of theta \n    //!  \\returns The new bounced theta definitely in the bounds\n    //!\n    Eigen::VectorXd bouncyBounds(const Eigen::VectorXd& val,const Eigen::VectorXd& min, const Eigen::VectorXd& max)\n    { \n      Eigen::VectorXd delta = max - min;\n      Eigen::VectorXd result = val;\n      Eigen::Matrix<bool, Eigen::Dynamic, 1> tooBig = (val.array() > max.array());\n      Eigen::Matrix<bool, Eigen::Dynamic, 1> tooSmall = (val.array() < min.array());\n      for (uint i=0; i< result.size(); i++)\n      {\n        bool big = tooBig(i);\n        bool small = tooSmall(i);\n        if (big)\n        {\n          double overstep = val(i)-max(i);\n          int nSteps = (int)(overstep /  delta(i));\n          double stillToGo = overstep - nSteps*delta(i);\n          if (nSteps % 2 == 0)\n            result(i) = max(i) - stillToGo;\n          else\n            result(i) = min(i) + stillToGo;\n        }\n        if (small)\n        {\n          double understep = min(i) - val(i);\n          int nSteps = (int)(understep / delta(i));\n          double stillToGo = understep - nSteps*delta(i);\n          if (nSteps % 2 == 0)\n            result(i) = min(i) + stillToGo;\n          else\n            result(i) = max(i) - stillToGo;\n        }\n      }\n      return result;\n    }\n    \n    //! An adaptive Gaussian proposal function. It randomly varies each value in\n    //! the state according to a Gaussian distribution whose variance changes\n    //! depending on the acceptance ratio of a chain. It also bounces of the\n    //! walls of the hard boundaries given so as not to get stuck in corners.\n    //! \n    //! \\param state The current state of the chain\n    //! \\param sigma The standard deviation of the distribution (step size of the proposal)\n    //! \\param min The minimum bound of theta \n    //! \\param max The maximum bound of theta \n    //! \\returns The new proposed theta\n    //!\n    Eigen::VectorXd adaptiveGaussianProposal(const Eigen::VectorXd &state, double sigma, \n        const Eigen::VectorXd& min, const Eigen::VectorXd& max)\n    {\n      // Random number generators\n      static std::random_device rd;\n      static std::mt19937 generator(rd());\n      static std::normal_distribution<> rand; // Standard normal\n\n      // Vary each paramater according to a Gaussian distribution\n      Eigen::VectorXd proposal(state.rows());\n      for (int i = 0; i < proposal.rows(); i++)\n        proposal(i) = state(i) + rand(generator) * sigma;\n\n      return bouncyBounds(proposal, min, max);\n    };\n    \n    \n  }\n}\n", "meta": {"hexsha": "5eadcc7ab024bc598d61fbfab73a8bf511c24249", "size": 3159, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/infer/adaptive.hpp", "max_stars_repo_name": "NICTA/obsidian", "max_stars_repo_head_hexsha": "911984dae2116415cc30621691d4020c34ea9e15", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2015-01-04T13:50:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-22T01:03:57.000Z", "max_issues_repo_path": "src/infer/adaptive.hpp", "max_issues_repo_name": "NICTA/obsidian", "max_issues_repo_head_hexsha": "911984dae2116415cc30621691d4020c34ea9e15", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/infer/adaptive.hpp", "max_forks_repo_name": "NICTA/obsidian", "max_forks_repo_head_hexsha": "911984dae2116415cc30621691d4020c34ea9e15", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2016-08-31T05:42:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-21T21:37:47.000Z", "avg_line_length": 33.2526315789, "max_line_length": 115, "alphanum_fraction": 0.6033554922, "num_tokens": 769, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191214879991, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.4542230709922978}}
{"text": "#include <iostream>\n#include <igl/readPLY.h>\n#include <igl/grad.h>\n#include <igl/opengl/glfw/Viewer.h>\n#include <igl/heat_geodesics.h>\n#include <igl/triangle_triangle_adjacency.h>\n#include <Eigen/Dense>\n#include <cstdlib>\n#include <random>\n#include <unordered_map>\n#include <chrono>\n\n\nstd::random_device rd;\nstd::mt19937 e2(rd());\nstd::uniform_real_distribution<> rand01(0, 1);\n\nusing Vec3 = Eigen::Vector3d;\nEigen::MatrixXd V;\nEigen::MatrixXi F;\nEigen::MatrixXi TT;\nEigen::SparseMatrix<double> G;\nigl::HeatGeodesicsData<double> heat_data;\nstd::unordered_map<int, std::set<int>> neighbours;\n\nvoid ComputeNeighbours() {\n  for(int f = 0; f< F.rows(); f++) {\n    const auto f0 = F(f, 0);\n    const auto f1 = F(f, 1);\n    const auto f2 = F(f, 2);\n\n    neighbours[f0].insert(f1);\n    neighbours[f0].insert(f2);\n    neighbours[f1].insert(f0);\n    neighbours[f1].insert(f2);\n    neighbours[f2].insert(f0);\n    neighbours[f2].insert(f1);\n  }\n}\n\nbool is_in_ring(int f_a, int f_b, int ring) {\n  std::vector<int> q;\n  std::set<int> visited;\n\n  q.push_back(f_b);\n  for(int i=0; i<ring; i++) {\n    if(q.size() == 0) {\n      break;\n    }\n\n    std::vector<int> new_q;\n    for(auto &f : q) {\n      if(visited.find(f) != visited.end()) {\n        continue;\n      }\n\n      visited.insert(f);\n      int n0 = TT(f, 0);\n      int n1 = TT(f, 1);\n      int n2 = TT(f, 2);\n      if(n0 == f_a || n1 == f_a || n2 == f_a) {\n        return true;\n      }\n      new_q.push_back(n0);\n      new_q.push_back(n1);\n      new_q.push_back(n2);\n    }\n    q = std::move(new_q);\n  }\n  return false;\n}\n\n\nvoid sample_point(Vec3& out, Vec3& bary, int& f) {\n  f = rand() % F.rows();\n  const auto v0 = F(f, 0);\n  const auto v1 = F(f, 1);\n  const auto v2 = F(f, 2);\n\n  const double b0 = rand01(e2);\n  const double b1 = rand01(e2) * (1.0 - b0);\n  const double b2 = 1.0 - b1 - b0;\n\n  out = b0*V.row(v0) + b1*V.row(v1) + b2*V.row(v2);\n  bary = {b0, b1, b2};\n}\n\n// doesn't consider TWO POINTS ON SAME TRIANGLE\nvoid sample_point_close_to(int f_orig, Vec3& out, Vec3& bary, int& f) {\n  const int hops = rand() % 5;\n  f = f_orig;\n  for(int i=0; i<hops || f==f_orig; i++) {\n    int new_f = -1;\n    while(new_f == -1) {\n      new_f = TT(f, rand()%3);\n    }\n    f = new_f;\n  }\n\n  const auto v0 = F(f, 0);\n  const auto v1 = F(f, 1);\n  const auto v2 = F(f, 2);\n\n  const double b0 = rand01(e2);\n  const double b1 = rand01(e2) * (1.0 - b0);\n  const double b2 = 1.0 - b1 - b0;\n\n  out = b0*V.row(v0) + b1*V.row(v1) + b2*V.row(v2);\n  bary = {b0, b1, b2};\n}\n\nconst Eigen::VectorXd& all_geodesics_from_point(int v1) {\n  static std::unordered_map<int, Eigen::VectorXd> cache_v;\n\n  const auto entry = cache_v.find(v1);\n  if(entry != cache_v.end()) {\n    return entry->second;\n  }\n\n  Eigen::VectorXi gamma;\n  Eigen::VectorXd D;\n  gamma.resize(1); gamma << v1;\n  igl::heat_geodesics_solve(heat_data, gamma, D);\n  cache_v[v1] = std::move(D);\n\n  return cache_v[v1];\n}\n\nconst Eigen::VectorXd all_euclidean_from_point(const Vec3& src) {\n  Eigen::VectorXd D;\n\n  D = (V.array().rowwise() - src.transpose().array()).matrix().rowwise().norm();\n\n  return D;\n}\n\ndouble geodesic_distance(int v1, int v2) {\n  static std::unordered_map<int, Eigen::VectorXd> cache_v;\n  if(v1 > v2) {\n    std::swap(v1, v2);\n  }\n\n  const auto entry = cache_v.find(v1);\n  if(entry != cache_v.end()) {\n    return entry->second(v2);\n  }\n\n  Eigen::VectorXi gamma;\n  Eigen::VectorXd D;\n  gamma.resize(1); gamma << v1;\n  igl::heat_geodesics_solve(heat_data, gamma, D);\n\n  const double d = D(v2);\n  cache_v[v1] = std::move(D);\n\n  return d;\n}\n\ndouble geodesic_distance_from_face(int f, int v) {\n  static std::unordered_map<int, Eigen::VectorXd> cache_f;\n  const auto entry = cache_f.find(f);\n  if(entry != cache_f.end()) {\n    return entry->second(v);\n  }\n\n  Eigen::VectorXi gamma;\n  Eigen::VectorXd D;\n  gamma.resize(1); gamma << F(f, 0), F(f, 1), F(f, 2);\n  igl::heat_geodesics_solve(heat_data, gamma, D);\n\n  const double d = D(v);\n  cache_f[f] = std::move(D);\n\n  return d;\n}\n\n// consider 9 possible paths based on triangles and chose the shortest\ndouble geodesic_distance_bo9(\n        const Vec3& pt_a, const Vec3& bary_a, int f_a,\n        const Vec3& pt_b, const Vec3& bary_b, int f_b,\n        Vec3* grad_out=nullptr\n        ) {\n  if(f_a == f_b) {\n    if(grad_out != nullptr) {\n      *grad_out = pt_a - pt_b;\n    }\n    return (pt_a - pt_b).norm();\n  }\n\n  int best_i, best_j;\n  double best_dist = 1e9;\n  for(int i=0; i<3; i++) {\n    // geodesic(==euclidean) distance between point a and face i\n    const double d_ai = (pt_a - V.row(F(f_a, i)).transpose()).norm();\n\n    for(int j=0; j<3; j++) {\n      // geodesic distance between the two vertices on the mesh\n      const double g_ij = geodesic_distance(F(f_a,i), F(f_b,j));\n\n      // geodesic(==euclidean) distance between point b and face j\n      const double d_bi = (pt_b - V.row(F(f_b, j)).transpose()).norm();\n\n      // total geodesic distance\n      const double g = d_ai + g_ij + d_bi;\n\n      // std::cout << \"(\" << i << \",\" << j <<\") \" << d_ai << \" + \" << g_ij << \" + \" << d_bi << \" == \" << g << \"\\n\";\n\n      if(g < best_dist) {\n        best_dist = g;\n        best_i = i;\n        best_j = j;\n      }\n    }\n  }\n\n  if(grad_out != nullptr) {\n    // const auto& D = all_geodesics_from_point(F(f_b, best_j));\n    const auto D = all_euclidean_from_point(pt_b);\n    const Eigen::MatrixXd GD_all = Eigen::Map<const Eigen::MatrixXd>((G*D).eval().data(), F.rows(), 3);\n    const Eigen::MatrixXd GD = GD_all.row(f_a);\n\n    (*grad_out)[0] = GD(0, 0);\n    (*grad_out)[1] = GD(0, 1);\n    (*grad_out)[2] = GD(0, 2);\n  }\n\n  return best_dist;\n}\n\ndouble geodesic_distance_barydatar(\n        const Vec3& pt_a, const Vec3& bary_a, int f_a,\n        const Vec3& pt_b, const Vec3& bary_b, int f_b,\n        Vec3 *grad_out\n) {\n  // ref: https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3346950/\n  if(f_a == f_b) {\n    if(grad_out != nullptr) {\n      *grad_out = pt_a - pt_b;\n    }\n    return (pt_a - pt_b).norm();\n  }\n\n  double res = 0.0;\n\n  for(int i=0; i<3; i++) {\n    const double g_i0 = geodesic_distance(F(f_a,i), F(f_b,0));\n    const double g_i1 = geodesic_distance(F(f_a,i), F(f_b,1));\n    const double g_i2 = geodesic_distance(F(f_a,i), F(f_b,2));\n    const double g_iy = bary_b[0]*g_i0 + bary_b[1]*g_i1 + bary_b[2]*g_i2;\n    res += bary_a[i] * g_iy;\n  }\n\n  if(grad_out != nullptr) {\n    if(is_in_ring(f_a, f_b, 1)) {\n      *grad_out = pt_a - pt_b;\n    } else {\n      *grad_out = Vec3(0.0, 0.0, 0.0);\n      const auto D = all_euclidean_from_point(pt_b);\n      const Eigen::MatrixXd GD_all = Eigen::Map<const Eigen::MatrixXd>((G*D).eval().data(), F.rows(), 3);\n\n      Eigen::MatrixXd GD_all_pervertex;\n      igl::per_vertex_normals(V, F, GD_all, GD_all_pervertex);\n\n      for(int i=0; i<3; i++) {\n        const Vec3 g = GD_all_pervertex.row(F(f_a, i));\n        *grad_out += bary_a[i] * g;\n      }\n    }\n  }\n\n  return res;\n}\n\ndouble geodesic_distance_testmeshfimgrad(\n        const Vec3& pt_a, const Vec3& bary_a, int f_a,\n        const Vec3& pt_b, const Vec3& bary_b, int f_b,\n        Vec3 *grad_out\n) {\n  if(grad_out != nullptr) {\n    *grad_out = {0.0, 0.0, 0.0};\n\n    const auto D = all_euclidean_from_point(pt_b);\n    const auto grad_v = [&](int v) {\n      Vec3 df = {0.0, 0.0, 0.0};\n      for(int o : neighbours[v]) {\n        const Vec3 pt_diff = V.row(o) - V.row(v);\n        const double value_diff = D[o] - D[v];\n\n        df[0] += value_diff / (pt_diff[0] + 0.0001);\n        df[1] += value_diff / (pt_diff[1] + 0.0001);\n        df[2] += value_diff / (pt_diff[2] + 0.0001);\n      }\n      df /= (double) neighbours[v].size();\n      return df;\n    };\n\n    for(int i=0; i<3; i++) {\n      *grad_out += bary_a[i] * grad_v(F(f_a, i));\n    }\n\n  }\n\n  return (pt_a - pt_b).norm();\n}\n\n// barycentric, but my own interpretation?\ndouble geodesic_distance_barykk(\n  const Vec3& pt_a, const Vec3& bary_a, int f_a,\n  const Vec3& pt_b, const Vec3& bary_b, int f_b\n  ) {\n  if(f_a == f_b) {\n    return (pt_a - pt_b).norm();\n  }\n\n  const Vec3 distances = {\n          geodesic_distance_from_face(f_b, F(f_a, 0)),\n          geodesic_distance_from_face(f_b, F(f_a, 1)),\n          geodesic_distance_from_face(f_b, F(f_a, 2)),\n  };\n  return distances.dot(bary_a);\n}\n\nint main() {\n  srand(time(nullptr));\n\n  const auto mesh_filepath = \"/scratch/karthik/projects/ShapeWorks/Examples/Python/Output/plane/ply/plane_highres.ply\";\n  igl::readPLY(mesh_filepath, V, F);\n\n  std::cerr << \"Mesh:\\n\";\n  std::cerr << \"V: \" << V.rows() << \"x\" << V.cols() << \"\\n\";\n  std::cerr << \"F: \" << F.rows() << \"x\" << F.cols() << \"\\n\";\n  std::cerr << \"Bounds: [\" << V.minCoeff() << \"] -> [\" << V.maxCoeff() << \"]\\n\\n\";\n\n  igl::grad(V, F, G);\n  igl::triangle_triangle_adjacency(F, TT);\n  ComputeNeighbours();\n\n  igl::heat_geodesics_precompute(V, F, heat_data);\n\n  Vec3 pt_a, bary_a; int f_a;\n  Vec3 pt_b, bary_b; int f_b;\n\n  // compare geodesic distance\n  for(int i=0; i<10000; i++) {\n    sample_point(pt_a, bary_a, f_a);\n\n    if(i < 5000) {\n      sample_point_close_to(f_a, pt_b, bary_b, f_b);\n    } else {\n      sample_point(pt_b, bary_b, f_b);\n    }\n\n    Vec3 geo_grad;\n    // const double geo = geodesic_distance_barykk(pt_a, bary_a, f_a, pt_b, bary_b, f_b);\n    // const double geo = geodesic_distance_testmeshfimgrad(pt_a, bary_a, f_a, pt_b, bary_b, f_b, &geo_grad);\n    // const double geo = geodesic_distance_bo9(pt_a, bary_a, f_a, pt_b, bary_b, f_b, &geo_grad);\n    const double geo = geodesic_distance_barydatar(pt_a, bary_a, f_a, pt_b, bary_b, f_b, &geo_grad);\n\n    /*\n    using namespace std::chrono;\n    const auto start = high_resolution_clock::now();\n    const auto end = high_resolution_clock::now();\n    const auto elapsed = duration_cast<nanoseconds>(end - start).count();\n    std::cout << \"time: \" << elapsed <<\"\\n\";\n    continue;\n    */\n\n    const double euc = (pt_a - pt_b).norm();\n    const Vec3 euc_grad = pt_a - pt_b;\n\n    const double geo_angle = std::atan2(geo_grad.y(), geo_grad.x());\n    const double euc_angle = std::atan2(euc_grad.y(), euc_grad.x());\n    const double geo_mag = geo_grad.norm();\n    const double euc_mag = euc_grad.norm();\n\n    std::cout << \"distance: \" << geo <<       \" | \" << euc <<       \" (diff: \" << geo - euc <<             \") \";\n    std::cout << \"| angle:  \" << geo_angle << \" | \" << euc_angle << \" (diff: \" << geo_angle - euc_angle << \") \";\n    std::cout << \"|   mag:  \" << geo_mag   << \" | \" << euc_mag   << \" (diff: \" << geo_mag   - euc_mag   << \") \";\n    std::cout << \"\\n\";\n  }\n\n  return 0;\n\n  Eigen::MatrixXd T1(2, 3);\n  T1.row(0) = pt_a;\n  T1.row(1) = pt_b;\n\n  Eigen::MatrixXd T2(1, 3); T2 << 1.0, 0.0, 0.0;\n  igl::opengl::glfw::Viewer viewer;\n  viewer.data().set_mesh(V, F);\n  viewer.data().set_points(T1, T2);\n  // viewer.data().show_lines = false;\n  // viewer.data().line_width = 2.0;\n  viewer.launch();\n\n  return 0;\n}\n", "meta": {"hexsha": "b91b66d21454498dfe169f5a2417dab2e428caa8", "size": 10763, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/geoapprox.cpp", "max_stars_repo_name": "medakk/geodesic-sandbox", "max_stars_repo_head_hexsha": "955af7d0cdecf472045b3227f2981c41070e9a10", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/geoapprox.cpp", "max_issues_repo_name": "medakk/geodesic-sandbox", "max_issues_repo_head_hexsha": "955af7d0cdecf472045b3227f2981c41070e9a10", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/geoapprox.cpp", "max_forks_repo_name": "medakk/geodesic-sandbox", "max_forks_repo_head_hexsha": "955af7d0cdecf472045b3227f2981c41070e9a10", "max_forks_repo_licenses": ["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.0427135678, "max_line_length": 119, "alphanum_fraction": 0.5894267398, "num_tokens": 3629, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.4542230691409022}}
{"text": "#pragma once\n#include <vizkit3d_debug_drawings/commands/DrawCommand.hpp>\n#include <string>\n#include <Eigen/Core>\n#include <vizkit3d_debug_drawings/commands/BoostSerializationHelpers.hpp>\n\nnamespace osg\n{\n    class Node;\n}\n\nnamespace vizkit3dDebugDrawings\n{\nclass DrawAABBCommand : public DrawCommand\n{\n    friend class boost::serialization::access;\n    template<class Archive>\n    void serialize(Archive & ar, const unsigned int version)\n    {\n        // serialize base class information\n        ar & boost::serialization::base_object<DrawCommand>(*this);\n        ar & min;\n        ar & max;\n        ar & colorRGBA;\n    }\n    \npublic:\n    DrawAABBCommand();\n    \n    DrawAABBCommand(const std::string& drawingChannel, const Eigen::Vector3d& min,\n                    const Eigen::Vector3d& max, const Eigen::Vector4d& colorRGBA);\n    \n    virtual osg::ref_ptr<osgviz::Object> createPrimitive() const;\n    \n    virtual DrawAABBCommand* clone() const;\n    \nprivate:\n    Eigen::Vector3d min;\n    Eigen::Vector3d max;\n    Eigen::Vector4d colorRGBA;\n};\n}\n", "meta": {"hexsha": "d883059f74805cdfb3ff3611e31d7200d4a5c680", "size": 1049, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/commands/primitives/DrawAABBCommand.hpp", "max_stars_repo_name": "pierrewillenbrockdfki/gui-vizkit3d_debug_drawings", "max_stars_repo_head_hexsha": "553b0bac93ef1f410e4b9842e8d9aa7391e5ddab", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/commands/primitives/DrawAABBCommand.hpp", "max_issues_repo_name": "pierrewillenbrockdfki/gui-vizkit3d_debug_drawings", "max_issues_repo_head_hexsha": "553b0bac93ef1f410e4b9842e8d9aa7391e5ddab", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/commands/primitives/DrawAABBCommand.hpp", "max_forks_repo_name": "pierrewillenbrockdfki/gui-vizkit3d_debug_drawings", "max_forks_repo_head_hexsha": "553b0bac93ef1f410e4b9842e8d9aa7391e5ddab", "max_forks_repo_licenses": ["BSD-3-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.3953488372, "max_line_length": 82, "alphanum_fraction": 0.6825548141, "num_tokens": 257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.4541917745301965}}
{"text": "//=======================================================================\n// Copyright 1997, 1998, 1999, 2000 University of Notre Dame.\n// Authors: Andrew Lumsdaine, Lie-Quan Lee, Jeremy G. Siek\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n#include <boost/config.hpp>\n#include <iostream>\n#include <list>\n#include <algorithm>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/topological_sort.hpp>\n#include <iterator>\n#include <utility>\n\n\ntypedef std::pair<std::size_t,std::size_t> Pair;\n\n/*\n  Topological sort example\n\n  The topological sort algorithm creates a linear ordering\n  of the vertices such that if edge (u,v) appears in the graph,\n  then u comes before v in the ordering.\n\n  Sample output:\n\n  A topological ordering: 2 5 0 1 4 3\n\n*/\n\nint\nmain(int , char* [])\n{\n  //begin\n  using namespace boost;\n\n  /* Topological sort will need to color the graph.  Here we use an\n     internal decorator, so we \"property\" the color to the graph.\n     */\n  typedef adjacency_list<vecS, vecS, directedS,\n    property<vertex_color_t, default_color_type> > Graph;\n\n  typedef boost::graph_traits<Graph>::vertex_descriptor Vertex;\n  Pair edges[6] = { Pair(0,1), Pair(2,4),\n                    Pair(2,5),\n                    Pair(0,3), Pair(1,4),\n                    Pair(4,3) };\n#if defined(BOOST_MSVC) && BOOST_MSVC <= 1300\n  // VC++ can't handle the iterator constructor\n  Graph G(6);\n  for (std::size_t j = 0; j < 6; ++j)\n    add_edge(edges[j].first, edges[j].second, G);\n#else\n  Graph G(edges, edges + 6, 6);\n#endif\n\n  boost::property_map<Graph, vertex_index_t>::type id = get(vertex_index, G);\n\n  typedef std::vector< Vertex > container;\n  container c;\n  topological_sort(G, std::back_inserter(c));\n\n  std::cout << \"A topological ordering: \";\n  for (container::reverse_iterator ii = c.rbegin();\n       ii != c.rend(); ++ii)\n    std::cout << id[*ii] << \" \";\n  std::cout << std::endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "6bea056d5817b0e95a82a2d5ef997f83286b6b60", "size": 2095, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/libs/graph/example/topo_sort.cpp", "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/libs/graph/example/topo_sort.cpp", "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/libs/graph/example/topo_sort.cpp", "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": 28.3108108108, "max_line_length": 77, "alphanum_fraction": 0.6171837709, "num_tokens": 557, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737473266736, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.45419177406555594}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n\nnamespace ipc::rigid {\n\n///\n/// Generate a canonical triangle/quad subdivided from a regular grid\n///\n/// @param[in]  n  \t\t\t { n grid quads }\n/// @param[in]  tri\t\t\t { is a tri or a quad }\n/// @param[out] V            { #V x 2 output vertices positions }\n/// @param[out] F            { #F x 3 output triangle indices }\n///\nvoid regular_2d_grid(\n    const int n, const bool tri, Eigen::MatrixXd& V, Eigen::MatrixXi& F);\n\nvoid regular_2d_grid(\n    const int num_cols,\n    const int num_rows,\n    Eigen::MatrixXd& V,\n    Eigen::MatrixXi& F);\n\n} // namespace ipc::rigid\n", "meta": {"hexsha": "2c204bca7274dc3ca1c985977c5d46a7091e7f83", "size": 603, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/utils/regular_2d_grid.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/utils/regular_2d_grid.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/utils/regular_2d_grid.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": 24.12, "max_line_length": 73, "alphanum_fraction": 0.6185737977, "num_tokens": 167, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.45419177000120403}}
{"text": "// Copyright (c) 2005 - 2015 Marc de Kamps\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n//\n//    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n//    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation\n//      and/or other materials provided with the distribution.\n//    * 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\n//      without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY\n// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 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, STRICT LIABILITY, OR TORT (INCLUDING\n// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n#define BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n#include <TwoDLib.hpp>\n#include <vector>\n#include <iostream>\n\nusing namespace std;\nusing namespace TwoDLib;\n\nBOOST_AUTO_TEST_CASE(CellCreationTest)\n{\n\tvector<double> vec_v(4);\n\tvector<double> vec_w(4);\n\n\tvec_v[0] = 0.;\n\tvec_v[1] = 1.;\n\tvec_v[2] = 1.;\n\tvec_v[3] = 0.;\n\n\tvec_w[0] = 0.;\n\tvec_w[1] = 0.;\n\tvec_w[2] = 1.;\n\tvec_w[3] = 1.;\n\n\tQuadrilateral quad(vec_v, vec_w);\n\tBOOST_REQUIRE( quad.SignedArea()  ==  1);\n\tBOOST_REQUIRE( quad.IsClockwise() == -1);\n\n\tvec_v[0] = 0.;\n\tvec_v[1] = 0.;\n\tvec_v[2] = 1.;\n\tvec_v[3] = 1.;\n\n\tvec_w[0] = 0.;\n\tvec_w[1] = 1.;\n\tvec_w[2] = 1.;\n\tvec_w[3] = 0.;\n\n\tQuadrilateral quad2(vec_v, vec_w);\n\n\tBOOST_REQUIRE( quad2.SignedArea() == -1);\n\tBOOST_REQUIRE( quad2.IsClockwise() ==  1);\n\n}\n\nBOOST_AUTO_TEST_CASE(InsideClockWise){\n\tvector<double>  vec_v(4);\n\tvector<double>  vec_w(4);\n\n\tvec_v[0] = 0.;\n\tvec_v[1] = 0.;\n\tvec_v[2] = 1.;\n\tvec_v[3] = 1.;\n\n\tvec_w[0] = 0.;\n\tvec_w[1] = 1.;\n\tvec_w[2] = 1.;\n\tvec_w[3] = 0.;\n\n\tQuadrilateral quad(vec_v, vec_w);\n\n\tPoint p(0.5,0.5);\n\n\n\tBOOST_REQUIRE( quad.IsInside(p) == true );\n\n\tPoint p1(-0.5,0.5);\n\tBOOST_REQUIRE(quad.IsInside(p1) == false);\n\tPoint p2(0.5,1.5);\n\tBOOST_REQUIRE(quad.IsInside(p2) == false);\n\tPoint p3(1.5,0.5);\n\tBOOST_REQUIRE(quad.IsInside(p3) == false);\n\tPoint p4(0.5,-0.5);\n\tBOOST_REQUIRE(quad.IsInside(p4) == false);\n\n}\n\nBOOST_AUTO_TEST_CASE(InsideAntiClockWise){\n\tvector<double>  vec_v(4);\n\tvector<double>  vec_w(4);\n\n\tvec_v[0] = 0.;\n\tvec_v[1] = 1.;\n\tvec_v[2] = 1.;\n\tvec_v[3] = 0.;\n\n\tvec_w[0] = 0.;\n\tvec_w[1] = 0.;\n\tvec_w[2] = 1.;\n\tvec_w[3] = 1.;\n\n\tQuadrilateral quad(vec_v, vec_w);\n\n\tPoint p(0.5,0.5);\n\n\n\tBOOST_REQUIRE( quad.IsInside(p) == true );\n\n\tPoint p1(-0.5,0.5);\n\tBOOST_REQUIRE(quad.IsInside(p1) == false);\n\tPoint p2(0.5,1.5);\n\tBOOST_REQUIRE(quad.IsInside(p2) == false);\n\tPoint p3(1.5,0.5);\n\tBOOST_REQUIRE(quad.IsInside(p3) == false);\n\tPoint p4(0.5,-0.5);\n\tBOOST_REQUIRE(quad.IsInside(p4) == false);\n}\n\n\nBOOST_AUTO_TEST_CASE(InsideConcave){\n\tvector<double>  vec_v(4);\n\tvector<double>  vec_w(4);\n\n\tvec_v[0] = -1.;\n\tvec_v[1] =  0.;\n\tvec_v[2] =  1.;\n\tvec_v[3] =  0.;\n\n\tvec_w[0] = -0.5;\n\tvec_w[1] =  0.;\n\tvec_w[2] = -0.5;\n\tvec_w[3] =  1.;\n\n\tQuadrilateral quad(vec_v, vec_w);\n\n\tPoint p(0.0,0.5);\n\tBOOST_REQUIRE( quad.IsInside(p) == true );\n\n\tPoint p1(-1.,0.);\n\tBOOST_REQUIRE(quad.IsInside(p1) == false);\n\tPoint p2( 1.,0.);\n\tBOOST_REQUIRE(quad.IsInside(p2) == false);\n\tPoint p3(0.,-0.1);\n\tBOOST_REQUIRE(quad.IsInside(p3) == false);\n\tPoint p4(0., 1.1);\n\tBOOST_REQUIRE(quad.IsInside(p4) == false);\n\n}\n\nBOOST_AUTO_TEST_CASE(Split){\n\tvector<double> v(Quadrilateral::_nr_points);\n\tv[0] = 0;\n\tv[1] = 1;\n\tv[2] = 0;\n\tv[3] = -1;\n\n\tvector<double> w(Quadrilateral::_nr_points);\n\tw[0] = 0;\n\tw[1] = -0.5;\n\tw[2] =  1.0;\n\tw[3] = -0.5;\n\n\tQuadrilateral quad(v,w);\n\n\tpair<Triangle,Triangle> ts = quad.Split();\n\n\tTriangle t1 = ts.first;\n\n\tPoint p1 = t1.Points()[0];\n\tPoint p2 = t1.Points()[1];\n\tPoint p3 = t1.Points()[2];\n\n\n\n\tBOOST_REQUIRE( p1[0] == 0 && p1[1] == 0);\n\tBOOST_REQUIRE( p2[0] == 0 && p2[1] == 1);\n\tBOOST_REQUIRE( p3[0] == 1 && p3[1] == -0.5);\n\n\n\tTriangle t2 = ts.second;\n\n\tp1 = t2.Points()[0];\n\tp2 = t2.Points()[1];\n\tp3 = t2.Points()[2];\n\n\n\tBOOST_REQUIRE( p1[0] == 0 && p1[1] == 0);\n\tBOOST_REQUIRE( p2[0] == 0 && p2[1] == 1);\n\tBOOST_REQUIRE( p3[0] == -1 && p3[1] == -0.5);\n\n// Now rotate the points. Same triangles should be produced\n\n\tv[1] = 0;\n\tv[2] = 1;\n\tv[3] = 0;\n\tv[0] = -1;\n\n\tw[1] = 0;\n\tw[2] = -0.5;\n\tw[3] =  1.0;\n\tw[0] = -0.5;\n\n\tQuadrilateral quad2(v,w);\n\tpair<Triangle,Triangle> ts2 = quad2.Split();\n\n\tTriangle t3 = ts2.first;\n\n\tp1 = t3.Points()[0];\n\tp2 = t3.Points()[1];\n\tp3 = t3.Points()[2];\n\n\n\tBOOST_REQUIRE( p1[0] == 0 && p1[1] == 0);\n\tBOOST_REQUIRE( p2[0] == 0 && p2[1] == 1);\n\tBOOST_REQUIRE( p3[0] == -1 && p3[1] == -0.5);\n\n\tTriangle t4 = ts2.second;\n\n\tp1 = t4.Points()[0];\n\tp2 = t4.Points()[1];\n\tp3 = t4.Points()[2];\n\n\tBOOST_REQUIRE( p1[0] == 0 && p1[1] == 0);\n\tBOOST_REQUIRE( p2[0] == 0 && p2[1] == 1);\n\tBOOST_REQUIRE( p3[0] == 1 && p3[1] == -0.5);\n\n}\n\nBOOST_AUTO_TEST_CASE(CentroidTest){\n\tvector<double>  vec_v(4);\n\tvector<double>  vec_w(4);\n\n\tvec_v[0] = 0.;\n\tvec_v[1] = 0.;\n\tvec_v[2] = 1.;\n\tvec_v[3] = 1.;\n\n\tvec_w[0] = 0.;\n\tvec_w[1] = 1.;\n\tvec_w[2] = 1.;\n\tvec_w[3] = 0.;\n\n\tQuadrilateral quad(vec_v, vec_w);\n\n\tPoint centre = quad.Centroid();\n\tBOOST_REQUIRE(centre[0] == 0.5);\n\tBOOST_REQUIRE(centre[1] == 0.5);\n}\n\n", "meta": {"hexsha": "72d6d59f57fc82c1c97033b4effcab941673b0f6", "size": 5923, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "apps/UnitTwoDLib/QuadrilateralTest.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/UnitTwoDLib/QuadrilateralTest.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/UnitTwoDLib/QuadrilateralTest.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": 23.046692607, "max_line_length": 162, "alphanum_fraction": 0.6403849401, "num_tokens": 2068, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.45419177000120403}}
{"text": "// Copyright 2015 Clemson University\n// Authors: Bradley S. Meyer\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n#include <iostream>\n#include <fstream>\n#include <boost/graph/adjacency_list.hpp>\n\n#include \"../include/rank_spanning_branchings.hpp\"\n\nstruct print_branching\n{\n\n  print_branching(){}\n\n  template <typename BranchingGraph>\n  bool operator()( BranchingGraph& bg )\n  {\n\n    typedef\n      typename\n        boost::property_map<BranchingGraph, boost::edge_weight_t>::const_type\n        WeightMap;\n\n    WeightMap w;\n    typename boost::property_traits<WeightMap>::value_type weight;\n\n    std::cout << \"Branching:\";\n\n    weight = 0;\n\n    BGL_FORALL_EDGES_T( e, bg, BranchingGraph )\n    {\n\n      std::cout << \" (\" << boost::source( e, bg ) << \",\" <<\n        boost::target( e, bg ) << \")\";\n\n      weight += get( w, e );\n\n    }\n\n    std::cout << std::endl << \"  Weight: \" << weight << std::endl << std::endl;\n\n    return true;\n\n  }\n\n};\n   \nint\nmain()\n{\n  typedef boost::adjacency_list < boost::vecS, boost::vecS, boost::directedS,\n    boost::no_property, boost::property < boost::edge_weight_t, int > > Graph;\n#if defined(BOOST_MSVC) && BOOST_MSVC <= 1300\n  typedef boost::graph_traits < Graph >::edge_descriptor Edge;\n#endif\n  typedef std::pair<int, int> E;\n\n  const int num_nodes = 4;\n  E edge_array[] = { E(0, 1), E(0, 2), E(0, 3), E(1, 2), E(2, 1), E(2, 3),\n    E(3, 2), E(1, 3), E(3, 1)\n  };\n  int weights[] = { 5, 1, 1, 11, 10, 5, 8, 4, 9 };\n\n  std::size_t num_edges = sizeof(edge_array) / sizeof(E);\n#if defined(BOOST_MSVC) && BOOST_MSVC <= 1300\n  Graph g(num_nodes);\n  boost::property_map<Graph, boost::edge_weight_t>::type weightmap =\n    get(edge_weight, g);\n  for (std::size_t j = 0; j < num_edges; ++j) {\n    Edge e; bool inserted;\n    boost::tie(e, inserted) = add_edge(edge_array[j].first, edge_array[j].second, g);\n    weightmap[e] = weights[j];\n  }\n#else\n  Graph g(edge_array, edge_array + num_edges, weights, num_nodes);\n#endif\n\n  // Rank branchings in descending order of weight (use default\n  // weight comparison).\n\n  std::cout << std::endl;\n\n  std::cout << \"Spanning branchings in descending order of weight:\"\n            << std::endl << std::endl;\n\n  rsb::rank_spanning_branchings(\n    g,\n    print_branching()\n  );\n\n  std::cout << std::endl;\n\n  // Rank branchings in ascending order of weight (use supplied\n  // weight comparison).\n\n  std::cout << \"Spanning branchings in ascending order of weight:\"\n            << std::endl << std::endl;\n\n  rsb::rank_spanning_branchings(\n    g,\n    print_branching(),\n    boost::distance_compare( std::greater<int>() )\n  );\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "7b390c63ff60c1163c2d0e61714bd522ffb7dc59", "size": 2794, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/rank-branchings1.cpp", "max_stars_repo_name": "mbradle/rank_spanning_branchings", "max_stars_repo_head_hexsha": "86aa045beebe0e5f273f0ee1bce5e91ca4f4f079", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/rank-branchings1.cpp", "max_issues_repo_name": "mbradle/rank_spanning_branchings", "max_issues_repo_head_hexsha": "86aa045beebe0e5f273f0ee1bce5e91ca4f4f079", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/rank-branchings1.cpp", "max_forks_repo_name": "mbradle/rank_spanning_branchings", "max_forks_repo_head_hexsha": "86aa045beebe0e5f273f0ee1bce5e91ca4f4f079", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.9464285714, "max_line_length": 85, "alphanum_fraction": 0.6188260558, "num_tokens": 801, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.4541917654722115}}
{"text": "/*\n * Copyright (c) Nuno Alves de Sousa 2019\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 FIXTURE_DGEMM_H\n#define FIXTURE_DGEMM_H\n\n#include <cstdint>\n#include <algorithm>\n#include <cmath>\n#include <cstddef>\n#include <new>\n\n#include <celero/Celero.h>\n\n#include <Eigen/Eigen>\n\n#include <mkl.h>\n\n#include <random_vector.hpp>\n#include <debug.hpp>\n\nusing EigenMatrix = Eigen::MatrixXd;\nusing MKLMatrix = double*;\n\nenum class ProgressionPolicy {linear, geometric, semilogGemm, semilogAdd};\n\n/**\n * Creates a set of linearly increasing matrix dimensions\n * @param numberOfTests Total number of tests\n * @param increment Increment value for the next set of matrix dimensions\n * @return A problemSpace (i.e. the set of matrix dimensions)\n */\ninline std::vector<celero::TestFixture::ExperimentValue>\nlinearProgression(int numberOfTests, int increment)\n{\n    std::vector<celero::TestFixture::ExperimentValue> problemSpace;\n\n    // Generate a set of matrix dimensions\n    for (int i = 0; i < numberOfTests; ++i) {\n        // matrix dimensions as a function of the test number\n        problemSpace.push_back(static_cast<std::int64_t>(increment*(i+1)));\n    }\n    return problemSpace;\n}\n\n/**\n * Creates a set of matrix dimensions that follow a geometric progression\n * @param numberOfTests Total number of tests\n * @param increment Common ration for the geometric progression\n * @return A problemSpace (i.e. the set of matrix dimensions)\n */\ninline std::vector<celero::TestFixture::ExperimentValue>\ngeometricProgression(int numberOfTests, int increment)\n{\n    // Start Value = 1 and Iterations = 0 (default)\n    std::vector<celero::TestFixture::ExperimentValue> problemSpace{1, 0};\n\n    // Generate a set of matrix dimensions\n    for (int i = 0; i < numberOfTests; ++i) {\n        // matrix dimensions as a function of the test number\n        problemSpace.push_back(static_cast<std::int64_t>(problemSpace.back().Value * increment));\n    }\n    return problemSpace;\n}\n\n/**\n * Creates a set of matrix dimensions to create a semilog plot when\n * benchmarking gdemm functions (faster decay of benchmark iterations)\n * @param numberOfTests Total number of tests\n * @return A problemSpace (i.e. the set of matrix dimensions)\n */\ninline std::vector<celero::TestFixture::ExperimentValue>\nsemilogGemmProgression(int numberOfTests)\n{\n    std::vector<celero::TestFixture::ExperimentValue> problemSpace;\n\n    std::int64_t matrixDim = 1;\n    for (int i = 1; i <= numberOfTests; ++i) {\n        auto orderMag = static_cast<std::int64_t>\n            (std::floor(std::log10(matrixDim)));\n        matrixDim += static_cast<std::int64_t>(std::pow(10, orderMag));\n\n        // Adjust iterations of the problemSpace according to matrix dimensions\n        static std::int64_t iterations;\n        switch (matrixDim) {\n            case      2: iterations = 100; break;\n            case    100: iterations = 25;  break;\n            case   1000: iterations = 5;   break;\n            case 10'000: iterations = 3;   break;\n        }\n        problemSpace.push_back({matrixDim, iterations});\n    }\n    return problemSpace;\n}\n\n/**\n * Creates a set of matrix dimensions to create a semilog plot when\n * benchmarking matrix addition (slower decay of benchmark iterations)\n * @param numberOfTests Total number of tests\n * @return A problemSpace (i.e. the set of matrix dimensions)\n */\ninline std::vector<celero::TestFixture::ExperimentValue>\nsemilogAddProgression(int numberOfTests)\n{\n    std::vector<celero::TestFixture::ExperimentValue> problemSpace;\n\n    std::int64_t matrixDim = 1;\n    for (int i = 1; i <= numberOfTests; ++i) {\n        auto orderMag = static_cast<std::int64_t>\n        (std::floor(std::log10(matrixDim)));\n        matrixDim += static_cast<std::int64_t>(std::pow(10, orderMag));\n\n        // Adjust iterations of the problemSpace according to matrix dimensions\n        static std::int64_t iterations;\n        switch (matrixDim) {\n            case      2: iterations = 100; break;\n            case   1000: iterations = 75;   break;\n        }\n        problemSpace.push_back({matrixDim, iterations});\n    }\n    return problemSpace;\n}\n\n/// Base class for all fixtures ralated to matrix operations\n/// \\tparam policy The ProgressionPolicy for the benchmark fixture\ntemplate<ProgressionPolicy policy>\nclass MatrixFixture: public celero::TestFixture\n{\npublic:\n    MatrixFixture() = default;\n\n    /// The problem space is a set of matrix dimensions\n    std::vector<celero::TestFixture::ExperimentValue> getExperimentValues() const override\n    {\n        switch (policy) {\n            case ProgressionPolicy::linear:\n                return linearProgression(numLinearProgressionTests\n                                        ,increment);\n            case ProgressionPolicy::geometric:\n                return geometricProgression(numGeometricProgressionTests\n                                           ,increment);\n            case ProgressionPolicy::semilogGemm:\n                return semilogGemmProgression(numSemilogGemmProgressionTests);\n            case ProgressionPolicy::semilogAdd:\n                return semilogAddProgression(numSemilogAddProgressionTests);\n        }\n    }\n\nprotected:\n    // Helper setter\n    void updateMatrixDim(std::int64_t newDim)\n    {\n        matrixDim = newDim;\n        matrixSize = matrixDim * matrixDim;\n    }\n\n    // Helper generator according to current matrix dimensions\n    std::vector<double> makeRandomMatrixData()\n    {\n        return makeRandomVector(matrixSize, dataMin, dataMax);\n    }\n\n    std::int64_t matrixDim;\n    std::int64_t matrixSize;\n\nprivate:\n    static constexpr int increment = 25;\n\n    static constexpr int numLinearProgressionTests = 100;\n    static constexpr int numGeometricProgressionTests = 100;\n    static constexpr int numSemilogGemmProgressionTests = 35;\n\n    // Fewer tests because of additional memory requirements (matrix copies)\n    static constexpr int numSemilogAddProgressionTests = 35;\n\n    static constexpr double dataMin = 0.0;\n    static constexpr double dataMax = 1.0;\n};\n\n/// This MKL fixture allocates aligned buffers\ntemplate<ProgressionPolicy policy = ProgressionPolicy::linear>\nclass MKLFixture: public MatrixFixture<policy>\n{\npublic:\n    MKLFixture() = default;\n\n    /// Before each run build matrices of random integers\n    void setUp(const celero::TestFixture::ExperimentValue& experimentValue) override\n    {\n        // Update matrix dimensions based on the current experiment\n        this->updateMatrixDim(experimentValue.Value);\n\n        // Initialize MKL matrices\n        mA = allocate_dmatrix(this->matrixSize);\n        mC = allocate_dmatrix(this->matrixSize);\n\n        auto matrixData = this->makeRandomMatrixData();\n\n        std::copy(matrixData.begin(), matrixData.end(), mA);\n        std::fill(mC, mC + this->matrixSize, 0);\n\n        MKL_DEBUG(mA, this->matrixDim, this->matrixDim);\n        MKL_DEBUG(mC, this->matrixDim, this->matrixDim);\n    }\n\n    // Clear MKL matrices on tearDown and do not include deallocation time\n    void tearDown() override\n    {\n        mkl_free(mA);\n        mkl_free(mC);\n    }\n\nprotected:\n    // Helper allocation function\n    virtual double* allocate_dmatrix(std::int64_t matrixSize)\n    {\n        auto ptr =\n            static_cast<double*>\n                (mkl_malloc(matrixSize*sizeof(double), this->align));\n        if (!ptr) {\n            std::cerr << \"error: cannot allocate matrices\\n\";\n            throw std::bad_alloc{};\n        }\n        return ptr;\n    }\n\n    MKLMatrix mA = nullptr;\n    MKLMatrix mC = nullptr;\n\n    static constexpr int align = 64; // default alignment on 64-byte bounndary\n};\n\n/// This MKL fixture with copies for mkl_domatadd\ntemplate<ProgressionPolicy policy = ProgressionPolicy::linear>\nclass MKLFixtureB: public MKLFixture<policy>\n{\npublic:\n    MKLFixtureB() = default;\n\n    /// Before each run build matrices of random integers\n    void setUp(const celero::TestFixture::ExperimentValue& experimentValue) override\n    {\n        // Update matrix dimensions and allocate mA\n        MKLFixture<policy>::setUp(experimentValue);\n\n        // Allocate additional space for mAcopy and mC\n        mB = allocate_dmatrix(this->matrixSize);\n        std::copy(this->mA, this->mA + this->matrixSize, mB);\n        MKL_DEBUG(mB, this->matrixDim, this->matrixDim);\n    }\n\n    // Clear MKL matrices on tearDown and do not include deallocation time\n    void tearDown() override\n    {\n        MKLFixture<policy>::tearDown();\n        mkl_free(mB);\n    }\n\nprotected:\n    // Helper allocation function\n    virtual double* allocate_dmatrix(std::int64_t matrixSize)\n    {\n        auto ptr =\n             static_cast<double*>(mkl_malloc(matrixSize*sizeof(double), this->align));\n        if (!ptr) {\n            throw std::bad_alloc{};\n        }\n        return ptr;\n    }\n\n    MKLMatrix mB = nullptr;\n};\n\ntemplate<ProgressionPolicy policy = ProgressionPolicy::linear>\nclass EigenFixture: public MatrixFixture<policy>\n{\npublic:\n    EigenFixture() = default;\n\n    /// Before each run build matrices of random data and setup threading\n    void setUp(const celero::TestFixture::ExperimentValue& experimentValue) override\n    {\n        if constexpr (numberOfThreads != 0) {\n            // Eigen threading\n            Eigen::setNbThreads(numberOfThreads);\n        }\n\n        // Update matrix dimensions based on the current experiment\n        this->updateMatrixDim(experimentValue.Value);\n\n        // Initialize Eigen matrix\n        auto matrixData = this->makeRandomMatrixData();\n        eA = Eigen::Map<EigenMatrix>(matrixData.data()\n                                    ,this->matrixDim\n                                    ,this->matrixDim);\n        EIGEN_DEBUG(eA);\n    }\n\nprotected:\n    EigenMatrix eA;\n\n    static constexpr int numberOfThreads = 4;\n};\n\n#endif //FIXTURE_DGEMM_H\n", "meta": {"hexsha": "2654c529c951e8bb8f3cb62076c9b52f9d9440ad", "size": 9927, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/fixture.hpp", "max_stars_repo_name": "seriouslyhypersonic/benchmark_eigen_mkl", "max_stars_repo_head_hexsha": "c2dde3a3ce9c51dd428746400de8e8d2802dc6c0", "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/fixture.hpp", "max_issues_repo_name": "seriouslyhypersonic/benchmark_eigen_mkl", "max_issues_repo_head_hexsha": "c2dde3a3ce9c51dd428746400de8e8d2802dc6c0", "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/fixture.hpp", "max_forks_repo_name": "seriouslyhypersonic/benchmark_eigen_mkl", "max_forks_repo_head_hexsha": "c2dde3a3ce9c51dd428746400de8e8d2802dc6c0", "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.0225806452, "max_line_length": 97, "alphanum_fraction": 0.6711997582, "num_tokens": 2304, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6654105454764747, "lm_q2_score": 0.6825737214979746, "lm_q1q2_score": 0.4541917523498746}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2015 NumScale SAS\n  @copyright 2015 J.T. Lapreste\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_COMMON_GENERIC_FUNCTION_IS_DENORMAL_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_GENERIC_FUNCTION_IS_DENORMAL_HPP_INCLUDED\n\n#include <boost/simd/meta/as_logical.hpp>\n#include <boost/simd/constant/smallestposval.hpp>\n#include <boost/simd/function/abs.hpp>\n#include <boost/simd/function/is_less.hpp>\n#include <boost/simd/function/is_nez.hpp>\n#include <boost/simd/function/logical_and.hpp>\n#include <boost/simd/constant/false.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/logical.hpp>\n#include <boost/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 ( is_denormal_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::generic_< bd::arithmetic_<A0> >\n                          )\n  {\n    using result = bs::as_logical_t<A0>;\n    BOOST_FORCEINLINE  result  operator() ( A0 ) const BOOST_NOEXCEPT\n    {\n      return False<result>();\n    }\n  };\n  BOOST_DISPATCH_OVERLOAD ( is_denormal_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::generic_< bd::floating_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE  bs::as_logical_t<A0> operator() ( A0 const& a0) const BOOST_NOEXCEPT\n    {\n      return bitwise_and(is_nez(a0), is_less(bs::abs(a0), Smallestposval<A0>()));\n    }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "93b3245c3bf6a776c6473723d7ae560c4f9583e9", "size": 1935, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arch/common/generic/function/is_denormal.hpp", "max_stars_repo_name": "yaeldarmon/boost.simd", "max_stars_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/simd/arch/common/generic/function/is_denormal.hpp", "max_issues_repo_name": "yaeldarmon/boost.simd", "max_issues_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/arch/common/generic/function/is_denormal.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.3620689655, "max_line_length": 100, "alphanum_fraction": 0.5772609819, "num_tokens": 427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125848754471, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4541643393688266}}
{"text": "#include <ros/ros.h>\n\n#include <rosbag/bag.h>\n#include <rosbag/view.h>\n#include <boost/foreach.hpp>\n#define foreach BOOST_FOREACH\n\n#include <gps_convert_utils.h>\n#include <nav_msgs/Odometry.h>\n#include <nav_msgs/Path.h>\n#include <sensor_msgs/NavSatFix.h>\n\n#include <Eigen/Eigen>\n\nEigen::Vector3d first_pose;\nbool first_pose_flag = false;\n\nros::Publisher pub_odom;\n\nvoid GPSHandler(const sensor_msgs::NavSatFix::ConstPtr& rtk_msg) {\n  double latitude = rtk_msg->latitude;\n  double longitude = rtk_msg->longitude;\n  double altitude = rtk_msg->altitude;\n\n  // \u8f6c\u5316\u4e3autm\u5750\u6807\u7cfb\n  UTMCoor utmcoor;\n  LatLonToUTMXY(latitude / 180.0 * M_PI, longitude / 180.0 * M_PI, 51, utmcoor);\n  Eigen::Vector3d gps_utm(utmcoor.x, utmcoor.y, altitude);\n  if (!first_pose_flag) {\n    first_pose = gps_utm;\n    first_pose_flag = true;\n  }\n\n  gps_utm -= first_pose;\n\n  nav_msgs::Odometry odom_msg;\n  odom_msg.header.frame_id = \"/map\";\n  odom_msg.header.stamp = ros::Time::now();\n  odom_msg.pose.pose.position.x = gps_utm(0);\n  odom_msg.pose.pose.position.y = gps_utm(1);\n  odom_msg.pose.pose.position.z = gps_utm(2);\n  odom_msg.pose.covariance[0] = rtk_msg->position_covariance[0];\n  odom_msg.pose.covariance[7] = rtk_msg->position_covariance[4];\n  odom_msg.pose.covariance[14] = rtk_msg->position_covariance[8];\n\n  pub_odom.publish(odom_msg);\n}\n\nint main(int argc, char** argv) {\n  ros::init(argc, argv, \"gps_visualization\");\n  ros::NodeHandle n;\n\n  ros::Publisher pub_gps_path = n.advertise<nav_msgs::Path>(\"/gps_path\", 10);\n  pub_odom = n.advertise<nav_msgs::Odometry>(\"/gps_odom\", 10);\n\n  std::string bag_path = \"/home/hkw/rosbag/rs_ruby_mti_680_new.bag\";\n  std::string gps_topic = \"/gnss\";\n\n  rosbag::Bag bag;\n  bag.open(bag_path, rosbag::bagmode::Read);\n\n  std::vector<std::string> topics;\n  topics.push_back(gps_topic);\n\n  rosbag::View view_;\n  rosbag::View view_full;\n  view_full.addQuery(bag);\n  ros::Time time_init = view_full.getBeginTime();\n  ros::Time time_finish = view_full.getEndTime();\n\n  view_.addQuery(bag, rosbag::TopicQuery(topics), time_init, time_finish);\n  if (view_.size() == 0) {\n    ROS_ERROR(\"No messages to play on specified topics.  Exiting.\");\n    ros::shutdown();\n    return 0;\n  }\n\n  ros::Rate rate(10);\n  for (const rosbag::MessageInstance& m : view_) {\n    ros::Time ros_bag_time = m.getTime();\n    if (m.getTopic() == gps_topic) {\n      sensor_msgs::NavSatFix::ConstPtr gps_msg =\n          m.instantiate<sensor_msgs::NavSatFix>();\n      if (gps_msg != NULL) {\n        GPSHandler(gps_msg);\n        ros::spinOnce();\n        rate.sleep();\n      }\n    }\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "4fe93263df422a6d0bf0f7cf6ed00ddc4300d095", "size": 2575, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/gpsVisualization.cpp", "max_stars_repo_name": "hkwww/LIO-SAM", "max_stars_repo_head_hexsha": "254dcca72fda264c6f3ae99150e49edaa56284df", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/gpsVisualization.cpp", "max_issues_repo_name": "hkwww/LIO-SAM", "max_issues_repo_head_hexsha": "254dcca72fda264c6f3ae99150e49edaa56284df", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gpsVisualization.cpp", "max_forks_repo_name": "hkwww/LIO-SAM", "max_forks_repo_head_hexsha": "254dcca72fda264c6f3ae99150e49edaa56284df", "max_forks_repo_licenses": ["BSD-3-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.3936170213, "max_line_length": 80, "alphanum_fraction": 0.692038835, "num_tokens": 778, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597974, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.454164332655732}}
{"text": "/* Copyright (C) 2010-2019, The Regents of The University of Michigan.\n All rights reserved.\n\n This software was developed as part of the The Vulcan project in the Intelligent Robotics Lab\n under the direction of Benjamin Kuipers, kuipers@umich.edu. Use of this code is governed by an\n MIT-style License that can be found at \"https://github.com/h2ssh/Vulcan\".\n*/\n\n\n/**\n* \\file     gl_shapes.cpp\n* \\author   Collin Johnson\n*\n* Definition of a number of functions for drawing various primitive shapes using OpenGL.\n*/\n\n#include <ui/common/gl_shapes.h>\n#include <ui/common/ui_color.h>\n#include <math/angle_range.h>\n#include <core/point.h>\n#include <core/multivariate_gaussian.h>\n#include <math/geometry/arc.h>\n#include <math/geometry/circle.h>\n#include <math/geometry/rectangle.h>\n#include <math/geometry/polygon.h>\n#include <boost/range/iterator_range.hpp>\n#include <GL/gl.h>\n\nnamespace vulcan\n{\nnamespace ui\n{\n\nconst float ARROW_ANGLE        = 150.0f;   // degrees of offset for the lines forming the point of the arrow\n// The arrow ratios are how long the arrow head is vs. the length\nconst float SMALL_ARROW_RATIO  = 0.1f;\nconst float MEDIUM_ARROW_RATIO = 0.2f;\nconst float LARGE_ARROW_RATIO  = 0.3f;\n\nvoid draw_filled_partial_ellipse(Point<float>  center,\n                                 float               xAxisRadius,\n                                 float               yAxisRadius,\n                                 math::angle_range_t range,\n                                 int                 numSegments);\nvoid draw_line_partial_ellipse(Point<float>  center,\n                               float               xAxisRadius,\n                               float               yAxisRadius,\n                               math::angle_range_t range,\n                               float               lineWidth,\n                               int                 numSegments);\nvoid draw_arrow(const Point<float>& start, float length, float direction, float lineWidth, float ratio);\nvoid draw_arrow_polygon(const Point<float>& start,\n                        float length,\n                        float direction,\n                        float lineWidth,\n                        float ratio,\n                        bool filled);\ntemplate <typename PointIter>\nvoid gl_draw_filled_polygon_impl(PointIter begin, PointIter end);\n\ntemplate <typename PointIter>\nvoid gl_draw_line_polygon_impl(PointIter begin, PointIter end, float lineWidth);\n\n\nvoid gl_draw_filled_circle(const Point<float>& center, float radius, int numSegments)\n{\n    gl_draw_filled_ellipse(center, radius, radius, numSegments);\n}\n\n\nvoid gl_draw_line_circle(const Point<float>& center, float radius, float width, int numSegments)\n{\n    gl_draw_line_ellipse(center, radius, radius, width, numSegments);\n}\n\n\nvoid gl_draw_filled_arc(const math::Arc<float>& arc, int numSegments)\n{\n    draw_filled_partial_ellipse(arc.center(), arc.radius(), arc.radius(), arc.range(), numSegments);\n}\n\n\nvoid gl_draw_line_arc(const math::Arc<float>& arc, float width, int numSegments)\n{\n    draw_line_partial_ellipse(arc.center(), arc.radius(), arc.radius(), arc.range(), width, numSegments);\n\n    // Draw line segments connecting the center of the arc to the curved portion\n    glLineWidth(width);\n    glBegin(GL_LINES);\n    glVertex2f(arc.center().x, arc.center().y);\n    glVertex2f(arc.center().x + (arc.radius() * std::cos(arc.range().start)),\n               arc.center().y + (arc.radius() * std::sin(arc.range().start)));\n    glVertex2f(arc.center().x, arc.center().y);\n    glVertex2f(arc.center().x + (arc.radius() * std::cos(arc.range().start + arc.range().extent)),\n               arc.center().y + (arc.radius() * std::sin(arc.range().start + arc.range().extent)));\n    glEnd();\n}\n\n\nvoid gl_draw_filled_circle(const math::Circle<float>& circle, int numSegments)\n{\n    gl_draw_filled_circle(circle.center(), circle.radius(), numSegments);\n}\n\n\nvoid gl_draw_line_circle(const math::Circle<float>& circle, float width, int numSegments)\n{\n    gl_draw_line_circle(circle.center(), circle.radius(), width, numSegments);\n}\n\n\nvoid gl_draw_filled_ellipse(const Point<float>& center, float xAxisRadius, float yAxisRadius, int numSegments)\n{\n    draw_filled_partial_ellipse(center, xAxisRadius, yAxisRadius, math::angle_range_t(0.0f, 2*M_PI), numSegments);\n}\n\n\nvoid gl_draw_line_ellipse(const Point<float>& center, float xAxisRadius, float yAxisRadius, float width, int numSegments)\n{\n    draw_line_partial_ellipse(center, xAxisRadius, yAxisRadius, math::angle_range_t(0.0f, 2*M_PI), width, numSegments);\n}\n\n\nvoid gl_draw_filled_polygon(const std::vector<Point<float>>& vertices)\n{\n    gl_draw_filled_polygon_impl(vertices.begin(), vertices.end());\n}\n\n\nvoid gl_draw_line_polygon(const std::vector<Point<float>>& vertices, float width)\n{\n    gl_draw_line_polygon_impl(vertices.begin(), vertices.end(), width);\n}\n\n\nvoid gl_draw_filled_polygon(const math::Polygon<double>& polygon)\n{\n    gl_draw_filled_polygon_impl(polygon.begin(), polygon.end());\n}\n\n\nvoid gl_draw_line_polygon(const math::Polygon<double>& polygon, float width)\n{\n    gl_draw_line_polygon_impl(polygon.begin(), polygon.end(), width);\n}\n\n\nvoid gl_draw_filled_rectangle(const math::Rectangle<float>& rect)\n{\n    glBegin(GL_QUADS);\n    glVertex2f(rect.bottomLeft.x,  rect.bottomLeft.y);\n    glVertex2f(rect.bottomRight.x, rect.bottomRight.y);\n    glVertex2f(rect.topRight.x,    rect.topRight.y);\n    glVertex2f(rect.topLeft.x,     rect.topLeft.y);\n    glEnd();\n}\n\n\nvoid gl_draw_line_rectangle(const math::Rectangle<float>& rect, float width)\n{\n    glLineWidth(width);\n    glBegin(GL_LINE_LOOP);\n    glVertex2f(rect.bottomLeft.x,  rect.bottomLeft.y);\n    glVertex2f(rect.bottomRight.x, rect.bottomRight.y);\n    glVertex2f(rect.topRight.x,    rect.topRight.y);\n    glVertex2f(rect.topLeft.x,     rect.topLeft.y);\n    glEnd();\n}\n\n\nvoid gl_draw_filled_triangle(const Point<float>& center, float width, float height, float orientation)\n{\n    glPushMatrix();\n    glTranslatef(center.x, center.y, 0.0f);\n    glRotatef(orientation*180.0f/M_PI, 0.0f, 0.0f, 1.0f);\n    glBegin(GL_TRIANGLES);\n    glVertex2f(-height/2.0f, -width/2.0f);\n    glVertex2f(height/2.0f, 0.0f);\n    glVertex2f(-height/2.0f, width/2.0f);\n    glEnd();\n    glPopMatrix();\n}\n\n\nvoid gl_draw_line_triangle(const Point<float>& center, float width, float height, float orientation, float lineWidth)\n{\n    glLineWidth(lineWidth);\n    glPushMatrix();\n    glTranslatef(center.x, center.y, 0.0f);\n    glRotatef(orientation*180.0f/M_PI, 0.0f, 0.0f, 1.0f);\n    glBegin(GL_LINE_LOOP);\n    glVertex2f(-height/2.0f, -width/2.0f);\n    glVertex2f(height/2.0f, 0.0f);\n    glVertex2f(-height/2.0f, width/2.0f);\n    glEnd();\n    glPopMatrix();\n}\n\n\nvoid gl_draw_small_arrow(const Point<float>& start, float length, float direction, float lineWidth)\n{\n    draw_arrow(start, length, direction, lineWidth, SMALL_ARROW_RATIO);\n}\n\n\nvoid gl_draw_medium_arrow(const Point<float>& start, float length, float direction, float lineWidth)\n{\n    draw_arrow(start, length, direction, lineWidth, MEDIUM_ARROW_RATIO);\n}\n\n\nvoid gl_draw_large_arrow(const Point<float>& start, float length, float direction, float lineWidth)\n{\n    draw_arrow(start, length, direction, lineWidth, LARGE_ARROW_RATIO);\n}\n\n\nvoid gl_draw_small_arrow_polygon_line(const Point<float>& start, float length, float direction, float lineWidth)\n{\n    draw_arrow_polygon(start, length, direction, lineWidth, SMALL_ARROW_RATIO, false);\n}\n\n\nvoid gl_draw_medium_arrow_polygon_line(const Point<float>& start, float length, float direction, float lineWidth)\n{\n    draw_arrow_polygon(start, length, direction, lineWidth, MEDIUM_ARROW_RATIO, false);\n}\n\n\nvoid gl_draw_large_arrow_polygon_line(const Point<float>& start, float length, float direction, float lineWidth)\n{\n    draw_arrow_polygon(start, length, direction, lineWidth, LARGE_ARROW_RATIO, false);\n}\n\n\nvoid gl_draw_small_arrow_polygon_filled(const Point<float>& start, float length, float direction)\n{\n    draw_arrow_polygon(start, length, direction, 0.0f, SMALL_ARROW_RATIO, true);\n}\n\n\nvoid gl_draw_medium_arrow_polygon_filled(const Point<float>& start, float length, float direction)\n{\n    draw_arrow_polygon(start, length, direction, 0.0f, MEDIUM_ARROW_RATIO, true);\n}\n\n\nvoid gl_draw_large_arrow_polygon_filled(const Point<float>& start, float length, float direction)\n{\n    draw_arrow_polygon(start, length, direction, 0.0f, LARGE_ARROW_RATIO, true);\n}\n\n\nvoid gl_draw_gaussian_distribution(const MultivariateGaussian& gaussian, float numSigma, const GLColor& color, float width)\n{\n    /*\n    * A Gaussian distribution will be drawn as the following:\n    *\n    *   - A low-alpha filled-in ellipse\n    *   - Lines along the major and minor axis\n    *   - A solid line bounding the ellipse\n    */\n\n    const int NUM_SEGMENTS = 36;\n\n    Vector eigenvalues;\n    Matrix eigenvectors;\n\n    Point<float> center(gaussian.getMean()(0), gaussian.getMean()(1));\n    Matrix xyCov = gaussian.getCovariance().submat(arma::span(0,1), arma::span(0,1));\n\n    arma::eig_sym(eigenvalues, eigenvectors, xyCov);\n\n    float theta = atan2(eigenvectors(1, 0), eigenvectors(0, 0));\n\n    // The eigenvalues are sigma^2, so scale them to represent the desired number of sigmas for the ellipses\n    eigenvalues = numSigma * arma::sqrt(eigenvalues);\n\n    glPushMatrix();\n\n    glTranslatef(center.x, center.y, 0.0f);\n    glRotatef(theta*180.0f/M_PI, 0.0f, 0.0f, 1.0f);\n\n    color.set(0.33f);\n    gl_draw_filled_ellipse(Point<float>(0.0f, 0.0f), eigenvalues(0), eigenvalues(1), NUM_SEGMENTS);\n\n    color.set();\n\n    glLineWidth(width);\n    glBegin(GL_LINES);\n    glVertex2f(-eigenvalues(0), 0.0f);\n    glVertex2f(eigenvalues(0), 0.0f);\n\n    glVertex2f(0.0f, -eigenvalues(1));\n    glVertex2f(0.0f, eigenvalues(1));\n    glEnd();\n\n    gl_draw_line_ellipse(Point<float>(0.0f, 0.0f), eigenvalues(0), eigenvalues(1), width, NUM_SEGMENTS);\n\n    glPopMatrix();\n}\n\n\nvoid draw_filled_partial_ellipse(Point<float>  center,\n                                 float               xAxisRadius,\n                                 float               yAxisRadius,\n                                 math::angle_range_t range,\n                                 int                 numSegments)\n{\n    // Use the triangle fan to easily draw the circle by incrementing the next vertex by the segment interval\n    float rotationStep = range.extent / numSegments;\n\n    glBegin(GL_TRIANGLE_FAN);\n\n    glVertex2f(center.x, center.y);\n\n    // Need to do <= numSegments because the first vertex needs to be drawn a second time in order to close the circle\n    for(int n = 0; n <= numSegments; ++n)\n    {\n        glVertex2f(center.x + xAxisRadius*cos(n*rotationStep + range.start),\n                   center.y + yAxisRadius*sin(n*rotationStep + range.start));\n    }\n\n    glEnd();\n}\n\n\nvoid draw_line_partial_ellipse(Point<float>  center,\n                               float               xAxisRadius,\n                               float               yAxisRadius,\n                               math::angle_range_t range,\n                               float               lineWidth,\n                               int                 numSegments)\n{\n    float rotationStep = range.extent / numSegments;\n\n    glLineWidth(lineWidth);\n    glBegin(GL_LINE_STRIP);\n\n    // Need to do <= numSegments because the first vertex needs to be drawn a second time in order to close the circle\n    for(int n = 0; n <= numSegments; ++n)\n    {\n        glVertex2f(center.x + xAxisRadius*cos(n*rotationStep + range.start),\n                   center.y + yAxisRadius*sin(n*rotationStep + range.start));\n    }\n\n    glEnd();\n}\n\n\nvoid draw_arrow(const Point<float>& start, float length, float direction, float lineWidth, float ratio)\n{\n    float headLength = length * ratio;\n\n    glLineWidth(lineWidth);\n    glPushMatrix();\n    glTranslatef(start.x, start.y, 0.0f);\n    glRotatef(direction*180.0/M_PI, 0.0f, 0.0f, 1.0f);\n    glBegin(GL_LINES);\n\n    // Body of the arrow\n    glVertex2f(0.0f, 0.0f);\n    glVertex2f(length, 0.0f);\n\n    // Left arrow\n    glVertex2f(length, 0.0f);\n    glVertex2f(length - headLength*std::cos(ARROW_ANGLE), headLength*std::sin(ARROW_ANGLE));\n\n    // Right arrow\n    glVertex2f(length, 0.0f);\n    glVertex2f(length - headLength*std::cos(ARROW_ANGLE), -headLength*std::sin(ARROW_ANGLE));\n\n    glEnd();\n    glPopMatrix();\n}\n\n\nvoid draw_arrow_polygon(const Point<float>& start,\n                        float length,\n                        float direction,\n                        float lineWidth,\n                        float ratio,\n                        bool filled)\n{\n    // The body of the array is 2/3 of the length\n    // The height of the head is 1/3 the length\n    const float headLength = length * ratio;\n    const float height = headLength * 0.8f;\n    const float bodyLength = length - headLength;\n    const float bodyHeight = height / 2.0f;\n\n    math::Rectangle<float> body(Point<float>(0.0f, -bodyHeight), Point<float>(bodyLength, bodyHeight));\n    Point<float> triangleBottom(bodyLength, -height);\n    Point<float> triangleTop(bodyLength, height);\n    Point<float> triangleRight(length, 0.0f);\n\n    glPushMatrix();\n    glTranslatef(start.x, start.y, 0.0f);\n    glRotatef(direction * 180.0 / M_PI, 0.0, 0.0, 1.0);\n\n    if(filled)\n    {\n        gl_draw_filled_rectangle(body);\n        glBegin(GL_TRIANGLES);\n        glVertex2f(triangleTop.x, triangleTop.y);\n        glVertex2f(triangleRight.x, triangleRight.y);\n        glVertex2f(triangleBottom.x, triangleBottom.y);\n        glEnd();\n    }\n    else\n    {\n\n        glLineWidth(lineWidth);\n        glBegin(GL_LINE_LOOP);\n        glVertex2f(body.bottomRight.x, body.bottomRight.y);\n        glVertex2f(body.bottomLeft.x, body.bottomLeft.y);\n        glVertex2f(body.topLeft.x, body.topLeft.y);\n        glVertex2f(body.topRight.x, body.topRight.y);\n        glVertex2f(triangleTop.x, triangleTop.y);\n        glVertex2f(triangleRight.x, triangleRight.y);\n        glVertex2f(triangleBottom.x, triangleBottom.y);\n        glEnd();\n    }\n\n    glPopMatrix();\n}\n\n\ntemplate <typename PointIter>\nvoid gl_draw_filled_polygon_impl(PointIter begin, PointIter end)\n{\n    glBegin(GL_POLYGON);\n\n    for(auto vertex : boost::make_iterator_range(begin, end))\n    {\n        glVertex2f(vertex.x, vertex.y);\n    }\n\n    glEnd();\n}\n\n\ntemplate <typename PointIter>\nvoid gl_draw_line_polygon_impl(PointIter begin, PointIter end, float lineWidth)\n{\n    glLineWidth(lineWidth);\n    glBegin(GL_LINE_LOOP);\n\n    for(auto vertex : boost::make_iterator_range(begin, end))\n    {\n        glVertex2f(vertex.x, vertex.y);\n    }\n\n    glEnd();\n}\n\n} // namespace ui\n} // namespace vulcan\n", "meta": {"hexsha": "84fe50c9a651e96a76f124e7cddd6aafeb4cd068", "size": 14599, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ui/common/gl_shapes.cpp", "max_stars_repo_name": "h2ssh/Vulcan", "max_stars_repo_head_hexsha": "cc46ec79fea43227d578bee39cb4129ad9bb1603", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2020-03-29T09:37:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T08:56:31.000Z", "max_issues_repo_path": "src/ui/common/gl_shapes.cpp", "max_issues_repo_name": "h2ssh/Vulcan", "max_issues_repo_head_hexsha": "cc46ec79fea43227d578bee39cb4129ad9bb1603", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-03-05T08:00:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-05T08:00:50.000Z", "max_forks_repo_path": "src/ui/common/gl_shapes.cpp", "max_forks_repo_name": "h2ssh/Vulcan", "max_forks_repo_head_hexsha": "cc46ec79fea43227d578bee39cb4129ad9bb1603", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2019-05-13T00:04:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-20T08:56:38.000Z", "avg_line_length": 31.8061002179, "max_line_length": 123, "alphanum_fraction": 0.6650455511, "num_tokens": 3483, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4541643326557318}}
{"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#ifndef CLOTHO_WEIGHT_DISTRIBUTION_HELPER_HPP_\n#define CLOTHO_WEIGHT_DISTRIBUTION_HELPER_HPP_\n\n#include <boost/property_tree/ptree.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include \"clotho/random/normal_distribution_parameter.hpp\"\n\nnamespace clotho {\nnamespace genetics {\n\ntemplate < class T >\nstruct weight_distribution_helper;\n\n\ntemplate < >\nstruct weight_distribution_helper< double > {\n    typedef boost::random::normal_distribution< double > type;\n    typedef typename type::param_type                   result_type;\n\n    static result_type  makeParameter( boost::property_tree::ptree & config ) {\n        normal_distribution_parameter< double > param( config );\n        return result_type( param.m_mean, param.m_sigma );\n    }\n};\n\ntemplate < >\nstruct weight_distribution_helper< float > {\n    typedef boost::random::normal_distribution< float >     type;\n    typedef typename type::param_type                       result_type;\n\n    static result_type  makeParameter( boost::property_tree::ptree & config ) {\n        normal_distribution_parameter< float > param( config );\n        return result_type( param.m_mean, param.m_sigma );\n    }\n};\n\n}   // namespace genetics\n}   // namespace clotho\n\n#endif  // CLOTHO_WEIGHT_DISTRIBUTION_HELPER_HPP_\n\n", "meta": {"hexsha": "abced00a4b93ab3b68de04f80b2ced230005dc8b", "size": 1873, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/clotho/data_spaces/generators/weight_distribution_helper.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/data_spaces/generators/weight_distribution_helper.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/data_spaces/generators/weight_distribution_helper.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.0545454545, "max_line_length": 79, "alphanum_fraction": 0.7261078484, "num_tokens": 400, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597971, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.45416433265573175}}
{"text": "#include <vector>\n#include <tuple>\n\n#include <Eigen/Core>\n\nnamespace tsp {\ntypedef Eigen::MatrixXd distance_matrix_t;\ntypedef std::vector<int> path_t;\ntypedef Eigen::Matrix<uint8_t, Eigen::Dynamic, Eigen::Dynamic> ordered_neighbors_t;\n\ndistance_matrix_t randomDistanceMatrix(int N);\n/// Compute nearest neighbor from i\nordered_neighbors_t neighborMatrix(const distance_matrix_t& d);\ndouble evaluateCost(const distance_matrix_t& d, const path_t& path);\n\nnamespace heuristic_nearest {\nstd::tuple<double, path_t> solve (const distance_matrix_t& d);\n}\nnamespace dynamic_programming {\nstd::tuple<double, path_t> solveWithBound (const distance_matrix_t& d,\n    double costUpperBound,\n    bool allowPruning = true);\n\ninline std::tuple<double, path_t> solve (const distance_matrix_t& d,\n    bool allowPruning = true)\n{\n  return solveWithBound(d, std::numeric_limits<double>::infinity(), allowPruning);\n}\n\nstd::tuple<double, path_t> solveWithHeuristic (const distance_matrix_t& d,\n    bool allowPruning = true);\n\n}\nnamespace brute_force {\nstd::tuple<double, path_t> solve (const distance_matrix_t& d);\n}\nnamespace approximative_kopt {\nvoid swap2opt(path_t& path, int i, int k);\nbool swap3opt(const distance_matrix_t& d, path_t& path, int i, int j, int k);\nstd::tuple<double, path_t> solve2opt (const distance_matrix_t& d, path_t initialGuess = path_t());\nstd::tuple<double, path_t> solve3opt (const distance_matrix_t& d, path_t initialGuess = path_t());\n}\n}\n", "meta": {"hexsha": "b3773337034939f46e381746dacb74b3e8672131", "size": 1449, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/tsp.hpp", "max_stars_repo_name": "jmirabel/agimus-demos", "max_stars_repo_head_hexsha": "d18703626f3bac322dec788ad9506495771d15a3", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-10T09:39:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-10T09:39:44.000Z", "max_issues_repo_path": "src/tsp.hpp", "max_issues_repo_name": "jmirabel/agimus-demos", "max_issues_repo_head_hexsha": "d18703626f3bac322dec788ad9506495771d15a3", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-02-20T14:08:08.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-23T14:29:26.000Z", "max_forks_repo_path": "src/tsp.hpp", "max_forks_repo_name": "jmirabel/agimus-demos", "max_forks_repo_head_hexsha": "d18703626f3bac322dec788ad9506495771d15a3", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2018-08-21T12:03:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-15T08:43:39.000Z", "avg_line_length": 32.9318181818, "max_line_length": 98, "alphanum_fraction": 0.7694962043, "num_tokens": 359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125626441471, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4541643259426369}}
{"text": "/**\n * @author     : Zhao Chonyyao (cyzhao@zju.edu.cn)\n * @date       : 2021-04-30\n * @description: embedded elasticity finite element method problem\n * @version    : 1.0\n */\n#include <memory>\n#include <iomanip>\n#include <boost/property_tree/ptree.hpp>\n\n#include \"Common/error.h\"\n\n// TODO: possible bad idea of having dependence to model in problem module\n#include \"Model/fem/elas_energy.h\"\n#include \"Model/fem/mass_matrix.h\"\n\n#include \"Problem/energy/basic_energy.h\"\n#include \"Io/io.h\"\n#include \"Geometry/extract_surface.imp\"\n#include \"Geometry/interpolate.h\"\n#include \"libigl/include/igl/readOBJ.h\"\n\n#include \"embedded_elas_fem_problem.h\"\n\nnamespace PhysIKA {\nusing namespace std;\nusing namespace Eigen;\nusing namespace igl;\n\ntemplate <typename T>\nusing MAT = Eigen::Matrix<T, -1, -1>;\ntemplate <typename T>\nusing VEC = Eigen::Matrix<T, -1, 1>;\n\ntemplate <typename T>\nembedded_elas_problem_builder<T>::embedded_elas_problem_builder(const T* x, const boost::property_tree::ptree& pt)\n    : pt_(pt)\n{\n    //TODO: need to check exception\n    using Vector3T               = Eigen::Matrix<T, 3, 1>;\n    const string filename        = pt.get<string>(\"filename\");\n    const string filename_coarse = pt.get<string>(\"filename_coarse\");\n    cout << \"filename \" << filename << \"\\n filename_coarse \" << filename_coarse << endl;\n    MAT<T>   nods;\n    MatrixXi cells;\n\n    MAT<T>   nods_coarse;\n    MatrixXi cells_coarse;\n\n    string type = pt.get<string>(\"type\", \"tet\");\n    if (type == \"vox\")\n        type = \"hex\";\n    string type_coarse = pt.get<string>(\"type_coarse\", type);\n    if (type_coarse == \"vox\")\n        type_coarse = \"hex\";\n    cout << \"mesh type is \" << type << endl;\n    cout << \"coarse type is \" << type_coarse << endl;\n    if (type_coarse == \"tet\")\n    {\n        IF_ERR(exit, mesh_read_from_vtk<T, 4>(filename_coarse.c_str(), nods_coarse, cells_coarse));\n    }\n    else if (type_coarse == \"hex\")\n    {\n        exit_if(mesh_read_from_vtk<T, 8>(filename_coarse.c_str(), nods_coarse, cells_coarse));\n    }\n    else if (type_coarse == \"hybrid\")\n    {\n        cout << \"read hybrid mesh \" << filename << endl;\n        exit_if(mesh_read_from_vtk<T, 8>(filename_coarse.c_str(), nods_coarse));\n    }\n    else\n    {\n        // error_msg(\"type:<%s> is not supported.\", type.c_str());\n    }\n    cout << \"number of cells is \" << cells_coarse.cols() << endl;\n#if 1\n    if (type_coarse == \"hybrid\")\n    {\n        Vector3T nods_min = nods_coarse.col(0);\n        Vector3T nods_max = nods_coarse.col(1);\n        for (size_t i = 0; i < 3; ++i)\n        {\n            nods_min(i) = nods_coarse.row(i).minCoeff();\n            nods_max(i) = nods_coarse.row(i).maxCoeff();\n        }\n        Matrix<T, 3, 8> nods_coarsest = Matrix<T, 3, 8>::Ones();\n        //set z\n        nods_coarsest.block<1, 4>(2, 0) *= nods_min(2);\n        nods_coarsest.block<1, 4>(2, 4) *= nods_max(2);\n        //set y\n        Vector4i y_min{ { 2, 3, 6, 7 } };\n        Vector4i y_max{ { 0, 1, 4, 5 } };\n        nods_coarsest(1, y_min) *= nods_min(1);\n        nods_coarsest(1, y_max) *= nods_max(1);\n        //set x\n        Vector4i x_min{ { 0, 3, 4, 7 } };\n        Vector4i x_max{ { 1, 2, 5, 6 } };\n        nods_coarsest(0, x_min) *= nods_min(0);\n        nods_coarsest(0, x_max) *= nods_max(0);\n\n        nods_coarse = nods_coarsest;\n\n        cout << nods_coarse << endl;\n        cells_coarse.resize(8, 1);\n        cells_coarse.col(0).setLinSpaced(8, 0, 7);\n        Eigen::MatrixXi hexs2tets = hex_2_tet(cells_coarse);\n        cells_coarse              = hexs2tets;\n\n        cout << cells_coarse << endl;\n        type_coarse = \"tet\";\n    }\n#endif\n    if (filename.rfind(\".obj\") != string::npos)\n    {\n        readOBJ(filename.c_str(), nods, cells);\n        nods.transposeInPlace();\n        cells.transposeInPlace();\n    }\n    else\n    {\n        //TODO: need to check file reading error\n        if (type == \"tet\")\n        {\n            IF_ERR(exit, mesh_read_from_vtk<T, 4>(filename.c_str(), nods, cells));\n        }\n        else if (type == \"hex\")\n        {\n            exit_if(mesh_read_from_vtk<T, 8>(filename.c_str(), nods, cells));\n        }\n        //else if (type == \"hybrid\") {\n        //\tcout << \"read hybrid mesh \" << filename << endl;\n        //\texit_if(mesh_read_from_vtk<T, 8>(filename.c_str(), nods));\n        //\n\n        //}\n        else\n        {\n            // error_msg(\"type:<%s> is not supported.\", type.c_str());\n        }\n    }\n\n    if (cells.size() == 0)\n        cells.resize(4, 0);\n    if (cells_coarse.size() == 0)\n        cells_coarse.resize(4, 0);\n    interp_pts_in_tets<T, 3>(nods, cells, nods_coarse, fine_to_coarse_coef_);\n    //interp_pts_in_point_cloud<T, 3>(nods_coarse, nods, coarse_to_fine_coef_);\n\n    if (type_coarse == \"tet\")\n        interp_pts_in_tets<T, 3>(nods_coarse, cells_coarse, nods, coarse_to_fine_coef_);\n    else\n    {\n        //interp_pts_in_point_cloud<T, 3>(nods_coarse, nods, coarse_to_fine_coef_);\n        Eigen::MatrixXi hexs2tets = hex_2_tet(cells_coarse);\n        cout << \"size of hexs2tets \" << hexs2tets.rows() << \" \" << hexs2tets.cols() << endl;\n        interp_pts_in_tets<T, 3>(nods_coarse, hexs2tets, nods, coarse_to_fine_coef_);\n    }\n\n    const size_t num_nods = nods_coarse.cols();\n    cout << \"V\" << nods_coarse.rows() << \" \" << nods_coarse.cols() << endl\n         << \"T \" << cells_coarse.rows() << \" \" << cells_coarse.cols() << endl;\n    if (x != nullptr)\n    {\n        nods        = Map<const MAT<T>>(x, nods.rows(), nods.cols());\n        nods_coarse = nods * fine_to_coarse_coef_;\n    }\n\n    cout << \"Boundary Box :\\n\"\n         << nods_coarse.rowwise().minCoeff() << endl\n         << nods_coarse.rowwise().maxCoeff() << endl;\n\n    REST_  = nods;\n    cells_ = cells;\n    /*Matrix<T, -1, -1> nods_temp = nods_coarse;*/\n    fine_verts_num_ = REST_.cols();\n\n    auto         phy_paras = pt.get_child(\"physics\");\n    const T      rho       = phy_paras.get<T>(\"rho\", 20);\n    const T      Young     = phy_paras.get<T>(\"Young\", 2000.0);\n    const T      poi       = phy_paras.get<T>(\"poi\", 0.3);\n    const T      gravity   = phy_paras.get<T>(\"gravity\", 9.8);\n    const T      dt        = phy_paras.get<T>(\"dt\", 0.01);\n    const T      w_pos     = phy_paras.get<T>(\"w_pos\", 1e6);\n    const size_t num_frame = phy_paras.get<size_t>(\"num_frames\", 100);\n\n    //read fixed points\n    vector<size_t> cons(0);\n    const string   cons_file_path = pt.get<string>(\"cons\", \"\");\n    /*if(cons_file_path != \"\")\n    IF_ERR(exit, read_fixed_verts_from_csv(cons_file_path.c_str(), cons));*/\n    cout << \"constrint \" << cons.size() << \" points\" << endl;\n\n    //calc mass vector\n    Matrix<T, -1, 1> mass_vec(num_nods);\n    // calc_mass_vector<T>(nods, cells, rho, mass_vec);\n    if (type_coarse == \"tet\")\n        mass_calculator<T, 3, 4, 1, 1, basis_func, quadrature>(nods_coarse, cells_coarse, rho, mass_vec);\n    else if (type_coarse == \"hex\")\n        mass_calculator<T, 3, 8, 1, 2, basis_func, quadrature>(nods_coarse, cells_coarse, rho, mass_vec);\n\n    cout << \"build energy\" << endl;\n    int ELAS = 0;\n    int GRAV = 1;\n    int KIN  = 2;\n    int POS  = 3;\n    if (pt_.get<string>(\"solver_type\") == \"explicit\")\n        POS = 2;\n\n    ebf_.resize(POS + 1);\n    {\n        const string csttt_type = phy_paras.get<string>(\"csttt\", \"linear\");\n\n        gen_elas_energy_intf<T>(type_coarse, csttt_type, nods_coarse, cells_coarse, Young, poi, ebf_[ELAS], &elas_intf_);\n        /* nods_coarse = nods_temp;*/\n        // to lowercase.\n        char axis  = pt.get<char>(\"grav_axis\", 'y') | 0x20;\n        ebf_[GRAV] = make_shared<gravity_energy<T, 3>>(num_nods, 1, gravity, mass_vec, axis);\n        kinetic_   = make_shared<momentum<T, 3>>(nods_coarse.data(), num_nods, mass_vec, dt);\n\n        if (pt_.get<string>(\"solver_type\") == \"implicit\")\n            ebf_[KIN] = kinetic_;\n\n        ebf_[POS] = make_shared<position_constraint<T, 3>>(nods_coarse.data(), num_nods, w_pos, cons);\n    }\n    cout << \"set up energy done.\" << endl;\n\n    //set constraint\n\n    enum constraint_type\n    {\n        COLL\n    };\n    cbf_.resize(COLL + 1);\n    collider_  = nullptr;\n    cbf_[COLL] = collider_;\n\n    shared_ptr<Problem<T, 3>> pb      = make_shared<Problem<T, 3>>(ebf_[0], nullptr);\n    auto                      dat_str = make_shared<dat_str_core<T, 3>>(pb->Nx() / 3, pt.get<bool>(\"hes_is_const\", false));\n    compute_hes_pattern(pb->energy_, dat_str);\n    ebf_[0]->Hes(nods_coarse.data(), dat_str);\n    SparseMatrix<T> K = dat_str->get_hes();\n\n    embedded_interp_ = make_shared<embedded_interpolate<T>>(nods_coarse, coarse_to_fine_coef_, fine_to_coarse_coef_, K, 0.586803 / 2);\n\n    if (pt_.get<string>(\"solver_type\") == \"explicit\")\n    {\n        Map<Matrix<T, -1, 1>> position(nods_coarse.data(), nods_coarse.size());\n        semi_implicit_ = make_shared<semi_implicit<T>>(dt, mass_vec, position);\n    }\n    cout << \"init problem done.\" << endl;\n}\n\ntemplate <typename T>\nstd::shared_ptr<Problem<T, 3>> embedded_elas_problem_builder<T>::build_problem() const\n{\n    cout << \"assemble energy\" << endl;\n    shared_ptr<Functional<T, 3>> energy;\n    try\n    {\n        energy = build_energy_t<T, 3>(ebf_);\n    }\n    catch (std::exception& e)\n    {\n        cerr << e.what() << endl;\n        exit(EXIT_FAILURE);\n    }\n\n    shared_ptr<Constraint<T>> constraint;\n    cout << \"assemble constraint\" << endl;\n    bool all_null = true;\n    for (auto& c : cbf_)\n        if (c != nullptr)\n            all_null = false;\n    if (all_null)\n    {\n        constraint = nullptr;\n        cout << \"WARNGING: No hard constraints.\" << endl;\n    }\n    else\n    {\n        try\n        {\n            constraint = build_constraint_t<T>(cbf_);\n        }\n        catch (std::exception& e)\n        {\n            cerr << e.what() << endl;\n            exit(EXIT_FAILURE);\n        }\n    }\n    exit_if(constraint != nullptr && energy->Nx() != constraint->Nx(), \"energy and constraint has different dimension.\");\n    return make_shared<Problem<T, 3>>(energy, constraint);\n}\n\ntemplate <typename T>\nint embedded_elas_problem_builder<T>::update_problem(const T* x, const T* v)\n{\n    embedded_interp_->update_verts(x, fine_verts_num_);\n    const Eigen::Matrix<T, -1, -1>& verts = embedded_interp_->get_verts();\n\n    IF_ERR(return, kinetic_->update_location_and_velocity(verts.data(), v));\n    if (collider_ != nullptr)\n        IF_ERR(return, collider_->update(verts.data()));\n    return 0;\n}\n\ntemplate class embedded_elas_problem_builder<double>;\n\ntemplate class embedded_elas_problem_builder<float>;\n\n}  // namespace PhysIKA\n", "meta": {"hexsha": "507405c0c6d9f3619bbf486c2c2b17e1517b792d", "size": 10465, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Source/Dynamics/FiniteElementMethod/Source/Problem/integrated_problem/embedded_elas_fem_problem.cc", "max_stars_repo_name": "weikm/sandcarSimulation2", "max_stars_repo_head_hexsha": "fe499d0a3289c0ac1acce69c7dc78d8ce1b2708a", "max_stars_repo_licenses": ["Apache-2.0"], "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/Dynamics/FiniteElementMethod/Source/Problem/integrated_problem/embedded_elas_fem_problem.cc", "max_issues_repo_name": "weikm/sandcarSimulation2", "max_issues_repo_head_hexsha": "fe499d0a3289c0ac1acce69c7dc78d8ce1b2708a", "max_issues_repo_licenses": ["Apache-2.0"], "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/Dynamics/FiniteElementMethod/Source/Problem/integrated_problem/embedded_elas_fem_problem.cc", "max_forks_repo_name": "weikm/sandcarSimulation2", "max_forks_repo_head_hexsha": "fe499d0a3289c0ac1acce69c7dc78d8ce1b2708a", "max_forks_repo_licenses": ["Apache-2.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.5416666667, "max_line_length": 134, "alphanum_fraction": 0.5945532728, "num_tokens": 3050, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.752012562644147, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4541643259426367}}
{"text": "// Copyright Stephan T. Lavavej, http://nuwen.net .\n// Distributed under the Boost Software License, Version 1.0.\n// See accompanying file LICENSE_1_0.txt or copy at\n// http://boost.org/LICENSE_1_0.txt .\n\n#ifndef PHAM_RANDOM_HH\n#define PHAM_RANDOM_HH\n\n#include \"compiler.hh\"\n\n#ifdef NUWEN_PLATFORM_MSVC\n    #pragma once\n#endif\n\n#include \"clock.hh\"\n#include \"time.hh\"\n#include \"typedef.hh\"\n#include \"vector.hh\"\n\n#include \"external_begin.hh\"\n    #include <boost/random/mersenne_twister.hpp>\n    #include <boost/utility.hpp>\n#include \"external_end.hh\"\n\nnamespace nuwen {\n    namespace random {\n        class twister : public boost::noncopyable {\n        public:\n            inline twister();\n\n            inline uc_t   random_uc();\n            inline us_t   random_us();\n            inline ul_t   random_ul();\n            inline ull_t  random_ull();\n            inline float  random_float_0_1();\n            inline double random_double_0_1();\n\n        private:\n            boost::mt19937 m_mt;\n        };\n    }\n}\n\nnamespace pham {\n    inline nuwen::ul_t make_seed() {\n        using namespace nuwen;\n\n        const ull_t ctr = clock_ctr();\n\n        const ul_t a = static_cast<ul_t>(ctr >> 32);\n        const ul_t b = static_cast<ul_t>(ctr & 0xFFFFFFFFUL);\n\n        const ull_t uqh = ull_from_sll(current_qh_time());\n\n        const ul_t c = static_cast<ul_t>(uqh >> 32);\n        const ul_t d = static_cast<ul_t>(uqh & 0xFFFFFFFFUL);\n\n        return a ^ b ^ c ^ d;\n    }\n}\n\ninline nuwen::random::twister::twister() : m_mt(pham::make_seed()) { }\n\ninline nuwen::uc_t nuwen::random::twister::random_uc() {\n    return static_cast<nuwen::uc_t>(m_mt() & 0xFF);\n}\n\ninline nuwen::us_t nuwen::random::twister::random_us() {\n    return static_cast<nuwen::us_t>(m_mt() & 0xFFFF);\n}\n\ninline nuwen::ul_t nuwen::random::twister::random_ul() {\n    return m_mt();\n}\n\ninline nuwen::ull_t nuwen::random::twister::random_ull() {\n    ull_t ret = m_mt();\n    ret <<= 32;\n    ret |= m_mt();\n\n    return ret;\n}\n\ninline float nuwen::random::twister::random_float_0_1() {\n    return static_cast<float>(random_ul()) / static_cast<float>(0xFFFFFFFFUL);\n}\n\ninline double nuwen::random::twister::random_double_0_1() {\n    return static_cast<double>(random_ull()) / static_cast<double>(0xFFFFFFFFFFFFFFFFULL);\n}\n\n#endif // Idempotency\n", "meta": {"hexsha": "d4b0beac591996846cc6d484a2c4203ba0cf3c17", "size": 2299, "ext": "hh", "lang": "C++", "max_stars_repo_path": "random.hh", "max_stars_repo_name": "nurettin/libnuwen", "max_stars_repo_head_hexsha": "5b3012d9e75552c372a4d09b218b7af04a928e68", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2019-09-17T10:33:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-29T10:03:42.000Z", "max_issues_repo_path": "random.hh", "max_issues_repo_name": "nurettin/libnuwen", "max_issues_repo_head_hexsha": "5b3012d9e75552c372a4d09b218b7af04a928e68", "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": "random.hh", "max_forks_repo_name": "nurettin/libnuwen", "max_forks_repo_head_hexsha": "5b3012d9e75552c372a4d09b218b7af04a928e68", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-10-05T04:31:22.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-05T04:31:22.000Z", "avg_line_length": 24.7204301075, "max_line_length": 90, "alphanum_fraction": 0.6454980426, "num_tokens": 620, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859598, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.45415664801417327}}
{"text": "////////////////////////////////////////////////////////////////////////////////\n//  Copyright (c) 2021 Andreas Wagner.\n//\n//  Distributed under the Boost Software License, Version 1.0. (See accompanying\n//  file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n////////////////////////////////////////////////////////////////////////////////\n\n#ifndef TUMORMODELS_UPWINDING_FORMULAS_LINEARIZED_FLOW_HPP\n#define TUMORMODELS_UPWINDING_FORMULAS_LINEARIZED_FLOW_HPP\n\n#include <Eigen/Dense>\n#include <cassert>\n\n#include \"vessel_formulas.hpp\"\n\nnamespace macrocirculation {\n\nnamespace linearized {\n\n/*! @brief Calculates the upwinding at an inner boundary.\n *\n * @param alpha The \\f$ \\sqrt{\\frac{C}{L}} \\f$ factor for the linearized characteristics.\n * @param p_l   The pressure at the boundary of the left cell.\n * @param q_l   The flux at the boundary of the left cell.\n * @param p_r   The pressure at the boundary of the right cell.\n * @param q_r   The flux at the boundary of the right cell.\n * @param p_up  The upwinded pressure.\n * @param q_up  The upwinded flux.\n */\ninline void inner_boundary(double alpha, double p_l, double q_l, double p_r, double q_r, double &p_up, double &q_up) {\n  q_up = 0.5 * (q_l + q_r + alpha * (p_l - p_r));\n  p_up = (alpha * p_l + q_l  - q_up) / alpha;\n}\n\n/*! @brief Calculates the upwinding at an nfurcation.\n *\n * @param p         The boundary pressure values of each vessel at a common vertex.\n * @param q         The boundary flux values of each vessel at a common vertex.\n * @param params    The physical edge parameters near the nfurcation.\n * @param sigma     The vessel normals (+1 if the vessel points to the vertex, -1 if not).\n * @param p_up      The upwinded pressure values.\n * @param q_up      The upwinded flux values.\n */\ninline void nfurcation_boundary(const std::vector<double> &p,\n                                const std::vector<double> &q,\n                                const std::vector<VesselParameters> &params,\n                                const std::vector<double> &sigma,\n                                std::vector<double> &p_up,\n                                std::vector<double> &q_up) {\n  // all vectors need to have the same size:\n  assert(p.size() == q.size());\n  assert(p_up.size() == p.size());\n  assert(q_up.size() == p.size());\n  assert(params.size() == p.size());\n  assert(sigma.size() == p.size());\n\n  const size_t N = p.size();\n\n  // dof-ordering: (p_1, q_1, p_2, q_2, ... p_N, q_N)\n  Eigen::MatrixXd mat(p.size() + q.size(), p.size() + q.size());\n  Eigen::VectorXd rhs(p.size() + q.size());\n\n  mat.setZero();\n\n  // vector containing the \\f$ \\sqrt{ \\frac{C}{L} } \\f$ factors:\n  std::vector<double> alpha;\n  for (auto &param : params) {\n    alpha.push_back(std::sqrt(linear::get_C(param) / linear::get_L(param)));\n  }\n\n  // constrain the upwinded fluxes to zero:\n  for (int k = 0; k < N; k += 1) {\n    mat(0, 2 * k + 1) = sigma[k];\n  }\n  rhs(0) = 0;\n\n  // the characteristics should be equal\n  for (int k = 0; k < N; k += 1) {\n    mat(1 + k, 2 * k) = 0.5 * alpha[k] * sigma[k];\n    mat(1 + k, 2 * k + 1) = 0.5;\n    rhs(1 + k) = 0.5 * alpha[k] * sigma[k] * p[k] + 0.5 * q[k];\n  }\n\n  // the pressures should be equal\n  for (int k = 1; k < N; k += 1) {\n    mat(N + k, 2 * k) = 1.;\n    mat(N + k, 2 * (k - 1)) = -1.;\n    rhs(N + k) = 0.;\n  }\n\n  Eigen::VectorXd result = mat.fullPivLu().solve(rhs);\n\n  for (int k = 0; k < N; k += 1) {\n    p_up[k] = result[2 * k];\n    q_up[k] = result[2 * k + 1];\n  }\n}\n\n} // namespace linearized\n\n} // namespace macrocirculation\n\n#endif //TUMORMODELS_UPWINDING_FORMULAS_LINEARIZED_FLOW_HPP\n", "meta": {"hexsha": "068a8be9f7fcfe27c2a44b4009139fbcc0a558b3", "size": 3610, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/macrocirculation/upwinding_formulas_linearized_flow.hpp", "max_stars_repo_name": "CancerModeling/Flows1D0D3D", "max_stars_repo_head_hexsha": "ca87bd11acd1f558ee64c379d051e41175a13b6a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-12T11:42:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T11:42:31.000Z", "max_issues_repo_path": "src/macrocirculation/upwinding_formulas_linearized_flow.hpp", "max_issues_repo_name": "CancerModeling/Flows1D0D3D", "max_issues_repo_head_hexsha": "ca87bd11acd1f558ee64c379d051e41175a13b6a", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/macrocirculation/upwinding_formulas_linearized_flow.hpp", "max_forks_repo_name": "CancerModeling/Flows1D0D3D", "max_forks_repo_head_hexsha": "ca87bd11acd1f558ee64c379d051e41175a13b6a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7115384615, "max_line_length": 118, "alphanum_fraction": 0.5814404432, "num_tokens": 1047, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859598, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.45415664801417327}}
{"text": "#ifndef __num_t_hpp__\n#define __num_t_hpp__\n\n/**\n * @file\n * \n * @copyright 2013 Recalcitrant Software, LLC.\n * @license Distributed under the Boost Software License,\n * Version 1.0. See included LICENSE.md or\n * http://www.boost.org/LICENSE_1_0.txt for the complete\n * license.\n */\n\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n\nusing int_t = boost::multiprecision::number\n<\n   boost::multiprecision::cpp_int_backend<>,\n   boost::multiprecision::expression_template_option::et_off\n>;\n\nusing num_t = boost::multiprecision::number\n<\n   boost::multiprecision::cpp_dec_float<1024>,\n   boost::multiprecision::expression_template_option::et_off\n>;\n\n#endif\n", "meta": {"hexsha": "b7ebd8d658c03b0a5f130f172a2f68af8b9517aa", "size": 700, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "num_t.hpp", "max_stars_repo_name": "recalcitrantsoftware/mancalc", "max_stars_repo_head_hexsha": "593b27b65c38b7e273476e6463d9802f5f48b926", "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": "num_t.hpp", "max_issues_repo_name": "recalcitrantsoftware/mancalc", "max_issues_repo_head_hexsha": "593b27b65c38b7e273476e6463d9802f5f48b926", "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": "num_t.hpp", "max_forks_repo_name": "recalcitrantsoftware/mancalc", "max_forks_repo_head_hexsha": "593b27b65c38b7e273476e6463d9802f5f48b926", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.3333333333, "max_line_length": 60, "alphanum_fraction": 0.7571428571, "num_tokens": 175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4541566480141732}}
{"text": "#ifndef STAN_MATH_PRIM_FUN_MODIFIED_BESSEL_FIRST_KIND_HPP\n#define STAN_MATH_PRIM_FUN_MODIFIED_BESSEL_FIRST_KIND_HPP\n\n#include <stan/math/prim/meta.hpp>\n#include <stan/math/prim/err.hpp>\n#include <boost/math/special_functions/bessel.hpp>\n\nnamespace stan {\nnamespace math {\n\n/**\n *\n   \\f[\n   \\mbox{modified\\_bessel\\_first\\_kind}(v, z) =\n   \\begin{cases}\n     I_v(z) & \\mbox{if } -\\infty\\leq z \\leq \\infty \\\\[6pt]\n     \\textrm{error} & \\mbox{if } z = \\textrm{NaN}\n   \\end{cases}\n   \\f]\n\n   \\f[\n   \\frac{\\partial\\, \\mbox{modified\\_bessel\\_first\\_kind}(v, z)}{\\partial z} =\n   \\begin{cases}\n     \\frac{\\partial\\, I_v(z)}{\\partial z} & \\mbox{if } -\\infty\\leq z\\leq \\infty\n \\\\[6pt] \\textrm{error} & \\mbox{if } z = \\textrm{NaN} \\end{cases} \\f]\n\n   \\f[\n     {I_v}(z) = \\left(\\frac{1}{2}z\\right)^v\\sum_{k=0}^\\infty\n \\frac{\\left(\\frac{1}{4}z^2\\right)^k}{k!\\Gamma(v+k+1)} \\f]\n\n     \\f[\n     \\frac{\\partial \\, I_v(z)}{\\partial z} = I_{v-1}(z)-\\frac{v}{z}I_v(z)\n     \\f]\n *\n */\ntemplate <typename T2>\ninline T2 modified_bessel_first_kind(int v, const T2 z) {\n  check_not_nan(\"modified_bessel_first_kind\", \"z\", z);\n\n  return boost::math::cyl_bessel_i(v, z);\n}\n\n}  // namespace math\n}  // namespace stan\n\n#endif\n", "meta": {"hexsha": "c8ed75bb766ccc9641e42a3d21c98aaa9dbf2cce", "size": 1196, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/prim/fun/modified_bessel_first_kind.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/fun/modified_bessel_first_kind.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/fun/modified_bessel_first_kind.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": 25.4468085106, "max_line_length": 79, "alphanum_fraction": 0.631270903, "num_tokens": 455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4541566480141732}}
{"text": "// Copyright (c) 2018 Evan S Weinberg\n// Test bounds on the residual of sequential solves\n\n#include <iostream>\n#include <iomanip>\n#include <cmath>\n#include <string>\n#include <sstream>\n#include <complex>\n#include <random>\n\n// Borrow dense matrix eigenvalue routines.\n#include <Eigen/Dense>\n\n#include \"blas/generic_vector.h\"\n\n#include \"square_wilson.h\"\n#include \"inverters/generic_bicgstab.h\"\n\nusing namespace std; \nusing namespace Eigen;\n\ntypedef Matrix<std::complex<double>, Dynamic, Dynamic, ColMajor> cMatrix;\n\nint main(int argc, char** argv)\n{  \n\n  complex<double> *gauge_links;\n\n  // Set output precision to be long.\n  cout << setprecision(10);\n\n  // Inversion info\n  inversion_info invif;\n\n  // RNG related things.\n  std::mt19937 generator (1337u); // RNG, 1337u is the seed. \n  double inv_variance = 6.0; // inverse of variance for gaussian non-compact U(1) links.\n\n  // Basic information about the lattice.\n  int length = 24;\n  double m_sq = 0.001;\n\n  // max iter\n  int max_iter = 100000;\n\n  // Set tolerances below.I'll nonetheless type the proof up tomorrow, but in any case, I'm feeling good\n\n  // Some start-up.\n  int volume = length*length;\n  int wilson_volume = 2*volume;\n  \n  // Create a random compact U(1) link.\n  gauge_links = allocate_vector<complex<double>>(2*length*length);\n  gaussian_real(gauge_links, 2*length*length, generator, 1.0/inv_variance);\n  polar(gauge_links, 2*length*length);\n\n  // Structure which gets passed to the function.\n  laplace_gauged_struct lapstr_gauged;\n  lapstr_gauged.length = length;\n  lapstr_gauged.m_sq = m_sq;\n  lapstr_gauged.gauge_links = gauge_links; \n\n  ///////////////////////////////////////////////////\n  // GET THE CONDITION NUMBER OF THE WILSON MATRIX //\n  ///////////////////////////////////////////////////\n\n  // Need to get the sqrt of the largest and smallest eigenvalue of the normal op\n\n  double condition_number = 0;\n\n  {\n    complex<double> *rhs_cplx;\n    complex<double> *inter_cplx;\n\n    // Vectors. \n    rhs_cplx = allocate_vector<complex<double>>(wilson_volume);\n    inter_cplx = allocate_vector<complex<double>>(wilson_volume);\n\n    // Zero out the vector.\n    zero_vector(rhs_cplx, 2*length*length);\n    zero_vector(inter_cplx, 2*length*length);\n\n    // Allocate a sufficiently gigantic matrix.\n    cMatrix mat_cplx = cMatrix::Zero(wilson_volume, wilson_volume);\n\n    // Form matrix elements. This is where it's important that\n    // dMatrix and cMatrix are column major.\n    // I should probably make this safer by using a \"Map\".\n    for (int i = 0; i < wilson_volume; i++)\n    {\n      // Set a point on the rhs for a matrix element.\n      zero_vector(rhs_cplx, wilson_volume);\n      rhs_cplx[i] = 1.0;\n      zero_vector(inter_cplx, wilson_volume);\n      square_wilson_gauged(inter_cplx, rhs_cplx, &lapstr_gauged);\n\n      // Where we put the result of the matrix element.\n      complex<double>* mptr = &(mat_cplx(i*wilson_volume));\n\n      square_wilson_dagger_gauged(mptr, inter_cplx, &lapstr_gauged);\n    }\n\n    SelfAdjointEigenSolver<cMatrix> eigsolve_cplx(volume);\n    eigsolve_cplx.compute(mat_cplx);\n\n    double largest_eval = real(eigsolve_cplx.eigenvalues()(wilson_volume-1));\n    double smallest_eval = real(eigsolve_cplx.eigenvalues()(0));\n    std::cout << \" Largest singular value: \" << sqrt(largest_eval) << \"\\n\";\n    std::cout << \"Smallest singular value: \" << sqrt(smallest_eval) << \"\\n\";\n    \n    condition_number = sqrt(largest_eval/smallest_eval);\n    std::cout << \"       Condition number: \" << condition_number << \"\\n\";\n\n    deallocate_vector(&rhs_cplx);\n    deallocate_vector(&inter_cplx);\n  }\n\n  ///////////////////////////////////\n  // PERFORM SEQUENTIAL INVERSIONS //\n  ///////////////////////////////////\n\n  // truly desired tolerance.\n  double eps = 1e-10; \n\n  // tolerances\n  //double eps_1 = 1e-3;\n  //double eps_2 = 1e-14;\n\n  // bound\n  double eps_1 = eps/2;\n  double eps_2 = eps/(2*condition_number);\n\n  {\n    // Get a rhs b.\n    complex<double>* b;\n    b = allocate_vector<complex<double>>(wilson_volume);\n    gaussian_real(b, wilson_volume, generator, 1.0/inv_variance);\n\n    double bnorm = sqrt(norm2sq(b, wilson_volume));\n\n    // We want to solve M^dag M x = b.\n    // Define Y == M^dag, X == M\n    // Solve Y X x = b sequentially.\n    // First, define y == X x and solve Y y = b.\n    std::cout << \"\\nSolve Y y = b\\n\";\n    complex<double>* y;\n    y = allocate_vector<complex<double>>(wilson_volume);\n    zero_vector(y, wilson_volume);\n\n    invif = minv_vector_bicgstab(y, b, wilson_volume, max_iter, eps_1, square_wilson_dagger_gauged, &lapstr_gauged);\n    if (invif.success == true)\n    {\n      printf(\"  Algorithm %s took %d iterations to reach a tolerance of %.8e.\\n\", invif.name.c_str(), invif.iter, sqrt(invif.resSq)/bnorm);\n    }\n\n    // Next, solve M x = y\n    double ynorm = sqrt(norm2sq(y, wilson_volume));\n    std::cout << \"\\nSolve X x = y\\n\";\n    complex<double>* x;\n    x = allocate_vector<complex<double>>(wilson_volume);\n    zero_vector(x, wilson_volume);\n\n    invif = minv_vector_bicgstab(x, y, wilson_volume, max_iter, eps_2, square_wilson_gauged, &lapstr_gauged);\n    if (invif.success == true)\n    {\n      printf(\"  Algorithm %s took %d iterations to reach a tolerance of %.8e.\\n\", invif.name.c_str(), invif.iter, sqrt(invif.resSq)/ynorm);\n    }\n\n    // Do the verify.\n    complex<double>* tmp;\n    tmp = allocate_vector<complex<double>>(wilson_volume);\n    zero_vector(tmp, wilson_volume);\n\n    complex<double>* check;\n    check = allocate_vector<complex<double>>(wilson_volume);\n    zero_vector(check, wilson_volume);\n\n    // Apply M^dag M\n    square_wilson_gauged(tmp, x, &lapstr_gauged);\n    square_wilson_dagger_gauged(check, tmp, &lapstr_gauged);\n    double rel_res = sqrt(diffnorm2sq(check, b, wilson_volume))/bnorm;\n    printf(\"\\nThe normal op tolerance is %.8e.\\n\", rel_res);\n\n    // Check the equality.\n    printf(\"\\nThis should be below %.8e.\\n\", eps_1 + condition_number*eps_2);\n\n    deallocate_vector(&b);\n    deallocate_vector(&y);\n    deallocate_vector(&x);\n    deallocate_vector(&tmp);\n    deallocate_vector(&check);\n\n  }\n\n  //////////////\n  // CLEAN UP //\n  //////////////\n\n  // Free the lattice.\n  //delete[] lattice;\n\n  \n  deallocate_vector(&gauge_links);\n  return 0;\n}\n\n\n", "meta": {"hexsha": "705e6ca272387a945c442ce5fb4278dbbb7039c8", "size": 6216, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/n08_sequential_solve/sequential.cpp", "max_stars_repo_name": "weinbe2/quantum-linalg", "max_stars_repo_head_hexsha": "ce852dc459c8a5010f777f219c0dc6623ec918e0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/n08_sequential_solve/sequential.cpp", "max_issues_repo_name": "weinbe2/quantum-linalg", "max_issues_repo_head_hexsha": "ce852dc459c8a5010f777f219c0dc6623ec918e0", "max_issues_repo_licenses": ["MIT"], "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/n08_sequential_solve/sequential.cpp", "max_forks_repo_name": "weinbe2/quantum-linalg", "max_forks_repo_head_hexsha": "ce852dc459c8a5010f777f219c0dc6623ec918e0", "max_forks_repo_licenses": ["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.7416267943, "max_line_length": 139, "alphanum_fraction": 0.6578185328, "num_tokens": 1713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4541566480141732}}
{"text": "#pragma once\n\n#include <cmath>\n#include <numeric>\n#include <vector>\n#include <limits>\n#include <iomanip>\n#include <fstream>\n#include <iostream>\nusing namespace std;\n\n#include <eigen3/Eigen/Core>\n#include <eigen3/Eigen/Dense>\n#include <eigen3/Eigen/Sparse>\nusing namespace Eigen;\n\n#include <boost/version.hpp>\n#include <boost/limits.hpp>\n#include <boost/filesystem.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/numeric/conversion/bounds.hpp>\n\n#include <boost/config.hpp>\n#include <boost/program_options.hpp>\n#include <boost/program_options/parsers.hpp>\n#include <boost/program_options/detail/config_file.hpp>\n#include <boost/math/distributions/normal.hpp>\n#include <boost/algorithm/string.hpp>\nnamespace po = boost::program_options;\n\n#ifndef UTIL_H\n#define UTIL_H\n\nconst double Inf = numeric_limits<double>::infinity();\nconst double pi = boost::math::constants::pi<double>();\nconst double log_2 = boost::math::constants::ln_two<double>();\nconst double log_pi = log(boost::math::constants::pi<double>());\nconst double pi_180 = pi / 180.0;\n\ntypedef Eigen::SparseMatrix<double> SpMat; // Declares a column-major sparse matrix type of double\ntypedef Eigen::Triplet<double> Tri;\n\nclass Params {\npublic:\n    \n    Params( );\n    ~Params( );\n    Params(const string &params_file, const long seed_from_command_line);\n    bool check_input_params( ) const;\n    \n    friend ostream& operator<<(ostream& out, const Params& params);\n    \n    long seed;\n    bool testing;\n    bool diploid;\n    string datapath, mcmcpath, prevpath, gridpath, olderpath;\n    double qEffctHalfInterval, mEffctHalfInterval;\n    double mrateMuLowerBound, qrateMuLowerBound, mrateMuUpperBound, qrateMuUpperBound;\n    double mSeedsProposalS2, mSeedsProposalS2x, mSeedsProposalS2y;\n    double qSeedsProposalS2, qSeedsProposalS2x, qSeedsProposalS2y;\n    double qEffctProposalS2, mEffctProposalS2, mrateMuProposalS2, qrateMuProposalS2;\n    double momegaProposalS2, qomegaProposalS2;\n    double mnegBiProb, qnegBiProb;\n    double qVoronoiPr;\n    double min_omegam, max_omegam;\n    double min_omegaq, max_omegaq;\n    double temp;\n    double lowerBound, upperBound, genomeSize;\n    int numMCMCIter, numBurnIter, numThinIter;\n    int nDemes, nIndiv, mnegBiSize, qnegBiSize;\n    string distance;\n};\n\n\ndouble get_bootstrap_var(const MatrixXi &Sims, VectorXd cvec, const VectorXi &indiv2deme, int nb, int alpha, int beta);\ndouble poisln(const MatrixXd &expectedIBD, const MatrixXd &observedIBDCnt, const MatrixXd &ceffective, const MatrixXd &cMatrix);\nVectorXd split(const string &line);\ndouble mvgammaln(const double a, const int p);\ndouble max(double a, double b);\nMatrixXd pairwise_distance(const MatrixXd &X, const MatrixXd &Y);\nMatrixXd readMatrixXd(const string &filename);\ndouble trace_AxB(const MatrixXd &A, const MatrixXd &B);\nvoid getWeights(VectorXd &w, VectorXd &x);\ndouble median(vector<double> &v);\n\n\nbool dlmcell(const string &filename, const VectorXd &sizes, const vector<double> &array);\nvoid removeRow(MatrixXd &matrix, const int rowToRemove);\nvoid removeElem(VectorXd &vector, const int elemToRemove);\nvoid insertRow(MatrixXd &mat, const VectorXd &row);\nvoid insertElem(VectorXd &vec, const double &elem);\n\ndouble dnegbinln(const int k, const int size, const double prob);\ndouble dinvgamln(const double x, const double shape, const double scale);\ndouble dmvnormln(const VectorXd &x, const VectorXd &mu, const MatrixXd &sigma);\ndouble dtrnormln(const double x, const double mu, const double sigma2, const double bnd);\n\nVectorXd slice(const VectorXd &A, const VectorXi &I);\nMatrixXd slice(const MatrixXd &A, const VectorXi &R, const VectorXi &C);\n\nMatrixXd greatcirc_dist(const MatrixXd &X, const MatrixXd &Y);\nMatrixXd euclidean_dist(const MatrixXd &X, const MatrixXd &Y);\n\n#endif\n", "meta": {"hexsha": "3728ca3aba7949770a899d5e074f9cb8c63426db", "size": 3770, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/util.hpp", "max_stars_repo_name": "halasadi/eems2", "max_stars_repo_head_hexsha": "92c6b54cdd2cf30c0c363fa716487f4ace584fd3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2017-10-20T15:47:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T17:25:11.000Z", "max_issues_repo_path": "src/util.hpp", "max_issues_repo_name": "halasadi/eems2", "max_issues_repo_head_hexsha": "92c6b54cdd2cf30c0c363fa716487f4ace584fd3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2018-01-05T16:42:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-04T09:41:02.000Z", "max_forks_repo_path": "src/util.hpp", "max_forks_repo_name": "halasadi/eems2", "max_forks_repo_head_hexsha": "92c6b54cdd2cf30c0c363fa716487f4ace584fd3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-04-09T09:07:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-01T14:31:57.000Z", "avg_line_length": 35.9047619048, "max_line_length": 128, "alphanum_fraction": 0.7652519894, "num_tokens": 977, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859598, "lm_q2_score": 0.5926665999540697, "lm_q1q2_score": 0.4541566480141732}}
{"text": "#include <boost/test/unit_test.hpp>\n\n#include \"Core/ArrowUtilities.h\"\n#include \"../plotter/Matplotlib/Plot.h\"\n#include \"../learn/Learn.h\"\n#include \"../learn/SKLearn.h\"\n\nBOOST_AUTO_TEST_CASE(DoubleColumnNumpyRoundtrip)\n{\n    auto col = toColumn<std::optional<double>>({ 1.0, 2.0, std::nullopt, 3.0 });\n    auto nar = columnToNpArr(*col);\n    auto col2 = npArrayToColumn(nar, col->name());\n    BOOST_CHECK(col->Equals(*col2));\n}\n\nstruct RegressionFixture\n{\n    double coef = 2.0;\n    double intercept = 1.0;\n    double linearMap(double x) { return coef * x + intercept; };\n\n    std::vector<double> xsVector{ 1.0, 2.0, 3.0, 4.0, 5.0 };\n    std::vector<double> ysVector = transformToVector(xsVector, [this](double x) { return linearMap(x); });\n\n    std::vector<double> newSample{ 20.0 };\n\n    std::shared_ptr<arrow::Table> xs = tableFromVectors(xsVector);\n    std::shared_ptr<arrow::Column> ys = toColumn(ysVector);\n\n    double predictAt20(pybind11::object model)\n    {\n        auto predictedAt20 = toVector<double>(*sklearn::predict(model, *tableFromVectors(newSample)));\n        return predictedAt20.at(0);\n    }\n};\n\nBOOST_FIXTURE_TEST_CASE(LinearRegression, RegressionFixture)\n{\n    auto linReg = sklearn::newLinearRegression();\n    BOOST_CHECK_EQUAL((std::string)linReg.get_type().str(), \"<class 'sklearn.linear_model.base.LinearRegression'>\");\n    sklearn::fit(linReg, *xs, *ys);;\n\n    auto inferredCoef = linReg.attr(\"coef_\").cast<double>();\n    auto inferredIntercept = linReg.attr(\"intercept_\").cast<double>();\n    BOOST_CHECK_EQUAL(inferredCoef, coef);\n    BOOST_CHECK_EQUAL(inferredIntercept, intercept);\n\n    BOOST_CHECK_EQUAL(sklearn::score(linReg, *xs, *ys), 1.0);\n\n    auto predictedAt20 = predictAt20(linReg);\n    BOOST_CHECK_EQUAL(predictedAt20, linearMap(20));\n}\n\nBOOST_FIXTURE_TEST_CASE(LogisticRegression, RegressionFixture)\n{\n    // TODO: find a better example\n    // now just check that functions can be called to obtain whatever results\n    auto logReg = sklearn::newLogisticRegression(5.25);\n    BOOST_CHECK_EQUAL((std::string)logReg.get_type().str(), \"<class 'sklearn.linear_model.logistic.LogisticRegression'>\");\n    BOOST_CHECK_EQUAL(logReg.attr(\"C\").cast<double>(), 5.25);\n\n    sklearn::fit(logReg, *xs, *ys);\n    //BOOST_CHECK_EQUAL(sklearn::score(logReg, *xs, *ys), 1.0);\n    \n    // see what got inferred\n\n    auto predictedAt20 = predictAt20(logReg);\n    //BOOST_CHECK_EQUAL(predictedAt20, linearMap(20));\n\n}", "meta": {"hexsha": "93bee9ef76a649b0a68f9dfb05228ed53f50695a", "size": 2435, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "native_libs/test/LearnTests.cpp", "max_stars_repo_name": "mwu-tow/Dataframes", "max_stars_repo_head_hexsha": "fd82802fe9b490cee9ac7be9aee0f5cc2e1fba28", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-05-09T17:25:29.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-30T21:22:14.000Z", "max_issues_repo_path": "native_libs/test/LearnTests.cpp", "max_issues_repo_name": "mwu-tow/Dataframes", "max_issues_repo_head_hexsha": "fd82802fe9b490cee9ac7be9aee0f5cc2e1fba28", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 94.0, "max_issues_repo_issues_event_min_datetime": "2018-07-09T19:02:56.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-29T13:30:39.000Z", "max_forks_repo_path": "native_libs/test/LearnTests.cpp", "max_forks_repo_name": "mwu-tow/Dataframes", "max_forks_repo_head_hexsha": "fd82802fe9b490cee9ac7be9aee0f5cc2e1fba28", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-05-16T21:05:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-19T14:36:33.000Z", "avg_line_length": 34.7857142857, "max_line_length": 122, "alphanum_fraction": 0.6977412731, "num_tokens": 672, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.5926665999540697, "lm_q1q2_score": 0.4541566480141731}}
{"text": "#define BOOST_TEST_MODULE blas\n\n#include <boost/test/unit_test.hpp>\n#include <boost/test/test_case_template.hpp>\n#include <boost/mpl/list.hpp>\n\n\n#include <mla/vector/all.h++>\n\n#include <mla/operations/level1/asum.h++>\n\n\ntypedef boost::mpl::list<\n\tmla::vector::Dense<float>,\n\tmla::vector::Dense<double>,\n\tmla::vector::SparseCS<float>,\n\tmla::vector::SparseCS<double>\n> vector_type_list;\n\n\n\nBOOST_AUTO_TEST_SUITE(test_boost_level1)\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( blas_level1_test_asum_one_dense, VectorType, vector_type_list )\n{\n\tusing namespace mla;\n\n\tVectorType x(3);\n\tx.setValue(0, 1.0f);\n\tx.setValue(1, 1.0f);\n\tx.setValue(2, 1.0f);\n\n\ttypename VectorType::scalar_type value;\n\tvalue = asum(x);\n\n\tBOOST_CHECK_CLOSE( value, 3.0f, 1.0e-5 );\n}\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( blas_level1_test_asum_one_sparse, VectorType, vector_type_list )\n{\n\tusing namespace mla;\n\n\tVectorType x(5);\n\tx.setValue(0, 1.0f);\n\tx.setValue(2, 1.0f);\n\tx.setValue(4, 1.0f);\n\n\ttypename VectorType::scalar_type value;\n\tvalue = asum(x);\n\n\tBOOST_CHECK_CLOSE( value, 3.0f, 1.0e-5 );\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n\n", "meta": {"hexsha": "a134bfb1483fc87e1794fa24ec3a6a9e4832d231", "size": 1085, "ext": "c++", "lang": "C++", "max_stars_repo_path": "unit_tests/test_blas_level1_asum.c++", "max_stars_repo_name": "ruimaciel/mla", "max_stars_repo_head_hexsha": "b05f5913067af31a345cd2187de25871dbe31856", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "unit_tests/test_blas_level1_asum.c++", "max_issues_repo_name": "ruimaciel/mla", "max_issues_repo_head_hexsha": "b05f5913067af31a345cd2187de25871dbe31856", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unit_tests/test_blas_level1_asum.c++", "max_forks_repo_name": "ruimaciel/mla", "max_forks_repo_head_hexsha": "b05f5913067af31a345cd2187de25871dbe31856", "max_forks_repo_licenses": ["BSD-3-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.3898305085, "max_line_length": 95, "alphanum_fraction": 0.7391705069, "num_tokens": 327, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115012, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.45415664168777814}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n\n\nnamespace boltzmann {\n\n/**\n * @brief Barycentric interpolation formula\n *\n * @param wi\n * @param xi\n */\ntemplate <typename NUMERIC = double>\nclass LagrangePolynomial\n{\n public:\n  typedef NUMERIC numeric_t;\n  typedef Eigen::Matrix<numeric_t, -1, 1> vector_t;\n\n public:\n  /**\n   * @brief comput barycentric\n   *\n   * @param wi   weights from barycentric interpolation formula\n   * @param xi   abscissas\n   */\n  static void compute_weights(vector_t &wi, const vector_t &xi);\n  /**\n   *\n   *\n   * @param y    output\n   * @param x    evaluation points\n   * @param xi   abscissas\n   * @param yi   interpolation values\n   * @param wi   weights (obtained via compute weights)\n   */\n  static void evaluate(\n      vector_t &y, const vector_t &x, const vector_t &xi, const vector_t &yi, const vector_t &wi);\n};\n\n// --------------------------------------------------------------------------------\ntemplate <typename NUMERIC>\nvoid\nLagrangePolynomial<NUMERIC>::compute_weights(vector_t &wi, const vector_t &xi)\n{\n  const int N = xi.size();\n\n  assert(wi.size() == xi.size());\n\n  for (int i = 0; i < N; ++i) {\n    numeric_t v = 1;\n    for (int j = 0; j < N; ++j) {\n      if (j != i) v *= (xi[j] - xi[i]);\n    }\n    wi[i] = 1 / v;\n  }\n}\n\n// --------------------------------------------------------------------------------\ntemplate <typename NUMERIC>\nvoid\nLagrangePolynomial<NUMERIC>::evaluate(\n    vector_t &y, const vector_t &x, const vector_t &xi, const vector_t &yi, const vector_t &wi)\n{\n  const numeric_t tol(1e-15);\n\n  vector_t dist(xi.size());\n\n  // number of grid points\n  const int N = xi.size();\n\n  // number of evaluation nodes\n  const int n = x.size();\n  assert(y.size() == x.size());\n\n  // iterate over evaluation points in x(j)\n  for (int j = 0; j < n; ++j) {\n    // compute distance\n    bool done = false;\n    for (int k = 0; k < N; ++k) {\n      dist(k) = x(j) - xi(k);\n      if (std::abs(dist(k)) < tol) {\n        y(j) = yi(k);\n        done = true;\n        break;\n      }\n    }\n    if (done) continue;\n\n    // compute sum\n    double denom = 0;\n    double numer = 0;\n\n    for (int k = 0; k < N; ++k) {\n      double v = (wi[k] / dist[k]);\n      denom += v;\n      numer += v * yi[k];\n    }\n    y(j) = numer / denom;\n  }\n}\n\n}  // end namespace boltzmann\n", "meta": {"hexsha": "79be34f248f47d260986be6713301af5f0702140", "size": 2288, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "spectral/lagrange_polynomial.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/lagrange_polynomial.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/lagrange_polynomial.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": 21.7904761905, "max_line_length": 98, "alphanum_fraction": 0.5380244755, "num_tokens": 662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081925, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.45404564052148827}}
{"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\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include <iostream>\n#include <cmath>\n\n#include <boost/numeric/mtl/mtl.hpp>\n#include <boost/numeric/mtl/recursion/bit_masking.hpp>\n#include <boost/numeric/mtl/recursion/predefined_masks.hpp>\n#include <boost/numeric/mtl/operation/print.hpp>\n\nusing namespace std;  \n\ntemplate <typename Matrix>\nvoid print_matrix(Matrix& matrix)\n{ \n    typedef typename mtl::Collection<Matrix>::size_type   size_type;\n    using std::cout;\n    for (size_type i=0 ; i<num_rows(matrix); i++ ){\n\tfor(size_type j=0; j<num_cols(matrix);  j++ ){\n\t    cout.fill (' '); cout.width (8); cout.precision (5); cout.flags (ios_base::left);\n\t    cout << showpoint <<  matrix[i][j] <<\"  \";\n\t}\n\tcout << endl;\n    }\n}\n\n\ntemplate <typename Matrix>\nvoid test(Matrix& matrix, const char* name)\n{\n    typedef typename mtl::Collection<Matrix>::size_type   size_type;\n    matrix= 0;\n    {\n\tmtl::mat::inserter<Matrix> ins(matrix);\n\tfor (size_type i= 0; i < matrix.num_rows(); i++)\n\t    for (size_type j= 0; j < matrix.num_cols(); j++)\n\t\tif ((i + j) & 1)\n\t\t    ins(i, j) << i + 2*j;\n    }\n\n    std::cout << \"\\n\" << name << \"\\n\";\n    print_matrix(matrix);\n\n    mtl::mat::transposed_view<Matrix> trans(matrix);\n    std::cout << \"Transposed\" << \"\\n\";\n    print_matrix(trans);\n\n    std::cout << \"with <<\" << \"\\n\"\n\t      << trans << \"\\n\";\n\n    std::cout << \"with << and formatted\" << \"\\n\"\n\t      << with_format(trans, 7, 4) << \"\\n\";\n\n    Matrix square(5, 5);\n    square= matrix * trans;\n\n    std::cout << \"squared before:\\n\" << with_format(trans, 4, 2)\n\t      << \"squared in place:\\n\" << matrix * trans << \"\\n\";\n\n    // Comparison with FP!!!! :-! Make something better eventually\n    //MTL_THROW_IF((matrix * trans)[0][1] != 1.0, mtl::runtime_error(\"Wrong multiplicatin result!\"));\n}\n\n\nint main(int, char**)\n{\n    using namespace mtl;\n\n    dense2D<double>                                dr(5, 7);\n    dense2D<double, mat::parameters<col_major> > dc(5, 7);\n    morton_dense<double,  morton_mask>             md(5, 7);\n    morton_dense<double,  doppled_16_row_mask>     d16r(5, 7);\n    compressed2D<double>                           comp(5, 7);\n\n    test(dr, \"Dense row major\");\n    test(dc, \"Dense column major\");\n    test(md, \"Morton N-order\");\n    test(d16r, \"Hybrid 16 row-major\");\n    //test(comp, \"compressed2D\");\n\n    return 0;\n}\n\n\n\n\n\n", "meta": {"hexsha": "eb276783696c4fb8aa52d26ca77785b80874738c", "size": 2732, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/print_matrix_test.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/mtl/test/print_matrix_test.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/mtl/test/print_matrix_test.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 27.8775510204, "max_line_length": 101, "alphanum_fraction": 0.6079795022, "num_tokens": 780, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.45404563594675906}}
{"text": "#include <arrow/memory_pool.h>\n#include <arrow/table.h>\n#include <arrow/array.h>\n#include <arrow/compute/api_vector.h>\n\n#include <boost/assert.hpp>\n\n#include <iostream>\n#include <memory>\n#include <limits>\n#include <iterator>\n#include <algorithm>\n\n#include \"attribute_mapper.h\"\n#include \"arrow_utils.h\"\n#include \"arrow_convenience.h\"\n#include \"arrowcube.h\"\n\n/******************************************************************************/\n\nusing namespace std;\nusing namespace arrow;\n\npair<double, double>\ncol_bounds(const std::string &colname,\n           shared_ptr<Table> arrow)\n{\n  shared_ptr<ChunkedArray> col = arrow->GetColumnByName(colname);\n\n  double min_so_far = numeric_limits<double>::max(),\n      max_so_far = numeric_limits<double>::min();\n\n  arrow_foreach<DoubleType>(\n      col,\n      [&min_so_far,\n       &max_so_far](double v) {\n        min_so_far = std::min(min_so_far, v);\n        max_so_far = std::max(max_so_far, v);\n      });\n  \n  return make_pair(min_so_far, max_so_far);\n}\n\npair<double, double>\ncol_mean_stdev(\n    const std::string &colname,\n    shared_ptr<Table> arrow)\n{\n  shared_ptr<ChunkedArray> col = arrow->GetColumnByName(colname);\n\n  size_t n = 0;\n  double ex = 0.0, exx = 0.0;\n\n  arrow_foreach<DoubleType>(\n      col,\n      [&n, &ex, &exx](double v) {\n        // drop nans\n        if (v != v)\n          return;\n        ++n;\n        ex += v;\n        exx += v * v;\n      });\n  ex /= n;\n  exx /= n;\n  return make_pair(ex, sqrt(exx - ex * ex)); // this is numerically unstable, :shrug:\n}\n\nostream &operator<<(ostream &os, const std::pair<double, double> &v)\n{\n  return os << \"(\" << v.first << \",\" << v.second << \")\";\n}\n\ntemplate <typename T1, typename T2>\nvoid write_ppm(\n    size_t width, size_t height,\n    ostream &os,\n    const std::vector<T2> &vec,\n    T1 closure)\n{\n  os << \"P3\\n\" << width << \" \" << height << \"\\n255\\n\";\n  for (size_t y = 0; y < height; ++y) {\n    for (size_t x = 0; x < width; ++x) {\n      const T2 &v = vec[y * width + x];\n      int r, g, b;\n      std::tie(r, g, b) = closure(v);\n      os << r << \" \" << g << \" \" << b << endl;\n    }\n  }\n}\n\nstd::tuple<int, int, int> color(float u)\n{\n  if (u == 0) {\n    return make_tuple(0, 0, 0);\n  }\n  u *= 3;\n  if (u < 1) {\n    return make_tuple(int(u * 255), 0, 0);\n  }\n  if (u < 2) {\n    u -= 1;\n    return make_tuple(255, int(u * 255), 0);\n  }\n  u -= 2;\n  return make_tuple(255, 255, int(u * 255));\n}\n\ntemplate <typename T>\n// This should be done more carefully for large data.\nshared_ptr<Table>\nconvert_to_fixed(shared_ptr<Table> input,\n                 vector<string> columns,\n                 vector<T*> xforms\n                 )\n{\n  vector<shared_ptr<Field> > fields;\n  vector<shared_ptr<ChunkedArray> > arrays;\n  \n  for (size_t i = 0; i < columns.size(); ++i) {\n    string &c = columns[i];\n    fields.push_back(field(c, shared_ptr<DataType>(new UInt32Type), false));\n    // shared_ptr<Array> array;\n    shared_ptr<ChunkedArray> col = input->GetColumnByName(c);\n\n    vector<shared_ptr<Array>> array_vector;\n    auto chunks = col->chunks();\n    for (auto &chunk: chunks) {\n      NumericBuilder<UInt32Type> builder;\n      auto float_chunk = std::static_pointer_cast<DoubleArray>(chunk);\n      for (size_t j = 0; j < float_chunk->length(); ++j) {\n        int32_t v = xforms[i]->convert(float_chunk->Value(j));\n        OK_OR_DIE(builder.Append(v));\n      }\n      shared_ptr<Array> a;\n      OK_OR_DIE(builder.Finish(&a));\n      array_vector.push_back(a);\n    }\n    cerr << array_vector.size() << endl;\n    cerr << col->chunks().size() << endl;\n    shared_ptr<ChunkedArray> ca(new ChunkedArray(array_vector));\n    arrays.push_back(ca);\n    cerr << ca->length() << endl;\n  }\n\n  return Table::Make(\n      schema(fields),\n      arrays);\n}\n\nshared_ptr<Table> make_address_table(shared_ptr<Table> arrow)\n{\n  cerr << \"Bounds:\" << endl;\n  cerr << \"  pickup_latitude: \" << col_bounds(\"pickup_latitude\", arrow) << endl;\n  cerr << \"  pickup_longitude: \" << col_bounds(\"pickup_longitude\", arrow) << endl;\n  cerr << \"  dropoff_latitude: \" << col_bounds(\"dropoff_latitude\", arrow) << endl;\n  cerr << \"  dropoff_longitude: \" << col_bounds(\"dropoff_longitude\", arrow) << endl;\n  cerr << \"mean/stdev:\" << endl;\n  cerr << \"  pickup_latitude: \" << col_mean_stdev(\"pickup_latitude\", arrow) << endl;\n  cerr << \"  pickup_longitude: \" << col_mean_stdev(\"pickup_longitude\", arrow) << endl;\n  cerr << \"  dropoff_latitude: \" << col_mean_stdev(\"dropoff_latitude\", arrow) << endl;\n  cerr << \"  dropoff_longitude: \" << col_mean_stdev(\"dropoff_longitude\", arrow) << endl;\n\n  const size_t resolution = 256;\n  \n  // DoubleAttribute lat( 40.5,  41, resolution);\n  // DoubleAttribute lon(-74.25, -73.75, resolution);\n  CenterWidthAttribute lat(40.75, 0.25, resolution);\n  CenterWidthAttribute lon(-74, 0.25, resolution);\n\n  vector<CenterWidthAttribute*> xforms = {&lat, &lon};\n  shared_ptr<Table> addresses =\n      convert_to_fixed<CenterWidthAttribute>(\n          arrow,\n          { \"pickup_latitude\", \"pickup_longitude\" },\n          xforms);\n  \n  return addresses;\n}\n\nvoid test_with_nyc_pickup_data(std::string filename)\n{\n  shared_ptr<Table> arrow = read_feather_table(filename);\n\n  // cerr << \"Bounds:\" << endl;\n  // cerr << \"  pickup_latitude: \" << col_bounds(\"pickup_latitude\", arrow) << endl;\n  // cerr << \"  pickup_longitude: \" << col_bounds(\"pickup_longitude\", arrow) << endl;\n  // cerr << \"  dropoff_latitude: \" << col_bounds(\"dropoff_latitude\", arrow) << endl;\n  // cerr << \"  dropoff_longitude: \" << col_bounds(\"dropoff_longitude\", arrow) << endl;\n  // cerr << \"mean/stdev:\" << endl;\n  // cerr << \"  pickup_latitude: \" << col_mean_stdev(\"pickup_latitude\", arrow) << endl;\n  // cerr << \"  pickup_longitude: \" << col_mean_stdev(\"pickup_longitude\", arrow) << endl;\n  // cerr << \"  dropoff_latitude: \" << col_mean_stdev(\"dropoff_latitude\", arrow) << endl;\n  // cerr << \"  dropoff_longitude: \" << col_mean_stdev(\"dropoff_longitude\", arrow) << endl;\n\n  const size_t resolution = 256;\n  \n  // // DoubleAttribute lat( 40.5,  41, resolution);\n  // // DoubleAttribute lon(-74.25, -73.75, resolution);\n  // CenterWidthAttribute lat(40.75, 0.25, resolution);\n  // CenterWidthAttribute lon(-74, 0.25, resolution);\n\n  // vector<CenterWidthAttribute*> xforms = {&lat, &lon};\n  shared_ptr<Table> addresses = make_address_table(arrow);\n      // convert_to_fixed<CenterWidthAttribute>(\n      //     arrow,\n      //     { \"pickup_latitude\", \"pickup_longitude\" },\n      //     xforms);\n\n  // cerr << \"Hello ?\" << endl;\n  // arrow_foreach<Int32Type>(\n  //     addresses->GetColumnByName(\"pickup_longitude\"),\n  //     [](uint32_t v) {\n  //       cerr << v << endl;\n  //     });\n  // cerr << \"Hello ?\" << endl;\n  \n  vector<size_t> counts_2d(resolution * resolution);\n  size_t n = 0;\n  arrow_foreach<Int32Type>(\n      addresses->GetColumnByName(\"pickup_latitude\"),\n      addresses->GetColumnByName(\"pickup_longitude\"),\n      [&n, &counts_2d](uint32_t i_lat, uint32_t i_lon) {\n        ++n;\n        i_lat = resolution - 1 - i_lat;\n        counts_2d[i_lon + resolution * i_lat]++;\n      });\n  size_t mx = *std::max_element(counts_2d.begin(), counts_2d.end());\n  cerr << n << \" \" << mx << endl;\n\n  write_ppm(resolution, resolution,\n            cout,\n            counts_2d,\n            [&mx](size_t v) {\n              float u = log(v + 1) / log(mx + 1);\n              return color(u);\n            });\n}\n\nstruct CountPolicy\n{\n  int count;\n  CountPolicy(): count(0) {};\n  \n  inline void add(const RowIterator &row) {\n    ++count;\n  }\n};\n\n/******************************************************************************/\n\nvoid test_arrow_cube(std::string filename)\n{\n  shared_ptr<Table>\n      arrow = read_feather_table(filename),\n      addresses = make_address_table(arrow);\n      \n  // nc2::ArrowCube ac(addresses, { \"pickup_latitude\", \"pickup_longitude\" });\n  // CountPolicy policy;\n  // ac.range_query<size_t, CountPolicy>(policy, { make_pair(size_t(0), size_t(256)), make_pair(size_t(0), size_t(256)) });\n  // cerr << policy.count << endl;\n\n  // compute::SortOrder order = compute::SortOrder::Ascending;\n  compute::SortOptions options({\n      compute::SortKey(\"pickup_latitude\", compute::SortOrder::Ascending)\n    });\n  auto sorted_df = sort_table(addresses, &options);\n}\n\nvoid test_arrow_convenience()\n{\n  shared_ptr table = make_table(\n      {{ \"col1\", make_chunked_array<UInt32Type>({ 0, 0, 0, 1, 1, 1, 2, 2, 2 }) },\n       { \"col2\", make_chunked_array<UInt32Type>({ 0, 0, 1, 0, 2, 2, 1, 2, 2 }) },\n       { \"agg\",  make_chunked_array<DoubleType>({ 1, 1, 1, 1, 1, 1, 1, 1, 1 }) }\n      });\n\n  {\n    RowIterator itor({\n        ChunkedArrayIterator(table->GetColumnByName(\"col1\")),\n        ChunkedArrayIterator(table->GetColumnByName(\"col2\")),\n        ChunkedArrayIterator(table->GetColumnByName(\"agg\"))\n      });\n    \n    do {\n      for (size_t i = 0; i < 2; ++i) {\n        cerr << itor.cols_[i].value<UInt32Type>() << \" \";\n      }\n      cerr << \"agg: \" << itor.cols_[2].value<DoubleType>() << endl;\n    } while (!itor.next());\n  }\n  \n  table = CompressAggregation<UInt32Type, DoubleType>::call(\n      table, { \"col1\", \"col2\" }, { \"agg\" });\n\n  {\n    RowIterator itor({\n        ChunkedArrayIterator(table->GetColumnByName(\"col1\")),\n        ChunkedArrayIterator(table->GetColumnByName(\"col2\")),\n        ChunkedArrayIterator(table->GetColumnByName(\"agg\"))\n      });\n\n    do {\n      for (size_t i = 0; i < 2; ++i) {\n        cerr << itor.cols_[i].value<UInt32Type>() << \" \";\n      }\n      cerr << \"agg: \" << itor.cols_[2].value<DoubleType>() << endl;\n    } while (!itor.next());\n  }\n}\n\n\nint main(int argc, char **argv)\n{\n  const std::string filename = \"/Users/cscheid/data/nyc-tlc/feather/yellow_tripdata_2014-02.feather\";\n  // test_with_nyc_pickup_data(argv[1]);\n  // test_arrow_cube(filename);\n  test_arrow_convenience();\n}\n", "meta": {"hexsha": "ae6c67ceeb330a045dec8c5547c542855bdddde5", "size": 9765, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/test_arrow.cc", "max_stars_repo_name": "hdc-arizona/pothos", "max_stars_repo_head_hexsha": "5b75dd71ee2babd2860245bb4ffb1d489d5531be", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-01T05:09:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T05:09:56.000Z", "max_issues_repo_path": "src/test_arrow.cc", "max_issues_repo_name": "hdc-arizona/pothos", "max_issues_repo_head_hexsha": "5b75dd71ee2babd2860245bb4ffb1d489d5531be", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-03-01T08:11:17.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-01T08:11:17.000Z", "max_forks_repo_path": "src/test_arrow.cc", "max_forks_repo_name": "hdc-arizona/pothos", "max_forks_repo_head_hexsha": "5b75dd71ee2babd2860245bb4ffb1d489d5531be", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-08T09:06:54.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-08T09:06:54.000Z", "avg_line_length": 30.515625, "max_line_length": 123, "alphanum_fraction": 0.6001024066, "num_tokens": 2756, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.454045635946759}}
{"text": "#include <boost/test/unit_test.hpp>\n\n#include \"ssmkit/random/generator.hpp\"\n\n#include <thread>\n#include <array>\n#include <random>\n#include <algorithm>\n\nusing namespace ssmkit;\nusing namespace std;\n\nBOOST_AUTO_TEST_SUITE(generator_test);\n\n// thread task\nvoid sample(double *r){\n  uniform_real_distribution<double> dist;\n  *r = dist(ssmkit::random::Generator::get().getGenerator());\n}\n\nBOOST_AUTO_TEST_CASE(multithread) {\n  constexpr unsigned int n = 100;\n  // array to store samples\n  array<double, n> samples;\n  array<thread, n> thrd;\n  unsigned int repeat = 20;\n  \n  for (int i=0; i<repeat; i++){\n    auto sb = samples.begin();\n    generate_n(thrd.begin(), n, [&sb]() { return thread(sample, sb++); });\n    for_each(thrd.begin(), thrd.end(), [](auto &t) { t.join(); });\n\n    // check if there is any replicate\n    bool ch =\n        all_of(samples.begin(), samples.end(), [&samples](const auto &sb) {\n          return count_if(samples.begin(), samples.end(), [&sb](const auto &s) {\n                   return s == sb;\n                 }) == 1 ? true : false;\n        });\n    BOOST_CHECK(ch);\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "8111dfb40579b68b7cdce644c95e8dd317f6a62c", "size": 1127, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/random/generator.cpp", "max_stars_repo_name": "vahid-bastani/ssmpack", "max_stars_repo_head_hexsha": "68aed98b1c661a7d1c9e5610656de57f6a967532", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2016-07-08T09:18:49.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-10T06:46:55.000Z", "max_issues_repo_path": "test/random/generator.cpp", "max_issues_repo_name": "vahidbas/ssmkit", "max_issues_repo_head_hexsha": "68aed98b1c661a7d1c9e5610656de57f6a967532", "max_issues_repo_licenses": ["MIT"], "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/random/generator.cpp", "max_forks_repo_name": "vahidbas/ssmkit", "max_forks_repo_head_hexsha": "68aed98b1c661a7d1c9e5610656de57f6a967532", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-01-03T17:46:08.000Z", "max_forks_repo_forks_event_max_datetime": "2018-01-03T17:46:08.000Z", "avg_line_length": 25.0444444444, "max_line_length": 80, "alphanum_fraction": 0.6291038154, "num_tokens": 286, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081925, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.454045635946759}}
{"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#include <boost/simd/ieee/include/functions/frexp.hpp>\n#include <boost/simd/sdk/simd/native.hpp>\n#include <boost/simd/sdk/simd/io.hpp>\n#include <boost/simd/include/constants/one.hpp>\n#include <boost/simd/include/constants/half.hpp>\n#include <boost/simd/include/constants/limitexponent.hpp>\n#include <boost/simd/include/constants/mindenormal.hpp>\n#include <boost/simd/include/constants/minexponent.hpp>\n#include <boost/simd/include/constants/halfeps.hpp>\n#include <boost/simd/include/constants/nbmantissabits.hpp>\n#include <boost/simd/include/constants/smallestposval.hpp>\n#include <boost/simd/include/constants/one.hpp>\n#include <boost/simd/include/constants/two.hpp>\n#include <boost/simd/include/constants/four.hpp>\n#include <boost/simd/include/functions/divides.hpp>\n#include <boost/simd/include/functions/ldexp.hpp>\n#include <boost/dispatch/functor/meta/call.hpp>\n#include <boost/dispatch/meta/as_integer.hpp>\n#include <boost/fusion/include/vector_tie.hpp>\n#include <boost/simd/sdk/config.hpp>\n#include <nt2/sdk/unit/module.hpp>\n#include <nt2/sdk/unit/tests/relation.hpp>\n#include <nt2/sdk/unit/tests/ulp.hpp>\n#include <nt2/sdk/unit/tests/type_expr.hpp>\n\nNT2_TEST_CASE_TPL( frexp0, BOOST_SIMD_SIMD_REAL_TYPES)\n{\n  using boost::simd::frexp;\n  using boost::simd::ldexp;\n  using boost::simd::tag::frexp_;\n  using boost::simd::native;\n\n  typedef native<T,BOOST_SIMD_DEFAULT_EXTENSION>            vT;\n  typedef typename boost::dispatch::meta::as_integer<vT,signed>::type viT;\n\n  {\n    viT e;\n    vT  m;\n    vT  a = boost::simd::Valmax<vT>();\n    frexp(a, m, e);\n    NT2_TEST_ULP_EQUAL(m, boost::simd::One<vT>()-boost::simd::Halfeps<vT>(), 1);\n    NT2_TEST_EQUAL(e, boost::simd::Limitexponent<vT>());\n    NT2_TEST_EQUAL(ldexp(m,e),a);\n  }\n#ifndef BOOST_SIMD_NO_DENORMALS\n  {\n    viT e;\n    vT  m;\n    vT  a = boost::simd::Mindenormal<vT>();\n    frexp(a, m, e);\n    NT2_TEST_ULP_EQUAL(m, boost::simd::Half<vT>(), 1);\n    NT2_TEST_EQUAL(e, boost::simd::Minexponent<vT>()-boost::simd::Nbmantissabits<vT>()+boost::simd::One<viT>());\n    NT2_TEST_EQUAL(ldexp(m,e),a);\n }\n\n  {\n    viT e;\n    vT  m;\n    vT  a = boost::simd::Smallestposval<vT>()/boost::simd::Two<vT>();\n    frexp(a, m, e);\n    NT2_TEST_ULP_EQUAL(m, boost::simd::Half<vT>(), 1);\n    NT2_TEST_EQUAL(e, boost::simd::Minexponent<vT>());\n    NT2_TEST_EQUAL(ldexp(m,e),a);\n }\n\n  {\n    viT e;\n    vT  m;\n    vT  a = boost::simd::Smallestposval<vT>()/boost::simd::Four<vT>();\n    frexp(a, m, e);\n    NT2_TEST_ULP_EQUAL(m, boost::simd::Half<vT>(), 1);\n    NT2_TEST_EQUAL(e, boost::simd::Minexponent<vT>()-boost::simd::One<viT>());\n    NT2_TEST_EQUAL(ldexp(m,e),a);\n }\n#endif\n}\n\nNT2_TEST_CASE_TPL( frexp, BOOST_SIMD_SIMD_REAL_TYPES)\n{\n  using boost::simd::frexp;\n  using boost::simd::tag::frexp_;\n  using boost::simd::native;\n\n  typedef native<T,BOOST_SIMD_DEFAULT_EXTENSION>            vT;\n  typedef typename boost::dispatch::meta::as_integer<vT,signed>::type viT;\n\n  NT2_TEST_TYPE_IS( (typename boost::dispatch::meta::call<frexp_(vT)>::type)\n                  , (std::pair<vT,viT>)\n                  );\n\n  {\n    viT e;\n    vT  m;\n\n    frexp(boost::simd::One<vT>(), m, e);\n    NT2_TEST_EQUAL(m, boost::simd::Half<vT>());\n    NT2_TEST_EQUAL(e, boost::simd::One<viT>());\n  }\n\n  {\n    viT e;\n    vT  m;\n\n    m = frexp(boost::simd::One<vT>(), e);\n    NT2_TEST_EQUAL(m, boost::simd::Half<vT>());\n    NT2_TEST_EQUAL(e, boost::simd::One<viT>());\n  }\n\n  {\n    viT e;\n    vT  m;\n\n    boost::fusion::vector_tie(m,e) = frexp(boost::simd::One<vT>());\n    NT2_TEST_EQUAL(m, boost::simd::Half<vT>());\n    NT2_TEST_EQUAL(e, boost::simd::One<viT>());\n  }\n\n  {\n    std::pair<vT,viT> p;\n\n    p = frexp(boost::simd::One<vT>());\n    NT2_TEST_EQUAL(p.first  , boost::simd::Half<vT>());\n    NT2_TEST_EQUAL(p.second , boost::simd::One<viT>());\n  }\n}\n", "meta": {"hexsha": "e53a71e4befcffff24452ba4d7275cabcbf8f8f7", "size": 4283, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/base/unit/ieee/simd/frexp.cpp", "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/unit/ieee/simd/frexp.cpp", "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/unit/ieee/simd/frexp.cpp", "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.9626865672, "max_line_length": 112, "alphanum_fraction": 0.6306327341, "num_tokens": 1273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.454045635946759}}
{"text": "///////////////////////////////////////////////////////////////\n//  Copyright 2011 John Maddock. Distributed under the Boost\n//  Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_\n\n#ifdef _MSC_VER\n#  define _SCL_SECURE_NO_WARNINGS\n#endif\n\n#define BOOST_MATH_OVERFLOW_ERROR_POLICY ignore_error\n\n#if !defined(TEST_MPF_50) && !defined(TEST_BACKEND) && !defined(TEST_CPP_DEC_FLOAT) && !defined(TEST_MPFR_50)\n#  define TEST_MPF_50\n#  define TEST_MPFR_50\n#  define TEST_CPP_DEC_FLOAT\n\n#ifdef _MSC_VER\n#pragma message(\"CAUTION!!: No backend type specified so testing everything.... this will take some time!!\")\n#endif\n#ifdef __GNUC__\n#pragma warning \"CAUTION!!: No backend type specified so testing everything.... this will take some time!!\"\n#endif\n\n#endif\n\n#if defined(TEST_MPF_50)\n#include <boost/multiprecision/gmp.hpp>\n#endif\n#if defined(TEST_MPFR_50)\n#include <boost/multiprecision/mpfr.hpp>\n#endif\n#ifdef TEST_BACKEND\n#include <boost/multiprecision/concepts/mp_number_archetypes.hpp>\n#endif\n#ifdef TEST_CPP_DEC_FLOAT\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#endif\n\n#include \"table_type.hpp\"\n#define TEST_UDT\n\n#include <boost/math/special_functions/ellint_2.hpp>\n#include \"libs/math/test/test_ellint_2.hpp\"\n\nvoid expected_results()\n{\n   //\n   // Define the max and mean errors expected for\n   // various compilers and platforms.\n   //\n   add_expected_result(\n      \".*\",                          // compiler\n      \".*\",                          // stdlib\n      \".*\",                          // platform\n      \".*\",                          // test type(s)\n      \".*\",                          // test data group\n      \".*\", 300, 200);               // test function\n   //\n   // Finish off by printing out the compiler/stdlib/platform names,\n   // we do this to make it easier to mark up expected error rates.\n   //\n   std::cout << \"Tests run with \" << BOOST_COMPILER << \", \"\n      << BOOST_STDLIB << \", \" << BOOST_PLATFORM << std::endl;\n}\n\n\nBOOST_AUTO_TEST_CASE( test_main )\n{\n   using namespace boost::multiprecision;\n   expected_results();\n   //\n   // Test at:\n   // 18 decimal digits: tests 80-bit long double approximations\n   // 30 decimal digits: tests 128-bit long double approximations\n   // 35 decimal digits: tests arbitrary precision code\n   //\n#ifdef TEST_MPF_50\n   test_spots(number<gmp_float<18> >(), \"number<gmp_float<18> >\");\n   test_spots(number<gmp_float<30> >(), \"number<gmp_float<30> >\");\n   test_spots(number<gmp_float<35> >(), \"number<gmp_float<35> >\");\n   // there should be at least one test with expression templates off:\n   test_spots(number<gmp_float<35>, et_off>(), \"number<gmp_float<35>, et_off>\");\n#endif\n#ifdef TEST_MPFR_50\n   test_spots(number<mpfr_float_backend<18> >(), \"number<mpfr_float_backend<18> >\");\n   test_spots(number<mpfr_float_backend<30> >(), \"number<mpfr_float_backend<30> >\");\n   test_spots(number<mpfr_float_backend<35> >(), \"number<mpfr_float_backend<35> >\");\n#endif\n#ifdef TEST_CPP_DEC_FLOAT\n   test_spots(number<cpp_dec_float<18> >(), \"number<cpp_dec_float<18> >\");\n   test_spots(number<cpp_dec_float<30> >(), \"number<cpp_dec_float<30> >\");\n   test_spots(number<cpp_dec_float<35, long long, std::allocator<void> > >(), \"number<cpp_dec_float<35, long long, std::allocator<void> > >\");\n#endif\n}\n\n", "meta": {"hexsha": "4f9cd2ae7da74351398ab081dec5d13cedf5e35a", "size": 3321, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/multiprecision/test/math/test_ellint_2.cpp", "max_stars_repo_name": "smart-make/boost", "max_stars_repo_head_hexsha": "46509a094f8a844eefd5bb8a0030b739a04d79e1", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-12-15T19:55:56.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-15T19:55:56.000Z", "max_issues_repo_path": "libs/multiprecision/test/math/test_ellint_2.cpp", "max_issues_repo_name": "smart-make/boost", "max_issues_repo_head_hexsha": "46509a094f8a844eefd5bb8a0030b739a04d79e1", "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/multiprecision/test/math/test_ellint_2.cpp", "max_forks_repo_name": "smart-make/boost", "max_forks_repo_head_hexsha": "46509a094f8a844eefd5bb8a0030b739a04d79e1", "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.59375, "max_line_length": 142, "alphanum_fraction": 0.6672688949, "num_tokens": 856, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.685949467848392, "lm_q2_score": 0.6619228625116081, "lm_q1q2_score": 0.4540456352965219}}
{"text": "// Copyright \u00a9 2013 the Search Authors under the MIT license. See AUTHORS for the list of authors.\n#pragma once\n\n#include <vector>\n#include <boost/optional.hpp>\n\nvoid fatal(const char*, ...);\n\ntemplate <class Ops, class Elm> class BinHeap {\npublic:\n\n\t// push pushes a new element into the heap in\n\t// O(lg n) time.\n\tvoid push(Elm e) {\n\t\theap.push_back(e);\n\t\tOps::setind(e, heap.size() - 1);\n\t\tpullup(heap.size() - 1);\n\t}\n\n\t// pop pops the front element from the heap and\n\t// returns it in O(lg n) time.\n\tboost::optional<Elm> pop() {\n\t\tif (heap.size() == 0)\n\t\t\treturn boost::optional<Elm>();\n\n\t\tElm res = heap[0];\n\t\tif (heap.size() > 1) {\n\t\t\theap[0] = heap.back();\n\t\t\theap.pop_back();\n\t\t\tOps::setind(heap[0], 0);\n\t\t\tpushdown(0);\n\t\t} else {\n\t\t\theap.pop_back();\n\t\t}\n\t\tOps::setind(res, -1);\n\n\t\treturn boost::optional<Elm>(res);\n\t}\n\n\t// front returns the front element of the heap if it is\n\t// not empty and an empty option if the heap is empty.\n\t// O(1) time.\n\tboost::optional<Elm> front() {\n\t\tif (heap.size() == 0)\n\t\t\treturn boost::optional<Elm>();\n\t\treturn boost::optional<Elm>(heap[0]);\n\t}\n\n\t// update updates the element in the heap at the given\n\t// index.  This should be called whenever the priority\n\t// of an element changes.  O(lg n) time.\n\tvoid update(long i) {\n\t\tif (i < 0 || (unsigned int) i >= heap.size())\n\t\t\tfatal(\"Updating an invalid heap index: %ld, size=%lu\\n\", i, heap.size());\n\t\ti = pullup(i);\n\t\tpushdown(i);\n\t}\n\n\t// pushupdate either pushes the element or updates it's\n\t// position in the queue, given the element and i, it's\n\t// index value.  Note that the index value must be tracked\n\t// properly, i.e., i < 0 means that the element is not in\n\t// the priority queue and i  >= 0 means that the element\n\t// is at the given index. O(lg n) time.\n\tvoid pushupdate(Elm e, long i) {\n\t\tif (i  < 0)\n\t\t\tpush(e);\n\t\telse\n\t\t\tupdate(i);\n\t}\n\n\t// empty returns true if the heap is empty and\n\t// false otherwise.\n\tbool empty() const { return heap.empty(); }\n\n\t// clear clears all of the elements from the heap\n\t// leaving it empty.\n\tvoid clear() { heap.clear(); }\n\n \t// size returns the number of entries in the heap.\n\tlong size() const { return heap.size(); }\n\n\t// at returns the element of the heap at the given\n\t// index.\n\tElm at(long i) {\n\t\tassert (i < size());\n\t\treturn heap[i];\n\t}\n\n\t// data returns the raw vector used to back the\n\t// heap.  If you mess with this then you must\n\t// reinit the heap afterwards to ensure that the\n\t// heap property still holds.\n\tstd::vector<Elm> &data() { return heap; }\n\n\t// reinit reinitialize the heap property in O(n) time.\n\tvoid reinit() {\n\t\tif (heap.size() <= 0)\n\t\t\treturn;\n\n\t\tfor (unsigned int i = 0; i < heap.size(); i++)\n\t\t\tOps::setind(heap[i], i);\n\n\t\tfor (long i = heap.size() / 2; ; i--) {\n\t\t\tpushdown(i);\n\t\t\tif (i == 0)\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\t// append appends the vector of elements to the heap\n\t// and ensures that the heap property holds after.\n\tvoid append(const std::vector<Elm> &elms) {\n\t\theap.insert(heap.end(), elms.begin(), elms.end());\n\t\treinit();\n\t}\n\n\tlong pushdown(long i) {\n\t\tlong l = left(i), r = right(i);\n\n\t\tlong sml = i;\n\t\tif (l < size() && Ops::pred(heap[l], heap[i]))\n\t\t\tsml = l;\n\t\tif (r < size() && Ops::pred(heap[r], heap[sml]))\n\t\t\tsml = r;\n\n\t\tif (sml != i) {\n\t\t\tswap(sml, i);\n\t\t\treturn pushdown(sml);\n\t\t}\n\n\t\treturn i;\n\t}\n\nprivate:\n\tfriend bool binheap_push_test();\n\tfriend bool binheap_pop_test();\n\n\tlong parent(long i) { return (i - 1) / 2; }\n\n\tlong left(long i) { return 2 * i + 1; }\n\n\tlong right(long i) { return 2 * i + 2; }\n\n\tlong pullup(long i) {\n\t\tif (i == 0)\n\t\t\treturn i;\n\t\tlong p = parent(i);\n\t\tif (Ops::pred(heap[i], heap[p])) {\n\t\t\tswap(i, p);\n\t\t\treturn pullup(p);\n\t\t}\n\t\treturn i;\n\t}\n\n\tvoid swap(long i, long j) {\n\t\tOps::setind(heap[i], j);\n\t\tOps::setind(heap[j], i);\n\t\tElm tmp = heap[i];\n\t\theap[i] = heap[j];\n\t\theap[j] = tmp;\n\t}\n\n\tstd::vector<Elm> heap;\n};\n", "meta": {"hexsha": "a5ece2672641861f584a22e84def240bc91ee234", "size": 3837, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "structs/binheap.hpp", "max_stars_repo_name": "skiesel/search", "max_stars_repo_head_hexsha": "b9bb14810a85d6a486d603b3d81444c9d0b246b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28.0, "max_stars_repo_stars_event_min_datetime": "2015-02-10T04:06:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T11:51:38.000Z", "max_issues_repo_path": "structs/binheap.hpp", "max_issues_repo_name": "skiesel/search", "max_issues_repo_head_hexsha": "b9bb14810a85d6a486d603b3d81444c9d0b246b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2016-11-03T12:03:28.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-13T17:35:40.000Z", "max_forks_repo_path": "structs/binheap.hpp", "max_forks_repo_name": "skiesel/search", "max_forks_repo_head_hexsha": "b9bb14810a85d6a486d603b3d81444c9d0b246b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-10-22T20:22:45.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-30T20:11:31.000Z", "avg_line_length": 23.1144578313, "max_line_length": 98, "alphanum_fraction": 0.6135001303, "num_tokens": 1211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.4540456316971481}}
{"text": "#define BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n\n#include \"DRegularLanguage.hpp\"\n#include <memory>\n\nusing namespace FACore;\nusing namespace std;\n\ntemplate<unsigned int ALPHABET_SIZE>\nDRegularLanguage<ALPHABET_SIZE> EmptyLanguage() {\n    typedef DRegularLanguage<ALPHABET_SIZE> Language;\n    typedef typename Language::Machine Machine;\n    \n    shared_ptr<const Machine> automaton( new Machine() );\n    // By default, it will be the implementation of the empty language\n    \n    return Language(automaton, 0);\n}\n\ntemplate<unsigned int ALPHABET_SIZE>\nDRegularLanguage<ALPHABET_SIZE> FullLanguage() {\n    typedef DRegularLanguage<ALPHABET_SIZE> Language;\n    typedef typename Language::Machine Machine;\n    \n    Machine* machine = new Machine();\n    \n    // By default, it will be the implementation of the empty language\n    auto state = machine->AddState(true);\n    \n    for(unsigned int c = 0; c < Language::AlphabetSize; c++) {\n        machine->SetArc(state, c, state);\n    }\n    \n    return Language(machine, state);\n}\n\ntemplate<class LanguageType>\nbool InLanguage(LanguageType &language, std::vector<typename LanguageType::StateId> word) {\n    return language.contains(word.begin(), word.end());\n}\n\ntemplate<class LanguageType>\nbool NotInLanguage(LanguageType &language, std::vector<typename LanguageType::StateId> word) {\n    return !language.contains(word.begin(), word.end());\n}\n\nBOOST_AUTO_TEST_SUITE( TestDRegularLanguage );\n\nBOOST_AUTO_TEST_CASE( empty_language_alphabet2 )\n{\n    DRegularLanguage<2> emptyLanguage = EmptyLanguage<2>(); // This is the default\n    \n    BOOST_CHECK( NotInLanguage(emptyLanguage, {}) );\n    BOOST_CHECK( NotInLanguage(emptyLanguage, {0}) );\n    BOOST_CHECK( NotInLanguage(emptyLanguage, {1}) );\n    BOOST_CHECK( NotInLanguage(emptyLanguage, {1,0,1}) );\n}\n\n\nBOOST_AUTO_TEST_CASE( empty_language_alphabet3 )\n{\n    DRegularLanguage<3> emptyLanguage = EmptyLanguage<3>(); // This is the default\n    \n    BOOST_CHECK( NotInLanguage(emptyLanguage, {}) );\n    BOOST_CHECK( NotInLanguage(emptyLanguage, {0}) );\n    BOOST_CHECK( NotInLanguage(emptyLanguage, {1}) );\n    BOOST_CHECK( NotInLanguage(emptyLanguage, {1,0,2}) );\n}\n\nBOOST_AUTO_TEST_CASE( full_language )\n{\n    DRegularLanguage<2> emptyLanguage = FullLanguage<2>(); // This is the default\n    \n    BOOST_CHECK( InLanguage(emptyLanguage, {}) );\n    BOOST_CHECK( InLanguage(emptyLanguage, {0}) );\n    BOOST_CHECK( InLanguage(emptyLanguage, {1}) );\n    BOOST_CHECK( InLanguage(emptyLanguage, {1,0,1}) );\n}\n\nBOOST_AUTO_TEST_CASE( thue_morse )\n{\n    // The thue morse machine accepts a bit string iff it has an odd number of ones\n    DAutomaton<2> *thueMorseMachine = new DAutomaton<2>();\n    auto evenState = thueMorseMachine->AddState(false);\n    auto oddState = thueMorseMachine->AddState(true);\n    \n    thueMorseMachine->SetArc(evenState, 0, evenState);\n    thueMorseMachine->SetArc(evenState, 1, oddState);\n    thueMorseMachine->SetArc(oddState, 0, oddState);\n    thueMorseMachine->SetArc(oddState, 1, evenState);\n    \n    DRegularLanguage<2> thueMorseSequence(thueMorseMachine, evenState);\n    \n    // Test using the normal as well as integer \"contains\" function\n    BOOST_CHECK( !thueMorseSequence.contains(0) );\n    BOOST_CHECK( NotInLanguage(thueMorseSequence, {} ));\n    BOOST_CHECK( NotInLanguage(thueMorseSequence, {0} ));\n    BOOST_CHECK( NotInLanguage(thueMorseSequence, {0,0} ));\n    \n    BOOST_CHECK( !thueMorseSequence.contains(3) );\n    BOOST_CHECK( NotInLanguage(thueMorseSequence, {1,1} ));\n    BOOST_CHECK( NotInLanguage(thueMorseSequence, {0,1,1} ));\n    \n    BOOST_CHECK( !thueMorseSequence.contains(5) );\n    BOOST_CHECK( NotInLanguage(thueMorseSequence, {1,0,1} ));\n    \n    \n    BOOST_CHECK( thueMorseSequence.contains(1) );\n    BOOST_CHECK( InLanguage(thueMorseSequence, {1}) );\n    BOOST_CHECK( InLanguage(thueMorseSequence, {0,1}) );\n    \n    BOOST_CHECK( thueMorseSequence.contains(2) );\n    BOOST_CHECK( InLanguage(thueMorseSequence, {1,0}) );\n    BOOST_CHECK( InLanguage(thueMorseSequence, {0,1,0}) );\n    \n    BOOST_CHECK( thueMorseSequence.contains(4) );\n    BOOST_CHECK( InLanguage(thueMorseSequence, {1,0,0}) );\n}\n\nBOOST_AUTO_TEST_SUITE_END();", "meta": {"hexsha": "5573e413790801c8b537c13ac0733d4407264699", "size": 4181, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/TestDRegularLanguage.cpp", "max_stars_repo_name": "4cad/facore", "max_stars_repo_head_hexsha": "9af1dcce9a26531120031b88ba71486fd7403ccd", "max_stars_repo_licenses": ["MIT"], "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/TestDRegularLanguage.cpp", "max_issues_repo_name": "4cad/facore", "max_issues_repo_head_hexsha": "9af1dcce9a26531120031b88ba71486fd7403ccd", "max_issues_repo_licenses": ["MIT"], "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/TestDRegularLanguage.cpp", "max_forks_repo_name": "4cad/facore", "max_forks_repo_head_hexsha": "9af1dcce9a26531120031b88ba71486fd7403ccd", "max_forks_repo_licenses": ["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.5537190083, "max_line_length": 94, "alphanum_fraction": 0.7172925138, "num_tokens": 1099, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494421679929, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.4540456274475372}}
{"text": "//\n//                              libieeep1788\n//\n//   An implementation of the preliminary IEEE P1788 standard for\n//   interval arithmetic\n//\n//\n//   Copyright 2013 - 2015\n//\n//   Marco Nehmeier (nehmeier@informatik.uni-wuerzburg.de)\n//   Department of Computer Science,\n//   University of Wuerzburg, Germany\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//   UnF<double>::less required by applicable law or agreed to in writing, software\n//   distributed under the License is distributed on an \"AS IS\" BASIS,\n//   WITHOUT WARRANTIES OR CONDITIONS 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#define BOOST_TEST_MODULE \"Flavor: IO [p1788/flavor/infsup/setbased/mpfr_bin_ieee754_flavor]\"\n#include \"test/util/boost_test_wrapper.hpp\"\n\n#include \"p1788/exception/exception.hpp\"\n#include \"p1788/decoration/decoration.hpp\"\n#include \"p1788/flavor/infsup/setbased/mpfr_bin_ieee754_flavor.hpp\"\n\n#include \"test/util/mpfr_bin_ieee754_flavor_io_test_util.hpp\"\n\n#include <boost/test/output_test_stream.hpp>\n\n#include <limits>\n#include <sstream>\n\ntemplate<typename T>\nusing F = p1788::flavor::infsup::setbased::mpfr_bin_ieee754_flavor<T>;\n\ntemplate<typename T>\nusing REP = typename F<T>::representation;\n\ntemplate<typename T>\nusing REP_DEC = typename F<T>::representation_dec;\n\ntypedef p1788::decoration::decoration DEC;\n\nconst double INF_D = std::numeric_limits<double>::infinity();\nconst double MAX_D = std::numeric_limits<double>::max();\n\n\nBOOST_AUTO_TEST_CASE(minimal_empty_output_test)\n{\n    boost::test_tools::output_test_stream output;\n\n    F<double>::operator_interval_to_text(output, F<double>::empty());\n    BOOST_CHECK( output.is_equal( \"[empty]\" ) );\n\n\n    output << p1788::io::upper_case;\n    F<double>::operator_interval_to_text(output, F<double>::empty());\n    BOOST_CHECK( output.is_equal( \"[EMPTY]\" ) );\n\n    output << p1788::io::hex;\n    output << p1788::io::lower_case;\n    output << p1788::io::string_width(12);\n    F<double>::operator_interval_to_text(output, F<double>::empty());\n    BOOST_CHECK( output.is_equal( \"[  empty   ]\" ) );\n\n    output << p1788::io::no_punctuation;\n    output << p1788::io::upper_case;\n    F<double>::operator_interval_to_text(output, F<double>::empty());\n    BOOST_CHECK( output.is_equal( \"   EMPTY    \" ) );\n\n    output << p1788::io::string_width(11);\n    F<double>::operator_interval_to_text(output, F<double>::empty());\n    BOOST_CHECK( output.is_equal( \"   EMPTY   \" ) );\n\n    output << p1788::io::decimal;\n    output << p1788::io::punctuation;\n    output << p1788::io::lower_case;\n    F<double>::operator_interval_to_text(output, F<double>::empty());\n    BOOST_CHECK( output.is_equal( \"[  empty  ]\" ) );\n\n    output << p1788::io::dec_numeric;\n    output << p1788::io::lower_case;\n    output << p1788::io::string_width(0);\n    output << p1788::io::special_no_bounds;\n    F<double>::operator_interval_to_text(output, F<double>::empty());\n    BOOST_CHECK( output.is_equal( \"[ ]\" ) );\n\n    output << p1788::io::hex;\n    output << p1788::io::upper_case;\n    F<double>::operator_interval_to_text(output, F<double>::empty());\n    BOOST_CHECK( output.is_equal( \"[ ]\" ) );\n\n    output << p1788::io::lower_case;\n    output << p1788::io::string_width(9);\n    F<double>::operator_interval_to_text(output, F<double>::empty());\n    BOOST_CHECK( output.is_equal( \"[       ]\" ) );\n\n    output << p1788::io::no_punctuation;\n    output << p1788::io::upper_case;\n    F<double>::operator_interval_to_text(output, F<double>::empty());\n    BOOST_CHECK( output.is_equal( \"  EMPTY  \" ) );\n\n    output << p1788::io::decimal;\n    output << p1788::io::lower_case;\n    output << p1788::io::string_width(0);\n    output << p1788::io::special_bounds;\n    output << p1788::io::punctuation;\n    F<double>::operator_interval_to_text(output, F<double>::empty());\n    BOOST_CHECK( output.is_equal( \"[inf,-inf]\" ) );\n\n    output << p1788::io::dec_alpha;\n    output << p1788::io::upper_case;\n    F<double>::operator_interval_to_text(output, F<double>::empty());\n    BOOST_CHECK( output.is_equal( \"[INF,-INF]\" ) );\n\n    output << p1788::io::hex;\n    output << p1788::io::lower_case;\n    output << p1788::io::string_width(9);\n    F<double>::operator_interval_to_text(output, F<double>::empty());\n    BOOST_CHECK( output.is_equal( \"[inf,-inf]\" ) );\n\n    output << p1788::io::string_width(15);\n    F<double>::operator_interval_to_text(output, F<double>::empty());\n    BOOST_CHECK( output.is_equal( \"[  inf,   -inf]\" ) );\n\n    output << p1788::io::string_width(16);\n    F<double>::operator_interval_to_text(output, F<double>::empty());\n    BOOST_CHECK( output.is_equal( \"[   inf,   -inf]\" ) );\n\n    output << p1788::io::decimal;\n    output << p1788::io::string_width(17);\n    output << p1788::io::upper_case;\n    F<double>::operator_interval_to_text(output, F<double>::empty());\n    BOOST_CHECK( output.is_equal( \"[   INF,    -INF]\" ) );\n\n    output << p1788::io::string_width(18);\n    output << p1788::io::lower_case;\n    F<double>::operator_interval_to_text(output, F<double>::empty());\n    BOOST_CHECK( output.is_equal( \"[    inf,    -inf]\" ) );\n\n    output << p1788::io::no_punctuation;\n    output << p1788::io::upper_case;\n    F<double>::operator_interval_to_text(output, F<double>::empty());\n    BOOST_CHECK( output.is_equal( \"     INF      -INF\" ) );\n\n    output << p1788::io::hex;\n    output << p1788::io::upper_case;\n    output << p1788::io::string_width(0);\n    F<double>::operator_interval_to_text(output, F<double>::empty());\n    BOOST_CHECK( output.is_equal( \"INF -INF\" ) );\n\n    output << p1788::io::special_text;\n    output << p1788::io::punctuation;\n    output << p1788::io::width(10);\n    F<double>::operator_interval_to_text(output, F<double>::empty());\n    BOOST_CHECK( output.is_equal( \"[        EMPTY        ]\" ) );\n\n    output << p1788::io::special_bounds;\n    F<double>::operator_interval_to_text(output, F<double>::empty());\n    BOOST_CHECK( output.is_equal( \"[       INF,      -INF]\" ) );\n\n    output << p1788::io::string_width(23);\n    F<double>::operator_interval_to_text(output, F<double>::empty());\n    BOOST_CHECK( output.is_equal( \"[       INF,      -INF]\" ) );\n\n    output << p1788::io::string_width(25);\n    F<double>::operator_interval_to_text(output, F<double>::empty());\n    BOOST_CHECK( output.is_equal( \"[        INF,       -INF]\" ) );\n\n    output << p1788::io::special_no_bounds;\n    F<double>::operator_interval_to_text(output, F<double>::empty());\n    BOOST_CHECK( output.is_equal( \"[                       ]\" ) );\n\n    output << p1788::io::string_width(0);\n    F<double>::operator_interval_to_text(output, F<double>::empty());\n    BOOST_CHECK( output.is_equal( \"[                     ]\" ) );\n\n    output << p1788::io::special_bounds;\n    output << p1788::io::precision(27);\n    output << p1788::io::lower_case;\n    F<double>::operator_interval_to_text(output, F<double>::empty());\n    BOOST_CHECK( output.is_equal( \"[       inf,      -inf]\" ) );\n}\n\n\n\nBOOST_AUTO_TEST_CASE(minimal_empty_dec_output_test)\n{\n    boost::test_tools::output_test_stream output;\n\n    F<double>::operator_interval_to_text(output, F<double>::empty_dec());\n    BOOST_CHECK( output.is_equal( \"[empty]\" ) );\n\n    output << p1788::io::upper_case;\n    F<double>::operator_interval_to_text(output, F<double>::empty_dec());\n    BOOST_CHECK( output.is_equal( \"[EMPTY]\" ) );\n\n    output << p1788::io::hex;\n    output << p1788::io::lower_case;\n    output << p1788::io::string_width(12);\n    F<double>::operator_interval_to_text(output, F<double>::empty_dec());\n    BOOST_CHECK( output.is_equal( \"[  empty   ]\" ) );\n\n    output << p1788::io::no_punctuation;\n    output << p1788::io::upper_case;\n    F<double>::operator_interval_to_text(output, F<double>::empty_dec());\n    BOOST_CHECK( output.is_equal( \"   EMPTY    \" ) );\n\n    output << p1788::io::string_width(11);\n    F<double>::operator_interval_to_text(output, F<double>::empty_dec());\n    BOOST_CHECK( output.is_equal( \"   EMPTY   \" ) );\n\n    output << p1788::io::decimal;\n    output << p1788::io::punctuation;\n    output << p1788::io::lower_case;\n    F<double>::operator_interval_to_text(output, F<double>::empty_dec());\n    BOOST_CHECK( output.is_equal( \"[  empty  ]\" ) );\n\n    output << p1788::io::lower_case;\n    output << p1788::io::string_width(0);\n    output << p1788::io::special_no_bounds;\n    F<double>::operator_interval_to_text(output, F<double>::empty_dec());\n    BOOST_CHECK( output.is_equal( \"[ ]\" ) );\n\n    output << p1788::io::dec_numeric;\n    output << p1788::io::hex;\n    output << p1788::io::upper_case;\n    F<double>::operator_interval_to_text(output, F<double>::empty_dec());\n    BOOST_CHECK( output.is_equal( \"[ ]\" ) );\n\n    output << p1788::io::lower_case;\n    output << p1788::io::string_width(9);\n    F<double>::operator_interval_to_text(output, F<double>::empty_dec());\n    BOOST_CHECK( output.is_equal( \"[       ]\" ) );\n\n    output << p1788::io::no_punctuation;\n    output << p1788::io::upper_case;\n    F<double>::operator_interval_to_text(output, F<double>::empty_dec());\n    BOOST_CHECK( output.is_equal( \"  EMPTY  \" ) );\n\n    output << p1788::io::decimal;\n    output << p1788::io::lower_case;\n    output << p1788::io::string_width(0);\n    output << p1788::io::special_bounds;\n    output << p1788::io::punctuation;\n    F<double>::operator_interval_to_text(output, F<double>::empty_dec());\n    BOOST_CHECK( output.is_equal( \"[inf,-inf]\" ) );\n\n    output << p1788::io::dec_alpha;\n    output << p1788::io::hex;\n    output << p1788::io::upper_case;\n    F<double>::operator_interval_to_text(output, F<double>::empty_dec());\n    BOOST_CHECK( output.is_equal( \"[INF,-INF]\" ) );\n\n    output << p1788::io::lower_case;\n    output << p1788::io::string_width(9);\n    F<double>::operator_interval_to_text(output, F<double>::empty_dec());\n    BOOST_CHECK( output.is_equal( \"[inf,-inf]\" ) );\n\n    output << p1788::io::string_width(15);\n    F<double>::operator_interval_to_text(output, F<double>::empty_dec());\n    BOOST_CHECK( output.is_equal( \"[  inf,   -inf]\" ) );\n\n    output << p1788::io::string_width(16);\n    F<double>::operator_interval_to_text(output, F<double>::empty_dec());\n    BOOST_CHECK( output.is_equal( \"[   inf,   -inf]\" ) );\n\n    output << p1788::io::decimal;\n    output << p1788::io::string_width(17);\n    output << p1788::io::upper_case;\n    F<double>::operator_interval_to_text(output, F<double>::empty_dec());\n    BOOST_CHECK( output.is_equal( \"[   INF,    -INF]\" ) );\n\n    output << p1788::io::hex;\n    output << p1788::io::string_width(18);\n    output << p1788::io::lower_case;\n    F<double>::operator_interval_to_text(output, F<double>::empty_dec());\n    BOOST_CHECK( output.is_equal( \"[    inf,    -inf]\" ) );\n\n    output << p1788::io::no_punctuation;\n    output << p1788::io::upper_case;\n    F<double>::operator_interval_to_text(output, F<double>::empty_dec());\n    BOOST_CHECK( output.is_equal( \"     INF      -INF\" ) );\n\n    output << p1788::io::decimal;\n    output << p1788::io::lower_case;\n    output << p1788::io::string_width(0);\n    F<double>::operator_interval_to_text(output, F<double>::empty_dec());\n    BOOST_CHECK( output.is_equal( \"inf -inf\" ) );\n\n    output << p1788::io::hex;\n    output << p1788::io::special_text;\n    output << p1788::io::punctuation;\n    F<double>::operator_interval_to_text(output, F<double>::empty_dec());\n    BOOST_CHECK( output.is_equal( \"[empty]\" ) );\n\n    output << p1788::io::inf_sup_form;\n    output << p1788::io::width(10);\n    F<double>::operator_interval_to_text(output, F<double>::empty_dec());\n    BOOST_CHECK( output.is_equal( \"[        empty        ]\" ) );\n\n    output << p1788::io::special_bounds;\n    F<double>::operator_interval_to_text(output, F<double>::empty_dec());\n    BOOST_CHECK( output.is_equal( \"[       inf,      -inf]\" ) );\n\n    output << p1788::io::string_width(23);\n    F<double>::operator_interval_to_text(output, F<double>::empty_dec());\n    BOOST_CHECK( output.is_equal( \"[       inf,      -inf]\" ) );\n\n    output << p1788::io::string_width(25);\n    F<double>::operator_interval_to_text(output, F<double>::empty_dec());\n    BOOST_CHECK( output.is_equal( \"[        inf,       -inf]\" ) );\n\n    output << p1788::io::special_no_bounds;\n    F<double>::operator_interval_to_text(output, F<double>::empty_dec());\n    BOOST_CHECK( output.is_equal( \"[                       ]\" ) );\n\n    output << p1788::io::string_width(0);\n    F<double>::operator_interval_to_text(output, F<double>::empty_dec());\n    BOOST_CHECK( output.is_equal( \"[                     ]\" ) );\n\n    output << p1788::io::special_bounds;\n    output << p1788::io::precision(27);\n    output << p1788::io::upper_case;\n    F<double>::operator_interval_to_text(output, F<double>::empty_dec());\n    BOOST_CHECK( output.is_equal( \"[       INF,      -INF]\" ) );\n}\n\n\nBOOST_AUTO_TEST_CASE(minimal_entire_output_test)\n{\n    boost::test_tools::output_test_stream output;\n\n    F<double>::operator_interval_to_text(output, F<double>::entire() );\n    BOOST_CHECK( output.is_equal( \"[entire]\" ) );\n\n    output << p1788::io::upper_case;\n    F<double>::operator_interval_to_text(output, F<double>::entire() );\n    BOOST_CHECK( output.is_equal( \"[ENTIRE]\" ) );\n\n    output << p1788::io::lower_case;\n    output << p1788::io::string_width(12);\n    F<double>::operator_interval_to_text(output, F<double>::entire() );\n    BOOST_CHECK( output.is_equal( \"[  entire  ]\" ) );\n\n    output << p1788::io::no_punctuation;\n    output << p1788::io::upper_case;\n    F<double>::operator_interval_to_text(output, F<double>::entire() );\n    BOOST_CHECK( output.is_equal( \"   ENTIRE   \" ) );\n\n    output << p1788::io::hex;\n    output << p1788::io::string_width(11);\n    F<double>::operator_interval_to_text(output, F<double>::entire() );\n    BOOST_CHECK( output.is_equal( \"  ENTIRE   \" ) );\n\n    output << p1788::io::punctuation;\n    output << p1788::io::lower_case;\n    F<double>::operator_interval_to_text(output, F<double>::entire() );\n    BOOST_CHECK( output.is_equal( \"[ entire  ]\" ) );\n\n    output << p1788::io::decimal;\n    output << p1788::io::lower_case;\n    output << p1788::io::string_width(0);\n    output << p1788::io::special_no_bounds;\n    F<double>::operator_interval_to_text(output, F<double>::entire() );\n    BOOST_CHECK( output.is_equal( \"[,]\" ) );\n\n    output << p1788::io::dec_numeric;\n    output << p1788::io::hex;\n    output << p1788::io::upper_case;\n    F<double>::operator_interval_to_text(output, F<double>::entire() );\n    BOOST_CHECK( output.is_equal( \"[,]\" ) );\n\n    output << p1788::io::decimal;\n    output << p1788::io::lower_case;\n    output << p1788::io::string_width(9);\n    F<double>::operator_interval_to_text(output, F<double>::entire() );\n    BOOST_CHECK( output.is_equal( \"[   ,   ]\" ) );\n\n    output << p1788::io::no_punctuation;\n    output << p1788::io::upper_case;\n    F<double>::operator_interval_to_text(output, F<double>::entire() );\n    BOOST_CHECK( output.is_equal( \" ENTIRE  \" ) );\n\n    output << p1788::io::hex;\n    output << p1788::io::lower_case;\n    output << p1788::io::string_width(0);\n    output << p1788::io::special_bounds;\n    output << p1788::io::punctuation;\n    F<double>::operator_interval_to_text(output, F<double>::entire() );\n    BOOST_CHECK( output.is_equal( \"[-inf,inf]\" ) );\n\n    output << p1788::io::upper_case;\n    F<double>::operator_interval_to_text(output, F<double>::entire() );\n    BOOST_CHECK( output.is_equal( \"[-INF,INF]\" ) );\n\n    output << p1788::io::lower_case;\n    output << p1788::io::string_width(6);\n    F<double>::operator_interval_to_text(output, F<double>::entire() );\n    BOOST_CHECK( output.is_equal( \"[-inf,inf]\" ) );\n\n    output << p1788::io::dec_alpha;\n    output << p1788::io::decimal;\n    output << p1788::io::string_width(15);\n    F<double>::operator_interval_to_text(output, F<double>::entire() );\n    BOOST_CHECK( output.is_equal( \"[  -inf,   inf]\" ) );\n\n    output << p1788::io::string_width(16);\n    output << p1788::io::upper_case;\n    F<double>::operator_interval_to_text(output, F<double>::entire() );\n    BOOST_CHECK( output.is_equal( \"[   -INF,   INF]\" ) );\n\n    output << p1788::io::hex;\n    output << p1788::io::string_width(17);\n    F<double>::operator_interval_to_text(output, F<double>::entire() );\n    BOOST_CHECK( output.is_equal( \"[   -INF,    INF]\" ) );\n\n    output << p1788::io::string_width(18);\n    output << p1788::io::lower_case;\n    F<double>::operator_interval_to_text(output, F<double>::entire() );\n    BOOST_CHECK( output.is_equal( \"[    -inf,    inf]\" ) );\n\n    output << p1788::io::decimal;\n    output << p1788::io::no_punctuation;\n    output << p1788::io::upper_case;\n    F<double>::operator_interval_to_text(output, F<double>::entire() );\n    BOOST_CHECK( output.is_equal( \"     -INF      INF\" ) );\n\n    output << p1788::io::string_width(0);\n    F<double>::operator_interval_to_text(output, F<double>::entire() );\n    BOOST_CHECK( output.is_equal( \"-INF INF\" ) );\n\n    output << p1788::io::special_text;\n    output << p1788::io::punctuation;\n    output << p1788::io::inf_sup_form;\n    output << p1788::io::width(10);\n    F<double>::operator_interval_to_text(output, F<double>::entire());\n    BOOST_CHECK( output.is_equal( \"[        ENTIRE       ]\" ) );\n\n    output << p1788::io::special_bounds;\n    F<double>::operator_interval_to_text(output, F<double>::entire());\n    BOOST_CHECK( output.is_equal( \"[      -INF,       INF]\" ) );\n\n    output << p1788::io::string_width(23);\n    F<double>::operator_interval_to_text(output, F<double>::entire());\n    BOOST_CHECK( output.is_equal( \"[      -INF,       INF]\" ) );\n\n    output << p1788::io::string_width(25);\n    F<double>::operator_interval_to_text(output, F<double>::entire());\n    BOOST_CHECK( output.is_equal( \"[       -INF,        INF]\" ) );\n\n    output << p1788::io::special_no_bounds;\n    F<double>::operator_interval_to_text(output, F<double>::entire());\n    BOOST_CHECK( output.is_equal( \"[           ,           ]\" ) );\n\n    output << p1788::io::string_width(0);\n    F<double>::operator_interval_to_text(output, F<double>::entire());\n    BOOST_CHECK( output.is_equal( \"[          ,          ]\" ) );\n\n    output << p1788::io::special_bounds;\n    output << p1788::io::precision(27);\n    output << p1788::io::upper_case;\n    F<double>::operator_interval_to_text(output, F<double>::entire());\n    BOOST_CHECK( output.is_equal( \"[      -INF,       INF]\" ) );\n}\n\nBOOST_AUTO_TEST_CASE(minimal_entire_dec_output_test)\n{\n    boost::test_tools::output_test_stream output;\n\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(-INF_D,INF_D), DEC::trv) );\n    BOOST_CHECK( output.is_equal( \"[entire]_trv\" ) );\n\n    output << p1788::io::upper_case;\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(-INF_D,INF_D), DEC::dac) );\n    BOOST_CHECK( output.is_equal( \"[ENTIRE]_DAC\" ) );\n\n    output << p1788::io::hex;\n    output << p1788::io::lower_case;\n    output << p1788::io::string_width(13);\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(-INF_D,INF_D), DEC::trv) );\n    BOOST_CHECK( output.is_equal( \"[entire ]_trv\" ) );\n\n    output << p1788::io::no_punctuation;\n    output << p1788::io::upper_case;\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(-INF_D,INF_D), DEC::def) );\n    BOOST_CHECK( output.is_equal( \" ENTIRE   DEF\" ) );\n\n    output << p1788::io::decimal;\n    output << p1788::io::string_width(11);\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(-INF_D,INF_D), DEC::dac) );\n    BOOST_CHECK( output.is_equal( \"ENTIRE  DAC\" ) );\n\n    output << p1788::io::hex;\n    output << p1788::io::punctuation;\n    output << p1788::io::lower_case;\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(-INF_D,INF_D), DEC::trv) );\n    BOOST_CHECK( output.is_equal( \"[entire]_trv\" ) );\n\n    output << p1788::io::dec_numeric;\n    output << p1788::io::decimal;\n    output << p1788::io::lower_case;\n    output << p1788::io::string_width(0);\n    output << p1788::io::special_no_bounds;\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(-INF_D,INF_D), DEC::def) );\n    BOOST_CHECK( output.is_equal( \"[,]_8\" ) );\n\n    output << p1788::io::upper_case;\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(-INF_D,INF_D), DEC::trv) );\n    BOOST_CHECK( output.is_equal( \"[,]_4\" ) );\n\n    output << p1788::io::lower_case;\n    output << p1788::io::string_width(9);\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(-INF_D,INF_D), DEC::def) );\n    BOOST_CHECK( output.is_equal( \"[  ,  ]_8\" ) );\n\n    output << p1788::io::hex;\n    output << p1788::io::no_punctuation;\n    output << p1788::io::upper_case;\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(-INF_D,INF_D), DEC::dac) );\n    BOOST_CHECK( output.is_equal( \"ENTIRE 12\" ) );\n\n    output << p1788::io::dec_alpha;\n    output << p1788::io::decimal;\n    output << p1788::io::lower_case;\n    output << p1788::io::string_width(0);\n    output << p1788::io::special_bounds;\n    output << p1788::io::punctuation;\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(-INF_D,INF_D), DEC::trv) );\n    BOOST_CHECK( output.is_equal( \"[-inf,inf]_trv\" ) );\n\n    output << p1788::io::upper_case;\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(-INF_D,INF_D), DEC::dac) );\n    BOOST_CHECK( output.is_equal( \"[-INF,INF]_DAC\" ) );\n\n    output << p1788::io::hex;\n    output << p1788::io::lower_case;\n    output << p1788::io::string_width(6);\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(-INF_D,INF_D), DEC::trv) );\n    BOOST_CHECK( output.is_equal( \"[-inf,inf]_trv\" ) );\n\n    output << p1788::io::string_width(15);\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(-INF_D,INF_D), DEC::def) );\n    BOOST_CHECK( output.is_equal( \"[-inf, inf]_def\" ) );\n\n    output << p1788::io::decimal;\n    output << p1788::io::string_width(16);\n    output << p1788::io::upper_case;\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(-INF_D,INF_D), DEC::dac) );\n    BOOST_CHECK( output.is_equal( \"[ -INF, INF]_DAC\" ) );\n\n    output << p1788::io::string_width(17);\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(-INF_D,INF_D), DEC::trv) );\n    BOOST_CHECK( output.is_equal( \"[ -INF,  INF]_TRV\" ) );\n\n    output << p1788::io::hex;\n    output << p1788::io::string_width(18);\n    output << p1788::io::lower_case;\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(-INF_D,INF_D), DEC::def) );\n    BOOST_CHECK( output.is_equal( \"[  -inf,  inf]_def\" ) );\n\n    output << p1788::io::decimal;\n    output << p1788::io::no_punctuation;\n    output << p1788::io::upper_case;\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(-INF_D,INF_D), DEC::trv) );\n    BOOST_CHECK( output.is_equal( \"   -INF    INF TRV\" ) );\n\n    output << p1788::io::string_width(0);\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(-INF_D,INF_D), DEC::dac) );\n    BOOST_CHECK( output.is_equal( \"-INF INF DAC\" ) );\n\n    output << p1788::io::lower_case;\n    output << p1788::io::special_text;\n    output << p1788::io::punctuation;\n    output << p1788::io::inf_sup_form;\n    output << p1788::io::width(10);\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(-INF_D,INF_D), DEC::trv) );\n    BOOST_CHECK( output.is_equal( \"[        entire       ]_trv\" ) );\n\n    output << p1788::io::special_bounds;\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(-INF_D,INF_D), DEC::def) );\n    BOOST_CHECK( output.is_equal( \"[      -inf,       inf]_def\" ) );\n\n    output << p1788::io::string_width(27);\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(-INF_D,INF_D), DEC::dac) );\n    BOOST_CHECK( output.is_equal( \"[      -inf,       inf]_dac\" ) );\n\n    output << p1788::io::string_width(29);\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(-INF_D,INF_D), DEC::trv) );\n    BOOST_CHECK( output.is_equal( \"[       -inf,        inf]_trv\" ) );\n\n    output << p1788::io::special_no_bounds;\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(-INF_D,INF_D), DEC::def) );\n    BOOST_CHECK( output.is_equal( \"[           ,           ]_def\" ) );\n\n    output << p1788::io::string_width(0);\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(-INF_D,INF_D), DEC::dac) );\n    BOOST_CHECK( output.is_equal( \"[          ,          ]_dac\" ) );\n\n    output << p1788::io::special_bounds;\n    output << p1788::io::precision(27);\n    output << p1788::io::upper_case;\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(-INF_D,INF_D), DEC::trv) );\n    BOOST_CHECK( output.is_equal( \"[      -INF,       INF]_TRV\" ) );\n}\n\n\nBOOST_AUTO_TEST_CASE(minimal_nai_output_test)\n{\n    boost::test_tools::output_test_stream output;\n\n\n    F<double>::operator_interval_to_text(output, F<double>::nai());\n    BOOST_CHECK( output.is_equal( \"[nai]\" ) );\n\n    output << p1788::io::hex;\n    output << p1788::io::upper_case;\n    F<double>::operator_interval_to_text(output, F<double>::nai());\n    BOOST_CHECK( output.is_equal( \"[NAI]\" ) );\n\n    output << p1788::io::decimal;\n    output << p1788::io::lower_case;\n    output << p1788::io::string_width(12);\n    F<double>::operator_interval_to_text(output, F<double>::nai());\n    BOOST_CHECK( output.is_equal( \"[   nai    ]\" ) );\n\n    output << p1788::io::dec_numeric;\n    output << p1788::io::no_punctuation;\n    output << p1788::io::upper_case;\n    output << p1788::io::hex;\n    F<double>::operator_interval_to_text(output, F<double>::nai());\n    BOOST_CHECK( output.is_equal( \"    NAI     \" ) );\n\n    output << p1788::io::string_width(11);\n    output << p1788::io::decimal;\n    F<double>::operator_interval_to_text(output, F<double>::nai());\n    BOOST_CHECK( output.is_equal( \"    NAI    \" ) );\n\n    output << p1788::io::dec_alpha;\n    output << p1788::io::punctuation;\n    output << p1788::io::lower_case;\n    F<double>::operator_interval_to_text(output, F<double>::nai());\n    BOOST_CHECK( output.is_equal( \"[   nai   ]\" ) );\n\n    output << p1788::io::upper_case;\n    output << p1788::io::special_text;\n    output << p1788::io::no_punctuation;\n    output << p1788::io::inf_sup_form;\n    output << p1788::io::punctuation;\n    output << p1788::io::width(10);\n    F<double>::operator_interval_to_text(output, F<double>::nai() );\n    BOOST_CHECK( output.is_equal( \"[         NAI         ]\" ) );\n\n    output << p1788::io::special_bounds;\n    F<double>::operator_interval_to_text(output, F<double>::nai() );\n    BOOST_CHECK( output.is_equal( \"[         NAI         ]\" ) );\n\n    output << p1788::io::string_width(23);\n    F<double>::operator_interval_to_text(output, F<double>::nai() );\n    BOOST_CHECK( output.is_equal( \"[         NAI         ]\" ) );\n\n    output << p1788::io::string_width(25);\n    F<double>::operator_interval_to_text(output, F<double>::nai() );\n    BOOST_CHECK( output.is_equal( \"[          NAI          ]\" ) );\n\n    output << p1788::io::special_no_bounds;\n    F<double>::operator_interval_to_text(output, F<double>::nai() );\n    BOOST_CHECK( output.is_equal( \"[          NAI          ]\" ) );\n\n    output << p1788::io::string_width(0);\n    F<double>::operator_interval_to_text(output, F<double>::nai() );\n    BOOST_CHECK( output.is_equal( \"[         NAI         ]\" ) );\n\n    output << p1788::io::special_bounds;\n    output << p1788::io::precision(27);\n    output << p1788::io::lower_case;\n    F<double>::operator_interval_to_text(output, F<double>::nai() );\n    BOOST_CHECK( output.is_equal( \"[         nai         ]\" ) );\n}\n\n\n\nBOOST_AUTO_TEST_CASE(minimal_bare_interval_output_test)\n{\n    boost::test_tools::output_test_stream output;\n\n    F<double>::operator_interval_to_text(output, REP<double>(0.1,0.1) );\n    BOOST_CHECK( output.is_equal( \"[0.1,0.100001]\" ) );\n\n    output << p1788::io::upper_case;\n    F<double>::operator_interval_to_text(output, REP<double>(-0.1,0.1) );\n    BOOST_CHECK( output.is_equal( \"[-0.100001,0.100001]\" ) );\n\n    output << p1788::io::lower_case;\n    output << p1788::io::string_width(22);\n    F<double>::operator_interval_to_text(output, REP<double>(-0.1,0.1) );\n    BOOST_CHECK( output.is_equal( \"[ -0.100001, 0.100001]\" ) );\n\n    output << p1788::io::no_punctuation;\n    output << p1788::io::upper_case;\n    F<double>::operator_interval_to_text(output, REP<double>(-0.1,0.1) );\n    BOOST_CHECK( output.is_equal( \"  -0.100001   0.100001\" ) );\n\n    output << p1788::io::hex;\n    output << p1788::io::string_width(0);\n    F<double>::operator_interval_to_text(output, REP<double>(-0.1,1.3) );\n    BOOST_CHECK( output.is_equal( \"-0X1.999999999999AP-4 0X1.4CCCCCCCCCCCDP+0\" ) );\n\n    output << p1788::io::punctuation;\n    output << p1788::io::lower_case;\n    output << p1788::io::precision(5);\n    output << p1788::io::width(15);\n    F<double>::operator_interval_to_text(output, REP<double>(-0.1,1.3) );\n    BOOST_CHECK( output.is_equal( \"[  -0x1.9999ap-4,   0x1.4cccdp+0]\" ) );\n\n    output << p1788::io::string_width(35);\n    output << p1788::io::special_no_bounds;\n    F<double>::operator_interval_to_text(output, REP<double>(0.1,1.3) );\n    BOOST_CHECK( output.is_equal( \"[    0x1.99999p-4,    0x1.4cccdp+0]\" ) );\n\n    output << p1788::io::string_width(0);\n    output << p1788::io::precision(20);\n    F<double>::operator_interval_to_text(output, REP<double>(0.1,1.3) );\n    BOOST_CHECK( output.is_equal( \"[0x1.999999999999a0000000p-4,0x1.4cccccccccccd0000000p+0]\" ) );\n\n    output << p1788::io::decimal;\n    output << p1788::io::precision(0);\n    output << p1788::io::width(10);\n    F<double>::operator_interval_to_text(output, REP<double>(0.1,0.1) );\n    BOOST_CHECK( output.is_equal( \"[  0.100000,  0.100001]\" ) );\n\n    output << p1788::io::upper_case;\n    F<double>::operator_interval_to_text(output, REP<double>(-0.1,0.1) );\n    BOOST_CHECK( output.is_equal( \"[ -0.100001,  0.100001]\" ) );\n\n    output << p1788::io::lower_case;\n    output << p1788::io::string_width(25);\n    output << p1788::io::precision(7);\n    F<double>::operator_interval_to_text(output, REP<double>(0.1,0.1) );\n    BOOST_CHECK( output.is_equal( \"[  0.1000000,  0.1000001]\" ) );\n\n    output << p1788::io::decimal_scientific;\n    output << p1788::io::string_width(0);\n    output << p1788::io::upper_case;\n    F<double>::operator_interval_to_text(output, REP<double>(0.1,0.1) );\n    BOOST_CHECK( output.is_equal( \"[       0.1, 0.1000001]\" ) );\n\n    output << p1788::io::scientific;\n    F<double>::operator_interval_to_text(output, REP<double>(0.1,1.3) );\n    BOOST_CHECK( output.is_equal( \"[1.0000000E-01,1.3000001E+00]\" ) );\n\n    output << p1788::io::lower_case;\n    F<double>::operator_interval_to_text(output, REP<double>(-INF_D,0.1) );\n    BOOST_CHECK( output.is_equal( \"[      -inf,1.0000001e-01]\" ) );\n\n    output << p1788::io::decimal_scientific;\n    output << p1788::io::upper_case;\n    F<double>::operator_interval_to_text(output, REP<double>(0.1,INF_D) );\n    BOOST_CHECK( output.is_equal( \"[       0.1,       INF]\" ) );\n\n    output << p1788::io::hex;\n    F<double>::operator_interval_to_text(output, REP<double>(-INF_D,0.1) );\n    BOOST_CHECK( output.is_equal( \"[      -INF,0X1.999999AP-4]\" ) );\n\n    output << p1788::io::decimal;\n    F<double>::operator_interval_to_text(output, REP<double>(0.1,INF_D) );\n    BOOST_CHECK( output.is_equal( \"[ 0.1000000,       INF]\" ) );\n\n}\n\n\n\nBOOST_AUTO_TEST_CASE(minimal_decorated_interval_output_test)\n{\n    boost::test_tools::output_test_stream output;\n\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(0.1,0.1), DEC::trv) );\n    BOOST_CHECK( output.is_equal( \"[0.1,0.100001]_trv\" ) );\n\n    output << p1788::io::upper_case;\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(-0.1,0.1), DEC::def) );\n    BOOST_CHECK( output.is_equal( \"[-0.100001,0.100001]_DEF\" ) );\n\n    output << p1788::io::lower_case;\n    output << p1788::io::string_width(26);\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(-0.1,0.1), DEC::dac) );\n    BOOST_CHECK( output.is_equal( \"[ -0.100001, 0.100001]_dac\" ) );\n\n    output << p1788::io::no_punctuation;\n    output << p1788::io::upper_case;\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(-0.1,0.1), DEC::com) );\n    BOOST_CHECK( output.is_equal( \"  -0.100001   0.100001 COM\" ) );\n\n    output << p1788::io::dec_numeric;\n    output << p1788::io::hex;\n    output << p1788::io::string_width(0);\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(-0.1,1.3), DEC::trv) );\n    BOOST_CHECK( output.is_equal( \"-0X1.999999999999AP-4 0X1.4CCCCCCCCCCCDP+0 4\" ) );\n\n    output << p1788::io::punctuation;\n    output << p1788::io::lower_case;\n    output << p1788::io::precision(5);\n    output << p1788::io::width(15);\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(-0.1,1.3), DEC::def) );\n    BOOST_CHECK( output.is_equal( \"[  -0x1.9999ap-4,   0x1.4cccdp+0]_8\" ) );\n\n    output << p1788::io::string_width(35);\n    output << p1788::io::special_no_bounds;\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(0.1,1.3), DEC::dac) );\n    BOOST_CHECK( output.is_equal( \"[   0x1.99999p-4,   0x1.4cccdp+0]_12\" ) );\n\n    output << p1788::io::string_width(0);\n    output << p1788::io::precision(20);\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(0.1,1.3), DEC::com) );\n    BOOST_CHECK( output.is_equal( \"[0x1.999999999999a0000000p-4,0x1.4cccccccccccd0000000p+0]_16\" ) );\n\n    output << p1788::io::decimal;\n    output << p1788::io::precision(0);\n    output << p1788::io::width(10);\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(0.1,0.1), DEC::trv) );\n    BOOST_CHECK( output.is_equal( \"[  0.100000,  0.100001]_4\" ) );\n\n    output << p1788::io::dec_alpha;\n    output << p1788::io::upper_case;\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(-0.1,0.1), DEC::def) );\n    BOOST_CHECK( output.is_equal( \"[ -0.100001,  0.100001]_DEF\" ) );\n\n    output << p1788::io::lower_case;\n    output << p1788::io::string_width(29);\n    output << p1788::io::precision(7);\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(0.1,0.1), DEC::dac) );\n    BOOST_CHECK( output.is_equal( \"[  0.1000000,  0.1000001]_dac\" ) );\n\n    output << p1788::io::decimal_scientific;\n    output << p1788::io::string_width(0);\n    output << p1788::io::upper_case;\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(0.1,0.1), DEC::com) );\n    BOOST_CHECK( output.is_equal( \"[       0.1, 0.1000001]_COM\" ) );\n\n    output << p1788::io::scientific;\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(0.1,1.3), DEC::trv) );\n    BOOST_CHECK( output.is_equal( \"[1.0000000E-01,1.3000001E+00]_TRV\" ) );\n\n    output << p1788::io::lower_case;\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(-INF_D,0.1), DEC::def) );\n    BOOST_CHECK( output.is_equal( \"[      -inf,1.0000001e-01]_def\" ) );\n\n    output << p1788::io::decimal_scientific;\n    output << p1788::io::upper_case;\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(0.1,INF_D), DEC::dac) );\n    BOOST_CHECK( output.is_equal( \"[       0.1,       INF]_DAC\" ) );\n\n    output << p1788::io::hex;\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(-INF_D,0.1), DEC::trv) );\n    BOOST_CHECK( output.is_equal( \"[      -INF,0X1.999999AP-4]_TRV\" ) );\n\n    output << p1788::io::decimal;\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(0.1,INF_D), DEC::def) );\n    BOOST_CHECK( output.is_equal( \"[ 0.1000000,       INF]_DEF\" ) );\n\n}\n\n\nBOOST_AUTO_TEST_CASE(minimal_uncertain_interval_output_test)\n{\n    boost::test_tools::output_test_stream output;\n\n    output << p1788::io::uncertain_form;\n\n    F<double>::operator_interval_to_text(output, REP<double>(-INF_D,INF_D) );\n    BOOST_CHECK( output.is_equal( \"0.000000??\" ) );\n\n    F<double>::operator_interval_to_text(output, REP<double>(0.1,INF_D) );\n    BOOST_CHECK( output.is_equal( \"0.100000??u\" ) );\n\n    F<double>::operator_interval_to_text(output, REP<double>(-INF_D,0.1) );\n    BOOST_CHECK( output.is_equal( \"0.100001??d\" ) );\n\n    output << p1788::io::uncertain_exponent;\n    F<double>::operator_interval_to_text(output, REP<double>(-INF_D,INF_D) );\n    BOOST_CHECK( output.is_equal( \"0.000000??e+00\" ) );\n\n    F<double>::operator_interval_to_text(output, REP<double>(0.1,INF_D) );\n    BOOST_CHECK( output.is_equal( \"1.000000??ue-01\" ) );\n\n    F<double>::operator_interval_to_text(output, REP<double>(-INF_D,0.1) );\n    BOOST_CHECK( output.is_equal( \"1.000001??de-01\" ) );\n\n    output << p1788::io::precision(1);\n    output << p1788::io::string_width(20);\n    output << p1788::io::upper_case;\n    F<double>::operator_interval_to_text(output, REP<double>(-INF_D,INF_D) );\n    BOOST_CHECK( output.is_equal( \"           0.0??E+00\" ) );\n\n    F<double>::operator_interval_to_text(output, REP<double>(0.1,INF_D) );\n    BOOST_CHECK( output.is_equal( \"          1.0??UE-01\" ) );\n\n    F<double>::operator_interval_to_text(output, REP<double>(-INF_D,0.1) );\n    BOOST_CHECK( output.is_equal( \"          1.1??DE-01\" ) );\n\n    output << p1788::io::no_uncertain_exponent;\n    output << p1788::io::no_punctuation;\n    F<double>::operator_interval_to_text(output, REP<double>(-INF_D,INF_D) );\n    BOOST_CHECK( output.is_equal( \"               0.0??\" ) );\n\n    F<double>::operator_interval_to_text(output, REP<double>(0.1,INF_D) );\n    BOOST_CHECK( output.is_equal( \"              0.1??U\" ) );\n\n    F<double>::operator_interval_to_text(output, REP<double>(-INF_D,0.1) );\n    BOOST_CHECK( output.is_equal( \"              0.2??D\" ) );\n\n\n    output << p1788::io::precision(5);\n    output << p1788::io::string_width(0);\n    output << p1788::io::lower_case;\n    F<double>::operator_interval_to_text(output, REP<double>(0.1, 0.2) );\n    BOOST_CHECK( output.is_equal( \"0.15000?5001\" ) );\n\n    output << p1788::io::uncertain_down_form;\n    output << p1788::io::precision(7);\n    F<double>::operator_interval_to_text(output, REP<double>(0.1, 0.2) );\n    BOOST_CHECK( output.is_equal( \"0.2000001?1000001d\" ) );\n\n    output << p1788::io::uncertain_up_form;\n    output << p1788::io::precision(0);\n    output << p1788::io::string_width(18);\n    output << p1788::io::upper_case;\n    F<double>::operator_interval_to_text(output, REP<double>(-0.1, 0.2) );\n    BOOST_CHECK( output.is_equal( \" -0.100001?300002U\" ) );\n\n\n    output << p1788::io::precision(0);\n    output << p1788::io::string_width(0);\n    output << p1788::io::lower_case;\n    output << p1788::io::uncertain_exponent;\n    F<double>::operator_interval_to_text(output, REP<double>(-100, 0.2) );\n    BOOST_CHECK( output.is_equal( \"-1.000000?1002001ue+02\" ) );\n\n    F<double>::operator_interval_to_text(output, REP<double>(-100, 0.0) );\n    BOOST_CHECK( output.is_equal( \"-1.000000?1000000ue+02\" ) );\n\n    F<double>::operator_interval_to_text(output, REP<double>(-100, -0.2) );\n    BOOST_CHECK( output.is_equal( \"-1.000000?998000ue+02\" ) );\n\n    F<double>::operator_interval_to_text(output, REP<double>(-0.2, 100) );\n    BOOST_CHECK( output.is_equal( \"-2.000001?1002000001ue-01\" ) );\n\n    F<double>::operator_interval_to_text(output, REP<double>(0.0,100) );\n    BOOST_CHECK( output.is_equal( \"0.000000?100000000ue+00\" ) );\n\n    F<double>::operator_interval_to_text(output, REP<double>(0.2, 100) );\n    BOOST_CHECK( output.is_equal( \"2.000000?998000000ue-01\" ) );\n\n\n    output << p1788::io::uncertain_down_form;\n    F<double>::operator_interval_to_text(output, REP<double>(-0.2, 100) );\n    BOOST_CHECK( output.is_equal( \"1.000000?1002001de+02\" ) );\n\n    F<double>::operator_interval_to_text(output, REP<double>(0.0,100) );\n    BOOST_CHECK( output.is_equal( \"1.000000?1000000de+02\" ) );\n\n    F<double>::operator_interval_to_text(output, REP<double>(0.2, 100) );\n    BOOST_CHECK( output.is_equal( \"1.000000?998000de+02\" ) );\n\n    F<double>::operator_interval_to_text(output, REP<double>(-100, 0.2) );\n    BOOST_CHECK( output.is_equal( \"2.000001?1002000001de-01\" ) );\n\n    F<double>::operator_interval_to_text(output, REP<double>(-100, 0.0) );\n    BOOST_CHECK( output.is_equal( \"0.000000?100000000de+00\" ) );\n\n    F<double>::operator_interval_to_text(output, REP<double>(-100, -0.2) );\n    BOOST_CHECK( output.is_equal( \"-2.000000?998000000de-01\" ) );\n\n    output << p1788::io::uncertain_form;\n\n    F<double>::operator_interval_to_text(output, REP<double>(-0.2, 100) );\n    BOOST_CHECK( output.is_equal( \"4.990000?5010001e+01\" ) );\n\n    F<double>::operator_interval_to_text(output, REP<double>(0.0,100) );\n    BOOST_CHECK( output.is_equal( \"5.000000?5000000e+01\" ) );\n\n    F<double>::operator_interval_to_text(output, REP<double>(0.2, 100) );\n    BOOST_CHECK( output.is_equal( \"5.010000?4990000e+01\" ) );\n\n    F<double>::operator_interval_to_text(output, REP<double>(-100, 0.2) );\n    BOOST_CHECK( output.is_equal( \"-4.990000?5010001e+01\" ) );\n\n    F<double>::operator_interval_to_text(output, REP<double>(-100, 0.0) );\n    BOOST_CHECK( output.is_equal( \"-5.000000?5000000e+01\" ) );\n\n    F<double>::operator_interval_to_text(output, REP<double>(-100, -0.2) );\n    BOOST_CHECK( output.is_equal( \"-5.010000?4990000e+01\" ) );\n\n    output << p1788::io::uncertain_form;\n    output << p1788::io::upper_case;\n    output << p1788::io::special_bounds;\n    output << p1788::io::no_punctuation;\n    F<double>::operator_interval_to_text(output, F<double>::empty());\n    BOOST_CHECK( output.is_equal( \"INF -INF\" ) );\n\n    output << p1788::io::special_text;\n    output << p1788::io::punctuation;\n    F<double>::operator_interval_to_text(output, F<double>::empty());\n    BOOST_CHECK( output.is_equal( \"[EMPTY]\" ) );\n}\n\n\n\nBOOST_AUTO_TEST_CASE(minimal_uncertain_interval_dec_output_test)\n{\n    boost::test_tools::output_test_stream output;\n\n    output << p1788::io::uncertain_form;\n\n\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(-INF_D,INF_D), DEC::trv) );\n    BOOST_CHECK( output.is_equal( \"0.000000??_trv\" ) );\n\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(0.1,INF_D), DEC::def) );\n    BOOST_CHECK( output.is_equal( \"0.100000??u_def\" ) );\n\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(-INF_D,0.1), DEC::dac) );\n    BOOST_CHECK( output.is_equal( \"0.100001??d_dac\" ) );\n\n    output << p1788::io::uncertain_exponent;\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(-INF_D,INF_D), DEC::trv) );\n    BOOST_CHECK( output.is_equal( \"0.000000??e+00_trv\" ) );\n\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(0.1,INF_D), DEC::def) );\n    BOOST_CHECK( output.is_equal( \"1.000000??ue-01_def\" ) );\n\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(-INF_D,0.1), DEC::dac) );\n    BOOST_CHECK( output.is_equal( \"1.000001??de-01_dac\" ) );\n\n    output << p1788::io::precision(1);\n    output << p1788::io::string_width(20);\n    output << p1788::io::upper_case;\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(-INF_D,INF_D), DEC::trv) );\n    BOOST_CHECK( output.is_equal( \"       0.0??E+00_TRV\" ) );\n\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(0.1,INF_D), DEC::def) );\n    BOOST_CHECK( output.is_equal( \"      1.0??UE-01_DEF\" ) );\n\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(-INF_D,0.1), DEC::dac) );\n    BOOST_CHECK( output.is_equal( \"      1.1??DE-01_DAC\" ) );\n\n    output << p1788::io::no_uncertain_exponent;\n    output << p1788::io::no_punctuation;\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(-INF_D,INF_D), DEC::trv) );\n    BOOST_CHECK( output.is_equal( \"           0.0?? TRV\" ) );\n\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(0.1,INF_D), DEC::def) );\n    BOOST_CHECK( output.is_equal( \"          0.1??U DEF\" ) );\n\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(-INF_D,0.1), DEC::dac) );\n    BOOST_CHECK( output.is_equal( \"          0.2??D DAC\" ) );\n\n\n    output << p1788::io::precision(5);\n    output << p1788::io::string_width(0);\n    output << p1788::io::lower_case;\n    output << p1788::io::dec_numeric;\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(0.1, 0.2), DEC::trv) );\n    BOOST_CHECK( output.is_equal( \"0.15000?5001 4\" ) );\n\n    output << p1788::io::uncertain_down_form;\n    output << p1788::io::precision(7);\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(0.1, 0.2), DEC::def) );\n    BOOST_CHECK( output.is_equal( \"0.2000001?1000001d 8\" ) );\n\n    output << p1788::io::uncertain_up_form;\n    output << p1788::io::precision(0);\n    output << p1788::io::string_width(21);\n    output << p1788::io::upper_case;\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(-0.1, 0.2), DEC::dac) );\n    BOOST_CHECK( output.is_equal( \" -0.100001?300002U 12\" ) );\n\n\n    output << p1788::io::precision(0);\n    output << p1788::io::string_width(0);\n    output << p1788::io::lower_case;\n    output << p1788::io::uncertain_exponent;\n    output << p1788::io::punctuation;\n    output << p1788::io::dec_alpha;\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(-100, 0.2), DEC::com) );\n    BOOST_CHECK( output.is_equal( \"-1.000000?1002001ue+02_com\" ) );\n\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(-100, 0.0), DEC::trv) );\n    BOOST_CHECK( output.is_equal( \"-1.000000?1000000ue+02_trv\" ) );\n\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(-100, -0.2), DEC::def) );\n    BOOST_CHECK( output.is_equal( \"-1.000000?998000ue+02_def\" ) );\n\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(-0.2, 100), DEC::dac) );\n    BOOST_CHECK( output.is_equal( \"-2.000001?1002000001ue-01_dac\" ) );\n\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(0.0,100), DEC::com) );\n    BOOST_CHECK( output.is_equal( \"0.000000?100000000ue+00_com\" ) );\n\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(0.2, 100), DEC::trv) );\n    BOOST_CHECK( output.is_equal( \"2.000000?998000000ue-01_trv\" ) );\n\n\n    output << p1788::io::uncertain_down_form;\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(-0.2, 100), DEC::def) );\n    BOOST_CHECK( output.is_equal( \"1.000000?1002001de+02_def\" ) );\n\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(0.0,100), DEC::dac) );\n    BOOST_CHECK( output.is_equal( \"1.000000?1000000de+02_dac\" ) );\n\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(0.2, 100), DEC::com) );\n    BOOST_CHECK( output.is_equal( \"1.000000?998000de+02_com\" ) );\n\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(-100, 0.2), DEC::trv) );\n    BOOST_CHECK( output.is_equal( \"2.000001?1002000001de-01_trv\" ) );\n\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(-100, 0.0), DEC::def) );\n    BOOST_CHECK( output.is_equal( \"0.000000?100000000de+00_def\" ) );\n\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(-100, -0.2), DEC::dac) );\n    BOOST_CHECK( output.is_equal( \"-2.000000?998000000de-01_dac\" ) );\n\n    output << p1788::io::uncertain_form;\n\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(-0.2, 100), DEC::com) );\n    BOOST_CHECK( output.is_equal( \"4.990000?5010001e+01_com\" ) );\n\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(0.0,100), DEC::trv) );\n    BOOST_CHECK( output.is_equal( \"5.000000?5000000e+01_trv\" ) );\n\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(0.2, 100), DEC::def) );\n    BOOST_CHECK( output.is_equal( \"5.010000?4990000e+01_def\" ) );\n\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(-100, 0.2), DEC::dac) );\n    BOOST_CHECK( output.is_equal( \"-4.990000?5010001e+01_dac\" ) );\n\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(-100, 0.0), DEC::com) );\n    BOOST_CHECK( output.is_equal( \"-5.000000?5000000e+01_com\" ) );\n\n    F<double>::operator_interval_to_text(output, REP_DEC<double>(REP<double>(-100, -0.2), DEC::trv) );\n    BOOST_CHECK( output.is_equal( \"-5.010000?4990000e+01_trv\" ) );\n\n    output << p1788::io::special_bounds;\n    output << p1788::io::no_punctuation;\n    F<double>::operator_interval_to_text(output, F<double>::empty_dec());\n    BOOST_CHECK( output.is_equal( \"inf -inf\" ) );\n\n    output << p1788::io::hex;\n    output << p1788::io::special_text;\n    output << p1788::io::punctuation;\n    F<double>::operator_interval_to_text(output, F<double>::empty_dec());\n    BOOST_CHECK( output.is_equal( \"[empty]\" ) );\n\n    F<double>::operator_interval_to_text(output, F<double>::nai() );\n    BOOST_CHECK( output.is_equal( \"[nai]\" ) );\n\n    output << p1788::io::upper_case;\n    output << p1788::io::no_punctuation;\n    F<double>::operator_interval_to_text(output, F<double>::nai() );\n    BOOST_CHECK( output.is_equal( \"NAI\" ) );\n}\n\n\n\nBOOST_AUTO_TEST_CASE(minimal_decorated_interval_input_test)\n{\n    {\n        REP_DEC<double> di;\n        std::istringstream is(\"[ Nai  ]\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK( F<double>::is_nai(di) );\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP_DEC<double> di(REP<double>(-1.0,2.0),DEC::trv);\n        std::istringstream is(\"[ Nai  ]_ill\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL( di, REP_DEC<double>(REP<double>(-1.0,2.0),DEC::trv) );\n        BOOST_CHECK(!is);\n    }\n\n    {\n        REP_DEC<double> di(REP<double>(-1.0,2.0),DEC::trv);\n        std::istringstream is(\"[ Nai  ]_trv\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL( di, REP_DEC<double>(REP<double>(-1.0,2.0),DEC::trv) );\n        BOOST_CHECK(!is);\n    }\n\n    {\n        REP_DEC<double> di;\n        std::istringstream is(\"[ Empty  ]\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK( F<double>::is_empty(di) );\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP_DEC<double> di;\n        std::istringstream is(\"[ Empty  ]_trv\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK( F<double>::is_empty(di) );\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP_DEC<double> di(REP<double>(-1.0,2.0),DEC::trv);\n        std::istringstream is(\"[ Empty  ]_ill\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL( di, REP_DEC<double>(REP<double>(-1.0,2.0),DEC::trv) );\n        BOOST_CHECK(!is);\n    }\n\n    {\n        REP_DEC<double> di;\n        std::istringstream is(\"[  ]\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK( F<double>::is_empty(di) );\n        BOOST_CHECK(is);\n    }\n\n\n    {\n        REP_DEC<double> di(REP<double>(-1.0,2.0),DEC::trv);\n        std::istringstream is(\"[  ]_com\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL( di, REP_DEC<double>(REP<double>(-1.0,2.0),DEC::trv) );\n        BOOST_CHECK(!is);\n    }\n\n    {\n        REP_DEC<double> di;\n        std::istringstream is(\"[  ]_trv\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK( F<double>::is_empty(di) );\n        BOOST_CHECK(is);\n    }\n\n\n    {\n        REP_DEC<double> di;\n        std::istringstream is(\"[,]\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL(di, F<double>::entire_dec());\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP_DEC<double> di;\n        std::istringstream is(\"[,]_trv\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL(di, REP_DEC<double>(REP<double>(-INF_D,INF_D),DEC::trv));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP_DEC<double> di(REP<double>(-1.0,2.0),DEC::trv);\n        std::istringstream is(\"[,]_com\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL( di, REP_DEC<double>(REP<double>(-1.0,2.0),DEC::trv) );\n        BOOST_CHECK(!is);\n    }\n\n    {\n        REP_DEC<double> di;\n        std::istringstream is(\"[ entire  ]\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL(di, F<double>::entire_dec());\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP_DEC<double> di;\n        std::istringstream is(\"[ ENTIRE ]_dac\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL(di, REP_DEC<double>(REP<double>(-INF_D,INF_D),DEC::dac));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP_DEC<double> di(REP<double>(-1.0,2.0),DEC::trv);\n        std::istringstream is(\"[   Entire ]_com\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL( di, REP_DEC<double>(REP<double>(-1.0,2.0),DEC::trv) );\n        BOOST_CHECK(!is);\n    }\n\n    {\n        REP_DEC<double> di;\n        std::istringstream is(\"[ -inf , INF  ]\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL(di, F<double>::entire_dec());\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP_DEC<double> di;\n        std::istringstream is(\"[ -inf, INF ]_def\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL(di, REP_DEC<double>(REP<double>(-INF_D,INF_D),DEC::def));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP_DEC<double> di(REP<double>(-1.0,2.0),DEC::trv);\n        std::istringstream is(\"[ -inf ,  INF ]_com\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL( di, REP_DEC<double>(REP<double>(-1.0,2.0),DEC::trv) );\n        BOOST_CHECK(!is);\n    }\n\n    {\n        REP_DEC<double> di;\n        std::istringstream is(\"[-1.0,1.0]\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL(di, REP_DEC<double>(REP<double>(-1.0,1.0),DEC::com));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP_DEC<double> di;\n        std::istringstream is(\"[  -1.0  ,  1.0  ]_com\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL(di, REP_DEC<double>(REP<double>(-1.0,1.0),DEC::com));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP_DEC<double> di;\n        std::istringstream is(\"[  -1.0  , 1.0]_trv\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL(di, REP_DEC<double>(REP<double>(-1.0,1.0),DEC::trv));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP_DEC<double> di(REP<double>(-1.0,2.0),DEC::trv);\n        std::istringstream is(\"[  -1.0  , 1.0]_ill\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL( di, REP_DEC<double>(REP<double>(-1.0,2.0),DEC::trv) );\n        BOOST_CHECK(!is);\n    }\n\n    {\n        REP_DEC<double> di(REP<double>(-1.0,2.0),DEC::trv);\n        std::istringstream is(\"[  -1.0  , 1.0]_fooo\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL( di, REP_DEC<double>(REP<double>(-1.0,2.0),DEC::trv) );\n        BOOST_CHECK(!is);\n    }\n\n    {\n        REP_DEC<double> di(REP<double>(-1.0,2.0),DEC::trv);\n        std::istringstream is(\"[  -1.0  , 1.0]_da c\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL( di, REP_DEC<double>(REP<double>(-1.0,2.0),DEC::trv) );\n        BOOST_CHECK(!is);\n    }\n\n    {\n        REP_DEC<double> di(REP<double>(-1.0,2.0),DEC::trv);\n        std::istringstream is(\"[  -1.0  , 1.0]_da\");\n        is.exceptions(is.eofbit);\n        BOOST_CHECK_THROW(F<double>::operator_text_to_interval(is, di), std::ios_base::failure);\n        BOOST_CHECK_EQUAL( di, REP_DEC<double>(REP<double>(-1.0,2.0),DEC::trv) );\n        BOOST_CHECK(!is);\n    }\n\n    {\n        REP_DEC<double> di;\n        std::istringstream is(\"[-1,]\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL(di, REP_DEC<double>(REP<double>(-1.0,INF_D),DEC::dac));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP_DEC<double> di;\n        std::istringstream is(\"[-1.0, +inf]_def\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL(di, REP_DEC<double>(REP<double>(-1.0,INF_D),DEC::def));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP_DEC<double> di;\n        std::istringstream is(\"[-1.0, +infinity]_def\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL(di, REP_DEC<double>(REP<double>(-1.0,INF_D),DEC::def));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP_DEC<double> di(REP<double>(-1.0,2.0),DEC::trv);\n        std::istringstream is(\"[-1.0,]_com\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL( di, REP_DEC<double>(REP<double>(-1.0,2.0),DEC::trv) );\n        BOOST_CHECK(!is);\n    }\n\n    {\n        REP_DEC<double> di;\n        std::istringstream is(\"[-Inf, 1.000 ]\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL(di, REP_DEC<double>(REP<double>(-INF_D,1.0),DEC::dac));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP_DEC<double> di;\n        std::istringstream is(\"[-Infinity, 1.000 ]_trv\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL(di, REP_DEC<double>(REP<double>(-INF_D,1.0),DEC::trv));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP_DEC<double> di(REP<double>(-15.0,27.0),DEC::trv);\n        std::istringstream is(\"[-Inf, 1.000 ]_ill\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL( di, REP_DEC<double>(REP<double>(-15.0,27.0),DEC::trv) );\n        BOOST_CHECK(!is);\n    }\n\n    {\n        REP_DEC<double> di;\n        std::istringstream is(\"[1.0E+400 ]_com\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL(di, REP_DEC<double>(REP<double>(MAX_D,INF_D),DEC::dac));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP_DEC<double> di;\n        std::istringstream is(\"[1.0000000000000002E+6000 ]_com\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL(di, REP_DEC<double>(REP<double>(MAX_D,INF_D),DEC::dac));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP_DEC<double> di;\n        std::istringstream is(\"[-1.0000000000000002E+6000 ]_com\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL(di, REP_DEC<double>(REP<double>(-INF_D,-MAX_D),DEC::dac));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP_DEC<double> di;\n        std::istringstream is(\"[10000000000000002]_com\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL(di, REP_DEC<double>(REP<double>(10000000000000002,10000000000000002),DEC::com));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP_DEC<double> di;\n        std::istringstream is(\"[-10000000000000002]_com\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL(di, REP_DEC<double>(REP<double>(-10000000000000002,-10000000000000002),DEC::com));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP_DEC<double> di;\n        std::istringstream is(\"[-1.0000000000000002E+6000, 1.0000000000000001E+6000]_com\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL(di, REP_DEC<double>(REP<double>(-INF_D,INF_D),DEC::dac));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP_DEC<double> di;\n        std::istringstream is(\"[ -4/2, 10/5 ]_com\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL(di, REP_DEC<double>(REP<double>(-2.0,2.0),DEC::com));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP_DEC<double> di;\n        std::istringstream is(\"[ -1/10, 1/10 ]_com\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL(di, REP_DEC<double>(REP<double>(-0.1,0.1),DEC::com));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP_DEC<double> di(REP<double>(-1.0,2.0),DEC::trv);\n        std::istringstream is(\"[ 1/-10, 1/10 ]_com\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL( di, REP_DEC<double>(REP<double>(-1.0,2.0),DEC::trv) );\n        BOOST_CHECK(!is);\n    }\n\n    {\n        REP_DEC<double> di(REP<double>(-1.0,2.0),DEC::trv);\n        std::istringstream is(\"[ 1/10, 1/+10 ]_com\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL( di, REP_DEC<double>(REP<double>(-1.0,2.0),DEC::trv) );\n        BOOST_CHECK(!is);\n    }\n\n    {\n        REP_DEC<double> di(REP<double>(-1.0,2.0),DEC::trv);\n        std::istringstream is(\"[ 1/0, 1/10 ]_com\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL( di, REP_DEC<double>(REP<double>(-1.0,2.0),DEC::trv) );\n        BOOST_CHECK(!is);\n    }\n\n    {\n        REP_DEC<double> di(REP<double>(-1.0,2.0),DEC::trv);\n        std::istringstream is(\"[-I  nf, 1.000 ]\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL( di, REP_DEC<double>(REP<double>(-1.0,2.0),DEC::trv) );\n        BOOST_CHECK(!is);\n    }\n\n    {\n        REP_DEC<double> di(REP<double>(-1.0,2.0),DEC::trv);\n        std::istringstream is(\"[-Inf, 1.0  00 ]\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL( di, REP_DEC<double>(REP<double>(-1.0,2.0),DEC::trv) );\n        BOOST_CHECK(!is);\n    }\n\n    {\n        REP_DEC<double> di(REP<double>(-1.0,12.0),DEC::trv);\n        std::istringstream is(\"[-Inf ]\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL( di, REP_DEC<double>(REP<double>(-1.0,12.0),DEC::trv) );\n        BOOST_CHECK(!is);\n    }\n\n    {\n        REP_DEC<double> di(REP<double>(-1.0,2.0),DEC::trv);\n        std::istringstream is(\"[1.0,-1.0]\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL( di, REP_DEC<double>(REP<double>(-1.0,2.0),DEC::trv) );\n        BOOST_CHECK(!is);\n    }\n\n    {\n        REP_DEC<double> di(REP<double>(-1.0,2.0),DEC::trv);\n        std::istringstream is(\"[-1.0,1.0\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL( di, REP_DEC<double>(REP<double>(-1.0,2.0),DEC::trv) );\n        BOOST_CHECK(!is);\n    }\n\n    {\n        REP_DEC<double> di(REP<double>(-1.0,2.0),DEC::trv);\n        std::istringstream is(\"-1.0,1.0]\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL( di, REP_DEC<double>(REP<double>(-1.0,2.0),DEC::trv) );\n        BOOST_CHECK(!is);\n    }\n\n    {\n        REP_DEC<double> di(REP<double>(-1.0,2.0),DEC::trv);\n        std::istringstream is(\"[1.0\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL( di, REP_DEC<double>(REP<double>(-1.0,2.0),DEC::trv) );\n        BOOST_CHECK(!is);\n    }\n\n    {\n        REP_DEC<double> di(REP<double>(-1.0,2.0),DEC::trv);\n        std::istringstream is(\"-1.0]\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL( di, REP_DEC<double>(REP<double>(-1.0,2.0),DEC::trv) );\n        BOOST_CHECK(!is);\n    }\n\n\n    {\n        REP_DEC<double> di(REP<double>(-1.0,2.0),DEC::trv);\n        std::istringstream is(\"[Inf , INF]\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL( di, REP_DEC<double>(REP<double>(-1.0,2.0),DEC::trv) );\n        BOOST_CHECK(!is);\n    }\n\n    {\n        REP_DEC<double> di(REP<double>(-1.0,5.0),DEC::trv);\n        std::istringstream is(\"[ foo ]\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL( di, REP_DEC<double>(REP<double>(-1.0,5.0),DEC::trv) );\n        BOOST_CHECK(!is);\n    }\n\n    {\n        REP_DEC<double> di(REP<double>(-1.0,5.0),DEC::trv);\n        std::istringstream is(\"[1.0000000000000002,1.0000000000000001]\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL( di, REP_DEC<double>(REP<double>(-1.0,5.0),DEC::trv) );\n        BOOST_CHECK(!is);\n    }\n\n    {\n        REP_DEC<double> di(REP<double>(-1.0,5.0),DEC::trv);\n        std::istringstream is(\"[1.0000000000000002E+6000,1.0000000000000001E+6000]\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL( di, REP_DEC<double>(REP<double>(-1.0,5.0),DEC::trv) );\n        BOOST_CHECK(!is);\n    }\n\n    {\n        REP_DEC<double> di(REP<double>(-1.0,5.0),DEC::trv);\n        std::istringstream is(\"[10000000000000001/10000000000000000,10000000000000002/10000000000000001]\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL( di, REP_DEC<double>(REP<double>(-1.0,5.0),DEC::trv) );\n        BOOST_CHECK(!is);\n    }\n\n    {\n        REP_DEC<double> di(REP<double>(-1.0,5.0),DEC::trv);\n        std::istringstream is(\"[0x1.00000000000001p0,0x1.00000000000002p0]\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL( di, REP_DEC<double>(REP<double>(std::stod(\"0x1.0p0\"),std::stod(\"0x1.0000000000001p0\")),DEC::com) );\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP_DEC<double> di(REP<double>(-1.0,5.0),DEC::trv);\n        std::istringstream is(\"[-0x1.00000000000001p0,0x1.00000000000002p0]\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL( di, REP_DEC<double>(REP<double>(std::stod(\"-0x1.0000000000001p0\"),std::stod(\"0x1.0000000000001p0\")),DEC::com) );\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP_DEC<double> di(REP<double>(-1.0,5.0),DEC::trv);\n        std::istringstream is(\"[0x1.00000000000001,0x1.00000000000002p0]\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL( di, REP_DEC<double>(REP<double>(-1.0,5.0),DEC::trv) );\n        BOOST_CHECK(!is);\n    }\n\n    {\n        REP_DEC<double> di(REP<double>(-1.0,5.0),DEC::trv);\n        std::istringstream is(\"[0x1.00000000000001p0,0x1.00000000000002]\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL( di, REP_DEC<double>(REP<double>(-1.0,5.0),DEC::trv) );\n        BOOST_CHECK(!is);\n    }\n\n    {\n        REP_DEC<double> di(REP<double>(-1.0,5.0),DEC::trv);\n        std::istringstream is(\"[0x1.00000000000001,0x1.00000000000002]\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL( di, REP_DEC<double>(REP<double>(-1.0,5.0),DEC::trv) );\n        BOOST_CHECK(!is);\n    }\n\n    {\n        REP_DEC<double> di(REP<double>(-1.0,5.0),DEC::trv);\n        std::istringstream is(\"[0x1.00000000000001p0]\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL( di, REP_DEC<double>(REP<double>(std::stod(\"0x1.0p0\"),std::stod(\"0x1.0000000000001p0\")),DEC::com) );\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP_DEC<double> di(REP<double>(-1.0,5.0),DEC::trv);\n        std::istringstream is(\"[-0x1.00000000000001p0]\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL( di, REP_DEC<double>(REP<double>(std::stod(\"-0x1.0000000000001p0\"),std::stod(\"-0x1.0p0\")),DEC::com) );\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP_DEC<double> di(REP<double>(-1.0,5.0),DEC::trv);\n        std::istringstream is(\"[0x1.00000000000001]\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL( di, REP_DEC<double>(REP<double>(-1.0,5.0),DEC::trv) );\n        BOOST_CHECK(!is);\n    }\n\n    {\n        REP_DEC<double> di(REP<double>(-1.0,5.0),DEC::trv);\n        std::istringstream is(\"[0x1.00000000000001]\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL( di, REP_DEC<double>(REP<double>(-1.0,5.0),DEC::trv) );\n        BOOST_CHECK(!is);\n    }\n\n    {\n        REP_DEC<double> di(REP<double>(-1.0,5.0),DEC::trv);\n        std::istringstream is(\"[0x1.00000000000002p0,0x1.00000000000001p0]\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL( di, REP_DEC<double>(REP<double>(-1.0,5.0),DEC::trv) );\n        BOOST_CHECK(!is);\n    }\n\n    {\n        REP_DEC<double> di(REP<double>(-1.0,5.0),DEC::trv);\n        std::istringstream is(\"[-0x1.00000000000001p0,-0x1.00000000000002p0]\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL( di, REP_DEC<double>(REP<double>(-1.0,5.0),DEC::trv) );\n        BOOST_CHECK(!is);\n    }\n\n    {\n        REP_DEC<double> di(REP<double>(-1.0,5.0),DEC::trv);\n        std::istringstream is(\"[-0x1.00000000000001p0, 10/5]\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL( di, REP_DEC<double>(REP<double>(std::stod(\"-0x1.0000000000001p0\"), 2.0),DEC::com) );\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP_DEC<double> di(REP<double>(-1.0,5.0),DEC::trv);\n        std::istringstream is(\"[0x1.00000000000001p0, 2.5]\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL( di, REP_DEC<double>(REP<double>(1.0, 2.5),DEC::com) );\n        BOOST_CHECK(is);\n    }\n\n}\n\n\nBOOST_AUTO_TEST_CASE(minimal_interval_input_test)\n{\n    {\n        REP<double> i;\n        std::istringstream is(\"[ Empty  ]\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK( F<double>::is_empty(i) );\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP<double> i;\n        std::istringstream is(\"[ Empty  ]_trv\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK( F<double>::is_empty(i) );\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP<double> i(3.5,4.7);\n        std::istringstream is(\"[ Empty  ]_ill\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL( i, REP<double>(3.5,4.7) );\n        BOOST_CHECK(!is);\n    }\n\n    {\n        REP<double> i;\n        std::istringstream is(\"[  ]\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK( F<double>::is_empty(i) );\n        BOOST_CHECK(is);\n    }\n\n\n    {\n        REP<double> i(3.5,4.7);\n        std::istringstream is(\"[  ]_com\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL( i, REP<double>(3.5,4.7) );\n        BOOST_CHECK(!is);\n    }\n\n    {\n        REP<double> i;\n        std::istringstream is(\"[  ]_trv\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK( F<double>::is_empty(i) );\n        BOOST_CHECK(is);\n    }\n\n\n    {\n        REP<double> i;\n        std::istringstream is(\"[,]\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL(i, F<double>::entire());\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP<double> i;\n        std::istringstream is(\"[,]_trv\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL(i, F<double>::entire());\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP<double> i(3.5,4.7);\n        std::istringstream is(\"[,]_com\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL( i, REP<double>(3.5,4.7) );\n        BOOST_CHECK(!is);\n    }\n\n    {\n        REP<double> i;\n        std::istringstream is(\"[ entire  ]\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL(i, F<double>::entire());\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP<double> i;\n        std::istringstream is(\"[ ENTIRE ]_dac\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL(i, F<double>::entire());\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP<double> i(3.5,4.7);\n        std::istringstream is(\"[   Entire ]_com\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL( i, REP<double>(3.5,4.7) );\n        BOOST_CHECK(!is);\n    }\n\n    {\n        REP<double> i;\n        std::istringstream is(\"[ -inf , INF  ]\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL(i, F<double>::entire());\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP<double> i;\n        std::istringstream is(\"[ -inf, INF ]_def\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL(i, F<double>::entire());\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP<double> i(3.5,4.7);\n        std::istringstream is(\"[ -inf ,  INF ]_com\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL( i, REP<double>(3.5,4.7) );\n        BOOST_CHECK(!is);\n    }\n\n\n    {\n        REP<double> i;\n        std::istringstream is(\"[-1.0,1]\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL(i, REP<double>(-1.0,1.0));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP<double> i;\n        std::istringstream is(\"[  -1.0  ,  1.0  ]_com\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL(i, REP<double>(-1.0,1.0));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP<double> i;\n        std::istringstream is(\"[  -1.0  , 1.0]_trv\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL(i, REP<double>(-1.0,1.0));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP<double> i(3.5,4.7);\n        std::istringstream is(\"[  -1.0  , 1.0]_ill\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL( i, REP<double>(3.5,4.7) );\n        BOOST_CHECK(!is);\n    }\n\n    {\n        REP<double> i(3.5,4.7);\n        std::istringstream is(\"[  -1.0  , 1.0]_fooo\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL( i, REP<double>(3.5,4.7) );\n        BOOST_CHECK(!is);\n    }\n\n    {\n        REP<double> i(3.5,4.7);\n        std::istringstream is(\"[  -1.0  , 1.0]_da c\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL( i, REP<double>(3.5,4.7) );\n        BOOST_CHECK(!is);\n    }\n\n\n    {\n        REP<double> i;\n        std::istringstream is(\"[-1.0,]\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL(i, REP<double>(-1.0,INF_D));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP<double> i;\n        std::istringstream is(\"[-1.0, +inf]_def\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL(i, REP<double>(-1.0,INF_D));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP<double> i;\n        std::istringstream is(\"[-1.0, +infinity]_def\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL(i, REP<double>(-1.0,INF_D));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP<double> i(3.5,4.7);\n        std::istringstream is(\"[-1.0,]_com\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL( i, REP<double>(3.5,4.7) );\n        BOOST_CHECK(!is);\n    }\n\n    {\n        REP<double> i;\n        std::istringstream is(\"[-Inf, 1.000 ]\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL(i, REP<double>(-INF_D,1.0));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP<double> i;\n        std::istringstream is(\"[-Infinity, 1.000 ]_trv\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL(i, REP<double>(-INF_D,1.0));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP<double> i(-35.0,-0.7);\n        std::istringstream is(\"[-Inf, 1.000 ]_ill\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL( i, REP<double>(-35.0,-0.7) );\n        BOOST_CHECK(!is);\n    }\n\n    {\n        REP<double> i;\n        std::istringstream is(\"[ 0.1 ]_com\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL(i, REP<double>(std::stod(\"0x1.9999999999999p-4\"),std::stod(\"0x1.999999999999ap-4\")));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP<double> i;\n        std::istringstream is(\"[ 1/10 ]\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL(i, REP<double>(std::stod(\"0x1.9999999999999p-4\"),std::stod(\"0x1.999999999999ap-4\")));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP<double> i;\n        std::istringstream is(\"[1.0E+400 ]_com\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL(i, REP<double>(MAX_D,INF_D));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP<double> i;\n        std::istringstream is(\"[ -4/2, 10/5 ]_com\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL(i, REP<double>(-2.0,2.0));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP<double> i;\n        std::istringstream is(\"[ -1/10, 1/10 ]_com\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL(i, REP<double>(-0.1,0.1));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP<double> i(3.5,4.7);\n        std::istringstream is(\"[ 1/-10, 1/10 ]_com\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL( i, REP<double>(3.5,4.7) );\n        BOOST_CHECK(!is);\n    }\n\n    {\n        REP<double> i(3.5,45.7);\n        std::istringstream is(\"1.0, 1.000]\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL( i, REP<double>(3.5,45.7) );\n        BOOST_CHECK(!is);\n    }\n\n    {\n        REP<double> i(3.5,45.7);\n        std::istringstream is(\"[1.0, 1.000\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL( i, REP<double>(3.5,45.7) );\n        BOOST_CHECK(!is);\n    }\n\n    {\n        REP<double> i(3.5,45.7);\n        std::istringstream is(\"1.000]\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL( i, REP<double>(3.5,45.7) );\n        BOOST_CHECK(!is);\n    }\n\n    {\n        REP<double> i(3.5,45.7);\n        std::istringstream is(\"[1.0\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL( i, REP<double>(3.5,45.7) );\n        BOOST_CHECK(!is);\n    }\n\n    {\n        REP<double> i(3.5,45.7);\n        std::istringstream is(\"[-I  nf, 1.000 ]\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL( i, REP<double>(3.5,45.7) );\n        BOOST_CHECK(!is);\n    }\n\n    {\n        REP<double> i(35.0,45.7);\n        std::istringstream is(\"[-Inf, 1.0  00 ]\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL( i, REP<double>(35.0,45.7) );\n        BOOST_CHECK(!is);\n    }\n\n    {\n        REP<double> i(-1.0,2.0);\n        std::istringstream is(\"[1.0,-1.0]\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL( i, REP<double>(-1.0,2.0) );\n        BOOST_CHECK(!is);\n    }\n\n    {\n        REP<double> i(-0.5,4.7);\n        std::istringstream is(\"[-Inf ]\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL( i, REP<double>(-0.5,4.7) );\n        BOOST_CHECK(!is);\n    }\n\n    {\n        REP<double> i(3.5,4.7);\n        std::istringstream is(\"[Inf , INF]\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL( i, REP<double>(3.5,4.7) );\n        BOOST_CHECK(!is);\n    }\n\n    {\n        REP<double> i(3.5,4.7);\n        std::istringstream is(\"[ foo ]\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL( i, REP<double>(3.5,4.7) );\n        BOOST_CHECK(!is);\n    }\n\n    {\n        REP<double> i(3.5,4.7);\n        std::istringstream is(\"[1.0000000000000002,1.0000000000000001]\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL( i, REP<double>(3.5,4.7) );\n        BOOST_CHECK(!is);\n    }\n\n    {\n        REP<double> i(3.5,4.7);\n        std::istringstream is(\"[10000000000000001/10000000000000000,10000000000000002/10000000000000001]\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL( i, REP<double>(3.5,4.7) );\n        BOOST_CHECK(!is);\n    }\n\n    {\n        REP<double> i(3.5,4.7);\n        std::istringstream is(\"[0x1.00000000000002p0,0x1.00000000000001p0]\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL( i, REP<double>(3.5,4.7) );\n        BOOST_CHECK(!is);\n    }\n}\n\n\nBOOST_AUTO_TEST_CASE(minimal_uncertain_interval_dec_input_test)\n{\n    {\n        REP_DEC<double> di;\n        std::istringstream is(\"0.0?\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL(di, REP_DEC<double>(REP<double>(-0.05,0.05),DEC::com));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP_DEC<double> di;\n        std::istringstream is(\"0.0?u_trv\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL(di, REP_DEC<double>(REP<double>(0.0,0.05),DEC::trv));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP_DEC<double> di;\n        std::istringstream is(\"0.0?d_dac\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL(di, REP_DEC<double>(REP<double>(-0.05,0.0),DEC::dac));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP_DEC<double> di;\n        std::istringstream is(\"2.5?\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL(di, REP_DEC<double>(REP<double>(std::stod(\"0x1.3999999999999p+1\"),std::stod(\"0x1.4666666666667p+1\")),DEC::com));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP_DEC<double> di;\n        std::istringstream is(\"2.5?u\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL(di, REP_DEC<double>(REP<double>(2.5,std::stod(\"0x1.4666666666667p+1\")),DEC::com));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP_DEC<double> di;\n        std::istringstream is(\"2.5?d_trv\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL(di, REP_DEC<double>(REP<double>(std::stod(\"0x1.3999999999999p+1\"),2.5),DEC::trv));\n        BOOST_CHECK(is);\n    }\n\n\n    {\n        REP_DEC<double> di;\n        std::istringstream is(\"0.000?5\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL(di, REP_DEC<double>(REP<double>(-0.005,0.005),DEC::com));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP_DEC<double> di;\n        std::istringstream is(\"0.000?5u_def\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL(di, REP_DEC<double>(REP<double>(0.0,0.005),DEC::def));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP_DEC<double> di;\n        std::istringstream is(\"0.000?5d\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL(di, REP_DEC<double>(REP<double>(-0.005,0.0),DEC::com));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP_DEC<double> di;\n        std::istringstream is(\"2.500?5\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL(di, REP_DEC<double>(REP<double>(std::stod(\"0x1.3f5c28f5c28f5p+1\"),std::stod(\"0x1.40a3d70a3d70bp+1\")),DEC::com));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP_DEC<double> di;\n        std::istringstream is(\"2.500?5u\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL(di, REP_DEC<double>(REP<double>(2.5,std::stod(\"0x1.40a3d70a3d70bp+1\")),DEC::com));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP_DEC<double> di;\n        std::istringstream is(\"2.500?5d\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL(di, REP_DEC<double>(REP<double>(std::stod(\"0x1.3f5c28f5c28f5p+1\"),2.5),DEC::com));\n        BOOST_CHECK(is);\n    }\n\n\n    {\n        REP_DEC<double> di;\n        std::istringstream is(\"0.0??_dac\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL(di, REP_DEC<double>(REP<double>(-INF_D,INF_D),DEC::dac));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP_DEC<double> di;\n        std::istringstream is(\"0.0??u_trv\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL(di, REP_DEC<double>(REP<double>(0.0,INF_D),DEC::trv));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP_DEC<double> di;\n        std::istringstream is(\"0.0??d\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL(di, REP_DEC<double>(REP<double>(-INF_D,0.0),DEC::dac));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP_DEC<double> di;\n        std::istringstream is(\"5?\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL(di, REP_DEC<double>(REP<double>(4.5,5.5),DEC::com));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP_DEC<double> di;\n        std::istringstream is(\"5?d\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL(di, REP_DEC<double>(REP<double>(4.5,5.0),DEC::com));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP_DEC<double> di;\n        std::istringstream is(\"5?u\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL(di, REP_DEC<double>(REP<double>(5.0,5.5),DEC::com));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP_DEC<double> di;\n        std::istringstream is(\"-5?\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL(di, REP_DEC<double>(REP<double>(-5.5,-4.5),DEC::com));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP_DEC<double> di;\n        std::istringstream is(\"-5?d\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL(di, REP_DEC<double>(REP<double>(-5.5,-5.0),DEC::com));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP_DEC<double> di;\n        std::istringstream is(\"-5?u\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL(di, REP_DEC<double>(REP<double>(-5.0,-4.5),DEC::com));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP_DEC<double> di;\n        std::istringstream is(\"2.5??\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL(di, REP_DEC<double>(REP<double>(-INF_D,INF_D),DEC::dac));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP_DEC<double> di;\n        std::istringstream is(\"2.5??u_def\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL(di, REP_DEC<double>(REP<double>(2.5,INF_D),DEC::def));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP_DEC<double> di;\n        std::istringstream is(\"2.5??d_dac\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL(di, REP_DEC<double>(REP<double>(-INF_D,2.5),DEC::dac));\n        BOOST_CHECK(is);\n    }\n\n\n    {\n        REP_DEC<double> di;\n        std::istringstream is(\"2.500?5e+27\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL(di, REP_DEC<double>(REP<double>(std::stod(\"0x1.01fa19a08fe7fp+91\"),std::stod(\"0x1.0302cc4352683p+91\")),DEC::com));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP_DEC<double> di;\n        std::istringstream is(\"2.500?5ue4_def\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL(di, REP_DEC<double>(REP<double>(std::stod(\"0x1.86ap+14\"),std::stod(\"0x1.8768p+14\")),DEC::def));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP_DEC<double> di;\n        std::istringstream is(\"2.500?5de-5\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL(di, REP_DEC<double>(REP<double>(std::stod(\"0x1.a2976f1cee4d5p-16\"),std::stod(\"0x1.a36e2eb1c432dp-16\")),DEC::com));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP_DEC<double> di;\n        std::string rep = \"10?18\";\n        rep += std::string(308, '0');\n        rep += \"_com\";\n        std::stringstream is(rep);\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL(di, REP_DEC<double>(REP<double>(-INF_D,INF_D),DEC::dac));\n        BOOST_CHECK(is);\n    }\n\n\n    {\n        REP_DEC<double> di;\n        std::istringstream is(\"10?3_com\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL(di, REP_DEC<double>(REP<double>(7.0,13.0),DEC::com));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP_DEC<double> di;\n        std::istringstream is(\"10?3e380_com\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL(di, REP_DEC<double>(REP<double>(MAX_D,INF_D),DEC::dac));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP_DEC<double> di(REP<double>(-3.3,10.01),DEC::com);\n        std::istringstream is(\"5\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL(di, REP_DEC<double>(REP<double>(-3.3,10.01),DEC::com));\n        BOOST_CHECK(!is);\n    }\n\n    {\n        REP_DEC<double> di(REP<double>(-3.7,0.01),DEC::def);\n        std::istringstream is(\"0.0??_com\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL(di, REP_DEC<double>(REP<double>(-3.7,0.01),DEC::def));\n        BOOST_CHECK(!is);\n    }\n\n    {\n        REP_DEC<double> di(REP<double>(3.7,12.4),DEC::trv);\n        std::istringstream is(\"0.0??u_ill\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL(di, REP_DEC<double>(REP<double>(3.7,12.4),DEC::trv));\n        BOOST_CHECK(!is);\n    }\n\n    {\n        REP_DEC<double> di(REP<double>(-3.3,10.01),DEC::com);\n        std::istringstream is(\"0.0??d_com\");\n        F<double>::operator_text_to_interval(is, di);\n        BOOST_CHECK_EQUAL(di, REP_DEC<double>(REP<double>(-3.3,10.01),DEC::com));\n        BOOST_CHECK(!is);\n    }\n\n    {\n        REP_DEC<double> di(REP<double>(-3.3,10.01),DEC::com);\n        std::istringstream is(\"0.0?22d_cm\");\n        is.exceptions(is.eofbit);\n        BOOST_CHECK_THROW(F<double>::operator_text_to_interval(is, di), std::ios_base::failure);\n        BOOST_CHECK_EQUAL(di, REP_DEC<double>(REP<double>(-3.3,10.01),DEC::com));\n        BOOST_CHECK(!is);\n    }\n}\n\n\n\n\nBOOST_AUTO_TEST_CASE(minimal_uncertain_interval_input_test)\n{\n    {\n        REP<double> i;\n        std::istringstream is(\"0.0?\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL(i, REP<double>(-0.05,0.05));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP<double> i;\n        std::istringstream is(\"0.0?u_trv\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL(i, REP<double>(0.0,0.05));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP<double> i;\n        std::istringstream is(\"0.0?d_dac\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL(i, REP<double>(-0.05,0.0));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP<double> i;\n        std::istringstream is(\"2.5?\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL(i, REP<double>(std::stod(\"0x1.3999999999999p+1\"),std::stod(\"0x1.4666666666667p+1\")));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP<double> i;\n        std::istringstream is(\"2.5?u\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL(i, REP<double>(2.5,std::stod(\"0x1.4666666666667p+1\")));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP<double> i;\n        std::istringstream is(\"2.5?d_trv\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL(i, REP<double>(std::stod(\"0x1.3999999999999p+1\"),2.5));\n        BOOST_CHECK(is);\n    }\n\n\n    {\n        REP<double> i;\n        std::istringstream is(\"0.000?5\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL(i, REP<double>(-0.005,0.005));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP<double> i;\n        std::istringstream is(\"0.000?5u_def\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL(i, REP<double>(0.0,0.005));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP<double> i;\n        std::istringstream is(\"0.000?5d\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL(i, REP<double>(-0.005,0.0));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP<double> i;\n        std::istringstream is(\"2.500?5\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL(i, REP<double>(std::stod(\"0x1.3f5c28f5c28f5p+1\"),std::stod(\"0x1.40a3d70a3d70bp+1\")));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP<double> i;\n        std::istringstream is(\"2.500?5u\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL(i, REP<double>(2.5,std::stod(\"0x1.40a3d70a3d70bp+1\")));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP<double> i;\n        std::istringstream is(\"2.500?5d\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL(i, REP<double>(std::stod(\"0x1.3f5c28f5c28f5p+1\"),2.5));\n        BOOST_CHECK(is);\n    }\n\n\n    {\n        REP<double> i;\n        std::istringstream is(\"0.0??_dac\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL(i, REP<double>(-INF_D,INF_D));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP<double> i;\n        std::istringstream is(\"0.0??u_trv\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL(i, REP<double>(0.0,INF_D));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP<double> i;\n        std::istringstream is(\"0.0??d\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL(i, REP<double>(-INF_D,0.0));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP<double> i;\n        std::istringstream is(\"2.5??\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL(i, REP<double>(-INF_D,INF_D));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP<double> i;\n        std::istringstream is(\"2.5??u_def\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL(i, REP<double>(2.5,INF_D));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP<double> i;\n        std::istringstream is(\"2.5??d_dac\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL(i, REP<double>(-INF_D,2.5));\n        BOOST_CHECK(is);\n    }\n\n\n    {\n        REP<double> i;\n        std::istringstream is(\"2.500?5e+27\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL(i, REP<double>(std::stod(\"0x1.01fa19a08fe7fp+91\"),std::stod(\"0x1.0302cc4352683p+91\")));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP<double> i;\n        std::istringstream is(\"2.500?5ue4_def\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL(i, REP<double>(std::stod(\"0x1.86ap+14\"),std::stod(\"0x1.8768p+14\")));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP<double> i;\n        std::istringstream is(\"2.500?5de-5\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL(i, REP<double>(std::stod(\"0x1.a2976f1cee4d5p-16\"),std::stod(\"0x1.a36e2eb1c432dp-16\")));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP<double> i;\n        std::string rep = \"10?18\";\n        rep += std::string(308, '0');\n        rep += \"_com\";\n        std::stringstream is(rep);\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL(i, REP<double>(-INF_D,INF_D));\n        BOOST_CHECK(is);\n    }\n\n\n    {\n        REP<double> i;\n        std::istringstream is(\"10?3_com\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL(i, REP<double>(7.0,13.0));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP<double> i;\n        std::istringstream is(\"10?3e380_com\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL(i, REP<double>(MAX_D,INF_D));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP<double> i;\n        std::istringstream is(\"1.0000000000000001?1\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL(i, REP<double>(1.0,std::stod(\"0x1.0000000000001p+0\")));\n        BOOST_CHECK(is);\n    }\n\n    {\n        REP<double> i(2.0,3.0);\n        std::istringstream is(\"12\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL(i, REP<double>(2.0,3.0));\n        BOOST_CHECK(!is);\n    }\n\n    {\n        REP<double> i(2.0,3.0);\n        std::istringstream is(\"0.0??_com\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL( i, REP<double>(2.0,3.0) );\n        BOOST_CHECK(!is);\n    }\n\n    {\n        REP<double> i(2.5,3.4);\n        std::istringstream is(\"0.0??u_ill\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL( i, REP<double>(2.5,3.4) );\n        BOOST_CHECK(!is);\n    }\n\n    {\n        REP<double> i(-2.0,-1.0);\n        std::istringstream is(\"0.0??d_com\");\n        F<double>::operator_text_to_interval(is, i);\n        BOOST_CHECK_EQUAL( i, REP<double>(-2.0,-1.0) );\n        BOOST_CHECK(!is);\n    }\n}\n", "meta": {"hexsha": "193ca805800c6a941d14d89b3779f642e00735cb", "size": 95652, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/p1788/flavor/infsup/setbased/test_mpfr_bin_ieee754_flavor_io.cpp", "max_stars_repo_name": "nehmeier/libieeep1788", "max_stars_repo_head_hexsha": "1f10b896ff532e95818856614ab3073189e81199", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 41.0, "max_stars_repo_stars_event_min_datetime": "2015-01-23T07:52:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T03:15:21.000Z", "max_issues_repo_path": "test/p1788/flavor/infsup/setbased/test_mpfr_bin_ieee754_flavor_io.cpp", "max_issues_repo_name": "nehmeier/libieeep1788", "max_issues_repo_head_hexsha": "1f10b896ff532e95818856614ab3073189e81199", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 25.0, "max_issues_repo_issues_event_min_datetime": "2015-01-25T16:13:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-14T12:05:08.000Z", "max_forks_repo_path": "test/p1788/flavor/infsup/setbased/test_mpfr_bin_ieee754_flavor_io.cpp", "max_forks_repo_name": "nehmeier/libieeep1788", "max_forks_repo_head_hexsha": "1f10b896ff532e95818856614ab3073189e81199", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-02-22T11:06:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-23T09:57:32.000Z", "avg_line_length": 36.0678733032, "max_line_length": 140, "alphanum_fraction": 0.6105047464, "num_tokens": 28248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081926, "lm_q2_score": 0.6619228625116081, "lm_q1q2_score": 0.45404562679730043}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2021 Mikhail Komarov <nemo@nil.foundation>\n// Copyright (c) 2021 Nikita Kaskov <nbering@nil.foundation>\n// Copyright (c) 2022 Ilia Shirobokov <i.shirobokov@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#define BOOST_TEST_MODULE pedersen_test\n\n#include <vector>\n#include <iostream>\n#include <random>\n\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 <nil/crypto3/algebra/curves/bls12.hpp>\n#include <nil/crypto3/algebra/fields/arithmetic_params/bls12.hpp>\n#include <nil/crypto3/algebra/random_element.hpp>\n#include <nil/crypto3/algebra/fields/bls12/base_field.hpp>\n#include <nil/crypto3/algebra/fields/bls12/scalar_field.hpp>\n\n#include <nil/crypto3/math/polynomial/polynomial.hpp>\n\n#include <nil/crypto3/zk/commitments/polynomial/pedersen.hpp>\n\nusing namespace nil::crypto3;\n\nBOOST_AUTO_TEST_SUITE(pedersen_test_suite)\n\nBOOST_AUTO_TEST_CASE(pedersen_basic_test) {\n\n    // setup\n    using curve_type = algebra::curves::bls12<381>;\n    using curve_group_type = curve_type::template g1_type<>;\n    using field_type = typename curve_type::scalar_field_type;\n\n    constexpr static const int n = 50;\n    constexpr static const int k = 26;\n    static curve_group_type::value_type g = algebra::random_element<curve_group_type>();\n    static curve_group_type::value_type h = algebra::random_element<curve_group_type>();\n    while (g == h) {\n        h = algebra::random_element<curve_group_type>();\n    }\n\n    typedef typename zk::commitments::pedersen<curve_type> pedersen_type;\n\n    typedef typename pedersen_type::proof_type proof_type;\n    typedef typename pedersen_type::params_type params_type;\n\n    params_type params;\n\n    params.n = n;\n    params.k = k;\n    params.g = g;\n    params.h = h;\n\n    BOOST_CHECK(g != h);\n    BOOST_CHECK(n >= k);\n    BOOST_CHECK(k > 0);\n\n    // commit\n    constexpr static const field_type::value_type w = field_type::value_type(37684);\n\n    // eval\n    proof_type proof = pedersen_type::proof_eval(params, w);\n\n    // verify\n    BOOST_CHECK(pedersen_type::verify_eval(params, proof));\n\n    std::vector<int> idx;\n    std::vector<int> idx_base;\n    for (int i = 1; i <= n; ++i) {\n        idx_base.push_back(i);\n    }\n    std::random_device rd;\n    std::mt19937 gen(rd());\n    std::shuffle(idx_base.begin(), idx_base.end(), gen);\n    for (int i = 0; i < k; ++i) {\n        idx.push_back(idx_base[i]);\n    }\n    \n    BOOST_CHECK(idx.size() >= k);\n    field_type::value_type secret = pedersen_type::message_eval(params, proof, idx);\n    BOOST_CHECK(w == secret);\n}\n\nBOOST_AUTO_TEST_CASE(pedersen_short_test) {\n\n    // setup\n    using curve_type = algebra::curves::bls12<381>;\n    using curve_group_type = curve_type::template g1_type<>;\n    using field_type = typename curve_type::scalar_field_type;\n\n    constexpr static const int n = 2;\n    constexpr static const int k = 1;\n    static curve_group_type::value_type g = algebra::random_element<curve_group_type>();\n    static curve_group_type::value_type h = algebra::random_element<curve_group_type>();\n    while (g == h) {\n        h = algebra::random_element<curve_group_type>();\n    }\n\n    typedef typename zk::commitments::pedersen<curve_type> pedersen_type;\n\n    typedef typename pedersen_type::proof_type proof_type;\n    typedef typename pedersen_type::params_type params_type;\n\n    params_type params;\n\n    params.n = n;\n    params.k = k;\n    params.g = g;\n    params.h = h;\n\n    BOOST_CHECK(g != h);\n    BOOST_CHECK(n >= k);\n    BOOST_CHECK(k > 0);\n\n    // commit\n    constexpr static const field_type::value_type w = field_type::value_type(3);\n\n    // eval\n    proof_type proof = pedersen_type::proof_eval(params, w);\n\n    // verify\n    BOOST_CHECK(pedersen_type::verify_eval(params, proof));\n\n    std::vector<int> idx;\n    std::vector<int> idx_base;\n    for (int i = 1; i <= n; ++i) {\n        idx_base.push_back(i);\n    }\n    std::random_device rd;\n    std::mt19937 gen(rd());\n    std::shuffle(idx_base.begin(), idx_base.end(), gen);\n    for (int i = 0; i < k; ++i) {\n        idx.push_back(idx_base[i]);\n    }\n    \n    BOOST_CHECK(idx.size() >= k);\n    field_type::value_type secret = pedersen_type::message_eval(params, proof, idx);\n    BOOST_CHECK(w == secret);\n}\n\nBOOST_AUTO_TEST_CASE(pedersen_long_test) {\n\n    // setup\n    using curve_type = algebra::curves::bls12<381>;\n    using curve_group_type = curve_type::template g1_type<>;\n    using field_type = typename curve_type::scalar_field_type;\n\n    constexpr static const int n = 2000000000;\n    constexpr static const int k = 1999999999;\n    static curve_group_type::value_type g = algebra::random_element<curve_group_type>();\n    static curve_group_type::value_type h = algebra::random_element<curve_group_type>();\n    while (g == h) {\n        h = algebra::random_element<curve_group_type>();\n    }\n\n    typedef typename zk::commitments::pedersen<curve_type> pedersen_type;\n\n    typedef typename pedersen_type::proof_type proof_type;\n    typedef typename pedersen_type::params_type params_type;\n\n    params_type params;\n\n    params.n = n;\n    params.k = k;\n    params.g = g;\n    params.h = h;\n\n    BOOST_CHECK(g != h);\n    BOOST_CHECK(n >= k);\n    BOOST_CHECK(k > 0);\n\n    // commit\n    constexpr static const field_type::value_type w = field_type::value_type(300000000);\n\n    // eval\n    proof_type proof = pedersen_type::proof_eval(params, w);\n\n    // verify\n    BOOST_CHECK(pedersen_type::verify_eval(params, proof));\n\n    std::vector<int> idx;\n    std::vector<int> idx_base;\n    for (int i = 1; i <= n; ++i) {\n        idx_base.push_back(i);\n    }\n    std::random_device rd;\n    std::mt19937 gen(rd());\n    std::shuffle(idx_base.begin(), idx_base.end(), gen);\n    for (int i = 0; i < k; ++i) {\n        idx.push_back(idx_base[i]);\n    }\n    \n    BOOST_CHECK(idx.size() >= k);\n    field_type::value_type secret = pedersen_type::message_eval(params, proof, idx);\n    BOOST_CHECK(w == secret);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "f4397fe0b12f46ec067a6bbfa7d69b55b787c32e", "size": 7185, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/commitment/pedersen.cpp", "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/commitment/pedersen.cpp", "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/commitment/pedersen.cpp", "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": 32.2197309417, "max_line_length": 88, "alphanum_fraction": 0.6786360473, "num_tokens": 1769, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.4539548140159895}}
{"text": "//std::function< std::vector<bool> (long N)> remember this is what is being passed in!\n#include <NTL/ZZ.h>\n\n#include \"../elements/Element.hpp\"\n#include \"../algorithms/rem_forest.hpp\"\n\n#include <vector>\n#include <random>\n\nusing std::vector;\n\nvector<bool> constant_slow(long B) {\n\tlong n = 1;\n\tfor (long i = 0; i < 10*B; ++i) { n = (((n*2+17)/3-19)*5-101); } //just gibberish\n\n\tvector<bool> incidence;\n\tbool ans = (B+n)%5;\n\n\tincidence.push_back(ans);\n\treturn incidence;\n}\n\n\nvector<bool> random_zz_remtree(long B) {\n\n\tvector <Elt<NTL::ZZ> > A_rand (B);\n\tvector <Elt<NTL::ZZ> > m_rand (B);\n\n\tstd::random_device rd;\n\tstd::mt19937 mt(rd());\n\tstd::uniform_int_distribution<long> dist(1, B);\n\n\tfor(long i = 0; i < B; ++i){\n\t\t//long bitsize = log2(i+1)+2;\n\t\tA_rand[i] = dist(mt);\n\t\tm_rand[i] = dist(mt);\n\t}\n\n\tremainder_forest(A_rand, m_rand, 0, 0);\n\n\tvector<bool> ret(1);\n\treturn ret;\n}", "meta": {"hexsha": "725affb55ed44a69de3fd9470ae3cfd52518b56b", "size": 877, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/searches/benchmarks.cpp", "max_stars_repo_name": "adienes/remainder-tree", "max_stars_repo_head_hexsha": "0aa76214ab6f2a4389ec45a239ea660749989a90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/searches/benchmarks.cpp", "max_issues_repo_name": "adienes/remainder-tree", "max_issues_repo_head_hexsha": "0aa76214ab6f2a4389ec45a239ea660749989a90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/searches/benchmarks.cpp", "max_forks_repo_name": "adienes/remainder-tree", "max_forks_repo_head_hexsha": "0aa76214ab6f2a4389ec45a239ea660749989a90", "max_forks_repo_licenses": ["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.3953488372, "max_line_length": 86, "alphanum_fraction": 0.6385404789, "num_tokens": 289, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.4539548092663129}}
{"text": "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n//\n// gDLS*: Generalized Pose-and-Scale Estimation Given Scale and Gravity Priors\n//\n// Victor Fragoso, Joseph DeGol, Gang Hua.\n// Proc. of the IEEE/CVF Conf. on Computer Vision and Pattern Recognition 2020.\n//\n// Please contact the author of this library if you have any questions.\n// Author: Victor Fragoso (victor.fragoso@microsoft.com)\n\n#include \"gdls_star/gdls_star.h\"\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#include <glog/logging.h>\n\n#include <cmath>\n#include <complex>\n#include <utility>\n#include <vector>\n\n#include \"math/alignment.h\"\n#include \"math/utils.h\"\n#include \"upnp/build_upnp_action_matrix_using_symmetry.h\"\n\nnamespace msft {\nnamespace {\n// Useful aliases.\nusing Matrix3x10d = Eigen::Matrix<double, 3, 10>;\nusing Matrix10d = Eigen::Matrix<double, 10, 10>;\nusing Matrix8cd = Eigen::Matrix<std::complex<double>, 8, 8>;\nusing Matrix8d = Eigen::Matrix<double, 8, 8>;\nusing RowVector10d = Eigen::Matrix<double, 1, 10>;\nusing Vector10d = Eigen::Matrix<double, 10, 1>;\n\nusing CostParameters = GdlsStar::CostParameters;\nusing Input = GdlsStar::Input;\nusing Priors = GdlsStar::Priors;\nusing Solution = GdlsStar::Solution;\n\nconstexpr int kNumMaxRotationsExploitingSymmetry = 8;\n\n// Computes the skew-symmetric matrix to compute the cross product.\ninline Eigen::Matrix3d\nComputeSkewSymmetricMatrix(const Eigen::Vector3d& vector) {\n  Eigen::Matrix3d skew_symmetric_matrix;\n  skew_symmetric_matrix.setZero();\n  skew_symmetric_matrix(0, 1) = -vector.z();\n  skew_symmetric_matrix(1, 0) = vector.z();\n  skew_symmetric_matrix(0, 2) = vector.y();\n  skew_symmetric_matrix(2, 0) = -vector.y();\n  skew_symmetric_matrix(1, 2) = -vector.x();\n  skew_symmetric_matrix(2, 1) = vector.x();\n  return skew_symmetric_matrix;\n}\n\n// This function arranges a 3D point into a 3x10 matrix so that we can\n// rotate a point using the rotation expressed as a function of the monomials.\n// See Eq. xxiv of the gDLS* supplemental material.\nMatrix3x10d LeftMultiply(const Eigen::Vector3d& point) {\n  Matrix3x10d phi_mat;\n  // Row 0.\n  phi_mat(0, 0) = point.x();\n  phi_mat(0, 1) = point.x();\n  phi_mat(0, 2) = -point.x();\n  phi_mat(0, 3) = -point.x();\n  phi_mat(0, 4) = 0.0;\n  phi_mat(0, 5) = 2 * point.z();\n  phi_mat(0, 6) = -2 * point.y();\n  phi_mat(0, 7) = 2 * point.y();\n  phi_mat(0, 8) = 2 * point.z();\n  phi_mat(0, 9) = 0.0;\n\n  // Row 1.\n  phi_mat(1, 0) = point.y();\n  phi_mat(1, 1) = -point.y();\n  phi_mat(1, 2) = point.y();\n  phi_mat(1, 3) = -point.y();\n  phi_mat(1, 4) = -2.0 * point.z();\n  phi_mat(1, 5) = 0.0;\n  phi_mat(1, 6) = 2 * point.x();\n  phi_mat(1, 7) = 2 * point.x();\n  phi_mat(1, 8) = 0.0;\n  phi_mat(1, 9) = 2 * point.z();\n\n  // Row 3.\n  phi_mat(2, 0) = point.z();\n  phi_mat(2, 1) = -point.z();\n  phi_mat(2, 2) = -point.z();\n  phi_mat(2, 3) = point.z();\n  phi_mat(2, 4) = 2.0 * point.y();\n  phi_mat(2, 5) = -2.0 * point.x();\n  phi_mat(2, 6) = 0.0;\n  phi_mat(2, 7) = 0.0;\n  phi_mat(2, 8) = 2.0 * point.x();\n  phi_mat(2, 9) = 2.0 * point.y();\n  return phi_mat;\n}\n\n// Check that the input to gDLS* is valid. It checks the inputs have the same\n// sizes and that the prior scales are valid.\ninline void IsInputDatumValid(const Input& input) {\n  CHECK_EQ(input.ray_origins.size(), input.ray_directions.size());\n  CHECK_EQ(input.ray_origins.size(), input.world_points.size());\n  CHECK_GE(input.priors.scale_penalty, 0.0);\n  CHECK_GE(input.priors.gravity_penalty, 0.0);\n}\n\nEigen::Matrix4d ComputeHMatrix(\n    const std::vector<Eigen::Vector3d>& ray_origins,\n    const std::vector<Eigen::Vector3d>& ray_directions,\n    const double scale_penalty_factor) {\n  Eigen::Matrix4d h_inverse = Eigen::Matrix4d::Zero();\n  for (size_t i = 0; i < ray_directions.size(); ++i) {\n    // Computing the scalar in the top-left corner of matrix H^-1.\n    h_inverse(0, 0) +=\n        ray_origins[i].squaredNorm() -\n        ray_origins[i].dot(ray_directions[i]) *\n        ray_origins[i].dot(ray_directions[i]);\n\n    // Computing the 3x1 row-vector of the top-right part of matrix H^-1.\n    const Eigen::Vector3d temp_term =\n        ray_origins[i].dot(ray_directions[i]) * ray_directions[i] -\n        ray_origins[i];\n    h_inverse.block<3, 1>(1, 0) += temp_term;\n\n    // Computing the 1x3 vector of the bottom-left part of matrix H^-1.\n    h_inverse.block<1, 3>(0, 1) += temp_term.transpose();\n\n    // Bottom right 3x3 block of matrix H^-1.\n    h_inverse.block<3, 3>(1, 1) +=\n        Eigen::Matrix3d::Identity() -\n        (ray_directions[i] * ray_directions[i].transpose());\n  }\n\n  // Add the scale penalty term to the first entry of h_inverse.\n  h_inverse(0, 0) += scale_penalty_factor;\n\n  const Eigen::Matrix4d h_matrix = h_inverse.inverse();\n\n  return h_matrix;\n}\n\n// Compute the the matrix F in Eq. xiv i the supplemental material of gDLS*.\n// This matrix is F = -B * H.\nEigen::MatrixXd ComputeFMat(\n    const std::vector<Eigen::Vector3d>& ray_origins,\n    const std::vector<Eigen::Vector3d>& ray_directions,\n    const Eigen::Matrix4d& h_matrix) {\n  const int num_points = ray_origins.size();\n  Eigen::MatrixXd f_mat(num_points, 4);\n  Eigen::RowVector4d helper_vec;\n  for (size_t i = 0; i < num_points; ++i) {\n    // Scalar term: -r_i' c_i.\n    helper_vec[0] = -ray_directions[i].dot(ray_origins[i]);\n    // Vector term: r'.\n    helper_vec.tail(3) = ray_directions[i].transpose();\n    // Computing i-th row of matrix F.\n    f_mat.block(i, 0, 1, 4) = helper_vec * h_matrix;\n  }\n  return f_mat;\n}\n\nvoid ComputeScaleAndTranslationFactors(const Input& input,\n                                       const Eigen::Matrix4d& h_matrix,\n                                       RowVector10d* scale_factor,\n                                       Matrix3x10d* translation_factor) {\n  // Useful aliases.\n  const std::vector<Eigen::Vector3d>& ray_origins = input.ray_origins;\n  const std::vector<Eigen::Vector3d>& ray_directions = input.ray_directions;\n  const std::vector<Eigen::Vector3d>& world_points = input.world_points;\n  const size_t num_correspondences = ray_directions.size();\n  Eigen::Matrix<double, 4, 10> sv_helper = Eigen::Matrix<double, 4, 10>::Zero();\n  for (size_t i = 0; i < num_correspondences; ++i) {\n    const Matrix3x10d left_multiply_matrix = LeftMultiply(world_points[i]);\n    // Scale factor.\n    sv_helper.row(0) +=\n        (ray_origins[i].transpose() - ray_origins[i].dot(ray_directions[i]) *\n         ray_directions[i].transpose()) * left_multiply_matrix;\n\n    // Translation factor.\n    sv_helper.block<3, 10>(1, 0) +=\n        (ray_directions[i] * ray_directions[i].transpose() -\n         Eigen::Matrix3d::Identity()) * left_multiply_matrix;\n  }\n\n  sv_helper = h_matrix * sv_helper;\n  *scale_factor = sv_helper.row(0);\n  *translation_factor = sv_helper.block<3, 10>(1, 0);\n}\n\n// Computes vector k_i from the scale-constrained gDLS.\ninline Eigen::Vector3d ComputeLinearTermPerPoint(\n    const int point_idx,\n    const Eigen::Matrix4d& h_matrix,\n    const Eigen::MatrixXd& f_matrix,\n    const Eigen::Vector3d& ray_origin,\n    const Eigen::Vector3d& ray_direction,\n    const Priors& priors) {\n  // Scale linear term.\n  const Eigen::Vector3d scalar_linear_term =\n      f_matrix(point_idx, 0) * ray_direction - h_matrix.col(0).tail(3) +\n      h_matrix(0, 0) * ray_origin;\n\n  // Compute total linear term.\n  const Eigen::Vector3d linear_term =\n      priors.scale_prior * priors.scale_penalty * scalar_linear_term;\n  return linear_term;\n}\n\nMatrix10d\nComputeQuadraticPenaltyMatrixFromGravityRegularizer(const Input& input,\n                                                    double penalty) {\n  // Compute the left-multiply matrix for gravity index.\n  const Matrix3x10d world_gravity_dir_matrix =\n      LeftMultiply(input.priors.world_down_direction.normalized());\n  const Eigen::Vector3d query_gravity_dir =\n      input.priors.query_down_direction.normalized();\n  const Eigen::Matrix3d query_down_dir_mat =\n      ComputeSkewSymmetricMatrix(query_gravity_dir);\n  // M = penalty * L(g_I)' * Cross(g_Q)^T * Cross(g_Q) L(g_I),\n  // L() is the left-multiply function, and Cross() is the skew-symmetric\n  // matrix for cross product. Here g indicates gravity direction according\n  // to Q (query) and I (reference).\n  const Matrix10d penalty_matrix =\n      penalty * world_gravity_dir_matrix.transpose() *\n      query_down_dir_mat.transpose() *\n      query_down_dir_mat * world_gravity_dir_matrix;\n  return penalty_matrix;\n}\n\ninline Matrix10d ComputeQuadraticPenaltiesFromScaleConstraint(\n    const double scale_penalty,\n    const RowVector10d& scale_factor) {\n  return scale_penalty * scale_factor.transpose() * scale_factor;\n}\n\ninline Vector10d ComputeLinearPenaltiesFromScaleConstraint(\n    const Priors& priors,\n    const Eigen::Matrix4d& h_matrix,\n    const RowVector10d& scale_factor) {\n  const double& scale_prior = priors.scale_prior;\n  const double& scale_penalty = priors.scale_penalty;\n  const double scalar =\n      scale_penalty * scale_prior * h_matrix(0, 0) - scale_prior;\n  return scale_penalty * scalar * scale_factor;\n}\n\ninline double ComputeConstantTermFromScaleConstraint(\n    const Priors& priors,\n    const Eigen::Matrix4d& h_matrix) {\n  const double& scale_penalty = priors.scale_penalty;\n  const double& scale_prior = priors.scale_prior;\n  const double scale_term =\n      scale_penalty * scale_prior * h_matrix(0, 0) - scale_prior;\n  const double term = scale_term * scale_term;\n  return scale_penalty * term;\n}\n\n// The observed pattern is that duplicate rotations appear consequtively in the\n// vector, i.e., rotation[i] == rotation[i + 1] is common.\nstd::vector<Eigen::Quaterniond> RemoveDuplicateRotations(\n    const std::vector<Eigen::Quaterniond>& candidate_rotations) {\n  const double kAngleThreshold = DegToRad(0.1);\n  std::vector<Eigen::Quaterniond> rotations;\n  rotations.reserve(candidate_rotations.size());\n\n  // If no rotations then return empty vector.\n  if (candidate_rotations.empty()) {\n    return rotations;\n  }\n\n  for (int i = 0; i < candidate_rotations.size(); ++i) {\n    bool duplicate_rotation = false;\n    const Eigen::Quaterniond& candidate_rotation = candidate_rotations[i];\n    for (int j = rotations.size() - 1; j >= 0; --j) {\n      if (candidate_rotation.angularDistance(rotations[j]) < kAngleThreshold) {\n        duplicate_rotation = true;\n        break;\n      }\n    }\n    if (!duplicate_rotation) {\n      rotations.push_back(candidate_rotation);\n    }\n  }\n  return rotations;\n}\n\n// Constructs the vector s as indicated in Eq. 13 of gDLS* main paper.\ninline Vector10d ComputeRotationVector(const Eigen::Quaterniond& rotation) {\n  Vector10d rotation_vector;\n  // Set the values of the rotation vector.\n  rotation_vector[0] = rotation.w() * rotation.w();\n  rotation_vector[1] = rotation.x() * rotation.x();\n  rotation_vector[2] = rotation.y() * rotation.y();\n  rotation_vector[3] = rotation.z() * rotation.z();\n  rotation_vector[4] = rotation.w() * rotation.x();\n  rotation_vector[5] = rotation.w() * rotation.y();\n  rotation_vector[6] = rotation.w() * rotation.z();\n  rotation_vector[7] = rotation.x() * rotation.y();\n  rotation_vector[8] = rotation.x() * rotation.z();\n  rotation_vector[9] = rotation.y() * rotation.z();\n  return rotation_vector;\n}\n\nstd::vector<Eigen::Vector3d> ComputeScalesAndTranslations(\n    const std::vector<Eigen::Quaterniond>& rotations,\n    const Matrix3x10d& translation_factor,\n    const Input& input,\n    const Eigen::Matrix4d& h_matrix,\n    const RowVector10d& scale_factor,\n    std::vector<double>* scales) {\n  // Solve for translation as a function of rotation.\n  std::vector<Eigen::Vector3d> translations;\n  translations.reserve(rotations.size());\n  CHECK_NOTNULL(scales)->reserve(rotations.size());\n  const double& scale_penalty = input.priors.scale_penalty;\n  for (const Eigen::Quaterniond& rotation : rotations) {\n    const Vector10d rotationVector = ComputeRotationVector(rotation);\n    translations.emplace_back(\n        translation_factor * rotationVector +\n        scale_penalty * input.priors.scale_prior * h_matrix.col(0).tail(3));\n    scales->emplace_back(\n        scale_factor * rotationVector +\n        scale_penalty * input.priors.scale_prior * h_matrix(0, 0));\n  }\n  return translations;\n}\n\nvoid DiscardBadSolutions(const Input& input_datum, Solution* solution) {\n  // Useful aliases.\n  std::vector<Eigen::Quaterniond>& solution_rotations = solution->rotations;\n  std::vector<Eigen::Vector3d>& solution_translations = solution->translations;\n  std::vector<double>& solution_scales = solution->scales;\n  CHECK_EQ(solution_rotations.size(), solution_translations.size());\n  CHECK_EQ(solution_rotations.size(), solution_scales.size());\n  std::vector<Eigen::Quaterniond> final_rotations;\n  std::vector<Eigen::Vector3d> final_translations;\n  std::vector<double> final_scales;\n  final_rotations.reserve(solution_rotations.size());\n  final_translations.reserve(solution_translations.size());\n  final_scales.reserve(solution_scales.size());\n\n  const std::vector<Eigen::Vector3d>& world_points = input_datum.world_points;\n  const std::vector<Eigen::Vector3d>& ray_origins = input_datum.ray_origins;\n  const std::vector<Eigen::Vector3d>& ray_directions =\n      input_datum.ray_directions;\n\n  // For every computed solution, check that points are in front of camera.\n  for (int i = 0; i < solution_rotations.size(); ++i) {\n    const Eigen::Quaterniond& soln_rotation = solution_rotations[i];\n    const Eigen::Vector3d& soln_translation = solution_translations[i];\n    const double scale = solution_scales[i];\n\n    // Check that all points are in front of the camera. Discard the solution\n    // if this is not the case.\n    bool all_points_in_front_of_camera = true;\n\n    for (int j = 0; j < world_points.size(); ++j) {\n      const Eigen::Vector3d transformed_point =\n          soln_rotation * world_points[j] + soln_translation -\n          scale * ray_origins[j];\n\n      // Find the rotation that puts the image ray at unit Z direction.\n      const Eigen::Quaterniond unrot =\n          Eigen::Quaterniond::FromTwoVectors(ray_directions[j],\n                                             Eigen::Vector3d::UnitZ());\n\n      // Rotate the transformed point and check if the z coordinate is\n      // negative. This will indicate if the point is projected behind the\n      // camera.\n      const Eigen::Vector3d rotated_projection = unrot * transformed_point;\n      if (rotated_projection.z() < 0) {\n        all_points_in_front_of_camera = false;\n        break;\n      }\n    }\n\n    if (all_points_in_front_of_camera) {\n      final_rotations.emplace_back(soln_rotation);\n      final_translations.emplace_back(soln_translation);\n      final_scales.push_back(scale);\n    }\n  }\n\n  // Set the final solutions.\n  std::swap(solution_rotations, final_rotations);\n  std::swap(solution_translations, final_translations);\n  std::swap(solution_scales, final_scales);\n}\n\n}  // namespace\n\nvoid GdlsStar::ComputeHelperMatrices(const Input& input) {\n  // Compute helper matrices.\n  // Compute H matrix from.\n  helper_matrices_.h_matrix =\n      ComputeHMatrix(input.ray_origins,\n                     input.ray_directions,\n                     input.priors.scale_penalty);\n\n  // Compute the F matrix, they are needed for the translation prior part.\n  helper_matrices_.f_matrix = ComputeFMat(input.ray_origins,\n                                          input.ray_directions,\n                                          helper_matrices_.h_matrix);\n\n  // Compute scale and translation factors.\n  ComputeScaleAndTranslationFactors(input,\n                                    helper_matrices_.h_matrix,\n                                    &helper_matrices_.scale_factor,\n                                    &helper_matrices_.translation_factor);\n}\n\nvoid GdlsStar::ComputeLeastSquaresCostParameters(const Input& input) {\n  // Useful aliases.\n  const std::vector<Eigen::Vector3d>& ray_origins = input.ray_origins;\n  const std::vector<Eigen::Vector3d>& ray_directions = input.ray_directions;\n  const std::vector<Eigen::Vector3d>& world_points = input.world_points;\n  const size_t num_correspondences = ray_directions.size();\n\n  cost_params_.quadratic_penalty_mat.setZero();\n  cost_params_.linear_penalty_vector.setZero();\n  cost_params_.gamma = 0.0;\n  for (int i = 0; i < num_correspondences; ++i) {\n    // Compute the quadratic term per point.\n    const Matrix3x10d left_multiply_matrix = LeftMultiply(world_points[i]);\n    const Matrix3x10d cost_coeff_term =\n        (ray_directions[i] * ray_directions[i].transpose() -\n         Eigen::Matrix3d::Identity()) *\n        (LeftMultiply(world_points[i]) -\n         ray_origins[i] * helper_matrices_.scale_factor +\n         helper_matrices_.translation_factor);\n    cost_params_.quadratic_penalty_mat +=\n        cost_coeff_term.transpose() * cost_coeff_term;\n\n    // Compute the linear term per point as calculated in Eq. 22 of scale and\n    // gravity constrained gdls.\n    const Eigen::Vector3d scalar_penalty_vector =\n        ComputeLinearTermPerPoint(i,\n                                  helper_matrices_.h_matrix,\n                                  helper_matrices_.f_matrix,\n                                  ray_origins[i],\n                                  ray_directions[i],\n                                  input.priors);\n    cost_params_.linear_penalty_vector +=\n        scalar_penalty_vector.transpose() * cost_coeff_term;\n\n    // Compute the constant term per point.\n    cost_params_.gamma += scalar_penalty_vector.dot(scalar_penalty_vector);\n  }\n\n  // Add penalties for gravity constraints.\n  if (input.priors.gravity_penalty > 0.0) {\n    cost_params_.quadratic_penalty_mat +=\n        ComputeQuadraticPenaltyMatrixFromGravityRegularizer(\n            input, input.priors.gravity_penalty);\n  }\n\n  // Add penalties for scale constraints.\n  if (input.priors.scale_penalty > 0.0) {\n    cost_params_.quadratic_penalty_mat +=\n        ComputeQuadraticPenaltiesFromScaleConstraint(\n            input.priors.scale_penalty,\n            helper_matrices_.scale_factor);\n    cost_params_.linear_penalty_vector +=\n        ComputeLinearPenaltiesFromScaleConstraint(\n            input.priors,\n            helper_matrices_.h_matrix,\n            helper_matrices_.scale_factor);\n    cost_params_.gamma +=\n        ComputeConstantTermFromScaleConstraint(\n            input.priors,\n            helper_matrices_.h_matrix);\n  }\n}\n\nCostParameters GdlsStar::ComputeCostParameters(const Input& input) {\n  // Validate input.\n  IsInputDatumValid(input);\n\n  // Compute all the helper matrices.\n  ComputeHelperMatrices(input);\n\n  // Compute the least squares cost parameters.\n  ComputeLeastSquaresCostParameters(input);\n\n  return cost_params_;\n}\n\nstd::vector<Eigen::Quaterniond> GdlsStar::EstimateRotations() {\n  std::vector<Eigen::Quaterniond> rotations(kNumMaxRotationsExploitingSymmetry);\n  // Build action matrix.\n  const Matrix8d action_matrix = theia::BuildActionMatrixUsingSymmetry(\n      cost_params_.quadratic_penalty_mat,\n      cost_params_.linear_penalty_vector,\n      &template_matrix_);\n\n  const Eigen::EigenSolver<Matrix8d> eigen_solver(action_matrix);\n  const Matrix8cd eigen_vectors = eigen_solver.eigenvectors();\n\n  for (int i = 0; i < rotations.size(); ++i) {\n    // Complex solutions can be good, in particular when the number of\n    // correspondences is really low. To use these complex solutions, we simply\n    // ignore their imaginary part.\n    rotations[i] = Eigen::Quaterniond(eigen_vectors(4, i).real(),\n                                      eigen_vectors(5, i).real(),\n                                      eigen_vectors(6, i).real(),\n                                      eigen_vectors(7, i).real()).normalized();\n  }\n\n  return RemoveDuplicateRotations(rotations);\n}\n\nbool GdlsStar::EstimateSimilarityTransformation(const Input& input,\n                                                Solution* solution) {\n  CHECK_NOTNULL(solution)->rotations.clear();\n  solution->translations.clear();\n  solution->scales.clear();\n\n  // Construct cost parameters.\n  ComputeCostParameters(input);\n\n  // Estimate rotations.\n  solution->rotations = EstimateRotations();\n\n  // Compute translations and scales.\n  solution->translations =\n      ComputeScalesAndTranslations(solution->rotations,\n                                   helper_matrices_.translation_factor,\n                                   input,\n                                   helper_matrices_.h_matrix,\n                                   helper_matrices_.scale_factor,\n                                   &solution->scales);\n\n  // Discard solutions that do not have the points in front of the camera.\n  DiscardBadSolutions(input, solution);\n  return !solution->rotations.empty();\n}\n\n}  // namespace msft\n", "meta": {"hexsha": "de502e6acffaa45dc0ddcc1880f4eea6a13f9c65", "size": 20629, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/gdls_star/gdls_star.cc", "max_stars_repo_name": "vfragoso/gdls_star", "max_stars_repo_head_hexsha": "38e2dbc9996ddf4618cbc679d41588594935c5f9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-05-06T18:09:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-09T08:40:06.000Z", "max_issues_repo_path": "src/gdls_star/gdls_star.cc", "max_issues_repo_name": "vfragoso/gdls_star", "max_issues_repo_head_hexsha": "38e2dbc9996ddf4618cbc679d41588594935c5f9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gdls_star/gdls_star.cc", "max_forks_repo_name": "vfragoso/gdls_star", "max_forks_repo_head_hexsha": "38e2dbc9996ddf4618cbc679d41588594935c5f9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-10-29T19:25:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-10T11:39:45.000Z", "avg_line_length": 37.9907918969, "max_line_length": 80, "alphanum_fraction": 0.6811285084, "num_tokens": 5221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.4539548092663129}}
{"text": "\n#include <mmtbx/error.h>\n#include <iotbx/pdb/hierarchy.h>\n#include <scitbx/vec3.h>\n#include <boost/optional.hpp>\n#include <limits>\n#include <cstring>\n\n#define HB_Q1 0.42\n#define HB_Q2 0.2\n#define HB_F 332\n#define HB_F_Q1_Q2 27.888\n\nnamespace mmtbx { namespace secondary_structure { namespace dssp {\n  using namespace iotbx::pdb::hierarchy;\n\n  inline double hbond_energy (\n      scitbx::vec3<double> c_xyz,\n      scitbx::vec3<double> h_xyz,\n      scitbx::vec3<double> o_xyz,\n      scitbx::vec3<double> n_xyz) {\n    double r_ON = (o_xyz - n_xyz).length();\n    double r_CH = (c_xyz - h_xyz).length();\n    double r_OH = (o_xyz - h_xyz).length();\n    double r_CN = (c_xyz - n_xyz).length();\n    double E = HB_F_Q1_Q2 * (1./r_ON + 1./r_CH - 1./r_OH - 1./r_CN);\n    return E;\n  }\n\n  // given a backbone nitrogen atom, calculate the position of the attached\n  // hydrogen atom.\n  boost::optional< scitbx::vec3<double> >\n  get_n_h_position (\n    atom const& N,\n    double nh_bond_length=1.01)\n  {\n    bool have_caN = false;\n    bool have_cN = false;\n    scitbx::vec3<double> N_xyz = N.data->xyz;\n    scitbx::vec3<double> caN_xyz(0,0,0);\n    scitbx::vec3<double> cN_xyz(0,0,0);\n    // find CA attached to N\n    boost::optional<atom_group> ag_N = N.parent();\n    MMTBX_ASSERT(ag_N);\n    unsigned n_ats = ag_N->atoms_size();\n    std::vector<atom> agN_atoms = ag_N->atoms();\n    for(unsigned i_at=0;i_at<n_ats;i_at++) {\n      atom const& a = agN_atoms[i_at];\n      if (std::strcmp(a.data->name.elems, \" CA \") == 0) {\n        caN_xyz = scitbx::vec3<double>(a.data->xyz);\n        have_caN = true;\n        break;\n      }\n    }\n    if (! have_caN) {\n      return boost::optional< scitbx::vec3<double> >();\n    }\n    // find previous C attached to N\n    boost::optional<residue_group> rg_N = ag_N->parent();\n    boost::optional<chain> chn_N = rg_N->parent();\n    unsigned n_rgs = chn_N->residue_groups_size();\n    std::vector<residue_group> rgs = chn_N->residue_groups();\n    residue_group prev_rg;\n    bool have_prev_rg = false;\n    for (unsigned i_rg = 0; i_rg < n_rgs; i_rg++) {\n      if (rgs[i_rg].memory_id() == rg_N->memory_id()) {\n        break;\n      } else {\n        prev_rg = rgs[i_rg];\n        have_prev_rg = true;\n      }\n    }\n    if (! have_prev_rg) {\n      return boost::optional< scitbx::vec3<double> >();\n    }\n    unsigned n_ags = prev_rg.atom_groups_size();\n    std::vector<atom_group> const& ags = prev_rg.atom_groups();\n    for (unsigned i_ag = 0; i_ag < n_ags; i_ag++) {\n      if (ags[i_ag].data->altloc.elems[0] == ag_N->data->altloc.elems[0]) {\n        n_ats = ags[i_ag].atoms_size();\n        std::vector<atom> prev_atoms = ags[i_ag].atoms();\n        for (unsigned i_at = 0; i_at < n_ats; i_at++) {\n          atom const& a = prev_atoms[i_at];\n          if (std::strcmp(a.data->name.elems, \" C  \") == 0) {\n            cN_xyz = scitbx::vec3<double>(a.data->xyz);\n            have_cN = true;\n            break;\n          }\n        }\n        break;\n      }\n    }\n    if (! have_cN) {\n      return boost::optional< scitbx::vec3<double> >();\n    }\n    scitbx::vec3<double> midpoint = (caN_xyz + cN_xyz) / 2;\n    scitbx::vec3<double> vec_nm = N_xyz - midpoint;\n    scitbx::vec3<double>hN_xyz = N_xyz + (vec_nm.normalize() * nh_bond_length);\n    return boost::optional< scitbx::vec3<double> >(hN_xyz);\n  }\n\n\n  // given carbonyl oxygen and amino nitrogen atoms, calculate the hydrogen\n  // bond energy between them.\n  boost::optional<double>\n  get_o_n_hbond_energy (\n    atom const& O,\n    atom const& N,\n    double nh_bond_length=1.01)\n  {\n    scitbx::vec3<double> N_xyz = N.data->xyz;\n    scitbx::vec3<double> O_xyz = O.data->xyz;\n    bool have_cO = false;\n    scitbx::vec3<double> cO_xyz(0,0,0);\n    boost::optional< scitbx::vec3<double> > hN_xyz;\n    // find C attached to O\n    boost::optional<atom_group> ag_O = O.parent();\n    MMTBX_ASSERT(ag_O);\n    unsigned n_ats = ag_O->atoms_size();\n    std::vector<atom> const& atoms = ag_O->atoms();\n    for(unsigned i_at=0;i_at<n_ats;i_at++) {\n      atom const& a = atoms[i_at];\n      if (std::strcmp(a.data->name.elems, \" C  \") == 0) {\n        cO_xyz = scitbx::vec3<double>(a.data->xyz);\n        have_cO = true;\n        break;\n      }\n    }\n    if (! have_cO) {\n      return boost::optional<double>();\n    }\n    double rCN = (cO_xyz - N_xyz).length_sq();\n    if (rCN > 49.0) {\n      return boost::optional<double>();\n    }\n    // now calculate the hydrogen position\n    hN_xyz = get_n_h_position(N, nh_bond_length);\n    if (! hN_xyz) {\n      return boost::optional<double>();\n    }\n    // finally we can calculate the energy\n    return hbond_energy(cO_xyz, *hN_xyz, O_xyz, N_xyz);\n  }\n\n}}} // namespace mmtbx::secondary_structure::dssp\n", "meta": {"hexsha": "19ab489116664c028b11afdb1545241c0e87498e", "size": 4683, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "mmtbx/secondary_structure/dssp.hpp", "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": "mmtbx/secondary_structure/dssp.hpp", "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": "mmtbx/secondary_structure/dssp.hpp", "max_forks_repo_name": "rimmartin/cctbx_project", "max_forks_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 115.0, "max_forks_repo_forks_event_min_datetime": "2016-11-15T08:17:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T15:30:14.000Z", "avg_line_length": 32.0753424658, "max_line_length": 79, "alphanum_fraction": 0.6075165492, "num_tokens": 1476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.453954804516636}}
{"text": "#include \"PitBased.h\"\n#include <boost/math/distributions/normal.hpp>\n#include \"../Parameters.h\"\n#include \"../Obs.h\"\n\nUpdaterPitBased::UpdaterPitBased(const Options& iOptions, const Data& iData) : Updater(iOptions, iData) {\n   iOptions.check();\n}\nfloat UpdaterPitBased::update(float iCdf,\n      const Obs& iRecentObs,\n      const Distribution::ptr iRecent,\n      const Distribution::ptr iDist,\n      const Parameters& iParameters) const {\n   float obs = iRecentObs.getValue();\n   if(!Global::isValid(obs))\n      return iCdf;\n\n   float recentPit = iRecent->getCdf(obs);\n   if(!Global::isValid(recentPit))\n      return iCdf;\n\n   float sigma0 = iParameters[0];\n   float sigma = getSigma(sigma0);\n   float returnValue = Global::MV;\n   int   n = Global::getTimeDiff(iDist->getDate(), iDist->getInit(), iDist->getOffset(),\n                                 iRecentObs.getDate(), iRecentObs.getInit(), iRecentObs.getOffset());\n\n   // TODO\n   if(n == 0) {\n      if(iCdf < recentPit)\n         return 0;\n      else if(iCdf > recentPit)\n         return 1;\n      else\n         return recentPit;\n   }\n   n = 1;\n\n   if(sigma > 0.5) {\n      return iCdf;\n   }\n   else {\n      float accum = 0;\n      for(int i = -mNumIterations; i <= mNumIterations; i++) {\n         float mean = recentPit;\n         float std  = sqrt((float) n)*sigma;\n         assert(std > 0);\n         boost::math::normal dist(mean, std);\n         float part1 = boost::math::cdf(dist, iCdf + 2*i) - boost::math::cdf(dist, 2*i);\n         float part2 = (1 - boost::math::cdf(dist, -iCdf + 2*i)) - (1 - boost::math::cdf(dist, 2*i));\n         float diff = part1 + part2;\n         if(diff < 0) diff = 0;\n         if(diff > 1) diff = 1;\n         accum += diff;\n      }\n      if(accum < 0) {\n         accum = 0;\n         assert(0);\n      }\n      else if(accum > 1) {\n         accum = 1;\n         //assert(0);\n      }\n      returnValue = accum;\n   }\n\n   return returnValue;\n}\nfloat UpdaterPitBased::getSigma(float iSigma0) const {\n   float sigma;\n   if(iSigma0 > 0.3) {\n      sigma = 10;\n   }\n   else {\n      sigma = tan(iSigma0*3.5)/3.5;\n   }\n   return sigma;\n}\n\nvoid UpdaterPitBased::getDefaultParameters(Parameters& iParameters) const {\n   float sigma0 = 0.30;\n   iParameters[0] = sigma0;\n}\n\nvoid UpdaterPitBased::updateParameters(const std::vector<Distribution::ptr>& iDists,\n      const std::vector<Obs>& iObs,\n      const std::vector<Distribution::ptr>& iRecentDists,\n      const std::vector<Obs>& iRecentObs,\n      Parameters& iParameters) const {\n   // Own \n   assert(iDists.size() == iObs.size());\n   assert(iDists.size() == iRecentDists.size());\n   assert(iDists.size() == iRecentObs.size());\n   float prevSigma = iParameters[0];\n   int counter = 0;\n   float total = 0;\n   for(int i = 0; i < iDists.size(); i++) {\n      int   n = Global::getTimeDiff(iDists[i]->getDate(), iDists[i]->getInit(), iDists[i]->getOffset(),\n            iRecentObs[i].getDate(), 0, iRecentObs[i].getOffset());\n      //std::cout << iDists[i]->getDate() << \" \" << iRecentObs[i].getDate() << \" \" << n << std::endl;\n      if(n > 0) {\n         //std::cout << \"Update parameters: \" << iObs[i].getValue() << \" \" << iRecentObs[i].getValue() << \" \" << n << std::endl;\n         float recentObs = iRecentObs[i].getValue();\n         float obs       = iObs[i].getValue();\n         if(Global::isValid(recentObs) && Global::isValid(obs)) {\n            float recentPit = iRecentDists[i]->getCdf(recentObs);\n            float pit       = iDists[i]->getCdf(obs);\n            if(Global::isValid(recentPit) && Global::isValid(pit)) {\n               // TODO: Use the value of 'n'\n               total += fabs(recentPit - pit);\n               counter++;\n            }\n         }\n      }\n   }\n   if(counter > 0) {\n      float newSigma = total / counter;\n      iParameters[0] = Processor::combine(prevSigma, newSigma, counter);\n   }\n}\n", "meta": {"hexsha": "f5e5417e2654335f8953e88e0ffc1dfd0d6ac4b7", "size": 3838, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Updaters/PitBased.cpp", "max_stars_repo_name": "dsiuta/Comps", "max_stars_repo_head_hexsha": "2071279280d33946e975de25deedc60f1881eda0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Updaters/PitBased.cpp", "max_issues_repo_name": "dsiuta/Comps", "max_issues_repo_head_hexsha": "2071279280d33946e975de25deedc60f1881eda0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Updaters/PitBased.cpp", "max_forks_repo_name": "dsiuta/Comps", "max_forks_repo_head_hexsha": "2071279280d33946e975de25deedc60f1881eda0", "max_forks_repo_licenses": ["BSD-3-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.7190082645, "max_line_length": 128, "alphanum_fraction": 0.5659197499, "num_tokens": 1099, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619091240701, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.453954799766959}}
{"text": "//  (C) Copyright Nick Thompson 2021.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include <random>\n#include <array>\n#include <vector>\n#include <benchmark/benchmark.h>\n#include <boost/math/interpolators/bezier_polynomial.hpp>\n\nusing boost::math::interpolators::bezier_polynomial;\n\ntemplate<class Real>\nvoid BezierPolynomial(benchmark::State& state)\n{\n    std::random_device rd;\n    std::mt19937_64 mt(rd());\n    std::uniform_real_distribution<Real> unif(0, 10);\n\n    std::vector<std::array<Real, 3>> v(state.range(0));\n\n    for (size_t i = 0; i < v.size(); ++i) {\n        v[i][0] = unif(mt);\n        v[i][1] = unif(mt);\n        v[i][2] = unif(mt);\n    }\n\n    auto bp = bezier_polynomial(std::move(v));\n    Real t = 0;\n    for (auto _ : state)\n    {\n        auto p = bp(t);\n        benchmark::DoNotOptimize(p[0]);\n        t += std::numeric_limits<Real>::epsilon();\n    }\n     state.SetComplexityN(state.range(0));\n}\n\nBENCHMARK_TEMPLATE(BezierPolynomial, double)->DenseRange(2, 30)->Complexity();\n\nBENCHMARK_MAIN();\n", "meta": {"hexsha": "1aef8ff9c50d6779eaac8e38e660865e1b22bbf9", "size": 1162, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "reporting/performance/bezier_polynomial_performance.cpp", "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": "reporting/performance/bezier_polynomial_performance.cpp", "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": "reporting/performance/bezier_polynomial_performance.cpp", "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.023255814, "max_line_length": 78, "alphanum_fraction": 0.6488812392, "num_tokens": 332, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.82446190912407, "lm_q2_score": 0.5506073655352403, "lm_q1q2_score": 0.45395479976695885}}
{"text": "#include <stan/math/rev/scal.hpp>\n#include <gtest/gtest.h>\n#include <math/rev/scal/util.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <limits>\n\nTEST(AgradRev, if_else) {\n  using stan::math::if_else;\n  using stan::math::var;\n\n  EXPECT_FLOAT_EQ(1.0, if_else(true, var(1.0), var(2.0)).val());\n  EXPECT_FLOAT_EQ(2.0, if_else(false, var(1.0), var(2.0)).val());\n\n  EXPECT_FLOAT_EQ(1.0, if_else(true, 1.0, var(2.0)).val());\n  EXPECT_FLOAT_EQ(2.0, if_else(false, 1.0, var(2.0)).val());\n\n  EXPECT_FLOAT_EQ(1.0, if_else(true, var(1.0), 2.0).val());\n  EXPECT_FLOAT_EQ(2.0, if_else(false, var(1.0), 2.0).val());\n}\n\nTEST(AgradRev, if_else_nan) {\n  using stan::math::if_else;\n\n  double nan = std::numeric_limits<double>::quiet_NaN();\n  stan::math::var nan_v = std::numeric_limits<double>::quiet_NaN();\n  stan::math::var a_v = 1.2;\n\n  EXPECT_FLOAT_EQ(1.2, if_else(true, 1.2, nan_v).val());\n  EXPECT_FLOAT_EQ(1.2, if_else(true, a_v, nan).val());\n  EXPECT_FLOAT_EQ(1.2, if_else(true, a_v, nan_v).val());\n  EXPECT_PRED1(boost::math::isnan<double>, if_else(false, 1.2, nan_v).val());\n  EXPECT_PRED1(boost::math::isnan<double>, if_else(false, a_v, nan).val());\n  EXPECT_PRED1(boost::math::isnan<double>, if_else(false, a_v, nan_v).val());\n\n  EXPECT_PRED1(boost::math::isnan<double>, if_else(true, nan_v, 2.4).val());\n  EXPECT_PRED1(boost::math::isnan<double>, if_else(true, nan, a_v).val());\n  EXPECT_PRED1(boost::math::isnan<double>, if_else(true, nan_v, a_v).val());\n\n  a_v = 2.4;\n  EXPECT_FLOAT_EQ(2.4, if_else(false, nan_v, 2.4).val());\n  EXPECT_FLOAT_EQ(2.4, if_else(false, nan, a_v).val());\n  EXPECT_FLOAT_EQ(2.4, if_else(false, nan_v, a_v).val());\n\n  EXPECT_PRED1(boost::math::isnan<double>, if_else(true, nan_v, nan).val());\n  EXPECT_PRED1(boost::math::isnan<double>, if_else(true, nan, nan_v).val());\n  EXPECT_PRED1(boost::math::isnan<double>, if_else(true, nan_v, nan_v).val());\n  EXPECT_PRED1(boost::math::isnan<double>, if_else(false, nan, nan_v).val());\n  EXPECT_PRED1(boost::math::isnan<double>, if_else(false, nan_v, nan).val());\n  EXPECT_PRED1(boost::math::isnan<double>, if_else(false, nan_v, nan_v).val());\n}\n\nTEST(AgradRev, check_varis_on_stack_27) {\n  stan::math::var x = 1.0;\n  stan::math::var y = 2.0;\n  test::check_varis_on_stack(stan::math::if_else(true, x, y));\n  test::check_varis_on_stack(stan::math::if_else(false, x, y));\n  test::check_varis_on_stack(stan::math::if_else(true, x, 2.0));\n  test::check_varis_on_stack(stan::math::if_else(false, x, 2.0));\n  test::check_varis_on_stack(stan::math::if_else(true, 1.0, y));\n  test::check_varis_on_stack(stan::math::if_else(false, 1.0, y));\n}\n", "meta": {"hexsha": "a96178cce73402ed532a80d2bed75985f7bfba95", "size": 2618, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/math_unit/math/rev/scal/fun/if_else_test.cpp", "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": "tests/math_unit/math/rev/scal/fun/if_else_test.cpp", "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": "tests/math_unit/math/rev/scal/fun/if_else_test.cpp", "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": 42.2258064516, "max_line_length": 79, "alphanum_fraction": 0.6856378915, "num_tokens": 884, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702880639791, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.4538588127113022}}
{"text": "/*=============================================================================\r\n    Spirit v1.6.0\r\n    Copyright (c) 2002-2003 Joel de Guzman\r\n    Copyright (c) 2002 Juan Carlos Arevalo-Baeza\r\n    http://spirit.sourceforge.net/\r\n\r\n    Permission to copy, use, modify, sell and distribute this software is\r\n    granted provided this copyright notice appears in all copies. This\r\n    software is provided \"as is\" without express or implied warranty, and\r\n    with no claim as to its suitability for any purpose.\r\n=============================================================================*/\r\n#include <boost/spirit/core.hpp>\r\n#include <boost/spirit/utility/functor_parser.hpp>\r\n#include <iostream>\r\n#include <vector>\r\n#include <string>\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\nusing namespace std;\r\nusing namespace boost::spirit;\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n//\r\n//  Our parser functor\r\n//\r\n///////////////////////////////////////////////////////////////////////////////\r\nstruct number_parser\r\n{\r\n    typedef int result_t;\r\n    template <typename ScannerT>\r\n    int\r\n    operator()(ScannerT const& scan, result_t& result) const\r\n    {\r\n        if (scan.at_end())\r\n            return -1;\r\n\r\n        char ch = *scan;\r\n        if (ch < '0' || ch > '9')\r\n            return -1;\r\n\r\n        result = 0;\r\n        int len = 0;\r\n\r\n        do\r\n        {\r\n            result = result*10 + int(ch - '0');\r\n            ++len;\r\n            ++scan;\r\n        } while (!scan.at_end() && (ch = *scan, ch >= '0' && ch <= '9'));\r\n\r\n        return len;\r\n    }\r\n};\r\n\r\nfunctor_parser<number_parser> number_parser_p;\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n//\r\n//  Our number parser functions\r\n//\r\n///////////////////////////////////////////////////////////////////////////////\r\nbool\r\nparse_number(char const* str, int& n)\r\n{\r\n    return parse(str, lexeme_d[number_parser_p[assign(n)]], space_p).full;\r\n}\r\n\r\nbool\r\nparse_numbers(char const* str, std::vector<int>& n)\r\n{\r\n    return\r\n        parse(\r\n            str,\r\n            lexeme_d[number_parser_p[append(n)]]\r\n                >> *(',' >> lexeme_d[number_parser_p[append(n)]]),\r\n            space_p\r\n        ).full;\r\n}\r\n\r\n////////////////////////////////////////////////////////////////////////////\r\n//\r\n//  Main program\r\n//\r\n////////////////////////////////////////////////////////////////////////////\r\nint\r\nmain()\r\n{\r\n    cout << \"/////////////////////////////////////////////////////////\\n\\n\";\r\n    cout << \"\\t\\tA number parser implemented as a functor for Spirit...\\n\\n\";\r\n    cout << \"/////////////////////////////////////////////////////////\\n\\n\";\r\n\r\n    cout << \"Give me an integer number command\\n\";\r\n    cout << \"Commands:\\n\";\r\n    cout << \"  A <num> --> parses a single number\\n\";\r\n    cout << \"  B <num>, <num>, ... --> parses a series of numbers \";\r\n    cout << \"separated by commas\\n\";\r\n    cout << \"  Q --> quit\\n\\n\";\r\n\r\n    string str;\r\n    while (getline(cin, str))\r\n    {\r\n        if (str[0] == 'q' || str[0] == 'Q')\r\n            break;\r\n\r\n        else if (str[0] == 'a' || str[0] == 'A')\r\n        {\r\n            int n;\r\n            if (parse_number(str.c_str()+1, n))\r\n            {\r\n                cout << \"-------------------------\\n\";\r\n                cout << \"Parsing succeeded\\n\";\r\n                cout << str << \" Parses OK: \" << n << endl;\r\n                cout << \"-------------------------\\n\";\r\n            }\r\n            else\r\n            {\r\n                cout << \"-------------------------\\n\";\r\n                cout << \"Parsing failed\\n\";\r\n                cout << \"-------------------------\\n\";\r\n            }\r\n        }\r\n\r\n        else if (str[0] == 'b' || str[0] == 'B')\r\n        {\r\n            std::vector<int> n;\r\n            if (parse_numbers(str.c_str()+1, n))\r\n            {\r\n                cout << \"-------------------------\\n\";\r\n                cout << \"Parsing succeeded\\n\";\r\n                int size = n.size();\r\n                cout << str << \" Parses OK: \" << size << \" number(s): \" << n[0];\r\n                for (int i = 1; i < size; ++i) {\r\n                    cout << \", \" << n[i];\r\n                }\r\n                cout << endl;\r\n                cout << \"-------------------------\\n\";\r\n            }\r\n            else\r\n            {\r\n                cout << \"-------------------------\\n\";\r\n                cout << \"Parsing failed\\n\";\r\n                cout << \"-------------------------\\n\";\r\n            }\r\n        }\r\n\r\n        else\r\n        {\r\n            cout << \"-------------------------\\n\";\r\n            cout << \"Unrecognized command!!\";\r\n            cout << \"-------------------------\\n\";\r\n        }\r\n    }\r\n\r\n    cout << \"Bye... :-) \\n\\n\";\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "5a1daba0fde6d5d918fd3df76189a42601a72ae8", "size": 4791, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sdk/boost_1_30_0/libs/spirit/example/fundamental/functor_parser.cpp", "max_stars_repo_name": "acidicMercury8/xray-1.0", "max_stars_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-01-30T12:51:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-31T08:36:49.000Z", "max_issues_repo_path": "sdk/boost_1_30_0/libs/spirit/example/fundamental/functor_parser.cpp", "max_issues_repo_name": "acidicMercury8/xray-1.0", "max_issues_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_issues_repo_licenses": ["Linux-OpenIB"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sdk/boost_1_30_0/libs/spirit/example/fundamental/functor_parser.cpp", "max_forks_repo_name": "acidicMercury8/xray-1.0", "max_forks_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5159235669, "max_line_length": 81, "alphanum_fraction": 0.3375078272, "num_tokens": 954, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6261241911813151, "lm_q2_score": 0.7248702702332476, "lm_q1q2_score": 0.4538588116611735}}
{"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 \"toplevelfixture.hpp\"\n#include <boost/test/unit_test.hpp>\n#include <ql/cashflows/fixedratecoupon.hpp>\n#include <ql/quotes/simplequote.hpp>\n#include <ql/termstructures/credit/flathazardrate.hpp>\n#include <ql/termstructures/yield/flatforward.hpp>\n#include <ql/time/calendars/weekendsonly.hpp>\n#include <ql/time/schedule.hpp>\n#include <qle/instruments/impliedbondspread.hpp>\n#include <qle/pricingengines/discountingriskybondengine.hpp>\n\n#include <boost/make_shared.hpp>\n\nusing namespace boost::unit_test_framework;\nusing namespace QuantLib;\n\nBOOST_FIXTURE_TEST_SUITE(QuantExtTestSuite, qle::test::TopLevelFixture)\n\nBOOST_AUTO_TEST_SUITE(BondsTest)\n\nBOOST_AUTO_TEST_CASE(testBondSpreads) {\n\n    BOOST_TEST_MESSAGE(\"Testing QuantExt bond spread helper\");\n\n    SavedSettings backup;\n    Settings::instance().evaluationDate() = Date(8, Dec, 2016);\n    Date today = Settings::instance().evaluationDate();\n\n    // market data\n    Handle<Quote> rateQuote(boost::make_shared<SimpleQuote>(0.02));\n    Handle<Quote> issuerSpreadQuote(boost::make_shared<SimpleQuote>(0.01));\n    DayCounter dc = Actual365Fixed();\n    Handle<YieldTermStructure> yts(boost::make_shared<FlatForward>(today, rateQuote, dc, Compounded, Semiannual));\n    Handle<DefaultProbabilityTermStructure> dpts(boost::make_shared<FlatHazardRate>(today, issuerSpreadQuote, dc));\n    Handle<Quote> bondSpecificSpread(boost::make_shared<SimpleQuote>(0.005));\n\n    // build the bond\n    Date startDate = today;\n    Date endDate = startDate + Period(10, Years);\n    Period tenor = 6 * Months;\n    Calendar calendar = WeekendsOnly();\n    BusinessDayConvention bdc = Following;\n    BusinessDayConvention bdcEnd = bdc;\n    DateGeneration::Rule rule = DateGeneration::Forward;\n    bool endOfMonth = false;\n    Date firstDate, lastDate;\n    Schedule schedule(startDate, endDate, tenor, calendar, bdc, bdcEnd, rule, endOfMonth, firstDate, lastDate);\n\n    Real redemption = 100.0;\n    Real couponRate = 0.04;\n    Leg leg =\n        FixedRateLeg(schedule).withNotionals(redemption).withCouponRates(couponRate, dc).withPaymentAdjustment(bdc);\n\n    boost::shared_ptr<QuantLib::Bond> bond(boost::make_shared<QuantLib::Bond>(0, WeekendsOnly(), today, leg));\n    Handle<Quote> recovery;\n    boost::shared_ptr<PricingEngine> pricingEngine(\n        boost::make_shared<QuantExt::DiscountingRiskyBondEngine>(yts, dpts, recovery, bondSpecificSpread, 1 * Months));\n    bond->setPricingEngine(pricingEngine);\n\n    Real price = bond->dirtyPrice();\n    BOOST_TEST_MESSAGE(\"Bond price = \" << price);\n\n    // now calculated the implied bond spread, given the price\n    boost::shared_ptr<SimpleQuote> tmpSpread = boost::make_shared<SimpleQuote>(0.0);\n    Handle<Quote> tmpSpreadH(tmpSpread);\n    boost::shared_ptr<PricingEngine> tmpEngine;\n    tmpEngine.reset(new QuantExt::DiscountingRiskyBondEngine(yts, dpts, recovery, tmpSpreadH, 1 * Months));\n\n    Real impliedSpread = QuantExt::detail::ImpliedBondSpreadHelper::calculate(bond, tmpEngine, tmpSpread, price, false,\n                                                                              1.e-12, 10000, -0.02, 1.00);\n    BOOST_TEST_MESSAGE(\"Implied spread = \" << impliedSpread);\n    BOOST_CHECK_CLOSE(impliedSpread, bondSpecificSpread->value(), 0.0001);\n\n    Real price2 = bond->dirtyPrice();\n    BOOST_CHECK_EQUAL(price, price2);\n\n    // which spread would mean the bond price is par?\n    Real parRedemption = 100.0;\n    Real impliedSpreadPar = QuantExt::detail::ImpliedBondSpreadHelper::calculate(\n        bond, tmpEngine, tmpSpread, parRedemption, false, 1.e-12, 10000, -0.02, 1.00);\n    BOOST_TEST_MESSAGE(\"Par bond price would require spread of \" << impliedSpreadPar);\n    BOOST_CHECK_EQUAL(\n        price, bond->dirtyPrice()); // ensure hypothetical impliedSpread calc has not affected the original position\n\n    boost::dynamic_pointer_cast<SimpleQuote>(*bondSpecificSpread)->setValue(impliedSpreadPar);\n    Real pricePar = bond->dirtyPrice();\n    BOOST_TEST_MESSAGE(\"Bond spread of \" << bondSpecificSpread->value() << \" means price of \" << pricePar);\n    BOOST_CHECK_CLOSE(pricePar, parRedemption, 0.0001);\n\n    // now check that bond pricing works even if no credit curve exists\n\n    dpts = Handle<DefaultProbabilityTermStructure>();\n    pricingEngine.reset(new QuantExt::DiscountingRiskyBondEngine(yts, dpts, recovery, bondSpecificSpread, 1 * Months));\n    tmpEngine.reset(new QuantExt::DiscountingRiskyBondEngine(yts, dpts, recovery, tmpSpreadH, 1 * Months));\n    bond->setPricingEngine(pricingEngine);\n    Real priceNoIssuerCurve = bond->dirtyPrice();\n    BOOST_TEST_MESSAGE(\"Bond price (ignoring issuer spread) = \" << priceNoIssuerCurve);\n    impliedSpread = QuantExt::detail::ImpliedBondSpreadHelper::calculate(bond, tmpEngine, tmpSpread, priceNoIssuerCurve,\n                                                                         false, 1.e-12, 10000, -0.02, 1.00);\n    BOOST_TEST_MESSAGE(\"Bond spread (ignoring issuer spread) = \" << impliedSpread);\n    BOOST_CHECK_CLOSE(impliedSpread, bondSpecificSpread->value(), 0.0001);\n\n    // which spread would mean the bond price is par?\n    impliedSpreadPar = QuantExt::detail::ImpliedBondSpreadHelper::calculate(bond, tmpEngine, tmpSpread, parRedemption,\n                                                                            false, 1.e-12, 10000, -0.02, 1.00);\n    BOOST_TEST_MESSAGE(\"Par bond price would require spread of \" << impliedSpreadPar);\n    BOOST_CHECK_CLOSE(impliedSpreadPar, bondSpecificSpread->value() + issuerSpreadQuote->value(), 0.0001);\n    boost::dynamic_pointer_cast<SimpleQuote>(*bondSpecificSpread)->setValue(impliedSpreadPar);\n    pricePar = bond->dirtyPrice();\n    BOOST_TEST_MESSAGE(\"Bond spread of \" << bondSpecificSpread->value() << \" means price of \" << pricePar);\n    BOOST_CHECK_CLOSE(pricePar, parRedemption, 0.0001);\n}\nBOOST_AUTO_TEST_SUITE_END()\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "587c47baf84918288be8593a4691cfde139b3091", "size": 6612, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QuantExt/test/bonds.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/test/bonds.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/test/bonds.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": 49.3432835821, "max_line_length": 120, "alphanum_fraction": 0.7264065336, "num_tokens": 1605, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702880639792, "lm_q2_score": 0.6261241702517975, "lm_q1q2_score": 0.4538588076542404}}
{"text": "/**\n * @file qfeinterpolator.cc\n * @brief NPDE homework DebuggingFEM code\n * @author Simon Meierhans\n * @date 27/03/2019\n * @copyright Developed at ETH Zurich\n */\n\n#include \"qfeinterpolator.h\"\n\n#include <lf/mesh/mesh.h>\n\n#include <Eigen/Core>\n\nnamespace DebuggingFEM {\n\n/* SAM_LISTING_BEGIN_1 */\nEigen::Vector2d globalCoordinate(int idx, const lf::mesh::Entity &cell) {\n  // Consistency check for arguments\n  LF_ASSERT_MSG(cell.RefEl() == lf::base::RefEl::kTria(),\n                \"Implemented for triangles only\");\n  // Fetch pointer to asscoiated geometry object\n  const lf::geometry::Geometry *geom = cell.Geometry();\n  // For returning the global coordinates of the interpolation node\n  Eigen::Vector2d result;\n  // Reference coordinates of the vertices of the triangle\n  Eigen::Matrix<double, 2, 3> corners(2, 3);\n  corners << 0., 1., 0., 0., 0., 1.;\n  //====================\n  // Your code goes here\n  //====================\n  return result;\n}\n/* SAM_LISTING_END_1 */\n\n}  // namespace DebuggingFEM\n", "meta": {"hexsha": "441db44846e17fea7312f2bbba60ec530abb6979", "size": 1004, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/DebuggingFEM/templates/qfeinterpolator.cc", "max_stars_repo_name": "kryo4096/NPDECODES", "max_stars_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/DebuggingFEM/templates/qfeinterpolator.cc", "max_issues_repo_name": "kryo4096/NPDECODES", "max_issues_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/DebuggingFEM/templates/qfeinterpolator.cc", "max_forks_repo_name": "kryo4096/NPDECODES", "max_forks_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 27.1351351351, "max_line_length": 73, "alphanum_fraction": 0.6613545817, "num_tokens": 274, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6261241772283033, "lm_q2_score": 0.7248702642896702, "lm_q1q2_score": 0.4538587978256325}}
{"text": "#include <benchmark/benchmark.h>\n\n#include <Eigen/Core>\n\n#include <mitrax/dim.hpp>\n\n#include <random>\n#include <string>\n\n#include \"../../../include/get_binaryop.hpp\"\n\n\nusing namespace mitrax;\nusing namespace mitrax::literals;\n\n\ntemplate < typename T, typename Op >\n[[gnu::noinline]]\nvoid bm(benchmark::State& state, Op op, rt_dim_pair_t d1, rt_dim_pair_t d2){\n\tstd::random_device rd;\n\tstd::mt19937 gen(rd());\n\tstd::uniform_int_distribution< T > dis(\n\t\tstd::numeric_limits< T >::min(),\n\t\tstd::numeric_limits< T >::max()\n\t);\n\n\tEigen::Matrix< T, Eigen::Dynamic, Eigen::Dynamic > m1(\n\t\tsize_t(d1.rows()), size_t(d1.cols())\n\t);\n\tfor(int y = 0; y < m1.rows(); ++y){\n\t\tfor(int x = 0; x < m1.cols(); ++x){\n\t\t\tm1(y, x) = dis(gen);\n\t\t}\n\t}\n\n\tEigen::Matrix< T, Eigen::Dynamic, Eigen::Dynamic > m2(\n\t\tsize_t(d2.rows()), size_t(d2.cols())\n\t);\n\tfor(int y = 0; y < m2.rows(); ++y){\n\t\tfor(int x = 0; x < m2.cols(); ++x){\n\t\t\tm2(y, x) = dis(gen);\n\t\t}\n\t}\n\n\twhile(state.KeepRunning()){\n\t\tauto res = op(m1, m2).eval();\n\t\tbenchmark::DoNotOptimize(res);\n\t}\n}\n\n\n#include <boost/hana/tuple.hpp>\n#include <boost/hana/for_each.hpp>\n\n\nnamespace init{\n\n\tconstexpr auto dimensions = boost::hana::make_tuple(\n\t\t\tdim_pair(2_CS, 2_RS),\n\t\t\tdim_pair(4_CS, 2_RS),\n\t\t\tdim_pair(8_CS, 2_RS),\n\t\t\tdim_pair(8_CS, 4_RS),\n\t\t\tdim_pair(8_CS, 8_RS),\n\t\t\tdim_pair(8_CS, 16_RS),\n\t\t\tdim_pair(8_CS, 32_RS),\n\t\t\tdim_pair(8_CS, 64_RS),\n\t\t\tdim_pair(16_CS, 64_RS),\n\t\t\tdim_pair(32_CS, 64_RS),\n\t\t\tdim_pair(64_CS, 64_RS),\n\t\t\tdim_pair(128_CS, 64_RS),\n\t\t\tdim_pair(256_CS, 64_RS),\n\t\t\tdim_pair(256_CS, 128_RS),\n\t\t\tdim_pair(256_CS, 256_RS)\n\t\t);\n\n\tusing plus = std::plus<>;\n\tusing multiplies = std::multiplies<>;\n\n}\n\n#include \"main.hpp\"\n", "meta": {"hexsha": "293ed225942efa4652e8919b1e5338f8b25a5b12", "size": 1670, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "benchmark/benchmark/binary_op/size/Eigen_rt_heap.cpp", "max_stars_repo_name": "bebuch/Mitrax", "max_stars_repo_head_hexsha": "bc33a1b93058886daab3e4ef736ef9b519111454", "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": "benchmark/benchmark/binary_op/size/Eigen_rt_heap.cpp", "max_issues_repo_name": "bebuch/Mitrax", "max_issues_repo_head_hexsha": "bc33a1b93058886daab3e4ef736ef9b519111454", "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": "benchmark/benchmark/binary_op/size/Eigen_rt_heap.cpp", "max_forks_repo_name": "bebuch/Mitrax", "max_forks_repo_head_hexsha": "bc33a1b93058886daab3e4ef736ef9b519111454", "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": 20.3658536585, "max_line_length": 76, "alphanum_fraction": 0.6377245509, "num_tokens": 572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.4538587951543439}}
{"text": "#include <iostream>\n#define ADEPT_NO_AUTOMATIC_DIFFERENTIATION\n#define ADEPT_REAL_TYPE_SIZE 4\n#include <adept_arrays.h>\n#include \"Timer.h\"\n\n#define ASSIGN   =\n#define WARMUP_OPERATOR + exp\n#define OPERATOR + fastexp\n//#define SUFFIX_OP + 0.5\n#define SUFFIX_OP\n\nusing namespace adept;\n\nint main()\n{\n  Timer timer;\n  timer.print_on_exit();\n  int n = 128;\n\n  static const int rep = 10000;\n  //  static const int rep = 10;\n\n  std::cout << \"Packet<Real>::size = \" << internal::Packet<Real>::size << \"\\n\";\n\n  Stack stack;\n\n  aMatrix M(n,n), P(n,n), Q(n,n);\n  //  Array<2,aReal,false> M(n,n), P(n,n), Q(n,n);\n  aReal Mc[n][n], Pc[n][n], Qc[n][n];\n\n  for (int i = 0; i < n; ++i) {\n    for (int j = 0; j < n; ++j) {\n      P(i,j) = Pc[i][j] = 0.01 * (i-j);\n      Q(i,j) = Qc[i][j] = 0.1 * (j+1);\n      M(i,j) = Mc[i][j] = 0.0;\n    }\n  }\n\n  int t_c_style_w = timer.new_activity(\"C-style for loops (warm-up)\");\n  int t_c_style = timer.new_activity(\"C-style for loops\");\n  int t_adept_w = timer.new_activity(\"Adept (warm-up)\");\n  int t_adept = timer.new_activity(\"Adept\");\n  int t_adept_container_w = timer.new_activity(\"Adept container only (warm-up)\");\n  int t_adept_container = timer.new_activity(\"Adept container only\");\n#ifndef ADEPT_NO_AUTOMATIC_DIFFERENTIATION\n  int t_jacobian_w = timer.new_activity(\"Jacobian (warm-up)\");\n  int t_jacobian = timer.new_activity(\"Jacobian\");\n  int t_jacobian_array_w = timer.new_activity(\"Jacobian array-op (warm-up)\");\n  int t_jacobian_array = timer.new_activity(\"Jacobian array-op\");\n#endif\n\n  stack.new_recording();\n  timer.start(t_c_style_w);\n  for (int irep = 0; irep < rep; ++irep) {\n    for (int i = 0; i < n; ++i) {\n      for (int j = 0; j < n; ++j) {\n\tMc[i][j] ASSIGN Pc[i][j] WARMUP_OPERATOR (Qc[i][j] SUFFIX_OP);\n      }\n    }\n  }\n  timer.stop();\n\n  if (n <= 10) {\n    std::cout << \"C-style M = \\n\";\n    for (int i = 0; i < n; ++i) {\n      for (int j = 0; j < n; ++j) {\n\tstd::cout << \" \" << Mc[i][j];\n      }\n      std::cout << \"\\n\";\n    }\n  }\n  \n  //  std::cout << stack;\n\n  stack.new_recording();\n  timer.start(t_c_style);\n  for (int irep = 0; irep < rep; ++irep) {\n    for (int i = 0; i < n; ++i) {\n      for (int j = 0; j < n; ++j) {\n\tMc[i][j] ASSIGN Pc[i][j] OPERATOR (Qc[i][j] SUFFIX_OP);\n      }\n    }\n  }\n  timer.stop();\n  //  std::cout << stack;\n\n#ifndef ADEPT_NO_AUTOMATIC_DIFFERENTIATION\n  stack.independent(&Pc[0][0], n*n);\n  stack.dependent(&Mc[0][0], n*n);\n\n  timer.start(t_jacobian_w);\n  Real* jac;\n  jac = new Real[n*n*n*n];\n\n  stack.jacobian_forward(jac);\n  timer.stop();\n  timer.start(t_jacobian);\n  stack.jacobian_forward(jac);\n  timer.stop();\n#endif\n\n\n  //  std::cout << Mc[0][0] << \" \" << Mc[10][10] << \"\\n\";\n\n  stack.new_recording();\n  timer.start(t_adept_w);\n  for (int irep = 0; irep < rep; ++irep) {\n    //    M ASSIGN noalias(P WARMUP_OPERATOR (Q SUFFIX_OP));\n    M ASSIGN P WARMUP_OPERATOR (Q SUFFIX_OP);\n  }\n  timer.stop();\n  //  std::cout << stack;\n\n  if (n <= 10) {\n    std::cout << \"Array-style M = \\n\";\n    for (int i = 0; i < n; ++i) {\n      for (int j = 0; j < n; ++j) {\n\tstd::cout << \" \" << M(i,j);\n      }\n      std::cout << \"\\n\";\n    }\n  }\n\n  std::cout << \"Alignment offset = \" << (P OPERATOR (Q SUFFIX_OP)).alignment_offset() << \"\\n\";\n\n\n  stack.new_recording();\n  timer.start(t_adept);\n  for (int irep = 0; irep < rep; ++irep) {\n    //    M += noalias(P OPERATOR (Q SUFFIX_OP));\n    M ASSIGN P OPERATOR (Q SUFFIX_OP);\n  }\n  timer.stop();\n  //  std::cout << stack;\n\n\n#ifndef ADEPT_NO_AUTOMATIC_DIFFERENTIATION\n\n  stack.clear_independents();\n  stack.clear_dependents();\n  stack.independent(P);\n  stack.dependent(Q);\n  //  stack.independent(P.data(), n*n);\n  //  stack.dependent(M.data(), n*n);\n\n  std::cout << stack;\n\n  timer.start(t_jacobian_array_w);\n  stack.jacobian_forward(jac);\n  timer.stop();\n  timer.start(t_jacobian_array);\n  stack.jacobian_forward(jac);\n  timer.stop();\n#endif\n\n  stack.new_recording();\n  timer.start(t_adept_container_w);\n  for (int irep = 0; irep < rep; ++irep) {\n    for (int i = 0; i < n; ++i) {\n      for (int j = 0; j < n; ++j) {\n\tM(i,j) ASSIGN P(i,j) WARMUP_OPERATOR (Q(i,j) SUFFIX_OP);\n      }\n    }\n  }\n  timer.stop();\n  //  std::cout << stack;\n  //  std::cout << M;\n\n  stack.new_recording();\n  timer.start(t_adept_container);\n  for (int irep = 0; irep < rep; ++irep) {\n    for (int i = 0; i < n; ++i) {\n      for (int j = 0; j < n; ++j) {\n\tM(i,j) ASSIGN P(i,j) OPERATOR (Q(i,j) SUFFIX_OP);\n      }\n    }\n  }\n  timer.stop();\n  //  std::cout << stack;\n}\n", "meta": {"hexsha": "a8d06113f4a0c4aee388a1426cb039c17acf0d0a", "size": 4462, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_array_speed.cpp", "max_stars_repo_name": "yairchu/Adept-2", "max_stars_repo_head_hexsha": "3b4f898c74139618464ccd8e8df0934aed9ed6a2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 131.0, "max_stars_repo_stars_event_min_datetime": "2016-07-06T04:06:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T22:34:47.000Z", "max_issues_repo_path": "test/test_array_speed.cpp", "max_issues_repo_name": "yairchu/Adept-2", "max_issues_repo_head_hexsha": "3b4f898c74139618464ccd8e8df0934aed9ed6a2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2016-06-20T20:20:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-15T14:55:01.000Z", "max_forks_repo_path": "test/test_array_speed.cpp", "max_forks_repo_name": "yairchu/Adept-2", "max_forks_repo_head_hexsha": "3b4f898c74139618464ccd8e8df0934aed9ed6a2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 31.0, "max_forks_repo_forks_event_min_datetime": "2017-10-07T00:07:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-05T17:51:17.000Z", "avg_line_length": 24.5164835165, "max_line_length": 94, "alphanum_fraction": 0.5775437024, "num_tokens": 1529, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.4538587951543439}}
{"text": "// Author(s): Jeroen Keiren\n// Copyright: see the accompanying file COPYING or copy at\n// https://svn.win.tue.nl/trac/MCRL2/browser/trunk/COPYING\n//\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//\n/// \\file list_test.cpp\n/// \\brief Basic regression test for list expressions.\n\n#include <boost/test/minimal.hpp>\n\n#include \"mcrl2/data/list.h\"\n#include \"mcrl2/data/parse.h\"\n#include \"mcrl2/data/rewriter.h\"\n\n\nusing namespace mcrl2;\nusing namespace mcrl2::data;\nusing namespace mcrl2::data::sort_list;\n\ntemplate <typename Predicate>\nvoid test_data_expression(const std::string& s, const mcrl2::data::variable_vector& v, Predicate p)\n{\n  data_expression e = parse_data_expression(s, v);\n  BOOST_CHECK(p(e));\n}\n\n/* Test case for various list expressions, based\n   on the following specification:\n\nproc P(l: List(Nat)) = (1 in l) -> tau . P(10 |> l ++ [#l] <| 100)\n                     + (l.1 == 30) -> tau . P(tail(l))\n                     + (head(l) == 20) -> tau . P([rhead(l)] ++ rtail(l));\n\ninit P([20, 30, 40]);\n*/\nvoid list_expression_test()\n{\n  data::data_specification specification;\n\n  specification.add_context_sort(sort_list::list(sort_pos::pos()));\n\n\n  data::rewriter normaliser(specification);\n\n  variable_vector v;\n  v.push_back(parse_variable(\"l:List(Nat)\"));\n\n  test_data_expression(\"1 in l\", v, is_in_application);\n  test_data_expression(\"10 |> l\", v, is_cons_application);\n  test_data_expression(\"l <| 10\", v, is_snoc_application);\n  test_data_expression(\"#l\", v, is_count_application);\n  test_data_expression(\"l ++ [10]\", v, is_concat_application);\n  test_data_expression(\"l.1\", v, is_element_at_application);\n  test_data_expression(\"head(l)\", v, is_head_application);\n  test_data_expression(\"rhead(l)\", v, is_rhead_application);\n  test_data_expression(\"tail(l)\", v, is_tail_application);\n  test_data_expression(\"rtail(l)\", v, is_rtail_application);\n\n  data_expression e = parse_data_expression(\"[10]\", v);\n  BOOST_CHECK(is_cons_application(normaliser(e)));\n}\n\nint test_main(int argc, char** argv)\n{\n  list_expression_test();\n\n  return EXIT_SUCCESS;\n}\n\n", "meta": {"hexsha": "661ee895e8cd48da2920c816fa7d97be12287302", "size": 2177, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libraries/data/test/list_test.cpp", "max_stars_repo_name": "wiegerw/mcrl3", "max_stars_repo_head_hexsha": "15260c92ab35930398d6dfb34d31351b05101ca9", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-22T09:16:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-22T09:16:39.000Z", "max_issues_repo_path": "libraries/data/test/list_test.cpp", "max_issues_repo_name": "wiegerw/mcrl3", "max_issues_repo_head_hexsha": "15260c92ab35930398d6dfb34d31351b05101ca9", "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": "libraries/data/test/list_test.cpp", "max_forks_repo_name": "wiegerw/mcrl3", "max_forks_repo_head_hexsha": "15260c92ab35930398d6dfb34d31351b05101ca9", "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.8219178082, "max_line_length": 99, "alphanum_fraction": 0.7060174552, "num_tokens": 573, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056295505783, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.45385089435196924}}
{"text": "#include <boost/assign/std/vector.hpp>\n#include <cradle/common.hpp>\n#include <cradle/geometry/common.hpp>\n#include <cradle/geometry/transformations.hpp>\n#include <cradle/math/common.hpp>\n#include <vector>\n\n#include <cradle/test.hpp>\n\nusing namespace cradle;\n\nTEST_CASE(\"sizeof_vector\")\n{\n    // Check that vectors don't have any size overhead.\n    REQUIRE(sizeof(vector<3, int>) == 3 * sizeof(int));\n    REQUIRE(sizeof(vector<1, float>) == sizeof(float));\n    REQUIRE(sizeof(vector<2, double>) == 2 * sizeof(double));\n}\n\nvoid\nf(vector3i const& v)\n{\n}\n\n// confirm that the vector operators work as expected\nTEST_CASE(\"vector_operators\")\n{\n    vector<3, int> p = make_vector<int>(1, 1, 0),\n                   q = make_vector<int>(4, 2, 6);\n    vector<3, int> v = make_vector<int>(3, 1, 2);\n\n    REQUIRE(p - q == make_vector<int>(-3, -1, -6));\n    REQUIRE(p + v == make_vector<int>(4, 2, 2));\n\n    REQUIRE(v * 3 == make_vector<int>(9, 3, 6));\n    REQUIRE(v / 2 == make_vector<int>(1, 0, 1));\n\n    REQUIRE(!(p == q));\n    REQUIRE(p != q);\n\n    REQUIRE(!(p - q == v));\n    REQUIRE(p - q != v);\n}\n\nTEST_CASE(\"vector_slice\")\n{\n    {\n        vector3i p = make_vector<int>(6, 7, 8);\n        REQUIRE(slice(p, 0) == make_vector<int>(7, 8));\n        REQUIRE(slice(p, 1) == make_vector<int>(6, 8));\n        REQUIRE(slice(p, 2) == make_vector<int>(6, 7));\n    }\n\n    {\n        vector2f p = make_vector<float>(9, 17);\n        REQUIRE(slice(p, 0) == make_vector<float>(17));\n        REQUIRE(slice(p, 1) == make_vector<float>(9));\n    }\n\n    {\n        vector4i p = make_vector<int>(4, 3, 2, 1);\n        REQUIRE(slice(p, 0) == make_vector<int>(3, 2, 1));\n        REQUIRE(slice(p, 1) == make_vector<int>(4, 2, 1));\n        REQUIRE(slice(p, 2) == make_vector<int>(4, 3, 1));\n        REQUIRE(slice(p, 3) == make_vector<int>(4, 3, 2));\n    }\n}\n\nTEST_CASE(\"test_unslice_vector\")\n{\n    {\n        vector3i p = make_vector<int>(6, 7, 8);\n        REQUIRE(unslice(p, 0, 0) == make_vector<int>(0, 6, 7, 8));\n        REQUIRE(unslice(p, 1, 0) == make_vector<int>(6, 0, 7, 8));\n        REQUIRE(unslice(p, 2, 0) == make_vector<int>(6, 7, 0, 8));\n        REQUIRE(unslice(p, 3, 0) == make_vector<int>(6, 7, 8, 0));\n    }\n\n    {\n        vector2d p = make_vector<double>(9, 17);\n        REQUIRE(unslice(p, 0, 2.1) == make_vector<double>(2.1, 9, 17));\n        REQUIRE(unslice(p, 1, 2.1) == make_vector<double>(9, 2.1, 17));\n        REQUIRE(unslice(p, 2, 2.1) == make_vector<double>(9, 17, 2.1));\n    }\n}\n\nTEST_CASE(\"test_uniform_vector\")\n{\n    REQUIRE((uniform_vector<3, int>(0)) == make_vector<int>(0, 0, 0));\n    REQUIRE(\n        (uniform_vector<4, unsigned>(1)) == make_vector<unsigned>(1, 1, 1, 1));\n    REQUIRE((uniform_vector<2, float>(6)) == make_vector<float>(6, 6));\n}\n\nTEST_CASE(\"vector_almost_equal\")\n{\n    REQUIRE(almost_equal(\n        make_vector<double>(0, 0, 0),\n        make_vector<double>(0, 0, default_equality_tolerance<double>() / 2)));\n    REQUIRE(!almost_equal(\n        make_vector<float>(0, 0, 0), make_vector<float>(0, 0, 1)));\n    REQUIRE(almost_equal(\n        make_vector<float>(0, 0, 0), make_vector<float>(0, 0, 1), 2));\n}\n\nTEST_CASE(\"vector_cross\")\n{\n    // with objects\n    REQUIRE(almost_equal(\n        cross(make_vector<double>(1, 0, 0), make_vector<double>(0, 1, 0)),\n        make_vector<double>(0, 0, 1)));\n    REQUIRE(almost_equal(\n        cross(make_vector<double>(0, 1, 0), make_vector<double>(1, 0, 0)),\n        make_vector<double>(0, 0, -1)));\n\n    // with expressions\n    REQUIRE(almost_equal(\n        cross(\n            make_vector<double>(1, 0, 0) - make_vector<double>(0, 0, 0),\n            make_vector<double>(0, 1, 0) - make_vector<double>(0, 0, 0)),\n        make_vector<double>(0, 0, 1)));\n\n    // mixing expressions and objects\n    REQUIRE(almost_equal(\n        cross(\n            make_vector<double>(1, 0, 0) - make_vector<double>(0, 0, 0),\n            make_vector<double>(0, 1, 0)),\n        make_vector<double>(0, 0, 1)));\n    REQUIRE(almost_equal(\n        cross(\n            make_vector<double>(1, 0, 0),\n            make_vector<double>(0, 1, 0) - make_vector<double>(0, 0, 0)),\n        make_vector<double>(0, 0, 1)));\n}\n\nTEST_CASE(\"vector_dot\")\n{\n    // with objects\n    REQUIRE(almost_equal(\n        dot(make_vector<double>(1, 1), make_vector<double>(0.7, 0.3)), 1.));\n    REQUIRE(almost_equal(\n        dot(make_vector<double>(1, 0, 0), make_vector<double>(0, 1, 0)), 0.));\n    REQUIRE(almost_equal(\n        dot(make_vector<double>(1), make_vector<double>(0.6)), 0.6));\n    REQUIRE(dot(make_vector<int>(1, 2, 0), make_vector<int>(2, 3, 0)) == 8);\n\n    // with expressions\n    REQUIRE(almost_equal(\n        dot(make_vector<double>(1, 0, 1) - make_vector<double>(0, 0, 0),\n            make_vector<double>(0.7, 0, 0.3) - make_vector<double>(0, 0, 0)),\n        1.));\n\n    // mixing expressions and objects\n    REQUIRE(almost_equal(\n        dot(make_vector<float>(1, 1),\n            make_vector<float>(0.7f, 0.3f) - make_vector<float>(0, 0)),\n        1.f));\n    REQUIRE(almost_equal(\n        dot(make_vector<double>(1, 0, 1) - make_vector<double>(0, 0, 0),\n            make_vector<double>(0.7, 0, 0.3)),\n        1.));\n}\n\nTEST_CASE(\"vector_length\")\n{\n    // length2()\n    REQUIRE(length2(make_vector<int>(2, 0, 1)) == 5);\n\n    // length()\n    REQUIRE(almost_equal(length(make_vector<double>(2, 1)), sqrt(5.)));\n\n    // length() with an expression\n    REQUIRE(almost_equal(\n        length(make_vector<double>(2, 0, 1) - make_vector<double>(1, 0, 0)),\n        sqrt(2.)));\n}\n\nTEST_CASE(\"unit_vector\")\n{\n    REQUIRE(almost_equal(\n        unit(make_vector<double>(4, 0, 3)), make_vector<double>(0.8, 0, 0.6)));\n\n    // with an expression\n    REQUIRE(almost_equal(\n        unit(make_vector<double>(3, 0) - make_vector<double>(0, 4)),\n        make_vector<double>(0.6, -0.8)));\n}\n\nTEST_CASE(\"perpendicular_vector\")\n{\n    for (int x = -1; x < 2; ++x)\n    {\n        for (int y = -1; y < 2; ++y)\n        {\n            for (int z = -1; z < 2; ++z)\n            {\n                if (x != 0 || y != 0 || z != 0)\n                {\n                    vector<3, double> v = make_vector<double>(x, y, z);\n                    CRADLE_CHECK_ALMOST_EQUAL(\n                        dot(v, get_perpendicular(v)), 0.);\n                    CRADLE_CHECK_ALMOST_EQUAL(\n                        length(get_perpendicular(v)), 1.);\n                }\n            }\n        }\n    }\n}\n\nTEST_CASE(\"product_test\")\n{\n    REQUIRE(product(make_vector<int>(2, 3, 1)) == 6);\n    REQUIRE(product(make_vector<int>(2, -1, 3, 1)) == -6);\n\n    REQUIRE(almost_equal(product(make_vector<float>(2.5, 4, 2)), 20.f));\n    REQUIRE(almost_equal(product(make_vector<double>(2.5, 4)), 10.));\n\n    // with an expression\n    REQUIRE(\n        product(make_vector<int>(2, -1, 3, 0) - make_vector<int>(6, 0, 0, 1))\n        == -12);\n}\n\nTEST_CASE(\"vector_io\")\n{\n    vector3i p = make_vector<int>(2, 0, 3);\n    REQUIRE(to_string(p) == \"(2, 0, 3)\");\n}\n\nTEST_CASE(\"compute_mean_vector_test\")\n{\n    using namespace boost::assign;\n\n    std::vector<vector3d> vectors;\n    vectors += make_vector<double>(2, 0, 3), make_vector<double>(6, 1, 7),\n        make_vector<double>(0, 0, 0), make_vector<double>(1, 2, 0),\n        make_vector<double>(3, 2, 1), make_vector<double>(6, 4, 1);\n\n    REQUIRE(almost_equal(\n        compute_mean(vectors, uniform_vector<3>(0.)),\n        make_vector<double>(3, 1.5, 2)));\n}\n\nTEST_CASE(\"plane_test\")\n{\n    plane<double> default_constructed;\n\n    vector3d p = make_vector<double>(0, 0, 0);\n    vector3d normal = make_vector<double>(1, 0, 0);\n\n    plane<double> plane(p, normal);\n    REQUIRE(plane.point == p);\n    REQUIRE(plane.normal == normal);\n\n    vector3d q = make_vector<double>(0, 0, 1);\n    plane.point = q;\n    REQUIRE(plane.point == q);\n    REQUIRE(plane.normal == normal);\n\n    normal = make_vector<double>(0, 1, 0);\n    plane.normal = normal;\n    REQUIRE(plane.point == q);\n    REQUIRE(plane.normal == normal);\n}\n\nTEST_CASE(\"simple_box1i_test\")\n{\n    box1i b(make_vector<int>(-1), make_vector<int>(4));\n\n    REQUIRE(get_center(b)[0] == 1);\n    REQUIRE(b.corner[0] == -1);\n    REQUIRE(b.size[0] == 4);\n\n    REQUIRE(!is_inside(b, make_vector<int>(-2)));\n    REQUIRE(is_inside(b, make_vector<int>(-1)));\n    REQUIRE(is_inside(b, make_vector<int>(2)));\n    REQUIRE(!is_inside(b, make_vector<int>(3)));\n    REQUIRE(!is_inside(b, make_vector<int>(4)));\n}\n\nTEST_CASE(\"simple_box1d_test\")\n{\n    box1d b(make_vector<double>(-1), make_vector<double>(3));\n\n    CRADLE_CHECK_ALMOST_EQUAL(get_center(b), make_vector<double>(0.5));\n    CRADLE_CHECK_ALMOST_EQUAL(b.corner, make_vector<double>(-1));\n    CRADLE_CHECK_ALMOST_EQUAL(b.size, make_vector<double>(3));\n\n    REQUIRE(!is_inside(b, make_vector<double>(-2)));\n    REQUIRE(is_inside(b, make_vector<double>(-1)));\n    REQUIRE(is_inside(b, make_vector<double>(0)));\n    REQUIRE(is_inside(b, make_vector<double>(1)));\n    REQUIRE(is_inside(b, make_vector<double>(1.5)));\n    REQUIRE(is_inside(b, make_vector<double>(1.9)));\n    REQUIRE(!is_inside(b, make_vector<double>(2)));\n    REQUIRE(!is_inside(b, make_vector<double>(4)));\n}\n\nTEST_CASE(\"simple_box2d_test\")\n{\n    box2d b(make_vector<double>(-1, -1), make_vector<double>(3, 3));\n\n    CRADLE_CHECK_ALMOST_EQUAL(area(b), 9.);\n\n    CRADLE_CHECK_ALMOST_EQUAL(get_center(b), make_vector<double>(0.5, 0.5));\n    CRADLE_CHECK_ALMOST_EQUAL(b.corner, make_vector<double>(-1, -1));\n    CRADLE_CHECK_ALMOST_EQUAL(b.size, make_vector<double>(3, 3));\n\n    REQUIRE(!is_inside(b, make_vector<double>(-2, -2)));\n    REQUIRE(!is_inside(b, make_vector<double>(-2, 0)));\n    REQUIRE(!is_inside(b, make_vector<double>(0, 4)));\n    REQUIRE(!is_inside(b, make_vector<double>(0, 2)));\n    REQUIRE(is_inside(b, make_vector<double>(-1, -1)));\n    REQUIRE(is_inside(b, make_vector<double>(0, 1.9)));\n    REQUIRE(is_inside(b, make_vector<double>(0, 0)));\n    REQUIRE(is_inside(b, make_vector<double>(1.5, 1.5)));\n    REQUIRE(is_inside(b, make_vector<double>(0, 1)));\n}\n\nTEST_CASE(\"box_slicing_test\")\n{\n    REQUIRE(\n        slice(\n            box3d(make_vector<double>(0, 2, 1), make_vector<double>(4, 3, 5)),\n            0)\n        == box2d(make_vector<double>(2, 1), make_vector<double>(3, 5)));\n    REQUIRE(\n        slice(\n            box3d(make_vector<double>(0, 2, 1), make_vector<double>(4, 3, 5)),\n            1)\n        == box2d(make_vector<double>(0, 1), make_vector<double>(4, 5)));\n    REQUIRE(\n        slice(\n            box3d(make_vector<double>(0, 2, 1), make_vector<double>(4, 3, 5)),\n            2)\n        == box2d(make_vector<double>(0, 2), make_vector<double>(4, 3)));\n\n    REQUIRE(\n        slice(box2i(make_vector<int>(0, 2), make_vector<int>(4, 3)), 0)\n        == box1i(make_vector<int>(2), make_vector<int>(3)));\n    REQUIRE(\n        slice(box2i(make_vector<int>(0, 2), make_vector<int>(4, 3)), 1)\n        == box1i(make_vector<int>(0), make_vector<int>(4)));\n}\n\nTEST_CASE(\"add_box_border_test\")\n{\n    REQUIRE(\n        add_border(\n            box3i(make_vector<int>(0, 2, 1), make_vector<int>(4, 3, 5)), 2)\n        == box3i(make_vector<int>(-2, 0, -1), make_vector<int>(8, 7, 9)));\n\n    REQUIRE(\n        add_border(\n            box3i(make_vector<int>(0, 2, 1), make_vector<int>(4, 3, 5)),\n            make_vector<int>(2, 1, 0))\n        == box3i(make_vector<int>(-2, 1, 1), make_vector<int>(8, 5, 5)));\n}\n\nTEST_CASE(\"simple_vector_test\")\n{\n    circle<double> c(make_vector<double>(0, 0), 1);\n    CRADLE_CHECK_ALMOST_EQUAL(area(c), pi);\n    REQUIRE(!is_inside(c, make_vector<double>(0, 2)));\n    REQUIRE(!is_inside(c, make_vector<double>(2, 0)));\n    REQUIRE(!is_inside(c, make_vector<double>(1.1, 0)));\n    REQUIRE(!is_inside(c, make_vector<double>(0.9, 0.9)));\n    REQUIRE(!is_inside(c, make_vector<double>(0, -1.1)));\n    REQUIRE(is_inside(c, make_vector<double>(0.9, 0)));\n    REQUIRE(is_inside(c, make_vector<double>(0, 0)));\n    REQUIRE(is_inside(c, make_vector<double>(0, -0.9)));\n    REQUIRE(is_inside(c, make_vector<double>(-0.7, 0.7)));\n    REQUIRE(is_inside(c, make_vector<double>(0.3, 0.5)));\n}\n\nTEST_CASE(\"off_center_test\")\n{\n    circle<double> c(make_vector<double>(4, 1), 2);\n    CRADLE_CHECK_ALMOST_EQUAL(area(c), 4 * pi);\n    REQUIRE(!is_inside(c, make_vector<double>(0, 0)));\n    REQUIRE(!is_inside(c, make_vector<double>(1.9, 1)));\n    REQUIRE(!is_inside(c, make_vector<double>(6.1, 1)));\n    REQUIRE(!is_inside(c, make_vector<double>(4, 3.1)));\n    REQUIRE(!is_inside(c, make_vector<double>(4, -1.1)));\n    REQUIRE(is_inside(c, make_vector<double>(4, 1)));\n    REQUIRE(is_inside(c, make_vector<double>(2.6, 2.4)));\n}\n\nTEST_CASE(\"by_value_test\")\n{\n    vector2d p0 = make_vector<double>(0, 1), p1 = make_vector<double>(4, 4);\n    line_segment<2, double> segment(p0, p1);\n\n    REQUIRE(segment[0] == p0);\n    REQUIRE(segment[1] == p1);\n    CRADLE_CHECK_ALMOST_EQUAL(length(segment), 5.);\n}\n\nTEST_CASE(\"identity_matrix_test\")\n{\n    REQUIRE(\n        (identity_matrix<4, double>())\n        == make_matrix<double>(\n            1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1));\n\n    REQUIRE(\n        (identity_matrix<3, double>())\n        == make_matrix<double>(1, 0, 0, 0, 1, 0, 0, 0, 1));\n}\n\nTEST_CASE(\"matrix_operations_test\")\n{\n    matrix<3, 3, double> m, i = identity_matrix<3, double>();\n\n    m = i - 2 * i;\n    REQUIRE(m == make_matrix<double>(-1, 0, 0, 0, -1, 0, 0, 0, -1));\n\n    m *= 2;\n    REQUIRE(m == make_matrix<double>(-2, 0, 0, 0, -2, 0, 0, 0, -2));\n\n    m = i;\n    m /= 2;\n    REQUIRE(m == make_matrix<double>(0.5, 0, 0, 0, 0.5, 0, 0, 0, 0.5));\n\n    m += i * 3;\n    REQUIRE(m == make_matrix<double>(3.5, 0, 0, 0, 3.5, 0, 0, 0, 3.5));\n\n    m -= 2 * i;\n    REQUIRE(m == make_matrix<double>(1.5, 0, 0, 0, 1.5, 0, 0, 0, 1.5));\n\n    REQUIRE(m == m);\n    REQUIRE(m != i);\n}\n\nTEST_CASE(\"matrix_conversion_test\")\n{\n    matrix<3, 3, double> m(identity_matrix<3, float>());\n}\n\nTEST_CASE(\"matrix_inverse3_test\")\n{\n    matrix<4, 4, double> m\n        = translation(make_vector<double>(4, 3, 7))\n          * scaling_transformation(make_vector<double>(.1, 2, 1.2))\n          * rotation_about_x(angle<double, degrees>(90));\n\n    matrix<4, 4, double> inv_m = inverse(m);\n\n    CRADLE_CHECK_ALMOST_EQUAL(\n        transform_point(\n            inv_m, transform_point(m, make_vector<double>(0, 0, 0))),\n        make_vector<double>(0, 0, 0));\n    CRADLE_CHECK_ALMOST_EQUAL(\n        transform_point(\n            inv_m, transform_point(m, make_vector<double>(2, 1, 7))),\n        make_vector<double>(2, 1, 7));\n    CRADLE_CHECK_ALMOST_EQUAL(\n        transform_point(\n            inv_m, transform_point(m, make_vector<double>(1, 0, 17))),\n        make_vector<double>(1, 0, 17));\n}\n\nTEST_CASE(\"matrix_inverse2_test\")\n{\n    matrix<3, 3, double> m\n        = translation(make_vector<double>(3, 7))\n          * scaling_transformation(make_vector<double>(.1, 1.2))\n          * rotation(angle<double, degrees>(90));\n\n    matrix<3, 3, double> inv_m = inverse(m);\n\n    CRADLE_CHECK_ALMOST_EQUAL(\n        transform_point(inv_m, transform_point(m, make_vector<double>(0, 0))),\n        make_vector<double>(0, 0));\n    CRADLE_CHECK_ALMOST_EQUAL(\n        transform_point(inv_m, transform_point(m, make_vector<double>(1, 7))),\n        make_vector<double>(1, 7));\n    CRADLE_CHECK_ALMOST_EQUAL(\n        transform_point(inv_m, transform_point(m, make_vector<double>(0, 17))),\n        make_vector<double>(0, 17));\n}\n\nTEST_CASE(\"matrix_inverse1_test\")\n{\n    matrix<2, 2, double> m = translation(make_vector<double>(1))\n                             * scaling_transformation(make_vector<double>(.1));\n\n    matrix<2, 2, double> inv_m = inverse(m);\n\n    CRADLE_CHECK_ALMOST_EQUAL(\n        transform_point(inv_m, transform_point(m, make_vector<double>(0))),\n        make_vector<double>(0));\n    CRADLE_CHECK_ALMOST_EQUAL(\n        transform_point(inv_m, transform_point(m, make_vector<double>(7))),\n        make_vector<double>(7));\n    CRADLE_CHECK_ALMOST_EQUAL(\n        transform_point(inv_m, transform_point(m, make_vector<double>(17))),\n        make_vector<double>(17));\n    CRADLE_CHECK_ALMOST_EQUAL(\n        transform_point(inv_m, transform_point(m, make_vector<double>(1))),\n        make_vector<double>(1));\n}\n", "meta": {"hexsha": "7783499efa2be248df87d2338562e95472122b28", "size": 16052, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/geometry/common.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": "unit_tests/geometry/common.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": "unit_tests/geometry/common.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": 31.9125248509, "max_line_length": 79, "alphanum_fraction": 0.5946299527, "num_tokens": 4980, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.689305616785446, "lm_q2_score": 0.6584175139669998, "lm_q1q2_score": 0.4538508905673628}}
{"text": "#ifndef LAYER_NN\n#define LAYER_NN\n\n#include <string>\n#include <armadillo>\n\nusing namespace std;\nusing namespace arma;\n\nclass layer {\n    public:\n        /*---- Linked List ---*/\n        layer   *next;\n        layer   *prev;\n        \n        /*--- General Parameters ---*/\n        string  activation;\n        int     layerNumber;\n        int     input_size, output_size;\n        \n        /*--- Specific Parameters ---*/\n        mat     W, dW;\n        mat     B, dB;\n        \n        /*--- Input & Output ---*/\n        mat     Z, Y, dL;\n        \n        /* METHODS */\n        layer();\n        \n        void    feed(mat);\n        void    back(mat,mat);\n        void    gradient_descent(float);\n\n};\n\n#endif\n", "meta": {"hexsha": "7df4e76fdce4169307b5ac05a3724745f2706b4f", "size": 703, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "C++/include/layer.hpp", "max_stars_repo_name": "StxGuy/NobleNeuron", "max_stars_repo_head_hexsha": "03660c837c004e2871054e2ce9b1af14650ab8ed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-04-12T06:40:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-09T16:43:05.000Z", "max_issues_repo_path": "C++/include/layer.hpp", "max_issues_repo_name": "StxGuy/NobleNeuron", "max_issues_repo_head_hexsha": "03660c837c004e2871054e2ce9b1af14650ab8ed", "max_issues_repo_licenses": ["MIT"], "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++/include/layer.hpp", "max_forks_repo_name": "StxGuy/NobleNeuron", "max_forks_repo_head_hexsha": "03660c837c004e2871054e2ce9b1af14650ab8ed", "max_forks_repo_licenses": ["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.5, "max_line_length": 40, "alphanum_fraction": 0.4580369844, "num_tokens": 159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6893056167854461, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.4538508905673628}}
{"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 Sampler.cpp\n * @author Alex Cunningham\n */\n\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n\n#include <gtsam/linear/Sampler.h>\nnamespace gtsam {\n\n/* ************************************************************************* */\nSampler::Sampler(const noiseModel::Diagonal::shared_ptr& model, int32_t seed)\n\t: model_(model), generator_(static_cast<unsigned>(seed))\n{\n}\n\n/* ************************************************************************* */\nSampler::Sampler(const Vector& sigmas, int32_t seed)\n: model_(noiseModel::Diagonal::Sigmas(sigmas, true)), generator_(static_cast<unsigned>(seed))\n{\n}\n\n/* ************************************************************************* */\nSampler::Sampler(int32_t seed)\n: generator_(static_cast<unsigned>(seed))\n{\n}\n\n/* ************************************************************************* */\nVector Sampler::sampleDiagonal(const Vector& sigmas) {\n\tsize_t d = sigmas.size();\n\tVector result(d);\n\tfor (size_t i = 0; i < d; i++) {\n\t\tdouble sigma = sigmas(i);\n\n\t\t// handle constrained case separately\n\t\tif (sigma == 0.0) {\n\t\t\tresult(i) = 0.0;\n\t\t} else {\n\t\t\ttypedef boost::normal_distribution<double> Normal;\n\t\t\tNormal dist(0.0, sigma);\n\t\t\tboost::variate_generator<boost::minstd_rand&, Normal> norm(generator_, dist);\n\t\t\tresult(i) = norm();\n\t\t}\n\t}\n\treturn result;\n}\n\n/* ************************************************************************* */\nVector Sampler::sample() {\n\tassert(model_.get());\n\tconst Vector& sigmas = model_->sigmas();\n\treturn sampleDiagonal(sigmas);\n}\n\n/* ************************************************************************* */\nVector Sampler::sampleNewModel(const noiseModel::Diagonal::shared_ptr& model) {\n\tassert(model.get());\n\tconst Vector& sigmas = model->sigmas();\n\treturn sampleDiagonal(sigmas);\n}\n/* ************************************************************************* */\n\n} // \\namespace gtsam\n", "meta": {"hexsha": "6031440bd5dbc6d65f24da974f4d3f2459728d6e", "size": 2327, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/linear/Sampler.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/Sampler.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/Sampler.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": 30.2207792208, "max_line_length": 93, "alphanum_fraction": 0.4929093253, "num_tokens": 456, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6584175139669997, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.4538508905673627}}
{"text": "#ifndef DENSEFACTORIZATIONFACTORY_HPP\n#define DENSEFACTORIZATIONFACTORY_HPP\n\n#include <iostream>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\ntemplate <class serialType>\nclass denseFactorizationFactory\n{\npublic:\n\n  denseFactorizationFactory();\n\n  denseFactorizationFactory(serialType &mat);\n\n  void reset(serialType &mat);\n\n  void BDCSVD();\n\n  void HouseholderQR();\n  \n  void PartialPivLU();\n\n  serialType getU() { return U; }\n\n  serialType getSingularValues() { return S; }\n \n  serialType getV() { return V; }\n\n  serialType getQ() { return Q; }\n\nprivate:\n\n  serialType *dense_matrix_ = NULL;\n\n  // containers to store factorizations\n  serialType U;\n  serialType S;\n  serialType V;\n  serialType Q;\n\n};\n\n#include \"denseFactorizationFactory_impl.hpp\"\n\n#endif /*DENSEFACTORIZATIONFACTORY_HPP*/\n", "meta": {"hexsha": "9ba4e21f9c92a71f6e1680619986d31d9048d47c", "size": 793, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/wrapped_eigen.d/factorization.d/denseFactorizationFactory.hpp", "max_stars_repo_name": "TtheBC01/pEigen", "max_stars_repo_head_hexsha": "090ba4389df936f9c4ce3726ea807f757c57ef1f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/wrapped_eigen.d/factorization.d/denseFactorizationFactory.hpp", "max_issues_repo_name": "TtheBC01/pEigen", "max_issues_repo_head_hexsha": "090ba4389df936f9c4ce3726ea807f757c57ef1f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/wrapped_eigen.d/factorization.d/denseFactorizationFactory.hpp", "max_forks_repo_name": "TtheBC01/pEigen", "max_forks_repo_head_hexsha": "090ba4389df936f9c4ce3726ea807f757c57ef1f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.1836734694, "max_line_length": 46, "alphanum_fraction": 0.737704918, "num_tokens": 199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6893056295505784, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.4538508897317892}}
{"text": "// std::function allows us to save a function object as a member of any class\n// and to use a function between separate compilation units\n#include <boost/phoenix.hpp>\n#include <cmath>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <string>\n\nint main()\n{\n    using namespace std::string_literals;\n    using namespace boost::phoenix::arg_names;\n\n    auto testFunction = std::function<float(float, float)>{};\n\n    float a = 3;\n    float b = -4.2;\n    float x = 2;\n\n    // TODO: explore why it fails\n    // ordinary function\n    // testFunction = std::fmax;\n    // std::cout << \"max of \" << a << \" and \" << b\n    //           << \": \" << testFunction(a, b) << '\\n';\n\n    // class with a call operator\n    testFunction = std::multiplies<float>();\n    std::cout << \"multiplication of \" << a << \" and \" << b\n              << \": \" << testFunction(a, b) << '\\n';\n\n    // class with a generic call operator\n    testFunction = std::multiplies<>();\n    std::cout << \"multiplication of \" << a << \" and \" << b\n              << \": \" << testFunction(a, b) << '\\n';\n\n    // lambda\n    testFunction = [x](float a, float b) { return a * x + b; };\n    std::cout << \"lambda result: \" << testFunction(a, b) << '\\n';\n\n    // generic lambda\n    testFunction = [x](auto a, auto b) { return a * x + b; };\n    std::cout << \"generic lambda result: \" << testFunction(a, b) << '\\n';\n\n    // boost.phoenix expression\n    testFunction = (arg1 + arg2) / 2;\n    std::cout << \"boost.phoenix expression result: \"\n              << testFunction(a, b) << '\\n';\n\n\n\n    // use member function as a function object\n    auto s = \"A small pond\"s;\n    std::function<bool(std::string)> f = &std::string::empty;\n\n    std::cout << std::boolalpha;\n    std::cout << \"'\" << s  << \"'\" << \" is empty: \" << f(s) << '\\n';\n}\n", "meta": {"hexsha": "4999d3fec0ba618975b262390d7170db0c0da210", "size": 1791, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/functional_objects/wrapping_with_std_function.cpp", "max_stars_repo_name": "JIghtuse/functional-cpp", "max_stars_repo_head_hexsha": "2e8d7b69b433411b2867be269ff563aebc5520cf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-07-26T19:38:03.000Z", "max_stars_repo_stars_event_max_datetime": "2017-07-26T19:38:03.000Z", "max_issues_repo_path": "src/functional_objects/wrapping_with_std_function.cpp", "max_issues_repo_name": "JIghtuse/functional-cpp", "max_issues_repo_head_hexsha": "2e8d7b69b433411b2867be269ff563aebc5520cf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/functional_objects/wrapping_with_std_function.cpp", "max_forks_repo_name": "JIghtuse/functional-cpp", "max_forks_repo_head_hexsha": "2e8d7b69b433411b2867be269ff563aebc5520cf", "max_forks_repo_licenses": ["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.3559322034, "max_line_length": 77, "alphanum_fraction": 0.5566722501, "num_tokens": 498, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056167854461, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.45385088594718276}}
{"text": "#include <boost/units/io.hpp>\n#include <boost/units/quantity.hpp>\n#include <boost/units/systems/si.hpp>\n#include <iostream>\n\nusing Length_unit = boost::units::si::length;\nusing Time_unit = boost::units::si::time;\nusing Velocity_unit = boost::units::si::velocity;\nusing Length = boost::units::quantity<Length_unit>;\nusing Time = boost::units::quantity<Time_unit>;\nusing Velocity = boost::units::quantity<Velocity_unit>;\n\nVelocity compute_velocity(const Length dx, const Time dt) {\n    return dt/dx;\n}\n\nint main() {\n    // define units to make formulas easier to read\n    Length_unit m {boost::units::si::meter};\n    Time_unit s {boost::units::si::seconds};\n\n    Length distance {3.5*m};\n    Time time {2.0*s};\n    Velocity velocity = compute_velocity(distance, time);\n    std::cout << velocity << std::endl;\n    return 0;\n}\n", "meta": {"hexsha": "29eccb864ea1fc2493ff769ebb8e5499b5da97cb", "size": 823, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source-code/Boost/Units/units_not_okay.cpp", "max_stars_repo_name": "gjbex/Scientific-C-", "max_stars_repo_head_hexsha": "d7aeb88743ffa2a43b1df1569a9200b2447f401c", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 115.0, "max_stars_repo_stars_event_min_datetime": "2015-03-23T13:34:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T00:27:21.000Z", "max_issues_repo_path": "source-code/Boost/Units/units_not_okay.cpp", "max_issues_repo_name": "gjbex/Scientific-C-", "max_issues_repo_head_hexsha": "d7aeb88743ffa2a43b1df1569a9200b2447f401c", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 56.0, "max_issues_repo_issues_event_min_datetime": "2015-02-25T15:04:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-03T07:42:48.000Z", "max_forks_repo_path": "source-code/Boost/Units/units_not_okay.cpp", "max_forks_repo_name": "gjbex/Scientific-C-", "max_forks_repo_head_hexsha": "d7aeb88743ffa2a43b1df1569a9200b2447f401c", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 59.0, "max_forks_repo_forks_event_min_datetime": "2015-11-26T11:44:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T00:27:22.000Z", "avg_line_length": 29.3928571429, "max_line_length": 59, "alphanum_fraction": 0.7010935601, "num_tokens": 209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.689305616785446, "lm_q2_score": 0.6584175072643415, "lm_q1q2_score": 0.45385088594718276}}
{"text": "\n// Copyright (C) 2009-2012 Lorenzo Caminiti\n// Distributed under the Boost Software License, Version 1.0\n// (see accompanying file LICENSE_1_0.txt or a copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n// Home at http://www.boost.org/libs/local_function\n\n#include <boost/local_function.hpp>\n#include <boost/function.hpp>\n#include <boost/phoenix/core.hpp>\n#include <boost/phoenix/function.hpp>\n#include <boost/detail/lightweight_test.hpp>\n\n//[phoenix_factorial_local\nint main(void) {\n    using boost::phoenix::arg_names::arg1;\n\n    int BOOST_LOCAL_FUNCTION(int n) { // Unfortunately, monomorphic.\n        return (n <= 0) ? 1 : n * factorial_impl(n - 1);\n    } BOOST_LOCAL_FUNCTION_NAME(recursive factorial_impl)\n\n    boost::phoenix::function< boost::function<int (int)> >\n            factorial(factorial_impl); // Phoenix function from local function.\n\n    int i = 4;\n    BOOST_TEST(factorial(i)() == 24);      // Call.\n    BOOST_TEST(factorial(arg1)(i) == 24);  // Lazy call.\n    return boost::report_errors();\n}\n//]\n", "meta": {"hexsha": "0fd5fa53d38605f7783826bb221a152b1a8e0bf6", "size": 1017, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/libs/local_function/example/phoenix_factorial_local.cpp", "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/libs/local_function/example/phoenix_factorial_local.cpp", "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/libs/local_function/example/phoenix_factorial_local.cpp", "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": 32.8064516129, "max_line_length": 79, "alphanum_fraction": 0.6961651917, "num_tokens": 263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.689305616785446, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.4538508859471827}}
{"text": "#pragma once\n\n#ifdef PY_BINDINGS\n    #include <pybind11/pybind11.h>\n    #include <pybind11/stl.h>\n    #include <pybind11/iostream.h>\n    #include <pybind11/functional.h>\n    namespace py = pybind11;\n#endif\n\n// #include <boost/multiprecision/gmp.hpp>\n// using BigInt = boost::multiprecision::mpz_int;\n// namespace std {\n//     inline BigInt abs(BigInt num) {\n//         return boost::multiprecision::abs(num);\n//     }\n// }\n// inline std::string toString(BigInt& num, int base = 10) {\n//     num.str(base);\n// }\n\n#include <gmpxx.h>\nusing BigInt = mpz_class;\nnamespace std {\n    inline BigInt abs(BigInt& num) {\n        return ::abs(num);\n    }\n}\n\ninline std::string toString(BigInt& num, int base = 10) {\n    return num.get_str(base);\n}\n\n#ifdef PY_BINDINGS\n    namespace pybind11 { namespace detail {\n        template <> struct type_caster<BigInt> {\n        public:\n            /**\n             * This macro establishes the name 'BigInt' in\n             * function signatures and declares a local variable\n             * 'value' of type BigInt\n             */\n            PYBIND11_TYPE_CASTER(BigInt, _(\"BigInt\"));\n\n            /**\n             * Conversion part 1 (Python->C++): convert a PyObject into a BigInt\n             * instance or return false upon failure. The second argument\n             * indicates whether implicit conversions should be applied.\n             */\n            bool load(handle src, bool) {\n                /* Extract PyObject from handle */\n                PyObject *source = src.ptr();\n                /* Try converting into a Python integer value */\n                PyObject *pyNumber = nullptr;\n                PyObject *pyString = nullptr;\n\n                bool error = false;\n\n                pyNumber = PyNumber_Long(source);\n                if (!pyNumber) {\n                    error = true;\n                } else {\n                    // using base 10 because boost multiprecision does not\n                    // seem to support sign for base 16\n                    pyString = PyNumber_ToBase(pyNumber,10);\n                    if (!pyString) {\n                        error = true;\n                    } else {\n                        const char* string = PyUnicode_AsUTF8(pyString);\n                        if (string) {\n                            try {\n                                value = BigInt(string);\n                            } catch (const std::runtime_error& e) {\n                                error = true;\n                            }\n                        }\n\n\n                    }\n\n                }\n\n                error |= (PyErr_Occurred() != nullptr);\n                if (pyNumber)\n                    Py_DECREF(pyNumber);\n                if (pyString)\n                    Py_DECREF(pyString);\n                return !error;\n            }\n\n            /**\n             * Conversion part 2 (C++ -> Python): convert an BigInt instance into\n             * a Python object. The second and third arguments are used to\n             * indicate the return value policy and parent object (for\n             * ``return_value_policy::reference_internal``) and are generally\n             * ignored by implicit casters.\n             */\n            static handle cast(BigInt src, return_value_policy /* policy */, handle /* parent */) {\n                std::string string = toString(src,10);\n                PyObject *pyString = PyUnicode_FromString(string.c_str());\n                PyObject *result = PyNumber_Long(pyString);\n                Py_DECREF(pyString);\n                return result;\n            }\n        };\n    }} // namespace pybind11::detail\n#endif // ifdef PY_BINDINGS", "meta": {"hexsha": "83a9efdd624f5ec4d0fc8238f0c288e13751a288", "size": 3635, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "veripb/optimized/BigInt.hpp", "max_stars_repo_name": "StephanGocht/VeriPB", "max_stars_repo_head_hexsha": "a6b4314be574f09af0736600583dc714a469c0d7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-03-03T16:16:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T09:23:36.000Z", "max_issues_repo_path": "veripb/optimized/BigInt.hpp", "max_issues_repo_name": "StephanGocht/VeriPB", "max_issues_repo_head_hexsha": "a6b4314be574f09af0736600583dc714a469c0d7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 25.0, "max_issues_repo_issues_event_min_datetime": "2019-11-19T17:23:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-23T16:51:46.000Z", "max_forks_repo_path": "veripb/optimized/BigInt.hpp", "max_forks_repo_name": "StephanGocht/VeriPB", "max_forks_repo_head_hexsha": "a6b4314be574f09af0736600583dc714a469c0d7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-01T02:15:59.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-01T02:15:59.000Z", "avg_line_length": 33.9719626168, "max_line_length": 99, "alphanum_fraction": 0.5031636864, "num_tokens": 722, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.45385088552939595}}
{"text": "#include \"../src/streamingcc_include/hyper_loglog.h\"\n#define BOOST_TEST_MODULE ClassTest\n#define BOOST_TEST_DYN_LINK\n\n#include <boost/test/unit_test.hpp>\n#include <random>\n#include <map>\n#include <iostream>\n#include <vector>\n#include <set>\n\nusing namespace streamingcc;\nusing namespace std;\n\nBOOST_AUTO_TEST_CASE(util_Test) {\n    hyper_loglog count;\n    set<int> s;\n    for(int i = 0; i < 100000; ++i)\n    {\n      int cur = rand() % 10000000;\n      s.insert(cur);\n      count.update(cur);\n    }\n    int e = count.estimate(), ans = s.size();\n    BOOST_CHECK(e >= 0.1 * ans && e <= 10 * ans);\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "ba849dc92247a5cd91f0edee1fb53b3727abc264", "size": 612, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tests/hyper_loglog_test.cc", "max_stars_repo_name": "jiecchen/StreamingCC", "max_stars_repo_head_hexsha": "34547a16239735771341a5bb202204b71c6d1fa2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28.0, "max_stars_repo_stars_event_min_datetime": "2015-10-24T12:35:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-19T04:46:40.000Z", "max_issues_repo_path": "tests/hyper_loglog_test.cc", "max_issues_repo_name": "jiecchen/StreamingCC", "max_issues_repo_head_hexsha": "34547a16239735771341a5bb202204b71c6d1fa2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-06-18T13:46:35.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-18T13:46:35.000Z", "max_forks_repo_path": "tests/hyper_loglog_test.cc", "max_forks_repo_name": "jiecchen/StreamingCC", "max_forks_repo_head_hexsha": "34547a16239735771341a5bb202204b71c6d1fa2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2016-06-25T03:56:08.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-07T08:49:14.000Z", "avg_line_length": 13.3043478261, "max_line_length": 52, "alphanum_fraction": 0.635620915, "num_tokens": 162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056295505784, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.45385088511160904}}
{"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_SHUFFLE_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_SHUFFLE_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n  /*!\n    @ingroup group-swar\n\n    Shuffle the elements of a boost::simd::pack using an index permutation described by compile-time\n    integral constants.\n\n    @par Semantic:\n\n    For any boost::simd::pack @c x of base type @c T and cardinal @c N and @c N compile-time\n    integral constants @c I1...In with value comprised between @c -1 and @c N-1, the following code:\n\n    @code\n    boost::simd::pack<T,N> r = shuffle<I1,...,In>(x);\n    @endcode\n\n    is equivalent to:\n\n    @code\n    boost::simd::pack<T,N> r{ I1 != -1 ? x[I1] : 0, ..., In != -1 ? x[In] : 0 };\n    @endcode\n\n    The actual integral constants is mapped at compile-time to the optimal sequence of\n    intrinsics to apply the desired permutation.\n\n    The special index value @c -1 is used to specify that, instead of fetching a data from inside\n    the shuffled boost::simd::pack, the value @c 0 has to be inserted in the result.\n\n    @par Example:\n\n    @snippet shuffle.unary.cpp shuffle-unary\n\n    Possible output:\n\n    @code\n    Original: (1, 2, 3, 4)\n    Permuted: (4, 0, 3, 1)\n    @endcode\n\n    @param  a  boost::simd::pack to shuffle\n  **/\n  template<int P0, int ... Ps, typename T>  T shuffle(T const& a);\n\n  /*!\n    @ingroup group-swar\n\n    Shuffle the elements of two boost::simd::pack using an index permutation described by compile-time\n    integral constants.\n\n    @par Semantic:\n\n    For any boost::simd::pack @c x and @c y of base type @c T and cardinal @c N and @c N\n    compile-time integral constants @c I1...In with value comprised between @c -1 and @c 2*N-1,\n    the following code:\n\n    @code\n    boost::simd::pack<T,N> r = shuffle<I1,...,In>(x,y);\n    @endcode\n\n    is equivalent to:\n\n    @code\n    boost::simd::pack<T,N> r{ I1 != -1 ? (I1<N ? x[I1] : y[I1-N]) : 0, ..., In != -1 ? (In<N ? x[In] : y[In-N]) : 0 };\n    @endcode\n\n    The actual integral constants is mapped at compile-time to the optimal sequence of\n    intrinsics to apply the desired permutation.\n\n    The special index value @c -1 is used to specify that, instead of fetching a data from inside\n    the shuffled boost::simd::pack, the value @c 0 has to be inserted in the result.\n\n    @par Example:\n\n    @snippet shuffle.binary.cpp shuffle-binary\n\n    Possible output:\n\n    @code\n    Original: (1, 2, 3, 4) (10, 20, 30, 40)\n    Permuted: (0, 4, 40, 0)\n    @endcode\n\n    @param  a  boost::simd::pack to shuffle\n    @param  b  boost::simd::pack to shuffle\n  **/\n  template<int P0, int ... Ps, typename T>  T shuffle(T const& a,T const& b);\n\n  /*!\n    @ingroup group-swar\n\n    Shuffle the elements of a boost::simd::pack using an index permutation described by compile-time\n    meta-function.\n\n    @par Semantic:\n\n    For any boost::simd::pack @c x of base type @c T and cardinal @c N and a meta-function @c Perm,\n    the following code:\n\n    @code\n    boost::simd::pack<T,N> r = shuffle<Perm>(x);\n    @endcode\n\n    is equivalent to:\n\n    @code\n    boost::simd::pack<T,N> r = shuffle<Perm::apply<0,N>::value,...,Perm::apply<N-1,N>::value>(x);\n    @endcode\n\n    The permutation computed by the meta-function @c Perm is mapped at compile-time to the\n    optimal sequence of intrinsics to apply the desired permutation.\n\n    @par Defining a permutation meta-function\n\n    Permutation meta-function can be built in two different ways:\n\n    - Define a Permutation meta-function as a struct with an internal @c apply structure that\n      proceed to compute a given permutation index at compile-time. This @c apply internal\n      structure takes two integral constant types as parameter: @c C the cardinal of the\n      boost::simd::pack to be shuffled and @c I the index of the permutation index computed.\n\n    - Define a @c constexpr function taking two integers: @c c the cardinal of the boost::simd::pack\n      to be shuffled and @c i the index of the permutation index computed. This function returns the\n      computed value of the permutation index computed. Said function is then wrapped inside the\n      boost::simd::pattern template type before being used with boost::simd::shuffle.\n\n    The special index value @c -1 can be returned to specify that, instead of fetching a data from\n    inside the shuffled boost::simd::pack, the value @c 0 has to be inserted in the result.\n\n    @notebox{Using permutation expressed as a metafunction has the advantage to be cardinal agnostic,\n    thus making a given shuffle calls independant of the actual pack cardinal, leading to a more\n    generic code}\n\n    @par Example:\n\n    @snippet shuffle.perm.cpp shuffle-perm\n\n    Possible output:\n\n    @code\n    Original: (1, 2, 3, 4)\n    Permuted: (4, 0, 3, 1)\n    Permuted: (4, 4, 4, 4)\n    @endcode\n\n    @tparam Permutation Permutation meta-function generating the permutation index\n    @param  a           boost::simd::pack to shuffle\n  **/\n  template<typename Permutation, typename T>  T shuffle(T const& a);\n\n  /*!\n    @ingroup group-swar\n\n    Shuffle the elements of two boost::simd::pack using an index permutation described by compile-time\n    meta-function.\n\n    @par Semantic:\n\n    For any boost::simd::pack @c x and @c y of base type @c T and cardinal @c N and a meta-function @c Perm,\n    the following code:\n\n    @code\n    boost::simd::pack<T,N> r = shuffle<Perm>(x,y);\n    @endcode\n\n    is equivalent to:\n\n    @code\n    boost::simd::pack<T,N> r = shuffle<Perm::apply<0,N>::value,...,Perm::apply<N-1,N>::value>(x,y);\n    @endcode\n\n    The permutation computed by the meta-function @c Perm is mapped at compile-time to the\n    optimal sequence of intrinsics to apply the desired permutation.\n\n    @par Defining a permutation meta-function\n\n    Permutation meta-function can be built in two different ways:\n\n    - Define a Permutation meta-function as a struct with an internal @c apply structure that\n      proceed to compute a given permutation index at compile-time. This @c apply internal\n      structure takes two integral constant types as parameter: @c C the cardinal of the\n      boost::simd::pack to be shuffled and @c I the index of the permutation index computed.\n\n    - Define a @c constexpr function taking two integers: @c c the cardinal of the boost::simd::pack\n      to be shuffled and @c i the index of the permutation index computed. This function returns the\n      computed value of the permutation index computed. Said function is then wrapped inside the\n      boost::simd::pattern template type before being used with boost::simd::shuffle.\n\n    The special index value @c -1 can be returned to specify that, instead of fetching a data from\n    inside the shuffled boost::simd::pack, the value @c 0 has to be inserted in the result.\n\n    @notebox{Using permutation expressed as a metafunction has the advantage to be cardinal agnostic,\n    thus making a given shuffle calls independant of the actual pack cardinal, leading to a more\n    generic code}\n\n    @par Example:\n\n    @snippet shuffle.perm2.cpp shuffle-perm2\n\n    Possible output:\n\n    @code\n    Original: (1, 2, 3, 4)\n    Permuted: (10, 20, 3, 4)\n    @endcode\n\n    @tparam Permutation Permutation meta-function generating the permutation index\n    @param  a           boost::simd::pack to shuffle\n    @param  b           boost::simd::pack to shuffle\n  **/\n  template<typename Permutation, typename T>  T shuffle(T const& a,T const& b);\n} }\n#endif\n\n#include <boost/simd/function/scalar/shuffle.hpp>\n#include <boost/simd/function/simd/shuffle.hpp>\n\n#endif\n", "meta": {"hexsha": "f32bdd367570976db85609c7f9feb3d11ab39318", "size": 7933, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/shuffle.hpp", "max_stars_repo_name": "nickporubsky/boost-simd-clone", "max_stars_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_stars_repo_licenses": ["BSL-1.0"], "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": "include/boost/simd/function/shuffle.hpp", "max_issues_repo_name": "timblechmann/boost.simd", "max_issues_repo_head_hexsha": "2217f1d0102193799469b533e3a7118bf4a77dde", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/function/shuffle.hpp", "max_forks_repo_name": "timblechmann/boost.simd", "max_forks_repo_head_hexsha": "2217f1d0102193799469b533e3a7118bf4a77dde", "max_forks_repo_licenses": ["BSL-1.0"], "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": 34.0472103004, "max_line_length": 118, "alphanum_fraction": 0.6667086852, "num_tokens": 2017, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.6893056104028797, "lm_q1q2_score": 0.4538508771246093}}
{"text": "/**\n *  Author: Cedric LE GENTIL\n *\n *  Copyright 2021 Cedric LE GENTIL\n *\n *  This run Monte Carlo simulation experiements for the paper\n *  \n *  Disclaimer:\n *  This code is not optimised neither for performance neither for maintainability.\n *  There might still be errors in the code, logic or procedure. Every feedback is welcomed.\n *\n *  For any further question or if you see any problem in that code\n *  le.gentil.cedric@gmail.com\n **/\n\n\n#include <iostream>\n#include <string>\n\n\n#include <boost/program_options.hpp>\n#include \"sensor_input/imu_simulator.h\"\n#include \"imu_preintegration/preintegration.h\"\n#include \"common/random.h\"\n#include \"common/utils.h\"\n\n\ncelib::PreintMeas VanillaPreintegration(celib::ImuData data, double start_t, double t)\n{\n    celib::PreintMeas output;\n    output.delta_R = celib::Mat3::Identity();\n    output.delta_v = celib::Vec3::Zero();\n    output.delta_p = celib::Vec3::Zero();\n    output.cov = celib::Mat9::Zero();\n\n    int counter = 0;\n    while(start_t > data.gyr[counter].t)\n    {\n        counter++;\n        if(counter == data.acc.size())\n        {\n            throw std::range_error(\"VanillaPreintegration: looks like integration window is out of data\");\n        }\n    }\n\n    double dt = data.gyr[counter].t - start_t;\n    celib::Vec3 acc;\n    acc << data.acc[counter-1].data[0],\n           data.acc[counter-1].data[1],\n           data.acc[counter-1].data[2];\n    celib::Vec3 gyr;\n    gyr << data.gyr[counter-1].data[0],\n           data.gyr[counter-1].data[1],\n           data.gyr[counter-1].data[2];\n\n\n    celib::Mat6 cov_imu = celib::Mat6::Identity();\n    cov_imu.block<3,3>(0,0) = data.gyr_var*celib::Mat3::Identity();\n    cov_imu.block<3,3>(3,3) = data.acc_var*celib::Mat3::Identity();\n\n    while(t > data.gyr[counter].t)\n    {\n        celib::Vec3 acc_rot = output.delta_R*acc;\n        output.delta_p = output.delta_p + (output.delta_v*dt) + (acc_rot*dt*dt/2.0);\n        output.delta_v = output.delta_v + (acc_rot*dt);\n        celib::Mat3 e_R = celib::ExpMap(gyr*dt);\n        celib::Mat3 j_r = celib::JacobianRighthandExpMap<double>(gyr*dt);\n        celib::Mat9 A = celib::Mat9::Identity();\n        celib::Mat9_6 B = celib::Mat9_6::Zero();\n        celib::Mat3 skew_acc = celib::ToSkewSymMat(acc);\n        A.block<3,3>(0,0) = e_R.transpose();\n        A.block<3,3>(3,0) = -output.delta_R*skew_acc*dt;\n        A.block<3,3>(6,0) = -output.delta_R*skew_acc*dt*dt/2.0;\n        A.block<3,3>(6,3) = celib::Mat3::Identity();\n\n        B.block<3,3>(0,0) = j_r*dt;\n        B.block<3,3>(3,3) = output.delta_R*dt;\n        B.block<3,3>(3,6) = output.delta_R*dt*dt/2.0;\n\n        \n        output.delta_R = output.delta_R*e_R;\n\n        output.cov = (A*output.cov*A.transpose()) + (B*cov_imu*B.transpose());\n\n        if(counter >= (data.acc.size()-1))\n        {\n            throw std::range_error(\"VanillaPreintegration: looks like integration window is out of data\");\n        }else{\n            counter++;\n            acc << data.acc[counter-1].data[0],\n                data.acc[counter-1].data[1],\n                data.acc[counter-1].data[2];\n            gyr << data.gyr[counter-1].data[0],\n                data.gyr[counter-1].data[1],\n                data.gyr[counter-1].data[2];\n            dt = data.acc[counter].t - data.acc[counter-1].t;\n            if( (data.acc[counter-1].t < t) && (t < data.acc[counter].t) )\n            {\n                dt = t - data.acc[counter-1].t;\n            }\n\n        }\n    }\n    return output;\n}\n\n\n\nint main(int argc, char* argv[]){\n\n    celib::PreintOption preint_opt;\n    preint_opt.min_freq = 500;\n    \n\n    int nb_monte_carlo = 100;\n    double overlap = 0.15;\n\n    \n    // Program options\n    boost::program_options::options_description opt_description(\"Allowed options\");\n    opt_description.add_options()\n        (\"help,h\", \"Produce help message\")\n        (\"experiment,e\", boost::program_options::value< int >(), \"1 = accuracy metrics (default), 2 = computation time, 3 = noise robustness, 4 = bias correction\")\n        (\"nb_monte_carlo,n\", boost::program_options::value< int >(), \"(default = 100)\")\n        ;\n\n    boost::program_options::variables_map var_map;\n    boost::program_options::store(boost::program_options::parse_command_line(argc, argv, opt_description), var_map);\n    boost::program_options::notify(var_map);    \n\n    // Check help options\n    if(var_map.count(\"help\")) {\n        std::cout << opt_description << std::endl;\n        return 1;\n    }\n    \n    int experiment_type = 1;\n    if(var_map.count(\"experiment\"))\n    {\n        experiment_type = var_map[\"experiment\"].as<int>();\n    }\n    if(var_map.count(\"nb_monte_carlo\"))\n    {\n        nb_monte_carlo = var_map[\"nb_monte_carlo\"].as<int>();\n    }\n\n\n    if(experiment_type == 1)\n    { // Metrics for the accuracy  with realistic noise\n\n        std::cout << \"ACCURACY EXPERIMENT\" << std::endl;\n        std::cout.precision(3);\n\n        std::vector<double> durations = {0.05, 0.1, 0.5, 1.0};\n        celib::ImuSimulatorOption sim_opt;\n        sim_opt.acc_std = 0.04;\n        sim_opt.gyr_std = 0.01;\n\n        int nb_methods = 7;\n\n        std::vector<std::vector<std::vector<double> > > rot_error_avg;\n        std::vector<std::vector<std::vector<double> > > rot_error_std;\n        std::vector<std::vector<std::vector<double> > > vel_error_avg;\n        std::vector<std::vector<std::vector<double> > > vel_error_std;\n        std::vector<std::vector<std::vector<double> > > pos_error_avg;\n        std::vector<std::vector<std::vector<double> > > pos_error_std;\n        std::vector<std::vector<std::vector<double> > > rot_rel_error_avg;\n        std::vector<std::vector<std::vector<double> > > pos_rel_error_avg;\n\n        std::vector<double> avg_ang_vel;\n        std::vector<double> avg_vel;\n        for(int type = 0; type < 2; ++type)\n        {\n            rot_error_avg.push_back(std::vector<std::vector<double> >());\n            rot_error_std.push_back(std::vector<std::vector<double> >());\n            vel_error_avg.push_back(std::vector<std::vector<double> >());\n            vel_error_std.push_back(std::vector<std::vector<double> >());\n            pos_error_avg.push_back(std::vector<std::vector<double> >());\n            pos_error_std.push_back(std::vector<std::vector<double> >());\n            rot_rel_error_avg.push_back(std::vector<std::vector<double> >());\n            pos_rel_error_avg.push_back(std::vector<std::vector<double> >());\n\n            \n            avg_vel.push_back(0);\n            avg_ang_vel.push_back(0);\n\n            if(type == 1)\n            {\n                sim_opt.motion_type = \"slow\";\n            }\n            else\n            {\n                sim_opt.motion_type = \"fast\";\n            }\n            std::cout << \"===============================================\" << std::endl;\n            std::cout << \"Run results for \" << sim_opt.motion_type << \" motion\" << std::endl;\n            for(int d = 0; d < durations.size(); ++d)\n            {\n\n                rot_error_avg[type].push_back(std::vector<double>(nb_methods,0.0));\n                rot_error_std[type].push_back(std::vector<double>(nb_methods,0.0));\n                vel_error_avg[type].push_back(std::vector<double>(nb_methods,0.0));\n                vel_error_std[type].push_back(std::vector<double>(nb_methods,0.0));\n                pos_error_avg[type].push_back(std::vector<double>(nb_methods,0.0));\n                pos_error_std[type].push_back(std::vector<double>(nb_methods,0.0));\n                rot_rel_error_avg[type].push_back(std::vector<double>(nb_methods,0.0));\n                pos_rel_error_avg[type].push_back(std::vector<double>(nb_methods,0.0));\n                std::cout << \"Duration : \" << durations[d] << \" s\" << std::endl;\n\n\n                std::vector<std::vector<double> > rot_errors(nb_methods);\n                std::vector<std::vector<double> > vel_errors(nb_methods);\n                std::vector<std::vector<double> > pos_errors(nb_methods);\n                std::vector<std::vector<double> > rot_rel_errors(nb_methods);\n                std::vector<std::vector<double> > pos_rel_errors(nb_methods);\n                for(int i = 0; i < nb_monte_carlo; ++i)\n                {\n                    std::cout << i << \".\" << std::flush;\n                    celib::ImuSimulator imu_sim(sim_opt);\n                    avg_vel[type] += imu_sim.getAvgVel();\n                    avg_ang_vel[type] += imu_sim.getAvgAngVel();\n                    celib::RandomGenerator rand_gen;\n                    double start_t = rand_gen.randUniform(overlap,sim_opt.dataset_length - durations[d] - overlap);\n                    double end_t = start_t + durations[d];\n                    auto data = imu_sim.get(start_t-overlap, end_t+overlap);\n\n                    double pos_dist = imu_sim.getTranslationDistance(start_t, end_t);\n                    double rot_dist = imu_sim.getOrientationDistance(start_t, end_t);\n\n\n                    for(int method = 0; method < nb_methods; ++method)\n                    {\n                        celib::PreintMeas preint;\n                        if(method == 0)\n                        {\n                            preint = VanillaPreintegration(data, start_t, end_t);\n                        }\n                        else\n                        {\n                            // Create a preintegration object\n                            celib::PreintPrior prior;\n                            std::vector<std::vector<double> > t;\n                            std::vector<double> temp_t;\n                            temp_t.push_back(end_t);\n                            t.push_back(temp_t);\n                            if(method == 1)\n                            {\n                                preint_opt.type = celib::LPM;\n                                preint_opt.train_gpm = false;\n                                preint_opt.quantum = -1;\n                            }\n                            else if(method == 2)\n                            {\n                                preint_opt.type = celib::GPM;\n                                preint_opt.train_gpm = false;\n                                preint_opt.quantum = -1;\n                            }\n                            else if(method == 3)\n                            {\n                                preint_opt.type = celib::GPM;\n                                preint_opt.train_gpm = true;\n                                preint_opt.quantum = -1;\n                            }\n                            else if(method == 4)\n                            {\n                                preint_opt.type = celib::UGPM;\n                                preint_opt.train_gpm = false;\n                                preint_opt.quantum = -1;\n                            }\n                            else if(method == 5)\n                            {\n                                preint_opt.type = celib::UGPM;\n                                preint_opt.train_gpm = true;\n                                preint_opt.quantum = -1;\n                            }\n                            else\n                            {\n                                preint_opt.type = celib::UGPM;\n                                preint_opt.train_gpm = false;\n                                preint_opt.quantum = 0.2;\n                            }\n                            celib::ImuPreintegration imu_preint(data, start_t, t, preint_opt, prior);\n                            preint = imu_preint.get(0,0);\n\n                        }\n                        auto error = imu_sim.testPreint(start_t, end_t, preint);\n                        rot_errors[method].push_back(error[0]);\n                        vel_errors[method].push_back(error[1]);\n                        pos_errors[method].push_back(error[2]);\n                        rot_rel_errors[method].push_back(error[0]/rot_dist);\n                        pos_rel_errors[method].push_back(error[2]/pos_dist);\n                    }\n                }\n                std::cout << std::endl;\n\n                for(int method = 0; method < nb_methods; ++method)\n                {\n                    for(int i = 0; i < nb_monte_carlo; ++i)\n                    {\n                        rot_error_avg[type][d][method] += rot_errors[method][i];\n                        vel_error_avg[type][d][method] += vel_errors[method][i];\n                        pos_error_avg[type][d][method] += pos_errors[method][i];\n                        rot_rel_error_avg[type][d][method] += rot_rel_errors[method][i];\n                        pos_rel_error_avg[type][d][method] += pos_rel_errors[method][i];\n                    }\n                    rot_error_avg[type][d][method] /= nb_monte_carlo;\n                    vel_error_avg[type][d][method] /= nb_monte_carlo;\n                    pos_error_avg[type][d][method] /= nb_monte_carlo;\n                    rot_rel_error_avg[type][d][method] /= nb_monte_carlo;\n                    pos_rel_error_avg[type][d][method] /= nb_monte_carlo;\n                    for(int i = 0; i < nb_monte_carlo; ++i)\n                    {\n                        rot_error_std[type][d][method] += std::pow(rot_errors[method][i] - rot_error_avg[type][d][method],2);\n                        vel_error_std[type][d][method] += std::pow(vel_errors[method][i] - vel_error_avg[type][d][method],2);\n                        pos_error_std[type][d][method] += std::pow(pos_errors[method][i] - pos_error_avg[type][d][method],2);\n                    }\n                    rot_error_std[type][d][method] = std::sqrt(rot_error_std[type][d][method]/nb_monte_carlo);\n                    vel_error_std[type][d][method] = std::sqrt(vel_error_std[type][d][method]/nb_monte_carlo);\n                    pos_error_std[type][d][method] = std::sqrt(pos_error_std[type][d][method]/nb_monte_carlo);\n\n                }\n            }\n        }\n\n\n        std::cout << std::endl << \"RESULT \" << std::endl << \"(Methods: 0 = PM, 1 = LPM, 2 = GPM, 3 = UGPM, 4 = GPM trained, 5 = UGPM trained, 6 = UGPM per chunk\" << std::endl;\n        for(int type = 0; type < 2; ++type)\n        {\n            avg_vel[type] /= double(nb_monte_carlo);\n            avg_ang_vel[type] /= double(nb_monte_carlo);\n\n            if(type == 1) std::cout << std::endl << std::endl << \"Slow motion\" << std::endl;\n            if(type == 0) std::cout << std::endl << std::endl << \"Fast motion\" << std::endl;\n            std::cout << \"Avg velocity : \" << avg_vel[type] << \" m/s    Avg ang velocity : \" << avg_ang_vel[type] << \" rad/s\" << std::endl;\n            std::cout << \" Rot and Pos error ====\" << std::endl;\n            std::cout << \"Duration \\\\ method\";\n            for(int i = 0; i < nb_methods; ++i) std::cout << \"      \" << i;\n            std::cout << std::endl;\n            for(int d = 0; d < durations.size(); ++d)\n            {\n                std::cout << \"\\\\\\\\ \\\\hline \\\\hline\" << std::endl;\n                std::cout << \"\\\\multirow{4}{*}{\" << durations[d] << \"} & Rot abs. er. [$\\\\,\\\\mathrm{mrad}$]      \";\n                for(int method = 0; method < nb_methods; ++method)\n                {\n                    std::cout << \" &  \" << \"\\\\scriptsize \" << rot_error_avg[type][d][method]*1000.0 << \" $\\\\pm$ \" << rot_error_std[type][d][method]*1000.0;\n\n                }\n                std::cout << std::endl;\n                std::cout << \"\\\\\\\\ & Rot rel. er.      \";\n                for(int method = 0; method < nb_methods; ++method)\n                {\n                    std::cout << \" &  \" << \"\\\\scriptsize \" << rot_rel_error_avg[type][d][method]*100.0 << \"\\\\%\";\n\n                }\n                std::cout << std::endl;\n                std::cout << \"\\\\\\\\ \\\\cline{2-9}\" << std::endl;\n                std::cout << \" & Pos abs. er. [$\\\\,\\\\mathrm{mm}$]      \";\n                for(int method = 0; method < nb_methods; ++method)\n                {\n                    std::cout << \" &  \" << \"\\\\scriptsize \" << pos_error_avg[type][d][method]*1000.0 << \" $\\\\pm$ \" << pos_error_std[type][d][method]*1000.0;\n                }\n                std::cout << std::endl;\n                std::cout << \"\\\\\\\\ & Pos rel. er.      \";\n                for(int method = 0; method < nb_methods; ++method)\n                {\n                    std::cout << \" &  \" << \"\\\\scriptsize \" << pos_rel_error_avg[type][d][method]*100.0 << \"\\\\%\";\n\n                }\n                std::cout << std::endl;\n            }\n            std::cout << std::endl << \" Rot error ====\" << std::endl;\n            std::cout << \"Duration \\\\ method\";\n            for(int i = 0; i < nb_methods; ++i) std::cout << \"      \" << i;\n            std::cout << std::endl;\n            for(int d = 0; d < durations.size(); ++d)\n            {\n                std::cout << durations[d] << \"\\\\\\\\              \";\n                for(int method = 0; method < nb_methods; ++method)\n                {\n                    std::cout << \" &  \" << rot_error_avg[type][d][method] << \" $\\\\pm$ \" << rot_error_std[type][d][method];\n                }\n                std::cout << std::endl;\n            }\n            std::cout << std::endl << \" Vel error ====\" << std::endl;\n            std::cout << \"Duration \\\\ method\";\n            for(int i = 0; i < nb_methods; ++i) std::cout << \"      \" << i;\n            std::cout << std::endl;\n            for(int d = 0; d < durations.size(); ++d)\n            {\n                std::cout << durations[d] << \"\\\\\\\\              \";\n                for(int method = 0; method < nb_methods; ++method)\n                {\n                    std::cout << \" &  \" << vel_error_avg[type][d][method] << \" $\\\\pm$ \" << vel_error_std[type][d][method];\n                }\n                std::cout << std::endl;\n            }\n            std::cout << std::endl << \" Pos error ====\" << std::endl;\n            std::cout << \"Duration \\\\ method\";\n            for(int i = 0; i < nb_methods; ++i) std::cout << \"      \" << i;\n            std::cout << std::endl;\n            for(int d = 0; d < durations.size(); ++d)\n            {\n                std::cout << durations[d] << \"              \";\n                for(int method = 0; method < nb_methods; ++method)\n                {\n                    std::cout << \" &  \" << pos_error_avg[type][d][method] << \" $\\\\pm$ \" << pos_error_std[type][d][method];\n                }\n                std::cout << std::endl;\n            }\n        }\n    }\n\n    if(experiment_type == 2)\n    { // Metrics for the computation time  with realistic noise\n\n        std::cout << \"COMPUTATION TIME EXPERIMENT\" << std::endl;\n        std::cout.precision(4);\n\n        std::vector<double> durations = {0.05, 0.1, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5};\n        celib::ImuSimulatorOption sim_opt;\n        sim_opt.acc_std = 0.04;\n        sim_opt.gyr_std = 0.01;\n\n        int nb_methods = 7;\n\n        std::vector<std::vector<double> > time_average;\n\n        celib::StopWatch stop_watch;\n\n        std::cout << \"===============================================\" << std::endl;\n        for(int d = 0; d < durations.size(); ++d)\n        {\n\n            time_average.push_back(std::vector<double>(nb_methods,0.0));\n            std::cout << \"Duration : \" << durations[d] << \" s\" << std::endl;\n\n\n            for(int i = 0; i < nb_monte_carlo; ++i)\n            {\n                std::cout << i << \".\" << std::flush;\n                celib::ImuSimulator imu_sim(sim_opt);\n                celib::RandomGenerator rand_gen;\n                double start_t = rand_gen.randUniform(overlap,sim_opt.dataset_length - durations[d] - overlap);\n                double end_t = start_t + durations[d];\n                auto data = imu_sim.get(start_t-overlap, end_t+overlap);\n\n                for(int method = 0; method < nb_methods; ++method)\n                {\n                    celib::PreintMeas preint;\n                    double time;\n                    stop_watch.reset();\n                    if(method == 0)\n                    {\n                        stop_watch.start();\n                        preint = VanillaPreintegration(data, start_t, end_t);\n                        time = stop_watch.stop();\n                    }\n                    else\n                    {\n                        // Create a preintegration object\n                        celib::PreintPrior prior;\n                        std::vector<std::vector<double> > t;\n                        std::vector<double> temp_t;\n                        temp_t.push_back(end_t);\n                        t.push_back(temp_t);\n                        if(method == 1)\n                        {\n                            preint_opt.type = celib::LPM;\n                            preint_opt.train_gpm = false;\n                            preint_opt.quantum = -1;\n                        }\n                        else if(method == 2)\n                        {\n                            preint_opt.type = celib::GPM;\n                            preint_opt.train_gpm = false;\n                            preint_opt.quantum = -1;\n                        }\n                        else if(method == 3)\n                        {\n                            preint_opt.type = celib::GPM;\n                            preint_opt.train_gpm = true;\n                            preint_opt.quantum = -1;\n                        }\n                        else if(method == 4)\n                        {\n                            preint_opt.type = celib::UGPM;\n                            preint_opt.train_gpm = false;\n                            preint_opt.quantum = -1;\n                        }\n                        else if(method == 5)\n                        {\n                            preint_opt.type = celib::UGPM;\n                            preint_opt.train_gpm = true;\n                            preint_opt.quantum = -1;\n                        }\n                        else\n                        {\n                            preint_opt.type = celib::UGPM;\n                            preint_opt.train_gpm = false;\n                            preint_opt.quantum = 0.2;\n                        }\n                        stop_watch.start();\n                        celib::ImuPreintegration imu_preint(data, start_t, t, preint_opt, prior);\n                        preint = imu_preint.get(0,0);\n                        time = stop_watch.stop();\n                    }\n                    time_average[d][method] += time;\n                    auto error = imu_sim.testPreint(start_t, end_t, preint);\n                }\n            }\n            std::cout << std::endl;\n\n            for(int method = 0; method < nb_methods; ++method)\n            {\n                time_average[d][method] /= nb_monte_carlo;\n            }\n        }\n        \n\n\n        std::cout << std::endl << \"RESULT computation time \" << std::endl << \"(Methods: 0 = PM, 1 = LPM, 2 = GPM, 3 = UGPM, 4 = GPM trained, 5 = UGPM trained, 6 = UGPM per chunk\" << std::endl;\n        std::cout << \"Duration (ms)\\\\ method\";\n        for(int i = 0; i < nb_methods; ++i) std::cout << \"      \" << i;\n        std::cout << std::endl;\n        for(int d = 0; d < durations.size(); ++d)\n        {\n            std::cout << \"\\\\scriptsize \" << durations[d]*1000.0 << \"            \";\n            for(int method = 0; method < nb_methods; ++method)\n            {\n                std::cout << \" &  \\\\scriptsize \" << time_average[d][method];\n            }\n            std::cout << std::endl;\n        }\n    }\n\n\n    if(experiment_type == 3)\n    { // Metrics for the robustness to noise\n\n        std::cout << \"NOISE ROBUSTNESS EXPERIMENT\" << std::endl;\n\n\n        {\n            celib::ImuSimulatorOption sim_opt;\n            std::vector<double> noise_factor = {0.001, 0.33, 0.66, 1, 1.33, 1.66, 2, 2.33, 2.66, 3, 3.33, 3.66, 4, 4.33, 4.66, 5};\n            double acc_std = 0.02;\n            double gyr_std = 0.01;\n            sim_opt.motion_type = \"fast\";\n            double duration = 1;\n            int nb_methods = 4;\n\n            std::vector<std::vector<std::vector<double> > > rot_error_avg;\n            std::vector<std::vector<std::vector<double> > > rot_error_std;\n            std::vector<std::vector<std::vector<double> > > vel_error_avg;\n            std::vector<std::vector<std::vector<double> > > vel_error_std;\n            std::vector<std::vector<std::vector<double> > > pos_error_avg;\n            std::vector<std::vector<std::vector<double> > > pos_error_std;\n            for(int type = 0; type < 2; ++type)\n            {\n                rot_error_avg.push_back(std::vector<std::vector<double> >());\n                rot_error_std.push_back(std::vector<std::vector<double> >());\n                vel_error_avg.push_back(std::vector<std::vector<double> >());\n                vel_error_std.push_back(std::vector<std::vector<double> >());\n                pos_error_avg.push_back(std::vector<std::vector<double> >());\n                pos_error_std.push_back(std::vector<std::vector<double> >());\n\n                std::cout << \"===============================================\" << std::endl;\n                std::cout << \"Run results for \" << sim_opt.motion_type << \" motion\" << std::endl;\n                for(int d = 0; d < noise_factor.size(); ++d)\n                {\n\n                    if(type == 0)\n                    {\n                        sim_opt.acc_std = noise_factor[d] * acc_std;\n                        sim_opt.gyr_std = 0.00001;\n                    }\n                    else\n                    {\n                        sim_opt.acc_std = 0.00001;\n                        sim_opt.gyr_std = noise_factor[d] * gyr_std;\n                    }\n\n                    rot_error_avg[type].push_back(std::vector<double>(nb_methods,0.0));\n                    rot_error_std[type].push_back(std::vector<double>(nb_methods,0.0));\n                    vel_error_avg[type].push_back(std::vector<double>(nb_methods,0.0));\n                    vel_error_std[type].push_back(std::vector<double>(nb_methods,0.0));\n                    pos_error_avg[type].push_back(std::vector<double>(nb_methods,0.0));\n                    pos_error_std[type].push_back(std::vector<double>(nb_methods,0.0));\n                    std::cout << \"Noise factor : \" << noise_factor[d] << std::endl;\n\n\n                    std::vector<std::vector<double> > rot_errors(nb_methods);\n                    std::vector<std::vector<double> > vel_errors(nb_methods);\n                    std::vector<std::vector<double> > pos_errors(nb_methods);\n                    for(int i = 0; i < nb_monte_carlo; ++i)\n                    {\n                        std::cout << i << \".\" << std::flush;\n                        celib::ImuSimulator imu_sim(sim_opt);\n                        celib::RandomGenerator rand_gen;\n                        double start_t = rand_gen.randUniform(overlap,sim_opt.dataset_length - duration - overlap);\n                        double end_t = start_t + duration;\n                        auto data = imu_sim.get(start_t-overlap, end_t+overlap);\n\n                        for(int method = 0; method < nb_methods; ++method)\n                        {\n                            celib::PreintMeas preint;\n                            if(method == 0)\n                            {\n                                preint = VanillaPreintegration(data, start_t, end_t);\n                            }\n                            else\n                            {\n                                // Create a preintegration object\n                                celib::PreintPrior prior;\n                                std::vector<std::vector<double> > t;\n                                std::vector<double> temp_t;\n                                temp_t.push_back(end_t);\n                                t.push_back(temp_t);\n                                if(method == 1)\n                                {\n                                    preint_opt.type = celib::LPM;\n                                    preint_opt.train_gpm = false;\n                                }\n                                else if(method == 2)\n                                {\n                                    preint_opt.type = celib::GPM;\n                                    preint_opt.train_gpm = true;\n                                }\n                                else\n                                {\n                                    preint_opt.type = celib::UGPM;\n                                    preint_opt.train_gpm = true;\n                                }\n                                celib::ImuPreintegration imu_preint(data, start_t, t, preint_opt, prior);\n                                preint = imu_preint.get(0,0);\n\n                            }\n                            auto error = imu_sim.testPreint(start_t, end_t, preint);\n                            rot_errors[method].push_back(error[0]);\n                            vel_errors[method].push_back(error[1]);\n                            pos_errors[method].push_back(error[2]);\n                        }\n                    }\n                    std::cout << std::endl;\n\n                    for(int method = 0; method < nb_methods; ++method)\n                    {\n                        for(int i = 0; i < nb_monte_carlo; ++i)\n                        {\n                            rot_error_avg[type][d][method] += rot_errors[method][i];\n                            vel_error_avg[type][d][method] += vel_errors[method][i];\n                            pos_error_avg[type][d][method] += pos_errors[method][i];\n                        }\n                        rot_error_avg[type][d][method] /= nb_monte_carlo;\n                        vel_error_avg[type][d][method] /= nb_monte_carlo;\n                        pos_error_avg[type][d][method] /= nb_monte_carlo;\n                        for(int i = 0; i < nb_monte_carlo; ++i)\n                        {\n                            rot_error_std[type][d][method] += std::pow(rot_errors[method][i] - rot_error_avg[type][d][method],2);\n                            vel_error_std[type][d][method] += std::pow(vel_errors[method][i] - vel_error_avg[type][d][method],2);\n                            pos_error_std[type][d][method] += std::pow(pos_errors[method][i] - pos_error_avg[type][d][method],2);\n                        }\n                        rot_error_std[type][d][method] = std::sqrt(rot_error_std[type][d][method]/nb_monte_carlo);\n                        vel_error_std[type][d][method] = std::sqrt(vel_error_std[type][d][method]/nb_monte_carlo);\n                        pos_error_std[type][d][method] = std::sqrt(pos_error_std[type][d][method]/nb_monte_carlo);\n\n                    }\n                }\n            }\n            std::cout << std::endl << \"RESULTS \" << std::endl << \"(Methods: PM, LPM, GPM trained, UGPM trained\" << std::endl;\n            for(int type = 0; type < 2; ++type)\n            {\n                if(type == 0) std::cout << std::endl << std::endl << \"Acc noise\" << std::endl;\n                if(type == 1) std::cout << std::endl << std::endl << \"Gyr noise\" << std::endl;\n                std::cout << \" Rot error ====\" << std::endl;\n                for(int i = 0; i < nb_methods; ++i) std::cout << \"      \" << i;\n                std::cout << std::endl;\n                for(int method = 0; method < nb_methods; ++method)\n                {\n                    for(int d = 0; d < noise_factor.size(); ++d)\n                    {\n                        if(type==0)\n                        {\n                                std::cout << \" (\" << acc_std*noise_factor[d] << \",\" << rot_error_avg[type][d][method] << \")\";\n                        }else\n                        {\n                                std::cout << \" (\" << gyr_std*noise_factor[d] << \",\" << rot_error_avg[type][d][method] << \")\";\n                        }\n                    }\n                    std::cout << std::endl;\n                }\n                std::cout << \" Pos error ====\" << std::endl;\n                for(int i = 0; i < nb_methods; ++i) std::cout << \"      \" << i;\n                std::cout << std::endl;\n                for(int method = 0; method < nb_methods; ++method)\n                {\n                    for(int d = 0; d < noise_factor.size(); ++d)\n                    {\n                        if(type==0)\n                        {\n                                std::cout << \" (\" << acc_std*noise_factor[d] << \",\" << pos_error_avg[type][d][method] << \")\";\n                        }else\n                        {\n                                std::cout << \" (\" << gyr_std*noise_factor[d] << \",\" << pos_error_avg[type][d][method] << \")\";\n                        }\n                    }\n                    std::cout << std::endl;\n                }\n            }\n        }\n        {\n            celib::ImuSimulatorOption sim_opt;\n            std::vector<double> noise_factor = {0.0001, 0.33, 0.66, 1, 1.33, 1.66, 2, 2.33, 2.66, 3, 3.33, 3.66, 4, 4.33, 4.66, 5};\n            double acc_std = 0.02;\n            double gyr_std = 0.01;\n            sim_opt.motion_type = \"slow\";\n            double duration = 1;\n            int nb_methods = 4;\n\n            std::vector<std::vector<std::vector<double> > > rot_error_avg;\n            std::vector<std::vector<std::vector<double> > > rot_error_std;\n            std::vector<std::vector<std::vector<double> > > vel_error_avg;\n            std::vector<std::vector<std::vector<double> > > vel_error_std;\n            std::vector<std::vector<std::vector<double> > > pos_error_avg;\n            std::vector<std::vector<std::vector<double> > > pos_error_std;\n            for(int type = 0; type < 2; ++type)\n            {\n                rot_error_avg.push_back(std::vector<std::vector<double> >());\n                rot_error_std.push_back(std::vector<std::vector<double> >());\n                vel_error_avg.push_back(std::vector<std::vector<double> >());\n                vel_error_std.push_back(std::vector<std::vector<double> >());\n                pos_error_avg.push_back(std::vector<std::vector<double> >());\n                pos_error_std.push_back(std::vector<std::vector<double> >());\n\n                std::cout << \"===============================================\" << std::endl;\n                std::cout << \"Run results for \" << sim_opt.motion_type << \" motion\" << std::endl;\n                for(int d = 0; d < noise_factor.size(); ++d)\n                {\n\n                    if(type == 0)\n                    {\n                        sim_opt.acc_std = noise_factor[d] * acc_std;\n                        sim_opt.gyr_std = 0.00001;\n                    }\n                    else\n                    {\n                        sim_opt.acc_std = 0.00001;\n                        sim_opt.gyr_std = noise_factor[d] * gyr_std;\n                    }\n\n                    rot_error_avg[type].push_back(std::vector<double>(nb_methods,0.0));\n                    rot_error_std[type].push_back(std::vector<double>(nb_methods,0.0));\n                    vel_error_avg[type].push_back(std::vector<double>(nb_methods,0.0));\n                    vel_error_std[type].push_back(std::vector<double>(nb_methods,0.0));\n                    pos_error_avg[type].push_back(std::vector<double>(nb_methods,0.0));\n                    pos_error_std[type].push_back(std::vector<double>(nb_methods,0.0));\n                    std::cout << \"Noise factor : \" << noise_factor[d] << std::endl;\n\n\n                    std::vector<std::vector<double> > rot_errors(nb_methods);\n                    std::vector<std::vector<double> > vel_errors(nb_methods);\n                    std::vector<std::vector<double> > pos_errors(nb_methods);\n                    for(int i = 0; i < nb_monte_carlo; ++i)\n                    {\n                        std::cout << i << \".\" << std::flush;\n                        celib::ImuSimulator imu_sim(sim_opt);\n                        celib::RandomGenerator rand_gen;\n                        double start_t = rand_gen.randUniform(overlap,sim_opt.dataset_length - duration - overlap);\n                        double end_t = start_t + duration;\n                        auto data = imu_sim.get(start_t-overlap, end_t+overlap);\n\n                        for(int method = 0; method < nb_methods; ++method)\n                        {\n                            celib::PreintMeas preint;\n                            if(method == 0)\n                            {\n                                preint = VanillaPreintegration(data, start_t, end_t);\n                            }\n                            else\n                            {\n                                // Create a preintegration object\n                                celib::PreintPrior prior;\n                                std::vector<std::vector<double> > t;\n                                std::vector<double> temp_t;\n                                temp_t.push_back(end_t);\n                                t.push_back(temp_t);\n                                if(method == 1)\n                                {\n                                    preint_opt.type = celib::LPM;\n                                    preint_opt.train_gpm = false;\n                                }\n                                else if(method == 2)\n                                {\n                                    preint_opt.type = celib::GPM;\n                                    preint_opt.train_gpm = true;\n                                }\n                                else\n                                {\n                                    preint_opt.type = celib::UGPM;\n                                    preint_opt.train_gpm = true;\n                                }\n                                celib::ImuPreintegration imu_preint(data, start_t, t, preint_opt, prior);\n                                preint = imu_preint.get(0,0);\n\n                            }\n                            auto error = imu_sim.testPreint(start_t, end_t, preint);\n                            rot_errors[method].push_back(error[0]);\n                            vel_errors[method].push_back(error[1]);\n                            pos_errors[method].push_back(error[2]);\n                        }\n                    }\n                    std::cout << std::endl;\n\n                    for(int method = 0; method < nb_methods; ++method)\n                    {\n                        for(int i = 0; i < nb_monte_carlo; ++i)\n                        {\n                            rot_error_avg[type][d][method] += rot_errors[method][i];\n                            vel_error_avg[type][d][method] += vel_errors[method][i];\n                            pos_error_avg[type][d][method] += pos_errors[method][i];\n                        }\n                        rot_error_avg[type][d][method] /= nb_monte_carlo;\n                        vel_error_avg[type][d][method] /= nb_monte_carlo;\n                        pos_error_avg[type][d][method] /= nb_monte_carlo;\n                        for(int i = 0; i < nb_monte_carlo; ++i)\n                        {\n                            rot_error_std[type][d][method] += std::pow(rot_errors[method][i] - rot_error_avg[type][d][method],2);\n                            vel_error_std[type][d][method] += std::pow(vel_errors[method][i] - vel_error_avg[type][d][method],2);\n                            pos_error_std[type][d][method] += std::pow(pos_errors[method][i] - pos_error_avg[type][d][method],2);\n                        }\n                        rot_error_std[type][d][method] = std::sqrt(rot_error_std[type][d][method]/nb_monte_carlo);\n                        vel_error_std[type][d][method] = std::sqrt(vel_error_std[type][d][method]/nb_monte_carlo);\n                        pos_error_std[type][d][method] = std::sqrt(pos_error_std[type][d][method]/nb_monte_carlo);\n\n                    }\n                }\n            }\n            std::cout << std::endl << \"RESULTS \" << std::endl << \"(Methods: PM, LPM, GPM trained, UGPM trained\" << std::endl;\n            for(int type = 0; type < 2; ++type)\n            {\n                if(type == 0) std::cout << std::endl << std::endl << \"Acc noise\" << std::endl;\n                if(type == 1) std::cout << std::endl << std::endl << \"Gyr noise\" << std::endl;\n                std::cout << \" Rot error ====\" << std::endl;\n                for(int i = 0; i < nb_methods; ++i) std::cout << \"      \" << i;\n                std::cout << std::endl;\n                for(int method = 0; method < nb_methods; ++method)\n                {\n                    for(int d = 0; d < noise_factor.size(); ++d)\n                    {\n                        if(type==0)\n                        {\n                                std::cout << \" (\" << acc_std*noise_factor[d] << \",\" << rot_error_avg[type][d][method] << \")\";\n                        }else\n                        {\n                                std::cout << \" (\" << gyr_std*noise_factor[d] << \",\" << rot_error_avg[type][d][method] << \")\";\n                        }\n                    }\n                    std::cout << std::endl;\n                }\n                std::cout << \" Pos error ====\" << std::endl;\n                for(int i = 0; i < nb_methods; ++i) std::cout << \"      \" << i;\n                std::cout << std::endl;\n                for(int method = 0; method < nb_methods; ++method)\n                {\n                    for(int d = 0; d < noise_factor.size(); ++d)\n                    {\n                        if(type==0)\n                        {\n                                std::cout << \" (\" << acc_std*noise_factor[d] << \",\" << pos_error_avg[type][d][method] << \")\";\n                        }else\n                        {\n                                std::cout << \" (\" << gyr_std*noise_factor[d] << \",\" << pos_error_avg[type][d][method] << \")\";\n                        }\n                    }\n                    std::cout << std::endl;\n                }\n            }\n        }\n    }\n\n    if(experiment_type == 4)\n    { // Metrics for the robustness to noise\n\n        std::cout << \"BIAS CORRECTION EXPERIMENT\" << std::endl;\n\n        celib::ImuSimulatorOption sim_opt;\n        std::vector<double> gyr_bias_norm = {0.01, 0.05, 0.1, 0.2, 0.4, 0.6, 0.8, 1.0};\n        std::vector<double> acc_bias_norm = {0.01, 0.05, 0.1, 0.2, 0.4, 0.6, 0.8, 1.0};\n        std::vector<double> dt_bias = {0.001, 0.005, 0.01, 0.02, 0.04, 0.06, 0.08 , 0.1};\n        sim_opt.acc_std = 0.04;\n        sim_opt.gyr_std = 0.01;\n\n        double duration = 1.0;\n        std::cout.precision(3);\n\n        std::vector<std::vector<double> > gyr_rot_error_avg;\n        std::vector<std::vector<double> > gyr_pos_error_avg;\n        std::vector<std::vector<double> > acc_rot_error_avg;\n        std::vector<std::vector<double> > acc_pos_error_avg;\n        std::vector<std::vector<double> > dt_rot_error_avg;\n        std::vector<std::vector<double> > dt_pos_error_avg;\n        std::vector<std::vector<double> > gyr_rot_error_raw_avg;\n        std::vector<std::vector<double> > gyr_pos_error_raw_avg;\n        std::vector<std::vector<double> > acc_rot_error_raw_avg;\n        std::vector<std::vector<double> > acc_pos_error_raw_avg;\n        std::vector<std::vector<double> > dt_rot_error_raw_avg;\n        std::vector<std::vector<double> > dt_pos_error_raw_avg;\n\n        for(int type = 0; type < 2; ++type)\n        {\n            gyr_rot_error_avg.push_back(std::vector<double>());\n            gyr_pos_error_avg.push_back(std::vector<double>());\n            acc_rot_error_avg.push_back(std::vector<double>());\n            acc_pos_error_avg.push_back(std::vector<double>());\n            dt_rot_error_avg.push_back(std::vector<double>());\n            dt_pos_error_avg.push_back(std::vector<double>());\n            gyr_rot_error_raw_avg.push_back(std::vector<double>());\n            gyr_pos_error_raw_avg.push_back(std::vector<double>());\n            acc_rot_error_raw_avg.push_back(std::vector<double>());\n            acc_pos_error_raw_avg.push_back(std::vector<double>());\n            dt_rot_error_raw_avg.push_back(std::vector<double>());\n            dt_pos_error_raw_avg.push_back(std::vector<double>());\n            \n\n            if(type == 0)\n            {\n                sim_opt.motion_type = \"slow\";\n            }\n            else\n            {\n                sim_opt.motion_type = \"fast\";\n            }\n            std::cout << \"===============================================\" << std::endl;\n            std::cout << \"Run results for \" << sim_opt.motion_type << \" motion\" << std::endl;\n\n            std::vector<std::vector<double> > gyr_rot_error(gyr_bias_norm.size());\n            std::vector<std::vector<double> > gyr_pos_error(gyr_bias_norm.size());\n            std::vector<std::vector<double> > acc_rot_error(acc_bias_norm.size());\n            std::vector<std::vector<double> > acc_pos_error(acc_bias_norm.size());\n            std::vector<std::vector<double> > dt_rot_error(acc_bias_norm.size());\n            std::vector<std::vector<double> > dt_pos_error(acc_bias_norm.size());\n            std::vector<std::vector<double> > gyr_rot_raw_error(gyr_bias_norm.size());\n            std::vector<std::vector<double> > gyr_pos_raw_error(gyr_bias_norm.size());\n            std::vector<std::vector<double> > acc_rot_raw_error(acc_bias_norm.size());\n            std::vector<std::vector<double> > acc_pos_raw_error(acc_bias_norm.size());\n            std::vector<std::vector<double> > dt_rot_raw_error(acc_bias_norm.size());\n            std::vector<std::vector<double> > dt_pos_raw_error(acc_bias_norm.size());\n\n            for(int i = 0; i < nb_monte_carlo; ++i)\n            {\n                std::cout << i << \".\" << std::flush;\n                celib::ImuSimulator imu_sim(sim_opt);\n                celib::RandomGenerator rand_gen;\n                double start_t = rand_gen.randUniform(overlap,sim_opt.dataset_length - duration - overlap);\n                double end_t = start_t + duration;\n                auto data = imu_sim.get(start_t-overlap, end_t+overlap);\n                auto data_save = data;\n\n                double pos_dist = imu_sim.getTranslationDistance(start_t, end_t);\n                double rot_dist = imu_sim.getOrientationDistance(start_t, end_t);\n\n                celib::Vec3 unit_vec = celib::Vec3::Random();\n                unit_vec = unit_vec / (unit_vec.norm());\n\n                for(int ibw = 0; ibw < gyr_bias_norm.size(); ++ibw)\n                {\n                    data = data_save;\n                    celib::Vec3 bias_vec = gyr_bias_norm[ibw] * unit_vec;\n                    for(int idata = 0; idata < data.acc.size(); idata++)\n                    {\n                        data.gyr[idata].data[0] += bias_vec(0);\n                        data.gyr[idata].data[1] += bias_vec(1);\n                        data.gyr[idata].data[2] += bias_vec(2);\n                    }\n\n                    celib::PreintPrior prior;\n                    std::vector<std::vector<double> > t;\n                    std::vector<double> temp_t;\n                    temp_t.push_back(end_t);\n                    t.push_back(temp_t);\n                    preint_opt.type = celib::UGPM;\n                    preint_opt.train_gpm = true;\n                    celib::ImuPreintegration imu_preint(data, start_t, t, preint_opt, prior);\n                    celib::PreintMeas preint = imu_preint.get(0,0);\n                    celib::PreintMeas preint_corrected;\n                    preint_corrected.delta_R = preint.delta_R * celib::ExpMap(preint.d_delta_R_d_bw * (-bias_vec)); \n                    preint_corrected.delta_v = preint.delta_v + (preint.d_delta_v_d_bw * (-bias_vec)); \n                    preint_corrected.delta_p = preint.delta_p + (preint.d_delta_p_d_bw * (-bias_vec)); \n\n                    auto raw_error = imu_sim.testPreint(start_t, end_t, preint);\n                    gyr_rot_raw_error[ibw].push_back(raw_error[0]/rot_dist);\n                    gyr_pos_raw_error[ibw].push_back(raw_error[2]/pos_dist);\n                    auto error = imu_sim.testPreint(start_t, end_t, preint_corrected);\n                    gyr_rot_error[ibw].push_back(error[0]/rot_dist);\n                    gyr_pos_error[ibw].push_back(error[2]/pos_dist);\n                }\n\n\n                for(int ibf = 0; ibf < acc_bias_norm.size(); ++ibf)\n                {\n                    data = data_save;\n                    celib::Vec3 bias_vec = acc_bias_norm[ibf] * unit_vec;\n                    for(int idata = 0; idata < data.acc.size(); idata++)\n                    {\n                        data.acc[idata].data[0] += bias_vec(0);\n                        data.acc[idata].data[1] += bias_vec(1);\n                        data.acc[idata].data[2] += bias_vec(2);\n                    }\n\n                    celib::PreintPrior prior;\n                    std::vector<std::vector<double> > t;\n                    std::vector<double> temp_t;\n                    temp_t.push_back(end_t);\n                    t.push_back(temp_t);\n                    preint_opt.type = celib::UGPM;\n                    preint_opt.train_gpm = true;\n                    celib::ImuPreintegration imu_preint(data, start_t, t, preint_opt, prior);\n                    celib::PreintMeas preint = imu_preint.get(0,0);\n                    celib::PreintMeas preint_corrected;\n                    preint_corrected.delta_v = preint.delta_v + (preint.d_delta_v_d_bf * (-bias_vec)); \n                    preint_corrected.delta_p = preint.delta_p + (preint.d_delta_p_d_bf * (-bias_vec)); \n\n                    auto raw_error = imu_sim.testPreint(start_t, end_t, preint);\n                    acc_rot_raw_error[ibf].push_back(raw_error[0]/rot_dist);\n                    acc_pos_raw_error[ibf].push_back(raw_error[2]/pos_dist);\n                    auto error = imu_sim.testPreint(start_t, end_t, preint_corrected);\n                    acc_rot_error[ibf].push_back(error[0]/rot_dist);\n                    acc_pos_error[ibf].push_back(error[2]/pos_dist);\n                }\n\n\n                for(int idt = 0; idt < dt_bias.size(); ++idt)\n                {\n                    data = data_save;\n                    for(int idata = 0; idata < data.acc.size(); idata++)\n                    {\n                        data.acc[idata].t += dt_bias[idt];\n                        data.gyr[idata].t += dt_bias[idt];\n                    }\n\n                    celib::PreintPrior prior;\n                    std::vector<std::vector<double> > t;\n                    std::vector<double> temp_t;\n                    temp_t.push_back(end_t);\n                    t.push_back(temp_t);\n                    preint_opt.type = celib::UGPM;\n                    preint_opt.train_gpm = true;\n                    celib::ImuPreintegration imu_preint(data, start_t, t, preint_opt, prior);\n                    celib::PreintMeas preint = imu_preint.get(0,0);\n                    celib::PreintMeas preint_corrected;\n                    preint_corrected.delta_R = preint.delta_R * celib::ExpMap(preint.d_delta_R_d_t * dt_bias[idt]); \n                    preint_corrected.delta_v = preint.delta_v + (preint.d_delta_v_d_t * dt_bias[idt]); \n                    preint_corrected.delta_p = preint.delta_p + (preint.d_delta_p_d_t * dt_bias[idt]); \n\n                    auto raw_error = imu_sim.testPreint(start_t, end_t, preint);\n                    dt_rot_raw_error[idt].push_back(raw_error[0]/rot_dist);\n                    dt_pos_raw_error[idt].push_back(raw_error[2]/pos_dist);\n                    auto error = imu_sim.testPreint(start_t, end_t, preint_corrected);\n                    dt_rot_error[idt].push_back(error[0]/rot_dist);\n                    dt_pos_error[idt].push_back(error[2]/pos_dist);\n                }\n\n\n            }\n            std::cout << std::endl;\n            for(int ibw = 0; ibw < gyr_bias_norm.size(); ++ibw)\n            {\n                gyr_rot_error_avg[type].push_back(0);\n                gyr_pos_error_avg[type].push_back(0);\n                gyr_rot_error_raw_avg[type].push_back(0);\n                gyr_pos_error_raw_avg[type].push_back(0);\n                for(int isample = 0; isample < nb_monte_carlo; ++isample)\n                {\n                    gyr_rot_error_avg[type][ibw] += gyr_rot_error[ibw][isample];\n                    gyr_pos_error_avg[type][ibw] += gyr_pos_error[ibw][isample];\n                    gyr_rot_error_raw_avg[type][ibw] += gyr_rot_raw_error[ibw][isample];\n                    gyr_pos_error_raw_avg[type][ibw] += gyr_pos_raw_error[ibw][isample];\n                }\n                gyr_rot_error_avg[type][ibw] /= nb_monte_carlo;\n                gyr_pos_error_avg[type][ibw] /= nb_monte_carlo;\n\n                gyr_rot_error_raw_avg[type][ibw] /= nb_monte_carlo;\n                gyr_pos_error_raw_avg[type][ibw] /= nb_monte_carlo;\n            }\n            for(int ibf = 0; ibf < acc_bias_norm.size(); ++ibf)\n            {\n                acc_rot_error_avg[type].push_back(0);\n                acc_pos_error_avg[type].push_back(0);\n                acc_rot_error_raw_avg[type].push_back(0);\n                acc_pos_error_raw_avg[type].push_back(0);\n                for(int isample = 0; isample < nb_monte_carlo; ++isample)\n                {\n                    acc_rot_error_avg[type][ibf] += acc_rot_error[ibf][isample];\n                    acc_pos_error_avg[type][ibf] += acc_pos_error[ibf][isample];\n                    acc_rot_error_raw_avg[type][ibf] += acc_rot_raw_error[ibf][isample];\n                    acc_pos_error_raw_avg[type][ibf] += acc_pos_raw_error[ibf][isample];\n                }\n                acc_rot_error_avg[type][ibf] /= nb_monte_carlo;\n                acc_pos_error_avg[type][ibf] /= nb_monte_carlo;\n                acc_rot_error_raw_avg[type][ibf] /= nb_monte_carlo;\n                acc_pos_error_raw_avg[type][ibf] /= nb_monte_carlo;\n\n            }\n            for(int idt = 0; idt < dt_bias.size(); ++idt)\n            {\n                dt_rot_error_avg[type].push_back(0);\n                dt_pos_error_avg[type].push_back(0);\n                dt_rot_error_raw_avg[type].push_back(0);\n                dt_pos_error_raw_avg[type].push_back(0);\n                for(int isample = 0; isample < nb_monte_carlo; ++isample)\n                {\n                    dt_rot_error_avg[type][idt] += dt_rot_error[idt][isample];\n                    dt_pos_error_avg[type][idt] += dt_pos_error[idt][isample];\n                    dt_rot_error_raw_avg[type][idt] += dt_rot_raw_error[idt][isample];\n                    dt_pos_error_raw_avg[type][idt] += dt_pos_raw_error[idt][isample];\n                }\n                dt_rot_error_avg[type][idt] /= nb_monte_carlo;\n                dt_pos_error_avg[type][idt] /= nb_monte_carlo;\n                dt_rot_error_raw_avg[type][idt] /= nb_monte_carlo;\n                dt_pos_error_raw_avg[type][idt] /= nb_monte_carlo;\n\n            }\n        }\n\n\n\n        std::cout << \"RESULTS\" << std::endl;\n\n        std::cout << std::endl;\n        std::cout << \">>>> Gyr bias experiment\" << std::endl;\n        std::cout << \"\\\\scriptsize Bias norm \";\n        for(auto n:gyr_bias_norm)\n        {\n            std::cout << \" & \\\\scriptsize \" << n;\n        }\n        std::cout << std::endl << std::endl;\n        for(int type = 0; type < 2; ++type)\n        {\n            if(type == 0) std::cout << \"\\\\scriptsize Slow Rot er.\";\n            if(type == 1) std::cout << \"\\\\scriptsize Fast Rot er.\";\n            for(int b = 0; b < gyr_bias_norm.size(); ++b)\n            {\n                std::cout << \" & \\\\scriptsize \" << 100*gyr_rot_error_raw_avg[type][b] << \" & \\\\scriptsize \" << 100*gyr_rot_error_avg[type][b];\n            }\n            std::cout << std::endl;\n        }\n        std::cout << std::endl;\n        for(int type = 0; type < 2; ++type)\n        {\n            if(type == 0) std::cout << \"\\\\scriptsize Slow Pos er.\";\n            if(type == 1) std::cout << \"\\\\scriptsize Fast Pos er.\";\n            for(int b = 0; b < gyr_bias_norm.size(); ++b)\n            {\n                std::cout << \" & \\\\scriptsize \" << 100*gyr_pos_error_raw_avg[type][b] << \" & \\\\scriptsize \" << 100*gyr_pos_error_avg[type][b];\n            }\n            std::cout << std::endl;\n        }\n        std::cout << std::endl << std::endl;\n\n        std::cout << \">>>> Acc bias experiment\" << std::endl;\n        std::cout << \"\\\\scriptsize Bias norm \";\n        for(auto n:acc_bias_norm)\n        {\n            std::cout << \" & \\\\scriptsize \" << n;\n        }\n        std::cout << std::endl << std::endl;\n        for(int type = 0; type < 2; ++type)\n        {\n            if(type == 0) std::cout << \"\\\\scriptsize Slow Pos er.\";\n            if(type == 1) std::cout << \"\\\\scriptsize Fast Pos er.\";\n            for(int b = 0; b < acc_bias_norm.size(); ++b)\n            {\n                std::cout << \" & \\\\scriptsize \" << 100*acc_pos_error_raw_avg[type][b] << \" & \\\\scriptsize \" << 100*acc_pos_error_avg[type][b];\n            }\n            std::cout << std::endl;\n        }\n        std::cout << std::endl << std::endl;\n\n        std::cout << \">>>> Timeshift experiment\" << std::endl;\n        std::cout << \"\\\\scriptsize Timeshift \";\n        for(auto n:dt_bias)\n        {\n            std::cout << \" & \\\\scriptsize \" << n;\n        }\n        std::cout << std::endl;\n        for(int type = 0; type < 2; ++type)\n        {\n            if(type == 0) std::cout << \"\\\\scriptsize Slow Rot er.\";\n            if(type == 1) std::cout << \"\\\\scriptsize Fast Rot er.\";\n            for(int b = 0; b < dt_bias.size(); ++b)\n            {\n                std::cout << \" & \\\\scriptsize \" << 100*dt_rot_error_raw_avg[type][b] << \" & \\\\scriptsize \" << 100*dt_rot_error_avg[type][b];\n            }\n            std::cout << std::endl;\n        }\n        std::cout << std::endl;\n        for(int type = 0; type < 2; ++type)\n        {\n            if(type == 0) std::cout << \"\\\\scriptsize Slow Pos er.\";\n            if(type == 1) std::cout << \"\\\\scriptsize Fast Pos er.\";\n            for(int b = 0; b < dt_bias.size(); ++b)\n            {\n                std::cout << \" & \\\\scriptsize \" << 100*dt_pos_error_raw_avg[type][b] << \" & \\\\scriptsize \" << 100*dt_pos_error_avg[type][b];\n            }\n            std::cout << std::endl;\n        }\n        std::cout << std::endl;\n    }\n\n\n\n    return 0;\n}\n", "meta": {"hexsha": "007815a10938cb79c9093fc317b141d033381292", "size": 57849, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/app/src/paper_metrics.cpp", "max_stars_repo_name": "ecbaum/ugpm", "max_stars_repo_head_hexsha": "3ab6ff2dbc59642e0e9739f5f4647a906f19e333", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/app/src/paper_metrics.cpp", "max_issues_repo_name": "ecbaum/ugpm", "max_issues_repo_head_hexsha": "3ab6ff2dbc59642e0e9739f5f4647a906f19e333", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/app/src/paper_metrics.cpp", "max_forks_repo_name": "ecbaum/ugpm", "max_forks_repo_head_hexsha": "3ab6ff2dbc59642e0e9739f5f4647a906f19e333", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.6515650741, "max_line_length": 192, "alphanum_fraction": 0.4649864302, "num_tokens": 13317, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.45384577142389504}}
{"text": "#include <fstream>\n#include <sstream>\n#include <iostream>\n#include <string>\n#include <iomanip>\n#include <optional>\n#include <cctype>\n#include <map>\n#include <algorithm>\n#include <vector>\n#include <range/v3/view.hpp>\n#include <range/v3/algorithm.hpp>\n#include <boost/dynamic_bitset.hpp>\n#include <complex>\nusing namespace std::literals::complex_literals;\n#include \"../aoc2020/matrix.h\"\n#include \"../aoc2020/mypair.h\"\n\nnamespace views = ranges::views;\n\ntemplate<int N>\nconcept Module4 = N % 4 == 0;\n\ntemplate<int N>\nauto rotateSquare(const FixedMatrix<bool, N, N> &m)\n{\n  FixedMatrix<bool, N, N> r;\n  for (int i = 0; i < N; ++i) {\n    for (int j = 0; j < N; ++j) {\n      r(j, N - 1 - i) = m(i, j);\n    }\n  }\n  return r;\n}\ntemplate<int N>\nauto flipSquare(const FixedMatrix<bool, N, N> &m)\n{\n  FixedMatrix<bool, N, N> r;\n  for (int i = 0; i < N; ++i) {\n    std::reverse_copy(m.row(i).begin(), m.row(i).end(), r.row(i));\n  }\n  return r;\n}\n\ntemplate<int N>\nauto rotateflipSquare(const FixedMatrix<bool, N, N> &m)\n{\n  std::array<FixedMatrix<bool, N, N>, 8> r;\n\n  r[0] = m;\n  for (int i = 0; i < 3; ++i) {\n    r[i + 1] = rotateSquare(r[i]);\n  }\n\n  r[4] = flipSquare(m);\n  for (int i = 4; i < 7; ++i) {\n    r[i + 1] = rotateSquare(r[i]);\n  }\n  return r;\n}\n\n\nclass Game\n{\n  std::map<FixedMatrix<bool, 2>, FixedMatrix<bool, 3>> ruleB_;\n  std::map<FixedMatrix<bool, 3>, FixedMatrix<bool, 4>> ruleC_;\n  FixedMatrix<bool, 3> mat_;\n\n  template<int N>\n  void insert(std::map<FixedMatrix<bool, N>, FixedMatrix<bool, N + 1>> &m, FixedMatrix<bool, N> const &k, const FixedMatrix<bool, N + 1> &v)\n  {\n    //std::cout << N << \"v\" << std::endl;\n    //std::cout << v << std::endl;\n    auto r = rotateflipSquare(k);\n    for (auto square : r) {\n      //std::cout << square << std::endl;\n      m[square] = v;\n    }\n  }\n  //Matrix r;\n  template<int M, int N>\n  FixedMatrix<bool, M> subMatrix(const FixedMatrix<bool, N> &input, int m, int n)\n  {\n    FixedMatrix<bool, M> r;\n    for (int i = 0; i < M; ++i) {\n      for (int j = 0; j < M; ++j) {\n        r(i, j) = input(m + i, n + j);\n      }\n    }\n    return r;\n  }\n  template<int N, int M>\n  void assignsubMatrix(FixedMatrix<bool, N> &input, int m, int n, const FixedMatrix<bool, M> &r)\n  {\n    for (int i = 0; i < M; ++i) {\n      for (int j = 0; j < M; ++j) {\n        input(m + i, n + j) = r(i, j);\n      }\n    }\n  }\n\n\npublic:\n  void outputrules() const\n  {\n    std::cout << \"rulesB:\\n\";\n    for (auto &[k, v] : ruleB_) {\n      std::cout << k << std::endl;\n      std::cout << v << std::endl;\n      std::cout << \"---------\\n\";\n    }\n    std::cout << \"rulesC:\\n\";\n    for (auto &[k, v] : ruleC_) {\n      std::cout << k << std::endl;\n      std::cout << v << std::endl;\n      std::cout << \"---------\\n\";\n    }\n  }\n\n  template<int N>\n  requires(Module4<N>)\n    FixedMatrix<bool, N + N / 2> transform(const FixedMatrix<bool, N> &input)\n  {\n\n    std::cout << \"transform\" << N << std::endl;\n    FixedMatrix<bool, N + N / 2> r;\n    for (int i = 0; i < N; i += 2) {\n      for (int j = 0; j < N; j += 2) {\n        FixedMatrix<bool, 2, 2> m = subMatrix<2>(input, i, j);\n        std::cout << \"--\" << i << \",\" << j << \"-input--------\" << std::endl;\n\n        std::cout << m << std::endl;\n        std::cout << \"--\" << i * 3 / 2 << \",\" << j * 3 / 2 << \"-output--------\" << std::endl;\n        std::cout << ruleB_[m] << std::endl;\n        assignsubMatrix(r, i * 3 / 2, j * 3 / 2, ruleB_[m]);\n      }\n    }\n    return r;\n  }\n  template<int N>\n  requires((N % 6) == 0 || N == 3 || Module4<N>)\n    FixedMatrix<bool, N + N / 3> transform(const FixedMatrix<bool, N> &input)\n  {\n    std::cout << \"transform\" << N << std::endl;\n    FixedMatrix<bool, N + N / 3> r;\n    for (int i = 0; i < N; i += 3) {\n      for (int j = 0; j < N; j += 3) {\n        FixedMatrix<bool, 3, 3> m = subMatrix<3>(input, i, j);\n        std::cout << \"--\" << i << \",\" << j << \"-input--------\" << std::endl;\n        std::cout << m << std::endl;\n        std::cout << \"--\" << i * 4 / 3 << \",\" << j * 4 / 3 << \"-output--------\" << std::endl;\n        std::cout << ruleC_[m] << std::endl;\n        assignsubMatrix(r, i * 4 / 3, j * 4 / 3, ruleC_[m]);\n      }\n    }\n    return r;\n  }\n  Game()\n  {\n  }\n  friend std::istream &operator>>(std::istream &is, Game &g)\n  {\n    std::string k, v;\n    while (is >> k >> v) {\n      if (k.size() == 5) {\n        FixedMatrix<bool, 2> matk;\n        auto mk = k | views::split('/') | views::transform([](auto row) {\n          return row | views::transform([](char c) { return c == '#'; });\n        });\n        {\n          auto id = 0;\n          for (auto i = mk.begin(); i != mk.end(); ++i, ++id) {\n            auto jd = 0;\n            for (auto j = (*i).begin(); j != (*i).end(); ++j, ++jd) {\n              matk(id, jd) = *j;\n            }\n          }\n        }\n        FixedMatrix<bool, 3> matv;\n        auto mv = v | views::split('/') | views::transform([](auto row) {\n          return row | views::transform([](char c) { return c == '#'; });\n        });\n        auto id = 0;\n        for (auto i = mv.begin(); i != mv.end(); ++i, ++id) {\n          auto jd = 0;\n          for (auto j = (*i).begin(); j != (*i).end(); ++j, ++jd) {\n            int n = *j;\n            matv(id, jd) = n;\n          }\n        }\n        g.insert(g.ruleB_, matk, matv);\n      } else {\n        FixedMatrix<bool, 3> matk;\n        auto mk = k | views::split('/') | views::transform([](auto row) {\n          return row | views::transform([](char c) { return c == '#'; });\n        });\n        {\n          auto id = 0;\n          for (auto i = mk.begin(); i != mk.end(); ++i, ++id) {\n            auto jd = 0;\n            for (auto j = (*i).begin(); j != (*i).end(); ++j, ++jd) {\n              matk(id, jd) = *j;\n            }\n          }\n        }\n        FixedMatrix<bool, 4> matv;\n        auto mv = v | views::split('/') | views::transform([](auto row) {\n          return row | views::transform([](char c) { return c == '#'; });\n        });\n        auto id = 0;\n        for (auto i = mv.begin(); i != mv.end(); ++i, ++id) {\n          auto jd = 0;\n          for (auto j = (*i).begin(); j != (*i).end(); ++j, ++jd) {\n            int n = *j;\n            matv(id, jd) = n;\n          }\n        }\n        g.insert(g.ruleC_, matk, matv);\n      }\n    }\n\n    return is;\n  }\n};\n\nint main(int argc, char **argv)\n{\n  if (argc > 1) {\n    Game g;\n    std::ifstream iss(argv[1]);\n    iss >> g;\n    //g.outputrules();\n    //return 0;\n    FixedMatrix<bool, 3> mat_;\n    mat_(0, 1) = true;\n    mat_(1, 2) = true;\n    mat_(2, 0) = true;\n    mat_(2, 1) = true;\n    mat_(2, 2) = true;\n    auto A1 = g.transform(mat_);//4\n    std::cout << A1 << std::endl;\n    auto A2 = g.transform(A1);//6\n    std::cout << A2 << std::endl;\n    auto A3 = g.transform(A2);\n    std::cout << A3 << std::endl;\n    auto A4 = g.transform(A3);\n    std::cout << A4 << std::endl;\n    auto A5 = g.transform(A4);\n    std::cout << A5 << std::endl;\n    std::cout << std::count(std::begin(A5.array()), std::end(A5.array()), 1) << std::endl;\n  }\n}\n", "meta": {"hexsha": "eb86ad830a20cd50228e0db5b659ed1b52e03051", "size": 6964, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "aoc2017/aoc172101.cpp", "max_stars_repo_name": "jiayuehua/adventOfCode", "max_stars_repo_head_hexsha": "fd47ddefd286fe94db204a9850110f8d1d74d15b", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "aoc2017/aoc172101.cpp", "max_issues_repo_name": "jiayuehua/adventOfCode", "max_issues_repo_head_hexsha": "fd47ddefd286fe94db204a9850110f8d1d74d15b", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "aoc2017/aoc172101.cpp", "max_forks_repo_name": "jiayuehua/adventOfCode", "max_forks_repo_head_hexsha": "fd47ddefd286fe94db204a9850110f8d1d74d15b", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5256916996, "max_line_length": 140, "alphanum_fraction": 0.4681217691, "num_tokens": 2337, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.45384576636170987}}
{"text": "// This is a finite element solver for the stochastic failure of 3D octect-truss\r\n// system under uniaxial tension. Matrix calculations rely on Eigen linear algebra\r\n// library.\r\n//\r\n// Copyright (c) 2019 Wen Luo <wenluo2016@u.northwestern.edu>\r\n//\r\n// Permission is hereby granted, free of charge, to any person obtaining a copy\r\n// of this software and associated documentation files (the \"Software\"), to deal\r\n// in the Software without restriction, including without limitation the rights\r\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n// copies of the Software, and to permit persons to whom the Software is\r\n// furnished to do so, subject to the following conditions:\r\n//\r\n// The above copyright notice and this permission notice shall be included in\r\n// all copies or substantial portions of the Software.\r\n//\r\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n// SOFTWARE.\r\n\r\n#include <iostream>\r\n#include <vector>\r\n#include <string>\r\n#include <cmath>\r\n#include <Eigen/Sparse>\r\n#include <algorithm>\r\n#include <fstream>\r\n\r\n#include \"functions_Geometry.h\"\r\n#include \"functions_Kernel.h\"\r\n#include \"functions_Post-processing.h\"\r\n#include \"functions_Random_vec.h\"\r\n#include \"functions_Step_control.h\"\r\n#include \"erf_inv.h\"\r\n\r\nusing namespace std;\r\nusing std::vector;\r\n//using namespace Eigen;\r\n\r\n//// Debug only --------------//\r\n//#include <chrono>\r\n//using namespace std::chrono;\r\n////--------------------------//\r\n\r\n\r\n/** ----------------------------------------- Unit System ------------------------------------------- *\r\n  * length:       10^-6 m                                                                             *\r\n  * force:        10^-6 N                                                                             *\r\n  * pressure:     MPa (10^6 Pa)                                                                       *\r\n  * ------------------------------------------------------------------------------------------------- */\r\n\r\n/** --------------------------------------- Model Parameters ---------------------------------------- *\r\n  * Young's Modulus:              10^4 MPa                    Link Length:            2 micron        *\r\n  * Mean Tensile Strength:      ~ 10^2 MPa                    Link Section Diameter:  0.5 micron      *\r\n  * ------------------------------------------------------------------------------------------------- */\r\n\r\nint main()\r\n{\r\n    /**------------------------------Geometry Definition & Preprocessing-----------------------------**/\r\n    const size_t nx = 8, ny = 4, nz = 4;\r\n    const double l_block = sqrt(2); // 10^-6 m\r\n    const double len = sqrt(2) * l_block;\r\n    /* nodal coordinates */\r\n    vector<vector<double> > coords;\r\n    coords.reserve((nx+3)*(ny+3)*(nz+3)/2);\r\n    SetCoords(nx, ny, nz, l_block, coords);\r\n    /* total number of nodes */\r\n    const size_t n_node = coords.size();\r\n\r\n    /* connectivity matrix */\r\n    vector<vector<vector<size_t> > > conn(6);\r\n    /* flattened conn */\r\n    vector<vector<size_t>> conn_flat;\r\n    conn_flat.reserve(6*nx*ny*nz);\r\n    SetConnectivity(len, coords, conn, conn_flat);\r\n\r\n//    for(auto it = conn_flat.cbegin(); it != conn_flat.cend(); ++it){\r\n//        cout << (*it)[0] << \", \" << (*it)[1] << endl;\r\n//    }\r\n\r\n    /* total number of elements */\r\n    const size_t n_ele = conn_flat.size();\r\n\r\n    /* write mesh information to VTK_XML file */\r\n//    WriteMeshXML(\"octet_lattice_CELL.vtu\", n_node, n_ele, coords, conn_flat);\r\n\r\n\r\n    /**-------------------------------------End of Pre-processing-------------------------------------**/\r\n    /**-----------------------------------------------------------------------------------------------**/\r\n    /**--------------------------------------------Kernel---------------------------------------------**/\r\n    /* element stiffness matrix - entry form */\r\n    const double elas = 10000, area = 3.1415926 * 0.5 * 0.5 / 4;\r\n\r\n    /* ind_u: list of DOF index of delta_u_0 (prescribed disp.)\r\n     * ind_f: list of DOF index of delta_f_1 (prescribed load) */\r\n    vector<size_t> ind_u, ind_f, ind_RF;\r\n    ind_u.reserve( (nx+1)*(ny+1)+2*(ny+1)*(nz+1)+(nx+1)*(nz+1) );\r\n    ind_f.reserve( 3*n_node - nx*ny+2*ny*nz+nx*nz );\r\n    ind_RF.reserve( (nx+1)*(ny+1) );\r\n    SetDispLoadDomain(nx*l_block, coords, ind_RF, ind_u, ind_f);\r\n\r\n    /* global u_0 vector (trial_u0) */\r\n    const size_t size_u = ind_u.size();\r\n    Eigen::VectorXd trial_u0 = Eigen::ArrayXd::Zero(size_u);\r\n    Set_u0(size_u, nx*l_block, coords, ind_u, trial_u0);\r\n\r\n    /* global f_1 vector - ALL ZEROS */\r\n    const size_t size_f = ind_f.size();\r\n    Eigen::VectorXd delta_f_1 = Eigen::ArrayXd::Zero(size_f);\r\n\r\n    /* permutation vector */\r\n    Eigen::VectorXi perm_Vec(size_u+size_f);\r\n    for (size_t i = 0; i != size_u+size_f; ++i){\r\n        if (i < size_u)\r\n            perm_Vec(i) = ind_u[i];\r\n        else\r\n            perm_Vec(i) = ind_f[i-size_u];\r\n    }\r\n\r\n    const size_t n_run = 5;\r\n    const size_t n_batch = 100;\r\n//    const size_t batch_offset = 0*n_run;\r\n    for(size_t run = 0; run != n_run; ++run){\r\n        /* string index of runs for output */\r\n//        string str_run = std::to_string(run+batch_offset);\r\n//        str_run = string(6 - str_run.length(), '0') + str_run;\r\n\r\n        /* global stiffness matrix spK*/\r\n        Eigen::SparseMatrix<double> spK_glob(3*n_node,3*n_node); // matrix dimension: dimension of geometry * n_node\r\n        SetStiff_glob(n_ele, elas, area, len, coords, conn_flat, spK_glob);\r\n\r\n        /* Variables initialization */\r\n        Eigen::VectorXd u_glob = Eigen::ArrayXd::Zero(size_u+size_f);\r\n        Eigen::VectorXd f_glob = Eigen::ArrayXd::Zero(size_u+size_f);\r\n\r\n        vector<double> strain(n_ele), stress(n_ele);\r\n        vector<double> sig_ratio(n_ele);\r\n\r\n        // residual element stiffness (damage indicator)\r\n        vector<double> res_Ke(n_ele, elas*area/len);\r\n        // critical elements\r\n        size_t cri_ele_ind_new = n_ele + 10;\r\n\r\n        // reaction forces\r\n        double RF = 0;\r\n\r\n        // history variables\r\n        size_t n_step = 12*ny*nz;\r\n        Eigen::MatrixXd load_disp = Eigen::MatrixXd::Constant(n_step, 2, 0);\r\n\r\n        // random number generation\r\n        vector<double> bound_tensile(n_ele), bound_compressive(n_ele);\r\n//        SetBoundariesWeibull(5, 100, bound_tensile, bound_compressive, 10);\r\n        SetBoundariesGaussWeibull(bound_tensile, bound_compressive, 10);\r\n\r\n//        cout << \"Bounds = \" << endl;\r\n//        for(auto it = bound_tensile.cbegin(); it != bound_tensile.cend(); ++it)\r\n//            cout << *it << endl;\r\n\r\n        /** ~~~~~~ Entering step loops ~~~~~~ **/\r\n        for(size_t step = 0; step != n_step; ++step){\r\n//            cout << \"------------------------------------\" << endl;\r\n//            cout << \"STEP = \" << step << endl;\r\n\r\n            RunElasticSolver(0.01*trial_u0, delta_f_1, ind_u, ind_f, perm_Vec, spK_glob, u_glob, f_glob);\r\n\r\n            GetStressStrain_Elastic(elas, area, len, res_Ke, conn_flat, coords, u_glob, strain, stress);\r\n\r\n            /* Get loading multiplier */\r\n            GetLoadRatio_Elastic(bound_tensile, bound_compressive, res_Ke, stress, sig_ratio);\r\n//            cout << \"RATIO = \" << endl;\r\n//            for(auto it = sig_ratio.cbegin(); it != sig_ratio.cend(); ++it)\r\n//                cout << '\\t' << *it << endl;\r\n\r\n            /* Critical element */\r\n            auto cri_ele_it = std::min_element(sig_ratio.cbegin(), sig_ratio.cend());\r\n            cri_ele_ind_new = distance(sig_ratio.cbegin(), cri_ele_it);\r\n//            cout << \"index = \" << cri_ele_ind_new << endl;\r\n\r\n            /* Correct Field Variables */\r\n            u_glob *= (*cri_ele_it);\r\n            f_glob *= (*cri_ele_it);\r\n            MulVec(strain, *cri_ele_it);\r\n            MulVec(stress, *cri_ele_it);\r\n\r\n            /* Update SPK */\r\n            UpdateSPK(cri_ele_ind_new, len, elas*area/len, 0, coords, conn_flat, spK_glob);\r\n\r\n            /* Update res_Ke */\r\n            res_Ke[cri_ele_ind_new] = 0;\r\n\r\n            /**--------------------------**/\r\n            /**      Record Output       **/\r\n            /**--------------------------**/\r\n            // load-displacement curve\r\n            RF = 0;\r\n            for (auto it = ind_RF.cbegin(); it != ind_RF.cend(); ++it){\r\n                RF += f_glob(*it);\r\n            }\r\n            load_disp(step,0) = u_glob(ind_RF[0]);\r\n            load_disp(step,1) = RF;\r\n\r\n            /**--------------------------**/\r\n            /**   Write to Output File   **/\r\n            /**--------------------------**/\r\n//            // Field Variables\r\n//            WriteMeshXML(\"Brittle_T_\"+str_run+\"/odb_octet_\"+std::to_string(step)+\".vtu\",\r\n//                         n_node, n_ele, coords, conn_flat);\r\n//            WriteNodeDataXML(\"Brittle_T_\"+str_run+\"/odb_octet_\"+std::to_string(step)+\".vtu\",\r\n//                             n_node, u_glob, f_glob);\r\n//            WriteElementDataXML(\"Brittle_T_\"+str_run+\"/odb_octet_\"+std::to_string(step)+\".vtu\",\r\n//                                n_ele, strain, stress, res_Ke, bound_tensile);\r\n//            WriteEndXML(\"Brittle_T_\"+str_run+\"/odb_octet_\"+std::to_string(step)+\".vtu\");\r\n            /**--------------------------**/\r\n            /* Break Condition */\r\n            if(load_disp(step,1)/load_disp(step,0) < 0.01 * load_disp(0,1)/load_disp(0,0))\r\n                break;\r\n\r\n        }/** ~~~~~~ End of step loops ~~~~~~ **/\r\n//        /* Load Displacement Curve */\r\n//        ofstream dbg_f;\r\n//        //dbg_f.open(\"Brittle_T_\"+str_run+\"/LoadDisp_Lattice_\"+str_run+\".dat\",ios::out|ios::trunc);\r\n//        dbg_f.open(\"Brittle_T_results/LoadDisp_octet_\"+str_run+\".dat\",ios::out|ios::trunc);\r\n//        dbg_f << load_disp << endl;\r\n//        dbg_f.close();\r\n        /* maximum loads vector */\r\n        ofstream dbg_f;\r\n        dbg_f.open(\"Brittle_T_results/PeakLoads_octet_\"+std::to_string(n_batch)+\".dat\",ios::out|ios::app);\r\n        dbg_f << load_disp.colwise().maxCoeff()(1) << endl;\r\n        dbg_f.close();\r\n\r\n//        /* first strength vector */\r\n//        dbg_f.open(\"Brittle_T_results/FirstLoads_octet_\"+std::to_string(n_batch)+\".dat\",ios::out|ios::app);\r\n//        dbg_f << load_disp(0,1) << endl;\r\n//        dbg_f.close();\r\n//\r\n//        /* second strength vector */\r\n//        dbg_f.open(\"Brittle_T_results/SecondLoads_octet_\"+std::to_string(n_batch)+\".dat\",ios::out|ios::app);\r\n//        dbg_f << load_disp(1,1) << endl;\r\n//        dbg_f.close();\r\n//\r\n//        /* third strength vector */\r\n//        dbg_f.open(\"Brittle_T_results/ThirdLoads_octet_\"+std::to_string(n_batch)+\".dat\",ios::out|ios::app);\r\n//        dbg_f << load_disp(2,1) << endl;\r\n//        dbg_f.close();\r\n    }\r\n    /* Update new coordinates *///    cout << \"minimum_ratio = \" << *critical_ele_it << endl;\r\n//    vector<vector<double> > coords_new;\r\n//    get_stress_strain(elas, len, conn_flat, coords, u_glob);\r\n\r\n    /**-----------------------------------------End of Kernel------------------------------------------**/\r\n    /**------------------------------------------------------------------------------------------------**/\r\n    /**-------------------------------------------Debugging--------------------------------------------**/\r\n\r\n//    cout << \"u_1 = \" << endl;\r\n//    cout << u_1 << endl;\r\n//    cout << \"u_glob = \" << endl;\r\n//    cout << u_glob << endl;\r\n\r\n\r\n//    cout << \"Sum of forces = \" << temp << endl;\r\n//    ofstream dbg_f;\r\n//    dbg_f.open(\"dbg_B.dat\",ios::out|ios::trunc);\r\n//    dbg_f << '\\n' << \"Sparse Global Stiffness Matrix:\" << '\\n'\r\n//          << Eigen::MatrixXd(spK_glob) << endl;\r\n//    dbg_f << load_disp << endl;\r\n//    dbg_f << '\\n' << \"permutation vector:\" << '\\n' << perm_Vec << endl;\r\n//    dbg_f.close();\r\n\r\n//    for (auto it = ind_u.cbegin(); it != ind_u.cend(); ++it){\r\n//        cout << *it << '\\n';\r\n//    }\r\n//    cout << endl;\r\n\r\n\r\n//    auto start = high_resolution_clock::now();\r\n//    auto stop = high_resolution_clock::now();\r\n//    auto duration = duration_cast<microseconds>(stop - start);\r\n//\r\n//    cout << \"Time taken by function: \"\r\n//         << duration.count() << \" 10^-6s \" << endl;\r\n\r\n\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "134ff8fdd6aa5b4b09da1d7bce69adfcbe12d339", "size": 12580, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "Rowenasteroidbelt/Stochastic-Octet-FEM", "max_stars_repo_head_hexsha": "3f737c3c6ffa70d48065f1b87499bed97e1616bc", "max_stars_repo_licenses": ["MIT"], "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": "Rowenasteroidbelt/Stochastic-Octet-FEM", "max_issues_repo_head_hexsha": "3f737c3c6ffa70d48065f1b87499bed97e1616bc", "max_issues_repo_licenses": ["MIT"], "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": "Rowenasteroidbelt/Stochastic-Octet-FEM", "max_forks_repo_head_hexsha": "3f737c3c6ffa70d48065f1b87499bed97e1616bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-07-01T20:19:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-01T20:19:47.000Z", "avg_line_length": 43.3793103448, "max_line_length": 117, "alphanum_fraction": 0.5097774245, "num_tokens": 3018, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.45384576636170976}}
{"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 *    References\n *      Mengali, G., and A.A. Quarta, Fondamenti di Meccanica del volo Spaziale.\n *      Noomen, R., Lambert targeter Excel file.\n *      Izzo, D., Keplerian_Toolbox.\n *\n *    Notes\n *      The elliptical case was taken from Example 6.1, page 159-162 of ( Mengali, Quarta ). The\n *      hyperbolic case was taken from ( Noomen, R. ). The retrograde and near-pi cases are verified\n *      against values found with the Lambert routine available in the Keplerian_Toolbox from\n *      ESA/ACT. It is assumed that the first two test cases are sufficient to test the radial and\n *      tangential velocity components computations. These are therefore not tested in the last two\n *      test cases.\n *\n */\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MAIN\n\n#include <boost/test/unit_test.hpp>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include \"tudat/astro/basic_astro/orbitalElementConversions.h\"\n#include \"tudat/astro/basic_astro/unitConversions.h\"\n#include \"tudat/basics/testMacros.h\"\n\n#include \"tudat/astro/mission_segments/zeroRevolutionLambertTargeterIzzo.h\"\n\nnamespace tudat\n{\nnamespace unit_tests\n{\n\nusing namespace unit_conversions;\n\n//! Test the Izzo Lambert targeting algorithm code.\nBOOST_AUTO_TEST_SUITE( test_zero_revolution_lambert_targeter_izzo )\n\n//! Test hyperbolic case.\nBOOST_AUTO_TEST_CASE( testHyperbolicCase )\n// Copied and slightly adapted from unitTestLambertTargeterIzzo (rev 466)\n{\n    // Expected test result in meters.\n    // Hyperbolic test case (results from excel file [1]).\n    const double expectedValueOfSemiMajorAxisHyperbola = -1270129.3602e3;\n    const double expectedValueOfRadialSpeedAtDepartureHyperbola = -0.74546e3;\n    const double expectedValueOfRadialSpeedAtArrivalHyperbola = 0.69321e3;\n    const double expectedValueOfTransverseSpeedAtDepartureHyperbola = 0.15674e3;\n    const double expectedValueOfTransverseSpeedAtArrivalHyperbola = 0.10450e3;\n    const Eigen::Vector3d expectedInertialVelocityAtDeparture( -745.457, 156.743, 0.0 );\n    const Eigen::Vector3d expectedInertialVelocityAtArrival( 104.495, -693.209, 0.0 );\n\n    // Tolerances.\n    const double toleranceSemiMajorAxisHyperbola = 1.0e-7;\n    const double toleranceVelocity = 1.0e-4;\n\n    // Time conversions.\n    const double timeOfFlightInDaysHyperbola = 100.0;\n    const double timeOfFlightHyperbola = convertJulianDaysToSeconds( timeOfFlightInDaysHyperbola );\n\n    // Central body gravitational parameter.\n    const double earthGravitationalParameter = 398600.4418e9;\n\n    // The starting point is twice as far as L1 and L2, which is not really\n    // realistic, but it is not about the case, but about the verification.\n    const Eigen::Vector3d positionAtDepartureHyperbola( convertAstronomicalUnitsToMeters( 0.02 ),\n                                                        0.0, 0.0 ),\n            positionAtArrivalHyperbola( 0.0, convertAstronomicalUnitsToMeters( -0.03 ), 0.0 );\n\n    // Compute Lambert targeting algorithms.\n    mission_segments::ZeroRevolutionLambertTargeterIzzo lambertTargeterHyperbola(\n                positionAtDepartureHyperbola, positionAtArrivalHyperbola, timeOfFlightHyperbola,\n                earthGravitationalParameter );\n\n    // Create local vectors for position and velocity.\n    const Eigen::Vector3d positionDepartureHyperbola = positionAtDepartureHyperbola;\n    const Eigen::Vector3d velocityDepartureHyperbola =\n            lambertTargeterHyperbola.getInertialVelocityAtDeparture( );\n\n    // Test if the computed semi-major axis corresponds to the expected value within the specified\n    // tolerance.\n    BOOST_CHECK_CLOSE_FRACTION( lambertTargeterHyperbola.getSemiMajorAxis( ),\n                                expectedValueOfSemiMajorAxisHyperbola,\n                                toleranceSemiMajorAxisHyperbola );\n\n    // Test if the computed transverse and radial velocity components corresponds to the\n    // expected values within the specified tolerance.\n    BOOST_CHECK_CLOSE_FRACTION( lambertTargeterHyperbola.getRadialVelocityAtDeparture( ),\n                                expectedValueOfRadialSpeedAtDepartureHyperbola,\n                                toleranceVelocity );\n    BOOST_CHECK_CLOSE_FRACTION( lambertTargeterHyperbola.getRadialVelocityAtArrival( ),\n                                expectedValueOfRadialSpeedAtArrivalHyperbola,\n                                toleranceVelocity );\n    BOOST_CHECK_CLOSE_FRACTION( lambertTargeterHyperbola.getTransverseVelocityAtDeparture( ),\n                                expectedValueOfTransverseSpeedAtDepartureHyperbola,\n                                toleranceVelocity );\n    BOOST_CHECK_CLOSE_FRACTION( lambertTargeterHyperbola.getTransverseVelocityAtArrival( ),\n                                expectedValueOfTransverseSpeedAtArrivalHyperbola,\n                                toleranceVelocity );\n\n    // Check that velocities match expected values within the defined tolerance.\n    TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedInertialVelocityAtDeparture,\n                                       lambertTargeterHyperbola.getInertialVelocityAtDeparture( ),\n                                       toleranceVelocity );\n    TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedInertialVelocityAtArrival,\n                                       lambertTargeterHyperbola.getInertialVelocityAtArrival( ),\n                                       toleranceVelocity );\n\n    // Test if the computed solution is anti-clockwise, if the z-component of the angular momentum\n    // (h = r \\times v) is positive.\n    BOOST_CHECK_GT( positionDepartureHyperbola.cross( velocityDepartureHyperbola ).z( ), 0 );\n}\n\n//! Test elliptical case.\nBOOST_AUTO_TEST_CASE( testEllipticalCase )\n// Copied and slightly adapted from unitTestLambertTargeterIzzo (rev 466)\n{\n    // Elliptical test case (results from example 6.1 page 159-162 [2]).\n    // Set canonical units for Earth (see page 29 [2]).\n    double distanceUnit = 6.378136e6;\n    double timeUnit = 806.78;\n\n    // Set expected test result in meters.\n    double expectedValueOfSemiMajorAxisEllipse = 5.4214 * distanceUnit;\n    double expectedValueOfRadialSpeedAtDepartureEllipse = 2.73580e3;\n    double expectedValueOfRadialSpeedAtArrivalEllipse = 2.97503e3;\n    double expectedValueOfTransverseSpeedAtDepartureEllipse = 6.59430e3;\n    double expectedValueOfTransverseSpeedAtArrivalEllipse = 3.29715e3;\n    const Eigen::Vector3d expectedInertialVelocityAtDeparture( 2735.8, 6594.3, 0.0 );\n    const Eigen::Vector3d expectedInertialVelocityAtArrival( -1367.9, 4225.03, 0.0 );\n\n    // Tolerance in absolute units.\n    double toleranceSemiMajorAxisEllipse = 1.0e4;\n    double toleranceVelocity = 1.0e-2;\n\n    // Time conversions.\n    double timeOfFlightEllipse = 5.0 * timeUnit;\n\n    // Central body gravitational parameter.\n    const double earthGravitationalParameter = 398600.4418e9;\n\n    // Elliptical orbit case.\n    const Eigen::Vector3d positionAtDepartureEllipse( 2.0 * distanceUnit, 0.0, 0.0 ),\n            positionAtArrivalEllipse( 2.0 * distanceUnit, 2.0 * sqrt( 3.0 ) * distanceUnit, 0.0 );\n\n    // Compute Lambert targeting algorithms.\n    mission_segments::ZeroRevolutionLambertTargeterIzzo lambertTargeterEllipse(\n                positionAtDepartureEllipse, positionAtArrivalEllipse, timeOfFlightEllipse,\n                earthGravitationalParameter );\n\n    // Create local vectors for position and velocity.\n    const Eigen::Vector3d positionDepartureEllipse = positionAtDepartureEllipse;\n    const Eigen::Vector3d velocityDepartureEllipse =\n            lambertTargeterEllipse.getInertialVelocityAtDeparture( );\n\n    // Test if the computed semi-major axis corresponds to the expected value within the specified\n    // tolerance.\n    BOOST_CHECK_CLOSE_FRACTION( lambertTargeterEllipse.getSemiMajorAxis( ),\n                                expectedValueOfSemiMajorAxisEllipse,\n                                toleranceSemiMajorAxisEllipse );\n\n    // Test if the computed transverse and radial velocity components corresponds to the\n    // expected values within the specified tolerance.\n    BOOST_CHECK_CLOSE_FRACTION( lambertTargeterEllipse.getRadialVelocityAtDeparture( ),\n                                expectedValueOfRadialSpeedAtDepartureEllipse,\n                                toleranceVelocity );\n    BOOST_CHECK_CLOSE_FRACTION( lambertTargeterEllipse.getRadialVelocityAtArrival( ),\n                                expectedValueOfRadialSpeedAtArrivalEllipse,\n                                toleranceVelocity );\n    BOOST_CHECK_CLOSE_FRACTION( lambertTargeterEllipse.getTransverseVelocityAtDeparture( ),\n                                expectedValueOfTransverseSpeedAtDepartureEllipse,\n                                toleranceVelocity );\n    BOOST_CHECK_CLOSE_FRACTION( lambertTargeterEllipse.getTransverseVelocityAtArrival( ),\n                                expectedValueOfTransverseSpeedAtArrivalEllipse,\n                                toleranceVelocity );\n\n    // Check that velocities match expected values within the defined tolerance.\n    TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedInertialVelocityAtDeparture,\n                                       lambertTargeterEllipse.getInertialVelocityAtDeparture( ),\n                                       toleranceVelocity );\n    TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedInertialVelocityAtArrival,\n                                       lambertTargeterEllipse.getInertialVelocityAtArrival( ),\n                                       toleranceVelocity );\n\n    // Test if the computed solution is anti-clockwise, if the z-component of the angular momentum\n    // (h = r \\times v) is positive.\n    BOOST_CHECK_GT( positionDepartureEllipse.cross( velocityDepartureEllipse ).z( ), 0 );\n}\n\n//! Test retrograde Earth-Mars transfer.\nBOOST_AUTO_TEST_CASE ( testRetrograde )\n// Copied and slightly adapted from unitTestLambertTargeterIzzo (rev 466).\n{\n    // Set tolerance.\n    const double tolerance = 1.0e-9;\n\n    // Set positions at departure and arrival.\n    /* Values taken from http://ccar.colorado.edu/~rla/lambert_j2000.html for JDi = 2456036 and\n     * JDf = 2456336.\n     */\n    const Eigen::Vector3d positionAtDeparture( -131798187443.90068, -72114797019.4148,\n                                               2343782.3918863535 ),\n            positionAtArrival( 202564770723.92966, -42405023055.01754, -5861543784.413235 );\n\n    // Set time-of-flight, coherent with initial and final positions.\n    const double timeOfFlight = convertJulianDaysToSeconds( 300.0 );\n\n    // Set central body (the Sun) gravitational parameter. Value taken from keptoolbox.\n    const double solarGravitationalParameter = 1.32712428e20;\n\n    // Set expected values for inertial velocities. Values obtained with keptoolbox.\n    const Eigen::Vector3d expectedInitialVelocity( -14157.8507230353, 28751.266655828,\n                                                   1395.46037631136 ),\n            expectedFinalVelocity( -6609.91626743654, -22363.5220239692, -716.519714631494 );\n\n    // Compute Lambert solution.\n    mission_segments::ZeroRevolutionLambertTargeterIzzo lambertTargeterRetrograde(\n                positionAtDeparture, positionAtArrival,\n                timeOfFlight, solarGravitationalParameter, true );\n\n    // Retrieve inertial velocities.\n    const Eigen::Vector3d initialVelocity =\n            lambertTargeterRetrograde.getInertialVelocityAtDeparture( );\n    const Eigen::Vector3d finalVelocity = lambertTargeterRetrograde.getInertialVelocityAtArrival( );\n\n    // Check that velocities match expected values within the defined tolerance.\n    TUDAT_CHECK_MATRIX_CLOSE( initialVelocity, expectedInitialVelocity, tolerance );\n    TUDAT_CHECK_MATRIX_CLOSE( finalVelocity, expectedFinalVelocity, tolerance );\n}\n\n//! Test near-pi, circular, coplanar, Earth-Mars transfer.\nBOOST_AUTO_TEST_CASE ( testNearPi )\n// Copied and slightly adapted from unitTestLambertTargeterIzzo (rev 466).\n{\n    // Set tolerance.\n    const double tolerance = 1.0e-6;\n\n    // Set time-of-flight, coherent with initial and final positions.\n    const double timeOfFlight = convertJulianDaysToSeconds( 300.0 );\n\n    // Set central body (the Sun) gravitational parameter. Value taken from keptoolbox.\n    const double solarGravitationalParameter = 1.32712428e20;\n\n    // Set Keplerian elements at departure and arrival.\n    Eigen::Matrix< double, 6, 1 > keplerianStateAtDeparture, keplerianStateAtArrival;\n    keplerianStateAtDeparture << convertAstronomicalUnitsToMeters( 1.0 ), 0.0,\n            0.0, 0.0, 0.0, 0.0;\n    keplerianStateAtArrival << convertAstronomicalUnitsToMeters( 1.5 ), 0.0, 0.0,\n            0.0, 0.0, convertDegreesToRadians( 179.999 );\n\n    //  Convert to Cartesian elements.\n    const Eigen::Matrix< double, 6, 1 > cartesianStateAtDeparture =\n            orbital_element_conversions::convertKeplerianToCartesianElements(\n                keplerianStateAtDeparture, solarGravitationalParameter );\n    const Eigen::Matrix< double, 6, 1 > cartesianStateAtArrival =\n            orbital_element_conversions::convertKeplerianToCartesianElements(\n                keplerianStateAtArrival, solarGravitationalParameter );\n\n    // Extract positions at departure and arrival.\n    const Eigen::Vector3d positionAtDeparture = cartesianStateAtDeparture.head( 3 );\n    const Eigen::Vector3d positionAtArrival = cartesianStateAtArrival.head( 3 );\n\n    // Set expected values for inertial velocities. Values obtained with keptoolbox.\n    const Eigen::Vector3d expectedInitialVelocity( 3160.36638344209, 32627.4771454454, 0.0 ),\n            expectedFinalVelocity( 3159.89183582648, -21751.7065841264, 0.0 );\n\n    // Compute Lambert solution.\n    mission_segments::ZeroRevolutionLambertTargeterIzzo lambertTargeterRetrograde(\n                positionAtDeparture, positionAtArrival, timeOfFlight, solarGravitationalParameter );\n\n    // Retrieve inertial velocities.\n    const Eigen::Vector3d initialVelocity =\n            lambertTargeterRetrograde.getInertialVelocityAtDeparture( );\n    const Eigen::Vector3d finalVelocity = lambertTargeterRetrograde.getInertialVelocityAtArrival( );\n\n    // Check that velocities match expected values within the defined tolerance.\n    TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedInitialVelocity, initialVelocity, tolerance );\n    TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedFinalVelocity, finalVelocity, tolerance );\n}\n\nBOOST_AUTO_TEST_SUITE_END( )\n\n} // namespace unit_tests\n} // namespace tudat\n", "meta": {"hexsha": "0e300587197dc92c081b7a736496a4959ea998a9", "size": 14843, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/src/astro/mission_segments/unitTestZeroRevolutionLambertTargeterIzzo.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": "tests/src/astro/mission_segments/unitTestZeroRevolutionLambertTargeterIzzo.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": "tests/src/astro/mission_segments/unitTestZeroRevolutionLambertTargeterIzzo.cpp", "max_forks_repo_name": "kimonito98/tudat", "max_forks_repo_head_hexsha": "c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.3152542373, "max_line_length": 100, "alphanum_fraction": 0.7137371151, "num_tokens": 3576, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128672997041659, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.45384575623733897}}
{"text": "/*\n * Copyright (c) 2020-2021, Marco S\u00e1nchez Beeckman\n * All rights reserved.\n *\n * This source code is licensed under the BSD-style license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n#include <array>\n#include <chrono>\n#include <iostream>\n#include <limits>\n#include <random>\n\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n#include <opencv2/core.hpp>\n\n#include \"Homography.h\"\n\n\nnamespace tfg {\n\n/** \n * Obtain weights that minimize the smooth truncated quadratic cost given by equation (2) in Szeliski's paper.\n * The formula for these weights is shown in equation (3).\n * @param residuals2 Squared track residuals, ordered by track.\n * @param tau2 Tau squared, an inlier threshold for equations (2) to (4) in Szeliski's paper.\n * @return The squared weights, ordered by track.\n */\nstd::vector<float> getWeights2(std::vector<float> &residuals2, float tau2) {\n    std::vector<float> weights2;\n    weights2.reserve(residuals2.size());\n    for(unsigned int i = 0; i < residuals2.size(); i++) {\n        float boundedResidual2 = residuals2[i] < tau2 ? residuals2[i] : tau2;\n        float weight2 = 1 - boundedResidual2/tau2;\n        weights2.push_back(weight2);\n    }\n    return weights2;\n}\n\nstd::vector<float> getWeightsFromInliers(std::vector<std::vector<int>> &inliers, std::shared_ptr<tfg::TrackTable> &trackTable) {\n    std::vector<float> weights(trackTable->numberOfTracks(), 0);\n    std::vector<unsigned int> timesCountedAsInlier(trackTable->numberOfTracks(), 0);\n    for(unsigned int f = 0; f < inliers.size(); f++) {\n        std::vector<unsigned int> trajectories = trackTable->trajectoriesInFrame(f);\n        for(unsigned int i = 0; i < inliers[f].size(); i++) {\n            timesCountedAsInlier[trajectories[inliers[f][i]]]++;\n        }\n    }\n\n    for(unsigned int t = 0; t < weights.size(); t++) {\n        const unsigned int trackDuration = trackTable->durationOfTrack(t);\n        // weights[t] = timesCountedAsInlier[t] == 0 ? 0 : 1;\n        weights[t] = timesCountedAsInlier[t] == trackDuration - 1 ? 1 : 0;\n    }\n\n    return weights;\n}\n\n/**\n * Obtain the homography that fits a model the best given a set of origin points and another set of destinations, using RANSAC.\n * @param p0 Origin points.\n * @param p1 Destination points.\n * @param n Number of points.\n * @param niter Number of iterations for RANSAC.\n * @param tolerance Maximum distance in pixels to consider a point an inlier.\n * @param H Output homography.\n * @param inliers Output list of indexes that correspond to those of the tracks that are inliers.\n */\nvoid computeHomographyRANSAC(const std::vector<cv::Vec2f> &p0, const std::vector<cv::Vec2f> &p1, int n, int niter, float tolerance, cv::Matx33f &H, std::vector<int> &inliers) {\n    \n    float tolerance2 = tolerance * tolerance;\n    unsigned int maxInliers = 0;\n    std::vector<int> bestInliers;\n\n    std::array<int, 4> randomIndices;\n    std::random_device randomDevice;\n    std::mt19937 mersenneTwister(randomDevice());\n    std::uniform_int_distribution<int> uniformIntDist(0, n-1);\n\n    for(int iter = 0; iter < niter; iter++) {\n\n        // Sample 4 different numbers between 0 and n-1\n        for(int i = 0; i < 4; i++) {\n            int randomNumber = uniformIntDist(mersenneTwister);\n            while(std::find(randomIndices.begin(), randomIndices.end(), randomNumber) != randomIndices.end()) {\n                randomNumber = uniformIntDist(mersenneTwister);\n            }\n            randomIndices[i] = randomNumber;\n        }\n\n        // Obtain the 4 points corresponding to the random indices\n        std::vector<cv::Vec2f> pointsL(4); \n        std::vector<cv::Vec2f> pointsR(4);\n        for(int i = 0; i < 4; i++) {\n            pointsL[i] = p0[randomIndices[i]];\n            pointsR[i] = p1[randomIndices[i]];\n        }\n\n        // Compute homography using Least Squares method\n        cv::Matx33f Haux;\n        std::vector<unsigned int> zeros(4, 0);\n        std::vector<float> ones(1, 1.0f);\n        tfg::computeHomographyWLS(pointsL, pointsR, 4, zeros, ones, Haux);\n\n        // Obtain the inliers for this iteration\n        std::vector<int> iterationInliers;\n        iterationInliers.reserve(n);\n        for(int i = 0; i < n; i++) {\n            cv::Vec3f pointOrigin;\n            cv::Vec3f pointDestination;\n            pointOrigin(0) = p0[i](0);      pointOrigin(1) = p0[i](1);      pointOrigin(2) = 1.0f;\n            pointDestination(0) = p1[i](0); pointDestination(1) = p1[i](1); pointDestination(2) = 1.0f;\n\n            cv::Vec3f pred = Haux * pointOrigin;\n\n            if(pred(2) == 0.0f) continue;\n\n            pred(0) = pred(0)/pred(2); pred(1) = pred(1)/pred(2); pred(2) = 1.0f;\n            float reprojectionError2 = cv::norm(pointDestination - pred, cv::NORM_L2SQR);\n            if(reprojectionError2 < tolerance2) {\n                iterationInliers.push_back(i);\n            }\n        }\n\n        // If the number of inliers has increased from the best iteration, update it along with the homography\n        const unsigned int numInliers = iterationInliers.size();\n        if(numInliers > maxInliers) {\n            maxInliers = numInliers;\n            bestInliers.swap(iterationInliers);\n\n            H(0,0) = Haux(0,0); H(0,1) = Haux(0,1); H(0,2) = Haux(0,2);\n            H(1,0) = Haux(1,0); H(1,1) = Haux(1,1); H(1,2) = Haux(1,2);\n            H(2,0) = Haux(2,0); H(2,1) = Haux(2,1); H(2,2) = Haux(2,2);\n        }\n\n    }\n    inliers.swap(bestInliers);\n}\n\n/**\n * Compute an homography using Weighted Least Squares, i.e. minimize ||WAh||, whose solution is the eigenvector with smallest eigenvalue of the matrix AtWtWA.\n * @param p0 Origin points.\n * @param p1 Destination points.\n * @param n Number of points.\n * @param trajectories The index of the trajectory corresponding to each one of the points.\n * @param weights2 The weights of each track, squared.\n * @param H Output homography.\n */\nvoid computeHomographyWLS(const std::vector<cv::Vec2f> &p0, const std::vector<cv::Vec2f> &p1, int n, const std::vector<unsigned int> &trajectories, const std::vector<float> &weights2, cv::Matx33f &H) {\n\n    // Normalize the left and right observations\n    std::vector<cv::Vec2f> pnorm0;\n    std::vector<cv::Vec2f> pnorm1;\n    cv::Vec2f centerL(0, 0), centerR(0, 0);\n    cv::Vec2f scaleL(0, 0), scaleR(0, 0);\n    tfg::isotropicNormalization(p0, pnorm0, centerL, scaleL);\n    tfg::isotropicNormalization(p1, pnorm1, centerR, scaleR);\n\n    ////////////////////////// Minimization problem || Ah || /////////////////////////////\n\n    Eigen::Matrix3d Tpl, Timinv;\n\n    // Similarity transformation of the plane\n    Tpl(0, 0) = scaleL(0); Tpl(0, 1) = 0.0;       Tpl(0, 2) = -scaleL(0)*centerL(0);\n    Tpl(1, 0) = 0.0;       Tpl(1, 1) = scaleL(1); Tpl(1, 2) = -scaleL(1)*centerL(1);\n    Tpl(2, 0) = 0.0;       Tpl(2, 1) = 0.0;       Tpl(2, 2) = 1.0;\n\n    // Inverse similarity transformation of the image\n    Timinv(0, 0) = 1.0/scaleR(0); Timinv(0, 1) = 0.0;           Timinv(0, 2) = centerR(0);\n    Timinv(1, 0) = 0.0;           Timinv(1, 1) = 1.0/scaleR(1); Timinv(1, 2) = centerR(1);\n    Timinv(2, 0) = 0.0;           Timinv(2, 1) = 0.0;           Timinv(2, 2) = 1.0;\n\n    // Build At*Wt*W*A\n    Eigen::Matrix<double, 9, 9> AtA = Eigen::Matrix<double, 9, 9>::Zero();\n    for(int i = 0; i < n; i++) {\n        float xpl = pnorm0[i](0), ypl = pnorm0[i](1),\n                xim = pnorm1[i](0), yim = pnorm1[i](1);\n            \n        std::array<float, 9> row1 = {0.0f, 0.0f, 0.0f, -xpl, -ypl, -1.0f, yim * xpl, yim * ypl, yim};\n        std::array<float, 9> row2 = {xpl, ypl, 1.0f, 0.0f, 0.0f, 0.0f, -xim * xpl, -xim * ypl, -xim};\n        float w2 = weights2[trajectories[i]];\n\n        // Lower half only, since SelfAdjointEigenSolver does not use the upper half\n        for(int j = 0; j < 9; j++) {\n            for(int k = j; k < 9; k++) {\n                AtA(k, j) += w2 * row1[j] * row1[k] + w2 * row2[j] * row2[k];\n            }\n        }\n    }\n\n    Eigen::SelfAdjointEigenSolver<Eigen::Matrix<double, 9, 9>> eigenSolver;\n    eigenSolver.compute(AtA);\n    Eigen::Matrix3d V(eigenSolver.eigenvectors().col(0).data()); V.transposeInPlace();\n\n    // Denormalize H = Timinv * V.col(imin)* Tpl;\n    Eigen::Matrix3d Vdenorm = Timinv * (V * Tpl);\n\n    // Divide every entry by H(2, 2) so the bottom right entry is 1\n    for(int i = 0; i < 3; i++) {\n        for(int j = 0; j < 3; j++) {\n            H(i, j) = static_cast<float>(Vdenorm(i, j)/Vdenorm(2, 2));\n        }\n    }\n}\n\n/**\n * Normalize points such that their centroid is at the origin, and their average distance to it is sqrt(2).\n * @param points Vector of points.\n * @param normalizedPoints Output vector of normalized points.\n * @param center Output computed centroid of the points.\n * @param scale Output computed scaling factor.\n */ \nvoid isotropicNormalization(const std::vector<cv::Vec2f> &points, std::vector<cv::Vec2f> &normalizedPoints, cv::Vec2f &center, cv::Vec2f &scale) {\n    const int NUMBER_OF_POINTS = points.size();\n    normalizedPoints.clear();\n    normalizedPoints.reserve(NUMBER_OF_POINTS);\n\n    // Compute baricenter of the observations\n    center(0) = 0.0f; center(1) = 0.0f;\n    for(int i = 0; i < NUMBER_OF_POINTS; i++) {\n        center = center + points[i];\n    }\n    center = center / NUMBER_OF_POINTS;\n\n    // Scaling so that the average distance from the center is sqrt(2)\n    scale(0) = 0.0f; scale(1) = 0.0f;\n    for(int i = 0; i < NUMBER_OF_POINTS; i++) {\n        const float obsDistance = cv::norm(points[i] - center);\n        scale(0) = scale(0) + obsDistance;\n        scale(1) = scale(1) + obsDistance;\n    }\n    scale(0) = (sqrtf(2.0f) * NUMBER_OF_POINTS) / scale(0);\n    scale(1) = (sqrtf(2.0f) * NUMBER_OF_POINTS) / scale(1);\n\n    // Normalize the observations\n    for(int i = 0; i < NUMBER_OF_POINTS; i++) {\n        normalizedPoints[i](0) = (points[i](0) - center(0)) * scale(0);\n        normalizedPoints[i](1) = (points[i](1) - center(1)) * scale(1);\n    }\n}\n\n/**\n * Perform Iteratively Reweighted Least Squares on a model with already computed initial homographies and weights.\n * @param model The initial model, to be updated on each iteration if an improvement is made.\n * @param trackTable The table with the previously computed tracks.\n * @param weights2 The squared weights of the tracks.\n * @param tau2 Tau squared, an inlier threshold for equations (2) to (4) in Szeliski's paper.\n */\nvoid IRLS(std::shared_ptr<tfg::MotionModel> &model, std::shared_ptr<tfg::TrackTable> &trackTable, std::vector<float> &weights2, float tau2) {\n    // std::cout << \"First homography of the initial model:\" << '\\n';\n    // model->printHomography(0);\n\n    float s = 1.0f;\n    unsigned int k = 0;\n    float bestCost = -1;\n\n    std::vector<float> initialWeights2(weights2.size(), 1.0f);\n    std::vector<float> refinedWeights2(weights2.size(), 1.0f);\n    std::vector<float> bestWeights2(weights2.size(), 1.0f);\n\n    bool converged = false;\n    unsigned int numIter = 0;\n    initialWeights2.swap(weights2);\n    std::shared_ptr<tfg::MotionModel> refinedModel;\n\n    while(numIter < 50 && !converged) {\n        std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now();\n\n        // Refine model with new weights\n        refinedModel = std::make_shared<tfg::MotionModel>(trackTable, tau2);\n        refinedModel->fitFromWeights(initialWeights2);\n\n        // Compute residuals of the new model\n        std::vector<float> residuals2 = refinedModel->getResiduals2();\n        std::vector<float> currentWeights2 = tfg::getWeights2(residuals2, tau2);\n        // Update weights based on the current best model and the new one, then get the cost of the model\n        for(unsigned int i = 0; i < weights2.size(); i++) {\n            refinedWeights2[i] = s*currentWeights2[i] + (1-s)*bestWeights2[i];\n        }\n        float cost = refinedModel->getCost();\n\n        std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();\n\n        std::cout << \"(\" << k + 1 << \") Iteration cost: \" << cost << '\\n';\n        std::cout << \"(\" << k + 1 << \") Cost margin: \" << std::abs((cost - bestCost) / bestCost) << '\\n';\n        std::cout << \"(\" << k + 1 << \") Time: \" << (std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count())/1000000.0 << \" seconds\" << '\\n';\n\n        // If the cost has increased, reduce the step. If it has decreased, make the step bigger and update the best model to the new one\n        if(cost > bestCost && bestCost >= 0) {\n            s = s/4;\n        } else {\n            if(cost > 0 && std::abs((cost - bestCost) / bestCost) < 0.00001) converged = true;\n            bestCost = cost;\n            k = k + 1;\n            s = 4*s < 1 ? 4*s : 1;\n            for(unsigned int i = 0; i < bestWeights2.size(); i++) {\n                bestWeights2[i] = initialWeights2[i];\n            }\n            model = refinedModel;\n        }\n        initialWeights2.swap(refinedWeights2);\n        numIter++;\n    }\n    weights2.swap(bestWeights2);\n}\n\n} // namespace tfg\n", "meta": {"hexsha": "f7226c078bee9e0b86dbbd6ca29033948658b0de", "size": 12955, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/bgmm/Homography.cpp", "max_stars_repo_name": "msanchez-beeckman/tfg-video-segmentation", "max_stars_repo_head_hexsha": "b0a85df6d7a428abe21c5b6ed131cb047fecd1f6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-22T10:29:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-22T10:29:22.000Z", "max_issues_repo_path": "src/bgmm/Homography.cpp", "max_issues_repo_name": "msanchez-beeckman/tfg-video-segmentation", "max_issues_repo_head_hexsha": "b0a85df6d7a428abe21c5b6ed131cb047fecd1f6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/bgmm/Homography.cpp", "max_forks_repo_name": "msanchez-beeckman/tfg-video-segmentation", "max_forks_repo_head_hexsha": "b0a85df6d7a428abe21c5b6ed131cb047fecd1f6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.7903225806, "max_line_length": 201, "alphanum_fraction": 0.6117329217, "num_tokens": 3904, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321964553657, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.45371385177841034}}
{"text": "#include <algorithm>\n#include <boost/filesystem.hpp>\n#include <chrono>\n#include <cmath>\n#include <functional>\n#include <list>\n#include <map>\n#include <memory>\n#include <optional>\n#include <random>\n#include <set>\n#include <sstream>\n#include <string>\n#include <type_traits>\n#include <unordered_map>\n#include <vector>\n", "meta": {"hexsha": "d5e03f9f46bbec8ebf0bc95b4b220642073cbc37", "size": 315, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/core_pch.hpp", "max_stars_repo_name": "LazyFalcon/TechDemo-v4", "max_stars_repo_head_hexsha": "7b865e20beb7f04fde6e7df66be30f555e0aef5a", "max_stars_repo_licenses": ["MIT"], "max_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_pch.hpp", "max_issues_repo_name": "LazyFalcon/TechDemo-v4", "max_issues_repo_head_hexsha": "7b865e20beb7f04fde6e7df66be30f555e0aef5a", "max_issues_repo_licenses": ["MIT"], "max_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_pch.hpp", "max_forks_repo_name": "LazyFalcon/TechDemo-v4", "max_forks_repo_head_hexsha": "7b865e20beb7f04fde6e7df66be30f555e0aef5a", "max_forks_repo_licenses": ["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.5294117647, "max_line_length": 31, "alphanum_fraction": 0.7396825397, "num_tokens": 69, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321964553657, "lm_q2_score": 0.6370308013713525, "lm_q1q2_score": 0.4537138468704402}}
{"text": "\ufeff#define BOOST_TEST_MAIN\n#define BOOST_TEST_MODULE UnitTest\n\n#include <string>\n#include <fstream>\n#include <boost/hana.hpp>\n#include <boost/test/unit_test.hpp>\n#include <rapidjson/rapidjson.h>\n#include <rapidjson/reader.h>\n\n#include \"boilerplateCodeDoc.h\"\n\nnamespace hana = boost::hana;\nnamespace boiler = boilerplateCodeDoc;\n\n// make CTEST_OUTPUT_ON_FAILURE=1 test\n// just logging something ( --log_level=message )\n\nstatic constexpr const char* const CSS {R\"(\ntable, th, td {\n    border: 1px solid black;\n    border-collapse: collapse;\n}\nth, td {\n    padding: 5px;\n    text-align: left;\n}\ntable#t01 {\n    width: 100%;\n    background-color: #f1f1c1;\n}\n)\"};\n\nstruct GlobalInit {\n  GlobalInit() : argc(boost::unit_test_framework::framework::master_test_suite().argc),\n\t\targv(boost::unit_test_framework::framework::master_test_suite().argv){}\n  ~GlobalInit() {}\n  int argc {};\n  char **argv {nullptr};\n};\nBOOST_GLOBAL_FIXTURE( GlobalInit );\n\nBOOST_AUTO_TEST_CASE( test000 ) {\n   BOOST_TEST_MESSAGE( \"\\ntest000: BASIC USAGE of HANA lib\" );\n\n   using namespace hana::literals;\n\n   struct Fish { std::string name; };\n   struct Cat  { std::string name; };\n   struct Dog  { std::string name; };\n\n     // Sequences capable of holding heterogeneous objects, and algorithms\n  // to manipulate them.\n  auto animals = hana::make_tuple(Fish{\"Nemo\"}, Cat{\"Garfield\"}, Dog{\"Snoopy\"});\n  auto names = hana::transform(animals, [](auto a) {\n    return a.name;\n  });\n  BOOST_CHECK(hana::reverse(names) == hana::make_tuple(\"Snoopy\", \"Garfield\", \"Nemo\"));\n\n  // No compile-time information is lost: even if `animals` can't be a\n  // constant expression because it contains strings, its length is constexpr.\n  BOOST_CHECK(hana::length(animals) == 3u);\n\n  // Computations on types can be performed with the same syntax as that of\n  // normal C++. Believe it or not, everything is done at compile-time.\n  auto animal_types = hana::make_tuple(hana::type_c<Fish*>, hana::type_c<Cat&>, hana::type_c<Dog*>);\n  auto animal_ptrs = hana::filter(animal_types, [](auto a) {\n    return hana::traits::is_pointer(a);\n  });\n  BOOST_CHECK(animal_ptrs == hana::make_tuple(hana::type_c<Fish*>, hana::type_c<Dog*>));\n\n  // And many other goodies to make your life easier, including:\n  // 1. Access to elements in a tuple with a sane syntax.\n  static_assert(animal_ptrs[0_c] == hana::type_c<Fish*>, \"\");\n  static_assert(animal_ptrs[1_c] == hana::type_c<Dog*>, \"\");\n\n  // 2. Unroll loops at compile-time without hassle.\n  std::string s;\n  hana::int_c<10>.times([&]{ s += \"x\"; });\n  // equivalent to s += \"x\"; s += \"x\"; ... s += \"x\";\n\n  // 3. Easily check whether an expression is valid.\n  //    This is usually achieved with complex SFINAE-based tricks.\n  auto has_name = hana::is_valid([](auto&& x) -> decltype((void)x.name) { });\n  BOOST_CHECK(has_name(animals[0_c]));\n  BOOST_CHECK(!has_name(1));\n}\n\nBOOST_AUTO_TEST_CASE( test001 ) {\n   BOOST_TEST_MESSAGE( \"\\ntest001: BASIC USAGE of RapidJSON lib\" );\n\n   using namespace rapidjson;\n   using namespace std;\n\n   struct MyHandler {\n       bool Null() { BOOST_TEST_MESSAGE(\"Null()\"); return true; }\n       bool Bool(bool b) { BOOST_TEST_MESSAGE(\"Bool(\" << boolalpha << b << \")\"); return true; }\n       bool Int(int i) { BOOST_TEST_MESSAGE(\"Int(\" << i << \")\"); return true; }\n       bool Uint(unsigned u) { BOOST_TEST_MESSAGE(\"Uint(\" << u << \")\"); return true; }\n       bool Int64(int64_t i) { BOOST_TEST_MESSAGE(\"Int64(\" << i << \")\"); return true; }\n       bool Uint64(uint64_t u) { BOOST_TEST_MESSAGE(\"Uint64(\" << u << \")\"); return true; }\n       bool Double(double d) { BOOST_TEST_MESSAGE(\"Double(\" << d << \")\"); return true; }\n       bool RawNumber(const char* str, SizeType length, bool copy) {\n\t   BOOST_TEST_MESSAGE(\"Number(\" << str << \", \" << length << \", \" << boolalpha << copy << \")\");\n\t   return true;\n       }\n       bool String(const char* str, SizeType length, bool copy) {\n\t   BOOST_TEST_MESSAGE(\"String(\" << str << \", \" << length << \", \" << boolalpha << copy << \")\");\n\t   return true;\n       }\n       bool StartObject() { BOOST_TEST_MESSAGE(\"StartObject()\"); return true; }\n       bool Key(const char* str, SizeType length, bool copy) {\n\t   BOOST_TEST_MESSAGE(\"Key(\" << str << \", \" << length << \", \" << boolalpha << copy << \")\");\n\t   return true;\n       }\n       bool EndObject(SizeType memberCount) { BOOST_TEST_MESSAGE(\"EndObject(\" << memberCount << \")\"); return true; }\n       bool StartArray() { BOOST_TEST_MESSAGE(\"StartArray()\"); return true; }\n       bool EndArray(SizeType elementCount) { BOOST_TEST_MESSAGE(\"EndArray(\" << elementCount << \")\"); return true; }\n   };\n\n   const char json[] = \" { \\\"hello\\\" : \\\"world\\\", \\\"t\\\" : true , \\\"f\\\" : false, \\\"n\\\": null, \\\"i\\\":123, \\\"pi\\\": 3.1416, \\\"a\\\":[1, 2, 3, 4] } \";\n\n   MyHandler handler;\n   Reader reader;\n   StringStream ss(json);\n\n   BOOST_CHECK(kParseErrorNone == reader.Parse(ss, handler));\n}\n\nBOOST_AUTO_TEST_CASE( test002 ) {\n   BOOST_TEST_MESSAGE( \"\\ntest002: Transform external Json Schema into HTML\");\n\n   // taken for granted that CMake copied default json schema file in the very directory where this test binary is generated\n   std::string filename{\"schema.json\"};\n   std::string binary{boost::unit_test::framework::master_test_suite().argv[0]};\n   size_t found = binary.find_last_of(\"/\\\\\");\n   if( found > 0 ) {\n\tBOOST_TEST_MESSAGE( \"found=\" << found);\n\tfilename = binary.substr(0,found+1) + filename;\n   }\n\n   int argc =boost::unit_test::framework::master_test_suite().argc;\n   if( argc > 1) {\n\tfilename = std::string(boost::unit_test::framework::master_test_suite().argv[1]);\n   }\n   BOOST_TEST_MESSAGE( \"current binary=\" << binary );\n   BOOST_TEST_MESSAGE( \"schema.json=\" << filename );\n\n   boiler::JsonSchema jsonSchema{filename};\n   BOOST_TEST_MESSAGE( \"Json Schema: \" << jsonSchema.message);\n   boiler::JsonSchema2HTML handler {};\n   bool result = handler(jsonSchema);\n   BOOST_TEST_MESSAGE( \"JsonSchema2HTML: \" << handler.message << \"\\n\\n\" << handler.filtered);\n   BOOST_CHECK( result );\n}\n\nBOOST_AUTO_TEST_CASE( test003 ) {\n   BOOST_TEST_MESSAGE( \"\\ntest003: Transform external Json Schema into C++ structure header\");\n\n   // taken for granted that CMake copied default json schema file in the very directory where this test binary is generated\n   std::string filename{\"schema.json\"};\n   std::string binary{boost::unit_test::framework::master_test_suite().argv[0]};\n   size_t found = binary.find_last_of(\"/\\\\\");\n   if( found > 0 ) {\n\tBOOST_TEST_MESSAGE( \"found=\" << found);\n\tfilename = binary.substr(0,found+1) + filename;\n   }\n\n   int argc =boost::unit_test::framework::master_test_suite().argc;\n   if( argc > 1) {\n\tfilename = std::string(boost::unit_test::framework::master_test_suite().argv[1]);\n   }\n   BOOST_TEST_MESSAGE( \"current binary=\" << binary );\n   BOOST_TEST_MESSAGE( \"schema.json=\" << filename );\n\n   boiler::JsonSchema jsonSchema{filename};\n   BOOST_TEST_MESSAGE( \"Json Schema: \" << jsonSchema.message);\n   boiler::JsonSchema2H handler {};\n   bool result = handler(jsonSchema);\n   BOOST_TEST_MESSAGE( \"JsonSchema2H: \" << handler.message << \"\\n\\n\" << handler.filtered);\n   BOOST_CHECK( result );\n}\n\nBOOST_AUTO_TEST_CASE( test004 ) {\n   BOOST_TEST_MESSAGE( \"\\ntest004: Transform external Json Schema into C++ structure file\");\n\n   // taken for granted that CMake copied default json schema file in the very directory where this test binary is generated\n   std::string filename{\"schema.json\"};\n   std::string binary{boost::unit_test::framework::master_test_suite().argv[0]};\n   size_t found = binary.find_last_of(\"/\\\\\");\n   if( found > 0 ) {\n\tBOOST_TEST_MESSAGE( \"found=\" << found);\n\tfilename = binary.substr(0,found+1) + filename;\n   }\n\n   int argc =boost::unit_test::framework::master_test_suite().argc;\n   if( argc > 1) {\n\tfilename = std::string(boost::unit_test::framework::master_test_suite().argv[1]);\n   }\n   BOOST_TEST_MESSAGE( \"current binary=\" << binary );\n   BOOST_TEST_MESSAGE( \"schema.json=\" << filename );\n\n   boiler::JsonSchema jsonSchema{filename};\n   BOOST_TEST_MESSAGE( \"Json Schema: \" << jsonSchema.message);\n   boiler::JsonSchema2CPP handler {};\n   bool result = handler(jsonSchema);\n   BOOST_TEST_MESSAGE( \"JsonSchema2CPP: \" << handler.message << \"\\n\\n\" << handler.filtered);\n   BOOST_CHECK( result );\n}\n\n", "meta": {"hexsha": "1b6a17818d4c650d45fcedf301572d808a59748c", "size": 8234, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/main.cpp", "max_stars_repo_name": "xue2sheng/decoupleUserOutput", "max_stars_repo_head_hexsha": "8d969deef89c01404ab4ca2ddec350864c3e3196", "max_stars_repo_licenses": ["MIT"], "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/main.cpp", "max_issues_repo_name": "xue2sheng/decoupleUserOutput", "max_issues_repo_head_hexsha": "8d969deef89c01404ab4ca2ddec350864c3e3196", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/main.cpp", "max_forks_repo_name": "xue2sheng/decoupleUserOutput", "max_forks_repo_head_hexsha": "8d969deef89c01404ab4ca2ddec350864c3e3196", "max_forks_repo_licenses": ["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.0236966825, "max_line_length": 143, "alphanum_fraction": 0.6685693466, "num_tokens": 2139, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.4537138439961752}}
{"text": "//N0673230\n#include <boost/test/unit_test.hpp>\n\n#include \"logs.h\"\n#include \"route.h\"\n#include \"track.h\"\n\nusing namespace GPS;\n\nBOOST_AUTO_TEST_SUITE( total_Height_Gain )\n\nconst bool isFileName = true;\n\n// The elevation of ABCD.gpx is always 0. This means that the totalHeightGain is always going to be 0\n//this test checks that the function returns 0 for the ABCD.gpx file.\nBOOST_AUTO_TEST_CASE( ABCD_HeightGain )\n{\n   Route route = Route(LogFiles::GPXRoutesDir + \"ABCD.gpx\", isFileName);\n   BOOST_CHECK_EQUAL( route.totalHeightGain(), 0 );\n}\n\n// The elevation of NorthYorkMoors.gpx changes, and the total should be 285648.\n//this test checks that the function returns 285648 for the NorthYorkMoors.gpx file.\nBOOST_AUTO_TEST_CASE( North_HeightGain )\n{\n   Route route = Route(LogFiles::GPXRoutesDir + \"NorthYorkMoors.gpx\", isFileName);\n   BOOST_CHECK_CLOSE( route.totalHeightGain(), 285648, 0.01 );\n}\n\n//the minimum elevation possible is the same as the radius of the earth. If a value exceeds this it shouldn't be counted and an out_of_range error should be thrown.\n// this test case uses ExtremeValues.gpx to see if the function throws an error for extreme elevation values.\n//if the extreme value causes and error to be throw, then it passes the test.\nBOOST_AUTO_TEST_CASE( ExtremeValues_HeightGain )\n{\n   Route route = Route(LogFiles::GPXRoutesDir + \"ExtremeValues.gpx\", isFileName);\n   BOOST_CHECK_THROW( route.totalHeightGain(), std::out_of_range );\n}\n\n//As there is below sea level it is possible that the elevation may be negative.\n//This means that the function needs to be able to work out negative elevations as well.\n//this test case uses the BelowSeaLevel.gpx file to find out if the function can correctly calculate a negative total elevation for a route below sea level.\n//if the elevation is calculated correctly the function passes the test.\n//this also makes sure that the previous test case only works for extreme negative values, i.e. the ones greater than the radius of the earth.\n\nBOOST_AUTO_TEST_CASE( BelowSeaLevel_HeightGain )\n{\n   Route route = Route(LogFiles::GPXRoutesDir + \"BelowSeaLevel.gpx\", isFileName);\n   BOOST_CHECK_CLOSE( route.totalHeightGain(), -300, 0.01);\n}\n\n\n//Although it is possible to go higher, the maximum elevation that a person can reach on foot is the summit of Mount Everest. Which is 8848 metres above sea level.\n//this test case checks that the function accepts extreme positive elevation values.\n//As it is technically possible to go above this level, the function doesn't limit the elevation. But this test tests for large values.\nBOOST_AUTO_TEST_CASE( MountEverest_HeightGain )\n{\n   Route route = Route(LogFiles::GPXRoutesDir + \"MountEverest.gpx\", isFileName);\n   BOOST_CHECK_CLOSE( route.totalHeightGain(), 26524, 0.01);\n}\n\n\n\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "a1fc941ed7d18d10158449d0cc9997066ceb8aac", "size": 2810, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/gpx-tests/n0673230_totalheightgain.cpp", "max_stars_repo_name": "EdwinLangley/GPX-Route-and-Track", "max_stars_repo_head_hexsha": "e4de303c62c7e9dc92724e8f257f7960ff77c992", "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/gpx-tests/n0673230_totalheightgain.cpp", "max_issues_repo_name": "EdwinLangley/GPX-Route-and-Track", "max_issues_repo_head_hexsha": "e4de303c62c7e9dc92724e8f257f7960ff77c992", "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/gpx-tests/n0673230_totalheightgain.cpp", "max_forks_repo_name": "EdwinLangley/GPX-Route-and-Track", "max_forks_repo_head_hexsha": "e4de303c62c7e9dc92724e8f257f7960ff77c992", "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": 43.2307692308, "max_line_length": 164, "alphanum_fraction": 0.7754448399, "num_tokens": 668, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321964553656, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.45371384196246994}}
{"text": "#include <ros/ros.h>\n#include <stdio.h>\n\n#include <tf/transform_listener.h>\n#include <Eigen/Dense>\n\n\nint main(int argc, char** argv)\n{ \n  ros::init(argc, argv, \"my_tf_listener\");\n  ros::NodeHandle node(\"~\");\n  //ros::NodeHandle node;\n\n  tf::TransformListener listener;\n  ros::Rate rate(1);\n  float r_x = 0.0f;\n  float r_y = 0.0f;\n  float r_z = 0.0f;\n  float r_w = 0.0f;\n\n  float t_x = 0.0f;\n  float t_y = 0.0f;\n  float t_z = 0.0f;\n  int count = 0;\n\n  bool cali;\n  int caliStep;\n  node.param(\"calibration\", cali, true);\n  node.param(\"calibrationStep\", caliStep, 1);\n  // std::cout << \"The value of calibration \" << cali << std::endl;\n\n  //while (node.ok())\n  while (ros::ok())\n  {\n      // hold the transformation parameters between two coordinate frames \n      //tf::StampedTransform result_cali; \n      tf::StampedTransform transformPara;\n      try\n      { \n        if (cali)\n        {\n          if (caliStep == 1)\n          {\n            // listener.waitForTransform(\"inter_robotBase_frame\", \"endEffectorI5_frame\", ros::Time(0), ros::Duration(3.0));\n            listener.waitForTransform(\"base_link\", \"camera_frame1\", ros::Time(0), ros::Duration(4.0));\n            // For calibration - calculate the transformation between the two frames\n            listener.lookupTransform(\"camera_frame1\", \"base_link\", ros::Time(0), transformPara);\n            // listener.lookupTransform(\"base_link\", \"camera_frame1\", ros::Time(0), transformPara);\n\n            // get the value\n            tf::Quaternion rotation = transformPara.getRotation();\n            tf::Vector3 tfVect = transformPara.getOrigin();\n\n            std::cout << \"Calibration at Step 1 - Inverse Quaternion from Auto I5 Robot\" << std::endl;\n            ROS_INFO(\"Origin & Quat: %f %f %f %f %f %f %f\", tfVect.x(), tfVect.y(), tfVect.z(), rotation.x(), rotation.y(), rotation.z(), rotation.w());\n \n            \n            tf::Matrix3x3 mat(rotation);\n            tfScalar y, p, r;\n            mat.getEulerYPR(y, p, r);\n\n            ROS_INFO(\"Three Angles: %f %f %f \", r, p, y);\n\n\n            // btQuaternion::btMatrix3x3 tfMatrix; // = transformPara.getBasis();\n\n            // geometry_msgs::Pose robot_pose;\n            Eigen::Matrix4f hete_matrix;\n            \n            // for translation\n            hete_matrix(0,3) = tfVect.x();\n            hete_matrix(1,3) = tfVect.y();\n            hete_matrix(2,3) = tfVect.z();\n            hete_matrix(3,3) = 1;\n            // the last row\n            hete_matrix(3,0) = 0;\n            hete_matrix(3,1) = 0;\n            hete_matrix(3,2) = 0;\n            \n            // for rotation part\n            hete_matrix(0,0) = 1 - 2*pow(rotation.y(),2) - 2*pow(rotation.z(),2);\n            hete_matrix(1,0) = 2*(rotation.x()*rotation.y() + rotation.z()*rotation.w());\n            hete_matrix(2,0) = 2*(rotation.x()*rotation.z() - rotation.y()*rotation.w());\n\n            hete_matrix(0,1) = 2*(rotation.x()*rotation.y() - rotation.z()*rotation.w());\n            hete_matrix(1,1) = 1 - 2*pow(rotation.x(),2) - 2*pow(rotation.z(),2);\n            hete_matrix(2,1) = 2*(rotation.x()*rotation.w() + rotation.y()*rotation.z());\n\n            hete_matrix(0,2) = 2*(rotation.x()*rotation.z() + rotation.y()*rotation.w());\n            hete_matrix(1,2) = 2*(rotation.y()*rotation.z() - rotation.x()*rotation.w());\n            hete_matrix(2,2) = 1 - 2*pow(rotation.x(),2) - 2*pow(rotation.y(),2);\n\n\n\n            ROS_INFO(\"Matrix: %f %f %f %f \", hete_matrix(0,0), hete_matrix(0,1), hete_matrix(0,2), hete_matrix(0,3));\n            ROS_INFO(\"Matrix: %f %f %f %f \", hete_matrix(1,0), hete_matrix(1,1), hete_matrix(1,2), hete_matrix(1,3));\n            ROS_INFO(\"Matrix: %f %f %f %f \", hete_matrix(2,0), hete_matrix(2,1), hete_matrix(2,2), hete_matrix(2,3));\n            ROS_INFO(\"Matrix: %f %f %f %f \", hete_matrix(3,0), hete_matrix(3,1), hete_matrix(3,2), hete_matrix(3,3));\n            \n          \n\n\n\n            // ROS_INFO(\"Matrix: %f %f %f \", tfMatrix.xz(), tfMatrix.yz(), tfMatrix.zz());\n          }\n\n          if (caliStep == 2)\n          {\n            count++;\n            // wait until the two frames of camera and robot base are available\n            listener.waitForTransform(\"camera_depth_optical_frame\", \"depend_robotBase_frame\", ros::Time(0), ros::Duration(3.0));\n            // For calibration - calculate the transformation between the two frames\n            listener.lookupTransform(\"camera_depth_optical_frame\", \"depend_robotBase_frame\", ros::Time(0), transformPara);\n\n            // get the angle/quaternion\n            tf::Quaternion rotation = transformPara.getRotation();\n            // get the distance between the two frames\n            tf::Vector3 tfVect = transformPara.getOrigin();\n\n            r_x += rotation.x();\n            r_y += rotation.y();\n            r_z += rotation.z();\n            r_w += rotation.w();\n            t_x += tfVect.x();\n            t_y += tfVect.y();\n            t_z += tfVect.z();\n\n            ROS_INFO(\"Gathering data %d\", count);\n            if (count == 100)\n            {\n                std::cout << \"Calibration at Step 2 - Quaternion of robotBase frame comapring to camera_frame\" << std::endl;\n                //ROS_INFO(\"Quat: %f %f %f %f\", );\n                ROS_INFO(\"Origin & Quat: %f %f %f %f %f %f %f\", t_x/float(count), t_y/float(count), t_z/float(count), r_x/float(count), r_y/float(count), r_z/float(count), r_w/float(count));\n                count = 0;\n                t_x = 0.0;\n                t_y = 0.0;\n                t_z = 0.0;\n                r_x = 0.0;\n                r_y = 0.0;\n                r_z = 0.0;\n                r_w = 0.0;\n            }\n          }\n        }\n        else\n        {\n          // For xtion_frame.txt & displaying axes in OpenRave\n          // wait for two frames: estimate_robot_base_frame and grasp_aubo_frame available\n          listener.waitForTransform(\"fix_robotBase_frame\", \"grasp_aubo_frame\", ros::Time(0), ros::Duration(3.0));        \n\n          // transform the coordiantes from grasp_aubo_frame to estimate_robot_base_frame\n          // For display grasp in OpenRave\n          listener.lookupTransform(\"fix_robotBase_frame\", \"grasp_aubo_frame\", ros::Time(0), transformPara);  \n\n          // get the value\n          tf::Quaternion rotation = transformPara.getRotation();\n          tf::Vector3 tfVect = transformPara.getOrigin();\n\n          ROS_INFO(\"Origin & Quat: %f %f %f %f %f %f %f\", tfVect.x(), tfVect.y(), tfVect.z(), rotation.x(), rotation.y(), rotation.z(), rotation.w());\n        }\n      }\n      catch (tf::TransformException &ex) \n      {\n        ROS_ERROR(\"%s\",ex.what());\n        ros::Duration(1.0).sleep();\n        continue;\n      }\n      \n      rate.sleep();\n  }\n  return 0;\n}", "meta": {"hexsha": "bd1e55b701ee463cbfb10ecbc86f424f21f108a8", "size": 6681, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "hybrid_robot/src/coordinate_transform.cpp", "max_stars_repo_name": "buivn/hybrid_robot", "max_stars_repo_head_hexsha": "f19671a905d981adb0abb384862234aac12c204a", "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": "hybrid_robot/src/coordinate_transform.cpp", "max_issues_repo_name": "buivn/hybrid_robot", "max_issues_repo_head_hexsha": "f19671a905d981adb0abb384862234aac12c204a", "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": "hybrid_robot/src/coordinate_transform.cpp", "max_forks_repo_name": "buivn/hybrid_robot", "max_forks_repo_head_hexsha": "f19671a905d981adb0abb384862234aac12c204a", "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.8430232558, "max_line_length": 190, "alphanum_fraction": 0.5493189642, "num_tokens": 1820, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321964553656, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.4537138419624699}}
{"text": "// Copyright Matt Overby 2021.\n// Distributed under the MIT License.\n\n#ifndef MCL_READSEAMEDOBJ_HPP\n#define MCL_READSEAMEDOBJ_HPP 1\n\n#include <Eigen/Core>\n#include <vector>\n\n// TODO my own readOBJ to remove igl dependency\n#include <igl/readOBJ.h>\n\nnamespace mcl\n{\n\nstatic inline bool read_seamed_obj(\n\tstd::string filename,\n\tEigen::MatrixXd &V3D, // 3D vertices\n\tEigen::MatrixXd &VTC, // 2D UV tex init, if found\n\tEigen::MatrixXi &F)\n{\n\tusing namespace Eigen;\n\tMatrixXd V3D_, vN_unused;\n\tMatrixXi F3D_, fN_unused;\n\tbool read_success = igl::readOBJ(\n\t\tfilename,\n\t\tV3D_, VTC, vN_unused,\n\t\tF3D_, F, fN_unused);\n\n\tif (!read_success) { return false; }\n\n\tif (VTC.rows() > 0 && F.rows() > 0)\n\t{\n\t\t// Create 3D verts from F so face meshes match\n\t\tstd::vector<bool> filled(VTC.rows(),false);\n\t\tV3D = MatrixXd::Zero(VTC.rows(),3);\n\t\tif(F3D_.rows() != F.rows()){ return false; }\n\t\tint nf = F3D_.rows();\n\t\tfor(int i=0; i<nf; i++)\n\t\t{\n\t\t\tfor(int j:{0,1,2})\n\t\t\t{\n\t\t\t\tint f = F3D_(i,j);\n\t\t\t\tint f_uv = F(i,j);\n\t\t\t\tif(!filled[f_uv])\n\t\t\t\t{\n\t\t\t\t\tV3D.row(f_uv) = V3D_.row(f);\n\t\t\t\t\tfilled[f_uv] = true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\telse\n\t{\n\t\tF = F3D_;\n\t\tVTC = V3D_.block(0,0,V3D_.rows(),2);\n\t\tV3D = V3D_;\n\t}\n\n\tif( F.minCoeff() > 0 ){ F.array() -= 1; }\n\treturn true;\n\n}\n\n} // end ns mcl\n\n#endif", "meta": {"hexsha": "223cc4c8b203733981cbe12180d370cfb59483f6", "size": 1263, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/MCL/ReadSeamedObj.hpp", "max_stars_repo_name": "mattoverby/mclgeom", "max_stars_repo_head_hexsha": "d3ecd2a878900f33ba1412b8d82e643895201e51", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/MCL/ReadSeamedObj.hpp", "max_issues_repo_name": "mattoverby/mclgeom", "max_issues_repo_head_hexsha": "d3ecd2a878900f33ba1412b8d82e643895201e51", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-26T22:44:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T02:54:23.000Z", "max_forks_repo_path": "include/MCL/ReadSeamedObj.hpp", "max_forks_repo_name": "mattoverby/mclgeom", "max_forks_repo_head_hexsha": "d3ecd2a878900f33ba1412b8d82e643895201e51", "max_forks_repo_licenses": ["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.8507462687, "max_line_length": 50, "alphanum_fraction": 0.622327791, "num_tokens": 453, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321964553657, "lm_q2_score": 0.6370307875894139, "lm_q1q2_score": 0.4537138370544998}}
{"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/**\n  * \\file lsh-run.cpp\n  * \\brief Example of using RandomThresholding LSH index for L1 distance.\n  *\n  * This program is an example of using LSH index.  The LSH used is\n  * Tail<RepeatHash<ThresholdingLsh> >.  The ThresholdingLSH is repeated\n  * M times and then randomly hashed to a integer within the range of\n  * [0, H).  The size of one hash table is H.  The LSH family approximates\n  * L1 distance.\n  *\n  * The program reconstruct the LSH index by default.  You can give the\n  * --index option to make the program save the LSH index.  The next\n  * time you run the program with the same --index option, the program\n  * will try to load the previously saved index.  When a saved index is\n  * used, you need to make sure that the dataset and other parameters match\n  * the previous run.  However, the benchmark file, Q and K can be different.\n  *\n\\verbatim\nAllowed options:\n  -h [ --help ]            produce help message.\n  -M [ -- ] arg (=20)\n  -L [ -- ] arg (=1)       number of hash tables\n  -Q [ -- ] arg (=100)     number of queries to use\n  -K [ -- ] arg (=50)      number of nearest neighbors to retrieve\n  -D [ --data ] arg        dataset path\n  -B [ --benchmark ] arg   benchmark path\n  --index arg              index file\n  -H [ -- ] arg (=1017881) hash table size, use the default.\n\\endverbatim\n  * \n  */\n\n#include <boost/program_options.hpp>\n#include <boost/progress.hpp>\n#include <boost/format.hpp>\n#include <boost/timer.hpp>\n#include <lshkit.h>\n\nusing namespace std;\nusing namespace lshkit;\nnamespace po = boost::program_options; \n\nint main (int argc, char *argv[])\n{\n    string data_file;\n    string benchmark;\n    string index_file;\n\n    float R;\n    unsigned M, L, H;\n    unsigned Q, K;\n    bool do_benchmark = true;\n    bool use_index = false; // load the index from a file\n\n    boost::timer timer;\n\n    po::options_description desc(\"Allowed options\");\n    desc.add_options()\n        (\"help,h\", \"produce help message.\")\n        (\",M\", po::value<unsigned>(&M)->default_value(20), \"\")\n        (\",L\", po::value<unsigned>(&L)->default_value(1), \"number of hash tables\")\n        (\",Q\", po::value<unsigned>(&Q)->default_value(100), \"number of queries to use\")\n        (\",K\", po::value<unsigned>(&K)->default_value(50), \"number of nearest neighbors to retrieve\")\n        (\",R\", po::value<float>(&R)->default_value(numeric_limits<float>::max()), \"R-NN distance range\")\n        (\"data,D\", po::value<string>(&data_file), \"dataset path\")\n        (\"benchmark,B\", po::value<string>(&benchmark), \"benchmark path\")\n        (\"index\", po::value<string>(&index_file), \"index file\")\n        (\",H\", po::value<unsigned>(&H)->default_value(1017881), \"hash table size, use the default.\")\n        ;\n\n    po::variables_map vm;\n    po::store(po::parse_command_line(argc, argv, desc), vm);\n    po::notify(vm); \n\n    if (vm.count(\"help\") || (vm.count(\"data\") < 1))\n    {\n        cout << desc;\n        return 0;\n    }\n\n    if ((Q == 0) || (vm.count(\"benchmark\") == 0)) {\n        do_benchmark = false;\n    }\n\n    if (vm.count(\"index\") == 1) {\n        use_index = true;\n    }\n\n    cout << \"LOADING DATA...\" << endl;\n    timer.restart();\n    FloatMatrix data(data_file);\n    cout << boost::format(\"LOAD TIME: %1%s.\") % timer.elapsed() << endl;\n\n    //typedef Tail<RepeatHash<CauchyLsh> > MyLsh;\n\n    typedef Tail<RepeatHash<ThresholdingLsh> > MyLsh;\n    typedef LshIndex<MyLsh, unsigned> Index;\n\n    metric::l1<float> l1(data.getDim());\n    FloatMatrix::Accessor accessor(data);\n    Index index;\n\n    bool index_loaded = false;\n\n    if (use_index) {\n        ifstream is(index_file.c_str(), ios_base::binary);\n        if (is) {\n            is.exceptions(ios_base::eofbit | ios_base::failbit | ios_base::badbit);\n            cout << \"LOADING INDEX...\" << endl;\n            timer.restart();\n            index.load(is);\n            BOOST_VERIFY(is);\n            cout << boost::format(\"LOAD TIME: %1%s.\") % timer.elapsed() << endl;\n            index_loaded = true;\n        }\n    }\n\n    if (!index_loaded) {\n        // We define a short name for the MPLSH index.\n        float min = numeric_limits<float>::max();\n        float max = -numeric_limits<float>::max();\n\n        for (int i = 0; i < data.getSize(); ++i) {\n            for (int j = 0; j < data.getDim(); ++j) {\n                if (data[i][j] > max) max = data[i][j];\n                if (data[i][j] < min) min = data[i][j];\n            }\n        }\n\n        Index::Parameter param;\n\n        // Setup the parameters.  Note that L is not provided here.\n        param.range = H;\n        param.repeat = M;\n        param.min = min;\n        param.max = max;\n        param.dim = data.getDim();\n        DefaultRng rng;\n\n        index.init(param, rng, L);\n        // The accessor.\n\n        // Initialize the index structure.  Note L is passed here.\n        cout << \"CONSTRUCTING INDEX...\" << endl;\n\n        timer.restart();\n        {\n            boost::progress_display progress(data.getSize());\n            for (int i = 0; i < data.getSize(); ++i)\n            {\n                // Insert an item to the hash table.\n                // Note that only the key is passed in here.\n                // MPLSH will get the feature from the accessor.\n                index.insert(i, data[i]);\n                ++progress;\n            }\n        }\n        cout << boost::format(\"CONSTRUCTION TIME: %1%s.\") % timer.elapsed() << endl;\n\n        if (use_index) {\n            timer.restart();\n            cout << \"SAVING INDEX...\" << endl;\n            {\n                ofstream os(index_file.c_str(), ios_base::binary);\n                os.exceptions(ios_base::eofbit | ios_base::failbit | ios_base::badbit);\n                index.save(os);\n                BOOST_VERIFY(os);\n            }\n            cout << boost::format(\"SAVING TIME: %1%s\") % timer.elapsed() << endl;\n        }\n    }\n\n    if (do_benchmark) {\n\n        Benchmark<> bench;\n        cout << \"LOADING BENCHMARK...\" << endl;\n        bench.load(benchmark);\n        bench.resize(Q, K);\n        cout << \"DONE.\" << endl;\n\n        for (unsigned i = 0; i < Q; ++i)\n        {\n            for (unsigned j = 0; j < K; ++j)\n            {\n                assert(bench.getAnswer(i)[j].key < data.getSize());\n            }\n        }\n\n        cout << \"RUNNING QUERIES...\" << endl;\n\n        Stat recall;\n        Stat cost;\n\n        timer.restart();\n        {\n            TopkScanner<FloatMatrix::Accessor, metric::l1<float> > query(accessor, l1, K, R);\n            boost::progress_display progress(Q);\n            for (unsigned i = 0; i < Q; ++i)\n            {\n                query.reset(data[bench.getQuery(i)]);\n                index.query(data[bench.getQuery(i)], query);\n                recall << bench.getAnswer(i).recall(query.topk());\n                cost << double(query.cnt())/double(data.getSize());\n                ++progress;\n            }\n        }\n        cout << boost::format(\"QUERY TIME: %1%s.\") % timer.elapsed() << endl;\n\n        cout << \"[RECALL] \" << recall.getAvg() << \" +/- \" << recall.getStd() << endl;\n        cout << \"[COST] \" << cost.getAvg() << \" +/- \" << cost.getStd() << endl;\n\n    }\n\n    return 0;\n}\n\n", "meta": {"hexsha": "8eef80462b86c059ed3bd708b6c00edb38574a76", "size": 7856, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "similarity_search/lshkit/tools/lsh-run.cpp", "max_stars_repo_name": "huonw/nmslib", "max_stars_repo_head_hexsha": "2e424ef7c6eff10ecaf47392fd99f93f645e752f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 150.0, "max_stars_repo_stars_event_min_datetime": "2016-06-03T16:39:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-24T05:32:56.000Z", "max_issues_repo_path": "similarity_search/lshkit/tools/lsh-run.cpp", "max_issues_repo_name": "huonw/nmslib", "max_issues_repo_head_hexsha": "2e424ef7c6eff10ecaf47392fd99f93f645e752f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2016-06-03T13:43:21.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-28T07:42:02.000Z", "max_forks_repo_path": "similarity_search/lshkit/tools/lsh-run.cpp", "max_forks_repo_name": "huonw/nmslib", "max_forks_repo_head_hexsha": "2e424ef7c6eff10ecaf47392fd99f93f645e752f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 42.0, "max_forks_repo_forks_event_min_datetime": "2016-05-18T05:53:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-27T19:57:52.000Z", "avg_line_length": 33.2881355932, "max_line_length": 104, "alphanum_fraction": 0.5628818737, "num_tokens": 1979, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.4537138341802351}}
{"text": "#include <shg/specfunc.h>\n#include <boost/math/distributions/fisher_f.hpp>\n#include <boost/math/distributions/normal.hpp>\n#include <boost/math/distributions/students_t.hpp>\n#include <boost/math/special_functions/beta.hpp>\n#include <boost/math/special_functions/digamma.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n#include <shg/mconsts.h>\n#include <shg/utils.h>\n#include \"testing.h\"\n\nnamespace SHG::Testing {\n\nBOOST_AUTO_TEST_SUITE(specfunc_test)\n\nBOOST_AUTO_TEST_CASE(normal_integral_at_zero_test) {\n     using boost::math::normal_distribution;\n     const double y = normal_integral(0.0);\n     BOOST_CHECK(faeq(y, 0.5, 1e-12));\n}\n\nnamespace bdata = boost::unit_test::data;\n\nBOOST_DATA_TEST_CASE(normal_integral_test, bdata::xrange(61), xr1) {\n     using boost::math::normal_distribution;\n     const double x = -3.0 + xr1 * 0.1;\n     const double y = normal_integral(x);\n     normal_distribution normal;\n     const double z = cdf(normal, x);\n     BOOST_CHECK(faeq(y, z, 1e-12));\n}\n\nBOOST_DATA_TEST_CASE(ppnd_test, bdata::xrange(199), xr1) {\n     using boost::math::normal_distribution;\n     const int i = xr1;\n     const double x = 0.005 * (i + 1);\n     const double y = ppnd7(x);\n     normal_distribution normal;\n     const double z = quantile(normal, x);\n     BOOST_CHECK(faeq(y, z, 3e-7));\n}\n\nBOOST_DATA_TEST_CASE(gammad_test,\n                     bdata::xrange(101) * bdata::xrange(100), xr1,\n                     xr2) {\n     using boost::math::gamma_p;\n     const double x = xr1 * 0.1;\n     const double p = (xr2 + 1) * 0.1;\n     const double y = gammad(x, p);\n     const double z = gamma_p(p, x);\n     BOOST_CHECK(faeq(y, z, 1e-8));\n}\n\nBOOST_DATA_TEST_CASE(probst_test,\n                     bdata::xrange(18) * bdata::xrange(81), xr1,\n                     xr2) {\n     using boost::math::students_t_distribution;\n     const int df = xr1 + 1;\n     const double x = xr2 * 0.1;\n     const double y = probst(x, df);\n     students_t_distribution t(narrow_cast<double, int>(df));\n     const double z = cdf(t, x);\n     BOOST_CHECK(faeq(y, z, 1e-15));\n}\n\nBOOST_DATA_TEST_CASE(betain_test,\n                     bdata::xrange(9) * bdata::xrange(10) *\n                          bdata::xrange(10),\n                     xr1, xr2, xr3) {\n     using boost::math::ibeta;\n     const double x = xr1 * 0.1;\n     const double p = xr2 + 1;\n     const double q = xr3 + 1;\n     const double y = betain(x, p, q);\n     const double z = ibeta(p, q, x);\n     BOOST_CHECK(faeq(y, z, 1e-10));\n}\n\nBOOST_DATA_TEST_CASE(cdffdist_test,\n                     bdata::xrange(10) * bdata::xrange(10) *\n                          bdata::xrange(10),\n                     xr1, xr2, xr3) {\n     using boost::math::fisher_f_distribution;\n     const int m = xr1 + 1;\n     const int n = xr2 + 1;\n     const double x = xr3 + 1;\n\n     const double y = cdffdist(m, n, x);\n     fisher_f_distribution f(narrow_cast<double, int>(m),\n                             narrow_cast<double, int>(n));\n     const double z = cdf(f, x);\n     BOOST_CHECK(faeq(y, z, 3e-8));\n}\n\nBOOST_AUTO_TEST_CASE(digamma_at_zero_test) {\n     BOOST_CHECK_THROW(digamma(0.0), std::invalid_argument);\n}\n\n// digamma(0.5) = -2 ln(2) - gamma\nBOOST_AUTO_TEST_CASE(digamma_at_half_test) {\n     using Constants::gamma;\n     BOOST_CHECK(faeq<double>(\n          digamma(0.5), -2.0 * std::log(2.0) - gamma<double>, 9e-7));\n}\n\n// digamma(n) = -gamma + \\sum_{k = 1}^{n - 1} (1 / k) for n >= 2\nBOOST_DATA_TEST_CASE(digamma_at_int_test, bdata::xrange(19), xr1) {\n     using Constants::gamma;\n     const int n = xr1 + 2;\n     double s = 0.0;\n     for (int k = n - 1; k > 0; k--)\n          s += 1.0 / k;\n     s -= gamma<double>;\n     BOOST_CHECK(faeq<double>(digamma(n), s, 3e-7));\n}\n\nBOOST_DATA_TEST_CASE(digamma_test, bdata::xrange(100), xr1) {\n     const float x = (xr1 + 1) * 0.1;\n     const float y = digamma(x);\n     const float z = boost::math::digamma(x);\n     BOOST_CHECK(faeq(y, z, 1e-6f));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n}  // namespace SHG::Testing\n", "meta": {"hexsha": "b0b557e31327aaec5ffdff5c20b68827ab17bbc3", "size": 3979, "ext": "cc", "lang": "C++", "max_stars_repo_path": "testing/specfunc_test.cc", "max_stars_repo_name": "shgalus/shg", "max_stars_repo_head_hexsha": "0318d0126cf12c3236183447d130969c468a02fa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2015-05-21T04:14:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-31T17:15:15.000Z", "max_issues_repo_path": "testing/specfunc_test.cc", "max_issues_repo_name": "shgalus/shg", "max_issues_repo_head_hexsha": "0318d0126cf12c3236183447d130969c468a02fa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-05-21T05:31:04.000Z", "max_issues_repo_issues_event_max_datetime": "2015-05-21T05:31:04.000Z", "max_forks_repo_path": "testing/specfunc_test.cc", "max_forks_repo_name": "shgalus/shg", "max_forks_repo_head_hexsha": "0318d0126cf12c3236183447d130969c468a02fa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2015-05-21T04:14:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-18T12:35:22.000Z", "avg_line_length": 31.3307086614, "max_line_length": 69, "alphanum_fraction": 0.6079416939, "num_tokens": 1221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.45371383418023503}}
{"text": "/*\n *  parameter_test.cpp\n *\n *  Created by Ania M. Kedzierska on 11/11/11.\n *  Copyright 2011 Politecnic University of Catalonia, Center for Genomic Regulation.  This is program can be redistributed, modified or else as given by the terms of the GNU General Public License.\n *\n */\n// as in parameter.cpp, this file contains additional functions I used for testing and getting a feel of the problem.\n\n#include \"parameter_tests.h\"\n#include \"em.h\"\n#include \"sampling.h\"\n#include \"parameters.h\"\n#include \"miscelania.h\"\n#include \"random.h\"\n#include \"alignment.h\"\n#include \"fisher.h\"\n#include <tuple>\n\n#include <vector>\n#include <algorithm>\n#include \"boost/math/distributions/chi_squared.hpp\"\n#include \"boost/math/special_functions/fpclassify.hpp\"\n#include \"boost/math/special_functions/erf.hpp\"\n#include <boost/math/special_functions/beta.hpp>\n\n#include <cmath>\n#include<iostream>\n#include <fstream>\n#include <list>\n\n#include <stdexcept>\n\n// Those values should be read from a file, here they were calculated prior to the simulations\ndouble get_scale_constant(Model &Mod) {\n  if (Mod.m == JC) return 11.8877007085245;\n  else if (Mod.m == K80) return 14.3316208140274;\n  else if (Mod.m == K81) return 17.3950207294731;\n  else if (Mod.m == SSM) return 17.3738070524995;\n  else return 0;\n}\n\n// multinomial sampling\n\n// p: vector with probabilities\n// N: length of the sampled vector\n// x: output vector with a single multinomial sample of length p.size(),\n// the entry x[s] is the count for the state s and these entries add up to N.\n\nvoid multinomial_sample(std::vector<double> &p, long N, std::vector<double> &x) {\n\tunsigned long i;\n\tlong s;\n\tx.resize(p.size(), 0);   // counts for every possible state. Initially set to 0.\n\tfor (i=0; i < p.size(); i++) {\n\t\tx[i] = 0;\n\t}\n\n\tfor(long j=0; j < N; j++) {\n\t\ts = discrete(p);\n\t\t//std::cout << \"sample: \" << s << \"             \\n\";\n\n\t\tx[s]++;\n\t}\n\n}\n\n\n// sum of KL's for the first row of the transition matrix.\nvoid KL_divergence_edges(Tree &T, Model &Mod, Parameters &Par1, Parameters &Par2, std::vector<double> &KL) {\n  long e, i, r, rr;\n  double d, dacc;\n  r = 0;\n  rr = 1;\n\n\t//if unimplemented modelwas called\n  if (Mod.m != JC && Mod.m != K80  && Mod.m != K81  && Mod.m != SSM) {\n    throw std::range_error( \"ERROR: KL_divergence_edges not implemented for this model.\");\n  }\n\n  KL.resize(T.nedges);\n  for (e=0; e < T.nedges; e++) {\n    dacc = 0;\n    for (i=0; i < T.nalpha; i++) {\n      if (Par1.tm[e][r][i] > 0) {\n        d = Par1.tm[e][r][i]*log(Par1.tm[e][r][i]/Par2.tm[e][r][i]);\n      } else {\n        d = 0;\n      }\n      dacc = dacc + d;\n    }\n\n    if (Mod.m == SSM) {\n      for (i=0; i < T.nalpha; i++) {\n        if (Par1.tm[e][rr][i] > 0) {\n          d = Par1.tm[e][rr][i]*log(Par1.tm[e][rr][i]/Par2.tm[e][rr][i]);\n        } else {\n          d = 0;\n        }\n        dacc = dacc + d;\n      }\n    }\n    KL[e] = dacc;\n  }\n}\n\n\n// Computes a chi^2 statistic. Covbr is the inverse covariance matrix for a branch.\ndouble chi2_mult(std::vector<double> &mu, std::vector<double> &x, Array2 &Covbr){\n  double X = 0.0;\n  for(unsigned int i=0; i < mu.size(); i++) {\n    for(unsigned int j=0; j < mu.size(); j++) {\n      X = X + Covbr[j][i]*(x[i] - mu[i])*(x[j] - mu[j]);\n    }\n  }\n  return X;\n}\n\n\nbool double_pointer_comparison(const double *a, const double *b) {\n  return *a < *b;\n}\n\n// version 2:\nvoid BH(std::vector<double> &pvals, std::vector<double> &qvals) {\n\tlong i, n;\n\n        // Copies pvals to qvals\n        for(unsigned long j=0; j < pvals.size(); j++) {\n\t  qvals[j] = pvals[j];\n        }\n\n     \tstd::vector<double*> pvals_p;        // the vector of pointers\n\tn = (long) pvals.size();\n\n        pvals_p.resize(n);\n        for(long j=0; j < n; j++) {\n\t     pvals_p[j] = &qvals[j];\n        }\n\n        // Sorts the vector of pointers only.\n\tstd::sort(pvals_p.begin(), pvals_p.end(), double_pointer_comparison);\n\n\t     // Here corrects p-values using the sorted vector of pointers pval_p.\n        // *(pvals_p[i]) is the value of the i-th smallest number in qvals,\n        // moreover, modifying its value here, changes it in the vector qvals.\n\n\tfor(i=n-2; i >= 0; i--) {\n\t  *(pvals_p[i]) = *(pvals_p[i]) * ((double)n/(double)(i+1));\n\t  if (*(pvals_p[i]) > *(pvals_p[i+1])) *(pvals_p[i]) = *(pvals_p[i+1]);\n\t}\n}\n\n// Computes the p-value of X for a chi^2 distribution with a given df\ndouble pvalue_chi2 (double X, int df) {\n\tif (boost::math::isinf(X)) {\n\t\treturn 0.;\n\t} else {\n\t\tboost::math::chi_squared chi2(df);\n\t\treturn 1 - boost::math::cdf(chi2, X);\n\t}\n}\n\n// Uses Fischer's method to combine the p-values\ndouble Fisher_combined_pvalue(std::vector<double> &pvals) {\n  int i;\n  long n;\n  double X2;\n  n = pvals.size();\n\n  // We compute the Fisher's statistic\n  X2 = 0;\n  for (i=0; i < n; i++) {\n    X2 = X2 + -2*log(pvals[i]);\n  }\n\n  // Return the p-value of Fisher's statistc\n  return pvalue_chi2(X2, 2*n);\n}\n\n\n// Normalizes a vector of data.\nvoid normalize(std::vector<double> &x) {\n  unsigned long i;\n  double mean, std;\n  mean = 0.;\n  for (i = 0; i < x.size(); i++) {\n    mean = mean + x[i];\n  }\n  mean = mean / (double)x.size();\n\n  std = 0.;\n  for (i=0; i < x.size(); i++) {\n    std = std + (x[i] - mean)*(x[i] - mean);\n  }\n  std = sqrt(std);\n\n  for (i=0; i < x.size(); i++) {\n    x[i] = (x[i] - mean)/std;\n  }\n}\n\n\n// Combines p-values using Z-score.\ndouble Zscore_combined_pvalue(std::vector<double> &pvals) {\n\n  unsigned long i;\n  double z, zcomb, pcomb;\n\n  zcomb = 0.;\n  for (i=0; i < pvals.size(); i++) {\n\n    // If some p-value is 0, the score will be 0.\n    if (pvals[i] <= 0) {\n      return 0;\n    }\n\n    // If some p-value is 1, the score will be 1.\n    if (pvals[i] >= 1) {\n      return 1;\n    }\n\n    z = sqrt(2)*boost::math::erf_inv(2*(1-pvals[i]) - 1);       // Sure ???\n    zcomb = zcomb + z;\n  }\n  zcomb = zcomb / sqrt((double) pvals.size());\n  pcomb = 1 - 0.5*(1+erf(zcomb/sqrt(2)));\n  return pcomb;\n}\n\n\n\n// Performs N repetitions of the EM algorithm and computes combined p-values for every edge.\n// Parameters:\n// Nrep:    Number of repetitions\n// length:  Length of the alignment of simulated data\n// pvals:   Vector of p-values indexed by the edges in T\n// data_prefix: If different from != \"\" stores the output data\n\nvoid parameter_test(Tree &T, Model &Mod, long Nrep, long length, double eps, std::vector<double> &pvals, std::string data_prefix, bool save_mc_exact){\n\n  long iter;\n  long i, r;\n\n  double df, C;\n  double distance, KL;\n\tKL=0;\n\tdistance=0;\n  double likel;\n\n\n  Parameters Parsim, Par, Par_noperm;\n  Alignment align;\n  Counts data;\n\n  double eps_pseudo = 0.001;     // Amount added to compute the pseudo-counts.\n\n  StateList sl;\n\n  bool save_data = (data_prefix != \"\");\n\n\n  std::string output_filename;\n  std::stringstream output_index;\n  std::ofstream logfile;\n  std::ofstream logdistfile;\n\n  std::ofstream out_chi2;\n  std::ofstream out_br;\n  std::ofstream out_brPerc;\n\n  std::ofstream out_pvals;\n  std::ofstream out_pvals_noperm;\n  std::ofstream out_qvals;\n  std::ofstream out_bound;\n  std::ofstream out_variances;\n  std::ofstream out_qvalsComb;\n  std::ofstream out_qvalsCombzscore;\n  std::ofstream out_covmatrix;\n\n  std::ofstream out_parest;\n  std::ofstream out_parsim;\n\n  std::vector<double> KLe;\n  std::vector<std::vector<double> > chi2_array; // an array of chi2 for every edge.\n  std::vector<std::vector<double> > mult_array; // an array of mult for every edge.\n  std::vector<std::vector<double> > br_array; // an array of br. length for every edge.\n  std::vector<std::vector<double> > br_arrayPerc; // an array of br. length for every edge.\n\n  std::vector<std::vector<double> > cota_array; // an array of upper bounds of the diff in lengths for every edge.\n  std::vector<std::vector<double> > pval_array; // an array of pvals for every edge.\n  std::vector<std::vector<double> > pval_noperm_array;\n  std::vector<std::vector<double> > qval_array; // an array of qvalues for every edge.\n  std::vector<std::vector<double> > variances_array; // an array of theoretical variances.\n  std::vector<std::vector<double> > parest_array; // array of estimated parameters\n  std::vector<std::vector<double> > parsim_array; // array of simulation parameters\n\n\t//  ci_binom ci_bin; // condfidence interval\n  std::vector<std::vector<ci_binom> > CIbinomial ; //  \tvector of CIs\n\n  std::list<long> produced_nan;\n\n  long npars = T.nedges*Mod.df + Mod.rdf;\n\n  // Initializing pvals\n  pvals.resize(T.nedges);\n\n  // Initialize the parameters for simulation of K81 data for testing\n  Par = create_parameters(T);\n  Parsim = create_parameters(T);\n\n  // Initializing data structures\n  KLe.resize(T.nedges);\n\n\tpval_array.resize(T.nedges);\n        pval_noperm_array.resize(T.nedges);\n        qval_array.resize(T.nedges);\n\tchi2_array.resize(T.nedges);\n\tmult_array.resize(T.nedges);\n\tbr_array.resize(T.nedges);\n        br_arrayPerc.resize(T.nedges);\n\tcota_array.resize(T.nedges);\n        variances_array.resize(npars);\n        parest_array.resize(npars);\n        parsim_array.resize(npars);\n\n\t// initialize to 0's\n  for (i=0; i < T.nedges; i++) {\n      pval_array[i].resize(Nrep, 0);\n      pval_noperm_array[i].resize(Nrep, 0);\n      qval_array[i].resize(Nrep, 0);\n          chi2_array[i].resize(Nrep, 0);\n\t  mult_array[i].resize(Nrep, 0);\n\t  br_array[i].resize(Nrep, 0);\n          br_arrayPerc[i].resize(Nrep, 0);\n\t  cota_array[i].resize(Nrep, 0);\n  }\n\n  for(i=0; i < npars; i++) {\n    variances_array[i].resize(Nrep, 0);\n    parest_array[i].resize(Nrep, 0);\n    parsim_array[i].resize(Nrep, 0);\n  }\n\n  // Information about the chi^2.\n  df = Mod.df;\n  C = get_scale_constant(Mod);\n\n\n  if (save_data) {\n    logfile.open((data_prefix + \".log\").c_str(), std::ios::out);\n    logfile << \"model:  \" << Mod.name << std::endl;\n    logfile << \"length: \" << length << std::endl;\n    logfile << \"eps:    \" << eps << std::endl;\n    logfile << \"nalpha: \" << T.nalpha << std::endl;\n    logfile << \"leaves: \" << T.nleaves << std::endl;\n    logfile << \"tree:   \" << T.tree_name << std::endl;\n    logfile << std::endl;\n    logdistfile.open((data_prefix + \".dist.log\").c_str(), std::ios::out);\n\n    out_chi2.open((\"out_chi2-\" + data_prefix + \".txt\").c_str(), std::ios::out);\n    out_br.open((\"out_br-\" + data_prefix + \".txt\").c_str(), std::ios::out);\n    out_brPerc.open((\"out_brPerc-\" + data_prefix + \".txt\").c_str(), std::ios::out);\n    out_pvals.open((\"out_pvals-\" + data_prefix + \".txt\").c_str(), std::ios::out);\n    out_pvals_noperm.open((\"out_pvals_noperm-\" + data_prefix + \".txt\").c_str(), std::ios::out);\n    out_qvals.open((\"out_qvals-\" + data_prefix + \".txt\").c_str(), std::ios::out);\n    out_variances.open((\"out_variances-\" + data_prefix + \".txt\").c_str(), std::ios::out);\n    out_parest.open((\"out_params-est-\" + data_prefix + \".txt\").c_str(), std::ios::out);\n    out_parsim.open((\"out_params-sim-\" + data_prefix + \".txt\").c_str(), std::ios::out);\n    out_bound.open((\"out_bound-\" + data_prefix + \".txt\").c_str(), std::ios::out);\n    out_qvalsComb.open((\"out_qvalsComb-\" + data_prefix + \".txt\").c_str(), std::ios::out);\n    out_qvalsCombzscore.open((\"out_qvalsCombzscore-\" + data_prefix + \".txt\").c_str(), std::ios::out);\n\n    out_parsim.precision(15);\n    out_parest.precision(15);\n    out_variances.precision(15);\n  }\n\n\n\t// uncomment the 2 following lines if want to fix the parameters\n\t// random_parameters_length(T, Mod, Parsim);\n\t //random_data(T, Mod, Parsim, length, align);\n\n  for (iter=0; iter < Nrep; iter++) {\n    std::cout << \"iteration: \" << iter << \"             \\n\";\n\n    // Produces an alignment from random parameters\n    random_parameters_length(T, Mod, Parsim);\n\n\n    random_data(T, Mod, Parsim, length, align);\n    get_counts(align, data);\n    add_pseudocounts(eps_pseudo, data);\n\n    // Saving data\n    if (save_data) {\n      output_index.str(\"\");\n      output_index << iter;\n      output_filename = data_prefix + \"-\" + output_index.str();\n      save_alignment(align, output_filename + \".fa\");\n      save_parameters(Parsim, output_filename + \".sim.dat\");\n    }\n\n    // Runs the EM\n    std::tie(likel, iter) = EMalgorithm(T, Mod, Par, data, eps);\n\n    // If algorithm returns NaN skip this iteration.\n    if (boost::math::isnan(likel)) {\n      produced_nan.push_back(iter);\n      continue;\n    }\n    copy_parameters(Par, Par_noperm);\n\n    // Chooses the best permutation.\n    guess_permutation(T, Mod, Par);\n\n    distance = parameters_distance(Parsim, Par);\n\n      // estimated counts: Par ; original: Parsim\n      std::vector<double> counts_est;\n      counts_est.resize(T.nalpha, 0);\n\n\n      // calculate the cov matrix\n      std::vector<std::vector<double> > Cov;\n      Array2 Cov_br;\n\n      full_MLE_covariance_matrix(T, Mod, Parsim, length, Cov);\n\n      if(save_data) {\n          save_matrix(Cov, output_filename + \".cov.dat\");\n      }\n\n      // Save the covariances in an array\n      std::vector<double> param;\n      std::vector<double> param_sim;\n\n      param.resize(npars);\n      param_sim.resize(npars);\n\n      get_free_param_vector(T, Mod, Par, param);\n      get_free_param_vector(T, Mod, Parsim, param_sim);\n\n      for(i=0; i < npars; i++) {\n\tvariances_array[i][iter] = Cov[i][i];\n        parsim_array[i][iter] = param_sim[i];\n        parest_array[i][iter] = param[i];\n      }\n\n      std::vector<double> xbranca, xbranca_noperm, mubranca;\n      double chi2_noperm;\n      xbranca.resize(Mod.df);\n      xbranca_noperm.resize(Mod.df);\n      mubranca.resize(Mod.df);\n      for (i=0; i < T.nedges; i++) {\n\t\t  r = 0; // row to be fixed\n\t\t  // Extracts the covariance matrix, 1 edge\n\n\t\t\t\t  branch_inverted_covariance_matrix(Mod, Cov, i, Cov_br);\n                  get_branch_free_param_vector(T, Mod, Parsim, i, mubranca);\n                  get_branch_free_param_vector(T, Mod, Par, i, xbranca);\n                  get_branch_free_param_vector(T, Mod, Par_noperm, i, xbranca_noperm);\n\n\t\t\t      chi2_array[i][iter] = chi2_mult(mubranca, xbranca, Cov_br);\n                  chi2_noperm = chi2_mult(mubranca, xbranca_noperm, Cov_br);\n\n\n                  pval_array[i][iter] =  pvalue_chi2(chi2_array[i][iter], Mod.df);\n                  pval_noperm_array[i][iter] = pvalue_chi2(chi2_noperm, Mod.df);\n\n\t\t\t      br_array[i][iter] = T.edges[i].br - branch_length(Par.tm[i], T.nalpha);\n\t\t\t\t  br_arrayPerc[i][iter] = branch_length(Par.tm[i], T.nalpha)/T.edges[i].br;\n\n\n\t\t// Upper bound on the parameter distance using multinomial:\n\t\t//  cota_array[i][iter] = bound_mult(Parsim.tm[i], Xm, length);\n\t    // and using the  L2 bound\n\t\t  cota_array[i][iter] = branch_length_error_bound_mult(Parsim.tm[i], Par.tm[i]);\n\t\t  out_br <<  br_array[i][iter]  << \" \";\n\t\t  out_brPerc <<  br_arrayPerc[i][iter]  << \" \";\n\n\t\t  out_bound  <<  cota_array[i][iter] << \" \";\n\t\t  out_chi2 << chi2_array[i][iter] << \" \";\n\n\t\t\t}\n         out_chi2 << std::endl;\n\t\t out_bound  <<  std::endl;\n\t\t out_br << std::endl;\n\t\t out_brPerc << std::endl;\n\n\n\n\n    // Saves more data.\n    if (save_data) {\n      logfile << iter << \": \" << distance << \"   \" << KL << std::endl;\n      save_parameters(Par, output_filename + \".est.dat\");\n\n      logdistfile << iter << \": \";\n      logdistfile << parameters_distance_root(Par, Parsim) << \" \";\n      for(int j=0; j < T.nedges; j++) {\n        logdistfile << parameters_distance_edge(Par, Parsim, j) << \" \";\n      }\n      logdistfile << std::endl;\n    }\n\n} // close iter loop here\n\n  // Correct the p-values\n  for(i=0; i < T.nedges; i++) {\n       BH(pval_array[i], qval_array[i]);\n\t//save them\n  }\n\n  if (save_mc_exact) {\n    for(long iter=0; iter < Nrep; iter++) {\n      for(long i=0; i < T.nedges; i++) {\n        out_pvals << pval_array[i][iter] << \"  \";\n        out_pvals_noperm << pval_noperm_array[i][iter] << \"  \";\n        out_qvals << qval_array[i][iter] << \"  \";\n      }\n      out_pvals  << std::endl;\n      out_pvals_noperm << std::endl;\n      out_qvals  << std::endl;\n\n      for(long i=0; i < npars; i++) {\n        out_variances << variances_array[i][iter] << \"  \";\n        out_parsim << parsim_array[i][iter] << \"  \";\n        out_parest << parest_array[i][iter] << \"  \";\n      }\n      out_variances << std::endl;\n      out_parsim << std::endl;\n      out_parest << std::endl;\n    }\n  }\n\n\t// now combine the pvalues\n   for(i=0; i < T.nedges; i++) {\n\tpvals[i] = Fisher_combined_pvalue(pval_array[i]);\n    //using the Zscore it goes like this: pvals[i] = Zscore_combined_pvalue(pval_array[i]);\n\tif (save_mc_exact) {\t   out_qvalsComb <<  pvals[i] << \"  \" ;\n\tout_qvalsCombzscore << Zscore_combined_pvalue(pval_array[i]) << \" \";\n\t}\n  }\n\n  // Close files\n  if (save_data) {\n    logdistfile.close();\n    logfile.close();\n  }\n\nif (save_mc_exact) {\n\tout_chi2.close();\n\tout_bound.close();\n        out_variances.close();\n        out_parest.close();\n        out_parsim.close();\n\tout_br.close();\n\tout_brPerc.close();\n\n\tout_pvals.close();\n        out_qvals.close();\n\tout_qvalsComb.close();\n\tout_qvalsCombzscore.close();\n        out_covmatrix.close();\n\t}\n\n  // Warn if some EM's produced NaN.\n  if (produced_nan.size() > 0) {\n    std::cout << std::endl;\n    std::cout << \"WARNING: Some iterations produced NaN.\" << std::endl;\n    std::list<long>::iterator it;\n    for (it = produced_nan.begin(); it != produced_nan.end(); it++) {\n      std::cout << *it << \", \";\n    }\n    std::cout << std::endl;\n  }\n}\n\n// below we test the fit the fit of the theoretical distribution to the data, i.e. we simulate data with all visible and check it per node,\n// that is what was used to produce the histograms in the paper\n\nvoid parameter_cloud(Tree &T, Model &Mod, long Nrep, long length, double eps, Parameters &Parsim){\n\n  long iter;\n\n  float likel;\n\n\n  Parameters Par;\n  Alignment align;\n  Counts data;\n\n  double eps_pseudo = 0.001;     // Amount added to compute the pseudo-counts.\n\n  // Initialize the parameters for simulation of K81 data for testing\n  Par = create_parameters(T);\n\n  // Obtaining the distribution of estimated parameters with EM\n\n  std::ofstream estpar;\n  estpar.open(\"est-par.dat\", std::ios::out);\n  estpar.precision(15);\n\n  std::vector<double> param;\n  for (iter=0; iter < Nrep; iter++) {\n    random_data(T, Mod, Parsim, length, align);\n    get_counts(align, data);\n    add_pseudocounts(eps_pseudo, data);\n\n    // Runs EM\n    std::tie(likel, iter)= EMalgorithm(T, Mod, Par, data, eps);\n\n    // Choses the best permutation.\n    guess_permutation(T, Mod, Par);\n\n    get_free_param_vector(T, Mod, Par, param);\n\n    for (unsigned long k=0; k < param.size(); k++) {\n      estpar << param[k] << \"  \";\n    }\n    estpar << std::endl;\n  }\n\n}\n", "meta": {"hexsha": "834328d0db922a57140b65cd5a66677b7f674880", "size": 18407, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/parameter_tests.cpp", "max_stars_repo_name": "Algebraicphylogenetics/Empar", "max_stars_repo_head_hexsha": "1c2b4eec4ac0917c65786acf36de4b906d95715c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/parameter_tests.cpp", "max_issues_repo_name": "Algebraicphylogenetics/Empar", "max_issues_repo_head_hexsha": "1c2b4eec4ac0917c65786acf36de4b906d95715c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/parameter_tests.cpp", "max_forks_repo_name": "Algebraicphylogenetics/Empar", "max_forks_repo_head_hexsha": "1c2b4eec4ac0917c65786acf36de4b906d95715c", "max_forks_repo_licenses": ["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.4512, "max_line_length": 198, "alphanum_fraction": 0.6198185473, "num_tokens": 5474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.453713834180235}}
{"text": "#include \"Line2D.h\"\n#include \"Angle.h\"\n#include \"Pose2D.h\"\n#include \"Geometry.h\"\n\n#include <cmath>\n#include <boost/concept_check.hpp>\n#include <limits>\n\n\nusing namespace A2O;\nusing namespace Eigen;\n\nLine2D::Line2D()\n      : _start(0, 0), _extension(1, 0)\n{\n}\n\nLine2D::Line2D(const double& m,\n\t       const double& b)\n      : _start(0, b), _extension(1, m)\n{\n}\n\nLine2D::Line2D(const double& xStart,\n\t       const double& yStart,\n\t       const Angle& alpha,\n\t       const double& length)\n      : _start(xStart, yStart), _extension(alpha.getVector(length))\n{\n  if (_extension(0) == 0 && _extension(1) == 0) {\n    _extension = Vector2d(1, 0);\n  }\n}\n\nLine2D::Line2D(const Eigen::Vector2d& start,\n\t       const Angle& alpha,\n\t       const double& length)\n      : _start(start), _extension(alpha.getVector(length))\n{\n  validate();\n}\n\nLine2D::Line2D(const Vector2d& start,\n\t       const Vector2d& end)\n      : _start(start), _extension(end - start)\n{\n  validate();\n}\n\nLine2D::Line2D(const double& xStart,\n\t       const double& yStart,\n\t       const double& xEnd,\n\t       const double& yEnd)\n      : _start(xStart, yStart), _extension(xEnd - xStart, yEnd - yStart)\n{\n  validate();\n}\n\nLine2D::~Line2D()\n{\n}\n\nvoid Line2D::validate()\n{\n  if (_extension(0) == 0 && _extension(1) == 0) {\n    _extension = Vector2d(0, 1);\n  }\n}\n\nconst Eigen::Vector2d& Line2D::getStart() const\n{\n  return _start;\n}\n\nconst Eigen::Vector2d& Line2D::getExtensionVector() const\n{\n  return _extension;\n}\n\nconst Eigen::Vector2d Line2D::getEnd() const\n{\n  return _start + _extension;\n}\n\nconst Angle Line2D::getAngle() const\n{\n  return Angle::to(_extension);\n}\n\nconst double Line2D::m() const\n{\n  if (_extension(0) == 0) {\n    if (_extension(1) > 0) {\n      return std::numeric_limits<double>::max();\n    } else {\n      return std::numeric_limits<double>::lowest();\n    }\n  }\n  \n  return _extension(1) / _extension(0);\n}\n\nconst double Line2D::b() const\n{\n  if (_extension(0) == 0) {\n    return 0;\n  }\n  \n  return _start(1) - ((_extension(1) / _extension(0)) * _start(0));\n}\n\nconst double Line2D::yValue(const double& x) const\n{\n  if (_extension(0) == 0) {\n    // this line is y-parallel\n    return 0;\n  }\n  \n  return (_extension(1) / _extension(0)) * (x - _start(0)) + _start(1);\n}\n\nconst double Line2D::xValue(const double& y) const\n{\n  if (_extension(1) == 0) {\n    // this line is x-parallel\n    return _start(0);\n  }\n  \n  return (_extension(0) / _extension(1)) * (y - _start(1)) + _start(0);\n}\n\nPose2D Line2D::getClosestPose(const Vector2d& point)\n{\n\n  Angle lineAngle(Angle::to(_extension));\n  Angle pointAngle(Angle::to(point - _start));\n  \n  Angle offsetAngle (pointAngle - lineAngle);\n  double hypotenuse = Geometry::getDistance<double, 2>(point, _start);\n  double factor = cos(offsetAngle.rad()) * hypotenuse;\n  Vector2d closestPoint (_start + _extension / Geometry::getNorm<double, 2>(_extension) * factor);\n  \n  return Pose2D(closestPoint, Angle::to(_extension));\n}\n\n\nstd::vector< Vector2d > Line2D::getTrail(const Vector2d& start, const Vector2d& end)\n{\n  Pose2D poseStart = getClosestPose(start);\n  Pose2D poseEnd = getClosestPose(end);\n  double distance = poseStart.getDistanceTo(poseEnd);\n  Vector2d offset = poseStart.getAngle().getVector(0.1 * distance);\n  Vector2d point = poseStart.getPosition();\n  std::vector<Vector2d> points;\n  int i = 0;\n  do{\n    point += offset;\n    points.push_back(point);\n  } while(++i < 10);\n  return points;\n}\n\nbool Line2D::operator==(const Line2D& other) const\n{\n  return _start == other._start && _extension == other._extension;\n}\n\nbool Line2D::operator!=(const Line2D& other) const\n{\n  return !(*this == other);\n}\n", "meta": {"hexsha": "ef40a74af5a0b507c361d664cfd02b6b96ee4ee3", "size": 3624, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/aadcUser/src/HSOG_Runtime/a2o/utils/geometry/Line2D.cpp", "max_stars_repo_name": "AppliedAutonomyOffenburg/AADC_2015_A2O", "max_stars_repo_head_hexsha": "19a2ac67d743ad23e5a259ca70aed6b3d1f2e3ac", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-09-09T21:39:29.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-09T21:39:29.000Z", "max_issues_repo_path": "src/aadcUser/src/HSOG_Runtime/a2o/utils/geometry/Line2D.cpp", "max_issues_repo_name": "TeamAutonomousCarOffenburg/A2O_2015", "max_issues_repo_head_hexsha": "19a2ac67d743ad23e5a259ca70aed6b3d1f2e3ac", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/aadcUser/src/HSOG_Runtime/a2o/utils/geometry/Line2D.cpp", "max_forks_repo_name": "TeamAutonomousCarOffenburg/A2O_2015", "max_forks_repo_head_hexsha": "19a2ac67d743ad23e5a259ca70aed6b3d1f2e3ac", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-04-05T06:34:08.000Z", "max_forks_repo_forks_event_max_datetime": "2016-04-05T06:34:08.000Z", "avg_line_length": 20.9479768786, "max_line_length": 98, "alphanum_fraction": 0.6481788079, "num_tokens": 1116, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321720225279, "lm_q2_score": 0.6370308013713525, "lm_q1q2_score": 0.45371383130596993}}
{"text": "#include <trajopt_utils/macros.h>\nTRAJOPT_IGNORE_WARNINGS_PUSH\n#include <cstdio>\n#include <gtest/gtest.h>\n#include <Eigen/Core>\n#include <iostream>\n#include <sstream>\n#include <vector>\nTRAJOPT_IGNORE_WARNINGS_POP\n\n#include <trajopt_sco/expr_ops.hpp>\n#include <trajopt_sco/solver_interface.hpp>\n#include <trajopt_sco/solver_utils.hpp>\n#include <trajopt_utils/logging.hpp>\n#include <trajopt_utils/stl_to_string.hpp>\n\nusing namespace sco;\n\nTEST(solver_utils, exprToEigen)\n{\n  int n_vars = 2;\n  std::vector<VarRepPtr> x_info;\n  VarVector x;\n  for (int i = 0; i < n_vars; ++i)\n  {\n    std::stringstream var_name;\n    var_name << \"x_\" << i;\n    VarRepPtr x_el(new VarRep(i, var_name.str(), nullptr));\n    x_info.push_back(x_el);\n    x.push_back(Var(x_el.get()));\n  }\n\n  // x_affine = [3, 2]*x + 1\n  AffExpr x_affine;\n  x_affine.vars = x;\n  x_affine.coeffs = DblVec{ 3, 2 };\n  x_affine.constant = 1;\n\n  std::cout << \"x_affine=  \" << x_affine << std::endl;\n  std::cout << \"expecting A = [3, 2];\" << std::endl << \"          u = [1]\" << std::endl;\n  Eigen::MatrixXd m_A_expected(1, n_vars);\n  m_A_expected << 3, 2;\n  Eigen::VectorXd v_u_expected(1);\n  v_u_expected << -1;\n\n  Eigen::SparseVector<double> v_A;\n  exprToEigen(x_affine, v_A, n_vars);\n  ASSERT_EQ(v_A.size(), m_A_expected.cols());\n  Eigen::VectorXd v_A_d = v_A;\n  Eigen::VectorXd m_A_r = m_A_expected.row(0);\n  EXPECT_TRUE(v_A_d.isApprox(m_A_r)) << \"error converting x_affine\"\n                                     << \" to Eigen::SparseVector. \"\n                                     << \"v_A :\" << std::endl\n                                     << v_A << std::endl;\n\n  Eigen::SparseMatrix<double> m_A;\n  Eigen::VectorXd v_u;\n  AffExprVector x_affine_vector(1, x_affine);\n  exprToEigen(x_affine_vector, m_A, v_u, n_vars);\n  ASSERT_EQ(v_u_expected.size(), v_u.size());\n  EXPECT_TRUE(v_u_expected == v_u) << \"v_u_expected != v_u\" << std::endl << \"v_u:\" << std::endl << v_u << std::endl;\n  EXPECT_EQ(m_A.nonZeros(), 2) << \"m_A.nonZeros() != 2\" << std::endl;\n  ASSERT_EQ(m_A.rows(), m_A_expected.rows());\n  ASSERT_EQ(m_A.cols(), m_A_expected.cols());\n  EXPECT_TRUE(m_A.isApprox(m_A_expected)) << \"error converting x_affine to \"\n                                          << \"Eigen::SparseMatrix. m_A :\" << std::endl\n                                          << m_A << std::endl;\n\n  QuadExpr x_squared = exprSquare(x_affine);\n  std::cout << \"x_squared= \" << x_squared << std::endl;\n  std::cout << \"expecting Q = [9, 6;\" << std::endl\n            << \"               6, 4]\" << std::endl\n            << \"          q = [6, 4]\" << std::endl;\n  Eigen::MatrixXd m_Q_expected(2, 2);\n  m_Q_expected << 9, 6, 6, 4;\n  DblVec v_q_expected{ 6, 4 };\n\n  Eigen::SparseMatrix<double> m_Q;\n  Eigen::VectorXd v_q;\n  exprToEigen(x_squared, m_Q, v_q, n_vars);\n  {\n    Eigen::Map<Eigen::VectorXd, Eigen::Unaligned> v_q_e_eig(v_q_expected.data(), v_q_expected.size());\n    ASSERT_EQ(v_q.size(), v_q_e_eig.size());\n    EXPECT_TRUE(v_q_e_eig.isApprox(v_q)) << \"v_q_expected != v_q\" << std::endl\n                                         << \"v_q:\" << std::endl\n                                         << v_q << std::endl;\n  }\n  EXPECT_TRUE(m_Q.isApprox(m_Q_expected)) << \"error converting x_squared to \"\n                                          << \"Eigen::SparseMatrix. m_Q :\" << std::endl\n                                          << m_Q << std::endl;\n  EXPECT_EQ(m_Q.nonZeros(), 4) << \"m_Q.nonZeros() != 4\" << std::endl;\n\n  exprToEigen(x_squared, m_Q, v_q, n_vars, true);\n  {\n    Eigen::Map<Eigen::VectorXd, Eigen::Unaligned> v_q_e_eig(v_q_expected.data(), v_q_expected.size());\n    EXPECT_TRUE(v_q_e_eig.isApprox(v_q)) << \"v_q_expected != v_q\" << std::endl\n                                         << \"v_q:\" << std::endl\n                                         << v_q << std::endl;\n  }\n  EXPECT_TRUE(m_Q.isApprox(2 * m_Q_expected)) << \"error converting x_squared to\"\n                                              << \" Eigen::SparseMatrix. m_Q :\" << std::endl\n                                              << m_Q << std::endl;\n  EXPECT_EQ(m_Q.nonZeros(), 4) << \"m_Q.nonZeros() != 4\" << std::endl;\n\n  x_affine.coeffs = DblVec{ 0, 2 };\n  std::cout << \"x_affine=  \" << x_affine << std::endl;\n  std::cout << \"expecting A = [0, 2];\" << std::endl;\n  x_squared = exprSquare(x_affine);\n  std::cout << \"x_squared= \" << x_squared << std::endl;\n  std::cout << \"expecting Q = [0, 0;\" << std::endl << \"               0, 4]\" << std::endl;\n  m_Q_expected.setZero();\n  m_Q_expected << 0, 0, 0, 4;\n  exprToEigen(x_squared, m_Q, v_q, n_vars, false, false);\n  EXPECT_TRUE(m_Q.isApprox(m_Q_expected)) << \"error converting x_squared to \"\n                                          << \"Eigen::SparseMatrix. m_Q :\" << std::endl\n                                          << m_Q << std::endl;\n  EXPECT_EQ(m_Q.nonZeros(), 1) << \"m_Q.nonZeros() != 1\" << std::endl;\n\n  exprToEigen(x_squared, m_Q, v_q, n_vars, true, false);\n  EXPECT_TRUE(m_Q.isApprox(2 * m_Q_expected)) << \"error converting x_squared to\"\n                                              << \" Eigen::SparseMatrix. m_Q :\" << std::endl\n                                              << m_Q << std::endl;\n  EXPECT_EQ(m_Q.nonZeros(), 1) << \"m_Q.nonZeros() != 1\" << std::endl;\n\n  exprToEigen(x_squared, m_Q, v_q, n_vars, false, true);\n  EXPECT_TRUE(m_Q.isApprox(m_Q_expected)) << \"error converting x_squared to \"\n                                          << \"Eigen::SparseMatrix. m_Q :\" << std::endl\n                                          << m_Q << std::endl;\n  EXPECT_EQ(m_Q.nonZeros(), 2) << \"m_Q.nonZeros() != 2\" << std::endl;\n\n  exprToEigen(x_squared, m_Q, v_q, n_vars, true, true);\n  EXPECT_TRUE(m_Q.isApprox(2 * m_Q_expected)) << \"error converting x_squared to\"\n                                              << \"Eigen::SparseMatrix. m_Q :\" << std::endl\n                                              << m_Q << std::endl;\n  EXPECT_EQ(m_Q.nonZeros(), 2) << \"m_Q.nonZeros() != 2\" << std::endl;\n}\n\nTEST(solver_utils, eigenToTriplets)\n{\n  Eigen::MatrixXd m_Q(2, 2);\n  m_Q << 9, 0, 6, 4;\n  Eigen::SparseMatrix<double> m_Q_sparse_expected = m_Q.sparseView();\n  IntVec m_Q_i, m_Q_j;\n  DblVec m_Q_ij;\n  eigenToTriplets(m_Q_sparse_expected, m_Q_i, m_Q_j, m_Q_ij);\n  Eigen::SparseMatrix<double> m_Q_sparse(2, 2);\n  tripletsToEigen(m_Q_i, m_Q_j, m_Q_ij, m_Q_sparse);\n  EXPECT_TRUE(m_Q_sparse.isApprox(m_Q)) << \"m_Q != m_Q_sparse when converting \"\n                                        << \"m_Q -> triplets -> m_Q_sparse. m_Q:\" << std::endl\n                                        << m_Q << std::endl;\n  EXPECT_EQ(m_Q_sparse.nonZeros(), 3) << \"m_Q.nonZeros() != 3\" << std::endl;\n}\n\nTEST(solver_utils, eigenToCSC)\n{\n  DblVec P;\n  IntVec rows_i;\n  IntVec cols_p;\n  {\n    /*\n     * M = [ 1, 2, 3,\n     *       1, 0, 9,\n     *       1, 8, 0]\n     */\n    Eigen::MatrixXd M(3, 3);\n    M << 1, 2, 3, 1, 0, 9, 1, 8, 0;\n    Eigen::SparseMatrix<double> Ms = M.sparseView();\n\n    eigenToCSC(Ms, rows_i, cols_p, P);\n\n    EXPECT_TRUE(rows_i.size() == P.size()) << \"rows_i.size() != P.size()\";\n    EXPECT_TRUE((P == DblVec{ 1, 1, 1, 2, 8, 3, 9 })) << \"bad P:\\n\" << CSTR(P);\n    EXPECT_TRUE((rows_i == IntVec{ 0, 1, 2, 0, 2, 0, 1 })) << \"bad rows_i:\\n\" << CSTR(rows_i);\n    EXPECT_TRUE((cols_p == IntVec{ 0, 3, 5, 7 })) << \"cols_p not in \"\n                                                  << \"CRC form:\\n\"\n                                                  << CSTR(cols_p);\n  }\n  {\n    /*\n     * M = [ 0, 2, 0,\n     *       7, 0, 0,\n     *       0, 0, 0]\n     */\n    Eigen::SparseMatrix<double> M(3, 3);\n    M.coeffRef(0, 1) = 2;\n    M.coeffRef(1, 0) = 7;\n\n    eigenToCSC(M, rows_i, cols_p, P);\n\n    EXPECT_TRUE(rows_i.size() == P.size()) << \"rows_i.size() != P.size()\";\n    EXPECT_TRUE((P == DblVec{ 7, 2 })) << \"bad P:\\n\" << CSTR(P);\n    EXPECT_TRUE((rows_i == IntVec{ 1, 0 })) << \"rows_i != data_j:\\n\"\n                                            << CSTR(rows_i) << \" vs\\n\"\n                                            << CSTR((IntVec{ 1, 0 }));\n    EXPECT_TRUE((cols_p == IntVec{ 0, 1, 2, 2 })) << \"cols_p not in \"\n                                                  << \"CRC form:\\n\"\n                                                  << CSTR(cols_p);\n\n    std::vector<long long int> rows_i_ll, cols_p_ll;\n    std::vector<long long int> rows_i_ll_exp{ 1, 0 };\n    std::vector<long long int> cols_p_ll_exp{ 0, 1, 2, 2 };\n\n    eigenToCSC(M, rows_i_ll, cols_p_ll, P);\n    EXPECT_TRUE(rows_i_ll.size() == P.size()) << \"rows_i_ll.size() != P.size()\";\n    EXPECT_TRUE((rows_i_ll == rows_i_ll_exp));\n    EXPECT_TRUE((cols_p_ll == cols_p_ll_exp));\n\n    std::vector<unsigned long long int> rows_i_ull, cols_p_ull;\n    std::vector<unsigned long long int> rows_i_ull_exp{ 1, 0 };\n    std::vector<unsigned long long int> cols_p_ull_exp{ 0, 1, 2, 2 };\n    eigenToCSC(M, rows_i_ull, cols_p_ull, P);\n    EXPECT_TRUE(rows_i_ull.size() == P.size()) << \"rows_i_ll.size() != P.size()\";\n    EXPECT_TRUE((rows_i_ull == rows_i_ull_exp));\n    EXPECT_TRUE((cols_p_ull == cols_p_ull_exp));\n  }\n  {\n    /*\n     * M = [ 0, 0, 0,\n     *       0, 0, 0,\n     *       0, 6, 0]\n     */\n    Eigen::SparseMatrix<double> M(3, 3);\n    M.coeffRef(2, 1) = 6;\n\n    eigenToCSC(M, rows_i, cols_p, P);\n\n    EXPECT_TRUE(rows_i.size() == P.size()) << \"rows_i.size() != P.size()\";\n    EXPECT_TRUE((P == DblVec{ 6 })) << \"bad P:\\n\" << CSTR(P);\n    EXPECT_TRUE((rows_i == IntVec{ 2 })) << \"rows_i != data_j:\\n\" << CSTR(rows_i) << \" vs\\n\" << CSTR((IntVec{ 1, 0 }));\n    EXPECT_TRUE((cols_p == IntVec{ 0, 0, 1, 1 })) << \"cols_p not in \"\n                                                  << \"CRC form:\\n\"\n                                                  << CSTR(cols_p);\n  }\n}\n\nTEST(solver_utils, eigenToCSC_upper_triangular)\n{\n  /*\n   * M = [ 1, 2, 0,\n   *       2, 4, 0,\n   *       0, 0, 9]\n   */\n  Eigen::MatrixXd M(3, 3);\n  M << 1, 2, 0, 2, 4, 0, 0, 0, 9;\n  Eigen::SparseMatrix<double> Ms = M.sparseView();\n\n  DblVec P;\n  IntVec rows_i;\n  IntVec cols_p;\n  eigenToCSC<Eigen::Upper>(Ms, rows_i, cols_p, P);\n\n  EXPECT_TRUE(rows_i.size() == P.size()) << \"rows_i.size() != P.size()\";\n  EXPECT_TRUE((P == DblVec{ 1, 2, 4, 9 })) << \"bad P:\\n\" << CSTR(P);\n  EXPECT_TRUE((rows_i == IntVec{ 0, 0, 1, 2 })) << \"rows_i != expected\"\n                                                << \":\\n\"\n                                                << CSTR(rows_i) << \" vs\\n\"\n                                                << CSTR((IntVec{ 0, 0, 1, 2 }));\n  EXPECT_TRUE((cols_p == IntVec{ 0, 1, 3, 4 })) << \"cols_p not in \"\n                                                << \"CRC form:\\n\"\n                                                << CSTR(cols_p);\n}\n", "meta": {"hexsha": "084648dd37ada6d48adcb67ea536a2b66c0f8be6", "size": 10615, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "moveit_planners/trajopt/trajopt_sco/test/solver-utils-unit.cpp", "max_stars_repo_name": "adam-vonderviszt/moveit", "max_stars_repo_head_hexsha": "b18b8c66963907aa6d03cbee4450fc3d6e740162", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "moveit_planners/trajopt/trajopt_sco/test/solver-utils-unit.cpp", "max_issues_repo_name": "adam-vonderviszt/moveit", "max_issues_repo_head_hexsha": "b18b8c66963907aa6d03cbee4450fc3d6e740162", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "moveit_planners/trajopt/trajopt_sco/test/solver-utils-unit.cpp", "max_forks_repo_name": "adam-vonderviszt/moveit", "max_forks_repo_head_hexsha": "b18b8c66963907aa6d03cbee4450fc3d6e740162", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.5152671756, "max_line_length": 119, "alphanum_fraction": 0.5126707489, "num_tokens": 3290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321720225278, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.4537138263979998}}
{"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\u00e4nkt), 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#define MTL_WITH_DEVELOPMENT\n#define MTL_VERBOSE_TEST\n\n#include <string>\n#include <iostream>\n\n#include <boost/numeric/mtl/mtl.hpp>\n#include <boost/numeric/mtl/matrix/sparse_banded.hpp>\n\n\ntemplate <typename Matrix>\nvoid laplacian_test(Matrix& A, unsigned dim1, unsigned dim2, const char* name)\n{\n    mtl::io::tout << \"\\n\" << name << \"\\n\";\n    laplacian_setup(A, dim1, dim2);\n    mtl::io::tout << \"Laplacian A:\\n\" << A << std::endl;\n    if (dim1 > 1 && dim2 > 1) {\n\ttypename Matrix::value_type four(4.0), minus_one(-1.0), zero(0.0);\n\tMTL_THROW_IF(A[0][0] != four, mtl::runtime_error(\"wrong diagonal\"));\n\tMTL_THROW_IF(A[0][1] != minus_one, mtl::runtime_error(\"wrong east neighbor\"));\n\tMTL_THROW_IF(A[0][dim2] != minus_one, mtl::runtime_error(\"wrong south neighbor\"));\n\tMTL_THROW_IF(dim2 > 2 && A[0][2] != zero, mtl::runtime_error(\"wrong zero-element\"));\n\tMTL_THROW_IF(A[1][0] != minus_one, mtl::runtime_error(\"wrong west neighbor\"));\n\tMTL_THROW_IF(A[dim2][0] != minus_one, mtl::runtime_error(\"wrong north neighbor\"));\n\tMTL_THROW_IF(dim2 > 2 && A[2][0] != zero, mtl::runtime_error(\"wrong zero-element\"));\n    }\n}\n\ntemplate <typename Matrix>\nvoid rectangle_test(Matrix& A, const char* name)\n{\n    {\n\tmtl::mat::inserter<Matrix> ins(A);\n\tint i= 1;\n\tunsigned nc= num_cols(A);\n\tfor (unsigned r= 0; r < num_rows(A); r++) {\n\t    if (r < nc - 4) ins(r, r + 4) << i++;\n\t    if (r < nc) ins(r, r) << i++;\n\t    if (r >= 2 && r < nc + 2) ins(r, r - 2) << i++;\n\t    if (r >= 4 && r < nc + 4) ins[r][r - 4] << i++;\n\t}\n    }\n    mtl::io::tout << name << \": A=\\n\" << A << '\\n';\n}\n\ntemplate <typename Matrix, typename Tag>\nvoid two_d_iteration(const Matrix & A, Tag)\n{\n    namespace traits = mtl::traits;\n\n    typename traits::row<Matrix>::type                                 row(A); \n    typename traits::col<Matrix>::type                                 col(A); \n    typename traits::const_value<Matrix>::type                         value(A); \n    typedef typename traits::range_generator<Tag, Matrix>::type        cursor_type;\n    for (cursor_type cursor = mtl::begin<Tag>(A), cend = mtl::end<Tag>(A); cursor != cend; ++cursor) {\n\ttypedef mtl::tag::nz     inner_tag;\n\tmtl::io::tout << \"---\\n\";\n\ttypedef typename traits::range_generator<inner_tag, cursor_type>::type icursor_type;\n\tfor (icursor_type icursor = mtl::begin<inner_tag>(cursor), icend = mtl::end<inner_tag>(cursor); icursor != icend; ++icursor)\n\t    mtl::io::tout << \"A[\" << row(*icursor) << \", \" << col(*icursor) << \"] = \" << value(*icursor) << '\\n';\n    }\n    mtl::io::tout << \"===\\n\\n\";\n} \n\ntemplate <typename Matrix>\nvoid mat_vec_mult_test(const Matrix& A, const char* name)\n{\n    typedef typename Matrix::value_type  value_type;\n    mtl::io::tout << name << \" \" << num_rows(A) << \" by \" << num_cols(A) << '\\n' << A;\n\n    mtl::dense_vector<value_type> v, w(num_cols(A), 3.0), v2;\n    v= A * w;\n    mtl::io::tout << \"A * v =    \" << v << '\\n';\n\n    mtl::compressed2D<value_type> B(A);\n    v2= B * w;\n    mtl::io::tout << \"Should be: \" << v2 << \"\\n\\n\";\n    v2-= v;\n    MTL_THROW_IF(two_norm(v2) > 0.001, \n\t\t mtl::runtime_error(\"wrong result for sparse banded times vector\"));\n}\n\nint main(int, char**)\n{\n    using namespace mtl;\n#ifdef MTL_WITH_DEVELOPMENT\n    unsigned dim1= 3, dim2= 4;\n    mat::sparse_banded<double>  dr, dr2(6, 11), dr3(11, 6), dr4(6, 5);\n    \n    laplacian_test(dr, dim1, dim2, \"Dense row major\");\n    rectangle_test(dr2, \"Dense row major\");\n    rectangle_test(dr3, \"Dense row major\");\n    rectangle_test(dr4, \"Dense row major\");\n\n    mat::compressed2D<double> C;\n    laplacian_setup(C, dim1, dim2);\n\n    mat::sparse_banded<double>  D;\n    D= C;\n    mtl::io::tout << \"D is\\n\" << D << '\\n';\n\n    two_d_iteration(D, mtl::tag::row());\n\n    mat::compressed2D<double> E;\n    E= D;\n    mtl::io::tout << \"E is\\n\" << E << '\\n';\n\n    mat::sparse_banded<double>  dr5(5, 5), dr6(5, 5);\n    {\n\tmtl::mat::inserter<mat::sparse_banded<double> > ins5(dr5), ins6(dr6);\t\n\tins5[2][0] << 1; ins5[3][1] << 2; ins5[4][2] << 3; ins5[4][0] << 4;\n\tins6[0][2] << 1; ins6[1][3] << 2; ins6[2][4] << 3; ins6[0][4] << 4;\n    }\n\n    mat_vec_mult_test(dr2, \"Dense row major\");\n    mat_vec_mult_test(dr3, \"Dense row major\");\n    mat_vec_mult_test(dr4, \"Dense row major\");\n    mat_vec_mult_test(dr5, \"Dense row major\");\n    mat_vec_mult_test(dr6, \"Dense row major\");\n\n    mat_vec_mult_test(dr, \"Dense row major\");\n#endif\n    \n\n\n    return 0;\n}\n \n", "meta": {"hexsha": "a0817b75317a0bfddccfbf298d408975f45dc459", "size": 4823, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/sparse_banded_matrix_test.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/mtl/test/sparse_banded_matrix_test.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/mtl/test/sparse_banded_matrix_test.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 34.2056737589, "max_line_length": 125, "alphanum_fraction": 0.6029442256, "num_tokens": 1581, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6370307806984444, "lm_q2_score": 0.712232184238947, "lm_q1q2_score": 0.4537138243642947}}
{"text": "/// @file raster_example2.cc\n/// @brief raster example\n/// @author Jeff Perry <jeffsp@gmail.com>\n/// @version 1.0\n/// @date 2013-01-14\n\n#include \"jack_rabbit/jack_rabbit.h\"\n#include <algorithm>\n#include <boost/static_assert.hpp>\n#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <string>\n#include <vector>\n\nusing namespace jack_rabbit;\nusing namespace std;\n\n// Our video display mode dimensions.\nconst size_t WIDTH = 320;\nconst size_t HEIGHT = 240;\n\n// An RGB pixel\nstruct Pixel\n{\n    char rgb[3];\n};\n\n// Imagine that some sort of a display class, like this one,\n// provides access to the video display buffer.  We can\n// interface with the video buffer using a raster if we\n// utilize a simple custom allocator, defined below.\ntemplate <\n    size_t W,\n    size_t H\n>\nclass Display\n{\n    public:\n    Display () : p_ (W * H) { }\n    Pixel *Pixels () { return &p_[0]; }\n    size_t Width () const { return W; }\n    size_t Height () const { return H; }\n    private:\n    vector<Pixel> p_;\n};\nDisplay<WIDTH,HEIGHT> display;\n\n// Our custom allocator does not allocate any memory, but\n// instead it returns an address to the video display\n// memory.  The container that uses this allocator might not\n// ask for *exactly* the number of bytes specified in the\n// raster constructor.  If this happens, allocate will fail.\ntemplate<class T>\nclass Alloc : public allocator<T>\n{\n    public:\n    T *allocate (size_t n, const void *hint = 0)\n    {\n        if (n != display.Width () * display.Height ())\n            throw runtime_error (\"allocate failed\");\n        return display.Pixels ();\n    }\n    void deallocate (Pixel *p, size_t n) { }\n    private:\n};\n\n// Convert from YUV colorspace to RGB colorspace\ntemplate<typename Ty>\ninline Ty YUVR (Ty y, Ty  , Ty v) { return  y + 1.14 * v; }\ntemplate<typename Ty>\ninline Ty YUVG (Ty y, Ty u, Ty v) { return  y - 0.40 * u - 0.58 * v; }\ntemplate<typename Ty>\ninline Ty YUVB (Ty y, Ty u, Ty  ) { return  y + 2.03 * u; }\ntemplate<typename Ty>\ninline Ty CLIP (Ty x) { return x > 1.0 ? 1.0 : (x < 0.0 ? 0.0 : x); }\n\n// Our subscript function object writes a chromaticity\n// diagram of YUV values.  The diagram is white in the\n// center and smoothly changes color from green to red, then\n// purple, blue, and back to green as it goes around the\n// edge of the diagram.\ntemplate<typename T>\nstruct Func\n{\n    Func (size_t /*r*/, size_t /*c*/) :\n        MAXD (sqrt (static_cast<double> (CX * CX + CY * CY)))\n    { }\n    T operator() (size_t r, size_t c)\n    {\n        // Luminance is determined by distance from center\n        double dx = static_cast<double> (c) - CX;\n        double dy = static_cast<double> (r) - CY;\n        double l = 1.0 - sqrt (dx * dx + dy * dy) / MAXD;\n        // Color is determined by coordinate\n        double v = static_cast<double> (c) / W - 0.5;\n        double u = static_cast<double> (r) / H - 0.5;\n        Pixel p;\n        // Convert YUV to RGB\n        p.rgb[0] = static_cast<char> (CLIP (YUVR (l, u, v)) * 255);\n        p.rgb[1] = static_cast<char> (CLIP (YUVG (l, u, v)) * 255);\n        p.rgb[2] = static_cast<char> (CLIP (YUVB (l, u, v)) * 255);\n        return p;\n    }\n    static const int W = WIDTH;\n    static const int H = HEIGHT;\n    static const int CX = (W - 1) / 2;\n    static const int CY = (H - 1) / 2;\n    const double MAXD;\n};\n\n// PPM file writer helper\ntemplate<class T>\nvoid WritePPM (const T &m, ofstream &ofs)\n{\n    // Write a ppm header\n    ofs << \"P6\\n\"\n        << \"# Raster Example\\n\"\n        << m.cols () << ' ' << m.rows () << '\\n'\n        << \"255\\n\";\n\n    // Write the ppm pixels\n    const std::streamsize sz =\n        static_cast<std::streamsize> (m.size () * 3);\n    ofs.write (reinterpret_cast<const char *> (&m[0]), sz);\n}\n\nint main ()\n{\n    try\n    {\n        BOOST_STATIC_ASSERT (sizeof (Pixel) == 3);\n\n        // Access the display through a raster\n        raster<Pixel> pixels (display.Height (), display.Width (), Pixel (), Alloc<Pixel> ());\n\n        // Note that functor expects rows X cols\n        subscript_generator<Pixel,Func> f (display.Height (), display.Width ());\n\n        // Make a colorful display\n        generate (pixels.begin (), pixels.end (), f);\n\n        // Save the image to a file\n        const string fn (\"raster_example2.ppm\");\n        clog << \"Writing image to \" << fn << \"...\" << endl;\n\n        ofstream ofs (fn.c_str ());\n        if (!ofs)\n            throw std::runtime_error (\"Could not open file for writing\");\n\n        WritePPM (pixels, ofs);\n\n        return 0;\n    }\n    catch (const exception &e)\n    {\n        cerr << e.what () << endl;\n        return -1;\n    }\n}\n", "meta": {"hexsha": "5ad8b98c19e2e87ec19b074a7773ba3660ae3c68", "size": 4597, "ext": "cc", "lang": "C++", "max_stars_repo_path": "jsp/rcm_denoising/jack_rabbit/examples/raster_example2.cc", "max_stars_repo_name": "jeffsp/kaggle_denoising", "max_stars_repo_head_hexsha": "ad0e86a34c8c0c98c95e3ec3fe791a6b75154a27", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-06-04T14:34:01.000Z", "max_stars_repo_stars_event_max_datetime": "2015-06-04T14:34:01.000Z", "max_issues_repo_path": "jsp/rcm_denoising/jack_rabbit/examples/raster_example2.cc", "max_issues_repo_name": "jeffsp/kaggle_denoising", "max_issues_repo_head_hexsha": "ad0e86a34c8c0c98c95e3ec3fe791a6b75154a27", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "jsp/rcm_denoising/jack_rabbit/examples/raster_example2.cc", "max_forks_repo_name": "jeffsp/kaggle_denoising", "max_forks_repo_head_hexsha": "ad0e86a34c8c0c98c95e3ec3fe791a6b75154a27", "max_forks_repo_licenses": ["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.5527950311, "max_line_length": 94, "alphanum_fraction": 0.6012616924, "num_tokens": 1284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.4537138243642947}}
{"text": "// MIT License\n//\n// MEII - MAHI Exo-II Library\n// Copyright (c) 2020 Mechatronics and Haptic Interfaces Lab - Rice 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// Author(s): Craig McDonald (craig.g.mcdonald@gmail.com)\n\n#pragma once\n\n#include <vector>\n#include <Mahi/Util/Math/Integrator.hpp>\n#include <Mahi/Util/Timing/Time.hpp>\n#include <Mahi/Robo/Trajectories/Trajectory.hpp>\n#include <Mahi/Robo/Trajectories/WayPoint.hpp>\n#include <Eigen/Dense>\n\nnamespace mahi {\nnamespace robo {\n\n    class DynamicMotionPrimitive {\n\n    public:\n\n\t\t/// Constructor without nonlinear function\n\t\tDynamicMotionPrimitive(const mahi::util::Time &sample_period, const WayPoint &start, const WayPoint &goal, double gamma = 25.0 / 3.0);\n\n\t\t/// Returns the trajectory generated by the DMP\n        const Trajectory& trajectory();\n\n\t\t/// Updates the trajectory of the DMP based on the new value of theta\n\t\tconst Trajectory& update(const std::vector<double> &theta);\n\n\t\t/// Clears the DMP memory\n        void clear();\n\n\t\t/// Sets the start point and regenerates the trajectory. Returns true if successful.\n\t\tbool set_start(const WayPoint &start);\n\n\t\t/// Sets the goal point and regenerates the trajectory. Returns true if successful.\n\t\tbool set_goal(const WayPoint &goal);\n\n\t\t/// Sets the start point and goal point and regenerates the trajectory. Returns true if successful.\n\t\tbool set_endpoints(const WayPoint &start, const WayPoint &goal);\n\n\t\t/// Sets the interp_method and max_diff properties of the trajectory.\n\t\tvoid set_trajectory_params(Trajectory::Interp interp_method = Trajectory::Interp::Linear, const std::vector<double> &max_diff = { mahi::util::INF });\n\n\t\t/// Returns the value of the parameter gamma\n\t\tdouble get_gamma() const;\n\n\t\t/// Returns the value of the parameter tau\n\t\tdouble get_tau() const;\n\n    private:\n\n\t\t/// Checks that input parameters start, goal, K, and D all have dimensions that are consistent\n        bool check_param_dim();\n\n\t\t/// Sets the parameter tau based on given waypoints and generates a vector of waypoint times for the trajectory\n\t\tvoid set_timing_parameters();\n\n\t\t/// Generate trajectory from given parameters\n\t\tvoid generate_trajectory();\n\n\n    private:\n        \n\t\tmahi::util::Time Ts_; // sample period\n        WayPoint q_0_; // starting point\n\t\tWayPoint g_; // goal point\n        Eigen::MatrixXd K_; // stiffness matrix\n        Eigen::MatrixXd D_; // damping matrix\n\t\t\n\t\tdouble gamma_; // rate parameter for decay of nonlinear vector field\n        double tau_; // temporal scaling factor ensuring arrival at the goal\n        double s_; // phase variable that monotonically decreases from one to zero\n\t\t\n        std::size_t path_dim_; // dimensionality of the trajectory\n        std::size_t path_size_; // number of waypoints in the trajectory\n        std::vector<double> times_; // vector of times associated with trajectory waypoints\n\t\tstd::size_t current_time_idx_; // index for tracking generation of trajectory\n\t\tstd::vector<mahi::util::Integrator> integrator_; // vector of integrators for integrating state equations\n        \n        Eigen::VectorXd q_0_mat_; // matrix for storing starting point position\n\t\tEigen::VectorXd g_mat_; // matrix for storing goal point position\n        Eigen::VectorXd q_mat_; // matrix for storing current states\n        Eigen::VectorXd q_dot_mat_; // matrix for storing current first time derivative of states\n\t\tEigen::VectorXd q_ddot_mat_; // matrix for storing current second time derivative of states\n\t\tEigen::VectorXd theta_mat_; // matrix for storing current feature weighting vector\n\n        Trajectory trajectory_; // trajectory generated upon construction or update of feature weighting vector theta\n\n    };\n\n}  // namespace robo\n}  // namespace mahi\n", "meta": {"hexsha": "a737b302a7c400731f10683031ab49598eca54aa", "size": 4279, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/Mahi/Robo/Trajectories/DynamicMotionPrimitive.hpp", "max_stars_repo_name": "chip5441/mahi-robo", "max_stars_repo_head_hexsha": "2ebf10c38ce0a73ce870fadc53f4ae8f73d0d1a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-07T13:40:28.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-07T13:40:28.000Z", "max_issues_repo_path": "include/Mahi/Robo/Trajectories/DynamicMotionPrimitive.hpp", "max_issues_repo_name": "chip5441/mahi-robo", "max_issues_repo_head_hexsha": "2ebf10c38ce0a73ce870fadc53f4ae8f73d0d1a4", "max_issues_repo_licenses": ["MIT"], "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/Mahi/Robo/Trajectories/DynamicMotionPrimitive.hpp", "max_forks_repo_name": "chip5441/mahi-robo", "max_forks_repo_head_hexsha": "2ebf10c38ce0a73ce870fadc53f4ae8f73d0d1a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-21T09:44:36.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-21T09:44:36.000Z", "avg_line_length": 39.9906542056, "max_line_length": 151, "alphanum_fraction": 0.7331152138, "num_tokens": 963, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.45371382436429464}}
{"text": "#define BOOST_TEST_MODULE ea_solver_unit_tests\n\n#include <boost/test/included/unit_test.hpp>\n#include <armadillo>\n#include \"../src/numerical/evolutionary_algorithm/ea_solver.h\"\n#include \"test_utils.cpp\"\n#include \"../src/logging/easylogging++.h\"\n\nINITIALIZE_EASYLOGGINGPP\n\nusing namespace arma;\n\nmat signals = create_signals();\nauto solver = EASolver(SIGNALS, 200, 200, 0.0001, 100, 50);\n\nBOOST_AUTO_TEST_CASE(good_initial_guess_should_converge_quickly)\n{\n    mat weights = {1, 1, 2};\n    mat guess = {0.5, 1.5, 2.1};\n    solver.set_initial_guess(guess);\n    mat signal = sum_signal(weights, signals);\n    mat result = solver.solve(signal);\n    BOOST_CHECK(is_equal(weights, result, 0.1));\n}\n\nBOOST_AUTO_TEST_CASE(bad_initial_guess_should_not_converge)\n{\n    mat weights = {1, 1, 2};\n    mat guess = {-50000, 50000, 500};\n    solver.set_initial_guess(guess);\n    mat signal = sum_signal(weights, signals);\n    mat result = solver.solve(signal);\n    BOOST_CHECK(!is_equal(weights, result, 0.1));       // Note: !is_equal = not equal\n}", "meta": {"hexsha": "7b2a09dfa8a04e78d8c36247da652bb2fec2bb09", "size": 1032, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/set_initial_solution_test.cpp", "max_stars_repo_name": "omyllymaki/math", "max_stars_repo_head_hexsha": "05c44762aae43268fa965104c19ba86c4284c549", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-11-04T03:43:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-05T09:12:24.000Z", "max_issues_repo_path": "tests/set_initial_solution_test.cpp", "max_issues_repo_name": "omyllymaki/math", "max_issues_repo_head_hexsha": "05c44762aae43268fa965104c19ba86c4284c549", "max_issues_repo_licenses": ["MIT"], "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/set_initial_solution_test.cpp", "max_forks_repo_name": "omyllymaki/math", "max_forks_repo_head_hexsha": "05c44762aae43268fa965104c19ba86c4284c549", "max_forks_repo_licenses": ["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.3529411765, "max_line_length": 86, "alphanum_fraction": 0.7209302326, "num_tokens": 287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289836, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4536772684568666}}
{"text": "\n\n#ifndef __MOTIONNLP_HPP__\n#define __MOTIONNLP_HPP__\n\n#include \"IpTNLP.hpp\"\n#include <math.h>\n#include <Eigen/Dense>\n#include <iostream>\n\n#include \"motion_planner/Agent.hpp\"\n#include <motion_planner/NumericalIntegrationConstraints.hpp>\n\nusing namespace Ipopt;\n\nclass MotionNLP: public TNLP\n{\n\n\npublic:\n\n  Agent* p_agent;\n\n  /** default constructor */\n  MotionNLP();\n  MotionNLP(Agent* p_agent);\n\n  /** default destructor */\n  virtual ~MotionNLP();\n\n     /**@name Overloaded from TNLP */\n     //@{\n     /** Method to return some info about the nlp */\n     virtual bool get_nlp_info(\n        Index&          n,\n        Index&          m,\n        Index&          nnz_jac_g,\n        Index&          nnz_h_lag,\n        IndexStyleEnum& index_style\n     );\n\n     /** Method to return the bounds for my problem */\n     virtual bool get_bounds_info(\n        Index   n,\n        Number* x_l,\n        Number* x_u,\n        Index   m,\n        Number* g_l,\n        Number* g_u\n     );\n\n     /** Method to return the starting point for the algorithm */\n     virtual bool get_starting_point(\n        Index   n,\n        bool    init_x,\n        Number* x,\n        bool    init_z,\n        Number* z_L,\n        Number* z_U,\n        Index   m,\n        bool    init_lambda,\n        Number* lambda\n     );\n\n     /** Method to return the objective value */\n     virtual bool eval_f(\n        Index         n,\n        const Number* x,\n        bool          new_x,\n        Number&       obj_value\n     );\n\n     /** Method to return the gradient of the objective */\n     virtual bool eval_grad_f(\n        Index         n,\n        const Number* x,\n        bool          new_x,\n        Number*       grad_f\n     );\n\n     /** Method to return the constraint residuals */\n     virtual bool eval_g(\n        Index         n,\n        const Number* x,\n        bool          new_x,\n        Index         m,\n        Number*       g\n     );\n\n     /** Method to return:\n      *   1) The structure of the Jacobian (if \"values\" is NULL)\n      *   2) The values of the Jacobian (if \"values\" is not NULL)\n      */\n     virtual bool eval_jac_g(\n        Index         n,\n        const Number* x,\n        bool          new_x,\n        Index         m,\n        Index         nele_jac,\n        Index*        iRow,\n        Index*        jCol,\n        Number*       values\n     );\n\n     /** Method to return:\n      *   1) The structure of the Hessian of the Lagrangian (if \"values\" is NULL)\n      *   2) The values of the Hessian of the Lagrangian (if \"values\" is not NULL)\n      */\n     virtual bool eval_h(\n        Index         n,\n        const Number* x,\n        bool          new_x,\n        Number        obj_factor,\n        Index         m,\n        const Number* lambda,\n        bool          new_lambda,\n        Index         nele_hess,\n        Index*        iRow,\n        Index*        jCol,\n        Number*       values\n     );\n\n     /** This method is called when the algorithm is complete so the TNLP can store/write the solution */\n     virtual void finalize_solution(\n        SolverReturn               status,\n        Index                      n,\n        const Number*              x,\n        const Number*              z_L,\n        const Number*              z_U,\n        Index                      m,\n        const Number*              g,\n        const Number*              lambda,\n        Number                     obj_value,\n        const IpoptData*           ip_data,\n        IpoptCalculatedQuantities* ip_cq\n     );\n     //@}\n     double getQuadraticCost(const Eigen::Vector3d & final_state,\n                                                         const Eigen::Vector3d & target,\n                                                         Eigen::Vector3d & gradient_f);\n  private:\n     /**@name Methods to block default compiler methods.\n      *\n      * The compiler automatically generates the following three methods.\n      *  Since the default compiler implementation is generally not what\n      *  you want (for all but the most simple classes), we usually\n      *  put the declarations of these methods in the private section\n      *  and never implement them. This prevents the compiler from\n      *  implementing an incorrect \"default\" behavior without us\n      *  knowing. (See Scott Meyers book, \"Effective C++\")\n      */\n     //@{\n     MotionNLP(\n        const MotionNLP&\n     );\n\n     MotionNLP& operator=(\n        const MotionNLP&\n     );\n     //@}\n     NumericalIntegrationConstraints integration_constr;\n\n  };\n\n  #endif\n", "meta": {"hexsha": "dc4759892f8f47605b17dfdeb7c765fd400bc2c9", "size": 4503, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/legged_motion_planner/MotionNLP.hpp", "max_stars_repo_name": "despargy/legged_motion_planner", "max_stars_repo_head_hexsha": "ffd92a9a19d6dfc7a289355f519cea46f8dcd7ff", "max_stars_repo_licenses": ["MIT"], "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/legged_motion_planner/MotionNLP.hpp", "max_issues_repo_name": "despargy/legged_motion_planner", "max_issues_repo_head_hexsha": "ffd92a9a19d6dfc7a289355f519cea46f8dcd7ff", "max_issues_repo_licenses": ["MIT"], "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/legged_motion_planner/MotionNLP.hpp", "max_forks_repo_name": "despargy/legged_motion_planner", "max_forks_repo_head_hexsha": "ffd92a9a19d6dfc7a289355f519cea46f8dcd7ff", "max_forks_repo_licenses": ["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.1265060241, "max_line_length": 105, "alphanum_fraction": 0.5196535643, "num_tokens": 1005, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289835, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.4536772684568666}}
{"text": "/*************************************************\n * @Description: file content\n * @Author: yuanquan\n * @Email: yuanquan2011@qq.com\n * @Date: 2021-05-17 21:20:13\n * @LastEditors: yuanquan\n * @LastEditTime: 2021-07-24 12:20:47\n * @copyright: Copyright (c) yuanquan\n *************************************************/\n#include <iostream>\n#include <vector>\n#include <set>\n#include <string>\n#include <gtest/gtest.h>\n#include <boost/array.hpp>\n#include <tuple>\n\nusing namespace std;\nusing namespace boost;\nusing namespace testing;\n\nint removeElement(vector<int>& nums, int val) {\n\tint len = 0;\n\tfor(int i=0; i < nums.size(); ++i)\n\t{\n\t\tif(nums[i] != val)\n\t\t{\n\t\t\tnums[len] = nums[i];\n\t\t\t++len;\n\t\t}\n\t}\n\treturn len;\n}\n\nTEST(removeDuplicatesTest, test)\n{\n\tusing TestData = tuple<vector<int>, int, vector<int>>;\n\tvector<TestData> datas{\n\t\tmake_tuple(vector<int>{3,2,2,3}, 3, vector<int>{2, 2}),\n\t\tmake_tuple(vector<int>{0, 1, 2, 2, 3, 0, 4, 2}, 2, vector<int>{0, 1, 3, 0, 4}),\n\n\t};\n\tfor(auto& dat : datas)\n\t{\n\t\tauto& nums = get<0>(dat);\n\t\tauto& val = get<1>(dat);\n\t\tauto& result = get<2>(dat);\n\t\tnums.resize(removeElement(nums, val));\n\t\tsort(result.begin(), result.end());\n\t\tsort(nums.begin(), nums.end());\n\t\tEXPECT_EQ(result, nums);\n\t}\n}\n\n", "meta": {"hexsha": "ba40755d57a07ee9a7229db7592d668d3104604a", "size": 1230, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "solved/27_remoteElement.cpp", "max_stars_repo_name": "ysdg/Leetcode", "max_stars_repo_head_hexsha": "772245ba8f6aff92d3ce13a3d27c0a4f62162354", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "solved/27_remoteElement.cpp", "max_issues_repo_name": "ysdg/Leetcode", "max_issues_repo_head_hexsha": "772245ba8f6aff92d3ce13a3d27c0a4f62162354", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "solved/27_remoteElement.cpp", "max_forks_repo_name": "ysdg/Leetcode", "max_forks_repo_head_hexsha": "772245ba8f6aff92d3ce13a3d27c0a4f62162354", "max_forks_repo_licenses": ["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.3636363636, "max_line_length": 81, "alphanum_fraction": 0.5829268293, "num_tokens": 379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.7606506581031359, "lm_q1q2_score": 0.45367726522071133}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// 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_TAIL_MEAN_HPP_DE_01_01_2006\n#define BOOST_ACCUMULATORS_STATISTICS_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/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/statistics_fwd.hpp>\n#include <boost/accumulators/statistics/count.hpp>\n#include <boost/accumulators/statistics/tail.hpp>\n#include <boost/accumulators/statistics/tail_quantile.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_tail_mean_impl\n    //\n    /**\n        @brief Estimation of the coherent tail mean based on order statistics (for both left and right tails)\n\n        The coherent tail mean \\f$\\widehat{CTM}_{n,\\alpha}(X)\\f$ is equal to the non-coherent tail mean \\f$\\widehat{NCTM}_{n,\\alpha}(X)\\f$\n        plus a correction term that ensures coherence in case of non-continuous distributions.\n\n        \\f[\n            \\widehat{CTM}_{n,\\alpha}^{\\mathrm{right}}(X) = \\widehat{NCTM}_{n,\\alpha}^{\\mathrm{right}}(X) +\n            \\frac{1}{\\lceil n(1-\\alpha)\\rceil}\\hat{q}_{n,\\alpha}(X)\\left(1 - \\alpha - \\frac{1}{n}\\lceil n(1-\\alpha)\\rceil \\right)\n        \\f]\n\n        \\f[\n            \\widehat{CTM}_{n,\\alpha}^{\\mathrm{left}}(X) = \\widehat{NCTM}_{n,\\alpha}^{\\mathrm{left}}(X) +\n            \\frac{1}{\\lceil n\\alpha\\rceil}\\hat{q}_{n,\\alpha}(X)\\left(\\alpha - \\frac{1}{n}\\lceil n\\alpha\\rceil \\right)\n        \\f]\n    */\n    template<typename Sample, typename LeftRight>\n    struct coherent_tail_mean_impl\n      : accumulator_base\n    {\n        typedef typename numeric::functional::fdiv<Sample, std::size_t>::result_type float_type;\n        // for boost::result_of\n        typedef float_type result_type;\n\n        coherent_tail_mean_impl(dont_care) {}\n\n        template<typename Args>\n        result_type result(Args const &args) const\n        {\n            std::size_t cnt = count(args);\n\n            std::size_t n = static_cast<std::size_t>(\n                std::ceil(\n                    cnt * ( ( is_same<LeftRight, left>::value ) ? args[quantile_probability] : 1. - args[quantile_probability] )\n                )\n            );\n\n            extractor<tag::non_coherent_tail_mean<LeftRight> > const some_non_coherent_tail_mean = {};\n\n            return some_non_coherent_tail_mean(args)\n                 + numeric::fdiv(quantile(args), n)\n                 * (\n                     ( is_same<LeftRight, left>::value ) ? args[quantile_probability] : 1. - args[quantile_probability]\n                     - numeric::fdiv(n, count(args))\n                   );\n        }\n        \n        // serialization is done by accumulators it depends on\n        template<class Archive>\n        void serialize(Archive & ar, const unsigned int file_version) {}\n    };\n\n    ///////////////////////////////////////////////////////////////////////////////\n    // non_coherent_tail_mean_impl\n    //\n    /**\n        @brief Estimation of the (non-coherent) tail mean based on order statistics (for both left and right tails)\n\n        An estimation of the non-coherent tail mean \\f$\\widehat{NCTM}_{n,\\alpha}(X)\\f$ is given by the mean of the\n        \\f$\\lceil n\\alpha\\rceil\\f$ smallest samples (left tail) or the mean of the  \\f$\\lceil n(1-\\alpha)\\rceil\\f$\n        largest samples (right tail), \\f$n\\f$ being the total number of samples and \\f$\\alpha\\f$ the quantile level:\n\n        \\f[\n            \\widehat{NCTM}_{n,\\alpha}^{\\mathrm{right}}(X) = \\frac{1}{\\lceil n(1-\\alpha)\\rceil} \\sum_{i=\\lceil \\alpha n \\rceil}^n X_{i:n}\n        \\f]\n\n        \\f[\n            \\widehat{NCTM}_{n,\\alpha}^{\\mathrm{left}}(X) = \\frac{1}{\\lceil n\\alpha\\rceil} \\sum_{i=1}^{\\lceil \\alpha n \\rceil} X_{i:n}\n        \\f]\n\n        It thus requires the caching of at least the \\f$\\lceil n\\alpha\\rceil\\f$ smallest or the \\f$\\lceil n(1-\\alpha)\\rceil\\f$\n        largest samples.\n\n        @param quantile_probability\n    */\n    template<typename Sample, typename LeftRight>\n    struct non_coherent_tail_mean_impl\n      : accumulator_base\n    {\n        typedef typename numeric::functional::fdiv<Sample, std::size_t>::result_type float_type;\n        // for boost::result_of\n        typedef float_type result_type;\n\n        non_coherent_tail_mean_impl(dont_care) {}\n\n        template<typename Args>\n        result_type result(Args const &args) const\n        {\n            std::size_t cnt = count(args);\n\n            std::size_t n = static_cast<std::size_t>(\n                std::ceil(\n                    cnt * ( ( is_same<LeftRight, left>::value ) ? args[quantile_probability] : 1. - args[quantile_probability] )\n                )\n            );\n\n            // If n is in a valid range, return result, otherwise return NaN or throw exception\n            if (n <= static_cast<std::size_t>(tail(args).size()))\n                return numeric::fdiv(\n                    std::accumulate(\n                        tail(args).begin()\n                      , tail(args).begin() + n\n                      , Sample(0)\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 Sample(0);\n                }\n            }\n        }\n        \n        // serialization is done by accumulators it depends on\n        template<class Archive>\n        void serialize(Archive & ar, const unsigned int file_version) {}\n    };\n\n} // namespace impl\n\n\n///////////////////////////////////////////////////////////////////////////////\n// tag::coherent_tail_mean<>\n// tag::non_coherent_tail_mean<>\n//\nnamespace tag\n{\n    template<typename LeftRight>\n    struct coherent_tail_mean\n      : depends_on<count, quantile, non_coherent_tail_mean<LeftRight> >\n    {\n        typedef accumulators::impl::coherent_tail_mean_impl<mpl::_1, LeftRight> impl;\n    };\n\n    template<typename LeftRight>\n    struct non_coherent_tail_mean\n      : depends_on<count, tail<LeftRight> >\n    {\n        typedef accumulators::impl::non_coherent_tail_mean_impl<mpl::_1, LeftRight> impl;\n    };\n\n    struct abstract_non_coherent_tail_mean\n      : depends_on<>\n    {\n    };\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// extract::non_coherent_tail_mean;\n// extract::coherent_tail_mean;\n//\nnamespace extract\n{\n    extractor<tag::abstract_non_coherent_tail_mean> const non_coherent_tail_mean = {};\n    extractor<tag::tail_mean> const coherent_tail_mean = {};\n\n    BOOST_ACCUMULATORS_IGNORE_GLOBAL(non_coherent_tail_mean)\n    BOOST_ACCUMULATORS_IGNORE_GLOBAL(coherent_tail_mean)\n}\n\nusing extract::non_coherent_tail_mean;\nusing extract::coherent_tail_mean;\n\n// for the purposes of feature-based dependency resolution,\n// coherent_tail_mean<LeftRight> provides the same feature as tail_mean\ntemplate<typename LeftRight>\nstruct feature_of<tag::coherent_tail_mean<LeftRight> >\n  : feature_of<tag::tail_mean>\n{\n};\n\ntemplate<typename LeftRight>\nstruct feature_of<tag::non_coherent_tail_mean<LeftRight> >\n  : feature_of<tag::abstract_non_coherent_tail_mean>\n{\n};\n\n// So that non_coherent_tail_mean can be automatically substituted\n// with weighted_non_coherent_tail_mean when the weight parameter is non-void.\ntemplate<typename LeftRight>\nstruct as_weighted_feature<tag::non_coherent_tail_mean<LeftRight> >\n{\n    typedef tag::non_coherent_weighted_tail_mean<LeftRight> type;\n};\n\ntemplate<typename LeftRight>\nstruct feature_of<tag::non_coherent_weighted_tail_mean<LeftRight> >\n  : feature_of<tag::non_coherent_tail_mean<LeftRight> >\n{};\n\n// NOTE that non_coherent_tail_mean cannot be feature-grouped with tail_mean,\n// which is the base feature for coherent tail means, since (at least for\n// non-continuous distributions) non_coherent_tail_mean is a different measure!\n\n}} // namespace boost::accumulators\n\n#ifdef _MSC_VER\n# pragma warning(pop)\n#endif\n\n#endif\n", "meta": {"hexsha": "f56606d14e64333fcfafad058302d332b117ae6f", "size": 9158, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/accumulators/statistics/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": "ReactNativeFrontend/ios/Pods/boost/boost/accumulators/statistics/tail_mean.hpp", "max_issues_repo_name": "Harshitha91/Tmdb-react-native-node", "max_issues_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/accumulators/statistics/tail_mean.hpp", "max_forks_repo_name": "Harshitha91/Tmdb-react-native-node", "max_forks_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 35.9137254902, "max_line_length": 138, "alphanum_fraction": 0.6185848439, "num_tokens": 2162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.453677261984556}}
{"text": "#ifndef PARSETYPE_HPP\n#define PARSETYPE_HPP\n\n#include <string>\n#include <vector>\n#include <iostream>\n#include <sstream>\n#include <boost/variant.hpp>\n#include <gmpxx.h>\n\nstruct parse_t;\n\ntypedef std::string val_t;\ntypedef std::vector<parse_t> args_t;\n\ntypedef parse_t command;\ntypedef parse_t expr;\ntypedef parse_t test;\n\nnamespace checktestdata {\n\nstruct none_t {};\n\nstd::ostream& operator<<(std::ostream&, const none_t&);\n\nstruct value_t {\n\tboost::variant<none_t, mpz_class, mpf_class, std::string> val;\n\n\tvalue_t(): val(none_t()) {}\n\texplicit value_t(mpz_class x): val(x) {}\n\texplicit value_t(mpf_class x): val(x) {}\n\texplicit value_t(std::string x): val(x) {}\n\n\toperator mpz_class() const;\n\toperator mpf_class() const;\n\n\t// This is a member function instead of a casting operator, since\n\t// otherwise the string could be used in other implicit casts.\n\tstd::string getstr() const;\n\n\t// This converts any value type to a string representation.\n\tstd::string tostr() const;\n};\n\nconst int value_none   = 0;\nconst int value_int    = 1;\nconst int value_float  = 2;\nconst int value_string = 3;\n\n} // namespace checktestdata\n\nstd::ostream &operator<<(std::ostream &, const parse_t &);\n\nstruct parse_t {\n\tval_t val;\n\targs_t args;\n\tchar op;\n\t/*\n\t  Operator/type of this node, can be any of the following:\n\n\t  +-*%/^ standard binary arithmetic operations\n\t  n      (unary) negation\n\n\t  ?      a comparison operator stored in 'val'\n\t  |&!    logical AND,OR,NOT\n\t  EMUA   EOF,MATCH,UNIQUE,INARRAY keywords used within test expressions\n\n\t  I      integer constant\n\t  F      float constant\n\t  S      string constant\n\n\t  a      variable assigment with two arguments: variable name, expression.\n\t  f      function returning a value\n\t  l      list of expressions (e.g. for array indices or argument list)\n\t  v      variable with array indices in second argument\n\t  @      command with list of arguments provided in second argument,\n\t  ' '    command\n\t  ~      uninitialized object, to detect unset default arguments\n\t*/\n\n\tmutable checktestdata::value_t cache;\n\n\tparse_t(): val(), args(), op('~') {}\n\tparse_t(args_t _args): val(), args(_args), op(' ') {}\n\tparse_t(val_t _val, args_t _args): val(_val), args(_args), op(' ') {}\n\n\t// Parsing command with optional arguments\n\texplicit\n\tparse_t(val_t _val, parse_t arg1 = parse_t(),\n\t                    parse_t arg2 = parse_t(),\n\t                    parse_t arg3 = parse_t(),\n\t                    parse_t arg4 = parse_t(),\n\t                    parse_t arg5 = parse_t(),\n\t                    parse_t arg6 = parse_t())\n\t: val(_val), args(), op(' ')\n\t{\n\t\tif ( arg1.op!='~' ) args.push_back(arg1);\n\t\tif ( arg2.op!='~' ) args.push_back(arg2);\n\t\tif ( arg3.op!='~' ) args.push_back(arg3);\n\t\tif ( arg4.op!='~' ) args.push_back(arg4);\n\t\tif ( arg5.op!='~' ) args.push_back(arg5);\n\t\tif ( arg6.op!='~' ) args.push_back(arg6);\n\t}\n\n\t// Parsing arithmetic/logical/compare operator and some other\n\t// special cases\n\texplicit\n\tparse_t(char _op, parse_t arg1 = parse_t(),\n\t                  parse_t arg2 = parse_t(),\n\t                  parse_t arg3 = parse_t(),\n\t                  parse_t arg4 = parse_t(),\n\t                  parse_t arg5 = parse_t(),\n\t                  parse_t arg6 = parse_t())\n\t: val(), args(), op(_op)\n\t{\n\t\tswitch ( op ) {\n\t\tcase 'l': // list: create new or append one argument\n\t\t\tif ( arg2.op=='~' ) {\n\t\t\t\tif ( arg1.op!='~' ) args.push_back(arg1);\n\t\t\t} else {\n\t\t\t\targs = arg1.args;\n\t\t\t\targs.push_back(arg2);\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase 'I': // integer, float, string literal values\n\t\tcase 'F':\n\t\tcase 'S':\n\t\t\tval = arg1.val;\n\t\t\tbreak;\n\n\t\tcase 'a': // variable assignment\n\t\t\targs.push_back(arg1);\n\t\t\targs.push_back(arg2);\n\t\t\tbreak;\n\n\t\tcase 'v': // variable, read index from arg2 if present\n\t\t\tval = arg1.val;\n\t\t\tif ( arg2.op=='l' ) args = arg2.args;\n\t\t\tbreak;\n\n\t\tcase '@': // Command with argument list in arg2\n\t\t\top = ' ';\n\t\t\tval = arg1.val;\n\t\t\targs = arg2.args;\n\t\t\tbreak;\n\n\t\tcase 'U': // UNIQUE test, has argument list in arg1\n\t\t\targs = arg1.args;\n\t\t\tbreak;\n\n\t\tcase '?': // comparison operator as arg1\n\t\t\tval = arg1.val;\n\t\t\targs.push_back(arg2);\n\t\t\targs.push_back(arg3);\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tif ( arg1.op!='~' ) args.push_back(arg1);\n\t\t\tif ( arg2.op!='~' ) args.push_back(arg2);\n\t\t\tif ( arg3.op!='~' ) args.push_back(arg3);\n\t\t\tif ( arg4.op!='~' ) args.push_back(arg4);\n\t\t\tif ( arg5.op!='~' ) args.push_back(arg5);\n\t\t\tif ( arg6.op!='~' ) args.push_back(arg6);\n\t\t}\n\t}\n\n\tconst val_t& name()  const { return val; }\n\tsize_t       nargs() const { return args.size(); }\n\tconst char*  c_str() const { return val.c_str(); }\n\n\toperator const std::string& () const { return val; }\n};\n\n#endif /* PARSETYPE_HPP */\n", "meta": {"hexsha": "b84e207427170ffd08060d2285d20ecba350ea81", "size": 4634, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "parsetype.hpp", "max_stars_repo_name": "RagnarGrootKoerkamp/checktestdata", "max_stars_repo_head_hexsha": "4ff2444b09adcaf2dec209cb1253d2167f3e032b", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2015-03-20T12:17:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T00:20:49.000Z", "max_issues_repo_path": "parsetype.hpp", "max_issues_repo_name": "RagnarGrootKoerkamp/checktestdata", "max_issues_repo_head_hexsha": "4ff2444b09adcaf2dec209cb1253d2167f3e032b", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 15.0, "max_issues_repo_issues_event_min_datetime": "2015-12-23T17:22:43.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-01T19:52:30.000Z", "max_forks_repo_path": "parsetype.hpp", "max_forks_repo_name": "RagnarGrootKoerkamp/checktestdata", "max_forks_repo_head_hexsha": "4ff2444b09adcaf2dec209cb1253d2167f3e032b", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 21.0, "max_forks_repo_forks_event_min_datetime": "2015-12-23T16:06:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-08T12:40:50.000Z", "avg_line_length": 26.3295454545, "max_line_length": 75, "alphanum_fraction": 0.6204143289, "num_tokens": 1261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.453677261984556}}
{"text": "/*\n * COPYRIGHT AND PERMISSION NOTICE\n * Penn Software MSCKF_VIO\n * Copyright (C) 2017 The Trustees of the University of Pennsylvania\n * All rights reserved.\n */\n\n#include <iostream>\n#include <iomanip>\n#include <cmath>\n#include <iterator>\n#include <algorithm>\n\n#include <Eigen/SVD>\n#include <Eigen/QR>\n#include <Eigen/SparseCore>\n#include <Eigen/SPQRSupport>\n#include <boost/math/distributions/chi_squared.hpp>\n\n#include <eigen_conversions/eigen_msg.h>\n#include <tf_conversions/tf_eigen.h>\n#include <sensor_msgs/PointCloud2.h>\n#include <pcl_ros/point_cloud.h>\n#include <pcl/point_types.h>\n\n#include <msckf_vio/msckf_vio.h>\n#include <msckf_vio/math_utils.hpp>\n#include <msckf_vio/utils.h>\n\nusing namespace std;\nusing namespace Eigen;\n\nnamespace msckf_vio{\n// Static member variables in IMUState class.\nStateIDType IMUState::next_id = 0;\ndouble IMUState::gyro_noise = 0.001;\ndouble IMUState::acc_noise = 0.01;\ndouble IMUState::gyro_bias_noise = 0.001;\ndouble IMUState::acc_bias_noise = 0.01;\nVector3d IMUState::gravity = Vector3d(0, 0, -GRAVITY_ACCELERATION);\nIsometry3d IMUState::T_imu_body = Isometry3d::Identity();\n\n// Static member variables in CAMState class.\nIsometry3d CAMState::T_cam0_cam1 = Isometry3d::Identity();\n\n// Static member variables in Feature class.\nFeatureIDType Feature::next_id = 0;\ndouble Feature::observation_noise = 0.01;\nFeature::OptimizationConfig Feature::optimization_config;\n\nmap<int, double> MsckfVio::chi_squared_test_table;\n\nMsckfVio::MsckfVio(ros::NodeHandle& pnh):\n  is_gravity_set(false),\n  is_first_img(true),\n  nh(pnh) {\n  return;\n}\n\n// \u5bfc\u5165\u5404\u79cd\u53c2\u6570\uff0c\u5305\u62ec\u9608\u503c\u3001\u4f20\u611f\u5668\u8bef\u5dee\u6807\u51c6\u5dee\u7b49\nbool MsckfVio::loadParameters() {\n  // Frame id\n  nh.param<string>(\"fixed_frame_id\", fixed_frame_id, \"world\");\n  nh.param<string>(\"child_frame_id\", child_frame_id, \"robot\");\n  nh.param<bool>(\"publish_tf\", publish_tf, true);\n  nh.param<double>(\"frame_rate\", frame_rate, 40.0);\n  nh.param<double>(\"position_std_threshold\", position_std_threshold, 8.0);\n\n  nh.param<double>(\"rotation_threshold\", rotation_threshold, 0.2618);\t// QXC\uff1a\u5927\u7ea6\u4e3a15\u00b0\n  nh.param<double>(\"translation_threshold\", translation_threshold, 0.4);\n  nh.param<double>(\"tracking_rate_threshold\", tracking_rate_threshold, 0.5);\n\n  // Feature optimization parameters\n  nh.param<double>(\"feature/config/translation_threshold\",\n      Feature::optimization_config.translation_threshold, 0.2);\n\n  // Noise related parameters\n  nh.param<double>(\"noise/gyro\", IMUState::gyro_noise, 0.001);\n  nh.param<double>(\"noise/acc\", IMUState::acc_noise, 0.01);\n  nh.param<double>(\"noise/gyro_bias\", IMUState::gyro_bias_noise, 0.001);\n  nh.param<double>(\"noise/acc_bias\", IMUState::acc_bias_noise, 0.01);\n  nh.param<double>(\"noise/feature\", Feature::observation_noise, 0.01);\n\n  // Use variance instead of standard deviation.\n  IMUState::gyro_noise *= IMUState::gyro_noise;\n  IMUState::acc_noise *= IMUState::acc_noise;\n  IMUState::gyro_bias_noise *= IMUState::gyro_bias_noise;\n  IMUState::acc_bias_noise *= IMUState::acc_bias_noise;\n  Feature::observation_noise *= Feature::observation_noise;\n\n  // Set the initial IMU state.\n  // The intial orientation and position will be set to the origin\n  // implicitly. But the initial velocity and bias can be\n  // set by parameters.\n  // TODO: is it reasonable to set the initial bias to 0?\n  nh.param<double>(\"initial_state/velocity/x\",\n      state_server.imu_state.velocity(0), 0.0);\n  nh.param<double>(\"initial_state/velocity/y\",\n      state_server.imu_state.velocity(1), 0.0);\n  nh.param<double>(\"initial_state/velocity/z\",\n      state_server.imu_state.velocity(2), 0.0);\n\n  // The initial covariance of orientation and position can be\n  // set to 0. But for velocity, bias and extrinsic parameters,\n  // there should be nontrivial uncertainty.\n  double gyro_bias_cov, acc_bias_cov, velocity_cov;\n  nh.param<double>(\"initial_covariance/velocity\",\n      velocity_cov, 0.25);\n  nh.param<double>(\"initial_covariance/gyro_bias\",\n      gyro_bias_cov, 1e-4);\n  nh.param<double>(\"initial_covariance/acc_bias\",\n      acc_bias_cov, 1e-2);\n\n  double extrinsic_rotation_cov, extrinsic_translation_cov;\n  nh.param<double>(\"initial_covariance/extrinsic_rotation_cov\",\n      extrinsic_rotation_cov, 3.0462e-4);\t// QXC\uff1a\u5927\u7ea6\u4e3a1\u00b0\u7684\u5e73\u65b9\n  nh.param<double>(\"initial_covariance/extrinsic_translation_cov\",\n      extrinsic_translation_cov, 1e-4);\n\n  state_server.state_cov = MatrixXd::Zero(21, 21);\n  for (int i = 3; i < 6; ++i)\n    state_server.state_cov(i, i) = gyro_bias_cov;\n  for (int i = 6; i < 9; ++i)\n    state_server.state_cov(i, i) = velocity_cov;\n  for (int i = 9; i < 12; ++i)\n    state_server.state_cov(i, i) = acc_bias_cov;\n  for (int i = 15; i < 18; ++i)\n    state_server.state_cov(i, i) = extrinsic_rotation_cov;\n  for (int i = 18; i < 21; ++i)\n    state_server.state_cov(i, i) = extrinsic_translation_cov;\n\n  // Transformation offsets between the frames involved.\n  Isometry3d T_imu_cam0 = utils::getTransformEigen(nh, \"cam0/T_cam_imu\");\n  Isometry3d T_cam0_imu = T_imu_cam0.inverse();\n\n  state_server.imu_state.R_imu_cam0 = T_cam0_imu.linear().transpose();\n  state_server.imu_state.t_cam0_imu = T_cam0_imu.translation();\n  CAMState::T_cam0_cam1 =\n    utils::getTransformEigen(nh, \"cam1/T_cn_cnm1\");\n  IMUState::T_imu_body =\n    utils::getTransformEigen(nh, \"T_imu_body\").inverse();\n\n  // Maximum number of camera states to be stored\n  nh.param<int>(\"max_cam_state_size\", max_cam_state_size, 30);\n\n  ROS_INFO(\"===========================================\");\n  ROS_INFO(\"fixed frame id: %s\", fixed_frame_id.c_str());\n  ROS_INFO(\"child frame id: %s\", child_frame_id.c_str());\n  ROS_INFO(\"publish tf: %d\", publish_tf);\n  ROS_INFO(\"frame rate: %f\", frame_rate);\n  ROS_INFO(\"position std threshold: %f\", position_std_threshold);\n  ROS_INFO(\"Keyframe rotation threshold: %f\", rotation_threshold);\n  ROS_INFO(\"Keyframe translation threshold: %f\", translation_threshold);\n  ROS_INFO(\"Keyframe tracking rate threshold: %f\", tracking_rate_threshold);\n  ROS_INFO(\"gyro noise: %.10f\", IMUState::gyro_noise);\n  ROS_INFO(\"gyro bias noise: %.10f\", IMUState::gyro_bias_noise);\n  ROS_INFO(\"acc noise: %.10f\", IMUState::acc_noise);\n  ROS_INFO(\"acc bias noise: %.10f\", IMUState::acc_bias_noise);\n  ROS_INFO(\"observation noise: %.10f\", Feature::observation_noise);\n  ROS_INFO(\"initial velocity: %f, %f, %f\",\n      state_server.imu_state.velocity(0),\n      state_server.imu_state.velocity(1),\n      state_server.imu_state.velocity(2));\n  ROS_INFO(\"initial gyro bias cov: %f\", gyro_bias_cov);\n  ROS_INFO(\"initial acc bias cov: %f\", acc_bias_cov);\n  ROS_INFO(\"initial velocity cov: %f\", velocity_cov);\n  ROS_INFO(\"initial extrinsic rotation cov: %f\",\n      extrinsic_rotation_cov);\n  ROS_INFO(\"initial extrinsic translation cov: %f\",\n      extrinsic_translation_cov);\n\n  cout << T_imu_cam0.linear() << endl;\n  cout << T_imu_cam0.translation().transpose() << endl;\n\n  ROS_INFO(\"max camera state #: %d\", max_cam_state_size);\n  ROS_INFO(\"===========================================\");\n  return true;\n}\n\n// \u58f0\u660e\u672c\u8282\u70b9\u5f00\u59cb\u53d1\u5e03\u548c\u8ba2\u9605\u7684\u5404\u79cdtopic\nbool MsckfVio::createRosIO() {\n  odom_pub = nh.advertise<nav_msgs::Odometry>(\"odom\", 10);\t// QXC\uff1a\u5f00\u59cb\u53d1\u5e03\u540d\u4e3aodom\u7684topic\uff0c\u5176\u6d88\u606f\u7c7b\u578b\u4e3anav_msgs::Odometry\uff0c\u6700\u5927\u7f13\u5b58\u4e3a10\n  feature_pub = nh.advertise<sensor_msgs::PointCloud2>(\t\t// QXC\uff1a\u5f00\u59cb\u53d1\u5e03\u540d\u4e3afeature_point_cloud\u7684topic\uff0c\u5176\u6d88\u606f\u7c7b\u578b\u4e3asensor_msgs::PointCloud2\uff0c\n      \"feature_point_cloud\", 10);\t\t\t\t            //\t    \u6700\u5927\u7f13\u5b58\u4e3a10\n\n  reset_srv = nh.advertiseService(\"reset\",\n      &MsckfVio::resetCallback, this);\n\n  imu_sub = nh.subscribe(\"imu\", 100,\t\t\t\t// QXC\uff1a\u5f00\u59cb\u8ba2\u9605\u540d\u4e3aimu\u7684topic\uff0c\u6700\u5927\u7f13\u5b58\u4e3a100\n      &MsckfVio::imuCallback, this);\n  feature_sub = nh.subscribe(\"features\", 40,\t\t\t// QXC\uff1a\u5f00\u59cb\u8ba2\u9605\u540d\u4e3afeatures\u7684topic\uff0c\u6700\u5927\u7f13\u5b58\u4e3a40\n      &MsckfVio::featureCallback, this);\n\n  mocap_odom_sub = nh.subscribe(\"mocap_odom\", 10,\t\t// QXC\uff1a\u5f00\u59cb\u8ba2\u9605\u540d\u4e3amocap_odom\u7684topic\uff0c\u6700\u5927\u7f13\u5b58\u4e3a10\n      &MsckfVio::mocapOdomCallback, this);\n  mocap_odom_pub = nh.advertise<nav_msgs::Odometry>(\"gt_odom\", 1);\t// QXC\uff1a\u5f00\u59cb\u53d1\u5e03\u540d\u4e3agt_odom\u7684topic\uff0c\u5176\u6d88\u606f\u7c7b\u578b\u4e3anav_msgs::Odometry\uff0c\u6700\u5927\u7f13\u5b58\u4e3a1\n\n  return true;\n}\n\n// \u8c03\u7528loadParameters()\u51fd\u6570\u5bfc\u5165\u5404\u79cd\u53c2\u6570\uff0c\u8c03\u7528createRosIO()\u51fd\u6570\u53d1\u5e03\u548c\u8ba2\u9605\u5404\u79cdtopic\nbool MsckfVio::initialize() {\n  if (!loadParameters()) return false;\n  ROS_INFO(\"Finish loading ROS parameters...\");\n\n  // Initialize state server\n  state_server.continuous_noise_cov =\n    Matrix<double, 12, 12>::Zero();\n  state_server.continuous_noise_cov.block<3, 3>(0, 0) =\n    Matrix3d::Identity()*IMUState::gyro_noise;\n  state_server.continuous_noise_cov.block<3, 3>(3, 3) =\n    Matrix3d::Identity()*IMUState::gyro_bias_noise;\n  state_server.continuous_noise_cov.block<3, 3>(6, 6) =\n    Matrix3d::Identity()*IMUState::acc_noise;\n  state_server.continuous_noise_cov.block<3, 3>(9, 9) =\n    Matrix3d::Identity()*IMUState::acc_bias_noise;\n\n  // Initialize the chi squared test table with confidence\n  // level 0.95.\n  for (int i = 1; i < 100; ++i) {\n    boost::math::chi_squared chi_squared_dist(i);\n    chi_squared_test_table[i] =\n      boost::math::quantile(chi_squared_dist, 0.05);\n  }\n\n  if (!createRosIO()) return false;\n  ROS_INFO(\"Finish creating ROS IO...\");\n\n  return true;\n}\n\n// \u5f53\u63a5\u6536\u5230topic\uff1aimu\u65f6\u8c03\u7528\u7684\u51fd\u6570\uff0c\u9759\u6b62\u65f6\u7684\u524d200\u6761\u8fdb\u884c\u521d\u59cb\u5316\uff08\u9640\u87babias\u3001\u91cd\u529b\u3001\u521d\u59cb\u59ff\u6001\uff09\u5de5\u4f5c\uff0c\u5176\u4ed6\u65f6\u95f4\u53ea\u7ba1\u5c06imu\u6570\u636e\u538b\u5165\u5bb9\u5668\u4e2d\nvoid MsckfVio::imuCallback(\n    const sensor_msgs::ImuConstPtr& msg) {\n\n  // IMU msgs are pushed backed into a buffer instead of\n  // being processed immediately. The IMU msgs are processed\n  // when the next image is available, in which way, we can\n  // easily handle the transfer delay.\n  imu_msg_buffer.push_back(*msg);\n\n  if (!is_gravity_set) {\n    if (imu_msg_buffer.size() < 200) return;\t// QXC\uff1aIMU\u6570\u636e\u4e0d\u8db3200\u6761\u65f6\u4e0d\u5bf9\u91cd\u529b\u548cbias\u8fdb\u884c\u521d\u59cb\u5316\n    //if (imu_msg_buffer.size() < 10) return;\n    initializeGravityAndBias();\t\t// QXC\uff1a\u8fdb\u884c\u521d\u59cb\u5316\u7684IMU\u6570\u636e\u5fc5\u987b\u662f\u9759\u6b62\u65f6\u91c7\u96c6\u7684\n    is_gravity_set = true;\n  }\n\n  return;\n}\n\n// \u521d\u59cb\u5316\u9640\u87ba\u4eeabias\u3001\u91cd\u529b\u4ee5\u53ca\u521d\u59cb\u59ff\u6001\uff0c\u53ef\u4ee5\u770b\u51fa\u8fd9\u91cc\u9700\u8981\u5229\u7528\u9759\u6b62\u65f6IMU\u91c7\u96c6\u7684\u6570\u636e\n// QXC\uff1a\u8fd9\u4e2a\u521d\u59cb\u5316\u65b9\u6cd5\u4e0d\u5bf9\u52a0\u8ba1\u96f6\u504f\u505a\u8865\u507f\uff0c\u53ef\u80fd\u4f1a\u51fa\u95ee\u9898\nvoid MsckfVio::initializeGravityAndBias() {\n\n  // Initialize gravity and gyro bias.\n  Vector3d sum_angular_vel = Vector3d::Zero();\n  Vector3d sum_linear_acc = Vector3d::Zero();\n\n  for (const auto& imu_msg : imu_msg_buffer) {\n    Vector3d angular_vel = Vector3d::Zero();\n    Vector3d linear_acc = Vector3d::Zero();\n\n    tf::vectorMsgToEigen(imu_msg.angular_velocity, angular_vel);\t// QXC\uff1a\u8be5\u51fd\u6570\u6765\u81ea<eigen_conversions/eigen_msg.h>\n    tf::vectorMsgToEigen(imu_msg.linear_acceleration, linear_acc);\n\n    sum_angular_vel += angular_vel;\n    sum_linear_acc += linear_acc;\n  }\n\n  state_server.imu_state.gyro_bias =\n    sum_angular_vel / imu_msg_buffer.size();\n  //IMUState::gravity =\n  //  -sum_linear_acc / imu_msg_buffer.size();\n  // This is the gravity in the IMU frame.\n  Vector3d gravity_imu =\n    sum_linear_acc / imu_msg_buffer.size();\n\n  // Initialize the initial orientation, so that the estimation\n  // is consistent with the inertial frame.\n  double gravity_norm = gravity_imu.norm();\n  IMUState::gravity = Vector3d(0.0, 0.0, -gravity_norm);\n\n  Quaterniond q0_i_w = Quaterniond::FromTwoVectors(\n    gravity_imu, -IMUState::gravity);\t// QXC\uff1aQuaterniond\u53ca\u5176\u76f8\u5173\u65b9\u6cd5\u6765\u81eaEIgen\uff0c\u8fd4\u56de\u7684\u662fC_b2w\u5bf9\u5e94\u7684\u56db\u5143\u6570\uff0c\u4f46\u6ce8\u610fEigen\u7684\u56db\u5143\u6570\u91c7\u7528HN\uff0c\u4e14\u4e0e\u65cb\u8f6c\u77e9\u9635\u7684\u8f6c\u6362\u91c7\u7528\u7f57\u5fb7\u91cc\u683c\u65af\u516c\u5f0f\n  state_server.imu_state.orientation =\n    rotationToQuaternion(q0_i_w.toRotationMatrix().transpose());    // QXC\uff1a\u8be5\u51fd\u6570\u4e3a\u672c\u7a0b\u5e8f\u81ea\u5e26\uff0c\u6b64\u5904\u4f20\u5165\u7684\u53c2\u6570\u662fC_w2b\n\n  return;\n}\n\n// \u54cd\u5e94\u91cd\u7f6e\u6d88\u606f\u7684\u56de\u8c03\u51fd\u6570\uff0c\u91cd\u7f6e\u6574\u4e2avio\nbool MsckfVio::resetCallback(\n    std_srvs::Trigger::Request& req,\n    std_srvs::Trigger::Response& res) {\n\n  ROS_WARN(\"Start resetting msckf vio...\");\n  // Temporarily shutdown the subscribers to prevent the\n  // state from updating.\n  feature_sub.shutdown();\n  imu_sub.shutdown();\n\n  // Reset the IMU state.\n  IMUState& imu_state = state_server.imu_state;\n  imu_state.time = 0.0;\n  imu_state.orientation = Vector4d(0.0, 0.0, 0.0, 1.0);\n  imu_state.position = Vector3d::Zero();\n  imu_state.velocity = Vector3d::Zero();\n  imu_state.gyro_bias = Vector3d::Zero();\n  imu_state.acc_bias = Vector3d::Zero();\n  imu_state.orientation_null = Vector4d(0.0, 0.0, 0.0, 1.0);\n  imu_state.position_null = Vector3d::Zero();\n  imu_state.velocity_null = Vector3d::Zero();\n\n  // Remove all existing camera states.\n  state_server.cam_states.clear();\n\n  // Reset the state covariance.\n  double gyro_bias_cov, acc_bias_cov, velocity_cov;\n  nh.param<double>(\"initial_covariance/velocity\",\n      velocity_cov, 0.25);\n  nh.param<double>(\"initial_covariance/gyro_bias\",\n      gyro_bias_cov, 1e-4);\n  nh.param<double>(\"initial_covariance/acc_bias\",\n      acc_bias_cov, 1e-2);\n\n  double extrinsic_rotation_cov, extrinsic_translation_cov;\n  nh.param<double>(\"initial_covariance/extrinsic_rotation_cov\",\n      extrinsic_rotation_cov, 3.0462e-4);\n  nh.param<double>(\"initial_covariance/extrinsic_translation_cov\",\n      extrinsic_translation_cov, 1e-4);\n\n  state_server.state_cov = MatrixXd::Zero(21, 21);\n  for (int i = 3; i < 6; ++i)\n    state_server.state_cov(i, i) = gyro_bias_cov;\n  for (int i = 6; i < 9; ++i)\n    state_server.state_cov(i, i) = velocity_cov;\n  for (int i = 9; i < 12; ++i)\n    state_server.state_cov(i, i) = acc_bias_cov;\n  for (int i = 15; i < 18; ++i)\n    state_server.state_cov(i, i) = extrinsic_rotation_cov;\n  for (int i = 18; i < 21; ++i)\n    state_server.state_cov(i, i) = extrinsic_translation_cov;\n\n  // Clear all exsiting features in the map.\n  map_server.clear();\n\n  // Clear the IMU msg buffer.\n  imu_msg_buffer.clear();\n\n  // Reset the starting flags.\n  is_gravity_set = false;\n  is_first_img = true;\n\n  // Restart the subscribers.\n  imu_sub = nh.subscribe(\"imu\", 100,\n      &MsckfVio::imuCallback, this);            // QXC\uff1a\u91cd\u65b0\u5f00\u59cb\u8ba2\u9605imu\u6d88\u606f\n  feature_sub = nh.subscribe(\"features\", 40,\n      &MsckfVio::featureCallback, this);        // QXC\uff1a\u91cd\u65b0\u5f00\u59cb\u8ba2\u9605feature\u6d88\u606f\n\n  // TODO: When can the reset fail?\n  res.success = true;\n  ROS_WARN(\"Resetting msckf vio completed...\");\n  return true;\n}\n\n// \u6839\u636e\u5230\u6765\u7684\u65b0\u4e00\u5e27\u7684features\uff0c\u8fdb\u884c\u5904\u7406\uff0c\u5305\u62ec\uff1a\u79ef\u5206\u4e0a\u5e27\u5230\u672c\u5e27\u4e4b\u95f4\u7684IMU\u6570\u636e\uff1b\u8ba1\u7b97\u5e76\u5c06\u5f53\u524d\u5e27\u72b6\u6001\u6269\u7ef4\u5230\u7cfb\u7edf\u72b6\u6001\u4e2d\uff1b\u66f4\u65b0feature\u89c2\u6d4b\u4fe1\u606f\uff1b\n// \u4f9d\u636e\u4e0d\u518d\u8ddf\u8e2a\u7684feature\u7684\u6d4b\u91cf\u8fdb\u884cMSCKF\u7684\u6d4b\u91cf\u66f4\u65b0\uff1b\u5f53\u6269\u7ef4\u7684cam\u8fbe\u5230\u6700\u5927\u503c\u65f6\u5254\u9664\u90e8\u5206cam\u72b6\u6001\uff0c\u5e76\u4f9d\u636e\u4e0e\u8fd9\u4e9bcam\u72b6\u6001\u76f8\u5173\u8054\u7684\u4e00\u4e9bfeature\u8fdb\u884cMSCKF\u6d4b\u91cf\u66f4\u65b0\uff1b\n// \u53d1\u5e03\u672c\u8282\u70b9\u5e94\u5f53\u53d1\u5e03\u7684\u4e00\u4e9b\u6d88\u606f\uff1b\u6839\u636eIMU\u72b6\u6001\u4f4d\u7f6e\u534f\u65b9\u5dee\u5224\u65ad\u662f\u5426\u9700\u8981\u91cd\u7f6e\u6574\u4e2a\u7cfb\u7edf\u3002\nvoid MsckfVio::featureCallback(\n    const CameraMeasurementConstPtr& msg) {\n\n  // Return if the gravity vector has not been set.\n  if (!is_gravity_set) return;\t\t// QXC\uff1aIMU\u59ff\u6001\u521d\u59cb\u5316\u4e4b\u524d\u4e0d\u5904\u7406feature\u6d88\u606f\n\n  // Start the system if the first image is received.\n  // The frame where the first image is received will be\n  // the origin.\n  if (is_first_img) {\n    is_first_img = false;\n    state_server.imu_state.time = msg->header.stamp.toSec();\n  }\n\n  static double max_processing_time = 0.0;\n  static int critical_time_cntr = 0;\n  double processing_start_time = ros::Time::now().toSec();\n\n  // Propogate the IMU state.\n  // that are received before the image msg.\n  ros::Time start_time = ros::Time::now();\n  batchImuProcessing(msg->header.stamp.toSec());\t// QXC\uff1a\u5bf9\u4e0a\u4e00\u5e27\u65f6\u523b\u4e4b\u540e\u3001\u5f53\u524d\u5e27\u65f6\u523b\u4e4b\u524d\u7684IMU\u6570\u636e\u8fdb\u884c\u79ef\u5206\n  double imu_processing_time = (\n      ros::Time::now()-start_time).toSec();     // QXC\uff1a\u83b7\u53d6\u5904\u7406\u65f6\u95f4\n\n  // Augment the state vector.      // QXC\uff1afeatureCallback\u6bcf\u6b21\u90fd\u8c03\u7528\u8fd9\u4e2a\u51fd\u6570\uff0c\u53ef\u89c1\u6bcf\u4e00\u5e27\u7684\u76f8\u673a\u72b6\u6001\u662f\u4e00\u76f4\u90fd\u88ab\u589e\u5e7f\u7684\n  start_time = ros::Time::now();\n  stateAugmentation(msg->header.stamp.toSec());\t\t// QXC\uff1a\u6839\u636e\u5f53\u524dIMU\u72b6\u6001\u8ba1\u7b97\u76f8\u673a\u72b6\u6001\uff0c\u540c\u65f6\u66f4\u65b0\u5897\u5e7f\u534f\u65b9\u5dee\u77e9\u9635\n  double state_augmentation_time = (\n      ros::Time::now()-start_time).toSec();\n\n  // Add new observations for existing features or new\n  // features in the map server.\n  start_time = ros::Time::now();\n  addFeatureObservations(msg);                      // QXC\uff1a\u4e3amap_server\u6dfb\u52a0\u65b0\u7684\u7279\u5f81\u70b9\u89c2\u6d4b\uff08\u53ef\u80fd\u662f\u65e7\u7279\u5f81\u70b9\u7684\u65b0\u89c2\u6d4b\uff0c\u4e5f\u53ef\u80fd\u662f\u65b0\u7279\u5f81\u70b9\u9996\u6b21\u89c2\u6d4b\u5230\uff09\n  double add_observations_time = (\n      ros::Time::now()-start_time).toSec();\n\n  // Perform measurement update if necessary.\n  start_time = ros::Time::now();\n  removeLostFeatures();                             // QXC\uff1a\u5229\u7528\u5f53\u524d\u5e27\u4e0d\u518d\u80fd\u8ddf\u8e2a\u5230\u7684feature\u8fdb\u884cMSCKF\u7684\u6d4b\u91cf\u66f4\u65b0\n  double remove_lost_features_time = (\n      ros::Time::now()-start_time).toSec();\n\n  start_time = ros::Time::now();\n  pruneCamStateBuffer();        // QXC\uff1a\u5f53cam\u72b6\u6001\u6570\u8fbe\u5230\u6700\u5927\u503c\u65f6\uff0c\u6311\u51fa\u82e5\u5e72cam\u72b6\u6001\u5f85\u5220\u9664\uff0c\u5e76\u57fa\u4e8e\u80fd\u88ab2\u5e27\u4ee5\u4e0a\u8fd9\u4e9bcam\u89c2\u6d4b\u5230\u7684feature\u8fdb\u884cMSCKF\u6d4b\u91cf\u66f4\u65b0\n  double prune_cam_states_time = (\n      ros::Time::now()-start_time).toSec();\n\n  // Publish the odometry.\n  start_time = ros::Time::now();\n  publish(msg->header.stamp);                       // QXC\uff1a\u5f00\u59cb\u53d1\u5e03tf\u3001odometry\u548c\u7279\u5f81\u70b9\u4e91\u7b49\u6d88\u606f\n  double publish_time = (\n      ros::Time::now()-start_time).toSec();\n\n  // Reset the system if necessary.\n  onlineReset();                                    // QXC\uff1a\u6839\u636eIMU\u72b6\u6001\u4f4d\u7f6e\u534f\u65b9\u5dee\u5224\u65ad\u662f\u5426\u91cd\u7f6e\u6574\u4e2a\u7cfb\u7edf\n\n  double processing_end_time = ros::Time::now().toSec();\n  double processing_time =\n    processing_end_time - processing_start_time;\n  if (processing_time > 1.0/frame_rate) {\n    ++critical_time_cntr;\n    ROS_INFO(\"\\033[1;31mTotal processing time %f/%d...\\033[0m\",\n        processing_time, critical_time_cntr);\n    //printf(\"IMU processing time: %f/%f\\n\",\n    //    imu_processing_time, imu_processing_time/processing_time);\n    //printf(\"State augmentation time: %f/%f\\n\",\n    //    state_augmentation_time, state_augmentation_time/processing_time);\n    //printf(\"Add observations time: %f/%f\\n\",\n    //    add_observations_time, add_observations_time/processing_time);\n    printf(\"Remove lost features time: %f/%f\\n\",\n        remove_lost_features_time, remove_lost_features_time/processing_time);\n    printf(\"Remove camera states time: %f/%f\\n\",\n        prune_cam_states_time, prune_cam_states_time/processing_time);\n    //printf(\"Publish time: %f/%f\\n\",\n    //    publish_time, publish_time/processing_time);\n  }\n\n  return;\n}\n\n// \u4e0eodometry\u771f\u503c\u76f8\u5173\u7684\u65b9\u6cd5\nvoid MsckfVio::mocapOdomCallback(\n    const nav_msgs::OdometryConstPtr& msg) {\n  static bool first_mocap_odom_msg = true;\n\n  // If this is the first mocap odometry messsage, set\n  // the initial frame.\n  if (first_mocap_odom_msg) {\n    Quaterniond orientation;\n    Vector3d translation;\n    tf::pointMsgToEigen(\n        msg->pose.pose.position, translation);\n    tf::quaternionMsgToEigen(\n        msg->pose.pose.orientation, orientation);\n    //tf::vectorMsgToEigen(\n    //    msg->transform.translation, translation);\n    //tf::quaternionMsgToEigen(\n    //    msg->transform.rotation, orientation);\n    mocap_initial_frame.linear() = orientation.toRotationMatrix();\n    mocap_initial_frame.translation() = translation;\n    first_mocap_odom_msg = false;\n  }\n\n  // Transform the ground truth.\n  Quaterniond orientation;\n  Vector3d translation;\n  //tf::vectorMsgToEigen(\n  //    msg->transform.translation, translation);\n  //tf::quaternionMsgToEigen(\n  //    msg->transform.rotation, orientation);\n  tf::pointMsgToEigen(\n      msg->pose.pose.position, translation);\n  tf::quaternionMsgToEigen(\n      msg->pose.pose.orientation, orientation);\n\n  Eigen::Isometry3d T_b_v_gt;\n  T_b_v_gt.linear() = orientation.toRotationMatrix();\n  T_b_v_gt.translation() = translation;\n  Eigen::Isometry3d T_b_w_gt = mocap_initial_frame.inverse() * T_b_v_gt;\n\n  //Eigen::Vector3d body_velocity_gt;\n  //tf::vectorMsgToEigen(msg->twist.twist.linear, body_velocity_gt);\n  //body_velocity_gt = mocap_initial_frame.linear().transpose() *\n  //  body_velocity_gt;\n\n  // Ground truth tf.\n  if (publish_tf) {\n    tf::Transform T_b_w_gt_tf;\n    tf::transformEigenToTF(T_b_w_gt, T_b_w_gt_tf);\n    tf_pub.sendTransform(tf::StampedTransform(\n          T_b_w_gt_tf, msg->header.stamp, fixed_frame_id, child_frame_id+\"_mocap\"));\n  }\n\n  // Ground truth odometry.\n  nav_msgs::Odometry mocap_odom_msg;\n  mocap_odom_msg.header.stamp = msg->header.stamp;\n  mocap_odom_msg.header.frame_id = fixed_frame_id;\n  mocap_odom_msg.child_frame_id = child_frame_id+\"_mocap\";\n\n  tf::poseEigenToMsg(T_b_w_gt, mocap_odom_msg.pose.pose);\n  //tf::vectorEigenToMsg(body_velocity_gt,\n  //    mocap_odom_msg.twist.twist.linear);\n\n  mocap_odom_pub.publish(mocap_odom_msg);\n  return;\n}\n\n// \u5bf9\u4e0a\u4e00\u5e27\u56fe\u50cf\u4e4b\u524d\u6700\u540e\u4e00\u6761IMU\u6570\u636e\u4e4b\u540e\u7684\uff0c\u5f53\u524d\u5e27\u56fe\u50cf\u65f6\u523b\u4e4b\u524d\u7684IMU\u6570\u636e\u8fdb\u884c\u60ef\u6027\u9012\u63a8\u89e3\u7b97\uff0c\u540c\u65f6\u66f4\u65b0\u72b6\u6001\u534f\u65b9\u5dee\u77e9\u9635\nvoid MsckfVio::batchImuProcessing(const double& time_bound) {\n  // Counter how many IMU msgs in the buffer are used.\n  int used_imu_msg_cntr = 0;\n\n  for (const auto& imu_msg : imu_msg_buffer) {\n    double imu_time = imu_msg.header.stamp.toSec();\n    if (imu_time < state_server.imu_state.time) {\n      ++used_imu_msg_cntr;\n      continue;\n    }\n    if (imu_time > time_bound) break;\n\n    // QXC\uff1a\u6ce8\u610f\uff0c\u5728\u9996\u6b21\u5904\u7406feature\u800c\u8c03\u7528\u672c\u51fd\u6570\u65f6\uff0ctime_bound\u4e0estate_server.imu_state.time\u76f8\u7b49\uff0c\n      //    \u56e0\u6b64\u4e0a\u8ff0\u4e24\u4e2aif\u5c06\u4f1a\u6f0f\u6389\u4e00\u79cd\u6781\u7aef\u60c5\u51b5\uff0c\u5373\u67d0\u6761IMU\u6570\u636e\u65f6\u95f4\u6233\u6b63\u597d\u548cfeature\u65f6\u95f4\u6233\u76f8\u7b49\uff0c\u4f46\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0c\u6839\u636eprocessModel\u7684\u5206\u6790\uff0c\u5c06\u4e0d\u4f1a\u8fdb\u884c\u4efb\u4f55\u9012\u63a8\n\n    // Convert the msgs.\n    Vector3d m_gyro, m_acc;\n    tf::vectorMsgToEigen(imu_msg.angular_velocity, m_gyro);         // QXC\uff1atf\u7cfb\u5217\u51fd\u6570\u6765\u81earos\u81ea\u8eab\n    tf::vectorMsgToEigen(imu_msg.linear_acceleration, m_acc);\n\n    // Execute process model.\n    processModel(imu_time, m_gyro, m_acc);      // QXC\uff1a\u6ce8\u610f\u8fd9\u4e2a\u51fd\u6570\u662f\u9012\u63a8\u4e00\u6761IMI\u6570\u636e\uff0c\u800c\u4e0d\u662f\u9012\u63a8\u4e00\u7cfb\u5217\uff08\u6574\u4e2afor\u5faa\u73af\u5b9e\u73b0\u9012\u63a8\u4e00\u7cfb\u5217\uff09\n    ++used_imu_msg_cntr;\n  }\n\n  // Set the state ID for the new IMU state.\n  state_server.imu_state.id = IMUState::next_id++;\n\n  // Remove all used IMU msgs.\n  imu_msg_buffer.erase(imu_msg_buffer.begin(),\n      imu_msg_buffer.begin()+used_imu_msg_cntr);\n\n  return;\n}\n\n// \u8fdb\u884c\u60ef\u6027\u9012\u63a8\u548c\u72b6\u6001\u534f\u65b9\u5dee\u9635\u9012\u63a8\n// \u9996\u6b21\u8c03\u7528\u8be5\u51fd\u6570\u65f6\uff0c\u53ef\u80fd\u9047\u5230\u201dtime==imu_state.time\u201c\u7684\u60c5\u5f62\uff08\u5b58\u5728\u548c\u7b2c\u4e00\u4e2a\u88ab\u5904\u7406\u7684feature\u65f6\u95f4\u6233\u76f8\u540c\u7684IMU\u6570\u636e\uff09\uff0c\u8fd9\u65f6\u4f1a\u4f7f\u5f97dtime\u4e3a0\uff0c\u4ece\u800c\u5e76\u4e0d\u53d1\u751f\u4ec0\u4e48\u9012\u63a8\nvoid MsckfVio::processModel(const double& time,\n    const Vector3d& m_gyro,\n    const Vector3d& m_acc) {\n\n  // Remove the bias from the measured gyro and acceleration\n  IMUState& imu_state = state_server.imu_state;\n  Vector3d gyro = m_gyro - imu_state.gyro_bias;\n  Vector3d acc = m_acc - imu_state.acc_bias;\t\t// QXC\uff1a\u5728\u6ca1\u5f00\u59cb\u6ee4\u6ce2\u4e4b\u524d\uff0cacc_bias\u59cb\u7ec8\u662f0\n  double dtime = time - imu_state.time;\t\t// QXC\uff1a\u4e24\u4e2aIMU\u6d4b\u91cf\u4e4b\u95f4\u7684\u65f6\u95f4\u95f4\u9694\uff08\u9664\u4e86\u5728\u7b2c\u4e00\u5e27\u4e4b\u540e\u7684\u7b2c\u4e00\u6761IMU\u6570\u636e\uff0c\u6b64\u65f6\u7b97\u51fa\u7684\u662f\u548c\u7b2c\u4e00\u5e27\u4e4b\u95f4\u7684\u65f6\u95f4\u5dee\uff09\n\n  // Compute discrete transition and noise covariance matrix\n  Matrix<double, 21, 21> F = Matrix<double, 21, 21>::Zero();\n  Matrix<double, 21, 12> G = Matrix<double, 21, 12>::Zero();\n\n  F.block<3, 3>(0, 0) = -skewSymmetric(gyro);\n  F.block<3, 3>(0, 3) = -Matrix3d::Identity();\n  F.block<3, 3>(6, 0) = -quaternionToRotation(\n      imu_state.orientation).transpose()*skewSymmetric(acc);\n  F.block<3, 3>(6, 9) = -quaternionToRotation(\t\t// QXC\uff1a\u6ce8\u610f\uff01\uff01\u8fd9\u91cc\u7684F\u9635\u4e2d\u6ca1\u6709\u8003\u8651\u5730\u7403\u81ea\u8f6c\uff01\uff01\uff01\n      imu_state.orientation).transpose();\n  F.block<3, 3>(12, 6) = Matrix3d::Identity();\n\n  G.block<3, 3>(0, 0) = -Matrix3d::Identity();\n  G.block<3, 3>(3, 3) = Matrix3d::Identity();\n  G.block<3, 3>(6, 6) = -quaternionToRotation(\n      imu_state.orientation).transpose();\n  G.block<3, 3>(9, 9) = Matrix3d::Identity();\n\n  // Approximate matrix exponential to the 3rd order,\n  // which can be considered to be accurate enough assuming\n  // dtime is within 0.01s.\n  Matrix<double, 21, 21> Fdt = F * dtime;\n  Matrix<double, 21, 21> Fdt_square = Fdt * Fdt;\n  Matrix<double, 21, 21> Fdt_cube = Fdt_square * Fdt;\n  Matrix<double, 21, 21> Phi = Matrix<double, 21, 21>::Identity() +\n    Fdt + 0.5*Fdt_square + (1.0/6.0)*Fdt_cube;\n\n  // Propogate the state using 4th order Runge-Kutta\n  predictNewState(dtime, gyro, acc);\n\n  // Modify the transition matrix\t// QXC\uff1a\u8fd9\u90e8\u5206\u5b8c\u5168\u6ca1\u770b\u61c2\n  Matrix3d R_kk_1 = quaternionToRotation(imu_state.orientation_null);\n  Phi.block<3, 3>(0, 0) =\n    quaternionToRotation(imu_state.orientation) * R_kk_1.transpose();\t// QXC\uff1a\u8fd9\u4e48\u4e00\u6539\uff0c\u76f8\u5f53\u4e8eF\u77e9\u9635\u5bf9\u89d2\u7ebf\u4e0a\u9996\u4e2a3*3\u77e9\u9635\u538b\u6839\u6ca1\u7528\u4e86\n\n  Vector3d u = R_kk_1 * IMUState::gravity;\n  RowVector3d s = (u.transpose()*u).inverse() * u.transpose();\n\n  Matrix3d A1 = Phi.block<3, 3>(6, 0);\n  Vector3d w1 = skewSymmetric(\n      imu_state.velocity_null-imu_state.velocity) * IMUState::gravity;\n  Phi.block<3, 3>(6, 0) = A1 - (A1*u-w1)*s;\t// QXC\uff1a\u770b\u4e0d\u61c2\uff0c\u4f46\u77e5\u9053\u5bf9\u4e8ePhi\u9635\u4e2d\u7684\u8fd9\u4e00\u90e8\u5206\uff0cF\u77e9\u9635\u5bf9\u89d2\u7ebf\u4e0a\u9996\u4e2a3*3\u77e9\u9635\u4e5f\u6ca1\u6709\u8d21\u732e\u4e86\n\n  Matrix3d A2 = Phi.block<3, 3>(12, 0);\n  Vector3d w2 = skewSymmetric(\n      dtime*imu_state.velocity_null+imu_state.position_null-\n      imu_state.position) * IMUState::gravity;\n  Phi.block<3, 3>(12, 0) = A2 - (A2*u-w2)*s;\t// QXC\uff1a\u540c\u4e0a\n\n  // Propogate the state covariance matrix.\n  Matrix<double, 21, 21> Q = Phi*G*state_server.continuous_noise_cov*\n    G.transpose()*Phi.transpose()*dtime;        // QXC\uff1a\u7528\u5e38\u503c\u77e9\u9635\u6a21\u578b\u4f30\u7b97Q\u9635\uff0cQ=Phi*G*q*\n  state_server.state_cov.block<21, 21>(0, 0) =\n    Phi*state_server.state_cov.block<21, 21>(0, 0)*Phi.transpose() + Q;\n\n  if (state_server.cam_states.size() > 0) {\t// QXC\uff1a\u5f53\u72b6\u6001\u91cf\u6269\u7ef4\u4e86\u76f8\u673a\u72b6\u6001\u65f6\uff0c\u8fd8\u9700\u8981\u66f4\u65b0\u6269\u7ef4\u7684P\u9635\n    state_server.state_cov.block(\t// QXC\uff1ablock(i,j,p,q)\u51fd\u6570\u8868\u793a\u4ece\u77e9\u9635\u7684\u7b2ci\u884c\u7b2cj\u5217\u5143\u7d20\u5f00\u59cb\uff0c\u53d6p\u884c\uff0cq\u5217\n        0, 21, 21, state_server.state_cov.cols()-21) =\n      Phi * state_server.state_cov.block(\n        0, 21, 21, state_server.state_cov.cols()-21);\n    state_server.state_cov.block(\n        21, 0, state_server.state_cov.rows()-21, 21) =\n      state_server.state_cov.block(\n        21, 0, state_server.state_cov.rows()-21, 21) * Phi.transpose();\n  }\n\n  MatrixXd state_cov_fixed = (state_server.state_cov +\t\t// QXC\uff1a\u4fdd\u6301\u5bf9\u79f0\u6027\n      state_server.state_cov.transpose()) / 2.0;\n  state_server.state_cov = state_cov_fixed;\n\n  // Update the state correspondes to null space.\t// QXC\uff1a\u8fd9\u6837\u770b\u6765\uff0c\u8fd9\u4e2a\u6240\u8c13\u7684null space\u4e0d\u8fc7\u5c31\u662f\u4fdd\u5b58\u4e0a\u4e00\u65f6\u523b\u7684\u72b6\u6001\u7f62\u4e86\u3002\u3002\n  imu_state.orientation_null = imu_state.orientation;\n  imu_state.position_null = imu_state.position;\n  imu_state.velocity_null = imu_state.velocity;\n\n  // Update the state info\n  state_server.imu_state.time = time;       // QXC\uff1aimu\u72b6\u6001\u65f6\u95f4\u66f4\u65b0\u5230\u9012\u63a8\u5b8c\u7684\u8fd9\u6761IMU\u6570\u636e\u65f6\u95f4\n  return;\n}\n\n// \u8fdb\u884c\u60ef\u6027\u9012\u63a8\uff0c\u5176\u4e2d\u59ff\u6001\u56db\u5143\u6570\u91c7\u7528\u6bd5\u5361\u6cd5\u66f4\u65b0\uff0c\u901f\u5ea6\u548c\u4f4d\u7f6e\u91c7\u7528\u5300\u52a0\u901f\u5ea6\u5047\u8bbe\u76844\u9636LK\u6cd5\nvoid MsckfVio::predictNewState(const double& dt,\n    const Vector3d& gyro,\n    const Vector3d& acc) {\n\n  // TODO: Will performing the forward integration using\n  //    the inverse of the quaternion give better accuracy?\n  double gyro_norm = gyro.norm();\n  Matrix4d Omega = Matrix4d::Zero();\n  Omega.block<3, 3>(0, 0) = -skewSymmetric(gyro);\n  Omega.block<3, 1>(0, 3) = gyro;\n  Omega.block<1, 3>(3, 0) = -gyro;\n\n  Vector4d& q = state_server.imu_state.orientation;\n  Vector3d& v = state_server.imu_state.velocity;\n  Vector3d& p = state_server.imu_state.position;\n\n  // Some pre-calculation\n  Vector4d dq_dt, dq_dt2;\n  if (gyro_norm > 1e-5) {\n    dq_dt = (cos(gyro_norm*dt*0.5)*Matrix4d::Identity() +\n      1/gyro_norm*sin(gyro_norm*dt*0.5)*Omega) * q;\t// QXC\uff1a\u56db\u5143\u6570\u7684\u6bd5\u5361\u6cd5\u66f4\u65b0\uff0c\u53c2\u89c1\u79e6\u6c38\u5143\u300a\u60ef\u6027\u5bfc\u822a\u300b\u7b2c\u4e00\u7248P301\u5f0f(9.2.52)\uff0c\u6ce8\u610f\u89d2\u589e\u91cf\u7684\u8ba1\u7b97\n    dq_dt2 = (cos(gyro_norm*dt*0.25)*Matrix4d::Identity() +\n      1/gyro_norm*sin(gyro_norm*dt*0.25)*Omega) * q;\t// QXC\uff1adt/2\u65f6\u7684\u56db\u5143\u6570\u6bd5\u5361\u6cd5\u66f4\u65b0\n  }\n  else {\t// QXC\uff1a\u5f53\u89d2\u589e\u91cf\u5f88\u5c0f\u65f6\u7684\u8fd1\u4f3c\uff0c\u5b9e\u90e8\u9879\u6ca1\u6709\u505a\u8fd1\u4f3c\uff0c\u865a\u90e8\u9879\u4f7f\u7528\u4e86\u6d1b\u5fc5\u8fbe\u6cd5\u5219\uff01\n    dq_dt = (Matrix4d::Identity()+0.5*dt*Omega) *\n      cos(gyro_norm*dt*0.5) * q;\n    dq_dt2 = (Matrix4d::Identity()+0.25*dt*Omega) *\n      cos(gyro_norm*dt*0.25) * q;\n  }\n  Matrix3d dR_dt_transpose = quaternionToRotation(dq_dt).transpose();\n  Matrix3d dR_dt2_transpose = quaternionToRotation(dq_dt2).transpose();\n\n  // k1 = f(tn, yn)\n  Vector3d k1_v_dot = quaternionToRotation(q).transpose()*acc +\n    IMUState::gravity;\n  Vector3d k1_p_dot = v;\n\t\t\t\t\t// QXC\uff1a\u8fd9\u91cc\u76844\u9636LK\u6cd5\u7528\u4e86\u5300\u52a0\u901f\u5ea6\u5047\u8bbe\uff0c\u5373\u8ba4\u4e3a\u524d\u4e00\u65f6\u523b\u7684\u52a0\u901f\u5ea6\u548c\u5f53\u524d\u65f6\u523b\u76f8\u7b49\uff01\n  // k2 = f(tn+dt/2, yn+k1*dt/2)\n  Vector3d k1_v = v + k1_v_dot*dt/2;\n  Vector3d k2_v_dot = dR_dt2_transpose*acc +\n    IMUState::gravity;\n  Vector3d k2_p_dot = k1_v;\n\n  // k3 = f(tn+dt/2, yn+k2*dt/2)\n  Vector3d k2_v = v + k2_v_dot*dt/2;\n  Vector3d k3_v_dot = dR_dt2_transpose*acc +\n    IMUState::gravity;\n  Vector3d k3_p_dot = k2_v;\n\n  // k4 = f(tn+dt, yn+k3*dt)\n  Vector3d k3_v = v + k3_v_dot*dt;\n  Vector3d k4_v_dot = dR_dt_transpose*acc +\n    IMUState::gravity;\n  Vector3d k4_p_dot = k3_v;\n\n  // yn+1 = yn + dt/6*(k1+2*k2+2*k3+k4)\n  q = dq_dt;\t\t\t\t// QXC\uff1a\u6240\u8c13\u76844\u9636LK\u6cd5\u53ea\u9488\u5bf9\u901f\u5ea6\u548c\u4f4d\u7f6e\u4f7f\u7528\uff0c\u5e76\u672a\u9488\u5bf9\u59ff\u6001\u505a\uff0c\u59ff\u6001\u53ea\u7528\u4e86\u524d\u9762\u7684\u6bd5\u5361\u6cd5\u66f4\u65b0\n  quaternionNormalize(q);\t// QXC\uff1a\u6765\u81ea\u672c\u5de5\u7a0b\u4e2d\u7684math_utils.hpp\n  v = v + dt/6*(k1_v_dot+2*k2_v_dot+2*k3_v_dot+k4_v_dot);\n  p = p + dt/6*(k1_p_dot+2*k2_p_dot+2*k3_p_dot+k4_p_dot);\n\n  return;\n}\n\n// \u6839\u636eIMU\u7684\u72b6\u6001\u8ba1\u7b97\u76f8\u673a\u72b6\u6001\uff0c\u540c\u65f6\u66f4\u65b0\u589e\u5e7f\u534f\u65b9\u5dee\u77e9\u9635\nvoid MsckfVio::stateAugmentation(const double& time) {\n\n  const Matrix3d& R_i_c = state_server.imu_state.R_imu_cam0;\t// QXC\uff1a\u672c\u7a0b\u5e8f\u4e2d\u7684R_a_b\u7406\u89e3\u4e3aa\u7cfb\u5230b\u7cfb\u7684\u65cb\u8f6c\u77e9\u9635\n  const Vector3d& t_c_i = state_server.imu_state.t_cam0_imu;\t// QXC\uff1a\u672c\u7a0b\u5e8f\u4e2d\u7684t_a_b\u7406\u89e3\u4e3ab\u7cfb\u4e0ba\u7cfb\u539f\u70b9\u7684\u5750\u6807\uff08\u4e0eorbslam\u4e2d\u4f4d\u59ffR-t\u4e2d\u7684t\u4e0d\u540c\uff09\n\n  // Add a new camera state to the state server.\t// QXC\uff1a\u53ef\u4ee5\u770b\u51fa\uff0c\u672c\u7a0b\u5e8f\u4e0d\u505a\u4efb\u4f55\u65f6\u95f4\u5bf9\u51c6\uff0c\u76f4\u63a5\u7528\u6bcf\u5e27\u56fe\u50cf\u524d\u6700\u8fd1\u7684\u4e00\u4e2aIMU\u72b6\u6001\u6362\u7b97CAM\u72b6\u6001\n  Matrix3d R_w_i = quaternionToRotation(\n      state_server.imu_state.orientation);      // QXC\uff1aquaternionToRotation\u65b9\u6cd5\u4e3a\u672c\u7a0b\u5e8f\u81ea\u5e26\uff0c\u6b64\u5904\u8fd4\u56de\u7684\u53c2\u6570\u662fC_w2b\n  Matrix3d R_w_c = R_i_c * R_w_i;\n  Vector3d t_c_w = state_server.imu_state.position +\n    R_w_i.transpose()*t_c_i;\n\n  state_server.cam_states[state_server.imu_state.id] =\n    CAMState(state_server.imu_state.id);\n  CAMState& cam_state = state_server.cam_states[\n    state_server.imu_state.id];\n\n  cam_state.time = time;\n  cam_state.orientation = rotationToQuaternion(R_w_c);\n  cam_state.position = t_c_w;\n\n  cam_state.orientation_null = cam_state.orientation;\n  cam_state.position_null = cam_state.position;\n\n  // Update the covariance matrix of the state.\n  // To simplify computation, the matrix J below is the nontrivial block\n  // in Equation (16) in \"A Multi-State Constraint Kalman Filter for Vision\n  // -aided Inertial Navigation\".\n  Matrix<double, 6, 21> J = Matrix<double, 6, 21>::Zero();\n  J.block<3, 3>(0, 0) = R_i_c;\n  J.block<3, 3>(0, 15) = Matrix3d::Identity();\t\t// QXC\uff1a\u8fd9\u91cc\u662f\u5173\u4e8eq_c_i\u7684Jacobian\uff0c\u6050\u6015\u4e0d\u5bf9\uff0c\u5e94\u5f53\u662f\u3002\u3002\n  J.block<3, 3>(3, 0) = skewSymmetric(R_w_i.transpose()*t_c_i);\n  //J.block<3, 3>(3, 0) = -R_w_i.transpose()*skewSymmetric(t_c_i);\n  J.block<3, 3>(3, 12) = Matrix3d::Identity();\n  J.block<3, 3>(3, 18) = Matrix3d::Identity();\t\t// QXC\uff1a\u8fd9\u91cc\u662f\u5173\u4e8ep_c_i\u7684Jacobian\uff0c\u6050\u6015\u4e0d\u5bf9\uff0c\u5e94\u5f53\u662fR_w_i.transpose()\n\n  // Resize the state covariance matrix.\n  size_t old_rows = state_server.state_cov.rows();\n  size_t old_cols = state_server.state_cov.cols();\n  state_server.state_cov.conservativeResize(old_rows+6, old_cols+6);\n\n  // Rename some matrix blocks for convenience.\n  const Matrix<double, 21, 21>& P11 =\n    state_server.state_cov.block<21, 21>(0, 0);\n  const MatrixXd& P12 =\n    state_server.state_cov.block(0, 21, 21, old_cols-21);\n\n  // Fill in the augmented state covariance.\n  state_server.state_cov.block(old_rows, 0, 6, old_cols) << J*P11, J*P12;\t// QXC\uff1aPIC\uff08\u7684\u8f6c\u7f6e\uff09\u6700\u521d\u662f\u7531J*PIIkk\u8ba1\u7b97\u5f97\u5230\u7684\u3002\u7c7b\u4f3c\u6d4b\u91cf\u503c\u4e0e\u72b6\u6001\u7684\u534f\u65b9\u5dee\n  state_server.state_cov.block(0, old_cols, old_rows, 6) =\n    state_server.state_cov.block(old_rows, 0, 6, old_cols).transpose();\n  state_server.state_cov.block<6, 6>(old_rows, old_cols) =\n    J * P11 * J.transpose();\n\n  // Fix the covariance to be symmetric\n  MatrixXd state_cov_fixed = (state_server.state_cov +\n      state_server.state_cov.transpose()) / 2.0;\n  state_server.state_cov = state_cov_fixed;\n\n  return;\n}\n\n// \u4f9d\u636e\u89c6\u89c9\u524d\u7aef\u53d1\u6765\u7684feature\uff08\u7279\u5f81\u70b9\u5df2\u7ecf\u8fdb\u884c\u4e86\u76f8\u5173\u5904\u7406\uff0c\u4e0d\u540c\u7684\u7279\u5f81\u70b9\u6709\u4e0d\u540cID\uff09\u6d88\u606f\uff0c\u4e3amap_server\u6dfb\u52a0\u65b0\u7684\u89c2\u6d4b\uff08\u67d0ID\u7279\u5f81\u70b9\u5728\u67d0ID\u72b6\u6001\u4e0b\u7684\u50cf\u7d20\u5750\u6807\uff09\nvoid MsckfVio::addFeatureObservations(\n    const CameraMeasurementConstPtr& msg) {\n\n  StateIDType state_id = state_server.imu_state.id;\n  int curr_feature_num = map_server.size();\n  int tracked_feature_num = 0;\n\n  // Add new observations for existing features or new\n  // features in the map server.\n  for (const auto& feature : msg->features) {\n    if (map_server.find(feature.id) == map_server.end()) {\t// QXC\uff1a\u89c6\u89c9\u524d\u7aef\u5904\u7406\u5e94\u5f53\u662f\u5c06\u6240\u6709\u7684\u7279\u5f81\u90fd\u7f16\u53f7\u4e86\uff0c\u5982\u679c\u6ca1\u6709\u548c\u539f\u6765\u7684\u5339\u914d\u7ed3\u679c\uff0c\u5c31\u65b0\u589e\u4e00\u4e2a\u7f16\u53f7\n      // This is a new feature.\n      map_server[feature.id] = Feature(feature.id);\n      map_server[feature.id].observations[state_id] =\n        Vector4d(feature.u0, feature.v0,\n            feature.u1, feature.v1);    // QXC\uff1a\u672c\u5de5\u7a0b\u4e3a\u53cc\u76ee\u65b9\u5f0f\n    } else {\n      // This is an old feature.\n      map_server[feature.id].observations[state_id] =\n        Vector4d(feature.u0, feature.v0,\n            feature.u1, feature.v1);\n      ++tracked_feature_num;\n    }\n  }\n\n  tracking_rate =\t\t\t\t\t// QXC\uff1a\u8ddf\u8e2a\u7387\uff0c\u8868\u793a\u65e7\u7684\u7279\u5f81\u70b9\u88ab\u8ddf\u8e2a\u4e0a\u7684\u6bd4\u4f8b\n    static_cast<double>(tracked_feature_num) /\n    static_cast<double>(curr_feature_num);\n\n  return;\n}\n\n// \u6c42\u89c2\u6d4b\u5173\u4e8ecam\u8bef\u5dee\u72b6\u6001\uff08\u59ff\u6001\u8bef\u5dee\u89d2\u3001\u4f4d\u7f6e\uff09\u548cfeature\u4f4d\u7f6e\u7684Jacobian\uff08\u6839\u636e\u6587\u732eTR_MSCKF\uff09\uff0c\u5e76\u5bf9\u83b7\u5f97\u7684Jacobian\u8fdb\u884c\u4fee\u6539\u4ee5\u6ee1\u8db3\u53ef\u89c2\u6027\u8981\u6c42\uff08\u6839\u636e\u6587\u732eOC-VINS\uff09\nvoid MsckfVio::measurementJacobian(\n    const StateIDType& cam_state_id,\n    const FeatureIDType& feature_id,\n    Matrix<double, 4, 6>& H_x, Matrix<double, 4, 3>& H_f, Vector4d& r) {\n\n  // Prepare all the required data.\n  const CAMState& cam_state = state_server.cam_states[cam_state_id];\n  const Feature& feature = map_server[feature_id];\n\n  // Cam0 pose.\n  Matrix3d R_w_c0 = quaternionToRotation(cam_state.orientation);\n  const Vector3d& t_c0_w = cam_state.position;\n\n  // Cam1 pose.\n  Matrix3d R_c0_c1 = CAMState::T_cam0_cam1.linear();\n  Matrix3d R_w_c1 = CAMState::T_cam0_cam1.linear() * R_w_c0;\n  Vector3d t_c1_w = t_c0_w - R_w_c1.transpose()*CAMState::T_cam0_cam1.translation();  // QXC\uff1aT_cam0_cam1\u8868\u793ac1\u7cfb\u4e0bc0\u7684\u4f4d\u7f6e\n\n  // 3d feature position in the world frame.\n  // And its observation with the stereo cameras.\n  const Vector3d& p_w = feature.position;   // QXC\uff1afeature.position\u7531Mour07\u7684Appendix\u7ed9\u51fa\u7684\u65b9\u6cd5\u8ba1\u7b97\u51fa\n  const Vector4d& z = feature.observations.find(cam_state_id)->second;\n\n  // Convert the feature position from the world frame to\n  // the cam0 and cam1 frame.\n  Vector3d p_c0 = R_w_c0 * (p_w-t_c0_w);\n  Vector3d p_c1 = R_w_c1 * (p_w-t_c1_w);\n\n  // Compute the Jacobians.\n  Matrix<double, 4, 3> dz_dpc0 = Matrix<double, 4, 3>::Zero();\n  dz_dpc0(0, 0) = 1 / p_c0(2);\n  dz_dpc0(1, 1) = 1 / p_c0(2);\n  dz_dpc0(0, 2) = -p_c0(0) / (p_c0(2)*p_c0(2));\n  dz_dpc0(1, 2) = -p_c0(1) / (p_c0(2)*p_c0(2));\n\n  Matrix<double, 4, 3> dz_dpc1 = Matrix<double, 4, 3>::Zero();\n  dz_dpc1(2, 0) = 1 / p_c1(2);\n  dz_dpc1(3, 1) = 1 / p_c1(2);\n  dz_dpc1(2, 2) = -p_c1(0) / (p_c1(2)*p_c1(2));\n  dz_dpc1(3, 2) = -p_c1(1) / (p_c1(2)*p_c1(2));\n\n  Matrix<double, 3, 6> dpc0_dxc = Matrix<double, 3, 6>::Zero();\n  dpc0_dxc.leftCols(3) = skewSymmetric(p_c0);\n  dpc0_dxc.rightCols(3) = -R_w_c0;\n\n  Matrix<double, 3, 6> dpc1_dxc = Matrix<double, 3, 6>::Zero();\n  dpc1_dxc.leftCols(3) = R_c0_c1 * skewSymmetric(p_c0);\n  dpc1_dxc.rightCols(3) = -R_w_c1;\n\n  Matrix3d dpc0_dpg = R_w_c0;\n  Matrix3d dpc1_dpg = R_w_c1;\n\n  H_x = dz_dpc0*dpc0_dxc + dz_dpc1*dpc1_dxc;\n  H_f = dz_dpc0*dpc0_dpg + dz_dpc1*dpc1_dpg;\n\n  // Modifty the measurement Jacobian to ensure\n  // observability constrain.\n  Matrix<double, 4, 6> A = H_x;\n  Matrix<double, 6, 1> u = Matrix<double, 6, 1>::Zero();\n  u.block<3, 1>(0, 0) = quaternionToRotation(\n      cam_state.orientation_null) * IMUState::gravity;\n  u.block<3, 1>(3, 0) = skewSymmetric(\n      p_w-cam_state.position_null) * IMUState::gravity;\n  H_x = A - A*u*(u.transpose()*u).inverse()*u.transpose();\n  H_f = -H_x.block<4, 3>(0, 3);\n\n  // Compute the residual.\n  r = z - Vector4d(p_c0(0)/p_c0(2), p_c0(1)/p_c0(2),\n      p_c1(0)/p_c1(2), p_c1(1)/p_c1(2));\n\n  return;\n}\n\n// \u6c42\u6307\u5b9a\u7684feature\u7684\u89c2\u6d4b\u5173\u4e8e\u80fd\u89c2\u6d4b\u5230\u5b83\u7684\u6240\u6709cam\u7684\u72b6\u6001\u53cafeature\u4f4d\u7f6e\u7684Jacobian\uff0c\u5e76\u8fdb\u884cnull space\u6295\u5f71\u4f7f\u5f97feature\u4f4d\u7f6e\u88abmarginalize\u6389\nvoid MsckfVio::featureJacobian(\n    const FeatureIDType& feature_id,\n    const std::vector<StateIDType>& cam_state_ids,\n    MatrixXd& H_x, VectorXd& r) {\n\n  const auto& feature = map_server[feature_id];\n\n  // Check how many camera states in the provided camera\n  // id camera has actually seen this feature.\n  vector<StateIDType> valid_cam_state_ids(0);\n  for (const auto& cam_id : cam_state_ids) {    // QXC\uff1a\u8f93\u5165\u53c2\u6570cam_state_ids\u5b9e\u9645\u4e0a\u5df2\u7ecf\u662f\u89c2\u6d4b\u5230\u5f53\u524dfeature\u7684camid\u4e86\uff0c\u4f46\u8fd9\u91cc\u53c8\u786e\u8ba4\u4e86\u4e00\u6b21\uff01\u662f\u5426\u6709\u5fc5\u8981\uff1f\uff1f\n    if (feature.observations.find(cam_id) ==\n        feature.observations.end()) continue;\n\n    valid_cam_state_ids.push_back(cam_id);\n  }\n\n  int jacobian_row_size = 0;\n  jacobian_row_size = 4 * valid_cam_state_ids.size();   // QXC\uff1a\u8fd9\u662f\u6587\u732eTR_MSCKF\u4e2d\u5f0f22\u7684\u884c\uff08\u53cc\u76ee\u60c5\u5f62\uff09\uff0c\u8fd8\u672a\u8fdb\u884cnull space marginalization\n\n  MatrixXd H_xj = MatrixXd::Zero(jacobian_row_size,\n      21+state_server.cam_states.size()*6);\n  MatrixXd H_fj = MatrixXd::Zero(jacobian_row_size, 3);\n  VectorXd r_j = VectorXd::Zero(jacobian_row_size);\n  int stack_cntr = 0;\n\n  for (const auto& cam_id : valid_cam_state_ids) {    // QXC\uff1a\u5bf9\u6240\u6709\u53ef\u89c2\u6d4b\u5230\u5f53\u524dfeature\u7684cam\uff0c\u6c42feature\u89c2\u6d4b\u5173\u4e8ecam\u72b6\u6001\u548cfeature\u4f4d\u7f6e\u7684Jacobian\n\n    Matrix<double, 4, 6> H_xi = Matrix<double, 4, 6>::Zero();\n    Matrix<double, 4, 3> H_fi = Matrix<double, 4, 3>::Zero();\n    Vector4d r_i = Vector4d::Zero();\n    measurementJacobian(cam_id, feature.id, H_xi, H_fi, r_i);   // QXC\uff1a\u8ba1\u7b97\u6d4b\u91cf\u503c\u5173\u4e8ecam\u72b6\u6001\u548cfeature\u4f4d\u7f6e\u7684Jacobian\uff0c\u540c\u65f6\u505a\u5173\u4e8e\u53ef\u89c2\u6027\u7684\u4fee\u6b63\n\n    auto cam_state_iter = state_server.cam_states.find(cam_id);\n    int cam_state_cntr = std::distance(\n        state_server.cam_states.begin(), cam_state_iter);     // QXC\uff1a\u53ef\u89c1TR_MSCKF\u5f0f22\u4e2d\u7684cam\u4f4d\u59ff\u5305\u62ec\u4e86\u6240\u6709\u88ab\u589e\u5e7f\u7684cam\n\n    // Stack the Jacobians.\n    H_xj.block<4, 6>(stack_cntr, 21+6*cam_state_cntr) = H_xi;\n    H_fj.block<4, 3>(stack_cntr, 0) = H_fi;\n    r_j.segment<4>(stack_cntr) = r_i;\n    stack_cntr += 4;\n  }\n\n  // Project the residual and Jacobians onto the nullspace\n  // of H_fj.\n  JacobiSVD<MatrixXd> svd_helper(H_fj, ComputeFullU | ComputeThinV);\n  MatrixXd A = svd_helper.matrixU().rightCols(\n      jacobian_row_size - 3);\n\n  H_x = A.transpose() * H_xj;     // QXC\uff1a\u672c\u53e5\u548c\u4e0b\u4e00\u53e5\u53c2\u7167Mour07\u5f0f23\u548c24\n  r = A.transpose() * r_j;\n\n  return;\n}\n\n// \u6839\u636eMour07\u4e2dIII-E\u90e8\u5206\u8fdb\u884cMSCKF\u7684\u6d4b\u91cf\u66f4\u65b0\uff0c\u9996\u5148\u5229\u7528QR\u5206\u89e3\u5c06\u89c2\u6d4b\u6b8b\u5dee\u65b9\u7a0b\u8fdb\u4e00\u6b65\u964d\u7ef4\uff0c\u7136\u540e\u6839\u636e\u65b0\u6b8b\u5dee\u65b9\u7a0b\u8ba1\u7b97\u5361\u5c14\u66fc\u589e\u76ca\uff0c\u8fdb\u884cIMU\u72b6\u6001\u3001cam\u72b6\u6001\u4ee5\u53caP\u9635\u66f4\u65b0\nvoid MsckfVio::measurementUpdate(\n    const MatrixXd& H, const VectorXd& r) {\n\n  if (H.rows() == 0 || r.rows() == 0) return;\n\n  // Decompose the final Jacobian matrix to reduce computational\n  // complexity as in Equation (28), (29).\n  MatrixXd H_thin;\n  VectorXd r_thin;\n\n  if (H.rows() > H.cols()) {    // QXC\uff1aH\u9635\u884c\u6570\u8d85\u8fc7\u5217\u6570\u65f6\uff0c\u624d\u901a\u8fc7H\u9635\u7684QR\u5206\u89e3\u964d\u7ef4\uff08H\u7684\u5217\u6570\u662f\u53d7IMU\u72b6\u6001\u6570\u548ccam\u72b6\u6001\u4e0a\u9650\u9650\u5236\u7684\uff0c\u4e0d\u4f1a\u8fc7\u591a\uff09\n    // Convert H to a sparse matrix.\n    SparseMatrix<double> H_sparse = H.sparseView();\n\n    // Perform QR decompostion on H_sparse.\n    SPQR<SparseMatrix<double> > spqr_helper;\n    spqr_helper.setSPQROrdering(SPQR_ORDERING_NATURAL);\n    spqr_helper.compute(H_sparse);\n\n    MatrixXd H_temp;\n    VectorXd r_temp;\n    (spqr_helper.matrixQ().transpose() * H).evalTo(H_temp);\n    (spqr_helper.matrixQ().transpose() * r).evalTo(r_temp);\n\n    H_thin = H_temp.topRows(21+state_server.cam_states.size()*6);       // QXC\uff1a\u4e3a\u4ec0\u4e48\u53ea\u53d6\u524d(21+6N)\u884c\u5462\uff1f\n    r_thin = r_temp.head(21+state_server.cam_states.size()*6);\n\n    //HouseholderQR<MatrixXd> qr_helper(H);\n    //MatrixXd Q = qr_helper.householderQ();\n    //MatrixXd Q1 = Q.leftCols(21+state_server.cam_states.size()*6);\n\n    //H_thin = Q1.transpose() * H;\n    //r_thin = Q1.transpose() * r;\n  } else {\n    H_thin = H;\n    r_thin = r;\n  }\n\n  // Compute the Kalman gain.\n  const MatrixXd& P = state_server.state_cov;\n  MatrixXd S = H_thin*P*H_thin.transpose() +\n      Feature::observation_noise*MatrixXd::Identity(\n        H_thin.rows(), H_thin.rows());\n  //MatrixXd K_transpose = S.fullPivHouseholderQr().solve(H_thin*P);\n  MatrixXd K_transpose = S.ldlt().solve(H_thin*P);\n  MatrixXd K = K_transpose.transpose();\n\n  // Compute the error of the state.\n  VectorXd delta_x = K * r_thin;\n\n  // Update the IMU state.\n  const VectorXd& delta_x_imu = delta_x.head<21>();\n\n  if (//delta_x_imu.segment<3>(0).norm() > 0.15 ||\n      //delta_x_imu.segment<3>(3).norm() > 0.15 ||\n      delta_x_imu.segment<3>(6).norm() > 0.5 ||\n      //delta_x_imu.segment<3>(9).norm() > 0.5 ||\n      delta_x_imu.segment<3>(12).norm() > 1.0) {\n    printf(\"delta velocity: %f\\n\", delta_x_imu.segment<3>(6).norm());\n    printf(\"delta position: %f\\n\", delta_x_imu.segment<3>(12).norm());\n    ROS_WARN(\"Update change is too large.\");\n    //return;\n  }\n\n  const Vector4d dq_imu =\n    smallAngleQuaternion(delta_x_imu.head<3>());\n  state_server.imu_state.orientation = quaternionMultiplication(\n      dq_imu, state_server.imu_state.orientation);\n  state_server.imu_state.gyro_bias += delta_x_imu.segment<3>(3);\n  state_server.imu_state.velocity += delta_x_imu.segment<3>(6);\n  state_server.imu_state.acc_bias += delta_x_imu.segment<3>(9);\n  state_server.imu_state.position += delta_x_imu.segment<3>(12);\n\n  const Vector4d dq_extrinsic =\n    smallAngleQuaternion(delta_x_imu.segment<3>(15));\n  state_server.imu_state.R_imu_cam0 = quaternionToRotation(\n      dq_extrinsic) * state_server.imu_state.R_imu_cam0;\n  state_server.imu_state.t_cam0_imu += delta_x_imu.segment<3>(18);\n\n  // Update the camera states.\n  auto cam_state_iter = state_server.cam_states.begin();\n  for (int i = 0; i < state_server.cam_states.size();\n      ++i, ++cam_state_iter) {\n    const VectorXd& delta_x_cam = delta_x.segment<6>(21+i*6);\n    const Vector4d dq_cam = smallAngleQuaternion(delta_x_cam.head<3>());\n    cam_state_iter->second.orientation = quaternionMultiplication(\n        dq_cam, cam_state_iter->second.orientation);\n    cam_state_iter->second.position += delta_x_cam.tail<3>();\n  }\n\n  // Update state covariance.\n  MatrixXd I_KH = MatrixXd::Identity(K.rows(), H_thin.cols()) - K*H_thin;\n  //state_server.state_cov = I_KH*state_server.state_cov*I_KH.transpose() +\n  //  K*K.transpose()*Feature::observation_noise;       // QXC\uff1a\u6709\u70b9\u5c0f\u9519\u8bef\uff0c\u5e94\u662fK*Feature::observation_noise*K.transpose()\n  state_server.state_cov = I_KH*state_server.state_cov;     // QXC\uff1a\u53c2\u8003\u79e6\u6c38\u5143\u300a\u5361\u5c14\u66fc\u6ee4\u6ce2\u4e0e\u7ec4\u5408\u5bfc\u822a\u300b\u7b2c\u4e09\u7248P34\u5f0f(2.2.4e')\n\n  // Fix the covariance to be symmetric\n  MatrixXd state_cov_fixed = (state_server.state_cov +\n      state_server.state_cov.transpose()) / 2.0;\n  state_server.state_cov = state_cov_fixed;\n\n  return;\n}\n\n// \u6ca1\u592a\u770b\u61c2\u5177\u4f53\u539f\u7406\uff0c\u4f46\u5e94\u8be5\u662f\u7528\u6765\u68c0\u6d4b\u57fa\u4e8eH\u9635\u7684\u6d4b\u91cf\u9884\u6d4b\u534f\u65b9\u5dee\u548c\u6b8b\u5deer\u662f\u5426\u5951\u5408\u7684\u65b9\u6cd5\nbool MsckfVio::gatingTest(\n    const MatrixXd& H, const VectorXd& r, const int& dof) {\n\n  MatrixXd P1 = H * state_server.state_cov * H.transpose();\n  MatrixXd P2 = Feature::observation_noise *\n    MatrixXd::Identity(H.rows(), H.rows());\n  double gamma = r.transpose() * (P1+P2).ldlt().solve(r);   // QXC\uff1a\u76f8\u5f53\u4e8e\u662f\u5728\u7b97 rT*[(P1+P2)^-1]*r\n\n  //cout << dof << \" \" << gamma << \" \" <<\n  //  chi_squared_test_table[dof] << \" \";\n\n  if (gamma < chi_squared_test_table[dof]) {\n    //cout << \"passed\" << endl;\n    return true;\n  } else {\n    //cout << \"failed\" << endl;\n    return false;\n  }\n}\n\n// \u9009\u51fa\u5f53\u524d\u5e27\u4e0d\u518d\u80fd\u8ddf\u8e2a\u5230\u7684feature\uff0c\u7b5b\u9009\u6389\u8d28\u91cf\u4e0d\u4f73\u8005\uff0c\u5229\u7528\u901a\u8fc7\u7b5b\u9009\u7684feature\u8ba1\u7b97\u6d4b\u91cfJacobian\uff0c\u7ee7\u800c\u8fdb\u884cMSCKF\u6d4b\u91cf\u66f4\u65b0\uff0c\u6700\u540e\u5c06\u8fd9\u4e9b\u4e0d\u518d\u88ab\u8ddf\u8e2a\u7684feature\u5220\u6389\u3002\n// \u6ce8\u610f\uff0c\u6700\u540e\u88ab\u5220\u9664\u7684feature\u5305\u62ec\uff1a\u5931\u6548feature\u4ee5\u53ca\u8fdb\u884c\u4e86\u6d4b\u91cf\u66f4\u65b0\u7684feature\uff0c\u9996\u5148\u5b83\u4eec\u5f97\u6ee1\u8db3\u4e0d\u88ab\u5f53\u524d\u5e27\u89c2\u6d4b\u5230\u3002\n// \u8fd8\u6709\u4e00\u4e2a\u7ec6\u8282\u662f\uff0c\u6240\u6709\u901a\u8fc7\u7b5b\u9009\u7684feature\uff0c\u5728\u8ba1\u7b97\u5b8cJacobian\u4e4b\u540e\u90fd\u5e94\u5f53\u8fdb\u884c\u95e8\u9650\u7b5b\u9009\uff08\u57fa\u4e8eJacobian\u548c\u6d4b\u91cf\u6b8b\u5dee\uff09\uff0c\u8fdb\u4e00\u6b65\u5254\u9664\u4e00\u4e9b\u8d28\u91cf\u4e0d\u597d\u7684feature\u3002\nvoid MsckfVio::removeLostFeatures() {\n\n  // Remove the features that lost track.\n  // BTW, find the size the final Jacobian matrix and residual vector.\n  int jacobian_row_size = 0;\n  vector<FeatureIDType> invalid_feature_ids(0);\n  vector<FeatureIDType> processed_feature_ids(0);\n\n  for (auto iter = map_server.begin();    // QXC\uff1a\u6839\u636eMour07\u4e2d\u7684III-E\uff0c\u7b5b\u9009\u51fa\u7684\u662f\u4e0d\u518d\u80fd\u8ddf\u8e2a\u5230\u7684\uff0c\u4e14\u80fd\u591f\u521d\u59cb\u5316\u6210\u529f\u7684feature\n      iter != map_server.end(); ++iter) {\n    // Rename the feature to be checked.\n    auto& feature = iter->second;\n\n    // Pass the features that are still being tracked.\n    if (feature.observations.find(state_server.imu_state.id) !=     // QXC\uff1a\u5f53\u67d0feature\u5728\u5f53\u524d\u72b6\u6001\u4e2d\u6709\u89c2\u6d4b\u65f6\uff0c\u8df3\u8fc7\uff08continue\uff09\n        feature.observations.end()) continue;\n    if (feature.observations.size() < 3) {        // QXC\uff1a\u5bf9\u4e8e\u5f53\u524d\u672a\u89c2\u6d4b\u5230\u7684feature\uff0c\u5982\u679c\u5b83\u5728\u5176\u4ed6\u5e27\u88ab\u89c2\u6d4b\u5230\u7684\u603b\u6b21\u6570\u5c0f\u4e8e3\uff08\u5373\u53ea\u5728\u4e24\u4e2a\u91c7\u6837\u65f6\u523b\u88ab\u89c2\u6d4b\u5230\u8fc7\uff09\uff0c\u5219\u8ba4\u4e3a\u5b83\u662f\u5931\u6548\u7684\n      invalid_feature_ids.push_back(feature.id);\n      continue;\n    }\n\n    // Check if the feature can be initialized if it\n    // has not been.\n    if (!feature.is_initialized) {      // QXC\uff1afeature\u672a\u88ab\u521d\u59cb\u5316\u65f6\u624d\u4f1a\u8fdb\u884c\u4e0b\u5217\u68c0\u67e5\n      if (!feature.checkMotion(state_server.cam_states)) {\n        invalid_feature_ids.push_back(feature.id);      // QXC\uff1a\u5f53feature\u5728\u89c2\u6d4b\u5230\u5176\u7684\u9996\u672b\u4e24\u5e27\u4e2d\u53cd\u6620\u7684\u89c6\u5dee\u8f83\u5c0f\u65f6\uff0c\u8ba4\u4e3a\u5b83\u662f\u5931\u6548\u7684\n        continue;\n      } else {\n        if(!feature.initializePosition(state_server.cam_states)) {      // QXC\uff1a\u5c1d\u8bd5\u5bf9feature\u7684\u4f4d\u7f6e\u8fdb\u884c\u8ba1\u7b97\uff08\u5229\u7528Mour07\u4e2dAppendix\u7ed9\u51fa\u7684\u65b9\u6cd5\uff09\n          invalid_feature_ids.push_back(feature.id);    // QXC\uff1afeature\u521d\u59cb\u5316\u5931\u8d25\u65f6\u4e5f\u8ba4\u4e3a\u5b83\u662f\u5931\u6548\u7684\n          continue;\n        }\n      }\n    }\n\n    // QXC\uff1a\u6765\u5230\u8fd9\u91cc\u8bf4\u660e\u8fd9\u4e2afeature\u662f\u5f53\u524d\u672a\u89c2\u6d4b\u5230\uff0c\u4f46\u5728\u5176\u4ed6\u65f6\u523b\u89c2\u6d4b\u6b21\u6570\u8d85\u8fc72\u6b21\uff0c\u4e14\u6210\u529f\u521d\u59cb\u5316\u7684\n\n    jacobian_row_size += 4*feature.observations.size() - 3;     // QXC\uff1a\u53cc\u76ee\u6240\u4ee5\u4e58\u4ee54\uff0c\u4f46\u4e3a\u4ec0\u4e48\u8981\u51cf3\u5462\uff1f\u8fd9\u91cc\u5e94\u8be5\u662f\u8ba1\u7b97\u8fdb\u884c\u4e86nullspace\u8fb9\u7f18\u5316\u540e\u7684H\u5c3a\u5bf8\uff0c\u56e0\u6b64\u8981\u51cf\u53bb3\n    processed_feature_ids.push_back(feature.id);\n  }\n\n  //cout << \"invalid/processed feature #: \" <<\n  //  invalid_feature_ids.size() << \"/\" <<\n  //  processed_feature_ids.size() << endl;\n  //cout << \"jacobian row #: \" << jacobian_row_size << endl;\n\n  // Remove the features that do not have enough measurements.\n  for (const auto& feature_id : invalid_feature_ids)    // QXC\uff1a\u79fb\u9664\u5931\u6548\u7279\u5f81\uff0c\u5305\u62ec\u53ea\u89c2\u6d4b\u52302\u6b21\u7684\u3001\u89c6\u5dee\u8fc7\u5c0f\u7684\u4ee5\u53ca\u521d\u59cb\u5316\u4f4d\u7f6e\u5931\u8d25\u7684\n    map_server.erase(feature_id);\n\n  // Return if there is no lost feature to be processed.\n  if (processed_feature_ids.size() == 0) return;    // QXC\uff1a\u6839\u636eMour07\u4e2dIII-E\uff0c\u8981\u5904\u7406\u7684\u662f\u4e0d\u518d\u80fd\u8ddf\u8e2a\u5230\u7684feature\n\n  MatrixXd H_x = MatrixXd::Zero(jacobian_row_size,\n      21+6*state_server.cam_states.size());\n  VectorXd r = VectorXd::Zero(jacobian_row_size);\n  int stack_cntr = 0;\n\n  // Process the features which lose track.\n  for (const auto& feature_id : processed_feature_ids) {    // QXC\uff1a\u6c42\u53d6\u6240\u6709\u9009\u51fa\u7684feature\u5bf9\u5e94\u7684Jacobian\uff0c\u5c06\u5b83\u4eec\u5806\u53e0\u8d77\u6765\n    auto& feature = map_server[feature_id];\n\n    vector<StateIDType> cam_state_ids(0);\n    for (const auto& measurement : feature.observations)\n      cam_state_ids.push_back(measurement.first);\n\n    MatrixXd H_xj;\n    VectorXd r_j;\n    featureJacobian(feature.id, cam_state_ids, H_xj, r_j);    // QXC\uff1a\u6c42\u67d0\u4e2afeature\u89c2\u6d4b\u76f8\u5173\u7684Jacobian\uff0c\u8fdb\u884cnull space marginalization\n\n    if (gatingTest(H_xj, r_j, cam_state_ids.size()-1)) {    // QXC\uff1a\u7528\u95e8\u9650\u6d4b\u8bd5\u68c0\u6d4b\u57fa\u4e8eH_xj\u7684\u6d4b\u91cf\u9884\u6d4b\u534f\u65b9\u5dee\u548c\u6b8b\u5dee\u7684\u5173\u7cfb\u662f\u5426\u5408\u7406\n      H_x.block(stack_cntr, 0, H_xj.rows(), H_xj.cols()) = H_xj;\n      r.segment(stack_cntr, r_j.rows()) = r_j;\n      stack_cntr += H_xj.rows();\n    }\n\n    // Put an upper bound on the row size of measurement Jacobian,\n    // which helps guarantee the executation time.\n    if (stack_cntr > 1500) break;\n  }\n\n  H_x.conservativeResize(stack_cntr, H_x.cols());   // QXC\uff1a\u91cd\u65b0\u5b9a\u4e49\u77e9\u9635\u7ef4\u6570\uff0c\u56e0\u4e3a\u6709\u7684feature\u6ca1\u901a\u8fc7gatingtest\n  r.conservativeResize(stack_cntr);                 //      \u6216\u8005\u6709\u7684feature\u5728featureJacobian\u4e2d\u4e8c\u6b21\u786e\u8ba4\u89c2\u6d4bcam\u53ef\u80fd\u4f1a\u51cf\u5c11cam\u6570\u91cf\n\n  // Perform the measurement update step.\n  measurementUpdate(H_x, r);        // QXC\uff1a\u6839\u636eMour07\u4e2dIII-E\u90e8\u5206\u8fdb\u884cMSCKF\u7684\u6d4b\u91cf\u66f4\u65b0\n\n  // Remove all processed features from the map.\n  for (const auto& feature_id : processed_feature_ids)      // QXC\uff1a\u8fd9\u4e9b\u6d4b\u91cf\u4e0d\u518d\u88ab\u89c2\u6d4b\u5230\uff0c\u5c06\u5b83\u4eec\u79fb\u9664\n    map_server.erase(feature_id);\n\n  return;\n}\n\n// \u6311\u9009\u51fa\u4e24\u6761\u5197\u4f59cam\u72b6\u6001\uff0c\u89c4\u5219\u4e0eMour07\u7684III-E\u90e8\u5206\u4e0d\u7b26\uff0c\u5728\u672c\u5de5\u7a0b\u5bf9\u5e94\u6587\u732e\u7684III-D\u4e2d\u8fdb\u884c\u4e86\u8bf4\u660e\nvoid MsckfVio::findRedundantCamStates(\n    vector<StateIDType>& rm_cam_state_ids) {\n\n  // Move the iterator to the key position.\n  auto key_cam_state_iter = state_server.cam_states.end();\n  for (int i = 0; i < 4; ++i)\n    --key_cam_state_iter;\n  auto cam_state_iter = key_cam_state_iter;\n  ++cam_state_iter;\n  auto first_cam_state_iter = state_server.cam_states.begin();\n\n  // Pose of the key camera state.\n  const Vector3d key_position =\n    key_cam_state_iter->second.position;\n  const Matrix3d key_rotation = quaternionToRotation(\n      key_cam_state_iter->second.orientation);\n\n  // Mark the camera states to be removed based on the\n  // motion between states.\n  for (int i = 0; i < 2; ++i) {\n    const Vector3d position =\n      cam_state_iter->second.position;\n    const Matrix3d rotation = quaternionToRotation(\n        cam_state_iter->second.orientation);\n\n    double distance = (position-key_position).norm();\n    double angle = AngleAxisd(\n        rotation*key_rotation.transpose()).angle();\n\n    //if (angle < 0.1745 && distance < 0.2 && tracking_rate > 0.5) {\n    if (angle < 0.2618 && distance < 0.4 && tracking_rate > 0.5) {  // QXC\uff1a\u5982\u679c\u8fd9\u4e2a\u6761\u4ef6\u7b2c\u4e00\u6b21\u5c31\u4e0d\u6ee1\u8db3\uff0c\u5219\u4f1a\u9009\u62e9\u6700\u65e9\u7684\u4e24\u5e27\u72b6\u6001\n      rm_cam_state_ids.push_back(cam_state_iter->first);\n      ++cam_state_iter;\n    } else {\n      rm_cam_state_ids.push_back(first_cam_state_iter->first);\n      ++first_cam_state_iter;\n    }\n  }\n\n  // Sort the elements in the output vector.\n  sort(rm_cam_state_ids.begin(), rm_cam_state_ids.end());\n\n  return;\n}\n\n// \u5f53\u6269\u7ef4\u7684cam\u72b6\u6001\u6570\u91cf\u8fbe\u5230\u6700\u5927\u5c3a\u5bf8\u65f6\uff0c\u9009\u53d6\u82e5\u5e72\uff08\u76ee\u524d\u4e3a2\uff09\u6761cam\u72b6\u6001\u6765\u5220\u9664\uff0c\u4ee5\u6e05\u7406buffer\uff0c\u5728\u6240\u6709feature\u4e2d\u627e\u5230\u81f3\u5c11\u80fd\u88ab\u5176\u4e2d2\u5e27\u89c2\u6d4b\u5230\uff0c\u4e14\u6210\u529f\u521d\u59cb\u5316\u7684feature\uff0c\n// \u57fa\u4e8e\u8fd9\u4e9bfeature\u5173\u4e8e\u8981\u88ab\u5220\u9664\u7684\u5e27\u4e2d\u76f8\u5e94\u7684\u89c2\u6d4b\u8fdb\u884cMSCKF\u6d4b\u91cf\u66f4\u65b0\u3002\u6700\u540e\u5728\u534f\u65b9\u5dee\u77e9\u9635\u4e2d\u53bb\u9664\u4e0e\u8fd9\u4e9b\u5e27\u76f8\u5173\u7684\u7ef4\u5ea6\u3002\n// \u6ce8\u610f\uff0c\u6240\u6709feature\u5173\u4e8e\u8981\u88ab\u5254\u9664\u7684\u5e27\u7684\u89c2\u6d4b\u90fd\u5c06\u88ab\u5220\u9664\uff0c\u76f8\u5f53\u4e8e\u5b8c\u5168\u6d88\u9664\u8981\u88ab\u5254\u9664\u5e27\u7684\u6b8b\u4f59\u5f71\u54cd\u3002\nvoid MsckfVio::pruneCamStateBuffer() {\n\n  if (state_server.cam_states.size() < max_cam_state_size)      // QXC\uff1a\u5f53\u6269\u7ef4\u7684cam\u72b6\u6001\u8d85\u8fc7\u6700\u5927\u6570\u91cf\u65f6\u624d\u7ee7\u7eed\n    return;\n\n  // Find two camera states to be removed.\n  vector<StateIDType> rm_cam_state_ids(0);\n  findRedundantCamStates(rm_cam_state_ids);     // QXC\uff1a\u6311\u9009\u51fa\u5197\u4f59\u7684cam\u72b6\u6001\uff08\u4e24\u6761\uff09\n\n  // Find the size of the Jacobian matrix.\n  int jacobian_row_size = 0;\n  for (auto& item : map_server) {\n    auto& feature = item.second;\n    // Check how many camera states to be removed are associated\n    // with this feature.\n    vector<StateIDType> involved_cam_state_ids(0);\n    for (const auto& cam_id : rm_cam_state_ids) {       // QXC\uff1a\u6311\u9009\u51fa\u5f53\u524dfeature\u5bf9\u5e94\u7684\u8981\u5254\u9664\u7684cam\n      if (feature.observations.find(cam_id) !=\n          feature.observations.end())\n        involved_cam_state_ids.push_back(cam_id);\n    }\n\n    if (involved_cam_state_ids.size() == 0) continue;\n    if (involved_cam_state_ids.size() == 1) {\n      feature.observations.erase(involved_cam_state_ids[0]);    // QXC\uff1a\u5982\u679cfeature\u53ea\u88ab\u8981\u88ab\u5220\u9664\u7684cam\u4e2d\u5176\u4e2d\u4e4b\u4e00\u89c2\u6d4b\u5230\uff0c\u5219\u53ea\u662f\u5728feature\u4e2d\u5254\u9664\u8be5\u89c2\u6d4b\n      continue;\n    }\n\n    if (!feature.is_initialized) {      // QXC\uff1afeature\u672a\u88ab\u521d\u59cb\u5316\u65f6\u624d\u4f1a\u8fdb\u884c\u4e0b\u5217\u68c0\u67e5\n      // Check if the feature can be initialize.\n      if (!feature.checkMotion(state_server.cam_states)) {\n        // If the feature cannot be initialized, just remove\n        // the observations associated with the camera states\n        // to be removed.       // QXC\uff1a\u5f53feature\u5728\u89c2\u6d4b\u5230\u5176\u7684\u9996\u672b\u4e24\u5e27\u4e2d\u53cd\u6620\u7684\u89c6\u5dee\u8f83\u5c0f\u65f6\uff0c\u5220\u9664\u5176\u5173\u4e8e\u8981\u5254\u9664\u7684cam\u7684\u89c2\u6d4b\n        for (const auto& cam_id : involved_cam_state_ids)\n          feature.observations.erase(cam_id);\n        continue;\n      } else {\n        if(!feature.initializePosition(state_server.cam_states)) {      // QXC\uff1a\u521d\u59cb\u5316\u5931\u8d25\u65f6\uff0c\u5220\u9664\u5176\u5173\u4e8e\u8981\u5254\u9664\u7684cam\u7684\u89c2\u6d4b\n          for (const auto& cam_id : involved_cam_state_ids)\n            feature.observations.erase(cam_id);\n          continue;\n        }\n      }\n    }\n\n    // QXC\uff1a\u4ee3\u7801\u6765\u5230\u8fd9\u91cc\u8bf4\u660e\u67d0\u4e2afeature\u80fd\u88ab\u8981\u5254\u9664\u76841\u4e2a\u4ee5\u4e0a\u7684can\u89c2\u6d4b\u5230\uff0c\u4e14\u8be5feature\u4f4d\u7f6e\u6210\u529f\u521d\u59cb\u5316\uff08\u8fc7\uff09\u3002\n\n    jacobian_row_size += 4*involved_cam_state_ids.size() - 3;\n  }\n\n  //cout << \"jacobian row #: \" << jacobian_row_size << endl;\n\n  // Compute the Jacobian and residual.\n  MatrixXd H_x = MatrixXd::Zero(jacobian_row_size,\n      21+6*state_server.cam_states.size());\n  VectorXd r = VectorXd::Zero(jacobian_row_size);\n  int stack_cntr = 0;\n\n  for (auto& item : map_server) {\n    auto& feature = item.second;\n    // Check how many camera states to be removed are associated\n    // with this feature.\n    vector<StateIDType> involved_cam_state_ids(0);\n    for (const auto& cam_id : rm_cam_state_ids) {\n      if (feature.observations.find(cam_id) !=\n          feature.observations.end())\n        involved_cam_state_ids.push_back(cam_id);\n    }\n\n    // QXC\uff1a\u7ecf\u8fc7\u524d\u9762\u7684\u4e00\u4e2afor\u5faa\u73af\u5904\u7406\uff0c\u6240\u6709\u7684feature\u8981\u4e48\u5b8c\u5168\u4e0d\u88ab\u8981\u5254\u9664\u7684cam\u89c2\u6d4b\u5230\uff0c\u8981\u4e48\u81f3\u5c11\u88ab\u4e24\u4e2a\u8981\u5254\u9664\u7684cam\u89c2\u6d4b\u5230\n\n    if (involved_cam_state_ids.size() == 0) continue;\n\n    MatrixXd H_xj;\n    VectorXd r_j;\n    featureJacobian(feature.id, involved_cam_state_ids, H_xj, r_j);   // QXC\uff1a\u6c42\u67d0\u4e2afeature\u89c2\u6d4b\u76f8\u5173\u7684Jacobian\n\n    if (gatingTest(H_xj, r_j, involved_cam_state_ids.size())) {     // QXC\uff1a\u7528\u95e8\u9650\u6d4b\u8bd5\u68c0\u6d4b\u57fa\u4e8eH_xj\u7684\u6d4b\u91cf\u9884\u6d4b\u534f\u65b9\u5dee\u548c\u6b8b\u5dee\u7684\u5173\u7cfb\u662f\u5426\u5408\u7406\n      H_x.block(stack_cntr, 0, H_xj.rows(), H_xj.cols()) = H_xj;\n      r.segment(stack_cntr, r_j.rows()) = r_j;\n      stack_cntr += H_xj.rows();\n    }\n\n    for (const auto& cam_id : involved_cam_state_ids)   // QXC\uff1a\u5904\u7406\u8fc7\u540e\u5c06feature\u4e2d\u5173\u4e8e\u8981\u5254\u9664\u7684cam\u7684\u89c2\u6d4b\u5254\u9664\n      feature.observations.erase(cam_id);\n  }\n\n  H_x.conservativeResize(stack_cntr, H_x.cols());   // QXC\uff1a\u91cd\u65b0\u5b9a\u4e49\u77e9\u9635\u7ef4\u6570\uff0c\u56e0\u4e3a\u6709\u7684feature\u6ca1\u901a\u8fc7gatingtest\uff0c\n  r.conservativeResize(stack_cntr);                 //      \u6216\u8005\u6709\u7684feature\u5728featureJacobian\u4e2d\u4e8c\u6b21\u786e\u8ba4\u89c2\u6d4bcam\u53ef\u80fd\u4f1a\u51cf\u5c11cam\u6570\u91cf\n\n  // Perform measurement update.\n  measurementUpdate(H_x, r);        // QXC\uff1a\u8fdb\u884cMSCKF\u7684\u6d4b\u91cf\u66f4\u65b0\uff0c\u53c2\u7167Mour07\u7684III-E\n\n  for (const auto& cam_id : rm_cam_state_ids) {\n    int cam_sequence = std::distance(state_server.cam_states.begin(),\n        state_server.cam_states.find(cam_id));\n    int cam_state_start = 21 + 6*cam_sequence;\n    int cam_state_end = cam_state_start + 6;\n\n    // Remove the corresponding rows and columns in the state\n    // covariance matrix.\n    if (cam_state_end < state_server.state_cov.rows()) {\n      state_server.state_cov.block(cam_state_start, 0,\n          state_server.state_cov.rows()-cam_state_end,\n          state_server.state_cov.cols()) =\n        state_server.state_cov.block(cam_state_end, 0,\n            state_server.state_cov.rows()-cam_state_end,\n            state_server.state_cov.cols());\n\n      state_server.state_cov.block(0, cam_state_start,\n          state_server.state_cov.rows(),\n          state_server.state_cov.cols()-cam_state_end) =\n        state_server.state_cov.block(0, cam_state_end,\n            state_server.state_cov.rows(),\n            state_server.state_cov.cols()-cam_state_end);\n\n      state_server.state_cov.conservativeResize(\n          state_server.state_cov.rows()-6, state_server.state_cov.cols()-6);\n    } else {    // QXC\uff1a\u6682\u65f6\u6ca1\u60f3\u660e\u767d\u4e3a\u4ec0\u4e48\u4f1a\u51fa\u73b0else\u7684\u60c5\u5f62\uff08\u5373\u8981\u5220\u9664\u7684cam\u72b6\u6001\u7684\u7ef4\u5ea6\u5df2\u7ecf\u8d85\u51fa\u4e86\u534f\u65b9\u5dee\u7ef4\u5ea6\uff09\n      state_server.state_cov.conservativeResize(\n          state_server.state_cov.rows()-6, state_server.state_cov.cols()-6);\n    }\n\n    // Remove this camera state in the state vector.\n    state_server.cam_states.erase(cam_id);\n  }\n\n  return;\n}\n\n// \u5f53IMU\u72b6\u6001\u7684\u4f4d\u7f6e\u534f\u65b9\u5dee\uff08\u7684\u6839\uff09\u8d85\u51fa\u9608\u503c\u65f6\uff08\u8bf4\u660e\u6ee4\u6ce2\u53d1\u6563\u4e86\uff09\uff0c\u8fdb\u884c\u6574\u4e2a\u7cfb\u7edf\u91cd\u7f6e\nvoid MsckfVio::onlineReset() {\n\n  // Never perform online reset if position std threshold\n  // is non-positive.\n  if (position_std_threshold <= 0) return;\n  static long long int online_reset_counter = 0;\n\n  // Check the uncertainty of positions to determine if\n  // the system can be reset.\n  double position_x_std = std::sqrt(state_server.state_cov(12, 12));\n  double position_y_std = std::sqrt(state_server.state_cov(13, 13));\n  double position_z_std = std::sqrt(state_server.state_cov(14, 14));\n\n  if (position_x_std < position_std_threshold &&\n      position_y_std < position_std_threshold &&\n      position_z_std < position_std_threshold) return;\n\n  ROS_WARN(\"Start %lld online reset procedure...\",\n      ++online_reset_counter);\n  ROS_INFO(\"Stardard deviation in xyz: %f, %f, %f\",\n      position_x_std, position_y_std, position_z_std);\n\n  // Remove all existing camera states.\n  state_server.cam_states.clear();\n\n  // Clear all exsiting features in the map.\n  map_server.clear();\n\n  // Reset the state covariance.\n  double gyro_bias_cov, acc_bias_cov, velocity_cov;\n  nh.param<double>(\"initial_covariance/velocity\",\n      velocity_cov, 0.25);\n  nh.param<double>(\"initial_covariance/gyro_bias\",\n      gyro_bias_cov, 1e-4);\n  nh.param<double>(\"initial_covariance/acc_bias\",\n      acc_bias_cov, 1e-2);\n\n  double extrinsic_rotation_cov, extrinsic_translation_cov;\n  nh.param<double>(\"initial_covariance/extrinsic_rotation_cov\",\n      extrinsic_rotation_cov, 3.0462e-4);\n  nh.param<double>(\"initial_covariance/extrinsic_translation_cov\",\n      extrinsic_translation_cov, 1e-4);\n\n  state_server.state_cov = MatrixXd::Zero(21, 21);\n  for (int i = 3; i < 6; ++i)\n    state_server.state_cov(i, i) = gyro_bias_cov;\n  for (int i = 6; i < 9; ++i)\n    state_server.state_cov(i, i) = velocity_cov;\n  for (int i = 9; i < 12; ++i)\n    state_server.state_cov(i, i) = acc_bias_cov;\n  for (int i = 15; i < 18; ++i)\n    state_server.state_cov(i, i) = extrinsic_rotation_cov;\n  for (int i = 18; i < 21; ++i)\n    state_server.state_cov(i, i) = extrinsic_translation_cov;\n\n  ROS_WARN(\"%lld online reset complete...\", online_reset_counter);\n  return;\n}\n\n// \u53d1\u5e03tf\u3001odometry\u3001\u7279\u5f81\u70b9\u4e91\u7b49\u6d88\u606f\nvoid MsckfVio::publish(const ros::Time& time) {\n\n  // Convert the IMU frame to the body frame.\n  const IMUState& imu_state = state_server.imu_state;\n  Eigen::Isometry3d T_i_w = Eigen::Isometry3d::Identity();\n  T_i_w.linear() = quaternionToRotation(\n      imu_state.orientation).transpose();\n  T_i_w.translation() = imu_state.position;\n\n  Eigen::Isometry3d T_b_w = IMUState::T_imu_body * T_i_w *\n    IMUState::T_imu_body.inverse();     // QXC\uff1a\u6ca1\u770b\u61c2\u4e3a\u4ec0\u4e48\u8fd8\u8981\u4e58\u4e2aT_imu_body\u7684\u9006\n  Eigen::Vector3d body_velocity =\n    IMUState::T_imu_body.linear() * imu_state.velocity;\n\n  // Publish tf     // QXC\uff1atf\u662f\u7528\u4e8e\u7ef4\u62a4\u4e00\u4e2a\u673a\u5668\u4eba\u4e0a\u6240\u6709\u5750\u6807\u7cfb\u95f4\u76f8\u5bf9\u53d8\u6362\u5173\u7cfb\u7684\u4e1c\u897f\n  if (publish_tf) {\n    tf::Transform T_b_w_tf;\n    tf::transformEigenToTF(T_b_w, T_b_w_tf);\n    tf_pub.sendTransform(tf::StampedTransform(\n          T_b_w_tf, time, fixed_frame_id, child_frame_id));\n  }\n\n  // Publish the odometry\n  nav_msgs::Odometry odom_msg;\n  odom_msg.header.stamp = time;\n  odom_msg.header.frame_id = fixed_frame_id;\n  odom_msg.child_frame_id = child_frame_id;\n\n  tf::poseEigenToMsg(T_b_w, odom_msg.pose.pose);\n  tf::vectorEigenToMsg(body_velocity, odom_msg.twist.twist.linear);\n\n  // Convert the covariance.\n  Matrix3d P_oo = state_server.state_cov.block<3, 3>(0, 0);\n  Matrix3d P_op = state_server.state_cov.block<3, 3>(0, 12);\n  Matrix3d P_po = state_server.state_cov.block<3, 3>(12, 0);\n  Matrix3d P_pp = state_server.state_cov.block<3, 3>(12, 12);\n  Matrix<double, 6, 6> P_imu_pose = Matrix<double, 6, 6>::Zero();\n  P_imu_pose << P_pp, P_po, P_op, P_oo;\n\n  Matrix<double, 6, 6> H_pose = Matrix<double, 6, 6>::Zero();\n  H_pose.block<3, 3>(0, 0) = IMUState::T_imu_body.linear();\n  H_pose.block<3, 3>(3, 3) = IMUState::T_imu_body.linear();\n  Matrix<double, 6, 6> P_body_pose = H_pose *\n    P_imu_pose * H_pose.transpose();\n\n  for (int i = 0; i < 6; ++i)\n    for (int j = 0; j < 6; ++j)\n      odom_msg.pose.covariance[6*i+j] = P_body_pose(i, j);\n\n  // Construct the covariance for the velocity.\n  Matrix3d P_imu_vel = state_server.state_cov.block<3, 3>(6, 6);\n  Matrix3d H_vel = IMUState::T_imu_body.linear();\n  Matrix3d P_body_vel = H_vel * P_imu_vel * H_vel.transpose();\n  for (int i = 0; i < 3; ++i)\n    for (int j = 0; j < 3; ++j)\n      odom_msg.twist.covariance[i*6+j] = P_body_vel(i, j);\n\n  odom_pub.publish(odom_msg);\n\n  // Publish the 3D positions of the features that\n  // has been initialized.\n  pcl::PointCloud<pcl::PointXYZ>::Ptr feature_msg_ptr(\n      new pcl::PointCloud<pcl::PointXYZ>());\n  feature_msg_ptr->header.frame_id = fixed_frame_id;\n  feature_msg_ptr->height = 1;\n  for (const auto& item : map_server) {\n    const auto& feature = item.second;\n    if (feature.is_initialized) {\n      Vector3d feature_position =\n        IMUState::T_imu_body.linear() * feature.position;\n      feature_msg_ptr->points.push_back(pcl::PointXYZ(\n            feature_position(0), feature_position(1), feature_position(2)));\n    }\n  }\n  feature_msg_ptr->width = feature_msg_ptr->points.size();\n\n  feature_pub.publish(feature_msg_ptr);\n\n  return;\n}\n\n} // namespace msckf_vio\n\n", "meta": {"hexsha": "93a842d1095bc86020805e352921c63ed6fc1e05", "size": 56550, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/msckf_vio.cpp", "max_stars_repo_name": "jiangmancheng/MSCKF-VIO-noted", "max_stars_repo_head_hexsha": "5d7ba9663d74853346c0859430944a84d4e717a2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-01-15T00:09:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-22T12:32:04.000Z", "max_issues_repo_path": "src/msckf_vio.cpp", "max_issues_repo_name": "jiangmancheng/MSCKF-VIO-noted", "max_issues_repo_head_hexsha": "5d7ba9663d74853346c0859430944a84d4e717a2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/msckf_vio.cpp", "max_forks_repo_name": "jiangmancheng/MSCKF-VIO-noted", "max_forks_repo_head_hexsha": "5d7ba9663d74853346c0859430944a84d4e717a2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-01-22T04:26:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-05T01:40:31.000Z", "avg_line_length": 38.0295897781, "max_line_length": 127, "alphanum_fraction": 0.7048806366, "num_tokens": 19461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.45367726198455594}}
{"text": "/*\n * cg.cpp\n *\n *  Created on: Feb 22, 2013\n *      Author: Joao Cunha <joao.cunha@ua.pt>\n */\n\n#include \"cg.h\"\n\n#include <iostream>\n\n#include <Eigen/Core>\n\nusing namespace std;\n\nnamespace libgp\n{\n\nCG::CG()\n{\n}\n\nCG::~CG()\n{\n}\n\nvoid CG::maximize(GaussianProcess* gp, size_t n, bool verbose)\n{\n\tconst double INT = 0.1; // don't reevaluate within 0.1 of the limit of the current bracket\n\tconst double EXT = 3.0; // extrapolate maximum 3 times the current step-size\n\tconst int MAX = 20;\t\t// max 20 function evaluations per line search\n\tconst double RATIO = 10;\t// maximum allowed slope ratio\n\tconst double SIG = 0.1, RHO = SIG/2;\n\t/* SIG and RHO are the constants controlling the Wolfe-\n\t   Powell conditions. SIG is the maximum allowed absolute ratio between\n\t   previous and new slopes (derivatives in the search direction), thus setting\n\t   SIG to low (positive) values forces higher precision in the line-searches.\n\t   RHO is the minimum allowed fraction of the expected (from the slope at the\n\t   initial point in the linesearch). Constants must satisfy 0 < RHO < SIG < 1.\n\t   Tuning of SIG (depending on the nature of the function to be optimized) may\n\t  speed up the minimization; it is probably not worth playing much with RHO.\n\t*/\n\n\t/* The code falls naturally into 3 parts, after the initial line search is\n\t   started in the direction of steepest descent. 1) we first enter a while loop\n\t   which uses point 1 (p1) and (p2) to compute an extrapolation (p3), until we\n\t   have extrapolated far enough (Wolfe-Powell conditions). 2) if necessary, we\n\t   enter the second loop which takes p2, p3 and p4 chooses the subinterval\n\t   containing a (local) minimum, and interpolates it, unil an acceptable point\n\t   is found (Wolfe-Powell conditions). Note, that points are always maintained\n\t   in order p0 <= p1 <= p2 < p3 < p4. 3) compute a new search direction using\n\t   conjugate gradients (Polack-Ribiere flavour), or revert to steepest if there\n\t   was a problem in the previous line-search. Return the best value so far, if\n\t   two consecutive line-searches fail, or whenever we run out of function\n\t   evaluations or line-searches. During extrapolation, the \"f\" function may fail\n\t   either with an error or returning Nan or Inf, and maxmize should handle this\n\t   gracefully.\n\t*/\n\n\n\tbool ls_failed = false;\t\t\t\t\t\t\t\t\t//prev line-search failed\n\tdouble f0 = -gp->log_likelihood();\t\t\t\t\t\t//initial negative marginal log likelihood\n\tEigen::VectorXd df0 = -gp->log_likelihood_gradient();\t//initial gradient\n\tEigen::VectorXd X = gp->covf().get_loghyper();\t\t\t//hyper parameters\n\n\tif(verbose) cout << f0 << endl;\n\n\tEigen::VectorXd s = -df0;\t\t\t\t\t\t\t\t//initial search direction\n\tdouble d0 = -s.dot(s);\t\t\t\t\t\t\t\t\t//initial slope\n\tdouble x3 = 1/(1-d0);\n\n\tdouble f3 = 0;\n\tdouble d3 = 0;\n\tEigen::VectorXd df3 = df0;\n\n\tdouble x2 = 0, x4 = 0;\n\tdouble f2 = 0, f4 = 0;\n\tdouble d2 = 0, d4 = 0;\n\n\tfor (unsigned int i = 0; i < n; ++i)\n\t{\n\t\t//copy current values\n\t\tEigen::VectorXd X0 = X;\n\t\tdouble F0 = f0;\n\t\tEigen::VectorXd dF0 = df0;\n\t\tunsigned int M = min(MAX, (int)(n-i));\n\n\t\twhile(1)\t\t\t\t\t\t\t\t\t\t\t//keep extrapolating until necessary\n\t\t{\n\t\t\tx2 = 0;\n\t\t\tf2 = f0;\n\t\t\td2 = d0;\n\t\t\tf3 = f0;\n\t\t\tdf3 = df0;\n\t\t\tdouble success = false;\n\n\t\t\twhile( !success && M>0)\n\t\t\t{\n\t\t\t\tM --;\n\t\t\t\ti++;\n\t\t\t\tgp->covf().set_loghyper(X+s*x3);\n\t\t\t\tf3 = -gp->log_likelihood();\n\t\t\t\tdf3 = -gp->log_likelihood_gradient();\n\n\t\t\t\tif(verbose) cout << f3 << endl;\n\n\t\t\t\tbool nanFound = false;\n\t\t\t\t//test NaN and Inf's\n\t\t\t\tfor (int j = 0; j < df3.rows(); ++j)\n\t\t\t\t{\n\t\t\t\t\tif(isnan(df3(j)))\n\t\t\t\t\t{\n\t\t\t\t\t\tnanFound = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif(!isnan(f3) && !isinf(f3) && !nanFound)\n\t\t\t\t\tsuccess = true;\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tx3 = (x2+x3)/2; \t\t\t\t\t\t// if fail, bissect and try again\n\t\t\t\t}\n\t\t\t}\n\t\t\t//keep best values\n\t\t\tif(f3 < F0)\n\t\t\t{\n\t\t\t\tX0 = X+s*x3;\n\t\t\t\tF0 = f3;\n\t\t\t\tdF0 = df3;\n\t\t\t}\n\n\t\t\td3 = df3.dot(s);\t\t\t\t\t\t\t\t// new slope\n\n\t\t\tif( (d3 > SIG*d0) || (f3 >  f0+x3*RHO*d0) || M == 0) // are we done extrapolating?\n\t\t\t{\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tdouble x1 = x2; double f1 = f2; double d1 = d2;\t// move point 2 to point 1\n\t\t\tx2 = x3; f2 = f3; d2 = d3;\t\t\t\t\t\t// move point 3 to point 2\n\t\t\tdouble A = 6*(f1-f2) + 3*(d2+d1)*(x2-x1);\t\t\t\t// make cubic extrapolation\n\t\t\tdouble B = 3*(f2-f1) - (2*d1+d2)*(x2-x1);\n\t\t\tx3 = x1-d1*(x2-x1)*(x2-x1)/(B+sqrt(B*B -A*d1*(x2-x1)));\n\t\t\tif(isnan(x3) || x3 < 0 || x3 > x2*EXT)\t\t\t// num prob | wrong sign | beyond extrapolation limit\n\t\t\t\tx3 = EXT*x2;\n\t\t\telse if(x3 < x2+INT*(x2-x1))\t\t\t\t\t// too close to previous point\n\t\t\t\tx3 = x2+INT*(x2-x1);\n\t\t}\n\n\t\twhile( ( (abs(d3) > -SIG*d0) || (f3 > f0+x3*RHO*d0) ) && (M > 0))\t// keep interpolating\n\t\t{\n\t\t\tif( (d3 > 0) || (f3 > f0+x3*RHO*d0) )\t\t\t// choose subinterval\n\t\t\t{\t\t\t\t\t\t\t\t\t\t\t\t// move point 3 to point 4\n\t\t\t\tx4 = x3;\n\t\t\t\tf4 = f3;\n\t\t\t\td4 = d3;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tx2 = x3;\t\t\t\t\t\t\t\t\t//move point 3 to point 2\n\t\t\t\tf2 = f3;\n\t\t\t\td2 = d3;\n\t\t\t}\n\n\t\t\tif(f4 > f0)\n\t\t\t\tx3 = x2 - (0.5*d2*(x4-x2)*(x4-x2))/(f4-f2-d2*(x4-x2));\t// quadratic interpolation\n\t\t\telse\n\t\t\t{\n\t\t\t\tdouble A = 6*(f2-f4)/(x4-x2)+3*(d4+d2);\n\t\t\t\tdouble B = 3*(f4-f2)-(2*d2+d4)*(x4-x2);\n\t\t\t\tx3 = x2+sqrt(B*B-A*d2*(x4-x2)*(x4-x2) -B)/A;\n\t\t\t}\n\n\t\t\tif(isnan(x3) || isinf(x3))\n\t\t\t\tx3 = (x2+x4)/2;\n\n\t\t\tx3 = std::max(std::min(x3, x4-INT*(x4-x2)), x2+INT*(x4-x2));\n\n\t\t\tgp->covf().set_loghyper(X+s*x3);\n\t\t\tf3 = -gp->log_likelihood();\n\t\t\tdf3 = -gp->log_likelihood_gradient();\n\n\t\t\tif(f3 < F0)\t\t\t\t\t\t\t\t\t\t\t\t// keep best values\n\t\t\t{\n\t\t\t\tX0 = X+s*x3;\n\t\t\t\tF0 = f3;\n\t\t\t\tdF0 = df3;\n\t\t\t}\n\n\t\t\tif(verbose) cout << F0 << endl;\n\n\t\t\tM--;\n\t\t\ti++;\n\t\t\td3 = df3.dot(s);\t\t\t\t\t\t\t\t\t\t// new slope\n\t\t}\n\n\t\tif( (abs(d3) < -SIG*d0) && (f3 < f0+x3*RHO*d0))\n\t\t{\n\t\t\tX = X+s*x3;\n\t\t\tf0 = f3;\n\t\t\ts = (df3.dot(df3)-df0.dot(df3)) / (df0.dot(df0))*s - df3;\t// Polack-Ribiere CG direction\n\t\t\tdf0 = df3;\t\t\t\t\t\t\t\t\t\t\t\t\t// swap derivatives\n\t\t\td3 = d0; d0 = df0.dot(s);\n\t\t\tif(verbose) cout << f0 << endl;\n\t\t\tif(d0 > 0)\t\t\t\t\t\t\t\t\t\t\t\t\t// new slope must be negative\n\t\t\t{\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// otherwise use steepest direction\n\t\t\t\ts = -df0;\n\t\t\t\td0 = -s.dot(s);\n\t\t\t}\n\n\t\t\tx3 = x3 * std::min(RATIO, d3/(d0-std::numeric_limits< double >::min()));\t// slope ratio but max RATIO\n\t\t\tls_failed = false;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// this line search did not fail\n\t\t}\n\t\telse\n\t\t{\t\t\t\t\t\t\t\t\t\t\t\t\t\t// restore best point so far\n\t\t\tX = X0;\n\t\t\tf0 = F0;\n\t\t\tdf0 = dF0;\n\n\t\t\tif(verbose) cout << f0 << endl;\n\n\t\t\tif(ls_failed || i >= n)\t\t\t\t\t\t\t\t// line search failed twice in a row\n\t\t\t\tbreak;\t\t\t\t\t\t\t\t\t\t\t// or we ran out of time, so we give up\n\n\t\t\ts = -df0;\n\t\t\td0 = -s.dot(s);\t\t\t\t\t\t\t\t\t\t// try steepest\n\t\t\tx3 = 1/(1-d0);\n\t\t\tls_failed = true;\t\t\t\t\t\t\t\t\t// this line search failed\n\t\t}\n\n\n\t}\n\tgp->covf().set_loghyper(X);\n}\n\n}\n", "meta": {"hexsha": "897f32006cf2ae2432b186da04d9755ca44448ab", "size": 6583, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/external_library/libgp/src/cg.cc", "max_stars_repo_name": "ecbaum/ugpm", "max_stars_repo_head_hexsha": "3ab6ff2dbc59642e0e9739f5f4647a906f19e333", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 89.0, "max_stars_repo_stars_event_min_datetime": "2015-02-28T12:20:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T17:15:57.000Z", "max_issues_repo_path": "src/cg.cc", "max_issues_repo_name": "Bellout/libgp", "max_issues_repo_head_hexsha": "f2bcfe7b5b6f02444ef98caf822717662c13fc88", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 212.0, "max_issues_repo_issues_event_min_datetime": "2018-09-21T10:44:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T14:33:05.000Z", "max_forks_repo_path": "src/cg.cc", "max_forks_repo_name": "Bellout/libgp", "max_forks_repo_head_hexsha": "f2bcfe7b5b6f02444ef98caf822717662c13fc88", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 58.0, "max_forks_repo_forks_event_min_datetime": "2015-03-08T09:22:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-14T10:12:31.000Z", "avg_line_length": 27.776371308, "max_line_length": 104, "alphanum_fraction": 0.5813458909, "num_tokens": 2310, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.45367726198455594}}
{"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 \"toplevelfixture.hpp\"\n#include <boost/foreach.hpp>\n#include <boost/make_shared.hpp>\n#include <boost/math/distributions/chi_squared.hpp>\n#include <boost/test/unit_test.hpp>\n#include <qle/math/deltagammavar.hpp>\n\nusing namespace QuantLib;\nusing namespace QuantExt;\n\nusing namespace boost::unit_test_framework;\nusing std::vector;\n\nnamespace {\nvoid test(const Size dim, const bool nonzeroDelta, const bool nonzeroGamma, const Size seedParam, const Size seedMc,\n          const Size paths) {\n\n    BOOST_TEST_MESSAGE(\"################ Testing delta gamma VaR, dim=\" << dim << \", delta=\" << nonzeroDelta\n                                                                        << \", gamma=\" << nonzeroGamma\n                                                                        << \", paths=\" << paths << \"\\n\");\n\n    MersenneTwisterUniformRng mt(seedParam);\n\n    // generate random covariance matrix\n\n    BOOST_TEST_MESSAGE(\"Generate transformation matrix L\");\n    Matrix L(dim, dim, 0.0);\n    Real det = 0.0;\n    do {\n        for (Size i = 0; i < dim; ++i) {\n            for (Size j = 0; j < dim; ++j) {\n                L[i][j] = mt.nextReal();\n            }\n        }\n        det = determinant(L);\n        BOOST_TEST_MESSAGE(\"... done, determinant is \" << det);\n    } while (close_enough(det, 0.0));\n\n    Matrix omega = transpose(L) * L;\n\n    // scale entries such that they have order of magnitude 0.1\n    Real num = QuantExt::detail::absMax(omega);\n    omega /= num * 10.0;\n\n    // generate random delta vector\n\n    BOOST_TEST_MESSAGE(\"Generate delta\");\n    Array delta(dim, 0.0);\n    if (nonzeroDelta) {\n        for (Size i = 0; i < dim; ++i) {\n            delta[i] = mt.nextReal() * 1000.0 - 500.0;\n        }\n    }\n\n    // generate random gamma matrix, TODO negative gammas?\n\n    BOOST_TEST_MESSAGE(\"Generate gamma\");\n    Matrix gamma(dim, dim, 0.0), shift(dim, dim, 0.0);\n    if (nonzeroGamma) {\n        for (Size i = 0; i < dim; ++i) {\n            for (Size j = 0; j < i; ++j) {\n                gamma[i][j] = gamma[j][i] = mt.nextReal() * 1000.0; // - 500.0;\n            }\n            gamma[i][i] = mt.nextReal() * 1000.0; // - 500.0;\n        }\n    }\n\n    BOOST_TEST_MESSAGE(\"delta=\" << delta);\n    if (gamma.rows() <= 20) {\n        BOOST_TEST_MESSAGE(\"\\ngamma=\\n\" << gamma);\n        BOOST_TEST_MESSAGE(\"omega=\\n\" << omega);\n    } else {\n        BOOST_TEST_MESSAGE(\"\\ngamma= too big to display (\" << gamma.rows() << \"x\" << gamma.columns() << \")\");\n        BOOST_TEST_MESSAGE(\"omega= too big to display (\" << omega.rows() << \"x\" << omega.columns() << \")\\n\");\n    }\n\n    // check results against MC simulation\n\n    std::vector<Real> quantiles;\n    quantiles.push_back(0.9);\n    quantiles.push_back(0.95);\n    quantiles.push_back(0.99);\n    quantiles.push_back(0.999);\n    quantiles.push_back(0.9999);\n\n    BOOST_TEST_MESSAGE(\"Run MC simulation...\");\n    Matrix nullGamma(dim, dim, 0.0);\n    std::vector<Real> mc1All = deltaGammaVarMc<PseudoRandom>(omega, delta, nullGamma, quantiles, paths, seedMc);\n    std::vector<Real> mc2All = deltaGammaVarMc<PseudoRandom>(omega, delta, gamma, quantiles, paths, seedMc);\n    BOOST_TEST_MESSAGE(\"MC simulation Done.\");\n\n    BOOST_TEST_MESSAGE(\"      Quantile      dVaR(MC)      dgVaR(MC)    dVaR(Mdl)\");\n    BOOST_TEST_MESSAGE(\"========================================================\");\n\n    Size i = 0;\n    BOOST_FOREACH (Real q, quantiles) {\n\n        Real mc1 = mc1All[i];\n        Real mc2 = mc2All[i++];\n\n        Real dVar = deltaVar(omega, delta, q);\n\n        BOOST_TEST_MESSAGE(std::right << std::setw(14) << q << std::setw(14) << mc1 << std::setw(14) << mc2\n                                      << std::setw(14) << dVar);\n\n        BOOST_CHECK_CLOSE(dVar, mc1, 5.0);\n    }\n\n    BOOST_TEST_MESSAGE(\"========================================================\\n\\n\");\n\n} // test\n} // anonymous namespace\n\nBOOST_FIXTURE_TEST_SUITE(QuantExtTestSuite, qle::test::TopLevelFixture)\n\nBOOST_AUTO_TEST_SUITE(DeltaGammaVarTest)\n\nBOOST_AUTO_TEST_CASE(testDeltaGammaVar) {\n\n    // TODO add more test cases (negative gammas, higher dimensions)\n\n    Size n = (Size)1E7;\n\n    test(1, true, false, 42, 42, n);\n    test(1, true, true, 42, 42, n);\n\n    test(2, true, false, 42, 42, n);\n    test(2, true, true, 42, 42, n);\n\n    test(10, true, false, 42, 42, n);\n    test(10, true, true, 42, 42, n);\n\n    // fewer paths here\n    test(100, true, false, 42, 42, (Size)1E6);\n    test(100, true, true, 42, 42, (Size)1E6);\n}\n\nBOOST_AUTO_TEST_CASE(testNegativeGamma) {\n\n    BOOST_TEST_MESSAGE(\"Testing delta gamma var for pl = -u^2, u standard normal...\");\n\n    // choose n=1, gamma=-10k, omega = 1, then the pl is -0.5*u^2 with\n    // u standard normal, in other words  -2pl is chi-squared\n    // distributed with one degree of freedom\n\n    boost::math::chi_squared_distribution<Real> chisq(1.0);\n\n    Real gamma = -10000.0;\n\n    Array delta(1, 0.0);\n    Matrix gamma_m(1, 1, gamma);\n    Matrix omega(1, 1, 1.0);\n\n    Real p = 0.99;\n\n    Real var_mc = deltaGammaVarMc<PseudoRandom>(omega, delta, gamma_m, p, 1000000, 142);\n\n    Real refVal = 0.5 * gamma * boost::math::quantile(chisq, 1.0 - p);\n\n    BOOST_TEST_MESSAGE(\"mc  = \" << var_mc);\n    BOOST_TEST_MESSAGE(\"ref = \" << refVal);\n\n    BOOST_CHECK_SMALL(std::abs(refVal - var_mc), 0.5);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "6ecd5c9bba4d4d60f5cb8bc3f6876d9aba25d837", "size": 6071, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QuantExt/test/deltagammavar.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/test/deltagammavar.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/test/deltagammavar.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": 32.4652406417, "max_line_length": 116, "alphanum_fraction": 0.6017130621, "num_tokens": 1663, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255928, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.4536772555122451}}
{"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_MAXMAG_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_MAXMAG_HPP_INCLUDED\n\n#include <boost/simd/function/abs.hpp>\n#include <boost/simd/function/max.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  BOOST_DISPATCH_OVERLOAD ( maxmag_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_< bd::arithmetic_<A0> >\n                          , bd::scalar_< bd::arithmetic_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() ( A0 a0, A0 a1) const BOOST_NOEXCEPT\n    {\n      A0 aa0 = simd::abs(a0);\n      A0 aa1 = simd::abs(a1);\n      return aa0 < aa1 ? a1 : aa1 <  aa0 ? a0 : simd::max(a0, a1);\n    }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "61e5605b592eba807b44f24ddf0169ddfbe50aeb", "size": 1284, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/scalar/function/maxmag.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/maxmag.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/maxmag.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.1, "max_line_length": 100, "alphanum_fraction": 0.5241433022, "num_tokens": 290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255928, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.4536772555122451}}
{"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_EXPONENT_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_EXPONENT_HPP_INCLUDED\n\n#include <boost/simd/detail/constant/maxexponent.hpp>\n#include <boost/simd/constant/nbmantissabits.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/function/exponentbits.hpp>\n#include <boost/simd/function/if_else_zero.hpp>\n#include <boost/simd/function/is_eqz.hpp>\n#include <boost/simd/function/is_invalid.hpp>\n#include <boost/simd/function/shr.hpp>\n#include <boost/simd/detail/math.hpp>\n#include <boost/simd/detail/dispatch/function/overload.hpp>\n#include <boost/simd/detail/dispatch/meta/as_integer.hpp>\n#include <boost/config.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  BOOST_DISPATCH_OVERLOAD ( exponent_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_< bd::integer_<A0> >\n                          )\n  {\n    using result_t = bd::as_integer_t<A0, signed>;\n    BOOST_FORCEINLINE result_t operator() ( A0) const BOOST_NOEXCEPT\n    {\n      return Zero<result_t>();\n    }\n  };\n\n#ifdef BOOST_SIMD_HAS_ILOGB\n  BOOST_DISPATCH_OVERLOAD ( exponent_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_< bd::double_<A0> >\n                          )\n  {\n    using result_t = bd::as_integer_t<A0, signed>;\n    BOOST_FORCEINLINE result_t operator() ( A0 a0) const BOOST_NOEXCEPT\n    {\n      if (is_invalid(a0) || is_eqz(a0)) return Zero<result_t>();\n      return ::ilogb(a0);\n    }\n  };\n#endif\n\n#ifdef BOOST_SIMD_HAS_ILOGBF\n  BOOST_DISPATCH_OVERLOAD ( exponent_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_< bd::single_<A0> >\n                          )\n  {\n    using result_t = bd::as_integer_t<A0, signed>;\n    BOOST_FORCEINLINE result_t operator() ( A0 a0) const BOOST_NOEXCEPT\n    {\n      if (is_invalid(a0) || is_eqz(a0)) return Zero<result_t>();\n      return ::ilogbf(a0);\n    }\n  };\n#endif\n\n  BOOST_DISPATCH_OVERLOAD ( exponent_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_< bd::floating_<A0> >\n                          )\n  {\n    using result_t = bd::as_integer_t<A0, signed>;\n    BOOST_FORCEINLINE result_t operator() ( A0 a0) const BOOST_NOEXCEPT\n    {\n      if (is_invalid(a0) || is_eqz(a0)) return Zero<result_t>();\n      const int nmb = int(Nbmantissabits<A0>());\n      const result_t x = shr(exponentbits(a0), nmb);\n      return x-if_else_zero(a0, Maxexponent<A0>());\n    }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "8b01c4c6a2a517f8c92483e519450d53c53caf17", "size": 3082, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/scalar/function/exponent.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/scalar/function/exponent.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/exponent.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": 32.7872340426, "max_line_length": 100, "alphanum_fraction": 0.5642439974, "num_tokens": 716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255928, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.453677255512245}}
{"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/*!\n * \\file\n**/\n#ifndef BOOST_SIMD_TOOLBOX_CONSTANT_CONSTANTS_MINEXPONENT_HPP_INCLUDED\n#define BOOST_SIMD_TOOLBOX_CONSTANT_CONSTANTS_MINEXPONENT_HPP_INCLUDED\n\n#include <boost/simd/include/functor.hpp>\n#include <boost/simd/sdk/meta/int_c.hpp>\n#include <boost/simd/sdk/constant/constant.hpp>\n\n/*!\n * \\ingroup boost_simd_constant\n * \\defgroup boost_simd_constant_minexponent Minexponent\n *\n * \\par Description\n * Constant Minexponent\n *\n * \\par Header file\n *\n * \\code\n * #include <nt2/include/functions/minexponent.hpp>\n * \\endcode\n *\n *\n * \\synopsis\n *\n * \\code\n * namespace boost::simd\n * {\n *   template <class T,class A0>\n *     meta::call<tag::minexponent_(A0)>::type\n *     Minexponent();\n * }\n * \\endcode\n *\n *\n * \\param T template parameter of Minexponent\n *\n * \\return type T value\n *\n *\n**/\n\nnamespace boost { namespace simd\n{\n  namespace tag\n  {\n    /*!\n     * \\brief Define the tag Minexponent of functor Minexponent\n     *        in namespace boost::simd::tag for toolbox boost.simd.constant\n    **/\n    struct Minexponent : ext::pure_constant_<Minexponent>\n    {\n      template<class Target, class Dummy=void>\n      struct  apply : meta::int_c<typename Target::type,0> {};\n    };\n\n  template<class T, class Dummy>\n  struct  Minexponent::apply<boost::dispatch::meta::single_<T>,Dummy>\n        : meta::int_c<boost::simd::int32_t,-126> {};\n\n  template<class T, class Dummy>\n  struct  Minexponent::apply<boost::dispatch::meta::double_<T>,Dummy>\n        : meta::int_c<boost::simd::int64_t,-1022> {};\n  }\n\n  BOOST_SIMD_CONSTANT_IMPLEMENTATION(boost::simd::tag::Minexponent, Minexponent)\n} }\n\n#include <boost/simd/sdk/constant/common.hpp>\n\n#endif\n", "meta": {"hexsha": "cde8330d46495d4bba4405127aa1d5be28fb3de2", "size": 2161, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/constant/include/boost/simd/toolbox/constant/constants/minexponent.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/constant/include/boost/simd/toolbox/constant/constants/minexponent.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/constant/include/boost/simd/toolbox/constant/constants/minexponent.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": 26.6790123457, "max_line_length": 80, "alphanum_fraction": 0.6219342897, "num_tokens": 543, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419958239132, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.45360759217830005}}
{"text": "//  (C) Copyright 2006 Eric Niebler, Olivier Gygi\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 <boost/test/unit_test.hpp>\r\n#include <boost/test/floating_point_comparison.hpp>\r\n#include <boost/random.hpp>\r\n#include <boost/accumulators/accumulators.hpp>\r\n#include <boost/accumulators/statistics/stats.hpp>\r\n#include <boost/accumulators/statistics/median.hpp>\r\n\r\nusing namespace boost;\r\nusing namespace unit_test;\r\nusing namespace accumulators;\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// test_stat\r\n//\r\nvoid test_stat()\r\n{\r\n    // two random number generators\r\n    double mu = 1.;\r\n    boost::lagged_fibonacci607 rng;\r\n    boost::normal_distribution<> mean_sigma(mu,1);\r\n    boost::variate_generator<boost::lagged_fibonacci607&, boost::normal_distribution<> > normal(rng, mean_sigma);\r\n\r\n    accumulator_set<double, stats<tag::median(with_p_square_quantile) > > acc;\r\n    accumulator_set<double, stats<tag::median(with_density) > >\r\n        acc_dens( density_cache_size = 10000, density_num_bins = 1000 );\r\n    accumulator_set<double, stats<tag::median(with_p_square_cumulative_distribution) > >\r\n        acc_cdist( p_square_cumulative_distribution_num_cells = 100 );\r\n\r\n    for (std::size_t i=0; i<100000; ++i)\r\n    {\r\n        double sample = normal();\r\n        acc(sample);\r\n        acc_dens(sample);\r\n        acc_cdist(sample);\r\n    }\r\n\r\n    BOOST_CHECK_CLOSE(1., median(acc), 1.);\r\n    BOOST_CHECK_CLOSE(1., median(acc_dens), 1.);\r\n    BOOST_CHECK_CLOSE(1., median(acc_cdist), 3.);\r\n}\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// init_unit_test_suite\r\n//\r\ntest_suite* init_unit_test_suite( int argc, char* argv[] )\r\n{\r\n    test_suite *test = BOOST_TEST_SUITE(\"median test\");\r\n\r\n    test->add(BOOST_TEST_CASE(&test_stat));\r\n\r\n    return test;\r\n}\r\n", "meta": {"hexsha": "366349a9d5bcc2595aa675b60b711d253c290c64", "size": 1994, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/accumulators/test/median.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/accumulators/test/median.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/accumulators/test/median.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.3793103448, "max_line_length": 114, "alphanum_fraction": 0.6404212638, "num_tokens": 454, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419958239132, "lm_q2_score": 0.6548947155710233, "lm_q1q2_score": 0.4536075828476475}}
{"text": "// Copyright Abel Sinkovics (abel@sinkovics.hu)  2015.\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#include <boost/metaparse/string.hpp>\r\n#include <boost/metaparse/sequence_apply.hpp>\r\n#include <boost/metaparse/last_of.hpp>\r\n#include <boost/metaparse/int_.hpp>\r\n#include <boost/metaparse/token.hpp>\r\n#include <boost/metaparse/lit_c.hpp>\r\n#include <boost/metaparse/one_of.hpp>\r\n#include <boost/metaparse/empty.hpp>\r\n#include <boost/metaparse/entire_input.hpp>\r\n#include <boost/metaparse/build_parser.hpp>\r\n\r\n#include <boost/rational.hpp>\r\n\r\n#include <boost/config.hpp>\r\n\r\n#include <boost/mpl/int.hpp>\r\n\r\n#include <iostream>\r\n\r\nusing boost::metaparse::sequence_apply2;\r\nusing boost::metaparse::last_of;\r\nusing boost::metaparse::int_;\r\nusing boost::metaparse::token;\r\nusing boost::metaparse::lit_c;\r\nusing boost::metaparse::one_of;\r\nusing boost::metaparse::empty;\r\nusing boost::metaparse::entire_input;\r\nusing boost::metaparse::build_parser;\r\n\r\ntemplate <class Num, class Denom>\r\nstruct rational\r\n{\r\n  typedef rational type;\r\n\r\n  static boost::rational<int> run()\r\n  {\r\n    return boost::rational<int>(Num::type::value, Denom::type::value);\r\n  }\r\n};\r\n\r\ntypedef\r\n  sequence_apply2<\r\n    rational,\r\n\r\n    token<int_>,\r\n    one_of<\r\n      last_of<lit_c<'/'>, token<int_> >,\r\n      empty<boost::mpl::int_<1> >\r\n    >\r\n  >\r\n  rational_grammar;\r\n\r\ntypedef build_parser<entire_input<rational_grammar> > rational_parser;\r\n\r\n#ifdef RATIONAL\r\n#  error RATIONAL already defined\r\n#endif\r\n#define RATIONAL(s) \\\r\n  (::rational_parser::apply<BOOST_METAPARSE_STRING(s)>::type::run())\r\n\r\n#if BOOST_METAPARSE_STD < 2011\r\n\r\nint main()\r\n{\r\n  std::cout << \"Please use a compiler that supports constexpr\" << std::endl;\r\n}\r\n\r\n#else\r\n\r\nint main()\r\n{\r\n  const boost::rational<int> r1 = RATIONAL(\"1/3\");\r\n  const boost::rational<int> r2 = RATIONAL(\"4/4\");\r\n  const boost::rational<int> r3 = RATIONAL(\"1\");\r\n  const boost::rational<int> r4 = RATIONAL(\"13/11\");\r\n\r\n  // Uncommenting the following line generates a compilation error. On a\r\n  // number of platforms the error report contains the following (or something\r\n  // similar):\r\n  // x__________________PARSING_FAILED__________________x<1, 3, digit_expected>\r\n  // where 1, 3 is the location of the error inside the string literal.\r\n//  const boost::rational<int> r5 = RATIONAL(\"7/\");\r\n\r\n  std::cout\r\n    << r1 << std::endl\r\n    << r2 << std::endl\r\n    << r3 << std::endl\r\n    << r4 << std::endl;\r\n}\r\n\r\n#endif\r\n\r\n", "meta": {"hexsha": "28b60c796e47835476c6990ff8ea8842f3e6c2d2", "size": 2568, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/metaparse/example/rational/main.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": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/metaparse/example/rational/main.cpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-04T18:00:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-04T18:00:00.000Z", "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/metaparse/example/rational/main.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 26.2040816327, "max_line_length": 80, "alphanum_fraction": 0.6838006231, "num_tokens": 694, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947155710233, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.45360757869261004}}
{"text": "#include <Eigen/Sparse>\n#include <Eigen/Dense>\n#include <iostream>\n#include \"setup_rotation_cluster.h\"\n#include \"kmeans_clustering.h\"\n\nusing namespace Eigen;\nusing namespace std;\ntypedef Eigen::Triplet<double> Trip;\n\n\nvoid setup_rotation_cluster(int nrc, bool reduced, const MatrixXi& mT, \n    const MatrixXd& mV, std::vector<VectorXi>& ibones, std::vector<VectorXi>& imuscle, \n    VectorXd& mred_x, VectorXd& mred_r, VectorXd& mred_w,\n\tSparseMatrix<double>& mC, SparseMatrix<double>& mA, MatrixXd& mG, VectorXd& mx0, \n\tstd::vector<SparseMatrix<double>>& mRotationBLOCK, std::map<int, std::vector<int>>& mr_cluster_elem_map, VectorXi& mr_elem_cluster_map){\n    std::cout<<\"+ Rotation Clusters\"<<std::endl;\n    if(nrc==0){\n        //unreduced\n        nrc = mT.rows();\n    }\n\n    mr_elem_cluster_map.resize(mT.rows());\n    if(nrc==mT.rows() && reduced==false){\n        //unreduced\n        for(int i=0; i<mT.rows(); i++){\n            mr_elem_cluster_map[i] = i;\n        }   \n    }else{\n\n        if(3*mV.rows()==mred_x.size() && reduced==false){\n            std::cout<<\"Continuous mesh is unreduced. Kmeans won't work.\"<<std::endl;\n            exit(0);\n        }else{\n            if(nrc==mT.rows()){\n                for(int i=0; i<mT.rows(); i++){\n                   mr_elem_cluster_map[i] = i;\n                }  \n            }else{\n                kmeans_clustering(mr_elem_cluster_map, nrc, ibones, imuscle, mG, mC, mA, mx0);\n            }\n        }\n\n    }\n\n    for(int i=0; i<mT.rows(); i++){\n        mr_cluster_elem_map[mr_elem_cluster_map[i]].push_back(i);\n    }\n\n    mred_r.resize(9*nrc);\n    for(int i=0; i<nrc; i++){\n        mred_r[9*i+0] = 1;\n        mred_r[9*i+1] = 0;\n        mred_r[9*i+2] = 0;\n        mred_r[9*i+3] = 0;\n        mred_r[9*i+4] = 1;\n        mred_r[9*i+5] = 0;\n        mred_r[9*i+6] = 0;\n        mred_r[9*i+7] = 0;\n        mred_r[9*i+8] = 1;\n    }\n    mred_w.resize(3*nrc);\n    mred_w.setZero();\n\n    if(reduced){\n        for(int c=0; c<nrc; c++){\n            std::vector<int> notfix = mr_cluster_elem_map[c];\n            // SparseMatrix<double> bo(mT.rows(), notfix.size());\n            // bo.setZero();\n            std::vector<Trip> bo_trip;\n            bo_trip.reserve(notfix.size());\n\n            int i = 0;\n            int f = 0;\n            for(int j =0; j<notfix.size(); j++){\n                if (i==notfix[f]){\n                    bo_trip.push_back(Trip(i, j, 1));\n                    f++;\n                    i++;\n                    continue;\n                }\n                j--;\n                i++;\n            }\n\n            \n            std::vector<Trip> b_trip;\n            b_trip.reserve(bo_trip.size());  \n            for(int k =0; k<bo_trip.size(); k++){\n                b_trip.push_back(Trip(12*bo_trip[k].row()+0, 12*bo_trip[k].col()+0, bo_trip[k].value()));\n                b_trip.push_back(Trip(12*bo_trip[k].row()+1, 12*bo_trip[k].col()+1, bo_trip[k].value()));\n                b_trip.push_back(Trip(12*bo_trip[k].row()+2, 12*bo_trip[k].col()+2, bo_trip[k].value()));\n                b_trip.push_back(Trip(12*bo_trip[k].row()+3, 12*bo_trip[k].col()+3, bo_trip[k].value()));\n                b_trip.push_back(Trip(12*bo_trip[k].row()+4, 12*bo_trip[k].col()+4, bo_trip[k].value()));\n                b_trip.push_back(Trip(12*bo_trip[k].row()+5, 12*bo_trip[k].col()+5, bo_trip[k].value()));\n                b_trip.push_back(Trip(12*bo_trip[k].row()+6, 12*bo_trip[k].col()+6, bo_trip[k].value()));\n                b_trip.push_back(Trip(12*bo_trip[k].row()+7, 12*bo_trip[k].col()+7, bo_trip[k].value()));\n                b_trip.push_back(Trip(12*bo_trip[k].row()+8, 12*bo_trip[k].col()+8, bo_trip[k].value()));\n                b_trip.push_back(Trip(12*bo_trip[k].row()+9, 12*bo_trip[k].col()+9, bo_trip[k].value()));\n                b_trip.push_back(Trip(12*bo_trip[k].row()+10, 12*bo_trip[k].col()+10, bo_trip[k].value()));\n                b_trip.push_back(Trip(12*bo_trip[k].row()+11, 12*bo_trip[k].col()+11, bo_trip[k].value()));\n            }\n\n            SparseMatrix<double> b(12*mT.rows(), 12*notfix.size());\n            b.setFromTriplets(b_trip.begin(), b_trip.end());\n            mRotationBLOCK.push_back(b);\n        }\n    }\n    std::cout<<\"- Rotation Clusters\"<<std::endl;\n}", "meta": {"hexsha": "1be6d79ec47b8911e4aa4109efb8ebb63a49a12b", "size": 4225, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PreProcessing/setup_rotation_cluster.cpp", "max_stars_repo_name": "alecjacobson/fast_muscles", "max_stars_repo_head_hexsha": "92150eaa81a4c1cbd27a76dbe4f10d27dffca3b4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-09T08:28:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-09T08:28:39.000Z", "max_issues_repo_path": "PreProcessing/setup_rotation_cluster.cpp", "max_issues_repo_name": "alecjacobson/fast_muscles", "max_issues_repo_head_hexsha": "92150eaa81a4c1cbd27a76dbe4f10d27dffca3b4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PreProcessing/setup_rotation_cluster.cpp", "max_forks_repo_name": "alecjacobson/fast_muscles", "max_forks_repo_head_hexsha": "92150eaa81a4c1cbd27a76dbe4f10d27dffca3b4", "max_forks_repo_licenses": ["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.4090909091, "max_line_length": 137, "alphanum_fraction": 0.5252071006, "num_tokens": 1265, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.835483553488848, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.45355334488358734}}
{"text": "#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE Suites\n#define EIGEN_USE_MKL_ALL \n#include <boost/test/unit_test.hpp>\n#include\"basis.hpp\"\n#include\"operators.hpp\"\n#include\"tpoperators.hpp\"\n\nusing namespace boost::unit_test;\nusing boost::unit_test_framework::test_suite;\nusing namespace Many_Body;\nBOOST_AUTO_TEST_SUITE(basistesting)\n\nBOOST_AUTO_TEST_SUITE(operatortesting)\nBOOST_AUTO_TEST_CASE(operatoroperations)\n{\n  using namespace Eigen;\n  using Mat=Operators::Mat;\n  const size_t L=3;\n\n   ElectronBasis<L> e1(1);\n   //std::cout << int(L/2) << std::endl;\n   ElectronBasis<L> e2(2);\n      double t1=1;\n   double t2=1;\n   double u=1;\n   // std::cout<< e1;\n   //   std::cout<< e2;\n   TensorProduct<ElectronBasis<L>, ElectronBasis<L>> TP(e1, e2);\n   //        std::cout<< TP;\n   //Mat E11=Operators::EKinOperator(TP,  t1);\n   //   std::cout<< E11;\n   Mat E1=Operators::EKinOperatorL(TP, e1, t1);\n   Mat E2=Operators::EKinOperatorR(TP, e2, t2);\n    Mat C=Operators::CalculateCouplungOperator(TP, e2, u);\n    Mat H=E1+E2+ C;\n\n    Eigen::MatrixXd HH =Eigen::MatrixXd(H);\n    std::cout << HH << std::endl;\n    Eigen::VectorXd ev(TP.dim);\n    // diag(HH, ev);\n\n    // std::cout << ev << std::endl;\n   // std::cout << NR;\n   // Mat EK=Operators::EKinOperator(e);\n   \n   //    std::cout << EK;\n   // VectorXd v(5);\n  //  MatrixXcd mat = MatrixXcd::Random(5, 5);\n  // MatrixXcd mat4= mat+mat.adjoint();\n  //  MatrixXcd mat2=mat4;\n\n  //  Many_Body::diagherm(mat4, v);\n  //     MatrixXcd mat3=mat4.adjoint();\n  //  std::cout<< mat3*mat2*mat4<< std::endl;\n  //   std::cout<< v<< std::endl;\n  //   numberoperator<ElectronBasis> n2;\n  //      kineticoperator<ElectronBasis> cdagc1(e);\n  // \tkineticoperator<ElectronBasis> cdagc2;\n  \n  // \tdouble t=3;\n  // \tsouble l=1;\n  // \thamiltonian<ElectronBasis> H1{t*n1+ l*cdagc1};\n  // \t\thamiltonian<ElectronBasis > H2{t*n2+ l*cdagc2};\n  // \t\tH2(e);\n  // \t\tcout<< H2.energies();\n // \t\t\t\tcout<< H1.energies(); \n\n}      \n}\n// BOOST_AUTO_TEST_CASE(electrondimension)\n// {\n// }\nBOOST_AUTO_TEST_SUITE_END()\n// EOF\n", "meta": {"hexsha": "1dc2c7e40a1186a42c4d06600300682a49a94305", "size": 2041, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "testdir/operatortest.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": "testdir/operatortest.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": "testdir/operatortest.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": 26.8552631579, "max_line_length": 64, "alphanum_fraction": 0.6398824106, "num_tokens": 691, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4535120657033274}}
{"text": "#include <complex>\n#include <iostream>\n#include <cstdint>\n#include <vector>\n#include <cassert>\n#include <random>\n\nusing namespace std;\n\ntypedef int64_t Torus64;\n\ntypedef int32_t Torus32;\n\nconst double DBL2M64 = 1./(1l<<32)/(1l<<32);\n\n#if 1\n//fixed point real number:\n//96 bit integer v\n//representing the value v/2^64 mod 2^32\n\n#ifndef intmul\n#define intmul intmul_best\n#endif\n\nstruct Real96 {\n    __uint128_t v;\n\n    Real96(uint64_t value=0);\n    Real96(uint64_t lo, uint64_t hi);\n};\n\nReal96::Real96(uint64_t value) {\n    v=value;\n}\n\nReal96::Real96(uint64_t lo, uint64_t hi) {\n    v=hi;\n    v<<=64;\n    v|=lo;\n}\n\nostream& operator<<(ostream& out, const Real96& r) {\n    out << \"[\"<< (int64_t(r.v>>64)) << \"].[\" << (int64_t(r.v&0xFFFFFFFFFFFFFFFFUL)) << \"] (\" << double(__int128_t(r.v))*DBL2M64 << \")\";\n    return out;\n}\n\nvoid add(Real96& dest, const Real96& a, const Real96& b) {\n    dest.v=a.v+b.v;\n}\nReal96 operator+(const Real96& a, const Real96& b) {\n    Real96 reps; add(reps,a,b); return reps;\n}\nvoid operator+=(Real96& a, const Real96& b) {\n    add(a,a,b);\n}\n\n\nvoid sub(Real96& dest, const Real96& a, const Real96& b) {\n    dest.v=a.v-b.v;\n}\nvoid neg(Real96& dest, const Real96& a) {\n    dest.v=-a.v;\n}\nReal96 operator-(const Real96& a, const Real96& b) {\n    Real96 reps; sub(reps,a,b); return reps;\n}\nvoid operator-=(Real96& a, const Real96& b) {\n    sub(a,a,b);\n}\nReal96 operator-(const Real96& a) {\n    Real96 reps; neg(reps,a); return reps;\n}\n\nvoid extmul(Real96& dest, int a, const Real96& b) {\n    dest.v=a*b.v;\n}\n\n\nvoid  intmul_ref(Real96& dest, const Real96& a, const Real96& b) {\n    __int128_t av = a.v;\n    //__uint128_t avu = a.v;\n    __int128_t bv = b.v;\n    //__uint128_t bvu = b.v;\n    //__uint128_t alo = av&0xFFFFFFFFFFFFFFFFUL;\n    __uint128_t blo = bv&0xFFFFFFFFFFFFFFFFUL;\n    int32_t ahi = av>>64;\n    __int128_t bhi = bv>>127;\n    assert(bhi==0 || bhi==-1);\n    assert(ahi<1l<<31 || ahi>=-1l<<31);\n\n    __int128_t w0 = (uint64_t(a.v)*blo)>>64; //between [0 and 2^64-2]\n    w0 += ahi*blo - (bhi&av);\n    dest.v = w0;\n\n}\n\nvoid __attribute ((noinline)) intmul_asm_fk(Real96& dest, const Real96& a, const Real96& b) {\n    //const Real96* aad = &a;\n    //const Real96* bad = &b;\n    //Real96* destad = &dest;\n    uint64_t tmpa;\n    uint64_t tmpb;\n    uint64_t tmpc;\n    uint64_t tmpd;\n    uint64_t tmpe;\n    uint64_t tbval;\n    __asm volatile (\n\t\"movq      %[b],%[tbval]\\n\"\n        \"movq      8(%[a]), %[tmpb]\\n\"           // tmpb=ahi\n        \"sarq      $63, %[tmpb]\\n\"               // tmpb=ahi<0?-1:0\n        \"movq      (%[tbval]), %%rdx\\n\"          // rdx=blo\n        \"mulx      (%[a]), %[tmpa], %[tmpe]\\n\"   // [e:a] = alo*blo = [u:v]\n        \"mulx      8(%[a]), %[tmpa], %[tmpd]\\n\"  // [d:a] = ahi*blo = [w:x]\n        \"negq      %%rdx\\n\"\n        \"andq      %%rdx, %[tmpb]\\n\"             // tmpb=ahi<0?-blo:0\n        \"addq      %[tmpe], %[tmpa]\\n\"           // x+=u\n        \"movq      8(%[tbval]), %[tmpc]\\n\"       // c=bhi\n        \"adcq      %[tmpb], %[tmpd]\\n\"           // w+=-blo if ahi<0\n        \"btq       $63, %[tmpc]\\n\"               // test sign of bhi\n        \"jnc       1f\\n\"\n        \"subq      (%[a]), %[tmpa]\\n\"            // x-=alo\n        \"sbbq      8(%[a]), %[tmpd]\\n\"           // w-=ahi+carry\n        \"1:\\n\"\n        \"movq      %[tmpa], (%[dest])\\n\"\n        \"movq      %[tmpd], 8(%[dest])\\n\" \n\t: [tmpa] \"=r\" (tmpa),\n\t  [tmpb] \"=r\" (tmpb),\n\t  [tmpc] \"=r\" (tmpc),\n\t  [tmpd] \"=r\" (tmpd),\n\t  [tmpe] \"=r\" (tmpe),\n\t  [tbval] \"=r\" (tbval)\n\t: [dest] \"r\" (&dest),\n\t  [a] \"r\"(&a),\n\t  [b] \"r\"(&b)\n\t: \"%rdx\",\"memory\"\n\t   );\n}\n\n#include <bmi2intrin.h>\n\ntypedef union {\n    __uint128_t vu128;\n    unsigned long long vu64[2];\n    __int128_t v128;\n    long long v64[2];\n} UINT128;\n\nvoid intmul_best(Real96& dest, const Real96& a, const Real96& b) {\n    const UINT128* aa = (const UINT128*) &a;\n    const UINT128* ab = (const UINT128*) &b;\n    //UINT128* adest = (UINT128*) &dest;\n    UINT128 tab;\n    UINT128 tcd;\n    //UINT128 tef;\n    _mulx_u64(ab->vu64[0],aa->vu64[0],&tcd.vu64[0]);  // td=u\n    tab.vu64[0]=_mulx_u64(ab->vu64[0],aa->vu64[1],&tab.vu64[1]);\n    tcd.vu64[1]=(aa->v64[1]>>63)&(-ab->vu64[0]); //(aa->vu64[1]&0x8000000000000000UL)?(-ab->vu64[0]):0;\n    tab.vu128+=tcd.vu128;\n    if (ab->vu64[1]&0x8000000000000000UL) tab.vu128-=aa->vu128;\n    //tcd.vu64[0]=ab->vu64[1]&aa->vu64[0];\n    //tcd.vu64[1]=ab->vu64[1]&aa->vu64[1];\n    //tab.vu128-=tcd.vu128;\n#ifdef NDEBUG\n    dest.v=tab.vu128;\n#else\n    intmul_ref(dest,a,b);\n    assert(dest.v==tab.vu128);\n#endif\n}\n\nReal96 operator*(int a, const Real96& b) {\n    Real96 reps; extmul(reps,a,b); return reps;\n}\nvoid operator*=(Real96& b, int a) {\n    extmul(b,a,b);\n}\nReal96 operator*(const Real96& a, const Real96& b) {\n    Real96 reps; intmul(reps,a,b); return reps;\n}\nvoid operator*=(Real96& a, const Real96& b) {\n    intmul(a,a,b);\n}\n\nReal96 t64tor96(Torus64 v) {\n    Real96 reps; \n    int64_t vv = v;\n    reps.v = vv;\n    return reps;\n}\n\nReal96 dtor96(double v) {\n    Real96 reps;\n    int64_t iv = floor(v);\n    v = v-iv;\n    assert(v>=0 && v<1.);\n    v *= (1ul<<32);\n    v *= (1ul<<32);\n    uint64_t lv = v;\n    __int128_t pv = iv;\n    pv <<= 64;\n    pv |= lv;\n    reps.v = pv;\n    return reps;\n}\n\nbool very_close(const Real96& a,const Real96& b) {\n    bool reps = (abs(__int128_t(a.v-b.v))<10000);\n    if (!reps) {\n\tcerr << \"not close: \" << a << \" vs. \" << b << endl;\n    }\n    return reps;\n}\n\n#else\ntypedef double Real96;\n\nReal96 t64tor96(Torus64 v) {\n    return double(v)*DBL2M64;\n}\n\nReal96 dtor96(double v) {\n    return v;\n}\n\nbool very_close(const Real96& a,const Real96& b) {\n    bool reps = (abs(a-b)<1e-5);\n    if (!reps) {\n\tcerr << \"not close: \" << a << \" vs. \" << b << endl;\n    }\n    return reps;\n}\n\n#endif\n\n//-----------------------------------------------------------------------\n\ntypedef complex<Real96> Cplx96;\n\n//-----------------------------------------------------------------------\n\n#include <NTL/RR.h>\nusing namespace NTL;\n\nRR PI_RR = ComputePi_RR();\n\nReal96 accurate_cos(int i,int n) { //cos(2pi*i/n)\n    i = ((i%n) + n)%n;\n    if (i==0) return Real96(-1,0);\n    ZZ cosi = RoundToZZ(cos(PI_RR*2*i/n)*pow(to_RR(2),to_RR(64)));\n    if (cosi>=0)\n\treturn Real96(to_long(cosi));\n    else\n\treturn Real96(to_long(cosi+power(to_ZZ(2),64)),-1);\n\n/*\n    if (i>=3*n/4) return dtor96(cos(2.*M_PI*(n-i)/double(n)));\n    if (i>=2*n/4) return dtor96(-cos(2.*M_PI*(i-n/2)/double(n)));\n    if (i>=1*n/4) return dtor96(-cos(2.*M_PI*(n/2-i)/double(n)));\n    return dtor96(cos(2.*M_PI*(i)/double(n)));\n    */\n}\n\nReal96 accurate_sin(int i,int n) { //sin(2pi*i/n)\n    i = ((i%n) + n)%n;\n    if (i==n/4) return Real96(-1,0);\n    ZZ sini = RoundToZZ(sin(PI_RR*2*i/n)*pow(to_RR(2),to_RR(64)));\n    if (sini>=0)\n\treturn Real96(to_long(sini));\n    else\n\treturn Real96(to_long(sini+power(to_ZZ(2),64)),-1);\n/*\n    if (i>=3*n/4) return dtor96(-sin(2.*M_PI*(n-i)/double(n)));\n    if (i>=2*n/4) return dtor96(-sin(2.*M_PI*(i-n/2)/double(n)));\n    if (i>=1*n/4) return dtor96(sin(2.*M_PI*(n/2-i)/double(n)));\n    return dtor96(sin(2.*M_PI*(i)/double(n)));\n    */\n}\n\n//reverse the bits of i (mod n)\nint rev(int i, int n) {\n    int reps=0;\n    for (int j=1; j<n; j*=2) {\n\treps = 2*reps + (i%2);\n\ti/=2;\n    }\n    return reps;\n}\n\nbool very_close(const Cplx96& a,const Cplx96& b) {\n    bool reps = (very_close(a.real(),b.real()) && very_close(a.imag(),b.imag()));\n    if (!reps) {\n\tcerr << \"not close: \" << a << \" vs. \" << b << endl;\n    }\n    return reps;\n}\n\n\n\n\n\n\n// FFT from Torus64^N to Cplx96^(N/2)  mod X^N+1\n// N = 2048 (note: n=2N ici)\n\n\n//at the beginning of iteration nn\n// a_{j,i} has P_{i%nn}(omega^j) \n// where j between [rev(1) and rev(3)[\n// and i between [0 and nn[\nvoid ifft_check(int n, int nn, const Cplx96* acur, const vector<Real96>& a, const vector<Cplx96>& powomega) {\n    int ns4=n/4;\t\n    cerr << \"Checking iteration \" << nn << endl;\n    for (int i=0; i<ns4; i++) {\n\tcout << \"i: \" << i << \"   \" << acur[i] << endl;\n    }\n    int m = n/nn;\n    int rev1m = rev(1,m);\n    int rev3m = rev(3,m);\n    int idex = 0;\n    for (int revj=rev1m; revj<rev3m; revj++) {\n\tint j = rev(revj,m);\n\tcerr << \"check-- j: \" << j << endl;\n\tfor (int i=0; i<nn; i++) {\n\t    cerr << \"check--- i: \" << i << \"(mod \" << nn << \")\" << endl;\n\t    const Cplx96& test_cur = acur[idex];\n\t    //sum_[t=i%nn] a_t omega^jt\n\t    Cplx96 pij(0,0);\n\t    for (int k=i; k<n; k+=nn) {\n\t\t//cout << \"ak: \" << a[k] << endl;\n\t\tpij += a[k] * powomega[(k*j) % n];\n\t    }\n\t    assert(very_close(test_cur,pij));\n\t    idex++;\n\t}\n    }\n}\n\n\n//at the beginning of iteration halfnn:\n//   m=n/halfnn\n//   P_{j%m}(omb^i)\n//   for j in [rev(1,m) to rev(3,m)[\n//   and i in [0,halfnn[\nvoid fft_check(\n\tint n, int halfnn, \n\tconst Cplx96* pcur,\n\tconst vector<Cplx96>& p,\n\tconst vector<Cplx96>& powombar\n\t) {\n    int ns4=n/4;\n    cerr << \"DIRECT FFT: Checking iteration \" << halfnn  << endl;\n    for (int i=0; i<ns4; i++) {\n\tcout << \"i: \" << i << \"   \" << pcur[i] << endl;\n    }\n    int m = n/halfnn;\n    int rev1m = rev(1,m);\n    int rev3m = rev(3,m);\n    int idex = 0;\n    for (int revj=rev1m; revj<rev3m; revj++) {\n\tint j = rev(revj,m);\n\tcerr << \"check-- j: \" << j << \"(mod \" << m << \")\" << endl;\n\tfor (int i=0; i<halfnn; i++) {\n\t    cerr << \"check--- i: \" << i << endl;\n\t    //P_sum_[k=j%m] p_k omb^ik-j\n\t    Cplx96 pij(0,0);\t\n\t    for (int k=j; k<n; k+=m) {\n\t\t//if (halfnn==8 && j==1 && i==1) cerr << \"pij(\" << pij << \")\" << \"+= p_\"<<k<<\"(\"<<p[k]<<\") * omb[\"<<i*(k-j)<<\"](\"<< powombar[(i*(k-j)) % n] <<\")\" << endl; \n\t\tpij += p[k] * powombar[(i*(k-j)) % n];\n\t    }\n\t    assert(very_close(pcur[idex],pij));\n\t    idex++;\n\t}\n    }\n}\n\n\n\nvoid precomp_iFFT(vector<Cplx96>& powomega, int n) {\n    powomega.resize(n);\n    for (int i=0; i<n; i++)\n\tpowomega[i]=Cplx96(accurate_cos(i,n),accurate_sin(i,n));\n}\n\nvoid precomp_FFT(vector<Cplx96>& powombar, int n) {\n    powombar.resize(n);\n    for (int i=0; i<n; i++)\n\tpowombar[i]=Cplx96(accurate_cos(i,n),accurate_sin((n-i)%n,n));\n}\n\n// P -> P(omega)\nvoid iFFT(Cplx96* out, const Torus64* in, int n, const vector<Cplx96>& powomega) {\n    //const int N = n/2;\n    const int ns4 = n/4;\n\n#ifndef NDEBUG\n    vector<Real96> a; a.resize(n);\n    for (int i=0; i<n/2; i++)\n\ta[i]=t64tor96(in[i]/2);\n    for (int i=0; i<n/2; i++)\n\ta[n/2+i]=-a[i];\n#endif\n\n\n    //interpret the input coefs as real and imaginary parts:\n    //RRRRRRRRRRIIIIIIIII\n    //multiply by omega^j\n    for (int j=0; j<ns4; j++)\n\tout[j] = Cplx96(t64tor96(in[j]),t64tor96(in[j+ns4]))*powomega[j];\n\n    //at the beginning of iteration nn\n    // a_{j,i} has P_{i%nn}(omega^j) \n    // where j between [rev(1) and rev(3)[\n    // and i between [0 and nn[\n    for (int nn=ns4; nn>=2; nn/=2) {\n\tint halfnn = nn/2;\n#ifndef NDEBUG\n\tcerr << \"Starting iteration \" << nn << endl;\n\tint m = n/nn;\n\tifft_check(n, nn, out, a, powomega);\n#endif\n\tfor (int block=0; block<ns4; block+=nn) {\n#ifndef NDEBUG\n\t    int j = rev(rev(1,m)+block,m);\n\t    cerr << \"-- block j: \" << j  << \" --> \" << j << \",\" << j+halfnn/2 << endl;\n#endif\n\t    for (int off=0; off<halfnn; off++) {\n#ifndef NDEBUG\n\t\tcerr << \"--- i: \" << off << \" using: omg^\" << (2*(ns4/halfnn)*off)%n << endl;\n#endif\n\t\tCplx96 t1 = out[block+off];\n\t\tCplx96 t2 = out[block+off+halfnn];\n\t\tout[block+off]=t1+t2;\n\t\tout[block+off+halfnn]=(t1-t2)*powomega[(2*(ns4/halfnn)*off)%n];\n\t    }\n\t}\n    }\n    {\n#ifndef NDEBUG\n\tint nn = 1;\n\tifft_check(n, nn, out, a, powomega);\n#endif\n    }\n}\n\n// P(omega) -> P\nvoid FFT(Torus64* out, Cplx96* in, int n, const vector<Cplx96>& powombar) {\n    //const int N = n/2;\n    const int ns4 = n/4;\n\n#ifndef NDEBUG\n    vector<Cplx96> a; a.resize(n);\n    for (int i=0; i<n; i++) a[i]=Cplx96(0);\n    int rev1m = rev(1,n);\n    int rev3m = rev(3,n);\n    for (int revj=rev1m; revj<rev3m; revj++) {\n\tint j = rev(revj,n);\n\tcout << \"assign:\" << j << \" \" << revj-rev1m << endl;\n\ta[j]=in[revj-rev1m];\n\ta[n-j]=Cplx96(a[j].real(),-a[j].imag());\n    }\n#endif\n\n\n#ifndef NDEBUG\n\tcerr << \"Checking iteration 1\" << endl;\n\tfft_check(n, 1, in, a, powombar);\n#endif\n\n    //at the beginning of iteration nn\n    // a_{j,i} has P_{i%nn}(omega^j) \n    // where j between [rev(1) and rev(3)[\n    // and i between [0 and nn[\n    for (int nn=2; nn<=ns4; nn*=2) {\n\tint halfnn = nn/2;\n\tfor (int block=0; block<ns4; block+=nn) {\n\t    //#ifndef NDEBUG\n\t    //\t    int j = rev(rev(1,m)+block,m);\n\t    //\t    cerr << \"-- block j: \" << j  << \" --> \" << j << \",\" << j+halfnn/2 << endl;\n\t    //#endif\n\t    for (int off=0; off<halfnn; off++) {\n\t\t//#ifndef NDEBUG\n\t\t//\t\tcerr << \"--- i: \" << off << \" using: omg^\" << (2*(ns4/halfnn)*off)%n << endl;\n\t\t//#endif\n\t\tCplx96 t1 = in[block+off];\n\t\tCplx96 t2 = in[block+off+halfnn]*powombar[(2*(ns4/halfnn)*off)%n];\n\t\tin[block+off]=t1+t2;\n\t\tin[block+off+halfnn]=(t1-t2);\n\t    }\n\t}\n#ifndef NDEBUG\n\tcerr << \"Ending iteration \" << nn << endl;\n\tfft_check(n, nn, in, a, powombar);\n#endif\n    }\n\n\n    //interpret the input coefs as real and imaginary parts:\n    //RRRRRRRRRRIIIIIIIII\n    //multiply by omega^j\n    for (int j=0; j<ns4; j++) {\n\tin[j] *= powombar[j];\n\tout[j] = in[j].real().v>>10;  // /ns4;  //divide by N/2\n\tout[j+ns4] = in[j].imag().v>>10; // /ns4; //divide by N/2\n    }\n\n    {\n\t//#ifndef NDEBUG\n\t//\tint nn = 1;\n\t//\tifft_check(n, nn, out, a, powomega);\n\t//#endif\n    }\n}\n\n\n\nint main(int argc, char** argv) {\n\n#if 1\n\n    const int N = 2048;\n    const int Ns2 = N/2;\n#ifndef NDEBUG\n    const int NBTRIALS=1;\n#else\n    const int NBTRIALS=10000;\n#endif\n\n#ifndef NDEBUG\n    //test cosinus\n    for (int i=0; i<=2*N; i++) {\n\t//if (i!=1024) continue;\n\tReal96 c = accurate_cos(i,2*N);\n\tReal96 s = accurate_sin(i,2*N);\n\tcout << \"i: \" << i  << \", \" << cos(2*i*M_PI/64.) << endl;\n\tcout << \"c \" << c << endl;\n\tcout << \"s \" << s << endl;\n\tcout << \"c*c \" << c*c << endl;\n\tcout << \"s*s \" << s*s << endl;\n\tReal96 t = c*c+s*s;\n\tcout << \"cos test\" <<  i << \":\" << t << endl;\n\tassert(very_close(t,Real96(0,1)));\n    }\n#endif\n\n    //test de la IFFT\n    Cplx96 out[Ns2];\n    Torus64 in[N];\n    Torus64 revout[N];\n\n    vector<Cplx96> powomega;\n    vector<Cplx96> powombar;\n\n    std::default_random_engine generator;\n    std::uniform_int_distribution<Torus64> distribution(numeric_limits<Torus64>::min(),numeric_limits<Torus64>::max());\n\n    for (int i=0; i<N; i++) {\n\tin[i]=distribution(generator);\n    }\n\n    precomp_iFFT(powomega,2*N);\n    precomp_FFT(powombar,2*N);\n\n#ifndef NDEBUG\n    //test powomega\n    for (int i=0; i<2*N; i++) {\n\t//if (i!=1024) continue;\n\tcout << \"powomega: \" << i << \" : \" << powomega[i] << endl; \n\tassert(very_close(powomega[i]*powomega[(2*N-i)%(2*N)],Cplx96(Real96(0,1))));\n\tassert(very_close(powomega[i]*powombar[i],Cplx96(Real96(0,1))));\n    }\n\n#endif\n\n    clock_t t0 = clock();\n    for (int i=0; i<NBTRIALS; i++)\n\tiFFT(out,in,2*N,powomega);\n    clock_t t1 = clock();\n    for (int i=0; i<NBTRIALS; i++)\n\tFFT(revout,out,2*N,powombar);\n    clock_t t2 = clock();\n#ifndef NDEBUG\n    for (int i=0; i<N; i++)\n\tcout << hex << revout[i] << \" \"<< in[i] << \" \" << (revout[i]^in[i]) << endl;\n#endif\n    cout << \"time IFFT: \" << (t1-t0)/double(NBTRIALS) << \"mus\" << endl;\n    cout << \"time FFT: \" << (t2-t1)/double(NBTRIALS) << \"mus\" << endl;\n\n#endif\n\n#if 0\n    const int NBTRIALS=100;\n    \n    //test d'un keyswitch binaire\n    int nlvl2=2048;\n    int tlvl2=32;\n    int klvl1=2;\n    int Nlvl1=1024;\n    int llvl1=4;\n\n    int KS_size=Nlvl1*(klvl1+1)*(klvl1+1)*tlvl2*nlvl2;\n    cout << \"KS_size: \" << KS_size << \" * 32bits\" << endl;\n    Torus32* KS_rrr = new Torus32[Nlvl1*(klvl1+1)*(klvl1+1)*tlvl2*nlvl2];\n    Torus32** KS_rr = new Torus32*[(klvl1+1)*tlvl2*nlvl2];\n    Torus32*** KS_r = new Torus32**[tlvl2*nlvl2];\n    Torus32**** KS = new Torus32***[nlvl2];\n    for (int i=0; i<Nlvl1*(klvl1+1)*(klvl1+1)*tlvl2*nlvl2; i++) KS_rrr[i]=i; //random\n    for (int i=0; i<(klvl1+1)*tlvl2*nlvl2; i++) KS_rr[i]=KS_rrr+i*(Nlvl1*(klvl1+1));\n    for (int i=0; i<tlvl2*nlvl2; i++) KS_r[i]=KS_rr+i*(klvl1+1);\n    for (int i=0; i<nlvl2; i++) KS[i]=KS_r+i*tlvl2;\n\n    Torus64* samples_r = new Torus64[(nlvl2+1)*llvl1];\n    Torus64** samples = new Torus64*[llvl1];\n    for (int i=0; i<(nlvl2+1)*llvl1; i++) samples_r[i]=i; //random\n    for (int i=0; i<llvl1; i++) samples[i]=samples_r+i*(nlvl2+1);\n\n    Torus32* KSres = new Torus32[(klvl1+1)*Nlvl1];    \n\n    clock_t tdebks = clock();\n    for (int trial=0; trial<NBTRIALS; trial++) {\n\tint u=0;\n\tfor (int i=0; i<(klvl1+1)*Nlvl1; i++) KSres[i]=0;\n\tKSres[u*Nlvl1]=samples[0][nlvl2]; //b\n\tfor (int i=0; i<nlvl2; i++) {\n\t    //decompose a\n\t    uint64_t ai=samples[0][i];\n\t    for (int j=0; j<tlvl2; j++) {\n\t\tint8_t aij=(ai & 1ul<<(63-j))?1:0;\n\t\tfor (int l=0; l<(klvl1+1)*Nlvl1; l++)\n\t\t    KSres[l]+=aij*KS[i][j][u][l];\n\t    }\n\t}\n    }\n    clock_t tendks = clock();\n\n    cout << \"KS:\" << double(tendks-tdebks)/NBTRIALS << \"mus \" << endl;\n#endif\n\n}\n", "meta": {"hexsha": "3e52a1d15ea49838060e12c4eb2de8cae6affa4b", "size": 16677, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "high-precision-anticyclic-fft/src/code.cpp", "max_stars_repo_name": "tfhe/experimental-tfhe", "max_stars_repo_head_hexsha": "248ee1fd69e4344d19026371dec251c6ab28edfc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2017-08-13T01:43:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-10T08:56:16.000Z", "max_issues_repo_path": "high-precision-anticyclic-fft/src/code.cpp", "max_issues_repo_name": "tfhe/experimental-tfhe", "max_issues_repo_head_hexsha": "248ee1fd69e4344d19026371dec251c6ab28edfc", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "high-precision-anticyclic-fft/src/code.cpp", "max_forks_repo_name": "tfhe/experimental-tfhe", "max_forks_repo_head_hexsha": "248ee1fd69e4344d19026371dec251c6ab28edfc", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-02-08T01:09:00.000Z", "max_forks_repo_forks_event_max_datetime": "2018-02-08T01:09:00.000Z", "avg_line_length": 26.0985915493, "max_line_length": 157, "alphanum_fraction": 0.5417641063, "num_tokens": 6384, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.4535120657033274}}
{"text": "/**\n * \\ file FFT.cpp\n */\n\n#include <cmath>\n\n#include <ATK/Utility/FFT.h>\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_NO_MAIN\n#include <boost/test/unit_test.hpp>\n\nBOOST_AUTO_TEST_CASE( FFT_test )\n{\n  std::vector<double> input(128);\n  std::vector<double> ref(128);\n  for(int i = 0; i < 100; ++i)\n  {\n    input[i] = ref[i] = i+1;\n  }\n  std::vector<std::complex<double> > frequency(128);\n  \n  ATK::FFT<double> processor;\n  processor.set_size(128);\n  \n  processor.process_forward(input.data(), frequency.data(), 100);\n  processor.process_backward(frequency.data(), input.data(), 128);\n  \n  for(int i = 0; i < 100; ++i)\n  {\n    BOOST_REQUIRE_CLOSE(input[i], ref[i], 0.0001);\n  }\n}\n\nBOOST_AUTO_TEST_CASE( doubleFFT_test )\n{\n  std::vector<double> input(128);\n  std::vector<double> double_input(128);\n  std::vector<double> ref(128);\n  for(int i = 0; i < 100; ++i)\n  {\n    input[i] = ref[i] = i+1;\n    double_input[i] = 2 * (i+1);\n  }\n  std::vector<std::complex<double> > frequency(128);\n  std::vector<std::complex<double> > double_frequency(128);\n  \n  ATK::FFT<double> processor;\n  processor.set_size(128);\n  \n  processor.process_forward(input.data(), frequency.data(), 100);\n  processor.process_forward(double_input.data(), double_frequency.data(), 100);\n  processor.process_backward(frequency.data(), input.data(), 128);\n  processor.process_backward(double_frequency.data(), double_input.data(), 128);\n  \n  for(int i = 0; i < 100; ++i)\n  {\n    BOOST_REQUIRE_CLOSE(input[i], ref[i], 0.0001);\n    BOOST_REQUIRE_CLOSE(double_input[i], 2*ref[i], 0.0001);\n  }\n}\n", "meta": {"hexsha": "e0f37ff6582e706cdb9902080401086bc45c1728", "size": 1555, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/Utility/FFT.cpp", "max_stars_repo_name": "apohl79/AudioTK", "max_stars_repo_head_hexsha": "05ac241b0bc6a8f841d93257b4d81e5961b1f627", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-05-17T15:29:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T22:26:08.000Z", "max_issues_repo_path": "tests/Utility/FFT.cpp", "max_issues_repo_name": "apohl79/AudioTK", "max_issues_repo_head_hexsha": "05ac241b0bc6a8f841d93257b4d81e5961b1f627", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/Utility/FFT.cpp", "max_forks_repo_name": "apohl79/AudioTK", "max_forks_repo_head_hexsha": "05ac241b0bc6a8f841d93257b4d81e5961b1f627", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-04-21T13:43:57.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-28T19:10:14.000Z", "avg_line_length": 25.0806451613, "max_line_length": 80, "alphanum_fraction": 0.6604501608, "num_tokens": 450, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.4535120657033274}}
{"text": "#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <memory>\n#include <cmath>\n#include <iostream>\n\n#include \"sparsetensor.h\"\n#include \"bpmfutils.h\"\n#include \"noisemodels.h\"\n\nusing namespace Eigen;\n\n////  AdaptiveGaussianNoise  ////\nvoid AdaptiveGaussianNoise::init(MatrixData & matrixData) {\n  double se = 0.0;\n  double mean_value = matrixData.mean_value;\n\n#pragma omp parallel for schedule(dynamic, 4) reduction(+:se)\n  for (int k = 0; k < matrixData.Y.outerSize(); ++k) {\n    for (SparseMatrix<double>::InnerIterator it(matrixData.Y, k); it; ++it) {\n      se += square(it.value() - mean_value);\n    }\n  }\n\n  var_total = se / matrixData.Y.nonZeros();\n  if (var_total <= 0.0 || std::isnan(var_total)) {\n    // if var cannot be computed using 1.0\n    var_total = 1.0;\n  }\n  // Var(noise) = Var(total) / (SN + 1)\n  alpha     = (sn_init + 1.0) / var_total;\n  alpha_max = (sn_max + 1.0)  / var_total;\n}\n\nvoid AdaptiveGaussianNoise::init(TensorData & data) {\n  double se = 0.0;\n  double mean_value = data.mean_value;\n\n  auto& sparseMode   = (*data.Y)[0];\n  VectorXd & values  = sparseMode->values;\n\n#pragma omp parallel for schedule(dynamic, 4) reduction(+:se)\n  for (int i = 0; i < values.size(); i++) {\n    se += square(values(i) - mean_value);\n  }\n  var_total = se / values.size();\n  if (var_total <= 0.0 || std::isnan(var_total)) {\n    var_total = 1.0;\n  }\n  // Var(noise) = Var(total) / (SN + 1)\n  alpha     = (sn_init + 1.0) / var_total;\n  alpha_max = (sn_max + 1.0)  / var_total;\n}\n\nvoid AdaptiveGaussianNoise::update(MatrixData & data, std::vector< std::unique_ptr<Eigen::MatrixXd> > & samples)\n{\n  double sumsq = 0.0;\n  MatrixXd & U = *samples[0];\n  MatrixXd & V = *samples[1];\n\n  Eigen::SparseMatrix<double> & train = data.Y;\n  double mean_value = data.mean_value;\n\n#pragma omp parallel for schedule(dynamic, 4) reduction(+:sumsq)\n  for (int j = 0; j < train.outerSize(); j++) {\n    auto Vj = V.col(j);\n    for (SparseMatrix<double>::InnerIterator it(train, j); it; ++it) {\n      double Yhat = Vj.dot( U.col(it.row()) ) + mean_value;\n      sumsq += square(Yhat - it.value());\n    }\n  }\n  // (a0, b0) correspond to a prior of 1 sample of noise with full variance\n  double a0 = 0.5;\n  double b0 = 0.5 * var_total;\n  double aN = a0 + train.nonZeros() / 2.0;\n  double bN = b0 + sumsq / 2.0;\n  alpha = rgamma(aN, 1.0 / bN);\n  if (alpha > alpha_max) {\n    alpha = alpha_max;\n  }\n}\n\nvoid AdaptiveGaussianNoise::update(TensorData & data, std::vector< std::unique_ptr<Eigen::MatrixXd> > & samples)\n{\n  double sumsq = 0.0;\n  double mean_value = data.mean_value;\n\n  auto& sparseMode = (*data.Y)[0];\n  auto& U = samples[0];\n\n  const int nmodes = samples.size();\n  const int num_latents = U->rows();\n\n#pragma omp parallel for schedule(dynamic, 4) reduction(+:sumsq)\n  for (int n = 0; n < data.dims(0); n++) {\n    Eigen::VectorXd u = U->col(n);\n    for (int j = sparseMode->row_ptr(n);\n             j < sparseMode->row_ptr(n + 1);\n             j++)\n    {\n      VectorXi idx = sparseMode->indices.row(j);\n      // computing prediction from tensor\n      double Yhat = mean_value;\n      for (int d = 0; d < num_latents; d++) {\n        double tmp = u(d);\n\n        for (int m = 1; m < nmodes; m++) {\n          tmp *= (*samples[m])(d, idx(m - 1));\n        }\n        Yhat += tmp;\n      }\n      sumsq += square(Yhat - sparseMode->values(j));\n    }\n\n  }\n  double a0 = 0.5;\n  double b0 = 0.5;\n  double aN = a0 + sparseMode->values.size() / 2.0;\n  double bN = b0 + sumsq / 2.0;\n  alpha = rgamma(aN, 1.0 / bN);\n  if (alpha > alpha_max) {\n    alpha = alpha_max;\n  }\n}\n\ninline double nCDF(double val) {return 0.5 * erfc(-val * M_SQRT1_2);}\n\n/////  evalModel functions\nvoid ProbitNoise::evalModel(MatrixData & data, const int n, Eigen::VectorXd & predictions, Eigen::VectorXd & predictions_var,\n        std::vector< std::unique_ptr<Eigen::MatrixXd> > & samples) {\n  const unsigned N = data.Ytest.nonZeros();\n  Eigen::VectorXd pred(N);\n  Eigen::VectorXd test(N);\n  Eigen::MatrixXd & rows = *samples[0];\n  Eigen::MatrixXd & cols = *samples[1];\n\n// #pragma omp parallel for schedule(dynamic,8) reduction(+:se, se_avg) <- dark magic :)\n  for (int k = 0; k < data.Ytest.outerSize(); ++k) {\n    int idx = data.Ytest.outerIndexPtr()[k];\n    for (Eigen::SparseMatrix<double>::InnerIterator it(data.Ytest,k); it; ++it) {\n     pred[idx] = nCDF(cols.col(it.col()).dot(rows.col(it.row())));\n     test[idx] = it.value();\n\n      // https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Online_algorithm\n      double pred_avg;\n      if (n == 0) {\n        pred_avg = pred[idx];\n      } else {\n        double delta = pred[idx] - predictions[idx];\n        pred_avg = (predictions[idx] + delta / (n + 1));\n        predictions_var[idx] += delta * (pred[idx] - pred_avg);\n      }\n      predictions[idx++] = pred_avg;\n\n   }\n  }\n  auc_test_onesample = auc(pred,test);\n  auc_test = auc(predictions, test);\n}\n\nvoid FixedGaussianNoise::evalModel(MatrixData & data, const int n, Eigen::VectorXd & predictions, Eigen::VectorXd & predictions_var,\n        std::vector< std::unique_ptr<Eigen::MatrixXd> > & samples) {\n   auto rmse = eval_rmse(data.Ytest, n, predictions, predictions_var, *samples[1], *samples[0], data.mean_value);\n   rmse_test = rmse.second;\n   rmse_test_onesample = rmse.first;\n}\n\n\nvoid AdaptiveGaussianNoise::evalModel(MatrixData & data, const int n, Eigen::VectorXd & predictions, Eigen::VectorXd & predictions_var,\n        std::vector< std::unique_ptr<Eigen::MatrixXd> > & samples) {\n   auto rmse = eval_rmse(data.Ytest, n, predictions, predictions_var, *samples[1], *samples[0], data.mean_value);\n   rmse_test = rmse.second;\n   rmse_test_onesample = rmse.first;\n}\n\n\n\n// evalModel for TensorData\nvoid ProbitNoise::evalModel(TensorData & data, const int Nepoch, Eigen::VectorXd & predictions, Eigen::VectorXd & predictions_var,\n        std::vector< std::unique_ptr<Eigen::MatrixXd> > & samples) {\n  // TODO\n  throw std::runtime_error(\"ProbitNoise::evalModel unimplemented.\");\n}\n\n\nvoid FixedGaussianNoise::evalModel(TensorData & data, const int n, Eigen::VectorXd & predictions, Eigen::VectorXd & predictions_var,\n        std::vector< std::unique_ptr<Eigen::MatrixXd> > & samples) {\n  auto rmse = eval_rmse_tensor(data.Ytest, n, predictions, predictions_var, samples, data.mean_value);\n  rmse_test = rmse.second;\n  rmse_test_onesample = rmse.first;\n}\n\nvoid AdaptiveGaussianNoise::evalModel(TensorData & data, const int n, Eigen::VectorXd & predictions, Eigen::VectorXd & predictions_var,\n        std::vector< std::unique_ptr<Eigen::MatrixXd> > & samples) {\n  auto rmse = eval_rmse_tensor(data.Ytest, n, predictions, predictions_var, samples, data.mean_value);\n  rmse_test = rmse.second;\n  rmse_test_onesample = rmse.first;\n}\n\n//evalModel for Censored data\nvoid FixedGaussianNoise::evalModel(MatrixDataCensored & data, const int n, Eigen::VectorXd & predictions, Eigen::VectorXd & predictions_var,\n        std::vector< std::unique_ptr<Eigen::MatrixXd> > & samples) {\n  auto rmse = eval_rmse(data.Ytest, n, predictions, predictions_var, *samples[1], *samples[0], data.mean_value);\n  rmse_test = rmse.second;\n  rmse_test_onesample = rmse.first;\n}\n\nvoid AdaptiveGaussianNoise::evalModel(MatrixDataCensored & data, const int n, Eigen::VectorXd & predictions, Eigen::VectorXd & predictions_var,\n        std::vector< std::unique_ptr<Eigen::MatrixXd> > & samples) {\n  //TODO\n  throw std::runtime_error(\"evalModel not implemented for Censored Data and adaptive noise\");\n}\n\nvoid ProbitNoise::evalModel(MatrixDataCensored & data, const int n, Eigen::VectorXd & predictions, Eigen::VectorXd & predictions_var,\n        std::vector< std::unique_ptr<Eigen::MatrixXd> > & samples) {\n//TODO\nthrow std::runtime_error(\"evalModel not implemented for Censored Data and probit noise\");\n}\n", "meta": {"hexsha": "6666c47d7b4fde0ac8ec367dbde88824b6033cef", "size": 7747, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/macau-cpp/noisemodels.cpp", "max_stars_repo_name": "edebrouwer/macau", "max_stars_repo_head_hexsha": "0b22d21ed954209406246e70178523102e98f922", "max_stars_repo_licenses": ["MIT"], "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/macau-cpp/noisemodels.cpp", "max_issues_repo_name": "edebrouwer/macau", "max_issues_repo_head_hexsha": "0b22d21ed954209406246e70178523102e98f922", "max_issues_repo_licenses": ["MIT"], "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/macau-cpp/noisemodels.cpp", "max_forks_repo_name": "edebrouwer/macau", "max_forks_repo_head_hexsha": "0b22d21ed954209406246e70178523102e98f922", "max_forks_repo_licenses": ["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.3744292237, "max_line_length": 143, "alphanum_fraction": 0.6579321027, "num_tokens": 2239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.4535101742573441}}
{"text": "\n#include <Eigen/SparseCore>\n\nextern \"C\" {\n\nsize_t\nprod_nnz(\n        size_t          a_rows,\n        size_t          a_cols,\n        size_t          b_cols,\n        const int64_t * a_indptr,\n        const int64_t * a_indices,\n        const double *  a_data,\n        const int64_t * b_indptr,\n        const int64_t * b_indices,\n        const double *  b_data\n    )\n{\n    typedef Eigen::SparseMatrix<double, Eigen::RowMajor, int64_t> SpMat;\n    int64_t a_nnz = a_indptr[a_rows];\n    int64_t b_nnz = b_indptr[a_cols];\n    Eigen::Map<const SpMat> a(\n        a_rows, a_cols, a_nnz, a_indptr, a_indices, a_data\n    );\n    Eigen::Map<const SpMat> b(\n        a_cols, b_cols, b_nnz, b_indptr, b_indices, b_data\n    );\n    SpMat c = a * b;\n    return c.nonZeros();\n}\n\n} // extern C\n", "meta": {"hexsha": "e09a5401a86166139b71994113911e9e04bc0764", "size": 772, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sprs-benches/src/eigen.cpp", "max_stars_repo_name": "TristanCacqueray/sprs", "max_stars_repo_head_hexsha": "38953136024e1814895b560951f41d0e10c42d16", "max_stars_repo_licenses": ["Apache-2.0", "MIT"], "max_stars_count": 281.0, "max_stars_repo_stars_event_min_datetime": "2015-07-31T16:27:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T01:35:15.000Z", "max_issues_repo_path": "sprs-benches/src/eigen.cpp", "max_issues_repo_name": "TristanCacqueray/sprs", "max_issues_repo_head_hexsha": "38953136024e1814895b560951f41d0e10c42d16", "max_issues_repo_licenses": ["Apache-2.0", "MIT"], "max_issues_count": 232.0, "max_issues_repo_issues_event_min_datetime": "2015-07-03T18:08:51.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T17:27:21.000Z", "max_forks_repo_path": "sprs-benches/src/eigen.cpp", "max_forks_repo_name": "TristanCacqueray/sprs", "max_forks_repo_head_hexsha": "38953136024e1814895b560951f41d0e10c42d16", "max_forks_repo_licenses": ["Apache-2.0", "MIT"], "max_forks_count": 45.0, "max_forks_repo_forks_event_min_datetime": "2015-09-10T11:38:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T23:51:34.000Z", "avg_line_length": 23.3939393939, "max_line_length": 72, "alphanum_fraction": 0.5829015544, "num_tokens": 234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.453510174257344}}
{"text": "/**\n * \\ file ButterworthFilter.cpp\n */\n\n#include <ATK/EQ/ButterworthFilter.h>\n#include <ATK/EQ/IIRFilter.h>\n\n#include <ATK/Mock/FFTCheckerFilter.h>\n#include <ATK/Mock/SimpleSinusGeneratorFilter.h>\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_NO_MAIN\n#include <boost/test/unit_test.hpp>\n\n#define PROCESSSIZE (1024*64)\n\nBOOST_AUTO_TEST_CASE( IIRFilter_ButterworthLowPassCoefficients_1k_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(1000);\n  \n  ATK::IIRFilter<ATK::ButterworthLowPassCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_cut_frequency(100);\n  filter.set_order(3);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(100, 0));\n  frequency_checks.push_back(std::make_pair(1000, 0.03158665365618605));\n  frequency_checks.push_back(std::make_pair(10000, 0));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_ButterworthLowPassCoefficients_100_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(100);\n  \n  ATK::IIRFilter<ATK::ButterworthLowPassCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_cut_frequency(100);\n  filter.set_order(3);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(10, 0));\n  frequency_checks.push_back(std::make_pair(100, 0.8408964151592208));\n  frequency_checks.push_back(std::make_pair(1000, 0));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_ButterworthLowPassCoefficients_2k_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(2000);\n  \n  ATK::IIRFilter<ATK::ButterworthLowPassCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_cut_frequency(100);\n  filter.set_order(3);\n\n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(100, 0));\n  frequency_checks.push_back(std::make_pair(1000, 0));\n  frequency_checks.push_back(std::make_pair(2000, 0.011129047318919743));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_ButterworthLowPassCoefficients_200_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(200);\n  \n  ATK::IIRFilter<ATK::ButterworthLowPassCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_cut_frequency(100);\n  filter.set_order(3);\n\n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(100, 0));\n  frequency_checks.push_back(std::make_pair(200, 0.3520674471793266));\n  frequency_checks.push_back(std::make_pair(1000, 0));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_ButterworthHighPassCoefficients_1k_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(1000);\n  \n  ATK::IIRFilter<ATK::ButterworthHighPassCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_cut_frequency(100);\n  filter.set_order(3);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(100, 0));\n  frequency_checks.push_back(std::make_pair(1000, 1));\n  frequency_checks.push_back(std::make_pair(10000, 0));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_ButterworthHighPassCoefficients_100_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(100);\n  \n  ATK::IIRFilter<ATK::ButterworthHighPassCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_cut_frequency(100);\n  filter.set_order(3);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(10, 0));\n  frequency_checks.push_back(std::make_pair(100, 0.8408964152940196));\n  frequency_checks.push_back(std::make_pair(1000, 0));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_ButterworthHighPassCoefficients_2k_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(2000);\n  \n  ATK::IIRFilter<ATK::ButterworthHighPassCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_cut_frequency(100);\n  filter.set_order(3);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(100, 0));\n  frequency_checks.push_back(std::make_pair(1000, 0));\n  frequency_checks.push_back(std::make_pair(2000, 1));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_ButterworthHighPassCoefficients_200_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(200);\n  \n  ATK::IIRFilter<ATK::ButterworthHighPassCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_cut_frequency(100);\n  filter.set_order(3);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(100, 0));\n  frequency_checks.push_back(std::make_pair(200, 0.9961319837713813));\n  frequency_checks.push_back(std::make_pair(1000, 0));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_ButterworthBandPassCoefficients_1k_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(1000);\n  \n  ATK::IIRFilter<ATK::ButterworthBandPassCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_cut_frequencies(std::make_pair(200, 1000));\n  filter.set_order(3);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(100, 0));\n  frequency_checks.push_back(std::make_pair(1000, 0.8406150184993316));\n  frequency_checks.push_back(std::make_pair(10000, 0));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_ButterworthBandPassCoefficients_100_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(100);\n  \n  ATK::IIRFilter<ATK::ButterworthBandPassCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_cut_frequencies(std::make_pair(200, 1000));\n  filter.set_order(3);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(10, 0));\n  frequency_checks.push_back(std::make_pair(100, 0.27288445508133696));\n  frequency_checks.push_back(std::make_pair(1000, 0));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_ButterworthBandPassCoefficients_2k_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(2000);\n  \n  ATK::IIRFilter<ATK::ButterworthBandPassCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_cut_frequencies(std::make_pair(200, 1000));\n  filter.set_order(3);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(100, 0));\n  frequency_checks.push_back(std::make_pair(1000, 0));\n  frequency_checks.push_back(std::make_pair(2000, 0.27185528281637));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_ButterworthBandPassCoefficients_200_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(200);\n  \n  ATK::IIRFilter<ATK::ButterworthBandPassCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_cut_frequencies(std::make_pair(200, 1000));\n  filter.set_order(3);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(100, 0));\n  frequency_checks.push_back(std::make_pair(200, 0.8408965558193944));\n  frequency_checks.push_back(std::make_pair(1000, 0));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_ButterworthBandStopCoefficients_1k_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(1000);\n  \n  ATK::IIRFilter<ATK::ButterworthBandStopCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_cut_frequencies(std::make_pair(200, 1000));\n  filter.set_order(3);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(100, 0));\n  frequency_checks.push_back(std::make_pair(1000, 0.8406817187144716));\n  frequency_checks.push_back(std::make_pair(10000, 0));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_ButterworthBandStopCoefficients_100_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(100);\n  \n  ATK::IIRFilter<ATK::ButterworthBandStopCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_cut_frequencies(std::make_pair(200, 1000));\n  filter.set_order(3);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(10, 0));\n  frequency_checks.push_back(std::make_pair(100, 0.9981831475045972));\n  frequency_checks.push_back(std::make_pair(1000, 0));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_ButterworthBandStopCoefficients_2k_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(2000);\n  \n  ATK::IIRFilter<ATK::ButterworthBandStopCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_cut_frequencies(std::make_pair(200, 1000));\n  filter.set_order(3);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(100, 0));\n  frequency_checks.push_back(std::make_pair(1000, 0));\n  frequency_checks.push_back(std::make_pair(2000, 0.9985753881639808));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n\nBOOST_AUTO_TEST_CASE( IIRFilter_ButterworthBandStopCoefficients_200_test )\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(1024*64);\n  generator.set_amplitude(1);\n  generator.set_frequency(200);\n  \n  ATK::IIRFilter<ATK::ButterworthBandStopCoefficients<double> > filter;\n  filter.set_input_sampling_rate(1024*64);\n  filter.set_output_sampling_rate(1024*64);\n  filter.set_cut_frequencies(std::make_pair(200, 1000));\n  filter.set_order(3);\n  \n  ATK::FFTCheckerFilter<double> checker;\n  checker.set_input_sampling_rate(1024*64);\n  std::vector<std::pair<int, double> > frequency_checks;\n  frequency_checks.push_back(std::make_pair(100, 0));\n  frequency_checks.push_back(std::make_pair(200, 0.8408969221170415));\n  frequency_checks.push_back(std::make_pair(1000, 0));\n  checker.set_checks(frequency_checks);\n  \n  checker.set_input_port(0, &filter, 0);\n  filter.set_input_port(0, &generator, 0);\n  \n  filter.process(1024*64);\n  \n  checker.process(PROCESSSIZE);\n}\n", "meta": {"hexsha": "8007b038e3529d22174c74eb76a376abed4a421c", "size": 16109, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/EQ/ButterworthFilter.cpp", "max_stars_repo_name": "apohl79/AudioTK", "max_stars_repo_head_hexsha": "05ac241b0bc6a8f841d93257b4d81e5961b1f627", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-05-17T15:29:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T22:26:08.000Z", "max_issues_repo_path": "tests/EQ/ButterworthFilter.cpp", "max_issues_repo_name": "apohl79/AudioTK", "max_issues_repo_head_hexsha": "05ac241b0bc6a8f841d93257b4d81e5961b1f627", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/EQ/ButterworthFilter.cpp", "max_forks_repo_name": "apohl79/AudioTK", "max_forks_repo_head_hexsha": "05ac241b0bc6a8f841d93257b4d81e5961b1f627", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-04-21T13:43:57.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-28T19:10:14.000Z", "avg_line_length": 33.5604166667, "max_line_length": 74, "alphanum_fraction": 0.775342976, "num_tokens": 4457, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4535101685951034}}
{"text": "#include <boost/geometry/arithmetic/determinant.hpp>\n", "meta": {"hexsha": "81299826b3e3a41b5f12b89e93ee3375fd0630fb", "size": 53, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_geometry_arithmetic_determinant.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_geometry_arithmetic_determinant.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_geometry_arithmetic_determinant.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 26.5, "max_line_length": 52, "alphanum_fraction": 0.8301886792, "num_tokens": 12, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996142, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.45351016859510335}}
{"text": "#ifndef HOPS_DEGENERATEMULTIVARIATEGAUSSIANMODEL_HPP\n#define HOPS_DEGENERATEMULTIVARIATEGAUSSIANMODEL_HPP\n\n#define _USE_MATH_DEFINES\n#include <math.h>\n#include <Eigen/Cholesky>\n#include <Eigen/Core>\n#include <Eigen/LU>\n#include <utility>\n\nnamespace hops {\n    template<typename Matrix, typename Vector>\n    class DegenerateMultivariateGaussianModel {\n    public:\n        using MatrixType = Matrix;\n        using VectorType = Vector;\n\n        DegenerateMultivariateGaussianModel(VectorType mean, MatrixType covariance, std::vector<long> inactive = std::vector<long>(0));\n\n        typename MatrixType::Scalar computeNegativeLogLikelihood(const VectorType &x) const;\n\n        MatrixType computeExpectedFisherInformation(const VectorType &) const;\n\n        VectorType computeLogLikelihoodGradient(const VectorType &x) const;\n\n    private:\n        VectorType mean;\n        MatrixType covariance;\n        std::vector<long> inactive;\n        MatrixType inverseCovariance;\n        typename MatrixType::Scalar logNormalizationConstant;\n\n        void removeRow(Eigen::MatrixXd& matrix, unsigned int rowToRemove) const {\n            unsigned int numRows = matrix.rows()-1;\n            unsigned int numCols = matrix.cols();\n\n            if (rowToRemove < numRows) {\n                matrix.block(rowToRemove,0,numRows-rowToRemove,numCols) = matrix.bottomRows(numRows-rowToRemove);\n            }\n\n            matrix.conservativeResize(numRows,numCols);\n        }\n\n        void removeColumn(Eigen::MatrixXd& matrix, unsigned int colToRemove) const {\n            unsigned int numRows = matrix.rows();\n            unsigned int numCols = matrix.cols()-1;\n\n            if (colToRemove < numCols) {\n                matrix.block(0,colToRemove,numRows,numCols-colToRemove) = matrix.rightCols(numCols-colToRemove);\n            }\n\n            matrix.conservativeResize(numRows,numCols);\n        }\n\n        void removeRow(Eigen::VectorXd& vector, unsigned int rowToRemove) const {\n            unsigned int numRows = vector.rows()-1;\n\n            if (rowToRemove < numRows) {\n                vector.segment(rowToRemove,numRows-rowToRemove) = vector.tail(numRows-rowToRemove);\n            }\n\n            vector.conservativeResize(numRows);\n        }\n\n        void stripInactive (Eigen::MatrixXd& matrix) const {\n            for (auto& i : inactive) {\n                removeRow(matrix, i);\n                removeColumn(matrix, i);\n            }\n        }\n\n        void stripInactive (Eigen::VectorXd& vector) const {\n            for (auto& i : inactive) {\n                removeRow(vector, i);\n            }\n        }\n    };\n\n    template<typename MatrixType, typename VectorType>\n    DegenerateMultivariateGaussianModel<MatrixType, VectorType>::DegenerateMultivariateGaussianModel(VectorType mean,\n                                                                                 MatrixType covariance,\n                                                                                 std::vector<long> inactive) :\n        mean(mean),\n        covariance(covariance),\n        inactive(inactive)\n    {\n        stripInactive(this->mean);\n        stripInactive(this->covariance);\n\n        Eigen::LLT<MatrixType, Eigen::Upper> solver(this->covariance);\n        Eigen::Matrix<typename MatrixType::Scalar, Eigen::Dynamic, Eigen::Dynamic> matrixL = solver.matrixL();\n        Eigen::Matrix<typename MatrixType::Scalar, Eigen::Dynamic, Eigen::Dynamic> matrixU = solver.matrixU();\n        Eigen::Matrix<typename MatrixType::Scalar, Eigen::Dynamic, Eigen::Dynamic> inverseMatrixL = matrixL.inverse();\n        inverseCovariance = inverseMatrixL * inverseMatrixL.transpose();\n\n        logNormalizationConstant = -static_cast<typename MatrixType::Scalar>(this->mean.rows()) / 2 *\n                                   std::log(2 * M_PI)\n                                   - matrixL.diagonal().array().log().sum();\n    }\n\n    template<typename MatrixType, typename VectorType>\n    typename MatrixType::Scalar\n    DegenerateMultivariateGaussianModel<MatrixType, VectorType>::computeNegativeLogLikelihood(const VectorType &x) const {\n        VectorType _x = x;\n        stripInactive(_x);\n        return -logNormalizationConstant +\n               0.5 * static_cast<typename MatrixType::Scalar>((_x - mean).transpose() * inverseCovariance * (_x - mean));\n    }\n\n    template<typename MatrixType, typename VectorType>\n    MatrixType\n    DegenerateMultivariateGaussianModel<MatrixType, VectorType>::computeExpectedFisherInformation(const VectorType &) const {\n        return inverseCovariance;\n    }\n\n    template<typename MatrixType, typename VectorType>\n    VectorType\n    DegenerateMultivariateGaussianModel<MatrixType, VectorType>::computeLogLikelihoodGradient(const VectorType &x) const {\n        VectorType _x = x;\n        stripInactive(_x);\n        return -inverseCovariance * (_x - mean);\n    }\n}\n\n#endif //HOPS_DEGENERATEMULTIVARIATEGAUSSIANMODEL_HPP\n", "meta": {"hexsha": "ff5090df8c0de51122a98301faef9ee234bd59a8", "size": 4906, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/hops/Model/DegenerateMultivariateGaussianModel.hpp", "max_stars_repo_name": "modsim/hops", "max_stars_repo_head_hexsha": "4285dd75a07dd844295440a0756b3ba25f5819ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2020-11-26T05:13:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T02:08:40.000Z", "max_issues_repo_path": "include/hops/Model/DegenerateMultivariateGaussianModel.hpp", "max_issues_repo_name": "modsim/hops", "max_issues_repo_head_hexsha": "4285dd75a07dd844295440a0756b3ba25f5819ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-02-20T23:16:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-20T23:16:34.000Z", "max_forks_repo_path": "include/hops/Model/DegenerateMultivariateGaussianModel.hpp", "max_forks_repo_name": "modsim/hops", "max_forks_repo_head_hexsha": "4285dd75a07dd844295440a0756b3ba25f5819ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.9365079365, "max_line_length": 135, "alphanum_fraction": 0.6418671015, "num_tokens": 1018, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905302989295534, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.45351016293286256}}
{"text": "#ifndef STAN_MATH_PRIM_PROB_NEG_BINOMIAL_RNG_HPP\n#define STAN_MATH_PRIM_PROB_NEG_BINOMIAL_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 shape and\n * inverse scale parameters using the given random number generator.\n *\n * alpha and beta can each be a scalar or a one-dimensional container. Any\n * non-scalar inputs must be the same size.\n *\n * @tparam T_shape type of shape parameter\n * @tparam T_inv type of inverse scale parameter\n * @tparam RNG type of random number generator\n * @param alpha (Sequence of) positive shape parameter(s)\n * @param beta (Sequence of) positive inverse scale parameter(s)\n * @param rng random number generator\n * @return (Sequence of) negative binomial random variate(s)\n * @throw std::domain_error if alpha or beta are nonpositive\n * @throw std::invalid_argument if non-scalar arguments are of different\n * sizes\n */\ntemplate <typename T_shape, typename T_inv, class RNG>\ninline typename VectorBuilder<true, int, T_shape, T_inv>::type neg_binomial_rng(\n    const T_shape& alpha, const T_inv& beta, RNG& rng) {\n  using boost::gamma_distribution;\n  using boost::variate_generator;\n  using boost::random::poisson_distribution;\n  using T_alpha_ref = ref_type_t<T_shape>;\n  using T_beta_ref = ref_type_t<T_inv>;\n  static const char* function = \"neg_binomial_rng\";\n  check_consistent_sizes(function, \"Shape parameter\", alpha,\n                         \"Inverse scale Parameter\", beta);\n  T_alpha_ref alpha_ref = alpha;\n  T_beta_ref beta_ref = beta;\n  check_positive_finite(function, \"Shape parameter\", alpha_ref);\n  check_positive_finite(function, \"Inverse scale parameter\", beta_ref);\n\n  scalar_seq_view<T_alpha_ref> alpha_vec(alpha_ref);\n  scalar_seq_view<T_beta_ref> beta_vec(beta_ref);\n  size_t N = max_size(alpha, beta);\n  VectorBuilder<true, int, T_shape, T_inv> output(N);\n\n  for (size_t n = 0; n < N; ++n) {\n    double rng_from_gamma = variate_generator<RNG&, gamma_distribution<> >(\n        rng, gamma_distribution<>(alpha_vec[n], 1.0 / beta_vec[n]))();\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": "c8b527dcc235937e0a4d37b7b3cb9ea66734cfbb", "size": 3008, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/prim/prob/neg_binomial_rng.hpp", "max_stars_repo_name": "bayesmix-dev/math", "max_stars_repo_head_hexsha": "3616f7195adc95ef8e719a2af845d61102bc9272", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-14T14:33:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-14T14:33:37.000Z", "max_issues_repo_path": "stan/math/prim/prob/neg_binomial_rng.hpp", "max_issues_repo_name": "bayesmix-dev/math", "max_issues_repo_head_hexsha": "3616f7195adc95ef8e719a2af845d61102bc9272", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/neg_binomial_rng.hpp", "max_forks_repo_name": "bayesmix-dev/math", "max_forks_repo_head_hexsha": "3616f7195adc95ef8e719a2af845d61102bc9272", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-05-10T12:55:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-10T12:55:07.000Z", "avg_line_length": 39.0649350649, "max_line_length": 80, "alphanum_fraction": 0.7323803191, "num_tokens": 706, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581741774411, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4534170405309413}}
{"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_STRATEGIES_SPHERICAL_DISTANCE_CROSS_TRACK_HPP\n#define BOOST_GEOMETRY_STRATEGIES_SPHERICAL_DISTANCE_CROSS_TRACK_HPP\n\n\n#include <boost/concept_check.hpp>\n#include <boost/mpl/if.hpp>\n#include <boost/type_traits.hpp>\n\n#include <boost/geometry/core/cs.hpp>\n#include <boost/geometry/core/access.hpp>\n#include <boost/geometry/core/radian_access.hpp>\n\n\n#include <boost/geometry/strategies/distance.hpp>\n#include <boost/geometry/strategies/concepts/distance_concept.hpp>\n\n#include <boost/geometry/util/promote_floating_point.hpp>\n#include <boost/geometry/util/math.hpp>\n\n#ifdef BOOST_GEOMETRY_DEBUG_CROSS_TRACK\n#  include <boost/geometry/io/dsv/write.hpp>\n#endif\n\n\n\nnamespace boost { namespace geometry\n{\n\nnamespace strategy { namespace distance\n{\n\n/*!\n\\brief Strategy functor for distance point to segment calculation\n\\ingroup strategies\n\\details Class which calculates the distance of a point to a segment, using latlong points\n\\see http://williams.best.vwh.net/avform.htm\n\\tparam Point point type\n\\tparam PointOfSegment \\tparam_segment_point\n\\tparam CalculationType \\tparam_calculation\n\\tparam Strategy underlying point-point distance strategy, defaults to haversine\n\n\\qbk{\n[heading See also]\n[link geometry.reference.algorithms.distance.distance_3_with_strategy distance (with strategy)]\n}\n\n*/\ntemplate\n<\n    typename Point,\n    typename PointOfSegment = Point,\n    typename CalculationType = void,\n    typename Strategy = typename services::default_strategy<point_tag, Point>::type\n>\nclass cross_track\n{\npublic :\n    typedef typename promote_floating_point\n        <\n            typename select_calculation_type\n                <\n                    Point,\n                    PointOfSegment,\n                    CalculationType\n                >::type\n        >::type return_type;\n\n    inline cross_track()\n    {\n        m_strategy = Strategy();\n        m_radius = m_strategy.radius();\n    }\n\n    inline cross_track(return_type const& r)\n        : m_radius(r)\n        , m_strategy(r)\n    {}\n\n    inline cross_track(Strategy const& s)\n        : m_strategy(s)\n    {\n        m_radius = m_strategy.radius();\n    }\n\n\n    // It might be useful in the future\n    // to overload constructor with strategy info.\n    // crosstrack(...) {}\n\n\n    inline return_type apply(Point const& p,\n                PointOfSegment const& sp1, PointOfSegment const& sp2) const\n    {\n        // http://williams.best.vwh.net/avform.htm#XTE\n        return_type d1 = m_strategy.apply(sp1, p);\n\n        // Actually, calculation of d2 not necessary if we know that the projected point is on the great circle...\n        return_type d2 = m_strategy.apply(sp2, p);\n\n        return_type crs_AD = course(sp1, p);\n        return_type crs_AB = course(sp1, sp2);\n        return_type XTD = m_radius * geometry::math::abs(asin(sin(d1 / m_radius) * sin(crs_AD - crs_AB)));\n\n#ifdef BOOST_GEOMETRY_DEBUG_CROSS_TRACK\nstd::cout << \"Course \" << dsv(sp1) << \" to \" << dsv(p) << \" \" << crs_AD * geometry::math::r2d << std::endl;\nstd::cout << \"Course \" << dsv(sp1) << \" to \" << dsv(sp2) << \" \" << crs_AB * geometry::math::r2d << std::endl;\nstd::cout << \"XTD: \" << XTD << \" d1: \" <<  d1  << \" d2: \" <<  d2  << std::endl;\n#endif\n\n\n        // Return shortest distance, either to projected point on segment sp1-sp2, or to sp1, or to sp2\n        return return_type((std::min)((std::min)(d1, d2), XTD));\n    }\n\n    inline return_type radius() const { return m_radius; }\n\nprivate :\n    BOOST_CONCEPT_ASSERT\n        (\n            (geometry::concept::PointDistanceStrategy<Strategy >)\n        );\n\n\n    return_type m_radius;\n\n    // Point-point distances are calculated in radians, on the unit sphere\n    Strategy m_strategy;\n\n    /// Calculate course (bearing) between two points. Might be moved to a \"course formula\" ...\n    inline return_type course(Point const& p1, Point const& p2) const\n    {\n        // http://williams.best.vwh.net/avform.htm#Crs\n        return_type dlon = get_as_radian<0>(p2) - get_as_radian<0>(p1);\n        return_type cos_p2lat = cos(get_as_radian<1>(p2));\n\n        // \"An alternative formula, not requiring the pre-computation of d\"\n        return atan2(sin(dlon) * cos_p2lat,\n            cos(get_as_radian<1>(p1)) * sin(get_as_radian<1>(p2))\n            - sin(get_as_radian<1>(p1)) * cos_p2lat * cos(dlon));\n    }\n\n};\n\n\n\n#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\nnamespace services\n{\n\ntemplate <typename Point, typename PointOfSegment, typename CalculationType, typename Strategy>\nstruct tag<cross_track<Point, PointOfSegment, CalculationType, Strategy> >\n{\n    typedef strategy_tag_distance_point_segment type;\n};\n\n\ntemplate <typename Point, typename PointOfSegment, typename CalculationType, typename Strategy>\nstruct return_type<cross_track<Point, PointOfSegment, CalculationType, Strategy> >\n{\n    typedef typename cross_track<Point, PointOfSegment, CalculationType, Strategy>::return_type type;\n};\n\n\ntemplate\n<\n    typename Point,\n    typename PointOfSegment,\n    typename CalculationType,\n    typename Strategy,\n    typename P,\n    typename PS\n>\nstruct similar_type<cross_track<Point, PointOfSegment, CalculationType, Strategy>, P, PS>\n{\n    typedef cross_track<Point, PointOfSegment, CalculationType, Strategy> type;\n};\n\n\ntemplate\n<\n    typename Point,\n    typename PointOfSegment,\n    typename CalculationType,\n    typename Strategy,\n    typename P,\n    typename PS\n>\nstruct get_similar<cross_track<Point, PointOfSegment, CalculationType, Strategy>, P, PS>\n{\n    static inline typename similar_type\n        <\n            cross_track<Point, PointOfSegment, CalculationType, Strategy>, P, PS\n        >::type apply(cross_track<Point, PointOfSegment, CalculationType, Strategy> const& strategy)\n    {\n        return cross_track<P, PS, CalculationType, Strategy>(strategy.radius());\n    }\n};\n\n\ntemplate <typename Point, typename PointOfSegment, typename CalculationType, typename Strategy>\nstruct comparable_type<cross_track<Point, PointOfSegment, CalculationType, Strategy> >\n{\n    // Comparable type is here just the strategy\n    typedef typename similar_type\n        <\n            cross_track\n                <\n                    Point, PointOfSegment, CalculationType, Strategy\n                >, Point, PointOfSegment\n        >::type type;\n};\n\n\ntemplate \n<\n    typename Point, typename PointOfSegment, \n    typename CalculationType, \n    typename Strategy\n>\nstruct get_comparable<cross_track<Point, PointOfSegment, CalculationType, Strategy> >\n{\n    typedef typename comparable_type\n        <\n            cross_track<Point, PointOfSegment, CalculationType, Strategy>\n        >::type comparable_type;\npublic :\n    static inline comparable_type apply(cross_track<Point, PointOfSegment, CalculationType, Strategy> const& strategy)\n    {\n        return comparable_type(strategy.radius());\n    }\n};\n\n\ntemplate \n<\n    typename Point, typename PointOfSegment, \n    typename CalculationType, \n    typename Strategy\n>\nstruct result_from_distance<cross_track<Point, PointOfSegment, CalculationType, Strategy> >\n{\nprivate :\n    typedef typename cross_track<Point, PointOfSegment, CalculationType, Strategy>::return_type return_type;\npublic :\n    template <typename T>\n    static inline return_type apply(cross_track<Point, PointOfSegment, CalculationType, Strategy> const& , T const& distance)\n    {\n        return distance;\n    }\n};\n\n\ntemplate \n<\n    typename Point, typename PointOfSegment, \n    typename CalculationType, \n    typename Strategy\n>\nstruct strategy_point_point<cross_track<Point, PointOfSegment, CalculationType, Strategy> >\n{\n    typedef Strategy type;\n};\n\n\n\n/*\n\nTODO:  spherical polar coordinate system requires \"get_as_radian_equatorial<>\"\n\ntemplate <typename Point, typename PointOfSegment, typename Strategy>\nstruct default_strategy\n    <\n        segment_tag, Point, PointOfSegment, \n        spherical_polar_tag, spherical_polar_tag, \n        Strategy\n    >\n{\n    typedef cross_track\n        <\n            Point,\n            PointOfSegment,\n            void,\n            typename boost::mpl::if_\n                <\n                    boost::is_void<Strategy>,\n                    typename default_strategy\n                        <\n                            point_tag, Point, PointOfSegment,\n                            spherical_polar_tag, spherical_polar_tag\n                        >::type,\n                    Strategy\n                >::type\n        > type;\n};\n*/\n\ntemplate <typename Point, typename PointOfSegment, typename Strategy>\nstruct default_strategy\n    <\n        segment_tag, Point, PointOfSegment, \n        spherical_equatorial_tag, spherical_equatorial_tag, \n        Strategy\n    >\n{\n    typedef cross_track\n        <\n            Point,\n            PointOfSegment,\n            void,\n            typename boost::mpl::if_\n                <\n                    boost::is_void<Strategy>,\n                    typename default_strategy\n                        <\n                            point_tag, Point, PointOfSegment,\n                            spherical_equatorial_tag, spherical_equatorial_tag\n                        >::type,\n                    Strategy\n                >::type\n        > type;\n};\n\n\n\n} // namespace services\n#endif // DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\n\n\n}} // namespace strategy::distance\n\n\n#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\n\n\n#endif\n\n\n}} // namespace boost::geometry\n\n\n#endif // BOOST_GEOMETRY_STRATEGIES_SPHERICAL_DISTANCE_CROSS_TRACK_HPP\n", "meta": {"hexsha": "ba589223ecadbee1ad46b0726cdb9be4ad46415d", "size": 9719, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/geometry/strategies/spherical/distance_cross_track.hpp", "max_stars_repo_name": "brinkqiang/dmspirit", "max_stars_repo_head_hexsha": "4eb09bed3a69d9327610560fe38c54d9f24112d8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-01-10T05:04:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-25T10:10:39.000Z", "max_issues_repo_path": "Boost_1_49/boost/geometry/strategies/spherical/distance_cross_track.hpp", "max_issues_repo_name": "jjzhang166/WinUtil4", "max_issues_repo_head_hexsha": "7c7b1e9bbe2fb6177bb066d74764d10711748ec5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Boost_1_49/boost/geometry/strategies/spherical/distance_cross_track.hpp", "max_forks_repo_name": "jjzhang166/WinUtil4", "max_forks_repo_head_hexsha": "7c7b1e9bbe2fb6177bb066d74764d10711748ec5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-11-08T01:56:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-21T09:02:49.000Z", "avg_line_length": 27.7685714286, "max_line_length": 125, "alphanum_fraction": 0.6686901945, "num_tokens": 2163, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286833, "lm_q2_score": 0.6150878555160666, "lm_q1q2_score": 0.45341703342744066}}
{"text": "#include \"io_utils.h\"\n\n#include <Eigen/Dense>\n#include <fstream>\n\nEigen::MatrixXd bayesmix::read_eigen_matrix(const std::string &filename,\n                                            const char delim /* = ','*/) {\n  // Initialize objects\n  unsigned int cols = 0, rows = 0;\n  double buffer[MAXBUFSIZE];\n  std::ifstream filestream(filename);\n  if (!filestream.is_open()) {\n    std::string err = \"File \" + filename + \" does not exist\";\n    throw std::invalid_argument(err);\n  }\n\n  // Loop over file lines\n  std::string line, entry;\n  while (getline(filestream, line, '\\n')) {\n    unsigned int temp = 0;\n    std::stringstream linestream(line);\n    while (getline(linestream, entry, delim)) {\n      // Place read values into the buffer array\n      std::stringstream entrystream(entry);\n      entrystream >> buffer[cols * rows + temp++];\n    }\n    if (temp == 0) {\n      continue;\n    }\n    if (cols == 0) {\n      cols = temp;\n    }\n    rows++;\n  }\n\n  filestream.close();\n\n  // Fill an Eigen Matrix with values from the buffer array\n  Eigen::MatrixXd mat(rows, cols);\n  for (size_t i = 0; i < rows; i++) {\n    for (size_t j = 0; j < cols; j++) {\n      mat(i, j) = buffer[cols * i + j];\n    }\n  }\n  return mat;\n};\n\nvoid bayesmix::write_matrix_to_file(const Eigen::MatrixXd &mat,\n                                    const std::string &filename,\n                                    const char delim /*= ','*/) {\n  using namespace Eigen;\n  std::string del;\n  del = delim;\n  const IOFormat CSVFormat(StreamPrecision, DontAlignCols, del, \"\\n\");\n  std::ofstream file(filename.c_str());\n  file << mat.format(CSVFormat);\n}\n", "meta": {"hexsha": "3c4bf59c02522377e68a4ceb8913172c4bf2ddd4", "size": 1608, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/utils/io_utils.cc", "max_stars_repo_name": "edoardopalli/bayesmix", "max_stars_repo_head_hexsha": "2253d97b58e9d5fe9bd769944ae46cab0d938819", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_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/io_utils.cc", "max_issues_repo_name": "edoardopalli/bayesmix", "max_issues_repo_head_hexsha": "2253d97b58e9d5fe9bd769944ae46cab0d938819", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/io_utils.cc", "max_forks_repo_name": "edoardopalli/bayesmix", "max_forks_repo_head_hexsha": "2253d97b58e9d5fe9bd769944ae46cab0d938819", "max_forks_repo_licenses": ["BSD-3-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.724137931, "max_line_length": 74, "alphanum_fraction": 0.5808457711, "num_tokens": 411, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.7371581568543043, "lm_q1q2_score": 0.4534170298756902}}
{"text": "#include <cassert>\n\n#include <iostream>\n#include <fstream>\n\n#include <boost/program_options.hpp>\n\n#include <graphlab.hpp>\n\n#include \"factor_graph.hpp\"\n\n\n#include <graphlab/macros_def.hpp>\n\n\n\n// Types from the factor_graph.hpp\ntypedef factor_graph::factor_type factor_type;\ntypedef factor_graph::domain_type domain_type;\ntypedef factor_type::assignment_type  assignment_type;\ntypedef factor_graph::variable_type   variable_type;\n\n// Structs\n// ===========================================================================>\n\nstruct vertex_data {\n  factor_type potential;\n  factor_type belief;\n  void load(graphlab::iarchive& arc) {\n    arc >> potential;\n    arc >> belief;\n  }\n  void save(graphlab::oarchive& arc) const {\n    arc << potential;\n    arc << belief;\n  }\n}; // End of vertex data\n\nstruct edge_data {\n  factor_type message;\n  factor_type old_message;\n  void load(graphlab::iarchive& arc) {\n    arc >> message;\n    arc >> old_message;\n  }\n  void save(graphlab::oarchive& arc) const {\n    arc << message;\n    arc << old_message;\n  }\n}; // End of edge data\n\n\n// Define the graph types\ntypedef graphlab::graph<vertex_data, edge_data> graph_type;\ntypedef graphlab::types<graph_type> gl_types;\n\ndouble bound = 1e-5;\ndouble damping = 0.3;\n\n\n// Update Functions\n// ===========================================================================>\nvoid bp_update(gl_types::iscope& scope, \n               gl_types::icallback& scheduler) {\n   // Grab the state from the scope\n  // ------------------------------------------------------->\n  // Get the vertex data\n  vertex_data& vdata = scope.vertex_data();\n  \n  // Get the in and out edges by reference\n  const gl_types::edge_list in_edges = scope.in_edge_ids();\n  const gl_types::edge_list out_edges = scope.out_edge_ids();\n  assert(in_edges.size() == out_edges.size());\n\n  // Compute the belief\n  // ------------------------------------------------------->\n  // Initialize the belief as the value of the factor\n  vdata.belief = vdata.potential;\n  foreach(graphlab::edge_id_t ineid, in_edges) {\n    // Get the in and out edge data\n    edge_data& edata = scope.edge_data(ineid);\n    edata.old_message = edata.message;\n    vdata.belief *= edata.old_message;\n  }\n  vdata.belief.normalize();\n\n\n  // Compute outbound messages\n  // ------------------------------------------------>\n  // Send outbound messages\n  factor_type cavity, tmp_msg;\n  for(size_t i = 0; i < in_edges.size(); ++i) {\n    // Get the edge ids\n    const graphlab::edge_id_t outeid = out_edges[i];\n    const 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    // Create stack allocated cavity factor\n    cavity = vdata.belief;   \n    // Compute cavity\n    cavity /= in_edge.old_message; // Make the cavity a cavity\n    cavity.normalize();\n\n    // Create stack allocated temporary message\n    tmp_msg.set_args(out_edge.message.args());\n    assert(tmp_msg.num_vars() == 1);\n    tmp_msg.marginalize(cavity);\n    tmp_msg.normalize();\n\n    // Compute message residual\n    double residual = tmp_msg.l1_diff(out_edge.old_message);\n     // Damp the message\n    tmp_msg.damp(out_edge.message, damping);   \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\n/**\n * Construct a belief propagation graph from a factor graph\n */\nvoid make_bp_graph(const factor_graph& fgraph,\n                   gl_types::graph& graph) {\n  assert(!fgraph.variables().empty());\n  assert(!fgraph.factors().empty());\n  assert(fgraph.variables().rbegin()->id()\n         == fgraph.variables().size()-1);\n  vertex_data vdata;\n  // Add all the variables \n  foreach(factor_graph::variable_type variable, fgraph.variables()) {\n    factor_graph::domain_type domain(variable);\n    vdata.potential.set_args(domain);\n    vdata.potential.uniform();\n    vdata.belief = vdata.potential;  \n    graphlab::vertex_id_t vid = graph.add_vertex(vdata);\n    assert(vid == variable.id());\n  }\n  assert(graph.num_vertices() == fgraph.variables().size());\n  // Add all the factors and all the edges\n  size_t factor_index = graph.num_vertices();\n  edge_data edata;\n  foreach(const factor_graph::factor_type& factor, fgraph.factors()) {\n    // Setup the vertex data for a factor\n    vdata.potential = factor;\n    vdata.belief.set_args(factor.args());\n    vdata.belief.uniform();\n    // Add the factor to the graph\n    graphlab::vertex_id_t vid = graph.add_vertex(vdata);\n    assert(vid == factor_index);    \n    // Attach all the edges\n    for(size_t i = 0; i < factor.num_vars(); ++i) {\n      factor_graph::variable_type variable = factor.args().var(i);\n      factor_graph::domain_type domain(variable);\n      edata.message.set_args(domain);\n      edata.message.uniform();\n      edata.old_message = edata.message;     \n      graph.add_edge(factor_index, variable.id(), edata);                     \n      graph.add_edge(variable.id(), factor_index, edata);\n    }\n    ++factor_index;\n  }\n  graph.finalize();\n} // end of make_bp_graph\n\n\n/**\n * Save the final belief estimates to a text file.\n */\nvoid save_beliefs(const std::string& filename,\n                  factor_graph& fgraph,\n                  gl_types::graph& graph,\n                  size_t num_variables) {\n  // Open the file to store the final belief vectors\n  std::ofstream fout(filename.c_str());\n  assert(fout.good());\n  // Save all the beliefs\n  for(size_t i = 0; i < num_variables; ++i) {\n    vertex_data& vdata = graph.vertex_data(i);\n    vdata.belief.normalize();\n    fout << fgraph.var_name(i) << \" // \";\n    // Save the normalized belief estimates to the file\n    for(size_t j = 0; j < vdata.belief.size(); ++j) {\n      fout << std::exp(vdata.belief.logP(j));\n      if((j + 1) < vdata.belief.size()) fout << \", \";\n    }\n    fout << \"\\n\";\n  }\n  fout.close();   \n} // end of save beliefs\n\n\n\n\n// MAIN\n// ============================================================================>\nint main(int argc, char** argv) {\n  std::cout << \"This program solves the sidechain prediction task.\"\n            << std::endl;\n\n  // Parse command line arguments --------------------------------------------->\n  bound = 1E-5; // <-- Defined globally\n  damping = 0.3; // <-- Defined globally\n  std::string network_filename;\n  std::string beliefs_filename = \"beliefs.txt\";\n \n  \n  graphlab::command_line_options clopts(\"Run Loopy BP on an Alchemy Network\");\n  clopts.attach_option(\"graph\",\n                       &network_filename,\n                       \"The Alchemy factor graph file.\");\n  clopts.add_positional(\"graph\");\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(\"beliefs\",\n                       &beliefs_filename, beliefs_filename,\n                       \"The file to save the belief predictions\"); \n  clopts.set_scheduler_type(\"splash(splash_size=100)\");\n  clopts.set_scope_type(\"edge\");\n\n  // set the global logger\n  // global_logger().set_log_level(LOG_WARNING);\n  // global_logger().set_log_to_console(true);\n\n  bool success = clopts.parse(argc, argv);\n  if(!success && !clopts.is_set(\"graph\")) {    \n    return EXIT_FAILURE;\n  }\n \n  gl_types::core core;\n  core.set_engine_options(clopts);\n  core.sched_options().add_option(\"update_function\", bp_update);\n\n  \n  // Load the factor graph from file ------------------------------------------>\n  std::cout << \"Loading Factor Graph in Alchemy Format\" << std::endl;\n  factor_graph fgraph;\n  fgraph.load_alchemy(network_filename);\n  const size_t num_variables = fgraph.variables().size();\n  const size_t num_factors = fgraph.factors().size();\n  std::cout << \"Finished!\" << std::endl;\n\n  \n  // Build the BP graph from the factor graph---------------------------------->\n  std::cout << \"Building BP graph from the factor graph\" << std::endl;\n  make_bp_graph( fgraph, core.graph() ); \n  size_t num_vertices = core.graph().num_vertices();\n  assert(num_vertices == num_variables + num_factors);\n  size_t num_edges = core.graph().num_edges();\n  std::cout << \"Loaded: \" << num_vertices << \" vertices \"\n            << \"and \" << num_edges << \" edges.\" << std::endl;\n  std::cout << \"Finished!\" << std::endl;\n\n  \n  // Tell the scheduler that the bp_update function should be applied\n  // to all vertices with priority:\n  double initial_priority = 100.0;\n  core.add_task_to_all(bp_update, initial_priority);\n  \n\n  // Running the engine ------------------------------------------------------->\n  std::cout << \"Running the engine. \" << std::endl;\n  // Run the engine (this blocks until their are no tasks left).\n  // Convergence is determined when there are no update tasks left.\n  const double runtime = core.start();\n  std::cout << \"Done!\" << std::endl;\n  \n  // Print some fun facts------------------------------------------------------>\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  \n  // Save the beliefs --------------------------------------------------------->\n  std::cout << \"Saving the beliefs. \" << std::endl;\n  save_beliefs(beliefs_filename, fgraph, core.graph(), num_variables);\n  std::cout << \"Finished saving beliefs.\" << std::endl;\n\n\n  // // Save statistics about the run -------------------------------------------->\n  // std::cout << \"Saving the statistics file. \" << std::endl;\n  // std::ofstream stats(opts.stats_filename.c_str(), std::ios::app);\n  // assert(stats.good());\n  // stats << opts.scheduler << \", \"\n  //       << opts.network_filename << \", \"\n  //       << opts.scope << \", \"\n  //       << opts.ncpus << \", \"\n  //       << runtime << \", \"\n  //       << update_count << \", \"\n  //       << num_vertices << \", \"\n  //       << num_edges << \", \"\n  //       << num_variables << \", \"\n  //       << num_factors << \", \"\n  //       << opts.splash_size << std::endl;\n  // stats.close();\n  // std::cout << \"Finished saving statistics file.\" << std::endl;\n\n \n  return EXIT_SUCCESS;\n} // end of main\n\n", "meta": {"hexsha": "3984ca89478057a547dd6f027f30aa84b284f6c0", "size": 10711, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "demoapps/mln_loopybp/factor_bp.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/mln_loopybp/factor_bp.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/mln_loopybp/factor_bp.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.3676012461, "max_line_length": 83, "alphanum_fraction": 0.5956493325, "num_tokens": 2500, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799252, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.45341702632393976}}
{"text": "#ifndef STAN_MATH_PRIM_PROB_CATEGORICAL_LOGIT_GLM_LPMF_HPP\n#define STAN_MATH_PRIM_PROB_CATEGORICAL_LOGIT_GLM_LPMF_HPP\n\n#include <stan/math/prim/meta.hpp>\n#include <stan/math/prim/err.hpp>\n#include <stan/math/prim/scal/fun/size_zero.hpp>\n#include <Eigen/Core>\n#include <cmath>\n\nnamespace stan {\nnamespace math {\n\n/** \\ingroup multivar_dists\n * Returns the log PMF of the Generalized Linear Model (GLM)\n * with categorical distribution and logit (softmax) link function.\n *\n * @tparam T_y type of classes. It can be either `std::vector<int>` or `int`.\n * @tparam T_x_scalar type of a scalar in the matrix of independent variables\n * (features)\n * @tparam T_x_rows compile-time number of rows of `x`. It can be either\n * `Eigen::Dynamic` or 1.\n * @tparam T_alpha_scalar type of scalar in the intercept vector\n * @tparam T_beta_scalar type of a scalar in the matrix of weights\n * @param y a scalar or vector of classes. If it is a scalar it will be\n * broadcast - used for all instances. Values should be between 1 and number of\n * classes, including endpoints.\n * @param x design matrix or row vector. If it is a row vector it will be\n * broadcast - used for all instances.\n * @param alpha intercept vector (in log odds)\n * @param beta weight matrix\n * @return log probability or log sum of probabilities\n * @throw std::domain_error x, beta or alpha is infinite or y is not within\n * bounds\n * @throw std::invalid_argument if container sizes mismatch.\n */\ntemplate <bool propto, typename T_y, typename T_x_scalar, int T_x_rows,\n          typename T_alpha_scalar, typename T_beta_scalar>\nreturn_type_t<T_x_scalar, T_alpha_scalar, T_beta_scalar>\ncategorical_logit_glm_lpmf(\n    const T_y& y, const Eigen::Matrix<T_x_scalar, T_x_rows, Eigen::Dynamic>& x,\n    const Eigen::Matrix<T_alpha_scalar, Eigen::Dynamic, 1>& alpha,\n    const Eigen::Matrix<T_beta_scalar, Eigen::Dynamic, Eigen::Dynamic>& beta) {\n  using T_partials_return\n      = partials_return_t<T_x_scalar, T_alpha_scalar, T_beta_scalar>;\n  static const char* function = \"categorical_logit_glm_lpmf\";\n\n  using Eigen::Array;\n  using Eigen::Dynamic;\n  using Eigen::Matrix;\n  using std::exp;\n  using std::log;\n\n  const size_t N_instances = T_x_rows == 1 ? size(y) : x.rows();\n  const size_t N_attributes = x.cols();\n  const size_t N_classes = beta.cols();\n\n  check_consistent_size(function, \"Vector of dependent variables\", y,\n                        N_instances);\n  check_consistent_size(function, \"Intercept vector\", alpha, N_classes);\n  check_size_match(function, \"x.cols()\", N_attributes, \"beta.rows()\",\n                   beta.rows());\n  check_bounded(function, \"categorical outcome out of support\", y, 1,\n                N_classes);\n\n  if (size_zero(y) || N_classes == 1) {\n    return 0;\n  }\n\n  if (!include_summand<propto, T_x_scalar, T_alpha_scalar,\n                       T_beta_scalar>::value) {\n    return 0;\n  }\n\n  const auto& x_val = value_of_rec(x);\n  const auto& beta_val = value_of_rec(beta);\n  const auto& alpha_val = value_of_rec(alpha);\n\n  const auto& alpha_val_vec = as_column_vector_or_scalar(alpha_val).transpose();\n\n  Array<T_partials_return, T_x_rows, Dynamic> lin\n      = (x_val * beta_val).rowwise() + alpha_val_vec;\n  Array<T_partials_return, T_x_rows, 1> lin_max\n      = lin.rowwise().maxCoeff();  // This is used to prevent overflow when\n                                   // calculating softmax/log_sum_exp and\n                                   // similar expressions\n  Array<T_partials_return, T_x_rows, Dynamic> exp_lin\n      = exp(lin.colwise() - lin_max);\n  Array<T_partials_return, T_x_rows, 1> inv_sum_exp_lin\n      = 1 / exp_lin.rowwise().sum();\n\n  T_partials_return logp = log(inv_sum_exp_lin).sum() - lin_max.sum();\n  if (T_x_rows == 1) {\n    logp *= N_instances;\n  }\n  scalar_seq_view<T_y> y_seq(y);\n  for (int i = 0; i < N_instances; i++) {\n    if (T_x_rows == 1) {\n      logp += lin(0, y_seq[i] - 1);\n    } else {\n      logp += lin(i, y_seq[i] - 1);\n    }\n  }\n  // TODO(Tadej) maybe we can replace previous block with the following line\n  // when we have newer Eigen  T_partials_return logp =\n  // lin(Eigen::all,y-1).sum() + log(inv_sum_exp_lin).sum() - lin_max.sum();\n\n  if (!std::isfinite(logp)) {\n    check_finite(function, \"Weight vector\", beta);\n    check_finite(function, \"Intercept\", alpha);\n    check_finite(function, \"Matrix of independent variables\", x);\n  }\n\n  // Compute the derivatives.\n  operands_and_partials<Matrix<T_x_scalar, T_x_rows, Dynamic>,\n                        Matrix<T_alpha_scalar, Dynamic, 1>,\n                        Matrix<T_beta_scalar, Dynamic, Dynamic>>\n      ops_partials(x, alpha, beta);\n\n  if (!is_constant_all<T_x_scalar>::value) {\n    if (T_x_rows == 1) {\n      Array<double, 1, Dynamic> beta_y = beta_val.col(y_seq[0] - 1);\n      for (int i = 1; i < N_instances; i++) {\n        beta_y += beta_val.col(y_seq[i] - 1).array();\n      }\n      ops_partials.edge1_.partials_\n          = beta_y\n            - (exp_lin.matrix() * beta_val.transpose()).array().colwise()\n                  * inv_sum_exp_lin * N_instances;\n    } else {\n      Array<double, Dynamic, Dynamic> beta_y(N_instances, N_attributes);\n      for (int i = 0; i < N_instances; i++) {\n        beta_y.row(i) = beta_val.col(y_seq[i] - 1);\n      }\n      ops_partials.edge1_.partials_\n          = beta_y\n            - (exp_lin.matrix() * beta_val.transpose()).array().colwise()\n                  * inv_sum_exp_lin;\n      // TODO(Tadej) maybe we can replace previous block with the following line\n      // when we have newer Eigen  ops_partials.edge1_.partials_ = beta_val(y -\n      // 1, all) - (exp_lin.matrix() * beta.transpose()).colwise() *\n      // inv_sum_exp_lin;\n    }\n  }\n  if (!is_constant_all<T_alpha_scalar, T_beta_scalar>::value) {\n    Array<T_partials_return, T_x_rows, Dynamic> neg_softmax_lin\n        = exp_lin.colwise() * -inv_sum_exp_lin;\n    if (!is_constant_all<T_alpha_scalar>::value) {\n      if (T_x_rows == 1) {\n        ops_partials.edge2_.partials_\n            = neg_softmax_lin.colwise().sum() * N_instances;\n      } else {\n        ops_partials.edge2_.partials_ = neg_softmax_lin.colwise().sum();\n      }\n      for (int i = 0; i < N_instances; i++) {\n        ops_partials.edge2_.partials_[y_seq[i] - 1] += 1;\n      }\n    }\n    if (!is_constant_all<T_beta_scalar>::value) {\n      Matrix<T_partials_return, Dynamic, Dynamic> beta_derivative;\n      if (T_x_rows == 1) {\n        beta_derivative\n            = x_val.transpose() * neg_softmax_lin.matrix() * N_instances;\n      } else {\n        beta_derivative = x_val.transpose() * neg_softmax_lin.matrix();\n      }\n\n      for (int i = 0; i < N_instances; i++) {\n        if (T_x_rows == 1) {\n          beta_derivative.col(y_seq[i] - 1) += x_val;\n        } else {\n          beta_derivative.col(y_seq[i] - 1) += x_val.row(i);\n        }\n      }\n      // TODO(Tadej) maybe we can replace previous loop with the following line\n      // when we have newer Eigen  ops_partials.edge3_.partials_(Eigen::all, y -\n      // 1) += x_val.colwise.sum().transpose();\n\n      ops_partials.edge3_.partials_ = std::move(beta_derivative);\n    }\n  }\n  return ops_partials.build(logp);\n}\n\ntemplate <typename T_y, typename T_x_scalar, int T_x_rows,\n          typename T_alpha_scalar, typename T_beta_scalar>\nreturn_type_t<T_x_scalar, T_alpha_scalar, T_beta_scalar>\ncategorical_logit_glm_lpmf(\n    const T_y& y, const Eigen::Matrix<T_x_scalar, T_x_rows, Eigen::Dynamic>& x,\n    const Eigen::Matrix<T_alpha_scalar, Eigen::Dynamic, 1>& alpha,\n    const Eigen::Matrix<T_beta_scalar, Eigen::Dynamic, Eigen::Dynamic>& beta) {\n  return categorical_logit_glm_lpmf<false>(y, x, alpha, beta);\n}\n\n}  // namespace math\n}  // namespace stan\n\n#endif\n", "meta": {"hexsha": "70730c3819db46b8db36dcd29da1e1318e1dc32b", "size": 7670, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/prim/prob/categorical_logit_glm_lpmf.hpp", "max_stars_repo_name": "christophernhill/math", "max_stars_repo_head_hexsha": "dc41aba296d592c7099be15eed6ba136d0f140b3", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/categorical_logit_glm_lpmf.hpp", "max_issues_repo_name": "christophernhill/math", "max_issues_repo_head_hexsha": "dc41aba296d592c7099be15eed6ba136d0f140b3", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/categorical_logit_glm_lpmf.hpp", "max_forks_repo_name": "christophernhill/math", "max_forks_repo_head_hexsha": "dc41aba296d592c7099be15eed6ba136d0f140b3", "max_forks_repo_licenses": ["BSD-3-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.7373737374, "max_line_length": 80, "alphanum_fraction": 0.6603650587, "num_tokens": 2053, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.779992900254107, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.45341228359833396}}
{"text": "// Volumetric3D_bubble.cpp\n// created by Kuangdai on 19-Oct-2016 \n// a bubble-shaped heterogeneity\n\n#include \"Volumetric3D_bubble.h\"\n#include \"Parameters.h\"\n#include \"Geodesy.h\"\n#include <boost/algorithm/string.hpp>\n#include <sstream>\n\nvoid Volumetric3D_bubble::initialize(const std::vector<std::string> &params) {\n    // need at least 7 parameters to make a bubble\n    if (params.size() < 7) {\n        throw std::runtime_error(\"Volumetric3D_bubble::initialize || \"\n            \"Not enough parameters for a bubble-shaped heterogeneity. Need 7 at least.\");\n    }\n        \n    const std::string source = \"Volumetric3D_bubble::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_bubble::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_bubble::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(mDepth, params[4], source); mDepth *= 1e3;\n    Parameters::castValue(mLat, params[5], source);\n    Parameters::castValue(mLon, params[6], source);\n    \n    // optional\n    try {\n        int ipar = 7;\n        Parameters::castValue(mSourceCentered, params.at(ipar++), source);\n        Parameters::castValue(mFluid, params.at(ipar++), source);\n        Parameters::castValue(mHWHM, params.at(ipar++), source); mHWHM *= 1e3;\n    } catch (std::out_of_range) {\n        // nothing\n    }    \n    \n    // compute xyz of endpoints and length\n    RDCol3 rtpBubble;\n    if (mSourceCentered) {\n        RDCol3 rtpBubbleSrc;\n        rtpBubbleSrc(0) = Geodesy::getROuter() - mDepth;\n        rtpBubbleSrc(1) = mLat * degree;\n        rtpBubbleSrc(2) = mLon * degree;\n        rtpBubble = Geodesy::rotateSrc2Glob(rtpBubbleSrc, mSrcLat, mSrcLon, mSrcDep);\n    } else {\n        rtpBubble(0) = Geodesy::getROuter() - mDepth;\n        rtpBubble(1) = Geodesy::lat2Theta_d(mLat, mDepth);\n        rtpBubble(2) = Geodesy::lon2Phi(mLon);\n    }\n    mXyzBubble = Geodesy::toCartesian(rtpBubble);\n    \n    // use 20% of radius for HWHM if not specified\n    if (mHWHM < 0.) {\n        mHWHM = mRadius * .2;\n    }\n    \n    // for Absolute models\n    if (mReferenceType == Volumetric3D::MaterialRefType::Absolute) {\n        // decay is not allowed\n        mHWHM = 0.;\n        // convert to SI\n        mValueInside *= MaterialPropertyAbsSI[mMaterialProp];\n    }\n}\n\nbool Volumetric3D_bubble::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    double distance = (mXyzBubble - xyzTarget).norm();\n    \n    // treat as center if inside bubble\n    distance -= mRadius; \n    if (distance < 0.) {\n        distance = 0.;\n    }\n    \n    // outside range\n    if (distance > 4. * mHWHM) {\n        return false;\n    }\n    \n    // compute Gaussian\n    double stddev = mHWHM / sqrt(2. * log(2.));\n    double gaussian = mValueInside * exp(-distance * distance / (stddev * stddev * 2.));\n    \n    // set perturbations    \n    values[0] = gaussian;\n    return true;    \n}\n\nstd::string Volumetric3D_bubble::verbose() const {\n    std::stringstream ss;\n    ss << \"\\n======================= 3D Volumetric ======================\" << std::endl;\n    ss << \"  Model Name           =   bubble\" << 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 << \"  Bubble Radius / km   =   \" << mRadius / 1e3 << std::endl;\n    ss << \"  Depth / km           =   \" << mDepth / 1e3 << std::endl;\n    ss << \"  Lat or Theta / deg   =   \" << mLat << std::endl;\n    ss << \"  Lon or Phi / deg     =   \" << mLon << std::endl;\n    ss << \"  Source-centered      =   \" << (mSourceCentered ? \"YES\" : \"NO\") << std::endl;\n    ss << \"  HWHM / km            =   \" << mHWHM / 1e3 << std::endl;\n    ss << \"======================= 3D Volumetric ======================\\n\" << std::endl;\n    return ss.str();\n}\n\n", "meta": {"hexsha": "e3a3f1a9308d7a1d3a264d746e2f2edb2c094c37", "size": 5718, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SOLVER/src/3d_model/3d_volumetric/simple_shapes/Volumetric3D_bubble.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_bubble.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_bubble.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": 36.1898734177, "max_line_length": 112, "alphanum_fraction": 0.5835956628, "num_tokens": 1653, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4534122835983339}}
{"text": "\n#include <alglib/ap.h>\n#include <alglib/interpolation.h>\n\n#include \"spline-2d.hpp\"\n\n#define This Spline2d\n\nnamespace perceive\n{\nusing std::cout;\nusing std::endl;\n\n// ----------------------------------------------------------------------- Pimpl\n\nclass This::Pimpl\n{\n public:\n   Pimpl()\n       : is_init(false)\n       , n_control_points(0)\n       , approx_length(dNAN)\n   {}\n\n   Vector2 range_hint{0.0, 1.0};\n   bool is_init;\n   uint n_control_points;\n   double approx_length;\n   alglib::spline1dinterpolant spline_x;\n   alglib::spline1dinterpolant spline_y;\n   alglib::spline1dfitreport rep_x;\n   alglib::spline1dfitreport rep_y;\n};\n\n// ---------------------------------------------------------------- Construction\n\nThis::Spline2d()\n    : pimpl(make_unique<Pimpl>())\n{}\n\nThis::Spline2d(const Spline2d& rhs)\n    : Spline2d()\n{\n   *this = rhs;\n}\nThis::Spline2d(Spline2d&& rhs)\n    : pimpl{nullptr}\n{\n   *this = std::move(rhs);\n}\n\nThis::Spline2d(const std::vector<Vector2>& ps, double rho, int M_factor)\n    : Spline2d()\n{\n   init(ps, rho, M_factor);\n}\nThis::Spline2d(const std::vector<Vector2r>& ps, double rho, int M_factor)\n    : Spline2d()\n{\n   init(ps, rho, M_factor);\n}\nThis::Spline2d(const std::deque<Vector2>& ps, double rho, int M_factor)\n    : Spline2d()\n{\n   init(ps, rho, M_factor);\n}\nThis::Spline2d(const std::deque<Vector2r>& ps, double rho, int M_factor)\n    : Spline2d()\n{\n   init(ps, rho, M_factor);\n}\n\nThis::~Spline2d() = default;\n\nSpline2d& This::operator=(const Spline2d& rhs)\n{\n   if(this != &rhs) *pimpl = *rhs.pimpl;\n   return *this;\n}\n\nSpline2d& This::operator=(Spline2d&& rhs) = default;\n\n// ------------------------------------------------------------------- Accessors\n\nbool This::is_init() const { return pimpl->is_init; }\nuint This::n_control_points() const { return pimpl->n_control_points; }\ndouble This::approx_length() const { return pimpl->approx_length; }\n\ndouble This::rms_error_x() const { return pimpl->rep_x.rmserror; }\ndouble This::avg_error_x() const { return pimpl->rep_x.avgerror; }\ndouble This::avg_rel_error_x() const { return pimpl->rep_x.avgrelerror; }\ndouble This::max_error_x() const { return pimpl->rep_x.maxerror; }\n\ndouble This::rms_error_y() const { return pimpl->rep_y.rmserror; }\ndouble This::avg_error_y() const { return pimpl->rep_y.avgerror; }\ndouble This::avg_rel_error_y() const { return pimpl->rep_y.avgrelerror; }\ndouble This::max_error_y() const { return pimpl->rep_y.maxerror; }\n\nVector2& This::range_hint() { return pimpl->range_hint; }\nconst Vector2& This::range_hint() const { return pimpl->range_hint; }\n\n// -------------------------------------------------------------------- p-spline\n\n/*************************************************************************\nFitting by penalized cubic spline.\n\nEquidistant grid with M nodes on [min(x,xc),max(x,xc)] is  used  to  build\nbasis functions. Basis functions are cubic splines with  natural  boundary\nconditions. Problem is regularized by  adding non-linearity penalty to the\nusual least squares penalty function:\n\n    S(x) = arg min { LS + P }, where\n    LS   = SUM { w[i]^2*(y[i] - S(x[i]))^2 } - least squares penalty\n    P    = C*10^rho*integral{ S''(x)^2*dx } - non-linearity penalty\n    rho  - tunable constant given by user\n    C    - automatically determined scale parameter,\n           makes penalty invariant with respect to scaling of X, Y, W.\n\nINPUT PARAMETERS:\n    X   -   points, array[0..N-1].\n    Y   -   function values, array[0..N-1].\n    N   -   number of points (optional):\n            * N>0\n            * if given, only first N elements of X/Y are processed\n            * if not given, automatically determined from X/Y sizes\n    M   -   number of basis functions ( = number_of_nodes), M>=4.\n    Rho -   regularization  constant  passed   by   user.   It   penalizes\n            nonlinearity in the regression spline. It  is  logarithmically\n            scaled,  i.e.  actual  value  of  regularization  constant  is\n            calculated as 10^Rho. It is automatically scaled so that:\n            * Rho=2.0 corresponds to moderate amount of nonlinearity\n            * generally, it should be somewhere in the [-8.0,+8.0]\n            If you do not want to penalize nonlineary,\n            pass small Rho. Values as low as -15 should work.\n\nOUTPUT PARAMETERS:\n    Info-   same format as in LSFitLinearWC() subroutine.\n            * Info>0    task is solved\n            * Info<=0   an error occured:\n                        -4 means inconvergence of internal SVD or\n                           Cholesky decomposition; problem may be\n                           too ill-conditioned (very rare)\n    S   -   spline interpolant.\n    Rep -   Following fields are set:\n            * RMSError      rms error on the (X,Y).\n            * AvgError      average error on the (X,Y).\n            * AvgRelError   average relative error on the non-zero Y\n            * MaxError      maximum error\n                            NON-WEIGHTED ERRORS ARE CALCULATED\n\nIMPORTANT:\n    this subroitine doesn't calculate task's condition number for K<>0.\n\nNOTE 1: additional nodes are added to the spline outside  of  the  fitting\ninterval to force linearity when x<min(x,xc) or x>max(x,xc).  It  is  done\nfor consistency - we penalize non-linearity  at [min(x,xc),max(x,xc)],  so\nit is natural to force linearity outside of this interval.\n\nNOTE 2: function automatically sorts points,  so  caller may pass unsorted\narray.\n\n  -- ALGLIB PROJECT --\n     Copyright 18.08.2009 by Bochkanov Sergey\n*************************************************************************/\n\ntemplate<typename U>\nbool init_pspline(Spline2d& curve,\n                  const U& container,\n                  double rho,\n                  unsigned M_factor)\n{\n   curve.pimpl->n_control_points = 0;\n   curve.pimpl->is_init          = false;\n   curve.pimpl->approx_length    = dNAN;\n   curve.pimpl->range_hint       = Vector2(0.0, 1.0);\n\n   const uint32_t len = uint32_t(container.size());\n   if(len < 5) return false;\n\n   alglib::real_1d_array T;\n   alglib::real_1d_array X;\n   alglib::real_1d_array Y;\n   auto extra = 0u;\n   T.setlength(len + extra);\n   X.setlength(len + extra);\n   Y.setlength(len + extra);\n\n   uint counter = 0;\n   double t     = 0.0;\n   double dt    = 1.0 / double(len - 1);\n   for(const auto& p : container) {\n      T[counter] = t;\n      X[counter] = p(0);\n      Y[counter] = p(1);\n      t += dt;\n      counter++;\n   }\n\n   // Add the last point in five more times... to get boundary\n   for(auto i = 0u; i < extra; ++i) {\n      T[len + i] = 1.0;\n      X[len + i] = container.back()(0);\n      Y[len + i] = container.back()(1);\n   }\n\n   alglib::ae_int_t info_x, info_y;\n   alglib::ae_int_t M = std::max<int>(4, int(M_factor));\n\n   alglib::spline1dfitpenalized(\n       T, X, M, rho, info_x, curve.pimpl->spline_x, curve.pimpl->rep_x);\n   alglib::spline1dfitpenalized(\n       T, Y, M, rho, info_y, curve.pimpl->spline_y, curve.pimpl->rep_y);\n\n   curve.pimpl->n_control_points = unsigned(M);\n\n   if(info_x > 0 || info_y > 0) {\n      curve.pimpl->is_init       = true;\n      curve.pimpl->approx_length = 0.0;\n      double dt                  = 0.1 / double(M - 1);\n      Vector2 p                  = curve.evaluate(0.0);\n      for(double t = dt; t <= 1.0; t += dt) {\n         Vector2 q = curve.evaluate(t);\n         curve.pimpl->approx_length += (p - q).norm();\n         p = q;\n      }\n   }\n\n   return curve.pimpl->is_init;\n}\n\n// ------------------------------------------------------------------------ Init\n\nbool This::init(const std::vector<Vector2>& ps, double rho, int M_factor)\n{\n   return init_pspline(*this, ps, rho, unsigned(M_factor));\n}\n\nbool This::init(const std::deque<Vector2>& ps, double rho, int M_factor)\n{\n   return init_pspline(*this, ps, rho, unsigned(M_factor));\n}\n\nbool This::init(const std::vector<Vector2r>& ps, double rho, int M_factor)\n{\n   return init_pspline(*this, ps, rho, unsigned(M_factor));\n}\n\nbool This::init(const std::deque<Vector2r>& ps, double rho, int M_factor)\n{\n   return init_pspline(*this, ps, rho, unsigned(M_factor));\n}\n\n// -------------------------------------------------------------------- Evaluate\n\nVector2 This::evaluate(double t) const\n{\n   // assert(t >= 0.0 && t <= 1.0);\n\n   return is_init() ? Vector2(alglib::spline1dcalc(pimpl->spline_x, t),\n                              alglib::spline1dcalc(pimpl->spline_y, t))\n                    : Vector2::nan();\n}\n\nThis::GradientResult This::gradient(double t) const\n{\n   GradientResult x;\n\n   if(is_init()) {\n      double s, ds, ds2;\n      double r, dr, dr2;\n      alglib::spline1ddiff(pimpl->spline_x, t, s, ds, ds2);\n      alglib::spline1ddiff(pimpl->spline_y, t, r, dr, dr2);\n      x.x(0) = s;\n      x.x(1) = r;\n      x.g(0) = -dr;\n      x.g(1) = ds;\n      x.g.normalise();\n   } else {\n      x.x = x.g = Vector2::nan();\n   }\n\n   return x;\n}\n\n// ---------------------------------------------------------------------- Unpack\n\nstd::vector<array<double, 12>> This::unpack() const\n{\n   alglib::ae_int_t nx{0};\n   alglib::ae_int_t ny{0};\n   alglib::real_2d_array tbl_x, tbl_y;\n   spline1dunpack(pimpl->spline_x, nx, tbl_x);\n   spline1dunpack(pimpl->spline_y, ny, tbl_y);\n\n   if(nx != ny)\n      FATAL(format(\"How did this happen? nx = {} != {} = ny\", nx, ny));\n\n   auto N = tbl_x.rows();\n\n   // INFO(format(\"nx = {}, len = ({}, {})\", nx, tbl_x.rows(),tbl_x.cols()));\n\n   std::vector<array<double, 12>> out;\n   out.resize(size_t(N));\n   for(alglib::ae_int_t ind = 0; ind < N; ++ind) {\n      auto& coeff = out[size_t(ind)];\n      auto ptr    = &coeff[0];\n      for(unsigned i = 0; i < 6; ++i) *ptr++ = tbl_x(ind, i);\n      for(unsigned i = 0; i < 6; ++i) *ptr++ = tbl_y(ind, i);\n   }\n\n   return out;\n}\n\nvoid This::init(const std::vector<array<double, 12>>& coefficients) const\n{\n   using alglib::spline1dinterpolant;\n\n   auto make_interpolant = [&](bool is_x, spline1dinterpolant& interpolant) {\n      unsigned offset = (is_x) ? 0 : 6;\n\n      const unsigned dilate   = 1; // number of point per cooef set\n      const double dilate_inv = 1.0 / double(dilate);\n      const unsigned n        = unsigned(coefficients.size() * dilate + 1);\n      alglib::real_1d_array x, y, d; // (x, f(x), f'(x))\n      x.setlength(n);\n      y.setlength(n);\n      d.setlength(n);\n      unsigned pos = 0; // write position\n\n      auto write = [&](double t,\n                       double X0,\n                       double X1,\n                       double C0,\n                       double C1,\n                       double C2,\n                       double C3) {\n         x(pos) = X0 + t * (X1 - X0);\n         y(pos) = C0 + C1 * t + C2 * t * t + C3 * t * t * t;\n         d(pos) = C1 + 2.0 * C2 * t + 3.0 * C3 * t * t;\n         pos++;\n      };\n\n      for(unsigned ind = 0; ind < coefficients.size(); ++ind) {\n         const auto& CC = coefficients[ind];\n         auto X0        = CC[0 + offset];\n         auto X1        = CC[1 + offset];\n         auto C0        = CC[2 + offset];\n         auto C1        = CC[3 + offset];\n         auto C2        = CC[4 + offset];\n         auto C3        = CC[5 + offset];\n         for(unsigned i = 0; i < dilate; ++i)\n            write(dilate_inv * double(i), X0, X1, C0, C1, C2, C3);\n\n         // Write that final coefficient\n         if(ind == coefficients.size() - 1) write(1.0, X0, X1, C0, C1, C2, C3);\n      }\n\n      assert(pos == n);\n\n      alglib::spline1dbuildhermite(x, y, d, interpolant);\n   };\n\n   spline1dinterpolant spline_x, spline_y;\n   make_interpolant(true, spline_x);\n   make_interpolant(false, spline_y);\n\n   pimpl->spline_x         = spline_x;\n   pimpl->spline_y         = spline_y;\n   pimpl->is_init          = true;\n   pimpl->n_control_points = unsigned(coefficients.size());\n   pimpl->rep_x.rmserror = pimpl->rep_y.rmserror = 0.0;\n   pimpl->rep_x.avgerror = pimpl->rep_y.avgerror = 0.0;\n   pimpl->rep_x.maxerror = pimpl->rep_y.maxerror = 0.0;\n   pimpl->rep_x.avgrelerror = pimpl->rep_y.avgrelerror = 0.0;\n}\n\n// ----------------------------------------------------------------- Interpolate\n\nvoid This::interpolate(unsigned n,\n                       std::vector<Vector2>& out,\n                       double min_t,\n                       double max_t)\n{\n   assert(min_t >= 0.0 && min_t <= 1.0);\n   assert(max_t >= 0.0 && max_t <= 1.0);\n   assert(min_t <= max_t);\n\n   out.reserve(n);\n\n   if(n == 0)\n      return;\n   else if(n == 1)\n      out.push_back(evaluate(max_t));\n   else {\n      double t  = min_t;\n      double dt = (max_t - min_t) / double(n - 1);\n      for(unsigned i = 0; i < n - 1; ++i) {\n         out.push_back(evaluate(clamp(t, min_t, max_t)));\n         t += dt;\n      }\n      out.push_back(evaluate(max_t));\n   }\n\n   assert(out.size() == n);\n}\n\n// ---------------------------------------------------------------------- Smooth\n\nbool This::smooth(std::vector<Vector2>& path, double rho, int M_factor)\n{\n   if(path.size() < 5) return false;\n   Spline2d spline;\n   if(!spline.init(path, rho, M_factor)) return false;\n   std::vector<Vector2> t;\n   spline.interpolate(unsigned(path.size()), t);\n   if(!(t.size() == path.size()))\n      FATAL(format(\"Container size mismatch: expected {}, but got {}\",\n                   path.size(),\n                   t.size()));\n   auto src = t.begin();\n   auto dst = path.begin();\n   while(src != t.end()) *src++ = *dst++;\n   return true;\n}\n\n// ---------------------------------------------------------------------- Find-t\n\ndouble find_t(const Spline2d& spline,\n              double y_value,\n              double start_t,\n              bool forward,\n              double epsilon)\n{\n   if(!spline.is_init()) return double(NAN);\n\n   uint n_cps = spline.n_control_points();\n   assert(n_cps > 0);\n   assert(start_t >= 0 && start_t <= 1.0);\n   double step = (forward ? 1.0 : -1.0) * 0.5 / double(n_cps);\n\n   double last_t  = start_t;\n   Vector2 last_v = spline.evaluate(start_t);\n   double next_t  = last_t + step;\n   if(next_t <= 0.0) next_t = 0.0;\n   if(next_t >= 1.0) next_t = 1.0;\n   Vector2 next_v = spline.evaluate(next_t);\n\n   auto is_between = [&]() {\n      return (last_v.y < next_v.y)\n                 ? inclusive_between<double>(last_v.y, y_value, next_v.y)\n                 : inclusive_between<double>(next_v.y, y_value, last_v.y);\n   };\n\n   while(inclusive_between(0.0, next_t, 1.0) && !is_between()) {\n      last_v = next_v;\n      last_t = next_t;\n      next_t += step;\n      if(inclusive_between(0.0, next_t, 1.0)) next_v = spline.evaluate(next_t);\n   }\n\n   if(!is_between()) return dNAN;\n\n   // Okay now we have to do a binary search to find 't'\n   struct S\n   {\n      S()\n          : y(dNAN)\n          , t(dNAN)\n      {}\n      S(double y_, double t_)\n          : y(y_)\n          , t(t_)\n      {}\n      double y;\n      double t;\n   };\n   S upper(last_v.y, last_t);\n   S lower(next_v.y, next_t);\n   if(upper.y < lower.y) { // swap\n      S tmp(upper);\n      upper = lower;\n      lower = tmp;\n   }\n\n   double error = 1.0;\n   uint counter = 0;\n   S mid;\n   while(error > epsilon) {\n      if(counter++ > 100) FATAL(format(\"Failed to find 't' value!\"));\n\n      mid.t = 0.5 * (upper.t + lower.t);\n      mid.y = spline.evaluate(mid.t).y;\n      error = fabs(mid.y - y_value);\n\n      bool go_low = inclusive_between(lower.y, y_value, mid.y)\n                    || inclusive_between(mid.y, y_value, lower.y);\n      bool go_high = inclusive_between(upper.y, y_value, mid.y)\n                     || inclusive_between(mid.y, y_value, upper.y);\n      if((go_low && go_high) || (!go_low && !go_high))\n         LOG_ERR(format(\"t escaped\"));\n\n      if(go_low) upper = mid;\n      if(go_high) lower = mid;\n   }\n   // INFO(format(\"counter = {}\") % counter);\n   return mid.t;\n}\n\n// --------------------------------------------------------------- Intersections\n\nVector2 spline_spline_intersection(const Spline2d& a,\n                                   const Spline2d& b,\n                                   const real threshold) // pixels\n{\n   // Have to find two 't' values (ta, tb) such that\n   // a.evaluate(ta) == b.evaluate(tb)\n\n   array<double, 3> tas, tbs;\n   array<Vector2, 3> vas, vbs;\n\n   // This _could_ be more efficient: two*golden-section at worst\n   // However, 'intersections' is not the bottle-neck for this\n   // cost-function. (Refitting the splines is.)\n   auto update = [&](double ta, double tb, double range) {\n      tas[0] = clamp(ta - 0.5 * range, 0.0, 1.0);\n      tas[1] = ta;\n      tas[2] = clamp(ta + 0.5 * range, 0.0, 1.0);\n      tbs[0] = clamp(tb - 0.5 * range, 0.0, 1.0);\n      tbs[1] = tb;\n      tbs[2] = clamp(tb + 0.5 * range, 0.0, 1.0);\n      for(unsigned i = 0; i < tas.size(); ++i) {\n         vas[i] = a.evaluate(tas[i]);\n         vbs[i] = b.evaluate(tbs[i]);\n      }\n\n      // which are the closest?\n      unsigned best_i{0}, best_j{0};\n      real best_dist = std::numeric_limits<real>::max();\n      for(unsigned i = 0; i < tas.size(); ++i) {\n         for(unsigned j = 0; j < tbs.size(); ++j) {\n            auto dist = vas[i].quadrance(vbs[j]);\n            if(dist < best_dist) {\n               best_dist = dist;\n               best_i    = i;\n               best_j    = j;\n            }\n         }\n      }\n\n      auto ret = Vector3(tas[best_i], tbs[best_j], best_dist);\n\n      if(false) {\n         INFO(\"REPORT\");\n         cout << format(\"tas = [{}]\", implode(tas.begin(), tas.end(), \", \"))\n              << endl;\n         cout << format(\"tbs = [{}]\", implode(tbs.begin(), tbs.end(), \", \"))\n              << endl;\n         cout << format(\"vas = [{}]\", implode(vas.begin(), vas.end(), \", \"))\n              << endl;\n         cout << format(\"vbs = [{}]\", implode(vbs.begin(), vbs.end(), \", \"))\n              << endl;\n         cout << format(\"ret = {}\", str(ret)) << endl;\n\n         fgetc(stdin);\n      }\n\n      return ret;\n   };\n\n   double range = 1.0;\n   double ta{0.0}, tb{0.0};\n   Vector3 val(0.5, 0.5, std::numeric_limits<real>::max());\n   unsigned counter = 0;\n   while(val.z > (threshold * threshold)) {\n      if(counter++ > 100) { break; }\n      val = update(val.x, val.y, range);\n      range *= 0.5;\n   }\n\n   return 0.5 * (a.evaluate(val.x) + b.evaluate(val.y));\n}\n\n} // namespace perceive\n", "meta": {"hexsha": "4b33aad0eb601c05639d97252ae8fd05b09b71ed", "size": 18069, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "multiview/multiview_cpp/src/perceive/geometry/splines/spline-2d.cpp", "max_stars_repo_name": "prcvlabs/multiview", "max_stars_repo_head_hexsha": "1a03e14855292967ffb0c0ec7fff855c5abbc9d2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-09-03T23:12:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T21:43:32.000Z", "max_issues_repo_path": "multiview/multiview_cpp/src/perceive/geometry/splines/spline-2d.cpp", "max_issues_repo_name": "prcvlabs/multiview", "max_issues_repo_head_hexsha": "1a03e14855292967ffb0c0ec7fff855c5abbc9d2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-09-08T02:57:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-26T05:33:02.000Z", "max_forks_repo_path": "multiview/multiview_cpp/src/perceive/geometry/splines/spline-2d.cpp", "max_forks_repo_name": "prcvlabs/multiview", "max_forks_repo_head_hexsha": "1a03e14855292967ffb0c0ec7fff855c5abbc9d2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-09-26T03:14:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T06:42:52.000Z", "avg_line_length": 30.9400684932, "max_line_length": 80, "alphanum_fraction": 0.5413691959, "num_tokens": 5118, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4534122835983339}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2015 NumScale SAS\n  @copyright 2015 J.T. Lapreste\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_NEXTPOW2_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_NEXTPOW2_HPP_INCLUDED\n\n#include <boost/simd/constant/half.hpp>\n#include <boost/simd/function/scalar/abs.hpp>\n#include <boost/simd/function/scalar/abss.hpp>\n#include <boost/simd/function/scalar/ffs.hpp>\n#include <boost/simd/function/scalar/frexp.hpp>\n#include <boost/simd/function/scalar/minusone.hpp>\n#include <boost/simd/function/scalar/reversebits.hpp>\n#include <boost/dispatch/function/overload.hpp>\n#include <boost/dispatch/meta/as_integer.hpp>\n#include <boost/dispatch/meta/as_integer.hpp>\n#include <boost/config.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  BOOST_DISPATCH_OVERLOAD ( nextpow2_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_ < bd::unsigned_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() ( A0 a0) const BOOST_NOEXCEPT\n    {\n      if (!a0) return a0;\n      return sizeof(A0)*8-ffs(reversebits(a0));\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( nextpow2_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_ < bd::signed_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() ( A0 a0) const BOOST_NOEXCEPT\n    {\n      if (!a0) return a0;\n      return sizeof(A0)*8-ffs(reversebits(abss(a0)));\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( nextpow2_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_ < bd::floating_<A0> >\n                          )\n  {\n    using result_t = bd::as_integer_t<A0, signed>;\n    BOOST_FORCEINLINE result_t operator() ( A0 a0) const BOOST_NOEXCEPT\n    {\n      A0 m;\n      result_t p;\n      simd::frexp(simd::abs(a0), m, p);\n      return (m == Half<A0>())  ? minusone(p) :  p;\n    }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "5d319077078cd3282409c1fa6f44d4ab29a02b14", "size": 2379, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arch/common/scalar/function/nextpow2.hpp", "max_stars_repo_name": "yaeldarmon/boost.simd", "max_stars_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/simd/arch/common/scalar/function/nextpow2.hpp", "max_issues_repo_name": "yaeldarmon/boost.simd", "max_issues_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/arch/common/scalar/function/nextpow2.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": 31.72, "max_line_length": 100, "alphanum_fraction": 0.5472887768, "num_tokens": 565, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4534122835983339}}
{"text": "/**\n * @file tests/recurrent_network_test.cpp\n * @author Marcus Edel\n *\n * Tests the recurrent network.\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#include <mlpack/core.hpp>\n\n#include <ensmallen.hpp>\n#include <mlpack/methods/ann/layer/layer.hpp>\n#include <mlpack/methods/ann/loss_functions/mean_squared_error.hpp>\n#include <mlpack/methods/ann/rnn.hpp>\n#include <mlpack/methods/ann/brnn.hpp>\n#include <mlpack/core/data/binarize.hpp>\n#include <mlpack/core/math/random.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n#include \"serialization.hpp\"\n#include \"custom_layer.hpp\"\n\nusing namespace mlpack;\nusing namespace mlpack::ann;\nusing namespace ens;\nusing namespace mlpack::math;\n\nBOOST_AUTO_TEST_SUITE(RecurrentNetworkTest);\n\n/**\n * Construct a 2-class dataset out of noisy sines.\n *\n * @param data Input data used to store the noisy sines.\n * @param labels Labels used to store the target class of the noisy sines.\n * @param points Number of points/features in a single sequence.\n * @param sequences Number of sequences for each class.\n * @param noise The noise factor that influences the sines.\n */\nvoid GenerateNoisySines(arma::cube& data,\n                        arma::mat& labels,\n                        const size_t points,\n                        const size_t sequences,\n                        const double noise = 0.3)\n{\n  arma::colvec x =  arma::linspace<arma::colvec>(0, points - 1, points) /\n      points * 20.0;\n  arma::colvec y1 = arma::sin(x + arma::as_scalar(arma::randu(1)) * 3.0);\n  arma::colvec y2 = arma::sin(x / 2.0 + arma::as_scalar(arma::randu(1)) * 3.0);\n\n  data = arma::zeros(1 /* single dimension */, sequences * 2, points);\n  labels = arma::zeros(2 /* 2 classes */, sequences * 2);\n\n  for (size_t seq = 0; seq < sequences; seq++)\n  {\n    arma::vec sequence = arma::randu(points) * noise + y1 +\n        arma::as_scalar(arma::randu(1) - 0.5) * noise;\n    for (size_t i = 0; i < points; ++i)\n      data(0, seq, i) = sequence[i];\n\n    labels(0, seq) = 1;\n\n    sequence = arma::randu(points) * noise + y2 +\n        arma::as_scalar(arma::randu(1) - 0.5) * noise;\n    for (size_t i = 0; i < points; ++i)\n      data(0, sequences + seq, i) = sequence[i];\n\n    labels(1, sequences + seq) = 1;\n  }\n}\n\n/**\n * Train the BRNN on a larger dataset.\n */\nBOOST_AUTO_TEST_CASE(SequenceClassificationBRNNTest)\n{\n  // Using same test for RNN below.\n  size_t successes = 0;\n  const size_t rho = 10;\n\n  for (size_t trial = 0; trial < 6; ++trial)\n  {\n    // Generate 12 (2 * 6) noisy sines. A single sine contains rho\n    // points/features.\n    arma::cube input;\n    arma::mat labelsTemp;\n    GenerateNoisySines(input, labelsTemp, rho, 6);\n\n    arma::cube labels = arma::zeros<arma::cube>(1, labelsTemp.n_cols, rho);\n    for (size_t i = 0; i < labelsTemp.n_cols; ++i)\n    {\n      const int value = arma::as_scalar(arma::find(\n          arma::max(labelsTemp.col(i)) == labelsTemp.col(i), 1)) + 1;\n      labels.tube(0, i).fill(value);\n    }\n\n    Add<> add(4);\n    Linear<> lookup(1, 4);\n    SigmoidLayer<> sigmoidLayer;\n    Linear<> linear(4, 4);\n    Recurrent<>* recurrent = new Recurrent<>(\n        add, lookup, linear, sigmoidLayer, rho);\n\n    BRNN<> model(rho);\n    model.Add<IdentityLayer<> >();\n    model.Add(recurrent);\n    model.Add<Linear<> >(4, 5);\n\n    StandardSGD opt(0.1, 1, 500 * input.n_cols, -100);\n    model.Train(input, labels, opt);\n    BOOST_TEST_CHECKPOINT(\"Training over\");\n    arma::cube prediction;\n    model.Predict(input, prediction);\n    BOOST_TEST_CHECKPOINT(\"Prediction over\");\n\n    size_t error = 0;\n    for (size_t i = 0; i < prediction.n_cols; ++i)\n    {\n      const int predictionValue = arma::as_scalar(arma::find(\n          arma::max(prediction.slice(rho - 1).col(i)) ==\n          prediction.slice(rho - 1).col(i), 1) + 1);\n\n      const int targetValue = arma::as_scalar(arma::find(\n          arma::max(labelsTemp.col(i)) == labelsTemp.col(i), 1)) + 1;\n\n      if (predictionValue == targetValue)\n      {\n        error++;\n      }\n    }\n\n    double classificationError = 1 - double(error) / prediction.n_cols;\n    BOOST_TEST_CHECKPOINT(classificationError);\n    if (classificationError <= 0.2)\n    {\n      ++successes;\n      break;\n    }\n  }\n\n  BOOST_REQUIRE_GE(successes, 1);\n}\n\n/**\n * Train the vanilla network on a larger dataset.\n */\nBOOST_AUTO_TEST_CASE(SequenceClassificationTest)\n{\n  // It isn't guaranteed that the recurrent network will converge in the\n  // specified number of iterations using random weights. If this works 1 of 6\n  // times, I'm fine with that. All I want to know is that the network is able\n  // to escape from local minima and to solve the task.\n  size_t successes = 0;\n  const size_t rho = 10;\n\n  for (size_t trial = 0; trial < 6; ++trial)\n  {\n    // Generate 12 (2 * 6) noisy sines. A single sine contains rho\n    // points/features.\n    arma::cube input;\n    arma::mat labelsTemp;\n    GenerateNoisySines(input, labelsTemp, rho, 6);\n\n    arma::cube labels = arma::zeros<arma::cube>(1, labelsTemp.n_cols, rho);\n    for (size_t i = 0; i < labelsTemp.n_cols; ++i)\n    {\n      const int value = arma::as_scalar(arma::find(\n          arma::max(labelsTemp.col(i)) == labelsTemp.col(i), 1)) + 1;\n      labels.tube(0, i).fill(value);\n    }\n\n    /**\n     * Construct a network with 1 input unit, 4 hidden units and 10 output\n     * units. The hidden layer is connected to itself. The network structure\n     * looks like:\n     *\n     *  Input         Hidden        Output\n     * Layer(1)      Layer(4)      Layer(10)\n     * +-----+       +-----+       +-----+\n     * |     |       |     |       |     |\n     * |     +------>|     +------>|     |\n     * |     |    ..>|     |       |     |\n     * +-----+    .  +--+--+       +-----+\n     *            .     .\n     *            .     .\n     *            .......\n     */\n    Add<> add(4);\n    Linear<> lookup(1, 4);\n    SigmoidLayer<> sigmoidLayer;\n    Linear<> linear(4, 4);\n    Recurrent<>* recurrent = new Recurrent<>(\n        add, lookup, linear, sigmoidLayer, rho);\n\n    RNN<> model(rho);\n    model.Add<IdentityLayer<> >();\n    model.Add(recurrent);\n    model.Add<Linear<> >(4, 10);\n    model.Add<LogSoftMax<> >();\n\n    StandardSGD opt(0.1, 1, 500 * input.n_cols, -100);\n    model.Train(input, labels, opt);\n\n    arma::cube prediction;\n    model.Predict(input, prediction);\n\n    size_t error = 0;\n    for (size_t i = 0; i < prediction.n_cols; ++i)\n    {\n      const int predictionValue = arma::as_scalar(arma::find(\n          arma::max(prediction.slice(rho - 1).col(i)) ==\n          prediction.slice(rho - 1).col(i), 1) + 1);\n\n      const int targetValue = arma::as_scalar(arma::find(\n          arma::max(labelsTemp.col(i)) == labelsTemp.col(i), 1)) + 1;\n\n      if (predictionValue == targetValue)\n      {\n        error++;\n      }\n    }\n\n    double classificationError = 1 - double(error) / prediction.n_cols;\n    if (classificationError <= 0.2)\n    {\n      ++successes;\n      break;\n    }\n  }\n\n  BOOST_REQUIRE_GE(successes, 1);\n}\n\n/**\n * Generate a random Reber grammar.\n *\n * For more information, see the following thesis.\n *\n * @code\n * @misc{Gers2001,\n *   author = {Felix Gers},\n *   title = {Long Short-Term Memory in Recurrent Neural Networks},\n *   year = {2001}\n * }\n * @endcode\n *\n * @param transitions Reber grammar transition matrix.\n * @param reber The generated Reber grammar string.\n */\nvoid GenerateReber(const arma::Mat<char>& transitions, std::string& reber)\n{\n  size_t idx = 0;\n  reber = \"B\";\n\n  do\n  {\n    const int grammerIdx = rand() % 2;\n    reber += arma::as_scalar(transitions.submat(idx, grammerIdx, idx,\n        grammerIdx));\n\n    idx = arma::as_scalar(transitions.submat(idx, grammerIdx + 2, idx,\n        grammerIdx + 2)) - '0';\n  } while (idx != 0);\n}\n\n/**\n * Generate a random recursive Reber grammar.\n *\n * @param transitions Recursive Reber grammar transition matrix.\n * @param averageRecursion Average recursive depth of the reber grammar.\n * @param maxRecursion Maximum recursive depth of reber grammar.\n * @param reber The generated embedded Reber grammar string.\n * @param addEnd Add ending 'E' to the generated grammar.\n */\nvoid GenerateRecursiveReber(const arma::Mat<char>& transitions,\n                            size_t averageRecursion,\n                            size_t maxRecursion,\n                            std::string& reber,\n                            bool addEnd = true)\n{\n  char c = (rand() % averageRecursion) == 1 ? 'P' : 'T';\n\n  if (maxRecursion == 1 || c == 'T')\n  {\n    c = 'T';\n    GenerateReber(transitions, reber);\n  }\n  else\n  {\n    GenerateRecursiveReber(transitions, averageRecursion, --maxRecursion,\n        reber, false);\n  }\n\n  reber = c + reber + c;\n\n  if (addEnd)\n  {\n    reber = \"B\" + reber + \"E\";\n  }\n}\n\n/**\n * Convert a unit vector to a Reber symbol.\n *\n * @param translation The unit vector to be converted.\n * @param symbol The converted unit vector stored as Reber symbol.\n */\ntemplate<typename MatType>\nvoid ReberReverseTranslation(const MatType& translation, char& symbol)\n{\n  arma::Col<char> symbols;\n  symbols << 'B' << 'T' << 'S' << 'X' << 'P' << 'V' << 'E' << arma::endr;\n  const int idx = arma::as_scalar(arma::find(translation == 1, 1, \"first\"));\n\n  symbol = symbols(idx);\n}\n\n/**\n * Convert a Reber symbol to a unit vector.\n *\n * @param symbol Reber symbol to be converted.\n * @param translation The converted symbol stored as unit vector.\n */\nvoid ReberTranslation(const char symbol, arma::colvec& translation)\n{\n  arma::Col<char> symbols;\n  symbols << 'B' << 'T' << 'S' << 'X' << 'P' << 'V' << 'E' << arma::endr;\n  const int idx = arma::as_scalar(arma::find(symbols == symbol, 1, \"first\"));\n\n  translation = arma::zeros<arma::colvec>(7);\n  translation(idx) = 1;\n}\n\n/**\n * Given a Reber string, return a Reber string with all reachable next symbols.\n *\n * @param transitions The Reber transistion matrix.\n * @param reber The Reber string used to generate all reachable next symbols.\n * @param nextReber All reachable next symbols.\n */\nvoid GenerateNextReber(const arma::Mat<char>& transitions,\n                       const std::string& reber, std::string& nextReber)\n{\n  size_t idx = 0;\n\n  for (size_t grammer = 1; grammer < reber.length(); grammer++)\n  {\n    const int grammerIdx = arma::as_scalar(arma::find(\n        transitions.row(idx) == reber[grammer], 1, \"first\"));\n\n    idx = arma::as_scalar(transitions.submat(idx, grammerIdx + 2, idx,\n        grammerIdx + 2)) - '0';\n  }\n\n  nextReber = arma::as_scalar(transitions.submat(idx, 0, idx, 0));\n  nextReber += arma::as_scalar(transitions.submat(idx, 1, idx, 1));\n}\n\n/**\n * Given a recursive Reber string, return a Reber string with all\n * reachable next symbols.\n *\n * @param transitions The Reber transistion matrix.\n * @param reber The Reber string used to generate all reachable next symbols.\n * @param nextReber All reachable next symbols.\n */\nvoid GenerateNextRecursiveReber(const arma::Mat<char>& transitions,\n                                const std::string& reber,\n                                std::string& nextReber)\n{\n  size_t state = 0;\n  size_t numPs = 0;\n\n  for (size_t cIndex = 0; cIndex < reber.length(); cIndex++)\n  {\n    char c = reber[cIndex];\n\n    if (c == 'B' && state == 0)\n    {\n      state = 1;\n    }\n    else if (c == 'P' && state == 1)\n    {\n      numPs++;\n      state = 1;\n    }\n    else if (c == 'T' && state == 1)\n    {\n      state = 2;\n    }\n    else if (c == 'B' && state == 2)\n    {\n      size_t pos = reber.find('E');\n      if (pos != std::string::npos)\n      {\n        cIndex = pos;\n        state = 4;\n      }\n      else\n      {\n        GenerateNextReber(transitions, reber.substr(cIndex), nextReber);\n        state = 3;\n      }\n    }\n    else if (c == 'T' && state == 4)\n    {\n      state = 5;\n    }\n    else if (c == 'P' && state == 5)\n    {\n      numPs--;\n      state = 5;\n    }\n  }\n\n  if (state == 0 || state == 2)\n  {\n    nextReber = \"B\";\n  }\n  else if (state == 1)\n  {\n    nextReber = \"PT\";\n  }\n  else if (state == 4)\n  {\n    nextReber = \"T\";\n  }\n  else if (state == 5)\n  {\n    if (numPs == 0)\n    {\n      nextReber = \"E\";\n    }\n    else\n    {\n      nextReber = \"P\";\n    }\n  }\n}\n\n/**\n * @brief Creates the reber grammar data for tests.\n *\n * @param trainInput The train data\n * @param trainLabels The train labels\n * @param testInput The test input\n * @param recursive whether recursive Reber\n * @param trainReberGrammarCount The number of training set\n * @param testReberGrammarCount The number of test set\n * @param averageRecursion Average recursion\n * @param maxRecursion Max recursion\n * @return arma::Mat<char> The Reber state translation to be used.\n */\narma::Mat<char> GenerateReberGrammarData(\n                              arma::field<arma::mat>& trainInput,\n                              arma::field<arma::mat>& trainLabels,\n                              arma::field<arma::mat>& testInput,\n                              bool recursive = false,\n                              const size_t trainReberGrammarCount = 700,\n                              const size_t testReberGrammarCount = 250,\n                              const size_t averageRecursion = 3,\n                              const size_t maxRecursion = 5)\n{\n  // Reber state transition matrix. (The last two columns are the indices to the\n  // next path).\n  arma::Mat<char> transitions;\n  transitions << 'T' << 'P' << '1' << '2' << arma::endr\n              << 'X' << 'S' << '3' << '1' << arma::endr\n              << 'V' << 'T' << '4' << '2' << arma::endr\n              << 'X' << 'S' << '2' << '5' << arma::endr\n              << 'P' << 'V' << '3' << '5' << arma::endr\n              << 'E' << 'E' << '0' << '0' << arma::endr;\n\n\n  std::string trainReber, testReber;\n\n  arma::colvec translation;\n\n  // Generate the training data.\n  for (size_t i = 0; i < trainReberGrammarCount; ++i)\n  {\n    if (recursive)\n      GenerateRecursiveReber(transitions, 3, 5, trainReber);\n    else\n      GenerateReber(transitions, trainReber);\n\n    for (size_t j = 0; j < trainReber.length() - 1; ++j)\n    {\n      ReberTranslation(trainReber[j], translation);\n      trainInput(0, i) = arma::join_cols(trainInput(0, i), translation);\n\n      ReberTranslation(trainReber[j + 1], translation);\n      trainLabels(0, i) = arma::join_cols(trainLabels(0, i), translation);\n    }\n  }\n\n  // Generate the test data.\n  for (size_t i = 0; i < testReberGrammarCount; ++i)\n  {\n    if (recursive)\n      GenerateRecursiveReber(transitions, averageRecursion, maxRecursion,\n          testReber);\n    else\n      GenerateReber(transitions, testReber);\n\n    for (size_t j = 0; j < testReber.length() - 1; ++j)\n    {\n      ReberTranslation(testReber[j], translation);\n      testInput(0, i) = arma::join_cols(testInput(0, i), translation);\n    }\n  }\n\n  return transitions;\n}\n\n/**\n * Train the specified network and the construct a Reber grammar dataset.\n */\ntemplate<typename ModelType>\nvoid ReberGrammarTestNetwork(ModelType& model,\n                             const bool recursive = false,\n                             const size_t averageRecursion = 3,\n                             const size_t maxRecursion = 5,\n                             const size_t iterations = 10,\n                             const size_t trials = 5)\n{\n  const size_t trainReberGrammarCount = 700;\n  const size_t testReberGrammarCount = 250;\n\n  arma::field<arma::mat> trainInput(1, trainReberGrammarCount);\n  arma::field<arma::mat> trainLabels(1, trainReberGrammarCount);\n  arma::field<arma::mat> testInput(1, testReberGrammarCount);\n\n  arma::Mat<char> transitions =\n                  GenerateReberGrammarData(trainInput,\n                                           trainLabels,\n                                           testInput,\n                                           recursive,\n                                           trainReberGrammarCount,\n                                           testReberGrammarCount,\n                                           averageRecursion,\n                                           maxRecursion);\n\n  /*\n   * Construct a network with 7 input units, layerSize hidden units and 7 output\n   * units. The hidden layer is connected to itself. The network structure looks\n   * like:\n   *\n   *  Input         Hidden        Output\n   * Layer(7)  Layer(layerSize)   Layer(7)\n   * +-----+       +-----+       +-----+\n   * |     |       |     |       |     |\n   * |     +------>|     +------>|     |\n   * |     |    ..>|     |       |     |\n   * +-----+    .  +--+--+       +-- ---+\n   *            .     .\n   *            .     .\n   *            .......\n   */\n  // It isn't guaranteed that the recurrent network will converge in the\n  // specified number of iterations using random weights. If this works 1 of 5\n  // times, I'm fine with that. All I want to know is that the network is able\n  // to escape from local minima and to solve the task.\n  size_t successes = 0;\n  size_t offset = 0;\n  const size_t inputSize = 7;\n  for (size_t trial = 0; trial < trials; ++trial)\n  {\n    // Reset model before using for next trial.\n    model.Reset();\n    MomentumSGD opt(0.06, 50, 2, -50000);\n\n    arma::cube inputTemp, labelsTemp;\n    for (size_t iteration = 0; iteration < (iterations + offset); iteration++)\n    {\n      for (size_t j = 0; j < trainReberGrammarCount; ++j)\n      {\n        // Each sequence may be a different length, so we need to extract them\n        // manually.  We will reshape them into a cube with each slice equal to\n        // a time step.\n        inputTemp = arma::cube(trainInput.at(0, j).memptr(), inputSize, 1,\n            trainInput.at(0, j).n_elem / inputSize, false, true);\n        labelsTemp = arma::cube(trainLabels.at(0, j).memptr(), inputSize, 1,\n            trainInput.at(0, j).n_elem / inputSize, false, true);\n\n        model.Rho() = inputTemp.n_elem / inputSize;\n        model.Train(inputTemp, labelsTemp, opt);\n        opt.ResetPolicy() = false;\n      }\n    }\n\n    double error = 0;\n\n    // Ask the network to predict the next Reber grammar in the given sequence.\n    for (size_t i = 0; i < testReberGrammarCount; ++i)\n    {\n      arma::cube prediction;\n      arma::cube input(testInput.at(0, i).memptr(), inputSize, 1,\n          testInput.at(0, i).n_elem / inputSize, false, true);\n\n      model.Rho() = input.n_elem / inputSize;\n      model.Predict(input, prediction);\n\n      const size_t reberGrammerSize = 7;\n      std::string inputReber = \"\";\n\n      size_t reberError = 0;\n\n      for (size_t j = 0; j < (prediction.n_elem / reberGrammerSize); ++j)\n      {\n        char predictedSymbol, inputSymbol;\n        std::string reberChoices;\n\n        arma::umat output = (prediction.slice(j) == (arma::ones(\n            reberGrammerSize, 1) *\n            arma::as_scalar(arma::max(prediction.slice(j)))));\n\n        ReberReverseTranslation(output, predictedSymbol);\n        ReberReverseTranslation(input.slice(j), inputSymbol);\n        inputReber += inputSymbol;\n\n        if (recursive)\n          GenerateNextRecursiveReber(transitions, inputReber, reberChoices);\n        else\n          GenerateNextReber(transitions, inputReber, reberChoices);\n\n        if (reberChoices.find(predictedSymbol) != std::string::npos)\n          reberError++;\n      }\n\n      if (reberError != (prediction.n_elem / reberGrammerSize))\n        error += 1;\n    }\n\n    error /= testReberGrammarCount;\n    if (error <= 0.3)\n    {\n      ++successes;\n      break;\n    }\n\n    offset += 3;\n  }\n\n  BOOST_REQUIRE_GE(successes, 1);\n}\n\n/**\n * Train the specified networks on an embedded Reber grammar dataset.\n */\nBOOST_AUTO_TEST_CASE(LSTMReberGrammarTest)\n{\n  RNN<MeanSquaredError<> > model(5);\n  model.Add<Linear<> >(7, 10);\n  model.Add<LSTM<> >(10, 10);\n  model.Add<Linear<> >(10, 7);\n  model.Add<SigmoidLayer<> >();\n  ReberGrammarTestNetwork(model, false);\n}\n\n/**\n * Train the specified networks on an embedded Reber grammar dataset.\n */\nBOOST_AUTO_TEST_CASE(FastLSTMReberGrammarTest)\n{\n  RNN<MeanSquaredError<> > model(5);\n  model.Add<Linear<> >(7, 8);\n  model.Add<FastLSTM<> >(8, 8);\n  model.Add<Linear<> >(8, 7);\n  model.Add<SigmoidLayer<> >();\n  ReberGrammarTestNetwork(model, false);\n}\n\n/**\n * Train the specified networks on an embedded Reber grammar dataset.\n */\nBOOST_AUTO_TEST_CASE(GRURecursiveReberGrammarTest)\n{\n  RNN<MeanSquaredError<> > model(5);\n  model.Add<Linear<> >(7, 16);\n  model.Add<GRU<> >(16, 16);\n  model.Add<Linear<> >(16, 7);\n  model.Add<SigmoidLayer<> >();\n  ReberGrammarTestNetwork(model, true, 3, 5, 10, 7);\n}\n\n/**\n * Train BLSTM on an embedded Reber grammar dataset.\n */\nBOOST_AUTO_TEST_CASE(BRNNReberGrammarTest)\n{\n  BRNN<MeanSquaredError<>, AddMerge<>, SigmoidLayer<> > model(5);\n  model.Add<Linear<> >(7, 10);\n  model.Add<LSTM<> >(10, 10);\n  model.Add<Linear<> >(10, 7);\n  ReberGrammarTestNetwork(model, false, 3, 5, 1);\n}\n\n/*\n * This sample is a simplified version of Derek D. Monner's Distracted Sequence\n * Recall task, which involves 10 symbols:\n *\n * Targets: must be recognized and remembered by the network.\n * Distractors: never need to be remembered.\n * Prompts: direct the network to give an answer.\n *\n * A single trial consists of a temporal sequence of 10 input symbols. The first\n * 8 consist of 2 randomly chosen target symbols and 6 randomly chosen\n * distractor symbols in an random order. The remaining two symbols are two\n * prompts, which direct the network to produce the first and second target in\n * the sequence, in order.\n *\n * For more information, see the following paper.\n *\n * @code\n * @misc{Monner2012,\n *   author = {Monner, Derek and Reggia, James A},\n *   title = {A generalized LSTM-like training algorithm for second-order\n *   recurrent neural networks},\n *   year = {2012}\n * }\n * @endcode\n *\n * @param input The generated input sequence.\n * @param input The generated output sequence.\n */\nvoid GenerateDistractedSequence(arma::mat& input, arma::mat& output)\n{\n  input = arma::zeros<arma::mat>(10, 10);\n  output = arma::zeros<arma::mat>(3, 10);\n\n  arma::uvec index = arma::shuffle(arma::linspace<arma::uvec>(0, 7, 8));\n\n  // Set the target in the input sequence and the corresponding targets in the\n  // output sequence by following the correct order.\n  for (size_t i = 0; i < 2; ++i)\n  {\n    size_t idx = rand() % 2;\n    input(idx, index(i)) = 1;\n    output(idx, index(i) > index(i == 0) ? 9 : 8) = 1;\n  }\n\n  for (size_t i = 2; i < 8; ++i)\n    input(2 + rand() % 6, index(i)) = 1;\n\n  // Set the prompts which direct the network to give an answer.\n  input(8, 8) = 1;\n  input(9, 9) = 1;\n\n  input.reshape(input.n_elem, 1);\n  output.reshape(output.n_elem, 1);\n}\n\n/**\n * Train the specified network and the construct distracted sequence recall\n * dataset.\n */\ntemplate<typename RecurrentLayerType>\nvoid DistractedSequenceRecallTestNetwork(\n    const size_t cellSize, const size_t hiddenSize)\n{\n  const size_t trainDistractedSequenceCount = 600;\n  const size_t testDistractedSequenceCount = 300;\n\n  arma::field<arma::mat> trainInput(1, trainDistractedSequenceCount);\n  arma::field<arma::mat> trainLabels(1, trainDistractedSequenceCount);\n  arma::field<arma::mat> testInput(1, testDistractedSequenceCount);\n  arma::field<arma::mat> testLabels(1, testDistractedSequenceCount);\n\n  // Generate the training data.\n  for (size_t i = 0; i < trainDistractedSequenceCount; ++i)\n    GenerateDistractedSequence(trainInput(0, i), trainLabels(0, i));\n\n  // Generate the test data.\n  for (size_t i = 0; i < testDistractedSequenceCount; ++i)\n    GenerateDistractedSequence(testInput(0, i), testLabels(0, i));\n\n  /*\n   * Construct a network with 10 input units, layerSize hidden units and 3\n   * output units. The hidden layer is connected to itself. The network\n   * structure looks like:\n   *\n   *  Input        Recurrent      Hidden       Output\n   * Layer(10)  Layer(cellSize)   Layer(3)     Layer(3)\n   * +-----+       +-----+       +-----+       +-----+\n   * |     |       |     |       |     |       |     |\n   * |     +------>|     +------>|     |------>|     |\n   * |     |    ..>|     |       |     |       |     |\n   * +-----+    .  +--+--+       +-----+       +-----+\n   *            .     .\n   *            .     .\n   *            .......\n   */\n  const size_t outputSize = 3;\n  const size_t inputSize = 10;\n  const size_t rho = trainInput.at(0, 0).n_elem / inputSize;\n\n  // It isn't guaranteed that the recurrent network will converge in the\n  // specified number of iterations using random weights. If this works 1 of 5\n  // times, I'm fine with that. All I want to know is that the network is able\n  // to escape from local minima and to solve the task.\n  size_t successes = 0;\n  size_t offset = 0;\n  for (size_t trial = 0; trial < 5; ++trial)\n  {\n    RNN<MeanSquaredError<> > model(rho);\n    model.Add<IdentityLayer<> >();\n    model.Add<Linear<> >(inputSize, cellSize);\n    model.Add<RecurrentLayerType>(cellSize, hiddenSize);\n    model.Add<Linear<> >(hiddenSize, outputSize);\n    model.Add<SigmoidLayer<> >();\n\n    StandardSGD opt(0.1, 50, 2, -50000);\n\n    // We increase the number of iterations (training) if the first run didn't\n    // pass.\n    arma::cube inputTemp, labelsTemp;\n    for (size_t iteration = 0; iteration < (9 + offset); iteration++)\n    {\n      for (size_t j = 0; j < trainDistractedSequenceCount; ++j)\n      {\n        inputTemp = arma::cube(trainInput.at(0, j).memptr(), inputSize, 1,\n            trainInput.at(0, j).n_elem / inputSize, false, true);\n        labelsTemp = arma::cube(trainLabels.at(0, j).memptr(), outputSize, 1,\n            trainLabels.at(0, j).n_elem / outputSize, false, true);\n\n        model.Train(inputTemp, labelsTemp, opt);\n      }\n    }\n\n    double error = 0;\n\n    // Ask the network to predict the targets in the given sequence at the\n    // prompts.\n    for (size_t i = 0; i < testDistractedSequenceCount; ++i)\n    {\n      arma::cube output;\n      arma::cube input(testInput.at(0, i).memptr(), inputSize, 1,\n          testInput.at(0, i).n_elem / inputSize, false, true);\n\n      model.Predict(input, output);\n      for (size_t j = 0; j < output.n_slices; ++j)\n      {\n        arma::mat outputSlice = output.slice(j);\n        data::Binarize(outputSlice, outputSlice, 0.5);\n        output.slice(j) = outputSlice;\n      }\n\n      arma::cube label(testLabels.at(0, i).memptr(), outputSize, 1,\n          testLabels.at(0, i).n_elem / outputSize, false, true);\n      if (arma::accu(arma::abs(label - output)) != 0)\n        error += 1;\n    }\n\n    error /= testDistractedSequenceCount;\n    // Can we reproduce the results from the paper. They provide an 95% accuracy\n    // on a test set of 1000 randomly selected sequences.\n    // Ensure that this is within tolerance, which is at least as good as the\n    // paper's results (plus a little bit for noise).\n    if (error <= 0.3)\n    {\n      ++successes;\n      break;\n    }\n\n    offset += 2;\n  }\n\n  BOOST_REQUIRE_GE(successes, 1);\n}\n\n/**\n * Train the specified networks on the Derek D. Monner's distracted sequence\n * recall task.\n */\nBOOST_AUTO_TEST_CASE(LSTMDistractedSequenceRecallTest)\n{\n  DistractedSequenceRecallTestNetwork<LSTM<> >(4, 8);\n}\n\n/**\n * Train the specified networks on the Derek D. Monner's distracted sequence\n * recall task.\n */\nBOOST_AUTO_TEST_CASE(FastLSTMDistractedSequenceRecallTest)\n{\n  DistractedSequenceRecallTestNetwork<FastLSTM<> >(4, 8);\n}\n\n/**\n * Train the specified networks on the Derek D. Monner's distracted sequence\n * recall task.\n */\nBOOST_AUTO_TEST_CASE(GRUDistractedSequenceRecallTest)\n{\n  DistractedSequenceRecallTestNetwork<GRU<> >(4, 8);\n}\n\n/**\n * Create a simple recurrent neural network for the noisy sines task, and\n * require that it produces the exact same network for a few batch sizes.\n */\ntemplate<typename RecurrentLayerType>\nvoid BatchSizeTest()\n{\n  const size_t rho = 10;\n\n  // Generate 12 (2 * 6) noisy sines. A single sine contains rho\n  // points/features.\n  arma::cube input;\n  arma::mat labelsTemp;\n  GenerateNoisySines(input, labelsTemp, rho, 6);\n\n  arma::cube labels = arma::zeros<arma::cube>(1, labelsTemp.n_cols, rho);\n  for (size_t i = 0; i < labelsTemp.n_cols; ++i)\n  {\n    const int value = arma::as_scalar(arma::find(\n        arma::max(labelsTemp.col(i)) == labelsTemp.col(i), 1)) + 1;\n    labels.tube(0, i).fill(value);\n  }\n\n  RNN<> model(rho);\n  model.Add<Linear<>>(1, 10);\n  model.Add<SigmoidLayer<>>();\n  model.Add<RecurrentLayerType>(10, 10);\n  model.Add<SigmoidLayer<>>();\n  model.Add<Linear<>>(10, 10);\n  model.Add<SigmoidLayer<>>();\n\n  model.Reset();\n  arma::mat initParams = model.Parameters();\n\n  StandardSGD opt(1e-5, 1, 5, -100, false);\n  model.Train(input, labels, opt);\n\n  // This is trained with one point.\n  arma::mat outputParams = model.Parameters();\n\n  model.Reset();\n  model.Parameters() = initParams;\n  opt.BatchSize() = 2;\n  model.Train(input, labels, opt);\n\n  CheckMatrices(outputParams, model.Parameters(), 1);\n\n  model.Parameters() = initParams;\n  opt.BatchSize() = 5;\n  model.Train(input, labels, opt);\n\n  CheckMatrices(outputParams, model.Parameters(), 1);\n}\n\n/**\n * Ensure LSTMs work with larger batch sizes.\n */\nBOOST_AUTO_TEST_CASE(LSTMBatchSizeTest)\n{\n  BatchSizeTest<LSTM<>>();\n}\n\n/**\n * Ensure fast LSTMs work with larger batch sizes.\n */\nBOOST_AUTO_TEST_CASE(FastLSTMBatchSizeTest)\n{\n  BatchSizeTest<FastLSTM<>>();\n}\n\n/**\n * Ensure GRUs work with larger batch sizes.\n */\nBOOST_AUTO_TEST_CASE(GRUBatchSizeTest)\n{\n  BatchSizeTest<GRU<>>();\n}\n\n/**\n * Make sure the RNN can be properly serialized.\n */\nBOOST_AUTO_TEST_CASE(SerializationTest)\n{\n  const size_t rho = 10;\n\n  // Generate 12 (2 * 6) noisy sines. A single sine contains rho\n  // points/features.\n  arma::cube input;\n  arma::mat labelsTemp;\n  GenerateNoisySines(input, labelsTemp, rho, 6);\n\n  arma::cube labels = arma::zeros<arma::cube>(1, labelsTemp.n_cols, rho);\n  for (size_t i = 0; i < labelsTemp.n_cols; ++i)\n  {\n    const int value = arma::as_scalar(arma::find(\n        arma::max(labelsTemp.col(i)) == labelsTemp.col(i), 1)) + 1;\n    labels.tube(0, i).fill(value);\n  }\n\n  /**\n   * Construct a network with 1 input unit, 4 hidden units and 10 output\n   * units. The hidden layer is connected to itself. The network structure\n   * looks like:\n   *\n   *  Input         Hidden        Output\n   * Layer(1)      Layer(4)      Layer(10)\n   * +-----+       +-----+       +-----+\n   * |     |       |     |       |     |\n   * |     +------>|     +------>|     |\n   * |     |    ..>|     |       |     |\n   * +-----+    .  +--+--+       +-----+\n   *            .     .\n   *            .     .\n   *            .......\n   */\n  Add<> add(4);\n  Linear<> lookup(1, 4);\n  SigmoidLayer<> sigmoidLayer;\n  Linear<> linear(4, 4);\n  Recurrent<>* recurrent = new Recurrent<>(add, lookup, linear,\n      sigmoidLayer, rho);\n\n  RNN<> model(rho);\n  model.Add<IdentityLayer<> >();\n  model.Add(recurrent);\n  model.Add<Linear<> >(4, 10);\n  model.Add<LogSoftMax<> >();\n\n  StandardSGD opt(0.1, 1, input.n_cols /* 1 epoch */, -100);\n  model.Train(input, labels, opt);\n\n  // Serialize the network.\n  RNN<> xmlModel(1), textModel(3), binaryModel(5);\n  SerializeObjectAll(model, xmlModel, textModel, binaryModel);\n\n  // Take predictions, check the output.\n  arma::cube prediction, xmlPrediction, textPrediction, binaryPrediction;\n  model.Predict(input, prediction);\n  xmlModel.Predict(input, xmlPrediction);\n  textModel.Predict(input, textPrediction);\n  binaryModel.Predict(input, binaryPrediction);\n\n  CheckMatrices(prediction, xmlPrediction, textPrediction, binaryPrediction);\n}\n\n/**\n * Test RNN with a custom layer.\n */\nvoid ReberGrammarTestCustomNetwork(const size_t hiddenSize = 4,\n                                   const bool recursive = false,\n                                   const size_t iterations = 10)\n{\n  const size_t trainReberGrammarCount = 700;\n  const size_t testReberGrammarCount = 250;\n\n  arma::field<arma::mat> trainInput(1, trainReberGrammarCount);\n  arma::field<arma::mat> trainLabels(1, trainReberGrammarCount);\n  arma::field<arma::mat> testInput(1, testReberGrammarCount);\n\n  arma::Mat<char> transitions =\n                  GenerateReberGrammarData(trainInput,\n                                           trainLabels,\n                                           testInput,\n                                           recursive,\n                                           trainReberGrammarCount,\n                                           testReberGrammarCount);\n\n  /*\n   * Construct a network with 7 input units, layerSize hidden units and 7 output\n   * units. The hidden layer is connected to itself. The network structure looks\n   * like:\n   *\n   *  Input         Hidden        Output\n   * Layer(7)  Layer(layerSize)   Layer(7)\n   * +-----+       +-----+       +-----+\n   * |     |       |     |       |     |\n   * |     +------>|     +------>|     |\n   * |     |    ..>|     |       |     |\n   * +-----+    .  +--+--+       +-- ---+\n   *            .     .\n   *            .     .\n   *            .......\n   */\n  // It isn't guaranteed that the recurrent network will converge in the\n  // specified number of iterations using random weights. If this works 1 of 10\n  // times, I'm fine with that. All I want to know is that the network is able\n  // to escape from local minima and to solve the task.\n  size_t successes = 0;\n  size_t offset = 0;\n  for (size_t trial = 0; trial < 10; ++trial)\n  {\n    const size_t outputSize = 7;\n    const size_t inputSize = 7;\n\n    RNN<MeanSquaredError<>, RandomInitialization, CustomLayer<> > model(5);\n    model.Add<Linear<> >(inputSize, hiddenSize);\n    model.Add<GRU<> >(hiddenSize, hiddenSize);\n    model.Add<Linear<> >(hiddenSize, outputSize);\n    model.Add<CustomLayer<> >();\n    MomentumSGD opt(0.06, 50, 2, -50000);\n\n    arma::cube inputTemp, labelsTemp;\n    for (size_t iteration = 0; iteration < (iterations + offset); iteration++)\n    {\n      for (size_t j = 0; j < trainReberGrammarCount; ++j)\n      {\n        // Each sequence may be a different length, so we need to extract them\n        // manually.  We will reshape them into a cube with each slice equal to\n        // a time step.\n        inputTemp = arma::cube(trainInput.at(0, j).memptr(), inputSize, 1,\n            trainInput.at(0, j).n_elem / inputSize, false, true);\n        labelsTemp = arma::cube(trainLabels.at(0, j).memptr(), inputSize, 1,\n            trainInput.at(0, j).n_elem / inputSize, false, true);\n\n        model.Rho() = inputTemp.n_elem / inputSize;\n        model.Train(inputTemp, labelsTemp, opt);\n        opt.ResetPolicy() = false;\n      }\n    }\n\n    double error = 0;\n\n    // Ask the network to predict the next Reber grammar in the given sequence.\n    for (size_t i = 0; i < testReberGrammarCount; ++i)\n    {\n      arma::cube prediction;\n      arma::cube input(testInput.at(0, i).memptr(), inputSize, 1,\n          testInput.at(0, i).n_elem / inputSize, false, true);\n\n      model.Rho() = input.n_elem / inputSize;\n      model.Predict(input, prediction);\n\n      const size_t reberGrammerSize = 7;\n      std::string inputReber = \"\";\n\n      size_t reberError = 0;\n\n      for (size_t j = 0; j < (prediction.n_elem / reberGrammerSize); ++j)\n      {\n        char predictedSymbol, inputSymbol;\n        std::string reberChoices;\n\n        arma::umat output = (prediction.slice(j) == (arma::ones(\n            reberGrammerSize, 1) *\n            arma::as_scalar(arma::max(prediction.slice(j)))));\n\n        ReberReverseTranslation(output, predictedSymbol);\n        ReberReverseTranslation(input.slice(j), inputSymbol);\n        inputReber += inputSymbol;\n\n        if (recursive)\n          GenerateNextRecursiveReber(transitions, inputReber, reberChoices);\n        else\n          GenerateNextReber(transitions, inputReber, reberChoices);\n\n        if (reberChoices.find(predictedSymbol) != std::string::npos)\n          reberError++;\n      }\n\n      if (reberError != (prediction.n_elem / reberGrammerSize))\n        error += 1;\n    }\n\n    error /= testReberGrammarCount;\n    if (error <= 0.35)\n    {\n      ++successes;\n      break;\n    }\n\n    offset += 3;\n  }\n\n  BOOST_REQUIRE_GE(successes, 1);\n}\n\n/**\n * Train the specified networks on an embedded Reber grammar dataset.\n */\nBOOST_AUTO_TEST_CASE(CustomRecursiveReberGrammarTest)\n{\n  ReberGrammarTestCustomNetwork(16, true);\n}\n\n/**\n * @brief Generates noisy sine wave and outputs the data and the labels that\n *        can be used directly for training and testing with RNN.\n *\n * @param data The data points as output\n * @param labels The expected values as output\n * @param rho The size of the sequence of each data point\n * @param outputSteps How many output steps to consider for every rho inputs\n * @param dataPoints  The number of generated data points. The actual generated\n *        data points may be more than this to adjust to the outputSteps. But at\n *        the minimum these many data points will be generated.\n * @param gain The gain on the amplitude\n * @param freq The frquency of the sine wave\n * @param phase The phase shift if any\n * @param noisePercent The percent noise to induce\n * @param numCycles How many full size wave cycles required. All the data\n *        points will be fit into these cycles.\n * @param normalize Whether to normalise the data. This may be required for some\n *        layers like LSTM. Default is true.\n */\nvoid GenerateNoisySinRNN(arma::cube& data,\n                         arma::cube& labels,\n                         size_t rho,\n                         size_t outputSteps = 1,\n                         const int dataPoints = 100,\n                         const double gain = 1.0,\n                         const int freq = 10,\n                         const double phase = 0,\n                         const int noisePercent = 20,\n                         const double numCycles = 6.0,\n                         const bool normalize = true)\n{\n  int points = dataPoints;\n  int r = dataPoints % rho;\n\n  if (r == 0)\n  {\n    points += outputSteps;\n  }\n  else\n  {\n    points += rho - r + outputSteps;\n  }\n\n  arma::colvec x(points);\n  int i = 0;\n  double interval = numCycles / freq / points;\n\n  x.for_each([&i, gain, freq, phase, noisePercent, interval]\n    (arma::colvec::elem_type& val) {\n    double t = interval * (++i);\n    val = gain * ::sin(2 * M_PI * freq * t + phase) +\n        (noisePercent * gain / 100 * Random(0.0, 0.1));\n  });\n\n  arma::colvec y = x;\n  if (normalize)\n    y = arma::normalise(x);\n\n  // Now break this into columns of rho size slices.\n  size_t numColumns = y.n_elem / rho;\n  data = arma::cube(1, numColumns, rho);\n  labels = arma::cube(outputSteps, numColumns, 1);\n\n  for (size_t i = 0; i < numColumns; ++i)\n  {\n    data.tube(0, i) = y.rows(i * rho, i * rho + rho - 1);\n    labels.subcube(0, i, 0, outputSteps - 1, i, 0) =\n        y.rows(i * rho + rho, i * rho + rho + outputSteps - 1);\n  }\n}\n\n/**\n * @brief RNNSineTest Test a simple RNN using noisy sine. Use single output\n *        for multiple inputs.\n * @param hiddenUnits No of units in the hiddenlayer.\n * @param rho The input sequence length.\n * @param numEpochs The number of epochs to run.\n * @return The mean squared error of the prediction.\n */\ndouble RNNSineTest(size_t hiddenUnits, size_t rho, size_t numEpochs = 100)\n{\n  RNN<MeanSquaredError<> > net(rho, true);\n  net.Add<LinearNoBias<> >(1, hiddenUnits);\n  net.Add<LSTM<> >(hiddenUnits, hiddenUnits);\n  net.Add<LinearNoBias<> >(hiddenUnits, 1);\n\n  RMSProp opt(0.005, 100, 0.9, 1e-08, 50000, 1e-5);\n\n  // Generate data\n  arma::cube data;\n  arma::cube labels;\n  GenerateNoisySinRNN(data, labels, rho, 1, 2000, 20.0, 200, 0.0, 45, 20);\n\n  // Break into training and test sets. Simply split along columns.\n  size_t trainCols = data.n_cols * 0.8; // Take 20% out for testing.\n  size_t testCols = data.n_cols - trainCols;\n  arma::cube testData = data.subcube(0, data.n_cols - testCols, 0,\n      data.n_rows - 1, data.n_cols - 1, data.n_slices - 1);\n  arma::cube testLabels = labels.subcube(0, labels.n_cols - testCols, 0,\n      labels.n_rows - 1, labels.n_cols - 1, labels.n_slices - 1);\n\n  for (size_t i = 0; i < numEpochs; ++i)\n  {\n    net.Train(data.subcube(0, 0, 0, data.n_rows - 1, trainCols - 1,\n        data.n_slices - 1), labels.subcube(0, 0, 0, labels.n_rows - 1,\n        trainCols - 1, labels.n_slices - 1), opt);\n  }\n  // Well now it should be trained. Do the test here.\n  arma::cube prediction;\n  net.Predict(testData, prediction);\n\n  // The prediction must really follow the test data. So convert both the test\n  // data and the pediction to vectors and compare the two.\n  arma::colvec testVector = arma::vectorise(testData);\n  arma::colvec predVector = arma::vectorise(prediction);\n\n  // Adjust the vectors for comparison, as the prediction is one step ahead.\n  testVector = testVector.rows(1, testVector.n_rows - 1);\n  predVector = predVector.rows(0, predVector.n_rows - 2);\n  double error = std::sqrt(arma::sum(arma::square(testVector - predVector))) /\n      testVector.n_rows;\n\n  return error;\n}\n\n/**\n * Test RNN using multiple timestep input and single output.\n */\nBOOST_AUTO_TEST_CASE(MultiTimestepTest)\n{\n  double err = RNNSineTest(4, 10, 20);\n  BOOST_REQUIRE_LE(err, 0.025);\n}\n\n/**\n * Test that RNN::Train() returns finite objective value.\n */\nBOOST_AUTO_TEST_CASE(RNNTrainReturnObjective)\n{\n  const size_t rho = 10;\n\n  // Generate 12 (2 * 6) noisy sines. A single sine contains rho\n  // points/features.\n  arma::cube input;\n  arma::mat labelsTemp;\n  GenerateNoisySines(input, labelsTemp, rho, 6);\n\n  arma::cube labels = arma::zeros<arma::cube>(1, labelsTemp.n_cols, rho);\n  for (size_t i = 0; i < labelsTemp.n_cols; ++i)\n  {\n    const int value = arma::as_scalar(arma::find(\n        arma::max(labelsTemp.col(i)) == labelsTemp.col(i), 1)) + 1;\n    labels.tube(0, i).fill(value);\n  }\n\n  /**\n   * Construct a network with 1 input unit, 4 hidden units and 10 output\n   * units. The hidden layer is connected to itself. The network structure\n   * looks like:\n   *\n   *  Input         Hidden        Output\n   * Layer(1)      Layer(4)      Layer(10)\n   * +-----+       +-----+       +-----+\n   * |     |       |     |       |     |\n   * |     +------>|     +------>|     |\n   * |     |    ..>|     |       |     |\n   * +-----+    .  +--+--+       +-----+\n   *            .     .\n   *            .     .\n   *            .......\n   */\n  Add<> add(4);\n  Linear<> lookup(1, 4);\n  SigmoidLayer<> sigmoidLayer;\n  Linear<> linear(4, 4);\n  Recurrent<>* recurrent = new Recurrent<>(add, lookup, linear,\n      sigmoidLayer, rho);\n\n  RNN<> model(rho);\n  model.Add<IdentityLayer<> >();\n  model.Add(recurrent);\n  model.Add<Linear<> >(4, 10);\n  model.Add<LogSoftMax<> >();\n\n  StandardSGD opt(0.1, 1, input.n_cols /* 1 epoch */, -100);\n  double objVal = model.Train(input, labels, opt);\n\n  BOOST_REQUIRE_EQUAL(std::isfinite(objVal), true);\n}\n\n/**\n * Test that BRNN::Train() returns finite objective value.\n */\nBOOST_AUTO_TEST_CASE(BRNNTrainReturnObjective)\n{\n  const size_t rho = 10;\n\n  arma::cube input;\n  arma::mat labelsTemp;\n  GenerateNoisySines(input, labelsTemp, rho, 6);\n\n  arma::cube labels = arma::zeros<arma::cube>(1, labelsTemp.n_cols, rho);\n  for (size_t i = 0; i < labelsTemp.n_cols; ++i)\n  {\n    const int value = arma::as_scalar(arma::find(\n        arma::max(labelsTemp.col(i)) == labelsTemp.col(i), 1)) + 1;\n    labels.tube(0, i).fill(value);\n  }\n\n  Add<> add(4);\n  Linear<> lookup(1, 4);\n  SigmoidLayer<> sigmoidLayer;\n  Linear<> linear(4, 4);\n  Recurrent<>* recurrent = new Recurrent<>(\n      add, lookup, linear, sigmoidLayer, rho);\n\n  BRNN<> model(rho);\n  model.Add<IdentityLayer<> >();\n  model.Add(recurrent);\n  model.Add<Linear<> >(4, 5);\n\n  StandardSGD opt(0.1, 1, 500 * input.n_cols, -100);\n  double objVal = model.Train(input, labels, opt);\n  BOOST_TEST_CHECKPOINT(\"Training over\");\n\n  // Test that BRNN::Train() returns finite objective value.\n  BOOST_REQUIRE_EQUAL(std::isfinite(objVal), true);\n}\n\n/**\n * Test that RNN::Train() does not give an error for large rho.\n */\nBOOST_AUTO_TEST_CASE(LargeRhoValueRnnTest)\n{\n  // Setting rho value greater than sequence length which is 17.\n  const size_t rho = 100;\n  const size_t hiddenSize = 128;\n  const size_t numLetters = 256;\n  using MatType = arma::cube;\n  std::vector<std::string>trainingData = { \"THIS IS THE INPUT 0\" ,\n                                           \"THIS IS THE INPUT 1\" ,\n                                           \"THIS IS THE INPUT 3\"};\n\n\n  RNN<> model(rho);\n  model.Add<IdentityLayer<>>();\n  model.Add<LSTM<>>(numLetters, hiddenSize, rho);\n  model.Add<Dropout<>>(0.1);\n  model.Add<Linear<>>(hiddenSize, numLetters);\n\n  const auto makeInput = [numLetters](const char *line) -> MatType\n  {\n    const auto strLen = strlen(line);\n    // Rows: number of dimensions.\n    // Cols: number of sequences/points.\n    // Slices: number of steps in sequences.\n    MatType result(numLetters, 1, strLen, arma::fill::zeros);\n    for (size_t i = 0; i < strLen; ++i)\n    {\n      result.at(static_cast<arma::uword>(line[i]), 0, i) = 1.0;\n    }\n    return result;\n  };\n\n  const auto makeTarget = [] (const char *line) -> MatType\n  {\n    const auto strLen = strlen(line);\n    // Responses for NegativeLogLikelihood should be\n    // non-one-hot-encoded class IDs (from 1 to num_classes).\n    MatType result(1, 1, strLen, arma::fill::zeros);\n    // The response is the *next* letter in the sequence.\n    for (size_t i = 0; i < strLen - 1; ++i)\n    {\n      result.at(0, 0, i) = static_cast<arma::uword>(line[i + 1]) + 1.0;\n    }\n    // The final response is empty, so we set it to class 0.\n    result.at(0, 0, strLen - 1) = 1.0;\n    return result;\n  };\n\n  std::vector<MatType> inputs(trainingData.size());\n  std::vector<MatType> targets(trainingData.size());\n  for (size_t i = 0; i < trainingData.size(); ++i)\n  {\n    inputs[i] = makeInput(trainingData[i].c_str());\n    targets[i] = makeTarget(trainingData[i].c_str());\n  }\n  ens::SGD<> opt(0.01, 1, 100);\n  model.Train(inputs[0], targets[0], opt);\n  BOOST_TEST_CHECKPOINT(\"Training over\");\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "10635e80fb987bf60096f046931c57f332a5dc15", "size": 45966, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/recurrent_network_test.cpp", "max_stars_repo_name": "tejasvi/mlpack", "max_stars_repo_head_hexsha": "9bc159c52d13139834cc89e8669fe65fc97fa107", "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-12-09T17:58:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-09T17:58:29.000Z", "max_issues_repo_path": "src/mlpack/tests/recurrent_network_test.cpp", "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/tests/recurrent_network_test.cpp", "max_forks_repo_name": "R-Aravind/mlpack", "max_forks_repo_head_hexsha": "99d11a9b4d379885cf7f8160d8c71fb792fa1bbc", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-20T19:38:10.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-20T19:38:10.000Z", "avg_line_length": 31.0581081081, "max_line_length": 80, "alphanum_fraction": 0.6027498586, "num_tokens": 12845, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541067, "lm_q2_score": 0.5813030906443134, "lm_q1q2_score": 0.4534122835983339}}
{"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__INTERP__BEZIER_HPP_\n#define SMOOTH__INTERP__BEZIER_HPP_\n\n/**\n * @file\n * @brief bezier splines on lie groups.\n */\n\n#include <ranges>\n\n#include <Eigen/Sparse>\n#include <Eigen/SparseLU>\n\n#include \"smooth/concepts.hpp\"\n#include \"smooth/internal/utils.hpp\"\n\n#include \"common.hpp\"\n\nnamespace smooth {\n\n/**\n * @brief Bezier curve on [0, 1].\n * @tparam N Polonimial degree of curve.\n * @tparam G LieGroup type.\n *\n * The curve is defined by\n * \\f[\n *  g(t) = g_0 * \\exp(\\tilde B_1(t) v_1) * ... \\exp(\\tilde B_N(t) v_N)\n * \\f]\n * where \\f$\\tilde B_i(t)\\f$ are cumulative Bernstein basis functions and\n * \\f$v_i = g_i \\ominus g_{i-1}\\f$ are the control point differences.\n */\ntemplate<std::size_t N, LieGroup G>\nclass Bezier\n{\npublic:\n  /**\n   * @brief Default constructor creates a constant curve on [0, 1] equal to identity.\n   */\n  Bezier() : g0_(G::Identity()) { vs_.fill(G::Tangent::Zero()); }\n\n  /**\n   * @brief Create curve from rvalue parameter values.\n   *\n   * @param g0 starting value\n   * @param vs differences [v_1, ..., v_n] between control points\n   */\n  Bezier(G && g0, std::array<typename G::Tangent, N> && vs) : g0_(std::move(g0)), vs_(std::move(vs))\n  {}\n\n  /**\n   * @brief Create curve from parameter values.\n   *\n   * @tparam Rv range containing control point differences\n   * @param g0 starting value\n   * @param vs differences [v_1, ..., v_n] between control points\n   *\n   * @note Range value type of \\p Rv must be the tangent type of \\p G.\n   */\n  template<std::ranges::range Rv>\n  Bezier(const G & g0, const Rv & vs) : g0_(g0)\n  {\n    if (std::ranges::size(vs) != N) { throw std::runtime_error(\"Wrong number of control points\"); }\n    std::copy(std::ranges::begin(vs), std::ranges::end(vs), vs_.begin());\n  }\n\n  /// @brief Copy constructor\n  Bezier(const Bezier &) = default;\n  /// @brief Move constructor\n  Bezier(Bezier &&) = default;\n  /// @brief Copy assignment\n  Bezier & operator=(const Bezier &) = default;\n  /// @brief Move assignment\n  Bezier & operator=(Bezier &&) = default;\n  /// @brief Destructor\n  ~Bezier() = default;\n\n  /**\n   * @brief Evaluate Bezier curve.\n   *\n   * @param[in] t time point to evaluate at\n   * @param[out] vel output body velocity at evaluation time\n   * @param[out] acc output body acceleration at evaluation time\n   * @return spline value at time t\n   *\n   * @note Input \\p t is clamped to interval [0, 1]\n   */\n  G eval(double t, detail::OptTangent<G> vel = {}, detail::OptTangent<G> acc = {}) const\n  {\n    double tc = std::clamp<double>(t, 0, 1);\n\n    constexpr auto Mstatic = detail::cum_coefmat<CSplineType::BEZIER, double, N>().transpose();\n    Eigen::Map<const Eigen::Matrix<double, N + 1, N + 1, Eigen::RowMajor>> M(Mstatic[0].data());\n\n    return cspline_eval<N>(g0_, vs_, M, tc, vel, acc);\n  }\n\nprivate:\n  G g0_;\n  std::array<typename G::Tangent, N> vs_;\n};\n\n/**\n * @brief Piecewise curve built from Bezier segments.\n *\n * The curve is given by\n * \\f[\n *  \\mathbf{x}(t) = p_i \\left( \\frac{t - t_i}{t_{i+1} - t_{i}} \\right)\n * \\f]\n * for \\f$ t \\in [t_i, t_{i+1}]\\f$\n * where \\f$p_i\\f$ is a Bezier curve on \\f$[0, 1]\\f$.\n */\ntemplate<std::size_t N, LieGroup G>\nclass PiecewiseBezier\n{\npublic:\n  /**\n   * @brief Default constructor creates a constant curve defined on [0, 1] equal to identity.\n   */\n  PiecewiseBezier() : knots_{0, 1}, segments_{Bezier<N, G>{}} {}\n\n  /**\n   * @brief Create a PiecewiseBezier from knot times and Bezier segments.\n   *\n   * @param knots points \\f$ t_i \\f$\n   * @param segments Bezier curves \\f$ p_i \\f$\n   */\n  PiecewiseBezier(std::vector<double> && knots, std::vector<Bezier<N, G>> && segments)\n      : knots_(std::move(knots)), segments_(std::move(segments))\n  {}\n\n  /**\n   * @brief Create a PiecewiseBezier from knot times and Bezier segments.\n   *\n   * @param knots points \\f$ t_i \\f$\n   * @param segments Bezier curves \\f$ p_i \\f$\n   */\n  template<std::ranges::range Rt, std::ranges::range Rs>\n  PiecewiseBezier(const Rt & knots, const Rs & segments)\n      : knots_(std::ranges::begin(knots), std::ranges::end(knots)),\n        segments_(std::ranges::begin(segments), std::ranges::end(segments))\n  {}\n\n  /// @brief Copy constructor\n  PiecewiseBezier(const PiecewiseBezier &) = default;\n  /// @brief Move constructor\n  PiecewiseBezier(PiecewiseBezier &&) = default;\n  /// @brief Copy assignment\n  PiecewiseBezier & operator=(const PiecewiseBezier &) = default;\n  /// @brief Move assignment\n  PiecewiseBezier & operator=(PiecewiseBezier &&) = default;\n  /// @brief Destructor\n  ~PiecewiseBezier() = default;\n\n  /// @brief Minimal time where curve is defined.\n  double t_min() const { return knots_.front(); }\n\n  /// @brief Maximal time where curve is defined.\n  double t_max() const { return knots_.back(); }\n\n  /**\n   * @brief Evalauate PiecewiseBezier curve.\n   *\n   * @param[in] t time point to evaluate at\n   * @param[out] vel output body velocity at evaluation time\n   * @param[out] acc output body acceleration at evaluation time\n   * @return curve value at time t\n   */\n  G eval(double t, detail::OptTangent<G> vel = {}, detail::OptTangent<G> acc = {}) const\n  {\n    /// find index\n    // TODO binary search\n    std::size_t istar = 0;\n    while (istar + 2 < knots_.size() && knots_[istar + 1] <= t) { ++istar; }\n\n    double T = knots_[istar + 1] - knots_[istar];\n\n    const double u = (t - knots_[istar]) / T;\n\n    G g = segments_[istar].eval(u, vel, acc);\n\n    if (vel.has_value()) { vel.value() /= T; }\n    if (acc.has_value()) { acc.value() /= (T * T); }\n\n    return g;\n  }\n\nprivate:\n  std::vector<double> knots_;\n  std::vector<Bezier<N, G>> segments_;\n};\n\n/**\n * @brief Fit a linear PiecewiseBezier curve to data.\n *\n * The resulting curve passes through the data points and has piecewise\n * constant velocity.\n *\n * @warning Result has discontinuous derivatives at knot points\n *\n * @tparam Rt, Rg range types\n * @param tt interpolation times\n * @param gg interpolation values\n */\ntemplate<std::ranges::range Rt, std::ranges::range Rg>\nPiecewiseBezier<1, std::ranges::range_value_t<Rg>> fit_linear_bezier(const Rt & tt, const Rg & gg)\n{\n  if (std::ranges::size(tt) < 2 || std::ranges::size(gg) < 2) {\n    throw std::runtime_error(\"Not enough points\");\n  }\n  using G = std::ranges::range_value_t<Rg>;\n\n  const std::size_t N = std::min<std::size_t>(std::ranges::size(tt), std::ranges::size(gg)) - 1;\n\n  std::vector<Bezier<1, G>> segments(N);\n\n  auto it_g = std::ranges::begin(gg);\n  auto it_t = std::ranges::begin(tt);\n\n  for (auto i = 0u; i != N; ++i, ++it_t, ++it_g) {\n    segments[i] = Bezier<1, G>(*it_g, std::array<typename G::Tangent, 1>{(*(it_g + 1) - *it_g)});\n  }\n\n  auto take_view = tt | std::views::take(N + 1);\n  std::vector<double> knots(std::ranges::begin(take_view), std::ranges::end(take_view));\n\n  return PiecewiseBezier<1, G>(std::move(knots), std::move(segments));\n}\n\n/**\n * @brief Fit a quadratic PiecewiseBezier curve to data.\n *\n * The resulting curve passes through the data points and has\n * continuous derivatives.\n *\n * @warning Result may exhibit oscillatory behavior since second derivative\n * is free.\n *\n * @tparam Rt, Rg range types\n * @param tt interpolation times\n * @param gg interpolation values\n */\ntemplate<std::ranges::range Rt, std::ranges::range Rg>\nPiecewiseBezier<2, std::ranges::range_value_t<Rg>> fit_quadratic_bezier(\n  const Rt & tt, const Rg & gg)\n{\n  if (std::ranges::size(tt) < 2 || std::ranges::size(gg) < 2) {\n    throw std::runtime_error(\"Not enough points\");\n  }\n  using G             = std::ranges::range_value_t<Rg>;\n  const std::size_t N = std::min<std::size_t>(std::ranges::size(tt), std::ranges::size(gg)) - 1;\n\n  std::vector<Bezier<2, G>> segments(N);\n\n  auto it_g = std::ranges::begin(gg);\n  auto it_t = std::ranges::begin(tt);\n\n  typename G::Tangent v0 = (*(it_g + 1) - *it_g) / (*(it_t + 1) - *it_t);\n\n  for (auto i = 0u; i != N; ++i, ++it_t, ++it_g) {\n    const double dt = *(it_t + 1) - *it_t;\n\n    // scaled velocity\n    const typename G::Tangent va = v0 * dt;\n\n    // create segment\n    const typename G::Tangent v1 = va / 2;\n    const typename G::Tangent v2 = *(it_g + 1) - (*it_g * G::exp(va / 2));\n\n    segments[i] = Bezier<2, G>(*it_g, std::array<typename G::Tangent, 2>{v1, v2});\n\n    // unscaled end velocity for interval\n    v0 = v2 * 2 / dt;\n  }\n\n  auto take_view = tt | std::views::take(N + 1);\n  std::vector<double> knots(std::ranges::begin(take_view), std::ranges::end(take_view));\n\n  return PiecewiseBezier<2, G>(std::move(knots), std::move(segments));\n}\n\n/**\n * @brief Fit a cubic PiecewiseBezier curve to data.\n *\n * The resulting curve passes through the data points, has continuous first\n * derivatives, and approximately continuous second derivatives.\n *\n * @tparam Rt, Rg range types\n * @param tt interpolation times\n * @param gg interpolation values\n */\ntemplate<std::ranges::range Rt, std::ranges::range Rg>\nPiecewiseBezier<3, std::ranges::range_value_t<Rg>> fit_cubic_bezier(const Rt & tt, const Rg & gg)\n{\n  if (std::ranges::size(tt) < 2 || std::ranges::size(gg) < 2) {\n    throw std::runtime_error(\"Not enough points\");\n  }\n  using G = std::ranges::range_value_t<Rg>;\n\n  // number of intervals\n  const std::size_t N = std::min<std::size_t>(std::ranges::size(tt), std::ranges::size(gg)) - 1;\n\n  std::size_t NumVars = G::Dof * 3 * N;\n\n  Eigen::SparseMatrix<typename G::Scalar> lhs;\n  lhs.resize(NumVars, NumVars);\n  Eigen::Matrix<int, -1, 1> nnz = Eigen::Matrix<int, -1, 1>::Constant(NumVars, 3);\n  nnz.head(G::Dof).setConstant(2);\n  nnz.tail(G::Dof).setConstant(2);\n  lhs.reserve(nnz);\n\n  Eigen::Matrix<typename G::Scalar, -1, 1> rhs(NumVars);\n  rhs.setZero();\n\n  // variable layout:\n  //\n  // [ v_{1, 0}; v_{2, 0}; v_{3, 0}; v_{1, 1}; v_{2, 1}; v_{3, 1}; ...]\n  //\n  // where v_ji is a Dof-length vector\n\n  const auto idx = [&](int j, int i) { return 3 * G::Dof * i + G::Dof * (j - 1); };\n\n  std::size_t row_counter = 0;\n\n  //// LEFT END POINT  ////\n\n  // zero second derivative at start:\n  // v_{1, 0} = v_{2, 0}\n  const std::size_t v10_start = idx(1, 0);\n  const std::size_t v20_start = idx(2, 0);\n  for (auto n = 0u; n != G::Dof; ++n) {\n    lhs.insert(row_counter + n, v10_start + n) = 1;\n    lhs.insert(row_counter + n, v20_start + n) = -1;\n  }\n  row_counter += G::Dof;\n\n  //// INTERIOR END POINT  ////\n\n  auto it_t = std::ranges::begin(tt);\n  auto it_g = std::ranges::begin(gg);\n\n  for (auto i = 0u; i + 1 < N; ++i, ++it_t, ++it_g) {\n    const std::size_t v1i_start = idx(1, i);\n    const std::size_t v2i_start = idx(2, i);\n    const std::size_t v3i_start = idx(3, i);\n\n    const std::size_t v1ip_start = idx(1, i + 1);\n    const std::size_t v2ip_start = idx(2, i + 1);\n\n    // segment lengths\n    const typename G::Scalar Ti  = *(it_t + 1) - *it_t;\n    const typename G::Scalar Tip = *(it_t + 2) - *(it_t + 1);\n\n    // pass through control points\n    // v_{1, i} + v_{2, i} + v_{3, i} = x_{i+1} - x_i\n    for (auto n = 0u; n != G::Dof; ++n) {\n      lhs.insert(row_counter + n, v1i_start + n) = 1;\n      lhs.insert(row_counter + n, v2i_start + n) = 1;\n      lhs.insert(row_counter + n, v3i_start + n) = 1;\n    }\n    rhs.segment(row_counter, G::Dof) = *(it_g + 1) - *(it_g);\n    row_counter += G::Dof;\n\n    // velocity continuity\n    // v_{3, i} = v_{1, i+1}\n    for (auto n = 0u; n != G::Dof; ++n) {\n      lhs.insert(row_counter + n, v3i_start + n)  = 1 * Tip;\n      lhs.insert(row_counter + n, v1ip_start + n) = -1 * Ti;\n    }\n    row_counter += G::Dof;\n\n    // acceleration continuity (approximate for Lie groups)\n    // v_{2, i} - v_{3, i} = v_{2, i+1} - v_{1, i+1}\n    for (auto n = 0u; n != G::Dof; ++n) {\n      lhs.insert(row_counter + n, v2i_start + n)  = 1 * (Tip * Tip);\n      lhs.insert(row_counter + n, v3i_start + n)  = -1 * (Tip * Tip);\n      lhs.insert(row_counter + n, v1ip_start + n) = -1 * (Ti * Ti);\n      lhs.insert(row_counter + n, v2ip_start + n) = 1 * (Ti * Ti);\n    }\n    row_counter += G::Dof;\n  }\n\n  //// RIGHT END POINT  ////\n\n  const std::size_t v1_nm_start = idx(1, N - 1);\n  const std::size_t v2_nm_start = idx(2, N - 1);\n  const std::size_t v3_nm_start = idx(3, N - 1);\n\n  // end at last control point\n  // v_{1, n-1} + v_{2, n-1} v_{3, n-1} = x_{n} - x_{n-1}\n  for (auto n = 0u; n != G::Dof; ++n) {\n    lhs.insert(row_counter + n, v1_nm_start + n) = 1;\n    lhs.insert(row_counter + n, v2_nm_start + n) = 1;\n    lhs.insert(row_counter + n, v3_nm_start + n) = 1;\n  }\n  rhs.segment(row_counter, G::Dof) = *(it_g + 1) - *it_g;\n  row_counter += G::Dof;\n\n  // zero second derivative at end:\n  // v_{2, n-1} = v_{3, n-1}\n  for (auto n = 0u; n != G::Dof; ++n) {\n    lhs.insert(row_counter + n, v2_nm_start + n) = 1;\n    lhs.insert(row_counter + n, v3_nm_start + n) = -1;\n  }\n\n  //// DONE FILLING SPARSE MATRIX ////\n\n  lhs.makeCompressed();\n\n  //// SOLVE SYSTEM ////\n\n  Eigen::SparseLU<decltype(lhs), Eigen::COLAMDOrdering<int>> solver(lhs);\n  Eigen::VectorXd result = solver.solve(rhs);\n\n  //// EXTRACT SOLUTION ////\n\n  std::vector<Bezier<3, G>> segments;\n  segments.reserve(N);\n\n  it_g = std::ranges::begin(gg);\n\n  for (auto i = 0u; i != N; ++i, ++it_g) {\n    const std::size_t v1i_start = idx(1, i);\n    const std::size_t v3i_start = idx(3, i);\n\n    typename G::Tangent v1 = result.template segment<G::Dof>(v1i_start);\n    typename G::Tangent v3 = result.template segment<G::Dof>(v3i_start);\n    // re-compute v2 to compensate for linearization\n    // this ensures points are interpolated, but the cost is\n    // potential non-continuity of the second derivative\n    typename G::Tangent v2 = *(it_g + 1) * G::exp(-v3) - *(it_g)*G::exp(v1);\n\n    segments.emplace_back(\n      *it_g, std::array<typename G::Tangent, 3>{std::move(v1), std::move(v2), std::move(v3)});\n  }\n\n  auto take_view = tt | std::views::take(N + 1);\n  std::vector<double> knots(std::ranges::begin(take_view), std::ranges::end(take_view));\n\n  return PiecewiseBezier<3, G>(std::move(knots), std::move(segments));\n}\n\n}  // namespace smooth\n\n#endif  // SMOOTH__INTERP__BEZIER_HPP_\n", "meta": {"hexsha": "b209efd7a9e4d9ac50b825e9a48e3488645b8885", "size": 15146, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/smooth/spline/bezier.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/spline/bezier.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/spline/bezier.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": 32.1571125265, "max_line_length": 100, "alphanum_fraction": 0.6317179453, "num_tokens": 4765, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4534122835983339}}
{"text": "#include \"CubicInterpolation/BicubicSplines.h\"\n#include \"CubicInterpolation/InterpolantBuilder.h\"\n\n#include <Eigen/Dense>\n#include <boost/math/differentiation/finite_difference.hpp>\n#include <boost/math/interpolators/cardinal_cubic_b_spline.hpp>\n#include <boost/serialization/access.hpp>\n#include <cmath>\n#include <vector>\n\n#include <chrono>\n#include <iostream>\n\nnamespace cubic_splines {\nnamespace detail {\n\ntemplate <typename T> auto calculate_node(T val, unsigned int n_max) {\n  auto n = std::floor(val);\n  if (n < 0)\n    return 0u;\n  if (static_cast<unsigned int>(n) > n_max - 2u)\n    return n_max - 2u;\n  return static_cast<unsigned int>(n);\n}\n\ntemplate <typename T> auto exponent_vector(T x) {\n  auto x_vec = ::Eigen::Matrix<T, 4, 1>(4);\n  for (size_t i = 0; i < 4; ++i) {\n    x_vec(i) = 1;\n    for (size_t j = 1; j <= i; ++j)\n      x_vec(i) *= x;\n  }\n  return x_vec;\n}\n} // namespace detail\n\nnamespace detail {}\n\ntemplate <typename T> struct BicubicSplines<T>::RuntimeData {\n  using MatrixX = ::Eigen::Matrix<T, ::Eigen::Dynamic, ::Eigen::Dynamic>;\n  using Matrix4 = ::Eigen::Matrix<T, 4, 4>;\n\n  MatrixX y, dydx1, dydx2, d2ydx1dx2;\n  Matrix4 m =\n      (Matrix4() << 1, 0, -3, 2, 0, 0, 3, -2, 0, 1, -2, 1, 0, 0, -1, 1).finished();\n\n  RuntimeData() = default;\n\n  RuntimeData(size_t n1, size_t n2)\n      : y(n1, n2), dydx1(n1, n2), dydx2(n1, n2), d2ydx1dx2(n1, n2){};\n\n  template <typename T1>\n  RuntimeData(T1 &&_y, T1 &&_dydx1, T1 &&_dydx2, T1 &&_d2ydx1dx2)\n      : y(std::forward<T1>(_y)), dydx1(std::forward<T1>(_dydx1)),\n        dydx2(std::forward<T1>(_dydx2)), d2ydx1dx2(std::forward<T1>(_d2ydx1dx2)){};\n\n  template <typename T1> static ::std::vector<T> to_vector(T1 m) {\n    return ::std::vector<T>(m.data(), m.data() + m.rows() * m.cols());\n  }\n\n  auto get_dimensions() const {\n    return std::array<long int, 2>{static_cast<long int>(y.rows()),\n                                   static_cast<long int>(y.cols())};\n  }\n\n  StorageData to_storage_data() const;\n};\n\ntemplate <typename T> struct BicubicSplines<T>::StorageData {\n  using MatrixX = ::Eigen::Matrix<T, ::Eigen::Dynamic, ::Eigen::Dynamic>;\n\n  ::std::array<long int, 2> size;\n  ::std::vector<T> y, dydx1, dydx2, d2ydx1dx2;\n\n  friend class boost::serialization::access;\n  template <class Archive> void serialize(Archive &ar, const unsigned int) {\n    ar &size;\n    ar &y;\n    ar &dydx1;\n    ar &dydx2;\n    ar &d2ydx1dx2;\n  }\n\n  template <typename V> inline auto to_matrix(V v) const {\n    return ::Eigen::Map<MatrixX>(v.data(), size[0], size[1]);\n  }\n\npublic:\n  StorageData() = default;\n\n  template <typename T1>\n  StorageData(std::array<long int, 2> _size, T1 &&_y, T1 &&_dydx1, T1 &&_dydx2,\n              T1 &&_d2ydx1dx2)\n      : size(std::move(_size)), y(std::forward<T1>(_y)), dydx1(std::forward<T1>(_dydx1)),\n        dydx2(std::forward<T1>(_dydx2)), d2ydx1dx2(std::forward<T1>(_d2ydx1dx2)){};\n\n  auto to_runtime_data() const {\n    return RuntimeData(to_matrix(y), to_matrix(dydx1), to_matrix(dydx2),\n                       to_matrix(d2ydx1dx2));\n  }\n};\n\ntemplate <typename T>\ntypename BicubicSplines<T>::StorageData\nBicubicSplines<T>::RuntimeData::to_storage_data() const {\n  return StorageData(get_dimensions(), to_vector(y), to_vector(dydx1), to_vector(dydx2),\n                     to_vector(d2ydx1dx2));\n}\n\ntemplate <typename T>\nBicubicSplines<T>::BicubicSplines(BicubicSplines::RuntimeData _data)\n    : data(::std::make_unique<BicubicSplines::RuntimeData>(_data)) {}\n\ntemplate <typename T>\nBicubicSplines<T>::BicubicSplines(Definition const &def, std::string path,\n                                  std::string filename) {\n  try {\n    auto storage_data = load<BicubicSplines>(path, filename);\n    *this = BicubicSplines(storage_data.to_runtime_data());\n  } catch (std::system_error const &ex) {\n    if (ex.code().value() != ENOENT)\n      throw(ex);\n    *this = BicubicSplines(def);\n    save(data->to_storage_data(), path, filename);\n  }\n}\n\ntemplate <typename T>\nstd::tuple<T, T> BicubicSplines<T>::back_transform(Definition const &def,\n                                                   unsigned long n1,\n                                                   unsigned long n2) const {\n  auto x1 = def.axis[0]->back_transform(n1);\n  auto x2 = def.axis[1]->back_transform(n2);\n  return std::make_tuple(x1, x2);\n}\n\ntemplate <typename T>\ntemplate <typename T1>\nstd::array<T, 2>\nBicubicSplines<T>::_prime(T1 func, std::array<std::unique_ptr<Axis<T>>, 2> const &axis,\n                          unsigned int n1, unsigned int n2) {\n  using boost::math::differentiation::finite_difference_derivative;\n  auto f_x1 = [&func, ax = axis[0].get(), x2 = axis[1]->back_transform(n2)](T t1) {\n    return func(ax->back_transform(t1), x2);\n  };\n  auto f_x2 = [&func, ax = axis[1].get(), x1 = axis[0]->back_transform(n1)](T t2) {\n    return func(x1, ax->back_transform(t2));\n  };\n  auto dydx = std::array<T, 2>();\n  dydx[0] = finite_difference_derivative(f_x1, static_cast<T>(n1));\n  dydx[1] = finite_difference_derivative(f_x2, static_cast<T>(n2));\n  return dydx;\n}\n\n/* template <typename T> */\n/* template <typename T1> */\n/* std::vector<std::tuple<unsigned int, T>> */\n/* BicubicSplines<T>::_prime(std::vector<T> const &yi, T1 func, unsigned int n_max) { */\n/*   auto spline = boost::math::interpolators::cardinal_cubic_b_spline<T>( */\n/*       yi.data(), yi.size(), 0, 1, func(0u), func(n_max)); */\n/*   auto diff = std::vector<std::tuple<unsigned int, T>>(); */\n/*   for (auto i = 0u; i < n_max; ++i) */\n/*     diff.emplace_back(i, spline.prime(i)); */\n/*   return diff; */\n/* } */\n\ntemplate <typename T>\ntemplate <typename T1>\nT BicubicSplines<T>::_double_prime(Definition const &def, T1 func, unsigned int n1,\n                                   unsigned int n2) {\n  using boost::math::differentiation::finite_difference_derivative;\n  auto f_x1 = [&func, ax = def.axis[0].get()](T t1, T t2) {\n    return func(ax->back_transform(t1), t2);\n  };\n  auto dydx1 = [&f_x1, n1](T t2) {\n    return finite_difference_derivative([&f_x1, t2](T t1) { return f_x1(t1, t2); },\n                                        static_cast<T>(n1));\n  };\n  auto dydx1_x2 = [&dydx1, ax = def.axis[1].get()](T t2) {\n    return dydx1(ax->back_transform(t2));\n  };\n  return finite_difference_derivative(dydx1_x2, static_cast<T>(n2));\n}\n\ntemplate <typename T>\nBicubicSplines<T>::BicubicSplines(Definition const &def)\n    : data(std::make_shared<RuntimeData>(def.axis[0]->required_nodes(),\n                                         def.axis[1]->required_nodes())) {\n  using boost::math::differentiation::finite_difference_derivative;\n  auto func = [&def](T x1, T x2) {\n    if (def.f_trafo)\n      return def.f_trafo->transform(def.f(x1, x2));\n    return def.f(x1, x2);\n  };\n\n  for (auto n1 = 0u; n1 < data->y.rows(); ++n1) {\n    for (auto n2 = 0u; n2 < data->y.cols(); ++n2) {\n      auto x = back_transform(def, n1, n2);\n      data->y(n1, n2) = func(std::get<0>(x), std::get<1>(x));\n    }\n  }\n\n  auto n_rows = data->y.rows();\n  auto n_cols = data->y.cols();\n  if (def.approx_derivates) {\n    for (auto n1 = 0u; n1 < n_cols; ++n1) {\n      auto yi = RuntimeData::to_vector(data->y.col(n1));\n      auto diff = [this, &def, &func, n1](unsigned int n) {\n        return _prime(func, def.axis, n, n1)[0];\n      };\n      auto spline = boost::math::interpolators::cardinal_cubic_b_spline<T>(\n          yi.data(), yi.size(), 0, 1, diff(0u), diff(n_rows - 1));\n      for (auto row = 0; row < n_rows; ++row)\n        data->dydx1(n1, row) = spline.prime(row);\n    }\n    data->dydx1.transposeInPlace();\n\n    ::Eigen::Matrix<T, ::Eigen::Dynamic, ::Eigen::Dynamic> y_rowise = data->y;\n    y_rowise.transposeInPlace();\n    for (auto n2 = 0u; n2 < n_rows; ++n2) {\n      auto yi = RuntimeData::to_vector(y_rowise.col(n2));\n      auto diff = [this, &def, &func, n2](unsigned int n) {\n        return _prime(func, def.axis, n2, n)[1];\n      };\n      auto spline = boost::math::interpolators::cardinal_cubic_b_spline<T>(\n          yi.data(), yi.size(), 0, 1, diff(0u), diff(n_cols - 1));\n      for (auto col = 0; col < n_cols; ++col)\n        data->dydx2(col, n2) = spline.prime(col);\n    }\n    data->dydx2.transposeInPlace();\n  } else {\n    for (auto n1 = 0u; n1 < n_rows; ++n1) {\n      for (auto n2 = 0u; n2 < n_cols; ++n2) {\n        auto dydx = _prime(func, def.axis, n1, n2);\n        data->dydx1(n1, n2) = dydx[0];\n        data->dydx2(n1, n2) = dydx[1];\n      }\n    }\n  }\n  if (def.approx_derivates) {\n    ::Eigen::Matrix<T, ::Eigen::Dynamic, ::Eigen::Dynamic> dydx1_rowise = data->dydx1;\n    dydx1_rowise.transposeInPlace();\n    for (auto n2 = 0u; n2 < n_rows; ++n2) {\n      auto yi = RuntimeData::to_vector(dydx1_rowise.col(n2));\n      auto diff = [this, &def, &func, n2](unsigned int n) {\n        return _double_prime(def, func, n2, n);\n      };\n      auto spline = boost::math::interpolators::cardinal_cubic_b_spline<T>(\n          yi.data(), yi.size(), 0, 1, diff(0u), diff(n_cols - 1));\n      for (auto col = 0; col < n_cols; ++col)\n        data->d2ydx1dx2(col, n2) = spline.prime(col);\n    }\n    data->d2ydx1dx2.transposeInPlace();\n  } else {\n    for (auto n1 = 0u; n1 < n_rows; ++n1) {\n      for (auto n2 = 0u; n2 < n_cols; ++n2)\n        data->d2ydx1dx2(n1, n2) = _double_prime(def, func, n1, n2);\n    }\n  }\n}\n\ntemplate <typename T> T BicubicSplines<T>::evaluate(T x0, T x1) const {\n  auto n0 = detail::calculate_node(x0, data->y.cols());\n  auto n1 = detail::calculate_node(x1, data->y.rows());\n  auto temp = ::Eigen::Matrix<T, 4, 4>(4, 4);\n  temp.template block<2, 2>(0, 0) = data->y.block(n0, n1, 2, 2);\n  temp.template block<2, 2>(2, 0) = data->dydx1.block(n0, n1, 2, 2);\n  temp.template block<2, 2>(0, 2) = data->dydx2.block(n0, n1, 2, 2);\n  temp.template block<2, 2>(2, 2) = data->d2ydx1dx2.block(n0, n1, 2, 2);\n  auto v1 = detail::exponent_vector(x0 - n0);\n  auto v2 = detail::exponent_vector(x1 - n1);\n  return v1.dot((data->m.transpose() * (temp * data->m)) * v2);\n}\n\ntemplate <typename T> std::array<T, 2> BicubicSplines<T>::prime(T x0, T x1) const {\n  using boost::math::differentiation::finite_difference_derivative;\n  auto grad = std::array<T, 2>();\n  grad[0] =\n      finite_difference_derivative([this, x1](T x_0) { return evaluate(x_0, x1); }, x0);\n  grad[1] =\n      finite_difference_derivative([this, x0](T x_1) { return evaluate(x0, x_1); }, x1);\n  return grad;\n}\n\ntemplate <typename T> T BicubicSplines<T>::double_prime(T x0, T x1) const {\n  using boost::math::differentiation::finite_difference_derivative;\n  return finite_difference_derivative(\n      [this, x1](T x_1) {\n        return finite_difference_derivative(\n            [this, x_1](T x_2) { return evaluate(x_1, x_2); }, x1);\n      },\n      x0);\n}\n} // namespace cubic_splines\n\ntemplate class cubic_splines::BicubicSplines<double>;\ntemplate class cubic_splines::BicubicSplines<float>;\n", "meta": {"hexsha": "43b53399f948d62946864f444b1ebd72bc3dfccb", "size": 10775, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/detail/BicubicSplines.cxx", "max_stars_repo_name": "maxnoe/cubic_interpolation", "max_stars_repo_head_hexsha": "5e272ed3b2697a72bdbc4978b7eb7494c333bd5f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-01-07T15:35:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-14T06:59:47.000Z", "max_issues_repo_path": "src/detail/BicubicSplines.cxx", "max_issues_repo_name": "maxnoe/cubic_interpolation", "max_issues_repo_head_hexsha": "5e272ed3b2697a72bdbc4978b7eb7494c333bd5f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2021-02-12T11:46:11.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-31T09:03:01.000Z", "max_forks_repo_path": "src/detail/BicubicSplines.cxx", "max_forks_repo_name": "maxnoe/cubic_interpolation", "max_forks_repo_head_hexsha": "5e272ed3b2697a72bdbc4978b7eb7494c333bd5f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-02-12T14:34:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-19T13:33:52.000Z", "avg_line_length": 36.1577181208, "max_line_length": 89, "alphanum_fraction": 0.6151276102, "num_tokens": 3527, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257127, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4534122776525368}}
{"text": "/* pcmsolver_copyright_start */\n/*\n *     PCMSolver, an API for the Polarizable Continuum Model\n *     Copyright (C) 2013-2016 Roberto Di Remigio, Luca Frediani and contributors\n *     \n *     This file is part of PCMSolver.\n *     \n *     PCMSolver is free software: you can redistribute it and/or modify\n *     it under the terms of the GNU Lesser General Public License as published by\n *     the Free Software Foundation, either version 3 of the License, or\n *     (at your option) any later version.\n *     \n *     PCMSolver is distributed in the hope that it will be useful,\n *     but WITHOUT ANY WARRANTY; without even the implied warranty of\n *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *     GNU Lesser General Public License for more details.\n *     \n *     You should have received a copy of the GNU Lesser General Public License\n *     along with PCMSolver.  If not, see <http://www.gnu.org/licenses/>.\n *     \n *     For information on the complete list of contributors to the\n *     PCMSolver API, see: <http://pcmsolver.readthedocs.io/>\n */\n/* pcmsolver_copyright_end */\n\n#include \"catch.hpp\"\n\n#include <cmath>\n#include <iostream>\n\n\n#include <Eigen/Core>\n\n#include \"bi_operators/CollocationIntegrator.hpp\"\n#include \"AnalyticEvaluate.hpp\"\n#include \"green/AnisotropicLiquid.hpp\"\n#include \"green/DerivativeTypes.hpp\"\n\nSCENARIO(\"Evaluation of the anisotropic liquid Green's function and its derivatives\", \"[green][green_anisotropic_liquid]\")\n{\n    GIVEN(\"A liquid with an anisotropic permittivity tensor\")\n    {\n        Eigen::Vector3d epsilon = (Eigen::Vector3d() << 2.0, 80.0, 15.0).finished();\n        Eigen::Vector3d euler   = (Eigen::Vector3d() << 6.0, 40.0, 15.0).finished();\n        Eigen::Vector3d source = Eigen::Vector3d::Random();\n        Eigen::Vector3d sourceNormal = source + Eigen::Vector3d::Random();\n        sourceNormal.normalize();\n        Eigen::Vector3d probe = Eigen::Vector3d::Random();\n        Eigen::Vector3d probeNormal = probe + Eigen::Vector3d::Random();\n        probeNormal.normalize();\n        Eigen::Array4d result = analyticAnisotropicLiquid(epsilon, euler, sourceNormal, source, probeNormal, probe);\n\n        /*! \\class AnisotropicLiquid\n         *  \\test \\b AnisotropicLiquidTest_numerical tests the numerical evaluation of the AnisotropicLiquid Green's function against analytical result\n         */\n        WHEN(\"the derivatives are evaluated numerically\")\n        {\n            AnisotropicLiquid<Numerical, CollocationIntegrator> gf(epsilon, euler);\n            THEN(\"the value of the Green's function is\")\n            {\n                double value = result(0);\n                double gf_value = gf.kernelS(source, probe);\n                REQUIRE(value == Approx(gf_value));\n            }\n            AND_THEN(\"the value of the Green's function directional derivative wrt the probe point is\")\n            {\n                double derProbe = result(1);\n                double gf_derProbe = gf.derivativeProbe(probeNormal, source, probe);\n                REQUIRE(derProbe == Approx(gf_derProbe));\n            }\n            AND_THEN(\"the value of the Green's function directional derivative wrt the source point is\")\n            {\n                double derSource = result(2);\n                double gf_derSource = gf.derivativeSource(sourceNormal, source, probe);\n                REQUIRE(derSource == Approx(gf_derSource));\n            }\n        }\n\n        /*! \\class AnisotropicLiquid\n         *  \\test \\b AnisotropicLiquidTest_directional_AD tests the automatic evaluation (directional derivative only)\n         *  of the AnisotropicLiquid Green's function against analytical result\n         */\n        WHEN(\"the derivatives are evaluated via AD\")\n        {\n            AnisotropicLiquid<> gf(epsilon, euler);\n            THEN(\"the value of the Green's function is\")\n            {\n                double value = result(0);\n                double gf_value = gf.kernelS(source, probe);\n                REQUIRE(value == Approx(gf_value));\n            }\n            AND_THEN(\"the value of the Green's function directional derivative wrt the probe point is\")\n            {\n                double derProbe = result(1);\n                double gf_derProbe = gf.derivativeProbe(probeNormal, source, probe);\n                REQUIRE(derProbe == Approx(gf_derProbe));\n            }\n            AND_THEN(\"the value of the Green's function directional derivative wrt the source point is\")\n            {\n                double derSource = result(2);\n                double gf_derSource = gf.derivativeSource(sourceNormal, source, probe);\n                REQUIRE(derSource == Approx(gf_derSource));\n            }\n        }\n\n        /*! \\class AnisotropicLiquid\n         *  \\test \\b AnisotropicLiquidTest_gradient_AD tests the automatic evaluation (full gradient)\n         *  of the AnisotropicLiquid Green's function against analytical result\n         */\n        WHEN(\"the derivatives are evaluated via AD using the full gradient\")\n        {\n            AnisotropicLiquid<AD_gradient, CollocationIntegrator> gf(epsilon, euler);\n            THEN(\"the value of the Green's function is\")\n            {\n                double value = result(0);\n                double gf_value = gf.kernelS(source, probe);\n                REQUIRE(value == Approx(gf_value));\n            }\n            AND_THEN(\"the value of the Green's function directional derivative wrt the probe point is\")\n            {\n                double derProbe = result(1);\n                double gf_derProbe = gf.derivativeProbe(probeNormal, source, probe);\n                REQUIRE(derProbe == Approx(gf_derProbe));\n            }\n            AND_THEN(\"the value of the Green's function directional derivative wrt the source point is\")\n            {\n                double derSource = result(2);\n                double gf_derSource = gf.derivativeSource(sourceNormal, source, probe);\n                REQUIRE(derSource == Approx(gf_derSource));\n            }\n        }\n\n        /*! \\class AnisotropicLiquid\n         *  \\test \\b AnisotropicLiquidTest_hessian_AD tests the automatic evaluation (full hessian)\n         *  of the AnisotropicLiquid Green's function against analytical result\n         */\n        WHEN(\"the derivatives are evaluated via AD using the full hessian\")\n        {\n            AnisotropicLiquid<AD_hessian, CollocationIntegrator> gf(epsilon, euler);\n            THEN(\"the value of the Green's function is\")\n            {\n                double value = result(0);\n                double gf_value = gf.kernelS(source, probe);\n                REQUIRE(value == Approx(gf_value));\n            }\n            AND_THEN(\"the value of the Green's function directional derivative wrt the probe point is\")\n            {\n                double derProbe = result(1);\n                double gf_derProbe = gf.derivativeProbe(probeNormal, source, probe);\n                REQUIRE(derProbe == Approx(gf_derProbe));\n            }\n            AND_THEN(\"the value of the Green's function directional derivative wrt the source point is\")\n            {\n                double derSource = result(2);\n                double gf_derSource = gf.derivativeSource(sourceNormal, source, probe);\n                REQUIRE(derSource == Approx(gf_derSource));\n            }\n            /*\n               AND_THEN(\"the value of the Green's function hessian is\")\n               {\n               double hessian = result(4);\n               double gf_hessian = gf.hessian(sourceNormal, source, probeNormal, probe);\n               REQUIRE(hessian == Approx(gf_hessian));\n               }\n               */\n        }\n    }\n\n    // Define a uniform dielectric as an anisotropic dielectric and test the evaluation of the\n    // Green's function and derivatives against the analytic result for the uniform dielectric\n    GIVEN(\"A liquid with an isotropic permittivity tensor\")\n    {\n        Eigen::Vector3d epsilon = (Eigen::Vector3d() << 80.0, 80.0, 80.0).finished();\n        Eigen::Vector3d euler   = (Eigen::Vector3d() << 0.0, 0.0, 0.0).finished();\n        Eigen::Vector3d source = Eigen::Vector3d::Random();\n        Eigen::Vector3d sourceNormal = source + Eigen::Vector3d::Random();\n        sourceNormal.normalize();\n        Eigen::Vector3d probe = Eigen::Vector3d::Random();\n        Eigen::Vector3d probeNormal = probe + Eigen::Vector3d::Random();\n        probeNormal.normalize();\n        Eigen::Array4d result = analyticUniformDielectric(epsilon(0), sourceNormal, source, probeNormal, probe);\n\n        /*! \\class AnisotropicLiquid\n         *  \\test \\b AnisotropicLiquidUniformTest_numerical tests the numerical evaluation of the AnisotropicLiquid Green's function against analytical result for a uniform dielectric\n         */\n        WHEN(\"the derivatives are evaluated numerically\")\n        {\n            AnisotropicLiquid<Numerical, CollocationIntegrator> gf(epsilon, euler);\n            THEN(\"the value of the Green's function is\")\n            {\n                double value = result(0);\n                double gf_value = gf.kernelS(source, probe);\n                REQUIRE(value == Approx(gf_value));\n            }\n            AND_THEN(\"the value of the Green's function directional derivative wrt the probe point is\")\n            {\n                double derProbe = result(1);\n                double gf_derProbe = gf.derivativeProbe(probeNormal, source, probe);\n                REQUIRE(derProbe == Approx(gf_derProbe));\n            }\n            AND_THEN(\"the value of the Green's function directional derivative wrt the source point is\")\n            {\n                double derSource = result(2);\n                double gf_derSource = gf.derivativeSource(sourceNormal, source, probe);\n                REQUIRE(derSource == Approx(gf_derSource));\n            }\n        }\n\n        /*! \\class AnisotropicLiquid\n         *  \\test \\b AnisotropicLiquidUniformTest_directional_AD tests the automatic evaluation (directional derivative only)\n         *  of the AnisotropicLiquid Green's function against analytical result for a uniform dielectric\n         */\n        WHEN(\"the derivatives are evaluated via AD\")\n        {\n            AnisotropicLiquid<AD_directional, CollocationIntegrator> gf(epsilon, euler);\n            THEN(\"the value of the Green's function is\")\n            {\n                double value = result(0);\n                double gf_value = gf.kernelS(source, probe);\n                REQUIRE(value == Approx(gf_value));\n            }\n            AND_THEN(\"the value of the Green's function directional derivative wrt the probe point is\")\n            {\n                double derProbe = result(1);\n                double gf_derProbe = gf.derivativeProbe(probeNormal, source, probe);\n                REQUIRE(derProbe == Approx(gf_derProbe));\n            }\n            AND_THEN(\"the value of the Green's function directional derivative wrt the source point is\")\n            {\n                double derSource = result(2);\n                double gf_derSource = gf.derivativeSource(sourceNormal, source, probe);\n                REQUIRE(derSource == Approx(gf_derSource));\n            }\n        }\n\n        /*! \\class AnisotropicLiquid\n         *  \\test \\b AnisotropicLiquidUniformTest_gradient_AD tests the automatic evaluation (full gradient)\n         *  of the AnisotropicLiquid Green's function against analytical result for a uniform dielectric\n         */\n        WHEN(\"the derivatives are evaluated via AD using the full gradient\")\n        {\n            AnisotropicLiquid<AD_gradient, CollocationIntegrator> gf(epsilon, euler);\n            THEN(\"the value of the Green's function is\")\n            {\n                double value = result(0);\n                double gf_value = gf.kernelS(source, probe);\n                REQUIRE(value == Approx(gf_value));\n            }\n            AND_THEN(\"the value of the Green's function directional derivative wrt the probe point is\")\n            {\n                double derProbe = result(1);\n                double gf_derProbe = gf.derivativeProbe(probeNormal, source, probe);\n                REQUIRE(derProbe == Approx(gf_derProbe));\n            }\n            AND_THEN(\"the value of the Green's function directional derivative wrt the source point is\")\n            {\n                double derSource = result(2);\n                double gf_derSource = gf.derivativeSource(sourceNormal, source, probe);\n                REQUIRE(derSource == Approx(gf_derSource));\n            }\n        }\n\n        /*! \\class AnisotropicLiquid\n         *  \\test \\b AnisotropicLiquidUniformTest_hessian_AD tests the automatic evaluation (full hessian)\n         *  of the AnisotropicLiquid Green's function against analytical result for a uniform dielectric\n         */\n        WHEN(\"the derivatives are evaluated via AD using the full hessian\")\n        {\n            AnisotropicLiquid<AD_hessian, CollocationIntegrator> gf(epsilon, euler);\n            THEN(\"the value of the Green's function is\")\n            {\n                double value = result(0);\n                double gf_value = gf.kernelS(source, probe);\n                REQUIRE(value == Approx(gf_value));\n            }\n            AND_THEN(\"the value of the Green's function directional derivative wrt the probe point is\")\n            {\n                double derProbe = result(1);\n                double gf_derProbe = gf.derivativeProbe(probeNormal, source, probe);\n                REQUIRE(derProbe == Approx(gf_derProbe));\n            }\n            AND_THEN(\"the value of the Green's function directional derivative wrt the source point is\")\n            {\n                double derSource = result(2);\n                double gf_derSource = gf.derivativeSource(sourceNormal, source, probe);\n                REQUIRE(derSource == Approx(gf_derSource));\n            }\n            /*\n               AND_THEN(\"the value of the Green's function hessian is\")\n               {\n               double hessian = result(4);\n               double gf_hessian = gf.hessian(sourceNormal, source, probeNormal, probe);\n               REQUIRE(hessian == Approx(gf_hessian));\n               }\n               */\n        }\n    }\n}\n", "meta": {"hexsha": "68bd2620858c432292314c27ce91b264bae4c8c0", "size": 14098, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "external/PCMSolver/PCMSolver-source/tests/green/green_anisotropic_liquid.cpp", "max_stars_repo_name": "robertodr/externalize", "max_stars_repo_head_hexsha": "c7b1dda2009dab329a6efb580c57ef8e1494cf3b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-02-15T22:16:34.000Z", "max_stars_repo_stars_event_max_datetime": "2017-02-15T22:16:34.000Z", "max_issues_repo_path": "external/PCMSolver/PCMSolver-source/tests/green/green_anisotropic_liquid.cpp", "max_issues_repo_name": "robertodr/externalize", "max_issues_repo_head_hexsha": "c7b1dda2009dab329a6efb580c57ef8e1494cf3b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "external/PCMSolver/PCMSolver-source/tests/green/green_anisotropic_liquid.cpp", "max_forks_repo_name": "robertodr/externalize", "max_forks_repo_head_hexsha": "c7b1dda2009dab329a6efb580c57ef8e1494cf3b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.1505016722, "max_line_length": 183, "alphanum_fraction": 0.6017874876, "num_tokens": 2974, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257126, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4534122776525367}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// statistics::survival::model::meta::model_data.hpp                         //\n//                                                                           //\n//  Copyright 2009 Erwann Rogard. Distributed under the Boost                //\n//  Software License, Version 1.0. (See accompanying file                    //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)         //\n///////////////////////////////////////////////////////////////////////////////\n#ifndef BOOST_STATISTICS_SURVIVAL_MODEL_META_MODEL_DATA_HPP_ER_2009\n#define BOOST_STATISTICS_SURVIVAL_MODEL_META_MODEL_DATA_HPP_ER_2009\n#include <boost/statistics/model/wrap/aggregate/model_data.hpp>\n#include <boost/statistics/survival/data/data/event.hpp>\n\nnamespace boost{\nnamespace statistics{\nnamespace survival{\nnamespace model{\nnamespace meta{        \n\n    // See statistics/model/libs/doc/readme\n    template<typename T,typename M,typename X>\n    struct model_data{\n        typedef boost::statistics::survival::data::event<T> y_;\n        typedef boost::statistics::model::model_data_< M, X, y_ > type;\n    };\n    \n}// meta\n}// model    \n}// survival\n}// statistics\n}// boost\n\n#endif", "meta": {"hexsha": "dc8b29dbb0440272519313c19c01451eae41ab9c", "size": 1249, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "survival_model copy/boost/statistics/survival/model/meta/model_data.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": "survival_model copy/boost/statistics/survival/model/meta/model_data.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": "survival_model copy/boost/statistics/survival/model/meta/model_data.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": 39.03125, "max_line_length": 79, "alphanum_fraction": 0.5572457966, "num_tokens": 240, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4534078779401391}}
{"text": "\n#include <cstdio>\n#include <iomanip>\n#include <iostream>\n#include <limits>\n#include <stdexcept>\n\n#include <Eigen/Dense>\n\n#include <spii/spii.h>\n#include <spii/solver.h>\n\n#include \"sgdsolver.hpp\"\n\nnamespace spii {\n\nvoid SGDSolver::solve(const Function& function, SolverResults* results) const {\n  // Get the dimensionality of the problem.\n  size_t dimension = function.get_number_of_scalars();\n  std::cout << \"Dimension is \" << dimension << std::endl;\n\n  if (dimension == 0) {\n    results->exit_condition = SolverResults::FUNCTION_TOLERANCE;\n    return;\n  }\n\n  Eigen::VectorXd current_point, gradient;\n  Eigen::VectorXd next_point, next_point_gradient;\n\n  function.copy_user_to_global(&current_point);\n  Eigen::VectorXd stepdirection(dimension);\n\n  results->exit_condition = SolverResults::INTERNAL_ERROR;\n  int iteration = 0;\n\n  double function_value = std::numeric_limits<double>::quiet_NaN();\n  double gradient_norm = std::numeric_limits<double>::quiet_NaN();\n\n  double previous_function_value = 0;\n  double gain = 1.0;\n\n  double exponentially_weighed_average_gain = gain;\n\n  while (iteration < 500) {\n    function_value = function.evaluate(current_point, &gradient);\n    gradient_norm = std::max(gradient.maxCoeff(), -gradient.minCoeff());\n    stepdirection = -gradient;\n\n    gain = previous_function_value - function_value;\n\n    printf(\"[%d:] Loss is %+.17e, norm is %+.17e, gain is %+.17e\\n\",\n      iteration, function_value, gradient_norm, gain);\n\n    double stepsize = (1.0 / gradient_norm) * (1.0/(iteration+1));\n\n    // Evaluate the function at the next point and see if we are making\n    // progress.\n    double next_function_value;\n    while (stepsize > 1.0e-10) {\n      next_point = current_point + (10*stepsize) * stepdirection;\n      next_function_value = function.evaluate(next_point,\n        &next_point_gradient);\n      // In order to make progress, the next_function_value needs to be smaller\n      // than the current_function_value, so the gain needs to be positive.\n      gain = function_value - next_function_value;\n      if ((gain <= 0) || std::isnan(gain)) {\n        printf(\"[%d:] gain is %+.17e, reducing stepsize * norm from %+.17e\\n\", \n          iteration, gain, stepsize * gradient_norm);\n        stepsize = stepsize / 100.0;\n      } else {\n        printf(\"[%d:] gain is %+.17e reducing loss to %+.17e\\n\", iteration,\n          gain, next_function_value);\n        current_point = next_point;\n        gradient = next_point_gradient;\n        break;\n      }\n    }\n\n    if (stepsize <= 1.0e-100) {\n      exponentially_weighed_average_gain = gain + (0.001 *\n        exponentially_weighed_average_gain);\n    } else {\n      exponentially_weighed_average_gain = gain +\n        (0.5 * exponentially_weighed_average_gain);\n    }\n\n    printf(\"[%d:] Exponentially weighed avg gain: %+.17e\\n\", iteration,\n      exponentially_weighed_average_gain);\n\n    if (exponentially_weighed_average_gain < 1.0e-20) {\n      printf(\"[%d:] Exponentially weighed avg gain too small, aborting\\n\", iteration);\n      if (exponentially_weighed_average_gain < 0.0) {\n        printf(\"[%d:] Can't be negative, exiting.\\n\", iteration);\n        exit(-1);\n      }\n      break;\n    }\n\n    if (function_value < 1.0) {\n      printf(\"[%d:] Loss less than 1, aborting\\n\", iteration);\n      break;\n    }\n    ++iteration;\n    previous_function_value = function_value;\n  }\n\n  function.copy_global_to_user(current_point);\n}\n\n\n} // namespace spii\n\n", "meta": {"hexsha": "56eae9db340a61aadaa3548c2dedc1d5542cc6ab", "size": 3427, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "learning/sgdsolver.cpp", "max_stars_repo_name": "johannespitz/functionsimsearch", "max_stars_repo_head_hexsha": "0ca99527b413209240dc1eda4727a6fae4353848", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 353.0, "max_stars_repo_stars_event_min_datetime": "2018-09-11T22:56:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T02:12:09.000Z", "max_issues_repo_path": "learning/sgdsolver.cpp", "max_issues_repo_name": "johannespitz/functionsimsearch", "max_issues_repo_head_hexsha": "0ca99527b413209240dc1eda4727a6fae4353848", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 15.0, "max_issues_repo_issues_event_min_datetime": "2018-09-17T21:03:22.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-10T07:39:46.000Z", "max_forks_repo_path": "learning/sgdsolver.cpp", "max_forks_repo_name": "johannespitz/functionsimsearch", "max_forks_repo_head_hexsha": "0ca99527b413209240dc1eda4727a6fae4353848", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 62.0, "max_forks_repo_forks_event_min_datetime": "2018-09-11T17:02:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-27T19:46:51.000Z", "avg_line_length": 30.3274336283, "max_line_length": 86, "alphanum_fraction": 0.6711409396, "num_tokens": 852, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4534078779401391}}
{"text": "#include <fstream>\n#include <iostream>\n#include <vector>\n#include <Eigen/Dense>\n#include <cassert>\n#include <algorithm>\n#include <cmath>\n#include <iterator>\n#include \"sobol.h\"\n#include \"Transformable.h\"\n#include \"RunManagerAbstract.h\"\n#include \"ParamTransformSeq.h\"\n#include \"ModelRunPP.h\"\n#include \"Stats.h\"\n#include \"FileManager.h\"\n\nusing namespace std;\nusing namespace Eigen;\n\n\nSobol::Sobol(Pest &_pest_scenario,\n\tFileManager &_file_manager, ObjectiveFunc *_obj_func_ptr,\n\tconst ParamTransformSeq &_par_transform,\n\tint _n_sample, PARAM_DIST _par_dist, unsigned int _seed)\n\t: GsaAbstractBase(_pest_scenario, _file_manager, _obj_func_ptr, _par_transform,\n\t\t_par_dist, _seed), n_sample(_n_sample)\n\t{\n\t}\n\nVectorXd Sobol::gen_rand_vec(long nsample, double min, double max)\n{\n\tVectorXd v(nsample);\n\tlong v_len = v.size();\n\n\n\tif (par_dist == PARAM_DIST::normal)\n\t{\n\t\tstd::normal_distribution<> distribution((max + min) / 2.0, (max - min) / 4.0);\n\t\tfor (long i = 0; i < v_len; ++i)\n\t\t{\n\t\t\tv[i] = distribution(rand_engine);\n\t\t\twhile (v[i] < min || v[i] > max) v[i] = distribution(rand_engine);\n\t\t}\n\t}\n\telse\n\t{\n\t\tstd::uniform_real_distribution<double> distribution(min, max);\n\t\tfor (long i = 0; i < v_len; ++i)\n\t\t{\n\t\t\tv[i] = distribution(rand_engine);\n\t\t}\n\t}\n\treturn v;\n}\n\nvoid Sobol::gen_m1_m2()\n{\n\tlong npar = adj_par_name_vec.size();\n\t//generate random matrices\n\tdouble par_min;\n\tdouble par_max;\n\tVectorXd v1;\n\tVectorXd v2;\n\tm1 = MatrixXd::Zero(n_sample, npar);\n\tm2 = MatrixXd::Zero(n_sample, npar);\n\tfor (int i=0; i<npar; ++i)\n\t{\n\t\tstring &p_name = adj_par_name_vec[i];\n\t\tpar_min = min_numeric_pars[p_name];\n\t\tpar_max = max_numeric_pars[p_name];\n\t\tv1 = gen_rand_vec(n_sample, par_min, par_max);\n\t\tv2 = gen_rand_vec(n_sample, par_min, par_max);\n\t\tm1.col(i) = v1;\n\t\tm2.col(i) = v2;\n\t}\n}\n\nMatrixXd Sobol::gen_N_matrix(const MatrixXd &m1, const MatrixXd &m2, const vector<int> &idx_vec)\n{\n  MatrixXd n = m2;\n  for (int i : idx_vec)\n  {\n\tn.col(i) = m1.col(i);\n  }\n  return n;\n}\n\nvoid Sobol::add_model_runs(RunManagerAbstract &run_manager, const MatrixXd &n)\n{\n\tfor (int i=0; i<n_sample; ++i)\n\t{\n\t\tVectorXd tmp_vec =  n.row(i);\n\t\tParameters tmp_pars(adj_par_name_vec, tmp_vec);\n\t\tbase_partran_seq_ptr->numeric2model_ip(tmp_pars);\n\t\trun_manager.add_run(tmp_pars);\n\t}\n}\n\nvoid Sobol::assemble_runs(RunManagerAbstract &run_manager)\n{\n\tMatrixXd c;\n\trun_manager.reinitialize();\n\tgen_m1_m2();\n\n\t//calculate a0\n\tint n_adj_par = adj_par_name_vec.size();\n\n\tadd_model_runs(run_manager, m1);\n\tadd_model_runs(run_manager, m2);\n\n\t//cout << m1 << endl << endl;\n\t//cout << m2 << endl << endl;\n\t//calculate first order runs a1,....an\n\tvector<int> idx_vec;\n\tfor (int ai=0; ai<n_adj_par; ++ai)\n\t{\n\t\tidx_vec.clear();\n\n\t\tidx_vec.push_back(ai);\n\t\tc = gen_N_matrix(m1, m2, idx_vec);\n\t\t//cout << c << endl << endl;\n\t\tadd_model_runs(run_manager, c);\n\t}\n}\n\n\nvector<double> Sobol::get_obs_vec(RunManagerAbstract &run_manager, int run_set, ModelRun &model_run, const string &obs_name)\n{\n\tModelRun run0 = model_run;\n\n\tint run_b = run_set * n_sample;\n\tint run_e = run_b + n_sample;\n\n\tParameters pars0;\n\tObservations obs0;\n\tint nrun = 0;\n\tvector<double> obs_vec = vector<double>(n_sample, MISSING_DATA);\n\tfor (int run_id = run_b; run_id<run_e; ++run_id)\n\t{\n\t\tdouble obs = MISSING_DATA;\n\t\tbool success = run_manager.get_run(run_id, pars0, obs0);\n\t\tif (success)\n\t\t{\n\t\t\trun0.update_ctl(pars0, obs0);\n\t\t\tobs = obs0.get_rec(obs_name);\n\t\t\tif (obs == Observations::no_data) obs = MISSING_DATA;\n\t\t}\n\t\tobs_vec[nrun] = obs;\n\t\tnrun++;\n\t}\n\treturn obs_vec;\n}\n\n\nvector<double> Sobol::get_phi_vec(RunManagerAbstract &run_manager, int run_set, ModelRun &model_run)\n{\n\tModelRun run0 = model_run;\n\n\tint run_b = run_set * n_sample;\n\tint run_e = run_b + n_sample;\n\n\tParameters pars0;\n\tObservations obs0;\n\tint nrun = 0;\n\tvector<double> phi_vec = vector<double>(n_sample, MISSING_DATA);\n\tfor(int run_id=run_b; run_id<run_e; ++run_id)\n\t{\n\t\tdouble phi = MISSING_DATA;\n\t\tbool success = run_manager.get_run(run_id, pars0, obs0);\n\t\tif (success)\n\t\t{\n\t\t\trun0.update_ctl(pars0, obs0);\n\t\t\tphi = run0.get_phi(0.0);\n\t\t}\n\t\tphi_vec[nrun] = phi;\n\t\tnrun++;\n\t}\n\treturn phi_vec;\n}\n\nvoid Sobol::calc_sen(RunManagerAbstract &run_manager, ModelRun model_run)\n{\n\tofstream &fout_sbl = file_manager_ptr->open_ofile_ext(\"sbl\");\n\tfout_sbl << \"Sobol Sensitivity for PHI\" << endl;\n\tcalc_sen_single(run_manager, model_run, fout_sbl, string());\n\n\tvector<string> obs_names = run_manager.get_obs_name_vec();\n\tfor (const string &iobs : obs_names)\n\t{\n\t\tfout_sbl << endl << endl;\n\t\tfout_sbl << \"Sobol Sensitivity for observation \\\"\" << iobs <<\"\\\"\" << endl;\n\t\tcalc_sen_single(run_manager, model_run, fout_sbl, iobs);\n\t}\n\n\tfile_manager_ptr->close_file(\"sbl\");\n}\n\n\nvoid Sobol::calc_sen_single(RunManagerAbstract &run_manager, ModelRun model_run, ofstream &fout_sbl, const string &obs_name)\n{\n\tvector<double> ya;\n\tvector<double> yb;\n\tif (obs_name.empty())\n\t{\n\t\tya = get_phi_vec(run_manager, 0, model_run);\n\t\tyb = get_phi_vec(run_manager, 1, model_run);\n\t}\n\telse\n\t{\n\t\tya = get_obs_vec(run_manager, 0, model_run, obs_name);\n\t\tyb = get_obs_vec(run_manager, 1, model_run, obs_name);\n\t}\n\n\tvector<double> ya_yb_prod = vec_array_prod(ya, yb, MISSING_DATA);\n\tvector<double> y_ab;\n\ty_ab.reserve(ya.size() + yb.size()); // preallocate memory\n\ty_ab.insert(y_ab.end(), ya.begin(), ya.end());\n\ty_ab.insert(y_ab.end(), yb.begin(), yb.end());\n\n\t//Compute Mean for the S_i's\n\tdouble mean_sq_si = vec_mean_missing_data(ya_yb_prod, MISSING_DATA);\n\t// Compute Var for S_i's\n\tpair<double, size_t> data = sum_of_prod_missing_data(y_ab, y_ab, MISSING_DATA);\n\tdouble var_si = data.first / (data.second - 2.0) - mean_sq_si;\n\n\t//Compute Mean for the S_ti's\n\tdouble mean_sq_sti = pow(vec_mean_missing_data(y_ab, MISSING_DATA), 2.0);\n\t// Compute Var for S_ti's\n\tdouble sti_u = sobol_u_missing_data(yb, yb, MISSING_DATA);\n\tdouble var_sti = sti_u - mean_sq_sti;\n\tfout_sbl << \"E(Y) = \" << sqrt(mean_sq_si) << \";  Var(Y) = \" << var_si << \" (for S_i calculations)\" << endl;\n\tfout_sbl << \"E(Y) = \" << sqrt(mean_sq_sti) << \";  Var(Y) = \" << var_sti << \" (for S_ti calculations)\" << endl;\n\tsize_t npar = adj_par_name_vec.size();\n\n\tfout_sbl << \"parameter_name, s_i, st_i, n_runs\" << endl;\n\tfor (size_t i=0; i<npar; ++i)\n\t{\n\t\tvector<double> yci;\n\t\tif (obs_name.empty())\n\t\t{\n\t\t\tyci = get_phi_vec(run_manager, i + 2, model_run);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tyci = get_obs_vec(run_manager, i + 2, model_run, obs_name);\n\t\t}\n\n\t\tpair<double, int> sumprod_num = sum_of_prod_missing_data(ya, yci, MISSING_DATA);\n\t\tlong int n_runs = sumprod_num.second;\n\t\tdouble sobol_uj = sumprod_num.first / (sumprod_num.second - 1.0);\n\t\tdouble si = (sobol_uj - mean_sq_si) / var_si;\n\n\t\tdouble sobol_umj = sobol_u_missing_data(yb, yci, MISSING_DATA);\n\t\tdouble sti = 1 - (sobol_umj - mean_sq_sti) / var_sti;\n\n\t\tfout_sbl << adj_par_name_vec[i] << \", \" << si << \", \" << sti << \", \" << n_runs << endl;\n\t}\n}\n", "meta": {"hexsha": "4fa3bf92353720bd94d63aea685c5d3d480295c9", "size": 6831, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/src_pestpp/programs/gsa/sobol.cpp", "max_stars_repo_name": "jtwhite79/worked_example", "max_stars_repo_head_hexsha": "cae16f633073f82fa09c45ed37a080a902c59097", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-23T20:47:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-23T20:47:29.000Z", "max_issues_repo_path": "src/src_pestpp/programs/gsa/sobol.cpp", "max_issues_repo_name": "jtwhite79/worked_example", "max_issues_repo_head_hexsha": "cae16f633073f82fa09c45ed37a080a902c59097", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/src_pestpp/programs/gsa/sobol.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": 26.3745173745, "max_line_length": 124, "alphanum_fraction": 0.6927243449, "num_tokens": 2143, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.45340787794013904}}
{"text": "#include <iostream>\n#include <fstream>\n#include <vector>\n#include <string>\n#include <map>\n#include <tuple>\n\n#include <boost/algorithm/string.hpp>\n#include <boost/lexical_cast.hpp>\n\n#include \"Day8.hpp\"\n\nvoid day8() {\n\tstd::ifstream inputFile(\"Day8.txt\");\n\tstd::string line;\n\tstd::getline(inputFile, line);\n\n\tstd::vector<int> numbers;\n\t\n\tconst int WIDTH = 25;\n\tconst int HEIGHT = 6;\n\tconst int LAYERS_COUNT = 100;\n\n\tint x = 0;\n\tint y = 0;\n\tint layer = 0;\n\n\tstd::vector<std::vector<std::vector<int>>> layers(LAYERS_COUNT);\n\tlayers[0] = std::vector<std::vector<int>>(HEIGHT);\n\tlayers[0][0] = std::vector<int>(WIDTH);\n\n\tfor (int i = 0; i < line.size(); ++i) {\n\t\tint currentNumber = std::stoi(line.substr(i, 1));\n\t\tlayers[layer][y][x] = currentNumber;\n\t\tx++;\n\t\tif (i == 14999) {\n\t\t\tbreak;\n\t\t}\n\t\tif (x % WIDTH == 0) {\n\t\t\tx = 0;\n\t\t\ty++;\n\t\t\tif (y % HEIGHT == 0) {\n\t\t\t\ty = 0;\n\t\t\t\tlayer++;\n\t\t\t\tlayers[layer] = std::vector<std::vector<int>>(HEIGHT);\n\t\t\t}\n\t\t\tlayers[layer][y] = std::vector<int>(WIDTH);\n\t\t}\n\t}\n\n\tstd::map<int, int> count0;\n\tstd::map<int, int> count1;\n\tstd::map<int, int> count2;\n\n\tint layerWithFewer0 = -1;\n\tint minNumber0 = WIDTH * HEIGHT;\n\n\tint i = 0;\n\tint lol = 0;\n\tfor (auto itLayer = layers.begin(); itLayer != layers.end(); ++itLayer) {\n\t\tcount0[i] = 0;\n\t\tcount1[i] = 0;\n\t\tcount2[i] = 0;\n\n\t\tfor (auto itHeight = itLayer->begin(); itHeight != itLayer->end(); ++itHeight) {\n\t\t\tfor (auto itWidth = itHeight->begin(); itWidth != itHeight->end(); ++itWidth) {\n\t\t\t\tlol++;\n\t\t\t\tswitch (*itWidth)\n\t\t\t\t{\n\t\t\t\tcase 0:\n\t\t\t\t\tcount0[i]++;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 1:\n\t\t\t\t\tcount1[i]++;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\tcount2[i]++;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (count0[i] < minNumber0) {\n\t\t\tminNumber0 = count0[i];\n\t\t\tlayerWithFewer0 = i;\n\t\t}\n\n\t\t//std::cout << \"Layer \" << i << \" 0: \" << count0[i] << \" 1: \" << count1[i] << \" 2: \" << count2[i] << std::endl;\n\n\t\ti++;\n\t}\n\n\t//std::cout << \"Layer with Min 0: \" << layerWithFewer0 << \"(\" << minNumber0 << \") - Mult: \" << (count1[layerWithFewer0] * count2[layerWithFewer0]) << std::endl;\n\n\t//for (auto i = numbers.begin(); i != numbers.end(); ++i)\n\t//\tstd::cout << *i << ' ';\n\t\n\tstd::vector<std::vector<int>> finalMessage = std::vector<std::vector<int>>(HEIGHT);\n\tfor (int y = 0; y < HEIGHT; ++y) {\n\t\tfinalMessage[y] = std::vector<int>(WIDTH);\n\t}\n\n\tstd::cout << std::endl << std::endl;\n\tfor (int y = 0; y < HEIGHT; ++y) {\n\t\tfor (int x = 0; x < WIDTH; ++x) {\n\t\t\tint layer = 0;\n\t\t\twhile (layers[layer][y][x] == 2) {\n\t\t\t\tlayer++;\n\t\t\t}\n\t\t\tint value = layers[layer][y][x];\n\t\t\tfinalMessage[y][x] = value;\n\t\t\tstd::cout << (value == 1 ? \"x\" : \" \");\n\t\t}\n\t\tstd::cout << std::endl;\n\t}\n}", "meta": {"hexsha": "577e174dd49699deb7efb53fe324303406e689c1", "size": 2608, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AdventOfCode2019/Day8.cpp", "max_stars_repo_name": "Epono/AdventOfCode2019", "max_stars_repo_head_hexsha": "d035b8943a7e9b96491ed7a499e98101c08256c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AdventOfCode2019/Day8.cpp", "max_issues_repo_name": "Epono/AdventOfCode2019", "max_issues_repo_head_hexsha": "d035b8943a7e9b96491ed7a499e98101c08256c1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AdventOfCode2019/Day8.cpp", "max_forks_repo_name": "Epono/AdventOfCode2019", "max_forks_repo_head_hexsha": "d035b8943a7e9b96491ed7a499e98101c08256c1", "max_forks_repo_licenses": ["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.4827586207, "max_line_length": 161, "alphanum_fraction": 0.5571319018, "num_tokens": 886, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4534011925015351}}
{"text": "#include <vector>\n#include <memory>\n#include <Eigen/Core>\n#include <sequential-line-search/sequential-line-search.h>\n\n///////////////////////////////////////////////////////////////////////////////\n// C API\n///////////////////////////////////////////////////////////////////////////////\n\nvoid init(unsigned);\nvoid proceedOptimization(double);\nstd::vector<double> getParametersFromSlider(double);\nstd::vector<double> getXmax();\n\n///////////////////////////////////////////////////////////////////////////////\n// unnamed namespace for sealing\n///////////////////////////////////////////////////////////////////////////////\n\nusing namespace sequential_line_search;\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\n\nnamespace\n{\n\n    std::shared_ptr<sequential_line_search::PreferenceRegressor> regressor;\n    std::shared_ptr<sequential_line_search::Slider> slider;\n\n    sequential_line_search::Data data;\n\n    unsigned        dimension;\n    Eigen::VectorXd x_max;\n    double          y_max;\n\n    void clear()\n    {\n        regressor = nullptr;\n        slider    = nullptr;\n\n        data.X = MatrixXd::Zero(0, 0);\n        data.D.clear();\n        x_max  = VectorXd::Zero(0);\n        y_max  = NAN;\n    }\n\n    std::vector<double> convertToSTL(const Eigen::VectorXd& vec_x_Eigen)\n    {\n        std::vector<double> vec_x_STL(vec_x_Eigen.rows());\n        for (int i = 0; i < vec_x_Eigen.rows(); ++ i)\n        {\n            vec_x_STL[i] = vec_x_Eigen(i);\n        }\n        return vec_x_STL;\n    }\n\n    void computeRegression()\n    {\n        regressor = std::make_shared<PreferenceRegressor>(data.X, data.D);\n    }\n\n    void updateSliderEnds()\n    {\n        // If this is the first time...\n        if (x_max.rows() == 0)\n        {\n            slider = std::make_shared<Slider>(utils::generateRandomVector(dimension), utils::generateRandomVector(dimension), true);\n            return;\n        }\n\n        const VectorXd x_1 = regressor->find_arg_max();\n        const VectorXd x_2 = acquisition_function::FindNextPoint(*regressor);\n\n        slider = std::make_shared<Slider>(x_1, x_2, true);\n    }\n\n    const VectorXd computeParametersFromSlider(double value)\n    {\n        return slider->end_0 * (1.0 - value) + slider->end_1 *  value;\n    }\n\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// C API\n///////////////////////////////////////////////////////////////////////////////\n\nvoid init(unsigned _dimension)\n{\n    dimension = _dimension;\n    clear();\n    computeRegression();\n    updateSliderEnds();\n}\n\nvoid proceedOptimization(double slider_position)\n{\n    // Add new preference data\n    const VectorXd x = computeParametersFromSlider(slider_position);\n    data.AddNewPoints(x, { slider->orig_0, slider->orig_1 });\n\n    // Compute regression\n    computeRegression();\n\n    // Check the current best\n    unsigned index;\n    y_max = regressor->y.maxCoeff(&index);\n    x_max = regressor->X.col(index);\n\n    // Update slider ends\n    updateSliderEnds();\n}\n\nstd::vector<double> getParametersFromSlider(double value)\n{\n    return convertToSTL(slider->end_0 * (1.0 - value) + slider->end_1 * value);\n}\n\nstd::vector<double> getXmax()\n{\n    return convertToSTL(x_max);\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// pybind11\n///////////////////////////////////////////////////////////////////////////////\n\n#include <pybind11/pybind11.h>\n#include <pybind11/stl.h>\nnamespace py = pybind11;\n\nPYBIND11_MODULE(pySequentialLineSearch, m) {\n    m.doc() = R\"pbdoc(\n    Sequential Line Search Plugin by Pybind11\n    -----------------------------------------\n\n    .. currentmodule:: SequentialLineSearch\n\n    .. autosummary::\n    :toctree: _generate\n    init\n    proceedOptimization\n    getParametersFromSlider\n    getXmax\n    )pbdoc\";\n\n    m.def(\"init\", &init, R\"pbdoc(\n          (Re)initializes this module.\n          arg0: parameter dimension (int)\n          )pbdoc\");\n\n    m.def(\"proceedOptimization\", &proceedOptimization, R\"pbdoc(\n          Proceeds the optimization step by feeding the slider value.\n          arg0: slider position (double)\n          )pbdoc\");\n\n    m.def(\"getParametersFromSlider\", &getParametersFromSlider, R\"pbdoc(\n          Gets the parameters as list, in the specific slider position.\n          arg0: slider position (double)\n          )pbdoc\");\n\n    m.def(\"getXmax\", &getXmax, R\"pbdoc(\n          Gets the current best parameters as a list.\n          )pbdoc\");\n\n#ifdef VERSION_INFO\n    m.attr(\"__version__\") = VERSION_INFO;\n#else\n    m.attr(\"__version__\") = \"dev\";\n#endif\n}\n", "meta": {"hexsha": "4ecccd3f450e0041c5d11729a1d1cdf09cb4a2d5", "size": 4543, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "python/pySequentialLineSearch.cpp", "max_stars_repo_name": "stnoh/sequential-line-search", "max_stars_repo_head_hexsha": "3d40aa23facf6f23e6ed8835c928dd229b7a35ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "python/pySequentialLineSearch.cpp", "max_issues_repo_name": "stnoh/sequential-line-search", "max_issues_repo_head_hexsha": "3d40aa23facf6f23e6ed8835c928dd229b7a35ae", "max_issues_repo_licenses": ["MIT"], "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/pySequentialLineSearch.cpp", "max_forks_repo_name": "stnoh/sequential-line-search", "max_forks_repo_head_hexsha": "3d40aa23facf6f23e6ed8835c928dd229b7a35ae", "max_forks_repo_licenses": ["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.567251462, "max_line_length": 132, "alphanum_fraction": 0.5467752586, "num_tokens": 986, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4534011925015351}}
{"text": "/*\n\nCopyright (c) 2005-2018, University of Oxford.\nAll rights reserved.\n\nUniversity of Oxford means the Chancellor, Masters and Scholars of the\nUniversity of Oxford, having an administrative office at Wellington\nSquare, Oxford OX1 2JD, UK.\n\nThis file is part of Chaste.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n * Redistributions of source code must retain the above copyright notice,\n   this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice,\n   this list of conditions and the following disclaimer in the documentation\n   and/or other materials provided with the distribution.\n * Neither the name of the University of Oxford nor the names of its\n   contributors may be used to endorse or promote products derived from this\n   software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\nGOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\nHOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\nLIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\nOF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*/\n\n#ifndef DELTANOTCHODESYSTEM_HPP_\n#define DELTANOTCHODESYSTEM_HPP_\n\n#include \"ChasteSerialization.hpp\"\n#include <boost/serialization/base_object.hpp>\n\n#include <cmath>\n#include <iostream>\n\n#include \"AbstractOdeSystem.hpp\"\n\n/**\n * Represents the Delta-Notch ODE system described by Collier et al,\n * \"Pattern formation by lateral inhibition with feedback: a mathematical\n * model of delta-notch intercellular signalling\" (Journal of Theoretical\n * Biology 183:429-446, 1996).\n */\nclass DeltaNotchOdeSystem : public AbstractOdeSystem\n{\nprivate:\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\n    ///\\todo extract model parameters as member variables\n\npublic:\n\n    /**\n     * Default constructor.\n     *\n     * @param stateVariables optional initial conditions for state variables (only used in archiving)\n     */\n    DeltaNotchOdeSystem(std::vector<double> stateVariables=std::vector<double>());\n\n    /**\n     * Destructor.\n     */\n    ~DeltaNotchOdeSystem();\n\n    /**\n     * Compute the RHS of the  Collier et al. 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  Collier et al. system of equations).\n     */\n    void EvaluateYDerivatives(double time, const std::vector<double>& rY, std::vector<double>& rDY);\n};\n\n// Declare identifier for the serializer\n#include \"SerializationExportWrapper.hpp\"\nCHASTE_CLASS_EXPORT(DeltaNotchOdeSystem)\n\nnamespace boost\n{\nnamespace serialization\n{\n/**\n * Serialize information required to construct a DeltaNotchOdeSystem.\n */\ntemplate<class Archive>\ninline void save_construct_data(\n    Archive & ar, const DeltaNotchOdeSystem * t, const unsigned int file_version)\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 DeltaNotchOdeSystem.\n */\ntemplate<class Archive>\ninline void load_construct_data(\n    Archive & ar, DeltaNotchOdeSystem * t, const unsigned int file_version)\n{\n    std::vector<double> state_variables;\n    ar & state_variables;\n\n    // Invoke inplace constructor to initialise instance\n    ::new(t)DeltaNotchOdeSystem(state_variables);\n}\n}\n} // namespace ...\n\n#endif /*DELTANOTCHODESYSTEM_HPP_*/\n", "meta": {"hexsha": "f346ea8559b3a24c836101d1129cb6e393cf45b8", "size": 4583, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cell_based/src/odes/DeltaNotchOdeSystem.hpp", "max_stars_repo_name": "DGermano8/ChasteDom", "max_stars_repo_head_hexsha": "539a3a811698214c0938489b0cfdffd1abccf667", "max_stars_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cell_based/src/odes/DeltaNotchOdeSystem.hpp", "max_issues_repo_name": "DGermano8/ChasteDom", "max_issues_repo_head_hexsha": "539a3a811698214c0938489b0cfdffd1abccf667", "max_issues_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cell_based/src/odes/DeltaNotchOdeSystem.hpp", "max_forks_repo_name": "DGermano8/ChasteDom", "max_forks_repo_head_hexsha": "539a3a811698214c0938489b0cfdffd1abccf667", "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": 33.9481481481, "max_line_length": 103, "alphanum_fraction": 0.7479816714, "num_tokens": 1003, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4534011925015351}}
{"text": "//\n//  Copyright Toon Knapen, Karl Meerbergen\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#include \"../../blas/test/random.hpp\"\n\n#include <boost/numeric/bindings/begin.hpp>\n#include <boost/numeric/bindings/value_type.hpp>\n#include <boost/numeric/bindings/remove_imaginary.hpp>\n#include <boost/numeric/bindings/ublas/matrix.hpp>\n#include <boost/numeric/bindings/ublas/vector.hpp>\n#include <boost/numeric/bindings/lapack/driver/gees.hpp>\n#include <boost/numeric/bindings/detail/array.hpp>\n#include <boost/numeric/bindings/vector_view.hpp>\n//#include <boost/numeric/bindings/detail/complex_utils.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/type_traits/is_complex.hpp>\n#include <boost/mpl/if.hpp>\n\n#include <iostream>\n#include <limits>\n\n\nnamespace ublas = boost::numeric::ublas;\nnamespace lapack = boost::numeric::bindings::lapack;\nnamespace bindings = boost::numeric::bindings;\n\nstruct apply_real {\n  template< typename MatrixA, typename VectorW, typename MatrixVS,\n        typename Workspace >\n  static inline std::ptrdiff_t gees( const char jobvs, const char sort,\n        external_fp select, MatrixA& a, fortran_int_t& sdim, VectorW& w,\n        MatrixVS& vs, Workspace work ) {\n    return lapack::gees( jobvs, sort, select, a, sdim, w, vs, work );\n    /*\n    fortran_int_t info = lapack::gees( jobvs, sort, select, a, sdim,\n      bindings::detail::real_part_view(w), bindings::detail::imag_part_view(w),\n      vs, work );\n    bindings::detail::interlace(w);\n    return info;\n    */\n  }\n};\n\nstruct apply_complex {\n  template< typename MatrixA, typename VectorW, typename MatrixVS,\n        typename Workspace >\n  static inline std::ptrdiff_t gees( const char jobvs, const char sort,\n        external_fp select, MatrixA& a, fortran_int_t& sdim, VectorW& w,\n        MatrixVS& vs, Workspace work ) {\n    return lapack::gees( jobvs, sort, select, a, sdim, w, vs, work );\n  }\n};\n\n\n// Randomize a matrix\ntemplate <typename M>\nvoid randomize(M& m) {\n   typedef typename M::size_type  size_type ;\n   typedef typename M::value_type value_type ;\n\n   size_type size1 = m.size1() ;\n   size_type size2 = m.size2() ;\n\n   for (size_type i=0; i<size2; ++i) {\n      for (size_type j=0; j<size1; ++j) {\n         m(j,i) = random_value< value_type >() ;\n      }\n   }\n} // randomize()\n\n\ntemplate< typename T >\nstruct dispatch_select\n{\n};\ntemplate<>\nstruct dispatch_select<float>\n{\n  static fortran_bool_t my_select(float* w_real, float* w_imag) {\n    return *w_real > std::abs(*w_imag);\n  }\n};\ntemplate<>\nstruct dispatch_select<double>\n{\n  static fortran_bool_t my_select(double* w_real, double* w_imag) {\n    return *w_real > std::abs(*w_imag);\n  }\n};\ntemplate<>\nstruct dispatch_select<std::complex<float> >\n{\n  static fortran_bool_t my_select(std::complex<float>* w) {\n    return w->real() > std::abs(w->imag());\n  }\n};\ntemplate<>\nstruct dispatch_select<std::complex<double> >\n{\n  static fortran_bool_t my_select(std::complex<double>* w) {\n    return w->real() > std::abs(w->imag());\n  }\n};\n\n\ntemplate <typename T, typename W>\nint do_memory_type(int n, W workspace) {\n   typedef typename boost::mpl::if_<boost::is_complex<T>, apply_complex, apply_real>::type apply_t;\n   typedef typename bindings::remove_imaginary< T>::type real_type ;\n   typedef std::complex< real_type >                                            complex_type ;\n\n   typedef ublas::matrix<T, ublas::column_major> matrix_type ;\n   typedef ublas::vector<complex_type>           vector_type ;\n   double safety_factor (1.5);\n\n   // Set matrix\n   matrix_type a( n, n );\n   matrix_type z( n, n );\n   vector_type e1( n );\n   vector_type e2( n );\n\n   randomize( a );\n   matrix_type a2( a );\n   external_fp select = reinterpret_cast<external_fp>(dispatch_select<T>::my_select);\n   fortran_int_t sdim_info(0);\n   // Compute Schur decomposition.\n   apply_t::gees( 'V', 'S', select, a, sdim_info, e1, z, workspace ) ;\n\n   // Check Schur factorization\n   if (norm_frobenius( prod( a2, z ) - prod( z, a ) )\n           >= safety_factor*10.0* norm_frobenius( a2 ) * std::numeric_limits< real_type >::epsilon() ) return 255 ;\n\n   matrix_type z_dummy( 1, 1 );\n   apply_t::gees( 'N', 'S', select, a2, sdim_info, e2, z_dummy, workspace ) ;\n   if (norm_2( e1 - e2 ) > safety_factor*norm_2( e1 ) * std::numeric_limits< real_type >::epsilon()) return 255 ;\n\n   if (norm_frobenius( a2 - a )\n           >= safety_factor*10.0* norm_frobenius( a2 ) * std::numeric_limits< real_type >::epsilon() ) return 255 ;\n\n\n   return 0 ;\n} // do_value_type()\n\n\ntemplate <typename T>\nstruct Workspace {\n   typedef ublas::vector<T>                         array_type ;\n   typedef ublas::vector< fortran_bool_t >               bool_array_type ;\n   typedef lapack::detail::workspace2< array_type,bool_array_type > type ;\n\n   Workspace(size_t n)\n   : work_( 3*n )\n   , bwork_( n )\n   {}\n\n   type operator() () {\n      return lapack::workspace(work_, bwork_) ;\n   }\n\n   array_type work_ ;\n   bool_array_type bwork_;\n};\n\n\ntemplate <typename T>\nstruct Workspace< std::complex<T> > {\n   typedef ublas::vector<T>                                                 real_array_type ;\n   typedef ublas::vector< std::complex<T> >                                 complex_array_type ;\n   typedef ublas::vector< fortran_bool_t >                                       bool_array_type ;\n   typedef lapack::detail::workspace3< complex_array_type,real_array_type,bool_array_type > type ;\n\n   Workspace(size_t n)\n   : work_( 2*n )\n   , rwork_( n )\n   , bwork_( n )\n   {}\n\n   type operator() () {\n      return lapack::workspace(work_, rwork_, bwork_) ;\n   }\n\n   complex_array_type work_ ;\n   real_array_type    rwork_ ;\n   bool_array_type    bwork_;\n};\n\n\ntemplate <typename T>\nint do_value_type() {\n   const int n = 8 ;\n   \n   if (do_memory_type<T,lapack::optimal_workspace>( n, lapack::optimal_workspace() ) ) return 255 ;\n   if (do_memory_type<T,lapack::minimal_workspace>( n, lapack::minimal_workspace() ) ) return 255 ;\n\n   Workspace<T> work( n );\n   if (do_memory_type<T,typename Workspace<T>::type >( n, work() ) ) return 255 ;\n   return 0;\n} // do_value_type()\n\n\nint main() {\n   // Run tests for different value_types\n   std::cout << \"float\\n\" ;\n   if (do_value_type<float>()) return 255;\n\n   std::cout << \"double\\n\" ;\n   if (do_value_type<double>()) return 255;\n\n   std::cout << \"complex<float>\\n\" ;\n   if (do_value_type< std::complex<float> >()) return 255;\n\n   std::cout << \"complex<double>\\n\" ;\n   if (do_value_type< std::complex<double> >()) return 255;\n\n   std::cout << \"Regression test succeeded\\n\" ;\n   return 0;\n}\n", "meta": {"hexsha": "7022638b00694eca5cef1898b8f67fc078cca3ce", "size": 6647, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "externals/numeric_bindings/libs/numeric/bindings/lapack/test/ublas_gees.cpp", "max_stars_repo_name": "ljktest/siconos", "max_stars_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-08-02T14:21:57.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-05T10:34:45.000Z", "max_issues_repo_path": "externals/numeric_bindings/libs/numeric/bindings/lapack/test/ublas_gees.cpp", "max_issues_repo_name": "ljktest/siconos", "max_issues_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-11-07T21:30:35.000Z", "max_issues_repo_issues_event_max_datetime": "2017-11-08T19:44:18.000Z", "max_forks_repo_path": "externals/numeric_bindings/libs/numeric/bindings/lapack/test/ublas_gees.cpp", "max_forks_repo_name": "ljktest/siconos", "max_forks_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-01-28T21:11:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-28T21:11:52.000Z", "avg_line_length": 29.8071748879, "max_line_length": 115, "alphanum_fraction": 0.6557845645, "num_tokens": 1797, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4534011925015351}}
{"text": "#ifndef UTIL_HPP\n#define UTIL_HPP\n\n#include <fmt/color.h>\n#include <fmt/format.h>\n\n#include <algorithm>\n#include <charconv>\n#include <cmath>\n#include <execution>\n#include <fstream>\n#include <iostream>\n#include <numeric>\n#include <optional>\n#include <ostream>\n#include <set>\n#include <sstream>\n#include <string>\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n\n#include <Eigen/Eigen>\n\ntemplate <typename T>\nstatic std::optional<T> parse_number(const std::string& s)\n{\n    static_assert(std::is_arithmetic_v<T>);\n    T result;\n    if (auto [p, ec] = std::from_chars(s.data(), s.data() + s.size(), result); ec == std::errc()) {\n        return { result };\n    }\n    return {};\n}\n\nstatic std::vector<std::string> split(const std::string& s, char delimiter)\n{\n    std::vector<std::string> tokens;\n    std::string token;\n    std::istringstream tokenStream(s);\n    while (std::getline(tokenStream, token, delimiter)) {\n        tokens.push_back(token);\n    }\n    return tokens;\n}\n\ntemplate <typename T>\nstatic std::vector<T> to_vec(const std::string& s, char delimiter)\n{\n    auto tokens = split(s, delimiter);\n    std::vector<T> vec;\n    for (const auto& t : tokens) {\n        if (auto res = parse_number<T>(t); !res.has_value()) {\n            throw new std::runtime_error(fmt::format(\"Error: cannot parse '{}' as an {}\\n\", t, typeid(T).name()));\n        } else {\n            vec.push_back(res.value());\n        }\n    }\n    return vec;\n}\n\n#endif\n", "meta": {"hexsha": "155369fc73c484edc210d8f484a998356012126b", "size": 1458, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/util.hpp", "max_stars_repo_name": "foolnotion/Advent2019", "max_stars_repo_head_hexsha": "af724dc7b078ed03630163139f837e74a953e68c", "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/util.hpp", "max_issues_repo_name": "foolnotion/Advent2019", "max_issues_repo_head_hexsha": "af724dc7b078ed03630163139f837e74a953e68c", "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/util.hpp", "max_forks_repo_name": "foolnotion/Advent2019", "max_forks_repo_head_hexsha": "af724dc7b078ed03630163139f837e74a953e68c", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.1428571429, "max_line_length": 114, "alphanum_fraction": 0.6364883402, "num_tokens": 361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.4534011890712616}}
{"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 \"xregOpenCLMath.h\"\n\n#include <boost/compute/utility/source.hpp>\n\nconst char* xreg::kOPENCL_MATH_UTILS_SRC = BOOST_COMPUTE_STRINGIZE_SOURCE(\n\nfloat3 xregFloat4HmgToFloat3(const float4 a)\n{\n  return (float3) (a.x, a.y, a.z);\n}\n\nfloat xregFloat1Norm(const float x)\n{\n  return fabs(x);\n}\n\nfloat xregFloat2Norm(const float2 x)\n{\n  return sqrt((x.x * x.x) + (x.y * x.y));\n}\n\nfloat xregFloat3Norm(const float3 x)\n{\n  return sqrt((x.x * x.x) + (x.y * x.y) + (x.z * x.z));\n}\n\nfloat xregFloat4HmgNorm(const float4 x)\n{\n  return sqrt((x.x * x.x) + (x.y * x.y) + (x.z * x.z));\n}\n\nfloat xregFloat4Norm(const float4 x)\n{\n  return sqrt((x.x * x.x) + (x.y * x.y) + (x.z * x.z)  + (x.w * x.w));\n}\n\nfloat xregFloat8Norm(const float8 x)\n{\n  return sqrt((x.s0 * x.s0) + (x.s1 * x.s1) + (x.s2 * x.s2)  + (x.s3 * x.s3) +\n              (x.s4 * x.s4) + (x.s5 * x.s5) + (x.s6 * x.s6)  + (x.s7 * x.s7));\n}\n\nfloat xregFloat16Norm(const float16 x)\n{\n  return sqrt((x.s0 * x.s0) + (x.s1 * x.s1) + (x.s2 * x.s2)  + (x.s3 * x.s3) +\n              (x.s4 * x.s4) + (x.s5 * x.s5) + (x.s6 * x.s6)  + (x.s7 * x.s7) +\n              (x.s8 * x.s8) + (x.s9 * x.s9) + (x.sa * x.sa)  + (x.sb * x.sb) +\n              (x.sc * x.sc) + (x.sd * x.sd) + (x.se * x.se)  + (x.sf * x.sf));\n}\n\nfloat2 xregFloat2Normalize(const float2 x)\n{\n  return x / xregFloat2Norm(x);\n}\n\nfloat3 xregFloat3Normalize(const float3 x)\n{\n  return x / xregFloat3Norm(x);\n}\n\nfloat4 xregFloat4Normalize(const float4 x)\n{\n  return x / xregFloat4Norm(x);\n}\n\nfloat8 xregFloat8Normalize(const float8 x)\n{\n  return x / xregFloat8Norm(x);\n}\n\nfloat16 xregFloat16Normalize(const float16 x)\n{\n  return x / xregFloat16Norm(x);\n}\n\nfloat xregFloat1NormSq(const float x)\n{\n  return x * x;\n}\n\nfloat xregFloat2NormSq(const float2 x)\n{\n  return (x.x * x.x) + (x.y * x.y);\n}\n\nfloat xregFloat3NormSq(const float3 x)\n{\n  return (x.x * x.x) + (x.y * x.y) + (x.z * x.z);\n}\n\nfloat xregFloat4HmgNormSq(const float4 x)\n{\n  return (x.x * x.x) + (x.y * x.y) + (x.z * x.z);\n}\n\nfloat xregFloat4NormSq(const float4 x)\n{\n  return (x.x * x.x) + (x.y * x.y) + (x.z * x.z)  + (x.w * x.w);\n}\n\nfloat xregFloat8NormSq(const float8 x)\n{\n  return (x.s0 * x.s0) + (x.s1 * x.s1) + (x.s2 * x.s2)  + (x.s3 * x.s3) +\n         (x.s4 * x.s4) + (x.s5 * x.s5) + (x.s6 * x.s6)  + (x.s7 * x.s7);\n}\n\nfloat xregFloat16NormSq(const float16 x)\n{\n  return (x.s0 * x.s0) + (x.s1 * x.s1) + (x.s2 * x.s2)  + (x.s3 * x.s3) +\n         (x.s4 * x.s4) + (x.s5 * x.s5) + (x.s6 * x.s6)  + (x.s7 * x.s7) +\n         (x.s8 * x.s8) + (x.s9 * x.s9) + (x.sa * x.sa)  + (x.sb * x.sb) +\n         (x.sc * x.sc) + (x.sd * x.sd) + (x.se * x.se)  + (x.sf * x.sf);\n}\n\nfloat3 xregFrm4x4XformFloat3Pt(const float16 frm, const float3 a)\n{\n  float3 b;\n\n  b.x = (frm.s0 * a.x) + (frm.s1 * a.y) + (frm.s2 * a.z) + frm.s3;\n  b.y = (frm.s4 * a.x) + (frm.s5 * a.y) + (frm.s6 * a.z) + frm.s7;\n  b.z = (frm.s8 * a.x) + (frm.s9 * a.y) + (frm.sa * a.z) + frm.sb;\n\n  return b;\n}\n\nfloat3 xregFrm4x4XformFloat3Vec(const float16 frm, const float3 a)\n{\n  float3 b;\n\n  b.x = (frm.s0 * a.x) + (frm.s1 * a.y) + (frm.s2 * a.z);\n  b.y = (frm.s4 * a.x) + (frm.s5 * a.y) + (frm.s6 * a.z);\n  b.z = (frm.s8 * a.x) + (frm.s9 * a.y) + (frm.sa * a.z);\n\n  return b;\n}\n\nfloat4 xregFrm4x4XformFloat4Pt(const float16 frm, const float4 a)\n{\n  float4 b;\n\n  b.x = (frm.s0 * a.x) + (frm.s1 * a.y) + (frm.s2 * a.z) + frm.s3;\n  b.y = (frm.s4 * a.x) + (frm.s5 * a.y) + (frm.s6 * a.z) + frm.s7;\n  b.z = (frm.s8 * a.x) + (frm.s9 * a.y) + (frm.sa * a.z) + frm.sb;\n  b.w = 1;\n\n  return b;\n}\n\nfloat4 xregFrm4x4XformFloat4Vec(const float16 frm, const float4 a)\n{\n  float4 b;\n\n  b.x = (frm.s0 * a.x) + (frm.s1 * a.y) + (frm.s2 * a.z);\n  b.y = (frm.s4 * a.x) + (frm.s5 * a.y) + (frm.s6 * a.z);\n  b.z = (frm.s8 * a.x) + (frm.s9 * a.y) + (frm.sa * a.z);\n  b.w = 0;\n\n  return b;\n}\n\nfloat16 xregFrm4x4Composition(const float16 f, const float16 g)\n{\n  float16 h;\n\n  h.s0 = (f.s0 * g.s0) + (f.s1 * g.s4) + (f.s2 * g.s8);\n  h.s1 = (f.s0 * g.s1) + (f.s1 * g.s5) + (f.s2 * g.s9);\n  h.s2 = (f.s0 * g.s2) + (f.s1 * g.s6) + (f.s2 * g.sa);\n  h.s3 = f.s3 + (f.s0 * g.s3) + (f.s1 * g.s7) + (f.s2 * g.sb);\n  h.s4 = (f.s4 * g.s0) + (f.s5 * g.s4) + (f.s6 * g.s8);\n  h.s5 = (f.s4 * g.s1) + (f.s5 * g.s5) + (f.s6 * g.s9);\n  h.s6 = (f.s4 * g.s2) + (f.s5 * g.s6) + (f.s6 * g.sa);\n  h.s7 = f.s7 + (f.s4 * g.s3) + (f.s5 * g.s7) + (f.s6 * g.sb);\n  h.s8 = (f.s8 * g.s0) + (f.s9 * g.s4) + (f.sa * g.s8);\n  h.s9 = (f.s8 * g.s1) + (f.s9 * g.s5) + (f.sa * g.s9);\n  h.sa = (f.s8 * g.s2) + (f.s9 * g.s6) + (f.sa * g.sa);\n  h.sb = f.sb + (f.s8 * g.s3) + (f.s9 * g.s7) + (f.sa * g.sb);\n  h.sc = 0;\n  h.sd = 0;\n  h.se = 0;\n  h.sf = 1;\n\n  return h;\n}\n\nfloat16 xregFrm4x4SE3Inv(const float16 h)\n{\n  float16 h_inv;\n \n  // transpose for rotation inverse: R^-1 = R^T\n  \n  // row 1\n  h_inv.s0 = h.s0;\n  h_inv.s1 = h.s4;\n  h_inv.s2 = h.s8;\n  \n  // row 2\n  h_inv.s4 = h.s1;\n  h_inv.s5 = h.s5;\n  h_inv.s6 = h.s9;\n\n  // row 3\n  h_inv.s8 = h.s2;\n  h_inv.s9 = h.s6;\n  h_inv.sa = h.sa;\n\n  // translation inverse: t^-1 = -R^T * t\n  h_inv.s3 = -((h_inv.s0 * h.s3) + (h_inv.s1 * h.s7) + (h_inv.s2 * h.sb));\n  h_inv.s7 = -((h_inv.s4 * h.s3) + (h_inv.s5 * h.s7) + (h_inv.s6 * h.sb));\n  h_inv.sb = -((h_inv.s8 * h.s3) + (h_inv.s9 * h.s7) + (h_inv.sa * h.sb));\n\n  h_inv.sc = 0;\n  h_inv.sd = 0;\n  h_inv.se = 0;\n  h_inv.sf = 1;\n\n  return h_inv;\n}\n\nfloat2 xregFrm3x3XformFloat2Pt(const float16 frm, const float2 a)\n{\n  float2 b;\n\n  b.x = (frm.s0 * a.x) + (frm.s1 * a.y) + frm.s2;\n  b.y = (frm.s3 * a.x) + (frm.s4 * a.y) + frm.s5;\n\n  return b;\n}\n\nfloat2 xregFrm3x3XformFloat2Vec(const float16 frm, const float2 a)\n{\n  float2 b;\n\n  b.x = (frm.s0 * a.x) + (frm.s1 * a.y);\n  b.y = (frm.s3 * a.x) + (frm.s4 * a.y);\n\n  return b;\n}\n\nfloat16 xregFrm3x3Identity()\n{\n  float16 A;\n\n  A.s0 = 1;\n  A.s1 = 0;\n  A.s2 = 0;\n\n  A.s3 = 0;\n  A.s4 = 1;\n  A.s5 = 0;\n\n  A.s6 = 0;\n  A.s7 = 0;\n  A.s8 = 1;\n\n  return A;\n}\n\nfloat16 xregFrm4x4Identity()\n{\n  float16 A;\n\n  A.s0 = 1;\n  A.s1 = 0;\n  A.s2 = 0;\n  A.s3 = 0;\n\n  A.s4 = 0;\n  A.s5 = 1;\n  A.s6 = 0;\n  A.s7 = 0;\n\n  A.s8 = 0;\n  A.s9 = 0;\n  A.sa = 1;\n  A.sb = 0;\n\n  A.sc = 0;\n  A.sd = 0;\n  A.se = 0;\n  A.sf = 1;\n\n  return A;\n}\n\nfloat xregFloat2Inner(const float2 x, const float2 y)\n{\n  return (x.x * y.x) + (x.y * y.y);\n}\n\nfloat xregFloat3Inner(const float3 x, const float3 y)\n{\n  return (x.x * y.x) + (x.y * y.y) + (x.z * y.z);\n}\n\nfloat xregFloat4HmgInner(const float4 x, const float4 y)\n{\n  return (x.x * y.x) + (x.y * y.y) + (x.z * y.z);\n}\n\nfloat xregFloat4Inner(const float4 x, const float4 y)\n{\n  return (x.x * y.x) + (x.y * y.y) + (x.z * y.z) + (x.w * y.w);\n}\n\nfloat xregFloat8Inner(const float8 x, const float8 y)\n{\n  return (x.s0 * y.s0) + (x.s1 * y.s1) + (x.s2 * y.s2) + (x.s3 * y.s3) +\n         (x.s4 * y.s4) + (x.s5 * y.s5) + (x.s6 * y.s6) + (x.s7 * y.s7);\n}\n\nfloat xregFloat16Inner(const float16 x, const float16 y)\n{\n  return (x.s0 * y.s0) + (x.s1 * y.s1) + (x.s2 * y.s2) + (x.s3 * y.s3) +\n         (x.s4 * y.s4) + (x.s5 * y.s5) + (x.s6 * y.s6) + (x.s7 * y.s7) +\n         (x.s8 * y.s8) + (x.s9 * y.s9) + (x.sa * y.sa) + (x.sb * y.sb) +\n         (x.sc * y.sc) + (x.sd * y.sd) + (x.se * y.se) + (x.sf * y.sf);\n}\n\n// Useful for debugging:\n\nvoid xregPrintMat4x4(const float16 x)\n{\n  printf(\"[ %+9.3f , %+9.3f , %+9.3f , %+9.3f ;\\n\"\n         \"  %+9.3f , %+9.3f , %+9.3f , %+9.3f ;\\n\"\n         \"  %+9.3f , %+9.3f , %+9.3f , %+9.3f ;\\n\"\n         \"  %+9.3f , %+9.3f , %+9.3f , %+9.3f ]\\n\",\n         x.s0, x.s1, x.s2, x.s3,\n         x.s4, x.s5, x.s6, x.s7,\n         x.s8, x.s9, x.sa, x.sb,\n         x.sc, x.sd, x.se, x.sf);\n}\n\n);\n", "meta": {"hexsha": "c86a0adcb08ee49a7d324d45649a33ad26552f99", "size": 8645, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/opencl/xregOpenCLMath.cpp", "max_stars_repo_name": "gaocong13/Orthopedic-Robot-Navigation", "max_stars_repo_head_hexsha": "bf36f7de116c1c99b86c9ba50f111c3796336af0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2021-11-16T08:17:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T11:08:55.000Z", "max_issues_repo_path": "lib/opencl/xregOpenCLMath.cpp", "max_issues_repo_name": "gaocong13/Orthopedic-Robot-Navigation", "max_issues_repo_head_hexsha": "bf36f7de116c1c99b86c9ba50f111c3796336af0", "max_issues_repo_licenses": ["MIT"], "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/opencl/xregOpenCLMath.cpp", "max_forks_repo_name": "gaocong13/Orthopedic-Robot-Navigation", "max_forks_repo_head_hexsha": "bf36f7de116c1c99b86c9ba50f111c3796336af0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-11-16T08:17:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-16T08:17:42.000Z", "avg_line_length": 24.1480446927, "max_line_length": 81, "alphanum_fraction": 0.5368421053, "num_tokens": 3692, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4534011856409881}}
{"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_MAX_HPP_INCLUDED\n#define BOOST_SIMD_TOOLBOX_ARITHMETIC_FUNCTIONS_SCALAR_MAX_HPP_INCLUDED\n#include <boost/simd/toolbox/arithmetic/functions/max.hpp>\n#include <boost/simd/include/functions/scalar/is_nan.hpp>\n#include <boost/simd/include/constants/nan.hpp>\n#include <boost/mpl/max.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION ( boost::simd::tag::max_, tag::cpu_\n                                    , (A0)\n                                    , (scalar_< arithmetic_<A0> >)\n                                      (scalar_< arithmetic_<A0> >)\n                                    )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    {\n      return (a0 > a1) ? a0 : a1;\n    }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION ( boost::simd::tag::max_, tag::cpu_\n                                    , (A0)(A1)\n                                    , (mpl_integral_< scalar_< fundamental_<A0> > >)\n                                      (scalar_< arithmetic_<A1> >)\n                                    )\n  {\n    typedef A1 result_type;\n    BOOST_FORCEINLINE result_type operator()(A0 const&, A1 a1) const\n    {\n      return (A0::value > a1) ? A0::value : a1;\n    }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION ( boost::simd::tag::max_, tag::cpu_\n                                    , (A0)(A1)\n                                    , (scalar_< arithmetic_<A0> >)\n                                      (mpl_integral_< scalar_< fundamental_<A1> > >)\n                                    )\n  {\n    typedef A0 result_type;\n    BOOST_FORCEINLINE result_type operator()(A0 a0, A1 const&) const\n    {\n      return (a0 > A1::value) ? a0 : A1::value;\n    }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION ( boost::simd::tag::max_, tag::cpu_\n                                    , (A0)(A1)\n                                    , (mpl_integral_< scalar_< fundamental_<A0> > >)\n                                      (mpl_integral_< scalar_< fundamental_<A1> > >)\n                                    )\n  {\n    typedef typename  boost::mpl::max<A0,A1>::type result_type;\n\n    BOOST_FORCEINLINE result_type operator()(A0 const&, A1 const&) const\n    {\n      return result_type();\n    }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION ( boost::simd::tag::max_, tag::cpu_\n                                    , (A0)\n                                    , (scalar_< floating_<A0> >)\n                                      (scalar_< floating_<A0> >)\n                                    )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    {\n      if (is_nan(a0) || is_nan(a1)) return Nan<result_type>();\n      return (a0 > a1) ? a0 : a1;\n    }\n  };\n} } }\n\n#endif\n", "meta": {"hexsha": "e419a4067f1f61f85c09b84057c5322368c5ea8a", "size": 3251, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/arithmetic/include/boost/simd/toolbox/arithmetic/functions/scalar/max.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/max.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/max.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": 37.367816092, "max_line_length": 84, "alphanum_fraction": 0.4823131344, "num_tokens": 739, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.45340118564098797}}
{"text": "/*\n\nPICCANTE\nThe hottest HDR imaging library!\nhttp://vcg.isti.cnr.it/piccante\n\nCopyright (C) 2014-2016\nVisual Computing Laboratory - ISTI CNR\nhttp://vcg.isti.cnr.it\nLibrary author: Francesco Banterle\nThis file author: Giorgio Marcias\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_ALGORITHMS_MITSUNAGA_NAYAR_CRF_HPP\n#define PIC_ALGORITHMS_MITSUNAGA_NAYAR_CRF_HPP\n\n#include<algorithm>\n#include<limits>\n#include<vector>\n\n#include \"../base.hpp\"\n\n#ifndef PIC_DISABLE_EIGEN\n\n#ifndef PIC_EIGEN_NOT_BUNDLED\n    #include \"../externals/Eigen/LU\"\n#else\n    #include <Eigen/LU>\n#endif\n\n#endif\n\nnamespace pic {\n\n/**\n * @brief MitsunagaNayarClassic computes the inverse CRF of a camera as a polynomial function.\n * @param samples           Sample array of size nSamples x #exposures.\n * @param nSamples          Number of samples, for each exposure.\n * @param exposures         Array of exposure timings (size: #exposures = 'Q' as in the Mitsunaga & Nayar paper).\n * @param coefficients      The output coefficients ('c' in the paper) resulting from the computation.\n * @param computeRatios     false if exact exposures are passed, true to approximate exposure ratios as in the paper.\n * @param R                 The output estimated exposure ratios, i.e. R[q1][q2] = 'R_{q1,q2}' as in the book.\n * @param eps               Threshold for stopping the approximation process.\n * @param max_iterations    Maximum number of iterations.\n * @return The error as in the paper.\n */\nPIC_INLINE float MitsunagaNayarClassic(int *samples, const std::size_t nSamples, const std::vector<float> &exposures,\n                                   std::vector<float> &coefficients, const bool computeRatios, std::vector<float> &R,\n                                   const float eps, const std::size_t max_iterations)\n{\n#ifndef PIC_DISABLE_EIGEN\n    float eval, val, tmp1, tmp2;\n    const std::size_t Q = exposures.size();\n    const std::size_t N = coefficients.size() - 1;\n\n    const float Mmax = 1.f;\n\n    for (float &_c : coefficients) {\n        _c = 0.f;\n    }\n\n    if (!samples || Q < 2 || coefficients.size() < 2) {\n        return std::numeric_limits<float>::infinity();\n    }\n\n    R.assign(Q < 2 ? 0 : Q - 1, 1.f);\n    for (int q = 0; q < R.size(); ++q) {\n        R[q] = exposures[q] / exposures[q+1];\n    }\n\n    //Check valid samples\n    std::vector<std::vector<float>> g(nSamples, std::vector<float>(Q, 0.f));\n    std::size_t P = 0;\n    for (std::size_t p = 0; p < nSamples; ++p) {\n        bool valid = false;\n        for (std::size_t q = 0; q < Q-1; ++q) {\n            if (samples[p * Q + q] >= 0 && samples[p * Q + q+1] >= 0) {\n                valid = true;\n                break;\n            }\n        }\n        if (valid) {\n            for (std::size_t q = 0; q < Q; ++q) {\n                if (samples[p * Q + q] >= 0) {\n                    g[P][q] = samples[p * Q + q] / 255.f;\n                } else {\n                    g[P][q] = -1.f;\n                }\n            }\n            ++P;\n        }\n    }\n    g.resize(P);\n\n    if (g.empty()) {\n        return std::numeric_limits<float>::infinity();\n    }\n\n    //Precompute test with exponentials\n    std::vector<Eigen::VectorXf> test;\n    if (computeRatios) {\n        test.assign(256, Eigen::VectorXf::Zero(N+1));\n        for (std::size_t i = 0; i < 256; ++i) {\n            test[i][0] = 1.f;\n            for (std::size_t n = 1; n <= N; ++n) {\n                test[i][n] = (i / 255.f) * test[i][n-1];\n            }\n        }\n    }\n\n    //Precompute M with exponentials\n    std::vector<std::vector<std::vector<float>>> M(P,\n                                                   std::vector<std::vector<float>>(Q,\n                                                                                   std::vector<float>(N+1, 0.f)));\n    for (std::size_t p = 0; p < P; ++p) {\n        for (std::size_t q = 0; q < Q; ++q) {\n            M[p][q][0] = 1.f;\n            for (std::size_t n = 1; n <= N; ++n) {\n                M[p][q][n] = g[p][q] * M[p][q][n-1];\n            }\n        }\n    }\n\n    std::vector<std::vector<std::vector<float>>> d(P,\n                                                   std::vector<std::vector<float>>(Q-1,\n                                                                                   std::vector<float>(N+1, 1.f)));\n    Eigen::MatrixXf A = Eigen::MatrixXf::Zero(N, N);\n    Eigen::VectorXf x, b = Eigen::VectorXf::Zero(N);\n    Eigen::VectorXf c(N+1), prev_c = Eigen::VectorXf::Zero(N+1);\n\n    std::size_t iter = 0;\n\n    do {\n        //Compute d\n        for (std::size_t p = 0; p < P; ++p) {\n            for (std::size_t q = 0; q < Q-1; ++q) {\n                if (g[p][q] >= 0.f && g[p][q+1] >= 0.f) {\n                    for (std::size_t n = 0; n <= N; ++n) {\n                        d[p][q][n] = M[p][q][n] - R[q] * M[p][q+1][n];\n                    }\n                } else {\n                    d[p][q].assign(N+1, 0.f);\n                }\n            }\n        }\n\n        //Build the matrix A of the linear system\n        A.setZero(N, N);\n        for (std::size_t i = 0; i < N; ++i) {\n            for (std::size_t j = 0; j < N; ++j) {\n                for (std::size_t p = 0; p < P; ++p) {\n                    for (std::size_t q = 0; q < Q - 1; ++q) {\n                        A(i, j) += d[p][q][i] * (d[p][q][j] - d[p][q][N]);\n                    }\n                }\n            }\n        }\n\n        //Build the vector of knowns b\n        b.setZero(N);\n        for (std::size_t i = 0; i < N; ++i) {\n            for (std::size_t p = 0; p < P; ++p) {\n                for (std::size_t q = 0; q < Q - 1; ++q) {\n                    b(i) -= Mmax * d[p][q][i] * d[p][q][N];\n                }\n            }\n        }\n\n        //Solve the linear system\n        x = A.partialPivLu().solve(b);\n        c << x, Mmax - x.sum();\n\n        if (computeRatios) {\n            //Evaluate approximation increment\n            eval = std::numeric_limits<float>::lowest();\n            for (const Eigen::VectorXf &_M : test) {\n                val = std::abs((c - prev_c).dot(_M));\n                if (val > eval) {\n                    eval = val;\n                }\n            }\n\n            //Update R\n            for (std::size_t q = 0; q < Q-1; ++q) {\n                R[q] = 0.f;\n                tmp1 = 0.f;\n                tmp2 = 0.f;\n                for (std::size_t p = 0; p < P; ++p) {\n                    if (g[p][q] >= 0.f && g[p][q+1] >= 0.f) {\n                        for (std::size_t n = 0; n <= N; ++n) {\n                            tmp1 += c[n] * M[p][q][n];\n                            tmp2 += c[n] * M[p][q+1][n];\n                        }\n                    }\n                }\n                R[q] += tmp1 / tmp2;\n            }\n\n            ++iter;\n        }\n    } while (computeRatios && eval > eps && iter < max_iterations);\n\n    for (std::size_t n = 0; n <= N; ++n) {\n        coefficients[n] = c[n];\n    }\n\n    //Evaluate error\n    eval = 0.f;\n    for (std::size_t q = 0; q < Q-1; ++q) {\n        for (std::size_t p = 0; p < P; ++p) {\n            if (g[p][q] >= 0.f && g[p][q+1] >= 0.f) {\n                val = 0.f;\n                for (std::size_t n = 0; n <= N; ++n) {\n                    val += coefficients[n] * (M[p][q][n] - R[q] * M[p][q+1][n]);\n                }\n                eval += val * val;\n            }\n        }\n    }\n\n    return eval;\n#else\n    return -1.0f;\n#endif\n}\n\n/**\n * @brief MitsunagaNayarFull computes the inverse CRF of a camera as a polynomial function, using all exposure ratios.\n * @param samples           Sample array of size nSamples x #exposures.\n * @param nSamples          Number of samples, for each exposure.\n * @param exposures         Array of exposure timings (size: #exposures = 'Q' as in the Mitsunaga & Nayar paper).\n * @param coefficients      The output coefficients ('c' in the paper) resulting from the computation.\n * @param computeRatios     false if exact exposures are passed, true to approximate exposure ratios as in the paper.\n * @param R                 The output estimated exposure ratios, i.e. R[q1][q2] = 'R_{q1,q2}' as in the book.\n * @param eps               Threshold for stopping the approximation process.\n * @param max_iterations    Maximum number of iterations.\n * @return The error as in the paper.\n */\nPIC_INLINE float MitsunagaNayarFull(int *samples, const std::size_t nSamples, const std::vector<float> &exposures,\n                                std::vector<float> &coefficients, bool computeRatios, std::vector<std::vector<float>> &R,\n                                const float eps, const std::size_t max_iterations)\n{\n#ifndef PIC_DISABLE_EIGEN\n    float eval, val, tmp1, tmp2;\n    const std::size_t Q = exposures.size();\n    const std::size_t N = coefficients.size() - 1;\n\n    const float Mmax = 1.f;\n\n    for (float &_c : coefficients) {\n        _c = 0.f;\n    }\n    R.assign(Q < 2 ? 0 : Q, std::vector<float>(Q < 2 ? 0 : Q, 1.f));\n    for (int q1 = 0; q1 < R.size(); ++q1) {\n        for (int q2 = 0; q2 < R[q1].size(); ++q2) {\n            if (q2 == q1) {\n                R[q1][q2] = 1.f;\n            } else {\n                R[q1][q2] = exposures[q1] / exposures[q2];\n            }\n        }\n    }\n    if (!samples || Q < 2 || coefficients.size() < 2) {\n        return std::numeric_limits<float>::infinity();\n    }\n\n    //Check valid samples\n    std::vector<std::vector<float>> g(nSamples, std::vector<float>(Q, 0.f));\n    std::size_t P = 0;\n    for (std::size_t p = 0; p < nSamples; ++p) {\n        std::size_t valid = 0;\n        for (std::size_t q = 0; q < Q; ++q) {\n            if (samples[p * Q + q] >= 0) {\n                ++valid;\n            }\n        }\n        if (valid > 1) {\n            for (std::size_t q = 0; q < Q; ++q) {\n                if (samples[p * Q + q] >= 0) {\n                    g[P][q] = samples[p * Q + q] / 255.f;\n                } else {\n                    g[P][q] = -1.f;\n                }\n            }\n            ++P;\n        }\n    }\n    g.resize(P);\n\n    if (g.empty()) {\n        return std::numeric_limits<float>::infinity();\n    }\n\n    //Precompute test with exponentials\n    std::vector<Eigen::VectorXf> test;\n    if (computeRatios) {\n        test.assign(256, Eigen::VectorXf::Zero(N+1));\n        for (std::size_t i = 0; i < 256; ++i) {\n            test[i][0] = 1.f;\n            for (std::size_t n = 1; n <= N; ++n) {\n                test[i][n] = (i / 255.f) * test[i][n-1];\n            }\n        }\n    }\n\n    //Precompute M with exponentials\n    std::vector<std::vector<std::vector<float>>> M(P,\n                                                   std::vector<std::vector<float>>(Q,\n                                                                                   std::vector<float>(N+1, 0.f)));\n    for (std::size_t p = 0; p < P; ++p) {\n        for (std::size_t q = 0; q < Q; ++q) {\n            M[p][q][0] = 1.f;\n            for (std::size_t n = 1; n <= N; ++n) {\n                M[p][q][n] = g[p][q] * M[p][q][n-1];\n            }\n        }\n    }\n\n    std::vector<std::vector<std::vector<std::vector<float>>>> d(P,\n                                                                std::vector<std::vector<std::vector<float>>>(Q,\n                                                                            std::vector<std::vector<float>>(Q,\n                                                                                        std::vector<float>(N+1, 1.f))));\n    Eigen::MatrixXf A = Eigen::MatrixXf::Zero(N, N);\n    Eigen::VectorXf x, b = Eigen::VectorXf::Zero(N);\n    Eigen::VectorXf c(N+1), prev_c = Eigen::VectorXf::Zero(N+1);\n\n    std::size_t iter = 0;\n\n    do {\n        //Compute d\n        for (std::size_t p = 0; p < P; ++p) {\n            for (std::size_t q1 = 0; q1 < Q; ++q1) {\n                for (std::size_t q2 = 0; q2 < Q; ++q2) {\n                    d[p][q1][q2].assign(N+1, 0.f);\n                    if (q2 != q1) {\n                        for (std::size_t n = 0; n <= N; ++n) {\n                            if (g[p][q1] >= 0.f && g[p][q2] >= 0.f) {\n                                d[p][q1][q2][n] = M[p][q1][n] - R[q1][q2] * M[p][q2][n];\n                            } else {\n                                d[p][q1][q2][n] = 0.f;\n                            }\n                        }\n                    }\n                }\n            }\n        }\n\n        //Build the matrix A of the linear system\n        A.setZero(N, N);\n        for (std::size_t i = 0; i < N; ++i) {\n            for (std::size_t j = 0; j < N; ++j) {\n                for (std::size_t p = 0; p < P; ++p) {\n                    for (std::size_t q1 = 0; q1 < Q; ++q1) {\n                        for (std::size_t q2 = 0; q2 < Q; ++q2) {\n                            if (q2 != q1) {\n                                A(i, j) += d[p][q1][q2][i] * (d[p][q1][q2][j] - d[p][q1][q2][N]);\n                            }\n                        }\n                    }\n                }\n            }\n        }\n\n        //Build the vector of knowns b\n        b.setZero(N);\n        for (std::size_t i = 0; i < N; ++i) {\n            for (std::size_t p = 0; p < P; ++p) {\n                for (std::size_t q1 = 0; q1 < Q; ++q1) {\n                    for (std::size_t q2 = 0; q2 < Q; ++q2) {\n                        if (q2 != q1) {\n                            b(i) -= Mmax * d[p][q1][q2][i] * d[p][q1][q2][N];\n                        }\n                    }\n                }\n            }\n        }\n\n        //Solve the linear system\n        x = A.partialPivLu().solve(b);\n        c << x, Mmax - x.sum();\n\n        if (computeRatios) {\n            //Evaluate approximation increment\n            eval = std::numeric_limits<float>::lowest();\n            for (const Eigen::VectorXf &_M : test) {\n                val = std::abs((c - prev_c).dot(_M));\n                if (val > eval) {\n                    eval = val;\n                }\n            }\n\n            //Update R\n            for (std::size_t q1 = 0; q1 < Q; ++q1) {\n                for (std::size_t q2 = 0; q2 < Q; ++q2) {\n                    R[q1][q2] = 0.f;\n                    tmp1 = 0.f;\n                    tmp2 = 0.f;\n                    for (std::size_t p = 0; p < P; ++p) {\n                        if (g[p][q1] >= 0.f && g[p][q2] >= 0.f) {\n                            for (std::size_t n = 0; n <= N; ++n) {\n                                tmp1 += c[n] * M[p][q1][n];\n                                tmp2 += c[n] * M[p][q2][n];\n                            }\n                        }\n                    }\n                    R[q1][q2] += tmp1 / tmp2;\n                }\n            }\n\n            ++iter;\n        }\n    } while (computeRatios && eval > eps && iter < max_iterations);\n\n    for (std::size_t n = 0; n <= N; ++n) {\n        coefficients[n] = c[n];\n    }\n\n    //Evaluate error\n    eval = 0.f;\n    for (std::size_t q1 = 0; q1 < Q; ++q1) {\n        for (std::size_t q2 = 0; q2 < Q; ++q2) {\n            if (q2 != q1) {\n                for (std::size_t p = 0; p < P; ++p) {\n                    if (g[p][q1] >= 0.f && g[p][q2] >= 0.f) {\n                        val = 0.f;\n                        for (std::size_t n = 0; n <= N; ++n) {\n                            val += coefficients[n] * (M[p][q1][n] - R[q1][q2] * M[p][q2][n]);\n                        }\n                        eval += val * val;\n                    }\n                }\n            }\n        }\n    }\n\n    return eval;\n#else\n    return -1.0f;\n#endif\n}\n\n}\n\n#endif // PIC_ALGORITHMS_MITSUNAGA_NAYAR_CRF_HPP\n", "meta": {"hexsha": "ad63d04e4a3d40db0538bf35be63b5f1831bd8cc", "size": 15523, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/mitsunaga_nayar_crf.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/algorithms/mitsunaga_nayar_crf.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/algorithms/mitsunaga_nayar_crf.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": 34.4955555556, "max_line_length": 121, "alphanum_fraction": 0.413193326, "num_tokens": 4486, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.45340118564098797}}
{"text": "/**\n * @file set_cover_test.cpp\n * @brief\n * @author Piotr Smulewicz\n * @version 1.0\n * @date 2014-02-17\n */\n\n#include \"test_utils/set_cover_check.hpp\"\n#include \"test_utils/test_result_check.hpp\"\n#include \"test_utils/logger.hpp\"\n\n#include \"paal/greedy/set_cover/set_cover.hpp\"\n#include \"paal/utils/functors.hpp\"\n\n#include <boost/test/unit_test.hpp>\n#include <boost/range/irange.hpp>\n\n#include <vector>\n#include <iterator>\n\nBOOST_AUTO_TEST_CASE(SetCover) {\n    const int OPTIMAL = 2;\n    std::vector<std::vector<int>> sets_element = { { 1, 2 },\n                                                   { 3, 4, 5, 6 },\n                                                   { 7, 8, 9, 10, 11, 12, 13,\n                                                     14 },\n                                                   { 1, 3, 5, 7, 9, 11, 13 },\n                                                   { 2, 4, 6, 8, 10, 12, 0 } };\n    auto costs = paal::utils::return_one_functor();\n    auto sets = boost::irange(0, 5);\n    auto set_to_elements = paal::utils::make_array_to_functor(sets_element);\n    std::vector<int> result;\n    auto element_index = paal::utils::identity_functor{};\n    auto cost =\n        paal::greedy::set_cover(sets, costs, set_to_elements,\n                                std::back_inserter(result), element_index);\n    double approximation_ratio =\n        set_cover_result_check(sets, set_to_elements, result);\n    check_result(cost, OPTIMAL, approximation_ratio);\n}\n", "meta": {"hexsha": "0179e48536326f6afeaa9d02ab0e210bf9a290b2", "size": 1465, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/greedy/set_cover_test.cpp", "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": "test/greedy/set_cover_test.cpp", "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": "test/greedy/set_cover_test.cpp", "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": 34.880952381, "max_line_length": 79, "alphanum_fraction": 0.5488054608, "num_tokens": 377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389817407017, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.45340117878044084}}
{"text": "//=======================================================================\n// Copyright 2001 Jeremy G. Siek, Andrew Lumsdaine, Lie-Quan Lee,\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n\n#ifndef GF2_MST_HPP\n#define GF2_MST_HPP\n\n#include <boost/config.hpp>\n#include <iostream>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/prim_minimum_spanning_tree.hpp>\n\nnamespace rapter\n{\n\nnamespace mst\n{\n    typedef std::pair< int, int > Edge;\n    template <typename _Scalar>\n    class MST\n    {\n        public:\n            //addEdge()\n    };\n\ntemplate <typename _Scalar>\nint mstMain()\n{\n    using namespace boost;\n\n    typedef adjacency_list < vecS\n                           , vecS\n                           , undirectedS\n                           , property<vertex_distance_t, _Scalar>\n                           , property < edge_weight_t, _Scalar >\n                           > Graph;\n\n\n    const int num_nodes = 5;\n    Edge edges[] = { Edge(0, 2), Edge(1, 3), Edge(1, 4), Edge(2, 1), Edge(2, 3),\n                  Edge(3, 4), Edge(4, 0)\n                };\n    _Scalar weights[] = { 1, 1, 2, 7, 3, 1, 1 };\n    int num_edges = sizeof(edges) / sizeof(Edge);\n    Graph g(edges, edges + num_edges, weights, num_nodes);\n    typename property_map<Graph, edge_weight_t>::type weightmap = get(edge_weight, g);\n    std::vector < typename graph_traits < Graph >::vertex_descriptor > p( num_vertices(g) );\n\n    prim_minimum_spanning_tree(g, &p[0]);\n    std::fstream dotfile(\"mst.dot\");\n    if ( !dotfile.is_open() )\n    {\n        std::cerr << \"[\" << __func__ << \"]: \" << \"could not open mst.dot\" << std::endl;\n        return EXIT_FAILURE;\n    }\n\n    dotfile << \"digraph {\\nedge [dir=none]\\n\";\n    // Original\n    for ( std::size_t i = 0; i != num_edges; ++i )\n    {\n        dotfile << \"V\" << edges[i].first << \" -> \" << \"V\" << edges[i].second << std::endl;\n    }\n    // MST\n    for (std::size_t i = 0; i != p.size(); ++i)\n        if (p[i] != i)\n        {\n            std::cout << \"parent[\" << i << \"] = \" << p[i] << std::endl;\n            dotfile << \"v\" << p[i] << \" -> \" << \"v\" << i << std::endl;\n        }\n        else\n            std::cout << \"parent[\" << i << \"] = no parent\" << std::endl;\n\n    dotfile << \"}\\n\";\n    dotfile.close();\n    std::system(\"dot -Tpng mst.dot -o mst.png && eog mst.png\");\n\n    return EXIT_SUCCESS;\n}\n\n} //...ns mst\n\n} //...ns GF2\n\n#endif // GF2_MST_HPP\n", "meta": {"hexsha": "d2ffed3a9a8c710cc524133b7ded429ddbea8d62", "size": 2571, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "visualization/include/rapter/visualization/mst.hpp", "max_stars_repo_name": "frozar/RAPter", "max_stars_repo_head_hexsha": "8f1f9a37e4ac12fa08a26d18f58d3b335f797200", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2017-09-21T19:52:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T13:47:02.000Z", "max_issues_repo_path": "visualization/include/rapter/visualization/mst.hpp", "max_issues_repo_name": "frozar/RAPter", "max_issues_repo_head_hexsha": "8f1f9a37e4ac12fa08a26d18f58d3b335f797200", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2017-07-26T15:00:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-03T03:08:15.000Z", "max_forks_repo_path": "visualization/include/rapter/visualization/mst.hpp", "max_forks_repo_name": "frozar/RAPter", "max_forks_repo_head_hexsha": "8f1f9a37e4ac12fa08a26d18f58d3b335f797200", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2017-03-24T16:56:08.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-21T13:18:33.000Z", "avg_line_length": 28.8876404494, "max_line_length": 92, "alphanum_fraction": 0.5036950603, "num_tokens": 710, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389817407017, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.45340117878044084}}
{"text": "#pragma once\n\n#include <armadillo>\n\n#include \"heattransfer/radial.hpp\"\n\n/*!\n * \\brief Implements 1d radial unsteady heat transfer.\n *\n * This is documented in Jan Fredrik Helgaker's PhD thesis and in\n *  - <a href=\"10.1016/j.apm.2009.07.017\">Sensitivity of pipeline gas flow model to the selection of the equation of state</a>\n *  - <a href=\"10.1016/j.cherd.2009.06.008\">Transient flow in natural gas pipeline - The effect of pipeline thermal model</a>\n */\nclass UnsteadyHeatTransfer : public RadialHeatTransfer\n{\npublic:\n    /*!\n     * \\brief Construct from complete description of pipeline and surroundings.\n     * \\param diameter Inner diameter [m]\n     * \\param pipeWall PipeWall instance\n     * \\param burialDepth Distance from top of pipe to top of burial medium [m]\n     * \\param burialMedium BurialMedium instance\n     * \\param ambientFluid AmbientFluid instanc.\n     */\n    UnsteadyHeatTransfer(\n            const double diameter,\n            const PipeWall& pipeWall,\n            const double burialDepth,\n            const BurialMedium& burialMedium,\n            const AmbientFluid& ambientFluid);\n\n    /*!\n     * \\brief Evaluate 1d radial unsteady heat transfer model.\n     *\n     * Operates on a HeatTransferState and returns a new HeatTransferState.\n     * Requires the discretization temperature HeatTransferState::m_temperature.\n     *\n     * \\param current Current HeatTransferState\n     * \\param timeStep Time step [s]\n     * \\param ambientTemperature Ambient temperature [K]\n     * \\param gasPressure Gas pressure [Pa]\n     * \\param gasTemperature Gas temperature [K]\n     * \\param gasReynoldsNumber Reynolds number of gas [-]\n     * \\param gasHeatCapacity Gas heat capacity (\\f$c_p\\f$) [J/(kg K)]\n     * \\param gasViscosity Gas dynamic viscosity [Pa s] = [kg/m*s]\n     * \\return HeatTransferState with new heat flux.\n     */\n    virtual HeatTransferState evaluate(\n            const HeatTransferState& current,\n            const double timeStep,\n            const double ambientTemperature,\n            const double gasPressure,\n            const double gasTemperature,\n            const double gasReynoldsNumber,\n            const double gasHeatCapacity,\n            const double gasViscosity) const override;\n\n    /*!\n     * \\brief Internal method used for evaluating the unsteady heat transfer model.\n     *\n     * This is exposed for testing purposes. We typically use pointers anyway,\n     * so this is not accessible without casting to UnsteadyHeatTransfer.\n     *\n     * \\param shellTemperature The temperature of each discretization layer [K]\n     * \\param timeStep Time step [s]\n     * \\param ambientTemperature Ambient temperature [K]\n     * \\param gasPressure Gas pressure [Pa]\n     * \\param gasTemperature Gas temperature [K]\n     * \\param gasReynoldsNumber Reynolds number of gas [-]\n     * \\param gasHeatCapacity Gas heat capacity (\\f$c_p\\f$) [J/(kg K)]\n     * \\param gasViscosity Gas dynamic viscosity [Pa s] = [kg/m*s]\n     * \\return HeatTransferState with new heat flux.\n     */\n    HeatTransferState evaluateInternal(\n            const arma::vec& shellTemperature,\n            const double timeStep,\n            const double ambientTemperature,\n            const double gasPressure,\n            const double gasTemperature,\n            const double gasReynoldsNumber,\n            const double gasHeatCapacity,\n            const double gasViscosity) const;\n\n    /*!\n     * \\brief Thermalize the unsteady heat transfer model to steady state.\n     *\n     * This just performs an infinite time step to find the temperature\n     * distribution in the discretization layers at steady state.\n     * This could also be done analytically, if we had the analytic solution.\n     *\n     * \\param ambientTemperature Ambient temperature [K]\n     * \\param gasPressure Gas pressure [Pa]\n     * \\param gasTemperature Gas temperature [K]\n     * \\param gasReynoldsNumber Reynolds number of gas [-]\n     * \\param gasHeatCapacity Gas heat capacity (\\f$c_p\\f$) [J/(kg K)]\n     * \\param gasViscosity Gas dynamic viscosity [Pa s] = [kg/m*s]\n     * \\return HeatTransferState with new heat flux.\n     */\n    HeatTransferState thermalizeToSteadyState(\n            const double ambientTemperature,\n            const double gasPressure,\n            const double gasTemperature,\n            const double gasReynoldsNumber,\n            const double gasHeatCapacity,\n            const double gasViscosity) const;\n\nprivate:\n    //! Heat transfer coefficient for each discretization layer.\n    //! This is the k_i from eq. (2.26) in JFH PhD thesis.\n    arma::vec m_heatTransferCoefficient;\n\n    /*!\n     * \\brief Internal (private) method used for solving the equations in the 1d\n     * radial unsteady heat transfer model.\n     *\n     * \\param shellTemperature The temperature of each discretization layer [K]\n     * \\param timeStep Time step [s]\n     * \\param ambientTemperature Ambient temperature [K]\n     * \\param gasPressure Gas pressure [Pa]\n     * \\param gasTemperature Gas temperature [K]\n     * \\param gasReynoldsNumber Reynolds number of gas [-]\n     * \\param gasHeatCapacity Gas heat capacity (\\f$c_p\\f$) [J/(kg K)]\n     * \\param gasViscosity Gas dynamic viscosity [Pa s] = [kg/m*s]\n     * \\return HeatTransferState with new heat flux.\n     */\n    arma::vec solveEquations(\n            const arma::vec& shellTemperature,\n            const double timeStep,\n            const double gasPressure,\n            const double gasTemperature,\n            const double ambientTemperature,\n            const double gasReynoldsNumber,\n            const double gasHeatCapacity,\n            const double gasViscosity) const;\n};\n", "meta": {"hexsha": "7bee863dbeaa80f0703a653f4df661b0bbfcee42", "size": 5631, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/heattransfer/unsteady.hpp", "max_stars_repo_name": "kewin1983/transient-pipeline-flow", "max_stars_repo_head_hexsha": "4ffe0b61d3d40d9bcb82a3743b2c2e403521835d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-26T03:30:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-26T03:30:07.000Z", "max_issues_repo_path": "src/heattransfer/unsteady.hpp", "max_issues_repo_name": "kewin1983/transient-pipeline-flow", "max_issues_repo_head_hexsha": "4ffe0b61d3d40d9bcb82a3743b2c2e403521835d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/heattransfer/unsteady.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.4044117647, "max_line_length": 126, "alphanum_fraction": 0.6696856686, "num_tokens": 1257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389817407016, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.45340117878044073}}
{"text": "#ifndef QUANTUM_GENERAL\n#define QUANTUM_GENERAL\n\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <Eigen/KroneckerProduct>\n\ntypedef std::complex<float> Complex;\ntypedef Eigen::Matrix<Complex, Eigen::Dynamic, 1> Vector;\ntypedef Eigen::SparseMatrix<Complex> Matrix;\n\nint pow2(int exp);\nvoid printBin(int N, int BITS);\n//return |0>\nVector zero(void);\n\n//return |1>\nVector one(void);\n\n//returns |N> for a space of size NQUBITS\nVector basis(int N, int NQUBITS);\n#endif\n", "meta": {"hexsha": "a4570bc27b29ab7df5d3013e671c8fec3b9f6529", "size": 471, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "one/general.hpp", "max_stars_repo_name": "RobertZ2011/qcposts", "max_stars_repo_head_hexsha": "090636a41ae00f875d501e90463d57066ab5e317", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "one/general.hpp", "max_issues_repo_name": "RobertZ2011/qcposts", "max_issues_repo_head_hexsha": "090636a41ae00f875d501e90463d57066ab5e317", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "one/general.hpp", "max_forks_repo_name": "RobertZ2011/qcposts", "max_forks_repo_head_hexsha": "090636a41ae00f875d501e90463d57066ab5e317", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.4782608696, "max_line_length": 57, "alphanum_fraction": 0.7473460722, "num_tokens": 127, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8175744939732855, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.4533209098131537}}
{"text": "#include <iostream>\n#include <cmath>\n#include <algorithm>\n#include <vector>\n#include <boost/multiprecision/cpp_int.hpp>\nusing namespace boost::multiprecision;\nusing namespace std;\nint main() {\n    cpp_int n, m; cin >> n;\n    long long int cnt = 0;\n    m = n;\n    while (m > 0) {\n        m /= 10;\n        cnt++;\n    }\n    cpp_int com = (cpp_int)pow(10, cnt) - 1, c = (cpp_int)pow(10, cnt - 1), ans = 0;\n\n    while(true) {\n        if (n < com) com -= c;\n        else break;\n    }\n    while (com > 0) {\n        ans += (com % 10);\n        com /= 10;\n    }\n    cout << ans << endl;\n}\n", "meta": {"hexsha": "e523620433fbf1c699bf3dc3a423fe254d00bfb8", "size": 579, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AtCoder/agc021/a/main.cpp", "max_stars_repo_name": "H-Tatsuhiro/Com_Pro-Cpp", "max_stars_repo_head_hexsha": "fd79f7821a76b11f4a6f83bbb26a034db577a877", "max_stars_repo_licenses": ["MIT"], "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/agc021/a/main.cpp", "max_issues_repo_name": "H-Tatsuhiro/Com_Pro-Cpp", "max_issues_repo_head_hexsha": "fd79f7821a76b11f4a6f83bbb26a034db577a877", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-10-19T08:47:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T05:23:56.000Z", "max_forks_repo_path": "AtCoder/agc021/a/main.cpp", "max_forks_repo_name": "H-Tatsuhiro/Com_Pro-Cpp", "max_forks_repo_head_hexsha": "fd79f7821a76b11f4a6f83bbb26a034db577a877", "max_forks_repo_licenses": ["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.6785714286, "max_line_length": 84, "alphanum_fraction": 0.518134715, "num_tokens": 181, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.4533208999548674}}
{"text": "#ifndef INITIALIZERS_HPP\n#define INITIALIZERS_HPP\n\n#include <boost/random.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/uniform_real_distribution.hpp>\n#include <Eigen/Dense>\n\nusing Matrix = Eigen::MatrixXd;\nusing MatrixType = Eigen::Ref<const Eigen::MatrixXd>;\n\nnamespace hmm {\n  namespace initializers {\n    \n    // random number generator\n    static boost::mt19937 rng;\n\n    /**\n     * Base initializer class (virtual).\n     * Subclasses should be implemented as functors\n     * templated by parameters.\n     * Calling the functor should return an Eigen matrix.\n     *\n     */\n    struct Initializer {\n    public:\n      virtual MatrixType operator()() = 0;\n    };\n\n\n    /**\n     * Initialize a matrix of zeros.\n     * @tparam n_rows Number of rows\n     * @tparam n_cols Number of columns\n     *\n     */\n    template<std::size_t n_rows, std::size_t n_cols>\n    struct ZeroInitializer : public Initializer {\n    public:\n      MatrixType operator()() override {\n        return Matrix::Zero(n_rows, n_cols);\n      }\n    };\n\n    \n    /**\n     * Initialize a matrix with uniformly distributed values.\n     * @tparam n_rows Number of rows\n     * @tparam n_cols Number of columns\n     * @param lower Support lower bound for uniform distribution\n     * @param upper Support upper bound for uniform distribution\n     *\n     */\n    template<std::size_t n_rows, std::size_t n_cols>\n    struct UniformInitializer : public Initializer {\n    public:\n      UniformInitializer(const double lower, const double upper)\n        : m_lower(lower),\n          m_upper(upper),\n          m_unifd(boost::random::uniform_real_distribution<>(lower, upper)) {}\n\n      MatrixType operator()() override {\n        return Matrix::Zero(n_rows, n_cols)\n          .unaryExpr([&](double t){ return m_unifd(rng); });\n      }\n\n    private:\n      double m_lower;\n      double m_upper;\n      boost::random::uniform_real_distribution<double> m_unifd;\n    };\n\n\n    /**\n     * Initialize a matrix with normally distributed values.\n     * @tparam n_rows Number of rows\n     * @tparam n_cols Number of columns\n     * @param mean Location parameter for the normal distribution\n     * @param var Variance parameter for the normal distribution\n     *\n     */\n    template<std::size_t n_rows, std::size_t n_cols>\n    struct NormalInitializer : public Initializer {\n    public:\n      NormalInitializer(const double mean, const double var)\n        : m_mean(mean),\n          m_var(var),\n          m_gaussd(boost::normal_distribution<>(mean, var)) {}\n      MatrixType operator()() override {\n        boost::variate_generator<boost::mt19937&,\n                                 boost::normal_distribution<>> gaussvars(rng, m_gaussd);\n        return Matrix::Zero(n_rows, n_cols)\n          .unaryExpr([&](double t){ return gaussvars(); });\n      }\n\n    private:\n      double m_mean;\n      double m_var;\n      boost::normal_distribution<double> m_gaussd;\n    };\n  }\n}\n\n#endif\n", "meta": {"hexsha": "bfd472d0d6d581ea64076d9e0896e0f2f0ad5c2b", "size": 2947, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/initializers.hpp", "max_stars_repo_name": "alindgupta/HMM-cpp", "max_stars_repo_head_hexsha": "0475341ff8059b6f8148a844cd6c61637af3bfc2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/initializers.hpp", "max_issues_repo_name": "alindgupta/HMM-cpp", "max_issues_repo_head_hexsha": "0475341ff8059b6f8148a844cd6c61637af3bfc2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/initializers.hpp", "max_forks_repo_name": "alindgupta/HMM-cpp", "max_forks_repo_head_hexsha": "0475341ff8059b6f8148a844cd6c61637af3bfc2", "max_forks_repo_licenses": ["BSD-3-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.0666666667, "max_line_length": 88, "alphanum_fraction": 0.6420088225, "num_tokens": 657, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583376458153, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.45331585825079945}}
{"text": "/*\n * The MIT License\n *\n * Copyright 2017 Christoph Wurst <christoph@winzerhof-wurst.at>.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n\n#include <cstdlib>\n#include <boost/spirit/include/qi.hpp>\n#include <boost/phoenix.hpp>\n\nusing namespace std;\nnamespace qi = boost::spirit::qi;\n\nstruct print_functor {\n\n\tvoid operator()(int const &i) const {\n\t\tcout << i << endl;\n\t}\n};\n\n/**\n * expr = term *( '+' term | '-' term )\n * term = fact *( '*' fact | '/' fact )\n * fact = double | '(' expr ')'\n */\ntemplate<typename Iterator>\nstruct simple_calc_grammar : qi::grammar<Iterator, qi::space_type> {\n\n\tsimple_calc_grammar() : simple_calc_grammar::base_type(expr) {\n\t\texpr = term >> *('+' >> term | '-' >> term);\n\t\tterm = fact >> *('*' >> fact | '/' >> fact);\n\t\tfact = qi::double_ | '(' >> expr >> ')';\n\t}\n\n\tqi::rule<Iterator, qi::space_type> expr, term, fact;\n};\n\n/**\n * expr = term *( '+' term | '-' term )\n * term = fact *( '*' fact | '/' fact )\n * fact = double | '(' expr ')'\n */\ntemplate<typename Iterator>\nstruct advanced_calc_grammar : qi::grammar<Iterator, double(), qi::space_type> {\n\n\tadvanced_calc_grammar() : advanced_calc_grammar::base_type(expr) {\n\t\texpr = term [ qi::_val = qi::_1 ]\n\t\t\t>>\n\t\t\t*('+' >> term [ qi::_val += qi::_1 ]\n\t\t\t| '-' >> term [ qi::_val += qi::_1 ]\n\t\t\t);\n\t\tterm = fact [qi::_val = qi::_1]\n\t\t\t>>\n\t\t\t*('*' >> fact [ qi::_val *= qi::_1 ]\n\t\t\t| '/' >> fact [ qi::_val /= qi::_1 ]\n\t\t\t);\n\t\tfact = qi::double_ [ qi::_val = qi::_1 ]\n\t\t\t| '(' >> expr [ qi::_val = qi::_1 ]\n\t\t\t>> ')';\n\t}\n\n\tqi::rule<Iterator, double(), qi::space_type> expr, term, fact;\n};\n\n/*\n * \n */\nint main(int argc, char** argv) {\n\tstring input;\n\tint output;\n\n\tgetline(cin, input);\n\tauto begin = input.begin();\n\tauto end = input.end();\n\n\tadvanced_calc_grammar<decltype(begin) > grammar;\n\tbool success = qi::phrase_parse(begin,\n\t\tend,\n\t\tgrammar,\n\t\tqi::space,\n\t\toutput);\n\n\tif (success) {\n\t\tcout << \"Matched. Result=\" << output << endl;\n\t} else {\n\t\tcout << \"Error!\" << endl;\n\t}\n\n\treturn 0;\n}\n\n", "meta": {"hexsha": "d48f956679f4280f40d5f6c49eb1fefb31690bea", "size": 3008, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "ChristophWurst/GP2_UE02_Ex2", "max_stars_repo_head_hexsha": "1e3cc35a36be2b2053c0ab9b8f74e6511c781ba2", "max_stars_repo_licenses": ["MIT"], "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": "ChristophWurst/GP2_UE02_Ex2", "max_issues_repo_head_hexsha": "1e3cc35a36be2b2053c0ab9b8f74e6511c781ba2", "max_issues_repo_licenses": ["MIT"], "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": "ChristophWurst/GP2_UE02_Ex2", "max_forks_repo_head_hexsha": "1e3cc35a36be2b2053c0ab9b8f74e6511c781ba2", "max_forks_repo_licenses": ["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.3454545455, "max_line_length": 80, "alphanum_fraction": 0.6379654255, "num_tokens": 792, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.4533158500356755}}
{"text": "#ifndef MOCHIMOCHI_BINARY_OML_INTERFACE_HPP_\n#define MOCHIMOCHI_BINARY_OML_INTERFACE_HPP_\n\n#include <string>\n#include <Eigen/Dense>\n\nusing namespace std;\n\n/**\n * The BinaryOML interface declares the operations that all concrete BinaryOML must implement.\n */\nclass BinaryOML {\n public:\n  virtual ~BinaryOML() {}\n  virtual bool update(const Eigen::VectorXd& feature, const int label) = 0;\n  virtual int predict(const Eigen::VectorXd& x) const = 0;\n  virtual void save(const string& filename) = 0;\n  virtual void load(const string& filename) = 0;\n  virtual string name() const = 0;\n};\n\n#endif", "meta": {"hexsha": "b68f950cc0892bfd8e1791bea6b7bf1466562f69", "size": 589, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "mochimochi/classifier/factory/binary_oml.hpp", "max_stars_repo_name": "georgeslabreche/MochiMochi", "max_stars_repo_head_hexsha": "6ed0e8e078504a068a812735567d196f5d88e69f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mochimochi/classifier/factory/binary_oml.hpp", "max_issues_repo_name": "georgeslabreche/MochiMochi", "max_issues_repo_head_hexsha": "6ed0e8e078504a068a812735567d196f5d88e69f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mochimochi/classifier/factory/binary_oml.hpp", "max_forks_repo_name": "georgeslabreche/MochiMochi", "max_forks_repo_head_hexsha": "6ed0e8e078504a068a812735567d196f5d88e69f", "max_forks_repo_licenses": ["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.7727272727, "max_line_length": 94, "alphanum_fraction": 0.7504244482, "num_tokens": 146, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.6513548714339144, "lm_q1q2_score": 0.4533158453255269}}
{"text": "//=======================================================================\n// Copyright 1997-2001 University of Notre Dame.\n// Authors: Andrew Lumsdaine, Lie-Quan Lee, Jeremy G. Siek\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n\n#include <boost/config.hpp>\n#include <iostream>\n#include <vector>\n#include <boost/graph/strong_components.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/graphviz.hpp>\n#include <boost/graph/graph_utility.hpp>\n/*\n  Sample output:\n  A directed graph:\n  a --> b f h \n  b --> c a \n  c --> d b \n  d --> e \n  e --> d \n  f --> g \n  g --> f d \n  h --> i \n  i --> h j e c \n  j --> \n\n  Total number of components: 4\n  Vertex a is in component 3\n  Vertex b is in component 3\n  Vertex c is in component 3\n  Vertex d is in component 0\n  Vertex e is in component 0\n  Vertex f is in component 1\n  Vertex g is in component 1\n  Vertex h is in component 3\n  Vertex i is in component 3\n  Vertex j is in component 2\n */\n\nint main(int, char*[])\n{\n  using namespace boost;\n  const char* name = \"abcdefghij\";\n\n  GraphvizDigraph G;\n  read_graphviz(\"scc.dot\", G);\n\n  std::cout << \"A directed graph:\" << std::endl;\n  print_graph(G, name);\n  std::cout << std::endl;\n\n  typedef graph_traits<GraphvizGraph>::vertex_descriptor Vertex;\n    \n  std::vector<int> component(num_vertices(G)), discover_time(num_vertices(G));\n  std::vector<default_color_type> color(num_vertices(G));\n  std::vector<Vertex> root(num_vertices(G));\n  int num = strong_components(G, &component[0], \n                              root_map(&root[0]).\n                              color_map(&color[0]).\n                              discover_time_map(&discover_time[0]));\n    \n  std::cout << \"Total number of components: \" << num << std::endl;\n  std::vector<int>::size_type i;\n  for (i = 0; i != component.size(); ++i)\n    std::cout << \"Vertex \" << name[i]\n         <<\" is in component \" << component[i] << std::endl;\n    \n  return 0;\n}\n", "meta": {"hexsha": "4b01f88624bb584a3b4e6930905fa49bb73e9770", "size": 2114, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/graph/example/strong_components.cpp", "max_stars_repo_name": "mike-code/boost_1_38_0", "max_stars_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-07-31T13:56:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-13T02:55:10.000Z", "max_issues_repo_path": "libs/graph/example/strong_components.cpp", "max_issues_repo_name": "boost-cmake/vintage", "max_issues_repo_head_hexsha": "dcfb7da3177134eddaee6789d6f582259cb0d6ee", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-01-17T10:11:43.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-17T10:11:43.000Z", "max_forks_repo_path": "libs/graph/example/strong_components.cpp", "max_forks_repo_name": "boost-cmake/vintage", "max_forks_repo_head_hexsha": "dcfb7da3177134eddaee6789d6f582259cb0d6ee", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2021-08-31T14:34:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-19T08:25:58.000Z", "avg_line_length": 28.5675675676, "max_line_length": 78, "alphanum_fraction": 0.5860927152, "num_tokens": 548, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334525, "lm_q2_score": 0.6513548714339144, "lm_q1q2_score": 0.4533158453255268}}
{"text": "#pragma once\n\n#include \"common.hpp\"\n#include \"variant.hpp\"\n\n#include <set>\n#include <optional>\n#include <vector>\n#include <random>\n\n#include <boost/range.hpp>\n\n// Mostly stuff for simple property-based testing\n\nnamespace ckvs { namespace utils {\n\ntemplate <typename ContainterT,\n          typename IterT   = decltype(std::begin(std::declval<ContainterT &>())),\n          typename ResultT = std::vector<boost::iterator_range<IterT>>>\nauto split_to_random_parts(ContainterT && v, const size_t nParts, std::default_random_engine & gen)\n  -> std::optional<ResultT>\n{\n  std::optional<ResultT> result{std::nullopt};\n  if(nParts > std::size(v))\n    return result;\n\n  result = ResultT{};\n  std::set<size_t> random_cuts;\n\n  std::uniform_int_distribution<size_t> rnd{1ull, std::size(v) - 1};\n  while(std::size(random_cuts) != nParts - 1)\n    random_cuts.emplace(rnd(gen));\n\n  result->reserve(nParts);\n\n  auto to_iter = [&v](const size_t idx) {\n    auto result = std::begin(v);\n    std::advance(result, idx);\n    return result;\n  };\n\n  size_t prev_cut = 0;\n  for(const auto cut_point : random_cuts)\n  {\n    result->emplace_back(to_iter(prev_cut), to_iter(cut_point));\n    prev_cut = cut_point;\n  }\n  result->emplace_back(to_iter(prev_cut), std::end(v));\n\n  return result;\n}\n\ntemplate <\n  typename T,\n  typename = std::enable_if_t<std::is_arithmetic_v<T>>,\n  typename DisT =\n    std::conditional_t<std::is_floating_point_v<T>, std::uniform_real_distribution<T>, std::uniform_int_distribution<T>>>\nvoid random_value(T & val, std::default_random_engine & gen)\n{\n  DisT dis(std::numeric_limits<T>::min(), std::numeric_limits<T>::max() - 1);\n  val = dis(gen);\n}\n\ninline void random_value(const size_t                 min_length,\n                         const size_t                 max_length,\n                         std::string &                s,\n                         std::default_random_engine & gen)\n{\n  const size_t len = std::uniform_int_distribution<size_t>{min_length, max_length}(gen);\n\n  std::uniform_int_distribution<short> char_gen{32, 126};\n  s.resize(len);\n  for(char & c : s)\n    while(!isalnum(c = static_cast<char>(char_gen(gen))))\n      continue;\n}\n\ntemplate <typename VariantT>\nvoid random_variant(VariantT & var, const size_t max_binary_size, std::default_random_engine & gen)\n{\n  default_init_variant(var, gen() % std::variant_size_v<VariantT>);\n  std::visit(overloaded{[&](auto && val) { random_value(val, gen); },\n                        [&](std::string & str) { random_value(1ull, max_binary_size, str, gen); }},\n             var);\n}\n\ninline uint64_t fast_thread_local_rand(const uint64_t min, const uint64_t max)\n{\n  thread_local static std::default_random_engine              gen{std::random_device{}()};\n  thread_local static std::uniform_int_distribution<uint64_t> rnd;\n  using range_t = std::uniform_int_distribution<uint64_t>::param_type;\n  return rnd(gen, range_t{min, max});\n}\n\n\n}}", "meta": {"hexsha": "42abb33fc734ef03e7d5d2f717f2e8cdcd200c7f", "size": 2904, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/ckvs/utils/random.hpp", "max_stars_repo_name": "yuyoyuppe/ckvs", "max_stars_repo_head_hexsha": "ea3da2ad243ab9ee6252d56488034c4f28141e75", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-11-04T10:43:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-10T16:23:58.000Z", "max_issues_repo_path": "src/ckvs/utils/random.hpp", "max_issues_repo_name": "yuyoyuppe/ckvs", "max_issues_repo_head_hexsha": "ea3da2ad243ab9ee6252d56488034c4f28141e75", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ckvs/utils/random.hpp", "max_forks_repo_name": "yuyoyuppe/ckvs", "max_forks_repo_head_hexsha": "ea3da2ad243ab9ee6252d56488034c4f28141e75", "max_forks_repo_licenses": ["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.25, "max_line_length": 121, "alphanum_fraction": 0.6676997245, "num_tokens": 733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583124210897, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.45331584182055146}}
{"text": "//=======================================================================\r\n// Copyright 2000 University of Notre Dame.\r\n// Authors: Jeremy G. Siek, Andrew Lumsdaine, Lie-Quan Lee\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 EDMUNDS_KARP_MAX_FLOW_HPP\r\n#define EDMUNDS_KARP_MAX_FLOW_HPP\r\n\r\n#include <boost/config.hpp>\r\n#include <vector>\r\n#include <algorithm> // for std::min and std::max\r\n#include <boost/config.hpp>\r\n#include <boost/pending/queue.hpp>\r\n#include <boost/property_map.hpp>\r\n#include <boost/graph/graph_traits.hpp>\r\n#include <boost/graph/properties.hpp>\r\n#include <boost/graph/filtered_graph.hpp>\r\n#include <boost/graph/breadth_first_search.hpp>\r\n\r\nnamespace boost {\r\n\r\n  // The \"labeling\" algorithm from \"Network Flows\" by Ahuja, Magnanti,\r\n  // Orlin.  I think this is the same as or very similar to the original\r\n  // Edmunds-Karp algorithm.  This solves the maximum flow problem.\r\n\r\n  namespace detail {\r\n\r\n    template <class Graph, class ResCapMap>\r\n    filtered_graph<Graph, is_residual_edge<ResCapMap> >\r\n    residual_graph(Graph& g, ResCapMap residual_capacity) {\r\n      return filtered_graph<Graph, is_residual_edge<ResCapMap> >\r\n        (g, is_residual_edge<ResCapMap>(residual_capacity));\r\n    }\r\n\r\n    template <class Graph, class PredEdgeMap, class ResCapMap,\r\n              class RevEdgeMap>\r\n    inline void\r\n    augment(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 = p[sink];\r\n      do {\r\n        BOOST_USING_STD_MIN();\r\n        delta = min BOOST_PREVENT_MACRO_SUBSTITUTION(delta, residual_capacity[e]);\r\n        u = source(e, g);\r\n        e = p[u];\r\n      } while (u != src);\r\n\r\n      // push delta units of flow along the augmenting path\r\n      e = p[sink];\r\n      do {\r\n        residual_capacity[e] -= delta;\r\n        residual_capacity[reverse_edge[e]] += delta;\r\n        u = source(e, g);\r\n        e = p[u];\r\n      } while (u != src);\r\n    }\r\n\r\n  } // namespace detail\r\n\r\n  template <class Graph, \r\n            class CapacityEdgeMap, class ResidualCapacityEdgeMap,\r\n            class ReverseEdgeMap, class ColorMap, class PredEdgeMap>\r\n  typename property_traits<CapacityEdgeMap>::value_type\r\n  edmunds_karp_max_flow\r\n    (Graph& g, \r\n     typename graph_traits<Graph>::vertex_descriptor src,\r\n     typename graph_traits<Graph>::vertex_descriptor sink,\r\n     CapacityEdgeMap cap, \r\n     ResidualCapacityEdgeMap res,\r\n     ReverseEdgeMap rev, \r\n     ColorMap color, \r\n     PredEdgeMap pred)\r\n  {\r\n    typedef typename graph_traits<Graph>::vertex_descriptor vertex_t;\r\n    typedef typename property_traits<ColorMap>::value_type ColorValue;\r\n    typedef color_traits<ColorValue> Color;\r\n    \r\n    typename graph_traits<Graph>::vertex_iterator u_iter, u_end;\r\n    typename graph_traits<Graph>::out_edge_iterator ei, e_end;\r\n    for (tie(u_iter, u_end) = vertices(g); u_iter != u_end; ++u_iter)\r\n      for (tie(ei, e_end) = out_edges(*u_iter, g); ei != e_end; ++ei)\r\n        res[*ei] = cap[*ei];\r\n    \r\n    color[sink] = Color::gray();\r\n    while (color[sink] != Color::white()) {\r\n      boost::queue<vertex_t> Q;\r\n      breadth_first_search\r\n        (detail::residual_graph(g, res), src, Q,\r\n         make_bfs_visitor(record_edge_predecessors(pred, on_tree_edge())),\r\n         color);\r\n      if (color[sink] != Color::white())\r\n        detail::augment(g, src, sink, pred, res, rev);\r\n    } // while\r\n    \r\n    typename property_traits<CapacityEdgeMap>::value_type flow = 0;\r\n    for (tie(ei, e_end) = out_edges(src, g); ei != e_end; ++ei)\r\n      flow += (cap[*ei] - res[*ei]);\r\n    return flow;\r\n  } // edmunds_karp_max_flow()\r\n  \r\n  namespace detail {\r\n    //-------------------------------------------------------------------------\r\n    // Handle default for color property map\r\n\r\n    // use of class here is a VC++ workaround\r\n    template <class ColorMap>\r\n    struct edmunds_karp_dispatch2 {\r\n      template <class Graph, class PredMap, class P, class T, class R>\r\n      static typename edge_capacity_value<Graph, P, T, R>::type\r\n      apply\r\n      (Graph& g,\r\n       typename graph_traits<Graph>::vertex_descriptor src,\r\n       typename graph_traits<Graph>::vertex_descriptor sink,\r\n       PredMap pred,\r\n       const bgl_named_params<P, T, R>& params,\r\n       ColorMap color)\r\n      {\r\n        return edmunds_karp_max_flow\r\n          (g, src, sink, \r\n           choose_const_pmap(get_param(params, edge_capacity), g, edge_capacity),\r\n           choose_pmap(get_param(params, edge_residual_capacity), \r\n                       g, edge_residual_capacity),\r\n           choose_const_pmap(get_param(params, edge_reverse), g, edge_reverse),\r\n           color, pred);\r\n      }\r\n    };\r\n    template<>\r\n    struct edmunds_karp_dispatch2<detail::error_property_not_found> {\r\n      template <class Graph, class PredMap, class P, class T, class R>\r\n      static typename edge_capacity_value<Graph, P, T, R>::type\r\n      apply\r\n      (Graph& g,\r\n       typename graph_traits<Graph>::vertex_descriptor src,\r\n       typename graph_traits<Graph>::vertex_descriptor sink,\r\n       PredMap pred,\r\n       const bgl_named_params<P, T, R>& params,\r\n       detail::error_property_not_found)\r\n      {\r\n        typedef typename graph_traits<Graph>::edge_descriptor edge_descriptor;\r\n        typedef typename graph_traits<Graph>::vertices_size_type size_type;\r\n        size_type n = is_default_param(get_param(params, vertex_color)) ?\r\n          num_vertices(g) : 1;\r\n        std::vector<default_color_type> color_vec(n);\r\n        return edmunds_karp_max_flow\r\n          (g, src, sink, \r\n           choose_const_pmap(get_param(params, edge_capacity), g, edge_capacity),\r\n           choose_pmap(get_param(params, edge_residual_capacity), \r\n                       g, edge_residual_capacity),\r\n           choose_const_pmap(get_param(params, edge_reverse), g, edge_reverse),\r\n           make_iterator_property_map(color_vec.begin(), choose_const_pmap\r\n                                      (get_param(params, vertex_index),\r\n                                       g, vertex_index), color_vec[0]),\r\n           pred);\r\n      }\r\n    };\r\n\r\n    //-------------------------------------------------------------------------\r\n    // Handle default for predecessor property map\r\n\r\n    // use of class here is a VC++ workaround\r\n    template <class PredMap>\r\n    struct edmunds_karp_dispatch1 {\r\n      template <class Graph, class P, class T, class R>\r\n      static typename edge_capacity_value<Graph, P, T, R>::type\r\n      apply(Graph& g,\r\n            typename graph_traits<Graph>::vertex_descriptor src,\r\n            typename graph_traits<Graph>::vertex_descriptor sink,\r\n            const bgl_named_params<P, T, R>& params,\r\n            PredMap pred)\r\n      {\r\n        typedef typename property_value< bgl_named_params<P,T,R>, vertex_color_t>::type C;\r\n        return edmunds_karp_dispatch2<C>::apply\r\n          (g, src, sink, pred, params, get_param(params, vertex_color));\r\n      }\r\n    };\r\n    template<>\r\n    struct edmunds_karp_dispatch1<detail::error_property_not_found> {\r\n\r\n      template <class Graph, class P, class T, class R>\r\n      static typename edge_capacity_value<Graph, P, T, R>::type\r\n      apply\r\n      (Graph& g,\r\n       typename graph_traits<Graph>::vertex_descriptor src,\r\n       typename graph_traits<Graph>::vertex_descriptor sink,\r\n       const bgl_named_params<P, T, R>& params,\r\n       detail::error_property_not_found)\r\n      {\r\n        typedef typename graph_traits<Graph>::edge_descriptor edge_descriptor;\r\n        typedef typename graph_traits<Graph>::vertices_size_type size_type;\r\n        size_type n = is_default_param(get_param(params, vertex_predecessor)) ?\r\n          num_vertices(g) : 1;\r\n        std::vector<edge_descriptor> pred_vec(n);\r\n        \r\n        typedef typename property_value< bgl_named_params<P,T,R>, vertex_color_t>::type C;\r\n        return edmunds_karp_dispatch2<C>::apply\r\n          (g, src, sink, \r\n           make_iterator_property_map(pred_vec.begin(), choose_const_pmap\r\n                                      (get_param(params, vertex_index),\r\n                                       g, vertex_index), pred_vec[0]),\r\n           params, \r\n           get_param(params, vertex_color));\r\n      }\r\n    };\r\n    \r\n  } // namespace detail\r\n\r\n  template <class Graph, class P, class T, class R>\r\n  typename detail::edge_capacity_value<Graph, P, T, R>::type\r\n  edmunds_karp_max_flow\r\n    (Graph& g,\r\n     typename graph_traits<Graph>::vertex_descriptor src,\r\n     typename graph_traits<Graph>::vertex_descriptor sink,\r\n     const bgl_named_params<P, T, R>& params)\r\n  {\r\n    typedef typename property_value< bgl_named_params<P,T,R>, vertex_predecessor_t>::type Pred;\r\n    return detail::edmunds_karp_dispatch1<Pred>::apply\r\n      (g, src, sink, params, get_param(params, vertex_predecessor));\r\n  }\r\n\r\n  template <class Graph>\r\n  typename property_traits<\r\n    typename property_map<Graph, edge_capacity_t>::const_type\r\n  >::value_type\r\n  edmunds_karp_max_flow\r\n    (Graph& g,\r\n     typename graph_traits<Graph>::vertex_descriptor src,\r\n     typename graph_traits<Graph>::vertex_descriptor sink)\r\n  {\r\n    bgl_named_params<int, buffer_param_t> params(0);\r\n    return edmunds_karp_max_flow(g, src, sink, params);\r\n  }\r\n\r\n} // namespace boost\r\n\r\n#endif // EDMUNDS_KARP_MAX_FLOW_HPP\r\n", "meta": {"hexsha": "40d888ac5bc967781bbdf6dd2989c14158fa3fdd", "size": 9979, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/graph/edmunds_karp_max_flow.hpp", "max_stars_repo_name": "dstrigl/mcotf", "max_stars_repo_head_hexsha": "92a9caf6173b1241a2f9ed45cd379469762b7178", "max_stars_repo_licenses": ["BSL-1.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": "include/boost/graph/edmunds_karp_max_flow.hpp", "max_issues_repo_name": "dstrigl/mcotf", "max_issues_repo_head_hexsha": "92a9caf6173b1241a2f9ed45cd379469762b7178", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/graph/edmunds_karp_max_flow.hpp", "max_forks_repo_name": "dstrigl/mcotf", "max_forks_repo_head_hexsha": "92a9caf6173b1241a2f9ed45cd379469762b7178", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.7569721116, "max_line_length": 96, "alphanum_fraction": 0.6259144203, "num_tokens": 2265, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.45331584061537833}}
{"text": "#include \"scheme/nest/pmap/UnitMap.hh\"\n#include \"scheme/nest/pmap/ScaleMap.hh\"\n#include \"scheme/nest/pmap/DiscreteChoiceMap.hh\"\n#include \"scheme/nest/NEST.hh\"\n#include \"scheme/nest/NEST_test_util.hh\"\n#include <gtest/gtest.h>\n#include <boost/assign/std/vector.hpp> // for 'operator+=()'\n#include <random>\n#include <boost/foreach.hpp>\n\nnamespace scheme {\nnamespace nest {\nnamespace pmap {\n\n\nusing std::cout;\nusing std::endl;\n\nusing scheme::nest::StorePointer;\n\n\nTEST(NEST_ScaleMap,particular_values){\n\t{\n\t\ttypedef util::SimpleArray<1,double> VAL;\n\t\tVAL lb, ub;\n\t\tutil::SimpleArray<1,size_t> bs;\n\t\tlb = -16.0;\n\t\tub =  16.0;\n\t\tbs = 1;\n\t\tNEST<1,VAL,ScaleMap> nest1(lb,ub,bs);\n\t\tbs = 2;\n\t\tNEST<1,VAL,ScaleMap> nest2(lb,ub,bs);\n\t\tASSERT_EQ( nest1.set_and_get(0,0)[0],  0.0 );\n\t\tASSERT_EQ( nest1.set_and_get(0,1)[0], -8.0 );\n\t\tASSERT_EQ( nest1.set_and_get(1,1)[0],  8.0 );\n\n\t\tASSERT_EQ( nest2.set_and_get(0,0)[0], -8.0 );\n\t\tASSERT_EQ( nest2.set_and_get(1,0)[0],  8.0 );\t\n\t\tASSERT_EQ( nest2.set_and_get(0,1)[0],-12.0 );\n\t\tASSERT_EQ( nest2.set_and_get(1,1)[0], -4.0 );\t\n\t\tASSERT_EQ( nest2.set_and_get(2,1)[0],  4.0 );\n\t\tASSERT_EQ( nest2.set_and_get(3,1)[0], 12.0 );\t\n\t}\n\t{\n\t\ttypedef util::SimpleArray<2,double> VAL;\n\t\tutil::SimpleArray<2,double> lb(-16.0,-24), ub(16.0, 24);\n\t\tutil::SimpleArray<2,size_t> bs(2,3);\n\t\tNEST<2,VAL,ScaleMap> nest(lb,ub,bs);\n\t\tASSERT_EQ( nest.set_and_get(0,0), VAL(-8,-16) );\n\t\tASSERT_EQ( nest.set_and_get(1,0), VAL( 8,-16) );\t\n\t\tASSERT_EQ( nest.set_and_get(2,0), VAL(-8,  0) );\n\t\tASSERT_EQ( nest.set_and_get(3,0), VAL( 8,  0) );\t\n\t\tASSERT_EQ( nest.set_and_get(4,0), VAL(-8, 16) );\n\t\tASSERT_EQ( nest.set_and_get(5,0), VAL( 8, 16) );\n\t\tASSERT_EQ( nest.set_and_get(0,1), VAL(-12,-20) );\n\t\tASSERT_EQ( nest.set_and_get(1,1), VAL( -4,-20) );\n\t\tASSERT_EQ( nest.set_and_get(2,1), VAL(-12,-12) );\n\t\tASSERT_EQ( nest.set_and_get(3,1), VAL( -4,-12) );\n\t\tASSERT_EQ( nest.set_and_get(0,2), VAL(-14,-22) );\n\t\tASSERT_EQ( nest.set_and_get(1,2), VAL(-10,-22) );\n\t\tASSERT_EQ( nest.set_and_get(2,2), VAL(-14,-18) );\n\t\tASSERT_EQ( nest.set_and_get(3,2), VAL(-10,-18) );\n\t\tASSERT_EQ( nest.set_and_get(0,3), VAL(-15,-23) );\n\t\tASSERT_EQ( nest.set_and_get(1,3), VAL(-13,-23) );\n\t\tASSERT_EQ( nest.set_and_get(2,3), VAL(-15,-21) );\n\t\tASSERT_EQ( nest.set_and_get(3,3), VAL(-13,-21) );\n\t\tASSERT_EQ( nest.set_and_get(5*64+60,3), VAL(13,21) );\n\t\tASSERT_EQ( nest.set_and_get(5*64+61,3), VAL(15,21) );\n\t\tASSERT_EQ( nest.set_and_get(5*64+62,3), VAL(13,23) );\n\t\tASSERT_EQ( nest.set_and_get(5*64+63,3), VAL(15,23) );\n\t\t// cout << VAL(0,0) << endl;\n\t}\n}\n\n\nTEST(UnitMap,value_to_params_for_cell){\n\ttypedef UnitMap<2> MapType;\n\tMapType umap(3);\n\tMapType::Params params;\n\n\tumap.value_to_params_for_cell( MapType::ValueType(1.5,0.5), 0, params, 0  );\n\tASSERT_EQ( params[0], 1.5 );\n\tASSERT_EQ( params[1], 0.5 );\n\n\tumap.value_to_params_for_cell( MapType::ValueType(1.5,0.5), 0, params, 1  );\n\tASSERT_EQ( params[0], 0.5 );\n\tASSERT_EQ( params[1], 0.5 );\n\n\tumap.value_to_params_for_cell( MapType::ValueType(1.5,0.5), 0, params, 2  );\n\tASSERT_EQ( params[0], -0.5 );\n\tASSERT_EQ( params[1],  0.5 );\n\n\tumap.value_to_params_for_cell( MapType::ValueType(0.2,0.5), 0, params, 2  );\n\tASSERT_EQ( params[0], -1.8 );\n\tASSERT_EQ( params[1],  0.5 );\n}\n\nTEST(ScaleMap,value_to_params_for_cell){\n\t{\n\t\ttypedef ScaleMap<2> MapType;\n\t\tMapType smap(\n\t\t\tMapType::Params(0,0),\n\t\t\tMapType::Params(4,4),\n\t\t\tMapType::Indices(4,4)\n\t\t);\n\n\t\tMapType::Params params;\n\n\t\tsmap.value_to_params_for_cell( MapType::ValueType(1.5,0.5), 0, params, smap.indices_to_cellindex(MapType::Indices(0,0)) );\n\t\tASSERT_EQ( params[0], 1.5 );\n\t\tASSERT_EQ( params[1], 0.5 );\n\n\t\tsmap.value_to_params_for_cell( MapType::ValueType(1.5,0.5), 0, params, smap.indices_to_cellindex(MapType::Indices(1,0)) );\n\t\tASSERT_EQ( params[0], 0.5 );\n\t\tASSERT_EQ( params[1], 0.5 );\n\n\t\tsmap.value_to_params_for_cell( MapType::ValueType(1.5,0.5), 0, params, smap.indices_to_cellindex(MapType::Indices(0,1)) );\n\t\tASSERT_EQ( params[0],  1.5 );\n\t\tASSERT_EQ( params[1], -0.5 );\n\n\t\tsmap.value_to_params_for_cell( MapType::ValueType(1.5,0.5), 0, params, smap.indices_to_cellindex(MapType::Indices(2,0)) );\n\t\tASSERT_EQ( params[0],-0.5 );\n\t\tASSERT_EQ( params[1], 0.5 );\n\n\t\tsmap.value_to_params_for_cell( MapType::ValueType(1.5,0.5), 0, params, smap.indices_to_cellindex(MapType::Indices(1,2)) );\n\t\tASSERT_EQ( params[0],  0.5 );\n\t\tASSERT_EQ( params[1], -1.5 );\n\n\t\tsmap.value_to_params_for_cell( MapType::ValueType(1.5,0.5), 0, params, smap.indices_to_cellindex(MapType::Indices(3,3)) );\n\t\tASSERT_EQ( params[0], -1.5 );\n\t\tASSERT_EQ( params[1], -2.5 );\n\t}\n\t{\n\t\ttypedef ScaleMap<2> MapType;\n\t\tdouble scale = 2.0;\n\t\tMapType::Params shift(0.597,1.1243);\n\t\tMapType smap(\n\t\t\tMapType::Params(0.0,0.0)*scale-shift,\n\t\t\tMapType::Params(4.0,4.0)*scale-shift,\n\t\t\tMapType::Indices(4,4)\n\t\t);\n\n\t\tMapType::Params params;\n\n\t\tsmap.value_to_params_for_cell( MapType::ValueType(1.5*scale-shift[0],0.5*scale-shift[1]), 0, params, smap.indices_to_cellindex(MapType::Indices(0,0)) );\n\t\tASSERT_EQ( params[0], 1.5 );\n\t\tASSERT_EQ( params[1], 0.5 );\n\n\t\tsmap.value_to_params_for_cell( MapType::ValueType(1.5*scale-shift[0],0.5*scale-shift[1]), 0, params, smap.indices_to_cellindex(MapType::Indices(1,0)) );\n\t\tASSERT_EQ( params[0], 0.5 );\n\t\tASSERT_EQ( params[1], 0.5 );\n\n\t\tsmap.value_to_params_for_cell( MapType::ValueType(1.5*scale-shift[0],0.5*scale-shift[1]), 0, params, smap.indices_to_cellindex(MapType::Indices(0,1)) );\n\t\tASSERT_EQ( params[0],  1.5 );\n\t\tASSERT_EQ( params[1], -0.5 );\n\n\t\tsmap.value_to_params_for_cell( MapType::ValueType(1.5*scale-shift[0],0.5*scale-shift[1]), 0, params, smap.indices_to_cellindex(MapType::Indices(2,0)) );\n\t\tASSERT_EQ( params[0],-0.5 );\n\t\tASSERT_EQ( params[1], 0.5 );\n\n\t\tsmap.value_to_params_for_cell( MapType::ValueType(1.5*scale-shift[0],0.5*scale-shift[1]), 0, params, smap.indices_to_cellindex(MapType::Indices(1,2)) );\n\t\tASSERT_EQ( params[0],  0.5 );\n\t\tASSERT_EQ( params[1], -1.5 );\n\n\t\tsmap.value_to_params_for_cell( MapType::ValueType(1.5*scale-shift[0],0.5*scale-shift[1]), 0, params, smap.indices_to_cellindex(MapType::Indices(3,3)) );\n\t\tASSERT_EQ( params[0], -1.5 );\n\t\tASSERT_EQ( params[1], -2.5 );\n\t}\n}\n\n\n\n\n\ntemplate<int DIM>\nvoid test_index_lookup_scaled(){\n\ttypedef util::SimpleArray<DIM,double> VAL;\n\tutil::SimpleArray<10,double> lb0(-1.3,2.2,0,-3,-5,-9.9,1.3,44,-13.3,99);\n\tutil::SimpleArray<10,double> ub0(1.3,4.2,1,10,-3, 9.9,4.3,44, 13.3,199);\n\tutil::SimpleArray<10,size_t> bs0(2,1,2,3,4,5,6,7,8,9);\n\n\ttypedef util::SimpleArray<DIM,double> VAL;\n\tVAL lb, ub;\n\tutil::SimpleArray<DIM,size_t> bs;\n\tfor(size_t i = 0; i < DIM; ++i){\n\t\tlb[i] = lb0[i]; ub[i] = ub0[i]; bs[i] = bs0[i];\n\t}\n\tNEST<DIM,VAL,ScaleMap,StoreValue> nest(lb,ub,bs);\n\tsize_t rmax = 6/DIM;\n\tfor(size_t r = 0; r <= rmax; ++r){\n\t\tfor(size_t i = 0; i < nest.size(r); ++i){\n\t\t\tASSERT_TRUE( nest.set_state(i,r) );\n\t\t\tVAL value = nest.value();\n\t\t\tsize_t index = nest.get_index(value,r);\n\t\t\tASSERT_EQ( i, index );\n\t\t\tfor(size_t r2 = 0; r2 <= r; ++r2){\n\t\t\t\tsize_t index2 = nest.get_index(value,r2);\n\t\t\t\tASSERT_EQ( i>>(DIM*(r-r2)), index2 );\n\t\t\t}\n\t\t}\n\t}\n}\n\nTEST(NEST_ScaleMap,index_lookup_scaled){\n\ttest_index_lookup_scaled<1>();\n\ttest_index_lookup_scaled<2>();\n\ttest_index_lookup_scaled<3>();\n\ttest_index_lookup_scaled<4>();\n\ttest_index_lookup_scaled<5>();\n\ttest_index_lookup_scaled<6>();\n}\n\n\ntemplate<int DIM>\nvoid test_map_scale_bounds(){\n\tBOOST_STATIC_ASSERT((DIM<10));\n\tutil::SimpleArray<10,double> lb0(-1.3,2.2,0,-3,-5,-9.9,1.3,44,-13.3,99),ub0(1.3,4.2,1,10,-3, 9.9,4.3,44, 13.3,199);\n\tutil::SimpleArray<10,size_t> bs0(1,2,3,4,5,6,7,8,9,10);\n\n\ttypedef util::SimpleArray<DIM,double> VAL;\n\tVAL lb, ub;\n\tutil::SimpleArray<DIM,size_t> bs;\n\tfor(size_t i = 0; i < DIM; ++i){\n\t\tlb[i] = lb0[i]; ub[i] = ub0[i]; bs[i] = bs0[i];\n\t}\n\tNEST<DIM,VAL,ScaleMap,StoreValue> nest(lb,ub,bs);\n\n\tsize_t resl = 8/DIM;\n\tfor(size_t i = 0; i < nest.size(resl); ++i){\n\t\tASSERT_TRUE( nest.set_state(i,resl) );\n\t\tfor(size_t j = 0; j < DIM; ++j){ \n\t\t\tASSERT_LT( lb[j], nest.value()[j] ); ASSERT_LT( nest.value()[j] , ub[j] );\n\t\t}\n\t\tASSERT_FALSE( nest.set_state(i+nest.size(resl),resl) );\n\t\tfor(size_t j = 0; j < DIM; ++j){ \n\t\t\tASSERT_LT( lb[j], nest.value()[j] ); ASSERT_LT( nest.value()[j] , ub[j] );\n\t\t}\n\t}\n\n}\n\nTEST(NEST_ScaleMap,map_scale){ \n\ttest_map_scale_bounds<1>();\n\ttest_map_scale_bounds<2>();\n\ttest_map_scale_bounds<3>();\n\ttest_map_scale_bounds<4>();\n\ttest_map_scale_bounds<5>();\n\ttest_map_scale_bounds<6>();\n}\n\ntemplate<class NEST>\nvoid test_bin_circumradius(\n\tNEST nest,\n\ttypename NEST::ValueType lb,\n\ttypename NEST::ValueType ub\n){\n    size_t NITER = 10*1000;\n\t#ifdef SCHEME_BENCHMARK\n\tNITER *= 50;\n\t#endif\n\tstd::mt19937 rng((unsigned int)time(0));\n\tstd::uniform_real_distribution<> uniform;\n\ttypename NEST::ValueType randpt;\n\tfor(size_t r = 0; r <= std::min((size_t)10,(size_t)NEST::MAX_RESL_ONE_CELL); ++r){\n\t\tdouble maxdis = 0;\n\t\tfor(size_t iter=0; iter < NITER/NEST::DIMENSION; ++iter){\n\t\t\tfor(size_t i = 0; i < NEST::DIMENSION; ++i) \n\t\t\t\trandpt[i] = uniform(rng)*(ub[i]-lb[i])+lb[i];\n\t\t\tnest.set_state( nest.get_index(randpt,r) ,r);\n\t\t\tdouble dist = (randpt-nest.value()).norm();\n\t\t\t// cout << randpt.transpose() << \" \" << nest.value().transpose() << endl;\n\t\t\tmaxdis = fmax(maxdis,dist);\n\t\t\tASSERT_LE( dist, nest.bin_circumradius(r) );\n\t\t}\n\t\t// covering radius should be reasonably tigth\n\t\t// cout << NEST::DIMENSION << \" \" << r << \" \" << nest.bin_circumradius(r) << \" \" << maxdis << endl;\n\t\tif( nest.bin_circumradius(r)*(1.0-(double)NEST::DIMENSION/20.0) > maxdis ){\n\t\t\tcout << \"WARNING(PROBABILISTIC): covering radius may be too loose DIM=\" << NEST::DIMENSION << \" resl=\" << r << endl;\n\t\t\tcout << \"                        covering radius \" << nest.bin_circumradius(r) << \" max observerd: \" << maxdis << endl;\n\t\t\tcout << \"                        if you see a handful of these, don't worry. if you see lots, then worry\" << endl;\n\t\t}\n\t\t// cout << DIM << \" \" << maxdis << \" \" << nest.bin_circumradius(r) << std::endl;\n\t}\n}\n\nTEST(NEST_UnitMap,NEST_bin_circumradius_unitmap){\n\t{ NEST<1>::ValueType lb,ub; lb.fill(0); ub.fill(1); test_bin_circumradius( NEST<1>(), lb, ub ); }\n\t{ NEST<2>::ValueType lb,ub; lb.fill(0); ub.fill(1); test_bin_circumradius( NEST<2>(), lb, ub ); }\n\t{ NEST<3>::ValueType lb,ub; lb.fill(0); ub.fill(1); test_bin_circumradius( NEST<3>(), lb, ub ); }\n\t{ NEST<4>::ValueType lb,ub; lb.fill(0); ub.fill(1); test_bin_circumradius( NEST<4>(), lb, ub ); }\n\t{ NEST<5>::ValueType lb,ub; lb.fill(0); ub.fill(1); test_bin_circumradius( NEST<5>(), lb, ub ); }\n\t{ NEST<6>::ValueType lb,ub; lb.fill(0); ub.fill(1); test_bin_circumradius( NEST<6>(), lb, ub ); }\n}\n\ntemplate<int DIM>\nvoid test_bin_circumradius_scalemap(){\n\ttypedef NEST<DIM,util::SimpleArray<DIM,double>,ScaleMap> NestType;\n\ttypename NestType::ValueType lb, ub;\n\tfor(size_t i = 0; i < DIM; ++i){\n\t\tlb[i] = -1;\n\t\tub[i] = 1+2*i;\n\t}\n\tNestType nest(lb,ub);\n\ttest_bin_circumradius< NestType >( nest, lb, ub );\n}\n\nTEST(NEST_ScaleMap,NEST_bin_circumradius_scalemap){\n\ttest_bin_circumradius_scalemap<1>();\n\ttest_bin_circumradius_scalemap<2>();\n\ttest_bin_circumradius_scalemap<3>();\n\ttest_bin_circumradius_scalemap<4>();\n\ttest_bin_circumradius_scalemap<5>();\n\ttest_bin_circumradius_scalemap<6>();\n}\n\ntemplate<class NestType>\nvoid test_coverage_random_ScaleMap(){\n    size_t NITER = 1*1000;\n    double FUDGE = 0.06;\n\t#ifdef SCHEME_BENCHMARK\n\tNITER *= 50;\n\tFUDGE = 0.03;\n\t#endif\n\n\tstd::mt19937 rng((unsigned int)time(0));\n\tstd::uniform_real_distribution<> uniform;\n\t\n\t// set up random bounds\n\ttypename NestType::Params lb,ub;\n\ttypename NestType::Indices cs;\n\tfor(size_t i = 0; i < NestType::DIMENSION; ++i){\n\t\tdouble b1 = uniform(rng)*20.0 - 10.0;\n\t\tdouble b2 = uniform(rng)*20.0 - 10.0;\n\t\tlb[i] = std::min(b1,b2);\n\t\tub[i] = std::max(b1,b2);\n\t\tcs[i] = (typename NestType::IndexType)(uniform(rng)*3.999) + 1;\n\t\tassert(lb[i] < ub[i]);\n\t\tassert(cs[i] > 0);\n\t}\n\t// cout << \"LB \" << lb.transpose() << endl;\n\t// cout << \"UB \" << ub.transpose() << endl;\t\n\t// cout << \"CS \" << cs.transpose() << endl;\t\t\n\n\tNestType nest(lb,ub,cs);\n\tsize_t max_resl = std::min((size_t)10,(size_t)NestType::MAX_RESL_ONE_CELL-2); // -2 because we set cs up to 4 per dimension\n\tstd::vector<double> largest_d2_for_r(max_resl+1,0.0);\n\tfor(size_t i = 0; i < NITER; ++i){\n\n\t\t// set up random value within bounds\n\t\ttypename NestType::ValueType val;\n\t\tfor(size_t j = 0; j < NestType::DIMENSION; ++j){\n\t\t\tval[j] = (ub[j]-lb[j])*uniform(rng) + lb[j];\n\t\t\tassert(lb[j] <= val[j]);\n\t\t\tassert(ub[j] >= val[j]);\n\t\t}\n\n\n\t\t// run generic coverage test\n\t\tgeneric_test_coverage_of_value( nest, val, largest_d2_for_r, max_resl );\n\n\t}\n\tfor(size_t r = 0; r <= max_resl; ++r){\n\t\t// cout << r << \" \" << largest_d2_for_r[r] << endl;\n\t\t// factor of 1.0+0.03*DIM is a *TOTAL* hack, errer does not scale this way by dimension\n\t\t// but it's enough to make sure the curcumradius is reasonably tight\n\t\tASSERT_LT(  nest.bin_circumradius(r), (1.0+FUDGE*(double)NestType::DIMENSION)*sqrt(largest_d2_for_r[r]) );\n\t}\n\n}\n\nTEST(NEST_ScaleMap,test_coverage_DIM_1_to_9){\n\ttest_coverage_random_ScaleMap<  NEST<1,util::SimpleArray<1,double>,ScaleMap>  >();\n\ttest_coverage_random_ScaleMap<  NEST<2,util::SimpleArray<2,double>,ScaleMap>  >();\n\ttest_coverage_random_ScaleMap<  NEST<3,util::SimpleArray<3,double>,ScaleMap>  >();\n\ttest_coverage_random_ScaleMap<  NEST<4,util::SimpleArray<4,double>,ScaleMap>  >();\n\ttest_coverage_random_ScaleMap<  NEST<5,util::SimpleArray<5,double>,ScaleMap>  >();\n\ttest_coverage_random_ScaleMap<  NEST<6,util::SimpleArray<6,double>,ScaleMap>  >();\n\ttest_coverage_random_ScaleMap<  NEST<7,util::SimpleArray<7,double>,ScaleMap>  >();\n\ttest_coverage_random_ScaleMap<  NEST<8,util::SimpleArray<8,double>,ScaleMap>  >();\n\ttest_coverage_random_ScaleMap<  NEST<9,util::SimpleArray<9,double>,ScaleMap>  >();\t\t\t\n}\n\n\n}\n}\n}\n\n", "meta": {"hexsha": "51f45c8cb67537f8c4e8245adab9aca124a58908", "size": 13700, "ext": "cc", "lang": "C++", "max_stars_repo_path": "schemelib/scheme/nest/pmap/parameter_maps.gtest.cc", "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/nest/pmap/parameter_maps.gtest.cc", "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/nest/pmap/parameter_maps.gtest.cc", "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": 35.3092783505, "max_line_length": 154, "alphanum_fraction": 0.6624087591, "num_tokens": 4952, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.4533158406153783}}
{"text": "#include <QApplication>\n#include <QMessageBox>\n#include <QMainWindow>\n#include \"Kernel_type.h\"\n#include \"Polyhedron_type.h\"\n#include \"Scene_polyhedron_item.h\"\n#include \"Scene_polylines_item.h\"\n\n#include <CGAL/Three/Polyhedron_demo_plugin_helper.h>\n#include <CGAL/Three/Polyhedron_demo_plugin_interface.h>\n\n#include <CGAL/Polygon_mesh_processing/stitch_borders.h>\n\n#include <CGAL/boost/graph/split_graph_into_polylines.h>\n#include <CGAL/boost/graph/helpers.h>\n#include <boost/graph/filtered_graph.hpp>\n\ntemplate <typename G>\nstruct Is_border {\n  const G& g;\n  Is_border(const G& g)\n    : g(g)\n  {}\n\n template <typename Descriptor>\n  bool operator()(const Descriptor& d) const {\n   return is_border(d,g);\n  }\n\n  bool operator()(typename boost::graph_traits<G>::vertex_descriptor d) const {\n    return is_border(d,g) != boost::none;\n  }\n\n};\n\n\nusing namespace CGAL::Three;\nclass Polyhedron_demo_polyhedron_stitching_plugin :\n  public QObject,\n  public Polyhedron_demo_plugin_helper\n{\n  Q_OBJECT\n  Q_INTERFACES(CGAL::Three::Polyhedron_demo_plugin_interface)\n  Q_PLUGIN_METADATA(IID \"com.geometryfactory.PolyhedronDemo.PluginInterface/1.0\")\n\n  QAction* actionDetectBorders;\n  QAction* actionStitchBorders;\npublic:\n  QList<QAction*> actions() const { return QList<QAction*>() << actionDetectBorders << actionStitchBorders; }\n  using Polyhedron_demo_plugin_helper::init;\n  void init(QMainWindow* mainWindow, CGAL::Three::Scene_interface* scene_interface, Messages_interface* /* m */)\n  {\n    actionDetectBorders= new QAction(tr(\"Detect Boundaries\"), mainWindow);\n    actionStitchBorders= new QAction(tr(\"Stitch Duplicated Boundaries\"), mainWindow);\n    actionDetectBorders->setObjectName(\"actionDetectBorders\");\n    actionStitchBorders->setObjectName(\"actionStitchBorders\");\n    actionStitchBorders->setProperty(\"subMenuName\", \"Polygon Mesh Processing\");\n    actionDetectBorders->setProperty(\"subMenuName\", \"Polygon Mesh Processing\");\n    Polyhedron_demo_plugin_helper::init(mainWindow, scene_interface);\n  }\n\n  bool applicable(QAction*) const {\n    Q_FOREACH(int index, scene->selectionIndices())\n    {\n      if ( qobject_cast<Scene_polyhedron_item*>(scene->item(index)) )\n        return true;\n    }\n    return false;\n  }\n\npublic Q_SLOTS:\n  void on_actionDetectBorders_triggered();\n  void on_actionStitchBorders_triggered();\n\n}; // end Polyhedron_demo_polyhedron_stitching_plugin\n\n\n\nstruct Polyline_visitor\n{\n  Scene_polylines_item* new_item;\n\n  Polyline_visitor(Scene_polylines_item* new_item)\n    : new_item(new_item)\n  {}\n\n  void start_new_polyline()\n  {\n    new_item->polylines.push_back( Scene_polylines_item::Polyline() );\n  }\n\n  void add_node(boost::graph_traits<Polyhedron>::vertex_descriptor vd)\n  {\n    new_item->polylines.back().push_back(vd->point());\n  }\n  void end_polyline(){}\n};\n\nvoid Polyhedron_demo_polyhedron_stitching_plugin::on_actionDetectBorders_triggered()\n{\n  Q_FOREACH(int index, scene->selectionIndices())\n  {\n    Scene_polyhedron_item* item =\n      qobject_cast<Scene_polyhedron_item*>(scene->item(index));\n\n    if(item)\n    {\n      Scene_polylines_item* new_item = new Scene_polylines_item();\n\n      Polyhedron* pMesh = item->polyhedron();\n      pMesh->normalize_border();\n\n#if 0\n      for (Polyhedron::Halfedge_iterator\n              it=pMesh->border_halfedges_begin(), it_end=pMesh->halfedges_end();\n              it!=it_end; ++it)\n      {\n        if (!it->is_border()) continue;\n        /// \\todo build cycles and graph with nodes of valence 2.\n        new_item->polylines.push_back( Scene_polylines_item::Polyline() );\n        new_item->polylines.back().push_back( it->opposite()->vertex()->point() );\n        new_item->polylines.back().push_back( it->vertex()->point() );\n      }\n#else\n      typedef boost::filtered_graph<Polyhedron,Is_border<Polyhedron>, Is_border<Polyhedron> > BorderGraph;\n      \n      Is_border<Polyhedron> ib(*pMesh);\n      BorderGraph bg(*pMesh,ib,ib);\n      Polyline_visitor polyline_visitor(new_item); \n      CGAL::split_graph_into_polylines( bg,\n                                        polyline_visitor,\n                                        CGAL::internal::IsTerminalDefault() );\n#endif\n      \n      if (new_item->polylines.empty())\n      {\n        delete new_item;\n      }\n      else\n      {\n        new_item->setName(tr(\"Boundary of %1\").arg(item->name()));\n        new_item->setColor(Qt::red);\n        scene->addItem(new_item);\n        new_item->invalidateOpenGLBuffers();\n      }\n    }\n  }\n}\n\nvoid Polyhedron_demo_polyhedron_stitching_plugin::on_actionStitchBorders_triggered()\n{\n  Q_FOREACH(int index, scene->selectionIndices())\n  {\n    Scene_polyhedron_item* item =\n      qobject_cast<Scene_polyhedron_item*>(scene->item(index));\n\n    if(item)\n    {\n      Polyhedron* pMesh = item->polyhedron();\n      CGAL::Polygon_mesh_processing::stitch_borders(*pMesh);\n      item->invalidateOpenGLBuffers();\n      scene->itemChanged(item);\n    }\n  }\n}\n\n#include \"Polyhedron_stitching_plugin.moc\"\n", "meta": {"hexsha": "17522c46114110884f6685ebcf95a7709aa26302", "size": 4946, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "graphics/cgal/Polyhedron/demo/Polyhedron/Plugins/PMP/Polyhedron_stitching_plugin.cpp", "max_stars_repo_name": "hlzz/dotfiles", "max_stars_repo_head_hexsha": "0591f71230c919c827ba569099eb3b75897e163e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-03-30T14:31:52.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-02T05:01:32.000Z", "max_issues_repo_path": "graphics/cgal/Polyhedron/demo/Polyhedron/Plugins/PMP/Polyhedron_stitching_plugin.cpp", "max_issues_repo_name": "hlzz/dotfiles", "max_issues_repo_head_hexsha": "0591f71230c919c827ba569099eb3b75897e163e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "graphics/cgal/Polyhedron/demo/Polyhedron/Plugins/PMP/Polyhedron_stitching_plugin.cpp", "max_forks_repo_name": "hlzz/dotfiles", "max_forks_repo_head_hexsha": "0591f71230c919c827ba569099eb3b75897e163e", "max_forks_repo_licenses": ["BSD-3-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.4404761905, "max_line_length": 112, "alphanum_fraction": 0.7035988678, "num_tokens": 1216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548511303336, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.4533158353026427}}
{"text": "// This file is part of MLDB. Copyright 2015 mldb.ai inc. All rights reserved.\n\n/* least_squares_test.cc\n   Jeremy Barnes, 25 February 2008\n   Copyright (c) 2008 Jeremy Barnes.  All rights reserved.\n\n   Test of the least squares class.\n*/\n\n#define BOOST_TEST_MAIN\n#define BOOST_TEST_DYN_LINK\n\n#include <boost/test/unit_test.hpp>\n#include <boost/test/tools/floating_point_comparison.hpp>\n#include <thread>\n\n#include <vector>\n#include <stdint.h>\n#include <iostream>\n\n#include \"mldb/plugins/jml/algebra/irls.h\"\n#include \"mldb/utils/vector_utils.h\"\n\nusing namespace ML;\nusing namespace std;\n\nusing boost::unit_test::test_suite;\nusing namespace boost::test_tools;\n\nnamespace ML {\nextern __thread std::ostream * debug_remove_dependent;\n}\n\ntemplate<typename Float>\nvoid do_test_identity()\n{\n    boost::multi_array<Float, 2> array(boost::extents[2][2]);\n    array[0][0] = 1;\n    array[1][1] = 1;\n\n    vector<int> result = remove_dependent(array);\n    BOOST_CHECK_EQUAL(array[0][0], 1.0);\n    BOOST_CHECK_EQUAL(array[0][1], 0.0);\n    BOOST_CHECK_EQUAL(array[1][0], 0.0);\n    BOOST_CHECK_EQUAL(array[1][1], 1.0);\n\n    BOOST_REQUIRE_EQUAL(result.size(), 2);\n    BOOST_CHECK_EQUAL(result[0], 0);\n    BOOST_CHECK_EQUAL(result[1], 1);\n}\n\nBOOST_AUTO_TEST_CASE( test_identity )\n{\n    do_test_identity<double>();\n    do_test_identity<float>();\n}\n\ntemplate<typename Float>\nvoid do_test_null()\n{\n    boost::multi_array<Float, 2> array(boost::extents[2][2]);\n\n    BOOST_CHECK_EQUAL(array.shape()[0], 2);\n    BOOST_CHECK_EQUAL(array.shape()[1], 2);\n\n    debug_remove_dependent = &cerr;\n    vector<int> result = remove_dependent(array);\n    debug_remove_dependent = 0;\n\n    BOOST_CHECK_EQUAL(array.shape()[0], 0);\n    BOOST_CHECK_EQUAL(array.shape()[1], 2);\n\n    BOOST_REQUIRE_EQUAL(result.size(), 2);\n    BOOST_CHECK_EQUAL(result[0], -1);\n    BOOST_CHECK_EQUAL(result[1], -1);\n}\n\nBOOST_AUTO_TEST_CASE( test_null )\n{\n    do_test_null<double>();\n    do_test_null<float>();\n}\n\ntemplate<typename Float>\nvoid do_test_uniform()\n{\n    boost::multi_array<Float, 2> array(boost::extents[2][2]);\n    array[0][0] = array[0][1] = array[1][0] = array[1][1] = 1.0;\n\n    BOOST_CHECK_EQUAL(array.shape()[0], 2);\n    BOOST_CHECK_EQUAL(array.shape()[1], 2);\n\n    debug_remove_dependent = &cerr;\n    vector<int> result = remove_dependent(array);\n    debug_remove_dependent = 0;\n\n    BOOST_CHECK_EQUAL(array.shape()[0], 1);\n    BOOST_CHECK_EQUAL(array.shape()[1], 2);\n\n    BOOST_CHECK_EQUAL(array[0][0], 1.0);\n    BOOST_CHECK_EQUAL(array[0][1], 1.0);\n\n    BOOST_REQUIRE_EQUAL(result.size(), 2);\n    BOOST_CHECK_EQUAL(result[0],  -1);\n    BOOST_CHECK_EQUAL(result[1],   0);\n}\n\nBOOST_AUTO_TEST_CASE( test_uniform )\n{\n    do_test_uniform<double>();\n    do_test_uniform<float>();\n}\n\ntemplate<typename Float>\nvoid do_test_dependent()\n{\n    boost::multi_array<Float, 2> array(boost::extents[3][2]);\n    array[0][0] = 1;\n    array[1][1] = 1;\n    array[2][1] = 1;\n\n    BOOST_CHECK_EQUAL(array.shape()[0], 3);\n    BOOST_CHECK_EQUAL(array.shape()[1], 2);\n\n    vector<int> result = remove_dependent(array);\n\n    cerr << \"result = \" << result << endl;\n\n    BOOST_CHECK_EQUAL(array.shape()[0], 2);\n    BOOST_CHECK_EQUAL(array.shape()[1], 2);\n\n    BOOST_CHECK_EQUAL(array[0][0], 1.0);\n    BOOST_CHECK_EQUAL(array[0][1], 0.0);\n    BOOST_CHECK_EQUAL(array[1][0], 0.0);\n    BOOST_CHECK_EQUAL(array[1][1], 1.0);\n\n    BOOST_REQUIRE_EQUAL(result.size(), 3);\n\n    BOOST_CHECK_EQUAL(result[0],  0);\n    BOOST_CHECK_EQUAL(result[1], -1);\n    BOOST_CHECK_EQUAL(result[2],  1);\n}\n\nBOOST_AUTO_TEST_CASE( test_dependent )\n{\n    do_test_dependent<double>();\n    do_test_dependent<float>();\n}\n\n\n", "meta": {"hexsha": "3b8571b6e6251eec151d8e30a1eb428a949bf9b2", "size": 3625, "ext": "cc", "lang": "C++", "max_stars_repo_path": "plugins/jml/algebra/testing/remove_dependent_test.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/algebra/testing/remove_dependent_test.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/algebra/testing/remove_dependent_test.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": 24.0066225166, "max_line_length": 78, "alphanum_fraction": 0.6794482759, "num_tokens": 1010, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.45331583119508095}}
{"text": "/// \\file\n// --------------------------------------------------------------------------\n// This file is part of the reference implementation for the paper\n//    QFib: Fast and Efficient Brain Tractogram Compression\n//    C. Mercier*, S. Rousseau*, P. Gori, I. Bloch and T. Boubekeur\n//    NeuroInformatics 2020\n//    DOI: 10.1007/s12021-020-09452-0\n//\n// All rights reserved. Use of this source code is governed by a\n// MIT license that can be found in the LICENSE file.\n// --------------------------------------------------------------------------\n#pragma once\n\n\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n#include <Eigen/Geometry>\n#include <Eigen/Dense>\n\n#include \"saveload.hpp\"\n#include <vector>\n\nnamespace utl\n{\n///\n/// \\brief meanMaxError Function to compute average and maximum error between two sets of fibers containing the exact same number of points and fibers\n/// \\param fibersA Vector containing the first set of fibers\n/// \\param fibersB Vector containing the second set of fibers\n/// \\param meanError Average error\n/// \\param maxError Maximum error\n/// \\param totalNbPts Variable containing the total number of points in the bundle, used for average error computation\n///\n\nvoid meanMaxError(const std::vector< std::vector<Vector3f> > & fibersA, const std::vector< std::vector<Vector3f> > & fibersB, double & meanError, float & maxError, uint64_t & totalNbPts)\n{\n\tmeanError = 0;\n\tmaxError = 0.f;\n\tassert(fibersA.size() == fibersB.size());\n\tfor(unsigned f = 0; f < fibersA.size(); ++f)\n\t{\n\t\tassert(fibersA[f].size() == fibersB[f].size());\n\t\tfor(unsigned p = 0; p < fibersA[f].size(); ++p)\n\t\t{\n\t\t\tfloat err = (fibersA[f][p] - fibersB[f][p]).norm();\n\t\t\tmaxError = err > maxError ? err : maxError;\n\t\t\tmeanError  += err / double(totalNbPts);\n\t\t}\n\t}\n}\n\n///\n/// \\brief error Function to compute the error between two sets of fibers with the exact same number of points and fibers\n/// This error is computed depending on the length of the fibers\n/// \\param fibersA Vector containing the first set of fibers\n/// \\param fibersB Vector containing the second set of fibers\n/// \\param minError Minimum error\n/// \\param meanError Average error\n/// \\param maxError Maximum error\n/// \\param minEndPointError Minimum error on every end point\n/// \\param meanEndPointError Average error on every end point\n/// \\param maxEndPointError Maximum error on every end point\n/// \\param totalNbPts Variable containing the total number of points in the bundle, used for average error computation\n/// \\param steps Number of length separation to perform\n/// \\param minValue Minimum length to consider\n/// \\param maxValue Maximum length to consider\n///\n\nvoid error(const std::vector<std::vector<Vector3f> > & fibersA, const std::vector< std::vector<Vector3f> > & fibersB,\n\t\t   vector<float>& minError, vector<double>& meanError, vector<float>& maxError,\n\t\t   float & minEndPointError, float & meanEndPointError, float & maxEndPointError, uint64_t & totalNbPts,\n\t\t   unsigned steps = 10, float minValue = 35, float maxValue = 260)\n{\n\tminEndPointError = std::numeric_limits<float>::max();\n\tmeanEndPointError = 0.f;\n\tmaxEndPointError = 0.f;\n\tunsigned nbSteps = (maxValue - minValue)/steps;\n\tminError.resize(nbSteps, std::numeric_limits<float>::max());\n\tmeanError.resize(nbSteps, 0);\n\tmaxError.resize(nbSteps, 0);\n\n\tunsigned nbEndPoints = fibersA.size();\n\tassert(fibersA.size() == fibersB.size());\n\tfor(unsigned f = 0; f < fibersA.size(); ++f)\n\t{\n\t\tunsigned tablePos = (float)((fibersA[f].size() - 1) * (fibersA[f][1]-fibersA[f][0]).norm() - minValue) / (float)(maxValue - minValue) * (nbSteps-1);\n\t\tif (tablePos>nbSteps-1) tablePos = nbSteps - 1;\n\t\tassert(fibersA[f].size() == fibersB[f].size());\n\t\tfor(unsigned p = 0; p < fibersA[f].size()-1; ++p)\n\t\t{\n\t\t\tfloat err = (fibersA[f][p] - fibersB[f][p]).norm();\n\t\t\tmeanError[tablePos]  += err / double(totalNbPts);\n\t\t\tmaxError[tablePos] = err > maxError[tablePos] ? err : maxError[tablePos];\n\t\t\tminError[tablePos] = err < minError[tablePos] ? err : minError[tablePos];\n\t\t}\n\t\tfloat err = (fibersA[f][fibersA[f].size()-1] - fibersB[f][fibersA[f].size()-1]).norm();\n\t\tmeanError[tablePos]  += err / double(totalNbPts);\n\t\tmaxError[tablePos] = err > maxError[tablePos] ? err : maxError[tablePos];\n\t\tminError[tablePos] = err < minError[tablePos] ? err : minError[tablePos];\n\t\tminEndPointError = err < minEndPointError ? err : minEndPointError;\n\t\tmeanEndPointError += err / double(nbEndPoints);\n\t\tmaxEndPointError = err > maxEndPointError ? err : maxEndPointError;\n\t}\n}\n}\n", "meta": {"hexsha": "d3717c9fdaf4f09721443ff4a5aa952663a45e2e", "size": 4491, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sources/utilities.hpp", "max_stars_repo_name": "syrousseau/qfib", "max_stars_repo_head_hexsha": "72987f025d2158ed3f325055c2ae5b37c49be786", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-02-14T14:50:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T19:23:00.000Z", "max_issues_repo_path": "sources/utilities.hpp", "max_issues_repo_name": "syrousseau/qfib", "max_issues_repo_head_hexsha": "72987f025d2158ed3f325055c2ae5b37c49be786", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-02-06T14:54:00.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-16T14:58:35.000Z", "max_forks_repo_path": "sources/utilities.hpp", "max_forks_repo_name": "syrousseau/qfib", "max_forks_repo_head_hexsha": "72987f025d2158ed3f325055c2ae5b37c49be786", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-04T16:10:22.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-04T16:10:22.000Z", "avg_line_length": 42.7714285714, "max_line_length": 186, "alphanum_fraction": 0.6811400579, "num_tokens": 1194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583124210896, "lm_q2_score": 0.6513548511303336, "lm_q1q2_score": 0.4533158229799571}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2015 NumScale SAS\n  @copyright 2015 J.T.Lapreste\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_DETAIL_SCALAR_D_EXPO_REDUCTION_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_DETAIL_SCALAR_D_EXPO_REDUCTION_HPP_INCLUDED\n\n#include <boost/simd/arch/detail/scalar/horner.hpp>\n#include <boost/simd/constant/invlog10_2.hpp>\n#include <boost/simd/constant/invlog_2.hpp>\n#include <boost/simd/constant/log10_2hi.hpp>\n#include <boost/simd/constant/log10_2lo.hpp>\n#include <boost/simd/constant/log_10.hpp>\n#include <boost/simd/constant/log_2.hpp>\n#include <boost/simd/constant/log_2hi.hpp>\n#include <boost/simd/constant/log_2lo.hpp>\n#include <boost/simd/constant/maxlog.hpp>\n#include <boost/simd/constant/maxlog10.hpp>\n#include <boost/simd/constant/maxlog2.hpp>\n#include <boost/simd/constant/minlog.hpp>\n#include <boost/simd/constant/minlog10.hpp>\n#include <boost/simd/constant/minlog2.hpp>\n#include <boost/simd/constant/two.hpp>\n#include <boost/simd/function/simd/fma.hpp>\n#include <boost/simd/function/simd/fnms.hpp>\n#include <boost/simd/function/simd/inc.hpp>\n#include <boost/simd/function/simd/oneminus.hpp>\n#include <boost/simd/function/simd/oneplus.hpp>\n#include <boost/simd/function/simd/round2even.hpp>\n#include <boost/simd/function/simd/sqr.hpp>\n#include <boost/simd/logical.hpp>\n#include <boost/dispatch/meta/scalar_of.hpp>\n\nnamespace boost { namespace simd\n{\n  namespace detail\n  {\n    namespace bd =  boost::dispatch;\n    namespace bs =  boost::simd;\n\n    template < class A0> struct exp_reduction < A0, natural_tag, double>\n    {\n      using l_t = logical<A0>;\n      static BOOST_FORCEINLINE l_t isgemaxlog(A0 a0) BOOST_NOEXCEPT\n      {\n        return (a0 >= Maxlog<A0>());\n      }\n\n      static BOOST_FORCEINLINE l_t isleminlog(A0 a0) BOOST_NOEXCEPT\n      {\n        return (a0 <= Minlog<A0>());\n      }\n\n      static BOOST_FORCEINLINE A0 reduce( A0 a0\n                                        , A0& hi, A0& lo, A0& x) BOOST_NOEXCEPT\n      {\n        A0 k = round2even(Invlog_2<A0>()*a0);\n        hi = fnms(k, Log_2hi<A0>(), a0); //a0-k*L\n        lo = k*Log_2lo<A0>();\n        x  = hi-lo;\n        return k;\n      }\n\n      static BOOST_FORCEINLINE A0 approx(A0 x) BOOST_NOEXCEPT\n      {\n        A0 const t = sqr(x);\n        return fnms(t, horner<BOOST_SIMD_HORNER_COEFF_T(A0, 5,\n                                                        ( 0x3e66376972bea4d0ull\n                                                        , 0xbebbbd41c5d26bf1ull\n                                                        , 0x3f11566aaf25de2cull\n                                                        , 0xbf66c16c16bebd93ull\n                                                        , 0x3fc555555555553eull\n                                                        )\n                                                       )>(t), x); //x-h*t\n      }\n\n      static BOOST_FORCEINLINE A0 finalize(A0 x, A0 c, A0 hi, A0 lo) BOOST_NOEXCEPT\n      {\n        return oneminus(((lo-(x*c)/(Two<A0>()-c))-hi));\n      }\n\n    };\n\n    template < class A0 > struct exp_reduction < A0, two_tag, double>\n    {\n      using l_t = logical<A0>;\n      static BOOST_FORCEINLINE l_t isgemaxlog(A0 a0) BOOST_NOEXCEPT\n      {\n        return (a0 >= Maxlog2<A0>());\n      }\n\n      static BOOST_FORCEINLINE l_t isleminlog(A0 a0) BOOST_NOEXCEPT\n      {\n        return (a0 <= Minlog2<A0>());\n      }\n\n      static BOOST_FORCEINLINE A0 reduce(A0 a0, A0, A0, A0& x) BOOST_NOEXCEPT\n      {\n        A0 k = round2even(a0);\n        x = (a0 - k)*Log_2<A0>();\n        return k;\n      }\n\n      static BOOST_FORCEINLINE A0 approx(A0 x) BOOST_NOEXCEPT\n      {\n        const A0 t =  sqr(x);\n        return fnms(t, horner<BOOST_SIMD_HORNER_COEFF_T(A0, 5,\n                                                        ( 0x3e66376972bea4d0ull\n                                                        , 0xbebbbd41c5d26bf1ull\n                                                        , 0x3f11566aaf25de2cull\n                                                        , 0xbf66c16c16bebd93ull\n                                                        , 0x3fc555555555553eull\n                                                        )\n                                                       )> (t), x); //x-h*t\n      }\n\n      static BOOST_FORCEINLINE A0 finalize( A0 x, A0 c, A0, A0& ) BOOST_NOEXCEPT\n      {\n        return oneminus(((-(x*c)/(Two<A0>()-c))-x));\n      }\n    };\n\n    template < class A0 > struct exp_reduction < A0, ten_tag, double>\n    {\n      using l_t = logical<A0>;\n      static BOOST_FORCEINLINE l_t isgemaxlog(A0 a0) BOOST_NOEXCEPT\n      {\n        return (a0 >= Maxlog10<A0>());\n      }\n\n      static BOOST_FORCEINLINE l_t isleminlog(A0 a0) BOOST_NOEXCEPT\n      {\n        return (a0 <= Minlog10<A0>());\n      }\n\n      static BOOST_FORCEINLINE A0 reduce(A0 a0, A0&, A0&, A0& x) BOOST_NOEXCEPT\n      {\n        A0 k  = round2even(Invlog10_2<A0>()*a0);\n        x = fnms(k, Log10_2hi<A0>(), a0);\n        x = fnms(k, Log10_2lo<A0>(), x);\n        return k;\n      }\n\n      static BOOST_FORCEINLINE A0 approx(A0 x) BOOST_NOEXCEPT\n      {\n        A0 xx = sqr(x);\n        A0 px = x*horner<BOOST_SIMD_HORNER_COEFF_T(A0, 4,\n                                                   (0x3fa4fd75f3062dd4ull,\n                                                    0x40277d9474c55934ull,\n                                                    0x40796b7a050349e4ull,\n                                                    0x40a2b4798e134a01ull)\n                                                  )> (xx);\n        A0 x2 =  px/(horner<BOOST_SIMD_HORNER_COEFF_T(A0, 4,\n                                                      (0x3ff0000000000000ull,\n                                                       0x405545fdce51ca08ull,\n                                                       0x4093e05eefd67782ull,\n                                                       0x40a03f37650df6e2ull)\n                                                     )> (xx)-px);\n        return oneplus(x2+x2);\n      }\n\n      static BOOST_FORCEINLINE A0 finalize(A0, A0 c, A0,  A0 ) BOOST_NOEXCEPT\n      {\n        return c;\n      }\n    };\n  }\n} }\n#endif\n", "meta": {"hexsha": "829411dee655ea1b70fa48a393a0353b2f1b90f3", "size": 6443, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arch/detail/scalar/d_expo_reduction.hpp", "max_stars_repo_name": "yaeldarmon/boost.simd", "max_stars_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/simd/arch/detail/scalar/d_expo_reduction.hpp", "max_issues_repo_name": "yaeldarmon/boost.simd", "max_issues_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/arch/detail/scalar/d_expo_reduction.hpp", "max_forks_repo_name": "yaeldarmon/boost.simd", "max_forks_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.4011299435, "max_line_length": 100, "alphanum_fraction": 0.4985255316, "num_tokens": 1680, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.45321247216997884}}
{"text": "#include <benchmark/benchmark.h>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include \"UKF/Types.h\"\n#include \"UKF/Integrator.h\"\n#include \"UKF/StateVector.h\"\n#include \"UKF/MeasurementVector.h\"\n#include \"UKF/Core.h\"\n\nenum MyStateFields {\n    Position,\n    Velocity,\n    Attitude,\n    AngularVelocity\n};\n\nusing MyStateVector = UKF::StateVector<\n    UKF::Field<Position, UKF::Vector<3>>,\n    UKF::Field<Velocity, UKF::Vector<3>>,\n    UKF::Field<Attitude, UKF::Quaternion>,\n    UKF::Field<AngularVelocity, UKF::Vector<3>>\n>;\n\nnamespace UKF {\nnamespace Parameters {\ntemplate <> constexpr real_t AlphaSquared<MyStateVector> = 1e-6;\n}\n\n/*\nState vector process model. One version takes body frame kinematic\nacceleration and angular acceleration as inputs, the other doesn't (assumes\nzero accelerations).\n*/\ntemplate <> template <>\nMyStateVector MyStateVector::derivative<UKF::Vector<3>, UKF::Vector<3>>(\n        const UKF::Vector<3>& acceleration, const UKF::Vector<3>& angular_acceleration) const {\n    MyStateVector temp;\n    \n    /* Position derivative. */\n    temp.set_field<Position>(get_field<Velocity>());\n\n    /* Velocity derivative. */\n    temp.set_field<Velocity>(get_field<Attitude>().conjugate() * acceleration);\n\n    /* Attitude derivative. */\n    UKF::Quaternion temp_q;\n    temp_q.vec() = get_field<AngularVelocity>();\n    temp_q.w() = 0;\n    temp.set_field<Attitude>(temp_q);\n\n    /* Angular velocity derivative. */\n    temp.set_field<AngularVelocity>(angular_acceleration);\n\n    return temp;\n}\n\ntemplate <> template <>\nMyStateVector MyStateVector::derivative<>() const {\n    return derivative(UKF::Vector<3>(0, 0, 0), UKF::Vector<3>(0, 0, 0));\n}\n\n}\n\n/* Set up measurement vector class. */\nenum MyMeasurementFields {\n    GPS_Position,\n    GPS_Velocity,\n    Accelerometer,\n    Magnetometer,\n    Gyroscope\n};\n\nusing MyMeasurementVector = UKF::DynamicMeasurementVector<\n    UKF::Field<GPS_Position, UKF::Vector<3>>,\n    UKF::Field<GPS_Velocity, UKF::Vector<3>>,\n    UKF::Field<Accelerometer, UKF::Vector<3>>,\n    UKF::Field<Magnetometer, UKF::FieldVector>,\n    UKF::Field<Gyroscope, UKF::Vector<3>>\n>;\n\nusing MyCore = UKF::Core<\n    MyStateVector,\n    MyMeasurementVector,\n    UKF::IntegratorRK4\n>;\n\nnamespace UKF {\n/*\nDefine measurement model to be used in tests. NOTE: These are just for\ntesting, don't expect them to make any physical sense whatsoever.\n*/\ntemplate <> template <>\nUKF::Vector<3> MyMeasurementVector::expected_measurement\n<MyStateVector, GPS_Position>(const MyStateVector& state) {\n    return state.get_field<Position>();\n}\n\ntemplate <> template <>\nUKF::Vector<3> MyMeasurementVector::expected_measurement\n<MyStateVector, GPS_Velocity>(const MyStateVector& state) {\n    return state.get_field<Velocity>();\n}\n\ntemplate <> template <>\nUKF::Vector<3> MyMeasurementVector::expected_measurement\n<MyStateVector, Accelerometer>(const MyStateVector& state) {\n    return state.get_field<Attitude>() * UKF::Vector<3>(0, 0, -9.8);\n}\n\ntemplate <> template <>\nUKF::FieldVector MyMeasurementVector::expected_measurement\n<MyStateVector, Magnetometer>(const MyStateVector& state) {\n    return state.get_field<Attitude>() * UKF::FieldVector(1, 0, 0);\n}\n\ntemplate <> template <>\nUKF::Vector<3> MyMeasurementVector::expected_measurement\n<MyStateVector, Gyroscope>(const MyStateVector& state) {\n    return state.get_field<AngularVelocity>();\n}\n\n}\n\nMyCore create_initialised_test_filter() {\n    MyCore test_filter;\n    test_filter.state.set_field<Position>(UKF::Vector<3>(0, 0, 0));\n    test_filter.state.set_field<Velocity>(UKF::Vector<3>(0, 0, 0));\n    test_filter.state.set_field<Attitude>(UKF::Quaternion(1, 0, 0, 0));\n    test_filter.state.set_field<AngularVelocity>(UKF::Vector<3>(0, 0, 0));\n    test_filter.covariance = MyStateVector::CovarianceMatrix::Zero();\n    test_filter.covariance.diagonal() << 10000, 10000, 10000, 100, 100, 100, 1, 1, 5, 10, 10, 10;\n    test_filter.measurement_covariance << 10, 10, 10, 1, 1, 1, 5e-1, 5e-1, 5e-1, 5e-1, 5e-1, 5e-1, 0.05, 0.05, 0.05;\n\n    real_t a, b;\n    real_t dt = 0.01;\n    a = std::sqrt(0.1*dt*dt);\n    b = std::sqrt(0.1*dt);\n    test_filter.process_noise_covariance << a, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n                                            0, a, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n                                            0, 0, a, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n                                            0, 0, 0, b, 0, 0, 0, 0, 0, 0, 0, 0,\n                                            0, 0, 0, 0, b, 0, 0, 0, 0, 0, 0, 0,\n                                            0, 0, 0, 0, 0, b, 0, 0, 0, 0, 0, 0,\n                                            0, 0, 0, 0, 0, 0, a, 0, 0, 0, 0, 0,\n                                            0, 0, 0, 0, 0, 0, 0, a, 0, 0, 0, 0,\n                                            0, 0, 0, 0, 0, 0, 0, 0, a, 0, 0, 0,\n                                            0, 0, 0, 0, 0, 0, 0, 0, 0, b, 0, 0,\n                                            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, b, 0,\n                                            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, b;\n\n    return test_filter;\n}\n\nvoid Core_APrioriStep(benchmark::State& state) {\n    MyCore test_filter = create_initialised_test_filter();\n\n    while(state.KeepRunning()) {\n        test_filter.a_priori_step(0.01);\n    }\n}\n\nBENCHMARK(Core_APrioriStep);\n\nvoid Core_InnovationStep(benchmark::State& state) {\n    MyCore test_filter = create_initialised_test_filter();\n    MyMeasurementVector m;\n\n    m.set_field<GPS_Position>(UKF::Vector<3>(100, 10, -50));\n    m.set_field<GPS_Velocity>(UKF::Vector<3>(20, 0, 0));\n    m.set_field<Accelerometer>(UKF::Vector<3>(0, 0, -9.8));\n    m.set_field<Magnetometer>(UKF::FieldVector(0, -1, 0));\n    m.set_field<Gyroscope>(UKF::Vector<3>(0.5, 0, 0));\n\n    test_filter.a_priori_step(0.01);\n\n    while(state.KeepRunning()) {\n        test_filter.innovation_step(m);\n    }\n}\n\nBENCHMARK(Core_InnovationStep);\n\nvoid Core_APosterioriStep(benchmark::State& state) {\n    MyCore test_filter = create_initialised_test_filter();\n    MyMeasurementVector m;\n\n    m.set_field<GPS_Position>(UKF::Vector<3>(100, 10, -50));\n    m.set_field<GPS_Velocity>(UKF::Vector<3>(20, 0, 0));\n    m.set_field<Accelerometer>(UKF::Vector<3>(0, 0, -9.8));\n    m.set_field<Magnetometer>(UKF::FieldVector(0, -1, 0));\n    m.set_field<Gyroscope>(UKF::Vector<3>(0.5, 0, 0));\n\n    test_filter.a_priori_step(0.01);\n    test_filter.innovation_step(m);\n\n    MyStateVector::CovarianceMatrix initial_cov = test_filter.covariance;\n    MyStateVector initial_state = test_filter.state;\n\n    while(state.KeepRunning()) {\n        test_filter.covariance = initial_cov;\n        test_filter.state = initial_state;\n        test_filter.a_posteriori_step();\n    }\n}\n\nBENCHMARK(Core_APosterioriStep);\n", "meta": {"hexsha": "d5ea5d1558d0dda7b403d7115ca2f2b679371fad", "size": 6720, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "benchmark/CoreBenchmark.cpp", "max_stars_repo_name": "rafaelrietmann/ukf", "max_stars_repo_head_hexsha": "bf53dacafbfee8c7591c48a66b50229f82afe4b4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 320.0, "max_stars_repo_stars_event_min_datetime": "2015-01-07T05:49:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:52:15.000Z", "max_issues_repo_path": "benchmark/CoreBenchmark.cpp", "max_issues_repo_name": "msnh2012/ukf", "max_issues_repo_head_hexsha": "04f0a996fee1f49699142bf5b149548a8d3a4ad1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 22.0, "max_issues_repo_issues_event_min_datetime": "2015-03-03T17:28:32.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T14:46:54.000Z", "max_forks_repo_path": "benchmark/CoreBenchmark.cpp", "max_forks_repo_name": "msnh2012/ukf", "max_forks_repo_head_hexsha": "04f0a996fee1f49699142bf5b149548a8d3a4ad1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 155.0, "max_forks_repo_forks_event_min_datetime": "2015-02-20T01:18:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-22T01:58:53.000Z", "avg_line_length": 32.4637681159, "max_line_length": 116, "alphanum_fraction": 0.6282738095, "num_tokens": 2116, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.45321247216997884}}
{"text": "#ifndef YQVMC_EXTERNAL_LIBRARY_ADAPTOR_EIGEN3_HPP\n#define YQVMC_EXTERNAL_LIBRARY_ADAPTOR_EIGEN3_HPP\n\n#include <Eigen/Core>\n#include \"../impl_/mae_traits.hpp\"\n\nnamespace yqvmc {\n  namespace impl_ {\n    template <typename S_, int R_, int C_, int O_, int MR_, int MC_>\n    struct MeanAndErrorTraits<Eigen::Array<S_, R_, C_, O_, MR_, MC_>, void> {\n    public:\n      typedef Eigen::Array<S_, R_, C_, O_, MR_, MC_> input_type;\n      typedef typename input_type::Scalar Scalar;\n      typedef typename std::conditional<input_type::ColsAtCompileTime == 1,\n        Eigen::Array<Scalar, Eigen::Dynamic, 1>,\n        Eigen::Array<Scalar, Eigen::Dynamic, Eigen::Dynamic> >::type sum_type;\n      typedef sum_type result_type;\n\n      static void set_zero(sum_type& x) { x.setZero(); }\n      static void add_to(sum_type& x, const input_type& dx) {\n        if (x.size() == 0)\n          x = dx;\n        else\n          x += dx;\n      }\n      static input_type square(const input_type& x) { return x*x; }\n      static result_type mean(const sum_type& x, std::size_t n) {\n        return x/n;\n      }\n      static result_type standard_error(const result_type& x2mean,\n        const result_type& xmean, std::size_t n) {\n        return ((x2mean - xmean*xmean) / n).sqrt();\n      }\n    };\n  }\n}\n\n#endif\n", "meta": {"hexsha": "c1ca65d58c643f92c3c1a6f23a72a36ca5fac381", "size": 1277, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/yqvmc/libadapt/eigen3_adaptor.hpp", "max_stars_repo_name": "yangqi137/yqvmc", "max_stars_repo_head_hexsha": "73b7367f6d4b01ea61612ea0888b285c8dac2fad", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/yqvmc/libadapt/eigen3_adaptor.hpp", "max_issues_repo_name": "yangqi137/yqvmc", "max_issues_repo_head_hexsha": "73b7367f6d4b01ea61612ea0888b285c8dac2fad", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/yqvmc/libadapt/eigen3_adaptor.hpp", "max_forks_repo_name": "yangqi137/yqvmc", "max_forks_repo_head_hexsha": "73b7367f6d4b01ea61612ea0888b285c8dac2fad", "max_forks_repo_licenses": ["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.7435897436, "max_line_length": 78, "alphanum_fraction": 0.6405638215, "num_tokens": 348, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.45320963819081034}}
{"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_LOG1P_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_LOG1P_HPP_INCLUDED\n#include <boost/simd/detail/overload.hpp>\n\n#include <boost/simd/detail/dispatch/function/overload.hpp>\n#include <boost/config.hpp>\n\n#include <boost/simd/function/any.hpp>\n#include <boost/simd/function/bitwise_cast.hpp>\n#include <boost/simd/function/dec.hpp>\n#include <boost/simd/function/fma.hpp>\n#include <boost/simd/function/ifrexp.hpp>\n#include <boost/simd/function/genmask.hpp>\n#include <boost/simd/function/horn.hpp>\n#include <boost/simd/function/if_else.hpp>\n#include <boost/simd/function/if_minus.hpp>\n#include <boost/simd/function/if_nan_else.hpp>\n#include <boost/simd/function/inc.hpp>\n#include <boost/simd/function/is_ngez.hpp>\n#include <boost/simd/function/is_nez.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/tofloat.hpp>\n\n#include <boost/simd/constant/half.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/minf.hpp>\n#include <boost/simd/constant/sqrt_2o_2.hpp>\n#include <boost/simd/constant/two.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\n BOOST_DISPATCH_OVERLOAD_IF ( log1p_\n                             , (typename A0, typename X)\n                             , (detail::is_native<X>)\n                             , bd::cpu_\n                             , bs::pack_< bd::single_<A0>, X>\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator()( const A0& a0) BOOST_NOEXCEPT\n    {\n      return musl_(log1p)(a0);\n    }\n  };\n\n BOOST_DISPATCH_OVERLOAD_IF ( log1p_\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) BOOST_NOEXCEPT\n    {\n      return plain_(log1p)(a0);\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD_IF ( log1p_\n                          , (typename A0, typename X)\n                          , (detail::is_native<X>)\n                          , bd::cpu_\n                          , bs::musl_tag\n                          , bs::pack_< bd::single_<A0>, X>\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() (const musl_tag &, const A0& a0) const BOOST_NOEXCEPT\n    {\n      using uiA0 = bd::as_integer_t<A0, unsigned>;\n      using iA0 = bd::as_integer_t<A0,   signed>;\n      const A0 uf =  inc(a0);\n      auto isnez = is_nez(uf);\n\n      uiA0 iu = bitwise_cast<uiA0>(uf);\n      iu += 0x3f800000 - 0x3f3504f3;\n      iA0 k = bitwise_cast<iA0>(iu>>23) - 0x7f;\n      /* correction term ~ log(1+x)-log(u), avoid underflow in c/u */\n      /* reduce x into [sqrt(2)/2, sqrt(2)] */\n      iu = (iu&0x007fffff) + 0x3f3504f3;\n      A0 f =  dec(bitwise_cast<A0>(iu));\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 = Half<A0>()*sqr(f);\n      A0 dk = tofloat(k);\n      A0  c = if_else( k >= 2, oneminus(uf-a0), a0-dec(uf))/uf;\n      A0 r = fma(dk, Log_2hi<A0>(), ((fma(s, (hfsq+R), dk*Log_2lo<A0>()+c) - hfsq) + f));\n#ifndef BOOST_SIMD_NO_INFINITIES\n      A0 zz = if_else(isnez, if_else(a0 == Inf<A0>(), Inf<A0>(), r), Minf<A0>());\n#else\n      A0 zz = if_else(isnez, r, Minf<A0>());\n#endif\n      return if_nan_else(is_ngez(uf), zz);\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD_IF ( log1p_\n                             , (typename A0, typename X)\n                             , (detail::is_native<X>)\n                             , bd::cpu_\n                             , bs::musl_tag\n                             , bs::pack_< bd::double_<A0>, X>\n                             )\n  {\n    BOOST_FORCEINLINE A0 operator() (const musl_tag &, const A0& a0) const BOOST_NOEXCEPT\n    {\n      using uiA0 = bd::as_integer_t<A0, unsigned>;\n      using iA0 = bd::as_integer_t<A0,   signed>;\n      const A0 uf =  inc(a0);\n      auto isnez = is_nez(uf);\n\n      /* reduce x into [sqrt(2)/2, sqrt(2)] */\n      uiA0 hu = bitwise_cast<uiA0>(uf)>>32;\n      hu += 0x3ff00000 - 0x3fe6a09e;\n      iA0 k = bitwise_cast<iA0>(hu>>20) - 0x3ff;\n      /* correction term ~ log(1+x)-log(u), avoid underflow in c/u */\n      A0  c =  if_else( k >= 2, oneminus(uf-a0), a0-dec(uf))/uf;\n      hu =  (hu&0x000fffff) + 0x3fe6a09e;\n      A0 f = bitwise_cast<A0>( bitwise_cast<uiA0>(hu<<32) | (bitwise_and(0xffffffffull, bitwise_cast<uiA0>(uf))));\n      f = dec(f);\n\n      A0 hfsq = Half<A0>()*sqr(f);\n      A0 s = f/(2.0 + 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 = tofloat(k);\n      A0 r = fma(dk, Log_2hi<A0>(), ((fma(s, (hfsq+R), dk*Log_2lo<A0>()+c) - hfsq) + f));\n\n#ifndef BOOST_SIMD_NO_INFINITIES\n      A0 zz = if_else(isnez, if_else(a0 == Inf<A0>(), Inf<A0>(), r), Minf<A0>());\n#else\n      A0 zz = if_else(isnez, r, Minf<A0>());\n#endif\n      return if_nan_else(is_ngez(uf), zz);\n    }\n  };\n//=================================================================================================================\n  BOOST_DISPATCH_OVERLOAD_IF ( log1p_\n                          , (typename A0, typename X)\n                          , (detail::is_native<X>)\n                          , bd::cpu_\n                          , bs::plain_tag\n                          , bs::pack_< bd::single_<A0>, X>\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() (const plain_tag &, const A0& a0) const BOOST_NOEXCEPT\n    {\n      using iA0 = bd::as_integer_t<A0,   signed>;\n      const A0 uf =  inc(a0);\n      auto isnez = is_nez(uf);\n\n     /* reduce x into [sqrt(2)/2, sqrt(2)] */\n      iA0 k;\n      A0 x;\n      std::tie(x, k) = ifrexp(uf);\n      A0  x_lt_sqrthf = genmask(Sqrt_2o_2<A0>() >  x);\n      k += bitwise_cast<iA0>(x_lt_sqrthf);\n      A0 f = dec(x+bitwise_and(x, x_lt_sqrthf));\n      /* correction term ~ log(1+x)-log(u), avoid underflow in c/u */\n      A0  c = if_else( k >= 2, oneminus(uf-a0), a0-dec(uf))/uf;\n\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 = Half<A0>()*sqr(f);\n      A0 dk = tofloat(k);\n      A0 r = fma(dk, Log_2hi<A0>(), ((fma(s, (hfsq+R), dk*Log_2lo<A0>()+c) - hfsq) + f));\n#ifndef BOOST_SIMD_NO_INFINITIES\n      A0 zz = if_else(isnez, if_else(a0 == Inf<A0>(), Inf<A0>(), r), Minf<A0>());\n#else\n      A0 zz = if_else(isnez, r, Minf<A0>());\n#endif\n      return if_nan_else(is_ngez(uf), zz);\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD_IF ( log1p_\n                             , (typename A0, typename X)\n                             , (detail::is_native<X>)\n                             , bd::cpu_\n                             , bs::plain_tag\n                             , bs::pack_< bd::double_<A0>, X>\n                             )\n  {\n    BOOST_FORCEINLINE A0 operator() (const plain_tag &, const A0& a0) const BOOST_NOEXCEPT\n    {\n      using iA0 = bd::as_integer_t<A0,   signed>;\n      const A0 uf =  inc(a0);\n      auto isnez = is_nez(uf);\n\n      /* reduce x into [sqrt(2)/2, sqrt(2)] */\n      iA0 k;\n      A0 x;\n      std::tie(x, k) = ifrexp(uf);\n      A0  x_lt_sqrthf = genmask(Sqrt_2o_2<A0>() >  x);\n      k += bitwise_cast<iA0>(x_lt_sqrthf);\n      A0 f = dec(x+bitwise_and(x, x_lt_sqrthf));\n      /* correction term ~ log(1+x)-log(u), avoid underflow in c/u */\n      A0  c = if_else( k >= 2, oneminus(uf-a0), a0-dec(uf))/uf;\n\n      A0 hfsq = Half<A0>()*sqr(f);\n      A0 s = f/(2.0 + 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 = tofloat(k);\n      A0 r = fma(dk, Log_2hi<A0>(), ((fma(s, (hfsq+R), dk*Log_2lo<A0>()+c) - hfsq) + f));\n\n#ifndef BOOST_SIMD_NO_INFINITIES\n      A0 zz = if_else(isnez, if_else(a0 == Inf<A0>(), Inf<A0>(), r), Minf<A0>());\n#else\n      A0 zz = if_else(isnez, r, Minf<A0>());\n#endif\n      return if_nan_else(is_ngez(uf), zz);\n    }\n  };\n\n\n\n\n} } }\n\n#endif\n", "meta": {"hexsha": "fee964e0e2030a9891d3e163af978dcfa8425329", "size": 9176, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arch/common/simd/function/log1p.hpp", "max_stars_repo_name": "nickporubsky/boost-simd-clone", "max_stars_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_stars_repo_licenses": ["BSL-1.0"], "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": "include/boost/simd/arch/common/simd/function/log1p.hpp", "max_issues_repo_name": "nickporubsky/boost-simd-clone", "max_issues_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/arch/common/simd/function/log1p.hpp", "max_forks_repo_name": "nickporubsky/boost-simd-clone", "max_forks_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_forks_repo_licenses": ["BSL-1.0"], "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": 35.9843137255, "max_line_length": 115, "alphanum_fraction": 0.5320401046, "num_tokens": 2988, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.45320963819081034}}
{"text": "#include <stdlib.h>\n#include <stdio.h>\n#include <iostream>\n#include <iomanip>\n#include <limits.h>\n#include <Eigen/Eigen>\n#include <opengv/triangulation/methods.hpp>\n#include <opengv/relative_pose/methods.hpp>\n#include <opengv/relative_pose/CentralRelativeAdapter.hpp>\n#include <opengv/sac_problems/relative_pose/CentralRelativePoseSacProblem.hpp>\n#include <opengv/absolute_pose/methods.hpp>\n#include <opengv/absolute_pose/CentralAbsoluteAdapter.hpp>\n#include <opengv/sac/Ransac.hpp>\n#include <opengv/sac_problems/absolute_pose/AbsolutePoseSacProblem.hpp>\n#include <opengv/math/cayley.hpp>\n#include <sstream>\n#include <fstream>\n#include <boost/concept_check.hpp>\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\t//initialize random seed\n\tinitializeRandomSeed();\n\t\n\t//set experiment parameters\n\tdouble noise = 2.5;\n\tdouble outlierFraction = 0.3;\n\tsize_t numberPoints = 200;\n\t\n\t//generate a random pose for viewpoint 1\n\ttranslation_t position1 = Eigen::Vector3d::Zero();\n\trotation_t rotation1 = Eigen::Matrix3d::Identity();\n\t\n\t//generate a random pose for viewpoint 2\n\ttranslation_t position2 = generateRandomTranslation(2.0);\n\trotation_t rotation2 = generateRandomRotation(0.25);\n\t\n\t//create a fake central camera\n\ttranslations_t camOffsets;\n\trotations_t camRotations;\n\tgenerateCentralCameraSystem( camOffsets, camRotations );\n\t\n\t//derive correspondences based on random point-cloud\n\tbearingVectors_t bearingVectors1;\n\tbearingVectors_t bearingVectors2;\n\tstd::vector<int> camCorrespondences1; //unused in the central case\n\tstd::vector<int> camCorrespondences2; //unused in the central case\n\tEigen::MatrixXd gt(3,numberPoints);\n\tgenerateRandom2D2DCorrespondences(\n\t\tposition1, rotation1, position2, rotation2,\n\t\tcamOffsets, camRotations, numberPoints, noise, outlierFraction,\n\t\tbearingVectors1, bearingVectors2,\n\t\tcamCorrespondences1, camCorrespondences2, gt );\n\t\n\t\n\tstd::cout << \"*************************************************\" << std::endl;\n\tstd::cout << \"\t\tGround Truth\" << std::endl;\n\tstd::cout << \"*************************************************\" << std::endl;\n\t\n\t//print the experiment characteristics\n\tprintExperimentCharacteristics(\n\t\tposition2 / position2.norm(), rotation2, noise, outlierFraction );\n\t\n\t/*********************************\n\t * \t\tCompute Relative Pose\t *\n\t * *******************************/\n\t\n\tstd::cout << \"*************************************************\" << std::endl;\n\tstd::cout << \"Computing relative Pose between View 0 and View 1\" << std::endl;\n\tstd::cout << \"*************************************************\" << std::endl;\n\t\n\trelative_pose::CentralRelativeAdapter rel_adapter(\n\t\tbearingVectors1,\n\t\tbearingVectors2);\n\t\n\tsac::Ransac<\n\tsac_problems::relative_pose::CentralRelativePoseSacProblem> rel_ransac;\n\tstd::shared_ptr<\n\tsac_problems::relative_pose::CentralRelativePoseSacProblem> relposeproblem_ptr(\n\t\tnew sac_problems::relative_pose::CentralRelativePoseSacProblem(\n\t\t\trel_adapter,\n\t\t\tsac_problems::relative_pose::CentralRelativePoseSacProblem::NISTER));\n\trel_ransac.sac_model_ = relposeproblem_ptr;\n\trel_ransac.threshold_ = 2.*(1.0 - cos(atan(sqrt(2.0)*0.5/800.0)));\n\trel_ransac.max_iterations_ = 1000;\n\t\n\t//Run the experiment\n\tstruct timeval tic;\n\tstruct timeval toc;\n\tgettimeofday( &tic, 0 );\n\trel_ransac.computeModel();\n\tgettimeofday( &toc, 0 );\n\tdouble ransac_time = TIMETODOUBLE(timeval_minus(toc,tic));\n\t\n\t//print results for ransac 1\n\tstd::cout << \"the ransac threshold is: \" << rel_ransac.threshold_ << std::endl;\n\tstd::cout << \"the normalized translation result is: \" << std::endl;\n\tstd::cout << rel_ransac.model_coefficients_.col(3)/\n\trel_ransac.model_coefficients_.col(3).norm() << std::endl << std::endl;\n\tstd::cout << \"Ransac needed \" << rel_ransac.iterations_ << \" iterations and \";\n\tstd::cout << ransac_time << \" seconds\" << std::endl << std::endl;\n\tstd::cout << \"the number of inliers is: \" << rel_ransac.inliers_.size() << \" out of \" << numberPoints;;\n\tstd::cout << std::endl << std::endl;\n\t\n\ttranslation_t t = rel_ransac.model_coefficients_.col(3) / rel_ransac.model_coefficients_.col(3).norm();\n\trotation_t R = rel_ransac.model_coefficients_.block<3,3>(0,0);\n\t\n\tbearingVectors1.clear();\n\tbearingVectors2.clear();\n\t\n\tfor(size_t i = 0 ; i < rel_ransac.inliers_.size() ; ++i)\n\t{\n\t\tbearingVectors1.push_back(rel_adapter.getBearingVector1(rel_ransac.inliers_[i]));\n\t\tbearingVectors2.push_back(rel_adapter.getBearingVector2(rel_ransac.inliers_[i]));\n\t}\n\t\n\trelative_pose::CentralRelativeAdapter adapter(\n\t\tbearingVectors1,\n\t\tbearingVectors2,\n\t\trel_adapter.gett12() / rel_adapter.gett12().norm(),\n\t\trel_adapter.getR12());\n\n\t/*********************************\n\t * \t\tTriangulate Points\t\t *\n\t * *******************************/\n\t\n\tstd::cout << \"*************************************************\" << std::endl;\n\tstd::cout << \"Triangulating Points between View 0 and View 1\" << std::endl;\n\tstd::cout << \"*************************************************\" << std::endl;\n\t\n\tstd::cout << \"running triangulation algorithm 2\" << std::endl << std::endl;\n\tMatrixXd triangulate2_results(3,(int) rel_ransac.inliers_.size());\n\tgettimeofday( &tic, 0 );\n\t\n\tfor(size_t j = 0; j < rel_ransac.inliers_.size(); j++)\n\t{\n\t\ttriangulate2_results.block<3,1>(0,j) = triangulation::triangulate2(adapter,j);\n\t}\n\t\n\tgettimeofday( &toc, 0 );\n\t\n\transac_time = TIMETODOUBLE(timeval_minus(toc,tic));\n\t\n\t/*\n\tstd::cout << \"triangulation truth: \" << std::endl;\n\tstd::cout << gt << std::endl;\n\t*/\n\t\n\tstd::cout << \"triangulation result: \" << std::endl;\n\tstd::cout << triangulate2_results.col(0) << std::endl << std::endl;\n\n\tstd::cout << \" in \" << ransac_time << \" seconds\" << std::endl << std::endl;\n\t\n\t/*\n\tMatrixXd error(1,numberPoints);\n\tfor(size_t i = 0; i < numberPoints; i++)\n\t{\n\t\tVector3d singleError = triangulate2_results.col(i) - gt.col(i);\n\t\terror(0,i) = singleError.norm();\n\t}\n\tstd::cout << \"triangulation error is: \" << std::endl << error << std::endl;\n\t*/\n\t\n\t/*********************************\n\t * \t\tCompute Absolute Pose\t *\n\t * *******************************/\n\t\n\t\n\tstd::cout << \"*************************************************\" << std::endl;\n\tstd::cout << \"Computing absolute Pose of View 1 from 3D points\" << std::endl;\n\tstd::cout << \"*************************************************\" << std::endl;\n\t\n\tpoints_t points;\n\t\n\tfor(size_t i = 0 ; i < rel_ransac.inliers_.size() ; ++i)\n\t{\n\t\t//store the point\n\t\tpoints.push_back(triangulate2_results.col(i));\n\t}\n\t\n\t//create a central absolute adapter\n\tabsolute_pose::CentralAbsoluteAdapter abs_adapter(\n\t\tbearingVectors2,\n\t\tpoints);\n\t\n\ttransformation_t optimized_pose;\n\t\n\t//Create an AbsolutePoseSac problem and Ransac\n\t//The method can be set to KNEIP, GAO or EPNP\n\tsac::Ransac<sac_problems::absolute_pose::AbsolutePoseSacProblem> abs_ransac;\n\tstd::shared_ptr<\n\tsac_problems::absolute_pose::AbsolutePoseSacProblem> abspose_kneip_ptr(\n\t\tnew sac_problems::absolute_pose::AbsolutePoseSacProblem(\n\t\t\tabs_adapter,\n\t\t\tsac_problems::absolute_pose::AbsolutePoseSacProblem::KNEIP));\n\tabs_ransac.sac_model_ = abspose_kneip_ptr;\n\tabs_ransac.threshold_ = 1.0*(1.0 - cos(atan(sqrt(2.0)*0.5/800.0)));\n\tabs_ransac.max_iterations_ = 1000;\n\t\n\t//Run the experiment\n\tgettimeofday( &tic, 0 );\n\tabs_ransac.computeModel();\n\tgettimeofday( &toc, 0 );\n\transac_time = TIMETODOUBLE(timeval_minus(toc,tic));\n\t\n\t//print the results\n\tstd::cout << \"KNEIP: \" << std::endl;\n\tstd::cout << \"the ransac results is: \" << std::endl;\n\tstd::cout << abs_ransac.model_coefficients_ << std::endl << std::endl;\n\tstd::cout << \"Ransac needed \" << abs_ransac.iterations_ << \" iterations and \";\n\tstd::cout << ransac_time << \" seconds\" << std::endl << std::endl;\n\tstd::cout << \"the number of inliers is: \" << abs_ransac.inliers_.size() << \" out of \" << rel_ransac.inliers_.size();\n\tstd::cout << std::endl << std::endl;\n\t\n\tabs_ransac.sac_model_->optimizeModelCoefficients(abs_ransac.inliers_, abs_ransac.model_coefficients_, optimized_pose);\n\t\n\tstd::cout << \"the sac optimized ransac results is: \" << std::endl;\n\tstd::cout <<  optimized_pose << std::endl << std::endl;\n\t\n\tt = abs_ransac.model_coefficients_.col(3);\n\tR = abs_ransac.model_coefficients_.block<3,3>(0,0);\n\t\n\tabs_adapter.sett(t);\n\tabs_adapter.setR(R);\n\t\n\ttransformation_t nonlinear_transformation =\n\tabsolute_pose::optimize_nonlinear(abs_adapter);\n\t\n\tstd::cout << \"results from nonlinear algorithm with every points:\" << std::endl;\n\tstd::cout << nonlinear_transformation << std::endl << std::endl;\n\t\n\tstd::cout << \"Truth is: \" << std::endl  << std::endl;\n\tstd::cout << position2 / position2.norm() << std::endl << std::endl;\n\tstd::cout << rotation2 << std::endl << std::endl;\n\t\n\t\n\t/*********************************\n\t * \t\tSimulation of view 3\t *\n\t * *******************************/\n\t\n\t\n\tstd::cout << \"*************************************************\" << std::endl;\n\tstd::cout << \"\t\tSimulating a 3rd View \" << std::endl;\n\tstd::cout << \"*************************************************\" << std::endl;\n\t\n\t//generate a random pose for viewpoint 3\n\ttranslation_t position3 = position2 + generateRandomTranslation(5.0);\n\trotation_t rotation3 = generateRandomRotation(0.25);\n\n\t//derive correspondences based on random point-cloud\n\tbearingVectors_t bearingVectors3;\n\tstd::vector<int> camCorrespondences22; //unused in the central case\n\tstd::vector<int> camCorrespondences33; //unused in the central case\n\t\n\tfor( size_t i = 0; i < points.size(); i++ )\n\t{\n\t\t//get the point in viewpoint 3\n\t\tpoint_t bodyPoint3 = rotation3.transpose()*(points[i] - position3);\n\n\t\t//get the point in the camera in viewpoint 2\n\t\tbearingVectors3.push_back(bodyPoint3);\n\t\t\n\t\t//normalize the bearing-vectors\n\t\tbearingVectors3[i] = bearingVectors3[i] / bearingVectors3[i].norm();\n\t\t\n\t\t//add noise\n\t\tbearingVectors3[i] = addNoise(2.5,bearingVectors3[i]);\n\t}\n\n\t//print the experiment characteristics\n\tprintExperimentCharacteristics(\n\t\tposition3, rotation3, noise, outlierFraction );\n\t\n\t//create a central absolute adapter\n\tabsolute_pose::CentralAbsoluteAdapter next_abs_adapter(\n\t\tbearingVectors3,\n\t\tpoints);\n\t\n\t//Create an AbsolutePoseSac problem and Ransac\n\t//The method can be set to KNEIP, GAO or EPNP\n\tsac::Ransac<sac_problems::absolute_pose::AbsolutePoseSacProblem> next_abs_ransac;\n\tstd::shared_ptr<\n\tsac_problems::absolute_pose::AbsolutePoseSacProblem> next_abspose_kneip_ptr(\n\t\tnew sac_problems::absolute_pose::AbsolutePoseSacProblem(\n\t\t\tnext_abs_adapter,\n\t\t\tsac_problems::absolute_pose::AbsolutePoseSacProblem::KNEIP));\n\tnext_abs_ransac.sac_model_ = next_abspose_kneip_ptr;\n\tnext_abs_ransac.threshold_ = 2.0*(1.0 - cos(atan(sqrt(2.0)*0.5/800.0)));\n\tnext_abs_ransac.max_iterations_ = 1000;\n\t\n\t//Run the experiment\n\tgettimeofday( &tic, 0 );\n\tnext_abs_ransac.computeModel();\n\tgettimeofday( &toc, 0 );\n\transac_time = TIMETODOUBLE(timeval_minus(toc,tic));\n\t\n\t//print the results\n\tstd::cout << \"KNEIP: \" << std::endl;\n\tstd::cout << \"the ransac results is: \" << std::endl;\n\tstd::cout << next_abs_ransac.model_coefficients_ << std::endl << std::endl;\n\tstd::cout << \"Ransac needed \" << next_abs_ransac.iterations_ << \" iterations and \";\n\tstd::cout << ransac_time << \" seconds\" << std::endl << std::endl;\n\tstd::cout << \"the number of inliers is: \" << next_abs_ransac.inliers_.size() << \" out of \" << rel_ransac.inliers_.size();\n\tstd::cout << std::endl << std::endl;\n\t\n\tnext_abs_ransac.sac_model_->optimizeModelCoefficients(next_abs_ransac.inliers_, next_abs_ransac.model_coefficients_, optimized_pose);\n\t\n\tstd::cout << \"the sac optimized ransac results is: \" << std::endl;\n\tstd::cout <<  optimized_pose << std::endl << std::endl;\n\t\n\tt = next_abs_ransac.model_coefficients_.col(3);\n\tR = next_abs_ransac.model_coefficients_.block<3,3>(0,0);\n\t\n\tnext_abs_adapter.sett(t);\n\tnext_abs_adapter.setR(R);\n\t\n\tnonlinear_transformation =\n\tabsolute_pose::optimize_nonlinear(next_abs_adapter);\n\t\n\tstd::cout << \"results from nonlinear algorithm with every points:\" << std::endl;\n\tstd::cout << nonlinear_transformation << std::endl << std::endl;\n\t\n\tstd::cout << \"Truth is: \" << std::endl  << std::endl;\n\tstd::cout << position3 << std::endl << std::endl;\n\tstd::cout << rotation3 << std::endl << std::endl;\n\t\n}\n\t", "meta": {"hexsha": "84735dcc06dfa187fe6ea420f0ae8e26f3260247", "size": 12205, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_odom.cpp", "max_stars_repo_name": "ferreram/opengv", "max_stars_repo_head_hexsha": "c2c1fd306169e3ae92f256da989a94295e7aa8ee", "max_stars_repo_licenses": ["BSD-3-Clause"], "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_odom.cpp", "max_issues_repo_name": "ferreram/opengv", "max_issues_repo_head_hexsha": "c2c1fd306169e3ae92f256da989a94295e7aa8ee", "max_issues_repo_licenses": ["BSD-3-Clause"], "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_odom.cpp", "max_forks_repo_name": "ferreram/opengv", "max_forks_repo_head_hexsha": "c2c1fd306169e3ae92f256da989a94295e7aa8ee", "max_forks_repo_licenses": ["BSD-3-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.2166172107, "max_line_length": 134, "alphanum_fraction": 0.6731667349, "num_tokens": 3370, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.45320963210154147}}
{"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 <utility>\n#include <Eigen/Core>\n#include <limits>\n#include <cassert>\n#include \"metro/regression/LogLikelihood.hpp\"\n#include \"metro/ModifiedCholesky.hpp\"\n#include \"metro/ModifiedNewtonRaphson.hpp\"\n#include \"metro/CholeskyStepper.hpp\"\n\n#define DEBUG 1\n\nnamespace metro {\n\tCholeskyStepper::CholeskyStepper( double tolerance, int max_iterations, Tracer tracer ):\n\t\tm_tolerance( tolerance ),\n\t\tm_max_iterations( max_iterations ),\n\t\tm_tracer( tracer ),\n\t\tm_iteration( -1 ),\n\t\tm_target_ll( -std::numeric_limits< double >::infinity() )\n\t{\n\t\tassert( tolerance > 0 ) ;\n\t}\n\t\n\tbool CholeskyStepper::step( Function& function, Vector* result ) {\n\t\t++m_iteration ;\n\t\t//std::cerr << \"CholeskyStepper::step(): calling evaluate()...\\n\" ;\n\t\tfunction.evaluate( 2 ) ;\n\t\tdouble const ll = function.get_value_of_function() ;\n\t\tm_solver.compute( -function.get_value_of_second_derivative() ) ;\n\n\t\t// Different possible stopping conditions are possible.\n\t\t// One is to stop when the predicted improvement in function\n\t\t// value is small.  This amount is encoded by the directional derivative.\n\t\t// However, for statistical model fitting we would like a rule that is invariant to\n\t\t// various types of rescaling the function.  For example\n\t\t// - scaling parameters (which scales the derivative)\n\t\t// - multiplying the function by a constant (which is a bit like adding more data)\n\t\t// A rule like directional_derivative < tolerance does not have these properties.\n\n\t\t// Instead, we compute the derivative normalised to 'standard Gaussian' space.\n\t\t// Theory: if the function 2nd derivative H = LL\u1d57 then \u03a3=(L\u1d57)\u207b\u00b9L\u207b\u00b9.\n\t\t// We assume the log-likelihood looks like this:\n\t\t// f(x) = s(L\u1d57(x-x\u2080)) + O((x-x\u2080)\u00b3)\n\t\t// near the true maximum x\u2080, where s is the standard multivariate normal\n\t\t// log-density.  Then\n\t\t// f'(x) = -L L\u1d57 (x-x\u2080) + O((x-x\u2080)\u00b2)   (expressed as a column vector).\n\t\t// We put a convergence condition on the corresponding derivative in s-space, given by\n\t\t// z = L\u207b\u00b9 f'(x) = -L\u1d57(x-x\u2080) + O((x-x\u2080)\u00b2)\n\t\t// This has the nice interpretation of being interpretable as a distance\n\t\t// to the maximum in the uncorrelated-variable space that is the domain of s.\n\n\t\tdouble const derivativeOneNorm = function.get_value_of_first_derivative().array().abs().maxCoeff() ;\n\t\tVector step = m_solver.solve( function.get_value_of_first_derivative() ) ;\n\t\t//Vector const sqrtStep = m_solver.halfSolve( function.get_value_of_first_derivative() ) ;\n\t\tdouble directional_derivative = function.get_value_of_first_derivative().transpose() * step ;\n\n\t\tbool converged = (\n\t\t\t(derivativeOneNorm < m_tolerance)\n\t\t\t&& ( ll >= ( m_target_ll - m_tolerance ) )\n\t\t\t//&& (sqrtStep.array().abs().maxCoeff() < m_tolerance )\n\t\t\t&& (directional_derivative < m_tolerance )\n\t\t) ;\n\n\t\tif( m_tracer ) {\n\t\t\tm_tracer( m_iteration, ll, m_target_ll, function.parameters(), function.get_value_of_first_derivative(), step, converged ) ;\n\t\t}\n\n\t\tif(\n\t\t\tconverged || (m_iteration) >= m_max_iterations \n\t\t) {\n\t\t\treturn false ;\n\t\t} else {\n\t\t\t(*result) = step ;\n\t\t\tm_target_ll = std::max( m_target_ll, ll ) ;\n\t\t\treturn true ;\n\t\t}\n\t}\n\t\n\tbool CholeskyStepper::diverged() const {\n\t\treturn m_iteration >= m_max_iterations || m_target_ll != m_target_ll ;\n\t}\n\n\tstd::size_t CholeskyStepper::number_of_iterations() const {\n\t\treturn m_iteration ;\n\t}\n\n\tvoid CholeskyStepper::reset() {\n\t\tm_iteration = -1 ;\n\t\tm_target_ll = -std::numeric_limits< double >::infinity() ;\n\t}\n}\n", "meta": {"hexsha": "f003ac0ba65c7af1051cfeba5d30b599274c2909", "size": 3633, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "metro/src/CholeskyStepper.cpp", "max_stars_repo_name": "gavinband/qctool", "max_stars_repo_head_hexsha": "8d8adb45151c91f953fe4a9af00498073b1132ba", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-04-21T05:42:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T14:59:43.000Z", "max_issues_repo_path": "metro/src/CholeskyStepper.cpp", "max_issues_repo_name": "gavinband/qctool", "max_issues_repo_head_hexsha": "8d8adb45151c91f953fe4a9af00498073b1132ba", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-09T16:11:04.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-10T11:18:56.000Z", "max_forks_repo_path": "metro/src/CholeskyStepper.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.0714285714, "max_line_length": 127, "alphanum_fraction": 0.7065785852, "num_tokens": 998, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4532096321015414}}
{"text": "#ifndef CY_NNQS_JASTROW_HPP\n#define CY_NNQS_JASTROW_HPP\n#include <random>\n#include <Eigen/Dense>\n#include \"Utilities/type_traits.hpp\"\n#include <nlohmann/json.hpp>\nnamespace yannq\n{\ntemplate<typename T>\nclass Jastrow\n{\npublic:\n\tusing Scalar=T;\n\ttypedef Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> Matrix;\n\ttypedef Eigen::Matrix<T, Eigen::Dynamic, 1>  Vector;\n\nprivate:\n\tint n_;\n\n\tVector a_;\n\tMatrix J_;\n\npublic:\n\n\tnlohmann::json desc() const\n\t{\n\t\treturn nlohmann::json\n\t\t{\n\t\t\t{\"name\", \"Jastrow\"},\n\t\t\t{\"n\", n_},\n\t\t};\n\t}\n\n\n\tinline int getN() const\n\t{\n\t\treturn n_;\n\t}\n\n\tJastrow(int n)\n\t\t: n_(n), a_(n_), J_(n,n)\n\t{\n\t}\n\n\tvoid resize(int n)\n\t{\n\t\tn_ = n;\n\t\ta_.resize(n);\n\t\tJ_.resize(n,n);\n\t}\n\n\tint getDim() const\n\t{\n\t\treturn n_ + n_*(n_-1)/2;\n\t}\n\n\tVector getA() const\n\t{\n\t\treturn a_;\n\t}\n\tMatrix getJ() const\n\t{\n\t\treturn J_;\n\t}\n\n\tvoid setA(const Vector& a) const\n\t{\n\t\ta_ = a;\n\t}\n\n\tvoid setJ(const Matrix& J) const\n\t{\n\t\tJ_ = J;\n\t}\n\n\n\n\tT A(int i) const\n\t{\n\t\treturn a_(i);\n\t}\n\tT J(int i, int j) const\n\t{\n\t\treturn J_(i,j);\n\t}\n\n\ttemplate <typename RandomEngine, class U=T,\n               typename std::enable_if < !is_complex_type<U>::value, int >::type = 0 >\n\tvoid initializeRandom(RandomEngine& re, T weight = 0.001)\n\t{\n\t\tstd::normal_distribution<double> nd{};\n\t\t\n\t\tfor(int i = 0; i < n_; i++)\n\t\t{\n\t\t\ta_(i) = weight*nd(re);\n\t\t}\n\t\tJ_.setZero();\n\t\tfor(int j = n_-1; j >=0; --j)\n\t\t{\n\t\t\tfor(int i = 0; i < j; i++)\n\t\t\t{\n\t\t\t\tJ_(i, j) = weight*nd(re);\n\t\t\t}\n\t\t}\n\t}\n\ttemplate <typename RandomEngine, class U=T,\n               typename std::enable_if < is_complex_type<U>::value, int >::type = 0 >\n\tvoid initializeRandom(RandomEngine& re, T weight = 0.001)\n\t{\n\t\tstd::normal_distribution<double> nd{};\n\t\t\n\t\tfor(int i = 0; i < n_; i++)\n\t\t{\n\t\t\ta_(i) = weight*T(nd(re),nd(re));\n\t\t}\n\t\tJ_.setZero();\n\t\tfor(int j = n_-1; j >=0; --j)\n\t\t{\n\t\t\tfor(int i = 0; i < j; i++)\n\t\t\t{\n\t\t\t\tJ_(i, j) = weight*T(nd(re),nd(re));\n\t\t\t}\n\t\t}\n\t}\n\n\tT calcTheta(const Eigen::VectorXi& sigma) const\n\t{\n\t\tVector s = sigma.cast<T>();\n\t\tT res = a_.transpose()*s;\n\t\tres += T(s.transpose()*J_*s);\n\t\treturn res;\n\t}\n\n\tstd::tuple<Eigen::VectorXi, T> makeData(const Eigen::VectorXi& sigma) const\n\t{\n\t\treturn std::make_tuple(sigma, calcTheta(sigma));\n\t}\n\n\tVector logDeriv(const std::tuple<Eigen::VectorXi, T>& t) const\n\t{\n\t\tVector res(getDim());\n\t\tfor(int i = 0; i < n_; i++)\n\t\t{\n\t\t\tres(i) = std::get<0>(t)(i);\n\t\t}\n\t\tfor(int i = 0; i < n_; i++)\n\t\t{\n\t\t\tfor(int j = i+1; i < n_; j++)\n\t\t\t{\n\t\t\t\tres(i*n_+j+n_) = std::get<0>(t)(i)*std::get<0>(t)(j);\n\t\t\t}\n\t\t}\n\t\treturn res;\n\t}\n\n\tvoid updateParams(const Vector& u)\n\t{\n\t\ta_ += u.segment(0, n_);\n\t\tfor(int i = 0; i < n_; i++)\n\t\t{\n\t\t\tfor(int j = i+1; i < n_; j++)\n\t\t\t{\n\t\t\t\tJ_(i, j) += u(i*n_ + j + n_);\n\t\t\t}\n\t\t}\n\t}\n\n\n};\n}\n#endif//CY_NNQS_JASTROW_HPP\n", "meta": {"hexsha": "d2945b9fd49094870056ad7dd5a7c7619e2bb122", "size": 2732, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Yannq/Machines/Jastrow.hpp", "max_stars_repo_name": "cecri/yannq", "max_stars_repo_head_hexsha": "b78c1f86a255059f06b34dd5e538449e7261d0ee", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Yannq/Machines/Jastrow.hpp", "max_issues_repo_name": "cecri/yannq", "max_issues_repo_head_hexsha": "b78c1f86a255059f06b34dd5e538449e7261d0ee", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Yannq/Machines/Jastrow.hpp", "max_forks_repo_name": "cecri/yannq", "max_forks_repo_head_hexsha": "b78c1f86a255059f06b34dd5e538449e7261d0ee", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.8837209302, "max_line_length": 86, "alphanum_fraction": 0.5636896047, "num_tokens": 992, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4532096321015414}}
{"text": "// \u591a\u500d\u9577\u6574\u6570\u30a8\u30a4\u30ea\u30a2\u30b9 (\u88dc\u5b8c\u30fb\u30b3\u30f3\u30d1\u30a4\u30eb\u304c\u91cd\u304f\u306a\u308b)\n#include <boost/multiprecision/cpp_int.hpp>\nusing mll = boost::multiprecision::cpp_int;", "meta": {"hexsha": "0d17fb98b5eb0e4075dcaf03355883043835fee8", "size": 117, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "template/base_template/mll.cpp", "max_stars_repo_name": "ganmodokix/ysn", "max_stars_repo_head_hexsha": "74cad18941102539493dda821e17e767bbecde89", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "template/base_template/mll.cpp", "max_issues_repo_name": "ganmodokix/ysn", "max_issues_repo_head_hexsha": "74cad18941102539493dda821e17e767bbecde89", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "template/base_template/mll.cpp", "max_forks_repo_name": "ganmodokix/ysn", "max_forks_repo_head_hexsha": "74cad18941102539493dda821e17e767bbecde89", "max_forks_repo_licenses": ["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.0, "max_line_length": 43, "alphanum_fraction": 0.7863247863, "num_tokens": 51, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4532096321015414}}
{"text": "\r\n///////////////////////////////////////////////////////////////////////////////\r\n//  Copyright 2013 Nikhar Agrawal\r\n//  Copyright 2013 Christopher Kormanyos\r\n//  Copyright 2014 John Maddock\r\n//  Copyright 2013 Paul Bristow\r\n//  Distributed under the Boost\r\n//  Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef _BOOST_POLYGAMMA_DETAIL_2013_07_30_HPP_\r\n  #define _BOOST_POLYGAMMA_DETAIL_2013_07_30_HPP_\r\n\r\n#include <cmath>\r\n  #include <limits>\r\n  #include <boost/cstdint.hpp>\r\n  #include <boost/math/policies/policy.hpp>\r\n  #include <boost/math/special_functions/bernoulli.hpp>\r\n  #include <boost/math/special_functions/trunc.hpp>\r\n  #include <boost/math/special_functions/zeta.hpp>\r\n  #include <boost/math/special_functions/digamma.hpp>\r\n  #include <boost/math/special_functions/sin_pi.hpp>\r\n  #include <boost/math/special_functions/cos_pi.hpp>\r\n  #include <boost/math/special_functions/pow.hpp>\r\n  #include <boost/mpl/if.hpp>\r\n  #include <boost/mpl/int.hpp>\r\n  #include <boost/static_assert.hpp>\r\n  #include <boost/type_traits/is_convertible.hpp>\r\n\r\n#ifdef _MSC_VER\r\n#pragma once\r\n#pragma warning(push)\r\n#pragma warning(disable:4702) // Unreachable code (release mode only warning)\r\n#endif\r\n\r\nnamespace boost { namespace math { namespace detail{\r\n\r\n  template<class T, class Policy>\r\n  T polygamma_atinfinityplus(const int n, const T& x, const Policy& pol, const char* function) // for large values of x such as for x> 400\r\n  {\r\n     // See http://functions.wolfram.com/GammaBetaErf/PolyGamma2/06/02/0001/\r\n     BOOST_MATH_STD_USING\r\n     //\r\n     // sum       == current value of accumulated sum.\r\n     // term      == value of current term to be added to sum.\r\n     // part_term == value of current term excluding the Bernoulli number part\r\n     //\r\n     if(n + x == x)\r\n     {\r\n        // x is crazy large, just concentrate on the first part of the expression and use logs:\r\n        if(n == 1) return 1 / x;\r\n        T nlx = n * log(x);\r\n        if((nlx < tools::log_max_value<T>()) && (n < (int)max_factorial<T>::value))\r\n           return ((n & 1) ? 1 : -1) * boost::math::factorial<T>(n - 1) * pow(x, -n);\r\n        else\r\n         return ((n & 1) ? 1 : -1) * exp(boost::math::lgamma(T(n), pol) - n * log(x));\r\n     }\r\n     T term, sum, part_term;\r\n     T x_squared = x * x;\r\n     //\r\n     // Start by setting part_term to:\r\n     //\r\n     // (n-1)! / x^(n+1)\r\n     //\r\n     // which is common to both the first term of the series (with k = 1)\r\n     // and to the leading part.  \r\n     // We can then get to the leading term by:\r\n     //\r\n     // part_term * (n + 2 * x) / 2\r\n     //\r\n     // and to the first term in the series \r\n     // (excluding the Bernoulli number) by:\r\n     //\r\n     // part_term n * (n + 1) / (2x)\r\n     //\r\n     // If either the factorial would overflow,\r\n     // or the power term underflows, this just gets set to 0 and then we\r\n     // know that we have to use logs for the initial terms:\r\n     //\r\n     part_term = ((n > (int)boost::math::max_factorial<T>::value) && (T(n) * n > tools::log_max_value<T>())) \r\n        ? T(0) : static_cast<T>(boost::math::factorial<T>(n - 1, pol) * pow(x, -n - 1));\r\n     if(part_term == 0)\r\n     {\r\n        // Either n is very large, or the power term underflows,\r\n        // set the initial values of part_term, term and sum via logs:\r\n        part_term = static_cast<T>(boost::math::lgamma(n, pol) - (n + 1) * log(x));\r\n        sum = exp(part_term + log(n + 2 * x) - boost::math::constants::ln_two<T>());\r\n        part_term += log(T(n) * (n + 1)) - boost::math::constants::ln_two<T>() - log(x);\r\n        part_term = exp(part_term);\r\n     }\r\n     else\r\n     {\r\n        sum = part_term * (n + 2 * x) / 2;\r\n        part_term *= (T(n) * (n + 1)) / 2;\r\n        part_term /= x;\r\n     }\r\n     //\r\n     // If the leading term is 0, so is the result:\r\n     //\r\n     if(sum == 0)\r\n        return sum;\r\n\r\n     for(unsigned k = 1;;)\r\n     {\r\n        term = part_term * boost::math::bernoulli_b2n<T>(k, pol);\r\n        sum += term;\r\n        //\r\n        // Normal termination condition:\r\n        //\r\n        if(fabs(term / sum) < tools::epsilon<T>())\r\n           break;\r\n        //\r\n        // Increment our counter, and move part_term on to the next value:\r\n        //\r\n        ++k;\r\n        part_term *= T(n + 2 * k - 2) * (n - 1 + 2 * k);\r\n        part_term /= (2 * k - 1) * 2 * k;\r\n        part_term /= x_squared;\r\n        //\r\n        // Emergency get out termination condition:\r\n        //\r\n        if(k > policies::get_max_series_iterations<Policy>())\r\n        {\r\n           return policies::raise_evaluation_error(function, \"Series did not converge, closest value was %1%\", sum, pol);\r\n        }\r\n     }\r\n     \r\n     if((n - 1) & 1)\r\n        sum = -sum;\r\n\r\n     return sum;\r\n  }\r\n\r\n  template<class T, class Policy>\r\n  T polygamma_attransitionplus(const int n, const T& x, const Policy& pol, const char* function)\r\n  {\r\n    // See: http://functions.wolfram.com/GammaBetaErf/PolyGamma2/16/01/01/0017/\r\n\r\n    // Use N = (0.4 * digits) + (4 * n) for target value for x:\r\n    BOOST_MATH_STD_USING\r\n    const int d4d  = static_cast<int>(0.4F * policies::digits_base10<T, Policy>());\r\n    const int N = d4d + (4 * n);\r\n    const int m    = n;\r\n    const int iter = N - itrunc(x);\r\n\r\n    if(iter > (int)policies::get_max_series_iterations<Policy>())\r\n       return policies::raise_evaluation_error<T>(function, (\"Exceeded maximum series evaluations evaluating at n = \" + boost::lexical_cast<std::string>(n) + \" and x = %1%\").c_str(), x, pol);\r\n\r\n    const int minus_m_minus_one = -m - 1;\r\n\r\n    T z(x);\r\n    T sum0(0);\r\n    T z_plus_k_pow_minus_m_minus_one(0);\r\n\r\n    // Forward recursion to larger x, need to check for overflow first though:\r\n    if(log(z + iter) * minus_m_minus_one > -tools::log_max_value<T>())\r\n    {\r\n       for(int k = 1; k <= iter; ++k)\r\n       {\r\n          z_plus_k_pow_minus_m_minus_one = pow(z, minus_m_minus_one);\r\n          sum0 += z_plus_k_pow_minus_m_minus_one;\r\n          z += 1;\r\n       }\r\n       sum0 *= boost::math::factorial<T>(n);\r\n    }\r\n    else\r\n    {\r\n       for(int k = 1; k <= iter; ++k)\r\n       {\r\n          T log_term = log(z) * minus_m_minus_one + boost::math::lgamma(T(n + 1), pol);\r\n          sum0 += exp(log_term);\r\n          z += 1;\r\n       }\r\n    }\r\n    if((n - 1) & 1)\r\n       sum0 = -sum0;\r\n\r\n    return sum0 + polygamma_atinfinityplus(n, z, pol, function);\r\n  }\r\n\r\n  template <class T, class Policy>\r\n  T polygamma_nearzero(int n, T x, const Policy& pol, const char* function)\r\n  {\r\n     BOOST_MATH_STD_USING\r\n     //\r\n     // If we take this expansion for polygamma: http://functions.wolfram.com/06.15.06.0003.02\r\n     // and substitute in this expression for polygamma(n, 1): http://functions.wolfram.com/06.15.03.0009.01\r\n     // we get an alternating series for polygamma when x is small in terms of zeta functions of\r\n     // integer arguments (which are easy to evaluate, at least when the integer is even).\r\n     //\r\n     // In order to avoid spurious overflow, save the n! term for later, and rescale at the end:\r\n     //\r\n     T scale = boost::math::factorial<T>(n, pol);\r\n     //\r\n     // \"factorial_part\" contains everything except the zeta function\r\n     // evaluations in each term:\r\n     //\r\n     T factorial_part = 1;\r\n     //\r\n     // \"prefix\" is what we'll be adding the accumulated sum to, it will\r\n     // be n! / z^(n+1), but since we're scaling by n! it's just \r\n     // 1 / z^(n+1) for now:\r\n     //\r\n     T prefix = pow(x, n + 1);\r\n     if(prefix == 0)\r\n        return boost::math::policies::raise_overflow_error<T>(function, 0, pol);\r\n     prefix = 1 / prefix;\r\n     //\r\n     // First term in the series is necessarily < zeta(2) < 2, so\r\n     // ignore the sum if it will have no effect on the result anyway:\r\n     //\r\n     if(prefix > 2 / policies::get_epsilon<T, Policy>())\r\n        return ((n & 1) ? 1 : -1) * \r\n         (tools::max_value<T>() / prefix < scale ? policies::raise_overflow_error<T>(function, 0, pol) : prefix * scale);\r\n     //\r\n     // As this is an alternating series we could accelerate it using \r\n     // \"Convergence Acceleration of Alternating Series\",\r\n     // Henri Cohen, Fernando Rodriguez Villegas, and Don Zagier, Experimental Mathematics, 1999.\r\n     // In practice however, it appears not to make any difference to the number of terms\r\n     // required except in some edge cases which are filtered out anyway before we get here.\r\n     //\r\n     T sum = prefix;\r\n     for(unsigned k = 0;;)\r\n     {\r\n        // Get the k'th term:\r\n        T term = factorial_part * boost::math::zeta(T(k + n + 1), pol);\r\n        sum += term;\r\n        // Termination condition:\r\n        if(fabs(term) < fabs(sum * boost::math::policies::get_epsilon<T, Policy>()))\r\n           break;\r\n        //\r\n        // Move on k and factorial_part:\r\n        //\r\n        ++k;\r\n        factorial_part *= (-x * (n + k)) / k;\r\n        //\r\n        // Last chance exit:\r\n        //\r\n        if(k > policies::get_max_series_iterations<Policy>())\r\n           return policies::raise_evaluation_error<T>(function, \"Series did not converge, best value is %1%\", sum, pol);\r\n     }\r\n     //\r\n     // We need to multiply by the scale, at each stage checking for oveflow:\r\n     //\r\n     if(boost::math::tools::max_value<T>() / scale < sum)\r\n        return boost::math::policies::raise_overflow_error<T>(function, 0, pol);\r\n     sum *= scale;\r\n     return n & 1 ? sum : T(-sum);\r\n  }\r\n\r\n  //\r\n  // Helper function which figures out which slot our coefficient is in\r\n  // given an angle multiplier for the cosine term of power:\r\n  //\r\n  template <class Table>\r\n  typename Table::value_type::reference dereference_table(Table& table, unsigned row, unsigned power)\r\n  {\r\n     return table[row][power / 2];\r\n  }\r\n\r\n\r\n\r\n  template <class T, class Policy>\r\n  T poly_cot_pi(int n, T x, T xc, const Policy& pol, const char* function)\r\n  {\r\n     BOOST_MATH_STD_USING\r\n     // Return n'th derivative of cot(pi*x) at x, these are simply\r\n     // tabulated for up to n = 9, beyond that it is possible to\r\n     // calculate coefficients as follows:\r\n     //\r\n     // The general form of each derivative is:\r\n     //\r\n     // pi^n * SUM{k=0, n} C[k,n] * cos^k(pi * x) * csc^(n+1)(pi * x)\r\n     //\r\n     // With constant C[0,1] = -1 and all other C[k,n] = 0;\r\n     // Then for each k < n+1:\r\n     // C[k-1, n+1]  -= k * C[k, n];\r\n     // C[k+1, n+1]  += (k-n-1) * C[k, n];\r\n     //\r\n     // Note that there are many different ways of representing this derivative thanks to\r\n     // the many trigomonetric identies available.  In particular, the sum of powers of\r\n     // cosines could be replaced by a sum of cosine multiple angles, and indeed if you\r\n     // plug the derivative into Mathematica this is the form it will give.  The two\r\n     // forms are related via the Chebeshev polynomials of the first kind and\r\n     // T_n(cos(x)) = cos(n x).  The polynomial form has the great advantage that\r\n     // all the cosine terms are zero at half integer arguments - right where this\r\n     // function has it's minumum - thus avoiding cancellation error in this region.\r\n     //\r\n     // And finally, since every other term in the polynomials is zero, we can save\r\n     // space by only storing the non-zero terms.  This greatly complexifies\r\n     // subscripting the tables in the calculation, but halves the storage space\r\n     // (and complexity for that matter).\r\n     //\r\n     T s = fabs(x) < fabs(xc) ? boost::math::sin_pi(x, pol) : boost::math::sin_pi(xc, pol);\r\n     T c = boost::math::cos_pi(x, pol);\r\n     switch(n)\r\n     {\r\n     case 1:\r\n        return -constants::pi<T, Policy>() / (s * s);\r\n     case 2:\r\n     {\r\n        return 2 * constants::pi<T, Policy>() * constants::pi<T, Policy>() * c / boost::math::pow<3>(s, pol);\r\n     }\r\n     case 3:\r\n     {\r\n        int P[] = { -2, -4 };\r\n        return boost::math::pow<3>(constants::pi<T, Policy>(), pol) * tools::evaluate_even_polynomial(P, c) / boost::math::pow<4>(s, pol);\r\n     }\r\n     case 4:\r\n     {\r\n        int P[] = { 16, 8 };\r\n        return boost::math::pow<4>(constants::pi<T, Policy>(), pol) * c * tools::evaluate_even_polynomial(P, c) / boost::math::pow<5>(s, pol);\r\n     }\r\n     case 5:\r\n     {\r\n        int P[] = { -16, -88, -16 };\r\n        return boost::math::pow<5>(constants::pi<T, Policy>(), pol) * tools::evaluate_even_polynomial(P, c) / boost::math::pow<6>(s, pol);\r\n     }\r\n     case 6:\r\n     {\r\n        int P[] = { 272, 416, 32 };\r\n        return boost::math::pow<6>(constants::pi<T, Policy>(), pol) * c * tools::evaluate_even_polynomial(P, c) / boost::math::pow<7>(s, pol);\r\n     }\r\n     case 7:\r\n     {\r\n        int P[] = { -272, -2880, -1824, -64 };\r\n        return boost::math::pow<7>(constants::pi<T, Policy>(), pol) * tools::evaluate_even_polynomial(P, c) / boost::math::pow<8>(s, pol);\r\n     }\r\n     case 8:\r\n     {\r\n        int P[] = { 7936, 24576, 7680, 128 };\r\n        return boost::math::pow<8>(constants::pi<T, Policy>(), pol) * c * tools::evaluate_even_polynomial(P, c) / boost::math::pow<9>(s, pol);\r\n     }\r\n     case 9:\r\n     {\r\n        int P[] = { -7936, -137216, -185856, -31616, -256 };\r\n        return boost::math::pow<9>(constants::pi<T, Policy>(), pol) * tools::evaluate_even_polynomial(P, c) / boost::math::pow<10>(s, pol);\r\n     }\r\n     case 10:\r\n     {\r\n        int P[] = { 353792, 1841152, 1304832, 128512, 512 };\r\n        return boost::math::pow<10>(constants::pi<T, Policy>(), pol) * c * tools::evaluate_even_polynomial(P, c) / boost::math::pow<11>(s, pol);\r\n     }\r\n     case 11:\r\n     {\r\n        int P[] = { -353792, -9061376, -21253376, -8728576, -518656, -1024};\r\n        return boost::math::pow<11>(constants::pi<T, Policy>(), pol) * tools::evaluate_even_polynomial(P, c) / boost::math::pow<12>(s, pol);\r\n     }\r\n     case 12:\r\n     {\r\n        int P[] = { 22368256, 175627264, 222398464, 56520704, 2084864, 2048 };\r\n        return boost::math::pow<12>(constants::pi<T, Policy>(), pol) * c * tools::evaluate_even_polynomial(P, c) / boost::math::pow<13>(s, pol);\r\n     }\r\n#ifndef BOOST_NO_LONG_LONG\r\n     case 13:\r\n     {\r\n        long long P[] = { -22368256LL, -795300864LL, -2868264960LL, -2174832640LL, -357888000LL, -8361984LL, -4096 };\r\n        return boost::math::pow<13>(constants::pi<T, Policy>(), pol) * tools::evaluate_even_polynomial(P, c) / boost::math::pow<14>(s, pol);\r\n     }\r\n     case 14:\r\n     {\r\n        long long P[] = { 1903757312LL, 21016670208LL, 41731645440LL, 20261765120LL, 2230947840LL, 33497088LL, 8192 };\r\n        return boost::math::pow<14>(constants::pi<T, Policy>(), pol) * c * tools::evaluate_even_polynomial(P, c) / boost::math::pow<15>(s, pol);\r\n     }\r\n     case 15:\r\n     {\r\n        long long P[] = { -1903757312LL, -89702612992LL, -460858269696LL, -559148810240LL, -182172651520LL, -13754155008LL, -134094848LL, -16384 };\r\n        return boost::math::pow<15>(constants::pi<T, Policy>(), pol) * tools::evaluate_even_polynomial(P, c) / boost::math::pow<16>(s, pol);\r\n     }\r\n     case 16:\r\n     {\r\n        long long P[] = { 209865342976LL, 3099269660672LL, 8885192097792LL, 7048869314560LL, 1594922762240LL, 84134068224LL, 536608768LL, 32768 };\r\n        return boost::math::pow<16>(constants::pi<T, Policy>(), pol) * c * tools::evaluate_even_polynomial(P, c) / boost::math::pow<17>(s, pol);\r\n     }\r\n     case 17:\r\n     {\r\n        long long P[] = { -209865342976LL, -12655654469632LL, -87815735738368LL, -155964390375424LL, -84842998005760LL, -13684856848384LL, -511780323328LL, -2146926592LL, -65536 };\r\n        return boost::math::pow<17>(constants::pi<T, Policy>(), pol) * tools::evaluate_even_polynomial(P, c) / boost::math::pow<18>(s, pol);\r\n     }\r\n     case 18:\r\n     {\r\n        long long P[] = { 29088885112832LL, 553753414467584LL, 2165206642589696LL, 2550316668551168LL, 985278548541440LL, 115620218667008LL, 3100738912256LL, 8588754944LL, 131072 };\r\n        return boost::math::pow<18>(constants::pi<T, Policy>(), pol) * c * tools::evaluate_even_polynomial(P, c) / boost::math::pow<19>(s, pol);\r\n     }\r\n     case 19:\r\n     {\r\n        long long P[] = { -29088885112832LL, -2184860175433728LL, -19686087844429824LL, -48165109676113920LL, -39471306959486976LL, -11124607890751488LL, -965271355195392LL, -18733264797696LL, -34357248000LL, -262144 };\r\n        return boost::math::pow<19>(constants::pi<T, Policy>(), pol) * tools::evaluate_even_polynomial(P, c) / boost::math::pow<20>(s, pol);\r\n     }\r\n     case 20:\r\n     {\r\n        long long P[] = { 4951498053124096LL, 118071834535526400LL, 603968063567560704LL, 990081991141490688LL, 584901762421358592LL, 122829335169859584LL, 7984436548730880LL, 112949304754176LL, 137433710592LL, 524288 };\r\n        return boost::math::pow<20>(constants::pi<T, Policy>(), pol) * c * tools::evaluate_even_polynomial(P, c) / boost::math::pow<21>(s, pol);\r\n     }\r\n#endif\r\n     }\r\n\r\n     //\r\n     // We'll have to compute the coefficients up to n, \r\n     // complexity is O(n^2) which we don't worry about for now\r\n     // as the values are computed once and then cached.\r\n     // However, if the final evaluation would have too many\r\n     // terms just bail out right away:\r\n     //\r\n     if((unsigned)n / 2u > policies::get_max_series_iterations<Policy>())\r\n        return policies::raise_evaluation_error<T>(function, \"The value of n is so large that we're unable to compute the result in reasonable time, best guess is %1%\", 0, pol);\r\n#ifdef BOOST_HAS_THREADS\r\n     static boost::detail::lightweight_mutex m;\r\n     boost::detail::lightweight_mutex::scoped_lock l(m);\r\n#endif\r\n     static int digits = tools::digits<T>();\r\n     static std::vector<std::vector<T> > table(1, std::vector<T>(1, T(-1)));\r\n\r\n     int current_digits = tools::digits<T>();\r\n\r\n     if(digits != current_digits)\r\n     {\r\n        // Oh my... our precision has changed!\r\n        table = std::vector<std::vector<T> >(1, std::vector<T>(1, T(-1)));\r\n        digits = current_digits;\r\n     }\r\n\r\n     int index = n - 1;\r\n\r\n     if(index >= (int)table.size())\r\n     {\r\n        for(int i = (int)table.size() - 1; i < index; ++i)\r\n        {\r\n           int offset = i & 1; // 1 if the first cos power is 0, otherwise 0.\r\n           int sin_order = i + 2;  // order of the sin term\r\n           int max_cos_order = sin_order - 1;  // largest order of the polynomial of cos terms\r\n           int max_columns = (max_cos_order - offset) / 2;  // How many entries there are in the current row.\r\n           int next_offset = offset ? 0 : 1;\r\n           int next_max_columns = (max_cos_order + 1 - next_offset) / 2;  // How many entries there will be in the next row\r\n           table.push_back(std::vector<T>(next_max_columns + 1, T(0)));\r\n\r\n           for(int column = 0; column <= max_columns; ++column)\r\n           {\r\n              int cos_order = 2 * column + offset;  // order of the cosine term in entry \"column\"\r\n              BOOST_ASSERT(column < (int)table[i].size());\r\n              BOOST_ASSERT((cos_order + 1) / 2 < (int)table[i + 1].size());\r\n              table[i + 1][(cos_order + 1) / 2] += ((cos_order - sin_order) * table[i][column]) / (sin_order - 1);\r\n              if(cos_order)\r\n                table[i + 1][(cos_order - 1) / 2] += (-cos_order * table[i][column]) / (sin_order - 1);\r\n           }\r\n        }\r\n\r\n     }\r\n     T sum = boost::math::tools::evaluate_even_polynomial(&table[index][0], c, table[index].size());\r\n     if(index & 1)\r\n        sum *= c;  // First coeffient is order 1, and really an odd polynomial.\r\n     if(sum == 0)\r\n        return sum;\r\n     //\r\n     // The remaining terms are computed using logs since the powers and factorials\r\n     // get real large real quick:\r\n     //\r\n     T power_terms = n * log(boost::math::constants::pi<T>());\r\n     if(s == 0)\r\n        return sum * boost::math::policies::raise_overflow_error<T>(function, 0, pol);\r\n     power_terms -= log(fabs(s)) * (n + 1);\r\n     power_terms += boost::math::lgamma(T(n));\r\n     power_terms += log(fabs(sum));\r\n\r\n     if(power_terms > boost::math::tools::log_max_value<T>())\r\n        return sum * boost::math::policies::raise_overflow_error<T>(function, 0, pol);\r\n\r\n     return exp(power_terms) * ((s < 0) && ((n + 1) & 1) ? -1 : 1) * boost::math::sign(sum);\r\n  }\r\n\r\n  template <class T, class Policy>\r\n  struct polygamma_initializer\r\n  {\r\n     struct init\r\n     {\r\n        init()\r\n        {\r\n           // Forces initialization of our table of coefficients and mutex:\r\n           boost::math::polygamma(30, T(-2.5f), Policy());\r\n        }\r\n        void force_instantiate()const{}\r\n     };\r\n     static const init initializer;\r\n     static void force_instantiate()\r\n     {\r\n        initializer.force_instantiate();\r\n     }\r\n  };\r\n\r\n  template <class T, class Policy>\r\n  const typename polygamma_initializer<T, Policy>::init polygamma_initializer<T, Policy>::initializer;\r\n  \r\n  template<class T, class Policy>\r\n  inline T polygamma_imp(const int n, T x, const Policy &pol)\r\n  {\r\n    BOOST_MATH_STD_USING\r\n    static const char* function = \"boost::math::polygamma<%1%>(int, %1%)\";\r\n    polygamma_initializer<T, Policy>::initializer.force_instantiate();\r\n    if(n < 0)\r\n       return policies::raise_domain_error<T>(function, \"Order must be >= 0, but got %1%\", static_cast<T>(n), pol);\r\n    if(x < 0)\r\n    {\r\n       if(floor(x) == x)\r\n       {\r\n          //\r\n          // Result is infinity if x is odd, and a pole error if x is even.\r\n          //\r\n          if(lltrunc(x) & 1)\r\n             return policies::raise_overflow_error<T>(function, 0, pol);\r\n          else\r\n             return policies::raise_pole_error<T>(function, \"Evaluation at negative integer %1%\", x, pol);\r\n       }\r\n       T z = 1 - x;\r\n       T result = polygamma_imp(n, z, pol) + constants::pi<T, Policy>() * poly_cot_pi(n, z, x, pol, function);\r\n       return n & 1 ? T(-result) : result;\r\n    }\r\n    //\r\n    // Limit for use of small-x-series is chosen\r\n    // so that the series doesn't go too divergent\r\n    // in the first few terms.  Ordinarily this\r\n    // would mean setting the limit to ~ 1 / n,\r\n    // but we can tolerate a small amount of divergence:\r\n    //\r\n    T small_x_limit = (std::min)(T(T(5) / n), T(0.25f));\r\n    if(x < small_x_limit)\r\n    {\r\n      return polygamma_nearzero(n, x, pol, function);\r\n    }\r\n    else if(x > 0.4F * policies::digits_base10<T, Policy>() + 4.0f * n)\r\n    {\r\n      return polygamma_atinfinityplus(n, x, pol, function);\r\n    }\r\n    else if(x == 1)\r\n    {\r\n       return (n & 1 ? 1 : -1) * boost::math::factorial<T>(n, pol) * boost::math::zeta(T(n + 1), pol);\r\n    }\r\n    else if(x == 0.5f)\r\n    {\r\n       T result = (n & 1 ? 1 : -1) * boost::math::factorial<T>(n, pol) * boost::math::zeta(T(n + 1), pol);\r\n       if(fabs(result) >= ldexp(tools::max_value<T>(), -n - 1))\r\n          return boost::math::sign(result) * policies::raise_overflow_error<T>(function, 0, pol);\r\n       result *= ldexp(T(1), n + 1) - 1;\r\n       return result;\r\n    }\r\n    else\r\n    {\r\n      return polygamma_attransitionplus(n, x, pol, function);\r\n    }\r\n  }\r\n\r\n} } } // namespace boost::math::detail\r\n\r\n#ifdef _MSC_VER\r\n#pragma warning(pop)\r\n#endif\r\n\r\n#endif // _BOOST_POLYGAMMA_DETAIL_2013_07_30_HPP_\r\n\r\n", "meta": {"hexsha": "b11a2546f805f77fd48d859d92b7e3efacd2e44b", "size": 23151, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ios/Pods/boost-for-react-native/boost/math/special_functions/detail/polygamma.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/special_functions/detail/polygamma.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/special_functions/detail/polygamma.hpp", "max_forks_repo_name": "rudylee/expo", "max_forks_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_forks_repo_licenses": ["Apache-2.0", "MIT"], "max_forks_count": 1329.0, "max_forks_repo_forks_event_min_datetime": "2015-11-03T20:25:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T18:10:38.000Z", "avg_line_length": 41.4150268336, "max_line_length": 221, "alphanum_fraction": 0.5789814695, "num_tokens": 6665, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4532096260122723}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n    Copyright (c) 2020, Klaus Spanderen\n    All rights reserved.\n\n    Redistribution and use in source and binary forms, with or without\n    modification, are permitted provided that the following conditions are met:\n\n    1. Redistributions of source code must retain the above copyright notice, this\n    list of conditions and the following disclaimer.\n\n    2. Redistributions in binary form must reproduce the above copyright notice,\n    this list of conditions and the following disclaimer in the documentation\n    and/or other materials provided with the distribution.\n    \n    3. Neither the names of the copyright holders nor the names of the QuantLib   \n    Group and 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 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/*! \\file mphestonengine.hpp\n    \\brief multi precision Heston vanilla engine\n*/\n\n#ifndef quantlib_mp_heston_vanilla_engine_hpp\n#define quantlib_mp_heston_vanilla_engine_hpp\n\n#include <ql/pricingengines/genericmodelengine.hpp>\n#include <ql/models/equity/hestonmodel.hpp>\n#include <ql/instruments/vanillaoption.hpp>\n\n#include <boost/multiprecision/cpp_dec_float.hpp>\n\nnamespace QuantLib {\n\n    class MPHestonVanillaEngine\n        : public GenericModelEngine<HestonModel,\n                                    VanillaOption::arguments,\n                                    VanillaOption::results> {\n      public:\n        typedef boost::multiprecision::number<\n            boost::multiprecision::cpp_dec_float<150> > MP_Real;\n\n        MPHestonVanillaEngine(const ext::shared_ptr<HestonModel>& model,Size n);\n\n        void calculate() const;\n\n      private:\n        const Size n_;\n        const ext::shared_ptr<HestonModel> model_;\n\n        std::vector<MP_Real> x_, w_;\n    };\n}\n\n#endif\n", "meta": {"hexsha": "9429cf9be056ac4c519737c90d13b6e4fa779061", "size": 2675, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/pricingengines/vanilla/mphestonvanillaengine.hpp", "max_stars_repo_name": "klausspanderen/HestonExponentialFitting", "max_stars_repo_head_hexsha": "a06e596340820b181699eb105c90b854246c26b8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ql/pricingengines/vanilla/mphestonvanillaengine.hpp", "max_issues_repo_name": "klausspanderen/HestonExponentialFitting", "max_issues_repo_head_hexsha": "a06e596340820b181699eb105c90b854246c26b8", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/pricingengines/vanilla/mphestonvanillaengine.hpp", "max_forks_repo_name": "klausspanderen/HestonExponentialFitting", "max_forks_repo_head_hexsha": "a06e596340820b181699eb105c90b854246c26b8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-28T10:57:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T10:57:06.000Z", "avg_line_length": 38.768115942, "max_line_length": 82, "alphanum_fraction": 0.7244859813, "num_tokens": 569, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079209, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.45320651955353525}}
{"text": "/**\n * @file dense_chained_multiplication.cpp\n * @brief Benchmarks the chained multiplication of 6 random square matrices of increasing size\n *\n * @author Matthew Powelson\n * @date April 1, 2020\n * @version TODO\n * @bug No known bugs\n *\n * @copyright Copyright (c) 2020, Southwest Research Institute\n *\n * @par License\n * Software License Agreement (Apache License)\n * @par\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * @par\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#include <benchmark/benchmark.h>\n\n#include <arrayfire.h>\n#include <Eigen/Eigen>\n#include <torch/torch.h>\n\nauto BM_PYTORCH_CM = [](benchmark::State& state, int size, torch::Device device) {\n  torch::TensorOptions options =\n      torch::TensorOptions().dtype(torch::kFloat64).layout(torch::kStrided).device(device).requires_grad(true);\n\n  torch::manual_seed(0);\n  torch::Tensor tensor0 = torch::rand({ size, size }, options);\n  torch::manual_seed(1);\n  torch::Tensor tensor1 = torch::rand({ size, size }, options);\n  torch::manual_seed(2);\n  torch::Tensor tensor2 = torch::rand({ size, size }, options);\n  torch::manual_seed(3);\n  torch::Tensor tensor3 = torch::rand({ size, size }, options);\n  torch::manual_seed(4);\n  torch::Tensor tensor4 = torch::rand({ size, size }, options);\n  torch::manual_seed(5);\n  torch::Tensor tensor5 = torch::rand({ size, size }, options);\n\n  torch::Tensor result = torch::rand({ size, size }, options);\n\n  for (auto _ : state)\n  {\n    benchmark::DoNotOptimize(\n        result = torch::mm(torch::mm(torch::mm(torch::mm(torch::mm(tensor0, tensor1), tensor2), tensor3), tensor4),\n                           tensor5));\n  }\n};\n\nauto BM_EIGEN_CM = [](benchmark::State& state, int size) {\n  srand(0);\n  Eigen::MatrixXd matrix1 = Eigen::MatrixXd::Random(size, size);\n  srand(1);\n  Eigen::MatrixXd matrix2 = Eigen::MatrixXd::Random(size, size);\n  srand(2);\n  Eigen::MatrixXd matrix3 = Eigen::MatrixXd::Random(size, size);\n  srand(3);\n  Eigen::MatrixXd matrix4 = Eigen::MatrixXd::Random(size, size);\n  srand(4);\n  Eigen::MatrixXd matrix5 = Eigen::MatrixXd::Random(size, size);\n  srand(5);\n  Eigen::MatrixXd matrix6 = Eigen::MatrixXd::Random(size, size);\n\n  Eigen::MatrixXd result = Eigen::MatrixXd::Random(size, size);\n  for (auto _ : state)\n  {\n    benchmark::DoNotOptimize(result = matrix1 * matrix2 * matrix3 * matrix4 * matrix5 * matrix6);\n  }\n};\n\nauto BM_ARRAYFIRE_CM = [](benchmark::State& state, int size, auto device) {\n  af::setBackend(device);\n\n  af::setSeed(0);\n  af::array array0 = af::randu(size, size);\n  af::setSeed(1);\n  af::array array1 = af::randu(size, size);\n  af::setSeed(2);\n  af::array array2 = af::randu(size, size);\n  af::setSeed(3);\n  af::array array3 = af::randu(size, size);\n  af::setSeed(4);\n  af::array array4 = af::randu(size, size);\n  af::setSeed(5);\n  af::array array5 = af::randu(size, size);\n\n  af::array result = af::randu(size, size);\n  for (auto _ : state)\n  {\n    benchmark::DoNotOptimize(result = af::matmul(af::matmul(array0, array1, array2, array3), array4, array5));\n  }\n};\n\nint main(int argc, char** argv)\n{\n  for (auto& test_input : { 2, 3, 4, 8, 16, 32, 64, 128, 256, 512, 1028, 2056})\n  {\n    std::string name = \"BM_PYTORCH_CPU_CM_Size_\" + std::to_string(test_input);\n    benchmark::RegisterBenchmark(name.c_str(), BM_PYTORCH_CM, test_input, torch::kCPU)\n        ->UseRealTime()\n        ->Unit(benchmark::TimeUnit::kMicrosecond);\n  }\n  for (auto& test_input : { 2, 3, 4, 8, 16, 32, 64, 128, 256, 512, 1028, 2056})\n  {\n    std::string name = \"BM_PYTORCH_GPU_CM_Size_\" + std::to_string(test_input);\n    benchmark::RegisterBenchmark(name.c_str(), BM_PYTORCH_CM, test_input, torch::kCUDA)\n        ->UseRealTime()\n        ->Unit(benchmark::TimeUnit::kMicrosecond);\n  }\n  for (auto& test_input : { 2, 3, 4, 8, 16, 32, 64, 128, 256, 512, 1028, 2056})\n  {\n    std::string name = \"BM_EIGEN_CM_Size_\" + std::to_string(test_input);\n    benchmark::RegisterBenchmark(name.c_str(), BM_EIGEN_CM, test_input)\n        ->UseRealTime()\n        ->Unit(benchmark::TimeUnit::kMicrosecond);\n  }\n  for (auto& test_input : { 2, 3, 4, 8, 16, 32, 64, 128, 256, 512, 1028, 2056})\n  {\n    std::string name = \"BM_ARRAYFIRE_CPU_CM_Size_\" + std::to_string(test_input);\n    benchmark::RegisterBenchmark(name.c_str(), BM_ARRAYFIRE_CM, test_input, AF_BACKEND_CPU)\n        ->UseRealTime()\n        ->Unit(benchmark::TimeUnit::kMicrosecond);\n  }\n  for (auto& test_input : { 2, 3, 4, 8, 16, 32, 64, 128, 256, 512, 1028, 2056})\n  {\n    std::string name = \"BM_ARRAYFIRE_CUDA_CM_Size_\" + std::to_string(test_input);\n    benchmark::RegisterBenchmark(name.c_str(), BM_ARRAYFIRE_CM, test_input, AF_BACKEND_CUDA)\n        ->UseRealTime()\n        ->Unit(benchmark::TimeUnit::kMicrosecond);\n  }\n  for (auto& test_input : { 2, 3, 4, 8, 16, 32, 64, 128, 256, 512, 1028, 2056})\n  {\n    std::string name = \"BM_ARRAYFIRE_OPENCL_CM_Size_\" + std::to_string(test_input);\n    benchmark::RegisterBenchmark(name.c_str(), BM_ARRAYFIRE_CM, test_input, AF_BACKEND_OPENCL)\n        ->UseRealTime()\n        ->Unit(benchmark::TimeUnit::kMicrosecond);\n  }\n  benchmark::Initialize(&argc, argv);\n  benchmark::RunSpecifiedBenchmarks();\n}\n", "meta": {"hexsha": "a6311c12a1d3b906a596a2b3b4b04a5c97e049f8", "size": 5566, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/dense_chained_multiplication.cpp", "max_stars_repo_name": "mpowelson/matrix_math_benchmarks", "max_stars_repo_head_hexsha": "b1796c2c8e1eb1af2691129decc156f68ef3d07a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-06-16T18:25:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-17T02:08:27.000Z", "max_issues_repo_path": "src/dense_chained_multiplication.cpp", "max_issues_repo_name": "mpowelson/matrix_math_benchmarks", "max_issues_repo_head_hexsha": "b1796c2c8e1eb1af2691129decc156f68ef3d07a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/dense_chained_multiplication.cpp", "max_forks_repo_name": "mpowelson/matrix_math_benchmarks", "max_forks_repo_head_hexsha": "b1796c2c8e1eb1af2691129decc156f68ef3d07a", "max_forks_repo_licenses": ["Apache-2.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.8609271523, "max_line_length": 115, "alphanum_fraction": 0.6715774344, "num_tokens": 1669, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079209, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.45320651955353525}}
{"text": "#pragma once\n#include <Eigen/Core>\n#include <iostream>\n\nnamespace srrg2_core {\n  //! @brief ldg implements similiarity class eigen illnesses style\n  template <typename Scalar_, int Dim_>\n  class Similiarity_ {\n  public:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    static constexpr int Dim       = Dim_;\n    static constexpr int MatrixDim = Dim + 1;\n    using Index                    = Eigen::Index;\n    using Scalar                   = Scalar_;\n    using ThisType                 = Similiarity_<Scalar, Dim>;\n    using MatrixType               = Eigen::Matrix<Scalar, MatrixDim, MatrixDim>;\n    using VectorType               = Eigen::Matrix<Scalar, Dim, 1>;\n    using ConstMatrixType          = const MatrixType;\n    using LinearType               = Eigen::Matrix<Scalar, Dim, Dim>;\n    using ConstLinearType          = const LinearType;\n    using TranslationType          = Eigen::Matrix<Scalar, Dim, 1>;\n    using ConstTranslationType     = const TranslationType;\n    // ldg blocks in super fancy eigen way\n    using LinearBlock           = Eigen::Block<MatrixType, Dim, Dim>;\n    using ConstLinearBlock      = const Eigen::Block<ConstMatrixType, Dim, Dim>;\n    using TranslationBlock      = Eigen::Block<MatrixType, Dim, 1>;\n    using ConstTranslationBlock = const Eigen::Block<ConstMatrixType, Dim, 1>;\n\n    //! @brief ldg constructing similiarity to identity\n    Similiarity_() {\n      _matrix.setIdentity();\n    }\n\n    //! @brief ldg copy construction, allows direct initialization\n    Similiarity_(const Similiarity_& other) {\n      _matrix.setIdentity();\n      this->linear()         = other.linear();\n      this->translation()    = other.translation();\n      this->inverseScaling() = other.inverseScaling();\n    }\n\n    static ThisType Identity() {\n      return ThisType();\n    }\n\n    //! @brief ldg accessor matrix type\n    ConstMatrixType& matrix() const {\n      return _matrix;\n    }\n\n    // ! @brief ldg setter matrix type, eigen style\n    MatrixType& matrix() {\n      return _matrix;\n    }\n\n    //! @brief ldg accessor to rotational part\n    ConstLinearBlock linear() const {\n      return ConstLinearBlock(_matrix, 0, 0);\n    }\n\n    //! @brief ldg setter to rotational part\n    LinearBlock linear() {\n      return LinearBlock(_matrix, 0, 0);\n    }\n\n    //! @brief ldg accessor to rotational part\n    ConstLinearBlock rotation() const {\n      return linear();\n    }\n\n    //! @brief ldg setter to rotational part\n    LinearBlock rotation() {\n      return linear();\n    }\n\n    //! @brief ldg accessor to translational part\n    TranslationBlock translation() {\n      return TranslationBlock(_matrix, 0, Dim);\n    }\n\n    //! @brief ldg setter to translational part\n    ConstTranslationBlock translation() const {\n      return ConstTranslationBlock(_matrix, 0, Dim);\n    }\n\n    //! @brief ldg accessor to inverse scaling value, scalar\n    const Scalar& inverseScaling() const {\n      return _matrix.coeffRef(Dim, Dim);\n    }\n\n    //! @brief ldg setter to inverse scaling value, scalar\n    Scalar& inverseScaling() {\n      return _matrix.coeffRef(Dim, Dim);\n    }\n\n    //! @brief ldg set matrix to indentity\n    void setIdentity() {\n      _matrix.setIdentity();\n    }\n\n    //! @brief ldg returns a inverse of a similiarity\n    ThisType inverse() const {\n      ThisType inverse_sim;\n      inverse_sim.setIdentity();\n      inverse_sim.linear() = this->linear().transpose();\n      inverse_sim.translation() =\n        -Scalar(1) / this->inverseScaling() * (inverse_sim.linear() * this->translation());\n      inverse_sim.inverseScaling() = Scalar(1) / this->inverseScaling();\n      return inverse_sim;\n    }\n\n    //! @brief ldg multiply operator between similiarities\n    ThisType operator*(const ThisType& other) const {\n      ThisType result;\n      result.setIdentity();\n      ConstLinearType& R      = other.linear();\n      ConstTranslationType& t = other.translation();\n      const Scalar& is        = other.inverseScaling();\n      result.linear()         = this->linear() * R;\n      result.translation()    = this->linear() * t + is * this->translation();\n      result.inverseScaling() = is * this->inverseScaling();\n      return result;\n    }\n\n    //! @brief ldg multiply operator similiarity * vector\n    VectorType operator*(const VectorType& other) const {\n      VectorType result;\n      result = Scalar(1) / this->inverseScaling() * (this->linear() * other + this->translation());\n      return result;\n    }\n\n    //! @brief ldg equal operator, copy similiarities\n    ThisType& operator=(const ThisType& other) {\n      this->linear()         = other.linear();\n      this->translation()    = other.translation();\n      this->inverseScaling() = other.inverseScaling();\n      return *this;\n    }\n\n    //! @brief ldg multiply operator between similiarities, write result on current sim\n    ThisType& operator*=(const ThisType& other) {\n      *this = *this * other;\n      return *this;\n    }\n\n    Scalar& operator()(Index row, Index col) {\n      return _matrix(row, col);\n    }\n\n    Scalar operator()(Index row, Index col) const {\n      return _matrix(row, col);\n    }\n\n    Index rows() const {\n      return _matrix.rows();\n    }\n\n    Index cols() const {\n      return _matrix.cols();\n    }\n\n  protected:\n    MatrixType _matrix;\n  };\n\n} // namespace srrg2_core\n", "meta": {"hexsha": "2ef3471720f577033639ee860107e758b1d12d66", "size": 5264, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "catkin_ws/src/srrg2_core/srrg2_core/src/srrg_geometry/similiarity.hpp", "max_stars_repo_name": "laaners/progetto-labiagi_pick_e_delivery", "max_stars_repo_head_hexsha": "3453bfbc1dd7562c78ba06c0f79b069b0a952c0e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-03-11T14:36:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-09T09:01:15.000Z", "max_issues_repo_path": "catkin_ws/src/srrg2_core/srrg2_core/src/srrg_geometry/similiarity.hpp", "max_issues_repo_name": "laaners/progetto-labiagi_pick_e_delivery", "max_issues_repo_head_hexsha": "3453bfbc1dd7562c78ba06c0f79b069b0a952c0e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-06-07T17:25:04.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-15T07:36:10.000Z", "max_forks_repo_path": "catkin_ws/src/srrg2_core/srrg2_core/src/srrg_geometry/similiarity.hpp", "max_forks_repo_name": "laaners/progetto-labiagi_pick_e_delivery", "max_forks_repo_head_hexsha": "3453bfbc1dd7562c78ba06c0f79b069b0a952c0e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-11-30T08:17:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-19T05:07:07.000Z", "avg_line_length": 31.5209580838, "max_line_length": 99, "alphanum_fraction": 0.6270896657, "num_tokens": 1226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4532065141695859}}
{"text": "#include <string>\n#include <cstdlib>\n#include <iostream>\n#include <cmath>\n#include <cassert>\n#include <vector>\n#include <map>\n#include <algorithm>\n\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_01.hpp>\n\n#include <rstbx/indexing_api/indexing_api.h>\n#include <rstbx/dps_core/direction.h>\n#include <cctbx/math/mod.h>\n\nnamespace af = scitbx::af;\nnamespace constants = scitbx::constants;\nusing rstbx::Direction;\nusing rstbx::Directional_FFT;\nusing rstbx::kvalcmp;\n\naf::shared<int>\nrstbx::indexing_api::cpp_absence_test(af::shared<cctbx::miller::index<> > hkl,\n                     const int& mod, cctbx::miller::index<> vecrep){\n  af::shared<int> cum;\n  for (std::size_t i=0; i<mod; ++i) {cum.push_back(0);}\n\n  typedef af::shared<cctbx::miller::index<> >::const_iterator For;\n  For b = hkl.begin();\n  For e = hkl.end();\n  for (;b!=e;++b){\n    int pattern_sum = (*b)[0]*vecrep[0] + (*b)[1]*vecrep[1] + (*b)[2]*vecrep[2];\n    cum[cctbx::math::mod_positive(pattern_sum, mod)]+=1;\n  }\n\n  return cum;\n}\n\nrstbx::indexing_api::dps_extended::dps_extended():rstbx::dps_core(){}\n\nvoid\nrstbx::indexing_api::dps_extended::setData(const pointlist& raw){\n  rawdata=pointlistmm();\n  rawdata.reserve(raw.size());\n  for (std::size_t i = 0; i< raw.size(); ++i) {\n      rawdata.push_back(raw[i]);\n  }\n}\n\nrstbx::Direction\nrstbx::indexing_api::dps_extended::refine_direction(const rstbx::Direction& candidate,\n                               const double& current_grid,\n                               const double& target_grid) const {\n  double incr = current_grid/4.0; //recursively smaller grid with neighbor overlap\n  if (incr < target_grid) { return candidate; }\n  rstbx::Direction direction0(candidate.dvec);\n  rstbx::Direction direction1(candidate.psi + incr, candidate.phi);\n  scitbx::vec3<double> rotaxisi = direction0.dvec.cross(direction1.dvec).normalize();\n  scitbx::vec3<double> rotaxisj = rotaxisi.cross(direction1.dvec).normalize();\n\n  rstbx::Direction best_refined = candidate;\n  for (int i = -2; i < 3; ++i) {\n    scitbx::vec3<double> rotate1 = direction0.dvec.unit_rotate_around_origin(rotaxisi,-i*incr);\n    for (int j = -2; j < 3; ++j) {\n      scitbx::vec3<double> rotate2 = rotate1.unit_rotate_around_origin(rotaxisj,-j*incr);\n      SCITBX_ASSERT(std::abs(1.0 - rotate2.length())<0.00001); //rotate2 is unit vector\n      rstbx::Direction new_candidate(rotate2);\n      rstbx::fftptr dfft( fft_factory(new_candidate) );\n\n      if ( dfft->kval() > best_refined.kval ) {\n        new_candidate.extract_directional_properties(dfft);\n        best_refined=new_candidate;\n      }\n    }\n  }\n  return refine_direction(best_refined,incr,target_grid);\n}\n\ndouble\nrstbx::indexing_api::dps_extended::high()const{\n  //Go through all film coordinates and get high resolution limit\n  // This is NOT a safe function if rawdata.size()==0 due to\n  // dereferencing s.end().  This bug causes a painful infinite loop\n  // in some runtime environments.  See the protecting test in classify_spots().\n  // The real fix will be to split this\n  // class into components, with the high() function being a member\n  // of the class containing rawdata.\n\n  SCITBX_ASSERT (xyzdata.size() > 0);\n  af::shared<double> s(xyzdata.size());\n  for (std::size_t i = 0; i<xyzdata.size(); ++i) {\n    s[i] =         1./xyzdata[i].length();\n  }\n  double dmax = *(std::max_element<af::shared<double>::const_iterator>(s.begin(),s.end()));\n  //dmax is maximum squared distance (mm^2) from the beam center\n  return dmax;\n}\n\naf::shared< scitbx::vec3<double> >\nrstbx::indexing_api::raw_spot_positions_mm_to_reciprocal_space_xyz(\n  pointlist raw_spot_input,\n  dxtbx::model::Detector const& detector, double const& inverse_wave,\n  scitbx::vec3<double> const& S0_vector, scitbx::vec3<double> const& axis, af::shared<int> panelID\n){\n\n  // it is not clear how we will plug in to this function if and when\n  // we need to use a derived detector class with a different implemented\n  // behavior of get_lab_coord().\n\n  af::shared< scitbx::vec3<double> > reciprocal_space_vectors;\n  // with a single panel only, all the convenience functions work for us\n  for (int n = 0; n != raw_spot_input.size(); ++n) {\n    int pid = panelID[n];\n\n    // tile surface to laboratory transformation\n    scitbx::vec2<double> raw_spot(raw_spot_input[n][0],raw_spot_input[n][1]);\n    scitbx::vec3<double> lab_direct = detector[pid].get_lab_coord(raw_spot);\n\n    // laboratory direct to reciprocal space xyz transformation\n    scitbx::vec3<double> lab_recip = (lab_direct.normalize() * inverse_wave) - S0_vector;\n\n      // raw_spot_input[n][2] MUST be given in degrees.\n    reciprocal_space_vectors.push_back( lab_recip.rotate_around_origin(\n      axis, -raw_spot_input[n][2] * scitbx::constants::pi_180) );\n  }\n  return reciprocal_space_vectors;\n\n}\n\naf::shared< scitbx::vec3<double> >\nrstbx::indexing_api::raw_spot_positions_mm_to_reciprocal_space_xyz(\n  pointlist raw_spot_input,\n  dxtbx::model::Detector const& detector, double const& inverse_wave,\n  scitbx::vec3<double> const& S0_vector, af::shared<int> panelID\n){\n\n  // it is not clear how we will plug in to this function if and when\n  // we need to use a derived detector class with a different implemented\n  // behavior of get_lab_coord().\n\n  af::shared< scitbx::vec3<double> > reciprocal_space_vectors;\n  // with a single panel only, all the convenience functions work for us\n  for (int n = 0; n != raw_spot_input.size(); ++n) {\n    int pid = panelID[n];\n\n    // tile surface to laboratory transformation\n    scitbx::vec2<double> raw_spot(raw_spot_input[n][0],raw_spot_input[n][1]);\n    scitbx::vec3<double> lab_direct = detector[pid].get_lab_coord(raw_spot);\n\n    // laboratory direct to reciprocal space xyz transformation\n    scitbx::vec3<double> lab_recip = (lab_direct.normalize() * inverse_wave) - S0_vector;\n\n      // raw_spot_input[n][2] MUST be given in degrees.\n    reciprocal_space_vectors.push_back(lab_recip);\n  }\n  return reciprocal_space_vectors;\n\n}\n", "meta": {"hexsha": "730f22e84c0896b1d8df7c5e6aaf3e7628543d55", "size": 5965, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rstbx/indexing_api/indexing_api.cpp", "max_stars_repo_name": "rimmartin/cctbx_project", "max_stars_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 155.0, "max_stars_repo_stars_event_min_datetime": "2016-11-23T12:52:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:35:44.000Z", "max_issues_repo_path": "rstbx/indexing_api/indexing_api.cpp", "max_issues_repo_name": "rimmartin/cctbx_project", "max_issues_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": 590.0, "max_issues_repo_issues_event_min_datetime": "2016-12-10T11:31:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T23:10:09.000Z", "max_forks_repo_path": "rstbx/indexing_api/indexing_api.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": 37.28125, "max_line_length": 98, "alphanum_fraction": 0.701424979, "num_tokens": 1663, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4532065141695859}}
{"text": "#include <stdint.h>\n#include <iostream>\n#include <math.h>\n#include <tgmath.h>\n#include <string.h>\n#include <fstream>\n#include <stdlib.h>\nusing namespace std;\n\n#ifndef M_PI\n#define M_PI 3.14159265358979323846\n#endif\n\n#ifndef M_PI_2\n#define M_PI_2 1.57079632679489661923\n#endif\n\n#define STB_IMAGE_IMPLEMENTATION\n#include \"stb_image.h\"\n#define STB_IMAGE_WRITE_IMPLEMENTATION\n#include \"stb_image_write.h\"\n\n//Un des deux ou aucun des deux\n#define DRAWSTARS 1 //Si 1 etoiles sur le fond celeste, sinon rien\n#define DRAWGRID 0  //Si 1 grille sur le fond celeste\n\n//Un des deux ou aucun des deux\n#define ADISK_NORMAL 1 //Si 1, texture + temperature, sinon rien\n#define ADISK_GRID 0   //Si 1, grille, sinon rien\n\n#include \"fct.h\"\n#include \"raytracing.h\"\n#include \"par_for.h\"\n\n#define CHANNEL_NUM 3\n\n#define MAXITER 500000\n\nstatic const int Neq = 6; //Nombre de variables pour l'integration numerique\n\nstruct Rendu rdr;\nstruct Scene scn;\nstruct Blackhole bh;\nstruct Disk disk;\n\nint adisk_width, adisk_height, adisk_bpp;\nuint8_t *adisk = stbi_load(\"adisk_upscaled.png\", &adisk_width, &adisk_height, &adisk_bpp, 3);\n\nstatic const int SpectrumSampleSize = 76; //nombre d'\u00e9chantillons\nfloat deltaWaveLength = 4.;               //(En nm, espacement des \u00e9chantillons)\nfloat wavelengthSamples[SpectrumSampleSize], wavelengthSamples5[SpectrumSampleSize], sensitivitySamplesR[SpectrumSampleSize], sensitivitySamplesG[SpectrumSampleSize], sensitivitySamplesB[SpectrumSampleSize];\n\nvoid readSensitivityData(const char *filename, float *wavelengthSamples, float *wavelengthSamples5, float *sensitivitySamplesR, float *sensitivitySamplesG, float *sensitivitySamplesB)\n{\n    int cnt = 0;\n    ifstream source;       // build a read-Stream\n    source.open(filename); // open data\n\n    for (std::string line; std::getline(source, line);) //read stream line by line\n    {\n        std::istringstream in(line); //make a stream for the line itself\n\n        in >> wavelengthSamples[cnt] >> sensitivitySamplesR[cnt] >> sensitivitySamplesG[cnt] >> sensitivitySamplesB[cnt]; //now read the whitespace-separated floats\n\n        wavelengthSamples5[cnt] = pow(wavelengthSamples[cnt], 5);\n        cnt++;\n    }\n}\n\nvoid getBodyColor(float *rgbR, float *rgbG, float *rgbB, float temperature, float brightness)\n{\n    float I;\n\n    for (int l = 0; l < SpectrumSampleSize; ++l)\n    {\n\n        I = (6.e14 / wavelengthSamples5[l]) / exp(1.43913e7 / (wavelengthSamples[l] * temperature) - 1.) * brightness; //6e14 pour renormaliser les composante des pixels\n\n        I *= deltaWaveLength;\n        *rgbR += sensitivitySamplesR[l] * I;\n        *rgbG += sensitivitySamplesG[l] * I;\n        *rgbB += sensitivitySamplesB[l] * I;\n    }\n}\n\n//Affiche une grille sur le disque\nvoid getDiskColorGrid(float phi, float r, float *rgbR, float *rgbG, float *rgbB)\n{\n    phi = (phi + M_PI) / (2. * M_PI);\n\n    bool a = int((100 * phi)) % 2; //100 alternances de couleur par tour\n\n    bool b = ((r - disk.R_min) / (disk.R_max - disk.R_min) > .5); //S\u00e9parer le disque en 2 radialement\n\n    if (a ^ b) //Ou exclusif\n    {\n        *rgbR = 255.;\n        *rgbG = 0.;\n    }\n    else\n    {\n        *rgbR = 0.;\n        *rgbG = 255.;\n    }\n}\n\n//Passage aux coordonnees de Boyer Lindquist\n//Pour l'instant juste passage au coordonn\u00e9es sph\u00e9riques (plus simple)\n//Utilis\u00e9 uniquement pour trouver la pos initiale de la camera, pas important\nvoid cartesianToBl(float x, float y, float z, float *r, float *theta, float *phi)\n{\n\n    float r2 = x * x + y * y + z * z;\n    *r = sqrt(r2);\n\n    *phi = atan2(y, x);\n    *theta = acos(z / (*r));\n}\n\n//Passage des coordonn\u00e9es de Boyer Lindquist au coordonn\u00e9es cart\u00e9sienne (exacte)\nvoid blToCartesian(float r, float theta, float phi, float *x, float *y, float *z)\n{\n\n    float sintheta = sin(theta);\n    float costheta = cos(theta);\n    float cosphi = cos(phi);\n    float sinphi = sin(phi);\n    float temp = sintheta * sqrt(r * r + bh.a2);\n\n    *x = temp * cosphi;\n    *y = temp * sinphi;\n    *z = r * costheta;\n}\n\n/* Fonction utilis\u00e9 pour l'int\u00e9gration */\nvoid geodesic(float L, float kappa, float *y, float *dydx)\n{\n    float r, theta, pr, ptheta;\n\n    r = y[0];\n    theta = y[1];\n    pr = y[4];\n    ptheta = y[5];\n\n    float r2 = r * r;\n    float twor = 2.0 * r;\n\n    float sintheta, costheta;\n    sintheta = sin(theta);\n    costheta = cos(theta);\n\n    float costheta2 = costheta * costheta;\n    float sintheta2 = sintheta * sintheta;\n\n    float sigma = r2 + bh.a2 * costheta2;\n    float delta = r2 - twor + bh.a2;\n    float sd = sigma * delta;\n    float siginv = 1.0 / sigma;\n    float bot = 1.0 / sd;\n\n    /* Prevent problems with the axis */\n    if (sintheta < 1e-8)\n    {\n        sintheta = 1e-8;\n        sintheta2 = 1e-16;\n    }\n\n    dydx[0] = -pr * delta * siginv;\n    dydx[1] = -ptheta * siginv;\n    dydx[2] = -(twor * bh.a + (sigma - twor) * L / sintheta2) * bot;\n    dydx[3] = -(1.0 + (twor * (r2 + bh.a2) - twor * bh.a * L) * bot);\n    dydx[4] = -(((r - 1.0) * (-kappa) + twor * (r2 + bh.a2) - 2.0 * bh.a * L) * bot - 2.0 * pr * pr * (r - 1.0) * siginv);\n    dydx[5] = -sintheta * costheta * (L * L / (sintheta2 * sintheta2) - bh.a2) * siginv;\n}\n\n/* Conditions initiales pour un rayon */\nvoid initial(float r0, float theta0, float *L, float *kappa, float *y0, float *ydot0, float x, float y)\n{\n    y0[0] = r0;\n    y0[1] = theta0;\n    y0[2] = 0;\n    y0[3] = 0;\n    y0[4] = cos(y) * cos(x);\n    y0[5] = sin(y) / r0;\n\n    float sintheta, costheta;\n    sintheta = sin(theta0);\n    costheta = cos(theta0);\n    float costheta2 = costheta * costheta;\n    float sintheta2 = sintheta * sintheta;\n\n    float rdot0 = y0[4];\n    float thetadot0 = y0[5];\n\n    float r2 = r0 * r0;\n    float sigma = r2 + bh.a2 * costheta2;\n    float delta = r2 - 2.0 * r0 + bh.a2;\n    float s1 = sigma - 2.0 * r0;\n\n    y0[4] = rdot0 * sigma / delta;\n    y0[5] = thetadot0 * sigma;\n\n    ydot0[0] = rdot0;\n    ydot0[1] = thetadot0;\n    ydot0[2] = cos(y) * sin(x) / (r0 * sin(theta0));\n\n    float phidot0 = ydot0[2];\n    float energy2 = s1 * (rdot0 * rdot0 / delta + thetadot0 * thetadot0) + delta * sintheta2 * phidot0 * phidot0;\n\n    float energy = sqrt(energy2);\n\n    /* Energie de 1 */\n    y0[4] = y0[4] / energy;\n    y0[5] = y0[5] / energy;\n\n    /* Angular Momentum with E = 1 */\n    *L = ((sigma * delta * phidot0 - 2.0 * bh.a * r0 * energy) * sintheta2 / s1) / energy;\n\n    *kappa = y0[5] * y0[5] + bh.a2 * sintheta2 + (*L) * (*L) / sintheta2;\n\n    /* Hack - make sure everything is normalized correctly by a call to geodesic */\n\n    geodesic(*L, *kappa, y0, ydot0);\n}\n\n//Obtenir la direction du rayon \u00e0 partir des coord de BL (y) et de leurs d\u00e9riv\u00e9es (dydx)\n//Retourne un vecteur norm\u00e9\nvoid getDirection(float *y, float *dydx, float *xp, float *yp, float *zp)\n{\n\n    float costheta = cos(y[1]);\n    float sintheta = sin(y[1]);\n    float cosphi = cos(y[2]);\n    float sinphi = sin(y[2]);\n    float r2 = y[0] * y[0];\n    float R2 = r2 + bh.a2;\n    float R = sqrt(r2 + bh.a2);\n\n    *xp = R * dydx[1] * cosphi * costheta - R * dydx[2] * sinphi * sintheta + sintheta * cosphi * y[0] * dydx[0] / R;\n    *yp = R * dydx[1] * sinphi * costheta + R * dydx[2] * cosphi * sintheta + sintheta * sinphi * y[0] * dydx[0] / R;\n    *zp = -y[0] * sintheta * dydx[1] + dydx[0] * costheta;\n    normalise(xp, yp, zp);\n}\n\n//Simulation complete d'un rayon (trajectoire+collision)\nvoid sim(float r0, float theta0, float phi0, float xpixel, float ypixel, float *xp, float *yp, float *zp, float *pixel_transpr, float *pixel_transpg, float *pixel_transpb, float *canalAlpha, bool *ReachedInfinity, int *nbCollision)\n{\n    int N = 0; //Nombre d'it\u00e9rations\n    int k = 0; //nombre de collision\n\n    float oldtheta; //pour detecter le passage \u00e0 travers le plan z=0 (pour tracer le disque)\n\n    bool zSignChange, diskDistance, diskCollision;\n\n    //Euler\n\n    //float y[Neq];\n    //float dydx[Neq];\n\n    //RK4\n    float y[Neq];\n    float ak[Neq];\n    float dydx1[Neq], dydx2[Neq], dydx3[Neq], dydx4[Neq];\n    float ytemp[Neq];\n\n    float L, kappa;\n\n    initial(r0, theta0, &L, &kappa, y, ak, xpixel, ypixel);\n\n    float currentStep = rdr.step(y[0]);\n\n    int l = 0; //Juste pour effectuer des boucles sans redeclarer de var\n\n    while ((N < MAXITER) && (rdr.R_min < y[0]) && (y[0] < rdr.R_inf))\n    {\n\n        N += 1;\n\n        oldtheta = y[1];\n\n        currentStep = rdr.step(y[0]);\n\n        //Euler\n        /*for (int l = 0; l < Neq; l++)\n\t    {\n\t\t    float hdydx = currentStep * dydx[l];\n\t\t    y[l] = y[l] + hdydx;\n\t    }\n\n\t    geodesic(L,kappa,y, dydx);*/\n\n        //RK4\n        geodesic(L, kappa, y, ak);\n        for (l = 0; l < Neq; ++l)\n        {\n            dydx1[l] = ak[l];\n            ytemp[l] = y[l] + .5 * currentStep * ak[l];\n        }\n        geodesic(L, kappa, ytemp, ak);\n        for (l = 0; l < Neq; ++l)\n        {\n            dydx2[l] = ak[l];\n            ytemp[l] = y[l] + .5 * currentStep * ak[l];\n        }\n        geodesic(L, kappa, ytemp, ak);\n        for (l = 0; l < Neq; ++l)\n        {\n            dydx3[l] = ak[l];\n            ytemp[l] = y[l] + currentStep * ak[l];\n        }\n        geodesic(L, kappa, ytemp, ak);\n        for (l = 0; l < Neq; ++l)\n        {\n            dydx4[l] = ak[l];\n            dydx1[l] = currentStep / 6. * (dydx1[l] + 2. * dydx2[l] + 2. * dydx3[l] + dydx4[l]); //Recuperer une bonne approx de la deriv\u00e9e dans dydx1\n            y[l] = y[l] + dydx1[l];\n        }\n\n        zSignChange = (oldtheta > M_PI_2) != (y[1] > M_PI_2);      //on traverse le plan z=0\n        diskDistance = (y[0] < disk.R_max) && (y[0] > disk.R_min); //On l'a travers\u00e9 la ou est le disque\n        diskCollision = zSignChange && diskDistance;\n\n        if (diskCollision)\n        {\n            float xpos, ypos, zpos;\n            blToCartesian(y[0], y[1], y[2], &xpos, &ypos, &zpos); //Obtenir la position en coord cartesiennes\n            getDirection(y, dydx1, xp, yp, zp);                   //Obtenir la direction (en coord cartesiennes)\n\n            //Trouver le point de colision (en allant tout droit entre les deux point au dessus et en dessous du disque (valable si le pas est assez petit))\n            float lambda = -zpos / (*zp);\n            float coll_x = xpos + lambda * (*xp);\n            float coll_y = ypos + lambda * (*yp);\n            float coll_z = zpos + lambda * (*zp);\n            float r = norm(coll_x, coll_y, coll_z);\n\n            diskCollision = (r < disk.R_max) && (r > disk.R_min); //#reverification plus pr\u00e9cise\n            if (diskCollision)\n            {\n                if (k < rdr.maxtransparency)\n                {\n\n                    float phi = atan2(coll_y / r, coll_x / r); //Coordonn\u00e9 du point d'impact (en sph\u00e9rique)\n\n#if ADISK_NORMAL == 1\n\n                    float diskspeed_x, diskspeed_y, diskspeed_z;\n\n                    //rotation prograde du disque\n\n                    sphericalToCartesian(M_PI / 2., phi + M_PI / 2., &diskspeed_x, &diskspeed_y, &diskspeed_z); //Direction de la vitesse en ce point, sens trigo,mvt circulaire\n\n                    float beta = disk.RotationSpeed(r);                                                         //Obtenir la norme de la vitesse des poussi\u00e8res en ce point\n                    float costhetadoppler = -((*xp) * diskspeed_x + (*yp) * diskspeed_y + (*zp) * diskspeed_z); //Obtenir le cosinus de l'angle entre le rayon et la vitesse des particules (Les vecteurs sont norm\u00e9s)\n                    //- \u00e0 cause du sens des rayons\n\n                    //Temperature du disque \u00e0 cet endroit\n                    float Temp = disk.Temp(r);\n\n                    //D\u00e9calage en fr\u00e9quence \u00e9gal \u00e0 d\u00e9calage en temperature, valable aussi pour l'intensit\u00e9\n\n                    Temp = Temp * (1 + beta * costhetadoppler) / sqrt(1 - beta * beta); //Effet doppler relativiste\n\n                    //calcul du redshift gravitationnel\n                    float gtt = 1. - 1. / r;\n                    float gtphi = bh.a / r;\n                    float gphiphi = -(r * r + bh.a2 + bh.a2 / r);\n                    float omega = beta / r;                                                //Vitesse angulaire\n                    Temp = Temp * sqrt(gtt + 2 * gtphi * omega + gphiphi * omega * omega); //Redshift gravitationnel\n\n                    //Recuperer la texture du disque \u00e0 cet endroit, qu'on utilise uniquemenet pour obtenir la transparence du disque\n                    int cx = int((r - disk.R_min) * (adisk_height - 1) / (disk.R_max - disk.R_min));\n                    int cy = int((adisk_width - 1) * mod(disk.texture_rep * phi - M_PI, 2. * M_PI) / (2. * M_PI));\n\n                    int loc = (cx * adisk_width + cy) * CHANNEL_NUM;\n\n                    pixel_transpr[k] = 0.;\n                    pixel_transpg[k] = 0.;\n                    pixel_transpb[k] = 0.;\n\n                    getBodyColor(&pixel_transpr[k], &pixel_transpg[k], &pixel_transpb[k], Temp, 1.); //Obtenir la couleur\n\n                    canalAlpha[k] = (float)adisk[loc + 1] / 255.; //Choix: on utilise la composante verte (le +1) pour reconstituer la transparence\n\n#endif\n\n#if ADISK_GRID == 1\n\n                    getDiskColorGrid(phi, r, &pixel_transpr[k], &pixel_transpg[k], &pixel_transpb[k]); //Motif de grille sur le disque et calcul de la transparence\n                    canalAlpha[0] = 1.;\n#endif\n\n                    k++;\n                }\n            }\n        }\n    }\n\n    *ReachedInfinity = (y[0] >= rdr.R_inf);\n    *nbCollision = k;\n\n    if (*ReachedInfinity)\n    {\n        //Pour visualiser quels rayons ont atteints R_inf\n        //*nbCollision=1;\n        //pixel_transpr[0]=255;\n        //canalAlpha[0]=.5;\n\n        getDirection(y, dydx1, xp, yp, zp);\n        normalise(xp, yp, zp); //Ne pas effectuer inutilement cette op\u00e9ration\n    }\n}\n\n//Simulation d'un rayon (trajectoire uniquement)\nvoid sim_opt(float r0, float theta0, float phi0, float xpixel, float ypixel, float *xp, float *yp, float *zp, bool *ReachedInfinity)\n{\n\n    int N = 0;\n\n    //Euler\n    //float y[Neq];\n    //float dydx[Neq];\n\n    //RK4\n    float y[Neq], ak[Neq];\n    float dydx1[Neq], dydx2[Neq], dydx3[Neq], dydx4[Neq];\n    float ytemp[Neq];\n\n    float L, kappa;\n\n    initial(r0, theta0, &L, &kappa, y, ak, xpixel, ypixel); //CI\n\n    float currentStep = rdr.step(y[0]);\n\n    int l;\n\n    while ((N < MAXITER) && (rdr.R_min < y[0]) && (y[0] < rdr.R_inf))\n    {\n\n        N += 1;\n\n        currentStep = rdr.step(y[0]);\n\n        //Euler\n        /*for (int l = 0; l < Neq; l++)\n\t    {\n\t\t    float hdydx = currentStep * dydx[l];\n\t\t    y[l] = y[l] + hdydx;\n\t    }\n\t    geodesic(L,kappa,y, dydx);*/\n\n        //RK4\n\n        geodesic(L, kappa, y, ak);\n        for (l = 0; l < Neq; ++l)\n        {\n            dydx1[l] = ak[l];\n            ytemp[l] = y[l] + .5 * currentStep * ak[l];\n        }\n        geodesic(L, kappa, ytemp, ak);\n        for (l = 0; l < Neq; ++l)\n        {\n            dydx2[l] = ak[l];\n            ytemp[l] = y[l] + .5 * currentStep * ak[l];\n        }\n        geodesic(L, kappa, ytemp, ak);\n        for (l = 0; l < Neq; ++l)\n        {\n            dydx3[l] = ak[l];\n            ytemp[l] = y[l] + currentStep * ak[l];\n        }\n        geodesic(L, kappa, ytemp, ak);\n        for (l = 0; l < Neq; ++l)\n        {\n            dydx4[l] = ak[l];\n            dydx1[l] = currentStep / 6. * (dydx1[l] + 2. * dydx2[l] + 2. * dydx3[l] + dydx4[l]); //Recuperer une bonne aprrox de la deriv\u00e9e\n            y[l] = y[l] + dydx1[l];\n        }\n    }\n\n    *ReachedInfinity = (y[0] >= rdr.R_inf);\n\n    if (*ReachedInfinity)\n    { //Ne pas effectuer inutilement cette op\u00e9ration\n        getDirection(y, dydx1, xp, yp, zp);\n        normalise(xp, yp, zp);\n    }\n}\n\n//Simulation d'un faisceu de rayons (uniquement dans le cas ou on dessine des \u00e9toiles)\nvoid sim_bundle(int i, int j, float x, float y, float z, float *pixelr, float *pixelg, float *pixelb)\n{ //arguments: i et j position du pixel, x,y,z position initiale du rayon dans l'espace\n\n    float r0, theta0, phi0;\n    cartesianToBl(x, y, z, &r0, &theta0, &phi0); //Approximativement (compliqu\u00e9 de passer de cartesien \u00e0 BL), mais pas important\n\n    float xpcentre0, ypcentre0, zpcentre0;\n    float xpcentref, ypcentref, zpcentref;\n    float xp0, yp0, zp0;\n    float xpf, ypf, zpf;\n\n    bool ReachedInfinity = true;\n    int nbCollision;\n\n    float maxdist2 = 0.;\n    float maxdist2_0 = 0.;\n    //float mindist2=1000.;\n    //float mindist2_0=1000.;\n\n    /*float Distances2[4];\n    float Distances2_0[4];\n    float dilatation=1.;*/\n\n    float pixel_transpr[rdr.maxtransparency], pixel_transpg[rdr.maxtransparency], pixel_transpb[rdr.maxtransparency];\n    float canalAlpha[rdr.maxtransparency];\n\n    xpcentref = xpcentre0;\n    ypcentref = ypcentre0;\n    zpcentref = zpcentre0;\n\n    float range = 0.075 * 20. / (rdr.width - 1.0); //FOV\n    //float range = 0.1 * 20. / (rdr.width - 1.0);\n\n    float xpixel = -(i - (rdr.width + 1.0) / 2) * range;\n    float ypixel = -(j - (rdr.height + 1.0) / 2) * range;\n\n    sim(r0, theta0, phi0, xpixel, ypixel, &xpcentref, &ypcentref, &zpcentref, pixel_transpr, pixel_transpg, pixel_transpb, canalAlpha, &ReachedInfinity, &nbCollision); //Simulation du rayon principal\n\n#if DRAWSTARS == 1\n\n    int Nray = 0;\n\n    while (Nray < 4 && ReachedInfinity)\n    {\n\n        if (Nray == 0)\n        {\n            xpixel = -(i + rdr.delta - (rdr.width + 1.0) / 2) * range;\n            ypixel = -(j - (rdr.height + 1.0) / 2) * range;\n        }\n        if (Nray == 1)\n        {\n            xpixel = -(i - rdr.delta - (rdr.width + 1.0) / 2) * range;\n            ypixel = -(j - (rdr.height + 1.0) / 2) * range;\n        }\n        if (Nray == 2)\n        {\n            xpixel = -(i - (rdr.width + 1.0) / 2) * range;\n            ypixel = -(j + rdr.delta - (rdr.height + 1.0) / 2) * range;\n        }\n        if (Nray == 3)\n        {\n            xpixel = -(i - (rdr.width + 1.0) / 2) * range;\n            ypixel = -(j - rdr.delta - (rdr.height + 1.0) / 2) * range;\n        }\n\n        Nray++;\n\n        xpf = xp0;\n        ypf = yp0;\n        zpf = zp0;\n\n        sim_opt(r0, theta0, phi0, xpixel, ypixel, &xpf, &ypf, &zpf, &ReachedInfinity); //Simulation des rayons secondaires\n\n        if (ReachedInfinity)\n        {\n            //Calcule de la taille de la zone d'impact des differents rayons (zone en terme de direction)\n            //On trouve le rayon maxdist du cercle centr\u00e9 sur la direction du rayon principal, qui contient les autres rayons (tjrs en terme de direction)\n            //Calcul en coord cartesienne pour \u00e9viter les discontinuit\u00e9s li\u00e9es au modulo 2PI\n\n            //float dx0=xpcentre0-xp0;\n            //float dy0=ypcentre0-yp0;\n            //float dz0=zpcentre0-zp0;\n\n            //float dist2_0=sqrnorm(dx0,dy0,dz0);\n\n            float dx = xpcentref - xpf;\n            float dy = ypcentref - ypf;\n            float dz = zpcentref - zpf;\n\n            float dist2 = sqrnorm(dx, dy, dz);\n\n            //if (maxdist2_0<dist2_0){ maxdist2_0=dist2_0; }\n            if (maxdist2 < dist2)\n            {\n                maxdist2 = dist2;\n            }\n        }\n    }\n\n    if (ReachedInfinity)\n    { //Si tous les rayons se sont \u00e9chapp\u00e9s, on regarde quels \u00e9toiles sont dans le cercle form\u00e9 par le faisceau sur le ciel\n\n        float maxdist = sqrt(maxdist2);\n        float sqrdistanceToStar; //sqrnorm(scn.starx[i]-xpcentref,scn.stary[i]-ypcentref,scn.starz[i]-zpcentref);\n\n        float c1, c2, c3;\n\n        for (int i = 0; i < Nstar; ++i)\n        {\n\n            c1 = abs(scn.starx[i] - xpcentref);\n\n            if (c1 < maxdist)\n            {\n                c2 = abs(scn.stary[i] - ypcentref);\n                if (c2 < maxdist)\n                {\n                    c3 = abs(scn.starz[i] - zpcentref);\n                    if (c3 < maxdist)\n                    {\n                        sqrdistanceToStar = sqrnorm(c1, c2, c3);\n                        if (sqrdistanceToStar < maxdist2)\n                        {\n                            getBodyColor(pixelr, pixelg, pixelb, scn.starTemp[i], scn.starBrightness[i] * 12.); //(R\u00e9cupere la couleur et effectue l'addition composante par composante)\n                        }\n                    }\n                }\n            }\n        }\n\n        float b = 1e-7 / maxdist2; //Angle solide initial environ constant \u00e9gal \u00e0 1e-7\n        *pixelr *= b;\n        *pixelg *= b;\n        *pixelb *= b;\n    }\n#endif\n#if DRAWGRID == 0\n    getFinalColor(pixelr, pixelg, pixelb, pixel_transpr, pixel_transpg, pixel_transpb, canalAlpha, nbCollision); // Calcul de transparence\n#else\n    getFinalColorGrid(xpcentref, ypcentref, zpcentref, pixelr, pixelg, pixelb, pixel_transpr, pixel_transpg, pixel_transpb, nbCollision, ReachedInfinity); // Calcul de la transparence, et calcul de la couleur de la grille\n#endif\n}\n\nvoid render(const char *name)\n{\n    float *image = new float[rdr.width * rdr.height * CHANNEL_NUM]; //Tableau qui va contenir les donn\u00e9es\n\n    int Chunkcomputed = 0;\n    pl::async_par_for(0, rdr.TotalChunknumber, [&](unsigned h) {\n        //for (int h=0;h<rdr.TotalChunknumber;++h){ //A utiliser si jamais pl async ne marche pas\n        printf(\"file %s - Chunk %04d/%04d started - %.2f pourcents  \\n\", name, h, rdr.TotalChunknumber, 100. * (float)Chunkcomputed / ((float)rdr.TotalChunknumber));\n\n        int j0 = h/rdr.NChunkWidth;\n        int i0 = h % rdr.NChunkWidth;\n\n        i0*=rdr.ChunkSizeWidth;\n        j0*=rdr.ChunkSizeHeight;\n        int i1=i0 + rdr.ChunkSizeWidth;\n        int j1=j0 + rdr.ChunkSizeHeight;\n\n\n        for (int j = j0; j < j1; ++j)\n        {\n\n            for (int i = i0; i < i1; ++i)\n            {\n\n                float pixelr, pixelg, pixelb;\n\n                pixelr = 0.;\n                pixelg = 0.;\n                pixelb = 0.;\n\n                sim_bundle(i, j, scn.camera.x, scn.camera.y, scn.camera.z, &pixelr, &pixelg, &pixelb);\n\n                int loc = (rdr.width * j + i) * CHANNEL_NUM;\n\n                image[loc] = pixelr;\n                image[loc + 1] = pixelg;\n                image[loc + 2] = pixelb;\n\n                \n            }\n        }\n        Chunkcomputed++;\n        \n    });\n    //}\n\n    //Postprocess possible ici\n    int index = 0;\n\n    uint8_t *image_byte = new uint8_t[rdr.width * rdr.height * CHANNEL_NUM]; //Image finale\n\n    std::cout << \"conversion\" << endl;\n\n    for (int j = 0; j < rdr.height; ++j)\n    {\n\n        for (int i = 0; i < rdr.width; ++i)\n        {\n\n            image_byte[index] = char(image[index]);\n            index++;\n\n            image_byte[index] = char(image[index]);\n            index++;\n\n            image_byte[index] = char(image[index]);\n            index++;\n        }\n    }\n\n    stbi_write_png(name, rdr.width, rdr.height, CHANNEL_NUM, image_byte, rdr.width * CHANNEL_NUM); \n}\n\nint image(string fichier)//int image()\n{\n    ifstream monFlux;\n    monFlux.open(fichier.c_str()) ;\n    \n    if (monFlux)\n    {\n        monFlux >> bh.a >> disk.R_max >> scn.camera.x >> scn.camera.y >> scn.camera.z >> rdr.R_inf >> rdr.width >> rdr.height;\n        cout<<\"Les param\u00e8tres ont \u00e9t\u00e9 initialis\u00e9s\"<<endl;\n        if (adisk == NULL)\n        {\n            cout<<\"L'image de d\u00e9part n'a pas \u00e9t\u00e9 trouv\u00e9e\"<< endl;\n            exit(0);\n        }\n\n        /*rdr.height = 1080 / 8;\n        rdr.width = 1920 / 8;\n        rdr.R_inf = 21.5; //distance \u00e0 partir de laquelle on considere etre a l'infini */\n\n        rdr.ChunkSizeHeight = 15; //Blocs de 15 par 15 pixels trait\u00e9s en parallele\n        rdr.ChunkSizeWidth = 15; //Blocs de 15 par 15 pixels trait\u00e9s en parallele\n\n        //Euler\n        /*rdr.stepmax=0.0035;\n    rdr.stepmin=0.002; //0.001 min sinon erreurs arrondi ?*/\n\n        //RK4\n        rdr.stepmax = 0.02 * 15;\n        rdr.stepmin = 0.007 * 15;\n\n        rdr.delta = .5; //Ecart angulaire (en pixel) entre les rayons d'un m\u00eame faisceau\n\n        //bh.a = 0.5;   //spin (adimensionn\u00e9,entre 0 et 1)\n        bh.precalc(); //A executer avant inner orbit\n\n        disk.R_min = bh.inner_orbit(); //Trouver l'orbite la plus proche du trou noir encore stable (prograde)\n\n        //disk.R_max = 16.;\n        disk.betamax = 0.65; //Vitesse du disque au plus proche du trou noir (c'est la qu'est la vitesse max pour un profil de vitesse en r^-1/2)\n        disk.TMax = 17500.;  //temperature du disque au plus proche du trou noir\n\n        //scn.FOV=40.;\n\n        disk.texture_rep = 8.; //R\u00e9p\u00e9ter la texture du dique (en longeur pour ne pas qu'elle soit pixelis\u00e9e)\n\n        rdr.precalc(bh.a2); //quelques calculs pour avoir les carr\u00e9s de certaines qtit\u00e9 et le fov en radian etc..\n        //scn.precalc(rdr.width);\n        disk.precalc();\n\n        scn.generateSky();\n\n        //Rendre une image fixe:\n        /*scn.camera.x = 20.;\n        scn.camera.y = 0.;\n        scn.camera.z = 1.2;*/\n\n        /*scn.camera.theta=0.04;\n    scn.camera.phi=0.01;*/\n\n        readSensitivityData(\"sensitivity.txt\", wavelengthSamples, wavelengthSamples5, sensitivitySamplesR, sensitivitySamplesG, sensitivitySamplesB);\n\n        /*for (int l = 0; l < SpectrumSampleSize; ++l)\n    {\n        printf(\"WL:%f R:%f, G:%f B:%f \\n\",wavelengthSamples[l],sensitivitySamplesR[l],sensitivitySamplesG[l],sensitivitySamplesB[l]);\n    }*/\n\n        //float R,G,B;\n        //getBodyColor(&R,&G,&B,6000,1.);\n        //printf(\"R:%f G:%f, B:%f \\n\",R,G,B);\n\n        cout << \"Start\" << endl;\n        render(\"resultat.png\");\n        cout << \"End\" << endl;\n\n        stbi_image_free(adisk);\n    }\n    else\n    {\n        cout << \"Erreur le fichier ne s'est pas ouvert\" << endl;\n    }\n    return 0;\n}\n\n/*int main()\n{\n    image(\"params.txt\");\n    return 0;\n}*/\n\n#include <boost/python.hpp> \n\nBOOST_PYTHON_MODULE(kerr)\n{\n    using namespace boost::python;\n    def(\"image\", image);\n}", "meta": {"hexsha": "661bf4b8a0ff7ab47958caa4a23834129aad14aa", "size": 25471, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "version_cpp_kerr/main.cpp", "max_stars_repo_name": "florentdup/projet-info-trou-noir", "max_stars_repo_head_hexsha": "f4a299866129001bbf9f4f44b10998ed189f2da7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-05-01T13:25:22.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-18T15:56:58.000Z", "max_issues_repo_path": "version_cpp_kerr/main.cpp", "max_issues_repo_name": "florentdup/projet-info-trou-noir", "max_issues_repo_head_hexsha": "f4a299866129001bbf9f4f44b10998ed189f2da7", "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": "version_cpp_kerr/main.cpp", "max_forks_repo_name": "florentdup/projet-info-trou-noir", "max_forks_repo_head_hexsha": "f4a299866129001bbf9f4f44b10998ed189f2da7", "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.7593516209, "max_line_length": 231, "alphanum_fraction": 0.5603627655, "num_tokens": 7971, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839874, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4532065087856363}}
{"text": "#include <aslam/backend/Optimizer2.hpp>\r\n// std::partial_sum\r\n#include <numeric>\r\n#include <aslam/backend/ErrorTerm.hpp>\r\n// M.inverse()\r\n#include <Eigen/Dense>\r\n#include <sm/eigen/assert_macros.hpp>\r\n#include <sparse_block_matrix/linear_solver_dense.h>\r\n#include <sparse_block_matrix/linear_solver_cholmod.h>\r\n#ifndef QRSOLVER_DISABLED\r\n#include <sparse_block_matrix/linear_solver_spqr.h>\r\n#include <aslam/backend/SparseQrLinearSystemSolver.hpp>\r\n#endif\r\n#include <aslam/backend/sparse_matrix_functions.hpp>\r\n#include <aslam/backend/BlockCholeskyLinearSystemSolver.hpp>\r\n#include <aslam/backend/SparseCholeskyLinearSystemSolver.hpp>\r\n#include <aslam/backend/DenseQrLinearSystemSolver.hpp>\r\n#include <sm/PropertyTree.hpp>\r\n\r\n\r\nnamespace aslam {\r\n    namespace backend {\r\n\r\n\r\n        Optimizer2::Optimizer2(const Optimizer2Options& options) :\r\n            _options(options)\r\n        {\r\n            initializeLinearSolver();\r\n            initializeTrustRegionPolicy();\r\n        }\r\n\r\n        Optimizer2::Optimizer2(const sm::PropertyTree& config, boost::shared_ptr<LinearSystemSolver> linearSystemSolver, boost::shared_ptr<TrustRegionPolicy> trustRegionPolicy) {\r\n          Optimizer2Options options;\r\n          options.convergenceDeltaJ = config.getDouble(\"convergenceDeltaJ\", options.convergenceDeltaJ);\r\n          options.convergenceDeltaX = config.getDouble(\"convergenceDeltaX\", options.convergenceDeltaX);\r\n          options.maxIterations = config.getInt(\"maxIterations\", options.maxIterations);\r\n          options.doSchurComplement = config.getBool(\"doSchurComplement\", options.doSchurComplement);\r\n          options.verbose = config.getBool(\"verbose\", options.verbose);\r\n          options.linearSolverMaximumFails = config.getInt(\"linearSolverMaximumFails\", options.linearSolverMaximumFails);\r\n          options.nThreads = config.getInt(\"nThreads\", options.nThreads);\r\n          options.linearSystemSolver = linearSystemSolver;\r\n          options.trustRegionPolicy = trustRegionPolicy;\r\n          _options = options;\r\n          initializeLinearSolver();\r\n          initializeTrustRegionPolicy();\r\n          // USING C++11 would allow to do constructor delegation and more elegant code, i.e., directly call the upper constructor\r\n        }\r\n\r\n        Optimizer2::~Optimizer2()\r\n        {\r\n        }\r\n\r\n\r\n        /// \\brief Set up to work on the optimization problem.\r\n        void Optimizer2::setProblem(boost::shared_ptr<OptimizationProblemBase> problem)\r\n        {\r\n            _problem = problem;\r\n        }\r\n\r\n        void Optimizer2::initializeTrustRegionPolicy()\r\n        {\r\n          if( !_options.trustRegionPolicy ) {\r\n            _options.verbose && std::cout << \"No trust region policy set in the options. Defaulting to levenberg_marquardt\\n\";\r\n            _trustRegionPolicy.reset( new LevenbergMarquardtTrustRegionPolicy() );\r\n          } else {\r\n            _trustRegionPolicy = _options.trustRegionPolicy;\r\n          }\r\n\r\n\r\n          // \\todo remove this check when the sparse qr solver supports an augmented diagonal\r\n          if(_solver->name() == \"sparse_qr\" && _trustRegionPolicy->name() == \"levenberg_marquardt\") {\r\n            _options.verbose && std::cout << \"The sparse_qr solver is not compatible with levenberg_marquardt. Changing to the dog_leg trust region policy\\n\";\r\n            _trustRegionPolicy.reset( new DogLegTrustRegionPolicy() );\r\n          }\r\n\r\n          _options.verbose && std::cout << \"Using the \" << _trustRegionPolicy->name() << \" trust region policy\\n\";\r\n\r\n        }\r\n\r\n\r\n        void Optimizer2::initializeLinearSolver()\r\n        {\r\n          if( ! _options.linearSystemSolver ) {\r\n            _options.verbose && std::cout << \"No linear system solver set in the options. Defaulting to the sparse_cholesky solver\\n\";\r\n            _solver.reset(new SparseCholeskyLinearSystemSolver());\r\n          } else {\r\n            _solver = _options.linearSystemSolver;\r\n          }\r\n\r\n          _options.verbose && std::cout << \"Using the \" << _solver->name() << \" linear system solver\\n\";\r\n        }\r\n\r\n        /// \\brief initialize the optimizer to run on an optimization problem.\r\n        ///        This should be called before calling optimize()\r\n        void Optimizer2::initialize()\r\n        {\r\n          initializeLinearSolver();\r\n          initializeTrustRegionPolicy();\r\n\r\n          SM_ASSERT_FALSE(Exception, _problem.get() == NULL, \"No optimization problem has been set\");\r\n            _options.verbose && std::cout << \"Initializing\\n\";\r\n            Timer init(\"Optimizer2: Initialize Total\");\r\n            _designVariables.clear();\r\n            _designVariables.reserve(_problem->numDesignVariables());\r\n            _errorTerms.clear();\r\n            _errorTerms.reserve(_problem->numErrorTerms());\r\n            Timer initDv(\"Optimizer2: Initialize---Design Variables\");\r\n            // Run through all design variables adding active ones to an active list.\r\n            // std::cout << \"dvloop 1\\n\";\r\n            for (size_t i = 0; i < _problem->numDesignVariables(); ++i) {\r\n                DesignVariable* dv = _problem->designVariable(i);\r\n                if (dv->isActive())\r\n                    _designVariables.push_back(dv);\r\n            }\r\n            SM_ASSERT_FALSE(Exception, _designVariables.empty(), \"It is illegal to run the optimizer with all marginalized design variables.\");\r\n            // Assign block indices to the design variables.\r\n            // \"blocks\" will hold the structure of the left-hand-side of Gauss-Newton\r\n            int columnBase = 0;\r\n            // std::cout << \"dvloop 2\\n\";\r\n            for (size_t i = 0; i < _designVariables.size(); ++i) {\r\n                _designVariables[i]->setBlockIndex(i);\r\n                _designVariables[i]->setColumnBase(columnBase);\r\n                columnBase += _designVariables[i]->minimalDimensions();\r\n            }\r\n            initDv.stop();\r\n            Timer initEt(\"Optimizer2: Initialize---Error Terms\");\r\n            // Get all of the error terms that work on these design variables.\r\n            int dim = 0;\r\n            // std::cout << \"eloop 1\\n\";\r\n            for (unsigned i = 0; i < _problem->numErrorTerms(); ++i) {\r\n                ErrorTerm* e = _problem->errorTerm(i);\r\n                _errorTerms.push_back(e);\r\n                e->setRowBase(dim);\r\n                dim += e->dimension();\r\n            }\r\n            initEt.stop();\r\n            SM_ASSERT_FALSE(Exception, _errorTerms.empty(), \"It is illegal to run the optimizer with no error terms.\");\r\n            Timer initMx(\"Optimizer2: Initialize---Matrices\");\r\n            // Set up the block matrix structure.\r\n            // std::cout << \"init structure\\n\";\r\n            //      initializeLinearSolver();\r\n            _solver->initMatrixStructure(_designVariables, _errorTerms, _trustRegionPolicy->requiresAugmentedDiagonal());\r\n            initMx.stop();\r\n            _options.verbose && std::cout << \"Optimization problem initialized with \" << _designVariables.size() << \" design variables and \" << _errorTerms.size() << \" error terms\\n\";\r\n            // \\todo Say how big the problem is.\r\n            _options.verbose && std::cout << \"The Jacobian matrix is \" << dim << \" x \" << columnBase << std::endl;\r\n\r\n\r\n            // \\todo initialize the trust region stuff.\r\n\r\n        }\r\n\r\n\r\n        /*\r\n        // returns true of stop!\r\n        bool Optimizer2::evaluateStoppingCriterion(int iterations)\r\n        {\r\n\r\n        // as we have analytic Jacobians we can assume the precision to be:\r\n        double epsilon = std::numeric_limits<double>::epsilon();\r\n\r\n        double x_norm = ...;\r\n\r\n        // the gradient: is simply the right hand side of GN:\r\n        double grad_norm = _rhs.norm();\r\n        double abs_J = fabs(_J);\r\n\r\n        // the first condition:\r\n        bool crit1 = grad_norm < sqrt(epsilon) * (1 + abs_J);\r\n\r\n        bool crit2 = _dx.norm() < sqrt(epsilon) * (1 + x_norm);\r\n\r\n        bool crit3 = fabs(_J - _p_J) < epsilon * (1 + abs_J);\r\n\r\n        bool crit4 = iterations < _options.maxIterations;\r\n\r\n        return (crit1 && crit2 && crit3) || crit4;\r\n\r\n        }*/\r\n\r\n\r\n\r\n        SolutionReturnValue Optimizer2::optimize()\r\n        {\r\n            Timer timeGn(\"Optimizer2: build Hessian\", true);\r\n            Timer timeErr(\"Optimizer2: evaluate error\", true);\r\n            Timer timeSchur(\"Optimizer2: Schur complement\", true);\r\n            Timer timeBackSub(\"Optimizer2: Back substitution\", true);\r\n            Timer timeSolve(\"Optimizer2: Solve linear system\", true);\r\n            // Select the design variables and (eventually) the error terms involved in the optimization.\r\n            initialize();\r\n            SolutionReturnValue srv;\r\n            _p_J = 0.0;\r\n\r\n            //std::cout << \"Evaluate error for the first time\\n\";\r\n            // This sets _J\r\n            timeErr.start();\r\n            evaluateError(true);\r\n            timeErr.stop();\r\n            _p_J = _J;\r\n            srv.JStart = _p_J;\r\n            // *** while not done\r\n            _options.verbose && std::cout << \"[\" << srv.iterations << \".0]: J: \" << _J << std::endl;\r\n            // Set up the estimation problem.\r\n            double deltaX = _options.convergenceDeltaX + 1.0;\r\n            double deltaJ = _options.convergenceDeltaJ + 1.0;\r\n            bool previousIterationFailed = false;\r\n            bool linearSolverFailure = false;\r\n\r\n            SM_ASSERT_TRUE(Exception, _solver.get() != NULL, \"The solver is null\");\r\n            _trustRegionPolicy->setSolver(_solver);\r\n            _trustRegionPolicy->optimizationStarting(_J);\r\n\r\n            // Loop until convergence\r\n            while (srv.iterations <  _options.maxIterations &&\r\n                   srv.failedIterations < _options.maxIterations &&\r\n                   ((deltaX > _options.convergenceDeltaX &&\r\n                     fabs(deltaJ) > _options.convergenceDeltaJ) ||\r\n                    linearSolverFailure)) {\r\n\r\n                timeSolve.start();\r\n                bool solutionSuccess = _trustRegionPolicy->solveSystem(_J, previousIterationFailed, _options.nThreads, _dx);\r\n                timeSolve.stop();\r\n\r\n                if (!solutionSuccess) {\r\n                    _options.verbose && std::cout << \"[WARNING] System solution failed\\n\";\r\n                    previousIterationFailed = true;\r\n                    linearSolverFailure = true;\r\n                    srv.failedIterations++;\r\n                } else {\r\n                    /// Apply the state update. _A, _b, _dx, and _H are passed in implicitly.\r\n                    timeBackSub.start();\r\n                    deltaX = applyStateUpdate();\r\n                    timeBackSub.stop();\r\n                    // This sets _J\r\n                    timeErr.start();\r\n                    evaluateError(true);\r\n                    timeErr.stop();\r\n                    deltaJ = _p_J - _J;\r\n                    // This was a regression.\r\n                    if( _trustRegionPolicy->revertOnFailure() )\r\n                    {\r\n                        if(deltaJ < 0.0)\r\n                        {\r\n                            _options.verbose && std::cout << \"Last step was a regression. Reverting\\n\";\r\n                            revertLastStateUpdate();\r\n                            srv.failedIterations++;\r\n                            previousIterationFailed = true;\r\n                        }\r\n                        else\r\n                        {\r\n                            _p_J = _J;\r\n                            previousIterationFailed = false;\r\n                        }\r\n                    }\r\n                    else\r\n                    {\r\n                        _p_J = _J;\r\n                    }\r\n                    srv.iterations++;\r\n\r\n                    _options.verbose && std::cout << \"[\" << srv.iterations << \"]: J: \" << _J << \", dJ: \" << deltaJ << \", deltaX: \" << deltaX << \", \";\r\n                    _options.verbose && _trustRegionPolicy->printState(std::cout);\r\n                    _options.verbose && std::cout << std::endl;\r\n                } // if the linear solver failed / else\r\n            }\r\n\r\n            srv.JFinal = _p_J;\r\n            srv.dXFinal = deltaX;\r\n            srv.dJFinal = deltaJ;\r\n            srv.linearSolverFailure = linearSolverFailure;\r\n            return srv;\r\n        }\r\n\r\n\r\n            DesignVariable* Optimizer2::designVariable(size_t i)\r\n            {\r\n                SM_ASSERT_LT_DBG(Exception, i, _designVariables.size(), \"index out of bounds\");\r\n                return _designVariables[i];\r\n            }\r\n\r\n\r\n\r\n            size_t Optimizer2::numDesignVariables() const\r\n            {\r\n                return _designVariables.size();\r\n            }\r\n\r\n\r\n            double Optimizer2::applyStateUpdate()\r\n            {\r\n                // Apply the update to the dense state.\r\n                int startIdx = 0;\r\n                for (size_t i = 0; i < numDesignVariables(); i++) {\r\n                    DesignVariable* d = _designVariables[i];\r\n                    const int dbd = d->minimalDimensions();\r\n                    Eigen::VectorXd dxS = _dx.segment(startIdx, dbd);\r\n                    dxS *= d->scaling();\r\n                    d->update(&dxS[0], dbd);\r\n                    startIdx += dbd;\r\n                }\r\n                // Track the maximum delta\r\n                // \\todo: should this be some other metric?\r\n                double deltaX = _dx.array().abs().maxCoeff();\r\n                return deltaX;\r\n            }\r\n\r\n\r\n\r\n\r\n\r\n            void Optimizer2::revertLastStateUpdate()\r\n            {\r\n                for (size_t i = 0; i < _designVariables.size(); i++) {\r\n                    _designVariables[i]->revertUpdate();\r\n                }\r\n            }\r\n\r\n\r\n            Optimizer2Options& Optimizer2::options()\r\n            {\r\n                return _options;\r\n            }\r\n\r\n\r\n            double Optimizer2::evaluateError(bool useMEstimator)\r\n            {\r\n                SM_ASSERT_TRUE(Exception, _solver.get() != NULL, \"The solver is null\");\r\n                _J = _solver->evaluateError(_options.nThreads, useMEstimator);\r\n                return _J;\r\n            }\r\n\r\n\r\n            /// \\brief return the reduced system dx\r\n            const Eigen::VectorXd& Optimizer2::dx() const\r\n            {\r\n                return _dx;\r\n            }\r\n\r\n            /// The value of the objective function.\r\n            double Optimizer2::J() const\r\n            {\r\n                return _J;\r\n            }\r\n\r\n            void Optimizer2::printTiming() const\r\n            {\r\n                sm::timing::Timing::print(std::cout);\r\n            }\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n            void Optimizer2::checkProblemSetup()\r\n            {\r\n                // Check that all error terms are hooked up to design variables.\r\n            }\r\n\r\n\r\n\r\n            void Optimizer2::computeDiagonalCovariances(SparseBlockMatrix& outP, double lambda)\r\n            {\r\n                SM_THROW(Exception, \"Broken\");\r\n\r\n                std::vector<std::pair<int, int> > blockIndices;\r\n                for (size_t i = 0; i < _designVariables.size(); ++i) {\r\n                    blockIndices.push_back(std::make_pair(i, i));\r\n                }\r\n                computeCovarianceBlocks(blockIndices, outP, lambda);\r\n            }\r\n\r\n    void Optimizer2::computeCovarianceBlocks(const std::vector<std::pair<int, int> > & /* blockIndices */, SparseBlockMatrix& /* outP */, double /* lambda */)\r\n            {\r\n                SM_THROW(Exception, \"Broken\");\r\n\r\n            }\r\n\r\n\r\n    void Optimizer2::computeCovariances(SparseBlockMatrix& /* outP */, double /* lambda */)\r\n            {\r\n                SM_THROW(Exception, \"Broken\");\r\n\r\n            }\r\n\r\n        void Optimizer2::computeHessian(SparseBlockMatrix& outH, double lambda)\r\n            {\r\n\r\n              boost::shared_ptr<BlockCholeskyLinearSystemSolver> solver_sp;\r\n              solver_sp.reset(new BlockCholeskyLinearSystemSolver());\r\n              // True here for creating the diagonal conditioning.\r\n              solver_sp->initMatrixStructure(_designVariables, _errorTerms, true);\r\n\r\n              _options.verbose && std::cout << \"Setting the diagonal conditioner to: \" << lambda << \".\\n\";\r\n              evaluateError(false);\r\n              solver_sp->setConstantConditioner(lambda);\r\n              solver_sp->buildSystem(_options.nThreads, false);\r\n              solver_sp->copyHessian(outH);\r\n            }\r\n\r\n      const LinearSystemSolver * Optimizer2::getBaseSolver() const {\r\n          return _solver.get();\r\n      }\r\n\r\n\r\n\r\n        const Matrix * Optimizer2::getJacobian() const {\r\n            return _solver->Jacobian();\r\n        }\r\n\r\n\r\n        } // namespace backend\r\n    } // namespace aslam\r\n", "meta": {"hexsha": "0ec5964e11ce9bde1744c130ec00a7d60c3d04c9", "size": 16655, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "aslam_optimizer/aslam_backend/src/Optimizer2.cpp", "max_stars_repo_name": "mintar/kalibr", "max_stars_repo_head_hexsha": "f4af670fbd87a0acd2c6771b4fb418dc12cc6026", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-01-06T12:57:01.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-15T15:00:46.000Z", "max_issues_repo_path": "aslam_optimizer/aslam_backend/src/Optimizer2.cpp", "max_issues_repo_name": "mintar/kalibr", "max_issues_repo_head_hexsha": "f4af670fbd87a0acd2c6771b4fb418dc12cc6026", "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_optimizer/aslam_backend/src/Optimizer2.cpp", "max_forks_repo_name": "mintar/kalibr", "max_forks_repo_head_hexsha": "f4af670fbd87a0acd2c6771b4fb418dc12cc6026", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-05-26T06:33:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-07T21:08:14.000Z", "avg_line_length": 40.0360576923, "max_line_length": 184, "alphanum_fraction": 0.5445211648, "num_tokens": 3353, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.63341027751814, "lm_q1q2_score": 0.45315691171234646}}
{"text": "#include \"precompiled.h\"\n\n#ifndef AUTOMATIC_PRECOMPILATION\n#include <boost/property_tree/ptree.hpp>\n#include <boost/throw_exception.hpp>\n#include <exception>\n#include <memory>\n#include <algorithm>\n#include <boost/lexical_cast.hpp>\n#endif\n\n#include \"grid.h\"\n#include \"utility.h\"\n#include \"grid_tests.h\"\n#include \"utility.h\"\n#include \"global_config.h\"\n#include \"grid_iterators.h\"\n#include \"configuration_parser.h\"\n\n\nvoid cut_off(double& a){ // or you need something like CodeRefTHR\n\ta = abs(a)<1e-15 ? 0 : a;\n}\n\n\nnamespace fipster { namespace _grid {\n\n\tstate_variable_t::state_variable_t( const ptree& pt ) \n\t\t:\tn(betterGet<int>(pt,\"n\",\"state variable\"))\t\t\n\t\t,\tspacing_node(betterChild(pt,\"spacing\",\"state variable \"+toS(n)))\n\t\t, hits_zero(spacing_node.get(\"<xmlattr>.hitsZero\",false))\n\t{\n\t\tlower_bound = pt.get<double>(\"lowerBound\");\n\t\tupper_bound = pt.get<double>(\"upperBound\");\n\t\tFIPSTER_ASSERT(lower_bound<upper_bound);\n\t\ttolerance = pt.get(\"tolerance\",1e-17);\n\n\t\tspacing_type = spacing_node.get<string>(\"<xmlattr>.type\");\n\t}\n\n\ttemplate<class A>\n\tvoid state_variable_t::fill_coords( A& coords, A& stepsizes )\n\t{\n#define coords(i) coords[i]\n#define stepsizes(i) stepsizes[i]\n\t\t// homogeneous #########################################\n\t\tif(spacing_type == \"homogeneous\"){\n\t\t\tdouble s;\n\t\t\ts = (upper_bound-lower_bound)/(n-1);\n\t\t\tfor(uint i = 0; i<n ; ++i )\n\t\t\t\tcoords(i) = i*s + lower_bound;\t\t\t\t\t\n\n\t\t\t// exponential #########################################\n\t\t}else if(spacing_type == \"exponential\"){\n\t\t\tdouble a,b,h = spacing_node.get<double>(\"h\");\n\t\t\ta = (upper_bound-lower_bound)/(exp(h)-1.0);\n\t\t\tb = h/(n-1);\n\t\t\tfor(uint i=0; i < n; ++i)\n\t\t\t\tcoords(i) = a*(exp(i*b)-1.0)+lower_bound;\n\n\t\t\t// not implemented #########################################\n\t\t}else\n\t\t\tBOOST_THROW_EXCEPTION(invalid_argument(\"Grid spacing '\"+spacing_type+\"' not implemented\"));\n\n    //shift to include 0\n\t\tdouble shift = 0;\n\t\tif(hits_zero){\n\t\t\tvector<double> temp=coords;\n\t\t\tfor(auto& t: temp) t=abs(t);\n\t\t\tshift=coords(min_element(begin(temp),end(temp))-begin(temp));\n\t\t\tfor(auto& t: coords) t-=shift;\n\t\t}\n\t\n\t\t//produce stepsizes\n\t\tfor(uint i=0;i<n-1;i++){\n\t\t\tcut_off(coords(i));\n\t\t\tstepsizes(i) = coords(i+1)-coords(i);\n\t\t\t\n\t\t}\n\n\t\t// validate coordinates and stepsizes  #########################################\n\t\tdouble s=abs(coords(n-1)-upper_bound+shift);\n\t\tif(s >= tolerance*(upper_bound-lower_bound) \n\t\t\t|| s!=s ) //This checks for NaN and Inf and stuff\n\t\t\tBOOST_THROW_EXCEPTION(underflow_error\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t(\"coords did to not add up (rel.Err: \"+toString(s)+\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t \", tolerance: \"+toString(tolerance)+\")\"));\n\n#undef coords\n#undef stepsizes\n\t}\n\n\t\n\n\n\tGrid::Grid( const ptree& pt )\n\t\t: state_variables_config_t(pt)\n\t\t, id(betterGet<string>(pt,\"<xmlattr>.id\",\"grid\"))\n\t\t, max_subgrid(pt.get_optional<double>(\"maxSubgrid\"))\n\t{\n\t\t//infer the dimension of the grid\n\t\tD = sv_vec.size();\n\t\tsizes.resize(D);\n\n\t\tmaxsize=0;\n\t\tfor(uint i=0;i<D;i++){\n\t\t\tsizes[i] = sv_vec[i].n;\n\t\t\tmaxsize = max(maxsize,sizes[i]);\n\t\t}\n\n\t\t//Strides and Number of points\n\t\tN.resize(implemented_inner_grids);\n\t\tstrides.resize(implemented_inner_grids,D);\n\t\tNbound.resize(implemented_inner_grids-1);\n\n\t\tfor(uint j=0; j < implemented_inner_grids; ++j) \n\t\t{\n\t\t\t//Strides\n\t\t\tstrides(j,0) = 1;\n\t\t\tfor(uint i=1; i < D; ++i)\n\t\t\t\tstrides(j,i)=strides(j,i-1)*(sizes[i-1]-j*2);\n\n\t\t\t//Number of points\n\t\t\tN[j]=strides(j,D-1)*(sizes[D-1]-j*2);\n\n\t\t\t//check if sizes are sufficient to implement up to implemented_inner_grids!\n\t\t\tif(max_subgrid && *max_subgrid>=j && sizes[D-1]<=(int)j*2)\n\t\t\t\tBOOST_THROW_EXCEPTION(\n\t\t\t\t\truntime_error(\"grid size in dimension \"+toS(j)+\" is too small for inner_grid \"+toS(j)));\n\t\t}\n\n\t\t//Number of boundary points\n\t\tfor(uint j=0; j < implemented_inner_grids-1; ++j) \n\t\t\tNbound[j] = N[j] - N[j+1];\n\n\t\t//origin offsets\n\t\tfor(uint j=0; j < implemented_inner_grids; ++j) \n\t\t\torigin_offset[j] = strides.row(j).sum()*j;\n\n\n\t\t//reserve space\n\t\tcoords.resize(D);\n\t\tstepsizes.resize(D);\n\n\t\t//fill coordinates and stepsizes\n\t\tfor(uint i=0;i<D;i++){\n\t\t\tcoords[i].resize(sizes[i]);\n\t\t\tstepsizes[i].resize(sizes[i]-1);\n\t\t\tsv_vec[i].fill_coords(coords[i],stepsizes[i]);\n\t\t}\n\n\t\t//test iterator logic:\n\t\tif(global_config::get().test_grid_iterators)\n\t\t\ttest_iterator_logic(*this);\n\t}\n\n\n\tostream& operator<<(ostream& out,const Grid& grid)\n\t{\n\t\tauto state_it = grid_iterator<0,true>(grid);\n\t\tfor(;state_it!=grid.end<0>();++state_it){\n\t\t\tout<<state_it.ind<<\"\\t\";\n\t\t\tfor(uint i=0;i<grid.D;i++)\n\t\t\t\tout<<boost::lexical_cast<string>(state_it.state()[i])<<\"\\t\";\n\t\t\tout<<\"\\n\";\n\t\t}\n\t\tout.flush();\t\t\n\t\treturn out;\t\t\n\t}\n\n\t\t\n}}\n", "meta": {"hexsha": "ca8639e9bd3f5962775c4b7614375946c23bf074", "size": 4574, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/grid_config.cpp", "max_stars_repo_name": "johannesgerer/fipster", "max_stars_repo_head_hexsha": "10e840e01d196cddef75bf3eeb427f720b3e0ad6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-29T14:33:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-29T14:33:37.000Z", "max_issues_repo_path": "src/grid_config.cpp", "max_issues_repo_name": "johannesgerer/fipster", "max_issues_repo_head_hexsha": "10e840e01d196cddef75bf3eeb427f720b3e0ad6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/grid_config.cpp", "max_forks_repo_name": "johannesgerer/fipster", "max_forks_repo_head_hexsha": "10e840e01d196cddef75bf3eeb427f720b3e0ad6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.4393063584, "max_line_length": 94, "alphanum_fraction": 0.6311762134, "num_tokens": 1354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239836484143, "lm_q2_score": 0.6334102775181399, "lm_q1q2_score": 0.45315690402587533}}
{"text": "#define BOOST_TEST_MODULE \"test_truncate\"\n\n#include <boost/test/included/unit_test.hpp>\n\n// the code to test:\n#include \"truncate.hpp\"\n\nBOOST_AUTO_TEST_CASE(_fast_pow) {\n    // results for fast_pow(e < -126) are not defined\n    BOOST_CHECK_EQUAL(fast_pow(0), 1);\n    BOOST_CHECK_EQUAL(fast_pow(1), 2);\n    BOOST_CHECK_EQUAL(fast_pow(2), 4);\n    BOOST_CHECK_EQUAL(fast_pow(5), 32);\n    BOOST_CHECK_EQUAL(fast_pow(-1), 0.5);\n    BOOST_CHECK_EQUAL(fast_pow(-2), 0.25);\n    BOOST_CHECK_EQUAL(fast_pow(-4), 0.0625);\n    BOOST_CHECK_EQUAL(fast_pow(64), std::pow(2.0, 64));\n    BOOST_CHECK_EQUAL(fast_pow(-64), std::pow(2.0, -64));\n    BOOST_CHECK_EQUAL(std::numeric_limits<float>::min(), (float)(std::pow(2.0, -126)));\n    BOOST_CHECK_EQUAL(fast_pow(-125), (float)std::pow(2.0, -125));\n    BOOST_CHECK_EQUAL(fast_pow(-126), (float)std::pow(2.0, -126));\n    BOOST_CHECK_EQUAL(fast_pow(INT8_MAX), std::pow(2.0, INT8_MAX));\n    BOOST_CHECK_EQUAL(fast_pow(INT8_MIN), -1.0 * std::numeric_limits<float>::infinity());\n}\n\nBOOST_AUTO_TEST_CASE(_count_zeros) {\n    // int32_t count_zeros(int32_t x)\n    BOOST_CHECK_EQUAL(count_zeros(0), 32);\n    BOOST_CHECK_EQUAL(count_zeros(1), 31);\n    BOOST_CHECK_EQUAL(count_zeros(2), 30);\n    BOOST_CHECK_EQUAL(count_zeros(3), 30);\n    BOOST_CHECK_EQUAL(count_zeros(INT32_MAX), 1);\n    BOOST_CHECK_EQUAL(count_zeros(INT32_MIN), 0);\n}\n\nBOOST_AUTO_TEST_CASE(_bit_truncate_float) {\n    // float bit_truncate_float(float val, float err)\n    BOOST_CHECK_SMALL(bit_truncate_float(0.11, 0.01) - 0.11, 0.01);\n    BOOST_CHECK(bit_truncate_float(0.11, 0.01) < 0.11);\n\n    BOOST_CHECK_SMALL(bit_truncate_float(0.11, 0.01) - 0.11, 0.01);\n    BOOST_CHECK(bit_truncate_float(0.11, 0.01) < 0.11);\n\n    BOOST_CHECK(bit_truncate_float(0.0, 0.0) == 0.0);\n    BOOST_CHECK_SMALL(bit_truncate_float(0.11, 0.0) - 0.11, 0.0001);\n    BOOST_CHECK_SMALL(bit_truncate_float(1.11, 0.0) - 1.11, 0.0001);\n    BOOST_CHECK(bit_truncate_float(0.0, 0.1) == 0.0);\n\n    BOOST_CHECK_SMALL(bit_truncate_float(-0.11, 0.0) + 0.11, 0.0001);\n    BOOST_CHECK_SMALL(bit_truncate_float(-1.11, 0.0) + 1.11, 0.0001);\n\n    BOOST_CHECK_EQUAL(bit_truncate_float(std::numeric_limits<float>::max(), 0.01),\n                      std::numeric_limits<float>::max());\n    BOOST_CHECK_EQUAL(bit_truncate_float(std::numeric_limits<float>::min(), 0.01),\n                      std::numeric_limits<float>::min());\n}\n", "meta": {"hexsha": "a40633f0f868a11ccb2e35dea77506b65a8f2de8", "size": 2377, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/boost/test_truncate.cpp", "max_stars_repo_name": "james-s-willis/kotekan", "max_stars_repo_head_hexsha": "155e874bb039702cec72c1785362a017548aa00a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/boost/test_truncate.cpp", "max_issues_repo_name": "james-s-willis/kotekan", "max_issues_repo_head_hexsha": "155e874bb039702cec72c1785362a017548aa00a", "max_issues_repo_licenses": ["MIT"], "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/boost/test_truncate.cpp", "max_forks_repo_name": "james-s-willis/kotekan", "max_forks_repo_head_hexsha": "155e874bb039702cec72c1785362a017548aa00a", "max_forks_repo_licenses": ["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.701754386, "max_line_length": 89, "alphanum_fraction": 0.6907867059, "num_tokens": 767, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239836484143, "lm_q2_score": 0.6334102775181399, "lm_q1q2_score": 0.45315690402587533}}
{"text": "#ifndef LINEAR_BASIS_HPP\n#define LINEAR_BASIS_HPP\n\n#include <armadillo>\n#include <math.h>\n\n\nclass LinearBasisFunction : public Basis {\n\npublic:\n\n    int _nX;\n    int _nK;\n    int _nU;\n    int _nM;\n    int _nKU;\n\n    LinearBasisFunction(int _nX = 7, int _nK = 9, int _nU = 2 , int _nM = 6, int _nKU = 2) : Basis(_nX,_nK,_nU,_nM,_nKU) {\n        this->_nX = _nX;\n        this->_nK = _nK;\n        this->_nU = _nU;\n        this->_nM = _nM;\n        this->_nKU = _nKU;\n    }\n\n    arma::vec fk(const arma::vec & x, const arma::vec & u ) {\n        return arma::join_cols( fkx(x), fku(x, u) );\n    }\n\n    arma::vec fkx( const arma::vec& x ) {\n        return arma::vec({\n            x[0],\n            x[1],\n            x[2],\n            x[3],\n            x[4],\n            x[5],\n            1\n        });\n    }\n\n    arma::vec fku( const arma::vec & x, const arma::vec& u ) {\n\n        return arma::vec({\n            u[0],\n            u[1]\n          });\n\n    }\n\n    arma::mat fkudu( const arma::vec & x, const arma::vec & u) {\n        return arma::mat({\n            {1,0},\n            {0,1}\n        });\n    }\n\n};\n\n#endif\n", "meta": {"hexsha": "32902212d89954efcc42c65c70ac1c47be0391f5", "size": 1108, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/model_based_shared_control/src/robotlib/dynamicalSystems/koopman/basis_functions/linear_basis.hpp", "max_stars_repo_name": "argallab/model_based_shared_control", "max_stars_repo_head_hexsha": "ff42226b6345266f35a32021c7d0b44cc5948ec1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-05-08T19:47:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T06:43:31.000Z", "max_issues_repo_path": "src/model_based_shared_control/src/robotlib/dynamicalSystems/koopman/basis_functions/linear_basis.hpp", "max_issues_repo_name": "argallab/model_based_shared_control", "max_issues_repo_head_hexsha": "ff42226b6345266f35a32021c7d0b44cc5948ec1", "max_issues_repo_licenses": ["MIT"], "max_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_based_shared_control/src/robotlib/dynamicalSystems/koopman/basis_functions/linear_basis.hpp", "max_forks_repo_name": "argallab/model_based_shared_control", "max_forks_repo_head_hexsha": "ff42226b6345266f35a32021c7d0b44cc5948ec1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-05-08T19:47:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-07T10:10:17.000Z", "avg_line_length": 18.1639344262, "max_line_length": 122, "alphanum_fraction": 0.4485559567, "num_tokens": 377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.4531569018106638}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2013 Kyle Lutz <kyle.r.lutz@gmail.com>\n//\n// Distributed under the Boost Software License, Version 1.0\n// See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt\n//\n// See http://kylelutz.github.com/compute for more information.\n//---------------------------------------------------------------------------//\n\n#define BOOST_TEST_MODULE TestTransformIf\n#include <boost/test/unit_test.hpp>\n\n#include <boost/compute/lambda.hpp>\n#include <boost/compute/functional.hpp>\n#include <boost/compute/experimental/transform_if.hpp>\n#include <boost/compute/container/vector.hpp>\n\n#include \"check_macros.hpp\"\n#include \"context_setup.hpp\"\n\nnamespace compute = boost::compute;\n\nBOOST_AUTO_TEST_CASE(abs_if_odd)\n{\n    using compute::lambda::_1;\n\n    // input data\n    int data[] = { -2, -3, -4, -5, -6, -7, -8, -9 };\n    compute::vector<int> vector(data, data + 8, queue);\n\n    // calculate absolute value only for odd values\n    compute::experimental::transform_if(\n        vector.begin(),\n        vector.end(),\n        vector.begin(),\n        compute::abs<int>(),\n        _1 % 2 != 0,\n        queue\n    );\n\n    // check transformed values\n    CHECK_RANGE_EQUAL(int, 8, vector, (-2, +3, -4, +5, -6, +7, -8, +9));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "ba738a258247adbab840c5f7c1322943fdf27b30", "size": 1358, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_transform_if.cpp", "max_stars_repo_name": "bastiankoe/compute", "max_stars_repo_head_hexsha": "57eec36d20e122a496d3fbfddf8bf4ad8d6f4a4f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-31T17:12:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-31T17:12:33.000Z", "max_issues_repo_path": "test/test_transform_if.cpp", "max_issues_repo_name": "bastiankoe/compute", "max_issues_repo_head_hexsha": "57eec36d20e122a496d3fbfddf8bf4ad8d6f4a4f", "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/test_transform_if.cpp", "max_forks_repo_name": "bastiankoe/compute", "max_forks_repo_head_hexsha": "57eec36d20e122a496d3fbfddf8bf4ad8d6f4a4f", "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.8936170213, "max_line_length": 79, "alphanum_fraction": 0.5905743741, "num_tokens": 326, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154240079185319, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.4531568995954516}}
{"text": "// Copyright 2014, Max Planck Society.\r\n// Distributed under the BSD 3-Clause license.\r\n// (See accompanying file LICENSE.txt or copy at\r\n// http://opensource.org/licenses/BSD-3-Clause)\r\n\r\n#ifndef GRASSMANN_AVERAGES_PCA_HPP__\r\n#define GRASSMANN_AVERAGES_PCA_HPP__\r\n\r\n/*!@file\r\n * Grassmann PCA functions, following the paper of Soren Hauberg.\r\n *\r\n * @note These implementations assume the existence of boost somewhere. \r\n */\r\n\r\n#include <vector>\r\n\r\n\r\n#include <boost/numeric/ublas/vector_expression.hpp>\r\n#include <boost/numeric/ublas/vector.hpp>\r\n\r\n\r\n// for the thread pools\r\n#include <boost/asio/io_service.hpp>\r\n#include <boost/bind.hpp>\r\n#include <boost/thread/thread.hpp>\r\n#include <boost/signals2.hpp>\r\n\r\n// utilities\r\n#include <include/private/utilities.hpp>\r\n\r\n\r\nnamespace grassmann_averages_pca\r\n{\r\n\r\n  namespace ub = boost::numeric::ublas;\r\n\r\n  /*!@brief Grassmann Averages for scalable PCA algorithm\r\n   *\r\n   * This class implements the Grassmann average for computing the PCA in a robust manner. \r\n   * Its purpose is to compute the PCA of a dataset @f$\\{X_i\\}@f$, where each @f$X_i@f$ is a vector of dimension\r\n   * D. \r\n   * \r\n   * The algorithm is the following:\r\n   * - pick a random or a given @f$\\mu_{k, 0}@f$, where @f$k@f$ is the current eigen-vector being computed and @f$0@f$ is the current iteration number (0). \r\n   * - until the sequence @f$(\\mu_{k, t})_t@f$ converges, do:\r\n   *   - computes the sign @f$s_{j, t}@f$ of the projection of the input vectors @f$X_j@f$ onto @f$\\mu_{i, t}@f$. We have @f[s_{j, t} = X_j \\cdot \\mu_{k, t} \\geq 0@f]\r\n   *   - compute the update of @f$\\mu_{k, .}@f$: @f[\\mu_{k, t+1} = \\frac{\\sum_j s_{j, t} X_j}{\\left\\|\\sum_j s_{j, t} X_j\\right\\|}@f]\r\n   * - project the @f$X_j@f$'s onto the orthogonal subspace of @f$\\mu_{k} = \\lim_{t \\rightarrow +\\infty} \\mu_{k, t}@f$: @f[\\forall j, X_{j} = X_{j} - X_{j}\\cdot\\mu_{k} @f]\r\n   *\r\n   * The range taken by @f$k@f$ is a parameter of the algorithm: @c max_dimension_to_compute (see grassmann_pca::batch_process). \r\n   * The range taken by @f$t@f$ is also a parameter of the algorithm: @c max_iterations (see grassmann_pca::batch_process).\r\n   * The test for convergence is delegated to the class details::convergence_check.\r\n   *\r\n   * The computation is distributed among several threads. The multithreading strategy is \r\n   * - to split the computation of @f$\\sum_j s_{j, t} X_j@f$ among several independant chunks. This computation involves the inner product and the sign. Each chunk addresses \r\n   *   a subset of the data @f$\\{X_j\\}@f$ without any overlap with other chunks. The maximal size of a chunk can be configured through the function grassmann_pca::set_max_chunk_size.\r\n   *   By default, the size of the chunk would be the size of the data divided by the number of threads.\r\n   * - to split the computation of the projection onto the orthogonal subspace of @f$\\mu_{k}@f$.\r\n   * - to split the computation of the regular PCA algorithm (if any) into several independant chunks.\r\n   *\r\n   * The number of threads can be configured through the function grassmann_pca::set_nb_processors.\r\n   * \r\n   * @note\r\n   * The algorithm may also perform a few \"regular PCA\" steps, which is the computation of the eigen-vector with highest eigen-value. This can be configured through the function\r\n   * grassmann_pca::set_nb_steps_pca.\r\n   *\r\n   * @tparam data_t type of vectors used for the computation. \r\n   * @tparam observer_t an observer type following the signature of the class grassmann_trivial_callback.\r\n   * @tparam norm_mu_t norm used to normalize the eigen-vector and project them onto the unit circle.\r\n   *\r\n   * @author Soren Hauberg, Raffi Enficiaud\r\n   */\r\n  template <class data_t, \r\n            class observer_t = grassmann_trivial_callback<data_t>,\r\n            class norm_mu_t = details::norm2>\r\n  struct grassmann_pca\r\n  {\r\n  private:\r\n    //! Random generator for initialising @f$\\mu@f$ at each dimension. \r\n    details::random_data_generator<data_t> random_init_op;\r\n\r\n    //! Norm used for normalizing @f$\\mu@f$.\r\n    norm_mu_t norm_op;\r\n\r\n    //! Number of parallel tasks that will be used for computing.\r\n    size_t nb_processors;\r\n\r\n    //! Maximal size of a chunk (infinity by default).\r\n    size_t max_chunk_size;\r\n\r\n    //! Number of steps for the initial PCA like algorithm (default to 3).\r\n    size_t nb_steps_pca;\r\n\r\n    //! Indicates that the incoming data is not centered and a centering should be performed prior\r\n    //! to the computation of the PCA or the trimmed grassmann average.\r\n    bool need_centering;\r\n\r\n    //! An instance observing the steps of the algorithm\r\n    observer_t *observer;    \r\n\r\n    //!@internal\r\n    //!@brief Contains the logic for processing part of the accumulator\r\n    struct asynchronous_chunks_processor\r\n    {\r\n    private:\r\n      //! Type of the elements contained in the vectors\r\n      typedef typename data_t::value_type scalar_t;\r\n\r\n      //! Number of vectors contained in this chunk.\r\n      size_t nb_elements;\r\n\r\n      //! Dimension of the vectors.\r\n      size_t data_dimension;\r\n\r\n      //! Internal accumulator.\r\n      //! Should live beyond the scope of update and init, as required by the merger.\r\n      data_t accumulator;\r\n\r\n      //! Signs stored for decreasing the number of updates\r\n      std::vector<bool> v_signs;\r\n      \r\n      // this is to send an update of the value of mu to one listener\r\n      // the connexion should be managed externally\r\n      typedef boost::function<void (data_t const*)> connector_accumulator_t;\r\n      connector_accumulator_t signal_acc;\r\n\r\n      typedef boost::function<void ()> connector_counter_t;\r\n      connector_counter_t signal_counter;\r\n\r\n      //! The matrix containing a copy of the data.\r\n      //! The vectors are stored per row in this matrix.\r\n      scalar_t *p_c_matrix;\r\n      \r\n      //! Padding for one line of the matrix\r\n      size_t data_padding;\r\n\r\n      //! \"Optimized\" inner product.\r\n      //! This one has the particularity to be more cache/memory bandwidth friendly. More efficient\r\n      //! implementations may be used, but it turned out that the memory bandwidth is saturated when\r\n      //! many threads are processing different data.\r\n      scalar_t inner_product(scalar_t const* p_mu, scalar_t const* current_line) const\r\n      {\r\n        scalar_t const * const current_line_end = current_line + data_dimension;\r\n\r\n        const int _64_elements = static_cast<int>(data_dimension >> 6);\r\n        scalar_t acc(0);\r\n\r\n        for(int j = 0; j < _64_elements; j++, current_line += 64, p_mu += 64)\r\n        {\r\n          for(int i = 0; i < 64; i++)\r\n          {\r\n            acc += current_line[i] * p_mu[i];\r\n          }\r\n        }\r\n        for(; current_line < current_line_end; current_line++, p_mu++)\r\n        {\r\n          acc += (*current_line) * (*p_mu);\r\n        }\r\n        return acc;\r\n      }\r\n\r\n      //! \"Optimized\" inner product\r\n      scalar_t inner_product(scalar_t const* p_mu, size_t element_index) const\r\n      {\r\n        return inner_product(p_mu, p_c_matrix + element_index * data_padding);\r\n      }\r\n\r\n\r\n\r\n    public:\r\n      asynchronous_chunks_processor() : nb_elements(0), data_dimension(0), p_c_matrix(0), data_padding(0)\r\n      {\r\n      }\r\n      \r\n      ~asynchronous_chunks_processor()\r\n      {\r\n        delete [] p_c_matrix;\r\n      }\r\n\r\n\r\n      //! Sets the data range\r\n      template <class container_iterator_t>\r\n      void set_data_range(container_iterator_t const &b, container_iterator_t const& e)\r\n      {\r\n        nb_elements = std::distance(b, e);\r\n        assert(nb_elements > 0);\r\n        v_signs.resize(nb_elements);\r\n\r\n        // aligning on 32 bytes = 1 << 5\r\n        data_padding = (data_dimension*sizeof(scalar_t) + (1<<5) - 1) & (~((1<<5)-1));\r\n        data_padding /= sizeof(scalar_t);\r\n        \r\n        delete [] p_c_matrix;\r\n        p_c_matrix = new scalar_t[data_padding*nb_elements];\r\n        \r\n        container_iterator_t bb(b);\r\n\r\n        scalar_t *current_line = p_c_matrix;\r\n        for(int line = 0; line < nb_elements; line ++, current_line += data_padding, ++bb)\r\n        {         \r\n          for(int column = 0; column < data_dimension; column++)\r\n          {\r\n            current_line[column] = (*bb)(column);\r\n          }\r\n        }\r\n        \r\n        signal_counter();\r\n      }\r\n\r\n      //! Sets the dimension of each vectors\r\n      //! @pre data_dimensions_ strictly positive\r\n      void set_data_dimensions(size_t data_dimensions_)\r\n      {\r\n        data_dimension = data_dimensions_;\r\n        assert(data_dimension > 0);\r\n      }\r\n\r\n      //! Returns the callback object that will be called to signal an updated accumulator.\r\n      connector_accumulator_t& connector_accumulator()\r\n      {\r\n        return signal_acc;\r\n      }\r\n\r\n      //! Returns the callback object that will be called to signal the end of the current computation.\r\n      connector_counter_t& connector_counter()\r\n      {\r\n        return signal_counter;\r\n      }\r\n\r\n\r\n      //! Centering the data in case it was not possible to do it beforehand\r\n      void data_centering_first_phase(size_t full_dataset_size)\r\n      {\r\n        scalar_t const * current_line = p_c_matrix;\r\n        accumulator = data_t(data_dimension, 0);\r\n        scalar_t * const p_acc_begin = &accumulator(0);\r\n        scalar_t const * const p_acc_end = p_acc_begin + data_dimension;\r\n        \r\n        \r\n        for(size_t current_element = 0; \r\n            current_element < nb_elements; \r\n            current_element++, current_line+= data_padding - data_dimension)\r\n        {\r\n          scalar_t * p_acc = p_acc_begin;\r\n          for(; p_acc < p_acc_end; p_acc++, current_line++)\r\n          {\r\n            *p_acc += *current_line;\r\n          }\r\n        }\r\n\r\n\r\n        for(scalar_t * p_acc = p_acc_begin; p_acc < p_acc_end; p_acc++)\r\n        {\r\n          *p_acc /= full_dataset_size;\r\n        }\r\n\r\n\r\n        // posts the new value to the listeners for the current dimension\r\n        signal_acc(&accumulator);\r\n        signal_counter();\r\n\r\n      }\r\n\r\n      //! Project the data onto the orthogonal subspace of the provided vector\r\n      void data_centering_second_phase(data_t const &mean_value)\r\n      {\r\n        scalar_t * current_line = p_c_matrix;\r\n        scalar_t const * const p_mean_begin = &mean_value(0);\r\n        scalar_t const * const p_mean_end = p_mean_begin + data_dimension;\r\n        \r\n        \r\n        for(size_t current_element = 0; \r\n            current_element < nb_elements; \r\n            current_element++, current_line+= data_padding - data_dimension)\r\n        {\r\n          const scalar_t * p_mean = p_mean_begin;\r\n          for(; p_mean < p_mean_end; p_mean++, current_line++)\r\n          {\r\n            *current_line -= *p_mean;\r\n          }\r\n        }\r\n\r\n        // posts the new value to the listeners for the current dimension\r\n        signal_counter();\r\n\r\n      }\r\n\r\n\r\n      //! PCA steps\r\n      void pca_accumulation(data_t const &mu)\r\n      {\r\n        accumulator = data_t(data_dimension, 0);\r\n        scalar_t const * const p_mu = &mu.data()[0];\r\n        scalar_t * const p_acc = &accumulator.data()[0];\r\n                \r\n        scalar_t const * current_line = p_c_matrix;\r\n\r\n        for(size_t s = 0; s < nb_elements; s++, current_line += data_padding)\r\n        {\r\n          const scalar_t inner_prod = inner_product(p_mu, current_line);\r\n          for(size_t d = 0; d < data_dimension; d++)\r\n          {\r\n            p_acc[d] += inner_prod * current_line[d];\r\n          }\r\n        }\r\n\r\n        // posts the new value to the listeners\r\n        signal_acc(&accumulator);\r\n        signal_counter();\r\n      }\r\n\r\n\r\n\r\n      //! Initialises the accumulator and the signs vector from the first mu\r\n      void initial_accumulation(data_t const &mu)\r\n      {\r\n        accumulator = data_t(data_dimension, 0);\r\n        std::vector<bool>::iterator itb(v_signs.begin());\r\n\r\n        scalar_t const * const p_mu = &mu.data()[0];\r\n        scalar_t * const p_acc = &accumulator.data()[0];\r\n\r\n        // first iteration, we store the signs\r\n        for(size_t s = 0; s < nb_elements; ++itb, s++)\r\n        {\r\n          bool sign = inner_product(p_mu, s) >= 0;\r\n\r\n          *itb = sign;\r\n          scalar_t *p(p_acc);\r\n          scalar_t const * current_line = p_c_matrix + s * data_padding;\r\n          scalar_t const * const current_line_end = current_line + data_dimension;\r\n          if(sign)\r\n          {\r\n            for(; current_line < current_line_end; ++current_line, ++p)\r\n            {\r\n              *p += *current_line;              \r\n            }\r\n          }\r\n          else \r\n          {\r\n            for(; current_line < current_line_end; ++current_line, ++p)\r\n            {\r\n              *p -= *current_line;              \r\n            }\r\n          }\r\n        }\r\n\r\n\r\n        // posts the new value to the listeners\r\n        signal_acc(&accumulator);\r\n        signal_counter();\r\n      }\r\n\r\n\r\n      //! Update the accumulator and the signs vector from an upated mu\r\n      void update_accumulation(data_t const& mu)\r\n      {\r\n        accumulator = data_t(data_dimension, 0);\r\n\r\n        bool update = false;\r\n\r\n        scalar_t const * const p_mu = &mu.data()[0];\r\n        scalar_t * const p_acc = &accumulator.data()[0];\r\n        scalar_t const * current_line = p_c_matrix;\r\n\r\n\r\n        std::vector<bool>::iterator itb(v_signs.begin());\r\n        for(size_t s = 0; s < nb_elements; ++itb, s++, current_line += data_padding)\r\n        {\r\n          bool sign = inner_product(p_mu, current_line) >= 0;\r\n          if(sign != *itb)\r\n          {\r\n            update = true;\r\n\r\n            // update the value of the accumulator according to sign change\r\n            *itb = sign;\r\n            \r\n            scalar_t *p(p_acc);\r\n            scalar_t const * current_line_copy= current_line;\r\n            scalar_t const * const current_line_end = current_line + data_dimension;\r\n            \r\n            if(sign)\r\n            {\r\n              for(; current_line_copy < current_line_end; ++current_line_copy, ++p)\r\n              {\r\n                *p += *current_line_copy;\r\n              }\r\n            }\r\n            else \r\n            {\r\n              for(; current_line_copy < current_line_end; ++current_line_copy, ++p)\r\n              {\r\n                *p -= *current_line_copy;\r\n              }\r\n            }\r\n          }\r\n        }\r\n\r\n        // posts the new value to the listeners\r\n        if(update)\r\n        {\r\n          scalar_t *p(p_acc);\r\n          for(size_t d = 0; d < data_dimension; d++, ++p)\r\n          {\r\n            *p *= 2;\r\n          }          \r\n          signal_acc(&accumulator);\r\n        }\r\n        signal_counter();\r\n      }\r\n\r\n      //! Project the data onto the orthogonal subspace of the provided vector\r\n\t    template <class vector_t>\r\n      void project_onto_orthogonal_subspace(vector_t const &mu)\r\n      {\r\n        // update of vectors in the orthogonal space, and update of the norms at the same time. \r\n\t\t    std::vector<typename vector_t::value_type> v(mu.begin(), mu.end()); // some issues with VC2015\r\n        scalar_t const * const p_mu = &v[0];\r\n        scalar_t * current_line = p_c_matrix;\r\n        \r\n        for(size_t line = 0; line < nb_elements; line ++, current_line += data_padding)\r\n        {\r\n          scalar_t const inner_prod = inner_product(p_mu, current_line);\r\n          for(int column = 0; column < data_dimension; column++)\r\n          {\r\n            current_line[column] -= inner_prod * p_mu[column];\r\n          }               \r\n        }\r\n  \r\n        signal_counter();\r\n      }\r\n\r\n    };\r\n\r\n\r\n    /*!@internal\r\n     * @brief Accumulation gathering the result of all workers.\r\n     *\r\n     * The purpose of this class is to add the computed accumulator of each thread to the final result\r\n     * which contains the sum of all accumulators. \r\n     *\r\n     */\r\n    struct asynchronous_results_merger : \r\n      details::threading::asynchronous_results_merger<\r\n        data_t,\r\n        details::threading::merger_addition<data_t>,\r\n        details::threading::initialisation_vector_specific_dimension<data_t>\r\n        >\r\n    {\r\n    private:\r\n      typedef details::threading::initialisation_vector_specific_dimension<data_t> data_init_type;\r\n      typedef details::threading::merger_addition<data_t> merger_type;\r\n      typedef details::threading::asynchronous_results_merger<data_t, merger_type, data_init_type> parent_type;\r\n    \r\n    public:\r\n\r\n      /*!Constructor\r\n       *\r\n       * @param dimension_ the number of dimensions of the vector to accumulate\r\n       */\r\n      asynchronous_results_merger(size_t data_dimension_) : parent_type(data_init_type(data_dimension_))\r\n      {}\r\n\r\n\r\n    };\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n  public:\r\n\r\n    /*!@brief Constructor\r\n     * \r\n     * @note By default the number of processors used for computation is set to 1.\r\n     * The maximum size of the chunks is \"infinite\": each chunk will receive in that case the size of the data\r\n     * divided by the number of running threads.\r\n     */\r\n    grassmann_pca() : \r\n      random_init_op(details::fVerySmallButStillComputable, details::fVeryBigButStillComputable), \r\n      nb_processors(1),\r\n      max_chunk_size(std::numeric_limits<size_t>::max()),\r\n      nb_steps_pca(3),\r\n      need_centering(false),\r\n      observer(0)\r\n    {}\r\n\r\n    //! Sets the observer of the algorithm. \r\n    //!\r\n    //! The lifetime of the observer is not managed by this class. Set to 0 to disable\r\n    //! observation.\r\n    bool set_observer(observer_t* observer_)\r\n    {\r\n      observer = observer_;\r\n      return true;\r\n    }\r\n\r\n    //! Sets the number of parallel tasks used for computing.\r\n    bool set_nb_processors(size_t nb_processors_)\r\n    {\r\n      nb_processors = nb_processors_;\r\n      return true;\r\n    }\r\n\r\n    /*!@brief Sets the maximum chunk size. \r\n     *\r\n     * By default, the chunk size is the size of the data divided by the number of processing threads.\r\n     * Lowering the chunk size should provid better granularity in the overall processing time at the end \r\n     * of the processing.\r\n     */\r\n    bool set_max_chunk_size(size_t chunk_size)\r\n    {\r\n      if(chunk_size == 0)\r\n      {\r\n        return false;\r\n      }\r\n      max_chunk_size = chunk_size;\r\n      return true;\r\n    }\r\n\r\n    //! Sets the number of iterations for the \"regular PCA\" algorithm. \r\n    bool set_nb_steps_pca(size_t nb_steps)\r\n    {\r\n      nb_steps_pca = nb_steps;\r\n      return true;\r\n    }\r\n\r\n    //! Sets the centering flags.\r\n    //!\r\n    //! If set to true, a centering will be performed before applying any computation (PCA and Grassmann averages). \r\n    bool set_centering(bool need_centering_)\r\n    {\r\n      need_centering = need_centering_;\r\n      return true;\r\n    }\r\n\r\n\r\n\r\n    /*!@brief Performs the computation of the eigen-vectors of the provided dataset.\r\n     *\r\n     * @tparam it_t an input random iterator. Each element pointed by the iterator should be convertible to data_t.\r\n     * @tparam it_o_basisvectors_t an output iterator for storing the computed eigenvalues. This iterator should model a forward output iterator.\r\n     *\r\n     * @param[in] max_iterations the maximum number of iterations in order to compute each eigen-vector. \r\n     * @param[in] max_dimension_to_compute the maximum number of eigen-vectors to compute.\r\n     * @param[in] it an (input) iterator pointing on the beginning of the data\r\n     * @param[in] ite an (input) iterator pointing on the end of the data\r\n     * @param[out] it_basisvectors an iterator on the beginning of the area where the computed eigen-vectors will be stored. The space should be at least @c max_dimension_to_compute.\r\n     * @param[in] initial_guess if provided, the initial vectors will be initialized to this value. The size of the pointed container should be at least @c max_dimension_to_compute.\r\n     *\r\n     * @returns true on success, false otherwise\r\n     * @pre \r\n     * - @c !(it >= ite)\r\n     * - all the vectors given by the iterators pair should be of the same size (no check is performed).\r\n     * - @c std::next(it_eigenvectors, i) should yield a valid iterator pointing on a valid storage area, for @c i in [0, max_dimension_to_compute[.\r\n     *\r\n     */\r\n    template <class it_t, class it_o_basisvectors_t>\r\n    bool batch_process(\r\n      const size_t max_iterations,\r\n      size_t max_dimension_to_compute,\r\n      it_t const it, \r\n      it_t const ite, \r\n      it_o_basisvectors_t it_basisvectors,\r\n      std::vector<data_t> const * initial_guess = 0)\r\n    {\r\n\r\n      // add some log information\r\n      if(it >= ite)\r\n      {\r\n        return false;\r\n      }\r\n\r\n      // preparing the thread pool, to avoid individual thread creation/deletion at each step.\r\n      // we perform the init here because it might take some time for the thread to really start.\r\n      boost::asio::io_service ioService;\r\n      boost::thread_group threadpool;\r\n\r\n\r\n      // in case of non clean exit (or even in case of clean one).\r\n      details::threading::safe_stop worker_lock_guard(ioService, threadpool);\r\n\r\n      // this is exactly the number of processors\r\n      boost::asio::io_service::work work(ioService);\r\n      for(int i = 0; i < nb_processors; i++)\r\n      {\r\n        threadpool.create_thread(boost::bind(&boost::asio::io_service::run, &ioService));\r\n      }\r\n\r\n      // contains the number of elements. In case the iterator is random access, could be deduced simply \r\n      // by a call to distance.\r\n      size_t size_data(std::distance(it, ite));\r\n\r\n      // size of the chunks.\r\n      const size_t chunks_size = std::min(max_chunk_size, static_cast<size_t>(ceil(double(size_data)/nb_processors)));\r\n      const size_t nb_chunks = (size_data + chunks_size - 1) / chunks_size;\r\n\r\n      // number of dimensions of the data vectors\r\n      const size_t number_of_dimensions = it->size();\r\n      \r\n\r\n      // the first element is used for the init guess because for dynamic std::vector like element, the size is needed.\r\n      data_t mu(initial_guess != 0 ? (*initial_guess)[0] : random_init_op(*it));\r\n      mu *= typename data_t::value_type(1./norm_op(mu)); // normalizing\r\n      assert(mu.size() == number_of_dimensions);\r\n\r\n      max_dimension_to_compute = std::min(max_dimension_to_compute, number_of_dimensions);\r\n      \r\n      size_t iterations = 0;\r\n\r\n\r\n      // preparing the ranges on which each processing thread will run.\r\n      // the number of objects can be much more than the current number of processors, in order to\r\n      // avoid waiting too long for a thread (better granularity) but involving a slight overhead in memory and\r\n      // processing at the synchronization point.\r\n      typedef asynchronous_chunks_processor async_processor_t;\r\n      std::vector<async_processor_t> v_individual_accumulators(nb_chunks);\r\n\r\n      asynchronous_results_merger async_merger(number_of_dimensions);\r\n      async_merger.init_notifications();\r\n\r\n      {\r\n        it_t it_current_begin(it);\r\n        for(int i = 0; i < nb_chunks; i++)\r\n        {\r\n          // setting the range\r\n          it_t it_current_end;\r\n          if(i == nb_chunks - 1)\r\n          {\r\n            // just in case the division giving the chunk has some rounding (the parenthesis are important\r\n            // otherwise it is a + followed by a -, which can be out of range after the first +)\r\n            it_current_end = it_current_begin + (size_data - chunks_size*(nb_chunks - 1));\r\n          }\r\n          else\r\n          {\r\n            it_current_end = it_current_begin + chunks_size;\r\n          }\r\n\r\n          async_processor_t &current_acc_object = v_individual_accumulators[i];\r\n\r\n          // attaching the update object callbacks\r\n          current_acc_object.connector_accumulator() = boost::bind(&asynchronous_results_merger::update, &async_merger, _1);\r\n          current_acc_object.connector_counter() = boost::bind(&asynchronous_results_merger::notify, &async_merger);\r\n\r\n          // updating the dimension of the problem\r\n          current_acc_object.set_data_dimensions(number_of_dimensions);\r\n\r\n          // pushing the asynchronous copy\r\n          ioService.post(\r\n            boost::bind(\r\n              &async_processor_t::template set_data_range<it_t>, \r\n              boost::ref(v_individual_accumulators[i]), \r\n              it_current_begin, it_current_end));\r\n\r\n          //bool b_result = current_acc_object.set_data_range(it_current_begin, it_current_end);\r\n          //if(!b_result)\r\n          //{\r\n          //  return b_result;\r\n          //}\r\n\r\n\r\n          // updating the next \r\n          it_current_begin = it_current_end;\r\n        }\r\n        \r\n        // waiting for completion (barrier)\r\n        async_merger.wait_notifications(v_individual_accumulators.size());\r\n        \r\n      }\r\n\r\n\r\n      // Centering the data if needed: \r\n      // - first run the accumulation and gather all results in a multithreaded manner\r\n      // - second center the data with the collected mean\r\n      if(need_centering)\r\n      {\r\n        // Computing the accumulation\r\n        async_merger.init();\r\n\r\n        for(int i = 0; i < v_individual_accumulators.size(); i++)\r\n        {\r\n          ioService.post(\r\n            boost::bind(\r\n              &async_processor_t::data_centering_first_phase, \r\n              boost::ref(v_individual_accumulators[i]),\r\n              size_data)); // size of the dataset to perform division and avoid doing accumulation over big numerical values\r\n        }\r\n\r\n        // waiting for completion (barrier)\r\n        async_merger.wait_notifications(v_individual_accumulators.size());\r\n\r\n        // gathering the accumulated, already divided by the size \r\n        data_t mean_vector = async_merger.get_merged_result();\r\n\r\n        //for (auto i = mean_vector.begin(); i != mean_vector.end(); ++i)\r\n        //{\r\n        //  std::cout << *i << ' ';\r\n        //}\r\n\r\n        // sending result to observer\r\n        if(observer)\r\n        {\r\n          observer->signal_mean(mean_vector);\r\n        }\r\n\r\n\r\n        // centering the data\r\n        async_merger.init();\r\n\r\n        for(int i = 0; i < v_individual_accumulators.size(); i++)\r\n        {\r\n          ioService.post(\r\n            boost::bind(\r\n              &async_processor_t::data_centering_second_phase, \r\n              boost::ref(v_individual_accumulators[i]),\r\n              boost::cref(mean_vector)\r\n              ));\r\n        }\r\n\r\n        // waiting for completion (barrier)\r\n        async_merger.wait_notifications(v_individual_accumulators.size());\r\n\r\n\r\n      }\r\n\r\n\r\n\r\n\r\n\r\n      // for each dimension\r\n      for(size_t current_subspace_index = 0; \r\n          current_subspace_index < max_dimension_to_compute; \r\n          current_subspace_index++, ++it_basisvectors)\r\n      {\r\n\r\n\r\n        // PCA like initial steps\r\n        if(nb_steps_pca)\r\n        {\r\n          for(size_t pca_it = 0; pca_it < nb_steps_pca; pca_it++)\r\n          {\r\n            // reseting the final accumulator\r\n            async_merger.init();\r\n\r\n            // pushing the initialisation of the mu and sign vectors to the pool\r\n            for(int i = 0; i < v_individual_accumulators.size(); i++)\r\n            {\r\n              ioService.post(\r\n                boost::bind(\r\n                  &async_processor_t::pca_accumulation, \r\n                  boost::ref(v_individual_accumulators[i]), \r\n                  boost::cref(mu)));\r\n            }\r\n\r\n            // waiting for completion (barrier)\r\n            async_merger.wait_notifications(v_individual_accumulators.size());\r\n\r\n            // gathering the first mu\r\n            mu = async_merger.get_merged_result();\r\n            \r\n            double norm_mu = norm_op(mu);\r\n            if(norm_mu < 1E-12)\r\n            {\r\n              if(observer)\r\n              {\r\n                std::ostringstream o;\r\n                o << \"The result of the PCA is null for subspace \" << current_subspace_index;\r\n                observer->log_error_message(o.str().c_str());\r\n              }\r\n              return false;\r\n            }            \r\n            \r\n            mu *= typename data_t::value_type(1./norm_mu);\r\n          }\r\n          \r\n          // sending result to observer\r\n          if(observer)\r\n          {\r\n            observer->signal_pca(mu, current_subspace_index);\r\n          }          \r\n        }\r\n\r\n\r\n\r\n        details::convergence_check<data_t> convergence_op(mu);\r\n\r\n        // reseting the accumulator and the notifications\r\n        async_merger.init();\r\n\r\n        // pushing the initialisation of the mu and sign vectors to the pool\r\n        for(int i = 0; i < v_individual_accumulators.size(); i++)\r\n        {\r\n          ioService.post(\r\n            boost::bind(\r\n              &async_processor_t::initial_accumulation, \r\n              boost::ref(v_individual_accumulators[i]), \r\n              boost::cref(mu)));\r\n        }\r\n\r\n        \r\n        // waiting for completion (barrier)\r\n        async_merger.wait_notifications(v_individual_accumulators.size());\r\n\r\n        // gathering the first mu\r\n        mu = async_merger.get_merged_result();\r\n        mu *= typename data_t::value_type(1./norm_op(mu));\r\n\r\n\r\n        // other iterations as usual\r\n        for(iterations = 1; !convergence_op(mu) && iterations < max_iterations; iterations++)\r\n        {\r\n\r\n          // reseting the final accumulator\r\n          async_merger.init_notifications();\r\n          //async_merger.init();\r\n          //async_merger.get_merged_result() = mu_no_norm;\r\n\r\n          // pushing the update of the mu (and signs)\r\n          for(int i = 0; i < v_individual_accumulators.size(); i++)\r\n          {\r\n            ioService.post(boost::bind(&async_processor_t::update_accumulation, boost::ref(v_individual_accumulators[i]), boost::cref(mu)));\r\n          }\r\n\r\n          // waiting for completion (barrier)\r\n          async_merger.wait_notifications(v_individual_accumulators.size());\r\n\r\n          // gathering the mus\r\n          //mu_no_norm = async_merger.get_merged_result();\r\n          mu = async_merger.get_merged_result();\r\n          mu *= typename data_t::value_type(1./norm_op(mu));\r\n\r\n          // sending result to observer\r\n          if(observer)\r\n          {\r\n            observer->signal_intermediate_result(mu, current_subspace_index, iterations);\r\n          }\r\n        }\r\n\r\n        // mu is the eigenvector of the current dimension, we store it in the output vector\r\n        *it_basisvectors = mu;\r\n\r\n        // sending result to observer\r\n        if(observer)\r\n        {\r\n          observer->signal_eigenvector(*it_basisvectors, current_subspace_index);\r\n        }   \r\n\r\n        // projection onto the orthogonal subspace\r\n        if(current_subspace_index < max_dimension_to_compute - 1)\r\n        {\r\n\r\n          async_merger.init_notifications();\r\n\r\n          // pushing the update of the mu (and signs)\r\n          for(int i = 0; i < v_individual_accumulators.size(); i++)\r\n          {\r\n            ioService.post(\r\n              boost::bind(\r\n                &async_processor_t::template project_onto_orthogonal_subspace<typename it_o_basisvectors_t::value_type>,\r\n                boost::ref(v_individual_accumulators[i]), \r\n                *it_basisvectors)); // this is not mu, since we are changing it before the process ends here\r\n          }\r\n\r\n          mu = initial_guess != 0 ? (*initial_guess)[current_subspace_index+1] : random_init_op(*it);\r\n\r\n          async_merger.wait_notifications(v_individual_accumulators.size());\r\n\r\n        }\r\n        \r\n      }\r\n\r\n\r\n      // stopping the pool is done in the destruction of worker_lock_guard\r\n\r\n\r\n\r\n      return true;\r\n    }\r\n  };\r\n\r\n}\r\n\r\n#endif /* GRASSMANN_AVERAGES_PCA_HPP__ */\r\n", "meta": {"hexsha": "6177672e8a91db548d34b37d95494735663eb14b", "size": 31507, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "2_learning/BG/TGA-PCA/include/grassmann_pca.hpp", "max_stars_repo_name": "BGU-CS-VIL/JA-POLS", "max_stars_repo_head_hexsha": "0ee34ec0c8c7d7fdfc0c5b1c85b2bb6632cc3c41", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2020-03-16T08:52:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T09:05:47.000Z", "max_issues_repo_path": "2_learning/BG/TGA-PCA/include/grassmann_pca.hpp", "max_issues_repo_name": "BGU-CS-VIL/JA-POLS", "max_issues_repo_head_hexsha": "0ee34ec0c8c7d7fdfc0c5b1c85b2bb6632cc3c41", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-08-24T17:28:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-24T17:28:19.000Z", "max_forks_repo_path": "2_learning/BG/TGA-PCA/include/grassmann_pca.hpp", "max_forks_repo_name": "BGU-CS-VIL/JA-POLS", "max_forks_repo_head_hexsha": "0ee34ec0c8c7d7fdfc0c5b1c85b2bb6632cc3c41", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-04T20:54:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-04T20:54:24.000Z", "avg_line_length": 35.5609480813, "max_line_length": 183, "alphanum_fraction": 0.6023423366, "num_tokens": 6942, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239836484144, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.45315689412419297}}
{"text": "//\n// Copyright \u00a9 2017 Arm Ltd. All rights reserved.\n// SPDX-License-Identifier: MIT\n//\n\n#include <boost/test/unit_test.hpp>\n#include \"ParserFlatbuffersSerializeFixture.hpp\"\n#include <armnnDeserializer/IDeserializer.hpp>\n\n#include <string>\n\nBOOST_AUTO_TEST_SUITE(Deserializer)\n\nstruct BatchNormalizationFixture : public ParserFlatbuffersSerializeFixture\n{\n    explicit BatchNormalizationFixture(const std::string &inputShape,\n                                       const std::string &outputShape,\n                                       const std::string &meanShape,\n                                       const std::string &varianceShape,\n                                       const std::string &offsetShape,\n                                       const std::string &scaleShape,\n                                       const std::string &dataType,\n                                       const std::string &dataLayout)\n    {\n        m_JsonString = R\"(\n    {\n        inputIds: [0],\n        outputIds: [2],\n        layers: [\n           {\n            layer_type: \"InputLayer\",\n            layer: {\n                base: {\n                    layerBindingId: 0,\n                    base: {\n                        index: 0,\n                        layerName: \"InputLayer\",\n                        layerType: \"Input\",\n                        inputSlots: [{\n                            index: 0,\n                            connection: {sourceLayerIndex:0, outputSlotIndex:0 },\n                            }],\n                        outputSlots: [{\n                            index: 0,\n                            tensorInfo: {\n                                dimensions: )\" + inputShape + R\"(,\n                                dataType: \")\" + dataType + R\"(\",\n                                quantizationScale: 0.5,\n                                quantizationOffset: 0\n                                },\n                            }]\n                        },\n                    }\n                },\n            },\n        {\n        layer_type: \"BatchNormalizationLayer\",\n        layer : {\n            base: {\n                index:1,\n                layerName: \"BatchNormalizationLayer\",\n                layerType: \"BatchNormalization\",\n                inputSlots: [{\n                        index: 0,\n                        connection: {sourceLayerIndex:0, outputSlotIndex:0 },\n                   }],\n                outputSlots: [{\n                    index: 0,\n                    tensorInfo: {\n                        dimensions: )\" + outputShape + R\"(,\n                        dataType: \")\" + dataType + R\"(\"\n                    },\n                    }],\n                },\n            descriptor: {\n                eps: 0.0010000000475,\n                dataLayout: \")\" + dataLayout + R\"(\"\n                },\n            mean: {\n                info: {\n                         dimensions: )\" + meanShape + R\"(,\n                         dataType: \")\" + dataType + R\"(\"\n                     },\n                data_type: IntData,\n                data: {\n                    data: [1084227584],\n                    }\n                },\n            variance: {\n                info: {\n                         dimensions: )\" + varianceShape + R\"(,\n                         dataType: \")\" + dataType + R\"(\"\n                     },\n               data_type: IntData,\n                data: {\n                    data: [1073741824],\n                    }\n                },\n            beta: {\n                info: {\n                         dimensions: )\" + offsetShape + R\"(,\n                         dataType: \")\" + dataType + R\"(\"\n                     },\n                data_type: IntData,\n                data: {\n                    data: [0],\n                    }\n                },\n            gamma: {\n                info: {\n                         dimensions: )\" + scaleShape + R\"(,\n                         dataType: \")\" + dataType + R\"(\"\n                     },\n                data_type: IntData,\n                data: {\n                    data: [1065353216],\n                    }\n                },\n            },\n        },\n        {\n        layer_type: \"OutputLayer\",\n        layer: {\n            base:{\n                layerBindingId: 0,\n                base: {\n                    index: 2,\n                    layerName: \"OutputLayer\",\n                    layerType: \"Output\",\n                    inputSlots: [{\n                        index: 0,\n                        connection: {sourceLayerIndex:1, outputSlotIndex:0 },\n                    }],\n                    outputSlots: [ {\n                        index: 0,\n                        tensorInfo: {\n                            dimensions: )\" + outputShape + R\"(,\n                            dataType: \")\" + dataType + R\"(\"\n                        },\n                    }],\n                }\n            }},\n        }]\n    }\n)\";\n        Setup();\n    }\n};\n\nstruct BatchNormFixture : BatchNormalizationFixture\n{\n    BatchNormFixture():BatchNormalizationFixture(\"[ 1, 3, 3, 1 ]\",\n                                                 \"[ 1, 3, 3, 1 ]\",\n                                                 \"[ 1 ]\",\n                                                 \"[ 1 ]\",\n                                                 \"[ 1 ]\",\n                                                 \"[ 1 ]\",\n                                                 \"Float32\",\n                                                 \"NHWC\"){}\n};\n\nBOOST_FIXTURE_TEST_CASE(BatchNormalizationFloat32, BatchNormFixture)\n{\n    RunTest<4, armnn::DataType::Float32>(0,\n                                         {{\"InputLayer\", { 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f, 9.0f }}},\n                                         {{\"OutputLayer\",{ -2.8277204f, -2.12079024f, -1.4138602f,\n                                           -0.7069301f,  0.0f,         0.7069301f,\n                                           1.4138602f,  2.12079024f,  2.8277204f }}});\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "ba3f01ee5fb616465d4844a843d8e524f5f25aad", "size": 6013, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/armnnDeserializer/test/DeserializeBatchNormalization.cpp", "max_stars_repo_name": "tuanhe/armnn", "max_stars_repo_head_hexsha": "8a4bd6671d0106dfb788b8c9019f2f9646770f8d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-03T23:46:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-03T23:46:08.000Z", "max_issues_repo_path": "src/armnnDeserializer/test/DeserializeBatchNormalization.cpp", "max_issues_repo_name": "tuanhe/armnn", "max_issues_repo_head_hexsha": "8a4bd6671d0106dfb788b8c9019f2f9646770f8d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/armnnDeserializer/test/DeserializeBatchNormalization.cpp", "max_forks_repo_name": "tuanhe/armnn", "max_forks_repo_head_hexsha": "8a4bd6671d0106dfb788b8c9019f2f9646770f8d", "max_forks_repo_licenses": ["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.9593023256, "max_line_length": 116, "alphanum_fraction": 0.3282887078, "num_tokens": 1096, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.727975460709318, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.453135118404484}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_EULER_FUNCTIONS_SCALAR_SIGNGAM_HPP_INCLUDED\n#define NT2_EULER_FUNCTIONS_SCALAR_SIGNGAM_HPP_INCLUDED\n\n#include <nt2/euler/functions/signgam.hpp>\n#include <nt2/include/functions/scalar/is_nan.hpp>\n#include <nt2/include/functions/scalar/is_lez.hpp>\n#include <nt2/include/functions/scalar/is_flint.hpp>\n#include <nt2/include/functions/scalar/is_odd.hpp>\n#include <nt2/include/functions/scalar/floor.hpp>\n#include <nt2/include/functions/scalar/is_inf.hpp>\n#include <nt2/include/constants/one.hpp>\n#include <nt2/include/constants/two.hpp>\n#include <nt2/include/constants/nan.hpp>\n#include <boost/dispatch/meta/as_floating.hpp>\n\nnamespace nt2 { namespace ext\n{\n  NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::signgam_, tag::cpu_\n                            , (A0)\n                            , (scalar_< fundamental_<A0> >)\n                            )\n  {\n    typedef typename boost::dispatch::meta::as_floating<A0>::type result_type;\n    NT2_FUNCTOR_CALL(1)\n    {\n      typedef result_type type;\n      bool isinfa0 =  nt2::is_inf(a0);\n      if (nt2::is_lez(a0))\n      {\n        if (nt2::is_flint(a0)||isinfa0)\n          return nt2::Nan<type>();\n        else\n          return nt2::One<type>()-bool(nt2::is_odd(nt2::floor(a0)))*nt2::Two<A0>();\n      }\n      else if (nt2::is_nan(a0)) return a0;\n      return nt2::One<type>();\n    }\n  };\n} }\n\n\n#endif\n", "meta": {"hexsha": "b686a3db587021e2601bfc34fe4374279b594180", "size": 1852, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/euler/include/nt2/euler/functions/scalar/signgam.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/euler/include/nt2/euler/functions/scalar/signgam.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/euler/include/nt2/euler/functions/scalar/signgam.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": 36.3137254902, "max_line_length": 83, "alphanum_fraction": 0.5890928726, "num_tokens": 464, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754607093178, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.45313511840448395}}
{"text": "#ifndef STAN_MATH_PRIM_PROB_HMM_LATENT_RNG_HPP\n#define STAN_MATH_PRIM_PROB_HMM_LATENT_RNG_HPP\n\n#include <stan/math/prim/core.hpp>\n#include <stan/math/prim/meta.hpp>\n#include <stan/math/prim/err/hmm_check.hpp>\n#include <stan/math/prim/fun/Eigen.hpp>\n#include <boost/random.hpp>\n#include <vector>\n\nnamespace stan {\nnamespace math {\n\n/**\n * For a hidden Markov model with observation y, hidden state x,\n * and parameters theta, generate samples from the posterior distribution\n * of the hidden states, x.\n * In this setting, the hidden states are discrete\n * and takes values over the finite space {1, ..., K}.\n * log_omegas is a matrix of observational densities, where\n * the (i, j)th entry corresponds to the density of the ith observation, y_i,\n * given x_i = j.\n * The transition matrix Gamma is such that the (i, j)th entry is the\n * probability that x_n = j given x_{n - 1} = i. The rows of Gamma are\n * simplexes.\n *\n * @tparam T_omega type of the log likelihood matrix\n * @tparam T_Gamma type of the transition matrix\n * @tparam T_rho type of the initial guess vector\n * @param[in] log_omegas log matrix of observational densities.\n * @param[in] Gamma transition density between hidden states.\n * @param[in] rho initial state\n * @param[in] rng random number generator\n * @return sample from the posterior distribution of the hidden states.\n * @throw `std::invalid_argument` if Gamma is not square, when we have\n *         at least one transition, or if the size of rho is not the\n *         number of rows of log_omegas.\n * @throw `std::domain_error` if rho is not a simplex and of the rows\n *         of Gamma are not a simplex (when there is at least one transition).\n */\ntemplate <typename T_omega, typename T_Gamma, typename T_rho, class RNG,\n          require_all_eigen_t<T_omega, T_Gamma>* = nullptr,\n          require_eigen_col_vector_t<T_rho>* = nullptr>\ninline std::vector<int> hmm_latent_rng(const T_omega& log_omegas,\n                                       const T_Gamma& Gamma, const T_rho& rho,\n                                       RNG& rng) {\n  int n_states = log_omegas.rows();\n  int n_transitions = log_omegas.cols() - 1;\n\n  Eigen::MatrixXd omegas = value_of(log_omegas).array().exp();\n  ref_type_t<decltype(value_of(rho))> rho_dbl = value_of(rho);\n  ref_type_t<decltype(value_of(Gamma))> Gamma_dbl = value_of(Gamma);\n  hmm_check(log_omegas, Gamma_dbl, rho_dbl, \"hmm_latent_rng\");\n\n  Eigen::MatrixXd alphas(n_states, n_transitions + 1);\n  alphas.col(0) = omegas.col(0).cwiseProduct(rho_dbl);\n  alphas.col(0) /= alphas.col(0).maxCoeff();\n\n  for (int n = 0; n < n_transitions; ++n) {\n    alphas.col(n + 1)\n        = omegas.col(n + 1).cwiseProduct(Gamma_dbl.transpose() * alphas.col(n));\n    alphas.col(n + 1) /= alphas.col(n + 1).maxCoeff();\n  }\n\n  Eigen::VectorXd beta = Eigen::VectorXd::Ones(n_states);\n\n  // sample the last hidden state\n  std::vector<int> hidden_states(n_transitions + 1);\n  std::vector<double> probs(n_states);\n  Eigen::Map<Eigen::VectorXd> probs_vec(probs.data(), n_states);\n  probs_vec = alphas.col(n_transitions) / alphas.col(n_transitions).sum();\n  boost::random::discrete_distribution<> cat_hidden(probs);\n  hidden_states[n_transitions] = cat_hidden(rng) + stan::error_index::value;\n\n  for (int n = n_transitions; n-- > 0;) {\n    // Sample the nth hidden state conditional on (n + 1)st hidden state.\n    // Subtract error_index in order to use C++ index.\n    int last_hs = hidden_states[n + 1] - stan::error_index::value;\n\n    probs_vec = alphas.col(n).cwiseProduct(Gamma_dbl.col(last_hs))\n                * beta(last_hs) * omegas(last_hs, n + 1);\n\n    probs_vec /= probs_vec.sum();\n\n    // discrete_distribution produces samples in [0, K), so\n    // we need to add 1 to generate over [1, K).\n    boost::random::discrete_distribution<> cat_hidden(probs);\n    hidden_states[n] = cat_hidden(rng) + stan::error_index::value;\n\n    // update backwards state\n    beta = Gamma_dbl * (omegas.col(n + 1).cwiseProduct(beta));\n    beta /= beta.maxCoeff();\n  }\n\n  return hidden_states;\n}\n\n}  // namespace math\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "24037e37df31636934a9c892c7e785c8f963bb2c", "size": 4074, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/prim/prob/hmm_latent_rng.hpp", "max_stars_repo_name": "LaudateCorpus1/math", "max_stars_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-14T14:33:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-14T14:33:37.000Z", "max_issues_repo_path": "stan/math/prim/prob/hmm_latent_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/hmm_latent_rng.hpp", "max_forks_repo_name": "LaudateCorpus1/math", "max_forks_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-05-10T12:55:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-10T12:55:07.000Z", "avg_line_length": 40.3366336634, "max_line_length": 80, "alphanum_fraction": 0.6912125675, "num_tokens": 1104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.6224593382055109, "lm_q1q2_score": 0.45313511615587443}}
{"text": "// Author: Sudeep Pillai (spillai@csail.mit.edu)\n// License: BSD\n// Last modified: Sep 14, 2014\n\n// Wrapper for most external modules\n#include <boost/python.hpp>\n#include <boost/python/suite/indexing/vector_indexing_suite.hpp>\n#include <exception>\n\n// Opencv includes\n#include <opencv2/opencv.hpp>\n\n// np_opencv_converter\n#include \"np_opencv_converter.hpp\"\n#include \"fast_guided_filter.hpp\"\n\nnamespace py = boost::python;\n\n\n\nstatic cv::Mat boxfilter(const cv::Mat &I, int r)\n{\n    cv::Mat result;\n    cv::blur(I, result, cv::Size(r, r));\n    return result;\n}\n\nstatic cv::Mat convertTo(const cv::Mat &mat, int depth)\n{\n    if (mat.depth() == depth)\n        return mat;\n\n    cv::Mat result;\n    mat.convertTo(result, depth);\n    return result;\n}\n\nclass FastGuidedFilterImpl\n{\npublic:\n    FastGuidedFilterImpl(int r, double eps,int s):r(r),eps(eps),s(s){}\n    virtual ~FastGuidedFilterImpl() {}\n\n    cv::Mat filter(const cv::Mat &p, int depth);\n\nprotected:\n    int Idepth,r,s;\n    double eps;\n\nprivate:\n    virtual cv::Mat filterSingleChannel(const cv::Mat &p) const = 0;\n};\n\nclass FastGuidedFilterMono : public FastGuidedFilterImpl\n{\npublic:\n    FastGuidedFilterMono(const cv::Mat &I, int r, double eps,int s);\n\nprivate:\n    virtual cv::Mat filterSingleChannel(const cv::Mat &p) const;\n\nprivate:\n\n    cv::Mat I,origI, mean_I, var_I;\n};\n\nclass FastGuidedFilterColor : public FastGuidedFilterImpl\n{\npublic:\n    FastGuidedFilterColor(const cv::Mat &I, int r, double eps,int s);\n\nprivate:\n    virtual cv::Mat filterSingleChannel(const cv::Mat &p) const;\n\nprivate:\n    std::vector<cv::Mat> origIchannels,Ichannels;\n    cv::Mat mean_I_r, mean_I_g, mean_I_b;\n    cv::Mat invrr, invrg, invrb, invgg, invgb, invbb;\n};\n\n\ncv::Mat FastGuidedFilterImpl::filter(const cv::Mat &p, int depth)\n{\n    cv::Mat p2 = convertTo(p, Idepth);\n    cv::resize(p2 ,p2,cv::Size(p2.cols/s,p2.rows/s),0,0,CV_INTER_NN);\n    cv::Mat result;\n    if (p.channels() == 1)\n    {\n        result = filterSingleChannel(p2);\n    }\n    else\n    {\n        std::vector<cv::Mat> pc;\n        cv::split(p2, pc);\n\n        for (std::size_t i = 0; i < pc.size(); ++i)\n            pc[i] = filterSingleChannel(pc[i]);\n\n        cv::merge(pc, result);\n    }\n\n    return convertTo(result, depth == -1 ? p.depth() : depth);\n}\n\nFastGuidedFilterMono::FastGuidedFilterMono(const cv::Mat &origI, int r, double eps,int s):FastGuidedFilterImpl(r,eps,s)\n{\n\n    if (origI.depth() == CV_32F || origI.depth() == CV_64F)\n        this->origI = origI.clone();\n    else\n        this->origI = convertTo(origI, CV_32F);\n    cv::resize(this->origI ,I,cv::Size(this->origI.cols/s,this->origI.rows/s),0,0,CV_INTER_NN);\n    Idepth = I.depth();\n\n    mean_I = boxfilter(I, r);\n    cv::Mat mean_II = boxfilter(I.mul(I), r);\n    var_I = mean_II - mean_I.mul(mean_I);\n}\n\ncv::Mat FastGuidedFilterMono::filterSingleChannel(const cv::Mat &p) const\n{\n\n    cv::Mat mean_p = boxfilter(p, r);\n    cv::Mat mean_Ip = boxfilter(I.mul(p), r);\n    cv::Mat cov_Ip = mean_Ip - mean_I.mul(mean_p); // this is the covariance of (I, p) in each local patch.\n\n    cv::Mat a = cov_Ip / (var_I + eps);\n    cv::Mat b = mean_p - a.mul(mean_I);\n\n    cv::Mat mean_a = boxfilter(a, r);\n    cv::Mat mean_b = boxfilter(b, r);\n    cv::resize(mean_a ,mean_a,cv::Size(origI.cols,origI.rows),0,0,CV_INTER_LINEAR);\n    cv::resize(mean_b ,mean_b,cv::Size(origI.cols,origI.rows),0,0,CV_INTER_LINEAR);\n    return mean_a.mul(origI) + mean_b;\n}\n\nFastGuidedFilterColor::FastGuidedFilterColor(const cv::Mat &origI, int r, double eps, int s):FastGuidedFilterImpl(r,eps,s)// : r(r), eps(eps)\n{\n\n    cv::Mat I;\n    if (origI.depth() == CV_32F || origI.depth() == CV_64F)\n        I = origI.clone();\n    else\n        I = convertTo(origI, CV_32F);\n    Idepth = I.depth();\n\n    cv::split(I, origIchannels);\n    cv::resize(I,I,cv::Size(I.cols/s,I.rows/s),0,0,CV_INTER_NN);\n    cv::split(I, Ichannels);\n\n    mean_I_r = boxfilter(Ichannels[0], r);\n    mean_I_g = boxfilter(Ichannels[1], r);\n    mean_I_b = boxfilter(Ichannels[2], r);\n\n    // variance of I in each local patch: the matrix Sigma.\n    // Note the variance in each local patch is a 3x3 symmetric matrix:\n    //           rr, rg, rb\n    //   Sigma = rg, gg, gb\n    //           rb, gb, bb\n    cv::Mat var_I_rr = boxfilter(Ichannels[0].mul(Ichannels[0]), r) - mean_I_r.mul(mean_I_r) + eps;\n    cv::Mat var_I_rg = boxfilter(Ichannels[0].mul(Ichannels[1]), r) - mean_I_r.mul(mean_I_g);\n    cv::Mat var_I_rb = boxfilter(Ichannels[0].mul(Ichannels[2]), r) - mean_I_r.mul(mean_I_b);\n    cv::Mat var_I_gg = boxfilter(Ichannels[1].mul(Ichannels[1]), r) - mean_I_g.mul(mean_I_g) + eps;\n    cv::Mat var_I_gb = boxfilter(Ichannels[1].mul(Ichannels[2]), r) - mean_I_g.mul(mean_I_b);\n    cv::Mat var_I_bb = boxfilter(Ichannels[2].mul(Ichannels[2]), r) - mean_I_b.mul(mean_I_b) + eps;\n\n    // Inverse of Sigma + eps * I\n    invrr = var_I_gg.mul(var_I_bb) - var_I_gb.mul(var_I_gb);\n    invrg = var_I_gb.mul(var_I_rb) - var_I_rg.mul(var_I_bb);\n    invrb = var_I_rg.mul(var_I_gb) - var_I_gg.mul(var_I_rb);\n    invgg = var_I_rr.mul(var_I_bb) - var_I_rb.mul(var_I_rb);\n    invgb = var_I_rb.mul(var_I_rg) - var_I_rr.mul(var_I_gb);\n    invbb = var_I_rr.mul(var_I_gg) - var_I_rg.mul(var_I_rg);\n\n    cv::Mat covDet = invrr.mul(var_I_rr) + invrg.mul(var_I_rg) + invrb.mul(var_I_rb);\n\n    invrr /= covDet;\n    invrg /= covDet;\n    invrb /= covDet;\n    invgg /= covDet;\n    invgb /= covDet;\n    invbb /= covDet;\n}\n\ncv::Mat FastGuidedFilterColor::filterSingleChannel(const cv::Mat &p) const\n{\n    cv::Mat mean_p = boxfilter(p, r);\n\n    cv::Mat mean_Ip_r = boxfilter(Ichannels[0].mul(p), r);\n    cv::Mat mean_Ip_g = boxfilter(Ichannels[1].mul(p), r);\n    cv::Mat mean_Ip_b = boxfilter(Ichannels[2].mul(p), r);\n\n    // covariance of (I, p) in each local patch.\n    cv::Mat cov_Ip_r = mean_Ip_r - mean_I_r.mul(mean_p);\n    cv::Mat cov_Ip_g = mean_Ip_g - mean_I_g.mul(mean_p);\n    cv::Mat cov_Ip_b = mean_Ip_b - mean_I_b.mul(mean_p);\n\n    cv::Mat a_r = invrr.mul(cov_Ip_r) + invrg.mul(cov_Ip_g) + invrb.mul(cov_Ip_b);\n    cv::Mat a_g = invrg.mul(cov_Ip_r) + invgg.mul(cov_Ip_g) + invgb.mul(cov_Ip_b);\n    cv::Mat a_b = invrb.mul(cov_Ip_r) + invgb.mul(cov_Ip_g) + invbb.mul(cov_Ip_b);\n\n    cv::Mat b = mean_p - a_r.mul(mean_I_r) - a_g.mul(mean_I_g) - a_b.mul(mean_I_b);\n\n    cv::Mat mean_a_r = boxfilter(a_r, r);\n    cv::Mat mean_a_g = boxfilter(a_g, r);\n    cv::Mat mean_a_b = boxfilter(a_b, r);\n    cv::Mat mean_b = boxfilter(b, r);\n    cv::resize(mean_a_r ,mean_a_r,cv::Size(origIchannels[0].cols,origIchannels[0].rows),0,0,CV_INTER_LINEAR);\n    cv::resize(mean_a_g ,mean_a_g,cv::Size(origIchannels[1].cols,origIchannels[1].rows),0,0,CV_INTER_LINEAR);\n    cv::resize(mean_a_b ,mean_a_b,cv::Size(origIchannels[2].cols,origIchannels[2].rows),0,0,CV_INTER_LINEAR);\n    cv::resize(mean_b,mean_b,cv::Size(origIchannels[2].cols,origIchannels[2].rows),0,0,CV_INTER_LINEAR);\n    return (mean_a_r.mul(origIchannels[0]) +mean_a_g.mul(origIchannels[1]) +mean_a_b.mul(origIchannels[2]) + mean_b);\n\n}\n\n\nFastGuidedFilter::FastGuidedFilter(const cv::Mat &I, int r, double eps,int s)\n{\n    CV_Assert(I.channels() == 1 || I.channels() == 3);\n\n    if (I.channels() == 1)\n        impl_ = new FastGuidedFilterMono(I, 2 * (r/s) + 1, eps,s);\n    else\n        impl_ = new FastGuidedFilterColor(I, 2 * (r/s) + 1, eps,s);\n}\n\nFastGuidedFilter::~FastGuidedFilter()\n{\n    delete impl_;\n}\n\ncv::Mat FastGuidedFilter::filter(const cv::Mat &p, int depth) const\n{\n    return impl_->filter(p, depth);\n}\n\ncv::Mat fastGuidedFilter(const cv::Mat& I, const cv::Mat& p, int r, double eps, int s,int depth)\n{\n    return FastGuidedFilter(I, r, eps,s).filter(p, depth);\n}\n\ncv::Mat test_np_mat(const cv::Mat& in) {\n  std::cerr << \"in: \" << in << std::endl;\n  std::cerr << \"sz: \" << in.size() << std::endl;\n  return in.clone();\n}\n\ncv::Mat test_with_args(const cv::Mat_<float>& in, const int& var1 = 1,\n                       const double& var2 = 10.0, const std::string& name=std::string(\"test_name\")) {\n  std::cerr << \"in: \" << in << std::endl;\n  std::cerr << \"sz: \" << in.size() << std::endl;\n  std::cerr << \"Returning transpose\" << std::endl;\n  return in.t();\n}\n\nclass GenericWrapper {\n public: \n  GenericWrapper(const int& _var_int = 1, const float& _var_float = 1.f,\n                 const double& _var_double = 1.d, const std::string& _var_string = std::string(\"test_string\"))\n      : var_int(_var_int), var_float(_var_float), var_double(_var_double), var_string(_var_string)\n  {\n\n  }\n\n  cv::Mat process(const cv::Mat& in) {\n    std::cerr << \"in: \" << in << std::endl;\n    std::cerr << \"sz: \" << in.size() << std::endl;\n    std::cerr << \"Returning transpose\" << std::endl;\n    return in.t();\n  }\n\n private:\n  int var_int;\n  float var_float;\n  double var_double;\n  std::string var_string;  \n};\n\n// Wrap a few functions and classes for testing purposes\nnamespace fs { namespace python {\n\nBOOST_PYTHON_MODULE(fast_guided_filter)\n{\n  // Main types export\n  fs::python::init_and_export_converters();\n  py::scope scope = py::scope();\n\n  // Basic test\n  py::def(\"test_np_mat\", &test_np_mat);\n  py::def(\"fastGuidedFilter\",&fastGuidedFilter);\n\n  // With arguments\n  py::def(\"test_with_args\", &test_with_args,\n          (py::arg(\"src\"), py::arg(\"var1\")=1, py::arg(\"var2\")=10.0, py::arg(\"name\")=\"test_name\"));\n\n  // Class\n  py::class_<GenericWrapper>(\"GenericWrapper\")\n      .def(py::init<py::optional<int, float, double, std::string> >(\n          (py::arg(\"var_int\")=1, py::arg(\"var_float\")=1.f, py::arg(\"var_double\")=1.d,\n           py::arg(\"var_string\")=std::string(\"test\"))))\n      .def(\"process\", &GenericWrapper::process)\n      ;\n}\n\n} // namespace fs\n} // namespace python\n\n\n\n", "meta": {"hexsha": "ee7104ecff5b75e7d37c4eda4b9fb822f42dfd87", "size": 9632, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/fast_guided_filter.cpp", "max_stars_repo_name": "syhao/faster_guided_filter", "max_stars_repo_head_hexsha": "0cb16896b464d8fa1ffd3ad7c76d66b9485f63c4", "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": "tests/fast_guided_filter.cpp", "max_issues_repo_name": "syhao/faster_guided_filter", "max_issues_repo_head_hexsha": "0cb16896b464d8fa1ffd3ad7c76d66b9485f63c4", "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": "tests/fast_guided_filter.cpp", "max_forks_repo_name": "syhao/faster_guided_filter", "max_forks_repo_head_hexsha": "0cb16896b464d8fa1ffd3ad7c76d66b9485f63c4", "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.0709677419, "max_line_length": 141, "alphanum_fraction": 0.6447259136, "num_tokens": 3083, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4531351110573846}}
{"text": "/**\n * \\file      accelerometer-gyrometer.hpp\n * \\author    Mehdi Benallegue\n * \\date       2013\n * \\brief     Implements the accelerometer-gyrometer inertial measuremen\n *\n *\n */\n\n#ifndef SIMULATIONACCELEROMETERGYROMETERSENSORHPP\n#define SIMULATIONACCELEROMETERGYROMETERSENSORHPP\n\n#include <boost/assert.hpp>\n#include <Eigen/Core>\n\n#include <state-observation/api.h>\n#include <state-observation/sensors-simulation/algebraic-sensor.hpp>\n#include <state-observation/sensors-simulation/algorithm/linear-acceleration.hpp>\n#include <state-observation/sensors-simulation/algorithm/rotation-velocity.hpp>\n\nnamespace stateObservation\n{\n/**\n * \\class  AccelerometerGyrometer\n * \\brief  Implements the accelerometer-gyrometer measurements\n *\n *\n *\n * \\details\n *\n */\n\nclass STATE_OBSERVATION_DLLAPI AccelerometerGyrometer : public AlgebraicSensor,\n                                                        protected algorithm::LinearAcceleration,\n                                                        protected algorithm::RotationVelocity\n{\npublic:\n  AccelerometerGyrometer();\n\n  /// Virtual destructor\n  virtual ~AccelerometerGyrometer() {}\n\n  void setMatrixMode(bool matrixMode);\n\nprotected:\n  /// Gets the state vector Size\n  virtual Index getStateSize_() const;\n\n  /// Gets the measurements vector size\n  virtual Index getMeasurementSize_() const;\n\n  virtual Vector computeNoiselessMeasurement_();\n\n  Matrix3 r_;\n  Vector3 acc_;\n  Vector3 omega_;\n  Vector output_;\n\n  bool matrixMode_;\n\n  static const Index stateSize_ = 10;\n  static const Index stateSizeMatrix_ = 15;\n\n  static const Index measurementSize_ = 6;\n\n  Index currentStateSize_;\n};\n\n} // namespace stateObservation\n\n#endif // SIMULATIONACCELEROMETERGYROMETERSENSORHPP\n", "meta": {"hexsha": "d68e25cf850d53dfac85aa2f3dd06c64f524d714", "size": 1725, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/state-observation/sensors-simulation/accelerometer-gyrometer.hpp", "max_stars_repo_name": "mmurooka/state-observation", "max_stars_repo_head_hexsha": "4a6b8eb6fa841cf706a074132fb24b50e8534e35", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2018-11-01T16:10:48.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-09T00:03:46.000Z", "max_issues_repo_path": "include/state-observation/sensors-simulation/accelerometer-gyrometer.hpp", "max_issues_repo_name": "mmurooka/state-observation", "max_issues_repo_head_hexsha": "4a6b8eb6fa841cf706a074132fb24b50e8534e35", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2019-10-18T09:06:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-26T04:22:09.000Z", "max_forks_repo_path": "include/state-observation/sensors-simulation/accelerometer-gyrometer.hpp", "max_forks_repo_name": "mmurooka/state-observation", "max_forks_repo_head_hexsha": "4a6b8eb6fa841cf706a074132fb24b50e8534e35", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2018-06-19T09:00:17.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-11T06:14:51.000Z", "avg_line_length": 23.9583333333, "max_line_length": 96, "alphanum_fraction": 0.7211594203, "num_tokens": 381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4531351110573846}}
{"text": "#define BOOST_TEST_MODULE KDTree2Tests\n#include <boost/test/included/unit_test.hpp>\n#include <iterator>\n#include <algorithm>\n#include <sstream>\n#include \"kdtree.h\"\n\n// template<typename T>\n// std::string tos(const T& s) {\n//     std::ostringstream ss;\n//     ss << s;\n//     return ss.str();\n// }\n\npoint<> rctest[] {{2, 3}, {5, 4}, {9, 6}, {4, 7}, {8, 1}, {7, 2}};\npoint<int, 3> rct3[] {{0, 0, 0}, {7, 0, 0}, {0, 7, 0}, {0, 0, 7}, {4, 4, 4}, {7, 7, 7}};\n\nstruct KDFixture {\n    KDFixture() {\n        t.build(std::begin(rctest), std::end(rctest));\n    }\n    kdtree<> t;    \n    const point<> rc_expected {8, 1};\n    const point<> rc_reference { 9, 2 };\n};\n\nstruct KD3Fixture {\n    KD3Fixture() {\n        t3.build(std::begin(rct3), std::end(rct3));\n    }\n    kdtree<int, 3> t3;\n    const kdtree<int, 3>::point_type rc_reference { 4, 4, 4 };\n};\n\nBOOST_FIXTURE_TEST_SUITE(KDSuitem, KDFixture) \n    \n    BOOST_AUTO_TEST_CASE(BasicOperations)\n    {\n        point<> a { -3, 0 };\n        point<> b { 0, 0 };\n        BOOST_CHECK_EQUAL(9, a.distance_norm(b));\n        BOOST_CHECK_EQUAL(9, b.distance_norm(a));\n        point<> c{3, 0};\n        BOOST_CHECK_EQUAL(c, point<>(b - a));\n    }\n\n    BOOST_AUTO_TEST_CASE(EqualTEst)\n    {\n        point<> a { 5, 4 };\n        point<> b { 5, 4 };\n        point<> c { 0, 4 };\n        point<> d { 5, 0 };\n        point<> e { 1, 1 };\n        BOOST_CHECK(a == a);\n        BOOST_CHECK(a == b);\n        BOOST_CHECK(! (a == c));\n        BOOST_CHECK(! (a == d));\n        BOOST_CHECK(! (a == e));\n    }\n\n    BOOST_AUTO_TEST_CASE(RosettaCode)\n    {\n        auto r = t.nearest_neighbours(rc_reference);\n        BOOST_TEST(r.results_.size() == 1);\n        auto const& r0 = r.results_[0];\n        BOOST_TEST(*r0.p_ == rc_expected);\n    }\n\n    BOOST_AUTO_TEST_CASE(RC_max_params)\n    {\n        // 1: (8; 1) Distance 1.41421\n        // 2: (7; 2) Distance 2\n        // 3: (9; 6) Distance 4\n        // 4: (5; 4) Distance 4.47214\n        // 5: (4; 7) Distance 7.07107\n        // 6: (2; 3) Distance 7.07107\n        //  nodes visited: 6\n        auto r1 = t.nearest_neighbours(rc_reference);\n        BOOST_CHECK_EQUAL(1, r1.results_.size());\n\n        auto r2 = t.nearest_neighbours(rc_reference, 4);\n        // BOOST_TEST_MESSAGE(\"Result: \" << r2 );\n        BOOST_CHECK_EQUAL(4, r2.results_.size());\n        \n        auto r3 = t.nearest_neighbours(rc_reference, 4, 5.0);\n        // BOOST_TEST_MESSAGE(\"Result: \" << r3 );\n        BOOST_CHECK_EQUAL(4, r3.results_.size());\n        auto m = std::max_element(std::begin(r3.results_), std::end(r3.results_), kdtree<>::search_def::cmp);\n        // BOOST_TEST_MESSAGE ( \"Max \" << m->distance() );\n        BOOST_CHECK(m->distance() <= 5.0);\n\n        auto r4 = t.nearest_neighbours(rc_reference, 4, 4.0);\n        // BOOST_TEST_MESSAGE(\"Result: \" << r4 );\n        BOOST_CHECK_EQUAL(3, r4.results_.size());\n        auto m4 = std::max_element(std::begin(r4.results_), std::end(r4.results_), kdtree<>::search_def::cmp);\n        // BOOST_TEST_MESSAGE ( \"Max \" << *m4->p_ );\n        // BOOST_TEST_MESSAGE ( \"Max \" << m4->distance() );\n        BOOST_CHECK(m4->distance() <= 4.0);\n           \n    }\n\nBOOST_AUTO_TEST_SUITE_END()\n\nBOOST_FIXTURE_TEST_SUITE(Dim3Test, KD3Fixture)\n\n    BOOST_AUTO_TEST_CASE(T3Nearest) \n    {\n        auto r1 = t3.nearest_neighbours(rc_reference);\n        BOOST_CHECK_EQUAL(1, r1.results_.size());\n        point<int, 3> r { 4, 4, 4 };\n        BOOST_CHECK_EQUAL(*r1.results_[0].p_, r);\n    }\n\nBOOST_AUTO_TEST_SUITE_END()\n\n", "meta": {"hexsha": "dafc3b892d0cac296dd433335e31327a5e04d4cf", "size": 3489, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "experiments/kdtree_test.cpp", "max_stars_repo_name": "noeld/cpp", "max_stars_repo_head_hexsha": "572a145f8c79f7292b7b0611822ed34792df4e9c", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "experiments/kdtree_test.cpp", "max_issues_repo_name": "noeld/cpp", "max_issues_repo_head_hexsha": "572a145f8c79f7292b7b0611822ed34792df4e9c", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "experiments/kdtree_test.cpp", "max_forks_repo_name": "noeld/cpp", "max_forks_repo_head_hexsha": "572a145f8c79f7292b7b0611822ed34792df4e9c", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.0775862069, "max_line_length": 110, "alphanum_fraction": 0.5563198624, "num_tokens": 1109, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059775, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.4531351110573846}}
{"text": "#include \"algorithm/scc.hpp\"\n#include \"tool/container/forward_star_graph_factory.hpp\"\n\n#include <algorithm>\n#include <utility>\n#include <vector>\n\n#include <iostream>\n\nusing namespace nepomuk;\n// make sure we get a new main function here\n#define BOOST_TEST_MAIN\n#include <boost/test/unit_test.hpp>\n\nBOOST_AUTO_TEST_CASE(compute_scc)\n{\n    tool::container::ForwardStarGraphFactory factory;\n    //\n    // 0 - 1 -> 4 -> 6\n    // |   |    |\n    // 3 - 2    5\n    auto graph = factory.allocate(7, 12);\n    // 0\n    factory.add_node(graph);\n    factory.add_edge(graph, 1);\n    factory.add_edge(graph, 3);\n    // 1\n    factory.add_node(graph);\n    factory.add_edge(graph, 0);\n    factory.add_edge(graph, 2);\n    factory.add_edge(graph, 4);\n    // 2\n    factory.add_node(graph);\n    factory.add_edge(graph, 1);\n    factory.add_edge(graph, 3);\n    // 3\n    factory.add_node(graph);\n    factory.add_edge(graph, 0);\n    factory.add_edge(graph, 2);\n    // 4\n    factory.add_node(graph);\n    factory.add_edge(graph, 6);\n    factory.add_edge(graph, 5);\n    // 5\n    factory.add_node(graph);\n    factory.add_edge(graph, 4);\n    // 6\n    factory.add_node(graph);\n\n    BOOST_CHECK(factory.valid());\n\n    auto components = algorithm::computeSCC(graph);\n    BOOST_CHECK(components.size() == 3);\n    BOOST_CHECK_EQUAL(components.component(0), components.component(1));\n    BOOST_CHECK_EQUAL(components.component(0), components.component(2));\n    BOOST_CHECK_EQUAL(components.component(0), components.component(3));\n    BOOST_CHECK_EQUAL(components.component(4), components.component(5));\n    BOOST_CHECK(components.component(0) != components.component(4));\n    BOOST_CHECK(components.component(4) != components.component(6));\n    BOOST_CHECK(components.component(0) != components.component(6));\n\n    std::vector<std::size_t> sizes;\n    for (std::size_t i = 0; i < components.size(); ++i)\n        sizes.push_back(components.size(i));\n\n    if (components.size() == 3)\n    {\n        std::sort(sizes.begin(), sizes.end());\n        BOOST_CHECK_EQUAL(sizes[0], 1);\n        BOOST_CHECK_EQUAL(sizes[1], 2);\n        BOOST_CHECK_EQUAL(sizes[2], 4);\n    }\n}\n", "meta": {"hexsha": "c1908e34dd17b881c289f5f546ec87c604ab912a", "size": 2126, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/algorithm/scc.cc", "max_stars_repo_name": "mapbox/nepomuk", "max_stars_repo_head_hexsha": "8771482edb9b16bb0f5a152c15681c57eb3bb6b6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2017-05-12T11:52:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-06T06:05:08.000Z", "max_issues_repo_path": "test/algorithm/scc.cc", "max_issues_repo_name": "mapbox/nepomuk", "max_issues_repo_head_hexsha": "8771482edb9b16bb0f5a152c15681c57eb3bb6b6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 49.0, "max_issues_repo_issues_event_min_datetime": "2017-05-11T16:13:58.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-13T11:19:17.000Z", "max_forks_repo_path": "test/algorithm/scc.cc", "max_forks_repo_name": "mapbox/nepomuk", "max_forks_repo_head_hexsha": "8771482edb9b16bb0f5a152c15681c57eb3bb6b6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-11-19T12:04:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-06T06:14:25.000Z", "avg_line_length": 28.7297297297, "max_line_length": 72, "alphanum_fraction": 0.6599247413, "num_tokens": 542, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.4531351110573845}}
{"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#pragma once\n\n#include <Eigen/Geometry>\n\n#include \"kindr/common/common.hpp\"\n#include \"kindr/common/assert_macros_eigen.hpp\"\n#include \"kindr/quaternions/QuaternionBase.hpp\"\n\nnamespace kindr {\n\n\ntemplate<typename PrimType_>\nclass UnitQuaternion;\n\n//! Implementation of a Quaternion based on Eigen::Quaternion\n/*!\n * The Hamiltonian convention is used, where\n * Q = w + x*i + y*j + z*k and i*i=j*j=k*k=ijk=-1.\n *\n * The following two typedefs are provided for convenience:\n *   - QuaternionF for float\n *   - QuaternionD for double\n * \\ingroup quaternions\n * \\see rm::UnitQuaternion for an implementation of a unit quaternion\n * \\see rm::rotations::RotationQuaternion for quaternions that represent a rotation\n */\ntemplate<typename PrimType_>\nclass Quaternion : public QuaternionBase<Quaternion<PrimType_>>, private Eigen::Quaternion<PrimType_> {\n private:\n  typedef Eigen::Quaternion<PrimType_> Base;\n public:\n  //! the implementation type, i.e., Eigen::Quaternion<>\n  typedef Base Implementation;\n  //! the scalar type, i.e., the type of the coefficients\n  typedef PrimType_ Scalar;\n  //! the imaginary type, i.e., Eigen::Quaternion<>\n  typedef Eigen::Matrix<PrimType_,3,1> Imaginary;\n  //! quaternion as 4x1 matrix: [w; x; y; z]\n  typedef Eigen::Matrix<PrimType_,4,1> Vector4;\n\n  //! Default constructor creates a quaternion with all coefficients equal to zero\n  Quaternion()\n    : Base(Implementation(0,0,0,0)) {\n  }\n\n  /*! \\brief Constructor using four scalars.\n   *  \\param w     first entry of the quaternion\n   *  \\param x     second entry of the quaternion\n   *  \\param y     third entry of the quaternion\n   *  \\param z     fourth entry of the quaternion\n   */\n  Quaternion(Scalar w, Scalar x, Scalar y, Scalar z)\n    : Base(w,x,y,z) {\n  }\n\n  /*! \\brief Constructor using real and imaginary part.\n   *  \\param real   real part (PrimType_)\n   *  \\param imag   imaginary part (Eigen::Matrix<PrimType_,3,1>)\n   */\n  Quaternion(Scalar real, const Imaginary& imag)\n    : Base(real,imag(0),imag(1),imag(2)) {\n  }\n\n  /*! \\brief Constructor using Eigen::Matrix<PrimType_,4,1>.\n   *  \\param other   Eigen::Matrix<PrimType_,4,1>\n   */\n  Quaternion(const Vector4& vector4)\n    : Base(vector4(0),vector4(1),vector4(2),vector4(3)) {\n  }\n\n  // create from Eigen::Quaternion\n  explicit Quaternion(const Base& other)\n    : Base(other) {\n  }\n\n  /*! \\returns the inverse of the quaternion\n    */\n  Quaternion inverted() const {\n    return Quaternion(Implementation::inverse());\n  }\n\n  /*! \\inverts the quaternion\n    */\n  Quaternion& invert() {\n    *this = Quaternion(Implementation::inverse());\n    return *this;\n  }\n\n  /*! \\returns the conjugate of the quaternion\n    */\n  Quaternion conjugated() const {\n    return Quaternion(Implementation::conjugate());\n  }\n\n  /*! \\conjugates the quaternion\n    */\n  Quaternion& conjugate() {\n    *this = Quaternion(Implementation::conjugate());\n    return *this;\n  }\n\n  Quaternion& operator =(const Quaternion<PrimType_>& other) {\n    this->w() = other.w();\n    this->x() = other.x();\n    this->y() = other.y();\n    this->z() = other.z();\n    return *this;\n  }\n\n  Quaternion& operator =(const UnitQuaternion<PrimType_>& other) {\n    *this = Quaternion(other.toImplementation());\n    return *this;\n  }\n\n//  bool operator ==(const Quaternion<PrimType_>& other) {\n//\t  return this->isEqual(other);\n//  }\n\n  template<typename PrimTypeIn_>\n  Quaternion& operator ()(const Quaternion<PrimTypeIn_>& other) {\n//\t*this = other.template cast<PrimType_>();\n\tthis->w() = static_cast<PrimType_>(other.w());\n\tthis->x() = static_cast<PrimType_>(other.x());\n\tthis->y() = static_cast<PrimType_>(other.y());\n\tthis->z() = static_cast<PrimType_>(other.z());\n\treturn *this;\n  }\n\n  template<typename PrimTypeIn_>\n  Quaternion& operator ()(const UnitQuaternion<PrimTypeIn_>& other) {\n//\t*this = other.uq.template cast<PrimType_>(); // uq is private\n\tthis->w() = static_cast<PrimType_>(other.w());\n\tthis->x() = static_cast<PrimType_>(other.x());\n\tthis->y() = static_cast<PrimType_>(other.y());\n\tthis->z() = static_cast<PrimType_>(other.z());\n\treturn *this;\n  }\n\n  inline Implementation& toImplementation() {\n    return static_cast<Implementation&>(*this);\n  }\n  inline const Implementation& toImplementation() const {\n    return static_cast<const Implementation&>(*this);\n  }\n\n  using QuaternionBase<Quaternion<PrimType_>>::operator==;\n  using QuaternionBase<Quaternion<PrimType_>>::operator*;\n\n  inline Scalar w() const {\n    return Base::w();\n  }\n\n  inline Scalar x() const {\n    return Base::x();\n  }\n\n  inline Scalar y() const {\n    return Base::y();\n  }\n\n  inline Scalar z() const {\n    return Base::z();\n  }\n\n  inline Scalar& w() { // todo: attention: no assertion for unitquaternions!\n    return Base::w();\n  }\n\n  inline Scalar& x() {\n    return Base::x();\n  }\n\n  inline Scalar& y() {\n    return Base::y();\n  }\n\n  inline Scalar& z() {\n    return Base::z();\n  }\n\n  inline Scalar real() const {\n    return Base::w();\n  }\n\n  inline Imaginary imaginary() const {\n    return Imaginary(Base::x(),Base::y(),Base::z());\n  }\n\n  inline Vector4 vector() const {\n    Vector4 vector4;\n    vector4 << w(), x(), y(), z();\n    return vector4;\n  }\n\n  inline Scalar norm() const {\n    return Base::norm();\n  }\n\n  Quaternion normalized() const {\n    return Quaternion(this->Base::normalized());\n  }\n\n  Quaternion& normalize() {\n\t  this->Base::normalize();\n\t  return *this;\n  }\n\n  Quaternion& setZero() {\n    this->w() = Scalar(0.0);\n    this->x() = Scalar(0.0);\n    this->y() = Scalar(0.0);\n    this->z() = Scalar(0.0);\n    return *this;\n  }\n\n  /*! \\brief Get zero element.\n   *  \\returns zero element\n   */\n  static Quaternion Zero() {\n    return Quaternion();\n  }\n\n  UnitQuaternion<PrimType_> toUnitQuaternion() const {\n    return UnitQuaternion<PrimType_>(this->Base::normalized());\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    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    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    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    return Qright;\n  }\n};\n\n//! Quaternion using double\ntypedef Quaternion<double> QuaternionD;\n//! Quaternion using float\ntypedef Quaternion<float> QuaternionF;\n\n//! Implementation of a unit quaternion based on Eigen::Quaternion\n/*! The Hamiltonian convention is used, where\n * Q = w + x*i + y*j + z*k and i*i=j*j=k*k=ijk=-1.\n *\n * The following two typedefs are provided for convenience:\n *   - UnitQuaternionF for float\n *   - UnitQuaternionD for double\n * \\ingroup quaternions\n * \\see rm::Quaternion for an implementation of a generic quaternion\n * \\see rm::rotations::RotationQuaternion for quaternions that represent a rotation\n */\ntemplate<typename PrimType_>\nclass UnitQuaternion : public UnitQuaternionBase<UnitQuaternion<PrimType_>> {\n private:\n  Quaternion<PrimType_> unitQuternion_;\n  typedef UnitQuaternionBase<UnitQuaternion<PrimType_>> Base;\n public:\n  //! the implementation type, i.e., Eigen::Quaternion<>\n  typedef typename Quaternion<PrimType_>::Implementation Implementation;\n  //! the scalar type, i.e., the type of the coefficients\n  typedef PrimType_ Scalar;\n  //! the imaginary type, i.e., Eigen::Quaternion<>\n  typedef Eigen::Matrix<PrimType_,3,1> Imaginary;\n  //! quaternion as 4x1 matrix: [w; x; y; z]\n  typedef Eigen::Matrix<PrimType_,4,1> Vector4;\n\n  //! Default Constructor initializes the unit quaternion to identity\n  UnitQuaternion()\n    : unitQuternion_(Implementation::Identity()) {\n  }\n\n  //! Constructor to create unit quaternion from coefficients\n  /*! Q = w + x*i + y*j + z*k\n   * \\param   w   scalar\n   * \\param   x   vector index 1\n   * \\param   y   vector index 2\n   * \\param   z   vector index 3\n   */\n  UnitQuaternion(Scalar w, Scalar x, Scalar y, Scalar z)\n    : unitQuternion_(w,x,y,z) {\n    KINDR_ASSERT_SCALAR_NEAR_DBG(std::runtime_error, norm(), static_cast<Scalar>(1.0), static_cast<Scalar>(1e-2), \"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  UnitQuaternion(Scalar real, const Imaginary& imag)\n    : unitQuternion_(real,imag) {\n    KINDR_ASSERT_SCALAR_NEAR_DBG(std::runtime_error, norm(), static_cast<Scalar>(1.0), static_cast<Scalar>(1e-2), \"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  UnitQuaternion(const Vector4& vector4)\n    : unitQuternion_(vector4(0),vector4(1),vector4(2),vector4(3)) {\n    KINDR_ASSERT_SCALAR_NEAR_DBG(std::runtime_error, norm(), static_cast<Scalar>(1.0), static_cast<Scalar>(1e-2), \"Input quaternion has not unit length.\");\n  }\n\n  //! Constructor to create unit quaternion from Quaternion\n  explicit UnitQuaternion(const Quaternion<PrimType_>& other)\n    : unitQuternion_(other.toImplementation()) {\n    KINDR_ASSERT_SCALAR_NEAR_DBG(std::runtime_error, norm(), static_cast<Scalar>(1.0), static_cast<Scalar>(1e-2), \"Input quaternion has not unit length.\");\n  }\n\n  //! Constructor to create unit quaternion from Eigen::Quaternion\n  /*!\n   * \\param other Eigen::Quaternion\n   */\n  explicit UnitQuaternion(const Implementation& other)\n    : unitQuternion_(other) {\n    KINDR_ASSERT_SCALAR_NEAR_DBG(std::runtime_error, norm(), static_cast<Scalar>(1.0), static_cast<Scalar>(1e-2), \"Input quaternion has not unit length.\");\n  }\n\n  UnitQuaternion& operator =(const UnitQuaternion<PrimType_>& other) {\n\t    this->w() = other.w();\n\t    this->x() = other.x();\n\t    this->y() = other.y();\n\t    this->z() = other.z();\n\t    return *this;\n  }\n\n  template<typename PrimTypeIn_>\n  UnitQuaternion& operator ()(const UnitQuaternion<PrimTypeIn_>& other) {\n//\tuq = other.uq;\n\tthis->w() = static_cast<PrimType_>(other.w());\n\tthis->x() = static_cast<PrimType_>(other.x());\n\tthis->y() = static_cast<PrimType_>(other.y());\n\tthis->z() = static_cast<PrimType_>(other.z());\n\treturn *this;\n  }\n\n  template<typename PrimTypeIn_>\n  UnitQuaternion& operator ()(const Quaternion<PrimTypeIn_>& other) {\n//\t\t*this = (UnitQuaternion)quat;\n//\tuq = other.template cast<PrimType_>();\n\tthis->w() = static_cast<PrimType_>(other.w());\n\tthis->x() = static_cast<PrimType_>(other.x());\n\tthis->y() = static_cast<PrimType_>(other.y());\n\tthis->z() = static_cast<PrimType_>(other.z());\n    KINDR_ASSERT_SCALAR_NEAR_DBG(std::runtime_error, norm(), static_cast<Scalar>(1.0), 1e-2, \"Input quaternion has not unit length.\");\n\treturn *this;\n  }\n\n//  UnitQuaternion<PrimType_> operator *(const UnitQuaternion<PrimType_>& other) {\n//\t  return UnitQuaternion<PrimType_>(this->uq * other.uq);\n//  }\n//\n//  Quaternion<PrimType_> operator *(const Quaternion<PrimType_>& other) {\n//\t  return Quaternion<PrimType_>(this->uq * other);\n//  }\n//  bool operator ==(const UnitQuaternion<PrimType_>& other) {\n//\t  return this->uq == other.uq;\n//  }\n//\n//  bool operator ==(const Quaternion<PrimType_>& other) {\n//\t  return this->uq == other.uq;\n//  }\n\n  inline Scalar w() const {\n    return unitQuternion_.w();\n  }\n\n  inline Scalar x() const {\n    return unitQuternion_.x();\n  }\n\n  inline Scalar y() const {\n    return unitQuternion_.y();\n  }\n\n  inline Scalar z() const {\n    return unitQuternion_.z();\n  }\n\n  inline Scalar& w() { // todo: attention: no assertion for unitquaternions!\n    return unitQuternion_.w();\n  }\n\n  inline Scalar& x() {\n    return unitQuternion_.x();\n  }\n\n  inline Scalar& y() {\n    return unitQuternion_.y();\n  }\n\n  inline Scalar& z() {\n    return unitQuternion_.z();\n  }\n\n  inline Scalar real() const {\n    return unitQuternion_.w();\n  }\n\n  inline Imaginary imaginary() const {\n    return Imaginary(unitQuternion_.x(),unitQuternion_.y(),unitQuternion_.z());\n  }\n\n  inline Vector4 vector() const {\n    Vector4 vector4;\n    vector4 << w(), x(), y(), z();\n    return vector4;\n  }\n\n//  using Base::operator*;\n\n//  using UnitQuaternionBase<UnitQuaternion<PrimType_>>::conjugate;\n\n  /*! \\returns the conjugate of the quaternion\n    */\n  UnitQuaternion conjugated() const {\n    return UnitQuaternion(unitQuternion_.conjugated());\n  }\n\n  /*! \\conjugates the quaternion\n    */\n  UnitQuaternion& conjugate() {\n    unitQuternion_.conjugate();\n    return *this;\n  }\n\n//  using Base::inverted;\n//  using Base::invert;\n\n//  /*! \\returns the inverse of the quaternion which is the conjugate for unit quaternions\n//    */\n//  UnitQuaternion inverse() const {\n//    return UnitQuaternion(Base::conjugate());\n//  }\n\n  Scalar norm() const {\n    return unitQuternion_.norm();\n  }\n\n  /*! \\brief Sets unit quaternion to identity.\n   *  \\returns reference\n   */\n  UnitQuaternion& setIdentity() {\n    this->w() = Scalar(0.0);\n    this->x() = Scalar(0.0);\n    this->y() = Scalar(0.0);\n    this->z() = Scalar(0.0);\n    return *this;\n  }\n\n  /*! \\brief Get identity unit quaternion.\n   *  \\returns identity unit quaternion\n   */\n  static UnitQuaternion Identity() {\n    return UnitQuaternion(Implementation::Identity());\n  }\n\n  const Implementation& toImplementation() const {\n    return unitQuternion_.toImplementation();\n  }\n\n  Implementation& toImplementation() {\n    return unitQuternion_.toImplementation();\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    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    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    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    return Qright;\n  }\n};\n\n//! Unit quaternion using double\ntypedef UnitQuaternion<double> UnitQuaternionD;\n//! Unit quaternion using float\ntypedef UnitQuaternion<float> UnitQuaternionF;\n\n\n\n} // namespace kindr\n\n", "meta": {"hexsha": "293ebd8e6535f8402e6bed9f2a7220c1b5b89d87", "size": 17888, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/kindr/quaternions/Quaternion.hpp", "max_stars_repo_name": "flieger19/kindr", "max_stars_repo_head_hexsha": "9f754517870b770d1e678a7c741c688c2081ec68", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/kindr/quaternions/Quaternion.hpp", "max_issues_repo_name": "flieger19/kindr", "max_issues_repo_head_hexsha": "9f754517870b770d1e678a7c741c688c2081ec68", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/kindr/quaternions/Quaternion.hpp", "max_forks_repo_name": "flieger19/kindr", "max_forks_repo_head_hexsha": "9f754517870b770d1e678a7c741c688c2081ec68", "max_forks_repo_licenses": ["BSD-3-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.7619047619, "max_line_length": 155, "alphanum_fraction": 0.6541256708, "num_tokens": 5033, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754371026367, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.453135103710285}}
{"text": "#pragma once\n\n#include <fmt/format.h>\n\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/graphviz.hpp>\n#include <boost/graph/small_world_generator.hpp>\n#include <boost/random/linear_congruential.hpp>\n\nusing Graph = boost::adjacency_list<>;\nusing SWGen = boost::small_world_iterator<boost::minstd_rand, Graph>;\n\ninline auto make_graph(unsigned size)\n{\n  boost::minstd_rand gen;\n  Graph              graph{SWGen(gen, size, 6, 0.03), SWGen(),\n              static_cast<boost::adjacency_list<>::vertices_size_type>(size)};\n  return graph;\n}\n\ninline void write_graph(Graph const& graph)\n{\n  write_graphviz(std::cout, graph);\n}\n", "meta": {"hexsha": "c9e13d8bcffa2ee8f7fc631e16903767c0e6fc4d", "size": 636, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/CausalGraph.hpp", "max_stars_repo_name": "acgetchell/causal-sets-explorer", "max_stars_repo_head_hexsha": "329f2151014df1b8c38c6f6ba807aea2cb32b7e8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-05-21T01:33:11.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-16T00:13:23.000Z", "max_issues_repo_path": "include/CausalGraph.hpp", "max_issues_repo_name": "acgetchell/causal-sets-explorer", "max_issues_repo_head_hexsha": "329f2151014df1b8c38c6f6ba807aea2cb32b7e8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2017-05-31T11:22:40.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-06T06:06:58.000Z", "max_forks_repo_path": "include/CausalGraph.hpp", "max_forks_repo_name": "acgetchell/causal-sets-explorer", "max_forks_repo_head_hexsha": "329f2151014df1b8c38c6f6ba807aea2cb32b7e8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-05-30T13:40:14.000Z", "max_forks_repo_forks_event_max_datetime": "2017-05-30T13:40:14.000Z", "avg_line_length": 25.44, "max_line_length": 78, "alphanum_fraction": 0.7264150943, "num_tokens": 155, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754371026367, "lm_q2_score": 0.6224593241981982, "lm_q1q2_score": 0.45313509861179513}}
{"text": "#pragma once\n\n#include <Eigen/Eigen>\n#include <cmath>\n#include <vector>\n\n#include \"root_finder.hpp\"\n\n// Polynomial order and trajectory dimension are fixed here\ntypedef Eigen::Matrix<double, 3, 6> CoefficientMat;\ntypedef Eigen::Matrix<double, 3, 5> VelCoefficientMat;\ntypedef Eigen::Matrix<double, 3, 4> AccCoefficientMat;\n\nnamespace mpc_utils{\nclass Piece {\n private:\n  double duration;\n  CoefficientMat coeffMat;\n\n public:\n  Piece() = default;\n\n  Piece(double dur, const CoefficientMat &cMat)\n      : duration(dur), coeffMat(cMat) {}\n\n  inline int getDim() const {\n    return 3;\n  }\n\n  inline int getOrder() const {\n    return 5;\n  }\n\n  inline double getDuration() const {\n    return duration;\n  }\n\n  inline const CoefficientMat &getCoeffMat() const {\n    return coeffMat;\n  }\n\n  inline VelCoefficientMat getVelCoeffMat() const {\n    VelCoefficientMat velCoeffMat;\n    int n = 1;\n    for (int i = 4; i >= 0; i--) {\n      velCoeffMat.col(i) = n * coeffMat.col(i);\n      n++;\n    }\n    return velCoeffMat;\n  }\n\n  inline Eigen::Vector3d getPos(const double &t) const {\n    Eigen::Vector3d pos(0.0, 0.0, 0.0);\n    double tn = 1.0;\n    for (int i = 5; i >= 0; i--) {\n      pos += tn * coeffMat.col(i);\n      tn *= t;\n    }\n    return pos;\n  }\n\n  inline Eigen::Vector3d getVel(const double &t) const {\n    Eigen::Vector3d vel(0.0, 0.0, 0.0);\n    double tn = 1.0;\n    int n = 1;\n    for (int i = 4; i >= 0; i--) {\n      vel += n * tn * coeffMat.col(i);\n      tn *= t;\n      n++;\n    }\n    return vel;\n  }\n\n  inline Eigen::Vector3d getAcc(const double &t) const {\n    Eigen::Vector3d acc(0.0, 0.0, 0.0);\n    double tn = 1.0;\n    int m = 1;\n    int n = 2;\n    for (int i = 3; i >= 0; i--) {\n      acc += m * n * tn * coeffMat.col(i);\n      tn *= t;\n      m++;\n      n++;\n    }\n    return acc;\n  }\n\n  inline Eigen::Vector3d getJer(const double &t) const {\n    Eigen::Vector3d jer(0.0, 0.0, 0.0);\n    double tn = 1.0;\n    int l = 1;\n    int m = 2;\n    int n = 3;\n    for (int i = 2; i >= 0; i--) {\n      jer += l * m * n * tn * coeffMat.col(i);\n      tn *= t;\n      l++;\n      m++;\n      n++;\n    }\n    return jer;\n  }\n\n  inline CoefficientMat normalizePosCoeffMat() const {\n    CoefficientMat nPosCoeffsMat;\n    double t = 1.0;\n    for (int i = 5; i >= 0; i--) {\n      nPosCoeffsMat.col(i) = coeffMat.col(i) * t;\n      t *= duration;\n    }\n    return nPosCoeffsMat;\n  }\n\n  inline VelCoefficientMat normalizeVelCoeffMat() const {\n    VelCoefficientMat nVelCoeffMat;\n    int n = 1;\n    double t = duration;\n    for (int i = 4; i >= 0; i--) {\n      nVelCoeffMat.col(i) = n * coeffMat.col(i) * t;\n      t *= duration;\n      n++;\n    }\n    return nVelCoeffMat;\n  }\n\n  inline AccCoefficientMat normalizeAccCoeffMat() const {\n    AccCoefficientMat nAccCoeffMat;\n    int n = 2;\n    int m = 1;\n    double t = duration * duration;\n    for (int i = 3; i >= 0; i--) {\n      nAccCoeffMat.col(i) = n * m * coeffMat.col(i) * t;\n      n++;\n      m++;\n      t *= duration;\n    }\n    return nAccCoeffMat;\n  }\n\n  inline double getMaxVelRate() const {\n    Eigen::MatrixXd nVelCoeffMat = normalizeVelCoeffMat();\n    Eigen::VectorXd coeff = RootFinder::polySqr(nVelCoeffMat.row(0)) +\n                            RootFinder::polySqr(nVelCoeffMat.row(1)) +\n                            RootFinder::polySqr(nVelCoeffMat.row(2));\n    int N = coeff.size();\n    int n = N - 1;\n    for (int i = 0; i < N; i++) {\n      coeff(i) *= n;\n      n--;\n    }\n    if (coeff.head(N - 1).squaredNorm() < DBL_EPSILON) {\n      return 0.0;\n    } else {\n      double l = -0.0625;\n      double r = 1.0625;\n      while (fabs(RootFinder::polyVal(coeff.head(N - 1), l)) < DBL_EPSILON) {\n        l = 0.5 * l;\n      }\n      while (fabs(RootFinder::polyVal(coeff.head(N - 1), r)) < DBL_EPSILON) {\n        r = 0.5 * (r + 1.0);\n      }\n      std::set<double> candidates = RootFinder::solvePolynomial(coeff.head(N - 1), l, r,\n                                                                FLT_EPSILON / duration);\n      candidates.insert(0.0);\n      candidates.insert(1.0);\n      double maxVelRateSqr = -INFINITY;\n      double tempNormSqr;\n      for (std::set<double>::const_iterator it = candidates.begin();\n           it != candidates.end();\n           it++) {\n        if (0.0 <= *it && 1.0 >= *it) {\n          tempNormSqr = getVel((*it) * duration).squaredNorm();\n          maxVelRateSqr = maxVelRateSqr < tempNormSqr ? tempNormSqr : maxVelRateSqr;\n        }\n      }\n      return sqrt(maxVelRateSqr);\n    }\n  }\n\n  inline double getMaxAccRate() const {\n    Eigen::MatrixXd nAccCoeffMat = normalizeAccCoeffMat();\n    Eigen::VectorXd coeff = RootFinder::polySqr(nAccCoeffMat.row(0)) +\n                            RootFinder::polySqr(nAccCoeffMat.row(1)) +\n                            RootFinder::polySqr(nAccCoeffMat.row(2));\n    int N = coeff.size();\n    int n = N - 1;\n    for (int i = 0; i < N; i++) {\n      coeff(i) *= n;\n      n--;\n    }\n    if (coeff.head(N - 1).squaredNorm() < DBL_EPSILON) {\n      return 0.0;\n    } else {\n      double l = -0.0625;\n      double r = 1.0625;\n      while (fabs(RootFinder::polyVal(coeff.head(N - 1), l)) < DBL_EPSILON) {\n        l = 0.5 * l;\n      }\n      while (fabs(RootFinder::polyVal(coeff.head(N - 1), r)) < DBL_EPSILON) {\n        r = 0.5 * (r + 1.0);\n      }\n      std::set<double> candidates = RootFinder::solvePolynomial(coeff.head(N - 1), l, r,\n                                                                FLT_EPSILON / duration);\n      candidates.insert(0.0);\n      candidates.insert(1.0);\n      double maxAccRateSqr = -INFINITY;\n      double tempNormSqr;\n      for (std::set<double>::const_iterator it = candidates.begin();\n           it != candidates.end();\n           it++) {\n        if (0.0 <= *it && 1.0 >= *it) {\n          tempNormSqr = getAcc((*it) * duration).squaredNorm();\n          maxAccRateSqr = maxAccRateSqr < tempNormSqr ? tempNormSqr : maxAccRateSqr;\n        }\n      }\n      return sqrt(maxAccRateSqr);\n    }\n  }\n\n  inline bool checkMaxVelRate(const double &maxVelRate) const {\n    double sqrMaxVelRate = maxVelRate * maxVelRate;\n    if (getVel(0.0).squaredNorm() >= sqrMaxVelRate ||\n        getVel(duration).squaredNorm() >= sqrMaxVelRate) {\n      return false;\n    } else {\n      Eigen::MatrixXd nVelCoeffMat = normalizeVelCoeffMat();\n      Eigen::VectorXd coeff = RootFinder::polySqr(nVelCoeffMat.row(0)) +\n                              RootFinder::polySqr(nVelCoeffMat.row(1)) +\n                              RootFinder::polySqr(nVelCoeffMat.row(2));\n      double t2 = duration * duration;\n      coeff.tail<1>()(0) -= sqrMaxVelRate * t2;\n      return RootFinder::countRoots(coeff, 0.0, 1.0) == 0;\n    }\n  }\n\n  inline bool checkMaxAccRate(const double &maxAccRate) const {\n    double sqrMaxAccRate = maxAccRate * maxAccRate;\n    if (getAcc(0.0).squaredNorm() >= sqrMaxAccRate ||\n        getAcc(duration).squaredNorm() >= sqrMaxAccRate) {\n      return false;\n    } else {\n      Eigen::MatrixXd nAccCoeffMat = normalizeAccCoeffMat();\n      Eigen::VectorXd coeff = RootFinder::polySqr(nAccCoeffMat.row(0)) +\n                              RootFinder::polySqr(nAccCoeffMat.row(1)) +\n                              RootFinder::polySqr(nAccCoeffMat.row(2));\n      double t2 = duration * duration;\n      double t4 = t2 * t2;\n      coeff.tail<1>()(0) -= sqrMaxAccRate * t4;\n      return RootFinder::countRoots(coeff, 0.0, 1.0) == 0;\n    }\n  }\n\n  // GaaiLam\n  inline double project_pt(const Eigen::Vector3d &pt,\n                           double &tt, Eigen::Vector3d &pro_pt) {\n    // 2*(p-p0)^T * \\dot{p} = 0\n    auto l_coeff = getCoeffMat();\n    l_coeff.col(5) = l_coeff.col(5) - pt;\n    auto r_coeff = getVelCoeffMat();\n    Eigen::VectorXd eq = Eigen::VectorXd::Zero(2 * 5);\n    for (int j = 0; j < l_coeff.rows(); ++j) {\n      eq = eq + RootFinder::polyConv(l_coeff.row(j), r_coeff.row(j));\n    }\n    double l = -0.0625;\n    double r = duration + 0.0625;\n    while (fabs(RootFinder::polyVal(eq, l)) < DBL_EPSILON) {\n      l = 0.5 * l;\n    }\n    while (fabs(RootFinder::polyVal(eq, r)) < DBL_EPSILON) {\n      r = 0.5 * (duration + r);\n    }\n    std::set<double> roots =\n        RootFinder::solvePolynomial(eq, l, r, 1e-6);\n    // std::cout << \"# roots: \" << roots.size() << std::endl;\n    double min_dist = -1;\n    for (const auto &root : roots) {\n      // std::cout << \"root: \" << root << std::endl;\n      if (root < 0 || root > duration) {\n        continue;\n      }\n      if (getVel(root).norm() < 1e-6) {  // velocity == 0, ignore it\n        continue;\n      }\n      // std::cout << \"find min!\" << std::endl;\n      Eigen::Vector3d p = getPos(root);\n      // std::cout << \"p: \" << p.transpose() << std::endl;\n      double distance = (p - pt).norm();\n      if (distance < min_dist || min_dist < 0) {\n        min_dist = distance;\n        tt = root;\n        pro_pt = p;\n      }\n    }\n    return min_dist;\n  }\n\n  inline bool intersection_plane(const Eigen::Vector3d p,\n                                 const Eigen::Vector3d v,\n                                 double &tt, Eigen::Vector3d &pt) const {\n    // (pt - p)^T * v = 0\n    auto coeff = getCoeffMat();\n    coeff.col(5) = coeff.col(5) - p;\n    Eigen::VectorXd eq = coeff.transpose() * v;\n    double l = -0.0625;\n    double r = duration + 0.0625;\n    while (fabs(RootFinder::polyVal(eq, l)) < DBL_EPSILON) {\n      l = 0.5 * l;\n    }\n    while (fabs(RootFinder::polyVal(eq, r)) < DBL_EPSILON) {\n      r = 0.5 * (duration + r);\n    }\n    std::set<double> roots =\n        RootFinder::solvePolynomial(eq, l, r, 1e-6);\n    for (const auto &root : roots) {\n      tt = root;\n      pt = getPos(root);\n      return true;\n    }\n    return false;\n  }\n};\n\nclass Trajectory {\n private:\n  typedef std::vector<Piece> Pieces;\n  Pieces pieces;\n\n public:\n  Trajectory() = default;\n\n  Trajectory(const std::vector<double> &durs,\n             const std::vector<CoefficientMat> &cMats) {\n    int N = std::min(durs.size(), cMats.size());\n    pieces.reserve(N);\n    for (int i = 0; i < N; i++) {\n      pieces.emplace_back(durs[i], cMats[i]);\n    }\n  }\n\n  inline int getPieceNum() const {\n    return pieces.size();\n  }\n\n  inline Eigen::VectorXd getDurations() const {\n    int N = getPieceNum();\n    Eigen::VectorXd durations(N);\n    for (int i = 0; i < N; i++) {\n      durations(i) = pieces[i].getDuration();\n    }\n    return durations;\n  }\n\n  inline double getTotalDuration() const {\n    int N = getPieceNum();\n    double totalDuration = 0.0;\n    for (int i = 0; i < N; i++) {\n      totalDuration += pieces[i].getDuration();\n    }\n    return totalDuration;\n  }\n\n  inline Eigen::MatrixXd getPositions() const {\n    int N = getPieceNum();\n    Eigen::MatrixXd positions(3, N + 1);\n    for (int i = 0; i < N; i++) {\n      positions.col(i) = pieces[i].getCoeffMat().col(5);\n    }\n    positions.col(N) = pieces[N - 1].getPos(pieces[N - 1].getDuration());\n    return positions;\n  }\n\n  inline const Piece &operator[](int i) const {\n    return pieces[i];\n  }\n\n  inline Piece &operator[](int i) {\n    return pieces[i];\n  }\n\n  inline void clear(void) {\n    pieces.clear();\n    return;\n  }\n\n  inline Pieces::const_iterator begin() const {\n    return pieces.begin();\n  }\n\n  inline Pieces::const_iterator end() const {\n    return pieces.end();\n  }\n\n  inline Pieces::iterator begin() {\n    return pieces.begin();\n  }\n\n  inline Pieces::iterator end() {\n    return pieces.end();\n  }\n\n  inline void reserve(const int &n) {\n    pieces.reserve(n);\n    return;\n  }\n\n  inline void emplace_back(const Piece &piece) {\n    pieces.emplace_back(piece);\n    return;\n  }\n\n  inline void emplace_back(const double &dur,\n                           const CoefficientMat &cMat) {\n    pieces.emplace_back(dur, cMat);\n    return;\n  }\n\n  inline void append(const Trajectory &traj) {\n    pieces.insert(pieces.end(), traj.begin(), traj.end());\n    return;\n  }\n\n  inline int locatePieceIdx(double &t) const {\n    int N = getPieceNum();\n    int idx;\n    double dur;\n    for (idx = 0;\n         idx < N &&\n         t > (dur = pieces[idx].getDuration());\n         idx++) {\n      t -= dur;\n    }\n    if (idx == N) {\n      idx--;\n      t += pieces[idx].getDuration();\n    }\n    return idx;\n  }\n\n  inline Eigen::Vector3d getPos(double t) const {\n    int pieceIdx = locatePieceIdx(t);\n    return pieces[pieceIdx].getPos(t);\n  }\n\n  inline Eigen::Vector3d getVel(double t) const {\n    int pieceIdx = locatePieceIdx(t);\n    return pieces[pieceIdx].getVel(t);\n  }\n\n  inline Eigen::Vector3d getAcc(double t) const {\n    int pieceIdx = locatePieceIdx(t);\n    return pieces[pieceIdx].getAcc(t);\n  }\n\n  inline Eigen::Vector3d getJer(double t) const {\n    int pieceIdx = locatePieceIdx(t);\n    return pieces[pieceIdx].getJer(t);\n  }\n\n  inline Eigen::Vector3d getJuncPos(int juncIdx) const {\n    if (juncIdx != getPieceNum()) {\n      return pieces[juncIdx].getCoeffMat().col(5);\n    } else {\n      return pieces[juncIdx - 1].getPos(pieces[juncIdx - 1].getDuration());\n    }\n  }\n\n  inline Eigen::Vector3d getJuncVel(int juncIdx) const {\n    if (juncIdx != getPieceNum()) {\n      return pieces[juncIdx].getCoeffMat().col(4);\n    } else {\n      return pieces[juncIdx - 1].getVel(pieces[juncIdx - 1].getDuration());\n    }\n  }\n\n  inline Eigen::Vector3d getJuncAcc(int juncIdx) const {\n    if (juncIdx != getPieceNum()) {\n      return pieces[juncIdx].getCoeffMat().col(3) * 2.0;\n    } else {\n      return pieces[juncIdx - 1].getAcc(pieces[juncIdx - 1].getDuration());\n    }\n  }\n\n  inline double getMaxVelRate() const {\n    int N = getPieceNum();\n    double maxVelRate = -INFINITY;\n    double tempNorm;\n    for (int i = 0; i < N; i++) {\n      tempNorm = pieces[i].getMaxVelRate();\n      maxVelRate = maxVelRate < tempNorm ? tempNorm : maxVelRate;\n    }\n    return maxVelRate;\n  }\n\n  inline double getMaxAccRate() const {\n    int N = getPieceNum();\n    double maxAccRate = -INFINITY;\n    double tempNorm;\n    for (int i = 0; i < N; i++) {\n      tempNorm = pieces[i].getMaxAccRate();\n      maxAccRate = maxAccRate < tempNorm ? tempNorm : maxAccRate;\n    }\n    return maxAccRate;\n  }\n\n  inline bool checkMaxVelRate(const double &maxVelRate) const {\n    int N = getPieceNum();\n    bool feasible = true;\n    for (int i = 0; i < N && feasible; i++) {\n      feasible = feasible && pieces[i].checkMaxVelRate(maxVelRate);\n    }\n    return feasible;\n  }\n\n  inline bool checkMaxAccRate(const double &maxAccRate) const {\n    int N = getPieceNum();\n    bool feasible = true;\n    for (int i = 0; i < N && feasible; i++) {\n      feasible = feasible && pieces[i].checkMaxAccRate(maxAccRate);\n    }\n    return feasible;\n  }\n\n  // GaaiLam\n  inline double project_pt(const Eigen::Vector3d &pt,\n                           int &ii, double &tt, Eigen::Vector3d &pro_pt) {\n    double min_dist = -1;\n    for (int i = 0; i < getPieceNum(); ++i) {\n      auto piece = pieces[i];\n      double t = 0;\n      double dist = piece.project_pt(pt, t, pro_pt);\n      if (dist < 0) {\n        continue;\n      }\n      if (min_dist < 0 || dist < min_dist) {\n        min_dist = dist;\n        ii = i;\n        tt = t;\n      }\n    }\n    return min_dist;\n  }\n  inline bool intersection_plane(const Eigen::Vector3d p,\n                                 const Eigen::Vector3d v,\n                                 int &ii, double &tt, Eigen::Vector3d &pt) {\n    for (int i = 0; i < getPieceNum(); ++i) {\n      const auto &piece = pieces[i];\n      if (piece.intersection_plane(p, v, tt, pt)) {\n        ii = i;\n        return true;\n      }\n    }\n    return false;\n  }\n  inline std::vector<Eigen::Vector3d> way_points() {\n    std::vector<Eigen::Vector3d> pts;\n    for (int i = 0; i < getPieceNum(); ++i) {\n      pts.push_back(pieces[i].getPos(0));\n    }\n    return pts;\n  }\n};\n}", "meta": {"hexsha": "3fdb739611c909c8c7d96db52951aba18b3b2294", "size": 15589, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/mpc/include/mpc_utils/poly_traj_utils.hpp", "max_stars_repo_name": "GaoLon/diablo_mpc", "max_stars_repo_head_hexsha": "8050e9df76383ad99b23bd5c0771d41f888eb340", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/mpc/include/mpc_utils/poly_traj_utils.hpp", "max_issues_repo_name": "GaoLon/diablo_mpc", "max_issues_repo_head_hexsha": "8050e9df76383ad99b23bd5c0771d41f888eb340", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mpc/include/mpc_utils/poly_traj_utils.hpp", "max_forks_repo_name": "GaoLon/diablo_mpc", "max_forks_repo_head_hexsha": "8050e9df76383ad99b23bd5c0771d41f888eb340", "max_forks_repo_licenses": ["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.7384341637, "max_line_length": 88, "alphanum_fraction": 0.5601385592, "num_tokens": 4631, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149978955811, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.45309119396786995}}
{"text": "#include <boost/units/base_units/metric/hour.hpp>\r\n#include <boost/units/base_units/us/mile.hpp>\r\n#include <boost/units/io.hpp>\r\n#include <boost/units/make_scaled_unit.hpp>\r\n#include <boost/units/quantity.hpp>\r\n#include <boost/units/systems/si/length.hpp>\r\n#include <boost/units/systems/si/prefixes.hpp>\r\n#include <boost/units/systems/si/time.hpp>\r\n#include <boost/units/systems/si/velocity.hpp>\r\n#include <cassert>\r\n#include <iostream>\r\n\r\nnamespace {\r\n\r\nnamespace bu = boost::units;\r\n\r\n// h\r\nusing hour = bu::metric::hour_base_unit::unit_type;\r\nBOOST_UNITS_STATIC_CONSTANT(hours, hour);\r\n\r\n// km\r\nusing kilometer = bu::make_scaled_unit<bu::si::length, bu::scale<10, bu::static_rational<3>>>::type;\r\n\r\n// km/h\r\nusing kilometer_per_hour = bu::divide_typeof_helper<kilometer, hour>::type;\r\nBOOST_UNITS_STATIC_CONSTANT(kilometers_per_hour, kilometer_per_hour);\r\n\r\n// mi\r\nusing mile = bu::us::mile_base_unit::unit_type;\r\nBOOST_UNITS_STATIC_CONSTANT(miles, mile);\r\n\r\n// mi/h\r\nusing mile_per_hour = bu::divide_typeof_helper<mile, hour>::type;\r\nBOOST_UNITS_STATIC_CONSTANT(miles_per_hour, mile_per_hour);\r\n\r\nconstexpr bu::quantity<bu::si::velocity> avg_speed(bu::quantity<bu::si::length> d, bu::quantity<bu::si::time> t)\r\n{\r\n  return d / t;\r\n  // return d * t;\r\n}\r\n\r\ntemplate<typename T>\r\nvoid km_per_h(const T& v)\r\n{\r\n  const bu::quantity<kilometer_per_hour> kmph(v);\r\n\r\n  std::cout << \"v = \" << v << '\\n';       // prints \"v = 30.5556 m s^-1\"\r\n  std::cout << \"kmph = \" << kmph << '\\n'; // prints \"kmph = 110 k(m h^-1)\"\r\n\r\n  assert(v.value() != 110);                                                 // <=== !!!!\r\n  assert(v == bu::quantity<bu::si::velocity>(110 * kilometers_per_hour));\r\n  assert(bu::quantity<kilometer_per_hour>(v) != 110 * kilometers_per_hour); // <=== !!!!\r\n  assert(kmph.value() != 110);                                              // <=== !!!!\r\n  assert(kmph != 110 * kilometers_per_hour);                                // <=== !!!!\r\n}\r\n\r\nvoid km_per_h()\r\n{\r\n  constexpr auto v = avg_speed(bu::quantity<bu::si::length>(220 * bu::si::kilo * bu::si::meters), bu::quantity<bu::si::time>(2 * hours));\r\n  km_per_h(v);\r\n}\r\n\r\nvoid km_per_h(double a, double b)\r\n{\r\n  const auto v = avg_speed(bu::quantity<bu::si::length>(a * bu::si::kilo * bu::si::meters), bu::quantity<bu::si::time>(b * hours));\r\n  km_per_h(v);\r\n}\r\n\r\ntemplate<typename T>\r\nvoid mi_per_h(const T& v)\r\n{\r\n  const bu::quantity<mile_per_hour> miph(v);\r\n\r\n  std::cout << \"v = \" << v << '\\n';       // prints \"v = 31.2928 m s^-1\"\r\n  std::cout << \"miph = \" << miph << '\\n'; // prints \"miph = 70 mi h^-1\"\r\n\r\n  assert(v.value() != 70);                                          // <=== !!!!\r\n  assert(v == bu::quantity<bu::si::velocity>(70 * miles_per_hour));\r\n  assert(bu::quantity<mile_per_hour>(v) != 70 * miles_per_hour);    // <=== !!!!\r\n  assert(miph.value() != 70);                                       // <=== !!!!\r\n  assert(miph != 70 * miles_per_hour);                              // <=== !!!!\r\n}\r\n\r\nvoid mi_per_h()\r\n{\r\n  const auto v2 = avg_speed(bu::quantity<bu::si::length>(140 * miles), bu::quantity<bu::si::time>(2 * hours));\r\n  mi_per_h(v2);\r\n}\r\n\r\nvoid mi_per_h(double a, double b)\r\n{\r\n  const auto v2 = avg_speed(bu::quantity<bu::si::length>(a * miles), bu::quantity<bu::si::time>(b * hours));\r\n  mi_per_h(v2);\r\n}\r\n\r\n}  // namespace\r\n\r\nint main()\r\n{\r\n  km_per_h();\r\n  km_per_h(220, 2);\r\n  mi_per_h();\r\n  mi_per_h(140, 2);\r\n}\r\n", "meta": {"hexsha": "8845f2c9dbce2e06682b6738933c068cf2da9b9f", "size": 3413, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/boost/avg_speed_si_coherent_units.cpp", "max_stars_repo_name": "mpusz/units-compare", "max_stars_repo_head_hexsha": "1515cb8e163c9f50ebe7571aa329e5c0f332ba72", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-05-09T12:22:07.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-09T12:22:07.000Z", "max_issues_repo_path": "src/boost/avg_speed_si_coherent_units.cpp", "max_issues_repo_name": "mpusz/units_compare", "max_issues_repo_head_hexsha": "1515cb8e163c9f50ebe7571aa329e5c0f332ba72", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/boost/avg_speed_si_coherent_units.cpp", "max_forks_repo_name": "mpusz/units_compare", "max_forks_repo_head_hexsha": "1515cb8e163c9f50ebe7571aa329e5c0f332ba72", "max_forks_repo_licenses": ["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.5047619048, "max_line_length": 138, "alphanum_fraction": 0.581892763, "num_tokens": 991, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149978955811, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.45309119396786995}}
{"text": "#include \"boundary.hpp\"\n#include \"eigen_ext.hpp\"\n#include \"parameters.hpp\"\n#include <cassert>\n#include <iostream>\n\n#include <Eigen/Core>\n#include <Eigen/SparseCore>\n\nnamespace pear {\nvoid boundary_vector(Vec &xp, Vec &yp, MatI &boundary, Vec &Bu, Vec &Bv,\n                     Mat &Kbu, Mat &Kbv) {\n  /*\n  INPUTS\n  xp : vector with points x coordinates\n  yp : vector with points y coordinates\n  g1 : vector of indices of first points of the gamma1 boundary segment\n  g2 : vector of indices of second ponts of the gamma1 boundary segment\n\n  OUTPUTS\n  Bu, Bv : boundary vector\n  Kbu, Kbv : boundary vector term dependent on Cu and Cv\n   */\n  int np = xp.rows();\n  int nb = boundary.rows();\n  int ng = 2 * nb - boundary.col(2).sum();\n\n  VecI g1(ng);\n  VecI g2(ng);\n  compute_skin(boundary, g1, g2);\n\n  // COMPUTE DISTANCES\n  Vec hpx =\n      (pear::extract<Vec>(xp, g1) - pear::extract<Vec>(xp, g2)).array().pow(2);\n  Vec hpy =\n      (pear::extract<Vec>(yp, g1) - pear::extract<Vec>(yp, g2)).array().pow(2);\n\n  Vec h = (hpy + hpx).array().pow(.5);\n\n  // COMPUTE BOUNDARY FUNC\n  Vec bu(np);\n  Vec bv(np);\n  Vec kbu(np);\n  Vec kbv(np);\n  boundary_func(xp, bu, bv, kbu, kbv);\n\n  // BB\n  Vec bbu1 =\n      (h.array() *\n       (2 * pear::extract<Vec>(bu, g1) + pear::extract<Vec>(bu, g2)).array() /\n       6);\n\n  Vec bbu2 =\n      (h.array() *\n       (pear::extract<Vec>(bu, g1) + 2 * pear::extract<Vec>(bu, g2)).array() /\n       6);\n\n  Vec bbv1 =\n      (h.array() *\n       (2 * pear::extract<Vec>(bv, g1) + pear::extract<Vec>(bv, g2)).array() /\n       6);\n\n  Vec bbv2 =\n      (h.array() *\n       (pear::extract<Vec>(bu, g1) + 2 * pear::extract<Vec>(bu, g2)).array() /\n       6);\n\n  // KBB\n  Vec kbbu1 =\n      (h.array() *\n       (3 * pear::extract<Vec>(kbu, g1) + pear::extract<Vec>(kbu, g2)).array() /\n       12);\n\n  Vec kbbu2 =\n      (h.array() *\n       (pear::extract<Vec>(kbu, g1) + 3 * pear::extract<Vec>(kbu, g2)).array() /\n       12);\n\n  Vec kbbum =\n      (h.array() *\n       (pear::extract<Vec>(kbu, g1) + pear::extract<Vec>(kbu, g2)).array() /\n       12);\n\n  Vec kbbv1 =\n      (h.array() *\n       (3 * pear::extract<Vec>(kbv, g1) + pear::extract<Vec>(kbv, g2)).array() /\n       12);\n\n  Vec kbbv2 =\n      (h.array() *\n       (pear::extract<Vec>(kbv, g1) + 3 * pear::extract<Vec>(kbv, g2)).array() /\n       12);\n\n  Vec kbbvm =\n      (h.array() *\n       (pear::extract<Vec>(kbv, g1) + pear::extract<Vec>(kbv, g2)).array() /\n       12);\n\n  // FILL BOUNDARY VECTOR\n  for (int idxg = 0; idxg < ng; idxg++) {\n    Bu(g1(idxg)) += bbu1(idxg);\n    Bu(g2(idxg)) += bbu2(idxg);\n    Bv(g2(idxg)) += bbv1(idxg);\n    Bv(g2(idxg)) += bbv2(idxg);\n  }\n\n  // FILL BOUNDARY MATRIX\n\n  for (int idxg = 0; idxg < ng; idxg++) {\n    Kbu(g1(idxg), g1(idxg)) += kbbu1(idxg);\n    Kbu(g2(idxg), g2(idxg)) += kbbu2(idxg);\n    Kbu(g1(idxg), g2(idxg)) += kbbum(idxg);\n    Kbu(g2(idxg), g1(idxg)) += kbbum(idxg);\n\n    Kbv(g1(idxg), g1(idxg)) += kbbv1(idxg);\n    Kbv(g2(idxg), g2(idxg)) += kbbv2(idxg);\n    Kbv(g1(idxg), g2(idxg)) += kbbvm(idxg);\n    Kbv(g2(idxg), g1(idxg)) += kbbvm(idxg);\n  }\n}\n\nvoid boundary_func(Vec &xp, Vec &bu, Vec &bv, Vec &kbu, Vec &kbv) {\n  bu = xp * pear::hu * pear::Cuamb;\n  bv = xp * pear::hv * pear::Cvamb;\n\n  kbu = -pear::hu * xp;\n  kbv = -pear::hv * xp;\n}\n\nvoid compute_skin(MatI &boundary, VecI &g1, VecI &g2) {\n  int nb = boundary.rows();\n  int ng = 2 * nb - boundary.col(2).sum();\n\n  int idxg = 0;\n  for (int idxb = 0; idxb < nb; idxb++) {\n    if (boundary(idxb, 2) == 1) {\n      g1(idxg) = boundary(idxb, 0);\n      g2(idxg) = boundary(idxb, 1);\n      idxg++;\n    }\n  }\n}\n} // namespace pear\n", "meta": {"hexsha": "d266634ae3a71f01fffa07c35daec526ea352042", "size": 3593, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/boundary.cpp", "max_stars_repo_name": "hdeplaen/the_winning_pear", "max_stars_repo_head_hexsha": "e3eb2f553fdcbdc7d5e5357dbb07fd60e41b8d35", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/boundary.cpp", "max_issues_repo_name": "hdeplaen/the_winning_pear", "max_issues_repo_head_hexsha": "e3eb2f553fdcbdc7d5e5357dbb07fd60e41b8d35", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/boundary.cpp", "max_forks_repo_name": "hdeplaen/the_winning_pear", "max_forks_repo_head_hexsha": "e3eb2f553fdcbdc7d5e5357dbb07fd60e41b8d35", "max_forks_repo_licenses": ["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.9513888889, "max_line_length": 80, "alphanum_fraction": 0.5432785973, "num_tokens": 1315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149978955811, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.45309119396786995}}
{"text": "//\n// Created by david on 2019-05-27.\n//\n\n#include <Eigen/QR>\n#include <general/class_tic_toc.h>\n#include <math/svd.h>\n\nstd::optional<long long> svd::solver::count = 0;\n\nsvd::solver::solver() {\n    setLogLevel(2);\n    t_wrk = std::make_unique<class_tic_toc>();\n    t_adj = std::make_unique<class_tic_toc>();\n    t_jac = std::make_unique<class_tic_toc>();\n    t_svd = std::make_unique<class_tic_toc>();\n    if(not count) count = 0;\n}\nvoid svd::solver::copy_settings(const svd::settings &svd_settings) {\n    if(svd_settings.threshold) threshold = svd_settings.threshold.value();\n    if(svd_settings.switchsize) switchsize = svd_settings.switchsize.value();\n    if(svd_settings.loglevel) setLogLevel(svd_settings.loglevel.value());\n    if(svd_settings.use_bdc) use_bdc = svd_settings.use_bdc.value();\n    if(svd_settings.use_lapacke) use_lapacke = svd_settings.use_lapacke.value();\n    if(svd_settings.profile and svd_settings.profile.value()) enableProfiling();\n}\n\nsvd::solver::solver(const svd::settings &svd_settings) : solver() { copy_settings(svd_settings); }\n\nsvd::solver::solver(std::optional<svd::settings> svd_settings) : solver() {\n    if(svd_settings) copy_settings(svd_settings.value());\n}\n\nvoid svd::solver::enableProfiling() {\n    t_wrk->set_properties(true, 5, \"work\");\n    t_adj->set_properties(true, 5, \"adjoint\");\n    t_jac->set_properties(true, 5, \"jacobi\");\n    t_svd->set_properties(true, 5, \"bdcsvd\");\n}\nvoid svd::solver::disableProfiling() {\n    t_wrk->set_properties(false, 0, \"\");\n    t_adj->set_properties(false, 0, \"\");\n    t_jac->set_properties(false, 0, \"\");\n    t_svd->set_properties(false, 0, \"\");\n}\n\nvoid svd::solver::setLogLevel(size_t logLevel) {\n    if(not svd::log)\n        tools::Logger::setLogger(svd::log, \"svd\", logLevel, true);\n    else\n        tools::Logger::setLogLevel(svd::log, logLevel);\n    svd::log->set_pattern(\"[%Y-%m-%d %H:%M:%S.%e][%n]%^[%=8l]%$ %v\");\n}\n\n/*! \\brief Performs SVD on a matrix\n *  This function is defined in cpp to avoid long compilation times when having Eigen::BDCSVD included everywhere in headers.\n *  Performs rigorous checks to ensure stability of DMRG.\n *  In some cases Eigen::BCDSVD/JacobiSVD will fail with segfault. Here we use a patched version of Eigen that throws an error\n *  instead so we get a chance to catch it and use lapack svd instead.\n *   \\param mat_ptr Pointer to the matrix. Supported are double * and std::complex<double> *\n *   \\param rows Rows of the matrix\n *   \\param cols Columns of the matrix\n *   \\param rank_max Maximum number of singular values\n *   \\return The U, S, and V matrices (with S as a vector) extracted from the Eigen::BCDSVD SVD object.\n */\ntemplate<typename Scalar>\nstd::tuple<svd::solver::MatrixType<Scalar>, svd::solver::VectorType<Scalar>, svd::solver::MatrixType<Scalar>, long>\n    svd::solver::do_svd(const Scalar *mat_ptr, long rows, long cols, std::optional<long> rank_max) {\n    if(use_lapacke) {\n        try {\n            return do_svd_lapacke(mat_ptr, rows, cols, rank_max);\n        } catch(const std::exception &ex) {\n            svd::log->warn(FMT_COMPILE(\"Lapacke failed to perform SVD: {} | Trying Eigen\"), ex.what());\n            return do_svd_eigen(mat_ptr, rows, cols, rank_max);\n        }\n    }else {\n        try {\n            return do_svd_eigen(mat_ptr, rows, cols, rank_max);\n        } catch(const std::exception &ex) {\n            svd::log->warn(FMT_COMPILE(\"Eigen failed to perform SVD: {} | Trying Lapacke\"), ex.what());\n            return do_svd_lapacke(mat_ptr, rows, cols, rank_max);\n        }\n    }\n}\n\n//! \\relates svd::class_SVD\n//! \\brief force instantiation of do_svd for type 'double'\ntemplate std::tuple<svd::solver::MatrixType<double>, svd::solver::VectorType<double>, svd::solver::MatrixType<double>, long>\n    svd::solver::do_svd(const double *, long, long, std::optional<long>);\n\nusing cplx = std::complex<double>;\n//! \\relates svd::class_SVD\n//! \\brief force instantiation of do_svd for type 'std::complex<double>'\ntemplate std::tuple<svd::solver::MatrixType<cplx>, svd::solver::VectorType<cplx>, svd::solver::MatrixType<cplx>, long>\n    svd::solver::do_svd(const cplx *, long, long, std::optional<long>);\n\ntemplate<typename Scalar>\nEigen::Tensor<Scalar, 2> svd::solver::pseudo_inverse(const Eigen::Tensor<Scalar, 2> &tensor) {\n    if(tensor.dimension(0) <= 0) { throw std::runtime_error(\"pseudo_inverse error: Dimension is zero: tensor.dimension(0)\"); }\n    if(tensor.dimension(1) <= 0) { throw std::runtime_error(\"pseudo_inverse error: Dimension is zero: tensor.dimension(1)\"); }\n    Eigen::Map<const MatrixType<Scalar>> mat(tensor.data(), tensor.dimension(0), tensor.dimension(1));\n    return Textra::TensorCast(mat.completeOrthogonalDecomposition().pseudoInverse());\n}\n\n//! \\relates svd::class_SVD\n//! \\brief force instantiation of pseudo_inverse for type 'double'\ntemplate Eigen::Tensor<double, 2> svd::solver::pseudo_inverse(const Eigen::Tensor<double, 2> &tensor);\n//! \\relates svd::class_SVD\n//! \\brief force instantiation of pseudo_inverse for type 'std::complex<double>'\ntemplate Eigen::Tensor<cplx, 2> svd::solver::pseudo_inverse(const Eigen::Tensor<cplx, 2> &tensor);", "meta": {"hexsha": "d7df2eb6d7b1bd1eead8b15ec17ef2d531ba676b", "size": 5130, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/math/svd/svd.cpp", "max_stars_repo_name": "DavidAce/DMRG", "max_stars_repo_head_hexsha": "e465fd903eade1bf6aa74daacd8e2cf02e9e9332", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2017-10-31T22:50:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T15:45:27.000Z", "max_issues_repo_path": "source/math/svd/svd.cpp", "max_issues_repo_name": "DavidAce/DMRG", "max_issues_repo_head_hexsha": "e465fd903eade1bf6aa74daacd8e2cf02e9e9332", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/math/svd/svd.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": 46.6363636364, "max_line_length": 126, "alphanum_fraction": 0.6947368421, "num_tokens": 1433, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.754914997895581, "lm_q2_score": 0.6001883592602049, "lm_q1q2_score": 0.4530911939678698}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// weighted_count.hpp                                                        //\n//                                                                           //\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_DETAIL_WEIGHTED_COUNT_HPP_ER_2010\n#define BOOST_ACCUMULATORS_STATISTICS_DETAIL_WEIGHTED_COUNT_HPP_ER_2010\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/parameters/weight.hpp>\n#include <boost/accumulators/framework/accumulators/external_accumulator.hpp>\n#include <boost/accumulators/framework/depends_on.hpp>\n#include <boost/accumulators/statistics_fwd.hpp>\n\n// This file is a modification of Boost.Accumulator's count.hpp by Eric Niebler. \n\nnamespace boost { namespace accumulators\n{\n\nnamespace impl\n{\n    ///////////////////////////////////////////////////////////////////////////////\n    // weighted_count_impl\n    template<typename Weight>\n    struct weighted_count_impl\n      : accumulator_base\n    {\n        typedef Weight weighted_sample;\n\n        // for boost::result_of\n        typedef weighted_sample result_type;\n\n        template<typename Args>\n        weighted_count_impl(Args const &args)\n          : weighted_count_(\n                numeric::zero<Weight>::value\n            )\n        {\n        }\n\n        template<typename Args>\n        void operator ()(Args const &args)\n        {\n            // what about overflow?\n            this->weighted_count_ += args[ weight ];\n        }\n\n        result_type result(dont_care) const\n        {\n            return this->weighted_count_;\n        }\n\n    private:\n\n        weighted_sample weighted_count_;\n    };\n\n} // namespace impl\n\nnamespace tag\n{\n    struct weighted_count\n      : depends_on<>\n    {\n        typedef accumulators::impl::weighted_count_impl<mpl::_2> impl;\n    };\n\n/*\n    template<typename VariateType, typename VariateTag>\n    struct weighted_count_of_variates\n      : depends_on<>\n    {\n        /// INTERNAL ONLY\n        ///\n        typedef accumulators::impl::weighted_count_impl<VariateType, mpl::_2, VariateTag> impl;\n    };\n\n    struct abstract_weighted_count_of_variates\n      : depends_on<>\n    {\n    };\n*/\n}\n\nnamespace extract\n{\n    extractor<tag::weighted_count> const weighted_count = {};\n//    extractor<tag::abstract_weighted_count_of_variates> const weighted_count_of_variates = {};\n\n    BOOST_ACCUMULATORS_IGNORE_GLOBAL(weighted_count)\n//    BOOST_ACCUMULATORS_IGNORE_GLOBAL(weighted_count_of_variates)\n}\n\nusing extract::weighted_count;\n//using extract::weighted_count_of_variates;\n\n/*\ntemplate<typename VariateType, typename VariateTag>\nstruct feature_of<tag::weighted_count_of_variates<VariateType, VariateTag> >\n  : feature_of<tag::abstract_weighted_count_of_variates>\n{\n};\n*/\n\n}} // namespace boost::accumulators\n\n#endif\n", "meta": {"hexsha": "6a0194910777f49b84d493004dac8540932dfc66", "size": 3290, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "support/boost/accumulators/statistics/detail/weighted_count.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": "support/boost/accumulators/statistics/detail/weighted_count.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": "support/boost/accumulators/statistics/detail/weighted_count.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": 29.1150442478, "max_line_length": 96, "alphanum_fraction": 0.6224924012, "num_tokens": 645, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.453091187349021}}
{"text": "#include \"SimulationCore_pcp.h\"\n\n#include <Eigen/SparseLU>\n\n#define Keep_Newmark_Coefficients\n#include \"Step_S2D_CHM_s_FEM_uUp.h\"\n\nnamespace\n{\n\ttypedef Model_S2D_CHM_s_FEM_uUp::ShapeFuncValue ShapeFuncValue;\n\ttypedef Model_S2D_CHM_s_FEM_uUp::GaussPoint GaussPoint_fem;\n\ttypedef Model_S2D_CHM_s_FEM_uUp::Element Element_fem;\n\ttypedef Model_S2D_CHM_s_FEM_uUp::Node Node_fem;\n\ttypedef Model_S2D_CHM_s_FEM_uUp::DOF DOF;\n\t\n\tvoid print_sparse_mat(Eigen::SparseMatrix<double> &mat,\n\t\tstd::fstream &out_file, const char *mat_name = nullptr)\n\t{\n\t\tif (mat_name)\n\t\t\tout_file << mat_name << \"\\n\";\n\t\tsize_t row_num = mat.rows();\n\t\tsize_t col_num = mat.cols();\n\t\tdouble value;\n\t\tfor (size_t i = 0; i < row_num; ++i)\n\t\t{\n\t\t\tfor (size_t j = 0; j < col_num; ++j)\n\t\t\t{\n\t\t\t\tvalue = mat.coeff(i, j);\n\t\t\t\tout_file << value << \", \";\n\t\t\t}\n\t\t\tout_file << \"\\n\";\n\t\t}\n\t}\n};\n\nStep_S2D_CHM_s_FEM_uUp::Step_S2D_CHM_s_FEM_uUp() :\n\tStep(&solve_substep_S2D_CHM_s_FEM_uUp),\n\tmodel(nullptr), kmat_col(nullptr) {}\n\nStep_S2D_CHM_s_FEM_uUp::~Step_S2D_CHM_s_FEM_uUp() {}\n\nint Step_S2D_CHM_s_FEM_uUp::init_calculation(void)\n{\n\tif (is_first_step) {}\n\n\tkmat_col = new double[model->dof_num];\n\n\t// for debug\n\tout_file.open(\"debug_mat_out_CHM_s_FEM_uUp.csv\", std::ios::binary | std::ios::out);\n\t\n\treturn 0;\n}\n\nint Step_S2D_CHM_s_FEM_uUp::finalize_calculation(void)\n{\n\tif (kmat_col)\n\t{\n\t\tdelete[] kmat_col;\n\t\tkmat_col = nullptr;\n\t}\n\t\n\t// for debug\n\tout_file.close();\n\n\treturn 0;\n}\n\nint solve_substep_S2D_CHM_s_FEM_uUp(void *_self)\n{\n\t// for debug\n\t//static std::fstream out_f2(\"out_f2.txt\", std::ios::binary | std::ios::out);\n\n\tStep_S2D_CHM_s_FEM_uUp &self = *(Step_S2D_CHM_s_FEM_uUp *)(_self);\n\tModel_S2D_CHM_s_FEM_uUp &model = *self.model;\n\tdouble dt = self.dtime;\n\tdouble dt2 = dt * dt;\n\n\t// list of non-zeros coefficients\n\tMatrixCoefficientSet<> &g_kmat_coefs = self.g_kmat_coefs;\n\tg_kmat_coefs.init(model.dof_num);\n\tEigen::VectorXd g_fvec(model.dof_num);\n\tg_fvec.setZero();\n\n\tsize_t l2g_dof_id_map[20];\n\tdouble e_kmat[20][20], e_fvec[20];\n\tfor (size_t e_id = 0; e_id < model.elem_num; ++e_id)\n\t{\n\t\tElement_fem &e = model.elems[e_id];\n\t\t// form elemental stiffness matrix and force vector\n\t\tself.form_elem_stiffness_mat_and_force_vec(e, e_kmat, e_fvec);\n\t\t\n\t\t// map from local dof id to global dof id\n\t\t// solid phase ux\n\t\tl2g_dof_id_map[0] = model.n_id_to_dof_id(e.n1_id, DOF::usx);\n\t\tl2g_dof_id_map[1] = model.n_id_to_dof_id(e.n2_id, DOF::usx);\n\t\tl2g_dof_id_map[2] = model.n_id_to_dof_id(e.n3_id, DOF::usx);\n\t\tl2g_dof_id_map[3] = model.n_id_to_dof_id(e.n4_id, DOF::usx);\n\t\t// solid phase uy\n\t\tl2g_dof_id_map[4] = model.n_id_to_dof_id(e.n1_id, DOF::usy);\n\t\tl2g_dof_id_map[5] = model.n_id_to_dof_id(e.n2_id, DOF::usy);\n\t\tl2g_dof_id_map[6] = model.n_id_to_dof_id(e.n3_id, DOF::usy);\n\t\tl2g_dof_id_map[7] = model.n_id_to_dof_id(e.n4_id, DOF::usy);\n\t\t// fluid phase ux\n\t\tl2g_dof_id_map[8]  = model.n_id_to_dof_id(e.n1_id, DOF::ufx);\n\t\tl2g_dof_id_map[9]  = model.n_id_to_dof_id(e.n2_id, DOF::ufx);\n\t\tl2g_dof_id_map[10] = model.n_id_to_dof_id(e.n3_id, DOF::ufx);\n\t\tl2g_dof_id_map[11] = model.n_id_to_dof_id(e.n4_id, DOF::ufx);\n\t\t// fluid phase uy\n\t\tl2g_dof_id_map[12] = model.n_id_to_dof_id(e.n1_id, DOF::ufy);\n\t\tl2g_dof_id_map[13] = model.n_id_to_dof_id(e.n2_id, DOF::ufy);\n\t\tl2g_dof_id_map[14] = model.n_id_to_dof_id(e.n3_id, DOF::ufy);\n\t\tl2g_dof_id_map[15] = model.n_id_to_dof_id(e.n4_id, DOF::ufy);\n\t\t// p\n\t\tl2g_dof_id_map[16] = model.n_id_to_dof_id(e.n1_id, DOF::p);\n\t\tl2g_dof_id_map[17] = model.n_id_to_dof_id(e.n2_id, DOF::p);\n\t\tl2g_dof_id_map[18] = model.n_id_to_dof_id(e.n3_id, DOF::p);\n\t\tl2g_dof_id_map[19] = model.n_id_to_dof_id(e.n4_id, DOF::p);\n\t\t//print_vec(l2g_dof_id_map);\n\t\t// add to global matrix and vector\n\t\tsize_t g_dof_id1, g_dof_id2;\n\t\tfor (size_t l_id1 = 0; l_id1 < 20; ++l_id1)\n\t\t{\n\t\t\t// add to global matrix\n\t\t\tg_dof_id1 = l2g_dof_id_map[l_id1];\n\t\t\tfor (size_t l_id2 = 0; l_id2 < 20; ++l_id2)\n\t\t\t{\n\t\t\t\tg_dof_id2 = l2g_dof_id_map[l_id2];\n\t\t\t\tg_kmat_coefs.add_coefficient(g_dof_id1, g_dof_id2, e_kmat[l_id1][l_id2]);\n\t\t\t}\n\t\t\t// add to global force vector\n\t\t\tg_fvec[g_dof_id1] += e_fvec[l_id1];\n\t\t}\n\t}\n\n\t// apply external force body force and traction\n\tsize_t dof_id;\n\t// traction\n\tdouble tfs[4];\n\tfor (size_t t_id = 0; t_id < model.tx_num; ++t_id)\n\t{\n\t\tTractionBC_2DFEM &tx = model.txs[t_id];\n\t\tmodel.cal_traction_bc(tx, tfs);\n\t\tElement_fem &e = model.elems[tx.elem_id];\n\t\tdof_id = model.n_id_to_dof_id(e.n1_id, DOF::usx);\n\t\tg_fvec[dof_id] += tfs[0];\n\t\tdof_id = model.n_id_to_dof_id(e.n2_id, DOF::usx);\n\t\tg_fvec[dof_id] += tfs[1];\n\t\tdof_id = model.n_id_to_dof_id(e.n3_id, DOF::usx);\n\t\tg_fvec[dof_id] += tfs[2];\n\t\tdof_id = model.n_id_to_dof_id(e.n4_id, DOF::usx);\n\t\tg_fvec[dof_id] += tfs[3];\n\t}\n\tfor (size_t t_id = 0; t_id < model.ty_num; ++t_id)\n\t{\n\t\tTractionBC_2DFEM &ty = model.tys[t_id];\n\t\tmodel.cal_traction_bc(ty, tfs);\n\t\tElement_fem &e = model.elems[ty.elem_id];\n\t\tdof_id = model.n_id_to_dof_id(e.n1_id, DOF::usy);\n\t\tg_fvec[dof_id] += tfs[0];\n\t\tdof_id = model.n_id_to_dof_id(e.n2_id, DOF::usy);\n\t\tg_fvec[dof_id] += tfs[1];\n\t\tdof_id = model.n_id_to_dof_id(e.n3_id, DOF::usy);\n\t\tg_fvec[dof_id] += tfs[2];\n\t\tdof_id = model.n_id_to_dof_id(e.n4_id, DOF::usy);\n\t\tg_fvec[dof_id] += tfs[3];\n\t}\n\t// body force ...  to be finished\n\t\n\t// apply displacement boundary condition\n\tdouble dig_term;\n\tfor (size_t bc_id = 0; bc_id < model.usx_num; ++bc_id)\n\t{\n\t\tDisplacementBC &dbc = model.usxs[bc_id];\n\t\tdof_id = model.n_id_to_dof_id(dbc.node_id, DOF::usx);\n\t\tdig_term = g_kmat_coefs.del_col_and_row(dof_id, self.kmat_col);\n\t\tfor (size_t row_id = 0; row_id < model.dof_num; ++row_id)\n\t\t\tg_fvec[row_id] -= self.kmat_col[row_id] * dbc.u;\n\t\tg_fvec[dof_id] = dig_term * dbc.u;\n\t}\n\tfor (size_t bc_id = 0; bc_id < model.usy_num; ++bc_id)\n\t{\n\t\tDisplacementBC &dbc = model.usys[bc_id];\n\t\tdof_id = model.n_id_to_dof_id(dbc.node_id, DOF::usy);\n\t\tdig_term = g_kmat_coefs.del_col_and_row(dof_id, self.kmat_col);\n\t\tfor (size_t row_id = 0; row_id < model.dof_num; ++row_id)\n\t\t\tg_fvec[row_id] -= self.kmat_col[row_id] * dbc.u;\n\t\tg_fvec[dof_id] = dig_term * dbc.u;\n\t}\n\tfor (size_t bc_id = 0; bc_id < model.ufx_num; ++bc_id)\n\t{\n\t\tDisplacementBC &dbc = model.ufxs[bc_id];\n\t\tdof_id = model.n_id_to_dof_id(dbc.node_id, DOF::ufx);\n\t\tdig_term = g_kmat_coefs.del_col_and_row(dof_id, self.kmat_col);\n\t\tfor (size_t row_id = 0; row_id < model.dof_num; ++row_id)\n\t\t\tg_fvec[row_id] -= self.kmat_col[row_id] * dbc.u;\n\t\tg_fvec[dof_id] = dig_term * dbc.u;\n\t}\n\tfor (size_t bc_id = 0; bc_id < model.ufy_num; ++bc_id)\n\t{\n\t\tDisplacementBC &dbc = model.ufys[bc_id];\n\t\tdof_id = model.n_id_to_dof_id(dbc.node_id, DOF::ufy);\n\t\tdig_term = g_kmat_coefs.del_col_and_row(dof_id, self.kmat_col);\n\t\tfor (size_t row_id = 0; row_id < model.dof_num; ++row_id)\n\t\t\tg_fvec[row_id] -= self.kmat_col[row_id] * dbc.u;\n\t\tg_fvec[dof_id] = dig_term * dbc.u;\n\t}\n\tfor (size_t bc_id = 0; bc_id < model.pbc_num; ++bc_id)\n\t{\n\t\tPressureBC &pbc = model.pbcs[bc_id];\n\t\tdof_id = model.n_id_to_dof_id(pbc.node_id, DOF::p);\n\t\tdig_term = g_kmat_coefs.del_col_and_row(dof_id, self.kmat_col);\n\t\tfor (size_t row_id = 0; row_id < model.dof_num; ++row_id)\n\t\t\tg_fvec[row_id] -= self.kmat_col[row_id] * pbc.p;\n\t\tg_fvec[dof_id] = dig_term * pbc.p;\n\t}\n\t\n\t// solve\n\t//g_kmat_coefs.print_with_iter();\n\tEigen::SparseMatrix<double> g_kmat(model.dof_num, model.dof_num);\n\tg_kmat.setFromTriplets(g_kmat_coefs.begin(), g_kmat_coefs.end());\n\t//print_sparse_mat(g_kmat, self.out_file,nullptr);\n\tEigen::SparseLU<Eigen::SparseMatrix<double> > solver(g_kmat);\n\tEigen::VectorXd g_du_vec = solver.solve(g_fvec);\n\t//std::cout << g_fvec << \"\\n\";\n\t//std::cout << g_du_vec << \"\\n\";\n\n\t// reapply disp bc\n\tfor (size_t bc_id = 0; bc_id < model.usx_num; ++bc_id)\n\t{\n\t\tDisplacementBC &dbc = model.usxs[bc_id];\n\t\tdof_id = model.n_id_to_dof_id(dbc.node_id, DOF::usx);\n\t\tg_du_vec[dof_id] = dbc.u;\n\t}\n\tfor (size_t bc_id = 0; bc_id < model.usy_num; ++bc_id)\n\t{\n\t\tDisplacementBC &dbc = model.usys[bc_id];\n\t\tdof_id = model.n_id_to_dof_id(dbc.node_id, DOF::usy);\n\t\tg_du_vec[dof_id] = dbc.u;\n\t}\n\tfor (size_t bc_id = 0; bc_id < model.ufx_num; ++bc_id)\n\t{\n\t\tDisplacementBC &dbc = model.ufxs[bc_id];\n\t\tdof_id = model.n_id_to_dof_id(dbc.node_id, DOF::ufx);\n\t\tg_du_vec[dof_id] = dbc.u;\n\t}\n\tfor (size_t bc_id = 0; bc_id < model.ufy_num; ++bc_id)\n\t{\n\t\tDisplacementBC &dbc = model.ufys[bc_id];\n\t\tdof_id = model.n_id_to_dof_id(dbc.node_id, DOF::ufy);\n\t\tg_du_vec[dof_id] = dbc.u;\n\t}\n\tfor (size_t bc_id = 0; bc_id < model.pbc_num; ++bc_id)\n\t{\n\t\tPressureBC &pbc = model.pbcs[bc_id];\n\t\tdof_id = model.n_id_to_dof_id(pbc.node_id, DOF::p);\n\t\tg_du_vec[dof_id] = pbc.p;\n\t}\n\t\n\t// update nodal variables\n\tdouble da, dv, du;\n\tfor (size_t n_id = 0; n_id < model.node_num; ++n_id)\n\t{\n\t\tNode_fem &n = model.nodes[n_id];\n\t\t// sx\n\t\tdof_id = model.n_id_to_dof_id(n_id, DOF::usx);\n\t\tdu = g_du_vec[dof_id];\n\t\tn.ux_s += du;\n\t\tdv = gamma / (beta * dt) * du - gamma / beta * n.vx_s + dt * (1.0 - gamma / (2.0 * beta)) * n.ax_s;\n\t\tn.vx_s += dv;\n\t\tda = du / (gamma * dt2) - n.vx_s / (gamma * dt) - n.ax_s / (2.0 * gamma);\n\t\tn.ax_s += da;\n\t\t// sy\n\t\tdof_id = model.n_id_to_dof_id(n_id, DOF::usy);\n\t\tdu = g_du_vec[dof_id];\n\t\tn.uy_s += du;\n\t\tdv = gamma / (beta * dt) * du - gamma / beta * n.vy_s + dt * (1.0 - gamma / (2.0 * beta)) * n.ay_s;\n\t\tn.vy_s += dv;\n\t\tda = du / (gamma * dt2) -  n.vy_s / (gamma * dt) - n.ay_s / (2.0 * gamma);\n\t\tn.ay_s += da;\n\t\t// fx\n\t\tdof_id = model.n_id_to_dof_id(n_id, DOF::ufx);\n\t\tdu = g_du_vec[dof_id];\n\t\tn.ux_f += du;\n\t\tdv = gamma / (beta * dt) * du - gamma / beta * n.vx_f + dt * (1.0 - gamma / (2.0 * beta)) * n.ax_f;\n\t\tn.vx_f += dv;\n\t\tda = 1.0 / (gamma * dt2) * du - 1.0 / (gamma * dt) * n.vx_f - 1.0 / (2.0 * gamma) * n.ax_f;\n\t\tn.ax_f += da;\n\t\t// fy\n\t\tdof_id = model.n_id_to_dof_id(n_id, DOF::ufy);\n\t\tdu = g_du_vec[dof_id];\n\t\tn.uy_f += du;\n\t\tdv = gamma / (beta * dt) * du - gamma / beta * n.vy_f + dt * (1.0 - gamma / (2.0 * beta)) * n.ay_s;\n\t\tn.vy_f += dv;\n\t\tda = 1.0 / (gamma * dt2) * du - 1.0 / (gamma * dt) * n.vy_f - 1.0 / (2.0 * gamma) * n.ay_s;\n\t\tn.ay_f += da;\n\t\t// p\n\t\tdof_id = model.n_id_to_dof_id(n_id, DOF::p);\n\t\tn.p += g_du_vec[dof_id];\n\t}\n\n\t// Update element variables\n\tShapeFuncValue &sf1 = model.gp1_sf;\n\tShapeFuncValue &sf2 = model.gp2_sf;\n\tShapeFuncValue &sf3 = model.gp3_sf;\n\tShapeFuncValue &sf4 = model.gp4_sf;\n\tdouble dux_s1, duy_s1, dux_f1, duy_f1, dp1;\n\tdouble dux_s2, duy_s2, dux_f2, duy_f2, dp2;\n\tdouble dux_s3, duy_s3, dux_f3, duy_f3, dp3;\n\tdouble dux_s4, duy_s4, dux_f4, duy_f4, dp4;\n\tfor (size_t e_id = 0; e_id < model.elem_num; ++e_id)\n\t{\n\t\tElement_fem &e = model.elems[e_id];\n\t\tdux_s1 = g_du_vec[model.n_id_to_dof_id(e.n1_id, DOF::usx)];\n\t\tduy_s1 = g_du_vec[model.n_id_to_dof_id(e.n1_id, DOF::usy)];\n\t\tdux_f1 = g_du_vec[model.n_id_to_dof_id(e.n1_id, DOF::ufx)];\n\t\tduy_f1 = g_du_vec[model.n_id_to_dof_id(e.n1_id, DOF::ufy)];\n\t\tdp1    = g_du_vec[model.n_id_to_dof_id(e.n1_id, DOF::p)];\n\t\tdux_s2 = g_du_vec[model.n_id_to_dof_id(e.n2_id, DOF::usx)];\n\t\tduy_s2 = g_du_vec[model.n_id_to_dof_id(e.n2_id, DOF::usy)];\n\t\tdux_f2 = g_du_vec[model.n_id_to_dof_id(e.n2_id, DOF::ufx)];\n\t\tduy_f2 = g_du_vec[model.n_id_to_dof_id(e.n2_id, DOF::ufy)];\n\t\tdp2    = g_du_vec[model.n_id_to_dof_id(e.n2_id, DOF::p)];\n\t\tdux_s3 = g_du_vec[model.n_id_to_dof_id(e.n3_id, DOF::usx)];\n\t\tduy_s3 = g_du_vec[model.n_id_to_dof_id(e.n3_id, DOF::usy)];\n\t\tdux_f3 = g_du_vec[model.n_id_to_dof_id(e.n3_id, DOF::ufx)];\n\t\tduy_f3 = g_du_vec[model.n_id_to_dof_id(e.n3_id, DOF::ufy)];\n\t\tdp3    = g_du_vec[model.n_id_to_dof_id(e.n3_id, DOF::p)];\n\t\tdux_s4 = g_du_vec[model.n_id_to_dof_id(e.n4_id, DOF::usx)];\n\t\tduy_s4 = g_du_vec[model.n_id_to_dof_id(e.n4_id, DOF::usy)];\n\t\tdux_f4 = g_du_vec[model.n_id_to_dof_id(e.n4_id, DOF::ufx)];\n\t\tduy_f4 = g_du_vec[model.n_id_to_dof_id(e.n4_id, DOF::ufy)];\n\t\tdp4    = g_du_vec[model.n_id_to_dof_id(e.n4_id, DOF::p)];\n\n\t\tself.update_gauss_point(e.gp1, sf1, dt, dt2,\n\t\t\tdux_s1, dux_s2, dux_s3, dux_s4,\n\t\t\tduy_s1, duy_s2, duy_s3, duy_s4,\n\t\t\tdux_f1, dux_f2, dux_f3, dux_f4,\n\t\t\tduy_f1, duy_f2, duy_f3, duy_f4,\n\t\t\tdp1, dp2, dp3, dp4);\n\n\t\tself.update_gauss_point(e.gp2, sf2, dt, dt2,\n\t\t\tdux_s1, dux_s2, dux_s3, dux_s4,\n\t\t\tduy_s1, duy_s2, duy_s3, duy_s4,\n\t\t\tdux_f1, dux_f2, dux_f3, dux_f4,\n\t\t\tduy_f1, duy_f2, duy_f3, duy_f4,\n\t\t\tdp1, dp2, dp3, dp4);\n\n\t\tself.update_gauss_point(e.gp3, sf3, dt, dt2,\n\t\t\tdux_s1, dux_s2, dux_s3, dux_s4,\n\t\t\tduy_s1, duy_s2, duy_s3, duy_s4,\n\t\t\tdux_f1, dux_f2, dux_f3, dux_f4,\n\t\t\tduy_f1, duy_f2, duy_f3, duy_f4,\n\t\t\tdp1, dp2, dp3, dp4);\n\n\t\tself.update_gauss_point(e.gp4, sf4, dt, dt2,\n\t\t\tdux_s1, dux_s2, dux_s3, dux_s4,\n\t\t\tduy_s1, duy_s2, duy_s3, duy_s4,\n\t\t\tdux_f1, dux_f2, dux_f3, dux_f4,\n\t\t\tduy_f1, duy_f2, duy_f3, duy_f4,\n\t\t\tdp1, dp2, dp3, dp4);\n\t}\n\t\n\treturn 0;\n}\n\nvoid Step_S2D_CHM_s_FEM_uUp::update_gauss_point(\n\tModel_S2D_CHM_s_FEM_uUp::GaussPoint &gp,\n\tModel_S2D_CHM_s_FEM_uUp::ShapeFuncValue &sf,\n\tdouble dt, double dt2,\n\tdouble dux_s1, double dux_s2, double dux_s3, double dux_s4,\n\tdouble duy_s1, double duy_s2, double duy_s3, double duy_s4,\n\tdouble dux_f1, double dux_f2, double dux_f3, double dux_f4,\n\tdouble duy_f1, double duy_f2, double duy_f3, double duy_f4,\n\tdouble dp1, double dp2, double dp3, double dp4)\n{\n\tdouble dux_s, duy_s, dux_f, duy_f, dp;\n\tdouble dvx_s, dvy_s, dvx_f, dvy_f;\n\tdouble dax_s, day_s, dax_f, day_f;\n\tdouble de11, de22, de12, ds11, ds22, ds12;\n\tdouble de_vol_s, de_vol_f;\n\n\t// displacement\n\tdux_s = dux_s1 * sf.N1 + dux_s2 * sf.N2 + dux_s3 * sf.N3 + dux_s4 * sf.N4;\n\tduy_s = duy_s1 * sf.N1 + duy_s2 * sf.N2 + duy_s3 * sf.N3 + duy_s4 * sf.N4;\n\tdux_f = dux_f1 * sf.N1 + dux_f2 * sf.N2 + dux_f3 * sf.N3 + dux_f4 * sf.N4;\n\tduy_f = duy_f1 * sf.N1 + duy_f2 * sf.N2 + duy_f3 * sf.N3 + duy_f4 * sf.N4;\n\t// velocity\n\tdvx_s = gamma / (beta * dt) * dux_s - gamma / beta * gp.vx_s\n\t\t  + dt * (1.0 - gamma / (2.0 * beta)) * gp.ax_s;\n\tdvy_s = gamma / (beta * dt) * duy_s - gamma / beta * gp.vy_s\n\t\t  + dt * (1.0 - gamma / (2.0 * beta)) * gp.ay_s;\n\tdvx_f = gamma / (beta * dt) * dux_f - gamma / beta * gp.vx_f\n\t\t  + dt * (1.0 - gamma / (2.0 * beta)) * gp.ax_f;\n\tdvy_f = gamma / (beta * dt) * duy_f - gamma / beta * gp.vy_f\n\t\t  + dt * (1.0 - gamma / (2.0 * beta)) * gp.ay_f;\n\t// acceleration\n\tdax_s = dux_s / (beta * dt2) - gp.vx_s / (beta * dt) - gp.ax_s / (2.0 * beta);\n\tday_s = duy_s / (beta * dt2) - gp.vy_s / (beta * dt) - gp.ay_s / (2.0 * beta);\n\tdax_f = dux_f / (beta * dt2) - gp.vx_f / (beta * dt) - gp.ax_f / (2.0 * beta);\n\tday_f = duy_f / (beta * dt2) - gp.vy_f / (beta * dt) - gp.ay_f / (2.0 * beta);\n\tgp.ux_s += dux_s;\n\tgp.uy_s += duy_s;\n\tgp.ux_f += dux_f;\n\tgp.uy_f += duy_f;\n\tgp.vx_s += dvx_s;\n\tgp.vy_s += dvy_s;\n\tgp.vx_f += dvx_f;\n\tgp.vy_f += dvy_f;\n\tgp.ax_s += dax_s;\n\tgp.ay_s += day_s;\n\tgp.ax_f += dax_f;\n\tgp.ay_f += day_f;\n\n\t// pore pressure\n\tgp.p += dp1 * sf.N1 + dp2 * sf.N2 + dp3 * sf.N3 + dp4 * sf.N4;\n\n\t// strain increment\n\tde11 = dux_s1 * sf.dN1_dx + dux_s2 * sf.dN2_dx\n\t\t + dux_s3 * sf.dN3_dx + dux_s4 * sf.dN4_dx;\n\tde22 = duy_s1 * sf.dN1_dy + duy_s2 * sf.dN2_dy\n\t\t + duy_s3 * sf.dN3_dy + duy_s4 * sf.dN4_dy;\n\tde12 = (dux_s1 * sf.dN1_dy + dux_s2 * sf.dN2_dy\n\t\t  + dux_s3 * sf.dN3_dy + dux_s4 * sf.dN4_dy\n\t\t  + duy_s1 * sf.dN1_dx + duy_s2 * sf.dN2_dx\n\t\t  + duy_s3 * sf.dN3_dx + duy_s4 * sf.dN4_dx) * 0.5;\n\tgp.e11 += de11;\n\tgp.e22 += de22;\n\tgp.e12 += de12;\n\n\t// update stress\n\tdouble E_tmp = gp.E / (1.0 + gp.niu) / (1.0 - 2.0 * gp.niu);\n\tds11 = E_tmp * ((1.0 - gp.niu) * de11 + gp.niu * de22);\n\tds22 = E_tmp * (gp.niu * de11 + (1.0 - gp.niu) * de22);\n\tds12 = 2.0 * gp.E / (2.0 * (1.0 + gp.niu)) * de12;\n\tgp.s11 += ds11;\n\tgp.s22 += ds22;\n\tgp.s12 += ds12;\n\t\n\t// volumetric strain of solid phase\n\tde_vol_s = de11 + de22;\n\t// \"volumetric strain\" of fluid phase\n\tde_vol_f = -(1.0 - gp.n) / gp.n * de_vol_s\n\t\t- (dux_f1 * sf.dN1_dx + dux_f2 * sf.dN2_dx + dux_f3 * sf.dN3_dx + dux_f4 * sf.dN4_dx)\n\t\t- (duy_f1 * sf.dN1_dy + duy_f2 * sf.dN2_dy + duy_f3 * sf.dN3_dy + duy_f4 * sf.dN4_dy);\n\t\n\t// porosity\n\t//gp.n = (de_vol_s + gp.n) / (1.0 + de_vol_s);\n\t// fluid density\n\t//gp.density_f += gp.density_f * de_vol_f;\n}\n", "meta": {"hexsha": "020fceacd11ada681fac24ce960b11e09a7fc708", "size": 15838, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SimulationCore/Step_S2D_CHM_s_FEM_uUp.cpp", "max_stars_repo_name": "MingAtUWA/SimpleMPM2", "max_stars_repo_head_hexsha": "7a1d7c257c621123d85a0630e93d42ae25c70fb4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SimulationCore/Step_S2D_CHM_s_FEM_uUp.cpp", "max_issues_repo_name": "MingAtUWA/SimpleMPM2", "max_issues_repo_head_hexsha": "7a1d7c257c621123d85a0630e93d42ae25c70fb4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SimulationCore/Step_S2D_CHM_s_FEM_uUp.cpp", "max_forks_repo_name": "MingAtUWA/SimpleMPM2", "max_forks_repo_head_hexsha": "7a1d7c257c621123d85a0630e93d42ae25c70fb4", "max_forks_repo_licenses": ["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.1175166297, "max_line_length": 101, "alphanum_fraction": 0.6627730774, "num_tokens": 6734, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.453091187349021}}
{"text": "#include <iostream>\n#include <Eigen/Sparse>\n\n\n\nint main(){\n\tEigen::Matrix<double, 4,4> A;\n\tEigen::VectorXd x;\n\tx.fill(0);\n\tint n = x.size();\n\n\tA=Eigen::MatrixXd::Random(4,4);\n\tA(0,1)=1;\n\tstd::cout << A << std::endl << n << std::endl;\n\t\n\treturn 0;\n\n}\n\n", "meta": {"hexsha": "89daecc8f955794d2f7a26f1fe55e638796d60a2", "size": 251, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/PS5/test.cpp", "max_stars_repo_name": "valentinjacot/backupETHZ", "max_stars_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T10:21:30.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-25T10:21:30.000Z", "max_issues_repo_path": "Nummerical Methods for CSE/PS5/test.cpp", "max_issues_repo_name": "valentinjacot/backupETHZ", "max_issues_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Nummerical Methods for CSE/PS5/test.cpp", "max_forks_repo_name": "valentinjacot/backupETHZ", "max_forks_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 12.55, "max_line_length": 47, "alphanum_fraction": 0.577689243, "num_tokens": 85, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4530911807301719}}
{"text": "#define BOOST_TEST_MODULE blas\n\n#include <boost/test/unit_test.hpp>\n#include <boost/test/test_case_template.hpp>\n#include <boost/mpl/list.hpp>\n\n\n#include <mla/vector/all.h++>\n\n#include <mla/operations/level1/axpy.h++>\n\n\ntypedef boost::mpl::list<\n\tmla::vector::Dense<float>,\n\tmla::vector::Dense<double>,\n\tmla::vector::SparseCS<float>,\n\tmla::vector::SparseCS<double>\n> vector_type_list;\n\n\n\nBOOST_AUTO_TEST_SUITE(test_boost_level1)\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( blas_level1_test_axpy_zero, VectorType, vector_type_list )\n{\n\tusing namespace mla;\n\n\tVectorType x(3);\n\tvector::Dense<typename VectorType::scalar_type > y(3);\n\n\ty.setZero();\n\t\n\ttypename VectorType::scalar_type value = 1.0f;\n\taxpy( value, x, y);\n\n\tfor( unsigned int i = 0; i < y.size(); i++)\n\t{\n\t\tBOOST_CHECK_CLOSE(y.getValue(i), 0.0f, 0.001f);\n\t}\n}\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( blas_level1_test_axpy_one, VectorType, vector_type_list )\n{\n\tusing namespace mla;\n\n\tVectorType x(3);\n\tx.setValue(0, 1.0f);\n\tx.setValue(1, 1.0f);\n\tx.setValue(2, 1.0f);\n\n\tvector::Dense<typename VectorType::scalar_type > y(3);\n\ty.setValue(0, 1.0f);\n\ty.setValue(1, 1.0f);\n\ty.setValue(2, 1.0f);\n\n\ttypename VectorType::scalar_type value = 1.0f;\n\taxpy( value, x, y);\n\n\tfor( unsigned int i = 0; i < y.size(); i++)\n\t{\n\t\tBOOST_CHECK_CLOSE(y.getValue(i), 2.0f, 0.001f);\n\t}\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n\n", "meta": {"hexsha": "f6299e5db2c5a8ad3bd7bc647a5d580e82ff8a4d", "size": 1338, "ext": "c++", "lang": "C++", "max_stars_repo_path": "unit_tests/test_blas_level1_axpy.c++", "max_stars_repo_name": "ruimaciel/mla", "max_stars_repo_head_hexsha": "b05f5913067af31a345cd2187de25871dbe31856", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "unit_tests/test_blas_level1_axpy.c++", "max_issues_repo_name": "ruimaciel/mla", "max_issues_repo_head_hexsha": "b05f5913067af31a345cd2187de25871dbe31856", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unit_tests/test_blas_level1_axpy.c++", "max_forks_repo_name": "ruimaciel/mla", "max_forks_repo_head_hexsha": "b05f5913067af31a345cd2187de25871dbe31856", "max_forks_repo_licenses": ["BSD-3-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.1142857143, "max_line_length": 89, "alphanum_fraction": 0.7085201794, "num_tokens": 419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4530911807301719}}
{"text": "#define PCL_NO_PRECOMPILE\n#include <pcl/visualization/cloud_viewer.h>\n#include <pcl/ModelCoefficients.h>\n#include <pcl/point_types.h>\n#include <pcl/io/pcd_io.h>\n#include <pcl/filters/extract_indices.h>\n#include <pcl/filters/voxel_grid.h>\n#include <pcl/features/normal_3d.h>\n#include <pcl/filters/conditional_removal.h>\n#include <pcl/kdtree/kdtree.h>\n#include <pcl/sample_consensus/method_types.h>\n#include <pcl/sample_consensus/model_types.h>\n#include <pcl/segmentation/sac_segmentation.h>\n#include <pcl/segmentation/extract_clusters.h>\n#include <thread>         // std::thread\n#include <mutex>          // std::mutex\n#include <chrono>\n\n#include <kitti_data_loader.h>\n#include <kitti_time_stamp_data.h>\n\n#include \"boost/program_options.hpp\"\n\n#include <Eigen/Core>\n\n#include \"ground_estimation.h\"\n#include <Eigen/Dense>\n#include <string>\n\n#include <sstream>\n\n#include <pcl_threaded_viewer.h>\n\nusing Ground = Eigen::Vector3f;\nusing GroundPlane = std::vector<Ground>;\nusing MasurementMat = Eigen::Vector3f;\nusing H = MasurementMat;\nusing cij = bool;\nusing C = std::vector<cij>;\nusing GP = std::vector<float>;\nusing F = Eigen::Matrix3f;\n\n#define GET_INDEX(x,y,n) ((y)*(n)+(x))\n\nfloat calculateHeightProbability(const PointXYZR p, const PointXYZGround Xi, const float sig_up_2, const float sig_down_2)\n{\n    Eigen::Vector3f hij(1.0f,Xi.x-p.x,Xi.y-p.y);\n    Eigen::Vector3f xi(Xi.z, Xi.sx, Xi.sy);\n    float dz = p.z - hij.transpose()*xi;\n    float prob = 0.0;\n    if(dz > 0)\n    {\n        prob = exp(-dz*dz/(2.0*sig_up_2));\n    }\n    else\n    {\n        prob = exp(-dz*dz/(2.0*sig_down_2));\n    }\n    return prob;\n}\n\nvoid calculateCloudProbability(PointXZYR_Cloud &cloud,const PointXZYGround_Cloud &Xi, float s1, float s2,float dl, float limit, int n)\n{\n    for (auto &point : cloud.points)\n    {\n        int nx = round((point.x+limit)/ dl);\n        int ny = round((point.y+limit)/ dl);\n        if(nx < 0 || nx >= n) continue;\n        if(ny < 0 || ny >= n) continue;\n        auto xi = Xi.points[GET_INDEX(nx,ny,n)];\n        float pc = calculateHeightProbability(point,xi,s1,s2);\n        //use r as the probability\n        point.r = pc;\n    }\n}\n\nvoid calculateNewXandP(PointXZYGround_Cloud &Xi_K_1, const PointXZYGround_Cloud &Xi_K, PointXZYGround_Cloud &Xi_K_m_1, const PointXZYR_Cloud &cloud, const PointXZYGround_Cloud &X, float dl, float limit, float alpha, float beta, float gamma, int n)\n{\n    for ( auto &xi : Xi_K_1.points)\n    {\n        xi.sx = 0;\n        xi.sy = 0;\n        xi.z = 0;\n    }\n\n    for (auto &point : cloud.points)\n    {\n        int nx = round((point.x + limit) / dl);\n        int ny = round((point.y + limit) / dl);\n        if (nx < 0 || nx >= n) continue;\n        if (ny < 0 || ny >= n) continue;\n        size_t index = GET_INDEX(nx, ny, n);\n        auto xi = Xi_K.points[index];\n        auto &xi_k_1 = Xi_K_1.points[index];\n        Eigen::Vector3f hij(1.0f, xi.x - point.x, xi.y - point.y);\n        Eigen::Vector3f result = alpha*point.r*point.z*hij;\n        xi_k_1.z += result(0);\n        xi_k_1.sx += result(1);\n        xi_k_1.sy += result(2);\n    }\n\n    for (auto &xi_k_1 : Xi_K_1.points)\n    {\n        int nx = round((xi_k_1.x + limit) / dl);\n        int ny = round((xi_k_1.y + limit) / dl);\n        if (nx < 0 || nx >= n) continue;\n        if (ny < 0 || ny >= n) continue;\n\n        if (nx - 1 > 0)\n        {\n            F f;\n            f << 1.0f, -dl, 0,\n                    0.0f, 1.0f, 0.0f,\n                    0.0f, 0.0f, 1.0f;\n            auto xi_1 = Xi_K.points[GET_INDEX(nx-1,ny,n)];\n            Eigen::Vector3f xi_k(xi_1.z, xi_1.sx, xi_1.sy);\n            Eigen::Vector3f result = beta*f.transpose()*xi_k;\n            xi_k_1.z += result(0);\n            xi_k_1.sx += result(1);\n            xi_k_1.sy += result(2);\n        }\n        if (nx + 1 < n)\n        {\n            F f;\n            f << 1.0f, dl, 0,\n                    0.0f, 1.0f, 0.0f,\n                    0.0f, 0.0f, 1.0f;\n            auto xi_1 = Xi_K.points[GET_INDEX(nx + 1, ny, n)];\n            Eigen::Vector3f xi_k(xi_1.z, xi_1.sx, xi_1.sy);\n            Eigen::Vector3f result = beta*f.transpose()*xi_k;\n            xi_k_1.z += result(0);\n            xi_k_1.sx += result(1);\n            xi_k_1.sy += result(2);\n        }\n\n        if (ny - 1 > 0)\n        {\n            F f;\n            f << 1.0f, 0, -dl,\n                    0.0f, 1.0f, 0.0f,\n                    0.0f, 0.0f, 1.0f;\n            auto xi_1 = Xi_K.points[GET_INDEX(nx , ny - 1, n)];\n            Eigen::Vector3f xi_k(xi_1.z, xi_1.sx, xi_1.sy);\n            Eigen::Vector3f result = beta*f.transpose()*xi_k;\n            xi_k_1.z += result(0);\n            xi_k_1.sx += result(1);\n            xi_k_1.sy += result(2);\n        }\n        if (ny + 1 < n)\n        {\n            F f;\n            f << 1.0f, 0, dl,\n                    0.0f, 1.0f, 0.0f,\n                    0.0f, 0.0f, 1.0f;\n            auto xi_1 = Xi_K.points[GET_INDEX(nx , ny + 1, n)];\n            Eigen::Vector3f xi_k(xi_1.z, xi_1.sx, xi_1.sy);\n            Eigen::Vector3f result = beta*f.transpose()*xi_k;\n            xi_k_1.z += result(0);\n            xi_k_1.sx += result(1);\n            xi_k_1.sy += result(2);\n        }\n\n        auto xi_k_m1 = Xi_K_m_1.points[GET_INDEX(nx, ny, n)];\n        xi_k_1.z += gamma*xi_k_m1.z;\n        xi_k_1.sx += gamma*xi_k_m1.sx;\n        xi_k_1.sy += gamma*xi_k_m1.sy;\n    }\n}\n\nstd::vector<std::string> getListFile(std::string path)\n{\n    std::vector<std::string> files;\n\n    if (!path.empty())\n    {\n        namespace fs = boost::filesystem;\n\n        fs::path apk_path(path);\n        fs::recursive_directory_iterator end;\n\n        for (fs::recursive_directory_iterator i(apk_path); i != end; ++i)\n        {\n            const fs::path cp = (*i);\n            files.push_back(cp.string());\n        }\n    }\n\n\n    std::sort(files.begin(), files.end(), [](const std::string &lhs, const std::string &rhs) { return lhs < rhs; });\n    return files;\n}\n\nint main (int argc, char** argv)\n{\n\n    namespace po = boost::program_options;\n\n    // Declare the supported options.\n    po::options_description desc(\"Allowed options\");\n    desc.add_options()\n            (\"help\", \"produce help message\")\n            (\"kitti_lidar_path\", po::value<std::string>(), \"set lidar data path\")\n            (\"kitti_oxts_path\", po::value<std::string>(), \"set oxs data path\")\n            (\"kitti_timestamp_file\", po::value<std::string>(), \"set time stamp fiel path\")\n            ;\n\n    po::variables_map vm;\n    po::store(po::parse_command_line(argc, argv, desc), vm);\n    po::notify(vm);\n\n    if (vm.count(\"help\")) {\n        std::cout << desc << \"\\n\";\n        return 0;\n    }\n\n    if (vm.count(\"kitti_lidar_path\")) {\n        std::cout << \"Kitti LiDAR Data Path was set to \"\n                  << vm[\"kitti_lidar_path\"].as<std::string>() << \".\\n\";\n    } else {\n        std::cout << \"Kitti Data Path was not set.\\n\";\n        return 1;\n    }\n\n    if (vm.count(\"kitti_oxts_path\")) {\n        std::cout << \"Kitti OXS Data Path was set to \"\n                  << vm[\"kitti_oxts_path\"].as<std::string>() << \".\\n\";\n    } else {\n        std::cout << \"Kitti OXS Data Path was not set.\\n\";\n        return 1;\n    }\n\n    if (vm.count(\"kitti_timestamp_file\")) {\n        std::cout << \"Kitti TimeStamp fiel was set to \"\n                  << vm[\"kitti_timestamp_file\"].as<std::string>() << \".\\n\";\n    } else {\n        std::cout << \"Kitti TimeStamp file was not set.\\n\";\n        return 1;\n    }\n\n    int nx = 100;\n    int ny = 100;\n    int N = nx*ny;\n    float dl = .50;\n    float x_limit = nx*dl/2;\n    float y_limit = ny*dl/2;\n\n    F f;\n    f << 1.0f, -dl, -dl,\n            0.0f, 1.0f, 0.0f,\n            0.0f, 0.0f, 1.0f;\n\n    float sig_up_2 = .05*.05;\n    float sig_down_2 = .5*.5;\n\n    PointXZYGround_Cloud ground_cloud;\n    ground_cloud.width    = nx;\n    ground_cloud.height   = ny;\n    ground_cloud.is_dense = true;\n    ground_cloud.points.resize (nx * ny);\n    PointXZYGround_Cloud X_cloud;\n    X_cloud.width    = nx;\n    X_cloud.height   = ny;\n    X_cloud.is_dense = true;\n    X_cloud.points.resize (nx * ny);\n    PointXZYGround_Cloud P_cloud;\n    P_cloud.width    = nx;\n    P_cloud.height   = ny;\n    P_cloud.is_dense = true;\n    P_cloud.points.resize (nx * ny);\n    pcl::PointCloud<PointXYZR> prob_cloud;\n    for(int y = 0; y < ny;y++)\n    {\n        float ly = dl*y-y_limit;\n        for(int x = 0; x < nx;x++)\n        {\n            float lx = dl*x-x_limit;\n            PointXYZGround p{lx,ly,0.0,0.0,0.0};\n            ground_cloud.points[GET_INDEX(x,y,nx)] = p;\n            X_cloud.points[GET_INDEX(x,y,nx)] = p;\n            P_cloud.points[GET_INDEX(x,y,nx)] = p;\n        }\n    }\n    PLCVisualizerWorker worker;\n    worker.run();\n    auto files = getListFile(vm[\"kitti_lidar_path\"].as<std::string>());\n    auto gps_files = getListFile(vm[\"kitti_oxts_path\"].as<std::string>());\n\n    int counter = 0;\n    KITTITimeStampData time_stamp_loader{vm[\"kitti_timestamp_file\"].as<std::string>()};\n\n    auto timestamps = time_stamp_loader.run();\n\n    auto format = [](float data)\n    {\n        return std::to_string(data);\n    };\n\n    auto format_time = [](const KITTITimeStamp &stamp)->std::string\n    {\n        char buff[100];\n        strftime (buff, 100, \"%F %H:%M:%S.\", &stamp.tm);\n        long nanoseconds = stamp.nanoseconds.count();\n        return std::string(buff)+std::to_string(nanoseconds);\n    };\n    for (auto file : files)\n    {\n        // Read in the cloud data\n        //pcl::PCDReader reader;\n        pcl::PointCloud<PointXYZR>::Ptr cloud_f(new pcl::PointCloud<PointXYZR>);\n        //reader.read (\"table_scene_lms400.pcd\", *cloud);\n        KITTIDataLoader loader{ file };\n        KITTIIMUGPSData gps{gps_files[counter]};\n        auto gps_map = gps.run();\n        pcl::PointCloud<PointXYZR>::Ptr cloud = loader.run();\n        pcl::PointCloud<PointXYZR>::Ptr cloud_filtered(new pcl::PointCloud<PointXYZR>);\n        pcl::PointCloud<PointXYZR>::Ptr cloud_remaining(new pcl::PointCloud<PointXYZR>);\n        // Create the filtering object: filter data to 100x100 m area\n        pcl::ConditionAnd<PointXYZR>::Ptr range_cond(new pcl::ConditionAnd<PointXYZR>());\n        range_cond->addComparison(pcl::FieldComparison<PointXYZR>::Ptr(new pcl::FieldComparison<PointXYZR>(\"x\", pcl::ComparisonOps::LT, x_limit)));\n        range_cond->addComparison(pcl::FieldComparison<PointXYZR>::Ptr(new pcl::FieldComparison<PointXYZR>(\"x\", pcl::ComparisonOps::GT, -x_limit)));\n        range_cond->addComparison(pcl::FieldComparison<PointXYZR>::Ptr(new pcl::FieldComparison<PointXYZR>(\"y\", pcl::ComparisonOps::LT, y_limit)));\n        range_cond->addComparison(pcl::FieldComparison<PointXYZR>::Ptr(new pcl::FieldComparison<PointXYZR>(\"y\", pcl::ComparisonOps::GT, -y_limit)));\n        pcl::ConditionalRemoval<PointXYZR> range_filt;\n        range_filt.setCondition(range_cond);\n        range_filt.setInputCloud(cloud);\n        range_filt.setKeepOrganized(false);\n\n        // The indices_x array indexes all points of cloud_in that have x between 0.0 and 1000.0\n        range_filt.filter(*cloud_filtered);\n        // The indices_rem array indexes all points of cloud_in that have x smaller than 0.0 or larger than 1000.0\n        //indices_rem = range_filt.getRemovedIndices ();\n\n        //viewer.addPointCloud<PointXYZR> (cloud, \"cloud\");\n        pcl::visualization::PointCloudColorHandlerCustom<PointXYZR>::Ptr plane_color_handler{ new pcl::visualization::PointCloudColorHandlerCustom<PointXYZR>(cloud, 255, 0, 255) };\n        pcl::visualization::PointCloudColorHandlerCustom<PointXYZR>::Ptr off_scene_model_color_handler{ new pcl::visualization::PointCloudColorHandlerCustom<PointXYZR>(cloud_filtered, 0, 255, 255) };\n        //viewer.setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 5, \"cloud_filtered\");\n        //viewer.setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 5, \"cloud\");\n        worker.addCloud(cloud, plane_color_handler,\"cloud\");\n        worker.addCloud(cloud_filtered, off_scene_model_color_handler, \"cloud_filtered\");\n\n        PCLTextInfo info = { file,0,0 };\n        PCLTextInfo lat = { format(gps_map[\"vf\"]),0,20 };\n        PCLTextInfo lon = { format(gps_map[\"vl\"]),0,40 };\n\n        auto tm = timestamps.at(counter);\n        PCLTextInfo time = { format_time(tm),0,60 };\n\n        worker.addText(\"File\",info);\n        worker.addText(\"vf\", lat);\n        worker.addText(\"vl\", lon);\n        worker.addText(\"timestamp\", time);\n        std::cout << \"File: \" << file << std::endl;\n        for (auto pair : gps_map)\n        {\n            //std::cout << pair.first << \" : \" << pair.second << std::endl;\n        }\n\n        std::cout << \"Time: \" << format_time(tm) << std::endl;\n\n        ++counter;\n\n    }\n    while (!worker.wasStopped())\n    {\n        std::this_thread::sleep_for(std::chrono::milliseconds(100));\n    }\n    // worker.stop();\n    while (!worker.wasStopped())\n    {\n        std::cout << \"Waiting to stop\" << std::endl;\n    }\n\n    return (0);\n}\n", "meta": {"hexsha": "9eb2924f759a1af2f385298cb8d3d2d54ab18aa9", "size": 12911, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ground_estimation.cpp", "max_stars_repo_name": "oscarazucena/pcl_test", "max_stars_repo_head_hexsha": "a55a5bd1b0db2697ed15ed41d3a20f4558afb926", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-03-05T01:19:28.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-05T01:19:28.000Z", "max_issues_repo_path": "src/ground_estimation.cpp", "max_issues_repo_name": "oscarazucena/pcl_test", "max_issues_repo_head_hexsha": "a55a5bd1b0db2697ed15ed41d3a20f4558afb926", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ground_estimation.cpp", "max_forks_repo_name": "oscarazucena/pcl_test", "max_forks_repo_head_hexsha": "a55a5bd1b0db2697ed15ed41d3a20f4558afb926", "max_forks_repo_licenses": ["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.4293333333, "max_line_length": 247, "alphanum_fraction": 0.5831461544, "num_tokens": 3737, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4530911807301719}}
{"text": "#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_int_distribution.hpp>\n\nint main()\n{\n  boost::random::mt19937 gen;\n  boost::random::uniform_int_distribution<> dist(1, 6);\n\n  if (dist(gen) > 6) {\n    return 1;\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "fdd339f8e5eda33e6555d9bc50e90d8278030e60", "size": 255, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/random_test.cc", "max_stars_repo_name": "cirrostratus1/rules_boost", "max_stars_repo_head_hexsha": "8a084196b14a396b6d4ff7c928ffbb6621f0d32c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 214.0, "max_stars_repo_stars_event_min_datetime": "2016-08-24T01:08:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T02:24:55.000Z", "max_issues_repo_path": "test/random_test.cc", "max_issues_repo_name": "cirrostratus1/rules_boost", "max_issues_repo_head_hexsha": "8a084196b14a396b6d4ff7c928ffbb6621f0d32c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 184.0, "max_issues_repo_issues_event_min_datetime": "2017-01-20T22:43:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T16:26:45.000Z", "max_forks_repo_path": "test/random_test.cc", "max_forks_repo_name": "cirrostratus1/rules_boost", "max_forks_repo_head_hexsha": "8a084196b14a396b6d4ff7c928ffbb6621f0d32c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 258.0, "max_forks_repo_forks_event_min_datetime": "2016-08-24T01:08:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T18:07:16.000Z", "avg_line_length": 17.0, "max_line_length": 55, "alphanum_fraction": 0.6862745098, "num_tokens": 75, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.754914975839675, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.45309118073017185}}
{"text": "#include <bits/stdc++.h>\nusing namespace std;\n// --------------------------------------------------------\n\n// reference: https://boostjp.github.io/tips/multiprec-int.html\n#include <boost/multiprecision/cpp_int.hpp>\ntypedef boost::multiprecision::cpp_int bint;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n    cout << fixed << setprecision(15);\n\n    bint A; cin >> A;\n    bint B; cin >> B;\n\n    bint ans = A + B;\n    cout << ans << '\\n';\n\n    return 0;\n}\n// Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=NTL_2_A&lang=ja\n//     please use language: C++11 (not C++17)\n", "meta": {"hexsha": "2949b77b1e3e8bfa881c8388fa06e6cf64f9950f", "size": 602, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/lib/other/big_integer.cpp", "max_stars_repo_name": "KATO-Hiro/atcoder-1", "max_stars_repo_head_hexsha": "c2cbfcfd5c3d46ac9810ba330a37d437aa2839c2", "max_stars_repo_licenses": ["MIT"], "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/lib/other/big_integer.cpp", "max_issues_repo_name": "KATO-Hiro/atcoder-1", "max_issues_repo_head_hexsha": "c2cbfcfd5c3d46ac9810ba330a37d437aa2839c2", "max_issues_repo_licenses": ["MIT"], "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/lib/other/big_integer.cpp", "max_forks_repo_name": "KATO-Hiro/atcoder-1", "max_forks_repo_head_hexsha": "c2cbfcfd5c3d46ac9810ba330a37d437aa2839c2", "max_forks_repo_licenses": ["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.0833333333, "max_line_length": 83, "alphanum_fraction": 0.5764119601, "num_tokens": 165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.754914975839675, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.45309118073017185}}
{"text": "#include <cmath>\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <complex>\n#include <algorithm>\n#include <chrono>\n#include <boost/program_options.hpp>\n#include <boost/spirit/include/karma.hpp>\n#include <boost/container/flat_map.hpp>\n#include <sndfile.h>\n#include <OpenImageIO/imageio.h>\n#ifdef ENABLE_CUDA\n#include <cufft.h>\n#include <cufftXt.h>\n#else\n#include <fftw3.h>\n#endif\n\nstruct fft_failed : public std::runtime_error {\n  fft_failed( const std::string &what ) : std::runtime_error( what ) {}\n  fft_failed( const char *what ) : std::runtime_error( what ) {}\n};\n\nstruct fft_initialization_failed : public fft_failed {\n  fft_initialization_failed( const std::string &what ) : fft_failed( what ) {}\n  fft_initialization_failed( const char *what ) : fft_failed( what ) {}\n};\nstruct fft_allocation_failed : public fft_failed {\n  fft_allocation_failed( const std::string &what ) : fft_failed( what ) {}\n  fft_allocation_failed( const char *what ) : fft_failed( what ) {}\n};\nstruct fft_execution_failed : public fft_failed {\n  fft_execution_failed( const std::string &what ) : fft_failed( what ) {}\n  fft_execution_failed( const char *what ) : fft_failed( what ) {}\n};\nstruct fft_data_transfar_failed : public fft_failed {\n  fft_data_transfar_failed( const std::string &what ) : fft_failed( what ) {}\n  fft_data_transfar_failed( const char *what ) : fft_failed( what ) {}\n};\n\n#ifdef ENABLE_CUDA\n\n#define checkCudaErrors( expr, exception ) \\\n{ \\\n  auto cuda_result = expr; \\\n  if( cuda_result != cudaSuccess ) \\\n    throw exception ( cudaGetErrorString( cudaGetLastError() ) ); \\\n}\n\n#define checkCuFFTErrors( expr, exception ) \\\n{ \\\n  auto cuda_result = expr; \\\n  if( cuda_result != CUFFT_SUCCESS ) \\\n    throw exception ( cudaGetErrorString( cudaGetLastError() ) ); \\\n}\n\nstruct fft_detail {\n  float *window;\n  size_t resolution;\n  size_t interval;\n  size_t width;\n  float *envelope;\n};\n\n__device__ inline void atomicAdd(float* address, float value) {\n  while( ( old = atomicExch( address, atomicExch( address, 0.0f ) + old ) ) != 0.0f );\n}\n\n__device__ cufftReal input_cb(\n  void *src, \n  size_t offset, \n  void *callerInfo, \n  void *sharedPtr\n) {\n  fft_detail *detail = (fft_detail*)callerInfo;\n  size_t index = offset % detail->resolution;\n  size_t batch = offset / detail->resolution;\n  int16_t element = ((int16_t*)src)[ index + batch * detail->interval ];\n  return ( cufftReal )( element/32767.f * detail->window[ index ] );\n}\n\n__device__ void output_cb(\n  void *dataOut, \n  size_t offset, \n  cufftComplex element, \n  void *callerInfo, \n  void *sharedPtr\n) {\n  fft_detail *detail = (fft_detail*)callerInfo;\n  size_t index = offset % ( (detail->resolution/2) + 1 );\n  size_t batch = offset / ( (detail->resolution/2) + 1 );\n  if( index < detail->width ) {\n    float abs = cuCabsf( element );\n    atomicAdd( detail->envelope + detail->width * batch, abs );\n    ( (float*)dataOut )[ index + detail->width * batch ] = abs;\n  }\n}\n\n__device__ cufftCallbackLoadR input_cb_ptr_d = input_cb; \n__device__ cufftCallbackStoreC output_cb_ptr_d = output_cb;\n\n__global__ void generate_window( fft_detail *detail ) {\n  size_t index = threadIdx.x + blockIdx.x * 1024;\n  detail->window[ index ] = sinf( float( M_PI ) * float( index ) / detail->resolution ); \n}\n\n__global__ void generate_window( float *window, unsigned int resolution ) {\n  size_t index = threadIdx.x + blockIdx.x * 1024;\n  window[ index ] = sinf( float( M_PI ) * float( index ) / resolution ); \n}\n\nusing window_list_t = boost::container::flat_map< unsigned int, std::shared_ptr< float > >;\n\nwindow_list_t generate_window() {\n  window_list_t result;\n  for( unsigned int i = 16u; i != 65536u; i <<= 1 ) {\n    float *window;\n    checkCudaErrors( cudaMalloc( &window, sizeof(float)*i ), fft_allocation_failed );\n    std::shared_ptr< float > wrapped( window, &cudaFree );\n    if( i > 1024 ) generate_window<<< i/1024, 1024 >>>( window, i );\n    else generate_window<<< 1, i >>>( window, i );\n    result.insert( result.end(), std::make_pair( i, wrapped ) );\n  }\n  checkCudaErrors( cudaDeviceSynchronize(), fft_initialization_failed );\n  return std::move( result );\n}\n\nstd::vector< float > fft( const window_list_t &window, const std::vector< int16_t > &data, size_t resolution, size_t interval, size_t width ) {\n  const auto window_iter = window.find( resolution );\n  if( window_iter == window.end() ) throw fft_initialization_failed( \"invalid resolution\" );\n  const size_t batch = ( data.size() - resolution )/interval + 1;\n  int16_t *envelope;\n  checkCudaErrors(cudaMalloc( &envelope, sizeof(float)*batch), fft_allocation_failed );\n  std::shared_ptr< float > wrapped_envelope( envelope, &cudaFree );\n  checkCudaErrors( cudaMemset( envelope, 0, batch * sizeof(float) ), fft_initialization_failed );\n  fft_detail *detail;\n  checkCudaErrors(cudaMallocManaged( &detail, sizeof(fft_detail),cudaMemAttachGlobal), fft_allocation_failed );\n  std::shared_ptr< fft_detail > wrapped_detail( detail, &cudaFree );\n  detail->resolution = resolution;\n  detail->interval = interval;\n  detail->width = width;\n  detail->window = window_iter->second.get();\n  detail->envelope = envelope;\n  int16_t *input;\n  checkCudaErrors(cudaMalloc( &input, sizeof(int16_t)*data.size()), fft_allocation_failed );\n  std::shared_ptr< int16_t > wrapped_input( input, &cudaFree );\n  checkCudaErrors(cudaMemcpy( input, data.data(), sizeof(int16_t)*data.size(), cudaMemcpyHostToDevice ), fft_data_transfar_failed );\n  float *output;\n  checkCudaErrors(cudaMalloc( &output, sizeof(float)*width*batch), fft_allocation_failed );\n  std::shared_ptr< float > wrapped_output( output, &cudaFree );\n  cufftHandle plan;\n  checkCuFFTErrors( cufftCreate( &plan ), fft_initialization_failed );\n  int signal_size = resolution;\n  size_t work_size;\n  checkCuFFTErrors( cufftMakePlanMany( plan, 1, &signal_size, 0, 0, 0, 0, 0, 0, CUFFT_R2C, batch, &work_size ), fft_initialization_failed );\n  cufftCallbackLoadR input_cb_ptr_h;\n  checkCudaErrors( cudaMemcpyFromSymbol( &input_cb_ptr_h, input_cb_ptr_d, sizeof( cufftCallbackLoadR ) ), fft_data_transfar_failed );\n  cufftCallbackStoreC output_cb_ptr_h;\n  checkCudaErrors( cudaMemcpyFromSymbol( &output_cb_ptr_h, output_cb_ptr_d, sizeof( cufftCallbackStoreC ) ), fft_data_transfar_failed );\n  checkCuFFTErrors( cufftXtSetCallback( plan, (void **)&input_cb_ptr_h, CUFFT_CB_LD_REAL, (void **)&detail ), fft_initialization_failed );\n  checkCuFFTErrors( cufftXtSetCallback( plan, (void **)&output_cb_ptr_h, CUFFT_CB_ST_COMPLEX, (void **)&detail ), fft_initialization_failed );\n  checkCuFFTErrors( cufftExecR2C( plan, (cufftReal*)input, (cufftComplex *)output ), fft_execution_failed );\n  std::vector< float > result( width*batch );\n  checkCudaErrors( cudaDeviceSynchronize(), fft_execution_failed );\n  checkCudaErrors(cudaMemcpy( result.data(), output, sizeof(float)*width*batch, cudaMemcpyDeviceToHost ),fft_data_transfar_failed);\n  return std::move( result );\n}\n#else\nusing window_list_t = boost::container::flat_map< unsigned int, std::vector< float > >;\n\nwindow_list_t generate_window() {\n  window_list_t result;\n  for( unsigned int i = 16u; i != 65536u; i <<= 1 ) {\n    float *window;\n    std::vector< float > w( i );\n    for( unsigned int j = 0u; j != i; ++j )\n      w[ j ] = sinf( float( M_PI ) * float( j ) / i );\n    result.insert( result.end(), std::make_pair( i, std::move( w ) ) );\n  }\n  return std::move( result );\n}\n\nstd::vector< float > fft( const window_list_t &window, const std::vector< int16_t > &data, size_t resolution, size_t interval, size_t width ) {\n  const auto window_iter = window.find( resolution );\n  if( window_iter == window.end() ) throw fft_initialization_failed( \"invalid resolution\" );\n  const size_t batch = ( data.size() - resolution )/interval + 1;\n  std::shared_ptr< float > input( (float*)fftwf_malloc(sizeof(float)*resolution), &fftwf_free );\n  if( !input ) throw fft_allocation_failed( \"unable to allocate memory for input\" );\n  std::shared_ptr< fftwf_complex > output( (fftwf_complex*)fftwf_malloc(sizeof(fftwf_complex)*resolution), &fftwf_free );\n  if( !output ) throw fft_allocation_failed( \"unable to allocate memory for output\" );\n  std::vector< float > result;\n  fftwf_plan plan = fftwf_plan_dft_r2c_1d( resolution, input.get(), output.get(), FFTW_ESTIMATE );\n  if( !plan ) fft_initialization_failed( \"unable to create the plan\" );\n  for( size_t current_batch = 0u; current_batch != batch; ++current_batch ) {\n    for( size_t i = 0u; i != resolution; ++i )\n      input.get()[ i ] = data[ i + current_batch * interval ]/32767.f * window_iter->second[ i ];\n    fftwf_execute( plan );\n    for( size_t i = 0u; i != width; ++i )\n      result.push_back( std::abs( std::complex< float >( output.get()[ i ][ 0 ], output.get()[ i ][ 1 ] ) ) );\n  }\n  fftwf_destroy_plan( plan );\n  return std::move( result );\n}\n\n#endif\n\nfloat accumulate( const std::vector< float > &input, int x, float kp, const std::vector< std::tuple< int, float > > &window ) {\n  float sum = std::accumulate(\n    window.begin(), window.end(), 0.f,\n    [&]( float s, const std::tuple< int, float > &v ) -> float {\n      int pos = x + std::get< 0 >( v );\n      if( pos < 0 || pos >= input.size() ) return s;\n      else return s + std::get< 1 >( v ) * input[ x + std::get< 0 >( v ) ];\n    }\n  );\n  return sum / kp;\n}\n\nstd::tuple< int, int, int > segment_envelope( const std::vector< float > &input, unsigned int sample_rate ) {\n  std::vector< float > grad;\n  for( size_t i = 1u; i != input.size(); ++i )\n    grad.emplace_back( ( input[ i ] - input[ i - 1u ] )*sample_rate );\n  std::vector< float > release( input.size(), 0 );\n  const auto blank = std::distance(\n    input.rbegin(),\n    std::find_if( input.rbegin(), input.rend(), []( float v ) { return v != 0; } )\n  ) + 1;\n  float min_grad = std::abs( grad[ input.size() - ( 1 + blank ) ] );\n  for( size_t i = 1u; i != input.size() - blank; ++i ) {\n    min_grad = std::min( min_grad, std::max( 0.f, -grad[ input.size() - ( i + blank ) ] ) );\n    release[ input.size() - ( i + blank ) ] = min_grad * ( float( i ) / sample_rate );\n  }\n  const auto release_pos = std::distance( release.begin(), std::max_element( release.begin(), release.end() ) );\n  float delay = 0.f;\n  const float max = *std::max_element( input.begin(), std::next( input.begin(), release_pos ) );\n  const auto p0 = std::find_if( input.begin(), std::next( input.begin(), release_pos ), [&]( float v ){ return v >= max * 0.2f; } );\n  const auto p1 = std::find_if( input.begin(), std::next( input.begin(), release_pos ), [&]( float v ){ return v >= max * 0.4f; } );\n  const auto tangent = float( std::distance( p0, p1 ) )/( *p1 - *p0 );\n  const auto intercept = float( std::distance( input.begin(), p0 ) ) - tangent * *p0;\n  const int delay_pos = std::max( int( intercept ), 0 );\n  std::vector< float > attack( input.size(), 0 );\n  min_grad = 1.f/tangent;\n  for( size_t i = 0u; i != release_pos - delay_pos; ++i ) {\n    min_grad = std::min( min_grad, std::max( 0.f, grad[ i + delay_pos ] ) );\n    attack[ i + delay_pos ] = min_grad * ( float( i ) / sample_rate );\n  }\n  const auto attack_pos = std::distance( attack.begin(), std::max_element( attack.begin(), attack.end() ) );\n  std::cout << attack_pos << \" \" << release_pos << std::endl;\n  return std::make_tuple( delay_pos, attack_pos, release_pos );\n}\n\nfloat rect( float x ) {\n  x -= floorf( x );\n  if( x < 0.5f ) return -1.f;\n  else return 1.f;\n}\n\nfloat tri( float x ) {\n  x -= floorf( x );\n  if( x < 0.25f ) return 4.f*x;\n  else if( x < 0.75f ) return -4.f*x+2.f;\n  else return 4.f*x-4.f;\n}\n\nstd::vector< int16_t > load_monoral( const std::string &filename, bool norm ) {\n  SF_INFO info;\n  info.frames = 0;\n  info.samplerate = 0;\n  info.channels = 0;\n  info.format = 0;\n  info.sections = 0;\n  info.seekable = 0;\n  std::cout << filename << std::endl;\n  auto audio_file = sf_open( filename.c_str(), SFM_READ, &info );\n  if( !audio_file ) {\n    std::cerr << \"Unable to open audio file\" << std::endl;\n    throw -1;\n  }\n  std::vector< int16_t > monoral;\n  std::vector< int16_t > multi_channel;\n  multi_channel.resize( info.frames * info.channels );\n  const auto read_count = sf_read_short( audio_file, multi_channel.data(), info.frames * info.channels );\n  if( read_count == 0u ) {\n    std::cerr << \"Unable to read audio file\" << std::endl;\n    throw -1;\n  }\n  sf_close( audio_file );\n  if( read_count % info.channels != 0 ) {\n    std::cerr << \"Invalid audio file\" << std::endl;\n    throw -1;\n  }\n  multi_channel.resize( read_count );\n  monoral.reserve( read_count / info.channels );\n  for( auto iter = multi_channel.begin(); iter != multi_channel.end(); ) {\n    auto next_iter = std::next( iter, info.channels );\n    monoral.emplace_back( std::accumulate( iter, next_iter, int16_t( 0 ) ) / info.channels );\n    iter = next_iter;\n  }\n  const auto audio_begin = std::find_if( monoral.begin(), monoral.end(), []( int16_t v ) { return v != 0; } );\n  std::cout << std::distance( monoral.begin(), audio_begin ) << std::endl;\n  monoral.erase( monoral.begin(), audio_begin );\n  const auto max_iter = std::max_element( monoral.begin(), monoral.end() );\n  const auto min_iter = std::min_element( monoral.begin(), monoral.end() );\n  const int16_t max =\n    std::max(\n      ( max_iter != monoral.end() ) ? std::abs( *max_iter ) : int16_t( 0 ),\n      ( min_iter != monoral.end() ) ? std::abs( *min_iter ) : int16_t( 0 )\n    );\n  if( norm ) {\n    if( max != 0 ) {\n      for( auto &elem: monoral )\n        elem = int32_t( elem ) * 32768 / max;\n    }\n  }\n  return monoral;\n}\n\nstruct spectrum_image {\n  spectrum_image(\n    const window_list_t &window,\n    const std::vector< int16_t > &audio,\n    int x_,\n    uint8_t note,\n    unsigned int sample_rate_,\n    uint32_t resolution_,\n    uint32_t interval_,\n    bool delayed\n  ) : x( x_ ), resolution( resolution_ ), interval( interval_ ), sample_rate( sample_rate_ ) {\n    y = audio.size() / ( sample_rate / interval );\n    const int channels = 3;\n    pixels.reserve( x * y * channels );\n    const float freq = exp2f( ( ( float( note ) +  3.f ) / 12.f ) ) * 6.875f;\n    std::vector< uint32_t > harmonic;\n    for( size_t i = 0u; i != 16u; ++ i ) {\n      harmonic.emplace_back( ceilf( freq * std::pow( 2.f, float( i ) ) * float( resolution ) * 2.f /float( sample_rate ) ) );\n    }\n    uint32_t base = harmonic.front();\n    std::cout << \"base : \" << base << std::endl;\n    size_t offset = 0;\n    size_t y_pos = 0;\n    size_t mute_since = 0;\n    const auto converted = fft( window, audio, resolution, sample_rate/interval, x );\n    const auto begin_date = std::chrono::high_resolution_clock::now();\n    for( auto iter = converted.begin(); iter != converted.end(); iter += x ) {\n      auto end = std::next( iter, x );\n      if( !delayed || ( x > base && *std::next( iter, base ) != 0 ) ) {\n        delayed = false;\n        auto harmonic_iter = harmonic.begin();\n        size_t x_pos = 0;\n        for( const auto &l : boost::make_iterator_range( iter, std::next( iter, x ) ) ) {\n          const auto p = uint8_t( std::min( std::max( 80.f * std::log10( std::max( l, 1.f ) ), 0.f ), 255.f ) );\n          if( *harmonic_iter == x_pos ) {\n            pixels.emplace_back( 128 + p / 2 );\n            pixels.emplace_back( p );\n            pixels.emplace_back( p );\n            ++harmonic_iter;\n          }\n          else if( y_pos % interval == 0 ) {\n            pixels.emplace_back( 128 + p / 2 );\n            pixels.emplace_back( p );\n            pixels.emplace_back( p );\n          }\n          else {\n            pixels.emplace_back( p );\n            pixels.emplace_back( p );\n            pixels.emplace_back( p );\n          }\n          ++x_pos;\n        }\n        envelope.emplace_back( std::accumulate( iter, end, 0.f ) );\n        ++y_pos;\n        if( std::find_if( iter, end, []( float v ) { return v != 0; } ) != end ) mute_since = y_pos;\n      }\n      else --y;\n    }\n    const auto end_date = std::chrono::high_resolution_clock::now();\n    std::cout << \"Elapsed: \" << std::chrono::duration_cast< std::chrono::microseconds >( end_date - begin_date ).count() << \"us\" << std::endl;\n    pixels.resize( x * mute_since * channels );\n  }\n  std::vector< float > envelope;\n  std::vector< uint8_t > pixels;\n  int x;\n  int y;\n  uint32_t resolution;\n  uint32_t interval;\n  uint32_t sample_rate;\n};\n\n\nint main( int argc, char* argv[] ) {\n  boost::program_options::options_description options(\"\u30aa\u30d7\u30b7\u30e7\u30f3\");\n  options.add_options()\n    (\"help,h\",    \"\u30d8\u30eb\u30d7\u3092\u8868\u793a\")\n    (\"input,i\", boost::program_options::value<std::string>(),  \"\u5165\u529b\u30d5\u30a1\u30a4\u30eb\")\n    (\"output,o\", boost::program_options::value<std::string>(),  \"\u51fa\u529b\u30d5\u30a1\u30a4\u30eb\")\n    (\"envelope,e\", boost::program_options::value<std::string>(),  \"\u30a8\u30f3\u30d9\u30ed\u30fc\u30d7\")\n    (\"note,n\", boost::program_options::value<int>()->default_value(60),  \"\u97f3\u968e\")\n    (\"width,w\", boost::program_options::value<int>()->default_value(1024),  \"\u5e45\")\n    (\"resolution,r\", boost::program_options::value<int>()->default_value(13),  \"\u5206\u89e3\u80fd\")\n    (\"interval,j\", boost::program_options::value<int>()->default_value(100),  \"\u9593\u9694\");\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\") || !params.count(\"input\") || !params.count(\"output\") || !params.count( \"note\" ) || !params.count( \"envelope\" ) ) {\n    std::cout << options << std::endl;\n    return 0;\n  }\n  const std::string input_filename = params[\"input\"].as<std::string>();\n  const std::string output_filename = params[\"output\"].as<std::string>();\n  const auto audio = load_monoral( input_filename, true );\n  const int x = params[\"width\"].as<int>();\n  const auto window = generate_window();\n  const spectrum_image image( window, audio, x, params[\"note\"].as<int>(), 44100, 1 << params[\"resolution\"].as<int>(), params[\"interval\"].as<int>(), true );\n  const int channels = 3;\n  using namespace OIIO_NAMESPACE;\n  ImageOutput *out = ImageOutput::create( output_filename );\n  if ( !out ) {\n    std::cerr << \"Unable to open output file\" << std::endl;\n    return -1;\n  }\n  ImageSpec spec ( image.x, image.y, channels, TypeDesc::UINT8);\n  out->open( output_filename, spec );\n  out->write_image( TypeDesc::UINT8, image.pixels.data() );\n out->close();\n\n  std::fstream envelope_file( params[\"envelope\"].as<std::string>(), std::ios::out );\n  for( int i = 0; i != image.envelope.size(); ++i ) {\n    std::string line;\n    namespace karma = boost::spirit::karma;\n    karma::generate( std::back_inserter( line ), karma::float_ << '\\t' << karma::float_ << karma::eol, boost::fusion::make_vector( float( i )/image.interval, image.envelope[ i ] ) );\n    envelope_file.write( line.c_str(), line.size() );\n  }\n  envelope_file.close();\n  const auto grad = segment_envelope( image.envelope, image.interval );\n  std::cout << \"delay : \" << std::get< 0 >( grad )/float( image.interval ) << std::endl;\n  std::cout << \"attack : \" << std::get< 1 >( grad )/float( image.interval ) << std::endl;\n  std::cout << \"release : \" << std::get< 2 >( grad )/float( image.interval ) << std::endl;\n//  for( size_t i = 0; i != grad.size(); ++i )\n//    std::cout << i * 0.01f << \" \" << grad[ i ] << \" \" << image.envelope[ i ] << std::endl;\n//  ImageOutput::destroy( out );\n}\n\n", "meta": {"hexsha": "5c293fae9e3d4ddf4bc2f0e9d12adbd43e519c4e", "size": 19174, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/wav2image.cpp", "max_stars_repo_name": "Fadis/genetic_fm", "max_stars_repo_head_hexsha": "415158b02e2c0dad8fafc81b5762b8889e493f10", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2016-10-08T08:55:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-17T03:19:54.000Z", "max_issues_repo_path": "src/wav2image.cpp", "max_issues_repo_name": "Fadis/genetic_fm", "max_issues_repo_head_hexsha": "415158b02e2c0dad8fafc81b5762b8889e493f10", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/wav2image.cpp", "max_forks_repo_name": "Fadis/genetic_fm", "max_forks_repo_head_hexsha": "415158b02e2c0dad8fafc81b5762b8889e493f10", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-06-21T00:06:30.000Z", "max_forks_repo_forks_event_max_datetime": "2018-06-21T00:06:30.000Z", "avg_line_length": 43.1846846847, "max_line_length": 182, "alphanum_fraction": 0.6503077084, "num_tokens": 5517, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.9059898178450964, "lm_q2_score": 0.5, "lm_q1q2_score": 0.4529949089225482}}
{"text": "// Component\n#include \"RosConversionHelper.hpp\"\n\n// Ros\n#include <tf/tf.h>\n#include <tf/transform_datatypes.h>\n\n// Libraries\n#include <boost/cstdfloat.hpp>\n#include <boost/shared_ptr.hpp>\n\n// Standard\n#include <utility>\n\nnamespace local_planner\n{\n\nfloat64_t RosConversionHelper::quaternionMsgToYawR(const geometry_msgs::Quaternion& q)\n{\n    tf::Quaternion new_q;\n    tf::quaternionMsgToTF(q, new_q);\n    float64_t roll_r, pitch_r, yaw_r;\n    tf::Matrix3x3(std::move(new_q)).getRPY(roll_r, pitch_r, yaw_r);\n\n    return yaw_r;\n}\n\n} // namespace local_planner", "meta": {"hexsha": "73ca05c88d54be27723639f8c1891b9db5df7823", "size": 556, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "catkin_ws/src/local_planner/src/types/helper/RosConversionHelper.cpp", "max_stars_repo_name": "WPI-Capstone-Project-Team-1-2020/Capstone-Final-Mile", "max_stars_repo_head_hexsha": "60cf6be95305ec720f001bf18327ae881168443c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "catkin_ws/src/local_planner/src/types/helper/RosConversionHelper.cpp", "max_issues_repo_name": "WPI-Capstone-Project-Team-1-2020/Capstone-Final-Mile", "max_issues_repo_head_hexsha": "60cf6be95305ec720f001bf18327ae881168443c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "catkin_ws/src/local_planner/src/types/helper/RosConversionHelper.cpp", "max_forks_repo_name": "WPI-Capstone-Project-Team-1-2020/Capstone-Final-Mile", "max_forks_repo_head_hexsha": "60cf6be95305ec720f001bf18327ae881168443c", "max_forks_repo_licenses": ["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.8571428571, "max_line_length": 86, "alphanum_fraction": 0.7356115108, "num_tokens": 153, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544335934766, "lm_q2_score": 0.6477982315512488, "lm_q1q2_score": 0.4529757854862243}}
{"text": "#include <boost/math/quadrature/gauss_kronrod.hpp>\n", "meta": {"hexsha": "ed1f76eb69c43dafc4aae19e09f57e2404e6fb84", "size": 51, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_quadrature_gauss_kronrod.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_quadrature_gauss_kronrod.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_quadrature_gauss_kronrod.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 25.5, "max_line_length": 50, "alphanum_fraction": 0.8235294118, "num_tokens": 14, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146849, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4529074902494829}}
{"text": "// SPDX-FileCopyrightText: 2020 Sotiris Papatheodorou, Imperial College London\n// SPDX-License-Identifier: BSD-3-Clause\n\n#ifndef __SENSOR_HPP\n#define __SENSOR_HPP\n\n#include <cmath>\n\n#include <Eigen/Dense>\n#include \"se/image_utils.hpp\"\n#include \"se/image/image.hpp\"\n#include \"se/projection.hpp\"\n\n\n\nnamespace se {\n\n  struct SensorConfig {\n    // General\n    int width = 0;\n    int height = 0;\n    bool left_hand_frame = false;\n    float near_plane = 0.f;\n    float far_plane = INFINITY;\n    // Pinhole camera\n    float fx = nan(\"\");\n    float fy = nan(\"\");\n    float cx = nan(\"\");\n    float cy = nan(\"\");\n    // LIDAR\n    Eigen::VectorXf beam_azimuth_angles = Eigen::VectorXf(1);\n    Eigen::VectorXf beam_elevation_angles = Eigen::VectorXf(1);\n\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n  };\n\n\n\n  struct PinholeCamera {\n    PinholeCamera(const SensorConfig& c);\n\n    PinholeCamera(const PinholeCamera& pinhole_camera,\n                  const float          scaling_factor);\n\n    /**\n     * \\brief Determine the corresponding image value of the projected pixel for a point_C in camera frame.\n     *\n     * \\param sensor          Reference to the used sensor used for the projection.\n     * \\param point_C         3D coordinates of the point to be projected in camera frame.\n     * \\param depth_image     Image\n     * \\param depth_value     Reference to the depth value to be determined.\n     * \\param valid_predicate Functor indicating if the fetched pixel value is valid.\n     *\n     * \\return is_valid   Returns true if the projection is successful and false if the projection is unsuccessful\n     *                    or the pixel value is invalid.\n     */\n    template <typename ValidPredicate>\n    bool projectToPixelValue(const Eigen::Vector3f&  point_C,\n                             const se::Image<float>& image,\n                             float&                  image_value,\n                             ValidPredicate          valid_predicate) const {\n      Eigen::Vector2f pixel_f;\n      if (model.project(point_C, &pixel_f) != srl::projection::ProjectionStatus::Successful) {\n        return false;\n      }\n      const Eigen::Vector2i pixel = se::round_pixel(pixel_f);\n      image_value = image(pixel.x(), pixel.y());\n      // Return false for invalid depth measurement\n      if (!valid_predicate(image_value)) {\n        return false;\n      }\n      return true;\n    }\n\n\n\n    template <typename ValidPredicate>\n    bool getPixelValue(const Eigen::Vector2f&  pixel_f,\n                       const se::Image<float>& image,\n                       float&                  image_value,\n                       ValidPredicate          valid_predicate) const {\n      if (!model.isInImage(pixel_f)) {\n        return false;\n      }\n      Eigen::Vector2i pixel = se::round_pixel(pixel_f);\n      image_value = image(pixel.x(), pixel.y());\n      // Return false for invalid depth measurement\n      if (!valid_predicate(image_value)) {\n        return false;\n      }\n      return true;\n    }\n\n\n\n    /**\n     * \\brief Computes the scale corresponding to the back-projected pixel size\n     * in voxel space\n     * \\param[in] block_centre    The coordinates of the VoxelBlock\n     *                            centre in the camera frame.\n     * \\param[in] voxel_dim       The voxel edge length in meters.\n     * \\param[in] last_scale      Scale from which propagate up voxel\n     *                            values.\n     * \\param[in] min_scale       Finest scale at which data has been\n     *                            integrated into the voxel block (-1 if no\n     *                            data has been integrated yet).\n     * \\param[in] max_block_scale The maximum allowed scale within a\n     *                            VoxelBlock.\n     * \\return The scale that should be used for the integration.\n     */\n    int computeIntegrationScale(const Eigen::Vector3f& block_centre,\n                                const float            voxel_dim,\n                                const int              last_scale,\n                                const int              min_scale,\n                                const int              max_block_scale) const;\n\n    /**\n     * \\brief Return the minimum distance at which measurements are available\n     * along the ray passing through pixels x and y.\n     *\n     * This differs from the PinholeCamera::near_plane since the near_plane is\n     * a z-value while nearDist is a distance along a ray.\n     *\n     * \\param[in] ray_C The ray starting from the camera center and expressed\n     *                  in the camera frame along which nearDist\n     *                  will be computed.\n     * \\return The minimum distance along the ray through the pixel at which\n     *         valid measurements may be encountered.\n     */\n    float nearDist(const Eigen::Vector3f& ray_C) const;\n\n    /**\n     * \\brief Return the maximum distance at which measurements are available\n     * along the ray passing through pixels x and y.\n     *\n     * This differs from the PinholeCamera::far_plane since the far_plane is a\n     * z-value while farDist is a distance along a ray.\n     *\n     * \\param[in] ray_C The ray starting from the camera center and expressed\n     *                  in the camera frame along which nearDist\n     *                  will be computed.\n     * \\return The maximum distance along the ray through the pixel at which\n     *         valid measurements may be encountered.\n     */\n    float farDist(const Eigen::Vector3f& ray_C) const;\n\n    /**\n     * \\brief Convert a point in the sensor frame into a depth measurement.\n     * For the PinholeCamera this means returning the z-coordinate\n     * of the point.\n     *\n     * \\param[in] point_C A point observed by the sensor expressed in the\n     *                    sensor frame.\n     * \\return The depth value that the sensor would get from this point.\n     */\n    float measurementFromPoint(const Eigen::Vector3f& point_C) const;\n\n    /**\n     * \\brief Test whether a 3D point in camera coordinates is inside the\n     * camera frustum.\n     */\n    bool pointInFrustum(const Eigen::Vector3f& point_C) const;\n\n    /**\n     * \\brief Test whether a 3D point in camera coordinates is inside the\n     * camera frustum.\n     *\n     * The difference from PinholeCamera::pointInFrustum is that it is assumed\n     * that the far plane is at infinity.\n     */\n    bool pointInFrustumInf(const Eigen::Vector3f& point_C) const;\n\n    /**\n     * \\brief Test whether a sphere in camera coordinates is inside the camera\n     * frustum.\n     *\n     * It is tested whether the sphere's center is inside the camera frustum\n     * offest outwards by the sphere's radius. This is a quick test that in\n     * some rare cases may return a sphere as being visible although it isn't.\n     */\n    bool sphereInFrustum(const Eigen::Vector3f& center_C,\n                         const float            radius) const;\n\n    /**\n     * \\brief Test whether a sphere in camera coordinates is inside the camera\n     * frustum.\n     *\n     * The difference from PinholeCamera::sphereInFrustum is that it is assumed\n     * that the far plane is at infinity.\n     */\n    bool sphereInFrustumInf(const Eigen::Vector3f& center_C,\n                            const float            radius) const;\n\n    static std::string type() { return \"pinholecamera\"; }\n\n\n\n    srl::projection::PinholeCamera<srl::projection::NoDistortion> model;\n    bool  left_hand_frame;\n    float near_plane;\n    float far_plane;\n    float scaled_pixel;\n    /** \\brief The horizontal field of view in radians. */\n    float horizontal_fov;\n    /** \\brief The vertical field of view in radians. */\n    float vertical_fov;\n\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n    private:\n      void computeFrustumVertices();\n      void computeFrustumNormals();\n\n      static constexpr int num_frustum_vertices_ = 8;\n      static constexpr int num_frustum_normals_ = 6;\n      Eigen::Matrix<float, 4, num_frustum_vertices_> frustum_vertices_;\n      Eigen::Matrix<float, 4, num_frustum_normals_> frustum_normals_;\n  };\n\n\n\n  struct OusterLidar {\n    OusterLidar(const SensorConfig& c);\n\n    OusterLidar(const OusterLidar& ouster_lidar,\n                const float        scaling_factor);\n\n    /**\n     * \\brief Determine the corresponding image value of the projected pixel for a point_C in camera frame.\n     *\n     * \\param sensor          Reference to the used sensor used for the projection.\n     * \\param point_C         3D coordinates of the point to be projected in camera frame.\n     * \\param depth_image     Image\n     * \\param depth_value     Reference to the depth value to be determined.\n     * \\param valid_predicate Functor indicating if the fetched pixel value is valid.\n     *\n     * \\return is_valid   Returns true if the projection is successful and false if the projection is unsuccessful\n     *                    or the depth value is invalid.\n     */\n    template <typename ValidPredicate>\n    bool projectToPixelValue(const Eigen::Vector3f&  point_C,\n                             const se::Image<float>& image,\n                             float&                  image_value,\n                             ValidPredicate          valid_predicate) const {\n      Eigen::Vector2f pixel_f;\n      if (model.project(point_C, &pixel_f) != srl::projection::ProjectionStatus::Successful) {\n        return false;\n      }\n      const Eigen::Vector2i pixel = se::round_pixel(pixel_f);\n      image_value = image(pixel.x(), pixel.y());\n      // Return false for invalid depth measurement\n      if (!valid_predicate(image_value)) {\n        return false;\n      }\n      return true;\n    }\n\n    /**\n     * \\brief Computes the scale corresponding to the back-projected pixel size\n     * in voxel space\n     * \\param[in] block_centre    The coordinates of the VoxelBlock\n     *                            centre in the camera frame.\n     * \\param[in] voxel_dim       The voxel edge length in meters.\n     * \\param[in] last_scale      Scale from which propagate up voxel\n     *                            values.\n     * \\param[in] min_scale       Finest scale at which data has been\n     *                            integrated into the voxel block (-1 if no\n     *                            data has been integrated yet).\n     * \\param[in] max_block_scale The maximum allowed scale within a\n     *                            VoxelBlock.\n     * \\return The scale that should be used for the integration.\n     */\n    int computeIntegrationScale(const Eigen::Vector3f& block_centre,\n                                const float            voxel_dim,\n                                const int              last_scale,\n                                const int              min_scale,\n                                const int              max_block_scale) const;\n\n    /**\n     * \\brief Return the minimum distance at which measurements are available\n     * along the ray passing through pixels x and y.\n     *\n     * This function just returns OusterLidar::near_plane.\n     *\n     * \\param[in] ray_C The ray starting from the camera center and expressed\n     *                  in the camera frame along which nearDist\n     *                  will be computed.\n     * \\return The minimum distance along the ray through the pixel at which\n     *         valid measurements may be encountered.\n     */\n    float nearDist(const Eigen::Vector3f& ray_C) const;\n\n    /**\n     * \\brief Return the maximum distance at which measurements are available\n     * along the ray passing through pixels x and y.\n     *\n     * This function just returns OusterLidar::far_plane.\n     *\n     * \\param[in] ray_C The ray starting from the camera center and expressed\n     *                  in the camera frame along which nearDist\n     *                  will be computed.\n     * \\return The maximum distance along the ray through the pixel at which\n     *         valid measurements may be encountered.\n     */\n    float farDist(const Eigen::Vector3f& ray_C) const;\n\n    /**\n     * \\brief Convert a point in the sensor frame into a depth measurement.\n     * For the OusterLidar this means returning the norm of the point.\n     *\n     * \\param[in] point_C A point observed by the sensor expressed in the\n     *                    sensor frame.\n     * \\return The depth value that the sensor would get from this point.\n     */\n    float measurementFromPoint(const Eigen::Vector3f& point_C) const;\n\n    /**\n     * \\brief Test whether a 3D point in camera coordinates is inside the\n     * sensor frustum.\n     *\n     * \\todo Implement\n     */\n    bool pointInFrustum(const Eigen::Vector3f& point_C) const;\n\n    /**\n     * \\brief Test whether a 3D point in camera coordinates is inside the\n     * sensor frustum.\n     *\n     * \\todo Implement\n     *\n     * The difference from OusterLidar::pointInFrustum is that it is assumed\n     * that the far plane is at infinity.\n     */\n    bool pointInFrustumInf(const Eigen::Vector3f& point_C) const;\n\n    /**\n     * \\brief Test whether a sphere in camera coordinates is inside the sensor\n     * frustum.\n     *\n     * \\todo Implement\n     *\n     * \\todo Describe any issues/assumptions/approximations once implemented.\n     */\n    bool sphereInFrustum(const Eigen::Vector3f& center_C,\n                         const float            radius) const;\n\n    /**\n     * \\brief Test whether a sphere in camera coordinates is inside the sensor\n     * frustum.\n     *\n     * \\todo Implement\n     *\n     * The difference from OusterLidar::sphereInFrustum is that it is assumed\n     * that the far plane is at infinity.\n     */\n    bool sphereInFrustumInf(const Eigen::Vector3f& center_C,\n                            const float            radius) const;\n\n    static std::string type() { return \"ousterlidar\"; }\n\n    srl::projection::OusterLidar model;\n    bool  left_hand_frame;\n    float near_plane;\n    float far_plane;\n    float min_ray_angle;\n    /** \\brief The horizontal field of view in radians. */\n    float horizontal_fov;\n    /** \\brief The vertical field of view in radians. */\n    float vertical_fov;\n\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n  };\n\n} // namespace se\n\n#endif\n\n", "meta": {"hexsha": "e4a7af7d7444a64d840a23825721ba03c6083e74", "size": 14106, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "se_shared/include/se/sensor.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_shared/include/se/sensor.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_shared/include/se/sensor.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": 37.3174603175, "max_line_length": 114, "alphanum_fraction": 0.610874805, "num_tokens": 3060, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.45290749024948285}}
{"text": "#pragma once\n//! c/c++ headers\n#include <cmath>\n#include <functional>\n#include <map>\n#include <memory>\n#include <tuple>\n#include <unordered_map>\n#include <utility>\n//! dependency headers\n#include <armadillo>\n#include <boost/functional/hash.hpp>\n#include <cppad/cppad.hpp>\n#include <cppad/ipopt/solve.hpp>\n#include \"nlohmann/json.hpp\"\n//! project headers\n#include \"correspondences/common/base.hpp\"\n#include \"correspondences/common/types.hpp\"\n#include \"correspondences/common/utilities.hpp\"\n\nnamespace correspondences {\nnamespace qap {\n/** @struct Config\n * @brief configuration parameters for optimization algorithm \n * @var Config::corr_threshold\n * value in optimum solution to declare a correspondence as valid {\\in (0, 1)}\n * @var Config::n_pair_threshold\n * minimum number of pairwise consistencies \n * @var Config::min_corr\n * number of correspondences/matches to identify during optimization \n */\nstruct Config : CorrespondencesConfigBase {\n  Config()\n    : CorrespondencesConfigBase() {\n      set_defaults();\n    }\n\n  explicit Config(nlohmann::json & config) :\n    CorrespondencesConfigBase(config) {\n      set_defaults();\n      json_utils::check_for_param(config, \"corr_threshold\", corr_threshold);\n      json_utils::check_for_param(config, \"n_pair_threshold\", n_pair_threshold);\n      json_utils::check_for_param(config, \"min_corr\", min_corr);\n    }\n\n  void set_defaults() noexcept final {\n    corr_threshold = 0.9;\n    n_pair_threshold = 5;\n    min_corr = 5;\n  }\n\n  double corr_threshold;\n  size_t n_pair_threshold, min_corr;\n};\n\n/** @class ConstrainedObjective\n * @brief class definition for point set registration relaxation objective\n */\nclass ConstrainedObjective {\n public:\n   /** @typedef ConstrainedObjective::ADVector\n    * @brief typedef for CppAD automatic differentiation during optimization execution\n    */\n   using ADvector = CPPAD_TESTVECTOR(CppAD::AD<double>);\n\n   /** ConstrainedObjective::ConstrainedObjective(source_pts, target_pts, config)\n    * @brief constructor for constrained objective function\n    *\n    * @param[in] source_pts distribution of (columnar) source points\n    * @param[in] target_pts distribution of (columnar) target points\n    * @param[in] config `Config` instance with optimization parameters; see `Config` definition\n    * @return\n    */\n   explicit ConstrainedObjective(arma::mat const & source_pts,\n       arma::mat const & target_pts, Config const & config) :\n     m_(static_cast<size_t>(source_pts.n_cols)), n_(static_cast<size_t>(target_pts.n_cols)),\n     min_corr_(config.min_corr) {\n     weights_ = generate_weight_tensor(source_pts, target_pts, config.epsilon,\n         config.pairwise_dist_threshold);\n     n_constraints_ = m_ + n_ + 2;\n   }\n\n   /** ConstrainedObjective::~ConstrainedObjective()\n    * @brief destructor for constrained objective function\n    *\n    * @param[in]\n    * @return\n    */\n   ~ConstrainedObjective();\n\n   /** ConstrainedObjective::operator()\n    * @brief operator overload for IPOPT\n    *\n    * @param[in][out] fgrad objective function evaluation (including constraints) at point `z`\n    * @param[in] z point for evaluation\n    * @return\n    */\n   void operator()(ADvector &fgrad, ADvector const & z) noexcept;\n\n   /** ConstrainedObjective::num_constraints()\n    * @brief return number of constraints for optimization objective\n    *\n    * @param[in]\n    * @return copy of private member `n_constraints_`\n    */\n   size_t num_constraints() const noexcept { return n_constraints_; }\n\n   /** ConstrainedObjective::num_source_pts()\n    * @brief return number of source points for optimization objective\n    *\n    * @param[in]\n    * @return copy of private member `m_`\n    */\n   size_t num_source_pts() const noexcept { return m_; }\n\n   /** ConstrainedObjective::num_target_pts()\n    * @brief return number of target points for optimization objective\n    *\n    * @param[in]\n    * @return copy of private member `n_`\n    */\n   size_t num_target_pts() const noexcept { return n_; }\n\n   /** ConstrainedObjective::num_min_corr()\n    * @brief return minimum number of correspondences for optimization objective\n    *\n    * @param[in]\n    * @return copy of private member `min_corr_`\n    */\n   size_t num_min_corr() const noexcept { return min_corr_; }\n\n   /** ConstrainedObjective::state_length()\n    * @brief get size of state vector for optimization objective\n    *\n    * @param[in]\n    * @return (m_ + 1)*(n_ + 1)\n    * @note includes slack variables\n    */\n   size_t state_length() const noexcept { return (m_ + 1) * (n_ + 1); }\n\n   /** ConstrainedObjective::get_weight_tensor()\n    * @brief get weight_tensor\n    *\n    * @param[in]\n    * @return copy of private member `weights_`\n    */\n   WeightTensor get_weight_tensor() const noexcept { return weights_; }\n\n private:\n   WeightTensor weights_;\n   size_t m_, n_, min_corr_, n_constraints_;\n};\n}  // namespace qap\n\n/** @class QAP : public CorrespondencesBase\n * @brief wrapper class definition for correspondence calculation by solving\n * a quadratic assignment problem (QAP)\n */\nclass QAP : public CorrespondencesBase {\n public:\n   /** @typedef QAP::DVec\n    * @brief typedef for CppAD test vector\n    */\n   using Dvec = CPPAD_TESTVECTOR(double);\n\n   /** @typedef QAP::ipopt_status_t\n    * @brief typedef for IPOPT return code\n    */\n   using ipopt_status_t = CppAD::ipopt::solve_result<Dvec>::status_type;\n\n   /** QAP::QAP(source_pts, target_pts, config)\n    * @brief constructor for optimization wrapper class\n    *\n    * @param[in] source_pts distribution of (columnar) source points\n    * @param[in] target_pts distribution of (columnar) target points\n    * @param[in] config `Config` instance with optimization parameters; see `Config` definition\n    * @return\n    */\n   explicit QAP(arma::mat const & source_pts,\n       arma::mat const & target_pts, qap::Config config) : config_(config) {\n     /*std::cout << \"####\" << std::endl;\n     std::cout << config_.epsilon << \", \" << config_.pairwise_dist_threshold << \", \"\n       << config_.corr_threshold << \", \" << config_.n_pair_threshold << \", \"\n       << config_.min_corr << std::endl;\n     std::cout << \"####\" << std::endl;*/\n     ptr_obj_ = std::make_unique<qap::ConstrainedObjective>(source_pts, target_pts, config);\n     optimum_.resize(ptr_obj_->state_length());\n   }\n\n   /** QAP::~QAP()\n    * @brief destructor for optimization wrapper class\n    *\n    * @param[in]\n    * @return\n    */\n   ~QAP();\n\n   /** QAP::calc_optimum()\n    * @brief run IPOPT to find optimum for optimization objective\n    *\n    * @param[in]\n    * @return solver status returned by IPOPT\n    */\n   ipopt_status_t calc_optimum() noexcept;\n\n   /** PointRegRelaxation::find_correspondences()\n    * @brief identify pairwise correspondences between source and target set given optimum found\n    * during optimization\n    *\n    * @param[in]\n    * @return solution status \n    * @see status_e definition in types.hpp\n    */\n   status_e calc_correspondences(correspondences_t & corr) noexcept final;\n\n   /** QAP::get_optimum()\n    * @brief get optimization\n    *\n    * @param[in]\n    * @return\n    */\n   arma::colvec get_optimum() const noexcept { return optimum_; }\n\n   /** QAP::linear_projection\n    * @brief Solve linear assignment problem:\n    *  max c.t()*flatten(X) subject to linear constraints\n    *\n    * @note linear constraints are constructed within the function\n    *\n    * @param [in][out] opt_lp projection of optimal solution onto permutation matrices\n    * @return true if converged, false otherwise\n    */\n   bool linear_projection(arma::colvec & opt_lp) const noexcept;\n\n   /** QAP::num_consistent_pairs()\n    * @brief get identified correspondences\n    *\n    * @param[in]\n    * @return number of pairwise consistencies identified\n    */\n   size_t num_consistent_pairs() const noexcept { return ptr_obj_->get_weight_tensor().size(); }\n\n private:\n   qap::Config config_;\n   std::unique_ptr<qap::ConstrainedObjective> ptr_obj_;\n   arma::colvec optimum_;\n};\n}  // namespace correspondences\n", "meta": {"hexsha": "314b5809001d24892546871ed9fb915ae395ec71", "size": 7965, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "correspondences/qap/include/correspondences/qap/qap.hpp", "max_stars_repo_name": "jwdinius/nmsac", "max_stars_repo_head_hexsha": "b765be4340cf8367e1af345dc156597ce425c818", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "correspondences/qap/include/correspondences/qap/qap.hpp", "max_issues_repo_name": "jwdinius/nmsac", "max_issues_repo_head_hexsha": "b765be4340cf8367e1af345dc156597ce425c818", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2020-07-19T23:38:48.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-14T22:36:30.000Z", "max_forks_repo_path": "correspondences/qap/include/correspondences/qap/qap.hpp", "max_forks_repo_name": "jwdinius/nmsac", "max_forks_repo_head_hexsha": "b765be4340cf8367e1af345dc156597ce425c818", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-06T06:59:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-06T06:59:04.000Z", "avg_line_length": 31.9879518072, "max_line_length": 96, "alphanum_fraction": 0.6882611425, "num_tokens": 1920, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812554, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4529074850024482}}
{"text": "//\n// MIT License\n// \n// Copyright (c) Deif Lou\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 <opencv2/imgproc.hpp>\n#include <Eigen/Dense>\n#include <limits>\n\n#include \"filter.h\"\n#include \"filterwidget.h\"\n#include <imgproc/lut.h>\n#include <imgproc/types.h>\n#include <imgproc/colorconversion.h>\n#include <misc/util.h>\n\n#define MAX_IMAGE_SIZE 128\n#define DEGREE 3\n#define MIU .5\n#define MIUSQR (MIU * MIU)\n#define MATRIXCOLUMNS ((DEGREE + 1) * (DEGREE + 2) / 2 - 1)\n#define BLURKERNELSIZE 5\n\nFilter::Filter() :\n    mOutputMode(CorrectedImageMode1)\n{\n}\n\nFilter::~Filter()\n{\n}\n\nImageFilter *Filter::clone()\n{\n    Filter * f = new Filter();\n    f->mOutputMode = mOutputMode;\n    return f;\n}\n\nextern \"C\" QHash<QString, QString> getIBPPluginInfo();\nQHash<QString, QString> Filter::info()\n{\n    return getIBPPluginInfo();\n}\n\nQImage Filter::process(const QImage &inputImage)\n{\n    if (inputImage.isNull() || inputImage.format() != QImage::Format_ARGB32)\n        return inputImage;\n\n    register int x, y, w = inputImage.width(), h = inputImage.height(), mean = 0, sw, sh, i, j;\n    register HSL * bitsHSL = (HSL *)malloc(w * h * sizeof(HSL)), * bitsHSLsl;\n    cv::Mat mlchannel(h, w, CV_8UC1);\n    register unsigned char * mbits8;\n    register double * mbits321, * mbits322;\n    register double weight;\n\n    // Convert to HSL\n    convertBGRToHSL(inputImage.bits(), (unsigned char *)bitsHSL, w * h);\n\n    // Separate L channel\n    for (y = 0; y < h; y++)\n    {\n        bitsHSLsl = bitsHSL + y * w;\n        mbits8 = mlchannel.ptr(y);\n        for (x = 0; x < w; x++)\n        {\n            *mbits8 = bitsHSLsl->l;\n            bitsHSLsl++;\n            mbits8++;\n        }\n    }\n\n    // Resample\n    cv::Mat mInitial;\n    if (w != MAX_IMAGE_SIZE || h != MAX_IMAGE_SIZE)\n    {\n        if (w > h)\n        {\n            sw = MAX_IMAGE_SIZE;\n            sh = h * MAX_IMAGE_SIZE / w;\n        }\n        else\n        {\n            sh = MAX_IMAGE_SIZE;\n            sw = w * MAX_IMAGE_SIZE / h;\n        }\n        sw = sw < 1 ? 1 : sw;\n        sh = sh < 1 ? 1 : sh;\n\n        cv::Mat mresized(sh, sw, CV_8UC1);\n        cv::resize(mlchannel, mresized, cv::Size(sw, sh), 0, 0, cv::INTER_CUBIC);\n        mInitial = mresized;\n    }\n    else\n    {\n        sw = w;\n        sh = h;\n        mInitial = mlchannel;\n    }\n\n    // Remove noise\n    cv::Mat mMatUChar(sh, sw, CV_8UC1);\n    cv::GaussianBlur(mInitial, mMatUChar, cv::Size(BLURKERNELSIZE, BLURKERNELSIZE), 0);\n\n    // Convert to float and scale\n    cv::Mat mMatDouble(sh, sw, CV_64FC1);\n    for (y = 0; y < sh; y++)\n    {\n        mbits8 = mMatUChar.ptr(y);\n        mbits321 = (double *)mMatDouble.ptr(y);\n        for (x = 0; x < sw; x++)\n        {\n            *mbits321 = (*mbits8) / 255.;\n            mbits8++;\n            mbits321++;\n        }\n    }\n\n    // Get the gradient of the blurred image\n    cv::Mat mGradientX(sh, sw, CV_64FC1);\n    cv::Mat mGradientY(sh, sw, CV_64FC1);\n    cv::Sobel(mMatDouble, mGradientX, -1, 1, 0);\n    cv::Sobel(mMatDouble, mGradientY, -1, 0, 1);\n\n    // Calculate weights\n    register int row = 0, column = 0, totalPixels = sw * sh;\n    Eigen::DiagonalMatrix<float, Eigen::Dynamic> ls_W(totalPixels * 2);\n    for (y = 0; y < sh; y++)\n    {\n        mbits321 = (double *)mGradientX.ptr(y);\n        mbits322 = (double *)mGradientY.ptr(y);\n        for (x = 0; x < sw; x++)\n        {\n            weight = sqrt(exp(-sqrt((*mbits321) * (*mbits321) + (*mbits322) * (*mbits322)) / MIUSQR));\n            ls_W.diagonal()[row] = ls_W.diagonal()[row + totalPixels] = weight;\n            row++;\n            mbits321++;\n            mbits322++;\n        }\n    }\n\n    // Surface fitting using eigen\n    // First set up the matrix A and the vector b for least squares fitting with the gradient image\n    row = 0;\n    column = 0;\n    Eigen::MatrixXf ls_A(totalPixels * 2, MATRIXCOLUMNS);\n    Eigen::VectorXf ls_b(totalPixels * 2);\n    Eigen::VectorXf ls_x;\n\n    for (y = 0; y < sh; y++)\n    {\n        mbits321 = (double *)mGradientX.ptr(y);\n        mbits322 = (double *)mGradientY.ptr(y);\n        for (x = 0; x < sw; x++)\n        {\n            column = 0;\n            // Fill matrix A with the monomial terms of the polynomial surface\n            for (i = 1; i <= DEGREE; i++)\n            {\n                for (j = 0; j <= i; j++)\n                {\n                    ls_A(row, column) = (i - j) * (x == 0 ? 1 : pow(x, i - j - 1)) * (y == 0 ? 1 : pow(y, j));\n                    ls_A(row + totalPixels, column) = j * (x == 0 ? 1 : pow(x, i - j)) * (y == 0 ? 1 : pow(y, j - 1));\n\n                    column++;\n                }\n            }\n            // Fill vector b with the image gradient values\n            ls_b(row) = *mbits321;\n            ls_b(row + totalPixels) = *mbits322;\n\n            mbits321++;\n            mbits322++;\n            row++;\n        }\n    }\n    // Solve...\n    ls_x = (ls_W * ls_A).jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(ls_W * ls_b);\n\n    // Set up the matrix A and the vector b for least squares fitting with the blurred image\n    ls_A = Eigen::MatrixXf(totalPixels, 2);\n    ls_b = Eigen::VectorXf(totalPixels);\n    ls_W.diagonal().conservativeResize(totalPixels);\n    register double value;\n    row = 0;\n    for (y = 0; y < sh; y++)\n    {\n        mbits321 = (double *)mMatDouble.ptr(y);\n        for (x = 0; x < sw; x++)\n        {\n            column = 0;\n            value = 0.;\n            for (i = 1; i <= DEGREE; i++)\n            {\n                for (j = 0; j <= i; j++)\n                {\n                    value += ls_x(column) * (x == 0 ? 1 : pow(x, i - j)) * (y == 0 ? 1 : pow(y, j));\n                    column++;\n                }\n            }\n            ls_A(row, 0) = value;\n            ls_A(row, 1) = 1;\n            ls_b(row) = *mbits321;\n\n            mbits321++;\n            row++;\n        }\n    }\n    // Solve...\n    ls_x = (ls_W * ls_A).jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(ls_W * ls_b);\n\n    // Create the IIH model image\n    row = 0;\n    for (y = 0; y < sh; y++)\n    {\n        mbits321 = (double *)mMatDouble.ptr(y);\n        for (x = 0; x < sw; x++)\n        {\n            *mbits321 = ls_A(row, 0) * ls_x(0) + ls_x(1);\n\n            mbits321++;\n            row++;\n        }\n    }\n\n    // Remap due to out of range values and scale\n    double minIIH, maxIIH, minIIHc, maxIIHc;\n    cv::minMaxLoc(mMatDouble, &minIIH, &maxIIH);\n    minIIHc = IBP_clamp(0., minIIH, 1.);\n    maxIIHc = IBP_clamp(0., maxIIH, 1.);\n    for (y = 0; y < sh; y++)\n    {\n        mbits321 = (double *)mMatDouble.ptr(y);\n        mbits8 = mMatUChar.ptr(y);\n        for (x = 0; x < sw; x++)\n        {\n            *mbits8 = round((minIIHc + ((*mbits321) - minIIH) * (maxIIHc - minIIHc) / (maxIIH - minIIH)) * 255.);\n            mean += *mbits8;\n            mbits8++;\n            mbits321++;\n        }\n    }\n    mean /= totalPixels;\n\n    // Resample\n    if (w != sw || h != sh)\n        cv::resize(mMatUChar, mlchannel, cv::Size(w, h), 0, 0, cv::INTER_CUBIC);\n    else\n        mlchannel = mMatUChar;\n\n    // Make output image\n    if (mOutputMode == CorrectedImageMode1)\n    {\n        // Divide lightness channel\n        for (y = 0; y < h; y++)\n        {\n            bitsHSLsl = bitsHSL + y * w;\n            mbits8 = mlchannel.ptr(y);\n            for (x = 0; x < w; x++)\n            {\n                bitsHSLsl->l = IBP_clamp(0, lut02[bitsHSLsl->l][IBP_clamp(1, *mbits8, 255)] * mean / 255, 255);\n                bitsHSLsl++;\n                mbits8++;\n            }\n        }\n    }\n    else if (mOutputMode == CorrectedImageMode2)\n    {\n        // Divide lightness channel\n        for (y = 0; y < h; y++)\n        {\n            bitsHSLsl = bitsHSL + y * w;\n            mbits8 = mlchannel.ptr(y);\n            for (x = 0; x < w; x++)\n            {\n                bitsHSLsl->l = IBP_clamp(0, lut02[bitsHSLsl->l][IBP_clamp(1, *mbits8, 255)], 255);\n                bitsHSLsl++;\n                mbits8++;\n            }\n        }\n    }\n    else\n    {\n        for (y = 0; y < h; y++)\n        {\n            bitsHSLsl = bitsHSL + y * w;\n            mbits8 = mlchannel.ptr(y);\n            for (x = 0; x < w; x++)\n            {\n                bitsHSLsl->h = bitsHSLsl->s = 0;\n                bitsHSLsl->l = *mbits8;\n                bitsHSLsl++;\n                mbits8++;\n            }\n        }\n    }\n\n    // Convert to RGB\n    QImage finalImage = inputImage.copy();\n    convertHSLToBGR((const unsigned char *)bitsHSL, finalImage.bits(), w * h);\n    free(bitsHSL);\n\n    return finalImage;\n}\n\nbool Filter::loadParameters(QSettings &s)\n{\n    QString outputModeStr;\n    OutputMode outputMode;\n\n    outputModeStr = s.value(\"outputmode\", \"correctedimagemode1\").toString();\n    if (outputModeStr == \"correctedimagemode1\")\n        outputMode = CorrectedImageMode1;\n    else if (outputModeStr == \"correctedimagemode2\")\n        outputMode = CorrectedImageMode2;\n    else if (outputModeStr == \"iihcorrectionmodel\")\n        outputMode = IIHCorrectionModel;\n    else\n        return false;\n\n    setOutputMode(outputMode);\n\n    return true;\n}\n\nbool Filter::saveParameters(QSettings &s)\n{\n    s.setValue(\"outputmode\", mOutputMode == CorrectedImageMode1 ? \"correctedimagemode1\" :\n                             mOutputMode == CorrectedImageMode2 ? \"correctedimagemode2\" : \"iihcorrectionmodel\");\n    return true;\n}\n\nQWidget *Filter::widget(QWidget *parent)\n{\n    FilterWidget * fw = new FilterWidget(parent);\n    fw->setOutputMode(mOutputMode);\n    connect(this, SIGNAL(outputModeChanged(Filter::OutputMode)), fw, SLOT(setOutputMode(Filter::OutputMode)));\n    connect(fw, SIGNAL(outputModeChanged(Filter::OutputMode)), this, SLOT(setOutputMode(Filter::OutputMode)));\n    return fw;\n}\n\nvoid Filter::setOutputMode(Filter::OutputMode om)\n{\n    if (om == mOutputMode)\n        return;\n    mOutputMode = om;\n    emit outputModeChanged(om);\n    emit parametersChanged();\n}\n", "meta": {"hexsha": "90cab1386383be012528b8e9acd51e5418d49838", "size": 10875, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/plugins/imagefilter_surfacefittingiihc/filter.cpp", "max_stars_repo_name": "deiflou/anitools", "max_stars_repo_head_hexsha": "9728f7569b59aa261dcaffc8332a1b02c2cd5fbe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-05-07T18:44:34.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-12T15:57:40.000Z", "max_issues_repo_path": "src/plugins/imagefilter_surfacefittingiihc/filter.cpp", "max_issues_repo_name": "deiflou/anitools", "max_issues_repo_head_hexsha": "9728f7569b59aa261dcaffc8332a1b02c2cd5fbe", "max_issues_repo_licenses": ["MIT"], "max_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/imagefilter_surfacefittingiihc/filter.cpp", "max_forks_repo_name": "deiflou/anitools", "max_forks_repo_head_hexsha": "9728f7569b59aa261dcaffc8332a1b02c2cd5fbe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-03-18T05:31:34.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-19T21:17:54.000Z", "avg_line_length": 29.3918918919, "max_line_length": 118, "alphanum_fraction": 0.5415172414, "num_tokens": 3180, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4529074850024481}}
{"text": "\n#include <boost/test/unit_test.hpp>\n#include \"triangle.h\"\n\nBOOST_AUTO_TEST_SUITE(test_triangle)\n\nBOOST_AUTO_TEST_CASE(test_triangle_trace)\n{\n\tmath::triangle<3> tri(math::vec<3>(0, 1, 0), math::vec<3>(0, 3, 1), math::vec<3>(1, 3, 0));\n\tmath::scalar t;\n\tmath::vec<3> v;\n\tbool result = tri.trace(math::ray<3>(math::vec<3>(-1, 2, 0), math::vec<3>(10, 0, 0)), t, v);\n\tBOOST_CHECK (result == true);\n\tBOOST_CHECK ((math::vec<3>(0.5f, 2, 0) - v).length() < math::EPSILON);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "326dcb33e6f2017d40f8ea9429d4acbbb92c8047", "size": 497, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/math/test_triangle.cc", "max_stars_repo_name": "mnvl/scratch", "max_stars_repo_head_hexsha": "7717772e0b9a85c8feb73fdc3562425f48b4a727", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-08-15T11:55:32.000Z", "max_stars_repo_stars_event_max_datetime": "2016-08-15T11:55:32.000Z", "max_issues_repo_path": "src/math/test_triangle.cc", "max_issues_repo_name": "mnvl/scratch", "max_issues_repo_head_hexsha": "7717772e0b9a85c8feb73fdc3562425f48b4a727", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/math/test_triangle.cc", "max_forks_repo_name": "mnvl/scratch", "max_forks_repo_head_hexsha": "7717772e0b9a85c8feb73fdc3562425f48b4a727", "max_forks_repo_licenses": ["BSD-3-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.6111111111, "max_line_length": 93, "alphanum_fraction": 0.6539235412, "num_tokens": 184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4529074850024481}}
{"text": "/*! \\file demo_2d_autoscaling.cpp\n    \\brief Demonstration of autoscaling in 2D plots.\n    \\details  An example to demonstrate simplest 2d *default* settings.\n     See also auto_2d_plot.cpp for a wider range of use.\n\n    \\date 20 Mar 2009\n    \\author Paul A. Bristow\n*/\n// Copyright Paul A Bristow 2009, 2021\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// This file is written to be included from a Quickbook .qbk document.\n// It can be compiled by the C++ compiler, and run. Any output can\n// also be added here as comment or included or pasted in elsewhere.\n// Caution: this file contains Quickbook markup as well as code\n// and comments: don't change any of the special comment markups!\n\n//[demo_2d_autoscaling_1\n\n/*`As always, we need a few includes to use Boost.Plot:\n*/\n\n#include <boost/svg_plot/svg_2d_plot.hpp>\n  //using namespace boost::svg;\n  //using boost::svg::svg_2d_plot;\n\n#include <iostream>\n  //using std::cout;\n  //using std::endl;\n  //using std::dec;\n  //using std::hex;\n\n#include <map>\n//  using std::map;\n//] [demo_2d_autoscaling_1]\n\nint main()\n{\n\n//[demo_2d_autoscaling_2\n/*`Some fictional data is pushed into an STL container, here `std::map`:\\n\n\n  This example uses a single map to demonstrate autoscaling.\n  We construct a `std::map` to hold our data-series, and insert some fictional values (that also sorts the data).\n  The 'index' value in [ ] is the X value.\n  */\n  std::map<const double, double> my_data;\n  my_data[1.1] = 3.2;\n  my_data[7.3] = 9.1;\n  my_data[2.12] = 2.4394;\n  my_data[5.47] = 5.3861;\n\n  using namespace boost::svg; // Convenient for access to named colors and data-point marker shapes.\n\n  try\n  { \n    // try'n'catch blocks are needed to ensure error messages from any exceptions are shown by the catch block below.\n   using boost::svg::svg_2d_plot;\n    svg_2d_plot my_2d_plot; // Construct a plot with all the default constructor values.\n    my_2d_plot.title(\"Autoscaling 2d Values\"); // Add a string title of the plot.\n\n/*` With the defaults ranges would be -10 to +10 for both X and Y axes.  We could chose our own ranges thus:\n    `.x_range(0, 6) // Add a range for the X-axis.\n    .y_range(0, 10) // Add a range for the Y-axis.`\n  Or we can use autoscaling.\n\n*/\n   my_2d_plot.xy_autoscale(my_data); // Autoscale both X and Y axes.\n\n/*`This says use the entire STL `std::map` container `my_data` to set both X and Y ranges.\n(The data used to autoscale the range(s) does not have to be the same as the data being plotted.\nFor example, if we have analysed a product and know that an attribute like strength can only decline as the product ages,\nit would make sense to use the reference 'as new' data to scale the plot for the 'aged' product samples).\n*/\n\n  /*`We can show the ranges used by autoscaling; */\n   std::cout << \"X min \" << my_2d_plot.x_range().first << \", X max \" << my_2d_plot.x_range().second << std::endl;\n   std::cout << \"Y min \" << my_2d_plot.y_range().first << \", Y max \"  << my_2d_plot.y_range().second << std::endl;\n\n\n\n/*`Then add the (one but could be more) data-series, @c my_data and a description, and how the data-points are to be marked,\nhere a circle with a diameter of 5 pixels, without a line joining the points (also the default).\n*/\n    my_2d_plot.plot(my_data, \"2d Values\").shape(circlet).size(8).line_on(false);\n\n/*`To use all these settings, finally write the plot to file.\n*/\n    my_2d_plot.write(\"./demo_2d_autoscaling.svg\");\n\n//] [demo_2d_autoscaling_2]\n  }\n  catch(const std::exception& e)\n  {\n    std::cout <<\n      \"\\n\"\"Message from thrown exception was:\\n   \" << e.what() << std::endl;\n  }\n  return 0;\n} // int main()\n\n/*\n\n//[demo_2d_autoscaling_output\n\nOutput:\nChecked: x_min 1.1, x_max 7.3, y_min 2.4394, y_max 9.1, 4 'good' values, 0 values at limits\n\n\n*/\n\n", "meta": {"hexsha": "75946f63a09b9323ce8e2e4f90a6591d274e87a1", "size": 3898, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/demo_2d_autoscaling.cpp", "max_stars_repo_name": "pabristow/svg_plot", "max_stars_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2016-03-09T03:23:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T14:02:07.000Z", "max_issues_repo_path": "example/demo_2d_autoscaling.cpp", "max_issues_repo_name": "pabristow/svg_plot", "max_issues_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2018-03-05T14:39:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-22T09:00:33.000Z", "max_forks_repo_path": "example/demo_2d_autoscaling.cpp", "max_forks_repo_name": "pabristow/svg_plot", "max_forks_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2016-11-04T14:36:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-17T08:12:03.000Z", "avg_line_length": 33.8956521739, "max_line_length": 124, "alphanum_fraction": 0.6967675731, "num_tokens": 1144, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.8056321796478255, "lm_q1q2_score": 0.45290747975541323}}
{"text": "//\n// OpenTissue, A toolbox for physical based simulation and animation.\n// Copyright (C) 2007 Department of Computer Science, University of Copenhagen\n//\n#include <OpenTissue/configuration.h>\n\n#include <OpenTissue/core/math/big/big_types.h>\n#include <OpenTissue/core/math/math_basic_types.h>\n#include <OpenTissue/kinematics/skeleton/skeleton_types.h>\n#include <OpenTissue/kinematics/inverse/inverse_compute_jacobian.h>\n#include <OpenTissue/kinematics/inverse/inverse_chain.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <OpenTissue/utility/utility_push_boost_filter.h>\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n#include <OpenTissue/utility/utility_pop_boost_filter.h>\n\n\ntypedef float\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t             real_type;\ntypedef OpenTissue::math::default_math_types\t\t  \t\t\t math_types;\ntypedef ublas::compressed_matrix<real_type>              matrix_type;\n\n/**\n* This is a dummy bone traits class implementation created just for\n* the unit-test compile.\n*\n* The bone trait class was created to fill out the Jacobian\n* matrix with the index of the bone. This way we can test\n* which bones map into which sub-blocks in the resulting Jacobian matrix.\n*\n* param size and dofs were chosen to create Jacobian sub-blocks of\n* size 1-by-1.\n*/\nclass MyBoneTraits \n  : public OpenTissue::skeleton::DefaultBoneTraits<math_types>\n{\npublic:\n\n  size_t active_dofs() const { return 1; };\n\n  template<typename bone_type, typename chain_type, typename matrix_range>\n  static void compute_jacobian( bone_type & bone, chain_type & chain, matrix_range & J )\n  {\n    BOOST_CHECK( J.size1() == chain.get_goal_dimension());\n    BOOST_CHECK( J.size2() == 1);\n\n    for( size_t i=0;i<chain.get_goal_dimension();++i)\n      J(i,0) = 1.0f*bone.get_number();\n  }\n\n};\n\ntypedef OpenTissue::skeleton::Types<math_types,MyBoneTraits>      skeleton_types;\ntypedef skeleton_types::skeleton_type                             skeleton_type;\ntypedef skeleton_types::bone_type                                 bone_type;\ntypedef skeleton_types::bone_traits                               bone_traits;\ntypedef OpenTissue::kinematics::inverse::Chain< skeleton_type >   chain_type;\n\n\nBOOST_AUTO_TEST_SUITE(opentissue_kinematics_inverse_compute_jacobian);\n\nBOOST_AUTO_TEST_CASE(test_cases)\n{\n  skeleton_type skeleton;\n\n  bone_type * b0 = skeleton.create_bone();\n  bone_type * b1 = skeleton.create_bone(b0);\n  bone_type * b2 = skeleton.create_bone(b1);\n  bone_type * b3 = skeleton.create_bone(b0);\n\n  // Create a few different kinematic chains\n  std::vector<chain_type> chains;\n  chains.resize( 3 );\n  chains[0].init( b0, b2 );\n  chains[1].init( b0, b1 );\n  chains[2].init( b0, b3 );\n\n  // Assemble Jacobian matrix of the kinematic chains.\n  matrix_type J;\n  OpenTissue::kinematics::inverse::compute_jacobian( chains.begin(), chains.end(), skeleton.begin(), skeleton.end(), J);\n\n  // Verify that the assembled Jacobian has the expeced pattern and data.\n  BOOST_CHECK( J.size1() == 9);\n  BOOST_CHECK( J.size2() == 4);\n\n\n  for( size_t i=0;i<chains[0].get_goal_dimension();++i)\n  {\n    BOOST_CHECK( J(i,0) == 1.0f*b0->get_number() );\n    BOOST_CHECK( J(i,1) == 1.0f*b1->get_number() );\n    BOOST_CHECK( J(i,2) == 1.0f*b2->get_number() );\n    BOOST_CHECK( J(i,3) == 0.0f                  );\n  }\n\n  size_t offset = chains[0].get_goal_dimension();\n  for( size_t i=0;i<chains[1].get_goal_dimension();++i)\n  {\n\n    BOOST_CHECK( J(i+offset,0) == 1.0f*b0->get_number() );\n    BOOST_CHECK( J(i+offset,1) == 1.0f*b1->get_number() );\n    BOOST_CHECK( J(i+offset,2) == 0.0f                  );\n    BOOST_CHECK( J(i+offset,3) == 0.0f                  );\n  }\n\n  offset += chains[1].get_goal_dimension();\n  for( size_t i=0;i<chains[2].get_goal_dimension();++i)\n  {\n\n    BOOST_CHECK( J(i+offset,0) == 1.0f*b0->get_number() );\n    BOOST_CHECK( J(i+offset,1) == 0.0f                  );\n    BOOST_CHECK( J(i+offset,2) == 0.0f                  );\n    BOOST_CHECK( J(i+offset,3) == 1.0f*b3->get_number() );\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "9d0a4294ac78e459e42e06cabfa3f69dc8351792", "size": 4099, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/kinematics/inverse/jacobian_assembly/src/unit_jacobian_assembly.cpp", "max_stars_repo_name": "ricortiz/OpenTissue", "max_stars_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 76.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:45:06.000Z", "max_issues_repo_path": "unit_tests/kinematics/inverse/jacobian_assembly/src/unit_jacobian_assembly.cpp", "max_issues_repo_name": "ricortiz/OpenTissue", "max_issues_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2018-11-20T14:32:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T15:26:45.000Z", "max_forks_repo_path": "unit_tests/kinematics/inverse/jacobian_assembly/src/unit_jacobian_assembly.cpp", "max_forks_repo_name": "ricortiz/OpenTissue", "max_forks_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2018-02-21T01:45:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T07:06:49.000Z", "avg_line_length": 34.1583333333, "max_line_length": 120, "alphanum_fraction": 0.6823615516, "num_tokens": 1103, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851919, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.45290298606559204}}
{"text": "#define BOOST_TEST_MODULE CODATA_2010\n#include <boost/test/included/unit_test.hpp>\n\n#include <cmath>\n#include <tuple>\n\ntypedef std::tuple<float, double, long double> test_types;\n\n#include <triumf/constants/codata_2010.hpp>\n\n// {220} lattice spacing of silicon\n// (1.920155714e-10 \u00b1 3.2e-18) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(lattice_spacing_of_silicon_220, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::lattice_spacing_of_silicon_220<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::lattice_spacing_of_silicon_220<\n                 T>::value() == static_cast<T>(1.920155714e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::lattice_spacing_of_silicon_220<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::lattice_spacing_of_silicon_220<\n                 T>::uncertainty() == static_cast<T>(3.2e-18));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::lattice_spacing_of_silicon_220<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::lattice_spacing_of_silicon_220<\n          T>::precision()));\n}\n\n// alpha particle-electron mass ratio\n// (7294.2995361 \u00b1 2.9e-06)\nBOOST_AUTO_TEST_CASE_TEMPLATE(alpha_particle_electron_mass_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::alpha_particle_electron_mass_ratio<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::alpha_particle_electron_mass_ratio<\n                 T>::value() == static_cast<T>(7294.2995361));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::alpha_particle_electron_mass_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::alpha_particle_electron_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(2.9e-06));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::alpha_particle_electron_mass_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::alpha_particle_electron_mass_ratio<\n          T>::precision()));\n}\n\n// alpha particle mass\n// (6.64465675e-27 \u00b1 2.9e-34) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(alpha_particle_mass, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::alpha_particle_mass<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::alpha_particle_mass<T>::value() ==\n             static_cast<T>(6.64465675e-27));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::alpha_particle_mass<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::alpha_particle_mass<T>::uncertainty() ==\n      static_cast<T>(2.9e-34));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::alpha_particle_mass<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::alpha_particle_mass<T>::precision()));\n}\n\n// alpha particle mass energy equivalent\n// (5.97191967e-10 \u00b1 2.6e-17) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(alpha_particle_mass_energy_equivalent, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::alpha_particle_mass_energy_equivalent<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::alpha_particle_mass_energy_equivalent<\n          T>::value() == static_cast<T>(5.97191967e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::alpha_particle_mass_energy_equivalent<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::alpha_particle_mass_energy_equivalent<\n          T>::uncertainty() == static_cast<T>(2.6e-17));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::alpha_particle_mass_energy_equivalent<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::alpha_particle_mass_energy_equivalent<\n          T>::precision()));\n}\n\n// alpha particle mass energy equivalent in MeV\n// (3727.37924 \u00b1 8.2e-05) MeV\nBOOST_AUTO_TEST_CASE_TEMPLATE(alpha_particle_mass_energy_equivalent_in_MeV, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          alpha_particle_mass_energy_equivalent_in_MeV<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::\n                 alpha_particle_mass_energy_equivalent_in_MeV<T>::value() ==\n             static_cast<T>(3727.37924));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          alpha_particle_mass_energy_equivalent_in_MeV<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::\n          alpha_particle_mass_energy_equivalent_in_MeV<T>::uncertainty() ==\n      static_cast<T>(8.2e-05));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          alpha_particle_mass_energy_equivalent_in_MeV<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::\n          alpha_particle_mass_energy_equivalent_in_MeV<T>::precision()));\n}\n\n// alpha particle mass in u\n// (4.001506179125 \u00b1 6.2e-11) u\nBOOST_AUTO_TEST_CASE_TEMPLATE(alpha_particle_mass_in_u, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::alpha_particle_mass_in_u<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::alpha_particle_mass_in_u<T>::value() ==\n      static_cast<T>(4.001506179125));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::alpha_particle_mass_in_u<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::alpha_particle_mass_in_u<\n                 T>::uncertainty() == static_cast<T>(6.2e-11));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::alpha_particle_mass_in_u<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2010::alpha_particle_mass_in_u<\n                    T>::precision()));\n}\n\n// alpha particle molar mass\n// (0.004001506179125 \u00b1 6.2e-14) kg mol^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(alpha_particle_molar_mass, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::alpha_particle_molar_mass<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::alpha_particle_molar_mass<T>::value() ==\n      static_cast<T>(0.004001506179125));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::alpha_particle_molar_mass<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::alpha_particle_molar_mass<\n                 T>::uncertainty() == static_cast<T>(6.2e-14));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::alpha_particle_molar_mass<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2010::alpha_particle_molar_mass<\n                    T>::precision()));\n}\n\n// alpha particle-proton mass ratio\n// (3.97259968933 \u00b1 3.6e-10)\nBOOST_AUTO_TEST_CASE_TEMPLATE(alpha_particle_proton_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::alpha_particle_proton_mass_ratio<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::alpha_particle_proton_mass_ratio<\n                 T>::value() == static_cast<T>(3.97259968933));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::alpha_particle_proton_mass_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::alpha_particle_proton_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(3.6e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::alpha_particle_proton_mass_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::alpha_particle_proton_mass_ratio<\n          T>::precision()));\n}\n\n// Angstrom star\n// (1.00001495e-10 \u00b1 9e-17) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(Angstrom_star, T, test_types) {\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::Angstrom_star<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::Angstrom_star<T>::value() ==\n             static_cast<T>(1.00001495e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Angstrom_star<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::Angstrom_star<T>::uncertainty() ==\n             static_cast<T>(9e-17));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Angstrom_star<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::Angstrom_star<T>::precision()));\n}\n\n// atomic mass constant\n// (1.660538921e-27 \u00b1 7.3e-35) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_mass_constant, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_mass_constant<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::atomic_mass_constant<T>::value() ==\n             static_cast<T>(1.660538921e-27));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_mass_constant<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::atomic_mass_constant<T>::uncertainty() ==\n      static_cast<T>(7.3e-35));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_mass_constant<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::atomic_mass_constant<T>::precision()));\n}\n\n// atomic mass constant energy equivalent\n// (1.492417954e-10 \u00b1 6.6e-18) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_mass_constant_energy_equivalent, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_mass_constant_energy_equivalent<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::atomic_mass_constant_energy_equivalent<\n          T>::value() == static_cast<T>(1.492417954e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_mass_constant_energy_equivalent<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::atomic_mass_constant_energy_equivalent<\n          T>::uncertainty() == static_cast<T>(6.6e-18));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_mass_constant_energy_equivalent<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::atomic_mass_constant_energy_equivalent<\n          T>::precision()));\n}\n\n// atomic mass constant energy equivalent in MeV\n// (931.494061 \u00b1 2.1e-05) MeV\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_mass_constant_energy_equivalent_in_MeV, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          atomic_mass_constant_energy_equivalent_in_MeV<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::\n                 atomic_mass_constant_energy_equivalent_in_MeV<T>::value() ==\n             static_cast<T>(931.494061));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          atomic_mass_constant_energy_equivalent_in_MeV<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::\n          atomic_mass_constant_energy_equivalent_in_MeV<T>::uncertainty() ==\n      static_cast<T>(2.1e-05));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          atomic_mass_constant_energy_equivalent_in_MeV<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::\n          atomic_mass_constant_energy_equivalent_in_MeV<T>::precision()));\n}\n\n// atomic mass unit-electron volt relationship\n// (931494061.0 \u00b1 21.0) eV\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_mass_unit_electron_volt_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          atomic_mass_unit_electron_volt_relationship<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::\n                 atomic_mass_unit_electron_volt_relationship<T>::value() ==\n             static_cast<T>(931494061.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          atomic_mass_unit_electron_volt_relationship<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::\n          atomic_mass_unit_electron_volt_relationship<T>::uncertainty() ==\n      static_cast<T>(21.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          atomic_mass_unit_electron_volt_relationship<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::\n          atomic_mass_unit_electron_volt_relationship<T>::precision()));\n}\n\n// atomic mass unit-hartree relationship\n// (34231776.845 \u00b1 0.024) E_h\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_mass_unit_hartree_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_mass_unit_hartree_relationship<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::atomic_mass_unit_hartree_relationship<\n          T>::value() == static_cast<T>(34231776.845));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_mass_unit_hartree_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::atomic_mass_unit_hartree_relationship<\n          T>::uncertainty() == static_cast<T>(0.024));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_mass_unit_hartree_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::atomic_mass_unit_hartree_relationship<\n          T>::precision()));\n}\n\n// atomic mass unit-hertz relationship\n// (2.2523427168e+23 \u00b1 160000000000000.0) Hz\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_mass_unit_hertz_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_mass_unit_hertz_relationship<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::atomic_mass_unit_hertz_relationship<\n          T>::value() == static_cast<T>(2.2523427168e+23));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_mass_unit_hertz_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::atomic_mass_unit_hertz_relationship<\n          T>::uncertainty() == static_cast<T>(160000000000000.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_mass_unit_hertz_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::atomic_mass_unit_hertz_relationship<\n          T>::precision()));\n}\n\n// atomic mass unit-inverse meter relationship\n// (751300660420000.0 \u00b1 530000.0) m^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_mass_unit_inverse_meter_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          atomic_mass_unit_inverse_meter_relationship<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::\n                 atomic_mass_unit_inverse_meter_relationship<T>::value() ==\n             static_cast<T>(751300660420000.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          atomic_mass_unit_inverse_meter_relationship<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::\n          atomic_mass_unit_inverse_meter_relationship<T>::uncertainty() ==\n      static_cast<T>(530000.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          atomic_mass_unit_inverse_meter_relationship<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::\n          atomic_mass_unit_inverse_meter_relationship<T>::precision()));\n}\n\n// atomic mass unit-joule relationship\n// (1.492417954e-10 \u00b1 6.6e-18) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_mass_unit_joule_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_mass_unit_joule_relationship<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::atomic_mass_unit_joule_relationship<\n          T>::value() == static_cast<T>(1.492417954e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_mass_unit_joule_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::atomic_mass_unit_joule_relationship<\n          T>::uncertainty() == static_cast<T>(6.6e-18));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_mass_unit_joule_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::atomic_mass_unit_joule_relationship<\n          T>::precision()));\n}\n\n// atomic mass unit-kelvin relationship\n// (10809540800000.0 \u00b1 9800000.0) K\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_mass_unit_kelvin_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_mass_unit_kelvin_relationship<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::atomic_mass_unit_kelvin_relationship<\n          T>::value() == static_cast<T>(10809540800000.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_mass_unit_kelvin_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::atomic_mass_unit_kelvin_relationship<\n          T>::uncertainty() == static_cast<T>(9800000.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_mass_unit_kelvin_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::atomic_mass_unit_kelvin_relationship<\n          T>::precision()));\n}\n\n// atomic mass unit-kilogram relationship\n// (1.660538921e-27 \u00b1 7.3e-35) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_mass_unit_kilogram_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_mass_unit_kilogram_relationship<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::atomic_mass_unit_kilogram_relationship<\n          T>::value() == static_cast<T>(1.660538921e-27));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_mass_unit_kilogram_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::atomic_mass_unit_kilogram_relationship<\n          T>::uncertainty() == static_cast<T>(7.3e-35));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_mass_unit_kilogram_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::atomic_mass_unit_kilogram_relationship<\n          T>::precision()));\n}\n\n// atomic unit of 1st hyperpolarizability\n// (3.206361449e-53 \u00b1 7.1e-61) C^3 m^3 J^-2\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_1st_hyperpolarizability, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_1st_hyperpolarizability<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::atomic_unit_of_1st_hyperpolarizability<\n          T>::value() == static_cast<T>(3.206361449e-53));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_1st_hyperpolarizability<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::atomic_unit_of_1st_hyperpolarizability<\n          T>::uncertainty() == static_cast<T>(7.1e-61));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_1st_hyperpolarizability<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::atomic_unit_of_1st_hyperpolarizability<\n          T>::precision()));\n}\n\n// atomic unit of 2nd hyperpolarizability\n// (6.23538054e-65 \u00b1 2.8e-72) C^4 m^4 J^-3\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_2nd_hyperpolarizability, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_2nd_hyperpolarizability<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::atomic_unit_of_2nd_hyperpolarizability<\n          T>::value() == static_cast<T>(6.23538054e-65));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_2nd_hyperpolarizability<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::atomic_unit_of_2nd_hyperpolarizability<\n          T>::uncertainty() == static_cast<T>(2.8e-72));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_2nd_hyperpolarizability<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::atomic_unit_of_2nd_hyperpolarizability<\n          T>::precision()));\n}\n\n// atomic unit of action\n// (1.054571726e-34 \u00b1 4.7e-42) J s\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_action, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_action<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::atomic_unit_of_action<T>::value() ==\n      static_cast<T>(1.054571726e-34));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_action<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::atomic_unit_of_action<T>::uncertainty() ==\n      static_cast<T>(4.7e-42));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_action<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::atomic_unit_of_action<T>::precision()));\n}\n\n// atomic unit of charge\n// (1.602176565e-19 \u00b1 3.5e-27) C\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_charge, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_charge<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::atomic_unit_of_charge<T>::value() ==\n      static_cast<T>(1.602176565e-19));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_charge<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::atomic_unit_of_charge<T>::uncertainty() ==\n      static_cast<T>(3.5e-27));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_charge<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::atomic_unit_of_charge<T>::precision()));\n}\n\n// atomic unit of charge density\n// (1081202338000.0 \u00b1 24000.0) C m^-3\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_charge_density, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_charge_density<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::atomic_unit_of_charge_density<\n                 T>::value() == static_cast<T>(1081202338000.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_charge_density<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::atomic_unit_of_charge_density<\n                 T>::uncertainty() == static_cast<T>(24000.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_charge_density<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::atomic_unit_of_charge_density<\n          T>::precision()));\n}\n\n// atomic unit of current\n// (0.00662361795 \u00b1 1.5e-10) A\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_current, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_current<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::atomic_unit_of_current<T>::value() ==\n      static_cast<T>(0.00662361795));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::atomic_unit_of_current<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::atomic_unit_of_current<\n                 T>::uncertainty() == static_cast<T>(1.5e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_current<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::atomic_unit_of_current<T>::precision()));\n}\n\n// atomic unit of electric dipole mom.\n// (8.47835326e-30 \u00b1 1.9e-37) C m\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_electric_dipole_mom, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_electric_dipole_mom<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::atomic_unit_of_electric_dipole_mom<\n                 T>::value() == static_cast<T>(8.47835326e-30));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_electric_dipole_mom<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::atomic_unit_of_electric_dipole_mom<\n                 T>::uncertainty() == static_cast<T>(1.9e-37));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_electric_dipole_mom<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::atomic_unit_of_electric_dipole_mom<\n          T>::precision()));\n}\n\n// atomic unit of electric field\n// (514220652000.0 \u00b1 11000.0) V m^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_electric_field, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_electric_field<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::atomic_unit_of_electric_field<\n                 T>::value() == static_cast<T>(514220652000.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_electric_field<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::atomic_unit_of_electric_field<\n                 T>::uncertainty() == static_cast<T>(11000.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_electric_field<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::atomic_unit_of_electric_field<\n          T>::precision()));\n}\n\n// atomic unit of electric field gradient\n// (9.717362e+21 \u00b1 210000000000000.0) V m^-2\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_electric_field_gradient, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_electric_field_gradient<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::atomic_unit_of_electric_field_gradient<\n          T>::value() == static_cast<T>(9.717362e+21));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_electric_field_gradient<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::atomic_unit_of_electric_field_gradient<\n          T>::uncertainty() == static_cast<T>(210000000000000.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_electric_field_gradient<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::atomic_unit_of_electric_field_gradient<\n          T>::precision()));\n}\n\n// atomic unit of electric polarizability\n// (1.6487772754e-41 \u00b1 1.6e-50) C^2 m^2 J^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_electric_polarizability, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_electric_polarizability<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::atomic_unit_of_electric_polarizability<\n          T>::value() == static_cast<T>(1.6487772754e-41));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_electric_polarizability<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::atomic_unit_of_electric_polarizability<\n          T>::uncertainty() == static_cast<T>(1.6e-50));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_electric_polarizability<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::atomic_unit_of_electric_polarizability<\n          T>::precision()));\n}\n\n// atomic unit of electric potential\n// (27.21138505 \u00b1 6e-07) V\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_electric_potential, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_electric_potential<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::atomic_unit_of_electric_potential<\n                 T>::value() == static_cast<T>(27.21138505));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_electric_potential<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::atomic_unit_of_electric_potential<\n                 T>::uncertainty() == static_cast<T>(6e-07));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_electric_potential<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::atomic_unit_of_electric_potential<\n          T>::precision()));\n}\n\n// atomic unit of electric quadrupole mom.\n// (4.486551331e-40 \u00b1 9.9e-48) C m^2\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_electric_quadrupole_mom, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_electric_quadrupole_mom<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::atomic_unit_of_electric_quadrupole_mom<\n          T>::value() == static_cast<T>(4.486551331e-40));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_electric_quadrupole_mom<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::atomic_unit_of_electric_quadrupole_mom<\n          T>::uncertainty() == static_cast<T>(9.9e-48));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_electric_quadrupole_mom<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::atomic_unit_of_electric_quadrupole_mom<\n          T>::precision()));\n}\n\n// atomic unit of energy\n// (4.35974434e-18 \u00b1 1.9e-25) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_energy, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_energy<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::atomic_unit_of_energy<T>::value() ==\n      static_cast<T>(4.35974434e-18));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_energy<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::atomic_unit_of_energy<T>::uncertainty() ==\n      static_cast<T>(1.9e-25));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_energy<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::atomic_unit_of_energy<T>::precision()));\n}\n\n// atomic unit of force\n// (8.23872278e-08 \u00b1 3.6e-15) N\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_force, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_force<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::atomic_unit_of_force<T>::value() ==\n             static_cast<T>(8.23872278e-08));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_force<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::atomic_unit_of_force<T>::uncertainty() ==\n      static_cast<T>(3.6e-15));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_force<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::atomic_unit_of_force<T>::precision()));\n}\n\n// atomic unit of length\n// (5.2917721092e-11 \u00b1 1.7e-20) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_length, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_length<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::atomic_unit_of_length<T>::value() ==\n      static_cast<T>(5.2917721092e-11));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_length<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::atomic_unit_of_length<T>::uncertainty() ==\n      static_cast<T>(1.7e-20));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_length<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::atomic_unit_of_length<T>::precision()));\n}\n\n// atomic unit of mag. dipole mom.\n// (1.854801936e-23 \u00b1 4.1e-31) J T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_mag_dipole_mom, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_mag_dipole_mom<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::atomic_unit_of_mag_dipole_mom<\n                 T>::value() == static_cast<T>(1.854801936e-23));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_mag_dipole_mom<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::atomic_unit_of_mag_dipole_mom<\n                 T>::uncertainty() == static_cast<T>(4.1e-31));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_mag_dipole_mom<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::atomic_unit_of_mag_dipole_mom<\n          T>::precision()));\n}\n\n// atomic unit of mag. flux density\n// (235051.7464 \u00b1 0.0052) T\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_mag_flux_density, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_mag_flux_density<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::atomic_unit_of_mag_flux_density<\n                 T>::value() == static_cast<T>(235051.7464));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_mag_flux_density<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::atomic_unit_of_mag_flux_density<\n                 T>::uncertainty() == static_cast<T>(0.0052));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_mag_flux_density<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::atomic_unit_of_mag_flux_density<\n          T>::precision()));\n}\n\n// atomic unit of magnetizability\n// (7.891036607e-29 \u00b1 1.3e-37) J T^-2\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_magnetizability, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_magnetizability<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::atomic_unit_of_magnetizability<\n                 T>::value() == static_cast<T>(7.891036607e-29));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_magnetizability<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::atomic_unit_of_magnetizability<\n                 T>::uncertainty() == static_cast<T>(1.3e-37));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_magnetizability<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::atomic_unit_of_magnetizability<\n          T>::precision()));\n}\n\n// atomic unit of mass\n// (9.10938291e-31 \u00b1 4e-38) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_mass, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_mass<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::atomic_unit_of_mass<T>::value() ==\n             static_cast<T>(9.10938291e-31));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_mass<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::atomic_unit_of_mass<T>::uncertainty() ==\n      static_cast<T>(4e-38));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_mass<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::atomic_unit_of_mass<T>::precision()));\n}\n\n// atomic unit of mom.um\n// (1.99285174e-24 \u00b1 8.8e-32) kg m s^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_momum, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_momum<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::atomic_unit_of_momum<T>::value() ==\n             static_cast<T>(1.99285174e-24));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_momum<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::atomic_unit_of_momum<T>::uncertainty() ==\n      static_cast<T>(8.8e-32));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_momum<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::atomic_unit_of_momum<T>::precision()));\n}\n\n// atomic unit of permittivity\n// (1.112650056e-10 \u00b1 0.0) F m^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_permittivity, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_permittivity<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::atomic_unit_of_permittivity<T>::value() ==\n      static_cast<T>(1.112650056e-10));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::atomic_unit_of_permittivity<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::atomic_unit_of_permittivity<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::atomic_unit_of_permittivity<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2010::atomic_unit_of_permittivity<\n                    T>::precision()));\n}\n\n// atomic unit of time\n// (2.418884326502e-17 \u00b1 1.2e-28) s\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_time, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_time<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::atomic_unit_of_time<T>::value() ==\n             static_cast<T>(2.418884326502e-17));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_time<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::atomic_unit_of_time<T>::uncertainty() ==\n      static_cast<T>(1.2e-28));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_time<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::atomic_unit_of_time<T>::precision()));\n}\n\n// atomic unit of velocity\n// (2187691.26379 \u00b1 0.00071) m s^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(atomic_unit_of_velocity, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_velocity<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::atomic_unit_of_velocity<T>::value() ==\n      static_cast<T>(2187691.26379));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::atomic_unit_of_velocity<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::atomic_unit_of_velocity<\n                 T>::uncertainty() == static_cast<T>(0.00071));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::atomic_unit_of_velocity<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::atomic_unit_of_velocity<T>::precision()));\n}\n\n// Avogadro constant\n// (6.02214129e+23 \u00b1 2.7e+16) mol^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(Avogadro_constant, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Avogadro_constant<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::Avogadro_constant<T>::value() ==\n             static_cast<T>(6.02214129e+23));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Avogadro_constant<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::Avogadro_constant<T>::uncertainty() ==\n      static_cast<T>(2.7e+16));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Avogadro_constant<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::Avogadro_constant<T>::precision()));\n}\n\n// Bohr magneton\n// (9.27400968e-24 \u00b1 2e-31) J T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(Bohr_magneton, T, test_types) {\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::Bohr_magneton<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::Bohr_magneton<T>::value() ==\n             static_cast<T>(9.27400968e-24));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Bohr_magneton<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::Bohr_magneton<T>::uncertainty() ==\n             static_cast<T>(2e-31));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Bohr_magneton<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::Bohr_magneton<T>::precision()));\n}\n\n// Bohr magneton in eV/T\n// (5.7883818066e-05 \u00b1 3.8e-14) eV T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(Bohr_magneton_in_eV_T, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Bohr_magneton_in_eV_T<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::Bohr_magneton_in_eV_T<T>::value() ==\n      static_cast<T>(5.7883818066e-05));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Bohr_magneton_in_eV_T<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::Bohr_magneton_in_eV_T<T>::uncertainty() ==\n      static_cast<T>(3.8e-14));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Bohr_magneton_in_eV_T<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::Bohr_magneton_in_eV_T<T>::precision()));\n}\n\n// Bohr magneton in Hz/T\n// (13996245550.0 \u00b1 310.0) Hz T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(Bohr_magneton_in_Hz_T, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Bohr_magneton_in_Hz_T<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::Bohr_magneton_in_Hz_T<T>::value() ==\n      static_cast<T>(13996245550.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Bohr_magneton_in_Hz_T<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::Bohr_magneton_in_Hz_T<T>::uncertainty() ==\n      static_cast<T>(310.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Bohr_magneton_in_Hz_T<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::Bohr_magneton_in_Hz_T<T>::precision()));\n}\n\n// Bohr magneton in inverse meters per tesla\n// (46.6864498 \u00b1 1e-06) m^-1 T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(Bohr_magneton_in_inverse_meters_per_tesla, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Bohr_magneton_in_inverse_meters_per_tesla<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::Bohr_magneton_in_inverse_meters_per_tesla<\n          T>::value() == static_cast<T>(46.6864498));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Bohr_magneton_in_inverse_meters_per_tesla<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::Bohr_magneton_in_inverse_meters_per_tesla<\n          T>::uncertainty() == static_cast<T>(1e-06));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Bohr_magneton_in_inverse_meters_per_tesla<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::Bohr_magneton_in_inverse_meters_per_tesla<\n          T>::precision()));\n}\n\n// Bohr magneton in K/T\n// (0.67171388 \u00b1 6.1e-07) K T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(Bohr_magneton_in_K_T, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Bohr_magneton_in_K_T<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::Bohr_magneton_in_K_T<T>::value() ==\n             static_cast<T>(0.67171388));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Bohr_magneton_in_K_T<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::Bohr_magneton_in_K_T<T>::uncertainty() ==\n      static_cast<T>(6.1e-07));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Bohr_magneton_in_K_T<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::Bohr_magneton_in_K_T<T>::precision()));\n}\n\n// Bohr radius\n// (5.2917721092e-11 \u00b1 1.7e-20) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(Bohr_radius, T, test_types) {\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::Bohr_radius<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::Bohr_radius<T>::value() ==\n             static_cast<T>(5.2917721092e-11));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Bohr_radius<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::Bohr_radius<T>::uncertainty() ==\n             static_cast<T>(1.7e-20));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Bohr_radius<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::Bohr_radius<T>::precision()));\n}\n\n// Boltzmann constant\n// (1.3806488e-23 \u00b1 1.3e-29) J K^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(Boltzmann_constant, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Boltzmann_constant<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::Boltzmann_constant<T>::value() ==\n             static_cast<T>(1.3806488e-23));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Boltzmann_constant<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::Boltzmann_constant<T>::uncertainty() ==\n      static_cast<T>(1.3e-29));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Boltzmann_constant<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::Boltzmann_constant<T>::precision()));\n}\n\n// Boltzmann constant in eV/K\n// (8.6173324e-05 \u00b1 7.8e-11) eV K^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(Boltzmann_constant_in_eV_K, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Boltzmann_constant_in_eV_K<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::Boltzmann_constant_in_eV_K<T>::value() ==\n      static_cast<T>(8.6173324e-05));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::Boltzmann_constant_in_eV_K<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::Boltzmann_constant_in_eV_K<\n                 T>::uncertainty() == static_cast<T>(7.8e-11));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::Boltzmann_constant_in_eV_K<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2010::Boltzmann_constant_in_eV_K<\n                    T>::precision()));\n}\n\n// Boltzmann constant in Hz/K\n// (20836618000.0 \u00b1 19000.0) Hz K^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(Boltzmann_constant_in_Hz_K, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Boltzmann_constant_in_Hz_K<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::Boltzmann_constant_in_Hz_K<T>::value() ==\n      static_cast<T>(20836618000.0));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::Boltzmann_constant_in_Hz_K<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::Boltzmann_constant_in_Hz_K<\n                 T>::uncertainty() == static_cast<T>(19000.0));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::Boltzmann_constant_in_Hz_K<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2010::Boltzmann_constant_in_Hz_K<\n                    T>::precision()));\n}\n\n// Boltzmann constant in inverse meters per kelvin\n// (69.503476 \u00b1 6.3e-05) m^-1 K^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(Boltzmann_constant_in_inverse_meters_per_kelvin,\n                              T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          Boltzmann_constant_in_inverse_meters_per_kelvin<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::\n                 Boltzmann_constant_in_inverse_meters_per_kelvin<T>::value() ==\n             static_cast<T>(69.503476));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          Boltzmann_constant_in_inverse_meters_per_kelvin<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::\n          Boltzmann_constant_in_inverse_meters_per_kelvin<T>::uncertainty() ==\n      static_cast<T>(6.3e-05));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          Boltzmann_constant_in_inverse_meters_per_kelvin<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::\n          Boltzmann_constant_in_inverse_meters_per_kelvin<T>::precision()));\n}\n\n// characteristic impedance of vacuum\n// (376.730313461 \u00b1 0.0) ohm\nBOOST_AUTO_TEST_CASE_TEMPLATE(characteristic_impedance_of_vacuum, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::characteristic_impedance_of_vacuum<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::characteristic_impedance_of_vacuum<\n                 T>::value() == static_cast<T>(376.730313461));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::characteristic_impedance_of_vacuum<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::characteristic_impedance_of_vacuum<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::characteristic_impedance_of_vacuum<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::characteristic_impedance_of_vacuum<\n          T>::precision()));\n}\n\n// classical electron radius\n// (2.8179403267e-15 \u00b1 2.7e-24) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(classical_electron_radius, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::classical_electron_radius<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::classical_electron_radius<T>::value() ==\n      static_cast<T>(2.8179403267e-15));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::classical_electron_radius<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::classical_electron_radius<\n                 T>::uncertainty() == static_cast<T>(2.7e-24));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::classical_electron_radius<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2010::classical_electron_radius<\n                    T>::precision()));\n}\n\n// Compton wavelength\n// (2.4263102389e-12 \u00b1 1.6e-21) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(Compton_wavelength, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Compton_wavelength<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::Compton_wavelength<T>::value() ==\n             static_cast<T>(2.4263102389e-12));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Compton_wavelength<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::Compton_wavelength<T>::uncertainty() ==\n      static_cast<T>(1.6e-21));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Compton_wavelength<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::Compton_wavelength<T>::precision()));\n}\n\n// Compton wavelength over 2 pi\n// (3.86159268e-13 \u00b1 2.5e-22) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(Compton_wavelength_over_2_pi, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Compton_wavelength_over_2_pi<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::Compton_wavelength_over_2_pi<\n                 T>::value() == static_cast<T>(3.86159268e-13));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Compton_wavelength_over_2_pi<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::Compton_wavelength_over_2_pi<\n                 T>::uncertainty() == static_cast<T>(2.5e-22));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Compton_wavelength_over_2_pi<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::Compton_wavelength_over_2_pi<\n          T>::precision()));\n}\n\n// conductance quantum\n// (7.7480917346e-05 \u00b1 2.5e-14) S\nBOOST_AUTO_TEST_CASE_TEMPLATE(conductance_quantum, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::conductance_quantum<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::conductance_quantum<T>::value() ==\n             static_cast<T>(7.7480917346e-05));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::conductance_quantum<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::conductance_quantum<T>::uncertainty() ==\n      static_cast<T>(2.5e-14));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::conductance_quantum<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::conductance_quantum<T>::precision()));\n}\n\n// conventional value of Josephson constant\n// (483597900000000.0 \u00b1 0.0) Hz V^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(conventional_value_of_Josephson_constant, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::conventional_value_of_Josephson_constant<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::conventional_value_of_Josephson_constant<\n          T>::value() == static_cast<T>(483597900000000.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::conventional_value_of_Josephson_constant<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::conventional_value_of_Josephson_constant<\n          T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::conventional_value_of_Josephson_constant<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::conventional_value_of_Josephson_constant<\n          T>::precision()));\n}\n\n// conventional value of von Klitzing constant\n// (25812.807 \u00b1 0.0) ohm\nBOOST_AUTO_TEST_CASE_TEMPLATE(conventional_value_of_von_Klitzing_constant, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          conventional_value_of_von_Klitzing_constant<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::\n                 conventional_value_of_von_Klitzing_constant<T>::value() ==\n             static_cast<T>(25812.807));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          conventional_value_of_von_Klitzing_constant<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::\n          conventional_value_of_von_Klitzing_constant<T>::uncertainty() ==\n      static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          conventional_value_of_von_Klitzing_constant<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::\n          conventional_value_of_von_Klitzing_constant<T>::precision()));\n}\n\n// Cu x unit\n// (1.00207697e-13 \u00b1 2.8e-20) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(Cu_x_unit, T, test_types) {\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::Cu_x_unit<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::Cu_x_unit<T>::value() ==\n             static_cast<T>(1.00207697e-13));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Cu_x_unit<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::Cu_x_unit<T>::uncertainty() ==\n             static_cast<T>(2.8e-20));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::Cu_x_unit<T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2010::Cu_x_unit<T>::precision()));\n}\n\n// deuteron-electron mag. mom. ratio\n// (-0.0004664345537 \u00b1 3.9e-12)\nBOOST_AUTO_TEST_CASE_TEMPLATE(deuteron_electron_mag_mom_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::deuteron_electron_mag_mom_ratio<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::deuteron_electron_mag_mom_ratio<\n                 T>::value() == static_cast<T>(-0.0004664345537));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::deuteron_electron_mag_mom_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::deuteron_electron_mag_mom_ratio<\n                 T>::uncertainty() == static_cast<T>(3.9e-12));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::deuteron_electron_mag_mom_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::deuteron_electron_mag_mom_ratio<\n          T>::precision()));\n}\n\n// deuteron-electron mass ratio\n// (3670.4829652 \u00b1 1.5e-06)\nBOOST_AUTO_TEST_CASE_TEMPLATE(deuteron_electron_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::deuteron_electron_mass_ratio<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::deuteron_electron_mass_ratio<\n                 T>::value() == static_cast<T>(3670.4829652));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::deuteron_electron_mass_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::deuteron_electron_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(1.5e-06));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::deuteron_electron_mass_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::deuteron_electron_mass_ratio<\n          T>::precision()));\n}\n\n// deuteron g factor\n// (0.8574382308 \u00b1 7.2e-09)\nBOOST_AUTO_TEST_CASE_TEMPLATE(deuteron_g_factor, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::deuteron_g_factor<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::deuteron_g_factor<T>::value() ==\n             static_cast<T>(0.8574382308));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::deuteron_g_factor<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::deuteron_g_factor<T>::uncertainty() ==\n      static_cast<T>(7.2e-09));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::deuteron_g_factor<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::deuteron_g_factor<T>::precision()));\n}\n\n// deuteron mag. mom.\n// (4.33073489e-27 \u00b1 1e-34) J T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(deuteron_mag_mom, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::deuteron_mag_mom<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::deuteron_mag_mom<T>::value() ==\n             static_cast<T>(4.33073489e-27));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::deuteron_mag_mom<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::deuteron_mag_mom<T>::uncertainty() ==\n      static_cast<T>(1e-34));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::deuteron_mag_mom<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::deuteron_mag_mom<T>::precision()));\n}\n\n// deuteron mag. mom. to Bohr magneton ratio\n// (0.0004669754556 \u00b1 3.9e-12)\nBOOST_AUTO_TEST_CASE_TEMPLATE(deuteron_mag_mom_to_Bohr_magneton_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::deuteron_mag_mom_to_Bohr_magneton_ratio<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::deuteron_mag_mom_to_Bohr_magneton_ratio<\n          T>::value() == static_cast<T>(0.0004669754556));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::deuteron_mag_mom_to_Bohr_magneton_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::deuteron_mag_mom_to_Bohr_magneton_ratio<\n          T>::uncertainty() == static_cast<T>(3.9e-12));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::deuteron_mag_mom_to_Bohr_magneton_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::deuteron_mag_mom_to_Bohr_magneton_ratio<\n          T>::precision()));\n}\n\n// deuteron mag. mom. to nuclear magneton ratio\n// (0.8574382308 \u00b1 7.2e-09)\nBOOST_AUTO_TEST_CASE_TEMPLATE(deuteron_mag_mom_to_nuclear_magneton_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          deuteron_mag_mom_to_nuclear_magneton_ratio<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::\n                 deuteron_mag_mom_to_nuclear_magneton_ratio<T>::value() ==\n             static_cast<T>(0.8574382308));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          deuteron_mag_mom_to_nuclear_magneton_ratio<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::\n                 deuteron_mag_mom_to_nuclear_magneton_ratio<T>::uncertainty() ==\n             static_cast<T>(7.2e-09));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          deuteron_mag_mom_to_nuclear_magneton_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::\n          deuteron_mag_mom_to_nuclear_magneton_ratio<T>::precision()));\n}\n\n// deuteron mass\n// (3.34358348e-27 \u00b1 1.5e-34) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(deuteron_mass, T, test_types) {\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::deuteron_mass<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::deuteron_mass<T>::value() ==\n             static_cast<T>(3.34358348e-27));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::deuteron_mass<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::deuteron_mass<T>::uncertainty() ==\n             static_cast<T>(1.5e-34));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::deuteron_mass<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::deuteron_mass<T>::precision()));\n}\n\n// deuteron mass energy equivalent\n// (3.00506297e-10 \u00b1 1.3e-17) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(deuteron_mass_energy_equivalent, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::deuteron_mass_energy_equivalent<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::deuteron_mass_energy_equivalent<\n                 T>::value() == static_cast<T>(3.00506297e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::deuteron_mass_energy_equivalent<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::deuteron_mass_energy_equivalent<\n                 T>::uncertainty() == static_cast<T>(1.3e-17));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::deuteron_mass_energy_equivalent<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::deuteron_mass_energy_equivalent<\n          T>::precision()));\n}\n\n// deuteron mass energy equivalent in MeV\n// (1875.612859 \u00b1 4.1e-05) MeV\nBOOST_AUTO_TEST_CASE_TEMPLATE(deuteron_mass_energy_equivalent_in_MeV, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::deuteron_mass_energy_equivalent_in_MeV<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::deuteron_mass_energy_equivalent_in_MeV<\n          T>::value() == static_cast<T>(1875.612859));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::deuteron_mass_energy_equivalent_in_MeV<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::deuteron_mass_energy_equivalent_in_MeV<\n          T>::uncertainty() == static_cast<T>(4.1e-05));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::deuteron_mass_energy_equivalent_in_MeV<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::deuteron_mass_energy_equivalent_in_MeV<\n          T>::precision()));\n}\n\n// deuteron mass in u\n// (2.013553212712 \u00b1 7.7e-11) u\nBOOST_AUTO_TEST_CASE_TEMPLATE(deuteron_mass_in_u, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::deuteron_mass_in_u<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::deuteron_mass_in_u<T>::value() ==\n             static_cast<T>(2.013553212712));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::deuteron_mass_in_u<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::deuteron_mass_in_u<T>::uncertainty() ==\n      static_cast<T>(7.7e-11));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::deuteron_mass_in_u<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::deuteron_mass_in_u<T>::precision()));\n}\n\n// deuteron molar mass\n// (0.002013553212712 \u00b1 7.7e-14) kg mol^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(deuteron_molar_mass, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::deuteron_molar_mass<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::deuteron_molar_mass<T>::value() ==\n             static_cast<T>(0.002013553212712));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::deuteron_molar_mass<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::deuteron_molar_mass<T>::uncertainty() ==\n      static_cast<T>(7.7e-14));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::deuteron_molar_mass<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::deuteron_molar_mass<T>::precision()));\n}\n\n// deuteron-neutron mag. mom. ratio\n// (-0.44820652 \u00b1 1.1e-07)\nBOOST_AUTO_TEST_CASE_TEMPLATE(deuteron_neutron_mag_mom_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::deuteron_neutron_mag_mom_ratio<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::deuteron_neutron_mag_mom_ratio<\n                 T>::value() == static_cast<T>(-0.44820652));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::deuteron_neutron_mag_mom_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::deuteron_neutron_mag_mom_ratio<\n                 T>::uncertainty() == static_cast<T>(1.1e-07));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::deuteron_neutron_mag_mom_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::deuteron_neutron_mag_mom_ratio<\n          T>::precision()));\n}\n\n// deuteron-proton mag. mom. ratio\n// (0.307012207 \u00b1 2.4e-09)\nBOOST_AUTO_TEST_CASE_TEMPLATE(deuteron_proton_mag_mom_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::deuteron_proton_mag_mom_ratio<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::deuteron_proton_mag_mom_ratio<\n                 T>::value() == static_cast<T>(0.307012207));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::deuteron_proton_mag_mom_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::deuteron_proton_mag_mom_ratio<\n                 T>::uncertainty() == static_cast<T>(2.4e-09));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::deuteron_proton_mag_mom_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::deuteron_proton_mag_mom_ratio<\n          T>::precision()));\n}\n\n// deuteron-proton mass ratio\n// (1.99900750097 \u00b1 1.8e-10)\nBOOST_AUTO_TEST_CASE_TEMPLATE(deuteron_proton_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::deuteron_proton_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::deuteron_proton_mass_ratio<T>::value() ==\n      static_cast<T>(1.99900750097));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::deuteron_proton_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::deuteron_proton_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(1.8e-10));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::deuteron_proton_mass_ratio<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2010::deuteron_proton_mass_ratio<\n                    T>::precision()));\n}\n\n// deuteron rms charge radius\n// (2.1424e-15 \u00b1 2.1e-18) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(deuteron_rms_charge_radius, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::deuteron_rms_charge_radius<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::deuteron_rms_charge_radius<T>::value() ==\n      static_cast<T>(2.1424e-15));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::deuteron_rms_charge_radius<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::deuteron_rms_charge_radius<\n                 T>::uncertainty() == static_cast<T>(2.1e-18));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::deuteron_rms_charge_radius<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2010::deuteron_rms_charge_radius<\n                    T>::precision()));\n}\n\n// electric constant\n// (8.854187817e-12 \u00b1 0.0) F m^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(electric_constant, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electric_constant<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::electric_constant<T>::value() ==\n             static_cast<T>(8.854187817e-12));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electric_constant<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::electric_constant<T>::uncertainty() ==\n      static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electric_constant<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::electric_constant<T>::precision()));\n}\n\n// electron charge to mass quotient\n// (-175882008800.0 \u00b1 3900.0) C kg^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_charge_to_mass_quotient, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_charge_to_mass_quotient<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::electron_charge_to_mass_quotient<\n                 T>::value() == static_cast<T>(-175882008800.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_charge_to_mass_quotient<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::electron_charge_to_mass_quotient<\n                 T>::uncertainty() == static_cast<T>(3900.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_charge_to_mass_quotient<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::electron_charge_to_mass_quotient<\n          T>::precision()));\n}\n\n// electron-deuteron mag. mom. ratio\n// (-2143.923498 \u00b1 1.8e-05)\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_deuteron_mag_mom_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_deuteron_mag_mom_ratio<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::electron_deuteron_mag_mom_ratio<\n                 T>::value() == static_cast<T>(-2143.923498));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_deuteron_mag_mom_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::electron_deuteron_mag_mom_ratio<\n                 T>::uncertainty() == static_cast<T>(1.8e-05));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_deuteron_mag_mom_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::electron_deuteron_mag_mom_ratio<\n          T>::precision()));\n}\n\n// electron-deuteron mass ratio\n// (0.00027244371095 \u00b1 1.1e-13)\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_deuteron_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_deuteron_mass_ratio<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::electron_deuteron_mass_ratio<\n                 T>::value() == static_cast<T>(0.00027244371095));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_deuteron_mass_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::electron_deuteron_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(1.1e-13));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_deuteron_mass_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::electron_deuteron_mass_ratio<\n          T>::precision()));\n}\n\n// electron g factor\n// (-2.00231930436153 \u00b1 5.3e-13)\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_g_factor, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_g_factor<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::electron_g_factor<T>::value() ==\n             static_cast<T>(-2.00231930436153));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_g_factor<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::electron_g_factor<T>::uncertainty() ==\n      static_cast<T>(5.3e-13));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_g_factor<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::electron_g_factor<T>::precision()));\n}\n\n// electron gyromag. ratio\n// (176085970800.0 \u00b1 3900.0) s^-1 T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_gyromag_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_gyromag_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::electron_gyromag_ratio<T>::value() ==\n      static_cast<T>(176085970800.0));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::electron_gyromag_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::electron_gyromag_ratio<\n                 T>::uncertainty() == static_cast<T>(3900.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_gyromag_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::electron_gyromag_ratio<T>::precision()));\n}\n\n// electron gyromag. ratio over 2 pi\n// (28024.95266 \u00b1 0.00062) MHz T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_gyromag_ratio_over_2_pi, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_gyromag_ratio_over_2_pi<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::electron_gyromag_ratio_over_2_pi<\n                 T>::value() == static_cast<T>(28024.95266));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_gyromag_ratio_over_2_pi<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::electron_gyromag_ratio_over_2_pi<\n                 T>::uncertainty() == static_cast<T>(0.00062));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_gyromag_ratio_over_2_pi<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::electron_gyromag_ratio_over_2_pi<\n          T>::precision()));\n}\n\n// electron-helion mass ratio\n// (0.00018195430761 \u00b1 1.7e-13)\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_helion_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_helion_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::electron_helion_mass_ratio<T>::value() ==\n      static_cast<T>(0.00018195430761));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::electron_helion_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::electron_helion_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(1.7e-13));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::electron_helion_mass_ratio<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2010::electron_helion_mass_ratio<\n                    T>::precision()));\n}\n\n// electron mag. mom.\n// (-9.2847643e-24 \u00b1 2.1e-31) J T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_mag_mom, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_mag_mom<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::electron_mag_mom<T>::value() ==\n             static_cast<T>(-9.2847643e-24));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_mag_mom<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::electron_mag_mom<T>::uncertainty() ==\n      static_cast<T>(2.1e-31));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_mag_mom<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::electron_mag_mom<T>::precision()));\n}\n\n// electron mag. mom. anomaly\n// (0.00115965218076 \u00b1 2.7e-13)\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_mag_mom_anomaly, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_mag_mom_anomaly<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::electron_mag_mom_anomaly<T>::value() ==\n      static_cast<T>(0.00115965218076));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::electron_mag_mom_anomaly<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::electron_mag_mom_anomaly<\n                 T>::uncertainty() == static_cast<T>(2.7e-13));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::electron_mag_mom_anomaly<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2010::electron_mag_mom_anomaly<\n                    T>::precision()));\n}\n\n// electron mag. mom. to Bohr magneton ratio\n// (-1.00115965218076 \u00b1 2.7e-13)\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_mag_mom_to_Bohr_magneton_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_mag_mom_to_Bohr_magneton_ratio<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::electron_mag_mom_to_Bohr_magneton_ratio<\n          T>::value() == static_cast<T>(-1.00115965218076));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_mag_mom_to_Bohr_magneton_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::electron_mag_mom_to_Bohr_magneton_ratio<\n          T>::uncertainty() == static_cast<T>(2.7e-13));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_mag_mom_to_Bohr_magneton_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::electron_mag_mom_to_Bohr_magneton_ratio<\n          T>::precision()));\n}\n\n// electron mag. mom. to nuclear magneton ratio\n// (-1838.2819709 \u00b1 7.5e-07)\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_mag_mom_to_nuclear_magneton_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          electron_mag_mom_to_nuclear_magneton_ratio<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::\n                 electron_mag_mom_to_nuclear_magneton_ratio<T>::value() ==\n             static_cast<T>(-1838.2819709));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          electron_mag_mom_to_nuclear_magneton_ratio<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::\n                 electron_mag_mom_to_nuclear_magneton_ratio<T>::uncertainty() ==\n             static_cast<T>(7.5e-07));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          electron_mag_mom_to_nuclear_magneton_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::\n          electron_mag_mom_to_nuclear_magneton_ratio<T>::precision()));\n}\n\n// electron mass\n// (9.10938291e-31 \u00b1 4e-38) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_mass, T, test_types) {\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::electron_mass<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::electron_mass<T>::value() ==\n             static_cast<T>(9.10938291e-31));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_mass<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::electron_mass<T>::uncertainty() ==\n             static_cast<T>(4e-38));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_mass<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::electron_mass<T>::precision()));\n}\n\n// electron mass energy equivalent\n// (8.18710506e-14 \u00b1 3.6e-21) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_mass_energy_equivalent, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_mass_energy_equivalent<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::electron_mass_energy_equivalent<\n                 T>::value() == static_cast<T>(8.18710506e-14));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_mass_energy_equivalent<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::electron_mass_energy_equivalent<\n                 T>::uncertainty() == static_cast<T>(3.6e-21));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_mass_energy_equivalent<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::electron_mass_energy_equivalent<\n          T>::precision()));\n}\n\n// electron mass energy equivalent in MeV\n// (0.510998928 \u00b1 1.1e-08) MeV\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_mass_energy_equivalent_in_MeV, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_mass_energy_equivalent_in_MeV<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::electron_mass_energy_equivalent_in_MeV<\n          T>::value() == static_cast<T>(0.510998928));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_mass_energy_equivalent_in_MeV<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::electron_mass_energy_equivalent_in_MeV<\n          T>::uncertainty() == static_cast<T>(1.1e-08));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_mass_energy_equivalent_in_MeV<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::electron_mass_energy_equivalent_in_MeV<\n          T>::precision()));\n}\n\n// electron mass in u\n// (0.00054857990946 \u00b1 2.2e-13) u\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_mass_in_u, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_mass_in_u<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::electron_mass_in_u<T>::value() ==\n             static_cast<T>(0.00054857990946));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_mass_in_u<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::electron_mass_in_u<T>::uncertainty() ==\n      static_cast<T>(2.2e-13));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_mass_in_u<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::electron_mass_in_u<T>::precision()));\n}\n\n// electron molar mass\n// (5.4857990946e-07 \u00b1 2.2e-16) kg mol^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_molar_mass, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_molar_mass<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::electron_molar_mass<T>::value() ==\n             static_cast<T>(5.4857990946e-07));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_molar_mass<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::electron_molar_mass<T>::uncertainty() ==\n      static_cast<T>(2.2e-16));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_molar_mass<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::electron_molar_mass<T>::precision()));\n}\n\n// electron-muon mag. mom. ratio\n// (206.7669896 \u00b1 5.2e-06)\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_muon_mag_mom_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_muon_mag_mom_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::electron_muon_mag_mom_ratio<T>::value() ==\n      static_cast<T>(206.7669896));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::electron_muon_mag_mom_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::electron_muon_mag_mom_ratio<\n                 T>::uncertainty() == static_cast<T>(5.2e-06));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::electron_muon_mag_mom_ratio<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2010::electron_muon_mag_mom_ratio<\n                    T>::precision()));\n}\n\n// electron-muon mass ratio\n// (0.00483633166 \u00b1 1.2e-10)\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_muon_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_muon_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::electron_muon_mass_ratio<T>::value() ==\n      static_cast<T>(0.00483633166));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::electron_muon_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::electron_muon_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(1.2e-10));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::electron_muon_mass_ratio<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2010::electron_muon_mass_ratio<\n                    T>::precision()));\n}\n\n// electron-neutron mag. mom. ratio\n// (960.9205 \u00b1 0.00023)\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_neutron_mag_mom_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_neutron_mag_mom_ratio<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::electron_neutron_mag_mom_ratio<\n                 T>::value() == static_cast<T>(960.9205));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_neutron_mag_mom_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::electron_neutron_mag_mom_ratio<\n                 T>::uncertainty() == static_cast<T>(0.00023));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_neutron_mag_mom_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::electron_neutron_mag_mom_ratio<\n          T>::precision()));\n}\n\n// electron-neutron mass ratio\n// (0.00054386734461 \u00b1 3.2e-13)\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_neutron_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_neutron_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::electron_neutron_mass_ratio<T>::value() ==\n      static_cast<T>(0.00054386734461));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::electron_neutron_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::electron_neutron_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(3.2e-13));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::electron_neutron_mass_ratio<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2010::electron_neutron_mass_ratio<\n                    T>::precision()));\n}\n\n// electron-proton mag. mom. ratio\n// (-658.2106848 \u00b1 5.4e-06)\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_proton_mag_mom_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_proton_mag_mom_ratio<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::electron_proton_mag_mom_ratio<\n                 T>::value() == static_cast<T>(-658.2106848));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_proton_mag_mom_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::electron_proton_mag_mom_ratio<\n                 T>::uncertainty() == static_cast<T>(5.4e-06));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_proton_mag_mom_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::electron_proton_mag_mom_ratio<\n          T>::precision()));\n}\n\n// electron-proton mass ratio\n// (0.00054461702178 \u00b1 2.2e-13)\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_proton_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_proton_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::electron_proton_mass_ratio<T>::value() ==\n      static_cast<T>(0.00054461702178));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::electron_proton_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::electron_proton_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(2.2e-13));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::electron_proton_mass_ratio<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2010::electron_proton_mass_ratio<\n                    T>::precision()));\n}\n\n// electron-tau mass ratio\n// (0.000287592 \u00b1 2.6e-08)\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_tau_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_tau_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::electron_tau_mass_ratio<T>::value() ==\n      static_cast<T>(0.000287592));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::electron_tau_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::electron_tau_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(2.6e-08));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_tau_mass_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::electron_tau_mass_ratio<T>::precision()));\n}\n\n// electron to alpha particle mass ratio\n// (0.000137093355578 \u00b1 5.5e-14)\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_to_alpha_particle_mass_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_to_alpha_particle_mass_ratio<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::electron_to_alpha_particle_mass_ratio<\n          T>::value() == static_cast<T>(0.000137093355578));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_to_alpha_particle_mass_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::electron_to_alpha_particle_mass_ratio<\n          T>::uncertainty() == static_cast<T>(5.5e-14));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_to_alpha_particle_mass_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::electron_to_alpha_particle_mass_ratio<\n          T>::precision()));\n}\n\n// electron to shielded helion mag. mom. ratio\n// (864.058257 \u00b1 1e-05)\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_to_shielded_helion_mag_mom_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_to_shielded_helion_mag_mom_ratio<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::electron_to_shielded_helion_mag_mom_ratio<\n          T>::value() == static_cast<T>(864.058257));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_to_shielded_helion_mag_mom_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::electron_to_shielded_helion_mag_mom_ratio<\n          T>::uncertainty() == static_cast<T>(1e-05));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_to_shielded_helion_mag_mom_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::electron_to_shielded_helion_mag_mom_ratio<\n          T>::precision()));\n}\n\n// electron to shielded proton mag. mom. ratio\n// (-658.2275971 \u00b1 7.2e-06)\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_to_shielded_proton_mag_mom_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_to_shielded_proton_mag_mom_ratio<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::electron_to_shielded_proton_mag_mom_ratio<\n          T>::value() == static_cast<T>(-658.2275971));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_to_shielded_proton_mag_mom_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::electron_to_shielded_proton_mag_mom_ratio<\n          T>::uncertainty() == static_cast<T>(7.2e-06));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_to_shielded_proton_mag_mom_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::electron_to_shielded_proton_mag_mom_ratio<\n          T>::precision()));\n}\n\n// electron-triton mass ratio\n// (0.00018192000653 \u00b1 1.7e-13)\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_triton_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_triton_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::electron_triton_mass_ratio<T>::value() ==\n      static_cast<T>(0.00018192000653));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::electron_triton_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::electron_triton_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(1.7e-13));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::electron_triton_mass_ratio<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2010::electron_triton_mass_ratio<\n                    T>::precision()));\n}\n\n// electron volt\n// (1.602176565e-19 \u00b1 3.5e-27) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_volt, T, test_types) {\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::electron_volt<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::electron_volt<T>::value() ==\n             static_cast<T>(1.602176565e-19));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_volt<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::electron_volt<T>::uncertainty() ==\n             static_cast<T>(3.5e-27));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_volt<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::electron_volt<T>::precision()));\n}\n\n// electron volt-atomic mass unit relationship\n// (1.07354415e-09 \u00b1 2.4e-17) u\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_volt_atomic_mass_unit_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          electron_volt_atomic_mass_unit_relationship<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::\n                 electron_volt_atomic_mass_unit_relationship<T>::value() ==\n             static_cast<T>(1.07354415e-09));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          electron_volt_atomic_mass_unit_relationship<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::\n          electron_volt_atomic_mass_unit_relationship<T>::uncertainty() ==\n      static_cast<T>(2.4e-17));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          electron_volt_atomic_mass_unit_relationship<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::\n          electron_volt_atomic_mass_unit_relationship<T>::precision()));\n}\n\n// electron volt-hartree relationship\n// (0.03674932379 \u00b1 8.1e-10) E_h\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_volt_hartree_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_volt_hartree_relationship<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::electron_volt_hartree_relationship<\n                 T>::value() == static_cast<T>(0.03674932379));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_volt_hartree_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::electron_volt_hartree_relationship<\n                 T>::uncertainty() == static_cast<T>(8.1e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_volt_hartree_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::electron_volt_hartree_relationship<\n          T>::precision()));\n}\n\n// electron volt-hertz relationship\n// (241798934800000.0 \u00b1 5300000.0) Hz\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_volt_hertz_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_volt_hertz_relationship<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::electron_volt_hertz_relationship<\n                 T>::value() == static_cast<T>(241798934800000.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_volt_hertz_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::electron_volt_hertz_relationship<\n                 T>::uncertainty() == static_cast<T>(5300000.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_volt_hertz_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::electron_volt_hertz_relationship<\n          T>::precision()));\n}\n\n// electron volt-inverse meter relationship\n// (806554.429 \u00b1 0.018) m^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_volt_inverse_meter_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_volt_inverse_meter_relationship<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::electron_volt_inverse_meter_relationship<\n          T>::value() == static_cast<T>(806554.429));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_volt_inverse_meter_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::electron_volt_inverse_meter_relationship<\n          T>::uncertainty() == static_cast<T>(0.018));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_volt_inverse_meter_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::electron_volt_inverse_meter_relationship<\n          T>::precision()));\n}\n\n// electron volt-joule relationship\n// (1.602176565e-19 \u00b1 3.5e-27) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_volt_joule_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_volt_joule_relationship<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::electron_volt_joule_relationship<\n                 T>::value() == static_cast<T>(1.602176565e-19));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_volt_joule_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::electron_volt_joule_relationship<\n                 T>::uncertainty() == static_cast<T>(3.5e-27));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_volt_joule_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::electron_volt_joule_relationship<\n          T>::precision()));\n}\n\n// electron volt-kelvin relationship\n// (11604.519 \u00b1 0.011) K\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_volt_kelvin_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_volt_kelvin_relationship<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::electron_volt_kelvin_relationship<\n                 T>::value() == static_cast<T>(11604.519));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_volt_kelvin_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::electron_volt_kelvin_relationship<\n                 T>::uncertainty() == static_cast<T>(0.011));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_volt_kelvin_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::electron_volt_kelvin_relationship<\n          T>::precision()));\n}\n\n// electron volt-kilogram relationship\n// (1.782661845e-36 \u00b1 3.9e-44) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(electron_volt_kilogram_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_volt_kilogram_relationship<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::electron_volt_kilogram_relationship<\n          T>::value() == static_cast<T>(1.782661845e-36));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_volt_kilogram_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::electron_volt_kilogram_relationship<\n          T>::uncertainty() == static_cast<T>(3.9e-44));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::electron_volt_kilogram_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::electron_volt_kilogram_relationship<\n          T>::precision()));\n}\n\n// elementary charge\n// (1.602176565e-19 \u00b1 3.5e-27) C\nBOOST_AUTO_TEST_CASE_TEMPLATE(elementary_charge, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::elementary_charge<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::elementary_charge<T>::value() ==\n             static_cast<T>(1.602176565e-19));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::elementary_charge<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::elementary_charge<T>::uncertainty() ==\n      static_cast<T>(3.5e-27));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::elementary_charge<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::elementary_charge<T>::precision()));\n}\n\n// elementary charge over h\n// (241798934800000.0 \u00b1 5300000.0) A J^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(elementary_charge_over_h, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::elementary_charge_over_h<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::elementary_charge_over_h<T>::value() ==\n      static_cast<T>(241798934800000.0));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::elementary_charge_over_h<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::elementary_charge_over_h<\n                 T>::uncertainty() == static_cast<T>(5300000.0));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::elementary_charge_over_h<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2010::elementary_charge_over_h<\n                    T>::precision()));\n}\n\n// Faraday constant\n// (96485.3365 \u00b1 0.0021) C mol^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(Faraday_constant, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Faraday_constant<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::Faraday_constant<T>::value() ==\n             static_cast<T>(96485.3365));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Faraday_constant<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::Faraday_constant<T>::uncertainty() ==\n      static_cast<T>(0.0021));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Faraday_constant<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::Faraday_constant<T>::precision()));\n}\n\n// Faraday constant for conventional electric current\n// (96485.3321 \u00b1 0.0043) C_90 mol^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(\n    Faraday_constant_for_conventional_electric_current, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          Faraday_constant_for_conventional_electric_current<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::\n          Faraday_constant_for_conventional_electric_current<T>::value() ==\n      static_cast<T>(96485.3321));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::\n                        Faraday_constant_for_conventional_electric_current<\n                            T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::\n                 Faraday_constant_for_conventional_electric_current<\n                     T>::uncertainty() == static_cast<T>(0.0043));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          Faraday_constant_for_conventional_electric_current<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::\n          Faraday_constant_for_conventional_electric_current<T>::precision()));\n}\n\n// Fermi coupling constant\n// (1.166364e-05 \u00b1 5e-11) GeV^-2\nBOOST_AUTO_TEST_CASE_TEMPLATE(Fermi_coupling_constant, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Fermi_coupling_constant<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::Fermi_coupling_constant<T>::value() ==\n      static_cast<T>(1.166364e-05));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::Fermi_coupling_constant<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::Fermi_coupling_constant<\n                 T>::uncertainty() == static_cast<T>(5e-11));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Fermi_coupling_constant<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::Fermi_coupling_constant<T>::precision()));\n}\n\n// fine-structure constant\n// (0.0072973525698 \u00b1 2.4e-12)\nBOOST_AUTO_TEST_CASE_TEMPLATE(fine_structure_constant, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::fine_structure_constant<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::fine_structure_constant<T>::value() ==\n      static_cast<T>(0.0072973525698));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::fine_structure_constant<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::fine_structure_constant<\n                 T>::uncertainty() == static_cast<T>(2.4e-12));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::fine_structure_constant<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::fine_structure_constant<T>::precision()));\n}\n\n// first radiation constant\n// (3.74177153e-16 \u00b1 1.7e-23) W m^2\nBOOST_AUTO_TEST_CASE_TEMPLATE(first_radiation_constant, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::first_radiation_constant<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::first_radiation_constant<T>::value() ==\n      static_cast<T>(3.74177153e-16));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::first_radiation_constant<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::first_radiation_constant<\n                 T>::uncertainty() == static_cast<T>(1.7e-23));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::first_radiation_constant<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2010::first_radiation_constant<\n                    T>::precision()));\n}\n\n// first radiation constant for spectral radiance\n// (1.191042869e-16 \u00b1 5.3e-24) W m^2 sr^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(first_radiation_constant_for_spectral_radiance, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          first_radiation_constant_for_spectral_radiance<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::\n                 first_radiation_constant_for_spectral_radiance<T>::value() ==\n             static_cast<T>(1.191042869e-16));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          first_radiation_constant_for_spectral_radiance<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::\n          first_radiation_constant_for_spectral_radiance<T>::uncertainty() ==\n      static_cast<T>(5.3e-24));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          first_radiation_constant_for_spectral_radiance<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::\n          first_radiation_constant_for_spectral_radiance<T>::precision()));\n}\n\n// hartree-atomic mass unit relationship\n// (2.9212623246e-08 \u00b1 2.1e-17) u\nBOOST_AUTO_TEST_CASE_TEMPLATE(hartree_atomic_mass_unit_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::hartree_atomic_mass_unit_relationship<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::hartree_atomic_mass_unit_relationship<\n          T>::value() == static_cast<T>(2.9212623246e-08));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::hartree_atomic_mass_unit_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::hartree_atomic_mass_unit_relationship<\n          T>::uncertainty() == static_cast<T>(2.1e-17));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::hartree_atomic_mass_unit_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::hartree_atomic_mass_unit_relationship<\n          T>::precision()));\n}\n\n// hartree-electron volt relationship\n// (27.21138505 \u00b1 6e-07) eV\nBOOST_AUTO_TEST_CASE_TEMPLATE(hartree_electron_volt_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::hartree_electron_volt_relationship<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::hartree_electron_volt_relationship<\n                 T>::value() == static_cast<T>(27.21138505));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::hartree_electron_volt_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::hartree_electron_volt_relationship<\n                 T>::uncertainty() == static_cast<T>(6e-07));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::hartree_electron_volt_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::hartree_electron_volt_relationship<\n          T>::precision()));\n}\n\n// Hartree energy\n// (4.35974434e-18 \u00b1 1.9e-25) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(Hartree_energy, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Hartree_energy<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::Hartree_energy<T>::value() ==\n             static_cast<T>(4.35974434e-18));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Hartree_energy<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::Hartree_energy<T>::uncertainty() ==\n             static_cast<T>(1.9e-25));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Hartree_energy<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::Hartree_energy<T>::precision()));\n}\n\n// Hartree energy in eV\n// (27.21138505 \u00b1 6e-07) eV\nBOOST_AUTO_TEST_CASE_TEMPLATE(Hartree_energy_in_eV, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Hartree_energy_in_eV<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::Hartree_energy_in_eV<T>::value() ==\n             static_cast<T>(27.21138505));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Hartree_energy_in_eV<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::Hartree_energy_in_eV<T>::uncertainty() ==\n      static_cast<T>(6e-07));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Hartree_energy_in_eV<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::Hartree_energy_in_eV<T>::precision()));\n}\n\n// hartree-hertz relationship\n// (6579683920729000.0 \u00b1 33000.0) Hz\nBOOST_AUTO_TEST_CASE_TEMPLATE(hartree_hertz_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::hartree_hertz_relationship<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::hartree_hertz_relationship<T>::value() ==\n      static_cast<T>(6579683920729000.0));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::hartree_hertz_relationship<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::hartree_hertz_relationship<\n                 T>::uncertainty() == static_cast<T>(33000.0));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::hartree_hertz_relationship<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2010::hartree_hertz_relationship<\n                    T>::precision()));\n}\n\n// hartree-inverse meter relationship\n// (21947463.13708 \u00b1 0.00011) m^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(hartree_inverse_meter_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::hartree_inverse_meter_relationship<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::hartree_inverse_meter_relationship<\n                 T>::value() == static_cast<T>(21947463.13708));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::hartree_inverse_meter_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::hartree_inverse_meter_relationship<\n                 T>::uncertainty() == static_cast<T>(0.00011));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::hartree_inverse_meter_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::hartree_inverse_meter_relationship<\n          T>::precision()));\n}\n\n// hartree-joule relationship\n// (4.35974434e-18 \u00b1 1.9e-25) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(hartree_joule_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::hartree_joule_relationship<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::hartree_joule_relationship<T>::value() ==\n      static_cast<T>(4.35974434e-18));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::hartree_joule_relationship<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::hartree_joule_relationship<\n                 T>::uncertainty() == static_cast<T>(1.9e-25));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::hartree_joule_relationship<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2010::hartree_joule_relationship<\n                    T>::precision()));\n}\n\n// hartree-kelvin relationship\n// (315775.04 \u00b1 0.29) K\nBOOST_AUTO_TEST_CASE_TEMPLATE(hartree_kelvin_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::hartree_kelvin_relationship<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::hartree_kelvin_relationship<T>::value() ==\n      static_cast<T>(315775.04));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::hartree_kelvin_relationship<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::hartree_kelvin_relationship<\n                 T>::uncertainty() == static_cast<T>(0.29));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::hartree_kelvin_relationship<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2010::hartree_kelvin_relationship<\n                    T>::precision()));\n}\n\n// hartree-kilogram relationship\n// (4.85086979e-35 \u00b1 2.1e-42) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(hartree_kilogram_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::hartree_kilogram_relationship<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::hartree_kilogram_relationship<\n                 T>::value() == static_cast<T>(4.85086979e-35));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::hartree_kilogram_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::hartree_kilogram_relationship<\n                 T>::uncertainty() == static_cast<T>(2.1e-42));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::hartree_kilogram_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::hartree_kilogram_relationship<\n          T>::precision()));\n}\n\n// helion-electron mass ratio\n// (5495.8852754 \u00b1 5e-06)\nBOOST_AUTO_TEST_CASE_TEMPLATE(helion_electron_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::helion_electron_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::helion_electron_mass_ratio<T>::value() ==\n      static_cast<T>(5495.8852754));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::helion_electron_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::helion_electron_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(5e-06));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::helion_electron_mass_ratio<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2010::helion_electron_mass_ratio<\n                    T>::precision()));\n}\n\n// helion g factor\n// (-4.255250613 \u00b1 5e-08)\nBOOST_AUTO_TEST_CASE_TEMPLATE(helion_g_factor, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::helion_g_factor<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::helion_g_factor<T>::value() ==\n             static_cast<T>(-4.255250613));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::helion_g_factor<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::helion_g_factor<T>::uncertainty() ==\n      static_cast<T>(5e-08));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::helion_g_factor<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::helion_g_factor<T>::precision()));\n}\n\n// helion mag. mom.\n// (-1.074617486e-26 \u00b1 2.7e-34) J T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(helion_mag_mom, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::helion_mag_mom<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::helion_mag_mom<T>::value() ==\n             static_cast<T>(-1.074617486e-26));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::helion_mag_mom<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::helion_mag_mom<T>::uncertainty() ==\n             static_cast<T>(2.7e-34));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::helion_mag_mom<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::helion_mag_mom<T>::precision()));\n}\n\n// helion mag. mom. to Bohr magneton ratio\n// (-0.001158740958 \u00b1 1.4e-11)\nBOOST_AUTO_TEST_CASE_TEMPLATE(helion_mag_mom_to_Bohr_magneton_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::helion_mag_mom_to_Bohr_magneton_ratio<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::helion_mag_mom_to_Bohr_magneton_ratio<\n          T>::value() == static_cast<T>(-0.001158740958));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::helion_mag_mom_to_Bohr_magneton_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::helion_mag_mom_to_Bohr_magneton_ratio<\n          T>::uncertainty() == static_cast<T>(1.4e-11));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::helion_mag_mom_to_Bohr_magneton_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::helion_mag_mom_to_Bohr_magneton_ratio<\n          T>::precision()));\n}\n\n// helion mag. mom. to nuclear magneton ratio\n// (-2.127625306 \u00b1 2.5e-08)\nBOOST_AUTO_TEST_CASE_TEMPLATE(helion_mag_mom_to_nuclear_magneton_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::helion_mag_mom_to_nuclear_magneton_ratio<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::helion_mag_mom_to_nuclear_magneton_ratio<\n          T>::value() == static_cast<T>(-2.127625306));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::helion_mag_mom_to_nuclear_magneton_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::helion_mag_mom_to_nuclear_magneton_ratio<\n          T>::uncertainty() == static_cast<T>(2.5e-08));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::helion_mag_mom_to_nuclear_magneton_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::helion_mag_mom_to_nuclear_magneton_ratio<\n          T>::precision()));\n}\n\n// helion mass\n// (5.00641234e-27 \u00b1 2.2e-34) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(helion_mass, T, test_types) {\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::helion_mass<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::helion_mass<T>::value() ==\n             static_cast<T>(5.00641234e-27));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::helion_mass<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::helion_mass<T>::uncertainty() ==\n             static_cast<T>(2.2e-34));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::helion_mass<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::helion_mass<T>::precision()));\n}\n\n// helion mass energy equivalent\n// (4.49953902e-10 \u00b1 2e-17) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(helion_mass_energy_equivalent, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::helion_mass_energy_equivalent<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::helion_mass_energy_equivalent<\n                 T>::value() == static_cast<T>(4.49953902e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::helion_mass_energy_equivalent<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::helion_mass_energy_equivalent<\n                 T>::uncertainty() == static_cast<T>(2e-17));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::helion_mass_energy_equivalent<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::helion_mass_energy_equivalent<\n          T>::precision()));\n}\n\n// helion mass energy equivalent in MeV\n// (2808.391482 \u00b1 6.2e-05) MeV\nBOOST_AUTO_TEST_CASE_TEMPLATE(helion_mass_energy_equivalent_in_MeV, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::helion_mass_energy_equivalent_in_MeV<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::helion_mass_energy_equivalent_in_MeV<\n          T>::value() == static_cast<T>(2808.391482));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::helion_mass_energy_equivalent_in_MeV<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::helion_mass_energy_equivalent_in_MeV<\n          T>::uncertainty() == static_cast<T>(6.2e-05));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::helion_mass_energy_equivalent_in_MeV<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::helion_mass_energy_equivalent_in_MeV<\n          T>::precision()));\n}\n\n// helion mass in u\n// (3.0149322468 \u00b1 2.5e-09) u\nBOOST_AUTO_TEST_CASE_TEMPLATE(helion_mass_in_u, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::helion_mass_in_u<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::helion_mass_in_u<T>::value() ==\n             static_cast<T>(3.0149322468));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::helion_mass_in_u<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::helion_mass_in_u<T>::uncertainty() ==\n      static_cast<T>(2.5e-09));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::helion_mass_in_u<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::helion_mass_in_u<T>::precision()));\n}\n\n// helion molar mass\n// (0.0030149322468 \u00b1 2.5e-12) kg mol^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(helion_molar_mass, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::helion_molar_mass<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::helion_molar_mass<T>::value() ==\n             static_cast<T>(0.0030149322468));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::helion_molar_mass<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::helion_molar_mass<T>::uncertainty() ==\n      static_cast<T>(2.5e-12));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::helion_molar_mass<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::helion_molar_mass<T>::precision()));\n}\n\n// helion-proton mass ratio\n// (2.9931526707 \u00b1 2.5e-09)\nBOOST_AUTO_TEST_CASE_TEMPLATE(helion_proton_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::helion_proton_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::helion_proton_mass_ratio<T>::value() ==\n      static_cast<T>(2.9931526707));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::helion_proton_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::helion_proton_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(2.5e-09));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::helion_proton_mass_ratio<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2010::helion_proton_mass_ratio<\n                    T>::precision()));\n}\n\n// hertz-atomic mass unit relationship\n// (4.4398216689e-24 \u00b1 3.1e-33) u\nBOOST_AUTO_TEST_CASE_TEMPLATE(hertz_atomic_mass_unit_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::hertz_atomic_mass_unit_relationship<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::hertz_atomic_mass_unit_relationship<\n          T>::value() == static_cast<T>(4.4398216689e-24));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::hertz_atomic_mass_unit_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::hertz_atomic_mass_unit_relationship<\n          T>::uncertainty() == static_cast<T>(3.1e-33));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::hertz_atomic_mass_unit_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::hertz_atomic_mass_unit_relationship<\n          T>::precision()));\n}\n\n// hertz-electron volt relationship\n// (4.135667516e-15 \u00b1 9.1e-23) eV\nBOOST_AUTO_TEST_CASE_TEMPLATE(hertz_electron_volt_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::hertz_electron_volt_relationship<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::hertz_electron_volt_relationship<\n                 T>::value() == static_cast<T>(4.135667516e-15));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::hertz_electron_volt_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::hertz_electron_volt_relationship<\n                 T>::uncertainty() == static_cast<T>(9.1e-23));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::hertz_electron_volt_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::hertz_electron_volt_relationship<\n          T>::precision()));\n}\n\n// hertz-hartree relationship\n// (1.5198298460045e-16 \u00b1 7.6e-28) E_h\nBOOST_AUTO_TEST_CASE_TEMPLATE(hertz_hartree_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::hertz_hartree_relationship<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::hertz_hartree_relationship<T>::value() ==\n      static_cast<T>(1.5198298460045e-16));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::hertz_hartree_relationship<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::hertz_hartree_relationship<\n                 T>::uncertainty() == static_cast<T>(7.6e-28));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::hertz_hartree_relationship<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2010::hertz_hartree_relationship<\n                    T>::precision()));\n}\n\n// hertz-inverse meter relationship\n// (3.335640951e-09 \u00b1 0.0) m^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(hertz_inverse_meter_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::hertz_inverse_meter_relationship<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::hertz_inverse_meter_relationship<\n                 T>::value() == static_cast<T>(3.335640951e-09));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::hertz_inverse_meter_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::hertz_inverse_meter_relationship<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::hertz_inverse_meter_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::hertz_inverse_meter_relationship<\n          T>::precision()));\n}\n\n// hertz-joule relationship\n// (6.62606957e-34 \u00b1 2.9e-41) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(hertz_joule_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::hertz_joule_relationship<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::hertz_joule_relationship<T>::value() ==\n      static_cast<T>(6.62606957e-34));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::hertz_joule_relationship<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::hertz_joule_relationship<\n                 T>::uncertainty() == static_cast<T>(2.9e-41));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::hertz_joule_relationship<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2010::hertz_joule_relationship<\n                    T>::precision()));\n}\n\n// hertz-kelvin relationship\n// (4.7992434e-11 \u00b1 4.4e-17) K\nBOOST_AUTO_TEST_CASE_TEMPLATE(hertz_kelvin_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::hertz_kelvin_relationship<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::hertz_kelvin_relationship<T>::value() ==\n      static_cast<T>(4.7992434e-11));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::hertz_kelvin_relationship<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::hertz_kelvin_relationship<\n                 T>::uncertainty() == static_cast<T>(4.4e-17));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::hertz_kelvin_relationship<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2010::hertz_kelvin_relationship<\n                    T>::precision()));\n}\n\n// hertz-kilogram relationship\n// (7.37249668e-51 \u00b1 3.3e-58) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(hertz_kilogram_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::hertz_kilogram_relationship<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::hertz_kilogram_relationship<T>::value() ==\n      static_cast<T>(7.37249668e-51));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::hertz_kilogram_relationship<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::hertz_kilogram_relationship<\n                 T>::uncertainty() == static_cast<T>(3.3e-58));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::hertz_kilogram_relationship<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2010::hertz_kilogram_relationship<\n                    T>::precision()));\n}\n\n// inverse fine-structure constant\n// (137.035999074 \u00b1 4.4e-08)\nBOOST_AUTO_TEST_CASE_TEMPLATE(inverse_fine_structure_constant, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::inverse_fine_structure_constant<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::inverse_fine_structure_constant<\n                 T>::value() == static_cast<T>(137.035999074));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::inverse_fine_structure_constant<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::inverse_fine_structure_constant<\n                 T>::uncertainty() == static_cast<T>(4.4e-08));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::inverse_fine_structure_constant<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::inverse_fine_structure_constant<\n          T>::precision()));\n}\n\n// inverse meter-atomic mass unit relationship\n// (1.3310250512e-15 \u00b1 9.4e-25) u\nBOOST_AUTO_TEST_CASE_TEMPLATE(inverse_meter_atomic_mass_unit_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          inverse_meter_atomic_mass_unit_relationship<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::\n                 inverse_meter_atomic_mass_unit_relationship<T>::value() ==\n             static_cast<T>(1.3310250512e-15));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          inverse_meter_atomic_mass_unit_relationship<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::\n          inverse_meter_atomic_mass_unit_relationship<T>::uncertainty() ==\n      static_cast<T>(9.4e-25));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          inverse_meter_atomic_mass_unit_relationship<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::\n          inverse_meter_atomic_mass_unit_relationship<T>::precision()));\n}\n\n// inverse meter-electron volt relationship\n// (1.23984193e-06 \u00b1 2.7e-14) eV\nBOOST_AUTO_TEST_CASE_TEMPLATE(inverse_meter_electron_volt_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::inverse_meter_electron_volt_relationship<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::inverse_meter_electron_volt_relationship<\n          T>::value() == static_cast<T>(1.23984193e-06));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::inverse_meter_electron_volt_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::inverse_meter_electron_volt_relationship<\n          T>::uncertainty() == static_cast<T>(2.7e-14));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::inverse_meter_electron_volt_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::inverse_meter_electron_volt_relationship<\n          T>::precision()));\n}\n\n// inverse meter-hartree relationship\n// (4.556335252755e-08 \u00b1 2.3e-19) E_h\nBOOST_AUTO_TEST_CASE_TEMPLATE(inverse_meter_hartree_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::inverse_meter_hartree_relationship<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::inverse_meter_hartree_relationship<\n                 T>::value() == static_cast<T>(4.556335252755e-08));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::inverse_meter_hartree_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::inverse_meter_hartree_relationship<\n                 T>::uncertainty() == static_cast<T>(2.3e-19));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::inverse_meter_hartree_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::inverse_meter_hartree_relationship<\n          T>::precision()));\n}\n\n// inverse meter-hertz relationship\n// (299792458.0 \u00b1 0.0) Hz\nBOOST_AUTO_TEST_CASE_TEMPLATE(inverse_meter_hertz_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::inverse_meter_hertz_relationship<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::inverse_meter_hertz_relationship<\n                 T>::value() == static_cast<T>(299792458.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::inverse_meter_hertz_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::inverse_meter_hertz_relationship<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::inverse_meter_hertz_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::inverse_meter_hertz_relationship<\n          T>::precision()));\n}\n\n// inverse meter-joule relationship\n// (1.986445684e-25 \u00b1 8.8e-33) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(inverse_meter_joule_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::inverse_meter_joule_relationship<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::inverse_meter_joule_relationship<\n                 T>::value() == static_cast<T>(1.986445684e-25));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::inverse_meter_joule_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::inverse_meter_joule_relationship<\n                 T>::uncertainty() == static_cast<T>(8.8e-33));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::inverse_meter_joule_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::inverse_meter_joule_relationship<\n          T>::precision()));\n}\n\n// inverse meter-kelvin relationship\n// (0.01438777 \u00b1 1.3e-08) K\nBOOST_AUTO_TEST_CASE_TEMPLATE(inverse_meter_kelvin_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::inverse_meter_kelvin_relationship<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::inverse_meter_kelvin_relationship<\n                 T>::value() == static_cast<T>(0.01438777));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::inverse_meter_kelvin_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::inverse_meter_kelvin_relationship<\n                 T>::uncertainty() == static_cast<T>(1.3e-08));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::inverse_meter_kelvin_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::inverse_meter_kelvin_relationship<\n          T>::precision()));\n}\n\n// inverse meter-kilogram relationship\n// (2.210218902e-42 \u00b1 9.8e-50) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(inverse_meter_kilogram_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::inverse_meter_kilogram_relationship<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::inverse_meter_kilogram_relationship<\n          T>::value() == static_cast<T>(2.210218902e-42));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::inverse_meter_kilogram_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::inverse_meter_kilogram_relationship<\n          T>::uncertainty() == static_cast<T>(9.8e-50));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::inverse_meter_kilogram_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::inverse_meter_kilogram_relationship<\n          T>::precision()));\n}\n\n// inverse of conductance quantum\n// (12906.4037217 \u00b1 4.2e-06) ohm\nBOOST_AUTO_TEST_CASE_TEMPLATE(inverse_of_conductance_quantum, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::inverse_of_conductance_quantum<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::inverse_of_conductance_quantum<\n                 T>::value() == static_cast<T>(12906.4037217));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::inverse_of_conductance_quantum<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::inverse_of_conductance_quantum<\n                 T>::uncertainty() == static_cast<T>(4.2e-06));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::inverse_of_conductance_quantum<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::inverse_of_conductance_quantum<\n          T>::precision()));\n}\n\n// Josephson constant\n// (483597870000000.0 \u00b1 11000000.0) Hz V^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(Josephson_constant, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Josephson_constant<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::Josephson_constant<T>::value() ==\n             static_cast<T>(483597870000000.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Josephson_constant<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::Josephson_constant<T>::uncertainty() ==\n      static_cast<T>(11000000.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Josephson_constant<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::Josephson_constant<T>::precision()));\n}\n\n// joule-atomic mass unit relationship\n// (6700535850.0 \u00b1 300.0) u\nBOOST_AUTO_TEST_CASE_TEMPLATE(joule_atomic_mass_unit_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::joule_atomic_mass_unit_relationship<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::joule_atomic_mass_unit_relationship<\n          T>::value() == static_cast<T>(6700535850.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::joule_atomic_mass_unit_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::joule_atomic_mass_unit_relationship<\n          T>::uncertainty() == static_cast<T>(300.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::joule_atomic_mass_unit_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::joule_atomic_mass_unit_relationship<\n          T>::precision()));\n}\n\n// joule-electron volt relationship\n// (6.24150934e+18 \u00b1 140000000000.0) eV\nBOOST_AUTO_TEST_CASE_TEMPLATE(joule_electron_volt_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::joule_electron_volt_relationship<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::joule_electron_volt_relationship<\n                 T>::value() == static_cast<T>(6.24150934e+18));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::joule_electron_volt_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::joule_electron_volt_relationship<\n                 T>::uncertainty() == static_cast<T>(140000000000.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::joule_electron_volt_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::joule_electron_volt_relationship<\n          T>::precision()));\n}\n\n// joule-hartree relationship\n// (2.29371248e+17 \u00b1 10000000000.0) E_h\nBOOST_AUTO_TEST_CASE_TEMPLATE(joule_hartree_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::joule_hartree_relationship<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::joule_hartree_relationship<T>::value() ==\n      static_cast<T>(2.29371248e+17));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::joule_hartree_relationship<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::joule_hartree_relationship<\n                 T>::uncertainty() == static_cast<T>(10000000000.0));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::joule_hartree_relationship<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2010::joule_hartree_relationship<\n                    T>::precision()));\n}\n\n// joule-hertz relationship\n// (1.509190311e+33 \u00b1 6.7e+25) Hz\nBOOST_AUTO_TEST_CASE_TEMPLATE(joule_hertz_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::joule_hertz_relationship<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::joule_hertz_relationship<T>::value() ==\n      static_cast<T>(1.509190311e+33));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::joule_hertz_relationship<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::joule_hertz_relationship<\n                 T>::uncertainty() == static_cast<T>(6.7e+25));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::joule_hertz_relationship<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2010::joule_hertz_relationship<\n                    T>::precision()));\n}\n\n// joule-inverse meter relationship\n// (5.03411701e+24 \u00b1 2.2e+17) m^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(joule_inverse_meter_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::joule_inverse_meter_relationship<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::joule_inverse_meter_relationship<\n                 T>::value() == static_cast<T>(5.03411701e+24));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::joule_inverse_meter_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::joule_inverse_meter_relationship<\n                 T>::uncertainty() == static_cast<T>(2.2e+17));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::joule_inverse_meter_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::joule_inverse_meter_relationship<\n          T>::precision()));\n}\n\n// joule-kelvin relationship\n// (7.2429716e+22 \u00b1 6.6e+16) K\nBOOST_AUTO_TEST_CASE_TEMPLATE(joule_kelvin_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::joule_kelvin_relationship<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::joule_kelvin_relationship<T>::value() ==\n      static_cast<T>(7.2429716e+22));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::joule_kelvin_relationship<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::joule_kelvin_relationship<\n                 T>::uncertainty() == static_cast<T>(6.6e+16));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::joule_kelvin_relationship<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2010::joule_kelvin_relationship<\n                    T>::precision()));\n}\n\n// joule-kilogram relationship\n// (1.112650056e-17 \u00b1 0.0) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(joule_kilogram_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::joule_kilogram_relationship<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::joule_kilogram_relationship<T>::value() ==\n      static_cast<T>(1.112650056e-17));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::joule_kilogram_relationship<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::joule_kilogram_relationship<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::joule_kilogram_relationship<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2010::joule_kilogram_relationship<\n                    T>::precision()));\n}\n\n// kelvin-atomic mass unit relationship\n// (9.2510868e-14 \u00b1 8.4e-20) u\nBOOST_AUTO_TEST_CASE_TEMPLATE(kelvin_atomic_mass_unit_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::kelvin_atomic_mass_unit_relationship<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::kelvin_atomic_mass_unit_relationship<\n          T>::value() == static_cast<T>(9.2510868e-14));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::kelvin_atomic_mass_unit_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::kelvin_atomic_mass_unit_relationship<\n          T>::uncertainty() == static_cast<T>(8.4e-20));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::kelvin_atomic_mass_unit_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::kelvin_atomic_mass_unit_relationship<\n          T>::precision()));\n}\n\n// kelvin-electron volt relationship\n// (8.6173324e-05 \u00b1 7.8e-11) eV\nBOOST_AUTO_TEST_CASE_TEMPLATE(kelvin_electron_volt_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::kelvin_electron_volt_relationship<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::kelvin_electron_volt_relationship<\n                 T>::value() == static_cast<T>(8.6173324e-05));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::kelvin_electron_volt_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::kelvin_electron_volt_relationship<\n                 T>::uncertainty() == static_cast<T>(7.8e-11));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::kelvin_electron_volt_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::kelvin_electron_volt_relationship<\n          T>::precision()));\n}\n\n// kelvin-hartree relationship\n// (3.1668114e-06 \u00b1 2.9e-12) E_h\nBOOST_AUTO_TEST_CASE_TEMPLATE(kelvin_hartree_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::kelvin_hartree_relationship<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::kelvin_hartree_relationship<T>::value() ==\n      static_cast<T>(3.1668114e-06));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::kelvin_hartree_relationship<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::kelvin_hartree_relationship<\n                 T>::uncertainty() == static_cast<T>(2.9e-12));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::kelvin_hartree_relationship<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2010::kelvin_hartree_relationship<\n                    T>::precision()));\n}\n\n// kelvin-hertz relationship\n// (20836618000.0 \u00b1 19000.0) Hz\nBOOST_AUTO_TEST_CASE_TEMPLATE(kelvin_hertz_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::kelvin_hertz_relationship<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::kelvin_hertz_relationship<T>::value() ==\n      static_cast<T>(20836618000.0));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::kelvin_hertz_relationship<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::kelvin_hertz_relationship<\n                 T>::uncertainty() == static_cast<T>(19000.0));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::kelvin_hertz_relationship<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2010::kelvin_hertz_relationship<\n                    T>::precision()));\n}\n\n// kelvin-inverse meter relationship\n// (69.503476 \u00b1 6.3e-05) m^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(kelvin_inverse_meter_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::kelvin_inverse_meter_relationship<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::kelvin_inverse_meter_relationship<\n                 T>::value() == static_cast<T>(69.503476));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::kelvin_inverse_meter_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::kelvin_inverse_meter_relationship<\n                 T>::uncertainty() == static_cast<T>(6.3e-05));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::kelvin_inverse_meter_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::kelvin_inverse_meter_relationship<\n          T>::precision()));\n}\n\n// kelvin-joule relationship\n// (1.3806488e-23 \u00b1 1.3e-29) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(kelvin_joule_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::kelvin_joule_relationship<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::kelvin_joule_relationship<T>::value() ==\n      static_cast<T>(1.3806488e-23));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::kelvin_joule_relationship<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::kelvin_joule_relationship<\n                 T>::uncertainty() == static_cast<T>(1.3e-29));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::kelvin_joule_relationship<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2010::kelvin_joule_relationship<\n                    T>::precision()));\n}\n\n// kelvin-kilogram relationship\n// (1.536179e-40 \u00b1 1.4e-46) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(kelvin_kilogram_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::kelvin_kilogram_relationship<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::kelvin_kilogram_relationship<\n                 T>::value() == static_cast<T>(1.536179e-40));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::kelvin_kilogram_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::kelvin_kilogram_relationship<\n                 T>::uncertainty() == static_cast<T>(1.4e-46));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::kelvin_kilogram_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::kelvin_kilogram_relationship<\n          T>::precision()));\n}\n\n// kilogram-atomic mass unit relationship\n// (6.02214129e+26 \u00b1 2.7e+19) u\nBOOST_AUTO_TEST_CASE_TEMPLATE(kilogram_atomic_mass_unit_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::kilogram_atomic_mass_unit_relationship<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::kilogram_atomic_mass_unit_relationship<\n          T>::value() == static_cast<T>(6.02214129e+26));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::kilogram_atomic_mass_unit_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::kilogram_atomic_mass_unit_relationship<\n          T>::uncertainty() == static_cast<T>(2.7e+19));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::kilogram_atomic_mass_unit_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::kilogram_atomic_mass_unit_relationship<\n          T>::precision()));\n}\n\n// kilogram-electron volt relationship\n// (5.60958885e+35 \u00b1 1.2e+28) eV\nBOOST_AUTO_TEST_CASE_TEMPLATE(kilogram_electron_volt_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::kilogram_electron_volt_relationship<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::kilogram_electron_volt_relationship<\n          T>::value() == static_cast<T>(5.60958885e+35));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::kilogram_electron_volt_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::kilogram_electron_volt_relationship<\n          T>::uncertainty() == static_cast<T>(1.2e+28));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::kilogram_electron_volt_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::kilogram_electron_volt_relationship<\n          T>::precision()));\n}\n\n// kilogram-hartree relationship\n// (2.061485968e+34 \u00b1 9.1e+26) E_h\nBOOST_AUTO_TEST_CASE_TEMPLATE(kilogram_hartree_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::kilogram_hartree_relationship<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::kilogram_hartree_relationship<\n                 T>::value() == static_cast<T>(2.061485968e+34));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::kilogram_hartree_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::kilogram_hartree_relationship<\n                 T>::uncertainty() == static_cast<T>(9.1e+26));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::kilogram_hartree_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::kilogram_hartree_relationship<\n          T>::precision()));\n}\n\n// kilogram-hertz relationship\n// (1.356392608e+50 \u00b1 6e+42) Hz\nBOOST_AUTO_TEST_CASE_TEMPLATE(kilogram_hertz_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::kilogram_hertz_relationship<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::kilogram_hertz_relationship<T>::value() ==\n      static_cast<T>(1.356392608e+50));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::kilogram_hertz_relationship<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::kilogram_hertz_relationship<\n                 T>::uncertainty() == static_cast<T>(6e+42));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::kilogram_hertz_relationship<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2010::kilogram_hertz_relationship<\n                    T>::precision()));\n}\n\n// kilogram-inverse meter relationship\n// (4.52443873e+41 \u00b1 2e+34) m^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(kilogram_inverse_meter_relationship, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::kilogram_inverse_meter_relationship<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::kilogram_inverse_meter_relationship<\n          T>::value() == static_cast<T>(4.52443873e+41));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::kilogram_inverse_meter_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::kilogram_inverse_meter_relationship<\n          T>::uncertainty() == static_cast<T>(2e+34));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::kilogram_inverse_meter_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::kilogram_inverse_meter_relationship<\n          T>::precision()));\n}\n\n// kilogram-joule relationship\n// (8.987551787e+16 \u00b1 0.0) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(kilogram_joule_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::kilogram_joule_relationship<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::kilogram_joule_relationship<T>::value() ==\n      static_cast<T>(8.987551787e+16));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::kilogram_joule_relationship<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::kilogram_joule_relationship<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::kilogram_joule_relationship<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2010::kilogram_joule_relationship<\n                    T>::precision()));\n}\n\n// kilogram-kelvin relationship\n// (6.5096582e+39 \u00b1 5.9e+33) K\nBOOST_AUTO_TEST_CASE_TEMPLATE(kilogram_kelvin_relationship, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::kilogram_kelvin_relationship<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::kilogram_kelvin_relationship<\n                 T>::value() == static_cast<T>(6.5096582e+39));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::kilogram_kelvin_relationship<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::kilogram_kelvin_relationship<\n                 T>::uncertainty() == static_cast<T>(5.9e+33));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::kilogram_kelvin_relationship<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::kilogram_kelvin_relationship<\n          T>::precision()));\n}\n\n// lattice parameter of silicon\n// (5.431020504e-10 \u00b1 8.9e-18) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(lattice_parameter_of_silicon, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::lattice_parameter_of_silicon<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::lattice_parameter_of_silicon<\n                 T>::value() == static_cast<T>(5.431020504e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::lattice_parameter_of_silicon<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::lattice_parameter_of_silicon<\n                 T>::uncertainty() == static_cast<T>(8.9e-18));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::lattice_parameter_of_silicon<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::lattice_parameter_of_silicon<\n          T>::precision()));\n}\n\n// Loschmidt constant (273.15 K, 100 kPa)\n// (2.6516462e+25 \u00b1 2.4e+19) m^-3\nBOOST_AUTO_TEST_CASE_TEMPLATE(Loschmidt_constant_27315_K_100_kPa, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Loschmidt_constant_27315_K_100_kPa<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::Loschmidt_constant_27315_K_100_kPa<\n                 T>::value() == static_cast<T>(2.6516462e+25));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Loschmidt_constant_27315_K_100_kPa<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::Loschmidt_constant_27315_K_100_kPa<\n                 T>::uncertainty() == static_cast<T>(2.4e+19));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Loschmidt_constant_27315_K_100_kPa<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::Loschmidt_constant_27315_K_100_kPa<\n          T>::precision()));\n}\n\n// Loschmidt constant (273.15 K, 101.325 kPa)\n// (2.6867805e+25 \u00b1 2.4e+19) m^-3\nBOOST_AUTO_TEST_CASE_TEMPLATE(Loschmidt_constant_27315_K_101325_kPa, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Loschmidt_constant_27315_K_101325_kPa<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::Loschmidt_constant_27315_K_101325_kPa<\n          T>::value() == static_cast<T>(2.6867805e+25));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Loschmidt_constant_27315_K_101325_kPa<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::Loschmidt_constant_27315_K_101325_kPa<\n          T>::uncertainty() == static_cast<T>(2.4e+19));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Loschmidt_constant_27315_K_101325_kPa<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::Loschmidt_constant_27315_K_101325_kPa<\n          T>::precision()));\n}\n\n// mag. constant\n// (1.2566370614e-06 \u00b1 0.0) N A^-2\nBOOST_AUTO_TEST_CASE_TEMPLATE(mag_constant, T, test_types) {\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::mag_constant<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::mag_constant<T>::value() ==\n             static_cast<T>(1.2566370614e-06));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::mag_constant<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::mag_constant<T>::uncertainty() ==\n             static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::mag_constant<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::mag_constant<T>::precision()));\n}\n\n// mag. flux quantum\n// (2.067833758e-15 \u00b1 4.6e-23) Wb\nBOOST_AUTO_TEST_CASE_TEMPLATE(mag_flux_quantum, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::mag_flux_quantum<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::mag_flux_quantum<T>::value() ==\n             static_cast<T>(2.067833758e-15));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::mag_flux_quantum<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::mag_flux_quantum<T>::uncertainty() ==\n      static_cast<T>(4.6e-23));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::mag_flux_quantum<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::mag_flux_quantum<T>::precision()));\n}\n\n// molar gas constant\n// (8.3144621 \u00b1 7.5e-06) J mol^-1 K^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(molar_gas_constant, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::molar_gas_constant<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::molar_gas_constant<T>::value() ==\n             static_cast<T>(8.3144621));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::molar_gas_constant<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::molar_gas_constant<T>::uncertainty() ==\n      static_cast<T>(7.5e-06));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::molar_gas_constant<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::molar_gas_constant<T>::precision()));\n}\n\n// molar mass constant\n// (0.001 \u00b1 0.0) kg mol^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(molar_mass_constant, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::molar_mass_constant<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::molar_mass_constant<T>::value() ==\n             static_cast<T>(0.001));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::molar_mass_constant<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::molar_mass_constant<T>::uncertainty() ==\n      static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::molar_mass_constant<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::molar_mass_constant<T>::precision()));\n}\n\n// molar mass of carbon-12\n// (0.012 \u00b1 0.0) kg mol^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(molar_mass_of_carbon_12, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::molar_mass_of_carbon_12<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::molar_mass_of_carbon_12<T>::value() ==\n      static_cast<T>(0.012));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::molar_mass_of_carbon_12<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::molar_mass_of_carbon_12<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::molar_mass_of_carbon_12<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::molar_mass_of_carbon_12<T>::precision()));\n}\n\n// molar Planck constant\n// (3.9903127176e-10 \u00b1 2.8e-19) J s mol^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(molar_Planck_constant, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::molar_Planck_constant<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::molar_Planck_constant<T>::value() ==\n      static_cast<T>(3.9903127176e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::molar_Planck_constant<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::molar_Planck_constant<T>::uncertainty() ==\n      static_cast<T>(2.8e-19));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::molar_Planck_constant<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::molar_Planck_constant<T>::precision()));\n}\n\n// molar Planck constant times c\n// (0.119626565779 \u00b1 8.4e-11) J m mol^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(molar_Planck_constant_times_c, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::molar_Planck_constant_times_c<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::molar_Planck_constant_times_c<\n                 T>::value() == static_cast<T>(0.119626565779));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::molar_Planck_constant_times_c<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::molar_Planck_constant_times_c<\n                 T>::uncertainty() == static_cast<T>(8.4e-11));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::molar_Planck_constant_times_c<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::molar_Planck_constant_times_c<\n          T>::precision()));\n}\n\n// molar volume of ideal gas (273.15 K, 100 kPa)\n// (0.022710953 \u00b1 2.1e-08) m^3 mol^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(molar_volume_of_ideal_gas_27315_K_100_kPa, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::molar_volume_of_ideal_gas_27315_K_100_kPa<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::molar_volume_of_ideal_gas_27315_K_100_kPa<\n          T>::value() == static_cast<T>(0.022710953));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::molar_volume_of_ideal_gas_27315_K_100_kPa<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::molar_volume_of_ideal_gas_27315_K_100_kPa<\n          T>::uncertainty() == static_cast<T>(2.1e-08));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::molar_volume_of_ideal_gas_27315_K_100_kPa<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::molar_volume_of_ideal_gas_27315_K_100_kPa<\n          T>::precision()));\n}\n\n// molar volume of ideal gas (273.15 K, 101.325 kPa)\n// (0.022413968 \u00b1 2e-08) m^3 mol^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(molar_volume_of_ideal_gas_27315_K_101325_kPa, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          molar_volume_of_ideal_gas_27315_K_101325_kPa<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::\n                 molar_volume_of_ideal_gas_27315_K_101325_kPa<T>::value() ==\n             static_cast<T>(0.022413968));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          molar_volume_of_ideal_gas_27315_K_101325_kPa<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::\n          molar_volume_of_ideal_gas_27315_K_101325_kPa<T>::uncertainty() ==\n      static_cast<T>(2e-08));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          molar_volume_of_ideal_gas_27315_K_101325_kPa<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::\n          molar_volume_of_ideal_gas_27315_K_101325_kPa<T>::precision()));\n}\n\n// molar volume of silicon\n// (1.205883301e-05 \u00b1 8e-13) m^3 mol^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(molar_volume_of_silicon, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::molar_volume_of_silicon<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::molar_volume_of_silicon<T>::value() ==\n      static_cast<T>(1.205883301e-05));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::molar_volume_of_silicon<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::molar_volume_of_silicon<\n                 T>::uncertainty() == static_cast<T>(8e-13));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::molar_volume_of_silicon<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::molar_volume_of_silicon<T>::precision()));\n}\n\n// Mo x unit\n// (1.00209952e-13 \u00b1 5.3e-20) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(Mo_x_unit, T, test_types) {\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::Mo_x_unit<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::Mo_x_unit<T>::value() ==\n             static_cast<T>(1.00209952e-13));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Mo_x_unit<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::Mo_x_unit<T>::uncertainty() ==\n             static_cast<T>(5.3e-20));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::Mo_x_unit<T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2010::Mo_x_unit<T>::precision()));\n}\n\n// muon Compton wavelength\n// (1.173444103e-14 \u00b1 3e-22) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(muon_Compton_wavelength, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::muon_Compton_wavelength<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::muon_Compton_wavelength<T>::value() ==\n      static_cast<T>(1.173444103e-14));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::muon_Compton_wavelength<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::muon_Compton_wavelength<\n                 T>::uncertainty() == static_cast<T>(3e-22));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::muon_Compton_wavelength<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::muon_Compton_wavelength<T>::precision()));\n}\n\n// muon Compton wavelength over 2 pi\n// (1.867594294e-15 \u00b1 4.7e-23) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(muon_Compton_wavelength_over_2_pi, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::muon_Compton_wavelength_over_2_pi<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::muon_Compton_wavelength_over_2_pi<\n                 T>::value() == static_cast<T>(1.867594294e-15));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::muon_Compton_wavelength_over_2_pi<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::muon_Compton_wavelength_over_2_pi<\n                 T>::uncertainty() == static_cast<T>(4.7e-23));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::muon_Compton_wavelength_over_2_pi<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::muon_Compton_wavelength_over_2_pi<\n          T>::precision()));\n}\n\n// muon-electron mass ratio\n// (206.7682843 \u00b1 5.2e-06)\nBOOST_AUTO_TEST_CASE_TEMPLATE(muon_electron_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::muon_electron_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::muon_electron_mass_ratio<T>::value() ==\n      static_cast<T>(206.7682843));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::muon_electron_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::muon_electron_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(5.2e-06));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::muon_electron_mass_ratio<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2010::muon_electron_mass_ratio<\n                    T>::precision()));\n}\n\n// muon g factor\n// (-2.0023318418 \u00b1 1.3e-09)\nBOOST_AUTO_TEST_CASE_TEMPLATE(muon_g_factor, T, test_types) {\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::muon_g_factor<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::muon_g_factor<T>::value() ==\n             static_cast<T>(-2.0023318418));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::muon_g_factor<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::muon_g_factor<T>::uncertainty() ==\n             static_cast<T>(1.3e-09));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::muon_g_factor<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::muon_g_factor<T>::precision()));\n}\n\n// muon mag. mom.\n// (-4.49044807e-26 \u00b1 1.5e-33) J T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(muon_mag_mom, T, test_types) {\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::muon_mag_mom<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::muon_mag_mom<T>::value() ==\n             static_cast<T>(-4.49044807e-26));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::muon_mag_mom<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::muon_mag_mom<T>::uncertainty() ==\n             static_cast<T>(1.5e-33));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::muon_mag_mom<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::muon_mag_mom<T>::precision()));\n}\n\n// muon mag. mom. anomaly\n// (0.00116592091 \u00b1 6.3e-10)\nBOOST_AUTO_TEST_CASE_TEMPLATE(muon_mag_mom_anomaly, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::muon_mag_mom_anomaly<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::muon_mag_mom_anomaly<T>::value() ==\n             static_cast<T>(0.00116592091));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::muon_mag_mom_anomaly<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::muon_mag_mom_anomaly<T>::uncertainty() ==\n      static_cast<T>(6.3e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::muon_mag_mom_anomaly<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::muon_mag_mom_anomaly<T>::precision()));\n}\n\n// muon mag. mom. to Bohr magneton ratio\n// (-0.00484197044 \u00b1 1.2e-10)\nBOOST_AUTO_TEST_CASE_TEMPLATE(muon_mag_mom_to_Bohr_magneton_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::muon_mag_mom_to_Bohr_magneton_ratio<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::muon_mag_mom_to_Bohr_magneton_ratio<\n          T>::value() == static_cast<T>(-0.00484197044));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::muon_mag_mom_to_Bohr_magneton_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::muon_mag_mom_to_Bohr_magneton_ratio<\n          T>::uncertainty() == static_cast<T>(1.2e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::muon_mag_mom_to_Bohr_magneton_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::muon_mag_mom_to_Bohr_magneton_ratio<\n          T>::precision()));\n}\n\n// muon mag. mom. to nuclear magneton ratio\n// (-8.89059697 \u00b1 2.2e-07)\nBOOST_AUTO_TEST_CASE_TEMPLATE(muon_mag_mom_to_nuclear_magneton_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::muon_mag_mom_to_nuclear_magneton_ratio<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::muon_mag_mom_to_nuclear_magneton_ratio<\n          T>::value() == static_cast<T>(-8.89059697));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::muon_mag_mom_to_nuclear_magneton_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::muon_mag_mom_to_nuclear_magneton_ratio<\n          T>::uncertainty() == static_cast<T>(2.2e-07));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::muon_mag_mom_to_nuclear_magneton_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::muon_mag_mom_to_nuclear_magneton_ratio<\n          T>::precision()));\n}\n\n// muon mass\n// (1.883531475e-28 \u00b1 9.6e-36) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(muon_mass, T, test_types) {\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::muon_mass<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::muon_mass<T>::value() ==\n             static_cast<T>(1.883531475e-28));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::muon_mass<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::muon_mass<T>::uncertainty() ==\n             static_cast<T>(9.6e-36));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::muon_mass<T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2010::muon_mass<T>::precision()));\n}\n\n// muon mass energy equivalent\n// (1.692833667e-11 \u00b1 8.6e-19) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(muon_mass_energy_equivalent, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::muon_mass_energy_equivalent<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::muon_mass_energy_equivalent<T>::value() ==\n      static_cast<T>(1.692833667e-11));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::muon_mass_energy_equivalent<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::muon_mass_energy_equivalent<\n                 T>::uncertainty() == static_cast<T>(8.6e-19));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::muon_mass_energy_equivalent<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2010::muon_mass_energy_equivalent<\n                    T>::precision()));\n}\n\n// muon mass energy equivalent in MeV\n// (105.6583715 \u00b1 3.5e-06) MeV\nBOOST_AUTO_TEST_CASE_TEMPLATE(muon_mass_energy_equivalent_in_MeV, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::muon_mass_energy_equivalent_in_MeV<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::muon_mass_energy_equivalent_in_MeV<\n                 T>::value() == static_cast<T>(105.6583715));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::muon_mass_energy_equivalent_in_MeV<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::muon_mass_energy_equivalent_in_MeV<\n                 T>::uncertainty() == static_cast<T>(3.5e-06));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::muon_mass_energy_equivalent_in_MeV<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::muon_mass_energy_equivalent_in_MeV<\n          T>::precision()));\n}\n\n// muon mass in u\n// (0.1134289267 \u00b1 2.9e-09) u\nBOOST_AUTO_TEST_CASE_TEMPLATE(muon_mass_in_u, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::muon_mass_in_u<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::muon_mass_in_u<T>::value() ==\n             static_cast<T>(0.1134289267));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::muon_mass_in_u<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::muon_mass_in_u<T>::uncertainty() ==\n             static_cast<T>(2.9e-09));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::muon_mass_in_u<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::muon_mass_in_u<T>::precision()));\n}\n\n// muon molar mass\n// (0.0001134289267 \u00b1 2.9e-12) kg mol^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(muon_molar_mass, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::muon_molar_mass<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::muon_molar_mass<T>::value() ==\n             static_cast<T>(0.0001134289267));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::muon_molar_mass<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::muon_molar_mass<T>::uncertainty() ==\n      static_cast<T>(2.9e-12));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::muon_molar_mass<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::muon_molar_mass<T>::precision()));\n}\n\n// muon-neutron mass ratio\n// (0.1124545177 \u00b1 2.8e-09)\nBOOST_AUTO_TEST_CASE_TEMPLATE(muon_neutron_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::muon_neutron_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::muon_neutron_mass_ratio<T>::value() ==\n      static_cast<T>(0.1124545177));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::muon_neutron_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::muon_neutron_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(2.8e-09));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::muon_neutron_mass_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::muon_neutron_mass_ratio<T>::precision()));\n}\n\n// muon-proton mag. mom. ratio\n// (-3.183345107 \u00b1 8.4e-08)\nBOOST_AUTO_TEST_CASE_TEMPLATE(muon_proton_mag_mom_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::muon_proton_mag_mom_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::muon_proton_mag_mom_ratio<T>::value() ==\n      static_cast<T>(-3.183345107));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::muon_proton_mag_mom_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::muon_proton_mag_mom_ratio<\n                 T>::uncertainty() == static_cast<T>(8.4e-08));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::muon_proton_mag_mom_ratio<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2010::muon_proton_mag_mom_ratio<\n                    T>::precision()));\n}\n\n// muon-proton mass ratio\n// (0.1126095272 \u00b1 2.8e-09)\nBOOST_AUTO_TEST_CASE_TEMPLATE(muon_proton_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::muon_proton_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::muon_proton_mass_ratio<T>::value() ==\n      static_cast<T>(0.1126095272));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::muon_proton_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::muon_proton_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(2.8e-09));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::muon_proton_mass_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::muon_proton_mass_ratio<T>::precision()));\n}\n\n// muon-tau mass ratio\n// (0.0594649 \u00b1 5.4e-06)\nBOOST_AUTO_TEST_CASE_TEMPLATE(muon_tau_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::muon_tau_mass_ratio<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::muon_tau_mass_ratio<T>::value() ==\n             static_cast<T>(0.0594649));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::muon_tau_mass_ratio<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::muon_tau_mass_ratio<T>::uncertainty() ==\n      static_cast<T>(5.4e-06));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::muon_tau_mass_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::muon_tau_mass_ratio<T>::precision()));\n}\n\n// natural unit of action\n// (1.054571726e-34 \u00b1 4.7e-42) J s\nBOOST_AUTO_TEST_CASE_TEMPLATE(natural_unit_of_action, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::natural_unit_of_action<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::natural_unit_of_action<T>::value() ==\n      static_cast<T>(1.054571726e-34));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::natural_unit_of_action<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::natural_unit_of_action<\n                 T>::uncertainty() == static_cast<T>(4.7e-42));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::natural_unit_of_action<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::natural_unit_of_action<T>::precision()));\n}\n\n// natural unit of action in eV s\n// (6.58211928e-16 \u00b1 1.5e-23) eV s\nBOOST_AUTO_TEST_CASE_TEMPLATE(natural_unit_of_action_in_eV_s, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::natural_unit_of_action_in_eV_s<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::natural_unit_of_action_in_eV_s<\n                 T>::value() == static_cast<T>(6.58211928e-16));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::natural_unit_of_action_in_eV_s<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::natural_unit_of_action_in_eV_s<\n                 T>::uncertainty() == static_cast<T>(1.5e-23));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::natural_unit_of_action_in_eV_s<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::natural_unit_of_action_in_eV_s<\n          T>::precision()));\n}\n\n// natural unit of energy\n// (8.18710506e-14 \u00b1 3.6e-21) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(natural_unit_of_energy, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::natural_unit_of_energy<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::natural_unit_of_energy<T>::value() ==\n      static_cast<T>(8.18710506e-14));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::natural_unit_of_energy<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::natural_unit_of_energy<\n                 T>::uncertainty() == static_cast<T>(3.6e-21));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::natural_unit_of_energy<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::natural_unit_of_energy<T>::precision()));\n}\n\n// natural unit of energy in MeV\n// (0.510998928 \u00b1 1.1e-08) MeV\nBOOST_AUTO_TEST_CASE_TEMPLATE(natural_unit_of_energy_in_MeV, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::natural_unit_of_energy_in_MeV<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::natural_unit_of_energy_in_MeV<\n                 T>::value() == static_cast<T>(0.510998928));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::natural_unit_of_energy_in_MeV<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::natural_unit_of_energy_in_MeV<\n                 T>::uncertainty() == static_cast<T>(1.1e-08));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::natural_unit_of_energy_in_MeV<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::natural_unit_of_energy_in_MeV<\n          T>::precision()));\n}\n\n// natural unit of length\n// (3.86159268e-13 \u00b1 2.5e-22) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(natural_unit_of_length, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::natural_unit_of_length<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::natural_unit_of_length<T>::value() ==\n      static_cast<T>(3.86159268e-13));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::natural_unit_of_length<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::natural_unit_of_length<\n                 T>::uncertainty() == static_cast<T>(2.5e-22));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::natural_unit_of_length<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::natural_unit_of_length<T>::precision()));\n}\n\n// natural unit of mass\n// (9.10938291e-31 \u00b1 4e-38) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(natural_unit_of_mass, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::natural_unit_of_mass<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::natural_unit_of_mass<T>::value() ==\n             static_cast<T>(9.10938291e-31));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::natural_unit_of_mass<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::natural_unit_of_mass<T>::uncertainty() ==\n      static_cast<T>(4e-38));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::natural_unit_of_mass<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::natural_unit_of_mass<T>::precision()));\n}\n\n// natural unit of mom.um\n// (2.73092429e-22 \u00b1 1.2e-29) kg m s^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(natural_unit_of_momum, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::natural_unit_of_momum<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::natural_unit_of_momum<T>::value() ==\n      static_cast<T>(2.73092429e-22));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::natural_unit_of_momum<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::natural_unit_of_momum<T>::uncertainty() ==\n      static_cast<T>(1.2e-29));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::natural_unit_of_momum<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::natural_unit_of_momum<T>::precision()));\n}\n\n// natural unit of mom.um in MeV/c\n// (0.510998928 \u00b1 1.1e-08) MeV/c\nBOOST_AUTO_TEST_CASE_TEMPLATE(natural_unit_of_momum_in_MeV_c, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::natural_unit_of_momum_in_MeV_c<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::natural_unit_of_momum_in_MeV_c<\n                 T>::value() == static_cast<T>(0.510998928));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::natural_unit_of_momum_in_MeV_c<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::natural_unit_of_momum_in_MeV_c<\n                 T>::uncertainty() == static_cast<T>(1.1e-08));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::natural_unit_of_momum_in_MeV_c<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::natural_unit_of_momum_in_MeV_c<\n          T>::precision()));\n}\n\n// natural unit of time\n// (1.28808866833e-21 \u00b1 8.3e-31) s\nBOOST_AUTO_TEST_CASE_TEMPLATE(natural_unit_of_time, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::natural_unit_of_time<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::natural_unit_of_time<T>::value() ==\n             static_cast<T>(1.28808866833e-21));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::natural_unit_of_time<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::natural_unit_of_time<T>::uncertainty() ==\n      static_cast<T>(8.3e-31));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::natural_unit_of_time<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::natural_unit_of_time<T>::precision()));\n}\n\n// natural unit of velocity\n// (299792458.0 \u00b1 0.0) m s^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(natural_unit_of_velocity, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::natural_unit_of_velocity<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::natural_unit_of_velocity<T>::value() ==\n      static_cast<T>(299792458.0));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::natural_unit_of_velocity<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::natural_unit_of_velocity<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::natural_unit_of_velocity<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2010::natural_unit_of_velocity<\n                    T>::precision()));\n}\n\n// neutron Compton wavelength\n// (1.3195909068e-15 \u00b1 1.1e-24) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_Compton_wavelength, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::neutron_Compton_wavelength<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::neutron_Compton_wavelength<T>::value() ==\n      static_cast<T>(1.3195909068e-15));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::neutron_Compton_wavelength<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::neutron_Compton_wavelength<\n                 T>::uncertainty() == static_cast<T>(1.1e-24));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::neutron_Compton_wavelength<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2010::neutron_Compton_wavelength<\n                    T>::precision()));\n}\n\n// neutron Compton wavelength over 2 pi\n// (2.1001941568e-16 \u00b1 1.7e-25) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_Compton_wavelength_over_2_pi, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::neutron_Compton_wavelength_over_2_pi<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::neutron_Compton_wavelength_over_2_pi<\n          T>::value() == static_cast<T>(2.1001941568e-16));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::neutron_Compton_wavelength_over_2_pi<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::neutron_Compton_wavelength_over_2_pi<\n          T>::uncertainty() == static_cast<T>(1.7e-25));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::neutron_Compton_wavelength_over_2_pi<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::neutron_Compton_wavelength_over_2_pi<\n          T>::precision()));\n}\n\n// neutron-electron mag. mom. ratio\n// (0.00104066882 \u00b1 2.5e-10)\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_electron_mag_mom_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::neutron_electron_mag_mom_ratio<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::neutron_electron_mag_mom_ratio<\n                 T>::value() == static_cast<T>(0.00104066882));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::neutron_electron_mag_mom_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::neutron_electron_mag_mom_ratio<\n                 T>::uncertainty() == static_cast<T>(2.5e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::neutron_electron_mag_mom_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::neutron_electron_mag_mom_ratio<\n          T>::precision()));\n}\n\n// neutron-electron mass ratio\n// (1838.6836605 \u00b1 1.1e-06)\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_electron_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::neutron_electron_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::neutron_electron_mass_ratio<T>::value() ==\n      static_cast<T>(1838.6836605));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::neutron_electron_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::neutron_electron_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(1.1e-06));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::neutron_electron_mass_ratio<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2010::neutron_electron_mass_ratio<\n                    T>::precision()));\n}\n\n// neutron g factor\n// (-3.82608545 \u00b1 9e-07)\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_g_factor, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::neutron_g_factor<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::neutron_g_factor<T>::value() ==\n             static_cast<T>(-3.82608545));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::neutron_g_factor<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::neutron_g_factor<T>::uncertainty() ==\n      static_cast<T>(9e-07));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::neutron_g_factor<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::neutron_g_factor<T>::precision()));\n}\n\n// neutron gyromag. ratio\n// (183247179.0 \u00b1 43.0) s^-1 T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_gyromag_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::neutron_gyromag_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::neutron_gyromag_ratio<T>::value() ==\n      static_cast<T>(183247179.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::neutron_gyromag_ratio<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::neutron_gyromag_ratio<T>::uncertainty() ==\n      static_cast<T>(43.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::neutron_gyromag_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::neutron_gyromag_ratio<T>::precision()));\n}\n\n// neutron gyromag. ratio over 2 pi\n// (29.1646943 \u00b1 6.9e-06) MHz T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_gyromag_ratio_over_2_pi, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::neutron_gyromag_ratio_over_2_pi<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::neutron_gyromag_ratio_over_2_pi<\n                 T>::value() == static_cast<T>(29.1646943));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::neutron_gyromag_ratio_over_2_pi<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::neutron_gyromag_ratio_over_2_pi<\n                 T>::uncertainty() == static_cast<T>(6.9e-06));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::neutron_gyromag_ratio_over_2_pi<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::neutron_gyromag_ratio_over_2_pi<\n          T>::precision()));\n}\n\n// neutron mag. mom.\n// (-9.6623647e-27 \u00b1 2.3e-33) J T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_mag_mom, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::neutron_mag_mom<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::neutron_mag_mom<T>::value() ==\n             static_cast<T>(-9.6623647e-27));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::neutron_mag_mom<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::neutron_mag_mom<T>::uncertainty() ==\n      static_cast<T>(2.3e-33));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::neutron_mag_mom<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::neutron_mag_mom<T>::precision()));\n}\n\n// neutron mag. mom. to Bohr magneton ratio\n// (-0.00104187563 \u00b1 2.5e-10)\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_mag_mom_to_Bohr_magneton_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::neutron_mag_mom_to_Bohr_magneton_ratio<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::neutron_mag_mom_to_Bohr_magneton_ratio<\n          T>::value() == static_cast<T>(-0.00104187563));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::neutron_mag_mom_to_Bohr_magneton_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::neutron_mag_mom_to_Bohr_magneton_ratio<\n          T>::uncertainty() == static_cast<T>(2.5e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::neutron_mag_mom_to_Bohr_magneton_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::neutron_mag_mom_to_Bohr_magneton_ratio<\n          T>::precision()));\n}\n\n// neutron mag. mom. to nuclear magneton ratio\n// (-1.91304272 \u00b1 4.5e-07)\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_mag_mom_to_nuclear_magneton_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::neutron_mag_mom_to_nuclear_magneton_ratio<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::neutron_mag_mom_to_nuclear_magneton_ratio<\n          T>::value() == static_cast<T>(-1.91304272));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::neutron_mag_mom_to_nuclear_magneton_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::neutron_mag_mom_to_nuclear_magneton_ratio<\n          T>::uncertainty() == static_cast<T>(4.5e-07));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::neutron_mag_mom_to_nuclear_magneton_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::neutron_mag_mom_to_nuclear_magneton_ratio<\n          T>::precision()));\n}\n\n// neutron mass\n// (1.674927351e-27 \u00b1 7.4e-35) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_mass, T, test_types) {\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::neutron_mass<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::neutron_mass<T>::value() ==\n             static_cast<T>(1.674927351e-27));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::neutron_mass<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::neutron_mass<T>::uncertainty() ==\n             static_cast<T>(7.4e-35));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::neutron_mass<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::neutron_mass<T>::precision()));\n}\n\n// neutron mass energy equivalent\n// (1.505349631e-10 \u00b1 6.6e-18) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_mass_energy_equivalent, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::neutron_mass_energy_equivalent<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::neutron_mass_energy_equivalent<\n                 T>::value() == static_cast<T>(1.505349631e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::neutron_mass_energy_equivalent<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::neutron_mass_energy_equivalent<\n                 T>::uncertainty() == static_cast<T>(6.6e-18));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::neutron_mass_energy_equivalent<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::neutron_mass_energy_equivalent<\n          T>::precision()));\n}\n\n// neutron mass energy equivalent in MeV\n// (939.565379 \u00b1 2.1e-05) MeV\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_mass_energy_equivalent_in_MeV, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::neutron_mass_energy_equivalent_in_MeV<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::neutron_mass_energy_equivalent_in_MeV<\n          T>::value() == static_cast<T>(939.565379));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::neutron_mass_energy_equivalent_in_MeV<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::neutron_mass_energy_equivalent_in_MeV<\n          T>::uncertainty() == static_cast<T>(2.1e-05));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::neutron_mass_energy_equivalent_in_MeV<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::neutron_mass_energy_equivalent_in_MeV<\n          T>::precision()));\n}\n\n// neutron mass in u\n// (1.008664916 \u00b1 4.3e-10) u\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_mass_in_u, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::neutron_mass_in_u<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::neutron_mass_in_u<T>::value() ==\n             static_cast<T>(1.008664916));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::neutron_mass_in_u<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::neutron_mass_in_u<T>::uncertainty() ==\n      static_cast<T>(4.3e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::neutron_mass_in_u<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::neutron_mass_in_u<T>::precision()));\n}\n\n// neutron molar mass\n// (0.001008664916 \u00b1 4.3e-13) kg mol^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_molar_mass, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::neutron_molar_mass<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::neutron_molar_mass<T>::value() ==\n             static_cast<T>(0.001008664916));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::neutron_molar_mass<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::neutron_molar_mass<T>::uncertainty() ==\n      static_cast<T>(4.3e-13));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::neutron_molar_mass<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::neutron_molar_mass<T>::precision()));\n}\n\n// neutron-muon mass ratio\n// (8.892484 \u00b1 2.2e-07)\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_muon_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::neutron_muon_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::neutron_muon_mass_ratio<T>::value() ==\n      static_cast<T>(8.892484));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::neutron_muon_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::neutron_muon_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(2.2e-07));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::neutron_muon_mass_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::neutron_muon_mass_ratio<T>::precision()));\n}\n\n// neutron-proton mag. mom. ratio\n// (-0.68497934 \u00b1 1.6e-07)\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_proton_mag_mom_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::neutron_proton_mag_mom_ratio<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::neutron_proton_mag_mom_ratio<\n                 T>::value() == static_cast<T>(-0.68497934));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::neutron_proton_mag_mom_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::neutron_proton_mag_mom_ratio<\n                 T>::uncertainty() == static_cast<T>(1.6e-07));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::neutron_proton_mag_mom_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::neutron_proton_mag_mom_ratio<\n          T>::precision()));\n}\n\n// neutron-proton mass difference\n// (2.30557392e-30 \u00b1 7.6e-37)\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_proton_mass_difference, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::neutron_proton_mass_difference<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::neutron_proton_mass_difference<\n                 T>::value() == static_cast<T>(2.30557392e-30));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::neutron_proton_mass_difference<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::neutron_proton_mass_difference<\n                 T>::uncertainty() == static_cast<T>(7.6e-37));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::neutron_proton_mass_difference<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::neutron_proton_mass_difference<\n          T>::precision()));\n}\n\n// neutron-proton mass difference energy equivalent\n// (2.0721465e-13 \u00b1 6.8e-20)\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_proton_mass_difference_energy_equivalent,\n                              T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          neutron_proton_mass_difference_energy_equivalent<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::\n                 neutron_proton_mass_difference_energy_equivalent<T>::value() ==\n             static_cast<T>(2.0721465e-13));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          neutron_proton_mass_difference_energy_equivalent<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::\n          neutron_proton_mass_difference_energy_equivalent<T>::uncertainty() ==\n      static_cast<T>(6.8e-20));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          neutron_proton_mass_difference_energy_equivalent<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::\n          neutron_proton_mass_difference_energy_equivalent<T>::precision()));\n}\n\n// neutron-proton mass difference energy equivalent in MeV\n// (1.29333217 \u00b1 4.2e-07)\nBOOST_AUTO_TEST_CASE_TEMPLATE(\n    neutron_proton_mass_difference_energy_equivalent_in_MeV, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          neutron_proton_mass_difference_energy_equivalent_in_MeV<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::\n          neutron_proton_mass_difference_energy_equivalent_in_MeV<T>::value() ==\n      static_cast<T>(1.29333217));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::\n                        neutron_proton_mass_difference_energy_equivalent_in_MeV<\n                            T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::\n                 neutron_proton_mass_difference_energy_equivalent_in_MeV<\n                     T>::uncertainty() == static_cast<T>(4.2e-07));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::\n                        neutron_proton_mass_difference_energy_equivalent_in_MeV<\n                            T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2010::\n                        neutron_proton_mass_difference_energy_equivalent_in_MeV<\n                            T>::precision()));\n}\n\n// neutron-proton mass difference in u\n// (0.00138844919 \u00b1 4.5e-10)\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_proton_mass_difference_in_u, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::neutron_proton_mass_difference_in_u<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::neutron_proton_mass_difference_in_u<\n          T>::value() == static_cast<T>(0.00138844919));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::neutron_proton_mass_difference_in_u<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::neutron_proton_mass_difference_in_u<\n          T>::uncertainty() == static_cast<T>(4.5e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::neutron_proton_mass_difference_in_u<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::neutron_proton_mass_difference_in_u<\n          T>::precision()));\n}\n\n// neutron-proton mass ratio\n// (1.00137841917 \u00b1 4.5e-10)\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_proton_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::neutron_proton_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::neutron_proton_mass_ratio<T>::value() ==\n      static_cast<T>(1.00137841917));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::neutron_proton_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::neutron_proton_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(4.5e-10));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::neutron_proton_mass_ratio<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2010::neutron_proton_mass_ratio<\n                    T>::precision()));\n}\n\n// neutron-tau mass ratio\n// (0.52879 \u00b1 4.8e-05)\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_tau_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::neutron_tau_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::neutron_tau_mass_ratio<T>::value() ==\n      static_cast<T>(0.52879));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::neutron_tau_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::neutron_tau_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(4.8e-05));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::neutron_tau_mass_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::neutron_tau_mass_ratio<T>::precision()));\n}\n\n// neutron to shielded proton mag. mom. ratio\n// (-0.68499694 \u00b1 1.6e-07)\nBOOST_AUTO_TEST_CASE_TEMPLATE(neutron_to_shielded_proton_mag_mom_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::neutron_to_shielded_proton_mag_mom_ratio<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::neutron_to_shielded_proton_mag_mom_ratio<\n          T>::value() == static_cast<T>(-0.68499694));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::neutron_to_shielded_proton_mag_mom_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::neutron_to_shielded_proton_mag_mom_ratio<\n          T>::uncertainty() == static_cast<T>(1.6e-07));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::neutron_to_shielded_proton_mag_mom_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::neutron_to_shielded_proton_mag_mom_ratio<\n          T>::precision()));\n}\n\n// Newtonian constant of gravitation\n// (6.67384e-11 \u00b1 8e-15) m^3 kg^-1 s^-2\nBOOST_AUTO_TEST_CASE_TEMPLATE(Newtonian_constant_of_gravitation, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Newtonian_constant_of_gravitation<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::Newtonian_constant_of_gravitation<\n                 T>::value() == static_cast<T>(6.67384e-11));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Newtonian_constant_of_gravitation<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::Newtonian_constant_of_gravitation<\n                 T>::uncertainty() == static_cast<T>(8e-15));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Newtonian_constant_of_gravitation<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::Newtonian_constant_of_gravitation<\n          T>::precision()));\n}\n\n// Newtonian constant of gravitation over h-bar c\n// (6.70837e-39 \u00b1 8e-43) (GeV/c^2)^-2\nBOOST_AUTO_TEST_CASE_TEMPLATE(Newtonian_constant_of_gravitation_over_h_bar_c, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          Newtonian_constant_of_gravitation_over_h_bar_c<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::\n                 Newtonian_constant_of_gravitation_over_h_bar_c<T>::value() ==\n             static_cast<T>(6.70837e-39));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          Newtonian_constant_of_gravitation_over_h_bar_c<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::\n          Newtonian_constant_of_gravitation_over_h_bar_c<T>::uncertainty() ==\n      static_cast<T>(8e-43));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          Newtonian_constant_of_gravitation_over_h_bar_c<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::\n          Newtonian_constant_of_gravitation_over_h_bar_c<T>::precision()));\n}\n\n// nuclear magneton\n// (5.05078353e-27 \u00b1 1.1e-34) J T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(nuclear_magneton, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::nuclear_magneton<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::nuclear_magneton<T>::value() ==\n             static_cast<T>(5.05078353e-27));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::nuclear_magneton<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::nuclear_magneton<T>::uncertainty() ==\n      static_cast<T>(1.1e-34));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::nuclear_magneton<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::nuclear_magneton<T>::precision()));\n}\n\n// nuclear magneton in eV/T\n// (3.1524512605e-08 \u00b1 2.2e-17) eV T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(nuclear_magneton_in_eV_T, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::nuclear_magneton_in_eV_T<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::nuclear_magneton_in_eV_T<T>::value() ==\n      static_cast<T>(3.1524512605e-08));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::nuclear_magneton_in_eV_T<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::nuclear_magneton_in_eV_T<\n                 T>::uncertainty() == static_cast<T>(2.2e-17));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::nuclear_magneton_in_eV_T<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2010::nuclear_magneton_in_eV_T<\n                    T>::precision()));\n}\n\n// nuclear magneton in inverse meters per tesla\n// (0.02542623527 \u00b1 5.6e-10) m^-1 T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(nuclear_magneton_in_inverse_meters_per_tesla, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          nuclear_magneton_in_inverse_meters_per_tesla<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::\n                 nuclear_magneton_in_inverse_meters_per_tesla<T>::value() ==\n             static_cast<T>(0.02542623527));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          nuclear_magneton_in_inverse_meters_per_tesla<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::\n          nuclear_magneton_in_inverse_meters_per_tesla<T>::uncertainty() ==\n      static_cast<T>(5.6e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          nuclear_magneton_in_inverse_meters_per_tesla<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::\n          nuclear_magneton_in_inverse_meters_per_tesla<T>::precision()));\n}\n\n// nuclear magneton in K/T\n// (0.00036582682 \u00b1 3.3e-10) K T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(nuclear_magneton_in_K_T, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::nuclear_magneton_in_K_T<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::nuclear_magneton_in_K_T<T>::value() ==\n      static_cast<T>(0.00036582682));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::nuclear_magneton_in_K_T<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::nuclear_magneton_in_K_T<\n                 T>::uncertainty() == static_cast<T>(3.3e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::nuclear_magneton_in_K_T<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::nuclear_magneton_in_K_T<T>::precision()));\n}\n\n// nuclear magneton in MHz/T\n// (7.62259357 \u00b1 1.7e-07) MHz T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(nuclear_magneton_in_MHz_T, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::nuclear_magneton_in_MHz_T<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::nuclear_magneton_in_MHz_T<T>::value() ==\n      static_cast<T>(7.62259357));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::nuclear_magneton_in_MHz_T<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::nuclear_magneton_in_MHz_T<\n                 T>::uncertainty() == static_cast<T>(1.7e-07));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::nuclear_magneton_in_MHz_T<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2010::nuclear_magneton_in_MHz_T<\n                    T>::precision()));\n}\n\n// Planck constant\n// (6.62606957e-34 \u00b1 2.9e-41) J s\nBOOST_AUTO_TEST_CASE_TEMPLATE(Planck_constant, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Planck_constant<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::Planck_constant<T>::value() ==\n             static_cast<T>(6.62606957e-34));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Planck_constant<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::Planck_constant<T>::uncertainty() ==\n      static_cast<T>(2.9e-41));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Planck_constant<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::Planck_constant<T>::precision()));\n}\n\n// Planck constant in eV s\n// (4.135667516e-15 \u00b1 9.1e-23) eV s\nBOOST_AUTO_TEST_CASE_TEMPLATE(Planck_constant_in_eV_s, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Planck_constant_in_eV_s<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::Planck_constant_in_eV_s<T>::value() ==\n      static_cast<T>(4.135667516e-15));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::Planck_constant_in_eV_s<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::Planck_constant_in_eV_s<\n                 T>::uncertainty() == static_cast<T>(9.1e-23));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Planck_constant_in_eV_s<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::Planck_constant_in_eV_s<T>::precision()));\n}\n\n// Planck constant over 2 pi\n// (1.054571726e-34 \u00b1 4.7e-42) J s\nBOOST_AUTO_TEST_CASE_TEMPLATE(Planck_constant_over_2_pi, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Planck_constant_over_2_pi<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::Planck_constant_over_2_pi<T>::value() ==\n      static_cast<T>(1.054571726e-34));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::Planck_constant_over_2_pi<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::Planck_constant_over_2_pi<\n                 T>::uncertainty() == static_cast<T>(4.7e-42));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::Planck_constant_over_2_pi<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2010::Planck_constant_over_2_pi<\n                    T>::precision()));\n}\n\n// Planck constant over 2 pi in eV s\n// (6.58211928e-16 \u00b1 1.5e-23) eV s\nBOOST_AUTO_TEST_CASE_TEMPLATE(Planck_constant_over_2_pi_in_eV_s, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Planck_constant_over_2_pi_in_eV_s<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::Planck_constant_over_2_pi_in_eV_s<\n                 T>::value() == static_cast<T>(6.58211928e-16));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Planck_constant_over_2_pi_in_eV_s<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::Planck_constant_over_2_pi_in_eV_s<\n                 T>::uncertainty() == static_cast<T>(1.5e-23));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Planck_constant_over_2_pi_in_eV_s<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::Planck_constant_over_2_pi_in_eV_s<\n          T>::precision()));\n}\n\n// Planck constant over 2 pi times c in MeV fm\n// (197.3269718 \u00b1 4.4e-06) MeV fm\nBOOST_AUTO_TEST_CASE_TEMPLATE(Planck_constant_over_2_pi_times_c_in_MeV_fm, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          Planck_constant_over_2_pi_times_c_in_MeV_fm<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::\n                 Planck_constant_over_2_pi_times_c_in_MeV_fm<T>::value() ==\n             static_cast<T>(197.3269718));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          Planck_constant_over_2_pi_times_c_in_MeV_fm<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::\n          Planck_constant_over_2_pi_times_c_in_MeV_fm<T>::uncertainty() ==\n      static_cast<T>(4.4e-06));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          Planck_constant_over_2_pi_times_c_in_MeV_fm<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::\n          Planck_constant_over_2_pi_times_c_in_MeV_fm<T>::precision()));\n}\n\n// Planck length\n// (1.616199e-35 \u00b1 9.7e-40) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(Planck_length, T, test_types) {\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::Planck_length<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::Planck_length<T>::value() ==\n             static_cast<T>(1.616199e-35));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Planck_length<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::Planck_length<T>::uncertainty() ==\n             static_cast<T>(9.7e-40));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Planck_length<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::Planck_length<T>::precision()));\n}\n\n// Planck mass\n// (2.17651e-08 \u00b1 1.3e-12) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(Planck_mass, T, test_types) {\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::Planck_mass<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::Planck_mass<T>::value() ==\n             static_cast<T>(2.17651e-08));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Planck_mass<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::Planck_mass<T>::uncertainty() ==\n             static_cast<T>(1.3e-12));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Planck_mass<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::Planck_mass<T>::precision()));\n}\n\n// Planck mass energy equivalent in GeV\n// (1.220932e+19 \u00b1 730000000000000.0) GeV\nBOOST_AUTO_TEST_CASE_TEMPLATE(Planck_mass_energy_equivalent_in_GeV, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Planck_mass_energy_equivalent_in_GeV<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::Planck_mass_energy_equivalent_in_GeV<\n          T>::value() == static_cast<T>(1.220932e+19));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Planck_mass_energy_equivalent_in_GeV<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::Planck_mass_energy_equivalent_in_GeV<\n          T>::uncertainty() == static_cast<T>(730000000000000.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Planck_mass_energy_equivalent_in_GeV<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::Planck_mass_energy_equivalent_in_GeV<\n          T>::precision()));\n}\n\n// Planck temperature\n// (1.416833e+32 \u00b1 8.5e+27) K\nBOOST_AUTO_TEST_CASE_TEMPLATE(Planck_temperature, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Planck_temperature<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::Planck_temperature<T>::value() ==\n             static_cast<T>(1.416833e+32));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Planck_temperature<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::Planck_temperature<T>::uncertainty() ==\n      static_cast<T>(8.5e+27));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Planck_temperature<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::Planck_temperature<T>::precision()));\n}\n\n// Planck time\n// (5.39106e-44 \u00b1 3.2e-48) s\nBOOST_AUTO_TEST_CASE_TEMPLATE(Planck_time, T, test_types) {\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::Planck_time<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::Planck_time<T>::value() ==\n             static_cast<T>(5.39106e-44));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Planck_time<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::Planck_time<T>::uncertainty() ==\n             static_cast<T>(3.2e-48));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Planck_time<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::Planck_time<T>::precision()));\n}\n\n// proton charge to mass quotient\n// (95788335.8 \u00b1 2.1) C kg^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(proton_charge_to_mass_quotient, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::proton_charge_to_mass_quotient<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::proton_charge_to_mass_quotient<\n                 T>::value() == static_cast<T>(95788335.8));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::proton_charge_to_mass_quotient<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::proton_charge_to_mass_quotient<\n                 T>::uncertainty() == static_cast<T>(2.1));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::proton_charge_to_mass_quotient<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::proton_charge_to_mass_quotient<\n          T>::precision()));\n}\n\n// proton Compton wavelength\n// (1.32140985623e-15 \u00b1 9.4e-25) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(proton_Compton_wavelength, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::proton_Compton_wavelength<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::proton_Compton_wavelength<T>::value() ==\n      static_cast<T>(1.32140985623e-15));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::proton_Compton_wavelength<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::proton_Compton_wavelength<\n                 T>::uncertainty() == static_cast<T>(9.4e-25));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::proton_Compton_wavelength<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2010::proton_Compton_wavelength<\n                    T>::precision()));\n}\n\n// proton Compton wavelength over 2 pi\n// (2.1030891047e-16 \u00b1 1.5e-25) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(proton_Compton_wavelength_over_2_pi, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::proton_Compton_wavelength_over_2_pi<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::proton_Compton_wavelength_over_2_pi<\n          T>::value() == static_cast<T>(2.1030891047e-16));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::proton_Compton_wavelength_over_2_pi<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::proton_Compton_wavelength_over_2_pi<\n          T>::uncertainty() == static_cast<T>(1.5e-25));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::proton_Compton_wavelength_over_2_pi<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::proton_Compton_wavelength_over_2_pi<\n          T>::precision()));\n}\n\n// proton-electron mass ratio\n// (1836.15267245 \u00b1 7.5e-07)\nBOOST_AUTO_TEST_CASE_TEMPLATE(proton_electron_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::proton_electron_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::proton_electron_mass_ratio<T>::value() ==\n      static_cast<T>(1836.15267245));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::proton_electron_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::proton_electron_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(7.5e-07));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::proton_electron_mass_ratio<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2010::proton_electron_mass_ratio<\n                    T>::precision()));\n}\n\n// proton g factor\n// (5.585694713 \u00b1 4.6e-08)\nBOOST_AUTO_TEST_CASE_TEMPLATE(proton_g_factor, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::proton_g_factor<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::proton_g_factor<T>::value() ==\n             static_cast<T>(5.585694713));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::proton_g_factor<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::proton_g_factor<T>::uncertainty() ==\n      static_cast<T>(4.6e-08));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::proton_g_factor<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::proton_g_factor<T>::precision()));\n}\n\n// proton gyromag. ratio\n// (267522200.5 \u00b1 6.3) s^-1 T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(proton_gyromag_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::proton_gyromag_ratio<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::proton_gyromag_ratio<T>::value() ==\n             static_cast<T>(267522200.5));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::proton_gyromag_ratio<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::proton_gyromag_ratio<T>::uncertainty() ==\n      static_cast<T>(6.3));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::proton_gyromag_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::proton_gyromag_ratio<T>::precision()));\n}\n\n// proton gyromag. ratio over 2 pi\n// (42.5774806 \u00b1 1e-06) MHz T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(proton_gyromag_ratio_over_2_pi, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::proton_gyromag_ratio_over_2_pi<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::proton_gyromag_ratio_over_2_pi<\n                 T>::value() == static_cast<T>(42.5774806));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::proton_gyromag_ratio_over_2_pi<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::proton_gyromag_ratio_over_2_pi<\n                 T>::uncertainty() == static_cast<T>(1e-06));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::proton_gyromag_ratio_over_2_pi<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::proton_gyromag_ratio_over_2_pi<\n          T>::precision()));\n}\n\n// proton mag. mom.\n// (1.410606743e-26 \u00b1 3.3e-34) J T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(proton_mag_mom, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::proton_mag_mom<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::proton_mag_mom<T>::value() ==\n             static_cast<T>(1.410606743e-26));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::proton_mag_mom<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::proton_mag_mom<T>::uncertainty() ==\n             static_cast<T>(3.3e-34));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::proton_mag_mom<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::proton_mag_mom<T>::precision()));\n}\n\n// proton mag. mom. to Bohr magneton ratio\n// (0.00152103221 \u00b1 1.2e-11)\nBOOST_AUTO_TEST_CASE_TEMPLATE(proton_mag_mom_to_Bohr_magneton_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::proton_mag_mom_to_Bohr_magneton_ratio<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::proton_mag_mom_to_Bohr_magneton_ratio<\n          T>::value() == static_cast<T>(0.00152103221));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::proton_mag_mom_to_Bohr_magneton_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::proton_mag_mom_to_Bohr_magneton_ratio<\n          T>::uncertainty() == static_cast<T>(1.2e-11));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::proton_mag_mom_to_Bohr_magneton_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::proton_mag_mom_to_Bohr_magneton_ratio<\n          T>::precision()));\n}\n\n// proton mag. mom. to nuclear magneton ratio\n// (2.792847356 \u00b1 2.3e-08)\nBOOST_AUTO_TEST_CASE_TEMPLATE(proton_mag_mom_to_nuclear_magneton_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::proton_mag_mom_to_nuclear_magneton_ratio<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::proton_mag_mom_to_nuclear_magneton_ratio<\n          T>::value() == static_cast<T>(2.792847356));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::proton_mag_mom_to_nuclear_magneton_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::proton_mag_mom_to_nuclear_magneton_ratio<\n          T>::uncertainty() == static_cast<T>(2.3e-08));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::proton_mag_mom_to_nuclear_magneton_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::proton_mag_mom_to_nuclear_magneton_ratio<\n          T>::precision()));\n}\n\n// proton mag. shielding correction\n// (2.5694e-05 \u00b1 1.4e-08)\nBOOST_AUTO_TEST_CASE_TEMPLATE(proton_mag_shielding_correction, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::proton_mag_shielding_correction<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::proton_mag_shielding_correction<\n                 T>::value() == static_cast<T>(2.5694e-05));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::proton_mag_shielding_correction<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::proton_mag_shielding_correction<\n                 T>::uncertainty() == static_cast<T>(1.4e-08));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::proton_mag_shielding_correction<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::proton_mag_shielding_correction<\n          T>::precision()));\n}\n\n// proton mass\n// (1.672621777e-27 \u00b1 7.4e-35) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(proton_mass, T, test_types) {\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::proton_mass<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::proton_mass<T>::value() ==\n             static_cast<T>(1.672621777e-27));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::proton_mass<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::proton_mass<T>::uncertainty() ==\n             static_cast<T>(7.4e-35));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::proton_mass<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::proton_mass<T>::precision()));\n}\n\n// proton mass energy equivalent\n// (1.503277484e-10 \u00b1 6.6e-18) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(proton_mass_energy_equivalent, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::proton_mass_energy_equivalent<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::proton_mass_energy_equivalent<\n                 T>::value() == static_cast<T>(1.503277484e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::proton_mass_energy_equivalent<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::proton_mass_energy_equivalent<\n                 T>::uncertainty() == static_cast<T>(6.6e-18));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::proton_mass_energy_equivalent<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::proton_mass_energy_equivalent<\n          T>::precision()));\n}\n\n// proton mass energy equivalent in MeV\n// (938.272046 \u00b1 2.1e-05) MeV\nBOOST_AUTO_TEST_CASE_TEMPLATE(proton_mass_energy_equivalent_in_MeV, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::proton_mass_energy_equivalent_in_MeV<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::proton_mass_energy_equivalent_in_MeV<\n          T>::value() == static_cast<T>(938.272046));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::proton_mass_energy_equivalent_in_MeV<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::proton_mass_energy_equivalent_in_MeV<\n          T>::uncertainty() == static_cast<T>(2.1e-05));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::proton_mass_energy_equivalent_in_MeV<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::proton_mass_energy_equivalent_in_MeV<\n          T>::precision()));\n}\n\n// proton mass in u\n// (1.007276466812 \u00b1 9e-11) u\nBOOST_AUTO_TEST_CASE_TEMPLATE(proton_mass_in_u, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::proton_mass_in_u<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::proton_mass_in_u<T>::value() ==\n             static_cast<T>(1.007276466812));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::proton_mass_in_u<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::proton_mass_in_u<T>::uncertainty() ==\n      static_cast<T>(9e-11));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::proton_mass_in_u<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::proton_mass_in_u<T>::precision()));\n}\n\n// proton molar mass\n// (0.001007276466812 \u00b1 9e-14) kg mol^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(proton_molar_mass, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::proton_molar_mass<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::proton_molar_mass<T>::value() ==\n             static_cast<T>(0.001007276466812));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::proton_molar_mass<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::proton_molar_mass<T>::uncertainty() ==\n      static_cast<T>(9e-14));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::proton_molar_mass<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::proton_molar_mass<T>::precision()));\n}\n\n// proton-muon mass ratio\n// (8.88024331 \u00b1 2.2e-07)\nBOOST_AUTO_TEST_CASE_TEMPLATE(proton_muon_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::proton_muon_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::proton_muon_mass_ratio<T>::value() ==\n      static_cast<T>(8.88024331));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::proton_muon_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::proton_muon_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(2.2e-07));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::proton_muon_mass_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::proton_muon_mass_ratio<T>::precision()));\n}\n\n// proton-neutron mag. mom. ratio\n// (-1.45989806 \u00b1 3.4e-07)\nBOOST_AUTO_TEST_CASE_TEMPLATE(proton_neutron_mag_mom_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::proton_neutron_mag_mom_ratio<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::proton_neutron_mag_mom_ratio<\n                 T>::value() == static_cast<T>(-1.45989806));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::proton_neutron_mag_mom_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::proton_neutron_mag_mom_ratio<\n                 T>::uncertainty() == static_cast<T>(3.4e-07));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::proton_neutron_mag_mom_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::proton_neutron_mag_mom_ratio<\n          T>::precision()));\n}\n\n// proton-neutron mass ratio\n// (0.99862347826 \u00b1 4.5e-10)\nBOOST_AUTO_TEST_CASE_TEMPLATE(proton_neutron_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::proton_neutron_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::proton_neutron_mass_ratio<T>::value() ==\n      static_cast<T>(0.99862347826));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::proton_neutron_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::proton_neutron_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(4.5e-10));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::proton_neutron_mass_ratio<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2010::proton_neutron_mass_ratio<\n                    T>::precision()));\n}\n\n// proton rms charge radius\n// (8.775e-16 \u00b1 5.1e-18) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(proton_rms_charge_radius, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::proton_rms_charge_radius<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::proton_rms_charge_radius<T>::value() ==\n      static_cast<T>(8.775e-16));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::proton_rms_charge_radius<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::proton_rms_charge_radius<\n                 T>::uncertainty() == static_cast<T>(5.1e-18));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::proton_rms_charge_radius<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2010::proton_rms_charge_radius<\n                    T>::precision()));\n}\n\n// proton-tau mass ratio\n// (0.528063 \u00b1 4.8e-05)\nBOOST_AUTO_TEST_CASE_TEMPLATE(proton_tau_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::proton_tau_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::proton_tau_mass_ratio<T>::value() ==\n      static_cast<T>(0.528063));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::proton_tau_mass_ratio<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::proton_tau_mass_ratio<T>::uncertainty() ==\n      static_cast<T>(4.8e-05));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::proton_tau_mass_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::proton_tau_mass_ratio<T>::precision()));\n}\n\n// quantum of circulation\n// (0.0003636947552 \u00b1 2.4e-13) m^2 s^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(quantum_of_circulation, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::quantum_of_circulation<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::quantum_of_circulation<T>::value() ==\n      static_cast<T>(0.0003636947552));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::quantum_of_circulation<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::quantum_of_circulation<\n                 T>::uncertainty() == static_cast<T>(2.4e-13));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::quantum_of_circulation<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::quantum_of_circulation<T>::precision()));\n}\n\n// quantum of circulation times 2\n// (0.0007273895104 \u00b1 4.7e-13) m^2 s^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(quantum_of_circulation_times_2, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::quantum_of_circulation_times_2<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::quantum_of_circulation_times_2<\n                 T>::value() == static_cast<T>(0.0007273895104));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::quantum_of_circulation_times_2<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::quantum_of_circulation_times_2<\n                 T>::uncertainty() == static_cast<T>(4.7e-13));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::quantum_of_circulation_times_2<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::quantum_of_circulation_times_2<\n          T>::precision()));\n}\n\n// Rydberg constant\n// (10973731.568539 \u00b1 5.5e-05) m^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(Rydberg_constant, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Rydberg_constant<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::Rydberg_constant<T>::value() ==\n             static_cast<T>(10973731.568539));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Rydberg_constant<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::Rydberg_constant<T>::uncertainty() ==\n      static_cast<T>(5.5e-05));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Rydberg_constant<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::Rydberg_constant<T>::precision()));\n}\n\n// Rydberg constant times c in Hz\n// (3289841960364000.0 \u00b1 17000.0) Hz\nBOOST_AUTO_TEST_CASE_TEMPLATE(Rydberg_constant_times_c_in_Hz, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Rydberg_constant_times_c_in_Hz<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::Rydberg_constant_times_c_in_Hz<\n                 T>::value() == static_cast<T>(3289841960364000.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Rydberg_constant_times_c_in_Hz<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::Rydberg_constant_times_c_in_Hz<\n                 T>::uncertainty() == static_cast<T>(17000.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Rydberg_constant_times_c_in_Hz<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::Rydberg_constant_times_c_in_Hz<\n          T>::precision()));\n}\n\n// Rydberg constant times hc in eV\n// (13.60569253 \u00b1 3e-07) eV\nBOOST_AUTO_TEST_CASE_TEMPLATE(Rydberg_constant_times_hc_in_eV, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Rydberg_constant_times_hc_in_eV<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::Rydberg_constant_times_hc_in_eV<\n                 T>::value() == static_cast<T>(13.60569253));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Rydberg_constant_times_hc_in_eV<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::Rydberg_constant_times_hc_in_eV<\n                 T>::uncertainty() == static_cast<T>(3e-07));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Rydberg_constant_times_hc_in_eV<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::Rydberg_constant_times_hc_in_eV<\n          T>::precision()));\n}\n\n// Rydberg constant times hc in J\n// (2.179872171e-18 \u00b1 9.6e-26) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(Rydberg_constant_times_hc_in_J, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Rydberg_constant_times_hc_in_J<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::Rydberg_constant_times_hc_in_J<\n                 T>::value() == static_cast<T>(2.179872171e-18));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Rydberg_constant_times_hc_in_J<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::Rydberg_constant_times_hc_in_J<\n                 T>::uncertainty() == static_cast<T>(9.6e-26));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Rydberg_constant_times_hc_in_J<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::Rydberg_constant_times_hc_in_J<\n          T>::precision()));\n}\n\n// Sackur-Tetrode constant (1 K, 100 kPa)\n// (-1.1517078 \u00b1 2.3e-06)\nBOOST_AUTO_TEST_CASE_TEMPLATE(Sackur_Tetrode_constant_1_K_100_kPa, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Sackur_Tetrode_constant_1_K_100_kPa<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::Sackur_Tetrode_constant_1_K_100_kPa<\n          T>::value() == static_cast<T>(-1.1517078));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Sackur_Tetrode_constant_1_K_100_kPa<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::Sackur_Tetrode_constant_1_K_100_kPa<\n          T>::uncertainty() == static_cast<T>(2.3e-06));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Sackur_Tetrode_constant_1_K_100_kPa<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::Sackur_Tetrode_constant_1_K_100_kPa<\n          T>::precision()));\n}\n\n// Sackur-Tetrode constant (1 K, 101.325 kPa)\n// (-1.1648708 \u00b1 2.3e-06)\nBOOST_AUTO_TEST_CASE_TEMPLATE(Sackur_Tetrode_constant_1_K_101325_kPa, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Sackur_Tetrode_constant_1_K_101325_kPa<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::Sackur_Tetrode_constant_1_K_101325_kPa<\n          T>::value() == static_cast<T>(-1.1648708));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Sackur_Tetrode_constant_1_K_101325_kPa<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::Sackur_Tetrode_constant_1_K_101325_kPa<\n          T>::uncertainty() == static_cast<T>(2.3e-06));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Sackur_Tetrode_constant_1_K_101325_kPa<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::Sackur_Tetrode_constant_1_K_101325_kPa<\n          T>::precision()));\n}\n\n// second radiation constant\n// (0.01438777 \u00b1 1.3e-08) m K\nBOOST_AUTO_TEST_CASE_TEMPLATE(second_radiation_constant, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::second_radiation_constant<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::second_radiation_constant<T>::value() ==\n      static_cast<T>(0.01438777));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::second_radiation_constant<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::second_radiation_constant<\n                 T>::uncertainty() == static_cast<T>(1.3e-08));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::second_radiation_constant<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2010::second_radiation_constant<\n                    T>::precision()));\n}\n\n// shielded helion gyromag. ratio\n// (203789465.9 \u00b1 5.1) s^-1 T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(shielded_helion_gyromag_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::shielded_helion_gyromag_ratio<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::shielded_helion_gyromag_ratio<\n                 T>::value() == static_cast<T>(203789465.9));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::shielded_helion_gyromag_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::shielded_helion_gyromag_ratio<\n                 T>::uncertainty() == static_cast<T>(5.1));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::shielded_helion_gyromag_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::shielded_helion_gyromag_ratio<\n          T>::precision()));\n}\n\n// shielded helion gyromag. ratio over 2 pi\n// (32.43410084 \u00b1 8.1e-07) MHz T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(shielded_helion_gyromag_ratio_over_2_pi, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::shielded_helion_gyromag_ratio_over_2_pi<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::shielded_helion_gyromag_ratio_over_2_pi<\n          T>::value() == static_cast<T>(32.43410084));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::shielded_helion_gyromag_ratio_over_2_pi<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::shielded_helion_gyromag_ratio_over_2_pi<\n          T>::uncertainty() == static_cast<T>(8.1e-07));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::shielded_helion_gyromag_ratio_over_2_pi<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::shielded_helion_gyromag_ratio_over_2_pi<\n          T>::precision()));\n}\n\n// shielded helion mag. mom.\n// (-1.074553044e-26 \u00b1 2.7e-34) J T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(shielded_helion_mag_mom, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::shielded_helion_mag_mom<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::shielded_helion_mag_mom<T>::value() ==\n      static_cast<T>(-1.074553044e-26));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::shielded_helion_mag_mom<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::shielded_helion_mag_mom<\n                 T>::uncertainty() == static_cast<T>(2.7e-34));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::shielded_helion_mag_mom<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::shielded_helion_mag_mom<T>::precision()));\n}\n\n// shielded helion mag. mom. to Bohr magneton ratio\n// (-0.001158671471 \u00b1 1.4e-11)\nBOOST_AUTO_TEST_CASE_TEMPLATE(shielded_helion_mag_mom_to_Bohr_magneton_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          shielded_helion_mag_mom_to_Bohr_magneton_ratio<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::\n                 shielded_helion_mag_mom_to_Bohr_magneton_ratio<T>::value() ==\n             static_cast<T>(-0.001158671471));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          shielded_helion_mag_mom_to_Bohr_magneton_ratio<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::\n          shielded_helion_mag_mom_to_Bohr_magneton_ratio<T>::uncertainty() ==\n      static_cast<T>(1.4e-11));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          shielded_helion_mag_mom_to_Bohr_magneton_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::\n          shielded_helion_mag_mom_to_Bohr_magneton_ratio<T>::precision()));\n}\n\n// shielded helion mag. mom. to nuclear magneton ratio\n// (-2.127497718 \u00b1 2.5e-08)\nBOOST_AUTO_TEST_CASE_TEMPLATE(shielded_helion_mag_mom_to_nuclear_magneton_ratio,\n                              T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          shielded_helion_mag_mom_to_nuclear_magneton_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::\n          shielded_helion_mag_mom_to_nuclear_magneton_ratio<T>::value() ==\n      static_cast<T>(-2.127497718));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          shielded_helion_mag_mom_to_nuclear_magneton_ratio<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::\n          shielded_helion_mag_mom_to_nuclear_magneton_ratio<T>::uncertainty() ==\n      static_cast<T>(2.5e-08));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          shielded_helion_mag_mom_to_nuclear_magneton_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::\n          shielded_helion_mag_mom_to_nuclear_magneton_ratio<T>::precision()));\n}\n\n// shielded helion to proton mag. mom. ratio\n// (-0.761766558 \u00b1 1.1e-08)\nBOOST_AUTO_TEST_CASE_TEMPLATE(shielded_helion_to_proton_mag_mom_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::shielded_helion_to_proton_mag_mom_ratio<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::shielded_helion_to_proton_mag_mom_ratio<\n          T>::value() == static_cast<T>(-0.761766558));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::shielded_helion_to_proton_mag_mom_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::shielded_helion_to_proton_mag_mom_ratio<\n          T>::uncertainty() == static_cast<T>(1.1e-08));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::shielded_helion_to_proton_mag_mom_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::shielded_helion_to_proton_mag_mom_ratio<\n          T>::precision()));\n}\n\n// shielded helion to shielded proton mag. mom. ratio\n// (-0.7617861313 \u00b1 3.3e-09)\nBOOST_AUTO_TEST_CASE_TEMPLATE(shielded_helion_to_shielded_proton_mag_mom_ratio,\n                              T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          shielded_helion_to_shielded_proton_mag_mom_ratio<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::\n                 shielded_helion_to_shielded_proton_mag_mom_ratio<T>::value() ==\n             static_cast<T>(-0.7617861313));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          shielded_helion_to_shielded_proton_mag_mom_ratio<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::\n          shielded_helion_to_shielded_proton_mag_mom_ratio<T>::uncertainty() ==\n      static_cast<T>(3.3e-09));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          shielded_helion_to_shielded_proton_mag_mom_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::\n          shielded_helion_to_shielded_proton_mag_mom_ratio<T>::precision()));\n}\n\n// shielded proton gyromag. ratio\n// (267515326.8 \u00b1 6.6) s^-1 T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(shielded_proton_gyromag_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::shielded_proton_gyromag_ratio<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::shielded_proton_gyromag_ratio<\n                 T>::value() == static_cast<T>(267515326.8));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::shielded_proton_gyromag_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::shielded_proton_gyromag_ratio<\n                 T>::uncertainty() == static_cast<T>(6.6));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::shielded_proton_gyromag_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::shielded_proton_gyromag_ratio<\n          T>::precision()));\n}\n\n// shielded proton gyromag. ratio over 2 pi\n// (42.5763866 \u00b1 1e-06) MHz T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(shielded_proton_gyromag_ratio_over_2_pi, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::shielded_proton_gyromag_ratio_over_2_pi<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::shielded_proton_gyromag_ratio_over_2_pi<\n          T>::value() == static_cast<T>(42.5763866));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::shielded_proton_gyromag_ratio_over_2_pi<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::shielded_proton_gyromag_ratio_over_2_pi<\n          T>::uncertainty() == static_cast<T>(1e-06));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::shielded_proton_gyromag_ratio_over_2_pi<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::shielded_proton_gyromag_ratio_over_2_pi<\n          T>::precision()));\n}\n\n// shielded proton mag. mom.\n// (1.410570499e-26 \u00b1 3.5e-34) J T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(shielded_proton_mag_mom, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::shielded_proton_mag_mom<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::shielded_proton_mag_mom<T>::value() ==\n      static_cast<T>(1.410570499e-26));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::shielded_proton_mag_mom<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::shielded_proton_mag_mom<\n                 T>::uncertainty() == static_cast<T>(3.5e-34));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::shielded_proton_mag_mom<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::shielded_proton_mag_mom<T>::precision()));\n}\n\n// shielded proton mag. mom. to Bohr magneton ratio\n// (0.001520993128 \u00b1 1.7e-11)\nBOOST_AUTO_TEST_CASE_TEMPLATE(shielded_proton_mag_mom_to_Bohr_magneton_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          shielded_proton_mag_mom_to_Bohr_magneton_ratio<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::\n                 shielded_proton_mag_mom_to_Bohr_magneton_ratio<T>::value() ==\n             static_cast<T>(0.001520993128));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          shielded_proton_mag_mom_to_Bohr_magneton_ratio<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::\n          shielded_proton_mag_mom_to_Bohr_magneton_ratio<T>::uncertainty() ==\n      static_cast<T>(1.7e-11));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          shielded_proton_mag_mom_to_Bohr_magneton_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::\n          shielded_proton_mag_mom_to_Bohr_magneton_ratio<T>::precision()));\n}\n\n// shielded proton mag. mom. to nuclear magneton ratio\n// (2.792775598 \u00b1 3e-08)\nBOOST_AUTO_TEST_CASE_TEMPLATE(shielded_proton_mag_mom_to_nuclear_magneton_ratio,\n                              T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          shielded_proton_mag_mom_to_nuclear_magneton_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::\n          shielded_proton_mag_mom_to_nuclear_magneton_ratio<T>::value() ==\n      static_cast<T>(2.792775598));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          shielded_proton_mag_mom_to_nuclear_magneton_ratio<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::\n          shielded_proton_mag_mom_to_nuclear_magneton_ratio<T>::uncertainty() ==\n      static_cast<T>(3e-08));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::\n          shielded_proton_mag_mom_to_nuclear_magneton_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::\n          shielded_proton_mag_mom_to_nuclear_magneton_ratio<T>::precision()));\n}\n\n// speed of light in vacuum\n// (299792458.0 \u00b1 0.0) m s^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(speed_of_light_in_vacuum, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::speed_of_light_in_vacuum<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::speed_of_light_in_vacuum<T>::value() ==\n      static_cast<T>(299792458.0));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::speed_of_light_in_vacuum<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::speed_of_light_in_vacuum<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::speed_of_light_in_vacuum<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2010::speed_of_light_in_vacuum<\n                    T>::precision()));\n}\n\n// standard acceleration of gravity\n// (9.80665 \u00b1 0.0) m s^-2\nBOOST_AUTO_TEST_CASE_TEMPLATE(standard_acceleration_of_gravity, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::standard_acceleration_of_gravity<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::standard_acceleration_of_gravity<\n                 T>::value() == static_cast<T>(9.80665));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::standard_acceleration_of_gravity<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::standard_acceleration_of_gravity<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::standard_acceleration_of_gravity<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::standard_acceleration_of_gravity<\n          T>::precision()));\n}\n\n// standard atmosphere\n// (101325.0 \u00b1 0.0) Pa\nBOOST_AUTO_TEST_CASE_TEMPLATE(standard_atmosphere, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::standard_atmosphere<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::standard_atmosphere<T>::value() ==\n             static_cast<T>(101325.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::standard_atmosphere<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::standard_atmosphere<T>::uncertainty() ==\n      static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::standard_atmosphere<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::standard_atmosphere<T>::precision()));\n}\n\n// standard-state pressure\n// (100000.0 \u00b1 0.0) Pa\nBOOST_AUTO_TEST_CASE_TEMPLATE(standard_state_pressure, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::standard_state_pressure<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::standard_state_pressure<T>::value() ==\n      static_cast<T>(100000.0));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::standard_state_pressure<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::standard_state_pressure<\n                 T>::uncertainty() == static_cast<T>(0.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::standard_state_pressure<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::standard_state_pressure<T>::precision()));\n}\n\n// Stefan-Boltzmann constant\n// (5.670373e-08 \u00b1 2.1e-13) W m^-2 K^-4\nBOOST_AUTO_TEST_CASE_TEMPLATE(Stefan_Boltzmann_constant, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Stefan_Boltzmann_constant<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::Stefan_Boltzmann_constant<T>::value() ==\n      static_cast<T>(5.670373e-08));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::Stefan_Boltzmann_constant<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::Stefan_Boltzmann_constant<\n                 T>::uncertainty() == static_cast<T>(2.1e-13));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::Stefan_Boltzmann_constant<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2010::Stefan_Boltzmann_constant<\n                    T>::precision()));\n}\n\n// tau Compton wavelength\n// (6.97787e-16 \u00b1 6.3e-20) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(tau_Compton_wavelength, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::tau_Compton_wavelength<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::tau_Compton_wavelength<T>::value() ==\n      static_cast<T>(6.97787e-16));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::tau_Compton_wavelength<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::tau_Compton_wavelength<\n                 T>::uncertainty() == static_cast<T>(6.3e-20));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::tau_Compton_wavelength<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::tau_Compton_wavelength<T>::precision()));\n}\n\n// tau Compton wavelength over 2 pi\n// (1.11056e-16 \u00b1 1e-20) m\nBOOST_AUTO_TEST_CASE_TEMPLATE(tau_Compton_wavelength_over_2_pi, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::tau_Compton_wavelength_over_2_pi<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::tau_Compton_wavelength_over_2_pi<\n                 T>::value() == static_cast<T>(1.11056e-16));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::tau_Compton_wavelength_over_2_pi<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::tau_Compton_wavelength_over_2_pi<\n                 T>::uncertainty() == static_cast<T>(1e-20));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::tau_Compton_wavelength_over_2_pi<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::tau_Compton_wavelength_over_2_pi<\n          T>::precision()));\n}\n\n// tau-electron mass ratio\n// (3477.15 \u00b1 0.31)\nBOOST_AUTO_TEST_CASE_TEMPLATE(tau_electron_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::tau_electron_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::tau_electron_mass_ratio<T>::value() ==\n      static_cast<T>(3477.15));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::tau_electron_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::tau_electron_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(0.31));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::tau_electron_mass_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::tau_electron_mass_ratio<T>::precision()));\n}\n\n// tau mass\n// (3.16747e-27 \u00b1 2.9e-31) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(tau_mass, T, test_types) {\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::tau_mass<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::tau_mass<T>::value() ==\n             static_cast<T>(3.16747e-27));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::tau_mass<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::tau_mass<T>::uncertainty() ==\n             static_cast<T>(2.9e-31));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::tau_mass<T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2010::tau_mass<T>::precision()));\n}\n\n// tau mass energy equivalent\n// (2.84678e-10 \u00b1 2.6e-14) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(tau_mass_energy_equivalent, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::tau_mass_energy_equivalent<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::tau_mass_energy_equivalent<T>::value() ==\n      static_cast<T>(2.84678e-10));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::tau_mass_energy_equivalent<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::tau_mass_energy_equivalent<\n                 T>::uncertainty() == static_cast<T>(2.6e-14));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::tau_mass_energy_equivalent<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2010::tau_mass_energy_equivalent<\n                    T>::precision()));\n}\n\n// tau mass energy equivalent in MeV\n// (1776.82 \u00b1 0.16) MeV\nBOOST_AUTO_TEST_CASE_TEMPLATE(tau_mass_energy_equivalent_in_MeV, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::tau_mass_energy_equivalent_in_MeV<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::tau_mass_energy_equivalent_in_MeV<\n                 T>::value() == static_cast<T>(1776.82));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::tau_mass_energy_equivalent_in_MeV<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::tau_mass_energy_equivalent_in_MeV<\n                 T>::uncertainty() == static_cast<T>(0.16));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::tau_mass_energy_equivalent_in_MeV<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::tau_mass_energy_equivalent_in_MeV<\n          T>::precision()));\n}\n\n// tau mass in u\n// (1.90749 \u00b1 0.00017) u\nBOOST_AUTO_TEST_CASE_TEMPLATE(tau_mass_in_u, T, test_types) {\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::tau_mass_in_u<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::tau_mass_in_u<T>::value() ==\n             static_cast<T>(1.90749));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::tau_mass_in_u<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::tau_mass_in_u<T>::uncertainty() ==\n             static_cast<T>(0.00017));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::tau_mass_in_u<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::tau_mass_in_u<T>::precision()));\n}\n\n// tau molar mass\n// (0.00190749 \u00b1 1.7e-07) kg mol^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(tau_molar_mass, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::tau_molar_mass<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::tau_molar_mass<T>::value() ==\n             static_cast<T>(0.00190749));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::tau_molar_mass<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::tau_molar_mass<T>::uncertainty() ==\n             static_cast<T>(1.7e-07));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::tau_molar_mass<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::tau_molar_mass<T>::precision()));\n}\n\n// tau-muon mass ratio\n// (16.8167 \u00b1 0.0015)\nBOOST_AUTO_TEST_CASE_TEMPLATE(tau_muon_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::tau_muon_mass_ratio<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::tau_muon_mass_ratio<T>::value() ==\n             static_cast<T>(16.8167));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::tau_muon_mass_ratio<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::tau_muon_mass_ratio<T>::uncertainty() ==\n      static_cast<T>(0.0015));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::tau_muon_mass_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::tau_muon_mass_ratio<T>::precision()));\n}\n\n// tau-neutron mass ratio\n// (1.89111 \u00b1 0.00017)\nBOOST_AUTO_TEST_CASE_TEMPLATE(tau_neutron_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::tau_neutron_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::tau_neutron_mass_ratio<T>::value() ==\n      static_cast<T>(1.89111));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::tau_neutron_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::tau_neutron_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(0.00017));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::tau_neutron_mass_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::tau_neutron_mass_ratio<T>::precision()));\n}\n\n// tau-proton mass ratio\n// (1.89372 \u00b1 0.00017)\nBOOST_AUTO_TEST_CASE_TEMPLATE(tau_proton_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::tau_proton_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::tau_proton_mass_ratio<T>::value() ==\n      static_cast<T>(1.89372));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::tau_proton_mass_ratio<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::tau_proton_mass_ratio<T>::uncertainty() ==\n      static_cast<T>(0.00017));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::tau_proton_mass_ratio<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::tau_proton_mass_ratio<T>::precision()));\n}\n\n// Thomson cross section\n// (6.652458734e-29 \u00b1 1.3e-37) m^2\nBOOST_AUTO_TEST_CASE_TEMPLATE(Thomson_cross_section, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Thomson_cross_section<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::Thomson_cross_section<T>::value() ==\n      static_cast<T>(6.652458734e-29));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Thomson_cross_section<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::Thomson_cross_section<T>::uncertainty() ==\n      static_cast<T>(1.3e-37));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Thomson_cross_section<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::Thomson_cross_section<T>::precision()));\n}\n\n// triton-electron mass ratio\n// (5496.9215267 \u00b1 5e-06)\nBOOST_AUTO_TEST_CASE_TEMPLATE(triton_electron_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::triton_electron_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::triton_electron_mass_ratio<T>::value() ==\n      static_cast<T>(5496.9215267));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::triton_electron_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::triton_electron_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(5e-06));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::triton_electron_mass_ratio<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2010::triton_electron_mass_ratio<\n                    T>::precision()));\n}\n\n// triton g factor\n// (5.957924896 \u00b1 7.6e-08)\nBOOST_AUTO_TEST_CASE_TEMPLATE(triton_g_factor, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::triton_g_factor<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::triton_g_factor<T>::value() ==\n             static_cast<T>(5.957924896));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::triton_g_factor<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::triton_g_factor<T>::uncertainty() ==\n      static_cast<T>(7.6e-08));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::triton_g_factor<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::triton_g_factor<T>::precision()));\n}\n\n// triton mag. mom.\n// (1.504609447e-26 \u00b1 3.8e-34) J T^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(triton_mag_mom, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::triton_mag_mom<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::triton_mag_mom<T>::value() ==\n             static_cast<T>(1.504609447e-26));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::triton_mag_mom<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::triton_mag_mom<T>::uncertainty() ==\n             static_cast<T>(3.8e-34));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::triton_mag_mom<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::triton_mag_mom<T>::precision()));\n}\n\n// triton mag. mom. to Bohr magneton ratio\n// (0.001622393657 \u00b1 2.1e-11)\nBOOST_AUTO_TEST_CASE_TEMPLATE(triton_mag_mom_to_Bohr_magneton_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::triton_mag_mom_to_Bohr_magneton_ratio<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::triton_mag_mom_to_Bohr_magneton_ratio<\n          T>::value() == static_cast<T>(0.001622393657));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::triton_mag_mom_to_Bohr_magneton_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::triton_mag_mom_to_Bohr_magneton_ratio<\n          T>::uncertainty() == static_cast<T>(2.1e-11));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::triton_mag_mom_to_Bohr_magneton_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::triton_mag_mom_to_Bohr_magneton_ratio<\n          T>::precision()));\n}\n\n// triton mag. mom. to nuclear magneton ratio\n// (2.978962448 \u00b1 3.8e-08)\nBOOST_AUTO_TEST_CASE_TEMPLATE(triton_mag_mom_to_nuclear_magneton_ratio, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::triton_mag_mom_to_nuclear_magneton_ratio<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::triton_mag_mom_to_nuclear_magneton_ratio<\n          T>::value() == static_cast<T>(2.978962448));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::triton_mag_mom_to_nuclear_magneton_ratio<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::triton_mag_mom_to_nuclear_magneton_ratio<\n          T>::uncertainty() == static_cast<T>(3.8e-08));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::triton_mag_mom_to_nuclear_magneton_ratio<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::triton_mag_mom_to_nuclear_magneton_ratio<\n          T>::precision()));\n}\n\n// triton mass\n// (5.0073563e-27 \u00b1 2.2e-34) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(triton_mass, T, test_types) {\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::triton_mass<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::triton_mass<T>::value() ==\n             static_cast<T>(5.0073563e-27));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::triton_mass<T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::triton_mass<T>::uncertainty() ==\n             static_cast<T>(2.2e-34));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::triton_mass<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::triton_mass<T>::precision()));\n}\n\n// triton mass energy equivalent\n// (4.50038741e-10 \u00b1 2e-17) J\nBOOST_AUTO_TEST_CASE_TEMPLATE(triton_mass_energy_equivalent, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::triton_mass_energy_equivalent<\n          T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::triton_mass_energy_equivalent<\n                 T>::value() == static_cast<T>(4.50038741e-10));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::triton_mass_energy_equivalent<\n          T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::triton_mass_energy_equivalent<\n                 T>::uncertainty() == static_cast<T>(2e-17));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::triton_mass_energy_equivalent<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::triton_mass_energy_equivalent<\n          T>::precision()));\n}\n\n// triton mass energy equivalent in MeV\n// (2808.921005 \u00b1 6.2e-05) MeV\nBOOST_AUTO_TEST_CASE_TEMPLATE(triton_mass_energy_equivalent_in_MeV, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::triton_mass_energy_equivalent_in_MeV<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::triton_mass_energy_equivalent_in_MeV<\n          T>::value() == static_cast<T>(2808.921005));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::triton_mass_energy_equivalent_in_MeV<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::triton_mass_energy_equivalent_in_MeV<\n          T>::uncertainty() == static_cast<T>(6.2e-05));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::triton_mass_energy_equivalent_in_MeV<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::triton_mass_energy_equivalent_in_MeV<\n          T>::precision()));\n}\n\n// triton mass in u\n// (3.0155007134 \u00b1 2.5e-09) u\nBOOST_AUTO_TEST_CASE_TEMPLATE(triton_mass_in_u, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::triton_mass_in_u<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::triton_mass_in_u<T>::value() ==\n             static_cast<T>(3.0155007134));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::triton_mass_in_u<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::triton_mass_in_u<T>::uncertainty() ==\n      static_cast<T>(2.5e-09));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::triton_mass_in_u<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::triton_mass_in_u<T>::precision()));\n}\n\n// triton molar mass\n// (0.0030155007134 \u00b1 2.5e-12) kg mol^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(triton_molar_mass, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::triton_molar_mass<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::triton_molar_mass<T>::value() ==\n             static_cast<T>(0.0030155007134));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::triton_molar_mass<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::triton_molar_mass<T>::uncertainty() ==\n      static_cast<T>(2.5e-12));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::triton_molar_mass<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::triton_molar_mass<T>::precision()));\n}\n\n// triton-proton mass ratio\n// (2.9937170308 \u00b1 2.5e-09)\nBOOST_AUTO_TEST_CASE_TEMPLATE(triton_proton_mass_ratio, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::triton_proton_mass_ratio<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::triton_proton_mass_ratio<T>::value() ==\n      static_cast<T>(2.9937170308));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::triton_proton_mass_ratio<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::triton_proton_mass_ratio<\n                 T>::uncertainty() == static_cast<T>(2.5e-09));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::triton_proton_mass_ratio<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2010::triton_proton_mass_ratio<\n                    T>::precision()));\n}\n\n// unified atomic mass unit\n// (1.660538921e-27 \u00b1 7.3e-35) kg\nBOOST_AUTO_TEST_CASE_TEMPLATE(unified_atomic_mass_unit, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::unified_atomic_mass_unit<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::unified_atomic_mass_unit<T>::value() ==\n      static_cast<T>(1.660538921e-27));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::unified_atomic_mass_unit<\n                    T>::uncertainty()));\n  BOOST_TEST(triumf::constants::codata_2010::unified_atomic_mass_unit<\n                 T>::uncertainty() == static_cast<T>(7.3e-35));\n  BOOST_TEST(\n      std::isfinite(triumf::constants::codata_2010::unified_atomic_mass_unit<\n                    T>::precision()));\n  BOOST_TEST(\n      !std::signbit(triumf::constants::codata_2010::unified_atomic_mass_unit<\n                    T>::precision()));\n}\n\n// von Klitzing constant\n// (25812.8074434 \u00b1 8.4e-06) ohm\nBOOST_AUTO_TEST_CASE_TEMPLATE(von_Klitzing_constant, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::von_Klitzing_constant<T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::von_Klitzing_constant<T>::value() ==\n      static_cast<T>(25812.8074434));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::von_Klitzing_constant<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::von_Klitzing_constant<T>::uncertainty() ==\n      static_cast<T>(8.4e-06));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::von_Klitzing_constant<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::von_Klitzing_constant<T>::precision()));\n}\n\n// weak mixing angle\n// (0.2223 \u00b1 0.0021)\nBOOST_AUTO_TEST_CASE_TEMPLATE(weak_mixing_angle, T, test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::weak_mixing_angle<T>::value()));\n  BOOST_TEST(triumf::constants::codata_2010::weak_mixing_angle<T>::value() ==\n             static_cast<T>(0.2223));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::weak_mixing_angle<T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::weak_mixing_angle<T>::uncertainty() ==\n      static_cast<T>(0.0021));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::weak_mixing_angle<T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::weak_mixing_angle<T>::precision()));\n}\n\n// Wien frequency displacement law constant\n// (58789254000.0 \u00b1 53000.0) Hz K^-1\nBOOST_AUTO_TEST_CASE_TEMPLATE(Wien_frequency_displacement_law_constant, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Wien_frequency_displacement_law_constant<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::Wien_frequency_displacement_law_constant<\n          T>::value() == static_cast<T>(58789254000.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Wien_frequency_displacement_law_constant<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::Wien_frequency_displacement_law_constant<\n          T>::uncertainty() == static_cast<T>(53000.0));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Wien_frequency_displacement_law_constant<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::Wien_frequency_displacement_law_constant<\n          T>::precision()));\n}\n\n// Wien wavelength displacement law constant\n// (0.0028977721 \u00b1 2.6e-09) m K\nBOOST_AUTO_TEST_CASE_TEMPLATE(Wien_wavelength_displacement_law_constant, T,\n                              test_types) {\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Wien_wavelength_displacement_law_constant<\n          T>::value()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::Wien_wavelength_displacement_law_constant<\n          T>::value() == static_cast<T>(0.0028977721));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Wien_wavelength_displacement_law_constant<\n          T>::uncertainty()));\n  BOOST_TEST(\n      triumf::constants::codata_2010::Wien_wavelength_displacement_law_constant<\n          T>::uncertainty() == static_cast<T>(2.6e-09));\n  BOOST_TEST(std::isfinite(\n      triumf::constants::codata_2010::Wien_wavelength_displacement_law_constant<\n          T>::precision()));\n  BOOST_TEST(!std::signbit(\n      triumf::constants::codata_2010::Wien_wavelength_displacement_law_constant<\n          T>::precision()));\n}\n", "meta": {"hexsha": "c75ea05423a2c1eeccb4ec3d867d5554f4477e96", "size": 305998, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/codata_2010.cpp", "max_stars_repo_name": "rmlmcfadden/triumfpp", "max_stars_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/codata_2010.cpp", "max_issues_repo_name": "rmlmcfadden/triumfpp", "max_issues_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_issues_repo_licenses": ["MIT"], "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/codata_2010.cpp", "max_forks_repo_name": "rmlmcfadden/triumfpp", "max_forks_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_forks_repo_licenses": ["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.7515012868, "max_line_length": 80, "alphanum_fraction": 0.6910764123, "num_tokens": 87368, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851919, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.45290298606559204}}
{"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 \"AngleTerm.h\"\n#include \"../MMExceptions.h\"\n#include <Utils/Constants.h>\n#include <Utils/Math/AtomicSecondDerivativeCollection.h>\n#include <Utils/Math/AutomaticDifferentiation/AutomaticDifferentiationHelpers.h>\n#include <Utils/Math/AutomaticDifferentiation/VectorDerivatives3D.h>\n#include <Eigen/Eigenvalues>\n#include <Eigen/Geometry>\n\nnamespace Scine {\n\nusing namespace Utils::AutomaticDifferentiation;\nnamespace MolecularMechanics {\n\nAngleTerm::AngleTerm(AtomIndex firstAtom, AtomIndex secondAtom, AtomIndex thirdAtom, const Angle& angle, const AngleType& typeOfAngle)\n  : firstAtom_(firstAtom), secondAtom_(secondAtom), thirdAtom_(thirdAtom), angle_(angle), typeOfAngle_(typeOfAngle) {\n}\n\nAngleTerm::~AngleTerm() = default;\n\ndouble AngleTerm::evaluateAngleTerm(const Utils::PositionCollection& positions,\n                                    Utils::AtomicSecondDerivativeCollection& derivatives) const {\n  if (this->disabled_)\n    return 0.0;\n  if (!angle_.hasParameters()) // Check this only if this term is not disabled\n    throw MMAngleParametersNotAvailableException(typeOfAngle_.a1, typeOfAngle_.a2, typeOfAngle_.a3);\n\n  Eigen::Vector3d a(positions.row(firstAtom_) - positions.row(secondAtom_));\n  Eigen::Vector3d b(positions.row(thirdAtom_) - positions.row(secondAtom_));\n\n  double angle = acos((a.dot(b) / (a.norm() * b.norm())));\n  Second1D result = angle_.getInteraction(angle);\n  double energy = result.value();\n\n  Second3D angleContributionAtom1;\n  Second3D angleContributionAtom2;\n  Second3D angleContributionAtom3;\n  if (angle < Utils::Constants::pi - singularityCriterion_ && angle > singularityCriterion_) {\n    calculateDerivativesWithNormalFormula(result, a, b, angleContributionAtom1, angleContributionAtom2, angleContributionAtom3);\n  }\n  else {\n    calculateDerivativesForCriticalAngles(result, a, b, angleContributionAtom1, angleContributionAtom2, angleContributionAtom3);\n    energy = 0;\n  }\n\n  derivatives[firstAtom_] += angleContributionAtom1;\n  derivatives[secondAtom_] += angleContributionAtom2;\n  derivatives[thirdAtom_] += angleContributionAtom3;\n\n  return energy;\n}\n\nSecond3D AngleTerm::threeDimDer(const Second1D& energy, const Second3D& alpha) {\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 AngleTerm::calculateDerivativesWithNormalFormula(const Second1D& angleDerivative, const Eigen::Vector3d& a,\n                                                      const Eigen::Vector3d& b, Second3D& angleContributionAtom1,\n                                                      Second3D& angleContributionAtom2, Second3D& angleContributionAtom3) {\n  // NB: suffix digit indicates with respect to which atom the derivative is taken\n  auto a1 = VectorDerivatives3D::spatialVectorHessian3D(a);\n  auto a2 = VectorDerivatives3D::spatialVectorHessian3DWithInverseDerivative(a);\n  auto b3 = VectorDerivatives3D::spatialVectorHessian3D(b);\n  auto b2 = VectorDerivatives3D::spatialVectorHessian3DWithInverseDerivative(b);\n\n  Second3D alpha1 = arccos(a1.dot(b) / (a1.norm() * b.norm()));\n  Second3D alpha2 = arccos(a2.dot(b2) / (a2.norm() * b2.norm())); // NB: maybe the second derivatives for atom 2 can be\n                                                                  // obtained from atom 1 and 2 in the end and this is\n                                                                  // not needed\n  Second3D alpha3 = arccos(b3.dot(a) / (a.norm() * b3.norm()));\n\n  angleContributionAtom1 = threeDimDer(angleDerivative, alpha1);\n  angleContributionAtom2 = threeDimDer(angleDerivative, alpha2);\n  angleContributionAtom3 = threeDimDer(angleDerivative, alpha3);\n}\n\nvoid AngleTerm::calculateDerivativesForCriticalAngles(const Second1D& angleDerivative, const Eigen::Vector3d& a,\n                                                      const Eigen::Vector3d& b, Second3D& angleContributionAtom1,\n                                                      Second3D& angleContributionAtom2, Second3D& angleContributionAtom3) {\n  // Explanation of formulas: see Alain's derivation\n  Eigen::Vector3d orientation = a.normalized();\n\n  double inverseDistanceSum = 1.0 / a.norm() + 1.0 / b.norm();\n  double d2thetad1 = 1.0 / a.squaredNorm();\n  double d2thetad3 = 1.0 / b.squaredNorm();\n  double d2thetad2 = inverseDistanceSum * inverseDistanceSum;\n\n  double d2dxx1 = d2thetad1 * angleDerivative.second(); // Second derivative of the Energy with respect to x in local\n                                                        // coordinate system for atom 1\n  double d2dxx2 = d2thetad2 * angleDerivative.second();\n  double d2dxx3 = d2thetad3 * angleDerivative.second();\n\n  double x = orientation.x();\n  double y = orientation.y();\n  double z = orientation.z();\n\n  // Get the local coordinate system: generate perpendicular unit x and y vectors\n  Eigen::Vector3d yV(0, z, -y);\n  if (std::abs(x) > std::abs(y))\n    yV = Eigen::Vector3d(-z, 0, x);\n  yV.normalize();\n  Eigen::Vector3d xV = yV.cross(orientation);\n\n  // Derivatives of local coordinates with respect to global coordinates\n  double dxdx = xV.x();\n  double dxdy = xV.y();\n  double dxdz = xV.z();\n  double dydx = yV.x();\n  double dydy = yV.y();\n  double dydz = yV.z();\n\n  angleContributionAtom1 = Second3D(0, 0, 0, 0, d2dxx1 * (dxdx * dxdx + dydx * dydx), d2dxx1 * (dxdy * dxdy + dydy * dydy),\n                                    d2dxx1 * (dxdz * dxdz + dydz * dydz), d2dxx1 * (dxdx * dxdy + dydx * dydy),\n                                    d2dxx1 * (dxdx * dxdz + dydx * dydz), d2dxx1 * (dxdy * dxdz + dydy * dydz));\n  angleContributionAtom2 = Second3D(0, 0, 0, 0, d2dxx2 * (dxdx * dxdx + dydx * dydx), d2dxx2 * (dxdy * dxdy + dydy * dydy),\n                                    d2dxx2 * (dxdz * dxdz + dydz * dydz), d2dxx2 * (dxdx * dxdy + dydx * dydy),\n                                    d2dxx2 * (dxdx * dxdz + dydx * dydz), d2dxx2 * (dxdy * dxdz + dydy * dydz));\n  angleContributionAtom3 = Second3D(0, 0, 0, 0, d2dxx3 * (dxdx * dxdx + dydx * dydx), d2dxx3 * (dxdy * dxdy + dydy * dydy),\n                                    d2dxx3 * (dxdz * dxdz + dydz * dydz), d2dxx3 * (dxdx * dxdy + dydx * dydy),\n                                    d2dxx3 * (dxdx * dxdz + dydx * dydz), d2dxx3 * (dxdy * dxdz + dydy * dydz));\n}\n\nAngleType AngleTerm::getTypeOfAngle() const {\n  return typeOfAngle_;\n}\n\nint AngleTerm::getFirstAtom() const {\n  return firstAtom_;\n}\n\nint AngleTerm::getSecondAtom() const {\n  return secondAtom_;\n}\n\nint AngleTerm::getThirdAtom() const {\n  return thirdAtom_;\n}\n\n} // namespace MolecularMechanics\n} // namespace Scine\n", "meta": {"hexsha": "69b85242f98145a5d4954deacd40ed8661015a72", "size": 7320, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Swoose/Swoose/MolecularMechanics/Interactions/AngleTerm.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/AngleTerm.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/AngleTerm.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": 46.6242038217, "max_line_length": 134, "alphanum_fraction": 0.6483606557, "num_tokens": 2055, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891479496521, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.45270340072422194}}
{"text": "#ifndef __EIGENMULTIVARIATENORMAL_HPP\n#define __EIGENMULTIVARIATENORMAL_HPP\n\n#include <Eigen/Dense>\n#include <math.h>\n\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n\ntemplate<typename _Scalar, int _size>\nclass EigenMultivariateNormal\n{\n    boost::mt19937 rng;    // The uniform pseudo-random algorithm\n    boost::normal_distribution<_Scalar> norm;  // The gaussian combinator\n    boost::variate_generator<boost::mt19937&,boost::normal_distribution<_Scalar> >\n       randN; // The 0-mean unit-variance normal generator\n\n    Eigen::Matrix<_Scalar,_size,_size> rot;\n    Eigen::Matrix<_Scalar,_size,1> scl;\n\n    Eigen::Matrix<_Scalar,_size,1> mean;\n\npublic:\n    EigenMultivariateNormal(const Eigen::Matrix<_Scalar,_size,1>& meanVec,\n        const Eigen::Matrix<_Scalar,_size,_size>& covarMat)\n        : randN(rng,norm)\n    {\n        setCovar(covarMat);\n        setMean(meanVec);\n    }\n\n    void setCovar(const Eigen::Matrix<_Scalar,_size,_size>& covarMat)\n    {\n        Eigen::SelfAdjointEigenSolver<Eigen::Matrix<_Scalar,_size,_size> >\n           eigenSolver(covarMat);\n        rot = eigenSolver.eigenvectors();\n        scl = eigenSolver.eigenvalues();\n        for (int ii=0;ii<_size;++ii) {\n            scl(ii,0) = sqrt(scl(ii,0));\n        }\n    }\n\n    void setMean(const Eigen::Matrix<_Scalar,_size,1>& meanVec)\n    {\n        mean = meanVec;\n    }\n\n    void nextSample(Eigen::Matrix<_Scalar,_size,1>& sampleVec)\n    {\n        for (int ii=0;ii<_size;++ii) {\n            sampleVec(ii,0) = randN()*scl(ii,0);\n        }\n        sampleVec = rot*sampleVec + mean;\n    }\n    \n};\n\n#endif\n", "meta": {"hexsha": "6aeb3ada97cce6a17cb9c671fda5c1382c50637b", "size": 1672, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/lidar_eskf/EigenMultivariateNormal.hpp", "max_stars_repo_name": "castacks/lidar_eskf", "max_stars_repo_head_hexsha": "da2648e0fc7afc2a0f5977cd5fbd855ba48cc459", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2018-05-11T18:07:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-10T10:00:02.000Z", "max_issues_repo_path": "include/lidar_eskf/EigenMultivariateNormal.hpp", "max_issues_repo_name": "castacks/lidar_eskf", "max_issues_repo_head_hexsha": "da2648e0fc7afc2a0f5977cd5fbd855ba48cc459", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/lidar_eskf/EigenMultivariateNormal.hpp", "max_forks_repo_name": "castacks/lidar_eskf", "max_forks_repo_head_hexsha": "da2648e0fc7afc2a0f5977cd5fbd855ba48cc459", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2018-05-11T18:07:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T11:58:11.000Z", "avg_line_length": 27.8666666667, "max_line_length": 82, "alphanum_fraction": 0.6590909091, "num_tokens": 454, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.4527033959263116}}
{"text": "#if !defined F_DECOMPOSER_HPP\n#define F_DECOMPOSER_HPP\n\n#include <Eigen/Core>\n#include <Eigen/LU>\n\nnamespace LocalStress {\n  // NOTE:\n  // drij = ri - rj;\n#define DECL_DECOMPOSE_FORCE_FUNC(N)                                    \\\n  template <typename T, int32_t num_body = N>                           \\\n  auto decomposeForce(const std::array<Vec<T>, N>& F,                   \\\n                      const std::array<Vec<T>, N*(N-1)/2>& dr) -> remove_reference_t<decltype(dr)> \\\n\n  // in  F = {F0, F1, F2}, dr = {dr01, dr12, dr20};\n  // out dF = {dF01, dF12, dF20};\n  DECL_DECOMPOSE_FORCE_FUNC(3) {\n    using dr_pair_t = remove_const_t<remove_reference_t<decltype(dr)>>;\n    const dr_pair_t dr_u {normalize(dr[0]), normalize(dr[1]), normalize(dr[2])};\n    const auto dFa = F[0] * (dr_u[0] - dr_u[2]) / (1.0 - dr_u[0] * dr_u[2]);\n    const auto dFb = F[1] * (dr_u[1] - dr_u[0]) / (1.0 - dr_u[1] * dr_u[0]);\n    const auto dFc = F[2] * (dr_u[2] - dr_u[1]) / (1.0 - dr_u[2] * dr_u[1]);\n    const auto dF01 = 0.5 * (dFa + dFb - dFc);\n    const auto dF12 = 0.5 * (dFb + dFc - dFa);\n    const auto dF02 = 0.5 * (dFc + dFa - dFb);\n    return {dF01 * dr_u[0], dF12 * dr_u[1], dF02 * dr_u[2]};\n  }\n\n#define VEC_TO_MAT(M, i, j, v)                  \\\n  do {                                          \\\n    for (int32_t axis = 0; axis < D; axis++) {  \\\n      M(D * i + axis, j) = v[axis];             \\\n    }                                           \\\n  } while (0)\n\n  // in  F = {F0, F1, F2, F3}, dr = {dr01, dr02, dr03, dr12, dr13, dr23}\n  // out dF = {dF01, dF02, dF03, dF12, dF13, dF23}\n  DECL_DECOMPOSE_FORCE_FUNC(4) {\n    constexpr int32_t nrows = num_body * D;\n    constexpr int32_t ncols = num_body * (num_body - 1) / 2;\n\n    Eigen::Matrix<T, nrows, ncols> dr_mat;\n    dr_mat.setZero();\n\n    // F0\n    VEC_TO_MAT(dr_mat, 0, 0, dr[0]);\n    VEC_TO_MAT(dr_mat, 0, 1, dr[1]);\n    VEC_TO_MAT(dr_mat, 0, 2, dr[2]);\n\n    // F1\n    VEC_TO_MAT(dr_mat, 1, 0, -dr[0]);\n    VEC_TO_MAT(dr_mat, 1, 3, dr[3]);\n    VEC_TO_MAT(dr_mat, 1, 4, dr[4]);\n\n    // F2\n    VEC_TO_MAT(dr_mat, 2, 1, -dr[1]);\n    VEC_TO_MAT(dr_mat, 2, 3, -dr[3]);\n    VEC_TO_MAT(dr_mat, 2, 5, dr[5]);\n\n    // F3\n    VEC_TO_MAT(dr_mat, 3, 2, -dr[2]);\n    VEC_TO_MAT(dr_mat, 3, 4, -dr[4]);\n    VEC_TO_MAT(dr_mat, 3, 5, -dr[5]);\n\n    Eigen::VectorXd F_vec(nrows);\n    std::copy_n(&F[0].x, nrows, F_vec.data());\n\n    Eigen::VectorXd cf_dF = dr_mat.fullPivLu().solve(F_vec);\n\n    return {cf_dF[0] * dr[0], cf_dF[1] * dr[1], cf_dF[2] * dr[2],\n            cf_dF[3] * dr[3], cf_dF[4] * dr[4], cf_dF[5] * dr[5]};\n  }\n\n#undef VEC_TO_MAT\n#undef DECL_DECOMPOSE_FORCE_FUNC\n}\n#endif\n", "meta": {"hexsha": "6b5d6ecf35e9a2e2a64e4e3d5048d68f1d2eae50", "size": 2619, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "f_decomposer.hpp", "max_stars_repo_name": "kohnakagawa/MDLSC", "max_stars_repo_head_hexsha": "0cca3180608cb39370bf8c19f72f05484871eb54", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "f_decomposer.hpp", "max_issues_repo_name": "kohnakagawa/MDLSC", "max_issues_repo_head_hexsha": "0cca3180608cb39370bf8c19f72f05484871eb54", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2017-09-10T10:09:35.000Z", "max_issues_repo_issues_event_max_datetime": "2017-09-17T12:43:47.000Z", "max_forks_repo_path": "f_decomposer.hpp", "max_forks_repo_name": "kohnakagawa/MDLSC", "max_forks_repo_head_hexsha": "0cca3180608cb39370bf8c19f72f05484871eb54", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-12-12T11:56:35.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-12T11:56:35.000Z", "avg_line_length": 33.5769230769, "max_line_length": 100, "alphanum_fraction": 0.5269186712, "num_tokens": 1017, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358014, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.45270339592631154}}
{"text": "\r\n\r\n#include <NTL/GF2E.h>\r\n\r\n#include <NTL/new.h>\r\n\r\nNTL_START_IMPL\r\n\r\n\r\nGF2EInfoT::GF2EInfoT(const GF2X& NewP)\r\n{\r\n   build(p, NewP);\r\n\r\n   if (p.size == 1) {\r\n      if (deg(p) <= NTL_BITS_PER_LONG/2)\r\n         KarCross = 4;\r\n      else\r\n         KarCross = 8;\r\n   }\r\n   else if (p.size == 2)\r\n      KarCross = 8;\r\n   else if (p.size <= 5)\r\n      KarCross = 4;\r\n   else if (p.size == 6)\r\n      KarCross = 3;\r\n   else \r\n      KarCross = 2;\r\n\r\n\r\n   if (p.size <= 1) {\r\n      if (deg(p) <= NTL_BITS_PER_LONG/2)\r\n         ModCross = 20;\r\n      else\r\n         ModCross = 40;\r\n   }\r\n   else if (p.size <= 2)\r\n      ModCross = 75;\r\n   else if (p.size <= 4)\r\n      ModCross = 50;\r\n   else\r\n      ModCross = 25;\r\n\r\n   if (p.size == 1) {\r\n      if (deg(p) <= NTL_BITS_PER_LONG/2)\r\n         DivCross = 100;\r\n      else\r\n         DivCross = 200;\r\n   }\r\n   else if (p.size == 2)\r\n      DivCross = 400;\r\n   else if (p.size <= 4)\r\n      DivCross = 200;\r\n   else if (p.size == 5)\r\n      DivCross = 150;\r\n   else if (p.size <= 13)\r\n      DivCross = 100;\r\n   else \r\n      DivCross = 75;\r\n\r\n   _card_exp = p.n;\r\n}\r\n\r\n\r\nconst ZZ& GF2E::cardinality()\r\n{\r\n   if (!GF2EInfo) LogicError(\"GF2E::cardinality: undefined modulus\");\r\n\r\n   do { // NOTE: thread safe lazy init\r\n      Lazy<ZZ>::Builder builder(GF2EInfo->_card);\r\n      if (!builder()) break;\r\n      UniquePtr<ZZ> p;\r\n      p.make();\r\n      power(*p, 2, GF2EInfo->_card_exp);\r\n      builder.move(p);\r\n   } while (0);\r\n\r\n   return *GF2EInfo->_card;\r\n}\r\n\r\n\r\n\r\n\r\nNTL_THREAD_LOCAL\r\nSmartPtr<GF2EInfoT> GF2EInfo = 0; \r\n\r\n\r\n\r\n\r\nvoid GF2E::init(const GF2X& p)\r\n{\r\n   GF2EContext c(p);\r\n   c.restore();\r\n}\r\n\r\n\r\nvoid GF2EContext::save()\r\n{\r\n   ptr = GF2EInfo;\r\n}\r\n\r\nvoid GF2EContext::restore() const\r\n{\r\n   GF2EInfo = ptr;\r\n}\r\n\r\n\r\n\r\nGF2EBak::~GF2EBak()\r\n{\r\n   if (MustRestore) c.restore();\r\n}\r\n\r\nvoid GF2EBak::save()\r\n{\r\n   c.save();\r\n   MustRestore = true;\r\n}\r\n\r\n\r\nvoid GF2EBak::restore()\r\n{\r\n   c.restore();\r\n   MustRestore = false;\r\n}\r\n\r\n\r\n\r\nconst GF2E& GF2E::zero()\r\n{\r\n   NTL_THREAD_LOCAL static GF2E z(INIT_NO_ALLOC);\r\n   return z;\r\n}\r\n\r\n\r\n\r\nistream& operator>>(istream& s, GF2E& x)\r\n{\r\n   GF2X 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(GF2E& x, const GF2E& a, const GF2E& b)\r\n{\r\n   GF2E t;\r\n\r\n   inv(t, b);\r\n   mul(x, a, t);\r\n}\r\n\r\nvoid div(GF2E& x, GF2 a, const GF2E& b)\r\n{\r\n   inv(x, b);\r\n   mul(x, x, a);\r\n}\r\n\r\nvoid div(GF2E& x, long a, const GF2E& b)\r\n{\r\n   inv(x, b);\r\n   mul(x, x, a);\r\n}\r\n\r\n\r\nvoid inv(GF2E& x, const GF2E& a)\r\n{\r\n   InvMod(x._GF2E__rep, a._GF2E__rep, GF2E::modulus());\r\n}\r\n\r\nNTL_END_IMPL\r\n", "meta": {"hexsha": "408508d77d19251de2ff8d860a7df2f8499b9d72", "size": 2590, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "WinNTL-8_1_2/src/GF2E.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/GF2E.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/GF2E.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": 14.9710982659, "max_line_length": 70, "alphanum_fraction": 0.5092664093, "num_tokens": 881, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.452703391128401}}
{"text": "/*\nCopyright (c) 2018 Inverse Palindrome\nApophis - SteeringBehaviors.cpp\nInversePalindrome.com\n*/\n\n\n#include \"Constants.hpp\"\n#include \"SteeringBehaviors.hpp\"\n\n#include <cocos/base/ccRandom.h>\n\n#include <boost/math/constants/constants.hpp>\n\n#include <cmath>\n\n\nb2Vec2 SteeringBehaviors::seek(const b2Vec2& bodyPosition, const b2Vec2& targetPosition, const b2Vec2& bodyVelocity, float maxSpeed)\n{\n    return desiredVelocity(bodyPosition, targetPosition, maxSpeed) - bodyVelocity;\n}\n\nb2Vec2 SteeringBehaviors::flee(const b2Vec2& bodyPosition, const b2Vec2& targetPosition, const b2Vec2& bodyVelocity, float maxSpeed)\n{\n    return desiredVelocity(targetPosition, bodyPosition, maxSpeed) - bodyVelocity;\n}\n\nb2Vec2 SteeringBehaviors::pursue(const b2Vec2& bodyPosition, const b2Vec2& targetPosition, const b2Vec2& bodyVelocity, const b2Vec2& targetVelocity, float maxSpeed)\n{\n    const auto predictionFrames = (targetPosition - bodyPosition).Length() / maxSpeed;\n\n    return seek(bodyPosition, targetPosition + predictionFrames * targetVelocity, bodyVelocity, maxSpeed);\n}\n\nb2Vec2 SteeringBehaviors::evade(const b2Vec2& bodyPosition, const b2Vec2& targetPosition, const b2Vec2& bodyVelocity, const b2Vec2& targetVelocity, float maxSpeed)\n{\n    const auto predictionFrames = (targetPosition - bodyPosition).Length() / maxSpeed;\n\n    return flee(bodyPosition, targetPosition + predictionFrames * targetVelocity, bodyVelocity, maxSpeed);\n}\n\nb2Vec2 SteeringBehaviors::arrive(const b2Vec2& bodyPosition, const b2Vec2& targetPosition, const b2Vec2& bodyVelocity, float slowRadius, float maxSpeed)\n{\n    if (const auto radius = (targetPosition - bodyPosition).Length(); radius < slowRadius)\n    {\n        return seek(bodyPosition, targetPosition, bodyVelocity, maxSpeed * radius / slowRadius);\n    }\n\n    return seek(bodyPosition, targetPosition, bodyVelocity, maxSpeed);\n}\n\nb2Vec2 SteeringBehaviors::wander(const b2Vec2& bodyPosition, const b2Vec2& bodyVelocity, float wanderDistance, float wanderRadius, float wanderRate, float& wanderAngle, float maxSpeed)\n{\n    auto wanderCenter = bodyVelocity;\n    wanderCenter.Normalize();\n    wanderCenter *= wanderDistance;\n    wanderCenter += { wanderRadius* std::cos(wanderAngle), wanderRadius* std::sin(wanderAngle) };\n\n    wanderAngle += cocos2d::rand_minus1_1() * wanderRate;\n\n    return seek(bodyPosition, bodyPosition + wanderCenter, bodyVelocity, maxSpeed);\n}\n\nb2Vec2 SteeringBehaviors::orbit(const b2Vec2& satellitePosition, const b2Vec2& primaryPosition, const b2Vec2& bodyVelocity, float maxSpeed)\n{\n    const auto radius = primaryPosition - satellitePosition;\n\n    auto steeringForce = radius.Skew();\n    steeringForce.Normalize();\n    steeringForce *= maxSpeed;\n\n    return steeringForce - bodyVelocity;\n}\n\nb2Vec2 SteeringBehaviors::alignForce(const b2Vec2& agentPosition, const std::vector<b2Vec2>& neighborVelocities, float alignmentForce)\n{\n    b2Vec2 steeringForce(0.f, 0.f);\n\n    for (const auto& neighborVelocity : neighborVelocities)\n    {\n        steeringForce += neighborVelocity;\n    }\n\n    if (!neighborVelocities.empty())\n    {\n        steeringForce *= 1.f / neighborVelocities.size();\n        steeringForce.Normalize();\n        steeringForce *= alignmentForce;\n    }\n\n    return steeringForce;\n}\n\nb2Vec2 SteeringBehaviors::cohesionForce(const b2Vec2& agentPosition, const std::vector<b2Vec2>& neighborPositions, float cohesionForce)\n{\n    b2Vec2 steeringForce(0.f, 0.f);\n\n    for (const auto& neighborPosition : neighborPositions)\n    {\n        steeringForce += neighborPosition;\n    }\n\n    if (!neighborPositions.empty())\n    {\n        steeringForce *= 1.f / neighborPositions.size();\n        steeringForce -= agentPosition;\n        steeringForce.Normalize();\n        steeringForce *= cohesionForce;\n    }\n\n    return steeringForce;\n}\n\nb2Vec2 SteeringBehaviors::separateForce(const b2Vec2& agentPosition, const std::vector<b2Vec2>& neighborPositions, float separationForce)\n{\n    b2Vec2 steeringForce(0.f, 0.f);\n\n    for (const auto& neighborPosition : neighborPositions)\n    {\n        steeringForce += neighborPosition - agentPosition;\n    }\n\n    if (!neighborPositions.empty())\n    {\n        steeringForce *= -1.f / neighborPositions.size();\n        steeringForce.Normalize();\n        steeringForce *= separationForce;\n    }\n\n    return steeringForce;\n}\n\nb2Vec2 SteeringBehaviors::desiredVelocity(const b2Vec2& bodyPosition, const b2Vec2& targetPosition, float maxSpeed)\n{\n    auto desiredVelocity = targetPosition - bodyPosition;\n    desiredVelocity.Normalize();\n    desiredVelocity *= maxSpeed;\n\n    return desiredVelocity;\n}\n\nfloat SteeringBehaviors::face(float desiredAngle, float bodyAngle, float bodyAngularVelocity, float bodyInertia)\n{\n    const auto nextAngle = bodyAngle + bodyAngularVelocity / Constants::FPS;\n    const auto totalRotation = std::remainderf(desiredAngle - nextAngle, 2 * boost::math::constants::pi<float>());\n\n    return bodyInertia * totalRotation * Constants::FPS;\n}\n\nfloat SteeringBehaviors::face(const b2Vec2& bodyPosition, const b2Vec2& targetPosition, float bodyAngle, float bodyAngularVelocity, float bodyInertia)\n{\n    const auto desiredAngle = std::atan2f(targetPosition.y - bodyPosition.y, targetPosition.x - bodyPosition.x);\n\n    return face(desiredAngle, bodyAngle, bodyAngularVelocity, bodyInertia);\n}\n", "meta": {"hexsha": "3d3473dcfaa60f2c5630e8810cd6c3ec2fccc4ed", "size": 5298, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Classes/SteeringBehaviors.cpp", "max_stars_repo_name": "InversePalindrome/Apophis", "max_stars_repo_head_hexsha": "c2bb39e87d63cb51bc67f8e3682d84b3b4f970c8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2018-08-20T17:28:29.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-05T15:19:31.000Z", "max_issues_repo_path": "Classes/SteeringBehaviors.cpp", "max_issues_repo_name": "InversePalindrome/JATR66", "max_issues_repo_head_hexsha": "c2bb39e87d63cb51bc67f8e3682d84b3b4f970c8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Classes/SteeringBehaviors.cpp", "max_forks_repo_name": "InversePalindrome/JATR66", "max_forks_repo_head_hexsha": "c2bb39e87d63cb51bc67f8e3682d84b3b4f970c8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-12-25T12:02:03.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-25T12:02:03.000Z", "avg_line_length": 33.9615384615, "max_line_length": 184, "alphanum_fraction": 0.7463193658, "num_tokens": 1281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891218080991, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.4527033863304903}}
{"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_HYPOT_HPP_INCLUDED\n#define BOOST_SIMD_ARITHMETIC_FUNCTIONS_SCALAR_HYPOT_HPP_INCLUDED\n\n#include <boost/simd/arithmetic/functions/hypot.hpp>\n#include <boost/dispatch/meta/as_integer.hpp>\n#include <boost/simd/sdk/config.hpp>\n#include <boost/simd/include/functions/scalar/abs.hpp>\n#include <boost/simd/include/functions/scalar/exponent.hpp>\n#include <boost/simd/include/functions/scalar/ldexp.hpp>\n#include <boost/simd/include/functions/scalar/sqr.hpp>\n#include <boost/simd/include/functions/scalar/sqrt.hpp>\n#include <boost/simd/include/functions/scalar/max.hpp>\n#include <boost/simd/include/functions/scalar/min.hpp>\n#include <boost/simd/include/constants/maxexponentm1.hpp>\n#include <boost/simd/include/constants/minexponent.hpp>\n#include <boost/simd/include/constants/zero.hpp>\n\n#ifndef BOOST_SIMD_NO_INVALIDS\n#include <boost/simd/include/functions/scalar/is_inf.hpp>\n#include <boost/simd/include/functions/scalar/is_nan.hpp>\n#include <boost/simd/include/constants/inf.hpp>\n#endif\n\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT          ( hypot_, tag::cpu_\n                                    , (A0)\n                                    , ((scalar_<floating_<A0> >))\n                                      ((scalar_<floating_<A0> >))\n                                    )\n  {\n    typedef A0 result_type;\n\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    {\n      typedef typename dispatch::meta::as_integer<result_type>::type   iA0;\n      #ifndef BOOST_SIMD_NO_INVALIDS\n      if (is_nan(a0) && is_inf(a1)) return Inf<A0>();\n      if (is_inf(a0) && is_nan(a1)) return Inf<A0>();\n      #endif\n      A0 r =  boost::simd::abs(a0);\n      A0 i =  boost::simd::abs(a1);\n      iA0 e =  exponent(boost::simd::max(i, r));\n      e = boost::simd::min(boost::simd::max(e,Minexponent<A0>()),Maxexponentm1<A0>());\n      return ldexp(sqrt(sqr(ldexp(r, -e))+sqr(ldexp(i, -e))), e);\n    }\n  };\n} } }\n\n#endif\n", "meta": {"hexsha": "81e5eb39058e94dd5378f43a43991177c31c052f", "size": 2464, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/scalar/hypot.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/hypot.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/hypot.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": 41.0666666667, "max_line_length": 86, "alphanum_fraction": 0.617288961, "num_tokens": 595, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424528443251, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.45266247722553976}}
{"text": "#include <queue>\n#include <fstream>\n#include <iostream>\n\n#include <boost/algorithm/string.hpp>\n\n#include \"../headers/Phylogeny.h\"\n\ntypedef boost::variate_generator<boost::mt19937 &, boost::exponential_distribution<>> exp_distribution;\n\nPhylogeny::Phylogeny(double alpha, double beta)\n{\n    this->alpha = alpha;\n    this->beta = beta;\n}\nstd::vector<std::vector<double>> Phylogeny::generateProbMatrix(double time)\n{\n    double s = (1 - std::exp(-4 * beta * time)) / 4;\n    double u = (1 + std::exp(-4 * beta * time) - 2 * std::exp(-2 * (alpha + beta) * time)) / 4;\n    double r = 1 - 2 * s - u;\n\n    std::vector<std::vector<double>> retArray = {\n        {r, s, u, s},\n        {s, r, s, u},\n        {u, s, r, s},\n        {s, u, s, r}};\n\n    return retArray;\n}\nstd::vector<treeVertex> Phylogeny::phylogenesy(std::vector<treeVertex> &tree, int epochs, double timeGeneratorMean)\n{\n    boost::mt19937 generator(5u);\n    exp_distribution distribution(generator, boost::exponential_distribution<>(timeGeneratorMean));\n\n    int actualEpoch = 0;\n    std::queue<int> vertexQueue;\n\n    for (treeVertex &vertex : tree)\n    {\n        if (vertex.left == 0 && vertex.right == 0) //only push leaves\n            vertexQueue.push(vertex.id);\n    }\n    while (!vertexQueue.empty())\n    {\n        int vertex = vertexQueue.front();\n        vertexQueue.pop();\n\n        double time = tree[vertex].timeDepth + distribution();\n\n        ProteinSequence nextSpecie = mutate(tree[vertex].sequence, time, generator);\n\n        if (nextSpecie.baseVec2String() == tree[vertex].sequence.baseVec2String())\n            continue;\n        treeVertex dummyVertex(tree[vertex].sequence);\n        tree[vertex].left = dummyVertex.id = tree.size();\n\n        dummyVertex.root = tree[vertex].id;\n        dummyVertex.depth = tree[vertex].depth + 1;\n        dummyVertex.timeDepth = time;\n\n        tree.push_back(dummyVertex);\n\n        treeVertex nextVertex(nextSpecie);\n\n        nextVertex.root = tree[vertex].id;\n        nextVertex.sequence = nextSpecie;\n        nextVertex.depth = tree[vertex].depth + 1;\n        nextVertex.timeDepth = time;\n\n        tree[vertex].right = nextVertex.id = tree.size();\n\n        tree.push_back(nextVertex);\n        actualEpoch++;\n        if (actualEpoch < epochs)\n        {\n            vertexQueue.push(dummyVertex.id);\n            vertexQueue.push(nextVertex.id);\n        }\n    }\n    return tree;\n}\n//TODO: mutatis mutandis\nProteinSequence Phylogeny::mutate(ProteinSequence &initialSequence, double &time, boost::mt19937 &generator)\n{\n    ProteinSequence mutatedSequence;\n\n    std::vector<std::vector<double>> probMatrix = generateProbMatrix(time);\n\n    for (base &prot : initialSequence)\n    {\n        int protCode = static_cast<int>(prot);\n        boost::random::discrete_distribution<int, double> mutationprobability(probMatrix[protCode]);\n        int nextProtein = mutationprobability(generator);\n        mutatedSequence.pushBack(static_cast<base>(nextProtein));\n    }\n\n    return mutatedSequence;\n}\n\nvoid Phylogeny::writeBranchesIntoFile(std::string filename, std::vector<treeVertex> &tree)\n{\n    std::ofstream targetFile;\n    std::vector<treeVertex> leaves;\n\n    for (treeVertex &vertex : tree)\n    {\n        if (vertex.right == 0 && vertex.left == 0)\n            leaves.push_back(vertex);\n    }\n\n    targetFile.open(filename, std::ios::out);\n\n    if (targetFile.is_open())\n    {\n\n        for (treeVertex &vertex : leaves)\n        {\n            targetFile << this->getReversedOrderOfAncestors(tree, vertex) << \"\\n\";\n        }\n    }\n}\n\nstd::string Phylogeny::getReversedOrderOfAncestors(std::vector<treeVertex> &tree, treeVertex &vertex)\n{\n    std::vector<std::string> sequences;\n\n    int nextVertex = vertex.id;\n    ProteinSequence sequence;\n    std::vector<std::string> stringVector;\n    while (nextVertex >= 0)\n    {\n        sequence = tree[nextVertex].sequence;\n\n        stringVector.push_back(sequence.baseVec2String());\n\n        nextVertex = tree[nextVertex].root;\n    }\n\n    std::string output;\n\n    for (int i = stringVector.size() - 1; i >= 0; i--)\n    {\n        output += stringVector[i] + \",\";\n    }\n    output += std::to_string(vertex.depth);\n    return output;\n}\nvoid Phylogeny::printTree(std::vector<treeVertex> &tree)\n{\n    treeVertex maxDepthVertex = *std::max_element(tree.begin(), tree.end(), [](treeVertex &a, treeVertex &b) { return a.depth < b.depth; });\n    for (int depth = 0; depth <= maxDepthVertex.depth; depth++)\n    {\n\n        for (treeVertex &vertex : tree)\n        {\n            if (vertex.depth == depth)\n            {\n                std::cout << vertex.sequence.baseVec2String() << \" (d=\" << vertex.timeDepth << \"|id=\" << vertex.id << \"|r=\" << vertex.root << \")   \";\n            }\n        }\n        std::cout << '\\n'\n                  << '\\n';\n    }\n}\n\nstd::vector<treeVertex> Phylogeny::reversePhylogeny(const std::string &filename)\n{\n    std::ifstream inputStream;\n    inputStream.open(filename);\n    std::vector<treeVertex> tree;\n\n    if (inputStream.is_open())\n    {\n        std::vector<std::vector<std::string>> readTree;\n        // read to map\n        std::string line;\n        std::vector<std::string> lineSplitted;\n        int maxLength = 0;\n        do\n        {\n            std::getline(inputStream, line);\n            boost::split(lineSplitted, line, boost::is_any_of(\",\"));\n            if (lineSplitted.back() != \"\")\n            {\n                int length = std::stoi(lineSplitted.back()) + 1;\n                if (length > maxLength)\n                    maxLength = length;\n            }\n            lineSplitted.pop_back();\n            readTree.push_back(lineSplitted);\n            lineSplitted.clear();\n\n        } while (!inputStream.eof());\n        readTree.pop_back();\n        // set root\n\n        treeVertex rootVertex;\n        rootVertex.sequence = ProteinSequence(readTree[0][0]);\n        rootVertex.id = 0;\n        rootVertex.root = -1;\n        rootVertex.depth = 0;\n\n        tree.push_back(rootVertex);\n\n        for (int i = 1; i < maxLength; i++)\n        {\n            for (std::vector<std::string> &stringVec : readTree)\n            {\n\n                for (int epoch = 1; epoch <= i && epoch < stringVec.size(); epoch++)\n                {\n                    std::string sequence = stringVec[epoch];\n                    std::string ancestor = stringVec[epoch - 1];\n                    std::vector<int> possibleAncestors;\n                    for (int i = 0; i < tree.size(); i++)\n                    {\n                        if (tree[i].sequence.baseVec2String() == ancestor && tree[i].depth == epoch - 1)\n                            possibleAncestors.push_back(i);\n                    }\n                    for (int vertex : possibleAncestors) // possible immediate ancestors, now we need to find way to the root\n                    {\n                        bool goodWay = true;\n                        int iter = 1;\n                        int nextVertex = vertex;\n                        while (goodWay && tree[nextVertex].root != -1 && epoch > iter)\n                        {\n                            if (tree[nextVertex].sequence.baseVec2String() != stringVec[epoch - iter])\n                            {\n                                goodWay = false;\n                                break;\n                            }\n                            iter++;\n                            nextVertex = tree[nextVertex].root;\n                        }\n                        if (!goodWay)\n                            continue;\n                        else\n                        {\n                            treeVertex newVertex;\n                            newVertex.sequence = ProteinSequence(sequence);\n                            newVertex.id = tree.size();\n                            newVertex.root = tree[vertex].id;\n                            newVertex.depth = epoch;\n\n                            ancestor = tree[vertex].sequence.baseVec2String();\n                            if (sequence == ancestor) //left child (no left child present)\n                            {\n                                if (tree[vertex].left == 0)\n                                {\n                                    tree.push_back(newVertex);\n                                    tree[vertex].left = newVertex.id;\n                                }\n                                else\n                                {\n                                    break;\n                                }\n                            }\n                            else if (tree[vertex].right == 0) //right child\n                            {\n                                tree.push_back(newVertex);\n                                tree[vertex].right = newVertex.id;\n                            }\n\n                            break;\n                        }\n                    }\n                }\n            }\n        }\n    }\n    return tree;\n}", "meta": {"hexsha": "763c07b4398220245c1ff96a3de5492be1e42a80", "size": 8886, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sources/Phylogeny.cpp", "max_stars_repo_name": "Mitrius/Bioinf_DNA_Evolution", "max_stars_repo_head_hexsha": "0e95797ec5676aa5bf7a37c6a4498bba915c076a", "max_stars_repo_licenses": ["MIT"], "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/Phylogeny.cpp", "max_issues_repo_name": "Mitrius/Bioinf_DNA_Evolution", "max_issues_repo_head_hexsha": "0e95797ec5676aa5bf7a37c6a4498bba915c076a", "max_issues_repo_licenses": ["MIT"], "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/Phylogeny.cpp", "max_forks_repo_name": "Mitrius/Bioinf_DNA_Evolution", "max_forks_repo_head_hexsha": "0e95797ec5676aa5bf7a37c6a4498bba915c076a", "max_forks_repo_licenses": ["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.6691176471, "max_line_length": 149, "alphanum_fraction": 0.509790682, "num_tokens": 1912, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.45260251409330027}}
{"text": "#define BOOST_TEST_MODULE \"test_3spn2_bond_potential\"\n\n#ifdef BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n#else\n#include <boost/test/included/unit_test.hpp>\n#endif\n\n#include <mjolnir/forcefield/3SPN2/ThreeSPN2BondPotential.hpp>\n\nBOOST_AUTO_TEST_CASE(potential_3spn2_bond_double)\n{\n    using real_type = double;\n    constexpr std::size_t N = 1000;\n    constexpr real_type   h = 1e-6;\n\n    const real_type k  = 1.0;\n    const real_type r0 = 5.0;\n\n    mjolnir::ThreeSPN2BondPotential<real_type> potential(k, r0);\n\n    const real_type x_min = 0.5 * r0;\n    const real_type x_max = 1.5 * r0;\n    const real_type dx = (x_max - x_min) / N;\n\n    for(std::size_t i=0; i<N; ++i)\n    {\n        const real_type x    = x_min + i * dx;\n        const real_type pot1 = potential.potential(x + h);\n        const real_type pot2 = potential.potential(x - h);\n        const real_type dpot = (pot1 - pot2) / (2 * h);\n        const real_type deri = potential.derivative(x);\n\n        if(std::abs(pot1 / pot2 - 1.0) < h)\n        {\n            // pot1 and pot2 are almost the same, thus dpot ~ 0.0.\n            // to avoid numerical error in dpot, here it checks `deri ~ 0.0`.\n            BOOST_TEST(deri == 0.0, boost::test_tools::tolerance(h));\n        }\n        else\n        {\n            BOOST_TEST(dpot == deri, boost::test_tools::tolerance(h));\n        }\n    }\n}\n\nBOOST_AUTO_TEST_CASE(potential_3spn2_bond_float)\n{\n    using real_type = float;\n    constexpr std::size_t N = 100;\n    constexpr real_type   h = 1e-3f;\n\n    const real_type k  = 1.0f;\n    const real_type r0 = 5.0f;\n\n    mjolnir::ThreeSPN2BondPotential<real_type> potential(k, r0);\n\n    const real_type x_min = 0.5 * r0;\n    const real_type x_max = 1.5 * r0;\n    const real_type dx = (x_max - x_min) / N;\n\n    for(std::size_t i=0; i<N; ++i)\n    {\n        const real_type x    = x_min + i * dx;\n        const real_type pot1 = potential.potential(x + h);\n        const real_type pot2 = potential.potential(x - h);\n        const real_type dpot = (pot1 - pot2) / (2 * h);\n        const real_type deri = potential.derivative(x);\n\n        if(std::abs(pot1 / pot2 - 1.0f) < h)\n        {\n            // pot1 and pot2 are almost the same, thus dpot ~ 0.0.\n            // to avoid numerical error in dpot, here it checks `deri ~ 0.0`.\n            BOOST_TEST(deri == 0.0f, boost::test_tools::tolerance(h));\n        }\n        else\n        {\n            BOOST_TEST(dpot == deri, boost::test_tools::tolerance(h));\n        }\n    }\n}\n", "meta": {"hexsha": "7420ab4c160e2fba67e1ccbb1eaa072cbf35aa45", "size": 2474, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/core/test_3spn2_bond_potential.cpp", "max_stars_repo_name": "yutakasi634/Mjolnir", "max_stars_repo_head_hexsha": "ab7a29a47f994111e8b889311c44487463f02116", "max_stars_repo_licenses": ["MIT"], "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/core/test_3spn2_bond_potential.cpp", "max_issues_repo_name": "yutakasi634/Mjolnir", "max_issues_repo_head_hexsha": "ab7a29a47f994111e8b889311c44487463f02116", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-07T11:41:45.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-08T10:01:38.000Z", "max_forks_repo_path": "test/core/test_3spn2_bond_potential.cpp", "max_forks_repo_name": "yutakasi634/Mjolnir", "max_forks_repo_head_hexsha": "ab7a29a47f994111e8b889311c44487463f02116", "max_forks_repo_licenses": ["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.1707317073, "max_line_length": 77, "alphanum_fraction": 0.5994341148, "num_tokens": 778, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952052, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.4525875010353015}}
{"text": "//  Copyright John Maddock 2006.\n//  Copyright Paul A. Bristow 2007, 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#ifndef BOOST_LIBS_MATH_TEST_INSTANTIATE_HPP\n#define BOOST_LIBS_MATH_TEST_INSTANTIATE_HPP\n\n#ifndef BOOST_MATH_ASSERT_UNDEFINED_POLICY\n#  define BOOST_MATH_ASSERT_UNDEFINED_POLICY false\n#endif\n\n#include <boost/math/distributions.hpp>\n\n#include <boost/math/special_functions.hpp>\n#include <boost/math/concepts/distributions.hpp>\n#include <boost/concept_archetype.hpp>\n\n#ifndef BOOST_MATH_INSTANTIATE_MINIMUM\n\ntypedef boost::math::policies::policy<boost::math::policies::promote_float<false>, boost::math::policies::promote_double<false> > test_policy;\n\nnamespace test{\n\nBOOST_MATH_DECLARE_SPECIAL_FUNCTIONS(test_policy)\n\n}\n\nnamespace dist_test{\n\nBOOST_MATH_DECLARE_DISTRIBUTIONS(double, test_policy)\n\n}\n#endif\n\n#if !defined(TEST_GROUP_1) && !defined(TEST_GROUP_2) && !defined(TEST_GROUP_3) \\\n   && !defined(TEST_GROUP_4) && !defined(TEST_GROUP_5) && !defined(TEST_GROUP_6) \\\n   && !defined(TEST_GROUP_7) && !defined(TEST_GROUP_8) && !defined(TEST_GROUP_9)\n#  define TEST_GROUP_1\n#  define TEST_GROUP_2\n#  define TEST_GROUP_3\n#  define TEST_GROUP_4\n#  define TEST_GROUP_5\n#  define TEST_GROUP_6\n#  define TEST_GROUP_7\n#  define TEST_GROUP_8\n#  define TEST_GROUP_9\n#endif\n\ntemplate <class RealType>\nvoid instantiate(RealType)\n{\n   using namespace boost;\n   using namespace boost::math;\n   using namespace boost::math::concepts;\n#ifdef TEST_GROUP_1\n   function_requires<DistributionConcept<arcsine_distribution<RealType> > >();\n   function_requires<DistributionConcept<bernoulli_distribution<RealType> > >();\n   function_requires<DistributionConcept<beta_distribution<RealType> > >();\n   function_requires<DistributionConcept<binomial_distribution<RealType> > >();\n   function_requires<DistributionConcept<cauchy_distribution<RealType> > >();\n   function_requires<DistributionConcept<chi_squared_distribution<RealType> > >();\n   function_requires<DistributionConcept<exponential_distribution<RealType> > >();\n   function_requires<DistributionConcept<extreme_value_distribution<RealType> > >();\n   function_requires<DistributionConcept<fisher_f_distribution<RealType> > >();\n   function_requires<DistributionConcept<gamma_distribution<RealType> > >();\n   function_requires<DistributionConcept<geometric_distribution<RealType> > >();\n   function_requires<DistributionConcept<hypergeometric_distribution<RealType> > >();\n   function_requires<DistributionConcept<hyperexponential_distribution<RealType> > >();\n   function_requires<DistributionConcept<inverse_chi_squared_distribution<RealType> > >();\n   function_requires<DistributionConcept<inverse_gamma_distribution<RealType> > >();\n   function_requires<DistributionConcept<inverse_gaussian_distribution<RealType> > >();\n   function_requires<DistributionConcept<laplace_distribution<RealType> > >();\n   function_requires<DistributionConcept<logistic_distribution<RealType> > >();\n   function_requires<DistributionConcept<lognormal_distribution<RealType> > >();\n   function_requires<DistributionConcept<negative_binomial_distribution<RealType> > >();\n   function_requires<DistributionConcept<non_central_chi_squared_distribution<RealType> > >();\n   function_requires<DistributionConcept<non_central_beta_distribution<RealType> > >();\n   function_requires<DistributionConcept<non_central_f_distribution<RealType> > >();\n   function_requires<DistributionConcept<non_central_t_distribution<RealType> > >();\n   function_requires<DistributionConcept<normal_distribution<RealType> > >();\n   function_requires<DistributionConcept<pareto_distribution<RealType> > >();\n   function_requires<DistributionConcept<poisson_distribution<RealType> > >();\n   function_requires<DistributionConcept<rayleigh_distribution<RealType> > >();\n   function_requires<DistributionConcept<students_t_distribution<RealType> > >();\n   function_requires<DistributionConcept<skew_normal_distribution<RealType> > >();\n   function_requires<DistributionConcept<triangular_distribution<RealType> > >();\n   function_requires<DistributionConcept<uniform_distribution<RealType> > >();\n   function_requires<DistributionConcept<weibull_distribution<RealType> > >();\n#endif\n#ifndef BOOST_MATH_INSTANTIATE_MINIMUM\n#ifdef TEST_GROUP_2\n   function_requires<DistributionConcept<arcsine_distribution<RealType> > >();\n   function_requires<DistributionConcept<bernoulli_distribution<RealType, test_policy> > >();\n   function_requires<DistributionConcept<beta_distribution<RealType, test_policy> > >();\n   function_requires<DistributionConcept<binomial_distribution<RealType, test_policy> > >();\n   function_requires<DistributionConcept<cauchy_distribution<RealType, test_policy> > >();\n   function_requires<DistributionConcept<chi_squared_distribution<RealType, test_policy> > >();\n   function_requires<DistributionConcept<exponential_distribution<RealType, test_policy> > >();\n   function_requires<DistributionConcept<extreme_value_distribution<RealType, test_policy> > >();\n   function_requires<DistributionConcept<fisher_f_distribution<RealType, test_policy> > >();\n   function_requires<DistributionConcept<gamma_distribution<RealType, test_policy> > >();\n   function_requires<DistributionConcept<geometric_distribution<RealType, test_policy> > >();\n   function_requires<DistributionConcept<hypergeometric_distribution<RealType, test_policy> > >();\n   function_requires<DistributionConcept<inverse_chi_squared_distribution<RealType, test_policy> > >();\n   function_requires<DistributionConcept<inverse_gamma_distribution<RealType, test_policy> > >();\n   function_requires<DistributionConcept<inverse_gaussian_distribution<RealType, test_policy> > >();\n   function_requires<DistributionConcept<laplace_distribution<RealType, test_policy> > >();\n   function_requires<DistributionConcept<logistic_distribution<RealType, test_policy> > >();\n   function_requires<DistributionConcept<lognormal_distribution<RealType, test_policy> > >();\n   function_requires<DistributionConcept<negative_binomial_distribution<RealType, test_policy> > >();\n   function_requires<DistributionConcept<non_central_chi_squared_distribution<RealType, test_policy> > >();\n   function_requires<DistributionConcept<non_central_beta_distribution<RealType, test_policy> > >();\n   function_requires<DistributionConcept<non_central_f_distribution<RealType, test_policy> > >();\n   function_requires<DistributionConcept<non_central_t_distribution<RealType, test_policy> > >();\n   function_requires<DistributionConcept<normal_distribution<RealType, test_policy> > >();\n   function_requires<DistributionConcept<pareto_distribution<RealType, test_policy> > >();\n   function_requires<DistributionConcept<poisson_distribution<RealType, test_policy> > >();\n   function_requires<DistributionConcept<rayleigh_distribution<RealType, test_policy> > >();\n   function_requires<DistributionConcept<skew_normal_distribution<RealType, test_policy> > >();\n   function_requires<DistributionConcept<students_t_distribution<RealType, test_policy> > >();\n   function_requires<DistributionConcept<triangular_distribution<RealType, test_policy> > >();\n   function_requires<DistributionConcept<uniform_distribution<RealType, test_policy> > >();\n   function_requires<DistributionConcept<weibull_distribution<RealType, test_policy> > >();\n#endif\n#ifdef TEST_GROUP_3\n   function_requires<DistributionConcept<dist_test::arcsine > >();\n   function_requires<DistributionConcept<dist_test::bernoulli > >();\n   function_requires<DistributionConcept<dist_test::beta > >();\n   function_requires<DistributionConcept<dist_test::binomial > >();\n   function_requires<DistributionConcept<dist_test::cauchy > >();\n   function_requires<DistributionConcept<dist_test::chi_squared > >();\n   function_requires<DistributionConcept<dist_test::exponential > >();\n   function_requires<DistributionConcept<dist_test::extreme_value > >();\n   function_requires<DistributionConcept<dist_test::fisher_f > >();\n   function_requires<DistributionConcept<dist_test::gamma > >();\n   function_requires<DistributionConcept<dist_test::geometric > >();\n   function_requires<DistributionConcept<dist_test::hypergeometric > >();\n   function_requires<DistributionConcept<dist_test::inverse_chi_squared > >();\n   function_requires<DistributionConcept<dist_test::inverse_gamma > >();\n   function_requires<DistributionConcept<dist_test::inverse_gaussian > >();\n   function_requires<DistributionConcept<dist_test::laplace > >();\n   function_requires<DistributionConcept<dist_test::logistic > >();\n   function_requires<DistributionConcept<dist_test::lognormal > >();\n   function_requires<DistributionConcept<dist_test::negative_binomial > >();\n   function_requires<DistributionConcept<dist_test::non_central_chi_squared > >();\n   function_requires<DistributionConcept<dist_test::non_central_beta > >();\n   function_requires<DistributionConcept<dist_test::non_central_f > >();\n   function_requires<DistributionConcept<dist_test::non_central_t > >();\n   function_requires<DistributionConcept<dist_test::normal > >();\n   function_requires<DistributionConcept<dist_test::pareto > >();\n   function_requires<DistributionConcept<dist_test::poisson > >();\n   function_requires<DistributionConcept<dist_test::rayleigh > >();\n   function_requires<DistributionConcept<dist_test::students_t > >();\n   function_requires<DistributionConcept<dist_test::triangular > >();\n   function_requires<DistributionConcept<dist_test::uniform > >();\n   function_requires<DistributionConcept<dist_test::weibull > >();\n   function_requires<DistributionConcept<dist_test::hypergeometric > >();\n#endif\n#endif\n   int i = 1;\n   // Deal with unused variable warnings:\n   (void)i;\n   RealType v1(0.5), v2(0.5), v3(0.5);\n   boost::detail::dummy_constructor dc;\n   boost::output_iterator_archetype<RealType> oi(dc);\n#ifdef TEST_GROUP_4\n   boost::math::tgamma(v1);\n   boost::math::tgamma1pm1(v1);\n   boost::math::lgamma(v1);\n   boost::math::lgamma(v1, &i);\n   boost::math::digamma(v1);\n   boost::math::trigamma(v1);\n   boost::math::polygamma(i, v1);\n   boost::math::tgamma_ratio(v1, v2);\n   boost::math::tgamma_delta_ratio(v1, v2);\n   boost::math::factorial<RealType>(i);\n   boost::math::unchecked_factorial<RealType>(i);\n   i = boost::math::max_factorial<RealType>::value;\n   boost::math::double_factorial<RealType>(i);\n   boost::math::rising_factorial(v1, i);\n   boost::math::falling_factorial(v1, i);\n   boost::math::tgamma(v1, v2);\n   boost::math::tgamma_lower(v1, v2);\n   boost::math::gamma_p(v1, v2);\n   boost::math::gamma_q(v1, v2);\n   boost::math::gamma_p_inv(v1, v2);\n   boost::math::gamma_q_inv(v1, v2);\n   boost::math::gamma_p_inva(v1, v2);\n   boost::math::gamma_q_inva(v1, v2);\n   boost::math::erf(v1);\n   boost::math::erfc(v1);\n   boost::math::erf_inv(v1);\n   boost::math::erfc_inv(v1);\n   boost::math::beta(v1, v2);\n   boost::math::beta(v1, v2, v3);\n   boost::math::betac(v1, v2, v3);\n   boost::math::ibeta(v1, v2, v3);\n   boost::math::ibetac(v1, v2, v3);\n   boost::math::ibeta_inv(v1, v2, v3);\n   boost::math::ibetac_inv(v1, v2, v3);\n   boost::math::ibeta_inva(v1, v2, v3);\n   boost::math::ibetac_inva(v1, v2, v3);\n   boost::math::ibeta_invb(v1, v2, v3);\n   boost::math::ibetac_invb(v1, v2, v3);\n   boost::math::gamma_p_derivative(v2, v3);\n   boost::math::ibeta_derivative(v1, v2, v3);\n   boost::math::binomial_coefficient<RealType>(i, i);\n   (boost::math::fpclassify)(v1);\n   (boost::math::isfinite)(v1);\n   (boost::math::isnormal)(v1);\n   (boost::math::isnan)(v1);\n   (boost::math::isinf)(v1);\n   (boost::math::signbit)(v1);\n   (boost::math::copysign)(v1, v2);\n   (boost::math::changesign)(v1);\n   (boost::math::sign)(v1);\n   boost::math::log1p(v1);\n   boost::math::expm1(v1);\n   boost::math::cbrt(v1);\n   boost::math::sqrt1pm1(v1);\n   boost::math::powm1(v1, v2);\n   boost::math::legendre_p(1, v1);\n   boost::math::legendre_p(1, 0, v1);\n   boost::math::legendre_q(1, v1);\n   boost::math::legendre_p_prime(1, v1);\n   boost::math::legendre_next(2, v1, v2, v3);\n   boost::math::legendre_next(2, 2, v1, v2, v3);\n   boost::math::laguerre(1, v1);\n   boost::math::laguerre(2, 1, v1);\n   boost::math::laguerre(2u, 1u, v1);\n   boost::math::laguerre_next(2, v1, v2, v3);\n   boost::math::laguerre_next(2, 1, v1, v2, v3);\n   boost::math::hermite(1, v1);\n   boost::math::hermite_next(2, v1, v2, v3);\n   boost::math::spherical_harmonic_r(2, 1, v1, v2);\n   boost::math::spherical_harmonic_i(2, 1, v1, v2);\n   boost::math::ellint_1(v1);\n   boost::math::ellint_1(v1, v2);\n   boost::math::ellint_2(v1);\n   boost::math::ellint_2(v1, v2);\n   boost::math::ellint_3(v1, v2);\n   boost::math::ellint_3(v1, v2, v3);\n   boost::math::ellint_d(v1);\n   boost::math::ellint_d(v1, v2);\n   boost::math::jacobi_zeta(v1, v2);\n   boost::math::heuman_lambda(v1, v2);\n   boost::math::ellint_rc(v1, v2);\n   boost::math::ellint_rd(v1, v2, v3);\n   boost::math::ellint_rf(v1, v2, v3);\n   boost::math::ellint_rg(v1, v2, v3);\n   boost::math::ellint_rj(v1, v2, v3, v1);\n   boost::math::jacobi_elliptic(v1, v2, &v1, &v2);\n   boost::math::jacobi_cd(v1, v2);\n   boost::math::jacobi_cn(v1, v2);\n   boost::math::jacobi_cs(v1, v2);\n   boost::math::jacobi_dc(v1, v2);\n   boost::math::jacobi_dn(v1, v2);\n   boost::math::jacobi_ds(v1, v2);\n   boost::math::jacobi_nc(v1, v2);\n   boost::math::jacobi_nd(v1, v2);\n   boost::math::jacobi_ns(v1, v2);\n   boost::math::jacobi_sc(v1, v2);\n   boost::math::jacobi_sd(v1, v2);\n   boost::math::jacobi_sn(v1, v2);\n   boost::math::hypot(v1, v2);\n   boost::math::sinc_pi(v1);\n   boost::math::sinhc_pi(v1);\n   boost::math::asinh(v1);\n   boost::math::acosh(v1);\n   boost::math::atanh(v1);\n   boost::math::sin_pi(v1);\n   boost::math::cos_pi(v1);\n   boost::math::cyl_neumann(v1, v2);\n   boost::math::cyl_neumann(i, v2);\n   boost::math::cyl_bessel_j(v1, v2);\n   boost::math::cyl_bessel_j(i, v2);\n   boost::math::cyl_bessel_i(v1, v2);\n   boost::math::cyl_bessel_i(i, v2);\n   boost::math::cyl_bessel_k(v1, v2);\n   boost::math::cyl_bessel_k(i, v2);\n   boost::math::sph_bessel(i, v2);\n   boost::math::sph_bessel(i, 1);\n   boost::math::sph_neumann(i, v2);\n   boost::math::sph_neumann(i, i);\n   boost::math::cyl_neumann_prime(v1, v2);\n   boost::math::cyl_neumann_prime(i, v2);\n   boost::math::cyl_bessel_j_prime(v1, v2);\n   boost::math::cyl_bessel_j_prime(i, v2);\n   boost::math::cyl_bessel_i_prime(v1, v2);\n   boost::math::cyl_bessel_i_prime(i, v2);\n   boost::math::cyl_bessel_k_prime(v1, v2);\n   boost::math::cyl_bessel_k_prime(i, v2);\n   boost::math::sph_bessel_prime(i, v2);\n   boost::math::sph_bessel_prime(i, 1);\n   boost::math::sph_neumann_prime(i, v2);\n   boost::math::sph_neumann_prime(i, i);\n   boost::math::cyl_bessel_j_zero(v1, i);\n   boost::math::cyl_bessel_j_zero(v1, i, i, oi);\n   boost::math::cyl_neumann_zero(v1, i);\n   boost::math::cyl_neumann_zero(v1, i, i, oi);\n#ifdef TEST_COMPLEX\n   boost::math::cyl_hankel_1(v1, v2);\n   boost::math::cyl_hankel_1(i, v2);\n   boost::math::cyl_hankel_2(v1, v2);\n   boost::math::cyl_hankel_2(i, v2);\n   boost::math::sph_hankel_1(v1, v2);\n   boost::math::sph_hankel_1(i, v2);\n   boost::math::sph_hankel_2(v1, v2);\n   boost::math::sph_hankel_2(i, v2);\n#endif\n   boost::math::airy_ai(v1);\n   boost::math::airy_bi(v1);\n   boost::math::airy_ai_prime(v1);\n   boost::math::airy_bi_prime(v1);\n\n   boost::math::airy_ai_zero<RealType>(i);\n   boost::math::airy_bi_zero<RealType>(i);\n   boost::math::airy_ai_zero<RealType>(i, i, oi);\n   boost::math::airy_bi_zero<RealType>(i, i, oi);\n\n   boost::math::expint(v1);\n   boost::math::expint(i);\n   boost::math::expint(i, v2);\n   boost::math::expint(i, i);\n   boost::math::zeta(v1);\n   boost::math::zeta(i);\n   boost::math::owens_t(v1, v2);\n   boost::math::trunc(v1);\n   boost::math::itrunc(v1);\n   boost::math::ltrunc(v1);\n   boost::math::round(v1);\n   boost::math::iround(v1);\n   boost::math::lround(v1);\n   boost::math::modf(v1, &v1);\n   boost::math::modf(v1, &i);\n   long l;\n   boost::math::modf(v1, &l);\n#ifdef BOOST_HAS_LONG_LONG\n   boost::math::lltrunc(v1);\n   boost::math::llround(v1);\n   boost::long_long_type ll;\n   boost::math::modf(v1, &ll);\n#endif\n   boost::math::pow<2>(v1);\n   boost::math::nextafter(v1, v1);\n   boost::math::float_next(v1);\n   boost::math::float_prior(v1);\n   boost::math::float_distance(v1, v1);\n   boost::math::ulp(v1);\n   boost::math::relative_difference(v1, v2);\n   boost::math::epsilon_difference(v1, v2);\n\n   boost::math::unchecked_bernoulli_b2n<RealType>(i);\n   boost::math::bernoulli_b2n<RealType>(i);\n   boost::math::bernoulli_b2n<RealType>(i, i, &v1);\n   boost::math::tangent_t2n<RealType>(i);\n   boost::math::tangent_t2n<RealType>(i, i, &v1);\n\n#endif\n#ifdef TEST_GROUP_9\n   //\n   // Over again, but arguments may be expression templates:\n   //\n   boost::math::tgamma(v1 + 0);\n   boost::math::tgamma1pm1(v1 + 0);\n   boost::math::lgamma(v1 * 1);\n   boost::math::lgamma(v1 * 1, &i);\n   boost::math::digamma(v1 * 1);\n   boost::math::trigamma(v1 * 1);\n   boost::math::polygamma(i, v1 * 1);\n   boost::math::tgamma_ratio(v1 * 1, v2 + 0);\n   boost::math::tgamma_delta_ratio(v1 * 1, v2 + 0);\n   boost::math::factorial<RealType>(i);\n   boost::math::unchecked_factorial<RealType>(i);\n   i = boost::math::max_factorial<RealType>::value;\n   boost::math::double_factorial<RealType>(i);\n   boost::math::rising_factorial(v1 * 1, i);\n   boost::math::falling_factorial(v1 * 1, i);\n   boost::math::tgamma(v1 * 1, v2 + 0);\n   boost::math::tgamma_lower(v1 * 1, v2 - 0);\n   boost::math::gamma_p(v1 * 1, v2 + 0);\n   boost::math::gamma_q(v1 * 1, v2 + 0);\n   boost::math::gamma_p_inv(v1 * 1, v2 + 0);\n   boost::math::gamma_q_inv(v1 * 1, v2 + 0);\n   boost::math::gamma_p_inva(v1 * 1, v2 + 0);\n   boost::math::gamma_q_inva(v1 * 1, v2 + 0);\n   boost::math::erf(v1 * 1);\n   boost::math::erfc(v1 * 1);\n   boost::math::erf_inv(v1 * 1);\n   boost::math::erfc_inv(v1 * 1);\n   boost::math::beta(v1 * 1, v2 + 0);\n   boost::math::beta(v1 * 1, v2 + 0, v3 / 1);\n   boost::math::betac(v1 * 1, v2 + 0, v3 / 1);\n   boost::math::ibeta(v1 * 1, v2 + 0, v3 / 1);\n   boost::math::ibetac(v1 * 1, v2 + 0, v3 / 1);\n   boost::math::ibeta_inv(v1 * 1, v2 + 0, v3 / 1);\n   boost::math::ibetac_inv(v1 * 1, v2 + 0, v3 / 1);\n   boost::math::ibeta_inva(v1 * 1, v2 + 0, v3 / 1);\n   boost::math::ibetac_inva(v1 * 1, v2 + 0, v3 / 1);\n   boost::math::ibeta_invb(v1 * 1, v2 + 0, v3 / 1);\n   boost::math::ibetac_invb(v1 * 1, v2 + 0, v3 / 1);\n   boost::math::gamma_p_derivative(v2 * 1, v3 + 0);\n   boost::math::ibeta_derivative(v1 * 1, v2 + 0, v3 / 1);\n   (boost::math::fpclassify)(v1 * 1);\n   (boost::math::isfinite)(v1 * 1);\n   (boost::math::isnormal)(v1 * 1);\n   (boost::math::isnan)(v1 * 1);\n   (boost::math::isinf)(v1 * 1);\n   (boost::math::signbit)(v1 * 1);\n   (boost::math::copysign)(v1 * 1, v2 + 0);\n   (boost::math::changesign)(v1 * 1);\n   (boost::math::sign)(v1 * 1);\n   boost::math::log1p(v1 * 1);\n   boost::math::expm1(v1 * 1);\n   boost::math::cbrt(v1 * 1);\n   boost::math::sqrt1pm1(v1 * 1);\n   boost::math::powm1(v1 * 1, v2 + 0);\n   boost::math::legendre_p(1, v1 * 1);\n   boost::math::legendre_p(1, 0, v1 * 1);\n   boost::math::legendre_p_prime(1, v1 * 1);\n   boost::math::legendre_q(1, v1 * 1);\n   boost::math::legendre_next(2, v1 * 1, v2 + 0, v3 / 1);\n   boost::math::legendre_next(2, 2, v1 * 1, v2 + 0, v3 / 1);\n   boost::math::laguerre(1, v1 * 1);\n   boost::math::laguerre(2, 1, v1 * 1);\n   boost::math::laguerre(2u, 1u, v1 * 1);\n   boost::math::laguerre_next(2, v1 * 1, v2 + 0, v3 / 1);\n   boost::math::laguerre_next(2, 1, v1 * 1, v2 + 0, v3 / 1);\n   boost::math::hermite(1, v1 * 1);\n   boost::math::hermite_next(2, v1 * 1, v2 + 0, v3 / 1);\n   boost::math::spherical_harmonic_r(2, 1, v1 * 1, v2 + 0);\n   boost::math::spherical_harmonic_i(2, 1, v1 * 1, v2 + 0);\n   boost::math::ellint_1(v1 * 1);\n   boost::math::ellint_1(v1 * 1, v2 + 0);\n   boost::math::ellint_2(v1 * 1);\n   boost::math::ellint_2(v1 * 1, v2 + 0);\n   boost::math::ellint_3(v1 * 1, v2 + 0);\n   boost::math::ellint_3(v1 * 1, v2 + 0, v3 / 1);\n   boost::math::ellint_rc(v1 * 1, v2 + 0);\n   boost::math::ellint_rd(v1 * 1, v2 + 0, v3 / 1);\n   boost::math::ellint_rf(v1 * 1, v2 + 0, v3 / 1);\n   boost::math::ellint_rg(v1 * 1, v2 + 0, v3 / 1);\n   boost::math::ellint_rj(v1 * 1, v2 + 0, v3 / 1, v1 * 1);\n   boost::math::ellint_d(v1 * 1);\n   boost::math::ellint_d(v1 * 1, v2 + 0);\n   boost::math::jacobi_zeta(v1 * 1, v2 + 0);\n   boost::math::heuman_lambda(v1 * 1, v2 + 0);\n   boost::math::jacobi_elliptic(v1 * 1, v2 + 0, &v1, &v2);\n   boost::math::jacobi_cd(v1 * 1, v2 + 0);\n   boost::math::jacobi_cn(v1 * 1, v2 + 0);\n   boost::math::jacobi_cs(v1 * 1, v2 + 0);\n   boost::math::jacobi_dc(v1 * 1, v2 + 0);\n   boost::math::jacobi_dn(v1 * 1, v2 + 0);\n   boost::math::jacobi_ds(v1 * 1, v2 + 0);\n   boost::math::jacobi_nc(v1 * 1, v2 + 0);\n   boost::math::jacobi_nd(v1 * 1, v2 + 0);\n   boost::math::jacobi_ns(v1 * 1, v2 + 0);\n   boost::math::jacobi_sc(v1 * 1, v2 + 0);\n   boost::math::jacobi_sd(v1 * 1, v2 + 0);\n   boost::math::jacobi_sn(v1 * 1, v2 + 0);\n   boost::math::hypot(v1 * 1, v2 + 0);\n   boost::math::sinc_pi(v1 * 1);\n   boost::math::sinhc_pi(v1 * 1);\n   boost::math::asinh(v1 * 1);\n   boost::math::acosh(v1 * 1);\n   boost::math::atanh(v1 * 1);\n   boost::math::sin_pi(v1 * 1);\n   boost::math::cos_pi(v1 * 1);\n   boost::math::cyl_neumann(v1 * 1, v2 + 0);\n   boost::math::cyl_neumann(i, v2 * 1);\n   boost::math::cyl_bessel_j(v1 * 1, v2 + 0);\n   boost::math::cyl_bessel_j(i, v2 * 1);\n   boost::math::cyl_bessel_i(v1 * 1, v2 + 0);\n   boost::math::cyl_bessel_i(i, v2 * 1);\n   boost::math::cyl_bessel_k(v1 * 1, v2 + 0);\n   boost::math::cyl_bessel_k(i, v2 * 1);\n   boost::math::sph_bessel(i, v2 * 1);\n   boost::math::sph_bessel(i, 1);\n   boost::math::sph_neumann(i, v2 * 1);\n   boost::math::sph_neumann(i, i);\n   boost::math::cyl_neumann_prime(v1 * 1, v2 + 0);\n   boost::math::cyl_neumann_prime(i, v2 * 1);\n   boost::math::cyl_bessel_j_prime(v1 * 1, v2 + 0);\n   boost::math::cyl_bessel_j_prime(i, v2 * 1);\n   boost::math::cyl_bessel_i_prime(v1 * 1, v2 + 0);\n   boost::math::cyl_bessel_i_prime(i, v2 * 1);\n   boost::math::cyl_bessel_k_prime(v1 * 1, v2 + 0);\n   boost::math::cyl_bessel_k_prime(i, v2 * 1);\n   boost::math::sph_bessel_prime(i, v2 * 1);\n   boost::math::sph_bessel_prime(i, 1);\n   boost::math::sph_neumann_prime(i, v2 * 1);\n   boost::math::sph_neumann_prime(i, i);\n   boost::math::cyl_bessel_j_zero(v1 * 1, i);\n   boost::math::cyl_bessel_j_zero(v1 * 1, i, i, oi);\n   boost::math::cyl_neumann_zero(v1 * 1, i);\n   boost::math::cyl_neumann_zero(v1 * 1, i, i, oi);\n#ifdef TEST_COMPLEX\n   boost::math::cyl_hankel_1(v1, v2);\n   boost::math::cyl_hankel_1(i, v2);\n   boost::math::cyl_hankel_2(v1, v2);\n   boost::math::cyl_hankel_2(i, v2);\n   boost::math::sph_hankel_1(v1, v2);\n   boost::math::sph_hankel_1(i, v2);\n   boost::math::sph_hankel_2(v1, v2);\n   boost::math::sph_hankel_2(i, v2);\n#endif\n   boost::math::airy_ai(v1 * 1);\n   boost::math::airy_bi(v1 * 1);\n   boost::math::airy_ai_prime(v1 * 1);\n   boost::math::airy_bi_prime(v1 * 1);\n   boost::math::expint(v1 * 1);\n   boost::math::expint(i);\n   boost::math::expint(i, v2 * 1);\n   boost::math::expint(i, i);\n   boost::math::zeta(v1 * 1);\n   boost::math::zeta(i);\n   boost::math::owens_t(v1 * 1, v2 + 0);\n   boost::math::trunc(v1 * 1);\n   boost::math::itrunc(v1 * 1);\n   boost::math::ltrunc(v1 * 1);\n   boost::math::round(v1 * 1);\n   boost::math::iround(v1 * 1);\n   boost::math::lround(v1 * 1);\n   //boost::math::modf(v1 * 1, &v1);\n   //boost::math::modf(v1 * 1, &i);\n   //long l;\n   //boost::math::modf(v1 * 1, &l);\n#ifdef BOOST_HAS_LONG_LONG\n   boost::math::lltrunc(v1 * 1);\n   boost::math::llround(v1 * 1);\n   //boost::long_long_type ll;\n   //boost::math::modf(v1 * 1, &ll);\n#endif\n   boost::math::pow<2>(v1 * 1);\n   boost::math::nextafter(v1 * 1, v1 + 0);\n   boost::math::float_next(v1 * 1);\n   boost::math::float_prior(v1 * 1);\n   boost::math::float_distance(v1 * 1, v1 * 1);\n   boost::math::ulp(v1 * 1);\n   boost::math::relative_difference(v1 * 1, v2 * 1);\n   boost::math::epsilon_difference(v1 * 1, v2 * 1);\n#endif\n#ifndef BOOST_MATH_INSTANTIATE_MINIMUM\n#ifdef TEST_GROUP_5\n   //\n   // All over again, with a policy this time:\n   //\n   test_policy pol;\n   boost::math::tgamma(v1, pol);\n   boost::math::tgamma1pm1(v1, pol);\n   boost::math::lgamma(v1, pol);\n   boost::math::lgamma(v1, &i, pol);\n   boost::math::digamma(v1, pol);\n   boost::math::trigamma(v1, pol);\n   boost::math::polygamma(i, v1, pol);\n   boost::math::tgamma_ratio(v1, v2, pol);\n   boost::math::tgamma_delta_ratio(v1, v2, pol);\n   boost::math::factorial<RealType>(i, pol);\n   boost::math::unchecked_factorial<RealType>(i);\n   i = boost::math::max_factorial<RealType>::value;\n   boost::math::double_factorial<RealType>(i, pol);\n   boost::math::rising_factorial(v1, i, pol);\n   boost::math::falling_factorial(v1, i, pol);\n   boost::math::tgamma(v1, v2, pol);\n   boost::math::tgamma_lower(v1, v2, pol);\n   boost::math::gamma_p(v1, v2, pol);\n   boost::math::gamma_q(v1, v2, pol);\n   boost::math::gamma_p_inv(v1, v2, pol);\n   boost::math::gamma_q_inv(v1, v2, pol);\n   boost::math::gamma_p_inva(v1, v2, pol);\n   boost::math::gamma_q_inva(v1, v2, pol);\n   boost::math::erf(v1, pol);\n   boost::math::erfc(v1, pol);\n   boost::math::erf_inv(v1, pol);\n   boost::math::erfc_inv(v1, pol);\n   boost::math::beta(v1, v2, pol);\n   boost::math::beta(v1, v2, v3, pol);\n   boost::math::betac(v1, v2, v3, pol);\n   boost::math::ibeta(v1, v2, v3, pol);\n   boost::math::ibetac(v1, v2, v3, pol);\n   boost::math::ibeta_inv(v1, v2, v3, pol);\n   boost::math::ibetac_inv(v1, v2, v3, pol);\n   boost::math::ibeta_inva(v1, v2, v3, pol);\n   boost::math::ibetac_inva(v1, v2, v3, pol);\n   boost::math::ibeta_invb(v1, v2, v3, pol);\n   boost::math::ibetac_invb(v1, v2, v3, pol);\n   boost::math::gamma_p_derivative(v2, v3, pol);\n   boost::math::ibeta_derivative(v1, v2, v3, pol);\n   boost::math::binomial_coefficient<RealType>(i, i, pol);\n   boost::math::log1p(v1, pol);\n   boost::math::expm1(v1, pol);\n   boost::math::cbrt(v1, pol);\n   boost::math::sqrt1pm1(v1, pol);\n   boost::math::powm1(v1, v2, pol);\n   boost::math::legendre_p(1, v1, pol);\n   boost::math::legendre_p(1, 0, v1, pol);\n   boost::math::legendre_p_prime(1, v1 * 1, pol);\n   boost::math::legendre_q(1, v1, pol);\n   boost::math::legendre_next(2, v1, v2, v3);\n   boost::math::legendre_next(2, 2, v1, v2, v3);\n   boost::math::laguerre(1, v1, pol);\n   boost::math::laguerre(2, 1, v1, pol);\n   boost::math::laguerre_next(2, v1, v2, v3);\n   boost::math::laguerre_next(2, 1, v1, v2, v3);\n   boost::math::hermite(1, v1, pol);\n   boost::math::hermite_next(2, v1, v2, v3);\n   boost::math::spherical_harmonic_r(2, 1, v1, v2, pol);\n   boost::math::spherical_harmonic_i(2, 1, v1, v2, pol);\n   boost::math::ellint_1(v1, pol);\n   boost::math::ellint_1(v1, v2, pol);\n   boost::math::ellint_2(v1, pol);\n   boost::math::ellint_2(v1, v2, pol);\n   boost::math::ellint_3(v1, v2, pol);\n   boost::math::ellint_3(v1, v2, v3, pol);\n   boost::math::ellint_d(v1, pol);\n   boost::math::ellint_d(v1, v2, pol);\n   boost::math::jacobi_zeta(v1, v2, pol);\n   boost::math::heuman_lambda(v1, v2, pol);\n   boost::math::ellint_rc(v1, v2, pol);\n   boost::math::ellint_rd(v1, v2, v3, pol);\n   boost::math::ellint_rf(v1, v2, v3, pol);\n   boost::math::ellint_rg(v1, v2, v3, pol);\n   boost::math::ellint_rj(v1, v2, v3, v1, pol);\n   boost::math::jacobi_elliptic(v1, v2, &v1, &v2, pol);\n   boost::math::jacobi_cd(v1, v2, pol);\n   boost::math::jacobi_cn(v1, v2, pol);\n   boost::math::jacobi_cs(v1, v2, pol);\n   boost::math::jacobi_dc(v1, v2, pol);\n   boost::math::jacobi_dn(v1, v2, pol);\n   boost::math::jacobi_ds(v1, v2, pol);\n   boost::math::jacobi_nc(v1, v2, pol);\n   boost::math::jacobi_nd(v1, v2, pol);\n   boost::math::jacobi_ns(v1, v2, pol);\n   boost::math::jacobi_sc(v1, v2, pol);\n   boost::math::jacobi_sd(v1, v2, pol);\n   boost::math::jacobi_sn(v1, v2, pol);\n   boost::math::hypot(v1, v2, pol);\n   boost::math::sinc_pi(v1, pol);\n   boost::math::sinhc_pi(v1, pol);\n   boost::math::asinh(v1, pol);\n   boost::math::acosh(v1, pol);\n   boost::math::atanh(v1, pol);\n   boost::math::sin_pi(v1, pol);\n   boost::math::cos_pi(v1, pol);\n   boost::math::cyl_neumann(v1, v2, pol);\n   boost::math::cyl_neumann(i, v2, pol);\n   boost::math::cyl_bessel_j(v1, v2, pol);\n   boost::math::cyl_bessel_j(i, v2, pol);\n   boost::math::cyl_bessel_i(v1, v2, pol);\n   boost::math::cyl_bessel_i(i, v2, pol);\n   boost::math::cyl_bessel_k(v1, v2, pol);\n   boost::math::cyl_bessel_k(i, v2, pol);\n   boost::math::sph_bessel(i, v2, pol);\n   boost::math::sph_bessel(i, 1, pol);\n   boost::math::sph_neumann(i, v2, pol);\n   boost::math::sph_neumann(i, i, pol);\n   boost::math::cyl_neumann_prime(v1, v2, pol);\n   boost::math::cyl_neumann_prime(i, v2, pol);\n   boost::math::cyl_bessel_j_prime(v1, v2, pol);\n   boost::math::cyl_bessel_j_prime(i, v2, pol);\n   boost::math::cyl_bessel_i_prime(v1, v2, pol);\n   boost::math::cyl_bessel_i_prime(i, v2, pol);\n   boost::math::cyl_bessel_k_prime(v1, v2, pol);\n   boost::math::cyl_bessel_k_prime(i, v2, pol);\n   boost::math::sph_bessel_prime(i, v2, pol);\n   boost::math::sph_bessel_prime(i, 1, pol);\n   boost::math::sph_neumann_prime(i, v2, pol);\n   boost::math::sph_neumann_prime(i, i, pol);\n   boost::math::cyl_bessel_j_zero(v1, i, pol);\n   boost::math::cyl_bessel_j_zero(v1, i, i, oi, pol);\n   boost::math::cyl_neumann_zero(v1, i, pol);\n   boost::math::cyl_neumann_zero(v1, i, i, oi, pol);\n#ifdef TEST_COMPLEX\n   boost::math::cyl_hankel_1(v1, v2, pol);\n   boost::math::cyl_hankel_1(i, v2, pol);\n   boost::math::cyl_hankel_2(v1, v2, pol);\n   boost::math::cyl_hankel_2(i, v2, pol);\n   boost::math::sph_hankel_1(v1, v2, pol);\n   boost::math::sph_hankel_1(i, v2, pol);\n   boost::math::sph_hankel_2(v1, v2, pol);\n   boost::math::sph_hankel_2(i, v2, pol);\n#endif\n   boost::math::airy_ai(v1, pol);\n   boost::math::airy_bi(v1, pol);\n   boost::math::airy_ai_prime(v1, pol);\n   boost::math::airy_bi_prime(v1, pol);\n\n   boost::math::airy_ai_zero<RealType>(i, pol);\n   boost::math::airy_bi_zero<RealType>(i, pol);\n   boost::math::airy_ai_zero<RealType>(i, i, oi, pol);\n   boost::math::airy_bi_zero<RealType>(i, i, oi, pol);\n\n   boost::math::expint(v1, pol);\n   boost::math::expint(i, pol);\n   boost::math::expint(i, v2, pol);\n   boost::math::expint(i, i, pol);\n   boost::math::zeta(v1, pol);\n   boost::math::zeta(i, pol);\n   boost::math::owens_t(v1, v2, pol);\n   //\n   // These next functions are intended to be found via ADL:\n   //\n   BOOST_MATH_STD_USING\n   trunc(v1, pol);\n   itrunc(v1, pol);\n   ltrunc(v1, pol);\n   round(v1, pol);\n   iround(v1, pol);\n   lround(v1, pol);\n   modf(v1, &v1, pol);\n   modf(v1, &i, pol);\n   modf(v1, &l, pol);\n#ifdef BOOST_HAS_LONG_LONG\n   using boost::math::lltrunc;\n   using boost::math::llround;\n   lltrunc(v1, pol);\n   llround(v1, pol);\n   modf(v1, &ll, pol);\n#endif\n   boost::math::pow<2>(v1, pol);\n   boost::math::nextafter(v1, v1, pol);\n   boost::math::float_next(v1, pol);\n   boost::math::float_prior(v1, pol);\n   boost::math::float_distance(v1, v1, pol);\n   boost::math::ulp(v1, pol);\n\n   boost::math::bernoulli_b2n<RealType>(i, pol);\n   boost::math::bernoulli_b2n<RealType>(i, i, &v1, pol);\n   boost::math::tangent_t2n<RealType>(i, pol);\n   boost::math::tangent_t2n<RealType>(i, i, &v1, pol);\n#endif\n#ifdef TEST_GROUP_6\n   //\n   // All over again with the versions in test::\n   //\n   test::tgamma(v1);\n   test::tgamma1pm1(v1);\n   test::lgamma(v1);\n   test::lgamma(v1, &i);\n   test::digamma(v1);\n   test::trigamma(v1);\n   test::polygamma(i, v1);\n   test::tgamma_ratio(v1, v2);\n   test::tgamma_delta_ratio(v1, v2);\n   test::factorial<RealType>(i);\n   test::unchecked_factorial<RealType>(i);\n   i = test::max_factorial<RealType>::value;\n   test::double_factorial<RealType>(i);\n   test::rising_factorial(v1, i);\n   test::falling_factorial(v1, i);\n   test::tgamma(v1, v2);\n   test::tgamma_lower(v1, v2);\n   test::gamma_p(v1, v2);\n   test::gamma_q(v1, v2);\n   test::gamma_p_inv(v1, v2);\n   test::gamma_q_inv(v1, v2);\n   test::gamma_p_inva(v1, v2);\n   test::gamma_q_inva(v1, v2);\n   test::erf(v1);\n   test::erfc(v1);\n   test::erf_inv(v1);\n   test::erfc_inv(v1);\n   test::beta(v1, v2);\n   test::beta(v1, v2, v3);\n   test::betac(v1, v2, v3);\n   test::ibeta(v1, v2, v3);\n   test::ibetac(v1, v2, v3);\n   test::ibeta_inv(v1, v2, v3);\n   test::ibetac_inv(v1, v2, v3);\n   test::ibeta_inva(v1, v2, v3);\n   test::ibetac_inva(v1, v2, v3);\n   test::ibeta_invb(v1, v2, v3);\n   test::ibetac_invb(v1, v2, v3);\n   test::gamma_p_derivative(v2, v3);\n   test::ibeta_derivative(v1, v2, v3);\n   test::binomial_coefficient<RealType>(i, i);\n   (test::fpclassify)(v1);\n   (test::isfinite)(v1);\n   (test::isnormal)(v1);\n   (test::isnan)(v1);\n   (test::isinf)(v1);\n   (test::signbit)(v1);\n   (test::copysign)(v1, v2);\n   (test::changesign)(v1);\n   (test::sign)(v1);\n   test::log1p(v1);\n   test::expm1(v1);\n   test::cbrt(v1);\n   test::sqrt1pm1(v1);\n   test::powm1(v1, v2);\n   test::legendre_p(1, v1);\n   test::legendre_p(1, 0, v1);\n   test::legendre_p_prime(1, v1 * 1);\n   test::legendre_q(1, v1);\n   test::legendre_next(2, v1, v2, v3);\n   test::legendre_next(2, 2, v1, v2, v3);\n   test::laguerre(1, v1);\n   test::laguerre(2, 1, v1);\n   test::laguerre_next(2, v1, v2, v3);\n   test::laguerre_next(2, 1, v1, v2, v3);\n   test::hermite(1, v1);\n   test::hermite_next(2, v1, v2, v3);\n   test::spherical_harmonic_r(2, 1, v1, v2);\n   test::spherical_harmonic_i(2, 1, v1, v2);\n   test::ellint_1(v1);\n   test::ellint_1(v1, v2);\n   test::ellint_2(v1);\n   test::ellint_2(v1, v2);\n   test::ellint_3(v1, v2);\n   test::ellint_3(v1, v2, v3);\n   test::ellint_d(v1);\n   test::ellint_d(v1, v2);\n   test::jacobi_zeta(v1, v2);\n   test::heuman_lambda(v1, v2);\n   test::ellint_rc(v1, v2);\n   test::ellint_rd(v1, v2, v3);\n   test::ellint_rf(v1, v2, v3);\n   test::ellint_rg(v1, v2, v3);\n   test::ellint_rj(v1, v2, v3, v1);\n   test::jacobi_elliptic(v1, v2, &v1, &v2);\n   test::jacobi_cd(v1, v2);\n   test::jacobi_cn(v1, v2);\n   test::jacobi_cs(v1, v2);\n   test::jacobi_dc(v1, v2);\n   test::jacobi_dn(v1, v2);\n   test::jacobi_ds(v1, v2);\n   test::jacobi_nc(v1, v2);\n   test::jacobi_nd(v1, v2);\n   test::jacobi_ns(v1, v2);\n   test::jacobi_sc(v1, v2);\n   test::jacobi_sd(v1, v2);\n   test::jacobi_sn(v1, v2);\n   test::hypot(v1, v2);\n   test::sinc_pi(v1);\n   test::sinhc_pi(v1);\n   test::asinh(v1);\n   test::acosh(v1);\n   test::atanh(v1);\n   test::sin_pi(v1);\n   test::cos_pi(v1);\n   test::cyl_neumann(v1, v2);\n   test::cyl_neumann(i, v2);\n   test::cyl_bessel_j(v1, v2);\n   test::cyl_bessel_j(i, v2);\n   test::cyl_bessel_i(v1, v2);\n   test::cyl_bessel_i(i, v2);\n   test::cyl_bessel_k(v1, v2);\n   test::cyl_bessel_k(i, v2);\n   test::sph_bessel(i, v2);\n   test::sph_bessel(i, 1);\n   test::sph_neumann(i, v2);\n   test::sph_neumann(i, i);\n   test::cyl_neumann_prime(v1, v2);\n   test::cyl_neumann_prime(i, v2);\n   test::cyl_bessel_j_prime(v1, v2);\n   test::cyl_bessel_j_prime(i, v2);\n   test::cyl_bessel_i_prime(v1, v2);\n   test::cyl_bessel_i_prime(i, v2);\n   test::cyl_bessel_k_prime(v1, v2);\n   test::cyl_bessel_k_prime(i, v2);\n   test::sph_bessel_prime(i, v2);\n   test::sph_bessel_prime(i, 1);\n   test::sph_neumann_prime(i, v2);\n   test::sph_neumann_prime(i, i);\n   test::cyl_bessel_j_zero(v1, i);\n   test::cyl_bessel_j_zero(v1, i, i, oi);\n   test::cyl_neumann_zero(v1, i);\n   test::cyl_neumann_zero(v1, i, i, oi);\n#ifdef TEST_COMPLEX\n   test::cyl_hankel_1(v1, v2);\n   test::cyl_hankel_1(i, v2);\n   test::cyl_hankel_2(v1, v2);\n   test::cyl_hankel_2(i, v2);\n   test::sph_hankel_1(v1, v2);\n   test::sph_hankel_1(i, v2);\n   test::sph_hankel_2(v1, v2);\n   test::sph_hankel_2(i, v2);\n#endif\n   test::airy_ai(i);\n   test::airy_bi(i);\n   test::airy_ai_prime(i);\n   test::airy_bi_prime(i);\n\n   test::airy_ai_zero<RealType>(i);\n   test::airy_bi_zero<RealType>(i);\n   test::airy_ai_zero<RealType>(i, i, oi);\n   test::airy_bi_zero<RealType>(i, i, oi);\n\n   test::expint(v1);\n   test::expint(i);\n   test::expint(i, v2);\n   test::expint(i, i);\n   test::zeta(v1);\n   test::zeta(i);\n   test::owens_t(v1, v2);\n   test::trunc(v1);\n   test::itrunc(v1);\n   test::ltrunc(v1);\n   test::round(v1);\n   test::iround(v1);\n   test::lround(v1);\n   test::modf(v1, &v1);\n   test::modf(v1, &i);\n   test::modf(v1, &l);\n#ifdef BOOST_HAS_LONG_LONG\n   test::lltrunc(v1);\n   test::llround(v1);\n   test::modf(v1, &ll);\n#endif\n   test::pow<2>(v1);\n   test::nextafter(v1, v1);\n   test::float_next(v1);\n   test::float_prior(v1);\n   test::float_distance(v1, v1);\n   test::ulp(v1);\n#endif\n#endif\n}\n\ntemplate <class RealType>\nvoid instantiate_mixed(RealType)\n{\n   using namespace boost;\n   using namespace boost::math;\n#ifndef BOOST_MATH_INSTANTIATE_MINIMUM\n   int i = 1;\n   (void)i;\n   long l = 1;\n   (void)l;\n   short s = 1;\n   (void)s;\n   float fr = 0.5F;\n   (void)fr;\n   double dr = 0.5;\n   (void)dr;\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   long double lr = 0.5L;\n   (void)lr;\n#else\n   double lr = 0.5L;\n   (void)lr;\n#endif\n#ifdef TEST_GROUP_7\n   boost::math::tgamma(i);\n   boost::math::tgamma1pm1(i);\n   boost::math::lgamma(i);\n   boost::math::lgamma(i, &i);\n   boost::math::digamma(i);\n   boost::math::trigamma(i);\n   boost::math::polygamma(i, i);\n   boost::math::tgamma_ratio(i, l);\n   boost::math::tgamma_ratio(fr, lr);\n   boost::math::tgamma_delta_ratio(i, s);\n   boost::math::tgamma_delta_ratio(fr, lr);\n   boost::math::rising_factorial(s, i);\n   boost::math::falling_factorial(s, i);\n   boost::math::tgamma(i, l);\n   boost::math::tgamma(fr, lr);\n   boost::math::tgamma_lower(i, s);\n   boost::math::tgamma_lower(fr, lr);\n   boost::math::gamma_p(i, s);\n   boost::math::gamma_p(fr, lr);\n   boost::math::gamma_q(i, s);\n   boost::math::gamma_q(fr, lr);\n   boost::math::gamma_p_inv(i, fr);\n   boost::math::gamma_q_inv(s, fr);\n   boost::math::gamma_p_inva(i, lr);\n   boost::math::gamma_q_inva(i, lr);\n   boost::math::erf(i);\n   boost::math::erfc(i);\n   boost::math::erf_inv(i);\n   boost::math::erfc_inv(i);\n   boost::math::beta(i, s);\n   boost::math::beta(fr, lr);\n   boost::math::beta(i, s, l);\n   boost::math::beta(fr, dr, lr);\n   boost::math::betac(l, i, s);\n   boost::math::betac(fr, dr, lr);\n   boost::math::ibeta(l, i, s);\n   boost::math::ibeta(fr, dr, lr);\n   boost::math::ibetac(l, i, s);\n   boost::math::ibetac(fr, dr, lr);\n   boost::math::ibeta_inv(l, s, i);\n   boost::math::ibeta_inv(fr, dr, lr);\n   boost::math::ibetac_inv(l, i, s);\n   boost::math::ibetac_inv(fr, dr, lr);\n   boost::math::ibeta_inva(l, i, s);\n   boost::math::ibeta_inva(fr, dr, lr);\n   boost::math::ibetac_inva(l, i, s);\n   boost::math::ibetac_inva(fr, dr, lr);\n   boost::math::ibeta_invb(l, i, s);\n   boost::math::ibeta_invb(fr, dr, lr);\n   boost::math::ibetac_invb(l, i, s);\n   boost::math::ibetac_invb(fr, dr, lr);\n   boost::math::gamma_p_derivative(i, l);\n   boost::math::gamma_p_derivative(fr, lr);\n   boost::math::ibeta_derivative(l, i, s);\n   boost::math::ibeta_derivative(fr, dr, lr);\n   (boost::math::fpclassify)(i);\n   (boost::math::isfinite)(s);\n   (boost::math::isnormal)(l);\n   (boost::math::isnan)(i);\n   (boost::math::isinf)(l);\n   boost::math::log1p(i);\n   boost::math::expm1(s);\n   boost::math::cbrt(l);\n   boost::math::sqrt1pm1(s);\n   boost::math::powm1(i, s);\n   boost::math::powm1(fr, lr);\n   //boost::math::legendre_p(1, i);\n   boost::math::legendre_p(1, 0, s);\n   boost::math::legendre_q(1, i);\n   boost::math::laguerre(1, i);\n   boost::math::laguerre(2, 1, i);\n   boost::math::laguerre(2u, 1u, s);\n   boost::math::hermite(1, s);\n   boost::math::spherical_harmonic_r(2, 1, s, i);\n   boost::math::spherical_harmonic_i(2, 1, fr, lr);\n   boost::math::ellint_1(i);\n   boost::math::ellint_1(i, s);\n   boost::math::ellint_1(fr, lr);\n   boost::math::ellint_2(i);\n   boost::math::ellint_2(i, l);\n   boost::math::ellint_2(fr, lr);\n   boost::math::ellint_3(i, l);\n   boost::math::ellint_3(fr, lr);\n   boost::math::ellint_3(s, l, i);\n   boost::math::ellint_3(fr, dr, lr);\n   boost::math::ellint_d(i);\n   boost::math::ellint_d(i, l);\n   boost::math::ellint_d(fr, lr);\n   boost::math::jacobi_zeta(i, l);\n   boost::math::jacobi_zeta(fr, lr);\n   boost::math::heuman_lambda(i, l);\n   boost::math::heuman_lambda(fr, lr);\n   boost::math::ellint_rc(i, s);\n   boost::math::ellint_rc(fr, lr);\n   boost::math::ellint_rd(s, i, l);\n   boost::math::ellint_rd(fr, lr, dr);\n   boost::math::ellint_rf(s, l, i);\n   boost::math::ellint_rf(fr, dr, lr);\n   boost::math::ellint_rg(s, l, i);\n   boost::math::ellint_rg(fr, dr, lr);\n   boost::math::ellint_rj(i, i, s, l);\n   boost::math::ellint_rj(i, fr, dr, lr);\n   boost::math::jacobi_cd(i, fr);\n   boost::math::jacobi_cn(i, fr);\n   boost::math::jacobi_cs(i, fr);\n   boost::math::jacobi_dc(i, fr);\n   boost::math::jacobi_dn(i, fr);\n   boost::math::jacobi_ds(i, fr);\n   boost::math::jacobi_nc(i, fr);\n   boost::math::jacobi_nd(i, fr);\n   boost::math::jacobi_ns(i, fr);\n   boost::math::jacobi_sc(i, fr);\n   boost::math::jacobi_sd(i, fr);\n   boost::math::jacobi_sn(i, fr);\n   boost::math::hypot(i, s);\n   boost::math::hypot(fr, lr);\n   boost::math::sinc_pi(i);\n   boost::math::sinhc_pi(i);\n   boost::math::asinh(s);\n   boost::math::acosh(l);\n   boost::math::atanh(l);\n   boost::math::sin_pi(s);\n   boost::math::cos_pi(s);\n   boost::math::cyl_neumann(fr, dr);\n   boost::math::cyl_neumann(i, s);\n   boost::math::cyl_bessel_j(fr, lr);\n   boost::math::cyl_bessel_j(i, s);\n   boost::math::cyl_bessel_i(fr, lr);\n   boost::math::cyl_bessel_i(i, s);\n   boost::math::cyl_bessel_k(fr, lr);\n   boost::math::cyl_bessel_k(i, s);\n   boost::math::sph_bessel(i, fr);\n   boost::math::sph_bessel(i, 1);\n   boost::math::sph_neumann(i, lr);\n   boost::math::sph_neumann(i, i);\n   boost::math::cyl_neumann_prime(fr, dr);\n   boost::math::cyl_neumann_prime(i, s);\n   boost::math::cyl_bessel_j_prime(fr, lr);\n   boost::math::cyl_bessel_j_prime(i, s);\n   boost::math::cyl_bessel_i_prime(fr, lr);\n   boost::math::cyl_bessel_i_prime(i, s);\n   boost::math::cyl_bessel_k_prime(fr, lr);\n   boost::math::cyl_bessel_k_prime(i, s);\n   boost::math::sph_bessel_prime(i, fr);\n   boost::math::sph_bessel_prime(i, 1);\n   boost::math::sph_neumann_prime(i, lr);\n   boost::math::sph_neumann_prime(i, i);\n   boost::math::owens_t(fr, dr);\n   boost::math::owens_t(i, s);\n\n   boost::math::policies::policy<> pol;\n\n\n   boost::math::tgamma(i, pol);\n   boost::math::tgamma1pm1(i, pol);\n   boost::math::lgamma(i, pol);\n   boost::math::lgamma(i, &i, pol);\n   boost::math::digamma(i, pol);\n   boost::math::trigamma(i, pol);\n   boost::math::polygamma(i, i, pol);\n   boost::math::tgamma_ratio(i, l, pol);\n   boost::math::tgamma_ratio(fr, lr, pol);\n   boost::math::tgamma_delta_ratio(i, s, pol);\n   boost::math::tgamma_delta_ratio(fr, lr, pol);\n   boost::math::rising_factorial(s, i, pol);\n   boost::math::falling_factorial(s, i, pol);\n   boost::math::tgamma(i, l, pol);\n   boost::math::tgamma(fr, lr, pol);\n   boost::math::tgamma_lower(i, s, pol);\n   boost::math::tgamma_lower(fr, lr, pol);\n   boost::math::gamma_p(i, s, pol);\n   boost::math::gamma_p(fr, lr, pol);\n   boost::math::gamma_q(i, s, pol);\n   boost::math::gamma_q(fr, lr, pol);\n   boost::math::gamma_p_inv(i, fr, pol);\n   boost::math::gamma_q_inv(s, fr, pol);\n   boost::math::gamma_p_inva(i, lr, pol);\n   boost::math::gamma_q_inva(i, lr, pol);\n   boost::math::erf(i, pol);\n   boost::math::erfc(i, pol);\n   boost::math::erf_inv(i, pol);\n   boost::math::erfc_inv(i, pol);\n   boost::math::beta(i, s, pol);\n   boost::math::beta(fr, lr, pol);\n   boost::math::beta(i, s, l, pol);\n   boost::math::beta(fr, dr, lr, pol);\n   boost::math::betac(l, i, s, pol);\n   boost::math::betac(fr, dr, lr, pol);\n   boost::math::ibeta(l, i, s, pol);\n   boost::math::ibeta(fr, dr, lr, pol);\n   boost::math::ibetac(l, i, s, pol);\n   boost::math::ibetac(fr, dr, lr, pol);\n   boost::math::ibeta_inv(l, s, i, pol);\n   boost::math::ibeta_inv(fr, dr, lr, pol);\n   boost::math::ibetac_inv(l, i, s, pol);\n   boost::math::ibetac_inv(fr, dr, lr, pol);\n   boost::math::ibeta_inva(l, i, s, pol);\n   boost::math::ibeta_inva(fr, dr, lr, pol);\n   boost::math::ibetac_inva(l, i, s, pol);\n   boost::math::ibetac_inva(fr, dr, lr, pol);\n   boost::math::ibeta_invb(l, i, s, pol);\n   boost::math::ibeta_invb(fr, dr, lr, pol);\n   boost::math::ibetac_invb(l, i, s, pol);\n   boost::math::ibetac_invb(fr, dr, lr, pol);\n   boost::math::gamma_p_derivative(i, l, pol);\n   boost::math::gamma_p_derivative(fr, lr, pol);\n   boost::math::ibeta_derivative(l, i, s, pol);\n   boost::math::ibeta_derivative(fr, dr, lr, pol);\n   boost::math::log1p(i, pol);\n   boost::math::expm1(s, pol);\n   boost::math::cbrt(l, pol);\n   boost::math::sqrt1pm1(s, pol);\n   boost::math::powm1(i, s, pol);\n   boost::math::powm1(fr, lr, pol);\n   //boost::math::legendre_p(1, i, pol);\n   boost::math::legendre_p(1, 0, s, pol);\n   boost::math::legendre_q(1, i, pol);\n   boost::math::laguerre(1, i, pol);\n   boost::math::laguerre(2, 1, i, pol);\n   boost::math::laguerre(2u, 1u, s, pol);\n   boost::math::hermite(1, s, pol);\n   boost::math::spherical_harmonic_r(2, 1, s, i, pol);\n   boost::math::spherical_harmonic_i(2, 1, fr, lr, pol);\n   boost::math::ellint_1(i, pol);\n   boost::math::ellint_1(i, s, pol);\n   boost::math::ellint_1(fr, lr, pol);\n   boost::math::ellint_2(i, pol);\n   boost::math::ellint_2(i, l, pol);\n   boost::math::ellint_2(fr, lr, pol);\n   boost::math::ellint_3(i, l, pol);\n   boost::math::ellint_3(fr, lr, pol);\n   boost::math::ellint_3(s, l, i, pol);\n   boost::math::ellint_3(fr, dr, lr, pol);\n   boost::math::ellint_d(i, pol);\n   boost::math::ellint_d(i, l, pol);\n   boost::math::ellint_d(fr, lr, pol);\n   boost::math::jacobi_zeta(i, l, pol);\n   boost::math::jacobi_zeta(fr, lr, pol);\n   boost::math::heuman_lambda(i, l, pol);\n   boost::math::heuman_lambda(fr, lr, pol);\n   boost::math::ellint_rc(i, s, pol);\n   boost::math::ellint_rc(fr, lr, pol);\n   boost::math::ellint_rd(s, i, l, pol);\n   boost::math::ellint_rd(fr, lr, dr, pol);\n   boost::math::ellint_rf(s, l, i, pol);\n   boost::math::ellint_rf(fr, dr, lr, pol);\n   boost::math::ellint_rg(s, l, i, pol);\n   boost::math::ellint_rg(fr, dr, lr, pol);\n   boost::math::ellint_rj(i, i, s, l, pol);\n   boost::math::ellint_rj(i, fr, dr, lr, pol);\n   boost::math::jacobi_cd(i, fr, pol);\n   boost::math::jacobi_cn(i, fr, pol);\n   boost::math::jacobi_cs(i, fr, pol);\n   boost::math::jacobi_dc(i, fr, pol);\n   boost::math::jacobi_dn(i, fr, pol);\n   boost::math::jacobi_ds(i, fr, pol);\n   boost::math::jacobi_nc(i, fr, pol);\n   boost::math::jacobi_nd(i, fr, pol);\n   boost::math::jacobi_ns(i, fr, pol);\n   boost::math::jacobi_sc(i, fr, pol);\n   boost::math::jacobi_sd(i, fr, pol);\n   boost::math::jacobi_sn(i, fr, pol);\n   boost::math::hypot(i, s, pol);\n   boost::math::hypot(fr, lr, pol);\n   boost::math::sinc_pi(i, pol);\n   boost::math::sinhc_pi(i, pol);\n   boost::math::asinh(s, pol);\n   boost::math::acosh(l, pol);\n   boost::math::atanh(l, pol);\n   boost::math::sin_pi(s, pol);\n   boost::math::cos_pi(s, pol);\n   boost::math::cyl_neumann(fr, dr, pol);\n   boost::math::cyl_neumann(i, s, pol);\n   boost::math::cyl_bessel_j(fr, lr, pol);\n   boost::math::cyl_bessel_j(i, s, pol);\n   boost::math::cyl_bessel_i(fr, lr, pol);\n   boost::math::cyl_bessel_i(i, s, pol);\n   boost::math::cyl_bessel_k(fr, lr, pol);\n   boost::math::cyl_bessel_k(i, s, pol);\n   boost::math::sph_bessel(i, fr, pol);\n   boost::math::sph_bessel(i, 1, pol);\n   boost::math::sph_neumann(i, lr, pol);\n   boost::math::sph_neumann(i, i, pol);\n   boost::math::cyl_neumann_prime(fr, dr, pol);\n   boost::math::cyl_neumann_prime(i, s, pol);\n   boost::math::cyl_bessel_j_prime(fr, lr, pol);\n   boost::math::cyl_bessel_j_prime(i, s, pol);\n   boost::math::cyl_bessel_i_prime(fr, lr, pol);\n   boost::math::cyl_bessel_i_prime(i, s, pol);\n   boost::math::cyl_bessel_k_prime(fr, lr, pol);\n   boost::math::cyl_bessel_k_prime(i, s, pol);\n   boost::math::sph_bessel_prime(i, fr, pol);\n   boost::math::sph_bessel_prime(i, 1, pol);\n   boost::math::sph_neumann_prime(i, lr, pol);\n   boost::math::sph_neumann_prime(i, i, pol);\n   boost::math::owens_t(fr, dr, pol);\n   boost::math::owens_t(i, s, pol);\n#endif\n#ifdef TEST_GROUP_8\n   test::tgamma(i);\n   test::tgamma1pm1(i);\n   test::lgamma(i);\n   test::lgamma(i, &i);\n   test::digamma(i);\n   test::trigamma(i);\n   test::polygamma(i, i);\n   test::tgamma_ratio(i, l);\n   test::tgamma_ratio(fr, lr);\n   test::tgamma_delta_ratio(i, s);\n   test::tgamma_delta_ratio(fr, lr);\n   test::rising_factorial(s, i);\n   test::falling_factorial(s, i);\n   test::tgamma(i, l);\n   test::tgamma(fr, lr);\n   test::tgamma_lower(i, s);\n   test::tgamma_lower(fr, lr);\n   test::gamma_p(i, s);\n   test::gamma_p(fr, lr);\n   test::gamma_q(i, s);\n   test::gamma_q(fr, lr);\n   test::gamma_p_inv(i, fr);\n   test::gamma_q_inv(s, fr);\n   test::gamma_p_inva(i, lr);\n   test::gamma_q_inva(i, lr);\n   test::erf(i);\n   test::erfc(i);\n   test::erf_inv(i);\n   test::erfc_inv(i);\n   test::beta(i, s);\n   test::beta(fr, lr);\n   test::beta(i, s, l);\n   test::beta(fr, dr, lr);\n   test::betac(l, i, s);\n   test::betac(fr, dr, lr);\n   test::ibeta(l, i, s);\n   test::ibeta(fr, dr, lr);\n   test::ibetac(l, i, s);\n   test::ibetac(fr, dr, lr);\n   test::ibeta_inv(l, s, i);\n   test::ibeta_inv(fr, dr, lr);\n   test::ibetac_inv(l, i, s);\n   test::ibetac_inv(fr, dr, lr);\n   test::ibeta_inva(l, i, s);\n   test::ibeta_inva(fr, dr, lr);\n   test::ibetac_inva(l, i, s);\n   test::ibetac_inva(fr, dr, lr);\n   test::ibeta_invb(l, i, s);\n   test::ibeta_invb(fr, dr, lr);\n   test::ibetac_invb(l, i, s);\n   test::ibetac_invb(fr, dr, lr);\n   test::gamma_p_derivative(i, l);\n   test::gamma_p_derivative(fr, lr);\n   test::ibeta_derivative(l, i, s);\n   test::ibeta_derivative(fr, dr, lr);\n   (test::fpclassify)(i);\n   (test::isfinite)(s);\n   (test::isnormal)(l);\n   (test::isnan)(i);\n   (test::isinf)(l);\n   test::log1p(i);\n   test::expm1(s);\n   test::cbrt(l);\n   test::sqrt1pm1(s);\n   test::powm1(i, s);\n   test::powm1(fr, lr);\n   //test::legendre_p(1, i);\n   test::legendre_p(1, 0, s);\n   test::legendre_q(1, i);\n   test::laguerre(1, i);\n   test::laguerre(2, 1, i);\n   test::laguerre(2u, 1u, s);\n   test::hermite(1, s);\n   test::spherical_harmonic_r(2, 1, s, i);\n   test::spherical_harmonic_i(2, 1, fr, lr);\n   test::ellint_1(i);\n   test::ellint_1(i, s);\n   test::ellint_1(fr, lr);\n   test::ellint_2(i);\n   test::ellint_2(i, l);\n   test::ellint_2(fr, lr);\n   test::ellint_3(i, l);\n   test::ellint_3(fr, lr);\n   test::ellint_3(s, l, i);\n   test::ellint_3(fr, dr, lr);\n   test::ellint_d(i);\n   test::ellint_d(i, l);\n   test::ellint_d(fr, lr);\n   test::jacobi_zeta(i, l);\n   test::jacobi_zeta(fr, lr);\n   test::heuman_lambda(i, l);\n   test::heuman_lambda(fr, lr);\n   test::ellint_rc(i, s);\n   test::ellint_rc(fr, lr);\n   test::ellint_rd(s, i, l);\n   test::ellint_rd(fr, lr, dr);\n   test::ellint_rf(s, l, i);\n   test::ellint_rf(fr, dr, lr);\n   test::ellint_rg(s, l, i);\n   test::ellint_rg(fr, dr, lr);\n   test::ellint_rj(i, i, s, l);\n   test::ellint_rj(i, fr, dr, lr);\n   test::hypot(i, s);\n   test::hypot(fr, lr);\n   test::sinc_pi(i);\n   test::sinhc_pi(i);\n   test::asinh(s);\n   test::acosh(l);\n   test::atanh(l);\n   test::sin_pi(s);\n   test::cos_pi(s);\n   test::cyl_neumann(fr, dr);\n   test::cyl_neumann(i, s);\n   test::cyl_bessel_j(fr, lr);\n   test::cyl_bessel_j(i, s);\n   test::cyl_bessel_i(fr, lr);\n   test::cyl_bessel_i(i, s);\n   test::cyl_bessel_k(fr, lr);\n   test::cyl_bessel_k(i, s);\n   test::sph_bessel(i, fr);\n   test::sph_bessel(i, 1);\n   test::sph_neumann(i, lr);\n   test::sph_neumann(i, i);\n   test::cyl_neumann_prime(fr, dr);\n   test::cyl_neumann_prime(i, s);\n   test::cyl_bessel_j_prime(fr, lr);\n   test::cyl_bessel_j_prime(i, s);\n   test::cyl_bessel_i_prime(fr, lr);\n   test::cyl_bessel_i_prime(i, s);\n   test::cyl_bessel_k_prime(fr, lr);\n   test::cyl_bessel_k_prime(i, s);\n   test::sph_bessel_prime(i, fr);\n   test::sph_bessel_prime(i, 1);\n   test::sph_neumann_prime(i, lr);\n   test::sph_neumann_prime(i, i);\n   test::airy_ai(i);\n   test::airy_bi(i);\n   test::airy_ai_prime(i);\n   test::airy_bi_prime(i);\n   test::owens_t(fr, dr);\n   test::owens_t(i, s);\n#endif\n#endif\n}\n\n\n#endif // BOOST_LIBS_MATH_TEST_INSTANTIATE_HPP\n", "meta": {"hexsha": "cdb0f1e877de222a064844444c34814a764d0baa", "size": 51860, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/src/boost_1_65_1/libs/math/test/compile_test/instantiate.hpp", "max_stars_repo_name": "shreyasvj25/turicreate", "max_stars_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-07-21T17:14:35.000Z", "max_stars_repo_stars_event_max_datetime": "2017-07-21T17:14:35.000Z", "max_issues_repo_path": "deps/src/boost_1_65_1/libs/math/test/compile_test/instantiate.hpp", "max_issues_repo_name": "shreyasvj25/turicreate", "max_issues_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-09-08T02:18:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T00:39:44.000Z", "max_forks_repo_path": "deps/src/boost_1_65_1/libs/math/test/compile_test/instantiate.hpp", "max_forks_repo_name": "shreyasvj25/turicreate", "max_forks_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-10-21T17:46:28.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-21T17:46:28.000Z", "avg_line_length": 37.2557471264, "max_line_length": 142, "alphanum_fraction": 0.6532202083, "num_tokens": 18702, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300449389325, "lm_q2_score": 0.6442251133170357, "lm_q1q2_score": 0.45258749780940594}}
{"text": "/*=============================================================================\n    Copyright (c) 2001-2007 Joel de Guzman\n    Copyright (c) 2001-2009 Hartmut Kaiser\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#include <climits>\n#include <boost/math/concepts/real_concept.hpp>\n#include <boost/detail/lightweight_test.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/home/support/detail/math/fpclassify.hpp>\n#include <boost/spirit/home/support/detail/math/signbit.hpp>\n\n#include \"test.hpp\"\nusing namespace spirit_test;\n\n///////////////////////////////////////////////////////////////////////////////\n//  These policies can be used to parse thousand separated\n//  numbers with at most 2 decimal digits after the decimal\n//  point. e.g. 123,456,789.01\n///////////////////////////////////////////////////////////////////////////////\ntemplate <typename T>\nstruct ts_real_policies : boost::spirit::qi::ureal_policies<T>\n{\n    //  2 decimal places Max\n    template <typename Iterator, typename Attribute>\n    static bool\n    parse_frac_n(Iterator& first, Iterator const& last, Attribute& attr)\n    {\n        return boost::spirit::qi::\n            extract_uint<T, 10, 1, 2, true>::call(first, last, attr);\n    }\n\n    //  No exponent\n    template <typename Iterator>\n    static bool\n    parse_exp(Iterator&, Iterator const&)\n    {\n        return false;\n    }\n\n    //  No exponent\n    template <typename Iterator, typename Attribute>\n    static bool\n    parse_exp_n(Iterator&, Iterator const&, Attribute&)\n    {\n        return false;\n    }\n\n    //  Thousands separated numbers\n    template <typename Iterator, typename Attribute>\n    static bool\n    parse_n(Iterator& first, Iterator const& last, Attribute& attr)\n    {\n        using namespace boost::spirit::qi;\n        using namespace boost::spirit;\n\n        uint_spec<unsigned, 10, 1, 3> uint3;\n        uint_spec<unsigned, 10, 3, 3> uint3_3;\n\n        T result = 0;\n        if (parse(first, last, uint3, result))\n        {\n            bool hit = false;\n            T n;\n            Iterator save = first;\n\n            while (parse(first, last, ',') && parse(first, last, uint3_3, n))\n            {\n                result = result * 1000 + n;\n                save = first;\n                hit = true;\n            }\n\n            first = save;\n            if (hit)\n                attr = result;\n            return hit;\n        }\n        return false;\n    }\n};\n\ntemplate <typename T>\nstruct no_trailing_dot_policy : boost::spirit::qi::real_policies<T>\n{\n    static bool const allow_trailing_dot = false;\n};\n\ntemplate <typename T>\nstruct no_leading_dot_policy : boost::spirit::qi::real_policies<T>\n{\n    static bool const allow_leading_dot = false;\n};\n\ntemplate <typename T>\nbool\ncompare(T n, double expected)\n{\n    double const eps = 0.00001;\n    T delta = n - expected;\n    return (delta >= -eps) && (delta <= eps);\n}\n\nint\nmain()\n{\n    ///////////////////////////////////////////////////////////////////////////////\n    //  thousand separated numbers\n    ///////////////////////////////////////////////////////////////////////////////\n    {\n        using boost::spirit::qi::uint_spec;\n        using boost::spirit::qi::parse;\n\n        uint_spec<unsigned, 10, 1, 3> uint3;\n        uint_spec<unsigned, 10, 3, 3> uint3_3;\n\n    #define r (uint3 >> *(',' >> uint3_3))\n\n        BOOST_TEST(test(\"1,234,567,890\", r));\n        BOOST_TEST(test(\"12,345,678,900\", r));\n        BOOST_TEST(test(\"123,456,789,000\", r));\n        BOOST_TEST(!test(\"1000,234,567,890\", r));\n        BOOST_TEST(!test(\"1,234,56,890\", r));\n        BOOST_TEST(!test(\"1,66\", r));\n    }\n\n    ///////////////////////////////////////////////////////////////////////////////\n    //  unsigned real number tests\n    ///////////////////////////////////////////////////////////////////////////////\n    {\n        using boost::spirit::qi::real_spec;\n        using boost::spirit::qi::parse;\n        using boost::spirit::qi::ureal_policies;\n\n        real_spec<double, ureal_policies<double> > udouble;\n        double  d;\n\n        BOOST_TEST(test(\"1234\", udouble));\n        BOOST_TEST(test_attr(\"1234\", udouble, d) && compare(d, 1234));\n\n        BOOST_TEST(test(\"1.2e3\", udouble));\n        BOOST_TEST(test_attr(\"1.2e3\", udouble, d) && compare(d, 1.2e3));\n\n        BOOST_TEST(test(\"1.2e-3\", udouble));\n        BOOST_TEST(test_attr(\"1.2e-3\", udouble, d) && compare(d, 1.2e-3));\n\n        BOOST_TEST(test(\"1.e2\", udouble));\n        BOOST_TEST(test_attr(\"1.e2\", udouble, d) && compare(d, 1.e2));\n\n        BOOST_TEST(test(\"1.\", udouble));\n        BOOST_TEST(test_attr(\"1.\", udouble, d) && compare(d, 1.));\n\n        BOOST_TEST(test(\".2e3\", udouble));\n        BOOST_TEST(test_attr(\".2e3\", udouble, d) && compare(d, .2e3));\n\n        BOOST_TEST(test(\"2e3\", udouble));\n        BOOST_TEST(test_attr(\"2e3\", udouble, d) && compare(d, 2e3));\n\n        BOOST_TEST(test(\"2\", udouble));\n        BOOST_TEST(test_attr(\"2\", udouble, d) && compare(d, 2));\n\n        using boost::math::fpclassify;\n        BOOST_TEST(test(\"inf\", udouble));\n        BOOST_TEST(test(\"infinity\", udouble));\n        BOOST_TEST(test(\"INF\", udouble));\n        BOOST_TEST(test(\"INFINITY\", udouble));\n        BOOST_TEST(test_attr(\"inf\", udouble, d) && FP_INFINITE == fpclassify(d));\n        BOOST_TEST(test_attr(\"INF\", udouble, d) && FP_INFINITE == fpclassify(d));\n        BOOST_TEST(test_attr(\"infinity\", udouble, d) && FP_INFINITE == fpclassify(d));\n        BOOST_TEST(test_attr(\"INFINITY\", udouble, d) && FP_INFINITE == fpclassify(d));\n\n        BOOST_TEST(test(\"nan\", udouble));\n        BOOST_TEST(test_attr(\"nan\", udouble, d) && FP_NAN == fpclassify(d));\n        BOOST_TEST(test(\"NAN\", udouble));\n        BOOST_TEST(test_attr(\"NAN\", udouble, d) && FP_NAN == fpclassify(d));\n\n        BOOST_TEST(test(\"nan(...)\", udouble));\n        BOOST_TEST(test_attr(\"nan(...)\", udouble, d) && FP_NAN == fpclassify(d));\n        BOOST_TEST(test(\"NAN(...)\", udouble));\n        BOOST_TEST(test_attr(\"NAN(...)\", udouble, d) && FP_NAN == fpclassify(d));\n\n        BOOST_TEST(!test(\"e3\", udouble));\n        BOOST_TEST(!test_attr(\"e3\", udouble, d));\n\n        BOOST_TEST(!test(\"-1.2e3\", udouble));\n        BOOST_TEST(!test_attr(\"-1.2e3\", udouble, d));\n\n        BOOST_TEST(!test(\"+1.2e3\", udouble));\n        BOOST_TEST(!test_attr(\"+1.2e3\", udouble, d));\n\n        BOOST_TEST(!test(\"1.2e\", udouble));\n        BOOST_TEST(!test_attr(\"1.2e\", udouble, d));\n\n        BOOST_TEST(!test(\"-.3\", udouble));\n        BOOST_TEST(!test_attr(\"-.3\", udouble, d));\n    }\n\n///////////////////////////////////////////////////////////////////////////////\n//  signed real number tests\n///////////////////////////////////////////////////////////////////////////////\n    {\n        using boost::spirit::double_;\n        using boost::spirit::qi::parse;\n        double  d;\n\n        BOOST_TEST(test(\"-1234\", double_));\n        BOOST_TEST(test_attr(\"-1234\", double_, d) && compare(d, -1234));\n\n        BOOST_TEST(test(\"-1.2e3\", double_));\n        BOOST_TEST(test_attr(\"-1.2e3\", double_, d) && compare(d, -1.2e3));\n\n        BOOST_TEST(test(\"+1.2e3\", double_));\n        BOOST_TEST(test_attr(\"+1.2e3\", double_, d) && compare(d, 1.2e3));\n\n        BOOST_TEST(test(\"-0.1\", double_));\n        BOOST_TEST(test_attr(\"-0.1\", double_, d) && compare(d, -0.1));\n\n        BOOST_TEST(test(\"-1.2e-3\", double_));\n        BOOST_TEST(test_attr(\"-1.2e-3\", double_, d) && compare(d, -1.2e-3));\n\n        BOOST_TEST(test(\"-1.e2\", double_));\n        BOOST_TEST(test_attr(\"-1.e2\", double_, d) && compare(d, -1.e2));\n\n        BOOST_TEST(test(\"-.2e3\", double_));\n        BOOST_TEST(test_attr(\"-.2e3\", double_, d) && compare(d, -.2e3));\n\n        BOOST_TEST(test(\"-2e3\", double_));\n        BOOST_TEST(test_attr(\"-2e3\", double_, d) && compare(d, -2e3));\n\n        BOOST_TEST(!test(\"-e3\", double_));\n        BOOST_TEST(!test_attr(\"-e3\", double_, d));\n\n        BOOST_TEST(!test(\"-1.2e\", double_));\n        BOOST_TEST(!test_attr(\"-1.2e\", double_, d));\n\n        using boost::spirit::math::fpclassify;\n        using boost::spirit::math::signbit;\n        BOOST_TEST(test(\"-inf\", double_));\n        BOOST_TEST(test(\"-infinity\", double_));\n        BOOST_TEST(test_attr(\"-inf\", double_, d) &&\n            FP_INFINITE == fpclassify(d) && signbit(d));\n        BOOST_TEST(test_attr(\"-infinity\", double_, d) &&\n            FP_INFINITE == fpclassify(d) && signbit(d));\n        BOOST_TEST(test(\"-INF\", double_));\n        BOOST_TEST(test(\"-INFINITY\", double_));\n        BOOST_TEST(test_attr(\"-INF\", double_, d) &&\n            FP_INFINITE == fpclassify(d) && signbit(d));\n        BOOST_TEST(test_attr(\"-INFINITY\", double_, d) &&\n            FP_INFINITE == fpclassify(d) && signbit(d));\n\n        BOOST_TEST(test(\"-nan\", double_));\n        BOOST_TEST(test_attr(\"-nan\", double_, d) &&\n            FP_NAN == fpclassify(d) && signbit(d));\n        BOOST_TEST(test(\"-NAN\", double_));\n        BOOST_TEST(test_attr(\"-NAN\", double_, d) &&\n            FP_NAN == fpclassify(d) && signbit(d));\n\n        BOOST_TEST(test(\"-nan(...)\", double_));\n        BOOST_TEST(test_attr(\"-nan(...)\", double_, d) &&\n            FP_NAN == fpclassify(d) && signbit(d));\n        BOOST_TEST(test(\"-NAN(...)\", double_));\n        BOOST_TEST(test_attr(\"-NAN(...)\", double_, d) &&\n            FP_NAN == fpclassify(d) && signbit(d));\n    }\n\n    ///////////////////////////////////////////////////////////////////////////////\n    //  strict real number tests\n    ///////////////////////////////////////////////////////////////////////////////\n    {\n        using boost::spirit::qi::real_spec;\n        using boost::spirit::qi::parse;\n        using boost::spirit::qi::strict_ureal_policies;\n        using boost::spirit::qi::strict_real_policies;\n\n        real_spec<double, strict_ureal_policies<double> > strict_udouble;\n        real_spec<double, strict_real_policies<double> > strict_double;\n        double  d;\n\n        BOOST_TEST(!test(\"1234\", strict_udouble));\n        BOOST_TEST(!test_attr(\"1234\", strict_udouble, d));\n\n        BOOST_TEST(test(\"1.2\", strict_udouble));\n        BOOST_TEST(test_attr(\"1.2\", strict_udouble, d) && compare(d, 1.2));\n\n        BOOST_TEST(!test(\"-1234\", strict_double));\n        BOOST_TEST(!test_attr(\"-1234\", strict_double, d));\n\n        BOOST_TEST(test(\"123.\", strict_double));\n        BOOST_TEST(test_attr(\"123.\", strict_double, d) && compare(d, 123));\n\n        BOOST_TEST(test(\"3.E6\", strict_double));\n        BOOST_TEST(test_attr(\"3.E6\", strict_double, d) && compare(d, 3e6));\n\n        real_spec<double, no_trailing_dot_policy<double> > notrdot_real;\n        real_spec<double, no_leading_dot_policy<double> > nolddot_real;\n\n        BOOST_TEST(!test(\"1234.\", notrdot_real));          //  Bad trailing dot\n        BOOST_TEST(!test(\".1234\", nolddot_real));          //  Bad leading dot\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    //  Special thousands separated numbers\n    ///////////////////////////////////////////////////////////////////////////\n    {\n        using boost::spirit::qi::real_spec;\n        using boost::spirit::qi::parse;\n        real_spec<double, ts_real_policies<double> > ts_real;\n        double  d;\n\n        BOOST_TEST(test(\"123,456,789.01\", ts_real));\n        BOOST_TEST(test_attr(\"123,456,789.01\", ts_real, d) && compare(d, 123456789.01));\n\n        BOOST_TEST(test(\"12,345,678.90\", ts_real));\n        BOOST_TEST(test_attr(\"12,345,678.90\", ts_real, d) && compare(d, 12345678.90));\n\n        BOOST_TEST(test(\"1,234,567.89\", ts_real));\n        BOOST_TEST(test_attr(\"1,234,567.89\", ts_real, d) && compare(d, 1234567.89));\n\n        BOOST_TEST(!test(\"1234,567,890\", ts_real));\n        BOOST_TEST(!test(\"1,234,5678,9\", ts_real));\n        BOOST_TEST(!test(\"1,234,567.89e6\", ts_real));\n        BOOST_TEST(!test(\"1,66\", ts_real));\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    //  Custom data type\n    ///////////////////////////////////////////////////////////////////////////\n    {\n        using boost::math::concepts::real_concept;\n        using boost::spirit::qi::real_spec;\n        using boost::spirit::qi::real_policies;\n        using boost::spirit::qi::parse;\n        \n        real_spec<real_concept, real_policies<real_concept> > custom_real;\n        real_concept d;\n        \n        BOOST_TEST(test(\"-1234\", custom_real));\n        BOOST_TEST(test_attr(\"-1234\", custom_real, d) && compare(d, -1234));\n\n        BOOST_TEST(test(\"-1.2e3\", custom_real));\n        BOOST_TEST(test_attr(\"-1.2e3\", custom_real, d) && compare(d, -1.2e3));\n\n        BOOST_TEST(test(\"+1.2e3\", custom_real));\n        BOOST_TEST(test_attr(\"+1.2e3\", custom_real, d) && compare(d, 1.2e3));\n\n        BOOST_TEST(test(\"-0.1\", custom_real));\n        BOOST_TEST(test_attr(\"-0.1\", custom_real, d) && compare(d, -0.1));\n\n        BOOST_TEST(test(\"-1.2e-3\", custom_real));\n        BOOST_TEST(test_attr(\"-1.2e-3\", custom_real, d) && compare(d, -1.2e-3));\n\n        BOOST_TEST(test(\"-1.e2\", custom_real));\n        BOOST_TEST(test_attr(\"-1.e2\", custom_real, d) && compare(d, -1.e2));\n\n        BOOST_TEST(test(\"-.2e3\", custom_real));\n        BOOST_TEST(test_attr(\"-.2e3\", custom_real, d) && compare(d, -.2e3));\n\n        BOOST_TEST(test(\"-2e3\", custom_real));\n        BOOST_TEST(test_attr(\"-2e3\", custom_real, d) && compare(d, -2e3));\n\n        BOOST_TEST(!test(\"-e3\", custom_real));\n        BOOST_TEST(!test_attr(\"-e3\", custom_real, d));\n\n        BOOST_TEST(!test(\"-1.2e\", custom_real));\n        BOOST_TEST(!test_attr(\"-1.2e\", custom_real, d));\n    }\n    \n    return boost::report_errors();\n}\n", "meta": {"hexsha": "1270dd826543ea69756eee4d3a1d1f149dbf9901", "size": 13830, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/spirit/test/qi/real.cpp", "max_stars_repo_name": "mike-code/boost_1_38_0", "max_stars_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-08-22T17:17:41.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-22T17:17:41.000Z", "max_issues_repo_path": "libs/spirit/test/qi/real.cpp", "max_issues_repo_name": "mike-code/boost_1_38_0", "max_issues_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/spirit/test/qi/real.cpp", "max_forks_repo_name": "mike-code/boost_1_38_0", "max_forks_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-07T05:20:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-07T05:20:43.000Z", "avg_line_length": 36.88, "max_line_length": 88, "alphanum_fraction": 0.536659436, "num_tokens": 3470, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442250928250376, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.4525874834131617}}
{"text": "#include <iostream>\n#include <typeinfo>\r\n#define BOOST_TEST_MODULE SparseMIASolveTests\n#include \"MIAConfig.h\"\r\n#ifdef MIA_USE_HEADER_ONLY_TESTS\r\n#include <boost/test/included/unit_test.hpp>\r\n#else\r\n#include <boost/test/unit_test.hpp>\r\n#endif\r\n\n#include \"SparseMIA.h\"\r\n#include \"DenseMIA.h\"\n#include \"Index.h\"\n#include \"LibMIAException.h\"\n#include \"LibMIAUtil.h\"\r\n\ntemplate<typename data_type, size_t _order>\r\nvoid random_mia(LibMIA::DenseMIA<data_type,_order> & mia,double _prob,bool need_ranked=true)\r\n{\r\n    boost::uniform_real<> uni_dist(0,1);\r\n    boost::variate_generator<boost::random::mt19937&, boost::uniform_real<> > uni(LibMIA::LibMIA_gen(), uni_dist);\r\n    boost::uniform_real<> uni_dist2(-10,10);\r\n    boost::variate_generator<boost::random::mt19937&, boost::uniform_real<> > uni2(LibMIA::LibMIA_gen(), uni_dist2);\r\n    mia.zeros();\r\n    for(auto it =mia.data_begin(); it<mia.data_end(); ++it)\r\n    {\r\n\r\n        if(uni()<_prob)\r\n        {\r\n            *it=uni2();\r\n        }\r\n\r\n    }\r\n}\n\n\r\ntemplate<class _data_type>\r\nvoid solve_work(size_t dim1, size_t dim2){\r\n\r\n    LibMIA::MIAINDEX i;\n    LibMIA::MIAINDEX j;\n    LibMIA::MIAINDEX k;\r\n    LibMIA::MIAINDEX l;\r\n    LibMIA::MIAINDEX m;\r\n    LibMIA::MIAINDEX n;\r\n    //LibMIA::MIAINDEX o;\r\n    //LibMIA::MIAINDEX p;\n\n    LibMIA::DenseMIA<_data_type,4> dense_a(dim1,dim1,dim1,dim1);\r\n    LibMIA::DenseMIA<_data_type,4> dense_a2(dim2,dim2,dim1,dim1);\r\n    LibMIA::DenseMIA<_data_type,4> dense_b(dim1,dim1,dim1,dim1);\r\n    LibMIA::DenseMIA<_data_type,4> dense_b2(dim2,dim2,dim1,dim1);\r\n    LibMIA::DenseMIA<_data_type,4> dense_c(dim1,dim1,dim1,dim1);\r\n    LibMIA::DenseMIA<_data_type,4> dense_d2(dim1,dim1,dim1,dim1);\r\n\r\n    LibMIA::SparseMIA<_data_type,4> a(dim1,dim1,dim1,dim1);\r\n    LibMIA::SparseMIA<_data_type,4> a2(dim2,dim2,dim1,dim1);\r\n    LibMIA::SparseMIA<_data_type,4> b(dim1,dim1,dim1,dim1);\r\n    LibMIA::SparseMIA<_data_type,4> b2(dim2,dim2,dim1,dim1);\r\n    //result of a solution of sparse equations is set to dense\r\n    LibMIA::DenseMIA<_data_type,4> c(dim1,dim1,dim1,dim1);\r\n\r\n\r\n    double _prob=0.4;\r\n    bool flag=true;\r\n    random_mia(dense_b,_prob);\r\n    while(flag){\r\n        random_mia(dense_a,_prob);\r\n\r\n        dense_c(i,j,m,n)=dense_a(i,j,k,l)|dense_b(k,l,m,n);\r\n        if (dense_c.solveInfo()==LibMIA::FullyRanked)\r\n            flag=false;\r\n\r\n    }\r\n    a=dense_a;\r\n    b=dense_b;\r\n    c(i,j,m,n)=a(i,j,k,l)|b(k,l,m,n);\r\n    BOOST_CHECK_MESSAGE(c.fuzzy_equals(dense_c,test_precision<_data_type>()),std::string(\"Inner/Outer Product Inverse 1 for \")+typeid(_data_type).name() );\r\n\r\n    flag=true;\r\n    while(flag){\r\n\r\n\r\n        dense_c(i,j,m,n)=dense_a(i,k,j,l)|dense_b(k,l,m,n);\r\n        if (dense_c.solveInfo()==LibMIA::FullyRanked)\r\n            break;\r\n        random_mia(dense_a,_prob);\r\n    }\r\n    a=dense_a;\r\n    c(i,j,m,n)=a(i,k,j,l)|b(k,l,m,n);\r\n\r\n    BOOST_CHECK_MESSAGE(c.fuzzy_equals(dense_c,test_precision<_data_type>()),std::string(\"Inner/Outer Product Inverse 2 for \")+typeid(_data_type).name() );\r\n\r\n    _prob=0.7;\r\n    random_mia(dense_a,_prob);\r\n    flag=true;\r\n    while(flag){\r\n\r\n\r\n        dense_c(i,j,l,m)=dense_a(i,!j,k,!l)|dense_b(k,!j,!l,m);\r\n        if (dense_c.solveInfo()==LibMIA::FullyRanked)\r\n            break;\r\n\r\n        random_mia(dense_a,_prob);\r\n    }\r\n    a=dense_a;\r\n    c(i,j,l,m)=a(i,!j,k,!l)|b(k,!j,!l,m);\r\n\r\n    BOOST_CHECK_MESSAGE(c.fuzzy_equals(dense_c,test_precision<_data_type>()),std::string(\"Inner/Outer/Inter Product Inverse 1 for \")+typeid(_data_type).name() );\r\n\r\n    flag=true;\r\n    while(flag){\r\n\r\n\r\n        dense_c(i,j,l,m)=dense_a(!i,!j,k,l)|dense_b(m,!j,k,!i);\r\n        if (dense_c.solveInfo()==LibMIA::FullyRanked)\r\n            break;\r\n        random_mia(dense_a,_prob);\r\n    }\r\n    a=dense_a;\r\n    c(i,j,l,m)=a(!i,!j,k,l)|b(m,!j,k,!i);\r\n\r\n    BOOST_CHECK_MESSAGE(c.fuzzy_equals(dense_c,test_precision<_data_type>()),std::string(\"Inner/Outer/Inter Product Inverse 2 for \")+typeid(_data_type).name() );\r\n\r\n\r\n//\r\n//    c(i,j,m,n)=a2(k,l,i,j)|b2(k,l,m,n);\r\n//    //test with normal equations\r\n//    d(o,p,m,n)=a2(k,l,o,p)*a2(k,l,i,j)*c(i,j,m,n);\r\n//    d2(i,j,m,n)=a2(k,l,i,j)*b2(k,l,m,n);\r\n//    BOOST_CHECK_MESSAGE(d.fuzzy_equals(d2,test_precision<_data_type>()),std::string(\"Inner/Outer Product Least Squares 1 for \")+typeid(_data_type).name() );\r\n\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE( SparseMIASolveTests )\n{\n\n\r\n\r\n    //solve_work<double>(10,10);\n    solve_work<float>(10,10);\r\n\r\n\n\n}\n", "meta": {"hexsha": "0bf6b2b214cf3322b7e5ce6626a50b4b5cea7093", "size": 4413, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tests/SparseMIA/sparse_mia_solve_test.cpp", "max_stars_repo_name": "extragoya/LibNT", "max_stars_repo_head_hexsha": "60372bf4e3c5d6665185358c4756da4fe547f093", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-26T05:11:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-26T05:11:32.000Z", "max_issues_repo_path": "src/tests/SparseMIA/sparse_mia_solve_test.cpp", "max_issues_repo_name": "extragoya/LibNT", "max_issues_repo_head_hexsha": "60372bf4e3c5d6665185358c4756da4fe547f093", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/SparseMIA/sparse_mia_solve_test.cpp", "max_forks_repo_name": "extragoya/LibNT", "max_forks_repo_head_hexsha": "60372bf4e3c5d6665185358c4756da4fe547f093", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-09-21T15:38:23.000Z", "max_forks_repo_forks_event_max_datetime": "2017-09-21T15:38:23.000Z", "avg_line_length": 30.2260273973, "max_line_length": 162, "alphanum_fraction": 0.6340358033, "num_tokens": 1407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185944046238982, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.4525525090550237}}
{"text": "#include <cmath>\n#include \"conex/debug_macros.h\"\n#include \"conex/divergence.h\"\n#include \"gtest/gtest.h\"\n#include <Eigen/Dense>\n\nnamespace conex {\n\nusing Eigen::MatrixXd;\n\nbool InLimits(double x, double lower, double upper) {\n  return x >= lower && x <= upper;\n}\n\ndouble Divergence(Eigen::VectorXd gw, double k) {\n  MatrixXd d = k * gw;\n  d.array() -= 1;\n  double dinf = d.array().abs().maxCoeff();\n  return d.squaredNorm() / (1 - dinf);\n}\n\nGTEST_TEST(MuSelection, DivergenceBound) {\n  int n = 3;\n  MatrixXd gw = Eigen::VectorXd::Random(n, 1).array().abs();\n\n  WeightedSlackEigenvalues p;\n  p.frobenius_norm_squared = gw.squaredNorm();\n  p.lambda_max = gw.maxCoeff();\n  p.lambda_min = gw.minCoeff();\n  p.trace = gw.sum();\n  p.rank = gw.rows();\n\n  // Div bound on one branch.\n  double k_ref = 2.0 / (p.lambda_max + p.lambda_min) * .8;\n  double hub_desired = Divergence(gw, k_ref);\n  EXPECT_NEAR(hub_desired, DivergenceUpperBound(k_ref, p), 1e-8);\n  double k = DivergenceUpperBoundInverse(hub_desired, p);\n  EXPECT_NEAR(hub_desired, Divergence(gw, k), 1e-8);\n  EXPECT_TRUE(k >= k_ref);\n\n  // Div bound on the other branch.\n  k_ref = 2.0 / (p.lambda_max + p.lambda_min) * 1.2;\n  hub_desired = Divergence(gw, k_ref);\n  EXPECT_NEAR(hub_desired, DivergenceUpperBound(k_ref, p), 1e-8);\n  k = DivergenceUpperBoundInverse(hub_desired, p);\n  EXPECT_NEAR(hub_desired, DivergenceUpperBound(k, p), 1e-8);\n  EXPECT_TRUE(k >= k_ref);\n\n  // Div bound undefined.\n  k_ref = 1000000;\n  hub_desired = Divergence(gw, k_ref);\n  EXPECT_NEAR(hub_desired, DivergenceUpperBound(k_ref, p), 1e-8);\n  k = DivergenceUpperBoundInverse(hub_desired, p);\n  EXPECT_TRUE(DivergenceUpperBound(k, p) < 0);\n  EXPECT_EQ(k, -1);\n}\n\n}  // namespace conex\n", "meta": {"hexsha": "e95a71fbcbb2d2cc58827639a96c240e60cc358f", "size": 1712, "ext": "cc", "lang": "C++", "max_stars_repo_path": "conex/test/test_divergence.cc", "max_stars_repo_name": "frankpermenter/conex", "max_stars_repo_head_hexsha": "40f8838e6e618bf68df9aae80db7272ff95b7244", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-10-04T20:41:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-04T20:41:20.000Z", "max_issues_repo_path": "conex/test/test_divergence.cc", "max_issues_repo_name": "frankpermenter/conex", "max_issues_repo_head_hexsha": "40f8838e6e618bf68df9aae80db7272ff95b7244", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "conex/test/test_divergence.cc", "max_forks_repo_name": "frankpermenter/conex", "max_forks_repo_head_hexsha": "40f8838e6e618bf68df9aae80db7272ff95b7244", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0169491525, "max_line_length": 65, "alphanum_fraction": 0.691588785, "num_tokens": 553, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.4525525014643238}}
{"text": "#include <stan/math/prim.hpp>\n#include <test/unit/math/prim/prob/vector_rng_test_helper.hpp>\n#include <test/unit/math/prim/prob/util.hpp>\n#include <gtest/gtest.h>\n#include <boost/math/distributions.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <limits>\n#include <vector>\n\nclass LoglogisticTestRig : public VectorRNGTestRig {\n public:\n  LoglogisticTestRig()\n      : VectorRNGTestRig(10000, 10, {2.5, 1.7, 0.2, 0.1, 2.0},\n                         {3, 2, 1, 5, 10, 6}, {-2.5, -1.7, -0.2, -0.1, 0.0},\n                         {-3, -2, -1, -4, -10, 0}, {0.1, 1.0, 2.5, 4.0},\n                         {1, 2, 3, 4}, {-2.7, -1.5, -0.5, 0.0},\n                         {-3, -2, -1, 0}) {}\n\n  template <typename T1, typename T2, typename T3, typename T_rng>\n  auto generate_samples(const T1& alpha, const T2& beta, const T3& unused,\n                        T_rng& rng) const {\n    return stan::math::loglogistic_rng(alpha, beta, rng);\n  }\n};\n\ndouble icdf(double x, double alpha, double beta) {\n  return alpha * pow(x / (1 - x), 1 / beta);\n}\n\nTEST(ProbDistributionsLoglogistic, errorCheck) {\n  check_dist_throws_all_types(LoglogisticTestRig());\n}\n\nTEST(ProbDistributionsLoglogistic, error_check) {\n  boost::random::mt19937 rng;\n  EXPECT_NO_THROW(stan::math::loglogistic_rng(10.0, 2.0, rng));\n\n  EXPECT_THROW(stan::math::loglogistic_rng(2.0, -1.0, rng), std::domain_error);\n  EXPECT_THROW(stan::math::loglogistic_rng(-2.0, 1.0, rng), std::domain_error);\n  EXPECT_THROW(\n      stan::math::loglogistic_rng(10, stan::math::positive_infinity(), rng),\n      std::domain_error);\n  EXPECT_THROW(\n      stan::math::loglogistic_rng(stan::math::positive_infinity(), 2, rng),\n      std::domain_error);\n}\n\nTEST(ProbDistributionsLoglogistic, test_sampling_icdf) {\n  for (double p : {0.0, 0.1, 0.2, 0.5, 0.7, 0.9, 0.99}) {\n    for (double alpha : {1.11, 0.13, 1.2, 4.67}) {\n      for (double beta : {0.11, 1.33, 2.0, 3.2}) {\n        double x = icdf(p, alpha, beta);\n        EXPECT_FLOAT_EQ(stan::math::loglogistic_cdf(x, alpha, beta), p);\n      }\n    }\n  }\n}\n\nTEST(ProbDistributionsLoglogistic, chiSquareGoodnessFitTest) {\n  boost::random::mt19937 rng;\n  int N = 10000;\n  int K = stan::math::round(2 * std::pow(N, 0.4));\n\n  std::vector<double> samples;\n  for (int i = 0; i < N; ++i) {\n    samples.push_back(stan::math::loglogistic_rng(1.2, 2.0, rng));\n  }\n  std::vector<double> quantiles;\n  for (int i = 1; i < K; ++i) {\n    double frac = static_cast<double>(i) / K;\n    quantiles.push_back(icdf(frac, 1.2, 2.0));\n  }\n  quantiles.push_back(std::numeric_limits<double>::max());\n\n  // Assert that they match\n  assert_matches_quantiles(samples, quantiles, 1e-6);\n}\n", "meta": {"hexsha": "94a38ea4cc7b46c26453cd666195480419e76ae2", "size": 2648, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/prim/prob/loglogistic_test.cpp", "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": "test/unit/math/prim/prob/loglogistic_test.cpp", "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": "test/unit/math/prim/prob/loglogistic_test.cpp", "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": 33.9487179487, "max_line_length": 79, "alphanum_fraction": 0.621978852, "num_tokens": 922, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185944046238981, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.45255249906847805}}
{"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#include <boost/random/linear_congruential.hpp>\n#include <boost/random/uniform_int.hpp>\n#include <boost/random/uniform_real.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <boost/generator_iterator.hpp>\n#include <boost/random/mersenne_twister.hpp>\n\n#include <vector>\n\n#include \"CppProject/randomGen.hpp\"\n\nnamespace randomGen\n{\n\ttypedef double Real;\n\ttypedef std::vector< Real > Vector2;\n\ttypedef std::vector< Real > VectorLong;\n\ttypedef boost::mt19937 generator_type; // mt19937 is a psuedo random number generator algorithm present in the boost library\n\n\tvoid randomGen( const Vector2 range, const int limit, VectorLong& output )\n\t{\n\t\t// generator type defined and initialized by a seed value\n\t\tgenerator_type generator( 900 ); // don't change the seed value while debugging otherwise the psuedo random generated numbers will change\n\t\t// define uniform random number distribution which produces type double values\n\t\t// between [min,max) for each orbital element. For more details please refer to \n\t\t// the following web link:\n\t\t// http://www.boost.org/doc/libs/1_60_0/libs/random/example/random_demo.cpp\n\t\tboost::uniform_real<> distribution( range[ 0 ], range[ 1 ] );\n\t\tboost::variate_generator<generator_type&, boost::uniform_real<> > uniform(generator, distribution);\n\t\tfor(int i = 0; i < limit; i++)\n\t\t{\n\t\t\toutput[ i ]\t= uniform();\n\t\t} \n\t}\n\n\tvoid randomGenWithSeed( const Vector2 range, const int limit, VectorLong& output, const int seed )\n\t{\n\t\t// generator type defined and initialized by a seed value\n\t\tgenerator_type generator( seed ); \n\t\t// define uniform random number distribution which produces type double values\n\t\t// between [min,max) for each orbital element. For more details please refer to \n\t\t// the following web link:\n\t\t// http://www.boost.org/doc/libs/1_60_0/libs/random/example/random_demo.cpp\n\t\tboost::uniform_real<> distribution( range[ 0 ], range[ 1 ] );\n\t\tboost::variate_generator<generator_type&, boost::uniform_real<> > uniform(generator, distribution);\n\t\tfor(int i = 0; i < limit; i++)\n\t\t{\n\t\t\toutput[ i ]\t= uniform();\n\t\t} \n\t}\n} // namespace randomGen", "meta": {"hexsha": "f45f19f616d4e87acf31e580f6cfef3e438fa185", "size": 2292, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/randomGen.cpp", "max_stars_repo_name": "abhi-agrawal/ATOM_ADR", "max_stars_repo_head_hexsha": "b3bfe9f0ff75bd188a06422342b3eec391942db9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/randomGen.cpp", "max_issues_repo_name": "abhi-agrawal/ATOM_ADR", "max_issues_repo_head_hexsha": "b3bfe9f0ff75bd188a06422342b3eec391942db9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/randomGen.cpp", "max_forks_repo_name": "abhi-agrawal/ATOM_ADR", "max_forks_repo_head_hexsha": "b3bfe9f0ff75bd188a06422342b3eec391942db9", "max_forks_repo_licenses": ["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.9285714286, "max_line_length": 139, "alphanum_fraction": 0.7412739965, "num_tokens": 568, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708562, "lm_q2_score": 0.6297746004557471, "lm_q1q2_score": 0.4525524964710512}}
{"text": "#include <mex.h> \n#include <math.h>\n#include <Eigen/Dense>\n#include <iostream>\n#include <stdio.h>\n\n\nusing namespace Eigen;\nusing namespace std;\n\n\nvoid mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])\n{\n\n    mxArray *vers_mex, *tets_mex;\n   \n    char *name;\n    double *vers, *tets;\n    \n    name = mxArrayToString(prhs[0]);\n    \n    mexPrintf(\"%s\\n\", name);\n    \n    int ver_num, tet_num;\n    float x, y, z;\n    int i1, i2, i3, i4;\n    \n    FILE* tet_file = fopen(name, \"rt\");\n    \n    fscanf(tet_file, \"#num of vertex: %d\\n\", &ver_num);\n    fscanf(tet_file, \"#num of tetrahedra: %d\\n\\n\", &tet_num);\n    \n    MatrixXd ver = MatrixXd::Zero(ver_num, 3);\n    MatrixXi tet = MatrixXi::Zero(tet_num, 4);\n    \n    for(int i = 0; i < ver_num; i++)\n    {\n        fscanf(tet_file, \"%f %f %f\\n\", &x, &y, &z);\n        \n        ver(i, 0) = x;\n        ver(i, 1) = y;\n        ver(i, 2) = z;\n    }\n    \n    fscanf(tet_file, \"\\n\");\n    \n    for(int i = 0; i < tet_num; i++)\n    {\n        fscanf(tet_file, \"%d %d %d %d\\n\", &i1, &i2, &i3, &i4);\n        \n        tet(i, 0) = i1;\n        tet(i, 1) = i2;\n        tet(i, 2) = i3;\n        tet(i, 3) = i4;\n    }\n    \n    fclose(tet_file);\n    \n    vers_mex = plhs[0] = mxCreateDoubleMatrix(ver.rows() * 3, 1, mxREAL);\n    tets_mex = plhs[1] = mxCreateDoubleMatrix(tet.rows() * 4, 1, mxREAL);\n    \n    vers = mxGetPr(vers_mex);\n    tets = mxGetPr(tets_mex);\n    \n    for(int i = 0; i < ver.rows(); i++)\n    {\n        vers[i] = ver(i, 0);\n        vers[ver.rows() + i] = ver(i, 1);\n        vers[2 * ver.rows() + i] = ver(i, 2);\n    }\n    \n    for(int i = 0; i < tet.rows(); i++)\n    {\n        tets[i] = tet(i, 0);\n        tets[tet.rows() + i] = tet(i, 1);\n        tets[2 * tet.rows() + i] = tet(i, 2);\n        tets[3 * tet.rows() + i] = tet(i, 3);\n    }\n    \n    return;\n    \n}", "meta": {"hexsha": "38d1956dd5cb64495d8a1760203e019311087b8f", "size": 1823, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/3D/lib/mex/load_tet_mex.cpp", "max_stars_repo_name": "ErisZhang/BCQN", "max_stars_repo_head_hexsha": "6c103e0e173bb825e4207b282a0cba2ce5d10e24", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2019-07-23T16:35:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-04T11:47:42.000Z", "max_issues_repo_path": "code/3D/lib/mex/load_tet_mex.cpp", "max_issues_repo_name": "ErisZhang/BCQN", "max_issues_repo_head_hexsha": "6c103e0e173bb825e4207b282a0cba2ce5d10e24", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-07-10T12:12:18.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-10T12:12:18.000Z", "max_forks_repo_path": "code/3D/lib/mex/load_tet_mex.cpp", "max_forks_repo_name": "ErisZhang/BCQN", "max_forks_repo_head_hexsha": "6c103e0e173bb825e4207b282a0cba2ce5d10e24", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-02-21T06:12:40.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-27T09:58:32.000Z", "avg_line_length": 22.2317073171, "max_line_length": 76, "alphanum_fraction": 0.4810751509, "num_tokens": 649, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943805178139, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.4525524938736239}}
{"text": "#ifndef HTOOL_SPMATRIX_HPP\n#define HTOOL_SPMATRIX_HPP\n\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <cassert>\n#include <complex>\n#include <iostream>\n#include <vector>\n//#include \"point.hpp\"\n\nnamespace htool {\n//================================//\n//      DECLARATIONS DE TYPE      //\n//================================//\n\n//typedef vector<Cplx>    vectCplx;\n\n//=================================================================//\n//                         CLASS SPARSE MATRIX\n/******************************************************************/ /**\n* Class for sparse matrices (in coordinate list format).\n* Its member objects are:\n*   - I: vector of the row indices,\n*   - J: vector of the column indices,\n*   - K: vector of the (complex) coefficients of the matrix,\n*   - nr: the number of rows,\n*   - nc: the number of columns.\n*********************************************************************/\n\nclass SpMatrix {\n\n  private:\n    std::vector<int> I, J;\n    std::vector<Cplx> K;\n    int nr;\n    int nc;\n\n  public:\n    //! ### Default constructor\n    /*!\n\t Initializes the matrix to the size 0*0.\n  */\n    SpMatrix() : nr(0), nc(0) {}\n\n    //! ### Another constructor\n    /*!\n\t Initializes the matrix with _nrp_ rows and _ncp_ columns,\n     _Ip_ as vector of the row indices, _Jp_ as vector of the column indices,\n     _Kp_ as vector of the coefficients of the matrix.\n  */\n    SpMatrix(const std::vector<int> &Ip, const std::vector<int> &Jp, std::vector<Cplx> &Kp, const int &nrp, const int &ncp) : I(Ip), J(Jp), K(Kp), nr(nrp), nc(ncp) {}\n\n    //! ### Copy constructor\n    /*!\n  */\n    SpMatrix(const SpMatrix &A) : I(A.I), J(A.J), K(A.K), nr(A.nr), nc(A.nc) {}\n\n    //! ### Assignement operator with a sparse matrix input argument\n    /*!\n\t Copies the _I_, _J_, _K_ of the input _A_ argument\n\t (which is a sparse matrix) into the vectors of\n\t calling instance.\n  */\n    void operator=(const SpMatrix &A) {\n        assert(nr == A.nr && nc == A.nc);\n        I = A.I;\n        J = A.J;\n        K = A.K;\n    }\n\n    //! ### Matrix-vector product\n    /*!\n\t The input parameter _u_ is the input vector\n\t (i.e. the right operand).\n  */\n    vectCplx operator*(const vectCplx &u) {\n        int ncoef = I.size();\n        vectCplx v(nr, 0.);\n        for (int j = 0; j < ncoef; j++)\n            v[I[j]] += K[j] * u[J[j]];\n        return v;\n    }\n\n    //! ### Matrix-vector product\n    /*!\n\t Another instanciation of the matrix-vector product\n\t that avoids the generation of temporary instance for the\n\t output vector. This routine achieves the operation\n\n\t lhs = m*rhs\n\n\t The left and right operands (_lhs_ and _rhs_) are templated\n\t and can then be of any type (not necessarily of type vectCplx).\n  */\n    template <typename LhsType, typename RhsType>\n    friend void MvProd(LhsType &lhs, const SpMatrix &m, const RhsType &rhs) {\n        int ncoef = m.I.size();\n        for (int j = 0; j < ncoef; j++)\n            lhs[m.I[j]] += m.K[j] * rhs[m.J[j]];\n    }\n\n    //! ### Modifies the size of the matrix\n    /*!\n     Changes the size of the matrix so that\n     the number of rows is set to _nbr_ and\n     the number of columns is set to _nbc_ and\n     the sizes of the 3 member vectors are set to _nbcoef_.\n     */\n    void resize(const int nbr, const int nbc, const int nbcoef) {\n        assert(nbcoef <= nbr * nbc);\n        nr = nbr;\n        nc = nbc;\n        I.resize(nbcoef);\n        J.resize(nbcoef);\n        K.resize(nbcoef);\n    }\n\n    //! ### Access to row indices\n    /*!\n     Returns the _i_th row index of the input argument _A_.\n     */\n    int &I_(const int i) {\n        assert(i < I.size());\n        return I[i];\n    }\n\n    //! ### Access to column indices\n    /*!\n     Returns the _i_th column index of the input argument _A_.\n     */\n    int &J_(const int i) {\n        assert(i < J.size());\n        return J[i];\n    }\n\n    //! ### Access to coefficients\n    /*!\n     Returns the _i_th coefficients inside _K_ of the input argument _A_.\n     */\n    Cplx &K_(const int i) {\n        assert(i < K.size());\n        return K[i];\n    }\n\n    //! ### Access to number of rows\n    /*!\n\t Returns the number of rows of the input argument _A_.\n  */\n    friend const int &nb_rows(const SpMatrix &A) { return A.nr; }\n\n    //! ### Access to number of columns\n    /*!\n\t Returns the number of columns of the input argument _A_.\n  */\n    friend const int &nb_cols(const SpMatrix &A) { return A.nc; }\n\n    //! ### Access to number of non zero coefficients\n    /*!\n     Returns the number of non zero coefficients of the input argument _A_.\n     */\n    friend int nb_coeff(const SpMatrix &A) { return A.I.size(); }\n\n    //! ### Compute the compression rate\n    /*!\n     1 - number of non zero coefficients/(nb_rows*nb_columns)\n     */\n    friend Real CompressionRate(const SpMatrix &A) {\n        Real comp;\n        comp = ((double)A.I.size()) / ((double)(A.nr * A.nc)); // number of non zero coefficients/(nb_rows*nb_columns)\n        return (1 - comp);\n    }\n};\n\n} // namespace htool\n#endif\n", "meta": {"hexsha": "0bf7fdaebea57cce3467b8244021a8f7b5d7abe2", "size": 4988, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/htool/types/sparsematrix.hpp", "max_stars_repo_name": "htool-ddm/htool", "max_stars_repo_head_hexsha": "e4dbec7c08c5008e62344fd0d5ebfdf95ef8863f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2020-05-06T15:20:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T10:27:56.000Z", "max_issues_repo_path": "include/htool/types/sparsematrix.hpp", "max_issues_repo_name": "htool-ddm/htool", "max_issues_repo_head_hexsha": "e4dbec7c08c5008e62344fd0d5ebfdf95ef8863f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2020-05-25T13:59:11.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-02T16:40:45.000Z", "max_forks_repo_path": "include/htool/types/sparsematrix.hpp", "max_forks_repo_name": "PierreMarchand20/htool", "max_forks_repo_head_hexsha": "b6e91690f8d7c20d67dfb3b8db2e7ea674405a37", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-04-25T07:44:35.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-05T16:57:00.000Z", "avg_line_length": 28.1807909605, "max_line_length": 166, "alphanum_fraction": 0.5549318364, "num_tokens": 1304, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943805178139, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.4525524938736239}}
{"text": "#include <mass.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n\nBOOST_AUTO_TEST_SUITE(mass);\n\nBOOST_AUTO_TEST_CASE(translate)\n{\n  \n  mass::Properties<double> B = mass::compute_sphere(1.0,1.0);\n  \n  double const dx   = 1.0;\n  double const dy   = 2.0;\n  double const dz   = 3.0;\n  \n  BOOST_CHECK( B.is_body_space() );  \n\n  mass::Properties<double> M = mass::translate_to_model_frame( dx, dy, dz, B);  \n  \n  BOOST_CHECK( M.is_model_space() );  \n\n  BOOST_CHECK(M.m_Ixx > B.m_Ixx);\n  BOOST_CHECK(M.m_Iyy > B.m_Iyy);\n  BOOST_CHECK(M.m_Izz > B.m_Izz);\n  BOOST_CHECK(M.m_Ixy < B.m_Ixy);\n  BOOST_CHECK(M.m_Ixz < B.m_Ixz);\n  BOOST_CHECK(M.m_Iyz < B.m_Iyz);\n  \n  BOOST_CHECK_CLOSE(M.m_m, B.m_m, 0.01 );\n  \n  BOOST_CHECK_CLOSE(M.m_x, dx, 0.01 );\n  BOOST_CHECK_CLOSE(M.m_y, dy, 0.01 );\n  BOOST_CHECK_CLOSE(M.m_z, dz, 0.01 );\n  \n  BOOST_CHECK_CLOSE(M.m_Qs, 1.0, 0.01 );\n  BOOST_CHECK_CLOSE(M.m_Qx, 0.0, 0.01 );\n  BOOST_CHECK_CLOSE(M.m_Qy, 0.0, 0.01 );\n  BOOST_CHECK_CLOSE(M.m_Qz, 0.0, 0.01 );\n\n  mass::Properties<double> C = mass::translate_to_body_frame( M);  \n\n  BOOST_CHECK_CLOSE(C.m_Ixx , B.m_Ixx, 0.01);\n  BOOST_CHECK_CLOSE(C.m_Iyy , B.m_Iyy, 0.01);\n  BOOST_CHECK_CLOSE(C.m_Izz , B.m_Izz, 0.01);\n  BOOST_CHECK_CLOSE(C.m_Ixy , B.m_Ixy, 0.01);\n  BOOST_CHECK_CLOSE(C.m_Ixz , B.m_Ixz, 0.01);\n  BOOST_CHECK_CLOSE(C.m_Iyz , B.m_Iyz, 0.01);\n  BOOST_CHECK_CLOSE(C.m_m   , B.m_m  , 0.01 );\n  BOOST_CHECK_CLOSE(C.m_x   , 0.0    , 0.01 );\n  BOOST_CHECK_CLOSE(C.m_y   , 0.0    , 0.01 );\n  BOOST_CHECK_CLOSE(C.m_z   , 0.0    , 0.01 );\n  BOOST_CHECK_CLOSE(C.m_Qs  , 1.0    , 0.01 );\n  BOOST_CHECK_CLOSE(C.m_Qx  , 0.0    , 0.01 );\n  BOOST_CHECK_CLOSE(C.m_Qy  , 0.0    , 0.01 );\n  BOOST_CHECK_CLOSE(C.m_Qz  , 0.0    , 0.01 );\n  \n  BOOST_CHECK( C.is_body_space() );  \n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "391a592e2d130426d4488d44e402cdea9c6aaab9", "size": 1931, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/SIMULATION/MASS/unit_tests/mass_translate/mass_translate.cpp", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-11-27T09:44:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-13T00:24:21.000Z", "max_issues_repo_path": "PROX/SIMULATION/MASS/unit_tests/mass_translate/mass_translate.cpp", "max_issues_repo_name": "erleben/matchstick", "max_issues_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_issues_repo_licenses": ["MIT"], "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/SIMULATION/MASS/unit_tests/mass_translate/mass_translate.cpp", "max_forks_repo_name": "erleben/matchstick", "max_forks_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_forks_repo_licenses": ["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.7076923077, "max_line_length": 80, "alphanum_fraction": 0.6649404454, "num_tokens": 698, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.6297745935070808, "lm_q1q2_score": 0.45255249147777854}}
{"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#pragma once\n\n//#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/inversive_congruential.hpp>\n\n#include <boost/random/uniform_int.hpp>\n#include <boost/random/uniform_real.hpp>\n#include <boost/random/variate_generator.hpp>\n\n#include <glm/fwd.hpp>\n\n\n#include \"NBBox.hpp\"\n\n#include \"NPY_API_EXPORT.hh\"\n\nclass NPY_API NGenerator \n{\n    //typedef boost::mt19937          RNG_t;\n    typedef boost::hellekalek1995   RNG_t ; \n    typedef boost::uniform_real<>   Distrib_t;\n    typedef boost::variate_generator< RNG_t, Distrib_t > Generator_t ;\n\n    public:\n        NGenerator(const nbbox& bb);\n        void operator()(nvec3& xyz);\n        void operator()(glm::vec3& xyz);\n    private:\n        nbbox m_bb ; \n        nvec3 m_side ; \n        RNG_t m_rng;\n        Distrib_t m_dist ;\n        Generator_t m_gen ; \n};\n\n\n\n", "meta": {"hexsha": "9281f573bfbb87462ce2a91a261df3a52ebef482", "size": 1540, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "npy/NGenerator.hpp", "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/NGenerator.hpp", "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/NGenerator.hpp", "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": 27.0175438596, "max_line_length": 77, "alphanum_fraction": 0.6935064935, "num_tokens": 379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4525292620451532}}
{"text": "// author: Danny Rakita\n\n#include <boost/python.hpp>\n#include <boost/python/numpy.hpp>\n#include <string>\n#include <math.h>\n#include <vector>\n#include <Eigen/Dense>\n\nusing namespace std;\nnamespace np = boost::python::numpy;\nnamespace p = boost::python;\n\nint main(int argc, char **argv) {\n  Py_Initialize();\n  np::initialize();\n}\n\nstring greet() {\n  return \"hello!\";\n}\n\ninline double SIGN(double x) {\n\treturn (x >= 0.0f) ? +1.0 : -1.0;\n}\n\ninline double NORM(double a, double b, double c, double d) {\n\treturn sqrt(a * a + b * b + c * c + d * d);\n}\n// quaternion = [w, x, y, z]'\nvector<double> mRot2Quat(np::ndarray m) {\n\tdouble r11 = p::extract<double>(m[0][0]);\n\tdouble r12 = p::extract<double>(m[0][1]);\n\tdouble r13 = p::extract<double>(m[0][2]);\n\tdouble r21 = p::extract<double>(m[1][0]);\n\tdouble r22 = p::extract<double>(m[1][1]);\n\tdouble r23 = p::extract<double>(m[1][2]);\n\tdouble r31 = p::extract<double>(m[2][0]);\n\tdouble r32 = p::extract<double>(m[2][1]);\n\tdouble r33 = p::extract<double>(m[2][2]);\n\tdouble q0 = (r11 + r22 + r33 + 1.0) / 4.0;\n\tdouble q1 = (r11 - r22 - r33 + 1.0) / 4.0;\n\tdouble q2 = (-r11 + r22 - r33 + 1.0) / 4.0;\n\tdouble q3 = (-r11 - r22 + r33 + 1.0) / 4.0;\n\tif (q0 < 0.0) {\n\t\tq0 = 0.0;\n\t}\n\tif (q1 < 0.0) {\n\t\tq1 = 0.0;\n\t}\n\tif (q2 < 0.0) {\n\t\tq2 = 0.0;\n\t}\n\tif (q3 < 0.0) {\n\t\tq3 = 0.0;\n\t}\n\tq0 = sqrt(q0);\n\tq1 = sqrt(q1);\n\tq2 = sqrt(q2);\n\tq3 = sqrt(q3);\n\tif (q0 >= q1 && q0 >= q2 && q0 >= q3) {\n\t\tq0 *= +1.0;\n\t\tq1 *= SIGN(r32 - r23);\n\t\tq2 *= SIGN(r13 - r31);\n\t\tq3 *= SIGN(r21 - r12);\n\t}\n\telse if (q1 >= q0 && q1 >= q2 && q1 >= q3) {\n\t\tq0 *= SIGN(r32 - r23);\n\t\tq1 *= +1.0;\n\t\tq2 *= SIGN(r21 + r12);\n\t\tq3 *= SIGN(r13 + r31);\n\t}\n\telse if (q2 >= q0 && q2 >= q1 && q2 >= q3) {\n\t\tq0 *= SIGN(r13 - r31);\n\t\tq1 *= SIGN(r21 + r12);\n\t\tq2 *= +1.0;\n\t\tq3 *= SIGN(r32 + r23);\n\t}\n\telse if (q3 >= q0 && q3 >= q1 && q3 >= q2) {\n\t\tq0 *= SIGN(r21 - r12);\n\t\tq1 *= SIGN(r31 + r13);\n\t\tq2 *= SIGN(r32 + r23);\n\t\tq3 *= +1.0;\n\t}\n\telse {\n\t\tprintf(\"coding error\\n\");\n\t}\n\tdouble r = NORM(q0, q1, q2, q3);\n\tq0 /= r;\n\tq1 /= r;\n\tq2 /= r;\n\tq3 /= r;\n\n\tvector<double> res(4);\n\tres[0] = q0; res[1] = q1; res[2] = q2; res[3] = q3;\n\n\treturn res;\n}\n\nvector<double> quaternion_multiply(vector<double> q1, vector<double> q0) {\n    vector<double> q(4);\n    q[0] = -q1[1]*q0[1] - q1[2]*q0[2] - q1[3]*q0[3] + q1[0]*q0[0];\n    q[1] =  q1[1]*q0[0] + q1[2]*q0[3] - q1[3]*q0[2] + q1[0]*q0[1];\n    q[2] = -q1[1]*q0[3] + q1[2]*q0[0] + q1[3]*q0[1] + q1[0]*q0[2];\n    q[3] =  q1[1]*q0[2] - q1[2]*q0[1] + q1[3]*q0[0] + q1[0]*q0[3];\n    return q;\n}\n\nvector<double> quaternion_inverse(vector<double> q) {\n    vector<double> q_i(4);\n    q_i[0] = q[0];\n    q_i[1] = -q[1];\n    q_i[2] = -q[2];\n    q_i[3] = -q[3];\n    double dot = q_i[0]*q_i[0] + q_i[1]*q_i[1] + q_i[2]*q_i[2] + q_i[3]*q_i[3];\n    q_i[0] = q_i[0] / dot;\n    q_i[1] = q_i[1] / dot;\n    q_i[2] = q_i[2] / dot;\n    q_i[3] = q_i[3] / dot;\n    return q_i;\n}\n\nvector<double> quaternion_log(vector<double> q) {\n    vector<double> rot_vec(3);\n    rot_vec[0] = q[1]; rot_vec[1] = q[2]; rot_vec[2] = q[3];\n    if(abs(q[0]) < 1.0) {\n        double a = acos(q[0]);\n        double sina = sin(a);\n        if (abs(sina) >= 0.05) {\n           double c = a/sina;\n           rot_vec[0] *= c;\n           rot_vec[1] *= c;\n           rot_vec[2] *= c;\n        }\n    }\n\n    return rot_vec;\n\n}\n\nvector<double> quaternion_disp(vector<double> q1, vector<double> q2) {\n    vector<double> inv = quaternion_inverse(q1);\n    vector<double> m = quaternion_multiply(inv, q2);\n    return quaternion_log(m);\n}\n\ndouble orientation_multiEE_obj(p::object frames, p::object goal_quats, p::list weights) {\n    double num_ee = p::len(frames);\n\n    double sum = 0.0;\n\n    for(int q=0; q < num_ee; q++) {\n        p::list f = p::extract<p::list>(frames[q]);\n\n        p::list rot_mats = p::extract<p::list>(f[1]);\n        int num_jts = p::len(rot_mats);\n\n        np::ndarray ee_rot = p::extract<np::ndarray>(rot_mats[num_jts-1]);\n\n        vector<double> ee_quat = mRot2Quat(ee_rot);\n        vector<double> ee_quat2(4);\n        ee_quat2[0] = -ee_quat[0];\n        ee_quat2[1] = -ee_quat[1];\n        ee_quat2[2] = -ee_quat[2];\n        ee_quat2[3] = -ee_quat[3];\n\n        // ee_quat2[0] = ee_quat[0];\n        // ee_quat2[1] = ee_quat[1];\n        // ee_quat2[2] = ee_quat[2];\n        // ee_quat2[3] = ee_quat[3];\n\n        p::object goal_quat_py = p::extract<p::object>(goal_quats[q]);\n        vector<double> goal_quat(4);\n        goal_quat[0] = p::extract<double>(goal_quat_py[0]);\n        goal_quat[1] = p::extract<double>(goal_quat_py[1]);\n        goal_quat[2] = p::extract<double>(goal_quat_py[2]);\n        goal_quat[3] = p::extract<double>(goal_quat_py[3]);\n\n        vector<double> r1 = quaternion_disp(goal_quat, ee_quat);\n        vector<double> r2 = quaternion_disp(goal_quat, ee_quat2);\n\n        double disp = sqrt(r1[0]*r1[0] + r1[1]*r1[1] + r1[2]*r1[2]);\n        double disp2 = sqrt(r2[0]*r2[0] + r2[1]*r2[1] + r2[2]*r2[2]);\n\n        sum += p::extract<double>(weights[q])*min(disp, disp2);\n\n    }\n\n    return sum;\n}\n\ndouble position_multiEE_obj(p::object frames, p::object eeGoals, p::list weights) {\n    double num_ee = p::len(frames);\n\n    double sum = 0.0;\n\n    for(int i = 0; i < num_ee; i++) {\n        p::list f = p::extract<p::list>(frames[i]);\n\n        p::list positions = p::extract<p::list>(f[0]);\n        int num_jts = p::len(positions);\n\n        np::ndarray eePos = p::extract<np::ndarray>(positions[num_jts-1]);\n\n        double eX = p::extract<double>(eePos[0]);\n        double eY = p::extract<double>(eePos[1]);\n        double eZ = p::extract<double>(eePos[2]);\n\n        np::ndarray eeGoal = p::extract<np::ndarray>(eeGoals[i]);\n        double gX = p::extract<double>(eeGoal[0]);\n        double gY = p::extract<double>(eeGoal[1]);\n        double gZ = p::extract<double>(eeGoal[2]);\n\n        double val = pow(eX-gX, 2.0) + pow(eY-gY, 2.0) + pow(eZ-gZ, 2.0);\n        val = sqrt(val);\n        sum += p::extract<double>(weights[i]) * val;\n    }\n\n    return sum;\n}\n\ndouble min_jt_jerk_obj(np::ndarray x, p::object prev, p::object prev2, p::object prev3) {\n    int vec_len = (int) p::len(x);\n\n    double sum = 0.0;\n\n    for(int i=0; i < vec_len; i++) {\n        double v1 = p::extract<double>(x[i]);\n        double v2 = p::extract<double>(prev[i]);\n        double v3 = p::extract<double>(prev2[i]);\n        double v4 = p::extract<double>(prev3[i]);\n\n        double vel3 = v3 - v4;\n        double vel2 = v2 - v3;\n        double vel1 = v1 - v2;\n\n        sum += pow((vel2 - vel3) - (vel1 - vel2), 2.0);\n    }\n\n    return sqrt(sum);\n}\n\ndouble min_jt_accel_obj(np::ndarray x, p::object prev, p::object prev2) {\n    int vec_len = (int) p::len(x);\n\n    double sum = 0.0;\n\n    for(int i=0; i < vec_len; i++) {\n        double v1 = p::extract<double>(x[i]);\n        double v2 = p::extract<double>(prev[i]);\n        double v3 = p::extract<double>(prev2[i]);\n\n        sum += pow((v2 - v3) - (v1 - v2), 2.0);\n    }\n\n    return sqrt(sum);\n}\n\ndouble min_jt_vel_obj(np::ndarray x, p::object prev) {\n    int vec_len = (int) p::len(x);\n\n    double sum = 0.0;\n\n    for(int i=0; i < vec_len; i++) {\n        double v1 = p::extract<double>(x[i]);\n        double v2 = p::extract<double>(prev[i]);\n\n        sum += pow((v1-v2), 2.0);\n    }\n    return sqrt(sum);\n}\n\n\ndouble nloss(double x_val, double t, double d, double c, double f, double g) {\n    return -exp( (- pow( (x_val - t), d) ) / (2.0 * pow(c,2.0))) + f * pow( (x_val - t), g);\n}\n\n\n\n\n\nBOOST_PYTHON_MODULE(objectives_ext)\n{\n    using namespace boost::python;\n    def(\"greet\", greet);\n    def(\"orientation_multiEE_obj\",orientation_multiEE_obj);\n    def(\"position_multiEE_obj\", position_multiEE_obj);\n    def(\"min_jt_vel_obj\", min_jt_vel_obj);\n    def(\"min_jt_accel_obj\", min_jt_accel_obj);\n    def(\"min_jt_jerk_obj\", min_jt_jerk_obj);\n    def(\"nloss\", nloss);\n}\n", "meta": {"hexsha": "f8f71104c103e56bba88e27144bd5e62f5450508", "size": 7788, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/RelaxedIK/GROOVE_RelaxedIK/boost/objectives.cpp", "max_stars_repo_name": "nancyhong123/relaxed_ik", "max_stars_repo_head_hexsha": "33b485d6020945c799c074d8a63e311a5d8ecc66", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/RelaxedIK/GROOVE_RelaxedIK/boost/objectives.cpp", "max_issues_repo_name": "nancyhong123/relaxed_ik", "max_issues_repo_head_hexsha": "33b485d6020945c799c074d8a63e311a5d8ecc66", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/RelaxedIK/GROOVE_RelaxedIK/boost/objectives.cpp", "max_forks_repo_name": "nancyhong123/relaxed_ik", "max_forks_repo_head_hexsha": "33b485d6020945c799c074d8a63e311a5d8ecc66", "max_forks_repo_licenses": ["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.5802047782, "max_line_length": 92, "alphanum_fraction": 0.5445557268, "num_tokens": 2926, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4525292620451532}}
{"text": "// This file is part of libigl, a simple c++ geometry processing library.\n// \n// Copyright (C) 2016 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 \"per_vertex_point_to_plane_quadrics.h\"\n#include \"quadric_binary_plus_operator.h\"\n#include <Eigen/QR>\n#include <cassert>\n#include <cmath>\n\n\nIGL_INLINE void igl::per_vertex_point_to_plane_quadrics(\n  const Eigen::MatrixXd & V,\n  const Eigen::MatrixXi & F,\n  const Eigen::MatrixXi & EMAP,\n  const Eigen::MatrixXi & EF,\n  const Eigen::MatrixXi & EI,\n  std::vector<\n    std::tuple<Eigen::MatrixXd,Eigen::RowVectorXd,double> > & quadrics)\n{\n  using namespace std;\n  typedef std::tuple<Eigen::MatrixXd,Eigen::RowVectorXd,double> Quadric;\n  const int dim = V.cols();\n  //// Quadrics per face\n  //std::vector<Quadric> face_quadrics(F.rows());\n  // Initialize each vertex quadric to zeros\n  quadrics.resize(\n    V.rows(),\n    // gcc <=4.8 can't handle initializer lists correctly\n    Quadric{Eigen::MatrixXd::Zero(dim,dim),Eigen::RowVectorXd::Zero(dim),0});\n  Eigen::MatrixXd I = Eigen::MatrixXd::Identity(dim,dim);\n  // Rather initial with zeros, initial with a small amount of energy pull\n  // toward original vertex position\n  const double w = 1e-10;\n  for(int v = 0;v<V.rows();v++)\n  {\n    std::get<0>(quadrics[v]) = w*I;\n    Eigen::RowVectorXd Vv = V.row(v);\n    std::get<1>(quadrics[v]) = w*-Vv;\n    std::get<2>(quadrics[v]) = w*Vv.dot(Vv);\n  }\n  // Generic nD qslim from \"Simplifying Surfaces with Color and Texture\n  // using Quadric Error Metric\" (follow up to original QSlim)\n  for(int f = 0;f<F.rows();f++)\n  {\n    int infinite_corner = -1;\n    for(int c = 0;c<3;c++)\n    {\n      if(\n         std::isinf(V(F(f,c),0)) || \n         std::isinf(V(F(f,c),1)) || \n         std::isinf(V(F(f,c),2)))\n      {\n        assert(infinite_corner == -1 && \"Should only be one infinite corner\");\n        infinite_corner = c;\n      }\n    }\n    // Inputs:\n    //   p  1 by n row point on the subspace \n    //   S  m by n matrix where rows coorespond to orthonormal spanning\n    //     vectors of the subspace to which we're measuring distance (usually\n    //     a plane, m=2)\n    //   weight  scalar weight\n    // Returns quadric triple {A,b,c} so that A-2*b+c measures the quadric\n    const auto subspace_quadric = [&I](\n      const Eigen::RowVectorXd & p,\n      const Eigen::MatrixXd & S,\n      const double  weight)->Quadric\n    {\n      // Dimension of subspace\n      const int m = S.rows();\n      // Weight face's quadric (v'*A*v + 2*b'*v + c) by area\n      // e1 and e2 should be perpendicular\n      Eigen::MatrixXd A = I;\n      Eigen::RowVectorXd b = -p;\n      double c = p.dot(p);\n      for(int i = 0;i<m;i++)\n      {\n        Eigen::RowVectorXd ei = S.row(i);\n        for(int j = 0;j<i;j++) assert(std::abs(S.row(j).dot(ei)) < 1e-10);\n        A += -ei.transpose()*ei;\n        b += p.dot(ei)*ei;\n        c += -pow(p.dot(ei),2);\n      }\n      // gcc <=4.8 can't handle initializer lists correctly: needs explicit\n      // cast\n      return Quadric{ weight*A, weight*b, weight*c };\n    };\n    if(infinite_corner == -1)\n    {\n      // Finite (non-boundary) face\n      Eigen::RowVectorXd p = V.row(F(f,0));\n      Eigen::RowVectorXd q = V.row(F(f,1));\n      Eigen::RowVectorXd r = V.row(F(f,2));\n      Eigen::RowVectorXd pq = q-p;\n      Eigen::RowVectorXd pr = r-p;\n      // Gram Determinant = squared area of parallelogram \n      double area = sqrt(pq.squaredNorm()*pr.squaredNorm()-pow(pr.dot(pq),2));\n      Eigen::RowVectorXd e1 = pq.normalized();\n      Eigen::RowVectorXd e2 = (pr-e1.dot(pr)*e1).normalized();\n      Eigen::MatrixXd S(2,V.cols());\n      S<<e1,e2;\n      Quadric face_quadric = subspace_quadric(p,S,area);\n      // Throw at each corner\n      for(int c = 0;c<3;c++)\n      {\n        quadrics[F(f,c)] = quadrics[F(f,c)] + face_quadric;\n      }\n    }else\n    {\n      // cth corner is infinite --> edge opposite cth corner is boundary\n      // Boundary edge vector\n      const Eigen::RowVectorXd p = V.row(F(f,(infinite_corner+1)%3));\n      Eigen::RowVectorXd ev = V.row(F(f,(infinite_corner+2)%3)) - p;\n      const double length = ev.norm();\n      ev /= length;\n      // Face neighbor across boundary edge\n      int e = EMAP(f+F.rows()*infinite_corner);\n      int opp = EF(e,0) == f ? 1 : 0;\n      int n =  EF(e,opp);\n      int nc = EI(e,opp);\n      assert(\n        ((F(f,(infinite_corner+1)%3) == F(n,(nc+1)%3) && \n          F(f,(infinite_corner+2)%3) == F(n,(nc+2)%3)) || \n          (F(f,(infinite_corner+1)%3) == F(n,(nc+2)%3) \n          && F(f,(infinite_corner+2)%3) == F(n,(nc+1)%3))) && \n        \"Edge flaps not agreeing on shared edge\");\n      // Edge vector on opposite face\n      const Eigen::RowVectorXd eu = V.row(F(n,nc)) - p;\n      assert(!std::isinf(eu(0)));\n      // Matrix with vectors spanning plane as columns\n      Eigen::MatrixXd A(ev.size(),2);\n      A<<ev.transpose(),eu.transpose();\n      // Use QR decomposition to find basis for orthogonal space\n      Eigen::HouseholderQR<Eigen::MatrixXd> qr(A);\n      const Eigen::MatrixXd Q = qr.householderQ();\n      const Eigen::MatrixXd N = \n        Q.topRightCorner(ev.size(),ev.size()-2).transpose();\n      assert(N.cols() == ev.size());\n      assert(N.rows() == ev.size()-2);\n      Eigen::MatrixXd S(N.rows()+1,ev.size());\n      S<<ev,N;\n      Quadric boundary_edge_quadric = subspace_quadric(p,S,length);\n      for(int c = 0;c<3;c++)\n      {\n        if(c != infinite_corner)\n        {\n          quadrics[F(f,c)] = quadrics[F(f,c)] + boundary_edge_quadric;\n        }\n      }\n    }\n  }\n}\n\n", "meta": {"hexsha": "6d1be71b0852373c880a638fa5717918a3b5cef3", "size": 5708, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "igl/per_vertex_point_to_plane_quadrics.cpp", "max_stars_repo_name": "aviadtzemah/animation2", "max_stars_repo_head_hexsha": "9a3f980fbe27672fe71f8f61f73b5713f2af5089", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2392.0, "max_stars_repo_stars_event_min_datetime": "2016-12-17T14:14:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T19:40:40.000Z", "max_issues_repo_path": "igl/per_vertex_point_to_plane_quadrics.cpp", "max_issues_repo_name": "aviadtzemah/animation2", "max_issues_repo_head_hexsha": "9a3f980fbe27672fe71f8f61f73b5713f2af5089", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 106.0, "max_issues_repo_issues_event_min_datetime": "2018-04-19T17:47:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-01T19:44:11.000Z", "max_forks_repo_path": "igl/per_vertex_point_to_plane_quadrics.cpp", "max_forks_repo_name": "aviadtzemah/animation2", "max_forks_repo_head_hexsha": "9a3f980fbe27672fe71f8f61f73b5713f2af5089", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 184.0, "max_forks_repo_forks_event_min_datetime": "2017-11-15T09:55:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T16:30:46.000Z", "avg_line_length": 36.1265822785, "max_line_length": 79, "alphanum_fraction": 0.5907498248, "num_tokens": 1654, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4525292550369162}}
{"text": "#include <frovedis.hpp>\n#include <frovedis/ml/glm/logistic_regression_with_lbfgs.hpp>\n\n#include <boost/program_options.hpp>\n\nusing namespace boost;\nusing namespace frovedis;\nusing namespace std;\n\ndouble to_double(std::string& line) {\n  return boost::lexical_cast<double>(line);\n}\n\nvoid do_train(const string& input, const string& label, const string& output,\n              size_t num_iteration, double alpha, size_t hist_size,\n              const string& regularizer, double regParam, bool intercept,\n              double convTol, MatType mType, bool binary) {\n\n  RegType rt;\n  if(regularizer == \"ZERO\") {\n    rt = ZERO;\n  } else if (regularizer == \"L1\") {\n    rt = L1;\n  } else if (regularizer == \"L2\") {\n    rt = L2;\n  } else {\n    cerr << \"invalid regularization type: \" << regularizer << endl;\n    exit(1);\n  }\n  if(binary) {\n    time_spent t(DEBUG);\n    auto mat = make_crs_matrix_loadbinary<double>(input);\n    t.show(\"load matrix: \");\n    auto lb = make_dvector_loadbinary<double>(label);\n    t.show(\"load label: \");\n    auto lm = logistic_regression_with_lbfgs::train(std::move(mat), lb,\n                                                    num_iteration, alpha,\n                                                    hist_size, regParam,\n                                                    rt, intercept,convTol, mType);\n    t.show(\"train time: \");\n    lm.savebinary(output);\n    t.show(\"save model time: \");\n  } else {\n    time_spent t(DEBUG);\n    auto mat = make_crs_matrix_load<double>(input);\n    t.show(\"load matrix: \");\n    auto lb = make_dvector_loadline(label).map(to_double);\n    t.show(\"load label: \");\n    auto lm = logistic_regression_with_lbfgs::train(std::move(mat), lb,\n                                                    num_iteration, alpha,\n                                                    hist_size, regParam,\n                                                    rt, intercept,convTol, mType);\n    t.show(\"train time: \");\n    lm.save(output);\n    t.show(\"save model time: \");\n  }\n}\n\nvoid do_predict(const string& input, const string& model, const string& output,\n                bool prob, bool binary) {\n  logistic_regression_model<double> lm;\n  if(binary) {\n    lm.loadbinary(model);\n    auto mat = make_crs_matrix_local_loadbinary<double>(input);\n    if(prob) {\n      auto r = lm.predict_probability(mat);\n      make_dvector_scatter(r).savebinary(output);\n    } else {\n      auto r = lm.predict(mat);\n      make_dvector_scatter(r).savebinary(output);\n    }\n  } else {\n    lm.load(model);\n    auto mat = make_crs_matrix_local_load<double>(input);\n    if(prob) {\n      auto r = lm.predict_probability(mat);\n      make_dvector_scatter(r).saveline(output);\n    } else {\n      auto r = lm.predict(mat);\n      make_dvector_scatter(r).saveline(output);\n    }\n  }\n}\n\nint main(int argc, char* argv[]) {\n  use_frovedis use(argc, argv);\n\n  using namespace boost::program_options;\n\n  options_description opt(\"option\");\n  opt.add_options()\n    (\"help,h\", \"print help\")\n    (\"predict,p\", \"predict mode\")\n    (\"predict-probability,y\", \"probability-predict mode\")\n    (\"input,i\", value<string>(), \"input matrix\")\n    (\"ell\", \"assume ell storage of input training data matrix\")\n    (\"crs\", \"assume crs storage of input training data matrix (default for X86)\")\n    (\"hybrid\", \"assume jds-crs hybrid storage of input training data matrix (default for SX)\")\n    (\"label,l\", value<string>(), \"input label (for train)\")\n    (\"model,m\", value<string>(), \"input model (for predict)\")\n    (\"output,o\", value<string>(), \"output model or predict result\")\n    (\"num-iteration,n\", value<size_t>(), \"number of iteration (default: 1000)\")\n    (\"alpha,a\", value<double>(), \"learning rate (default:0.01) \")\n    (\"history-size,h\", value<size_t>(), \"size for lbfgs history vectors (default: 10)\")\n    (\"regularizer,r\", value<string>(), \"regularizer (ZERO [default], L1, or L2)\")\n    (\"regularization-parameter,e\", value<double>(), \"regularization parameter (default: 0.01)\")\n    (\"convergence-tolerance,c\", value<double>(), \"a tolerance value to determine convergence (default: 0.001)\")\n    (\"intercept,t\", \"use bias or not\")\n    (\"verbose\", \"set loglevel to DEBUG\")\n    (\"verbose2\", \"set loglevel to TRACE\")\n    (\"binary,b\", \"use binary input/output\");\n\n  variables_map argmap;\n  store(command_line_parser(argc,argv).options(opt).allow_unregistered().\n        run(), argmap);\n  notify(argmap);\n\n  bool ispredict = false;\n  bool predict_probability = false;\n  string input, label, model, output;\n  size_t num_iteration = 100;\n  double alpha = 1.0;\n  size_t hist_size = 10;\n  double convTol = 0.001;\n  string regularizer = \"ZERO\";\n  double regParam = 0.01;\n  bool intercept = false;\n  bool binary = false;\n  MatType mType = CRS;\n  \n  if(argmap.count(\"help\")){\n    cerr << opt << endl;\n    exit(1);\n  }\n\n  if(argmap.count(\"predict\")){\n    ispredict = true;\n  }\n\n  if(argmap.count(\"predict-probability\")){\n    ispredict = true;\n    predict_probability = true;\n  }\n\n  if(argmap.count(\"input\")){\n    input = argmap[\"input\"].as<string>();\n  } else {\n    cerr << \"input is not specified\" << endl;\n    cerr << opt << endl;\n    exit(1);\n  }\n\n  if(!ispredict) {\n    if(argmap.count(\"label\")){\n      label = argmap[\"label\"].as<string>();\n    } else {\n      cerr << \"label file is not specified\" << endl;\n      cerr << opt << endl;\n      exit(1);\n    }\n\n    if(argmap.count(\"ell\")) {\n      mType = ELL;\n    } else if(argmap.count(\"crs\")) {\n      mType = CRS;\n    } else if(argmap.count(\"hybrid\")) {\n      mType = HYBRID;\n    }\n  }\n\n  if(ispredict) {\n    if(argmap.count(\"model\")){\n      model = argmap[\"model\"].as<string>();\n    } else {\n      cerr << \"model file is not specified\" << endl;\n      cerr << opt << endl;\n      exit(1);\n    }\n  }\n\n  if(argmap.count(\"output\")){\n    output = argmap[\"output\"].as<string>();\n  } else {\n    cerr << \"output is not specified\" << endl;\n    cerr << opt << endl;\n    exit(1);\n  }\n\n  if(argmap.count(\"num-iteration\")){\n    num_iteration = argmap[\"num-iteration\"].as<size_t>();\n  }\n\n  if(argmap.count(\"alpha\")){\n    alpha = argmap[\"alpha\"].as<double>();\n  }\n\n  if(argmap.count(\"history-size\")){\n    hist_size = argmap[\"history-size\"].as<size_t>();\n  }\n\n  if(argmap.count(\"regularizer\")){\n    regularizer = argmap[\"regularizer\"].as<string>();\n  }\n\n  if(argmap.count(\"regularization-parameter\")){\n    regParam = argmap[\"regularization-parameter\"].as<double>();\n  }\n\n  if(argmap.count(\"convergence-tolerance\")){\n    convTol = argmap[\"convergence-tolerance\"].as<double>();\n  }\n\n  if(argmap.count(\"intercept\")){\n    intercept = true;\n  }\n\n  if(argmap.count(\"binary\")){\n    binary = true;\n  }\n\n  if(argmap.count(\"verbose\")){\n    set_loglevel(DEBUG);\n  }\n\n  if(argmap.count(\"verbose2\")){\n    set_loglevel(TRACE);\n  }\n\n  if(ispredict) do_predict(input, model, output, predict_probability, binary);\n  else do_train(input, label, output, num_iteration, alpha, hist_size,\n                regularizer, regParam, intercept, convTol, mType, binary);\n}\n", "meta": {"hexsha": "33fd019276d1c061eb99e5d725e8e36f6cb39458", "size": 6956, "ext": "cc", "lang": "C++", "max_stars_repo_path": "samples/glm/lr_lbfgs.cc", "max_stars_repo_name": "wmeddie/frovedis", "max_stars_repo_head_hexsha": "c134e5e64114799cc7c265c72525ff98d06b49c1", "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": "samples/glm/lr_lbfgs.cc", "max_issues_repo_name": "wmeddie/frovedis", "max_issues_repo_head_hexsha": "c134e5e64114799cc7c265c72525ff98d06b49c1", "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": "samples/glm/lr_lbfgs.cc", "max_forks_repo_name": "wmeddie/frovedis", "max_forks_repo_head_hexsha": "c134e5e64114799cc7c265c72525ff98d06b49c1", "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.8540772532, "max_line_length": 111, "alphanum_fraction": 0.604226567, "num_tokens": 1763, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743505760727, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.45252925503691616}}
{"text": "////////////////////////////////////////////////////////////////////////////////\n// IncompressibleBalloonEnergyWithHessProjection.hh\n////////////////////////////////////////////////////////////////////////////////\n/*! @file\n//  Implementation of the incompressible neo-Hookean-based strain energy\n//  density used in Skouras 2014: Designing Inflatable Structures, expressed\n//  in terms of the 3x2 deformation gradient F instead of the 2x2 Cauchy-Green\n//  deformation tensor F^T F. We also provide analytical expressions for the\n//  eigenvalues and eigenvectors of the Hessian (wrt F), enabling Hessian\n//  projection to resolve indefiniteness.\n*/\n//  Author:  Julian Panetta (jpanetta), julian.panetta@gmail.com\n//  Created:  07/09/2019 10:56:53\n////////////////////////////////////////////////////////////////////////////////\n#ifndef INCOMPRESSIBLEBALLOONENERGYWITHHESSPROJECTION_HH\n#define INCOMPRESSIBLEBALLOONENERGYWITHHESSPROJECTION_HH\n\n#include <Eigen/Dense>\n#include <array>\n\ntemplate<typename Real>\nstruct IncompressibleBalloonEnergyWithHessProjection {\n    using V2d  = Eigen::Matrix<Real, 2, 1>;\n    using M2d  = Eigen::Matrix<Real, 2, 2>;\n    using M3d  = Eigen::Matrix<Real, 3, 3>;\n    using M32d = Eigen::Matrix<Real, 3, 2>;\n\n    IncompressibleBalloonEnergyWithHessProjection() { }\n\n    template<typename Derived>\n    IncompressibleBalloonEnergyWithHessProjection(const Eigen::MatrixBase<Derived> &F) { setF(F); }\n\n    template<typename Derived>\n    void setF(const Eigen::MatrixBase<Derived> &F) {\n        static_assert((Derived::RowsAtCompileTime == 3) && (Derived::ColsAtCompileTime == 2), \"F must be 3x2\");\n        m_F = F.template cast<Real>();\n\n        Eigen::JacobiSVD<M32d> svd(m_F, Eigen::ComputeFullU | Eigen::ComputeFullV);\n        m_sigma = svd.singularValues();\n        m_V = svd.matrixV();\n        m_U = svd.matrixU();\n\n        m_det32_F = m_sigma.prod();\n        m_det_C = m_det32_F * m_det32_F;\n\n        m_d_det32_F = (m_U.col(0) * m_sigma[1] * m_V.col(0).transpose() +\n                       m_U.col(1) * m_sigma[0] * m_V.col(1).transpose());\n\n        m_trace_C = m_F.squaredNorm();\n\n        m_d_psi_ddet = -2.0 / (m_det_C * m_det32_F);\n\n        // Compute eigendecomposition of det32_F's Hessian\n        /* static constexpr */ const Real inv_sqrt2 = 1.0 / std::sqrt(2.0); // std::sqrt is not constexpr!\n\n        // T = U [0 -1; 1 0; 0 0] V^T / sqrt(2)\n        m_eigmat[2] = (-inv_sqrt2 * m_U.col(0)) * m_V.col(1).transpose() +\n                       (inv_sqrt2 * m_U.col(1)) * m_V.col(0).transpose();\n        m_eigval[2] = 2.0 + m_d_psi_ddet;\n        // L = U [0 1; 1 0; 0 0] V^T / sqrt(2)\n        m_eigmat[3] = (inv_sqrt2 * m_U.col(0)) * m_V.col(1).transpose() +\n                      (inv_sqrt2 * m_U.col(1)) * m_V.col(0).transpose();\n        m_eigval[3] = 2.0 - m_d_psi_ddet;\n        // NX = U [0 0; 0 0; 1 0] V^T\n        m_eigmat[4] = m_U.col(2) * m_V.col(0).transpose();\n        m_eigval[4] = 2.0 + m_d_psi_ddet * m_sigma[1] / m_sigma[0];\n        // NY = U [0 0; 0 0; 0 1] V^T\n        m_eigmat[5] = m_U.col(2) * m_V.col(1).transpose();\n        m_eigval[5] = 2.0 + m_d_psi_ddet * m_sigma[0] / m_sigma[1];\n\n        // The \"R\" and \"P\" modes [1 0; 0 1; 0 0] and [1 0; 0 -1; 0 0]\n        // are not orthogonal to d_det32_F and thus will not\n        // be eigenmatrices of the energy density Hessian (after addition of the\n        // rank 1 term proportional to (d_det32_F otimes d_det32_F)).\n        // We need to compute the compute the eigendecomposition of the Hessian\n        // in this subspace by solving a 2x2 matrix eigenvalue problem.\n        // We first probe the Hessian with an orthonormal basis for this space:\n        //      d0 := U [1, 0; 0, 0; 0, 0] V^T and d1 := U [0, 1; 0, 0; 0, 0] V^T\n        // to obtain the reduced Hessian:\n        //      A_ij = di : d2psi / dF2 : dj\n        //  A = 2 I + 1 / det(c)^2 [6 sigma_2^2  4 det32_F  ]\n        //                         [4 det32_F    6 sigma_1^2]\n        // Whose eigendecomposition is:\n        Real e = 3 * (m_sigma[1] * m_sigma[1] - m_sigma[0] * m_sigma[0]),\n             x = std::sqrt(16 * m_det_C + e * e);\n        Eigen::Vector2d v0(e - x, 4 * m_det32_F),\n                        v1(e + x, 4 * m_det32_F);\n        v0.normalize();\n        v1.normalize();\n        m_eigmat[0] = (v0[0] * m_U.col(0)) * m_V.col(0).transpose() +\n                      (v0[1] * m_U.col(1)) * m_V.col(1).transpose();\n        m_eigmat[1] = (v1[0] * m_U.col(0)) * m_V.col(0).transpose() +\n                      (v1[1] * m_U.col(1)) * m_V.col(1).transpose();\n        m_eigval[0] = 2 + (3 * m_trace_C - x) / (m_det_C * m_det_C);\n        m_eigval[1] = 2 + (3 * m_trace_C + x) / (m_det_C * m_det_C);\n    }\n\n    Real energy() const {\n        return stiffness * (m_trace_C + 1.0 / m_det_C - 3.0);\n    }\n\n    M32d denergy() const {\n        return 2 * m_F + m_d_psi_ddet * m_d_det32_F;\n    }\n\n    template<class DeltaF>\n    Real denergy(const DeltaF &dF) const {\n        const Real d_det32_F = m_sigma[1] * m_U.col(0).dot(dF * m_V.col(0)) +\n                               m_sigma[0] * m_U.col(1).dot(dF * m_V.col(1));\n\n        return 2.0 * doubleContract(m_F, dF) + m_d_psi_ddet * d_det32_F;\n    }\n\n    template<class DeltaF>\n    M32d delta_denergy(const DeltaF &dF) const {\n        M32d result(M32d::Zero());\n        for (size_t i = 0; i < 6; ++i) {\n            if (applyHessianProjection && (m_eigval[i] <= 0)) continue;\n            result += (m_eigval[i] * doubleContract(m_eigmat[i], dF)) * m_eigmat[i];\n        }\n\n        return result;\n    }\n\n    template<class DeltaF>\n    Real d2energy(const DeltaF &dF_a, const DeltaF &dF_b) const {\n        return doubleContract(delta_denergy(dF_a), dF_b);\n    }\n\n    Real stiffness = 1.0;\n\n    // Whether to project d2energy/denergy onto the space of positive semi-semidefinite tensors.\n    bool applyHessianProjection = false;\n\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\nprivate:\n    // We need the singular value decomposition for our gradient/Hessian formulas.\n    M32d m_F, m_d_det32_F;\n\n    // Eigenmatrices of the determinant: \"R\", \"P\", \"T\", \"L\", \"NX\", and \"NY\"\n    std::array<M32d, 6> m_eigmat;\n    std::array<Real, 6> m_eigval;\n\n    M2d  m_V;\n    M3d  m_U;\n    V2d  m_sigma;\n    Real m_trace_C, m_det32_F, m_det_C, m_d_psi_ddet;\n};\n\n#endif /* end of include guard: INCOMPRESSIBLEBALLOONENERGYWITHHESSPROJECTION_HH */\n", "meta": {"hexsha": "d195e45649809f97bffb6e0061dc2f725227524e", "size": 6336, "ext": "hh", "lang": "C++", "max_stars_repo_path": "IncompressibleBalloonEnergyWithHessProjection.hh", "max_stars_repo_name": "jpanetta/Inflatables", "max_stars_repo_head_hexsha": "6941fb1bf4a2f61a847605aea37adef97bf05d76", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2021-10-05T18:52:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T06:35:04.000Z", "max_issues_repo_path": "IncompressibleBalloonEnergyWithHessProjection.hh", "max_issues_repo_name": "jpanetta/Inflatables", "max_issues_repo_head_hexsha": "6941fb1bf4a2f61a847605aea37adef97bf05d76", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "IncompressibleBalloonEnergyWithHessProjection.hh", "max_forks_repo_name": "jpanetta/Inflatables", "max_forks_repo_head_hexsha": "6941fb1bf4a2f61a847605aea37adef97bf05d76", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-09-24T22:26:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-14T21:51:18.000Z", "avg_line_length": 41.9602649007, "max_line_length": 111, "alphanum_fraction": 0.5738636364, "num_tokens": 2066, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.4525122581618465}}
{"text": "\n#include <fstream>\n#include <iostream>\n#include <string>\n#include <stdlib.h>\n#include <vector> \n//#include <random>\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\n#include \"genotype.h\"\n#include \"mailman.h\"\n#include \"arguments.h\"\n//#include \"helper.h\"\n#include \"storage.h\"\n\n#include \"/usr/include/boost/random.hpp\"\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//typedef Matrix<int, Dynamic, Dynamic, RowMajor> MatrixXdrInt;\n\nclass data {\n\n public:\n     MatrixXdr gen;\n     int index;\n\n};\n\n\n//Intermediate Variables\nint blocksize;\nint hsegsize;\ndouble *partialsums;\ndouble *sum_op;\t\t\ndouble *yint_e;\ndouble *yint_m;\ndouble **y_e;\ndouble **y_m;\n\n\nstruct timespec t0;\n\nclock_t total_begin = clock();\nMatrixXdr pheno;\nMatrixXdr mask;\nMatrixXdr covariate;  \nMatrixXdr Q;\nMatrixXdr v1; //W^ty\nMatrixXdr v2;            //QW^ty\nMatrixXdr v3;    //WQW^ty\nMatrixXdr new_pheno;\n\n\n\ngenotype g;\ngenotype g1;\ngenotype g2;\nMatrixXdr geno_matrix; //(p,n)\ngenotype* Geno;\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)\nMatrixXdr sum2;\nMatrixXdr sum;  \n\nEigen::RowVectorXd means_na;\nEigen::RowVectorXd stds_na;\n////////\n//related to phenotype\t\ndouble y_sum; \ndouble y_mean;\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;\nbool use_cov=false; \n\n\n//// jackknife index wich are computed based on annotation file\nMatrixXdr dic_index;\nMatrixXdr jack_bin_size;\nvector<int> len;\nvector<int> Annot;\n\nint real_Njack;  ///number of block for jackknife se\nint Njack;   /// number of block for streaming\nint Nbin;\nint Nz=10;\n///////\n\n//define random vector z's\nMatrixXdr  all_zb;\nMatrixXdr  all_Uzb;\nMatrixXdr res;\nMatrixXdr XXz;\nMatrixXdr Xy;\nMatrixXdr yXXy;\n\n\n///\n//Matrix<int, Dynamic, Dynamic, RowMajor> gen;\nMatrixXdr gen;\nbool read_header;\n//read variables\nunsigned char mask2;\nint wordsize;\nunsigned int unitsperword;\nint unitsize;\nint nrow, ncol;\nunsigned char *gtype;\nint Nsnp;\nint Nindv;\nbool **bin_annot;\nint step_size;\nint step_size_rem;\nstd::vector<std::vector<bool> > annot_bool;\nstd::vector<std::vector<int> > jack_bin;\n\nstd::vector<std::vector<bool> > annot_bool_real;\nstd::vector<std::vector<int> > jack_bin_real;\n\nvector <data> allgen;\nvector <genotype> allgen_mail;\nint global_snp_index;\nbool use_mailman=true;\n\n///reading single col annot\nvector <int> SNP_annot;\nbool use_1col_annot=false;\n\n\n///Variables for reg out cov on both side of LM\nbool both_side_cov=false;\nMatrixXdr UXXz;\nMatrixXdr XXUz;\nMatrixXdr Xz;\nMatrixXdr trVK;\n\nstd::istream& newline(std::istream& in)\n{\n    if ((in >> std::ws).peek() != std::char_traits<char>::to_int_type('\\n')) {\n        in.setstate(std::ios_base::failbit);\n    }\n    return in.ignore();\n}\n\n\nint read_cov(bool std,int Nind, std::string filename, std::string covname){\n\tifstream ifs(filename.c_str(), ios::in); \n\tstd::string line; \n\tstd::istringstream in; \n\tint covIndex = 0; \n\tstd::getline(ifs,line); \n\tin.str(line); \n\tstring b;\n\tvector<vector<int> > missing; \n\tint covNum=0;  \n\twhile(in>>b)\n\t{\n\t\tif(b!=\"FID\" && b !=\"IID\"){\n\t\tmissing.push_back(vector<int>()); //push an empty row  \n\t\tif(b==covname && covname!=\"\")\n\t\t\tcovIndex=covNum; \n\t\tcovNum++; \n\t\t}\n\t}\n\tvector<double> cov_sum(covNum, 0); \n\tif(covname==\"\")\n\t{\n\t\tcovariate.resize(Nind, covNum); \n\t\tcout<< \"Read in \"<<covNum << \" Covariates.. \"<<endl;\n\t}\n\telse \n\t{\n\t\tcovariate.resize(Nind, 1); \n\t\tcout<< \"Read in covariate \"<<covname<<endl;  \n\t}\n\n\t\n\tint j=0; \n\twhile(std::getline(ifs, line)){\n\t\tin.clear(); \n\t\tin.str(line);\n\t\tstring temp;\n\t\tin>>temp; in>>temp; //FID IID \n\t\tfor(int k=0; k<covNum; k++){\n\t\t\t\n\t\t\tin>>temp;\n\t\t\tif(temp==\"NA\")\n\t\t\t{\n\t\t\t\tmissing[k].push_back(j);\n\t\t\t\tcontinue; \n\t\t\t} \n\t\t\tdouble cur = atof(temp.c_str()); \n\t\t\tif(cur==-9)\n\t\t\t{\n\t\t\t\tmissing[k].push_back(j); \n\t\t\t\tcontinue; \n\t\t\t}\n\t\t\tif(covname==\"\")\n\t\t\t{\n\t\t\t\tcov_sum[k]= cov_sum[k]+ cur; \n\t\t\t\tcovariate(j,k) = cur; \n\t\t\t}\n\t\t\telse\n\t\t\t\tif(k==covIndex)\n\t\t\t\t{\n\t\t\t\t\tcovariate(j, 0) = cur;\n\t\t\t\t\tcov_sum[k] = cov_sum[k]+cur; \n\t\t\t\t}\n\t\t}\n\t\t//if(j<10) \n\t\t//\tcout<<covariate.block(j,0,1, covNum)<<endl; \n\t\tj++;\n\t}\n\t//compute cov mean and impute \n\tfor (int a=0; a<covNum ; a++)\n\t{\n\t\tint missing_num = missing[a].size(); \n\t\tcov_sum[a] = cov_sum[a] / (Nind - missing_num);\n\n\t\tfor(int b=0; b<missing_num; b++)\n\t\t{\n                        int index = missing[a][b];\n                        if(covname==\"\")\n                                covariate(index, a) = cov_sum[a];\n                        else if (a==covIndex)\n                                covariate(index, 0) = cov_sum[a];\n                } \n\t}\n\tif(std)\n\t{\n\t\tMatrixXdr cov_std;\n\t\tcov_std.resize(1,covNum);  \n\t\tMatrixXdr sum = covariate.colwise().sum();\n\t\tMatrixXdr sum2 = (covariate.cwiseProduct(covariate)).colwise().sum();\n\t\tMatrixXdr temp;\n//\t\ttemp.resize(Nind, 1); \n//\t\tfor(int i=0; i<Nind; i++)\n//\t\t\ttemp(i,0)=1;  \n\t\tfor(int b=0; b<covNum; b++)\n\t\t{\n\t\t\tcov_std(0,b) = sum2(0,b) + Nind*cov_sum[b]*cov_sum[b]- 2*cov_sum[b]*sum(0,b);\n\t\t\tcov_std(0,b) =sqrt((Nind- 1)/cov_std(0,b)) ;\n\t\t\tdouble scalar=cov_std(0,b); \n\t\t\tfor(int j=0; j<Nind; j++)\n\t\t\t{\n\t\t\t\tcovariate(j,b) = covariate(j,b)-cov_sum[b];  \n\t\t\t\tcovariate(j,b) =covariate(j,b)*scalar;\n\t\t\t} \n\t\t\t//covariate.col(b) = covariate.col(b) -temp*cov_sum[b];\n\t\t\t\n\t\t}\n\t}\t\n\treturn covNum; \n}\n\n\n\n\n\n\n\nvoid multiply_y_pre_fast(MatrixXdr &op, int Ncol_op ,MatrixXdr &res,bool subtract_means){\n\n        for(int k_iter=0;k_iter<Ncol_op;k_iter++){\n                sum_op[k_iter]=op.col(k_iter).sum();\n        }\n\n                        //cout << \"Nops = \" << Ncol_op << \"\\t\" <<g.Nsegments_hori << endl;\n        #if DEBUG==1\n                if(debug){\n                        print_time ();\n                        cout <<\"Starting mailman on premultiply\"<<endl;\n                        cout << \"Nops = \" << Ncol_op << \"\\t\" <<g.Nsegments_hori << endl;\n                        cout << \"Segment size = \" << g.segment_size_hori << endl;\n                        cout << \"Matrix size = \" <<g.segment_size_hori<<\"\\t\" <<g.Nindv << endl;\n                        cout << \"op = \" <<  op.rows () << \"\\t\" << op.cols () << endl;\n                }\n        #endif\n\n\n        //TODO: Memory Effecient SSE FastMultipy\n\n        for(int seg_iter=0;seg_iter<g.Nsegments_hori-1;seg_iter++){\n                mailman::fastmultiply(g.segment_size_hori,g.Nindv,Ncol_op,g.p[seg_iter],op,yint_m,partialsums,y_m);\n                int p_base = seg_iter*g.segment_size_hori;\n                for(int p_iter=p_base; (p_iter<p_base+g.segment_size_hori) && (p_iter<g.Nsnp) ; p_iter++ ){\n                        for(int k_iter=0;k_iter<Ncol_op;k_iter++)\n                                res(p_iter,k_iter) = y_m[p_iter-p_base][k_iter];\n                }\n        }\n\n        int last_seg_size = (g.Nsnp%g.segment_size_hori !=0 ) ? g.Nsnp%g.segment_size_hori : g.segment_size_hori;\n        mailman::fastmultiply(last_seg_size,g.Nindv,Ncol_op,g.p[g.Nsegments_hori-1],op,yint_m,partialsums,y_m);\n        int p_base = (g.Nsegments_hori-1)*g.segment_size_hori;\n        for(int p_iter=p_base; (p_iter<p_base+g.segment_size_hori) && (p_iter<g.Nsnp) ; p_iter++){\n                for(int k_iter=0;k_iter<Ncol_op;k_iter++)\n                        res(p_iter,k_iter) = y_m[p_iter-p_base][k_iter];\n        }\n\n        #if DEBUG==1\n                if(debug){\n                        print_time ();\n                        cout <<\"Ending mailman on premultiply\"<<endl;\n                }\n        #endif\n\n\n        if(!subtract_means)\n                return;\n\n        for(int p_iter=0;p_iter<p;p_iter++){\n                for(int k_iter=0;k_iter<Ncol_op;k_iter++){\n                        res(p_iter,k_iter) = res(p_iter,k_iter) - (g.get_col_mean(p_iter)*sum_op[k_iter]);\n                        if(var_normalize)\n                                res(p_iter,k_iter) = res(p_iter,k_iter)/(g.get_col_std(p_iter));\n                }\n        }\n\n}\n\n\n\nvoid multiply_y_post_fast(MatrixXdr &op_orig, int Nrows_op, MatrixXdr &res,bool subtract_means){\n\n        MatrixXdr op;\n        op = op_orig.transpose();\n\n        if(var_normalize && subtract_means){\n                for(int p_iter=0;p_iter<p;p_iter++){\n                        for(int k_iter=0;k_iter<Nrows_op;k_iter++)\n                                op(p_iter,k_iter) = op(p_iter,k_iter) / (g.get_col_std(p_iter));\n                }\n        }\n\n        #if DEBUG==1\n                if(debug){\n                        print_time ();\n                        cout <<\"Starting mailman on postmultiply\"<<endl;\n                }\n        #endif\n\n        int Ncol_op = Nrows_op;\n\n        //cout << \"ncol_op = \" << Ncol_op << endl;\n\n        int seg_iter;\n        for(seg_iter=0;seg_iter<g.Nsegments_hori-1;seg_iter++){\nmailman::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        }\n        int last_seg_size = (g.Nsnp%g.segment_size_hori !=0 ) ? g.Nsnp%g.segment_size_hori : g.segment_size_hori;\n        mailman::fastmultiply_pre(last_seg_size,g.Nindv,Ncol_op, seg_iter * g.segment_size_hori, g.p[seg_iter],op,yint_e,partialsums,y_e);\n\n        for(int n_iter=0; n_iter<n; n_iter++)  {\n                for(int k_iter=0;k_iter<Ncol_op;k_iter++) {\n                        res(k_iter,n_iter) = y_e[n_iter][k_iter];\n                        y_e[n_iter][k_iter] = 0;\n                }\n        }\n\n        #if DEBUG==1\n                if(debug){\n                        print_time ();\n                        cout <<\"Ending mailman on postmultiply\"<<endl;\n                }\n        #endif\n\n\n        if(!subtract_means)\n                return;\n\n        double *sums_elements = new double[Ncol_op];\n        memset (sums_elements, 0, Nrows_op * sizeof(int));\n\n        for(int k_iter=0;k_iter<Ncol_op;k_iter++){\n                double sum_to_calc=0.0;\n                for(int p_iter=0;p_iter<p;p_iter++)\n                        sum_to_calc += g.get_col_mean(p_iter)*op(p_iter,k_iter);\n                sums_elements[k_iter] = sum_to_calc;\n        }\n        for(int k_iter=0;k_iter<Ncol_op;k_iter++){\n                for(int n_iter=0;n_iter<n;n_iter++)\n                        res(k_iter,n_iter) = res(k_iter,n_iter) - sums_elements[k_iter];\n        }\n\n\n}\n\n\nvoid initial_var()\n{\n    /*if(key==1)\n        g=g1;\n    if(key==2)\n        g=g2;*/\n   // g=Geno[key];\n        \n\n\tp = g.Nsnp;\n        n = g.Nindv;\n\n\n        c.resize(p,k);\n        x.resize(k,n);\n        v.resize(p,k);\n        //means.resize(p,1);\n        //stds.resize(p,1);\n        sum2.resize(p,1);\n        sum.resize(p,1);\n\n\n        if(!fast_mode && !memory_efficient){\n                geno_matrix.resize(p,n);\n                g.generate_eigen_geno(geno_matrix,var_normalize);\n        }\n\n        //TODO: Initialization of c with gaussian distribution\n        c = MatrixXdr::Random(p,k);\n\n\n        // Initial intermediate data structures\n        blocksize = k;\n         hsegsize = g.segment_size_hori;        // = log_3(n)\n        int hsize = pow(3,hsegsize);\n        int vsegsize = g.segment_size_ver;              // = log_3(p)\n        int vsize = pow(3,vsegsize);\n\n        partialsums = new double [blocksize];\n        sum_op = new double[blocksize];\n        yint_e = new double [hsize*blocksize];\n        yint_m = new double [hsize*blocksize];\n        memset (yint_m, 0, hsize*blocksize * sizeof(double));\n        memset (yint_e, 0, hsize*blocksize * sizeof(double));\n\n        y_e  = new double*[g.Nindv];\n        for (int i = 0 ; i < g.Nindv ; i++) {\n                y_e[i] = new double[blocksize];\n                memset (y_e[i], 0, blocksize * sizeof(double));\n        }\n\n        y_m = new double*[hsegsize];\n        for (int i = 0 ; i < hsegsize ; i++)\n                y_m[i] = new double[blocksize];\n      /*  for(int i=0;i<p;i++){\n                means(i,0) = g.get_col_mean(i);\n                stds(i,0) =1/g.get_col_std(i);\n                //sum2(i,0) =g.get_col_sum2(i); \n                sum(i,0)= g.get_col_sum(i);\n        }\n\n*/\n\n\n}\n \n\n\n\n/*void read_cov(int Nind, std::string filename, std::string covname){\n\tifstream ifs(filename.c_str(), ios::in); \n\tstd::string line; \n\tstd::istringstream in; \n\tint covIndex = 0; \n\tstd::getline(ifs,line); \n\tin.str(line); \n\tstring b;\n\tvector<vector<int> > missing; \n\tint covNum=0;  \n\twhile(in>>b)\n\t{\n\t\tmissing.push_back(vector<int>()); //push an empty row  \n\t\tif(b==covname && covname!=\"\")\n\t\t\tcovIndex=covNum; \n\t\tcovNum++; \n\t}\n\tvector<double> cov_sum(covNum, 0); \n\tif(covname==\"\")\n\t{\n\t\tcovariate.resize(Nind, covNum); \n\t\tcout<< \"Read in \"<<covNum << \" Covariates.. \"<<endl;\n\t}\n\telse \n\t{\n\t\tcovariate.resize(Nind, 1); \n\t\tcout<< \"Read in covariate \"<<covname<<endl;  \n\t}\n\n\t\n\tint j=0; \n\twhile(std::getline(ifs, line)){\n\t\tin.clear(); \n\t\tin.str(line);\n\t\tstring temp; \n\t\tfor(int k=0; k<covNum; k++){\n\t\t\tin>>temp;\n\t\t\tif(temp==\"NA\")\n\t\t\t{\n\t\t\t\tmissing[k].push_back(j);\n\t\t\t\tcontinue;  \n\t\t\t} \n\t\t\tint cur = atof(temp.c_str()); \n\t\t\tif(cur==-9)\n\t\t\t{\n\t\t\t\tmissing[k].push_back(j); \n\t\t\t\tcontinue; \n\t\t\t}\n\t\t\tif(covname==\"\")\n\t\t\t{\n\t\t\t\tcov_sum[k]= cov_sum[k]+ cur; \n\t\t\t\tcovariate(j,k) = cur; \n\t\t\t}\n\t\t\telse\n\t\t\t\tif(k==covIndex)\n\t\t\t\t{\n\t\t\t\t\tcovariate(j, 0) = cur;\n\t\t\t\t\tcov_sum[k] = cov_sum[k]+cur; \n\t\t\t\t}\n\t\t} \n\t\tj++;\n\t}\n\t//compute cov mean and impute \n\tfor (int a=0; a<covNum ; a++)\n\t{\n\t\tint missing_num = missing[a].size(); \n\t\tcov_sum[a] = cov_sum[a] / (covNum - missing_num);\n\n\t\tfor(int b=0; b<missing_num; b++)\n\t\t{\n                        int index = missing[a][b];\n                        if(covname==\"\")\n                                covariate(index, a) = cov_sum[a];\n                        else if (a==covIndex)\n                                covariate(index, 0) = cov_sum[a];\n                } \n\t}\n}*/\nvoid read_pheno2(int Nind, std::string filename){\n//\tpheno.resize(Nind,1); \n\tifstream ifs(filename.c_str(), ios::in); \n\t\n\tstd::string line;\n\tstd::istringstream in;  \n\tint phenocount=0; \n//read header\n\tstd::getline(ifs,line); \n\tin.str(line); \n\tstring b; \n\twhile(in>>b)\n\t{\n\t\tif(b!=\"FID\" && b !=\"IID\")\n\t\t\tphenocount++; \n\t}\n\tpheno.resize(Nind, phenocount);\n\tmask.resize(Nind, phenocount);\n\tint i=0;  \n\twhile(std::getline(ifs, line)){\n\t\tin.clear(); \n\t\tin.str(line); \n\t\tstring temp;\n\t\t//fid,iid\n\t\t//todo: fid iid mapping; \n\t\t//todo: handle missing phenotype\n\t\tin>>temp; in>>temp; \n\t\tfor(int j=0; j<phenocount;j++) {\n\t\t\tin>>temp;\n\t\t\tdouble cur = atof(temp.c_str());\n\t\t\tif(temp==\"NA\" || cur==-9){\n\t\t\tpheno(i,j)=0;\n\t\t\tmask(i,j)=0;\n\t\t\t}\n\t\t\telse{\n\t\t\tpheno(i,j)=atof(temp.c_str());\n\t\t\tmask(i,j)=1;\n\n\t\t\t}\n\n    \n\t\t}\n\t\ti++;\n\t}\n\t//cout<<pheno; \n}\n\ndouble compute_yXXy(int num_snp){\n\n\n        MatrixXdr res(num_snp, 1);\n\n\t\n\tif(use_mailman==true)\n\t\tmultiply_y_pre_fast(pheno,1,res,false);\n\telse\n\t\t res=gen*pheno;\n\t\n\n\tres = res.cwiseProduct(stds);\n        MatrixXdr resid(num_snp, 1);\n        resid = means.cwiseProduct(stds);\n        resid = resid *y_sum;\n        MatrixXdr Xy(num_snp,1);\n        Xy = res-resid;\n    \n        double yXXy = (Xy.array()* Xy.array()).sum();\n        \n        return yXXy;\n\n}\n\ndouble compute_yVXXVy(int num_snp){\n        MatrixXdr new_pheno_sum = new_pheno.colwise().sum();\n        MatrixXdr res(num_snp, 1);\n        \n\t\n\n\n\n        if(use_mailman==true)\n                multiply_y_pre_fast(new_pheno,1,res,false);\n        else\n                 res=gen*new_pheno;\n\n\n\n        res = res.cwiseProduct(stds);\n        MatrixXdr resid(num_snp, 1);\n        resid = means.cwiseProduct(stds);\n        resid = resid *new_pheno_sum;\n        MatrixXdr Xy(num_snp,1);\n        Xy = res-resid;\n        double ytVXXVy = (Xy.array()* Xy.array()).sum();\n        return ytVXXVy;\n\n}\n\n\n\n\n\n\t\nMatrixXdr  compute_XXz (int num_snp){\n\t//mask\n\t/*for (int i=0;i<Nz;i++)\n\t   for(int j=0;j<Nindv;j++)\n\t\t all_zb(j,i)=all_zb(j,i)*mask(j,0);\n*/\n         res.resize(num_snp, Nz);\n\n        \n\tif(use_mailman==true)\n\t\tmultiply_y_pre_fast(all_zb,Nz,res, false);\n\telse\t\n        \tres=gen*all_zb;\n   \n\n        MatrixXdr zb_sum = all_zb.colwise().sum();\n        \n\n\tfor(int j=0; j<num_snp; j++)\n            for(int k=0; k<Nz;k++)\n                res(j,k) = res(j,k)*stds(j,0);\n            \n        MatrixXdr resid(num_snp, Nz);\n        MatrixXdr inter = means.cwiseProduct(stds);\n        resid = inter * zb_sum;\n        MatrixXdr inter_zb = res - resid;\n       \n\n\tfor(int k=0; k<Nz; k++)\n            for(int j=0; j<num_snp;j++)\n                inter_zb(j,k) =inter_zb(j,k) *stds(j,0);\n       MatrixXdr new_zb = inter_zb.transpose();\n       MatrixXdr new_res(Nz, Nindv);\n       \n\t\n\t if(use_mailman==true)\n\t    multiply_y_post_fast(new_zb, Nz, new_res, false);\n\t else\n\t    new_res=new_zb*gen;\t\n\n       MatrixXdr new_resid(Nz, num_snp);\n       MatrixXdr zb_scale_sum = new_zb * means;\n       new_resid = zb_scale_sum * MatrixXdr::Constant(1,Nindv, 1);\n\n\n                      /// new zb \n       MatrixXdr temp=new_res - new_resid;\n\n\tfor (int i=0;i<Nz;i++)\n           for(int j=0;j<Nindv;j++)\n                 temp(i,j)=temp(i,j)*mask(j,0);\n\n\n\treturn temp.transpose();\n       \n\n}\n\n\n\n\n\n\nMatrixXdr  compute_XXUz (int num_snp){\n        //mask\n/*        for (int i=0;i<Nz;i++)\n           for(int j=0;j<Nindv;j++)\n                 all_Uzb(j,i)=all_Uzb(j,i)*mask(j,0);\n*/\n         res.resize(num_snp, Nz);\n\n\n        if(use_mailman==true)\n                multiply_y_pre_fast(all_Uzb,Nz,res, false);\n        else\n                res=gen*all_Uzb;\n  \n\n        MatrixXdr zb_sum = all_Uzb.colwise().sum();\n\n\n        for(int j=0; j<num_snp; j++)\n            for(int k=0; k<Nz;k++)\n                res(j,k) = res(j,k)*stds(j,0);\n\n        MatrixXdr resid(num_snp, Nz);\n        MatrixXdr inter = means.cwiseProduct(stds);\n        resid = inter * zb_sum;\n        MatrixXdr inter_zb = res - resid;\n\n\n        for(int k=0; k<Nz; k++)\n            for(int j=0; j<num_snp;j++)\n                inter_zb(j,k) =inter_zb(j,k) *stds(j,0);\n       MatrixXdr new_zb = inter_zb.transpose();\n       MatrixXdr new_res(Nz, Nindv);\n\n\n         if(use_mailman==true)\n            multiply_y_post_fast(new_zb, Nz, new_res, false);\n         else\n            new_res=new_zb*gen;\n\n       MatrixXdr new_resid(Nz, num_snp);\n       MatrixXdr zb_scale_sum = new_zb * means;\n       new_resid = zb_scale_sum * MatrixXdr::Constant(1,Nindv, 1);\n\n\n                      /// new zb \n       MatrixXdr temp=new_res - new_resid;\n\n        for (int i=0;i<Nz;i++)\n           for(int j=0;j<Nindv;j++)\n                 temp(i,j)=temp(i,j)*mask(j,0);\n\n\n        return temp.transpose();\n\n\n}\n\n\n\nMatrixXdr  compute_Xz (int num_snp){\n\n         MatrixXdr new_zb= MatrixXdr::Random(Nz,num_snp);\n         new_zb = new_zb * sqrt(3);\n\n\t MatrixXdr new_res(Nz, Nindv);         \n\n        if(use_mailman==true)\n                multiply_y_post_fast(new_zb,Nz,new_res, false);\n        else\n                new_res=new_zb*gen;\n\n\n        MatrixXdr new_resid(Nz, num_snp);\n       MatrixXdr zb_scale_sum = new_zb * means;\n       new_resid = zb_scale_sum * MatrixXdr::Constant(1,Nindv, 1);\n\n\n                      /// new zb \n       MatrixXdr temp=new_res - new_resid;\n\n        for (int i=0;i<Nz;i++)\n           for(int j=0;j<Nindv;j++)\n                 temp(i,j)=temp(i,j)*mask(j,0);\n\n\n\n\n\treturn temp.transpose();\n}\n\n\n\n\n\n\n\n\nvoid read_annot (string filename){\n         \n//\tint step_size=Nsnp/Njack;\n  //      int step_size_rem=Nsnp%Njack;\n        vector<bool> snp_annot;\n\t//jack_bin.resize(Njack, vector<int>(Nbin,0));\t\n\t\n//\tcout<<step_size<<endl;\n\n\tifstream inp(filename.c_str());\n        if (!inp.is_open()){\n                cerr << \"Error reading file \"<< filename <<endl;\n                exit(1);\n        }\n        string line;\n        int j = 0 ;\n        int linenum = 0 ;\n        int num_parti;\n        stringstream check1(line);\n        string intermediate;\n        vector <string> tokens;\n        while(std::getline (inp, line)){\n                //linenum ++;\n                char c = line[0];\n                if (c=='#')\n                        continue;\n                istringstream ss (line);\n                if (line.empty())\n                        continue;\n                j++;\n                //cout<<line<<endl;\n\n                stringstream check1(line);\n                string intermediate;\n                vector <string> tokens;\n                // Tokenizing w.r.t. space ' ' \n                while(getline(check1, intermediate, ' '))\n                 {\n                      tokens.push_back(intermediate);\n                 }\n                 if(linenum==0){\n                 num_parti=tokens.size();\n\t\t Nbin=num_parti;\n                  snp_annot.resize(Nbin,0);\t \n          \t  jack_bin.resize(Njack, vector<int>(Nbin,0));\n\t         len.resize(num_parti,0);\n                }\n                int index_annot=0;\n                for(int i = 0; i < tokens.size(); i++){\n\t\t      snp_annot[i]=0;\n\t\t      if (tokens[i]==\"1\"){\n                            len[i]++;\n\t\t\t    snp_annot[i]=1;\n \t\t      }\n                }\n\t\tannot_bool.push_back(snp_annot);\n        linenum++;\n       }\n\n\t  if(Nsnp!=linenum){\n          cout<<\"Number of the rows in bim file and annotation file does not match\"<<endl;\n        }\n\n\tNsnp=linenum;\n\t//cout<<\"Total number of SNPs : \"<<Nsnp<<endl;\n\tint selected_snps=0;\n\tfor (int i=0;i<num_parti;i++){\n                cout<<len[i]<<\" SNPs in \"<<i<<\"-th bin\"<<endl;\n\t\tselected_snps+=len[i];\n        }\n\t\n\tcout<<\" Number of selected SNPs w.r.t  annot file : \" <<selected_snps<<endl;\n\n\n\t step_size=Nsnp/Njack;\n         step_size_rem=Nsnp%Njack;\n\tcout<<\"Number of SNPs per block : \"<<step_size<<endl;\n      //  cout<<\"stepsize : \"<<step_size_rem<<endl;\n\tjack_bin.resize(Njack, vector<int>(Nbin,0));\n\tint temp;\n\tfor (int i=0;i<Nsnp;i++)\n\t   for(int j=0;j<Nbin;j++)\n\t\t if (annot_bool[i][j]==1){\n\t\t\ttemp=i/step_size;\n\t\t\tif (temp>=Njack)\n\t\t\t\ttemp=Njack-1;\n\t\t\t//cout<<i<<\"xxx\"<<j<<\"xxx\"<<temp<<endl;\n\t\t\tjack_bin[temp][j]++;\t\n\t\t }\n/*\t\ncout<<\"jackbin\"<<endl;\n\tfor (int i=0;i<Njack;i++){\n\t   for(int j=0;j<Nbin;j++)\n                cout<<jack_bin[i][j]<<\" \";\n\t  cout<<endl;\n        }*/\n/*\nfor (int i=0;i<linenum;i++){\n  for(int j=0;j<Nbin;j++)\n\tcout<<annot_bool[i][j]<<\" \";\n  cout<<endl;\n}\n*/\n\n}\n\n\n\nvoid read_annot_real(string filename){\n         \n//\tint step_size=Nsnp/Njack;\n  //      int step_size_rem=Nsnp%Njack;\n        vector<bool> snp_annot;\n\t//jack_bin.resize(Njack, vector<int>(Nbin,0));\t\n\t\n//\tcout<<step_size<<endl;\n\n\tifstream inp(filename.c_str());\n        if (!inp.is_open()){\n                cerr << \"Error reading file \"<< filename <<endl;\n                exit(1);\n        }\n        string line;\n        int j = 0 ;\n        int linenum = 0 ;\n        int num_parti;\n        stringstream check1(line);\n        string intermediate;\n        vector <string> tokens;\n        while(std::getline (inp, line)){\n                //linenum ++;\n                char c = line[0];\n                if (c=='#')\n                        continue;\n                istringstream ss (line);\n                if (line.empty())\n                        continue;\n                j++;\n                //cout<<line<<endl;\n\n                stringstream check1(line);\n                string intermediate;\n                vector <string> tokens;\n                // Tokenizing w.r.t. space ' ' \n                while(getline(check1, intermediate, ' '))\n                 {\n                      tokens.push_back(intermediate);\n                 }\n                 if(linenum==0){\n                 num_parti=tokens.size();\n\t\t Nbin=num_parti;\n                  snp_annot.resize(Nbin,0);\t \n          \t  jack_bin_real.resize(real_Njack, vector<int>(Nbin,0));\n\t        // len.resize(num_parti,0);\n                }\n                int index_annot=0;\n                for(int i = 0; i < tokens.size(); i++){\n\t\t      snp_annot[i]=0;\n\t\t      if (tokens[i]==\"1\"){\n                      //      len[i]++;\n\t\t\t    snp_annot[i]=1;\n \t\t      }\n                }\n\t\tannot_bool_real.push_back(snp_annot);\n        linenum++;\n       }\n\n\t  if(Nsnp!=linenum){\n          cout<<\"Number of the rows in bim file and annotation file does not match\"<<endl;\n        }\n\n\tNsnp=linenum;\n\t//cout<<\"Total number of SNPs : \"<<Nsnp<<endl;\n\tint selected_snps=0;\n\tfor (int i=0;i<num_parti;i++){\n                cout<<len[i]<<\" SNPs in \"<<i<<\"-th bin\"<<endl;\n\t\tselected_snps+=len[i];\n        }\n\t\n\tcout<<\" Number of selected SNPs w.r.t  annot file : \" <<selected_snps<<endl;\n\n\n\t int step_size_temp=Nsnp/real_Njack;\n          int step_size_rem_temp=Nsnp%real_Njack;\n\tcout<<\"Number of SNPs per block : \"<<step_size<<endl;\n      //  cout<<\"stepsize : \"<<step_size_rem<<endl;\n\tjack_bin_real.resize(real_Njack, vector<int>(Nbin,0));\n\tint temp;\n\tfor (int i=0;i<Nsnp;i++)\n\t   for(int j=0;j<Nbin;j++)\n\t\t if (annot_bool_real[i][j]==1){\n\t\t\ttemp=i/step_size_temp;\n\t\t\tif (temp>=real_Njack)\n\t\t\t\ttemp=real_Njack-1;\n\t\t\t//cout<<i<<\"xxx\"<<j<<\"xxx\"<<temp<<endl;\n\t\t\tjack_bin_real[temp][j]++;\t\n\t\t }\n/*\t\ncout<<\"jackbin\"<<endl;\n\tfor (int i=0;i<Njack;i++){\n\t   for(int j=0;j<Nbin;j++)\n                cout<<jack_bin[i][j]<<\" \";\n\t  cout<<endl;\n        }*/\n/*\nfor (int i=0;i<linenum;i++){\n  for(int j=0;j<Nbin;j++)\n\tcout<<annot_bool[i][j]<<\" \";\n  cout<<endl;\n}\n*/\n\n}\n\n\n\n\n\n\n\n\n\n\n\n\n//vector <int> SNP_annot;\n\nvoid read_annot_1col (string filename){\n\t\n\t\n        ifstream ifs(filename.c_str(), ios::in);\n\n        std::string line;\n        std::istringstream in;\n        \n\t\n\tlen.resize(Nbin,0);\n\t step_size=Nsnp/Njack;\n         step_size_rem=Nsnp%Njack;\n        cout<<\"Number of SNPs per block : \"<<step_size<<endl;\n\tjack_bin.resize(Njack, vector<int>(Nbin,0));\n\tint i=0;\n        while(std::getline(ifs, line)){\n                in.clear();\n                in.str(line);\n                string temp;\n                \n\t\tin>>temp;        \n\t        int  cur = atoi(temp.c_str());\n\t\tSNP_annot.push_back(cur);\n\t\tlen[cur-1]++;\n\t\n\t\tint jack_val=i/step_size;\n\t\t if (jack_val==Njack)\n                    jack_val--;\n\t\tjack_bin[jack_val][SNP_annot[i]-1]++;\n\n               \n\t\t i++;\n        }\n\n\tif(Nsnp!=i){\n\t  cout<<\"Number of the rows in bim file and annotation file does not match\"<<endl;\n\t}\n\n\n        cout<<\"Total number of SNPs : \"<<Nsnp<<endl;\n        for (int i=0;i<Nbin;i++){\n                cout<<len[i]<<\" SNPs in \"<<i<<\"-th bin\"<<endl;\n        }\n\n        /*for (int i=0;i<Njack;i++){\n           for(int j=0;j<Nbin;j++)\n                cout<<jack_bin[i][j]<<\" \";\n          cout<<endl;\n        }*/\n\n\n}\n\nvoid read_bim (string filename){\n        ifstream inp(filename.c_str());\n        if (!inp.is_open()){\n                cerr << \"Error reading file \"<< filename <<endl;\n                exit(1);\n        }\n        string line;\n        int j = 0 ;\n        int linenum = 0 ;\n        while(std::getline (inp, line)){\n                linenum ++;\n                char c = line[0];\n                if (c=='#')\n                        continue;\n                istringstream ss (line);\n                if (line.empty())\n                        continue;\n                j++;\n        }\n        Nsnp = j;\n        inp.close();\n\tcout<<\"#SNP in bim file \"<<Nsnp<<endl;\n}\n\n\n\n\n\nvoid count_pheno(std::string filename){\n        ifstream ifs(filename.c_str(), ios::in);\n\n        std::string line;\n        int i=0;\n        while(std::getline(ifs, line)){\n                i++;\n        }\n        Nindv=i-1;\n}\n\n\n\n\nint  count_fam(std::string filename){\n        ifstream ifs(filename.c_str(), ios::in);\n\n        std::string line;\n        int i=0;\n        while(std::getline(ifs, line)){\n                i++;\n        }\n        return i;\n}\n\n\n\n//// functions related to reading without mailman\n\ntemplate<typename T>\nstatic std::istream & binary_read(std::istream& stream, T& value){\n        return stream.read(reinterpret_cast<char*>(&value), sizeof(T));\n}\n\nvoid set_metadata() {\n        wordsize = sizeof(char) * 8;\n        unitsize = 2;\n        unitsperword = wordsize/unitsize;\n        mask2 = 0;\n        for (int i = 0 ; i < unitsize; i++)\n                mask2 = mask2 |(0x1<<i);\n    nrow = Nsnp;\n    ncol = ceil(1.0*Nindv/unitsperword);\n}\n\n\nint simulate2_geno_from_random(float p_j){\n        float rval = static_cast <float> (rand()) / static_cast <float> (RAND_MAX);\n        float dist_pj[3] = { (1-p_j)*(1-p_j), 2*p_j*(1-p_j), p_j*p_j };\n        if(rval < dist_pj[0] )\n                return 0;\n        else if( rval >= dist_pj[0] && rval < (dist_pj[0]+dist_pj[1]))\n                return 1;\n        else\n                return 2;\n}\n\n\n\n\n\n\n\n\n\nfloat get_observed_pj(const unsigned char* line){\n        int y[4];\n        int observed_sum=0;\n        int observed_ct=0;\n\n        for (int k = 0 ;k < ncol ; k++) {\n                unsigned char c = line [k];\n                y[0] = (c)&mask2;\n                y[1] = (c>>2)&mask2;\n                y[2] = (c>>4)&mask2;\n                y[3] = (c>>6)&mask2;\n                int j0 = k * unitsperword;\n                int lmax = 4;\n                if (k == ncol - 1)  {\n                        lmax = Nindv%4;\n                        lmax = (lmax==0)?4:lmax;\n                }\n                for ( int l = 0 ; l < lmax; l++){\n                        int j = j0 + l ;\n                        // Extract  PLINK coded genotype and convert into 0/1/2\n                        // // PLINK coding: \n                        // // 00->0\n                        // // 01->missing\n                        // // 10->1\n                        // // 11->2\n                        int val = y[l];\n                        val-- ;\n                        if(val != 0){\n                                val =  (val < 0 ) ? 0 :val ;\n                                observed_sum += val;\n                                observed_ct ++;\n                        }\n                }\n        }\n        return observed_sum*0.5/observed_ct;\n\n}\n\n\n\nvoid read_bed (std::istream& ifs,bool allow_missing,int num_snp)  {\n         //ifstream ifs (filename.c_str(), ios::in|ios::binary);\n        char magic[3];\n        set_metadata ();\n\n    gtype =  new unsigned char[ncol];\n\n     if(read_header)  \n      binary_read(ifs,magic);\n\n        int sum=0;\n\n        // Note that the coding of 0 and 2 can get flipped relative to plink because plink uses allele frequency (minor)\n        // allele to code a SNP as 0 or 1.\n        // This flipping does not matter for results.\n        int y[4];\n        \nfor(int i=0;i<num_snp;i++){\n\t\tglobal_snp_index++;\n                ifs.read (reinterpret_cast<char*>(gtype), ncol*sizeof(unsigned char));\n                float p_j = get_observed_pj(gtype);\n        for (int k = 0 ;k < ncol ; k++) {\n                unsigned char c = gtype [k];\n                        // Extract PLINK genotypes\n                y[0] = (c)&mask2;\n                y[1] = (c>>2)&mask2;\n                y[2] = (c>>4)&mask2;\n                y[3] = (c>>6)&mask2;\n                        int j0 = k * unitsperword;\n                        // Handle number of individuals not being a multiple of 4\n                        int lmax = 4;\n                        if (k == ncol - 1)  {\n                                lmax = Nindv%4;\n                                lmax = (lmax==0)?4:lmax;\n                        }\n                        for ( int l = 0 ; l < lmax; l++){\n                                int j = j0 + l ;\n                                // Extract  PLINK coded genotype and convert into 0/1/2\n                                // PLINK coding: \n                                // 00->0\n                                // 01->missing\n                                // 10->1\n                                // 11->2\n                                int val = y[l];\n                                if(val==1 && !allow_missing){\n                                        val = simulate2_geno_from_random(p_j);\n                                        val++;\n                                        val = (val==1) ? 0 : val;\n  //                                 val=0;\n\t\t\t\t }\n                                val-- ;\n                                val =  (val < 0 ) ? 0 :val ;\n\t\t\t\tsum += val;\n\t\t\t   \n\t\t\t    for(int bin_index=0;bin_index<Nbin;bin_index++){\n\t\t\t\tif(annot_bool[global_snp_index][bin_index]==1){\n                        \t    \n\t\t\t\t      int snp_index;\n\t\t\t\t     //int snp_index=allgen[bin_index].index;\n\t\t\t\t     //allgen[bin_index].gen(snp_index,j)=val;\n\t\t\t\t\t\t\n\t\t\t\t     if(use_mailman==true){\n\t\t\t\t \t snp_index=allgen_mail[bin_index].index;\n\t\t\t\t\t int horiz_seg_no = snp_index/allgen_mail[bin_index].segment_size_hori; \n\t\t\t\t\t allgen_mail[bin_index].p[horiz_seg_no][j] = 3 *allgen_mail[bin_index].p[horiz_seg_no][j]  + val;\t \n\t\t\t\t     // computing sum for every snp to compute mean\n\t\t\t\t         allgen_mail[bin_index].columnsum[snp_index]+=val;\n\n\t\t\t\t      }\n\t\t\t\t     else{\n\t\t\t\t\t snp_index=allgen[bin_index].index;\n                                         allgen[bin_index].gen(snp_index,j)=val;\n\t\t\t\t     }\n\t\t\t\t\n\t\t\t\t}\n \t\t\t     \n\t\t\t    }\n\n                    }\n        }\n\n    for(int bin_index=0;bin_index<Nbin;bin_index++)\n       if(annot_bool[global_snp_index][bin_index]==1){\n       \t\t//cout<<\"global\"<<global_snp_index<<endl;\n\t\t        //cout<<allgen[bin_index].index<<endl; \n\t\t//       allgen[bin_index].index++;\n\t\n\t      if(use_mailman==true)\n\t\t  allgen_mail[bin_index].index++;\n\t       else\n\t           allgen[bin_index].index++;\t\t\n\t}\n\n    \n\n   }        \n\t\n\tsum = 0 ;\n        delete[] gtype;\n}\n\n\n\n\nvoid read_bed2 (std::istream& ifs,bool allow_missing,int num_snp)  {\n         //ifstream ifs (filename.c_str(), ios::in|ios::binary);\n        char magic[3];\n        set_metadata ();\n\n    gtype =  new unsigned char[ncol];\n\n     if(read_header)\n      binary_read(ifs,magic);\n \n        int sum=0;\n\n        // Note that the coding of 0 and 2 can get flipped relative to plink because plink uses allele frequency (minor)\n        // allele to code a SNP as 0 or 1.\n        // This flipping does not matter for results.\n        int y[4];\n\nint bin_pointer;\n\nvector<int> pointer_bins;\n\nfor(int i=0;i<num_snp;i++){\n                global_snp_index++;\n                ifs.read (reinterpret_cast<char*>(gtype), ncol*sizeof(unsigned char));\n                float p_j = get_observed_pj(gtype);\n\t \n\n\t   pointer_bins.clear();      \n       \t  for(int bin_index=0;bin_index<Nbin;bin_index++)\n       \t\tif(annot_bool[global_snp_index][bin_index]==1)\n\t\t\t  pointer_bins.push_back(bin_index);\n\t\t\t//bin_pointer=bin_index;\n\n\t  for (int k = 0 ;k < ncol ; k++) {\n                unsigned char c = gtype [k];\n                        // Extract PLINK genotypes\n                y[0] = (c)&mask2;\n                y[1] = (c>>2)&mask2;\n                y[2] = (c>>4)&mask2;\n                y[3] = (c>>6)&mask2;\n                        int j0 = k * unitsperword;\n                        // Handle number of individuals not being a multiple of 4\n                        int lmax = 4;\n                        if (k == ncol - 1)  {\n                                lmax = Nindv%4;\n                                lmax = (lmax==0)?4:lmax;\n                        }\n                        for ( int l = 0 ; l < lmax; l++){\n                                int j = j0 + l ;\n                                // Extract  PLINK coded genotype and convert into 0/1/2\n                                // PLINK coding: \n                                // 00->0\n                                // 01->missing\n                                // 10->1\n                                // 11->2\n                                int val = y[l];\n                                if(val==1 && !allow_missing){\n                                        val = simulate2_geno_from_random(p_j);\n                                        val++;\n                                        val = (val==1) ? 0 : val;\n                                   //val=0;\n                                 }\n                                val-- ;\n                                val =  (val < 0 ) ? 0 :val ;\n                                sum += val;\n\n                            for(int bin_index=0;bin_index<pointer_bins.size();bin_index++){\n\t\t\t\t\t\n\t\t\t\t       bin_pointer=pointer_bins[bin_index];\n                                      int snp_index;\n\n                                     if(use_mailman==true){\n                                         snp_index=allgen_mail[bin_pointer].index;\n                                         int horiz_seg_no = snp_index/allgen_mail[bin_pointer].segment_size_hori;\n                                         allgen_mail[bin_pointer].p[horiz_seg_no][j] = 3 *allgen_mail[bin_pointer].p[horiz_seg_no][j]  + val;\n                                     // computing sum for every snp to compute mean\n                                         allgen_mail[bin_pointer].columnsum[snp_index]+=val;\n\n                                      }\n                                     else{\n                                         snp_index=allgen[bin_pointer].index;\n                                         allgen[bin_pointer].gen(snp_index,j)=val;\n                                     }\n\n\n                            }\n\n                    }\n        }\n\n    for(int bin_index=0;bin_index<pointer_bins.size();bin_index++){\n     \t\tbin_pointer=pointer_bins[bin_index];\n\t         if(use_mailman==true)\n                  allgen_mail[bin_pointer].index++;\n               else\n                   allgen[bin_pointer].index++;\n    }\t\n\n\n\n}\n\n        sum = 0 ;\n        delete[] gtype;\n}\n\n\n\nvoid read_bed_1colannot (std::istream& ifs,bool allow_missing,int num_snp)  {\n         //ifstream ifs (filename.c_str(), ios::in|ios::binary);\n        char magic[3];\n        set_metadata ();\n\n    gtype =  new unsigned char[ncol];\n\n     if(read_header)\n      binary_read(ifs,magic);\n\n        int sum=0;\n\n        // Note that the coding of 0 and 2 can get flipped relative to plink because plink uses allele frequency (minor)\n        // allele to code a SNP as 0 or 1.\n        // This flipping does not matter for results.\n        int y[4];\n\nint bin_pointer;\n\n//vector<int> pointer_bins;\n\nfor(int i=0;i<num_snp;i++){\n                global_snp_index++;\n                ifs.read (reinterpret_cast<char*>(gtype), ncol*sizeof(unsigned char));\n                float p_j = get_observed_pj(gtype);\n\n          for (int k = 0 ;k < ncol ; k++) {\n                unsigned char c = gtype [k];\n                        // Extract PLINK genotypes\n                y[0] = (c)&mask2;\n                y[1] = (c>>2)&mask2;\n                y[2] = (c>>4)&mask2;\n                y[3] = (c>>6)&mask2;\n                        int j0 = k * unitsperword;\n                        // Handle number of individuals not being a multiple of 4\n                        int lmax = 4;\n                        if (k == ncol - 1)  {\n                                lmax = Nindv%4;\n                                lmax = (lmax==0)?4:lmax;\n                        }\n                        for ( int l = 0 ; l < lmax; l++){\n                                int j = j0 + l ;\n                                // Extract  PLINK coded genotype and convert into 0/1/2\n                                // PLINK coding: \n                                // 00->0\n                                // 01->missing\n                                // 10->1\n                                // 11->2\n                                int val = y[l];\n                                if(val==1 && !allow_missing){\n                                        val = simulate2_geno_from_random(p_j);\n                                        val++;\n                                        val = (val==1) ? 0 : val;\n                                   //val=0;\n                                 }\n                                val-- ;\n                                val =  (val < 0 ) ? 0 :val ;\n                                sum += val;\n//cout<<\"sss\"<<endl;\n//cout<<global_snp_index<<endl;\n\n                                       bin_pointer=SNP_annot[global_snp_index]-1;\n                           \n//\tcout<<bin_pointer<<endl;\n\t\t\t           int snp_index;\n                                     if(use_mailman==true){\n                                         snp_index=allgen_mail[bin_pointer].index;\n                                         int horiz_seg_no = snp_index/allgen_mail[bin_pointer].segment_size_hori;\n                                         allgen_mail[bin_pointer].p[horiz_seg_no][j] = 3 *allgen_mail[bin_pointer].p[horiz_seg_no][j]  + val;\n                                     // computing sum for every snp to compute mean\n                                         allgen_mail[bin_pointer].columnsum[snp_index]+=val;\n\n                                      }\n                                     else{\n                                         snp_index=allgen[bin_pointer].index;\n                                         allgen[bin_pointer].gen(snp_index,j)=val;\n                                     }\n\n\n                    }\n        }\n\n        \tbin_pointer=SNP_annot[global_snp_index]-1;\n\t         if(use_mailman==true)\n                  allgen_mail[bin_pointer].index++;\n               else\n                   allgen[bin_pointer].index++;\n}\n\n  sum = 0 ;\n  delete[] gtype;\n\n\n\n}\n\nMatrixXdr jack_se(MatrixXdr jack){\n\nint nrows=jack.rows();\nint ncols=jack.cols();\nMatrixXdr sum_row=jack.rowwise().mean();\nMatrixXdr SEjack;\nSEjack=MatrixXdr::Zero(nrows,1);\ndouble temp_val=0;\nfor (int i=0;i<nrows;i++){\n    for (int j=0;j<ncols;j++){\n        temp_val=jack(i,j)-sum_row(i);\n        temp_val= temp_val* temp_val;\n        SEjack(i,0)+=temp_val;\n    }\n    SEjack(i,0)=SEjack(i,0)*(Njack-1)/Njack;\n    SEjack(i,0)=sqrt(SEjack(i,0));\n}\n\n\nreturn SEjack;\n}\n\nint main(int argc, char const *argv[]){\n \n\n\nparse_args(argc,argv);\n////////////////////////////////////////////\n///////////////////////////////////////////\n    \n    //MAX_ITER =  command_line_opts.max_iterations ; \n        int B = command_line_opts.batchNum;\n        k_orig = command_line_opts.num_of_evec ;\n        debug = command_line_opts.debugmode ;\n        check_accuracy = command_line_opts.getaccuracy;\n        var_normalize = false;\n        accelerated_em = command_line_opts.accelerated_em;\n        k = k_orig + command_line_opts.l;\n        k = (int)ceil(k/10.0)*10;\n        command_line_opts.l = k - k_orig;\n        //p = Nsnp;\n        //n = Nindv;\n        //bool toStop=false;\n       // toStop=true;\n        srand((unsigned int) time(0));\n        //srand(1);\n\t//Nz=10;\n\tNz=command_line_opts.num_of_evec;\n        k=Nz;\n         ///clock_t io_end = clock();\n\n\tNjack=command_line_opts.jack_number;\n\t\n\tif(command_line_opts.memory_efficient==true){\n\t\treal_Njack=Njack;\n\t\tNjack=Njack*10;\n\t}\n\telse\n\t{\n\t\treal_Njack=Njack;\n\t}\n\tcout<<\"real_Njack \"<<real_Njack<<endl;\n////\nstring filename;\n//////////////////////////// Read multi genotypes\nstring line;\nint cov_num;\nint num_files=0;\nstring geno_name=command_line_opts.GENOTYPE_FILE_PATH;\n\n/////////Read bim file to count # SNPs\nstd::stringstream f1;\nf1 << geno_name << \".bim\";\nread_bim (f1.str());\n\n//////Read annotation files\nfilename=command_line_opts.Annot_PATH;\n\nif(use_1col_annot==true){\nread_annot_1col(filename);\n}\nelse{\nread_annot(filename);\nread_annot_real(filename);\n}\n//filename=command_line_opts.Annot_PATH;\n\n///reading phnotype and save the number of indvs\nfilename=command_line_opts.PHENOTYPE_FILE_PATH;\ncount_pheno(filename);\n\nstd::stringstream f0;\nf0 << geno_name << \".fam\";\nstring name_fam=f0.str();\nint fam_lines=count_fam(name_fam);\n\nif (fam_lines!=Nindv)\n\texitWithError(\"# indvs in fam file and pheno file does not match \");\n\nread_pheno2(Nindv,filename);\ncout<<\"Number of Indvs :\"<<Nindv<<endl;\ny_sum=pheno.sum();\n\n//read covariate\n//std::string covfile=\"/home/alipazoki/UKBB/kathy_pheno/height.covar\";\n//:qstd::string covfile=\"/home/alipazoki/UKBB/maf_ld/sub_indv/10k.bmi.covar\";\n//bool usee_cov=false;\n//if(usee_cov==true){\nstd::string covfile=command_line_opts.COVARIATE_FILE_PATH;\nstd::string covname=\"\";\nif(covfile!=\"\"){\n     use_cov=true;\n     cov_num=read_cov(false,Nindv, covfile, covname);\n\t//cout<<cov_num<<endl;\n}\nelse if(covfile==\"\"){\n     cout<<\"No Covariate File Specified\"<<endl;\n     both_side_cov=false;\n\n}\n/// regress out cov from phenotypes\n\nif(use_cov==true){\nMatrixXdr mat_mask=mask.replicate(1,cov_num);\ncovariate=covariate.cwiseProduct(mat_mask);\n\nMatrixXdr WtW= covariate.transpose()*covariate;\nQ=WtW.inverse(); // Q=(W^tW)^-1\n//cout<<\" Number of covariates\"<<cov_num<<endl;\n\n/*MatrixXdr v1=covariate.transpose()*pheno; //W^ty\nMatrixXdr v2=Q*v1;            //QW^ty\nMatrixXdr v3=covariate*v2;    //WQW^ty\nnew_pheno=pheno-v3;\nnew_pheno=new_pheno.cwiseProduct(mask);\n*/\nif (both_side_cov==false){\nMatrixXdr v1=covariate.transpose()*pheno; //W^ty\nMatrixXdr v2=Q*v1;            //QW^ty\nMatrixXdr v3=covariate*v2;    //WQW^ty\nnew_pheno=pheno-v3;\npheno=new_pheno.cwiseProduct(mask);\n\ny_sum=pheno.sum();\ny_mean = y_sum/mask.sum();\n  for(int i=0; i<Nindv; i++){\n       if(pheno(i,0)!=0)\n           pheno(i,0) =pheno(i,0) - y_mean; //center phenotype\n  }\ny_sum=pheno.sum();\n\n}\n\nif (both_side_cov==true){\ny_sum=pheno.sum();\ny_mean = y_sum/mask.sum();\n  for(int i=0; i<Nindv; i++){\n       if(pheno(i,0)!=0)\n           pheno(i,0) =pheno(i,0) - y_mean; //center phenotype\n  }\ny_sum=pheno.sum();\n\nv1=covariate.transpose()*pheno; //W^ty\nv2=Q*v1;            //QW^ty\nv3=covariate*v2;    //WQW^ty\nnew_pheno=pheno-v3;\nnew_pheno=new_pheno.cwiseProduct(mask);\n\n\n\n}\n\t\n\n\n\n}\nif(use_cov==false){\ny_sum=pheno.sum();\ny_mean = y_sum/mask.sum();\n  for(int i=0; i<Nindv; i++){\n       if(pheno(i,0)!=0)\n           pheno(i,0) =pheno(i,0) - y_mean; //center phenotype\n  }\ny_sum=pheno.sum();\n\n}\n                 \n////// normalize phenotype\n\n/*\n//bool pheno_norm=false;/\ny_sum=pheno.sum();\ny_mean = y_sum/mask.sum();\n\n//if(pheno_norm==true){\nfor(int i=0; i<Nindv; i++){\n   if(pheno(i,0)!=0)\n      pheno(i,0) =pheno(i,0) - y_mean; //center phenotype\n}\ny_sum=pheno.sum();\n\n//}\n\n*/\n\n\n\n\n\n\n//define random vector z's\n//Nz=1;\n\nall_zb= MatrixXdr::Random(Nindv,Nz);\nall_zb = all_zb * sqrt(3);\n\nboost::mt19937 seedr;\nseedr.seed(std::time(0));\nboost::normal_distribution<> dist(0,1);\nboost::variate_generator<boost::mt19937&, boost::normal_distribution<> > z_vec(seedr, dist);\n\nfor (int i=0;i<Nz;i++)\n   for(int j=0;j<Nindv;j++)\n      all_zb(j,i)=z_vec();\n\n\n\n\nfor (int i=0;i<Nz;i++)\n   for(int j=0;j<Nindv;j++)\n      all_zb(j,i)=all_zb(j,i)*mask(j,0);\n\n\n/*for (int i=0;i<Nindv;i++)\nfor (int j=0;j<Nz;j++)\n        all_zb(i,j)=pheno(i,0);\n*/\n\nif(both_side_cov==true){\n\nall_Uzb.resize(Nindv,Nz);\nfor (int j=0;j<Nz;j++){\n MatrixXdr w1=covariate.transpose()*all_zb.col(j);\n MatrixXdr w2=Q*w1;\n MatrixXdr w3=covariate*w2;\n all_Uzb.col(j)=w3;\n}\n\n}\n\n\nMatrixXdr output;\n//define \n\n//e\n//Njack=1;\n\nXXz=MatrixXdr::Zero(Nindv,Nbin*(real_Njack+1)*Nz);\n\nif(both_side_cov==true){\nUXXz=MatrixXdr::Zero(Nindv,Nbin*(real_Njack+1)*Nz);\nXXUz=MatrixXdr::Zero(Nindv,Nbin*(real_Njack+1)*Nz);\n//Xz=MatrixXdr::Zero(Nindv,Nbin*(Njack+1)*Nz);\n}\nyXXy=MatrixXdr::Zero(Nbin,real_Njack+1);\n\n//allgen.resize(Nbin);\nif(use_mailman==true) \n  allgen_mail.resize(Nbin);\nelse\n  allgen.resize(Nbin);\n \nint bin_index=0;\n///// code for handeling overlapping annotations\nstd::stringstream f3;\nf3 << geno_name << \".bed\";\nstring name=f3.str();\ncout<<name<<endl;\nifstream ifs (name.c_str(), ios::in|ios::binary);\nread_header=true;\nglobal_snp_index=-1;\n\n\ncout<<\"Start reading genotypes in blocks\"<<endl;\n    \n\n\nMatrixXdr vec1;\nMatrixXdr w1;\nMatrixXdr w2;\nMatrixXdr w3;\n\nint jack_index_real;\nfor (int jack_index=0;jack_index<Njack;jack_index++){\t\n\n\tjack_index_real=jack_index/10;\n\n\tint read_Nsnp=(jack_index<(Njack-1)) ? (step_size) : (step_size+step_size_rem);\n\t//cout<<Nsnp<<endl;\n/*\tfor (int bin_index=0;bin_index<Nbin;bin_index++){\n\t\n\n\t        allgen[bin_index].gen.resize(jack_bin[jack_index][bin_index],Nindv);\n\t        allgen[bin_index].index=0;\n       }\n*/\n       if(use_mailman==true){\n        for (int i=0;i<Nbin;i++){\n  //      cout<<\"eee\"<<endl;\n\tallgen_mail[i].segment_size_hori = floor(log(Nindv)/log(3)) - 2 ;\n        allgen_mail[i].Nsegments_hori = ceil(jack_bin[jack_index][i]*1.0/(allgen_mail[i].segment_size_hori*1.0));\n        allgen_mail[i].p.resize(allgen_mail[i].Nsegments_hori,std::vector<int>(Nindv));\n        allgen_mail[i].not_O_i.resize(jack_bin[jack_index][i]);\n        allgen_mail[i].not_O_j.resize(Nindv);\n\tallgen_mail[i].index=0;\n\tallgen_mail[i].Nsnp=jack_bin[jack_index][i];\n\tallgen_mail[i].Nindv=Nindv;\n       \t\n\t allgen_mail[i].columnsum.resize(jack_bin[jack_index][i],1);\n\t  for (int index_temp=0;index_temp<jack_bin[jack_index][i];index_temp++)\n\t\t    allgen_mail[i].columnsum[index_temp]=0;\n\n\t }\n       }\n       else{\n\t   for (int bin_index=0;bin_index<Nbin;bin_index++){\n                allgen[bin_index].gen.resize(jack_bin[jack_index][bin_index],Nindv);\n                allgen[bin_index].index=0;\n           }\n       }\n\n       \n\tif(use_1col_annot==true)\n\t\tread_bed_1colannot(ifs,missing,read_Nsnp);\n\telse\n\t\tread_bed2(ifs,missing,read_Nsnp);\n       read_header=false;\n\n     for (int bin_index=0;bin_index<Nbin;bin_index++){\n\t  int num_snp;\n\t  if (use_mailman==true)\n\t\tnum_snp=allgen_mail[bin_index].index;\n\t  else\n\t\tnum_snp=allgen[bin_index].index;\n\n\n\t  if(num_snp!=0){\n\t  stds.resize(num_snp,1);\n\t  means.resize(num_snp,1);\n\t  \n\t  if(use_mailman==true){\n\t\tfor (int i=0;i<num_snp;i++)\n\t\t   means(i,0)=(double)allgen_mail[bin_index].columnsum[i]/Nindv;\n    \t }\t\t\t\n          else\t  \n\t\tmeans=allgen[bin_index].gen.rowwise().mean();\n          \n\n\t  for (int i=0;i<num_snp;i++)\n\t       stds(i,0)=1/sqrt((means(i,0)*(1-(0.5*means(i,0)))));\n\n\t   //gen=allgen[bin_index].gen;\n\t   \n\t//   cout<<\"gen rows\"<<gen.rows()<<endl;\n//\t   cout<<\"jack \"<<jack_index<<\" bin \"<<bin_index<<\" num smp \"<<num_snp<<endl;\n\n\t   if (use_mailman==true){\n\t   \tg=allgen_mail[bin_index];\n                 g.segment_size_hori = floor(log(Nindv)/log(3)) - 2 ;\n        \t g.Nsegments_hori = ceil(jack_bin[jack_index][bin_index]*1.0/(g.segment_size_hori*1.0));\n        \t g.p.resize(g.Nsegments_hori,std::vector<int>(Nindv));\n        \t g.not_O_i.resize(jack_bin[jack_index][bin_index]);\n        \t g.not_O_j.resize(Nindv);\n\t\tinitial_var();\n\t   }\n\t  else{\n\t\t gen=allgen[bin_index].gen;\n\t\t\n          }  \n\n\t output=compute_XXz(num_snp);\n\n\t  /* if(use_mailman==true){\n                cout<<\"tttttttt\"<<endl;\n\t\tg=allgen_mail[bin_index];\n\t\tinitial_var();\n\t        output=compute_XXz(num_snp);\n           }*/\n\n          // cout<<\"dddddddddddddd\"<<endl;\n\t   for (int z_index=0;z_index<Nz;z_index++){\n\t\tif(num_snp!=len[bin_index])\n                 XXz.col((bin_index*(real_Njack+1)*Nz)+(jack_index_real*Nz)+z_index)+=output.col(z_index);\n                 XXz.col((bin_index*(real_Njack+1)*Nz)+(real_Njack*Nz)+z_index)+=output.col(z_index);   /// save whole sample\n\n\t\t if(both_side_cov==true) {\n\t\t  vec1=output.col(z_index);\n\t\t  w1=covariate.transpose()*vec1;\n                  w2=Q*w1;\n                  w3=covariate*w2;\n\t\t  if(num_snp!=len[bin_index])\n\t\t  UXXz.col((bin_index*(real_Njack+1)*Nz)+(jack_index_real*Nz)+z_index)+=w3;\n\t\t  UXXz.col((bin_index*(real_Njack+1)*Nz)+(real_Njack*Nz)+z_index)+=w3;\n\t\t }\n\n            }\n\n\t   if (both_side_cov==true){\n\t      output=compute_XXUz(num_snp); \n\t      for (int z_index=0;z_index<Nz;z_index++){\n                   if(num_snp!=len[bin_index])\n\t\t   XXUz.col((bin_index*(real_Njack+1)*Nz)+(jack_index_real*Nz)+z_index)+=output.col(z_index);\n                 XXUz.col((bin_index*(real_Njack+1)*Nz)+(real_Njack*Nz)+z_index)+=output.col(z_index);   /// save whole sample\n\t       }\t \n\t  }\n\t\t   \n\t   //compute yXXy\n\t\tdouble val_temp=0;\n\t   if(both_side_cov==false){\n\t   val_temp=compute_yXXy(num_snp);\n\t   yXXy(bin_index,jack_index_real)+=val_temp;\n\t   }\n\t   else{\n\t   val_temp=compute_yVXXVy(num_snp);\n\t   yXXy(bin_index,jack_index_real)+= val_temp;\n\n\t   }\n           yXXy(bin_index,real_Njack)+= val_temp;\n\t\n\t   if(num_snp==len[bin_index])\n\t\tyXXy(bin_index,jack_index_real)=0;\n\n\t  //compute Xz\n/*\n\t  if(both_side_cov==true){\n\t\tMatrixXdr out2=compute_Xz(num_snp);\n\t\t for (int z_index=0;z_index<Nz;z_index++){\n\t\t\t  if(num_snp!=len[bin_index])\n\t\t          Xz.col((bin_index*(Njack+1)*Nz)+(jack_index*Nz)+z_index)=out2.col(z_index);\n                 \t  Xz.col((bin_index*(Njack+1)*Nz)+(Njack*Nz)+z_index)+=out2.col(z_index);\t\n\t\t }\n\t  }\n\n*/\n\t\n\tcout<<num_snp<< \"SNPs in bin \"<<bin_index<<\" from \"<<jack_index<<\" block\"<<endl;   \n\t//cout<<\" Reading and computing bin \"<<bin_index <<\"  of \"<< jack_index<<\"-th is finished\"<<endl;\n\t   \n\t    if(use_mailman==true){\n\t\tdelete[] sum_op;\n        \tdelete[] partialsums;\n       \t\t delete[] yint_e;\n        \tdelete[] yint_m;\n        \tfor (int i  = 0 ; i < hsegsize; i++)\n                \tdelete[] y_m [i];\n        \tdelete[] y_m;\n\n        \tfor (int i  = 0 ; i < g.Nindv; i++)\n                \tdelete[] y_e[i];\n        \tdelete[] y_e;\n\n        \tstd::vector< std::vector<int> >().swap(g.p);\n        \tstd::vector< std::vector<int> >().swap(g.not_O_j);\n        \tstd::vector< std::vector<int> >().swap(g.not_O_i);\n\t\tstd::vector< std::vector<int> >().swap(allgen_mail[bin_index].p);\n                std::vector< std::vector<int> >().swap(allgen_mail[bin_index].not_O_j);\n                std::vector< std::vector<int> >().swap(allgen_mail[bin_index].not_O_i);\n        //g.p.clear();\n        //g.not_O_j.clear();\n        //g.not_O_i.clear();\n        \tg.columnsum.clear();\n        \tg.columnsum2.clear();\n        \tg.columnmeans.clear();\n       \t\t g.columnmeans2.clear();\n\t\t allgen_mail[bin_index].columnsum.clear();\n                allgen_mail[bin_index].columnsum2.clear();\n                allgen_mail[bin_index].columnmeans.clear();\n                 allgen_mail[bin_index].columnmeans2.clear();\n\t    }\n        }\n\n     }\n//cout<<\" Reading and computing  of \"<< jack_index<<\"-th is finished\"<<endl;\n}\n\ncout<<\" Reading and analysing of all blocks are finished\"<<endl;\n\nfor(int bin_index=0;bin_index<Nbin;bin_index++){\nfor(int jack_index=0;jack_index<real_Njack;jack_index++){\n        for (int z_index=0;z_index<Nz;z_index++){\n         \n\tMatrixXdr v1=XXz.col((bin_index*(real_Njack+1)*Nz)+(real_Njack*Nz)+z_index);\n        MatrixXdr v2=XXz.col((bin_index*(real_Njack+1)*Nz)+(jack_index*Nz)+z_index);\n\tXXz.col((bin_index*(real_Njack+1)*Nz)+(jack_index*Nz)+z_index)=v1-v2;\n\n\tif(both_side_cov==true){\n\t     v1=XXUz.col((bin_index*(real_Njack+1)*Nz)+(real_Njack*Nz)+z_index);\n             v2=XXUz.col((bin_index*(real_Njack+1)*Nz)+(jack_index*Nz)+z_index);\n             XXUz.col((bin_index*(real_Njack+1)*Nz)+(jack_index*Nz)+z_index)=v1-v2;\n\t\n\t     v1=UXXz.col((bin_index*(real_Njack+1)*Nz)+(real_Njack*Nz)+z_index);\n             v2=UXXz.col((bin_index*(real_Njack+1)*Nz)+(jack_index*Nz)+z_index);\n             UXXz.col((bin_index*(real_Njack+1)*Nz)+(jack_index*Nz)+z_index)=v1-v2;\n\n\t  \n           /*  v1=Xz.col((bin_index*(Njack+1)*Nz)+(Njack*Nz)+z_index);\n             v2=Xz.col((bin_index*(Njack+1)*Nz)+(jack_index*Nz)+z_index);\n             Xz.col((bin_index*(Njack+1)*Nz)+(jack_index*Nz)+z_index)=v1-v2;\n\t    */\n\t}\n\n\t\n\n       }\n        yXXy(bin_index,jack_index)=yXXy(bin_index,real_Njack)-yXXy(bin_index,jack_index);\n}\n}\n\n\n\n\n\n\n//cout<<\"sum col \"<<XXz.col(1).sum()<<endl;\n//cout<<\"yXXy\"<<yXXy<<endl;\n\t\n//// all XXy and yXXy and contributions of every jackknife subsamples  were computed till this line.\n\n/// normal equations LHS\nMatrixXdr  A_trs(Nbin,Nbin);\nMatrixXdr b_trk(Nbin,1);\nMatrixXdr c_yky(Nbin,1);\n\nMatrixXdr X_l(Nbin+1,Nbin+1);\nMatrixXdr Y_r(Nbin+1,1);\n//int bin_index=0;\nint jack_index=real_Njack;\nMatrixXdr B1;\nMatrixXdr B2;\nMatrixXdr C1;\nMatrixXdr C2;\ndouble trkij;\ndouble yy=(pheno.array() * pheno.array()).sum();\n\n\nif(both_side_cov==true){\nMatrixXdr Wty=covariate.transpose()*pheno; //W^ty\nMatrixXdr QWty=Q*Wty;\ndouble temp=(Wty.array() * QWty.array()).sum();\n\tyy=yy-temp;\n}\n\n\n\n\nint Nindv_mask=mask.sum();\nint NC;\nif(both_side_cov==true)\n   NC=Nindv_mask-cov_num;\nelse\n   NC=Nindv_mask;\n\n\n\n\n\n\n\nMatrixXdr jack;\nMatrixXdr point_est;\nMatrixXdr enrich_jack;\nMatrixXdr enrich_point_est;\n\njack.resize(Nbin+1,real_Njack);\npoint_est.resize(Nbin+1,1);\n\nenrich_jack.resize(Nbin,real_Njack);\nenrich_point_est.resize(Nbin,1);\n\n/*cout<<yXXy<<endl;\nfor (int i=0;i<Nbin;i++)\n   cout<<len[i]<<endl;\n*/\n\nMatrixXdr h1;\nMatrixXdr h2;\nMatrixXdr h3;\n\ndouble trkij_res1;\ndouble trkij_res2;\ndouble trkij_res3;\ndouble tk_res;\nfor (jack_index=0;jack_index<=real_Njack;jack_index++){\n  for (int i=0;i<Nbin;i++){\n\n\tif(both_side_cov==false)\t\n             b_trk(i,0)=Nindv_mask;\n\n\tif( jack_index<real_Njack && len[i]==jack_bin_real[jack_index][i])\n\t\t jack_bin_real[jack_index][i]=0;\n\n\n        if(jack_index==real_Njack)\n        c_yky(i,0)=yXXy(i,jack_index)/len[i];\n        else\n        c_yky(i,0)=yXXy(i,jack_index)/(len[i]-jack_bin_real[jack_index][i]);\n        //cout<<\"bin \"<<i<<\"yXXy \"<<yXXy(i,jack_index)<<endl;\n  \n       \n\tif(both_side_cov==true){\n\tB1=XXz.block(0,(i*(real_Njack+1)*Nz)+(jack_index*Nz),Nindv,Nz);\n\tC1=B1.array()*all_Uzb.array();\n        C2=C1.colwise().sum();\t\n\ttk_res=C2.sum();  \n\n\tif(jack_index==real_Njack)\n            tk_res=tk_res/len[i]/Nz;\n        else\n           tk_res=tk_res/(len[i]-jack_bin_real[jack_index][i])/Nz;\n\n        b_trk(i,0)=Nindv_mask-tk_res;\n\t}\n\n       for (int j=i;j<Nbin;j++){\n                //cout<<Njack<<endl;\n                B1=XXz.block(0,(i*(real_Njack+1)*Nz)+(jack_index*Nz),Nindv,Nz);\n                B2=XXz.block(0,(j*(real_Njack+1)*Nz)+(jack_index*Nz),Nindv,Nz);\n                C1=B1.array()*B2.array();\n                C2=C1.colwise().sum();\n                trkij=C2.sum();\n\n\n\t\tif(both_side_cov==true){\n\n\t\t\th1=covariate.transpose()*B1;\n                        h2=Q*h1;\n                        h3=covariate*h2;\n\t\t\tC1=h3.array()*B2.array();\n\t\t        C2=C1.colwise().sum();\n                        trkij_res1=C2.sum();\n\n\t\t        /*h1=covariate.transpose()*B2;\n                        h2=Q*h1;\n                        h3=covariate*h2;\n                        C1=h3.array()*B1.array();\n                        C2=C1.colwise().sum();\n                        trkij_res2=C2.sum();\n\t\t\t*/\n\n\t\t\tB1=XXUz.block(0,(i*(real_Njack+1)*Nz)+(jack_index*Nz),Nindv,Nz);\n               \t        B2=UXXz.block(0,(j*(real_Njack+1)*Nz)+(jack_index*Nz),Nindv,Nz);\n                        C1=B1.array()*B2.array();\n                        C2=C1.colwise().sum();\n                        trkij_res3=C2.sum();\n\n\t\t\t\n/*\t\t\tcout<<\"trrrr\"<<endl;\n\t\t\tcout<<trkij<<endl;\n\t\t\tcout<<trkij_res3<<endl;\n\t//\t\tcout<<trkij_res2<<endl;\n\t\t\tcout<<trkij_res1<<endl;\n\t\t\t cout<<\"trrrr\"<<endl;\n*/\n\t\t\ttrkij+=trkij_res3-trkij_res1-trkij_res1 ;\n\t     \n\t\t\t\n/*\n\t\t       B1=Xz.block(0,(i*(Njack+1)*Nz)+(jack_index*Nz),Nindv,Nz);\n\t\t       h1=covariate.transpose()*B1; //W^tXz\n                       h2=Q*h1;  //QW^tXz\n\t\t       \n\t\t       C1=h2.array()*h1.array();\n                        C2=C1.colwise().sum();\n\n\t\t\ttk_res=C2.sum();\t\n\n\t\t\tif(jack_index==Njack)\n\t\t\t\ttk_res=tk_res/len[i]/Nz;\n\t\t\telse\n\t\t\t  \ttk_res=tk_res/(len[i]-jack_bin[jack_index][i])/Nz;\t\n\t\t\n\t\t \tb_trk(i,0)=Nindv_mask-tk_res;\n*/\n\t     }\n\n\n\n\n                //cout<<\"tr\"<<i<<\" \"<<j<<\" : \"<<trkij<<endl;\n                if(jack_index==real_Njack)\n                trkij=trkij/len[i]/len[j]/Nz;\n                else\n                 trkij=trkij/(len[i]-jack_bin_real[jack_index][i])/(len[j]-jack_bin_real[jack_index][j])/Nz;\n                A_trs(i,j)=trkij;\n                A_trs(j,i)=trkij;\n\n        }\n  }\n\n\nX_l<<A_trs,b_trk,b_trk.transpose(),NC;\nY_r<<c_yky,yy;\n\n/*if(jack_index==Njack){\n   cout<<X_l<<endl;\n   cout<<Y_r<<endl;\n}\n  */ \nMatrixXdr herit=X_l.colPivHouseholderQr().solve(Y_r);\n\n\nif(jack_index==real_Njack){\n    cout<<\"Xl\"<<X_l<<endl;\n\tcout<<\"Yl\"<<Y_r<<endl;\n\n     for(int i=0;i<(Nbin+1);i++)\n          point_est(i,0)=herit(i,0);\n}\nelse{\n//if (jack_index==1)\n  // cout<<\"Xl\"<<X_l<<endl;\nfor(int i=0;i<(Nbin+1);i++)\n      jack(i,jack_index)=herit(i,0);\n}\n\n/*double total_val=0;\nfor(int i=0; i<Nbin;i++)\n    total_val+=herit(i,0);\n*/\n\n}//end of loop over jack\n\n\ndouble temp_sig=0;\ndouble temp_sum=0;\n\nstd::ofstream outfile;\nstring add_output=command_line_opts.OUTPUT_FILE_PATH;\noutfile.open(add_output.c_str(), std::ios_base::out);\n\ncout<<\"Annotation file info :\"<<endl;\nint selected_snps=0;\nfor (int i=0;i<Nbin;i++){\n   cout<<len[i]<<\" SNPs in \"<<i<<\"-th bin\"<<endl;\n      selected_snps+=len[i];\n}\ncout<<\" Number of selected SNPs w.r.t  annot file : \" <<selected_snps<<endl;\n\n\n\ncout<<endl<<\"OUTPUT: \"<<endl<<\"Variances: \"<<endl;\noutfile<<\"OUTPUT: \"<<endl<<\"Variances: \"<<endl;\nfor (int j=0;j<Nbin;j++){\n        cout<<\"Sigma^2_\"<<j<<\": \"<<point_est(j,0)<<endl;\n\toutfile<<\"Sigma^2_\"<<j<<\": \"<<point_est(j,0)<<endl;\n}\ncout<<\"Sigma^2_e: \"<<point_est(Nbin,0)<<endl;\noutfile<<\"Sigma^2_e: \"<<point_est(Nbin,0)<<endl;\n\n\n///compute h^2s\n\n\ntemp_sum=point_est.sum();\nfor (int j=0;j<Nbin;j++){\n        point_est(j,0)=point_est(j,0)/temp_sum;\n        temp_sig+=point_est(j,0);\n}\npoint_est(Nbin,0)=temp_sig;\n\nfor (int i=0;i<real_Njack;i++){\n   temp_sig=0;\n   temp_sum=jack.col(i).sum();\n   for (int j=0;j<Nbin;j++){\n        jack(j,i)=jack(j,i)/temp_sum;\n        temp_sig+=jack(j,i);\n   }\n   jack(Nbin,i)=temp_sig;\n   //cout<<\"jack\"<<i<<\" :\"<<temp_sig<<endl;\n}\n////\n\n\n\n////compute h^2 based on ldsc definition\nMatrixXdr her_per_snp;\nMatrixXdr her_cat_ldsc;\nMatrixXdr point_her_cat_ldsc;;\nher_cat_ldsc=MatrixXdr::Zero(Nbin,real_Njack);\nMatrixXdr her_per_snp_inbin(Nbin,1);\npoint_her_cat_ldsc=MatrixXdr::Zero(Nbin,1);\n\nfor (int k=0;k<=real_Njack;k++){\n\nif(k==real_Njack){\nfor(int i=0;i<Nbin;i++){\n    her_per_snp_inbin(i,0)=(double)point_est(i,0)/len[i];\n}\n}\nelse{\nfor(int i=0;i<Nbin;i++){\n    her_per_snp_inbin(i,0)=(double)jack(i,k)/len[i];\n}\n\n}\n//MatrixXdr her_per_snp;\n//MatrixXdr her_cat_ldsc;\n//MatrixXdr point_her_cat_ldsc;\nher_per_snp=MatrixXdr::Zero(Nsnp,1);\n//her_cat_ldsc=MatrixXdr::Zero(Nbin,Njack);\n//point_her_cat_ldsc=MatrixXdr::Zero(Nbin,1);\n\nfor(int i=0;i<Nsnp;i++){\n   for(int j=0;j<Nbin;j++){\n      if(annot_bool_real[i][j]==1)\n             her_per_snp(i,0)+=her_per_snp_inbin(j,0);\t     \t  \n   }\n\n   if(k==real_Njack){\n\n   for(int j=0;j<Nbin;j++)\n      if(annot_bool_real[i][j]==1)\n             point_her_cat_ldsc(j,0)+=her_per_snp(i,0);\n   \n   }\n   else\n   {\n\n   for(int j=0;j<Nbin;j++)\n      if(annot_bool_real[i][j]==1)\n             her_cat_ldsc(j,k)+=her_per_snp(i,0);\n    \n   }\n\n}\n}\n\n\n\n/*for(int i=0;i<Nsnp;i++){\n   for(int j=0;j<Nbin;j++){\n        int temp=i/step_size;\n        if (temp==Njack)\n             temp--;\n        if (annot_bool[i][j]==1){\n                her_cat_ldsc(j,temp)+=her_per_snp(i,0);\n//              her_cat_ldsc(j,Njack)+=her_per_snp(i,0);\n        }\n   }\n}\n*/\n\n//cout<<her_cat_ldsc<<endl;\n//MatrixXdr point_her_cat_ldsc=her_cat_ldsc.rowwise().sum();\n//cout<<point_her_cat_ldsc<<endl;\n\n//for (int i=0;i<Nbin;i++)\n //   for(int j=0;j<Njack;j++)\n   //        her_cat_ldsc(i,j)=point_her_cat_ldsc(i,0)- her_cat_ldsc(i,j);\n\n\n\n//cout<<point_her_cat_ldsc<<endl;\n\n\nMatrixXdr se_her_cat_ldsc=jack_se(her_cat_ldsc);\n//cout<<se_her_cat_ldsc<<endl;\n\ncout<<endl<<\"h^2's (heritabilities) and e's (enrichments) are computed based on Equation 9 (overlapping setting) in the paper  https://doi.org/10.1038/s41467-020-17576-9:\"<<endl;\noutfile<<endl<<\"h^2's (heritabilities) and e's (enrichments) are computed based on Equation 9 (overlapping setting) in the paper  https://doi.org/10.1038/s41467-020-17576-9:\"<<endl;\n\ncout<<endl<<\"h^2's: \"<<endl;\noutfile<<\"h^2's: \"<<endl;\nfor (int j=0;j<Nbin;j++){\n     cout<<\"h^2 of bin \"<<j<<\" : \"<<point_her_cat_ldsc(j,0)<<\" ,  se: \"<<se_her_cat_ldsc(j,0)<<endl;\n     outfile<<\"h^2 of bin \"<<j<<\" : \"<<point_her_cat_ldsc(j,0)<<\" ,  se: \"<<se_her_cat_ldsc(j,0)<<endl;\n}\n\n\n///prop of h2 ldsc def\n\nfor (int i=0;i<Nbin;i++)\n  point_her_cat_ldsc(i,0)=(double)point_her_cat_ldsc(i,0)/point_est(Nbin,0);\n\nfor(int i=0;i<real_Njack;i++)\n   for(int j=0;j<Nbin;j++)\n\ther_cat_ldsc(j,i)=(double)her_cat_ldsc(j,i)/jack(Nbin,i);\t  \n\n\n////print prop of h2 \n se_her_cat_ldsc=jack_se(her_cat_ldsc);\n\ncout<<endl<<\"h^2_i/h^2_t: \"<<endl;\noutfile<<\"h^2_i/h^2_t: \"<<endl;\nfor (int j=0;j<Nbin;j++){\n     cout<<\"h^2/h^2_t of bin \"<<j<<\" : \"<<point_her_cat_ldsc(j,0)<<\",  se: \"<<se_her_cat_ldsc(j,0)<<endl;\n     outfile<<\"h^2/h^2_t of bin \"<<j<<\" : \"<<point_her_cat_ldsc(j,0)<<\",  se: \"<<se_her_cat_ldsc(j,0)<<endl;\n}\n\n\ncout<<endl<<\"Enrichments: \"<<endl;\noutfile<<\"Enrichments: \"<<endl;\nfor (int j=0;j<Nbin;j++){\n\tdouble snp_por=(double)len[j]/Nsnp;\n     cout<<\"Enrichment of bin \"<<j<<\" : \"<<point_her_cat_ldsc(j,0)/snp_por<<\",  se: \"<<se_her_cat_ldsc(j,0)/snp_por<<endl;\n     outfile<<\"Enrichment of bin \"<<j<<\" : \"<<point_her_cat_ldsc(j,0)/snp_por<<\",  se: \"<<se_her_cat_ldsc(j,0)/snp_por<<endl;\n}\n\n///////////////////end h2 based on ldsc def\n\n\n\n\n\n///compute enrichment\n\ndouble per_her;\ndouble per_size;\nint total_size=0;\n\n//for (int i=0;i<Nbin;i++)\n  // total_size+=len[i];\ntotal_size=Nsnp;\n\nfor (int j=0;j<Nbin;j++){\n        per_her=point_est(j,0)/point_est(Nbin,0);\n        per_size=(double)len[j]/total_size;\n        enrich_point_est(j,0)=per_her/per_size;\n        //cout<<j<<\" \"<<per_her<<\" \"<<total_size<<\" \"<<len[j]<<\" \"<<per_size<<\" \"<<enrich_point_est(j,0)<<endl;\n}\n\n\nfor (int i=0;i<real_Njack;i++){\n    per_size=0;\n    /*total_size=0;\n    for (int j=0;j<Nbin;j++){\n        total_size+=(len[j]-jack_bin[i][j]);\n    } */\n\n    step_size=Nsnp/real_Njack;\n    step_size_rem=Nsnp%real_Njack;\n\t\n   int num_snp_in_jack=(i<(real_Njack-1)) ? (step_size) : (step_size+step_size_rem);\n   total_size=Nsnp-num_snp_in_jack;\n   for (int j=0;j<Nbin;j++){\n        per_her=jack(j,i)/jack(Nbin,i);\n        per_size=(double)(len[j]-jack_bin_real[i][j])/total_size;\n        enrich_jack(j,i)=per_her/per_size;\n        }\n}\n\n\n\n//compute se if h2 and enirchment\n\nMatrixXdr SEjack;\nSEjack=MatrixXdr::Zero(Nbin+1,1);\nSEjack=jack_se(jack);\n\n\nMatrixXdr enrich_SEjack;\nenrich_SEjack=MatrixXdr::Zero(Nbin,1);\nenrich_SEjack=jack_se(enrich_jack);\n\n\n\n\n\n\n/*\n////compute jackknife SE\nMatrixXdr sum_row=jack.rowwise().mean();\nMatrixXdr SEjack;\nSEjack=MatrixXdr::Zero(Nbin+1,1);\ndouble temp_val=0;\nfor (int i=0;i<=Nbin;i++){\n    for (int j=0;j<Njack;j++){\n        temp_val=jack(i,j)-sum_row(i);\n        temp_val= temp_val* temp_val;\n        SEjack(i,0)+=temp_val;\n    }\n    SEjack(i,0)=SEjack(i,0)*(Njack-1)/Njack;\n    SEjack(i,0)=sqrt(SEjack(i,0));\n}\n///////// compute jackknife SE of enrichment\nMatrixXdr sum_row=enrich_jack.rowwise().mean();\nMatrixXdr enrich_SEjack;\nenrich_SEjack=MatrixXdr::Zero(Nbin,1);\n double temp_val=0;\nfor (int i=0;i<Nbin;i++){\n    for (int j=0;j<Njack;j++){\n        temp_val=enrich_jack(i,j)-sum_row(i);\n        temp_val= temp_val* temp_val;\n        enrich_SEjack(i,0)+=temp_val;\n    }\n    enrich_SEjack(i,0)=enrich_SEjack(i,0)*(Njack-1)/Njack;\n    enrich_SEjack(i,0)=sqrt(enrich_SEjack(i,0));\n}\n*/\ncout<<endl<<\"h^2's (heritabilities) and e's (enrichments) are computed based on Equations 2-4 (non-overlapping setting) in the paper  https://doi.org/10.1038/s41467-020-17576-9:\"<<endl;\noutfile<<endl<<\"h^2's (heritabilities) and e's (enrichments) are computed based on Equations 2-4 (non-overlapping setting) in the paper  https://doi.org/10.1038/s41467-020-17576-9:\"<<endl;\n\ncout<<endl<<\"h^2's: \"<<endl;\noutfile<<\"h^2's: \"<<endl;\nfor (int j=0;j<Nbin;j++){\n     cout<<\"h^2 of bin \"<<j<<\" : \"<<point_est(j,0)<<\",  se: \"<<SEjack(j,0)<<endl;\n     outfile<<\"h^2 of bin \"<<j<<\" : \"<<point_est(j,0)<<\",  se: \"<<SEjack(j,0)<<endl;\n}\ncout<<\"Total h^2 : \"<<point_est(Nbin,0)<<\", se: \"<<SEjack(Nbin,0)<<endl;\noutfile<<\"Total h^2 : \"<<point_est(Nbin,0)<<\", se: \"<<SEjack(Nbin,0)<<endl;\n\ncout<<endl<<\"Enrichments: \"<<endl;\noutfile<<\"Enrichments: \"<<endl;\nfor (int j=0;j<Nbin;j++){\n     cout<<\"Enrichment of bin \"<<j<<\": \"<<enrich_point_est(j,0)<<\" ,  se: \"<<enrich_SEjack(j,0)<<endl;\n     outfile<<\"Enrichment of bin \"<<j<<\": \"<<enrich_point_est(j,0)<<\" ,  se: \"<<enrich_SEjack(j,0)<<endl;\n}\n/*std::ofstream outfile;\nstring add_output=command_line_opts.OUTPUT_FILE_PATH;\noutfile.open(add_output.c_str(), std::ios_base::app);\n\noutfile<<\"Point estimates: \"<<endl;\noutfile<<point_est.transpose()<<endl;\noutfile<<\"SEs     :\"<<endl;\noutfile<<SEjack.transpose()<<endl;\n\noutfile<<\"Enrichment: \"<<endl;\noutfile<<enrich_point_est.transpose()<<endl;\noutfile<<\"SEs     :\"<<endl;\noutfile<<enrich_SEjack.transpose()<<endl;\n*/\n\treturn 0;\n}\n", "meta": {"hexsha": "f6fd1f25b8f1871c7e12c1234c05246f4dc20557", "size": 68257, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/rhemc_ldsc_her_def_stream.cpp", "max_stars_repo_name": "fcooper8472/RHE-mc", "max_stars_repo_head_hexsha": "e2c87e10dff5b668aa2e145fd43b61a0da91d16b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-08T17:07:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-08T17:07:08.000Z", "max_issues_repo_path": "src/rhemc_ldsc_her_def_stream.cpp", "max_issues_repo_name": "fcooper8472/RHE-mc", "max_issues_repo_head_hexsha": "e2c87e10dff5b668aa2e145fd43b61a0da91d16b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2020-09-30T14:53:00.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-22T20:04:23.000Z", "max_forks_repo_path": "src/rhemc_ldsc_her_def_stream.cpp", "max_forks_repo_name": "fcooper8472/RHE-mc", "max_forks_repo_head_hexsha": "e2c87e10dff5b668aa2e145fd43b61a0da91d16b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2019-06-06T02:18:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-26T17:02:56.000Z", "avg_line_length": 26.3642332947, "max_line_length": 188, "alphanum_fraction": 0.5415268764, "num_tokens": 19842, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.45251225305011544}}
{"text": "// Dylan Losey, June 27, 2019.\n// print the current robot state\n\n\n#include <iostream>\n#include <Eigen/Core>\n\n#include <franka/exception.h>\n#include <franka/robot.h>\n#include <franka/model.h>\n\n\nint main() {\n\n  try {\n    franka::Robot robot(\"172.16.0.3\");\n    franka::Model model = robot.loadModel();\n\n    franka::RobotState robot_state = robot.readOnce();\n\n    Eigen::Map<const Eigen::Matrix<double, 4, 4> > T(robot_state.O_T_EE.data());\n    std::array<double, 42> jacobian_array = model.zeroJacobian(franka::Frame::kEndEffector, robot_state);\n    Eigen::Map<const Eigen::Matrix<double, 6, 7> > jacobian(jacobian_array.data());\n    // Eigen::Map<const Eigen::Matrix<double, 7, 1> > robot_state.q.data();\n    // Eigen::VectorXd xdot = jacobian * qdot;\n\n\n    std::cout << \"Here is the current robot state: \\n\" << std::endl;\n    std::cout << robot_state << std::endl;\n\n    std::cout << \"\\nHere is the current end-effector pose: \\n\" << std::endl;\n    std::cout << T << std::endl;\n\n    std::cout << \"\\nHere is the robot joint value: \\n\" << std::endl;\n    // std::cout << q << std::endl;\n\n\n  } catch (franka::Exception const& e) {\n    std::cout << e.what() << std::endl;\n    return -1;\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "94cb00656228bb09c36ae784813dff78404bc10b", "size": 1198, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/print_robot_state.cpp", "max_stars_repo_name": "ziangliuusc/libfranka", "max_stars_repo_head_hexsha": "c122dd012ed3d1c95776c71293f19d1b8bea0143", "max_stars_repo_licenses": ["Apache-2.0"], "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/print_robot_state.cpp", "max_issues_repo_name": "ziangliuusc/libfranka", "max_issues_repo_head_hexsha": "c122dd012ed3d1c95776c71293f19d1b8bea0143", "max_issues_repo_licenses": ["Apache-2.0"], "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/print_robot_state.cpp", "max_forks_repo_name": "ziangliuusc/libfranka", "max_forks_repo_head_hexsha": "c122dd012ed3d1c95776c71293f19d1b8bea0143", "max_forks_repo_licenses": ["Apache-2.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.6222222222, "max_line_length": 105, "alphanum_fraction": 0.6277128548, "num_tokens": 357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.45249133264484054}}
{"text": "#include <Eigen/Eigen>\n#include <boost/python/numpy.hpp>\n\nnamespace bp = boost::python;\nnamespace np = boost::python::numpy;\n\n#define EIGEN_ARRAY_CONVERTER(Type, N)                                                                                 \\\n    EigenFromPython<Type, N>();                                                                                        \\\n    bp::to_python_converter<Eigen::Ref<Type>, EigenToPython<Type>>();                                                  \\\n    EigenFromPython<const Type, N>();                                                                                  \\\n    bp::to_python_converter<Eigen::Ref<const Type>, EigenToPython<const Type>>();\n\ntemplate <typename T>\nstruct EigenToPython\n{\n    static PyObject *convert(const Eigen::Ref<T> &m)\n    {\n        double *data = const_cast<double *>(m.data());\n        bp::object capsule(\n            bp::handle<>(PyCapsule_New(new Eigen::Map<T>(data, m.rows(), m.cols()), nullptr, [](PyObject *ptr) {\n                delete (Eigen::Map<T> *)PyCapsule_GetPointer(ptr, nullptr);\n            })));\n        return boost::python::incref(\n            np::from_data(data, np::dtype::get_builtin<double>(), bp::make_tuple(m.rows(), m.cols()),\n                          bp::make_tuple(m.rowStride() * sizeof(double), m.colStride() * sizeof(double)), capsule)\n                .ptr());\n    }\n};\ntemplate <>\nPyObject *EigenToPython<Eigen::VectorXd>::convert(const Eigen::Ref<Eigen::VectorXd> &v)\n{\n    double *data = const_cast<double *>(v.data());\n    bp::object capsule(\n        bp::handle<>(PyCapsule_New(new Eigen::Map<Eigen::VectorXd>(data, v.rows()), nullptr, [](PyObject *ptr) {\n            delete (Eigen::Map<Eigen::VectorXd> *)PyCapsule_GetPointer(ptr, nullptr);\n        })));\n    return boost::python::incref(np::from_data(data, np::dtype::get_builtin<double>(), bp::make_tuple(v.rows()),\n                                               bp::make_tuple(v.innerStride() * sizeof(double)), capsule)\n                                     .ptr());\n}\ntemplate <>\nPyObject *EigenToPython<const Eigen::VectorXd>::convert(const Eigen::Ref<const Eigen::VectorXd> &v)\n{\n    double *data = const_cast<double *>(v.data());\n    bp::object capsule(\n        bp::handle<>(PyCapsule_New(new Eigen::Map<Eigen::VectorXd>(data, v.rows()), nullptr, [](PyObject *ptr) {\n            delete (Eigen::Map<Eigen::VectorXd> *)PyCapsule_GetPointer(ptr, nullptr);\n        })));\n    return boost::python::incref(np::from_data(data, np::dtype::get_builtin<double>(), bp::make_tuple(v.rows()),\n                                               bp::make_tuple(v.innerStride() * sizeof(double)), capsule)\n                                     .ptr());\n}\n\ntemplate <typename T>\nvoid copy_ndarray(const np::ndarray &array, void *storage)\n{\n    new (storage) Eigen::Ref<T>(Eigen::Map<T, 0, Eigen::OuterStride<>>(reinterpret_cast<double *>(array.get_data()),\n                                                                       array.shape(0), array.shape(1),\n                                                                       Eigen::OuterStride<>(array.strides(1))));\n}\ntemplate <>\nvoid copy_ndarray<Eigen::VectorXd>(const np::ndarray &array, void *storage)\n{\n    new (storage) Eigen::Ref<Eigen::VectorXd>(\n        Eigen::Map<Eigen::VectorXd>(reinterpret_cast<double *>(array.get_data()), array.shape(0)));\n}\ntemplate <>\nvoid copy_ndarray<const Eigen::VectorXd>(const np::ndarray &array, void *storage)\n{\n    new (storage) Eigen::Ref<const Eigen::VectorXd>(\n        Eigen::Map<const Eigen::VectorXd>(reinterpret_cast<double *>(array.get_data()), array.shape(0)));\n}\n\ntemplate <typename T, int N>\nstruct EigenFromPython\n{\n    EigenFromPython()\n    {\n        bp::converter::registry::push_back(&convertible, &construct, bp::type_id<Eigen::Ref<T>>());\n    }\n\n    static void *convertible(PyObject *p)\n    {\n        try\n        {\n            bp::object obj(bp::handle<>(bp::borrowed(p)));\n            std::unique_ptr<np::ndarray> array(new np::ndarray(\n                np::from_object(obj, np::dtype::get_builtin<double>(), N, N, np::ndarray::C_CONTIGUOUS)));\n            return array.release();\n        }\n        catch (bp::error_already_set &err)\n        {\n            bp::handle_exception();\n            return nullptr;\n        }\n    }\n\n    static void construct(PyObject *objPtr, bp::converter::rvalue_from_python_stage1_data *data)\n    {\n        std::unique_ptr<np::ndarray> array(reinterpret_cast<np::ndarray *>(data->convertible));\n        void *storage =\n            reinterpret_cast<bp::converter::rvalue_from_python_storage<Eigen::Ref<T>> *>(data)->storage.bytes;\n        copy_ndarray<T>(*array, storage);\n        data->convertible = storage;\n    }\n};\n", "meta": {"hexsha": "7d96ff402d9fdc7e5adaa10f3e4d29c8cba1543b", "size": 4709, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "py-bindings/numpy_eigen.cpp", "max_stars_repo_name": "jingxixu/ompl", "max_stars_repo_head_hexsha": "91aa14ef925e49d30980776411a76a1de719dde3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-20T03:53:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-20T03:53:52.000Z", "max_issues_repo_path": "py-bindings/numpy_eigen.cpp", "max_issues_repo_name": "jingxixu/ompl", "max_issues_repo_head_hexsha": "91aa14ef925e49d30980776411a76a1de719dde3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "py-bindings/numpy_eigen.cpp", "max_forks_repo_name": "jingxixu/ompl", "max_forks_repo_head_hexsha": "91aa14ef925e49d30980776411a76a1de719dde3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-05T12:23:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-05T12:23:32.000Z", "avg_line_length": 44.0093457944, "max_line_length": 120, "alphanum_fraction": 0.552771289, "num_tokens": 1023, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.45249133264484054}}
{"text": "#ifndef LINEAR_SOLVER_H\n#define LINEAR_SOLVER_H\n#include \"mtao/types.hpp\"\n#include <Eigen/Sparse>\n#include <memory>\n\nnamespace mtao::solvers::linear {\ntemplate <typename Matrix, typename Vector>\nstruct LinearSolverDerived\n{\n    LinearSolverDerived(const Matrix & A_, const Vector & b_, Vector & x_): A(A_), b(b_), x(x_) {}\n    typedef typename Vector::Scalar Scalar;\n    virtual void step() = 0;\n\n    protected:\n    const Matrix & A;\n    const Vector & b;\n    Vector & x;\n};\n\n\ntemplate <typename DerivedDerived, typename Matrix, typename Vector>\nDerivedDerived createLinearDerived(const Matrix & A, const Vector & b, Vector & x)\n{\n    return DerivedDerived(A,b,x);\n}\n\n\ntemplate <typename SolverType>\nstruct solver_traits {\n    using Scalar = double;\n    using Matrix = Eigen::SparseMatrix<Scalar>;\n    using Vector = mtao::VectorX<double>;\n};\n\ntemplate <typename Derived>\nstruct IterativeLinearSolver\n{\n\n    Derived& derived() { return *static_cast<Derived*>(this); }\n    const Derived& derived() const { return *static_cast<const Derived*>(this); }\n    using Traits = solver_traits<Derived>;\n    typedef typename Traits::Matrix Matrix;\n    typedef typename Traits::Vector Vector;\n    typedef typename Traits::Scalar Scalar;\n    IterativeLinearSolver(int max_its=1000, Scalar eps=0.001):\n        epsilon(eps), max_iterations(max_its) {}\n\n\n    //Scalar error() const { return derived().error(); }\n    virtual Scalar error()\n    {\n        return (b()-A()*x()).template lpNorm<Eigen::Infinity>();\n    }\n    void step() { return derived().step(); }\n    void solve()\n    {\n        int iterations = 0;\n        while(++iterations < max_iterations &&\n                error() > epsilon)\n        {\n            step();\n        }\n        //if(iterations >= max_iterations)\n        //std::cout << iterations << \"/\" << max_iterations << \": \" << capsule->error() << \"/\" << epsilon << std::endl;\n    }\n    void compute() {\n        derived().compute();\n    }\n    void compute(const Matrix & A, const Vector & b) {\n        _A = &A;\n        _b = &b;\n        _x.resize(A.rows());\n        compute();\n    }\n    void compute(const Matrix & A, const Vector & b, const Vector& x) {\n        _A = &A;\n        _b = &b;\n        _x = x;\n        compute();\n    }\n    Vector solve(const Matrix & A, const Vector & b)\n    {\n        compute(A,b);\n        return solve();\n    }\n    void solve(const Matrix & A, const Vector & b, const Vector & x)\n    {\n        compute(A,b,x);\n        solve();\n    }\n\n    const Matrix& A() const { return *_A; }\n    const Vector& b() const { return *_b; }\n    const Vector& x() const { return _x; }\n    Vector& x() { return _x; }\n    private:\n    const Matrix* _A = nullptr;\n    const Vector* _b = nullptr;\n    Vector _x;\n    Scalar epsilon = 1e-8;\n    int max_iterations = 1e3;\n};\n}\n\n#endif\n", "meta": {"hexsha": "51febbad769701776c0fe6fdedf670591126feff", "size": 2790, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mtao/solvers/linear/linear.hpp", "max_stars_repo_name": "mtao/core", "max_stars_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_stars_repo_licenses": ["MIT"], "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/mtao/solvers/linear/linear.hpp", "max_issues_repo_name": "mtao/core", "max_issues_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-04-18T16:16:05.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-18T16:17:36.000Z", "max_forks_repo_path": "include/mtao/solvers/linear/linear.hpp", "max_forks_repo_name": "mtao/core", "max_forks_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_forks_repo_licenses": ["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.0747663551, "max_line_length": 118, "alphanum_fraction": 0.5989247312, "num_tokens": 690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4524913262658595}}
{"text": "#ifndef __BASE_EIGEN_HH__\n#define __BASE_EIGEN_HH__\n\n#include <Eigen/Core>\n#include <Eigen/Geometry> \n\n\nnamespace base\n{\n    \n    // We define these typedefs to workaround alignment requirements for normal\n    // Eigen types. This reduces the amount of knowledge people have to have to\n    // manipulate these types -- as well as the structures that use them -- and\n    // make them usable in Orocos dataflow.\n    //\n    // Eigen supports converting them to \"standard\" eigen types in a\n    // straightforward way. Moreover, vectorization does not help for small\n    // sizes\n    typedef Eigen::Matrix<double, 2, 1, Eigen::DontAlign>     Vector2d;\n    typedef Eigen::Matrix<double, 3, 1, Eigen::DontAlign>     Vector3d;\n    typedef Eigen::Matrix<double, 4, 1, Eigen::DontAlign>     Vector4d;\n    typedef Eigen::Matrix<double, 6, 1, Eigen::DontAlign>     Vector6d;\n    typedef Eigen::Matrix<double, Eigen::Dynamic, 1, Eigen::DontAlign> \n                                                              VectorXd;\n\n    typedef Eigen::Matrix<double, 2, 2, Eigen::DontAlign>     Matrix2d;\n    typedef Eigen::Matrix<double, 3, 3, Eigen::DontAlign>     Matrix3d;\n    typedef Eigen::Matrix<double, 4, 4, Eigen::DontAlign>     Matrix4d;\n    typedef Eigen::Matrix<double, 6, 6, Eigen::DontAlign>     Matrix6d;\n    typedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::DontAlign> \n                                                              MatrixXd;\n\n    typedef Eigen::Quaternion<double, Eigen::DontAlign>   Quaterniond;\n    typedef Eigen::AngleAxis<double>    AngleAxisd;\n    typedef Eigen::Transform<double, 3, Eigen::Affine, Eigen::DontAlign> Affine3d;\n    typedef Eigen::Transform<double, 3, Eigen::Isometry, Eigen::DontAlign> Isometry3d;\n\n    // alias for backward compatibility\n    typedef Affine3d\t\t\t\t\t   Transform3d;\n\n    /**\n     * @brief Check if NaN values\n     */\n    template<typename _Derived>\n    static inline bool isnotnan(const Eigen::MatrixBase<_Derived>& x)\n    {\n        return ((x.array() == x.array())).all();\n    };\n\n    template<typename _Derived>\n    static inline bool isfinite(const Eigen::MatrixBase<_Derived>& x)\n    {\n        return isnotnan(x - x);\n    };\n\n}\n\n#endif\n\n", "meta": {"hexsha": "246676cd525152aaaa278300df3c7ddbe9b78830", "size": 2204, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "gr740_stream_aligner/Eigen.hpp", "max_stars_repo_name": "ESROCOS/gr740-stream_aligner", "max_stars_repo_head_hexsha": "fbcd23ab655b5cf2c1fcb8a0a5b6d2be66a5ebef", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gr740_stream_aligner/Eigen.hpp", "max_issues_repo_name": "ESROCOS/gr740-stream_aligner", "max_issues_repo_head_hexsha": "fbcd23ab655b5cf2c1fcb8a0a5b6d2be66a5ebef", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gr740_stream_aligner/Eigen.hpp", "max_forks_repo_name": "ESROCOS/gr740-stream_aligner", "max_forks_repo_head_hexsha": "fbcd23ab655b5cf2c1fcb8a0a5b6d2be66a5ebef", "max_forks_repo_licenses": ["BSD-3-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.7333333333, "max_line_length": 86, "alphanum_fraction": 0.6424682396, "num_tokens": 563, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4524913262658594}}
{"text": "#include <algorithm>\n#include <fstream>\n#include <functional>\n#include <iostream>\n#include <numeric>\n#include <random>\n#include <stdexcept>\n#include <string>\n#include <utility>\n#include <vector>\n\n#include <boost/algorithm/string.hpp>\n#include <boost/format.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/program_options.hpp>\n\n#include <vi_ea_nsga2.hpp>\n#include <vi_algo.hpp>\n\nnamespace vi\n{\n    namespace ea\n    {\n        struct mtsp\n        {\n            template <typename random_generator_type>\n            static\n            std::pair<std::vector<int>, std::vector<int>>\n            crossover_sequence_ox(random_generator_type&  random_generator,\n                                  const std::vector<int>& parent_sequence_a,\n                                  const std::vector<int>& parent_sequence_b)\n            {\n                const auto sequence_length = static_cast<int>(parent_sequence_a.size());\n\n                auto children = std::make_pair(\n                    std::vector<int>(sequence_length, -1),\n                    std::vector<int>(sequence_length, -1));\n\n                auto& child_sequence_a = children.first;\n                auto& child_sequence_b = children.second;\n\n                auto distribution = std::uniform_int_distribution<int>(0, sequence_length - 1U);\n                const auto first  = distribution(random_generator);\n                const auto second = distribution(random_generator);\n                const auto left   = std::min(first, second);\n                const auto right  = std::max(first, second);\n\n                for (auto m = left; m <= right; ++m)\n                {\n                    child_sequence_a[m] = parent_sequence_a[m];\n                    child_sequence_b[m] = parent_sequence_b[m];\n                }\n\n                auto m   = (right + 1) % sequence_length;\n                auto n_a = m;\n                auto n_b = m;\n\n                while (m != left)\n                {\n                    while (std::find(child_sequence_b.begin(), child_sequence_b.end(), parent_sequence_a[n_a]) != child_sequence_b.end())\n                    {\n                        n_a = (n_a + 1) % sequence_length;\n                    }\n\n                    while (std::find(child_sequence_a.begin(), child_sequence_a.end(), parent_sequence_b[n_b]) != child_sequence_a.end())\n                    {\n                        n_b = (n_b + 1) % sequence_length;\n                    }\n\n                    child_sequence_b[m] = parent_sequence_a[n_a];\n                    child_sequence_a[m] = parent_sequence_b[n_b];\n\n                    m = (m + 1) % sequence_length;\n                }\n\n                return children;\n            }\n\n            template <typename random_generator_type>\n            static\n            void\n            mutate_sequence(random_generator_type& random_generator,\n                            std::vector<int>&      sequence)\n            {\n                const auto sequence_length = static_cast<int>(sequence.size());\n                auto distribution = std::uniform_int_distribution<int>(0, sequence_length - 1U);\n                const auto a = distribution(random_generator);\n                const auto b = distribution(random_generator);\n                std::swap(sequence[a], sequence[b]);\n            }\n\n            static\n            boost::numeric::ublas::matrix<double>\n            read_file(const std::string& filename)\n            {\n                std::ifstream input{filename};\n\n                std::string              line{};\n                std::vector<std::string> parts{};\n\n                if (!std::getline(input, line))\n                {\n                    throw std::runtime_error(\"read_file: missing header\");\n                }\n\n                boost::split(parts, line, boost::is_any_of(\",\"), boost::token_compress_on);\n\n                const auto num_cities = static_cast<int>(parts.size()) - 1;\n\n                boost::numeric::ublas::matrix<double> values(num_cities, num_cities);\n\n                for (auto i = 0; i != num_cities; ++i)\n                {\n                    if (!std::getline(input, line))\n                    {\n                        throw std::runtime_error(\"read_file: missing input\");\n                    }\n\n                    parts.clear();\n                    boost::split(parts, line, boost::is_any_of(\"\\r\\n ,\"), boost::token_compress_on);\n\n                    for (auto j = 0; j <= i; ++j)\n                    {\n                        const auto value = boost::lexical_cast<double>(parts[j + 1]);\n                        values(i, j) = value;\n                        values(j, i) = value;\n                    }\n                }\n\n                return values;\n            }\n\n            boost::numeric::ublas::matrix<double> costs{};\n            boost::numeric::ublas::matrix<double> distances{};\n            unsigned                              num_cities{};\n\n            mtsp(const std::string& cost_filename,\n                 const std::string& distance_filename)\n                : costs{read_file(cost_filename)},\n                  distances{read_file(distance_filename)},\n                  num_cities{static_cast<unsigned>(costs.size1())}\n            {\n            }\n\n            std::vector<double>\n            evaluate_sequence(const std::vector<int>& sequence)\n            {\n                auto distance = 0.0;\n                auto cost     = 0.0;\n\n                auto from_city_id = sequence[0];\n\n                for (std::size_t i = 1; i != sequence.size(); ++i)\n                {\n                    const auto to_city_id = sequence[i];\n\n                    distance += distances(from_city_id, to_city_id);\n                    cost     += costs(from_city_id, to_city_id);\n\n                    from_city_id = to_city_id;\n                }\n\n                distance += distances(from_city_id, sequence[0]);\n                cost     += costs(from_city_id, sequence[0]);\n\n                return std::vector<double>{distance, cost};\n            }\n\n            template <typename random_generator_type>\n            std::vector<int>\n            generate_sequence(random_generator_type& random_generator)\n            {\n                std::vector<int> sequence(num_cities);\n                std::iota(sequence.begin(), sequence.end(), 0);\n                std::shuffle(sequence.begin(), sequence.end(), random_generator);\n                return sequence;\n            }\n        };\n    }\n}\n\nint\nmain(int argc, char** argv)\n{\n    namespace po = boost::program_options;\n\n    try\n    {\n        po::options_description description{\"Options\"};\n        description.add_options()\n            (\"crossover_rate\",        po::value<double>()->default_value(1.0),    \"Crossover rate\")\n            (\"generations\",           po::value<unsigned>()->default_value(200),  \"Generation count\")\n            (\"mutation_rate\",         po::value<double>()->default_value(0.05),   \"Mutation rate\")\n            (\"population_size\",       po::value<unsigned>()->default_value(1000), \"Population size\")\n            (\"tournament_group_size\", po::value<unsigned>()->default_value(20),  \"Tournament group size\")\n            (\"tournament_randomness\", po::value<double>()->default_value(0.1),    \"Tournament probability of selecting random winner\");\n\n        po::variables_map variables{};\n        po::store(po::parse_command_line(argc, argv, description), variables);\n\n        vi::ea::nsga2::options solver_options{\n            variables[\"crossover_rate\"].as<double>(),\n            variables[\"mutation_rate\"].as<double>(),\n            2U,\n            variables[\"population_size\"].as<unsigned>(),\n            variables[\"tournament_group_size\"].as<unsigned>(),\n            variables[\"tournament_randomness\"].as<double>()\n        };\n\n        auto rng{std::default_random_engine{std::random_device{}()}};\n        vi::ea::mtsp problem{\"../../project_5/data/cost.csv\", \"../../project_5/data/distance.csv\"};\n\n        using genotype_type = std::vector<int>;\n        using namespace std::placeholders;\n\n        auto solver = vi::ea::nsga2::build_system<genotype_type>(\n            rng,\n            solver_options,\n            std::bind(&vi::ea::mtsp::generate_sequence<decltype(rng)>, &problem, _1),\n            std::bind(&vi::ea::mtsp::evaluate_sequence, &problem, _1),\n            std::bind(&vi::ea::mtsp::crossover_sequence_ox<decltype(rng)>, _1, _2, _3),\n            std::bind(&vi::ea::mtsp::mutate_sequence<decltype(rng)>, _1, _2));\n\n        const auto generations = variables[\"generations\"].as<unsigned>();\n\n        for (auto generation = 1U; generation <= generations; ++generation)\n        {\n            solver.evolve(rng);\n\n            std::cout << boost::format(\n                \"Generation %u: Best distance %.2f (cost %.2f), Best cost %.2f (distance %.2f)\")\n                % generation\n                % solver.extreme_min[0]->objective_values[0]\n                % solver.extreme_min[0]->objective_values[1]\n                % solver.extreme_min[1]->objective_values[1]\n                % solver.extreme_min[1]->objective_values[0]\n                << std::endl;\n        }\n    }\n    catch (const po::error& error)\n    {\n        std::cerr << \"error: \" << error.what() << std::endl;\n        return EXIT_FAILURE;\n    }\n\n    return EXIT_SUCCESS;\n}\n\n", "meta": {"hexsha": "257e501b22a7b2216b648fcc6eae752d2baff204", "size": 9329, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "project_3_2017/program/mtsp.cpp", "max_stars_repo_name": "pveierland/permve-ntnu-it3708", "max_stars_repo_head_hexsha": "1066d5c1af5c953dbaf129d7e05ce32f2d4292aa", "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": "project_3_2017/program/mtsp.cpp", "max_issues_repo_name": "pveierland/permve-ntnu-it3708", "max_issues_repo_head_hexsha": "1066d5c1af5c953dbaf129d7e05ce32f2d4292aa", "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": "project_3_2017/program/mtsp.cpp", "max_forks_repo_name": "pveierland/permve-ntnu-it3708", "max_forks_repo_head_hexsha": "1066d5c1af5c953dbaf129d7e05ce32f2d4292aa", "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": 37.1673306773, "max_line_length": 137, "alphanum_fraction": 0.5218136992, "num_tokens": 1886, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4524913262658594}}
{"text": "//==============================================================================\n//         Copyright 2015 - J.T. Lapreste\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2015 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_ROUND_HPP_INCLUDED\n#define BOOST_SIMD_ARITHMETIC_FUNCTIONS_SCALAR_ROUND_HPP_INCLUDED\n\n#include <boost/simd/arithmetic/functions/round.hpp>\n#include <boost/simd/include/functions/scalar/abs.hpp>\n#include <boost/simd/include/functions/scalar/copysign.hpp>\n#include <boost/simd/include/functions/scalar/is_ltz.hpp>\n#include <boost/simd/include/functions/scalar/seldec.hpp>\n#include <boost/simd/include/functions/scalar/ceil.hpp>\n#include <boost/simd/include/functions/scalar/tenpower.hpp>\n#include <boost/simd/include/constants/maxflint.hpp>\n#include <boost/simd/include/constants/half.hpp>\n#include <boost/simd/sdk/math.hpp>\n#include <boost/dispatch/attributes.hpp>\n#include <cmath>\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT          ( round_, tag::cpu_\n                                    , (A0)\n                                    , (scalar_< integer_<A0> >)\n                                    )\n  {\n    typedef A0 result_type;\n    BOOST_FORCEINLINE BOOST_SIMD_FUNCTOR_CALL(1)\n    {\n      return a0;\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT          ( round_, tag::cpu_\n                                    , (A0)\n                                    , (scalar_< single_<A0> >)\n                                    )\n  {\n    typedef A0 result_type;\n    BOOST_FORCEINLINE BOOST_SIMD_FUNCTOR_CALL(1)\n    {\n#ifdef BOOST_SIMD_HAS_ROUNDF\n      return ::roundf(a0);\n#else\n      const result_type v = simd::abs(a0);\n      if (!(v <=  Maxflint<result_type>()))\n        return a0;\n      result_type c =  boost::simd::ceil(v);\n      return copysign(seldec(c-Half<result_type>() > v, c), a0);\n#endif\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT          ( round_, tag::cpu_\n                                    , (A0)\n                                    , (scalar_< double_<A0> >)\n                                    )\n  {\n    typedef A0 result_type;\n\n    BOOST_FORCEINLINE BOOST_SIMD_FUNCTOR_CALL(1)\n    {\n#ifdef BOOST_SIMD_HAS_ROUND\n      return ::round(a0);\n#else\n      const result_type v = simd::abs(a0);\n      if (!(v <=  Maxflint<result_type>()))\n        return a0;\n      result_type c =  boost::simd::ceil(v);\n      return copysign(seldec(c-Half<result_type>() > v, c), a0);\n#endif\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT          ( round_, tag::cpu_\n                                    , (A0)(A1)\n                                    , (scalar_< floating_<A0> >)\n                                      (scalar_< integer_<A1> >)\n                                    )\n  {\n    typedef A0 result_type;\n\n    BOOST_FORCEINLINE BOOST_SIMD_FUNCTOR_CALL(2)\n    {\n      typedef typename  dispatch::meta::as_integer<A0>::type itype;\n      A0 fac = tenpower(itype(a1));\n      A0 tmp = round(a0*fac)/fac;\n      return is_ltz(a1) ? round(tmp) : tmp;\n    }\n  };\n\n} } }\n\n#endif\n", "meta": {"hexsha": "de802e2c801d5b906c81a4e6c748bad8ab96661c", "size": 3376, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/scalar/round.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/round.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/round.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": 33.4257425743, "max_line_length": 80, "alphanum_fraction": 0.5396919431, "num_tokens": 784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4524913262658594}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   tstExponentialDistribution.cpp\n//! \\author Alex Robinson\n//! \\brief  Histogram distribution unit tests.\n//!\n//---------------------------------------------------------------------------//\n\n// Std Lib Includes\n#include <iostream>\n#include <cmath>\n\n// Boost Includes\n#include <boost/units/systems/si.hpp>\n#include <boost/units/systems/cgs.hpp>\n#include <boost/units/io.hpp>\n\n// FRENSIE Includes\n#include \"Utility_ExponentialDistribution.hpp\"\n#include \"Utility_RandomNumberGenerator.hpp\"\n#include \"Utility_PhysicalConstants.hpp\"\n#include \"Utility_UnitTraits.hpp\"\n#include \"Utility_QuantityTraits.hpp\"\n#include \"Utility_ElectronVoltUnit.hpp\"\n#include \"Utility_UnitTestHarnessWithMain.hpp\"\n#include \"ArchiveTestHelpers.hpp\"\n\n//---------------------------------------------------------------------------//\n// Testing Types\n//---------------------------------------------------------------------------//\n\nusing boost::units::quantity;\nusing namespace Utility::Units;\nnamespace si = boost::units::si;\nnamespace cgs = boost::units::cgs;\n\ntypedef TestArchiveHelper::TestArchives TestArchives;\n\ntypedef std::tuple<\n  std::tuple<si::energy,si::amount,cgs::energy,si::amount>,\n  std::tuple<cgs::energy,si::amount,si::energy,si::amount>,\n  std::tuple<si::energy,si::length,cgs::energy,cgs::length>,\n  std::tuple<cgs::energy,cgs::length,si::energy,si::length>,\n  std::tuple<si::energy,si::mass,cgs::energy,cgs::mass>,\n  std::tuple<cgs::energy,cgs::mass,si::energy,si::mass>,\n  std::tuple<si::energy,si::dimensionless,cgs::energy,cgs::dimensionless>,\n  std::tuple<cgs::energy,cgs::dimensionless,si::energy,si::dimensionless>,\n  std::tuple<si::energy,void*,cgs::energy,void*>,\n  std::tuple<cgs::energy,void*,si::energy,void*>,\n  std::tuple<ElectronVolt,si::amount,si::energy,si::amount>,\n  std::tuple<ElectronVolt,si::amount,cgs::energy,si::amount>,\n  std::tuple<ElectronVolt,si::amount,KiloElectronVolt,si::amount>,\n  std::tuple<ElectronVolt,si::amount,MegaElectronVolt,si::amount>,\n  std::tuple<KiloElectronVolt,si::amount,si::energy,si::amount>,\n  std::tuple<KiloElectronVolt,si::amount,cgs::energy,si::amount>,\n  std::tuple<KiloElectronVolt,si::amount,ElectronVolt,si::amount>,\n  std::tuple<KiloElectronVolt,si::amount,MegaElectronVolt,si::amount>,\n  std::tuple<MegaElectronVolt,si::amount,si::energy,si::amount>,\n  std::tuple<MegaElectronVolt,si::amount,cgs::energy,si::amount>,\n  std::tuple<MegaElectronVolt,si::amount,ElectronVolt,si::amount>,\n  std::tuple<MegaElectronVolt,si::amount,KiloElectronVolt,si::amount>,\n  std::tuple<void*,MegaElectronVolt,void*,KiloElectronVolt>\n > TestUnitTypeQuads;\n\n//---------------------------------------------------------------------------//\n// Testing Variables\n//---------------------------------------------------------------------------//\n\nstd::shared_ptr<Utility::UnivariateDistribution> distribution(\n\t\t\t     new Utility::ExponentialDistribution( 2.0, 3.0 ) );\nstd::shared_ptr<Utility::UnitAwareUnivariateDistribution<cgs::length,si::amount> > unit_aware_distribution( new Utility::UnitAwareExponentialDistribution<cgs::length,si::amount>( 2.0*si::mole, 300.0/si::meter, 0.0*si::meter ) );\n\n//---------------------------------------------------------------------------//\n// Tests.\n//---------------------------------------------------------------------------//\n// Check that the distribution can be evaluated\nFRENSIE_UNIT_TEST( ExponentialDistribution, evaluate )\n{\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( -1.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluate( 0.0 ), 2.0 );\n  FRENSIE_CHECK_FLOATING_EQUALITY(distribution->evaluate( 1.0 ), 2.0*exp(-3.0), 1e-12);\n}\n\n//---------------------------------------------------------------------------//\n// Check that the unit-aware distribution can be evaluated\nFRENSIE_UNIT_TEST( UnitAwareExponentialDistribution, evaluate )\n{\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate(-1.0*cgs::centimeter),\n\t\t       0.0*si::mole );\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( 0.0*cgs::centimeter),\n\t\t       2.0*si::mole );\n  FRENSIE_CHECK_FLOATING_EQUALITY(\n\t\t       unit_aware_distribution->evaluate( 1.0*cgs::centimeter),\n\t\t       2.0*exp(-3.0)*si::mole,\n\t\t       1e-12 );\n}\n\n//---------------------------------------------------------------------------//\n// Check that the PDF can be evaluated\nFRENSIE_UNIT_TEST( ExponentialDistribution, evaluatePDF )\n{\n  FRENSIE_CHECK_EQUAL( distribution->evaluatePDF( -1.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( distribution->evaluatePDF( 0.0 ), 3.0 );\n  FRENSIE_CHECK_FLOATING_EQUALITY(distribution->evaluatePDF(1.0), 3.0*exp(-3.0), 1e-12);\n}\n\n//---------------------------------------------------------------------------//\n// Check that the unit-aware PDF can be evaluated\nFRENSIE_UNIT_TEST( UnitAwareExponentialDistribution, evaluatePDF )\n{\n  FRENSIE_CHECK_EQUAL(\n\t\t  unit_aware_distribution->evaluatePDF( -1.0*cgs::centimeter ),\n\t\t  0.0/cgs::centimeter );\n  FRENSIE_CHECK_EQUAL(\n\t\t   unit_aware_distribution->evaluatePDF( 0.0*cgs::centimeter ),\n\t\t   3.0/cgs::centimeter );\n  FRENSIE_CHECK_FLOATING_EQUALITY(\n\t\t   unit_aware_distribution->evaluatePDF( 1.0*cgs::centimeter ),\n\t\t   3.0*exp(-3.0)/cgs::centimeter,\n\t\t   1e-12 );\n}\n\n//---------------------------------------------------------------------------//\n// Check that the distribution can be sampled\nFRENSIE_UNIT_TEST( ExponentialDistribution, sample_basic_static )\n{\n  std::vector<double> fake_stream( 3 );\n  fake_stream[0] = 0.0;\n  fake_stream[1] = 1.0 - 1e-15;\n  fake_stream[2] = 0.5;\n\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  double sample = Utility::ExponentialDistribution::sample( 3.0 );\n  FRENSIE_CHECK_EQUAL( sample, 0.0 );\n\n  sample = Utility::ExponentialDistribution::sample( 3.0 );\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 11.5131919974469596, 1e-15 );\n\n  sample = Utility::ExponentialDistribution::sample( 3.0 );\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, -std::log(0.5)/3.0, 1e-12 );\n\n  Utility::RandomNumberGenerator::unsetFakeStream();\n}\n\n//---------------------------------------------------------------------------//\n// Check that the unit-aware distribution can be sampled\nFRENSIE_UNIT_TEST( UnitAwareExponentialDistribution, sample_basic_static )\n{\n  std::vector<double> fake_stream( 3 );\n  fake_stream[0] = 0.0;\n  fake_stream[1] = 1.0 - 1e-15;\n  fake_stream[2] = 0.5;\n\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  quantity<cgs::length> sample =\n    Utility::UnitAwareExponentialDistribution<cgs::length>::sample( 3.0/cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter );\n\n  sample = Utility::UnitAwareExponentialDistribution<cgs::length>::sample( 3.0/cgs::centimeter );\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample,\n\t\t\t\t  11.5131919974469596*cgs::centimeter,\n\t\t\t\t  1e-15 );\n\n  sample = Utility::UnitAwareExponentialDistribution<cgs::length>::sample( 3.0/cgs::centimeter );\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample,\n\t\t\t\t  -std::log(0.5)/3.0*cgs::centimeter,\n\t\t\t\t  1e-12 );\n\n  Utility::RandomNumberGenerator::unsetFakeStream();\n}\n\n//---------------------------------------------------------------------------//\n// Check that the distribution can be sampled\nFRENSIE_UNIT_TEST( ExponentialDistribution, sample_static )\n{\n  std::vector<double> fake_stream( 5 );\n  fake_stream[0] = 0.0;\n  fake_stream[1] = 1.0 - 1e-15;\n  fake_stream[2] = 0.5;\n  fake_stream[3] = 0.5;\n  fake_stream[4] = 0.5;\n\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  double inf = std::numeric_limits<double>::infinity();\n\n  double sample = Utility::ExponentialDistribution::sample( 3.0, 0.0, inf );\n  FRENSIE_CHECK_EQUAL( sample, 0.0 );\n\n  sample = Utility::ExponentialDistribution::sample( 3.0, 0.0, inf );\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 11.5131919974469596, 1e-15 );\n\n  sample = Utility::ExponentialDistribution::sample( 3.0, 0.0, inf );\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, -std::log(0.5)/3.0, 1e-12 );\n\n  sample = Utility::ExponentialDistribution::sample( 3.0, 1.0, inf );\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 1.2310490601866484, 1e-12 );\n\n  sample = Utility::ExponentialDistribution::sample( 3.0, 1.0, 2.0 );\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 1.2148532763287345, 1e-12 );\n\n  Utility::RandomNumberGenerator::unsetFakeStream();\n}\n\n//---------------------------------------------------------------------------//\n// Check that the unit-aware distribution can be sampled\nFRENSIE_UNIT_TEST( UnitAwareExponentialDistribution, sample_static )\n{\n  std::vector<double> fake_stream( 3 );\n  fake_stream[0] = 0.0;\n  fake_stream[1] = 1.0 - 1e-15;\n  fake_stream[2] = 0.5;\n\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  quantity<cgs::length> inf =\n    Utility::QuantityTraits<quantity<cgs::length> >::inf();\n\n  quantity<cgs::length> sample =\n    Utility::UnitAwareExponentialDistribution<cgs::length>::sample(\n\t\t\t       3.0/cgs::centimeter, 0.0*cgs::centimeter, inf );\n  FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter );\n\n  sample = Utility::UnitAwareExponentialDistribution<cgs::length>::sample(\n\t\t\t       3.0/cgs::centimeter, 0.0*cgs::centimeter, inf );\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample,\n\t\t\t\t  11.5131919974469596*cgs::centimeter,\n\t\t\t\t  1e-15 );\n\n  sample = Utility::UnitAwareExponentialDistribution<cgs::length>::sample(\n\t\t\t       3.0/cgs::centimeter, 0.0*cgs::centimeter, inf );\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample,\n\t\t\t\t  -std::log(0.5)/3.0*cgs::centimeter,\n\t\t\t\t  1e-12 );\n\n  Utility::RandomNumberGenerator::unsetFakeStream();\n}\n\n//---------------------------------------------------------------------------//\n// Check that the distribution can be sampled\nFRENSIE_UNIT_TEST( ExponentialDistribution, sample )\n{\n  std::vector<double> fake_stream( 3 );\n  fake_stream[0] = 0.0;\n  fake_stream[1] = 1.0 - 1e-15;\n  fake_stream[2] = 0.5;\n\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  double sample = distribution->sample();\n  FRENSIE_CHECK_EQUAL( sample, 0.0 );\n\n  sample = distribution->sample();\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 11.5131919974469596, 1e-15 );\n\n  sample = distribution->sample();\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, -std::log(0.5)/3.0, 1e-12 );\n\n  Utility::RandomNumberGenerator::unsetFakeStream();\n}\n\n//---------------------------------------------------------------------------//\n// Check that the unit-aware distribution can be sampled\nFRENSIE_UNIT_TEST( UnitAwareExponentialDistribution, sample )\n{\n  std::vector<double> fake_stream( 3 );\n  fake_stream[0] = 0.0;\n  fake_stream[1] = 1.0 - 1e-15;\n  fake_stream[2] = 0.5;\n\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  quantity<cgs::length> sample = unit_aware_distribution->sample();\n  FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter );\n\n  sample = unit_aware_distribution->sample();\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample,\n\t\t\t\t  11.5131919974469596*cgs::centimeter,\n\t\t\t\t  1e-15 );\n\n  sample = unit_aware_distribution->sample();\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample,\n\t\t\t\t  -std::log(0.5)/3.0*cgs::centimeter,\n\t\t\t\t  1e-12 );\n\n  Utility::RandomNumberGenerator::unsetFakeStream();\n}\n\n//---------------------------------------------------------------------------//\n// Check that the distribution can be sampled\nFRENSIE_UNIT_TEST( ExponentialDistribution, sampleAndRecordTrials )\n{\n  std::vector<double> fake_stream( 3 );\n  fake_stream[0] = 0.0;\n  fake_stream[1] = 1.0 - 1e-15;\n  fake_stream[2] = 0.5;\n\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  Utility::DistributionTraits::Counter trials = 0;\n\n  double sample = distribution->sampleAndRecordTrials( trials );\n  FRENSIE_CHECK_EQUAL( sample, 0.0 );\n  FRENSIE_CHECK_EQUAL( trials, 1 );\n\n  sample = distribution->sampleAndRecordTrials( trials );\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, 11.5131919974469596, 1e-15 );\n  FRENSIE_CHECK_EQUAL( trials, 2 );\n\n  sample = distribution->sampleAndRecordTrials( trials );\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample, -std::log(0.5)/3.0, 1e-12 );\n  FRENSIE_CHECK_EQUAL( trials, 3 );\n\n  Utility::RandomNumberGenerator::unsetFakeStream();\n}\n\n//---------------------------------------------------------------------------//\n// Check that the unit-aware distribution can be sampled\nFRENSIE_UNIT_TEST( UnitAwareExponentialDistribution, sampleAndRecordTrials )\n{\n  std::vector<double> fake_stream( 3 );\n  fake_stream[0] = 0.0;\n  fake_stream[1] = 1.0 - 1e-15;\n  fake_stream[2] = 0.5;\n\n  Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n  Utility::DistributionTraits::Counter trials = 0;\n\n  quantity<cgs::length> sample =\n    unit_aware_distribution->sampleAndRecordTrials( trials );\n  FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( trials, 1 );\n\n  sample = unit_aware_distribution->sampleAndRecordTrials( trials );\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample,\n\t\t\t\t  11.5131919974469596*cgs::centimeter,\n\t\t\t\t  1e-15 );\n  FRENSIE_CHECK_EQUAL( trials, 2 );\n\n  sample = unit_aware_distribution->sampleAndRecordTrials( trials );\n  FRENSIE_CHECK_FLOATING_EQUALITY( sample,\n\t\t\t\t  -std::log(0.5)/3.0*cgs::centimeter,\n\t\t\t\t  1e-12 );\n  FRENSIE_CHECK_EQUAL( trials, 3 );\n\n  Utility::RandomNumberGenerator::unsetFakeStream();\n}\n\n//---------------------------------------------------------------------------//\n// Check that the upper bound of the distribution independent variable can be\n// returned\nFRENSIE_UNIT_TEST( ExponentialDistribution, getUpperBoundOfIndepVar )\n{\n  FRENSIE_CHECK_EQUAL( distribution->getUpperBoundOfIndepVar(),\n\t\t       std::numeric_limits<double>::infinity() );\n}\n\n//---------------------------------------------------------------------------//\n// Check that the upper bound of the unit-aware distribution independent\n// variable can be returned\nFRENSIE_UNIT_TEST( UnitAwareExponentialDistribution, getUpperBoundOfIndepVar )\n{\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->getUpperBoundOfIndepVar(),\n\t\t       Utility::QuantityTraits<quantity<cgs::length> >::inf());\n}\n\n//---------------------------------------------------------------------------//\n// Check that the lower bound of the distribution independent variable can be\n// returned\nFRENSIE_UNIT_TEST( ExponentialDistribution, getLowerBoundOfIndepVar )\n{\n  FRENSIE_CHECK_EQUAL( distribution->getLowerBoundOfIndepVar(), 0.0 );\n}\n\n//---------------------------------------------------------------------------//\n// Check that the lower bound of the unit-aware distribution independent\n// variable can be returned\nFRENSIE_UNIT_TEST( UnitAwareExponentialDistribution, getLowerBoundOfIndepVar )\n{\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->getLowerBoundOfIndepVar(),\n\t\t       Utility::QuantityTraits<quantity<cgs::length> >::zero());\n}\n\n//---------------------------------------------------------------------------//\n// Check that the distribution type can be returned\nFRENSIE_UNIT_TEST( ExponentialDistribution, getDistributionType )\n{\n  FRENSIE_CHECK_EQUAL( distribution->getDistributionType(),\n\t\t       Utility::EXPONENTIAL_DISTRIBUTION );\n}\n\n//---------------------------------------------------------------------------//\n// Check that the unit-aware distribution type can be returned\nFRENSIE_UNIT_TEST( UnitAwareExponentialDistribution, getDistributionType )\n{\n  FRENSIE_CHECK_EQUAL( unit_aware_distribution->getDistributionType(),\n\t\t       Utility::EXPONENTIAL_DISTRIBUTION );\n}\n\n//---------------------------------------------------------------------------//\n// Check if the distribution is tabular\nFRENSIE_UNIT_TEST( ExponentialDistribution, isTabular )\n{\n  FRENSIE_CHECK( !distribution->isTabular() );\n}\n\n//---------------------------------------------------------------------------//\n// Check if the unit-aware distribution is tabular\nFRENSIE_UNIT_TEST( UnitAwareExponentialDistribution, isTabular )\n{\n  FRENSIE_CHECK( !unit_aware_distribution->isTabular() );\n}\n\n//---------------------------------------------------------------------------//\n// Check if the distribution is continuous\nFRENSIE_UNIT_TEST( ExponentialDistribution, isContinuous )\n{\n  FRENSIE_CHECK( distribution->isContinuous() );\n}\n\n//---------------------------------------------------------------------------//\n// Check if the unit-aware distribution is continuous\nFRENSIE_UNIT_TEST( UnitAwareExponentialDistribution, isContinuous )\n{\n  FRENSIE_CHECK( unit_aware_distribution->isContinuous() );\n}\n\n//---------------------------------------------------------------------------//\n// Check if the distribution is compatible with the interpolation type\nFRENSIE_UNIT_TEST( ExponentialDistribution, isCompatibleWithInterpType )\n{\n  FRENSIE_CHECK( distribution->isCompatibleWithInterpType<Utility::LinLin>() );\n  FRENSIE_CHECK( distribution->isCompatibleWithInterpType<Utility::LinLog>() );\n  FRENSIE_CHECK( distribution->isCompatibleWithInterpType<Utility::LogLin>() );\n  FRENSIE_CHECK( distribution->isCompatibleWithInterpType<Utility::LogLog>() );\n\n  // Create another distribution that is compatible with all interpolation\n  // types\n  Utility::ExponentialDistribution test_dist( 1.0, 1.0, 0.1, 1.0 );\n\n  FRENSIE_CHECK( test_dist.isCompatibleWithInterpType<Utility::LinLin>() );\n  FRENSIE_CHECK( test_dist.isCompatibleWithInterpType<Utility::LinLog>() );\n  FRENSIE_CHECK( test_dist.isCompatibleWithInterpType<Utility::LogLin>() );\n  FRENSIE_CHECK( test_dist.isCompatibleWithInterpType<Utility::LogLog>() );\n}\n\n//---------------------------------------------------------------------------//\n// Check if the unit-aware distribution is compatible with the interp type\nFRENSIE_UNIT_TEST( UnitAwareExponentialDistribution,\n                   isCompatibleWithInterpType )\n{\n  FRENSIE_CHECK( unit_aware_distribution->isCompatibleWithInterpType<Utility::LinLin>() );\n  FRENSIE_CHECK( unit_aware_distribution->isCompatibleWithInterpType<Utility::LinLog>() );\n  FRENSIE_CHECK( unit_aware_distribution->isCompatibleWithInterpType<Utility::LogLin>() );\n  FRENSIE_CHECK( unit_aware_distribution->isCompatibleWithInterpType<Utility::LogLog>() );\n\n  // Create another distribution that is compatible with all interpolation\n  // types\n  Utility::UnitAwareExponentialDistribution<cgs::length,si::amount>\n    test_dist( 1.0*si::mole, 1.0/si::meter, 0.1*si::meter, 1.0*si::meter );\n\n  FRENSIE_CHECK( test_dist.isCompatibleWithInterpType<Utility::LinLin>() );\n  FRENSIE_CHECK( test_dist.isCompatibleWithInterpType<Utility::LinLog>() );\n  FRENSIE_CHECK( test_dist.isCompatibleWithInterpType<Utility::LogLin>() );\n  FRENSIE_CHECK( test_dist.isCompatibleWithInterpType<Utility::LogLog>() );\n}\n\n//---------------------------------------------------------------------------//\n// Check that a distribution can be placed in a stream\nFRENSIE_UNIT_TEST( ExponentialDistribution, ostream_operator )\n{\n  std::ostringstream oss;\n\n  oss << Utility::ExponentialDistribution();\n\n  Utility::VariantMap dist_data =\n    Utility::fromString<Utility::VariantMap>( oss.str() );\n\n  FRENSIE_CHECK_EQUAL( dist_data[\"type\"].toString(),\n                       \"Exponential Distribution\" );\n  FRENSIE_CHECK_EQUAL( dist_data[\"independent unit\"].toString(), \"void\" );\n  FRENSIE_CHECK_EQUAL( dist_data[\"dependent unit\"].toString(), \"void\" );\n  FRENSIE_CHECK_EQUAL( dist_data[\"exponent multiplier\"].toDouble(), 1.0 );\n  FRENSIE_CHECK_EQUAL( dist_data[\"multiplier\"].toDouble(), 1.0 );\n  FRENSIE_CHECK_EQUAL( dist_data[\"lower bound\"].toDouble(), 0.0 );\n  FRENSIE_CHECK_EQUAL( dist_data[\"upper bound\"].toDouble(),\n                       Utility::QuantityTraits<double>::inf() );\n\n  oss.str( \"\" );\n  oss.clear();\n\n  oss << Utility::ExponentialDistribution( 2.0 );\n\n  dist_data = Utility::fromString<Utility::VariantMap>( oss.str() );\n\n  FRENSIE_CHECK_EQUAL( dist_data[\"type\"].toString(),\n                       \"Exponential Distribution\" );\n  FRENSIE_CHECK_EQUAL( dist_data[\"independent unit\"].toString(), \"void\" );\n  FRENSIE_CHECK_EQUAL( dist_data[\"dependent unit\"].toString(), \"void\" );\n  FRENSIE_CHECK_EQUAL( dist_data[\"exponent multiplier\"].toDouble(), 1.0 );\n  FRENSIE_CHECK_EQUAL( dist_data[\"multiplier\"].toDouble(), 2.0 );\n  FRENSIE_CHECK_EQUAL( dist_data[\"lower bound\"].toDouble(), 0.0 );\n  FRENSIE_CHECK_EQUAL( dist_data[\"upper bound\"].toDouble(),\n                       Utility::QuantityTraits<double>::inf() );\n\n  oss.str( \"\" );\n  oss.clear();\n\n  oss << Utility::ExponentialDistribution( 2.0, 3.0 );\n\n  dist_data = Utility::fromString<Utility::VariantMap>( oss.str() );\n\n  FRENSIE_CHECK_EQUAL( dist_data[\"type\"].toString(),\n                       \"Exponential Distribution\" );\n  FRENSIE_CHECK_EQUAL( dist_data[\"independent unit\"].toString(), \"void\" );\n  FRENSIE_CHECK_EQUAL( dist_data[\"dependent unit\"].toString(), \"void\" );\n  FRENSIE_CHECK_EQUAL( dist_data[\"exponent multiplier\"].toDouble(), 3.0 );\n  FRENSIE_CHECK_EQUAL( dist_data[\"multiplier\"].toDouble(), 2.0 );\n  FRENSIE_CHECK_EQUAL( dist_data[\"lower bound\"].toDouble(), 0.0 );\n  FRENSIE_CHECK_EQUAL( dist_data[\"upper bound\"].toDouble(),\n                       Utility::QuantityTraits<double>::inf() );\n\n  oss.str( \"\" );\n  oss.clear();\n\n  oss << Utility::ExponentialDistribution( 2.0, 3.0, 1.0 );\n\n  dist_data = Utility::fromString<Utility::VariantMap>( oss.str() );\n\n  FRENSIE_CHECK_EQUAL( dist_data[\"type\"].toString(),\n                       \"Exponential Distribution\" );\n  FRENSIE_CHECK_EQUAL( dist_data[\"independent unit\"].toString(), \"void\" );\n  FRENSIE_CHECK_EQUAL( dist_data[\"dependent unit\"].toString(), \"void\" );\n  FRENSIE_CHECK_EQUAL( dist_data[\"exponent multiplier\"].toDouble(), 3.0 );\n  FRENSIE_CHECK_EQUAL( dist_data[\"multiplier\"].toDouble(), 2.0 );\n  FRENSIE_CHECK_EQUAL( dist_data[\"lower bound\"].toDouble(), 1.0 );\n  FRENSIE_CHECK_EQUAL( dist_data[\"upper bound\"].toDouble(),\n                       Utility::QuantityTraits<double>::inf() );\n\n  oss.str( \"\" );\n  oss.clear();\n\n  oss << Utility::ExponentialDistribution( 2.0, 3.0, 1.0, 2.0 );\n\n  dist_data = Utility::fromString<Utility::VariantMap>( oss.str() );\n\n  FRENSIE_CHECK_EQUAL( dist_data[\"type\"].toString(),\n                       \"Exponential Distribution\" );\n  FRENSIE_CHECK_EQUAL( dist_data[\"independent unit\"].toString(), \"void\" );\n  FRENSIE_CHECK_EQUAL( dist_data[\"dependent unit\"].toString(), \"void\" );\n  FRENSIE_CHECK_EQUAL( dist_data[\"exponent multiplier\"].toDouble(), 3.0 );\n  FRENSIE_CHECK_EQUAL( dist_data[\"multiplier\"].toDouble(), 2.0 );\n  FRENSIE_CHECK_EQUAL( dist_data[\"lower bound\"].toDouble(), 1.0 );\n  FRENSIE_CHECK_EQUAL( dist_data[\"upper bound\"].toDouble(), 2.0 );\n\n  oss.str( \"\" );\n  oss.clear();\n\n  oss << *distribution;\n\n  dist_data = Utility::fromString<Utility::VariantMap>( oss.str() );\n\n  FRENSIE_CHECK_EQUAL( dist_data[\"type\"].toString(),\n                       \"Exponential Distribution\" );\n  FRENSIE_CHECK_EQUAL( dist_data[\"independent unit\"].toString(), \"void\" );\n  FRENSIE_CHECK_EQUAL( dist_data[\"dependent unit\"].toString(), \"void\" );\n  FRENSIE_CHECK_EQUAL( dist_data[\"exponent multiplier\"].toDouble(), 3.0 );\n  FRENSIE_CHECK_EQUAL( dist_data[\"multiplier\"].toDouble(), 2.0 );\n  FRENSIE_CHECK_EQUAL( dist_data[\"lower bound\"].toDouble(), 0.0 );\n  FRENSIE_CHECK_EQUAL( dist_data[\"upper bound\"].toDouble(),\n                       Utility::QuantityTraits<double>::inf() );\n}\n\n//---------------------------------------------------------------------------//\n// Check that the unit-aware distribution can be placed in a stream\nFRENSIE_UNIT_TEST( UnitAwareExponentialDistribution, ostream_operator )\n{\n  std::ostringstream oss;\n  \n  oss << Utility::UnitAwareExponentialDistribution<cgs::length,si::amount>();\n\n  Utility::VariantMap dist_data =\n    Utility::fromString<Utility::VariantMap>( oss.str() );\n\n  FRENSIE_CHECK_EQUAL( dist_data[\"type\"].toString(),\n                       \"Exponential Distribution\" );\n  FRENSIE_CHECK_EQUAL( dist_data[\"independent unit\"].toString(),\n                       Utility::UnitTraits<cgs::length>::name() );\n  FRENSIE_CHECK_EQUAL( dist_data[\"dependent unit\"].toString(),\n                       Utility::UnitTraits<si::amount>::name() );\n  FRENSIE_CHECK_EQUAL( dist_data[\"exponent multiplier\"].toType<quantity<Utility::UnitTraits<cgs::length>::InverseUnit> >(),\n                       1.0/cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( dist_data[\"multiplier\"].toType<quantity<si::amount> >(),\n                       1.0*si::mole );\n  FRENSIE_CHECK_EQUAL( dist_data[\"lower bound\"].toType<quantity<cgs::length> >(),\n                       0.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( dist_data[\"upper bound\"].toType<quantity<cgs::length> >(),\n                       Utility::QuantityTraits<quantity<cgs::length> >::inf() );\n  \n  oss.str( \"\" );\n  oss.clear();\n  \n  oss << Utility::UnitAwareExponentialDistribution<cgs::length,si::amount>( 2.0*si::mole );\n\n  dist_data = Utility::fromString<Utility::VariantMap>( oss.str() );\n\n  FRENSIE_CHECK_EQUAL( dist_data[\"type\"].toString(),\n                       \"Exponential Distribution\" );\n  FRENSIE_CHECK_EQUAL( dist_data[\"independent unit\"].toString(),\n                       Utility::UnitTraits<cgs::length>::name() );\n  FRENSIE_CHECK_EQUAL( dist_data[\"dependent unit\"].toString(),\n                       Utility::UnitTraits<si::amount>::name() );\n  FRENSIE_CHECK_EQUAL( dist_data[\"exponent multiplier\"].toType<quantity<Utility::UnitTraits<cgs::length>::InverseUnit> >(),\n                       1.0/cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( dist_data[\"multiplier\"].toType<quantity<si::amount> >(),\n                       2.0*si::mole );\n  FRENSIE_CHECK_EQUAL( dist_data[\"lower bound\"].toType<quantity<cgs::length> >(),\n                       0.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( dist_data[\"upper bound\"].toType<quantity<cgs::length> >(),\n                       Utility::QuantityTraits<quantity<cgs::length> >::inf() );\n\n  oss.str( \"\" );\n  oss.clear();\n\n  oss << Utility::UnitAwareExponentialDistribution<cgs::length,si::amount>( 2.0*si::mole, 3.0/cgs::centimeter );\n\n  dist_data = Utility::fromString<Utility::VariantMap>( oss.str() );\n\n  FRENSIE_CHECK_EQUAL( dist_data[\"type\"].toString(),\n                       \"Exponential Distribution\" );\n  FRENSIE_CHECK_EQUAL( dist_data[\"independent unit\"].toString(),\n                       Utility::UnitTraits<cgs::length>::name() );\n  FRENSIE_CHECK_EQUAL( dist_data[\"dependent unit\"].toString(),\n                       Utility::UnitTraits<si::amount>::name() );\n  FRENSIE_CHECK_EQUAL( dist_data[\"exponent multiplier\"].toType<quantity<Utility::UnitTraits<cgs::length>::InverseUnit> >(),\n                       3.0/cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( dist_data[\"multiplier\"].toType<quantity<si::amount> >(),\n                       2.0*si::mole );\n  FRENSIE_CHECK_EQUAL( dist_data[\"lower bound\"].toType<quantity<cgs::length> >(),\n                       0.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( dist_data[\"upper bound\"].toType<quantity<cgs::length> >(),\n                       Utility::QuantityTraits<quantity<cgs::length> >::inf() );\n  \n  oss.str( \"\" );\n  oss.clear();\n\n  oss << Utility::UnitAwareExponentialDistribution<cgs::length,si::amount>( 2.0*si::mole, 3.0/cgs::centimeter, 1.0*cgs::centimeter );\n\n  dist_data = Utility::fromString<Utility::VariantMap>( oss.str() );\n\n  FRENSIE_CHECK_EQUAL( dist_data[\"type\"].toString(),\n                       \"Exponential Distribution\" );\n  FRENSIE_CHECK_EQUAL( dist_data[\"independent unit\"].toString(),\n                       Utility::UnitTraits<cgs::length>::name() );\n  FRENSIE_CHECK_EQUAL( dist_data[\"dependent unit\"].toString(),\n                       Utility::UnitTraits<si::amount>::name() );\n  FRENSIE_CHECK_EQUAL( dist_data[\"exponent multiplier\"].toType<quantity<Utility::UnitTraits<cgs::length>::InverseUnit> >(),\n                       3.0/cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( dist_data[\"multiplier\"].toType<quantity<si::amount> >(),\n                       2.0*si::mole );\n  FRENSIE_CHECK_EQUAL( dist_data[\"lower bound\"].toType<quantity<cgs::length> >(),\n                       1.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( dist_data[\"upper bound\"].toType<quantity<cgs::length> >(),\n                       Utility::QuantityTraits<quantity<cgs::length> >::inf() );\n\n  oss.str( \"\" );\n  oss.clear();\n\n  oss << Utility::UnitAwareExponentialDistribution<cgs::length,si::amount>( 2.0*si::mole, 3.0/cgs::centimeter, 1.0*cgs::centimeter, 2.0*cgs::centimeter );\n\n  dist_data = Utility::fromString<Utility::VariantMap>( oss.str() );\n\n  FRENSIE_CHECK_EQUAL( dist_data[\"type\"].toString(),\n                       \"Exponential Distribution\" );\n  FRENSIE_CHECK_EQUAL( dist_data[\"independent unit\"].toString(),\n                       Utility::UnitTraits<cgs::length>::name() );\n  FRENSIE_CHECK_EQUAL( dist_data[\"dependent unit\"].toString(),\n                       Utility::UnitTraits<si::amount>::name() );\n  FRENSIE_CHECK_EQUAL( dist_data[\"exponent multiplier\"].toType<quantity<Utility::UnitTraits<cgs::length>::InverseUnit> >(),\n                       3.0/cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( dist_data[\"multiplier\"].toType<quantity<si::amount> >(),\n                       2.0*si::mole );\n  FRENSIE_CHECK_EQUAL( dist_data[\"lower bound\"].toType<quantity<cgs::length> >(),\n                       1.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( dist_data[\"upper bound\"].toType<quantity<cgs::length> >(),\n                       2.0*cgs::centimeter );\n\n  oss.str( \"\" );\n  oss.clear();\n\n  oss << *unit_aware_distribution;\n  \n  dist_data = Utility::fromString<Utility::VariantMap>( oss.str() );\n\n  FRENSIE_CHECK_EQUAL( dist_data[\"type\"].toString(),\n                       \"Exponential Distribution\" );\n  FRENSIE_CHECK_EQUAL( dist_data[\"independent unit\"].toString(),\n                       Utility::UnitTraits<cgs::length>::name() );\n  FRENSIE_CHECK_EQUAL( dist_data[\"dependent unit\"].toString(),\n                       Utility::UnitTraits<si::amount>::name() );\n  FRENSIE_CHECK_EQUAL( dist_data[\"exponent multiplier\"].toType<quantity<Utility::UnitTraits<cgs::length>::InverseUnit> >(),\n                       3.0/cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( dist_data[\"multiplier\"].toType<quantity<si::amount> >(),\n                       2.0*si::mole );\n  FRENSIE_CHECK_EQUAL( dist_data[\"lower bound\"].toType<quantity<cgs::length> >(),\n                       0.0*cgs::centimeter );\n  FRENSIE_CHECK_EQUAL( dist_data[\"upper bound\"].toType<quantity<cgs::length> >(),\n                       Utility::QuantityTraits<quantity<cgs::length> >::inf() );\n}\n\n//---------------------------------------------------------------------------//\n// Check that a distribution can be archived\nFRENSIE_UNIT_TEST_TEMPLATE_EXPAND( ExponentialDistribution,\n                                   archive,\n                                   TestArchives )\n{\n  FETCH_TEMPLATE_PARAM( 0, RawOArchive );\n  FETCH_TEMPLATE_PARAM( 1, RawIArchive );\n\n  typedef typename std::remove_pointer<RawOArchive>::type OArchive;\n  typedef typename std::remove_pointer<RawIArchive>::type IArchive;\n  \n  std::string archive_base_name( \"test_exponential_dist\" );\n  std::ostringstream archive_ostream;\n\n  // Create and archive some exponential distributions\n  {\n    std::unique_ptr<OArchive> oarchive;\n\n    createOArchive( archive_base_name, archive_ostream, oarchive );\n    \n    Utility::ExponentialDistribution dist_a;\n    Utility::ExponentialDistribution dist_b( 2.0 );\n    Utility::ExponentialDistribution dist_c( 2.0, 3.0 );\n    Utility::ExponentialDistribution dist_d( 2.0, 3.0, 1.0 );\n    Utility::ExponentialDistribution dist_e( 2.0, 3.0, 1.0, 2.0 );\n\n    FRENSIE_REQUIRE_NO_THROW(\n                            (*oarchive) << BOOST_SERIALIZATION_NVP( dist_a ) );\n    FRENSIE_REQUIRE_NO_THROW(\n                            (*oarchive) << BOOST_SERIALIZATION_NVP( dist_b ) );\n    FRENSIE_REQUIRE_NO_THROW(\n                            (*oarchive) << BOOST_SERIALIZATION_NVP( dist_c ) );\n    FRENSIE_REQUIRE_NO_THROW(\n                            (*oarchive) << BOOST_SERIALIZATION_NVP( dist_d ) );\n    FRENSIE_REQUIRE_NO_THROW(\n                            (*oarchive) << BOOST_SERIALIZATION_NVP( dist_e ) );\n    FRENSIE_REQUIRE_NO_THROW(\n                      (*oarchive) << BOOST_SERIALIZATION_NVP( distribution ) );\n  }\n\n  // Copy the archive ostream to an istream\n  std::istringstream archive_istream( archive_ostream.str() );\n\n  // Load the archived distributions\n  std::unique_ptr<IArchive> iarchive;\n\n  createIArchive( archive_istream, iarchive );\n  \n  Utility::ExponentialDistribution dist_a;\n\n  FRENSIE_REQUIRE_NO_THROW(\n                           (*iarchive) >> BOOST_SERIALIZATION_NVP( dist_a ) );\n  FRENSIE_CHECK_EQUAL( dist_a, Utility::ExponentialDistribution() );\n\n  Utility::ExponentialDistribution dist_b;\n\n  FRENSIE_REQUIRE_NO_THROW(\n                           (*iarchive) >> BOOST_SERIALIZATION_NVP( dist_b ) );\n  FRENSIE_CHECK_EQUAL( dist_b, Utility::ExponentialDistribution( 2.0 ) );\n\n  Utility::ExponentialDistribution dist_c;\n\n  FRENSIE_REQUIRE_NO_THROW(\n                           (*iarchive) >> BOOST_SERIALIZATION_NVP( dist_c ) );\n  FRENSIE_CHECK_EQUAL( dist_c, Utility::ExponentialDistribution( 2.0, 3.0 ) );\n  FRENSIE_CHECK_EQUAL( dist_c.evaluatePDF( -1.0 ), 0.0 );\n  FRENSIE_CHECK_EQUAL( dist_c.evaluatePDF( 0.0 ), 3.0 );\n  FRENSIE_CHECK_FLOATING_EQUALITY(dist_c.evaluatePDF(1.0), 3.0*exp(-3.0), 1e-12);\n\n  Utility::ExponentialDistribution dist_d;\n\n  FRENSIE_REQUIRE_NO_THROW(\n                           (*iarchive) >> BOOST_SERIALIZATION_NVP( dist_d ) );\n  FRENSIE_CHECK_EQUAL( dist_d, Utility::ExponentialDistribution( 2.0, 3.0, 1.0 ) );\n\n  Utility::ExponentialDistribution dist_e;\n\n  FRENSIE_REQUIRE_NO_THROW(\n                           (*iarchive) >> BOOST_SERIALIZATION_NVP( dist_e ) );\n  FRENSIE_CHECK_EQUAL( dist_e, Utility::ExponentialDistribution( 2.0, 3.0, 1.0, 2.0 ) );\n\n  std::shared_ptr<Utility::UnivariateDistribution> shared_dist;\n\n  FRENSIE_REQUIRE_NO_THROW( (*iarchive) >> boost::serialization::make_nvp( \"distribution\", shared_dist ) );\n  FRENSIE_CHECK_EQUAL( *dynamic_cast<Utility::ExponentialDistribution*>( shared_dist.get() ),\n                       *dynamic_cast<Utility::ExponentialDistribution*>( distribution.get() ) );\n}\n\n//---------------------------------------------------------------------------//\n// Check that a unit-aware distribution can be archived\nFRENSIE_UNIT_TEST_TEMPLATE_EXPAND( UnitAwareExponentialDistribution,\n                                   archive,\n                                   TestArchives )\n{\n  FETCH_TEMPLATE_PARAM( 0, RawOArchive );\n  FETCH_TEMPLATE_PARAM( 1, RawIArchive );\n\n  typedef typename std::remove_pointer<RawOArchive>::type OArchive;\n  typedef typename std::remove_pointer<RawIArchive>::type IArchive;\n  \n  std::string archive_base_name( \"test_unit_aware_exponential_dist\" );\n  std::ostringstream archive_ostream;\n\n  // Create and archive some exponential distributions\n  {\n    std::unique_ptr<OArchive> oarchive;\n\n    createOArchive( archive_base_name, archive_ostream, oarchive );\n    \n    Utility::UnitAwareExponentialDistribution<cgs::length,si::amount> dist_a;\n    Utility::UnitAwareExponentialDistribution<cgs::length,si::amount> dist_b( 2.0*si::mole );\n    Utility::UnitAwareExponentialDistribution<cgs::length,si::amount> dist_c( 2.0*si::mole, 3.0/cgs::centimeter );\n    Utility::UnitAwareExponentialDistribution<cgs::length,si::amount> dist_d( 2.0*si::mole, 3.0/cgs::centimeter, 1.0*cgs::centimeter );\n    Utility::UnitAwareExponentialDistribution<cgs::length,si::amount> dist_e( 2.0*si::mole, 3.0/cgs::centimeter, 1.0*cgs::centimeter, 2.0*cgs::centimeter );\n\n    FRENSIE_REQUIRE_NO_THROW(\n                            (*oarchive) << BOOST_SERIALIZATION_NVP( dist_a ) );\n    FRENSIE_REQUIRE_NO_THROW(\n                            (*oarchive) << BOOST_SERIALIZATION_NVP( dist_b ) );\n    FRENSIE_REQUIRE_NO_THROW(\n                            (*oarchive) << BOOST_SERIALIZATION_NVP( dist_c ) );\n    FRENSIE_REQUIRE_NO_THROW(\n                            (*oarchive) << BOOST_SERIALIZATION_NVP( dist_d ) );\n    FRENSIE_REQUIRE_NO_THROW(\n                            (*oarchive) << BOOST_SERIALIZATION_NVP( dist_e ) );\n    FRENSIE_REQUIRE_NO_THROW(\n           (*oarchive) << BOOST_SERIALIZATION_NVP( unit_aware_distribution ) );\n  }\n\n  // Copy the archive ostream to an istream\n  std::istringstream archive_istream( archive_ostream.str() );\n\n  // Load the archived distributions\n  std::unique_ptr<IArchive> iarchive;\n\n  createIArchive( archive_istream, iarchive );\n\n  Utility::UnitAwareExponentialDistribution<cgs::length,si::amount> dist_a;\n\n  FRENSIE_REQUIRE_NO_THROW(\n                           (*iarchive) >> BOOST_SERIALIZATION_NVP( dist_a ) );\n  FRENSIE_CHECK_EQUAL( dist_a, (Utility::UnitAwareExponentialDistribution<cgs::length,si::amount>()) );\n\n  Utility::UnitAwareExponentialDistribution<cgs::length,si::amount> dist_b;\n\n  FRENSIE_REQUIRE_NO_THROW(\n                           (*iarchive) >> BOOST_SERIALIZATION_NVP( dist_b ) );\n  FRENSIE_CHECK_EQUAL( dist_b, (Utility::UnitAwareExponentialDistribution<cgs::length,si::amount>( 2.0*si::mole )) );\n\n  Utility::UnitAwareExponentialDistribution<cgs::length,si::amount> dist_c;\n\n  FRENSIE_REQUIRE_NO_THROW(\n                           (*iarchive) >> BOOST_SERIALIZATION_NVP( dist_c ) );\n  FRENSIE_CHECK_EQUAL( dist_c, (Utility::UnitAwareExponentialDistribution<cgs::length,si::amount>( 2.0*si::mole, 3.0/cgs::centimeter )) );\n\n  Utility::UnitAwareExponentialDistribution<cgs::length,si::amount> dist_d;\n\n  FRENSIE_REQUIRE_NO_THROW(\n                           (*iarchive) >> BOOST_SERIALIZATION_NVP( dist_d ) );\n  FRENSIE_CHECK_EQUAL( dist_d, (Utility::UnitAwareExponentialDistribution<cgs::length,si::amount>( 2.0*si::mole, 3.0/cgs::centimeter, 1.0*cgs::centimeter )) );\n\n  Utility::UnitAwareExponentialDistribution<cgs::length,si::amount> dist_e;\n\n  FRENSIE_REQUIRE_NO_THROW(\n                           (*iarchive) >> BOOST_SERIALIZATION_NVP( dist_e ) );\n  FRENSIE_CHECK_EQUAL( dist_e, (Utility::UnitAwareExponentialDistribution<cgs::length,si::amount>( 2.0*si::mole, 3.0/cgs::centimeter, 1.0*cgs::centimeter, 2.0*cgs::centimeter )) );\n\n  std::shared_ptr<Utility::UnitAwareUnivariateDistribution<cgs::length,si::amount>> shared_dist;\n\n  FRENSIE_REQUIRE_NO_THROW( (*iarchive) >> boost::serialization::make_nvp( \"unit_aware_distribution\", shared_dist ) );\n  FRENSIE_CHECK_EQUAL( (*dynamic_cast<Utility::UnitAwareExponentialDistribution<cgs::length,si::amount>*>( shared_dist.get() )),\n                       (*dynamic_cast<Utility::UnitAwareExponentialDistribution<cgs::length,si::amount>*>( unit_aware_distribution.get() )) );\n}\n\n//---------------------------------------------------------------------------//\n// Check that distributions can be scaled\nFRENSIE_UNIT_TEST_TEMPLATE_EXPAND( UnitAwareExponentialDistribution,\n\t\t\t\t   explicit_conversion,\n                                   TestUnitTypeQuads )\n{\n  FETCH_TEMPLATE_PARAM( 0, RawIndepUnitA );\n  FETCH_TEMPLATE_PARAM( 1, RawDepUnitA );\n  FETCH_TEMPLATE_PARAM( 2, RawIndepUnitB );\n  FETCH_TEMPLATE_PARAM( 3, RawDepUnitB );\n\n  typedef typename std::remove_pointer<RawIndepUnitA>::type IndepUnitA;\n  typedef typename std::remove_pointer<RawDepUnitA>::type DepUnitA;\n  typedef typename std::remove_pointer<RawIndepUnitB>::type IndepUnitB;\n  typedef typename std::remove_pointer<RawDepUnitB>::type DepUnitB;\n  \n  typedef typename Utility::UnitTraits<IndepUnitA>::template GetQuantityType<double>::type IndepQuantityA;\n  typedef typename Utility::UnitTraits<typename Utility::UnitTraits<IndepUnitA>::InverseUnit>::template GetQuantityType<double>::type InverseIndepQuantityA;\n\n  typedef typename Utility::UnitTraits<IndepUnitB>::template GetQuantityType<double>::type IndepQuantityB;\n  typedef typename Utility::UnitTraits<typename Utility::UnitTraits<IndepUnitB>::InverseUnit>::template GetQuantityType<double>::type InverseIndepQuantityB;\n\n  typedef typename Utility::UnitTraits<DepUnitA>::template GetQuantityType<double>::type DepQuantityA;\n  typedef typename Utility::UnitTraits<DepUnitB>::template GetQuantityType<double>::type DepQuantityB;\n\n  // Copy from unitless distribution to distribution type A (static method)\n  Utility::UnitAwareExponentialDistribution<IndepUnitA,DepUnitA>\n    unit_aware_dist_a_copy = Utility::UnitAwareExponentialDistribution<IndepUnitA,DepUnitA>::fromUnitlessDistribution( *dynamic_cast<Utility::ExponentialDistribution*>( distribution.get() ) );\n\n  // Copy from distribution type A to distribution type B (explicit cast)\n  Utility::UnitAwareExponentialDistribution<IndepUnitB,DepUnitB>\n    unit_aware_dist_b_copy( unit_aware_dist_a_copy );\n\n  IndepQuantityA indep_quantity_a =\n    Utility::QuantityTraits<IndepQuantityA>::initializeQuantity( 0.0 );\n  InverseIndepQuantityA inv_indep_quantity_a =\n    Utility::QuantityTraits<InverseIndepQuantityA>::initializeQuantity( 3.0 );\n  DepQuantityA dep_quantity_a =\n    Utility::QuantityTraits<DepQuantityA>::initializeQuantity( 2.0 );\n\n  IndepQuantityB indep_quantity_b( indep_quantity_a );\n  InverseIndepQuantityB inv_indep_quantity_b( inv_indep_quantity_a );\n  DepQuantityB dep_quantity_b( dep_quantity_a );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY(\n\t\t\t   unit_aware_dist_a_copy.evaluate( indep_quantity_a ),\n\t\t\t   dep_quantity_a,\n\t\t\t   1e-15 );\n  FRENSIE_CHECK_FLOATING_EQUALITY(\n\t\t\tunit_aware_dist_a_copy.evaluatePDF( indep_quantity_a ),\n\t\t\tinv_indep_quantity_a,\n\t\t\t1e-15 );\n  FRENSIE_CHECK_FLOATING_EQUALITY(\n\t\t\t   unit_aware_dist_b_copy.evaluate( indep_quantity_b ),\n\t\t\t   dep_quantity_b,\n\t\t\t   1e-15 );\n  FRENSIE_CHECK_FLOATING_EQUALITY(\n\t\t\tunit_aware_dist_b_copy.evaluatePDF( indep_quantity_b ),\n\t\t\tinv_indep_quantity_b,\n\t\t\t1e-15 );\n\n  Utility::setQuantity( indep_quantity_a, 1.0 );\n  Utility::setQuantity( inv_indep_quantity_a, 3.0*exp(-3.0) );\n  Utility::setQuantity( dep_quantity_a, 2.0*exp(-3.0) );\n\n  indep_quantity_b = IndepQuantityB( indep_quantity_a );\n  inv_indep_quantity_b = InverseIndepQuantityB( inv_indep_quantity_a );\n  dep_quantity_b = DepQuantityB( dep_quantity_a );\n\n  FRENSIE_CHECK_FLOATING_EQUALITY(\n\t\t\t   unit_aware_dist_a_copy.evaluate( indep_quantity_a ),\n\t\t\t   dep_quantity_a,\n\t\t\t   1e-15 );\n  FRENSIE_CHECK_FLOATING_EQUALITY(\n\t\t\tunit_aware_dist_a_copy.evaluatePDF( indep_quantity_a ),\n\t\t\tinv_indep_quantity_a,\n\t\t\t1e-15 );\n  FRENSIE_CHECK_FLOATING_EQUALITY(\n\t\t\t   unit_aware_dist_b_copy.evaluate( indep_quantity_b ),\n\t\t\t   dep_quantity_b,\n\t\t\t   1e-15 );\n  FRENSIE_CHECK_FLOATING_EQUALITY(\n\t\t\tunit_aware_dist_b_copy.evaluatePDF( indep_quantity_b ),\n\t\t\tinv_indep_quantity_b,\n\t\t\t1e-15 );\n}\n\n//---------------------------------------------------------------------------//\n// Custom setup\n//---------------------------------------------------------------------------//\nFRENSIE_CUSTOM_UNIT_TEST_SETUP_BEGIN();\n\nFRENSIE_CUSTOM_UNIT_TEST_INIT()\n{\n  // Initialize the random number generator\n  Utility::RandomNumberGenerator::createStreams();\n}\n\nFRENSIE_CUSTOM_UNIT_TEST_SETUP_END();\n\n//---------------------------------------------------------------------------//\n// end tstExponentialDistribution.cpp\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "fd6e2807c51d89ce2764907008ab98f68e199977", "size": 42845, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "packages/utility/distribution/test/tstExponentialDistribution.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/utility/distribution/test/tstExponentialDistribution.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/utility/distribution/test/tstExponentialDistribution.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": 43.1905241935, "max_line_length": 228, "alphanum_fraction": 0.6572062084, "num_tokens": 10895, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4524913262658594}}
{"text": "// Standard libraries\n#ifndef INCLUDE_STL\n\t#include <cstdlib>\n\t#include <iostream>\n\t#include <fstream>\n\t#include <sstream>\n\t#include <cmath>\n\t#include <string>\n\t#include <vector>\n\t#include <algorithm>\n\t#include <thread>\n\t#include <stdexcept>\n\t#define INCLUDE_STL\n#endif\n\n// External libraries\n#ifndef INCLUDE_EIGEN\n\t#include <Eigen/Dense>\n\t#define INCLUDE_EIGEN\n#endif\n\n// My libraries\n#ifndef INCLUDE_VOLUME\n\t#include \"volume.hpp\"\n\t#define INCLUDE_VOLUME\n#endif\n\nconst unsigned int N = 3;\n\nint main(int argc, char** argv) {\n\tEigen::MatrixXd u = Eigen::MatrixXd::Random(N, N);\n\tstd::cout << u << std::endl;\n\n\tEigen::MatrixXd v = Eigen::MatrixXd::Random(N, N);\n\t// std::cout << v << std::endl;\n\n\tEigen::MatrixXd p = Eigen::MatrixXd::Random(N, N);\n\t// std::cout << p << std::endl;\n\n\tEigen::Matrix<Node*, N+2, N+2> volumes;\n\n\t// Inner volumes\n\tfor (unsigned int i = 1; i < N+1; i++) {\t\t\n\t\tfor (unsigned int j = 1; j < N+1; j++) {\n\t\t\tvolumes(j, i) = new Volume(u(j-1, i-1), v(j-1, i-1), p(j-1, i-1));\n\t\t}\n\t}\n\n\t// Boundary volumes\n\tfor (unsigned int i = 1; i < N+1; i++) {\n\t\tvolumes(0, i) = new Boundary(volumes(N, i));\n\t\tvolumes(i, 0) = new Boundary(volumes(i, N));\n\t\tvolumes(N+1, i) = new Boundary(volumes(1, i));\n\t\tvolumes(i, N+1) = new Boundary(volumes(i, 1));\n\t}\n\n\t// Corner volumes\n\tvolumes(0, 0) = new Node();\n\tvolumes(N+1, 0) = new Node();\n\tvolumes(0, N+1) = new Node();\n\tvolumes(N+1, N+1) = new Node();\n\n\t/* Test */\n\n\tfor (unsigned int i = 0; i < N+2; i++) {\n\t\tfor (unsigned int j = 0; j < N+2; j++) {\n\t\t\tstd::cout << volumes(j, i)->get_u() << std::endl;\n\t\t}\n\t\tstd::cout << std::endl;\n\t}\n\n\tstd::cout << \"SET U\" << std::endl;\n\tvolumes(1, 1)->set_u(100.0);\n\n\tfor (unsigned int i = 0; i < N+2; i++) {\n\t\tfor (unsigned int j = 0; j < N+2; j++) {\n\t\t\tstd::cout << volumes(j, i)->get_u() << std::endl;\n\t\t}\n\t\tstd::cout << std::endl;\n\t}\n\n\treturn 0;\n}\n", "meta": {"hexsha": "fd4583afaf08c2f9fb84544e392c38e9e41beb1d", "size": 1845, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "polmes/spectro-NS", "max_stars_repo_head_hexsha": "e8e86f7ff9eb226d7855a82bacbafad196bb307a", "max_stars_repo_licenses": ["MIT"], "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": "polmes/spectro-NS", "max_issues_repo_head_hexsha": "e8e86f7ff9eb226d7855a82bacbafad196bb307a", "max_issues_repo_licenses": ["MIT"], "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": "polmes/spectro-NS", "max_forks_repo_head_hexsha": "e8e86f7ff9eb226d7855a82bacbafad196bb307a", "max_forks_repo_licenses": ["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.9642857143, "max_line_length": 69, "alphanum_fraction": 0.5913279133, "num_tokens": 641, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.5926665999540697, "lm_q1q2_score": 0.4524913262658593}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n#include <Eigen/Core>\n\n\n#if USE_DOUBLE  \n    typedef double real;\n    typedef Eigen::MatrixXd MatrixReal;\n#else\n    typedef float real;\n    typedef Eigen::MatrixXf MatrixReal;\n#endif\ntypedef Eigen::Matrix<real, Eigen::Dynamic, 3, Eigen::RowMajor> ObservationMatrix3;\n", "meta": {"hexsha": "f695e4a2ae130571816a5b310bf6dcaafbd6b856", "size": 304, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "react-frontend-docker/src_cpp/definitions.hpp", "max_stars_repo_name": "gbernardino/RVparcellation", "max_stars_repo_head_hexsha": "d6068f22eea4fe045f5ce7e19a54344c91a0090f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "react-frontend-docker/src_cpp/definitions.hpp", "max_issues_repo_name": "gbernardino/RVparcellation", "max_issues_repo_head_hexsha": "d6068f22eea4fe045f5ce7e19a54344c91a0090f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "react-frontend-docker/src_cpp/definitions.hpp", "max_forks_repo_name": "gbernardino/RVparcellation", "max_forks_repo_head_hexsha": "d6068f22eea4fe045f5ce7e19a54344c91a0090f", "max_forks_repo_licenses": ["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.2666666667, "max_line_length": 83, "alphanum_fraction": 0.7335526316, "num_tokens": 73, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7490872243177518, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.45239762100290815}}
{"text": "#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Surface_mesh.h>\n#include <CGAL/Surface_mesh/IO.h>\n#include <CGAL/boost/graph/selection.h>\n\n#include <boost/property_map/property_map.hpp>\n\n#include <iostream>\n#include <fstream>\n#include <set>\n#include <unordered_map>\n\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel;\ntypedef CGAL::Surface_mesh<Kernel::Point_3> SM;\ntypedef boost::graph_traits<SM>::face_descriptor face_descriptor;\n\nint main()\n{\n  SM sm;\n  std::ifstream input(CGAL::data_file_path(\"meshes/head.off\"));\n  input >> sm;\n\n// define my selection of faces to remove\n  std::unordered_map<face_descriptor, bool> is_selected_map;\n\n  const int selection_indices[30] = {652,18,328,698,322,212,808,353,706,869,646,352,788,696,714,796,937,2892,374,697,227,501,786,794,345,16,21,581,347,723};\n  std::set<int> index_set(&selection_indices[0], &selection_indices[0]+30);\n\n  std::vector<face_descriptor> faces_to_remove;\n  int index = 0;\n  for(face_descriptor fh : faces(sm))\n  {\n    if(index_set.count(index)==0)\n      is_selected_map[fh]=false;\n    else\n    {\n      faces_to_remove.push_back(fh);\n      is_selected_map[fh]=true;\n    }\n    ++index;\n  }\n\n  CGAL::regularize_face_selection_borders (sm, boost::make_assoc_property_map(is_selected_map), 0.5);\n\n  return 0;\n}\n\n", "meta": {"hexsha": "c0cdbb0565e291ec58cae398cccd4846493e5f81", "size": 1322, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "BGL/test/BGL/test_Regularize_face_selection_borders.cpp", "max_stars_repo_name": "ffteja/cgal", "max_stars_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "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": "BGL/test/BGL/test_Regularize_face_selection_borders.cpp", "max_issues_repo_name": "ffteja/cgal", "max_issues_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "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": "BGL/test/BGL/test_Regularize_face_selection_borders.cpp", "max_forks_repo_name": "ffteja/cgal", "max_forks_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "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": 26.9795918367, "max_line_length": 156, "alphanum_fraction": 0.7382753404, "num_tokens": 375, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4523976142370452}}
{"text": "// -----------------------------------------------------------------------------\n// Fern \u00a9 Geoneric\n//\n// This file is part of Geoneric Fern which is available under the terms of\n// the GNU General Public License (GPL), version 2. If you do not want to\n// be bound by the terms of the GPL, you may purchase a proprietary license\n// from Geoneric (http://www.geoneric.eu/contact).\n// -----------------------------------------------------------------------------\n#define BOOST_TEST_MODULE fern algorithm algebra vector laplacian\n#include <boost/test/unit_test.hpp>\n#include \"fern/core/data_customization_point/scalar.h\"\n#include \"fern/core/type_traits.h\"\n#include \"fern/core/types.h\"\n#include \"fern/feature/core/data_customization_point/masked_raster.h\"\n#include \"fern/algorithm/core/argument_customization_point/masked_raster.h\"\n#include \"fern/algorithm/core/mask_customization_point/array.h\"\n#include \"fern/algorithm/core/argument_traits/masked_raster.h\"\n#include \"fern/algorithm/algebra/vector/laplacian.h\"\n\n\nnamespace fa = fern::algorithm;\n\n\ntemplate<\n    class Value,\n    class Result>\nusing OutOfRangePolicy = fa::laplacian::OutOfRangePolicy<Value, Result>;\n\n\nBOOST_AUTO_TEST_CASE(out_of_range_policy)\n{\n    {\n        OutOfRangePolicy<fern::float32_t, fern::float32_t> policy;\n        BOOST_CHECK(policy.within_range(123.456f, 4.5f));\n        BOOST_CHECK(!policy.within_range(123.456f,\n            fern::nan<fern::float32_t>()));\n        BOOST_CHECK(!policy.within_range(123.456f,\n            fern::infinity<fern::float32_t>()));\n    }\n}\n\n\ntemplate<\n    class T>\nusing MaskedRaster = fern::MaskedRaster<T, 2>;\n\n\nBOOST_AUTO_TEST_CASE(algorithm)\n{\n    // Create input raster:\n    // +----+----+----+----+\n    // |  0 |  1 |  2 |  3 |\n    // +----+----+----+----+\n    // |  4 |  5 |  6 |  7 |\n    // +----+----+----+----+\n    // |  8 |  9 | 10 | 11 |\n    // +----+----+----+----+\n    // | 12 | 13 | 14 | 15 |\n    // +----+----+----+----+\n    // | 16 | 17 | 18 | 19 |\n    // +----+----+----+----+\n    size_t const nr_rows = 5;\n    size_t const nr_cols = 4;\n    auto extents = fern::extents[nr_rows][nr_cols];\n\n    double const cell_width = 2.0;\n    double const cell_height = 3.0;\n    double const west = 0.0;\n    double const north = 0.0;\n\n    MaskedRaster<double>::Transformation transformation{{west, cell_width,\n        north, cell_height}};\n    MaskedRaster<double> raster(extents, transformation);\n\n    std::iota(raster.data(), raster.data() + raster.num_elements(), 0);\n\n    fa::SequentialExecutionPolicy sequential;\n\n    // Calculate laplacian.\n    MaskedRaster<double> result(extents, transformation);\n\n    // Without masking input and output values.\n    {\n        fa::algebra::laplacian(sequential, raster, result);\n\n        // Verify the result.\n        BOOST_CHECK_EQUAL(get(result, index(result, 0, 0)),\n            (25.0 - (8.0 * 0.0)) / 6.0);\n        BOOST_CHECK_EQUAL(get(result, index(result, 1, 1)),\n            (100.0 - (20.0 * 5.0)) / 6.0);\n    }\n\n    using InputNoDataPolicy = fa::InputNoDataPolicies<\n        fa::DetectNoDataByValue<fern::Mask<2>>>;\n    using OutputNoDataPolicy = fa::MarkNoDataByValue<fern::Mask<2>>;\n\n    // With masking input and output values.\n    {\n        result.fill(999.0);\n        result.mask().fill(false);\n        raster.mask()[1][1] = true;\n\n        OutputNoDataPolicy output_no_data_policy(result.mask(), true);\n\n        fa::algebra::laplacian<fa::laplacian::OutOfRangePolicy>(\n            InputNoDataPolicy{{raster.mask(), true}},\n            output_no_data_policy,\n            sequential,\n            raster, result);\n\n        // Verify the result.\n        BOOST_CHECK_EQUAL(get(result.mask(), index(result.mask(), 0, 0)),\n            false);\n        BOOST_CHECK_EQUAL(get(result.mask(), index(result.mask(), 1, 1)),\n            true);\n        BOOST_CHECK_EQUAL(get(result, index(result, 0, 0)),\n            (15.0 - (6.0 * 0.0)) / 6.0);\n        BOOST_CHECK_EQUAL(get(result, index(result, 1, 1)), 999.0);\n    }\n}\n", "meta": {"hexsha": "7a30250f65cc20450ba0474336abfac2c0bf084d", "size": 3967, "ext": "cc", "lang": "C++", "max_stars_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/fern/source/fern/algorithm/algebra/vector/test/laplacian_test.cc", "max_stars_repo_name": "quanpands/wflow", "max_stars_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/fern/source/fern/algorithm/algebra/vector/test/laplacian_test.cc", "max_issues_repo_name": "quanpands/wflow", "max_issues_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/fern/source/fern/algorithm/algebra/vector/test/laplacian_test.cc", "max_forks_repo_name": "quanpands/wflow", "max_forks_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.7851239669, "max_line_length": 80, "alphanum_fraction": 0.5921351147, "num_tokens": 1063, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4523976142370452}}
{"text": "\n#ifndef NURSINGROBOT_STATESPACE_HPP\n#define NURSINGROBOT_STATESPACE_HPP\n\n#include <vector>\n#include <array>\n#include <Eigen/Dense>\n#include <Eigen/Core>\n#include <Eigen/StdVector>\n#include \"macros/class_forward.h\"\n#include <glog/logging.h>\n\nnamespace state_space {\n    //exponential coordinate of se(3) s = [w,v]\n    typedef Eigen::Matrix<double, 6, 1> R6;\n\n    //lie algebra se(3) of the lie group SE(3)\n    typedef Eigen::Matrix4d se_3;\n\n    //lie group SE(3)\n    typedef Eigen::Matrix4d SE_3;\n\n    //exponential coordinate of so(3)\n    typedef Eigen::Vector3d R3;\n\n    //lie algebra so(3) of the lie group SO(3)\n    typedef Eigen::Matrix3d so_3;\n\n    //lie group SO(3)\n    typedef Eigen::Matrix3d SO_3;\n\n    //adjoint matrix 6X6 for Lie bracket\n    typedef Eigen::Matrix<double, 6, 6> adjoint_mat;\n\n    typedef Eigen::Matrix<double, 6, 6> jacobian_mat;\n\n    /**\\note: 2e-8 denotes 1e-6 degree precision*/\n    static bool NearZero(const double val)\n    {\n        return (std::abs(val) < 1e-8);\n    }\n\n    /**\n    * A state space represents the set of possible states for a planning problem.\n    * for example Rn SO2 SO3 SE3 SE3\n    * This class is abstract and must be subclassed in order to provide actual\n    * functionality.\n    */\n    template<typename T>\n    class StateSpace {\n    public:\n        StateSpace() = default;\n\n        virtual ~StateSpace() = default;\n\n        //\n        virtual T operator+(const T &input) const = 0;\n\n        virtual T operator-(const T &input) const = 0;\n\n        virtual T operator*(double s) const = 0;\n\n        virtual T operator()(double theta) const = 0;\n\n        virtual bool operator==(const T &other) const = 0;\n\n        virtual T inverse() const = 0;\n\n        virtual T random(std::default_random_engine &randomEngine, const Eigen::MatrixX2d *bounds_ptr) const = 0;\n\n        virtual double distance(const T &to) const = 0;\n\n        virtual double norm() const = 0;\n\n        virtual const double *data() const = 0;\n\n        virtual unsigned int Dimensions() const = 0;\n    };\n\n\n}\n\n\n#endif //NURSINGROBOT_STATESPACE_HPP\n", "meta": {"hexsha": "361db52f3471468d90ca1db151662410d6d799d1", "size": 2067, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/StateSpace/StateSpace.hpp", "max_stars_repo_name": "ZhouYixuanRobtic/NursingRobot", "max_stars_repo_head_hexsha": "1372e4af40a3315b754d1b6273b5a00d09c4def6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-09T01:32:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-09T01:32:13.000Z", "max_issues_repo_path": "include/StateSpace/StateSpace.hpp", "max_issues_repo_name": "ZhouYixuanRobtic/NursingRobot", "max_issues_repo_head_hexsha": "1372e4af40a3315b754d1b6273b5a00d09c4def6", "max_issues_repo_licenses": ["MIT"], "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/StateSpace/StateSpace.hpp", "max_forks_repo_name": "ZhouYixuanRobtic/NursingRobot", "max_forks_repo_head_hexsha": "1372e4af40a3315b754d1b6273b5a00d09c4def6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-15T15:29:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-15T15:29:08.000Z", "avg_line_length": 24.3176470588, "max_line_length": 113, "alphanum_fraction": 0.6473149492, "num_tokens": 564, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4523976142370452}}
{"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 2016, 2017, 2018.\n// Modifications copyright (c) 2016-2018, Oracle and/or its affiliates.\n\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_STRATEGIES_CARTESIAN_AREA_HPP\n#define BOOST_GEOMETRY_STRATEGIES_CARTESIAN_AREA_HPP\n\n\n#include <boost/mpl/if.hpp>\n\n//#include <boost/geometry/arithmetic/determinant.hpp>\n#include <boost/geometry/core/access.hpp>\n#include <boost/geometry/core/coordinate_type.hpp>\n#include <boost/geometry/core/coordinate_dimension.hpp>\n#include <boost/geometry/strategies/area.hpp>\n#include <boost/geometry/util/select_most_precise.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\nnamespace strategy { namespace area\n{\n\n/*!\n\\brief Cartesian area calculation\n\\ingroup strategies\n\\details Calculates cartesian area using the trapezoidal rule\n\\tparam CalculationType \\tparam_calculation\n\n\\qbk{\n[heading See also]\n[link geometry.reference.algorithms.area.area_2_with_strategy area (with strategy)]\n}\n\n*/\ntemplate\n<\n    typename CalculationType = void\n>\nclass cartesian\n{\npublic :\n    template <typename Geometry>\n    struct result_type\n        : strategy::area::detail::result_type\n            <\n                Geometry,\n                CalculationType\n            >\n    {};\n    \n    template <typename Geometry>\n    class state\n    {\n        friend class cartesian;\n\n        typedef typename result_type<Geometry>::type return_type;\n\n    public:        \n        inline state()\n            : sum(0)\n        {\n            // Strategy supports only 2D areas\n            assert_dimension<Geometry, 2>();\n        }\n\n    private:\n        inline return_type area() const\n        {\n            return_type const two = 2;\n            return sum / two;\n        }\n\n        return_type sum;\n    };\n\n    template <typename PointOfSegment, typename Geometry>\n    static inline void apply(PointOfSegment const& p1,\n                             PointOfSegment const& p2,\n                             state<Geometry>& st)\n    {\n        typedef typename state<Geometry>::return_type return_type;\n\n        // Below formulas are equivalent, however the two lower ones\n        // suffer less from accuracy loss for great values of coordinates.\n        // See: https://svn.boost.org/trac/boost/ticket/11928\n\n        // SUM += x2 * y1 - x1 * y2;\n        // state.sum += detail::determinant<return_type>(p2, p1);\n\n        // SUM += (x2 - x1) * (y2 + y1)\n        //state.sum += (return_type(get<0>(p2)) - return_type(get<0>(p1)))\n        //           * (return_type(get<1>(p2)) + return_type(get<1>(p1)));\n\n        // SUM += (x1 + x2) * (y1 - y2)\n        st.sum += (return_type(get<0>(p1)) + return_type(get<0>(p2)))\n                * (return_type(get<1>(p1)) - return_type(get<1>(p2)));\n    }\n\n    template <typename Geometry>\n    static inline typename result_type<Geometry>::type\n        result(state<Geometry>& st)\n    {\n        return st.area();\n    }\n\n};\n\n#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\n\nnamespace services\n{\n    template <>\n    struct default_strategy<cartesian_tag>\n    {\n        typedef strategy::area::cartesian<> type;\n    };\n\n} // namespace services\n\n#endif // DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\n\n\n}} // namespace strategy::area\n\n\n\n}} // namespace boost::geometry\n\n\n#endif // BOOST_GEOMETRY_STRATEGIES_CARTESIAN_AREA_HPP\n", "meta": {"hexsha": "070e8f56b050eda04fb827428a8cabc5ededa6e1", "size": 3958, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/geometry/strategies/cartesian/area.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/area.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/area.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": 26.7432432432, "max_line_length": 83, "alphanum_fraction": 0.6574027287, "num_tokens": 963, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.45239761423704505}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_EULER_FUNCTIONS_SCALAR_ERF_HPP_INCLUDED\n#define NT2_EULER_FUNCTIONS_SCALAR_ERF_HPP_INCLUDED\n\n#include <nt2/euler/functions/erf.hpp>\n#include <nt2/euler/functions/details/erf_kernel.hpp>\n#include <nt2/include/constants/one.hpp>\n#include <nt2/include/constants/pi.hpp>\n#include <nt2/include/constants/two.hpp>\n#include <nt2/include/constants/twothird.hpp>\n#include <nt2/include/constants/zero.hpp>\n#include <nt2/include/functions/scalar/abs.hpp>\n#include <nt2/include/functions/scalar/exp.hpp>\n#include <nt2/include/functions/scalar/is_ltz.hpp>\n#include <nt2/include/functions/scalar/negif.hpp>\n#include <nt2/include/functions/scalar/oneminus.hpp>\n#include <nt2/include/functions/scalar/oneplus.hpp>\n#include <nt2/include/functions/scalar/sqr.hpp>\n#include <nt2/include/functions/scalar/sqrt.hpp>\n#include <nt2/sdk/meta/scalar_of.hpp>\n\n#include <boost/simd/sdk/config.hpp>\n\n#ifndef BOOST_SIMD_NO_INVALIDS\n#include <nt2/include/functions/scalar/is_nan.hpp>\n#endif\n\n#ifndef BOOST_SIMD_NO_INFINITIES\n#include <nt2/include/functions/scalar/is_inf.hpp>\n#include <nt2/include/functions/scalar/signnz.hpp>\n#endif\n\nnamespace nt2 { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT  ( erf_, tag::cpu_\n                            , (A0)\n                            , (scalar_< double_<A0> >)\n                            )\n  {\n    typedef A0 result_type;\n    NT2_FUNCTOR_CALL(1)\n    {\n      #ifndef BOOST_SIMD_NO_INVALIDS\n      if(is_nan(a0)) return a0;\n      #endif\n      A0 x =  nt2::abs(a0);\n      A0 xx = nt2::sqr(x);\n      if(x<= A0(0.0000000001))\n        return a0*nt2::Two<A0>()/nt2::sqrt(Pi<A0>());\n      else if (x<= A0(0.65))\n      {\n        return a0*details::erf_kernel<A0>::erf1(xx);\n      }\n      else if(x<= A0(2.2))\n      {\n        A0 z = oneminus(exp(-xx)*details::erf_kernel<A0>::erfc2(x));\n        return negif(is_ltz(a0), z);\n      }\n      else if(x<= A0(6))\n      {\n        A0 z = nt2::oneminus(exp(-xx)*details::erf_kernel<A0>::erfc3(x));\n        return nt2::negif(nt2::is_ltz(a0), z);\n      }\n      else\n        return nt2::One<A0>();\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  ( erf_, tag::cpu_\n                            , (A0)\n                            , (scalar_< single_<A0> >)\n                            )\n  {\n    typedef A0 result_type;\n    NT2_FUNCTOR_CALL(1)\n    {\n      #ifndef BOOST_SIMD_NO_INVALIDS\n      if(is_nan(a0)) return a0;\n      #endif\n      #ifndef BOOST_SIMD_NO_INFINITIES\n      if (nt2::is_inf(a0)) return signnz(a0);\n      #endif\n      A0 x =  nt2::abs(a0);\n      if (x < Twothird<A0>())\n      {\n        return a0*details::erf_kernel<A0>::erf1(sqr(x));\n      }\n      else\n      {\n       A0 z = x/oneplus(x)-A0(0.4);\n        A0 r2 =   oneminus(exp(-sqr(x))*details::erf_kernel<A0>::erfc2(z));\n        if (a0 < Zero<A0>()) r2 = -r2;\n        return r2;\n      }\n\n    }\n  };\n} }\n\n#endif\n", "meta": {"hexsha": "deac926949bcaf625611e9176ddaf19ad8fc3a33", "size": 3326, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/euler/include/nt2/euler/functions/scalar/erf.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/core/euler/include/nt2/euler/functions/scalar/erf.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/core/euler/include/nt2/euler/functions/scalar/erf.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.7962962963, "max_line_length": 80, "alphanum_fraction": 0.573962718, "num_tokens": 927, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.749087201911703, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.452397607471182}}
{"text": "#pragma once\n\n#include <boost/units/quantity.hpp>\n#include <boost/units/unit.hpp>\n\n#include <boost/units/base_units/si/kilogram.hpp>\n#include <boost/units/base_units/si/meter.hpp>\n#include <boost/units/base_units/si/second.hpp>\n#include <boost/units/physical_dimensions/length.hpp>\n#include <boost/units/physical_dimensions/mass.hpp>\n\n#include <boost/units/systems/si/acceleration.hpp>\n#include <boost/units/systems/si/force.hpp>\n#include <boost/units/systems/si/length.hpp>\n#include <boost/units/systems/si/mass.hpp>\n#include <boost/units/systems/si/momentum.hpp>\n#include <boost/units/systems/si/time.hpp>\n#include <boost/units/systems/si/velocity.hpp>\n\nnamespace bu = boost::units;\nnamespace si = bu::si;\n\nclass IEngine\n{\nprotected:\n    explicit IEngine() = default;\n\npublic:\n    virtual ~IEngine() = default;\n\n    using Length_t = bu::quantity<si::length>;\n    using Mass_t = bu::quantity<si::mass>;\n    using Time_t = bu::quantity<si::time>;\n    using Acceleration_t = bu::quantity<si::acceleration>;\n    using Speed_t = bu::quantity<si::velocity>;\n    using Momentum_t = bu::quantity<si::momentum>;\n    using Force_t = bu::quantity<si::force>;\n\n    virtual void reset(Length_t new_state) = 0;\n\n    virtual std::pair<Length_t, Speed_t> update(const Time_t dt) = 0;\n\n    void setThrottle(const double t);\n\nprotected:\n    Mass_t currentMass() const;\n\n    Force_t currentThrust() const;\n\n    Force_t gravity(const Length_t& height) const;\n\n    Force_t totalForce(const Length_t& height) const;\n\n    static const inline Mass_t dry_mass = 2792 * si::kilograms;\n    static const inline Mass_t total_mass = 16437 * si::kilograms;\n    double m_throttle;\n};", "meta": {"hexsha": "88932c555e9f78bc2bec83e1dbbbc9df674831d8", "size": 1653, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/iengine.hpp", "max_stars_repo_name": "julienlopez/QmlMoonLander", "max_stars_repo_head_hexsha": "fe3d7555abfc36a814f2205a0965198f5fca87d2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-08-30T03:04:27.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-30T03:04:27.000Z", "max_issues_repo_path": "src/iengine.hpp", "max_issues_repo_name": "julienlopez/QmlMoonLander", "max_issues_repo_head_hexsha": "fe3d7555abfc36a814f2205a0965198f5fca87d2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/iengine.hpp", "max_forks_repo_name": "julienlopez/QmlMoonLander", "max_forks_repo_head_hexsha": "fe3d7555abfc36a814f2205a0965198f5fca87d2", "max_forks_repo_licenses": ["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.0, "max_line_length": 69, "alphanum_fraction": 0.7265577737, "num_tokens": 441, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907933, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.45238133025372446}}
{"text": "#include \"../sigmaextended_prover.h\"\n#include \"../sigmaextended_verifier.h\"\n\n#include \"lelantus_test_fixture.h\"\n\n#include <boost/test/unit_test.hpp>\n\nnamespace lelantus {\n\nclass SigmaExtendedTests : public LelantusTestingSetup {\npublic:\n    struct Secret {\n    public:\n        Secret(std::size_t l) : l(l) {\n            s.randomize();\n            v.randomize();\n            r.randomize();\n        }\n\n    public:\n        std::size_t l;\n        Scalar s, v, r;\n    };\n\npublic:\n    typedef SigmaExtendedProver Prover;\n    typedef SigmaExtendedProof Proof;\n    typedef SigmaExtendedVerifier Verifier;\n\npublic:\n    SigmaExtendedTests() {}\n\npublic:\n    void GenerateParams(std::size_t _N, std::size_t _n, std::size_t _m = 0) {\n        N = _N;\n        n = _n;\n        m = _m;\n        if (!m) {\n            if (n <= 1) {\n                throw std::logic_error(\"Try to get value of m from invalid n\");\n            }\n\n            m = (std::size_t)std::round(log(N) / log(n));\n        }\n\n        h_gens = RandomizeGroupElements(n * m);\n        g.randomize();\n    }\n\n    void GenerateBatchProof(\n        Prover &prover,\n        std::vector<GroupElement> const &coins,\n        std::size_t l,\n        Scalar const &s,\n        Scalar const &v,\n        Scalar const &r,\n        Scalar const &x,\n        Proof &proof\n    ) {\n        auto gs = g * s.negate();\n        std::vector<GroupElement> commits(coins.begin(), coins.end());\n        for (auto &c : commits) {\n            c += gs;\n        }\n\n        Scalar rA, rB, rC, rD;\n        rA.randomize();\n        rB.randomize();\n        rC.randomize();\n        rD.randomize();\n\n        std::vector<Scalar> sigma;\n        std::vector<Scalar> Tk, Pk, Yk;\n        Tk.resize(m);\n        Pk.resize(m);\n        Yk.resize(m);\n\n        std::vector<Scalar> a;\n        a.resize(n * m);\n\n        prover.sigma_commit(\n            commits, l, rA, rB, rC, rD, a, Tk, Pk, Yk, sigma, proof);\n\n        prover.sigma_response(\n            sigma, a, rA, rB, rC, rD, v, r, Tk, Pk, x, proof);\n    }\n\npublic:\n    std::size_t N;\n    std::size_t n;\n    std::size_t m;\n\n    std::vector<GroupElement> h_gens;\n    GroupElement g;\n};\n\nBOOST_FIXTURE_TEST_SUITE(lelantus_sigma_tests, SigmaExtendedTests)\n\nBOOST_AUTO_TEST_CASE(one_out_of_N_variable_batch)\n{\n    GenerateParams(64, 4);\n\n    std::size_t commit_size = 60; // require padding\n    auto commits = RandomizeGroupElements(commit_size);\n\n    // Generate\n    std::vector<Secret> secrets;\n    std::vector<std::size_t> indexes = { 0, 1, 3, 59 };\n    std::vector<std::size_t> set_sizes = { 60, 60, 59, 16 };\n    \n    for (auto index : indexes) {\n        secrets.emplace_back(index);\n\n        auto &s = secrets.back();\n\n        commits[index] = Primitives::double_commit(\n            g, s.s, h_gens[1], s.v, h_gens[0], s.r\n        );\n    }\n\n    Prover prover(g, h_gens, n, m);\n    Verifier verifier(g, h_gens, n, m);\n    std::vector<Proof> proofs;\n    std::vector<Scalar> serials;\n    std::vector<Scalar> challenges;\n\n    for (std::size_t i = 0; i < indexes.size(); i++) {\n        Scalar x;\n        x.randomize();\n        proofs.emplace_back();\n        serials.push_back(secrets[i].s);\n        std::vector<GroupElement> commits_(commits.begin() + commit_size - set_sizes[i], commits.end());\n        GenerateBatchProof(\n            prover,\n            commits_,\n            secrets[i].l - (commit_size - set_sizes[i]),\n            secrets[i].s,\n            secrets[i].v,\n            secrets[i].r,\n            x,\n            proofs.back()\n        );\n        challenges.emplace_back(x);\n\n        // Verify individual proofs as a sanity check\n        BOOST_CHECK(verifier.singleverify(commits, x, secrets[i].s, set_sizes[i], proofs.back()));\n        BOOST_CHECK(verifier.singleverify(commits_, x, secrets[i].s, proofs.back()));\n    }\n\n    BOOST_CHECK(verifier.batchverify(commits, challenges, serials, set_sizes, proofs));\n}\n\nBOOST_AUTO_TEST_CASE(one_out_of_N_batch)\n{\n    GenerateParams(16, 4);\n\n    auto commits = RandomizeGroupElements(N);\n\n    // Generate\n    std::vector<Secret> secrets;\n\n    for (auto index : {1, 3, 5, 9, 15}) {\n        secrets.emplace_back(index);\n\n        auto &s = secrets.back();\n\n        commits[index] = Primitives::double_commit(\n            g, s.s, h_gens[1], s.v, h_gens[0], s.r);\n    }\n\n    Prover prover(g, h_gens, n, m);\n    std::vector<Proof> proofs;\n    std::vector<Scalar> serials;\n\n    Scalar x;\n    x.randomize();\n\n    for (auto const &s : secrets) {\n        proofs.emplace_back();\n        serials.push_back(s.s);\n        GenerateBatchProof(\n            prover, commits, s.l, s.s, s.v, s.r, x, proofs.back());\n    }\n\n    Verifier verifier(g, h_gens, n, m);\n    BOOST_CHECK(verifier.batchverify(commits, x, serials, proofs));\n\n    // verify subset of valid proofs should success also\n    serials.pop_back();\n    proofs.pop_back();\n    BOOST_CHECK(verifier.batchverify(commits, x, serials, proofs));\n}\n\nBOOST_AUTO_TEST_CASE(one_out_of_N_batch_with_some_invalid_proof)\n{\n    GenerateParams(16, 4);\n\n    auto commits = RandomizeGroupElements(N);\n\n    // Generate\n    std::vector<Secret> secrets;\n\n    for (auto index : {1, 3}) {\n        secrets.emplace_back(index);\n\n        auto &s = secrets.back();\n\n        commits[index] = Primitives::double_commit(\n            g, s.s, h_gens[1], s.v, h_gens[0], s.r);\n    }\n\n    Prover prover(g, h_gens, n, m);\n    std::vector<Proof> proofs;\n    std::vector<Scalar> serials;\n\n    Scalar x;\n    x.randomize();\n\n    for (auto const &s : secrets) {\n        proofs.emplace_back();\n        serials.push_back(s.s);\n        GenerateBatchProof(\n            prover, commits, s.l, s.s, s.v, s.r, x, proofs.back());\n    }\n\n    // Add an invalid\n    proofs.push_back(proofs.back());\n\n    serials.emplace_back(serials.back());\n    serials.back().randomize();\n\n    Verifier verifier(g, h_gens, n, m);\n    BOOST_CHECK(!verifier.batchverify(commits, x, serials, proofs));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n} // namespace lelantus", "meta": {"hexsha": "14ffbe5eb52544692cd545a9ebc4377a59db8213", "size": 5933, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/liblelantus/test/sigma_extended_test.cpp", "max_stars_repo_name": "arjundashrath/firo", "max_stars_repo_head_hexsha": "78e29d68b7354be702965fdd4f033709750776e5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 582.0, "max_stars_repo_stars_event_min_datetime": "2016-09-26T00:08:04.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-25T19:07:24.000Z", "max_issues_repo_path": "src/liblelantus/test/sigma_extended_test.cpp", "max_issues_repo_name": "arjundashrath/firo", "max_issues_repo_head_hexsha": "78e29d68b7354be702965fdd4f033709750776e5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 570.0, "max_issues_repo_issues_event_min_datetime": "2016-09-28T07:29:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-26T10:24:19.000Z", "max_forks_repo_path": "src/liblelantus/test/sigma_extended_test.cpp", "max_forks_repo_name": "arjundashrath/firo", "max_forks_repo_head_hexsha": "78e29d68b7354be702965fdd4f033709750776e5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 409.0, "max_forks_repo_forks_event_min_datetime": "2016-09-21T12:37:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-18T14:54:17.000Z", "avg_line_length": 24.9285714286, "max_line_length": 104, "alphanum_fraction": 0.578459464, "num_tokens": 1597, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.45238132126524383}}
{"text": "#ifndef PHD_PARTICLE_FILTER\n#define PHD_PARTICLE_FILTER\n\n#include <opencv2/core.hpp>\n#include <opencv2/highgui.hpp>\n#include <Eigen/Dense>\n#include <opencv2/core/eigen.hpp>\n\n#include \"../likelihood/gaussian.hpp\"\n#include \"../likelihood/multivariate_gaussian.hpp\"\n#include \"../utils/image_generator.hpp\"\n#include \"../utils/utils.hpp\"\n#include \"../detectors/hog_detector.hpp\"\n#include \"hungarian.h\"\n#include \"nms.hpp\"\n#include \"dpp.hpp\"\n\n#include <time.h>\n#include <float.h>\n#include <vector>\n#include <set>\n#include <iostream>\n#include <random>\n#include <chrono>\n#include <limits>\n#include <algorithm>\n\nusing namespace cv;\nusing namespace std;\nusing namespace Eigen;\n\nclass PHDGaussianMixture {\npublic:\n    int n_particles;\n   ~PHDGaussianMixture();\n    PHDGaussianMixture(bool verbose);\n    PHDGaussianMixture(bool verbose, double epsilon);\n    PHDGaussianMixture(bool verbose, double threshold, int neighbors, double min_scores_sum);\n    PHDGaussianMixture();\n    void initialize(Mat& current_frame, vector<Rect> detections,VectorXd detectionsWeights);\n    void update(Mat& image, vector<Rect> detections, VectorXd detectionsWeights);\n    void predict();\n    bool is_initialized();\n    vector<MyTarget> estimate(Mat& image, bool draw = false);\n    \nprotected:\n    mt19937 generator;\n    vector<VectorXd> theta_x;\n    bool initialized;\n    normal_distribution<double> position_random_walk, velocity_random_walk, scale_random_walk;\n    Size img_size;\n    vector<MyTarget> tracks;\n    vector<MyTarget> birth_model;\n    RNG rng;\n    set<int> labels;\n    bool verbose;\n\n    string pruning_method;\n    /* DPP parameters*/\n    double epsilon;\n\n    /* NMS parameters */\n    double threshold, min_scores_sum;\n    int neighbors;\n};\n\n#endif", "meta": {"hexsha": "db2c5e80ca17654ffd02cedbe2ec30c629457d7a", "size": 1730, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/models/phd_gaussian_mixture.hpp", "max_stars_repo_name": "fjorquerauribe/multitarget-tracking", "max_stars_repo_head_hexsha": "2ef5306f71bc1e197be0d9a7e379de1066fb815e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-08-29T13:55:40.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-11T20:49:10.000Z", "max_issues_repo_path": "src/models/phd_gaussian_mixture.hpp", "max_issues_repo_name": "fjorquerauribe/multitarget-tracking", "max_issues_repo_head_hexsha": "2ef5306f71bc1e197be0d9a7e379de1066fb815e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/models/phd_gaussian_mixture.hpp", "max_forks_repo_name": "fjorquerauribe/multitarget-tracking", "max_forks_repo_head_hexsha": "2ef5306f71bc1e197be0d9a7e379de1066fb815e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-06-01T07:00:14.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-21T05:21:04.000Z", "avg_line_length": 25.8208955224, "max_line_length": 94, "alphanum_fraction": 0.7346820809, "num_tokens": 388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.45236474437683694}}
{"text": "#include <iostream>\r\n\r\n#include <boost/array.hpp>\r\n#include <boost/numeric/odeint.hpp>\r\n\r\n#include \"Dynamics.h\"\r\n\r\nusing std::cout;\r\nusing std::endl;\r\n\r\nusing namespace boost::numeric::odeint;\r\n\r\nDynamics::Dynamics() : PI(3.14159265359), rng_(new boost::mt19937()), \r\n                       nd_(0, 1.0), var_nor(rng_, nd_),\r\n                       process_noise_(0), measurement_noise_(0)\r\n{\r\n     for (int i = 0; i < 5; i++) {\r\n          u_[i] = 0;\r\n          x0_[i] = 0;\r\n          state_[i] = 0;\r\n     }\r\n     \r\n     rng_->seed((++seed_) + time(NULL));     \r\n}\r\n\r\nstd::vector<double> Dynamics::time_vector(double t0, double dt, double tend)\r\n{\r\n     std::vector<double> tt;\r\n     for( double t = t0; t < tend ; t += dt ) {\r\n          tt.push_back(t);\r\n     }\r\n     return tt;\r\n}\r\n\r\nvoid Dynamics::set_time(double t0, double dt, double tend)\r\n{\r\n     t0_ = t0;\r\n     dt_ = dt;\r\n     tend_ = tend;\r\n\r\n     tt_.clear();\r\n     for( double t = t0_ ; t < tend_ ; t += dt_ ) {\r\n          tt_.push_back(t);\r\n     }\r\n}\r\n\r\nvoid Dynamics::set_x0(state_5d_type x0)\r\n{\r\n     for(int i = 0; i < 5; i++) {\r\n          x0_[i] = x0[i];          \r\n          state_[i] = x0[i];\r\n          measurement_[i] = 0;\r\n     }\r\n     \r\n     measurement_[0] = x0[0] + var_nor() * measurement_noise_;\r\n     measurement_[1] = x0[1] + var_nor() * measurement_noise_;\r\n}\r\n\r\nvoid Dynamics::compute_trajectory()\r\n{\r\n     headings_.clear();\r\n     truth_points_.clear();\r\n\r\n     if (model_ == cart || model_ == roomba) { \r\n          state_5d_type x = {x0_[0], x0_[1], x0_[2], x0_[3], x0_[4]};     \r\n          runge_kutta4< state_5d_type > stepper;     \r\n          \r\n          std::vector<double>::iterator it = tt_.begin();\r\n          for (; it != tt_.end(); it++) {\r\n               cv::Point2d truth, measured;\r\n               \r\n               truth = cv::Point2d(x[0], x[1]);\r\n               \r\n               measured.x = truth.x + var_nor() * measurement_noise_;\r\n               measured.y = truth.y + var_nor() * measurement_noise_;\r\n               \r\n               headings_.push_back(x[2]*180.0/PI);\r\n               truth_points_.push_back(truth);\r\n               measured_points_.push_back(measured);\r\n               \r\n               state_5d_type state;\r\n               state[0] = x[0];\r\n               state[1] = x[1];\r\n               state[2] = x[2];\r\n               state[3] = 0;\r\n               state[4] = 0;\r\n               states_.push_back(state);\r\n          \r\n               if (model_ == cart) {\r\n                    stepper.do_step(make_ode_wrapper( *this , &Dynamics::cart_model ), x , *it , dt_ );\r\n               } else { \r\n                    stepper.do_step(make_ode_wrapper( *this , &Dynamics::roomba_model ), x , *it , dt_ );\r\n               }\r\n          } \r\n     } else if (model_ == constant_velocity) {\r\n     }\r\n}\r\n\r\nvoid Dynamics::step_motion_model(double dt, double time)\r\n{\r\n     if (input_sequence_.size() > 0 && input_sequence_.front().time <= time) {\r\n          cout << \"Using input: \" << endl;\r\n          for (int i = 0; i < 5; i++) {\r\n               u_[i] = input_sequence_.front().input[i];\r\n               \r\n               printf(\"%d : %f\\n\", i, u_[i]);\r\n          }\r\n          input_sequence_.erase(input_sequence_.begin());\r\n     }\r\n     \r\n     if (model_ == cart || model_ == roomba) {                          \r\n          if (model_ == cart) {\r\n               stepper_.do_step(make_ode_wrapper( *this , &Dynamics::cart_model ), state_ , 0 , dt );\r\n          } else { \r\n               stepper_.do_step(make_ode_wrapper( *this , &Dynamics::roomba_model ), state_ , 0 , dt );\r\n          }\r\n     \r\n          cv::Point2d truth, measured;               \r\n          truth = cv::Point2d(state_[0], state_[1]);\r\n               \r\n          measured.x = truth.x + var_nor() * measurement_noise_;\r\n          measured.y = truth.y + var_nor() * measurement_noise_;\r\n               \r\n          measurement_[0] = measured.x;\r\n          measurement_[1] = measured.y;\r\n          measurement_[2] = 0;\r\n          measurement_[3] = 0;\r\n          measurement_[4] = 0;\r\n          \r\n          headings_.push_back(state_[2]*180.0/PI);\r\n          truth_points_.push_back(truth);\r\n          measured_points_.push_back(measured);\r\n     \r\n     } else if (model_ == constant_velocity) {\r\n     }\r\n}\r\n\r\nvoid Dynamics::set_input(state_5d_type input)\r\n{     \r\n     input_sequence_.clear();\r\n     \r\n     ControlInput control_input;\r\n     control_input.time = 0;\r\n     for(int i = 0; i < 5; i++) {\r\n          control_input.input[i] = input[i];\r\n     }          \r\n     \r\n     input_sequence_.push_back(control_input);          \r\n}\r\n\r\nvoid Dynamics::set_input(state_5d_type input, double time)\r\n{\r\n     ControlInput control_input;\r\n     control_input.time = time;\r\n     for(int i = 0; i < 5; i++) {\r\n          control_input.input[i] = input[i];\r\n     }          \r\n     \r\n     input_sequence_.push_back(control_input);          \r\n}\r\n\r\nvoid Dynamics::set_input_sequence(std::vector<ControlInput> &input_sequence)\r\n{\r\n     input_sequence_.clear();\r\n     \r\n     for (std::vector<ControlInput>::iterator it = input_sequence.begin();\r\n          it != input_sequence.end(); it++) {\r\n          \r\n          ControlInput control_input;\r\n          control_input.time = it->time;\r\n          for(int i = 0; i < 5; i++) {\r\n               control_input.input[i] = it->input[i];\r\n          }          \r\n          input_sequence_.push_back(control_input);\r\n     }\r\n}\r\n\r\nvoid Dynamics::cart_model(const state_5d_type &x , state_5d_type &dxdt , double t)\r\n{\r\n     /// 0 : x-position\r\n     /// 1 : y-position\r\n     /// 2 : theta\r\n\t  \r\n     //u_[0] = 2;\r\n     //u_[1] = 3.14159265359/20;     \r\n     \r\n     double u = u_[0];\r\n     double u_theta = u_[1];\r\n     double L = 3;\r\n     \r\n     dxdt[0] = u*cos(x[2]) + var_nor() * process_noise_; \r\n     dxdt[1] = u*sin(x[2]) + var_nor() * process_noise_; \r\n     dxdt[2] = u/L*tan(u_theta) + var_nor() * process_noise_;\r\n     dxdt[3] = 0;\r\n     dxdt[4] = 0;\r\n}\r\n\r\nvoid Dynamics::roomba_model(const state_5d_type &x , state_5d_type &dxdt , double t)\r\n{\r\n     /// 0 : x-position\r\n     /// 1 : y-position\r\n     /// 2 : theta\r\n\r\n     double R = 1;\r\n     double b = 0.5;\r\n\t\r\n     double w_l = u_[0];\r\n     double w_r = u_[1];     \r\n     \r\n     dxdt[0] = R*cos(x[2])*(w_r + w_l)/2;\r\n     dxdt[1] = R*sin(x[2])*(w_r + w_l)/2;\r\n     dxdt[2] = R*(w_r-w_l)/(2*b);\r\n     dxdt[3] = 0;\r\n     dxdt[4] = 0;\r\n}\r\n\r\n\r\n//void Dynamics::aircraft_6DOF_model(const state_type &x , state_type &dxdt , double t)\r\n//{\r\n//     /// 0:  u     : surge velocity\r\n//     /// 1:  v     : sway velocity\r\n//     /// 2:  w     : heave velocity\r\n//     /// 3:  p     : roll rate\r\n//     /// 4:  q     : pitch rate\r\n//     /// 5:  r     : yaw rate\r\n//     /// 6:  xpos  : earth x-pos\r\n//     /// 7:  ypos  : earth y-pos\r\n//     /// 8:  zpos  : earth z-pos\r\n//     /// 9:  phi   : roll angle\r\n//     /// 10: theta : pitch angle\r\n//     /// 11: psi   : yaw angle\r\n//              \r\n//     // Get current state values\r\n//     double u     = x[0];\r\n//     double v     = x[1];\r\n//     double w     = x[2];\r\n//     double p     = x[3];\r\n//     double q     = x[4];\r\n//     double r     = x[5];\r\n//     //double xpos  = x[6];\r\n//     //double ypos  = x[7];\r\n//     //double zpos  = x[8];\r\n//     double phi   = (x[9]);\r\n//     double theta = (x[10]);     \r\n//     double psi   = (x[11]);\r\n//     \r\n//     // Precalculate trig functions\r\n//     double c1 = cos(phi);\r\n//     double c2 = cos(theta); \r\n//     double c3 = cos(psi); \r\n//     double s1 = sin(phi); \r\n//     double s2 = sin(theta); \r\n//     double s3 = sin(psi); \r\n//     double t2 = tan(theta);\r\n//\r\n//     //double m = 4536; // mass\r\n//     double m = 1;\r\n//\r\n//     // Thrust is in surge direction\r\n//     \r\n//     // Force Inputs\r\n//     double Fx = u_[0];  \r\n//     double Fy = 0;\r\n//     double Fz = 0;\r\n//     double Fk = u_[1]; // roll\r\n//     double Fm = u_[2]; // pitch\r\n//     double Fn = 0; // yaw     \r\n//\r\n//     // For x-z symmetry:\r\n//     // 1.) Ixy = Iyx = 0\r\n//     // 2.) Iyz = Izy = 0\r\n//     //double Ixx = 23;\r\n//     //double Ixy = 0;\r\n//     //double Ixz = 2.97;\r\n//     //double Iyy = 15.13;\r\n//     //double Iyz = 0;\r\n//     //double Izz = 16.99;\r\n//\r\n//     double Ixx = 1;\r\n//     double Ixy = 0;\r\n//     double Ixz = 0;\r\n//     double Iyy = 1;\r\n//     double Iyz = 0;\r\n//     double Izz = 1;\r\n//\r\n//     //double Ixx = 35926.5;\r\n//     //double Ixy = 0;\r\n//     //double Ixz = 3418.17;\r\n//     //double Iyy = 33940.7;\r\n//     //double Iyz = 0;\r\n//     //double Izz = 67085.5;\r\n//\r\n//     // Calculate Translational Forces\r\n//     double X = Fx - m*q*w + m*r*v;\r\n//     double Y = Fy - m*r*u + m*p*w;\r\n//     double Z = Fz - m*p*v + m*q*u;\r\n//\r\n//     // Calculate Rotational Forces\r\n//     double K = Fk + Iyz*(pow(q,2)-pow(r,2)) + Ixz*p*q - Ixy*r*p + (Iyy-Izz)*q*r;\r\n//     double M = Fm + Ixz*(pow(r,2)-pow(p,2)) + Ixy*q*r - Iyz*p*q + (Izz-Ixx)*r*p;\r\n//     double N = Fn + Ixy*(pow(p,2)-pow(q,2)) + Iyz*r*p - Ixz*q*r + (Ixx-Iyy)*p*q;\r\n//\r\n//     // Calculate angles\r\n//     double P = p + (q*s1 + r*c1)*t2;\r\n//     double Q = q*c1 - r*s1;\r\n//     double R = (q*s1 + r*c1)*1.0/c2;\r\n//     \r\n//     // Calculate Velocities and Rates\r\n//     // xdot(1:6) = inv(A)*[X Y Z K M N]'\r\n//     Eigen::MatrixXd A, Forces, derivs;\r\n//     A.resize(9,9); Forces.resize(9,1);\r\n//     \r\n//     A << m, 0, 0,   0,    0,    0,  0, 0, 0,\r\n//          0, m, 0,   0,    0,    0,  0, 0, 0,\r\n//          0, 0, m,   0,    0,    0,  0, 0, 0,\r\n//          0, 0, 0,  Ixx, -Ixy, -Ixz, 0, 0, 0,\r\n//          0, 0, 0, -Ixy,  Iyy, -Iyz, 0, 0, 0,\r\n//          0, 0, 0, -Ixz, -Iyz,  Izz, 0, 0, 0,\r\n//          0, 0, 0,   0,    0,    0,  1, 0, 0,\r\n//          0, 0, 0,   0,    0,    0,  0, 1, 0,\r\n//          0, 0, 0,   0,    0,    0,  0, 0, 1;\r\n//          \r\n//\r\n//     Forces << X, Y, Z, K, M, N, P, Q, R;\r\n//\r\n//     derivs = A.inverse() * Forces;         \r\n//     \r\n//     dxdt[0] = derivs(0,0);\r\n//     dxdt[1] = derivs(1,0);\r\n//     dxdt[2] = derivs(2,0);\r\n//     dxdt[3] = derivs(3,0);\r\n//     dxdt[4] = derivs(4,0);\r\n//     dxdt[5] = derivs(5,0);\r\n//     \r\n//     // Calculate Positions\r\n//     dxdt[6] = c3*c2*u + (c3*s2*s1-s3*c1)*v + (s3*s1+c3*c1*s2)*w;\r\n//     dxdt[7] = s3*c2*u + (c1*c3+s1*s2*s3)*v + (c1*s2*s3-c3*s1)*w;\r\n//     dxdt[8] = -s2*u + c2*s1*v + c1*c2*w;\r\n//\r\n//     // Calculate Angles\r\n//     dxdt[9] = derivs(6,0);\r\n//     dxdt[10] = derivs(7,0);\r\n//     dxdt[11] = derivs(8,0);\r\n//}\r\n", "meta": {"hexsha": "d346a01af048d225d64282f5cf476436c6661ba3", "size": 10418, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/track/Dynamics.cpp", "max_stars_repo_name": "SyllogismRXS/opencv-workbench", "max_stars_repo_head_hexsha": "2fb5b0d67589642d438f21f1cf58aaa761d15757", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2015-10-05T04:33:31.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-20T02:47:36.000Z", "max_issues_repo_path": "src/track/Dynamics.cpp", "max_issues_repo_name": "SyllogismRXS/opencv-workbench", "max_issues_repo_head_hexsha": "2fb5b0d67589642d438f21f1cf58aaa761d15757", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/track/Dynamics.cpp", "max_forks_repo_name": "SyllogismRXS/opencv-workbench", "max_forks_repo_head_hexsha": "2fb5b0d67589642d438f21f1cf58aaa761d15757", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2015-07-18T16:01:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-28T11:56:02.000Z", "avg_line_length": 30.1971014493, "max_line_length": 106, "alphanum_fraction": 0.4527740449, "num_tokens": 3384, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.45236474437683694}}
{"text": "#include <boost/assert.hpp>\n#include <cmath>\n#include <limits>\n#include <utility>\n\n#include \"mh_moves/mh_moves.hpp\"\n#include \"mh_moves/mh_move_weights.hpp\"\n#include \"sampling/simple.hpp\"\n#include \"mh_moves/utility.hpp\"\n\nnamespace biggles {\n\nnamespace mh_moves\n{\n\n/// \\brief get the probability that pieces are merged given tracks (which contains pieces)\nfloat get_log_merge_prob(const partition_ptr_t &end_partition, const shared_const_track_ptr &front_piece,\n    const shared_const_track_ptr &back_piece)\n{\n    const track_collection &tracks = end_partition->tracks();\n    BOOST_ASSERT(tracks.contains(front_piece));\n    BOOST_ASSERT(tracks.contains(back_piece));\n    BOOST_ASSERT(tracks_could_be_merged2(*front_piece, *back_piece)>0.f);\n    front_weight_merging fw(end_partition->first_time_stamp(), end_partition->last_time_stamp());\n    float front_piece_weight = fw(front_piece);\n    float total_weight = fun_sum(tracks.begin(), tracks.end(), fw, 0.f);\n    float log_front_piece_prob = std::log(front_piece_weight) - std::log(total_weight);\n    back_weight_merging bw(front_piece);\n    float back_piece_weight = bw(back_piece);\n    BOOST_ASSERT(back_piece_weight > 0);\n    total_weight = fun_sum(tracks.begin(), tracks.end(), bw, 0.f);\n    float log_back_piece_prob = std::log(back_piece_weight) - std::log(total_weight);\n    return log_front_piece_prob + log_back_piece_prob;\n}\n\nbool split(const partition_ptr_t& start_partition_ptr, partition_ptr_t& end_partition, float& proposal_density_ratio)\n{\n    const track_collection& tracks(start_partition_ptr->tracks());\n\n    capability_recorder_ptr cap_rec_ptr = start_partition_ptr->get_capability_recorder();\n    BOOST_ASSERT(cap_rec_ptr.get() not_eq 0); // there actually is something assigned\n\n    // early-out: there must be at least one track\n    if(tracks.empty())\n        return false;\n\n    // choose a track to split\n    float log_track_prob(1.f);\n    /*\n    track_collection::const_iterator track_it(sample_track_with_minimum_size(tracks, 4, log_track_prob));\n    if(track_it == tracks.end())\n        return false;\n\n    // check we found one\n    BOOST_ASSERT(track_it != tracks.end());\n    BOOST_ASSERT((*track_it)->size() >= 4);\n    BOOST_ASSERT(log_track_prob <= 0.f);\n    const shared_const_track_ptr& track_to_split(*track_it);\n        */\n    shared_const_track_ptr track_to_split;\n    if (not select_track(split_weight_t(), tracks, track_to_split, log_track_prob)) {\n        return false;\n    }\n\n    // choose a splitting point\n    time_stamp ts_to_split_at(0);\n    float log_ts_prob(1.f);\n    // IMPORTANT: BOOST_VERIFY will still evaluate its argument even when not in debug mode\n    BOOST_VERIFY(sample_time_stamp_to_split_track(track_to_split, ts_to_split_at, log_ts_prob));\n    BOOST_ASSERT(log_ts_prob <= 0.f);\n\n    // create new tracks\n    float log_splitting_prob = 0.f; // due to noobs at the splitting end of the new tracks\n    shared_const_track_ptr_pair new_track_pair(\n        split_track_at_time_stamp(track_to_split, ts_to_split_at, log_splitting_prob));\n\n    // sanity check tracks\n    BOOST_ASSERT(new_track_pair.first->size() + new_track_pair.second->size() == track_to_split->size());\n    BOOST_ASSERT(new_track_pair.first->size() >= 2);\n    BOOST_ASSERT(new_track_pair.second->size() >= 2);\n    BOOST_ASSERT(new_track_pair.first->last_time_stamp() <= new_track_pair.second->first_time_stamp());\n    BOOST_ASSERT(tracks_could_be_merged(*new_track_pair.first, *new_track_pair.second));\n\n    // create copies of the tracks. The clutter is unaffected\n    shared_track_collection_ptr new_tracks(new track_collection(tracks));\n\n\n    cap_rec_ptr->add_erase_track(track_to_split);\n    cap_rec_ptr->add_insert_track(new_track_pair.first);\n    cap_rec_ptr->add_insert_track(new_track_pair.second);\n    cap_rec_ptr->set_editing_finished();\n\n    // remove the track from the collection\n    new_tracks->remove(track_to_split);\n    new_tracks->insert(new_track_pair.first);\n    new_tracks->insert(new_track_pair.second);\n\n    // update partition\n    end_partition = partition_ptr_t(\n        new partition(start_partition_ptr->pool(), new_tracks, start_partition_ptr->clutter_ptr(), start_partition_ptr->expansion())\n        );\n    end_partition->set_first_time_stamp(start_partition_ptr->first_time_stamp());\n    end_partition->set_last_time_stamp(start_partition_ptr->last_time_stamp());\n\n\n    // calculate forward (split) log prob.\n    float forward_log_prob = log_ts_prob + log_track_prob + log_splitting_prob;\n\n    float backward_log_prob = get_log_merge_prob(end_partition, new_track_pair.first, new_track_pair.second);\n\n    proposal_density_ratio = backward_log_prob - forward_log_prob;\n\n    return true;\n}\n\n}\n\n}\n", "meta": {"hexsha": "64134a45d1235aea7b402d87c6b3e4f1c72fa3c6", "size": 4692, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "biggles/mh_moves/move_split.cpp", "max_stars_repo_name": "fbi-octopus/biggles", "max_stars_repo_head_hexsha": "2dac4f1748ab87242951239caf274f302be1143a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-15T14:01:59.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-15T14:01:59.000Z", "max_issues_repo_path": "biggles/mh_moves/move_split.cpp", "max_issues_repo_name": "fbi-octopus/biggles", "max_issues_repo_head_hexsha": "2dac4f1748ab87242951239caf274f302be1143a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "biggles/mh_moves/move_split.cpp", "max_forks_repo_name": "fbi-octopus/biggles", "max_forks_repo_head_hexsha": "2dac4f1748ab87242951239caf274f302be1143a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.4285714286, "max_line_length": 132, "alphanum_fraction": 0.7502131287, "num_tokens": 1055, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585669110202, "lm_q2_score": 0.6187804337438502, "lm_q1q2_score": 0.45236473712535863}}
{"text": "/***********************************************************************\n *                      Kuramoto oscillators                           *\n *             Copyright (c) 2014-2015 Alex Khrabrov                   *\n ***********************************************************************\n * This program is free software. It comes without any warranty, to    *\n * the extent permitted by applicable law. You can redistribute it     *\n * and/or modify it under the terms of the Do What The Fuck You Want   *\n * To Public License, Version 2, as published by Sam Hocevar. See      *\n * license text below.                                                 *\n ***********************************************************************\n *                                                                     *\n *            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE              *\n *                    Version 2, December 2004                         *\n *                                                                     *\n * Copyright (C) 2004 Sam Hocevar <sam@hocevar.net>                    *\n *                                                                     *\n * Everyone is permitted to copy and distribute verbatim or modified   *\n * copies of this license document, and changing it is allowed as long *\n * as the name is changed.                                             *\n *                                                                     *\n *            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE              *\n *   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION   *\n *                                                                     *\n *  0. You just DO WHAT THE FUCK YOU WANT TO.                          *\n *                                                                     *\n ***********************************************************************/\n\ntypedef double fp_type;\n\n#define _USE_MATH_DEFINES\n#include <cmath>\nstatic const fp_type TWO_PI = 2.0 * M_PI;\n#undef _USE_MATH_DEFINES\n\n#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <string>\n#include <map>\n#include <random>\n#include <algorithm>\n#include <numeric>\n\n#include <cassert>\n#include <cstdint>\n#include <cstdlib>\n\n#include <boost/filesystem.hpp>\n#include <boost/program_options.hpp>\n\n#if defined(WIN32) || defined(_WIN32)\n#define PATH_SEPARATOR \"\\\\\"\n#else\n#define PATH_SEPARATOR \"/\"\n#endif\n\n#ifdef _MSC_VER\n#define FORCE_INLINE __forceinline\n#else\n#define FORCE_INLINE inline\n#endif\n\n//--------------------------------------------------------------------------------------------------\n\ntemplate<typename T>\nFORCE_INLINE T mean(const std::vector<T> & v)\n{\n    const auto size = v.size();\n    assert(size != 0);\n    T sum(0);\n    for(typename std::vector<T>::size_type i = 0; i < size; i++)\n        sum += v[i];\n    return sum / T(size);\n}\n\nstatic std::vector<fp_type> tmp_s;\nstatic std::vector<fp_type> tmp_c;\n\ntemplate<typename T>\nT calc_order_parameter(const std::vector<T> & phases)\n{\n    using namespace std;\n    const auto size = phases.size();\n    tmp_s.resize(size);\n    tmp_c.resize(size);\n    for(typename std::vector<T>::size_type i = 0; i < size; i++)\n    {\n        const T p = phases[i];\n        tmp_s[i] = sin(p);\n        tmp_c[i] = cos(p);\n    }\n    const T mean_sin = mean(tmp_s);\n    const T mean_cos = mean(tmp_c);\n    return sqrt(mean_cos * mean_cos + mean_sin * mean_sin);\n}\n\ntemplate<typename T>\nFORCE_INLINE T rand_range(T min, T max)\n{\n    assert(max > min);\n    return ((T(rand()) / T(RAND_MAX)) * (max - min)) + min;\n}\n\n//--------------------------------------------------------------------------------------------------\n\ntemplate<typename T>\nFORCE_INLINE T wrap_phase_1(T p)\n{\n    if(p > T(TWO_PI))\n        p -= T(TWO_PI);\n    else if(p < 0.0)\n        p += T(TWO_PI);\n    return p;\n}\n\ntemplate<typename T>\nFORCE_INLINE T wrap_phase_2(T p)\n{\n    while(p < 0.0 || p > T(TWO_PI))\n    {\n        if(p > T(TWO_PI))\n            p -= T(TWO_PI);\n        else if(p < 0.0)\n            p += T(TWO_PI);\n    }\n}\n\n//--------------------------------------------------------------------------------------------------\n\ntemplate<typename T>\nFORCE_INLINE T kuramoto_classic(const T phi)\n{\n    return std::sin(phi);\n}\n\ntemplate<int n, typename T>\nFORCE_INLINE T kuramoto_n(const T phi)\n{\n    return std::sin(T(n) * phi);\n}\n\ntemplate<typename T>\nFORCE_INLINE T daido_original(const T phi)\n{\n    return std::sin(phi) +\n        T(0.2) * std::cos(phi) -\n        T(0.3) * std::sin(T(2.0) * phi) +\n        T(0.6) * std::cos(T(2.0) * phi) +\n        T(0.7) * std::sin(T(3.0) * phi) -\n        T(0.4) * std::cos(T(3.0) * phi);\n}\n\ntemplate<typename T>\nFORCE_INLINE T coupling_1(const T phi)\n{\n    return std::sin(phi) + std::sin(T(3.0) * phi);\n}\n\ntemplate<typename T>\nFORCE_INLINE T coupling_2(const T phi)\n{\n    return std::sin(phi) +\n           std::sin(T(3.0) * phi) +\n           std::sin(T(6.0) * phi);\n}\n\ntemplate<typename T>\nFORCE_INLINE T coupling_3(const T phi)\n{\n    return std::sin(phi) + std::cos(T(3.0) * phi);\n}\n\ntemplate<typename T>\nFORCE_INLINE T coupling_4(const T phi)\n{\n    return std::cos(phi) + std::cos(T(3.0) * phi);\n}\n\n//--------------------------------------------------------------------------------------------------\n\ntemplate<typename T>\nvoid write_vector(std::ostream & os, const std::vector<T> & vec)\n{\n    for(const auto x : vec)\n        os << x << ' ';\n}\n\ntemplate<typename T>\nvoid dump_state\n(\n    const std::string & out_file_name,\n    const std::vector<T> & phase,\n    const std::vector<T> & vel,\n    const unsigned int step,\n    const unsigned int N,\n    const T r,\n    const T mean_phase\n)\n{\n    using namespace std;\n    ofstream out(out_file_name, ofstream::trunc);\n    out << step << ' ' << N << ' ' << r << ' ' << mean_phase << '\\n';\n    write_vector(out, phase);\n    out << '\\n';\n    write_vector(out, vel);\n}\n\ntemplate<typename T, T(*H)(T)>\nvoid run_simulation\n(\n    const bool quiet,                    // if true produce no output to console\n\n    const unsigned int N,                // number of oscillators\n    const unsigned int N_steps,          // simulations steps\n\n    const T dt,                          // time step\n\n    std::vector<T> phase,                // initial phases\n    const std::vector<T> freq,           // oscillator's frequencies\n    const std::vector<T> k,              // coupling matrix\n\n    const std::string & name,            // current working set name\n\n    const T noise,                       // noise amplitude\n\n    const T forcing_strength,            // when != 0 all oscillators are forced by external field\n    const T forcing_freq,                // external forcing frequency\n\n    const unsigned int dump_interval,    // how often to dump frame snapshots\n\n    const bool r_history_enabled,        // write r values to file\n    const bool mean_history_enabled,     // write mean values to file\n    const bool mean_vel_history_enabled, // write mean velocity values to file\n\n    const bool freq_modulation_enabled,  // is oscillator frequency modulation enabled\n    const std::vector<T> freq_ampl,      // frequency modulation amplitude\n    const std::vector<T> freq_freq,      // frequency modulation frequency\n    const std::vector<T> freq_offset,    // frequency modulation offset\n\n    const bool k_modulation_enabled,     // is coupling coefficient modulation enabled\n    const std::vector<T> k_ampl,         // coupling coefficient modulation amplitude\n    const std::vector<T> k_freq,         // coupling coefficient modulation frequency\n    const std::vector<T> k_offset,       // coupling coefficient modulation offset\n\n    const std::string & out_dir_name,      // MUST end with directory separator (/ or \\)\n    const std::string & r_file_path,       // if specified r history will be written to this file\n    const std::string & mean_file_path,    // if specified mean phase will be written to this file\n    const std::string & mean_vel_file_path // if specified mean velocity will be written to this file\n)\n{\n    using namespace std;\n\n    assert(N > 0 && dt > 0 && phase.size() == N && freq.size() == N && k.size() == N*N);\n    assert(freq_modulation_enabled ? (freq_ampl.size() == N && freq_freq.size() == N && freq_offset.size() == N) : true);\n    assert(k_modulation_enabled ? (k_ampl.size() == N && k_freq.size() == N*N && k_offset.size() == N*N) : true);\n\n    const T two_dt = T(2.0) * dt;\n\n    const bool add_noise = (noise != 0.0);\n    const bool forcing_enabled = (forcing_strength != 0.0);\n    const bool dump_enabled = (dump_interval != 0);\n\n    // collect global statistics during simulation\n    vector<T> r_hist(N_steps);\n    vector<T> mean_hist(N_steps);\n    vector<T> mean_vel_hist(N_steps);\n\n    vector<T> phase_old = phase;\n    vector<T> phase_old_old = phase;\n\n    vector<T> vel(N);\n\n    unsigned int dump_counter = 0;\n\n    for(unsigned int step = 0; step < N_steps; step++)\n    {\n        const T t = T(step) * dt;\n        for(unsigned int i = 0; i < N; i++)\n        {\n            T f;\n            if(!freq_modulation_enabled)\n                f = freq[i];\n            else\n                f = freq[i] + freq_ampl[i] * sin(T(TWO_PI) * freq_freq[i] * t + freq_offset[i]);\n\n            // NOTE: k[i*N + j] can be interpreted as k[i][j]\n            if(!k_modulation_enabled)\n            {\n                const unsigned int offset = i * N;\n                const T phase_old_i = phase_old[i];\n                for(unsigned int j = 0; j < N; j++)\n                    f += k[offset + j] * H(phase_old[j] - phase_old_i);\n            }\n            else\n            {\n                const unsigned int offset = i * N;\n                const T phase_old_i = phase_old[i];\n                for(unsigned int j = 0; j < N; j++)\n                {\n                    const unsigned int idx = offset + j;\n                    f += (k[idx] + k_ampl[i] * sin(T(TWO_PI) * k_freq[idx] * t + k_offset[idx]))\n                        * H(phase_old[j] - phase_old_i);\n                }\n            }\n\n            if(forcing_enabled)\n                f += forcing_strength * sin(forcing_freq * t - phase_old[i]);\n\n            if(add_noise)\n                f += rand_range<T>(-noise, noise);\n\n            // calculate new phase\n            const T p = phase_old[i] + f * dt;\n            phase[i] = wrap_phase_1(p);\n        }\n\n        for(unsigned int i = 0; i < N; i++)\n            vel[i] = (phase[i] - phase_old_old[i]) / two_dt;\n\n        const T r = calc_order_parameter(phase);\n        r_hist[step] = r;\n\n        const T mean_phase = mean(phase);\n        mean_hist[step] = mean_phase;\n\n        mean_vel_hist[step] = mean(vel);\n\n        if(dump_enabled)\n        {\n            if(dump_counter == 0)\n            {\n                dump_counter = dump_interval;\n                const string out_file_name(out_dir_name + to_string(step) + \".txt\");\n                if(!quiet)\n                    cout << \"Saving at step: \" << step << endl;\n                dump_state(out_file_name, phase, vel, step, N, r, mean_phase);\n            }\n            dump_counter--;\n        }\n        else if(!(step % 100))\n            if(!quiet)\n                cout << \"Step: \" << step << endl;\n\n        phase_old_old = phase_old;\n        phase_old = phase;\n    }\n\n    if(r_history_enabled)\n    {\n        ofstream r_out(r_file_path, ofstream::trunc);\n        write_vector(r_out, r_hist);\n    }\n\n    if(mean_history_enabled)\n    {\n        ofstream mean_out(mean_file_path, ofstream::trunc);\n        write_vector(mean_out, mean_hist);            \n    }\n\n    if(mean_vel_history_enabled)\n    {\n        ofstream mean_vel_out(mean_vel_file_path, ofstream::trunc);\n        write_vector(mean_vel_out, mean_vel_hist);            \n    }\n}\n\nvoid read_preset(std::ifstream & input,\n                 unsigned int & N,\n                 std::vector<double> & freq,\n                 std::vector<double> & phase,\n                 std::vector<double> & k)\n{\n    using namespace std;\n\n    uint32_t N_;\n    input.read(reinterpret_cast<char*>(&N_), sizeof(N_));\n    N = N_;\n\n    freq.resize(N);\n    phase.resize(N);\n    k.resize(N*N);\n\n    input.read(reinterpret_cast<char*>(freq.data()), N*sizeof(double));\n    input.read(reinterpret_cast<char*>(phase.data()), N*sizeof(double));\n    input.read(reinterpret_cast<char*>(k.data()), N*N*sizeof(double));\n}\n\nvoid read_freq_modulation_data(std::ifstream & input,\n                               unsigned int N,\n                               std::vector<double> & freq_ampl,\n                               std::vector<double> & freq_freq,\n                               std::vector<double> & freq_offset)\n{\n    using namespace std;\n\n    freq_ampl.resize(N);\n    freq_freq.resize(N);\n    freq_offset.resize(N);\n\n    input.read(reinterpret_cast<char*>(freq_ampl.data()), N*sizeof(double));\n    input.read(reinterpret_cast<char*>(freq_freq.data()), N*sizeof(double));\n    input.read(reinterpret_cast<char*>(freq_offset.data()), N*sizeof(double));\n}\n\nvoid read_k_modulation_data(std::ifstream & input,\n                            unsigned int N,\n                            std::vector<double> & k_ampl,\n                            std::vector<double> & k_freq,\n                            std::vector<double> & k_offset)\n{\n    using namespace std;\n\n    k_ampl.resize(N);\n    k_freq.resize(N*N);\n    k_offset.resize(N*N);\n\n    input.read(reinterpret_cast<char*>(k_ampl.data()), N*sizeof(double));\n    input.read(reinterpret_cast<char*>(k_freq.data()), N*N*sizeof(double));\n    input.read(reinterpret_cast<char*>(k_offset.data()), N*N*sizeof(double));\n}\n\nint main(int argc, char * argv[])\n{\n    using namespace std;\n    \n    ios_base::sync_with_stdio(false);\n    \n    try\n    {\n        namespace po = boost::program_options; \n        po::options_description desc(\"Options\"); \n        desc.add_options() \n            (\"help,h\", \"print help message\")\n            (\"quiet,q\", \"produce no output to console\")\n            \n            (\"preset,p\", po::value<std::string>()->required(), \"preset name\") \n            (\"steps,s\", po::value<unsigned int>()->default_value(1000), \"simulation steps\") \n            (\"dump-interval,di\", po::value<unsigned int>()->default_value(100), \"data dump interval\") \n            (\"dt\", po::value<double>()->default_value(0.01), \"simulation time step\")\n            \n            (\"noise\", po::value<double>()->default_value(0.0), \"noise level\")\n            \n            (\"coupling,c\", po::value<std::string>()->default_value(\"kuramoto\"), \"coupling type\")\n            \n            (\"forcing-strength,fs\", po::value<double>()->default_value(0.0), \"forcing strength\")\n            (\"forcing-freq,ff\", po::value<double>()->default_value(0.0), \"forcing frequency\")\n            \n            (\"enable-k-modulation\", \"enable coupling coefficient modulation\")\n            (\"enable-freq-modulation\", \"enable frequency modulation\")\n            \n            (\"r-file\", po::value<std::string>()->implicit_value(\"\"), \"r file path\")\n            (\"mean-phase-file\", po::value<std::string>()->implicit_value(\"\"), \"mean phase file path\")\n            (\"mean-vel-file\", po::value<std::string>()->implicit_value(\"\"), \"mean velocity file path\");\n\n        po::variables_map vm; \n        \n        try \n        {\n            po::store(po::parse_command_line(argc, argv, desc), vm);\n            \n            if(vm.count(\"help\"))\n            {\n                std::cout << std::endl \n                          << \"kuramoto_simulation - versatile Kuramoto simulation program\" << std::endl\n                          << std::endl \n                          << desc << std::endl; \n                return EXIT_SUCCESS;\n            }\n        }\n        catch(const po::error & e)\n        {\n            std::cerr << \"ERROR: \" << e.what() << std::endl << std::endl; \n            std::cerr << desc << std::endl; \n            return EXIT_FAILURE; \n        } \n\n        if(!vm.count(\"preset\"))\n        {\n            std::cerr << \"Preset name is required!\" << std::endl\n                      << \"Hint: use -h option to display help.\" << std::endl; \n            return EXIT_FAILURE;\n        }\n\n        const bool quiet = vm.count(\"quiet\");\n\n        const string preset_name = vm[\"preset\"].as<std::string>();\n        \n        const unsigned int N_steps = vm[\"steps\"].as<unsigned int>();\n        unsigned int dump_interval = vm[\"dump-interval\"].as<unsigned int>();\n        const fp_type dt = vm[\"dt\"].as<double>();\n        const string coupling_type = vm[\"coupling\"].as<std::string>();\n\n        const fp_type noise = vm[\"noise\"].as<double>();\n        \n        const fp_type forcing_strength = vm[\"forcing-strength\"].as<double>();\n        const fp_type forcing_freq = vm[\"forcing-freq\"].as<double>();\n\n        const bool freq_modulation_enabled = vm.count(\"enable-freq-modulation\");\n        const bool k_modulation_enabled = vm.count(\"enable-k-modulation\");\n\n        unsigned int N;\n        vector<fp_type> freq;\n        vector<fp_type> phase;\n        vector<fp_type> k;\n\n        // read preset data\n        {\n            ifstream input(preset_name + \".preset\", ifstream::in | ifstream::binary);\n\n            if(!input)\n            {\n                cerr << \"Unable to open input file: \" << preset_name << \".preset\" << endl;\n                return EXIT_FAILURE;\n            }\n\n            input.exceptions(ifstream::failbit | ifstream::badbit);\n\n            read_preset(input, N, freq, phase, k);\n        }\n\n        vector<fp_type> freq_ampl;\n        vector<fp_type> freq_freq;\n        vector<fp_type> freq_offset;\n\n        vector<fp_type> k_ampl;\n        vector<fp_type> k_freq;\n        vector<fp_type> k_offset;\n\n        if(freq_modulation_enabled)\n        {\n            if(!quiet)\n                cout << \"freq_modulation_enabled\" << endl;\n            ifstream input_s(preset_name + \".fm.preset\", ifstream::in | ifstream::binary);\n            if (!input_s)\n            {\n                cerr << \"Unable to open frequency modulation data file: \" << preset_name << \".fm.preset\" << endl;\n                return EXIT_FAILURE;\n            }\n            input_s.exceptions(ifstream::failbit | ifstream::badbit);\n            read_freq_modulation_data(input_s, N, freq_ampl, freq_freq, freq_offset);\n        }\n\n        if(k_modulation_enabled)\n        {\n            if(!quiet)\n                cout << \"k_modulation_enabled\" << endl;\n            ifstream input_s(preset_name + \".km.preset\", ifstream::in | ifstream::binary);\n            if (!input_s)\n            {\n                cerr << \"Unable to open k modulation data file: \" << preset_name << \".km.preset\" << endl;\n                return EXIT_FAILURE;\n            }\n            input_s.exceptions(ifstream::failbit | ifstream::badbit);\n            read_k_modulation_data(input_s, N, k_ampl, k_freq, k_offset);\n        }\n\n        if(!quiet)\n            std::cout << \"Data loaded.\" << std::endl;\n\n        const bool r_history_enabled = vm.count(\"r-file\");\n        const bool mean_history_enabled = vm.count(\"mean-phase-file\");\n        const bool mean_vel_history_enabled = vm.count(\"mean-vel-file\");\n\n        string r_file_path;\n        string mean_file_path;\n        string mean_vel_file_path;\n\n        string out_dir_name;\n        \n        // initialize dump directory\n        if(dump_interval > 0)\n        {\n            out_dir_name = \"dump_\" + preset_name + PATH_SEPARATOR + \"steps\" + PATH_SEPARATOR;\n            // std::cout << \"Creating steps dir: \" << out_dir_name << std::endl;\n            boost::filesystem::create_directories(out_dir_name);\n        }\n\n        if(r_history_enabled)\n        {\n            r_file_path = vm[\"r-file\"].as<std::string>();\n            if(r_file_path.empty())\n                r_file_path = out_dir_name + \"r.txt\";\n            const string path_str = boost::filesystem::path(r_file_path).parent_path().string();\n            if(!path_str.empty())\n                boost::filesystem::create_directories(path_str);\n        }\n\n        if(mean_history_enabled)\n        {\n            mean_file_path = vm[\"mean-phase-file\"].as<std::string>();\n            if(mean_file_path.empty())\n                mean_file_path = out_dir_name + \"mean.txt\";\n            const string path_str = boost::filesystem::path(mean_file_path).parent_path().string();\n            if(!path_str.empty())\n                boost::filesystem::create_directories(path_str);\n        }\n\n        if(mean_vel_history_enabled)\n        {\n            mean_vel_file_path = vm[\"mean-vel-file\"].as<std::string>();\n            if(mean_vel_file_path.empty())\n                mean_vel_file_path = out_dir_name + \"mean_vel.txt\";\n            const string path_str = boost::filesystem::path(mean_vel_file_path).parent_path().string();\n            if(!path_str.empty())\n                boost::filesystem::create_directories(path_str);\n        }\n\n        //std::cout << \"r_file_path: \" << r_file_path << std::endl;\n        //std::cout << \"mean_file_path: \" << mean_file_path << std::endl;\n        //std::cout << \"mean_vel_file_path: \" << mean_vel_file_path << std::endl;\n\n#define RUN_SIMUL(coupling)                  \\\n        run_simulation<fp_type, coupling>(   \\\n            quiet,                           \\\n            N, N_steps, dt,                  \\\n            phase, freq, k, preset_name,     \\\n            noise,                           \\\n            forcing_strength, forcing_freq,  \\\n            dump_interval,                   \\\n            r_history_enabled,               \\\n            mean_history_enabled,            \\\n            mean_vel_history_enabled,        \\\n            freq_modulation_enabled,         \\\n            freq_ampl,                       \\\n            freq_freq,                       \\\n            freq_offset,                     \\\n            k_modulation_enabled,            \\\n            k_ampl,                          \\\n            k_freq,                          \\\n            k_offset,                        \\\n            out_dir_name,                    \\\n            r_file_path,                     \\\n            mean_file_path,                  \\\n            mean_vel_file_path               \\\n        )\n\n        if(coupling_type == \"kuramoto\")\n            RUN_SIMUL(kuramoto_classic);\n        else if(coupling_type == \"kuramoto_2\")\n            RUN_SIMUL(kuramoto_n<2>);\n    \telse if(coupling_type == \"kuramoto_3\")\n    \t\tRUN_SIMUL(kuramoto_n<3>);\n    \telse if(coupling_type == \"kuramoto_4\")\n    \t\tRUN_SIMUL(kuramoto_n<4>);\n    \telse if(coupling_type == \"kuramoto_5\")\n    \t\tRUN_SIMUL(kuramoto_n<5>);\n    \telse if(coupling_type == \"kuramoto_6\")\n    \t\tRUN_SIMUL(kuramoto_n<6>);\n    \telse if(coupling_type == \"kuramoto_7\")\n    \t\tRUN_SIMUL(kuramoto_n<7>);\n    \telse if(coupling_type == \"kuramoto_8\")\n    \t\tRUN_SIMUL(kuramoto_n<8>);\n    \telse if(coupling_type == \"kuramoto_9\")\n    \t\tRUN_SIMUL(kuramoto_n<9>);\n    \telse if(coupling_type == \"kuramoto_10\")\n    \t\tRUN_SIMUL(kuramoto_n<10>);\n    \telse if(coupling_type == \"daido\")\n            RUN_SIMUL(daido_original);\n        else if(coupling_type == \"coupling_1\")\n            RUN_SIMUL(coupling_1);\n        else if(coupling_type == \"coupling_2\")\n            RUN_SIMUL(coupling_2);\n        else if(coupling_type == \"coupling_3\")\n            RUN_SIMUL(coupling_3);\n        else if(coupling_type == \"coupling_4\")\n            RUN_SIMUL(coupling_4);\n        else\n        {\n            std::cerr << \"Unknown coupling type: \" << coupling_type << std::endl;\n            return EXIT_FAILURE;\n        }\n    }\n    catch(std::exception& e) \n    { \n        std::cerr << \"Unhandled Exception reached the top of main: \" \n                  << e.what() << \", application will now exit.\" << std::endl; \n        return EXIT_FAILURE;\n    } \n\n    return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "a83c333552cb16a2ae12bdf163d6328ec5dcb140", "size": 23650, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kuramoto_simulation.cpp", "max_stars_repo_name": "mroja/kuramoto", "max_stars_repo_head_hexsha": "9957ae1cf09e0c463a2c3ba3e2421b6628caa27c", "max_stars_repo_licenses": ["WTFPL"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-02-02T21:32:30.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-02T21:32:30.000Z", "max_issues_repo_path": "kuramoto_simulation.cpp", "max_issues_repo_name": "mroja/kuramoto", "max_issues_repo_head_hexsha": "9957ae1cf09e0c463a2c3ba3e2421b6628caa27c", "max_issues_repo_licenses": ["WTFPL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kuramoto_simulation.cpp", "max_forks_repo_name": "mroja/kuramoto", "max_forks_repo_head_hexsha": "9957ae1cf09e0c463a2c3ba3e2421b6628caa27c", "max_forks_repo_licenses": ["WTFPL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.6774193548, "max_line_length": 121, "alphanum_fraction": 0.5233826638, "num_tokens": 5311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585669110202, "lm_q2_score": 0.6187804196836383, "lm_q1q2_score": 0.45236472684652024}}
{"text": "//  Copyright John Maddock 2008.\r\n//  Use, modification and distribution are subject to the\r\n//  Boost Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n//\r\n// Basic sanity check that header <boost/math/tr1.hpp>\r\n// #includes all the files that it needs to.\r\n//\r\n#include <boost/math/tr1.hpp>\r\n//\r\n// Note this header includes no other headers, this is\r\n// important if this test is to be meaningful:\r\n//\r\n#include \"test_compile_result.hpp\"\r\n\r\nvoid compile_and_link_test()\r\n{\r\n   unsigned ui = 0;\r\n\r\n   check_result<float>(boost::math::tr1::assoc_laguerre(ui, ui, f));\r\n   check_result<float>(boost::math::tr1::assoc_laguerref(ui, ui, f));\r\n   check_result<double>(boost::math::tr1::assoc_laguerre(ui, ui, d));\r\n   check_result<long double>(boost::math::tr1::assoc_laguerre(ui, ui, l));\r\n   check_result<long double>(boost::math::tr1::assoc_laguerrel(ui, ui, l));\r\n   check_result<double>(boost::math::tr1::assoc_laguerre(ui, ui, i));\r\n   check_result<double>(boost::math::tr1::assoc_laguerre(ui, ui, ui));\r\n\r\n   check_result<float>(boost::math::tr1::assoc_legendre(ui, ui, f));\r\n   check_result<float>(boost::math::tr1::assoc_legendref(ui, ui, f));\r\n   check_result<double>(boost::math::tr1::assoc_legendre(ui, ui, d));\r\n   check_result<long double>(boost::math::tr1::assoc_legendre(ui, ui, l));\r\n   check_result<long double>(boost::math::tr1::assoc_legendrel(ui, ui, l));\r\n   check_result<double>(boost::math::tr1::assoc_legendre(ui, ui, i));\r\n   check_result<double>(boost::math::tr1::assoc_legendre(ui, ui, ui));\r\n\r\n   check_result<float>(boost::math::tr1::beta(f, f));\r\n   check_result<float>(boost::math::tr1::betaf(f, f));\r\n   check_result<double>(boost::math::tr1::beta(d, d));\r\n   check_result<long double>(boost::math::tr1::beta(l, l));\r\n   check_result<long double>(boost::math::tr1::betal(l, l));\r\n   check_result<double>(boost::math::tr1::beta(ui, ui));\r\n   check_result<double>(boost::math::tr1::beta(i, ui));\r\n   check_result<double>(boost::math::tr1::beta(f, d));\r\n   check_result<long double>(boost::math::tr1::beta(l, d));\r\n\r\n   check_result<float>(boost::math::tr1::comp_ellint_1(f));\r\n   check_result<float>(boost::math::tr1::comp_ellint_1f(f));\r\n   check_result<double>(boost::math::tr1::comp_ellint_1(d));\r\n   check_result<long double>(boost::math::tr1::comp_ellint_1(l));\r\n   check_result<long double>(boost::math::tr1::comp_ellint_1l(l));\r\n   check_result<double>(boost::math::tr1::comp_ellint_1(ui));\r\n   check_result<double>(boost::math::tr1::comp_ellint_1(i));\r\n\r\n   check_result<float>(boost::math::tr1::comp_ellint_2(f));\r\n   check_result<float>(boost::math::tr1::comp_ellint_2f(f));\r\n   check_result<double>(boost::math::tr1::comp_ellint_2(d));\r\n   check_result<long double>(boost::math::tr1::comp_ellint_2(l));\r\n   check_result<long double>(boost::math::tr1::comp_ellint_2l(l));\r\n   check_result<double>(boost::math::tr1::comp_ellint_2(ui));\r\n   check_result<double>(boost::math::tr1::comp_ellint_2(i));\r\n\r\n   check_result<float>(boost::math::tr1::comp_ellint_3(f, f));\r\n   check_result<float>(boost::math::tr1::comp_ellint_3f(f, f));\r\n   check_result<double>(boost::math::tr1::comp_ellint_3(d, d));\r\n   check_result<long double>(boost::math::tr1::comp_ellint_3(l, l));\r\n   check_result<long double>(boost::math::tr1::comp_ellint_3l(l, l));\r\n   check_result<double>(boost::math::tr1::comp_ellint_3(ui, ui));\r\n   check_result<double>(boost::math::tr1::comp_ellint_3(i, ui));\r\n   check_result<double>(boost::math::tr1::comp_ellint_3(f, d));\r\n   check_result<long double>(boost::math::tr1::comp_ellint_3(l, d));\r\n\r\n   check_result<float>(boost::math::tr1::cyl_bessel_i(f, f));\r\n   check_result<float>(boost::math::tr1::cyl_bessel_if(f, f));\r\n   check_result<double>(boost::math::tr1::cyl_bessel_i(d, d));\r\n   check_result<long double>(boost::math::tr1::cyl_bessel_i(l, l));\r\n   check_result<long double>(boost::math::tr1::cyl_bessel_il(l, l));\r\n   check_result<double>(boost::math::tr1::cyl_bessel_i(ui, ui));\r\n   check_result<double>(boost::math::tr1::cyl_bessel_i(i, ui));\r\n   check_result<double>(boost::math::tr1::cyl_bessel_i(f, d));\r\n   check_result<long double>(boost::math::tr1::cyl_bessel_i(l, d));\r\n\r\n   check_result<float>(boost::math::tr1::cyl_bessel_j(f, f));\r\n   check_result<float>(boost::math::tr1::cyl_bessel_jf(f, f));\r\n   check_result<double>(boost::math::tr1::cyl_bessel_j(d, d));\r\n   check_result<long double>(boost::math::tr1::cyl_bessel_j(l, l));\r\n   check_result<long double>(boost::math::tr1::cyl_bessel_jl(l, l));\r\n   check_result<double>(boost::math::tr1::cyl_bessel_j(ui, ui));\r\n   check_result<double>(boost::math::tr1::cyl_bessel_j(i, ui));\r\n   check_result<double>(boost::math::tr1::cyl_bessel_j(f, d));\r\n   check_result<long double>(boost::math::tr1::cyl_bessel_j(l, d));\r\n\r\n   check_result<float>(boost::math::tr1::cyl_bessel_k(f, f));\r\n   check_result<float>(boost::math::tr1::cyl_bessel_kf(f, f));\r\n   check_result<double>(boost::math::tr1::cyl_bessel_k(d, d));\r\n   check_result<long double>(boost::math::tr1::cyl_bessel_k(l, l));\r\n   check_result<long double>(boost::math::tr1::cyl_bessel_kl(l, l));\r\n   check_result<double>(boost::math::tr1::cyl_bessel_k(ui, ui));\r\n   check_result<double>(boost::math::tr1::cyl_bessel_k(i, ui));\r\n   check_result<double>(boost::math::tr1::cyl_bessel_k(f, d));\r\n   check_result<long double>(boost::math::tr1::cyl_bessel_k(l, d));\r\n\r\n   check_result<float>(boost::math::tr1::cyl_neumann(f, f));\r\n   check_result<float>(boost::math::tr1::cyl_neumannf(f, f));\r\n   check_result<double>(boost::math::tr1::cyl_neumann(d, d));\r\n   check_result<long double>(boost::math::tr1::cyl_neumann(l, l));\r\n   check_result<long double>(boost::math::tr1::cyl_neumannl(l, l));\r\n   check_result<double>(boost::math::tr1::cyl_neumann(ui, ui));\r\n   check_result<double>(boost::math::tr1::cyl_neumann(i, ui));\r\n   check_result<double>(boost::math::tr1::cyl_neumann(f, d));\r\n   check_result<long double>(boost::math::tr1::cyl_neumann(l, d));\r\n\r\n   check_result<float>(boost::math::tr1::ellint_1(f, f));\r\n   check_result<float>(boost::math::tr1::ellint_1f(f, f));\r\n   check_result<double>(boost::math::tr1::ellint_1(d, d));\r\n   check_result<long double>(boost::math::tr1::ellint_1(l, l));\r\n   check_result<long double>(boost::math::tr1::ellint_1l(l, l));\r\n   check_result<double>(boost::math::tr1::ellint_1(ui, ui));\r\n   check_result<double>(boost::math::tr1::ellint_1(i, ui));\r\n   check_result<double>(boost::math::tr1::ellint_1(f, d));\r\n   check_result<long double>(boost::math::tr1::ellint_1(l, d));\r\n\r\n   check_result<float>(boost::math::tr1::ellint_2(f, f));\r\n   check_result<float>(boost::math::tr1::ellint_2f(f, f));\r\n   check_result<double>(boost::math::tr1::ellint_2(d, d));\r\n   check_result<long double>(boost::math::tr1::ellint_2(l, l));\r\n   check_result<long double>(boost::math::tr1::ellint_2l(l, l));\r\n   check_result<double>(boost::math::tr1::ellint_2(ui, ui));\r\n   check_result<double>(boost::math::tr1::ellint_2(i, ui));\r\n   check_result<double>(boost::math::tr1::ellint_2(f, d));\r\n   check_result<long double>(boost::math::tr1::ellint_2(l, d));\r\n\r\n   check_result<float>(boost::math::tr1::ellint_3(f, f, f));\r\n   check_result<float>(boost::math::tr1::ellint_3f(f, f, f));\r\n   check_result<double>(boost::math::tr1::ellint_3(d, d, d));\r\n   check_result<long double>(boost::math::tr1::ellint_3(l, l, l));\r\n   check_result<long double>(boost::math::tr1::ellint_3l(l, l, l));\r\n   check_result<double>(boost::math::tr1::ellint_3(ui, ui, i));\r\n   check_result<double>(boost::math::tr1::ellint_3(i, ui, f));\r\n   check_result<double>(boost::math::tr1::ellint_3(f, d, i));\r\n   check_result<long double>(boost::math::tr1::ellint_3(l, d, f));\r\n\r\n   check_result<float>(boost::math::tr1::expint(f));\r\n   check_result<float>(boost::math::tr1::expintf(f));\r\n   check_result<double>(boost::math::tr1::expint(d));\r\n   check_result<long double>(boost::math::tr1::expint(l));\r\n   check_result<long double>(boost::math::tr1::expintl(l));\r\n   check_result<double>(boost::math::tr1::expint(ui));\r\n   check_result<double>(boost::math::tr1::expint(i));\r\n\r\n   check_result<float>(boost::math::tr1::hermite(ui, f));\r\n   check_result<float>(boost::math::tr1::hermitef(ui, f));\r\n   check_result<double>(boost::math::tr1::hermite(ui, d));\r\n   check_result<long double>(boost::math::tr1::hermite(ui, l));\r\n   check_result<long double>(boost::math::tr1::hermitel(ui, l));\r\n   check_result<double>(boost::math::tr1::hermite(ui, i));\r\n   check_result<double>(boost::math::tr1::hermite(ui, ui));\r\n\r\n   check_result<float>(boost::math::tr1::laguerre(ui, f));\r\n   check_result<float>(boost::math::tr1::laguerref(ui, f));\r\n   check_result<double>(boost::math::tr1::laguerre(ui, d));\r\n   check_result<long double>(boost::math::tr1::laguerre(ui, l));\r\n   check_result<long double>(boost::math::tr1::laguerrel(ui, l));\r\n   check_result<double>(boost::math::tr1::laguerre(ui, i));\r\n   check_result<double>(boost::math::tr1::laguerre(ui, ui));\r\n\r\n   check_result<float>(boost::math::tr1::legendre(ui, f));\r\n   check_result<float>(boost::math::tr1::legendref(ui, f));\r\n   check_result<double>(boost::math::tr1::legendre(ui, d));\r\n   check_result<long double>(boost::math::tr1::legendre(ui, l));\r\n   check_result<long double>(boost::math::tr1::legendrel(ui, l));\r\n   check_result<double>(boost::math::tr1::legendre(ui, i));\r\n   check_result<double>(boost::math::tr1::legendre(ui, ui));\r\n\r\n   check_result<float>(boost::math::tr1::riemann_zeta(f));\r\n   check_result<float>(boost::math::tr1::riemann_zetaf(f));\r\n   check_result<double>(boost::math::tr1::riemann_zeta(d));\r\n   check_result<long double>(boost::math::tr1::riemann_zeta(l));\r\n   check_result<long double>(boost::math::tr1::riemann_zetal(l));\r\n   check_result<double>(boost::math::tr1::riemann_zeta(ui));\r\n   check_result<double>(boost::math::tr1::riemann_zeta(i));\r\n\r\n   check_result<float>(boost::math::tr1::sph_bessel(ui, f));\r\n   check_result<float>(boost::math::tr1::sph_besself(ui, f));\r\n   check_result<double>(boost::math::tr1::sph_bessel(ui, d));\r\n   check_result<long double>(boost::math::tr1::sph_bessel(ui, l));\r\n   check_result<long double>(boost::math::tr1::sph_bessell(ui, l));\r\n   check_result<double>(boost::math::tr1::sph_bessel(ui, i));\r\n   check_result<double>(boost::math::tr1::sph_bessel(ui, ui));\r\n\r\n   check_result<float>(boost::math::tr1::sph_legendre(ui, ui, f));\r\n   check_result<float>(boost::math::tr1::sph_legendref(ui, ui, f));\r\n   check_result<double>(boost::math::tr1::sph_legendre(ui, ui, d));\r\n   check_result<long double>(boost::math::tr1::sph_legendre(ui, ui, l));\r\n   check_result<long double>(boost::math::tr1::sph_legendrel(ui, ui, l));\r\n   check_result<double>(boost::math::tr1::sph_legendre(ui, ui, i));\r\n   check_result<double>(boost::math::tr1::sph_legendre(ui, ui, ui));\r\n\r\n   check_result<float>(boost::math::tr1::sph_neumann(ui, f));\r\n   check_result<float>(boost::math::tr1::sph_neumannf(ui, f));\r\n   check_result<double>(boost::math::tr1::sph_neumann(ui, d));\r\n   check_result<long double>(boost::math::tr1::sph_neumann(ui, l));\r\n   check_result<long double>(boost::math::tr1::sph_neumannl(ui, l));\r\n   check_result<double>(boost::math::tr1::sph_neumann(ui, i));\r\n   check_result<double>(boost::math::tr1::sph_neumann(ui, ui));\r\n\r\n   check_result<float>(boost::math::tr1::acosh(f));\r\n   check_result<float>(boost::math::tr1::acoshf(f));\r\n   check_result<double>(boost::math::tr1::acosh(d));\r\n   check_result<long double>(boost::math::tr1::acosh(l));\r\n   check_result<long double>(boost::math::tr1::acoshl(l));\r\n   check_result<double>(boost::math::tr1::acosh(ui));\r\n   check_result<double>(boost::math::tr1::acosh(i));\r\n\r\n   check_result<float>(boost::math::tr1::asinh(f));\r\n   check_result<float>(boost::math::tr1::asinhf(f));\r\n   check_result<double>(boost::math::tr1::asinh(d));\r\n   check_result<long double>(boost::math::tr1::asinh(l));\r\n   check_result<long double>(boost::math::tr1::asinhl(l));\r\n   check_result<double>(boost::math::tr1::asinh(ui));\r\n   check_result<double>(boost::math::tr1::asinh(i));\r\n\r\n   check_result<float>(boost::math::tr1::atanh(f));\r\n   check_result<float>(boost::math::tr1::atanhf(f));\r\n   check_result<double>(boost::math::tr1::atanh(d));\r\n   check_result<long double>(boost::math::tr1::atanh(l));\r\n   check_result<long double>(boost::math::tr1::atanhl(l));\r\n   check_result<double>(boost::math::tr1::atanh(ui));\r\n   check_result<double>(boost::math::tr1::atanh(i));\r\n\r\n   check_result<float>(boost::math::tr1::cbrt(f));\r\n   check_result<float>(boost::math::tr1::cbrtf(f));\r\n   check_result<double>(boost::math::tr1::cbrt(d));\r\n   check_result<long double>(boost::math::tr1::cbrt(l));\r\n   check_result<long double>(boost::math::tr1::cbrtl(l));\r\n   check_result<double>(boost::math::tr1::cbrt(ui));\r\n   check_result<double>(boost::math::tr1::cbrt(i));\r\n\r\n   check_result<float>(boost::math::tr1::copysign(f, f));\r\n   check_result<float>(boost::math::tr1::copysignf(f, f));\r\n   check_result<double>(boost::math::tr1::copysign(d, d));\r\n   check_result<long double>(boost::math::tr1::copysign(l, l));\r\n   check_result<long double>(boost::math::tr1::copysignl(l, l));\r\n   check_result<double>(boost::math::tr1::copysign(d, i));\r\n   check_result<double>(boost::math::tr1::copysign(ui, f));\r\n\r\n   check_result<float>(boost::math::tr1::erf(f));\r\n   check_result<float>(boost::math::tr1::erff(f));\r\n   check_result<double>(boost::math::tr1::erf(d));\r\n   check_result<long double>(boost::math::tr1::erf(l));\r\n   check_result<long double>(boost::math::tr1::erfl(l));\r\n   check_result<double>(boost::math::tr1::erf(ui));\r\n   check_result<double>(boost::math::tr1::erf(i));\r\n\r\n   check_result<float>(boost::math::tr1::erfc(f));\r\n   check_result<float>(boost::math::tr1::erfcf(f));\r\n   check_result<double>(boost::math::tr1::erfc(d));\r\n   check_result<long double>(boost::math::tr1::erfc(l));\r\n   check_result<long double>(boost::math::tr1::erfcl(l));\r\n   check_result<double>(boost::math::tr1::erfc(ui));\r\n   check_result<double>(boost::math::tr1::erfc(i));\r\n\r\n   check_result<float>(boost::math::tr1::expm1(f));\r\n   check_result<float>(boost::math::tr1::expm1f(f));\r\n   check_result<double>(boost::math::tr1::expm1(d));\r\n   check_result<long double>(boost::math::tr1::expm1(l));\r\n   check_result<long double>(boost::math::tr1::expm1l(l));\r\n   check_result<double>(boost::math::tr1::expm1(ui));\r\n   check_result<double>(boost::math::tr1::expm1(i));\r\n\r\n   check_result<float>(boost::math::tr1::fmin(f, f));\r\n   check_result<float>(boost::math::tr1::fminf(f, f));\r\n   check_result<double>(boost::math::tr1::fmin(d, d));\r\n   check_result<long double>(boost::math::tr1::fmin(l, l));\r\n   check_result<long double>(boost::math::tr1::fminl(l, l));\r\n   check_result<double>(boost::math::tr1::fmin(d, i));\r\n   check_result<double>(boost::math::tr1::fmin(ui, f));\r\n\r\n   check_result<float>(boost::math::tr1::fmax(f, f));\r\n   check_result<float>(boost::math::tr1::fmaxf(f, f));\r\n   check_result<double>(boost::math::tr1::fmax(d, d));\r\n   check_result<long double>(boost::math::tr1::fmax(l, l));\r\n   check_result<long double>(boost::math::tr1::fmaxl(l, l));\r\n   check_result<double>(boost::math::tr1::fmax(d, i));\r\n   check_result<double>(boost::math::tr1::fmax(ui, f));\r\n\r\n   check_result<float>(boost::math::tr1::hypot(f, f));\r\n   check_result<float>(boost::math::tr1::hypotf(f, f));\r\n   check_result<double>(boost::math::tr1::hypot(d, d));\r\n   check_result<long double>(boost::math::tr1::hypot(l, l));\r\n   check_result<long double>(boost::math::tr1::hypotl(l, l));\r\n   check_result<double>(boost::math::tr1::hypot(d, i));\r\n   check_result<double>(boost::math::tr1::hypot(ui, f));\r\n\r\n   check_result<float>(boost::math::tr1::lgamma(f));\r\n   check_result<float>(boost::math::tr1::lgammaf(f));\r\n   check_result<double>(boost::math::tr1::lgamma(d));\r\n   check_result<long double>(boost::math::tr1::lgamma(l));\r\n   check_result<long double>(boost::math::tr1::lgammal(l));\r\n   check_result<double>(boost::math::tr1::lgamma(ui));\r\n   check_result<double>(boost::math::tr1::lgamma(i));\r\n\r\n   check_result<long long>(boost::math::tr1::llround(f));\r\n   check_result<long long>(boost::math::tr1::llroundf(f));\r\n   check_result<long long>(boost::math::tr1::llround(d));\r\n   check_result<long long>(boost::math::tr1::llround(l));\r\n   check_result<long long>(boost::math::tr1::llroundl(l));\r\n   check_result<long long>(boost::math::tr1::llround(ui));\r\n   check_result<long long>(boost::math::tr1::llround(i));\r\n\r\n   check_result<float>(boost::math::tr1::log1p(f));\r\n   check_result<float>(boost::math::tr1::log1pf(f));\r\n   check_result<double>(boost::math::tr1::log1p(d));\r\n   check_result<long double>(boost::math::tr1::log1p(l));\r\n   check_result<long double>(boost::math::tr1::log1pl(l));\r\n   check_result<double>(boost::math::tr1::log1p(ui));\r\n   check_result<double>(boost::math::tr1::log1p(i));\r\n\r\n   check_result<long>(boost::math::tr1::lround(f));\r\n   check_result<long>(boost::math::tr1::lroundf(f));\r\n   check_result<long>(boost::math::tr1::lround(d));\r\n   check_result<long>(boost::math::tr1::lround(l));\r\n   check_result<long>(boost::math::tr1::lroundl(l));\r\n   check_result<long>(boost::math::tr1::lround(ui));\r\n   check_result<long>(boost::math::tr1::lround(i));\r\n\r\n   check_result<float>(boost::math::tr1::round(f));\r\n   check_result<float>(boost::math::tr1::roundf(f));\r\n   check_result<double>(boost::math::tr1::round(d));\r\n   check_result<long double>(boost::math::tr1::round(l));\r\n   check_result<long double>(boost::math::tr1::roundl(l));\r\n   check_result<double>(boost::math::tr1::round(ui));\r\n   check_result<double>(boost::math::tr1::round(i));\r\n\r\n   check_result<float>(boost::math::tr1::nextafter(f, f));\r\n   check_result<float>(boost::math::tr1::nextafterf(f, f));\r\n   check_result<double>(boost::math::tr1::nextafter(d, d));\r\n   check_result<long double>(boost::math::tr1::nextafter(l, l));\r\n   check_result<long double>(boost::math::tr1::nextafterl(l, l));\r\n   check_result<double>(boost::math::tr1::nextafter(d, i));\r\n   check_result<double>(boost::math::tr1::nextafter(ui, f));\r\n\r\n   check_result<float>(boost::math::tr1::nexttoward(f, f));\r\n   check_result<float>(boost::math::tr1::nexttowardf(f, f));\r\n   check_result<double>(boost::math::tr1::nexttoward(d, d));\r\n   check_result<long double>(boost::math::tr1::nexttoward(l, l));\r\n   check_result<long double>(boost::math::tr1::nexttowardl(l, l));\r\n   check_result<double>(boost::math::tr1::nexttoward(d, i));\r\n   check_result<double>(boost::math::tr1::nexttoward(ui, f));\r\n\r\n   check_result<float>(boost::math::tr1::tgamma(f));\r\n   check_result<float>(boost::math::tr1::tgammaf(f));\r\n   check_result<double>(boost::math::tr1::tgamma(d));\r\n   check_result<long double>(boost::math::tr1::tgamma(l));\r\n   check_result<long double>(boost::math::tr1::tgammal(l));\r\n   check_result<double>(boost::math::tr1::tgamma(ui));\r\n   check_result<double>(boost::math::tr1::tgamma(i));\r\n\r\n   check_result<float>(boost::math::tr1::trunc(f));\r\n   check_result<float>(boost::math::tr1::truncf(f));\r\n   check_result<double>(boost::math::tr1::trunc(d));\r\n   check_result<long double>(boost::math::tr1::trunc(l));\r\n   check_result<long double>(boost::math::tr1::truncl(l));\r\n   check_result<double>(boost::math::tr1::trunc(ui));\r\n   check_result<double>(boost::math::tr1::trunc(i));\r\n\r\n}\r\n", "meta": {"hexsha": "c06e6e9779d7ba27590aa9ee60f87d368462c7f4", "size": 19279, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/math/test/compile_test/tr1_incl_test.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": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/math/test/compile_test/tr1_incl_test.cpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-04T18:00:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-04T18:00:00.000Z", "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/math/test/compile_test/tr1_incl_test.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 52.5313351499, "max_line_length": 76, "alphanum_fraction": 0.6754499715, "num_tokens": 5948, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850154599563, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.4521511963973551}}
{"text": "#ifndef BIT_VECTOR_HPP\n#define BIT_VECTOR_HPP\n\n#include <assert.h>\n#include <string>\n#include <stdexcept>\n#include <algorithm>\n#include <vector>\n#include <iostream>\n\n#include \"config/config.hpp\"\n\n#include <boost/dynamic_bitset/dynamic_bitset.hpp>\n\n\n\nnamespace boost {\n\t/**\n\t * @brief The multiplication of two dynamic_bitsets. \n\t * Assume A=[a_1, a_2, ..., a_n] and B=[b_1, b_2, ..., b_n], the multiplication\n\t * of A*B = (a_1*b_1)+(a_2*b_2)+...+(a_n*b_n). This operation is equivalent \n\t * in function to determine whether A intersects with B.\n\t * @param two dynamic_bitsets a and b\n\t * @return the bool value of A*B.\n\t */\n\ttemplate <typename Block, typename Allocator>\n\tinline bool operator*(const dynamic_bitset<Block, Allocator>& a,\n\t\tconst dynamic_bitset<Block, Allocator>& b)\n\t{\n\t\tassert(a.size() == b.size());\n\n\t\t/************************************************************************/\n\t\t/* Methods one, needing to add friend function in source file           */\n\t\t/************************************************************************/\n\t\t//typedef typename dynamic_bitset<Block, Allocator>::size_type size_type;\n\n\t\t//for (size_type ii = a.num_blocks(); ii > 0; --ii) {\n\t\t//  size_type i = ii-1;\n\t\t//  if (a.m_bits[i] & b.m_bits[i])\n\t\t//    return true;\n\t\t//}\n\t\t//return false;\n\t\t// \n\n\t\t/************************************************************************/\n\t\t/* Method two, a quite easy way!!!                                      */\n\t\t/************************************************************************/\n\n\t\treturn a.intersects(b);\n\t}\n\n} // boost namespace end\n\n\n\nnamespace argumatrix {  // argumatrix\n\nusing namespace boost;\nclass bitvector: public dynamic_bitset<block_type>\n{\npublic:\n\t// Constructor\n\tbitvector(): dynamic_bitset<block_type>() { }\n\tbitvector(size_type _sz, unsigned long value = 0): dynamic_bitset<block_type>(_sz, value) { }\n\tbitvector(const std::string& _s): dynamic_bitset<block_type>(_s) { }\n\tbitvector(const dynamic_bitset<block_type>& _db): dynamic_bitset<block_type>(_db) { } \n\t\npublic:\n\t/**\n\t * @brief The multiplication of two bitvector. \n\t * Assume A=[a_1, a_2, ..., a_n] and B=[b_1, b_2, ..., b_n], the multiplication\n\t * of A*B = (a_1*b_1)+(a_2*b_2)+...+(a_n*b_n). This operation is equivalent \n\t * in function to determine whether A intersects with B.\n\t * @param two bitvector a and b\n\t * @return the bool value of A*B.\n\t */\n\tbool operator*(const bitvector& _bv);\n\n\t/**\n\t * @brief To decide whether the bitvector of an argument set is empty-set? \n\t * If all entries of this bitvector are 0's, then it is an empty set, and\n\t * this function return true, else return false. we must discriminate this\n\t * function from the function empty(), which is used to determine the size of\n\t * the bitvector is zero. This function is the same as the function none().\n\t * @return true if all entries of the bitvector are 0's, otherwise return false.\n\t */\n\tbool is_emptyset();\n\n\t/**\n\t * @brief To decide whether the bitvector of an argument set is universal? \n\t * If all entries of this bitvector are 1's, then it is an universal set, and\n\t * this function return true, else return false. \n\t */\n\tbool is_universal();\n\n\t/**\n\t * @brief Create an empty set (all 0's) or a universal set (all 1's) under a given size. \n\t * @param _sz the size of the empty set or the universal set\n\t * @return the bitvector of the empty set or the universal set.\n\t */\n\tstatic bitvector EmptySet(size_type _sz);\n\tstatic bitvector UniversalSet(size_type _sz);\n\n\t/**\n\t * increaser the bit vector with 1. \n\t * @param _sz the size of the empty set or the universal set\n\t * @return the bitvector of the empty set or the universal set.\n\t */\n\tbool Increase();\n};\n\n__inline\nbool bitvector::operator*(const bitvector& _bv)\n{\n\treturn intersects(_bv);\n}\n\ninline\nbool bitvector::is_emptyset()\n{\n\treturn !any();\n}\n\n__inline\nargumatrix::bitvector bitvector::EmptySet(size_type _sz)\n{\n\treturn bitvector(_sz, 0);\n}\n\n\nargumatrix::bitvector bitvector::UniversalSet(size_type _sz)\n{\n\t//bitvector universal_bv(_sz, 0);\n\t//universal_bv.set();  // set all 0's to all 1's\n\t//return universal_bv;\n\n\treturn bitvector(_sz, 0).set();\n}\n\nbool bitvector::Increase()\n{\n\treturn true;\n}\n\n__inline \nbool bitvector::is_universal()\n{\n\t// dynamic_bitset<>::all() may not be supported in the version\n\t// less than 1.61. For compatibility, an inefficient way is used.\n\n\t//return all();\n\treturn bitvector(this->size(), 0).set() == *this;\n}\n\n} // namespace argumatrix\n#endif\n", "meta": {"hexsha": "8624b3402355ec15c3548b94c98e02c487703f85", "size": 4452, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "bitmatrix/bitvector.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": "bitmatrix/bitvector.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": "bitmatrix/bitvector.hpp", "max_forks_repo_name": "xixicat/argmat-clpb", "max_forks_repo_head_hexsha": "eb76cb42ff7e9e2fd8d82a40778d1ac6343cea58", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.3566878981, "max_line_length": 94, "alphanum_fraction": 0.638589398, "num_tokens": 1170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.45215119464156495}}
{"text": "// Copyright Louis Dionne 2015\n// Distributed under the Boost Software License, Version 1.0.\n\n#include <boost/mpl/less.hpp>\n#include <boost/mpl/min_element.hpp>\n#include <boost/mpl/placeholders.hpp>\n#include <boost/mpl/sizeof.hpp>\n#include <boost/mpl/vector.hpp>\n\n#include <boost/hana/tuple.hpp>\n#include <boost/hana/type.hpp>\n\n#include <type_traits>\n\n\ntemplate <int n>\nstruct storage { char weight[n]; };\n\nnamespace then {\nusing namespace boost::mpl;\n\n// sample(smallest_type-then)\ntemplate <typename ...T>\nstruct smallest\n  : deref<\n    typename min_element<\n      vector<T...>, less<sizeof_<_1>, sizeof_<_2>>\n    >::type\n  >\n{ };\n\ntemplate <typename ...T>\nusing smallest_t = typename smallest<T...>::type;\n\nstatic_assert(std::is_same<\n  smallest_t<char, long, long double>, char\n>::value, \"\");\n// end-sample\n\nstatic_assert(std::is_same<\n  smallest_t<storage<3>, storage<1>, storage<2>>,\n  storage<1>\n>::value, \"\");\n}\n\n\nnamespace now {\nusing namespace boost::hana;\n\n// sample(smallest_type-now)\ntemplate <typename ...T>\nauto smallest = minimum(tuple_t<T...>, [](auto t, auto u) {\n  return sizeof_(t) < sizeof_(u);\n});\n\ntemplate <typename ...T>\nusing smallest_t = typename decltype(smallest<T...>)::type;\n\nstatic_assert(std::is_same<\n  smallest_t<char, long, long double>, char\n>::value, \"\");\n// end-sample\n\nstatic_assert(std::is_same<\n  smallest_t<storage<3>, storage<1>, storage<2>>,\n  storage<1>\n>::value, \"\");\n}\n\nint main() { }\n", "meta": {"hexsha": "c71c54c71252a7b43d138521c8661a9d9157e893", "size": 1433, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/smallest_type.cpp", "max_stars_repo_name": "ldionne/cppnow-2015-hana", "max_stars_repo_head_hexsha": "2f9e86996b61b11e19486741f59ef217ea9125a7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-07-02T22:23:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-22T19:44:15.000Z", "max_issues_repo_path": "code/smallest_type.cpp", "max_issues_repo_name": "ldionne/cppnow-2015-hana", "max_issues_repo_head_hexsha": "2f9e86996b61b11e19486741f59ef217ea9125a7", "max_issues_repo_licenses": ["MIT"], "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/smallest_type.cpp", "max_forks_repo_name": "ldionne/cppnow-2015-hana", "max_forks_repo_head_hexsha": "2f9e86996b61b11e19486741f59ef217ea9125a7", "max_forks_repo_licenses": ["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.1830985915, "max_line_length": 61, "alphanum_fraction": 0.6838799721, "num_tokens": 376, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.705785040214066, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.4521511928857741}}
{"text": "#ifndef YASMIC_ISTREAM_AS_MATRIX\r\n#define YASMIC_ISTREAM_AS_MATRIX\r\n\r\n#include <iostream>\r\n#include <boost/tuple/tuple.hpp>\r\n#include <yasmic/smatrix_traits.hpp>\r\n#include <iterator>\r\n\r\nnamespace yasmic\r\n{\r\n\ttemplate <>\r\n    struct smatrix_traits<std::istream> \r\n    {\r\n    \ttypedef unsigned int size_type;\r\n    \ttypedef int index_type;\r\n\t\ttypedef double value_type;\r\n\r\n\t\ttypedef std::istream_iterator<boost::tuple<index_type, index_type, value_type> > nonzero_iterator;\r\n\r\n\t\ttypedef void row_iterator;\r\n\t\ttypedef void row_nonzero_iterator;\r\n\t\ttypedef void column_iterator;\r\n\t\ttypedef void column_iterator;\r\n    };\r\n    \r\n    inline std::pair<typename smatrix_traits<std::istream>::size_type,\r\n                      typename smatrix_traits<std::istream>::size_type>\r\n    dimensions(std::istream& f)\r\n    {\r\n    \tsmatrix_traits<std::istream>::size_type nrows,ncols;\r\n    \t\r\n    \tf.seekg(0, std::ios_base::beg);\r\n        f >> nrows >> ncols;\r\n        \r\n        return (std::make_pair(nrows, ncols));\r\n    }\r\n    \r\n\tinline smatrix_traits<std::istream>::size_type ncols(std::istream& f)\r\n\t{\r\n\t\tsmatrix_traits<std::istream>::size_type nrows,ncols;\r\n\t\t\r\n\t\tboost::tie(nrows, ncols) = dimensions(f);\r\n\t\t\r\n\t\treturn (ncols);\r\n\t}\r\n\t\r\n\tinline smatrix_traits<std::istream>::size_type nrows(std::istream& f)\r\n\t{\r\n\t\tsmatrix_traits<std::istream>::size_type nrows,ncols;\r\n\t\t\r\n\t\tboost::tie(nrows, ncols) = dimensions(f);\r\n\t\t\r\n\t\treturn (nrows);\r\n\t}\r\n\t\r\n\tinline smatrix_traits<std::istream>::size_type nnz(std::istream& f)\r\n\t{\r\n\t\tsmatrix_traits<std::istream>::size_type d1,d2,nnz;\r\n\t\t\r\n        f.seekg(0, std::ios_base::beg);\r\n        f >> d1 >>  d2 >> nnz;\r\n        \r\n        return (nnz);\r\n\t}\r\n\t\r\n\tinline std::pair<smatrix_traits<std::istream>::nonzero_iterator,\r\n                      smatrix_traits<std::istream>::nonzero_iterator>\r\n    nonzeros(std::ifstream& f)\r\n    {\r\n    \tsmatrix_traits<std::istream>::size_type d1,d2,d3;\r\n    \tf.seekg(0, std::ios_base::beg);\r\n        f >> d1  >> d2 >> d3;\r\n        \r\n        typedef smatrix_traits<std::istream>::nonzero_iterator nz_iter;\r\n        \r\n        return (std::make_pair(nz_iter(f), nz_iter()));\r\n    }\r\n}\r\n\r\n#endif //YASMIC_ISTREAM_AS_MATRIX\r\n", "meta": {"hexsha": "eed9d92c6e84b2491d30c3f0fa2840df522332f1", "size": 2178, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "external_packages/matlab/default_packages/matlab_bgl_mac64/libmbgl/yasmic/istream_as_matrix.hpp", "max_stars_repo_name": "marielacour81/CBIG", "max_stars_repo_head_hexsha": "511af756c6ddabbd3a9681ce3514b79ef5aaaf3f", "max_stars_repo_licenses": ["MIT"], "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": "external_packages/matlab/default_packages/matlab_bgl_mac64/libmbgl/yasmic/istream_as_matrix.hpp", "max_issues_repo_name": "marielacour81/CBIG", "max_issues_repo_head_hexsha": "511af756c6ddabbd3a9681ce3514b79ef5aaaf3f", "max_issues_repo_licenses": ["MIT"], "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": "external_packages/matlab/default_packages/matlab_bgl_mac64/libmbgl/yasmic/istream_as_matrix.hpp", "max_forks_repo_name": "marielacour81/CBIG", "max_forks_repo_head_hexsha": "511af756c6ddabbd3a9681ce3514b79ef5aaaf3f", "max_forks_repo_licenses": ["MIT"], "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": 26.8888888889, "max_line_length": 101, "alphanum_fraction": 0.6326905418, "num_tokens": 551, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850154599563, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.45215119155486744}}
{"text": "/**\n * @author J Howard Johnson\n * @file sigprune_fet.cc\n * @brief Calculate Fisher's exact test significance levels\n * \n * \n * Technologies langagieres interactives / Interactive Language Technologies\n * Inst. de technologie de l'information / Institute for Information Technology\n * Conseil national de recherches Canada / National Research Council Canada\n * Copyright 2006-2011, Sa Majeste la Reine du Chef du Canada /\n * Copyright 2006-2011, Her Majesty in Right of Canada\n */\n\n#include <iostream>\n#include <fstream>\n#include <cmath>\n#include <boost/math/special_functions/gamma.hpp>\n\n#include \"file_utils.h\"\n#include \"arg_reader.h\"\n#include \"printCopyright.h\"\n\nusing namespace Portage;\nusing namespace std;\n\nstatic char help_message[] = \"\\n\\\nsigprune_fet [options] [INFILE [OUTFILE]]\\n\\\n\\n\\\n  Copy INFILE to OUTFILE (default stdin to stdout)\\n\\\n  adding 3 fields to the beginning:\\n\\\n     (1) sort key for log p level\\n\\\n     (2) log p level\\n\\\n     (3) flag\\n\\\n         0 : anti-linked (p_level > 0.50)\\n\\\n         1 : linked with log p level > alpha\\n\\\n         2 : linked with log p level = alpha (1-1-1's)\\n\\\n         3 : linked with log p level < alpha\\n\\\n\\n\\\nOptions:\\n\\\n\\n\\\n  -v    Write progress reports to cerr.\\n\\\n  -c    Don't cap anti-linked p_levels at 0.5. Using this\\n\\\n        flag ensures monotonic scores as joint frequency decreases while\\n\\\n        marginals are held constant.\\n\\\n  -l    Minimum flag value to output (for pruning)\\n\\\n  -n NL Copy only first NL lines [0 = all]\\n\\\n\";\n\n// globals\n\nstatic bool verbose = false;\nstatic bool no_cap = false;\nstatic Uint num_lines = 0;\nstatic Uint flag_threshold = 0;\nstatic string infile( \"-\" );\nstatic string outfile( \"-\" );\n\n// arg processing\n\nvoid getArgs( int argc, char* argv[] )\n{\n   const char* switches[] = { \"v\", \"c\", \"n:\", \"l:\" };\n   ArgReader arg_reader( ARRAY_SIZE( switches ), switches, 0, 2, help_message );\n   arg_reader.read( argc - 1, argv + 1 );\n\n   arg_reader.testAndSet( \"v\", verbose );\n   arg_reader.testAndSet( \"c\", no_cap );\n   arg_reader.testAndSet( \"n\", num_lines );\n   arg_reader.testAndSet( \"l\", flag_threshold );\n\n   arg_reader.testAndSet( 0, \"infile\", infile );\n   arg_reader.testAndSet( 1, \"outfile\", outfile );\n}\n\ntypedef long double quad;\n\nquad lnfact( double x )\n{\n   return lgamma( (quad) x + 1.0 );\n}\n\ndouble ln_hyper( double C_xy, double C_x, double C_y, double nn )\n{\n   quad result =\n      - lnfact( C_xy )\n      + lnfact( C_x )\n      - lnfact( C_x - C_xy )\n      + lnfact( C_y )\n      - lnfact( C_y - C_xy )\n      + lnfact( nn - C_x )\n      - lnfact( nn - C_x - C_y + C_xy )\n      + lnfact( nn - C_y )\n      - lnfact( nn );\n   return result;\n}\n\ndouble lnsum( double ln_x, double ln_y )\n{\n   if ( ln_x < ln_y ) swap( ln_x, ln_y );\n   double del = ln_y - ln_x;\n   double eps = exp( del );\n   if ( del < 10.0 ) return ln_x + log( 1.0 + eps );\n   double last_result = 0.0;\n   double result = ln_x;\n   double power = eps;\n   double i = 1.0;\n   while ( result != last_result ) {\n      last_result = result;\n      result = last_result + power / i;\n      power *= -eps;\n      ++i;\n   }\n   return result;\n//   return ln_x + log( exp( ln_y - ln_x ) + 1.0 );\n}\n\ndouble ln_p_value( double C_xy, double C_x, double C_y, double nn )\n{\n   double ln_p = ln_hyper( C_xy, C_x, C_y, nn );\n   double result = ln_p;\n   double C_xY = C_x - C_xy;\n   double C_Xy = C_y - C_xy;\n   double C_XY = nn - C_x - C_y + C_xy;\n   double C_xy_lim = ( ( C_x < C_y ) ? C_x : C_y );\n   double last_result = 0.0;\n   for ( ++C_xy;\n         C_xy <= C_xy_lim && result != last_result;\n         ++C_xy ) {\n      last_result = result;\n      ln_p +=   ( log( C_Xy-- ) + log( C_xY-- ) )\n              - ( log( C_xy   ) + log( ++C_XY ) );\n      result = lnsum( result, ln_p );\n   }\n   return result;\n}\n\nstring write_b64( double i )\n{\n   string result;\n   int nd = 0;\n   int digit;\n   int d[ 20 ];\n   if ( i > 0 ) {\n      while ( nd < 20 && i > 0 ) {\n         digit = fmod( i, 64.0 );\n         d[ nd++ ] = digit;\n         i = ( i - digit ) / 64.0;\n      }\n      result.push_back( 'P' + nd );\n      while ( nd > 0 ) {\n         result.push_back( '0' + d[ --nd ] );\n      }\n   } else {\n      i = -i;\n      while ( nd < 20 && i > 0 ) {\n         digit = fmod( i, 64.0 );\n         d[ nd++ ] = digit;\n         i = ( i - digit ) / 64.0;\n      }\n      result.push_back( 'O' - nd );\n      while ( nd > 0 ) {\n         result.push_back( 'o' - d[ --nd ] );\n      }\n   }\n   return result;\n}\n\n\n\nint main( int argc, char* argv[] )\n{\n   printCopyright(2006, \"sigprune_fet\");\n   getArgs( argc, argv );\n\n   iSafeMagicStream istr( infile );\n   oSafeMagicStream ostr( outfile );\n\n   Uint lineno = 0;\n   string line;\n   string line_copy;\n\n   ssize_t read;\n\n   int i;\n   vector< char * > field;\n\n   while (    getline( istr, line )\n           && (    lineno++ < num_lines\n                || num_lines == 0 ) ) {\n      line_copy = line;\n      read = line.length();\n      field.resize( 0 );\n      field.push_back( &line[ 0 ] );\n      for ( i = 0; i < read; ++i ) {\n         if (    line[ i ] == '\\t'\n              || line[ i ] == '\\n' ) {\n            line[ i ] = '\\0';\n            field.push_back( &line[ i + 1 ] );\n         }\n      }\n      double C_fr_en = strtod( field[ 1 ], 0 );\n      double C_fr    = strtod( field[ 2 ], 0 );\n      double C_en    = strtod( field[ 3 ], 0 );\n      double nn      = strtod( field[ 4 ], 0 );\n      if (    0.0 > C_fr_en\n           || C_fr_en > C_fr\n           || C_fr_en > C_en\n           || C_fr > nn\n           || C_en > nn ) {\n         error(ETFatal, \"Illegal contingency table\\n%d : %d : %d : %d : %d\", lineno, C_fr_en, C_fr, C_en, nn);\n      }\n      double minus_ln_nn = -log( nn );\n      Uint flag;\n      double p_value;\n\n// Anti-linked\n      if ( C_fr_en * nn < C_fr * C_en ) {\n         flag = 0;\n         p_value = no_cap ? ln_p_value( C_fr_en, C_fr, C_en, nn ) : -log( 2.0 );\n      }\n\n// 1-1-1 's\n      else if ( C_fr_en == 1.0 && C_fr == 1.0 && C_en == 1.0 ) {\n         flag = 2;\n         p_value = minus_ln_nn;\n      }\n\n// Associated less strongly than 1-1-1's\n      else {\n         p_value = ln_p_value( C_fr_en, C_fr, C_en, nn );\n         if ( p_value > minus_ln_nn ) {\n            flag = 1;\n         }\n\n// Associated more strongly than 1-1-1's\n         else {\n            flag = 3;\n         }\n      }\n\n      if ( flag >= flag_threshold ) {\n         double s_p_value = floor( p_value * 1.0e8 + 0.5 );\n         ostr << write_b64( s_p_value ) << '\\t';\n         ostr << setprecision( 14 );\n         ostr << s_p_value * 1.0e-8 << '\\t';\n         ostr << flag << '\\t';\n         ostr << line_copy << '\\n';\n      }\n   }\n}\n", "meta": {"hexsha": "7d656bbdce3362c2d212e4b1a120b9e1f3bb206a", "size": 6599, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/tm/sigprune_fet.cc", "max_stars_repo_name": "nrc-cnrc/Portage-SMT-TAS", "max_stars_repo_head_hexsha": "73f5a65de4adfa13008ea9a01758385c97526059", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/tm/sigprune_fet.cc", "max_issues_repo_name": "nrc-cnrc/Portage-SMT-TAS", "max_issues_repo_head_hexsha": "73f5a65de4adfa13008ea9a01758385c97526059", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tm/sigprune_fet.cc", "max_forks_repo_name": "nrc-cnrc/Portage-SMT-TAS", "max_forks_repo_head_hexsha": "73f5a65de4adfa13008ea9a01758385c97526059", "max_forks_repo_licenses": ["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.2908366534, "max_line_length": 110, "alphanum_fraction": 0.5400818306, "num_tokens": 2045, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370111, "lm_q2_score": 0.640635847978761, "lm_q1q2_score": 0.4521511897990771}}
{"text": "//=====================================================================//\n/*! @file\n\t@brief  Perlin Noise \u30e1\u30a4\u30f3\u95a2\u4fc2\n\t@author \u5e73\u677e\u90a6\u4ec1 (hira@rvf-rc45.net)\n*/\n//=====================================================================//\n#include <iostream>\n#include <tuple>\n#include \"pn_main.hpp\"\n#include \"core/glcore.hpp\"\n#include \"widgets/widget_utils.hpp\"\n#include <boost/lexical_cast.hpp>\n\nnamespace app {\n\n\tvoid pn_main::create_texture_()\n\t{\n//\t\tstd::cout << \"Ovtv: \" << octave_value_ << std::endl;\n//\t\tstd::cout << \"Freq: \" << frequency_value_ << std::endl;\n//\t\tstd::cout << \"Gain: \" << gain_value_ << std::endl;\n\n\t\tint w = src_image_->get_size().x;\n\t\tint h = src_image_->get_size().y;\n\n\t\tprn_image_.create(vtx::ipos(w, h), true);\n\n\t\tint task = 0;\n\t\tif(pn_menu_) {\n\t\t\ttask = pn_menu_->get_select_pos();\n\t\t}\n\t\tif(task == 0) {\n\t\t\tfor(int y = 0; y < h; ++y) {\n\t\t\t\tfor(int x = 0; x < w; ++x) {\n\t\t\t\t\tprn_image_.put_pixel(vtx::ipos(x, y), img::rgba8(0, 0, 0, 0));\n\t\t\t\t}\n\t\t\t}\n\t\t} else if(task == 1 || task == 2) {\n\t\t\ttypedef img::perlin_noise<float> perlin_noise;\n\t\t\tperlin_noise pn(12345);\n\t\t\tfloat fx = static_cast<float>(w) / frequency_value_;\n\t\t\tfloat fy = static_cast<float>(h) / frequency_value_;\n\n\t\t\tfor(int y = 0; y < h; ++y) {\n\t\t\t\tfor(int x = 0; x < w; ++x) {\n\t\t\t\t\tfloat n = pn.octave_noise(x / fx, y / fy, octave_value_) * gain_value_;\n\t\t\t\t\tif(task == 1) {\n\t\t\t\t\t\tn = perlin_noise::clamp(n * 0.5f + 0.5f, 0.0, 1.0);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tn = perlin_noise::compressor(n, -1.0f, -0.8f, 0.8f, 1.0f);\n\t\t\t\t\t\tn += 1.0f;\n\t\t\t\t\t\tn *= 0.5f;\n\t\t\t\t\t}\n\t\t\t\t\tuint8_t gray = static_cast<uint8_t>(n * 255);\n\t\t\t\t\tprn_image_.put_pixel(vtx::ipos(x, y), img::rgba8(gray, gray, gray, gray ^ 255));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid pn_main::blend_()\n\t{\n\t\tmobj_.destroy();\n\t\tmobj_.initialize();\n\t\tbld_image_ = img::shared_img(img::copy_image(src_image_.get()));\n\t\timg::img_rgba8* img = static_cast<img::img_rgba8*>(bld_image_.get());\n\t\timg->blend(vtx::ipos(0), prn_image_, vtx::srect(vtx::ipos(0), prn_image_.get_size()));\n\t\timg_handle_ = mobj_.install(img);\n\t\timage_->at_local_param().mobj_ = mobj_;\n\t\timage_->at_local_param().mobj_handle_ = img_handle_;\n\t}\n\n\ttypedef std::tuple<const std::string, const img::shared_img> save_t;\n\n\tbool save_task_(save_t t)\n\t{\n\t\timg::img_files imfs;\n\t\timfs.set_image(std::get<1>(t));\n\t\treturn imfs.save(std::get<0>(t));\n\t}\n\n\n\tvoid pn_main::image_info_(const std::string& file, const img::i_img* img)\n\t{\n\t\tstd::string s;\n\t\tif(!file.empty()) {\n\t\t\tsize_t fsz = utils::get_file_size(file);\n\t\t\tif(fsz > 0) s = \": \" + boost::lexical_cast<std::string>(fsz) + '\\n';\n\t\t\tterm_->output(s);\n\t\t}\n\t\ts = \"W: \" + boost::lexical_cast<std::string>(img->get_size().x) + '\\n';\n\t\tterm_->output(s);\n\t\ts = \"H: \" + boost::lexical_cast<std::string>(img->get_size().y) + '\\n';\n\t\tterm_->output(s);\n\t\timg::IMG::type t = img->get_type();\n\t\tif(t == img::IMG::INDEXED8) {\n\t\t\tterm_->output(\"INDEXED8\\n\");\n\t\t} else if(t == img::IMG::FULL8) {\n\t\t\tterm_->output(\"FULL8\\n\");\n\t\t}\n\t\tif(img->test_alpha()) {\n\t\t\tterm_->output(\"Alpha\\n\");\n\t\t}\n\t\ts = \"C: \" + boost::lexical_cast<std::string>(img->count_color()) + '\\n';\n\t\tterm_->output(s);\n\t\tterm_->output('\\n');\n\t}\n\n\n\t//-----------------------------------------------------------------//\n\t/*!\n\t\t@brief  \u521d\u671f\u5316\n\t*/\n\t//-----------------------------------------------------------------//\n\tvoid pn_main::initialize()\n\t{\n\t\tgl::core& core = gl::core::get_instance();\n\n\t\tusing namespace gui;\n\t\twidget_director& wd = director_.at().widget_director_;\n\n\t\t{ // \u753b\u50cf\u30d5\u30a1\u30a4\u30eb\u8868\u793a\u7528\u30d5\u30ec\u30fc\u30e0\n\t\t\twidget::param wp(vtx::irect(30, 30, 256, 256));\n\t\t\twidget_frame::param wp_;\n\t\t\twp_.plate_param_.set_caption(30);\n\t\t\tframe_ = wd.add_widget<widget_frame>(wp, wp_);\n\t\t}\n\n\t\t{ // \u753b\u50cf\u30d5\u30a1\u30a4\u30eb\u8868\u793a\u30a4\u30e1\u30fc\u30b8\n\t\t\twidget::param wp(vtx::irect(0, 0, 256, 256), frame_);\n\t\t\twidget_image::param wp_;\n\t\t\timage_ = wd.add_widget<widget_image>(wp, wp_);\n\t\t\timage_->set_state(widget::state::CLIP_PARENTS);\n\t\t\timage_->set_state(widget::state::RESIZE_ROOT);\n\t\t\timage_->set_state(widget::state::MOVE_ROOT, false);\n\t\t\timage_->set_state(widget::state::POSITION_LOCK, false);\n\t\t}\n\n\t\t{ // \u6a5f\u80fd\u30c4\u30fc\u30eb\u30d1\u30ec\u30c3\u30c8\n\t\t\twidget::param wp(vtx::irect(10, 10, 150, 430));\n\t\t\twidget_frame::param wp_;\n\t\t\ttools_ = wd.add_widget<widget_frame>(wp, wp_);\n\t\t\ttools_->set_state(widget::state::SIZE_LOCK);\n\t\t}\n\t\t{ // octave \u30b9\u30e9\u30a4\u30c0\u30fc\n\t\t\twidget::param wp(vtx::irect(10, 10+30*0, 130, 20), tools_);\n\t\t\twidget_slider::param wp_;\n\t\t\twp_.slider_param_.grid_ = 1.0f / 7.0f;\n\t\t\twp_.select_func_ = [this](float pos) {\n\t\t\t\toctave_value_ = static_cast<int>(pos * 7.0f);\n\t\t\t\tupdate_ = true;\n//\t\t\t\tstd::cout << \"Ovtv: \" << octave_value_ << \", \" << pos << std::endl;\n\t\t\t};\n\t\t\toctave_ = wd.add_widget<widget_slider>(wp, wp_);\n\t\t}\n\t\t{ // frequency \u30b9\u30e9\u30a4\u30c0\u30fc\n\t\t\twidget::param wp(vtx::irect(10, 10+30*1, 130, 20), tools_);\n\t\t\twidget_slider::param wp_;\n\t\t\twp_.slider_param_.grid_ = 1.0f / 15.0f;\n\t\t\twp_.select_func_ = [this](float pos){\n\t\t\t\tfrequency_value_ = pos * 15.0f + 1.0f;\n\t\t\t\tupdate_ = true;\n\t\t\t};\n\t\t\tfrequency_ = wd.add_widget<widget_slider>(wp, wp_);\n\t\t}\n\t\t{ // gain \u30b9\u30e9\u30a4\u30c0\u30fc\n\t\t\twidget::param wp(vtx::irect(10, 10+30*2, 130, 20), tools_);\n\t\t\twidget_slider::param wp_;\n\t\t\twp_.slider_param_.grid_ = 1.0f / 20.0f;\n\t\t\twp_.select_func_ = [this](float pos){\n\t\t\t\tgain_value_ = pos * 20.0f;\n\t\t\t\tupdate_ = true;\n\t\t\t};\n\t\t\tgain_ = wd.add_widget<widget_slider>(wp, wp_);\n\t\t}\n\t\t{ // \u30ea\u30b9\u30c8\n\t\t\twidget::param wp(vtx::irect(10, 10+30*3, 130, 40), tools_);\n\t\t\twidget_list::param wp_;\n\t\t\twp_.init_list_.push_back(\"None\");\n\t\t\twp_.init_list_.push_back(\"Smoke\");\n\t\t\twp_.init_list_.push_back(\"Flow\");\n\t\t\tpn_menu_ = wd.add_widget<widget_list>(wp, wp_);\n\t\t\tpn_menu_->at_local_param().select_func_ = [this](const std::string& text, int pos) {\n\t\t\t\tupdate_ = true;\n\t\t\t};\n\t\t}\n\n\t\tshort ofs = 150;\n\t\t{ // \u30ed\u30fc\u30c9\u30dc\u30bf\u30f3\n\t\t\twidget::param wp(vtx::irect(10, ofs+50*0, 100, 40), tools_);\n\t\t\twidget_button::param wp_(\"load\");\n\t\t\tload_ = wd.add_widget<widget_button>(wp, wp_);\n\t\t\tload_->at_local_param().select_func_ = [this](int id) {\n\t\t\t\tif(load_ctx_) {\n\t\t\t\t\tbool f = load_ctx_->get_state(gui::widget::state::ENABLE);\n\t\t\t\t\tload_ctx_->enable(!f);\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\n\t\t{ // \u30bb\u30fc\u30d6\u30dc\u30bf\u30f3\n\t\t\twidget::param wp(vtx::irect(10, ofs+50*1, 100, 40), tools_);\n\t\t\twidget_button::param wp_(\"save\");\n\t\t\tsave_ = wd.add_widget<widget_button>(wp, wp_);\n\t\t\tsave_->at_local_param().select_func_ = [this](int id) {\n\t\t\t\tif(save_ctx_) {\n\t\t\t\t\tbool f = save_ctx_->get_state(gui::widget::state::ENABLE);\n\t\t\t\t\tsave_ctx_->enable(!f);\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\t\tofs += 100;\n\n\t\t{ // \u30b9\u30b1\u30fc\u30eb FIT\n\t\t\twidget::param wp(vtx::irect(10, ofs+30*0, 90, 30), tools_);\n\t\t\twidget_radio::param wp_(\"fit\");\n\t\t\twp_.check_ = true;\n\t\t\tscale_fit_ = wd.add_widget<widget_radio>(wp, wp_);\n\t\t}\n\t\t{ // \u30b9\u30b1\u30fc\u30eb 1X\n\t\t\twidget::param wp(vtx::irect(10, ofs+30*1, 90, 30), tools_);\n\t\t\twidget_radio::param wp_(\"1x\");\n\t\t\tscale_1x_ = wd.add_widget<widget_radio>(wp, wp_);\n\t\t}\n\t\t{ // \u30b9\u30b1\u30fc\u30eb 2X\n\t\t\twidget::param wp(vtx::irect(10, ofs+30*2, 90, 30), tools_);\n\t\t\twidget_radio::param wp_(\"2x\");\n\t\t\tscale_2x_ = wd.add_widget<widget_radio>(wp, wp_);\n\t\t}\n\t\t{ // \u30b9\u30b1\u30fc\u30eb 3X\n\t\t\twidget::param wp(vtx::irect(10, ofs+30*3, 90, 30), tools_);\n\t\t\twidget_radio::param wp_(\"3x\");\n\t\t\tscale_3x_ = wd.add_widget<widget_radio>(wp, wp_);\n\t\t}\n\t\t{ // \u30b9\u30b1\u30fc\u30e9\u30fc\u30dc\u30bf\u30f3\n\t\t\twidget::param wp(vtx::irect(10, ofs+30*4+10, 100, 40), tools_);\n\t\t\twidget_button::param wp_(\"scale\");\n\t\t\tscale_ = wd.add_widget<widget_button>(wp, wp_);\n\t\t}\n\n\t\t{ // \u30bf\u30fc\u30df\u30ca\u30eb\n\t\t\t{\n\t\t\t\twidget::param wp(vtx::irect(10, 320, 9*14-8, 18*16+28));\n\t\t\t\twidget_frame::param wp_;\n\t\t\t\twp_.plate_param_.set_caption(20);\n\t\t\t\tinfo_ = wd.add_widget<widget_frame>(wp, wp_);\n\t\t\t}\n\t\t\t{\n\t\t\t\twidget::param wp(vtx::irect(0), info_);\n\t\t\t\twidget_terminal::param wp_;\n\t\t\t\twp_.echo_ = false;\n\t\t\t\tterm_ = wd.add_widget<widget_terminal>(wp, wp_);\n\t\t\t}\n\t\t}\n\n\t\t{ // load \u30d5\u30a1\u30a4\u30e9\u30fc\u672c\u4f53\n\t\t\twidget::param wp(vtx::irect(10, 30, 300, 200));\n\t\t\twidget_filer::param wp_(core.get_current_path());\n\t\t\tload_ctx_ = wd.add_widget<widget_filer>(wp, wp_);\n\t\t\tload_ctx_->enable(false);\n\t\t}\n\n\t\t{ // save \u30d5\u30a1\u30a4\u30e9\u30fc\u672c\u4f53\n\t\t\twidget::param wp(vtx::irect(10, 30, 300, 200));\n\t\t\twidget_filer::param wp_(core.get_current_path(), \"\", true);\n\t\t\tsave_ctx_ = wd.add_widget<widget_filer>(wp, wp_);\n\t\t\tsave_ctx_->enable(false);\n\t\t}\n\n\t\t{ // \u30c0\u30a4\u30a2\u30ed\u30b0\n\t\t\twidget::param wp(vtx::irect(10, 30, 450, 200));\n\t\t\twidget_dialog::param wp_;\n\t\t\tdialog_ = wd.add_widget<widget_dialog>(wp, wp_);\n\t\t\tdialog_->enable(false);\n\t\t}\n\t\t{ // \u30c0\u30a4\u30a2\u30ed\u30b0(cancel/ok)\n\t\t\twidget::param wp(vtx::irect(10, 30, 450, 200));\n\t\t\twidget_dialog::param wp_(widget_dialog::style::CANCEL_OK);\n\t\t\tdialog_yes_no_ = wd.add_widget<widget_dialog>(wp, wp_);\n\t\t\tdialog_yes_no_->enable(false);\n\t\t}\n\t\t{ // \u30c0\u30a4\u30a2\u30ed\u30b0(scale)\n\t\t\twidget::param wp(vtx::irect(10, 30, 450, 200));\n\t\t\twidget_dialog::param wp_(widget_dialog::style::CANCEL_OK);\n\t\t\tdialog_scale_ = wd.add_widget<widget_dialog>(wp, wp_);\n\t\t\tdialog_scale_->enable(false);\n\t\t}\n\n\t\tmobj_.initialize();\n\n\t\t// \u30d7\u30ea\u30d5\u30a1\u30ec\u30f3\u30b9\u306e\u53d6\u5f97\n\t\tsys::preference& pre = director_.at().preference_;\n\t\tif(load_ctx_) load_ctx_->load(pre);\n\t\tif(save_ctx_) save_ctx_->load(pre);\n\t\tif(frame_) frame_->load(pre);\n\t\tif(octave_) octave_->load(pre);\n\t\tif(frequency_) frequency_->load(pre);\n\t\tif(gain_) gain_->load(pre);\n\t\tif(pn_menu_) pn_menu_->load(pre);\n\t\tif(tools_) tools_->load(pre, false, false);\n\t\tif(scale_fit_) scale_fit_->load(pre);\n\t\tif(scale_1x_) scale_1x_->load(pre);\n\t\tif(scale_2x_) scale_2x_->load(pre);\n\t\tif(scale_3x_) scale_3x_->load(pre);\n\t\tif(info_) info_->load(pre);\n\t}\n\n\n\t//-----------------------------------------------------------------//\n\t/*!\n\t\t@brief  \u30a2\u30c3\u30d7\u30c7\u30fc\u30c8\n\t*/\n\t//-----------------------------------------------------------------//\n\tvoid pn_main::update()\n\t{\n\t\tgl::core& core = gl::core::get_instance();\n\n\t\tgui::widget_director& wd = director_.at().widget_director_;\n\n\t\tif(update_) {\n\t\t\tif(src_image_) {\n\t\t\t\tcreate_texture_();\n\t\t\t\tblend_();\n\t\t\t\tupdate_ = false;\n\t\t\t}\n\t\t}\n\n\t\tif(scale_) {\n\t\t\tif(scale_->get_selected()) {\n\t\t\t\tbool f = dialog_scale_->get_state(gui::widget::state::ENABLE);\n\t\t\t\tdialog_scale_->enable(!f);\n\t\t\t}\n\t\t}\n\n\t\tstd::string imfn;\n\t\tint id = core.get_recv_files_id();\n\t\tif(dd_id_ != id) {\n\t\t\tdd_id_ = id;\n\t\t\tconst utils::strings& ss = core.get_recv_files_path();\n\t\t\tif(!ss.empty()) {\n\t\t\t\timfn = ss.back();\n\t\t\t}\n\t\t}\n\n\t\tbool load_stall = false;\n\t\tbool save_stall = false;\n\n\t\tif(load_ctx_) {\n\t\t\tif(load_ctx_->get_state(gui::widget::state::ENABLE)) {\n\t\t\t\tsave_stall = true;\n\t\t\t}\n\t\t\tif(load_id_ != load_ctx_->get_select_file_id()) {\n\t\t\t\tload_id_ = load_ctx_->get_select_file_id();\n\t\t\t\timfn = load_ctx_->get_file();\n\t\t\t}\n\t\t}\n\n\t\tif(!imfn.empty()) {\n\t\t\timg::img_files& imf = wd.at_img_files();\n\t\t\tif(!imf.load(imfn)) {\n\t\t\t\tdialog_->set_text(\"Can't decode image file:\\n '\"\n\t\t\t\t\t\t\t\t  + load_ctx_->get_file() + \"'\");\n\t\t\t\tdialog_->enable();\n\t\t\t} else {\n\t\t\t\tsrc_image_ = imf.get_image();\n\t\t\t\tterm_->output(\"Ld\");\n\t\t\t\timage_info_(load_ctx_->get_file(), src_image_.get());\n\t\t\t\timage_offset_.set(0.0f);\n\t\t\t\tframe_->at_local_param().text_param_.set_text(imfn);\n\t\t\t\tupdate_ = true;\n\t\t\t}\n\t\t}\n\n\n\t\t// frame \u5185 image \u306e\u30b5\u30a4\u30ba\u3092\u8a2d\u5b9a\n\t\tif(frame_ && image_) {\n\t\t\tif(!image_->get_local_param().mobj_handle_) {\n\t\t\t\tsave_stall = true;\n\t\t\t}\n\n\t\t\tfloat s = 1.0f;\n\t\t\tif(scale_fit_->get_check()) {\n\t\t\t\tvtx::fpos is = mobj_.get_size(img_handle_);\n\t\t\t\tvtx::fpos ss = image_->at_rect().size;\n\t\t\t\tvtx::fpos sc = ss / is;\n\t\t\t\tif(sc.x < sc.y) s = sc.x; else s = sc.y;\n\t\t\t\timage_->at_local_param().offset_ = 0.0f;\n\t\t\t} else {\n\t\t\t\tif(scale_1x_->get_check()) s = 1.0f;\n \t\t\t\telse if(scale_2x_->get_check()) s = 2.0f;\n \t\t\t\telse if(scale_3x_->get_check()) s = 3.0f;\n\n\t\t\t\tif(image_->get_select_in()) {\n\t\t\t\t\timage_offset_ = image_->get_local_param().offset_;\n\t\t\t\t}\n\t\t\t\tif(image_->get_select()) {\n\t\t\t\t\tvtx::ipos d = image_->get_param().move_pos_ - image_->get_param().move_org_;\n\t\t\t\t\timage_->at_local_param().offset_ = image_offset_ + d / s;\n\t\t\t\t}\n\t\t\t}\n\t\t\timage_->at_local_param().scale_ = s;\n\n\t\t\t//\u30a8\u30ea\u30a2\u306e\u4f5c\u6210\n///\t\t\tarea_->at_param().rect_.org.set(0);\n///\t\t\tarea_->at_param().rect_.size = frame_->get_param().rect_.size;\n\t\t}\n\n\t\tif(save_ctx_) {\n\t\t\tif(save_ctx_->get_state(gui::widget::state::ENABLE)) {\n\t\t\t\tload_stall = true;\n\t\t\t}\n\t\t\tif(save_id_ != save_ctx_->get_select_file_id()) {\n\t\t\t\tsave_id_ = save_ctx_->get_select_file_id();\n\t\t\t\tconst std::string& fn = save_ctx_->get_file();\n\t\t\t\tif(utils::probe_file(fn)) {\n\t\t\t\t\tdialog_yes_no_->set_text(\"Over write ?:\\n'\"\n\t\t\t\t\t\t\t\t\t\t\t + fn + \"'\");\n\t\t\t\t\tdialog_yes_no_->enable();\n\t\t\t\t\tsave_dialog_ = true;\n\t\t\t\t} else {\n\t\t\t\t\tsave_dialog_ = false;\n\t\t\t\t}\n\t\t\t\tsave_file_name_ = fn;\n\t\t\t}\n\t\t}\n\n\t\tload_->set_state(gui::widget::state::STALL, load_stall);\n\t\tsave_->set_state(gui::widget::state::STALL, save_stall);\n\n\t\twd.update();\n\n\t\tif(!save_file_name_.empty()) {\n\t\t\tsave_t t = std::make_tuple(save_file_name_, src_image_);\n\t\t\tif(!save_task_(t)) {\n\t\t\t\tdialog_->set_text(\"Can't encode image file:\\n'\"\n\t\t\t\t\t\t\t\t  + save_file_name_ + \"'\");\n\t\t\t\tdialog_->enable();\n\t\t\t} else {\n\t\t\t\tterm_->output(\"Sv\");\n\t\t\t\timage_info_(save_file_name_, src_image_.get());\n\t\t\t}\n\t\t\tsave_file_name_.clear();\n#if 0\n\t\t\tif(image_saver_.valid()) {\n\t\t\t\tif(!image_saver_.get()) {\n\t\t\t\t\tdialog_->set_text(\"Can't encode image file:\\n'\"\n\t\t\t\t\t\t\t\t\t  + save_file_name_ + \"'\");\n\t\t\t\t\tdialog_->enable();\n\t\t\t\t} else {\n\t\t\t\t\tterm_->output(\"Sv\");\n\t\t\t\t\timage_info_(save_file_name_, src_image_.get());\n\t\t\t\t}\n\t\t\t\tsave_file_name_.clear();\n\t\t\t} else {\n\t\t\t\tbool launch = false;\n\t\t\t\tif(save_dialog_) {\n\t\t\t\t\tif(!dialog_yes_no_->get_state(gui::widget::state::ENABLE)) {\n\t\t\t\t\t\tif(dialog_yes_no_->get_local_param().return_ok_) {\n\t\t\t\t\t\t\tlaunch = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tlaunch = true;\n\t\t\t\t}\n\t\t\t\tif(launch) {\n\t\t\t\t\tsave_t t = std::make_tuple(save_file_name_, src_image_);\n\t\t\t\t\timage_saver_ = std::async(std::launch::async, save_task_, t);\n\t\t\t\t}\n\t\t\t}\n#endif\n\t\t}\n\t}\n\n\n\t//-----------------------------------------------------------------//\n\t/*!\n\t\t@brief  \u30ec\u30f3\u30c0\u30ea\u30f3\u30b0\n\t*/\n\t//-----------------------------------------------------------------//\n\tvoid pn_main::render()\n\t{\n\t\tdirector_.at().widget_director_.service();\n\t\tdirector_.at().widget_director_.render();\n\t}\n\n\n\t//-----------------------------------------------------------------//\n\t/*!\n\t\t@brief  \u5ec3\u68c4\n\t*/\n\t//-----------------------------------------------------------------//\n\tvoid pn_main::destroy()\n\t{\n\t\tsys::preference& pre = director_.at().preference_;\n\t\tif(load_ctx_) load_ctx_->save(pre);\n\t\tif(save_ctx_) save_ctx_->save(pre);\n\t\tif(frame_) frame_->save(pre);\n\t\tif(tools_) tools_->save(pre);\n\t\tif(octave_) octave_->save(pre);\n\t\tif(frequency_) frequency_->save(pre);\n\t\tif(gain_) gain_->save(pre);\n\t\tif(pn_menu_) pn_menu_->save(pre);\n\t\tif(scale_fit_) scale_fit_->save(pre);\n\t\tif(scale_1x_) scale_1x_->save(pre);\n\t\tif(scale_2x_) scale_2x_->save(pre);\n\t\tif(scale_3x_) scale_3x_->save(pre);\n\t\tif(info_) info_->save(pre);\n\t}\n}\n", "meta": {"hexsha": "21dcde6b5903c3d5364ce2dae0a9b00724c81164", "size": 14500, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "glfw3_app/pn/pn_main.cpp", "max_stars_repo_name": "hirakuni45/glfw3_app", "max_stars_repo_head_hexsha": "d9ceeef6d398229fda4849afe27f8b48d1597fcf", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2015-09-22T21:36:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-01T09:16:53.000Z", "max_issues_repo_path": "glfw3_app/pn/pn_main.cpp", "max_issues_repo_name": "hirakuni45/glfw3_app", "max_issues_repo_head_hexsha": "d9ceeef6d398229fda4849afe27f8b48d1597fcf", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "glfw3_app/pn/pn_main.cpp", "max_forks_repo_name": "hirakuni45/glfw3_app", "max_forks_repo_head_hexsha": "d9ceeef6d398229fda4849afe27f8b48d1597fcf", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-02-21T04:22:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-02T17:24:32.000Z", "avg_line_length": 28.4872298625, "max_line_length": 88, "alphanum_fraction": 0.5913103448, "num_tokens": 4760, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.45215118495658924}}
{"text": "#include <boost/math/special_functions/bessel.hpp>\n#include <iostream>\n#include <iterator>\n#include <algorithm>\n\nint main()\n{\n    using namespace boost::math;\n    std::cout << cyl_bessel_i(1000, 10) << \" \" << std::endl;\n}", "meta": {"hexsha": "18ca3f8fbd8e1a0c43e98ee13f6584d5679c4b02", "size": 221, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "try_code/try_cython/try_boost.cpp", "max_stars_repo_name": "pcmagic/stokes_flow", "max_stars_repo_head_hexsha": "464d512d3739eee77b33d1ebf2f27dae6cfa0423", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-11-11T05:00:53.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-11T05:00:53.000Z", "max_issues_repo_path": "try_code/try_cython/try_boost.cpp", "max_issues_repo_name": "pcmagic/stokes_flow", "max_issues_repo_head_hexsha": "464d512d3739eee77b33d1ebf2f27dae6cfa0423", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "try_code/try_cython/try_boost.cpp", "max_forks_repo_name": "pcmagic/stokes_flow", "max_forks_repo_head_hexsha": "464d512d3739eee77b33d1ebf2f27dae6cfa0423", "max_forks_repo_licenses": ["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.1, "max_line_length": 60, "alphanum_fraction": 0.6787330317, "num_tokens": 59, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.9111797100118214, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.45203063167596635}}
{"text": "/*=============================================================================\nCopyright 2020 Syed Ali Hasan <alihasan9922@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_HORIZON_COORD_HPP\n#define BOOST_ASTRONOMY_HORIZON_COORD_HPP\n\n#include <iostream>\n#include <boost/static_assert.hpp>\n#include <boost/geometry/core/cs.hpp>\n#include <boost/units/get_dimension.hpp>\n#include <boost/geometry/geometries/point.hpp>\n#include <boost/units/systems/si/plane_angle.hpp>\n#include <boost/units/systems/si/dimensionless.hpp>\n#include <boost/units/physical_dimensions/plane_angle.hpp>\n#include <boost/astronomy/coordinate/coord_sys/coord_sys.hpp>\n\n/**\n * The Horizon Coordinates, Altitude and Azimuth, of an object\n * in the sky are referred to the plane of the observer\u2019s horizon\n *\n * Azimuth\n * THe Azimuth, is in the range of 0\u25e6 to 360\u25e6 and indicates how far an object\n * in the sky is from the north as measured along an observer\u2019s horizon.\n *\n * Altitude\n * The Altitude, represented by the symbol h, and ranges from \u221290\u25e6 to +90\u25e6.\n * Positive altitudes indicate objects above the horizon while negative\n * altitudes indicate objects below the horizon.\n *\n**/\n\nnamespace boost { namespace astronomy { namespace coordinate {\n\nnamespace bu = boost::units;\nnamespace bg = boost::geometry;\n\ntemplate\n<\n    typename CoordinateType = double,\n    typename AltitudeQuantity = bu::quantity<bu::si::plane_angle, CoordinateType>,\n    typename AzimuthQuantity = bu::quantity<bu::si::plane_angle, CoordinateType>\n>\nstruct horizon_coord : public coord_sys\n    <2, bg::cs::spherical<bg::radian>, CoordinateType>\n{\n  ///@cond INTERNAL\n  BOOST_STATIC_ASSERT_MSG(\n      ((std::is_same<typename bu::get_dimension<AltitudeQuantity>::type,\n          bu::plane_angle_dimension>::value) &&\n       (std::is_same<typename bu::get_dimension<AzimuthQuantity>::type,\n           bu::plane_angle_dimension>::value)),\n      \"Altitude and Azimuth 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\npublic:\n    typedef AltitudeQuantity quantity1;\n    typedef AzimuthQuantity quantity2;\n\n    //Default constructor\n    horizon_coord() {}\n\n    horizon_coord\n    (\n        AltitudeQuantity const &Altitude,\n        AzimuthQuantity const &Azimuth\n    )\n    {\n        this->set_altitude_azimuth(Altitude, Azimuth);\n    }\n\n    //Create tuple of Altitude and Azimuth\n    std::tuple<AltitudeQuantity, AzimuthQuantity> get_altitude_azimuth() const\n    {\n        return std::make_tuple(this->get_altitude(), this->get_azimuth());\n    }\n\n    //Get Altitude\n    AltitudeQuantity get_altitude() const\n    {\n        return static_cast<AltitudeQuantity>\n            (\n                bu::quantity<bu::si::plane_angle, CoordinateType>::from_value\n                        (bg::get<0>(this->point))\n            );\n    }\n\n    //Get Azimuth\n    AzimuthQuantity get_azimuth() const\n    {\n        return static_cast<AzimuthQuantity>\n            (\n                bu::quantity<bu::si::plane_angle, CoordinateType>::from_value\n                        (bg::get<1>(this->point))\n            );\n    }\n\n    //Set value of Altitude and Azimuth\n    void set_altitude_azimuth\n    (\n        AltitudeQuantity const &Altitude,\n        AzimuthQuantity const &Azimuth\n    )\n    {\n        this->set_altitude(Altitude);\n        this->set_azimuth(Azimuth);\n    }\n\n    //Set Altitude\n    void set_altitude(AltitudeQuantity const &Altitude)\n    {\n        bg::set<0>\n            (\n                this->point,\n                static_cast<bu::quantity<bu::si::plane_angle, CoordinateType>>(Altitude).value()\n            );\n    }\n\n    //Set Azimuth\n    void set_azimuth(AzimuthQuantity const &Azimuth)\n    {\n        bg::set<1>\n            (\n                this->point,\n                static_cast<bu::quantity<bu::si::plane_angle, CoordinateType>>(Azimuth).value()\n            );\n    }\n\n}; //horizon_coord\n\n//Make Horizon Coordinate\ntemplate\n<\n    typename CoordinateType,\n    template<typename Unit1, typename CoordinateType_> class AltitudeQuantity,\n    template<typename Unit2, typename CoordinateType_> class AzimuthQuantity,\n    typename Unit1,\n    typename Unit2\n>\nhorizon_coord\n<\n    CoordinateType,\n    AltitudeQuantity<Unit1, CoordinateType>,\n    AzimuthQuantity<Unit2, CoordinateType>\n> make_horizon_coord\n(\n    AltitudeQuantity<Unit1, CoordinateType> const &Altitude,\n    AzimuthQuantity<Unit2, CoordinateType> const &Azimuth\n)\n{\n    return horizon_coord\n        <\n            CoordinateType,\n            AltitudeQuantity<Unit1, CoordinateType>,\n            AzimuthQuantity<Unit2, CoordinateType>\n        > (Altitude, Azimuth);\n}\n\n//Print Horizon Coordinates\ntemplate\n<\n    typename CoordinateType,\n    class AltitudeQuantity,\n    class AzimuthQuantity\n>\nstd::ostream &operator << (std::ostream &out, horizon_coord\n        <CoordinateType, AltitudeQuantity, AzimuthQuantity> const &point) {\n    out << \"Horizon Coordinate (Altitude: \"\n        << point.get_altitude() << \", Azimuth: \"\n        << point.get_azimuth() << \")\";\n\n    return out;\n}\n\n}}}\n\n#endif //BOOST_ASTRONOMY_HORIZON_COORD_HPP\n", "meta": {"hexsha": "11a712cbbc5be74bd73ff43e50735a03148f1077", "size": 5377, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/astronomy/coordinate/coord_sys/horizon_coord.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/coord_sys/horizon_coord.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/coord_sys/horizon_coord.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.543956044, "max_line_length": 96, "alphanum_fraction": 0.6531523154, "num_tokens": 1260, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723317123102955, "lm_q2_score": 0.6723317123102956, "lm_q1q2_score": 0.45202993137809405}}
{"text": "#include <stan/math/prim/scal.hpp>\n#include <gtest/gtest.h>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/math/distributions.hpp>\n\nTEST(ProbDistributionsNegBinomial, error_check) {\n  boost::random::mt19937 rng;\n  EXPECT_NO_THROW(stan::math::neg_binomial_2_rng(6, 2, rng));\n  EXPECT_NO_THROW(stan::math::neg_binomial_2_rng(0.5, 1, rng));\n  EXPECT_NO_THROW(stan::math::neg_binomial_2_rng(1e8, 1, rng));\n\n  EXPECT_THROW(stan::math::neg_binomial_2_rng(0, -2, rng),\n                 std::domain_error);\n  EXPECT_THROW(stan::math::neg_binomial_2_rng(6, -2, rng),\n                   std::domain_error);\n  EXPECT_THROW(stan::math::neg_binomial_2_rng(-6, -0.1, rng),\n                   std::domain_error);\n  EXPECT_THROW(stan::math::neg_binomial_2_rng(\n                 stan::math::positive_infinity(), 2, rng),\n                 std::domain_error);\n  EXPECT_THROW(stan::math::neg_binomial_2_rng(\n                 stan::math::positive_infinity(), 6, rng),\n                 std::domain_error);\n  EXPECT_THROW(stan::math::neg_binomial_2_rng(2,\n                 stan::math::positive_infinity(), rng),\n                 std::domain_error);\n\n  std::string error_msg;\n\n  error_msg = \"neg_binomial_2_rng: Location parameter \"\n              \"divided by the precision parameter is \"\n              \"inf, but must be finite!\";\n  try {\n    stan::math::neg_binomial_2_rng(1e300, 1e-300, rng);\n    FAIL() << \"neg_binomial_2_rng should have thrown\" << std::endl;\n  } catch (const std::exception& e) {\n    if (std::string(e.what()).find(error_msg) == std::string::npos)\n      FAIL() << \"Error message is different than expected\" << std::endl\n             << \"EXPECTED: \" << error_msg << std::endl\n             << \"FOUND: \" << e.what() << std::endl;\n    SUCCEED();\n  }\n\n  error_msg = \"neg_binomial_2_rng: Random number that \"\n              \"came from gamma distribution is\";\n  try {\n    stan::math::neg_binomial_2_rng(1e10, 1e20, rng);\n    FAIL() << \"neg_binomial_2_rng should have thrown\" << std::endl;\n  } catch (const std::exception& e) {\n    if (std::string(e.what()).find(error_msg) == std::string::npos)\n      FAIL() << \"Error message is different than expected\" << std::endl\n             << \"EXPECTED: \" << error_msg << std::endl\n             << \"FOUND: \" << e.what() << std::endl;\n    SUCCEED();\n  }\n}\n\nTEST(ProbDistributionsNegBinomial, chiSquareGoodnessFitTest) {\n  boost::random::mt19937 rng;\n  int N = 1000;\n  int K = boost::math::round(2 * std::pow(N, 0.4));\n  boost::math::negative_binomial_distribution<>dist (1.1, 1.1/(1.1+2.4));\n  boost::math::chi_squared mydist(K-1);\n\n  int loc[K - 1];\n  for(int i = 1; i < K; i++)\n    loc[i - 1] = i - 1;\n\n  int count = 0;\n  double bin [K];\n  double expect [K];\n  for(int i = 0 ; i < K; i++)  {\n    bin[i] = 0;\n    expect[i] = N * pdf(dist, i);\n  }\n  expect[K-1] = N * (1 - cdf(dist, K - 1));\n\n  while (count < N) {\n    int a = stan::math::neg_binomial_2_rng(2.4, 1.1, rng);\n    int i = 0;\n    while (i < K-1 && a > loc[i])\n      ++i;\n    ++bin[i];\n    count++;\n   }\n\n  double chi = 0;\n\n  for(int j = 0; j < K; j++)\n    chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) / expect[j]);\n\n  EXPECT_TRUE(chi < quantile(complement(mydist, 1e-6)));\n}\n\nTEST(ProbDistributionsNegBinomial, chiSquareGoodnessFitTest2) {\n  boost::random::mt19937 rng;\n  int N = 1000;\n  int K = boost::math::round(2 * std::pow(N, 0.4));\n  boost::math::negative_binomial_distribution<>dist (0.6, 0.6/(0.6+2.4));\n  boost::math::chi_squared mydist(K-1);\n\n  int loc[K - 1];\n  for(int i = 1; i < K; i++)\n    loc[i - 1] = i - 1;\n\n  int count = 0;\n  double bin [K];\n  double expect [K];\n  for(int i = 0 ; i < K; i++)  {\n    bin[i] = 0;\n    expect[i] = N * pdf(dist, i);\n  }\n  expect[K-1] = N * (1 - cdf(dist, K - 1));\n\n  while (count < N) {\n    int a = stan::math::neg_binomial_2_rng(2.4, 0.6, rng);\n    int i = 0;\n    while (i < K-1 && a > loc[i])\n      ++i;\n    ++bin[i];\n    count++;\n   }\n\n  double chi = 0;\n\n  for(int j = 0; j < K; j++)\n    chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) / expect[j]);\n\n  EXPECT_TRUE(chi < quantile(complement(mydist, 1e-6)));\n}\n\nTEST(ProbDistributionsNegBinomial, chiSquareGoodnessFitTest3) {\n  boost::random::mt19937 rng;\n  int N = 1000;\n  int K = boost::math::round(2 * std::pow(N, 0.4));\n  boost::math::negative_binomial_distribution<>dist (30, 30/(30+60.4));\n  boost::math::chi_squared mydist(K-1);\n\n  int loc[K - 1];\n  for(int i = 1; i < K; i++)\n    loc[i - 1] = i - 1;\n\n  int count = 0;\n  double bin [K];\n  double expect [K];\n  for(int i = 0 ; i < K; i++)  {\n    bin[i] = 0;\n    expect[i] = N * pdf(dist, i);\n  }\n  expect[K-1] = N * (1 - cdf(dist, K - 1));\n\n  while (count < N) {\n    int a = stan::math::neg_binomial_2_rng(60.4, 30, rng);\n    int i = 0;\n    while (i < K-1 && a > loc[i])\n      ++i;\n    ++bin[i];\n    count++;\n   }\n\n  double chi = 0;\n\n  for(int j = 0; j < K; j++)\n    chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) / expect[j]);\n\n  EXPECT_TRUE(chi < quantile(complement(mydist, 1e-6)));\n}\n\nTEST(ProbDistributionsNegBinomial, chiSquareGoodnessFitTest4) {\n  boost::random::mt19937 rng;\n  int N = 1000;\n  int K = boost::math::round(2 * std::pow(N, 0.4));\n  boost::math::negative_binomial_distribution<>dist (80, 80/(80+30.4));\n  boost::math::chi_squared mydist(K-1);\n\n  int loc[K - 1];\n  for(int i = 1; i < K; i++)\n    loc[i - 1] = i - 1;\n\n  int count = 0;\n  double bin [K];\n  double expect [K];\n  for(int i = 0 ; i < K; i++)  {\n    bin[i] = 0;\n    expect[i] = N * pdf(dist, i);\n  }\n  expect[K-1] = N * (1 - cdf(dist, K - 1));\n\n  while (count < N) {\n    int a = stan::math::neg_binomial_2_rng(30.4, 80, rng);\n    int i = 0;\n    while (i < K-1 && a > loc[i])\n      ++i;\n    ++bin[i];\n    count++;\n   }\n\n  double chi = 0;\n\n  for(int j = 0; j < K; j++)\n    chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) / expect[j]);\n\n  EXPECT_TRUE(chi < quantile(complement(mydist, 1e-6)));\n}\n\nTEST(ProbDistributionsNegBinomial, extreme_values) {\n  int N = 100;\n  double mu = 8;\n  double phi = 1e12;\n  for (int n = 0; n < 10; ++n) {\n    phi *= 10;\n    double logp = stan::math::neg_binomial_2_log<false>(N, mu, phi);\n    EXPECT_TRUE(logp < 0);\n  }\n}\n", "meta": {"hexsha": "60eef151dd5821513180f5bfcee306a75aed12e6", "size": 6109, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/scal/prob/neg_binomial_2_test.cpp", "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/test/unit/math/prim/scal/prob/neg_binomial_2_test.cpp", "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/test/unit/math/prim/scal/prob/neg_binomial_2_test.cpp", "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": 28.2824074074, "max_line_length": 73, "alphanum_fraction": 0.5658863971, "num_tokens": 2117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723317123102956, "lm_q2_score": 0.672331705744791, "lm_q1q2_score": 0.45202992696389716}}
{"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 <gtest/gtest.h>\n#include <vw/Math/MatrixSparseSkyline.h>\n\nusing namespace vw;\nusing namespace vw::math;\n\nstatic const double DELTA = 1e-4;\n\n// This is a fix for old versions of boost, the distribution uniform_01\n// was implemented with expectations of working with the variate generator.\n// instead we switch over to uniform_real as a backup solution in old boost.\n#if BOOST_VERSION <= 103800\n\n#include <boost/random/uniform_real.hpp>\n#define UNIFORM01 boost::uniform_real\n\n#else\n\n#include <boost/random/uniform_01.hpp>\n#define UNIFORM01 boost::uniform_01\n\n#endif\n\n#include <boost/random.hpp>\n\ntemplate <class GenT>\nVector<size_t> create_test_skyline(size_t size, size_t max_offset,\n                                   GenT& generator ) {\n  Vector<size_t> result(size);\n  for ( size_t i = 0; i < size; ++i ) {\n    ssize_t offset(i - size_t(generator()*(max_offset-1)) );\n    if ( offset < 0 ) offset = 0;\n    result[i] = static_cast<size_t>(offset);\n  }\n  return result;\n}\n\ntemplate <class VectorT, class GenT>\nvoid fill_vector(VectorT& b, GenT& generator) {\n  for ( size_t i = 0; i < b.size(); ++i )\n    b[i] = lround(generator()*100)+1;\n}\n\ntemplate <class MatrixT, class GenT>\nvoid fill_symmetric_matrix(MatrixT& A, Vector<size_t> const& skyline,\n                           GenT& generator ) {\n  for (size_t i = 0; i < A.rows(); ++i)\n    for (size_t j = skyline[i]; j < std::min(i+1,A.cols()); ++j) {\n      A(i,j) = lround(generator()*100)+1;\n      A(j,i) = A(i,j);\n    }\n}\n\n// Unoptimized LDLT decomposition\ntemplate <class MatrixT>\nvoid ldl_decomposition(MatrixT& A) {\n  VW_ASSERT(A.cols() == A.rows(), ArgumentErr() << \"ldl_decomposition: argument must be square and symmetric.\\n\");\n  for (size_t j = 0; j < A.cols(); ++j) {\n\n    // Compute v(1:j)\n    std::vector<double> v(j+1);\n    v[j] = A(j,j);\n    for (size_t i = 0; i < j; ++i) {\n      v[i] = A(j,i)*A(i,i);\n      v[j] -= A(j,i)*v[i];\n    }\n\n    // Store d(j) and compute L(j+1:n,j)\n    A(j,j) = v[j];\n    for (size_t i = j+1; i < A.cols(); ++i) {\n      double row_sum = 0;\n      for (size_t jj = 0; jj < j; ++jj)\n        row_sum += A(i,jj)*v[jj];\n      A(i,j) = ( A(i,j)-row_sum ) / v[j];\n    }\n  }\n}\n\n// Creating a Buckey Ball Sparse Skyline Matrix\ntemplate <class ElemT>\nvoid fill_with_buckeyball(MatrixSparseSkyline<ElemT>& A) {\n  A(2,1) = 1; A(5,1) = 1; A(6,1) = 1; A(3,2) = 1; A(11,2) = 1;\n  A(2,3) = 1; A(4,3) = 1; A(16,3) = 1; A(5,4) = 1; A(21,4) = 1;\n  A(26,5) = 1; A(7,6) = 1; A(10,6) = 1; A(8,7) = 1; A(30,7) = 1;\n  A(9,8) = 1; A(42,8) = 1; A(10,9) = 1; A(38,9) = 1; A(12,10) = 1;\n  A(12,11) = 1; A(15,11) = 1; A(13,12) = 1; A(14,13) = 1; A(37,13) = 1;\n  A(15,14) = 1; A(33,14) = 1; A(17,15) = 1; A(17,16) = 1; A(20,16) = 1;\n  A(18,17) = 1; A(19,18) = 1; A(32,18) = 1; A(20,19) = 1; A(53,19) = 1;\n  A(22,20) = 1; A(22,21) = 1; A(25,21) = 1; A(23,22) = 1; A(24,23) = 1;\n  A(52,23) = 1; A(25,24) = 1; A(48,24) = 1; A(27,25) = 1; A(27,26) = 1;\n  A(30,26) = 1; A(28,27) = 1; A(29,28) = 1; A(47,28) = 1; A(30,29) = 1;\n  A(43,29) = 1; A(32,31) = 1; A(35,31) = 1; A(54,31) = 1; A(33,32) = 1;\n  A(34,33) = 1; A(35,34) = 1; A(36,34) = 1; A(56,35) = 1; A(37,36) = 1;\n  A(40,36) = 1; A(38,37) = 1; A(39,38) = 1; A(40,39) = 1; A(41,39) = 1;\n  A(57,40) = 1; A(42,41) = 1; A(45,41) = 1; A(43,42) = 1; A(44,43) = 1;\n  A(45,44) = 1; A(46,44) = 1; A(58,45) = 1; A(47,46) = 1; A(50,46) = 1;\n  A(48,47) = 1; A(49,48) = 1; A(50,49) = 1; A(51,49) = 1; A(59,50) = 1;\n  A(52,51) = 1; A(55,51) = 1; A(53,52) = 1; A(54,53) = 1; A(55,54) = 1;\n  A(60,55) = 1; A(57,56) = 1; A(60,56) = 1; A(58,57) = 1; A(59,58) = 1;\n  A(60,59) = 1;\n}\n\nTEST(SparseSkyline, Creation ) {\n  MatrixSparseSkyline<double> sparse(4);\n  sparse(0,0) = 1;\n  sparse(0,1) = 2;\n  sparse(0,2) = 3;\n  sparse(0,3) = 4;\n  sparse(1,1) = 5;\n  EXPECT_EQ( sparse(1,0), sparse(0,1) );\n  EXPECT_EQ( sparse(2,0), sparse(0,2) );\n  EXPECT_EQ( sparse(3,0), 4 );\n\n  Vector<double> cv = select_col(sparse,0);\n  ASSERT_EQ( 4u, cv.size() );\n  EXPECT_EQ( 1, cv(0) );\n  EXPECT_EQ( 2, cv(1) );\n  EXPECT_EQ( 3, cv(2) );\n  EXPECT_EQ( 4, cv(3) );\n\n  cv = select_col(sparse,1);\n  ASSERT_EQ( 4u, cv.size() );\n  EXPECT_EQ( 2, cv(0) );\n  EXPECT_EQ( 5, cv(1) );\n  EXPECT_EQ( 0, cv(2) );\n  EXPECT_EQ( 0, cv(3) );\n\n  Vector<double> rv = select_row(sparse,2);\n  ASSERT_EQ( 4u, rv.size() );\n  EXPECT_EQ( 3, rv(0) );\n  EXPECT_EQ( 0, rv(1) );\n  EXPECT_EQ( 0, rv(2) );\n  EXPECT_EQ( 0, rv(3) );\n}\n\nTEST(SparseSkyline, LDL_decomp_correctness) {\n  size_t N = 50;\n  size_t S = 10;\n  boost::mt19937 random_gen(86);\n  typedef boost::variate_generator<boost::mt19937&,UNIFORM01<> > vargen_type;\n  vargen_type generator( random_gen, UNIFORM01<>() );\n\n  MatrixSparseSkyline<double> sparse_mat(N);\n\n  Vector<size_t> test_skyline = create_test_skyline(N, S, generator);\n\n  fill_symmetric_matrix(sparse_mat, test_skyline, generator);\n  Matrix<double> nonsparse_mat = sparse_mat;\n  MatrixSparseSkyline<double> original_sparse_mat = sparse_mat;\n\n  sparse_ldl_decomposition(sparse_mat);\n  for ( size_t i = 0; i < N; i++ )\n    for ( size_t j = 0; j < N; j++ )\n      if ( (sparse_mat(i,j) == 0)^(original_sparse_mat(i,j) == 0) )\n        FAIL() << \"Sparse structure was not preserved by sparse LDLT decomposition.\\nIndex(\" << i << \",\" << j << \") is \" << sparse_mat(i,j) << \" and \" << original_sparse_mat(i,j) << \"\\n\";\n\n  ldl_decomposition(nonsparse_mat);\n\n  for ( size_t i = 0; i < N; i++ )\n    for ( size_t j = 0; j < i; j++ )\n      EXPECT_NEAR(sparse_mat(i,j),nonsparse_mat(i,j),DELTA);\n}\n\nTEST(SparseSkyline, LDL_decomp_scalability) {\n  size_t N = 5000;\n  size_t S = 150;\n  boost::mt19937 random_gen(86);\n  typedef boost::variate_generator<boost::mt19937&,UNIFORM01<> > vargen_type;\n  vargen_type generator( random_gen, UNIFORM01<>() );\n\n  MatrixSparseSkyline<double> sparse_mat(N,N);\n  MatrixSparseSkyline<double> original_sparse_mat(N,N);\n  Vector<size_t> test_skyline = create_test_skyline(N,S,generator);\n\n  fill_symmetric_matrix(sparse_mat, test_skyline, generator);\n  original_sparse_mat = sparse_mat;\n\n  sparse_ldl_decomposition(sparse_mat);\n  for ( size_t i = 0; i < N; i++ )\n    for ( size_t j = 0; j < i; j++ )\n      if ( (sparse_mat(i,j) == 0)^(original_sparse_mat(i,j) == 0) )\n        FAIL() << \"Sparse structure was not preserved by sparse LDLT decomposition.\\nIndex(\" << i << \",\" << j << \") is \" << sparse_mat(i,j) << \" and \" << original_sparse_mat(i,j) << \"\\n\";\n}\n\nTEST(SparseSkyline, LDL_solve) {\n  size_t N = 50;\n  size_t S = 10;\n  boost::mt19937 random_gen(42);\n  typedef boost::variate_generator<boost::mt19937&,UNIFORM01<> > vargen_type;\n  vargen_type generator( random_gen, UNIFORM01<>() );\n\n  Matrix<double> A_nonsparse(N,N);\n  MatrixSparseSkyline<double> A_sparse(N,N);\n  Vector<size_t> test_skyline = create_test_skyline(N,S,generator);\n\n  fill_symmetric_matrix(A_sparse, test_skyline, generator);\n  MatrixSparseSkyline<double> A_sparse_original = A_sparse;\n  EXPECT_EQ( A_sparse.cols(), A_sparse_original.cols() );\n  EXPECT_EQ( A_sparse.rows(), A_sparse_original.rows() );\n  A_nonsparse = A_sparse;\n\n  // Create a vector to solve against\n  Vector<double> b(N);\n  fill_vector(b,generator);\n\n  // Solve using normal\n  Vector<double> x_nonsparse = inverse(A_nonsparse)*b;\n\n  // Sparse Version\n  Vector<double> x_sparse = sparse_solve(A_sparse, b);\n\n  for ( size_t i = 0; i < N; i++ )\n    EXPECT_NEAR( x_nonsparse[i], x_sparse[i], DELTA );\n\n  // Back checking (also showing off that multiplication is possible)\n  Vector<double> b_prime = A_sparse_original*x_sparse;\n  for ( size_t i = 0; i < N; i++ )\n    EXPECT_NEAR( b_prime[i], b[i], DELTA );\n}\n\nTEST(SparseSkyline, LDL_solve_scalability) {\n  int N = 1000;\n  int S = 100;\n  boost::mt19937 random_gen(86);\n  typedef boost::variate_generator<boost::mt19937&,UNIFORM01<> > vargen_type;\n  vargen_type generator( random_gen, UNIFORM01<>() );\n\n  MatrixSparseSkyline<double> A_sparse(N,N);\n  Vector<size_t> test_skyline = create_test_skyline(N,S,generator);\n  fill_symmetric_matrix(A_sparse, test_skyline, generator);\n\n  // Create a vector to solve against\n  Vector<double> b(A_sparse.cols());\n  fill_vector(b,generator);\n\n  // Solving for X\n  Vector<double> x_result = sparse_solve(A_sparse, b);\n}\n\n// Rearrangement data types\nTEST(SparseSkyline, VectorReorganize) {\n  std::vector<size_t> lookup;\n  lookup.push_back(2);\n  lookup.push_back(0);\n  lookup.push_back(1);\n  Vector3f vec(1,2,3);\n\n  VectorReorganize<Vector3f> rvec(vec, lookup);\n  EXPECT_EQ(rvec(0),3);\n  EXPECT_EQ(rvec(1),1);\n  EXPECT_EQ(rvec(2),2);\n\n  // Testing a convenience function\n  Vector3f nrvec = reorganize(vec, lookup);\n  EXPECT_EQ(nrvec(0),3);\n  EXPECT_EQ(nrvec(1),1);\n  EXPECT_EQ(nrvec(2),2);\n\n  // Reording back into self\n  nrvec = reorganize(nrvec, rvec.inverse());\n  for ( size_t i = 0; i < nrvec.size(); i++ )\n    EXPECT_EQ(nrvec[i],vec[i]);\n}\n\nTEST(SparseSkyline, VectorLargeReorganize) {\n  // Different from above in that this will actually invoke the\n  // VectorAssignImpl that calls std::copy and uses the iterators.\n  std::vector<size_t> lookup;\n  Vector<float> lvec(10);\n  for ( size_t i = 0, j = 9; i < 10; i++, j-- ) {\n    lookup.push_back(j);\n    lvec[i] = (i+2)*0.5f;\n  }\n\n  VectorReorganize<Vector<float> > rlvec2(lvec, lookup);\n  for ( size_t i = 0; i < 10; i++ )\n    EXPECT_EQ( rlvec2[i], lvec[lookup[i]] );\n\n  Vector<float> rlvec3 = rlvec2;\n  for ( size_t i = 0; i < 10; i++ )\n    EXPECT_EQ( rlvec3[i], lvec[lookup[i]] );\n}\n\nTEST(SparseSkyline, MatrixReorganize) {\n  std::vector<size_t> lookup;\n  lookup.push_back(2);\n  lookup.push_back(0);\n  lookup.push_back(1);\n  Matrix3x3f mat;\n  mat(0,0) = 1;\n  mat(1,1) = 2;\n  mat(2,2) = 3;\n  mat(0,1) = 4;\n  mat(0,2) = 6;\n\n  MatrixReorganize<Matrix3x3f> rmat(mat, lookup);\n  EXPECT_EQ(rmat(0,0), 3);\n  EXPECT_EQ(rmat(1,2), 4);\n  EXPECT_EQ(rmat(1,0), 6);\n\n  // Testing convenience function\n  Matrix3x3f nrmat = reorganize(mat, lookup);\n  EXPECT_EQ(nrmat(0,0), 3);\n  EXPECT_EQ(nrmat(1,2), 4);\n  EXPECT_EQ(nrmat(1,0), 6);\n\n  // Reordering back into self\n  nrmat = reorganize(nrmat, rmat.inverse());\n  for ( size_t i = 0; i < nrmat.cols(); i++ )\n    EXPECT_EQ(nrmat(i,i),mat(i,i));\n}\n\nTEST(SparseSkyline, MatrixLargeReorganize) {\n  std::vector<size_t> lookup;\n  Matrix<float> mat(10,10);\n  for ( size_t i = 0, j = 9; i < 10; i++, j-- ) {\n    lookup.push_back(j);\n    for ( size_t k = 0; k <= i; k++ ) {\n      mat(i,k) = i*k*0.5+2;\n      mat(k,i) = mat(i,k);\n    }\n  }\n\n  MatrixReorganize<Matrix<float> > rmat(mat, lookup);\n  for ( size_t i = 0; i < 10; i++ )\n    EXPECT_EQ( rmat(i,i), mat(lookup[i],lookup[i]) );\n\n  Matrix<float> rmat_copy = rmat;\n  for ( size_t i = 0; i < 10; i++ )\n    EXPECT_EQ( rmat_copy(i,i), mat(lookup[i],lookup[i]) );\n}\n\nTEST(SparseSkyline, CuthillMcKee) {\n  MatrixSparseSkyline<float> sparse(61);\n  fill_with_buckeyball(sparse);\n\n  // Solving for ordering\n  std::vector<size_t> new_ordering = cuthill_mckee_ordering(sparse,1);\n\n  // This ordering comes from the MATLAB cuthill mckee example\n  size_t ideal_order[61] = {1,6,2,5,7,26,30,10,11,12,3,4,8,27,29,9,15,13,16,17,21,25,42,28,43,38,37,14,20,18,22,24,41,47,44,39,36,33,19,32,23,48,45,46,40,34,53,31,52,49,58,50,57,35,54,51,59,56,55,60,0};\n\n  for ( size_t i = 0; i < new_ordering.size(); i++ )\n    EXPECT_EQ(ideal_order[i], new_ordering[i]);\n}\n\nTEST(SparseSkyline, ReorderOptimization) {\n  MatrixSparseSkyline<float> sparse(61);\n  fill_with_buckeyball(sparse);\n  sparse(1,0) = 2.0;\n  sparse(12,0) = 1.0;\n  sparse(33,0) = 5.0;\n  // Insuring positive definite\n  for ( size_t i = 0; i < 61; i++ ) {\n    sparse(i,i) += 5;\n    if ( i > 0 )\n      sparse(i-1,i) += 1;\n  }\n  Matrix<float> common = sparse;\n  Vector<float> x_ideal(61);\n  for ( size_t i = 0; i < 61; i++ )\n    x_ideal[i] = float((i+1)*0.5);\n\n  Vector<float> b = common*x_ideal;\n\n  // Standard unsparse unoptimized method\n  Vector<double> x_unsparse = inverse(common)*b;\n  EXPECT_EQ( 61u, x_unsparse.size() );\n\n  // Sparse Unoptimized method\n  MatrixSparseSkyline<float> sparse_copy = sparse;\n  Vector<double> x_sparse = sparse_solve(sparse_copy,b);\n  EXPECT_EQ( 61u, x_sparse.size() );\n\n  // Optimized method;\n  std::vector<size_t> new_ordering = cuthill_mckee_ordering(sparse,1);\n  math::MatrixReorganize<MatrixSparseSkyline<float> > rsparse( sparse, new_ordering);\n\n  Vector<size_t> new_skyline = solve_for_skyline(rsparse);\n  Vector<double> x_reorder = sparse_solve( rsparse,\n                                           reorganize(b,new_ordering),\n                                            new_skyline );\n  x_reorder = reorganize(x_reorder, rsparse.inverse() );\n  EXPECT_EQ( 61u, x_reorder.size() );\n\n  //std::cout << \"Unsparse Result: \" << x_unsparse << \"\\n\";\n  //std::cout << \"StandardSparseR: \" << x_sparse << \"\\n\";\n  //std::cout << \"Reorder SparseR: \" << x_reorder << \"\\n\";\n\n  // Make sure old methods still work\n  for ( size_t i = 0; i < 61; i++ )\n    EXPECT_NEAR( x_unsparse[i], x_sparse[i], DELTA );\n\n  // Does reorganized method work?\n  for ( size_t i = 0; i < 61; i++ )\n    EXPECT_NEAR( x_unsparse[i], x_reorder[i], DELTA );\n}\n\nTEST(SparseSkyline, ReorderConstCorrectness) {\n  // Checking that SparseSkyline works\n  math::MatrixSparseSkyline<double> sparse(1,1);\n  ASSERT_EQ( 1u, sparse.cols() );\n  ASSERT_EQ( 1u, sparse.rows() );\n  sparse(0,0) = 1;\n  ASSERT_EQ( 1, sparse(0,0) );\n  Vector<size_t> skyline = sparse.skyline();\n  ASSERT_EQ( 1u, skyline.size() );\n  EXPECT_EQ( 0u, skyline[0] );\n\n  { // Applying second layers that could goof const\n    math::MatrixTranspose<math::MatrixSparseSkyline<double> > tsparse( sparse );\n    ASSERT_EQ( 1u, tsparse.cols() );\n    ASSERT_EQ( 1u, tsparse.rows() );\n    EXPECT_EQ( 1, tsparse(0,0) );\n    const math::MatrixTranspose<math::MatrixSparseSkyline<double> > ctsparse( sparse );\n    ASSERT_EQ( 1u, ctsparse.cols() );\n    ASSERT_EQ( 1u, ctsparse.rows() );\n    EXPECT_EQ( 1, ctsparse(0,0) );\n\n\n    // Another example of the error\n    std::vector<size_t> reorder(1);\n    reorder[0] = 0;\n    math::MatrixReorganize<math::MatrixSparseSkyline<double> > rsparse( sparse, reorder );\n    ASSERT_EQ( 1u, rsparse.cols() );\n    ASSERT_EQ( 1u, rsparse.rows() );\n    EXPECT_EQ( 1, rsparse(0,0) );\n    const math::MatrixReorganize<math::MatrixSparseSkyline<double> > crsparse( sparse, reorder );\n    ASSERT_EQ( 1u, crsparse.cols() );\n    ASSERT_EQ( 1u, crsparse.rows() );\n    EXPECT_EQ( 1, crsparse(0,0) );\n\n  }\n}\n", "meta": {"hexsha": "c0de62f97f4c4f8a3482630b6814c1feb22dc169", "size": 14468, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/vw/Math/tests/TestMatrixSparseSkyline.cxx", "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/Math/tests/TestMatrixSparseSkyline.cxx", "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/Math/tests/TestMatrixSparseSkyline.cxx", "max_forks_repo_name": "rkrishnasanka/visionworkbench", "max_forks_repo_head_hexsha": "2af5da17dfd277f0cb3f19a97e3d49ba19cc9d24", "max_forks_repo_licenses": ["NASA-1.3"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-03-18T04:06:32.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-17T10:34:39.000Z", "avg_line_length": 32.7330316742, "max_line_length": 202, "alphanum_fraction": 0.6276610451, "num_tokens": 5246, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723317123102956, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.45202992696389704}}
{"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 testExpression.cpp\n * @date September 18, 2014\n * @author Frank Dellaert\n * @author Paul Furgale\n * @brief unit tests for Block Automatic Differentiation\n */\n\n#include <gtsam/3rdparty/ceres/example.h>\n#include <gtsam/nonlinear/AdaptAutoDiff.h>\n#include <gtsam/nonlinear/Expression.h>\n#include <gtsam/geometry/PinholeCamera.h>\n#include <gtsam/geometry/Pose3.h>\n#include <gtsam/geometry/Cal3_S2.h>\n#include <gtsam/geometry/Cal3Bundler.h>\n#include <gtsam/base/numericalDerivative.h>\n#include <gtsam/base/Testable.h>\n\n#include <CppUnitLite/TestHarness.h>\n\n#include <boost/assign/list_of.hpp>\nusing boost::assign::list_of;\nusing boost::assign::map_list_of;\n\nnamespace gtsam {\n\n// Special version of Cal3Bundler so that default constructor = 0,0,0\nstruct Cal3Bundler0 : public Cal3Bundler {\n  Cal3Bundler0(double f = 0, double k1 = 0, double k2 = 0, double u0 = 0,\n               double v0 = 0)\n      : Cal3Bundler(f, k1, k2, u0, v0) {}\n  Cal3Bundler0 retract(const Vector& d) const {\n    return Cal3Bundler0(fx() + d(0), k1() + d(1), k2() + d(2), px(), py());\n  }\n  Vector3 localCoordinates(const Cal3Bundler0& T2) const {\n    return T2.vector() - vector();\n  }\n};\n\ntemplate <>\nstruct traits<Cal3Bundler0> : public internal::Manifold<Cal3Bundler0> {};\n\n// With that, camera below behaves like Snavely's 9-dim vector\ntypedef PinholeCamera<Cal3Bundler0> Camera;\n}\n\nusing namespace std;\nusing namespace gtsam;\n\n/* ************************************************************************* */\n// Check that ceres rotation convention is the same\nTEST(AdaptAutoDiff, Rotation) {\n  Vector3 axisAngle(0.1, 0.2, 0.3);\n  Matrix3 expected = Rot3::Rodrigues(axisAngle).matrix();\n  Matrix3 actual;\n  ceres::AngleAxisToRotationMatrix(axisAngle.data(), actual.data());\n  EXPECT(assert_equal(expected, actual));\n}\n\n/* ************************************************************************* */\n// Some Ceres Snippets copied for testing\n// Copyright 2010, 2011, 2012 Google Inc. All rights reserved.\ntemplate <typename T>\ninline T& RowMajorAccess(T* base, int rows, int cols, int i, int j) {\n  return base[cols * i + j];\n}\n\ninline double RandDouble() {\n  double r = static_cast<double>(rand());\n  return r / RAND_MAX;\n}\n\n// A structure for projecting a 3x4 camera matrix and a\n// homogeneous 3D point, to a 2D inhomogeneous point.\nstruct Projective {\n  // Function that takes P and X as separate vectors:\n  //   P, X -> x\n  template <typename A>\n  bool operator()(A const P[12], A const X[4], A x[2]) const {\n    A PX[3];\n    for (int i = 0; i < 3; ++i) {\n      PX[i] = RowMajorAccess(P, 3, 4, i, 0) * X[0] +\n              RowMajorAccess(P, 3, 4, i, 1) * X[1] +\n              RowMajorAccess(P, 3, 4, i, 2) * X[2] +\n              RowMajorAccess(P, 3, 4, i, 3) * X[3];\n    }\n    if (PX[2] != 0.0) {\n      x[0] = PX[0] / PX[2];\n      x[1] = PX[1] / PX[2];\n      return true;\n    }\n    return false;\n  }\n\n  // Adapt to eigen types\n  Vector2 operator()(const MatrixRowMajor& P, const Vector4& X) const {\n    Vector2 x;\n    if (operator()(P.data(), X.data(), x.data()))\n      return x;\n    else\n      throw std::runtime_error(\"Projective fail\");\n  }\n};\n\n/* ************************************************************************* */\n// Test Ceres AutoDiff\nTEST(AdaptAutoDiff, AutoDiff) {\n  using ceres::internal::AutoDiff;\n\n  // Instantiate function\n  Projective projective;\n\n  // Make arguments\n  typedef Eigen::Matrix<double, 3, 4, Eigen::RowMajor> RowMajorMatrix34;\n  RowMajorMatrix34 P;\n  P << 1, 0, 0, 0, 0, 1, 0, 5, 0, 0, 1, 0;\n  Vector4 X(10, 0, 5, 1);\n\n  // Apply the mapping, to get image point b_x.\n  Vector expected = Vector2(2, 1);\n  Vector2 actual = projective(P, X);\n  EXPECT(assert_equal(expected, actual, 1e-9));\n\n  // Get expected derivatives\n  Matrix E1 = numericalDerivative21<Vector2, RowMajorMatrix34, Vector4>(\n      Projective(), P, X);\n  Matrix E2 = numericalDerivative22<Vector2, RowMajorMatrix34, Vector4>(\n      Projective(), P, X);\n\n  // Get derivatives with AutoDiff\n  Vector2 actual2;\n  MatrixRowMajor H1(2, 12), H2(2, 4);\n  double* parameters[] = {P.data(), X.data()};\n  double* jacobians[] = {H1.data(), H2.data()};\n  CHECK((AutoDiff<Projective, double, 12, 4>::Differentiate(\n      projective, parameters, 2, actual2.data(), jacobians)));\n  EXPECT(assert_equal(E1, H1, 1e-8));\n  EXPECT(assert_equal(E2, H2, 1e-8));\n}\n\n/* ************************************************************************* */\n// Test Ceres AutoDiff on Snavely, defined in ceres_example.h\n// Adapt to GTSAM types\nVector2 adapted(const Vector9& P, const Vector3& X) {\n  SnavelyProjection snavely;\n  Vector2 x;\n  if (snavely(P.data(), X.data(), x.data()))\n    return x;\n  else\n    throw std::runtime_error(\"Snavely fail\");\n}\n\n/* ************************************************************************* */\nnamespace example {\nCamera camera(Pose3(Rot3().retract(Vector3(0.1, 0.2, 0.3)), Point3(0, 5, 0)),\n              Cal3Bundler0(1, 0, 0));\nPoint3 point(10, 0, -5);  // negative Z-axis convention of Snavely!\nVector9 P = Camera().localCoordinates(camera);\nVector3 X = point;\n#ifdef GTSAM_POSE3_EXPMAP\nVector2 expectedMeasurement(1.3124675, 1.2057287);\n#else\nVector2 expectedMeasurement(1.2431567, 1.2525694);\n#endif\nMatrix E1 = numericalDerivative21<Vector2, Vector9, Vector3>(adapted, P, X);\nMatrix E2 = numericalDerivative22<Vector2, Vector9, Vector3>(adapted, P, X);\n}\n\n/* ************************************************************************* */\n// Check that Local worked as expected\nTEST(AdaptAutoDiff, Local) {\n  using namespace example;\n#ifdef GTSAM_POSE3_EXPMAP\n  Vector9 expectedP = (Vector9() << 0.1, 0.2, 0.3, 0.7583528428, 4.9582357859, -0.224941471539, 1, 0, 0).finished();\n#else\n  Vector9 expectedP = (Vector9() << 0.1, 0.2, 0.3, 0, 5, 0, 1, 0, 0).finished();\n#endif\n  EXPECT(equal_with_abs_tol(expectedP, P));\n  Vector3 expectedX(10, 0, -5);  // negative Z-axis convention of Snavely!\n  EXPECT(equal_with_abs_tol(expectedX, X));\n}\n\n/* ************************************************************************* */\n// Test Ceres AutoDiff\nTEST(AdaptAutoDiff, AutoDiff2) {\n  using namespace example;\n  using ceres::internal::AutoDiff;\n\n  // Apply the mapping, to get image point b_x.\n  Vector2 actual = adapted(P, X);\n  EXPECT(assert_equal(expectedMeasurement, actual, 1e-6));\n\n  // Instantiate function\n  SnavelyProjection snavely;\n\n  // Get derivatives with AutoDiff\n  Vector2 actual2;\n  MatrixRowMajor H1(2, 9), H2(2, 3);\n  double* parameters[] = {P.data(), X.data()};\n  double* jacobians[] = {H1.data(), H2.data()};\n  CHECK((AutoDiff<SnavelyProjection, double, 9, 3>::Differentiate(\n      snavely, parameters, 2, actual2.data(), jacobians)));\n  EXPECT(assert_equal(E1, H1, 1e-8));\n  EXPECT(assert_equal(E2, H2, 1e-8));\n}\n\n/* ************************************************************************* */\n// Test AutoDiff wrapper Snavely\nTEST(AdaptAutoDiff, AdaptAutoDiff) {\n  using namespace example;\n\n  typedef AdaptAutoDiff<SnavelyProjection, 2, 9, 3> Adaptor;\n  Adaptor snavely;\n\n  // Apply the mapping, to get image point b_x.\n  Vector2 actual = snavely(P, X);\n  EXPECT(assert_equal(expectedMeasurement, actual, 1e-6));\n\n  // Get derivatives with AutoDiff, not gives RowMajor results!\n  Matrix29 H1;\n  Matrix23 H2;\n  Vector2 actual2 = snavely(P, X, H1, H2);\n  EXPECT(assert_equal(expectedMeasurement, actual2, 1e-6));\n  EXPECT(assert_equal(E1, H1, 1e-8));\n  EXPECT(assert_equal(E2, H2, 1e-8));\n}\n\n/* ************************************************************************* */\n// Test AutoDiff wrapper in an expression\nTEST(AdaptAutoDiff, SnavelyExpression) {\n  typedef AdaptAutoDiff<SnavelyProjection, 2, 9, 3> Adaptor;\n\n  Expression<Vector9> P(1);\n  Expression<Vector3> X(2);\n\n  Expression<Vector2> expression(Adaptor(), P, X);\n\n  std::size_t RecordSize =\n    sizeof(internal::BinaryExpression<Vector2, Vector9, Vector3>::Record);\n\n  EXPECT_LONGS_EQUAL(\n    internal::upAligned(RecordSize) + P.traceSize() + X.traceSize(),\n    expression.traceSize());\n\n  set<Key> expected = list_of(1)(2);\n\n  EXPECT(expected == expression.keys());\n}\n\n/* ************************************************************************* */\nint main() {\n  TestResult tr;\n  return TestRegistry::runAllTests(tr);\n}\n/* ************************************************************************* */\n", "meta": {"hexsha": "1423b473e77282d9ebe8fcdfc9297277b0bc172b", "size": 8673, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/nonlinear/tests/testAdaptAutoDiff.cpp", "max_stars_repo_name": "coestreich/gtsam", "max_stars_repo_head_hexsha": "fc171877f03b70236c5cc59537d5f34f1eb88c86", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1402.0, "max_stars_repo_stars_event_min_datetime": "2017-03-28T00:18:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T10:28:32.000Z", "max_issues_repo_path": "gtsam/nonlinear/tests/testAdaptAutoDiff.cpp", "max_issues_repo_name": "coestreich/gtsam", "max_issues_repo_head_hexsha": "fc171877f03b70236c5cc59537d5f34f1eb88c86", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 851.0, "max_issues_repo_issues_event_min_datetime": "2017-11-27T15:09:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T22:26:38.000Z", "max_forks_repo_path": "gtsam/nonlinear/tests/testAdaptAutoDiff.cpp", "max_forks_repo_name": "coestreich/gtsam", "max_forks_repo_head_hexsha": "fc171877f03b70236c5cc59537d5f34f1eb88c86", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 565.0, "max_forks_repo_forks_event_min_datetime": "2017-11-30T16:15:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T02:53:04.000Z", "avg_line_length": 32.4831460674, "max_line_length": 116, "alphanum_fraction": 0.6011760636, "num_tokens": 2501, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723316860482762, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.45202990930710873}}
{"text": "// std includes\n#include <iostream> // cout, endl\n#include <memory> // shared_ptr\n#include <vector>\n#include <tuple>\n// thirdparties includes\n#include <Eigen/Dense>\n// lib includes\n// // s0s\n#include \"s0s/runge_kutta_fehlberg.h\"\n// // sl0\n#include \"sl0/object.h\"\n#include \"sl0/point.h\"\n// // sa0\n#include \"sa0/active.h\"\n#include \"sa0/actuator/point.h\"\n#include \"sa0/agent.h\"\n#include \"sa0/behaviour.h\"\n// simple includes\n#include \"flow.h\"\n\nusing TypeScalar = double;\ntemplate<typename ...Args>\nusing TypeContainer = std::vector<Args...>;\n// Space\nconstexpr unsigned int DIM = 3;\nusing TypeVector = Eigen::Matrix<TypeScalar, DIM, 1>;\n// Ref and View\ntemplate<int StateSize>\nusing TypeState = Eigen::Matrix<TypeScalar, StateSize, 1>;\ntemplate<typename ...Args>\nusing TypeRef = Eigen::Ref<Args...>;\ntemplate<typename ...Args>\nusing TypeView = Eigen::Map<Args...>;\n// Point\nusing TypeStepPoint = sl0::StepPoint<TypeState, DIM, TypeRef, TypeView, Flow>;\n// Choose passive\nusing TypeStepPassive = TypeStepPoint;\n// Active\nusing TypeStepActuator = sl0::sa0::StepActuator<TypeStepPassive::TypeStateStatic, TypeRef, TypeStepPassive>;\nusing TypeStepPointSwim = sl0::sa0::StepPointSwim<TypeStepPassive::TypeStateStatic, TypeRef, TypeStepPassive, TypeVector>;\nusing TypeStepActive = sl0::sa0::StepActive<TypeState, TypeRef, TypeView, TypeStepPassive, TypeStepActuator>;\n// Agent\nclass BehaviourCustom : public sl0::sa0::Behaviour<TypeStepActive::TypeStateStatic, TypeRef, TypeStepActive> {\n    public:\n        std::shared_ptr<Flow> sFlow;\n    public:\n        BehaviourCustom(const std::shared_ptr<Flow> p_sFlow) : sFlow(p_sFlow) {\n        }\n        void operator()(const TypeRef<const TypeStepActive::TypeStateStatic>& state, const double& t, const TypeStepActive&  stepActive) const override {\n            dynamic_cast<TypeStepPointSwim&>(*stepActive.sStepActuators[0]).velocity = sFlow->getVelocity(stepActive.cX(state), t);\n        }\n};\nusing TypeBehaviour = BehaviourCustom;\nusing TypeStep = sl0::sa0::StepAgent<TypeState, TypeRef, TypeView, TypeStepActive, TypeBehaviour>;\n// Solver\nusing TypeSolver = s0s::SolverRungeKuttaFehlberg;\n\nint main () { \n    TypeVector us = TypeVector::Constant(0.0);\n    TypeVector x0 = TypeVector::Constant(1.0);\n    double t0 = 0.0;\n    double dt = 1e-3;\n    double tEnd = 0.5;\n    unsigned int nt = std::round((tEnd - t0) / dt);\n    // Create flow\n    std::shared_ptr<Flow> sFlow = std::make_shared<Flow>();\n    // Create agent\n    sl0::sa0::Agent<TypeState, TypeRef, TypeView, TypeStepActive, TypeBehaviour, TypeSolver> agent(TypeStepActive(TypeStepPassive(sFlow)), std::make_shared<TypeBehaviour>(sFlow));\n    std::shared_ptr<TypeStepPointSwim> sStepPointSwim = std::make_shared<TypeStepPointSwim>(us);\n    agent.sStep->register_actuator(sStepPointSwim);\n    // Set initial state\n    agent.sStep->x(agent.state) = x0;\n    agent.t = t0;\n    // Computation\n    for(std::size_t i = 0; i < nt; i++) {\n        agent.update(dt);\n    }\n    // out\n    std::cout << \"\\n\";\n    std::cout << \"agent advected and swimming in an exponential flow, t = \" << agent.t << \", x = \" << \"\\n\";\n    std::cout << \"\\n\";\n    std::cout << \"agent position : \" << \"\\n\" << agent.sStep->x(agent.state) << \"\\n\";\n    std::cout << std::endl;\n}\n", "meta": {"hexsha": "76f831c16a2fb9eb76277372e7ab7ede5c60b9a3", "size": 3236, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/agent/main.cpp", "max_stars_repo_name": "C0PEP0D/sa0", "max_stars_repo_head_hexsha": "0d4d4106d64a2eaec6fd5f8cdba1a73bc0a26ea2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/agent/main.cpp", "max_issues_repo_name": "C0PEP0D/sa0", "max_issues_repo_head_hexsha": "0d4d4106d64a2eaec6fd5f8cdba1a73bc0a26ea2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/agent/main.cpp", "max_forks_repo_name": "C0PEP0D/sa0", "max_forks_repo_head_hexsha": "0d4d4106d64a2eaec6fd5f8cdba1a73bc0a26ea2", "max_forks_repo_licenses": ["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.6279069767, "max_line_length": 179, "alphanum_fraction": 0.695302843, "num_tokens": 933, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152325073083132, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.4520223473780954}}
{"text": "#ifdef _MSC_VER\n#include <boost/math/tr1.hpp>\nusing namespace boost::math::tr1;\n#else\n#include <math.h>\n#endif\n\n#include \"Hmm.hh\"\n\n\nStateDuration::StateDuration()\n  : a(0), b(0), a0(0), mode(0)\n{\n}\n\nvoid StateDuration::set_parameters(float a, float b)\n{\n  float temp;\n  \n  this->a = a;\n  this->b = b;\n  mode = 0;\n  if (a > 0)\n  {\n    const_term = -a*logf(b)-lgammaf(a);\n    temp = b*(a-1); // Mode of the gamma distribution\n    mode = (int)floor(temp);\n    if (get_log_prob(mode) < get_log_prob(mode+1))\n      mode++;\n  }\n}\n\n\nfloat StateDuration::get_log_prob(int duration) const\n{\n  if (a > 0)\n    return (a-1)*logf(duration)-duration/b+const_term;\n  return 0; // No duration penalty\n}\n\n\nvoid StateDuration::set_sr_parameters(float a0, float a1, float b0, float b1)\n{\n  this->a0 = a0;\n  this->a1 = a1;\n  this->b0 = b0;\n  this->b1 = b1;\n}\n\n\nfloat StateDuration::get_sr_comp_log_prob(int duration, float sr) const\n{\n  if (a0 > 0)\n  {\n    float ia = a0 + sr*a1;\n    float ib = b0 + sr*b1;\n    return (ia-1)*logf((float)duration)-(float)duration/ib-ia*logf(ib)-\n      lgammaf(ia);\n  }\n  else\n  {\n    return get_log_prob(duration);\n  }\n}\n", "meta": {"hexsha": "6dccd39d61286ae583338af632a2f60e7506d2e8", "size": 1134, "ext": "cc", "lang": "C++", "max_stars_repo_path": "decoder/src/Hmm.cc", "max_stars_repo_name": "phsmit/AaltoASR", "max_stars_repo_head_hexsha": "33cb58b288cc01bcdff0d6709a296d0dfcc7f74a", "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": "decoder/src/Hmm.cc", "max_issues_repo_name": "phsmit/AaltoASR", "max_issues_repo_head_hexsha": "33cb58b288cc01bcdff0d6709a296d0dfcc7f74a", "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": "decoder/src/Hmm.cc", "max_forks_repo_name": "phsmit/AaltoASR", "max_forks_repo_head_hexsha": "33cb58b288cc01bcdff0d6709a296d0dfcc7f74a", "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": 17.4461538462, "max_line_length": 77, "alphanum_fraction": 0.6208112875, "num_tokens": 384, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.45202233742185005}}
{"text": "\n#include <boost/test/unit_test.hpp>\n#include \"camera.h\"\n\nBOOST_AUTO_TEST_SUITE(camera)\n\nBOOST_AUTO_TEST_CASE(translation_rotation_1)\n{\n\tgraphic::Camera c;\n\tc.set_translation_rotation(math::vec<3>(0, 0, 0), math::vec<3>(0, 0, 0));\n\n\tBOOST_REQUIRE (((math::vec<3>(0, 0, 0) * c.get_view_matrix()) - math::vec<3>(0, 0, 0)).length_sq() < math::EPSILON);\n\tBOOST_REQUIRE ((math::vec<3>(0, 0, 0) - c.get_eye_point()).length_sq() < math::EPSILON);\n\tBOOST_REQUIRE ((math::vec<3>(0, 0, 1) - c.get_view_dir()).length_sq() < math::EPSILON);\n\tBOOST_REQUIRE ((math::vec<3>(0, 1, 0) - c.get_up_dir()).length_sq() < math::EPSILON);\n\tBOOST_REQUIRE ((math::vec<3>(1, 0, 0) - c.get_cross_dir()).length_sq() < math::EPSILON);\n}\n\nBOOST_AUTO_TEST_CASE(translation_rotation_2)\n{\n\tgraphic::Camera c;\n\tc.set_translation_rotation(math::vec<3>(-123, -456, -789), math::vec<3>(0, 0, 0));\n\n\tBOOST_REQUIRE (((math::vec<3>(0, 0, 0) * c.get_view_matrix()) + math::vec<3>(123, 456, 789)).length_sq() < math::EPSILON);\n\tBOOST_REQUIRE ((math::vec<3>(123, 456, 789) - c.get_eye_point()).length_sq() < math::EPSILON);\n\tBOOST_REQUIRE ((math::vec<3>(0, 0, 1) - c.get_view_dir()).length_sq() < math::EPSILON);\n\tBOOST_REQUIRE ((math::vec<3>(0, 1, 0) - c.get_up_dir()).length_sq() < math::EPSILON);\n\tBOOST_REQUIRE ((math::vec<3>(1, 0, 0) - c.get_cross_dir()).length_sq() < math::EPSILON);\n}\n\nBOOST_AUTO_TEST_CASE(translation_rotation_3)\n{\n\tgraphic::Camera c;\n\tc.set_translation_rotation(math::vec<3>(0, 0, 0), math::vec<3>(-math::PI/4, 0, 0));\n\n\tBOOST_REQUIRE (((math::vec<3>(0, 0, 0) * c.get_view_matrix()) + math::vec<3>(0, 0, 0)).length_sq() < math::EPSILON);\n\tBOOST_REQUIRE ((math::vec<3>(0, 0, 0) - c.get_eye_point()).length_sq() < math::EPSILON);\n\tBOOST_REQUIRE ((math::vec<3>(0, -0.707106f, 0.707106f) - c.get_view_dir()).length_sq() < math::EPSILON);\n\tBOOST_REQUIRE ((math::vec<3>(0, 0.707106f, 0.707106f) - c.get_up_dir()).length_sq() < math::EPSILON);\n\tBOOST_REQUIRE ((math::vec<3>(1, 0, 0) - c.get_cross_dir()).length_sq() < math::EPSILON);\n}\n\nBOOST_AUTO_TEST_CASE(translation_rotation_4)\n{\n\tgraphic::Camera c;\n\tc.set_translation_rotation(math::vec<3>(0, 0, 0), math::vec<3>(math::PI/2, 0, 0));\n\n\tBOOST_REQUIRE (((math::vec<3>(0, 0, 0) * c.get_view_matrix()) + math::vec<3>(0, 0, 0)).length_sq() < math::EPSILON);\n\tBOOST_REQUIRE ((math::vec<3>(0, 0, 0) - c.get_eye_point()).length_sq() < math::EPSILON);\n\tBOOST_REQUIRE ((math::vec<3>(0, 1, 0) - c.get_view_dir()).length_sq() < math::EPSILON);\n\tBOOST_REQUIRE ((math::vec<3>(0, 0, -1) - c.get_up_dir()).length_sq() < math::EPSILON);\n\tBOOST_REQUIRE ((math::vec<3>(1, 0, 0) - c.get_cross_dir()).length_sq() < math::EPSILON);\n}\n\nBOOST_AUTO_TEST_CASE(eye_lookat_up_1)\n{\n\tgraphic::Camera c;\n\tc.set_eye_lookat_up(math::vec<3>(0, 0, 0), math::vec<3>(0, 0, 1), math::vec<3>(0, 1, 0));\n\n\tBOOST_REQUIRE (((math::vec<3>(0, 0, 0) * c.get_view_matrix()) - math::vec<3>(0, 0, 0)).length_sq() < math::EPSILON);\n\tBOOST_REQUIRE ((math::vec<3>(0, 0, 0) - c.get_eye_point()).length_sq() < math::EPSILON);\n\tBOOST_REQUIRE ((math::vec<3>(0, 0, 1) - c.get_view_dir()).length_sq() < math::EPSILON);\n\tBOOST_REQUIRE ((math::vec<3>(0, 1, 0) - c.get_up_dir()).length_sq() < math::EPSILON);\n\tBOOST_REQUIRE ((math::vec<3>(1, 0, 0) - c.get_cross_dir()).length_sq() < math::EPSILON);\n}\n\nBOOST_AUTO_TEST_CASE(eye_lookat_up_2)\n{\n\tgraphic::Camera c;\n\tc.set_eye_lookat_up(math::vec<3>(123, 456, 789), math::vec<3>(123, 456, 790), math::vec<3>(0, 1, 0));\n\n\tBOOST_REQUIRE (((math::vec<3>(0, 0, 0) * c.get_view_matrix()) + math::vec<3>(123, 456, 789)).length_sq() < math::EPSILON);\n\tBOOST_REQUIRE ((math::vec<3>(123, 456, 789) - c.get_eye_point()).length_sq() < math::EPSILON);\n\tBOOST_REQUIRE ((math::vec<3>(0, 0, 1) - c.get_view_dir()).length_sq() < math::EPSILON);\n\tBOOST_REQUIRE ((math::vec<3>(0, 1, 0) - c.get_up_dir()).length_sq() < math::EPSILON);\n\tBOOST_REQUIRE ((math::vec<3>(1, 0, 0) - c.get_cross_dir()).length_sq() < math::EPSILON);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "0d6e8a166544907eb178431b07b8604527191559", "size": 3953, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/graphic/test_camera.cc", "max_stars_repo_name": "mnvl/scratch", "max_stars_repo_head_hexsha": "7717772e0b9a85c8feb73fdc3562425f48b4a727", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-08-15T11:55:32.000Z", "max_stars_repo_stars_event_max_datetime": "2016-08-15T11:55:32.000Z", "max_issues_repo_path": "src/graphic/test_camera.cc", "max_issues_repo_name": "mnvl/scratch", "max_issues_repo_head_hexsha": "7717772e0b9a85c8feb73fdc3562425f48b4a727", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/graphic/test_camera.cc", "max_forks_repo_name": "mnvl/scratch", "max_forks_repo_head_hexsha": "7717772e0b9a85c8feb73fdc3562425f48b4a727", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.4125, "max_line_length": 123, "alphanum_fraction": 0.6531748039, "num_tokens": 1438, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.45202233742185005}}
{"text": "#include \"TextureAnalysis.hpp\"\n\n#include <math.h>\n\n#include <Eigen/Eigenvalues>\n#include <algorithm>\n#include <ctime>\n#include <filesystem>\n#include <fstream>\n#include <iomanip>\n\nconst int white_color = 255;\nconst int black_color = 0;\n\nusing namespace glcm;\n\nnamespace fs = std::filesystem;\n\nTextureAnalysis::TextureAnalysis(int Ng) : _Ng(Ng) {\n    if (Ng > 0) {\n        // initialize probability matrices\n        _P_H.resize(_Ng, std::vector<int>(_Ng));\n        _P_V.resize(_Ng, std::vector<int>(_Ng));\n        _P_LD.resize(_Ng, std::vector<int>(_Ng));\n        _P_RD.resize(_Ng, std::vector<int>(_Ng));\n\n        _p_H.resize(_Ng, std::vector<double>(_Ng));\n        _p_V.resize(_Ng, std::vector<double>(_Ng));\n        _p_LD.resize(_Ng, std::vector<double>(_Ng));\n        _p_RD.resize(_Ng, std::vector<double>(_Ng));\n\n        // initialize probability vectors\n        _px_H.resize(_Ng);\n        _px_V.resize(_Ng);\n        _px_LD.resize(_Ng);\n        _px_RD.resize(_Ng);\n\n        _py_H.resize(_Ng);\n        _py_V.resize(_Ng);\n        _py_LD.resize(_Ng);\n        _py_RD.resize(_Ng);\n\n        _p_xpy_H.resize(2 * _Ng - 1);\n        _p_xpy_V.resize(2 * _Ng - 1);\n        _p_xpy_LD.resize(2 * _Ng - 1);\n        _p_xpy_RD.resize(2 * _Ng - 1);\n\n        _p_xny_H.resize(_Ng);\n        _p_xny_V.resize(_Ng);\n        _p_xny_LD.resize(_Ng);\n        _p_xny_RD.resize(_Ng);\n\n        // reset factors as zeros\n        ResetFactors();\n    } else {\n        std::cerr << \"Invalid Ng assignment (Ng < 0)!\\n\";\n    }\n}\n\nvoid TextureAnalysis::ProcessRectImage(const cv::Mat &image, int distance) {\n    // Clear the cache\n    ResetCache();\n\n    // Calculate matrices elements: central pixel coord (m ,n), where \"m\" is the row index, and \"n\" is the column index\n    for (int m = 0; m < image.rows; ++m) {\n        for (int n = 0; n < image.cols; ++n) {\n            // Nearest neighborhood pixel coord (k ,l), where \"k\" is the row index, and \"l\" is the column index\n            for (int k = m - distance; k <= m + distance; ++k) {\n                for (int l = n - distance; l <= n + distance; ++l) {\n                    if ((k >= 0) && (l >= 0) && (k < image.rows) && (l < image.cols)) {\n                        //// ToDo: need to check are pixel values in coordinates (m,n) and (k,l) nan or masked!!\n                        int j = (int) (image.at<uchar>(m, n)); // I(m,n)\n                        int i = (int) (image.at<uchar>(k, l)); // I(k,l)\n                        if (((k - m) == 0) && (abs(l - n) == distance)) {\n                            CountElemH(i, j);\n                        } else if ((((k - m) == distance) && ((l - n) == -distance)) ||\n                                   (((k - m) == -distance) && ((l - n) == distance))) {\n                            CountElemRD(i, j);\n                        } else if ((abs(k - m) == distance) && (l - n == 0)) {\n                            CountElemV(i, j);\n                        } else if ((((k - m) == distance) && ((l - n) == distance)) ||\n                                   (((k - m) == -distance) && ((l - n) == -distance))) {\n                            CountElemLD(i, j);\n                        } else if ((m == k) && (n == l)) {\n                            PushPixelValue(i);\n                        } else {\n                            // if ((m != k) || (n != l)) {\n                            //    cerr << \"unknown element:\" << endl;\n                            //    cerr << \"central element: (m, n) = (\" << m << \",\" << n << \")\" << endl;\n                            //    cerr << \"neighborhood element: (k, l) = (\" << k << \",\" << l << \")\" << endl;\n                            //}\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    // Normalize the matrices\n    Normalization();\n}\n\nvoid TextureAnalysis::ProcessPolygonImage(const cv::Mat &original_image, const cv::Mat &mask_image, int distance) {\n    // Clear the cache\n    ResetCache();\n\n    // Calculate matrices elements: central pixel coord (m ,n), where \"m\" is the row index, and \"n\" is the column index\n    int masked = 0;\n    int non_masked = 0;\n    for (int m = 0; m < original_image.rows; ++m) {\n        for (int n = 0; n < original_image.cols; ++n) {\n            // Nearest neighborhood pixel coord (k ,l), where \"k\" is the row index, and \"l\" is the column index\n            for (int k = m - distance; k <= m + distance; ++k) {\n                for (int l = n - distance; l <= n + distance; ++l) {\n                    if ((k >= 0) && (l >= 0) && (k < original_image.rows) && (l < original_image.cols)) {\n                        // Check is the nearest neighborhood pixel coord (k ,l) masked\n                        int mask_pixel_value = (int) (mask_image.at<uchar>(k, l));\n                        if (mask_pixel_value ==\n                            white_color) {             // if nearest neighborhood pixel coord (k ,l) is not masked\n                            int j = (int) (original_image.at<uchar>(m, n)); // I(m,n)\n                            int i = (int) (original_image.at<uchar>(k, l)); // I(k,l)\n                            if (((k - m) == 0) && (abs(l - n) == distance)) {\n                                CountElemH(i, j);\n                            } else if ((((k - m) == distance) && ((l - n) == -distance)) ||\n                                       (((k - m) == -distance) && ((l - n) == distance))) {\n                                CountElemRD(i, j);\n                            } else if ((abs(k - m) == distance) && (l - n == 0)) {\n                                CountElemV(i, j);\n                            } else if ((((k - m) == distance) && ((l - n) == distance)) ||\n                                       (((k - m) == -distance) && ((l - n) == -distance))) {\n                                CountElemLD(i, j);\n                            } else if ((m == k) && (n == l)) {\n                                PushPixelValue(i);\n                            } else {\n                                // if ((m != k) || (n != l)) {\n                                //    cerr << \"unknown element:\" << endl;\n                                //    cerr << \"central element: (m, n) = (\" << m << \",\" << n << \")\" << endl;\n                                //    cerr << \"neighborhood element: (k, l) = (\" << k << \",\" << l << \")\" << endl;\n                                //}\n                            }\n                            ++non_masked;\n                        } else {\n                            // cerr << \"masked coord: (k, l) = (\" << k << \",\" << l << \"), pixel value = \" << mask_pixel_value << endl;\n                            ++masked;\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    // Normalize the matrices\n    Normalization();\n}\n\nvoid TextureAnalysis::ResetCache() {\n    // reset probability matrices as zeros\n    for (int i = 0; i < _Ng; ++i) {\n        std::fill(_P_H[i].begin(), _P_H[i].end(), 0);\n        std::fill(_P_V[i].begin(), _P_V[i].end(), 0);\n        std::fill(_P_LD[i].begin(), _P_LD[i].end(), 0);\n        std::fill(_P_RD[i].begin(), _P_RD[i].end(), 0);\n\n        std::fill(_p_H[i].begin(), _p_H[i].end(), 0);\n        std::fill(_p_V[i].begin(), _p_V[i].end(), 0);\n        std::fill(_p_LD[i].begin(), _p_LD[i].end(), 0);\n        std::fill(_p_RD[i].begin(), _p_RD[i].end(), 0);\n    }\n\n    _pixel_values.clear();\n    _pixel_values_mean = std::numeric_limits<double>::quiet_NaN();\n    _pixel_values_STD = std::numeric_limits<double>::quiet_NaN();\n\n    // reset probability vectors as zeros\n    std::fill(_px_H.begin(), _px_H.end(), 0);\n    std::fill(_px_V.begin(), _px_V.end(), 0);\n    std::fill(_px_LD.begin(), _px_LD.end(), 0);\n    std::fill(_px_RD.begin(), _px_RD.end(), 0);\n\n    std::fill(_py_H.begin(), _py_H.end(), 0);\n    std::fill(_py_V.begin(), _py_V.end(), 0);\n    std::fill(_py_LD.begin(), _py_LD.end(), 0);\n    std::fill(_py_RD.begin(), _py_RD.end(), 0);\n\n    std::fill(_p_xpy_H.begin(), _p_xpy_H.end(), 0);\n    std::fill(_p_xpy_V.begin(), _p_xpy_V.end(), 0);\n    std::fill(_p_xpy_LD.begin(), _p_xpy_LD.end(), 0);\n    std::fill(_p_xpy_RD.begin(), _p_xpy_RD.end(), 0);\n\n    std::fill(_p_xny_H.begin(), _p_xny_H.end(), 0);\n    std::fill(_p_xny_V.begin(), _p_xny_V.end(), 0);\n    std::fill(_p_xny_LD.begin(), _p_xny_LD.end(), 0);\n    std::fill(_p_xny_RD.begin(), _p_xny_RD.end(), 0);\n\n    // reset factors as zeros\n    ResetFactors();\n}\n\nvoid TextureAnalysis::ResetFactors() {\n    // reset normalization factors as zeros\n    _R_H = 0;\n    _R_V = 0;\n    _R_LD = 0;\n    _R_RD = 0;\n\n    // initialize entropy factors\n    _HX_H = 0;\n    _HX_V = 0;\n    _HX_LD = 0;\n    _HX_RD = 0;\n\n    _HY_H = 0;\n    _HY_V = 0;\n    _HY_LD = 0;\n    _HY_RD = 0;\n\n    _HXY_H = 0;\n    _HXY_V = 0;\n    _HXY_LD = 0;\n    _HXY_RD = 0;\n\n    _HXY1_H = 0;\n    _HXY1_V = 0;\n    _HXY1_LD = 0;\n    _HXY1_RD = 0;\n\n    _HXY2_H = 0;\n    _HXY2_V = 0;\n    _HXY2_LD = 0;\n    _HXY2_RD = 0;\n}\n\nvoid TextureAnalysis::CountElemH(int i, int j) {\n    ++_P_H[i][j];\n    ++_R_H;\n}\n\nvoid TextureAnalysis::CountElemV(int i, int j) {\n    ++_P_V[i][j];\n    ++_R_V;\n}\n\nvoid TextureAnalysis::CountElemLD(int i, int j) {\n    ++_P_LD[i][j];\n    ++_R_LD;\n}\n\nvoid TextureAnalysis::CountElemRD(int i, int j) {\n    ++_P_RD[i][j];\n    ++_R_RD;\n}\n\nvoid TextureAnalysis::PushPixelValue(int pixel_value) {\n    _pixel_values.push_back((double) pixel_value);\n}\n\nvoid TextureAnalysis::Normalization() {\n    for (int i = 0; i < _Ng; ++i) {\n        for (int j = 0; j < _Ng; ++j) {\n            _p_H[i][j] = (double) _P_H[i][j] / (double) _R_H;\n            _p_V[i][j] = (double) _P_V[i][j] / (double) _R_V;\n            _p_LD[i][j] = (double) _P_LD[i][j] / (double) _R_LD;\n            _p_RD[i][j] = (double) _P_RD[i][j] / (double) _R_RD;\n        }\n    }\n\n    // calculate probability vectors\n    Calculate_px();\n    Calculate_py();\n    Calculate_p_xpy();\n    Calculate_p_xny();\n\n    // calculate pixels mean and STD in the region\n    CalculatePixelSTD(_pixel_values);\n}\n\nvoid TextureAnalysis::Calculate_px() {\n    for (int i = 0; i < _Ng; ++i) {\n        for (int j = 0; j < _Ng; ++j) {\n            _px_H[i] += _p_H[i][j];\n            _px_V[i] += _p_V[i][j];\n            _px_LD[i] += _p_LD[i][j];\n            _px_RD[i] += _p_RD[i][j];\n        }\n    }\n}\n\nvoid TextureAnalysis::Calculate_py() {\n    for (int j = 0; j < _Ng; ++j) {\n        for (int i = 0; i < _Ng; ++i) {\n            _py_H[j] += _p_H[i][j];\n            _py_V[j] += _p_V[i][j];\n            _py_LD[j] += _p_LD[i][j];\n            _py_RD[j] += _p_RD[i][j];\n        }\n    }\n}\n\nvoid TextureAnalysis::Calculate_p_xpy() {\n    for (int i = 0; i < _Ng; ++i) {\n        for (int j = 0; j < _Ng; ++j) {\n            int k = i + j;\n            _p_xpy_H[k] += _p_H[i][j];\n            _p_xpy_V[k] += _p_V[i][j];\n            _p_xpy_LD[k] += _p_LD[i][j];\n            _p_xpy_RD[k] += _p_RD[i][j];\n        }\n    }\n}\n\nvoid TextureAnalysis::Calculate_p_xny() {\n    for (int i = 0; i < _Ng; ++i) {\n        for (int j = 0; j < _Ng; ++j) {\n            int k = abs(i - j);\n            _p_xny_H[k] += _p_H[i][j];\n            _p_xny_V[k] += _p_V[i][j];\n            _p_xny_LD[k] += _p_LD[i][j];\n            _p_xny_RD[k] += _p_RD[i][j];\n        }\n    }\n}\n\ndouble TextureAnalysis::CalculateMean(const std::vector<double> &vec) {\n    double sum = 0.0;\n    for (int i = 0; i < vec.size(); ++i) {\n        sum += i * vec[i];\n    }\n    return sum;\n}\n\ndouble TextureAnalysis::CalculateSTD(const std::vector<double> &vec) {\n    double mean = CalculateMean(vec);\n    double sum = 0.0;\n    for (int i = 0; i < vec.size(); ++i) {\n        sum += (i - mean) * (i - mean) * vec[i];\n    }\n    return sqrt(sum);\n}\n\ndouble TextureAnalysis::CalculateGLCMMean_i(const std::vector<std::vector<double>> &mat) {\n    double mean = 0.0;\n    for (int i = 0; i < _Ng; ++i) {\n        for (int j = 0; j < _Ng; ++j) {\n            mean += i * mat[i][j];\n        }\n    }\n    return mean;\n}\n\ndouble TextureAnalysis::CalculateGLCMMean_j(const std::vector<std::vector<double>> &mat) {\n    double mean = 0.0;\n    for (int i = 0; i < _Ng; ++i) {\n        for (int j = 0; j < _Ng; ++j) {\n            mean += j * mat[i][j];\n        }\n    }\n    return mean;\n}\n\ndouble TextureAnalysis::CalculateGLCMSTD_i(const std::vector<std::vector<double>> &mat) {\n    double mu_x = CalculateGLCMMean_i(mat);\n    double sigma_x = 0.0;\n\n    for (int i = 0; i < _Ng; ++i) {\n        for (int j = 0; j < _Ng; ++j) {\n            sigma_x += (i - mu_x) * (i - mu_x) * mat[i][j];\n        }\n    }\n\n    return sqrt(sigma_x);\n}\n\ndouble TextureAnalysis::CalculateGLCMSTD_j(const std::vector<std::vector<double>> &mat) {\n    double mu_y = CalculateGLCMMean_j(mat);\n    double sigma_y = 0.0;\n\n    for (int i = 0; i < _Ng; ++i) {\n        for (int j = 0; j < _Ng; ++j) {\n            sigma_y += (j - mu_y) * (j - mu_y) * mat[i][j];\n        }\n    }\n\n    return sqrt(sigma_y);\n}\n\nvoid TextureAnalysis::CalculateHX() {\n    for (int i = 0; i < _Ng; ++i) {\n        if (_px_H[i] > 0) {\n            _HX_H -= _px_H[i] * log(_px_H[i]);\n        }\n        if (_px_V[i] > 0) {\n            _HX_V -= _px_V[i] * log(_px_V[i]);\n        }\n        if (_px_LD[i] > 0) {\n            _HX_LD -= _px_LD[i] * log(_px_LD[i]);\n        }\n        if (_px_RD[i] > 0) {\n            _HX_RD -= _px_RD[i] * log(_px_RD[i]);\n        }\n    }\n}\n\nvoid TextureAnalysis::CalculateHY() {\n    for (int i = 0; i < _Ng; ++i) {\n        if (_py_H[i] > 0) {\n            _HY_H -= _py_H[i] * log(_py_H[i]);\n        }\n        if (_py_V[i] > 0) {\n            _HY_V -= _py_V[i] * log(_py_V[i]);\n        }\n        if (_py_LD[i] > 0) {\n            _HY_LD -= _py_LD[i] * log(_py_LD[i]);\n        }\n        if (_py_RD[i] > 0) {\n            _HY_RD -= _py_RD[i] * log(_py_RD[i]);\n        }\n    }\n}\n\nvoid TextureAnalysis::CalculateHXY() {\n    for (int i = 0; i < _Ng; ++i) {\n        for (int j = 0; j < _Ng; ++j) {\n            if (_p_H[i][j] > 0) {\n                _HXY_H -= _p_H[i][j] * log(_p_H[i][j]);\n            }\n            if (_p_V[i][j] > 0) {\n                _HXY_V -= _p_V[i][j] * log(_p_V[i][j]);\n            }\n            if (_p_LD[i][j] > 0) {\n                _HXY_LD -= _p_LD[i][j] * log(_p_LD[i][j]);\n            }\n            if (_p_RD[i][j] > 0) {\n                _HXY_RD -= _p_RD[i][j] * log(_p_RD[i][j]);\n            }\n        }\n    }\n}\n\nvoid TextureAnalysis::CalculateHXY1() {\n    for (int i = 0; i < _Ng; ++i) {\n        for (int j = 0; j < _Ng; ++j) {\n            if (_px_H[i] * _py_H[j] > 0) {\n                _HXY1_H -= _p_H[i][j] * log(_px_H[i] * _py_H[j]);\n            }\n            if (_px_V[i] * _py_V[j] > 0) {\n                _HXY1_V -= _p_V[i][j] * log(_px_V[i] * _py_V[j]);\n            }\n            if (_px_LD[i] * _py_LD[j] > 0) {\n                _HXY1_LD -= _p_LD[i][j] * log(_px_LD[i] * _py_LD[j]);\n            }\n            if (_px_RD[i] * _py_RD[j] > 0) {\n                _HXY1_RD -= _p_RD[i][j] * log(_px_RD[i] * _py_RD[j]);\n            }\n        }\n    }\n}\n\nvoid TextureAnalysis::CalculateHXY2() {\n    for (int i = 0; i < _Ng; ++i) {\n        for (int j = 0; j < _Ng; ++j) {\n            if (_px_H[i] * _py_H[j] > 0) {\n                _HXY2_H -= _px_H[i] * _py_H[j] * log(_px_H[i] * _py_H[j]);\n            }\n            if (_px_V[i] * _py_V[j] > 0) {\n                _HXY2_V -= _px_V[i] * _py_V[j] * log(_px_V[i] * _py_V[j]);\n            }\n            if (_px_LD[i] * _py_LD[j] > 0) {\n                _HXY2_LD -= _px_LD[i] * _py_LD[j] * log(_px_LD[i] * _py_LD[j]);\n            }\n            if (_px_RD[i] * _py_RD[j] > 0) {\n                _HXY2_RD -= _px_RD[i] * _py_RD[j] * log(_px_RD[i] * _py_RD[j]);\n            }\n        }\n    }\n}\n\nFeatures TextureAnalysis::CalculateQ(int i, int j) {\n    double Q_H = 0.0;\n    double Q_V = 0.0;\n    double Q_LD = 0.0;\n    double Q_RD = 0.0;\n\n    for (int k = 0; k < _Ng; ++k) {\n        if ((_px_H[i] * _py_H[k]) != 0) {\n            Q_H += (_p_H[i][k] * _p_H[j][k]) / (_px_H[i] * _py_H[k]);\n        }\n        if ((_px_V[i] * _py_V[k]) != 0) {\n            Q_V += (_p_V[i][k] * _p_V[j][k]) / (_px_V[i] * _py_V[k]);\n        }\n        if ((_px_LD[i] * _py_LD[k]) != 0) {\n            Q_LD += (_p_LD[i][k] * _p_LD[j][k]) / (_px_LD[i] * _py_LD[k]);\n        }\n        if ((_px_RD[i] * _py_RD[k]) != 0) {\n            Q_RD += (_p_RD[i][k] * _p_RD[j][k]) / (_px_RD[i] * _py_RD[k]);\n        }\n    }\n\n    return {Q_H, Q_V, Q_LD, Q_RD};\n}\n\n//===============================================================================================================\n// Calculate texture feature coefficients\n//===============================================================================================================\n\nvoid TextureAnalysis::GetEnergy(Features &f) {\n    double f_H = 0.0;\n    double f_V = 0.0;\n    double f_LD = 0.0;\n    double f_RD = 0.0;\n\n    for (int i = 0; i < _Ng; ++i) {\n        for (int j = 0; j < _Ng; ++j) {\n            f_H += _p_H[i][j] * _p_H[i][j];\n            f_V += _p_V[i][j] * _p_V[i][j];\n            f_LD += _p_LD[i][j] * _p_LD[i][j];\n            f_RD += _p_RD[i][j] * _p_RD[i][j];\n        }\n    }\n\n    f(f_H, f_V, f_LD, f_RD);\n}\n\nvoid TextureAnalysis::GetContrast(Features &f) {\n    std::vector<double> sub_H(_Ng);\n    std::vector<double> sub_V(_Ng);\n    std::vector<double> sub_LD(_Ng);\n    std::vector<double> sub_RD(_Ng);\n\n    for (int i = 0; i < _Ng; ++i) {\n        for (int j = 0; j < _Ng; ++j) {\n            int n = abs(i - j);\n            sub_H[n] += _p_H[i][j];\n            sub_V[n] += _p_V[i][j];\n            sub_LD[n] += _p_LD[i][j];\n            sub_RD[n] += _p_RD[i][j];\n        }\n    }\n\n    double f_H = 0.0;\n    double f_V = 0.0;\n    double f_LD = 0.0;\n    double f_RD = 0.0;\n\n    for (int n = 0; n < _Ng; ++n) {\n        f_H += (n * n) * sub_H[n];\n        f_V += (n * n) * sub_V[n];\n        f_LD += (n * n) * sub_LD[n];\n        f_RD += (n * n) * sub_RD[n];\n    }\n\n    f(f_H, f_V, f_LD, f_RD);\n}\n\nvoid TextureAnalysis::GetContrastAnotherWay(Features &f) {\n    double f_H = 0.0;\n    double f_V = 0.0;\n    double f_LD = 0.0;\n    double f_RD = 0.0;\n\n    for (int i = 0; i < _Ng; ++i) {\n        for (int j = 0; j < _Ng; ++j) {\n            f_H += (i - j) * (i - j) * _p_H[i][j];\n            f_V += (i - j) * (i - j) * _p_V[i][j];\n            f_LD += (i - j) * (i - j) * _p_LD[i][j];\n            f_RD += (i - j) * (i - j) * _p_RD[i][j];\n        }\n    }\n\n    f(f_H, f_V, f_LD, f_RD);\n}\n\nvoid TextureAnalysis::GetCorrelationI(Features &f) {\n    // Calculate means\n    double mu_x_H = CalculateMean(_px_H);\n    double mu_x_V = CalculateMean(_px_V);\n    double mu_x_LD = CalculateMean(_px_LD);\n    double mu_x_RD = CalculateMean(_px_RD);\n\n    double mu_y_H = CalculateMean(_py_H);\n    double mu_y_V = CalculateMean(_py_V);\n    double mu_y_LD = CalculateMean(_py_LD);\n    double mu_y_RD = CalculateMean(_py_RD);\n\n    // Calculate STDs\n    double sigma_x_H = CalculateSTD(_px_H);\n    double sigma_x_V = CalculateSTD(_px_V);\n    double sigma_x_LD = CalculateSTD(_px_LD);\n    double sigma_x_RD = CalculateSTD(_px_RD);\n\n    double sigma_y_H = CalculateSTD(_py_H);\n    double sigma_y_V = CalculateSTD(_py_V);\n    double sigma_y_LD = CalculateSTD(_py_LD);\n    double sigma_y_RD = CalculateSTD(_py_RD);\n\n    double f_H = 0.0;\n    double f_V = 0.0;\n    double f_LD = 0.0;\n    double f_RD = 0.0;\n\n    for (int i = 0; i < _Ng; ++i) {\n        for (int j = 0; j < _Ng; ++j) {\n            f_H += (i - mu_x_H) * (j - mu_y_H) * _p_H[i][j] / (sigma_x_H * sigma_y_H);\n            f_V += (i - mu_x_V) * (j - mu_y_V) * _p_V[i][j] / (sigma_x_V * sigma_y_V);\n            f_LD += (i - mu_x_LD) * (j - mu_y_LD) * _p_LD[i][j] / (sigma_x_LD * sigma_y_LD);\n            f_RD += (i - mu_x_RD) * (j - mu_y_RD) * _p_RD[i][j] / (sigma_x_RD * sigma_y_RD);\n        }\n    }\n\n    f(f_H, f_V, f_LD, f_RD);\n}\n\nvoid TextureAnalysis::GetCorrelationIAnotherWay(Features &f) {\n    // Calculate means\n    double mu_x_H = CalculateGLCMMean_i(_p_H);\n    double mu_x_V = CalculateGLCMMean_i(_p_V);\n    double mu_x_LD = CalculateGLCMMean_i(_p_LD);\n    double mu_x_RD = CalculateGLCMMean_i(_p_RD);\n\n    double mu_y_H = CalculateGLCMMean_j(_p_H);\n    double mu_y_V = CalculateGLCMMean_j(_p_V);\n    double mu_y_LD = CalculateGLCMMean_j(_p_LD);\n    double mu_y_RD = CalculateGLCMMean_j(_p_RD);\n\n    // Calculate STDs\n    double sigma_x_H = CalculateGLCMSTD_i(_p_H);\n    double sigma_x_V = CalculateGLCMSTD_i(_p_V);\n    double sigma_x_LD = CalculateGLCMSTD_i(_p_LD);\n    double sigma_x_RD = CalculateGLCMSTD_i(_p_RD);\n\n    double sigma_y_H = CalculateGLCMSTD_j(_p_H);\n    double sigma_y_V = CalculateGLCMSTD_j(_p_V);\n    double sigma_y_LD = CalculateGLCMSTD_j(_p_LD);\n    double sigma_y_RD = CalculateGLCMSTD_j(_p_RD);\n\n    double f_H = 0.0;\n    double f_V = 0.0;\n    double f_LD = 0.0;\n    double f_RD = 0.0;\n\n    for (int i = 0; i < _Ng; ++i) {\n        for (int j = 0; j < _Ng; ++j) {\n            f_H += (i - mu_x_H) * (j - mu_y_H) * _p_H[i][j] / (sigma_x_H * sigma_y_H);\n            f_V += (i - mu_x_V) * (j - mu_y_V) * _p_V[i][j] / (sigma_x_V * sigma_y_V);\n            f_LD += (i - mu_x_LD) * (j - mu_y_LD) * _p_LD[i][j] / (sigma_x_LD * sigma_y_LD);\n            f_RD += (i - mu_x_RD) * (j - mu_y_RD) * _p_RD[i][j] / (sigma_x_RD * sigma_y_RD);\n        }\n    }\n\n    f(f_H, f_V, f_LD, f_RD);\n}\n\nvoid TextureAnalysis::GetCorrelationII(Features &f) {\n    // Calculate means\n    double mu_x_H = CalculateMean(_px_H);\n    double mu_x_V = CalculateMean(_px_V);\n    double mu_x_LD = CalculateMean(_px_LD);\n    double mu_x_RD = CalculateMean(_px_RD);\n\n    double mu_y_H = CalculateMean(_py_H);\n    double mu_y_V = CalculateMean(_py_V);\n    double mu_y_LD = CalculateMean(_py_LD);\n    double mu_y_RD = CalculateMean(_py_RD);\n\n    // Calculate STDs\n    double sigma_x_H = CalculateSTD(_px_H);\n    double sigma_x_V = CalculateSTD(_px_V);\n    double sigma_x_LD = CalculateSTD(_px_LD);\n    double sigma_x_RD = CalculateSTD(_px_RD);\n\n    double sigma_y_H = CalculateSTD(_py_H);\n    double sigma_y_V = CalculateSTD(_py_V);\n    double sigma_y_LD = CalculateSTD(_py_LD);\n    double sigma_y_RD = CalculateSTD(_py_RD);\n\n    double f_H = 0.0;\n    double f_V = 0.0;\n    double f_LD = 0.0;\n    double f_RD = 0.0;\n\n    for (int i = 0; i < _Ng; ++i) {\n        for (int j = 0; j < _Ng; ++j) {\n            f_H += (i * j) * _p_H[i][j];\n            f_V += (i * j) * _p_V[i][j];\n            f_LD += (i * j) * _p_LD[i][j];\n            f_RD += (i * j) * _p_RD[i][j];\n        }\n    }\n\n    f_H = (f_H - (mu_x_H * mu_y_H)) / (sigma_x_H * sigma_y_H);\n    f_V = (f_V - (mu_x_V * mu_y_V)) / (sigma_x_V * sigma_y_V);\n    f_LD = (f_LD - (mu_x_LD * mu_y_LD)) / (sigma_x_LD * sigma_y_LD);\n    f_RD = (f_RD - (mu_x_RD * mu_y_RD)) / (sigma_x_RD * sigma_y_RD);\n\n    f(f_H, f_V, f_LD, f_RD);\n}\n\nvoid TextureAnalysis::GetCorrelationIIAnotherWay(Features &f) {\n    // Calculate means\n    double mu_x_H = CalculateGLCMMean_i(_p_H);\n    double mu_x_V = CalculateGLCMMean_i(_p_V);\n    double mu_x_LD = CalculateGLCMMean_i(_p_LD);\n    double mu_x_RD = CalculateGLCMMean_i(_p_RD);\n\n    double mu_y_H = CalculateGLCMMean_j(_p_H);\n    double mu_y_V = CalculateGLCMMean_j(_p_V);\n    double mu_y_LD = CalculateGLCMMean_j(_p_LD);\n    double mu_y_RD = CalculateGLCMMean_j(_p_RD);\n\n    // Calculate STDs\n    double sigma_x_H = CalculateGLCMSTD_i(_p_H);\n    double sigma_x_V = CalculateGLCMSTD_i(_p_V);\n    double sigma_x_LD = CalculateGLCMSTD_i(_p_LD);\n    double sigma_x_RD = CalculateGLCMSTD_i(_p_RD);\n\n    double sigma_y_H = CalculateGLCMSTD_j(_p_H);\n    double sigma_y_V = CalculateGLCMSTD_j(_p_V);\n    double sigma_y_LD = CalculateGLCMSTD_j(_p_LD);\n    double sigma_y_RD = CalculateGLCMSTD_j(_p_RD);\n\n    double f_H = 0.0;\n    double f_V = 0.0;\n    double f_LD = 0.0;\n    double f_RD = 0.0;\n\n    for (int i = 0; i < _Ng; ++i) {\n        for (int j = 0; j < _Ng; ++j) {\n            f_H += (i * j) * _p_H[i][j];\n            f_V += (i * j) * _p_V[i][j];\n            f_LD += (i * j) * _p_LD[i][j];\n            f_RD += (i * j) * _p_RD[i][j];\n        }\n    }\n\n    f_H = (f_H - (mu_x_H * mu_y_H)) / (sigma_x_H * sigma_y_H);\n    f_V = (f_V - (mu_x_V * mu_y_V)) / (sigma_x_V * sigma_y_V);\n    f_LD = (f_LD - (mu_x_LD * mu_y_LD)) / (sigma_x_LD * sigma_y_LD);\n    f_RD = (f_RD - (mu_x_RD * mu_y_RD)) / (sigma_x_RD * sigma_y_RD);\n\n    f(f_H, f_V, f_LD, f_RD);\n}\n\nvoid TextureAnalysis::GetCorrelationIII(Features &f) {\n    // Calculate means\n    double mu_x_H = CalculateMean(_px_H);\n    double mu_x_V = CalculateMean(_px_V);\n    double mu_x_LD = CalculateMean(_px_LD);\n    double mu_x_RD = CalculateMean(_px_RD);\n\n    double mu_y_H = CalculateMean(_py_H);\n    double mu_y_V = CalculateMean(_py_V);\n    double mu_y_LD = CalculateMean(_py_LD);\n    double mu_y_RD = CalculateMean(_py_RD);\n\n    // Calculate STDs\n    double sigma_x_H = CalculateSTD(_px_H);\n    double sigma_x_V = CalculateSTD(_px_V);\n    double sigma_x_LD = CalculateSTD(_px_LD);\n    double sigma_x_RD = CalculateSTD(_px_RD);\n\n    double sigma_y_H = CalculateSTD(_py_H);\n    double sigma_y_V = CalculateSTD(_py_V);\n    double sigma_y_LD = CalculateSTD(_py_LD);\n    double sigma_y_RD = CalculateSTD(_py_RD);\n\n    double f_H = 0.0;\n    double f_V = 0.0;\n    double f_LD = 0.0;\n    double f_RD = 0.0;\n\n    for (int i = 0; i < _Ng; ++i) {\n        for (int j = 0; j < _Ng; ++j) {\n            f_H += (i * j) * _p_H[i][j];\n            f_V += (i * j) * _p_V[i][j];\n            f_LD += (i * j) * _p_LD[i][j];\n            f_RD += (i * j) * _p_RD[i][j];\n        }\n    }\n\n    f_H = (f_H - (mu_x_H * mu_y_H)) / (sigma_x_H * sigma_y_H * sigma_x_H * sigma_y_H);\n    f_V = (f_V - (mu_x_V * mu_y_V)) / (sigma_x_V * sigma_y_V * sigma_x_V * sigma_y_V);\n    f_LD = (f_LD - (mu_x_LD * mu_y_LD)) / (sigma_x_LD * sigma_y_LD * sigma_x_LD * sigma_y_LD);\n    f_RD = (f_RD - (mu_x_RD * mu_y_RD)) / (sigma_x_RD * sigma_y_RD * sigma_x_RD * sigma_y_RD);\n\n    f(f_H, f_V, f_LD, f_RD);\n}\n\nvoid TextureAnalysis::GetSumOfSquares(Features &f) {\n    double mean_H_x = CalculateGLCMMean_i(_p_H);\n    double mean_V_x = CalculateGLCMMean_i(_p_V);\n    double mean_LD_x = CalculateGLCMMean_i(_p_LD);\n    double mean_RD_x = CalculateGLCMMean_i(_p_RD);\n\n    double mean_H_y = CalculateGLCMMean_j(_p_H);\n    double mean_V_y = CalculateGLCMMean_j(_p_V);\n    double mean_LD_y = CalculateGLCMMean_j(_p_LD);\n    double mean_RD_y = CalculateGLCMMean_j(_p_RD);\n\n    double f_H = 0.0;\n    double f_V = 0.0;\n    double f_LD = 0.0;\n    double f_RD = 0.0;\n\n    for (int i = 0; i < _Ng; ++i) {\n        for (int j = 0; j < _Ng; ++j) {\n            f_H += (i - mean_H_x) * (i - mean_H_x) * _p_H[i][j] + (j - mean_H_y) * (j - mean_H_y) * _p_H[i][j];\n            f_V += (i - mean_V_x) * (i - mean_V_x) * _p_V[i][j] + (j - mean_V_y) * (j - mean_V_y) * _p_V[i][j];\n            f_LD += (i - mean_LD_x) * (i - mean_LD_x) * _p_LD[i][j] + (j - mean_LD_y) * (j - mean_LD_y) * _p_LD[i][j];\n            f_RD += (i - mean_RD_x) * (i - mean_RD_x) * _p_RD[i][j] + (j - mean_RD_y) * (j - mean_RD_y) * _p_RD[i][j];\n        }\n    }\n\n    f(f_H, f_V, f_LD, f_RD);\n}\n\nvoid TextureAnalysis::GetSumOfSquares_i(Features &f) {\n    double mean_H = CalculateGLCMMean_i(_p_H);\n    double mean_V = CalculateGLCMMean_i(_p_V);\n    double mean_LD = CalculateGLCMMean_i(_p_LD);\n    double mean_RD = CalculateGLCMMean_i(_p_RD);\n\n    double f_H = 0.0;\n    double f_V = 0.0;\n    double f_LD = 0.0;\n    double f_RD = 0.0;\n\n    for (int i = 0; i < _Ng; ++i) {\n        for (int j = 0; j < _Ng; ++j) {\n            f_H += (i - mean_H) * (i - mean_H) * _p_H[i][j];\n            f_V += (i - mean_V) * (i - mean_V) * _p_V[i][j];\n            f_LD += (i - mean_LD) * (i - mean_LD) * _p_LD[i][j];\n            f_RD += (i - mean_RD) * (i - mean_RD) * _p_RD[i][j];\n        }\n    }\n\n    f(f_H, f_V, f_LD, f_RD);\n}\n\nvoid TextureAnalysis::GetSumOfSquares_j(Features &f) {\n    double mean_H = CalculateGLCMMean_j(_p_H);\n    double mean_V = CalculateGLCMMean_j(_p_V);\n    double mean_LD = CalculateGLCMMean_j(_p_LD);\n    double mean_RD = CalculateGLCMMean_j(_p_RD);\n\n    double f_H = 0.0;\n    double f_V = 0.0;\n    double f_LD = 0.0;\n    double f_RD = 0.0;\n\n    for (int i = 0; i < _Ng; ++i) {\n        for (int j = 0; j < _Ng; ++j) {\n            f_H += (j - mean_H) * (j - mean_H) * _p_H[i][j];\n            f_V += (j - mean_V) * (j - mean_V) * _p_V[i][j];\n            f_LD += (j - mean_LD) * (j - mean_LD) * _p_LD[i][j];\n            f_RD += (j - mean_RD) * (j - mean_RD) * _p_RD[i][j];\n        }\n    }\n\n    f(f_H, f_V, f_LD, f_RD);\n}\n\nvoid TextureAnalysis::GetHomogeneityII(Features &f) {\n    double f_H = 0.0;\n    double f_V = 0.0;\n    double f_LD = 0.0;\n    double f_RD = 0.0;\n\n    for (int i = 0; i < _Ng; ++i) {\n        for (int j = 0; j < _Ng; ++j) {\n            f_H += _p_H[i][j] / (1 + (i - j) * (i - j));\n            f_V += _p_V[i][j] / (1 + (i - j) * (i - j));\n            f_LD += _p_LD[i][j] / (1 + (i - j) * (i - j));\n            f_RD += _p_RD[i][j] / (1 + (i - j) * (i - j));\n        }\n    }\n\n    f(f_H, f_V, f_LD, f_RD);\n}\n\nvoid TextureAnalysis::GetSumAverage(Features &f) {\n    double f_H = 0.0;\n    double f_V = 0.0;\n    double f_LD = 0.0;\n    double f_RD = 0.0;\n\n    for (int i = 0; i < (2 * _Ng - 1); ++i) {\n        f_H += i * _p_xpy_H[i];\n        f_V += i * _p_xpy_V[i];\n        f_LD += i * _p_xpy_LD[i];\n        f_RD += i * _p_xpy_RD[i];\n    }\n\n    f(f_H, f_V, f_LD, f_RD);\n}\n\nvoid TextureAnalysis::GetSumVariance(Features &f) {\n    Features f8;\n    GetSumEntropy(f8);\n\n    double f_H = 0.0;\n    double f_V = 0.0;\n    double f_LD = 0.0;\n    double f_RD = 0.0;\n\n    for (int i = 0; i < (2 * _Ng - 1); ++i) {\n        f_H += (i - f8.H) * (i - f8.H) * _p_xpy_H[i];\n        f_V += (i - f8.V) * (i - f8.V) * _p_xpy_V[i];\n        f_LD += (i - f8.LD) * (i - f8.LD) * _p_xpy_LD[i];\n        f_RD += (i - f8.RD) * (i - f8.RD) * _p_xpy_RD[i];\n    }\n\n    f(f_H, f_V, f_LD, f_RD);\n}\n\nvoid TextureAnalysis::GetSumEntropy(Features &f) {\n    double f_H = 0.0;\n    double f_V = 0.0;\n    double f_LD = 0.0;\n    double f_RD = 0.0;\n\n    for (int i = 0; i < (2 * _Ng - 1); ++i) {\n        if (_p_xpy_H[i] > 0) {\n            f_H -= _p_xpy_H[i] * log(_p_xpy_H[i]);\n        }\n        if (_p_xpy_V[i] > 0) {\n            f_V -= _p_xpy_V[i] * log(_p_xpy_V[i]);\n        }\n        if (_p_xpy_LD[i] > 0) {\n            f_LD -= _p_xpy_LD[i] * log(_p_xpy_LD[i]);\n        }\n        if (_p_xpy_RD[i] > 0) {\n            f_RD -= _p_xpy_RD[i] * log(_p_xpy_RD[i]);\n        }\n    }\n\n    f(f_H, f_V, f_LD, f_RD);\n}\n\nvoid TextureAnalysis::GetEntropy(Features &f) {\n    double f_H = 0.0;\n    double f_V = 0.0;\n    double f_LD = 0.0;\n    double f_RD = 0.0;\n\n    for (int i = 0; i < _Ng; ++i) {\n        for (int j = 0; j < _Ng; ++j) {\n            if (_p_H[i][j] > 0) {\n                f_H -= _p_H[i][j] * log(_p_H[i][j]);\n            }\n            if (_p_V[i][j] > 0) {\n                f_V -= _p_V[i][j] * log(_p_V[i][j]);\n            }\n            if (_p_LD[i][j] > 0) {\n                f_LD -= _p_LD[i][j] * log(_p_LD[i][j]);\n            }\n            if (_p_RD[i][j] > 0) {\n                f_RD -= _p_RD[i][j] * log(_p_RD[i][j]);\n            }\n        }\n    }\n\n    f(f_H, f_V, f_LD, f_RD);\n}\n\nvoid TextureAnalysis::GetDifferenceVariance(Features &f) {\n    double f_H = 0.0;\n    double f_V = 0.0;\n    double f_LD = 0.0;\n    double f_RD = 0.0;\n\n    for (int i = 0; i < _Ng; ++i) {\n        f_H += i * i * _p_xny_H[i];\n        f_V += i * i * _p_xny_V[i];\n        f_LD += i * i * _p_xny_LD[i];\n        f_RD += i * i * _p_xny_RD[i];\n    }\n\n    f(f_H, f_V, f_LD, f_RD);\n}\n\nvoid TextureAnalysis::GetDifferenceEntropy(Features &f) {\n    double f_H = 0.0;\n    double f_V = 0.0;\n    double f_LD = 0.0;\n    double f_RD = 0.0;\n\n    for (int i = 0; i < _Ng; ++i) {\n        if (_p_xny_H[i] > 0) {\n            f_H -= _p_xny_H[i] * log(_p_xny_H[i]);\n        }\n        if (_p_xny_V[i] > 0) {\n            f_V -= _p_xny_V[i] * log(_p_xny_V[i]);\n        }\n        if (_p_xny_LD[i] > 0) {\n            f_LD -= _p_xny_LD[i] * log(_p_xny_LD[i]);\n        }\n        if (_p_xny_RD[i] > 0) {\n            f_RD -= _p_xny_RD[i] * log(_p_xny_RD[i]);\n        }\n    }\n\n    f(f_H, f_V, f_LD, f_RD);\n}\n\nvoid TextureAnalysis::GetInformationMeasuresOfCorrelation(Features &f1, Features &f2) {\n    // calculate entropy factors\n    CalculateHX();\n    CalculateHY();\n    CalculateHXY();\n    CalculateHXY1();\n    CalculateHXY2();\n\n    // calculate the first Information Measures of Correlation\n    double f1_H;\n    double f1_V;\n    double f1_LD;\n    double f1_RD;\n\n    f1_H = (_HXY_H - _HXY1_H) / std::max(_HX_H, _HY_H);\n    f1_V = (_HXY_V - _HXY1_V) / std::max(_HX_V, _HY_V);\n    f1_LD = (_HXY_LD - _HXY1_LD) / std::max(_HX_LD, _HY_LD);\n    f1_RD = (_HXY_RD - _HXY1_RD) / std::max(_HX_RD, _HY_RD);\n\n    f1(f1_H, f1_V, f1_LD, f1_RD);\n\n    // calculate the second Information Measures of Correlation\n    double f2_H = sqrt(1.0 - exp(-2.0 * (_HXY2_H - _HXY_H)));\n    double f2_V = sqrt(1.0 - exp(-2.0 * (_HXY2_V - _HXY_V)));\n    double f2_LD = sqrt(1.0 - exp(-2.0 * (_HXY2_LD - _HXY_LD)));\n    double f2_RD = sqrt(1.0 - exp(-2.0 * (_HXY2_RD - _HXY_RD)));\n\n    f2(f2_H, f2_V, f2_LD, f2_RD);\n}\n\nvoid TextureAnalysis::GetMaximalCorrelationCoefficient(Features &f) {\n    // fill in Q matrices\n    Eigen::MatrixXd Q_H(_Ng, _Ng);\n    Eigen::MatrixXd Q_V(_Ng, _Ng);\n    Eigen::MatrixXd Q_LD(_Ng, _Ng);\n    Eigen::MatrixXd Q_RD(_Ng, _Ng);\n\n    for (int i = 0; i < _Ng; ++i) {\n        for (int j = 0; j < _Ng; ++j) {\n            Features q = CalculateQ(i, j);\n            // std::cout << \"q_H = \" << q.H << \", q_V = \" << q.V << \", q_LD = \" << q.LD << \", q_RD = \" << q.RD << std::endl;\n            Q_H(i, j) = q.H;\n            Q_V(i, j) = q.V;\n            Q_LD(i, j) = q.LD;\n            Q_RD(i, j) = q.RD;\n        }\n    }\n\n    Eigen::EigenSolver<Eigen::MatrixXd> eigen_solver_Q_H(Q_H);\n    Eigen::EigenSolver<Eigen::MatrixXd> eigen_solver_Q_V(Q_V);\n    Eigen::EigenSolver<Eigen::MatrixXd> eigen_solver_Q_LD(Q_LD);\n    Eigen::EigenSolver<Eigen::MatrixXd> eigen_solver_Q_RD(Q_RD);\n\n    // get eigenvalues\n    std::vector<double> eigens_H;\n    std::vector<double> eigens_V;\n    std::vector<double> eigens_LD;\n    std::vector<double> eigens_RD;\n\n    for (int i = 0; i < _Ng; ++i) {\n        std::complex<double> E_H = eigen_solver_Q_H.eigenvalues().col(0)[i];\n        std::complex<double> E_V = eigen_solver_Q_V.eigenvalues().col(0)[i];\n        std::complex<double> E_LD = eigen_solver_Q_LD.eigenvalues().col(0)[i];\n        std::complex<double> E_RD = eigen_solver_Q_RD.eigenvalues().col(0)[i];\n\n        eigens_H.push_back(E_H.real());\n        eigens_V.push_back(E_V.real());\n        eigens_LD.push_back(E_LD.real());\n        eigens_RD.push_back(E_RD.real());\n    }\n\n    // get second largest eigenvalues\n    std::nth_element(eigens_H.begin(), eigens_H.begin() + 1, eigens_H.end(), std::greater<double>());\n    std::nth_element(eigens_V.begin(), eigens_V.begin() + 1, eigens_V.end(), std::greater<double>());\n    std::nth_element(eigens_LD.begin(), eigens_LD.begin() + 1, eigens_LD.end(), std::greater<double>());\n    std::nth_element(eigens_RD.begin(), eigens_RD.begin() + 1, eigens_RD.end(), std::greater<double>());\n\n    f(eigens_H[1], eigens_V[1], eigens_LD[1], eigens_RD[1]);\n}\n\nvoid TextureAnalysis::GetMean(Features &f) {\n    double f_H = _pixel_values_mean;\n    double f_V = _pixel_values_mean;\n    double f_LD = _pixel_values_mean;\n    double f_RD = _pixel_values_mean;\n    f(f_H, f_V, f_LD, f_RD);\n}\n\nvoid TextureAnalysis::GetStd(Features &f) {\n    double f_H = _pixel_values_STD;\n    double f_V = _pixel_values_STD;\n    double f_LD = _pixel_values_STD;\n    double f_RD = _pixel_values_STD;\n    f(f_H, f_V, f_LD, f_RD);\n}\n\nvoid TextureAnalysis::GetAutoCorrelation(Features &f) {\n    double f_H = 0.0;\n    double f_V = 0.0;\n    double f_LD = 0.0;\n    double f_RD = 0.0;\n\n    for (int i = 0; i < _Ng; ++i) {\n        for (int j = 0; j < _Ng; ++j) {\n            f_H += i * j * _p_H[i][j];\n            f_V += i * j * _p_V[i][j];\n            f_LD += i * j * _p_LD[i][j];\n            f_RD += i * j * _p_RD[i][j];\n        }\n    }\n\n    f(f_H, f_V, f_LD, f_RD);\n}\n\nvoid TextureAnalysis::GetClusterProminence(Features &f) {\n    // Calculate means\n    double mu_x_H = CalculateMean(_px_H);\n    double mu_x_V = CalculateMean(_px_V);\n    double mu_x_LD = CalculateMean(_px_LD);\n    double mu_x_RD = CalculateMean(_px_RD);\n\n    double mu_y_H = CalculateMean(_py_H);\n    double mu_y_V = CalculateMean(_py_V);\n    double mu_y_LD = CalculateMean(_py_LD);\n    double mu_y_RD = CalculateMean(_py_RD);\n\n    double f_H = 0.0;\n    double f_V = 0.0;\n    double f_LD = 0.0;\n    double f_RD = 0.0;\n\n    for (int i = 0; i < _Ng; ++i) {\n        for (int j = 0; j < _Ng; ++j) {\n            f_H += pow((i + j - mu_x_H - mu_y_H), 4) * _p_H[i][j];\n            f_V += pow((i + j - mu_x_V - mu_y_V), 4) * _p_V[i][j];\n            f_LD += pow((i + j - mu_x_LD - mu_y_LD), 4) * _p_LD[i][j];\n            f_RD += pow((i + j - mu_x_RD - mu_y_RD), 4) * _p_RD[i][j];\n        }\n    }\n\n    f(f_H, f_V, f_LD, f_RD);\n}\n\nvoid TextureAnalysis::GetClusterShade(Features &f) {\n    // Calculate means\n    double mu_x_H = CalculateMean(_px_H);\n    double mu_x_V = CalculateMean(_px_V);\n    double mu_x_LD = CalculateMean(_px_LD);\n    double mu_x_RD = CalculateMean(_px_RD);\n\n    double mu_y_H = CalculateMean(_py_H);\n    double mu_y_V = CalculateMean(_py_V);\n    double mu_y_LD = CalculateMean(_py_LD);\n    double mu_y_RD = CalculateMean(_py_RD);\n\n    double f_H = 0.0;\n    double f_V = 0.0;\n    double f_LD = 0.0;\n    double f_RD = 0.0;\n\n    for (int i = 0; i < _Ng; ++i) {\n        for (int j = 0; j < _Ng; ++j) {\n            f_H += pow((i + j - mu_x_H - mu_y_H), 3) * _p_H[i][j];\n            f_V += pow((i + j - mu_x_V - mu_y_V), 3) * _p_V[i][j];\n            f_LD += pow((i + j - mu_x_LD - mu_y_LD), 3) * _p_LD[i][j];\n            f_RD += pow((i + j - mu_x_RD - mu_y_RD), 3) * _p_RD[i][j];\n        }\n    }\n\n    f(f_H, f_V, f_LD, f_RD);\n}\n\nvoid TextureAnalysis::GetDissimilarity(Features &f) {\n    double f_H = 0.0;\n    double f_V = 0.0;\n    double f_LD = 0.0;\n    double f_RD = 0.0;\n\n    for (int i = 0; i < _Ng; ++i) {\n        for (int j = 0; j < _Ng; ++j) {\n            f_H += fabs(i - j) * _p_H[i][j];\n            f_V += fabs(i - j) * _p_V[i][j];\n            f_LD += fabs(i - j) * _p_LD[i][j];\n            f_RD += fabs(i - j) * _p_RD[i][j];\n        }\n    }\n\n    f(f_H, f_V, f_LD, f_RD);\n}\n\nvoid TextureAnalysis::GetHomogeneityI(Features &f) {\n    double f_H = 0.0;\n    double f_V = 0.0;\n    double f_LD = 0.0;\n    double f_RD = 0.0;\n\n    for (int i = 0; i < _Ng; ++i) {\n        for (int j = 0; j < _Ng; ++j) {\n            f_H += _p_H[i][j] / (1 + fabs(i - j));\n            f_V += _p_V[i][j] / (1 + fabs(i - j));\n            f_LD += _p_LD[i][j] / (1 + fabs(i - j));\n            f_RD += _p_RD[i][j] / (1 + fabs(i - j));\n        }\n    }\n\n    f(f_H, f_V, f_LD, f_RD);\n}\n\nvoid TextureAnalysis::GetMaximumProbability(Features &f) {\n    double f_H = 0.0;\n    double f_V = 0.0;\n    double f_LD = 0.0;\n    double f_RD = 0.0;\n\n    for (int i = 0; i < _Ng; ++i) {\n        for (int j = 0; j < _Ng; ++j) {\n            if (_p_H[i][j] > f_H) {\n                f_H = _p_H[i][j];\n            }\n            if (_p_V[i][j] > f_V) {\n                f_V = _p_V[i][j];\n            }\n            if (_p_LD[i][j] > f_LD) {\n                f_LD = _p_LD[i][j];\n            }\n            if (_p_RD[i][j] > f_RD) {\n                f_RD = _p_RD[i][j];\n            }\n        }\n    }\n\n    f(f_H, f_V, f_LD, f_RD);\n}\n\nvoid TextureAnalysis::GetInverseDifferenceNormalized(Features &f) {\n    double f_H = 0.0;\n    double f_V = 0.0;\n    double f_LD = 0.0;\n    double f_RD = 0.0;\n\n    for (int i = 0; i < _Ng; ++i) {\n        for (int j = 0; j < _Ng; ++j) {\n            f_H += _p_H[i][j] / (1 + (abs(i - j) * abs(i - j) / _Ng));\n            f_V += _p_V[i][j] / (1 + (abs(i - j) * abs(i - j) / _Ng));\n            f_LD += _p_LD[i][j] / (1 + (abs(i - j) * abs(i - j) / _Ng));\n            f_RD += _p_RD[i][j] / (1 + (abs(i - j) * abs(i - j) / _Ng));\n        }\n    }\n\n    f(f_H, f_V, f_LD, f_RD);\n}\n\nvoid TextureAnalysis::GetInverseDifferenceMomentNormalized(Features &f) {\n    double f_H = 0.0;\n    double f_V = 0.0;\n    double f_LD = 0.0;\n    double f_RD = 0.0;\n\n    for (int i = 0; i < _Ng; ++i) {\n        for (int j = 0; j < _Ng; ++j) {\n            f_H += _p_H[i][j] / (1 + ((i - j) * (i - j) / _Ng));\n            f_V += _p_V[i][j] / (1 + ((i - j) * (i - j) / _Ng));\n            f_LD += _p_LD[i][j] / (1 + ((i - j) * (i - j) / _Ng));\n            f_RD += _p_RD[i][j] / (1 + ((i - j) * (i - j) / _Ng));\n        }\n    }\n\n    f(f_H, f_V, f_LD, f_RD);\n}\n\nstd::map<Type, Features> TextureAnalysis::Calculate(const std::set<Type> &types) {\n    std::map<Type, Features> results;\n    bool information_measures_of_correlation_done = false;\n    for (auto type : types) {\n        switch (type) {\n            case Type::Mean:\n                GetMean(results[Type::Mean]);\n                break;\n            case Type::Std:\n                GetStd(results[Type::Std]);\n                break;\n            case Type::AutoCorrelation:\n                GetAutoCorrelation(results[Type::AutoCorrelation]);\n                break;\n            case Type::Contrast:\n                GetContrast(results[Type::Contrast]);\n                break;\n            case Type::ContrastAnotherWay:\n                GetContrastAnotherWay(results[Type::ContrastAnotherWay]);\n                break;\n            case Type::CorrelationI:\n                GetCorrelationI(results[Type::CorrelationI]);\n                break;\n            case Type::CorrelationIAnotherWay:\n                GetCorrelationIAnotherWay(results[Type::CorrelationIAnotherWay]);\n                break;\n            case Type::CorrelationII:\n                GetCorrelationII(results[Type::CorrelationII]);\n                break;\n            case Type::CorrelationIIAnotherWay:\n                GetCorrelationIIAnotherWay(results[Type::CorrelationIIAnotherWay]);\n                break;\n            case Type::CorrelationIII:\n                GetCorrelationIII(results[Type::CorrelationIII]);\n                break;\n            case Type::ClusterProminence:\n                GetClusterProminence(results[Type::ClusterProminence]);\n                break;\n            case Type::ClusterShade:\n                GetClusterShade(results[Type::ClusterShade]);\n                break;\n            case Type::Dissimilarity:\n                GetDissimilarity(results[Type::Dissimilarity]);\n                break;\n            case Type::Energy:\n                GetEnergy(results[Type::Energy]);\n                break;\n            case Type::Entropy:\n                GetEntropy(results[Type::Entropy]);\n                break;\n            case Type::HomogeneityI:\n                GetHomogeneityI(results[Type::HomogeneityI]);\n                break;\n            case Type::HomogeneityII:\n                GetHomogeneityII(results[Type::HomogeneityII]);\n                break;\n            case Type::MaximumProbability:\n                GetMaximumProbability(results[Type::MaximumProbability]);\n                break;\n            case Type::SumOfSquares:\n                GetSumOfSquares(results[Type::SumOfSquares]);\n                break;\n            case Type::SumOfSquaresI:\n                GetSumOfSquares_i(results[Type::SumOfSquaresI]);\n                break;\n            case Type::SumOfSquaresJ:\n                GetSumOfSquares_j(results[Type::SumOfSquaresJ]);\n                break;\n            case Type::SumAverage:\n                GetSumAverage(results[Type::SumAverage]);\n                break;\n            case Type::SumEntropy:\n                GetSumEntropy(results[Type::SumEntropy]);\n                break;\n            case Type::SumVariance:\n                GetSumVariance(results[Type::SumVariance]);\n                break;\n            case Type::DifferenceVariance:\n                GetDifferenceVariance(results[Type::DifferenceVariance]);\n                break;\n            case Type::DifferenceEntropy:\n                GetDifferenceEntropy(results[Type::DifferenceEntropy]);\n                break;\n            case Type::InformationMeasuresOfCorrelationI:\n                if (!information_measures_of_correlation_done) {\n                    GetInformationMeasuresOfCorrelation(\n                            results[Type::InformationMeasuresOfCorrelationI],\n                            results[Type::InformationMeasuresOfCorrelationII]);\n                    information_measures_of_correlation_done = true;\n                }\n                break;\n            case Type::InformationMeasuresOfCorrelationII:\n                if (!information_measures_of_correlation_done) {\n                    GetInformationMeasuresOfCorrelation(\n                            results[Type::InformationMeasuresOfCorrelationI],\n                            results[Type::InformationMeasuresOfCorrelationII]);\n                    information_measures_of_correlation_done = true;\n                }\n                break;\n            case Type::InverseDifferenceNormalized:\n                GetInverseDifferenceNormalized(results[Type::InverseDifferenceNormalized]);\n                break;\n            case Type::InverseDifferenceMomentNormalized:\n                GetInverseDifferenceMomentNormalized(results[Type::InverseDifferenceMomentNormalized]);\n                break;\n            default:\n                std::cerr << \"Unknown feature type!\\n\";\n                break;\n        }\n    }\n\n    return results;\n}\n\nvoid TextureAnalysis::CalculateScore(double age, std::map<Type, Features> &features_map) {\n    if ((age > 0) && features_map.count(Type::Mean) && features_map.count(Type::Entropy) &&\n        features_map.count(Type::Contrast)) {\n        std::vector<double> params = {1.138, -1.814, 1.416, 1.714};\n\n        if (age < 60) {\n            age = 0;\n        } else {\n            age = 1;\n        }\n\n        double intensity_H = features_map.at(Type::Mean).H;\n        double intensity_V = features_map.at(Type::Mean).V;\n        double intensity_LD = features_map.at(Type::Mean).LD;\n        double intensity_RD = features_map.at(Type::Mean).RD;\n        double intensity = (intensity_H + intensity_V + intensity_LD + intensity_RD) / 4.0;\n\n        if (intensity < 51.39) {\n            intensity = 0;\n        } else {\n            intensity = 1;\n        }\n\n        double entropy_H = features_map.at(Type::Entropy).H;\n        double entropy_V = features_map.at(Type::Entropy).V;\n        double entropy_LD = features_map.at(Type::Entropy).LD;\n        double entropy_RD = features_map.at(Type::Entropy).RD;\n        double entropy = (entropy_H + entropy_V + entropy_LD + entropy_RD) / 4.0;\n\n        if (entropy < 7.119) {\n            entropy = 0;\n        } else {\n            entropy = 1;\n        }\n\n        double contrast_H = features_map.at(Type::Contrast).H;\n        double contrast_V = features_map.at(Type::Contrast).V;\n        double contrast_LD = features_map.at(Type::Contrast).LD;\n        double contrast_RD = features_map.at(Type::Contrast).RD;\n        double contrast = (contrast_H + contrast_V + contrast_LD + contrast_RD) / 4.0 / 10.0;\n\n        if (contrast < 7.1491) {\n            contrast = 0;\n        } else {\n            contrast = 1;\n        }\n\n        double f_H = params[0] * age + params[1] * intensity + params[2] * entropy +\n                     params[3] * contrast;\n        double f_V = params[0] * age + params[1] * intensity + params[2] * entropy +\n                     params[3] * contrast;\n        double f_LD = params[0] * age + params[1] * intensity + params[2] * entropy +\n                      params[3] * contrast;\n        double f_RD = params[0] * age + params[1] * intensity + params[2] * entropy +\n                      params[3] * contrast;\n\n        features_map[Type::Score](f_H, f_V, f_LD, f_RD);\n        features_map[Type::Age](age, age, age, age);\n    } else {\n        std::cerr << \"Can not calculate the Score!\\n\";\n    }\n}\n\nstd::string TextureAnalysis::TypeToString(const Type &type) {\n    std::string result;\n    switch (type) {\n        case Type::Mean:\n            result = \"Mean\";\n            break;\n        case Type::Std:\n            result = \"STD\";\n            break;\n        case Type::AutoCorrelation:\n            result = \"Auto Correlation\";\n            break;\n        case Type::Contrast:\n            result = \"Contrast\";\n            break;\n        case Type::ContrastAnotherWay:\n            result = \"Contrast (Check)\";\n            break;\n        case Type::CorrelationI:\n            result = \"Correlation I\";\n            break;\n        case Type::CorrelationIAnotherWay:\n            result = \"Correlation I (Check)\";\n            break;\n        case Type::CorrelationII:\n            result = \"Correlation II\";\n            break;\n        case Type::CorrelationIIAnotherWay:\n            result = \"Correlation II (Check)\";\n            break;\n        case Type::CorrelationIII:\n            result = \"Correlation III\";\n            break;\n        case Type::ClusterProminence:\n            result = \"Cluster Prominence\";\n            break;\n        case Type::ClusterShade:\n            result = \"Cluster Shade\";\n            break;\n        case Type::Dissimilarity:\n            result = \"Dissimilarity\";\n            break;\n        case Type::Energy:\n            result = \"Energy\";\n            break;\n        case Type::Entropy:\n            result = \"Entropy\";\n            break;\n        case Type::HomogeneityI:\n            result = \"Homogeneity I\";\n            break;\n        case Type::HomogeneityII:\n            result = \"Homogeneity II (Inverse Difference Moment)\";\n            break;\n        case Type::MaximumProbability:\n            result = \"Maximum Probability\";\n            break;\n        case Type::SumOfSquares:\n            result = \"Sum of Squares (in x and y)\";\n            break;\n        case Type::SumOfSquaresI:\n            result = \"Sum of Squares (in x)\";\n            break;\n        case Type::SumOfSquaresJ:\n            result = \"Sum of Squares (in y)\";\n            break;\n        case Type::SumAverage:\n            result = \"Sum Average\";\n            break;\n        case Type::SumEntropy:\n            result = \"Sum Entropy\";\n            break;\n        case Type::SumVariance:\n            result = \"Sum Variance\";\n            break;\n        case Type::DifferenceVariance:\n            result = \"Difference Variance\";\n            break;\n        case Type::DifferenceEntropy:\n            result = \"Difference Entropy\";\n            break;\n        case Type::InformationMeasuresOfCorrelationI:\n            result = \"Information Measures of Correlation I\";\n            break;\n        case Type::InformationMeasuresOfCorrelationII:\n            result = \"Information Measures of Correlation II\";\n            break;\n        case Type::InverseDifferenceNormalized:\n            result = \"Inverse Difference Normalized\";\n            break;\n        case Type::InverseDifferenceMomentNormalized:\n            result = \"Inverse Difference Moment Normalized\";\n            break;\n        case Type::Score:\n            result = \"Score\";\n            break;\n        case Type::Age:\n            result = \"Age\";\n            break;\n        default:\n            std::cerr << \"Unknown feature type!\\n\";\n            break;\n    }\n    return result;\n}\n\nstd::string TextureAnalysis::DirectionToString(const Direction &direction) {\n    std::string result;\n    switch (direction) {\n        case Direction::H:\n            result = \"H (0 deg)\";\n            break;\n        case Direction::V:\n            result = \"V (90 deg)\";\n            break;\n        case Direction::LD:\n            result = \"LD (135 deg)\";\n            break;\n        case Direction::RD:\n            result = \"RD (45 deg)\";\n            break;\n        case Direction::Avg:\n            result = \"Average\";\n            break;\n        default:\n            std::cerr << \"Unknown feature type!\\n\";\n            break;\n    }\n\n    return result;\n}\n\nvoid TextureAnalysis::Print(const std::map<Type, Features> &features) {\n    for (auto feature : features) {\n        std::cout << TypeToString(feature.first) << std::endl;\n        std::cout << std::setw(30) << DirectionToString(Direction::H) << \" = \" << feature.second.H << std::endl;\n        std::cout << std::setw(30) << DirectionToString(Direction::V) << \" = \" << feature.second.V << std::endl;\n        std::cout << std::setw(30) << DirectionToString(Direction::LD) << \" = \" << feature.second.LD << std::endl;\n        std::cout << std::setw(30) << DirectionToString(Direction::RD) << \" = \" << feature.second.RD << std::endl;\n        std::cout << std::setw(30) << DirectionToString(Direction::Avg) << \" = \" << feature.second.Avg() << std::endl;\n    }\n}\n\nvoid TextureAnalysis::SaveAsCSV(const std::string &image_name, std::map<Type, Features> features,\n                                const std::string &csv_name) {\n    // check whether the csv file exists or not\n    bool csv_file_exists = fs::exists(csv_name);\n\n    // get image file base name\n    std::string image_base_name = fs::path(image_name).filename().string();\n\n    // get current time\n    std::string current_time = GetCurrentTime();\n\n    // open the csv file\n    std::ofstream csv_file;\n    csv_file.open(csv_name,\n                  std::ios::out | std::ios::app); // open as the writing mode and append the csv file at the end\n\n    if (!csv_file) {\n        std::cerr << \"Can't the open file!\" << std::endl;\n        return;\n    }\n\n    if (!csv_file_exists) {\n        // write a row of titles\n        csv_file << \"Date,\";\n        csv_file << \"Image,\";\n        csv_file << \"Direction,\";\n        for (std::map<Type, Features>::iterator it = features.begin(); it != features.end(); ++it) {\n            csv_file << TypeToString(it->first) << \",\";\n        }\n        csv_file << \"\\n\";\n    }\n\n    // write a row of H values\n    csv_file << current_time << \",\";\n    csv_file << image_base_name << \",\";\n    csv_file << DirectionToString(Direction::H) << \",\";\n    for (std::map<Type, Features>::iterator it = features.begin(); it != features.end(); ++it) {\n        csv_file << it->second.H << \",\";\n    }\n    csv_file << \"\\n\";\n\n    // write a row of V values\n    csv_file << current_time << \",\";\n    csv_file << image_base_name << \",\";\n    csv_file << DirectionToString(Direction::V) << \",\";\n    for (std::map<Type, Features>::iterator it = features.begin(); it != features.end(); ++it) {\n        csv_file << it->second.V << \",\";\n    }\n    csv_file << \"\\n\";\n\n    // write a row of LD values\n    csv_file << current_time << \",\";\n    csv_file << image_base_name << \",\";\n    csv_file << DirectionToString(Direction::LD) << \",\";\n    for (std::map<Type, Features>::iterator it = features.begin(); it != features.end(); ++it) {\n        csv_file << it->second.LD << \",\";\n    }\n    csv_file << \"\\n\";\n\n    // write a row of RD values\n    csv_file << current_time << \",\";\n    csv_file << image_base_name << \",\";\n    csv_file << DirectionToString(Direction::RD) << \",\";\n    for (std::map<Type, Features>::iterator it = features.begin(); it != features.end(); ++it) {\n        csv_file << it->second.RD << \",\";\n    }\n    csv_file << \"\\n\";\n\n    // write a row of Avg values\n    csv_file << current_time << \",\";\n    csv_file << image_base_name << \",\";\n    csv_file << DirectionToString(Direction::Avg) << \",\";\n    for (std::map<Type, Features>::iterator it = features.begin(); it != features.end(); ++it) {\n        csv_file << it->second.Avg() << \",\";\n    }\n    csv_file << \"\\n\";\n\n    // close the csv file\n    csv_file.close();\n}\n\nstd::string TextureAnalysis::GetCurrentTime() {\n    time_t rawtime;\n    struct tm *timeinfo;\n    char buffer[80];\n\n    time(&rawtime);\n    timeinfo = localtime(&rawtime);\n\n    strftime(buffer, sizeof(buffer), \"%Y-%m-%d %H:%M:%S\", timeinfo);\n    std::string str(buffer);\n\n    return str;\n}\n\nvoid TextureAnalysis::CalculatePixelMean(const std::vector<double> &vec) {\n    _pixel_values_mean = 0.0;\n    for (int i = 0; i < vec.size(); ++i) {\n        _pixel_values_mean += vec[i];\n    }\n    _pixel_values_mean /= vec.size();\n}\n\nvoid TextureAnalysis::CalculatePixelSTD(const std::vector<double> &vec) {\n    CalculatePixelMean(vec);\n    _pixel_values_STD = 0.0;\n    for (int i = 0; i < vec.size(); ++i) {\n        _pixel_values_STD += (vec[i] - _pixel_values_mean) * (vec[i] - _pixel_values_mean);\n    }\n    _pixel_values_STD = _pixel_values_STD / (vec.size() - 1.0);\n    _pixel_values_STD = sqrt(_pixel_values_STD);\n}\n", "meta": {"hexsha": "c409b7330ff8f520529d6ae4faa6e371d0009f64", "size": 56061, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "analysis/TextureAnalysis.cpp", "max_stars_repo_name": "markccchiang/image-texture-analysis", "max_stars_repo_head_hexsha": "97026e5094be3c5bb0d5b469725dc364caea0775", "max_stars_repo_licenses": ["MIT"], "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/TextureAnalysis.cpp", "max_issues_repo_name": "markccchiang/image-texture-analysis", "max_issues_repo_head_hexsha": "97026e5094be3c5bb0d5b469725dc364caea0775", "max_issues_repo_licenses": ["MIT"], "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/TextureAnalysis.cpp", "max_forks_repo_name": "markccchiang/image-texture-analysis", "max_forks_repo_head_hexsha": "97026e5094be3c5bb0d5b469725dc364caea0775", "max_forks_repo_licenses": ["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.8610785463, "max_line_length": 134, "alphanum_fraction": 0.5107293841, "num_tokens": 17285, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324803738429, "lm_q2_score": 0.5544704649604272, "lm_q1q2_score": 0.45202233244372697}}
{"text": "#include <boost/math/special_functions/bessel.hpp>\n", "meta": {"hexsha": "915c7c42a88f804c929d82152ecadb5fd55cafc2", "size": 51, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_special_functions_bessel.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_special_functions_bessel.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_special_functions_bessel.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 25.5, "max_line_length": 50, "alphanum_fraction": 0.8235294118, "num_tokens": 11, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324713956854, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.45202232746560395}}
{"text": "#include <iostream>\r\n#include <Eigen/Dense>\r\n#include \"DepthCamera.h\"\r\n#include <ctime>\r\n#include \"FilterPipe.h\"\r\n#include \"PointCloud.h\"\r\n#include <cstdlib>\r\n#include \"PointCloudInterface.h\"\r\n#include \"RadiusOutlierFilter.h\"\r\n#include \"PassThroughFilter.h\"\r\n#include \"PointCloudGenerator.h\"\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n\tPointCloudRecorder pcr(\"out.txt\");\r\n\r\n\t// camera1\r\n\tDepthCamera cam1(\"camera1.txt\");\r\n\t\r\n\tFilterPipe *fp1 = new FilterPipe;\r\n\tfp1->addFilter(new RadiusOutlierFilter(25));\r\n\tfp1->addFilter(new PassThroughFilter(400, 0, 400, 0,  45, -45));\r\n\tcam1.setFilterPipe(fp1);\r\n\r\n\tEigen::Vector3d ang1;\r\n\tEigen::Vector3d tr1;\r\n\tang1(0) = 0, ang1(1) = 0, ang1(2) = -90;\r\n\ttr1(0) = 100, tr1(1) = 500, tr1(2) = 50;\r\n\tTransform t1;\r\n\tt1.setRotation(ang1);\r\n\tt1.setTranslation(tr1);\r\n\r\n\r\n\tcam1.setTransformRotation(ang1);\r\n\tcam1.setTransformTranslation(tr1);\r\n\t\r\n\t//camera2\r\n\tDepthCamera cam2(\"camera2.txt\");\r\n\r\n\tFilterPipe *fp2 = new FilterPipe;\r\n\tfp2->addFilter(new RadiusOutlierFilter(25));\r\n\tfp2->addFilter(new PassThroughFilter(500, 0, 500, 0, 45, -45));\r\n\tcam2.setFilterPipe(fp2);\r\n\r\n\tEigen::Vector3d ang2;\r\n\tEigen::Vector3d tr2;\r\n\tang2(0) = 0, ang2(1) = 0, ang2(2) = 90;\r\n\ttr2(0) = 550, tr2(1) = 50, tr2(2) = 50;\r\n\tTransform t2;\r\n\tt2.setRotation(ang2);\r\n\tt2.setTranslation(tr2);\r\n\r\n\tcam2.setTransformRotation(ang2);\r\n\tcam2.setTransformTranslation(tr2);\r\n\r\n\tPointCloudInterface pci;\r\n\tpci.addGenerator(&cam2);\r\n\tpci.addGenerator(&cam1);\r\n\tpci.setRecorder(&pcr);\r\n\tpci.generate();\r\n\tpci.record();\r\n\r\n\t\r\n\r\n\tsystem(\"pause\");\r\n}", "meta": {"hexsha": "ed6f252c89c9f2f8612363655bba0436dc1fd0f2", "size": 1546, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "ismail-klc/point-cloud-processing", "max_stars_repo_head_hexsha": "82d9c371a7c648ea4131e3d565f7274b806edf4d", "max_stars_repo_licenses": ["MIT"], "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": "ismail-klc/point-cloud-processing", "max_issues_repo_head_hexsha": "82d9c371a7c648ea4131e3d565f7274b806edf4d", "max_issues_repo_licenses": ["MIT"], "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": "ismail-klc/point-cloud-processing", "max_forks_repo_head_hexsha": "82d9c371a7c648ea4131e3d565f7274b806edf4d", "max_forks_repo_licenses": ["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.0746268657, "max_line_length": 66, "alphanum_fraction": 0.6772315653, "num_tokens": 491, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.78793120560257, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4520191192122183}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#include \"tests/Unit/TestingFramework.hpp\"\n\n#include <array>\n#include <boost/optional.hpp>\n#include <cstddef>\n#include <string>\n#include <unordered_map>\n\n#include \"ControlSystem/FunctionOfTime.hpp\"\n#include \"ControlSystem/PiecewisePolynomial.hpp\"\n#include \"DataStructures/DataVector.hpp\"\n#include \"DataStructures/Tensor/Tensor.hpp\"\n#include \"Domain/CoordinateMaps/Translation.hpp\"\n#include \"Utilities/ConstantExpressions.hpp\"\n#include \"Utilities/StdArrayHelpers.hpp\"\n#include \"Utilities/TypeTraits.hpp\"\n#include \"tests/Unit/Domain/CoordinateMaps/TestMapHelpers.hpp\"\n#include \"tests/Unit/TestHelpers.hpp\"\n\nSPECTRE_TEST_CASE(\"Unit.Domain.CoordMapsTimeDependent.Translation\",\n                  \"[Domain][Unit]\") {\n  // define vars for FunctionOfTime::PiecewisePolynomial f(t) = t**2.\n  double t = -1.0;\n  const double dt = 0.6;\n  const double final_time = 4.0;\n  constexpr size_t deriv_order = 3;\n\n  const std::array<DataVector, deriv_order + 1> init_func{\n      {{1.0}, {-2.0}, {2.0}, {0.0}}};\n  FunctionsOfTime::PiecewisePolynomial<deriv_order> f_of_t_derived(t,\n                                                                   init_func);\n  FunctionOfTime& f_of_t = f_of_t_derived;\n\n  const std::unordered_map<std::string, FunctionOfTime&> f_of_t_list = {\n      {\"trans\", f_of_t}};\n  const CoordMapsTimeDependent::Translation trans_map{};\n  // test serialized/deserialized map\n  const auto trans_map_deserialized = serialize_and_deserialize(trans_map);\n\n  const std::array<double, 1> point_xi{{3.2}};\n\n  while (t < final_time) {\n    const std::array<double, 1> trans_x{{square(t)}};\n    const std::array<double, 1> frame_vel{{f_of_t.func_and_deriv(t)[1][0]}};\n\n    CHECK_ITERABLE_APPROX(trans_map(point_xi, t, f_of_t_list),\n                          point_xi + trans_x);\n    CHECK_ITERABLE_APPROX(\n        trans_map.inverse(point_xi + trans_x, t, f_of_t_list).get(), point_xi);\n    CHECK_ITERABLE_APPROX(trans_map.frame_velocity(point_xi, t, f_of_t_list),\n                          frame_vel);\n\n    CHECK_ITERABLE_APPROX(trans_map_deserialized(point_xi, t, f_of_t_list),\n                          point_xi + trans_x);\n    CHECK_ITERABLE_APPROX(\n        trans_map_deserialized.inverse(point_xi + trans_x, t, f_of_t_list)\n            .get(),\n        point_xi);\n    CHECK_ITERABLE_APPROX(trans_map_deserialized.frame_velocity(\n                              point_xi + trans_x, t, f_of_t_list),\n                          frame_vel);\n\n    t += dt;\n  }\n\n  // time-independent checks\n  CHECK(trans_map.inv_jacobian(point_xi).get(0, 0) == 1.0);\n  CHECK(trans_map_deserialized.inv_jacobian(point_xi).get(0, 0) == 1.0);\n  CHECK(trans_map.jacobian(point_xi).get(0, 0) == 1.0);\n  CHECK(trans_map_deserialized.jacobian(point_xi).get(0, 0) == 1.0);\n\n  // Check inequivalence operator\n  CHECK_FALSE(trans_map != trans_map);\n  CHECK_FALSE(trans_map_deserialized != trans_map_deserialized);\n\n  // Check serialization\n  CHECK(trans_map == trans_map_deserialized);\n  CHECK_FALSE(trans_map != trans_map_deserialized);\n\n  test_coordinate_map_argument_types(trans_map, point_xi, t, f_of_t_list);\n}\n", "meta": {"hexsha": "1e2c496ee64d9681def38d3dbc1c464eabd2d067", "size": 3149, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/Unit/Domain/CoordinateMaps/Test_Translation.cpp", "max_stars_repo_name": "marissawalker/spectre", "max_stars_repo_head_hexsha": "afc8205e2f697de5e8e4f05e881499e05c9fd8a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/Unit/Domain/CoordinateMaps/Test_Translation.cpp", "max_issues_repo_name": "marissawalker/spectre", "max_issues_repo_head_hexsha": "afc8205e2f697de5e8e4f05e881499e05c9fd8a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/Unit/Domain/CoordinateMaps/Test_Translation.cpp", "max_forks_repo_name": "marissawalker/spectre", "max_forks_repo_head_hexsha": "afc8205e2f697de5e8e4f05e881499e05c9fd8a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.0470588235, "max_line_length": 79, "alphanum_fraction": 0.6916481423, "num_tokens": 816, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.78793120560257, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4520191192122183}}
{"text": "#pragma once\n\n#include <boost/mpl/identity.hpp>\n#include <boost/multiprecision/mpfr.hpp>\n#include <type_traits>\n\n#include <cmath>\n\n// own includes ---------------------------------------------------------\n#include \"traits/type_traits.hpp\"\n\nnamespace math {\n\n// ----------------------------------------------------------------------\n// SQRT\ntemplate <typename T>\ninline constexpr typename std::enable_if<std::is_floating_point<T>::value, T>::type\nsqrt(const T& t)\n{\n  return std::sqrt(t);\n}\n\ntemplate <typename T>\ninline constexpr typename std::enable_if<!std::is_floating_point<T>::value, T>::type\nsqrt(const T& t)\n{\n  return boost::multiprecision::sqrt(t);\n}\n\n// ----------------------------------------------------------------------\n// EXP\ntemplate <typename T>\ninline constexpr typename std::enable_if<std::is_floating_point<T>::value, T>::type\nexp(const T& t)\n{\n  return std::exp(t);\n}\n\ntemplate <typename T>\ninline constexpr typename std::enable_if<!std::is_floating_point<T>::value, T>::type\nexp(const T& t)\n{\n  return boost::multiprecision::exp(t);\n}\n\n// ----------------------------------------------------------------------\n// LOG\ntemplate <typename T>\ninline constexpr typename std::enable_if<std::is_floating_point<T>::value, T>::type\nlog(const T& t)\n{\n  return std::log(t);\n}\n\ntemplate <typename T>\ninline constexpr typename std::enable_if<!std::is_floating_point<T>::value, T>::type\nlog(const T& t)\n{\n  return boost::multiprecision::log(t);\n}\n\n// ----------------------------------------------------------------------\n// POW\ntemplate <typename T>\ninline constexpr typename std::enable_if<std::is_floating_point<T>::value, T>::type\npow(const T& base, const typename boost::mpl::identity<T>::type& exp)\n{\n  return std::pow(base, exp);\n}\n\ntemplate <typename T>\ninline constexpr typename std::enable_if<!std::is_floating_point<T>::value, T>::type\npow(const T& base, const typename boost::mpl::identity<T>::type& exp)\n{\n  return boost::multiprecision::pow(base, exp);\n}\n\n// ----------------------------------------------------------------------\n// ABS\ntemplate <typename T>\ninline constexpr typename std::enable_if<std::is_floating_point<T>::value, T>::type\nabs(const T& t)\n{\n  return std::abs(t);\n}\n\ntemplate <typename T>\ninline constexpr typename std::enable_if<!std::is_floating_point<T>::value, T>::type\nabs(const T& t)\n{\n  return boost::multiprecision::abs(t);\n}\n\n}  // end namespace math\n", "meta": {"hexsha": "f68f22dd9b3b5e0fcb14b89dd16c06c2649ec006", "size": 2402, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/mpfr/import_std_math.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/mpfr/import_std_math.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/mpfr/import_std_math.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": 25.2842105263, "max_line_length": 84, "alphanum_fraction": 0.5903413822, "num_tokens": 539, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.45201911349856766}}
{"text": "// $Id$\n//\n// Copyright (C)  2004-2006 Rational Discovery LLC\n//\n//   @@ All Rights Reserved @@\n//  This file is part of the RDKit.\n//  The contents are covered by the terms of the BSD license\n//  which is included in the file license.txt, found at the root\n//  of the RDKit source tree.\n//\n\n#include \"BoundsMatrix.h\"\n#include \"TriangleSmooth.h\"\n#include <iostream>\n#include <boost/smart_ptr.hpp>\n#include <math.h>\n#include <Numerics/SymmMatrix.h>\n#include \"DistGeomUtils.h\"\n#include <RDGeneral/utils.h>\n\nusing namespace DistGeom;\nusing namespace RDNumeric;\n\nvoid test1() {\n  // test triangle smoothing\n  unsigned int npt = 5;\n  double x = sqrt(3.0);\n  BoundsMatrix *mmat = new BoundsMatrix(npt);\n\n  mmat->setUpperBound(0, 1, 1.0);\n  mmat->setLowerBound(0, 1, 1.0);\n  mmat->setUpperBound(0, 2, x);\n  mmat->setLowerBound(0, 2, x);\n  mmat->setUpperBound(0, 3, 10.0);\n  mmat->setLowerBound(0, 3, 0.0);\n  mmat->setUpperBound(0, 4, 10.0);\n  mmat->setLowerBound(0, 4, 0.0);\n  mmat->setUpperBound(1, 2, 1.0);\n  mmat->setLowerBound(1, 2, 1.0);\n  mmat->setUpperBound(1, 3, x);\n  mmat->setLowerBound(1, 3, x);\n  mmat->setUpperBound(1, 4, 10.0);\n  mmat->setLowerBound(1, 4, 0.0);\n  mmat->setUpperBound(2, 3, 1.0);\n  mmat->setLowerBound(2, 3, 1.0);\n  mmat->setUpperBound(2, 4, x);\n  mmat->setLowerBound(2, 4, x);\n  mmat->setUpperBound(3, 4, 1.0);\n  mmat->setLowerBound(3, 4, 1.0);\n\n  BoundsMatPtr mptr(mmat);\n\n  triangleSmoothBounds(mptr);\n  CHECK_INVARIANT(RDKit::feq(mmat->getUpperBound(0, 1), 1.0, 0.001), \"\");\n  CHECK_INVARIANT(RDKit::feq(mmat->getLowerBound(0, 1), 1.0, 0.001), \"\");\n  CHECK_INVARIANT(RDKit::feq(mmat->getUpperBound(0, 2), 1.732, 0.001), \"\");\n  CHECK_INVARIANT(RDKit::feq(mmat->getLowerBound(0, 2), 1.732, 0.001), \"\");\n  CHECK_INVARIANT(RDKit::feq(mmat->getUpperBound(0, 3), 2.732, 0.001), \"\");\n  CHECK_INVARIANT(RDKit::feq(mmat->getLowerBound(0, 3), 0.732, 0.001), \"\");\n  CHECK_INVARIANT(RDKit::feq(mmat->getUpperBound(0, 4), 3.464, 0.001), \"\");\n  CHECK_INVARIANT(RDKit::feq(mmat->getLowerBound(0, 4), 0.0, 0.001), \"\");\n  CHECK_INVARIANT(RDKit::feq(mmat->getUpperBound(1, 2), 1.0, 0.001), \"\");\n  CHECK_INVARIANT(RDKit::feq(mmat->getLowerBound(1, 2), 1.0, 0.001), \"\");\n  CHECK_INVARIANT(RDKit::feq(mmat->getUpperBound(1, 3), 1.732, 0.001), \"\");\n  CHECK_INVARIANT(RDKit::feq(mmat->getLowerBound(1, 3), 1.732, 0.001), \"\");\n  CHECK_INVARIANT(RDKit::feq(mmat->getUpperBound(1, 4), 2.732, 0.001), \"\");\n  CHECK_INVARIANT(RDKit::feq(mmat->getLowerBound(1, 4), 0.732, 0.001), \"\");\n  CHECK_INVARIANT(RDKit::feq(mmat->getUpperBound(2, 3), 1.0, 0.001), \"\");\n  CHECK_INVARIANT(RDKit::feq(mmat->getLowerBound(2, 3), 1.0, 0.001), \"\");\n  CHECK_INVARIANT(RDKit::feq(mmat->getUpperBound(2, 4), 1.732, 0.001), \"\");\n  CHECK_INVARIANT(RDKit::feq(mmat->getLowerBound(2, 4), 1.732, 0.001), \"\");\n  CHECK_INVARIANT(RDKit::feq(mmat->getUpperBound(3, 4), 1.0, 0.001), \"\");\n  CHECK_INVARIANT(RDKit::feq(mmat->getLowerBound(3, 4), 1.0, 0.001), \"\");\n\n  DoubleSymmMatrix dmat(npt, 0.0);\n  RDKit::rng_type generator(42u);\n  generator.seed(100);\n  RDKit::uniform_double distrib(0, 1.0);\n  RDKit::double_source_type rng(generator, distrib);\n  pickRandomDistMat(*mmat, dmat, rng);\n\n  double sumElem = 0.0;\n  for (unsigned int i = 0; i < dmat.getDataSize(); i++) {\n    sumElem += dmat.getData()[i];\n  }\n  CHECK_INVARIANT(RDKit::feq(sumElem, 14.3079, 0.001), \"\");\n}\n\nvoid testIssue216() {\n  RDNumeric::DoubleSymmMatrix dmat(4);\n  dmat.setVal(0, 0, 0.0);\n  dmat.setVal(0, 1, 1.0);\n  dmat.setVal(0, 2, 1.0);\n  dmat.setVal(0, 3, 1.0);\n  dmat.setVal(1, 1, 0.0);\n  dmat.setVal(1, 2, 1.0);\n  dmat.setVal(1, 3, 1.0);\n  dmat.setVal(2, 2, 0.0);\n  dmat.setVal(2, 3, 1.0);\n  dmat.setVal(3, 3, 0.0);\n\n  std::cout << dmat;\n  RDGeom::PointPtrVect pos;\n  for (int i = 0; i < 4; i++) {\n    RDGeom::Point3D *pt = new RDGeom::Point3D();\n    pos.push_back(pt);\n  }\n\n  bool gotCoords = DistGeom::computeInitialCoords(dmat, pos);\n  CHECK_INVARIANT(gotCoords, \"\");\n\n  for (int i = 1; i < 4; i++) {\n    RDGeom::Point3D pti = *(RDGeom::Point3D *)pos[i];\n    for (int j = 0; j < i; j++) {\n      RDGeom::Point3D ptj = *(RDGeom::Point3D *)pos[j];\n      ptj -= pti;\n      CHECK_INVARIANT(RDKit::feq(ptj.length(), 1.0, 0.02), \"\");\n    }\n  }\n}\nint main() {\n  std::cout << \"***********************************************************\\n\";\n  std::cout << \"   test1 \\n\";\n  test1();\n\n  std::cout << \"***********************************************************\\n\";\n  std::cout << \"   testIssue216 \\n\";\n  testIssue216();\n  std::cout\n      << \"***********************************************************\\n\\n\";\n  return 0;\n}\n", "meta": {"hexsha": "1e924189024db29ddcb742a76dd792a37de46f54", "size": 4559, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Code/DistGeom/testDistGeom.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/DistGeom/testDistGeom.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/DistGeom/testDistGeom.cpp", "max_forks_repo_name": "docking-org/rdk", "max_forks_repo_head_hexsha": "6eb710254f027b348a8e3089e6a92c3d40de0949", "max_forks_repo_licenses": ["PostgreSQL"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-12-04T02:28:18.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-29T01:18:46.000Z", "avg_line_length": 34.2781954887, "max_line_length": 79, "alphanum_fraction": 0.6086861154, "num_tokens": 1802, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.45201911349856766}}
{"text": "/*-----------------------------------------------------------------------------+\nInterval Container Library\nAuthor: Joachim Faulhaber\nCopyright (c) 2007-2009: Joachim Faulhaber\nCopyright (c) 1999-2006: Cortex Software GmbH, Kantstrasse 57, Berlin\n+------------------------------------------------------------------------------+\n   Distributed under the Boost Software License, Version 1.0.\n      (See accompanying file LICENCE.txt or copy at\n           http://www.boost.org/LICENSE_1_0.txt)\n+-----------------------------------------------------------------------------*/\n\n/** Example partys_tallest_guests.cpp \\file partys_tallest_guests.cpp\n    \\brief Using <i>aggregate on overlap</i> the heights of the party's tallest\n           guests are computed.\n\n    In partys_tallest_guests.cpp we use a different instantiation of\n    interval map templates to compute maxima of guest heights.\n\n    Instead of aggregating groups of people attending the party in time\n    we aggregate the maximum of guest height for the time intervals.\n\n    Using a joining interval_map results in a smaller map: All interval\n    value pairs are joined if the maximum does not change in time. Using\n    a split_interval_map results in a larger map: All splits of intervals\n    that occur due to entering and leaving of guests are preserved in\n    the split_interval_map.\n\n    \\include partys_tallest_guests_/partys_tallest_guests.cpp\n*/\n//[example_partys_tallest_guests\n// The next line includes <boost/date_time/posix_time/posix_time.hpp>\n// and a few lines of adapter code.\n#include <boost/icl/ptime.hpp>\n#include <iostream>\n#include <boost/icl/interval_map.hpp>\n#include <boost/icl/split_interval_map.hpp>\n\nusing namespace std;\nusing namespace boost::posix_time;\nusing namespace boost::icl;\n\n\n// A party's height shall be defined as the maximum height of all guests ;-)\n// The last parameter 'inplace_max' is a functor template that calls a max\n// aggregation on overlap.\ntypedef interval_map<ptime, int, partial_absorber, less, inplace_max>\n    PartyHeightHistoryT;\n\n// Using a split_interval_map we preserve interval splittings that occurred via insertion.\ntypedef split_interval_map<ptime, int, partial_absorber, less, inplace_max>\n    PartyHeightSplitHistoryT;\n\nvoid partys_height()\n{\n    PartyHeightHistoryT tallest_guest;\n\n    tallest_guest +=\n      make_pair(\n        discrete_interval<ptime>::right_open(\n          time_from_string(\"2008-05-20 19:30\"),\n          time_from_string(\"2008-05-20 23:00\")),\n        180); // Mary & Harry: Harry is 1,80 m tall.\n\n    tallest_guest +=\n      make_pair(\n        discrete_interval<ptime>::right_open(\n          time_from_string(\"2008-05-20 20:10\"),\n          time_from_string(\"2008-05-21 00:00\")),\n        170); // Diana & Susan: Diana is 1,70 m tall.\n\n    tallest_guest +=\n      make_pair(\n        discrete_interval<ptime>::right_open(\n          time_from_string(\"2008-05-20 22:15\"),\n          time_from_string(\"2008-05-21 00:30\")),\n        200); // Peters height is 2,00 m\n\n    PartyHeightHistoryT::iterator height_ = tallest_guest.begin();\n    cout << \"-------------- History of maximum guest height -------------------\\n\";\n    while(height_ != tallest_guest.end())\n    {\n        discrete_interval<ptime> when = height_->first;\n        // Of what height are the tallest guests within the time interval 'when' ?\n        int height = (*height_++).second;\n        cout << \"[\" << first(when) << \" - \" << upper(when) << \")\"\n             << \": \" << height <<\" cm = \" << height/30.48 << \" ft\" << endl;\n    }\n\n}\n\n// Next we are using a split_interval_map instead of a joining interval_map\nvoid partys_split_height()\n{\n    PartyHeightSplitHistoryT tallest_guest;\n\n    // adding an element can be done wrt. simple aggregate functions\n    // like e.g. min, max etc. in their 'inplace' or op= incarnation\n    tallest_guest +=\n      make_pair(\n        discrete_interval<ptime>::right_open(\n          time_from_string(\"2008-05-20 19:30\"),\n          time_from_string(\"2008-05-20 23:00\")),\n        180); // Mary & Harry: Harry is 1,80 m tall.\n\n    tallest_guest +=\n      make_pair(\n        discrete_interval<ptime>::right_open(\n          time_from_string(\"2008-05-20 20:10\"),\n          time_from_string(\"2008-05-21 00:00\")),\n        170); // Diana & Susan: Diana is 1,70 m tall.\n\n    tallest_guest +=\n      make_pair(\n        discrete_interval<ptime>::right_open(\n          time_from_string(\"2008-05-20 22:15\"),\n          time_from_string(\"2008-05-21 00:30\")),\n        200); // Peters height is 2,00 m\n\n    PartyHeightSplitHistoryT::iterator height_ = tallest_guest.begin();\n    cout << \"\\n\";\n    cout << \"-------- Split History of maximum guest height -------------------\\n\";\n    cout << \"--- Same map as above but split for every interval insertion.  ---\\n\";\n    while(height_ != tallest_guest.end())\n    {\n        discrete_interval<ptime> when = height_->first;\n        // Of what height are the tallest guests within the time interval 'when' ?\n        int height = (*height_++).second;\n        cout << \"[\" << first(when) << \" - \" << upper(when) << \")\"\n             << \": \" << height <<\" cm = \" << height/30.48 << \" ft\" << endl;\n    }\n\n}\n\n\nint main()\n{\n    cout << \">>Interval Container Library: Sample partys_tallest_guests.cpp  <<\\n\";\n    cout << \"------------------------------------------------------------------\\n\";\n    partys_height();\n    partys_split_height();\n    return 0;\n}\n\n// Program output:\n/*-----------------------------------------------------------------------------\n>>Interval Container Library: Sample partys_tallest_guests.cpp  <<\n------------------------------------------------------------------\n-------------- History of maximum guest height -------------------\n[2008-May-20 19:30:00 - 2008-May-20 22:15:00): 180 cm = 5.90551 ft\n[2008-May-20 22:15:00 - 2008-May-21 00:30:00): 200 cm = 6.56168 ft\n\n-------- Split History of maximum guest height -------------------\n--- Same map as above but split for every interval insertion.  ---\n[2008-May-20 19:30:00 - 2008-May-20 20:10:00): 180 cm = 5.90551 ft\n[2008-May-20 20:10:00 - 2008-May-20 22:15:00): 180 cm = 5.90551 ft\n[2008-May-20 22:15:00 - 2008-May-20 23:00:00): 200 cm = 6.56168 ft\n[2008-May-20 23:00:00 - 2008-May-21 00:00:00): 200 cm = 6.56168 ft\n[2008-May-21 00:00:00 - 2008-May-21 00:30:00): 200 cm = 6.56168 ft\n-----------------------------------------------------------------------------*/\n//]\n", "meta": {"hexsha": "3b9589c880b43ba6e6a8cbae5cc7977b2adfce12", "size": 6391, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/libs/icl/example/partys_tallest_guests_/partys_tallest_guests.cpp", "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/libs/icl/example/partys_tallest_guests_/partys_tallest_guests.cpp", "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/libs/icl/example/partys_tallest_guests_/partys_tallest_guests.cpp", "max_forks_repo_name": "Bpowers4/turicreate", "max_forks_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 39.6956521739, "max_line_length": 90, "alphanum_fraction": 0.5991237678, "num_tokens": 1609, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802735722128, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.4520056112000378}}
{"text": "#ifndef MATHEVAL_IMPLEMENTATION\n#error \"Do not include ast.hpp directly!\"\n#endif\n\n#pragma once\n\n#include <boost/spirit/home/x3.hpp>\n#include <boost/spirit/home/x3/support/ast/variant.hpp>\n\n#include <list>\n#include <string>\n\nnamespace matheval {\n\nnamespace x3 = boost::spirit::x3;\n\nnamespace ast {\n\nstruct nil {};\nstruct unary_op;\nstruct binary_op;\nstruct ternary_op;\nstruct expression;\n\n// clang-format off\nstruct operand : x3::variant<\n                 nil\n                 , double\n                 , std::string\n                 , x3::forward_ast<unary_op>\n                 , x3::forward_ast<binary_op>\n                 , x3::forward_ast<ternary_op>\n                 , x3::forward_ast<expression>\n                 > {\n    using base_type::base_type;\n    using base_type::operator=;\n};\n// clang-format on\n\nstruct unary_op {\n    double (*op)(double);\n    operand rhs;\n};\n\nstruct binary_op {\n    double (*op)(double, double);\n    operand lhs;\n    operand rhs;\n};\n\nstruct ternary_op {\n    double (*op)(double, double, double);\n    operand p1;\n    operand p2;\n    operand p3;\n};\n\nstruct operation {\n    double (*op)(double, double);\n    operand rhs;\n};\n\nstruct expression {\n    operand lhs;\n    std::list<operation> rhs;\n};\n\n} // namespace ast\n\n} // namespace matheval\n", "meta": {"hexsha": "2b408f308f3ee3cfd317c8e46e3b69842bdb5377", "size": 1267, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/x3/ast.hpp", "max_stars_repo_name": "doj/boost_matheval", "max_stars_repo_head_hexsha": "61c6b3cb450127612e4f531ded37f3dca54a1419", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/x3/ast.hpp", "max_issues_repo_name": "doj/boost_matheval", "max_issues_repo_head_hexsha": "61c6b3cb450127612e4f531ded37f3dca54a1419", "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/x3/ast.hpp", "max_forks_repo_name": "doj/boost_matheval", "max_forks_repo_head_hexsha": "61c6b3cb450127612e4f531ded37f3dca54a1419", "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": 17.8450704225, "max_line_length": 55, "alphanum_fraction": 0.6116811365, "num_tokens": 304, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802735722128, "lm_q2_score": 0.6757645944891558, "lm_q1q2_score": 0.452005606832322}}
{"text": "#include <opencv2/highgui/highgui.hpp>\n#include \"opencv2/imgproc/imgproc.hpp\"\n#include <Eigen/Dense>\n#include <Eigen/Core>     // to use Eigen::Map\n#include \"contourDetection.h\"\n\nusing namespace cv;\nusing namespace std;\n\nMat imageSegmentation(const cv::Mat& color_image, SegmentationType type, ImageROI roi, int theshold) {\n\tRect2i ROI{roi.x_min, roi.y_min, roi.x_max - roi.x_min, roi.y_max - roi.y_min};            // create a rectangle for selecting ROI (x_min, y_min, x_max-x_min, y_max-y_min)\n\tMat imageROI = color_image(ROI);\n\tMat binary_image;                            // Binary image\n\tswitch(type) {\n\tcase SegmentationType::Black:\n\t{\n\t\tMat imageGray;                              // Gray scale image\n\t\tcv::cvtColor(imageROI, imageGray, CV_BGR2GRAY);\n\t\tconst int maxValue = 255;                         // Maximum value\n\t\tcv::threshold(imageGray, binary_image, theshold, maxValue, THRESH_BINARY);      // Binary image\n\t}\n\tbreak;\n\tcase SegmentationType::Red:\n\t{\n\t\tcv::Mat hsv_img;\n\t\tcv::cvtColor(imageROI, hsv_img, cv::COLOR_BGR2HSV);\n\n\t\t// Threshold the HSV image, keep only the red pixels\n\t\tcv::Mat mask1;\n\t\tcv::Mat mask2;\n\t\tcv::inRange(hsv_img, cv::Scalar(0, 100, 100), cv::Scalar(theshold, 255, 255), mask1);\n\t\tcv::inRange(hsv_img, cv::Scalar(179-theshold, 100, 100), cv::Scalar(179, 255, 255), mask2);\n\t\tcv::Mat detectRed = mask1 | mask2;        // With this red will be white and rest will be black\n\t\t// Reverse black and white to fit with the active contour alg.\n\t\tcv::bitwise_not(detectRed, binary_image);\n\t}\n\tbreak;\n\t}\n\n\tMat filtered_image;\n\tcv::erode(binary_image, filtered_image, Mat());\n\tcv::dilate(binary_image, filtered_image, Mat());\n\n\treturn filtered_image;\n}\n\nMat ContourToYXdata(const Mat &contours, int rowMax)   // function to transfer the contour data into XY coordinate data for optimization purposes\n{\n  // contours: Contour data\n  // rowMax: number of row of the image\n\t// See matlab function imgdata2plotdata\n  Mat XYdataReturn;\n  contours.col(1) = rowMax - contours.col(1) - 1;\n\t// contours.col(1) = contours.col(1) + 1;  // For obtain MATLAB liked data\n  return contours;\n}\n\nMat ContourDetect(Mat &image, SegmentationType type, ImageROI roi, int canny_thresh)\n{\n\tMat segmentedImage = imageSegmentation(image, type, roi);\n  int segmentedImageRow = segmentedImage.rows;\n\tvector<Vec4i> hierarchy;\n\tMat canny_output;\n\tvector<vector<Point> > contours;\n  Canny( segmentedImage, canny_output, canny_thresh, canny_thresh*2, 3 );\n  findContours( canny_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0) );\n  // waitKey(0);\n  Mat contourData(contours[0][0]);  // create a mat to store the contour\n  int index = 0;\n  std::cout << \"contour size \" << contours.size() << '\\n';\n  // Find the contour with most points(it must be the right contour)\n  for(int i= 0; i < contours.size(); i++)\n  {\n    if (contours[index].size() < contours[i].size())\n    {\n      index = i;\n    }\n  }\n  // Save all the contour data\n  for(int j= 0; j < contours[index].size();j++) // run until j < contours[i].size();\n  {\n    Mat temp(contours[index][j]);\n    hconcat(contourData, temp, contourData); //do whatever\n  }\n  Mat contourDataT;\n  transpose(contourData, contourDataT);\n  contourDataT(Range(1, contourDataT.rows), Range(0,contourDataT.cols)).copyTo(contourDataT);\n  Mat XYdata = ContourToYXdata(contourDataT, segmentedImageRow);\n\treturn XYdata;\n}\n", "meta": {"hexsha": "ab4ac56707f3574ded61c3f2aa3bed40fa6dbcc5", "size": 3380, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/alg.cpp", "max_stars_repo_name": "Jihong-Zhu/dloContour", "max_stars_repo_head_hexsha": "3ef1a127e53a4e564b6b512b1df14278e9bcd641", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/alg.cpp", "max_issues_repo_name": "Jihong-Zhu/dloContour", "max_issues_repo_head_hexsha": "3ef1a127e53a4e564b6b512b1df14278e9bcd641", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/alg.cpp", "max_forks_repo_name": "Jihong-Zhu/dloContour", "max_forks_repo_head_hexsha": "3ef1a127e53a4e564b6b512b1df14278e9bcd641", "max_forks_repo_licenses": ["Apache-2.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.1428571429, "max_line_length": 172, "alphanum_fraction": 0.6893491124, "num_tokens": 954, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802471698041, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.4520055977259401}}
{"text": "// Boost.Geometry Index\n//\n// Quickbook Examples\n//\n// Copyright (c) 2011-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//[rtree_quickstart\n\n//[rtree_quickstart_include\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point.hpp>\n#include <boost/geometry/geometries/box.hpp>\n\n#include <boost/geometry/index/rtree.hpp>\n\n// to store queries results\n#include <vector>\n\n// just for output\n#include <iostream>\n#include <boost/foreach.hpp>\n\nnamespace bg = boost::geometry;\nnamespace bgi = boost::geometry::index;\n//]\n\nint main(void)\n{\n    //[rtree_quickstart_valuetype\n    typedef bg::model::point<float, 2, bg::cs::cartesian> point;\n    typedef bg::model::box<point> box;\n    typedef std::pair<box, unsigned> value;\n    //]\n\n    //[rtree_quickstart_create\n    // create the rtree using default constructor\n    bgi::rtree< value, bgi::quadratic<16> > rtree;\n    //]\n\n    //[rtree_quickstart_insert\n    // create some values\n    for ( unsigned i = 0 ; i < 10 ; ++i )\n    {\n        // create a box\n        box b(point(i, i), point(i + 0.5f, i + 0.5f));\n        // insert new value\n        rtree.insert(std::make_pair(b, i));\n    }\n    //]\n    \n    //[rtree_quickstart_spatial_query\n    // find values intersecting some area defined by a box\n    box query_box(point(0, 0), point(5, 5));\n    std::vector<value> result_s;\n    rtree.query(bgi::intersects(query_box), std::back_inserter(result_s));\n    //]\n\n    //[rtree_quickstart_nearest_query\n    // find 5 nearest values to a point\n    std::vector<value> result_n;\n    rtree.query(bgi::nearest(point(0, 0), 5), std::back_inserter(result_n));\n    //]\n\n    //[rtree_quickstart_output\n    // display results\n    std::cout << \"spatial query box:\" << std::endl;\n    std::cout << bg::wkt<box>(query_box) << std::endl;\n    std::cout << \"spatial query result:\" << std::endl;\n    BOOST_FOREACH(value const& v, result_s)\n        std::cout << bg::wkt<box>(v.first) << \" - \" << v.second << std::endl;\n\n    std::cout << \"knn query point:\" << std::endl;\n    std::cout << bg::wkt<point>(point(0, 0)) << std::endl;\n    std::cout << \"knn query result:\" << std::endl;\n    BOOST_FOREACH(value const& v, result_n)\n        std::cout << bg::wkt<box>(v.first) << \" - \" << v.second << std::endl;\n    //]\n\n    return 0;\n}\n\n//]\n", "meta": {"hexsha": "80c88312275b84d0c3395231192717ce2a7a7cad", "size": 2441, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/doc/index/src/examples/rtree/quick_start.cpp", "max_stars_repo_name": "ballisticwhisper/boost", "max_stars_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2015-03-03T15:45:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-25T03:37:17.000Z", "max_issues_repo_path": "libs/geometry/doc/index/src/examples/rtree/quick_start.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/doc/index/src/examples/rtree/quick_start.cpp", "max_forks_repo_name": "ballisticwhisper/boost", "max_forks_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-04-17T15:37:11.000Z", "max_forks_repo_forks_event_max_datetime": "2018-06-10T14:06:31.000Z", "avg_line_length": 27.7386363636, "max_line_length": 79, "alphanum_fraction": 0.6337566571, "num_tokens": 717, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.6757645879592641, "lm_q1q2_score": 0.4520055935436999}}
{"text": "// Copyright (C) 2010  Davis E. King (davis@dlib.net)\n// License: Boost Software License   See LICENSE.txt for the full license.\n\n#include \"tester.h\"\n#include <dlib/manifold_regularization.h>\n#include <dlib/svm.h>\n#include <dlib/rand.h>\n#include <dlib/string.h>\n#include <dlib/graph_utils_threaded.h>\n#include <vector>\n#include <sstream>\n#include <ctime>\n\nnamespace  \n{\n    using namespace test;\n    using namespace dlib;\n    using namespace std;\n    dlib::logger dlog(\"test.linear_manifold_regularizer\");\n\n    template <typename hash_type, typename samples_type>\n    void test_find_k_nearest_neighbors_lsh(\n        const samples_type& samples\n    )\n    {\n        std::vector<sample_pair> edges1, edges2;\n\n        find_k_nearest_neighbors(samples, cosine_distance(), 2, edges1);\n        find_k_nearest_neighbors_lsh(samples, cosine_distance(), hash_type(), 2, 6, edges2, 2);\n\n        std::sort(edges1.begin(), edges1.end(), order_by_index<sample_pair>);\n        std::sort(edges2.begin(), edges2.end(), order_by_index<sample_pair>);\n\n        DLIB_TEST_MSG(edges1.size() == edges2.size(), edges1.size() << \"    \" << edges2.size());\n        for (unsigned long i = 0; i < edges1.size(); ++i)\n        {\n            DLIB_TEST(edges1[i] == edges2[i]);\n            DLIB_TEST_MSG(std::abs(edges1[i].distance() - edges2[i].distance()) < 1e-7,\n                edges1[i].distance() - edges2[i].distance());\n        }\n    }\n\n    template <typename scalar_type>\n    void test_knn_lsh_sparse()\n    {\n        dlib::rand rnd;\n        std::vector<std::map<unsigned long,scalar_type> > samples;\n        samples.resize(20);\n        for (unsigned int i = 0; i < samples.size(); ++i)\n        {\n            samples[i][0] = rnd.get_random_gaussian();\n            samples[i][2] = rnd.get_random_gaussian();\n        }\n\n        test_find_k_nearest_neighbors_lsh<hash_similar_angles_64>(samples);\n        test_find_k_nearest_neighbors_lsh<hash_similar_angles_128>(samples);\n        test_find_k_nearest_neighbors_lsh<hash_similar_angles_256>(samples);\n        test_find_k_nearest_neighbors_lsh<hash_similar_angles_512>(samples);\n    }\n\n    template <typename scalar_type>\n    void test_knn_lsh_dense()\n    {\n        dlib::rand rnd;\n        std::vector<matrix<scalar_type,0,1> > samples;\n        samples.resize(20);\n        for (unsigned int i = 0; i < samples.size(); ++i)\n        {\n            samples[i].set_size(2);\n            samples[i](0) = rnd.get_random_gaussian();\n            samples[i](1) = rnd.get_random_gaussian();\n        }\n\n        test_find_k_nearest_neighbors_lsh<hash_similar_angles_64>(samples);\n        test_find_k_nearest_neighbors_lsh<hash_similar_angles_128>(samples);\n        test_find_k_nearest_neighbors_lsh<hash_similar_angles_256>(samples);\n        test_find_k_nearest_neighbors_lsh<hash_similar_angles_512>(samples);\n    }\n\n\n\n    class linear_manifold_regularizer_tester : public tester\n    {\n        /*!\n            WHAT THIS OBJECT REPRESENTS\n                This object represents a unit test.  When it is constructed\n                it adds itself into the testing framework.\n        !*/\n    public:\n        linear_manifold_regularizer_tester (\n        ) :\n            tester (\n                \"test_linear_manifold_regularizer\",       // the command line argument name for this test\n                \"Run tests on the linear_manifold_regularizer object.\", // the command line argument description\n                0                     // the number of command line arguments for this test\n            )\n        {\n            seed = 1;\n        }\n\n        dlib::rand rnd;\n\n        unsigned long seed;\n\n        typedef matrix<double, 0, 1> sample_type;\n        typedef radial_basis_kernel<sample_type> kernel_type;\n\n        void do_the_test()\n        {\n            print_spinner();\n            std::vector<sample_type> samples;\n\n            // Declare an instance of the kernel we will be using.  \n            const kernel_type kern(0.1);\n\n            const unsigned long num_points = 200;\n\n            // create a large dataset with two concentric circles.  \n            generate_circle(samples, 1, num_points);  // circle of radius 1\n            generate_circle(samples, 5, num_points);  // circle of radius 5\n\n            std::vector<sample_pair> edges;\n            find_percent_shortest_edges_randomly(samples, squared_euclidean_distance(0.1, 4), 1, 10000, \"random seed\", edges);\n\n            dlog << LTRACE << \"number of edges generated: \" << edges.size();\n\n            empirical_kernel_map<kernel_type> ekm;\n\n            ekm.load(kern, randomly_subsample(samples, 100));\n\n            // Project all the samples into the span of our 50 basis samples\n            for (unsigned long i = 0; i < samples.size(); ++i)\n                samples[i] = ekm.project(samples[i]);\n\n\n            // Now create the manifold regularizer.   The result is a transformation matrix that\n            // embodies the manifold assumption discussed above. \n            linear_manifold_regularizer<sample_type> lmr;\n            lmr.build(samples, edges, use_gaussian_weights(0.1));\n            matrix<double> T = lmr.get_transformation_matrix(10000);\n\n            print_spinner();\n\n            // generate the T matrix manually and make sure it matches.  The point of this test\n            // is to make sure that the more complex version of this that happens inside the linear_manifold_regularizer\n            // is correct.  It uses a tedious block of loops to do it in a way that is a lot faster for sparse\n            // W matrices but isn't super straight forward.  \n            matrix<double> X(samples[0].size(), samples.size());\n            for (unsigned long i = 0; i < samples.size(); ++i)\n                set_colm(X,i) = samples[i];\n\n            matrix<double> W(samples.size(), samples.size());\n            W = 0;\n            for (unsigned long i = 0; i < edges.size(); ++i)\n            {\n                W(edges[i].index1(), edges[i].index2()) = use_gaussian_weights(0.1)(edges[i]);\n                W(edges[i].index2(), edges[i].index1()) = use_gaussian_weights(0.1)(edges[i]);\n            }\n            matrix<double> L = diagm(sum_rows(W)) - W;\n            matrix<double> trueT = inv_lower_triangular(chol(identity_matrix<double>(X.nr()) + (10000.0/sum(lowerm(W)))*X*L*trans(X)));\n\n            dlog << LTRACE << \"T error: \"<< max(abs(T - trueT));\n            DLIB_TEST(max(abs(T - trueT)) < 1e-7);\n\n\n            print_spinner();\n            // Apply the transformation generated by the linear_manifold_regularizer to \n            // all our samples.\n            for (unsigned long i = 0; i < samples.size(); ++i)\n                samples[i] = T*samples[i];\n\n\n            // For convenience, generate a projection_function and merge the transformation\n            // matrix T into it.  \n            projection_function<kernel_type> proj = ekm.get_projection_function();\n            proj.weights = T*proj.weights;\n\n\n            // Pick 2 different labeled points.  One on the inner circle and another on the outer.  \n            // For each of these test points we will see if using the single plane that separates\n            // them is a good way to separate the concentric circles.  Also do this a bunch \n            // of times with different randomly chosen points so we can see how robust the result is.\n            for (int itr = 0; itr < 10; ++itr)\n            {\n                print_spinner();\n                std::vector<sample_type> test_points;\n                // generate a random point from the radius 1 circle\n                generate_circle(test_points, 1, 1);\n                // generate a random point from the radius 5 circle\n                generate_circle(test_points, 5, 1);\n\n                // project the two test points into kernel space.  Recall that this projection_function\n                // has the manifold regularizer incorporated into it.  \n                const sample_type class1_point = proj(test_points[0]);\n                const sample_type class2_point = proj(test_points[1]);\n\n                double num_wrong = 0;\n\n                // Now attempt to classify all the data samples according to which point\n                // they are closest to.  The output of this program shows that without manifold \n                // regularization this test will fail but with it it will perfectly classify\n                // all the points.\n                for (unsigned long i = 0; i < samples.size(); ++i)\n                {\n                    double distance_to_class1 = length(samples[i] - class1_point);\n                    double distance_to_class2 = length(samples[i] - class2_point);\n\n                    bool predicted_as_class_1 = (distance_to_class1 < distance_to_class2);\n\n                    bool really_is_class_1 = (i < num_points);\n\n                    // now count how many times we make a mistake\n                    if (predicted_as_class_1 != really_is_class_1)\n                        ++num_wrong;\n                }\n\n                DLIB_TEST_MSG(num_wrong == 0, num_wrong);\n            }\n\n        }\n\n        void generate_circle (\n            std::vector<sample_type>& samples,\n            double radius,\n            const long num\n        )\n        {\n            sample_type m(2,1);\n\n            for (long i = 0; i < num; ++i)\n            {\n                double sign = 1;\n                if (rnd.get_random_double() < 0.5)\n                    sign = -1;\n                m(0) = 2*radius*rnd.get_random_double()-radius;\n                m(1) = sign*sqrt(radius*radius - m(0)*m(0));\n\n                samples.push_back(m);\n            }\n        }\n\n\n        void test_knn1()\n        {\n            std::vector<matrix<double,2,1> > samples;\n\n            matrix<double,2,1> test;\n            \n            test = 0,0;  samples.push_back(test);\n            test = 1,1;  samples.push_back(test);\n            test = 1,-1;  samples.push_back(test);\n            test = -1,1;  samples.push_back(test);\n            test = -1,-1;  samples.push_back(test);\n\n            std::vector<sample_pair> edges;\n            find_k_nearest_neighbors(samples, squared_euclidean_distance(), 1, edges);\n            DLIB_TEST(edges.size() == 4);\n\n            std::sort(edges.begin(), edges.end(), &order_by_index<sample_pair>);\n\n            DLIB_TEST(edges[0] == sample_pair(0,1,0));\n            DLIB_TEST(edges[1] == sample_pair(0,2,0));\n            DLIB_TEST(edges[2] == sample_pair(0,3,0));\n            DLIB_TEST(edges[3] == sample_pair(0,4,0));\n\n            find_k_nearest_neighbors(samples, squared_euclidean_distance(), 3, edges);\n            DLIB_TEST(edges.size() == 8);\n\n            find_k_nearest_neighbors(samples, squared_euclidean_distance(3.9, 4.1), 3, edges);\n            DLIB_TEST(edges.size() == 4);\n\n            std::sort(edges.begin(), edges.end(), &order_by_index<sample_pair>);\n\n            DLIB_TEST(edges[0] == sample_pair(1,2,0));\n            DLIB_TEST(edges[1] == sample_pair(1,3,0));\n            DLIB_TEST(edges[2] == sample_pair(2,4,0));\n            DLIB_TEST(edges[3] == sample_pair(3,4,0));\n\n            find_k_nearest_neighbors(samples, squared_euclidean_distance(30000, 4.1), 3, edges);\n            DLIB_TEST(edges.size() == 0);\n        }\n\n        void test_knn1_approx()\n        {\n            std::vector<matrix<double,2,1> > samples;\n\n            matrix<double,2,1> test;\n            \n            test = 0,0;  samples.push_back(test);\n            test = 1,1;  samples.push_back(test);\n            test = 1,-1;  samples.push_back(test);\n            test = -1,1;  samples.push_back(test);\n            test = -1,-1;  samples.push_back(test);\n\n            std::vector<sample_pair> edges;\n            find_approximate_k_nearest_neighbors(samples, squared_euclidean_distance(), 1, 10000, seed, edges);\n            DLIB_TEST(edges.size() == 4);\n\n            std::sort(edges.begin(), edges.end(), &order_by_index<sample_pair>);\n\n            DLIB_TEST(edges[0] == sample_pair(0,1,0));\n            DLIB_TEST(edges[1] == sample_pair(0,2,0));\n            DLIB_TEST(edges[2] == sample_pair(0,3,0));\n            DLIB_TEST(edges[3] == sample_pair(0,4,0));\n\n            find_approximate_k_nearest_neighbors(samples, squared_euclidean_distance(), 3, 10000, seed, edges);\n            DLIB_TEST(edges.size() == 8);\n\n            find_approximate_k_nearest_neighbors(samples, squared_euclidean_distance(3.9, 4.1), 3, 10000, seed, edges);\n            DLIB_TEST(edges.size() == 4);\n\n            std::sort(edges.begin(), edges.end(), &order_by_index<sample_pair>);\n\n            DLIB_TEST(edges[0] == sample_pair(1,2,0));\n            DLIB_TEST(edges[1] == sample_pair(1,3,0));\n            DLIB_TEST(edges[2] == sample_pair(2,4,0));\n            DLIB_TEST(edges[3] == sample_pair(3,4,0));\n\n            find_approximate_k_nearest_neighbors(samples, squared_euclidean_distance(30000, 4.1), 3, 10000, seed, edges);\n            DLIB_TEST(edges.size() == 0);\n        }\n\n        void test_knn2()\n        {\n            std::vector<matrix<double,2,1> > samples;\n\n            matrix<double,2,1> test;\n            \n            test = 1,1;  samples.push_back(test);\n            test = 1,-1;  samples.push_back(test);\n            test = -1,1;  samples.push_back(test);\n            test = -1,-1;  samples.push_back(test);\n\n            std::vector<sample_pair> edges;\n            find_k_nearest_neighbors(samples, squared_euclidean_distance(), 2, edges);\n            DLIB_TEST(edges.size() == 4);\n\n            std::sort(edges.begin(), edges.end(), &order_by_index<sample_pair>);\n\n            DLIB_TEST(edges[0] == sample_pair(0,1,0));\n            DLIB_TEST(edges[1] == sample_pair(0,2,0));\n            DLIB_TEST(edges[2] == sample_pair(1,3,0));\n            DLIB_TEST(edges[3] == sample_pair(2,3,0));\n\n            find_k_nearest_neighbors(samples, squared_euclidean_distance(), 200, edges);\n            DLIB_TEST(edges.size() == 4*3/2);\n        }\n\n        void test_knn2_approx()\n        {\n            std::vector<matrix<double,2,1> > samples;\n\n            matrix<double,2,1> test;\n            \n            test = 1,1;  samples.push_back(test);\n            test = 1,-1;  samples.push_back(test);\n            test = -1,1;  samples.push_back(test);\n            test = -1,-1;  samples.push_back(test);\n\n            std::vector<sample_pair> edges;\n            // For this simple graph and high number of samples we will do we should obtain the exact \n            // knn solution.\n            find_approximate_k_nearest_neighbors(samples, squared_euclidean_distance(), 2, 10000, seed,  edges);\n            DLIB_TEST(edges.size() == 4);\n\n            std::sort(edges.begin(), edges.end(), &order_by_index<sample_pair>);\n\n            DLIB_TEST(edges[0] == sample_pair(0,1,0));\n            DLIB_TEST(edges[1] == sample_pair(0,2,0));\n            DLIB_TEST(edges[2] == sample_pair(1,3,0));\n            DLIB_TEST(edges[3] == sample_pair(2,3,0));\n\n\n            find_approximate_k_nearest_neighbors(samples, squared_euclidean_distance(), 200, 10000, seed,  edges);\n            DLIB_TEST(edges.size() == 4*3/2);\n        }\n\n        void perform_test (\n        )\n        {\n            for (int i = 0; i < 5; ++i)\n            {\n                do_the_test();\n\n                ++seed;\n                test_knn1_approx();\n                test_knn2_approx();\n            }\n            test_knn1();\n            test_knn2();\n            test_knn_lsh_sparse<double>();\n            test_knn_lsh_sparse<float>();\n            test_knn_lsh_dense<double>();\n            test_knn_lsh_dense<float>();\n\n        }\n    };\n\n    // Create an instance of this object.  Doing this causes this test\n    // to be automatically inserted into the testing framework whenever this cpp file\n    // is linked into the project.  Note that since we are inside an unnamed-namespace \n    // we won't get any linker errors about the symbol a being defined multiple times. \n    linear_manifold_regularizer_tester a;\n\n}\n\n\n\n", "meta": {"hexsha": "e73b1c8d323d06294edc7dbe2f22be838e38b8cf", "size": 15875, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dlib/dlib/test/linear_manifold_regularizer.cpp", "max_stars_repo_name": "maxmert/nlp-mitie", "max_stars_repo_head_hexsha": "ec3153ef2fe7a80e7cf3d80d14b388b8cd679343", "max_stars_repo_licenses": ["Unlicense"], "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": "dlib/test/linear_manifold_regularizer.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": "dlib/test/linear_manifold_regularizer.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": 38.8141809291, "max_line_length": 135, "alphanum_fraction": 0.5769448819, "num_tokens": 3820, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.4520055933582245}}
{"text": "#include \"FWCore/MessageLogger/interface/MessageLogger.h\"\n#include \"TrackstersPCA.h\"\n#include \"TPrincipal.h\"\n\n#include <iostream>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\nvoid ticl::assignPCAtoTracksters(std::vector<Trackster> &tracksters,\n                                 const std::vector<reco::CaloCluster> &layerClusters,\n                                 double z_limit_em,\n                                 bool energyWeight) {\n  LogDebug(\"TrackstersPCA_Eigen\") << \"------- Eigen -------\" << std::endl;\n\n  for (auto &trackster : tracksters) {\n    Eigen::Vector3d point;\n    point << 0., 0., 0.;\n    Eigen::Vector3d barycenter;\n    barycenter << 0., 0., 0.;\n\n    auto fillPoint = [&](const reco::CaloCluster &c, const float weight = 1.f) {\n      point[0] = weight * c.x();\n      point[1] = weight * c.y();\n      point[2] = weight * c.z();\n    };\n\n    // Initialize this trackster with default, dummy values\n    trackster.setRawEnergy(0.f);\n    trackster.setRawEmEnergy(0.f);\n    trackster.setRawPt(0.f);\n    trackster.setRawEmPt(0.f);\n\n    size_t N = trackster.vertices().size();\n    float weight = 1.f / N;\n    float weights2_sum = 0.f;\n    Eigen::Vector3d sigmas;\n    sigmas << 0., 0., 0.;\n    Eigen::Vector3d sigmasEigen;\n    sigmasEigen << 0., 0., 0.;\n    Eigen::Matrix3d covM = Eigen::Matrix3d::Zero();\n\n    for (size_t i = 0; i < N; ++i) {\n      auto fraction = 1.f / trackster.vertex_multiplicity(i);\n      trackster.addToRawEnergy(layerClusters[trackster.vertices(i)].energy() * fraction);\n      if (std::abs(layerClusters[trackster.vertices(i)].z()) <= z_limit_em)\n        trackster.addToRawEmEnergy(layerClusters[trackster.vertices(i)].energy() * fraction);\n\n      // Compute the weighted barycenter.\n      if (energyWeight)\n        weight = layerClusters[trackster.vertices(i)].energy() * fraction;\n      fillPoint(layerClusters[trackster.vertices(i)], weight);\n      for (size_t j = 0; j < 3; ++j)\n        barycenter[j] += point[j];\n    }\n    if (energyWeight && trackster.raw_energy())\n      barycenter /= trackster.raw_energy();\n\n    // Compute the Covariance Matrix and the sum of the squared weights, used\n    // to compute the correct normalization.\n    // The barycenter has to be known.\n    for (size_t i = 0; i < N; ++i) {\n      fillPoint(layerClusters[trackster.vertices(i)]);\n      if (energyWeight && trackster.raw_energy())\n        weight =\n            (layerClusters[trackster.vertices(i)].energy() / trackster.vertex_multiplicity(i)) / trackster.raw_energy();\n      weights2_sum += weight * weight;\n      for (size_t x = 0; x < 3; ++x)\n        for (size_t y = 0; y <= x; ++y) {\n          covM(x, y) += weight * (point[x] - barycenter[x]) * (point[y] - barycenter[y]);\n          covM(y, x) = covM(x, y);\n        }\n    }\n    covM *= 1. / (1. - weights2_sum);\n\n    // Perform the actual decomposition\n    Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d>::RealVectorType eigenvalues_fromEigen;\n    Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d>::EigenvectorsType eigenvectors_fromEigen;\n    Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> eigensolver(covM);\n    if (eigensolver.info() != Eigen::Success) {\n      eigenvalues_fromEigen = eigenvalues_fromEigen.Zero();\n      eigenvectors_fromEigen = eigenvectors_fromEigen.Zero();\n    } else {\n      eigenvalues_fromEigen = eigensolver.eigenvalues();\n      eigenvectors_fromEigen = eigensolver.eigenvectors();\n    }\n\n    // Compute the spread in the both spaces.\n    for (size_t i = 0; i < N; ++i) {\n      fillPoint(layerClusters[trackster.vertices(i)]);\n      sigmas += weight * (point - barycenter).cwiseAbs2();\n      Eigen::Vector3d point_transformed = eigenvectors_fromEigen * (point - barycenter);\n      if (energyWeight && trackster.raw_energy())\n        weight =\n            (layerClusters[trackster.vertices(i)].energy() / trackster.vertex_multiplicity(i)) / trackster.raw_energy();\n      sigmasEigen += weight * (point_transformed.cwiseAbs2());\n    }\n    sigmas /= (1. - weights2_sum);\n    sigmasEigen /= (1. - weights2_sum);\n\n    // Add trackster attributes\n    trackster.setBarycenter(ticl::Trackster::Vector(barycenter));\n    trackster.fillPCAVariables(\n        eigenvalues_fromEigen, eigenvectors_fromEigen, sigmas, sigmasEigen, 3, ticl::Trackster::PCAOrdering::ascending);\n\n    LogDebug(\"TrackstersPCA\") << \"Use energy weighting: \" << energyWeight << std::endl;\n    LogDebug(\"TrackstersPCA\") << \"\\nTrackster characteristics: \" << std::endl;\n    LogDebug(\"TrackstersPCA\") << \"Size: \" << N << std::endl;\n    LogDebug(\"TrackstersPCA\") << \"Energy: \" << trackster.raw_energy() << std::endl;\n    LogDebug(\"TrackstersPCA\") << \"raw_pt: \" << trackster.raw_pt() << std::endl;\n    LogDebug(\"TrackstersPCA\") << \"Means:          \" << barycenter[0] << \", \" << barycenter[1] << \", \" << barycenter[2]\n                              << std::endl;\n    LogDebug(\"TrackstersPCA\") << \"EigenValues from Eigen/Tr(cov): \" << eigenvalues_fromEigen[2] / covM.trace() << \", \"\n                              << eigenvalues_fromEigen[1] / covM.trace() << \", \"\n                              << eigenvalues_fromEigen[0] / covM.trace() << std::endl;\n    LogDebug(\"TrackstersPCA\") << \"EigenValues from Eigen:         \" << eigenvalues_fromEigen[2] << \", \"\n                              << eigenvalues_fromEigen[1] << \", \" << eigenvalues_fromEigen[0] << std::endl;\n    LogDebug(\"TrackstersPCA\") << \"EigenVector 3 from Eigen: \" << eigenvectors_fromEigen(0, 2) << \", \"\n                              << eigenvectors_fromEigen(1, 2) << \", \" << eigenvectors_fromEigen(2, 2) << std::endl;\n    LogDebug(\"TrackstersPCA\") << \"EigenVector 2 from Eigen: \" << eigenvectors_fromEigen(0, 1) << \", \"\n                              << eigenvectors_fromEigen(1, 1) << \", \" << eigenvectors_fromEigen(2, 1) << std::endl;\n    LogDebug(\"TrackstersPCA\") << \"EigenVector 1 from Eigen: \" << eigenvectors_fromEigen(0, 0) << \", \"\n                              << eigenvectors_fromEigen(1, 0) << \", \" << eigenvectors_fromEigen(2, 0) << std::endl;\n    LogDebug(\"TrackstersPCA\") << \"Original sigmas:          \" << sigmas[0] << \", \" << sigmas[1] << \", \" << sigmas[2]\n                              << std::endl;\n    LogDebug(\"TrackstersPCA\") << \"SigmasEigen in PCA space: \" << sigmasEigen[2] << \", \" << sigmasEigen[1] << \", \"\n                              << sigmasEigen[0] << std::endl;\n    LogDebug(\"TrackstersPCA\") << \"covM:     \\n\" << covM << std::endl;\n  }\n}\n", "meta": {"hexsha": "9a91400195da10719e133558f18a4d69cb506855", "size": 6384, "ext": "cc", "lang": "C++", "max_stars_repo_path": "RecoHGCal/TICL/plugins/TrackstersPCA.cc", "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": "RecoHGCal/TICL/plugins/TrackstersPCA.cc", "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": "RecoHGCal/TICL/plugins/TrackstersPCA.cc", "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": 48.7328244275, "max_line_length": 120, "alphanum_fraction": 0.6018170426, "num_tokens": 1768, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117983401363, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.45199488084836287}}
{"text": "// Boost.Geometry Index\n//\n// R-tree quadratic split algorithm implementation\n//\n// Copyright (c) 2011-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_INDEX_DETAIL_RTREE_QUADRATIC_REDISTRIBUTE_ELEMENTS_HPP\n#define BOOST_GEOMETRY_INDEX_DETAIL_RTREE_QUADRATIC_REDISTRIBUTE_ELEMENTS_HPP\n\n#include <algorithm>\n\n#include <boost/geometry/index/detail/algorithms/content.hpp>\n#include <boost/geometry/index/detail/algorithms/union_content.hpp>\n\n#include <boost/geometry/index/detail/rtree/node/node.hpp>\n#include <boost/geometry/index/detail/rtree/visitors/insert.hpp>\n#include <boost/geometry/index/detail/rtree/visitors/is_leaf.hpp>\n\nnamespace boost { namespace geometry { namespace index {\n\nnamespace detail { namespace rtree {\n\nnamespace quadratic {\n\ntemplate <typename Elements, typename Parameters, typename Translator, typename Box>\nstruct pick_seeds\n{\n    typedef typename Elements::value_type element_type;\n    typedef typename rtree::element_indexable_type<element_type, Translator>::type indexable_type;\n    typedef typename index::detail::traits::coordinate_type<indexable_type>::type coordinate_type;\n    typedef Box box_type;\n    typedef typename index::detail::default_content_result<box_type>::type content_type;\n\n    static inline void apply(Elements const& elements,\n                             Parameters const& parameters,\n                             Translator const& tr,\n                             size_t & seed1,\n                             size_t & seed2)\n    {\n        const size_t elements_count = parameters.get_max_elements() + 1;\n        BOOST_GEOMETRY_INDEX_ASSERT(elements.size() == elements_count, \"wrong number of elements\");\n        BOOST_GEOMETRY_INDEX_ASSERT(2 <= elements_count, \"unexpected number of elements\");\n\n        content_type greatest_free_content = 0;\n        seed1 = 0;\n        seed2 = 1;\n\n        for ( size_t i = 0 ; i < elements_count - 1 ; ++i )\n        {\n            for ( size_t j = i + 1 ; j < elements_count ; ++j )\n            {\n                indexable_type const& ind1 = rtree::element_indexable(elements[i], tr);\n                indexable_type const& ind2 = rtree::element_indexable(elements[j], tr);\n\n                box_type enlarged_box;\n                geometry::convert(ind1, enlarged_box);\n                geometry::expand(enlarged_box, ind2);\n\n                content_type free_content = (index::detail::content(enlarged_box) - index::detail::content(ind1)) - index::detail::content(ind2);\n                \n                if ( greatest_free_content < free_content )\n                {\n                    greatest_free_content = free_content;\n                    seed1 = i;\n                    seed2 = j;\n                }\n            }\n        }\n\n        BOOST_GEOMETRY_INDEX_DETAIL_USE_PARAM(parameters)\n    }\n};\n\n} // namespace quadratic\n\ntemplate <typename Value, typename Options, typename Translator, typename Box, typename Allocators>\nstruct redistribute_elements<Value, Options, Translator, Box, Allocators, quadratic_tag>\n{\n    typedef typename Options::parameters_type parameters_type;\n\n    typedef typename rtree::node<Value, parameters_type, Box, Allocators, typename Options::node_tag>::type node;\n    typedef typename rtree::internal_node<Value, parameters_type, Box, Allocators, typename Options::node_tag>::type internal_node;\n    typedef typename rtree::leaf<Value, parameters_type, Box, Allocators, typename Options::node_tag>::type leaf;\n\n    typedef typename index::detail::default_content_result<Box>::type content_type;\n\n    template <typename Node>\n    static inline void apply(Node & n,\n                             Node & second_node,\n                             Box & box1,\n                             Box & box2,\n                             parameters_type const& parameters,\n                             Translator const& translator,\n                             Allocators & allocators)\n    {\n        typedef typename rtree::elements_type<Node>::type elements_type;\n        typedef typename elements_type::value_type element_type;\n        typedef typename rtree::element_indexable_type<element_type, Translator>::type indexable_type;\n        typedef typename index::detail::traits::coordinate_type<indexable_type>::type coordinate_type;\n\n        elements_type & elements1 = rtree::elements(n);\n        elements_type & elements2 = rtree::elements(second_node);\n        \n        BOOST_GEOMETRY_INDEX_ASSERT(elements1.size() == parameters.get_max_elements() + 1, \"unexpected elements number\");\n\n        // copy original elements\n        elements_type elements_copy(elements1);                                                             // MAY THROW, STRONG (alloc, copy)\n        elements_type elements_backup(elements1);                                                           // MAY THROW, STRONG (alloc, copy)\n        \n        // calculate initial seeds\n        size_t seed1 = 0;\n        size_t seed2 = 0;\n        quadratic::pick_seeds<\n            elements_type,\n            parameters_type,\n            Translator,\n            Box\n        >::apply(elements_copy, parameters, translator, seed1, seed2);\n\n        // prepare nodes' elements containers\n        elements1.clear();\n        BOOST_GEOMETRY_INDEX_ASSERT(elements2.empty(), \"second node's elements container should be empty\");\n\n        BOOST_TRY\n        {\n            // add seeds\n            elements1.push_back(elements_copy[seed1]);                                                      // MAY THROW, STRONG (copy)\n            elements2.push_back(elements_copy[seed2]);                                                      // MAY THROW, STRONG (alloc, copy)\n\n            // calculate boxes\n            geometry::convert(rtree::element_indexable(elements_copy[seed1], translator), box1);\n            geometry::convert(rtree::element_indexable(elements_copy[seed2], translator), box2);\n\n            // remove seeds\n            if (seed1 < seed2)\n            {\n                rtree::move_from_back(elements_copy, elements_copy.begin() + seed2);                        // MAY THROW, STRONG (copy)\n                elements_copy.pop_back();\n                rtree::move_from_back(elements_copy, elements_copy.begin() + seed1);                        // MAY THROW, STRONG (copy)\n                elements_copy.pop_back();\n            }\n            else\n            {\n                rtree::move_from_back(elements_copy, elements_copy.begin() + seed1);                        // MAY THROW, STRONG (copy)\n                elements_copy.pop_back();\n                rtree::move_from_back(elements_copy, elements_copy.begin() + seed2);                        // MAY THROW, STRONG (copy)\n                elements_copy.pop_back();\n            }\n\n            // initialize areas\n            content_type content1 = index::detail::content(box1);\n            content_type content2 = index::detail::content(box2);\n\n            size_t remaining = elements_copy.size();\n\n            // redistribute the rest of the elements\n            while ( !elements_copy.empty() )\n            {\n                typename elements_type::reverse_iterator el_it = elements_copy.rbegin();\n                bool insert_into_group1 = false;\n\n                size_t elements1_count = elements1.size();\n                size_t elements2_count = elements2.size();\n\n                // if there is small number of elements left and the number of elements in node is lesser than min_elems\n                // just insert them to this node\n                if ( elements1_count + remaining <= parameters.get_min_elements() )\n                {\n                    insert_into_group1 = true;\n                }\n                else if ( elements2_count + remaining <= parameters.get_min_elements() )\n                {\n                    insert_into_group1 = false;\n                }\n                // insert the best element\n                else\n                {\n                    // find element with minimum groups areas increses differences\n                    content_type content_increase1 = 0;\n                    content_type content_increase2 = 0;\n                    el_it = pick_next(elements_copy.rbegin(), elements_copy.rend(),\n                                      box1, box2, content1, content2, translator,\n                                      content_increase1, content_increase2);\n\n                    if ( content_increase1 < content_increase2 ||\n                         ( content_increase1 == content_increase2 && ( content1 < content2 ||\n                           ( content1 == content2 && elements1_count <= elements2_count ) )\n                         ) )\n                    {\n                        insert_into_group1 = true;\n                    }\n                    else\n                    {\n                        insert_into_group1 = false;\n                    }\n                }\n\n                // move element to the choosen group\n                element_type const& elem = *el_it;\n                indexable_type const& indexable = rtree::element_indexable(elem, translator);\n\n                if ( insert_into_group1 )\n                {\n                    elements1.push_back(elem);                                                              // MAY THROW, STRONG (copy)\n                    geometry::expand(box1, indexable);\n                    content1 = index::detail::content(box1);\n                }\n                else\n                {\n                    elements2.push_back(elem);                                                              // MAY THROW, STRONG (alloc, copy)\n                    geometry::expand(box2, indexable);\n                    content2 = index::detail::content(box2);\n                }\n\n                BOOST_GEOMETRY_INDEX_ASSERT(!elements_copy.empty(), \"expected more elements\");\n                typename elements_type::iterator el_it_base = el_it.base();\n                rtree::move_from_back(elements_copy, --el_it_base);                                         // MAY THROW, STRONG (copy)\n                elements_copy.pop_back();\n\n                BOOST_GEOMETRY_INDEX_ASSERT(0 < remaining, \"expected more remaining elements\");\n                --remaining;\n            }\n        }\n        BOOST_CATCH(...)\n        {\n            //elements_copy.clear();\n            elements1.clear();\n            elements2.clear();\n\n            rtree::destroy_elements<Value, Options, Translator, Box, Allocators>::apply(elements_backup, allocators);\n            //elements_backup.clear();\n\n            BOOST_RETHROW                                                                                     // RETHROW, BASIC\n        }\n        BOOST_CATCH_END\n    }\n\n    // TODO: awulkiew - change following function to static member of the pick_next class?\n\n    template <typename It>\n    static inline It pick_next(It first, It last,\n                               Box const& box1, Box const& box2,\n                               content_type const& content1, content_type const& content2,\n                               Translator const& translator,\n                               content_type & out_content_increase1, content_type & out_content_increase2)\n    {\n        typedef typename boost::iterator_value<It>::type element_type;\n        typedef typename rtree::element_indexable_type<element_type, Translator>::type indexable_type;\n\n        content_type greatest_content_incrase_diff = 0;\n        It out_it = first;\n        out_content_increase1 = 0;\n        out_content_increase2 = 0;\n        \n        // find element with greatest difference between increased group's boxes areas\n        for ( It el_it = first ; el_it != last ; ++el_it )\n        {\n            indexable_type const& indexable = rtree::element_indexable(*el_it, translator);\n\n            // calculate enlarged boxes and areas\n            Box enlarged_box1(box1);\n            Box enlarged_box2(box2);\n            geometry::expand(enlarged_box1, indexable);\n            geometry::expand(enlarged_box2, indexable);\n            content_type enlarged_content1 = index::detail::content(enlarged_box1);\n            content_type enlarged_content2 = index::detail::content(enlarged_box2);\n\n            content_type content_incrase1 = (enlarged_content1 - content1);\n            content_type content_incrase2 = (enlarged_content2 - content2);\n\n            content_type content_incrase_diff = content_incrase1 < content_incrase2 ?\n                content_incrase2 - content_incrase1 : content_incrase1 - content_incrase2;\n\n            if ( greatest_content_incrase_diff < content_incrase_diff )\n            {\n                greatest_content_incrase_diff = content_incrase_diff;\n                out_it = el_it;\n                out_content_increase1 = content_incrase1;\n                out_content_increase2 = content_incrase2;\n            }\n        }\n\n        return out_it;\n    }\n};\n\n}} // namespace detail::rtree\n\n}}} // namespace boost::geometry::index\n\n#endif // BOOST_GEOMETRY_INDEX_DETAIL_RTREE_QUADRATIC_REDISTRIBUTE_ELEMENTS_HPP\n", "meta": {"hexsha": "100279583c7a3bab741509436a0365313f1ac642", "size": 13171, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/geometry/index/detail/rtree/quadratic/redistribute_elements.hpp", "max_stars_repo_name": "graehl/boost", "max_stars_repo_head_hexsha": "37cc4ca77896a86ad10e90dc03e1e825dc0d5492", "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/index/detail/rtree/quadratic/redistribute_elements.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/index/detail/rtree/quadratic/redistribute_elements.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": 44.4966216216, "max_line_length": 145, "alphanum_fraction": 0.5755067952, "num_tokens": 2512, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.451994873845528}}
{"text": "#include <vector>\n#include <algorithm>\n#include <set>\n#include <iostream>\n#include <armadillo>\n\n#include \"Util.h\"\n#include \"PostCalMultiPop.h\"\n\nusing namespace arma;\n\n\nvoid printGSLPrint(mat &A, int row, int col) {\n\tfor(int i = 0; i < row; i++) {\n\t\tfor(int j = 0; j < col; j++)\n\t\t\tprintf(\"%g \", A(i, j));\n\t\tprintf(\"\\n\");\n\t}\t\n}\n\nstring PostCalMultiPop::convertConfig2String(int * config, int size) {\n\tstring result = \"0\";\n\tfor(int i = 0; i < size; i++)\n\t\tif(config[i]==1)\n\t\t\tresult+= \"_\" + convertInt(i);\n\treturn result;\n}\n\n// We compute dmvnorm(Zcc, mean=rep(0,nrow(Rcc)), Rcc + Rcc %*% Rcc) / dmvnorm(Zcc, rep(0, nrow(Rcc)), Rcc))\n// // togheter to avoid numerical over flow\ndouble PostCalMultiPop::fracdmvnorm(mat Z, mat mean, mat R, mat diagC, int pop, double NCP) {\n        mat newR = R + R * diagC  * R;\n        mat ZcenterMean = Z - mean;\n        mat res1 = trans(ZcenterMean) * inv(R) * (ZcenterMean);\n        mat res2 = trans(ZcenterMean) * inv(newR) *  (ZcenterMean);\n\n        double v1 = res1(0,0)/2-res2(0,0)/2-baseValue[pop]/2;\n        return(exp(v1)/sqrt(det(newR))* sqrt(det(R)));\n}\n\ndouble PostCalMultiPop::dmvnorm(mat Z, mat mean, mat R) {\n        mat ZcenterMean = Z - mean;\n        mat res = trans(ZcenterMean) * inv(R) * (ZcenterMean);\n        double v1 = res(0,0);\n        double v2 = log(sqrt(det(R)));\n        return (exp(-v1/2-v2));\n}\n\n// cc=causal SNPs\n// Rcc = LD of causal SNPs\n// Zcc = Z-score of causal SNPs\n// dmvnorm(Zcc, mean=rep(0,nrow(Rcc)), Rcc + Rcc %*% Rcc) / dmvnorm(Zcc, rep(0, nrow(Rcc)), Rcc))\n//\ndouble PostCalMultiPop::fastLikelihood(int * configure, int pop, double NCP) {\n\tint causalCount = 0;\n\tvector <int> causalIndex;\n\n\tfor(int i = 0; i < snpCount; i++) {\n\t\tcausalCount += configure[i];\n\t\tif(configure[i] == 1)\n\t\t\tcausalIndex.push_back(i);\n\t}\n\t\n\tif (causalCount == 0) {\n\t\tint maxVal = 0;\n\t\tfor(int i = 0; i < snpCount; i++) {\n\t\t\tif (maxVal < abs(stat[pop][i]))\n\t\t\t\tmaxVal = stat[pop][i];\n\t\t}\n\t\tbaseValue[pop] = maxVal * maxVal;\n\t}\n\n\tmat Rcc(causalCount, causalCount, fill::zeros);\n\tmat Zcc(causalCount, 1, fill::zeros);\n\tmat mean(causalCount, 1, fill::zeros);\n\tmat diagC(causalCount, causalCount, fill::zeros);\n\n\tfor (int i = 0; i < causalCount; i++){\n\t\tfor(int j = 0; j < causalCount; j++) {\n\t\t\tRcc(i,j) = sigmaMatrix[pop](causalIndex[i], causalIndex[j]);\n\t\t}\n\t\tZcc(i,0) = stat[pop][causalIndex[i]];\n\t\tdiagC(i,i) = NCP;\n\t}\n\treturn fracdmvnorm(Zcc, mean, Rcc, diagC,pop, NCP);\n}\n\nint PostCalMultiPop::nextBinary(int * data, int size) {\n\tint i = 0;\n\tint total_one = 0;\t\n\tint index = size-1;\n        int one_countinus_in_end = 0;\n\n        while(index >= 0 && data[index] == 1) {\n                index = index - 1;\n                one_countinus_in_end = one_countinus_in_end + 1;\n\t}\n\tif(index >= 0) {\n        \twhile(index >= 0 && data[index] == 0) {\n               \t index = index - 1;\t\n\t\t}\n\t}\n        if(index == -1) {\n                while(i <  one_countinus_in_end+1 && i < size) {\n                        data[i] = 1;\n                        i=i+1;\n\t\t}\n                i = 0;\n                while(i < size-one_countinus_in_end-1) {\n                        data[i+one_countinus_in_end+1] = 0;\n                        i=i+1;\n\t\t}\n\t}\n        else if(one_countinus_in_end == 0) {\n                data[index] = 0;\n                data[index+1] = 1;\n\t} else {\n                data[index] = 0;\n                while(i < one_countinus_in_end + 1) {\n                        data[i+index+1] = 1;\n\t\t\tif(i+index+1 >= size)\n\t\t\t\tprintf(\"ERROR3 %d\\n\", i+index+1);\n                        i=i+1;\n\t\t}\n                i = 0;\n                while(i < size - index - one_countinus_in_end - 2) {\n                        data[i+index+one_countinus_in_end+2] = 0;\n\t\t\tif(i+index+one_countinus_in_end+2 >= size) {\n\t\t\t\tprintf(\"ERROR4 %d\\n\", i+index+one_countinus_in_end+2);\n\t\t\t}\n                        i=i+1;\n\t\t}\n\t}\n\ti = 0;\n\ttotal_one = 0;\n\tfor(i = 0; i < size; i++)\n\t\tif(data[i] == 1)\n\t\t\ttotal_one = total_one + 1;\n\t\n\treturn(total_one);\t\t\n}\n\ndouble PostCalMultiPop::computeTotalLikelihood(double NCP) {\t\n\tint num = 0;\n\tdouble sumLikelihood = 0;\n\tdouble tmp_likelihood = 1;\n\tlong int total_iteration = 0 ;\n\tint * configure = (int *) malloc (snpCount * sizeof(int *)); // original data\t\n\n\tfor(long int i = 0; i <= maxCausalSNP; i++)\n\t\ttotal_iteration = total_iteration + nCr(snpCount, i);\n\tcout << snpCount << endl;\n\tcout << \"Max Causal=\" << maxCausalSNP << endl;\n\tcout << \"Total=\"      << total_iteration << endl;\n\tfor(long int i = 0; i < snpCount; i++) \n\t\tconfigure[i] = 0;\n\tfor(long int i = 0; i < total_iteration; i++) {\n\t\ttmp_likelihood = 1;\n\t\tfor (int pop =0 ; pop < popNum; pop++) \n                \ttmp_likelihood = tmp_likelihood * fastLikelihood(configure, pop, NCP) * (pow(gamma, num))*(pow(1-gamma, snpCount-num));\n\t\tsumLikelihood += tmp_likelihood;\n\t\tfor(int j = 0; j < snpCount; j++) {\n                        postValues[j] = postValues[j] + tmp_likelihood * configure[j];\n\t\t}\n\t\thistValues[num] = histValues[num] + tmp_likelihood;\n                num = nextBinary(configure, snpCount);\n       \t\tif(i % 100000 == 0)\n\t\t\tcout << i << \" \"  << sumLikelihood << endl;\n\t}\n\tfor(int i = 0; i <= maxCausalSNP; i++)\n\t\thistValues[i] = histValues[i]/sumLikelihood;\n        free(configure);\n        return(sumLikelihood);\n}\n\n/*\n\tstat is the z-scpres\n\tsigma is the correaltion matrix\n\tG is the map between snp and the gene (snp, gene)\n*/\ndouble PostCalMultiPop::findOptimalSetGreedy(double NCP, char * pcausalSet, int *rank,  double inputRho, string outputFileName) {\n\tint index = 0;\n        double rho = 0;\n        double total_post = 0;\n\n        totalLikeLihoodLOG = computeTotalLikelihood(NCP);\n\t\n\texport2File(outputFileName+\".log\", totalLikeLihoodLOG); //Output the total likelihood to the log File\n\tfor(int i = 0; i < snpCount; i++)\n\t\ttotal_post += postValues[i];\n\tprintf(\"Total Likelihood= %e SNP=%d \\n\", total_post, snpCount);\n\t\n        std::vector<data> items;\n        std::set<int>::iterator it;\n\t//output the poster to files\n        for(int i = 0; i < snpCount; i++) {\n             //printf(\"%d==>%e \",i, postValues[i]/total_likelihood);\n             items.push_back(data(postValues[i]/total_post, i, 0));\n        }\n        printf(\"\\n\");\n        std::sort(items.begin(), items.end(), by_number());\n        for(int i = 0; i < snpCount; i++)\n                rank[i] = items[i].index1;\n\n        for(int i = 0; i < snpCount; i++)\n                pcausalSet[i] = '0';\n        do{\n                rho += postValues[rank[index]]/total_post;\n                pcausalSet[rank[index]] = '1';\n                printf(\"%d %e\\n\", rank[index], rho);\n                index++;\n        } while( rho < inputRho);\n\n        printf(\"\\n\");\n\treturn(0);\n}\n", "meta": {"hexsha": "36bfa108dae53322c0ee0db9b933d070eac35d6a", "size": 6661, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "caviar/resources/usr/bin/PostCalMultiPop.cpp", "max_stars_repo_name": "collaborativebioinformatics/DSVifier", "max_stars_repo_head_hexsha": "3b2f2737cb947da96300009b75aebe977bf52801", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "caviar/resources/usr/bin/PostCalMultiPop.cpp", "max_issues_repo_name": "collaborativebioinformatics/DSVifier", "max_issues_repo_head_hexsha": "3b2f2737cb947da96300009b75aebe977bf52801", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "caviar/resources/usr/bin/PostCalMultiPop.cpp", "max_forks_repo_name": "collaborativebioinformatics/DSVifier", "max_forks_repo_head_hexsha": "3b2f2737cb947da96300009b75aebe977bf52801", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-07T10:42:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-07T10:42:06.000Z", "avg_line_length": 30.6958525346, "max_line_length": 136, "alphanum_fraction": 0.56057649, "num_tokens": 2075, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.451994873845528}}
{"text": "#include <boost/gil.hpp>\nusing namespace boost::gil;\n\ntemplate <typename Out>\nstruct halfdiff_cast_channels {\n    template <typename T> Out operator()(const T& in1, const T& in2) const {\n        return Out((in1-in2)/2);\n    }\n};\n\ntemplate <typename SrcView, typename DstView>\nvoid x_gradient(const SrcView& src, const DstView& dst) {\n    typedef typename channel_type<DstView>::type dst_channel_t;\n\n    for (int y=0; y<src.height(); ++y) {\n        typename SrcView::x_iterator src_it = src.row_begin(y);\n        typename DstView::x_iterator dst_it = dst.row_begin(y);\n\n        for (int x=1; x<src.width()-1; ++x)\n            static_transform(src_it[x-1], src_it[x+1], dst_it[x], \n                               halfdiff_cast_channels<dst_channel_t>());\n    }\n}\n\nvoid ComputeXGradientGray8(const unsigned char* src_pixels, ptrdiff_t src_row_bytes, int w, int h,\n                                   signed char* dst_pixels, ptrdiff_t dst_row_bytes) {\n    gray8c_view_t src = interleaved_view(w, h, (const gray8_pixel_t*)src_pixels,src_row_bytes);\n    gray8s_view_t dst = interleaved_view(w, h, (     gray8s_pixel_t*)dst_pixels,dst_row_bytes);\n    x_gradient(src,dst);\n}\n\nint main() {\n    return 0;\n}\n", "meta": {"hexsha": "1d5722150469c5bc21709b3f2ac7a2408eee4dda", "size": 1197, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/gil_test.cc", "max_stars_repo_name": "wxthon/rules_boost", "max_stars_repo_head_hexsha": "46916bd45a7ed0f1f64f5b5dff0fec5b87870d0a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 214.0, "max_stars_repo_stars_event_min_datetime": "2016-08-24T01:08:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T02:24:55.000Z", "max_issues_repo_path": "test/gil_test.cc", "max_issues_repo_name": "wxthon/rules_boost", "max_issues_repo_head_hexsha": "46916bd45a7ed0f1f64f5b5dff0fec5b87870d0a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 184.0, "max_issues_repo_issues_event_min_datetime": "2017-01-20T22:43:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T16:26:45.000Z", "max_forks_repo_path": "test/gil_test.cc", "max_forks_repo_name": "wxthon/rules_boost", "max_forks_repo_head_hexsha": "46916bd45a7ed0f1f64f5b5dff0fec5b87870d0a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 258.0, "max_forks_repo_forks_event_min_datetime": "2016-08-24T01:08:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T18:07:16.000Z", "avg_line_length": 34.2, "max_line_length": 98, "alphanum_fraction": 0.6574770259, "num_tokens": 318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.4519839541001593}}
{"text": "#pragma once\n\n// Polyvec\n#include <polyvec/core/macros.hpp>\n#include <polyvec/polygon-tracer/boundary-graph.hpp>\n#include <polyvec/pipeline_helper.hpp>\n#include <polyvec/shortest-path/dijkstra.hpp>\n#include <polyvec/curve-tracer/spline.hpp>\n#include <polyvec/regularity/symmetry.hpp>\n\n// Eigen\n#include <Eigen/Core>\n\n// libc++\n#include <unordered_map>\n#include <vector>\n#include <memory>\n\nNAMESPACE_BEGIN(polyvec)\n\n// Forward declarations\nclass FitClassifier;\n\n//\nclass ImageBoundary {\npublic:\n    ImageBoundary(\n        const Eigen::Matrix2Xi& points, \n        const int polygon_id,\n        const Eigen::Vector4d& color\n    );\n\n    // Returns true if the boundary vertex 'v' is flat, if that is the case, edges will not be\n    // constructed starting/from or to it\n    bool is_flat(const int v) const;\n\n    // Constructs the boundary graph allowing for flat vertices\n    void initialize_graph_with_flat_vertices(const Eigen::VectorXi& B_flat);\n\n    // Fits a polygon with regularization\n    void trace_polygon(\n        const std::unordered_set<int>& kopf_junctions = std::unordered_set<int>()\n    );\n    \n    // Fits a polygon without regularization\n    void trace_polygon_simple();\n\n    void compute_regularities();\n\n    // Resets the graph to its original state preserving the fitting results\n    void reset_graph();\n\n    // Adds an edge to the boundary graph, validating the indices\n    void add_edge(const polyfit::BoundaryGraph::Edge& e);\n\n    void remove_edges_crossing_vertices(const std::vector<int> V);\n\n    double bounding_box_area()const;\n\n    // Prunes the boundary graph so that the polygon will go through the specified corners.\n    // It does not trace a new polygon.\n    // The subpath *will* exist regardless of the current state of the boundary graph, but\n    // a polygon is not guaranteed to exist.\n    // It validates the subpath indices against the boundary\n    void force_graph_subpath(const Eigen::VectorXi& subpath);\n\n    // Returns the list of vertices in the polygon contained in [v_src, v_dst]\n    Eigen::VectorXi get_polygon_subpath(const int v_src, const int v_dst) const;\n\n    // Same as get_polygon_subpath but returns the index of the first and last vertex in the closed boundary interval [v_src, v_dst]\n    std::pair<int, int> get_polygon_subpath_bounds(const int v_src, const int v_dst) const;\n\n    // Returns the sum of the edge cost for all polygon edges contained within [v_first, v_last]\n    double calculate_subpath_energy(const int v_first, const int v_last) const;\n\n    // Returns the index of the polygon vertex matching the specified boundary vertex or -1 if it doesn't exist.\n    int find_polygon_vertex_for_boundary_vertex(const int v)const;\n\n    // assumes that v is a C^0 corner\n    int find_line_before_polygon_vertex(const int v)const;\n    int find_line_after_polygon_vertex(const int v)const;\n\n    // Obtains a tangent classification for each corner. A polygon must have been traced\n    // No curves are fit\n    void classify_corners(FitClassifier& classifier);\n\n    // Initializes the curves with their initial guesses\n    void fit_curves_initial_guess();\n\n    void flip_coordinate_system(const polyfit::BoundaryGraph::EdgeID edge);\n\n    std::pair<int, int> get_primitives_interval_open   (const int v_first, const int v_last, const int direction) const;\n    std::pair<int, int> get_primitives_interval_closed (const int v_first, const int v_last, const int direction) const;\n\n    std::vector<CurvePrimitive> clone_curves_at_corner_reversed (const int v_P) const;\n\n    // angle at *polygon* vertex\n    double angle_at_vertex(const int v);\n\n    // -----------------------------------------------\n    // Getters\n    int id() const { return _id; }\n    const Eigen::Vector4d& color() const { return _color; }\n\n    // Input raster\n    const Eigen::Matrix2Xi& raster_points() const { return _points; }\n    const Eigen::Matrix2Xd& raster_points_as_double()const { return _points_as_double; }\n\n    // Boundary\n    const Eigen::Matrix2Xd& boundary_points() const { return _polygon.B; }\n    const polyfit::BoundaryGraph::AccuracyMap& accuracy_map()const { return _accuracy_map; }\n    const std::vector<polyfit::BoundaryGraph::Edge>& edges() const { return _polygon.E; }\n    std::vector<polyfit::BoundaryGraph::Edge>& edges() { return _polygon.E; }\n    const std::vector<polyfit::BoundaryGraph::Edge>& edges_original() const { return _E_original; }\n    std::vector<size_t>& E_delete() { return _E_delete; }\n    const std::vector<int>& convexities() const { return _boundary_convexities; } // inside \n    std::vector<polyfit::Symmetry::SubPath>& raster_symmetries() { return _polygon.raster_symmetries; }\n    std::vector<polyfit::Symmetry::SubPath>& raster_symmetries_local() { return _polygon.raster_symmetries_local; }\n    const std::vector<polyfit::Symmetry::SubPath>& raster_symmetries() const { return _polygon.raster_symmetries; }\n\n    // Polygon\n    Eigen::VectorXi& polygon_vertices() { return _polygon.P; }\n    const Eigen::VectorXi& polygon_vertices() const { return _polygon.P; }\n    Eigen::Matrix2Xd& polygon_points() { return _polygon.PP; }\n    const Eigen::Matrix2Xd& polygon_points() const { return _polygon.PP; }\n    std::vector<Eigen::Index>& midpoints() { return _polygon.M; }\n    const std::vector<Eigen::Index>& midpoints() const { return _polygon.M; }\n    std::vector<bool>& midpoints_bits() { return _polygon.midpoints; }\n    const std::vector<bool>& midpoints_bits() const { return _polygon.midpoints; }\n    const std::vector<int>& polygon_convexities_inside() const { return _convexities_inside; }\n    const std::vector<int>& polygon_convexities_outside() const { return _convexities_outside; }\n    const polyfit::Regularity::RegularityInformation& regularity_graph() const { return _polygon.RE; }\n\tpolyfit::Regularity::RegularityInformation& regularity_graph() { return _polygon.RE; }\n\n    // Smooth fits\n    std::vector<TangentFitType>& tangents_fits() { return _tangents; }\n    const std::vector<TangentFitType>& tangents_fits() const { return _tangents; }\n    CurvePrimitiveSequence& spline() { return _spline; }\n    const CurvePrimitiveSequence& spline()const { return _spline; }\n    const std::vector<polyvec::AttemptInfo>& fitting_attempts() const { return _fitting_attempts; }\n\nprivate:\n    void _initialize_curve_fitter();\n    void _update_polygon();\n    void _update_convexities();\n    bool _is_polygon_data_consistent_and_exists();\n    void _initialize_graph_if_necessary();\n\n    // Initialization \n    const int _id;\n    const Eigen::Vector4d _color;\n\n    // Raster\n    Eigen::Matrix2Xi _points;\n    Eigen::Matrix2Xd _points_as_double;\n    std::vector<int> _boundary_convexities; // w.r.t. _polygon.B\n    std::vector<bool> _B_flat;\n\n    // Polygon\n    PolygonData                               _polygon;\n    std::vector<polyfit::BoundaryGraph::Edge> _E_original;\n    polyfit::BoundaryGraph::AccuracyMap                _accuracy_map;\n    polyfit::ShortestPath::State              _shortest_path_state;\n    std::vector<size_t>                       _E_delete;\n    \n    //\n    std::vector<int>                          _convexities_inside;\n    std::vector<int>                          _convexities_outside;\n\n    // Curves\n    bool _curves_dirty;\n    std::unique_ptr<CurveSequenceFitter> _spline_fitter;\n    CurvePrimitiveSequence _spline;\n    std::vector<TangentFitType> _tangents;\n    std::vector<polyvec::AttemptInfo> _fitting_attempts;\n\n    std::vector<bool> _edge_coordinate_systems;\n};\n\nNAMESPACE_END(polyvec)\n", "meta": {"hexsha": "b62d64d7eba3338cc20bee6564dbd5cf30034a82", "size": 7490, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/polyvec/polygon-tracer/image_boundary.hpp", "max_stars_repo_name": "ShnitzelKiller/polyfit", "max_stars_repo_head_hexsha": "51ddc6365a794db1678459140658211cb78f65b1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2020-08-17T17:25:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T05:49:12.000Z", "max_issues_repo_path": "include/polyvec/polygon-tracer/image_boundary.hpp", "max_issues_repo_name": "ShnitzelKiller/polyfit", "max_issues_repo_head_hexsha": "51ddc6365a794db1678459140658211cb78f65b1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-08-26T13:54:59.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-21T07:19:22.000Z", "max_forks_repo_path": "include/polyvec/polygon-tracer/image_boundary.hpp", "max_forks_repo_name": "ShnitzelKiller/polyfit", "max_forks_repo_head_hexsha": "51ddc6365a794db1678459140658211cb78f65b1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-08-26T23:26:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-04T09:06:07.000Z", "avg_line_length": 41.3812154696, "max_line_length": 132, "alphanum_fraction": 0.7126835781, "num_tokens": 1803, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140728, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.451983948245012}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2020-2021 Mikhail Komarov <nemo@nil.foundation>\n// Copyright (c) 2020-2021 Nikita Kaskov <nbering@nil.foundation>\n// Copyright (c) 2020-2021 Ilias Khairullin <ilias@nil.foundation>\n// Copyright (c) 2022 Ekaterina Chukavina <kate@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#define BOOST_TEST_MODULE algebra_short_weierstrass_coordinates_test\n\n#include <iostream>\n#include <type_traits>\n\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 <boost/property_tree/ptree.hpp>\n#include <boost/property_tree/json_parser.hpp>\n\n#include <nil/crypto3/algebra/curves/secp_r1.hpp>\n\n#include <nil/crypto3/algebra/random_element.hpp>\n\n#include <nil/crypto3/multiprecision/cpp_int.hpp>\n\nusing namespace nil::crypto3::algebra;\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 CurveParams, typename Form>\nvoid print_curve_point(std::ostream &os,\n                       const curves::detail::curve_element<CurveParams, Form, curves::coordinates::affine> &p) {\n    os << \"( X: [\";\n    print_field_element(os, p.X);\n    os << \"], Y: [\";\n    print_field_element(os, p.Y);\n    os << \"] )\" << std::endl;\n}\n\ntemplate<typename CurveParams, typename Form, typename Coordinates>\ntypename std::enable_if<std::is_same<Coordinates, curves::coordinates::jacobian_with_a4_minus_3>::value||\n                        std::is_same<Coordinates, curves::coordinates::jacobian>::value||                       \n                        std::is_same<Coordinates, curves::coordinates::projective_with_a4_minus_3>::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\nnamespace boost {\n    namespace test_tools {\n        namespace tt_detail {\n            template<typename CurveParams, typename Form, typename Coordinates>\n            struct print_log_value<curves::detail::curve_element<CurveParams, Form, Coordinates>> {\n                void operator()(std::ostream &os,\n                                curves::detail::curve_element<CurveParams, Form, Coordinates> const &p) {\n                    print_curve_point(os, p);\n                }\n            };\n\n            template<template<typename, typename> class P, typename K, typename V>\n            struct print_log_value<P<K, V>> {\n                void operator()(std::ostream &, P<K, V> const &) {\n                }\n            };\n\n            template<typename FieldParams>\n            struct print_log_value<typename fields::detail::element_fp<FieldParams>> {\n                void operator()(std::ostream &os, typename fields::detail::element_fp<FieldParams> const &e) {\n                    print_field_element(os, e);\n                }\n            };\n        }    // namespace tt_detail\n    }        // namespace test_tools\n}    // namespace boost\n\nconst char *test_data = \"../../../../libs/algebra/test/data/coordinates.json\";\n\nboost::property_tree::ptree string_data(std::string test_name) {\n    boost::property_tree::ptree string_data;\n    boost::property_tree::read_json(test_data, string_data);\n\n    return string_data.get_child(test_name);\n}\n\nenum curve_operation_test_constants : std::size_t { C1, C2 };\n\nenum curve_operation_test_points : std::size_t {\n    p1,\n    p2,\n    p1_plus_p2,\n    p1_minus_p2,\n    p1_mul_C1,\n    p2_mul_C1_plus_p2_mul_C2,\n    p1_dbl\n};\n\ntemplate<typename CurveGroup>\nvoid check_curve_operations(const std::vector<typename CurveGroup::value_type> &points,\n                            const std::vector<std::size_t> &constants) {\n    using nil::crypto3::multiprecision::cpp_int;\n\n    BOOST_CHECK_EQUAL(points[p1] + points[p2], points[p1_plus_p2]);\n    BOOST_CHECK_EQUAL(points[p1] - points[p2], points[p1_minus_p2]);\n    BOOST_CHECK_EQUAL(points[p1].doubled(), points[p1_dbl]);\n    BOOST_CHECK_EQUAL(points[p1] * static_cast<cpp_int>(constants[C1]), points[p1_mul_C1]);\n    BOOST_CHECK_EQUAL((points[p2] * static_cast<cpp_int>(constants[C1])) +\n                          (points[p2] * static_cast<cpp_int>(constants[C2])),\n                      points[p2_mul_C1_plus_p2_mul_C2]);\n    BOOST_CHECK_EQUAL((points[p2] * static_cast<cpp_int>(constants[C1])) +\n                          (points[p2] * static_cast<cpp_int>(constants[C2])),\n                      points[p2] * static_cast<cpp_int>(constants[C1] + constants[C2]));\n}\n\ntemplate<typename FpCurveGroup, typename TestSet>\nvoid fp_curve_test_init(std::vector<typename FpCurveGroup::value_type> &points,\n                        std::vector<std::size_t> &constants,\n                        const TestSet &test_set) {\n    typedef typename FpCurveGroup::field_type::value_type field_value_type;\n    std::array<field_value_type, 3> coordinates;\n\n    for (auto &point : test_set.second.get_child(\"point_coordinates\")) {\n        auto i = 0;\n        for (auto &coordinate : point.second) {\n            coordinates[i++] = field_value_type(typename field_value_type::integral_type(coordinate.second.data()));\n        }\n        points.emplace_back(typename FpCurveGroup::value_type(coordinates[0], coordinates[1], coordinates[2]));\n    }\n\n    for (auto &constant : test_set.second.get_child(\"constants\")) {\n        constants.emplace_back(std::stoul(constant.second.data()));\n    }\n}\n\ntemplate<typename CurveGroup, typename TestSet>\nvoid curve_operation_test(const TestSet &test_set,\n                          void (&test_init)(std::vector<typename CurveGroup::value_type> &,\n                                            std::vector<std::size_t> &,\n                                            const TestSet &)) {\n\n    std::vector<typename CurveGroup::value_type> points;\n    std::vector<std::size_t> constants;\n\n    test_init(points, constants, test_set);\n\n    check_curve_operations<CurveGroup>(points, constants);\n}\n\nBOOST_AUTO_TEST_SUITE(curves_manual_tests)\n\nBOOST_DATA_TEST_CASE(curve_operation_test_jacobian_minus_3, string_data(\"curve_operation_test_jacobian_minus_3\"), data_set) {\n    using policy_type = curves::secp_r1<256>::g1_type< curves::coordinates::jacobian_with_a4_minus_3,  curves::forms::short_weierstrass>;\n\n    curve_operation_test<policy_type>(data_set, fp_curve_test_init<policy_type>);\n}\n\nBOOST_DATA_TEST_CASE(curve_operation_test_jacobian, string_data(\"curve_operation_test_jacobian\"), data_set) {\n    using policy_type = curves::secp_r1<256>::g1_type< curves::coordinates::jacobian,  curves::forms::short_weierstrass>;\n\n    curve_operation_test<policy_type>(data_set, fp_curve_test_init<policy_type>);\n}\n\nBOOST_DATA_TEST_CASE(curve_operation_test_projective_with_a4_minus_3, string_data(\"curve_operation_test_projective_with_a4_minus_3\"), data_set) {\n    using policy_type = curves::secp_r1<256>::g1_type< curves::coordinates::projective_with_a4_minus_3,  curves::forms::short_weierstrass>;\n\n    curve_operation_test<policy_type>(data_set, fp_curve_test_init<policy_type>);\n}\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "89eb91cfcdfdff0158cdbcecf2eb001445d65a5d", "size": 8453, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/short_weierstrass_coordinates.cpp", "max_stars_repo_name": "JasonCoombs/crypto3-algebra", "max_stars_repo_head_hexsha": "3ddb4eb0ed65dc046660cc49811d17a140a4c72f", "max_stars_repo_licenses": ["MIT"], "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/short_weierstrass_coordinates.cpp", "max_issues_repo_name": "JasonCoombs/crypto3-algebra", "max_issues_repo_head_hexsha": "3ddb4eb0ed65dc046660cc49811d17a140a4c72f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-07-22T14:48:45.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-22T14:49:30.000Z", "max_forks_repo_path": "test/short_weierstrass_coordinates.cpp", "max_forks_repo_name": "NilFoundation/algebra", "max_forks_repo_head_hexsha": "f211b0ffb2c7d817d44d2a6d1cc586a6db62dc03", "max_forks_repo_licenses": ["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.1275510204, "max_line_length": 145, "alphanum_fraction": 0.6744351118, "num_tokens": 1942, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145998, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.45197368760591194}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2004, 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/dividendvanillaoption.hpp>\n#include <ql/instruments/impliedvolatility.hpp>\n#include <ql/pricingengines/vanilla/analyticdividendeuropeanengine.hpp>\n#include <ql/pricingengines/vanilla/fdblackscholesvanillaengine.hpp>\n#include <ql/utilities/dataformatters.hpp>\n#include <ql/cashflows/cashflowvectors.hpp>\n#include <ql/exercise.hpp>\n#include <boost/scoped_ptr.hpp>\n\nnamespace QuantLib {\n\n    DividendVanillaOption::DividendVanillaOption(\n                           const ext::shared_ptr<StrikedTypePayoff>& payoff,\n                           const ext::shared_ptr<Exercise>& exercise,\n                           const std::vector<Date>& dividendDates,\n                           const std::vector<Real>& dividends)\n    : OneAssetOption(payoff, exercise),\n      cashFlow_(DividendVector(dividendDates, dividends)) {}\n\n\n    Volatility DividendVanillaOption::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 AnalyticDividendEuropeanEngine(newProcess));\n            break;\n          case Exercise::American:\n            engine.reset(new FdBlackScholesVanillaEngine(newProcess));\n            break;\n          case Exercise::Bermudan:\n            QL_FAIL(\"engine not available for Bermudan option with dividends\");\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    void DividendVanillaOption::setupArguments(\n                                       PricingEngine::arguments* args) const {\n        OneAssetOption::setupArguments(args);\n\n        DividendVanillaOption::arguments* arguments =\n            dynamic_cast<DividendVanillaOption::arguments*>(args);\n        QL_REQUIRE(arguments != 0, \"wrong engine type\");\n\n        arguments->cashFlow = cashFlow_;\n    }\n\n\n    void DividendVanillaOption::arguments::validate() const {\n        OneAssetOption::arguments::validate();\n\n        Date exerciseDate = exercise->lastDate();\n\n        for (Size i = 0; i < cashFlow.size(); i++) {\n            QL_REQUIRE(cashFlow[i]->date() <= exerciseDate,\n                       \"the \" << io::ordinal(i+1) << \" dividend date (\"\n                       << cashFlow[i]->date()\n                       << \") is later than the exercise date (\"\n                       << exerciseDate << \")\");\n        }\n    }\n\n}\n\n", "meta": {"hexsha": "a1998e72facf5da78f0c1e334fb190151a81b20a", "size": 4233, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ql/instruments/dividendvanillaoption.cpp", "max_stars_repo_name": "urgu00/QuantLib", "max_stars_repo_head_hexsha": "fecce0abb0ff3d50da29c129f8f9e73176e20ab9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-07-30T17:51:09.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-30T17:51:09.000Z", "max_issues_repo_path": "ql/instruments/dividendvanillaoption.cpp", "max_issues_repo_name": "urgu00/QuantLib", "max_issues_repo_head_hexsha": "fecce0abb0ff3d50da29c129f8f9e73176e20ab9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2020-11-23T08:36:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T10:06:53.000Z", "max_forks_repo_path": "ql/instruments/dividendvanillaoption.cpp", "max_forks_repo_name": "urgu00/QuantLib", "max_forks_repo_head_hexsha": "fecce0abb0ff3d50da29c129f8f9e73176e20ab9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-06-04T15:19:22.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-18T08:24:37.000Z", "avg_line_length": 38.8348623853, "max_line_length": 79, "alphanum_fraction": 0.59437751, "num_tokens": 854, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145998, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4519736876059119}}
{"text": "/*=============================================================================\n\n  NifTK: A software platform for medical image computing.\n\n  Copyright (c) University College London (UCL). All rights reserved.\n\n  This software is distributed WITHOUT ANY WARRANTY; without even\n  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n  PURPOSE.\n\n  See LICENSE.txt in the top level directory for details.\n\n=============================================================================*/\n\n#include \"mitkOpenCVMaths.h\"\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <numeric>\n#include <algorithm>\n#include <functional>\n#include <mitkExceptionMacro.h>\n#include <niftkMathsUtils.h>\n#include <niftkVTKFunctions.h>\n\nnamespace mitk {\n\n//-----------------------------------------------------------------------------\nstd::vector<cv::Point3d> SubtractPointFromPoints(const std::vector<cv::Point3d> listOfPoints, const cv::Point3d& centroid)\n{\n  std::vector<cv::Point3d> result;\n\n  for (unsigned int i = 0; i < listOfPoints.size(); ++i)\n  {\n    cv::Point3d c;\n\n    c.x = listOfPoints[i].x - centroid.x;\n    c.y = listOfPoints[i].y - centroid.y;\n    c.z = listOfPoints[i].z - centroid.z;\n\n    result.push_back(c);\n  }\n\n return result;\n}\n\n\n//-----------------------------------------------------------------------------\nstd::vector<cv::Point3d> PointSetToVector(const mitk::PointSet::Pointer& pointSet ,\n    bool fillMissingIndicesWithNaN )\n{\n  std::vector<cv::Point3d> result;\n\n  mitk::PointSet::DataType* itkPointSet = pointSet->GetPointSet(0);\n  mitk::PointSet::PointsContainer* points = itkPointSet->GetPoints();\n  mitk::PointSet::PointsIterator pIt;\n  mitk::PointSet::PointType point;\n  mitk::PointSet::PointIdentifier iD;\n\n  mitk::PointSet::PointIdentifier myIndex = 0;\n  for (pIt = points->Begin(); pIt != points->End() ; )\n  {\n    iD = pIt->Index();\n    if ( ( ! fillMissingIndicesWithNaN ) || (  iD == myIndex )  )\n    {\n      point = pointSet->GetPoint ( iD );\n      cv::Point3d cvPoint;\n\n      cvPoint.x = point[0];\n      cvPoint.y = point[1];\n      cvPoint.z = point[2];\n      result.push_back(cvPoint);\n      myIndex ++;\n      ++pIt;\n    }\n    else\n    {\n      if ( iD < myIndex )\n      {\n        mitkThrow() << \"PointSetToVector mitk point set Id is less than vector index, I cannot handle this list. Try reordering your mps file so point ID's are in acscending order\";\n      }\n      else\n      {\n        while ( myIndex < iD )\n        {\n          MITK_INFO << \"Adding dummy point to world vector with ID \" << myIndex;\n          cv::Point3d cvPoint;\n          cvPoint.x = std::numeric_limits<double>::quiet_NaN();\n          cvPoint.y = std::numeric_limits<double>::quiet_NaN();\n          cvPoint.z = std::numeric_limits<double>::quiet_NaN();\n          result.push_back(cvPoint);\n          myIndex ++;\n        }\n      }\n    }\n  }\n\n  return result;\n}\n\n\n//-----------------------------------------------------------------------------\nvoid MakeIdentity(cv::Matx44d& outputMatrix)\n{\n  outputMatrix = cv::Matx44d::eye();\n}\n\n\n//-----------------------------------------------------------------------------\ncv::Matx33d CalculateCrossCovarianceH(\n    const std::vector<cv::Point3d>& q,\n    const std::vector<cv::Point3d>& qPrime)\n{\n  cv::Matx33d result = cv::Matx33d::zeros();\n\n  for (unsigned int i = 0; i < q.size(); ++i)\n  {\n    cv::Matx33d tmp(\n          q[i].x*qPrime[i].x, q[i].x*qPrime[i].y, q[i].x*qPrime[i].z,\n          q[i].y*qPrime[i].x, q[i].y*qPrime[i].y, q[i].y*qPrime[i].z,\n          q[i].z*qPrime[i].x, q[i].z*qPrime[i].y, q[i].z*qPrime[i].z\n        );\n\n    result += tmp;\n  }\n\n  return result;\n}\n\n\n//-----------------------------------------------------------------------------\nbool DoSVDPointBasedRegistration(const std::vector<cv::Point3d>& fixedPoints,\n                                 const std::vector<cv::Point3d>& movingPoints,\n                                 cv::Matx33d& H,\n                                 cv::Point3d &p,\n                                 cv::Point3d& pPrime,\n                                 cv::Matx44d& outputMatrix,\n                                 double &fiducialRegistrationError)\n{\n  // Based on Arun's method:\n  // Least-Squares Fitting of two, 3-D Point Sets, Arun, 1987,\n  // 10.1109/TPAMI.1987.4767965\n  //\n  // Also See:\n  // http://eecs.vanderbilt.edu/people/mikefitzpatrick/papers/2009_Medim_Fitzpatrick_TRE_FRE_uncorrelated_as_published.pdf\n  // Then:\n  // http://tango.andrew.cmu.edu/~gustavor/42431-intro-bioimaging/readings/ch8.pdf\n\n  bool success = false;\n\n  // Arun Equation 12.\n  cv::SVD svd(H);\n\n  // Arun Equation 13.\n  cv::Mat X = svd.vt.t() * svd.u.t();\n\n  // Replace with Fitzpatrick, chapter 8, page 470.\n  cv::Mat VU = svd.vt.t() * svd.u;\n  double detVU = cv::determinant(VU);\n  cv::Matx33d diag = cv::Matx33d::zeros();\n  diag(0,0) = 1;\n  diag(1,1) = 1;\n  diag(2,2) = detVU;\n  cv::Mat diagonal(diag);\n  X = (svd.vt.t() * (diagonal * svd.u.t()));\n\n  // Arun Step 5.\n\n  double detX = cv::determinant(X);\n  bool haveTriedToFixDeterminantIssue = false;\n\n  if ( detX < 0\n       && (   niftk::IsCloseToZero(svd.w.at<double>(0,0))\n           || niftk::IsCloseToZero(svd.w.at<double>(1,1))\n           || niftk::IsCloseToZero(svd.w.at<double>(2,2))\n          )\n     )\n  {\n    // Implement 2a in section VI in Arun paper.\n\n    cv::Mat VPrime = svd.vt.t();\n    VPrime.at<double>(0,2) = -1.0 * VPrime.at<double>(0,2);\n    VPrime.at<double>(1,2) = -1.0 * VPrime.at<double>(1,2);\n    VPrime.at<double>(2,2) = -1.0 * VPrime.at<double>(2,2);\n\n    X = VPrime * svd.u.t();\n    haveTriedToFixDeterminantIssue = true;\n  }\n\n  if (detX > 0 || haveTriedToFixDeterminantIssue)\n  {\n    // Arun Equation 10.\n    cv::Matx31d T, tmpP, tmpPPrime;\n    cv::Matx33d R(X);\n    tmpP(0,0) = p.x;\n    tmpP(1,0) = p.y;\n    tmpP(2,0) = p.z;\n    tmpPPrime(0,0) = pPrime.x;\n    tmpPPrime(1,0) = pPrime.y;\n    tmpPPrime(2,0) = pPrime.z;\n    T = tmpPPrime - R*tmpP;\n\n    ConstructAffineMatrix(T, R, outputMatrix);\n    fiducialRegistrationError = CalculateFiducialRegistrationError(fixedPoints, movingPoints, outputMatrix);\n\n    success = true;\n  }\n  else\n  {\n    MakeIdentity(outputMatrix);\n  }\n  return success;\n}\n\n\n//-----------------------------------------------------------------------------\ndouble CalculateFiducialRegistrationError(const std::vector<cv::Point3d>& fixedPoints,\n                                          const std::vector<cv::Point3d>& movingPoints,\n                                          const cv::Matx44d& matrix\n                                          )\n{\n  assert(fixedPoints.size() == movingPoints.size());\n\n  unsigned int numberOfPoints = fixedPoints.size();\n  double fiducialRegistrationError = 0;\n\n  for (unsigned int i = 0; i < numberOfPoints; ++i)\n  {\n    cv::Matx41d f, m, mPrime;\n    f(0,0) = fixedPoints[i].x;\n    f(1,0) = fixedPoints[i].y;\n    f(2,0) = fixedPoints[i].z;\n    f(3,0) = 1;\n    m(0,0) = movingPoints[i].x;\n    m(1,0) = movingPoints[i].y;\n    m(2,0) = movingPoints[i].z;\n    m(3,0) = 1;\n    mPrime = matrix * m;\n    double squaredError =   (f(0,0) - mPrime(0,0)) * (f(0,0) - mPrime(0,0))\n                          + (f(1,0) - mPrime(1,0)) * (f(1,0) - mPrime(1,0))\n                          + (f(2,0) - mPrime(2,0)) * (f(2,0) - mPrime(2,0))\n                          ;\n    fiducialRegistrationError += squaredError;\n  }\n  if (numberOfPoints > 0)\n  {\n    fiducialRegistrationError /= (double)numberOfPoints;\n  }\n  fiducialRegistrationError = sqrt(fiducialRegistrationError);\n  return fiducialRegistrationError;\n}\n\n\n//-----------------------------------------------------------------------------\ndouble CalculateFiducialRegistrationError(const mitk::PointSet::Pointer& fixedPointSet,\n                                          const mitk::PointSet::Pointer& movingPointSet,\n                                          vtkMatrix4x4& vtkMatrix)\n{\n  std::vector<cv::Point3d> fixedPoints = PointSetToVector(fixedPointSet);\n  std::vector<cv::Point3d> movingPoints = PointSetToVector(movingPointSet);\n  cv::Matx44d matrix;\n  CopyToOpenCVMatrix(vtkMatrix, matrix);\n\n  double fiducialRegistrationError = CalculateFiducialRegistrationError(fixedPoints, movingPoints, matrix);\n  return fiducialRegistrationError;\n}\n\n\n//-----------------------------------------------------------------------------\nvoid ConstructAffineMatrix(const cv::Matx31d& translation, const cv::Matx33d& rotation, cv::Matx44d& matrix)\n{\n  for (unsigned int i = 0; i < 3; ++i)\n  {\n    for (unsigned int j = 0; j < 3; ++j)\n    {\n      matrix(i,j) = rotation(i,j);\n    }\n    matrix(i, 3) = translation(i, 0);\n  }\n  matrix(3,0) = 0;\n  matrix(3,1) = 0;\n  matrix(3,2) = 0;\n  matrix(3,3) = 1;\n}\n\n\n//-----------------------------------------------------------------------------\nvoid CopyToVTK4x4Matrix(const cv::Matx44d& matrix, vtkMatrix4x4& vtkMatrix)\n{\n  for (unsigned int i = 0; i < 4; ++i)\n  {\n    for (unsigned int j = 0; j < 4; ++j)\n    {\n      vtkMatrix.SetElement(i, j, matrix(i,j));\n    }\n  }\n}\n\n\n//-----------------------------------------------------------------------------\nvoid CopyToOpenCVMatrix(const vtkMatrix4x4& matrix, cv::Matx44d& openCVMatrix)\n{\n  for (unsigned int i = 0; i < 4; ++i)\n  {\n    for (unsigned int j = 0; j < 4; ++j)\n    {\n      openCVMatrix(i, j) = matrix.GetElement(i, j);\n    }\n  }\n}\n\n\n//-----------------------------------------------------------------------------\nvoid CopyToVTK4x4Matrix(const cv::Mat& input, vtkMatrix4x4& output)\n{\n  if (input.rows != 4)\n  {\n    mitkThrow() << \"Input matrix does not have 4 rows.\" << std::endl;\n  }\n  if (input.cols != 4)\n  {\n    mitkThrow() << \"Input matrix does not have 4 columns.\" << std::endl;\n  }\n\n  for (unsigned int i = 0; i < 4; ++i)\n  {\n    for (unsigned int j = 0; j < 4; ++j)\n    {\n      output.SetElement(i, j, input.at<double>(i,j));\n    }\n  }\n}\n\n\n//-----------------------------------------------------------------------------\nvoid CopyToOpenCVMatrix(const vtkMatrix4x4& input, cv::Mat& output)\n{\n  if (output.rows != 4)\n  {\n    mitkThrow() << \"Output matrix does not have 4 rows.\" << std::endl;\n  }\n  if (output.cols != 4)\n  {\n    mitkThrow() << \"Output matrix does not have 4 columns.\" << std::endl;\n  }\n\n  for (unsigned int i = 0; i < 4; ++i)\n  {\n    for (unsigned int j = 0; j < 4; ++j)\n    {\n      output.at<double>(i,j) = input.GetElement(i,j);\n    }\n  }\n}\n\n\n//-----------------------------------------------------------------------------\nvoid CopyToOpenCVMatrix(const cv::Matx44d& input, cv::Mat& output)\n{\n  if (output.rows != 4)\n  {\n    mitkThrow() << \"Output matrix does not have 4 rows.\" << std::endl;\n  }\n  if (output.cols != 4)\n  {\n    mitkThrow() << \"Output matrix does not have 4 columns.\" << std::endl;\n  }\n\n  for (unsigned int i = 0; i < 4; ++i)\n  {\n    for (unsigned int j = 0; j < 4; ++j)\n    {\n      output.at<double>(i,j) = input(i,j);\n    }\n  }\n}\n\n\n//-----------------------------------------------------------------------------\nstd::vector < mitk::WorldPoint > operator*(const cv::Mat& M, const std::vector< mitk::WorldPoint > & p)\n{\n  cv::Mat src ( 4, p.size(), CV_64F );\n  for ( unsigned int i = 0 ; i < p.size() ; i ++ )\n  {\n    src.at<double>(0,i) = p[i].m_Point.x;\n    src.at<double>(1,i) = p[i].m_Point.y;\n    src.at<double>(2,i) = p[i].m_Point.z;\n    src.at<double>(3,i) = 1.0;\n  }\n  cv::Mat dst = M*src;\n  std::vector < mitk::WorldPoint > returnPoints;\n  for ( unsigned int i = 0 ; i < p.size() ; i ++ )\n  {\n    cv::Point3d point;\n    point.x = dst.at<double>(0,i) / dst.at<double>(3,i);\n    point.y = dst.at<double>(1,i) / dst.at<double>(3,i);\n    point.z = dst.at<double>(2,i) / dst.at<double>(3,i);\n    returnPoints.push_back(mitk::WorldPoint (point, p[i].m_Scalar));\n  }\n  return returnPoints;\n}\n\n\n//-----------------------------------------------------------------------------\nstd::vector<mitk::WorldPoint> operator*(const cv::Matx44d& M, const std::vector<mitk::WorldPoint>& p)\n{\n  return operator*(cv::Mat(4, 4, CV_64F, (void*) &M.val[0]), p);\n}\n\n\n//-----------------------------------------------------------------------------\nmitk::WorldPoint  operator*(const cv::Mat& M, const  mitk::WorldPoint & p)\n{\n  cv::Mat src ( 4, 1 , CV_64F );\n  src.at<double>(0,0) = p.m_Point.x;\n  src.at<double>(1,0) = p.m_Point.y;\n  src.at<double>(2,0) = p.m_Point.z;\n  src.at<double>(3,0) = 1.0;\n\n  cv::Mat dst = M*src;\n  mitk::WorldPoint  returnPoint;\n\n  cv::Point3d point;\n  point.x = dst.at<double>(0,0) / dst.at<double>(3, 0);\n  point.y = dst.at<double>(1,0) / dst.at<double>(3, 0);\n  point.z = dst.at<double>(2,0) / dst.at<double>(3, 0);\n  returnPoint = mitk::WorldPoint (point, p.m_Scalar);\n\n  return returnPoint;\n}\n\n\n//-----------------------------------------------------------------------------\nmitk::WorldPoint  operator*(const cv::Matx44d& M, const mitk::WorldPoint& p)\n{\n  return operator*(cv::Mat(4, 4, CV_64F, (void*) &M.val[0]), p);\n}\n\n\n//-----------------------------------------------------------------------------\nstd::vector <cv::Point3d> operator*(const cv::Mat& M, const std::vector<cv::Point3d>& p)\n{\n  cv::Mat src ( 4, p.size(), CV_64F );\n  for ( unsigned int i = 0 ; i < p.size() ; i ++ )\n  {\n    src.at<double>(0,i) = p[i].x;\n    src.at<double>(1,i) = p[i].y;\n    src.at<double>(2,i) = p[i].z;\n    src.at<double>(3,i) = 1.0;\n  }\n  cv::Mat dst = M*src;\n  std::vector <cv::Point3d> returnPoints;\n  for ( unsigned int i = 0 ; i < p.size() ; i ++ )\n  {\n    cv::Point3d point;\n    point.x = dst.at<double>(0,i) / dst.at<double>(3, i);\n    point.y = dst.at<double>(1,i) / dst.at<double>(3, i);\n    point.z = dst.at<double>(2,i) / dst.at<double>(3, i);\n    returnPoints.push_back(point);\n  }\n  return returnPoints;\n}\n\n\n//-----------------------------------------------------------------------------\nstd::vector <cv::Point3d> operator*(const cv::Matx44d& M, const std::vector<cv::Point3d>& p)\n{\n  return operator*(cv::Mat(4, 4, CV_64F, (void*) &M.val[0]), p);\n}\n\n\n//-----------------------------------------------------------------------------\ncv::Point3d operator*(const cv::Mat& M, const cv::Point3d& p)\n{\n  cv::Mat src ( 4, 1, CV_64F );\n  src.at<double>(0,0) = p.x;\n  src.at<double>(1,0) = p.y;\n  src.at<double>(2,0) = p.z;\n  src.at<double>(3,0) = 1.0;\n\n  cv::Mat dst = M*src;\n  cv::Point3d returnPoint;\n\n  returnPoint.x = dst.at<double>(0,0) / dst.at<double>(3, 0);\n  returnPoint.y = dst.at<double>(1,0) / dst.at<double>(3, 0);\n  returnPoint.z = dst.at<double>(2,0) / dst.at<double>(3, 0);\n\n  return returnPoint;\n}\n\n\n//-----------------------------------------------------------------------------\ncv::Point3d operator*(const cv::Matx44d& M, const cv::Point3d& p)\n{\n  return operator*(cv::Mat(4, 4, CV_64F, (void*) &M.val[0]), p);\n}\n\n//-----------------------------------------------------------------------------\nstd::pair < cv::Point3d , cv::Point3d > TransformPointPair(const cv::Matx44d& M, const std::pair < cv::Point3d, cv::Point3d >& p)\n{\n  return std::pair < cv::Point3d, cv::Point3d > ( M * p.first, M*p.second );\n}\n\n\n//-----------------------------------------------------------------------------\nbool NearlyEqual(const cv::Point2d& p1, const cv::Point2d& p2, const double& tolerance )\n{\n  if ( fabs(( ( p1.x - p2.x ) + ( p2.y - p2.y ) )) < tolerance )\n  {\n    return true;\n  }\n  else\n  {\n    return false;\n  }\n}\n\n//-----------------------------------------------------------------------------\nbool NearlyEqual(const cv::Point3d& p1, const cv::Point3d& p2, const double& tolerance )\n{\n  if ( fabs(( ( p1.x - p2.x ) + ( p2.y - p2.y ) + ( p1.z - p2.z ) )) < tolerance )\n  {\n    return true;\n  }\n  else\n  {\n    return false;\n  }\n}\n\n//-----------------------------------------------------------------------------\nbool ImageHeadersEqual ( const cv::Mat& m1 , const cv::Mat& m2 )\n{\n  bool equal = true;\n  if ( ! ( m1.type() == m2.type() ) )\n  {\n    equal = false;\n  }\n\n  if ( !( ( m1.rows == m2.rows ) && (m1.cols == m2.cols )  ) )\n  {\n    equal = false;\n  }\n  return equal;\n}\n\n//-----------------------------------------------------------------------------\nbool ImageDataEqual ( const cv::Mat& m1 , const cv::Mat& m2 , const double& tolerance)\n{\n  bool equal = ImageHeadersEqual (m1, m2 );\n\n  if ( ! equal )\n  {\n    MITK_WARN << \"Attempted to compare data in matrices of different types or sizes\";\n    return equal;\n  }\n\n  double error = 0 ;\n  for ( unsigned int i = 0 ; i < m1.rows ; i ++ )\n  {\n    for ( unsigned int j = 0 ; j < m1.cols ; j ++ )\n    {\n      for ( unsigned int channel = 0 ; channel < m1.channels() ; channel++ )\n      {\n        switch ( m1.depth() )\n        {\n          case  CV_8U:\n          {\n            error += static_cast<double>(m1.ptr<unsigned char> (i,j)[channel]) - static_cast<double>(m2.ptr<unsigned char> (i,j)[channel]) ;\n            break;\n          }\n          case CV_8S:\n          {\n            error += static_cast<double>(m1.ptr<char> (i,j)[channel]) - static_cast<double>(m2.ptr<char> (i,j)[channel]) ;\n            break;\n          }\n          case CV_16U:\n          {\n            error += static_cast<double>(m1.ptr<unsigned int> (i,j)[channel]) - static_cast<double>(m2.ptr<unsigned int> (i,j)[channel]) ;\n            break;\n          }\n          case CV_16S:\n          {\n            error += static_cast<double>(m1.ptr<int> (i,j)[channel]) - static_cast<double>(m2.ptr<int> (i,j)[channel]) ;\n            break;\n          }\n          case CV_32S:\n          {\n            error += static_cast<double>(m1.ptr<long int> (i,j)[channel]) - static_cast<double>(m2.ptr<long int> (i,j)[channel]) ;\n            break;\n          }\n          case CV_32F:\n          {\n            error += static_cast<double>(m1.ptr<float> (i,j)[channel]) - static_cast<double>(m2.ptr<float> (i,j)[channel]) ;\n            break;\n          }\n          case CV_64F:\n          {\n            error += static_cast<double>(m1.ptr<double> (i,j)[channel]) - static_cast<double>(m2.ptr<double> (i,j)[channel]) ;\n            break;\n          }\n          default:\n          {\n            MITK_WARN << \"Called compare data in matrices of unknown depth \" << m1.depth();\n            equal = false;\n            return equal;\n          }\n        }\n      }\n    }\n  }\n  if ( error > tolerance )\n  {\n    equal = false;\n  }\n  return equal;\n}\n\n\n//-----------------------------------------------------------------------------\ncv::Point2d operator/(const cv::Point2d& p1, const int& n)\n{\n  return cv::Point2d ( p1.x / static_cast<double>(n) , p1.y / static_cast<double>(n) );\n}\n\n//-----------------------------------------------------------------------------\ncv::Point2d operator*(const cv::Point2d& p1, const cv::Point2d& p2)\n{\n  return cv::Point2d ( p1.x * p2.x , p1.y * p2.y );\n}\n\n//-----------------------------------------------------------------------------\ncv::Point2d FindIntersect (const cv::Vec4i& line1, const cv::Vec4i& line2 )\n{\n  double a1;\n  double a2;\n  double b1;\n  double b2;\n  cv::Point2d returnPoint;\n  returnPoint.x = std::numeric_limits<double>::quiet_NaN();\n  returnPoint.y = std::numeric_limits<double>::quiet_NaN();\n\n  if ( ! ( fabs ( mitk::AngleBetweenLines(line1,line2) ) > 1e-6 ) )\n  {\n    return returnPoint;\n  }\n  if ( ( line1[2] == line1[0] )  || ( line2[2] == line2[0] )  )\n  {\n    if ( line1[2] == line1[0] )\n    {\n      //line1 is vertical so substitute x = line1[0] into equation for line2\n      a2 =( static_cast<double>(line2[3]) - static_cast<double>(line2[1]) ) /\n              ( static_cast<double>(line2[2]) - static_cast<double>(line2[0]) );\n      b2 = static_cast<double>(line2[1]) - a2 * static_cast<double>(line2[0]);\n      returnPoint.x = line1[0];\n      returnPoint.y = a2 * returnPoint.x + b2;\n    }\n    else\n    {\n      //line2 is vertical so substitute x = line2[0] into equation for line1\n      a1 =( static_cast<double>(line1[3]) - static_cast<double>(line1[1]) ) /\n              ( static_cast<double>(line1[2]) - static_cast<double>(line1[0]) );\n      b1 = static_cast<double>(line1[1]) - a1 * static_cast<double>(line1[0]);\n      returnPoint.x = line2[0];\n      returnPoint.y = a1 * returnPoint.x + b1;\n    }\n  }\n  else\n  {\n    a1 =( static_cast<double>(line1[3]) - static_cast<double>(line1[1]) ) /\n      ( static_cast<double>(line1[2]) - static_cast<double>(line1[0]) );\n    a2 =( static_cast<double>(line2[3]) - static_cast<double>(line2[1]) ) /\n      ( static_cast<double>(line2[2]) - static_cast<double>(line2[0]) );\n    b1 = static_cast<double>(line1[1]) - a1 * static_cast<double>(line1[0]);\n    b2 = static_cast<double>(line2[1]) - a2 * static_cast<double>(line2[0]);\n    returnPoint.x = ( b2 - b1 )/(a1 - a2 );\n    returnPoint.y = a1 * returnPoint.x + b1;\n  }\n\n  return returnPoint;\n}\n\n//-----------------------------------------------------------------------------\nbool PointInInterval ( const cv::Point2d& point , const cv::Vec4i& interval )\n{\n  if ( (((point.x >= static_cast<double>(interval[2])) && (point.x <= static_cast<double>(interval[0]))) ||\n    ((point.x >= static_cast<double>(interval[0])) && (point.x <= static_cast<double>(interval[2]))))  &&\n    (((point.y >= static_cast<double>(interval[3])) && (point.y <= static_cast<double>(interval[1]))) ||\n    ((point.y >= static_cast<double>(interval[1])) && (point.y <= static_cast<double>(interval[3])))) )\n  {\n    return true;\n  }\n  else\n  {\n    return false;\n  }\n}\n//-----------------------------------------------------------------------------\nbool CheckIfLinesArePerpendicular ( cv::Vec4i line1, cv::Vec4i line2 , double tolerance )\n{\n  if ( fabs ( mitk::AngleBetweenLines ( line1, line2 ) - (CV_PI/2.0) ) <= (tolerance * CV_PI/180.0) )\n  {\n    return true;\n  }\n  else\n  {\n    return false;\n  }\n}\n\n//-----------------------------------------------------------------------------\ndouble AngleBetweenLines ( cv::Vec4i line1, cv::Vec4i line2 )\n{\n  double u1 = static_cast<double>(line1[2]) - static_cast<double>(line1[0]);\n  double u2 = static_cast<double>(line1[3]) - static_cast<double>(line1[1]);\n  double v1 = static_cast<double>(line2[2]) - static_cast<double>(line2[0]);\n  double v2 = static_cast<double>(line2[3]) - static_cast<double>(line2[1]);\n\n  double cosAngle = fabs ( u1 * v1 + u2 * v2 ) /\n    ( (sqrt( u1*u1 + u2*u2)) * (sqrt( v1*v1 + v2*v2 )) );\n  return acos (cosAngle);\n}\n\n\n//-----------------------------------------------------------------------------\nstd::vector <cv::Point2d> FindIntersects (const std::vector <cv::Vec4i>& lines  , const bool& rejectIfPointNotOnBothLines,\n    const bool& rejectIfNotPerpendicular, const double& angleTolerance)\n{\n  std::vector<cv::Point2d> returnPoints;\n  if ( lines.size () < 2 )\n  {\n    MITK_WARN << \"Called FindIntersects with only \" << lines.size() << \" lines\";\n    return returnPoints;\n  }\n  for ( unsigned int i = 0 ; i < lines.size() - 1 ; i ++ )\n  {\n    for ( unsigned int j = i + 1 ; j < lines.size() ; j ++ )\n    {\n      if ( (!rejectIfNotPerpendicular) || CheckIfLinesArePerpendicular( lines[i], lines[j] , angleTolerance) )\n      {\n        cv::Point2d point =  FindIntersect (lines[i], lines[j]);\n        if (  (! rejectIfPointNotOnBothLines) ||\n          ( (mitk::PointInInterval ( point, lines[i] ) ) && ( PointInInterval ( point , lines[j] ) ) ) )\n        {\n          if ( ! ( boost::math::isnan(point.x) || boost::math::isnan(point.y) ) )\n          {\n            returnPoints.push_back ( point ) ;\n          }\n        }\n      }\n    }\n  }\n  return returnPoints;\n}\n\n\n//-----------------------------------------------------------------------------\ncv::Point2d GetCentroid(const std::vector<cv::Point2d>& points, bool RefineForOutliers,\n    cv::Point2d * StandardDeviation)\n{\n  cv::Point2d centroid;\n  centroid.x = 0.0;\n  centroid.y = 0.0;\n\n  unsigned int  numberOfPoints = points.size();\n\n  unsigned int goodPoints = 0;\n\n  for (unsigned int i = 0; i < numberOfPoints; ++i)\n  {\n    if ( ! ( boost::math::isnan(points[i].x) || boost::math::isnan(points[i].y) ) )\n    {\n      centroid.x += points[i].x;\n      centroid.y += points[i].y;\n      goodPoints++;\n    }\n  }\n\n  centroid.x /= (double) goodPoints;\n  centroid.y /= (double) goodPoints;\n  if ( ( ! RefineForOutliers ) && ( StandardDeviation == NULL ) )\n  {\n    return centroid;\n  }\n\n  cv::Point2d standardDeviation;\n  standardDeviation.x = 0.0;\n  standardDeviation.y = 0.0;\n\n  goodPoints = 0;\n  for (unsigned int i = 0; i < numberOfPoints ; ++i )\n  {\n    if ( ! ( boost::math::isnan(points[i].x) || boost::math::isnan(points[i].y) ) )\n    {\n      standardDeviation.x += ( points[i].x - centroid.x ) * (points[i].x - centroid.x);\n      standardDeviation.y += ( points[i].y - centroid.y ) * (points[i].y - centroid.y);\n      goodPoints++;\n    }\n  }\n  standardDeviation.x = sqrt ( standardDeviation.x/ (double) goodPoints ) ;\n  standardDeviation.y = sqrt ( standardDeviation.y/ (double) goodPoints ) ;\n\n  if ( ! RefineForOutliers )\n  {\n    *StandardDeviation = standardDeviation;\n    return centroid;\n  }\n\n  cv::Point2d highLimit (centroid.x + 2 * standardDeviation.x , centroid.y + 2 * standardDeviation.y);\n  cv::Point2d lowLimit (centroid.x - 2 * standardDeviation.x , centroid.y - 2 * standardDeviation.y);\n\n  centroid.x = 0.0;\n  centroid.y = 0.0;\n  goodPoints = 0 ;\n  for (unsigned int i = 0; i < numberOfPoints; ++i)\n  {\n    if ( ( points[i].x <= highLimit.x ) && ( points[i].x >= lowLimit.x ) &&\n         ( points[i].y <= highLimit.y ) && ( points[i].y >= lowLimit.y ) )\n    {\n      centroid.x += points[i].x;\n      centroid.y += points[i].y;\n      goodPoints++;\n    }\n  }\n\n  centroid.x /= (double) goodPoints;\n  centroid.y /= (double) goodPoints;\n\n  if ( StandardDeviation == NULL )\n  {\n    return centroid;\n  }\n  standardDeviation.x = 0.0;\n  standardDeviation.y = 0.0;\n  goodPoints = 0 ;\n  for (unsigned int i = 0; i < numberOfPoints ; ++i )\n  {\n    if ( ( ! ( boost::math::isnan(points[i].x) || boost::math::isnan(points[i].y) ) ) &&\n        ( points[i].x <= highLimit.x ) && ( points[i].x >= lowLimit.x ) &&\n         ( points[i].y <= highLimit.y ) && ( points[i].y >= lowLimit.y ) )\n    {\n      standardDeviation.x += ( points[i].x - centroid.x ) * (points[i].x - centroid.x);\n      standardDeviation.y += ( points[i].y - centroid.y ) * (points[i].y - centroid.y);\n      goodPoints++;\n    }\n  }\n  standardDeviation.x = sqrt ( standardDeviation.x/ (double) goodPoints ) ;\n  standardDeviation.y = sqrt ( standardDeviation.y/ (double) goodPoints ) ;\n\n  *StandardDeviation = standardDeviation;\n  return centroid;\n}\n\n\n//-----------------------------------------------------------------------------\ncv::Point3d GetCentroid(const std::vector<cv::Point3d>& points, bool RefineForOutliers , cv::Point3d* StandardDeviation)\n{\n  cv::Point3d centroid;\n  centroid.x = 0.0;\n  centroid.y = 0.0;\n  centroid.z = 0.0;\n\n  unsigned int  numberOfPoints = points.size();\n\n  unsigned int goodPoints = 0 ;\n  for (unsigned int i = 0; i < numberOfPoints; ++i)\n  {\n\n    if ( ! ( boost::math::isnan(points[i].x) || boost::math::isnan(points[i].y) || boost::math::isnan(points[i].z) ) )\n    {\n      centroid.x += points[i].x;\n      centroid.y += points[i].y;\n      centroid.z += points[i].z;\n      goodPoints++;\n    }\n  }\n\n  centroid.x /= (double) goodPoints;\n  centroid.y /= (double) goodPoints;\n  centroid.z /= (double) goodPoints;\n\n  if ( ! RefineForOutliers  && StandardDeviation == NULL)\n  {\n    return centroid;\n  }\n\n  cv::Point3d standardDeviation;\n  standardDeviation.x = 0.0;\n  standardDeviation.y = 0.0;\n  standardDeviation.z = 0.0;\n\n  goodPoints = 0;\n  for (unsigned int i = 0; i < numberOfPoints ; ++i )\n  {\n    if ( ! ( boost::math::isnan(points[i].x) || boost::math::isnan(points[i].y) || boost::math::isnan(points[i].z) ) )\n    {\n      standardDeviation.x += ( points[i].x - centroid.x ) * (points[i].x - centroid.x);\n      standardDeviation.y += ( points[i].y - centroid.y ) * (points[i].y - centroid.y);\n      standardDeviation.z += ( points[i].z - centroid.z ) * (points[i].z - centroid.z);\n      goodPoints++;\n    }\n  }\n  standardDeviation.x = sqrt ( standardDeviation.x/ (double) goodPoints ) ;\n  standardDeviation.y = sqrt ( standardDeviation.y/ (double) goodPoints ) ;\n  standardDeviation.z = sqrt ( standardDeviation.z/ (double) goodPoints ) ;\n\n  if ( ! RefineForOutliers )\n  {\n    *StandardDeviation = standardDeviation;\n    return centroid;\n  }\n  cv::Point3d highLimit (centroid.x + 2 * standardDeviation.x ,\n      centroid.y + 2 * standardDeviation.y, centroid.z + standardDeviation.z);\n  cv::Point3d lowLimit (centroid.x - 2 * standardDeviation.x ,\n      centroid.y - 2 * standardDeviation.y, centroid.z - standardDeviation.z);\n\n  centroid.x = 0.0;\n  centroid.y = 0.0;\n  centroid.z = 0.0;\n  goodPoints = 0 ;\n  for (unsigned int i = 0; i < numberOfPoints; ++i)\n  {\n    if ( ( ! ( boost::math::isnan(points[i].x) || boost::math::isnan(points[i].y) || boost::math::isnan(points[i].z) ) ) &&\n         ( points[i].x <= highLimit.x ) && ( points[i].x >= lowLimit.x ) &&\n         ( points[i].y <= highLimit.y ) && ( points[i].y >= lowLimit.y ) &&\n         ( points[i].z <= highLimit.z ) && ( points[i].z >= lowLimit.z ))\n    {\n      centroid.x += points[i].x;\n      centroid.y += points[i].y;\n      centroid.z += points[i].z;\n      goodPoints++;\n    }\n  }\n\n  centroid.x /= (double) goodPoints;\n  centroid.y /= (double) goodPoints;\n  centroid.z /= (double) goodPoints;\n\n  if ( StandardDeviation == NULL )\n  {\n    return centroid;\n  }\n  goodPoints = 0 ;\n  standardDeviation.x = 0.0;\n  standardDeviation.y = 0.0;\n  standardDeviation.z = 0.0;\n\n  for (unsigned int i = 0; i < numberOfPoints ; ++i )\n  {\n    if ( ( ! ( boost::math::isnan(points[i].x) || boost::math::isnan(points[i].y) || boost::math::isnan(points[i].z) ) ) &&\n         ( points[i].x <= highLimit.x ) && ( points[i].x >= lowLimit.x ) &&\n         ( points[i].y <= highLimit.y ) && ( points[i].y >= lowLimit.y ) &&\n         ( points[i].z <= highLimit.z ) && ( points[i].z >= lowLimit.z ))\n    {\n      standardDeviation.x += ( points[i].x - centroid.x ) * (points[i].x - centroid.x);\n      standardDeviation.y += ( points[i].y - centroid.y ) * (points[i].y - centroid.y);\n      standardDeviation.z += ( points[i].z - centroid.z ) * (points[i].z - centroid.z);\n      goodPoints++;\n    }\n  }\n  standardDeviation.x = sqrt ( standardDeviation.x/ (double) goodPoints ) ;\n  standardDeviation.y = sqrt ( standardDeviation.y/ (double) goodPoints ) ;\n  standardDeviation.z = sqrt ( standardDeviation.z/ (double) goodPoints ) ;\n  *StandardDeviation = standardDeviation;\n  return centroid;\n}\n\n\n//-----------------------------------------------------------------------------\ncv::Matx33d ConstructEulerRxMatrix(const double& rx)\n{\n  cv::Matx33d result;\n\n  double cosRx = cos(rx);\n  double sinRx = sin(rx);\n\n  result = result.eye();\n  result(1, 1) = cosRx;\n  result(1, 2) = sinRx;\n  result(2, 1) = -sinRx;\n  result(2, 2) = cosRx;\n  result(0, 0) = 1;\n\n  return result;\n}\n\n\n//-----------------------------------------------------------------------------\ncv::Matx33d ConstructEulerRyMatrix(const double& ry)\n{\n  cv::Matx33d result;\n\n  double cosRy = cos(ry);\n  double sinRy = sin(ry);\n\n  result = result.eye();\n  result(0, 0) = cosRy;\n  result(0, 2) = -sinRy;\n  result(2, 0) = sinRy;\n  result(2, 2) = cosRy;\n  result(1, 1) = 1;\n\n  return result;\n}\n\n\n//-----------------------------------------------------------------------------\ncv::Matx33d ConstructEulerRzMatrix(const double& rz)\n{\n  cv::Matx33d result;\n\n  double cosRz = cos(rz);\n  double sinRz = sin(rz);\n\n  result = result.eye();\n  result(0, 0) = cosRz;\n  result(0, 1) = sinRz;\n  result(1, 0) = -sinRz;\n  result(1, 1) = cosRz;\n  result(2, 2) = 1;\n\n  return result;\n}\n\n\n//-----------------------------------------------------------------------------\ncv::Matx33d ConstructEulerRotationMatrix(const double& rx, const double& ry, const double& rz)\n{\n  cv::Matx33d result;\n\n  cv::Matx33d rotationAboutX = ConstructEulerRxMatrix(rx);\n  cv::Matx33d rotationAboutY = ConstructEulerRyMatrix(ry);\n  cv::Matx33d rotationAboutZ = ConstructEulerRzMatrix(rz);\n\n  result = (rotationAboutZ * (rotationAboutY * rotationAboutX));\n  return result;\n}\n\n\n//-----------------------------------------------------------------------------\ncv::Matx13d ConvertEulerToRodrigues(\n    const double& rx,\n    const double& ry,\n    const double& rz\n    )\n{\n  cv::Matx13d rotationVector;\n\n  cv::Matx33d rotationMatrix = ConstructEulerRotationMatrix(rx, ry, rz);\n  cv::Rodrigues(rotationMatrix, rotationVector);\n\n  return rotationVector;\n}\n\n\n//-----------------------------------------------------------------------------\ncv::Matx44d ConstructRigidTransformationMatrix(\n    const double& rx,\n    const double& ry,\n    const double& rz,\n    const double& tx,\n    const double& ty,\n    const double& tz\n    )\n{\n  cv::Matx44d transformation;\n  mitk::MakeIdentity(transformation);\n\n  cv::Matx33d rotationMatrix = ConstructEulerRotationMatrix(rx, ry, rz);\n\n  for (int i = 0; i < 3; i++)\n  {\n    for (int j = 0; j < 3; j++)\n    {\n      transformation(i, j) = rotationMatrix(i, j);\n    }\n  }\n  transformation(0, 3) = tx;\n  transformation(1, 3) = ty;\n  transformation(2, 3) = tz;\n\n  return transformation;\n}\n\n\n//-----------------------------------------------------------------------------\ncv::Matx44d ConstructRodriguesTransformationMatrix(\n    const double& r1,\n    const double& r2,\n    const double& r3,\n    const double& tx,\n    const double& ty,\n    const double& tz\n    )\n{\n  cv::Matx44d transformation;\n  mitk::MakeIdentity(transformation);\n\n  cv::Matx13d rotationVector;\n  rotationVector(0,0) = r1;\n  rotationVector(0,1) = r2;\n  rotationVector(0,2) = r3;\n\n  cv::Matx33d rotationMatrix;\n  cv::Rodrigues(rotationVector, rotationMatrix);\n\n  for (int i = 0; i < 3; i++)\n  {\n    for (int j = 0; j < 3; j++)\n    {\n      transformation(i, j) = rotationMatrix(i, j);\n    }\n  }\n  transformation(0, 3) = tx;\n  transformation(1, 3) = ty;\n  transformation(2, 3) = tz;\n\n  return transformation;\n}\n\n\n//-----------------------------------------------------------------------------\ncv::Matx44d ConstructScalingTransformation(const double& sx, const double& sy, const double& sz)\n{\n  cv::Matx44d scaling;\n  mitk::MakeIdentity(scaling);\n\n  scaling(0,0) = sx;\n  scaling(1,1) = sy;\n  scaling(2,2) = sz;\n\n  return scaling;\n}\n\n\n//-----------------------------------------------------------------------------\ncv::Matx44d ConstructSimilarityTransformationMatrix(\n    const double& rx,\n    const double& ry,\n    const double& rz,\n    const double& tx,\n    const double& ty,\n    const double& tz,\n    const double& sx,\n    const double& sy,\n    const double& sz\n    )\n{\n  cv::Matx44d scaling;\n  cv::Matx44d rigid;\n  cv::Matx44d result;\n\n  rigid = ConstructRigidTransformationMatrix(rx, ry, rz, tx, ty, tz);\n  scaling = ConstructScalingTransformation(sx, sy, sz);\n\n  result = scaling * rigid;\n  return result;\n}\n\n\n//-----------------------------------------------------------------------------\ncv::Point3d FindMinimumValues ( std::vector < cv::Point3d > inputValues, cv::Point3i * indexes )\n{\n  cv::Point3d minimumValues;\n\n  if ( inputValues.size() > 0 )\n  {\n    minimumValues.x = inputValues[0].x;\n    minimumValues.y = inputValues[0].y;\n    minimumValues.z = inputValues[0].z;\n\n    if ( indexes != NULL )\n    {\n      indexes->x = 0;\n      indexes->y = 0;\n      indexes->z = 0;\n    }\n  }\n  for ( unsigned int i = 0 ; i < inputValues.size() ; i ++ )\n  {\n    std::cerr << i << std::endl;\n    if ( inputValues[i].x < minimumValues.x )\n    {\n      minimumValues.x = inputValues[i].x;\n      if ( indexes != NULL )\n      {\n        indexes->x = i;\n      }\n    }\n    if ( inputValues[i].y < minimumValues.y )\n    {\n      minimumValues.y = inputValues[i].y;\n      if ( indexes != NULL )\n      {\n        indexes->y = i;\n      }\n    }\n    if ( inputValues[i].z < minimumValues.z )\n    {\n      minimumValues.z = inputValues[i].z;\n      if ( indexes != NULL )\n      {\n        indexes->z = i;\n      }\n    }\n\n  }\n  return minimumValues;\n}\n\n//-----------------------------------------------------------------------------\nstd::pair < double, double >  RMSError (\n    std::vector < mitk::ProjectedPointPairsWithTimingError >  measured ,\n    std::vector < mitk::ProjectedPointPairsWithTimingError > actual ,\n    int indexToUse , cv::Point2d outlierSD, long long allowableTimingError,\n    bool duplicateLines )\n{\n  assert ( measured.size() == actual.size() );\n\n  std::pair < double, double>  RMSError;\n\n  RMSError.first = 0.0 ;\n  RMSError.second = 0.0 ;\n\n  mitk::ProjectedPointPair errorStandardDeviations;\n  mitk::ProjectedPointPair  errorMeans;\n  errorMeans = mitk::MeanError (measured, actual, &errorStandardDeviations,\n      indexToUse, allowableTimingError);\n  mitk::ProjectedPointPair lowLimit;\n  mitk::ProjectedPointPair highLimit;\n  lowLimit.m_Left = errorMeans.m_Left - (outlierSD * errorStandardDeviations.m_Left);\n  lowLimit.m_Right = errorMeans.m_Right - (outlierSD * errorStandardDeviations.m_Right);\n  highLimit.m_Left = errorMeans.m_Left + (outlierSD * errorStandardDeviations.m_Left);\n  highLimit.m_Right = errorMeans.m_Right + (outlierSD * errorStandardDeviations.m_Right);\n\n  std::pair < int , int > count;\n  count.first = 0;\n  count.second = 0;\n  int lowIndex = 0;\n  int highIndex = measured[0].m_Points.size();\n  if ( indexToUse != -1 )\n  {\n    lowIndex = indexToUse;\n    highIndex = indexToUse;\n  }\n  for ( int index = lowIndex; index < highIndex ; index ++ )\n  {\n    unsigned int increment=1;\n    if ( duplicateLines )\n    {\n      increment = 2;\n    }\n    for ( unsigned int frame = 0 ; frame < actual.size() ; frame += increment )\n    {\n      if ( measured[frame].m_TimingError < std::abs (allowableTimingError) )\n      {\n        if ( ! ( measured[frame].m_Points[index].LeftNaNOrInf() ) || actual[frame].m_Points[index].LeftNaNOrInf() )\n        {\n          cv::Point2d error =\n            actual[frame].m_Points[index].m_Left - measured[frame].m_Points[index].m_Left;\n\n          if ( ( error.x > lowLimit.m_Left.x ) && ( error.x < highLimit.m_Left.x ) &&\n             ( error.y > lowLimit.m_Left.y ) && ( error.y < highLimit.m_Left.y ) )\n          {\n            RMSError.first += ( error.x * error.x ) + ( error.y * error.y );\n            count.first ++;\n          }\n        }\n\n        if ( ! ( measured[frame].m_Points[index].RightNaNOrInf() ) || actual[frame].m_Points[index].RightNaNOrInf() )\n        {\n          cv::Point2d error =\n            actual[frame].m_Points[index].m_Right - measured[frame].m_Points[index].m_Right;\n\n          if ( ( error.x > lowLimit.m_Right.x ) && ( error.x < highLimit.m_Right.x ) &&\n             ( error.y > lowLimit.m_Right.y ) && ( error.y < highLimit.m_Right.y ) )\n          {\n            RMSError.second += ( error.x * error.x ) + ( error.y * error.y );\n            count.second ++;\n          }\n        }\n      }\n      else\n      {\n        if ( index == lowIndex )\n        {\n          MITK_WARN << \"mitk::RMSError Dropping point pair \" << frame << \",\" << (frame)+1  << \" due to high timing error \" << measured[frame].m_TimingError << \" > \" << allowableTimingError;\n        }\n      }\n    }\n  }\n  if ( count.first > 0 )\n  {\n    RMSError.first = sqrt ( RMSError.first / count.first );\n  }\n  if ( count.second > 0 )\n  {\n    RMSError.second = sqrt ( RMSError.second / count.second );\n  }\n  return RMSError;\n}\n\n//-----------------------------------------------------------------------------\nmitk::ProjectedPointPair MeanError (\n    std::vector < mitk::ProjectedPointPairsWithTimingError > measured ,\n    std::vector < mitk::ProjectedPointPairsWithTimingError > actual ,\n    mitk::ProjectedPointPair * StandardDeviations, int indexToUse,\n    long long allowableTimingError, bool duplicateLines)\n{\n  assert ( measured.size() == actual.size() );\n\n  mitk::ProjectedPointPair meanError;\n\n  meanError.m_Left.x = 0.0;\n  meanError.m_Left.y = 0.0;\n  meanError.m_Right.x = 0.0;\n  meanError.m_Right.y = 0.0;\n\n  std::pair < int , int > count;\n  count.first = 0;\n  count.second = 0;\n  int lowIndex = 0;\n  int highIndex = measured[0].m_Points.size();\n  if ( indexToUse != -1 )\n  {\n    lowIndex = indexToUse;\n    highIndex = indexToUse;\n  }\n\n  for ( int index = lowIndex; index < highIndex ; index ++ )\n  {\n    unsigned int increment=1;\n    if ( duplicateLines )\n    {\n      increment = 2;\n    }\n    for ( unsigned int frame = 0 ; frame < actual.size() ; frame += increment )\n    {\n      if ( measured[frame].m_TimingError < std::abs (allowableTimingError) )\n      {\n        if ( ! ( measured[frame].m_Points[index].LeftNaNOrInf()  || actual[frame].m_Points[index].LeftNaNOrInf() ) )\n        {\n          meanError.m_Left +=\n            actual[frame].m_Points[index].m_Left - measured[frame].m_Points[index].m_Left ;\n          count.first ++;\n        }\n        if ( ! ( measured[frame].m_Points[index].RightNaNOrInf() || actual[frame].m_Points[index].RightNaNOrInf() ) )\n        {\n          meanError.m_Right +=\n            actual[frame].m_Points[index].m_Right - measured[frame].m_Points[index].m_Right ;\n          count.second ++;\n        }\n      }\n      else\n      {\n        if ( index == lowIndex )\n        {\n          MITK_WARN << \"mitk::MeanError Dropping point pair \" << frame << \",\" << (frame)+1  << \" due to high timing error \" << measured[frame].m_TimingError << \" > \" << allowableTimingError;\n        }\n      }\n    }\n  }\n  if ( count.first > 0 )\n  {\n    meanError.m_Left =  meanError.m_Left / count.first ;\n  }\n  if ( count.second > 0 )\n  {\n    meanError.m_Right =  meanError.m_Right / count.second ;\n  }\n  if ( StandardDeviations == NULL )\n  {\n    return meanError;\n  }\n  else\n  {\n    StandardDeviations->m_Left.x = 0.0;\n    StandardDeviations->m_Left.y = 0.0;\n    StandardDeviations->m_Right.x = 0.0;\n    StandardDeviations->m_Right.y = 0.0;\n    for ( int index = lowIndex; index < highIndex ; index ++ )\n    {\n      for ( unsigned int frame = 0 ; frame < actual.size() ; frame ++ )\n      {\n        if ( measured[frame].m_TimingError < std::abs (allowableTimingError) )\n        {\n          if ( ! ( measured[frame].m_Points[index].LeftNaNOrInf() || actual[frame].m_Points[index].LeftNaNOrInf() ) )\n          {\n            cv::Point2d error =\n              actual[frame].m_Points[index].m_Left - measured[frame].m_Points[index].m_Left - meanError.m_Left;\n            StandardDeviations->m_Left += error * error;\n            count.first ++;\n          }\n          if ( ! ( measured[frame].m_Points[index].RightNaNOrInf() || actual[frame].m_Points[index].RightNaNOrInf() ) )\n          {\n            cv::Point2d error =\n              actual[frame].m_Points[index].m_Right - measured[frame].m_Points[index].m_Right - meanError.m_Right;\n            StandardDeviations->m_Right += error * error;\n            count.second ++;\n          }\n        }\n      }\n    }\n    if ( count.first > 0 )\n    {\n      StandardDeviations->m_Left.x =  sqrt(StandardDeviations->m_Left.x / count.first);\n      StandardDeviations->m_Left.y =  sqrt(StandardDeviations->m_Left.y / count.first) ;\n    }\n    if ( count.second > 0 )\n    {\n      StandardDeviations->m_Right.x = sqrt( StandardDeviations->m_Right.x / count.second) ;\n      StandardDeviations->m_Right.y = sqrt( StandardDeviations->m_Right.y / count.second) ;\n    }\n\n  }\n  return meanError;\n}\n\n//-----------------------------------------------------------------------------\ncv::Mat PerturbTransform (const cv::Mat transformIn ,\n    const double tx, const double ty, const double tz,\n    const double rx, const double ry, const double rz)\n{\n\n  cv::Mat rotationVector = cv::Mat (3,1,CV_64FC1);\n  cv::Mat rotationMatrix = cv::Mat (3,3,CV_64FC1);\n  cv::Mat perturbationMatrix = cv::Mat (4,4,CV_64FC1);\n  rotationVector.at<double>(0,0) = rx * CV_PI/180;\n  rotationVector.at<double>(1,0) = ry * CV_PI/180;\n  rotationVector.at<double>(2,0) = rz * CV_PI/180;\n\n  cv::Rodrigues ( rotationVector,rotationMatrix );\n  for ( int row = 0 ; row < 3 ; row ++ )\n  {\n    for ( int col = 0 ; col < 3 ; col ++ )\n    {\n      perturbationMatrix.at<double>(row,col) = rotationMatrix.at<double>(row,col);\n    }\n  }\n  perturbationMatrix.at<double>(0,3) = tx;\n  perturbationMatrix.at<double>(1,3) = ty;\n  perturbationMatrix.at<double>(2,3) = tz;\n  perturbationMatrix.at<double>(3,0) = 0.0;\n  perturbationMatrix.at<double>(3,1) = 0.0;\n  perturbationMatrix.at<double>(3,2) = 0.0;\n  perturbationMatrix.at<double>(3,3) = 1.0;\n\n  return transformIn * perturbationMatrix;\n}\n\n\n//-----------------------------------------------------------------------------\ncv::Point2d FindNearestPoint ( const cv::Point2d& point,\n    const std::vector < cv::Point2d>& matchingPoints, double * minRatio , unsigned int * Index )\n{\n  std::vector <cv::Point2d>  sortedMatches;\n  for ( unsigned int i = 0 ; i < matchingPoints.size() ; i ++ )\n  {\n    sortedMatches.push_back ( point - matchingPoints[i] );\n  }\n\n  if ( Index != NULL )\n  {\n    *Index = std::min_element(sortedMatches.begin(), sortedMatches.end(), DistanceCompare) -\n      sortedMatches.begin();\n  }\n\n  std::sort ( sortedMatches.begin(), sortedMatches.end () , DistanceCompare );\n\n  if ( minRatio != NULL )\n  {\n    if ( sortedMatches.size() > 1 )\n    {\n      *minRatio =\n        sqrt(sortedMatches[1].x * sortedMatches[1].x + sortedMatches[1].y * sortedMatches[1].y ) /\n        sqrt(sortedMatches[0].x * sortedMatches[0].x + sortedMatches[0].y * sortedMatches[0].y );\n    }\n    else\n    {\n      *minRatio = 0.0;\n    }\n  }\n  if (boost::math::isinf (sortedMatches[0].x))\n  {\n    *minRatio =  0.0;\n  }\n  return  point - sortedMatches [0];\n}\n\n//-----------------------------------------------------------------------------\nmitk::PickedObject FindNearestPickedObject ( const mitk::PickedObject& point, const std::vector <mitk::PickedObject>& matchingPoints ,\n    double* minRatio )\n{\n  mitk::PickedObject nearestPoint;\n  double nearestDistance = std::numeric_limits<double>::infinity();\n  double nextNearestDistance = std::numeric_limits<double>::infinity();\n\n  for ( std::vector<mitk::PickedObject>::const_iterator it = matchingPoints.begin() ; it < matchingPoints.end() ; ++it )\n  {\n    mitk::PickedObject delta;\n    double distance = point.DistanceTo(*it, delta);\n    if ( distance < nextNearestDistance )\n    {\n      if ( distance < nearestDistance )\n      {\n        nextNearestDistance = nearestDistance;\n        nearestDistance = distance;\n        nearestPoint = *it;\n      }\n      else\n      {\n        nextNearestDistance = distance;\n      }\n    }\n  }\n  if ( minRatio != NULL )\n  {\n    *minRatio = nextNearestDistance / nearestDistance;\n  }\n  return nearestPoint;\n}\n\n//-----------------------------------------------------------------------------\nbool DistanceCompare ( const cv::Point2d& p1, const cv::Point2d& p2 )\n{\n  double d1 = sqrt( p1.x * p1.x + p1.y * p1.y );\n  double d2 = sqrt( p2.x * p2.x + p2.y * p2.y );\n  return d1 < d2;\n}\n\n//-----------------------------------------------------------------------------\ncv::Mat Tracker2ToTracker1Rotation ( const std::vector<cv::Mat>& Tracker1ToWorld1,\n    const std::vector<cv::Mat>& World2ToTracker2, double& Residual)\n{\n\n  if ( Tracker1ToWorld1.size() != World2ToTracker2.size() )\n  {\n    MITK_ERROR << \"Called HandeyeRotation with unequal matrix vectors\";\n    Residual = -1.0;\n    return cv::Mat();\n  }\n  int numberOfViews = Tracker1ToWorld1.size();\n\n  cv::Mat A = cvCreateMat ( 3 * (numberOfViews - 1), 3, CV_64FC1 );\n  cv::Mat b = cvCreateMat ( 3 * (numberOfViews - 1), 1, CV_64FC1 );\n\n  for ( int i = 0; i < numberOfViews - 1; i ++ )\n  {\n    cv::Mat mat1 = cvCreateMat(4,4,CV_64FC1);\n    cv::Mat mat2 = cvCreateMat(4,4,CV_64FC1);\n    mat1 = Tracker1ToWorld1[i+1].inv() * Tracker1ToWorld1[i];\n    mat2 = World2ToTracker2[i+1] * World2ToTracker2[i].inv();\n\n    cv::Mat rotationMat1 = cvCreateMat(3,3,CV_64FC1);\n    cv::Mat rotationMat2 = cvCreateMat(3,3,CV_64FC1);\n    cv::Mat rotationVector1 = cvCreateMat(3,1,CV_64FC1);\n    cv::Mat rotationVector2 = cvCreateMat(3,1,CV_64FC1);\n    for ( int row = 0; row < 3; row ++ )\n    {\n      for ( int col = 0; col < 3; col ++ )\n      {\n        rotationMat1.at<double>(row,col) = mat1.at<double>(row,col);\n        rotationMat2.at<double>(row,col) = mat2.at<double>(row,col);\n      }\n    }\n    cv::Rodrigues (rotationMat1, rotationVector1 );\n    cv::Rodrigues (rotationMat2, rotationVector2 );\n\n    double norm1 = cv::norm(rotationVector1);\n    double norm2 = cv::norm(rotationVector2);\n\n    rotationVector1 *= 2*sin(norm1/2) / norm1;\n    rotationVector2 *= 2*sin(norm2/2) / norm2;\n\n    cv::Mat sum = rotationVector1 + rotationVector2;\n    cv::Mat diff = rotationVector2 - rotationVector1;\n\n    A.at<double>(i*3+0,0)=0.0;\n    A.at<double>(i*3+0,1)=-(sum.at<double>(2,0));\n    A.at<double>(i*3+0,2)=sum.at<double>(1,0);\n    A.at<double>(i*3+1,0)=sum.at<double>(2,0);\n    A.at<double>(i*3+1,1)=0.0;\n    A.at<double>(i*3+1,2)=-(sum.at<double>(0,0));\n    A.at<double>(i*3+2,0)=-(sum.at<double>(1,0));\n    A.at<double>(i*3+2,1)=sum.at<double>(0,0);\n    A.at<double>(i*3+2,2)=0.0;\n\n    b.at<double>(i*3+0,0)=diff.at<double>(0,0);\n    b.at<double>(i*3+1,0)=diff.at<double>(1,0);\n    b.at<double>(i*3+2,0)=diff.at<double>(2,0);\n\n  }\n\n  cv::Mat PseudoInverse = cvCreateMat(3,3,CV_64FC1);\n  cv::invert(A,PseudoInverse,CV_SVD);\n\n  cv::Mat pcgPrime = PseudoInverse * b;\n\n  cv::Mat Error = A * pcgPrime-b;\n\n  cv::Mat ErrorTransMult = cvCreateMat(Error.cols, Error.cols, CV_64FC1);\n\n  cv::mulTransposed (Error, ErrorTransMult, true);\n\n  Residual = sqrt(ErrorTransMult.at<double>(0,0)/(numberOfViews-1));\n\n  cv::Mat pcg = 2 * pcgPrime / ( sqrt(1 + cv::norm(pcgPrime) * cv::norm(pcgPrime)) );\n  cv::Mat id3 = cvCreateMat(3,3,CV_64FC1);\n  for ( int row = 0; row < 3; row ++ )\n  {\n    for ( int col = 0; col < 3; col ++ )\n    {\n      if ( row == col )\n      {\n        id3.at<double>(row,col) = 1.0;\n      }\n      else\n      {\n        id3.at<double>(row,col) = 0.0;\n      }\n    }\n  }\n\n  cv::Mat pcg_crossproduct = cvCreateMat(3,3,CV_64FC1);\n  pcg_crossproduct.at<double>(0,0)=0.0;\n  pcg_crossproduct.at<double>(0,1)=-(pcg.at<double>(2,0));\n  pcg_crossproduct.at<double>(0,2)=(pcg.at<double>(1,0));\n  pcg_crossproduct.at<double>(1,0)=(pcg.at<double>(2,0));\n  pcg_crossproduct.at<double>(1,1)=0.0;\n  pcg_crossproduct.at<double>(1,2)=-(pcg.at<double>(0,0));\n  pcg_crossproduct.at<double>(2,0)=-(pcg.at<double>(1,0));\n  pcg_crossproduct.at<double>(2,1)=(pcg.at<double>(0,0));\n  pcg_crossproduct.at<double>(2,2)=0.0;\n\n  cv::Mat pcg_mulTransposed = cvCreateMat(pcg.rows, pcg.rows, CV_64FC1);\n  cv::mulTransposed (pcg, pcg_mulTransposed, false);\n  cv::Mat rcg = ( 1 - cv::norm(pcg) * norm(pcg) /2 ) * id3\n    + 0.5 * ( pcg_mulTransposed + sqrt(4 - norm(pcg) * norm(pcg))*pcg_crossproduct);\n  return rcg;\n}\n//-----------------------------------------------------------------------------\ncv::Mat Tracker2ToTracker1Translation ( const std::vector<cv::Mat>& Tracker1ToWorld1,\n     const std::vector<cv::Mat>& World2ToTracker2, double& Residual, const cv::Mat& rcg)\n{\n  if ( Tracker1ToWorld1.size() != World2ToTracker2.size() )\n  {\n    MITK_ERROR << \"Called HandeyeTranslation with unequal matrix vectors\";\n    Residual = -1.0;\n    return cv::Mat();\n  }\n  int numberOfViews = Tracker1ToWorld1.size();\n\n  cv::Mat A = cvCreateMat ( 3 * (numberOfViews - 1), 3, CV_64FC1 );\n  cv::Mat b = cvCreateMat ( 3 * (numberOfViews - 1), 1, CV_64FC1 );\n\n  for ( int i = 0; i < numberOfViews - 1; i ++ )\n  {\n    cv::Mat mat1 = cvCreateMat(4,4,CV_64FC1);\n    cv::Mat mat2 = cvCreateMat(4,4,CV_64FC1);\n    mat1 = Tracker1ToWorld1[i+1].inv() * Tracker1ToWorld1[i];\n    mat2 = World2ToTracker2[i+1] * World2ToTracker2[i].inv();\n\n    A.at<double>(i*3+0,0)=mat1.at<double>(0,0) - 1.0;\n    A.at<double>(i*3+0,1)=mat1.at<double>(0,1) - 0.0;\n    A.at<double>(i*3+0,2)=mat1.at<double>(0,2) - 0.0;\n    A.at<double>(i*3+1,0)=mat1.at<double>(1,0) - 0.0;\n    A.at<double>(i*3+1,1)=mat1.at<double>(1,1) - 1.0;\n    A.at<double>(i*3+1,2)=mat1.at<double>(1,2) - 0.0;\n    A.at<double>(i*3+2,0)=mat1.at<double>(2,0) - 0.0;\n    A.at<double>(i*3+2,1)=mat1.at<double>(2,1) - 0.0;\n    A.at<double>(i*3+2,2)=mat1.at<double>(2,2) - 1.0;\n\n    cv::Mat m1_t = cvCreateMat(3,1,CV_64FC1);\n    cv::Mat m2_t = cvCreateMat(3,1,CV_64FC1);\n    for ( int j = 0; j < 3; j ++ )\n    {\n      m1_t.at<double>(j,0) = mat1.at<double>(j,3);\n      m2_t.at<double>(j,0) = mat2.at<double>(j,3);\n    }\n    cv::Mat b_t = rcg * m2_t - m1_t;\n\n    b.at<double>(i*3+0,0)=b_t.at<double>(0,0);\n    b.at<double>(i*3+1,0)=b_t.at<double>(1,0);\n    b.at<double>(i*3+2,0)=b_t.at<double>(2,0);\n\n  }\n  cv::Mat PseudoInverse = cvCreateMat(3,3,CV_64FC1);\n  cv::invert(A,PseudoInverse,CV_SVD);\n  cv::Mat tcg = PseudoInverse * b;\n\n  cv::Mat Error = A * tcg -b;\n  cv::Mat ErrorTransMult = cvCreateMat(Error.cols, Error.cols, CV_64FC1);\n  cv::mulTransposed (Error, ErrorTransMult, true);\n  Residual = sqrt(ErrorTransMult.at<double>(0,0)/(numberOfViews-1));\n  return tcg;\n}\n//-----------------------------------------------------------------------------\ncv::Mat Tracker2ToTracker1RotationAndTranslation ( const std::vector<cv::Mat>& Tracker1ToWorld1,\n     const std::vector<cv::Mat>& World2ToTracker2, std::vector<double>& Residuals,\n     cv::Mat * World2ToWorld1)\n{\n  Residuals.clear();\n  //init residuals with negative number to stop unit test passing\n  //  //if Load result and calibration both produce zero.\n  Residuals.push_back(-100.0);\n  Residuals.push_back(-100.0);\n\n  double RotationalResidual;\n  cv::Mat rcg = mitk::Tracker2ToTracker1Rotation ( Tracker1ToWorld1, World2ToTracker2, RotationalResidual);\n  double TranslationalResidual;\n  cv::Mat tcg = mitk::Tracker2ToTracker1Translation (Tracker1ToWorld1, World2ToTracker2, TranslationalResidual, rcg);\n\n  Residuals[0] = RotationalResidual;\n  Residuals[1] = TranslationalResidual;\n\n  cv::Mat tracker2ToTracker1 = cvCreateMat(4,4,CV_64FC1);\n  for ( int row = 0; row < 3; row ++ )\n  {\n    for ( int col = 0; col < 3; col ++ )\n    {\n      tracker2ToTracker1.at<double>(row,col) = rcg.at<double>(row,col);\n    }\n  }\n  for ( int row = 0; row < 3; row ++ )\n  {\n    tracker2ToTracker1.at<double>(row,3) = tcg.at<double>(row,0);\n  }\n  for ( int col = 0; col < 3; col ++ )\n  {\n    tracker2ToTracker1.at<double>(3,col) = 0.0;\n  }\n  tracker2ToTracker1.at<double>(3,3)=1.0;\n\n  if ( World2ToWorld1 != NULL )\n  {\n    std::vector<cv::Mat> world2ToWorld1s;\n    world2ToWorld1s.clear();\n    for ( int i = 0; i < Tracker1ToWorld1.size() ; i ++ )\n    {\n      cv::Mat world2ToWorld1 = cvCreateMat(4,4,CV_64FC1);\n      cv::Mat tracker2ToWorld1 = cvCreateMat(4,4,CV_64FC1);\n\n      tracker2ToWorld1 =  Tracker1ToWorld1[i]*(tracker2ToTracker1);\n      world2ToWorld1 = tracker2ToWorld1 *(World2ToTracker2[i]);\n      world2ToWorld1s.push_back(world2ToWorld1);\n    }\n    *World2ToWorld1 = mitk::AverageMatrices (world2ToWorld1s);\n    //lets do a check To get Tracker2 into Tracker1\n    //Tracker1InWorld1 = (Tracker2InWorld2 * world2ToWorld1) * tracker2toTracker1\n    for ( int i = 0 ; i < Tracker1ToWorld1.size() ; i++ )\n    {\n      if ( i == 0 )\n      {\n        MITK_INFO << \"Tracker 1: \" << i ;\n        MITK_INFO << Tracker1ToWorld1[i];\n        MITK_INFO << \"Tracker 2 to World 1 \" << i ;\n        MITK_INFO << (*World2ToWorld1) * World2ToTracker2[i].inv();\n        MITK_INFO << \"Tracker 1 to world 1 \"  << i ;\n        MITK_INFO <<  ((*World2ToWorld1) * World2ToTracker2[i].inv()) * tracker2ToTracker1.inv();\n      }\n      MITK_INFO << \"Difference \" << i ;\n      MITK_INFO << (((*World2ToWorld1) * World2ToTracker2[i].inv()) * tracker2ToTracker1.inv())- Tracker1ToWorld1[i];\n    }\n  }\n  else\n  {\n    MITK_INFO << \"Grid to world NULL \";\n  }\n  return tracker2ToTracker1;\n}\n\n//-----------------------------------------------------------------------------------------\ncv::Mat AverageMatrices (const std::vector <cv::Mat>& Matrices )\n{\n  cv::Mat temp = cvCreateMat(3,3,CV_64FC1);\n  cv::Mat temp_T = cvCreateMat (3,1,CV_64FC1);\n  for ( int row = 0 ; row < 3 ; row++ )\n  {\n    for ( int col = 0 ; col < 3 ; col++ )\n    {\n      temp.at<double>(row,col) = 0.0;\n    }\n    temp_T.at<double>(row,0) = 0.0;\n  }\n  for ( unsigned int i = 0 ; i < Matrices.size() ; i ++ )\n  {\n    for ( int row = 0 ; row < 3 ; row++ )\n    {\n      for ( int col = 0 ; col < 3 ; col++ )\n      {\n        double whatItWas = temp.at<double>(row,col);\n        double whatToAdd = Matrices[i].at<double>(row,col);\n        temp.at<double>(row,col) = whatItWas +  whatToAdd;\n      }\n      temp_T.at<double>(row,0) += Matrices[i].at<double>(row,3);\n    }\n\n    //we write temp out, not because it's interesting but because it\n    //seems to fix a bug in the averaging code, trac 2895\n    MITK_DEBUG << \"temp \" << temp;\n  }\n\n  temp_T = temp_T / static_cast<double>(Matrices.size());\n  temp = temp / static_cast<double>(Matrices.size());\n\n\n  cv::Mat rtr = temp.t() * temp;\n\n  cv::Mat eigenvectors = cvCreateMat(3,3,CV_64FC1);\n  cv::Mat eigenvalues = cvCreateMat(3,1,CV_64FC1);\n  cv::eigen(rtr , eigenvalues, eigenvectors);\n  cv::Mat rootedEigenValues = cvCreateMat(3,3,CV_64FC1);\n  //write out the vectors and values, because it might be interesting, trac 2972\n  MITK_DEBUG << \"eigenvalues \" << eigenvalues;\n  MITK_DEBUG << \"eigenvectors \" << eigenvectors;\n  for ( int row = 0 ; row < 3 ; row ++ )\n  {\n    for ( int col = 0 ; col < 3 ; col ++ )\n    {\n      if ( row == col )\n      {\n        rootedEigenValues.at<double>(row,col) = sqrt(1.0/eigenvalues.at<double>(row,0));\n      }\n      else\n      {\n        rootedEigenValues.at<double>(row,col) = 0.0;\n      }\n    }\n  }\n  //write out the rooted eigenValues trac 2972\n  MITK_DEBUG << \" rooted eigenvalues \" << rootedEigenValues;\n\n  cv::Mat returnMat = cvCreateMat (4,4,CV_64FC1);\n  cv::Mat temp2 = cvCreateMat(3,3,CV_64FC1);\n  temp2 = temp * ( eigenvectors * rootedEigenValues * eigenvectors.t() );\n  for ( int row = 0 ; row < 3 ; row ++ )\n  {\n    for ( int col = 0 ; col < 3 ; col ++ )\n    {\n      returnMat.at<double>(row,col) = temp2.at<double>(row,col);\n    }\n    returnMat.at<double>(row,3) = temp_T.at<double>(row,0);\n  }\n  returnMat.at<double>(3,0) = 0.0;\n  returnMat.at<double>(3,1) = 0.0;\n  returnMat.at<double>(3,2) = 0.0;\n  returnMat.at<double>(3,3)  = 1.0;\n  return returnMat;\n\n}\n\n//-----------------------------------------------------------------------------\nstd::vector<cv::Mat> FlipMatrices (const std::vector<cv::Mat> Matrices)\n{\n  std::vector<cv::Mat>  OutMatrices;\n  for ( unsigned int i = 0; i < Matrices.size(); i ++ )\n  {\n    if ( Matrices[i].type() == CV_64FC1 )\n    {\n      cv::Mat FlipMat = cvCreateMat(4,4,CV_64FC1);\n      FlipMat.at<double>(0,0) = Matrices[i].at<double>(0,0);\n      FlipMat.at<double>(0,1) = Matrices[i].at<double>(0,1);\n      FlipMat.at<double>(0,2) = Matrices[i].at<double>(0,2) * -1;\n      FlipMat.at<double>(0,3) = Matrices[i].at<double>(0,3);\n\n      FlipMat.at<double>(1,0) = Matrices[i].at<double>(1,0);\n      FlipMat.at<double>(1,1) = Matrices[i].at<double>(1,1);\n      FlipMat.at<double>(1,2) = Matrices[i].at<double>(1,2) * -1;\n      FlipMat.at<double>(1,3) = Matrices[i].at<double>(1,3);\n\n      FlipMat.at<double>(2,0) = Matrices[i].at<double>(2,0) * -1;\n      FlipMat.at<double>(2,1) = Matrices[i].at<double>(2,1) * -1;\n      FlipMat.at<double>(2,2) = Matrices[i].at<double>(2,2);\n      FlipMat.at<double>(2,3) = Matrices[i].at<double>(2,3) * -1;\n\n      FlipMat.at<double>(3,0) = Matrices[i].at<double>(3,0);\n      FlipMat.at<double>(3,1) = Matrices[i].at<double>(3,1);\n      FlipMat.at<double>(3,2) = Matrices[i].at<double>(3,2);\n      FlipMat.at<double>(3,3) = Matrices[i].at<double>(3,3);\n\n      OutMatrices.push_back(FlipMat);\n    }\n    else if ( Matrices[i].type() == CV_32FC1 )\n    {\n      cv::Mat FlipMat = cvCreateMat(4,4,CV_32FC1);\n      FlipMat.at<float>(0,0) = Matrices[i].at<float>(0,0);\n      FlipMat.at<float>(0,1) = Matrices[i].at<float>(0,1);\n      FlipMat.at<float>(0,2) = Matrices[i].at<float>(0,2) * -1;\n      FlipMat.at<float>(0,3) = Matrices[i].at<float>(0,3);\n\n      FlipMat.at<float>(1,0) = Matrices[i].at<float>(1,0);\n      FlipMat.at<float>(1,1) = Matrices[i].at<float>(1,1);\n      FlipMat.at<float>(1,2) = Matrices[i].at<float>(1,2) * -1;\n      FlipMat.at<float>(1,3) = Matrices[i].at<float>(1,3);\n\n      FlipMat.at<float>(2,0) = Matrices[i].at<float>(2,0) * -1;\n      FlipMat.at<float>(2,1) = Matrices[i].at<float>(2,1) * -1;\n      FlipMat.at<float>(2,2) = Matrices[i].at<float>(2,2);\n      FlipMat.at<float>(2,3) = Matrices[i].at<float>(2,3) * -1;\n\n      FlipMat.at<float>(3,0) = Matrices[i].at<float>(3,0);\n      FlipMat.at<float>(3,1) = Matrices[i].at<float>(3,1);\n      FlipMat.at<float>(3,2) = Matrices[i].at<float>(3,2);\n      FlipMat.at<float>(3,3) = Matrices[i].at<float>(3,3);\n\n      OutMatrices.push_back(FlipMat);\n    }\n  }\n  return OutMatrices;\n}\n\n//-----------------------------------------------------------------------------\nstd::vector<int> SortMatricesByDistance(const std::vector<cv::Mat>  Matrices)\n{\n  int NumberOfViews = Matrices.size();\n\n  std::vector<int> used;\n  std::vector<int> index;\n  for ( int i = 0; i < NumberOfViews; i++ )\n  {\n    used.push_back(i);\n    index.push_back(0);\n  }\n\n  int counter = 0;\n  int startIndex = 0;\n  double distance = 1e-10;\n  cv::Mat t1 = cvCreateMat(3,1,CV_64FC1);\n  cv::Mat t2 = cvCreateMat(3,1,CV_64FC1);\n  double d;\n\n  while ( fabs(distance) > 0 )\n  {\n    used [startIndex] = 0;\n    index [counter] = startIndex;\n    counter++;\n    distance = 0.0;\n    int CurrentIndex=0;\n    for ( int i = 0; i < NumberOfViews; i ++ )\n    {\n      if ( ( startIndex != i ) && ( used[i] != 0 ))\n      {\n        for ( int row = 0; row < 3; row ++ )\n        {\n          t1.at<double>(row,0) = Matrices[startIndex].at<double>(row,3);\n          t2.at<double>(row,0) = Matrices[i].at<double>(row,3);\n        }\n        d = cv::norm(t1-t2);\n\n        if ( d > distance )\n        {\n          distance = d;\n          CurrentIndex=i;\n        }\n      }\n    }\n    if ( counter < NumberOfViews )\n    {\n      index[counter] = CurrentIndex;\n    }\n    startIndex = CurrentIndex;\n  }\n  t1.release();\n  t2.release();\n  return index;\n}\n\n//-----------------------------------------------------------------------------\nstd::vector<int> SortMatricesByAngle(const std::vector<cv::Mat>  Matrices)\n{\n  int NumberOfViews = Matrices.size();\n\n  std::vector<int> used;\n  std::vector<int> index;\n  for ( int i = 0; i < NumberOfViews; i++ )\n  {\n    used.push_back(i);\n    index.push_back(0);\n  }\n\n  int counter = 0;\n  int startIndex = 0;\n  double distance = 1e-10;\n\n  cv::Mat t1 = cvCreateMat(3,3,CV_64FC1);\n  cv::Mat t2 = cvCreateMat(3,3,CV_64FC1);\n  cv::Mat t1q = cvCreateMat(4,1,CV_64FC1);\n  cv::Mat t2q = cvCreateMat(4,1,CV_64FC1);\n  double d;\n  while ( fabs(distance) > 0.0 )\n  {\n\n    for ( int row = 0; row < 3; row ++ )\n    {\n      for ( int col = 0; col < 3; col ++ )\n      {\n        t1.at<double>(row,col) = Matrices[startIndex].at<double>(row,col);\n      }\n    }\n    used [startIndex] = 0;\n    index [counter] = startIndex;\n    counter++;\n    distance = 0.0;\n    int CurrentIndex=0;\n    for ( int i = 0; i < NumberOfViews; i ++ )\n    {\n      if ( ( startIndex != i ) && ( used[i] != 0 ))\n      {\n        for ( int row = 0; row < 3; row ++ )\n        {\n          for ( int col = 0; col < 3; col ++ )\n          {\n            t2.at<double>(row,col) = Matrices[i].at<double>(row,col);\n          }\n        }\n\n        t1q = DirectionCosineToQuaternion(t1);\n        t2q = DirectionCosineToQuaternion(t2);\n        d = 2 * acos (t1q.at<double>(3,0) * t2q.at<double>(3,0)\n          + t1q.at<double>(0,0) * t2q.at<double>(0,0)\n          + t1q.at<double>(1,0) * t2q.at<double>(1,0)\n          + t1q.at<double>(2,0) * t2q.at<double>(2,0));\n        if ( d > distance )\n        {\n          distance = d;\n          CurrentIndex=i;\n        }\n      }\n    }\n    if ( counter < NumberOfViews )\n    {\n      index[counter] = CurrentIndex;\n    }\n    startIndex = CurrentIndex;\n  }\n  t1.release();\n  t2.release();\n  t1q.release();\n  t2q.release();\n  return index;\n}\n\n//-----------------------------------------------------------------------------\ndouble AngleBetweenMatrices(cv::Mat Mat1 , cv::Mat Mat2)\n{\n  //turn them into quaternions first\n  cv::Mat q1 = DirectionCosineToQuaternion(Mat1);\n  cv::Mat q2 = DirectionCosineToQuaternion(Mat2);\n\n  return 2 * acos (q1.at<double>(3,0) * q2.at<double>(3,0)\n      + q1.at<double>(0,0) * q2.at<double>(0,0)\n      + q1.at<double>(1,0) * q2.at<double>(1,0)\n      + q1.at<double>(2,0) * q2.at<double>(2,0));\n\n}\n\n//-----------------------------------------------------------------------------\ndouble DistanceBetweenMatrices(cv::Mat Mat1 , cv::Mat Mat2)\n{\n  cv::Mat t1 = cvCreateMat(3,1,CV_64FC1);\n  cv::Mat t2 = cvCreateMat(3,1,CV_64FC1);\n\n  for ( int row = 0; row < 3; row ++ )\n  {\n    t1.at<double>(row,0) = Mat1.at<double>(row,3);\n    t2.at<double>(row,0) = Mat2.at<double>(row,3);\n  }\n  double returnVal = cv::norm(t1-t2);\n  //This function still leaks memory, I'm not the following statements are\n  //working\n  t1.release();\n  t2.release();\n  return returnVal;\n}\n\n//-----------------------------------------------------------------------------\ncv::Mat DirectionCosineToQuaternion(cv::Mat dc_Matrix)\n{\n  cv::Mat q = cvCreateMat(4,1,CV_64FC1);\n  q.at<double>(0,0) = 0.5 * niftk::SafeSQRT ( 1 + dc_Matrix.at<double>(0,0) -\n  dc_Matrix.at<double>(1,1) - dc_Matrix.at<double>(2,2) ) *\n  niftk::ModifiedSignum ( dc_Matrix.at<double>(1,2) - dc_Matrix.at<double>(2,1));\n\n  q.at<double>(1,0) = 0.5 * niftk::SafeSQRT ( 1 - dc_Matrix.at<double>(0,0) +\n  dc_Matrix.at<double>(1,1) - dc_Matrix.at<double>(2,2) ) *\n  niftk::ModifiedSignum ( dc_Matrix.at<double>(2,0) - dc_Matrix.at<double>(0,2));\n\n  q.at<double>(2,0) = 0.5 * niftk::SafeSQRT ( 1 - dc_Matrix.at<double>(0,0) -\n  dc_Matrix.at<double>(1,1) + dc_Matrix.at<double>(2,2) ) *\n  niftk::ModifiedSignum ( dc_Matrix.at<double>(0,1) - dc_Matrix.at<double>(1,0));\n\n  q.at<double>(3,0) = 0.5 * niftk::SafeSQRT ( 1 + dc_Matrix.at<double>(0,0) +\n  dc_Matrix.at<double>(1,1) + dc_Matrix.at<double>(2,2) );\n\n  return q;\n}\n\n\n//-----------------------------------------------------------------------------\nvoid InvertRigid4x4Matrix(const CvMat& input, CvMat& output)\n{\n  if (input.rows != 4)\n  {\n    mitkThrow() << \"Input matrix must have 4 rows.\" << std::endl;\n  }\n  if (input.cols != 4)\n  {\n    mitkThrow() << \"Input matrix must have 4 columns.\" << std::endl;\n  }\n  if (output.rows != 4)\n  {\n    mitkThrow() << \"Output matrix must have 4 rows.\" << std::endl;\n  }\n  if (output.cols != 4)\n  {\n    mitkThrow() << \"Output matrix must have 4 columns.\" << std::endl;\n  }\n\n  CvMat *inputRotationMatrix = cvCreateMat(3,3,CV_64FC1);\n  CvMat *inputRotationMatrixTransposed = cvCreateMat(3,3,CV_64FC1);\n  CvMat *inputTranslationVector = cvCreateMat(3,1,CV_64FC1);\n  CvMat *inputTranslationVectorInverted = cvCreateMat(3,1,CV_64FC1);\n\n  // Copy from 4x4 to separate rotation matrix and translation vector.\n  for (int r = 0; r < 3; ++r)\n  {\n    for (int c = 0; c < 3; ++c)\n    {\n      CV_MAT_ELEM(*inputRotationMatrix, double, r, c) = CV_MAT_ELEM(input, double, r, c);\n    }\n    CV_MAT_ELEM(*inputTranslationVector, double, r, 0) = CV_MAT_ELEM(input, double, r, 3);\n  }\n\n  cvTranspose(inputRotationMatrix, inputRotationMatrixTransposed);\n  cvGEMM(inputRotationMatrixTransposed, inputTranslationVector, -1, NULL, 0, inputTranslationVectorInverted);\n\n  // Copy inverted matrix to output.\n  for (int r = 0; r < 3; ++r)\n  {\n    for (int c = 0; c < 3; ++c)\n    {\n      CV_MAT_ELEM(output, double, r, c) = CV_MAT_ELEM(*inputRotationMatrixTransposed, double, r, c);\n    }\n    CV_MAT_ELEM(output, double, r, 3) = CV_MAT_ELEM(*inputTranslationVectorInverted, double, r, 0);\n  }\n\n  CV_MAT_ELEM(output, double, 3, 0) = 0;\n  CV_MAT_ELEM(output, double, 3, 1) = 0;\n  CV_MAT_ELEM(output, double, 3, 2) = 0;\n  CV_MAT_ELEM(output, double, 3, 3) = 1;\n\n  cvReleaseMat(&inputRotationMatrix);\n  cvReleaseMat(&inputRotationMatrixTransposed);\n  cvReleaseMat(&inputTranslationVector);\n  cvReleaseMat(&inputTranslationVectorInverted);\n}\n\n\n//-----------------------------------------------------------------------------\nvoid InvertRigid4x4Matrix(const cv::Mat& input, cv::Mat& output)\n{\n  const CvMat inputCv = input;\n  CvMat outputCv = output;\n  InvertRigid4x4Matrix(inputCv, outputCv);\n}\n\n\n//-----------------------------------------------------------------------------\nvoid InvertRigid4x4Matrix(const cv::Matx44d& input, cv::Matx44d& output)\n{\n  cv::Mat tmpInput = cvCreateMat(4,4,CV_64FC1);\n  cv::Mat tmpOutput = cvCreateMat(4,4,CV_64FC1);\n  for (unsigned int r = 0; r < 4; r++)\n  {\n    for (unsigned int c = 0; c < 4; c++)\n    {\n      tmpInput.at<double>(r,c) = input(r,c);\n    }\n  }\n  InvertRigid4x4Matrix(tmpInput, tmpOutput);\n  output = tmpOutput;\n}\n\n\n//-----------------------------------------------------------------------------\nvoid InterpolateTransformationMatrix(const cv::Mat& before, const cv::Mat& after, const double& proportion, cv::Mat& output)\n{\n  vtkSmartPointer<vtkMatrix4x4> b = vtkSmartPointer<vtkMatrix4x4>::New();\n  vtkSmartPointer<vtkMatrix4x4> a = vtkSmartPointer<vtkMatrix4x4>::New();\n  vtkSmartPointer<vtkMatrix4x4> interp = vtkSmartPointer<vtkMatrix4x4>::New();\n\n  mitk::CopyToVTK4x4Matrix(before, *b);\n  mitk::CopyToVTK4x4Matrix(after, *a);\n\n  niftk::InterpolateTransformationMatrix(*b, *a, proportion, *interp);\n\n  mitk::CopyToOpenCVMatrix(*interp, output);\n}\n\n\n//-----------------------------------------------------------------------------\nvoid InterpolateTransformationMatrix(const cv::Matx44d& before, const cv::Matx44d& after, const double& proportion, cv::Matx44d& output)\n{\n  vtkSmartPointer<vtkMatrix4x4> b = vtkSmartPointer<vtkMatrix4x4>::New();\n  vtkSmartPointer<vtkMatrix4x4> a = vtkSmartPointer<vtkMatrix4x4>::New();\n  vtkSmartPointer<vtkMatrix4x4> interp = vtkSmartPointer<vtkMatrix4x4>::New();\n\n  mitk::CopyToVTK4x4Matrix(before, *b);\n  mitk::CopyToVTK4x4Matrix(after, *a);\n\n  niftk::InterpolateTransformationMatrix(*b, *a, proportion, *interp);\n\n  mitk::CopyToOpenCVMatrix(*interp, output);\n}\n\n//-----------------------------------------------------------------------------\nstd::string MatrixType ( const cv::Mat& matrix)\n{\n  std::string returnString;\n\n  switch ( matrix.type() )\n  {\n    case ( CV_8SC1 ):\n      returnString = \"CV_8SC1\";\n      break;\n    case ( CV_8SC2 ):\n      returnString = \"CV_8SC2\";\n      break;\n    case ( CV_8SC3 ):\n      returnString = \"CV_8SC3\";\n      break;\n    case ( CV_8SC4 ):\n      returnString = \"CV_8SC4\";\n      break;\n\n    case ( CV_8UC1 ):\n      returnString = \"CV_8UC1\";\n      break;\n    case ( CV_8UC2 ):\n      returnString = \"CV_8UC2\";\n      break;\n    case ( CV_8UC3 ):\n      returnString = \"CV_8UC3\";\n      break;\n    case ( CV_8UC4 ):\n      returnString = \"CV_8UC4\";\n      break;\n\n    case ( CV_16SC1 ):\n      returnString = \"CV_16SC1\";\n      break;\n    case ( CV_16SC2 ):\n      returnString = \"CV_16SC2\";\n      break;\n    case ( CV_16SC3 ):\n      returnString = \"CV_16SC3\";\n      break;\n    case ( CV_16SC4 ):\n      returnString = \"CV_16SC4\";\n      break;\n\n    case ( CV_16UC1 ):\n      returnString = \"CV_16UC1\";\n      break;\n    case ( CV_16UC2 ):\n      returnString = \"CV_16UC2\";\n      break;\n    case ( CV_16UC3 ):\n      returnString = \"CV_16UC3\";\n      break;\n    case ( CV_16UC4 ):\n      returnString = \"CV_16UC4\";\n      break;\n\n    case ( CV_32FC1 ):\n      returnString = \"CV_32FC1\";\n      break;\n    case ( CV_32FC2 ):\n      returnString = \"CV_32FC2\";\n      break;\n    case ( CV_32FC3 ):\n      returnString = \"CV_32FC3\";\n      break;\n    case ( CV_32FC4 ):\n      returnString = \"CV_32FC4\";\n      break;\n\n    case ( CV_64FC1 ):\n      returnString = \"CV_64FC1\";\n      break;\n    case ( CV_64FC2 ):\n      returnString = \"CV_64FC2\";\n      break;\n    case ( CV_64FC3 ):\n      returnString = \"CV_64FC3\";\n      break;\n    case ( CV_64FC4 ):\n      returnString = \"CV_64FC4\";\n      break;\n    default:\n      returnString = \"Don't know\";\n  }\n  return returnString;\n\n}\n\n//-----------------------------------------------------------------------------\nbool IsNaN ( const cv::Point2d& point)\n{\n  if ( ( boost::math::isnan ( point.x ))  || (boost::math::isnan (point.y)) )\n  {\n    return true;\n  }\n  else\n  {\n    return false;\n  }\n}\n\n//-----------------------------------------------------------------------------\nbool IsNaN ( const cv::Point3d& point)\n{\n  if ( ( boost::math::isnan ( point.x ))  || (boost::math::isnan (point.y)) || (boost::math::isnan (point.z)) )\n  {\n    return true;\n  }\n  else\n  {\n    return false;\n  }\n}\n\n\n//-----------------------------------------------------------------------------\nbool IsNotNaNorInf ( const cv::Point2d& point)\n{\n  bool ok = true;\n  if ( ( boost::math::isnan ( point.x ))  || (boost::math::isnan (point.y)) )\n  {\n    ok = false;\n  }\n  if ( ( boost::math::isinf ( point.x ))  || (boost::math::isinf (point.y)) )\n  {\n    ok = false;\n  }\n  return ok;\n}\n\n//-----------------------------------------------------------------------------\nbool IsNotNaNorInf ( const cv::Point3d& point)\n{\n  bool ok = true;\n  if ( ( boost::math::isnan ( point.x ))  || (boost::math::isnan (point.y)) || (boost::math::isnan(point.z)) )\n  {\n    ok = false;\n  }\n  if ( ( boost::math::isinf ( point.x ))  || (boost::math::isinf (point.y)) || (boost::math::isinf(point.z)) )\n  {\n    ok = false;\n  }\n  return ok;\n}\n\n//-----------------------------------------------------------------------------\ndouble DistanceToLine ( const std::pair<cv::Point3d, cv::Point3d>& line, const cv::Point3d& x0 )\n{\n  //courtesy Wolfram Mathworld\n  cv::Point3d x1;\n  cv::Point3d x2;\n\n  x1 = line.first;\n  x2 = line.second;\n\n  cv::Point3d d1 = x1-x0;\n  cv::Point3d d2 = x2-x1;\n\n  return mitk::Norm ( mitk::CrossProduct ( d2,d1 )) / (mitk::Norm(d2));\n}\n\n//-----------------------------------------------------------------------------\ndouble DistanceBetweenTwoPoints ( const cv::Point3d& p1 , const cv::Point3d& p2, cv::Point3d* delta )\n{\n  if ( delta != NULL )\n  {\n    *delta = p2 - p1;\n  }\n  return mitk::Norm ( p1 - p2 );\n}\n\n//-----------------------------------------------------------------------------\ndouble DistanceBetweenTwoSplines ( const std::vector <cv::Point3d>& s1 , const std::vector <cv::Point3d>& s2,\n    unsigned int splineOrder, cv::Point3d* delta )\n{\n  if ( ( s1.size() < 1) || (s2.size() < 2) )\n  {\n    MITK_WARN << \"Called mitk::DistanceBetweenTwoSplines with insufficient points, returning inf.: \" << s1.size() << \", \" << s2.size();\n    if ( delta != NULL )\n    {\n      *delta = cv::Point3d ( std::numeric_limits<double>::infinity(),std::numeric_limits<double>::infinity(),std::numeric_limits<double>::infinity());\n    }\n    return std::numeric_limits<double>::infinity();\n  }\n  std::vector < cv::Point3d > deltas ;\n  if ( splineOrder == 1 )\n  {\n    double sum = 0;\n    for ( std::vector<cv::Point3d>::const_iterator it_1 = s1.begin() ; it_1 < s1.end() ; it_1 ++ )\n    {\n      deltas.push_back ( cv::Point3d ( std::numeric_limits<double>::infinity() ,\n            std::numeric_limits<double>::infinity() ,\n            std::numeric_limits<double>::infinity() ));\n      if ( mitk::IsNaN ( *it_1) )\n      {\n        return std::numeric_limits<double>::quiet_NaN();\n      }\n      double shortestDistance = std::numeric_limits<double>::infinity();\n      for ( std::vector<cv::Point3d>::const_iterator it_2 = s2.begin() + 1 ; it_2 < s2.end() ; it_2 ++ )\n      {\n        if ( mitk::IsNaN ( *it_2) )\n        {\n          return std::numeric_limits<double>::quiet_NaN();\n        }\n        cv::Point3d signedDistance;\n        double distance = mitk::DistanceToLineSegment ( std::pair < cv::Point3d, cv::Point3d >(*(it_2) , *(it_2-1)), *it_1, &signedDistance );\n        if ( distance < shortestDistance )\n        {\n          shortestDistance = distance;\n          deltas.back() = signedDistance;\n        }\n      }\n      sum += shortestDistance;\n    }\n    if ( delta != NULL )\n    {\n      *delta = GetCentroid ( deltas );\n    }\n    return sum/s1.size();\n  }\n  else\n  {\n    MITK_WARN << \"Called mitk::DistanceBetweenTwoSplines with invalid splineOrder, returning inf.: \" << splineOrder;\n    return std::numeric_limits<double>::infinity();\n  }\n}\n\n//-----------------------------------------------------------------------------\ndouble DistanceToLineSegment ( const std::pair<cv::Point3d, cv::Point3d>& line, const cv::Point3d& x0, cv::Point3d* delta )\n{\n  //courtesy Wolfram Mathworld\n  cv::Point3d x1;\n  cv::Point3d x2;\n\n  x1 = line.first;\n  x2 = line.second;\n\n  cv::Point3d d1 = x2-x0;\n  cv::Point3d d2 = x2-x1;\n\n  double lambda = mitk::DotProduct ( d2, d1 ) /  mitk::DotProduct ( d2,d2 );\n  if ( lambda < 0 ) //we're beyond x2\n  {\n    if ( delta != NULL )\n    {\n      *delta = x0 - x2;\n    }\n    return mitk::Norm ( x2 - x0 );\n  }\n  if ( lambda > 1 ) //we're beyond x1\n  {\n    if ( delta != NULL )\n    {\n      *delta = x0 - x1;\n    }\n    return mitk::Norm ( x1 - x0 );\n  }\n  //else we're on the line segment\n\n  if ( delta != NULL )\n  {\n    *delta = ( x2 - lambda * d2 ) - x0;\n  }\n  return mitk::Norm ( mitk::CrossProduct ( d2,d1 )) / (mitk::Norm(d2));\n\n}\n\n//-----------------------------------------------------------------------------\ndouble DistanceBetweenLines ( const cv::Point3d& P0, const cv::Point3d& u, const cv::Point3d& Q0, const cv::Point3d& v ,\n    cv::Point3d& midpoint )\n{\n  // Method 1. Solve for shortest line joining two rays, then get midpoint.\n  // Taken from: http://geomalgorithms.com/a07-_distance.html\n  double sc, tc, a, b, c, d, e;\n  double distance;\n\n  cv::Point3d Psc;\n  cv::Point3d Qtc;\n  cv::Point3d W0;\n\n  // Difference of two origins\n\n  W0.x = P0.x - Q0.x;\n  W0.y = P0.y - Q0.y;\n  W0.z = P0.z - Q0.z;\n\n  a = u.x*u.x + u.y*u.y + u.z*u.z;\n  b = u.x*v.x + u.y*v.y + u.z*v.z;\n  c = v.x*v.x + v.y*v.y + v.z*v.z;\n  d = u.x*W0.x + u.y*W0.y + u.z*W0.z;\n  e = v.x*W0.x + v.y*W0.y + v.z*W0.z;\n  sc = (b*e - c*d) / (a*c - b*b);\n  tc = (a*e - b*d) / (a*c - b*b);\n\n  if ( boost::math::isnan(sc) || boost::math::isnan(tc) || boost::math::isinf(sc) || boost::math::isinf(tc) )\n  {\n    //lines are parallel\n    distance = mitk::DistanceToLine ( std::pair<cv::Point3d, cv::Point3d> ( P0, P0 + u ), Q0 );\n    midpoint.x = std::numeric_limits<double>::quiet_NaN();\n    midpoint.y = std::numeric_limits<double>::quiet_NaN();\n    midpoint.z = std::numeric_limits<double>::quiet_NaN();\n    return distance;\n  }\n  Psc.x = P0.x + sc*u.x;\n  Psc.y = P0.y + sc*u.y;\n  Psc.z = P0.z + sc*u.z;\n  Qtc.x = Q0.x + tc*v.x;\n  Qtc.y = Q0.y + tc*v.y;\n  Qtc.z = Q0.z + tc*v.z;\n\n  distance = sqrt((Psc.x - Qtc.x)*(Psc.x - Qtc.x)\n                        +(Psc.y - Qtc.y)*(Psc.y - Qtc.y)\n                        +(Psc.z - Qtc.z)*(Psc.z - Qtc.z));\n\n  midpoint.x = (Psc.x + Qtc.x)/2.0;\n  midpoint.y = (Psc.y + Qtc.y)/2.0;\n  midpoint.z = (Psc.z + Qtc.z)/2.0;\n\n  return distance;\n}\n\n//-----------------------------------------------------------------------------\ndouble DistanceBetweenLineAndSegment( const cv::Point3d& P0, const cv::Point3d& u, const cv::Point3d& x0, const cv::Point3d& x1 ,\n    cv::Point3d& closestPointOnSecondLine )\n{\n\n  std::pair < cv::Point3d, cv::Point3d > pl = mitk::TwoPointsToPLambda ( std::pair < cv::Point3d, cv::Point3d > ( x0, x1 ) );\n  cv::Point3d Q0 = pl.first;\n  cv::Point3d v = pl.second;\n  // Method 1. Solve for shortest line joining two rays, then get midpoint.\n  // Taken from: http://geomalgorithms.com/a07-_distance.html\n  double sc, tc, a, b, c, d, e;\n  double distance;\n\n  cv::Point3d Psc;\n  cv::Point3d Qtc;\n  cv::Point3d W0;\n\n  // Difference of two origins\n\n  W0.x = P0.x - Q0.x;\n  W0.y = P0.y - Q0.y;\n  W0.z = P0.z - Q0.z;\n\n  a = u.x*u.x + u.y*u.y + u.z*u.z;\n  b = u.x*v.x + u.y*v.y + u.z*v.z;\n  c = v.x*v.x + v.y*v.y + v.z*v.z;\n  d = u.x*W0.x + u.y*W0.y + u.z*W0.z;\n  e = v.x*W0.x + v.y*W0.y + v.z*W0.z;\n  sc = (b*e - c*d) / (a*c - b*b);\n  tc = (a*e - b*d) / (a*c - b*b);\n\n  if ( boost::math::isnan(sc) || boost::math::isnan(tc) || boost::math::isinf(sc) || boost::math::isinf(tc) )\n  {\n    //lines are parallel\n    distance = mitk::DistanceToLine ( std::pair<cv::Point3d, cv::Point3d> ( P0, P0 + u ), Q0 );\n    closestPointOnSecondLine.x = std::numeric_limits<double>::quiet_NaN();\n    closestPointOnSecondLine.y = std::numeric_limits<double>::quiet_NaN();\n    closestPointOnSecondLine.z = std::numeric_limits<double>::quiet_NaN();\n    return distance;\n  }\n  Psc.x = P0.x + sc*u.x;\n  Psc.y = P0.y + sc*u.y;\n  Psc.z = P0.z + sc*u.z;\n  Qtc.x = Q0.x + tc*v.x;\n  Qtc.y = Q0.y + tc*v.y;\n  Qtc.z = Q0.z + tc*v.z;\n\n  bool QtcOnSegment = false;\n  if ( x0.x > x1.x )\n  {\n    if ( (Qtc.x < x0.x) && (Qtc.x > x1.x) )\n    {\n      QtcOnSegment = true;\n    }\n  }\n  else\n  {\n    if ( (Qtc.x > x0.x) && (Qtc.x < x1.x) )\n    {\n      QtcOnSegment = true;\n    }\n  }\n\n  if ( QtcOnSegment )\n  {\n    distance = sqrt((Psc.x - Qtc.x)*(Psc.x - Qtc.x)\n                        +(Psc.y - Qtc.y)*(Psc.y - Qtc.y)\n                        +(Psc.z - Qtc.z)*(Psc.z - Qtc.z));\n    closestPointOnSecondLine = Qtc;\n  }\n  else\n  {\n    std::pair < cv::Point3d, cv::Point3d > twoPointsOnLine1 = std::pair < cv::Point3d , cv::Point3d > ( P0, P0 + u );\n    double x0Distance = mitk::DistanceToLine ( twoPointsOnLine1, x0 );\n    double x1Distance = mitk::DistanceToLine ( twoPointsOnLine1, x1 );\n\n    if ( x0Distance < x1Distance )\n    {\n      distance = x0Distance;\n      closestPointOnSecondLine = x0;\n    }\n    else\n    {\n      distance = x1Distance;\n      closestPointOnSecondLine = x1;\n    }\n  }\n  return distance;\n}\n\n\n//-----------------------------------------------------------------------------\nstd::pair < cv::Point3d , cv::Point3d > TwoPointsToPLambda ( const std::pair < cv::Point3d , cv::Point3d >& twoPointLine )\n{\n  cv::Point3d delta = twoPointLine.first - twoPointLine.second;;\n  double length = sqrt ( ( delta.x * delta.x ) + ( delta.y * delta.y ) + (delta.z * delta.z) );\n\n  cv::Point3d u = cv::Point3d (delta.x / length, delta.y/length, delta.z/length) ;\n\n  return ( std::pair < cv::Point3d , cv::Point3d > ( twoPointLine.first, u ) );\n}\n\n//-----------------------------------------------------------------------------\ncv::Point3d CrossProduct (const cv::Point3d& p1 , const cv::Point3d& p2)\n{\n  cv::Point3d cp;\n  cp.x = p1.y * p2.z - p1.z * p2.y;\n  cp.y = p1.z * p2.x - p1.x * p2.z;\n  cp.z = p1.x * p2.y - p1.y * p2.x;\n  return cp;\n}\n\n//-----------------------------------------------------------------------------\ndouble DotProduct (const cv::Point3d& p1 , const cv::Point3d& p2)\n{\n  return p1.x * p2.x + p1.y * p2.y + p1.z * p2.z;\n}\n\n//-----------------------------------------------------------------------------\ndouble Norm (const cv::Point3d& p1)\n{\n  return sqrt ( p1.x * p1.x + p1.y * p1.y + p1.z*p1.z);\n}\n\n//-----------------------------------------------------------------------------\nclass out_of_bounds\n{\n  const double m_XLow;\n  const double m_XHigh;\n  const double m_YLow;\n  const double m_YHigh;\n  const double m_ZLow;\n  const double m_ZHigh;\n\npublic:\n  out_of_bounds ( const double& xLow, const double& xHigh, const double& yLow, const double& yHigh, const double& zLow, const double zHigh)\n  : m_XLow (xLow)\n  , m_XHigh (xHigh)\n  , m_YLow (yLow)\n  , m_YHigh (yHigh)\n  , m_ZLow (zLow)\n  , m_ZHigh (zHigh)\n  {}\n\n  bool operator () ( const cv::Point3d& point ) const\n  {\n    return ( ( point.x < m_XLow ) || ( point.x > m_XHigh )\n        || ( point.y < m_YLow ) || ( point.y > m_YHigh )\n        || ( point.z < m_ZLow ) || ( point.z > m_ZHigh ) );\n  }\n\n  bool operator () ( const std::pair < cv::Point3d, double >& point ) const\n  {\n    return ( ( point.first.x < m_XLow ) || ( point.first.x > m_XHigh )\n        || ( point.first.y < m_YLow ) || ( point.first.y > m_YHigh )\n        || ( point.first.z < m_ZLow ) || ( point.first.z > m_ZHigh ) );\n  }\n\n};\n\n//-----------------------------------------------------------------------------\nunsigned int RemoveOutliers ( std::vector <cv::Point3d>& points,\n    const double& xLow, const double& xHigh,\n    const double& yLow, const double& yHigh,\n    const double& zLow, const double& zHigh)\n{\n  unsigned int originalSize = points.size();\n  points.erase ( std::remove_if ( points.begin(), points.end(), out_of_bounds (xLow, xHigh, yLow, yHigh, zLow, zHigh )), points.end() );\n  return originalSize - points.size();\n}\n\n//-----------------------------------------------------------------------------\nunsigned int RemoveOutliers ( std::vector <std::pair < cv::Point3d, double > > & points,\n    const double& xLow, const double& xHigh,\n    const double& yLow, const double& yHigh,\n    const double& zLow, const double& zHigh)\n{\n  unsigned int originalSize = points.size();\n  points.erase ( std::remove_if ( points.begin(), points.end(), out_of_bounds (xLow, xHigh, yLow, yHigh, zLow, zHigh )), points.end() );\n  return originalSize - points.size();\n}\n\n\n\n//-----------------------------------------------------------------------------\nvoid ExtractRigidBodyParameters(const vtkMatrix4x4& matrix, mitk::Point3D& outputRodriguesRotationParameters, mitk::Point3D& outputTranslationParameters)\n{\n  cv::Matx33d rotationMatrix;\n  cv::Matx31d rotationVector;\n\n  for (int r = 0; r < 3; r++)\n  {\n    for (int c = 0; c < 3; c++)\n    {\n      rotationMatrix(r,c) = matrix.GetElement(r, c);\n    }\n  }\n  cv::Rodrigues(rotationMatrix, rotationVector);\n\n  for (int i = 0; i < 3; i++)\n  {\n    outputRodriguesRotationParameters[i] = rotationVector(i, 0);\n    outputTranslationParameters[i] = matrix.GetElement(i, 3);\n  }\n}\n\n} // end namespace\n", "meta": {"hexsha": "84ea4bd670c2cbe423eab932d7104556daf1af51", "size": 84820, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "MITK/Modules/OpenCVUtils/mitkOpenCVMaths.cxx", "max_stars_repo_name": "NifTK/NifTK", "max_stars_repo_head_hexsha": "2358b333c89ff1bba1c232eecbbcdc8003305dfe", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2018-07-28T13:36:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-01T19:17:39.000Z", "max_issues_repo_path": "MITK/Modules/OpenCVUtils/mitkOpenCVMaths.cxx", "max_issues_repo_name": "NifTK/NifTK", "max_issues_repo_head_hexsha": "2358b333c89ff1bba1c232eecbbcdc8003305dfe", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MITK/Modules/OpenCVUtils/mitkOpenCVMaths.cxx", "max_forks_repo_name": "NifTK/NifTK", "max_forks_repo_head_hexsha": "2358b333c89ff1bba1c232eecbbcdc8003305dfe", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2018-08-20T07:06:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-07T07:55:27.000Z", "avg_line_length": 30.8998178506, "max_line_length": 190, "alphanum_fraction": 0.5496227305, "num_tokens": 25563, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.45197368108095753}}
{"text": "#include <Engine/MeshEdit/MinSurf.h>\n\n#include <Engine/Primitive/TriMesh.h>\n\n#include <Eigen/Sparse>\n\nusing namespace Ubpa;\n\nusing namespace std;\nusing namespace Eigen;\n\nMinSurf::MinSurf(Ptr<TriMesh> triMesh)\n\t: heMesh(make_shared<HEMesh<V>>())\n{\n\tInit(triMesh);\n}\n\nvoid MinSurf::Clear() {\n\theMesh->Clear();\n\ttriMesh = nullptr;\n}\n\nbool MinSurf::Init(Ptr<TriMesh> triMesh) {\n\tClear();\n\n\tif (triMesh == nullptr)\n\t\treturn true;\n\n\tif (triMesh->GetType() == TriMesh::INVALID) {\n\t\tprintf(\"ERROR::MinSurf::Init:\\n\"\n\t\t\t\"\\t\"\"trimesh is invalid\\n\");\n\t\treturn false;\n\t}\n\n\t// init half-edge structure\n\tsize_t nV = triMesh->GetPositions().size();\n\tvector<vector<size_t>> triangles;\n\ttriangles.reserve(triMesh->GetTriangles().size());\n\tfor (auto triangle : triMesh->GetTriangles())\n\t\ttriangles.push_back({ triangle->idx[0], triangle->idx[1], triangle->idx[2] });\n\theMesh->Reserve(nV);\n\theMesh->Init(triangles);\n\n\tif (!heMesh->IsTriMesh() || !heMesh->HaveBoundary()) {\n\t\tprintf(\"ERROR::MinSurf::Init:\\n\"\n\t\t\t\"\\t\"\"trimesh is not a triangle mesh or hasn't a boundaries\\n\");\n\t\theMesh->Clear();\n\t\treturn false;\n\t}\n\n\t// triangle mesh's positions ->  half-edge structure's positions\n\tfor (int i = 0; i < nV; i++) {\n\t\tauto v = heMesh->Vertices().at(i);\n\t\tv->pos = triMesh->GetPositions()[i].cast_to<vecf3>();\n\t}\n\n\tthis->triMesh = triMesh;\n\treturn true;\n}\n\nbool MinSurf::Run() {\n\tif (heMesh->IsEmpty() || !triMesh) {\n\t\tprintf(\"ERROR::MinSurf::Run\\n\"\n\t\t\t\"\\t\"\"heMesh->IsEmpty() || !triMesh\\n\");\n\t\treturn false;\n\t}\n\n\tMinimize();\n\n\t// half-edge structure -> triangle mesh\n\tsize_t nV = heMesh->NumVertices();\n\tsize_t nF = heMesh->NumPolygons();\n\tvector<pointf3> positions;\n\tvector<unsigned> indice;\n\tpositions.reserve(nV);\n\tindice.reserve(3 * nF);\n\tfor (auto v : heMesh->Vertices())\n\t\tpositions.push_back(v->pos.cast_to<pointf3>());\n\tfor (auto f : heMesh->Polygons()) { // f is triangle\n\t\tfor (auto v : f->BoundaryVertice()) // vertices of the triangle\n\t\t\tindice.push_back(static_cast<unsigned>(heMesh->Index(v)));\n\t}\n\n\ttriMesh->Init(indice, positions);\n\n\treturn true;\n}\n\nvoid MinSurf::Minimize() {\n\tint nV = heMesh->NumVertices();\n\tvector<Eigen::Triplet<double> > triplets;\n\n\tfor (int i = 0; i < nV; ++i) {\n\t\tV* vi = heMesh->Vertices()[i];\n\t\ttriplets.push_back(Eigen::Triplet<double>(i, i, 1));\n\n\t\tif (!vi->IsBoundary()) {\n\t\t\tdouble adjVertexSize = vi->AdjVertices().size();\n\t\t\tfor(int j = 0; j < adjVertexSize; ++j){\n\t\t\t\ttriplets.push_back(Eigen::Triplet<double>(i, heMesh->Index(vi->AdjVertices()[j]), -1.0 / adjVertexSize));\n\t\t\t}\n\t\t}\n\t}\n\n\tEigen::SparseMatrix<double> A(nV, nV);\n\tA.setZero();\n\tA.setFromTriplets(triplets.begin(), triplets.end());\n\tEigen::SparseLU<Eigen::SparseMatrix<double>> solver;\n\tsolver.compute(A);\n\t\n\tif (solver.info() != Eigen::Success) {\n\t\tcout << \"compute is error\" << endl;\n\t\treturn;\n\t}\n\n\tEigen::VectorXd resX(nV), resY(nV), resZ(nV), bX(nV), bY(nV), bZ(nV);\n\tbX.setZero(); bY.setZero(); bZ.setZero();\n\tfor (int i = 0; i < nV; ++i) {\n\t\tV* vi = heMesh->Vertices()[i];\n\t\tif (vi->IsBoundary()) {\n\t\t\tbX(i) = vi->pos.at(0);\n\t\t\tbY(i) = vi->pos.at(1);\n\t\t\tbZ(i) = vi->pos.at(2);\n\t\t}\n\t}\n\n\tresX = solver.solve(bX);\n\tresY = solver.solve(bY);\n\tresZ = solver.solve(bZ);\n\n\tfor (int i = 0; i < nV; ++i) {\n\t\tV* vi = heMesh->Vertices()[i];\n\n\t\tvi->pos.at(0) = resX(i);\n\t\tvi->pos.at(1) = resY(i);\n\t\tvi->pos.at(2) = resZ(i);\n\t\t//cout << resX(i) << \" \" << resY(i) << \" \" << resZ(i) << endl;\n\t}\n\n\treturn;\n}\n", "meta": {"hexsha": "150fc5c2f0e948751d7b6d857793460c74c65933", "size": 3386, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Engine/MeshEdit/MinSurf.cpp", "max_stars_repo_name": "trygas/CGHomework", "max_stars_repo_head_hexsha": "2dfff76f407b8a7ba87c5ba9d12a4428708ffbbe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Engine/MeshEdit/MinSurf.cpp", "max_issues_repo_name": "trygas/CGHomework", "max_issues_repo_head_hexsha": "2dfff76f407b8a7ba87c5ba9d12a4428708ffbbe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Engine/MeshEdit/MinSurf.cpp", "max_forks_repo_name": "trygas/CGHomework", "max_forks_repo_head_hexsha": "2dfff76f407b8a7ba87c5ba9d12a4428708ffbbe", "max_forks_repo_licenses": ["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.8450704225, "max_line_length": 109, "alphanum_fraction": 0.6311281748, "num_tokens": 1118, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.45197368108095753}}
{"text": "#define PROFILING_MODE\n\n#include <CGAL/basic.h>\n#include <CGAL/point_generators_2.h>\n#include <CGAL/Periodic_4_hyperbolic_Delaunay_triangulation_2.h>\n#include <CGAL/Periodic_4_hyperbolic_Delaunay_triangulation_traits_2.h>\n#include <CGAL/Hyperbolic_octagon_translation.h>\n#include <CGAL/CORE_Expr.h>\n#include <CGAL/Cartesian.h>\n#include <CGAL/determinant.h>\n#include <CGAL/Timer.h>\n#include <CGAL/Circular_kernel_2.h>\n#include <CGAL/Algebraic_kernel_for_circles_2_2.h>\n\n#include <boost/tuple/tuple.hpp>\n#include <boost/random/linear_congruential.hpp>\n#include <boost/random/uniform_smallint.hpp>\n#include <boost/random/variate_generator.hpp>\n\ntypedef CGAL::Periodic_4_hyperbolic_Delaunay_triangulation_traits_2<>           Traits;\ntypedef Traits::FT                                                              NT;\ntypedef CGAL::Periodic_4_hyperbolic_Delaunay_triangulation_2<Traits>            Triangulation;\ntypedef CGAL::Hyperbolic_octagon_translation_matrix<NT>                         Octagon_matrix;\ntypedef Triangulation::Point                                                    Point;\ntypedef Triangulation::Vertex_handle                                            Vertex_handle;\ntypedef Traits::Side_of_original_octagon                                        Side_of_original_octagon;\ntypedef Triangulation::Face_iterator                                            Face_iterator;\n\ntypedef CGAL::Cartesian<double>::Point_2                                        Point_double;\ntypedef CGAL::Creator_uniform_2<double, Point_double >                          Creator;\n\nlong calls_apply_identity(0);\nlong calls_apply_non_identity(0);\nlong calls_append_identity(0);\nlong calls_append_non_identity(0);\n\nlong calls_predicate_identity(0);\nlong calls_predicate_non_identity(0);\ndouble time_predicate_identity(0);\ndouble time_predicate_non_identity(0);\ndouble time_remove_dp(0);\n\nint main(int argc, char** argv)\n{\n  int N, iters;\n  if(argc < 2)\n  {\n    std::cout << \"usage: \" << argv[0] << \" [number_of_points_to_insert] [optional: number_of_iterations]\" << std::endl;\n    std::cout << \"Defaulting to 100k points, 10 iterations...\" << std::endl;\n    iters = 10;\n    N = 100000;\n  } else {\n    N = atoi(argv[1]);\n    if (argc < 3)\n      iters = 10;\n    else\n      iters = atoi(argv[2]);\n  }\n\n  Side_of_original_octagon pred;\n\n  std::cout << \"---- for best results, make sure that you have compiled me in Release mode ----\" << std::endl;\n\n  double extime = 0.0;\n\n  for(int exec = 1; exec <= iters; ++exec)\n  {\n    std::vector<Point> pts;\n    CGAL::Random_points_in_disc_2<Point_double, Creator> g(0.85);\n\n    int cnt = 0;\n    do\n    {\n      Point_double pd = *(++g);\n      if(pred(pd) != CGAL::ON_UNBOUNDED_SIDE)\n      {\n        Point pt = Point(pd.x(), pd.y());\n        pts.push_back(pt);\n        ++cnt;\n      }\n    }\n    while(cnt < N);\n\n    std::cout << \"iteration \" << exec << \": inserting into triangulation (rational dummy points)... \"; std::cout.flush();\n    Triangulation tr;\n\n    CGAL::Timer tt;\n    tt.start();\n    tr.insert(pts.begin(), pts.end());\n    tt.stop();\n    std::cout << \"DONE! (# of vertices = \" << tr.number_of_vertices() << \", time = \" << tt.time() << \" secs)\" << std::endl;\n    extime += tt.time();\n\n    int bfc = 0;\n    for(Face_iterator fit = tr.faces_begin(); fit != tr.faces_end(); fit++)\n    {\n      if(!(fit->translation(0).is_identity() &&\n           fit->translation(1).is_identity() &&\n           fit->translation(2).is_identity()))\n      {\n        ++bfc;\n      }\n    }\n\n    Triangulation::size_type Nf = tr.number_of_faces();\n    double perc = double(bfc)/double(Nf) * 100.0;\n    std::cout << \"Total number of faces      : \" << Nf << std::endl;\n    std::cout << \"Faces crossing the boundary: \" << bfc << std::endl;\n    std::cout << \"Percentage                 : \" << perc << std::endl;\n\n    std::cout << \"Triangulation is valid: \" << (tr.is_valid() ? \"YES\" : \"NO\") << std::endl;\n  }\n\n  double avgtime = extime / double(iters);\n  std::cout << \"---------------------------------------\" << std::endl;\n  std::cout << \"Average execution time over \" << iters << \" iterations: \" << avgtime << \" secs\" << std::endl << std::endl;\n\n\n  std::cout << \"Calls to append resulting in     identity: \" << calls_append_identity << std::endl;\n  std::cout << \"Calls to append resulting in non-identity: \" << calls_append_non_identity << std::endl;\n  std::cout << \"Percentage                               : \" << (double(calls_append_non_identity)/double(calls_append_non_identity+calls_append_identity)*100.0) << std::endl << std::endl;\n  std::cout << \"Calls to apply  with             identity: \" << calls_apply_identity << std::endl;\n  std::cout << \"Calls to apply  with         non-identity: \" << calls_apply_non_identity << std::endl;\n  std::cout << \"Percentage                               : \" << double(calls_apply_non_identity)/(double(calls_apply_non_identity+calls_apply_identity)*100.0) << std::endl << std::endl;\n\n  std::cout << \"Predicate calls with     identity translations: \" << calls_predicate_identity << std::endl;\n  std::cout << \"Predicate calls with non-identity translations: \" << calls_predicate_non_identity << std::endl;\n  std::cout << \"Percentage                               : \" << double(calls_predicate_non_identity)/double(calls_predicate_non_identity+calls_predicate_identity)*100.0 << std::endl << std::endl;\n\n  std::cout << \"Time in predicates with     identity translations: \" << time_predicate_identity << std::endl;\n  std::cout << \"Time in predicates with non-identity translations: \" << time_predicate_non_identity << std::endl;\n  std::cout << \"Percentage                                  : \" << double(time_predicate_non_identity)/double(time_predicate_non_identity+time_predicate_identity)*100.0 << std::endl << std::endl;\n\n  std::cout << \"Time to remove dummy points                 : \" << time_remove_dp << std::endl;\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "017df9d04bae344f9f76e94c4f778135bfad16d1", "size": 5895, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Periodic_4_hyperbolic_triangulation_2/benchmark/Periodic_4_hyperbolic_triangulation_2/bench_p4ht2_insertion.cpp", "max_stars_repo_name": "ffteja/cgal", "max_stars_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 3227.0, "max_stars_repo_stars_event_min_datetime": "2015-03-05T00:19:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:20:35.000Z", "max_issues_repo_path": "Periodic_4_hyperbolic_triangulation_2/benchmark/Periodic_4_hyperbolic_triangulation_2/bench_p4ht2_insertion.cpp", "max_issues_repo_name": "ffteja/cgal", "max_issues_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 5574.0, "max_issues_repo_issues_event_min_datetime": "2015-03-05T00:01:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:08:11.000Z", "max_forks_repo_path": "Periodic_4_hyperbolic_triangulation_2/benchmark/Periodic_4_hyperbolic_triangulation_2/bench_p4ht2_insertion.cpp", "max_forks_repo_name": "ffteja/cgal", "max_forks_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1274.0, "max_forks_repo_forks_event_min_datetime": "2015-03-05T00:01:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:47:56.000Z", "avg_line_length": 42.7173913043, "max_line_length": 195, "alphanum_fraction": 0.6179813401, "num_tokens": 1469, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.757794360334681, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.45197367455600307}}
{"text": "#ifndef OCCGRID_HPP\n#define OCCGRID_HPP\n// c\n#include <cmath>\n#include <cassert>\n\n// std\n#include <algorithm>\n#include <iostream>\n#include <stdexcept>\n\n// 3rd party\n#include <boost/math/constants/constants.hpp>\n#include <gtest/gtest.h>\n#include <opencv2/opencv.hpp>\n\n#include \"OccupancyGrid/occgrid.h\"\n#include \"OccupancyGrid/raytrace.hpp\"\n\n#undef DEBUG\n\nnamespace bconst = boost::math::constants;\n\ntemplate <typename real_type, typename int_type>\nconst uint8_t OccupancyGrid2D<real_type, int_type>::OCCUPIED = 0;\n\ntemplate <typename real_type, typename int_type>\nconst uint8_t OccupancyGrid2D<real_type, int_type>::FREE = 255;\n\ntemplate <typename real_t, typename int_t>\nreal_t OccupancyGrid2D<real_t, int_t>::nearest_neighbor_distance(\n    cv::Vec<real_t, 2> position,\n    real_t max_range,\n    cv::Vec<int_t, 2>& nearest_neighbor) \n{\n  int_t i = static_cast<int_t>(floor(position(0) - min_pt_(0) / cell_size_(0)));\n  int_t j = static_cast<int_t>(floor(position(1) - min_pt_(1) / cell_size_(1)));\n  int_t max_range_x = static_cast<int_t>(floor(max_range / cell_size_(0)));\n  std::vector<cv::Vec<int_t, 2> > manhattan_neighbours;\n  for (int_t r = 0; r < max_range_x; r ++) {\n      for (int_t xt = max(i - r, 0); xt <= min(i + r, og_.size[0]-1); xt++) {\n\n\t  int_t ry = \n\t    static_cast<int_t>(\n\t\tfloor(((r - fabs(xt - i))* cell_size_(0)) / cell_size_(1)));\n\n\t  // y has only two possible values\n\t  for (int_t yt = j - ry; yt <= j + ry; yt += ((2*ry <= 0) ? 1 : 2*ry)) {\n\t      //if (DEBUG)\n        // printf(\"(%d, %d), r: %d\\n\", xt, yt, r);\n\t      if (yt >= og_.size[1] || yt < 0)\n          continue;\n\n\t      if (is_occupied(xt, yt)) {\n            manhattan_neighbours.push_back(\n                cv::Vec<int_t, 2>(xt, yt));\n            //if (DEBUG)\n            //  printf(\"^^^^^^^^^^^^^^^^^^^\\n\");\n        }\n\t  }\n      }\n      if (manhattan_neighbours.size() > 0) {\n\t  break;\n      }\n  }\n  real_t min_distance = std::numeric_limits<double>::infinity();\n  for (typename std::vector<cv::Vec<int_t, 2> >::iterator it = \n      manhattan_neighbours.begin() ;\n      it != manhattan_neighbours.end(); ++it) \n    {\n      cv::Vec<real_t, 2> cell_mid_pt = *it;\n      cell_mid_pt += cv::Vec<real_t, 2>(0.5, 0.5);\n      cell_mid_pt = cell_mid_pt.mul(cell_size_);\n      cell_mid_pt += min_pt_;\n      real_t dist = cv::norm(cell_mid_pt - position);\n      if (min_distance > dist) {\n          min_distance = dist;\n          nearest_neighbor = *it;\n      }\n#ifdef DEBUG\n        printf(\"Neigbors: (%d, %d), %f\\n\", (*it)(0), (*it)(1), dist);\n#endif\n    }\n  return min_distance;\n}\n\ntemplate <typename real_t, typename int_t>\nreal_t OccupancyGrid2D<real_t, int_t>::ray_trace(\n    real_t px, \n    real_t py,\n    real_t ptheta,\n    real_t max_range,\n    cv::Vec<real_t, 2>& final_pos,\n    bool& reflectance) \n{\n  real_t dx = cos(ptheta);\n  real_t dy = sin(ptheta);\n\n  occgrid::ray_trace_iterator<real_t, int_t> ray_trace_it(\n      px, py, dx, dy, min_pt_(0), min_pt_(1),\n      cell_size_(0), cell_size_(1));\n\n  real_t dirmag = sqrt(dx*dx + dy*dy); \n  real_t n = floor(max_range * fabs(dx) / dirmag / cell_size_(0)) \n    + floor(max_range * fabs(dy) / dirmag / cell_size_(1));\n  int maxsizex = og_.size[0];\n  int maxsizey = og_.size[1];\n\n  for (;n > 0; --n, ++ray_trace_it) {\n\n      int i = ray_trace_it->first;\n      int j = ray_trace_it->second;\n\n#ifdef DEBUG\n      printf(\"(%d, %d), (%f, %f)\\n\", i, j, tx, ty);\n#endif\n\n\n      if (i < 0 ||  j < 0 || i >= maxsizex || j >= maxsizey ||\n          //(og_.at<uint8_t>(i, j) != FREE)) \n          is_occupied(i, j))\n        {\n          std::pair<real_t, real_t> final_pos_pair = ray_trace_it.real_position();\n          final_pos(0) = final_pos_pair.first;\n          final_pos(1) = final_pos_pair.second;\n\n          real_t disp_x = final_pos(0) - px;\n          real_t disp_y = final_pos(1) - py;\n          reflectance = true;\n          return sqrt(disp_x * disp_x + disp_y * disp_y);\n      }\n  }\n  reflectance = false;\n  return max_range;\n}\n\n#endif // OCCGRID_HPP\n", "meta": {"hexsha": "07b88aa9cd3dc917223a10242cff22d131d192b6", "size": 3986, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/OccupancyGrid/occgrid.hpp", "max_stars_repo_name": "wecacuee/modern-occupancy-grid", "max_stars_repo_head_hexsha": "c1405847dd715aec25ba416667fa4999d99d5b72", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 21.0, "max_stars_repo_stars_event_min_datetime": "2015-03-14T16:24:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-17T05:39:06.000Z", "max_issues_repo_path": "include/OccupancyGrid/occgrid.hpp", "max_issues_repo_name": "wecacuee/modern-occupancy-grid", "max_issues_repo_head_hexsha": "c1405847dd715aec25ba416667fa4999d99d5b72", "max_issues_repo_licenses": ["Apache-2.0"], "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/OccupancyGrid/occgrid.hpp", "max_forks_repo_name": "wecacuee/modern-occupancy-grid", "max_forks_repo_head_hexsha": "c1405847dd715aec25ba416667fa4999d99d5b72", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2015-08-10T02:02:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-20T12:20:29.000Z", "avg_line_length": 28.884057971, "max_line_length": 82, "alphanum_fraction": 0.6013547416, "num_tokens": 1237, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.45195353470803457}}
{"text": "/*\n * Copyright (C) 2016-2019 Istituto Italiano di Tecnologia (IIT)\n *\n * This software may be modified and distributed under the terms of the\n * BSD 3-Clause license. See the accompanying LICENSE file for details.\n */\n\n#include <iostream>\n#include <memory>\n\n#include <BayesFilters/BootstrapCorrection.h>\n#include <BayesFilters/DrawParticles.h>\n#include <BayesFilters/GaussianLikelihood.h>\n#include <BayesFilters/InitSurveillanceAreaGrid.h>\n#include <BayesFilters/SimulatedLinearSensor.h>\n#include <BayesFilters/SimulatedStateModel.h>\n#include <BayesFilters/Resampling.h>\n#include <BayesFilters/SIS.h>\n#include <BayesFilters/WhiteNoiseAcceleration.h>\n#include <BayesFilters/utils.h>\n#include <Eigen/Dense>\n\nusing namespace bfl;\nusing namespace Eigen;\n\n\nclass SISSimulation : public SIS\n{\npublic:\n    SISSimulation\n    (\n        unsigned int num_particle,\n        std::size_t state_size,\n        unsigned int simulation_steps,\n        std::unique_ptr<ParticleSetInitialization> initialization,\n        std::unique_ptr<PFPrediction> prediction,\n        std::unique_ptr<PFCorrection> correction,\n        std::unique_ptr<Resampling> resampling\n    ) noexcept :\n        SIS(num_particle, state_size, std::move(initialization), std::move(prediction), std::move(correction), std::move(resampling)),\n        simulation_steps_(simulation_steps)\n    { }\n\nprotected:\n    bool runCondition() override\n    {\n        if (getFilteringStep() < simulation_steps_)\n            return true;\n        else\n            return false;\n    }\n\nprivate:\n    unsigned int simulation_steps_;\n};\n\n\nint main()\n{\n    std::cout << \"Running a SIS particle filter on a simulated target.\" << std::endl;\n    std::cout << \"Data is logged in the test folder with prefix testSIS.\" << std::endl;\n\n    /* A set of parameters needed to run a SIS particle filter in a simulated environment. */\n    double surv_x = 1000.0;\n    double surv_y = 1000.0;\n    unsigned int num_particle_x = 100;\n    unsigned int num_particle_y = 100;\n    unsigned int num_particle = num_particle_x * num_particle_y;\n    Vector4d initial_state(10.0f, 0.0f, 10.0f, 0.0f);\n    unsigned int simulation_time = 100;\n    std::size_t state_size = 4;\n\n    /* Step 1 - Initialization */\n    /* Initialize initialization class. */\n    std::unique_ptr<ParticleSetInitialization> grid_initialization = utils::make_unique<InitSurveillanceAreaGrid>(surv_x, surv_y, num_particle_x, num_particle_y);\n\n\n    /* Step 2 - Prediction */\n    /* Step 2.1 - Define the state model */\n    /* Initialize a white noise acceleration state model. */\n    double T = 1.0f;\n    double tilde_q = 10.0f;\n\n    std::unique_ptr<StateModel> wna = utils::make_unique<WhiteNoiseAcceleration>(T, tilde_q);\n\n    /* Step 2.2 - Define the prediction step */\n    /* Initialize the particle filter prediction step and pass the ownership of the state model. */\n    std::unique_ptr<PFPrediction> pf_prediction = utils::make_unique<DrawParticles>();\n    pf_prediction->setStateModel(std::move(wna));\n\n\n    /* Step 3 - Correction */\n    /* Step 3.1 - Define where the measurement are originated from (either simulated or from a real process) */\n    /* Initialize simulaterd target model with a white noise acceleration. */\n    std::unique_ptr<StateModel> target_model = utils::make_unique<WhiteNoiseAcceleration>(T, tilde_q);\n    std::unique_ptr<SimulatedStateModel> simulated_state_model = utils::make_unique<SimulatedStateModel>(std::move(target_model), initial_state, simulation_time);\n    simulated_state_model->enable_log(\".\", \"testSIS\");\n\n    /* Initialize a measurement model (a linear sensor reading x and y coordinates). */\n    std::unique_ptr<MeasurementModel> simulated_linear_sensor = utils::make_unique<SimulatedLinearSensor>(std::move(simulated_state_model));\n    simulated_linear_sensor->enable_log(\".\", \"testSIS\");\n\n\n    /* Step 3.3 - Define the likelihood model */\n    /* Initialize the the exponential likelihood, a PFCorrection decoration of the particle filter correction step. */\n    std::unique_ptr<LikelihoodModel> exp_likelihood = utils::make_unique<GaussianLikelihood>();\n\n    /* Step 3.4 - Define the correction step */\n    /* Initialize the particle filter correction step and pass the ownership of the measurement model. */\n    std::unique_ptr<PFCorrection> pf_correction = utils::make_unique<BoostrapCorrection>();\n    pf_correction->setLikelihoodModel(std::move(exp_likelihood));\n    pf_correction->setMeasurementModel(std::move(simulated_linear_sensor));\n\n\n    /* Step 4 - Resampling */\n    /* Initialize a resampling algorithm */\n    std::unique_ptr<Resampling> resampling = utils::make_unique<Resampling>();\n\n\n    /* Step 5 - Assemble the particle filter */\n    std::cout << \"Constructing SIS particle filter...\" << std::flush;\n    SISSimulation sis_pf(num_particle, state_size, simulation_time, std::move(grid_initialization), std::move(pf_prediction), std::move(pf_correction), std::move(resampling));\n    sis_pf.enable_log(\".\", \"testSIS\");\n    std::cout << \"done!\" << std::endl;\n\n\n    /* Step 6 - Prepare the filter to be run */\n    std::cout << \"Booting SIS particle filter...\" << std::flush;\n    sis_pf.boot();\n    std::cout << \"completed!\" << std::endl;\n\n\n    /* Step 7 - Run the filter and wait until it is closed */\n    /* Note that since this is a simulation, the filter will end upon simulation termination */\n    std::cout << \"Running SIS particle filter...\" << std::flush;\n    sis_pf.run();\n    std::cout << \"waiting...\" << std::flush;\n    if (!sis_pf.wait())\n        return EXIT_FAILURE;\n    std::cout << \"completed!\" << std::endl;\n\n\n    return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "6c219249e54ba0af1162f0734af07c8b852ec969", "size": 5589, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_SIS/main.cpp", "max_stars_repo_name": "vesor/bayes-filters-lib", "max_stars_repo_head_hexsha": "24cfbed786a017f7aebb5bf3ace3694d4f7d5f66", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-05-27T02:52:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-10T07:06:39.000Z", "max_issues_repo_path": "test/test_SIS/main.cpp", "max_issues_repo_name": "vesor/bayes-filters-lib", "max_issues_repo_head_hexsha": "24cfbed786a017f7aebb5bf3ace3694d4f7d5f66", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_SIS/main.cpp", "max_forks_repo_name": "vesor/bayes-filters-lib", "max_forks_repo_head_hexsha": "24cfbed786a017f7aebb5bf3ace3694d4f7d5f66", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-14T08:20:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-14T08:20:28.000Z", "avg_line_length": 38.5448275862, "max_line_length": 175, "alphanum_fraction": 0.7074610843, "num_tokens": 1344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.45195353470803457}}
{"text": "#ifndef OTHELLO_AI_QLEARNINGPLAYER_HPP\n#define OTHELLO_AI_QLEARNINGPLAYER_HPP\n\n//Boost headers:\n#include <boost/random.hpp>\n//FANN headers:\n#include <fann/doublefann.h>\n#include <fann/fann_cpp.h>\n//Othello headers:\n#include <othello/ai/ILearningPlayer.hpp>\n#include <othello/game/Game.hpp>\n\n\nnamespace othello\n{\n    \n    namespace ai\n    {\n        \n        ////////////////////////////////////////////////////////////////\n        /// \\class QLearningPlayer\n        ///\n        /// \\brief A learning AI player that plays moves using Q\n        ///        Learning and a multilayer perceptron neural network\n        ///\n        ////////////////////////////////////////////////////////////////\n        class QLearningPlayer : public ILearningPlayer\n        {\n            private:\n                \n                ////////////////////////////////////////////////////////////////\n                /// \\brief Whether the player is in training mode\n                ///\n                ////////////////////////////////////////////////////////////////\n                bool training;\n                \n                \n                ////////////////////////////////////////////////////////////////\n                /// \\brief A mersenne_twister_engine for generating random\n                ///        numbers\n                ///\n                ////////////////////////////////////////////////////////////////\n                boost::random::mt19937 randomNumberGenerator;\n                \n                \n                ////////////////////////////////////////////////////////////////\n                /// \\brief Static multilayer perceptron network\n                ///\n                /// The network is static so that multiple agents share the same\n                /// network (for self-learning)\n                ///\n                ////////////////////////////////////////////////////////////////\n                static FANN::neural_net mlp;\n                \n                \n                ////////////////////////////////////////////////////////////////\n                /// \\struct TurnState\n                ///\n                /// \\brief Structure representing the state of the player at a\n                ///        certain turn in the game\n                ///\n                ////////////////////////////////////////////////////////////////\n                struct TurnState\n                {\n                    \n                    ////////////////////////////////////////////////////////////////\n                    /// \\brief The state of the board as an input into the NN\n                    ///\n                    ////////////////////////////////////////////////////////////////\n                    std::array<fann_type, game::Board::BOARD_SIZE * game::Board::BOARD_SIZE> input;\n                    \n                    \n                    ////////////////////////////////////////////////////////////////\n                    /// \\brief The index in output of the valid move with the\n                    ///        highest intensity\n                    ///\n                    ////////////////////////////////////////////////////////////////\n                    std::size_t playedMove;\n                    \n                    \n                    ////////////////////////////////////////////////////////////////\n                    /// \\brief The Q value of the state\n                    ///\n                    ////////////////////////////////////////////////////////////////\n                    fann_type QVal;\n                    \n                    \n                    ////////////////////////////////////////////////////////////////\n                    /// \\brief Class constructor\n                    ///\n                    ////////////////////////////////////////////////////////////////\n                    TurnState(std::array<fann_type, game::Board::BOARD_SIZE * game::Board::BOARD_SIZE> input,\n                              const std::size_t& playedMove, const fann_type& QVal)\n                            : input(input), playedMove(playedMove), QVal(QVal) {}\n                    \n                };\n                \n                \n                ////////////////////////////////////////////////////////////////\n                /// \\brief A vector containing the turn states of the on-going\n                ///        game\n                ///\n                ////////////////////////////////////////////////////////////////\n                std::vector<TurnState> states;\n                \n                \n                ////////////////////////////////////////////////////////////////\n                /// \\brief The discount factor\n                ///\n                ////////////////////////////////////////////////////////////////\n                const fann_type discountFactor = 1.0;\n                \n                \n                ////////////////////////////////////////////////////////////////\n                /// \\brief The probability for the network to pick a random\n                ///        action\n                ///\n                ////////////////////////////////////////////////////////////////\n                fann_type epsilon = 0.1;\n                \n                \n                ////////////////////////////////////////////////////////////////\n                /// \\brief The amount that epsilon should change every training\n                ///        cycle\n                ///\n                ////////////////////////////////////////////////////////////////\n                fann_type deltaEpsilon;\n            \n            \n            public:\n                \n                ////////////////////////////////////////////////////////////////\n                /// \\brief Class constructor\n                ///\n                /// \\param training Whether the player should be in training\n                ///        mode\n                /// \\param seed The seed to be used for random numbers\n                /// \\param numCycles The number of training cycles. Can be 0.\n                /// \\param numHiddenLayers The number of hidden layers\n                /// \\param numHiddenNeurons The number of neurons in each hidden\n                ///        layer\n                /// \\param discountFactor The discount factor (how much it\n                ///        discounts later rewards)\n                /// \\param learningRate How fast the values in the neural\n                ///        network change\n                /// \\param epsilon The probability of the player to select\n                ///        random moves during testing. Decreases linerarly over\n                ///        the course of training\n                ///\n                ////////////////////////////////////////////////////////////////\n                QLearningPlayer(const bool& training, const unsigned int& seed,\n                        const unsigned int& numCycles, const unsigned int& numHiddenLayers,\n                        const unsigned int& numHiddenNeurons, const fann_type& discountFactor,\n                        const fann_type& learningRate, const fann_type& epsilon);\n                \n                \n                ////////////////////////////////////////////////////////////////\n                /// \\brief Function that is called when the player should make a\n                ///        move. This function uses a neural network to make a\n                ///        decision\n                ///\n                /// \\param game A const reference to the game to make a move in\n                /// \\param player The index of this player in the game. (0 is\n                ///        player 1, 1 is player 2)\n                /// \\param possibleMoves A vector of the possible moves\n                ///\n                /// \\return A const pointer to a const move that will be played\n                ///         by the current player. This pointer must point to a\n                ///         move in possibleMoves\n                ///\n                ////////////////////////////////////////////////////////////////\n                const game::Move* makeMove(const game::Game& game, const uint8_t& player,\n                                           const std::vector<game::Move>& possibleMoves) override;\n                \n                \n                ////////////////////////////////////////////////////////////////\n                /// \\brief Virtual function that is called when a game finishes\n                ///\n                ////////////////////////////////////////////////////////////////\n                void gameFinished(const game::Game&, const uint8_t&) override;\n                \n                \n                ////////////////////////////////////////////////////////////////\n                /// \\brief Function to either enable or disable training the\n                ///        player\n                ///\n                /// \\param trainingMode Whether to enable or disable training\n                ///\n                ////////////////////////////////////////////////////////////////\n                void setTraining(const bool& trainingMode) override;\n            \n        };\n        \n    }\n    \n}\n\n#endif //OTHELLO_AI_QLEARNINGPLAYER_HPP\n", "meta": {"hexsha": "92245289b973a87dea59e99ed3b867a439d5eb41", "size": 9186, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/othello/ai/QLearningPlayer.hpp", "max_stars_repo_name": "Orfby/Othello-MMP", "max_stars_repo_head_hexsha": "72be0ee38a329eff536b17d1e5334353cfd58c6f", "max_stars_repo_licenses": ["MIT"], "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/othello/ai/QLearningPlayer.hpp", "max_issues_repo_name": "Orfby/Othello-MMP", "max_issues_repo_head_hexsha": "72be0ee38a329eff536b17d1e5334353cfd58c6f", "max_issues_repo_licenses": ["MIT"], "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/othello/ai/QLearningPlayer.hpp", "max_forks_repo_name": "Orfby/Othello-MMP", "max_forks_repo_head_hexsha": "72be0ee38a329eff536b17d1e5334353cfd58c6f", "max_forks_repo_licenses": ["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.1608040201, "max_line_length": 109, "alphanum_fraction": 0.3141737427, "num_tokens": 1246, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.45195352913461323}}
{"text": "#include \"catch.hpp\"\n\n#include <vector>\n\n#include <libArrhenius/Integration/ArrheniusIntegral.hpp>\n\n#include \"fakeit.hpp\"\n\nusing namespace libArrhenius;\nusing namespace libArrhenius::Constants;\n\nTEST_CASE(\"ArrheniusIntegral Usage\", \"[integral]\")\n{\n  double              tau = 2;\n  double              dt  = tau / 20;\n  size_t              N   = 4 * tau / dt;\n  std::vector<double> t(N), T(N);\n\n  for (size_t i = 0; i < t.size(); i++) {\n    t[i] = dt * i;\n    T[i] = 310;\n    if (t[i] > tau / 2) T[i] = 100 + 310;\n    if (t[i] > tau + tau / 2) T[i] = 310;\n  }\n\n  double A, Ea, Omega;\n\n  A  = 3.1e99;\n  Ea = 6.28e5;\n\n  SECTION(\"Trapezoid\")\n  {\n    ArrheniusIntegral<double> Arr(A, Ea);\n\n    Omega = Arr(N, t.data(), T.data());\n    CHECK(Omega == Approx(A * exp(-Ea / (MKS::R * 410)) * tau +\n                          A * exp(-Ea / (MKS::R * 310)) * 3 * tau));\n\n    A  = 2.00e30;\n    Ea = 2.00e5;\n\n    Arr.setA(A);\n    Arr.setEa(Ea);\n\n    Omega = Arr(N, t.data(), T.data());\n\n    CHECK(Omega == Approx(A * exp(-Ea / (MKS::R * 410)) * tau +\n                          A * exp(-Ea / (MKS::R * 310)) * 3 * tau)\n                       .epsilon(0.0001));\n\n    // this will result in a number too small for double\n    A  = 2.00e30;\n    Ea = 2.00e10;\n\n    Arr.setA(A);\n    Arr.setEa(Ea);\n\n    Omega = Arr(N, t.data(), T.data());\n\n    CHECK(Omega == 0);\n\n    // this will result in a number too large for double\n    A  = 2.00e300;\n    Ea = -2.00e5;\n\n    Arr.setA(A);\n    Arr.setEa(Ea);\n\n    Omega = Arr(N, t.data(), T.data());\n\n    CHECK(Omega == std::numeric_limits<double>::infinity());\n  }\n}\n\nTEST_CASE(\"ArrheniusIntegral Large Profile\", \"[integral]\")\n{\n  double A, Ea, Omega;\n\n  A  = 3.1e99;\n  Ea = 6.28e5;\n\n  ArrheniusIntegral<double> Arr(A, Ea);\n\n  // create a data set that will trigger parallelization.\n  double              tau = 2;\n  double              dt  = tau / 200;\n  size_t              N   = 1000;\n  std::vector<double> t(N), T(N);\n\n  SECTION(\"Constant Temperature\")\n  {\n    for (size_t i = 0; i < t.size(); i++) {\n      t[i] = dt * i;\n      T[i] = 310;\n      if (t[i] > tau / 2) T[i] = 100 + 310;\n      if (t[i] > tau + tau / 2) T[i] = 310;\n    }\n\n    double Exact = A * exp(-Ea / (MKS::R * 410)) * tau + A * exp(-Ea / (MKS::R * 310)) * 3 * tau;\n\n    SECTION(\"Trapezoid\")\n    {\n      ArrheniusIntegral<double, Trapezoid> Arr(A, Ea);\n      Omega = Arr(N, t.data(), T.data());\n      CHECK(Omega == Approx(Exact));\n    }\n    SECTION(\"Exponential Integral\")\n    {\n      ArrheniusIntegral<double, ExponentialIntegral> Arr(A, Ea);\n      Omega = Arr(N, t.data(), T.data());\n      CHECK(Omega == Approx(Exact).epsilon(0.05));\n    }\n  }\n\n  SECTION(\"Linear Temperature\")\n  {\n    for (size_t i = 0; i < t.size(); i++) {\n      t[i] = dt * i;\n      T[i] = 310 + t[i];\n    }\n\n    double t0 = t[0];\n    double t1 = t[t.size()-1];\n    double T0 = T[0];\n    double T1 = T[T.size()-1];\n    double Exact = A*(t1-t0)/(T1-T0)*( T1*boost::math::expint(2,Ea/(MKS::R * T1)) - T0*boost::math::expint(2,Ea/(MKS::R * T0)) );\n\n    SECTION(\"Trapezoid\")\n    {\n      ArrheniusIntegral<double, Trapezoid> Arr(A, Ea);\n      Omega = Arr(N, t.data(), T.data());\n      CHECK(Omega == Approx(Exact));\n    }\n    SECTION(\"Exponential Integral\")\n    {\n      ArrheniusIntegral<double, ExponentialIntegral> Arr(A, Ea);\n      Omega = Arr(N, t.data(), T.data());\n      CHECK(Omega == Approx(Exact));\n    }\n  }\n}\n\n#include <boost/multiprecision/cpp_dec_float.hpp>\nusing namespace boost::multiprecision;\n\nTEST_CASE(\"ArrheniusIntegral With Boost.Multiprecision\", \"[integral]\")\n{\n  // doesn't seem to work on Ubuntu with boost 1.57\n  // complains about the convert_to<>() calls...\n  cpp_dec_float_100              tau = 2;\n  cpp_dec_float_100              dt  = tau / 20;\n  size_t                         N   = (4 * tau / dt).convert_to<size_t>();\n  std::vector<cpp_dec_float_100> t(N), T(N);\n\n  for (size_t i = 0; i < t.size(); i++) {\n    t[i] = dt * i;\n    T[i] = 310;\n    if (t[i] > tau / 2) T[i] = 100 + 310;\n    if (t[i] > tau + tau / 2) T[i] = 310;\n  }\n\n  cpp_dec_float_100 A, Ea, Omega;\n\n  A  = 3.1e99;\n  Ea = 6.28e5;\n\n  ArrheniusIntegral<cpp_dec_float_100> Arr(A, Ea);\n\n  Omega = Arr(N, t.data(), T.data());\n  CHECK(Omega.convert_to<double>() ==\n        Approx((A * exp(-Ea / (MKS::R * 410)) * tau +\n                A * exp(-Ea / (MKS::R * 310)) * 3 * tau)\n                   .convert_to<double>()));\n\n  A  = 2.00e30;\n  Ea = 2.00e5;\n\n  Arr.setA(A);\n  Arr.setEa(Ea);\n\n  Omega = Arr(N, t.data(), T.data());\n\n  CHECK(Omega.convert_to<double>() ==\n        Approx((A * exp(-Ea / (MKS::R * 410)) * tau +\n                A * exp(-Ea / (MKS::R * 310)) * 3 * tau)\n                   .convert_to<double>())\n            .epsilon(0.001));\n\n  A  = 2.00e30;\n  Ea = 2.00e10;\n\n  Arr.setA(A);\n  Arr.setEa(Ea);\n\n  Omega = Arr(N, t.data(), T.data());\n\n  CHECK(Omega > 0);\n\n  // this will result in a number too large for double\n  A  = 2.00e300;\n  Ea = -2.00e5;\n\n  Arr.setA(A);\n  Arr.setEa(Ea);\n\n  Omega = Arr(N, t.data(), T.data());\n\n  CHECK(Omega != std::numeric_limits<cpp_dec_float_100>::infinity());\n}\n", "meta": {"hexsha": "fbfe870af0af807eec0a1b5c545a5ddea00844a2", "size": 5053, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "testing/CatchTests/ArrheniusIntegral_Tests.cpp", "max_stars_repo_name": "CD3/libArrhenius", "max_stars_repo_head_hexsha": "2cf65c9935c1661c6150ddfd86a999cf2fff2691", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "testing/CatchTests/ArrheniusIntegral_Tests.cpp", "max_issues_repo_name": "CD3/libArrhenius", "max_issues_repo_head_hexsha": "2cf65c9935c1661c6150ddfd86a999cf2fff2691", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "testing/CatchTests/ArrheniusIntegral_Tests.cpp", "max_forks_repo_name": "CD3/libArrhenius", "max_forks_repo_head_hexsha": "2cf65c9935c1661c6150ddfd86a999cf2fff2691", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.0619047619, "max_line_length": 129, "alphanum_fraction": 0.5187017613, "num_tokens": 1717, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.45195352913461323}}
{"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 \"LevenbergMarquardt.h\"\n#include <Eigen/Dense>\n#include <unsupported/Eigen/NonLinearOptimization>\n\nnamespace Scine {\nnamespace Utils {\n\nvoid LevenbergMarquardt::optimize(Eigen::VectorXd& parameters, UpdateFunctionManagerBase& updateFunctionManager) {\n  LMFunctor functor(updateFunctionManager);\n  functor.n = static_cast<int>(parameters.size());\n  functor.m = functor.updateFunctionManager_.getNumberOfDataPoints(parameters);\n  Eigen::LevenbergMarquardt<LMFunctor, double> lm(functor);\n  // Set maximum number of function evaluations if it was set to a sensible value\n  if (maxFuncEval > 0)\n    lm.parameters.maxfev = maxFuncEval;\n  lm.minimize(parameters);\n  // Calculate and update covariance matrix if desired\n  if (calculateCovarianceMatrix) {\n    auto hessian = lm.fjac.transpose() * lm.fjac;\n    auto inverseHessian = hessian.inverse();\n    auto variance = (1.0 / (functor.m - functor.n + 1.0)) * lm.fvec.squaredNorm();\n    covarianceMatrix_ = variance * inverseHessian;\n  }\n}\n\nLevenbergMarquardt::LMFunctor::LMFunctor(UpdateFunctionManagerBase& updateFunctionManager)\n  : updateFunctionManager_(updateFunctionManager) {\n}\n\n// Compute 'm' errors, one for each data point, for the given parameter values in 'x'\nint LevenbergMarquardt::LMFunctor::operator()(const Eigen::VectorXd& parameters, Eigen::VectorXd& fvec) const {\n  updateFunctionManager_.updateErrors(parameters, fvec);\n  return 0;\n}\n\n// Compute the Jacobian of the errors\nint LevenbergMarquardt::LMFunctor::df(const Eigen::VectorXd& parameters, Eigen::MatrixXd& fjac) const {\n  updateFunctionManager_.updateJacobian(parameters, fjac);\n  return 0;\n}\n\n// Returns 'm', the number of values.\nint LevenbergMarquardt::LMFunctor::values() const {\n  return m;\n}\n\n// Returns 'n', the number of inputs.\nint LevenbergMarquardt::LMFunctor::inputs() const {\n  return n;\n}\n\nconst Eigen::MatrixXd& LevenbergMarquardt::getCovarianceMatrix() {\n  return covarianceMatrix_;\n}\n\n} // namespace Utils\n} // namespace Scine", "meta": {"hexsha": "dcefd235f4e7e990c1ed1fea4014b36d03e2140f", "size": 2191, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Utils/Utils/Optimizer/LeastSquares/LevenbergMarquardt.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/Optimizer/LeastSquares/LevenbergMarquardt.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/Optimizer/LeastSquares/LevenbergMarquardt.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.234375, "max_line_length": 114, "alphanum_fraction": 0.7485166591, "num_tokens": 564, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.45195352913461323}}
{"text": "//==================================================================================================\n/**\n  Copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n**/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_COMMON_DETAIL_SCALAR_EXPO_BASE_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_DETAIL_SCALAR_EXPO_BASE_HPP_INCLUDED\n\n#ifndef BOOST_SIMD_NO_INVALIDS\n#include <boost/simd/function/is_nan.hpp>\n#endif\n#include <boost/simd/arch/common/detail/scalar/expo_reduction.hpp>\n#include <boost/simd/arch/common/detail/tags.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/function/ldexp.hpp>\n#include <boost/simd/function/toint.hpp>\n#include <boost/simd/detail/dispatch/meta/scalar_of.hpp>\n#include <boost/config.hpp>\n\nnamespace boost { namespace simd { namespace detail\n{\n  template< typename A0\n          , typename Tag\n          , typename Style\n          , typename base_A0 = bd::scalar_of_t<A0>\n          >\n  struct exponential\n  {};\n\n  template<typename A0, typename Tag>\n  struct exponential< A0, Tag, tag::not_simd_type, double>\n  {\n    typedef exp_reduction<A0,Tag>                        reduc_t;\n    // compute exp(ax) where a is 1, 2 or ten depending on Tag\n    static BOOST_FORCEINLINE A0 expa(A0 a0) BOOST_NOEXCEPT\n    {\n      if (reduc_t::isgemaxlog(a0)) return Inf<A0>();\n      if (reduc_t::isleminlog(a0)) return Zero<A0>();\n     #ifndef BOOST_SIMD_NO_INVALIDS\n      if (is_nan(a0)) return a0;\n     #endif\n      A0 hi = Zero<A0>(), lo = Zero<A0>(), x = Zero<A0>();\n      A0 k = reduc_t::reduce(a0, hi, lo, x);\n      A0 c = reduc_t::approx(x);\n      c = reduc_t::finalize(x, c, hi, lo);\n      return  ldexp(c, toint(k));\n    }\n  };\n\n  template<typename A0, typename Tag>\n  struct exponential< A0, Tag, tag::not_simd_type, float>\n  {\n    typedef exp_reduction<A0,Tag>                        reduc_t;\n    // compute exp(ax) where a is 1, 2 or ten depending on Tag\n    static BOOST_FORCEINLINE A0 expa(A0 a0) BOOST_NOEXCEPT\n    {\n\n      if (reduc_t::isgemaxlog(a0)) return Inf<A0>();\n      if (reduc_t::isleminlog(a0)) return Zero<A0>();\n    #ifndef BOOST_SIMD_NO_INVALIDS\n      if (is_nan(a0)) return a0;\n    #endif\n      A0 x;\n      A0 k = reduc_t::reduce(a0, x);\n      x = reduc_t::approx(x);\n      return  ldexp(x, toint(k));\n    }\n  };\n} } }\n#endif\n", "meta": {"hexsha": "b890c61cbda9c53a33f449f4a220b92bc004227a", "size": 2512, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/detail/scalar/expo_base.hpp", "max_stars_repo_name": "SylvainCorlay/pythran", "max_stars_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-02-25T22:23:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T15:13:12.000Z", "max_issues_repo_path": "third_party/boost/simd/arch/common/detail/scalar/expo_base.hpp", "max_issues_repo_name": "SylvainCorlay/pythran", "max_issues_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/arch/common/detail/scalar/expo_base.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 33.4933333333, "max_line_length": 100, "alphanum_fraction": 0.6086783439, "num_tokens": 668, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4519535291346132}}
{"text": "/** @file\n    @brief Implementation\n\n    @date 2015-2020\n\n    @author\n    Sensics, Inc.\n    <http://sensics.com/osvr>\n*/\n\n// Copyright 2015 Sensics, Inc.\n// Copyright 2019-2020 Collabora, Ltd.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//        http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <iostream>\n\n#if 0\ntemplate <typename T>\ninline void dumpKalmanDebugOuput(const char name[], const char expr[],\n                                 T const &value) {\n    std::cout << \"\\n(Kalman Debug Output) \" << name << \" [\" << expr << \"]:\\n\"\n              << value << std::endl;\n}\n\n#define FLEXKALMAN_DEBUG_OUTPUT(Name, Value)                                   \\\n    dumpKalmanDebugOuput(Name, #Value, Value)\n#endif\n\n// Internal Includes\n#include \"FlexKalman/AbsoluteOrientationMeasurement.h\"\n#include \"FlexKalman/AbsolutePositionMeasurement.h\"\n#include \"FlexKalman/FlexibleKalmanFilter.h\"\n#include \"FlexKalman/FlexibleUnscentedCorrect.h\"\n#include \"FlexKalman/PoseStateExponentialMap.h\"\n\n#include <catch2/catch.hpp>\n\n#include \"ContentsInvalid.h\"\n\nusing State = flexkalman::pose_exp_map::State;\nusing flexkalman::AbsoluteOrientationMeasurement;\nusing flexkalman::AbsolutePositionMeasurement;\n\nstatic void dumpState(State const &state, const char msg[], size_t iteration) {\n    std::cout << \"\\n\"\n              << msg << \" (iteration \" << iteration << \"):\\n\"\n              << state.stateVector().transpose() << std::endl;\n}\n\ntemplate <typename PM, typename M>\nstatic void runFilterAndCheck(State &state,\n                              flexkalman::ProcessModelBase<PM> &processModel,\n                              flexkalman::MeasurementBase<M> &meas, double dt,\n                              size_t iteration) {\n    INFO(\"Iteration \" << iteration);\n    INFO(\"prediction step\");\n    flexkalman::predict(state, processModel, dt);\n    dumpState(state, \"After prediction\", iteration);\n    REQUIRE_FALSE(stateContentsInvalid(state));\n    REQUIRE_FALSE(covarianceContentsInvalid(state));\n\n    REQUIRE_FALSE(\n        covarianceContentsInvalid(meas.derived().getCovariance(state)));\n\n    INFO(\"correction step\");\n    flexkalman::correctUnscented(state, meas.derived());\n    dumpState(state, \"After correction\", iteration);\n    REQUIRE_FALSE(stateContentsInvalid(state));\n    REQUIRE_FALSE(covarianceContentsInvalid(state));\n}\n\nTEMPLATE_TEST_CASE(\"ProcessModelStability\", \"\",\n                   flexkalman::pose_exp_map::ConstantVelocityProcessModel) {\n\n    using ProcessModel = TestType;\n    State state;\n    ProcessModel processModel;\n    std::size_t iteration = 0;\n\n    dumpState(state, \"Initial state\", iteration);\n\n    SECTION(\"IdentityAbsoluteOrientationMeasurement\") {\n        auto meas = AbsoluteOrientationMeasurement{\n            Eigen::Quaterniond::Identity(),\n            Eigen::Vector3d(0.00001, 0.00001, 0.00001)};\n        for (iteration = 0; iteration < 100; ++iteration) {\n            runFilterAndCheck(state, processModel, meas, 0.1, iteration);\n        }\n        // Can't use isApprox to compare to zero vector\n        CHECK(state.position().isMuchSmallerThan(0.001));\n        /// @todo check that it's roughly identity\n    }\n    SECTION(\"IdentityAbsolutePositionMeasurement\") {\n        auto meas = AbsolutePositionMeasurement{\n            Eigen::Vector3d::Zero(), Eigen::Vector3d::Constant(0.000007)};\n        for (iteration = 0; iteration < 100; ++iteration) {\n            runFilterAndCheck(state, processModel, meas, 0.1, iteration);\n        }\n        /// @todo check that it's roughly identity\n    }\n    SECTION(\"AbsolutePositionMeasurementXlate111\") {\n        auto meas = AbsolutePositionMeasurement{\n            Eigen::Vector3d::Constant(1), Eigen::Vector3d::Constant(0.000007)};\n        for (iteration = 0; iteration < 100; ++iteration) {\n            runFilterAndCheck(state, processModel, meas, 0.1, iteration);\n        }\n        /// @todo check that it's roughly identity orientation, position of 1,\n        /// 1, 1\n    }\n\n    SECTION(\"AbsoluteOrientationMeasurementConstantAngVel\") {\n        auto angleAxis = Eigen::AngleAxisd(0.001, Eigen::Vector3d::UnitX());\n        for (iteration = 0; iteration < 100; ++iteration) {\n            angleAxis.angle() += 0.001;\n            auto meas = AbsoluteOrientationMeasurement{\n                Eigen::Quaterniond(angleAxis),\n                Eigen::Vector3d(0.00001, 0.00001, 0.00001)};\n            runFilterAndCheck(state, processModel, meas, 0.1, iteration);\n        }\n        // Can't use isApprox to compare to zero vector\n        CHECK(state.position().isMuchSmallerThan(0.001));\n\n        INFO(\"Should almost reach the most recent measurement\");\n        CHECK(state.rotationVector()[0] ==\n              Approx(angleAxis.angle()).epsilon(0.1));\n        CHECK(state.rotationVector()[1] == Approx(0).margin(0.01));\n        CHECK(state.rotationVector()[2] == Approx(0).margin(0.01));\n        INFO(\"We shouldn't overshoot\")\n        CHECK(state.rotationVector().norm() < angleAxis.angle());\n    }\n}\n", "meta": {"hexsha": "41df5d22b2bec5c3a64ce61c947452ceb83483cc", "size": 5462, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/cplusplus/Kalman/KalmanExpNoNaNs.cpp", "max_stars_repo_name": "rpavlik/UVBI-and-KalmanFramework-Standalone", "max_stars_repo_head_hexsha": "2276a2f921f91814a03dee6d9abe0305c6abf37a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-06-08T13:33:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T05:12:29.000Z", "max_issues_repo_path": "tests/cplusplus/Kalman/KalmanExpNoNaNs.cpp", "max_issues_repo_name": "rpavlik/UVBI-and-KalmanFramework-Standalone", "max_issues_repo_head_hexsha": "2276a2f921f91814a03dee6d9abe0305c6abf37a", "max_issues_repo_licenses": ["Apache-2.0"], "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/cplusplus/Kalman/KalmanExpNoNaNs.cpp", "max_forks_repo_name": "rpavlik/UVBI-and-KalmanFramework-Standalone", "max_forks_repo_head_hexsha": "2276a2f921f91814a03dee6d9abe0305c6abf37a", "max_forks_repo_licenses": ["Apache-2.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.6689655172, "max_line_length": 80, "alphanum_fraction": 0.6525082387, "num_tokens": 1283, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6791787121629466, "lm_q2_score": 0.665410572017153, "lm_q1q2_score": 0.4519326953622196}}
{"text": "//////////////////////////////////////////////////////////////////////////////\n// random::poisson::devroye::detail::int_mean.hpp                        \t//\n//                                                                          //\n//                                                                          //\n//  (C) Copyright 2010 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_RANDOM_POISSON_EXT_DEVROYE_DETAIL_INT_MEAN_HPP_ER_2010\n#define BOOST_RANDOM_POISSON_EXT_DEVROYE_DETAIL_INT_MEAN_HPP_ER_2010\n#include <boost/range.hpp>\n#include <boost/math/special_functions/modf.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/exponential_distribution.hpp>\n\n#include <boost/random/poisson_ext/devroye/detail/math.hpp>\n#include <boost/random/poisson_ext/devroye/detail/parameters.hpp>\n\nnamespace boost{\nnamespace random{\nnamespace poisson{\nnamespace devroye{     \nnamespace detail{\n\n    // Samples from the poisson distribution with an integer mean\n    //\n    // Source : The computer generation of poisson random variables. L. Devroye,\n    // Computing 26, Springer-Verlag, 1981\n    //\n    // Parameter     Description\n    // Step4         A class that models the concept by the same name\n    // Int           An integer type\n    // T             A float type\n    // P             An error handling policy\n\t//\n    // Expression                 Requirement\n    // int_mean<Step4,Int,T,P>    Public base of Step4 \n\t//\n    // Concept Step4:\n    // int_mean<Step4,Int,T,P> is a public base, and\n    // Expression    Result type   Side effect\n    //  accept()     bool          if true, y is set to the value to be returned\n    //\n    // The numbers on the right are those of the lines of the Fortran listing \n    // given in the reference above.\n    template<typename Step4,typename Int,typename T,typename P>\n    class int_mean : public devroye::detail::parameters<Int,T,P>\n        {\n\n\t\ttypedef devroye::detail::math<Int,T,P> ma_;\n        typedef devroye::detail::parameters<Int,T,P> super1_;\n\n\t\tpublic:\n\n        typedef T input_type;\n        typedef Int result_type;\n\n        input_type mean() const { return ma_::to_float(this->int_mean_); }\n        void reset() { }\n                        \n\t\tint_mean():super1_(){}\n        explicit int_mean(const result_type& m)\n        \t:super1_(m),int_mean_(m){\n            \tBOOST_ASSERT(this->int_mean_val()>=0);\n            }\n\n        int_mean (const int_mean& that)\n        \t:super1_(that),\n            int_mean_(that.int_mean_),\n\t\t\tu_(that.u_),\n        \tx_(that.x_),\n        \ty_(that.y_),\n        \tv_(that.v_)\n            {}\n        \n        int_mean& operator=(const int_mean& that){\n        \tif(that!=this){\n\t\t\t\tstatic_cast<super1_&>(*this) = that;\n            \tthis->int_mean_ = (that.int_mean_);\n\t\t\t\tthis->u_ = (that.u_);\n        \t\tthis->x_ = (that.x_);\n        \t\tthis->y_ = (that.y_);\n        \t\tthis->v_ = (that.v_);\n            }\n\t\t\treturn (*this);\n\t\t}\n\n  \t\ttemplate<class U>\n  \t\tresult_type operator()(U& urng)\n  \t\t{\n\t\t\tresult_type result =  this->step1(urng);\t        \n            BOOST_ASSERT(result >= 0);\n            return result;\n        }\n\t\t\n            // --- I/O --- //\n            \n            template<class CharT, class Traits>\n            friend std::basic_ostream<CharT,Traits>&\n            operator<<(\n                std::basic_ostream<CharT,Traits>& os, \n                const int_mean& pd\n            )\n            {\n                os \t<< \"devroye(\"\n            \t\t<< pd.int_mean_val()\n            \t\t<< ','\n            \t\t<< pd.u() \n            \t\t<< ','\n            \t\t<< pd.x() \n            \t\t<< ','\n            \t\t<< pd.y() \n            \t\t<< ','\n            \t\t<< pd.v() \n            \t\t<< ')';\n                return os;\n            }\n            \n            template<class CharT, class Traits>\n            friend std::basic_istream<CharT,Traits>&\n            operator>>(\n                std::basic_istream<CharT,Traits>& is, \n                int_mean& pd\n            )\n            {\n            \tresult_type new_mean;\n                is\t>> std::ws\n            \t\t>> new_mean\n            \t\t>> std::ws\n                \t>> std::ws \t// u\n            \t\t>> std::ws\n                \t>> std::ws\t// x\n            \t\t>> std::ws\n                \t>> std::ws\t// y\n            \t\t>> std::ws\n                \t>> std::ws\t// v\n            \t\t>> std::ws;\n\t\t\t\tstatic_cast<Step4&>(pd) = Step4(new_mean);\n            \treturn is;\n            }\n            \n        // ----------- //\n            \n        protected:\n\t\t\n\t\ttemplate<typename U>\n\t\tinline result_type step1(U& urng){\n        \t// TODO max recursion policy\n            \n            // line 10 : case mean = 0;\n            \n            this->u_ = urng();\t\t\t\t\t\t\t\t\t\t\t\t//13\n            if(this->u()>this->p1()){ \n            \t// Reconciliation with Fortran listing :\n                // ptail = p2 + p3 = 1-p1. \n                // u' ~ 1-u. (u'<ptail) <=> (1-u<p2+p3) <=> (u > p1)\n            \treturn this->step3(urng);\n            }else{\n                return this->step2(urng);\n            }\t\n\t\t}\n\n\t\ttemplate<typename U>\n\t\tinline result_type step2(U& urng){\n        \tinput_type z = this->random_z(urng); \t\t\t\t\t\t\t//15\n        \tthis->x_ = ( this->sd1() * z ) + super1_::loc1();\n            if(\n            \t(this->x()>this->delta()) \n                \t||  (this->x()< (-this->m1()))\n            ){ \n            \treturn this->step1(urng);\n            }else{\n            \t// y is rounded away from zero\n                if(ma_::is_strictly_negative(this->x())){ \n                    this->y_ = ma_::floor(this->x());\n                }else{\n                    this->y_ = ma_::ceil(this->x());\n                }\n                input_type e  = this->random_exp1(urng);\n                this->v_ = -( e + ma_::pow(z,2)/ma_::to_float(2) ) + this->c1();\n                return this->step4(urng);\n            }\n        }\n\n\t\ttemplate<typename U>\n\t\tinline result_type step3(U& urng){\n        \n            // Reconciliation with Fortran listing :\n            // pbody = p3 = 1-(p1+p2) \n            // u' ~ 1-u. (u'<pbody) <=> (1-u<p3) <=> (u > p1+p2)\n        \tif(this->u()>this->p1()+this->p2()){ \t\t\t\t\t\t\t\n            \tthis->y_ = this->int_mean_val(); \n                return this->y();\n            }else{\n            \tinput_type e1 = this->random_exp1(urng);\n            \tinput_type e2 = this->random_exp1(urng);\n            \tthis->x_ = this->delta() + e1 / this->shape2();\t\t\t\t//51 \n            \tthis->y_ = ma_::to_int( ma_::ceil(this->x()) );\n            \tthis->v_ = - ( \n                \te2 + this->shape2() * (ma_::to_float(1) + this->x())\n                );\n            \treturn this->step4(urng);\n            }\n        }\n\n\t\ttemplate<typename U>\n\t\tinline result_type step4(U& urng){\n            Step4& derived = static_cast<Step4&>(*this);\t\t\n            if(derived.accept()){\n            \treturn this->y();\n            }else{\n\t\t\t\treturn this->step1(urng);            \n            }\n\t\t}\n\n\t\ttemplate<typename U>\n\t\tinput_type random_z(U& urng)const{\n        \ttypedef boost::normal_distribution<input_type> d_;\n            static d_ d = d_(ma_::to_float(0),ma_::to_float(1));\n            return d(urng);\n        }\n\n\t\ttemplate<typename U>\n\t\tinput_type random_exp1(U& urng)const{\n        \ttypedef boost::exponential_distribution<input_type> d_;\n            static d_ d = d_(ma_::to_float(1));\n            return d(urng);\n        }\n\n\t\t// Parameter\n\t\tresult_type int_mean_;\n        \n        // These are quantities that vary throughout sampling\n\t\tinput_type\tu_;\n        input_type \tx_;\n        result_type y_;\n        input_type \tv_;\n\n        const result_type& \tint_mean_val()const{ return this->int_mean_; } \n        const input_type& \tu()const{ return this->u_; } \n        const input_type& \tx()const{ return this->x_; } \n        const result_type& \ty()const{ return this->y_; } \n        const input_type& \tv()const{ return this->v_; } \n\n\t};\n\n}// detail\n}// devroye\n}// poisson\n}// random\n}// boost\n\n#endif \n", "meta": {"hexsha": "59ec3d97af2ddccd608ee45c4ddc82c8e47330d7", "size": 8254, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "random/boost/random/poisson_ext/devroye/detail/int_mean.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": "random/boost/random/poisson_ext/devroye/detail/int_mean.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": "random/boost/random/poisson_ext/devroye/detail/int_mean.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.368627451, "max_line_length": 80, "alphanum_fraction": 0.4701962685, "num_tokens": 2052, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6654105720171531, "lm_q2_score": 0.6791787056691697, "lm_q1q2_score": 0.45193269104119194}}
{"text": "#include <vector>\n\n#include <boost/shared_ptr.hpp>\n#include <gflags/gflags.h>\n#include <glog/logging.h>\n\n#include <cmath>\n\n#include \"caffe/blob.hpp\"\n#include \"caffe/common.hpp\"\n#include \"caffe/flow_transformer_layer.hpp\"\n#include \"caffe/util/math_functions.hpp\"\n\nnamespace caffe {\n\ntemplate <typename Dtype>\nvoid FlowTransformerLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom,\n      const vector<Blob<Dtype>*>& top) {\n\n\tstring prefix = \"\\t\\tFlow Transformer Layer:: LayerSetUp: \\t\";\n\n\n\tstd::cout<<prefix<<\"Getting output_H_ and output_W_\"<<std::endl;\n\toutput_H_ = bottom[0]->shape(2);\n\toutput_W_ = bottom[0]->shape(3);\n\tstd::cout<<prefix<<\"output_H_ = \"<<output_H_<<\", output_W_ = \"<<output_W_<<std::endl;\n\n\tstd::cout<<prefix<<\"Getting pre-defined parameters\"<<std::endl;\n\n\t// check the validation for the parameter theta\n\tCHECK(bottom[1]->shape(2) == bottom[0]->shape(2)) << \"The third dimension (height) of the flow field and \" <<\n\t\t\t\"U should be the same\" << std::endl;\n\tCHECK(bottom[1]->shape(3) == bottom[0]->shape(3)) << \"The forth dimension (width) of the flow field and \" <<\n\t\t\t\"U should be the same\" << std::endl;\n\n\t// initialize the matrix for output grid\n\tstd::cout<<prefix<<\"Initializing the matrix for output grid\"<<std::endl;\n\n\t//2 channel image, 1 channel each for U and V of flow field\n\tvector<int> shape_output(4);\n\tshape_output[0] = bottom[0]->shape(0);\n\tshape_output[1] = 2;\n\tshape_output[2] = output_H_;\n\tshape_output[3] = output_W_;\n\toutput_grid.Reshape(shape_output);\n\n\tDtype* data = output_grid.mutable_cpu_data();\n\tfor(int n=0;n<bottom[0]->shape(0);n++){\n\tfor(int r=0;r<output_H_;r++){\n\t\tfor(int c=0;c<output_W_;c++){\n\t\t\tdata[output_grid.offset(n,0,r,c)] = c;\n\t\t\tdata[output_grid.offset(n,1,r,c)] = r;\n\t\t}\n\t}\n\t}\n\n\t// initialize the matrix for input grid\n\tstd::cout<<prefix<<\"Initializing the matrix for input grid\"<<std::endl;\n\n\tvector<int> shape_input(4);\n\tshape_input[0] = bottom[0]->shape(0);\n\tshape_input[1] = 2;\n\tshape_input[2] = output_H_;\n\tshape_input[3] = output_W_;\n\tinput_grid.Reshape(shape_input);\n\n\tstd::cout<<prefix<<\"Initialization finished.\"<<std::endl;\n}\n\ntemplate <typename Dtype>\nvoid FlowTransformerLayer<Dtype>::Reshape(const vector<Blob<Dtype>*>& bottom,\n      const vector<Blob<Dtype>*>& top) {\n\tstring prefix = \"\\t\\tFlow Transformer Layer:: Reshape: \\t\";\n\n\tif(global_debug) std::cout<<prefix<<\"Starting!\"<<std::endl;\n\n\tN = bottom[0]->shape(0);\n\tC = bottom[0]->shape(1);\n\tH = bottom[0]->shape(2);\n\tW = bottom[0]->shape(3);\n\n\t// reshape V\n\tvector<int> shape(4);\n\n\tshape[0] = N;\n\tshape[1] = C;\n\tshape[2] = output_H_;\n\tshape[3] = output_W_;\n\n\ttop[0]->Reshape(shape);\n\n\t// reshape dTheta_tmp\n\tvector<int> dTheta_tmp_shape(4);\n\n\tdTheta_tmp_shape[0] = N;\n\tdTheta_tmp_shape[1] = 2;\n\tdTheta_tmp_shape[2] = 3;\n\tdTheta_tmp_shape[3] = output_H_ * output_W_ * C;\n\n\tdTheta_tmp.Reshape(dTheta_tmp_shape);\n\n\t// init all_ones_2\n\tvector<int> all_ones_2_shape(1);\n\tall_ones_2_shape[0] = output_H_ * output_W_ * C;\n\tall_ones_2.Reshape(all_ones_2_shape);\n\n\t// reshape full_theta\n\tvector<int> full_theta_shape(2);\n\tfull_theta_shape[0] = N;\n\tfull_theta_shape[1] = 6;\n\tfull_theta.Reshape(full_theta_shape);\n\n\tif(global_debug) std::cout<<prefix<<\"Finished.\"<<std::endl;\n}\n\ntemplate <typename Dtype>\nDtype FlowTransformerLayer<Dtype>::transform_forward_cpu(const Dtype* pic, Dtype px, Dtype py) {\n\t/*\n\tso i think this does the bilinear interpolation for a single pixel\n\t*/\n\n\tbool debug = false;\n\n\tstring prefix = \"\\t\\tFlow Transformer Layer:: transform_forward_cpu: \\t\";\n\n\tif(debug) std::cout<<prefix<<\"Starting!\\t\"<<std::endl;\n\tif(debug) std::cout<<prefix<<\"(px, py) = (\"<<px<<\", \"<<py<<\")\"<<std::endl;\n\n\tDtype res = (Dtype)0.;\n\n\tDtype x = px; Dtype y = py;\n\n\tif(debug) std::cout<<prefix<<\"(x, y) = (\"<<x<<\", \"<<y<<\")\"<<std::endl;\n\n\tint m, n; Dtype w;\n\n\tm = floor(x); n = floor(y); w = 0;\n\tif(debug) std::cout<<prefix<<\"1: (m, n) = (\"<<m<<\", \"<<n<<\")\"<<std::endl;\n\n\tif(m >= 0 && m < H && n >= 0 && n < W) {\n\t\tw = max(0, 1 - abs(x - m)) * max(0, 1 - abs(y - n));\n\t\tres += w * pic[m * W + n];\n\t\tif(debug) std::cout<<prefix<<\"w = \"<<w<<\", pic[m, n] = \"<<pic[m * W + n]<<std::endl;\n\t}\n\n\tm = floor(x) + 1; n = floor(y); w = 0;\n\tif(debug) std::cout<<prefix<<\"2: (m, n) = (\"<<m<<\", \"<<n<<\")\"<<std::endl;\n\n\tif(m >= 0 && m < H && n >= 0 && n < W) {\n\t\tw = max(0, 1 - abs(x - m)) * max(0, 1 - abs(y - n));\n\t\tres += w * pic[m * W + n];\n\t\tif(debug) std::cout<<prefix<<\"w = \"<<w<<\", pic[m, n] = \"<<pic[m * W + n]<<std::endl;\n\t}\n\n\tm = floor(x); n = floor(y) + 1; w = 0;\n\tif(debug) std::cout<<prefix<<\"3: (m, n) = (\"<<m<<\", \"<<n<<\")\"<<std::endl;\n\n\tif(m >= 0 && m < H && n >= 0 && n < W) {\n\t\tw = max(0, 1 - abs(x - m)) * max(0, 1 - abs(y - n));\n\t\tres += w * pic[m * W + n];\n\t\tif(debug) std::cout<<prefix<<\"w = \"<<w<<\", pic[m, n] = \"<<pic[m * W + n]<<std::endl;\n\t}\n\n\tm = floor(x) + 1; n = floor(y) + 1; w = 0;\n\tif(debug) std::cout<<prefix<<\"4: (m, n) = (\"<<m<<\", \"<<n<<\")\"<<std::endl;\n\n\tif(m >= 0 && m < H && n >= 0 && n < W) {\n\t\tw = max(0, 1 - abs(x - m)) * max(0, 1 - abs(y - n));\n\t\tres += w * pic[m * W + n];\n\t\tif(debug) std::cout<<prefix<<\"w = \"<<w<<\", pic[m, n] = \"<<pic[m * W + n]<<std::endl;\n\t}\n\n\tif(debug) std::cout<<prefix<<\"Finished. \\tres = \"<<res<<std::endl;\n\n\treturn res;\n}\n\ntemplate <typename Dtype>\nvoid FlowTransformerLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom,\n    const vector<Blob<Dtype>*>& top) {\n\n\tstring prefix = \"\\t\\tFlow Transformer Layer:: Forward_cpu: \\t\";\n\n\t/*\n\tCHECK(false) << \"Don't use the CPU implementation! If you really want to, delete the\" <<\n\t\t\t\" CHECK in st_layer.cpp file. Line number: 240-241.\" << std::endl;\n\t*/\n\n\tif(global_debug) std::cout<<prefix<<\"Starting!\"<<std::endl;\n\n\tconst Dtype* U = bottom[0]->cpu_data();\n\tconst Dtype* flows = bottom[1]->cpu_data();\n\t\n\tconst Dtype* output_grid_data = output_grid.cpu_data();\n\n\tDtype* input_grid_data = input_grid.mutable_cpu_data();\n\tDtype* V = top[0]->mutable_cpu_data();\n\n\tcaffe_set(input_grid.count(), (Dtype)0, input_grid_data);\n\tcaffe_set(top[0]->count(), (Dtype)0, V);\n\n\t//combine flow with grid\n\tcaffe_add(input_grid.count(),output_grid_data,flows,input_grid_data);\n\n\t// for each input\n\tfor(int i = 0; i < N; ++i) {\n\t\t//coordinates is a matrix of coordinates on the original image\n\t\t//to sample pixel values from\n\t\t//Dtype* coordinates = input_grid_data + (output_H_ * output_W_ * 2) * i;\n\t\t//Dtype* coordinates = input_grid_data + input_grid.offset(i,0,0,0);\n\n\t\t//do affine transformation\n\t\t//caffe_cpu_gemm<Dtype>(CblasNoTrans, CblasTrans, output_H_ * output_W_, 2, 3, (Dtype)1.,\n\t\t//      output_grid_data, theta + 6 * i, (Dtype)0., coordinates);\n\t\t\n\t\tDtype px, py;\n\n\t\t//for each pixel on the output, find the interpolated pixel value\n\t\tfor(int s = 0; s < output_H_; ++s){\n\t\t\tfor(int t = 0; t < output_W_; ++t) {\n\t\t\t\t//px,py should be the sample coordinates on the source img\n\n\t\t\t\tpy = input_grid_data[input_grid.offset(i,0,s,t)];\n\t\t\t\tpx = input_grid_data[input_grid.offset(i,1,s,t)];\n\n\t\t\t\tfor(int j = 0; j < C; ++j){\n\t\t\t\t\t//do interpolation\n\t\t\t\t\tV[top[0]->offset(i, j, s, t)] = transform_forward_cpu(\n\t\t\t\t\t\t\tU + bottom[0]->offset(i, j, 0, 0), px, py);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif(global_debug) std::cout<<prefix<<\"Finished.\"<<std::endl;\n}\n\ntemplate <typename Dtype>\nvoid FlowTransformerLayer<Dtype>::transform_backward_cpu(Dtype dV, const Dtype* U, const Dtype px,\n\t\tconst Dtype py, Dtype* dU, Dtype& dpx, Dtype& dpy) {\n\t/*\n\tU is the input image\n\tV is out output image, dV is local gradient from output\n\t*/\n\n\tbool debug = false;\n\n\tstring prefix = \"\\t\\tFlow Transformer Layer:: transform_backward_cpu: \\t\";\n\n\tif(debug) std::cout<<prefix<<\"Starting!\"<<std::endl;\n\n\t//Dtype x = (px + 1) / 2 * H; Dtype y = (py + 1) / 2 * W;\n\tDtype x = px; Dtype y = py;\n\tif(debug) std::cout<<prefix<<\"(x, y) = (\"<<x<<\", \"<<y<<\")\"<<std::endl;\n\n\tint m, n; Dtype w;\n\n\tm = floor(x); n = floor(y); w = 0;\n\tif(debug) std::cout<<prefix<<\"(m, n) = (\"<<m<<\", \"<<n<<\")\"<<std::endl;\n\n\tif(m >= 0 && m < H && n >= 0 && n < W) {\n\t\tw = max(0, 1 - abs(x - m)) * max(0, 1 - abs(y - n));\n\n\t\tif(to_compute_dU_) dU[m * W + n] += w * dV;\n\n\t\tif(abs(x - m) < 1) {\n\t\t\tif(m >= x) {\n\t\t\t\tdpx += max(0, 1 - abs(y - n)) * U[m * W + n] * dV;// * H / 2;\n\t\t\t\tif(debug) std::cout<<prefix<<\"dpx += \"<<max(0, 1 - abs(y - n))<<\" * \"<<U[m * W + n]<<\" * \"<<dV<<\" * \"<<H / 2<<std::endl;\n\t\t\t} else {\n\t\t\t\tdpx -= max(0, 1 - abs(y - n)) * U[m * W + n] * dV;// * H / 2;\n\t\t\t\tif(debug) std::cout<<prefix<<\"dpx -= \"<<max(0, 1 - abs(y - n))<<\" * \"<<U[m * W + n]<<\" * \"<<dV<<\" * \"<<H / 2<<std::endl;\n\t\t\t}\n\t\t}\n\n\t\tif(abs(y - n) < 1) {\n\t\t\tif(n >= y) {\n\t\t\t\tdpy += max(0, 1 - abs(x - m)) * U[m * W + n] * dV;// * W / 2;\n\t\t\t\tif(debug) std::cout<<prefix<<\"dpy += \"<<max(0, 1 - abs(x - m))<<\" * \"<<U[m * W + n]<<\" * \"<<dV<<\" * \"<<W / 2<<std::endl;\n\t\t\t} else {\n\t\t\t\tdpy -= max(0, 1 - abs(x - m)) * U[m * W + n] * dV;// * W / 2;\n\t\t\t\tif(debug) std::cout<<prefix<<\"dpy -= \"<<max(0, 1 - abs(x - m))<<\" * \"<<U[m * W + n]<<\" * \"<<dV<<\" * \"<<W / 2<<std::endl;\n\t\t\t}\n\t\t}\n\t}\n\n\tm = floor(x) + 1; n = floor(y); w = 0;\n\tif(debug) std::cout<<prefix<<\"(m, n) = (\"<<m<<\", \"<<n<<\")\"<<std::endl;\n\n\tif(m >= 0 && m < H && n >= 0 && n < W) {\n\t\tw = max(0, 1 - abs(x - m)) * max(0, 1 - abs(y - n));\n\n\t\tif(to_compute_dU_) dU[m * W + n] += w * dV;\n\n\t\tif(abs(x - m) < 1) {\n\t\t\tif(m >= x) {\n\t\t\t\tdpx += max(0, 1 - abs(y - n)) * U[m * W + n] * dV;// * H / 2;\n\t\t\t\tif(debug) std::cout<<prefix<<\"dpx += \"<<max(0, 1 - abs(y - n))<<\" * \"<<U[m * W + n]<<\" * \"<<dV<<\" * \"<<H / 2<<std::endl;\n\t\t\t} else {\n\t\t\t\tdpx -= max(0, 1 - abs(y - n)) * U[m * W + n] * dV;// * H / 2;\n\t\t\t\tif(debug) std::cout<<prefix<<\"dpx -= \"<<max(0, 1 - abs(y - n))<<\" * \"<<U[m * W + n]<<\" * \"<<dV<<\" * \"<<H / 2<<std::endl;\n\t\t\t}\n\t\t}\n\n\t\tif(abs(y - n) < 1) {\n\t\t\tif(n >= y) {\n\t\t\t\tdpy += max(0, 1 - abs(x - m)) * U[m * W + n] * dV;// * W / 2;\n\t\t\t\tif(debug) std::cout<<prefix<<\"dpy += \"<<max(0, 1 - abs(x - m))<<\" * \"<<U[m * W + n]<<\" * \"<<dV<<\" * \"<<W / 2<<std::endl;\n\t\t\t} else {\n\t\t\t\tdpy -= max(0, 1 - abs(x - m)) * U[m * W + n] * dV;// * W / 2;\n\t\t\t\tif(debug) std::cout<<prefix<<\"dpy -= \"<<max(0, 1 - abs(x - m))<<\" * \"<<U[m * W + n]<<\" * \"<<dV<<\" * \"<<W / 2<<std::endl;\n\t\t\t}\n\t\t}\n\t}\n\n\tm = floor(x); n = floor(y) + 1; w = 0;\n\tif(debug) std::cout<<prefix<<\"(m, n) = (\"<<m<<\", \"<<n<<\")\"<<std::endl;\n\n\tif(m >= 0 && m < H && n >= 0 && n < W) {\n\t\tw = max(0, 1 - abs(x - m)) * max(0, 1 - abs(y - n));\n\n\t\tif(to_compute_dU_) dU[m * W + n] += w * dV;\n\n\t\tif(abs(x - m) < 1) {\n\t\t\tif(m >= x) {\n\t\t\t\tdpx += max(0, 1 - abs(y - n)) * U[m * W + n] * dV;// * H / 2;\n\t\t\t\tif(debug) std::cout<<prefix<<\"dpx += \"<<max(0, 1 - abs(y - n))<<\" * \"<<U[m * W + n]<<\" * \"<<dV<<\" * \"<<H / 2<<std::endl;\n\t\t\t} else {\n\t\t\t\tdpx -= max(0, 1 - abs(y - n)) * U[m * W + n] * dV;// * H / 2;\n\t\t\t\tif(debug) std::cout<<prefix<<\"dpx -= \"<<max(0, 1 - abs(y - n))<<\" * \"<<U[m * W + n]<<\" * \"<<dV<<\" * \"<<H / 2<<std::endl;\n\t\t\t}\n\t\t}\n\n\t\tif(abs(y - n) < 1) {\n\t\t\tif(n >= y) {\n\t\t\t\tdpy += max(0, 1 - abs(x - m)) * U[m * W + n] * dV;// * W / 2;\n\t\t\t\tif(debug) std::cout<<prefix<<\"dpy += \"<<max(0, 1 - abs(x - m))<<\" * \"<<U[m * W + n]<<\" * \"<<dV<<\" * \"<<W / 2<<std::endl;\n\t\t\t} else {\n\t\t\t\tdpy -= max(0, 1 - abs(x - m)) * U[m * W + n] * dV;// * W / 2;\n\t\t\t\tif(debug) std::cout<<prefix<<\"dpy -= \"<<max(0, 1 - abs(x - m))<<\" * \"<<U[m * W + n]<<\" * \"<<dV<<\" * \"<<W / 2<<std::endl;\n\t\t\t}\n\t\t}\n\t}\n\n\tm = floor(x) + 1; n = floor(y) + 1; w = 0;\n\tif(debug) std::cout<<prefix<<\"(m, n) = (\"<<m<<\", \"<<n<<\")\"<<std::endl;\n\n\tif(m >= 0 && m < H && n >= 0 && n < W) {\n\t\tw = max(0, 1 - abs(x - m)) * max(0, 1 - abs(y - n));\n\n\t\tif(to_compute_dU_) dU[m * W + n] += w * dV;\n\n\t\tif(abs(x - m) < 1) {\n\t\t\tif(m >= x) {\n\t\t\t\tdpx += max(0, 1 - abs(y - n)) * U[m * W + n] * dV;// * H / 2;\n\t\t\t\tif(debug) std::cout<<prefix<<\"dpx += \"<<max(0, 1 - abs(y - n))<<\" * \"<<U[m * W + n]<<\" * \"<<dV<<\" * \"<<H / 2<<std::endl;\n\t\t\t} else {\n\t\t\t\tdpx -= max(0, 1 - abs(y - n)) * U[m * W + n] * dV;// * H / 2;\n\t\t\t\tif(debug) std::cout<<prefix<<\"dpx -= \"<<max(0, 1 - abs(y - n))<<\" * \"<<U[m * W + n]<<\" * \"<<dV<<\" * \"<<H / 2<<std::endl;\n\t\t\t}\n\t\t}\n\n\t\tif(abs(y - n) < 1) {\n\t\t\tif(n >= y) {\n\t\t\t\tdpy += max(0, 1 - abs(x - m)) * U[m * W + n] * dV;// * W / 2;\n\t\t\t\tif(debug) std::cout<<prefix<<\"dpy += \"<<max(0, 1 - abs(x - m))<<\" * \"<<U[m * W + n]<<\" * \"<<dV<<\" * \"<<W / 2<<std::endl;\n\t\t\t} else {\n\t\t\t\tdpy -= max(0, 1 - abs(x - m)) * U[m * W + n] * dV;// * W / 2;\n\t\t\t\tif(debug) std::cout<<prefix<<\"dpy -= \"<<max(0, 1 - abs(x - m))<<\" * \"<<U[m * W + n]<<\" * \"<<dV<<\" * \"<<W / 2<<std::endl;\n\t\t\t}\n\t\t}\n\t}\n\n\tif(debug) std::cout<<prefix<<\"Finished.\"<<std::endl;\n}\n\ntemplate <typename Dtype>\nvoid FlowTransformerLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,\n    const vector<bool>& propagate_down,\n    const vector<Blob<Dtype>*>& bottom) {\n\n\t\tstring prefix = \"\\t\\tFlow Transformer Layer:: Backward_cpu: \\t\";\n\n\t\t//CHECK(false) << \"Don't use the CPU implementation! If you really want to, delete the\" <<\n\t\t//\t\t\" CHECK in st_layer.cpp file. Line number: 420-421.\" << std::endl;\n\n\t\tif(global_debug) std::cout<<prefix<<\"Starting!\"<<std::endl;\n\n\t\tconst Dtype* dV = top[0]->cpu_diff();\n\t\tDtype* input_grid_data = input_grid.mutable_cpu_data();\n\t\t//const Dtype* output_grid_data = output_grid.cpu_data(); // remove if you don't need to recalc the input grid\n\t\tconst Dtype* U = bottom[0]->cpu_data();\n\n\t\tDtype* dU = bottom[0]->mutable_cpu_diff(); //we won't be setting this\n\t\t//Dtype* dTheta = bottom[1]->mutable_cpu_diff();\n\t\t//const Dtype* flows = bottom[1]->cpu_data(); // remove if you don't need to recalc the input grid\n\t\tDtype* flow_diff = bottom[1]->mutable_cpu_diff();\n\n\t\tcaffe_set(bottom[0]->count(), (Dtype)0, dU);\n\t\t//caffe_set(bottom[1]->count(), (Dtype)0, dTheta);\n\t\tcaffe_set(input_grid.count(), (Dtype)0, flow_diff);\n\n\t\t//calc input grid data, recalc incase blob is reset between forward and backward\n\t\t//caffe_add(input_grid.count(),output_grid_data,flows,input_grid_data);\n\n\t\tfor(int i = 0; i < N; ++i) {\n\n\t\t\t//const Dtype* coordinates = input_grid_data + (output_H_ * output_W_ * 2) * i;\n\t\t\t//Dtype* coordinates_diff = input_grid_diff + (output_H_ * output_W_ * 2) * i;\n\n\t\t\tconst Dtype* curInputGrid = &input_grid_data[input_grid.offset(i,0,0,0)];\n\t\t\t//since its just element wise addition, we are\n\t\t\t//just going to set the diff directly to the flow\n\t\t\tDtype* curFlowDiff = &flow_diff[bottom[1]->offset(i,0,0,0)];\n\n\t\t\t//int row_idx;\n\t\t\tDtype px, py, delta_dpx, delta_dpy;\n\n\t\t\tfor(int s = 0; s < output_H_; ++s)\n\t\t\t\tfor(int t = 0; t < output_W_; ++t) {\n\n\t\t\t\t\t//row_idx = output_W_ * s + t;\t//this means fix!\n\n\t\t\t\t\tpx = curInputGrid[input_grid.offset(0,1,s,t)];\n\t\t\t\t\tpy = curInputGrid[input_grid.offset(0,0,s,t)];\n\n\t\t\t\t\tfor(int j = 0; j < C; ++j) {\n\n\t\t\t\t\t\tdelta_dpx = delta_dpy = (Dtype)0.;\n\n\t\t\t\t\t\ttransform_backward_cpu(dV[top[0]->offset(i, j, s, t)], U + bottom[0]->offset(i, j, 0, 0),\n\t\t\t\t\t\t\t\tpx, py, dU + bottom[0]->offset(i, j, 0, 0), delta_dpx, delta_dpy);\n\n\t\t\t\t\t\tcurFlowDiff[bottom[1]->offset(0,1,s,t)] += delta_dpx;\n\t\t\t\t\t\tcurFlowDiff[bottom[1]->offset(0,0,s,t)] += delta_dpy;\n\t\t\t\t\t}\n\n\t\t\t\t\t/*\n\t\t\t\t\tdpx = curFlowDiff[row_idx * 2];\n\t\t\t\t\tdpy = curFlowDiff[row_idx * 2 + 1];\n\n\t\t\t\t\tdTheta[6 * i] += dpx * (s * 1.0 / output_H_ * 2 - 1);\n\t\t\t\t\tdTheta[6 * i + 1] += dpx * (t * 1.0 / output_W_ * 2 - 1);\n\t\t\t\t\tdTheta[6 * i + 2] += dpx;\n\t\t\t\t\tdTheta[6 * i + 3] += dpy * (s * 1.0 / output_H_ * 2 - 1);\n\t\t\t\t\tdTheta[6 * i + 4] += dpy * (t * 1.0 / output_W_ * 2 - 1);\n\t\t\t\t\tdTheta[6 * i + 5] += dpy;\n\t\t\t\t\t*/\n\t\t\t\t}\n\t\t}\n\n\t\tif(global_debug) std::cout<<prefix<<\"Finished.\"<<std::endl;\n}\n\n#ifdef CPU_ONLY\nSTUB_GPU(FlowTransformerLayer);\n#endif\n\nINSTANTIATE_CLASS(FlowTransformerLayer);\nREGISTER_LAYER_CLASS(FlowTransformer);\n\n}  // namespace caffe\n", "meta": {"hexsha": "abd15606e3ae79a93af30bb95cbf7734f12c5b73", "size": 15503, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/caffe/layers/flow_transformer_layer.cpp", "max_stars_repo_name": "bryanyzhu/GuidedNet", "max_stars_repo_head_hexsha": "4c87d392addc38700caf2856b450f2c74a79e122", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 26.0, "max_stars_repo_stars_event_min_datetime": "2017-06-05T19:19:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T14:36:37.000Z", "max_issues_repo_path": "src/caffe/layers/flow_transformer_layer.cpp", "max_issues_repo_name": "zmlshiwo/GuidedNet", "max_issues_repo_head_hexsha": "4c87d392addc38700caf2856b450f2c74a79e122", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-05-15T11:48:01.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-15T11:52:13.000Z", "max_forks_repo_path": "src/caffe/layers/flow_transformer_layer.cpp", "max_forks_repo_name": "zmlshiwo/GuidedNet", "max_forks_repo_head_hexsha": "4c87d392addc38700caf2856b450f2c74a79e122", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2017-06-12T16:59:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-16T18:31:17.000Z", "avg_line_length": 33.4838012959, "max_line_length": 124, "alphanum_fraction": 0.5462813649, "num_tokens": 5675, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6791787121629466, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.45193269085575377}}
{"text": "#include \"./../../header/graphcomponent.h\"\n//STL\n#include <iostream>\n#include <vector>\n#include <string>\n#include <fstream>\n#include <sstream>\n#include <iterator>\n//Boost\n\n#include <boost/config.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/graphviz.hpp>\n#include <boost/graph/graph_utility.hpp>\n#include <boost/graph/adjacency_list_io.hpp>\n#include <boost/graph/property_iter_range.hpp>\n#include <boost/graph/copy.hpp>\n#include <boost/property_map/property_map.hpp>\n\nusing namespace boost;\n\nvoid GraphComponent::read_graph_file(std::string filename, theGraph &g)\n{\n    std::ifstream infile(filename);\n    v_p id = get(&VertexProperty::index, g);\n    typedef graph_traits<theGraph>::vertex_descriptor Vertex;\n    typedef graph_traits<theGraph>::vertices_size_type size_type;\n    size_type n_vertices;\n    infile >> n_vertices; // read in number of vertices\n    std::vector<Vertex_t> vertex_set(n_vertices);\n    for (size_type i = 0; i < n_vertices; ++i)\n        vertex_set[i] = add_vertex(g);\n\n    size_type u, v;\n    while (infile >> u)\n        if (infile >> v)\n            add_edge(vertex_set[u], vertex_set[v], EdgeProperty(\"\"), g);\n        else\n            break;\n    //initialize the nums for the DFS\n    boost::graph_traits<theGraph>::vertex_iterator vi, viend;\n    int vnum = 0;\n    for (boost::tie(vi, viend) = vertices(g); vi != viend; ++vi)\n        id[*vi] = vnum++;\n}\n\nvoid GraphComponent::print_graph_file(theGraph &graph)\n{\n    v_p id = get(&VertexProperty::index, graph);\n\n    property_map<theGraph, std::string EdgeProperty::*>::type\n        name = get(&EdgeProperty::name, graph);\n    graph_traits<theGraph>::vertex_iterator i, end;\n    graph_traits<theGraph>::out_edge_iterator ei, edge_end;\n    for (boost::tie(i, end) = vertices(graph); i != end; ++i)\n    {\n        std::cout << id[*i] + 1 << \" \";\n        for (boost::tie(ei, edge_end) = out_edges(*i, graph); ei != edge_end; ++ei)\n            std::cout << \" -\" << name[*ei] << \"-> \" << id[target(*ei, graph)] + 1 << \"  \";\n        std::cout << std::endl;\n    }\n    // print_edges(theGraph, id);\n}\n", "meta": {"hexsha": "2e9e2be263622c158f3b0b3be1d7674c10c1ef8e", "size": 2089, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cpp/graphcomponent.cpp", "max_stars_repo_name": "yigitozgumus/AAPP_Project", "max_stars_repo_head_hexsha": "5d48b0112cc9c06debfbf77f9c76f32b53dfedf3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cpp/graphcomponent.cpp", "max_issues_repo_name": "yigitozgumus/AAPP_Project", "max_issues_repo_head_hexsha": "5d48b0112cc9c06debfbf77f9c76f32b53dfedf3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2018-06-18T20:29:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-09T08:33:32.000Z", "max_forks_repo_path": "src/cpp/graphcomponent.cpp", "max_forks_repo_name": "yigitozgumus/AAPP_Project", "max_forks_repo_head_hexsha": "5d48b0112cc9c06debfbf77f9c76f32b53dfedf3", "max_forks_repo_licenses": ["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.640625, "max_line_length": 90, "alphanum_fraction": 0.6486357109, "num_tokens": 551, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.4519326822136984}}
{"text": "// This file is part of Eigen, a lightweight C++ template library\n// for linear algebra.\n//\n// Copyright (C) 2010 Benoit Jacob <jacob.benoit.1@gmail.com>\n//\n// Eigen 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 3 of the License, or (at your option) any later version.\n//\n// Alternatively, 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 2 of\n// the License, or (at your option) any later version.\n//\n// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY\n// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License and a copy of the GNU General Public License along with\n// Eigen. If not, see <http://www.gnu.org/licenses/>.\n\n#include \"main.h\"\n#include <Eigen/SVD>\n\ntemplate<typename MatrixType> void upperbidiag(const MatrixType& m)\n{\n  const typename MatrixType::Index rows = m.rows();\n  const typename MatrixType::Index cols = m.cols();\n\n  typedef typename MatrixType::Scalar Scalar;\n  typedef Matrix<typename MatrixType::RealScalar, MatrixType::RowsAtCompileTime,  MatrixType::ColsAtCompileTime> RealMatrixType;\n\n  MatrixType a = MatrixType::Random(rows,cols);\n  internal::UpperBidiagonalization<MatrixType> ubd(a);\n  RealMatrixType b(rows, cols);\n  b.setZero();\n  b.block(0,0,cols,cols) = ubd.bidiagonal();\n  MatrixType c = ubd.householderU() * b * ubd.householderV().adjoint();\n  VERIFY_IS_APPROX(a,c);\n}\n\nvoid test_upperbidiagonalization()\n{\n  for(int i = 0; i < g_repeat; i++) {\n   CALL_SUBTEST_1( upperbidiag(MatrixXf(3,3)) );\n   CALL_SUBTEST_2( upperbidiag(MatrixXd(17,12)) );\n   CALL_SUBTEST_3( upperbidiag(MatrixXcf(20,20)) );\n   CALL_SUBTEST_4( upperbidiag(MatrixXcd(16,15)) );\n   CALL_SUBTEST_5( upperbidiag(Matrix<float,6,4>()) );\n   CALL_SUBTEST_6( upperbidiag(Matrix<float,5,5>()) );\n   CALL_SUBTEST_7( upperbidiag(Matrix<double,4,3>()) );\n  }\n}\n", "meta": {"hexsha": "86ec7132b3fa068c6aaf3672be5eefdd93ab8ab3", "size": 2260, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Plugins/SciberQuestToolKit/eigen-3.0.3/eigen-eigen-3.0.3/test/upperbidiagonalization.cpp", "max_stars_repo_name": "mathstuf/ParaView", "max_stars_repo_head_hexsha": "e867e280545ada10c4ed137f6a966d9d2f3db4cb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2015-03-12T00:12:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-26T08:56:31.000Z", "max_issues_repo_path": "Plugins/SciberQuestToolKit/eigen-3.0.3/eigen-eigen-3.0.3/test/upperbidiagonalization.cpp", "max_issues_repo_name": "mathstuf/ParaView", "max_issues_repo_head_hexsha": "e867e280545ada10c4ed137f6a966d9d2f3db4cb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-05-26T19:02:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-27T14:15:04.000Z", "max_forks_repo_path": "Plugins/SciberQuestToolKit/eigen-3.0.3/eigen-eigen-3.0.3/test/upperbidiagonalization.cpp", "max_forks_repo_name": "mathstuf/ParaView", "max_forks_repo_head_hexsha": "e867e280545ada10c4ed137f6a966d9d2f3db4cb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2019-07-04T12:54:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T13:04:38.000Z", "avg_line_length": 39.649122807, "max_line_length": 128, "alphanum_fraction": 0.7353982301, "num_tokens": 603, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6791786991753929, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.45193268221369826}}
{"text": "#define BOOST_TEST_MODULE \"lex_integer_test\"\n#include <toml/lexer.hpp>\n#include <boost/test/included/unit_test.hpp>\n#include <iostream>\n#include <iomanip>\n#include \"lex_aux.hpp\"\n\nusing namespace toml;\nusing namespace detail;\n\nBOOST_AUTO_TEST_CASE(test_decimal_correct)\n{\n    TOML_LEX_CHECK_ACCEPT(lex_integer, \"1234\",        \"1234\"       );\n    TOML_LEX_CHECK_ACCEPT(lex_integer, \"+1234\",       \"+1234\"      );\n    TOML_LEX_CHECK_ACCEPT(lex_integer, \"-1234\",       \"-1234\"      );\n    TOML_LEX_CHECK_ACCEPT(lex_integer, \"0\",           \"0\"          );\n    TOML_LEX_CHECK_ACCEPT(lex_integer, \"1_2_3_4\",     \"1_2_3_4\"    );\n    TOML_LEX_CHECK_ACCEPT(lex_integer, \"+1_2_3_4\",    \"+1_2_3_4\"   );\n    TOML_LEX_CHECK_ACCEPT(lex_integer, \"-1_2_3_4\",    \"-1_2_3_4\"   );\n    TOML_LEX_CHECK_ACCEPT(lex_integer, \"123_456_789\", \"123_456_789\");\n}\n\nBOOST_AUTO_TEST_CASE(test_decimal_invalid)\n{\n    TOML_LEX_CHECK_ACCEPT(lex_integer, \"123+45\",  \"123\");\n    TOML_LEX_CHECK_ACCEPT(lex_integer, \"123-45\",  \"123\");\n    TOML_LEX_CHECK_ACCEPT(lex_integer, \"01234\",   \"0\");\n    TOML_LEX_CHECK_ACCEPT(lex_integer, \"123__45\", \"123\");\n\n    TOML_LEX_CHECK_REJECT(lex_integer, \"_1234\");\n}\n\nBOOST_AUTO_TEST_CASE(test_hex_correct)\n{\n    TOML_LEX_CHECK_ACCEPT(lex_integer, \"0xDEADBEEF\",  \"0xDEADBEEF\" );\n    TOML_LEX_CHECK_ACCEPT(lex_integer, \"0xdeadbeef\",  \"0xdeadbeef\" );\n    TOML_LEX_CHECK_ACCEPT(lex_integer, \"0xDEADbeef\",  \"0xDEADbeef\" );\n    TOML_LEX_CHECK_ACCEPT(lex_integer, \"0xDEAD_BEEF\", \"0xDEAD_BEEF\");\n    TOML_LEX_CHECK_ACCEPT(lex_integer, \"0xdead_beef\", \"0xdead_beef\");\n    TOML_LEX_CHECK_ACCEPT(lex_integer, \"0xdead_BEEF\", \"0xdead_BEEF\");\n\n    TOML_LEX_CHECK_ACCEPT(lex_integer, \"0xFF\",     \"0xFF\"    );\n    TOML_LEX_CHECK_ACCEPT(lex_integer, \"0x00FF\",   \"0x00FF\"  );\n    TOML_LEX_CHECK_ACCEPT(lex_integer, \"0x0000FF\", \"0x0000FF\");\n}\n\nBOOST_AUTO_TEST_CASE(test_hex_invalid)\n{\n    TOML_LEX_CHECK_ACCEPT(lex_integer, \"0xAPPLE\",     \"0xA\");\n    TOML_LEX_CHECK_ACCEPT(lex_integer, \"0xDEAD+BEEF\", \"0xDEAD\");\n    TOML_LEX_CHECK_ACCEPT(lex_integer, \"0xDEAD__BEEF\", \"0xDEAD\");\n\n    TOML_LEX_CHECK_REJECT(lex_hex_int, \"0x_DEADBEEF\");\n    TOML_LEX_CHECK_REJECT(lex_hex_int, \"0x+DEADBEEF\");\n    TOML_LEX_CHECK_REJECT(lex_hex_int, \"-0xFF\"      );\n    TOML_LEX_CHECK_REJECT(lex_hex_int, \"-0x00FF\"    );\n\n    TOML_LEX_CHECK_ACCEPT(lex_integer, \"0x_DEADBEEF\", \"0\" );\n    TOML_LEX_CHECK_ACCEPT(lex_integer, \"0x+DEADBEEF\", \"0\" );\n    TOML_LEX_CHECK_ACCEPT(lex_integer, \"-0xFF\"      , \"-0\" );\n    TOML_LEX_CHECK_ACCEPT(lex_integer, \"-0x00FF\"    , \"-0\" );\n}\n\nBOOST_AUTO_TEST_CASE(test_oct_correct)\n{\n    TOML_LEX_CHECK_ACCEPT(lex_integer, \"0o777\",    \"0o777\"  );\n    TOML_LEX_CHECK_ACCEPT(lex_integer, \"0o7_7_7\",  \"0o7_7_7\");\n    TOML_LEX_CHECK_ACCEPT(lex_integer, \"0o007\",    \"0o007\"  );\n\n}\n\nBOOST_AUTO_TEST_CASE(test_oct_invalid)\n{\n    TOML_LEX_CHECK_ACCEPT(lex_integer, \"0o77+7\", \"0o77\");\n    TOML_LEX_CHECK_ACCEPT(lex_integer, \"0o1__0\", \"0o1\");\n\n    TOML_LEX_CHECK_REJECT(lex_oct_int, \"0o800\" );\n    TOML_LEX_CHECK_REJECT(lex_oct_int, \"-0o777\");\n    TOML_LEX_CHECK_REJECT(lex_oct_int, \"0o+777\");\n    TOML_LEX_CHECK_REJECT(lex_oct_int, \"0o_10\" );\n\n    TOML_LEX_CHECK_ACCEPT(lex_integer, \"0o800\",  \"0\");\n    TOML_LEX_CHECK_ACCEPT(lex_integer, \"-0o777\", \"-0\");\n    TOML_LEX_CHECK_ACCEPT(lex_integer, \"0o+777\", \"0\");\n    TOML_LEX_CHECK_ACCEPT(lex_integer, \"0o_10\",  \"0\");\n}\n\nBOOST_AUTO_TEST_CASE(test_bin_correct)\n{\n    TOML_LEX_CHECK_ACCEPT(lex_integer, \"0b10000\",    \"0b10000\"   );\n    TOML_LEX_CHECK_ACCEPT(lex_integer, \"0b010000\",   \"0b010000\"  );\n    TOML_LEX_CHECK_ACCEPT(lex_integer, \"0b01_00_00\", \"0b01_00_00\");\n    TOML_LEX_CHECK_ACCEPT(lex_integer, \"0b111111\",   \"0b111111\"  );\n}\n\nBOOST_AUTO_TEST_CASE(test_bin_invalid)\n{\n    TOML_LEX_CHECK_ACCEPT(lex_bin_int, \"0b11__11\", \"0b11\");\n    TOML_LEX_CHECK_ACCEPT(lex_bin_int, \"0b11+11\" , \"0b11\");\n\n    TOML_LEX_CHECK_REJECT(lex_bin_int, \"-0b10000\");\n    TOML_LEX_CHECK_REJECT(lex_bin_int, \"0b_1111\" );\n}\n", "meta": {"hexsha": "61fe600991eaf9fd3c145c28840f631c6b420b34", "size": 3924, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/lex_integer_test.cpp", "max_stars_repo_name": "ToruNiina/Boost.toml", "max_stars_repo_head_hexsha": "0d29d33834d29f476f2d1a0d9e2758660d3e8eb3", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2018-06-01T14:40:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T12:57:09.000Z", "max_issues_repo_path": "test/lex_integer_test.cpp", "max_issues_repo_name": "ToruNiina/Boost.toml", "max_issues_repo_head_hexsha": "0d29d33834d29f476f2d1a0d9e2758660d3e8eb3", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-12-07T22:33:37.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-09T19:49:50.000Z", "max_forks_repo_path": "test/lex_integer_test.cpp", "max_forks_repo_name": "ToruNiina/Boost.toml", "max_forks_repo_head_hexsha": "0d29d33834d29f476f2d1a0d9e2758660d3e8eb3", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-13T20:57:48.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-13T20:57:48.000Z", "avg_line_length": 37.7307692308, "max_line_length": 69, "alphanum_fraction": 0.7133027523, "num_tokens": 1384, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6791787121629465, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.45193268184282176}}
{"text": "#include <fstream>\n#include <assert.h> \n#include <stdlib.h>\n\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/rmat_graph_generator.hpp>\n#include <boost/random/linear_congruential.hpp>\n#include <boost/graph/graph_traits.hpp>\n\n\nvoid printUsageAndExit()\n{\n  printf(\"%s\", \"Usage:./rmatg x\\n\");\n  printf(\"%s\", \"x is the size of the graph, x>32 (Boost generator hang if x<32)\\n\");\n  exit(0);\n}\n\nint main(int argc, char *argv[])\n{\n  \n  // RMAT paper http://snap.stanford.edu/class/cs224w-readings/chakrabarti04rmat.pdf\n  // Boost doc on RMAT http://www.boost.org/doc/libs/1_49_0/libs/graph_parallel/doc/html/rmat_generator.html\n  \n  typedef boost::adjacency_list<boost::mapS, boost::vecS, boost::directedS> Graph;\n  typedef boost::unique_rmat_iterator<boost::minstd_rand, Graph> RMATGen;\n\n  if (argc < 2) printUsageAndExit();\n  int size = atoi (argv[1]);\n  if (size<32) printUsageAndExit();\n  assert (size > 31 && size < INT_MAX);\n  const unsigned num_edges = 16 * size;\n  /************************\n   * RMAT Gen\n   ************************/\n  std::cout << \"generating ... \"<<'\\n';\n  // values of a,b,c,d are from the graph500.\n  boost::minstd_rand gen;\n  Graph g(RMATGen(gen, size, num_edges, 0.57, 0.19, 0.19, 0.05, true), RMATGen(), size);\n  assert (num_edges == boost::num_edges(g));\n  \n  /************************\n   * Print\n   ************************/\n  boost::graph_traits<Graph>::edge_iterator edge, edge_end;\n  std::cout << \"vertices : \"      << boost::num_vertices(g) <<'\\n';\n  std::cout << \"edges : \"         << boost::num_edges(g) <<'\\n';\n  std::cout << \"average degree : \"<< static_cast<float>(boost::num_edges(g))/boost::num_vertices(g)<< '\\n';\n  \n  // Print in matrix coordinate real general format\n  std::cout << \"writing ... \"<<'\\n';\n  std::stringstream tmp;\n  tmp <<\"local_test_data/rmat_graph_\" << size << \".mtx\";\n  const std::string filename = tmp.str();\n  std::ofstream fout(tmp.str().c_str()) ;\n  if (argv[2]==NULL)\n  {\n    // Power law out degree with random weights\n    fout << \"%%MatrixMarket matrix coordinate real general\\n\";\n    fout << boost::num_vertices(g) <<' '<< boost::num_vertices(g)  <<' '<< boost::num_edges(g) << '\\n';\n    float val;\n    for( boost::tie(edge, edge_end) = boost::edges(g); edge != edge_end; ++edge)\n    {\n      val = (rand()%10)+(rand()%100)*(1e-2f);\n      fout << boost::source(*edge, g) << ' ' << boost::target(*edge, g)<< ' ' << val << '\\n';\n    }\n  }\n  else if (argv[2][0]=='i')\n  {\n    // Power law in degree (ie the transpose will have a power law)\n    // -- Edges only --\n    // * Wraning * edges will be unsorted, use sort_edges.cpp to sort the dataset.\n    fout << boost::num_vertices(g) <<' '<< boost::num_edges(g) << '\\n';\n    for( boost::tie(edge, edge_end) = boost::edges(g); edge != edge_end; ++edge)\n      fout <<boost::target(*edge, g)<< ' ' << boost::source(*edge, g) << '\\n';\n  }\n  else if (argv[2][0]=='o')\n  {\n    // Power law out degree\n    // -- Edges only --\n    fout << boost::num_vertices(g) <<' '<< boost::num_edges(g) << '\\n';\n    for( boost::tie(edge, edge_end) = boost::edges(g); edge != edge_end; ++edge)\n      fout << boost::source(*edge, g) << ' ' << boost::target(*edge, g)<< '\\n';\n  }\n  else printUsageAndExit();\n  fout.close();\n  std::cout << \"done\"<<'\\n';\n  return 0;\n}\n\n", "meta": {"hexsha": "76aa9a2ee9f627cf46f99cc2ede92e3b631b8741", "size": 3270, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/nvgraph/test/generators/rmat.cpp", "max_stars_repo_name": "seunghwak/cugraph", "max_stars_repo_head_hexsha": "f2f6f9147ce8c2f46b7b6dbc335f885c11b69004", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2019-09-13T11:43:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T10:11:59.000Z", "max_issues_repo_path": "cpp/nvgraph/test/generators/rmat.cpp", "max_issues_repo_name": "seunghwak/cugraph", "max_issues_repo_head_hexsha": "f2f6f9147ce8c2f46b7b6dbc335f885c11b69004", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2020-02-12T14:55:25.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-06T17:55:12.000Z", "max_forks_repo_path": "cpp/nvgraph/test/generators/rmat.cpp", "max_forks_repo_name": "seunghwak/cugraph", "max_forks_repo_head_hexsha": "f2f6f9147ce8c2f46b7b6dbc335f885c11b69004", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-04-06T01:34:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-21T17:13:24.000Z", "avg_line_length": 36.3333333333, "max_line_length": 108, "alphanum_fraction": 0.5917431193, "num_tokens": 967, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.6654105454764747, "lm_q1q2_score": 0.45193266869430077}}
{"text": "//=======================================================================\n// Copyright (c) 2013 Piotr Smulewicz\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n/**\n * @file k_cut_long_test.cpp\n * @brief\n * @author Piotr Smulewicz\n * @version 1.0\n * @date 2013-08-20\n */\n\n#include \"test_utils/logger.hpp\"\n#include \"test_utils/test_result_check.hpp\"\n\n#include \"paal/greedy/k_cut/k_cut.hpp\"\n\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/test/unit_test.hpp>\n\n\nconst int nu_vertices = 500;\nconst int nu_edges = 1000*100;\nconst int seed = 43;\nconst int parts = 20;\nconst int max_edge_weight_in_components = 10000;\nconst int max_edge_weight_between_components = 10;\nBOOST_AUTO_TEST_CASE(KCut) {\n    LOGLN(\"wertices: \" << nu_vertices << \" edges: \" << nu_edges);\n    LOGLN(\"parts: \" << parts);\n    //generate graph\n    std::vector<std::pair<int, int>> edges_p;\n    std::vector<long long> cost_edges;\n    std::srand(seed);\n    long long cost_cut_oncomponents = 0;\n    {\n        int source, target, edge_cost, nu_edges_copy = nu_edges;\n        while (--nu_edges_copy) {\n            source = rand() % nu_vertices;\n            target = rand() % nu_vertices;\n            edges_p.push_back(std::make_pair(source, target));\n            if (source % parts == target % parts) {\n                edge_cost = (rand() % max_edge_weight_in_components);\n            } else {\n                edge_cost = (rand() % max_edge_weight_between_components);\n                cost_cut_oncomponents += edge_cost;\n            }\n            cost_edges.push_back(edge_cost);\n        }\n    }\n    boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS,\n                    boost::no_property,\n                    boost::property < boost::edge_weight_t, int>\n                    > graph(edges_p.begin(), edges_p.end(), cost_edges.begin(), nu_vertices);\n    //solve\n    std::vector<std::pair<int, int>> vertices_parts;\n    long long cost_cut = paal::greedy::k_cut(graph, parts, back_inserter(vertices_parts));\n    //print result\n    LOGLN(\"cost cut: \" << cost_cut);\n    std::vector<int> vertices_to_parts;\n    vertices_to_parts.resize(vertices_parts.size());\n    for (auto i:vertices_parts) {\n        LOG(i.first << \"(\" << i.second << \"), \");\n        vertices_to_parts[i.first] = i.second;\n    }\n    LOGLN(\"\");\n    //verificate result\n    auto weight = get(boost::edge_weight, graph);\n    long long cost_cut_verification = 0;\n    auto all_edges = edges(graph);\n    for (auto edge : boost::make_iterator_range(all_edges)) {\n        if (vertices_to_parts[source(edge, graph)] != vertices_to_parts[target(edge, graph)])\n            cost_cut_verification += weight(edge);\n    }\n    BOOST_CHECK_EQUAL(cost_cut, cost_cut_verification);\n    LOGLN(\"Number of parts: \" << parts);\n    //estimate aproximation ratio\n    check_result_compare_to_bound(cost_cut_verification, cost_cut_oncomponents,\n                    2.0 - 2.0 / double(parts), paal::utils::less_equal(),\n                    0LL, \"cut cost on components: \");\n}\n", "meta": {"hexsha": "5b59903c5b94ad45524904754e4a2f282213ac3f", "size": 3183, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/greedy/k_cut/k_cut_long_test.cpp", "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": "test/greedy/k_cut/k_cut_long_test.cpp", "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": "test/greedy/k_cut/k_cut_long_test.cpp", "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.4470588235, "max_line_length": 93, "alphanum_fraction": 0.6094879045, "num_tokens": 763, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.6654105454764746, "lm_q1q2_score": 0.4519326686943007}}
{"text": "//  (C) Copyright John Maddock 2008.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include <pch.hpp>\n\n#include <boost/math/concepts/real_concept.hpp>\n#include <boost/math/tools/test.hpp>\n#define BOOST_TEST_MAIN\n#include <boost/test/unit_test.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/math/special_functions/next.hpp>\n#include <boost/math/special_functions/ulp.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/multiprecision/debug_adaptor.hpp>\n#include <iostream>\n#include <iomanip>\n\n#ifdef BOOST_MSVC\n#pragma warning(disable:4127)\n#endif\n\ntemplate <class T>\nbool is_normalized_value(const T& val)\n{\n   //\n   // Returns false if value has guard digits that are non-zero\n   //\n   boost::intmax_t shift = std::numeric_limits<T>::digits - ilogb(val) - 1;\n   T shifted = scalbn(val, shift);\n   return floor(shifted) == shifted;\n}\n\ntemplate <class T>\nvoid test_value(const T& val, const char* name)\n{\n   using namespace boost::math;\n   T upper = tools::max_value<T>();\n   T lower = -upper;\n\n   std::cout << \"Testing type \" << name << \" with initial value \" << val << std::endl;\n\n   BOOST_CHECK_EQUAL(float_distance(float_next(val), val), -1);\n   BOOST_CHECK(float_next(val) > val);\n   BOOST_CHECK_EQUAL(float_distance(float_prior(val), val), 1);\n   BOOST_CHECK(float_prior(val) < val);\n   BOOST_CHECK_EQUAL(float_distance((boost::math::nextafter)(val, upper), val), -1);\n   BOOST_CHECK((boost::math::nextafter)(val, upper) > val);\n   BOOST_CHECK_EQUAL(float_distance((boost::math::nextafter)(val, lower), val), 1);\n   BOOST_CHECK((boost::math::nextafter)(val, lower) < val);\n   BOOST_CHECK_EQUAL(float_distance(float_next(float_next(val)), val), -2);\n   BOOST_CHECK_EQUAL(float_distance(float_prior(float_prior(val)), val), 2);\n   BOOST_CHECK_EQUAL(float_distance(float_prior(float_prior(val)), float_next(float_next(val))), 4);\n   BOOST_CHECK_EQUAL(float_distance(float_prior(float_next(val)), val), 0);\n   BOOST_CHECK_EQUAL(float_distance(float_next(float_prior(val)), val), 0);\n   if (is_normalized_value(val))\n   {\n      BOOST_CHECK_EQUAL(float_prior(float_next(val)), val);\n      BOOST_CHECK_EQUAL(float_next(float_prior(val)), val);\n   }\n   BOOST_CHECK_EQUAL(float_distance(float_advance(val, 4), val), -4);\n   BOOST_CHECK_EQUAL(float_distance(float_advance(val, -4), val), 4);\n   if(std::numeric_limits<T>::is_specialized && (std::numeric_limits<T>::has_denorm == std::denorm_present))\n   {\n      BOOST_CHECK_EQUAL(float_distance(float_advance(float_next(float_next(val)), 4), float_next(float_next(val))), -4);\n      BOOST_CHECK_EQUAL(float_distance(float_advance(float_next(float_next(val)), -4), float_next(float_next(val))), 4);\n   }\n   if (is_normalized_value(val))\n   {\n      if (val > 0)\n      {\n         T n = val + ulp(val);\n         T fn = float_next(val);\n         if (n > fn)\n         {\n            BOOST_CHECK_LE(ulp(val), boost::math::tools::min_value<T>());\n         }\n         else\n         {\n            BOOST_CHECK_EQUAL(fn, n);\n         }\n      }\n      else if (val == 0)\n      {\n         BOOST_CHECK_GE(boost::math::tools::min_value<T>(), ulp(val));\n      }\n      else\n      {\n         T n = val - ulp(val);\n         T fp = float_prior(val);\n         if (n < fp)\n         {\n            BOOST_CHECK_LE(ulp(val), boost::math::tools::min_value<T>());\n         }\n         else\n         {\n            BOOST_CHECK_EQUAL(fp, n);\n         }\n      }\n   }\n}\n\ntemplate <class T>\nvoid test_values(const T& val, const char* name)\n{\n   static const T a = boost::lexical_cast<T>(\"1.3456724e22\");\n   static const T b = boost::lexical_cast<T>(\"1.3456724e-22\");\n   static const T z = 0;\n   static const T one = 1;\n   static const T radix = std::numeric_limits<T>::radix;\n\n   std::cout << \"Testing type \" << name << std::endl;\n\n   T den = (std::numeric_limits<T>::min)() / 4;\n   if(den != 0)\n   {\n      std::cout << \"Denormals are active\\n\";\n   }\n   else\n   {\n      std::cout << \"Denormals are flushed to zero.\\n\";\n   }\n\n   test_value(a, name);\n   test_value(T(-a), name);\n   test_value(b, name);\n   test_value(T(-b), name);\n   test_value(T(b / 3), name);\n   test_value(T(-b / 3), name);\n   test_value(boost::math::tools::epsilon<T>(), name);\n   test_value(T(-boost::math::tools::epsilon<T>()), name);\n   test_value(boost::math::tools::min_value<T>(), name);\n   test_value(T(-boost::math::tools::min_value<T>()), name);\n   if (std::numeric_limits<T>::is_specialized && (std::numeric_limits<T>::has_denorm == std::denorm_present) && ((std::numeric_limits<T>::min)() / 2 != 0))\n   {\n      test_value(z, name);\n      test_value(T(-z), name);\n   }\n   test_value(one, name);\n   test_value(T(-one), name);\n   test_value(radix, name);\n   test_value(T(-radix), name);\n\n   if(std::numeric_limits<T>::is_specialized && (std::numeric_limits<T>::has_denorm == std::denorm_present) && ((std::numeric_limits<T>::min)() / 2 != 0))\n   {\n      test_value(std::numeric_limits<T>::denorm_min(), name);\n      test_value(T(-std::numeric_limits<T>::denorm_min()), name);\n      test_value(T(2 * std::numeric_limits<T>::denorm_min()), name);\n      test_value(T(-2 * std::numeric_limits<T>::denorm_min()), name);\n   }\n\n   static const int primes[] = {\n      11,     13,     17,     19,     23,     29,\n      31,     37,     41,     43,     47,     53,     59,     61,     67,     71,\n      73,     79,     83,     89,     97,    101,    103,    107,    109,    113,\n      127,    131,    137,    139,    149,    151,    157,    163,    167,    173,\n      179,    181,    191,    193,    197,    199,    211,    223,    227,    229,\n      233,    239,    241,    251,    257,    263,    269,    271,    277,    281,\n      283,    293,    307,    311,    313,    317,    331,    337,    347,    349,\n      353,    359,    367,    373,    379,    383,    389,    397,    401,    409,\n      419,    421,    431,    433,    439,    443,    449,    457,    461,    463,\n   };\n\n   for(unsigned i = 0; i < sizeof(primes)/sizeof(primes[0]); ++i)\n   {\n      T v1 = val;\n      T v2 = val;\n      for(int j = 0; j < primes[i]; ++j)\n      {\n         v1 = boost::math::float_next(v1);\n         v2 = boost::math::float_prior(v2);\n      }\n      BOOST_CHECK_EQUAL(boost::math::float_distance(v1, val), -primes[i]);\n      BOOST_CHECK_EQUAL(boost::math::float_distance(v2, val), primes[i]);\n      BOOST_CHECK_EQUAL(boost::math::float_advance(val, primes[i]), v1);\n      BOOST_CHECK_EQUAL(boost::math::float_advance(val, -primes[i]), v2);\n   }\n   if(std::numeric_limits<T>::is_specialized && (std::numeric_limits<T>::has_infinity))\n   {\n      BOOST_CHECK_EQUAL(boost::math::float_prior(std::numeric_limits<T>::infinity()), (std::numeric_limits<T>::max)());\n      BOOST_CHECK_EQUAL(boost::math::float_next(-std::numeric_limits<T>::infinity()), -(std::numeric_limits<T>::max)());\n      BOOST_MATH_CHECK_THROW(boost::math::float_prior(-std::numeric_limits<T>::infinity()), std::domain_error);\n      BOOST_MATH_CHECK_THROW(boost::math::float_next(std::numeric_limits<T>::infinity()), std::domain_error);\n      if(boost::math::policies:: BOOST_MATH_OVERFLOW_ERROR_POLICY == boost::math::policies::throw_on_error)\n      {\n         BOOST_MATH_CHECK_THROW(boost::math::float_prior(-(std::numeric_limits<T>::max)()), std::overflow_error);\n         BOOST_MATH_CHECK_THROW(boost::math::float_next((std::numeric_limits<T>::max)()), std::overflow_error);\n      }\n      else\n      {\n         BOOST_CHECK_EQUAL(boost::math::float_prior(-(std::numeric_limits<T>::max)()), -std::numeric_limits<T>::infinity());\n         BOOST_CHECK_EQUAL(boost::math::float_next((std::numeric_limits<T>::max)()), std::numeric_limits<T>::infinity());\n      }\n   }\n}\n\nBOOST_AUTO_TEST_CASE( test_main )\n{\n   // Very slow, but debuggable:\n   //test_values(boost::multiprecision::number<boost::multiprecision::debug_adaptor<boost::multiprecision::cpp_dec_float_50::backend_type> >(0), \"cpp_dec_float_50\");\n\n   // Faster, but no good for diagnising the cause of any issues:\n   test_values(boost::multiprecision::cpp_dec_float_50(0), \"cpp_dec_float_50\");\n}\n", "meta": {"hexsha": "e1b490de61cea334448d79d9ccc41f38eb31bab0", "size": 8172, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "deps/src/boost_1_65_1/libs/math/test/test_next_decimal.cpp", "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/libs/math/test/test_next_decimal.cpp", "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/libs/math/test/test_next_decimal.cpp", "max_forks_repo_name": "shreyasvj25/turicreate", "max_forks_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 39.6699029126, "max_line_length": 165, "alphanum_fraction": 0.6235927558, "num_tokens": 2304, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6791786861878392, "lm_q2_score": 0.6654105454764747, "lm_q1q2_score": 0.4519326600522455}}
{"text": "//\n// Created by dch on 13/03/17.\n//\n\n#include <cuNDArray_fileio.h>\n#include <cuNDArray_math.h>\n\n#include <boost/program_options.hpp>\n#include <numeric>\n\n#include \"mssim.h\"\n\nnamespace po = boost::program_options;\n\nusing namespace Gadgetron;\n\nint main(int argc, char** argv) {\n\n    std::string image_file;\n    std::string reference_file;\n    float sigma;\n    po::options_description desc(\"Allowed options\");\n\n    desc.add_options()\n            (\"help\", \"produce help message\")\n            (\"image\",po::value<std::string>(&image_file))\n            (\"gold\",po::value<std::string>(&reference_file))\n            (\"sigma\",po::value<float>(&sigma)->default_value(1.5f));\n\n\n\n\tpo::variables_map vm;\n\tpo::store(po::parse_command_line(argc, argv, desc), vm);\n\tpo::notify(vm);\n\n    auto image = read_nd_array<float>(image_file.c_str());\n    auto gold = read_nd_array<float>(reference_file.c_str());\n\n\n\n    auto dims = *image->get_dimensions();\n    size_t phases = dims[3];\n\n    std::vector<float> results;\n\n\n    std::vector<size_t> dims3d(dims.begin(),dims.end()-1);\n\n    size_t elements = std::accumulate(dims3d.begin(),dims3d.end(),1,std::multiplies<size_t>());\n\n    for (size_t phase = 0; phase < phases; phase++){\n        hoNDArray<float> image_view(dims3d,image->get_data_ptr()+phase*elements);\n        hoNDArray<float> ref_view(dims3d,gold->get_data_ptr()+phase*elements);\n\n        cuNDArray<float> cu_image(image_view);\n        cuNDArray<float> cu_ref(ref_view);\n\n\n        results.push_back(mssim(&cu_image,&cu_ref,floatd3(sigma,sigma,sigma)));\n//\n//        cu_image -= cu_ref;\n//\n//        results.push_back(nrm2(&cu_image));\n\n    }\n\n\n    float sum = std::accumulate(results.begin(),results.end(),0.0f)/results.size();\n\n    std::cout << sum << std::endl;\n//\n//    for (auto r : results)\n//        std::cout << r <<  \" \";\n\n\n\n}\n\n", "meta": {"hexsha": "975603cfd4c355c44dafead10744f8c3fffd1d79", "size": 1823, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "xray/compare_images.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/compare_images.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/compare_images.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": 23.0759493671, "max_line_length": 95, "alphanum_fraction": 0.6357652222, "num_tokens": 481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432182679956, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.45190087870815654}}
{"text": "/*\n * @Description: tf\u76d1\u542c\u6a21\u5757\n * @Author: Ren Qian\n * @Date: 2020-02-06 16:10:31\n */\n#include \"lidar_localization/tf_listener/tf_listener.hpp\"\n\n#include <Eigen/Geometry>\n\nnamespace lidar_localization {\nTFListener::TFListener(ros::NodeHandle& nh, std::string base_frame_id, std::string child_frame_id) \n    :nh_(nh), base_frame_id_(base_frame_id), child_frame_id_(child_frame_id) {\n}\n\nbool TFListener::LookupData(Eigen::Matrix4f& transform_matrix) {\n    try {\n        tf::StampedTransform transform;\n        listener_.lookupTransform(base_frame_id_, child_frame_id_, ros::Time(0), transform);\n        TransformToMatrix(transform, transform_matrix);\n        return true;\n    } catch (tf::TransformException &ex) {\n        return false;\n    }\n}\n\nbool TFListener::TransformToMatrix(const tf::StampedTransform& transform, Eigen::Matrix4f& transform_matrix) {\n    Eigen::Translation3f tl_btol(transform.getOrigin().getX(), transform.getOrigin().getY(), transform.getOrigin().getZ());\n    \n    double roll, pitch, yaw;\n    tf::Matrix3x3(transform.getRotation()).getEulerYPR(yaw, pitch, roll);\n    Eigen::AngleAxisf rot_x_btol(roll, Eigen::Vector3f::UnitX());\n    Eigen::AngleAxisf rot_y_btol(pitch, Eigen::Vector3f::UnitY());\n    Eigen::AngleAxisf rot_z_btol(yaw, Eigen::Vector3f::UnitZ());\n\n    // \u6b64\u77e9\u9635\u4e3a child_frame_id \u5230 base_frame_id \u7684\u8f6c\u6362\u77e9\u9635\n    transform_matrix = (tl_btol * rot_z_btol * rot_y_btol * rot_x_btol).matrix();\n\n    return true;\n}\n}", "meta": {"hexsha": "263233c253472dc66ca0d4c9ead082c4ab2ff698", "size": 1434, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/lidar_localization/src/tf_listener/tf_lisener.cpp", "max_stars_repo_name": "WeihengXia0123/LiDAR_SLAM_revisit", "max_stars_repo_head_hexsha": "2f47fc3108c8f95b57c2c70972a9c5afe027881c", "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": "src/lidar_localization/src/tf_listener/tf_lisener.cpp", "max_issues_repo_name": "WeihengXia0123/LiDAR_SLAM_revisit", "max_issues_repo_head_hexsha": "2f47fc3108c8f95b57c2c70972a9c5afe027881c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lidar_localization/src/tf_listener/tf_lisener.cpp", "max_forks_repo_name": "WeihengXia0123/LiDAR_SLAM_revisit", "max_forks_repo_head_hexsha": "2f47fc3108c8f95b57c2c70972a9c5afe027881c", "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": 35.85, "max_line_length": 123, "alphanum_fraction": 0.7189679219, "num_tokens": 406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.4519008712132011}}
{"text": "#ifndef CT_TYPES_EIGEN_HPP\n#define CT_TYPES_EIGEN_HPP\n#include \"../reflect.hpp\"\n#include \"TArrayView.hpp\"\n#include <Eigen/Core>\n#include <array>\n\nnamespace ct\n{\n    template <class T, int ROWS, int COLS, int OPTS, int MAX_ROWS, int MAX_COLS>\n    struct ReflectImpl<Eigen::Matrix<T, ROWS, COLS, OPTS, MAX_ROWS, MAX_COLS>, void>\n    {\n        using DataType = Eigen::Matrix<T, ROWS, COLS, OPTS, MAX_ROWS, MAX_COLS>;\n        using this_t = ReflectImpl<DataType, void>;\n        static constexpr StringView getTypeName() { return GetName<DataType>::getName(); }\n\n        static std::array<Eigen::Index, 2> shape(const DataType& data) { return {data.rows(), data.cols()}; }\n\n        static void reshape(DataType& data, const std::array<Eigen::Index, 2> shape)\n        {\n            data.resize(shape[0], shape[1]);\n        }\n\n        static TArrayView<const T> getData(const DataType& mat) { return {mat.data(), ROWS * COLS}; }\n\n        static TArrayView<T> getDataMutable(DataType& mat) { return {mat.data(), ROWS * COLS}; }\n\n        REFLECT_STUB\n            PROPERTY_WITH_FLAG(Flags::COMPILE_TIME_CONSTANT, shape, &this_t::shape)\n            PROPERTY(data, &this_t::getData, &this_t::getDataMutable)\n            PROPERTY_WITH_FLAG(Flags::COMPILE_TIME_CONSTANT, size)\n            PROPERTY_WITH_FLAG(Flags::COMPILE_TIME_CONSTANT, colStride)\n            PROPERTY_WITH_FLAG(Flags::COMPILE_TIME_CONSTANT, rowStride)\n            PROPERTY_WITH_FLAG(Flags::COMPILE_TIME_CONSTANT, cols)\n            PROPERTY_WITH_FLAG(Flags::COMPILE_TIME_CONSTANT, rows)\n        REFLECT_INTERNAL_END;\n        static constexpr Indexer<NUM_FIELDS - 1> end() { return Indexer<NUM_FIELDS - 1>(); }\n    };\n\n    template <class T, int OPTS, int MAX_ROWS, int MAX_COLS>\n    struct ReflectImpl<Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, OPTS, MAX_ROWS, MAX_COLS>, void>\n    {\n        using DataType = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, OPTS, MAX_ROWS, MAX_COLS>;\n        using this_t = ReflectImpl<DataType, void>;\n        static constexpr StringView getTypeName() { return GetName<DataType>::getName(); }\n\n        static std::array<Eigen::Index, 2> shape(const DataType& data) { return {data.rows(), data.cols()}; }\n\n        static void reshape(DataType& data, const std::array<Eigen::Index, 2> shape)\n        {\n            data.resize(shape[0], shape[1]);\n        }\n\n        static TArrayView<const T> getData(const DataType& mat)\n        {\n            return {mat.data(), static_cast<size_t>(mat.rows() * mat.cols())};\n        }\n\n        static TArrayView<T> getDataMutable(DataType& mat)\n        {\n            return {mat.data(), static_cast<size_t>(mat.rows() * mat.cols())};\n        }\n\n        REFLECT_STUB\n            PROPERTY(shape, &this_t::shape, &this_t::reshape)\n            PROPERTY(data, &this_t::getData, &this_t::getDataMutable)\n            PROPERTY(size)\n            PROPERTY(colStride)\n            PROPERTY(rowStride)\n            PROPERTY(cols)\n            PROPERTY(rows)\n        REFLECT_INTERNAL_END;\n        static constexpr Indexer<NUM_FIELDS - 1> end() { return ct::Indexer<NUM_FIELDS - 1>(); }\n    };\n\n    template <typename T, int _Rows, int _Cols, int _Options, int _MaxRows, int _MaxCols>\n    struct ReflectImpl<Eigen::Array<T, _Rows, _Cols, _Options, _MaxRows, _MaxCols>, void>\n    {\n        using DataType = Eigen::Array<T, _Rows, _Cols, _Options, _MaxRows, _MaxCols>;\n        using this_t = ReflectImpl<DataType, void>;\n        static constexpr StringView getTypeName() { return GetName<DataType>::getName(); }\n\n        static TArrayView<const T> getData(const DataType& arr)\n        {\n            return {arr.data(), static_cast<size_t>(arr.rows() * arr.cols())};\n        }\n\n        static TArrayView<T> getDataMutable(DataType& arr)\n        {\n            return {arr.data(), static_cast<size_t>(arr.rows() * arr.cols())};\n        }\n\n        REFLECT_STUB\n            PROPERTY(data, &this_t::getData, &this_t::getDataMutable)\n        REFLECT_INTERNAL_END;\n        static constexpr Indexer<NUM_FIELDS - 1> end() { return Indexer<NUM_FIELDS - 1>(); }\n    };\n\n    DECL_NAME(Eigen::MatrixXf);\n    DECL_NAME(Eigen::Matrix2f);\n    DECL_NAME(Eigen::Matrix3f);\n    DECL_NAME(Eigen::Matrix4f);\n\n    DECL_NAME(Eigen::MatrixXd);\n    DECL_NAME(Eigen::Matrix2d);\n    DECL_NAME(Eigen::Matrix3d);\n    DECL_NAME(Eigen::Matrix4d);\n\n} // namespace ct\n\n#endif // CT_EIGEN_HPP\n", "meta": {"hexsha": "259bca9babc7ef98d8caadaa0aa4811670a1c96f", "size": 4368, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ct/types/eigen.hpp", "max_stars_repo_name": "dtmoodie/ct", "max_stars_repo_head_hexsha": "21dc0092d9d2615e5c4510371c63d9233118de5e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-07-28T01:43:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-09T09:39:09.000Z", "max_issues_repo_path": "include/ct/types/eigen.hpp", "max_issues_repo_name": "dtmoodie/ct", "max_issues_repo_head_hexsha": "21dc0092d9d2615e5c4510371c63d9233118de5e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-12-21T00:09:07.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-26T22:00:45.000Z", "max_forks_repo_path": "include/ct/types/eigen.hpp", "max_forks_repo_name": "dtmoodie/ct", "max_forks_repo_head_hexsha": "21dc0092d9d2615e5c4510371c63d9233118de5e", "max_forks_repo_licenses": ["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.0, "max_line_length": 109, "alphanum_fraction": 0.6362179487, "num_tokens": 1088, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.4519008712132011}}
{"text": "#include <blitz/array.h>\n#include <blitz/funcs.h>\n\nusing namespace blitz;\n\nint main()\n{\n    Array<int,1> A(4), B(4);\n    Array<float,1> C(4);\n\n    A = 1, 2, 3, 5;\n    B = 2, 2, 2, 7;\n\n    C = A / B;\n    cout << C << endl;\n\n#ifdef BZ_NEW_EXPRESSION_TEMPLATES\n    C = A / cast<float>(B);\n#else\n    C = A / cast(B, float());\n#endif\n    cout << C << endl;\n\n    return 0;\n}\n\n", "meta": {"hexsha": "7d84dd05fd52ab302090b38683231ec75fdf6af5", "size": 370, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depspawn-blitz-0.10/doc/examples/cast.cpp", "max_stars_repo_name": "fraguela/depspawn", "max_stars_repo_head_hexsha": "b5760f4c0d38a1b245ee5274e2ccc5c5fe2d3d45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-04-12T11:05:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T11:10:27.000Z", "max_issues_repo_path": "ibtk/third_party/blitz-0.10/doc/examples/cast.cpp", "max_issues_repo_name": "MSV-Project/IBAMR", "max_issues_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ibtk/third_party/blitz-0.10/doc/examples/cast.cpp", "max_forks_repo_name": "MSV-Project/IBAMR", "max_forks_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 13.7037037037, "max_line_length": 34, "alphanum_fraction": 0.5162162162, "num_tokens": 137, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217431943271999, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.4519008637182455}}
{"text": "//\n// Created by Amir Masoud Abdol on 2019-06-17.\n//\n\n#define BOOST_TEST_MODULE MetaAnalysis Test\n#define BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n\n#include <armadillo>\n#include <iostream>\n#include <fstream>\n\n#include \"ExperimentSetup.h\"\n#include \"Experiment.h\"\n#include \"Researcher.h\"\n#include \"HackingStrategy.h\"\n#include \"Journal.h\"\n#include \"ResearchStrategy.h\"\n#include \"PersistenceManager.h\"\n\n#include \"sam.h\"\n\n#include \"test_fixtures.h\"\n\nusing namespace arma;\nusing namespace sam;\nusing namespace std;\n\nusing json = nlohmann::json;\n\nbool FLAGS::VERBOSE = false;\nbool FLAGS::PROGRESS = false;\nbool FLAGS::DEBUG = false;\nbool FLAGS::UPDATECONFIG = false;\n\nBOOST_FIXTURE_TEST_SUITE( meta_analysis_strategy, SampleResearch )\n\n    BOOST_AUTO_TEST_CASE( fixed_effect_model )\n    {\n        \n        float r_estimate = 0.7766;\n        \n        nobs = 20;\n        mean = 0.5;\n        var = 2.;\n        cov = 0.75;\n        \n        j_conf[\"max_pubs\"] = 20;\n        \n        initResearch();\n        \n        runSampleSimulation();\n        \n        PersistenceManager::Writer pubwriter(\"/Users/amabdol/meta_pubs.csv\");\n        \n        FixedEffectEstimator fixed_model;\n        std::cout << \"Fixed: \" << std::endl;\n        std::cout << fixed_model.estimate(publications[0]);\n        \n        auto fe = fixed_model.estimate(publications[0]);\n        \n        BOOST_CHECK_SMALL(fe[0] - r_estimate, 0.001);\n        \n        RandomEffectEstimator random_model;\n        std::cout << \"Random: \" << std::endl;\n        std::cout << random_model.estimate(publications[0]);\n        \n        pubwriter.write(publications[0]);\n        \n        \n        \n    }\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "35e93ce3f557930df78d0cd1402de1d0aa4e87a2", "size": 1687, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sam-project/bakker-et-al-2012/SAM/SAM/tests/src/meta_analysis_test.cpp", "max_stars_repo_name": "amirmasoudabdol/bakker-et-al-2012-reproduction-using-sam", "max_stars_repo_head_hexsha": "518ab1cebaa80c19a12e92db8ae87386512ae053", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-25T20:21:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T20:21:41.000Z", "max_issues_repo_path": "sam-project/bakker-et-al-2012/SAM/SAM/tests/src/meta_analysis_test.cpp", "max_issues_repo_name": "amirmasoudabdol/bakker-et-al-2012-reproduction-using-sam", "max_issues_repo_head_hexsha": "518ab1cebaa80c19a12e92db8ae87386512ae053", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sam-project/bakker-et-al-2012/SAM/SAM/tests/src/meta_analysis_test.cpp", "max_forks_repo_name": "amirmasoudabdol/bakker-et-al-2012-reproduction-using-sam", "max_forks_repo_head_hexsha": "518ab1cebaa80c19a12e92db8ae87386512ae053", "max_forks_repo_licenses": ["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.4933333333, "max_line_length": 77, "alphanum_fraction": 0.6289270895, "num_tokens": 394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.45184681765604123}}
{"text": "#include <ros/ros.h>\n#include <Eigen/Geometry>\n#include <nav_msgs/Odometry.h>\n#include <sensor_msgs/Imu.h>\n#include <quadrotor_msgs/TRPYCommand.h>\n#include <quadrotor_simulator/Quadrotor.h>\n\ntypedef struct _ControlInput\n{\n  double rpm[4];\n} ControlInput;\n\ntypedef struct _Command\n{\n  float thrust;\n  float roll, pitch, yaw;\n  bool enable_motors;\n  float kR[3];\n  float kOm[3];\n} Command;\n\nstatic Command command;\n\nvoid stateToOdomMsg(const QuadrotorSimulator::Quadrotor::State &state, nav_msgs::Odometry &odom);\nvoid quadToImuMsg(const QuadrotorSimulator::Quadrotor &quad, sensor_msgs::Imu &imu);\n\n\nstatic ControlInput getControl(const QuadrotorSimulator::Quadrotor &quad, const Command &cmd)\n{\n  const double _kf = quad.getPropellerThrustCoefficient();\n  const double _km = quad.getPropellerMomentCoefficient();\n  const double kf = _kf;\n  const double km = _km/_kf*kf;\n\n  const double d = quad.getArmLength();\n  const Eigen::Matrix3f J = quad.getInertia().cast<float>();\n  const float I[3][3] = {{J(0,0), J(0,1), J(0,2)},\n                         {J(1,0), J(1,1), J(1,2)},\n                         {J(2,0), J(2,1), J(2,2)}};\n  const QuadrotorSimulator::Quadrotor::State state = quad.getState();\n\n  float R11 = state.R(0,0);\n  float R12 = state.R(0,1);\n  float R13 = state.R(0,2);\n  float R21 = state.R(1,0);\n  float R22 = state.R(1,1);\n  float R23 = state.R(1,2);\n  float R31 = state.R(2,0);\n  float R32 = state.R(2,1);\n  float R33 = state.R(2,2);\n\n  float Om1 = state.omega(0);\n  float Om2 = state.omega(1);\n  float Om3 = state.omega(2);\n\n  float Rd11 = cos(cmd.yaw)*cos(cmd.pitch);\n  float Rd12 = cos(cmd.yaw)*sin(cmd.pitch)*sin(cmd.roll) - cos(cmd.roll)*sin(cmd.yaw);\n  float Rd13 = sin(cmd.yaw)*sin(cmd.roll) + cos(cmd.yaw)*cos(cmd.roll)*sin(cmd.pitch);\n  float Rd21 = cos(cmd.pitch)*sin(cmd.yaw);\n  float Rd22 = cos(cmd.yaw)*cos(cmd.roll) + sin(cmd.yaw)*sin(cmd.pitch)*sin(cmd.roll);\n  float Rd23 = cos(cmd.roll)*sin(cmd.yaw)*sin(cmd.pitch) - cos(cmd.yaw)*sin(cmd.roll);\n  float Rd31 = -sin(cmd.pitch);\n  float Rd32 = cos(cmd.pitch)*sin(cmd.roll);\n  float Rd33 = cos(cmd.pitch)*cos(cmd.roll);\n\n  float Psi = 0.5f*(3.0f - (Rd11*R11 + Rd21*R21 + Rd31*R31 +\n                            Rd12*R12 + Rd22*R22 + Rd32*R32 +\n                            Rd13*R13 + Rd23*R23 + Rd33*R33));\n\n  float force = 0;\n  if(Psi < 1.0f) // Position control stability guaranteed only when Psi < 1\n    force = cmd.thrust;\n\n  float eR1 = 0.5f*(R12*Rd13 - R13*Rd12 + R22*Rd23 - R23*Rd22 + R32*Rd33 - R33*Rd32);\n  float eR2 = 0.5f*(R13*Rd11 - R11*Rd13 - R21*Rd23 + R23*Rd21 - R31*Rd33 + R33*Rd31);\n  float eR3 = 0.5f*(R11*Rd12 - R12*Rd11 + R21*Rd22 - R22*Rd21 + R31*Rd32 - R32*Rd31);\n\n  float eOm1 = Om1;\n  float eOm2 = Om2;\n  float eOm3 = Om3;\n\n  float in1 = Om2*(I[2][0]*Om1 + I[2][1]*Om2 + I[2][2]*Om3) - Om3*(I[1][0]*Om1 + I[1][1]*Om2 + I[1][2]*Om3);\n  float in2 = Om3*(I[0][0]*Om1 + I[0][1]*Om2 + I[0][2]*Om3) - Om1*(I[2][0]*Om1 + I[2][1]*Om2 + I[2][2]*Om3);\n  float in3 = Om1*(I[1][0]*Om1 + I[1][1]*Om2 + I[1][2]*Om3) - Om2*(I[0][0]*Om1 + I[0][1]*Om2 + I[0][2]*Om3);\n\n  float M1 = -cmd.kR[0]*eR1 - cmd.kOm[0]*eOm1 + in1;\n  float M2 = -cmd.kR[1]*eR2 - cmd.kOm[1]*eOm2 + in2;\n  float M3 = -cmd.kR[2]*eR3 - cmd.kOm[2]*eOm3 + in3;\n\n  float w_sq[4];\n  w_sq[0] = force/(4*kf) - M2/(2*d*kf) + M3/(4*km);\n  w_sq[1] = force/(4*kf) + M2/(2*d*kf) + M3/(4*km);\n  w_sq[2] = force/(4*kf) + M1/(2*d*kf) - M3/(4*km);\n  w_sq[3] = force/(4*kf) - M1/(2*d*kf) - M3/(4*km);\n\n  ControlInput control;\n  for(int i = 0; i < 4; i++)\n  {\n    if(cmd.enable_motors)\n    {\n      if(w_sq[i] < 0)\n        w_sq[i] = 0;\n\n      control.rpm[i] = sqrtf(w_sq[i]);\n    }\n    else\n    {\n      control.rpm[i] = 0;\n    }\n  }\n  return control;\n}\n\nstatic void cmd_callback(const quadrotor_msgs::TRPYCommand::ConstPtr &cmd)\n{\n  command.thrust = cmd->thrust;\n  command.roll = cmd->roll;\n  command.pitch = cmd->pitch;\n  command.yaw = cmd->yaw;\n  command.enable_motors = cmd->aux.enable_motors;\n}\n\nint main(int argc, char **argv)\n{\n  ros::init(argc, argv, \"quadrotor_simulator_so3\");\n\n  ros::NodeHandle n(\"~\");\n\n  ros::Publisher odom_pub = n.advertise<nav_msgs::Odometry>(\"odom\", 100);\n  ros::Publisher imu_pub = n.advertise<sensor_msgs::Imu>(\"imu\", 100);\n  ros::Subscriber cmd_sub = n.subscribe(\"cmd\", 100, &cmd_callback, ros::TransportHints().tcpNoDelay());\n\n  double simulation_rate;\n  n.param(\"rate/simulation\", simulation_rate, 1000.0);\n  ROS_ASSERT(simulation_rate > 0);\n\n  double odom_rate;\n  n.param(\"rate/odom\", odom_rate, 100.0);\n  const ros::Duration odom_pub_duration(1/odom_rate);\n\n  std::string quad_name;\n  n.param(\"quadrotor_name\", quad_name, std::string(\"quadrotor\"));\n\n  double kR[3], kOm[3];\n  n.param(\"gains/rot/x\", kR[0], 1.0);\n  n.param(\"gains/rot/y\", kR[1], 1.0);\n  n.param(\"gains/rot/z\", kR[2], 1.0);\n  n.param(\"gains/ang/x\", kOm[0], 0.13);\n  n.param(\"gains/ang/y\", kOm[1], 0.13);\n  n.param(\"gains/ang/z\", kOm[2], 0.1);\n  command.kR[0] = kR[0], command.kR[1] = kR[1], command.kR[2] = kR[2];\n  command.kOm[0] = kOm[0], command.kOm[1] = kOm[1], command.kOm[2] = kOm[2];\n\n  QuadrotorSimulator::Quadrotor quad;\n  QuadrotorSimulator::Quadrotor::State state = quad.getState();\n  n.param(\"initial_pos/x\", state.x(0), 0.0);\n  n.param(\"initial_pos/y\", state.x(1), 0.0);\n  n.param(\"initial_pos/z\", state.x(2), 0.0);\n  quad.setState(state);\n\n  ros::Rate r(simulation_rate);\n  const double simulation_dt = 1/simulation_rate;\n\n  command.enable_motors = false;\n\n  ControlInput control;\n\n  nav_msgs::Odometry odom_msg;\n  sensor_msgs::Imu imu_msg;\n  odom_msg.header.frame_id = \"/simulator\";\n  odom_msg.child_frame_id = \"/\" + quad_name;\n  imu_msg.header.frame_id = \"/\" + quad_name;\n\n  ros::Time next_odom_pub_time = ros::Time::now();\n  while(n.ok())\n  {\n    ros::spinOnce();\n\n    control = getControl(quad, command);\n    //ROS_INFO(\"command_thrust: %f, %f, %f, %f\\nrpm: %f, %f, %f, %f\", command.thrust, command.roll, command.pitch, command.yaw, control.rpm[0], control.rpm[1], control.rpm[2], control.rpm[3]);\n    quad.setInput(control.rpm[0], control.rpm[1], control.rpm[2], control.rpm[3]);\n    quad.step(simulation_dt);\n\n    ros::Time tnow = ros::Time::now();\n\n    if(tnow >= next_odom_pub_time)\n    {\n      next_odom_pub_time += odom_pub_duration;\n      state = quad.getState();\n      stateToOdomMsg(state, odom_msg);\n      quadToImuMsg(quad, imu_msg);\n      odom_msg.header.stamp = tnow;\n      imu_msg.header.stamp = tnow;\n      odom_pub.publish(odom_msg);\n      imu_pub.publish(imu_msg);\n    }\n\n    r.sleep();\n  }\n\n  return 0;\n}\n\nvoid stateToOdomMsg(const QuadrotorSimulator::Quadrotor::State &state, nav_msgs::Odometry &odom)\n{\n  odom.pose.pose.position.x = state.x(0);\n  odom.pose.pose.position.y = state.x(1);\n  odom.pose.pose.position.z = state.x(2);\n\n  Eigen::Quaterniond q(state.R);\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\n  odom.twist.twist.linear.x = state.v(0);\n  odom.twist.twist.linear.y = state.v(1);\n  odom.twist.twist.linear.z = state.v(2);\n\n  odom.twist.twist.angular.x = state.omega(0);\n  odom.twist.twist.angular.y = state.omega(1);\n  odom.twist.twist.angular.z = state.omega(2);\n}\n\nvoid quadToImuMsg(const QuadrotorSimulator::Quadrotor &quad, sensor_msgs::Imu &imu)\n{\n  const QuadrotorSimulator::Quadrotor::State state = quad.getState();\n  Eigen::Quaterniond q(state.R);\n  imu.orientation.x = q.x();\n  imu.orientation.y = q.y();\n  imu.orientation.z = q.z();\n  imu.orientation.w = q.w();\n\n  imu.angular_velocity.x = state.omega(0);\n  imu.angular_velocity.y = state.omega(1);\n  imu.angular_velocity.z = state.omega(2);\n\n  const double kf = quad.getPropellerThrustCoefficient();\n  const double m = quad.getMass();\n  const Eigen::Vector3d &external_force = quad.getExternalForce();\n  const double g = quad.getGravity();\n  const double thrust = kf*state.motor_rpm.square().sum();\n  Eigen::Vector3d acc;\n  if(state.x(2) < 1e-4)\n  {\n    acc = state.R*(external_force/m + Eigen::Vector3d(0,0,g));\n  }\n  else\n  {\n    acc = thrust/m*Eigen::Vector3d(0,0,1) + state.R*external_force/m;\n  }\n\n  imu.linear_acceleration.x = acc(0);\n  imu.linear_acceleration.y = acc(1);\n  imu.linear_acceleration.z = acc(2);\n}\n", "meta": {"hexsha": "96be9b9435a9d932fd2ffeaba6cb38801ddf9c94", "size": 8184, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Src/ros_simulator/src/quadrotor_simulator/src/quadrotor_simulator_trpy.cpp", "max_stars_repo_name": "Drona-Org/Drona-DMR", "max_stars_repo_head_hexsha": "ecc756ec137aee90ab5ac9ea97f09b6e030066f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-05-14T14:49:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T06:53:28.000Z", "max_issues_repo_path": "Src/ros_simulator/src/quadrotor_simulator/src/quadrotor_simulator_trpy.cpp", "max_issues_repo_name": "Dronacharya-Org/Dronacharya", "max_issues_repo_head_hexsha": "ecc756ec137aee90ab5ac9ea97f09b6e030066f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Src/ros_simulator/src/quadrotor_simulator/src/quadrotor_simulator_trpy.cpp", "max_forks_repo_name": "Dronacharya-Org/Dronacharya", "max_forks_repo_head_hexsha": "ecc756ec137aee90ab5ac9ea97f09b6e030066f0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-12-15T20:18:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-31T19:26:57.000Z", "avg_line_length": 31.8443579767, "max_line_length": 192, "alphanum_fraction": 0.6380742913, "num_tokens": 2849, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.5813030906443134, "lm_q1q2_score": 0.45184681165824375}}
{"text": "#pragma once\n\n#include <numeric>\n\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/function/cumsum.hpp>\n#include <boost/simd/function/splat.hpp>\n#include <boost/simd/function/sum.hpp>\n\n#include \"source.hpp\"\n\ntypedef boost::simd::pack<double> pack_double;\n\ntemplate<typename tag>\ndouble balanced_sum(source_1d<tag> &f)\n{\n    double res = 0.;\n    while (f.can_procure(1, res) && !f.is_aligned()) {\n        f.procure(res);\n    }\n\n    pack_double stack[62];\n    size_t p = 0;\n    for (size_t iteration = 0; f.can_procure(4, stack[0]); ++iteration) {\n        pack_double v = boost::simd::Zero<pack_double>();\n        f.procure(v);\n        f.procure(v);\n        pack_double w = boost::simd::Zero<pack_double>();\n        f.procure(w);\n        f.procure(w);\n        v += w;\n        size_t bitmask = 1;\n        for (; iteration & bitmask; bitmask <<= 1, --p) {\n            v += stack[p - 1];\n        }\n        stack[p++] = v;\n    }\n    pack_double vsum = boost::simd::Zero<pack_double>();\n    for (size_t i = p; i > 0; --i) {\n        vsum += stack[i - 1];\n    }\n    res = std::accumulate(vsum.begin(), vsum.end(), res);\n    while (f.can_procure(1, res)) {\n        f.procure(res);\n    }\n    return res;\n}\n\ntemplate<typename tag>\ndouble twin_balanced_sum(source_2d<tag>& f)\n{\n    double stat1 = 0.;\n    double stat2 = 0.;\n    while (f.can_procure(1, stat1) && !f.is_aligned()) {\n        f.procure(stat1, stat2);\n    }\n\n    pack_double stack1[62];\n    pack_double stack2[62];\n    size_t p = 0;\n    for (size_t iteration = 0; f.can_procure(4, stack1[0]); ++iteration) {\n        pack_double v1 = boost::simd::Zero<pack_double>();\n        pack_double v2 = boost::simd::Zero<pack_double>();\n        f.procure(v1, v2);\n        f.procure(v1, v2);\n        pack_double w1 = boost::simd::Zero<pack_double>();\n        pack_double w2 = boost::simd::Zero<pack_double>();\n        f.procure(w1, w2);\n        f.procure(w1, w2);\n        v1 += w1;\n        v2 += w2;\n        size_t bitmask = 1;\n        for (; iteration & bitmask; bitmask <<= 1, --p) {\n            v1 += stack1[p - 1];\n            v2 += stack2[p - 1];\n        }\n        stack1[p] = v1;\n        stack2[p++] = v2;\n    }\n    pack_double vsum1 = boost::simd::Zero<pack_double>();\n    pack_double vsum2 = boost::simd::Zero<pack_double>();\n    for (size_t i = p; i > 0; --i) {\n        vsum1 += stack1[i - 1];\n        vsum2 += stack2[i - 1];\n    }\n    stat1 = std::accumulate(vsum1.begin(), vsum1.end(), stat1);\n    stat2 = std::accumulate(vsum2.begin(), vsum2.end(), stat2);\n    while (f.can_procure(1, stat1)) {\n        f.procure(stat1, stat2);\n    }\n    return f.result(stat1, stat2);\n}\n\ninline void kahan_update(double &accumulator, double &compensator, double value)\n{\n    double const new_accumulator = accumulator + value;\n    double const first_option = (accumulator - new_accumulator) + value;\n    double const second_option = (value - new_accumulator) + accumulator;\n    if (std::abs(accumulator) > std::abs(value)) {\n        compensator += first_option;\n    } else {\n        compensator += second_option;\n    }\n    accumulator = new_accumulator;\n}\n\ntemplate<typename tag>\nvoid cum_sum(source_1d<tag> &f)\n{\n    double accumulator = 0.;\n    double compensator = 0.;\n    double value = 0.;\n    while (f.can_procure(1, value) && !f.is_aligned()) {\n        f.procure(value);\n        kahan_update(accumulator, compensator, value);\n        f.feed(accumulator + compensator);\n    }\n    pack_double pack_value1 = boost::simd::Zero<pack_double>();\n    pack_double pack_value2 = boost::simd::Zero<pack_double>();\n    while (f.can_procure(2, pack_value1)) {\n        f.procure(pack_value1);\n        f.procure(pack_value2);\n        pack_double const pack_cum_sum1 = boost::simd::cumsum(pack_value1);\n        pack_double const pack_cum_sum2 = boost::simd::cumsum(pack_value2);\n        pack_double const pack_feed_slice1 = pack_cum_sum1 + (accumulator + compensator);\n        f.feed(pack_feed_slice1);\n        kahan_update(accumulator, compensator, pack_cum_sum1[pack_double::static_size - 1]);\n        pack_double const pack_feed_slice2 = pack_cum_sum2 + (accumulator + compensator);\n        f.feed(pack_feed_slice2);\n        kahan_update(accumulator, compensator, pack_cum_sum2[pack_double::static_size - 1]);\n    }\n    value = 0.;\n    while (f.can_procure(1, accumulator)) {\n        f.procure(value);\n        kahan_update(accumulator, compensator, value);\n        f.feed(accumulator + compensator);\n    }\n}\n", "meta": {"hexsha": "91bc0ee8cb8252e47ef001e4d9c61b2dcaf4b550", "size": 4447, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/simd/headers/summing.hpp", "max_stars_repo_name": "Jolanrensen/viktor", "max_stars_repo_head_hexsha": "f78cba6e8b4393cc8e1b573c2f2d7e4228429898", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 89.0, "max_stars_repo_stars_event_min_datetime": "2015-11-12T21:22:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T05:19:07.000Z", "max_issues_repo_path": "src/simd/headers/summing.hpp", "max_issues_repo_name": "Jolanrensen/viktor", "max_issues_repo_head_hexsha": "f78cba6e8b4393cc8e1b573c2f2d7e4228429898", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 48.0, "max_issues_repo_issues_event_min_datetime": "2015-10-23T08:27:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-15T11:21:57.000Z", "max_forks_repo_path": "src/simd/headers/summing.hpp", "max_forks_repo_name": "Jolanrensen/viktor", "max_forks_repo_head_hexsha": "f78cba6e8b4393cc8e1b573c2f2d7e4228429898", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2017-10-25T14:49:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-21T12:34:04.000Z", "avg_line_length": 31.9928057554, "max_line_length": 92, "alphanum_fraction": 0.6046773105, "num_tokens": 1244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.45184681165824364}}
{"text": "#ifndef BOOST_QVM_DETAIL_DETERMINANT_IMPL_HPP_INCLUDED\n#define BOOST_QVM_DETAIL_DETERMINANT_IMPL_HPP_INCLUDED\n\n// Copyright 2008-2022 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#include <boost/qvm/config.hpp>\n#include <boost/qvm/mat_traits_array.hpp>\n#include <boost/qvm/static_assert.hpp>\n\nnamespace boost { namespace qvm {\n\nnamespace\nqvm_detail\n    {\n    template <int N>\n    struct\n    det_size\n        {\n        };\n\n    template <class M>\n    BOOST_QVM_CONSTEXPR BOOST_QVM_INLINE_TRIVIAL\n    typename mat_traits<M>::scalar_type\n    determinant_impl_( M const & a, det_size<2> )\n        {\n        return\n            mat_traits<M>::template read_element<0,0>(a) * mat_traits<M>::template read_element<1,1>(a) -\n            mat_traits<M>::template read_element<1,0>(a) * mat_traits<M>::template read_element<0,1>(a);\n        }\n\n    template <class M,int N>\n    BOOST_QVM_CONSTEXPR BOOST_QVM_INLINE_RECURSION\n    typename mat_traits<M>::scalar_type\n    determinant_impl_( M const & a, det_size<N> )\n        {\n        typedef typename mat_traits<M>::scalar_type T;\n        T m[N-1][N-1];\n        T det=T(0);\n        for( int j1=0; j1!=N; ++j1 )\n            {\n            for( int i=1; i!=N; ++i )\n                {\n                int j2 = 0;\n                for( int j=0; j!=N; ++j )\n                    {\n                    if( j==j1 )\n                        continue;\n                    m[i-1][j2] = mat_traits<M>::read_element_idx(i,j,a);\n                    ++j2;\n                    }\n                }\n            T d=determinant_impl_(m,det_size<N-1>());\n            if( j1&1 )\n                d=-d;\n            det += mat_traits<M>::read_element_idx(0,j1,a) * d;\n            }\n        return det;\n        }\n\n    template <class M>\n    BOOST_QVM_CONSTEXPR BOOST_QVM_INLINE_TRIVIAL\n    typename mat_traits<M>::scalar_type\n    determinant_impl( M const & a )\n        {\n        BOOST_QVM_STATIC_ASSERT(mat_traits<M>::rows==mat_traits<M>::cols);\n        return determinant_impl_(a,det_size<mat_traits<M>::rows>());\n        }\n    }\n\n} }\n\n#endif\n", "meta": {"hexsha": "0e18f959b3b3faf7eb77e4e8ac66a0142988742d", "size": 2204, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/qvm/detail/determinant_impl.hpp", "max_stars_repo_name": "boostorg/boost-qvm", "max_stars_repo_head_hexsha": "5791440b346232c391ab8d16f559ca5b2d7ae9b3", "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/qvm/detail/determinant_impl.hpp", "max_issues_repo_name": "boostorg/boost-qvm", "max_issues_repo_head_hexsha": "5791440b346232c391ab8d16f559ca5b2d7ae9b3", "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/qvm/detail/determinant_impl.hpp", "max_forks_repo_name": "boostorg/boost-qvm", "max_forks_repo_head_hexsha": "5791440b346232c391ab8d16f559ca5b2d7ae9b3", "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.0, "max_line_length": 105, "alphanum_fraction": 0.5712341198, "num_tokens": 575, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.45184681165824364}}
{"text": "#include \"random.hpp\"\n\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/random_simplify_point_set.h>\n#include <CGAL/property_map.h>\n#include <CGAL/IO/read_xyz_points.h>\n\n#include <vector>\n#include <fstream>\n#include <iostream>\n\n#include <cmath> \n\n#include <boost/tuple/tuple.hpp>\n\n#include \"DtcMainHelper.hpp\"\n\n// Types\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel;\ntypedef Kernel::Point_3 Point;\ntypedef boost::tuple<Point, float, float, float, float> MYPoint;\n\nvoid random(int argc, char*argv[]) {\n/*\nInput:\n    argv[0]: this program\n    argv[1]: \"random\"\n    argv[2]: dir of output data\n    argv[3]: filename of input data under ../tmp/\n    argv[4]: keep ratio in pecentage [0, 100]\n*/\n\n    if (argc != 5) {\n        std::cerr << \"[grid.cpp] require argc: 5, input argc: \" << argc << std::endl;\n        std::cerr << \"Format: program random output_dir input_file keep_ratio\" << std::endl;\n        exit(-1);\n    }\n\n    std::string sampler(argv[1]);\n    std::string dstDir(argv[2]);\n    std::string srcFile(argv[3]);\n    double keep_ratio = atof(argv[4]);\n    \n    std::vector<MYPoint> points;\n    std::string srcFilename = \"../tmp/\" + srcFile;\n\n    // read points \n    // std::cout << \"Reading file: \" << srcFilename << std::endl;\n    std::FILE *pFile = fopen(srcFilename.c_str(), \"rb\");\n    fseek(pFile, 0, SEEK_END);    // file pointer goes to the end of the file\n    long fileSize = ftell(pFile); // file size\n    rewind(pFile);                // rewind file pointer to the beginning\n    float *rawData = new float[fileSize];\n    fread(rawData, sizeof(float), fileSize/sizeof(float), pFile);\n    int nProperties = 7;\n    long number_of_points = fileSize / nProperties / sizeof(float); // x, y, z, r, g, b, label\n\n    for (int i = 0; i < number_of_points; i++) {\n        points.push_back(MYPoint(Point(rawData[nProperties*i], rawData[nProperties*i+1], rawData[nProperties*i+2]), \n            rawData[nProperties*i+3], rawData[nProperties*i+4], rawData[nProperties*i+5], rawData[nProperties*i+6]));\n    }\n\n\n    // processing time\n    uint64_t time_before_sample = DtcMainHelper::getTimestamp();\n\n    points.erase(CGAL::random_simplify_point_set(points.begin(), points.end(), CGAL::Nth_of_tuple_property_map<0, MYPoint>(), 100.0-keep_ratio),\n        points.end());\n\n    DtcMainHelper::dataToFile() << DtcMainHelper::getTimestamp() - time_before_sample << std::endl;\n\n    // log processing time to file time.txt\n    std::string dstFileSave = dstDir + \"/\" + srcFile + \".trim\";\n    // std::cout << dstFileSave << std::endl;\n\n    std::ofstream out(dstFileSave, std::ios_base::binary);\n    for (int i = 0; i < points.size(); i++) {\n            \n        float x = points[i].get<0>().x();\n        float y = points[i].get<0>().y();\n        float z = points[i].get<0>().z();\n        float r = points[i].get<1>();\n        float g = points[i].get<2>();\n        float b = points[i].get<3>();\n        float label = points[i].get<4>();\n        \n        out.write((char *)&x, sizeof(float));\n        out.write((char *)&y, sizeof(float));\n        out.write((char *)&z, sizeof(float));\n        out.write((char *)&r, sizeof(float));\n        out.write((char *)&g, sizeof(float));\n        out.write((char *)&b, sizeof(float));\n        out.write((char *)&label, sizeof(float));\n    }\n    out.close();\n}", "meta": {"hexsha": "160bcbabf35f021c149a486e78ae98495a20f606", "size": 3333, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Cpp/sample_data/src/random.cpp", "max_stars_repo_name": "dtczhl/Slimmer", "max_stars_repo_head_hexsha": "c93dac6a59828016484d8bef1c71e9ccceabab9c", "max_stars_repo_licenses": ["MIT"], "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/sample_data/src/random.cpp", "max_issues_repo_name": "dtczhl/Slimmer", "max_issues_repo_head_hexsha": "c93dac6a59828016484d8bef1c71e9ccceabab9c", "max_issues_repo_licenses": ["MIT"], "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/sample_data/src/random.cpp", "max_forks_repo_name": "dtczhl/Slimmer", "max_forks_repo_head_hexsha": "c93dac6a59828016484d8bef1c71e9ccceabab9c", "max_forks_repo_licenses": ["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.71875, "max_line_length": 144, "alphanum_fraction": 0.6207620762, "num_tokens": 895, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4518468116582436}}
{"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 \"matrix_utils.hpp\"\n\n#include <cmath>\n#include <vector>\n\n#include <boost/dynamic_bitset.hpp>\n#include <boost/format.hpp>\n\n#include <xtensor/xio.hpp>\n#include <xtensor-blas/xlinalg.hpp>\n\n#include <core/utils/bitset_utils.hpp>\n#include <core/utils/terminal.hpp>\n#include <reversible/pauli_tags.hpp>\n#include <reversible/target_tags.hpp>\n#include <reversible/simulation/simple_simulation.hpp>\n\nnamespace cirkit\n{\n\nusing namespace std::complex_literals;\n\n/******************************************************************************\n * Types                                                                      *\n ******************************************************************************/\n\n/******************************************************************************\n * Private functions                                                          *\n ******************************************************************************/\n\nxt::xarray<complex_t> get_2by2_matrix( complex_t a, complex_t b, complex_t c, complex_t d )\n{\n  xt::xarray<complex_t> matrix(std::vector<size_t>{2, 2});\n  matrix[{0,0}] = a;\n  matrix[{0,1}] = b;\n  matrix[{1,0}] = c;\n  matrix[{1,1}] = d;\n  return matrix;\n}\n\nxt::xarray<complex_t> kron( const std::vector<xt::xarray<complex_t>>& ms )\n{\n  assert( !ms.empty() );\n\n  auto r = ms[0u];\n\n  for ( auto i = 1u; i < ms.size(); ++i )\n  {\n    r = xt::linalg::kron( r, ms[i] );\n  }\n\n  return r;\n}\n\nxt::xarray<complex_t> identity( unsigned dimension )\n{\n  xt::xarray<complex_t> matrix(std::vector<size_t>{dimension, dimension});\n  for ( auto i = 0u; i < dimension; ++i )\n  {\n    matrix[{i, i}] = 1.0;\n  }\n  return matrix;\n}\n\nxt::xarray<complex_t> identity_padding( const xt::xarray<complex_t>& matrix, unsigned from, unsigned to, unsigned lines )\n{\n  std::vector<xt::xarray<complex_t>> ms;\n\n  if ( to + 1u < lines )\n  {\n    ms.push_back( identity( 1 << ( lines - to - 1u ) ) );\n  }\n\n  ms.push_back( matrix );\n\n  if ( from > 0u )\n  {\n    ms.push_back( identity( 1 << from ) );\n  }\n\n  return kron( ms );\n}\n\n/******************************************************************************\n * Public functions                                                           *\n ******************************************************************************/\n\nxt::xarray<complex_t> matrix_from_clifford_t_circuit( const circuit& circ, bool progress )\n{\n  xt::xarray<complex_t> matrix_X = get_2by2_matrix( 0.0, 1.0, 1.0, 0.0 );\n  xt::xarray<complex_t> matrix_H = 1.0 / sqrt( 2.0 ) * get_2by2_matrix( 1.0, 1.0, 1.0, -1.0 );\n  xt::xarray<complex_t> matrix_Z = get_2by2_matrix( 1.0, 0.0, 0.0, -1.0 );\n  xt::xarray<complex_t> matrix_S = get_2by2_matrix( 1.0, 0.0, 0.0, 1i );\n  xt::xarray<complex_t> matrix_Sdag = get_2by2_matrix( 1.0, 0.0, 0.0, -1i );\n  xt::xarray<complex_t> matrix_T = get_2by2_matrix( 1.0, 0.0, 0.0, exp( 1i * M_PI / 4.0 ) );\n  xt::xarray<complex_t> matrix_Tdag = get_2by2_matrix( 1.0, 0.0, 0.0, exp( -1i * M_PI / 4.0 ) );\n  xt::xarray<complex_t> matrix_zc = get_2by2_matrix( 1.0, 0.0, 0.0, 0.0 );\n  xt::xarray<complex_t> matrix_oc = get_2by2_matrix( 0.0, 0.0, 0.0, 1.0 );\n\n  const auto n = circ.lines();\n\n  std::vector<xt::xarray<complex_t>> gates;\n\n  for ( const auto& g : circ )\n  {\n    const auto target = g.targets().front();\n\n    if ( is_toffoli( g ) && g.controls().size() == 0u )\n    {\n      gates.push_back( identity_padding( matrix_X, target, target, n ) );\n    }\n    else if ( is_toffoli( g ) && g.controls().size() == 1u && g.controls().front().polarity() )\n    {\n      const auto control = g.controls().front().line();\n\n      if ( control < target )\n      {\n        const auto act = target - control;\n        const auto gate = xt::linalg::kron( identity( 1 << act ), matrix_zc ) + kron( {matrix_X, identity( 1 << ( act - 1 ) ), matrix_oc} );\n        gates.push_back( identity_padding( gate, control, target, n ) );\n      }\n      else\n      {\n        const auto act = control - target;\n        const auto gate = xt::linalg::kron( matrix_zc, identity( 1 << act ) ) + kron( {matrix_oc, identity( 1 << ( act - 1 ) ), matrix_X} );\n        gates.push_back( identity_padding( gate, target, control, n ) );\n      }\n    }\n    else if ( is_hadamard( g ) )\n    {\n      gates.push_back( identity_padding( matrix_H, target, target, n ) );\n    }\n    else if ( is_pauli( g ) )\n    {\n      const auto pauli = boost::any_cast<pauli_tag>( g.type() );\n      switch ( pauli.axis )\n      {\n      case pauli_axis::X:\n        if ( pauli.root == 1u )\n        {\n          gates.push_back( identity_padding( matrix_X, target, target, n ) );\n        }\n        else\n        {\n          std::cout << \"[w] unsupported X gate\" << std::endl;\n        }\n        break;\n      case pauli_axis::Z:\n        if ( pauli.root == 1u )\n        {\n          gates.push_back( identity_padding( matrix_Z, target, target, n ) );\n        }\n        else if ( pauli.root == 2u )\n        {\n          gates.push_back( identity_padding( pauli.adjoint ? matrix_Sdag : matrix_S, target, target, n ) );\n        }\n        else if ( pauli.root == 4u )\n        {\n          gates.push_back( identity_padding( pauli.adjoint ? matrix_Tdag : matrix_T, target, target, n ) );\n        }\n        else\n        {\n          std::cout << \"[w] unsupported Z gate with root \" << pauli.root << std::endl;\n        }\n        break;\n      default:\n        std::cout << \"[w] unsupported Pauli gate\" << std::endl;\n        break;\n      }\n    }\n    else\n    {\n      std::cout << \"[w] unsupported gate\" << std::endl;\n    }\n  }\n\n  if ( gates.empty() )\n  {\n    return identity( 1 << n );\n  }\n  else\n  {\n    progress_line pline( boost::str( boost::format( \"[i] (matrix_from_clifford_t_circuit) gate %%d / %d\" ) % gates.size() ), progress );\n\n    auto r = gates.front();\n    for ( auto i = 1u; i < gates.size(); ++i )\n    {\n      pline( i + 1u );\n      r = xt::linalg::dot( r, gates[i] );\n    }\n\n    return r;\n  }\n}\n\nxt::xarray<complex_t> matrix_from_reversible_circuit( const circuit& circ )\n{\n  const size_t N = 1 << circ.lines();\n\n  xt::xarray<complex_t> matrix(std::vector<size_t>{N, N});\n  foreach_bitset( circ.lines(), [&circ, &matrix]( const boost::dynamic_bitset<>& input ) {\n      boost::dynamic_bitset<> output;\n      simple_simulation( output, circ, input );\n      matrix[{input.to_ulong(), output.to_ulong()}] = 1.0;\n    } );\n\n  return matrix;\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": "a58e0e2eabc6cbe77294d28f618ba20be1747c9c", "size": 7651, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "addons/cirkit-addon-reversible/src/reversible/utils/matrix_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": "addons/cirkit-addon-reversible/src/reversible/utils/matrix_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": "addons/cirkit-addon-reversible/src/reversible/utils/matrix_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": 31.4855967078, "max_line_length": 140, "alphanum_fraction": 0.5621487387, "num_tokens": 2135, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4518468116582436}}
{"text": "/*===========================================================================*\\\n\nAuthor: Matthias W. Smith\nEmail:  mwsmith2@uw.edu\nDate:   11/02/14\n\nDetail: This is a new test program for my Fid libraries \n\n\\*===========================================================================*/\n\n\n//--- std includes ----------------------------------------------------------//\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <cmath>\nusing std::vector;\nusing std::cout;\nusing std::endl;\n\n//--- other includes --------------------------------------------------------//\n#include <armadillo>\n\n//--- project includes ------------------------------------------------------//\n#include \"fid.h\"\nusing namespace fid;\n\n\nint main(int argc, char** argv)\n{\n  // set precision\n  cout.precision(10);\n  cout.setf(std::ios::fixed, std::ios::floatfield);\n\n  // declare variables\n  int fid_length = 5000;\n  double ti = -1.0;\n  double dt = 0.001;\n  double ftruth = 23.0;\n\n  vector<double> wf;\n  vector<double> tm;\n  wf.reserve(fid_length);\n  tm.reserve(fid_length);\n\n  std::ofstream out;\n  out.precision(10);\n\n  for (int i = 0; i < fid_length; i++){\n    tm.push_back(i * dt + ti);\n  }\n\n  FidFactory ff;\n  ff.SetLarmorFreq(ftruth + sim::mixdown_freq);\n  ff.IdealFid(wf, tm);\n\n  for (int i = 0; i < wf.size(); ++i) {\n    wf[i] = sin(40 * tm[i]);\n  }\n\n  out.open(\"wvd_test_wf.txt\");\n  for (auto it = wf.begin(); it != wf.end(); ++it) {\n    out << *it << \", \";\n  }\n  out.close();\n\n  auto wf_im = dsp::hilbert(wf);\n\n  out.open(\"wvd_test_wf_im.txt\");\n  for (auto it = wf_im.begin(); it != wf_im.end(); ++it) {\n    out << *it << \", \";\n  }\n  out.close();\n\n  auto res = dsp::wvd(wf);\n  res.quiet_save(\"wvd_test.txt\", arma::csv_ascii);\n\n  return 0;\n}\n", "meta": {"hexsha": "d97fe6dab4d4105921531a45c7b93160a4d0cdb2", "size": 1730, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "test/src/test_wvd.cxx", "max_stars_repo_name": "mwsmith2/libfid", "max_stars_repo_head_hexsha": "5b68bb27ed18e0412e59527c1d2ca5afb29ceb3a", "max_stars_repo_licenses": ["MIT"], "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/src/test_wvd.cxx", "max_issues_repo_name": "mwsmith2/libfid", "max_issues_repo_head_hexsha": "5b68bb27ed18e0412e59527c1d2ca5afb29ceb3a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-01-16T17:59:38.000Z", "max_issues_repo_issues_event_max_datetime": "2015-08-07T21:34:46.000Z", "max_forks_repo_path": "test/src/test_wvd.cxx", "max_forks_repo_name": "mwsmith2/fid-analysis", "max_forks_repo_head_hexsha": "5b68bb27ed18e0412e59527c1d2ca5afb29ceb3a", "max_forks_repo_licenses": ["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.625, "max_line_length": 79, "alphanum_fraction": 0.4895953757, "num_tokens": 457, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4518468116582436}}
{"text": "\n/*\nassignmentGenerator.cpp - This file is part of the Bayesembler (v1.1.1)\n\n\nThe MIT License (MIT)\n\nCopyright (c) 2014 Lasse Maretty and Jonas Andreas Sibbesen\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*/\n\n\n#include <assignmentGenerator.h>\n#include <boost/random/discrete_distribution.hpp>\n#include <boost/random/binomial_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <boost/random/uniform_01.hpp>\n#include <algorithm>\n\ntypedef boost::random::uniform_int_distribution<> uniform_sampler_t;\ntypedef boost::random::binomial_distribution<> binomial_distribution_t;\ntypedef boost::random::variate_generator<boost::random::mt19937*, boost::random::binomial_distribution<> > binomial_sampler_t;\ntypedef boost::random::uniform_01<boost::random::mt19937*> uniform_01_sampler_t;\n\n\nAssignmentGenerator::AssignmentGenerator(mt_rng_pt_t mt_rng_pt_in, Eigen::MatrixXd * collapsed_map_eigen_in, vector<int> * collapsed_count_vec_in) {\n\n\tmt_rng_pt = mt_rng_pt_in;\n    collapsed_map_eigen = collapsed_map_eigen_in;\n    collapsed_count_vec = collapsed_count_vec_in;\n    num_transcripts = collapsed_map_eigen->cols();\n\n}\n\nvoid AssignmentGenerator::calcMinimumReadCover(stringstream& log_stream) {\n\n    log_stream << \"\\n[\" << getLocalTime() << \"] \" << \"Calculating minimum read cover\" << endl;\n    \n    tr1::unordered_set<int> minimum_set_temp;\n    \n    Eigen::Matrix< int,1,Eigen::Dynamic > logical_vector(collapsed_map_eigen->rows());\n    logical_vector.setOnes();\n    \n    Eigen::Matrix< int,Eigen::Dynamic,Eigen::Dynamic > binary_collapsed_map_eigen((collapsed_map_eigen->array() >= double_underflow).matrix().cast<int>());\n    \n    while (logical_vector.sum() > 0) {\n        \n        Eigen::RowVectorXi covered_reads(logical_vector * binary_collapsed_map_eigen);\n        int max_val = covered_reads.maxCoeff();\n        assert (max_val > 0);\n        \n        vector<int> max_indices;\n        max_indices.reserve(covered_reads.size());\n        \n        for (int i=0; i < covered_reads.size(); i++) {\n            \n            if (max_val == covered_reads[i]) {\n                \n                max_indices.push_back(i);\n                \n            }\n        }\n        \n        uniform_sampler_t set_index_dist(0,max_indices.size()-1);\n        int max_pos = max_indices[set_index_dist(*mt_rng_pt)];\n        \n        minimum_set_temp.insert(max_pos);\n        logical_vector = (logical_vector.array() - logical_vector.array() * binary_collapsed_map_eigen.col(max_pos).transpose().array()).matrix();\n    }\n    \n    minimum_set = minimum_set_temp;\n    \n    log_stream << \"[\" << getLocalTime() << \"] \" << \"Number of candidates in minimum read cover: \" << minimum_set.size() << \"\\n\" << endl;\n}\n\nint AssignmentGenerator::getMinimumReadCoverSize() {\n    \n    return minimum_set.size();\n}\n\nCountValueContainer AssignmentGenerator::initAssignmentMinimum(stringstream& log_stream) {\n\n    log_stream << \"[\" << getLocalTime() << \"] \" << \"Initialising read assignments using minimum set cover\" << endl;\n        \n    CountValueContainer map_counts(num_transcripts);\n        \n    for (int i=0; i < collapsed_count_vec->size(); i++) {\n        \n        vector<int> minimum_set_vec;\n        double norm_const = 0;\n\t\t\n\t\tfor (int j=0; j < collapsed_map_eigen->cols(); j++) {\n            \n\t\t\tif ((minimum_set.count(j) == 1) and ((*collapsed_map_eigen)(i,j) >= double_underflow)) {\n                \n\t\t\t\tminimum_set_vec.push_back(j);\n                norm_const += (*collapsed_map_eigen)(i,j);\n                \n\t\t\t}\n\t\t}\n\n        assert(norm_const >= double_underflow);\n        int num_samples = collapsed_count_vec->at(i);\n        double divider = 1;\n        \n        for (int j = 0; j < minimum_set_vec.size(); j++) {\n            \n            double norm_probability = (*collapsed_map_eigen)(i,minimum_set_vec[j])/norm_const;\n            \n            if (norm_probability >= double_underflow) {\n                \n                binomial_distribution_t binom_dist(num_samples, norm_probability/divider);\n                binomial_sampler_t binom_sampler(mt_rng_pt, binom_dist);\n                \n                int num_maps = binom_sampler();\n                map_counts.addToCount(num_maps,minimum_set_vec[j]);\n                \n                if (num_maps > 0) {\n                    \n                    map_counts.addToPlus(minimum_set_vec[j]);\n                    \n                }\n                \n                num_samples -= num_maps;                \n            }\n            \n            divider -= norm_probability;\n        }\n        \n        assert (num_samples == 0);      \n\t}\n    \n\tmap_counts.fetchNullSet();\n    vector <int> counts_out = map_counts.getCounts();\n\t// cout << \"Initialised assignment with counts:\\n\" << counts_out << endl;\n\t\n\treturn map_counts;\n    \n}\n\nCountValueContainer AssignmentGenerator::initEnsembleAssignment(vector<int> indices) {\n        \n    CountValueContainer map_counts(num_transcripts);\n                \n    for (int i=0; i < collapsed_count_vec->size(); i++) {\n                \n        double norm_const = 0;\n        \n\t\tfor (int j=0; j < indices.size(); j++) {\n            \n            norm_const += (*collapsed_map_eigen)(i,indices[j]);\n    \t}\n        \n        assert(norm_const >= double_underflow);\n        int num_samples = collapsed_count_vec->at(i);\n        double divider = 1;\n        \n        for (int j = 0; j < indices.size(); j++) {\n            \n            int current_idx = indices[j];\n            double norm_probability = (*collapsed_map_eigen)(i, current_idx)/norm_const;\n            \n            if (norm_probability >= double_underflow) {\n                \n                binomial_distribution_t binom_dist(num_samples, norm_probability/divider);\n                binomial_sampler_t binom_sampler(mt_rng_pt, binom_dist);\n                \n                int num_maps = binom_sampler();\n                map_counts.addToCount(num_maps, current_idx);\n                \n                if (num_maps > 0) {\n                    \n                    map_counts.addToPlus(current_idx);\n                    \n                }\n                \n                num_samples -= num_maps;\n                \n            }\n            \n            divider -= norm_probability;\n            \n        }\n        \n        assert (num_samples == 0);    \n\t}\n    \n\tmap_counts.fetchNullSet();\n    vector <int> counts_out = map_counts.getCounts();\n\t// cout << \"Initialised assignment with counts:\\n\" << counts_out << endl;\n\t\n\treturn map_counts;\n    \n}\n\nCountValueContainer AssignmentGenerator::initAssignment(stringstream& log_stream) {\n\n    log_stream << \"[\" << getLocalTime() << \"] \" << \"Initialising read assignments uniformly\" << endl;\n        \n    CountValueContainer map_counts(num_transcripts);\n        \n    for (int i=0; i < collapsed_count_vec->size(); i++) {\n        \n        int num_samples = collapsed_count_vec->at(i);\n        double divider = 1;\n        \n        for (int j = 0; j < num_transcripts; j++) {\n            \n            double norm_probability = (*collapsed_map_eigen)(i,j);\n            \n            if (norm_probability >= double_underflow) {\n                \n                binomial_distribution_t binom_dist(num_samples, norm_probability/divider);\n                binomial_sampler_t binom_sampler(mt_rng_pt, binom_dist);\n                \n                int num_maps = binom_sampler();\n                map_counts.addToCount(num_maps,j);\n                \n                if (num_maps > 0) {\n                    \n                    map_counts.addToPlus(j);\n                    \n                }\n                \n                num_samples -= num_maps;\n                \n            }\n            \n            divider -= norm_probability;\n            \n        }\n        \n        assert (num_samples == 0);\n        \n\t}\n    \n\tmap_counts.fetchNullSet();\n    vector <int> counts_out = map_counts.getCounts();\n\t// cout << \"Initialised assignment with counts:\\n\" << counts_out << endl;\n\t\n\treturn map_counts;\n    \n}\n\n\nCountValueContainer AssignmentGenerator::generateAssignment(ExpressionValueContainer expression) {\n\t\n    // Reset assignment map\n\tCountValueContainer map_counts(num_transcripts);\n    \n    // Create expression vector and calculate normalisation constants\n\tEigen::RowVectorXd expression_values(num_transcripts);\n\t\n\tfor (int i=0; i < num_transcripts; i++) {\n\t    \n\t\texpression_values(i) = expression.getValue(i);\n\t}\n      \n    uniform_01_sampler_t sample_uniform_01(mt_rng_pt);\n    \n    for (int i=0; i < collapsed_count_vec->size(); i++) {\n        \n        Eigen::RowVectorXd probabilities_unnormalised = collapsed_map_eigen->row(i).array() * expression_values.array();\n                \n        double normalisation_constant = probabilities_unnormalised.sum();\n        \n        assert (normalisation_constant >= double_underflow);\n        assert (probabilities_unnormalised.size() == num_transcripts);\n        \n        int num_samples = collapsed_count_vec->at(i);\n        \n        if (num_samples < 20) {\n        \n            vector <double> uniform_samples(num_samples);\n            \n            for (int j = 0; j < num_samples; j++) {\n                \n                uniform_samples[j] = sample_uniform_01();            \n            }\n            \n            sort (uniform_samples.begin(), uniform_samples.end());\n            double cum_sum = 0;\n            int index_num = 0;\n            \n            for (int j = 0; j < num_transcripts; j++) {\n            \n                cum_sum += probabilities_unnormalised[j]/normalisation_constant;\n                \n                if (uniform_samples[index_num] < cum_sum) {\n                    \n                    int samp_counter = 1;\n                    index_num +=1;\n                                        \n                    while (index_num < uniform_samples.size()) {\n                        \n                        if (uniform_samples[index_num] >= cum_sum) {\n                        \n                            break;   \n                        }\n                                                \n                        samp_counter += 1;\n                        index_num +=1;\n                        \n                    }\n                    \n                    map_counts.addToCount(samp_counter, j);\n                    map_counts.addToPlus(j);\n                    \n                }\n                \n                if (index_num == uniform_samples.size()) {\n                    \n                    break;\n                    \n                }\n              \n            }\n                    \n        } else {\n        \n            double divider = 1;\n        \n            for (int j = 0; j < num_transcripts; j++) {\n                \n                double norm_probability = probabilities_unnormalised[j]/normalisation_constant;\n                \n                if (norm_probability >= double_underflow) {\n                \n                    binomial_distribution_t binom_dist(num_samples, norm_probability/divider);\n                    binomial_sampler_t binom_sampler(mt_rng_pt, binom_dist);\n                    \n                    int num_maps = binom_sampler();\n                    \n                    if (num_maps > 0) {\n\n                        map_counts.addToCount(num_maps, j);                    \n                        map_counts.addToPlus(j);\n                    }\n                    \n                    num_samples -= num_maps;\n                }\n                \n                divider -= norm_probability;            \n            }\n            \n            assert (num_samples == 0);\n        \n        }\n        \n\t}\n\n\tmap_counts.fetchNullSet();\n\n\treturn map_counts;\n\n}\n\n\n\n", "meta": {"hexsha": "a4a99899bb41d1a053e483ad500060fd733589b8", "size": 12603, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/assignmentGenerator.cpp", "max_stars_repo_name": "bhurwitz33/bayesembler", "max_stars_repo_head_hexsha": "b1d8200d5ffa2ae3476391d9f35f26e5f14f517f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-10T15:43:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-10T15:43:12.000Z", "max_issues_repo_path": "src/assignmentGenerator.cpp", "max_issues_repo_name": "bhurwitz33/bayesembler", "max_issues_repo_head_hexsha": "b1d8200d5ffa2ae3476391d9f35f26e5f14f517f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/assignmentGenerator.cpp", "max_forks_repo_name": "bhurwitz33/bayesembler", "max_forks_repo_head_hexsha": "b1d8200d5ffa2ae3476391d9f35f26e5f14f517f", "max_forks_repo_licenses": ["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.4297082228, "max_line_length": 155, "alphanum_fraction": 0.5556613505, "num_tokens": 2498, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568417, "lm_q2_score": 0.5813030906443134, "lm_q1q2_score": 0.45184680566044594}}
{"text": "//\n// boost/radix/bitmask.hpp\n//\n// Copyright (c) Chris Glover, 2017-2018\n//\n// Distributed under the Boost Software License, Version 1.0. (See accompanying\n// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n//\n\n#ifndef BOOST_RADIX_BITMASK_HPP\n#define BOOST_RADIX_BITMASK_HPP\n\n#include <boost/radix/common.hpp>\n\n#include <boost/integer/integer_mask.hpp>\n#include <boost/radix/common.hpp>\n\nnamespace boost { namespace radix {\n\ntemplate <std::size_t Bits>\nstruct mask {\n  BOOST_STATIC_CONSTANT(\n      typename low_bits_mask_t<Bits>::fast,\n      value = ~(~low_bits_mask_t<Bits>::sig_bits_fast));\n};\n\ntemplate <std::size_t Bits, std::size_t Shift>\nstruct mask_shift {\n  BOOST_STATIC_CONSTANT(\n      typename low_bits_mask_t<Bits>::fast,\n      value = ~(~low_bits_mask_t<Bits>::sig_bits_fast) << Shift);\n};\n\n}} // namespace boost::radix\n\n#endif // BOOST_RADIX_BITMASK_HPP\n", "meta": {"hexsha": "d03b1116a876f550ef9d8771001265d8c329b8a7", "size": 890, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/radix/bitmask.hpp", "max_stars_repo_name": "cdglove/boost.radix", "max_stars_repo_head_hexsha": "39626a1a76eb33ce9bd43b3957f1a39678943a30", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-01-11T20:27:16.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-11T20:27:16.000Z", "max_issues_repo_path": "include/boost/radix/bitmask.hpp", "max_issues_repo_name": "cdglove/boost.radix", "max_issues_repo_head_hexsha": "39626a1a76eb33ce9bd43b3957f1a39678943a30", "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/radix/bitmask.hpp", "max_forks_repo_name": "cdglove/boost.radix", "max_forks_repo_head_hexsha": "39626a1a76eb33ce9bd43b3957f1a39678943a30", "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.0540540541, "max_line_length": 79, "alphanum_fraction": 0.7314606742, "num_tokens": 234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568416, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4518468056604458}}
{"text": "#include \"forward_dynamics.h\"\n\n#include <Eigen/Cholesky>\n#include <iit/rbd/robcogen_commons.h>\n\nusing namespace iit::rbd;\n\n// Initialization of static-const data\nconst iit::popi::dyn::ForwardDynamics::ExtForces\n    iit::popi::dyn::ForwardDynamics::zeroExtForces(Force::Zero());\n\niit::popi::dyn::ForwardDynamics::ForwardDynamics(InertiaProperties& inertia, MotionTransforms& transforms) :\n    inertiaProps( & inertia ),\n    motionTransforms( & transforms )\n{\n    EpauleAVD_v.setZero();\n    EpauleAVD_c.setZero();\n    HJambeAVD_v.setZero();\n    HJambeAVD_c.setZero();\n    BJambeAVD_v.setZero();\n    BJambeAVD_c.setZero();\n    EpauleAVG_v.setZero();\n    EpauleAVG_c.setZero();\n    HJambeAVG_v.setZero();\n    HJambeAVG_c.setZero();\n    BJambeAVG_v.setZero();\n    BJambeAVG_c.setZero();\n    EpauleARD_v.setZero();\n    EpauleARD_c.setZero();\n    HJambeARD_v.setZero();\n    HJambeARD_c.setZero();\n    BJambeARD_v.setZero();\n    BJambeARD_c.setZero();\n    EpauleARG_v.setZero();\n    EpauleARG_c.setZero();\n    HJambeARG_v.setZero();\n    HJambeARG_c.setZero();\n    BJambeARG_v.setZero();\n    BJambeARG_c.setZero();\n\n    vcross.setZero();\n    Ia_r.setZero();\n\n}\n\nvoid iit::popi::dyn::ForwardDynamics::fd(\n    JointState& qdd,\n    Acceleration& base_a,\n    const Velocity& base_v,\n    const Acceleration& g,\n    const JointState& qd,\n    const JointState& tau,\n    const ExtForces& fext/* = zeroExtForces */)\n{\n    \n    base_AI = inertiaProps->getTensor_base();\n    base_p = - fext[BASE];\n    EpauleAVD_AI = inertiaProps->getTensor_EpauleAVD();\n    EpauleAVD_p = - fext[EPAULEAVD];\n    HJambeAVD_AI = inertiaProps->getTensor_HJambeAVD();\n    HJambeAVD_p = - fext[HJAMBEAVD];\n    BJambeAVD_AI = inertiaProps->getTensor_BJambeAVD();\n    BJambeAVD_p = - fext[BJAMBEAVD];\n    EpauleAVG_AI = inertiaProps->getTensor_EpauleAVG();\n    EpauleAVG_p = - fext[EPAULEAVG];\n    HJambeAVG_AI = inertiaProps->getTensor_HJambeAVG();\n    HJambeAVG_p = - fext[HJAMBEAVG];\n    BJambeAVG_AI = inertiaProps->getTensor_BJambeAVG();\n    BJambeAVG_p = - fext[BJAMBEAVG];\n    EpauleARD_AI = inertiaProps->getTensor_EpauleARD();\n    EpauleARD_p = - fext[EPAULEARD];\n    HJambeARD_AI = inertiaProps->getTensor_HJambeARD();\n    HJambeARD_p = - fext[HJAMBEARD];\n    BJambeARD_AI = inertiaProps->getTensor_BJambeARD();\n    BJambeARD_p = - fext[BJAMBEARD];\n    EpauleARG_AI = inertiaProps->getTensor_EpauleARG();\n    EpauleARG_p = - fext[EPAULEARG];\n    HJambeARG_AI = inertiaProps->getTensor_HJambeARG();\n    HJambeARG_p = - fext[HJAMBEARG];\n    BJambeARG_AI = inertiaProps->getTensor_BJambeARG();\n    BJambeARG_p = - fext[BJAMBEARG];\n    // ---------------------- FIRST PASS ---------------------- //\n    // Note that, during the first pass, the articulated inertias are really\n    //  just the spatial inertia of the links (see assignments above).\n    //  Afterwards things change, and articulated inertias shall not be used\n    //  in functions which work specifically with spatial inertias.\n    \n    // + Link EpauleAVD\n    //  - The spatial velocity:\n    EpauleAVD_v = (motionTransforms-> fr_EpauleAVD_X_fr_base) * base_v;\n    EpauleAVD_v(AZ) += qd(RF_HAA_JOINT);\n    \n    //  - The velocity-product acceleration term:\n    motionCrossProductMx<Scalar>(EpauleAVD_v, vcross);\n    EpauleAVD_c = vcross.col(AZ) * qd(RF_HAA_JOINT);\n    \n    //  - The bias force term:\n    EpauleAVD_p += vxIv(EpauleAVD_v, EpauleAVD_AI);\n    \n    // + Link HJambeAVD\n    //  - The spatial velocity:\n    HJambeAVD_v = (motionTransforms-> fr_HJambeAVD_X_fr_EpauleAVD) * EpauleAVD_v;\n    HJambeAVD_v(AZ) += qd(RF_HFE_JOINT);\n    \n    //  - The velocity-product acceleration term:\n    motionCrossProductMx<Scalar>(HJambeAVD_v, vcross);\n    HJambeAVD_c = vcross.col(AZ) * qd(RF_HFE_JOINT);\n    \n    //  - The bias force term:\n    HJambeAVD_p += vxIv(HJambeAVD_v, HJambeAVD_AI);\n    \n    // + Link BJambeAVD\n    //  - The spatial velocity:\n    BJambeAVD_v = (motionTransforms-> fr_BJambeAVD_X_fr_HJambeAVD) * HJambeAVD_v;\n    BJambeAVD_v(AZ) += qd(RF_KFE_JOINT);\n    \n    //  - The velocity-product acceleration term:\n    motionCrossProductMx<Scalar>(BJambeAVD_v, vcross);\n    BJambeAVD_c = vcross.col(AZ) * qd(RF_KFE_JOINT);\n    \n    //  - The bias force term:\n    BJambeAVD_p += vxIv(BJambeAVD_v, BJambeAVD_AI);\n    \n    // + Link EpauleAVG\n    //  - The spatial velocity:\n    EpauleAVG_v = (motionTransforms-> fr_EpauleAVG_X_fr_base) * base_v;\n    EpauleAVG_v(AZ) += qd(LF_HAA_JOINT);\n    \n    //  - The velocity-product acceleration term:\n    motionCrossProductMx<Scalar>(EpauleAVG_v, vcross);\n    EpauleAVG_c = vcross.col(AZ) * qd(LF_HAA_JOINT);\n    \n    //  - The bias force term:\n    EpauleAVG_p += vxIv(EpauleAVG_v, EpauleAVG_AI);\n    \n    // + Link HJambeAVG\n    //  - The spatial velocity:\n    HJambeAVG_v = (motionTransforms-> fr_HJambeAVG_X_fr_EpauleAVG) * EpauleAVG_v;\n    HJambeAVG_v(AZ) += qd(LF_HFE_JOINT);\n    \n    //  - The velocity-product acceleration term:\n    motionCrossProductMx<Scalar>(HJambeAVG_v, vcross);\n    HJambeAVG_c = vcross.col(AZ) * qd(LF_HFE_JOINT);\n    \n    //  - The bias force term:\n    HJambeAVG_p += vxIv(HJambeAVG_v, HJambeAVG_AI);\n    \n    // + Link BJambeAVG\n    //  - The spatial velocity:\n    BJambeAVG_v = (motionTransforms-> fr_BJambeAVG_X_fr_HJambeAVG) * HJambeAVG_v;\n    BJambeAVG_v(AZ) += qd(LF_KFE_JOINT);\n    \n    //  - The velocity-product acceleration term:\n    motionCrossProductMx<Scalar>(BJambeAVG_v, vcross);\n    BJambeAVG_c = vcross.col(AZ) * qd(LF_KFE_JOINT);\n    \n    //  - The bias force term:\n    BJambeAVG_p += vxIv(BJambeAVG_v, BJambeAVG_AI);\n    \n    // + Link EpauleARD\n    //  - The spatial velocity:\n    EpauleARD_v = (motionTransforms-> fr_EpauleARD_X_fr_base) * base_v;\n    EpauleARD_v(AZ) += qd(RH_HAA_JOINT);\n    \n    //  - The velocity-product acceleration term:\n    motionCrossProductMx<Scalar>(EpauleARD_v, vcross);\n    EpauleARD_c = vcross.col(AZ) * qd(RH_HAA_JOINT);\n    \n    //  - The bias force term:\n    EpauleARD_p += vxIv(EpauleARD_v, EpauleARD_AI);\n    \n    // + Link HJambeARD\n    //  - The spatial velocity:\n    HJambeARD_v = (motionTransforms-> fr_HJambeARD_X_fr_EpauleARD) * EpauleARD_v;\n    HJambeARD_v(AZ) += qd(RH_HFE_JOINT);\n    \n    //  - The velocity-product acceleration term:\n    motionCrossProductMx<Scalar>(HJambeARD_v, vcross);\n    HJambeARD_c = vcross.col(AZ) * qd(RH_HFE_JOINT);\n    \n    //  - The bias force term:\n    HJambeARD_p += vxIv(HJambeARD_v, HJambeARD_AI);\n    \n    // + Link BJambeARD\n    //  - The spatial velocity:\n    BJambeARD_v = (motionTransforms-> fr_BJambeARD_X_fr_HJambeARD) * HJambeARD_v;\n    BJambeARD_v(AZ) += qd(RH_KFE_JOINT);\n    \n    //  - The velocity-product acceleration term:\n    motionCrossProductMx<Scalar>(BJambeARD_v, vcross);\n    BJambeARD_c = vcross.col(AZ) * qd(RH_KFE_JOINT);\n    \n    //  - The bias force term:\n    BJambeARD_p += vxIv(BJambeARD_v, BJambeARD_AI);\n    \n    // + Link EpauleARG\n    //  - The spatial velocity:\n    EpauleARG_v = (motionTransforms-> fr_EpauleARG_X_fr_base) * base_v;\n    EpauleARG_v(AZ) += qd(LH_HAA_JOINT);\n    \n    //  - The velocity-product acceleration term:\n    motionCrossProductMx<Scalar>(EpauleARG_v, vcross);\n    EpauleARG_c = vcross.col(AZ) * qd(LH_HAA_JOINT);\n    \n    //  - The bias force term:\n    EpauleARG_p += vxIv(EpauleARG_v, EpauleARG_AI);\n    \n    // + Link HJambeARG\n    //  - The spatial velocity:\n    HJambeARG_v = (motionTransforms-> fr_HJambeARG_X_fr_EpauleARG) * EpauleARG_v;\n    HJambeARG_v(AZ) += qd(LH_HFE_JOINT);\n    \n    //  - The velocity-product acceleration term:\n    motionCrossProductMx<Scalar>(HJambeARG_v, vcross);\n    HJambeARG_c = vcross.col(AZ) * qd(LH_HFE_JOINT);\n    \n    //  - The bias force term:\n    HJambeARG_p += vxIv(HJambeARG_v, HJambeARG_AI);\n    \n    // + Link BJambeARG\n    //  - The spatial velocity:\n    BJambeARG_v = (motionTransforms-> fr_BJambeARG_X_fr_HJambeARG) * HJambeARG_v;\n    BJambeARG_v(AZ) += qd(LH_KFE_JOINT);\n    \n    //  - The velocity-product acceleration term:\n    motionCrossProductMx<Scalar>(BJambeARG_v, vcross);\n    BJambeARG_c = vcross.col(AZ) * qd(LH_KFE_JOINT);\n    \n    //  - The bias force term:\n    BJambeARG_p += vxIv(BJambeARG_v, BJambeARG_AI);\n    \n    // + The floating base body\n    base_p += vxIv(base_v, base_AI);\n    \n    // ---------------------- SECOND PASS ---------------------- //\n    Matrix66 IaB;\n    Force pa;\n    \n    // + Link BJambeARG\n    BJambeARG_u = tau(LH_KFE_JOINT) - BJambeARG_p(AZ);\n    BJambeARG_U = BJambeARG_AI.col(AZ);\n    BJambeARG_D = BJambeARG_U(AZ);\n    \n    compute_Ia_revolute(BJambeARG_AI, BJambeARG_U, BJambeARG_D, Ia_r);  // same as: Ia_r = BJambeARG_AI - BJambeARG_U/BJambeARG_D * BJambeARG_U.transpose();\n    pa = BJambeARG_p + Ia_r * BJambeARG_c + BJambeARG_U * BJambeARG_u/BJambeARG_D;\n    ctransform_Ia_revolute(Ia_r, motionTransforms-> fr_BJambeARG_X_fr_HJambeARG, IaB);\n    HJambeARG_AI += IaB;\n    HJambeARG_p += (motionTransforms-> fr_BJambeARG_X_fr_HJambeARG).transpose() * pa;\n    \n    // + Link HJambeARG\n    HJambeARG_u = tau(LH_HFE_JOINT) - HJambeARG_p(AZ);\n    HJambeARG_U = HJambeARG_AI.col(AZ);\n    HJambeARG_D = HJambeARG_U(AZ);\n    \n    compute_Ia_revolute(HJambeARG_AI, HJambeARG_U, HJambeARG_D, Ia_r);  // same as: Ia_r = HJambeARG_AI - HJambeARG_U/HJambeARG_D * HJambeARG_U.transpose();\n    pa = HJambeARG_p + Ia_r * HJambeARG_c + HJambeARG_U * HJambeARG_u/HJambeARG_D;\n    ctransform_Ia_revolute(Ia_r, motionTransforms-> fr_HJambeARG_X_fr_EpauleARG, IaB);\n    EpauleARG_AI += IaB;\n    EpauleARG_p += (motionTransforms-> fr_HJambeARG_X_fr_EpauleARG).transpose() * pa;\n    \n    // + Link EpauleARG\n    EpauleARG_u = tau(LH_HAA_JOINT) - EpauleARG_p(AZ);\n    EpauleARG_U = EpauleARG_AI.col(AZ);\n    EpauleARG_D = EpauleARG_U(AZ);\n    \n    compute_Ia_revolute(EpauleARG_AI, EpauleARG_U, EpauleARG_D, Ia_r);  // same as: Ia_r = EpauleARG_AI - EpauleARG_U/EpauleARG_D * EpauleARG_U.transpose();\n    pa = EpauleARG_p + Ia_r * EpauleARG_c + EpauleARG_U * EpauleARG_u/EpauleARG_D;\n    ctransform_Ia_revolute(Ia_r, motionTransforms-> fr_EpauleARG_X_fr_base, IaB);\n    base_AI += IaB;\n    base_p += (motionTransforms-> fr_EpauleARG_X_fr_base).transpose() * pa;\n    \n    // + Link BJambeARD\n    BJambeARD_u = tau(RH_KFE_JOINT) - BJambeARD_p(AZ);\n    BJambeARD_U = BJambeARD_AI.col(AZ);\n    BJambeARD_D = BJambeARD_U(AZ);\n    \n    compute_Ia_revolute(BJambeARD_AI, BJambeARD_U, BJambeARD_D, Ia_r);  // same as: Ia_r = BJambeARD_AI - BJambeARD_U/BJambeARD_D * BJambeARD_U.transpose();\n    pa = BJambeARD_p + Ia_r * BJambeARD_c + BJambeARD_U * BJambeARD_u/BJambeARD_D;\n    ctransform_Ia_revolute(Ia_r, motionTransforms-> fr_BJambeARD_X_fr_HJambeARD, IaB);\n    HJambeARD_AI += IaB;\n    HJambeARD_p += (motionTransforms-> fr_BJambeARD_X_fr_HJambeARD).transpose() * pa;\n    \n    // + Link HJambeARD\n    HJambeARD_u = tau(RH_HFE_JOINT) - HJambeARD_p(AZ);\n    HJambeARD_U = HJambeARD_AI.col(AZ);\n    HJambeARD_D = HJambeARD_U(AZ);\n    \n    compute_Ia_revolute(HJambeARD_AI, HJambeARD_U, HJambeARD_D, Ia_r);  // same as: Ia_r = HJambeARD_AI - HJambeARD_U/HJambeARD_D * HJambeARD_U.transpose();\n    pa = HJambeARD_p + Ia_r * HJambeARD_c + HJambeARD_U * HJambeARD_u/HJambeARD_D;\n    ctransform_Ia_revolute(Ia_r, motionTransforms-> fr_HJambeARD_X_fr_EpauleARD, IaB);\n    EpauleARD_AI += IaB;\n    EpauleARD_p += (motionTransforms-> fr_HJambeARD_X_fr_EpauleARD).transpose() * pa;\n    \n    // + Link EpauleARD\n    EpauleARD_u = tau(RH_HAA_JOINT) - EpauleARD_p(AZ);\n    EpauleARD_U = EpauleARD_AI.col(AZ);\n    EpauleARD_D = EpauleARD_U(AZ);\n    \n    compute_Ia_revolute(EpauleARD_AI, EpauleARD_U, EpauleARD_D, Ia_r);  // same as: Ia_r = EpauleARD_AI - EpauleARD_U/EpauleARD_D * EpauleARD_U.transpose();\n    pa = EpauleARD_p + Ia_r * EpauleARD_c + EpauleARD_U * EpauleARD_u/EpauleARD_D;\n    ctransform_Ia_revolute(Ia_r, motionTransforms-> fr_EpauleARD_X_fr_base, IaB);\n    base_AI += IaB;\n    base_p += (motionTransforms-> fr_EpauleARD_X_fr_base).transpose() * pa;\n    \n    // + Link BJambeAVG\n    BJambeAVG_u = tau(LF_KFE_JOINT) - BJambeAVG_p(AZ);\n    BJambeAVG_U = BJambeAVG_AI.col(AZ);\n    BJambeAVG_D = BJambeAVG_U(AZ);\n    \n    compute_Ia_revolute(BJambeAVG_AI, BJambeAVG_U, BJambeAVG_D, Ia_r);  // same as: Ia_r = BJambeAVG_AI - BJambeAVG_U/BJambeAVG_D * BJambeAVG_U.transpose();\n    pa = BJambeAVG_p + Ia_r * BJambeAVG_c + BJambeAVG_U * BJambeAVG_u/BJambeAVG_D;\n    ctransform_Ia_revolute(Ia_r, motionTransforms-> fr_BJambeAVG_X_fr_HJambeAVG, IaB);\n    HJambeAVG_AI += IaB;\n    HJambeAVG_p += (motionTransforms-> fr_BJambeAVG_X_fr_HJambeAVG).transpose() * pa;\n    \n    // + Link HJambeAVG\n    HJambeAVG_u = tau(LF_HFE_JOINT) - HJambeAVG_p(AZ);\n    HJambeAVG_U = HJambeAVG_AI.col(AZ);\n    HJambeAVG_D = HJambeAVG_U(AZ);\n    \n    compute_Ia_revolute(HJambeAVG_AI, HJambeAVG_U, HJambeAVG_D, Ia_r);  // same as: Ia_r = HJambeAVG_AI - HJambeAVG_U/HJambeAVG_D * HJambeAVG_U.transpose();\n    pa = HJambeAVG_p + Ia_r * HJambeAVG_c + HJambeAVG_U * HJambeAVG_u/HJambeAVG_D;\n    ctransform_Ia_revolute(Ia_r, motionTransforms-> fr_HJambeAVG_X_fr_EpauleAVG, IaB);\n    EpauleAVG_AI += IaB;\n    EpauleAVG_p += (motionTransforms-> fr_HJambeAVG_X_fr_EpauleAVG).transpose() * pa;\n    \n    // + Link EpauleAVG\n    EpauleAVG_u = tau(LF_HAA_JOINT) - EpauleAVG_p(AZ);\n    EpauleAVG_U = EpauleAVG_AI.col(AZ);\n    EpauleAVG_D = EpauleAVG_U(AZ);\n    \n    compute_Ia_revolute(EpauleAVG_AI, EpauleAVG_U, EpauleAVG_D, Ia_r);  // same as: Ia_r = EpauleAVG_AI - EpauleAVG_U/EpauleAVG_D * EpauleAVG_U.transpose();\n    pa = EpauleAVG_p + Ia_r * EpauleAVG_c + EpauleAVG_U * EpauleAVG_u/EpauleAVG_D;\n    ctransform_Ia_revolute(Ia_r, motionTransforms-> fr_EpauleAVG_X_fr_base, IaB);\n    base_AI += IaB;\n    base_p += (motionTransforms-> fr_EpauleAVG_X_fr_base).transpose() * pa;\n    \n    // + Link BJambeAVD\n    BJambeAVD_u = tau(RF_KFE_JOINT) - BJambeAVD_p(AZ);\n    BJambeAVD_U = BJambeAVD_AI.col(AZ);\n    BJambeAVD_D = BJambeAVD_U(AZ);\n    \n    compute_Ia_revolute(BJambeAVD_AI, BJambeAVD_U, BJambeAVD_D, Ia_r);  // same as: Ia_r = BJambeAVD_AI - BJambeAVD_U/BJambeAVD_D * BJambeAVD_U.transpose();\n    pa = BJambeAVD_p + Ia_r * BJambeAVD_c + BJambeAVD_U * BJambeAVD_u/BJambeAVD_D;\n    ctransform_Ia_revolute(Ia_r, motionTransforms-> fr_BJambeAVD_X_fr_HJambeAVD, IaB);\n    HJambeAVD_AI += IaB;\n    HJambeAVD_p += (motionTransforms-> fr_BJambeAVD_X_fr_HJambeAVD).transpose() * pa;\n    \n    // + Link HJambeAVD\n    HJambeAVD_u = tau(RF_HFE_JOINT) - HJambeAVD_p(AZ);\n    HJambeAVD_U = HJambeAVD_AI.col(AZ);\n    HJambeAVD_D = HJambeAVD_U(AZ);\n    \n    compute_Ia_revolute(HJambeAVD_AI, HJambeAVD_U, HJambeAVD_D, Ia_r);  // same as: Ia_r = HJambeAVD_AI - HJambeAVD_U/HJambeAVD_D * HJambeAVD_U.transpose();\n    pa = HJambeAVD_p + Ia_r * HJambeAVD_c + HJambeAVD_U * HJambeAVD_u/HJambeAVD_D;\n    ctransform_Ia_revolute(Ia_r, motionTransforms-> fr_HJambeAVD_X_fr_EpauleAVD, IaB);\n    EpauleAVD_AI += IaB;\n    EpauleAVD_p += (motionTransforms-> fr_HJambeAVD_X_fr_EpauleAVD).transpose() * pa;\n    \n    // + Link EpauleAVD\n    EpauleAVD_u = tau(RF_HAA_JOINT) - EpauleAVD_p(AZ);\n    EpauleAVD_U = EpauleAVD_AI.col(AZ);\n    EpauleAVD_D = EpauleAVD_U(AZ);\n    \n    compute_Ia_revolute(EpauleAVD_AI, EpauleAVD_U, EpauleAVD_D, Ia_r);  // same as: Ia_r = EpauleAVD_AI - EpauleAVD_U/EpauleAVD_D * EpauleAVD_U.transpose();\n    pa = EpauleAVD_p + Ia_r * EpauleAVD_c + EpauleAVD_U * EpauleAVD_u/EpauleAVD_D;\n    ctransform_Ia_revolute(Ia_r, motionTransforms-> fr_EpauleAVD_X_fr_base, IaB);\n    base_AI += IaB;\n    base_p += (motionTransforms-> fr_EpauleAVD_X_fr_base).transpose() * pa;\n    \n    // + The acceleration of the floating base base, without gravity\n    Eigen::LLT<Matrix66d> llt(base_AI);\n    base_a = - llt.solve(base_p);  // base_a = - IA^-1 * base_p\n    \n    // ---------------------- THIRD PASS ---------------------- //\n    EpauleAVD_a = (motionTransforms-> fr_EpauleAVD_X_fr_base) * base_a + EpauleAVD_c;\n    qdd(RF_HAA_JOINT) = (EpauleAVD_u - EpauleAVD_U.dot(EpauleAVD_a)) / EpauleAVD_D;\n    EpauleAVD_a(AZ) += qdd(RF_HAA_JOINT);\n    \n    HJambeAVD_a = (motionTransforms-> fr_HJambeAVD_X_fr_EpauleAVD) * EpauleAVD_a + HJambeAVD_c;\n    qdd(RF_HFE_JOINT) = (HJambeAVD_u - HJambeAVD_U.dot(HJambeAVD_a)) / HJambeAVD_D;\n    HJambeAVD_a(AZ) += qdd(RF_HFE_JOINT);\n    \n    BJambeAVD_a = (motionTransforms-> fr_BJambeAVD_X_fr_HJambeAVD) * HJambeAVD_a + BJambeAVD_c;\n    qdd(RF_KFE_JOINT) = (BJambeAVD_u - BJambeAVD_U.dot(BJambeAVD_a)) / BJambeAVD_D;\n    BJambeAVD_a(AZ) += qdd(RF_KFE_JOINT);\n    \n    EpauleAVG_a = (motionTransforms-> fr_EpauleAVG_X_fr_base) * base_a + EpauleAVG_c;\n    qdd(LF_HAA_JOINT) = (EpauleAVG_u - EpauleAVG_U.dot(EpauleAVG_a)) / EpauleAVG_D;\n    EpauleAVG_a(AZ) += qdd(LF_HAA_JOINT);\n    \n    HJambeAVG_a = (motionTransforms-> fr_HJambeAVG_X_fr_EpauleAVG) * EpauleAVG_a + HJambeAVG_c;\n    qdd(LF_HFE_JOINT) = (HJambeAVG_u - HJambeAVG_U.dot(HJambeAVG_a)) / HJambeAVG_D;\n    HJambeAVG_a(AZ) += qdd(LF_HFE_JOINT);\n    \n    BJambeAVG_a = (motionTransforms-> fr_BJambeAVG_X_fr_HJambeAVG) * HJambeAVG_a + BJambeAVG_c;\n    qdd(LF_KFE_JOINT) = (BJambeAVG_u - BJambeAVG_U.dot(BJambeAVG_a)) / BJambeAVG_D;\n    BJambeAVG_a(AZ) += qdd(LF_KFE_JOINT);\n    \n    EpauleARD_a = (motionTransforms-> fr_EpauleARD_X_fr_base) * base_a + EpauleARD_c;\n    qdd(RH_HAA_JOINT) = (EpauleARD_u - EpauleARD_U.dot(EpauleARD_a)) / EpauleARD_D;\n    EpauleARD_a(AZ) += qdd(RH_HAA_JOINT);\n    \n    HJambeARD_a = (motionTransforms-> fr_HJambeARD_X_fr_EpauleARD) * EpauleARD_a + HJambeARD_c;\n    qdd(RH_HFE_JOINT) = (HJambeARD_u - HJambeARD_U.dot(HJambeARD_a)) / HJambeARD_D;\n    HJambeARD_a(AZ) += qdd(RH_HFE_JOINT);\n    \n    BJambeARD_a = (motionTransforms-> fr_BJambeARD_X_fr_HJambeARD) * HJambeARD_a + BJambeARD_c;\n    qdd(RH_KFE_JOINT) = (BJambeARD_u - BJambeARD_U.dot(BJambeARD_a)) / BJambeARD_D;\n    BJambeARD_a(AZ) += qdd(RH_KFE_JOINT);\n    \n    EpauleARG_a = (motionTransforms-> fr_EpauleARG_X_fr_base) * base_a + EpauleARG_c;\n    qdd(LH_HAA_JOINT) = (EpauleARG_u - EpauleARG_U.dot(EpauleARG_a)) / EpauleARG_D;\n    EpauleARG_a(AZ) += qdd(LH_HAA_JOINT);\n    \n    HJambeARG_a = (motionTransforms-> fr_HJambeARG_X_fr_EpauleARG) * EpauleARG_a + HJambeARG_c;\n    qdd(LH_HFE_JOINT) = (HJambeARG_u - HJambeARG_U.dot(HJambeARG_a)) / HJambeARG_D;\n    HJambeARG_a(AZ) += qdd(LH_HFE_JOINT);\n    \n    BJambeARG_a = (motionTransforms-> fr_BJambeARG_X_fr_HJambeARG) * HJambeARG_a + BJambeARG_c;\n    qdd(LH_KFE_JOINT) = (BJambeARG_u - BJambeARG_U.dot(BJambeARG_a)) / BJambeARG_D;\n    BJambeARG_a(AZ) += qdd(LH_KFE_JOINT);\n    \n    \n    // + Add gravity to the acceleration of the floating base\n    base_a += g;\n}\n", "meta": {"hexsha": "4b6b665e42db12cedd12299060d76415f9484029", "size": 18477, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "popi_software/popi/popi_code/cpp/forward_dynamics.cpp", "max_stars_repo_name": "T2honda/popi_project", "max_stars_repo_head_hexsha": "36901454c58b8200a0d67c780b57835e7dc786d2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 83.0, "max_stars_repo_stars_event_min_datetime": "2020-04-17T09:17:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T11:42:23.000Z", "max_issues_repo_path": "popi_software/popi/popi_code/cpp/forward_dynamics.cpp", "max_issues_repo_name": "T2honda/popi_project", "max_issues_repo_head_hexsha": "36901454c58b8200a0d67c780b57835e7dc786d2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-05-13T08:51:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-09T13:07:30.000Z", "max_forks_repo_path": "popi_software/popi/popi_code/cpp/forward_dynamics.cpp", "max_forks_repo_name": "T2honda/popi_project", "max_forks_repo_head_hexsha": "36901454c58b8200a0d67c780b57835e7dc786d2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 23.0, "max_forks_repo_forks_event_min_datetime": "2020-04-24T11:11:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T07:53:27.000Z", "avg_line_length": 43.1705607477, "max_line_length": 156, "alphanum_fraction": 0.6956215836, "num_tokens": 6999, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568416, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4518468056604458}}
{"text": "#include <fstream>\n#include <vector>\n#include <string>\n\n#include <rw/geometry/Box.hpp>\n#include <rw/geometry/PlainTriMesh.hpp>\n#include <rw/geometry/Plane.hpp>\n#include <rw/math/Random.hpp>\n#include <rw/math/Vector3D.hpp>\n#include <rw/loaders/model3d/STLFile.hpp>\n\n#include <boost/lexical_cast.hpp>\n\nusing namespace rw::geometry;\nusing rw::loaders::STLFile;\nusing namespace rw::math;\n\nint main(int argc, char** argv)\n{\n\tstatic const unsigned int SEED = static_cast<unsigned int>(time(NULL));\n\tRandom::seed(SEED);\n\tsrand(SEED);\n\n    if( argc < 4 ){\n\t\tstd::cout << \"------ Usage: \" << std::endl;\n\t    std::cout << \"- Arg 1 name of col data file\" << std::endl;\n\t    std::cout << \"- Arg 2 width of texels in meters\\n\" << std::endl;\n\t    std::cout << \"- Arg 3 name of output stl file\\n\" << std::endl;\n\t    return 0;\n\t}\n\n\tstd::string filename(argv[1]);\n\tdouble width = boost::lexical_cast<double>(argv[2]);\n\tstd::string outfile(argv[3]);\n\tstd::vector<Vector3D<> > texlets;\n\tchar line[256];\n\tstd::ifstream input(filename.c_str());\n\t// first line is a plane\n\n\tfloat vals[4];\n\tinput.getline(line, 256);\n    sscanf(line, \"%f %f %f %f\", &vals[0], &vals[1], &vals[2], &vals[3]);\n\n    Vector3D<> n(vals[0], vals[1], vals[2]);\n\n\n    Plane p( normalize(n), ((vals[3])/n.norm2())*-0.001 );\n\n\t// and then there are texlets\n\twhile(!input.eof()){\n\t    input.getline(line, 256);\n\t    sscanf(line, \"%f %f %f\", &vals[0], &vals[1], &vals[2]);\n\t    Vector3D<> v(vals[0],vals[1],vals[2]);\n\t    v = v*0.001; // the values are in mm\n\t    texlets.push_back(v);\n\t}\n\tinput.close();\n\t// now create the triangle mesh. Use boxes on the texlets\n\tBox texletBox(width,width,width);\n\tTriMesh::Ptr texletMesh = texletBox.getTriMesh();\n\tTriMesh::Ptr planeMesh = p.getTriMesh();\n\tsize_t meshSize = planeMesh->size()+texletMesh->size()*texlets.size();\n\tPlainTriMesh<> stlMesh(meshSize);\n\n\t// and copy plane triangles into the mesh\n\tfor(size_t i=0;i<planeMesh->size();i++)\n\t    stlMesh[i] = planeMesh->getTriangle(i);\n\n\t// and copy every point into the mesh\n\tfor(size_t i=0;i<texlets.size();i++){\n\t    Transform3D<> transform(texlets[i], Rotation3D<>::identity());\n\t    for(size_t j=0;j<texletMesh->size();j++){\n\t        size_t idx = planeMesh->size()+i*texletMesh->size()+j;\n\t        if(idx>=stlMesh.size())\n\t            RW_THROW(idx<< \">=\" << stlMesh.size() << \"  i:\" << i << \" \" << j);\n\t        stlMesh[idx] = texletMesh->getTriangle(j).transform( transform );\n\t    }\n\t}\n\n\tSTLFile::save(stlMesh, outfile);\n\treturn 0;\n}\n", "meta": {"hexsha": "d18134e3f1f0524c54ab7bbeb2483c2aaf9be7f6", "size": 2480, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "RobWorkSim/example/tools/src/imageFeaturesToStl.cpp", "max_stars_repo_name": "ZLW07/RobWork", "max_stars_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-29T14:16:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T14:16:27.000Z", "max_issues_repo_path": "RobWorkSim/example/tools/src/imageFeaturesToStl.cpp", "max_issues_repo_name": "ZLW07/RobWork", "max_issues_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RobWorkSim/example/tools/src/imageFeaturesToStl.cpp", "max_forks_repo_name": "ZLW07/RobWork", "max_forks_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8795180723, "max_line_length": 79, "alphanum_fraction": 0.6314516129, "num_tokens": 750, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.4518111783663076}}
{"text": "//==================================================================================================\n/*!\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#include <boost/simd/function/scalar/toint.hpp>\n#include <scalar_test.hpp>\n#include <boost/simd/detail/dispatch/meta/as_integer.hpp>\n#include <boost/simd/constant/inf.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/zero.hpp>\n#include <boost/simd/function/ldexp.hpp>\n\nSTF_CASE_TPL (\" bs::saturated_(bs::toint) real\",  STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using r_t = decltype(bs::saturated_(bs::toint)(T()));\n\n  // return type conformity test\n  STF_TYPE_IS(r_t, (bd::as_integer_t<T, signed>));\n\n  // specific values tests\n  STF_EQUAL(bs::saturated_(bs::toint)(T(2)*bs::Valmax<r_t>()),  bs::Valmax<r_t>());\n  STF_EQUAL(bs::saturated_(bs::toint)(T(2)*bs::Valmin<r_t>()),  bs::Valmin<r_t>());\n  STF_EQUAL(bs::saturated_(bs::toint)(T(1.5)*bs::Valmax<r_t>()),  bs::Valmax<r_t>());\n  STF_EQUAL(bs::saturated_(bs::toint)(T(1.5)*bs::Valmin<r_t>()),  bs::Valmin<r_t>());\n\n\n  STF_EQUAL(bs::saturated_(bs::toint)(bs::Inf<T>()),  bs::Inf<r_t>());\n  STF_EQUAL(bs::saturated_(bs::toint)(bs::Minf<T>()), bs::Minf<r_t>());\n  STF_EQUAL(bs::saturated_(bs::toint)(bs::Mone<T>()), bs::Mone<r_t>());\n  STF_EQUAL(bs::saturated_(bs::toint)(bs::Nan<T>()),  bs::Zero<r_t>());\n  STF_EQUAL(bs::saturated_(bs::toint)(bs::One<T>()),  bs::One<r_t>());\n  STF_EQUAL(bs::saturated_(bs::toint)(bs::Zero<T>()), bs::Zero<r_t>());\n\n  T v = T(1);\n  r_t iv = 1;\n  int N = sizeof(T)*8-1;\n  for(int i=0; i < N ; i++, v*= 2, iv <<= 1)\n  {\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n    STF_EQUAL(bs::saturated_(bs::toint)(v), iv);\n    STF_EQUAL(bs::saturated_(bs::toint)(-v), -iv);\n  }\n  STF_EQUAL(bs::saturated_(bs::toint)(bs::ldexp(bs::One<T>(), N)), bs::Valmax<r_t>());\n  STF_EQUAL(bs::saturated_(bs::toint)(bs::ldexp(bs::One<T>(), N+1)), bs::Valmax<r_t>());\n  STF_EQUAL(bs::saturated_(bs::toint)(-bs::ldexp(bs::One<T>(), N+1)), bs::Valmin<r_t>());\n  STF_EQUAL(bs::saturated_(bs::toint)(-bs::ldexp(bs::One<T>(), N+1)), bs::Valmin<r_t>());\n\n} // end of test for floating_\n\nSTF_CASE_TPL (\" bs::saturated_(bs::toint) unsigned_int\",  STF_UNSIGNED_INTEGRAL_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using r_t = decltype(bs::saturated_(bs::toint)(T()));\n\n  // return type conformity test\n  STF_TYPE_IS(r_t, (bd::as_integer_t<T, signed>));\n\n  // specific values tests\n  STF_EQUAL(bs::saturated_(bs::toint)(bs::One<T>()),  bs::One<r_t>());\n  STF_EQUAL(bs::saturated_(bs::toint)(bs::Zero<T>()), bs::Zero<r_t>());\n} // end of test for unsigned_int_\n\nSTF_CASE_TPL (\" bs::saturated_(bs::toint) signed\",  STF_SIGNED_INTEGRAL_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n\n  using r_t = decltype(bs::saturated_(bs::toint)(T()));\n  // return type conformity test\n  STF_TYPE_IS(r_t, (bd::as_integer_t<T, signed>));\n\n\n  // specific values tests\n  STF_EQUAL(bs::saturated_(bs::toint)(bs::Mone<T>()), bs::Mone<r_t>());\n  STF_EQUAL(bs::saturated_(bs::toint)(bs::One<T>()),  bs::One<r_t>());\n  STF_EQUAL(bs::saturated_(bs::toint)(bs::Zero<T>()), bs::Zero<r_t>());\n} // end of test for signed_int_\n", "meta": {"hexsha": "abf81dcb5139a2793f0b87bc73ef3fb1dda67573", "size": 3592, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/scalar/toint.saturated.cpp", "max_stars_repo_name": "timblechmann/boost.simd", "max_stars_repo_head_hexsha": "2217f1d0102193799469b533e3a7118bf4a77dde", "max_stars_repo_licenses": ["BSL-1.0"], "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": "test/function/scalar/toint.saturated.cpp", "max_issues_repo_name": "timblechmann/boost.simd", "max_issues_repo_head_hexsha": "2217f1d0102193799469b533e3a7118bf4a77dde", "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/function/scalar/toint.saturated.cpp", "max_forks_repo_name": "timblechmann/boost.simd", "max_forks_repo_head_hexsha": "2217f1d0102193799469b533e3a7118bf4a77dde", "max_forks_repo_licenses": ["BSL-1.0"], "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": 39.9111111111, "max_line_length": 100, "alphanum_fraction": 0.6191536748, "num_tokens": 1152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.6825737473266735, "lm_q1q2_score": 0.45181117781017904}}
{"text": "//\n// Created by alex on 26/05/20.\n//\n\n#include <cmath>\n#include <vector>\n#include <string>\n#include <iostream>\n#include <numeric>\n#include <boost/algorithm/string.hpp>\n#include <fstream>\n#include \"FileUtil.h\"\n\nusing namespace std;\n\nbool BothAreSpaces(char lhs, char rhs) { return (lhs == rhs) && (lhs == ' '); }\n\npair<vector<pair<int, int>>, int> FileUtil::load_graph(const std::string &file_path) {\n\n    vector<std::vector<int>> vertices;\n    string line;\n    ifstream file(file_path);\n    vector<std::pair<int, int>> edges_vec;\n    int n = -1;\n    if (file.is_open()) {\n\n        getline(file, line);\n        std::string::iterator new_end = std::unique(line.begin(), line.end(), BothAreSpaces);\n        line.erase(new_end, line.end());\n\n        boost::trim_right(line);\n        boost::trim_left(line);\n\n        vector<std::string> line_vec;\n        boost::split(line_vec, line, boost::is_any_of(\" \"));\n\n        string ninfo = line_vec[0];\n        string minfo = line_vec[1];\n\n        line_vec.clear();\n        boost::split(line_vec, ninfo, boost::is_any_of(\"=\"));\n        n = stoi(line_vec[1]);\n\n        line_vec.clear();\n        boost::split(line_vec, minfo, boost::is_any_of(\"=\"));\n        int m = stoi(line_vec[1]);\n        edges_vec.reserve(m);\n\n        while (getline(file, line)) {\n            line_vec.clear();\n            std::replace(std::begin(line),std::end(line),'\\t',' ');\n            boost::trim_right(line);\n            boost::trim_left(line);\n            std::string::iterator new_end = std::unique(line.begin(), line.end(), BothAreSpaces);\n            line.erase(new_end, line.end());\n\n            boost::split(line_vec, line, boost::is_any_of(\" \"));\n\n           int i = stoi(line_vec[0])-1;\n           int j = stoi(line_vec[1])-1;\n           edges_vec.emplace_back(i,j);\n        }\n        file.close();\n    } else {\n        cerr << \"Unable to open file\" << std::endl;\n    }\n    return make_pair(edges_vec, n);\n}\n\nvoid FileUtil::floydWarshall(std::vector<std::vector<float>> &G) {\n    int n = G.size();\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            for (int l = 0; l < n; ++l) {\n                float cost = (G[i][j] == +INFINITY || G[i][l] == +INFINITY) ?\n                             +INFINITY : G[i][j] + G[i][l];\n                if (cost < G[j][l]) {\n                    G[j][l] = cost;\n                }\n            }\n        }\n    }\n}\n\nfloat FileUtil::stdDev(std::vector<float> &items, float average) {\n    float std = 0;\n    for (float item : items) {\n        std += pow(item - average, 2);\n    }\n    int n = items.size() > 2 ? items.size() - 1 : items.size();\n    return sqrt(std / n);\n}\n\nbool FileUtil::save(std::string &output_path, std::string &content) {\n    std::ofstream output_file(output_path);\n//    output_file.write(&content, content.size());\n    output_file << content;\n    output_file.close();\n    return true;\n}\n", "meta": {"hexsha": "7de7fdcef7b9fb1757cdc345930a83b570d0dfaf", "size": 2891, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/utils/FileUtil.cpp", "max_stars_repo_name": "alex-cornejo/bff_alg", "max_stars_repo_head_hexsha": "9a06a0d2c8178751cfa9ba434eddf214c89f1eb1", "max_stars_repo_licenses": ["Apache-2.0"], "max_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/FileUtil.cpp", "max_issues_repo_name": "alex-cornejo/bff_alg", "max_issues_repo_head_hexsha": "9a06a0d2c8178751cfa9ba434eddf214c89f1eb1", "max_issues_repo_licenses": ["Apache-2.0"], "max_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/FileUtil.cpp", "max_forks_repo_name": "alex-cornejo/bff_alg", "max_forks_repo_head_hexsha": "9a06a0d2c8178751cfa9ba434eddf214c89f1eb1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-04T15:17:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-04T15:17:01.000Z", "avg_line_length": 28.6237623762, "max_line_length": 97, "alphanum_fraction": 0.5416810792, "num_tokens": 757, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.4518111738140917}}
{"text": "#define BOOST_TEST_ALTERNATIVE_INIT_API\n#include <boost/test/included/unit_test.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/parameterized_test.hpp>\n#include <boost/bind.hpp>\n\nclass test_class {\n    public:\n        void test_method(double d) {\n            BOOST_TEST(d * 100 == (double)(int)(d * 100),\n                       boost::test_tools::tolerance(0.0001));\n        }\n} tester;\n\nbool init_unit_test() {\n    double params[] = { 1., 1.00001 };\n\n    boost::function<void(double)> test_method = \n        boost::bind(&test_class::test_method, &tester, _1);\n\n    boost::unit_test::framework::master_test_suite().\n        add(BOOST_PARAM_TEST_CASE(test_method, params, params + 2));\n                                                \n    return true;\n}\n", "meta": {"hexsha": "81fa4bd1a9a2a66dd3e5fd636b645b1501a4d3d4", "size": 783, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "books/tech/cpp/boost/official_doc/11-correctness_and_testing/04-test/17-unary_method_test_case/main.cpp", "max_stars_repo_name": "ordinary-developer/education", "max_stars_repo_head_hexsha": "1b1f40dacab873b28ee01dfa33a9bd3ec4cfed58", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "books/tech/cpp/boost/official_doc/11-correctness_and_testing/04-test/17-unary_method_test_case/main.cpp", "max_issues_repo_name": "ordinary-developer/education", "max_issues_repo_head_hexsha": "1b1f40dacab873b28ee01dfa33a9bd3ec4cfed58", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "books/tech/cpp/boost/official_doc/11-correctness_and_testing/04-test/17-unary_method_test_case/main.cpp", "max_forks_repo_name": "ordinary-developer/education", "max_forks_repo_head_hexsha": "1b1f40dacab873b28ee01dfa33a9bd3ec4cfed58", "max_forks_repo_licenses": ["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.1153846154, "max_line_length": 68, "alphanum_fraction": 0.619412516, "num_tokens": 182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.4518111738140917}}
{"text": "#include <mtl/dense1D.h>\n#include <mtl/mtl.h>\n#include <mtl/utils.h>\n\n/*\n  example output:\n\n  [4,4,4,4,4,4,4,4,4,4]\n\n  */\n\nint\nmain()\n{\n  using namespace mtl;\n  //begin\n  dense1D<double> x(10,1);\n  dense1D<double> y(10);\n  double alpha = 4.0;\n  mtl::copy(scaled(x, alpha), y);\n  //end\n  print_vector(y);\n  return 0;\n}\n", "meta": {"hexsha": "4f1550ca2075297c5cfe1881316c91535a268f9c", "size": 318, "ext": "cc", "lang": "C++", "max_stars_repo_path": "stapl_release/tools/mtl-2.0/contrib/examples/vecvec_copy.cc", "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/tools/mtl-2.0/contrib/examples/vecvec_copy.cc", "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/tools/mtl-2.0/contrib/examples/vecvec_copy.cc", "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": 12.72, "max_line_length": 33, "alphanum_fraction": 0.5943396226, "num_tokens": 129, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.4518111738140917}}
{"text": "#include \"generator.h\"\n#include \"delaunay.h\"\n#include \"minimum_spanning_tree.h\"\n#include \"validate.h\"\n#include \"visualization.h\"\n#include <boost/program_options.hpp>\n\nusing namespace boost::program_options;\n\nint main(int argc, char *argv[])\n{\n    //set generate option\n    int GENERATE_CASE = 1;\n\n    //set the filename to save these points' & graph's data\n    std::string PREFIX, SUFFIX;\n    std::string POINTS_FILENAME;\n    std::string TRIANGULATION_FILENAME;\n    std::string VORONOI_FILENAME;\n    std::string MST_FILENAME;\n\n    //save points into this container\n    std::vector<Simple_Point> raw_data;\n\n    //save trangulation information into this container\n    std::vector<Edge> triangulation_data;\n\n    //save voronoi diagram infomation into this container\n    std::vector<std::pair<Simple_Point, Simple_Point> >voronoi_data;\n\n    //save mst infomation into this container\n    std::vector<Edge> mst_data;\n\n    //read from command line\n    try\n    {\n        options_description desc(\"Options\");\n        desc.add_options()\n        (\"help,h\", \"display this help and exit\")\n        (\"number,n\", value<int>(&Generator::TOTAL_NUMBER_OF_POINTS)->default_value(10000), \"number of points\")\n        (\"circle,c\", \"reset generation method to random in a circle, default: random in full square\")\n        (\"test,t\", value<std::string>(&PREFIX)->default_value(\"../../testcase/test/\"), \"test mode & set file path & read data from data.txt\")\n        (\"range,r\", value<int>(&Generator::MAX_COORDINATE)->default_value(10000), \"coordinate range [0, number)\")\n        (\"distance,d\", value<ld>(&Generator::MIN_DISTANCE)->default_value(1e-3), \"minimum distance between each pair of points\")\n        (\"img-size,i\", value<int>(&Visualization::IMAGE_SIZE)->default_value(2000), \"size of image\")\n        (\"suffix,s\", value<std::string>(&SUFFIX)->default_value(\"png\"), \"set the suffix of output image\")\n        (\"window,w\", \"display the window\")\n        (\"voronoi,v\", \"output voronoi diagram infomation\");\n\n        variables_map vm;\n        store(parse_command_line(argc, argv, desc), vm);\n        notify(vm);\n\n        if (vm.count(\"help\"))\n        {\n            std::cout << \"Delaunay triangulation for calculating Euclidean distance minimum spanning tree\" << std::endl;\n            std::cout << \"Made by n+e\\t2017-04\" << std::endl;\n            std::cout << std::endl;\n            std::cout << desc << std::endl;\n            std::cout << \"Examples:\" << std::endl;\n            std::cout << \"Generate new testcase in default file path, 10 points in [0,10), save in jpg file, and show window:\" << std::endl;\n            std::cout << \"\\t./main -n 10 -r 10 -s jpg -w\" << std::endl;\n            std::cout << \"Use circle-shape testcase in file \\\"../../testcase/circle_100000/\\\" and output voronoi message:\" << std::endl;\n            std::cout << \"\\t./main -t ../../testcase/circle_100000/ -v\" << std::endl << std::endl;\n            return 0;\n        }\n        if (Generator::TOTAL_NUMBER_OF_POINTS <= 0 || Generator::TOTAL_NUMBER_OF_POINTS >= 5000000)\n        {\n            std::cerr << \"Number of points is invalid!\" << std::endl;\n            return 1;\n        }\n        if (Visualization::IMAGE_SIZE <= 0 || Visualization::IMAGE_SIZE > 5000)\n        {\n            std::cerr << \"Size of image is invalid!\" << std::endl;\n            return 1;\n        }\n        if (Generator::MAX_COORDINATE <= 1)\n        {\n            std::cerr << \"max coordinate is invalid!\" << std::endl;\n            return 1;\n        }\n        if (Generator::MIN_DISTANCE <= 0)\n        {\n            std::cerr << \"min distance is invalid!\" << std::endl;\n            return 1;\n        }\n        if (vm.count(\"circle\"))\n            Generator::METHOD_CASE = 1;\n        if (vm.count(\"voronoi\"))\n            Delaunay_Triangulation::VORONOI_CASE = 1;\n        if (PREFIX != \"../../testcase/test/\")\n        {\n            GENERATE_CASE = 0;\n            if (PREFIX[PREFIX.length() - 1] != '/')\n                PREFIX += '/';\n        }\n        POINTS_FILENAME = PREFIX + \"data.txt\";\n        TRIANGULATION_FILENAME = PREFIX + \"triangulation.txt\";\n        VORONOI_FILENAME = PREFIX + \"voronoi.txt\";\n        MST_FILENAME = PREFIX + \"mst.txt\";\n\n        //generate data\n        if (GENERATE_CASE != 0)\n            raw_data = Generator().Save(POINTS_FILENAME);\n        else\n        {\n            TIME_BEGIN(\"Read data from data.txt\")\n            std::ifstream in;\n            in.open(POINTS_FILENAME.c_str());\n            ld x, y;\n            Generator::MAX_COORDINATE = 0;\n            while (in >> x >> y)\n            {\n                raw_data.push_back(Simple_Point(x, y));\n                if (Generator::MAX_COORDINATE < x)Generator::MAX_COORDINATE = x;\n                if (Generator::MAX_COORDINATE < y)Generator::MAX_COORDINATE = y;\n            }\n            std::sort(raw_data.begin(), raw_data.end());\n            Generator::TOTAL_NUMBER_OF_POINTS = raw_data.size();\n            in.close();\n            TIME_END\n        }\n        //calculate triangulation using CGAL library\n        Delaunay_Triangulation cgal_dt(raw_data);\n        cgal_dt.Save(TRIANGULATION_FILENAME, VORONOI_FILENAME, triangulation_data, voronoi_data);\n        //calculate mst with kruskal\n        MST mymst(triangulation_data);\n        mst_data = mymst.Save(MST_FILENAME);\n        //check delaunay triangulation\n        My_Delaunay myd(raw_data);\n        //check mst with prim\n        Prim prim(raw_data);\n        //visualize the result\n        Visualization visual(vm.count(\"window\"), PREFIX, SUFFIX, raw_data, triangulation_data, voronoi_data, mst_data);\n    }\n    catch (const error &e)\n    {\n        std::cerr << e.what() << std::endl;\n        return 1;\n    }\n    return 0;\n}\n", "meta": {"hexsha": "a02a8d9b1ec8a2f692c7fd5a93f9a27c482ecf3a", "size": 5685, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "\u9762\u5411\u5bf9\u8c61\u7a0b\u5e8f\u8bbe\u8ba1\u57fa\u7840/IndividualProject/oop_individual_project_2017/src/main.cpp", "max_stars_repo_name": "jasnzhuang/Personal-Homework", "max_stars_repo_head_hexsha": "edf633ce94f22a646786b85e133797339cf9fc3d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 463.0, "max_stars_repo_stars_event_min_datetime": "2019-10-25T04:28:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T06:03:44.000Z", "max_issues_repo_path": "\u9762\u5411\u5bf9\u8c61\u7a0b\u5e8f\u8bbe\u8ba1\u57fa\u7840/IndividualProject/oop_individual_project_2017/src/main.cpp", "max_issues_repo_name": "1002753959/Undergraduate", "max_issues_repo_head_hexsha": "95e6e95a98f53e350d628edacad0042382c6a464", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-11-28T08:05:22.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-28T08:26:34.000Z", "max_forks_repo_path": "\u9762\u5411\u5bf9\u8c61\u7a0b\u5e8f\u8bbe\u8ba1\u57fa\u7840/IndividualProject/oop_individual_project_2017/src/main.cpp", "max_forks_repo_name": "1002753959/Undergraduate", "max_forks_repo_head_hexsha": "95e6e95a98f53e350d628edacad0042382c6a464", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 201.0, "max_forks_repo_forks_event_min_datetime": "2019-04-10T07:17:10.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-15T09:46:30.000Z", "avg_line_length": 39.7552447552, "max_line_length": 141, "alphanum_fraction": 0.5880386983, "num_tokens": 1408, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.6825737214979745, "lm_q1q2_score": 0.45181116071357225}}
{"text": "#include <iostream>\n#include <vector>\n#include <utility>\n#include <iterator>\n#include <cstdlib>\n#include <limits>\n#include <cerrno>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/graph_concepts.hpp>\n#include <boost/concept_check.hpp>\n#include <boost/operators.hpp>\n#include <boost/iterator.hpp>\n#include <boost/multi_array.hpp>\n#include <boost/random.hpp>\n#include \"edmonds_optimum_branching.hpp\"\n\n//#define DEBUG\n\nusing namespace std;\nusing namespace boost;\n\nstruct Line {\n    unsigned int from, to, price;\n\n    Line(unsigned int from, unsigned int to, unsigned int price) : from(from), to(to), price(price) {};\n};\n\nstruct Result {\n    bool feasibility;\n    unsigned long total_cost;\n    unsigned int depot_id;\n    std::vector<Line> rec_offers;\n};\n\nclass GraphProcessor {\npublic:\n    bool load_input();\n    void find_hub();\n    void send_result();\n\nprivate:\n    Result last_res;\n    int cities_cnt;\n    std::vector<Line> lines;\n};\n\n// definitions of a complete graph that implements the EdgeListGraph\n// concept of Boost's graph library.\nnamespace boost {\n    struct complete_graph {\n        complete_graph(int n_vertices) : n_vertices(n_vertices) {}\n        int n_vertices;\n\n        struct edge_iterator : public input_iterator_helper<edge_iterator, int, std::ptrdiff_t, int const *, int>\n        {\n            int edge_idx, n_vertices;\n\n            edge_iterator() : edge_idx(0), n_vertices(-1) {}\n            edge_iterator(int n_vertices, int edge_idx) : edge_idx(edge_idx), n_vertices(n_vertices) {}\n            edge_iterator &operator++()\n            {\n                if (edge_idx >= n_vertices * n_vertices)\n                    return *this;\n                ++edge_idx;\n                if (edge_idx / n_vertices == edge_idx % n_vertices)\n                    ++edge_idx;\n                return *this;\n            }\n            int operator*() const {return edge_idx;}\n            bool operator==(const edge_iterator &iter) const\n            {\n                return edge_idx == iter.edge_idx;\n            }\n        };\n    };\n\n    template<>\n    struct graph_traits<complete_graph> {\n        typedef int                             vertex_descriptor;\n        typedef int                             edge_descriptor;\n        typedef directed_tag                    directed_category;\n        typedef disallow_parallel_edge_tag      edge_parallel_category;\n        typedef edge_list_graph_tag             traversal_category;\n        typedef complete_graph::edge_iterator   edge_iterator;\n        typedef unsigned                        edges_size_type;\n\n        static vertex_descriptor null_vertex() {return -1;}\n    };\n\n    pair<complete_graph::edge_iterator, complete_graph::edge_iterator>\n    edges(const complete_graph &g)\n    {\n        return make_pair(complete_graph::edge_iterator(g.n_vertices, 1),\n                         complete_graph::edge_iterator(g.n_vertices, g.n_vertices*g.n_vertices));\n    }\n\n    unsigned\n    num_edges(const complete_graph &g)\n    {\n        return (g.n_vertices - 1) * (g.n_vertices - 1);\n    }\n\n    int\n    source(int edge, const complete_graph &g)\n    {\n        return edge / g.n_vertices;\n    }\n\n    int\n    target(int edge, const complete_graph &g)\n    {\n        return edge % g.n_vertices;\n    }\n}\n\ntypedef graph_traits<complete_graph>::edge_descriptor Edge;\ntypedef graph_traits<complete_graph>::vertex_descriptor Vertex;\n", "meta": {"hexsha": "2f3a57137179107d43db671168497c1fc13eafce", "size": 3426, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "task1/find_hub.hpp", "max_stars_repo_name": "garncarz/prague-transport-2017", "max_stars_repo_head_hexsha": "f758a0f5a2e920bc5df8da74d4c55914c07d9fe3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "task1/find_hub.hpp", "max_issues_repo_name": "garncarz/prague-transport-2017", "max_issues_repo_head_hexsha": "f758a0f5a2e920bc5df8da74d4c55914c07d9fe3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "task1/find_hub.hpp", "max_forks_repo_name": "garncarz/prague-transport-2017", "max_forks_repo_head_hexsha": "f758a0f5a2e920bc5df8da74d4c55914c07d9fe3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.7899159664, "max_line_length": 113, "alphanum_fraction": 0.6284296556, "num_tokens": 705, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.45178851618364296}}
{"text": "#ifndef BG_UTILS_HPP\n#define BG_UTILS_HPP\n\n#include \"bg_types.hpp\"\n\n#include <boost/geometry/srs/epsg.hpp>\n#include <boost/geometry/srs/projection.hpp>\n#include <boost/geometry/srs/projections/proj4.hpp>\n\n#include <boost/range/adaptors.hpp>\n#include <boost/range/algorithm.hpp>\n\ntemplate <int ppc, class T>\nMultipolygon2D buffer2D(T && g, float width) {\n    Multipolygon2D mp2d;\n    boost::geometry::strategy::buffer::distance_symmetric<float>\n        distance_strategy(width / 2);\n    boost::geometry::strategy::buffer::join_round join_strategy(ppc);\n    boost::geometry::strategy::buffer::end_flat end_strategy;\n    boost::geometry::strategy::buffer::point_circle point_strategy(ppc);\n    boost::geometry::strategy::buffer::side_straight side_strategy;\n    boost::geometry::buffer(g, mp2d, distance_strategy, side_strategy,\n                            join_strategy, end_strategy, point_strategy);\n    return mp2d;\n}\n\ntemplate <class Point>\nMultipolygonGeo buffer_PointGeo(Point && p, float width) {\n    boost::geometry::srs::projection<> proj = boost::geometry::srs::proj4(\n        \"+proj=eqc +ellps=GRS80 +lon_0=\" + std::to_string(p.x()) +\n        \" +lat_0=\" + std::to_string(p.y()));\n\n    MultipolygonGeo mp;\n\n    Point2D p2d;\n    proj.forward(p, p2d);\n    Multipolygon2D mp2d = buffer2D<8>(p2d, width);\n    proj.inverse(mp2d, mp);\n\n    return mp;\n}\n\ntemplate <class Linestring>\nMultipolygonGeo buffer_LinestringGeo(Linestring && l, float width) {\n    PointGeo center = boost::geometry::return_centroid<PointGeo>(\n        boost::geometry::return_envelope<BoxGeo>(l));\n    boost::geometry::srs::projection<> proj = boost::geometry::srs::proj4(\n        \"+proj=eqc +ellps=GRS80 +lon_0=\" + std::to_string(center.x()) +\n        \" +lat_0=\" + std::to_string(center.y()));\n\n    MultipolygonGeo mp;\n\n    Linestring2D l2d;\n    proj.forward(l, l2d);\n\n    Linestring2D l2d_simplified;\n    boost::geometry::simplify(l2d, l2d_simplified, 0.5);\n\n    l2d_simplified[0] = Point2D(\n        (9999 * l2d_simplified[0].get<0>() + l2d_simplified[1].get<0>()) /\n            10000,\n        (9999 * l2d_simplified[0].get<1>() + l2d_simplified[1].get<1>()) /\n            10000);\n\n    const int last_id = l2d_simplified.size() - 1;\n    l2d_simplified[last_id] = Point2D((9999 * l2d_simplified[last_id].get<0>() +\n                                       l2d_simplified[last_id - 1].get<0>()) /\n                                          10000,\n                                      (9999 * l2d_simplified[last_id].get<1>() +\n                                       l2d_simplified[last_id - 1].get<1>()) /\n                                          10000);\n\n    Multipolygon2D mp2d = buffer2D<4>(l2d_simplified, width);\n\n    Multipolygon2D mp2d_simplified;\n    boost::geometry::simplify(mp2d, mp2d_simplified, 0.5);\n\n    proj.inverse(mp2d_simplified, mp);\n\n    // if(! boost::geometry::is_valid(mp)) {\n    //     std::string m;\n    //     boost::geometry::is_valid(mp, m);\n    //     throw std::runtime_error{m};\n    // }\n\n    return mp;\n}\n\n#endif  // BG_UTILS_HPP", "meta": {"hexsha": "3b2e6d3d583fa8aefaa0dd8394047ff7182b4774", "size": 3036, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/bg_utils.hpp", "max_stars_repo_name": "fhamonic/osm2sorted_geojson", "max_stars_repo_head_hexsha": "de2b83e43dab9756464a0de42f45335aa3562ce4", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-23T11:56:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-23T11:56:01.000Z", "max_issues_repo_path": "include/bg_utils.hpp", "max_issues_repo_name": "fhamonic/osm2geojson", "max_issues_repo_head_hexsha": "de2b83e43dab9756464a0de42f45335aa3562ce4", "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/bg_utils.hpp", "max_forks_repo_name": "fhamonic/osm2geojson", "max_forks_repo_head_hexsha": "de2b83e43dab9756464a0de42f45335aa3562ce4", "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.1123595506, "max_line_length": 80, "alphanum_fraction": 0.6225296443, "num_tokens": 857, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.45178851074907656}}
{"text": "/*\n\nAdopted from Thomas Prest's project https://github.com/tprest/Lattice-IBE and edited for this transformation. \nTherefore, please respect its license and requirements.\n\n*/\n\n\n\n#include <stdlib.h>\n#include <assert.h>\n#include <math.h>\n#include <complex.h>\n#include <time.h>\n#include <NTL/ZZ.h>\n#include <NTL/ZZX.h>\n#include <NTL/mat_ZZ.h>\n#include <gmp.h>\n\n\n#include \"params.h\"\n#include \"io.h\"\n#include \"FFT.h\"\n#include \"Sampling.h\"\n#include \"Random.h\"\n#include \"Algebra.h\"\n#include \"Scheme.h\"\n\n\nusing namespace std;\nusing namespace NTL;\n\n\n\n\n//==============================================================================\n//==============================================================================\n//                                  MAIN\n//==============================================================================\n//==============================================================================\n\n\nint main()\n{\n    cout << \"\\n=======================================================================\\n\";\n    cout << \"This program is a proof-of concept for efficient PEKS over lattices.\\n\";\n    cout << \"It generates a NTRU lattice of dimension 2N and associated modulus q,\\n\";\n    cout << \"and perform benches and tests, for user PEKS and Trapdoor  and Test.\";\n    cout << \"\\n=======================================================================\\n\\n\";\n\n    ZZX MSK[4];\n    ZZ_pX phiq, MPK;\n    unsigned int i;\n    float diff;\n    MSK_Data * MSKD = new MSK_Data;\n    MPK_Data * MPKD = new MPK_Data;\n    clock_t t1, t2;\n    const ZZX phi = Cyclo();\n\n    srand(rdtsc()); // initialisation of rand\n    cout << \"N = \" << N0 << endl;\n    cout << \"q = \" << q0 << endl;\n\n    ZZ_p::init(q1);\n    zz_p::init(q0);\n\n    phiq = conv<ZZ_pX>(phi);\n    ZZ_pXModulus PHI(phiq);\n\n\n    cout << \"\\n===================================================================\\n KEY GENERATION\";\n    cout << \"\\n===================================================================\\n\";\n    t1 = clock();\n    for(i=0; i<1; i++)\n    {\n        Keygen(MPK, MSK);\n    }\n\n    CompleteMSK(MSKD, MSK);\n    CompleteMPK(MPKD, MPK);\n\n    t2 = clock();\n    diff = ((float)t2 - (float)t1)/1000000.0F;\n    cout << \"It took \" << diff << \" seconds to generate user keys\" << endl;\n\n\n\n    //==============================================================================\n    //Key extraction bench and encryption/decryption bench\n    //==============================================================================\n    const unsigned int nb_trdb = 1000;\n    const unsigned int nb_crypb = 1000;\n    //const unsigned int nb_decrypb = 1000;\n\n\n    cout << \"\\n===================================================================\\n RUNNING PEKS BENCH FOR \";\n    cout << nb_crypb << \" DIFFERENT KEYWORDS\\n===================================================================\\n\";\n    Encrypt_Bench(nb_crypb, MPKD, MSKD);\n\n\n    cout << \"\\n===================================================================\\n RUNNING TRAPDOOR BENCH FOR \";\n    cout << nb_trdb << \" DIFFERENT KEYWORDS\\n===================================================================\\n\";\n    Trapdoor_Bench(nb_trdb, MSKD);\n\n    ///==============================================================================\n    //Key extraction test and encryption/decryption test\n    //==============================================================================\n    const unsigned int nb_trdt = 100;\n    const unsigned int nb_crypt = 100;\n\n\n    cout << \"\\n===================================================================\\n CHECKING PEKS VALIDITY FOR \";\n    cout << nb_crypt << \" DIFFERENT KEYWORDS\\n===================================================================\\n\";\n    Encrypt_Test(nb_crypt, MPKD, MSKD);\n\n    cout << \"\\n===================================================================\\n CHECKING TRAPDOOR VALIDITY FOR \";\n    cout << nb_trdt << \" DIFFERENT KEYWORDS\\n===================================================================\\n\";\n\tTrapdoor_Test(nb_trdt, MSKD);\n\n\n    free(MSKD);\n    free(MPKD);\n    return 0;\n}\n", "meta": {"hexsha": "ec351faf0d58a544a4b5e9e846cdbdf84763ea06", "size": 4037, "ext": "cc", "lang": "C++", "max_stars_repo_path": "PEKS.cc", "max_stars_repo_name": "Rbehnia/NTRUPEKS", "max_stars_repo_head_hexsha": "780d5ef54baaa6c09386185e4d4fce1dc2e394f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-09-15T01:54:10.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-25T06:55:49.000Z", "max_issues_repo_path": "PEKS.cc", "max_issues_repo_name": "Rbehnia/NTRUPEKS", "max_issues_repo_head_hexsha": "780d5ef54baaa6c09386185e4d4fce1dc2e394f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PEKS.cc", "max_forks_repo_name": "Rbehnia/NTRUPEKS", "max_forks_repo_head_hexsha": "780d5ef54baaa6c09386185e4d4fce1dc2e394f7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-05-22T21:39:45.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-22T21:39:45.000Z", "avg_line_length": 32.296, "max_line_length": 118, "alphanum_fraction": 0.3893980679, "num_tokens": 827, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186768138228, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4517885053145101}}
{"text": "#include <iostream>\n#include <string>\n#include <sstream>\n#include <NTL/ZZ_pX.h>\n#include <NTL/mat_ZZ_p.h>\n#include <NTL/vec_ZZ_p.h>\n\nusing namespace NTL;\nstd::stringstream outstream;\nstd::string tStr;\n \nstatic const char *ret_stream(void);\nstatic char *prep_string(char *s);\nextern \"C\" {\n    const char *convert_matrix(char *in);\n    const char *compute_laurent(char *t_yP, char *t_r, char *t_s);\n    void clear_stringstream(void);\n    void init(char *p);\n}\n\nvoid init(char *p) {\n    ZZ_p::init(conv<ZZ>(p));\n}\n\nvoid clear_stringstream(void) {\n    outstream.clear();\n    outstream.str(std::string());\n}\n\nstatic const char *ret_stream(void) {\n    tStr = std::move(outstream.str());\n    for (auto it = tStr.begin(); it != tStr.end(); it++) {\n        if ((*it == '\\n') || (*it == ' ')) {\n            *it = ',';\n        }\n    }\n    return tStr.c_str();\n}\n\nstatic char *prep_string(char *s) {\n    for (unsigned i = 0; s[i] != '\\0'; i++) {\n        if ((s[i] == ',') || (s[i] == 'L')) {\n            s[i] = ' ';\n        }\n    }\n    return s;\n}\n\nconst char *convert_matrix(char *in) {\n    clear_stringstream();\n\n    Mat<ZZ_p> mat{conv<Mat<ZZ_p>>(prep_string(in))};\n    outstream << mat;\n    return ret_stream();\n}\n\nconst char *compute_laurent(char *t_yP, char *t_r, char *t_s) {\n    clear_stringstream();\n\n    // convert\n    Mat<ZZ_p> rT, rPT;\n    unsigned n;\n#ifdef EXTRATESTS\n    Vec<ZZ_p> uv;\n#endif\n    {\n        Vec<ZZ_p> yP{conv<Vec<ZZ_p>>(prep_string(t_yP))};\n        Mat<ZZ_p> r{conv<Mat<ZZ_p>>(prep_string(t_r))};\n        Mat<ZZ_p> s{conv<Mat<ZZ_p>>(prep_string(t_s)) * 2};\n\n        // compute r' = r o yP + 2s\n        Mat<ZZ_p> rP{r};\n        for (unsigned i = 0; i < rP.NumRows(); i++) {\n            for (unsigned j = 0; j < rP.NumCols(); j++) {\n                rP[i][j] *= yP[j];\n            }\n            rP[i] += s[i];\n        }\n        rT = transpose(r);\n        rPT = transpose(rP);\n        n = yP.length();\n#ifdef EXTRATESTS\n        ZZ_p tmp;\n        uv.SetLength(2*r.NumRows() - 1);\n        for (unsigned ui = 0; ui < r.NumRows(); ui++) {\n            for (unsigned vi = 0; vi < r.NumRows(); vi++) {\n                InnerProduct(tmp, r[ui], rP[vi]);\n                uv[ui + vi] += tmp;\n            }\n        }\n#endif\n    }\n\n    // now compute r * r' using polymul\n    ZZ_pX fg;\n    {\n        ZZ_pX f, g, tmp;\n        for (unsigned j = 0; j < n; j++) {\n            f.rep = std::move(rT[j]);\n            g.rep = std::move(rPT[j]);\n            tmp = f * g;\n            fg += tmp;\n        }\n    }\n\n#ifdef EXTRATESTS\n    {\n        bool correct = true;\n        for (unsigned j = 0; j < uv.length(); j++) {\n            correct &= uv[j] == fg[j];\n        }\n        if (!correct) {\n            std::cerr << \"ERROR: mismatched results\\n\" << uv << std::endl << fg << std::endl;\n        }\n    }\n#endif\n\n    outstream << fg;\n    return ret_stream();\n}\n", "meta": {"hexsha": "970e77c23d17d7db3009df3b11649c6bd409f31e", "size": 2847, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/pylaurent.cc", "max_stars_repo_name": "hyraxZK/pylaurent", "max_stars_repo_head_hexsha": "c2176c97b06ee8e8e17c30fc53ba93c29e42c744", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/pylaurent.cc", "max_issues_repo_name": "hyraxZK/pylaurent", "max_issues_repo_head_hexsha": "c2176c97b06ee8e8e17c30fc53ba93c29e42c744", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pylaurent.cc", "max_forks_repo_name": "hyraxZK/pylaurent", "max_forks_repo_head_hexsha": "c2176c97b06ee8e8e17c30fc53ba93c29e42c744", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-12-27T07:03:05.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-27T07:03:05.000Z", "avg_line_length": 23.5289256198, "max_line_length": 93, "alphanum_fraction": 0.4959606603, "num_tokens": 868, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867681382279, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.45178850531451}}
{"text": "#ifndef SM_UNCERTAIN_TRANSFORMATION_HPP\n#define SM_UNCERTAIN_TRANSFORMATION_HPP\n\n#include <boost/serialization/base_object.hpp>\n#include \"Transformation.hpp\"\n#include \"UncertainHomogeneousPoint.hpp\"\n\nnamespace sm {\nnamespace kinematics {\n\nclass UncertainTransformation : public Transformation {\n  public:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n    typedef Eigen::Matrix<double, 6, 6> covariance_t;\n    ///\n    /// Default constructor. The transformation and uncertainty will\n    /// both be set to identity.\n    ///\n    UncertainTransformation();\n\n    UncertainTransformation(const Eigen::Matrix4d& T, const covariance_t& U);\n\n    UncertainTransformation(const Eigen::Matrix4d& T, double diagonalTranslationVariance,\n                            double diagonalRotationVariance);\n\n    UncertainTransformation(const Eigen::Vector4d& q_a_b, const Eigen::Vector3d& t_a_b_a, const covariance_t& U);\n\n    UncertainTransformation(const Eigen::Vector4d& q_a_b, const Eigen::Vector3d& t_a_b_a,\n                            double diagonalTranslationVariance, double diagonalRotationVariance);\n\n    UncertainTransformation(const Transformation& T, const covariance_t& U);\n\n    UncertainTransformation(const Transformation& T, double diagonalTranslationVariance,\n                            double diagonalRotationVariance);\n\n    /// \\brief Initialize with zero uncertainty\n    UncertainTransformation(const Transformation& T);\n    /// \\brief Initialize with zero uncertainty\n    UncertainTransformation(const Eigen::Matrix4d& T);\n    /// \\brief Initialize with zero uncertainty\n    UncertainTransformation(const Eigen::Vector4d& q_a_b, const Eigen::Vector3d& t_a_b_a);\n\n    virtual ~UncertainTransformation();\n\n    virtual UncertainTransformation operator*(const UncertainTransformation& rhs) const;\n    UncertainTransformation operator*(const Transformation& rhs) const;\n    UncertainHomogeneousPoint operator*(const HomogeneousPoint& rhs) const;\n\n    Eigen::Vector3d operator*(const Eigen::Vector3d& rhs) const { return Transformation::operator*(rhs); }\n    Eigen::Vector4d operator*(const Eigen::Vector4d& rhs) const { return Transformation::operator*(rhs); }\n\n    virtual UncertainHomogeneousPoint operator*(const UncertainHomogeneousPoint& rhs) const;\n\n    Transformation toTransformation() const;\n    UncertainTransformation inverse() const;\n\n    const covariance_t& U() const;\n\n    /// \\brief hhis gets the uncertainty based on the \"oplus\" function for updating the transformation matrix.\n    covariance_t UOplus() const;\n\n    /// \\brief This sets the uncertainty directly.\n    void setU(const covariance_t& U);\n\n    /// \\brief This sets the uncertainty based on the \"oplus\" function for updating the transformation matrix.\n    /// This is a different uncertainty than that carried around by the class, so one should be careful.\n    void setUOplus(const covariance_t& oplusU);\n\n    // Set this to a random transformation.\n    virtual void setRandom();\n\n    virtual void setRandom(double translationMaxMeters, double rotationMaxRadians);\n\n    bool isBinaryEqual(const UncertainTransformation& rhs) const;\n\n    enum { CLASS_SERIALIZATION_VERSION = 0 };\n    BOOST_SERIALIZATION_SPLIT_MEMBER()\n    template <class Archive>\n    void save(Archive& ar, const unsigned int version) const;\n    template <class Archive>\n    void load(Archive& ar, const unsigned int version);\n\n  private:\n    covariance_t _U;\n};\n\ntemplate <class Archive>\nvoid UncertainTransformation::save(Archive& ar, const unsigned int /* version */) const {\n    using ::boost::serialization::make_nvp;\n    ar << BOOST_SERIALIZATION_BASE_OBJECT_NVP(Transformation);\n    ar << make_nvp(\"_U\", _U);  // BOOST_SERIALIZATION_NVP(_U);\n}\n\ntemplate <class Archive>\nvoid UncertainTransformation::load(Archive& ar, const unsigned int version) {\n    SM_ASSERT_LE(std::runtime_error, version, (unsigned int)CLASS_SERIALIZATION_VERSION,\n                 \"Unsupported serialization version\");\n\n    using ::boost::serialization::make_nvp;\n    ar >> BOOST_SERIALIZATION_BASE_OBJECT_NVP(Transformation);\n    ar >> make_nvp(\"_U\", _U);  // BOOST_SERIALIZATION_NVP(_U);\n}\n\n}  // namespace kinematics\n}  // namespace sm\n\nBOOST_CLASS_VERSION(sm::kinematics::UncertainTransformation,\n                    sm::kinematics::UncertainTransformation::CLASS_SERIALIZATION_VERSION);\n\n#endif /* SM_UNCERTAIN_TRANSFORMATION_HPP */\n", "meta": {"hexsha": "a129bfbd6140c715a53d8eefa9b8b7549822ba64", "size": 4351, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Schweizer-Messer/sm_kinematics/include/sm/kinematics/UncertainTransformation.hpp", "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": "Schweizer-Messer/sm_kinematics/include/sm/kinematics/UncertainTransformation.hpp", "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": "Schweizer-Messer/sm_kinematics/include/sm/kinematics/UncertainTransformation.hpp", "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": 38.8482142857, "max_line_length": 113, "alphanum_fraction": 0.742817743, "num_tokens": 941, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191460821871, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.4516670397021968}}
{"text": "#include \"drake/solvers/sos_basis_generator.h\"\n\n#include <vector>\n\n#include <Eigen/Core>\n\n#include \"drake/solvers/integer_inequality_solver.h\"\nnamespace drake {\nnamespace solvers {\nnamespace {\n// Anonymous namespace containing collection of utility functions\nusing Variable = symbolic::Variable;\nusing Monomial = symbolic::Monomial;\nusing Variables = symbolic::Variables;\nusing MonomialVector = VectorX<symbolic::Monomial>;\nusing Exponent = Eigen::RowVectorXi;\nusing ExponentList = Eigen::Matrix<int, -1, -1, Eigen::RowMajor>;\n\n// Given a list of exponents and variables, returns a vector of monomials.\n// Ex: if exponents = [0, 1;1, 2], and vars = [x(0), x(1)], then the vector\n// [x(1); x(0)* x(1)\u00b2] is returned.\nMonomialVector ExponentsToMonomials(const ExponentList& exponents,\n                                    const drake::VectorX<Variable>& vars) {\n  MonomialVector monomials(exponents.rows());\n  for (int i = 0; i < exponents.rows(); i++) {\n    monomials(i) = Monomial(vars, exponents.row(i));\n  }\n  return monomials;\n}\n\n// Returns a list of all exponents that appear in a polynomial p.\n// E.g., given p = 1 + 2x\u2080\u00b2 + 3x\u2080*x\u2081\u00b2, returns [0, 0; 2, 0; 1, 2];\nExponentList GetPolynomialExponents(const drake::symbolic::Polynomial& p) {\n  const Variables& indeterminates{p.indeterminates()};\n  ExponentList exponents(p.monomial_to_coefficient_map().size(),\n                         indeterminates.size());\n  int row = 0;\n  for (const auto& m : p.monomial_to_coefficient_map()) {\n    int col = 0;\n    for (const auto& var : indeterminates) {\n      exponents(row, col++) = m.first.degree(var);\n    }\n    row++;\n  }\n  return exponents;\n}\n\nExponentList VerticalStack(const ExponentList& A, const ExponentList& B) {\n  DRAKE_ASSERT(A.cols() == B.cols());\n  if (A.rows() == 0) {\n    return B;\n  }\n  if (B.rows() == 0) {\n    return A;\n  }\n  ExponentList Y(A.rows() + B.rows(), B.cols());\n  Y << A, B;\n  return Y;\n}\n\nExponentList PairwiseSums(const ExponentList& exponents) {\n  int n = exponents.rows();\n  ExponentList sums((n * n - n) / 2, exponents.cols());\n  int cnt = 0;\n  for (int i = 0; i < n; i++) {\n    // Note: counter starts at i+1 to omit a+b when a = b.\n    for (int j = i + 1; j < n; j++) {\n      sums.row(cnt++) = exponents.row(i) + exponents.row(j);\n    }\n  }\n  return sums;\n}\n\n// Returns true if the first num_rows of A contains B.\nbool ContainsExponent(const ExponentList& A, int num_rows, const Exponent& B) {\n  DRAKE_ASSERT(B.rows() == 1 && B.cols() == A.cols());\n  DRAKE_ASSERT((num_rows >= 0) && (num_rows <= A.rows()));\n  for (int i = 0; i < num_rows; i++) {\n    if (A.row(i) == B) {\n      return true;\n    }\n  }\n  return false;\n}\n\n/* Intersection(A, B) removes duplicate rows from B and any row that doesn't\n * also appear in A.  For example, given A = [1, 0; 0, 1; 1, 1] and B = [1, 0;\n * 1, 1; 1, 1;], it overwrites B with [1, 0; 1, 1]. */\nvoid Intersection(const ExponentList& A, ExponentList* B) {\n  DRAKE_ASSERT(A.cols() == B->cols());\n  int index = 0;\n  for (int i = 0; i < B->rows(); i++) {\n    if ((ContainsExponent(A, A.rows(), B->row(i))) &&\n        !(ContainsExponent(*B, index, B->row(i)))) {\n      B->row(index++) = B->row(i);\n    }\n  }\n  B->conservativeResize(index, Eigen::NoChange);\n}\n\n/* Removes exponents of the monomials that aren't diagonally-consistent with\n * respect to the polynomial p and the given monomial basis.  A monomial is\n * diagonally-consistent if its square appears in p, or its square equals a\n * product of monomials in the basis; see, e.g., \"Pre- and Post-Processing\n * Sum-of-Squares Programs in Practice Johan L\u00f6fberg, IEEE Transactions on\n * Automatic Control, 2009.\" After execution, all exponents of inconsistent\n * monomials are removed from exponents_of_basis.\n*/\nvoid RemoveDiagonallyInconsistentExponents(const ExponentList& exponents_of_p,\n                                           ExponentList* exponents_of_basis) {\n  while (1) {\n    int num_exponents = exponents_of_basis->rows();\n\n    ExponentList valid_squares =\n        VerticalStack(PairwiseSums(*exponents_of_basis), exponents_of_p);\n\n    (*exponents_of_basis) = (*exponents_of_basis) * 2;\n    Intersection(valid_squares, exponents_of_basis);\n    (*exponents_of_basis) = (*exponents_of_basis) / 2;\n\n    if (exponents_of_basis->rows() == num_exponents) {\n      break;\n    }\n  }\n  return;\n}\n\nstruct Hyperplanes {\n  Eigen::MatrixXi normal_vectors;  // Each row contains a normal vector.\n  Eigen::VectorXi max_dot_product;\n  Eigen::VectorXi min_dot_product;\n};\n\n// Finding random supporting hyperplanes of 1/2 P, where P is the Newton\n// polytope of the polynomial p (i.e., the convex hull of its exponents).\nHyperplanes RandomSupportingHyperplanes(const ExponentList& exponents_of_p,\n                                        unsigned int seed) {\n  Hyperplanes H;\n\n  // get_random() samples uniformly between normal_vector_component_min/max.\n  // Current values of min and max set heuristically.\n  const int normal_vector_component_min = -10;\n  const int normal_vector_component_max = 10;\n  std::default_random_engine generator(seed);\n  std::uniform_int_distribution<int> distribution(normal_vector_component_min,\n                                                  normal_vector_component_max);\n  auto get_random = [&]() { return distribution(generator); };\n\n  // Number of hyperplanes currently picked heuristically.\n  int num_hyperplanes = 10 * exponents_of_p.cols();\n\n  H.normal_vectors = Eigen::MatrixXi(num_hyperplanes, exponents_of_p.cols());\n  for (int i = 0; i < H.normal_vectors.cols(); i++) {\n    H.normal_vectors.col(i)\n        << Eigen::VectorXi::NullaryExpr(num_hyperplanes, get_random);\n  }\n\n  Eigen::MatrixXi dot_products = H.normal_vectors * exponents_of_p.transpose();\n  H.max_dot_product = dot_products.rowwise().maxCoeff() / 2;\n  H.min_dot_product = dot_products.rowwise().minCoeff() / 2;\n\n  return H;\n}\n\n//  Generates the supporting hyperplanes of the Newton polytope that\n//  are induced by the total degree ordering.\nHyperplanes DegreeInducedHyperplanes(const ExponentList& exponents_of_p) {\n  Hyperplanes H;\n\n  // The hyperplane for total degree.\n  H.normal_vectors.resize(1, exponents_of_p.cols());\n  H.normal_vectors.setConstant(1);\n\n  Eigen::MatrixXi dot_products = H.normal_vectors * exponents_of_p.transpose();\n  H.max_dot_product = dot_products.rowwise().maxCoeff() / 2;\n  H.min_dot_product = dot_products.rowwise().minCoeff() / 2;\n\n  return H;\n}\n\nExponentList EnumerateInitialSet(const ExponentList& exponents_of_p) {\n  Eigen::VectorXi lower_bounds = exponents_of_p.colwise().minCoeff() / 2;\n  Eigen::VectorXi upper_bounds = exponents_of_p.colwise().maxCoeff() / 2;\n  Hyperplanes hyperplanes = DegreeInducedHyperplanes(exponents_of_p);\n\n  // We check the inequalities in two batches to allow for internal\n  // infeasibility propagation inside of EnumerateIntegerSolutions,\n  // which is done only if A has a column that is elementwise nonnegative\n  // or nonpositive. (This condition never holds if we check the\n  // inequalities in one batch, since A = [normal_vectors;-normal_vectors].)\n  ExponentList basis_exponents_1 = drake::solvers::EnumerateIntegerSolutions(\n      hyperplanes.normal_vectors, hyperplanes.max_dot_product, lower_bounds,\n      upper_bounds);\n\n  ExponentList basis_exponents = drake::solvers::EnumerateIntegerSolutions(\n      -hyperplanes.normal_vectors, -hyperplanes.min_dot_product, lower_bounds,\n      upper_bounds);\n\n  Intersection(basis_exponents_1, &basis_exponents);\n  return basis_exponents;\n}\n\n//  This function removes an element alpha from \"basis\" if a randomly generated\n//  hyperplane separates 2*alpha from the Newton polytope of the polynomial p.\n//  Note that this function is actually deterministic since the seed for\n//  the random number generator is set to predetermined constants.\nvoid RemoveWithRandomSeparatingHyperplanes(const ExponentList& exponents_of_p,\n                                           ExponentList* basis) {\n  // Declare this outside the main loop to avoid repeated dynamic memory\n  // allocation.\n  Eigen::MatrixXi dot_products;\n  int random_seed = 0;\n\n  while (1) {\n    int next_basis_size = 0;\n    int current_basis_size = basis->rows();\n\n    auto H = RandomSupportingHyperplanes(exponents_of_p, random_seed++);\n\n    // Remove monomials that the hyperplanes separate from the\n    // Newton polytope.\n    dot_products = (*basis) * H.normal_vectors.transpose();\n    for (int i = 0; i < current_basis_size; i++) {\n      bool keep_monomial = true;\n      for (int j = 0; j < dot_products.cols(); j++) {\n        if (dot_products(i, j) > H.max_dot_product(j) ||\n            dot_products(i, j) < H.min_dot_product(j)) {\n          keep_monomial = false;\n          break;\n        }\n      }\n\n      if (keep_monomial) {\n        basis->row(next_basis_size++) = basis->row(i);\n      }\n    }\n\n    basis->conservativeResize(next_basis_size, basis->cols());\n\n    // Quit if the basis is now empty or if its size wasn't reduced\n    // enough.\n    constexpr double kMinimumPercentReduction = .1;\n    if (next_basis_size >\n            current_basis_size * (1.0 - kMinimumPercentReduction) ||\n        next_basis_size == 0) {\n      break;\n    }\n  }\n  return;\n}\n\nExponentList ConstructMonomialBasis(const ExponentList& exponents_of_p) {\n  auto basis_exponents = EnumerateInitialSet(exponents_of_p);\n  RemoveWithRandomSeparatingHyperplanes(exponents_of_p, &basis_exponents);\n  RemoveDiagonallyInconsistentExponents(exponents_of_p, &basis_exponents);\n  return basis_exponents;\n}\n\n}  // namespace\n\nMonomialVector ConstructMonomialBasis(const drake::symbolic::Polynomial& p) {\n  const Variables& indeterminates{p.indeterminates()};\n  drake::VectorX<Variable> vars(indeterminates.size());\n  int cnt = 0;\n  for (auto& var : indeterminates) {\n    vars(cnt++) = var;\n  }\n\n  auto polynomial_exponents = GetPolynomialExponents(p);\n  auto basis_exponents = ConstructMonomialBasis(polynomial_exponents);\n  auto monomial_basis = ExponentsToMonomials(basis_exponents, vars);\n  return monomial_basis;\n}\n}  // namespace solvers\n}  // namespace drake\n", "meta": {"hexsha": "52714d10814f7edb61dfd1b071c01b17100fe29b", "size": 10024, "ext": "cc", "lang": "C++", "max_stars_repo_path": "solvers/sos_basis_generator.cc", "max_stars_repo_name": "RobotLocomotion/drake-python3.7", "max_stars_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-02-25T02:01:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-17T04:52:04.000Z", "max_issues_repo_path": "solvers/sos_basis_generator.cc", "max_issues_repo_name": "RobotLocomotion/drake-python3.7", "max_issues_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "solvers/sos_basis_generator.cc", "max_forks_repo_name": "RobotLocomotion/drake-python3.7", "max_forks_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-13T12:05:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-13T12:05:39.000Z", "avg_line_length": 36.3188405797, "max_line_length": 79, "alphanum_fraction": 0.6907422187, "num_tokens": 2671, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191460821871, "lm_q2_score": 0.6370308013713525, "lm_q1q2_score": 0.45166703481636766}}
{"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\n#define BOOST_TEST_MAIN\n\n#include <limits>\n\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/unit_test.hpp>\n#include <boost/date_time/gregorian/gregorian.hpp>\n\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/physicalConstants.h\"\n\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/timeConversions.h\"\n\nnamespace tudat\n{\nnamespace unit_tests\n{\n\nusing namespace basic_astrodynamics;\nusing namespace physical_constants;\n\n//! Test the functionality of the time conversion functions.\nBOOST_AUTO_TEST_SUITE( test_Time_Conversions )\n\n//! Unit test for Julian day to seconds conversion function.\nBOOST_AUTO_TEST_CASE( testJulianDayToSecondsConversions )\n{\n    // Test conversion from Julian day to seconds since epoch at 0 MJD.\n    {\n        // Set reference epoch and Julian day for tests.\n        const double referenceEpoch = JULIAN_DAY_AT_0_MJD;\n        const double julianDay = JULIAN_DAY_AT_0_MJD + 1.0e6 / 86400.0;\n\n        // Set expected seconds since epoch result.\n        const double expectedSecondsSinceEpoch = 1.0e6;\n\n        // Compute seconds since epoch given Julian day and reference epoch.\n        const double computedSecondsSinceEpoch = convertJulianDayToSecondsSinceEpoch(\n                    julianDay, referenceEpoch );\n\n        // Test that computed result matches expected result.\n        // Test is run at reduced tolerance, because the final digits of the seconds were lost\n        // when converting to Julian day.\n        BOOST_CHECK_CLOSE_FRACTION( computedSecondsSinceEpoch, expectedSecondsSinceEpoch,\n                                    1.0e-11 );\n    }\n\n    // Test conversion from Julian day to seconds since J2000 epoch.\n    {\n        // Set reference epoch and Julian day for tests.\n        const double referenceEpoch = JULIAN_DAY_ON_J2000;\n        const double julianDay = JULIAN_DAY_ON_J2000 + 0.5;\n\n        // Set expected seconds since epoch result.\n        double expectedSecondsSinceEpoch\n                = physical_constants::JULIAN_DAY / 2.0;\n\n        // Compute seconds since epoch given Julian day and reference epoch.\n        const double computedSecondsSinceEpoch = convertJulianDayToSecondsSinceEpoch(\n                    julianDay, referenceEpoch );\n\n        // Test that computed result matches expected result.\n        // Test is run at reduced tolerance, because the final digits of the seconds were lost\n        // when converting to Julian day.\n        BOOST_CHECK_CLOSE_FRACTION( computedSecondsSinceEpoch, expectedSecondsSinceEpoch,\n                                    std::numeric_limits< double >::epsilon( ) );\n    }\n\n    // Test conversion from Julian day to seconds since epoch at 0 MJD with long doubles.\n    {\n        // Set reference epoch and Julian day for tests.\n        const long double referenceEpoch = JULIAN_DAY_AT_0_MJD_LONG;\n        const long double julianDay = JULIAN_DAY_AT_0_MJD_LONG + 1.0e6L / 86400.0L;\n\n        // Set expected seconds since epoch result.\n        const long double expectedSecondsSinceEpoch = 1.0e6L;\n\n        // Compute seconds since epoch given Julian day and reference epoch.\n        const long double computedSecondsSinceEpoch = convertJulianDayToSecondsSinceEpoch< long double >(\n                    julianDay, referenceEpoch );\n\n        // Test that computed result matches expected result.\n        // Test is run at reduced tolerance, because the final digits of the seconds were lost\n        // when converting to Julian day.\n        BOOST_CHECK_CLOSE_FRACTION( computedSecondsSinceEpoch, expectedSecondsSinceEpoch,\n                                    1.0e-14 );\n    }\n\n    // Test conversion from Julian day to seconds since J2000 epoch  with long doubles\n    {\n        // Set reference epoch and Julian day for tests.\n        const long double referenceEpoch = JULIAN_DAY_ON_J2000_LONG;\n        const long double julianDay = JULIAN_DAY_ON_J2000_LONG + 0.5L;\n\n        // Set expected seconds since epoch result.\n        long double expectedSecondsSinceEpoch\n                = physical_constants::JULIAN_DAY_LONG / 2.0L;\n\n        // Compute seconds since epoch given Julian day and reference epoch.\n        const long double computedSecondsSinceEpoch = convertJulianDayToSecondsSinceEpoch< long double >(\n                    julianDay, referenceEpoch );\n\n        // Test that computed result matches expected result.\n        // Test is run at reduced tolerance, because the final digits of the seconds were lost\n        // when converting to Julian day.\n        BOOST_CHECK_CLOSE_FRACTION( computedSecondsSinceEpoch, expectedSecondsSinceEpoch,\n                                    std::numeric_limits< long double >::epsilon( ) );\n    }\n}\n\n//! Unit test for seconds to Julian day conversion function.\nBOOST_AUTO_TEST_CASE( testSecondsSinceEpochToJulianDayConversions )\n{\n    {\n        // Test conversion from seconds since epoch to Julian day.\n\n        // Set reference epoch and seconds since epoch for tests.\n        const double referenceEpoch = JULIAN_DAY_AT_0_MJD;\n        const double secondsSinceEpoch = 1.0e6;\n\n        // Set expected Julian day result.\n        const double expectedJulianDay = JULIAN_DAY_AT_0_MJD + 1.0e6 / 86400.0;\n\n        // Compute Julian day with seconds since reference epoch specified.\n        const double computedJulianDay = convertSecondsSinceEpochToJulianDay(\n                    secondsSinceEpoch, referenceEpoch );\n\n        // Test that computed result matches expected result.\n        BOOST_CHECK_CLOSE_FRACTION( computedJulianDay, expectedJulianDay,\n                                    std::numeric_limits< double >::epsilon( ) );\n    }\n\n    {\n        // Test conversion from seconds since epoch to Julian day with long doubles.\n\n        // Set reference epoch and seconds since epoch for tests.\n        const long double referenceEpoch = JULIAN_DAY_AT_0_MJD_LONG;\n        const long double secondsSinceEpoch = 1.0e6L;\n\n        // Set expected Julian day result.\n        const long double expectedJulianDay = JULIAN_DAY_AT_0_MJD_LONG + 1.0e6L / 86400.0L;\n\n        // Compute Julian day with seconds since reference epoch specified.\n        const long double computedJulianDay = convertSecondsSinceEpochToJulianDay< long double >(\n                    secondsSinceEpoch, referenceEpoch );\n\n        // Test that computed result matches expected result.\n        BOOST_CHECK_CLOSE_FRACTION( computedJulianDay, expectedJulianDay,\n                                    std::numeric_limits< long double >::epsilon( ) );\n    }\n}\n\n\n//! Unit test for calendar date to Julian day conversion function.\nBOOST_AUTO_TEST_CASE( testConversionCalendarDateToJulianDay )\n{\n    // Compute the Julian day of the calendar date: January 1st, 2000, at 12h0m0s.\n    {\n        //Use the function to compute the Julian day.\n        const double computedJulianDay = convertCalendarDateToJulianDay ( 2000, 1, 1, 12, 0, 0 );\n\n        //Known Julian day at this calendar date.\n        const double expectedJulianDay = basic_astrodynamics::JULIAN_DAY_ON_J2000;\n\n        // Test that computed result matches expected result.\n        BOOST_CHECK_CLOSE_FRACTION( computedJulianDay, expectedJulianDay,\n                                    std::numeric_limits< double >::epsilon( ) );\n    }\n\n    //Compute the Julian day of the calendar date: November 17th, 1858, At 0h0m0s.\n    {\n\n        //Use the function to compute the Julian day.\n        const double computedJulianDay = convertCalendarDateToJulianDay(\n                    1858, 11, 17, 0, 0, 0.0 );\n\n        //Known Julian day at this calendar date\n        const double expectedJulianDay = basic_astrodynamics::JULIAN_DAY_AT_0_MJD;\n\n        // Test that computed result matches expected result.\n        BOOST_CHECK_CLOSE_FRACTION( computedJulianDay, expectedJulianDay,\n                                    std::numeric_limits< double >::epsilon( ) );\n\n    }\n\n    //Test conversion wrapper against boost result.\n    {\n        const int year = 1749;\n        const int month = 3;\n        const int day = 30;\n\n        BOOST_CHECK_CLOSE_FRACTION( boost::gregorian::date( year, month, day ).julian_day( ) - 0.5,\n                                    convertCalendarDateToJulianDay( year, month, day, 0, 0, 0.0 ),\n                                    std::numeric_limits< double >::epsilon( ) );\n        const int hour = 4;\n        BOOST_CHECK_CLOSE_FRACTION( boost::gregorian::date( year, month, day ).julian_day( ) - 0.5 +\n                                    static_cast< double >( hour ) / 24.0,\n                                    convertCalendarDateToJulianDay( year, month, day, hour, 0, 0.0 ),\n                                    std::numeric_limits< double >::epsilon( ) );\n\n        const int minute = 36;\n        BOOST_CHECK_CLOSE_FRACTION( boost::gregorian::date( year, month, day ).julian_day( ) - 0.5 +\n                                    static_cast< double >( hour ) / 24.0 + static_cast< double >( minute ) / ( 24.0 * 60.0 ),\n                                    convertCalendarDateToJulianDay( year, month, day, hour, minute, 0.0 ),\n                                    std::numeric_limits< double >::epsilon( ) );\n\n        const double second = 21.36474854836359;\n        BOOST_CHECK_CLOSE_FRACTION( boost::gregorian::date( year, month, day ).julian_day( ) - 0.5 +\n                                    static_cast< double >( hour ) / 24.0 +\n                                    static_cast< double >( minute ) / ( 24.0 * 60.0 ) +\n                                    second / ( 24.0 * 60.0 * 60.0 ),\n                                    convertCalendarDateToJulianDay( year, month, day, hour, minute, second ),\n                                    std::numeric_limits< double >::epsilon( ) );\n\n    }\n}\n\nBOOST_AUTO_TEST_CASE( testTimeConversions )\n{\n    const double testModifiedJulianDay = 54583.87;\n    const double testJulianDay = testModifiedJulianDay + JULIAN_DAY_AT_0_MJD;\n    {\n        // Test conversions to/from Modified Julian day\n\n        BOOST_CHECK_CLOSE_FRACTION( testJulianDay, convertModifiedJulianDayToJulianDay( testModifiedJulianDay ),\n                                    2.0 * std::numeric_limits< double >::epsilon( ) );\n        BOOST_CHECK_CLOSE_FRACTION( testModifiedJulianDay, convertJulianDayToModifiedJulianDay( testJulianDay ),\n                                    10.0 * std::numeric_limits< double >::epsilon( ) );\n        BOOST_CHECK_CLOSE_FRACTION( convertJulianDayToModifiedJulianDay(\n                                        convertModifiedJulianDayToJulianDay( testModifiedJulianDay ) ),\n                                    testModifiedJulianDay, 10.0 * std::numeric_limits< double >::epsilon( ) );\n        BOOST_CHECK_CLOSE_FRACTION( convertModifiedJulianDayToJulianDay(\n                                        convertJulianDayToModifiedJulianDay( testJulianDay ) ),\n                                    testJulianDay, 2.0 * std::numeric_limits< double >::epsilon( ) );\n\n        // Test conversions to/from seconds since epoch\n        double secondsSinceModifedJulianDayZero = testModifiedJulianDay * JULIAN_DAY;\n        BOOST_CHECK_CLOSE_FRACTION( secondsSinceModifedJulianDayZero, convertJulianDayToSecondsSinceEpoch(\n                                        testJulianDay, JULIAN_DAY_AT_0_MJD ),\n                                    10.0 * std::numeric_limits< double >::epsilon( ) );\n        BOOST_CHECK_CLOSE_FRACTION( testJulianDay, convertSecondsSinceEpochToJulianDay(\n                                        secondsSinceModifedJulianDayZero, JULIAN_DAY_AT_0_MJD ),\n                                    2.0 * std::numeric_limits< double >::epsilon( ) );\n        BOOST_CHECK_CLOSE_FRACTION( testModifiedJulianDay /  JULIAN_YEAR_IN_DAYS,\n                                    convertSecondsSinceEpochToJulianYearsSinceEpoch( secondsSinceModifedJulianDayZero ),\n                                    2.0 * std::numeric_limits< double >::epsilon( ) );\n        BOOST_CHECK_CLOSE_FRACTION( testModifiedJulianDay / (  JULIAN_YEAR_IN_DAYS * 100.0 ),\n                                    convertSecondsSinceEpochToJulianCenturiesSinceEpoch( secondsSinceModifedJulianDayZero ),\n                                    2.0 * std::numeric_limits< double >::epsilon( ) );\n    }\n\n    {\n        // Test conversion from Julian day to calendar date\n        int testYear = 2008;\n        int testMonth = 4;\n        int testDay = 27;\n        boost::gregorian::date testCalendarDate( testYear, testMonth, testDay );\n        double testFractionOfDay = 0.37;\n\n        // Check direct conversion from julian day to calendar date\n        boost::gregorian::date calendarDate = convertJulianDayToCalendarDate( testJulianDay );\n        BOOST_CHECK_EQUAL( testYear, calendarDate.year( ) );\n        BOOST_CHECK_EQUAL( testMonth, calendarDate.month( ) );\n        BOOST_CHECK_EQUAL( testDay, calendarDate.day( ) );\n\n        // Check indirect conversion from julian day to calendar date\n        BOOST_CHECK_EQUAL( getDaysInMonth( 1, testYear ) +\n                           getDaysInMonth( 2, testYear ) +\n                           getDaysInMonth( 3, testYear ) +\n                           testDay, testCalendarDate.day_of_year( ) );\n\n        calendarDate = convertYearAndDaysInYearToDate(\n                    testYear, ( getDaysInMonth( 1, testYear ) +\n                                getDaysInMonth( 2, testYear ) +\n                                getDaysInMonth( 3, testYear ) +\n                                testDay ) - 1 ); // Subtract 1 to go to day 0 for first day of year.\n        BOOST_CHECK_EQUAL( testYear, calendarDate.year( ) );\n        BOOST_CHECK_EQUAL( testMonth, calendarDate.month( ) );\n        BOOST_CHECK_EQUAL( testDay, calendarDate.day( ) );\n\n        // Check if noon reference of Julian day is handled properly\n        calendarDate = convertJulianDayToCalendarDate( testJulianDay + 0.5 );\n        BOOST_CHECK_EQUAL( testYear, calendarDate.year( ) );\n        BOOST_CHECK_EQUAL( testMonth, calendarDate.month( ) );\n        BOOST_CHECK_EQUAL( testDay + 1, calendarDate.day( ) );\n\n        BOOST_CHECK_CLOSE_FRACTION( calculateJulianDaySinceEpoch(\n                                        testCalendarDate, 0.5 + testFractionOfDay, JULIAN_DAY_AT_0_MJD ),\n                                    testModifiedJulianDay,\n                                    50.0 * std::numeric_limits< double >::epsilon( ) );\n    }\n\n    // Test relativistic time scale conversions (TCG, TT, TDB, TCB) for double precision.\n    {\n        double secondsSinceJ2000Synchronization = getTimeOfTaiSynchronizationSinceJ2000< double >( );\n\n        // Test whether TCG and TT are both 0 at synchronization time.\n        double testTcg = convertTtToTcg( secondsSinceJ2000Synchronization );\n        double testTt = convertTcgToTt( secondsSinceJ2000Synchronization );\n\n        BOOST_CHECK_CLOSE_FRACTION( testTcg, secondsSinceJ2000Synchronization,\n                                    2.0 * std::numeric_limits< double >::epsilon( ) );\n        BOOST_CHECK_CLOSE_FRACTION( testTt, secondsSinceJ2000Synchronization,\n                                    2.0 * std::numeric_limits< double >::epsilon( ) );\n\n        // Test whether TDB and TCB are both at defined relative offset at given time.\n        double testTcb = convertTdbToTcb( secondsSinceJ2000Synchronization );\n        double testTdb = convertTcbToTdb( secondsSinceJ2000Synchronization );\n\n        BOOST_CHECK_CLOSE_FRACTION( testTdb, secondsSinceJ2000Synchronization + TDB_SECONDS_OFFSET_AT_SYNCHRONIZATION,\n                                    2.0 * std::numeric_limits< double >::epsilon( ) );\n        BOOST_CHECK_CLOSE_FRACTION( testTcb, secondsSinceJ2000Synchronization - TDB_SECONDS_OFFSET_AT_SYNCHRONIZATION,\n                                    2.0 * std::numeric_limits< double >::epsilon( ) );\n\n        // Test back and forth TCG<->TT, and expected value of TCG at TT=0..\n        double testTime = 0.0;\n\n        testTcg = convertTtToTcg( testTime);\n        testTt = convertTcgToTt( testTcg );\n\n        double expectedTcg = -secondsSinceJ2000Synchronization * LG_TIME_RATE_TERM /\n                ( 1.0 - physical_constants::LG_TIME_RATE_TERM_LONG );\n        BOOST_CHECK_CLOSE_FRACTION( testTcg, expectedTcg, 2.0 * std::numeric_limits< double >::epsilon( ) );\n        BOOST_CHECK_SMALL( testTt, std::numeric_limits< double >::epsilon( ) );\n\n        // Test back and forth TDB<->TCB, and expected value of TDB at TCB=0.\n        testTdb = convertTcbToTdb( testTime );\n        testTcb = convertTdbToTcb( testTdb );\n\n        double expectedTdb = secondsSinceJ2000Synchronization * LB_TIME_RATE_TERM + TDB_SECONDS_OFFSET_AT_SYNCHRONIZATION;\n\n        BOOST_CHECK_CLOSE_FRACTION( testTdb, expectedTdb, 2.0 * std::numeric_limits< double >::epsilon( ) );\n        BOOST_CHECK_SMALL( testTcb, 2.0 * std::numeric_limits< double >::epsilon( ) );\n\n        // Test back and forth TCG<->TT.\n        double secondsSinceModifedJulianDayZero = testModifiedJulianDay * JULIAN_DAY;\n        testTime = secondsSinceModifedJulianDayZero;\n\n        testTcg = convertTtToTcg< double >( testTime );\n        testTt = convertTcgToTt< double >( testTcg );\n\n        BOOST_CHECK_CLOSE_FRACTION( testTt, testTime, 2.0 * std::numeric_limits< double >::epsilon( ) );\n\n        // Test back and forth TDB<->TCB.\n        testTdb = convertTcbToTdb< long double >( testTime );\n        testTcb = convertTdbToTcb< long double >( testTdb );\n\n        BOOST_CHECK_CLOSE_FRACTION( testTcb, testTime, 2.0 * std::numeric_limits< double >::epsilon( ) );\n\n        secondsSinceModifedJulianDayZero = 1.0E12;\n\n        // Test rate difference between TCG and TT\n        double testTt1 = 0.0;\n        double testTt2 = secondsSinceModifedJulianDayZero;\n        double testTcg1 = convertTtToTcg< double >( testTt1 );\n        double testTcg2 = convertTtToTcg< double >( testTt2 );\n        double computedLg = 1.0 - ( testTt2 - testTt1 ) / ( testTcg2 - testTcg1 );\n        BOOST_CHECK_SMALL( computedLg - physical_constants::LG_TIME_RATE_TERM,\n                                    std::numeric_limits< double >::epsilon( ) );\n\n        testTcg1 = 0.0;\n        testTcg2 = secondsSinceModifedJulianDayZero;\n        testTt1 = convertTcgToTt< double >( testTcg1 );\n        testTt2 = convertTcgToTt< double >( testTcg2 );\n        computedLg = 1.0 - ( testTt2 - testTt1 ) / ( testTcg2 - testTcg1 );\n        BOOST_CHECK_SMALL( computedLg - physical_constants::LG_TIME_RATE_TERM,\n                                    std::numeric_limits< double >::epsilon( ) );\n\n\n        // Test rate difference between TDB and TCB\n        double testTcb1 = 0.0;\n        double testTcb2 = secondsSinceModifedJulianDayZero;\n        double testTdb1 = convertTcbToTdb< double >( testTcb1 );\n        double testTdb2 = convertTcbToTdb< double >( testTcb2 );\n        double computedLb = 1.0 - ( testTdb2 - testTdb1 ) / ( testTcb2 - testTcb1 );\n        BOOST_CHECK_SMALL( computedLb - physical_constants::LB_TIME_RATE_TERM,\n                                    std::numeric_limits< double >::epsilon( ) );\n\n        testTdb1 = 0.0;\n        testTdb2 = secondsSinceModifedJulianDayZero;\n        testTcb1 = convertTdbToTcb< double >( 0.0 );\n        testTcb2 = convertTdbToTcb< double >( secondsSinceModifedJulianDayZero );\n        computedLb = 1.0 - ( testTdb2 - testTdb1 ) / ( testTcb2 - testTcb1 );\n        BOOST_CHECK_SMALL( computedLb - physical_constants::LB_TIME_RATE_TERM,\n                                    std::numeric_limits< double >::epsilon( ) );\n    }\n\n    // Compare TT/TCG conversions against Sofa cookbook (only limited precision).\n    {\n        double expectedTT = physical_constants::JULIAN_DAY *\n                convertCalendarDateToJulianDaysSinceEpoch( 2006, 1, 15, 12, 25, 42.68400, JULIAN_DAY_ON_J2000 );\n        double expectedTCG = physical_constants::JULIAN_DAY *\n                convertCalendarDateToJulianDaysSinceEpoch( 2006, 1, 15, 12, 25, 43.32269, JULIAN_DAY_ON_J2000 );\n\n        double calculatedTT = convertTcgToTt( expectedTCG );\n        double calculatedTCG = convertTtToTcg( expectedTT );\n\n        BOOST_CHECK_SMALL( calculatedTCG - expectedTCG, 5.0E-5 );\n        BOOST_CHECK_SMALL( calculatedTT - expectedTT, 5.0E-5 );\n\n    }\n}\n\n// Test relativistic time scale conversions (TCG, TT, TDB, TCB) for long double precision.\nBOOST_AUTO_TEST_CASE( testTimeConversionsLong )\n{\n    // Define test dates (arbitrary).\n    const long double testModifiedJulianDay = static_cast< long double >( 54583.87 );\n    const long double testJulianDay = testModifiedJulianDay + JULIAN_DAY_AT_0_MJD_LONG;\n\n    // Test whether back and forth conversion between JD and MJD provides correct resulats.\n    BOOST_CHECK_CLOSE_FRACTION( testJulianDay, convertModifiedJulianDayToJulianDay< long double >( testModifiedJulianDay ),\n                                2.0 * std::numeric_limits< long double >::epsilon( ));\n    BOOST_CHECK_CLOSE_FRACTION( testModifiedJulianDay, convertJulianDayToModifiedJulianDay< long double >( testJulianDay ),\n                                2.0 * std::numeric_limits< long double >::epsilon( ) );\n    BOOST_CHECK_CLOSE_FRACTION( convertJulianDayToModifiedJulianDay< long double >(\n                                    convertModifiedJulianDayToJulianDay< long double >( testModifiedJulianDay ) ),\n                                testModifiedJulianDay, 2.0 * std::numeric_limits< long double >::epsilon( ) );\n    BOOST_CHECK_CLOSE_FRACTION( convertModifiedJulianDayToJulianDay(\n                                    convertJulianDayToModifiedJulianDay( testJulianDay ) ),\n                                testJulianDay, 2.0 * std::numeric_limits< long double >::epsilon( ) );\n\n    // Test conversion to seconds since Epoch for JD and MJD\n    long double secondsSinceModifedJulianDayZero = testModifiedJulianDay * JULIAN_DAY_LONG;\n\n    BOOST_CHECK_CLOSE_FRACTION( secondsSinceModifedJulianDayZero, convertJulianDayToSecondsSinceEpoch< long double >(\n                                    testJulianDay, JULIAN_DAY_AT_0_MJD_LONG ),\n                                2.0 * std::numeric_limits< long double >::epsilon( ) );\n    BOOST_CHECK_CLOSE_FRACTION( testJulianDay, convertSecondsSinceEpochToJulianDay< long double >(\n                                    secondsSinceModifedJulianDayZero, JULIAN_DAY_AT_0_MJD_LONG ),\n                                2.0 * std::numeric_limits< long double >::epsilon( ) );\n\n    // Test whether TCG and TT are both 0 at synchronization time.\n    long double secondsSinceJ2000Synchronization = getTimeOfTaiSynchronizationSinceJ2000< long double >( );\n\n    long double testTcg = convertTtToTcg< long double >( secondsSinceJ2000Synchronization );\n    long double testTt = convertTcgToTt< long double >( secondsSinceJ2000Synchronization );\n\n    BOOST_CHECK_CLOSE_FRACTION( testTcg, secondsSinceJ2000Synchronization,\n                                2.0 * std::numeric_limits< long double >::epsilon( ) );\n    BOOST_CHECK_CLOSE_FRACTION( testTt, secondsSinceJ2000Synchronization,\n                                2.0 * std::numeric_limits< long double >::epsilon( ) );\n\n    // Test whether TDB and TCB are both at defined relative offset at given time.\n    long double testTcb = convertTdbToTcb< long double >( secondsSinceJ2000Synchronization );\n    long double testTdb = convertTcbToTdb< long double >( secondsSinceJ2000Synchronization );\n\n    BOOST_CHECK_CLOSE_FRACTION( testTdb, secondsSinceJ2000Synchronization + TDB_SECONDS_OFFSET_AT_SYNCHRONIZATION,\n                                2.0 * std::numeric_limits< long double >::epsilon( ) );\n    BOOST_CHECK_CLOSE_FRACTION( testTcb, secondsSinceJ2000Synchronization - TDB_SECONDS_OFFSET_AT_SYNCHRONIZATION,\n                                2.0 * std::numeric_limits< long double >::epsilon( ) );\n\n    // Test back and forth TCG<->TT at t=0, and expected value of TCG at TT=0..\n    long double testTime = 0.0L;\n\n    testTcg = convertTtToTcg< long double >( testTime);\n    testTt = convertTcgToTt< long double >( testTcg );\n\n    long double expectedTcg = -secondsSinceJ2000Synchronization * LG_TIME_RATE_TERM_LONG /\n            ( 1.0L - LG_TIME_RATE_TERM_LONG);\n    BOOST_CHECK_CLOSE_FRACTION( testTcg, expectedTcg, 2.0 * std::numeric_limits< long double >::epsilon( ) );\n    BOOST_CHECK_CLOSE_FRACTION( testTt, testTime, 2.0 * std::numeric_limits< long double >::epsilon( ) );\n\n    // Test back and forth TDB<->TCB at t=0, and expected value of TDB at TCB=0.\n    testTdb = convertTcbToTdb< long double >( testTime );\n    testTcb = convertTdbToTcb< long double >( testTdb );\n\n    long double expectedTdb = secondsSinceJ2000Synchronization * LB_TIME_RATE_TERM_LONG +\n            TDB_SECONDS_OFFSET_AT_SYNCHRONIZATION_LONG;\n\n    BOOST_CHECK_CLOSE_FRACTION( testTdb, expectedTdb, 2.0 * std::numeric_limits< long double >::epsilon( ) );\n    BOOST_CHECK_SMALL( testTcb, 2.0 * std::numeric_limits< long double >::epsilon( ) );\n\n    // Test back and forth TCG<->TT.\n    testTime = secondsSinceModifedJulianDayZero;\n\n    testTcg = convertTtToTcg< long double >( testTime );\n    testTt = convertTcgToTt< long double >( testTcg );\n\n    BOOST_CHECK_CLOSE_FRACTION( testTt, testTime, 2.0 * std::numeric_limits< long double >::epsilon( ) );\n\n    // Test back and forth TDB<->TCB.\n    testTdb = convertTcbToTdb< long double >( testTime );\n    testTcb = convertTdbToTcb< long double >( testTdb );\n\n    BOOST_CHECK_CLOSE_FRACTION( testTcb, testTime, 2.0 * std::numeric_limits< long double >::epsilon( ) );\n\n    secondsSinceModifedJulianDayZero = 1.0E12;\n\n    // Test rate difference between TCG and TT\n    long double testTt1 = 0.0;\n    long double testTt2 = secondsSinceModifedJulianDayZero;\n    long double testTcg1 = convertTtToTcg< long double >( testTt1 );\n    long double testTcg2 = convertTtToTcg< long double >( testTt2 );\n    long double computedLg = 1.0L - ( testTt2 - testTt1 ) / ( testTcg2 - testTcg1 );\n    BOOST_CHECK_SMALL( computedLg - physical_constants::LG_TIME_RATE_TERM_LONG,\n                                std::numeric_limits< long double >::epsilon( ) );\n\n    testTcg1 = 0.0;\n    testTcg2 = secondsSinceModifedJulianDayZero;\n    testTt1 = convertTcgToTt< long double >( testTcg1 );\n    testTt2 = convertTcgToTt< long double >( testTcg2 );\n    computedLg = 1.0L - ( testTt2 - testTt1 ) / ( testTcg2 - testTcg1 );\n    BOOST_CHECK_SMALL( computedLg - physical_constants::LG_TIME_RATE_TERM_LONG,\n                                std::numeric_limits< long double >::epsilon( ) );\n\n\n    // Test rate difference between TDB and TCB\n    long double testTcb1 = 0.0L;\n    long double testTcb2 = secondsSinceModifedJulianDayZero;\n    long double testTdb1 = convertTcbToTdb< long double >( testTcb1 );\n    long double testTdb2 = convertTcbToTdb< long double >( testTcb2 );\n    long double computedLb = 1.0L - ( testTdb2 - testTdb1 ) / ( testTcb2 - testTcb1 );\n    BOOST_CHECK_SMALL( computedLb - physical_constants::LB_TIME_RATE_TERM_LONG,\n                                std::numeric_limits< long double >::epsilon( ) );\n\n    testTdb1 = 0.0;\n    testTdb2 = secondsSinceModifedJulianDayZero;\n    testTcb1 = convertTdbToTcb< long double >( 0.0 );\n    testTcb2 = convertTdbToTcb< long double >( secondsSinceModifedJulianDayZero );\n    computedLb = 1.0L - ( testTdb2 - testTdb1 ) / ( testTcb2 - testTcb1 );\n    BOOST_CHECK_SMALL( computedLb - physical_constants::LB_TIME_RATE_TERM_LONG,\n                                std::numeric_limits< long double >::epsilon( ) );\n\n}\n\nBOOST_AUTO_TEST_SUITE_END( )\n\n} // namespace unit_tests\n} // namespace tudat\n", "meta": {"hexsha": "c6afcb9fb01a24189622ad3d2a54b27eca8c0d37", "size": 27798, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/BasicAstrodynamics/UnitTests/unitTestTimeConversions.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/BasicAstrodynamics/UnitTests/unitTestTimeConversions.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/BasicAstrodynamics/UnitTests/unitTestTimeConversions.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": 51.3826247689, "max_line_length": 125, "alphanum_fraction": 0.6520253256, "num_tokens": 6867, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.4516670318685691}}
{"text": "#include \"needleman.h\"\n\n#include \"ereal.h\"\n#include <cassert>\n#include <algorithm>\n#include <blitz/tinyvec-et.h>\n#include <btl/logspace.h>\n\n// We assume the BLASTN default scoring scheme with Juke's/Cantor background. All logs are in base sqrt(2).\n// Defaults          Adjusted to remove/include the odds portion.\n// Match:       1   4\n// Mismatch:   -3   -12\n// Gap open:   -5   -20\n// Gap extend: -2   -8\nvoid needleman::init_pr() {\n   // match/mismatch probabilities\n   // pno_open should be rolled in here, but it's value is -0.006 which is\n   // barely representable by the precisian we use here. Ignore for now.\n   s =   4.0, 0.015625, 0.015625, 0.015625,\n         0.015625, 4.0, 0.015625, 0.015625,\n         0.015625, 0.015625, 4.0, 0.015625,\n         0.015625, 0.015625, 0.015625, 4.0;\n\n   // gap open\n   popen = 0.001043033;\n\n   // gap extend\n   pext = 0.0625;\n   pno_ext = 1.0-0.0625;\n}\n\nvoid needleman::set_parameters( nw_model_parameters const &mp ){\n\tset_mean_gap_length( mp.mean_gap_length );\n\tset_s( mp.pr_open, mp.p, mp.q );\n}\n\n// set mean gap length to n\nvoid needleman::set_mean_gap_length( double n ) {\n   // Since a gap is length 1 by the virtue of opening it, we adjust n down by 1.\n   // The remaining gap extension probability corresponds to the mean of a\n   // geometric distribution allowing zero extensions.\n   pext =  1.0-1.0/n;\n   pno_ext =  1.0/n;\n\t}\n\n// computes score matrix from match probabilities and background\nvoid needleman::set_s( double new_popen, blitz::Array<double,2> const &p, blitz::TinyVector<double,4> const &q ) {\n   using namespace std;\n   assert( p.rows() == 4 );\n   assert( p.cols() == 4 );\n\n   popen = new_popen;\n\tdouble pno_open = 1.0-2*new_popen;\n   for( int i = 0; i < 4; i++ ) for( int j = 0; j < 4; j++ ) s(i,j) = pno_open*p(i,j)/q(i)/q(j);\n}\n\nvoid needleman::maindp_init_borders( dparray &dp, dna_sequence_region_data &a, dna_sequence_region_data &b ) {\n   int n = (int) a.size(), m = (int)b.size();\n   assert( (n>=1) && (m>=1) );\n\n   // top corner is the only valid starting point\n   init_cell(dp(0,0).M); init_cell(dp(0,0).Ga); init_cell(dp(0,0).Gb);\n   dp(0,0).M.s = 1.0;\n\n   // Initialize borders. Scores represent opening a big gap.\n   init_cell(dp(1,0).M); init_cell(dp(1,0).Ga); init_cell(dp(1,0).Gb);\n   dp(1,0).Gb.from = M_state; dp(1,0).Gb.s = popen*pno_ext;\n   for( int i = 2; i <= n; i++ ) {\n      init_cell(dp(i,0).M); init_cell(dp(i,0).Ga); init_cell(dp(i,0).Gb);\n      dp(i,0).Gb.from = Gb_state; dp(i,0).Gb.s = dp(i-1,0).Gb.s*pext;\n   }\n   init_cell(dp(0,1).M); init_cell(dp(0,1).Ga); init_cell(dp(0,1).Gb);\n   dp(0,1).Ga.from = M_state; dp(0,1).Ga.s = popen*pno_ext;\n   for( int j = 2; j <= m; j++ ) {\n      init_cell(dp(0,j).M); init_cell(dp(0,j).Ga); init_cell(dp(0,j).Gb);\n      dp(0,j).Ga.from = Ga_state; dp(0,j).Ga.s = dp(0,j-1).Ga.s*pext;\n   }\n}\n\nvoid needleman::maindp_filldp( dparray &dp, dna_sequence_region_data &a, dna_sequence_region_data &b ) {\n   int n = (int) a.size(), m = (int)b.size();\n\tereal score, match_cost;\n   for( int i = 1; i <= n; i++ ) {\n   for( int j = 1; j <= m; j++ ) {\n      // first consider a match, default is come from match\n      match_cost = s((int)a[(uint)i-1],(int)b[(uint)j-1]);\n      dp(i,j).M.s = dp(i-1,j-1).M.s*match_cost;\n      dp(i,j).M.from = M_state;\n\n      // consider coming from a gap in A\n      score = dp(i-1,j-1).Ga.s*match_cost;\n      if( score > dp(i,j).M.s ) {\n         dp(i,j).M.s = score;\n         dp(i,j).M.from = Ga_state;\n      }\n\n      // consider coming from a gap in B\n      score = dp(i-1,j-1).Gb.s*match_cost;\n      if( score > dp(i,j).M.s ) {\n         dp(i,j).M.s = score;\n         dp(i,j).M.from = Gb_state;\n      }\n\n      // now consider extending or opening a gap in A, default is open a gap\n      dp(i,j).Ga.s = dp(i,j-1).M.s*popen*pno_ext;\n      dp(i,j).Ga.from = M_state;\n\n      // extend a gap\n      score = dp(i,j-1).Ga.s*pext;\n      if( score > dp(i,j).Ga.s ) {\n         dp(i,j).Ga.s = score;\n         dp(i,j).Ga.from = Ga_state;\n      }\n\n      // now consider extending or opening a gap in B, default is open a gap\n      dp(i,j).Gb.s = dp(i-1,j).M.s*popen*pno_ext;\n      dp(i,j).Gb.from = M_state;\n\n      // extend a gap\n      score = dp(i-1,j).Gb.s*pext;\n      if( score > dp(i,j).Gb.s ) {\n         dp(i,j).Gb.s = score;\n         dp(i,j).Gb.from = Gb_state;\n      }\n   } // for j\n   } // for i\n}\n\npairwise_dna_alignment needleman::maindp_traceback( dparray &dp, dna_sequence_region_data &a, dna_sequence_region_data &b ) {\n   using namespace std;\n   int n = (int) a.size(), m = (int)b.size();\n\n   // alignment sequences\n   dna_alignment_sequence_ptr newa = new_dna_alignment_sequence(), newb = new_dna_alignment_sequence();\n\n   // determine starting block\n   int i = n, j = m, next_i = n, next_j = m;\n   uint8_t type = M_state, next_type = no_state;\n   if( state_score(dp,i,j,type) < dp(i,j).Ga.s ) type = Ga_state;\n   if( state_score(dp,i,j,type) < dp(i,j).Gb.s ) type = Gb_state;\n   ereal alignment_score = state_score(dp,i,j,type);\n\n   while( (i > 0) || (j > 0) ) {\n      assert( type != no_state );\n      assert( type < num_states );\n      switch( type ) {\n         case M_state:\n            next_i = i - 1;\n            next_j = j - 1;\n            next_type = dp(i,j).M.from;\n            newa->data.push_front( a[(uint)i-1] );\n            newb->data.push_front( b[(uint)j-1] );\n            break;\n         case Ga_state:\n            next_i = i;\n            next_j = j - 1;\n            next_type = dp(i,j).Ga.from;\n            newa->data.push_front( dna_alignment_alpha::GAP );\n            newb->data.push_front( b[(uint)j-1] );\n            break;\n         case Gb_state:\n            next_i = i - 1;\n            next_j = j;\n            next_type = dp(i,j).Gb.from;\n            newa->data.push_front( a[(uint)i-1] );\n            newb->data.push_front( dna_alignment_alpha::GAP );\n      }\n      i = next_i;\n      j = next_j;\n      type = next_type;\n   }\n   return pairwise_dna_alignment( newa, newb, alignment_score.as_base() );\n}\n\npairwise_dna_alignment needleman::maindp( dna_sequence_region_data &a, dna_sequence_region_data &b ) {\n   int n = (int) a.size(), m = (int)b.size();\n   dparray dp(n+1,m+1);\n   maindp_init_borders( dp, a, b );\n   maindp_filldp( dp, a, b );\n   return maindp_traceback( dp, a, b );\n}\n\n// only need to initialize score scheme\nneedleman::needleman() {\n   s.resize(dna_alpha::SIZE,dna_alpha::SIZE);\n   init_pr();\n}\n\npairwise_dna_alignment needleman::align( dna_sequence_region &seqa, dna_sequence_region &seqb ) {\n   return maindp( seqa.data, seqb.data );\n}\n\nstd::pair<nw_model_parameters_ptr,ereal > needleman::estimate( dna_sequence_region &seqa, dna_sequence_region &seqb ) {\n\tusing namespace std;\n\tpairwise_dna_alignment aln = align(seqa,seqb);\n\tcounts cnt;\n\tdo_statistics(aln,cnt);\n\tnw_model_parameters_ptr nwp = update_probabilities(cnt);\n\treturn make_pair(nwp,aln.score);\n}\n\nvoid needleman::do_statistics( pairwise_dna_alignment &align, needleman::counts &cnt ) {\n\tassert( align.a->data.size() == align.b->data.size() );\n\n\tint gap_a = -1, gap_b = -1;\n\tfor( int c = 0; c < (int)align.a->data.size(); ++c ) {\n\t\tdna_alignment_alpha::symbol c_a = align.a->data[c], c_b = align.b->data[c];\n\n\t\t// found a pair!\n\t\tif( c_a != dna_alignment_alpha::GAP && c_b != dna_alignment_alpha::GAP ) {\n\t\t\tint base_a = dna_alpha::symbol(c_a).index();\n\t\t\tint base_b = dna_alpha::symbol(c_b).index();\n\t\t\tcnt.pairs( base_a, base_b) += 1;\n\t\t\tcnt.bases_a(base_a) += 1;\n\t\t\tcnt.bases_b(base_b) += 1;\n\n\t\t\t// closing a gap in A\n\t\t\tif( gap_a >= 0 ) {\n\t\t\t\tcnt.gap_lengths_a += c - gap_a + 1;\n\t\t\t\tgap_a = -1;\n\t\t\t}\n\n\t\t\t// closing a gap in B\n\t\t\tif( gap_b >= 0 ) {\n\t\t\t\tcnt.gap_lengths_b += c - gap_b + 1;\n\t\t\t\tgap_b = -1;\n\t\t\t}\n\n\t\t\t// found a gap in A\n\t\t} else if( c_a == dna_alignment_alpha::GAP && c_b != dna_alignment_alpha::GAP ) {\n\t\t\tcnt.bases_b((int)dna_alpha::symbol(c_b)) += 1;\n\n\t\t\t// gap is not open\n\t\t\tif( gap_a == -1 ) {\n\t\t\t\tgap_a = c;\n\t\t\t\tcnt.gaps_a += 1;\n\t\t\t} // otherwise nothing to do\n\n\t\t\t// closing a gap in B\n\t\t\tif( gap_b >= 0 ) {\n\t\t\t\tcnt.gap_lengths_b += c - gap_b + 1;\n\t\t\t\tgap_b = -1;\n\t\t\t}\n\t\t\t// found a gap in B\n\t\t} else if( c_a != dna_alignment_alpha::GAP && c_b == dna_alignment_alpha::GAP ) {\n\t\t\tcnt.bases_a((int)dna_alpha::symbol(c_a)) += 1;\n\n\t\t\t// closing a gap in A\n\t\t\tif( gap_a >= 0 ) {\n\t\t\t\tcnt.gap_lengths_a += c - gap_a + 1;\n\t\t\t\tgap_a = -1;\n\t\t\t}\n\n\t\t\t// gap is not open\n\t\t\tif( gap_b == -1 ) {\n\t\t\t\tgap_b = c;\n\t\t\t\tcnt.gaps_b += 1;\n\t\t\t} // otherwise nothing to do\n\t\t} else {\n\t\t\tusing namespace std;\n\t\t\tcerr << c << \"\\t\" << c_a << \"\\t\" << c_b << endl;\n\t\t\tassert( 0 && \"corrupt alignment\" );\n\t\t}\n\n\t} // for c\n\n\t// finished region, count any last gaps\n\t// closing a gap in A\n\tif( gap_a >= 0 ) {\n\t\tcnt.gap_lengths_a += align.a->data.size() - gap_a;\n\t\tgap_a = -1;\n\t}\n\n\t// closing a gap in B\n\tif( gap_b >= 0 ) {\n\t\tcnt.gap_lengths_b += align.a->data.size() - gap_b;\n\t\tgap_b = -1;\n\t}\n\n}\n\nnw_model_parameters_ptr needleman::update_probabilities( needleman::counts &cnt ) {\n\tusing namespace std;\n\tusing namespace blitz;\n\n\t// get combined base count for both sequences\n\tbase_count all_bases;\n\tall_bases = cnt.bases_a + cnt.bases_b;\n\tint total_bases = sum( all_bases );\n\n\tnw_model_parameters_ptr newp( new nw_model_parameters() );\n\n\t// compute p\n\tint total_pairs = sum( cnt.pairs(Range::all(),Range::all()) );\n\tfor( int i = 0; i < dna_alpha::SIZE; ++i ) {\n\t\tfor( int j = 0; j < dna_alpha::SIZE; ++j ) {\n\t\t\tnewp->p(i,j) = (double) cnt.pairs(i,j)/(double)total_pairs;\n\t\t} // j\n\t} // i\n\n\tfor( int i = 0; i < dna_alpha::SIZE; ++i ) {\n\t\tnewp->q(i) = (double) all_bases(i)/(double)total_bases;\n\t}\n\n\t// gap open\n\tint total_gaps = cnt.gaps_a + cnt.gaps_b;\n\tnewp->pr_open = (double)total_gaps/(double)total_bases;\n\n\t// mean gap length\n\tnewp->mean_gap_length = (double)(cnt.gap_lengths_a+cnt.gap_lengths_b)/(double)total_gaps;\n\treturn newp;\n}\n\n", "meta": {"hexsha": "3d9bbec7b3c5894bca580a2893ca7347fffaf9a6", "size": 9797, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libs/alignment/needleman.cc", "max_stars_repo_name": "akhudek/feast", "max_stars_repo_head_hexsha": "bb41ac122a9c0542a0fb71eec81ff5e872c556e5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-06-15T21:46:07.000Z", "max_stars_repo_stars_event_max_datetime": "2015-06-15T21:46:07.000Z", "max_issues_repo_path": "src/libs/alignment/needleman.cc", "max_issues_repo_name": "akhudek/feast", "max_issues_repo_head_hexsha": "bb41ac122a9c0542a0fb71eec81ff5e872c556e5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libs/alignment/needleman.cc", "max_forks_repo_name": "akhudek/feast", "max_forks_repo_head_hexsha": "bb41ac122a9c0542a0fb71eec81ff5e872c556e5", "max_forks_repo_licenses": ["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.2006369427, "max_line_length": 125, "alphanum_fraction": 0.5988567929, "num_tokens": 3254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.4516670318685691}}
{"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_RMSPROP_HPP\n#define NETKET_RMSPROP_HPP\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <cassert>\n#include <cmath>\n#include <complex>\n#include <iostream>\n#include \"abstract_optimizer.hpp\"\n\nnamespace netket {\n\nclass RMSProp : public AbstractOptimizer {\n  int npar_;\n\n  double eta_;\n  double beta_;\n\n  Eigen::VectorXd st_;\n\n  double epscut_;\n\n  const Complex I_;\n\n public:\n  explicit RMSProp(double eta = 0.001, double beta = 0.9,\n                   double epscut = 1.0e-7)\n      : eta_(eta), beta_(beta), epscut_(epscut), I_(0, 1) {\n    npar_ = -1;\n    PrintParameters();\n  }\n\n  // TODO remove\n  // Json constructor\n  explicit RMSProp(const json &pars) : I_(0, 1) {\n    npar_ = -1;\n\n    from_json(pars);\n    PrintParameters();\n  }\n\n  void PrintParameters() {\n    InfoMessage() << \"RMSProp optimizer initialized with these parameters :\"\n                  << std::endl;\n    InfoMessage() << \"Learning Rate = \" << eta_ << std::endl;\n    InfoMessage() << \"Beta = \" << beta_ << std::endl;\n    InfoMessage() << \"Epscut = \" << epscut_ << std::endl;\n  }\n\n  void Init(const Eigen::VectorXd &pars) override {\n    npar_ = pars.size();\n    st_.setZero(npar_);\n  }\n\n  void Init(const Eigen::VectorXcd &pars) override {\n    npar_ = 2 * pars.size();\n    st_.setZero(npar_);\n  }\n\n  void Update(const Eigen::VectorXd &grad, Eigen::VectorXd &pars) override {\n    assert(npar_ > 0);\n\n    st_ = beta_ * st_ + (1. - beta_) * grad.cwiseAbs2();\n\n    for (int i = 0; i < npar_; i++) {\n      pars(i) -= eta_ * grad(i) / (std::sqrt(st_(i)) + epscut_);\n    }\n  }\n\n  void Update(const Eigen::VectorXcd &grad, Eigen::VectorXd &pars) override {\n    Update(Eigen::VectorXd(grad.real()), pars);\n  }\n\n  void Update(const Eigen::VectorXcd &grad, Eigen::VectorXcd &pars) override {\n    assert(npar_ == 2 * pars.size());\n\n    for (int i = 0; i < pars.size(); i++) {\n      st_(2 * i) =\n          beta_ * st_(2 * i) + (1. - beta_) * std::pow(grad(i).real(), 2);\n      st_(2 * i + 1) =\n          beta_ * st_(2 * i + 1) + (1. - beta_) * std::pow(grad(i).imag(), 2);\n      pars(i) -= eta_ * grad(i).real() / (std::sqrt(st_(2 * i)) + epscut_);\n      pars(i) -=\n          eta_ * I_ * grad(i).imag() / (std::sqrt(st_(2 * i + 1)) + epscut_);\n    }\n  }\n\n  void Reset() override { st_ = Eigen::VectorXd::Zero(npar_); }\n\n  // TODO remove\n  void from_json(const json &pars) {\n    // DEPRECATED (to remove for v2.0.0)\n    std::string section = \"Optimizer\";\n    if (!FieldExists(pars, section)) {\n      section = \"Learning\";\n    }\n    eta_ = FieldOrDefaultVal(pars[section], \"LearningRate\", 0.001);\n    beta_ = FieldOrDefaultVal(pars[section], \"Beta\", 0.9);\n    epscut_ = FieldOrDefaultVal(pars[section], \"Epscut\", 1.0e-7);\n  }\n};\n\n}  // namespace netket\n\n#endif\n", "meta": {"hexsha": "78e00af9fcbdb6f3faa0cc48746e93cd0550a7c7", "size": 3359, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "NetKet/Optimizer/rms_prop.hpp", "max_stars_repo_name": "flatironinstitute/netket", "max_stars_repo_head_hexsha": "888a4b56b6242d62b45d32eda43e10066c65fdf9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-06-13T19:00:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-23T01:03:15.000Z", "max_issues_repo_path": "NetKet/Optimizer/rms_prop.hpp", "max_issues_repo_name": "flatironinstitute/netket", "max_issues_repo_head_hexsha": "888a4b56b6242d62b45d32eda43e10066c65fdf9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NetKet/Optimizer/rms_prop.hpp", "max_forks_repo_name": "flatironinstitute/netket", "max_forks_repo_head_hexsha": "888a4b56b6242d62b45d32eda43e10066c65fdf9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-23T01:04:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-23T01:04:00.000Z", "avg_line_length": 27.7603305785, "max_line_length": 78, "alphanum_fraction": 0.6174456684, "num_tokens": 981, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850933, "lm_q2_score": 0.6370308013713525, "lm_q1q2_score": 0.45166702698274014}}
{"text": "#include <string>\n#include <fstream>\n#include <cmath>\n\n#include <boost/test/unit_test.hpp>\n#include <boost/filesystem.hpp>\n#include <boost/filesystem/path.hpp>\n\n#include <am/graphchi/graphchi_basic_includes.hpp>\n#include <am/graphchi/engine/dynamic_graphs/graphchi_dynamicgraph_engine.hpp>\n#include <am/graphchi/api/functional/functional_api.hpp>\n#include <am/graphchi/util/toplist.hpp>\n\nusing namespace graphchi;\nnamespace bfs = boost::filesystem;\n\n#define DIR_PREFIX \"./tmp/am_graphchi_\"\n\n#define THRESHOLD 1e-1    \n#define RANDOMRESETPROB 0.15\n\n\ntypedef float VertexDataType;\ntypedef float EdgeDataType;\n\nstruct PagerankProgram : public GraphChiProgram<VertexDataType, EdgeDataType> {\n    \n    /**\n      * Called before an iteration starts. Not implemented.\n      */\n    void before_iteration(int iteration, graphchi_context &info) {\n    }\n    \n    /**\n      * Called after an iteration has finished. Not implemented.\n      */\n    void after_iteration(int iteration, graphchi_context &ginfo) {\n    }\n    \n    /**\n      * Called before an execution interval is started. Not implemented.\n      */\n    void before_exec_interval(vid_t window_st, vid_t window_en, graphchi_context &ginfo) {        \n    }\n    \n    \n    /**\n      * Pagerank update function.\n      */\n    void update(graphchi_vertex<VertexDataType, EdgeDataType> &v, graphchi_context &ginfo) {\n        float sum=0;\n        if (ginfo.iteration == 0) {\n            /* On first iteration, initialize vertex and out-edges. \n               The initialization is important,\n               because on every run, GraphChi will modify the data in the edges on disk. \n             */\n            for(int i=0; i < v.num_outedges(); i++) {\n                graphchi_edge<float> * edge = v.outedge(i);\n                edge->set_data(1.0 / v.num_outedges());\n            }\n            v.set_data(RANDOMRESETPROB); \n        } else {\n            /* Compute the sum of neighbors' weighted pageranks by\n               reading from the in-edges. */\n            for(int i=0; i < v.num_inedges(); i++) {\n                float val = v.inedge(i)->get_data();\n                sum += val;                    \n            }\n            \n            /* Compute my pagerank */\n            float pagerank = RANDOMRESETPROB + (1 - RANDOMRESETPROB) * sum;\n            \n            /* Write my pagerank divided by the number of out-edges to\n               each of my out-edges. */\n            if (v.num_outedges() > 0) {\n                float pagerankcont = pagerank / v.num_outedges();\n                for(int i=0; i < v.num_outedges(); i++) {\n                    graphchi_edge<float> * edge = v.outedge(i);\n                    edge->set_data(pagerankcont);\n                }\n            }\n                \n            /* Keep track of the progression of the computation.\n               GraphChi engine writes a file filename.deltalog. */\n            ginfo.log_change(std::abs(pagerank - v.get_data()));\n            \n            /* Set my new pagerank as the vertex value */\n            v.set_data(pagerank); \n        }\n    }\n    \n};\n\nstruct pagerank_kernel : public functional_kernel<float, float> {\n    \n    /* Initial value - on first iteration */\n    float initial_value(graphchi_context &info, vertex_info& myvertex) {\n        return 1.0;\n    }\n    \n    /* Called before first \"gather\" */\n    float reset() {\n        return 0.0;\n    }\n    \n    // Note: Unweighted version, edge value should also be passed\n    // \"Gather\"\n    float op_neighborval(graphchi_context &info, vertex_info& myvertex, vid_t nbid, float nbval) {\n        return nbval;\n    }\n    \n    // \"Sum\"\n    float plus(float curval, float toadd) {\n        return curval + toadd;\n    }\n    \n    // \"Apply\"\n    float compute_vertexvalue(graphchi_context &ginfo, vertex_info& myvertex, float nbvalsum) {\n        assert(ginfo.nvertices > 0);\n        return RANDOMRESETPROB / ginfo.nvertices + (1 - RANDOMRESETPROB) * nbvalsum;\n    }\n    \n    // \"Scatter\n    float value_to_neighbor(graphchi_context &info, vertex_info& myvertex, vid_t nbid, float myval) {\n        assert(myvertex.outdegree > 0);\n        return myval / myvertex.outdegree; \n    }\n    \n}; \n\n\n\nBOOST_AUTO_TEST_SUITE( graphchi_app_pagerank_suite )\n\nBOOST_AUTO_TEST_CASE(graphchi_pagerank)\n{\n    metrics m(\"pagerank\");\n    \n    /* Basic arguments for application */\n    bfs::path db_dir(DIR_PREFIX);\n    boost::filesystem::remove_all(db_dir);\n    bfs::create_directories(db_dir);\n    std::string filename = db_dir.string() + \"/graphchi_pagerank\";\n    ///generate fake inputs\n    std::ofstream of(filename.c_str());\n    const unsigned int size = 8;\n    const unsigned int src[size] = {1,2,3,4,5,6,7,8};\n    const unsigned int dest[size] = {4,2,3,1,3,2,8,1};\t\n    const float weight[size] = {0.1,0.2,0.3,0.1,0.5,0.6,0.8,1};\n    for(unsigned int i = 0; i < size; ++i)\n        of<<src[i]<<\" \"<<dest[i]<<\" \"<<weight[i]<<std::endl;\n    of.close();\n    \n    int niters = get_option_int(\"niters\", 4); // Number of iterations\n    bool scheduler = false;                       // Whether to use selective scheduling\n\n    int ntop = get_option_int(\"top\", 20);\n    \n    /* Detect the number of shards or preprocess an input to creae them */\n    int nshards = convert_if_notexists<EdgeDataType>(filename, \n                                                              get_option_string(\"nshards\", \"auto\"));\n\n    /* Run */\n    graphchi_engine<float, float> engine(filename, nshards, scheduler, m); \n    engine.set_modifies_inedges(false); // Improves I/O performance.\n    PagerankProgram program;\n    engine.run(program, niters);\n        \n    /* Output top ranked vertices */\n    std::vector< vertex_value<float> > top = get_top_vertices<float>(filename, ntop);\n    std::cout << \"Print top \" << ntop << \" vertices:\" << std::endl;\n    for(int i=0; i < (int)top.size(); i++) {\n        std::cout << (i+1) << \". \" << top[i].vertex << \"\\t\" << top[i].value << std::endl;\n    }\n    metrics_report(m);\n    \n    logstream(LOG_INFO) << \"Pagerank executed successfully!\" << std::endl;\n}\n\nBOOST_AUTO_TEST_CASE(graphchi_pagerank_functional)\n{\n    metrics m(\"pagerank-functional\");\n    \n    /* Basic arguments for application */\n    bfs::path db_dir(DIR_PREFIX);\n    boost::filesystem::remove_all(db_dir);\n    bfs::create_directories(db_dir);\n    std::string filename = db_dir.string() + \"/graphchi_pagerank-functional\";\n    ///generate fake inputs\n    std::ofstream of(filename.c_str());\n    const unsigned int size = 8;\n    const unsigned int src[size] = {1,2,3,4,5,6,7,8};\n    const unsigned int dest[size] = {4,2,3,1,3,2,8,1};\t\n    const float weight[size] = {0.1,0.2,0.3,0.1,0.5,0.6,0.8,1};\n    for(unsigned int i = 0; i < size; ++i)\n        of<<src[i]<<\" \"<<dest[i]<<\" \"<<weight[i]<<std::endl;\n    of.close();\n    \n    int niters = get_option_int(\"niters\", 4);\n    int ntop = get_option_int(\"top\", 20);\n    std::string mode = get_option_string(\"mode\", \"semisync\");\n\t\n    logstream(LOG_INFO) << \"Running pagerank functional.\" << std::endl;\n    run_functional_unweighted_synchronous<pagerank_kernel>(filename, niters, m);\n    logstream(LOG_INFO) << \"Pagerank functional passed successfully! Your system is working!\" << std::endl;\n    /* Write Top 20 */\n    std::vector< vertex_value<float> > top = get_top_vertices<float>(filename, ntop);\n    std::cout << \"Print top 20 vertices: \" << std::endl;\n    for(int i=0; i < (int) top.size(); i++) {\n        std::cout << (i+1) << \". \" << top[i].vertex << \"\\t\" << top[i].value << std::endl;\n    }\n\t\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n", "meta": {"hexsha": "aa91f3e5effb59eed7522665da587ac583b1e788", "size": 7505, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/am/graphchi/t_pagerank.cpp", "max_stars_repo_name": "izenecloud/izenelib", "max_stars_repo_head_hexsha": "9d5958100e2ce763fc75f27217adf982d7c9d902", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2015-03-03T19:13:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-03T08:11:56.000Z", "max_issues_repo_path": "test/am/graphchi/t_pagerank.cpp", "max_issues_repo_name": "izenecloud/izenelib", "max_issues_repo_head_hexsha": "9d5958100e2ce763fc75f27217adf982d7c9d902", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-12-24T00:12:11.000Z", "max_issues_repo_issues_event_max_datetime": "2016-12-24T00:12:11.000Z", "max_forks_repo_path": "test/am/graphchi/t_pagerank.cpp", "max_forks_repo_name": "izenecloud/izenelib", "max_forks_repo_head_hexsha": "9d5958100e2ce763fc75f27217adf982d7c9d902", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-09-06T01:55:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-20T02:16:13.000Z", "avg_line_length": 34.5852534562, "max_line_length": 107, "alphanum_fraction": 0.601065956, "num_tokens": 1931, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.6370308013713525, "lm_q1q2_score": 0.4516670269827401}}
{"text": "#ifndef AIKIDO_STATESPACE_SO3STATESPACE_HPP_\n#define AIKIDO_STATESPACE_SO3STATESPACE_HPP_\n#include <Eigen/Geometry>\n\n#include \"aikido/statespace/ScopedState.hpp\"\n#include \"aikido/statespace/StateSpace.hpp\"\n\nnamespace aikido {\nnamespace statespace {\n\n// Defined in detail/SO3-impl.hpp\ntemplate <class>\nclass SO3StateHandle;\n\n/// The two-dimensional special orthogonal group SO(3), i.e. the space of\n/// spatial rigid body rotations.\nclass SO3 : virtual public StateSpace\n{\npublic:\n  /// State in SO(3), a spatial rotation.\n  class State : public StateSpace::State\n  {\n  public:\n    using Quaternion = Eigen::Quaternion<double, Eigen::DontAlign>;\n\n    /// Constructs the identity element.\n    State();\n\n    ~State() = default;\n\n    /// Constructs a state in SO(3) from a unit quaternion.\n    ///\n    /// \\param _quaternion unit quaternion representing orientation\n    explicit State(const Quaternion& _quaternion);\n\n    /// Gets a state as a unit quaternion.\n    ///\n    /// \\return unit quaternion representing orientation\n    const Quaternion& getQuaternion() const;\n\n    /// Sets a state to a unit quaternion.\n    ///\n    /// \\param _quaternion unit quaternion representing orientation\n    void setQuaternion(const Quaternion& _quaternion);\n\n  private:\n    Quaternion mValue;\n\n    friend class SO3;\n  };\n\n  using StateHandle = SO3StateHandle<State>;\n  using StateHandleConst = SO3StateHandle<const State>;\n\n  using ScopedState = statespace::ScopedState<StateHandle>;\n  using ScopedStateConst = statespace::ScopedState<StateHandleConst>;\n\n  using StateSpace::compose;\n\n  using Quaternion = State::Quaternion;\n\n  /// Constructs a state space representing SO(3).\n  SO3() = default;\n\n  /// Helper function to create a \\c ScopedState.\n  ///\n  /// \\return new \\c ScopedState\n  ScopedState createState() const;\n\n  /// Creates an identical clone of \\c stateIn.\n  ScopedState cloneState(const StateSpace::State* stateIn) const;\n\n  /// Gets a state as a unit quaternion.\n  ///\n  /// \\param _state input state\n  /// \\return unit quaternion representing orientation\n  const Quaternion& getQuaternion(const State* _state) const;\n\n  /// Sets a state to a unit quaternion.\n  ///\n  /// \\param _state input state\n  /// \\param _quaternion unit quaternion representing orientation\n  void setQuaternion(State* _state, const Quaternion& _quaternion) const;\n\n  // Documentation inherited.\n  std::size_t getStateSizeInBytes() const override;\n\n  // Documentation inherited.\n  StateSpace::State* allocateStateInBuffer(void* _buffer) const override;\n\n  // Documentation inherited.\n  void freeStateInBuffer(StateSpace::State* _state) const override;\n\n  // Documentation inherited.\n  void compose(\n      const StateSpace::State* _state1,\n      const StateSpace::State* _state2,\n      StateSpace::State* _out) const override;\n\n  // Documentation inherited\n  void getIdentity(StateSpace::State* _out) const override;\n\n  // Documentation inherited\n  void getInverse(\n      const StateSpace::State* _in, StateSpace::State* _out) const override;\n\n  // Documentation inherited\n  std::size_t getDimension() const override;\n\n  // Documentation inherited\n  void copyState(\n      const StateSpace::State* _source,\n      StateSpace::State* _destination) const override;\n\n  /// Exponential mapping of Lie algebra element to a Lie group element. The\n  /// tangent space is parameterized as a spatial rotation velocity.\n  ///\n  /// \\param _tangent element of the tangent space\n  /// \\param[out] _out corresponding element of the Lie group\n  void expMap(\n      const Eigen::VectorXd& _tangent, StateSpace::State* _out) const override;\n\n  /// Log mapping of Lie group element to a Lie algebra element. The tangent\n  /// space is parameterized as a spatial rotational velocity.\n  ///\n  /// \\param _in element of this Lie group\n  /// \\param[out] _tangent corresponding element of the tangent space\n  void logMap(\n      const StateSpace::State* _in, Eigen::VectorXd& _tangent) const override;\n\n  /// Print the quaternion represented by the state.\n  /// Format: [w, x, y, z]\n  void print(const StateSpace::State* _state, std::ostream& _os) const override;\n};\n\n} // namespace statespace\n} // namespace aikido\n\n#include \"detail/SO3-impl.hpp\"\n\n#endif // ifndef AIKIDO_STATESPACE_SO3STATESPACE_HPP_\n", "meta": {"hexsha": "ed89772958862d6f0c4ceec2dcae98b7509e8050", "size": 4248, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/aikido/statespace/SO3.hpp", "max_stars_repo_name": "personalrobotics/r3", "max_stars_repo_head_hexsha": "1303e3f3ef99a0c2249abc7415d19113f0026565", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 181.0, "max_stars_repo_stars_event_min_datetime": "2016-04-22T15:11:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T12:51:08.000Z", "max_issues_repo_path": "include/aikido/statespace/SO3.hpp", "max_issues_repo_name": "personalrobotics/r3", "max_issues_repo_head_hexsha": "1303e3f3ef99a0c2249abc7415d19113f0026565", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 514.0, "max_issues_repo_issues_event_min_datetime": "2016-04-20T04:29:51.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T19:46:21.000Z", "max_forks_repo_path": "include/aikido/statespace/SO3.hpp", "max_forks_repo_name": "personalrobotics/r3", "max_forks_repo_head_hexsha": "1303e3f3ef99a0c2249abc7415d19113f0026565", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 31.0, "max_forks_repo_forks_event_min_datetime": "2017-03-17T09:53:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T10:35:05.000Z", "avg_line_length": 29.9154929577, "max_line_length": 80, "alphanum_fraction": 0.7245762712, "num_tokens": 1002, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.45166702209691106}}
{"text": "/******************************************************************************\nThis benchmark allows to compute the Tangential Complex from input files or \ngenerated point sets.\n\nIt reads the benchmark_script.txt file (located in the same folder as this \nfile) and compute one or several complexes for each line. Unless TC_NO_EXPORT \nis defined, each complex is exported as an OFF file and/or as a RIB file \n(RenderMan). In addition an XML file is created at each run of the benchmark. \nIt contains statistics about the complexes that were created. This XML file \ncan be processed in Excel, for example.\n ******************************************************************************/\n\n// Without TBB_USE_THREADING_TOOL Intel Inspector XE will report false positives in Intel TBB\n// (http://software.intel.com/en-us/articles/compiler-settings-for-threading-error-analysis-in-intel-inspector-xe/)\n#ifdef _DEBUG\n#define TBB_USE_THREADING_TOOL\n#endif\n\n#include <cstddef>\n\n//#define GUDHI_TC_USE_ANOTHER_POINT_SET_FOR_TANGENT_SPACE_ESTIM\n//#define TC_INPUT_STRIDES 3 // only take one point every TC_INPUT_STRIDES points\n#define TC_NO_EXPORT // do not output OFF files\n//#define TC_EXPORT_TO_RIB // \n//#define GUDHI_TC_EXPORT_SPARSIFIED_POINT_SET\n//#define GUDHI_TC_EXPORT_ALL_COORDS_IN_OFF\n\nconst std::size_t ONLY_LOAD_THE_FIRST_N_POINTS = 20000000;\n\n#include <gudhi/Debug_utils.h>\n#include <gudhi/Clock.h>\n#include <gudhi/Tangential_complex.h>\n#include <gudhi/sparsify_point_set.h>\n#include <gudhi/random_point_generators.h>\n#include <gudhi/Tangential_complex/utilities.h>\n\n#include <CGAL/assertions_behaviour.h>\n#include <CGAL/Epick_d.h>\n#include <CGAL/Random.h>\n\n#include <boost/algorithm/string/replace.hpp>\n#include <boost/algorithm/string/trim_all.hpp>\n#include <boost/range/adaptor/strided.hpp>\n\n#include <cstdlib>\n#include <ctime>\n#include <fstream>\n#include <cmath>  // for std::sqrt\n\n#ifdef GUDHI_USE_TBB\n#include <tbb/task_scheduler_init.h>\n#endif\n#include \"XML_exporter.h\"\n#include \"RIB_exporter.h\"\n#define GUDHI_TC_EXPORT_PERFORMANCE_DATA\n#define GUDHI_TC_SET_PERFORMANCE_DATA(value_name, value) \\\n        XML_perf_data::set(value_name, value);\n\n\nnamespace subsampl = Gudhi::subsampling;\nnamespace tc = Gudhi::tangential_complex;\n\nconst char * const BENCHMARK_SCRIPT_FILENAME = \"benchmark_script.txt\";\n\ntypedef CGAL::Epick_d<CGAL::Dynamic_dimension_tag> Kernel;\ntypedef Kernel::FT FT;\ntypedef Kernel::Point_d Point;\ntypedef Kernel::Vector_d Vector;\ntypedef tc::Tangential_complex<\nKernel, CGAL::Dynamic_dimension_tag,\nCGAL::Parallel_tag> TC;\ntypedef TC::Simplex Simplex;\ntypedef TC::Simplex_set Simplex_set;\n\nclass XML_perf_data {\n public:\n  typedef Streaming_XML_exporter<std::string> XML_exporter;\n\n  XML_perf_data(const std::string &filename)\n      : m_xml(filename, \"ContainerPerformance\", \"Perf\",\n              construct_subelements_names()) { }\n\n  virtual ~XML_perf_data() { }\n\n  static XML_perf_data &get() {\n    static XML_perf_data singleton(build_filename());\n    return singleton;\n  }\n\n  template <typename Value_type>\n  static void set(const std::string &name, Value_type value) {\n    get().set_data(name, value);\n  }\n\n  static void commit() {\n    get().commit_current_element();\n  }\n\n protected:\n\n  static std::string build_filename() {\n    std::stringstream sstr;\n    sstr << \"perf_logs/Performance_log_\" << time(0) << \".xml\";\n    return sstr.str();\n  }\n\n  static std::vector<std::string> construct_subelements_names() {\n    std::vector<std::string> subelements;\n    subelements.push_back(\"Input\");\n    subelements.push_back(\"Param1\");\n    subelements.push_back(\"Param2\");\n    subelements.push_back(\"Param3\");\n    subelements.push_back(\"Intrinsic_dim\");\n    subelements.push_back(\"Ambient_dim\");\n    subelements.push_back(\"Num_threads\");\n    subelements.push_back(\"Sparsity\");\n    subelements.push_back(\"Max_perturb\");\n    subelements.push_back(\"Num_points_in_input\");\n    subelements.push_back(\"Num_points\");\n    subelements.push_back(\"Perturb_technique\");\n    subelements.push_back(\"Perturb_which_points\");\n    subelements.push_back(\"Initial_num_inconsistent_local_tr\");\n    subelements.push_back(\"Best_num_inconsistent_local_tr\");\n    subelements.push_back(\"Final_num_inconsistent_local_tr\");\n    subelements.push_back(\"Init_time\");\n    subelements.push_back(\"Comput_time\");\n    subelements.push_back(\"Perturb_successful\");\n    subelements.push_back(\"Perturb_time\");\n    subelements.push_back(\"Perturb_steps\");\n    subelements.push_back(\"Result_pure_pseudomanifold\");\n    subelements.push_back(\"Result_num_wrong_dim_simplices\");\n    subelements.push_back(\"Result_num_wrong_number_of_cofaces\");\n    subelements.push_back(\"Result_num_unconnected_stars\");\n    subelements.push_back(\"Info\");\n\n    return subelements;\n  }\n\n  void set_data(const std::string &name, const std::string &value) {\n    m_current_element[name] = value;\n  }\n\n  template <typename Value_type>\n  void set_data(const std::string &name, Value_type value) {\n    std::stringstream sstr;\n    sstr << value;\n    set_data(name, sstr.str());\n  }\n\n  void commit_current_element() {\n    m_xml.add_element(m_current_element);\n    m_current_element.clear();\n  }\n\n  XML_exporter m_xml;\n  XML_exporter::Element_with_map m_current_element;\n};\n\ntemplate<\ntypename Kernel, typename OutputIteratorPoints>\nbool load_points_from_file(\n                           const std::string &filename,\n                           OutputIteratorPoints points,\n                           std::size_t only_first_n_points = (std::numeric_limits<std::size_t>::max)()) {\n  typedef typename Kernel::Point_d Point;\n\n  std::ifstream in(filename);\n  if (!in.is_open()) {\n    std::cerr << \"Could not open '\" << filename << \"'\" << std::endl;\n    return false;\n  }\n\n  Kernel k;\n  Point p;\n  int num_ppints;\n  in >> num_ppints;\n\n  std::size_t i = 0;\n  while (i < only_first_n_points && in >> p) {\n    *points++ = p;\n    ++i;\n  }\n\n#ifdef DEBUG_TRACES\n  std::cerr << \"'\" << filename << \"' loaded.\" << std::endl;\n#endif\n\n  return true;\n}\n\ntemplate<\ntypename Kernel, typename Tangent_space_basis,\ntypename OutputIteratorPoints, typename OutputIteratorTS>\nbool load_points_and_tangent_space_basis_from_file(\n                                                   const std::string &filename,\n                                                   OutputIteratorPoints points,\n                                                   OutputIteratorTS tangent_spaces,\n                                                   int intrinsic_dim,\n                                                   std::size_t only_first_n_points = (std::numeric_limits<std::size_t>::max)()) {\n  typedef typename Kernel::Point_d Point;\n  typedef typename Kernel::Vector_d Vector;\n\n  std::ifstream in(filename);\n  if (!in.is_open()) {\n    std::cerr << \"Could not open '\" << filename << \"'\" << std::endl;\n    return false;\n  }\n\n  Kernel k;\n  Point p;\n  int num_ppints;\n  in >> num_ppints;\n\n  std::size_t i = 0;\n  while (i < only_first_n_points && in >> p) {\n    *points++ = p;\n\n    Tangent_space_basis tsb(i);\n    for (int d = 0; d < intrinsic_dim; ++d) {\n      Vector v;\n      in >> v;\n      tsb.push_back(tc::internal::normalize_vector(v, k));\n    }\n    *tangent_spaces++ = tsb;\n    ++i;\n  }\n\n#ifdef DEBUG_TRACES\n  std::cerr << \"'\" << filename << \"' loaded.\" << std::endl;\n#endif\n\n  return true;\n}\n\n// color_inconsistencies: only works if p_complex = NULL\ntemplate <typename TC>\nbool export_to_off(\n                   TC const& tc,\n                   std::string const& input_name_stripped,\n                   std::string const& suffix,\n                   bool color_inconsistencies = false,\n                   typename TC::Simplicial_complex const* p_complex = NULL,\n                   Simplex_set const *p_simpl_to_color_in_red = NULL,\n                   Simplex_set const *p_simpl_to_color_in_green = NULL,\n                   Simplex_set const *p_simpl_to_color_in_blue = NULL) {\n#ifdef TC_NO_EXPORT\n  return true;\n#endif\n\n  CGAL::Identity<Point> proj_functor;\n\n  if (tc.intrinsic_dimension() <= 3) {\n    std::stringstream output_filename;\n    output_filename << \"output/\" << input_name_stripped << \"_\"\n        << tc.intrinsic_dimension() << \"_in_R\"\n        << tc.ambient_dimension() << \"_\"\n        << tc.number_of_vertices() << \"v\"\n        << suffix << \".off\";\n    std::ofstream off_stream(output_filename.str().c_str());\n\n    if (p_complex) {\n#ifndef TC_NO_EXPORT\n      tc.export_to_off(\n                       *p_complex, off_stream,\n                       p_simpl_to_color_in_red,\n                       p_simpl_to_color_in_green,\n                       p_simpl_to_color_in_blue,\n                       proj_functor);\n#endif\n    } else {\n      tc.export_to_off(\n                       off_stream, color_inconsistencies,\n                       p_simpl_to_color_in_red,\n                       p_simpl_to_color_in_green,\n                       p_simpl_to_color_in_blue,\n                       NULL,\n                       proj_functor);\n    }\n    return true;\n  }\n  return false;\n}\n\nvoid make_tc(std::vector<Point> &points,\n             TC::TS_container const& tangent_spaces,  // can be empty\n             int intrinsic_dim,\n             double sparsity = 0.01,\n             double max_perturb = 0.005,\n             bool perturb = true,\n             bool add_high_dim_simpl = false,\n             bool collapse = false,\n             double time_limit_for_perturb = 0.,\n             const char *input_name = \"tc\") {\n  Kernel k;\n\n  if (sparsity > 0. && !tangent_spaces.empty()) {\n    std::cerr << \"Error: cannot sparsify point set with pre-computed normals.\\n\";\n    return;\n  }\n\n  //===========================================================================\n  // Init\n  //===========================================================================\n  Gudhi::Clock t;\n\n  // Get input_name_stripped\n  std::string input_name_stripped(input_name);\n  size_t slash_index = input_name_stripped.find_last_of('/');\n  if (slash_index == std::string::npos)\n    slash_index = input_name_stripped.find_last_of('\\\\');\n  if (slash_index == std::string::npos)\n    slash_index = 0;\n  else\n    ++slash_index;\n  input_name_stripped = input_name_stripped.substr(\n                                                   slash_index, input_name_stripped.find_last_of('.') - slash_index);\n\n  GUDHI_TC_SET_PERFORMANCE_DATA(\"Num_points_in_input\", points.size());\n\n#ifdef GUDHI_TC_USE_ANOTHER_POINT_SET_FOR_TANGENT_SPACE_ESTIM\n  std::vector<Point> points_not_sparse = points;\n#endif\n\n  //===========================================================================\n  // Sparsify point set if requested\n  //===========================================================================\n  if (sparsity > 0.) {\n    std::size_t num_points_before = points.size();\n    std::vector<Point> sparsified_points;\n    subsampl::sparsify_point_set(k, points, sparsity*sparsity,\n                                 std::back_inserter(sparsified_points));\n    sparsified_points.swap(points);\n    std::cerr << \"Number of points before/after sparsification: \"\n        << num_points_before << \" / \" << points.size() << \"\\n\";\n\n#ifdef GUDHI_TC_EXPORT_SPARSIFIED_POINT_SET\n    std::ofstream ps_stream(\"output/sparsified_point_set.txt\");\n    tc::internal::export_point_set(k, points, ps_stream);\n#endif\n  }\n\n  GUDHI_TC_SET_PERFORMANCE_DATA(\"Sparsity\", sparsity);\n  GUDHI_TC_SET_PERFORMANCE_DATA(\"Max_perturb\", max_perturb);\n  GUDHI_TC_SET_PERFORMANCE_DATA(\"Num_points\", points.size());\n\n  //===========================================================================\n  // Compute Tangential Complex\n  //===========================================================================\n\n  TC tc(\n        points,\n        intrinsic_dim,\n#ifdef GUDHI_TC_USE_ANOTHER_POINT_SET_FOR_TANGENT_SPACE_ESTIM\n      points_not_sparse.begin(), points_not_sparse.end(),\n#endif\n      k);\n\n  if (!tangent_spaces.empty()) {\n    tc.set_tangent_planes(tangent_spaces);\n  }\n\n  t.end();\n  double init_time = t.num_seconds();\n\n  t.begin();\n  tc.compute_tangential_complex();\n  t.end();\n  double computation_time = t.num_seconds();\n\n  //===========================================================================\n  // Export to OFF\n  //===========================================================================\n\n  // Create complex\n  int max_dim = -1;\n  TC::Simplicial_complex complex;\n  Simplex_set inconsistent_simplices;\n  max_dim = tc.create_complex(complex, true, false, 2, &inconsistent_simplices);\n\n  // TODO(CJ): TEST\n  Gudhi::Simplex_tree<> stree;\n  tc.create_complex(stree, true, false);\n  // std::cerr << stree;\n\n  t.begin();\n  bool ret = export_to_off(\n                           tc, input_name_stripped, \"_INITIAL_TC\", true,\n                           &complex, &inconsistent_simplices);\n  t.end();\n  double export_before_time = (ret ? t.num_seconds() : -1);\n\n  unsigned int num_perturb_steps = 0;\n  double perturb_time = -1;\n  double export_after_perturb_time = -1.;\n  bool perturb_success = false;\n  if (perturb) {\n    //=========================================================================\n    // Try to fix inconsistencies by perturbing points\n    //=========================================================================\n    t.begin();\n    auto fix_result =\n        tc.fix_inconsistencies_using_perturbation(max_perturb, time_limit_for_perturb);\n    t.end();\n    perturb_time = t.num_seconds();\n\n    perturb_success = fix_result.success;\n    GUDHI_TC_SET_PERFORMANCE_DATA(\"Initial_num_inconsistent_local_tr\",\n                                  fix_result.initial_num_inconsistent_stars);\n    GUDHI_TC_SET_PERFORMANCE_DATA(\"Best_num_inconsistent_local_tr\",\n                                  fix_result.best_num_inconsistent_stars);\n    GUDHI_TC_SET_PERFORMANCE_DATA(\"Final_num_inconsistent_local_tr\",\n                                  fix_result.final_num_inconsistent_stars);\n\n    //=========================================================================\n    // Export to OFF\n    //=========================================================================\n\n    // Re-build the complex\n    Simplex_set inconsistent_simplices;\n    max_dim = tc.create_complex(complex, true, false, 2, &inconsistent_simplices);\n\n    t.begin();\n    bool exported = export_to_off(\n                                  tc, input_name_stripped, \"_AFTER_FIX\", true, &complex,\n                                  &inconsistent_simplices);\n    t.end();\n    export_after_perturb_time = (exported ? t.num_seconds() : -1);\n\n    //std::string fn = \"output/inc_stars/\";\n    //fn += input_name_stripped;\n    //tc.export_inconsistent_stars_to_OFF_files(fn);\n\n#if !defined(TC_NO_EXPORT) && defined(TC_EXPORT_TO_RIB)\n    std::ofstream rib(std::string(\"output/\") + input_name_stripped + \".rib\");\n    RIB_exporter<TC::Points, TC::Simplicial_complex::Simplex_set> rib_exporter(\n                                                                               tc.points(),\n                                                                               complex.simplex_range(),\n                                                                               rib,\n                                                                               input_name_stripped + \".tif\",\n                                                                               false,  // is_preview\n                                                                               std::make_tuple(2, 4, 6),\n                                                                               1600, 503  // resolution\n                                                                               );\n    rib_exporter.write_file();\n\n    std::ofstream rib_LQ(std::string(\"output/\") + input_name_stripped + \"_LQ.rib\");\n    RIB_exporter<TC::Points, TC::Simplicial_complex::Simplex_set> rib_exporter_LQ(\n                                                                                  tc.points(),\n                                                                                  complex.simplex_range(),\n                                                                                  rib_LQ,\n                                                                                  input_name_stripped + \"_LQ.tif\",\n                                                                                  true,  // is_preview\n                                                                                  std::make_tuple(0, 4, 5)\n                                                                                  );\n    rib_exporter_LQ.write_file();\n#endif\n  } else {\n    GUDHI_TC_SET_PERFORMANCE_DATA(\"Initial_num_inconsistent_local_tr\", \"N/A\");\n    GUDHI_TC_SET_PERFORMANCE_DATA(\"Best_num_inconsistent_local_tr\", \"N/A\");\n    GUDHI_TC_SET_PERFORMANCE_DATA(\"Final_num_inconsistent_local_tr\", \"N/A\");\n  }\n\n  max_dim = tc.create_complex(complex, true, false, 2);\n\n  complex.display_stats();\n\n  if (intrinsic_dim == 2)\n    complex.euler_characteristic(true);\n\n  //===========================================================================\n  // Collapse\n  //===========================================================================\n  if (collapse) {\n    complex.collapse(max_dim);\n    complex.display_stats();\n  }\n\n  //===========================================================================\n  // Is the result a pure pseudomanifold?\n  //===========================================================================\n  std::size_t num_wrong_dim_simplices,\n      num_wrong_number_of_cofaces,\n      num_unconnected_stars;\n  Simplex_set wrong_dim_simplices;\n  Simplex_set wrong_number_of_cofaces_simplices;\n  Simplex_set unconnected_stars_simplices;\n  bool is_pure_pseudomanifold = complex.is_pure_pseudomanifold(\n                                                               intrinsic_dim, tc.number_of_vertices(),\n                                                               false,  // do NOT allow borders\n                                                               false, 1,\n                                                               &num_wrong_dim_simplices, &num_wrong_number_of_cofaces,\n                                                               &num_unconnected_stars,\n                                                               &wrong_dim_simplices, &wrong_number_of_cofaces_simplices,\n                                                               &unconnected_stars_simplices);\n\n  //===========================================================================\n  // Export to OFF\n  //===========================================================================\n\n  double export_after_collapse_time = -1.;\n  if (collapse) {\n    t.begin();\n    bool exported = export_to_off(\n                                  tc, input_name_stripped, \"_AFTER_COLLAPSE\", false, &complex,\n                                  &wrong_dim_simplices, &wrong_number_of_cofaces_simplices,\n                                  &unconnected_stars_simplices);\n    t.end();\n    std::cerr\n        << \" OFF colors:\\n\"\n        << \"   * Red: wrong dim simplices\\n\"\n        << \"   * Green: wrong number of cofaces simplices\\n\"\n        << \"   * Blue: not-connected stars\\n\";\n    export_after_collapse_time = (exported ? t.num_seconds() : -1.);\n  }\n\n  //===========================================================================\n  // Display info\n  //===========================================================================\n\n  std::cerr\n      << \"\\n================================================\\n\"\n      << \"Number of vertices: \" << tc.number_of_vertices() << \"\\n\"\n      << \"Computation times (seconds): \\n\"\n      << \"  * Tangential complex: \" << init_time + computation_time << \"\\n\"\n      << \"    - Init + kd-tree = \" << init_time << \"\\n\"\n      << \"    - TC computation = \" << computation_time << \"\\n\"\n      << \"  * Export to OFF (before perturb): \" << export_before_time << \"\\n\"\n      << \"  * Fix inconsistencies 1: \" << perturb_time\n      << \" (\" << num_perturb_steps << \" steps) ==> \"\n      << (perturb_success ? \"FIXED\" : \"NOT fixed\") << \"\\n\"\n      << \"  * Export to OFF (after perturb): \" << export_after_perturb_time << \"\\n\"\n      << \"  * Export to OFF (after collapse): \"\n      << export_after_collapse_time << \"\\n\"\n      << \"================================================\\n\";\n\n  //===========================================================================\n  // Export info\n  //===========================================================================\n  GUDHI_TC_SET_PERFORMANCE_DATA(\"Init_time\", init_time);\n  GUDHI_TC_SET_PERFORMANCE_DATA(\"Comput_time\", computation_time);\n  GUDHI_TC_SET_PERFORMANCE_DATA(\"Perturb_successful\",\n                                (perturb_success ? 1 : 0));\n  GUDHI_TC_SET_PERFORMANCE_DATA(\"Perturb_time\", perturb_time);\n  GUDHI_TC_SET_PERFORMANCE_DATA(\"Perturb_steps\", num_perturb_steps);\n  GUDHI_TC_SET_PERFORMANCE_DATA(\"Result_pure_pseudomanifold\",\n                                (is_pure_pseudomanifold ? 1 : 0));\n  GUDHI_TC_SET_PERFORMANCE_DATA(\"Result_num_wrong_dim_simplices\",\n                                num_wrong_dim_simplices);\n  GUDHI_TC_SET_PERFORMANCE_DATA(\"Result_num_wrong_number_of_cofaces\",\n                                num_wrong_number_of_cofaces);\n  GUDHI_TC_SET_PERFORMANCE_DATA(\"Result_num_unconnected_stars\",\n                                num_unconnected_stars);\n  GUDHI_TC_SET_PERFORMANCE_DATA(\"Info\", \"\");\n}\n\nint main() {\n  CGAL::set_error_behaviour(CGAL::ABORT);\n\n#ifdef GUDHI_USE_TBB\n#ifdef _DEBUG\n  int num_threads = 1;\n#else\n  int num_threads = tbb::task_scheduler_init::default_num_threads() - 4;\n#endif\n#endif\n\n  std::ifstream script_file;\n  script_file.open(BENCHMARK_SCRIPT_FILENAME);\n  // Script?\n  // Script file format: each line gives\n  //    - Filename (point set) or \"generate_XXX\" (point set generation)\n  //    - Ambient dim\n  //    - Intrinsic dim\n  //    - Number of iterations with these parameters\n  if (script_file.is_open()) {\n    int i = 1;\n#ifdef GUDHI_USE_TBB\n#ifdef BENCHMARK_WITH_1_TO_MAX_THREADS\n    for (num_threads = 1;\n         num_threads <= tbb::task_scheduler_init::default_num_threads();\n         ++num_threads)\n#endif\n#endif\n      /*for (Concurrent_mesher_config::get().num_work_items_per_batch = 5 ;\n        Concurrent_mesher_config::get().num_work_items_per_batch < 100 ;\n        Concurrent_mesher_config::get().num_work_items_per_batch += 5)*/ {\n#ifdef GUDHI_USE_TBB\n      tbb::task_scheduler_init init(\n                                    num_threads > 0 ? num_threads : tbb::task_scheduler_init::automatic);\n#endif\n\n      std::cerr << \"Script file '\" << BENCHMARK_SCRIPT_FILENAME << \"' found.\\n\";\n      script_file.seekg(0);\n      while (script_file.good()) {\n        std::string line;\n        std::getline(script_file, line);\n        if (line.size() > 1 && line[0] != '#') {\n          boost::replace_all(line, \"\\t\", \" \");\n          boost::trim_all(line);\n          std::cerr << \"\\n\\n\";\n          std::cerr << \"*****************************************\\n\";\n          std::cerr << \"******* \" << line << \"\\n\";\n          std::cerr << \"*****************************************\\n\";\n          std::stringstream sstr(line);\n\n          std::string input;\n          std::string param1;\n          std::string param2;\n          std::string param3;\n          std::size_t num_points;\n          int ambient_dim;\n          int intrinsic_dim;\n          double sparsity;\n          double max_perturb;\n          char perturb, add_high_dim_simpl, collapse;\n          double time_limit_for_perturb;\n          int num_iteration;\n          sstr >> input;\n          sstr >> param1;\n          sstr >> param2;\n          sstr >> param3;\n          sstr >> num_points;\n          sstr >> ambient_dim;\n          sstr >> intrinsic_dim;\n          sstr >> sparsity;\n          sstr >> max_perturb;\n          sstr >> perturb;\n          sstr >> add_high_dim_simpl;\n          sstr >> collapse;\n          sstr >> time_limit_for_perturb;\n          sstr >> num_iteration;\n\n          for (int j = 0; j < num_iteration; ++j) {\n            std::string input_stripped = input;\n            size_t slash_index = input_stripped.find_last_of('/');\n            if (slash_index == std::string::npos)\n              slash_index = input_stripped.find_last_of('\\\\');\n            if (slash_index == std::string::npos)\n              slash_index = 0;\n            else\n              ++slash_index;\n            input_stripped = input_stripped.substr(\n                                                   slash_index, input_stripped.find_last_of('.') - slash_index);\n\n            GUDHI_TC_SET_PERFORMANCE_DATA(\"Input\", input_stripped);\n            GUDHI_TC_SET_PERFORMANCE_DATA(\"Param1\", param1);\n            GUDHI_TC_SET_PERFORMANCE_DATA(\"Param2\", param2);\n            GUDHI_TC_SET_PERFORMANCE_DATA(\"Param3\", param3);\n            GUDHI_TC_SET_PERFORMANCE_DATA(\"Ambient_dim\", ambient_dim);\n            GUDHI_TC_SET_PERFORMANCE_DATA(\"Intrinsic_dim\", intrinsic_dim);\n            GUDHI_TC_SET_PERFORMANCE_DATA(\"Perturb_technique\", \"Tangential_translation\");\n            GUDHI_TC_SET_PERFORMANCE_DATA(\"Perturb_which_points\", \"Center_vertex\");\n\n#ifdef GUDHI_USE_TBB\n            GUDHI_TC_SET_PERFORMANCE_DATA(\n                                          \"Num_threads\",\n                                          (num_threads == -1 ? tbb::task_scheduler_init::default_num_threads() : num_threads));\n#else\n            GUDHI_TC_SET_PERFORMANCE_DATA(\"Num_threads\", \"N/A\");\n#endif\n\n            std::cerr << \"\\nTC #\" << i << \"...\\n\";\n\n#ifdef GUDHI_TC_PROFILING\n            Gudhi::Clock t_gen;\n#endif\n\n            std::vector<Point> points;\n            TC::TS_container tangent_spaces;\n\n            if (input == \"generate_moment_curve\") {\n              points = Gudhi::generate_points_on_moment_curve<Kernel>(\n                                                                      num_points, ambient_dim,\n                                                                      std::atof(param1.c_str()), std::atof(param2.c_str()));\n            } else if (input == \"generate_plane\") {\n              points = Gudhi::generate_points_on_plane<Kernel>(\n                                                               num_points, intrinsic_dim, ambient_dim);\n            } else if (input == \"generate_sphere_d\") {\n              points = Gudhi::generate_points_on_sphere_d<Kernel>(\n                                                                  num_points, ambient_dim,\n                                                                  std::atof(param1.c_str()),  // radius\n                                                                  std::atof(param2.c_str()));  // radius_noise_percentage\n            } else if (input == \"generate_two_spheres_d\") {\n              points = Gudhi::generate_points_on_two_spheres_d<Kernel>(\n                                                                       num_points, ambient_dim,\n                                                                       std::atof(param1.c_str()),\n                                                                       std::atof(param2.c_str()),\n                                                                       std::atof(param3.c_str()));\n            } else if (input == \"generate_3sphere_and_circle_d\") {\n              GUDHI_CHECK(intrinsic_dim == 3,\n                          std::logic_error(\"Intrinsic dim should be 3\"));\n              GUDHI_CHECK(ambient_dim == 5,\n                          std::logic_error(\"Ambient dim should be 5\"));\n              points = Gudhi::generate_points_on_3sphere_and_circle<Kernel>(\n                                                                            num_points,\n                                                                            std::atof(param1.c_str()));\n            } else if (input == \"generate_torus_3D\") {\n              points = Gudhi::generate_points_on_torus_3D<Kernel>(\n                                                                  num_points,\n                                                                  std::atof(param1.c_str()),\n                                                                  std::atof(param2.c_str()),\n                                                                  param3 == \"Y\");\n            } else if (input == \"generate_torus_d\") {\n              points = Gudhi::generate_points_on_torus_d<Kernel>(\n                                                                 num_points,\n                                                                 intrinsic_dim,\n                                                                 (param1 == \"Y\") ? \"grid\" : \"random\",  // grid or random sample type\n                                                                 std::atof(param2.c_str()));  // radius_noise_percentage\n            } else if (input == \"generate_klein_bottle_3D\") {\n              points = Gudhi::generate_points_on_klein_bottle_3D<Kernel>(\n                                                                         num_points,\n                                                                         std::atof(param1.c_str()), std::atof(param2.c_str()));\n            } else if (input == \"generate_klein_bottle_4D\") {\n              points = Gudhi::generate_points_on_klein_bottle_4D<Kernel>(\n                                                                         num_points,\n                                                                         std::atof(param1.c_str()), std::atof(param2.c_str()),\n                                                                         std::atof(param3.c_str()));  // noise\n            } else if (input == \"generate_klein_bottle_variant_5D\") {\n              points = Gudhi::generate_points_on_klein_bottle_variant_5D<Kernel>(\n                                                                                 num_points,\n                                                                                 std::atof(param1.c_str()), std::atof(param2.c_str()));\n            } else {\n              // Contains tangent space basis\n              if (input.substr(input.size() - 3) == \"pwt\") {\n                load_points_and_tangent_space_basis_from_file\n                    <Kernel, typename TC::Tangent_space_basis > (\n                                                                 input, std::back_inserter(points),\n                                                                 std::back_inserter(tangent_spaces),\n                                                                 intrinsic_dim,\n                                                                 ONLY_LOAD_THE_FIRST_N_POINTS);\n              } else {\n                load_points_from_file<Kernel>(\n                                              input, std::back_inserter(points),\n                                              ONLY_LOAD_THE_FIRST_N_POINTS);\n              }\n            }\n\n#ifdef GUDHI_TC_PROFILING\n            t_gen.end();\n            std::cerr << \"Point set generated/loaded in \" << t_gen.num_seconds()\n                << \" seconds.\\n\";\n#endif\n\n            if (!points.empty()) {\n#if defined(TC_INPUT_STRIDES) && TC_INPUT_STRIDES > 1\n              auto p = points | boost::adaptors::strided(TC_INPUT_STRIDES);\n              std::vector<Point> points(p.begin(), p.end());\n              std::cerr << \"****************************************\\n\"\n                  << \"WARNING: taking 1 point every \" << TC_INPUT_STRIDES\n                  << \" points.\\n\"\n                  << \"****************************************\\n\";\n#endif\n\n              make_tc(points, tangent_spaces, intrinsic_dim,\n                      sparsity, max_perturb,\n                      perturb == 'Y', add_high_dim_simpl == 'Y', collapse == 'Y',\n                      time_limit_for_perturb, input.c_str());\n\n              std::cerr << \"TC #\" << i++ << \" done.\\n\";\n              std::cerr << \"\\n---------------------------------\\n\";\n            } else {\n              std::cerr << \"TC #\" << i++ << \": no points loaded.\\n\";\n            }\n\n            XML_perf_data::commit();\n          }\n        }\n      }\n      script_file.seekg(0);\n      script_file.clear();\n    }\n\n    script_file.close();\n  }    // Or not script?\n  else {\n    std::cerr << \"Script file '\" << BENCHMARK_SCRIPT_FILENAME << \"' NOT found.\\n\";\n  }\n\n  // system(\"pause\");\n  return 0;\n}\n", "meta": {"hexsha": "6da1425fbe171214b9ccbb2d0f8bba1e1bf3c4f1", "size": 32176, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Tangential_complex/benchmark/benchmark_tc.cpp", "max_stars_repo_name": "VincentRouvreau/gudhi-devel", "max_stars_repo_head_hexsha": "c6a7f0258406542b0c2b10bb6b2878f27b13394b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-05T05:45:06.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-05T05:45:06.000Z", "max_issues_repo_path": "src/Tangential_complex/benchmark/benchmark_tc.cpp", "max_issues_repo_name": "gspr/gudhi-devel", "max_issues_repo_head_hexsha": "6b8f24647a6f290f4e2f2f307de660dfae93cc90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Tangential_complex/benchmark/benchmark_tc.cpp", "max_forks_repo_name": "gspr/gudhi-devel", "max_forks_repo_head_hexsha": "6b8f24647a6f290f4e2f2f307de660dfae93cc90", "max_forks_repo_licenses": ["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.1457800512, "max_line_length": 135, "alphanum_fraction": 0.5167516161, "num_tokens": 6620, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.45166702209691106}}
{"text": "#ifndef __SPARSEINDEXSET__CLASS__\n#define __SPARSEINDEXSET__CLASS__\n\n// Eigen Library\n#include <Eigen/Dense>\n\n#include \"CONSTANTS.hpp\"\n\nclass SparseIndexSet {\n public:\n  /**     \\brief initializes the sparse anisotropic index set\n  *       \\param[in] q is the maximum level for the sparse index set\n  *       \\param[in] dim is the dimension of the sparse index set\n  *       \\param[in] cpFun is the comparison Function. sparse index set is\n  *                  constructed such that cpFun(alpha) <= q for all alpha in\n  *                  the sparse index set\n  *\n  * \t    Additionally, the set of multiindices _alpha and the weights _cw\n  *     \t are provided globally.\n  *\n  * \t    The function comp_indexSet computes a sparse multi index set\n  * \t    _alpha\\subset\\N^n by the function call\n  *       sparseIndexSet::Yw_alpha(0, &n, cpFun)\n  * \t    and corresponding weights _cw \\in \\Z^n to each multi index.\n  * \t    To determine the weights, we have to check for each multi index\n  *       alpha contained in _alpha if alpha + beta is in _alpha for each beta \n  *       in {0,1}^{n}. If this is the case, we update the weight by \n  *       (-1)^|beta|. Of course, the condition is always fulfilled for the \n  *       multiindex beta = 0. Therefore, we skip this multiindex and initialize\n  *       the weight cw with 1 which is associated with the second variable in\n  *       the function call to cw_alpha.\n  * \t    For a multi index alpha, the corresponding weight has only to be\n  *       computed if the multiindex alpha+1 is not contained in _alpha.\n  *       Otherwise, the corresponding weight is 0. With the index set, the\n  *       weights and the unidirectional quadrature formulas at hand, the\n  *       integral I(f) is approximated by the combination technique formula\n  * \t    I(f) \\approx \\sum_{i =0}^{_alpha.cols-1} _cw(i)*Q_{alpha.col(i)}.\n  * \t    Herein, _alpha.cols determines the number of multiindices in _alpha\n  *       and alpha.col(i) gives the i-th index in _alpha. The tensor product\n  *       quadrature formula Q_{alpha.col(i)} is specified by the unidirectional\n  *       quadrature formulas.\n  */\n  template <class Compare>\n  void computeIndexSet(int q, int dim, const Compare &cpFun) {\n    int k = 0;\n    Eigen::VectorXi currInd(dim);\n    // set max level for the sparse index set\n    _q = q;\n    // set dimension of the sparse grid\n    _dim = dim;\n    // allocate memory for _alpha and _cw to keep the overhead at a low level\n    // blocks of size __MEMCHUNKSIZE__ are allocated at once\n    _alpha.resize(_dim, __MEMCHUNKSIZE__);\n    _cw.resize(__MEMCHUNKSIZE__);\n    // set memory to 0\n    _alpha.setZero();\n    _cw.setZero();\n    // get a vector with all ones to reduce the overhead for the constructor of\n    // Eigen::VectorXi::Ones(_dim);\n    _myOnes = Eigen::VectorXi::Ones(_dim);\n    // start from multi index 0\\in Xw_alpha\n    currInd.setZero();\n    k = 0;\n    // test if 0 is in Xw_alpha, else index set empty due to downward closedness\n    if (cpFun(currInd) <= _q) {\n      // check if _cw(0)\\neq 0\n      if (cpFun(_myOnes) > _q) _cw(0) = combiWeights(0, 1, 1, currInd, cpFun);\n      if (_cw(0)) ++k;\n      // compute all other indices in Yw_alpha recursively\n      combiIndexSet(0, &k, cpFun, currInd);\n    }\n    // crop memory for _alpha and _cw to actual size\n    _alpha.conservativeResize(_dim, k);\n    _cw.conservativeResize(k);\n  }\n\n  /**   \\brief make an educated guess, what this function does...\n  *\n  */\n  const Eigen::MatrixXi &get_alpha(void) const { return _alpha; };\n\n  /**   \\brief make an educated guess, what this function does...\n  *\n  */\n  const Eigen::VectorXi &get_cw(void) const { return _cw; };\n\n protected:\n  /**     \\brief computes indices in weighted sparse grid space (recursive)\n  *\t    \\param[in] maxBit position of the digit of the current multiindex\n  *                  such that only digits with position greater or equal to\n  *                  maxBit are considered in the recursion.\n  *\t \t \\param[in] k counter for the number of multiindices is passed\n  *                  as pointer\n  *\t    \\param[in] cpFun function/functor/whatever which decides whether a\n  *                  multiindex is in the indexset or not.\n  *\n  *\t    Additionally, the level of the sparse grid _q, the dimension of the\n  *\t    multiindices _dim and the memory _alpha for the indexset is\n  *\t    provided globally and referred to.\n  *\n  *\t    The function Yw_alpha recursively computes the indexset of a\n  *\t    generalized sparse grid which is described by a level _q and a\n  *\t    function cpFun, i.e. it finds all multiindices alpha such that\n  *\t    cpFun(alpha)<= _q. To that end, we travel the set Xw_alpha and\n  *       at a multi index only if the corresponding _cw is non zero.\n  *\t    The function needs to be called with input parameters\n  *\t    maxBit=0, k=0 defined as a reference, predefined\n  *\t    function cpFun which maps from \\mathbb{N}^{_dim}\\to \\mathbb{R}.\n  *\t    Since cpFun(0)=0, the zero multiindex is always the first index\n  *\t    which is included in the sparse grid on default and serves as the\n  *\t    root node in the tree structure of the index set.\n  *\t    On level l of the tree, all indices alpha with\n  *\t    cpFun(alpha)<= _q and |alpha| = l-1 are computed.\n  *\t    Moreover, the tree is structured such that all indices alpha' which\n  *\t    are sons of a multiindex alpha fulfill alpha'>=alpha elementwise.\n  *\t    This structure immediately allows to exploit the downward closeness\n  *\t    of the indexset since we do not need a further recursion level\n  *\t    at an edge where the corresponding index does not belong to the\n  *       indexset.\n  *\t    Moreover, the integer maxBit is necessary to avoid multiple\n  *       repetition of multiindices. In every step maxBit is the position of\n  *       the digit which is modified to obtain the current multiindex. In the\n  *       subtree corresponding to this index only digits greater or equal to\n  *       maxBit will be considered for modification. A simple example for the\n  *       tree structure for _q=2, _dim=2 and cpFun(alpha) = alpha_1+alpha_2 is\n  *       depicted below.\n  *\n  *\t\t\t\t\t\t\t\t(0,0;mB=0;*k=0)\n  *\t\t\t\t\t\t\t\t/            \\\n  *\t\t\t\t\t\t(1,0;mB=0;*k=1) (0,1;mB=1;*k=4)\n  *\t\t\t\t\t\t/\t\t      \\               \\\n  *\t\t\t(2,0;mB=0;*k=2) (1,1;mB=1;*k=3)\t(0,2;mB=1;*k=5)\n  *\n  */\n  template <class Compare>\n  void combiIndexSet(int maxBit, int *k, const Compare &cpFun,\n                     Eigen::VectorXi &currInd) {\n    int cw = 0;\n    // successively increase all entries in the current index\n    for (int i = maxBit; i < _dim; ++i) {\n      ++currInd(i);\n      if (cpFun(currInd) <= _q) {\n        // if the index is in Xw_alpha, check if its weight is non zero\n        if (cpFun(currInd + _myOnes) > _q)\n          cw = combiWeights(0, 1, 1, currInd, cpFun);\n        else\n          cw = 0;\n        // if its weight is non zero, add it to the index set\n        if (cw) {\n          if (_alpha.cols() <= *k) {\n            _alpha.conservativeResize(_dim, _alpha.cols() + __MEMCHUNKSIZE__);\n            _cw.conservativeResize(_cw.size() + __MEMCHUNKSIZE__);\n          }\n          _alpha.col(*k) = currInd;\n          _cw(*k) = cw;\n          ++(*k);\n        }\n        // check son indices only if father index is in Xw. this is possible\n        // due to the downward closedness assumption\n        combiIndexSet(i, k, cpFun, currInd);\n      }\n      --currInd(i);\n    }\n  }\n\n  /**     \\brief computes weights for the tensor product quadrature (recursive)\n  *\t    \\param[in] maxBit position of the digit of the current multiindex\n  *                  such that only digits with position greater to maxBit are\n  *\t \t\t         considered in the recursion.\n  *       \\param[in] cw is initialize by 1 due to alpha+0\\in Xw if alpha in Xw\n  *\t    \\param[in] lvl current level-1 in the recursion tree.\n  *\t    \\param[in] ind current multi index alpha\n  *\t    \\param[in] cpFun function/functor/whatever which decides whether a\n  *                  multi index is in the indexset or not.\n  *\n  *\t    Additionally, the level of the sparse grid _q, the dimension of the\n  *\t    multiindices _dim and the memory _alpha for the indexset is\n  *\t    provided globally.\n  *\n  *\t    The function cw_alpha computes the coefficient of the indth\n  *\t    multi index in the combination technique formula corresponding to\n  *\t    the generalized sparse quadrature. This coefficient is given by\n  *\t    cw(alpha) = sum_{beta in {0,1}^_dim, alpha+beta in _alpha}\n  *       (-1)^|beta|. Hence, in order to determine the value of the\n  *       coefficient, we have to check for each beta in {0,1}^_dim if\n  *       alpha+beta belongs to the index set _alpha. For beta=(0,...,0),\n  *       alpha+beta belongs to _alpha and, hence, we\n  *       initialize cw=1 and do not have to consider this multiindex.\n  *\t    The downward closeness of the index set can be exploited once more\n  *\t    which results in a similar tree structure as in the function\n  *       Yw_alpha. The only difference of the tree is that once a digit of the\n  *       multiindex alpha is modified, we do not have to consider further\n  *       modification of this digit due to the condition beta in {0,1}^_dim.\n  *       This is realized in the recursive algorithm consider only digits which\n  *       are greater than maxBit in contrast to the \"greater than and equal\"\n  *       condition in Yw_alpha.\n  *\t    In the recursive algorithm, the multiindices beta do not need to be\n  *       computed explicitly, but the multiindex alpha is modified at each node\n  *       of the tree. Of course, this modification has to be revoked when the\n  *       recursion goes back to the parent node in the tree.\n  *\t    The value of lvl=|beta| is important since it determines whether the\n  *\t    coefficient is modified by +1 or -1.\n  *\t    A simple example of the algorithm for _q=2, _dim=2, ind = (1,0) and\n  *\t    cpFun(alpha) = alpha_1+alpha_2 is depicted below.\n  *\t    The further initial values are maxBit=mB=0, cw = 1, lvl=0.\n  *\n  *\t\t\t\t\t\t\t\t(1,0;mB=0;lvl=0;cw=1)\n  *\t\t\t\t\t\t\t\t/                   \\\n  *\t\t\t\t\t(2,0;mB=0;lvl=1;cw=0)   (1,1;mB=1;lvl=1;cw=-1)\n  *\t\t\t\t\t\t\t/\n  *\t\t\t[ (2,1;mB=1;lvl=2;cw=0) ] <-- is not contained in the\n  *                                   indexset, no modification of cw\n  *\n  *\t    The algorithm returns the final value of cw. In the example above\n  *       this would be the correct value cw(1,0)=-1.\n  */\n  template <class Compare>\n  int combiWeights(int maxBit, int cw, int lvl, Eigen::VectorXi &ind,\n                   const Compare &cpFun) {\n    // successively check all bits of the multiindex is contained\n    for (int i = maxBit; i < _dim; ++i) {\n      ++ind(i);\n      if (cpFun(ind) <= _q) {\n        if (lvl % 2)\n          --cw;\n        else\n          ++cw;\n        // again, exploit downward closedness and perform recursion only\n        // if father is contained in Xw_alpha\n        cw = combiWeights(i + 1, cw, lvl + 1, ind, cpFun);\n      }\n      --ind(i);\n    }\n\n    return cw;\n  }\n\n  // Member variables\n  Eigen::MatrixXi _alpha;\n  Eigen::VectorXi _cw;\n  Eigen::VectorXi _myOnes;\n  int _dim;\n  int _q;\n};\n#endif\n", "meta": {"hexsha": "1909fad49357d46a787d2c8f7a60a8b6e83abaf2", "size": 11136, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "SparseIndexSet.hpp", "max_stars_repo_name": "T3ks/SPQR", "max_stars_repo_head_hexsha": "b554d172fc798caa7a708bfbbb71a21d136403b1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-09-11T12:02:57.000Z", "max_stars_repo_stars_event_max_datetime": "2016-09-11T12:02:57.000Z", "max_issues_repo_path": "SparseIndexSet.hpp", "max_issues_repo_name": "T3ks/SPQR", "max_issues_repo_head_hexsha": "b554d172fc798caa7a708bfbbb71a21d136403b1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SparseIndexSet.hpp", "max_forks_repo_name": "T3ks/SPQR", "max_forks_repo_head_hexsha": "b554d172fc798caa7a708bfbbb71a21d136403b1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-01-28T02:25:12.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-12T16:43:19.000Z", "avg_line_length": 45.2682926829, "max_line_length": 80, "alphanum_fraction": 0.6327227011, "num_tokens": 3088, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.45166702209691095}}
{"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_NEARBYINT_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_NEARBYINT_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-arithmetic\n    Function object implementing nearbyint capabilities\n\n    Computes the rounded to even value of its parameter.\n\n    @par semantic:\n    For any given value @c x of type @c T:\n\n    @code\n    T r = nearbyint(x);\n    @endcode\n\n    Returns the nearest integer to x.\n\n    @par Note:\n    - If arg is /f$\\infty/f$, it is returned, unmodified\n    - If arg is $\\pm0/f$, it is returned, unmodified\n    - If arg is NaN, NaN is returned\n\n    - to even means that half integer values are rounded to the nearest\n    even value.\n\n    This function is in general quicker than @ref round which do the rouding on\n    half integer values away from zero.\n\n    @see round, ceil, floor, trunc\n  **/\n  Value nearbyint(Value const & x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/nearbyint.hpp>\n#include <boost/simd/function/simd/nearbyint.hpp>\n\n#endif\n", "meta": {"hexsha": "9cc04f1f0adbc35bc68b5788f1554706531b39b8", "size": 1430, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/nearbyint.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/nearbyint.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/nearbyint.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": 26.0, "max_line_length": 100, "alphanum_fraction": 0.6097902098, "num_tokens": 319, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.6370307875894138, "lm_q1q2_score": 0.4516670172110818}}
{"text": "#include <stan/math/prim/scal.hpp>\n#include <gtest/gtest.h>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/math/distributions.hpp>\n#include <test/unit/math/prim/scal/prob/util.hpp>\n#include <limits>\n#include <vector>\n\nTEST(ProbDistributionsPareto, error_check) {\n  boost::random::mt19937 rng;\n  EXPECT_NO_THROW(stan::math::pareto_rng(2.0, 1.0, rng));\n\n  EXPECT_THROW(stan::math::pareto_rng(2.0, -1.0, rng), std::domain_error);\n  EXPECT_THROW(stan::math::pareto_rng(-2.0, 1.0, rng), std::domain_error);\n  EXPECT_THROW(\n      stan::math::pareto_rng(stan::math::positive_infinity(), 1.0, rng),\n      std::domain_error);\n  EXPECT_THROW(stan::math::pareto_rng(2, stan::math::positive_infinity(), rng),\n               std::domain_error);\n}\n\nTEST(ProbDistributionsPareto, chiSquareGoodnessFitTest) {\n  boost::random::mt19937 rng;\n  int N = 10000;\n  int K = boost::math::round(2 * std::pow(N, 0.4));\n\n  std::vector<double> samples;\n  for (int i = 0; i < N; ++i) {\n    samples.push_back(stan::math::pareto_rng(2.0, 1.0, rng));\n  }\n\n  // Generate quantiles from boost's Pareto distribution\n  boost::math::pareto_distribution<> dist(2.0, 1.0);\n  std::vector<double> quantiles;\n  for (int i = 1; i < K; ++i) {\n    double frac = static_cast<double>(i) / K;\n    quantiles.push_back(quantile(dist, frac));\n  }\n  quantiles.push_back(std::numeric_limits<double>::max());\n\n  // Assert that they match\n  assert_matches_quantiles(samples, quantiles, 1e-6);\n}\n", "meta": {"hexsha": "332c867822790bc38a829e7d57de4d36571461b9", "size": 1453, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/prim/scal/prob/pareto_test.cpp", "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": "test/unit/math/prim/scal/prob/pareto_test.cpp", "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": "test/unit/math/prim/scal/prob/pareto_test.cpp", "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": 33.0227272727, "max_line_length": 79, "alphanum_fraction": 0.686166552, "num_tokens": 455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.45166701232525275}}
{"text": "/*\n * Copyright 2014-2015 Arne Johanson\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n *     http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#ifndef MESH_RECT_HPP_\n#define MESH_RECT_HPP_\n\n#include <vector>\n#include <utility>\n#include <algorithm>\n#include <cstdlib>\n#include <limits>\n#include <forward_list>\n#include <boost/iterator/iterator_facade.hpp>\n#include \"config.hpp\"\n#include \"util.hpp\"\n#include \"interval.hpp\"\n#include \"numa.hpp\"\n#ifdef SPRAT_BUILD_WITH_MPI\n#include \"parallel.hpp\"\n#endif\n\n\nstruct RectMeshDimension {\n\tstd::string name;\n\n\tuint nElements;\n\tuint nNodes;\n\n\t//real totalIntervalLength;\n\n\tstd::vector<real> nodes;\n\tstd::vector<real> elementDiameter;\n\n\treal minElementDiameter;\n\n\n\tRectMeshDimension() {}\n\n\tRectMeshDimension(std::string name_in, Interval x_in, uint nElements_in, bool logarithmic = false) :\n\t\tname(name_in),\n\t\tnElements(nElements_in),\n\t\tnNodes(nElements_in+1),\n\t\tnodes(nElements_in+1),\n\t\telementDiameter(nElements_in)\n\t{\n\t\tif(!logarithmic) {\n\t\t\tfor(auto i : UIntRange(0, nNodes)) {\n\t\t\t\tnodes[i] = x_in.a + ((real)i/(real)nElements) * (x_in.b - x_in.a);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tconst real L_a = log10(x_in.a);\n\t\t\tconst real L_b = log10(x_in.b);\n\n\t\t\tfor(auto i : UIntRange(0, nNodes)) {\n\t\t\t\tnodes[i] = pow(10.0, L_a + ((real)i/(real)nElements) * (L_b - L_a));\n\t\t\t}\n\t\t}\n\n\t\tfor(auto i : UIntRange(0, nElements)) {\n\t\t\telementDiameter[i] = nodes[i+1] - nodes[i];\n\t\t}\n\t\tminElementDiameter = *std::min_element(elementDiameter.cbegin(), elementDiameter.cend());\n\t}\n\n#ifdef SPRAT_BUILD_WITH_MPI\n\tvoid send(ParallelExecutionEnvironment const& pEE, int toID) const {\n\t\tpEE.sendUInt(nElements, toID);\n\t\tpEE.sendUInt(nNodes, toID);\n\t\tpEE.sendReal(minElementDiameter, toID);\n\t\tpEE.sendVectorContent(nodes, toID);\n\t\tpEE.sendVectorContent(elementDiameter, toID);\n\t}\n\tvoid recv(ParallelExecutionEnvironment const& pEE, int fromID=0) {\n\t\tname = \"\";\n\t\tnElements = pEE.recvUInt(fromID);\n\t\tnNodes = pEE.recvUInt(fromID);\n\t\tminElementDiameter = pEE.recvReal(fromID);\n\t\tnodes.resize(nNodes);\n\t\tpEE.recvVectorContent(nodes);\n\t\telementDiameter.resize(nElements);\n\t\tpEE.recvVectorContent(elementDiameter);\n\t}\n#endif\n\n\tvoid print(std::string name=\"\") const {\n\t\tif(name.length()>0) {\n\t\t\tstd::cout << \"This is RectMeshDimension \" << name << \".\" << std::endl;\n\t\t}\n\t\telse {\n\t\t\tstd::cout << \"This is a RectMeshDimension.\" << std::endl;\n\t\t}\n\n\t\tstd::cout << \"I consist of \" << nElements << \" Elements and \" << nNodes << \" Nodes.\" << std::endl;\n\t\tstd::cout << \"My Interval is [\" << nodes[0] << \", \" << nodes[nNodes-1] << \"] and my shortest element diameter is \" << minElementDiameter << \".\" << std::endl;\n\t\tstd::cout << \"My nodes: \" << std::endl;\n\t\tprintVector(nodes);\n\t\tstd::cout << \"My element diameters: \" << std::endl;\n\t\tprintVector(elementDiameter);\n\t\tstd::cout << std::endl;\n\t}\n};\n\n\n\n\ntemplate <unsigned int Dim>\nclass FEMMeshRectP1 {\npublic:\n\tconstexpr static index_t noNeighbor       = INDEX_T_NO_NEIGHBOR;\n\tconstexpr static index_t noLocalNeighbor  = INDEX_T_NO_LOCAL_NEIGHBOR;\n\tconstexpr static index_t maxValidNeighbor = INDEX_T_MAX_VALID;\n\n\tconstexpr static unsigned int nDimensions() {\n\t\treturn Dim;\n\t}\n\tconstexpr static unsigned int nDoFPerElement() {\n\t\treturn twoToThePowerOfN(Dim);\n\t}\n\tconstexpr static unsigned int nHypersufacesPerElement() {\n\t\treturn 2*Dim;\n\t}\nprivate:\n\tstruct ElementData {\n\t\tshort_index_t multiIndex[Dim];\n\t\tindex_t dofIndices[nDoFPerElement()];\n\t\tindex_t neighborIndices[nHypersufacesPerElement()];\n\n#ifdef SPRAT_BUILD_WITH_MPI\n\t\tvoid send(ParallelExecutionEnvironment const& pEE, int toID) const {\n\t\t\tfor(uint i=0; i<Dim; ++i) {\n\t\t\t\tpEE.sendShortIndex(multiIndex[i], toID);\n\t\t\t}\n\t\t\tfor(uint i=0; i<nDoFPerElement(); ++i) {\n\t\t\t\tpEE.sendIndex(dofIndices[i], toID);\n\t\t\t}\n\t\t\tfor(uint i=0; i<nHypersufacesPerElement(); ++i) {\n\t\t\t\tpEE.sendIndex(neighborIndices[i], toID);\n\t\t\t}\n\t\t}\n\t\tvoid recv(ParallelExecutionEnvironment const& pEE, int fromID=0) {\n\t\t\tfor(uint i=0; i<Dim; ++i) {\n\t\t\t\tmultiIndex[i] = pEE.recvShortIndex(fromID);\n\t\t\t}\n\t\t\tfor(uint i=0; i<nDoFPerElement(); ++i) {\n\t\t\t\tdofIndices[i] = pEE.recvIndex(fromID);\n\t\t\t}\n\t\t\tfor(uint i=0; i<nHypersufacesPerElement(); ++i) {\n\t\t\t\tneighborIndices[i] = pEE.recvIndex(fromID);\n\t\t\t}\n\t\t}\n#endif\n\t\tvoid print(index_t i) const {\n\t\t\tstd::cout << \"Element \" << i << \" mit Multiindex ( \";\n\t\t\tfor(uint i=0; i<Dim; ++i) {\n\t\t\t\tstd::cout << multiIndex[i] << \" \";\n\t\t\t}\n\t\t\tstd::cout << \") und Freiheitsgraden \";\n\t\t\tfor(uint i=0; i<nDoFPerElement(); ++i) {\n\t\t\t\tstd::cout << dofIndices[i] << \" \";\n\t\t\t}\n\t\t\tstd::cout << std::endl;\n\t\t}\n\t};\n\tstruct DoFData {\n\t\tshort_index_t multiIndex[Dim];\n\n#ifdef SPRAT_BUILD_WITH_MPI\n\t\tvoid send(ParallelExecutionEnvironment const& pEE, int toID) const {\n\t\t\tfor(uint i=0; i<Dim; ++i) {\n\t\t\t\tpEE.sendShortIndex(multiIndex[i], toID);\n\t\t\t}\n\t\t}\n\t\tvoid recv(ParallelExecutionEnvironment const& pEE, int fromID=0) {\n\t\t\tfor(uint i=0; i<Dim; ++i) {\n\t\t\t\tmultiIndex[i] = pEE.recvShortIndex(fromID);\n\t\t\t}\n\t\t}\n#endif\n\t\tvoid print(index_t i) const {\n\t\t\tstd::cout << \"DoF \" << i << \" mit Multiindex ( \";\n\t\t\tfor(uint i=0; i<Dim; ++i) {\n\t\t\t\tstd::cout << multiIndex[i] << \" \";\n\t\t\t}\n\t\t\tstd::cout << \")\" << std::endl;\n\t\t}\n\t};\n\n\tnuma_vector<ElementData> _elementData;\n\tstd::vector<bool> _elementHasDomainBorder;\n\tstd::vector<index_t> _elementsWithDomainBorder;\n\tnuma_vector<DoFData> _dofData;\n\tindex_t _nLocalElements;\n\tindex_t _nLocalDoF;\n\n#ifdef SPRAT_BUILD_WITH_OPENMP\n\tstd::vector<std::forward_list<index_t>> _elementsOfDoF;\n\tstd::vector<numa_vector<index_t>> _independentElementDecomposition;\n#endif //#ifdef SPRAT_BUILD_WITH_OPENMP\n\n\tconstexpr static unsigned int twoToThePowerOfN(unsigned int n) {\n\t\treturn (n>0 ? 2*twoToThePowerOfN(n-1) : 1);\n\t}\n\n\tindex_t multiIndexToElementIndexInFullyPopulatedMesh(short_index_t multiIndex[Dim]) {\n\t\tindex_t result = multiIndex[0];\n\t\tfor(uint i=1; i<Dim; ++i) {\n\t\t\tresult *= dimensions[i].nElements;\n\t\t\tresult += multiIndex[i];\n\t\t}\n\t\treturn result;\n\t}\n\n\tvoid findElementsWithDomainBorder() {\n\t\t_elementsWithDomainBorder.resize(0);\n\t\t_elementHasDomainBorder.resize(_elementData.size());\n\t\tfor(index_t i=0; i<_elementData.size(); ++i) {\n\t\t\t_elementHasDomainBorder[i] = false;\n\t\t\tfor(uint k=0; k<nHypersufacesPerElement(); ++k) {\n\t\t\t\tif(_elementData[i].neighborIndices[k] == noNeighbor) {\n\t\t\t\t\t_elementHasDomainBorder[i] = true;\n\t\t\t\t\t_elementsWithDomainBorder.push_back(i);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid createElementsOfDoF(index_t numDoF, std::vector<ElementData> const& elemData) {\n#ifdef SPRAT_BUILD_WITH_OPENMP\n\t\t_elementsOfDoF.resize(numDoF);\n\n\t\tfor(index_t i=0; i<numDoF; ++i) {\n\t\t\t_elementsOfDoF[i].clear();\n\t\t}\n\n\t\tfor(index_t i=0; i<elemData.size(); ++i) {\n\t\t\tfor(uint k=0; k<nDoFPerElement(); ++k) {\n\t\t\t\t_elementsOfDoF[elemData[i].dofIndices[k]].push_front(i);\n\t\t\t}\n\t\t}\n#endif //#ifdef SPRAT_BUILD_WITH_OPENMP\n\t}\n\n\tvoid createMaximalIndependentElementSets(std::vector<ElementData> const& elemData) {\n#ifdef SPRAT_BUILD_WITH_OPENMP\n\t\tstatic constexpr uint noColor = std::numeric_limits<uint>::max();\n\t\t//static constexpr uint noColor = UINT_MAX; // For Intel compiler bug\n\t\tstd::vector<uint> elementColor(elemData.size(), noColor);\n\t\tindex_t nUncolored = elemData.size();\n\t\tuint nColors = 0;\n\n\t\tfor(uint currentColor=0; nUncolored>0; ++currentColor) {\n\t\t\tfor(index_t i=0; i<elemData.size(); ++i) {\n\t\t\t\tif(elementColor[i] != noColor) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tbool hasNeighbourOfCurrentColor = false;\n\t\t\t\tfor(uint k=0; k<nDoFPerElement() && !hasNeighbourOfCurrentColor; ++k) {\n\t\t\t\t\tconst index_t dof = elemData[i].dofIndices[k];\n\t\t\t\t\tfor(auto it=_elementsOfDoF[dof].cbegin(); it!=_elementsOfDoF[dof].cend(); ++it) {\n\t\t\t\t\t\tif(elementColor[*it] == currentColor) {\n\t\t\t\t\t\t\thasNeighbourOfCurrentColor = true;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif(!hasNeighbourOfCurrentColor) {\n\t\t\t\t\telementColor[i] = currentColor;\n\t\t\t\t\tnUncolored -= 1;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tnColors += 1;\n\t\t}\n\n\t\tstd::vector<std::vector<index_t>> independentElementDecompositionTemp(nColors);\n\t\tfor(uint color=0; color<nColors; ++color) {\n\t\t\tindependentElementDecompositionTemp[color].clear();\n\t\t}\n\t\tfor(index_t i=0; i<elemData.size(); ++i) {\n\t\t\tindependentElementDecompositionTemp[elementColor[i]].push_back(i);\n\t\t}\n\n\t\t_independentElementDecomposition.resize(nColors);\n\t\tfor(uint color=0; color<nColors; ++color) {\n\t\t\t_independentElementDecomposition[color].resize(independentElementDecompositionTemp[color].size());\n\t\t\tforeach_omp_index(i, _independentElementDecomposition[color].size(), shared(color,independentElementDecompositionTemp), {\n\t\t\t\t\t_independentElementDecomposition[color][i] = independentElementDecompositionTemp[color][i];\n\t\t\t})\n\t\t}\n\n\n\t\t// Debug output\n\t\t//for(index_t i=0; i<nElements(); ++i) {\n\t\t//\tstd::cout << \"Element \" << i << \" hat Farbe \" << elementColor[i] << std::endl;\n\t\t//}\n\t\t//std::cout << std::endl;\n\t\t//for(uint color=0; color<nColors; ++color) {\n\t\t//\tstd::cout << \"Farbe \" << color << \" haben die Elemente:\";\n\t\t//\tfor(index_t i=0; i<_independentElementDecomposition[color].size(); ++i) {\n\t\t//\t\tstd::cout << \" \" << _independentElementDecomposition[color][i];\n\t\t//\t}\n\t\t//\tstd::cout << std::endl;\n\t\t//}\n#endif //#ifdef SPRAT_BUILD_WITH_OPENMP\n\t}\n\npublic:\n\tRectMeshDimension dimensions[Dim];\n\n\tFEMMeshRectP1() {}\n\n\tFEMMeshRectP1(std::vector<RectMeshDimension> const& dimensions_in) :\n\t\tFEMMeshRectP1(&dimensions_in[0]) {}\n\n\tFEMMeshRectP1(RectMeshDimension const * const dimensions_in) {\n\t\tindex_t totalElements = 1;\n\t\tindex_t totalDoF = 1;\n\t\tfor(uint i=0; i<Dim; ++i) {\n\t\t\tdimensions[i] = dimensions_in[i];\n\t\t\ttotalElements *= dimensions[i].nElements;\n\t\t\ttotalDoF *= dimensions[i].nNodes;\n\t\t}\n\n\t\tstd::vector<ElementData> elementDataTemp(totalElements);\n\t\t_nLocalElements = totalElements;\n\t\t_dofData.resize(totalDoF);\n\t\t_nLocalDoF = totalDoF;\n\t\t//std::cout << \"FEMMeshRectP1::FEMMeshRectP1: totalDoF=\"<<totalDoF<<\"_dofData.size()=\"<<_dofData.size()<<std::endl;\n\n\t\tfor(index_t index=0; index<totalElements; ++index) {\n\t\t\tfor(uint k=0; k<Dim; ++k) {\n\t\t\t\t// *** multiIndex\n\t\t\t\tindex_t divideAway = index;\n\t\t\t\tfor(uint j=Dim-1; j>k; --j) {\n\t\t\t\t\tdivideAway /= dimensions[j].nElements;\n\t\t\t\t}\n\t\t\t\telementDataTemp[index].multiIndex[k] = divideAway % dimensions[k].nElements;\n\t\t\t}\n\t\t\tfor(uint k=0; k<Dim; ++k) {\n\t\t\t\t// *** neighborIndices\n\t\t\t\tif(elementDataTemp[index].multiIndex[k] == 0) { // find left neighbor\n\t\t\t\t\telementDataTemp[index].neighborIndices[2*k  ] = noNeighbor;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tshort_index_t leftNeighborIndex[Dim];\n\t\t\t\t\tfor(uint j=0; j<Dim; ++j) {\n\t\t\t\t\t\tleftNeighborIndex[j] = elementDataTemp[index].multiIndex[j];\n\t\t\t\t\t}\n\t\t\t\t\tleftNeighborIndex[k] -= 1;\n\t\t\t\t\telementDataTemp[index].neighborIndices[2*k  ] = multiIndexToElementIndexInFullyPopulatedMesh(leftNeighborIndex);\n\t\t\t\t}\n\n\t\t\t\tif(elementDataTemp[index].multiIndex[k] == dimensions[k].nElements-1) { // find right neighbor\n\t\t\t\t\telementDataTemp[index].neighborIndices[2*k+1] = noNeighbor;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tshort_index_t rightNeighborIndex[Dim];\n\t\t\t\t\tfor(uint j=0; j<Dim; ++j) {\n\t\t\t\t\t\trightNeighborIndex[j] = elementDataTemp[index].multiIndex[j];\n\t\t\t\t\t}\n\t\t\t\t\trightNeighborIndex[k] += 1;\n\t\t\t\t\telementDataTemp[index].neighborIndices[2*k+1] = multiIndexToElementIndexInFullyPopulatedMesh(rightNeighborIndex);\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor(uint k=0; k<nDoFPerElement(); ++k) {\n\t\t\t\t// *** dofIndices\n\t\t\t\tuint dofPosition[Dim];\n\t\t\t\tuint divideAway = k;\n\t\t\t\tfor(uint j=0; j<Dim; ++j) {\n\t\t\t\t\tdofPosition[Dim-1-j] = divideAway%2;\n\t\t\t\t\tdivideAway /= 2;\n\t\t\t\t}\n\t\t\t\tindex_t dofIndex = 0;\n\t\t\t\tfor(uint j=0; j<Dim; ++j) {\n\t\t\t\t\tdofIndex *= dimensions[j].nNodes;\n\t\t\t\t\tdofIndex += elementDataTemp[index].multiIndex[j] + dofPosition[j];\n\t\t\t\t}\n\t\t\t\telementDataTemp[index].dofIndices[k] = dofIndex;\n\t\t\t}\n\t\t}\n\n\n\t\tcreateElementsOfDoF(totalDoF, elementDataTemp);\n\t\tcreateMaximalIndependentElementSets(elementDataTemp);\n\n\t\t_elementData.resize(elementDataTemp.size());\n\t\tforeachElementIndependently(auto tau, *this, shared(elementDataTemp), {\n\t\t\t\t_elementData[tau] = elementDataTemp[tau];\n\t\t})\n\t\telementDataTemp.clear();\n\n\t\tfindElementsWithDomainBorder();\n\n\t\t//std::cout << \"There are \" << _elementData.size() << \" elements in the master mesh.\" << std::endl;\n\n\n\t\tforeach_omp_index(index, totalDoF, , {\n\t\t\tfor(uint k=0; k<Dim; ++k) {\n\t\t\t\tindex_t divideAway = index;\n\t\t\t\tfor(uint j=Dim-1; j>k; --j) {\n\t\t\t\t\tdivideAway /= dimensions[j].nNodes;\n\t\t\t\t}\n\t\t\t\t_dofData[index].multiIndex[k] = divideAway % dimensions[k].nNodes;\n\t\t\t}\n\t\t})\n\t}\n\n#ifdef SPRAT_BUILD_WITH_MPI\n\tvoid receiveStrideDecomposition(ParallelExecutionEnvironment const& pEE, MPCommunicationRegistry& comRegistry) {\n\t\t/*\n\t\t * Empfange:\n\t\t * - Dim RectMeshDimensions\n\t\t * - Anzahl an Elementen\n\t\t * - Anzahl an lokalen Elementen\n\t\t * - Die Elemente (ElementData + den globalen Index des Elements)  -- zuerst die eigenen Elemente!\n\t\t *   Es ist garantiert, dass die globalen Indizes der empfangen Elemente aufsteigend sind (gilt nat\u00fcrlich nur jeweils f\u00fcr eigene und Nachbarelemente)\n\t\t * - Anzahl an DoF\n\t\t * - Anzahl an lokalen DoF\n\t\t * - Die DoF (DoFData + den globalen Index des DoF + ID dem der Knoten geh\u00f6rt) -- zuerst die eigenen DoF!\n\t\t *   Es ist garantiert, dass die DoF der Nachbarn in sich auch jeweils zusammenh\u00e4ngen (daher der Sort beim senden!)\n\t\t *\n\t\t */\n\n\t\t//sleep(pEE.processID());\n\n\t\tfor(uint k=0; k<Dim; ++k) {\n\t\t\tdimensions[k].recv(pEE); // Receive Dimensions\n\t\t\t//dimensions[k].print();\n\t\t}\n\n\t\t// Receive Elements\n\t\tstd::vector<ElementData> elementDataTemp(pEE.recvIndex());\n\t\t//_elementData.resize(pEE.recvIndex());\n\t\tIndexVector globalElementIDs(elementDataTemp.size());\n\t\t_nLocalElements = pEE.recvIndex();\n\t\tfor(index_t i=0; i<elementDataTemp.size(); ++i) {\n\t\t\telementDataTemp[i].recv(pEE);\n\t\t\t//elementDataTemp[i].print(i);\n\t\t\tglobalElementIDs[i] = pEE.recvIndex();\n\t\t}\n\n\t\t// Receive local DoF\n\t\tstd::vector<DoFData> dofDataTemp(pEE.recvIndex());\n\t\t//_dofData.resize(pEE.recvIndex());\n\t\tcomRegistry.nDoF = dofDataTemp.size();\n\t\tcomRegistry.nLocalDoF = _nLocalDoF = pEE.recvIndex();\n\t\tcomRegistry.globalDofIndexVector.resize(dofDataTemp.size());\n\t\tfor(index_t i=0; i<_nLocalDoF; ++i) {\n\t\t\tdofDataTemp[i].recv(pEE);\n\t\t\t//dofDataTemp[i].print(i);\n\t\t\tcomRegistry.globalDofIndexVector[i] = pEE.recvIndex();\n\t\t\tpEE.recvInt();\n\t\t}\n\t\t// Receive ghost DoF\n\t\tcomRegistry.dofRecvFromNeighbor.resize(0);\n\t\tuint lastNeighbor = 0;\n\t\tfor(index_t i=_nLocalDoF; i<dofDataTemp.size(); ++i) {\n\t\t\tdofDataTemp[i].recv(pEE);\n\t\t\t//dofDataTemp[i].print(i);\n\t\t\tcomRegistry.globalDofIndexVector[i] = pEE.recvIndex();\n\t\t\tuint recvNeighbor = pEE.recvInt();\n\t\t\tif(lastNeighbor != recvNeighbor) {\n\t\t\t\t//std::cout << \"Empfange Geisterpkt von \" << recvNeighbor << std::endl;\n\t\t\t\tlastNeighbor = recvNeighbor;\n\t\t\t\tcomRegistry.dofRecvFromNeighbor.push_back(MPNeighborDoFIndexVector(0, recvNeighbor));\n\t\t\t}\n\t\t\tcomRegistry.dofRecvFromNeighbor.back().push_back(comRegistry.globalDofIndexVector[i]);\n\t\t\t//std::cout << i << \" -> \" << globalDofIndexVector[i] << std::endl;\n\t\t}\n\n\n\t\t// In den Element-Daten m\u00fcssen die Indizes der DoF auf lokale angepasst werden..\n\t\tfor(index_t i=0; i<elementDataTemp.size(); ++i) {\n\t\t\tfor(uint k=0; k<nDoFPerElement(); ++k) {\n\t\t\t\telementDataTemp[i].dofIndices[k] = comRegistry.globalDofIndexVector.inverse(elementDataTemp[i].dofIndices[k]);\n\t\t\t}\n\t\t\t//elementDataTemp[i].print(i);\n\t\t}\n\n\n\t\t//std::cout << \"This is node \" << pEE.processID() << \". I received \" << elementDataTemp.size() << \" Elements, \"\n\t\t//\t\t<< _nLocalDoF << \" \" << dofDataTemp.size() << std::endl;\n\n\n\t\t/*\n\t\t * F\u00fcr jeden Nachbarn: Ich schicke dem Nachbarn meine dofRecvFromNeighbor (das sind globale Indizes), die er mit regelm\u00e4\u00dfig zusenden soll\n\t\t * Er schickt mir die dofSendToNeighbor, die diejenigen globalen Indized beinhalten, die ich ihm schicken soll.\n\t\t */\n\t\tcomRegistry.dofSendToNeighbor.resize(comRegistry.dofRecvFromNeighbor.size());\n\t\tfor(uint i=0; i<pEE.nComputeProcesses(); ++i) { // Knoten i ist mit Senden dran\n\t\t\tfor(uint k=0; k<comRegistry.dofRecvFromNeighbor.size(); ++k) {\n\t\t\t\tif(pEE.processID() == i+1) { // Wenn ich dran bin verschicke ich alle.\n\t\t\t\t\tcomRegistry.dofRecvFromNeighbor[k].send(pEE);\n\t\t\t\t}\n\t\t\t\telse if(comRegistry.dofRecvFromNeighbor[k].neighborID == i+1) { // Wenn ich nicht dran bin empfange ich ggf. von dem der dran ist.\n\t\t\t\t\t//dofSendToNeighbor[k].neighborID = i+1;\n\t\t\t\t\tcomRegistry.dofSendToNeighbor[k].recv(pEE, i+1);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\n\t\t//sleep(pEE.nComputeProcesses() + pEE.processID());\n\n\t\t// Wandele die empfangenen dofSendToNeighbor in ein local-to-local mapping um (d.h. dofSendToNeighbor[i] beinhaltet\n\t\t// dann diejenigen lokalen Indizes, die ich i in der dadurch vorgegebenen Reihenfolge schicken soll (also als erstes dofSendToNeighbor[i][0]...).\n\t\tfor(uint i=0; i<comRegistry.dofSendToNeighbor.size(); ++i) {\n\t\t\tcomRegistry.dofSendToNeighbor[i].invertWith(comRegistry.globalDofIndexVector);\n\t\t\t//std::cout << \"Prozess \" << pEE.processID() << \" schickt an \" << comRegistry.dofSendToNeighbor[i].neighborID << \":\" << std::endl;\n\t\t\t//for(uint k=0; k<comRegistry.dofSendToNeighbor[i].size(); ++k) {\n\t\t\t//\tstd::cout << comRegistry.dofSendToNeighbor[i][k] << std::endl;\n\t\t\t//\tassert(comRegistry.dofSendToNeighbor[i][k] < _nLocalDoF);\n\t\t\t//}\n\t\t}\n\n\t\t// Tue das gleiche auch f\u00fcr die zu empangnenden DoF; Denn da stehen ja bis jetzt *globale* DoF drin!\n\t\tfor(uint i=0; i<comRegistry.dofRecvFromNeighbor.size(); ++i) {\n\t\t\tcomRegistry.dofRecvFromNeighbor[i].invertWith(comRegistry.globalDofIndexVector);\n\t\t\t//std::cout << \"Prozess \" << pEE.processID() << \" empf\u00e4ngt von \" << comRegistry.dofRecvFromNeighbor[i].neighborID << \":\" << std::endl;\n\t\t\t//for(uint k=0; k<comRegistry.dofRecvFromNeighbor[i].size(); ++k) {\n\t\t\t//\tstd::cout << comRegistry.dofRecvFromNeighbor[i][k] << std::endl;\n\t\t\t//\tassert(comRegistry.dofRecvFromNeighbor[i][k] >= _nLocalDoF);\n\t\t\t//}\n\t\t}\n\n\t\t// Jetzt muss ich noch die elementDoFRecvFrom/SendToNeighbor aus dofRecvFrom/SendToNeighbor kreieren.\n\t\t// Die elementDoFRecvFrom/SendToNeighbor beschreiben das gleiche wie die dofRecvFrom/SendToNeighbor\n\t\t// nur f\u00fcr Arrays von Elementvektoren.\n\t\t// Daf\u00fcr gehe ich f\u00fcr jeden zu sendenden/empfangenden DoF alle Nachbarelemente durch und notiere mir\n\t\t// alle Vorkomnisse dieses DoF nacheinander. Sobald die Nachbarelemente bei Sender und Empf\u00e4nger die\n\t\t// gleiche Sortierung haben, k\u00f6nnen Sender und Empf\u00e4nger ohne weitere Kommunikation einen\n\t\t// \"Austauschplan\" f\u00fcr die Element-DoF erzeugen.\n\t\tcomRegistry.elementDoFRecvFromNeighbor.resize(comRegistry.dofRecvFromNeighbor.size());\n\t\tfor(uint i=0; i<comRegistry.dofRecvFromNeighbor.size(); ++i) {\n\t\t\tcomRegistry.elementDoFRecvFromNeighbor[i].resize(0);\n\t\t\tcomRegistry.elementDoFRecvFromNeighbor[i].neighborID = comRegistry.dofRecvFromNeighbor[i].neighborID;\n\t\t\tfor(index_t j=0; j<comRegistry.dofRecvFromNeighbor[i].size(); ++j) {\n\t\t\t\tfor(index_t k=_nLocalElements; k<elementDataTemp.size(); ++k) {\n\t\t\t\t\tfor(uint l=0; l<nDoFPerElement(); ++l) {\n\t\t\t\t\t\tif(elementDataTemp[k].dofIndices[l] == comRegistry.dofRecvFromNeighbor[i][j]) {\n\t\t\t\t\t\t\tcomRegistry.elementDoFRecvFromNeighbor[i].push_back(k*nDoFPerElement() + l);\n\t\t\t\t\t\t\t//std::cout << \"Prozess \" << pEE.processID() << \" empf\u00e4ngt von \" << comRegistry.elementDoFRecvFromNeighbor[i].neighborID << \" an Position \" << comRegistry.elementDoFRecvFromNeighbor[i].size()-1 << \" den lokalen ElementDoF \" << k*nDoFPerElement() + l << std::endl;\n\t\t\t\t\t\t\t//assert(elementDataTemp[k].dofIndices[l] >= _nLocalDoF);\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\tcomRegistry.elementDoFSendToNeighbor.resize(comRegistry.dofSendToNeighbor.size());\n\t\tfor(uint i=0; i<comRegistry.dofSendToNeighbor.size(); ++i) {\n\t\t\tcomRegistry.elementDoFSendToNeighbor[i].resize(0);\n\t\t\tcomRegistry.elementDoFSendToNeighbor[i].neighborID = comRegistry.dofSendToNeighbor[i].neighborID;\n\t\t\tfor(index_t j=0; j<comRegistry.dofSendToNeighbor[i].size(); ++j) {\n\t\t\t\t//std::cout << \"Prozess \" << pEE.processID() << \" sendet an \" << comRegistry.dofSendToNeighbor[i].neighborID << \" an Position \" << j << \" den lokalen DoF \" << comRegistry.dofSendToNeighbor[i][j] << std::endl;\n\t\t\t\tfor(index_t k=_nLocalElements; k<elementDataTemp.size(); ++k) {\n\t\t\t\t\tfor(uint l=0; l<nDoFPerElement(); ++l) {\n\t\t\t\t\t\tif(elementDataTemp[k].dofIndices[l] == comRegistry.dofSendToNeighbor[i][j]) {\n\t\t\t\t\t\t\tcomRegistry.elementDoFSendToNeighbor[i].push_back(k*nDoFPerElement() + l);\n\t\t\t\t\t\t\t//std::cout << \"Prozess \" << pEE.processID() << \" sendet an \" << comRegistry.elementDoFSendToNeighbor[i].neighborID << \" an Position \" << comRegistry.elementDoFSendToNeighbor[i].size()-1 << \" den lokalen ElementDoF \" << k*nDoFPerElement() + l << std::endl;\n\t\t\t\t\t\t\t//assert(elementDataTemp[k].dofIndices[l] < _nLocalDoF);\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//sleep(pEE.nProcesses() + pEE.processID());\n\n\t\tcomRegistry.createMPITypes();\n\n\t\t/*\n\t\t * Abschlie\u00dfend muss ich die lokalen Indizes der Nachbarn der Elemente finden.\n\t\t * Dazu suche ich alle globalen Elementnachbar in globalElementIDs und ersetze sie durch den Index in diesem\n\t\t * Vektor. Falls sie nicht gefunden werden, muss ich sie auf noNeighbour setzen.\n\t\t */\n\t\tfor(index_t i=0; i<elementDataTemp.size(); ++i) {\n\t\t\tfor(uint k=0; k<nHypersufacesPerElement(); ++k) {\n\t\t\t\tif(elementDataTemp[i].neighborIndices[k] != noNeighbor) {\n\t\t\t\t\tindex_t localIndex = globalElementIDs.inverse(elementDataTemp[i].neighborIndices[k]);\n\t\t\t\t\telementDataTemp[i].neighborIndices[k] = (localIndex < globalElementIDs.end() - globalElementIDs.begin() ? localIndex : noLocalNeighbor);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tcreateElementsOfDoF(dofDataTemp.size(), elementDataTemp);\n\t\tcreateMaximalIndependentElementSets(elementDataTemp);\n\n\t\t_elementData.resize(elementDataTemp.size());\n\t\tforeachElementIndependently(auto tau, *this, shared(elementDataTemp), {\n\t\t\t_elementData[tau] = elementDataTemp[tau];\n\t\t})\n\t\telementDataTemp.clear();\n\t\t_dofData.resize(dofDataTemp.size());\n\t\tforeach_omp_index(i, dofDataTemp.size(), shared(dofDataTemp), {\n\t\t\t_dofData[i] = dofDataTemp[i];\n\t\t})\n\t\tdofDataTemp.clear();\n\n\t\tfindElementsWithDomainBorder();\n\t}\n\n\tvoid createAndDistributeStrideDecomposition(ParallelExecutionEnvironment const& pEE, std::vector<index_t>& dofStartIndexForProcess) const {\n\t\t/*\n\t\t * Der Master ist daf\u00fcr verantwortlich, die Elemente/DoF den Slaves so zu schicken, dass\n\t\t * sie lokal richtig geordnet sind. So hat der Master auch gleich eine Zuordnung von\n\t\t * lokalen zu globalen DoF/Elementen f\u00fcr jedes Teilgebiet.\n\t\t */\n\t\t//localToGlobalDoF.resize(pEE.nComputeProcesses());\n\n\t\t// Bestimme wie viele DoF jeder Prozess bekommt.\n\t\tdofStartIndexForProcess.resize(pEE.nComputeProcesses()+1);\n\t\tindex_t baseStep = nDoF()/pEE.nComputeProcesses();\n\t\tindex_t remainder = nDoF()%pEE.nComputeProcesses();\n\t\tdofStartIndexForProcess[0] = 0;\n\t\tfor(uint i=0; i<pEE.nComputeProcesses(); ++i) {\n\t\t\tdofStartIndexForProcess[i+1] = dofStartIndexForProcess[i] + baseStep + (i<remainder ? 1 : 0);\n\t\t}\n\n\n\t\tfor(uint i=0; i<pEE.nComputeProcesses(); ++i) {\n\t\t\tfor(uint k=0; k<Dim; ++k) {\n\t\t\t\tdimensions[k].send(pEE, i+1); // Send Dimensions\n\t\t\t}\n\n\t\t\t// Finde heraus, welche Elemente an Knoten i zu senden sind. Sammele ihre Indizes.\n\t\t\tstd::vector<index_t> elementsForThisProcess(0);\n\t\t\tfor(index_t j=0; j<_elementData.size(); ++j) {\n\t\t\t\tfor(uint k=0; k<nDoFPerElement(); ++k) {\n\t\t\t\t\t// Liegt der Dof im i-ten Gebiet?\n\t\t\t\t\tindex_t currentDoFIndex = _elementData[j].dofIndices[k];\n\t\t\t\t\tif(currentDoFIndex >= dofStartIndexForProcess[i] && currentDoFIndex < dofStartIndexForProcess[i+1]) {\n\t\t\t\t\t\telementsForThisProcess.push_back(j);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Zerteile die Elemente in i-rein-lokale und i-Nachbarelemente\n\t\t\tstd::vector<index_t> localElements(0);\n\t\t\tstd::vector<index_t> neighborElements(0);\n\t\t\tfor(index_t j=0; j<elementsForThisProcess.size(); ++j) {\n\t\t\t\tuint nLocalDoF = 0;\n\t\t\t\tfor(uint k=0; k<nDoFPerElement(); ++k) {\n\t\t\t\t\tindex_t currentDoFIndex = _elementData[elementsForThisProcess[j]].dofIndices[k];\n\t\t\t\t\tif(currentDoFIndex >= dofStartIndexForProcess[i] && currentDoFIndex < dofStartIndexForProcess[i+1]) {\n\t\t\t\t\t\tnLocalDoF+=1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif(nLocalDoF == nDoFPerElement()) { // rein lokal\n\t\t\t\t\tlocalElements.push_back(elementsForThisProcess[j]);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tneighborElements.push_back(elementsForThisProcess[j]);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Diese Sorts sind eigentlich \u00fcberfl\u00fcssig, da durch die Art der Konstruktion die aufsteigende globale Reihenfolge bereits festgelegt ist,.\n\t\t\tstd::sort(localElements.begin(), localElements.end());\n\t\t\tstd::sort(neighborElements.begin(), neighborElements.end());\n\t\t\t//std::cout << \"Prozess \" << i+1 << \" bekommt \" << localElements.size() + neighborElements.size() << \" Elemente. Davon sind \" << localElements.size() << \" rein lokal.\" << std::endl;\n\n\t\t\t// Versende die gefundenen Elemente..\n\t\t\tpEE.sendIndex(localElements.size() + neighborElements.size(), i+1); // nElements\n\t\t\tpEE.sendIndex(localElements.size(), i+1); // nLocalElements\n\t\t\tfor(index_t j=0; j<localElements.size(); ++j) {\n\t\t\t\t_elementData[localElements[j]].send(pEE, i+1);\n\t\t\t\tpEE.sendIndex(localElements[j], i+1); // der globale Index\n\t\t\t}\n\t\t\tfor(index_t j=0; j<neighborElements.size(); ++j) {\n\t\t\t\t_elementData[neighborElements[j]].send(pEE, i+1);\n\t\t\t\tpEE.sendIndex(neighborElements[j], i+1); // der globale Index\n\t\t\t}\n\n\t\t\t// Finde heraus, welche Nodes *zus\u00e4tzlich* an den i-ten Knoten gesendet werden m\u00fcssen und wem sie geh\u00f6ren.\n\t\t\t// Iteriere dazu \u00fcber die Elemente, die uns geh\u00f6ren und notiere alle Knoten, die nicht unsere sind.\n\t\t\t// Passe dabei aber auf, keine DoF doppelt hinzuzuf\u00fcgen!\n\t\t\tstd::vector<std::pair<index_t, int>> additionalDoF; // Paar aus Knotenindex und Besitzer.\n\t\t\tfor(index_t j=0; j<neighborElements.size(); ++j) {\n\t\t\t\tfor(uint k=0; k<nDoFPerElement(); ++k) {\n\t\t\t\t\t// Liegt der Dof im i-ten Gebiet?\n\t\t\t\t\tindex_t currentDoFIndex = _elementData[neighborElements[j]].dofIndices[k];\n\t\t\t\t\tif(currentDoFIndex < dofStartIndexForProcess[i] || currentDoFIndex >= dofStartIndexForProcess[i+1]) {\n\t\t\t\t\t\tint owner = 0;\n\t\t\t\t\t\tfor(uint l=0; l<dofStartIndexForProcess.size()-1; ++l) {\n\t\t\t\t\t\t\tif(currentDoFIndex >= dofStartIndexForProcess[l] && currentDoFIndex < dofStartIndexForProcess[l+1]) {\n\t\t\t\t\t\t\t\towner = l+1;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif(std::find(additionalDoF.begin(), additionalDoF.end(), std::pair<index_t, int>(currentDoFIndex, owner))==additionalDoF.end()) {\n\t\t\t\t\t\t\tadditionalDoF.push_back(std::pair<index_t, int>(currentDoFIndex, owner));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Sortiere die Freiheitsgrade so, dass diejenigen, die zu einem Nachbarn geh\u00f6ren zusammenh\u00e4ngen.\n\t\t\tstd::sort(additionalDoF.begin(), additionalDoF.end(),\n\t\t\t\t\t[](const std::pair<index_t, int>& lhs, const std::pair<index_t, int>& rhs) -> bool {\n\t\t\t\tif(lhs.second != rhs.second) {\n\t\t\t\t\treturn lhs.second < rhs.second;\n\t\t\t\t}\n\t\t\t\treturn lhs.first < rhs.first; // Dies hier sorgt daf\u00fcr, dass die DoF f\u00fcr einen Nachbarn in sich noch nach globalem Index geordnetet sind.\n\t\t\t} );\n\n\t\t\tindex_t nLocalDoFForThisProcess = dofStartIndexForProcess[i+1]-dofStartIndexForProcess[i];\n\t\t\tpEE.sendIndex(nLocalDoFForThisProcess + additionalDoF.size(), i+1); // nDoF\n\t\t\tpEE.sendIndex(nLocalDoFForThisProcess, i+1); // nLocalDoF\n\t\t\t//localToGlobalDoF[i].resize(nLocalDoFForThisProcess + additionalDoF.size());\n\t\t\tfor(index_t j=0; j<nLocalDoFForThisProcess; ++j) {\n\t\t\t\t_dofData[dofStartIndexForProcess[i] + j].send(pEE, i+1);\n\t\t\t\tpEE.sendIndex(dofStartIndexForProcess[i] + j, i+1); // der globale Index\n\t\t\t\t//localToGlobalDoF[i][j] = dofStartIndexForProcess[i] + j;\n\t\t\t\tpEE.sendInt(i+1, i+1); // der besitzer\n\t\t\t}\n\t\t\tfor(index_t j=0; j<additionalDoF.size(); ++j) {\n\t\t\t\t_dofData[additionalDoF[j].first].send(pEE, i+1);\n\t\t\t\tpEE.sendIndex(additionalDoF[j].first, i+1); // der globale Index\n\t\t\t\t//localToGlobalDoF[i][nLocalDoFForThisProcess + j] = additionalDoF[j].first;\n\t\t\t\tpEE.sendInt(additionalDoF[j].second, i+1); // der besitzer\n\t\t\t}\n\t\t}\n\t}\n#endif // SPRAT_BUILD_WITH_MPI\n\n\n#ifdef SPRAT_BUILD_WITH_OPENMP\n\tstd::vector<numa_vector<index_t>> const& getIndependentElementDecomposition() const {\n\t\treturn _independentElementDecomposition;\n\t}\n#endif //#ifdef SPRAT_BUILD_WITH_OPENMP\n\n\tindex_t nElements() const {\n\t\treturn _elementData.size();\n\t}\n\tindex_t nLocalElements() const {\n\t\treturn _nLocalElements;\n\t}\n\tindex_t nElementsWithDomainBorder() const {\n\t\treturn _elementsWithDomainBorder.size();\n\t}\n\tindex_t nDoF() const {\n\t\treturn _dofData.size();\n\t}\n\tindex_t nLocalDoF() const {\n\t\treturn _nLocalDoF;\n\t}\n\n\n\tclass ElementT {\n\tpublic:\n\t\tconstexpr static unsigned int nDoFPerElement() {\n\t\t\treturn FEMMeshRectP1<Dim>::twoToThePowerOfN(Dim);\n\t\t}\n\tprivate:\n\n\t\tFEMMeshRectP1<Dim> const& _femMesh;\n\t\tconst index_t _index;\n\n\t\t// WARNING: Initially, end must be vec.size()\n\t\tindex_t binarySearchInSortedIndexVector(std::vector<index_t> const& vec, index_t begin, index_t end, index_t value) const {\n\t\t\tconst index_t mid = (begin+end)/2;\n\t\t\tconst index_t mid_value = vec[mid];\n\t\t\tif(mid_value == value) {\n\t\t\t\treturn mid;\n\t\t\t}\n\t\t\telse if(value < mid_value) {\n\t\t\t\treturn binarySearchInSortedIndexVector(vec, begin, mid, value);\n\t\t\t}\n\t\t\telse {\n\t\t\t\treturn binarySearchInSortedIndexVector(vec, mid, end, value);\n\t\t\t}\n\t\t}\n\n\tpublic:\n\t\tElementT(FEMMeshRectP1<Dim> const& femMesh, index_t index) : _femMesh(femMesh), _index(index) {}\n\n\t\toperator index_t() const {\n\t\t\treturn _index;\n\t\t}\n\t\tindex_t index() const {\n\t\t\treturn _index;\n\t\t}\n\n\t\tuint indexInDimension(uint dimension) const {\n\t\t\treturn _femMesh._elementData[_index].multiIndex[dimension];\n\t\t}\n\n\t\treal diamInDimension(uint dimension) const {\n\t\t\treturn _femMesh.dimensions[dimension].elementDiameter[indexInDimension(dimension)];\n\t\t}\n\n\t\tindex_t globalDoFIndex(uint localDoFIndex) const {\n\t\t\treturn _femMesh._elementData[_index].dofIndices[localDoFIndex];\n\t\t}\n\n\t\tindex_t const * globalDoFIndices() const {\n\t\t\treturn _femMesh._elementData[_index].dofIndices;\n\t\t}\n\n\t\tFEMMeshRectP1<Dim> const& getMesh() const {\n\t\t\treturn _femMesh;\n\t\t}\n\n\t\tbool hasDomainBorder() const {\n\t\t\treturn _femMesh._elementHasDomainBorder[_index];\n\t\t}\n\n\t\tindex_t iAmTheNThElementWithDomainBorder() const {\n\t\t\t//const index_t result = std::find(_femMesh._elementsWithDomainBorder.begin(), _femMesh._elementsWithDomainBorder.end(), _index) - _femMesh._elementsWithDomainBorder.begin();\n\t\t\t//if(result >= _femMesh._elementsWithDomainBorder.size()) {\n\t\t\t//\tstd::cout << \"IAmTheNThElementWithDomainBorder: This should NOT happen!!!\" << std::endl;\n\t\t\t//}\n\n\t\t\treturn binarySearchInSortedIndexVector(_femMesh._elementsWithDomainBorder, 0, _femMesh._elementsWithDomainBorder.size(), _index);\n\t\t}\n\t\tuint nDomainBorderHypesurfaces() const {\n\t\t\tuint result = 0;\n\t\t\tfor(uint i=0; i<nHypersufacesPerElement(); ++i) {\n\t\t\t\tif(neighborElementIndices()[i] == noNeighbor) {\n\t\t\t\t\tresult += 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn result;\n\t\t}\n\t\tindex_t neighborElementIndex(short_index_t index) const {\n\t\t\treturn _femMesh._elementData[_index].neighborIndices[index];\n\t\t}\n\t\tindex_t const * neighborElementIndices() const {\n\t\t\treturn _femMesh._elementData[_index].neighborIndices;\n\t\t}\n\n\t\t/*\n\t\t * Terminology:\n\t\t * (Global) DoF -- all DoF accessible by this compute node\n\t\t * LocalDoF     -- DoF genuinely belonging to this compute node\n\t\t * ElementDoF   -- DoF belonging to one element\n\t\t */\n\t\tclass ElementDoFT {\n\t\tprivate:\n\t\t\tuint _localIndex;\n\t\t\tindex_t _globalIndex;\n\n\t\tpublic:\n\t\t\tElementDoFT(uint localIndex, index_t globalIndex) : _localIndex(localIndex), _globalIndex(globalIndex) {\n\t\t\t\t//std::cout << \"Constructing ElementDoFT with localIndex \" << _localIndex << \" and global index \" << _globalIndex << std::endl;\n\t\t\t}\n\n\t\t\toperator uint() const {\n\t\t\t\treturn _localIndex;\n\t\t\t}\n\t\t\tuint index() const {\n\t\t\t\treturn _localIndex;\n\t\t\t}\n\n\t\t\tindex_t globalIndex() const {\n\t\t\t\treturn _globalIndex;\n\t\t\t}\n\n\t\t\tbool operator==(ElementDoFT const& other) const {\n\t\t\t\treturn _localIndex == other._localIndex;\n\t\t\t}\n\t\t\tbool operator!=(ElementDoFT const& other) const {\n\t\t\t\treturn _localIndex != other._localIndex;\n\t\t\t}\n\t\t\tbool operator<(ElementDoFT const& other) const {\n\t\t\t\treturn _localIndex < other._localIndex;\n\t\t\t}\n\t\t\tbool operator<=(ElementDoFT const& other) const {\n\t\t\t\treturn _localIndex <= other._localIndex;\n\t\t\t}\n\t\t\tbool operator>(ElementDoFT const& other) const {\n\t\t\t\treturn _localIndex > other._localIndex;\n\t\t\t}\n\t\t\tbool operator>=(ElementDoFT const& other) const {\n\t\t\t\treturn _localIndex >= other._localIndex;\n\t\t\t}\n\t\t};\n\n\t\ttypename FEMMeshRectP1<Dim>::ElementT::ElementDoFT elementDoF(uint localIndex) const {\n\t\t\treturn typename FEMMeshRectP1<Dim>::ElementT::ElementDoFT(localIndex, globalDoFIndex(localIndex));\n\t\t}\n\n\t\tclass IterateElementDoF {\n\t\tprivate:\n\t\t\tindex_t const*const _globalDoF;\n\n\t\tpublic:\n\t\t\tIterateElementDoF(typename FEMMeshRectP1<Dim>::ElementT element) :\n\t\t\t\t_globalDoF(element.globalDoFIndices()) {}\n\n\n\t\t\tclass const_iterator : public boost::iterator_facade<\n\t\t\tconst_iterator\n\t\t\t, typename FEMMeshRectP1<Dim>::ElementT::ElementDoFT const\n\t\t\t, boost::random_access_traversal_tag\n\t\t\t, typename FEMMeshRectP1<Dim>::ElementT::ElementDoFT const\n\t\t\t, signed_short_index_t> {\n\t\t\tpublic:\n\t\t\t\t//const_iterator() : _element(0), _elementDoFIndex(0) {}\n\t\t\t\texplicit const_iterator(index_t const* globalDoF) : _globalDoF(globalDoF), _localIndex(0) {}\n\t\t\t\tconst_iterator(index_t const* globalDoF, short_index_t localIndex) : _globalDoF(globalDoF), _localIndex(localIndex) {}\n\n\t\t\tprivate:\n\t\t\t\tfriend class boost::iterator_core_access;\n\n\t\t\t\tvoid increment() { ++_localIndex; }\n\t\t\t\tvoid decrement() { --_localIndex; }\n\t\t\t\tvoid advance(signed_short_index_t n) { _localIndex+=n; }\n\t\t\t\tsigned_short_index_t distance_to(const_iterator const& other) const { return other._localIndex - this->_localIndex; }\n\n\t\t\t\tbool equal(const_iterator const& other) const {\treturn this->_localIndex == other._localIndex; }\n\n\t\t\t\ttypename FEMMeshRectP1<Dim>::ElementT::ElementDoFT const dereference() const {\n\t\t\t\t\treturn typename FEMMeshRectP1<Dim>::ElementT::ElementDoFT(_localIndex, _globalDoF[_localIndex]);\n\t\t\t\t}\n\n\t\t\t\tindex_t const* _globalDoF;\n\t\t\t\tsigned_short_index_t _localIndex;\n\t\t\t};\n\t\t\ttypedef const_iterator iterator;\n\n\t\t\titerator begin() const { return iterator(_globalDoF); }\n\t\t\titerator end() const { return iterator(_globalDoF, FEMMeshRectP1<Dim>::nDoFPerElement()); }\n\t\t\tconst_iterator cbegin() const { return const_iterator(_globalDoF); }\n\t\t\tconst_iterator cend() const { return const_iterator(_globalDoF, FEMMeshRectP1<Dim>::nDoFPerElement()); }\n\t\t};\n\n\t\tclass HypersurfaceT {\n\t\tpublic:\n\t\t\tconstexpr static unsigned int nDoFPerHypersurface() {\n\t\t\t\treturn Dim;\n\t\t\t}\n\t\tprivate:\n\t\t\ttypename FEMMeshRectP1<Dim>::ElementT const& _element;\n\t\t\tshort_index_t _surfaceIndex;\n\t\tpublic:\n\t\t\tHypersurfaceT(typename FEMMeshRectP1<Dim>::ElementT const& element, uint localIndex) :\n\t\t\t\t_element(element),\n\t\t\t\t_surfaceIndex(localIndex)\n\t\t\t{}\n\n\t\t\toperator short_index_t() const {\n\t\t\t\treturn _surfaceIndex;\n\t\t\t}\n\t\t\tshort_index_t index() const {\n\t\t\t\treturn _surfaceIndex;\n\t\t\t}\n\n\t\t\tuint elementDoFIndex(uint hypersurfaceDoFIndex) const {\n\t\t\t\tconst uint normalDimension = _surfaceIndex/2;\n\t\t\t\tconst uint normalEntry = _surfaceIndex%2;\n\t\t\t\tconst uint allOnes = ~(0U);\n\t\t\t\tconst uint maskLowerPart = ~(allOnes << (Dim-1-normalDimension));\n\t\t\t\tconst uint maskHigherPart = allOnes << (Dim-1-normalDimension);\n\t\t\t\tconst uint result = (normalEntry<<(Dim-1-normalDimension))    |\n\t\t\t\t                    (hypersurfaceDoFIndex & maskLowerPart)    |\n\t\t\t\t                    ((hypersurfaceDoFIndex & maskHigherPart)<<1);\n\t\t\t\t//std::cout << \"F\u00fcr hypersurfaceDoFIndex=\" << hypersurfaceDoFIndex << \" von Hypersurface \" << _surfaceIndex <<\n\t\t\t\t//\t\t\" ist elementDoFIndex=\" << result << std::endl;\n\t\t\t\treturn result;\n\t\t\t}\n\n\t\t\tclass HypersurfaceDoFT {\n\t\t\tprivate:\n\t\t\t\tuint _hypersurfaceIndex;\n\t\t\t\tuint _elementIndex;\n\n\t\t\tpublic:\n\t\t\t\tHypersurfaceDoFT(uint hypersurfaceIndex, index_t elementIndex) : _hypersurfaceIndex(hypersurfaceIndex), _elementIndex(elementIndex) {}\n\n\t\t\t\toperator uint() const {\n\t\t\t\t\treturn _hypersurfaceIndex;\n\t\t\t\t}\n\t\t\t\tuint index() const {\n\t\t\t\t\treturn _hypersurfaceIndex;\n\t\t\t\t}\n\n\t\t\t\tuint elementDoFIndex() const {\n\t\t\t\t\treturn _elementIndex;\n\t\t\t\t}\n\n\t\t\t\tbool operator==(HypersurfaceDoFT const& other) const {\n\t\t\t\t\treturn _hypersurfaceIndex == other._hypersurfaceIndex;\n\t\t\t\t}\n\t\t\t\tbool operator!=(HypersurfaceDoFT const& other) const {\n\t\t\t\t\treturn _hypersurfaceIndex != other._hypersurfaceIndex;\n\t\t\t\t}\n\t\t\t\tbool operator<(HypersurfaceDoFT const& other) const {\n\t\t\t\t\treturn _hypersurfaceIndex < other._hypersurfaceIndex;\n\t\t\t\t}\n\t\t\t\tbool operator<=(HypersurfaceDoFT const& other) const {\n\t\t\t\t\treturn _hypersurfaceIndex <= other._hypersurfaceIndex;\n\t\t\t\t}\n\t\t\t\tbool operator>(HypersurfaceDoFT const& other) const {\n\t\t\t\t\treturn _hypersurfaceIndex > other._hypersurfaceIndex;\n\t\t\t\t}\n\t\t\t\tbool operator>=(HypersurfaceDoFT const& other) const {\n\t\t\t\t\treturn _hypersurfaceIndex >= other._hypersurfaceIndex;\n\t\t\t\t}\n\t\t\t};\n\n\t\t\ttypename FEMMeshRectP1<Dim>::ElementT::HypersurfaceT::HypersurfaceDoFT hypersurfaceDoF(uint hypersurfaceDoFIndex) const {\n\t\t\t\treturn typename FEMMeshRectP1<Dim>::ElementT::HypersurfaceT::HypersurfaceDoFT(hypersurfaceDoFIndex, elementDoFIndex(hypersurfaceDoFIndex));\n\t\t\t}\n\n\t\t\treal surfaceIntegral(HypersurfaceDoFT const& i, HypersurfaceDoFT const& j, uint dimension) {\n\t\t\t\tuint i_elem = i.elementDoFIndex();\n\t\t\t\tuint j_elem = j.elementDoFIndex();\n\n\t\t\t\tconst uint normalDimension = _surfaceIndex/2;\n\t\t\t\tif(normalDimension != dimension) {\n\t\t\t\t\treturn 0.0;\n\t\t\t\t}\n\n\t\t\t\tuint iMultiIndex[Dim];\n\t\t\t\tuint jMultiIndex[Dim];\n\n\t\t\t\tfor(uint k=0; k<Dim; ++k) {\n\t\t\t\t\tiMultiIndex[Dim-1-k] = i_elem%2;\n\t\t\t\t\ti_elem /= 2;\n\t\t\t\t\tjMultiIndex[Dim-1-k] = j_elem%2;\n\t\t\t\t\tj_elem /= 2;\n\t\t\t\t}\n\n\n\t\t\t\tconst real intValue[2] = {1.0/3.0, 1.0/6.0};\n\n\t\t\t\tconst bool isLeftSurface = (_surfaceIndex%2 == 0);\n\t\t\t\treal result = (isLeftSurface ? -1.0 : 1.0);\n\t\t\t\tfor(uint k=0; k<Dim; ++k) {\n\t\t\t\t\tif(k != normalDimension) {\n\t\t\t\t\t\tresult *= intValue[(iMultiIndex[k]!=jMultiIndex[k] ? 1 : 0)] * _element.diamInDimension(k);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn result;\n\t\t\t}\n\n\t\t\tclass IterateHypersurfaceDoF {\n\t\t\tprivate:\n\t\t\t\ttypename FEMMeshRectP1<Dim>::ElementT::HypersurfaceT const& _hypersurface;\n\n\t\t\tpublic:\n\t\t\t\tIterateHypersurfaceDoF(typename FEMMeshRectP1<Dim>::ElementT::HypersurfaceT const& hypersurface) :\n\t\t\t\t\t_hypersurface(hypersurface) {\n\t\t\t\t\t//std::cout << \"IterateHypersurfaceDoF(hypersurface), hypersurface = \" << &hypersurface << std::endl;\n\t\t\t\t}\n\n\n\t\t\t\tclass const_iterator : public boost::iterator_facade<\n\t\t\t\tconst_iterator\n\t\t\t\t, typename FEMMeshRectP1<Dim>::ElementT::HypersurfaceT::HypersurfaceDoFT const\n\t\t\t\t, boost::random_access_traversal_tag\n\t\t\t\t, typename FEMMeshRectP1<Dim>::ElementT::HypersurfaceT::HypersurfaceDoFT const\n\t\t\t\t, signed_short_index_t> {\n\t\t\t\tpublic:\n\t\t\t\t\t//const_iterator() : _element(0), _elementDoFIndex(0) {}\n\t\t\t\t\texplicit const_iterator(typename FEMMeshRectP1<Dim>::ElementT::HypersurfaceT const& hypersurface) : _hypersurface(hypersurface), _localIndex(0) {\n\t\t\t\t\t\t//std::cout << \"IterateHypersurfaceDoF::const_iterator(hypersurface), hypersurface = \" << &hypersurface << std::endl;\n\t\t\t\t\t}\n\t\t\t\t\tconst_iterator(typename FEMMeshRectP1<Dim>::ElementT::HypersurfaceT const& hypersurface, short_index_t localIndex) : _hypersurface(hypersurface), _localIndex(localIndex) {\n\t\t\t\t\t\t//std::cout << \"IterateHypersurfaceDoF::const_iterator(hypersurface, index), hypersurface = \" << &hypersurface << std::endl;\n\t\t\t\t\t}\n\n\t\t\t\tprivate:\n\t\t\t\t\tfriend class boost::iterator_core_access;\n\n\t\t\t\t\tvoid increment() { ++_localIndex; }\n\t\t\t\t\tvoid decrement() { --_localIndex; }\n\t\t\t\t\tvoid advance(signed_short_index_t n) { _localIndex+=n; }\n\t\t\t\t\tsigned_short_index_t distance_to(const_iterator const& other) const { return other._localIndex - this->_localIndex; }\n\n\t\t\t\t\tbool equal(const_iterator const& other) const {\treturn this->_localIndex == other._localIndex; }\n\n\t\t\t\t\ttypename FEMMeshRectP1<Dim>::ElementT::HypersurfaceT::HypersurfaceDoFT const dereference() const {\n\t\t\t\t\t\treturn _hypersurface.hypersurfaceDoF(_localIndex);\n\t\t\t\t\t}\n\n\t\t\t\t\ttypename FEMMeshRectP1<Dim>::ElementT::HypersurfaceT const& _hypersurface;\n\t\t\t\t\tsigned_short_index_t _localIndex;\n\t\t\t\t};\n\t\t\t\ttypedef const_iterator iterator;\n\n\t\t\t\titerator begin() const { return iterator(_hypersurface); }\n\t\t\t\titerator end() const { return iterator(_hypersurface, FEMMeshRectP1<Dim>::ElementT::HypersurfaceT::nDoFPerHypersurface()); }\n\t\t\t\tconst_iterator cbegin() const { return const_iterator(_hypersurface); }\n\t\t\t\tconst_iterator cend() const { return const_iterator(_hypersurface, FEMMeshRectP1<Dim>::ElementT::HypersurfaceT::nDoFPerHypersurface()); }\n\t\t\t};\n\t\t};\n\n\t\ttypename FEMMeshRectP1<Dim>::ElementT::HypersurfaceT hypersurface(uint surfaceIndex) const {\n\t\t\treturn typename FEMMeshRectP1<Dim>::ElementT::HypersurfaceT(*this, surfaceIndex);\n\t\t}\n\n\t\tclass IterateElementDomainBoundaryHypersurfaces {\n\t\tprivate:\n\t\t\ttypename FEMMeshRectP1<Dim>::ElementT const& _element;\n\t\t\tconst uint _nDomainBoundaryHypersurfaces;\n\t\tpublic:\n\t\t\tIterateElementDomainBoundaryHypersurfaces(typename FEMMeshRectP1<Dim>::ElementT const& element) :\n\t\t\t\t_element(element),\n\t\t\t\t_nDomainBoundaryHypersurfaces(element.nDomainBorderHypesurfaces()){}\n\n\t\t\tclass const_iterator : public boost::iterator_facade<\n\t\t\tconst_iterator\n\t\t\t, typename FEMMeshRectP1<Dim>::ElementT::HypersurfaceT const\n\t\t\t, boost::random_access_traversal_tag\n\t\t\t, typename FEMMeshRectP1<Dim>::ElementT::HypersurfaceT const\n\t\t\t, int> {\n\t\t\tpublic:\n\t\t\t\tconst_iterator() : _element(0), _hypersurfaceIndex(0) {}\n\t\t\t\t//explicit const_iterator(FEMMeshRectP1<Dim> const& femMesh) : _femMesh(femMesh), _elementIndex(0) {}\n\t\t\t\texplicit const_iterator(typename FEMMeshRectP1<Dim>::ElementT const& element) : _element(&element), _hypersurfaceIndex(0) {}\n\t\t\t\tconst_iterator(typename FEMMeshRectP1<Dim>::ElementT const& element, int hypersurfaceIndex) : _element(&element), _hypersurfaceIndex(hypersurfaceIndex) {}\n\n\t\t\tprivate:\n\t\t\t\tfriend class boost::iterator_core_access;\n\n\t\t\t\tvoid increment() { ++_hypersurfaceIndex; }\n\t\t\t\tvoid decrement() { --_hypersurfaceIndex; }\n\t\t\t\tvoid advance(int n) { _hypersurfaceIndex+=n; }\n\t\t\t\tint distance_to(const_iterator const& other) const { return  other._hypersurfaceIndex - this->_hypersurfaceIndex; }\n\n\t\t\t\tbool equal(const_iterator const& other) const {\treturn this->_hypersurfaceIndex == other._hypersurfaceIndex; }\n\n\t\t\t\ttypename FEMMeshRectP1<Dim>::ElementT::HypersurfaceT const dereference() const {\n\t\t\t\t\tuint nBorderSurface = 0;\n\t\t\t\t\tfor(int i=0; i<nHypersufacesPerElement(); ++i) {\n\t\t\t\t\t\tif(_element->neighborElementIndex(i) == noNeighbor) {\n\t\t\t\t\t\t\tif(nBorderSurface == _hypersurfaceIndex) {\n\t\t\t\t\t\t\t\tnBorderSurface = i;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tnBorderSurface += 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn _element->hypersurface(nBorderSurface);\n\t\t\t\t}\n\n\t\t\t\ttypename FEMMeshRectP1<Dim>::ElementT const* _element;\n\t\t\t\tint _hypersurfaceIndex;\n\t\t\t};\n\t\t\ttypedef const_iterator iterator;\n\n\t\t\titerator begin() const { return iterator(_element); }\n\t\t\titerator end() const { return iterator(_element, _nDomainBoundaryHypersurfaces); }\n\t\t\tconst_iterator cbegin() const { return const_iterator(_element); }\n\t\t\tconst_iterator cend() const { return const_iterator(_element, _nDomainBoundaryHypersurfaces); }\n\t\t};\n\t};\n\n\tElementT const element(index_t index) const {\n\t\treturn ElementT(*this, index);\n\t}\n\n\tclass DoFT {\n\tprivate:\n\t\tFEMMeshRectP1<Dim> const& _femMesh;\n\t\tconst index_t _index;\n\n\tpublic:\n\t\tDoFT(FEMMeshRectP1<Dim> const& femMesh, index_t index) : _femMesh(femMesh), _index(index) {}\n\n\t\toperator index_t() const {\n\t\t\treturn _index;\n\t\t}\n\t\tindex_t index() const {\n\t\t\treturn _index;\n\t\t}\n\n\t\tuint indexInDimension(uint dimension) const {\n\t\t\treturn _femMesh._dofData[_index].multiIndex[dimension];\n\t\t}\n\n\t\treal positionInDimension(uint dimension) const {\n\t\t\treturn _femMesh.dimensions[dimension].nodes[indexInDimension(dimension)];\n\t\t}\n\t};\n\n\tDoFT dof(index_t index) const {\n\t\treturn DoFT(*this, index);\n\t}\n\n\n\t/*\n\t * Iterations\n\t */\n\n\tclass IterateMeshElements {\n\tprivate:\n\t\tFEMMeshRectP1<Dim> const& _femMesh;\n\t\tconst index_t _beginIndex;\n\t\tconst index_t _endIndex;\n\n\tpublic:\n\t\tIterateMeshElements(FEMMeshRectP1<Dim> const& femMesh, index_t beginIndex, index_t endIndex) :\n\t\t\t_femMesh(femMesh), _beginIndex(beginIndex), _endIndex(endIndex) {}\n\n\n\t\tclass const_iterator : public boost::iterator_facade<\n\t\tconst_iterator\n\t\t, typename FEMMeshRectP1<Dim>::ElementT const\n\t\t, boost::random_access_traversal_tag\n\t\t, typename FEMMeshRectP1<Dim>::ElementT const\n\t\t, signed_index_t> {\n\t\tpublic:\n\t\t\tconst_iterator() : _femMesh(0), _elementIndex(0) {}\n\t\t\t//explicit const_iterator(FEMMeshRectP1<Dim> const& femMesh) : _femMesh(femMesh), _elementIndex(0) {}\n\t\t\tconst_iterator(FEMMeshRectP1<Dim> const& femMesh, index_t elementIndex) : _femMesh(&femMesh), _elementIndex(elementIndex) {}\n\n\t\tprivate:\n\t\t\tfriend class boost::iterator_core_access;\n\n\t\t\tvoid increment() { ++_elementIndex; }\n\t\t\tvoid decrement() { --_elementIndex; }\n\t\t\tvoid advance(signed_index_t n) { _elementIndex+=n; }\n\t\t\tsigned_index_t distance_to(const_iterator const& other) const { return  other._elementIndex - this->_elementIndex; }\n\n\t\t\tbool equal(const_iterator const& other) const {\treturn this->_elementIndex == other._elementIndex; }\n\n\t\t\ttypename FEMMeshRectP1<Dim>::ElementT const dereference() const {\n\t\t\t\treturn _femMesh->element(_elementIndex);\n\t\t\t}\n\n\t\t\tFEMMeshRectP1<Dim> const * _femMesh;\n\t\t\tsigned_index_t _elementIndex;\n\t\t};\n\t\ttypedef const_iterator iterator;\n\n\t\titerator begin() const { return iterator(_femMesh, _beginIndex); }\n\t\titerator end() const { return iterator(_femMesh, _endIndex); }\n\t\tconst_iterator cbegin() const { return const_iterator(_femMesh, _beginIndex); }\n\t\tconst_iterator cend() const { return const_iterator(_femMesh, _endIndex); }\n\t};\n\n\tclass IterateDoF {\n\tprivate:\n\t\tFEMMeshRectP1<Dim> const& _femMesh;\n\t\tconst index_t _beginIndex;\n\t\tconst index_t _endIndex;\n\tpublic:\n\t\tIterateDoF(FEMMeshRectP1<Dim> const& femMesh, index_t beginIndex, index_t endIndex) :\n\t\t\t_femMesh(femMesh), _beginIndex(beginIndex), _endIndex(endIndex) {}\n\n\n\t\tclass const_iterator : public boost::iterator_facade<\n\t\tconst_iterator\n\t\t, typename FEMMeshRectP1<Dim>::DoFT const\n\t\t, boost::random_access_traversal_tag\n\t\t, typename FEMMeshRectP1<Dim>::DoFT const\n\t\t, signed_index_t> {\n\t\tpublic:\n\t\t\t//const_iterator() : _element(0), _elementDoFIndex(0) {}\n\t\t\t//explicit const_iterator(Mesh_2DRect const& mesh) : _mesh(mesh), _dofIndex(0) {}\n\t\t\tconst_iterator(FEMMeshRectP1<Dim> const& femMesh, index_t dofIndex) : _femMesh(&femMesh), _dofIndex(dofIndex) {}\n\n\t\tprivate:\n\t\t\tfriend class boost::iterator_core_access;\n\n\t\t\tvoid increment() { ++_dofIndex; }\n\t\t\tvoid decrement() { --_dofIndex; }\n\t\t\tvoid advance(signed_index_t n) { _dofIndex+=n; }\n\t\t\tsigned_index_t distance_to(const_iterator const& other) const { return other._dofIndex - this->_dofIndex; }\n\n\t\t\tbool equal(const_iterator const& other) const {\treturn this->_dofIndex == other._dofIndex; }\n\n\t\t\ttypename FEMMeshRectP1<Dim>::DoFT const dereference() const {\n\t\t\t\treturn _femMesh->dof(_dofIndex);\n\t\t\t}\n\n\t\t\tFEMMeshRectP1<Dim> const* _femMesh;\n\t\t\tsigned_index_t _dofIndex;\n\t\t};\n\t\ttypedef const_iterator iterator;\n\n\t\titerator begin() const { return iterator(_femMesh, _beginIndex); }\n\t\titerator end() const { return iterator(_femMesh, _endIndex); }\n\t\tconst_iterator cbegin() const { return const_iterator(_femMesh, _beginIndex); }\n\t\tconst_iterator cend() const { return const_iterator(_femMesh, _endIndex); }\n\t};\n\n\n\t/*\n\t * Returns \\prod_{k=1}^n  \\int_0^1 \\tilde{\\phi}_i_k (x_k) * \\tilde{\\phi}_j_k (x_k) dx_k\n\t * Assertion: i and j are *local* DoF Indices (\\in {0,1,2, ..., nDofPerElement()})\n\t */\n\tstatic real integrateReferenceElement(uint i, uint j) {\n\t\tuint iMultiIndex[Dim];\n\t\tuint jMultiIndex[Dim];\n\n\t\tfor(uint k=0; k<Dim; ++k) {\n\t\t\tiMultiIndex[Dim-1-k] = i%2;\n\t\t\ti /= 2;\n\t\t\tjMultiIndex[Dim-1-k] = j%2;\n\t\t\tj /= 2;\n\t\t}\n\n\t\tconst real intValue[4] = {1.0/3.0, 1.0/6.0, 1.0/6.0, 1.0/3.0}; // (i_x/y, j_x/y): (0,0), (0,1), (1,0), (1,1)\n\t\treal result = 1.0;\n\t\tfor(uint k=0; k<Dim; ++k) {\n\t\t\tresult *= intValue[2*iMultiIndex[k] + jMultiIndex[k]];\n\t\t}\n\t\treturn result;\n\t}\n\n\t/*\n\t * Returns \\prod_{k=1,k!=l}^n  \\int_0^1 \\tilde{\\phi}_i_k (x_k) * \\tilde{\\phi}_j_k (x_k) dx_k *\n\t *         \\int_0^1 (d/dx_l \\tilde{\\phi}_i_l (x_l)) * \\tilde{\\phi}_j_l (x_l) dx\n\t * Assertion: i and j are *local* DoF Indices (\\in {0,1,2, ..., nDofPerElement()})\n\t */\n\tstatic real integratePartIntDerivativeReferenceElement(uint i, uint j, uint derivativeDimension) {\n\t\tuint iMultiIndex[Dim];\n\t\tuint jMultiIndex[Dim];\n\n\t\tfor(uint k=0; k<Dim; ++k) {\n\t\t\tiMultiIndex[Dim-1-k] = i%2;\n\t\t\ti /= 2;\n\t\t\tjMultiIndex[Dim-1-k] = j%2;\n\t\t\tj /= 2;\n\t\t}\n\n\t\tconst real intValue[4] = {1.0/3.0, 1.0/6.0, 1.0/6.0, 1.0/3.0}; // (i_x/y, j_x/y): (0,0), (0,1), (1,0), (1,1)\n\t\tconst real intDerivativeXValue[4] = {-0.5, -0.5, 0.5, 0.5}; // (i_x, j_x): (0,0), (0,1), (1,0), (1,1)\n\t\treal result = 1.0;\n\t\tfor(uint k=0; k<Dim; ++k) {\n\t\t\tif(k == derivativeDimension) {\n\t\t\t\tresult *= intDerivativeXValue[2*iMultiIndex[k] + jMultiIndex[k]];\n\t\t\t}\n\t\t\telse {\n\t\t\t\tresult *= intValue[2*iMultiIndex[k] + jMultiIndex[k]];\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n};\n\n\n\ntemplate <unsigned int Dim>\nstatic inline typename FEMMeshRectP1<Dim>::IterateMeshElements Elements(FEMMeshRectP1<Dim> const& femMesh) {\n\treturn typename FEMMeshRectP1<Dim>::IterateMeshElements(femMesh, 0, femMesh.nElements());\n}\ntemplate <unsigned int Dim>\nstatic inline typename FEMMeshRectP1<Dim>::IterateMeshElements LocalElements(FEMMeshRectP1<Dim> const& femMesh) {\n\treturn typename FEMMeshRectP1<Dim>::IterateMeshElements(femMesh, 0, femMesh.nLocalElements());\n}\ntemplate <unsigned int Dim>\nstatic inline typename FEMMeshRectP1<Dim>::IterateMeshElements NeighborElements(FEMMeshRectP1<Dim> const& femMesh) {\n\treturn typename FEMMeshRectP1<Dim>::IterateMeshElements(femMesh, femMesh.nLocalElements(), femMesh.nElements());\n}\n\ntemplate <unsigned int Dim>\nstatic inline UIntRange ElementDoFIndices(FEMMeshRectP1<Dim> const& femMesh) {\n\treturn UIntRange(0, FEMMeshRectP1<Dim>::nDoFPerElement());\n}\ntemplate <typename ElemT>\nstatic inline typename ElemT::IterateElementDoF ElementDoF(ElemT const& element) {\n\treturn typename ElemT::IterateElementDoF(element);\n}\ntemplate <typename ElemT>\nstatic inline typename ElemT::IterateElementDomainBoundaryHypersurfaces DomainBoundaryHypersurfaces(ElemT const& element) {\n\treturn typename ElemT::IterateElementDomainBoundaryHypersurfaces(element);\n}\ntemplate <typename HSurfaceT>\nstatic inline typename HSurfaceT::IterateHypersurfaceDoF HypersurfaceDoF(HSurfaceT const& hypersurface) {\n\treturn typename HSurfaceT::IterateHypersurfaceDoF(hypersurface);\n}\n\ntemplate <unsigned int Dim>\nstatic inline typename FEMMeshRectP1<Dim>::IterateDoF DoF(FEMMeshRectP1<Dim> const& femMesh) {\n\treturn typename FEMMeshRectP1<Dim>::IterateDoF(femMesh, 0, femMesh.nDoF());\n}\ntemplate <unsigned int Dim>\nstatic inline typename FEMMeshRectP1<Dim>::IterateDoF LocalDoF(FEMMeshRectP1<Dim> const& femMesh) {\n\treturn typename FEMMeshRectP1<Dim>::IterateDoF(femMesh, 0, femMesh.nLocalDoF());\n}\ntemplate <unsigned int Dim>\nstatic inline typename FEMMeshRectP1<Dim>::IterateDoF GhostDoF(FEMMeshRectP1<Dim> const& femMesh) {\n\treturn typename FEMMeshRectP1<Dim>::IterateDoF(femMesh, femMesh.nLocalDoF(), femMesh.nDoF());\n}\n\n\n\n#endif/* MESH_RECT_HPP_ */\n", "meta": {"hexsha": "fc4fd08943fee3f9485f5e3c0f6fd19a471301b3", "size": 51272, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pdedsl/mesh_rect.hpp", "max_stars_repo_name": "cau-se/sprat-pde-dsl", "max_stars_repo_head_hexsha": "15621aaf8b3e78f67f39a7c3c5ae30e02ee7c9ee", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pdedsl/mesh_rect.hpp", "max_issues_repo_name": "cau-se/sprat-pde-dsl", "max_issues_repo_head_hexsha": "15621aaf8b3e78f67f39a7c3c5ae30e02ee7c9ee", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pdedsl/mesh_rect.hpp", "max_forks_repo_name": "cau-se/sprat-pde-dsl", "max_forks_repo_head_hexsha": "15621aaf8b3e78f67f39a7c3c5ae30e02ee7c9ee", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.5445473984, "max_line_length": 270, "alphanum_fraction": 0.7039124668, "num_tokens": 15448, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081925, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.45164112108045784}}
{"text": "/**\n * \\file boost/numeric/ublasx/operation/sqr.hpp\n *\n * \\brief Compute the squared of each element of a vector or matrix expression.\n *\n * Copyright (c) 2011, Marco Guazzone\n * \n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\n\n#ifndef BOOST_NUMERIC_UBLASX_OPERATION_SQR_HPP\n#define BOOST_NUMERIC_UBLASX_OPERATION_SQR_HPP\n\n\n#include <boost/numeric/ublas/traits.hpp>\n#include <boost/numeric/ublasx/expression/matrix_unary_functor.hpp>\n#include <boost/numeric/ublasx/expression/vector_unary_functor.hpp>\n\n\nnamespace boost { namespace numeric { namespace ublasx {\n\nusing namespace ::boost::numeric::ublas;\n\nnamespace detail {\n\ntemplate <typename VectorExprT>\nstruct vector_sqr_functor_traits\n{\n\ttypedef VectorExprT input_expression_type;\n\ttypedef typename vector_traits<input_expression_type>::value_type signature_argument_type;\n\ttypedef signature_argument_type signature_result_type;\n\ttypedef vector_unary_functor_traits<\n\t\t\t\tinput_expression_type,\n\t\t\t\tsignature_result_type (signature_argument_type)\n\t\t\t> unary_functor_expression_type;\n\ttypedef typename unary_functor_expression_type::result_type result_type;\n\ttypedef typename unary_functor_expression_type::expression_type expression_type;\n};\n\n\ntemplate <typename MatrixExprT>\nstruct matrix_sqr_functor_traits\n{\n\ttypedef MatrixExprT input_expression_type;\n\ttypedef typename matrix_traits<input_expression_type>::value_type signature_argument_type;\n\ttypedef signature_argument_type signature_result_type;\n\ttypedef matrix_unary_functor_traits<\n\t\t\t\tinput_expression_type,\n\t\t\t\tsignature_result_type (signature_argument_type)\n\t\t\t> unary_functor_expression_type;\n\ttypedef typename unary_functor_expression_type::result_type result_type;\n\ttypedef typename unary_functor_expression_type::expression_type expression_type;\n};\n\n\nnamespace /*<unnamed>*/ {\n\ntemplate <typename T>\nBOOST_UBLAS_INLINE\nT sqr_impl(T x)\n{\n\treturn x*x;\n}\n\n} // Namespace <unnamed>\n\n} // Namespace detail\n\n\n/**\n * \\brief Compute the squared of each element of a given vector expression.\n *\n * \\tparam VectorExprT The type of the input vector expression.\n *\n * \\param ve The input vector expression.\n * \\return A matrix expression where each element of \\a ve has been multiplied by\n *  itself.\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\ntemplate <typename VectorExprT>\nBOOST_UBLAS_INLINE\ntypename detail::vector_sqr_functor_traits<VectorExprT>::result_type sqr(vector_expression<VectorExprT> const& ve)\n{\n\ttypedef typename detail::vector_sqr_functor_traits<VectorExprT>::expression_type expression_type;\n\ttypedef typename detail::vector_sqr_functor_traits<VectorExprT>::signature_argument_type signature_argument_type;\n\n\treturn expression_type(ve(), detail::sqr_impl<signature_argument_type>);\n//\treturn expression_type(ve(), detail::sqr_impl<signature_result_type>);\n//\ttypedef signature_result_type(*fun_ptr_type)(signature_argument_type);\n//\tfun_ptr_type ptr_sqr_fun(&detail::sqr_impl); \n//\treturn expression_type(ve(), ptr_sqr_fun);\n}\n\n\n/**\n * \\brief Compute the squared of each element of a given matrix expression.\n *\n * \\tparam MatrixExprT The type of the input matrix expression.\n *\n * \\param me The input matrix expression.\n * \\return A matrix expression where each element of \\a me has been multiplied by\n *  itself.\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\ntemplate <typename MatrixExprT>\nBOOST_UBLAS_INLINE\ntypename detail::matrix_sqr_functor_traits<MatrixExprT>::result_type sqr(matrix_expression<MatrixExprT> const& me)\n{\n\ttypedef typename detail::matrix_sqr_functor_traits<MatrixExprT>::expression_type expression_type;\n\ttypedef typename detail::matrix_sqr_functor_traits<MatrixExprT>::signature_argument_type signature_argument_type;\n\n\treturn expression_type(me(), detail::sqr_impl<signature_argument_type>);\n//\treturn expression_type(me(), detail::sqr_impl<signature_result_type>(signature_argument_type));\n//\ttypedef signature_result_type(*fun_ptr_type)(signature_argument_type);\n//\tfun_ptr_type ptr_sqr_fun(&detail::sqr_impl); \n//\treturn expression_type(me(), ptr_sqr_fun);\n}\n\n}}} // Namespace boost::numeric::ublasx\n\n\n#endif // BOOST_NUMERIC_UBLASX_OPERATION_SQR_HPP\n", "meta": {"hexsha": "a5bf16f0ddb2d28c05d92376cacb2bf78dd7c08c", "size": 4303, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/ublasx/operation/sqr.hpp", "max_stars_repo_name": "comcon1/boost-ublasx", "max_stars_repo_head_hexsha": "290b92b643a944825df99bece3468a4f81518056", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "boost/numeric/ublasx/operation/sqr.hpp", "max_issues_repo_name": "comcon1/boost-ublasx", "max_issues_repo_head_hexsha": "290b92b643a944825df99bece3468a4f81518056", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "boost/numeric/ublasx/operation/sqr.hpp", "max_forks_repo_name": "comcon1/boost-ublasx", "max_forks_repo_head_hexsha": "290b92b643a944825df99bece3468a4f81518056", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3565891473, "max_line_length": 114, "alphanum_fraction": 0.8068789217, "num_tokens": 968, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081925, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.45164112108045784}}
{"text": "// test_bernoulli.cpp\n\n// Copyright John Maddock 2006.\n// Copyright  Paul A. Bristow 2007, 2012.\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// Basic sanity test for Bernoulli Cumulative Distribution Function.\n\n#ifdef _MSC_VER\n#  pragma warning (disable : 4535) // calling _set_se_translator() requires /EHa.\n#  pragma warning (disable : 4244) // conversion possible loss of data.\n#  pragma warning (disable : 4996) // 'putenv': The POSIX name for this item is deprecated.\n#  pragma warning (disable : 4127) // conditional expression is constant.\n#endif\n\n// Default domain error policy is\n// #define BOOST_MATH_DOMAIN_ERROR_POLICY throw_on_error\n\n#include <boost/math/concepts/real_concept.hpp> // for real_concept\nusing ::boost::math::concepts::real_concept;\n#include <boost/math/tools/test.hpp>\n\n#include <boost/math/distributions/bernoulli.hpp> // for bernoulli_distribution\nusing boost::math::bernoulli_distribution;\n\n#define BOOST_TEST_MAIN\n#include <boost/test/unit_test.hpp> // for test_main\n#include <boost/test/floating_point_comparison.hpp> // for BOOST_CHECK_CLOSE_FRACTION, BOOST_CHECK_EQUAL...\n\n#include <iostream>\nusing std::cout;\nusing std::endl;\nusing std::fixed;\nusing std::right;\nusing std::left;\nusing std::showpoint;\nusing std::showpos;\nusing std::setw;\nusing std::setprecision;\n\n#include <limits>\nusing std::numeric_limits;\n\ntemplate <class RealType> // Any floating-point type RealType.\nvoid test_spots(RealType)\n{ // Parameter only provides the type, float, double... value ignored.\n\n  // Basic sanity checks, test data may be to double precision only\n  // so set tolerance to 100 eps expressed as a fraction,\n  // or 100 eps of type double expressed as a fraction,\n  // whichever is the larger.\n\n  RealType tolerance = (std::max)\n      (boost::math::tools::epsilon<RealType>(),\n      static_cast<RealType>(std::numeric_limits<double>::epsilon()));\n   tolerance *= 100;\n\n  cout << \"Tolerance for type \" << typeid(RealType).name()  << \" is \"\n    << setprecision(3) << tolerance  << \" (or \" << tolerance * 100 << \"%).\" << endl;\n\n  // Sources of spot test values - calculator,\n  // or Steve Moshier's command interpreter V1.3 100 decimal digit calculator,\n  // Wolfram function evaluator.\n\n  using boost::math::bernoulli_distribution; // of type RealType.\n  using  ::boost::math::cdf;\n  using  ::boost::math::pdf;\n\n  BOOST_CHECK_EQUAL(bernoulli_distribution<RealType>(static_cast<RealType>(0.5)).success_fraction(), static_cast<RealType>(0.5));\n  BOOST_CHECK_EQUAL(bernoulli_distribution<RealType>(static_cast<RealType>(0.1L)).success_fraction(), static_cast<RealType>(0.1L));\n  BOOST_CHECK_EQUAL(bernoulli_distribution<RealType>(static_cast<RealType>(0.9L)).success_fraction(), static_cast<RealType>(0.9L));\n\n  BOOST_MATH_CHECK_THROW( // Constructor success_fraction outside 0 to 1.\n       bernoulli_distribution<RealType>(static_cast<RealType>(2)), std::domain_error);\n  BOOST_MATH_CHECK_THROW(\n       bernoulli_distribution<RealType>(static_cast<RealType>(-2)), std::domain_error);\n\n  BOOST_MATH_CHECK_THROW(\n       pdf( // pdf k neither 0 nor 1.\n          bernoulli_distribution<RealType>(static_cast<RealType>(0.25L)), static_cast<RealType>(-1)), std::domain_error);\n\n  BOOST_MATH_CHECK_THROW(\n       pdf( // pdf k neither 0 nor 1.\n          bernoulli_distribution<RealType>(static_cast<RealType>(0.25L)), static_cast<RealType>(2)), std::domain_error);\n \n  BOOST_CHECK_EQUAL(\n    pdf( // OK k (or n)\n    bernoulli_distribution<RealType>(static_cast<RealType>(0.5L)), static_cast<RealType>(0)),\n      static_cast<RealType>(0.5)); // Expect 1 - p.\n\n  BOOST_CHECK_CLOSE_FRACTION(\n    pdf( // OK k (or n)\n    bernoulli_distribution<RealType>(static_cast<RealType>(0.6L)), static_cast<RealType>(0)),\n      static_cast<RealType>(0.4L), tolerance); // Expect  1 - p.\n\n  BOOST_CHECK_CLOSE_FRACTION(\n    pdf( // OK k (or n)\n    bernoulli_distribution<RealType>(static_cast<RealType>(0.6L)), static_cast<RealType>(0)),\n      static_cast<RealType>(0.4L), tolerance); // Expect  1- p.\n\n  BOOST_CHECK_CLOSE_FRACTION(\n    pdf( // OK k (or n)\n    bernoulli_distribution<RealType>(static_cast<RealType>(0.4L)), static_cast<RealType>(0)),\n      static_cast<RealType>(0.6L), tolerance); // Expect  1- p.\n\n  BOOST_CHECK_EQUAL(\n       mean(bernoulli_distribution<RealType>(static_cast<RealType>(0.5L))), static_cast<RealType>(0.5L));\n\n  BOOST_CHECK_EQUAL(\n       mean(bernoulli_distribution<RealType>(static_cast<RealType>(0.1L))),\n       static_cast<RealType>(0.1L));\n\n  BOOST_CHECK_CLOSE_FRACTION(\n       variance(bernoulli_distribution<RealType>(static_cast<RealType>(0.1L))),\n       static_cast<RealType>(0.09L),\n       tolerance);\n\n  BOOST_CHECK_CLOSE_FRACTION(\n       skewness(bernoulli_distribution<RealType>(static_cast<RealType>(0.1L))),\n       static_cast<RealType>(2.666666666666666666666666666666666666666666L),\n       tolerance);\n\n  BOOST_CHECK_CLOSE_FRACTION(\n       kurtosis(bernoulli_distribution<RealType>(static_cast<RealType>(0.1L))),\n       static_cast<RealType>(8.11111111111111111111111111111111111111111111L),\n       tolerance);\n\n  BOOST_CHECK_CLOSE_FRACTION(\n       kurtosis_excess(bernoulli_distribution<RealType>(static_cast<RealType>(0.1L))),\n       static_cast<RealType>(5.11111111111111111111111111111111111111111111L),\n       tolerance);\n\n  BOOST_MATH_CHECK_THROW(\n     quantile(\n        bernoulli_distribution<RealType>(static_cast<RealType>(2)), // prob >1\n        static_cast<RealType>(0)), std::domain_error\n     );\n  BOOST_MATH_CHECK_THROW(\n     quantile(\n        bernoulli_distribution<RealType>(static_cast<RealType>(-1)), // prob < 0\n        static_cast<RealType>(0)), std::domain_error\n     );\n  BOOST_MATH_CHECK_THROW(\n     quantile(\n        bernoulli_distribution<RealType>(static_cast<RealType>(0.5L)), // k >1\n        static_cast<RealType>(-1)), std::domain_error\n     );\n  BOOST_MATH_CHECK_THROW(\n     quantile(\n        bernoulli_distribution<RealType>(static_cast<RealType>(0.5L)), // k < 0\n        static_cast<RealType>(2)), std::domain_error\n     );\n\n  BOOST_CHECK_CLOSE_FRACTION(\n     cdf(\n        bernoulli_distribution<RealType>(static_cast<RealType>(0.6L)),\n        static_cast<RealType>(0)), \n        static_cast<RealType>(0.4L), // 1 - p\n        tolerance\n     );\n\n  BOOST_CHECK_CLOSE_FRACTION(\n     cdf(\n        bernoulli_distribution<RealType>(static_cast<RealType>(0.6L)),\n        static_cast<RealType>(1)), \n        static_cast<RealType>(1), // p\n        tolerance\n     );\n\n  BOOST_CHECK_CLOSE_FRACTION(\n     cdf(complement(\n        bernoulli_distribution<RealType>(static_cast<RealType>(0.6L)),\n        static_cast<RealType>(1))), \n        static_cast<RealType>(0),\n        tolerance\n     );\n\n  BOOST_CHECK_CLOSE_FRACTION(\n     cdf(complement(\n        bernoulli_distribution<RealType>(static_cast<RealType>(0.6L)),\n        static_cast<RealType>(0))), \n        static_cast<RealType>(0.6L),\n        tolerance\n     );\n\n  BOOST_CHECK_EQUAL(\n     quantile(\n        bernoulli_distribution<RealType>(static_cast<RealType>(0.6L)),\n        static_cast<RealType>(0.1L)),  // < p\n        static_cast<RealType>(0) \n     );\n\n  BOOST_CHECK_EQUAL(\n     quantile(\n        bernoulli_distribution<RealType>(static_cast<RealType>(0.6L)),\n        static_cast<RealType>(0.9L)),  // > p\n        static_cast<RealType>(1) \n     );\n\n   BOOST_CHECK_EQUAL(\n     quantile(complement(\n        bernoulli_distribution<RealType>(static_cast<RealType>(0.6L)),\n        static_cast<RealType>(0.1L))),  // < p\n        static_cast<RealType>(1) \n     );\n\n   BOOST_CHECK_EQUAL(\n     quantile(complement(\n        bernoulli_distribution<RealType>(static_cast<RealType>(0.6L)),\n        static_cast<RealType>(0.9L))),  // > p\n        static_cast<RealType>(0) \n     );\n\n   // Checks for 'bad' parameters.\n   // Construction.\n   BOOST_MATH_CHECK_THROW(bernoulli_distribution<RealType>(-1), std::domain_error); // p outside 0 to 1.\n   BOOST_MATH_CHECK_THROW(bernoulli_distribution<RealType>(+2), std::domain_error); // p outside 0 to 1.\n\n   // Parameters.\n   bernoulli_distribution<RealType> dist(RealType(1)); \n   BOOST_MATH_CHECK_THROW(pdf(dist, -1), std::domain_error);\n   BOOST_MATH_CHECK_THROW(cdf(dist, -1), std::domain_error);\n   BOOST_MATH_CHECK_THROW(cdf(complement(dist, -1)), std::domain_error);\n   BOOST_MATH_CHECK_THROW(quantile(dist, 2), std::domain_error);\n   BOOST_MATH_CHECK_THROW(quantile(complement(dist, -1)), std::domain_error);\n   BOOST_MATH_CHECK_THROW(quantile(dist, -1), std::domain_error);\n   BOOST_MATH_CHECK_THROW(quantile(complement(dist, -1)), std::domain_error);\n     \n   // No longer allow any parameter to be NaN or inf, so all these tests should throw.\n   if (std::numeric_limits<RealType>::has_quiet_NaN)\n   { \n    // Attempt to construct from non-finite should throw.\n     RealType nan = std::numeric_limits<RealType>::quiet_NaN();\n#ifndef BOOST_NO_EXCEPTIONS\n     BOOST_MATH_CHECK_THROW(bernoulli_distribution<RealType> b(nan), std::domain_error);\n#else\n     BOOST_MATH_CHECK_THROW(bernoulli_distribution<RealType>(nan), std::domain_error);\n#endif\n    // Non-finite parameters should throw.\n     bernoulli_distribution<RealType> b(RealType(1)); \n     BOOST_MATH_CHECK_THROW(pdf(b, +nan), std::domain_error); // x = NaN\n     BOOST_MATH_CHECK_THROW(cdf(b, +nan), std::domain_error); // x = NaN\n     BOOST_MATH_CHECK_THROW(cdf(complement(b, +nan)), std::domain_error); // x = + nan\n     BOOST_MATH_CHECK_THROW(quantile(b, +nan), std::domain_error); // p = + nan\n     BOOST_MATH_CHECK_THROW(quantile(complement(b, +nan)), std::domain_error); // p = + nan\n  } // has_quiet_NaN\n\n  if (std::numeric_limits<RealType>::has_infinity)\n  {\n     RealType inf = std::numeric_limits<RealType>::infinity(); \n#ifndef BOOST_NO_EXCEPTIONS\n     BOOST_MATH_CHECK_THROW(bernoulli_distribution<RealType> w(inf), std::domain_error);\n#else\n     BOOST_MATH_CHECK_THROW(bernoulli_distribution<RealType>(inf), std::domain_error);\n#endif\n     bernoulli_distribution<RealType> w(RealType(1)); \n#ifndef BOOST_NO_EXCEPTIONS\n     BOOST_MATH_CHECK_THROW(bernoulli_distribution<RealType> w(inf), std::domain_error);\n#else\n     BOOST_MATH_CHECK_THROW(bernoulli_distribution<RealType>(inf), std::domain_error);\n#endif\n     BOOST_MATH_CHECK_THROW(pdf(w, +inf), std::domain_error); // x = inf\n     BOOST_MATH_CHECK_THROW(cdf(w, +inf), std::domain_error); // x = inf\n     BOOST_MATH_CHECK_THROW(cdf(complement(w, +inf)), std::domain_error); // x = + inf\n     BOOST_MATH_CHECK_THROW(quantile(w, +inf), std::domain_error); // p = + inf\n     BOOST_MATH_CHECK_THROW(quantile(complement(w, +inf)), std::domain_error); // p = + inf\n   } // has_infinity\n\n} // template <class RealType>void test_spots(RealType)\n\nBOOST_AUTO_TEST_CASE( test_main )\n{\n   BOOST_MATH_CONTROL_FP;\n   // Check that can generate bernoulli distribution using both convenience methods:\n   bernoulli_distribution<double> bn1(0.5); // Using default RealType double.\n   boost::math::bernoulli bn2(0.5); // Using typedef. \n\n  BOOST_CHECK_EQUAL(bn1.success_fraction(), 0.5);\n  BOOST_CHECK_EQUAL(bn2.success_fraction(), 0.5);\n\n  BOOST_CHECK_EQUAL(kurtosis(bn2) -3, kurtosis_excess(bn2));\n  BOOST_CHECK_EQUAL(kurtosis_excess(bn2), -2);\n\n  //using namespace boost::math; or \n  using boost::math::bernoulli;\n\n  double tol5eps = std::numeric_limits<double>::epsilon() * 5; // 5 eps as a fraction.\n  // Default bernoulli is type double, so these test values should also be type double.\n  BOOST_CHECK_CLOSE_FRACTION(kurtosis_excess(bernoulli(0.1)), 5.11111111111111111111111111111111111111111111111111, tol5eps);\n  BOOST_CHECK_CLOSE_FRACTION(kurtosis_excess(bernoulli(0.9)), 5.11111111111111111111111111111111111111111111111111, tol5eps);\n  BOOST_CHECK_CLOSE_FRACTION(kurtosis(bernoulli(0.6)), 1./0.4 + 1./0.6 -3., tol5eps);\n  BOOST_CHECK_EQUAL(kurtosis(bernoulli(0)), +std::numeric_limits<double>::infinity());\n  BOOST_CHECK_EQUAL(kurtosis(bernoulli(1)), +std::numeric_limits<double>::infinity());\n // \n\n  // Basic sanity-check spot values.\n\n  // (Parameter value, arbitrarily zero, only communicates the floating point type).\n  test_spots(0.0F); // Test float.\n  test_spots(0.0); // Test double.\n  test_spots(0.0L); // Test long double.\n#if !BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x582))\n  test_spots(boost::math::concepts::real_concept(0.)); // Test real concept.\n#endif\n\n} // BOOST_AUTO_TEST_CASE( test_main )\n\n/*\n\nOutput is:\n\n  Description: Autorun \"J:\\Cpp\\MathToolkit\\test\\Math_test\\Debug\\test_bernouilli.exe\"\n  Running 1 test case...\n  Tolerance for type float is 1.19e-005 (or 0.00119%).\n  Tolerance for type double is 2.22e-014 (or 2.22e-012%).\n  Tolerance for type long double is 2.22e-014 (or 2.22e-012%).\n  Tolerance for type class boost::math::concepts::real_concept is 2.22e-014 (or 2.22e-012%).\n  \n  *** No errors detected\n\n\n*/\n\n\n", "meta": {"hexsha": "28b001d6ae136a91df71e443e9bae4d6a63c9e15", "size": 12871, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/libs/math/test/test_bernoulli.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/math/test/test_bernoulli.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/math/test/test_bernoulli.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": 39.1215805471, "max_line_length": 131, "alphanum_fraction": 0.7122989667, "num_tokens": 3515, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494421679929, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.45164111722393063}}
{"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#include <nt2/table.hpp>\n#include <nt2/include/functions/size.hpp>\n#include <nt2/include/functions/indices.hpp>\n#include <nt2/include/functions/resize.hpp>\n\n#include <nt2/sdk/unit/module.hpp>\n#include <nt2/sdk/unit/tests/basic.hpp>\n#include <nt2/sdk/unit/tests/relation.hpp>\n#include <nt2/sdk/unit/tests/type_expr.hpp>\n#include <boost/dispatch/meta/nth_hierarchy.hpp>\n\n\nNT2_TEST_CASE_TPL( indices, NT2_TYPES )\n{\n  using nt2::meta::as_;\n  typedef std::complex<T> cT;\n  {\n    for(std::ptrdiff_t i=-1;i<2;++i)\n    {\n      nt2::table<cT> x1 = nt2::indices( nt2::over(1,i), as_<cT>() );\n      NT2_TEST_EQUAL( nt2::extent(x1), nt2::of_size(1) );\n      NT2_TEST_EQUAL( x1(1),T(i) );\n    }\n  }\n  {\n    for(std::ptrdiff_t base=-1;base<2;++base)\n    {\n      nt2::table<T> ref( nt2::of_size(3,3) );\n      for(int j=0;j< 3;++j)\n        for(int i=0;i< 3;++i)\n          ref(1+i,1+j) = i+base;\n\n      nt2::table<cT> x0 = nt2::indices(3, nt2::over(1,base), as_<T>());\n      NT2_TEST_EQUAL( x0,ref );\n\n      for(int j=0;j< 3;++j)\n        for(int i=0;i< 3;++i)\n          ref(1+i,1+j) = j+base;\n\n      x0 = nt2::indices(3, nt2::over(2,base), as_<T>());\n      NT2_TEST_EQUAL( x0,ref );\n    }\n  }\n  {\n    for(std::ptrdiff_t base=-1;base<2;++base)\n    {\n      nt2::table<cT> ref( nt2::of_size(3,4) );\n      for(int j=0;j< 4;++j)\n        for(int i=0;i< 3;++i)\n          ref(1+i,1+j) = i+base;\n\n      nt2::table<cT> x0 = nt2::indices(3,4, nt2::over(1,base), as_<cT>());\n      NT2_TEST_EQUAL( nt2::extent(x0), nt2::of_size(3,4) );\n      NT2_TEST_EQUAL( x0,ref );\n\n      nt2::table<cT> x0f = nt2::indices( nt2::of_size(3,4), nt2::over(1,base), as_<cT>());\n      NT2_TEST_EQUAL( nt2::extent(x0f), nt2::of_size(3,4) );\n      NT2_TEST_EQUAL( x0f,ref );\n\n      for(int j=0;j< 4;++j)\n        for(int i=0;i< 3;++i)\n          ref(1+i,1+j) = j+base;\n\n      nt2::table<cT> x1 = nt2::indices(3,4, nt2::over(2,base), as_<cT>());\n      NT2_TEST_EQUAL( nt2::extent(x1), nt2::of_size(3,4) );\n      NT2_TEST_EQUAL( x1,ref );\n\n      nt2::table<cT> x1f = nt2::indices( nt2::of_size(3,4), nt2::over(2,base), as_<cT>());\n      NT2_TEST_EQUAL( nt2::extent(x1f), nt2::of_size(3,4) );\n      NT2_TEST_EQUAL( x1f,ref );\n\n      ref.resize( nt2::of_size(3,3,3) );\n      for(int k=0;k< 3;++k)\n        for(int j=0;j< 3;++j)\n          for(int i=0;i< 3;++i)\n            ref(1+i,1+j,1+k) = k+base;\n\n      nt2::table<cT> x2 = nt2::indices(3, 3,3, nt2::over(3,base), as_<cT>());\n      NT2_TEST_EQUAL( nt2::extent(x2), nt2::of_size(3,3,3) );\n      NT2_TEST_EQUAL( x2,ref );\n\n      nt2::table<cT> x2f = nt2::indices( nt2::of_size(3,3,3), nt2::over(3,base), as_<cT>());\n      NT2_TEST_EQUAL( nt2::extent(x2f), nt2::of_size(3,3,3) );\n      NT2_TEST_EQUAL( x2f,ref );\n\n      ref.resize( nt2::of_size(3,3,3,3) );\n      for(int l=0;l< 3;++l)\n        for(int k=0;k< 3;++k)\n          for(int j=0;j< 3;++j)\n            for(int i=0;i< 3;++i)\n              ref(1+i,1+j,1+k,1+l) = l+base;\n\n      nt2::table<cT> x3 = nt2::indices(3,3,3,3, nt2::over(4,base), as_<cT>());\n      NT2_TEST_EQUAL( nt2::extent(x3), nt2::of_size(3,3,3,3) );\n      NT2_TEST_EQUAL( x3,ref );\n\n      nt2::table<cT> x3f = nt2::indices( nt2::of_size(3,3,3,3), nt2::over(4,base), as_<cT>());\n      NT2_TEST_EQUAL( nt2::extent(x3f), nt2::of_size(3,3,3,3) );\n      NT2_TEST_EQUAL( x3f,ref );\n    }\n  }\n}\n", "meta": {"hexsha": "d95a4ec20f9c35489f1caac38a38d0566b5775bd", "size": 3807, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/type/complex/generative/unit/table/indices.cpp", "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/type/complex/generative/unit/table/indices.cpp", "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/type/complex/generative/unit/table/indices.cpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 34.2972972973, "max_line_length": 94, "alphanum_fraction": 0.5285001313, "num_tokens": 1415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494421679929, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.45164111722393063}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// rolling_mean.hpp\n//\n// Copyright 2008 Eric Niebler. Distributed under the Boost\n// Software License, Version 1.0. (See accompanying file\n// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#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\nnamespace impl\n{\n\n    ///////////////////////////////////////////////////////////////////////////////\n    // rolling_mean_impl\n    //    returns the unshifted results from the shifted rolling window\n    template<typename Sample>\n    struct rolling_mean_impl\n      : accumulator_base\n    {\n        typedef typename numeric::functional::average<Sample, std::size_t>::result_type result_type;\n\n        rolling_mean_impl(dont_care)\n        {}\n\n        template<typename Args>\n        result_type result(Args const &args) const\n        {\n            return numeric::average(rolling_sum(args), rolling_count(args));\n        }\n    };\n\n} // namespace impl\n\n///////////////////////////////////////////////////////////////////////////////\n// tag::rolling_mean\n//\nnamespace tag\n{\n    struct rolling_mean\n      : depends_on< rolling_sum, rolling_count >\n    {\n        /// INTERNAL ONLY\n        ///\n        typedef accumulators::impl::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} // namespace tag\n\n///////////////////////////////////////////////////////////////////////////////\n// extract::rolling_mean\n//\nnamespace extract\n{\n    extractor<tag::rolling_mean> const rolling_mean = {};\n}\n\nusing extract::rolling_mean;\n\n}} // namespace boost::accumulators\n\n#endif\n", "meta": {"hexsha": "59146d7013c28b199e78f6d745cc01ae2677be27", "size": 2423, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/accumulators/statistics/rolling_mean.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": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "boost/accumulators/statistics/rolling_mean.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": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "boost/accumulators/statistics/rolling_mean.hpp", "max_forks_repo_name": "mike-code/boost_1_38_0", "max_forks_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2875, "max_line_length": 100, "alphanum_fraction": 0.6330994635, "num_tokens": 490, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435083355187, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4516065275913833}}
{"text": "// Copyright Louis Dionne 2013-2016\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#include <boost/hana/assert.hpp>\n#include <boost/hana/concept/monoid.hpp>\n#include <boost/hana/plus.hpp>\n#include <boost/hana/tuple.hpp>\n#include <boost/hana/zero.hpp>\n\n#include <laws/monoid.hpp>\nnamespace hana = boost::hana;\n\n\nint main() {\n    hana::test::TestMonoid<int>{hana::make_tuple(0,1,2,3,4,5)};\n    hana::test::TestMonoid<unsigned int>{hana::make_tuple(0u,1u,2u,3u,4u,5u)};\n    hana::test::TestMonoid<long>{hana::make_tuple(0l,1l,2l,3l,4l,5l)};\n    hana::test::TestMonoid<unsigned long>{hana::make_tuple(0ul,1ul,2ul,3ul,4ul,5ul)};\n\n    // zero\n    static_assert(hana::zero<int>() == 0, \"\");\n\n    // plus\n    static_assert(hana::plus(6, 4) == 6 + 4, \"\");\n}\n", "meta": {"hexsha": "04b15276eb9a28220d171122844db760571b3afc", "size": 847, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/hana/test/monoid.cpp", "max_stars_repo_name": "metux/boost", "max_stars_repo_head_hexsha": "e0157afdd519a2b14356cea62fcdac81829324cc", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-06-01T15:17:22.000Z", "max_stars_repo_stars_event_max_datetime": "2015-06-01T16:06:53.000Z", "max_issues_repo_path": "libs/hana/test/monoid.cpp", "max_issues_repo_name": "metux/boost", "max_issues_repo_head_hexsha": "e0157afdd519a2b14356cea62fcdac81829324cc", "max_issues_repo_licenses": ["BSL-1.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": "libs/hana/test/monoid.cpp", "max_forks_repo_name": "metux/boost", "max_forks_repo_head_hexsha": "e0157afdd519a2b14356cea62fcdac81829324cc", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-03-19T07:18:18.000Z", "max_forks_repo_forks_event_max_datetime": "2017-03-19T07:18:18.000Z", "avg_line_length": 31.3703703704, "max_line_length": 85, "alphanum_fraction": 0.6824085006, "num_tokens": 291, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.45160651530842}}
{"text": "#include <spatialops/SpatialOpsTools.h>\n#include <spatialops/OperatorDatabase.h>\n\n#include <spatialops/structured/stencil/OneSidedOperatorTypes.h>\n#include <spatialops/structured/stencil/StencilBuilder.h>\n#include <spatialops/NeboStencilBuilder.h>\n#include <spatialops/structured/FieldComparisons.h>\n#include <spatialops/structured/Grid.h>\n#include <spatialops/Nebo.h>\n\n#include <test/TestHelper.h>\n#include <spatialops/structured/FieldHelper.h>\n#include <spatialops/util/TimeLogger.h>\n\n//#define PROFILING\n#ifdef PROFILING\n#include <valgrind/callgrind.h>\n#endif /* PROFILING */\n\n#include <boost/program_options.hpp>\nnamespace po = boost::program_options;\n\nusing namespace SpatialOps;\n\n#include <stdexcept>\nusing std::cout;\nusing std::endl;\n\n#include <algorithm>\n#include <functional>\n#include <type_traits>\n#include <vector>\n\n\n#define USING_VARYING_EDGE_STENCIL\n\n//--------------------------------------------------------------------\n\n\ntemplate<typename FieldT, typename DirT>\nstruct StencilsT\n{\n  typedef typename UnitTriplet<DirT>::type DirTripletT;\n  typedef typename Multiply<IndexTriplet<2, 2, 2>, DirTripletT>::result TwoDirTripletT;\n  typedef typename Multiply<IndexTriplet<3, 3, 3>, DirTripletT>::result ThreeDirTripletT;\n  typedef typename Multiply<IndexTriplet<4, 4, 4>, DirTripletT>::result FourDirTripletT;\n  //Main Point\n  public:\n    typedef typename NEBO_FIRST_IJK( 0, 0, 0)\n                   ::NEBO_ADD_POINT  ( DirTripletT )\n                   ::NEBO_ADD_POINT  ( TwoDirTripletT )\n                   ::NEBO_ADD_POINT  ( ThreeDirTripletT )\n                   ::NEBO_ADD_POINT  ( FourDirTripletT )\n                   ::NEBO_ADD_POINT  ( typename DirTripletT::Negate )\n                   ::NEBO_ADD_POINT  ( typename TwoDirTripletT::Negate )\n                   ::NEBO_ADD_POINT  ( typename ThreeDirTripletT::Negate )\n                   ::NEBO_ADD_POINT  ( typename FourDirTripletT::Negate )\n      MainPointStencilCollectionT;\n    typedef NeboStencilBuilder<Gradient,\n                               MainPointStencilCollectionT,\n                               FieldT,\n                               FieldT>\n            MainPointStencilT;\n    static const NeboStencilCoefCollection<MainPointStencilCollectionT::length> mainCoefs;\n\n#ifdef USING_VARYING_EDGE_STENCIL\n  //One Point\n  public:\n    //Positive\n    public:\n      typedef NEBO_FIRST_IJK( 0, 0, 0)\n        OnePointPositiveStencilCollectionT;\n        typedef NeboStencilBuilder<Gradient,\n                                   OnePointPositiveStencilCollectionT,\n                                   FieldT,\n                                   FieldT>\n                PBasicOneT;\n        static const NeboStencilCoefCollection<OnePointPositiveStencilCollectionT::length> pCoefOne;\n\n    //Negative\n    public:\n      typedef OnePointPositiveStencilCollectionT OnePointNegativeStencilCollectionT;\n      typedef PBasicOneT NBasicOneT;\n      static const NeboStencilCoefCollection<OnePointPositiveStencilCollectionT::length> nCoefOne;\n\n\n  //Two Point One Sided\n  public:\n    //Two Point Positive\n    public:\n      typedef typename NEBO_FIRST_IJK( 0, 0, 0)\n                     ::NEBO_ADD_POINT  ( DirTripletT )\n        TwoPointPositiveStencilCollectionT;\n        typedef NeboStencilBuilder<Gradient,\n                                   TwoPointPositiveStencilCollectionT,\n                                   FieldT,\n                                   FieldT>\n                PBasicTwoT;\n        static const NeboStencilCoefCollection<TwoPointPositiveStencilCollectionT::length> pCoefTwo;\n\n    //Two Point Negative\n    public:\n      typedef typename NEBO_FIRST_IJK( 0, 0, 0)\n                     ::NEBO_ADD_POINT  ( typename DirTripletT::Negate )\n        TwoPointNegativeStencilCollectionT;\n        typedef NeboStencilBuilder<Gradient,\n                                   TwoPointNegativeStencilCollectionT,\n                                   FieldT,\n                                   FieldT>\n                NBasicTwoT;\n        static const NeboStencilCoefCollection<TwoPointPositiveStencilCollectionT::length> nCoefTwo;\n\n\n  //Three Point Centered\n  public:\n    //Point Positive\n    public:\n      typedef typename NEBO_FIRST_IJK( 0, 0, 0)\n                     ::NEBO_ADD_POINT  ( DirTripletT )\n                     ::NEBO_ADD_POINT  ( typename DirTripletT::Negate )\n        ThreePointPositiveStencilCollectionT;\n        typedef NeboStencilBuilder<Gradient,\n                                   ThreePointPositiveStencilCollectionT,\n                                   FieldT,\n                                   FieldT>\n                PBasicThreeT;\n        static const NeboStencilCoefCollection<ThreePointPositiveStencilCollectionT::length> pCoefThree;\n\n    //Negative\n    public:\n      typedef ThreePointPositiveStencilCollectionT ThreePointNegativeStencilCollectionT;\n      typedef PBasicThreeT NBasicThreeT;\n        static const NeboStencilCoefCollection<ThreePointPositiveStencilCollectionT::length> nCoefThree;\n\n\n  //Four Point Slightly Centered\n  public:\n    //Point Positive\n    public:\n      typedef typename NEBO_FIRST_IJK( 0, 0, 0)\n                     ::NEBO_ADD_POINT  ( DirTripletT )\n                     ::NEBO_ADD_POINT  ( TwoDirTripletT )\n                     ::NEBO_ADD_POINT  ( typename DirTripletT::Negate )\n        FourPointPositiveStencilCollectionT;\n        typedef NeboStencilBuilder<Gradient,\n                                   FourPointPositiveStencilCollectionT,\n                                   FieldT,\n                                   FieldT>\n                PBasicFourT;\n        static const NeboStencilCoefCollection<FourPointPositiveStencilCollectionT::length> pCoefFour;\n\n    //Negative\n    public:\n      typedef typename NEBO_FIRST_IJK( 0, 0, 0)\n                     ::NEBO_ADD_POINT  ( typename DirTripletT::Negate )\n                     ::NEBO_ADD_POINT  ( typename TwoDirTripletT::Negate )\n                     ::NEBO_ADD_POINT  ( DirTripletT )\n        FourPointNegativeStencilCollectionT;\n        typedef NeboStencilBuilder<Gradient,\n                                   FourPointNegativeStencilCollectionT,\n                                   FieldT,\n                                   FieldT>\n                NBasicFourT;\n        static const NeboStencilCoefCollection<FourPointPositiveStencilCollectionT::length> nCoefFour;\n\n  typedef typename NeboGenericEmptyTypeList::template AddType<NBasicOneT>::Result\n                                           ::template AddType<NBasicTwoT>::Result\n                                           ::template AddType<NBasicThreeT>::Result\n                                           ::template AddType<NBasicFourT>::Result\n    NegativeStencilListT;\n\n\n  typedef typename NeboGenericEmptyTypeList::template AddType<PBasicOneT>::Result\n                                          ::template AddType<PBasicTwoT>::Result\n                                          ::template AddType<PBasicThreeT>::Result\n                                          ::template AddType<PBasicFourT>::Result\n    PositiveStencilListT;\n\n\n  typedef NeboVaryingEdgeStencilBuilder<DirT,\n                                        FieldT,\n                                        FieldT,\n                                        MainPointStencilT,\n                                        NegativeStencilListT,\n                                        PositiveStencilListT>\n          VaryEdgeOpT;\n#endif /* USING_VARYING_EDGE_STENCIL */\n\n  static void build_varying_stencils( const unsigned int nx,\n                                      const unsigned int ny,\n                                      const unsigned int nz,\n                                      const double Lx,\n                                      const double Ly,\n                                      const double Lz,\n                                      OperatorDatabase& opdb )\n  {\n    //Create main five point stencil\n    {\n      opdb.register_new_operator( new MainPointStencilT(mainCoefs) );\n    }\n\n#ifdef USING_VARYING_EDGE_STENCIL\n    //Create one point stencils\n    {\n      opdb.register_new_operator( new PBasicOneT(pCoefOne) ); //Same type as negative\n    }\n\n    //Create two point stencils\n    {\n      opdb.register_new_operator( new PBasicTwoT(pCoefTwo) );\n      opdb.register_new_operator( new NBasicTwoT(nCoefTwo) );\n    }\n\n    //Create three point stencils\n    {\n      opdb.register_new_operator( new PBasicThreeT(pCoefThree) ); //Same type as negative\n    }\n\n    //Create four point stencils\n    {\n      opdb.register_new_operator( new PBasicFourT(pCoefFour) );\n      opdb.register_new_operator( new NBasicFourT(nCoefFour) );\n    }\n\n    {\n      auto& mainStencil   = *opdb.retrieve_operator<MainPointStencilT>();\n      auto& pOnePointStencil = *opdb.retrieve_operator<PBasicOneT>();\n      auto& nOnePointStencil = *opdb.retrieve_operator<NBasicOneT>();\n      auto& pTwoPointStencil = *opdb.retrieve_operator<PBasicTwoT>();\n      auto& nTwoPointStencil = *opdb.retrieve_operator<NBasicTwoT>();\n      auto& pThreePointStencil = *opdb.retrieve_operator<PBasicThreeT>();\n      auto& nThreePointStencil = *opdb.retrieve_operator<NBasicThreeT>();\n      auto& pFourPointStencil = *opdb.retrieve_operator<PBasicFourT>();\n      auto& nFourPointStencil = *opdb.retrieve_operator<NBasicFourT>();\n      opdb.register_new_operator( new VaryEdgeOpT (mainStencil,\n                                                   NeboGenericEmptyTypeList()(nOnePointStencil)\n                                                                             (nTwoPointStencil)\n                                                                             (nThreePointStencil)\n                                                                             (nFourPointStencil),\n                                                   NeboGenericEmptyTypeList()(pOnePointStencil)\n                                                                             (pTwoPointStencil)\n                                                                             (pThreePointStencil)\n                                                                             (pFourPointStencil)) );\n    }\n#endif /* USING_VARYING_EDGE_STENCIL */\n  }\n\n  void build_varying_stencils( const Grid& grid, OperatorDatabase& opDB )\n  {\n    build_stencils( grid.extent(0), grid.extent(1), grid.extent(2),\n                    grid.length(0), grid.length(1), grid.length(2),\n                    opDB );\n  }\n};\n\n\ntemplate<typename FieldT, typename DirT>\nconst NeboStencilCoefCollection<StencilsT<FieldT, DirT>::OnePointPositiveStencilCollectionT::length>  StencilsT<FieldT, DirT>::pCoefOne\n= build_coef_collection(1.0);\ntemplate<typename FieldT, typename DirT>\nconst NeboStencilCoefCollection<StencilsT<FieldT, DirT>::OnePointPositiveStencilCollectionT::length>  StencilsT<FieldT, DirT>::nCoefOne\n= pCoefOne;\ntemplate<typename FieldT, typename DirT>\nconst NeboStencilCoefCollection<StencilsT<FieldT, DirT>::TwoPointPositiveStencilCollectionT::length>  StencilsT<FieldT, DirT>::pCoefTwo\n= build_coef_collection(1.0)(1.0);\ntemplate<typename FieldT, typename DirT>\nconst NeboStencilCoefCollection<StencilsT<FieldT, DirT>::TwoPointPositiveStencilCollectionT::length>  StencilsT<FieldT, DirT>::nCoefTwo\n= pCoefTwo;\ntemplate<typename FieldT, typename DirT>\nconst NeboStencilCoefCollection<StencilsT<FieldT, DirT>::ThreePointPositiveStencilCollectionT::length>  StencilsT<FieldT, DirT>::pCoefThree\n= build_coef_collection(1.0)(1.0)(1.0);\ntemplate<typename FieldT, typename DirT>\nconst NeboStencilCoefCollection<StencilsT<FieldT, DirT>::ThreePointPositiveStencilCollectionT::length>  StencilsT<FieldT, DirT>::nCoefThree\n= pCoefThree;\ntemplate<typename FieldT, typename DirT>\nconst NeboStencilCoefCollection<StencilsT<FieldT, DirT>::FourPointPositiveStencilCollectionT::length>  StencilsT<FieldT, DirT>::pCoefFour\n= build_coef_collection(1.0)(1.0)(1.0)(1.0);\ntemplate<typename FieldT, typename DirT>\nconst NeboStencilCoefCollection<StencilsT<FieldT, DirT>::FourPointPositiveStencilCollectionT::length>  StencilsT<FieldT, DirT>::nCoefFour\n= pCoefFour;\ntemplate<typename FieldT, typename DirT>\nconst NeboStencilCoefCollection<StencilsT<FieldT, DirT>::MainPointStencilCollectionT::length> StencilsT<FieldT, DirT>::mainCoefs\n= build_coef_collection(1.0)(1.0)(1.0)(1.0)(1.0)(1.0)(1.0)(1.0)(1.0);\n\n//--------------------------------------------------------------------\n\nenum RunMode\n{\n  CORRECTNESS,\n  TIMING,\n};\n\nstruct TimerPack\n{\n  Timer& i_timer;\n  double o_time;\n\n  TimerPack(Timer& i_timer)\n    : i_timer(i_timer)\n  {}\n};\n\ndouble ReturnMedian(std::function<double(Timer&)>& i_timedFunc,\n                    Timer& i_timer,\n                    const size_t i_iterations)\n{\n  std::vector<double> times;\n  times.reserve(i_iterations);\n  for(size_t i = 0; i < i_iterations; i++)\n  {\n    times.push_back(i_timedFunc(i_timer));\n  }\n\n  std::sort(times.begin(), times.end());\n\n  return times[i_iterations/2];\n}\n\n//--------------------------------------------------------------------\n\ntemplate<typename DirT, typename DOMAIN_SIDET, typename RHSType>\nGhostData CalculateRHSGhost(const RHSType& i_rhs)\n{\n  GhostData const mainStencilGhost(i_rhs.ghosts_without_bc());\n\n  GhostData const mainBCCells(i_rhs.ghosts_with_bc() - mainStencilGhost);\n\n  if(DOMAIN_SIDET::value == static_cast<int>(DomainEdgeSide::BOTH_SIDE::value)) {\n    /* Both sides means we do not fill in directional ghost data nor need it\n    */\n    IntVec plus = mainStencilGhost.get_plus();\n    plus[DirT::value] = 0;\n    IntVec minus = mainStencilGhost.get_minus();\n    minus[DirT::value] = 0;\n    return GhostData(minus, plus) + mainBCCells;\n  }\n  else {\n    if(DOMAIN_SIDET::value == static_cast<int>(DomainEdgeSide::MINUS_SIDE::value)) {\n      IntVec minus = mainStencilGhost.get_minus();\n\n      minus[DirT::value] = 0;\n\n      return GhostData(minus, mainStencilGhost.get_plus()) + mainBCCells;\n    }\n    else if(DOMAIN_SIDET::value == static_cast<int>(DomainEdgeSide:: PLUS_SIDE::value)) {\n      IntVec plus = mainStencilGhost.get_plus();\n\n      plus[DirT::value] = 0;\n\n      return GhostData(mainStencilGhost.get_minus(), plus) + mainBCCells;\n    }\n    else\n    {\n      return mainStencilGhost + mainBCCells;\n    }\n  };\n}\n\n#ifdef USING_VARYING_EDGE_STENCIL\nnamespace NinePointVaryingStencilTest\n{\n  namespace\n  {\n    template<typename FieldT, typename PointCollection, typename Arg>\n     struct EvalExpr {\n       NeboStencilCoefCollection<PointCollection::length> typedef Coefs;\n\n       typename PointCollection::Point typedef Point;\n\n       typename PointCollection::Collection typedef Collection;\n\n#ifdef __CUDACC__\n      __host__ __device__\n#endif /* __CUDACC__ */\n       static inline typename FieldT::value_type eval(Arg const & arg,\n                                                      Coefs const & coefs,\n                                                      int const x,\n                                                      int const y,\n                                                      int const z) {\n#ifdef __CUDA_ARCH__\n          return EvalExpr<FieldT, Collection, Arg>::eval(arg, coefs.others(), x, y, z)\n                 + arg.eval(x + Point::value_gpu(0),\n                            y + Point::value_gpu(1),\n                            z + Point::value_gpu(2)) * coefs.coef();\n#else\n          return EvalExpr<FieldT, Collection, Arg>::eval(arg, coefs.others(), x, y, z)\n                 + arg.eval(x + Point::value(0),\n                            y + Point::value(1),\n                            z + Point::value(2)) * coefs.coef();\n#endif /* __CUDA_ARCH__ */\n       }\n    };\n\n    template<typename FieldT, typename Point, typename Arg>\n     struct EvalExpr<FieldT, NeboStencilPointCollection<Point, NeboNil>, Arg > {\n       NeboStencilCoefCollection<1> typedef Coefs;\n\n#ifdef __CUDACC__\n      __host__ __device__\n#endif /* __CUDACC__ */\n       static inline typename FieldT::value_type eval(Arg const & arg,\n                                                      Coefs const & coefs,\n                                                      int const x,\n                                                      int const y,\n                                                      int const z) {\n#ifdef __CUDA_ARCH__\n          return arg.eval(x + Point::value_gpu(0),\n                          y + Point::value_gpu(1),\n                          z + Point::value_gpu(2)) * coefs.coef();\n#else\n          return arg.eval(x + Point::value(0),\n                          y + Point::value(1),\n                          z + Point::value(2)) * coefs.coef();\n#endif /* __CUDA_ARCH__ */\n       }\n    };\n  }\n\n  template<typename FieldT>\n  struct FieldArgWrapper\n  {\n    public:\n      FieldArgWrapper(FieldT i_f, const int i_deviceIndex)\n      : xGlob_(i_f.window_with_ghost().glob_dim(0)),\n        yGlob_(i_f.window_with_ghost().glob_dim(1)),\n        base_(i_f.field_values(i_deviceIndex) + (i_f.window_with_ghost().offset(0) +\n                                           i_f.get_valid_ghost_data().get_minus(0))\n              + (i_f.window_with_ghost().glob_dim(0) * ((i_f.window_with_ghost().offset(1)\n                                                       + i_f.get_valid_ghost_data().get_minus(1))\n                                                      + (i_f.window_with_ghost().glob_dim(1)\n                                                         * (i_f.window_with_ghost().offset(2)\n                                                            + i_f.get_valid_ghost_data().get_minus(2))))))\n    {}\n\n#ifdef __CUDACC__\n      __host__ __device__\n#endif /* __CUDACC__ */\n    inline typename FieldT::value_type eval(int const x, int const y, int const z) const {\n      return base_[x + xGlob_ * (y + (yGlob_ * z))];\n    }\n\n#ifdef __CUDACC__\n      __host__ __device__\n#endif /* __CUDACC__ */\n    inline typename FieldT::value_type& ref(int const x, int const y, int const z) {\n      return base_[x + xGlob_ * (y + (yGlob_ * z))];\n    }\n\n    private:\n      int const xGlob_;\n      int const yGlob_;\n      typename FieldT::value_type * base_;\n  };\n\n  namespace\n  {\n    template<typename DirT, typename DOMAIN_SIDET>\n    struct IncrementEdge;\n\n    template<typename DOMAIN_SIDET>\n    struct IncrementEdge<XDIR, DOMAIN_SIDET>\n    {\n      static inline void IncrX(int& v) {++v;}\n      static inline void IncrY(int& v) {++v;}\n      static inline void IncrZ(int& v) {++v;}\n\n      static inline void EdgeIncrX(int& v) {++v;}\n      static inline void EdgeIncrY(int& v) {}\n      static inline void EdgeIncrZ(int& v) {}\n\n      static inline bool ContinueX(const int startV, const int v, const int vLimit) { return startV == v; }\n      static inline bool ContinueY(const int startV, const int v, const int vLimit) { return v < vLimit; }\n      static inline bool ContinueZ(const int startV, const int v, const int vLimit) { return v < vLimit; }\n\n      template<typename FieldT>\n      static inline int MainStartX(const int start, const int negativeExtent){ return DOMAIN_SIDET::value\n                                                                                    & DomainEdgeSide::MINUS_SIDE::value ? StencilsT<FieldT, XDIR>::NegativeStencilListT::length\n                                                                                                                        : negativeExtent; }\n      template<typename FieldT>\n      static inline int MainEndX(const int extent)                           { return DOMAIN_SIDET::value\n                                                                                    & DomainEdgeSide::PLUS_SIDE::value ? extent - StencilsT<FieldT, XDIR>::PositiveStencilListT::length\n                                                                                                                       : extent; }\n      template<typename FieldT>\n      static inline int MainStartY(const int start, const int negativeExtent){ return start; }\n      template<typename FieldT>\n      static inline int MainEndY(const int extent)                           { return extent; }\n      template<typename FieldT>\n      static inline int MainStartZ(const int start, const int negativeExtent){ return start; }\n      template<typename FieldT>\n      static inline int MainEndZ(const int extent)                           { return extent; }\n\n      static inline int StartNegativeX(const int start) { return 0; }\n      static inline int StartNegativeY(const int start) { return start; }\n      static inline int StartNegativeZ(const int start) { return start; }\n\n      template<typename FieldT>\n      static inline int StartPositiveX(const int start, const int extent) { return extent - StencilsT<FieldT, XDIR>::PositiveStencilListT::length; }\n      template<typename FieldT>\n      static inline int StartPositiveY(const int start, const int extent) { return start; }\n      template<typename FieldT>\n      static inline int StartPositiveZ(const int start, const int extent) { return start; }\n\n      static inline int GetStaticIndex(const int x, const int y, const int z) { return x; }\n      static inline int GetRapidIncr  (const int x, const int y, const int z) { return y; }\n      static inline int GetSlowIncr   (const int x, const int y, const int z) { return z; }\n    };\n    template<typename DOMAIN_SIDET>\n    struct IncrementEdge<YDIR, DOMAIN_SIDET>\n    {\n      static inline void IncrX(int& v) {++v;}\n      static inline void IncrY(int& v) {++v;}\n      static inline void IncrZ(int& v) {++v;}\n\n      static inline void EdgeIncrX(int& v) {}\n      static inline void EdgeIncrY(int& v) {++v;}\n      static inline void EdgeIncrZ(int& v) {}\n\n      static inline bool ContinueX(const int startV, const int v, const int vLimit) { return v < vLimit; }\n      static inline bool ContinueY(const int startV, const int v, const int vLimit) { return startV == v; }\n      static inline bool ContinueZ(const int startV, const int v, const int vLimit) { return v < vLimit; }\n\n      template<typename FieldT>\n      static inline int MainStartX(const int start, const int negativeExtent){ return start; }\n      template<typename FieldT>\n      static inline int MainEndX(const int extent)                           { return extent; }\n      template<typename FieldT>\n      static inline int MainStartY(const int start, const int negativeExtent){ return DOMAIN_SIDET::value\n                                                                                    & DomainEdgeSide::MINUS_SIDE::value ? StencilsT<FieldT, YDIR>::NegativeStencilListT::length\n                                                                                                                        : negativeExtent; }\n      template<typename FieldT>\n      static inline int MainEndY(const int extent)                           { return DOMAIN_SIDET::value\n                                                                                    & DomainEdgeSide::PLUS_SIDE::value ? extent - StencilsT<FieldT, YDIR>::PositiveStencilListT::length\n                                                                                                                       : extent; }\n      template<typename FieldT>\n      static inline int MainStartZ(const int start, const int negativeExtent){ return start; }\n      template<typename FieldT>\n      static inline int MainEndZ(const int extent)                           { return extent; }\n\n      static inline int StartNegativeX(const int start) { return start; }\n      static inline int StartNegativeY(const int start) { return 0; }\n      static inline int StartNegativeZ(const int start) { return start; }\n\n      template<typename FieldT>\n      static inline int StartPositiveX(const int start, const int extent) { return start; }\n      template<typename FieldT>\n      static inline int StartPositiveY(const int start, const int extent) { return extent - StencilsT<FieldT, YDIR>::PositiveStencilListT::length; }\n      template<typename FieldT>\n      static inline int StartPositiveZ(const int start, const int extent) { return start; }\n\n      static inline int GetStaticIndex(const int x, const int y, const int z) { return y; }\n      static inline int GetRapidIncr  (const int x, const int y, const int z) { return x; }\n      static inline int GetSlowIncr   (const int x, const int y, const int z) { return z; }\n    };\n    template<typename DOMAIN_SIDET>\n    struct IncrementEdge<ZDIR, DOMAIN_SIDET>\n    {\n      static inline void IncrX(int& v) {++v;}\n      static inline void IncrY(int& v) {++v;}\n      static inline void IncrZ(int& v) {++v;}\n\n      static inline void EdgeIncrX(int& v) {}\n      static inline void EdgeIncrY(int& v) {}\n      static inline void EdgeIncrZ(int& v) {++v;}\n\n      static inline bool ContinueX(const int startV, const int v, const int vLimit) { return v < vLimit; }\n      static inline bool ContinueY(const int startV, const int v, const int vLimit) { return v < vLimit; }\n      static inline bool ContinueZ(const int startV, const int v, const int vLimit) { return startV == v; }\n\n      template<typename FieldT>\n      static inline int MainStartX(const int start, const int negativeExtent){ return start; }\n      template<typename FieldT>\n      static inline int MainEndX(const int extent)                           { return extent; }\n      template<typename FieldT>\n      static inline int MainStartY(const int start, const int negativeExtent){ return start; }\n      template<typename FieldT>\n      static inline int MainEndY(const int extent)                           { return extent; }\n      template<typename FieldT>\n      static inline int MainStartZ(const int start, const int negativeExtent){ return DOMAIN_SIDET::value\n                                                                                    & DomainEdgeSide::MINUS_SIDE::value ? StencilsT<FieldT, ZDIR>::NegativeStencilListT::length\n                                                                                                                        : negativeExtent; }\n      template<typename FieldT>\n      static inline int MainEndZ(const int extent)                           { return DOMAIN_SIDET::value\n                                                                                    & DomainEdgeSide::PLUS_SIDE::value ? extent - StencilsT<FieldT, ZDIR>::PositiveStencilListT::length\n                                                                                                                       : extent; }\n\n      static inline int StartNegativeX(const int start) { return start; }\n      static inline int StartNegativeY(const int start) { return start; }\n      static inline int StartNegativeZ(const int start) { return 0; }\n\n      template<typename FieldT>\n      static inline int StartPositiveX(const int start, const int extent) { return start; }\n      template<typename FieldT>\n      static inline int StartPositiveY(const int start, const int extent) { return start; }\n      template<typename FieldT>\n      static inline int StartPositiveZ(const int start, const int extent) { return extent - StencilsT<FieldT, ZDIR>::PositiveStencilListT::length; }\n\n      static inline int GetStaticIndex(const int x, const int y, const int z) { return z; }\n      static inline int GetRapidIncr  (const int x, const int y, const int z) { return x; }\n      static inline int GetSlowIncr   (const int x, const int y, const int z) { return y; }\n    };\n  }\n\n  namespace\n  {\n    template<typename DirT, typename DOMAIN_SIDET, typename FieldT>\n    inline void CustomTestManualEdgeIteration_CPU( const GhostData i_ghost, const IntVec i_npts, FieldArgWrapper<FieldT>& o_lhs, const FieldArgWrapper<FieldT>& i_rhs )\n    {\n      typedef IncrementEdge<DirT, DOMAIN_SIDET> EdgeT;\n      const IntVec properExtents = i_npts + i_ghost.get_plus();\n      {\n        int startX = EdgeT::StartNegativeX(-i_ghost.get_minus()[0]);\n        int startY = EdgeT::StartNegativeY(-i_ghost.get_minus()[1]);\n        int startZ = EdgeT::StartNegativeZ(-i_ghost.get_minus()[2]);\n\n        if(static_cast<int>(DOMAIN_SIDET::value) == DomainEdgeSide::MINUS_SIDE::value\n        || static_cast<int>(DOMAIN_SIDET::value) == DomainEdgeSide::BOTH_SIDE::value)\n        {\n          static_assert(std::is_same<typename StencilsT<FieldT, DirT>::NBasicFourT,  typename StencilsT<FieldT, DirT>::NegativeStencilListT::CurrentType>::value, \"Unexpected Stencil in Stencil List\");\n          static_assert(std::is_same<typename StencilsT<FieldT, DirT>::NBasicThreeT, typename StencilsT<FieldT, DirT>::NegativeStencilListT::Collection::CurrentType>::value, \"Unexpected Stencil in Stencil List\");\n          static_assert(std::is_same<typename StencilsT<FieldT, DirT>::NBasicTwoT,   typename StencilsT<FieldT, DirT>::NegativeStencilListT::Collection::Collection::CurrentType>::value, \"Unexpected Stencil in Stencil List\");\n          static_assert(std::is_same<typename StencilsT<FieldT, DirT>::NBasicOneT,   typename StencilsT<FieldT, DirT>::NegativeStencilListT::Collection::Collection::Collection::CurrentType>::value, \"Unexpected Stencil in Stencil List\");\n\n          //Negative 1\n          {\n            for(int z = startZ; EdgeT::ContinueZ(startZ, z, properExtents[2]); EdgeT::IncrZ(z)) {\n              for(int y = startY; EdgeT::ContinueY(startY, y, properExtents[1]); EdgeT::IncrY(y)) {\n                for(int x = startX; EdgeT::ContinueX(startX, x, properExtents[0]); EdgeT::IncrX(x)) {\n                  o_lhs.ref(x,y,z) = EvalExpr<FieldT, typename StencilsT<FieldT, DirT>::OnePointNegativeStencilCollectionT,\n                                            decltype(i_rhs)>::eval(i_rhs, StencilsT<FieldT, DirT>::nCoefOne, x, y, z);\n                }\n              }\n            }\n          }\n          //Negative 2\n          {\n            EdgeT::EdgeIncrX(startX);\n            EdgeT::EdgeIncrY(startY);\n            EdgeT::EdgeIncrZ(startZ);\n            for(int z = startZ; EdgeT::ContinueZ(startZ, z, properExtents[2]); EdgeT::IncrZ(z)) {\n              for(int y = startY; EdgeT::ContinueY(startY, y, properExtents[1]); EdgeT::IncrY(y)) {\n                for(int x = startX; EdgeT::ContinueX(startX, x, properExtents[0]); EdgeT::IncrX(x)) {\n                  o_lhs.ref(x,y,z) = EvalExpr<FieldT, typename StencilsT<FieldT, DirT>::TwoPointNegativeStencilCollectionT,\n                                            decltype(i_rhs)>::eval(i_rhs, StencilsT<FieldT, DirT>::nCoefTwo, x, y, z);\n                }\n              }\n            }\n          }\n          //Negative 3\n          {\n            EdgeT::EdgeIncrX(startX);\n            EdgeT::EdgeIncrY(startY);\n            EdgeT::EdgeIncrZ(startZ);\n            for(int z = startZ; EdgeT::ContinueZ(startZ, z, properExtents[2]); EdgeT::IncrZ(z)) {\n              for(int y = startY; EdgeT::ContinueY(startY, y, properExtents[1]); EdgeT::IncrY(y)) {\n                for(int x = startX; EdgeT::ContinueX(startX, x, properExtents[0]); EdgeT::IncrX(x)) {\n                  o_lhs.ref(x,y,z) = EvalExpr<FieldT, typename StencilsT<FieldT, DirT>::ThreePointNegativeStencilCollectionT,\n                                            decltype(i_rhs)>::eval(i_rhs, StencilsT<FieldT, DirT>::nCoefThree, x, y, z);\n                }\n              }\n            }\n          }\n          //Negative 4\n          {\n            EdgeT::EdgeIncrX(startX);\n            EdgeT::EdgeIncrY(startY);\n            EdgeT::EdgeIncrZ(startZ);\n            for(int z = startZ; EdgeT::ContinueZ(startZ, z, properExtents[2]); EdgeT::IncrZ(z)) {\n              for(int y = startY; EdgeT::ContinueY(startY, y, properExtents[1]); EdgeT::IncrY(y)) {\n                for(int x = startX; EdgeT::ContinueX(startX, x, properExtents[0]); EdgeT::IncrX(x)) {\n                  o_lhs.ref(x,y,z) = EvalExpr<FieldT, typename StencilsT<FieldT, DirT>::FourPointNegativeStencilCollectionT,\n                                            decltype(i_rhs)>::eval(i_rhs, StencilsT<FieldT, DirT>::nCoefFour, x, y, z);\n                }\n              }\n            }\n          }\n        }\n        //Main\n        {\n          for(int z = EdgeT::template MainStartZ<FieldT>(startZ, -i_ghost.get_minus()[2]); z < EdgeT::template MainEndZ<FieldT>(properExtents[2]); ++z) {\n            for(int y = EdgeT::template MainStartY<FieldT>(startY, -i_ghost.get_minus()[1]); y < EdgeT::template MainEndY<FieldT>(properExtents[1]); ++y) {\n              for(int x = EdgeT::template MainStartX<FieldT>(startX, -i_ghost.get_minus()[0]); x < EdgeT::template MainEndX<FieldT>(properExtents[0]); ++x) {\n                o_lhs.ref(x,y,z) = EvalExpr<FieldT, typename StencilsT<FieldT, DirT>::MainPointStencilCollectionT,\n                                          decltype(i_rhs)>::eval(i_rhs, StencilsT<FieldT, DirT>::mainCoefs, x, y, z);\n              }\n            }\n          }\n        }\n\n        if(static_cast<int>(DOMAIN_SIDET::value) == DomainEdgeSide::PLUS_SIDE::value\n        || static_cast<int>(DOMAIN_SIDET::value) == DomainEdgeSide::BOTH_SIDE::value)\n        {\n          static_assert(std::is_same<typename StencilsT<FieldT, DirT>::PBasicFourT,  typename StencilsT<FieldT, DirT>::PositiveStencilListT::CurrentType>::value, \"Unexpected Stencil in Stencil List\");\n          static_assert(std::is_same<typename StencilsT<FieldT, DirT>::PBasicThreeT, typename StencilsT<FieldT, DirT>::PositiveStencilListT::Collection::CurrentType>::value, \"Unexpected Stencil in Stencil List\");\n          static_assert(std::is_same<typename StencilsT<FieldT, DirT>::PBasicTwoT,   typename StencilsT<FieldT, DirT>::PositiveStencilListT::Collection::Collection::CurrentType>::value, \"Unexpected Stencil in Stencil List\");\n          static_assert(std::is_same<typename StencilsT<FieldT, DirT>::PBasicOneT,   typename StencilsT<FieldT, DirT>::PositiveStencilListT::Collection::Collection::Collection::CurrentType>::value, \"Unexpected Stencil in Stencil List\");\n\n          //Positive 4\n          {\n            startZ = EdgeT::template StartPositiveZ<FieldT>(startZ, properExtents[2]);\n            startY = EdgeT::template StartPositiveY<FieldT>(startY, properExtents[1]);\n            startX = EdgeT::template StartPositiveX<FieldT>(startX, properExtents[0]);\n            for(int z = startZ; EdgeT::ContinueZ(startZ, z, properExtents[2]); EdgeT::IncrZ(z)) {\n              for(int y = startY; EdgeT::ContinueY(startY, y, properExtents[1]); EdgeT::IncrY(y)) {\n                for(int x = startX; EdgeT::ContinueX(startX, x, properExtents[0]); EdgeT::IncrX(x)) {\n                  o_lhs.ref(x,y,z) = EvalExpr<FieldT, typename StencilsT<FieldT, DirT>::FourPointPositiveStencilCollectionT,\n                                            decltype(i_rhs)>::eval(i_rhs, StencilsT<FieldT, DirT>::pCoefFour, x, y, z);\n                }\n              }\n            }\n          }\n          //Positive 3\n          {\n            EdgeT::EdgeIncrX(startX);\n            EdgeT::EdgeIncrY(startY);\n            EdgeT::EdgeIncrZ(startZ);\n            for(int z = startZ; EdgeT::ContinueZ(startZ, z, properExtents[2]); EdgeT::IncrZ(z)) {\n              for(int y = startY; EdgeT::ContinueY(startY, y, properExtents[1]); EdgeT::IncrY(y)) {\n                for(int x = startX; EdgeT::ContinueX(startX, x, properExtents[0]); EdgeT::IncrX(x)) {\n                  o_lhs.ref(x,y,z) = EvalExpr<FieldT, typename StencilsT<FieldT, DirT>::ThreePointPositiveStencilCollectionT,\n                                            decltype(i_rhs)>::eval(i_rhs, StencilsT<FieldT, DirT>::pCoefThree, x, y, z);\n                }\n              }\n            }\n          }\n          //Positive 2\n          {\n            EdgeT::EdgeIncrX(startX);\n            EdgeT::EdgeIncrY(startY);\n            EdgeT::EdgeIncrZ(startZ);\n            for(int z = startZ; EdgeT::ContinueZ(startZ, z, properExtents[2]); EdgeT::IncrZ(z)) {\n              for(int y = startY; EdgeT::ContinueY(startY, y, properExtents[1]); EdgeT::IncrY(y)) {\n                for(int x = startX; EdgeT::ContinueX(startX, x, properExtents[0]); EdgeT::IncrX(x)) {\n                  o_lhs.ref(x,y,z) = EvalExpr<FieldT, typename StencilsT<FieldT, DirT>::TwoPointPositiveStencilCollectionT,\n                                            decltype(i_rhs)>::eval(i_rhs, StencilsT<FieldT, DirT>::pCoefTwo, x, y, z);\n                }\n              }\n            }\n          }\n          //Positive 1\n          {\n            EdgeT::EdgeIncrX(startX);\n            EdgeT::EdgeIncrY(startY);\n            EdgeT::EdgeIncrZ(startZ);\n            for(int z = startZ; EdgeT::ContinueZ(startZ, z, properExtents[2]); EdgeT::IncrZ(z)) {\n              for(int y = startY; EdgeT::ContinueY(startY, y, properExtents[1]); EdgeT::IncrY(y)) {\n                for(int x = startX; EdgeT::ContinueX(startX, x, properExtents[0]); EdgeT::IncrX(x)) {\n                  o_lhs.ref(x,y,z) = EvalExpr<FieldT, typename StencilsT<FieldT, DirT>::OnePointPositiveStencilCollectionT,\n                                            decltype(i_rhs)>::eval(i_rhs, StencilsT<FieldT, DirT>::pCoefOne, x, y, z);\n                }\n              }\n            }\n          }\n        }\n      }\n    }\n#ifdef __CUDACC__\n    //GPU Helper Function Collection\n    namespace\n    {\n      template<typename DirT, typename StencilPointCollectionT, typename FieldT>\n      __global__ void CudaEvalStencilEdge( const NeboStencilCoefCollection<StencilPointCollectionT::length> i_coefs,\n                                           const FieldArgWrapper<FieldT> i_rhs,\n                                           const int i_staticIndex,\n                                           const int i_firstLow,\n                                           const int i_firstHigh,\n                                           const int i_secondLow,\n                                           const int i_secondHigh,\n                                           FieldArgWrapper<FieldT> o_lhs)\n      {\n        const int first = i_firstLow + blockIdx.x * blockDim.x + threadIdx.x;\n        const int second = i_secondLow + blockIdx.y * blockDim.y + threadIdx.y;\n\n        if( first < i_firstHigh && second < i_secondHigh )\n        {\n          if(DirT::value == XDIR::value)\n          {\n            o_lhs.ref(i_staticIndex,first,second)\n              = EvalExpr<FieldT, StencilPointCollectionT,\n                         decltype(i_rhs)>::eval(i_rhs, i_coefs, i_staticIndex, first, second);\n          }\n          else if(DirT::value == YDIR::value)\n          {\n            o_lhs.ref(first,i_staticIndex,second)\n              = EvalExpr<FieldT, StencilPointCollectionT,\n                         decltype(i_rhs)>::eval(i_rhs, i_coefs, first, i_staticIndex, second);\n          }\n          else if(DirT::value == ZDIR::value)\n          {\n            o_lhs.ref(first,second,i_staticIndex)\n              = EvalExpr<FieldT, StencilPointCollectionT,\n                         decltype(i_rhs)>::eval(i_rhs, i_coefs, first, second, i_staticIndex);\n          }\n        }\n      }\n\n      template <typename StencilPointCollectionT, typename FieldT>\n      __global__ void CudaEvalStencil( const NeboStencilCoefCollection<StencilPointCollectionT::length> i_coefs,\n                                       const FieldArgWrapper<FieldT> i_rhs,\n                                       const int i_xLow,\n                                       const int i_xHigh,\n                                       const int i_yLow,\n                                       const int i_yHigh,\n                                       const int i_zLow,\n                                       const int i_zHigh,\n                                       FieldArgWrapper<FieldT> o_lhs)\n      {\n        const int x = i_xLow + blockIdx.x * blockDim.x + threadIdx.x;\n        const int y = i_yLow + blockIdx.y * blockDim.y + threadIdx.y;\n\n        const bool valid = x < i_xHigh && y < i_yHigh;\n\n        for(int z = i_zLow; z < i_zHigh; ++z)\n        {\n          if(valid)\n          {\n            o_lhs.ref(x,y,z) = EvalExpr<FieldT, StencilPointCollectionT, decltype(i_rhs)>::eval(i_rhs, i_coefs, x, y, z);\n          }\n        }\n      }\n\n    }\n    template<typename DirT, typename DOMAIN_SIDET, typename FieldT>\n    inline void CustomTestManualEdgeIteration_GPU( const GhostData i_ghost, const IntVec i_npts, FieldArgWrapper<FieldT>& o_lhs, const FieldArgWrapper<FieldT>& i_rhs )\n    {\n      typedef IncrementEdge<DirT, DOMAIN_SIDET> EdgeT;\n      const IntVec properExtents = i_npts + i_ghost.get_plus();\n      {\n        int startX = EdgeT::StartNegativeX(-i_ghost.get_minus()[0]);\n        int startY = EdgeT::StartNegativeY(-i_ghost.get_minus()[1]);\n        int startZ = EdgeT::StartNegativeZ(-i_ghost.get_minus()[2]);\n\n        const int blockDim = 16;\n        const int xGDim = properExtents[0] / blockDim + ((properExtents[0] % blockDim) > 0 ? 1 : 0);\n        const int yGDim = properExtents[1] / blockDim + ((properExtents[1] % blockDim) > 0 ? 1 : 0);\n\n        const int firstEdgeGDim  = EdgeT::GetRapidIncr(properExtents[0], properExtents[1],properExtents[2]) / blockDim + ((EdgeT::GetRapidIncr(properExtents[0], properExtents[1],properExtents[2]) % blockDim) > 0 ? 1 : 0);\n        const int secondEdgeGDim = EdgeT::GetSlowIncr (properExtents[0], properExtents[1],properExtents[2]) / blockDim + ((EdgeT::GetSlowIncr (properExtents[0], properExtents[1],properExtents[2]) % blockDim) > 0 ? 1 : 0);\n\n        const dim3 dimBlock(blockDim, blockDim);\n        const dim3 dimGrid(xGDim, yGDim);\n        const dim3 dimEdgeGrid(firstEdgeGDim, secondEdgeGDim);\n\n        if(static_cast<int>(DOMAIN_SIDET::value) == DomainEdgeSide::MINUS_SIDE::value\n        || static_cast<int>(DOMAIN_SIDET::value) == DomainEdgeSide::BOTH_SIDE::value)\n        {\n          static_assert(std::is_same<typename StencilsT<FieldT, DirT>::NBasicFourT,  typename StencilsT<FieldT, DirT>::NegativeStencilListT::CurrentType>::value, \"Unexpected Stencil in Stencil List\");\n          static_assert(std::is_same<typename StencilsT<FieldT, DirT>::NBasicThreeT, typename StencilsT<FieldT, DirT>::NegativeStencilListT::Collection::CurrentType>::value, \"Unexpected Stencil in Stencil List\");\n          static_assert(std::is_same<typename StencilsT<FieldT, DirT>::NBasicTwoT,   typename StencilsT<FieldT, DirT>::NegativeStencilListT::Collection::Collection::CurrentType>::value, \"Unexpected Stencil in Stencil List\");\n          static_assert(std::is_same<typename StencilsT<FieldT, DirT>::NBasicOneT,   typename StencilsT<FieldT, DirT>::NegativeStencilListT::Collection::Collection::Collection::CurrentType>::value, \"Unexpected Stencil in Stencil List\");\n\n          //Negative 1\n          {\n            CudaEvalStencilEdge<DirT, typename StencilsT<FieldT, DirT>::OnePointNegativeStencilCollectionT><<<dimEdgeGrid,dimBlock>>>(StencilsT<FieldT, DirT>::nCoefOne,\n                                                                    i_rhs,\n                                                                    EdgeT::GetStaticIndex(startX, startY, startZ),\n                                                                    EdgeT::GetRapidIncr(startX, startY, startZ),\n                                                                    EdgeT::GetRapidIncr(properExtents[0], properExtents[1], properExtents[2]),\n                                                                    EdgeT::GetSlowIncr(startX, startY, startZ),\n                                                                    EdgeT::GetSlowIncr(properExtents[0], properExtents[1], properExtents[2]),\n                                                                    o_lhs);\n          }\n          //Negative 2\n          {\n            EdgeT::EdgeIncrX(startX);\n            EdgeT::EdgeIncrY(startY);\n            EdgeT::EdgeIncrZ(startZ);\n            CudaEvalStencilEdge<DirT, typename StencilsT<FieldT, DirT>::TwoPointNegativeStencilCollectionT><<<dimEdgeGrid,dimBlock>>>(StencilsT<FieldT, DirT>::nCoefTwo,\n                                                                    i_rhs,\n                                                                    EdgeT::GetStaticIndex(startX, startY, startZ),\n                                                                    EdgeT::GetRapidIncr(startX, startY, startZ),\n                                                                    EdgeT::GetRapidIncr(properExtents[0], properExtents[1], properExtents[2]),\n                                                                    EdgeT::GetSlowIncr(startX, startY, startZ),\n                                                                    EdgeT::GetSlowIncr(properExtents[0], properExtents[1], properExtents[2]),\n                                                                    o_lhs);\n          }\n          //Negative 3\n          {\n            EdgeT::EdgeIncrX(startX);\n            EdgeT::EdgeIncrY(startY);\n            EdgeT::EdgeIncrZ(startZ);\n            CudaEvalStencilEdge<DirT, typename StencilsT<FieldT, DirT>::ThreePointNegativeStencilCollectionT><<<dimEdgeGrid,dimBlock>>>(StencilsT<FieldT, DirT>::nCoefThree,\n                                                                      i_rhs,\n                                                                      EdgeT::GetStaticIndex(startX, startY, startZ),\n                                                                      EdgeT::GetRapidIncr(startX, startY, startZ),\n                                                                      EdgeT::GetRapidIncr(properExtents[0], properExtents[1], properExtents[2]),\n                                                                      EdgeT::GetSlowIncr(startX, startY, startZ),\n                                                                      EdgeT::GetSlowIncr(properExtents[0], properExtents[1], properExtents[2]),\n                                                                      o_lhs);\n          }\n          //Negative 4\n          {\n            EdgeT::EdgeIncrX(startX);\n            EdgeT::EdgeIncrY(startY);\n            EdgeT::EdgeIncrZ(startZ);\n            CudaEvalStencilEdge<DirT, typename StencilsT<FieldT, DirT>::FourPointNegativeStencilCollectionT><<<dimEdgeGrid,dimBlock>>>(StencilsT<FieldT, DirT>::nCoefFour,\n                                                                     i_rhs,\n                                                                     EdgeT::GetStaticIndex(startX, startY, startZ),\n                                                                     EdgeT::GetRapidIncr(startX, startY, startZ),\n                                                                     EdgeT::GetRapidIncr(properExtents[0], properExtents[1], properExtents[2]),\n                                                                     EdgeT::GetSlowIncr(startX, startY, startZ),\n                                                                     EdgeT::GetSlowIncr(properExtents[0], properExtents[1], properExtents[2]),\n                                                                     o_lhs);\n          }\n        }\n        //Main\n        {\n          CudaEvalStencil<typename StencilsT<FieldT, DirT>::MainPointStencilCollectionT><<<dimGrid, dimBlock>>>( StencilsT<FieldT, DirT>::mainCoefs,\n                                                        i_rhs,\n                                                        EdgeT::template MainStartX<FieldT>(startX, -i_ghost.get_minus()[0]),\n                                                        EdgeT::template MainEndX<FieldT>(properExtents[0]),\n                                                        EdgeT::template MainStartY<FieldT>(startY, -i_ghost.get_minus()[1]),\n                                                        EdgeT::template MainEndY<FieldT>(properExtents[1]),\n                                                        EdgeT::template MainStartZ<FieldT>(startZ, -i_ghost.get_minus()[2]),\n                                                        EdgeT::template MainEndZ<FieldT>(properExtents[2]),\n                                                        o_lhs );\n        }\n\n        if(static_cast<int>(DOMAIN_SIDET::value) == DomainEdgeSide::PLUS_SIDE::value\n        || static_cast<int>(DOMAIN_SIDET::value) == DomainEdgeSide::BOTH_SIDE::value)\n        {\n          static_assert(std::is_same<typename StencilsT<FieldT, DirT>::PBasicFourT,  typename StencilsT<FieldT, DirT>::PositiveStencilListT::CurrentType>::value, \"Unexpected Stencil in Stencil List\");\n          static_assert(std::is_same<typename StencilsT<FieldT, DirT>::PBasicThreeT, typename StencilsT<FieldT, DirT>::PositiveStencilListT::Collection::CurrentType>::value, \"Unexpected Stencil in Stencil List\");\n          static_assert(std::is_same<typename StencilsT<FieldT, DirT>::PBasicTwoT,   typename StencilsT<FieldT, DirT>::PositiveStencilListT::Collection::Collection::CurrentType>::value, \"Unexpected Stencil in Stencil List\");\n          static_assert(std::is_same<typename StencilsT<FieldT, DirT>::PBasicOneT,   typename StencilsT<FieldT, DirT>::PositiveStencilListT::Collection::Collection::Collection::CurrentType>::value, \"Unexpected Stencil in Stencil List\");\n\n          //Positive 4\n          {\n            startZ = EdgeT::template StartPositiveZ<FieldT>(startZ, properExtents[2]);\n            startY = EdgeT::template StartPositiveY<FieldT>(startY, properExtents[1]);\n            startX = EdgeT::template StartPositiveX<FieldT>(startX, properExtents[0]);\n            CudaEvalStencilEdge<DirT, typename StencilsT<FieldT, DirT>::FourPointPositiveStencilCollectionT><<<dimEdgeGrid,dimBlock>>>(StencilsT<FieldT, DirT>::pCoefFour,\n                                                                     i_rhs,\n                                                                     EdgeT::GetStaticIndex(startX, startY, startZ),\n                                                                     EdgeT::GetRapidIncr(startX, startY, startZ),\n                                                                     EdgeT::GetRapidIncr(properExtents[0], properExtents[1], properExtents[2]),\n                                                                     EdgeT::GetSlowIncr(startX, startY, startZ),\n                                                                     EdgeT::GetSlowIncr(properExtents[0], properExtents[1], properExtents[2]),\n                                                                     o_lhs);\n\n          }\n          //Positive 3\n          {\n            EdgeT::EdgeIncrX(startX);\n            EdgeT::EdgeIncrY(startY);\n            EdgeT::EdgeIncrZ(startZ);\n            CudaEvalStencilEdge<DirT, typename StencilsT<FieldT, DirT>::ThreePointPositiveStencilCollectionT><<<dimEdgeGrid,dimBlock>>>(StencilsT<FieldT, DirT>::pCoefThree,\n                                                                      i_rhs,\n                                                                      EdgeT::GetStaticIndex(startX, startY, startZ),\n                                                                      EdgeT::GetRapidIncr(startX, startY, startZ),\n                                                                      EdgeT::GetRapidIncr(properExtents[0], properExtents[1], properExtents[2]),\n                                                                      EdgeT::GetSlowIncr(startX, startY, startZ),\n                                                                      EdgeT::GetSlowIncr(properExtents[0], properExtents[1], properExtents[2]),\n                                                                      o_lhs);\n          }\n          //Positive 2\n          {\n            EdgeT::EdgeIncrX(startX);\n            EdgeT::EdgeIncrY(startY);\n            EdgeT::EdgeIncrZ(startZ);\n            CudaEvalStencilEdge<DirT, typename StencilsT<FieldT, DirT>::TwoPointPositiveStencilCollectionT><<<dimEdgeGrid,dimBlock>>>(StencilsT<FieldT, DirT>::pCoefTwo,\n                                                                    i_rhs,\n                                                                    EdgeT::GetStaticIndex(startX, startY, startZ),\n                                                                    EdgeT::GetRapidIncr(startX, startY, startZ),\n                                                                    EdgeT::GetRapidIncr(properExtents[0], properExtents[1], properExtents[2]),\n                                                                    EdgeT::GetSlowIncr(startX, startY, startZ),\n                                                                    EdgeT::GetSlowIncr(properExtents[0], properExtents[1], properExtents[2]),\n                                                                    o_lhs);\n          }\n          //Positive 1\n          {\n            EdgeT::EdgeIncrX(startX);\n            EdgeT::EdgeIncrY(startY);\n            EdgeT::EdgeIncrZ(startZ);\n            CudaEvalStencilEdge<DirT, typename StencilsT<FieldT, DirT>::OnePointPositiveStencilCollectionT><<<dimEdgeGrid,dimBlock>>>(StencilsT<FieldT, DirT>::pCoefOne,\n                                                                    i_rhs,\n                                                                    EdgeT::GetStaticIndex(startX, startY, startZ),\n                                                                    EdgeT::GetRapidIncr(startX, startY, startZ),\n                                                                    EdgeT::GetRapidIncr(properExtents[0], properExtents[1], properExtents[2]),\n                                                                    EdgeT::GetSlowIncr(startX, startY, startZ),\n                                                                    EdgeT::GetSlowIncr(properExtents[0], properExtents[1], properExtents[2]),\n                                                                    o_lhs);\n          }\n        }\n      }\n    }\n#endif /* __CUDACC__ */\n\n  }\n\n  template<typename FieldT, typename DirT, typename DOMAIN_SIDET>\n  bool CustomTestManualEdgeIteration( const RunMode i_mode,\n                                      TimerPack* i_timerPack,\n                                      const int i_deviceIndex,\n                                      const IntVec i_npts,\n                                      const GhostData i_fieldGhost,\n                                      const BoundaryCellInfo i_bcinfo,\n                                      OperatorDatabase const & i_opdb,\n                                      Grid const & i_grid,\n                                      const bool i_printField = false,\n                                      SpatFldPtr<FieldT>* o_result = NULL )\n  {\n    const MemoryWindow mw = get_window_with_ghost(i_npts, i_fieldGhost, i_bcinfo);\n\n    FieldT x     ( mw, i_bcinfo, i_fieldGhost, NULL, InternalStorage, i_deviceIndex );\n    FieldT y     ( mw, i_bcinfo, i_fieldGhost, NULL, InternalStorage, i_deviceIndex );\n    FieldT z     ( mw, i_bcinfo, i_fieldGhost, NULL, InternalStorage, i_deviceIndex );\n    FieldT result( mw, i_bcinfo, i_fieldGhost, NULL, InternalStorage, i_deviceIndex );\n\n    // set field values\n    i_grid.set_coord<XDIR>(x);\n    i_grid.set_coord<YDIR>(y);\n    i_grid.set_coord<ZDIR>(z);\n\n    x <<= 1;\n    result <<= 0;\n\n    FieldArgWrapper<FieldT> lhs(result, i_deviceIndex);\n    const FieldArgWrapper<FieldT> rhs(x, i_deviceIndex);\n\n    GhostData rhsGhostWithBC = CalculateRHSGhost<DirT, DOMAIN_SIDET>((*i_opdb.retrieve_operator<typename StencilsT<FieldT, DirT>::MainPointStencilT>())(x).expr());\n\n    GhostData const ghosts = calculate_actual_ghost(true,\n        result.get_ghost_data(),\n        result.boundary_info(),\n        rhsGhostWithBC);\n\n    IntVec const extents = result.window_with_ghost().extent()\n                         - result.get_valid_ghost_data().get_minus()\n                         - result.get_valid_ghost_data().get_plus();\n\n    if(i_mode == TIMING)\n    {\n#ifdef ENABLE_THREADS\n      throw new std::runtime_error(\"Manual implementation of varying stencil is not threaded!\");\n#endif /* ENABLE_THREADS */\n      i_timerPack->i_timer.reset();\n    }\n    //Timed code\n    {\n      switch(i_deviceIndex)\n      {\n        case CPU_INDEX:\n          CustomTestManualEdgeIteration_CPU<DirT, DOMAIN_SIDET>(ghosts, extents, lhs, rhs);\n          break;\n#ifdef __CUDACC__\n        case GPU_INDEX:\n          CustomTestManualEdgeIteration_GPU<DirT, DOMAIN_SIDET>(ghosts, extents, lhs, rhs);\n          break;\n#endif /* __CUDACC__ */\n        default:\n          throw new std::runtime_error(\"Unkown device to execute Manual Edge Test On\");\n      }\n    }\n    if(i_mode == TIMING)\n    {\n#ifdef __CUDACC__\n      cudaDeviceSynchronize();\n#endif\n      i_timerPack->o_time = i_timerPack->i_timer.stop();\n    }\n    if(i_printField)\n    {\n      print_field(result, std::cout);\n    }\n\n    if(o_result != NULL)\n    {\n      *o_result = SpatialFieldStore::get<FieldT>(result, i_deviceIndex);\n      **o_result = result;\n    }\n\n    return true;\n }\n\n  template<typename FieldT, typename DirT, typename DOMAIN_SIDET>\n  bool CustomTestManual( const RunMode i_mode,\n                         TimerPack* i_timerPack,\n                         const int i_deviceIndex,\n                         const IntVec i_npts,\n                         const GhostData i_fieldGhost,\n                         const BoundaryCellInfo i_bcinfo,\n                         OperatorDatabase const & i_opdb,\n                         Grid const & i_grid,\n                         const bool i_printField = false,\n                         SpatFldPtr<FieldT>* o_result = NULL )\n  {\n    const MemoryWindow mw = get_window_with_ghost(i_npts, i_fieldGhost, i_bcinfo);\n\n    FieldT x     ( mw, i_bcinfo, i_fieldGhost, NULL, InternalStorage, i_deviceIndex );\n    FieldT y     ( mw, i_bcinfo, i_fieldGhost, NULL, InternalStorage, i_deviceIndex );\n    FieldT z     ( mw, i_bcinfo, i_fieldGhost, NULL, InternalStorage, i_deviceIndex );\n    FieldT result( mw, i_bcinfo, i_fieldGhost, NULL, InternalStorage, i_deviceIndex );\n\n    // set field values\n    i_grid.set_coord<XDIR>(x);\n    i_grid.set_coord<YDIR>(y);\n    i_grid.set_coord<ZDIR>(z);\n\n    FieldArgWrapper<FieldT> lhs(result, i_deviceIndex);\n    const FieldArgWrapper<FieldT> rhs(x, i_deviceIndex);\n\n    x <<= 1;\n    result <<= 0;\n\n    GhostData rhsGhostWithBC = CalculateRHSGhost<DirT, DOMAIN_SIDET>((*i_opdb.retrieve_operator<typename StencilsT<FieldT, DirT>::MainPointStencilT>())(x).expr());\n\n    GhostData const ghosts = calculate_actual_ghost(true,\n        result.get_ghost_data(),\n        result.boundary_info(),\n        rhsGhostWithBC);\n\n    IntVec const extents = result.window_with_ghost().extent()\n                         - result.get_valid_ghost_data().get_minus()\n                         - result.get_valid_ghost_data().get_plus();\n\n    IntVec const properExtents = extents + ghosts.get_plus();\n\n    if(i_mode == TIMING)\n    {\n#ifdef ENABLE_THREADS\n      throw new std::runtime_error(\"Manual implementation of varying stencil is not threaded!\");\n#endif /* ENABLE_THREADS */\n      i_timerPack->i_timer.reset();\n    }\n    //Timed code\n    {\n      static_assert(std::is_same<typename StencilsT<FieldT, DirT>::NBasicFourT,  typename StencilsT<FieldT, DirT>::NegativeStencilListT::CurrentType>::value, \"Unexpected Stencil in Stencil List\");\n      static_assert(std::is_same<typename StencilsT<FieldT, DirT>::NBasicThreeT, typename StencilsT<FieldT, DirT>::NegativeStencilListT::Collection::CurrentType>::value, \"Unexpected Stencil in Stencil List\");\n      static_assert(std::is_same<typename StencilsT<FieldT, DirT>::NBasicTwoT,   typename StencilsT<FieldT, DirT>::NegativeStencilListT::Collection::Collection::CurrentType>::value, \"Unexpected Stencil in Stencil List\");\n      static_assert(std::is_same<typename StencilsT<FieldT, DirT>::NBasicOneT,   typename StencilsT<FieldT, DirT>::NegativeStencilListT::Collection::Collection::Collection::CurrentType>::value, \"Unexpected Stencil in Stencil List\");\n      static_assert(std::is_same<typename StencilsT<FieldT, DirT>::PBasicFourT,  typename StencilsT<FieldT, DirT>::PositiveStencilListT::CurrentType>::value, \"Unexpected Stencil in Stencil List\");\n      static_assert(std::is_same<typename StencilsT<FieldT, DirT>::PBasicThreeT, typename StencilsT<FieldT, DirT>::PositiveStencilListT::Collection::CurrentType>::value, \"Unexpected Stencil in Stencil List\");\n      static_assert(std::is_same<typename StencilsT<FieldT, DirT>::PBasicTwoT,   typename StencilsT<FieldT, DirT>::PositiveStencilListT::Collection::Collection::CurrentType>::value, \"Unexpected Stencil in Stencil List\");\n      static_assert(std::is_same<typename StencilsT<FieldT, DirT>::PBasicOneT,   typename StencilsT<FieldT, DirT>::PositiveStencilListT::Collection::Collection::Collection::CurrentType>::value, \"Unexpected Stencil in Stencil List\");\n\n      {\n        for(int z = -ghosts.get_minus()[2]; z < properExtents[2]; z++) {\n          for(int y = -ghosts.get_minus()[1]; y < properExtents[1]; y++) {\n            for(int x = -ghosts.get_minus()[0]; x < properExtents[0]; x++) {\n              int i;\n              int negi;\n              if(DirT::value == 0)\n              {\n                i = x;\n                negi = properExtents[0] - i - 1;\n              }\n              else if (DirT::value == 1)\n              {\n                i = y;\n                negi = properExtents[1] - i - 1;\n              }\n              else if (DirT::value == 2)\n              {\n                i = z;\n                negi = properExtents[2] - i - 1;\n              }\n\n              if(i < StencilsT<FieldT, DirT>::NegativeStencilListT::length && (static_cast<int>(DOMAIN_SIDET::value) == DomainEdgeSide::MINUS_SIDE::value\n                                                                           ||  static_cast<int>(DOMAIN_SIDET::value) == DomainEdgeSide::BOTH_SIDE::value))\n              {\n                switch(i)\n                {\n                  case 0:\n                    lhs.ref(x,y,z) = EvalExpr<FieldT, typename StencilsT<FieldT, DirT>::OnePointNegativeStencilCollectionT,\n                                              decltype(rhs)>::eval(rhs,\n                                                                   StencilsT<FieldT, DirT>::nCoefOne,\n                                                                   x,\n                                                                   y,\n                                                                   z);\n                    break;\n                  case 1:\n                    lhs.ref(x,y,z) = EvalExpr<FieldT, typename StencilsT<FieldT, DirT>::TwoPointNegativeStencilCollectionT,\n                                              decltype(rhs)>::eval(rhs,\n                                                                   StencilsT<FieldT, DirT>::nCoefTwo,\n                                                                   x,\n                                                                   y,\n                                                                   z);\n                    break;\n                  case 2:\n                    lhs.ref(x,y,z) = EvalExpr<FieldT, typename StencilsT<FieldT, DirT>::ThreePointNegativeStencilCollectionT,\n                                              decltype(rhs)>::eval(rhs,\n                                                                   StencilsT<FieldT, DirT>::nCoefThree,\n                                                                   x,\n                                                                   y,\n                                                                   z);\n                    break;\n                  default:\n                  case 3:\n                    lhs.ref(x,y,z) = EvalExpr<FieldT, typename StencilsT<FieldT, DirT>::FourPointNegativeStencilCollectionT,\n                                              decltype(rhs)>::eval(rhs,\n                                                                   StencilsT<FieldT, DirT>::nCoefFour,\n                                                                   x,\n                                                                   y,\n                                                                   z);\n                    break;\n                }\n              }\n              else if(negi < StencilsT<FieldT, DirT>::PositiveStencilListT::length && (static_cast<int>(DOMAIN_SIDET::value) == DomainEdgeSide::PLUS_SIDE::value\n                                                                                   ||  static_cast<int>(DOMAIN_SIDET::value) == DomainEdgeSide::BOTH_SIDE::value))\n              {\n                switch(negi)\n                {\n                  case 0:\n                    lhs.ref(x,y,z) = EvalExpr<FieldT, typename StencilsT<FieldT, DirT>::OnePointPositiveStencilCollectionT,\n                                              decltype(rhs)>::eval(rhs,\n                                                                   StencilsT<FieldT, DirT>::pCoefOne,\n                                                                   x,\n                                                                   y,\n                                                                   z);\n                    break;\n                  case 1:\n                    lhs.ref(x,y,z) = EvalExpr<FieldT, typename StencilsT<FieldT, DirT>::TwoPointPositiveStencilCollectionT,\n                                              decltype(rhs)>::eval(rhs,\n                                                                   StencilsT<FieldT, DirT>::pCoefTwo,\n                                                                   x,\n                                                                   y,\n                                                                   z);\n                    break;\n                  case 2:\n                    lhs.ref(x,y,z) = EvalExpr<FieldT, typename StencilsT<FieldT, DirT>::ThreePointPositiveStencilCollectionT,\n                                              decltype(rhs)>::eval(rhs,\n                                                                   StencilsT<FieldT, DirT>::pCoefThree,\n                                                                   x,\n                                                                   y,\n                                                                   z);\n                    break;\n                  default:\n                  case 3:\n                    lhs.ref(x,y,z) = EvalExpr<FieldT, typename StencilsT<FieldT, DirT>::FourPointPositiveStencilCollectionT,\n                                              decltype(rhs)>::eval(rhs,\n                                                                   StencilsT<FieldT, DirT>::pCoefFour,\n                                                                   x,\n                                                                   y,\n                                                                   z);\n                    break;\n                }\n              }\n              else\n              {\n                lhs.ref(x,y,z) = EvalExpr<FieldT, typename StencilsT<FieldT, DirT>::MainPointStencilCollectionT,\n                                          decltype(rhs)>::eval(rhs,\n                                                               StencilsT<FieldT, DirT>::mainCoefs,\n                                                               x,\n                                                               y,\n                                                               z);\n              }\n            }\n          }\n        }\n      }\n    }\n    if(i_mode == TIMING)\n    {\n#ifdef __CUDACC__\n      cudaDeviceSynchronize();\n#endif\n      i_timerPack->o_time = i_timerPack->i_timer.stop();\n    }\n    if(i_printField)\n    {\n      print_field(result, std::cout);\n    }\n\n    if(o_result != NULL)\n    {\n      *o_result = SpatialFieldStore::get<FieldT>(result, i_deviceIndex);\n      **o_result = result;\n    }\n\n    return true;\n }\n\n  template<typename FieldT, typename DirT, typename DOMAIN_SIDET>\n  bool CustomTest( const RunMode i_mode,\n                   TimerPack* i_timerPack,\n                   const int i_deviceIndex,\n                   const IntVec i_npts,\n                   const GhostData i_fieldGhost,\n                   const BoundaryCellInfo i_bcinfo,\n                   OperatorDatabase const & i_opdb,\n                   Grid const & i_grid,\n                   const bool i_printField = false,\n                   SpatFldPtr<FieldT>* o_result = NULL )\n  {\n    const MemoryWindow mw = get_window_with_ghost(i_npts, i_fieldGhost, i_bcinfo);\n\n    FieldT x     ( mw, i_bcinfo, i_fieldGhost, NULL, InternalStorage, i_deviceIndex );\n    FieldT y     ( mw, i_bcinfo, i_fieldGhost, NULL, InternalStorage, i_deviceIndex );\n    FieldT z     ( mw, i_bcinfo, i_fieldGhost, NULL, InternalStorage, i_deviceIndex );\n    FieldT result( mw, i_bcinfo, i_fieldGhost, NULL, InternalStorage, i_deviceIndex );\n\n    // set field values\n    i_grid.set_coord<XDIR>(x);\n    i_grid.set_coord<YDIR>(y);\n    i_grid.set_coord<ZDIR>(z);\n\n    typename StencilsT<FieldT, DirT>::VaryEdgeOpT& op = *i_opdb.retrieve_operator<typename StencilsT<FieldT, DirT>::VaryEdgeOpT>();\n    x <<= 1;\n    result <<= 0;\n    if(i_mode == TIMING)\n    {\n      i_timerPack->i_timer.reset();\n    }\n    //Timed code\n    {\n#ifdef PROFILING\n      CALLGRIND_START_INSTRUMENTATION;\n#endif /* PROFILING */\n      result <<= op.operator()(x);\n#ifdef PROFILING\n      CALLGRIND_STOP_INSTRUMENTATION;\n#endif /* PROFILING */\n    }\n    if(i_mode == TIMING)\n    {\n#ifdef __CUDACC__\n      cudaDeviceSynchronize();\n#endif\n      i_timerPack->o_time = i_timerPack->i_timer.stop();\n    }\n    if(i_printField)\n    {\n      print_field(result, std::cout);\n    }\n\n    if(o_result != NULL)\n    {\n      *o_result = SpatialFieldStore::get<FieldT>(result, i_deviceIndex);\n      **o_result = result;\n    }\n\n    return true;\n  }\n}\n#endif /* USING_VARYING_EDGE_STENCIL */\n\nnamespace MainStencilTest\n{\n  template<typename FieldT, typename DirT, typename DOMAIN_SIDET>\n  bool CustomTest( const RunMode i_mode,\n                   TimerPack* i_timerPack,\n                   const int i_deviceIndex,\n                   const IntVec i_npts,\n                   const GhostData i_fieldGhost,\n                   const BoundaryCellInfo i_bcinfo,\n                   OperatorDatabase const & i_opdb,\n                   Grid const & i_grid,\n                   const bool i_printField = false,\n                   SpatFldPtr<FieldT>* o_result = NULL )\n  {\n    const MemoryWindow mw = get_window_with_ghost(i_npts, i_fieldGhost, i_bcinfo);\n\n    FieldT x     ( mw, i_bcinfo, i_fieldGhost, NULL, InternalStorage, i_deviceIndex );\n    FieldT y     ( mw, i_bcinfo, i_fieldGhost, NULL, InternalStorage, i_deviceIndex );\n    FieldT z     ( mw, i_bcinfo, i_fieldGhost, NULL, InternalStorage, i_deviceIndex );\n    FieldT result( mw, i_bcinfo, i_fieldGhost, NULL, InternalStorage, i_deviceIndex );\n\n    // set field values\n    i_grid.set_coord<XDIR>(x);\n    i_grid.set_coord<YDIR>(y);\n    i_grid.set_coord<ZDIR>(z);\n\n    typename StencilsT<FieldT, DirT>::MainPointStencilT& op = *i_opdb.retrieve_operator<typename StencilsT<FieldT, DirT>::MainPointStencilT>();\n    x <<= 1;\n    result <<= 0;\n    if(i_mode == TIMING)\n    {\n      i_timerPack->i_timer.reset();\n    }\n    //Timed code\n    {\n      result <<= op.operator()(x);\n    }\n    if(i_mode == TIMING)\n    {\n#ifdef __CUDACC__\n      cudaDeviceSynchronize();\n#endif\n      i_timerPack->o_time = i_timerPack->i_timer.stop();\n    }\n    if(i_printField)\n    {\n      print_field(result, std::cout);\n    }\n\n    if(o_result != NULL)\n    {\n      *o_result = SpatialFieldStore::get<FieldT>(result, i_deviceIndex);\n      **o_result = result;\n    }\n\n    return true;\n  }\n}\n\n//--------------------------------------------------------------------\n\ntemplate<typename FieldT, typename DirT, typename DOMAIN_SIDET>\nbool RunTests( const int i_deviceIndex, const double i_length, const IntVec i_npts, const GhostData i_fieldGhost, const BoundaryCellInfo i_bcinfo, Grid const & i_grid, const bool i_printField = false )\n{\n  TestHelper status( true );\n#ifdef USING_VARYING_EDGE_STENCIL\n  OperatorDatabase opdb;\n  StencilsT<FieldT, DirT>::build_varying_stencils( i_npts[0], i_npts[1], i_npts[2], i_length, i_length, i_length, opdb );\n\n  //Get varying edge result\n  SpatFldPtr<FieldT> neboResult;\n  NinePointVaryingStencilTest::CustomTest<FieldT, DirT, DOMAIN_SIDET>(CORRECTNESS, NULL, i_deviceIndex, i_npts, i_fieldGhost, i_bcinfo, opdb, i_grid, i_printField, &neboResult);\n\n  //Compare to other results\n  SpatFldPtr<FieldT> other;\n  //Nine Point Stencil\n  if(std::is_same<DomainEdgeSide::NO_SIDE, DOMAIN_SIDET>::value)\n  {\n    MainStencilTest::CustomTest<FieldT, DirT, DOMAIN_SIDET>(CORRECTNESS, NULL, i_deviceIndex, i_npts, i_fieldGhost, i_bcinfo, opdb, i_grid, i_printField, &other);\n    status( field_equal(*neboResult, *other), \"Varying edge equal to normal Nebo nine point stencil\" );\n  }\n  if(i_deviceIndex != GPU_INDEX)\n  {\n    //Manual implementation with linear iteration and if statements\n    {\n      NinePointVaryingStencilTest::CustomTestManual<FieldT, DirT, DOMAIN_SIDET>(CORRECTNESS, NULL, i_deviceIndex, i_npts, i_fieldGhost, i_bcinfo, opdb, i_grid, i_printField, &other);\n      status( field_equal(*neboResult, *other), \"Varying edge equal to manual implementation with if statements stencil\" );\n    }\n  }\n  //Manual implementation which iterates along edges\n  {\n    NinePointVaryingStencilTest::CustomTestManualEdgeIteration<FieldT, DirT, DOMAIN_SIDET>(CORRECTNESS, NULL, i_deviceIndex, i_npts, i_fieldGhost, i_bcinfo, opdb, i_grid, i_printField, &other);\n    status( field_equal(*neboResult, *other), \"Varying edge equal to manual implementation with edge iteration\" );\n  }\n#endif /* USING_VARYING_EDGE_STENCIL */\n\n  return status.ok();\n}\n\ntemplate<typename FieldT>\nbool Run(const double i_length, const IntVec& i_npts, const GhostData& i_ghost, const IntVec& i_bcMinus, const IntVec& i_bcPlus, const bool i_toTime, const size_t i_timingIterations)\n{\n  const BoundaryCellInfo bcinfo = BoundaryCellInfo::build<FieldT>(i_bcMinus, i_bcPlus);\n\n  TestHelper status( true );\n\n  {\n    cout << \"  domain : \" << i_npts << endl\n         << endl;\n  }\n\n  typedef DomainEdgeSide::NO_SIDE DOMAIN_SIDET;\n  typedef XDIR DirT;\n\n\n  const Grid grid( i_npts, DoubleVec(i_length, i_length, i_length) );\n\n# ifndef __CUDACC__\n      const int deviceIndex = CPU_INDEX;\n# else\n      const int deviceIndex = GPU_INDEX;\n#endif\n\n  if(i_toTime)\n  {\n    Timer timer;\n    OperatorDatabase opdb;\n#ifndef USING_VARYING_EDGE_STENCIL\n    build_stencils                         ( i_npts[0], i_npts[1], i_npts[2], i_length, i_length, i_length, opdb );\n#else\n    StencilsT<FieldT, DirT>::build_varying_stencils( i_npts[0], i_npts[1], i_npts[2], i_length, i_length, i_length, opdb );\n#endif /* !USING_VARYING_EDGE_STENCIL */\n\n\n    //Manual main stencil\n    {\n      std::function<double(Timer&)> lambda = [&](Timer& i_timer)\n      {\n        TimerPack pack(i_timer);\n        MainStencilTest::CustomTest<FieldT, DirT, DOMAIN_SIDET>(TIMING, &pack, deviceIndex, i_npts, i_ghost, bcinfo, opdb, grid);\n        return pack.o_time;\n      };\n\n      std::cout << \"Time with Single Stencil (Main 9 point): \"\n                << ReturnMedian(lambda, timer, i_timingIterations)\n                << std::endl;\n    }\n#ifdef USING_VARYING_EDGE_STENCIL\n    //Varying edge stencil\n    {\n      std::function<double(Timer&)> lambda = [&](Timer& i_timer)\n      {\n        TimerPack pack(i_timer);\n        NinePointVaryingStencilTest::CustomTest<FieldT, DirT, DOMAIN_SIDET>(TIMING, &pack, deviceIndex, i_npts, i_ghost, bcinfo, opdb, grid);\n        return pack.o_time;\n      };\n\n      std::cout << \"Time with Nebo: \"\n                << ReturnMedian(lambda, timer, i_timingIterations)\n                << std::endl;\n    }\n    //Manual varying edge stencil\n    {\n      std::function<double(Timer&)> lambda = [&](Timer& i_timer)\n      {\n        TimerPack pack(i_timer);\n        NinePointVaryingStencilTest::CustomTestManual<FieldT, DirT, DOMAIN_SIDET>(TIMING, &pack, deviceIndex, i_npts, i_ghost, bcinfo, opdb, grid);\n        return pack.o_time;\n      };\n\n      std::cout << \"Time via Manual: \"\n                << ReturnMedian(lambda, timer, i_timingIterations)\n                << std::endl;\n    }\n    //Manual varying edge stencil edge iteration\n    {\n      std::function<double(Timer&)> lambda = [&](Timer& i_timer)\n      {\n        TimerPack pack(i_timer);\n        NinePointVaryingStencilTest::CustomTestManualEdgeIteration<FieldT, DirT, DOMAIN_SIDET>(TIMING, &pack, deviceIndex, i_npts, i_ghost, bcinfo, opdb, grid);\n        return pack.o_time;\n      };\n\n      std::cout << \"Time with iteraing along edges: \"\n                << ReturnMedian(lambda, timer, i_timingIterations)\n                << std::endl;\n    }\n#endif /* USING_VARYING_EDGE_STENCIL */\n  }\n  else\n  {\n#ifdef USING_VARYING_EDGE_STENCIL\n    const bool printField = false;\n\n    const int xSideExecute = i_bcMinus[0] != 0 ? (i_bcPlus[0] != 0 ? static_cast<int>(DomainEdgeSide::BOTH_SIDE::value) : static_cast<int>(DomainEdgeSide::MINUS_SIDE::value))\n                                               : (i_bcPlus[0] != 0 ? static_cast<int>(DomainEdgeSide::PLUS_SIDE::value) : static_cast<int>(DomainEdgeSide::NO_SIDE::value));\n    const int ySideExecute = i_bcMinus[1] != 0 ? (i_bcPlus[1] != 0 ? static_cast<int>(DomainEdgeSide::BOTH_SIDE::value) : static_cast<int>(DomainEdgeSide::MINUS_SIDE::value))\n                                               : (i_bcPlus[1] != 0 ? static_cast<int>(DomainEdgeSide::PLUS_SIDE::value) : static_cast<int>(DomainEdgeSide::NO_SIDE::value));\n    const int zSideExecute = i_bcMinus[2] != 0 ? (i_bcPlus[2] != 0 ? static_cast<int>(DomainEdgeSide::BOTH_SIDE::value) : static_cast<int>(DomainEdgeSide::MINUS_SIDE::value))\n                                               : (i_bcPlus[2] != 0 ? static_cast<int>(DomainEdgeSide::PLUS_SIDE::value) : static_cast<int>(DomainEdgeSide::NO_SIDE::value));\n\n    switch(xSideExecute)\n    {\n      case DomainEdgeSide::NO_SIDE::value:\n        status( RunTests<FieldT, XDIR, DomainEdgeSide::NO_SIDE   >( deviceIndex, i_length, i_npts, i_ghost, bcinfo, grid, printField ), \"XDIR NO_SIDE\");\n        break;\n      case DomainEdgeSide::MINUS_SIDE::value:\n        status( RunTests<FieldT, XDIR, DomainEdgeSide::MINUS_SIDE>( deviceIndex, i_length, i_npts, i_ghost, bcinfo, grid, printField ), \"XDIR MINUS_SIDE\");\n        break;\n      case DomainEdgeSide::PLUS_SIDE::value:\n        status( RunTests<FieldT, XDIR, DomainEdgeSide::PLUS_SIDE >( deviceIndex, i_length, i_npts, i_ghost, bcinfo, grid, printField ), \"XDIR PLUS_SIDE\");\n        break;\n      case DomainEdgeSide::BOTH_SIDE::value:\n        status( RunTests<FieldT, XDIR, DomainEdgeSide::BOTH_SIDE >( deviceIndex, i_length, i_npts, i_ghost, bcinfo, grid, printField ), \"XDIR BOTH_SIDE\");\n        break;\n    }\n    switch(ySideExecute)\n    {\n      case DomainEdgeSide::NO_SIDE::value:\n        status( RunTests<FieldT, YDIR, DomainEdgeSide::NO_SIDE   >( deviceIndex, i_length, i_npts, i_ghost, bcinfo, grid, printField ), \"YDIR NO_SIDE\");\n        break;\n      case DomainEdgeSide::MINUS_SIDE::value:\n        status( RunTests<FieldT, YDIR, DomainEdgeSide::MINUS_SIDE>( deviceIndex, i_length, i_npts, i_ghost, bcinfo, grid, printField ), \"YDIR MINUS_SIDE\");\n        break;\n      case DomainEdgeSide::PLUS_SIDE::value:\n        status( RunTests<FieldT, YDIR, DomainEdgeSide::PLUS_SIDE >( deviceIndex, i_length, i_npts, i_ghost, bcinfo, grid, printField ), \"YDIR PLUS_SIDE\");\n        break;\n      case DomainEdgeSide::BOTH_SIDE::value:\n        status( RunTests<FieldT, YDIR, DomainEdgeSide::BOTH_SIDE >( deviceIndex, i_length, i_npts, i_ghost, bcinfo, grid, printField ), \"YDIR BOTH_SIDE\");\n        break;\n    }\n    switch(zSideExecute)\n    {\n      case DomainEdgeSide::NO_SIDE::value:\n        status( RunTests<FieldT, ZDIR, DomainEdgeSide::NO_SIDE   >( deviceIndex, i_length, i_npts, i_ghost, bcinfo, grid, printField ), \"ZDIR NO_SIDE\");\n        break;\n      case DomainEdgeSide::MINUS_SIDE::value:\n        status( RunTests<FieldT, ZDIR, DomainEdgeSide::MINUS_SIDE>( deviceIndex, i_length, i_npts, i_ghost, bcinfo, grid, printField ), \"ZDIR MINUS_SIDE\");\n        break;\n      case DomainEdgeSide::PLUS_SIDE::value:\n        status( RunTests<FieldT, ZDIR, DomainEdgeSide::PLUS_SIDE >( deviceIndex, i_length, i_npts, i_ghost, bcinfo, grid, printField ), \"ZDIR PLUS_SIDE\");\n        break;\n      case DomainEdgeSide::BOTH_SIDE::value:\n        status( RunTests<FieldT, ZDIR, DomainEdgeSide::BOTH_SIDE >( deviceIndex, i_length, i_npts, i_ghost, bcinfo, grid, printField ), \"ZDIR BOTH_SIDE\");\n        break;\n    }\n#endif /* USING_VARYING_EDGE_STENCIL */\n  }\n\n  return status.ok();\n}\n\n//--------------------------------------------------------------------\n\nenum FieldTypeEnum\n{\n  SVOL,\n  XVOL,\n  YVOL,\n  ZVOL,\n};\n\nstd::istream& operator>>(std::istream& in, FieldTypeEnum& field)\n{\n    std::string token;\n    in >> token;\n    if (token == \"SVOL\")\n        field = SVOL;\n    else if (token == \"XVOL\")\n      field = XVOL;\n    else if (token == \"YVOL\")\n      field = YVOL;\n    else if (token == \"ZVOL\")\n      field = ZVOL;\n    else \n        in.setstate(std::ios_base::failbit);\n    return in;\n}\n\nint main( int iarg, char* carg[] )\n{\n  int nx, ny, nz;\n  double length;\n  size_t timingIterations;\n  bool toTime;\n  bool pbcx = false, pbcy = false, pbcz = false;\n  bool nbcx = false, nbcy = false, nbcz = false;\n  int pgx, pgy, pgz;\n  int ngx, ngy, ngz;\n  FieldTypeEnum fieldEnum;\n  {\n    po::options_description desc(\"Supported Options\");\n    desc.add_options()\n          ( \"help\", \"print help message\\n\" )\n          ( \"timing\",  \"run timing tests instead of correctness tests\" )\n          ( \"timing-iterations\",   po::value<size_t>(&timingIterations)->default_value(100), \"Number of iterations to run while timing of which the median is taken\" )\n          ( \"nx\", po::value<int>   ( &nx     )->default_value( 32   ), \"number of points in x-dir for base mesh\" )\n          ( \"ny\", po::value<int>   ( &ny     )->default_value( 32   ), \"number of points in y-dir for base mesh\" )\n          ( \"nz\", po::value<int>   ( &nz     )->default_value( 32   ), \"number of points in z-dir for base mesh\" )\n          ( \"pbcx\", \"positive boundary condition on x-dir or not\" )\n          ( \"pbcy\", \"positive boundary condition on y-dir or not\" )\n          ( \"pbcz\", \"positive boundary condition on z-dir or not\" )\n          ( \"nbcx\", \"negative boundary condition on x-dir or not\" )\n          ( \"nbcy\", \"negative boundary condition on y-dir or not\" )\n          ( \"nbcz\", \"negative boundary condition on z-dir or not\" )\n          ( \"pgx\", po::value<int>   ( &pgx     )->default_value( 1   ), \"number of ghosts in positive x-dir for base mesh\" )\n          ( \"pgy\", po::value<int>   ( &pgy     )->default_value( 1   ), \"number of ghosts in positive y-dir for base mesh\" )\n          ( \"pgz\", po::value<int>   ( &pgz     )->default_value( 1   ), \"number of ghosts in positive z-dir for base mesh\" )\n          ( \"ngx\", po::value<int>   ( &ngx     )->default_value( 1   ), \"number of ghosts in negative x-dir for base mesh\" )\n          ( \"ngy\", po::value<int>   ( &ngy     )->default_value( 1   ), \"number of ghosts in negative y-dir for base mesh\" )\n          ( \"ngz\", po::value<int>   ( &ngz     )->default_value( 1   ), \"number of ghosts in negative z-dir for base mesh\" )\n          ( \"Field\", po::value<FieldTypeEnum>(&fieldEnum), \"type of field to run tests on [SVOL, XVOL, YVOL, or ZVOL]\" )\n          ( \"l\",  po::value<double>( &length )->default_value( 0.01 ), \"length of the domain\"                    );\n\n    po::variables_map args;\n    po::store( po::parse_command_line(iarg,carg,desc), args );\n    po::notify(args);\n\n    if( args.count(\"help\") ){\n      cout << desc << endl\n          << \"Example:\" << endl\n          << \"  test_varying_edge_stencil --nx 5 --ny 10 --nz 3 \" << endl\n          << endl;\n      return -1;\n    }\n\n    toTime = ( args.count(\"timing\") > 0 );\n\n    if( args.count(\"pbcx\") ) pbcx = true;\n    if( args.count(\"pbcy\") ) pbcy = true;\n    if( args.count(\"pbcz\") ) pbcz = true;\n    if( args.count(\"nbcx\") ) nbcx = true;\n    if( args.count(\"nbcy\") ) nbcy = true;\n    if( args.count(\"nbcz\") ) nbcz = true;\n  }\n\n  const IntVec bcMinus(nbcx, nbcy, nbcz);\n  const IntVec bcPlus(pbcx, pbcy, pbcz);\n  const GhostData ghost(ngx, pgx, ngy, pgy, ngz, pgz);\n  const IntVec npts(nx,ny,nz);\n\n  bool ret;\n  {\n    switch(fieldEnum)\n    {\n      default:\n      case SVOL:\n        cout << \"Field: SVolField\" << endl;\n        ret = Run<SVolField>(length, npts, ghost, bcMinus, bcPlus, toTime, timingIterations);\n        break;\n      case XVOL:\n        cout << \"Field: XVolField\" << endl;\n        ret = Run<XVolField>(length, npts, ghost, bcMinus, bcPlus, toTime, timingIterations);\n        break;\n      case YVOL:\n        cout << \"Field: YVolField\" << endl;\n        ret = Run<YVolField>(length, npts, ghost, bcMinus, bcPlus, toTime, timingIterations);\n        break;\n      case ZVOL:\n        cout << \"Field: ZVolField\" << endl;\n        ret = Run<ZVolField>(length, npts, ghost, bcMinus, bcPlus, toTime, timingIterations);\n        break;\n    }\n  }\n\n\n  if( ret ){\n    cout << \"Tests passed\" << endl;\n    return 0;\n  }\n  else {\n    cout << \"******************************\" << endl\n        << \"At least one test did not pass\" << endl\n        << \"******************************\" << endl;\n    return -1;\n  }\n}\n\n//--------------------------------------------------------------------\n\n", "meta": {"hexsha": "5154549306a35e591870055f314935843d8f3cc7", "size": 84768, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "spatialops/structured/stencil/test/test_varying_edge_stencil.cpp", "max_stars_repo_name": "MaxZZG/SpatialOps", "max_stars_repo_head_hexsha": "c673081a6214ac3020d2fa92d09663922815f740", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "spatialops/structured/stencil/test/test_varying_edge_stencil.cpp", "max_issues_repo_name": "MaxZZG/SpatialOps", "max_issues_repo_head_hexsha": "c673081a6214ac3020d2fa92d09663922815f740", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "spatialops/structured/stencil/test/test_varying_edge_stencil.cpp", "max_forks_repo_name": "MaxZZG/SpatialOps", "max_forks_repo_head_hexsha": "c673081a6214ac3020d2fa92d09663922815f740", "max_forks_repo_licenses": ["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.3698311008, "max_line_length": 236, "alphanum_fraction": 0.5571088146, "num_tokens": 19630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743168019989179, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.4515958347450584}}
{"text": "/**\n * $Id$\n *\n * Copyright (C)\n * 2015 - $Date$\n *     Martin Wolf <ndhist@martin-wolf.org>\n *\n * This file is distributed under the BSD 2-Clause Open Source License\n * (See LICENSE file).\n *\n */\n#include <boost/python.hpp>\n\n#include <ndhist/stats/var.hpp>\n\nnamespace bp = boost::python;\n\nnamespace ndhist {\nnamespace stats {\n\nvoid register_var()\n{\n    bp::def(\"var\"\n      , &py::var\n      , ( bp::arg(\"hist\")\n        , bp::arg(\"axis\")=bp::object()\n        )\n      , \"Calculates the variance along the given axis of the given ndhist    \\n\"\n        \"object. As in statistics, the variance is defined as                \\n\"\n        \":math:`V[x] = E[x^2] - E[x]^2`.                                     \\n\"\n        \"This function generates a projection along the given axis and then  \\n\"\n        \"calculates the variance.                                            \\n\"\n        \"If ``None`` is given as axis argument (the default), the variance   \\n\"\n        \"for all individual axes of the ndhist object is calculated and      \\n\"\n        \"returned as a tuple. But if the dimensionality of the histogram is  \\n\"\n        \"1, a scalar value is returned.                                      \\n\"\n        \"                                                                    \\n\"\n        \".. note:: This function is only defined for ndhist objects with POD \\n\"\n        \"          type axis values AND POD type weight values.              \\n\"\n    );\n}\n\n}// namespace stats\n}// namespace ndhist\n", "meta": {"hexsha": "a824732a288d6810fd5c6d2ee3b11e2ea1c7fcf3", "size": 1483, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/pybindings/stats/var.cpp", "max_stars_repo_name": "martwo/ndhist", "max_stars_repo_head_hexsha": "193cef3585b5d0277f0721bb9c3a1e78cc67cf1f", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/pybindings/stats/var.cpp", "max_issues_repo_name": "martwo/ndhist", "max_issues_repo_head_hexsha": "193cef3585b5d0277f0721bb9c3a1e78cc67cf1f", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pybindings/stats/var.cpp", "max_forks_repo_name": "martwo/ndhist", "max_forks_repo_head_hexsha": "193cef3585b5d0277f0721bb9c3a1e78cc67cf1f", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.9555555556, "max_line_length": 80, "alphanum_fraction": 0.5131490223, "num_tokens": 341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680199891789, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4515958347450582}}
{"text": "// Authors: David Alexander, Lance Hepler\n\n#include <pbcopper/align/AffineAlignment.h>\n\n#include <cassert>\n#include <cfloat>\n\n#include <algorithm>\n#include <string>\n#include <vector>\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n\n#include <pbcopper/align/PairwiseAlignment.h>\n#include <pbcopper/utility/MinMax.h>\n#include <pbcopper/utility/SequenceUtils.h>\n\nnamespace PacBio {\nnamespace Align {\n\nnamespace {\n\nclass IupacAware;\nclass Standard;\n\ninline bool IsIupacPartialMatch(char iupacCode, char b)\n{\n    assert(iupacCode != b);\n\n    switch (iupacCode) {\n        case 'R':\n            return (b == 'A' || b == 'G');\n        case 'Y':\n            return (b == 'C' || b == 'T');\n        case 'S':\n            return (b == 'G' || b == 'C');\n        case 'W':\n            return (b == 'A' || b == 'T');\n        case 'K':\n            return (b == 'G' || b == 'T');\n        case 'M':\n            return (b == 'A' || b == 'C');\n        default:\n            return false;\n    }\n}\n\ntemplate <typename C>\nfloat MatchScore(char t, char q, float matchScore, float mismatchScore, float partialMatchScore);\n\ntemplate <>\nfloat MatchScore<Standard>(char t, char q, float matchScore, float mismatchScore, float /*unused*/)\n{\n    return (t == q ? matchScore : mismatchScore);\n}\n\ntemplate <>\nfloat MatchScore<IupacAware>(char t, char q, float matchScore, float mismatchScore,\n                             float partialMatchScore)\n{\n    if (t == q) {\n        return matchScore;\n    } else if (IsIupacPartialMatch(t, q) || IsIupacPartialMatch(q, t)) {\n        return partialMatchScore;\n    } else {\n        return mismatchScore;\n    }  // NOLINT\n}\n\ntemplate <class C>\nPairwiseAlignment* AlignAffineGeneric(const std::string& target, const std::string& query,\n                                      AffineAlignmentParams params)\n{\n    // Implementation follows the textbook \"two-state\" affine gap model\n    // description from Durbin et. al\n    using boost::numeric::ublas::matrix;\n\n    int I = query.length();\n    int J = target.length();\n    matrix<float> M(I + 1, J + 1);\n    matrix<float> GAP(I + 1, J + 1);\n\n    // Initialization\n    M(0, 0) = 0;\n    GAP(0, 0) = -FLT_MAX;\n    for (int i = 1; i <= I; ++i) {\n        M(i, 0) = -FLT_MAX;\n        GAP(i, 0) = params.GapOpen + (i - 1) * params.GapExtend;\n    }\n    for (int j = 1; j <= J; ++j) {\n        M(0, j) = -FLT_MAX;\n        GAP(0, j) = params.GapOpen + (j - 1) * params.GapExtend;\n    }\n\n    // Main part of the recursion\n    for (int i = 1; i <= I; ++i) {\n        for (int j = 1; j <= J; ++j) {\n            float matchScore = MatchScore<C>(target[j - 1], query[i - 1], params.MatchScore,\n                                             params.MismatchScore, params.PartialMatchScore);\n            M(i, j) = std::max(M(i - 1, j - 1), GAP(i - 1, j - 1)) + matchScore;\n            GAP(i, j) =\n                Utility::Max(M(i, j - 1) + params.GapOpen, GAP(i, j - 1) + params.GapExtend,\n                             M(i - 1, j) + params.GapOpen, GAP(i - 1, j) + params.GapExtend);\n        }\n    }\n\n    // Perform the traceback\n    const int MATCH_MATRIX = 1;\n    const int GAP_MATRIX = 2;\n\n    std::string raQuery;\n    std::string raTarget;\n    int i = I;\n    int j = J;\n    int mat = (M(I, J) >= GAP(I, J) ? MATCH_MATRIX : GAP_MATRIX);\n    int iPrev;\n    int jPrev;\n    int matPrev;\n    while (i > 0 || j > 0) {\n        if (mat == MATCH_MATRIX) {\n            matPrev = (M(i - 1, j - 1) >= GAP(i - 1, j - 1) ? MATCH_MATRIX : GAP_MATRIX);\n            iPrev = i - 1;\n            jPrev = j - 1;\n            raQuery.push_back(query[iPrev]);\n            raTarget.push_back(target[jPrev]);\n        } else {\n            assert(mat == GAP_MATRIX);\n            float s[4];\n            s[0] = (j > 0 ? M(i, j - 1) + params.GapOpen : -FLT_MAX);\n            s[1] = (j > 0 ? GAP(i, j - 1) + params.GapExtend : -FLT_MAX);\n            s[2] = (i > 0 ? M(i - 1, j) + params.GapOpen : -FLT_MAX);\n            s[3] = (i > 0 ? GAP(i - 1, j) + params.GapExtend : -FLT_MAX);\n            int argMax = std::max_element(s, s + 4) - s;\n\n            matPrev = ((argMax == 0 || argMax == 2) ? MATCH_MATRIX : GAP_MATRIX);\n            if (argMax == 0 || argMax == 1) {\n                iPrev = i;\n                jPrev = j - 1;\n                raQuery.push_back('-');\n                raTarget.push_back(target[jPrev]);\n            } else {\n                iPrev = i - 1;\n                jPrev = j;\n                raQuery.push_back(query[iPrev]);\n                raTarget.push_back('-');\n            }\n        }\n\n        // Go to previous square\n        i = iPrev;\n        j = jPrev;\n        mat = matPrev;\n    }\n\n    assert(raQuery.length() == raTarget.length());\n    return new PairwiseAlignment(Utility::Reversed(raTarget), Utility::Reversed(raQuery));\n}\n\n}  // anonymous namespace\n\nAffineAlignmentParams::AffineAlignmentParams(float matchScore, float mismatchScore, float gapOpen,\n                                             float gapExtend, float partialMatchScore)\n    : MatchScore(matchScore)\n    , MismatchScore(mismatchScore)\n    , GapOpen(gapOpen)\n    , GapExtend(gapExtend)\n    , PartialMatchScore(partialMatchScore)\n{\n}\n\nAffineAlignmentParams DefaultAffineAlignmentParams() { return {0, -1.0, -1.0, -0.5, 0}; }\n\nAffineAlignmentParams IupacAwareAffineAlignmentParams() { return {0, -1.0, -1.0, -0.5, -0.25}; }\n\nPairwiseAlignment* AlignAffine(const std::string& target, const std::string& query,\n                               AffineAlignmentParams params)\n{\n    return AlignAffineGeneric<Standard>(target, query, params);\n}\n\nPairwiseAlignment* AlignAffineIupac(const std::string& target, const std::string& query,\n                                    AffineAlignmentParams params)\n{\n    return AlignAffineGeneric<IupacAware>(target, query, params);\n}\n\n}  // namespace Align\n}  // namespace PacBio\n", "meta": {"hexsha": "44396bec3903827138e7ddc8d5de32ce66396444", "size": 5852, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/align/AffineAlignment.cpp", "max_stars_repo_name": "mr-c/pbcopper", "max_stars_repo_head_hexsha": "6226c0adf041db717360cf0066bc91e8f556bf48", "max_stars_repo_licenses": ["BSD-3-Clause-Clear"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/align/AffineAlignment.cpp", "max_issues_repo_name": "mr-c/pbcopper", "max_issues_repo_head_hexsha": "6226c0adf041db717360cf0066bc91e8f556bf48", "max_issues_repo_licenses": ["BSD-3-Clause-Clear"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/align/AffineAlignment.cpp", "max_forks_repo_name": "mr-c/pbcopper", "max_forks_repo_head_hexsha": "6226c0adf041db717360cf0066bc91e8f556bf48", "max_forks_repo_licenses": ["BSD-3-Clause-Clear"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8, "max_line_length": 99, "alphanum_fraction": 0.5452836637, "num_tokens": 1656, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.451595827831858}}
{"text": "/**\n *  @file\n *  @copyright defined in evt/LICENSE.txt\n */\n#include <evt/chain/contracts/evt_link.hpp>\n\n#include <string.h>\n#include <algorithm>\n\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/endian/conversion.hpp>\n\n#include <fc/crypto/hex.hpp>\n#include <fc/crypto/elliptic.hpp>\n#include <evt/chain/exceptions.hpp>\n\nusing namespace boost::multiprecision;\n\n// pay: 2(header) + 5(time) + 5(max_pay) + 7(symbol) + 16(link-id)  = 35\n// pass: 2(header) + 5(time) + 22(domain) + 22(token) + 16(link-id) = 67\n// sigs: 65 * 3 = 195\nusing bigint_segs = number<cpp_int_backend<536, 536, unsigned_magnitude, checked, void>>;\nusing bigint_sigs = number<cpp_int_backend<1560, 1560, unsigned_magnitude, checked, void>>;\n\nnamespace evt { namespace chain { namespace contracts {\n\nnamespace internal {\n\nconst char* ALPHABETS  = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ$+-/:*\";\nconst int   MAX_BYTES  = 240;  // 195 / ((42 ^ 2) / 2048)\nconst char* URI_SCHEMA = \"https://evt.li/\";\n\ntemplate<typename T>\nbytes\ndecode(const std::string& nums, uint pos, uint end) {\n    auto num = T{0};\n    auto pz  = nums.find_first_not_of('0', pos);\n    EVT_ASSERT(pz != string::npos, evt_link_exception, \"Invalid EVT-Link\");\n\n    for(auto i = pz; i < end; i++) {\n        auto c = strchr(ALPHABETS, nums[i]);\n        FC_ASSERT(c != nullptr, \"invalid character in evt-link\");\n        num *= 42;\n        num += (c - ALPHABETS);\n    }\n\n    auto b = bytes();\n    b.reserve(MAX_BYTES);\n    for(auto i = 0u; i < (pz - pos); i++) {\n        b.emplace_back(0);\n    }\n    boost::multiprecision::export_bits(num, std::back_inserter(b), 8);\n\n    return b;\n}\n\nevt_link::segments_type\nparse_segments(const bytes& b, uint16_t& header) {\n    FC_ASSERT(b.size() > 2);\n\n    auto h  = *(uint16_t*)&b[0];\n    header  = boost::endian::big_to_native(h);\n\n    auto segs = evt_link::segments_type();\n\n    auto i  = 2u;\n    auto pk = 0u;\n    while(i < b.size()) {\n        auto k = (uint8_t)b[i];\n        EVT_ASSERT(k > pk, evt_link_exception, \"Segments are not ordered by keys\");\n        pk = k;\n\n        if(k <= 20) {\n            FC_ASSERT(b.size() > i + 1); // value is 1 byte\n            auto v = (uint8_t)b[i + 1];\n            segs.emplace(k, evt_link::segment(k, v));\n\n            i += 2;\n        }\n        else if(k <= 40) {\n            FC_ASSERT(b.size() > i + 2); // value is 2 byte\n            auto v = *(uint16_t*)(&b[i] + 1);\n            segs.emplace(k, evt_link::segment(k, boost::endian::big_to_native(v)));\n\n            i += 3;\n        }\n        else if(k <= 90) {\n            FC_ASSERT(b.size() > i + 4); // value is 4 byte\n            auto v = *(uint32_t*)(&b[i] + 1);\n            segs.emplace(k, evt_link::segment(k, boost::endian::big_to_native(v)));\n\n            i += 5;\n        }\n        else if(k <= 180) {\n            auto sz = 0u;\n            auto s  = 0u;\n\n            if(k > 155 && k <= 165) {\n                sz = 16;  // uuid, sizeof(uint128_t)\n            }\n            else {\n                FC_ASSERT(b.size() > i + 1); // first read length byte\n                sz = (uint8_t)b[i + 1];\n                s  = 1;\n            }\n\n\n            if(sz > 0) {\n                FC_ASSERT(b.size() > i + s + sz);\n                segs.emplace(k, evt_link::segment(k, std::string(&b[i] + 1 + s, sz)));\n            }\n            else {\n                segs.emplace(k, evt_link::segment(k, std::string()));\n            }\n\n            i += 1 + s + sz;\n        }\n        else {\n            EVT_THROW(evt_link_exception, \"Invalid key type: ${k}\", (\"k\",k));\n        }\n    }\n    return segs;\n}\n\nevt_link::signatures_type\nparse_signatures(const bytes& b) {\n    FC_ASSERT(b.size() > 0 && b.size() % 65 == 0);\n    auto sigs = evt_link::signatures_type();\n\n    for(auto i = 0u; i < b.size() / 65u; i++) {\n        auto shim = fc::ecc::compact_signature();\n        static_assert(sizeof(shim) == 65);\n        memcpy(shim.data(), &b[0] + i * 65, 65);\n\n        sigs.emplace(fc::ecc::signature_shim(shim));\n    }\n    return sigs;\n}\n\n}  // namespace internal\n\nevt_link\nevt_link::parse_from_evtli(const std::string& str) {\n    using namespace internal;\n\n    EVT_ASSERT(str.size() < 400, evt_link_exception, \"Link is too long, max length allowed: 400\");\n    EVT_ASSERT(str.size() > 20, evt_link_exception, \"Link is too short\");\n\n    size_t start = 0;\n    if(memcmp(str.data(), URI_SCHEMA, strlen(URI_SCHEMA)) == 0) {\n        start = strlen(URI_SCHEMA);\n    }\n\n    auto d = str.find_first_of('_', start);\n    \n    auto bsegs = bytes();\n    auto bsigs = bytes();\n\n    if(d == std::string::npos) {\n        bsegs = decode<bigint_segs>(str, start, str.size());\n    }\n    else {\n        bsegs = decode<bigint_segs>(str, start, d);\n        bsigs = decode<bigint_sigs>(str, d + 1, str.size());\n    }\n\n    auto link = evt_link();\n\n    link.segments_   = parse_segments(bsegs, link.header_);\n    link.signatures_ = parse_signatures(bsigs);\n\n    return link;\n}\n\nconst evt_link::segment&\nevt_link::get_segment(uint8_t key) const {\n    auto it = segments_.find(key);\n    EVT_ASSERT(it != segments_.end(), evt_link_no_key_exception, \"Cannot find segment for key: ${k}\", (\"k\",key));\n\n    return it->second;\n}\n\nbool\nevt_link::has_segment(uint8_t key) const {\n    return segments_.find(key) != segments_.end();\n}\n\nlink_id_type\nevt_link::get_link_id() const {\n    auto& seg = get_segment(link_id);\n    EVT_ASSERT(seg.strv && seg.strv->size() == sizeof(link_id_type), evt_link_id_exception, \"Not valid link id in this EVT-Link\");\n\n    auto id = link_id_type();\n    memcpy(&id, seg.strv->data(), sizeof(id));\n    return id;\n}\n\nnamespace internal {\n\ntemplate<typename Stream>\nvoid\nwrite_segments_bytes(const evt_link& link, Stream& stream) {\n    auto h = boost::endian::native_to_big(link.get_header());\n    static_assert(sizeof(h) == 2);  // uint16_t\n    stream.write((char*)&h, sizeof(h));\n\n    for(auto& seg_ : link.get_segments()) {\n        auto  key = seg_.first;\n        auto& seg = seg_.second;\n\n        static_assert(sizeof(key) == 1);  // uint8_t\n        stream.write((char*)&key, sizeof(key));\n        if(key <= 20) {\n            auto v = *seg.intv;\n            stream.write((char*)&v, 1);\n        }\n        else if(key <= 40) {\n            auto v = boost::endian::native_to_big((uint16_t)*seg.intv);\n            stream.write((char*)&v, 2);\n        }\n        else if(key <= 90) {\n            auto v = boost::endian::native_to_big((uint32_t)*seg.intv);\n            stream.write((char*)&v, 4);\n        }\n        else if(key <= 180) {\n            if(key > 155 && key <= 165) {\n                FC_ASSERT(seg.strv->size() == 16);\n                stream.write((char*)seg.strv->data(), 16);\n            }\n            else {\n                auto s = seg.strv->size();\n                FC_ASSERT(s < 255); // 1 byte length\n\n                stream.write((char*)&s, 1);\n                stream.write(seg.strv->data(), s);\n            }\n        }\n    }\n}\n\ntemplate<typename Stream>\nstruct stream_visitor : public fc::visitor<void> {\npublic:\n    stream_visitor(Stream& stream) : stream_(stream) {}\n\npublic:\n    template<typename Sig>\n    void\n    operator()(const Sig& sig) const {\n        static_assert(sizeof(sig._data) == 65, \"sig size is expected to be 65\");\n        stream_.write((char*)sig._data.data(), 65);\n    }\n\nprivate:\n    Stream& stream_;\n};\n\ntemplate<typename Stream>\nvoid\nwrite_signatures_bytes(const evt_link& link, Stream& stream) {\n    auto visitor = stream_visitor<Stream>(stream);\n    for(auto& sig : link.get_signatures()) {\n        sig.view(visitor);\n    }\n}\n\ntemplate<typename Num>\nvoid\nencode(const bytes& b, size_t sz, std::string& str) {\n    auto i = 0u;\n    for(i = 0u; i < sz; i++) {\n        if(b[i] == 0) {\n            str.push_back('0');\n        }\n        else {\n            break;\n        }\n    }\n\n    auto num = Num{0};\n    boost::multiprecision::import_bits(num, b.begin() + i, b.begin() + sz, 8);\n\n    while(num >= 42) {\n        auto r = num % 42;\n        str.push_back(*(ALPHABETS + (int)r));\n        num /= 42;\n    }\n    str.push_back(*(ALPHABETS + (int)num));\n    std::reverse(str.begin() + i, str.end());\n}\n\n}  // namespace internal\n\nfc::sha256\nevt_link::digest() const {\n    using namespace internal;\n\n    auto enc = fc::sha256::encoder();\n    write_segments_bytes(*this, enc);\n    return enc.result();\n}\n\nstd::string\nevt_link::to_string(int prefix) const {\n    using namespace internal;\n\n    auto temp = bytes(MAX_BYTES);\n    auto ds   = fc::datastream<char*>(temp.data(), temp.size());\n    auto str  = string();\n\n    if(prefix) {\n        str.append(URI_SCHEMA);\n    }\n\n    auto str1 = string();\n    write_segments_bytes(*this, ds);\n    encode<bigint_segs>(temp, ds.tellp(), str1);\n    str.append(str1);\n\n    if(!signatures_.empty()) {\n        str.push_back('_');\n\n        ds.seekp(0);\n        write_signatures_bytes(*this, ds);\n\n        auto str2 = string();\n        encode<bigint_sigs>(temp, ds.tellp(), str2);\n        str.append(str2);\n    }\n\n    return str;\n}\n\npublic_keys_set\nevt_link::restore_keys() const {\n    auto hash = digest();\n    auto keys = public_keys_set();\n\n    keys.reserve(signatures_.size());\n    for(auto& sig : signatures_) {\n        keys.emplace(public_key_type(sig, hash));\n    }\n    return keys;\n}\n\nvoid\nevt_link::add_segment(const segment& seg) {\n    auto it = segments_.emplace(seg.key, seg);\n    if(!it.second) {\n        // existed, replace old one\n        it.first->second = seg;\n    }\n}\n\nvoid\nevt_link::remove_segment(uint8_t key) {\n    segments_.erase(key);\n}\n\nvoid\nevt_link::add_signature(const signature_type& sig) {\n    signatures_.emplace(sig);\n}\n\nvoid\nevt_link::sign(const private_key_type& pkey) {\n    signatures_.emplace(pkey.sign(digest()));\n}\n\n}}}  // namespac evt::chain::contracts\n\nnamespace fc {\n\nusing evt::chain::contracts::evt_link;\n\nvoid\nfrom_variant(const fc::variant& v, evt_link& link) {\n    link = evt_link::parse_from_evtli(v.get_string());\n}\n\nvoid\nto_variant(const evt::chain::contracts::evt_link& link, fc::variant& v) {\n    auto vo   = fc::mutable_variant_object();\n    auto segs = fc::variants();\n    auto sigs = fc::variants();\n    auto keys = fc::variants();\n    \n    for(auto& it : link.get_segments()) {\n        auto  sego = fc::mutable_variant_object();\n        auto& seg  = it.second;\n\n        sego[\"key\"] = seg.key;\n        if(seg.key <= 90) {\n            sego[\"value\"] = *seg.intv;\n        }\n        else if(seg.key <= 155) {\n            sego[\"value\"] = *seg.strv;\n        }\n        else if(seg.key <= 180) {\n            sego[\"value\"] = fc::to_hex(seg.strv->c_str(), seg.strv->size());\n        }\n        segs.emplace_back(std::move(sego));\n    }\n\n    for(auto& sig : link.get_signatures()) {\n        sigs.emplace_back((std::string)sig);\n    }\n\n    for(auto& key : link.restore_keys()) {\n        keys.emplace_back((std::string)key);\n    }\n\n\n    vo[\"header\"]     = link.get_header();\n    vo[\"segments\"]   = std::move(segs);\n    vo[\"signatures\"] = std::move(sigs);\n    vo[\"keys\"]       = std::move(keys);\n\n    v = std::move(vo);\n}\n\n}  // namespace fc\n", "meta": {"hexsha": "4d8754b52f9cf0de8248d7c984c7dee62bb51d89", "size": 10974, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libraries/chain/contracts/evt_link.cpp", "max_stars_repo_name": "Laighno/evt", "max_stars_repo_head_hexsha": "90b94e831aebb62c6ad19ce59c9089e9f51cfd77", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-06-14T06:57:55.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-14T06:57:55.000Z", "max_issues_repo_path": "libraries/chain/contracts/evt_link.cpp", "max_issues_repo_name": "Zhang-Zexi/evt", "max_issues_repo_head_hexsha": "e90fe4dbab4b9512d120c79f33ecc62791e088bd", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libraries/chain/contracts/evt_link.cpp", "max_forks_repo_name": "Zhang-Zexi/evt", "max_forks_repo_head_hexsha": "e90fe4dbab4b9512d120c79f33ecc62791e088bd", "max_forks_repo_licenses": ["Apache-2.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.9432624113, "max_line_length": 130, "alphanum_fraction": 0.5634226353, "num_tokens": 3039, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.45156693910098944}}
{"text": "/********************************************************************************\n * Copyright 2009 The Robotics Group, The Maersk Mc-Kinney Moller Institute,\n * Faculty of Engineering, University of Southern Denmark\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n ********************************************************************************/\n\n#ifndef RW_MATH_PROJECTIONMATRIX_HPP_\n#define RW_MATH_PROJECTIONMATRIX_HPP_\n\n#if !defined(SWIG)\n#include <rw/core/Ptr.hpp>\n\n#include <Eigen/Core>\n#endif \nnamespace rw { namespace math {\n\n    /**\n     * @brief projection matrix\n     */\n    class ProjectionMatrix\n    {\n      private:\n        Eigen::Matrix< double, 4, 4 > _matrix;\n\n      public:\n        typedef rw::core::Ptr< ProjectionMatrix > Ptr;\n\n        //! @brief constructor\n        ProjectionMatrix (){};\n\n        //! @brief get the boost matrix corresponding to this projection\n        const Eigen::Matrix< double, 4, 4 > e () const { return _matrix; }\n\n        //! @brief test if this is a perspective projection\n        bool isPerspectiveProjection () { return _matrix (2, 3) < -0.5; }\n\n        //! @brief test if this is a ortographic projection\n        bool isOrtographicProjection () { return _matrix (3, 3) > 0.5; }\n\n        /**\n         * @brief set the projection matrix to an ortographic projection by defining\n         * the box with length to all sides (left, right, bottom, top, near and far)\n         * @param left [in] length in m to left edge of image\n         * @param right [in] length in m to right edge of image\n         * @param bottom [in] length in m to bottom edge of image\n         * @param top [in] length in m to top edge of image\n         * @param zNear [in] length in m to near clipping plane\n         * @param zFar [in] length in m to far clipping plane\n         */\n        void setOrtho (double left, double right, double bottom, double top, double zNear,\n                       double zFar);\n\n        //! get ortographic projection. Onli valid if isOrtographicProjection is true\n        bool getOrtho (double& left, double& right, double& bottom, double& top, double& zNear,\n                       double& zFar) const;\n\n        /**\n         * @brief set the projection matrix to the viewing frustum\n         * @param left [in] distance in m near cutting plane from center to left edge\n         * @param right [in] distance in m near cutting plane from center to right edge\n         * @param bottom [in] distance in m near cutting plane from center to bottom edge\n         * @param top [in] distance in m near cutting plane from center to top edge\n         * @param zNear [in] distance in m along z-axis to near cutting plane\n         * @param zFar [in] distance in m along z-axis to far cutting plane\n         */\n        void setFrustum (double left, double right, double bottom, double top, double zNear,\n                         double zFar);\n\n        /**\n         * @brief get the projection matrix to the viewing frustum\n         * @param left [out] distance in m near cutting plane from center to left edge\n         * @param right [out] distance in m near cutting plane from center to right edge\n         * @param bottom [out] distance in m near cutting plane from center to bottom edge\n         * @param top [out] distance in m near cutting plane from center to top edge\n         * @param zNear [out] distance in m along z-axis to near cutting plane\n         * @param zFar [out] distance in m along z-axis to far cutting plane\n         */\n        bool getFrustum (double& left, double& right, double& bottom, double& top, double& zNear,\n                         double& zFar) const;\n\n        /**\n         * @brief set the projection matrix to perspective projection\n         * @param fovy [in] vertical field of view [degrees]\n         * @param aspectRatio [in] aspect ratio between width and height of image\n         * @param zNear [in] distance to near cutting plane\n         * @param zFar [in] distance to far cutting plane\n         */\n        void setPerspective (double fovy, double aspectRatio, double zNear, double zFar);\n\n        /**\n         * @brief set the projection matrix to perspective projection\n         * @param fovy [in] vertical field of view [degrees]\n         * @param width [in] width of image\n         * @param height [in] height of image\n         * @param zNear [in] distance to near cutting plane\n         * @param zFar [in] distance to far cutting plane\n         */\n        void setPerspective (double fovy, double width, double height, double zNear, double zFar)\n        {\n            return setPerspective (fovy, (width * 1.0) / height, zNear, zFar);\n        }\n\n        /**\n         * @brief get the projection matrix to perspective projection\n         * @param fovy [in] vertical field of view [degrees]\n         * @param aspectRatio [in] aspect ratio between width and height of image\n         * @param zNear [in] distance to near cutting plane\n         * @param zFar [in] distance to far cutting plane\n         * @return is it succesfull\n         */\n        bool getPerspective (double& fovy, double& aspectRatio, double& zNear, double& zFar) const;\n\n        /**\n         * @brief convert the projection matrix to an OpenGL compatible matrix\n         * @param arr [out] array of 16*sizeof(T) with the opengl matrix\n         */\n        template< class T > void toOpenGLMatrix (T arr[16])\n        {\n            for (int j = 0; j < 4; j++) {\n                for (int k = 0; k < 4; k++)\n                    arr[j + 4 * k] = static_cast< T > (_matrix (j, k));\n            }\n        }\n\n        /**\n         * @brief creates a projection matrix with a perspective projection\n         * @param fovy\n         * @param aspectRatio\n         * @param zNear\n         * @param zFar\n         * @return new ProjectionMatrix.\n         */\n        static ProjectionMatrix makePerspective (double fovy, double aspectRatio, double zNear,\n                                                 double zFar);\n\n        /**\n         * @brief creates a projection matrix with a perspective projection\n         * @param fovy [in]\n         * @param width [in] of image\n         * @param height [in] of image\n         * @param zNear [in]\n         * @param zFar [in]\n         * @return new ProjectionMatrix.\n         */\n        static ProjectionMatrix makePerspective (double fovy, double width, double height,\n                                                 double zNear, double zFar);\n\n        /**\n         * @brief creates a projection matrix with a orthographic projection\n         * @param left\n         * @param right\n         * @param bottom\n         * @param top\n         * @param zNear\n         * @param zFar\n         * @return new ProjectionMatrix.\n         */\n        static ProjectionMatrix makeOrtho (double left, double right, double bottom, double top,\n                                           double zNear, double zFar);\n\n        /**\n         * get near and far clipping plane\n         * @return\n         */\n        std::pair< double, double > getClipPlanes () const;\n    };\n\n}}    // namespace rw::math\n\n#endif /* PROJECTIONMATRIX_HPP_ */\n", "meta": {"hexsha": "1b8063c701e771fd9517ded5e0eff0f71b9cd78c", "size": 7610, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "RobWork/src/rw/math/ProjectionMatrix.hpp", "max_stars_repo_name": "ZLW07/RobWork", "max_stars_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-29T14:16:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T14:16:27.000Z", "max_issues_repo_path": "RobWork/src/rw/math/ProjectionMatrix.hpp", "max_issues_repo_name": "ZLW07/RobWork", "max_issues_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RobWork/src/rw/math/ProjectionMatrix.hpp", "max_forks_repo_name": "ZLW07/RobWork", "max_forks_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.8131868132, "max_line_length": 99, "alphanum_fraction": 0.5886990802, "num_tokens": 1734, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195385342971, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.45154801264950517}}
{"text": "\n#include <Eigen/Core>\n#include <iostream>\n#include <mex.h>\n#include <igl/C_STR.h>\n#include <igl/matlab/mexErrMsgTxt.h>\n#undef assert\n#define assert( isOK ) ( (isOK) ? (void)0 : (void) ::mexErrMsgTxt(C_STR(__FILE__<<\":\"<<__LINE__<<\": failed assertion `\"<<#isOK<<\"'\"<<std::endl) ) )\n\n#include <igl/PI.h>\n#include <igl/iterative_closest_point.h>\n#include <igl/matlab/MexStream.h>\n#include <igl/matlab/parse_rhs.h>\n#include <igl/matlab/prepare_lhs.h>\n#include <igl/matlab/validate_arg.h>\n\n\nvoid mexFunction(\n  int          nlhs,\n  mxArray      *plhs[],\n  int          nrhs,\n  const mxArray *prhs[]\n)\n{\n  using namespace igl::matlab;\n  Eigen::MatrixXd VX,VY;\n  Eigen::MatrixXi FX,FY;\n  igl::matlab::MexStream mout;        \n  std::streambuf *outbuf = std::cout.rdbuf(&mout);\n  mexPrintf(\"Compiled at %s on %s\\n\",__TIME__,__DATE__);\n  mexErrMsgTxt(nrhs>=4,\"nrhs should be >= 4\");\n  parse_rhs_double(prhs+0,VX);\n  parse_rhs_index(prhs+1,FX);\n  parse_rhs_double(prhs+2,VY);\n  parse_rhs_index(prhs+3,FY);\n  int num_iters = 100;\n  int num_samples = 1000;\n\n  {\n    int i = 4;\n    while(i<nrhs)\n    {\n      mexErrMsgTxt(mxIsChar(prhs[i]),\"Parameter names should be strings\");\n      // Cast to char\n      const char * name = mxArrayToString(prhs[i]);\n      if(strcmp(\"MaxIter\",name)==0)\n      {\n        igl::matlab::validate_arg_scalar(i,nrhs,prhs,name);\n        igl::matlab::validate_arg_double(i,nrhs,prhs,name);\n        num_iters = (double)*mxGetPr(prhs[++i]);\n      }\n      else if(strcmp(\"NumSamples\",name)==0)\n      {\n        igl::matlab::validate_arg_scalar(i,nrhs,prhs,name);\n        igl::matlab::validate_arg_double(i,nrhs,prhs,name);\n        num_samples = (double)*mxGetPr(prhs[++i]);\n      }\n      else\n      {\n        mexErrMsgTxt(false,C_STR(\"Unrecognized Parameter: \"<<name));\n      }\n      i++;\n    }\n  }\n\n  Eigen::Matrix3d R;\n  Eigen::RowVector3d t;\n  igl::iterative_closest_point(VX,FX,VY,FY,num_samples,num_iters,R,t);\n\n  switch(nlhs)\n  {\n    case 3:\n    {\n      Eigen::MatrixXd VXRT = (VX*R).rowwise()+t;\n      prepare_lhs_double(VXRT,plhs+2);\n    }\n    case 2:\n      prepare_lhs_double(t,plhs+1);\n    case 1:\n      prepare_lhs_double(R,plhs+0);\n    default:break;\n  }\n\n  // Restore the std stream buffer Important!\n  std::cout.rdbuf(outbuf);\n  return;\n}\n", "meta": {"hexsha": "4e963d58c3377c1e1c1bd976eb62740697c5ecd3", "size": 2261, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gplottoolbox/mex/icp.cpp", "max_stars_repo_name": "karlic-luka/Spectral-clustering", "max_stars_repo_head_hexsha": "711042281c9fbedea1f12be822c9f55b629cc854", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gplottoolbox/mex/icp.cpp", "max_issues_repo_name": "karlic-luka/Spectral-clustering", "max_issues_repo_head_hexsha": "711042281c9fbedea1f12be822c9f55b629cc854", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gplottoolbox/mex/icp.cpp", "max_forks_repo_name": "karlic-luka/Spectral-clustering", "max_forks_repo_head_hexsha": "711042281c9fbedea1f12be822c9f55b629cc854", "max_forks_repo_licenses": ["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.6931818182, "max_line_length": 147, "alphanum_fraction": 0.62804069, "num_tokens": 704, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.45154800549350294}}
{"text": "// Copyright Louis Dionne 2013-2016\r\n// Distributed under the Boost Software License, Version 1.0.\r\n// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\r\n\r\n#include <boost/hana/assert.hpp>\r\n#include <boost/hana/greater.hpp>\r\n#include <boost/hana/less.hpp>\r\n#include <boost/hana/optional.hpp>\r\nnamespace hana = boost::hana;\r\n\r\n\r\nBOOST_HANA_CONSTANT_CHECK(hana::nothing < hana::just(3));\r\nBOOST_HANA_CONSTANT_CHECK(hana::just(0) > hana::nothing);\r\nstatic_assert(hana::just(1) < hana::just(3), \"\");\r\nstatic_assert(hana::just(3) > hana::just(2), \"\");\r\n\r\nint main() { }\r\n", "meta": {"hexsha": "16eb8b23fa1e5a85862723b0f96584d879507c09", "size": 595, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "thirdparty-cpp/boost_1_62_0/libs/hana/example/optional/orderable.cpp", "max_stars_repo_name": "nxplatform/nx-mobile", "max_stars_repo_head_hexsha": "0dc174c893f2667377cb2ef7e5ffeb212fa8b3e5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-12-15T19:57:24.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-15T19:57:24.000Z", "max_issues_repo_path": "thirdparty-cpp/boost_1_62_0/libs/hana/example/optional/orderable.cpp", "max_issues_repo_name": "nxplatform/nx-mobile", "max_issues_repo_head_hexsha": "0dc174c893f2667377cb2ef7e5ffeb212fa8b3e5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thirdparty-cpp/boost_1_62_0/libs/hana/example/optional/orderable.cpp", "max_forks_repo_name": "nxplatform/nx-mobile", "max_forks_repo_head_hexsha": "0dc174c893f2667377cb2ef7e5ffeb212fa8b3e5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0555555556, "max_line_length": 82, "alphanum_fraction": 0.7058823529, "num_tokens": 167, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.45154800549350294}}
{"text": "#include \"observables/SpectralDimensionObservable.h\"\n#include \"observables/Observable.h\"\n#include \"Utils.h\"\n#include \"Vertex.h\"\n#include \"Triangle.h\"\n#include <boost/math/special_functions/log1p.hpp>\n#include <boost/unordered_map.hpp>\n#include \"Config.h\"\n\nSpectralDimensionObservable::SpectralDimensionObservable(unsigned int writeFrequency) :\nObservable(writeFrequency, 0, true),\nsigmaMax(READ_CONF(\"spec.sigmaMax\", 1000)),\ndiffusionConst(READ_CONF(\"spec.diff\", 1.0)),\ndualLattice(READ_CONF(\"spec.dualLattice\", false)),\nfilename(createFilename(\"specdim\")),\nfile(filename.c_str()),\nspecDim(sigmaMax),\nspecDim1(sigmaMax) {\n}\n\nSpectralDimensionObservable::~SpectralDimensionObservable() {\n\n}\n\nvoid SpectralDimensionObservable::process(const std::vector<Vertex*>& state) {\n    boost::array<std::vector<double>, 2 > probBuffers;\n    std::vector< std::vector<unsigned int> > neighbours;\n\n    if (dualLattice) {\n        neighbours = buildDualLatticeConnectivity(state);\n    } else {\n        neighbours = buildLatticeConnectivity(state);\n    }\n\n    probBuffers[0] = std::vector<double>(neighbours.size());\n    probBuffers[1] = std::vector<double>(neighbours.size());\n\n    unsigned int cur = 0; // current buffer\n    unsigned int start = 0; // TODO: average over multiple starting points?\n    probBuffers[cur][start] = 1;\n    Spec prob(sigmaMax);\n\n    for (unsigned int sigma = 0; sigma < sigmaMax; sigma++) {\n        prob[sigma] = probBuffers[cur][start];\n\n        for (unsigned int i = 0; i < neighbours.size(); i++) {\n            if (probBuffers[cur][i] > epsilon) {\n                for (unsigned int n = 0; n < neighbours[i].size(); n++) {\n                    // if this node could not be reached in half the number of maximum steps,\n                    // it will never reach it back to the starting position\n                    if (sigma > sigmaMax / 2 && probBuffers[cur][neighbours[i][n]] < epsilon) {\n                        continue;\n                    }\n\n                    probBuffers[(cur + 1) % 2][neighbours[i][n]] += diffusionConst *\n                            probBuffers[cur][i] / static_cast<double> (neighbours[i].size());\n                }\n            }\n\n            // there is a probability that the diffusion particles remain where\n            // they are. This prevents wild oscillations at low sigma.\n            probBuffers[(cur + 1) % 2][i] += (1.0 - diffusionConst) * probBuffers[cur][i];\n        }\n\n        // switch buffers\n        for (unsigned int i = 0; i < neighbours.size(); i++) {\n            probBuffers[cur][i] = 0.0;\n        }\n\n        cur = (cur + 1) % 2;\n    }\n\n    /* Update spectral dimension */\n    for (unsigned int sigma = 2; sigma < sigmaMax - 1; sigma++) {\n        specDim[sigma] = -2.0 * (double) sigma * (prob[sigma + 1] / prob[sigma] - 1.0);\n        specDim1[sigma] = -2.0 * log(prob[sigma + 1] / prob[sigma]) /\n                boost::math::log1p(1.0 / (double) sigma);\n    }\n}\n\nvoid SpectralDimensionObservable::printToScreen() {\n}\n\nvoid SpectralDimensionObservable::printToFile() {\n    for (unsigned int sigma = 0; sigma < sigmaMax - 1; sigma++) {\n        file << specDim[sigma] << \" \";\n    }\n    file << std::endl;\n\n    for (unsigned int sigma = 0; sigma < sigmaMax - 1; sigma++) {\n        file << specDim1[sigma] << \" \";\n    }\n    file << std::endl;\n}\n", "meta": {"hexsha": "ebbe63ac85f93c1143f572e7a49b98e96e834cb6", "size": 3303, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/observables/SpectralDimensionObservable.cpp", "max_stars_repo_name": "benruijl/cdt", "max_stars_repo_head_hexsha": "340f00488f46167112dbc763810d7ebfbd1056d5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-06-30T16:07:31.000Z", "max_stars_repo_stars_event_max_datetime": "2017-06-30T16:07:31.000Z", "max_issues_repo_path": "src/observables/SpectralDimensionObservable.cpp", "max_issues_repo_name": "benruijl/cdt", "max_issues_repo_head_hexsha": "340f00488f46167112dbc763810d7ebfbd1056d5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/observables/SpectralDimensionObservable.cpp", "max_forks_repo_name": "benruijl/cdt", "max_forks_repo_head_hexsha": "340f00488f46167112dbc763810d7ebfbd1056d5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-11-28T15:44:21.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-28T15:44:21.000Z", "avg_line_length": 34.7684210526, "max_line_length": 95, "alphanum_fraction": 0.6033908568, "num_tokens": 839, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.45154800549350294}}
{"text": "#include <deal.II/base/function.h>\n#include <deal.II/base/function_lib.h>\n#include <deal.II/base/logstream.h>\n#include <deal.II/base/quadrature_lib.h>\n#include <deal.II/base/symmetric_tensor.h>\n#include <deal.II/base/tensor_function.h>\n#include <deal.II/base/utilities.h>\n\n#include <deal.II/lac/affine_constraints.h>\n#include <deal.II/lac/block_vector.h>\n#include <deal.II/lac/block_sparse_matrix.h>\n#include <deal.II/lac/full_matrix.h>\n#include <deal.II/lac/solver_gmres.h>\n#include <deal.II/lac/precondition.h>\n#include <deal.II/lac/vector.h>\n#include <deal.II/lac/solver_bicgstab.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_dgq.h>\n#include <deal.II/fe/fe_raviart_thomas.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\n#include <deal.II/lac/sparse_direct.h>\n#include <deal.II/base/timer.h>\n#include <deal.II/grid/grid_in.h>\n\n\n#include <cmath>\n#include <fstream>\n#include <iostream>\n\n#include \"json.hpp\"\n\nusing namespace dealii;\nusing Json = nlohmann::json;\n\ntemplate <int dim>\nclass THMConsolidation\n{\npublic:\n  THMConsolidation(const unsigned degree, const nlohmann::json json);\n  void run();\n\nprivate:\n  void make_grid();\n  void setup_system();\n  void assemble_system();\n  void solve(unsigned step);\n  void output_results(unsigned int step, unsigned int current_time) const;\n\n  Triangulation<dim>        triangulation_;\n  FESystem<dim>             fe_;\n  DoFHandler<dim>           dof_handler_;\n  //AffineConstraints<double> constraints_;\n\n/*\n  BlockSparsityPattern      sparsity_pattern_;\n  BlockSparseMatrix<double> system_matrix_;\n  BlockVector<double> solution_;\n  BlockVector<double> system_rhs_;\n*/\n  SparsityPattern      sparsity_pattern_;\n  SparseMatrix<double> system_matrix_;\n  SparseMatrix<double> system_matrix_k_;\n  SparseMatrix<double> system_matrix_c_;\n  Vector<double> solution_;\n  Vector<double> old_solution_;\n  Vector<double> system_rhs_;\n  Vector<double> solution_var_;\n\n  unsigned         degree_;\n  // double           model_length_;\n  // double           height_over_width_;\n  double            inner_radius_;\n  double            outer_radius_;\n  double            subdivision_;\n  double            max_steps_;\n  double           time_step_;\n  double           current_time_;\n  double           k_in_;\n  double           k_T_in_;\n  double           alpha_in;\n  double           lambda_in_;\n  double           mu_in_;\n  double           pressure_in_;\n  double           porosity_in_;\n  double           density_in_;\n  double           alpha_sw_in_;\n  double           h_cap_sw_in_;\n  double           step_torr_;\n  double           first_step_;\n  double           Q_in_;\n  const double     gamma_w=1;\n};\n\n// For Dirichlet boundary conditions\n// Deformation Dirichlet boundary conditions\ntemplate <int dim>\nclass DeformationDirichletBoundary : public Function<dim>\n{\npublic:\n  DeformationDirichletBoundary() : Function<dim>(dim + 2) {}\n  virtual void vector_value(const Point<dim> &p, Vector<double> &  value) const override;\n  void get_geometry(const double inner, const double outer) {inner_radius_ = inner; outer_radius_ = outer;}\nprivate:\n  double inner_radius_;\n  double outer_radius_;\n};\n\ntemplate <int dim>\nvoid DeformationDirichletBoundary<dim>::vector_value(const Point<dim> &p, Vector<double> &  values) const\n{\n  // if (p[2] == 0) {\n  //   for (unsigned int c = 0; c < 3; ++c) {\n  //     if (c==2){\n  //       values(c) = 0;\n  //     }\n  //     else {\n  //       values(c) = 0;\n  //     }\n\n  //   }\n  //   //values(0) = 11; values(1) = 21; values(2) = 51;\n  // } else if (p[0] == 0 || p[1] == 0 || std::abs(p[0]-model_length_) < 1e-12 || std::abs(p[1]-model_length_) < 1e-12) {\n  //   for (unsigned int c = 0; c < 2; ++c) values(c) = 0;\n  //   //values(0) = 31; values(1) = 41;\n  // if (std::abs(std::pow(p[0],2)+std::pow(p[1],2)+std::pow(p[2],2)-std::pow(inner_radius_,2))<=1e-5)\n  // {\n  //   values(0)=0; values(1)=0;values(2)=0;\n  // }\n   values(0)=0; values(1)=0;values(2)=0;\n  // if (std::abs(std::pow(p[0],2)+std::pow(p[1],2)+std::pow(p[2],2)-std::pow(outer_radius_,2))==0)\n  // {\n  //   values(0)=0; values(1)=0;values(2)=0;\n  // }\n\n}\n\n// Pressure dirichlet boundary\ntemplate <int dim>\nclass PressureDirichletBoundary : public Function<dim>\n{\npublic:\n  PressureDirichletBoundary() : Function<dim>(dim +2) {}\n  virtual void vector_value(const Point<dim> &p, Vector<double> &  value) const override;\n  void get_geometry(const double inner, const double outer) {inner_radius_ = inner; outer_radius_ = outer;}\nprivate:\n  double inner_radius_;\n  double outer_radius_;\n};\n\ntemplate <int dim>\nvoid PressureDirichletBoundary<dim>::vector_value(const Point<dim> &p, Vector<double> &  values) const\n{\n  // if (std::abs(p[2] - model_length_*height_over_width_) < 1e-12) values(3) = 0;\n  // // if (std::abs(p[2] - 0.0) < 1e-12) values(3) = 0.1;\n  // if (std::abs(std::pow(p[0],2)+std::pow(p[1],2)+std::pow(p[2],2)-std::pow(outer_radius_,2))<=1e-5)\n  // {\n  //   values(3)=0;\n  // }\n  values(3)=0;\n}\n\n// Temperature dirichlet boundary\ntemplate <int dim>\nclass TemperatureDirichletBoundary : public Function<dim>\n{\npublic:\n  TemperatureDirichletBoundary() : Function<dim>(dim + 1) {}\n  virtual void vector_value(const Point<dim> &p, Vector<double> &  value) const override;\n  void get_geometry(const double inner, const double outer) {inner_radius_ = inner; outer_radius_ = outer;}\nprivate:\n  double inner_radius_;\n  double outer_radius_;\n};\n\ntemplate <int dim>\nvoid TemperatureDirichletBoundary<dim>::vector_value(const Point<dim> &p, Vector<double> &  values) const\n{\n  \n  // if (std::abs(std::pow(p[0],2)+std::pow(p[1],2)+std::pow(p[2],2)-std::pow(outer_radius_,2))<=1e-5)\n  // {\n  //   values(4)=0;\n  // }\n   values(4)=0;\n  // if (std::abs(std::pow(p[0],2)+std::pow(p[1],2)+std::pow(p[2],2)-std::pow(inner_radius_,2))<=1e-3)\n  // {\n  //   values(4)=0;\n  // }\n}\n\ntemplate <int dim>\nclass DeformationNeumannBoundary : public TensorFunction<1,dim>\n{\npublic:\n  DeformationNeumannBoundary() : TensorFunction<1,dim>() {}\n  virtual void value_list(const std::vector<Point<dim>> &points,\n                          std::vector<Tensor<1,dim>> & values) const override;\n  void get_pressure(const double pressure) {pressure_ = pressure; }\nprivate:\n  double pressure_;\n};\n\ntemplate <int dim>\nvoid DeformationNeumannBoundary<dim>::value_list(const std::vector<Point<dim>> &points,\n                                                 std::vector<Tensor<1,dim>> & values) const\n{\n  (void)points;\n  AssertDimension(points.size(), values.size());\n  // for(auto &value : values) {\n  //   value[0] = 0; value[1] = 0; value[2] = -pressure_;\n  // }\n}\n// Pressure Neumann boundary\ntemplate <int dim>\nclass PressureNeumannBoundary : public TensorFunction<1,dim>\n{\npublic:\n  PressureNeumannBoundary() : TensorFunction<1,dim>() {}\n  virtual void value_list(const std::vector<Point<dim>> &points,\n                          std::vector<Tensor<1,dim>> & values) const override;\n  void get_pressure_grad(const Tensor<1,dim> pressure_grad) {pressure_grad_ = pressure_grad; }\nprivate:\n  Tensor<1,dim> pressure_grad_;\n};\n\ntemplate <int dim>\nvoid PressureNeumannBoundary<dim>::value_list(const std::vector<Point<dim>> &points,\n                                                 std::vector<Tensor<1,dim>> & values) const\n{\n  (void)points;\n  AssertDimension(points.size(), values.size());\n  for(auto &value : values) {\n    value[0] = 0; value[1] = 0; value[2] = 0;\n  }\n}\n// Temperature Neumann boundary\n// template <int dim>\n// class TemperatureNeumannBoundary : public TensorFunction<1,dim>\n// {\n// public:\n//   TemperatureNeumannBoundary() : TensorFunction<1,dim>() {}\n//   virtual void value_list(const std::vector<Point<dim>> &points,\n//                           std::vector<Tensor<1,dim>> & values) const override;\n//   void get_Q(const double Q) {Q_ = Q; }\n// private:\n//   double Q_;\n// };\n// template <int dim>\n// void TemperatureNeumannBoundary<dim>::value_list(const std::vector<Point<dim>> &points,\n//                                                  std::vector<Tensor<1,dim>> & values) const\n// {\n//   (void) points;\n//   for(auto &value : values) {\n//     ;\n//   }\n// }\ntemplate <int dim>\nclass TemperatureNeumannBoundary : public Function<dim>\n{\npublic:\n  TemperatureNeumannBoundary() : Function<dim>(dim + 2) {}\n  virtual void vector_value(const Point<dim> &p, Vector<double> &  value) const override;\n  void get_Q(const double Q) {Q_ = Q; }\nprivate:\n  double Q_;\n};\n\ntemplate <int dim>\nvoid TemperatureNeumannBoundary<dim>::vector_value(const Point<dim> &p, Vector<double> &  values) const\n{\n  (void)p;\n  for(auto &value : values) {\n     value=Q_;\n  }\n}\n\n\n\n// For initial conditions\ntemplate <int dim>\nclass DeformationInitial : public Function<dim>\n{\npublic:\n  DeformationInitial() : Function<dim>(dim + 2) {}\n  virtual void vector_value(const Point<dim> &p, Vector<double> &  value) const override;\n};\n\ntemplate <int dim>\nvoid DeformationInitial<dim>::vector_value(const Point<dim> &p, Vector<double> &  values) const\n{\n  (void)p;\n  for (unsigned int c = 0; c < this->n_components; ++c)\n    values(c) = 0.0;\n}\n\n\ntemplate <int dim>\nclass PressureInitial : public Function<dim>\n{\npublic:\n  PressureInitial() : Function<dim>(dim + 2) {}\n  virtual void vector_value(const Point<dim> &p, Vector<double> &  value) const override;\n  void get_pressure(const double pressure) {pressure_ = pressure; }\nprivate:\n  double pressure_;\n};\n\ntemplate <int dim>\nvoid PressureInitial<dim>::vector_value(const Point<dim> &p, Vector<double> &  values) const\n{\n  (void)p;\n  values(3) = 0;\n}\n\n\n// Initial temperature\ntemplate <int dim>\nclass TemperatureInitial : public Function<dim>\n{\npublic:\n  TemperatureInitial() : Function<dim>(dim + 2) {}\n  void vector_value(const Point<dim> &p, Vector<double> &  value) const override;\n  void get_temperature(const double temperature) {temperature_ = temperature; }\nprivate:\n  double temperature_;\n};\n\ntemplate <int dim>\nvoid TemperatureInitial<dim>::vector_value(const Point<dim> &p, Vector<double> &  values) const\n{\n  (void)p;\n  values(4) = 0;\n}\n\n\n// Initial porosity\ntemplate <int dim>\nclass PorosityInitial : public Function<dim>\n{\npublic:\n  PorosityInitial() : Function<dim>(1) {}\n  double value(const Point<dim> &p, const unsigned int component=0) const override;\n  void get_porosity(const double porosity) {porosity_ = porosity; }\nprivate:\n  double porosity_;\n};\n\ntemplate <int dim>\ndouble PorosityInitial<dim>::value(const Point<dim> &p, const unsigned int component) const\n{\n  return porosity_;\n}\n\n\ntemplate <int dim>\nTHMConsolidation<dim>::THMConsolidation(const unsigned degree, const nlohmann::json json)\n  : degree_(degree)\n  , fe_(FE_Q<dim>(degree+1), dim, FE_Q<dim>(degree), 1, FE_Q<dim>(degree), 1)\n  , dof_handler_(triangulation_)\n{\n  // model_length_ = json[\"parameters\"][\"model_length\"].template get<double>();\n  // height_over_width_ = json[\"parameters\"][\"height_over_width\"].template get<double>();\n  inner_radius_ = json[\"parameters\"][\"inner_radius\"].template get<unsigned>();\n  outer_radius_ = json[\"parameters\"][\"outer_radius\"].template get<unsigned>();\n  subdivision_ = json[\"parameters\"][\"subdivision\"].template get<unsigned>();\n  max_steps_ = json[\"parameters\"][\"max_steps\"].template get<unsigned>();\n  time_step_ = json[\"parameters\"][\"time_step\"].template get<double>();\n  // pressure_in_ = json[\"parameters\"][\"loading_on_top\"].template get<double>();\n  k_in_ = json[\"parameters\"][\"k\"].template get<double>();\n  k_T_in_ = json[\"parameters\"][\"k_T\"].template get<double>();\n  alpha_in = json[\"parameters\"][\"alpha\"].template get<double>();\n  lambda_in_ = json[\"parameters\"][\"lambda\"].template get<double>();\n  mu_in_ = json[\"parameters\"][\"mu\"].template get<double>();\n  porosity_in_ = json[\"parameters\"][\"porosity\"].template get<double>();\n  density_in_ = json[\"parameters\"][\"density\"].template get<double>();\n  Q_in_=json[\"parameters\"][\"Q\"].template get<double>();\n  alpha_sw_in_=json[\"parameters\"][\"alpha_sw\"].template get<double>();\n  h_cap_sw_in_=json[\"parameters\"][\"h_cap_sw\"].template get<double>();\n  std::cout<<\"inner_radius: \"<<inner_radius_<<\", outer_radius: \"<<outer_radius_<<std::endl\n           <<\"Subdivision: \"<<subdivision_<<std::endl\n           <<\"Total steps: \"<<max_steps_<<std::endl<<\"Time step: \"<<time_step_<<std::endl\n           <<\"k: \"<<k_in_<<std::endl\n           <<\"lambda: \"<<lambda_in_<<\", mu: \"<<mu_in_<<std::endl\n           <<\"k_T: \"<<k_T_in_<<\", Q_in: \"<<Q_in_<<std::endl;\n}\n\ntemplate <int dim>\nvoid THMConsolidation<dim>::make_grid()\n{\n  //Tensor<1,dim> TP1;\n  //TP1(0)=0;TP1(1)=0;TP1(2)=0;\n  //Tensor<1,dim> TP2;\n  //TP2(0)=model_length_;TP2(1)=model_length_;TP2(2)=model_length_;\n  const Point<dim,double> grid_p1(0.0, 0.0, 0.0);\n  // const Point<dim,double> grid_p2(model_length_, model_length_, model_length_ * height_over_width_);\n  // const std::vector<unsigned int> repetitions{subdivision_, subdivision_, subdivision_ * height_over_width_};\n   GridGenerator::hyper_shell(triangulation_,grid_p1, inner_radius_, outer_radius_,0);\n  // GridIn<dim> gridin;\n  // gridin.attach_triangulation(triangulation_);\n  // std::ifstream f(\"void_sphere3.msh\");\n  // gridin.read_msh(f);\n\n  //triangulation_.refine_global(2);\n  for (unsigned int i=0; i<=subdivision_; i++)\n  {  \n    std::cout<<(float(i)/float(subdivision_))*inner_radius_+(1-float(i)/float(subdivision_))*outer_radius_<<std::endl;\n    int j=0;\n    int j0=0;\n    for (const auto &cell : triangulation_.active_cell_iterators())\n  {\n    cell->clear_refine_flag();\n       j0=j0+1;   \n    if (grid_p1.distance(cell->center()) <= (float(i)/float(subdivision_))*inner_radius_+(1-float(i)/float(subdivision_))*outer_radius_)\n    {\n      // std::cout<<grid_p1.distance(cell->center())<<std::endl;\n      j=j+1;\n      cell->set_refine_flag();\n\n    } \n  }\n    triangulation_.execute_coarsening_and_refinement();\n    std::cout<<i<<\" refine loop \"<<j0<<\" all \"<<j<<\"refined\"<<std::endl;\n  }\n\n  // triangulation_.refine_global(subdivision_);\n\n  // Set boundary indicator for applying boundary conditions\n  // -x:1, +x:2, -y:3, +y:4, -z:5, +z:6\n  // if (dim == 3) {\n  //   for (const auto &cell : triangulation_.active_cell_iterators()) {\n  //     for (const auto &face : cell->face_iterators()) {\n  //       if (face->center()[0] == 0) face->set_all_boundary_ids(1);\n  //       else if (std::abs(face->center()[0] - model_length_) < 1e-12) face->set_all_boundary_ids(2);\n  //     }\n  //   }\n  //   for (const auto &cell : triangulation_.active_cell_iterators()) {\n  //     for (const auto &face : cell->face_iterators()) {\n  //       if (face->center()[1] == 0) face->set_all_boundary_ids(3);\n  //       else if (std::abs(face->center()[1] - model_length_) < 1e-12) face->set_all_boundary_ids(4);\n  //     }\n  //   }\n  //   for (const auto &cell : triangulation_.active_cell_iterators()) {\n  //     for (const auto &face : cell->face_iterators()) {\n  //       if (face->center()[2] == 0) face->set_all_boundary_ids(5);\n  //       else if (std::abs(face->center()[2] - model_length_*height_over_width_) < 1e-12) face->set_all_boundary_ids(6);\n  //     }\n  //   }\n  // }\n  // Set boundary indicator for applying boundary conditions\n  // inner:1 outer 2\n  if (dim==3)\n  {\n    double k1=0;\n    double k2=0;\n    int i=0;\n    int j=0;\n    for (const auto &cell : triangulation_.active_cell_iterators())\n    {\n      i++;\n      j=0;\n      for (const auto &face : cell->face_iterators())\n      {\n        j++;\n        if (std::abs(\n          std::pow(face->center()[0],2)+\n          std::pow(face->center()[1],2)+\n          std::pow(face->center()[2],2)\n          - std::pow(inner_radius_,2)) < 0.1)\n          {\n            face->set_all_boundary_ids(1);\n            k1++;\n            //std::cout<<i<<\" id1 \"<<j<<std::endl;\n          }\n        else if (std::abs(\n          std::pow(face->center()[0],2)+\n          std::pow(face->center()[1],2)+\n          std::pow(face->center()[2],2)\n          - std::pow(outer_radius_,2)) <10)\n          {\n            face->set_all_boundary_ids(2);\n            k2++;\n            // std::cout<<\"bc2: \"<<face->center()[0]<<\",\"<<face->center()[1]<<\",\"<<face->center()[2]<<std::endl;\n            //std::cout<<i<<\" id2 \"<<j<<std::endl;\n          }\n          else \n          {\n            face->set_all_boundary_ids(3);\n          }\n\n      }\n    }\n    std::cout<<\"k1 \"<<k1<<\",k2 \"<<k2<<std::endl;\n  }\n\n  dof_handler_.distribute_dofs(fe_);\n\n  // Re-numner dof, make velocities and pressures are not intermingled\n  DoFRenumbering::component_wise(dof_handler_);\n\n/*\n  // Set constraints to apply Dirichlet boundary conditions\n  {\n    constraints_.clear();\n\n    DeformationDirichletBoundary<dim> deformation_dirichlet;\n    deformation_dirichlet.get_model_length_and_ratio(model_length_, height_over_width_);\n    PressureDirichletBoundary<dim> pressure_dirichlet;\n    pressure_dirichlet.get_model_length_and_ratio(model_length_, height_over_width_);\n\n    FEValuesExtractors::Vector deformations_bottom(0);\n    FEValuesExtractors::Scalar pressure(dim);\n    std::vector<bool> deformations_side{true, true, false, false};\n    DoFTools::make_hanging_node_constraints(dof_handler_, constraints_);\n    for (int i = 1; i <= 4; ++i) {\n      VectorTools::interpolate_boundary_values(dof_handler_,\n                                               i,\n                                               deformation_dirichlet,\n                                               constraints_,\n                                               fe_.component_mask(deformations_side));\n    }\n    VectorTools::interpolate_boundary_values(dof_handler_,\n                                             5,\n                                             deformation_dirichlet,\n                                             constraints_,\n                                             fe_.component_mask(deformations_bottom));\n     VectorTools::interpolate_boundary_values(dof_handler_,\n                                              6,\n                                              pressure_dirichlet,\n                                              constraints_,\n                                              fe_.component_mask(pressure));\n//\n          // VectorTools::interpolate_boundary_values(dof_handler_,\n          //                                      5,\n          //                                      pressure_dirichlet,\n          //                                      constraints_,\n          //                                      fe_.component_mask(pressure));\n\n  }\n  constraints_.close();\n*/\n\n\n  // Count the number of velocity and pressure dofs\n  const std::vector<types::global_dof_index> dofs_per_component =\n    DoFTools::count_dofs_per_fe_component(dof_handler_);\n  unsigned int n_u = 0;\n  for(int i = 0; i < dim; ++i) n_u += dofs_per_component[i];\n  const unsigned int n_p = dofs_per_component[dim];\n  const unsigned int n_T = dofs_per_component[dim+1];\n\n  std::cout << \"Number of active cells: \" << triangulation_.n_active_cells()<< std::endl\n            << \"Total number of cells: \" << triangulation_.n_cells()<< std::endl\n            << \"Number of degrees of freedom: \" << dof_handler_.n_dofs()\n            << \" (\" << n_u << '+' << n_p << \"+\"<<n_T<<')' << std::endl;\n\n  // Allocate sparsity patterns\n/*\n  BlockDynamicSparsityPattern dsp(2, 2);\n  dsp.block(0, 0).reinit(n_u, n_u);\n  dsp.block(1, 0).reinit(n_p, n_u);\n  dsp.block(0, 1).reinit(n_u, n_p);\n             +\n  DoFTools::make_sparsity_pattern(dof_handler_, dsp, constraints_, false);\n\n  sparsity_pattern_.copy_from(dsp);\n  system_matrix_.reinit(sparsity_pattern_);\n\n  // Resize the solution and right hand side vectors\n  solution_.reinit(2);\n  solution_.block(0).reinit(n_u);\n  solution_.block(1).reinit(n_p);\n  solution_.collect_sizes();\n  system_rhs_.reinit(2);\n  system_rhs_.block(0).reinit(n_u);\n  system_rhs_.block(1).reinit(n_p);\n  system_rhs_.collect_sizes();\n*/\n  DynamicSparsityPattern dsp(n_u+n_p+n_T, n_u+n_p+n_T);\n  DoFTools::make_sparsity_pattern(dof_handler_, dsp/*, constraints_, false*/);\n  sparsity_pattern_.copy_from(dsp);\n  system_matrix_.reinit(sparsity_pattern_);\n  system_matrix_=0;\n  system_matrix_k_.reinit(sparsity_pattern_);\n  system_matrix_k_=0;\n  system_matrix_c_.reinit(sparsity_pattern_);\n  system_matrix_c_=0;\n  solution_.reinit(n_u+n_p+n_T);\n  solution_ = 0;\n  system_rhs_.reinit(n_u+n_p+n_T);\n  system_rhs_=0;\n}\n\n// Assemble matrix system\ntemplate <int dim>\nvoid THMConsolidation<dim>::assemble_system()\n{\n  const std::vector<size_t> deformation_idx{0, 1, 2};\n  const std::vector<size_t> pressure_idx{3};\n  const std::vector<size_t> temperature_idx{4};\n\n  system_matrix_ = 0;\n  system_matrix_k_ = 0;\n  system_matrix_c_ = 0;\n  system_rhs_    = 0;\n\n  QGauss<dim>     quadrature_formula(degree_+1 );\n  QGauss<dim - 1> face_quadrature_formula(degree_+1 );\n\n  FEValues<dim>     fe_values(fe_,\n                          quadrature_formula,\n                          update_values | update_gradients |\n                            update_quadrature_points | update_JxW_values);\n  FEFaceValues<dim> fe_face_values(fe_,\n                                   face_quadrature_formula,\n                                   update_values | update_normal_vectors |\n                                     update_quadrature_points |\n                                     update_JxW_values);\n\n  const unsigned int dofs_per_cell = fe_.dofs_per_cell;\n\n  const unsigned int n_q_points      = quadrature_formula.size();\n  const unsigned int n_face_q_points = face_quadrature_formula.size();\n\n  // Initialize local matrices\n  FullMatrix<double> local_matrix(dofs_per_cell, dofs_per_cell);\n  FullMatrix<double> local_matrix_k(dofs_per_cell, dofs_per_cell);\n  FullMatrix<double> local_matrix_c(dofs_per_cell, dofs_per_cell);\n  Vector<double>     local_rhs(dofs_per_cell);\n\n  // Initialize local old solution containers\n  std::vector<Vector<double>> old_solution_values(n_q_points,\n                                                  Vector<double>(dim+2));\n  //std::vector<Vector<double>> old_solution_values_face(n_face_q_points,\n                                                       //Vector<double>(dim + 1));\n\n  std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell);\n\n  // Initialize defined functions for boundary values\n  DeformationNeumannBoundary<dim> deformation_neumann_boundary;\n  TemperatureNeumannBoundary<dim> temperature_neumann_boundary;\n  temperature_neumann_boundary.get_Q(Q_in_);\n  // deformation_neumann_boundary.get_pressure(pressure_in_);\n  //PressureNeumannBoundary<dim> pressure_neumann_boundary;\n  //GravityValues<dim> gravity_boundary_values;\n  // Constant parameters\n  std::vector<double> lambda_values(n_q_points);\n  std::vector<double> mu_values(n_q_points);\n  std::vector<double> k_values(n_q_points);\n  std::vector<double> k_T_values(n_q_points);\n  std::vector<double> alpha_values(n_q_points);\n  std::vector<double> alpha_sw_values(n_q_points);\n  std::vector<double> porosity_values(n_q_points);\n  std::vector<double> h_cap_w_values(n_q_points);\n  std::vector<double> h_cap_sw_values(n_q_points);\n  std::vector<double> density_values(n_q_points);\n  std::vector<double> pressure_values(n_q_points);\n\n  Functions::ConstantFunction<dim> lambda(lambda_in_), mu(mu_in_), k(k_in_), alpha(alpha_in), k_T(k_T_in_),\n   porosity(porosity_in_),density(density_in_),alpha_sw(alpha_sw_in_),h_cap_sw(h_cap_sw_in_);\n\n  // std::vector<Tensor<1, dim>>         deformation_neumann_boundary_values(n_face_q_points);\n  std::vector<double>         temperature_neumann_boundary_values(n_face_q_points);\n\n  //std::vector<Tensor<1, dim>> boundary_g_values(n_q_points);\n  //std::vector<Tensor<1, dim>> pressure_neumann_boundary_values(n_q_points);\n  std::vector<double>         boundary_k_T_values(n_face_q_points);\n  const FEValuesExtractors::Vector deformations(0);\n  const FEValuesExtractors::Scalar pressure(dim);\n  const FEValuesExtractors::Scalar temperature(dim+1);\n  // std::cout<<\"cell_iterators started\"<<std::endl;\n\n  for (const auto &cell : dof_handler_.active_cell_iterators()) {\n    fe_values.reinit(cell);\n    local_matrix = 0;\n    local_matrix_k = 0;\n    local_matrix_c = 0;\n    local_rhs    = 0;\n\n    lambda.value_list(fe_values.get_quadrature_points(), lambda_values);\n    mu.value_list(fe_values.get_quadrature_points(), mu_values);\n    k.value_list(fe_values.get_quadrature_points(), k_values);\n    k_T.value_list(fe_values.get_quadrature_points(), k_T_values);\n    alpha.value_list(fe_values.get_quadrature_points(), alpha_values);\n    porosity.value_list(fe_values.get_quadrature_points(), porosity_values);\n    density.value_list(fe_values.get_quadrature_points(), density_values);\n    alpha_sw.value_list(fe_values.get_quadrature_points(), alpha_sw_values);\n    h_cap_sw.value_list(fe_values.get_quadrature_points(), h_cap_sw_values);\n\n    // Get old solution value at Gauss points\n    fe_values.get_function_values(solution_, old_solution_values);\n    // std::cout<<\"intergation\"<<std::endl;\n\n\n    // std::cout<<\"intergation\"<<std::endl;\n\n    for (unsigned int q = 0; q < n_q_points; ++q) {\n      for (unsigned int i = 0; i < dofs_per_cell; ++i) {\n        // std::cout<<\"i index\"<<std::endl;\n        const unsigned int component_i = fe_.system_to_component_index(i).first;\n\n        const Tensor<1, dim> phi_i_u = fe_values[deformations].value(i, q);\n        const Tensor<2, dim> grad_phi_i_u = fe_values[deformations].gradient(i, q);\n        const SymmetricTensor<2,dim> symmgrad_phi_i_u = fe_values[deformations].symmetric_gradient(i, q);\n        const double phi_i_p     = fe_values[pressure].value(i, q);\n        const double phi_i_T     = fe_values[temperature].value(i, q);\n                // std::cout<<\"break\"<<std::endl;\n        const Tensor<1, dim> grad_phi_i_p = fe_values[pressure].gradient(i, q);\n        const Tensor<1, dim> grad_phi_i_T = fe_values[temperature].gradient(i, q);\n        const double div_phi_i_u=fe_values[deformations].divergence(i,q);\n\n\n        for (unsigned int j = 0; j < dofs_per_cell; ++j) {\n          // std::cout<<\"j index\"<<std::endl;\n          const unsigned int component_j =  fe_.system_to_component_index(j).first;\n          const Tensor<1, dim> phi_j_u = fe_values[deformations].value(j, q);\n          //const Tensor<2, dim> grad_phi_j_u = fe_values[deformations].gradient(j, q);\n          const SymmetricTensor<2,dim> symmgrad_phi_j_u = fe_values[deformations].symmetric_gradient(j, q);\n          const double phi_j_p     = fe_values[pressure].value(j, q);\n          const double phi_j_T     = fe_values[temperature].value(j, q);\n          const Tensor<1, dim> grad_phi_j_p = fe_values[pressure].gradient(j, q);\n          const Tensor<1, dim> grad_phi_j_T = fe_values[temperature].gradient(j, q);\n          const double div_phi_j_u=fe_values[deformations].divergence(j,q);\n\n          Tensor<1, dim> sub_solution_deformation;\n          double sub_solution_pressure;\n          for(auto id : deformation_idx) sub_solution_deformation[id] = old_solution_values[q](id);\n          sub_solution_pressure = old_solution_values[q](dim);\n/*\n          local_matrix(i, j) +=\n             (\n             (lambda_values[q] * div_phi_i_u * div_phi_j_u)\n             +\n             (2 * mu_values[q] *symmgrad_phi_i_u * symmgrad_phi_j_u)\n             +\n             (-div_phi_i_u*phi_j_p)\n             +\n             (grad_phi_i_p * k_values[q] * grad_phi_j_p)/gamma_w\n             +\n             ( phi_i_p*div_phi_j_u/(time_step_) )\n             )*fe_values.JxW(q);\n*/\n\n          local_matrix_k(i, j) +=\n             (\n             (lambda_values[q] * div_phi_i_u * div_phi_j_u)\n             +\n             (2 * mu_values[q] *symmgrad_phi_i_u * symmgrad_phi_j_u) //K_uu\n             +\n             (+div_phi_i_u*phi_j_p) //Q_up\n             +\n             (-grad_phi_i_p * k_values[q] * grad_phi_j_p)/gamma_w //K_pp\n             +\n             (alpha_values[q]*div_phi_i_u*phi_j_T) //Q_uT\n             +\n             (k_T_values[q]*grad_phi_i_T*grad_phi_j_T) //K_tt0\n             //+\n             //(k_T_values[q]*h_cap_w_values[q]/gamma_w*phi_i_T*pressure_values[q]*grad_phi_j_p*grad_phi_j_T) // K_tt1\n             )*fe_values.JxW(q);\n\n\n          local_matrix_c(i, j) +=\n             (\n             ( phi_i_p*div_phi_j_u ) //R_pu\n             +\n             //(porosity_values[q]*alpha_values[q]*phi_i_p*phi_j_T)//R_pT Rui's formulation\n             (alpha_sw_values[q]*phi_i_p*phi_j_T) //R_pT booker's formulation\n             +\n             (density_values[q]*h_cap_sw_values[q]*phi_i_T*phi_j_T) //C_TT\n             )*fe_values.JxW(q)/(time_step_/* std::pow(10,step-1)*/);\n            //  if (local_matrix_c(i, j)!=0)\n            //  {\n            //    std::cout<<local_matrix_c(i, j)<<\" C\"<<local_matrix_k(i,j)<<\" K  \"<<std::endl;\n\n            //  }\n/*\n          local_rhs(i) +=\n           (\n             phi_i_p * div_phi_j_u / (time_step_ )\n           )\n           *\n            (\n              phi_j_u * sub_solution_deformation +k.value_list(fe_values.get_quadrature_points(), k_values);\n              phi_j_p * sub_solution_pressure\n            )\n            * fe_values.JxW(q);        system_matrix_.add(local_dof_indices[i],\n                           local_dof_indices[j],\n                           local_matrix_c(i, j));\n*/\n        } // for j\n\n      } // for i\n\n        //std::cout<<\"local rhs \"<<local_rhs<<std::endl;\n\n    } // for q\n\n\n\n    // Apply Neumann boundary conditions\n    for (const auto &face : cell->face_iterators()) {\n      if (face->boundary_id() == 1) {\n\n        fe_face_values.reinit(cell, face);\n\n        // deformation_neumann_boundary.value_list(fe_face_values.get_quadrature_points(), deformation_neumann_boundary_values);\n\n        temperature_neumann_boundary.value_list(fe_face_values.get_quadrature_points(), temperature_neumann_boundary_values);\n\n        k_T.value_list(fe_face_values.get_quadrature_points(), boundary_k_T_values);\n        //gravity_boundary_values.value_list(fe_face_values.get_quadrature_points(), boundary_g_values);\n\n        for (unsigned int q = 0; q < n_face_q_points; ++q) {\n          const Tensor<1, dim> nf = fe_face_values.normal_vector(q);\n\n          for (unsigned int i = 0; i < dofs_per_cell; ++i) {\n            const unsigned int component_i = fe_.system_to_component_index(i).first;\n            const Tensor<1, dim> phi_i_u = fe_face_values[deformations].value(i, q);\n            const double phi_i_p = fe_face_values[pressure].value(i, q);\n            const double phi_i_T = fe_face_values[temperature].value(i, q);\n            const Tensor<1, dim> grad_phi_i_T = fe_values[temperature].gradient(i, q);\n\n            local_rhs(i) +=\n             (\n              // (phi_i_u * deformation_neumann_boundary_values[q]) //A_u\n              +\n              // ((grad_phi_i_T *nf)*temperature_neumann_boundary_values[q]/boundary_k_T_values[q])\n              (phi_i_T*Q_in_/boundary_k_T_values[q]) //A_T\n             ) * fe_face_values.JxW(q);\n            //  std::cout<<temperature_neumann_boundary_values[q]<<\" BCvalue\"<<std::endl;\n            //  if (local_rhs(i)!=0){\n            //    std::cout<<local_rhs(i)<<\" nonzero RHS\"<<std::endl;\n            //  }\n            //  std::cout<<local_rhs(i)<<\" RHS\"<<std::endl;\n\n          }\n        }\n      }\n    } // for face\n\n    // Assemble local matrix into global\n    cell->get_dof_indices(local_dof_indices);\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                           local_matrix_k(i, j));\n        system_matrix_.add(local_dof_indices[i],\n                           local_dof_indices[j],\n                           local_matrix_c(i, j));\n        system_matrix_c_.add(local_dof_indices[i],\n                           local_dof_indices[j],\n                           local_matrix_c(i, j));\n      }\n    }\n    for (unsigned int i = 0; i < dofs_per_cell; ++i)\n      system_rhs_(local_dof_indices[i]) += local_rhs(i);\n    //constraints_.distribute_local_to_global(local_matrix, local_s, local_dof_indices, system_matrix_, system_rhs_);\n\n  } // for cell\n// for (int i=0; i<system_matrix_.n(); ++i)\n// {\n//   if (system_matrix_(i,i)==0)\n//   {\n//     std::cout<<system_matrix_(i,i)<<\" K \"<<std::endl;\n//   }\n// }\n\n\n  // rhs += C/t * solution\n  system_matrix_c_.vmult_add(system_rhs_, solution_);\n\n  // Apply Dirichlet boundary conditions\n  {\n    DeformationDirichletBoundary<dim> deformation_dirichlet;\n    deformation_dirichlet.get_geometry(inner_radius_, outer_radius_);\n    PressureDirichletBoundary<dim> pressure_dirichlet;\n    pressure_dirichlet.get_geometry(inner_radius_, outer_radius_);\n    TemperatureDirichletBoundary<dim> temperature_dirichlet;\n    temperature_dirichlet.get_geometry(inner_radius_, outer_radius_);\n\n//     FEValuesExtractors::Vector deformations_bottom(0);\n//     FEValuesExtractors::Scalar pressure(dim);\n//     FEValuesExtractors::Scalar temperature(dim);\n//     std::vector<bool> deformations_side{true, true, false, false};\n\n//     for (int i = 1; i <= 4; ++i) {\n//       std::map<types::global_dof_index, double> deformation_side_values;\n//       VectorTools::interpolate_boundary_values(dof_handler_,\n//                                                i,\n//                                                deformation_dirichlet,\n//                                                deformation_side_values,\n//                                                fe_.component_mask(deformations_side));\n//       MatrixTools::apply_boundary_values(deformation_side_values, system_matrix_, solution_, system_rhs_);\n//     }\n\n//     std::map<types::global_dof_index, double> deformation_bottom_values;\n//     VectorTools::interpolate_boundary_values(dof_handler_,\n//                                              5,\n//                                              deformation_dirichlet,\n//                                              deformation_bottom_values,\n//                                              fe_.component_mask(deformations_bottom));\n//     MatrixTools::apply_boundary_values(deformation_bottom_values, system_matrix_, solution_, system_rhs_);\n\n//     std::map<types::global_dof_index, double> pressure_values;\n//     VectorTools::interpolate_boundary_values(dof_handler_,\n//                                              6,\n//                                              pressure_dirichlet,\n//                                              pressure_values,\n//                                              fe_.component_mask(pressure));\n//     MatrixTools::apply_boundary_values(pressure_values, system_matrix_, solution_, system_rhs_);\n//   }\n     FEValuesExtractors::Vector deformation(0);\n     FEValuesExtractors::Scalar pressure(dim);\n     FEValuesExtractors::Scalar temperature(dim+1);\n     std::map<types::global_dof_index, double> deformation_values;\n     VectorTools::interpolate_boundary_values(dof_handler_,\n                                             1,\n                                             deformation_dirichlet,\n                                             deformation_values,\n                                             fe_.component_mask(deformation));\n        //  VectorTools::interpolate_boundary_values(dof_handler_,\n        //                                      2,\n        //                                      deformation_dirichlet,\n        //                                      deformation_values,\n        //                                      fe_.component_mask(deformation));\n        //  VectorTools::interpolate_boundary_values(dof_handler_,\n        //                                      3,\n        //                                      deformation_dirichlet,\n        //                                      deformation_values,\n        //                                      fe_.component_mask(deformation));\n     MatrixTools::apply_boundary_values(deformation_values, system_matrix_, solution_, system_rhs_);\n     std::map<types::global_dof_index, double> pressure_values;\n     VectorTools::interpolate_boundary_values(dof_handler_,\n                                             2,\n                                             pressure_dirichlet,\n                                             pressure_values,\n                                             fe_.component_mask(pressure));\n     MatrixTools::apply_boundary_values(pressure_values, system_matrix_, solution_, system_rhs_);\n    std::map<types::global_dof_index, double> temperature_values;\n     VectorTools::interpolate_boundary_values(dof_handler_,\n                                             2,\n                                             temperature_dirichlet,\n                                             temperature_values,\n                                             fe_.component_mask(temperature));\n     MatrixTools::apply_boundary_values(temperature_values, system_matrix_, solution_, system_rhs_);\n }\n}\n\n\n// GMRES solver\ntemplate <int dim>\nvoid THMConsolidation<dim>::solve(unsigned step)\n{\n  std::cout<<\"solver started\"<<std::endl;\n  //std::ofstream out(\"sparsity_pattern.svg\");\n  //sparsity_pattern_.print_svg(out);\n  //  double mxmax=system_matrix_.el(0,0);\n  // for(int i=0;  i<system_matrix_.m(); i++){\n  //   for(int j=0;  j<system_matrix_.n(); j++){\n  //     // std::cout<<i<<\" \"<<j<<\" i j \"<<std::endl;\n  //     if(mxmax<system_matrix_.el(i,j)){\n  //       mxmax=system_matrix_.el(i,j);\n        \n  //     }\n  //   }\n  // }\n  // // std::cout<<mxmax<<\" mxmax \"<<std::endl;\n  // // std::cout<<system_matrix_.m()<<\" m \"<<system_matrix_.n()<<\" n \"<<std::endl;\n\n  //  double mxcmax=system_matrix_c_.el(0,0);\n  // for(int i=0;  i<system_matrix_c_.m(); i++){\n  //   for(int j=0;  j<system_matrix_c_.n(); j++){\n  //     // std::cout<<i<<\" \"<<j<<\" i j \"<<std::endl;\n  //     if(mxcmax<system_matrix_c_.el(i,j)){\n  //       mxcmax=system_matrix_c_.el(i,j);\n        \n  //     }\n  //   }\n  // }\n  // std::cout<<mxcmax<<\" mxmax \"<<std::endl;\n\n  //  std::ofstream out1(\"matrix.txt\");\n  //  system_matrix_.print_as_numpy_arrays(out1);\n  //  std::ofstream out2(\"matrixc.txt\");\n  //  system_matrix_c_.print_as_numpy_arrays(out2);\n\nif (step > 0)\n{ std::cout<<system_rhs_.l2_norm()<<\" l2fnorm \"<<std::endl   ;\n  SolverControl               solver_control(std::max<std::size_t>(10000,\n                                                      system_rhs_.size()/100),\n                                1e-3* system_rhs_.l2_norm(),true,true);\n\n   SolverGMRES<Vector<double>> solver(solver_control);\n  //SolverBicgstab<Vector<double>> solver(solver_control);\n   //PreconditionSOR<SparseMatrix<double>> preconditioner;\n  // PreconditionIdentity preconditioner;\n   //preconditioner.initialize(system_matrix_,1.3);\n   PreconditionSSOR<SparseMatrix<double> > preconditioner;\n   preconditioner.initialize(system_matrix_, PreconditionSSOR<SparseMatrix<double>>::AdditionalData(.6));\n   solver.solve(system_matrix_, solution_, system_rhs_, preconditioner);\n\n   Vector<double> residual(dof_handler_.n_dofs());\n\n   system_matrix_.vmult(residual, solution_);\n   residual -= system_rhs_;\n   std::cout << \"   Iterations required for convergence: \"\n             << solver_control.last_step() << '\\n'\n             << \"   Max norm of residual:                \"\n             << residual.linfty_norm() << '\\n';\n             }\n\nelse\n{\n    SparseDirectUMFPACK A_direct;\n  A_direct.initialize(system_matrix_);\n  //A_direct.vmult(solution_, system_rhs_);\n  A_direct.factorize(system_matrix_);\n  A_direct.solve(system_rhs_);\n  solution_ = system_rhs_;\n}\n/*\n  // Direct solver\n\n*/\n/*\n    std::cout\n             << \"   Max norm of rhs: \"\n             << system_rhs_.linfty_norm() << '\\n' << std::endl;\n    std::cout\n             << \"   Max norm of matrix: \"\n             << system_matrix_.linfty_norm() << '\\n' << std::endl;\n    std::cout << \"Solving linear system... \";\n    Timer timer;\n    SparseDirectUMFPACK A_direct;\n    A_direct.initialize(system_matrix_);\n    A_direct.vmult(solution_, system_rhs_);\n    timer.stop();\n    std::cout << \"done (\" << timer.cpu_time() << \"s)\" << std::endl;\n    std::cout\n             << \"   Max norm of solution: \"\n             << solution_.linfty_norm() << '\\n' << std::endl;\n    Vector<double> residual(dof_handler_.n_dofs());\n    system_matrix_.vmult(residual, solution_);\n    residual -= system_rhs_;\n    std::cout\n             << \"   Max norm of residual: \"\n             << residual.linfty_norm() << '\\n' << std::endl;\n*/\n  //constraints_.distribute(solution_);\n}\n\n\n// Output results\ntemplate <int dim>\nvoid THMConsolidation<dim>::output_results(unsigned int time_step, unsigned current_time) const\n{\n  std::vector<std::string> solution_names={ \"ux\", \"uy\", \"uz\", \"p\", \"T\"};\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  DataOut<dim> data_out;\n  data_out.attach_dof_handler(dof_handler_);\n  data_out.add_data_vector(solution_,\n                           solution_names);\n  data_out.build_patches();\n  std::ofstream time_file (\"time.txt\",std::ios::app);\n  double value       = current_time_;\n    //myfile.write (*conversion, strlen (conversion));\n  time_file <<value<<\"\\n\";\n  time_file.close();\n\n  std::ofstream output(\n    \"outputfiles/solution-\" + Utilities::int_to_string(time_step, 2) + \".vtk\");\n  data_out.write_vtk(output);\n}\n\ntemplate <int dim>\nvoid THMConsolidation<dim>::run()\n{\n  Timer timer_grid;\n  make_grid();\n\n  // Apply initial values\n  {\n    std::vector<bool> deformations{true, true, true, false, false};\n    std::vector<bool> pressure{false, false, false, true, false};\n    std::vector<bool> temperature{false, false, false, false, true};\n\n    // PressureInitial<dim> pressure_initial;\n    // pressure_initial.get_pressure(pressure_in_);\n\n    VectorTools::interpolate(dof_handler_, DeformationInitial<dim>(),\n                             solution_, deformations);\n    VectorTools::interpolate(dof_handler_, PressureInitial<dim>(),\n                             solution_, pressure);\n    VectorTools::interpolate(dof_handler_, TemperatureInitial<dim>(),\n                             solution_, temperature);\n  }\n  std::cout<<\"output step 0\"<<std::endl;\n  output_results(0,0);\n  std::cout<<\"output step 0 end\"<<std::endl;\n  timer_grid.stop();\n  std::cout << \"Initialize mesh and initial conditions: \" << timer_grid.cpu_time() << \"s\" << std::endl;\n\n// // Normal time step\n//   first_step_=time_step_;\n//   // std::cout<<step_torr_;\n//   current_time_=0;\n//   double err=Q_in_*std::sqrt(system_rhs_.size())+1;\n//   old_solution_=0;\n//   for(unsigned step = 1; step<max_steps_ ; ++step) {\n//     if (step==1) {\n//       time_step_=first_step_;\n//     }\n\n\n//     Timer timer_assembler;\n//     std::cout<<\"assembler started\"<<std::endl;\n//     assemble_system();\n//     timer_assembler.stop();\n//     std::cout << \"Step: \"<<step<<\", assembler: \" << timer_assembler.cpu_time() << \"s\" << std::endl;\n//     std::cout << \"l2norm of rhs: \" << system_rhs_.l2_norm()<<std::endl;\n\n//     Timer timer_solver;\n//     solve(step);\n//     timer_solver.stop();\n//     std::cout << \"Step: \"<<step<<\", solver: \" << timer_solver.cpu_time() << \"s\" << std::endl;\n//     solution_var_=old_solution_;\n//     solution_var_-=solution_;\n//     std::cout<<solution_var_.l2_norm()<<\" norm\"<<std::endl;\n//     std::cout<<time_step_<<\" adaptive_time_step\"<<std::endl;\n//     current_time_+=time_step_;\n//     std::cout<<current_time_<<\" current_time\"<<std::endl;\n//     old_solution_=solution_;\n//     if (step>1){\n//       err=solution_var_.l2_norm();\n//     }\n//     // std::cout<<err<<\" err\"<<std::endl;\n//     // std::cout<<1e-2*pressure_in_*std::sqrt(system_rhs_.size())<<\" err1\"<<std::endl;\n\n\n\n//     Timer timer_out;\n//     output_results(step,current_time_);\n//     timer_out.stop();\n//     std::cout << \"Step: \"<<step<<\", output vtk files: \" << timer_out.cpu_time() << \"s\" << std::endl;\n\n//   }\n// //Normal time step ends\n\n\n\n\n  //Adaptive time step\n  first_step_=0.01*time_step_*gamma_w*(inner_radius_/subdivision_)*(inner_radius_/subdivision_)/(6*2*mu_in_*k_in_);\n  step_torr_=0.01*Q_in_*std::sqrt(system_rhs_.size());\n  // std::cout<<inner_radius_<<\" inner\"<<std::endl;\n  std::cout<<step_torr_<<\" step_torr\"<<std::endl;\n  std::cout<<first_step_<<\" frist_step\"<<std::endl;\n  current_time_=0;\n  double err=Q_in_*std::sqrt(system_rhs_.size())+1;\n  old_solution_=0;\n  //for(unsigned step = 1; err>1e-12*Q_in_*std::sqrt(system_rhs_.size()) ; ++step) {\n  for(unsigned step = 1; current_time_< 20000; ++step) {\n\n    if (step==1) {\n      time_step_=first_step_;\n    }\n\n\n    Timer timer_assembler;\n    std::cout<<\"assembler started\"<<std::endl;\n    assemble_system();\n    timer_assembler.stop();\n    std::cout << \"Step: \"<<step<<\", assembler: \" << timer_assembler.cpu_time() << \"s\" << std::endl;\n    std::cout << \"l2norm of rhs: \" << system_rhs_.l2_norm()<<std::endl;\n\n    Timer timer_solver;\n    solve(step);\n    timer_solver.stop();\n    std::cout << \"Step: \"<<step<<\", solver: \" << timer_solver.cpu_time() << \"s\" << std::endl;\n    solution_var_=old_solution_;\n    solution_var_-=solution_;\n    std::cout<<solution_var_.l2_norm()<<\" norm\"<<std::endl;\n    std::cout<<time_step_<<\" adaptive_time_step\"<<std::endl;\n    current_time_+=time_step_;\n    std::cout<<current_time_<<\" current_time\"<<std::endl;\n    old_solution_=solution_;\n    if (step>1){\n      err=solution_var_.l2_norm();\n    }\n    // std::cout<<err<<\" err\"<<std::endl;\n    // std::cout<<1e-2*pressure_in_*std::sqrt(system_rhs_.size())<<\" err1\"<<std::endl;\n\n\n\n    Timer timer_out;\n    output_results(step,current_time_);\n    timer_out.stop();\n    std::cout << \"Step: \"<<step<<\", output vtk files: \" << timer_out.cpu_time() << \"s\" << std::endl;\n    std::cout<<\"err: \"<<err<<std::endl;\n    if (err<step_torr_/10){\n      time_step_*=1.5;\n      std::cout<<\"larger step\"<<std::endl;\n    }\n    else if (err>step_torr_*10){\n      time_step_/=2;\n      std::cout<<\"smaller step\"<<std::endl;\n      if (time_step_<first_step_){\n        time_step_=first_step_;\n      }\n    }\n  }\n\n\n// adaptive time step ends\n}\n\n\nint main(int argc, char** argv) {\n\n  try {\n\n    if (argc != 2) {\n      std::cout << \"Usage: ./thm /path/to/input.json\\n\";\n      throw std::runtime_error(\"Incorrect number of input arguments\");\n    }\n\n    const std::string filename = argv[1];\n\n    // Input file\n    std::ifstream in(filename);\n    const nlohmann::json input_json = Json::parse(in);\n\n    std::string title = input_json[\"title\"].template get<std::string>();\n    unsigned degree = input_json[\"degree\"].template get<unsigned>();\n    std::cout<<title<<\", with degree: \"<<degree<<std::endl;\n\n    THMConsolidation<3> thm_consolidation_solver(degree, input_json);\n    thm_consolidation_solver.run();\n\n  } catch (std::exception& exc) {\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  } catch (...) {\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}\n", "meta": {"hexsha": "8ffdda71c3b1aac388ebc9ec60b67d332919da53", "size": 48187, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/main_consolidation.cc", "max_stars_repo_name": "zs0930/thm", "max_stars_repo_head_hexsha": "e67e918e895d82e74bd09f1c12ca5feb37569162", "max_stars_repo_licenses": ["MIT"], "max_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_consolidation.cc", "max_issues_repo_name": "zs0930/thm", "max_issues_repo_head_hexsha": "e67e918e895d82e74bd09f1c12ca5feb37569162", "max_issues_repo_licenses": ["MIT"], "max_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_consolidation.cc", "max_forks_repo_name": "zs0930/thm", "max_forks_repo_head_hexsha": "e67e918e895d82e74bd09f1c12ca5feb37569162", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-13T19:04:18.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T19:04:18.000Z", "avg_line_length": 37.3542635659, "max_line_length": 136, "alphanum_fraction": 0.6151244111, "num_tokens": 12303, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.45154800549350294}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n// Unit Test\r\n\r\n// Copyright (c) 2007-2011 Barend Gehrels, Amsterdam, the Netherlands.\r\n// Copyright (c) 2008-2011 Bruno Lalande, Paris, France.\r\n// Copyright (c) 2009-2011 Mateusz Loskot, London, UK.\r\n\r\n// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library\r\n// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n\r\n#include <geometry_test_common.hpp>\r\n\r\n#include <boost/geometry/algorithms/make.hpp>\r\n\r\n#include <boost/geometry/domains/gis/io/wkt/write_wkt.hpp>\r\n\r\n#include <boost/geometry/geometries/geometries.hpp>\r\n#include <boost/geometry/geometries/adapted/c_array.hpp>\r\n#include <boost/geometry/geometries/adapted/boost_tuple.hpp>\r\n#include <test_common/test_point.hpp>\r\n\r\nBOOST_GEOMETRY_REGISTER_C_ARRAY_CS(cs::cartesian)\r\nBOOST_GEOMETRY_REGISTER_BOOST_TUPLE_CS(cs::cartesian)\r\n\r\n\r\ntemplate <typename T, typename P>\r\nvoid test_point_2d()\r\n{\r\n    P p = bg::make<P>((T) 123, (T) 456);\r\n    BOOST_CHECK_CLOSE(bg::get<0>(p), 123.0, 1.0e-6);\r\n    BOOST_CHECK_CLOSE(bg::get<1>(p), 456.0, 1.0e-6);\r\n}\r\n\r\ntemplate <typename T, typename P>\r\nvoid test_point_3d()\r\n{\r\n    P p = bg::make<P>((T) 123, (T) 456, (T) 789);\r\n    BOOST_CHECK_CLOSE( bg::get<0>(p), 123.0, 1.0e-6);\r\n    BOOST_CHECK_CLOSE( bg::get<1>(p), 456.0, 1.0e-6);\r\n    BOOST_CHECK_CLOSE( bg::get<2>(p), 789.0, 1.0e-6);\r\n}\r\n\r\ntemplate <typename T, typename P>\r\nvoid test_box_2d()\r\n{\r\n    typedef bg::model::box<P> B;\r\n    B b = bg::make<B>((T) 123, (T) 456, (T) 789, (T) 1011);\r\n    BOOST_CHECK_CLOSE( (bg::get<bg::min_corner, 0>(b)), 123.0, 1.0e-6);\r\n    BOOST_CHECK_CLOSE( (bg::get<bg::min_corner, 1>(b)), 456.0, 1.0e-6);\r\n    BOOST_CHECK_CLOSE( (bg::get<bg::max_corner, 0>(b)), 789.0, 1.0e-6);\r\n    BOOST_CHECK_CLOSE( (bg::get<bg::max_corner, 1>(b)), 1011.0, 1.0e-6);\r\n\r\n    b = bg::make_inverse<B>();\r\n}\r\n\r\ntemplate <typename T, typename P>\r\nvoid test_linestring_2d()\r\n{\r\n    typedef bg::model::linestring<P> L;\r\n\r\n    T coors[][2] = {{1,2}, {3,4}};\r\n\r\n    L line = bg::detail::make::make_points<L>(coors);\r\n\r\n    BOOST_CHECK_EQUAL(line.size(), 2u);\r\n}\r\n\r\ntemplate <typename T, typename P>\r\nvoid test_linestring_3d()\r\n{\r\n    typedef bg::model::linestring<P> L;\r\n\r\n    T coors[][3] = {{1,2,3}, {4,5,6}};\r\n\r\n    L line = bg::detail::make::make_points<L>(coors);\r\n\r\n    BOOST_CHECK_EQUAL(line.size(), 2u);\r\n    //std::cout << dsv(line) << std::endl;\r\n\r\n}\r\n\r\ntemplate <typename T, typename P>\r\nvoid test_2d_t()\r\n{\r\n    test_point_2d<T, P>();\r\n    test_box_2d<T, P>();\r\n    test_linestring_2d<T, P>();\r\n}\r\n\r\ntemplate <typename P>\r\nvoid test_2d()\r\n{\r\n    test_2d_t<int, P>();\r\n    test_2d_t<float, P>();\r\n    test_2d_t<double, P>();\r\n}\r\n\r\ntemplate <typename T, typename P>\r\nvoid test_3d_t()\r\n{\r\n    test_linestring_3d<T, P>();\r\n//  test_point_3d<T, test_point>();\r\n}\r\n\r\ntemplate <typename P>\r\nvoid test_3d()\r\n{\r\n    test_3d_t<int, P>();\r\n    test_3d_t<float, P>();\r\n    test_3d_t<double, P>();\r\n}\r\n\r\nint test_main(int, char* [])\r\n{\r\n    //test_2d<int[2]>();\r\n    //test_2d<float[2]>();\r\n    //test_2d<double[2]>();\r\n    test_2d<bg::model::point<int, 2, bg::cs::cartesian> >();\r\n    test_2d<bg::model::point<float, 2, bg::cs::cartesian> >();\r\n    test_2d<bg::model::point<double, 2, bg::cs::cartesian> >();\r\n\r\n\r\n    test_3d<bg::model::point<double, 3, bg::cs::cartesian> >();\r\n\r\n#if defined(HAVE_TTMATH)\r\n    test_2d<bg::model::point<ttmath_big, 2, bg::cs::cartesian> >();\r\n    test_3d<bg::model::point<ttmath_big, 3, bg::cs::cartesian> >();\r\n#endif\r\n\r\n\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "11a67b32e332e354c9756d5c6946943407a9268e", "size": 3723, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/test/algorithms/make.cpp", "max_stars_repo_name": "Ron2014/boost_1_48_0", "max_stars_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "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/geometry/test/algorithms/make.cpp", "max_issues_repo_name": "Ron2014/boost_1_48_0", "max_issues_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "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/geometry/test/algorithms/make.cpp", "max_forks_repo_name": "Ron2014/boost_1_48_0", "max_forks_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "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.9782608696, "max_line_length": 80, "alphanum_fraction": 0.6290625839, "num_tokens": 1253, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.4515480019155017}}
{"text": "#include \"precompiled.h\"\n\n#ifndef AUTOMATIC_PRECOMPILATION\n#include <boost/throw_exception.hpp>\n#include <boost/property_tree/ptree.hpp>\n#include <string>\n#include <pretty_printer.h>\n#endif\n\n#include \"exceptions.h\"\n#include \"configuration_parser.h\"\n#include \"expectation_value_config.h\"\n#include \"Math.h\"\n#include \"global_config.h\"\n\nusing namespace fipster;\nusing namespace fipster::expectation_values;\n\n// #################################################\n// ##############   PHASE 1:\t\t\t############\n// ##############   CONFIGURATION       ############\n// #################################################\n\t\t\nexpect_future_t::expect_future_t(btime field_time, btime rannacher_time\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t , plain_spacetime_field exercise\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t ,boost::optional<double> entropic_theta\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t ,double discounting_factor)\n\t: field_time(field_time)\n\t, rannacher(field_time==rannacher_time)\n\t\t//apply rannacher to damp the oscillations caused by\n\t\t//discontinuities in the derivative of the payoff\n\t,exercise(exercise)\n{\n\tdetails.entropic_theta=entropic_theta;\n\tdetails.discounting_factor = discounting_factor;\n}\n\nconfig_t::config_t( const ptree& pt )\n\t: id(betterGet<string>(pt,\"<xmlattr>.id\",\"expectation value\"))\n\t, steps(betterChild(pt,\"timeStepping\",id),id+\".timeStepping\")\n{\n\n\tboundary_conditions_s = pt.get<string>(\"boundaryConditions\");\n\tfd_weights_s = pt.get<string>(\"finiteDifferenceWeights\");\n\n\tstrang_symmetrization = pt.get<bool>(\"strangSymmetrization\");\n\n\tauto ran=betterChild(pt,\"rannacherSteps\",id);\n\tauto id2=id+\".rannacherSteps\";\n\trannacher_step_size = getBtime(ran,\"stepSize\",id2);\n\trannacher_steps = betterGet<int>(ran,\"<xmlattr>.steps\",id2);\n\trannacher_theta = betterGet<double>(ran,\"theta\",id2);\n\trannacher_strang_symmetrization = betterGet<bool>(ran,\"strangSymmetrization\",id2);\n\n\ttheta = betterGet<double>(pt,\"theta\",id);\n\n\tif(theta<0 || theta>1)\n\t\tFIPSTER_THROW_EXCEPTION(runtime_error(toS(theta)+\" is no valid Time Stepping theta value\"));\n\t\t\n}\n\n\n", "meta": {"hexsha": "09970c891a7eca7ebf2418e6dee990ab78afa0e5", "size": 1983, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/expectation_value_config.cpp", "max_stars_repo_name": "johannesgerer/fipster", "max_stars_repo_head_hexsha": "10e840e01d196cddef75bf3eeb427f720b3e0ad6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-29T14:33:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-29T14:33:37.000Z", "max_issues_repo_path": "src/expectation_value_config.cpp", "max_issues_repo_name": "johannesgerer/fipster", "max_issues_repo_head_hexsha": "10e840e01d196cddef75bf3eeb427f720b3e0ad6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/expectation_value_config.cpp", "max_forks_repo_name": "johannesgerer/fipster", "max_forks_repo_head_hexsha": "10e840e01d196cddef75bf3eeb427f720b3e0ad6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.4761904762, "max_line_length": 94, "alphanum_fraction": 0.6863338376, "num_tokens": 487, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.6150878414043814, "lm_q1q2_score": 0.45154799513383936}}
{"text": "\n#include <alglib/optimization.h>\n#include <functional>\n#include <limits>\n#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n#include \"perceive/foundation.hpp\"\n\n#include \"levenberg-marquardt.hpp\"\n\nusing namespace alglib;\n\nnamespace perceive\n{\nstatic void opt_fun(const real_1d_array& x, real_1d_array& fi, void* ptr)\n{\n   using cost_fun_t = std::function<double(const double*)>;\n   fi[0] = (static_cast<cost_fun_t*>(ptr))->operator()(x.getcontent());\n}\n\n// ---------------------------------------- Levenberg-Marquardt (double version)\n\nvoid levenberg_marquardt(std::function<double(const double*)> fn,\n                         unsigned n,\n                         double start[],\n                         double xmin[],\n                         double reqmin,\n                         double diffstep, // 0.0001\n                         int kcount,\n                         int& icount,\n                         int& ifault)\n{\n   levenberg_marquardt(\n       fn, n, start, xmin, reqmin, diffstep, 1, kcount, icount, ifault);\n   // real_1d_array x;\n   // minlmstate state;\n   // minlmreport rep;\n\n   // icount = ifault = 0;\n\n   // // Copy in start point\n   // x.setlength(n);\n   // for(unsigned i = 0; i < n; ++i)\n   //     x[i] = start[i];\n\n   // minlmcreatev(n, 1, x, diffstep, state);           // Initialize state\n   // minlmsetcond(state, reqmin, kcount);              // constraints\n   // alglib::minlmoptimize(state, opt_fun, NULL, &fn); // Optimize\n   // minlmresults(state, x, rep);                      // Get results\n\n   // // Unpack\n   // for(unsigned i = 0; i < n; ++i)\n   //     xmin[i] = x[i];\n\n   // icount = rep.iterationscount;\n   // ifault = rep.terminationtype;\n}\n\n// ----------------------------------------- Levenberg-Marquardt (float version)\n\nvoid levenberg_marquardt(std::function<float(const float*)> fn,\n                         unsigned n,\n                         float start[],\n                         float xmin[],\n                         float reqmin,\n                         float diffstep, // 0.0001\n                         int kcount,\n                         int& icount,\n                         int& ifault)\n{\n   std::vector<float> buffer(n);\n   std::vector<double> start_d(n);\n   std::vector<double> xmin_d(n);\n\n   for(unsigned i = 0; i < n; ++i) start_d[i] = double(start[i]);\n   for(unsigned i = 0; i < n; ++i) xmin_d[i] = double(xmin[i]);\n\n   auto cost_fn = [&](const double* X) -> double {\n      for(auto& val : buffer) val = float(*X++);\n      return double(fn(&buffer[0]));\n   };\n\n   levenberg_marquardt(cost_fn,\n                       n,\n                       &start_d[0],\n                       &xmin_d[0],\n                       double(reqmin),\n                       double(diffstep),\n                       kcount,\n                       icount,\n                       ifault);\n\n   for(unsigned i = 0; i < n; ++i) xmin[i] = float(xmin_d[i]);\n}\n\n// --------------------------------------------------------------- With restarts\n\nvoid levenberg_marquardt(std::function<double(const double*)> fn,\n                         unsigned n,\n                         double start[],\n                         double xmin[],\n                         double reqmin,\n                         double diffstep,\n                         int numres,\n                         int kcount,\n                         int& icount,\n                         int& ifault)\n{\n   real_1d_array x;\n   minlmstate state;\n   minlmreport rep;\n   unsigned final_count = 0;\n\n   icount = ifault = 0;\n\n   double best_val = std::numeric_limits<double>::max();\n   std::function<double(const double*)> fn2z = [&](const double* X) {\n      auto val = fn(X);\n      if(val < best_val) {\n         best_val = val;\n         memcpy(&xmin[0], X, sizeof(double) * n);\n      }\n      return val;\n   };\n\n   // Copy in start point\n   x.setlength(n);\n   for(unsigned i = 0; i < n; ++i) x[i] = start[i];\n\n   try {\n      minlmcreatev(n, 1, x, diffstep, state);             // Initialize state\n      minlmsetcond(state, reqmin, kcount);                // constraints\n      alglib::minlmoptimize(state, opt_fun, NULL, &fn2z); // Optimize\n      minlmresults(state, x, rep);                        // Get results\n\n      // Unpack\n      icount += rep.iterationscount;\n      for(unsigned i = 0; i < n; ++i) xmin[i] = x[i];\n\n      for(int itr = 1; itr < numres && rep.terminationtype == 2; ++itr) {\n         // cout << \"------------------------------------------------------\"\n         //      << endl;\n         for(unsigned i = 0; i < n; ++i) x[i] = xmin[i];\n         diffstep *= 0.1;\n         minlmcreatev(n, 1, x, diffstep, state);             // Initialize state\n         minlmsetcond(state, reqmin, kcount);                // constraints\n         alglib::minlmoptimize(state, opt_fun, NULL, &fn2z); // Optimize\n         minlmresults(state, x, rep);\n         icount += rep.iterationscount;\n         for(unsigned i = 0; i < n; ++i) xmin[i] = x[i];\n      }\n\n      ifault = int(rep.terminationtype);\n   } catch(alglib::ap_error& e) {\n      ifault = -9;\n      LOG_ERR(format(\"Exception in levenberg-marquardt: {}\", e.msg));\n   } catch(std::exception& e) {\n      ifault = -9;\n      LOG_ERR(format(\"Exception in levenberg-marquardt: {}\", e.what()));\n   } catch(...) {\n      ifault = -9;\n   }\n}\n\nvoid levenberg_marquardt(std::function<float(const float*)> fn,\n                         unsigned n,\n                         float start[],\n                         float xmin[],\n                         float reqmin,\n                         float diffstep,\n                         int numres, // diffstep *= 0.1 between each restart\n                         int kcount,\n                         int& icount,\n                         int& ifault)\n{\n   std::vector<float> buffer(n);\n   std::vector<double> start_d(n);\n   std::vector<double> xmin_d(n);\n\n   for(unsigned i = 0; i < n; ++i) start_d[i] = double(start[i]);\n   for(unsigned i = 0; i < n; ++i) xmin_d[i] = double(xmin[i]);\n\n   auto cost_fn = [&](const double* X) -> double {\n      for(auto& val : buffer) val = float(*X++);\n      return double(fn(&buffer[0]));\n   };\n\n   levenberg_marquardt(cost_fn,\n                       n,\n                       &start_d[0],\n                       &xmin_d[0],\n                       double(reqmin),\n                       double(diffstep),\n                       numres,\n                       kcount,\n                       icount,\n                       ifault);\n\n   for(unsigned i = 0; i < n; ++i) xmin[i] = float(xmin_d[i]);\n}\n\n// ----------------------------------------------- Levenberg-Marquardt fault-str\n\nconst char* levenberg_marquardt_fault_str(int ifault)\n{\n   switch(ifault) {\n   case -9: return \"exception\";\n   case -8: return \"NAN/INF value detected either in function or Jacobian\";\n   case -7: return \"derivative correctness check failed\";\n   case -5: return \"inappropriate solver was used\";\n   case -3: return \"constraints are inconsistent\";\n   case 2: return \"relative step is no more than EpsX.\";\n   case 5: return \"MaxIts steps was taken\";\n   case 7: return \"stopping conditions forbid further improvement\";\n   case 8: return \"terminated by  user via MinLMRequestTermination()\";\n   default: return \"Unknown ifault condition\";\n   }\n}\n\n} // namespace perceive\n", "meta": {"hexsha": "f35cf0ecb62af7d895255830d53f142e66173884", "size": 7261, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "multiview/multiview_cpp/src/perceive/optimization/levenberg-marquardt.cpp", "max_stars_repo_name": "prcvlabs/multiview", "max_stars_repo_head_hexsha": "1a03e14855292967ffb0c0ec7fff855c5abbc9d2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-09-03T23:12:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T21:43:32.000Z", "max_issues_repo_path": "multiview/multiview_cpp/src/perceive/optimization/levenberg-marquardt.cpp", "max_issues_repo_name": "prcvlabs/multiview", "max_issues_repo_head_hexsha": "1a03e14855292967ffb0c0ec7fff855c5abbc9d2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-09-08T02:57:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-26T05:33:02.000Z", "max_forks_repo_path": "multiview/multiview_cpp/src/perceive/optimization/levenberg-marquardt.cpp", "max_forks_repo_name": "prcvlabs/multiview", "max_forks_repo_head_hexsha": "1a03e14855292967ffb0c0ec7fff855c5abbc9d2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-09-26T03:14:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T06:42:52.000Z", "avg_line_length": 32.5605381166, "max_line_length": 80, "alphanum_fraction": 0.4867098196, "num_tokens": 1774, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4515254344390854}}
{"text": "//\r\n// Created by phili on 26.12.2019.\r\n//\r\n\r\n#define _USE_MATH_DEFINES\r\n#include <iostream>\r\n#include <Eigen/Dense>\r\n#include <vector>\r\n\r\n#include <cmath>\r\n\r\n#ifndef M_PI\r\n  #define M_PI 3.14159265358979323846\r\n#endif\r\n\r\nusing namespace Eigen;\r\n\r\nstd::vector<double> f(MatrixXd &M, MatrixXd &V, const MatrixXd &D, double rr){\r\n  MatrixXd tt;\r\n  Matrix<bool, Eigen::Dynamic, 1> is_covered;\r\n  std::vector<double> d;\r\n  \r\n  \r\n  for (size_t k=0; k<10; k++){\r\n    tt = M.colwise()-V.col(k);\r\n    tt = D*tt;\r\n    is_covered = tt.colwise().squaredNorm().array() <= rr;\r\n    std::cout << is_covered << std::endl;\r\n    for(size_t i=0; i<M.cols(); i++){\r\n      if(is_covered(i)){\r\n        d.push_back(M(0,i));\r\n      }\r\n    }\r\n  }\r\n  return d;\r\n}\r\n\r\nint main(){\r\n  \r\n  MatrixXd M;\r\n  MatrixXd D;\r\n  MatrixXd V;\r\n  std::vector<double> blub;\r\n  \r\n  M = MatrixXd::Random(10,1000);\r\n  V = MatrixXd::Random(10,10);\r\n  D = MatrixXd::Random(10,10);\r\n  for (double k=0; k<1000; k+=10.){\r\n    blub = f(M,V,D, k);\r\n    for (auto bbb : blub){\r\n      std::cout << bbb << std::endl;\r\n    }\r\n  }\r\n  return 0;\r\n}", "meta": {"hexsha": "2f27ee0727035faa5978696d22bdd88cf9e8b3e6", "size": 1089, "ext": "cc", "lang": "C++", "max_stars_repo_path": "main2.cc", "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": "main2.cc", "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": "main2.cc", "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": 19.8, "max_line_length": 79, "alphanum_fraction": 0.5592286501, "num_tokens": 354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4515254344390854}}
{"text": "#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <string>\n#include <cmath>\n#include <typeinfo>\n#include <typeindex>\n#include <cassert>\n#include <unordered_map>\n#include <functional>\n\n#include <boost/program_options.hpp>\n#include <boost/algorithm/string.hpp>\n#include <boost/archive/binary_iarchive.hpp>\n#include <boost/archive/binary_oarchive.hpp>\n\n#include <logging.hpp>\n#include <matrix_serialization.hpp>\n#include <lapack.hpp>\n\n\n\nnamespace po = boost::program_options;\n\n\n\nauto init_options() -> po::options_description\n{\n\tpo::options_description desc;\n\n\tdesc.add_options()\n\t\t( \"help\", \"Produce the help message.\" )\n\t\t( \"type\", po::value<std::string>()->required()\n\t\t, \"Type of an element of the hamiltonian matrix. It may be one of: \"\n\t\t  \"float, double, cfloat, cdouble.\" )\n\t\t( \"energies\", po::value<std::string>()->required()\n\t\t, \"Name of the file where to save the eigenenergies of the system.\" )\n\t\t( \"states\", po::value<std::string>()->required()\n\t\t, \"Name of the file where to save the eigenestates of the system.\" );\n\t\n\treturn desc;\n}\n\n\nauto element_type(std::string input) -> std::type_index\n{\n\tusing namespace std::string_literals;\n\tstatic std::unordered_map<std::string, std::type_index> const types = \n\t\t{ { \"float\"s,   std::type_index(typeid(float))                }\n\t\t, { \"double\"s,  std::type_index(typeid(double))               }\n\t\t, { \"cfloat\"s,  std::type_index(typeid(std::complex<float>))  }\n\t\t, { \"cdouble\"s, std::type_index(typeid(std::complex<double>)) }\n\t\t};\n\t\n\tboost::to_lower(input);\n\ttry {\n\t\treturn types.at(input);\n\t} catch(std::out_of_range & e) {\n\t\tstd::cerr << \"Invalid element type `\" + input + \"`!\\n\";\n\t\tthrow;\n\t}\n}\n\n\n\ntemplate<class _Help, class _Run>\nauto process_command_line( int argc, char** argv\n                         , _Help&& help\n\t\t\t\t\t\t , _Run&& run ) -> void\n{\n\tauto const description = init_options();\n\tpo::variables_map vm;\n\n\tpo::store(po::command_line_parser(argc, argv).options(description).run()\n\t         , vm );\n\n\tif(vm.count(\"help\")) {\n\t\thelp(description);\n\t\treturn;\n\t}\n\n\tpo::notify(vm);\n\n\trun( element_type(vm[\"type\"].as<std::string>()) \n\t   , vm[\"energies\"].as<std::string>()\n\t   , vm[\"states\"].as<std::string>()\n\t   );\n}\n\n\ntemplate<class _T, class _IStream, class _OStream1, class _OStream2>\nauto solve( _IStream & input\n          , _OStream1 & energies_output\n\t\t  , _OStream2 & states_output ) -> void\n{\n\tboost::log::sources::severity_logger<tcm::severity_level> lg;\n\n\tLOG(lg, info) << \"Reading Hamiltonian...\";\n\ttcm::Matrix<_T> H;\n\tboost::archive::binary_iarchive input_archive{input};\n\tinput_archive >> H;\n\n\ttcm::Matrix<tcm::utils::Base<_T>>   E{H.height(), 1};\n\ttcm::Matrix<_T>                   Psi{H.height(), H.height()};\n\n\tLOG(lg, info) << \"Diagonalizing...\";\n\ttcm::lapack::heevr(H, E, Psi);\n\n\tLOG(lg, info) << \"Saving results...\";\n\tboost::archive::binary_oarchive energies_archive{energies_output};\n\tenergies_archive << E;\n\tboost::archive::binary_oarchive states_archive{states_output};\n\tstates_archive << Psi;\n\n\tLOG(lg, info) << \"Done!\";\n}\n\n\nauto run( std::type_index type\n        , std::string const& energies_filename\n\t\t, std::string const& states_filename ) -> void\n{\n\tstd::ofstream energies_file{energies_filename};\n\tif(not energies_file) {\n\t\tthrow std::runtime_error{ \"Could not open `\" + energies_filename\n\t\t                        + \"` for writing.\" };\n\t}\n\tstd::ofstream states_file{states_filename};\n\tif(not states_file) {\n\t\tthrow std::runtime_error{ \"Could not open `\" + states_filename\n\t\t                        + \"` for writing.\" };\n\t}\n\n\tusing solve_function_t = std::function<void()>;\n\tstatic std::unordered_map<std::type_index, solve_function_t> const \n\tdispatch = {\n\t\t{ std::type_index(typeid(float))\n\t\t, [&energies_file, &states_file]() \n\t\t  {solve<float>(std::cin, energies_file, states_file); } },\n\t\t{ std::type_index(typeid(double))\n\t\t, [&energies_file, &states_file]()\n\t\t  {solve<double>(std::cin, energies_file, states_file); } },\n\t\t{ std::type_index(typeid(std::complex<float>))\n\t\t, [&energies_file, &states_file]()\n\t\t  {solve<std::complex<float>>(std::cin, energies_file, states_file); } },\n\t\t{ std::type_index(typeid(std::complex<double>))\n\t\t, [&energies_file, &states_file]() \n\t\t  {solve<std::complex<double>>(std::cin, energies_file, states_file);} }\n\t};\n\n\ttcm::setup_console_logging();\n\tdispatch.at(type)();\n}\n\n\n\nint main(int argc, char** argv)\n{\n\tprocess_command_line\n\t\t( argc, argv\n\t\t, [](auto desc) { std::cout << desc << '\\n'; }\n\t\t, &run \n\t\t);\n\treturn 0;\n}\n\n", "meta": {"hexsha": "06fa596d369d9342539642bd714290fd45061357", "size": 4474, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/solve_system.cpp", "max_stars_repo_name": "twesterhout/plasmon-cpp", "max_stars_repo_head_hexsha": "a0e343ee718d9b30602b322ade6077e42e08d8e5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-05T11:12:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-05T11:12:07.000Z", "max_issues_repo_path": "src/solve_system.cpp", "max_issues_repo_name": "twesterhout/plasmon-cpp", "max_issues_repo_head_hexsha": "a0e343ee718d9b30602b322ade6077e42e08d8e5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/solve_system.cpp", "max_forks_repo_name": "twesterhout/plasmon-cpp", "max_forks_repo_head_hexsha": "a0e343ee718d9b30602b322ade6077e42e08d8e5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.7904191617, "max_line_length": 75, "alphanum_fraction": 0.6535538668, "num_tokens": 1205, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.45152542914189914}}
{"text": "/*\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n#define _USE_MATH_DEFINES\n#include <gtest/gtest.h>\n#include <Eigen/Core>\n#include <cmath>\n\n#include \"beanmachine/graph/graph.h\"\n\nusing namespace beanmachine::graph;\n\nTEST(testdistrib, lognormal) {\n  Graph g;\n  // LOG_MEAN and LOG_STD are the mean and standard deviation of the log of\n  // lognormal distribution\n  const double LOG_MEAN = -11.0;\n  const double LOG_STD = 3.0;\n  const double LOG_STD_SQ = 9.0;\n  const double MEAN = std::exp(LOG_MEAN + LOG_STD * LOG_STD / 2);\n  auto real1 = g.add_constant(LOG_MEAN);\n  auto pos1 = g.add_constant_pos_real(LOG_STD);\n\n  // negative tests that log normal has two parents\n  EXPECT_THROW(\n      g.add_distribution(\n          DistributionType::LOG_NORMAL,\n          AtomicType::POS_REAL,\n          std::vector<uint>{}),\n      std::invalid_argument);\n  EXPECT_THROW(\n      g.add_distribution(\n          DistributionType::LOG_NORMAL,\n          AtomicType::POS_REAL,\n          std::vector<uint>{real1}),\n      std::invalid_argument);\n  EXPECT_THROW(\n      g.add_distribution(\n          DistributionType::LOG_NORMAL,\n          AtomicType::POS_REAL,\n          std::vector<uint>{real1, pos1, real1}),\n      std::invalid_argument);\n\n  // negative test the parents must be a real and a positive\n  EXPECT_THROW(\n      g.add_distribution(\n          DistributionType::LOG_NORMAL,\n          AtomicType::POS_REAL,\n          std::vector<uint>{real1, real1}),\n      std::invalid_argument);\n\n  // test creation of a distribution\n  auto log_normal_dist = g.add_distribution(\n      DistributionType::LOG_NORMAL,\n      AtomicType::POS_REAL,\n      std::vector<uint>{real1, pos1});\n\n  // test distribution of mean and variance\n  auto real_val =\n      g.add_operator(OperatorType::SAMPLE, std::vector<uint>{log_normal_dist});\n  auto real_sq_val = g.add_operator(\n      OperatorType::MULTIPLY, std::vector<uint>{real_val, real_val});\n  g.query(real_val);\n  g.query(real_sq_val);\n  const std::vector<double>& means =\n      g.infer_mean(100000, InferenceType::REJECTION);\n  double variance = (std::exp(LOG_STD_SQ) - 1) * exp(2 * LOG_MEAN + LOG_STD_SQ);\n  EXPECT_NEAR(means[0], MEAN, 0.1);\n  EXPECT_NEAR(means[1] - means[0] * means[0], variance, 0.1);\n\n  // test log_prob and gradients\n  g.observe(real_val, M_E);\n\n  // f(x) = - log(3) - 0.5 log(2*pi) - 0.5 (log(x) + 11)^2 / 3^2 - log(x)\n  // f'(x) = (-11 - log(x) - 3^2) / (x * 3^2)\n  // f''(x) = (3^2 + log(x) + 11 - 1) / (3^2 * x^2)\n  // f(e) = approx. -11.0176;\n  // f'(e) = -7/3e (approx. -0.85838 )\n  // f''(e) = 20/9e^2 (approx. 0.30074)\n\n  EXPECT_NEAR(g.log_prob(real_val), -11.0176, 0.001);\n  double grad1 = 0;\n  double grad2 = 0;\n  g.gradient_log_prob(real_val, grad1, grad2);\n  EXPECT_NEAR(grad1, -0.85838, 0.01);\n  EXPECT_NEAR(grad2, 0.30074, 0.01);\n\n  // test gradient of log_prob w.r.t. sigma\n  const double SCALE = 3.5;\n  auto pos_scale = g.add_constant_pos_real(SCALE);\n  auto half_cauchy_dist = g.add_distribution(\n      DistributionType::HALF_CAUCHY,\n      AtomicType::POS_REAL,\n      std::vector<uint>{pos_scale});\n  auto pos_val =\n      g.add_operator(OperatorType::SAMPLE, std::vector<uint>{half_cauchy_dist});\n  g.observe(pos_val, 7.0);\n  auto pos_sq_val = g.add_operator(\n      OperatorType::MULTIPLY, std::vector<uint>{pos_val, pos_val});\n  auto normal_dist3 = g.add_distribution(\n      DistributionType::LOG_NORMAL,\n      AtomicType::POS_REAL,\n      std::vector<uint>{real1, pos_sq_val});\n  auto real_val3 =\n      g.add_operator(OperatorType::SAMPLE, std::vector<uint>{normal_dist3});\n  g.observe(real_val3, std::exp(5.0));\n  grad1 = grad2 = 0;\n  g.gradient_log_prob(pos_val, grad1, grad2);\n  EXPECT_NEAR(grad1, -0.483822, 1e-6);\n  EXPECT_NEAR(grad2, 0.038648, 1e-6);\n}\n\nTEST(testdistrib, backward_lognormal_lognormal) {\n  Graph g;\n  uint zero = g.add_constant(0.0);\n  uint pos_one = g.add_constant_pos_real(1.0);\n  uint two = g.add_constant((natural_t)2);\n\n  uint lognormal_dist = g.add_distribution(\n      DistributionType::LOG_NORMAL,\n      AtomicType::POS_REAL,\n      std::vector<uint>{zero, pos_one});\n  uint pos_mu =\n      g.add_operator(OperatorType::SAMPLE, std::vector<uint>{lognormal_dist});\n  uint mu = g.add_operator(OperatorType::TO_REAL, std::vector<uint>{pos_mu});\n\n  uint dist_y = g.add_distribution(\n      DistributionType::LOG_NORMAL,\n      AtomicType::POS_REAL,\n      std::vector<uint>{mu, pos_one});\n  uint y =\n      g.add_operator(OperatorType::IID_SAMPLE, std::vector<uint>{dist_y, two});\n  g.observe(pos_mu, 0.1);\n  Eigen::MatrixXd yobs(2, 1);\n  yobs << std::exp(0.5), std::exp(-0.5);\n  g.observe(y, yobs);\n\n  // test backward_param(), backward_value() and\n  // backward_param_iid(), backward_value_iid():\n  // To verify the grad1 results with pyTorch:\n  // mu = torch.tensor([0.1], requires_grad=True)\n  // y = torch.tensor([math.e**0.5, math.e**-0.5], requires_grad=True)\n  // log_p = (\n  //   torch.distributions.LogNormal(mu, torch.tensor(1.0)).log_prob(y).sum() +\n  //   torch.distributions.LogNormal(torch.tensor(0.0),\n  //   torch.tensor(1.0)).log_prob(mu)\n  // )\n  // torch.autograd.grad(log_p, mu) -> 12.8259\n  // torch.autograd.grad(log_p, y) -> [-0.8491, -0.6595]\n  std::vector<DoubleMatrix*> grad1;\n  g.eval_and_grad(grad1);\n  EXPECT_EQ(grad1.size(), 2);\n  EXPECT_NEAR((*grad1[0]), 12.8259, 1e-3);\n  EXPECT_NEAR(grad1[1]->coeff(0), -0.8491, 1e-3);\n  EXPECT_NEAR(grad1[1]->coeff(1), -0.6595, 1e-3);\n\n  // test log_prob() on vector value:\n  double log_prob_y = g.log_prob(y);\n  EXPECT_NEAR(log_prob_y, -2.0979, 0.001);\n}\n", "meta": {"hexsha": "0ee51ccb6b650089cdd6d4d42a6caabd76fc37fa", "size": 5637, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/beanmachine/graph/distribution/tests/log_normal_test.cpp", "max_stars_repo_name": "facebookresearch/beanmachine", "max_stars_repo_head_hexsha": "225114d9964b90c3a49adddc4387b4a47d1b4262", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 177.0, "max_stars_repo_stars_event_min_datetime": "2021-12-12T14:19:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T05:48:10.000Z", "max_issues_repo_path": "src/beanmachine/graph/distribution/tests/log_normal_test.cpp", "max_issues_repo_name": "facebookresearch/beanmachine", "max_issues_repo_head_hexsha": "225114d9964b90c3a49adddc4387b4a47d1b4262", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 171.0, "max_issues_repo_issues_event_min_datetime": "2021-12-11T06:12:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T20:26:29.000Z", "max_forks_repo_path": "src/beanmachine/graph/distribution/tests/log_normal_test.cpp", "max_forks_repo_name": "facebookresearch/beanmachine", "max_forks_repo_head_hexsha": "225114d9964b90c3a49adddc4387b4a47d1b4262", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 31.0, "max_forks_repo_forks_event_min_datetime": "2021-12-11T06:27:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T13:31:56.000Z", "avg_line_length": 34.1636363636, "max_line_length": 80, "alphanum_fraction": 0.6629412808, "num_tokens": 1709, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.803173777511623, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4515254238447127}}
{"text": "/*\nImport a ZDF point cloud and downsample it.\n*/\n\n#include <Zivid/CloudVisualizer.h>\n#include <Zivid/Zivid.h>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n#include <iostream>\n\nZivid::PointCloud downsample(const Zivid::PointCloud &, int);\nEigen::MatrixXi downsampleAndRound(const Eigen::MatrixXi &, int);\nEigen::MatrixXf gridSum(const Eigen::MatrixXf &, int);\nEigen::MatrixXf lineSum(Eigen::MatrixXf, int);\nfloat nanToZero(float);\nvoid visualizePointCloud(const Zivid::PointCloud &, Zivid::Application &);\n\nint main()\n{\n    try\n    {\n        Zivid::Application zivid;\n\n        std::string filename = \"Zivid3D.zdf\";\n        std::cout << \"Reading \" << filename << \" point cloud\" << std::endl;\n        Zivid::Frame frame(filename);\n\n        auto pointCloud = frame.getPointCloud();\n\n        auto downsamplingFactor = 4;\n\n        auto pointCloudDownsampled = downsample(pointCloud, downsamplingFactor);\n\n        visualizePointCloud(pointCloud, zivid);\n        visualizePointCloud(pointCloudDownsampled, zivid);\n    }\n\n    catch(const std::exception &e)\n    {\n        std::cerr << \"Error: \" << Zivid::toString(e) << std::endl;\n        return EXIT_FAILURE;\n    }\n}\n\nZivid::PointCloud downsample(const Zivid::PointCloud &pointCloud, int downsamplingFactor)\n{\n    /*\n\tFunction for downsampling a Zivid point cloud. The downsampling factor represents the denominator\n\tof a fraction that represents the size of the downsampled point cloud relative to the original\n\tpoint cloud, e.g. 2 - one-half,  3 - one-third, 4 one-quarter, etc.\n\t*/\n\n    if((pointCloud.height() % downsamplingFactor) || (pointCloud.width() % downsamplingFactor))\n    {\n        throw std::invalid_argument(\"Downsampling factor (\" + std::to_string(downsamplingFactor)\n                                    + \") has to a factor of the width (\" + std::to_string(pointCloud.width())\n                                    + \") and height (\" + std::to_string(pointCloud.height())\n                                    + \") of the input point cloud.\");\n    }\n\n    Eigen::MatrixXf x(pointCloud.height(), pointCloud.width());\n    Eigen::MatrixXf y(pointCloud.height(), pointCloud.width());\n    Eigen::MatrixXf z(pointCloud.height(), pointCloud.width());\n    Eigen::MatrixXi r(pointCloud.height(), pointCloud.width());\n    Eigen::MatrixXi g(pointCloud.height(), pointCloud.width());\n    Eigen::MatrixXi b(pointCloud.height(), pointCloud.width());\n    Eigen::MatrixXf contrast(pointCloud.height(), pointCloud.width());\n\n    for(size_t i = 0; i < pointCloud.height(); i++)\n    {\n        for(size_t j = 0; j < pointCloud.width(); j++)\n        {\n            x(i, j) = pointCloud(i, j).x;\n            y(i, j) = pointCloud(i, j).y;\n            z(i, j) = pointCloud(i, j).z;\n            r(i, j) = pointCloud(i, j).red();\n            g(i, j) = pointCloud(i, j).green();\n            b(i, j) = pointCloud(i, j).blue();\n            contrast(i, j) = pointCloud(i, j).contrast;\n        }\n    }\n\n    Eigen::MatrixXi redDownsampled = downsampleAndRound(r, downsamplingFactor);\n    Eigen::MatrixXi greenDownsampled = downsampleAndRound(g, downsamplingFactor);\n    Eigen::MatrixXi blueDownsampled = downsampleAndRound(b, downsamplingFactor);\n\n    std::function<float(float)> is_not_nan_functor = [](float f) { return !std::isnan(f); };\n    std::function<float(float)> nan_to_zero_functor = nanToZero;\n\n    Eigen::MatrixXf contrastNulled =\n        (z.unaryExpr(is_not_nan_functor)).cwiseProduct(contrast.unaryExpr(nan_to_zero_functor));\n\n    auto contrastWeight = gridSum(contrastNulled, downsamplingFactor);\n\n    Eigen::MatrixXf xContrasted = x.cwiseProduct(contrastNulled);\n    Eigen::MatrixXf yContrasted = y.cwiseProduct(contrastNulled);\n    Eigen::MatrixXf zContrasted = z.cwiseProduct(contrastNulled);\n    Eigen::MatrixXf contrastContrasted = contrast.cwiseProduct(contrastNulled);\n\n    Eigen::MatrixXf xDownsampled = gridSum(xContrasted, downsamplingFactor).cwiseQuotient(contrastWeight);\n    Eigen::MatrixXf yDownsampled = gridSum(yContrasted, downsamplingFactor).cwiseQuotient(contrastWeight);\n    Eigen::MatrixXf zDownsampled = gridSum(zContrasted, downsamplingFactor).cwiseQuotient(contrastWeight);\n    Eigen::MatrixXf contrastDownsampled = gridSum(contrastContrasted, downsamplingFactor).cwiseQuotient(contrastWeight);\n\n    Zivid::PointCloud pointCloudDownsampled(redDownsampled.rows(), redDownsampled.cols());\n\n    for(int i = 0; i < redDownsampled.rows(); i++)\n    {\n        for(int j = 0; j < redDownsampled.cols(); j++)\n        {\n            pointCloudDownsampled(i, j).setRgb(redDownsampled(i, j), greenDownsampled(i, j), blueDownsampled(i, j));\n            pointCloudDownsampled(i, j).setContrast(contrastDownsampled(i, j));\n            pointCloudDownsampled(i, j).x = xDownsampled(i, j);\n            pointCloudDownsampled(i, j).y = yDownsampled(i, j);\n            pointCloudDownsampled(i, j).z = zDownsampled(i, j);\n        }\n    }\n\n    return pointCloudDownsampled;\n}\n\nEigen::MatrixXi downsampleAndRound(const Eigen::MatrixXi &matrixi, int downsamplingFactor)\n{\n    Eigen::MatrixXf matrixf = matrixi.template cast<float>();\n\n    std::function<float(float)> round_functor = [](float f) { return std::round(f); };\n\n    return ((gridSum(matrixf, downsamplingFactor) / (downsamplingFactor * downsamplingFactor)).unaryExpr(round_functor))\n        .template cast<int>();\n}\n\nEigen::MatrixXf gridSum(const Eigen::MatrixXf &r, int downsamplingFactor)\n{\n    return lineSum(lineSum(r, downsamplingFactor).transpose(), downsamplingFactor).transpose();\n}\n\nEigen::MatrixXf lineSum(Eigen::MatrixXf matrix, int downsamplingFactor)\n{\n    Eigen::Map<Eigen::MatrixXf> flattenedMatrixMap(matrix.data(),\n                                                   downsamplingFactor,\n                                                   matrix.rows() * matrix.cols() / downsamplingFactor);\n    std::function<float(float)> nan_to_zero_functor = nanToZero;\n\n    Eigen::MatrixXf flattenedMatrixNansRemoved = flattenedMatrixMap.unaryExpr(nan_to_zero_functor);\n\n    Eigen::MatrixXf flattenedMatrixColwiseSum = flattenedMatrixNansRemoved.colwise().sum();\n\n    Eigen::Map<Eigen::MatrixXf> reshapedMatrixMap(flattenedMatrixColwiseSum.data(),\n                                                  matrix.rows() / downsamplingFactor,\n                                                  matrix.cols());\n\n    return reshapedMatrixMap;\n}\n\nfloat nanToZero(float x)\n{\n    if(std::isnan(x))\n    {\n        return 0;\n    }\n    else\n    {\n        return x;\n    }\n}\n\nvoid visualizePointCloud(const Zivid::PointCloud &pointCloud, Zivid::Application &zivid)\n{\n    std::cout << \"Setting up visualization\" << std::endl;\n    Zivid::CloudVisualizer vis;\n    zivid.setDefaultComputeDevice(vis.computeDevice());\n\n    std::cout << \"Displaying the point cloud\" << std::endl;\n    vis.showMaximized();\n    vis.show(pointCloud);\n    vis.resetToFit();\n\n    std::cout << \"Running the visualizer. Blocking until the window closes\" << std::endl;\n    vis.run();\n}\n", "meta": {"hexsha": "c4441aa3266006b35bea2820c7f647fdad4dbee7", "size": 6936, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/Applications/Advanced/Downsample/Downsample.cpp", "max_stars_repo_name": "ZachZheng0316/Cpp_Sample_For_Zivid_Camera", "max_stars_repo_head_hexsha": "f448e5a206bc755813727b319eae43dfe1504e6d", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/Applications/Advanced/Downsample/Downsample.cpp", "max_issues_repo_name": "ZachZheng0316/Cpp_Sample_For_Zivid_Camera", "max_issues_repo_head_hexsha": "f448e5a206bc755813727b319eae43dfe1504e6d", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/Applications/Advanced/Downsample/Downsample.cpp", "max_forks_repo_name": "ZachZheng0316/Cpp_Sample_For_Zivid_Camera", "max_forks_repo_head_hexsha": "f448e5a206bc755813727b319eae43dfe1504e6d", "max_forks_repo_licenses": ["BSD-3-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.9016393443, "max_line_length": 120, "alphanum_fraction": 0.6588811995, "num_tokens": 1718, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737775116229, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.45152542384471267}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_COMMON_DETAIL_SCALAR_D_LOG_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_DETAIL_SCALAR_D_LOG_HPP_INCLUDED\n\n#ifndef BOOST_SIMD_NO_NANS\n#include <boost/simd/function/is_nan.hpp>\n#endif\n#ifndef BOOST_SIMD_NO_INFINITIES\n#include <boost/simd/constant/inf.hpp>\n#endif\n#include <boost/simd/function/fast.hpp>\n#include <boost/simd/function/horn.hpp>\n#include <boost/simd/arch/common/detail/tags.hpp>\n#include <boost/simd/constant/half.hpp>\n#include <boost/simd/constant/invlog_10.hpp>\n#include <boost/simd/constant/invlog_2.hpp>\n#include <boost/simd/detail/constant/log_2hi.hpp>\n#include <boost/simd/detail/constant/log_2lo.hpp>\n#include <boost/simd/constant/log_2olog_10.hpp>\n#include <boost/simd/constant/minf.hpp>\n#include <boost/simd/constant/mone.hpp>\n#include <boost/simd/constant/sqrt_2o_2.hpp>\n#include <boost/simd/constant/two.hpp>\n#include <boost/simd/function/bitwise_and.hpp>\n#include <boost/simd/function/divides.hpp>\n#include <boost/simd/function/frexp.hpp>\n#include <boost/simd/function/genmask.hpp>\n#include <boost/simd/function/if_allbits_else.hpp>\n#include <boost/simd/function/if_else_zero.hpp>\n#include <boost/simd/function/is_equal.hpp>\n#include <boost/simd/function/is_eqz.hpp>\n#include <boost/simd/function/is_greater.hpp>\n#include <boost/simd/function/is_ltz.hpp>\n#include <boost/simd/function/logical_or.hpp>\n#include <boost/simd/function/minus.hpp>\n#include <boost/simd/function/dec.hpp>\n#include <boost/simd/function/multiplies.hpp>\n#include <boost/simd/function/plus.hpp>\n#include <boost/simd/function/if_plus.hpp>\n#include <boost/simd/function/sqr.hpp>\n#include <boost/simd/function/tofloat.hpp>\n#include <boost/simd/function/unary_minus.hpp>\n#include <tuple>\n\nnamespace boost { namespace simd\n{\n  namespace detail\n  {\n    namespace bd = boost::dispatch;\n\n    template < class A0 >\n    struct logarithm< A0, tag::not_simd_type, double>\n    {\n      static BOOST_FORCEINLINE void kernel_log(A0 a0,\n                                    A0& dk,\n                                    A0& hfsq,\n                                    A0& s,\n                                    A0& r,\n                                    A0& f) BOOST_NOEXCEPT\n      {\n        using i_t = bd::as_integer_t<A0, signed>;\n        A0 x;\n        i_t k;\n        std::tie(x, k) = fast_(frexp)(a0);\n        const i_t x_lt_sqrthf = (Sqrt_2o_2<A0>() > x) ? Mone<i_t>() : Zero<i_t>();\n        k += x_lt_sqrthf;\n        f = dec(x+bitwise_and(x, genmask(x_lt_sqrthf)));\n        dk = tofloat(k);\n        s = f/(Two<A0>()+f);\n        A0 z = sqr(s);\n        A0 w = sqr(z);\n        A0 t1= w*horn<A0,\n                      0x3fd999999997fa04ll,\n                      0x3fcc71c51d8e78afll,\n                      0x3fc39a09d078c69fll\n                      > (w);\n        A0 t2= z*horn<A0,\n                      0x3fe5555555555593ll,\n                      0x3fd2492494229359ll,\n                      0x3fc7466496cb03dell,\n                      0x3fc2f112df3e5244ll\n                      > (w);\n        r = t2+t1;\n        hfsq = Half<A0>()*sqr(f);\n      }\n\n      static BOOST_FORCEINLINE A0 log( A0 a0) BOOST_NOEXCEPT\n      {\n        // ln(2)hi  =  6.93147180369123816490e-01  or  0x3fe62e42fee00000\n        // ln(2)lo  =  1.90821492927058770002e-10  or  0x3dea39ef35793c76\n      #ifndef BOOST_SIMD_NO_INFINITIES\n        if (a0 == Inf<A0>()) return a0;\n      #endif\n      #ifdef BOOST_SIMD_NO_NANS\n        if (is_ltz(a0)) return Nan<A0>();\n      #else\n        if (is_nan(a0)||is_ltz(a0)) return Nan<A0>();\n      #endif\n        if (is_eqz(a0)) return Minf<A0>();\n        A0 dk, hfsq, s, R, f;\n        kernel_log(a0, dk, hfsq, s, R, f);\n        return  dk*Constant<A0, 0x3fe62e42fee00000ll>()-\n          ((hfsq-(s*(hfsq+R)+dk*Constant<A0, 0x3dea39ef35793c76ll>()))-f);\n      }\n\n      static BOOST_FORCEINLINE A0 log2(A0 a0) BOOST_NOEXCEPT\n      {\n      #ifndef BOOST_SIMD_NO_INFINITIES\n        if (a0 == Inf<A0>()) return a0;\n      #endif\n      #ifdef BOOST_SIMD_NO_NANS\n        if (is_ltz(a0)) return Nan<A0>();\n      #else\n        if (is_nan(a0)||is_ltz(a0)) return Nan<A0>();\n      #endif\n        if (is_eqz(a0)) return Minf<A0>();\n        A0 dk, hfsq, s, R, f;\n        kernel_log(a0, dk, hfsq, s, R, f);\n        return -(hfsq-(s*(hfsq+R))-f)*Invlog_2<A0>()+dk;\n      }\n\n      static BOOST_FORCEINLINE A0 log10(A0 a0) BOOST_NOEXCEPT\n      {\n      #ifndef BOOST_SIMD_NO_INFINITIES\n        if (a0 == Inf<A0>()) return a0;\n      #endif\n      #ifdef BOOST_SIMD_NO_NANS\n        if (is_ltz(a0)) return Nan<A0>();\n      #else\n        if (is_nan(a0)||is_ltz(a0)) return Nan<A0>();\n      #endif\n        if (is_eqz(a0)) return Minf<A0>();\n        A0 dk, hfsq, s, R, f;\n        kernel_log(a0, dk, hfsq, s, R, f);\n        return -(hfsq-(s*(hfsq+R))-f)*Invlog_10<A0>()+dk*Log_2olog_10<A0>();\n      }\n    };\n\n  }\n} }\n#endif\n", "meta": {"hexsha": "dc9f2fc1fc5f228a001f9b33551f3de20d6db1a7", "size": 5193, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/detail/scalar/d_log.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/scalar/d_log.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/scalar/d_log.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": 34.3907284768, "max_line_length": 100, "alphanum_fraction": 0.5832851916, "num_tokens": 1553, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933535169629, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.45143931939982845}}
{"text": "#include <CGAL/Advancing_front_surface_reconstruction.h>\n#include <CGAL/Aff_transformation_3.h>\n#include <CGAL/Alpha_shape_2.h>\n#include <CGAL/Alpha_shape_3.h>\n#include <CGAL/Alpha_shape_cell_base_3.h>\n#include <CGAL/Alpha_shape_face_base_2.h>\n#include <CGAL/Alpha_shape_vertex_base_2.h>\n#include <CGAL/Alpha_shape_vertex_base_3.h>\n#include <CGAL/Arr_conic_traits_2.h>\n#include <CGAL/Arr_polyline_traits_2.h>\n#include <CGAL/Arr_segment_traits_2.h>\n#include <CGAL/Arrangement_2.h>\n#include <CGAL/Boolean_set_operations_2.h>\n#include <CGAL/Bounded_kernel.h>\n#include <CGAL/CORE_algebraic_number_traits.h>\n#include <CGAL/Complex_2_in_triangulation_3.h>\n#include <CGAL/Delaunay_triangulation_2.h>\n#include <CGAL/Delaunay_triangulation_3.h>\n#include <CGAL/Exact_predicates_exact_constructions_kernel.h>\n#include <CGAL/Gps_traits_2.h>\n#include <CGAL/IO/facets_in_complex_2_to_triangle_mesh.h>\n#include <CGAL/IO/io.h>\n#include <CGAL/Implicit_surface_3.h>\n#include <CGAL/Labeled_mesh_domain_3.h>\n#include <CGAL/Mesh_complex_3_in_triangulation_3.h>\n#include <CGAL/Mesh_criteria_3.h>\n#include <CGAL/Mesh_triangulation_3.h>\n#include <CGAL/Polygon_2.h>\n#include <CGAL/Polygon_convex_decomposition_2.h>\n#include <CGAL/Polygon_mesh_processing/bbox.h>\n#include <CGAL/Polygon_mesh_processing/clip.h>\n#include <CGAL/Polygon_mesh_processing/corefinement.h>\n#include <CGAL/Polygon_mesh_processing/detect_features.h>\n#include <CGAL/Polygon_mesh_processing/extrude.h>\n#include <CGAL/Polygon_mesh_processing/orientation.h>\n#include <CGAL/Polygon_mesh_processing/polygon_mesh_to_polygon_soup.h>\n#include <CGAL/Polygon_mesh_processing/polygon_soup_to_polygon_mesh.h>\n#include <CGAL/Polygon_mesh_processing/random_perturbation.h>\n#include <CGAL/Polygon_mesh_processing/remesh.h>\n#include <CGAL/Polygon_mesh_processing/repair_polygon_soup.h>\n#include <CGAL/Polygon_mesh_processing/repair_self_intersections.h>\n#include <CGAL/Polygon_mesh_processing/smooth_mesh.h>\n#include <CGAL/Polygon_mesh_processing/smooth_shape.h>\n#include <CGAL/Polygon_mesh_processing/transform.h>\n#include <CGAL/Polygon_mesh_processing/triangulate_faces.h>\n#include <CGAL/Polygon_mesh_slicer.h>\n#include <CGAL/Polygon_triangulation_decomposition_2.h>\n#include <CGAL/Polygon_vertical_decomposition_2.h>\n#include <CGAL/Polygon_with_holes_2.h>\n#include <CGAL/Projection_traits_xy_3.h>\n#include <CGAL/Projection_traits_xz_3.h>\n#include <CGAL/Projection_traits_yz_3.h>\n#include <CGAL/Quotient.h>\n#include <CGAL/Simple_cartesian.h>\n#include <CGAL/Subdivision_method_3/subdivision_methods_3.h>\n#include <CGAL/Surface_mesh.h>\n#include <CGAL/Surface_mesh_default_triangulation_3.h>\n#include <CGAL/Surface_mesh_simplification/Policies/Edge_collapse/Count_ratio_stop_predicate.h>\n#include <CGAL/Surface_mesh_simplification/edge_collapse.h>\n#include <CGAL/Unique_hash_map.h>\n#include <CGAL/approximated_offset_2.h>\n#include <CGAL/boost/graph/Named_function_parameters.h>\n#include <CGAL/boost/graph/convert_nef_polyhedron_to_polygon_mesh.h>\n#include <CGAL/cartesian_homogeneous_conversion.h>\n#include <CGAL/convex_hull_3.h>\n#include <CGAL/create_offset_polygons_2.h>\n#include <CGAL/create_offset_polygons_from_polygon_with_holes_2.h>\n#include <CGAL/create_straight_skeleton_2.h>\n#include <CGAL/create_straight_skeleton_from_polygon_with_holes_2.h>\n#include <CGAL/exude_mesh_3.h>\n#include <CGAL/intersections.h>\n#include <CGAL/linear_least_squares_fitting_3.h>\n#include <CGAL/make_mesh_3.h>\n#include <CGAL/make_surface_mesh.h>\n#include <CGAL/minkowski_sum_2.h>\n#include <CGAL/minkowski_sum_3.h>\n#include <CGAL/offset_polygon_2.h>\n#include <CGAL/perturb_mesh_3.h>\n#include <emscripten/bind.h>\n\n#include <array>\n#include <boost/algorithm/string.hpp>\n#include <boost/algorithm/string/split.hpp>\n#include <boost/range/adaptor/reversed.hpp>\n#include <queue>\n\ntypedef CGAL::Exact_predicates_exact_constructions_kernel Kernel;\n\ntypedef Kernel::FT FT;\ntypedef Kernel::RT RT;\ntypedef Kernel::Line_3 Line;\ntypedef Kernel::Plane_3 Plane;\ntypedef Kernel::Point_2 Point_2;\ntypedef Kernel::Point_3 Point;\ntypedef Kernel::Segment_3 Segment;\ntypedef Kernel::Triangle_3 Triangle;\ntypedef Kernel::Vector_2 Vector_2;\ntypedef Kernel::Vector_3 Vector;\ntypedef Kernel::Direction_3 Direction;\ntypedef Kernel::Aff_transformation_3 Transformation;\ntypedef std::vector<Point> Points;\ntypedef std::vector<Point_2> Point_2s;\ntypedef CGAL::Surface_mesh<Point> Surface_mesh;\ntypedef Surface_mesh::Halfedge_index Halfedge_index;\ntypedef Surface_mesh::Face_index Face_index;\ntypedef Surface_mesh::Vertex_index Vertex_index;\ntypedef CGAL::Arr_segment_traits_2<Kernel> Traits_2;\ntypedef CGAL::Arrangement_2<Traits_2> Arrangement_2;\ntypedef Traits_2::X_monotone_curve_2 Segment_2;\n\ntypedef std::array<FT, 3> Triple;\ntypedef std::vector<Triple> Triples;\n\ntypedef std::array<double, 3> DoubleTriple;\ntypedef std::vector<DoubleTriple> DoubleTriples;\n\ntypedef std::array<FT, 4> Quadruple;\n\ntypedef std::vector<std::size_t> Polygon;\n\ntypedef CGAL::Exact_predicates_exact_constructions_kernel Kernel_2;\ntypedef CGAL::Polygon_2<Kernel_2> Polygon_2;\ntypedef CGAL::Polygon_with_holes_2<Kernel_2> Polygon_with_holes_2;\ntypedef CGAL::Straight_skeleton_2<Kernel_2> Straight_skeleton_2;\n\ntypedef CGAL::General_polygon_set_2<CGAL::Gps_segment_traits_2<Kernel>>\n    General_polygon_set_2;\n\nenum Status {\n  STATUS_OK = 0,\n  STATUS_EMPTY = 1,\n  STATUS_ZERO_THICKNESS = 2,\n};\n\nnamespace std {\n\ntemplate <typename K>\nstruct hash<CGAL::Plane_3<K>> {\n  std::size_t operator()(const CGAL::Plane_3<K>& plane) const {\n    // FIX: We can do better than this.\n    return 1;\n  }\n};\n\n}  // namespace std\n\n#ifndef TEST_ONLY\n\ndouble time_base = -1;\n\ndouble now(void) {\n  timeval t;\n  gettimeofday(&t, NULL);\n  double time = t.tv_sec + (t.tv_usec * 0.000001);\n  if (time_base == -1) {\n    time_base = time;\n  }\n  return time - time_base;\n}\n\nFT to_FT(const std::string& v) {\n  std::istringstream i(v);\n  FT ft;\n  i >> ft;\n  return ft;\n}\n\nFT to_FT(const double v) { return FT(v); }\n\nvoid Polygon__push_back(Polygon* polygon, std::size_t index) {\n  polygon->push_back(index);\n}\n\ntypedef std::vector<Polygon> Polygons;\n\nstruct Triple_array_traits {\n  struct Equal_3 {\n    bool operator()(const Triple& p, const Triple& q) const { return (p == q); }\n  };\n  struct Less_xyz_3 {\n    bool operator()(const Triple& p, const Triple& q) const {\n      return std::lexicographical_compare(p.begin(), p.end(), q.begin(),\n                                          q.end());\n    }\n  };\n  Equal_3 equal_3_object() const { return Equal_3(); }\n  Less_xyz_3 less_xyz_3_object() const { return Less_xyz_3(); }\n};\n\nconst Surface_mesh* FromPolygonSoupToSurfaceMesh(emscripten::val fill) {\n  Triples triples;\n  Polygons polygons;\n  // Workaround for emscripten::val() bindings.\n  Triples* triples_ptr = &triples;\n  Polygons* polygons_ptr = &polygons;\n  fill(triples_ptr, polygons_ptr);\n  CGAL::Polygon_mesh_processing::repair_polygon_soup(\n      triples, polygons, CGAL::parameters::geom_traits(Triple_array_traits()));\n  CGAL::Polygon_mesh_processing::orient_polygon_soup(triples, polygons);\n  Surface_mesh* mesh = new Surface_mesh();\n  CGAL::Polygon_mesh_processing::polygon_soup_to_polygon_mesh(triples, polygons,\n                                                              *mesh);\n  assert(CGAL::Polygon_mesh_processing::triangulate_faces(*mesh) == true);\n  // If a volume, ensure it is positive.\n  if (CGAL::is_closed(*mesh) &&\n      CGAL::Polygon_mesh_processing::volume(\n          *mesh, CGAL::parameters::all_default()) < 0) {\n    CGAL::Polygon_mesh_processing::reverse_face_orientations(*mesh);\n  }\n  return mesh;\n}\n\nvoid FromSurfaceMeshToPolygonSoup(const Surface_mesh* mesh,\n                                  const Transformation* transformation,\n                                  bool triangulate,\n                                  emscripten::val emit_polygon,\n                                  emscripten::val emit_point) {\n  if (triangulate) {\n    // Note: Destructive update.\n    Surface_mesh working_copy(*mesh);\n    CGAL::Polygon_mesh_processing::triangulate_faces(working_copy.faces(),\n                                                     working_copy);\n    return FromSurfaceMeshToPolygonSoup(&working_copy, transformation, false,\n                                        emit_polygon, emit_point);\n  }\n  Points points;\n  Polygons polygons;\n  CGAL::Polygon_mesh_processing::polygon_mesh_to_polygon_soup(*mesh, points,\n                                                              polygons);\n  for (const auto& polygon : polygons) {\n    emit_polygon();\n    for (const auto& index : polygon) {\n      const auto p = points[index].transform(*transformation);\n      emit_point(CGAL::to_double(p.x().exact()), CGAL::to_double(p.y().exact()),\n                 CGAL::to_double(p.z().exact()));\n    }\n  }\n}\n\nconst Surface_mesh* FromFunctionToSurfaceMesh(\n    double radius, double angular_bound, double radius_bound,\n    double distance_bound, double error_bound, emscripten::val function) {\n  typedef CGAL::Surface_mesh_default_triangulation_3 Tr;\n  // c2t3\n  typedef CGAL::Complex_2_in_triangulation_3<Tr> C2t3;\n  typedef Tr::Geom_traits GT;\n  typedef GT::Sphere_3 Sphere_3;\n  typedef GT::Point_3 Point_3;\n  typedef GT::FT FT;\n  typedef FT (*Function)(Point_3);\n  typedef CGAL::Implicit_surface_3<GT, Function> Surface_3;\n  typedef CGAL::Surface_mesh<Point_3> Epick_Surface_mesh;\n\n  Tr tr;          // 3D-Delaunay triangulation\n  C2t3 c2t3(tr);  // 2D-complex in 3D-Delaunay triangulation\n  // defining the surface\n  auto op = [&](const Point_3& p) {\n    return FT(function(CGAL::to_double(p.x()), CGAL::to_double(p.y()),\n                       CGAL::to_double(p.z()))\n                  .as<double>());\n  };\n  Surface_3 surface(\n      op,                                        // pointer to function\n      Sphere_3(CGAL::ORIGIN, radius * radius));  // bounding sphere\n  CGAL::Surface_mesh_default_criteria_3<Tr> criteria(\n      angular_bound,    // angular bound\n      radius_bound,     // radius bound\n      distance_bound);  // distance bound\n  // meshing surface\n  CGAL::make_surface_mesh(c2t3, surface, criteria, CGAL::Manifold_tag());\n  Epick_Surface_mesh epick_mesh;\n  CGAL::facets_in_complex_2_to_triangle_mesh(c2t3, epick_mesh);\n\n  Surface_mesh* epeck_mesh = new Surface_mesh();\n  copy_face_graph(epick_mesh, *epeck_mesh);\n  return epeck_mesh;\n}\n\nstruct TriangularSurfaceMeshBuilder {\n  typedef std::array<std::size_t, 3> Facet;\n\n  Surface_mesh& mesh;\n\n  template <typename PointIterator>\n  TriangularSurfaceMeshBuilder(Surface_mesh& mesh, PointIterator b,\n                               PointIterator e)\n      : mesh(mesh) {\n    for (; b != e; ++b) {\n      boost::graph_traits<Surface_mesh>::vertex_descriptor v;\n      v = add_vertex(mesh);\n      mesh.point(v) = *b;\n    }\n  }\n\n  TriangularSurfaceMeshBuilder& operator=(const Facet f) {\n    typedef boost::graph_traits<Surface_mesh>::vertex_descriptor\n        vertex_descriptor;\n    typedef boost::graph_traits<Surface_mesh>::vertices_size_type size_type;\n    mesh.add_face(vertex_descriptor(static_cast<size_type>(f[0])),\n                  vertex_descriptor(static_cast<size_type>(f[1])),\n                  vertex_descriptor(static_cast<size_type>(f[2])));\n    return *this;\n  }\n\n  TriangularSurfaceMeshBuilder& operator*() { return *this; }\n  TriangularSurfaceMeshBuilder& operator++() { return *this; }\n  TriangularSurfaceMeshBuilder operator++(int) { return *this; }\n};\n\nconst Surface_mesh* FromPointsToSurfaceMesh(emscripten::val fill_triples) {\n  Surface_mesh* mesh = new Surface_mesh();\n  std::vector<Triple> triples;\n  std::vector<Triple>* triples_ptr = &triples;\n  fill_triples(triples_ptr);\n  std::vector<Point> points;\n  for (const auto& triple : triples) {\n    points.emplace_back(Point{triple[0], triple[1], triple[2]});\n  }\n  TriangularSurfaceMeshBuilder builder(*mesh, points.begin(), points.end());\n  CGAL::advancing_front_surface_reconstruction(points.begin(), points.end(),\n                                               builder);\n  return mesh;\n}\n\nvoid FitPlaneToPoints(emscripten::val fill_triples,\n                      emscripten::val emit_plane) {\n  typedef CGAL::Epeck::Plane_3 Plane;\n  typedef CGAL::Epeck::Point_3 Point;\n  DoubleTriples triples;\n  std::vector<DoubleTriple>* triples_ptr = &triples;\n  fill_triples(triples_ptr);\n  std::vector<Point> points;\n  for (const auto& triple : triples) {\n    points.emplace_back(Point{triple[0], triple[1], triple[2]});\n  }\n  if (points.size() > 0) {\n    Plane plane;\n    linear_least_squares_fitting_3(points.begin(), points.end(), plane,\n                                   CGAL::Dimension_tag<0>());\n    // Prefer positive planes.\n    FT zly = CGAL::scalar_product(plane.orthogonal_vector(), Vector(0, 0, 1));\n    if (zly < 0) {\n      plane = plane.opposite();\n    } else {\n      FT xly = CGAL::scalar_product(plane.orthogonal_vector(), Vector(0, 1, 0));\n      if (xly < 0) {\n        plane = plane.opposite();\n      } else {\n        FT ylx =\n            CGAL::scalar_product(plane.orthogonal_vector(), Vector(1, 0, 0));\n        if (ylx < 0) {\n          plane = plane.opposite();\n        }\n      }\n    }\n    emit_plane(CGAL::to_double(plane.a()), CGAL::to_double(plane.b()),\n               CGAL::to_double(plane.c()), CGAL::to_double(plane.d()));\n  }\n}\n\nconst Surface_mesh* SubdivideSurfaceMesh(const Surface_mesh* input, int method,\n                                         int iterations) {\n  typedef boost::graph_traits<Surface_mesh>::edge_descriptor edge_descriptor;\n\n  Surface_mesh* mesh = new Surface_mesh(*input);\n\n  CGAL::Polygon_mesh_processing::triangulate_faces(*mesh);\n  switch (method) {\n    case 0:\n      CGAL::Subdivision_method_3::CatmullClark_subdivision(\n          *mesh,\n          CGAL::Polygon_mesh_processing::parameters::number_of_iterations(\n              iterations));\n      break;\n    // case 1:\n    //   CGAL::Subdivision_method_3::DooSabin_subdivision(*mesh,\n    //   CGAL::Polygon_mesh_processing::parameters::number_of_iterations(iterations));\n    //   break;\n    // case 2:\n    //  CGAL::Subdivision_method_3::DQQ(*mesh,\n    //  CGAL::Polygon_mesh_processing::parameters::number_of_iterations(iterations));\n    //  break;\n    case 3:\n      CGAL::Subdivision_method_3::Loop_subdivision(\n          *mesh,\n          CGAL::Polygon_mesh_processing::parameters::number_of_iterations(\n              iterations));\n      break;\n    // case 4:\n    //   CGAL::Subdivision_method_3::PQQ(*mesh,\n    //   CGAL::Polygon_mesh_processing::parameters::number_of_iterations(iterations));\n    //   break;\n    // case 5:\n    //   CGAL::Subdivision_method_3::PTQ(*mesh,\n    //   CGAL::Polygon_mesh_processing::parameters::number_of_iterations(iterations));\n    //   break;\n    // case 6:\n    //   CGAL::Subdivision_method_3::Sqrt3(*mesh,\n    //   CGAL::Polygon_mesh_processing::parameters::number_of_iterations(iterations));\n    //   break;\n    case 7:\n      CGAL::Subdivision_method_3::Sqrt3_subdivision(\n          *mesh,\n          CGAL::Polygon_mesh_processing::parameters::number_of_iterations(\n              iterations));\n      break;\n  }\n\n  return mesh;\n}\n\nconst Surface_mesh* ReverseFaceOrientationsOfSurfaceMesh(\n    const Surface_mesh* input, const Transformation* transformation) {\n  Surface_mesh* mesh = new Surface_mesh(*input);\n  CGAL::Polygon_mesh_processing::transform(*transformation, *mesh,\n                                           CGAL::parameters::all_default());\n  CGAL::Polygon_mesh_processing::reverse_face_orientations(mesh->faces(),\n                                                           *mesh);\n  return mesh;\n}\n\nbool IsBadSurfaceMesh(const Surface_mesh* input) {\n  Surface_mesh mesh(*input);\n  CGAL::Polygon_mesh_processing::triangulate_faces(mesh);\n  if (CGAL::Polygon_mesh_processing::does_self_intersect(\n          mesh, CGAL::parameters::all_default())) {\n    std::vector<std::pair<Surface_mesh::Face_index, Surface_mesh::Face_index>>\n        face_pairs;\n    CGAL::Polygon_mesh_processing::self_intersections(\n        mesh, std::back_inserter(face_pairs));\n    for (const auto& pair : face_pairs) {\n      std::cout << \"Intersection between: \" << pair.first << \" and \"\n                << pair.second << std::endl;\n    }\n    std::cout << std::setprecision(20) << mesh << std::endl;\n    return true;\n  }\n\n  for (const Vertex_index vertex : vertices(mesh)) {\n    if (CGAL::Polygon_mesh_processing::is_non_manifold_vertex(vertex, mesh)) {\n      std::cout << \"Non-manifold vertex \" << vertex << std::endl;\n      return true;\n    }\n  }\n\n  return false;\n}\n\nconst Surface_mesh* RemeshSurfaceMesh(const Surface_mesh* input,\n                                      emscripten::val get_length) {\n  typedef boost::graph_traits<Surface_mesh>::edge_descriptor edge_descriptor;\n\n  Surface_mesh* mesh = new Surface_mesh(*input);\n\n  CGAL::Polygon_mesh_processing::triangulate_faces(*mesh);\n\n  double edge_length;\n\n  while (edge_length = get_length().as<double>(), edge_length > 0) {\n    CGAL::Polygon_mesh_processing::split_long_edges(edges(*mesh), edge_length,\n                                                    *mesh);\n  }\n\n  return mesh;\n}\n\nconst Surface_mesh* TransformSurfaceMesh(const Surface_mesh* input, double m00,\n                                         double m01, double m02, double m03,\n                                         double m10, double m11, double m12,\n                                         double m13, double m20, double m21,\n                                         double m22, double m23, double hw) {\n  Surface_mesh* output = new Surface_mesh(*input);\n  CGAL::Polygon_mesh_processing::transform(\n      Transformation(FT(m00), FT(m01), FT(m02), FT(m03), FT(m10), FT(m11),\n                     FT(m12), FT(m13), FT(m20), FT(m21), FT(m22), FT(m23),\n                     FT(hw)),\n      *output, CGAL::parameters::all_default());\n  return output;\n}\n\nconst Surface_mesh* TransformSurfaceMeshByTransform(\n    const Surface_mesh* input, const Transformation* transform) {\n  Surface_mesh* output = new Surface_mesh(*input);\n  CGAL::Polygon_mesh_processing::transform(*transform, *output,\n                                           CGAL::parameters::all_default());\n  return output;\n}\n\nvoid compute_degrees(double a, RT& sin_alpha, RT& cos_alpha, RT& w) {\n  // Convert angle to radians.\n  double radians = a * M_PI / 180.0;\n  CGAL::rational_rotation_approximation(radians, sin_alpha, cos_alpha, w, RT(1),\n                                        RT(1000));\n}\n\nvoid compute_turn(double turn, RT& sin_alpha, RT& cos_alpha, RT& w) {\n  // Convert angle to radians.\n  double radians = turn * 2 * CGAL_PI;\n  CGAL::rational_rotation_approximation(radians, sin_alpha, cos_alpha, w, RT(1),\n                                        RT(1000));\n}\n\nconst Surface_mesh* BendSurfaceMesh(const Surface_mesh* input,\n                                    const Transformation* transform,\n                                    double referenceRadius) {\n  Surface_mesh* c = new Surface_mesh(*input);\n  CGAL::Polygon_mesh_processing::transform(*transform, *c,\n                                           CGAL::parameters::all_default());\n  CGAL::Polygon_mesh_processing::triangulate_faces(*c);\n\n  const FT referencePerimeterMm = 2 * CGAL_PI * referenceRadius;\n  const FT referenceRadiansPerMm = 2 / referencePerimeterMm;\n\n  // This does not look very efficient.\n  // CHECK: Figure out deformations.\n  for (const Surface_mesh::Vertex_index vertex : c->vertices()) {\n    if (c->is_removed(vertex)) {\n      continue;\n    }\n    Point& point = c->point(vertex);\n    const FT lx = point.x();\n    const FT ly = point.y();\n    const FT radius = ly;\n    // At the radius, perimeter mm should be a full turn.\n    // const FT perimeterMm = 2 * CGAL_PI * radius;\n    // const FT radiansPerMm = 2 / perimeterMm;\n    const FT radiansPerMm = referenceRadiansPerMm;\n    const FT radians = (0.50 * CGAL_PI) - (lx * radiansPerMm * CGAL_PI);\n    RT sin_alpha, cos_alpha, w;\n    CGAL::rational_rotation_approximation(CGAL::to_double(radians.exact()),\n                                          sin_alpha, cos_alpha, w, RT(1),\n                                          RT(1000));\n    const FT cx = (cos_alpha * radius) / w;\n    const FT cy = (sin_alpha * radius) / w;\n    point = Point(cx, cy, point.z());\n  }\n\n  // Ensure that it is still a positive volume.\n  if (CGAL::Polygon_mesh_processing::volume(\n          *c, CGAL::parameters::all_default()) < 0) {\n    CGAL::Polygon_mesh_processing::reverse_face_orientations(*c);\n  }\n\n  // Self intersections need to be handled by the caller.\n\n  return c;\n}\n\nconst Surface_mesh* TwistSurfaceMesh(const Surface_mesh* input,\n                                     const Transformation* transform,\n                                     double turnsPerMm) {\n  Surface_mesh* c = new Surface_mesh(*input);\n  CGAL::Polygon_mesh_processing::transform(*transform, *c,\n                                           CGAL::parameters::all_default());\n  CGAL::Polygon_mesh_processing::triangulate_faces(*c);\n\n  // This does not look very efficient.\n  // CHECK: Figure out deformations.\n  for (const Surface_mesh::Vertex_index vertex : c->vertices()) {\n    if (c->is_removed(vertex)) {\n      continue;\n    }\n    Point& point = c->point(vertex);\n    FT radians = CGAL::to_double(point.z()) * turnsPerMm * CGAL_PI;\n    RT sin_alpha, cos_alpha, w;\n    CGAL::rational_rotation_approximation(CGAL::to_double(radians.exact()),\n                                          sin_alpha, cos_alpha, w, RT(1),\n                                          RT(1000));\n    Transformation transformation(cos_alpha, sin_alpha, 0, 0, -sin_alpha,\n                                  cos_alpha, 0, 0, 0, 0, w, 0, w);\n    point = point.transform(transformation);\n  }\n  return c;\n}\n\nconst Surface_mesh* TaperSurfaceMesh(const Surface_mesh* input,\n                                     const Transformation* transform,\n                                     double xPlusFactor, double xMinusFactor,\n                                     double yPlusFactor, double yMinusFactor) {\n  const double kMinimumTaper = 0.01;\n  Surface_mesh* c = new Surface_mesh(*input);\n  CGAL::Polygon_mesh_processing::transform(*transform, *c,\n                                           CGAL::parameters::all_default());\n  CGAL::Polygon_mesh_processing::triangulate_faces(*c);\n\n  // This does not look very efficient.\n  // CHECK: Figure out deformations.\n  for (const Surface_mesh::Vertex_index vertex : c->vertices()) {\n    if (c->is_removed(vertex)) {\n      continue;\n    }\n    Point& point = c->point(vertex);\n    FT xFactor = 1.0 + point.z() * (point.x() > 0 ? xPlusFactor : xMinusFactor);\n    if (xFactor < kMinimumTaper) {\n      xFactor = kMinimumTaper;\n    }\n    FT yFactor = 1.0 + point.z() * (point.y() > 0 ? yPlusFactor : yMinusFactor);\n    if (yFactor < kMinimumTaper) {\n      yFactor = kMinimumTaper;\n    }\n    point = Point(point.x() * xFactor, point.y() * yFactor, point.z());\n  }\n  return c;\n}\n\nVector unitVector(const Vector& vector);\nVector NormalOfSurfaceMeshFacet(const Surface_mesh& mesh, Face_index facet);\n\nconst Surface_mesh* PushSurfaceMesh(const Surface_mesh* input,\n                                    const Transformation* transform,\n                                    double force, double minimum_distance,\n                                    double scale) {\n  Surface_mesh* c = new Surface_mesh(*input);\n  CGAL::Polygon_mesh_processing::transform(*transform, *c,\n                                           CGAL::parameters::all_default());\n  Point origin(0, 0, 0);\n  for (Surface_mesh::Vertex_index vertex : c->vertices()) {\n    if (c->is_removed(vertex)) {\n      continue;\n    }\n    Point& point = c->point(vertex);\n    Vector vector = Vector(point, origin);\n    FT distance2 = vector.squared_length();\n    point += unitVector(vector) * force / distance2;\n  }\n  return c;\n}\n\n// Use different iota to avoid 45 degree slides.\nconst double kIotaX = 10e-5;\nconst double kIotaY = 11e-5;\nconst double kIotaZ = 12e-5;\n\nvoid DestructiveDifferenceOfSurfaceMeshes(Surface_mesh& a, Surface_mesh& b,\n                                          bool check) {\n  double x = 0, y = 0, z = 0;\n  for (int shift = 0x17;; shift++) {\n    if (x != 0 || y != 0 || z != 0) {\n      std::cout << \"Note: Shifting difference by x=\" << x << \" y=\" << y\n                << \" z=\" << z << std::endl;\n      Transformation translation(CGAL::TRANSLATION, Vector(x, y, z));\n      CGAL::Polygon_mesh_processing::transform(translation, a,\n                                               CGAL::parameters::all_default());\n    }\n    if (check) {\n      if (CGAL::Polygon_mesh_processing::corefine_and_compute_difference(\n              a, b, a,\n              CGAL::Polygon_mesh_processing::parameters::\n                  throw_on_self_intersection(true),\n              CGAL::Polygon_mesh_processing::parameters::\n                  throw_on_self_intersection(true),\n              CGAL::Polygon_mesh_processing::parameters::\n                  throw_on_self_intersection(true))) {\n        break;\n      }\n    } else {\n      if (CGAL::Polygon_mesh_processing::corefine_and_compute_difference(\n              a, b, a, CGAL::parameters::all_default(),\n              CGAL::parameters::all_default(),\n              CGAL::parameters::all_default())) {\n        break;\n      }\n    }\n    const double direction = ((shift & (1 << 3)) ? -1 : 1) * (shift >> 4);\n    if (shift & (1 << 0)) {\n      x = kIotaX * direction;\n    } else {\n      x = 0;\n    }\n    if (shift & (1 << 1)) {\n      y = kIotaY * direction;\n    } else {\n      y = 0;\n    }\n    if (shift & (1 << 2)) {\n      z = kIotaZ * direction;\n    } else {\n      z = 0;\n    }\n  }\n}\n\nvoid DestructiveUnionOfSurfaceMeshes(Surface_mesh& a, Surface_mesh& b,\n                                     bool check) {\n  double x = 0, y = 0, z = 0;\n  for (int shift = 0x11;; shift++) {\n    if (x != 0 || y != 0 || z != 0) {\n      std::cout << \"Note: Shifting difference by x=\" << x << \" y=\" << y\n                << \" z=\" << z << std::endl;\n      Transformation translation(CGAL::TRANSLATION, Vector(x, y, z));\n      CGAL::Polygon_mesh_processing::transform(translation, a,\n                                               CGAL::parameters::all_default());\n    }\n    if (check) {\n      if (CGAL::Polygon_mesh_processing::corefine_and_compute_union(\n              a, b, a,\n              CGAL::Polygon_mesh_processing::parameters::\n                  throw_on_self_intersection(true),\n              CGAL::Polygon_mesh_processing::parameters::\n                  throw_on_self_intersection(true),\n              CGAL::Polygon_mesh_processing::parameters::\n                  throw_on_self_intersection(true))) {\n        break;\n      }\n    } else {\n      if (CGAL::Polygon_mesh_processing::corefine_and_compute_union(\n              a, b, a, CGAL::parameters::all_default(),\n              CGAL::parameters::all_default(),\n              CGAL::parameters::all_default())) {\n        break;\n      }\n    }\n    const double direction = ((shift & (1 << 3)) ? -1 : 1) * (shift >> 4);\n    if (shift & (1 << 0)) {\n      x = kIotaX * direction;\n    } else {\n      x = 0;\n    }\n    if (shift & (1 << 1)) {\n      y = kIotaY * direction;\n    } else {\n      y = 0;\n    }\n    if (shift & (1 << 2)) {\n      z = kIotaZ * direction;\n    } else {\n      z = 0;\n    }\n  }\n}\n\nconst Surface_mesh* GrowSurfaceMesh(const Surface_mesh* input, double amount) {\n  Surface_mesh* mesh = new Surface_mesh(*input);\n  std::unordered_map<Surface_mesh::Vertex_index, Point> grown_points;\n\n  for (const Surface_mesh::Vertex_index vertex : mesh->vertices()) {\n    Vector unit_vertex_normal =\n        CGAL::Polygon_mesh_processing::compute_vertex_normal(\n            vertex, *mesh, CGAL::parameters::all_default());\n    grown_points[vertex] = mesh->point(vertex) + unit_vertex_normal * amount;\n  }\n\n  for (const Surface_mesh::Vertex_index vertex : mesh->vertices()) {\n    mesh->point(vertex) = grown_points[vertex];\n  }\n\n  return mesh;\n}\n\nSurface_mesh* SimplifySurfaceMesh(const Surface_mesh* input, double ratio) {\n  typedef CGAL::Simple_cartesian<double> Cartesian_kernel;\n  typedef Cartesian_kernel::Point_3 Cartesian_point;\n  typedef CGAL::Surface_mesh<Cartesian_point> Cartesian_surface_mesh;\n\n  Cartesian_surface_mesh cartesian_surface_mesh;\n  copy_face_graph(*input, cartesian_surface_mesh);\n  CGAL::Surface_mesh_simplification::Count_ratio_stop_predicate<\n      Cartesian_surface_mesh>\n      stop(ratio);\n  int removed_edge_count = CGAL::Surface_mesh_simplification::edge_collapse(\n      cartesian_surface_mesh, stop);\n\n  Surface_mesh* output = new Surface_mesh();\n  copy_face_graph(cartesian_surface_mesh, *output);\n\n  return output;\n}\n\nconst Surface_mesh* RemoveSelfIntersectionsOfSurfaceMesh(\n    const Surface_mesh* input) {\n  Surface_mesh* mesh = new Surface_mesh(*input);\n  CGAL::Polygon_mesh_processing::experimental::\n      autorefine_and_remove_self_intersections(*mesh);\n  return mesh;\n}\n\nvoid Surface_mesh__EachFace(const Surface_mesh* mesh, emscripten::val op) {\n  for (const auto& face_index : mesh->faces()) {\n    if (!mesh->is_removed(face_index)) {\n      op(std::size_t(face_index));\n    }\n  }\n}\n\nvoid addTriple(Triples* triples, double x, double y, double z) {\n  triples->emplace_back(Triple{x, y, z});\n}\n\nvoid addDoubleTriple(DoubleTriples* triples, double x, double y, double z) {\n  triples->emplace_back(DoubleTriple{x, y, z});\n}\n\nvoid fillQuadruple(Quadruple* q, double x, double y, double z, double w) {\n  (*q)[0] = to_FT(x);\n  (*q)[1] = to_FT(y);\n  (*q)[2] = to_FT(z);\n  (*q)[3] = to_FT(w);\n}\n\nvoid fillExactQuadruple(Quadruple* q, const std::string& a,\n                        const std::string& b, const std::string& c,\n                        const std::string& d) {\n  (*q)[0] = to_FT(a);\n  (*q)[1] = to_FT(b);\n  (*q)[2] = to_FT(c);\n  (*q)[3] = to_FT(d);\n}\n\nvoid addPoint(Points* points, double x, double y, double z) {\n  points->emplace_back(Point{x, y, z});\n}\n\nvoid addExactPoint(Points* points, const std::string& x, const std::string& y,\n                   const std::string& z) {\n  points->emplace_back(Point{to_FT(x), to_FT(y), to_FT(z)});\n}\n\nvoid addPoint_2(Point_2s* points, double x, double y) {\n  points->emplace_back(Point_2{x, y});\n}\n\nstd::size_t Surface_mesh__halfedge_to_target(const Surface_mesh* mesh,\n                                             std::size_t halfedge_index) {\n  return std::size_t(mesh->target(Halfedge_index(halfedge_index)));\n}\n\nstd::size_t Surface_mesh__halfedge_to_face(const Surface_mesh* mesh,\n                                           std::size_t halfedge_index) {\n  return std::size_t(mesh->face(Halfedge_index(halfedge_index)));\n}\n\nstd::size_t Surface_mesh__halfedge_to_next_halfedge(\n    const Surface_mesh* mesh, std::size_t halfedge_index) {\n  return std::size_t(mesh->next(Halfedge_index(halfedge_index)));\n}\n\nstd::size_t Surface_mesh__halfedge_to_prev_halfedge(\n    const Surface_mesh* mesh, std::size_t halfedge_index) {\n  return std::size_t(mesh->prev(Halfedge_index(halfedge_index)));\n}\n\nstd::size_t Surface_mesh__halfedge_to_opposite_halfedge(\n    const Surface_mesh* mesh, std::size_t halfedge_index) {\n  return std::size_t(mesh->opposite(Halfedge_index(halfedge_index)));\n}\n\nstd::size_t Surface_mesh__vertex_to_halfedge(const Surface_mesh* mesh,\n                                             std::size_t vertex_index) {\n  return std::size_t(mesh->halfedge(Vertex_index(vertex_index)));\n}\n\nstd::size_t Surface_mesh__face_to_halfedge(const Surface_mesh* mesh,\n                                           std::size_t face_index) {\n  return std::size_t(mesh->halfedge(Face_index(face_index)));\n}\n\nconst Point& Surface_mesh__vertex_to_point(const Surface_mesh* mesh,\n                                           std::size_t vertex_index) {\n  return mesh->point(Vertex_index(vertex_index));\n}\n\nconst std::size_t Surface_mesh__add_exact(Surface_mesh* mesh, std::string x,\n                                          std::string y, std::string z) {\n  std::size_t index(mesh->add_vertex(Point{to_FT(x), to_FT(y), to_FT(z)}));\n  assert(index == std::size_t(Vertex_index(index)));\n  return index;\n}\n\nconst std::size_t Surface_mesh__add_vertex(Surface_mesh* mesh, float x, float y,\n                                           float z) {\n  std::size_t index(mesh->add_vertex(Point{x, y, z}));\n  assert(index == std::size_t(Vertex_index(index)));\n  return index;\n}\n\nconst std::size_t Surface_mesh__add_face(Surface_mesh* mesh) {\n  std::size_t index(mesh->add_face());\n  assert(index == std::size_t(Face_index(index)));\n  return index;\n}\n\nconst std::size_t Surface_mesh__add_face_vertices(Surface_mesh* mesh,\n                                                  emscripten::val next_vertex) {\n  std::vector<Vertex_index> vertices;\n  for (;;) {\n    Vertex_index vertex(next_vertex().as<std::size_t>());\n    if (!vertices.empty()) {\n      if (vertex == vertices[0]) {\n        break;\n      } else if (vertex == vertices.back()) {\n        std::cout << \"Duplicate vertex in add face.\" << std::endl;\n        continue;\n      }\n    }\n    vertices.push_back(vertex);\n  }\n  if (vertices.size() < 3) {\n    return -1;\n  } else {\n    auto facet = mesh->add_face(vertices);\n    if (!mesh->is_valid(facet)) {\n      std::cout << \"Invalid face\" << facet << std::endl;\n      return -1;\n    }\n    const auto facet_normal =\n        CGAL::Polygon_mesh_processing::compute_face_normal(facet, *mesh);\n    if (facet_normal == CGAL::NULL_VECTOR) {\n      std::cout << \"Adding degenerate face/facet\" << facet << std::endl;\n      std::cout << \"Adding degenerate face/mesh\" << *mesh << std::endl;\n      return -1;\n    }\n    std::size_t index(facet);\n    std::vector<Surface_mesh::Face_index> degenerate_faces;\n    CGAL::Polygon_mesh_processing::degenerate_faces(\n        mesh->faces(), *mesh, std::back_inserter(degenerate_faces));\n    if (degenerate_faces.size() > 0) {\n      for (const Surface_mesh::Face_index face : degenerate_faces) {\n        std::cout << \"Degenerate face\" << face << std::endl;\n      }\n      return -1;\n    }\n    if (CGAL::Polygon_mesh_processing::face_area(facet, *mesh) == 0) {\n      std::cout << \"Zero area face:\" << facet << std::endl;\n      return -1;\n    }\n    return index;\n  }\n}\n\nconst std::size_t Surface_mesh__add_edge(Surface_mesh* mesh) {\n  std::size_t index(mesh->add_edge());\n  assert(index == std::size_t(Halfedge_index(index)));\n  return index;\n}\n\nvoid Surface_mesh__set_edge_target(Surface_mesh* mesh, std::size_t edge,\n                                   std::size_t target) {\n  mesh->set_target(Halfedge_index(edge), Vertex_index(target));\n}\n\nvoid Surface_mesh__set_edge_next(Surface_mesh* mesh, std::size_t edge,\n                                 std::size_t next) {\n  mesh->set_next(Halfedge_index(edge), Halfedge_index(next));\n}\n\nvoid Surface_mesh__set_edge_face(Surface_mesh* mesh, std::size_t edge,\n                                 std::size_t face) {\n  mesh->set_face(Halfedge_index(edge), Face_index(face));\n}\n\nvoid Surface_mesh__set_face_edge(Surface_mesh* mesh, std::size_t face,\n                                 std::size_t edge) {\n  mesh->set_halfedge(Face_index(face), Halfedge_index(edge));\n}\n\nvoid Surface_mesh__set_vertex_edge(Surface_mesh* mesh, std::size_t face,\n                                   std::size_t edge) {\n  mesh->set_halfedge(Vertex_index(face), Halfedge_index(edge));\n}\n\nvoid Surface_mesh__set_vertex_halfedge_to_border_halfedge(Surface_mesh* mesh,\n                                                          std::size_t edge) {\n  return mesh->set_vertex_halfedge_to_border_halfedge(Halfedge_index(edge));\n}\n\nvoid Surface_mesh__collect_garbage(Surface_mesh* mesh) {\n  mesh->collect_garbage();\n}\n\ntemplate <typename MAP>\nstruct Project {\n  Project(MAP map, Vector vector) : map(map), vector(vector) {}\n\n  template <typename VD, typename T>\n  void operator()(const T&, VD vd) const {\n    put(map, vd, get(map, vd) + vector);\n  }\n\n  MAP map;\n  Vector vector;\n};\n\nPlane unitPlane(const Plane& p) {\n  Vector normal = p.orthogonal_vector();\n  // We can handle the axis aligned planes exactly.\n  if (normal.direction() == Vector(0, 0, 1).direction()) {\n    return Plane(p.point(), Vector(0, 0, 1));\n  } else if (normal.direction() == Vector(0, 0, -1).direction()) {\n    return Plane(p.point(), Vector(0, 0, -1));\n  } else if (normal.direction() == Vector(0, 1, 0).direction()) {\n    return Plane(p.point(), Vector(0, 1, 0));\n  } else if (normal.direction() == Vector(0, -1, 0).direction()) {\n    return Plane(p.point(), Vector(0, -1, 0));\n  } else if (normal.direction() == Vector(1, 0, 0).direction()) {\n    return Plane(p.point(), Vector(1, 0, 0));\n  } else if (normal.direction() == Vector(-1, 0, 0).direction()) {\n    return Plane(p.point(), Vector(-1, 0, 0));\n  } else {\n    // But the general case requires an approximation.\n    Vector unit_normal =\n        normal / CGAL_NTS approximate_sqrt(normal.squared_length());\n    return Plane(p.point(), unit_normal);\n  }\n}\n\nVector unitVector(const Vector& vector) {\n  // We can handle the axis aligned planes exactly.\n  if (vector.direction() == Vector(0, 0, 1).direction()) {\n    return Vector(0, 0, 1);\n  } else if (vector.direction() == Vector(0, 0, -1).direction()) {\n    return Vector(0, 0, -1);\n  } else if (vector.direction() == Vector(0, 1, 0).direction()) {\n    return Vector(0, 1, 0);\n  } else if (vector.direction() == Vector(0, -1, 0).direction()) {\n    return Vector(0, -1, 0);\n  } else if (vector.direction() == Vector(1, 0, 0).direction()) {\n    return Vector(1, 0, 0);\n  } else if (vector.direction() == Vector(-1, 0, 0).direction()) {\n    return Vector(-1, 0, 0);\n  } else {\n    // But the general case requires an approximation.\n    Vector unit_vector =\n        vector / CGAL_NTS approximate_sqrt(vector.squared_length());\n    return unit_vector;\n  }\n}\n\nPlane PlaneOfSurfaceMeshFacet(const Surface_mesh& mesh, Face_index facet) {\n  const auto h = mesh.halfedge(facet);\n  const Plane plane(mesh.point(mesh.source(h)),\n                    mesh.point(mesh.source(mesh.next(h))),\n                    mesh.point(mesh.source(mesh.next(mesh.next(h)))));\n  return plane;\n}\n\nbool SomePlaneOfSurfaceMesh(Plane& plane, const Surface_mesh& mesh) {\n  for (const auto& facet : mesh.faces()) {\n    plane = PlaneOfSurfaceMeshFacet(mesh, facet);\n    return true;\n  }\n  return false;\n}\n\nVector NormalOfSurfaceMeshFacet(const Surface_mesh& mesh, Face_index facet) {\n  const auto h = mesh.halfedge(facet);\n  return CGAL::normal(mesh.point(mesh.source(h)),\n                      mesh.point(mesh.source(mesh.next(h))),\n                      mesh.point(mesh.source(mesh.next(mesh.next(h)))));\n}\n\nVector SomeNormalOfSurfaceMesh(const Surface_mesh& mesh) {\n  for (const auto& facet : mesh.faces()) {\n    return NormalOfSurfaceMeshFacet(mesh, facet);\n  }\n  return CGAL::NULL_VECTOR;\n}\n\nclass SurfaceMeshAndTransform {\n public:\n  SurfaceMeshAndTransform() : fill_(nullptr){};\n  SurfaceMeshAndTransform(emscripten::val* fill) : fill_(fill){};\n\n  emscripten::val* fill_;\n  const Surface_mesh* mesh_;\n  const Transformation* transform_;\n\n  void set_mesh(const Surface_mesh* mesh) { mesh_ = mesh; }\n  void set_transform(const Transformation* transform) {\n    transform_ = transform;\n  }\n  bool fill(const Surface_mesh*& mesh, const Transformation*& transform) {\n    SurfaceMeshAndTransform* self = this;\n    if ((*fill_)(self).as<bool>()) {\n      mesh = mesh_;\n      transform = transform_;\n      return true;\n    } else {\n      return false;\n    }\n  }\n};\n\nconst Surface_mesh* LoftBetweenCongruentSurfaceMeshes(bool closed,\n                                                      emscripten::val fill) {\n  SurfaceMeshAndTransform admit(&fill);\n\n  const Surface_mesh* a;\n  const Surface_mesh* b;\n  const Transformation* a_transform;\n  const Transformation* b_transform;\n\n  if (!admit.fill(a, a_transform) || !admit.fill(b, b_transform)) {\n    return nullptr;\n  }\n\n  Surface_mesh* loft = new Surface_mesh();\n  const Surface_mesh* base = a;\n\n  std::unordered_map<Vertex_index, Vertex_index> base_map;\n  std::unordered_map<Vertex_index, Vertex_index> a_map;\n  std::unordered_map<Vertex_index, Vertex_index> b_map;\n\n  // Build the base of the wall.\n  for (const auto h : a->halfedges()) {\n    if (a->is_border(h)) {\n      auto a_source = a->source(h);\n      a_map[a_source] =\n          loft->add_vertex(a->point(a_source).transform(*a_transform));\n    }\n  }\n\n  if (closed) {\n    base = a;\n    base_map = a_map;\n  } else {\n    // Build the lower cap.\n    for (auto face : a->faces()) {\n      std::vector<Vertex_index> loft_vertices;\n      Halfedge_index start = a->halfedge(face);\n      Halfedge_index h = start;\n      do {\n        Vertex_index a_vertex = a->source(h);\n        auto a_vertex_it = a_map.find(a_vertex);\n        Vertex_index loft_vertex;\n        if (a_vertex_it == a_map.end()) {\n          loft_vertex =\n              loft->add_vertex(a->point(a_vertex).transform(*a_transform));\n          a_map[a_vertex] = loft_vertex;\n        } else {\n          loft_vertex = a_vertex_it->second;\n        }\n        loft_vertices.push_back(loft_vertex);\n        // Walk backward, so that the face is reversed.\n        h = a->prev(h);\n      } while (h != start);\n      loft->add_face(loft_vertices);\n    }\n  }\n\n  bool closing = false;\n\n  // Extend the wall, step by step.\n  for (;;) {\n    std::vector<Halfedge_index> base_edges;\n    for (const auto h : a->halfedges()) {\n      base_edges.push_back(h);\n    }\n    for (const auto h : base_edges) {\n      if (a->is_border(h)) {\n        auto a_source = a->source(h);\n        auto b_source_it = b_map.find(a_source);\n        Vertex_index b_source;\n        if (b_source_it == b_map.end()) {\n          b_source =\n              loft->add_vertex(b->point(a_source).transform(*b_transform));\n          b_map[a_source] = b_source;\n        } else {\n          b_source = b_source_it->second;\n        }\n        auto a_target = a->target(h);\n        auto b_target_it = b_map.find(a_target);\n        Vertex_index b_target;\n        if (b_target_it == b_map.end()) {\n          b_target =\n              loft->add_vertex(b->point(a_target).transform(*b_transform));\n          b_map[a_target] = b_target;\n        } else {\n          b_target = b_target_it->second;\n        }\n        auto face = loft->add_face(b_target, a_map[a_target], a_map[a_source],\n                                   b_source);\n      }\n    }\n\n    const Surface_mesh* next;\n    if (closing) {\n      // We just finished closing off the final walls.\n      break;\n    } else if (admit.fill(next, b_transform)) {\n      // Continue with the next wall.\n      a = b;\n      b = next;\n      a_map = b_map;\n      b_map.clear();\n      continue;\n    } else if (closed) {\n      // We need to build a wall back to the base.\n      a = b;\n      b = base;\n      a_map = b_map;\n      b_map = base_map;\n      closing = true;\n      continue;\n    } else {\n      // Build the upper cap.\n      for (auto face : b->faces()) {\n        std::vector<Vertex_index> loft_vertices;\n        Halfedge_index start = b->halfedge(face);\n        Halfedge_index h = start;\n        do {\n          Vertex_index b_vertex = b->source(h);\n          auto b_vertex_it = b_map.find(b_vertex);\n          Vertex_index loft_vertex;\n          if (b_vertex_it == b_map.end()) {\n            loft_vertex =\n                loft->add_vertex(b->point(b_vertex).transform(*b_transform));\n            b_map[b_vertex] = loft_vertex;\n          } else {\n            loft_vertex = b_vertex_it->second;\n          }\n          loft_vertices.push_back(loft_vertex);\n          h = b->next(h);\n        } while (h != start);\n        loft->add_face(loft_vertices);\n      }\n      break;\n    }\n  }\n\n  CGAL::Polygon_mesh_processing::triangulate_faces(*loft);\n  return loft;\n}\n\nclass SurfaceMeshQuery {\n  typedef CGAL::AABB_face_graph_triangle_primitive<Surface_mesh> Primitive;\n  typedef CGAL::AABB_traits<Kernel, Primitive> Traits;\n  typedef CGAL::AABB_tree<Traits> Tree;\n  typedef boost::optional<Tree::Intersection_and_primitive_id<Point>::Type>\n      Point_intersection;\n  typedef boost::optional<Tree::Intersection_and_primitive_id<Segment>::Type>\n      Segment_intersection;\n  typedef CGAL::Side_of_triangle_mesh<Surface_mesh, Kernel> Inside_tester;\n\n public:\n  SurfaceMeshQuery(const Surface_mesh* mesh,\n                   const Transformation* transformation) {\n    mesh_.reset(new Surface_mesh(*mesh));\n    CGAL::Polygon_mesh_processing::transform(*transformation, *mesh_,\n                                             CGAL::parameters::all_default());\n    tree_.reset(new Tree(faces(*mesh_).first, faces(*mesh_).second, *mesh_));\n    inside_tester_.reset(new Inside_tester(*tree_));\n  }\n\n  bool isIntersectingPointApproximate(double x, double y, double z) {\n    return (*inside_tester_)(Point(x, y, z)) == CGAL::ON_BOUNDED_SIDE;\n  }\n\n  void clipSegmentApproximate(double source_x, double source_y, double source_z,\n                              double target_x, double target_y, double target_z,\n                              emscripten::val emit_segment) {\n    const Point source(source_x, source_y, source_z);\n    const Point target(target_x, target_y, target_z);\n    Segment segment_query(source, target);\n    std::list<Segment_intersection> intersections;\n    tree_->all_intersections(segment_query, std::back_inserter(intersections));\n    // Handle pointwise intersections -- through faces.\n    std::vector<Point> points;\n    if ((*inside_tester_)(source) == CGAL::ON_BOUNDED_SIDE) {\n      // The segment starts inside the volume.\n      points.push_back(source);\n      points.push_back(source);\n    }\n    if ((*inside_tester_)(target) == CGAL::ON_BOUNDED_SIDE) {\n      // The segment ends inside the volume.\n      points.push_back(target);\n      points.push_back(target);\n    }\n    for (const auto& intersection : intersections) {\n      if (!intersection) {\n        continue;\n      }\n      // Note: intersection->second is the intersected face index.\n      // CHECK: We get doubles because we're intersecting with the interior of\n      // the faces.\n      if (const Point* point = boost::get<Point>(&intersection->first)) {\n        points.push_back(*point);\n      }\n    }\n    if (points.size() >= 4) {\n      if (source_x > target_x) {\n        std::sort(points.begin(), points.end(),\n                  [](const Point& a, const Point& b) { return a.x() > b.x(); });\n      } else if (source_x < target_x) {\n        std::sort(points.begin(), points.end(),\n                  [](const Point& a, const Point& b) { return a.x() < b.x(); });\n      } else if (source_y > target_y) {\n        std::sort(points.begin(), points.end(),\n                  [](const Point& a, const Point& b) { return a.y() > b.y(); });\n      } else if (source_y < target_y) {\n        std::sort(points.begin(), points.end(),\n                  [](const Point& a, const Point& b) { return a.y() < b.y(); });\n      } else if (source_z > target_z) {\n        std::sort(points.begin(), points.end(),\n                  [](const Point& a, const Point& b) { return a.z() > b.z(); });\n      } else if (source_z < target_z) {\n        std::sort(points.begin(), points.end(),\n                  [](const Point& a, const Point& b) { return a.z() < b.z(); });\n      } else {\n        std::cout << \"QQ/clipSegmentApproximate: impossible\" << std::endl;\n      }\n      // Now we should have pairs of doubled pointwise intersections.\n      for (size_t index = 0; index < points.size() - 2; index += 4) {\n        const Point& source = points[index];\n        const Point& target = points[index + 2];\n        emit_segment(CGAL::to_double(source.x().exact()),\n                     CGAL::to_double(source.y().exact()),\n                     CGAL::to_double(source.z().exact()),\n                     CGAL::to_double(target.x().exact()),\n                     CGAL::to_double(target.y().exact()),\n                     CGAL::to_double(target.z().exact()));\n      }\n    }\n    // Handle segmentwise intersections -- along faces.\n    for (const auto& intersection : intersections) {\n      if (!intersection) {\n        continue;\n      }\n      // Note: intersection->second is the intersected face index.\n      if (const Segment* segment = boost::get<Segment>(&intersection->first)) {\n        emit_segment(CGAL::to_double(segment->source().x().exact()),\n                     CGAL::to_double(segment->source().y().exact()),\n                     CGAL::to_double(segment->source().z().exact()),\n                     CGAL::to_double(segment->target().x().exact()),\n                     CGAL::to_double(segment->target().y().exact()),\n                     CGAL::to_double(segment->target().z().exact()));\n      }\n    }\n  }\n\n private:\n  std::unique_ptr<Surface_mesh> mesh_;\n  std::unique_ptr<Tree> tree_;\n  std::unique_ptr<Inside_tester> inside_tester_;\n};\n\nvoid SeparateSurfaceMesh(const Surface_mesh* input, bool keep_volumes,\n                         bool keep_cavities_in_volumes,\n                         bool keep_cavities_as_volumes,\n                         emscripten::val emit_mesh) {\n  std::vector<Surface_mesh> meshes;\n  std::vector<Surface_mesh> cavities;\n  std::vector<Surface_mesh> volumes;\n  CGAL::Polygon_mesh_processing::split_connected_components(*input, meshes);\n\n  // CHECK: Can we leverage volume_connected_components() here?\n  for (auto& mesh : meshes) {\n    // CHECK: Do we have an expensive move here?\n    if (CGAL::Polygon_mesh_processing::is_outward_oriented(mesh)) {\n      volumes.push_back(mesh);\n    } else {\n      cavities.push_back(mesh);\n    }\n  }\n\n  if (keep_volumes) {\n    for (auto& mesh : volumes) {\n      if (keep_cavities_in_volumes) {\n        CGAL::Side_of_triangle_mesh<Surface_mesh, Kernel> inside(mesh);\n        for (auto& cavity : cavities) {\n          for (const auto vertex : cavity.vertices()) {\n            if (inside(cavity.point(vertex)) == CGAL::ON_BOUNDED_SIDE) {\n              // Include the cavity in the mesh.\n              mesh.join(cavity);\n            }\n            // A single test is sufficient.\n            break;\n          }\n        }\n      }\n      Surface_mesh* output = new Surface_mesh(mesh);\n      emit_mesh(output);\n    }\n  }\n\n  if (keep_cavities_as_volumes) {\n    for (auto& mesh : cavities) {\n      CGAL::Polygon_mesh_processing::reverse_face_orientations(mesh);\n      Surface_mesh* output = new Surface_mesh(mesh);\n      emit_mesh(output);\n    }\n  }\n}\n\nbool admitVector(Vector& vector, emscripten::val fill_vector) {\n  Quadruple q;\n  Quadruple* qp = &q;\n  if (fill_vector(qp).as<bool>()) {\n    vector = Vector(q[0], q[1], q[2]);\n    return true;\n  }\n  return false;\n}\n\nVector estimateTriangleNormals(const std::vector<Triangle>& triangles) {\n  Vector estimate(0, 0, 0);\n  for (const Triangle& triangle : triangles) {\n    estimate +=\n        unitVector(CGAL::Polygon_mesh_processing::internal::triangle_normal(\n            triangle[0], triangle[1], triangle[2], Kernel()));\n  }\n  return estimate;\n}\n\nvoid computeCentroidOfSurfaceMesh(Point& centroid, const Surface_mesh& mesh) {\n  std::vector<Triangle> triangles;\n  for (const auto& facet : mesh.faces()) {\n    if (mesh.is_removed(facet)) {\n      continue;\n    }\n    const auto h = mesh.halfedge(facet);\n    triangles.push_back(Triangle(\n        mesh.point(mesh.source(h)), mesh.point(mesh.source(mesh.next(h))),\n        mesh.point(mesh.source(mesh.next(mesh.next(h))))));\n  }\n  centroid = CGAL::centroid(triangles.begin(), triangles.end(),\n                            CGAL::Dimension_tag<2>());\n}\n\nvoid ComputeCentroidOfSurfaceMesh(const Surface_mesh* input,\n                                  const Transformation* transformation,\n                                  emscripten::val emit_normal) {\n  Surface_mesh mesh(*input);\n  CGAL::Polygon_mesh_processing::transform(*transformation, mesh,\n                                           CGAL::parameters::all_default());\n  Point centroid;\n  computeCentroidOfSurfaceMesh(centroid, mesh);\n  std::ostringstream x;\n  x << centroid.x().exact();\n  std::string xs = x.str();\n  std::ostringstream y;\n  y << centroid.y().exact();\n  std::string ys = y.str();\n  std::ostringstream z;\n  z << centroid.z().exact();\n  std::string zs = z.str();\n  emit_normal(CGAL::to_double(centroid.x().exact()),\n              CGAL::to_double(centroid.y().exact()),\n              CGAL::to_double(centroid.z().exact()), xs, ys, zs);\n}\n\nvoid computeNormalOfSurfaceMesh(Vector& normal, const Surface_mesh& mesh) {\n  std::vector<Triangle> triangles;\n  for (const auto& facet : mesh.faces()) {\n    if (mesh.is_removed(facet)) {\n      continue;\n    }\n    const auto h = mesh.halfedge(facet);\n    triangles.push_back(Triangle(\n        mesh.point(mesh.source(h)), mesh.point(mesh.source(mesh.next(h))),\n        mesh.point(mesh.source(mesh.next(mesh.next(h))))));\n  }\n  Plane plane;\n  linear_least_squares_fitting_3(triangles.begin(), triangles.end(), plane,\n                                 CGAL::Dimension_tag<2>());\n  normal = plane.orthogonal_vector();\n  if (CGAL::scalar_product(normal, estimateTriangleNormals(triangles)) < 0) {\n    normal = -normal;\n  }\n}\n\nvoid ComputeNormalOfSurfaceMesh(const Surface_mesh* input,\n                                const Transformation* transformation,\n                                emscripten::val emit_normal) {\n  Surface_mesh mesh(*input);\n  CGAL::Polygon_mesh_processing::transform(*transformation, mesh,\n                                           CGAL::parameters::all_default());\n  Vector normal;\n  computeNormalOfSurfaceMesh(normal, mesh);\n  std::ostringstream x;\n  x << normal.x().exact();\n  std::string xs = x.str();\n  std::ostringstream y;\n  y << normal.y().exact();\n  std::string ys = y.str();\n  std::ostringstream z;\n  z << normal.z().exact();\n  std::string zs = z.str();\n  emit_normal(CGAL::to_double(normal.x().exact()),\n              CGAL::to_double(normal.y().exact()),\n              CGAL::to_double(normal.z().exact()), xs, ys, zs);\n}\n\nvoid ExtrusionOfSurfaceMesh(const Surface_mesh* input,\n                            const Transformation* transformation, double height,\n                            double depth, emscripten::val fill_normal,\n                            emscripten::val emit_mesh) {\n  Surface_mesh mesh(*input);\n  CGAL::Polygon_mesh_processing::transform(*transformation, mesh,\n                                           CGAL::parameters::all_default());\n\n  // Default to a vertical extrusion.\n  Vector normal;\n\n  // Infer a normal from the best-fit plane of the mesh.\n  if (!admitVector(normal, fill_normal)) {\n    CGAL::Polygon_mesh_processing::triangulate_faces(mesh);\n    computeNormalOfSurfaceMesh(normal, mesh);\n  }\n\n  Vector up;\n  Vector down;\n  // Could we precisely align with z-up, extrude, and then realign?\n  // Probably not, since if we could, we wouldn't need to.\n  if (normal.direction() == Vector(0, 0, 1).direction()) {\n    // Handle vertical extrusion precisely.\n    up = Vector(0, 0, 1) * height;\n    down = Vector(0, 0, 1) * depth;\n  } else if (normal.direction() == Vector(0, 0, -1).direction()) {\n    // Handle vertical extrusion precisely.\n    up = Vector(0, 0, -1) * height;\n    down = Vector(0, 0, -1) * depth;\n  } else if (normal.direction() == Vector(0, 1, 0).direction()) {\n    // Handle vertical extrusion precisely.\n    up = Vector(0, 1, 0) * height;\n    down = Vector(0, 1, 0) * depth;\n  } else if (normal.direction() == Vector(0, -1, 0).direction()) {\n    // Handle vertical extrusion precisely.\n    up = Vector(0, -1, 0) * height;\n    down = Vector(0, -1, 0) * depth;\n  } else if (normal.direction() == Vector(1, 0, 0).direction()) {\n    // Handle vertical extrusion precisely.\n    up = Vector(1, 0, 0) * height;\n    down = Vector(1, 0, 0) * depth;\n  } else if (normal.direction() == Vector(-1, 0, 0).direction()) {\n    // Handle vertical extrusion precisely.\n    up = Vector(-1, 0, 0) * height;\n    down = Vector(-1, 0, 0) * depth;\n  } else {\n    // Generally we need a unit normal, unfortunately this requires an\n    // approximation.\n    double length = sqrt(CGAL::to_double(normal.squared_length()));\n    up = normal * (height / length);\n    down = normal * (depth / length);\n  }\n\n  Surface_mesh* extruded_mesh = new Surface_mesh();\n\n  typedef typename boost::property_map<Surface_mesh, CGAL::vertex_point_t>::type\n      VPMap;\n  Project<VPMap> top(get(CGAL::vertex_point, *extruded_mesh), up);\n  Project<VPMap> bottom(get(CGAL::vertex_point, *extruded_mesh), down);\n  CGAL::Polygon_mesh_processing::extrude_mesh(mesh, *extruded_mesh, bottom,\n                                              top);\n  CGAL::Polygon_mesh_processing::triangulate_faces(*extruded_mesh);\n  if (CGAL::Polygon_mesh_processing::volume(\n          *extruded_mesh, CGAL::parameters::all_default()) == 0) {\n    delete extruded_mesh;\n  } else {\n    emit_mesh(extruded_mesh);\n  }\n}\n\ntemplate <typename MAP>\nstruct ProjectToPlane {\n  ProjectToPlane(MAP map, Vector vector, Plane plane)\n      : map(map), vector(vector), plane(plane) {}\n\n  template <typename VD, typename T>\n  void operator()(const T&, VD vd) const {\n    Line line(get(map, vd), vector);\n    auto result = CGAL::intersection(Line(get(map, vd), vector), plane);\n    if (result) {\n      if (Point* point = boost::get<Point>(&*result)) {\n        put(map, vd, *point);\n      }\n    }\n  }\n\n  MAP map;\n  Vector vector;\n  Plane plane;\n};\n\nconst Surface_mesh* ExtrusionToPlaneOfSurfaceMesh(\n    const Surface_mesh* input, const Transformation* transformation,\n    double high_x, double high_y, double high_z, double high_plane_x,\n    double high_plane_y, double high_plane_z, double high_plane_w, double low_x,\n    double low_y, double low_z, double low_plane_x, double low_plane_y,\n    double low_plane_z, double low_plane_w) {\n  Surface_mesh mesh(*input);\n  CGAL::Polygon_mesh_processing::transform(*transformation, mesh,\n                                           CGAL::parameters::all_default());\n\n  Surface_mesh* extruded_mesh = new Surface_mesh();\n\n  typedef typename boost::property_map<Surface_mesh, CGAL::vertex_point_t>::type\n      VPMap;\n  ProjectToPlane<VPMap> top(\n      get(CGAL::vertex_point, *extruded_mesh), Vector(high_x, high_y, high_z),\n      Plane(high_plane_x, high_plane_y, high_plane_z, high_plane_w));\n  ProjectToPlane<VPMap> bottom(\n      get(CGAL::vertex_point, *extruded_mesh), Vector(low_x, low_y, low_z),\n      Plane(low_plane_x, low_plane_y, low_plane_z, low_plane_w));\n\n  CGAL::Polygon_mesh_processing::extrude_mesh(mesh, *extruded_mesh, bottom,\n                                              top);\n\n  return extruded_mesh;\n}\n\nconst Surface_mesh::Vertex_index ensureVertex(\n    Surface_mesh& mesh, std::map<Point, Vertex_index>& vertices,\n    const Point& point) {\n  auto it = vertices.find(point);\n  if (it == vertices.end()) {\n    Surface_mesh::Vertex_index new_vertex = mesh.add_vertex(point);\n    vertices[point] = new_vertex;\n    return new_vertex;\n  }\n  return it->second;\n}\n\nvoid convertArrangementToPolygonsWithHoles(\n    const Arrangement_2& arrangement, std::vector<Polygon_with_holes_2>& out) {\n  std::queue<Arrangement_2::Face_const_handle> undecided;\n  CGAL::Unique_hash_map<Arrangement_2::Face_const_handle, bool> positive_faces;\n  CGAL::Unique_hash_map<Arrangement_2::Face_const_handle, bool> negative_faces;\n\n  for (Arrangement_2::Face_const_iterator face = arrangement.faces_begin();\n       face != arrangement.faces_end(); ++face) {\n    if (!face->has_outer_ccb()) {\n      negative_faces[face] = true;\n    } else {\n      undecided.push(face);\n    }\n  }\n\n  while (!undecided.empty()) {\n    Arrangement_2::Face_const_handle face = undecided.front();\n    undecided.pop();\n    if (positive_faces[face]) {\n      for (Arrangement_2::Hole_const_iterator hole = face->holes_begin();\n           hole != face->holes_end(); ++hole) {\n        positive_faces[(*hole)->twin()->face()] = false;\n        negative_faces[(*hole)->twin()->face()] = true;\n      }\n      continue;\n    }\n    if (negative_faces[face]) {\n      for (Arrangement_2::Hole_const_iterator hole = face->holes_begin();\n           hole != face->holes_end(); ++hole) {\n        positive_faces[(*hole)->twin()->face()] = true;\n        negative_faces[(*hole)->twin()->face()] = false;\n      }\n      continue;\n    }\n    bool decided = false;\n    Arrangement_2::Ccb_halfedge_const_circulator start = face->outer_ccb();\n    Arrangement_2::Ccb_halfedge_const_circulator edge = start;\n    do {\n      if (negative_faces[edge->twin()->face()]) {\n        positive_faces[face] = true;\n        negative_faces[face] = false;\n        decided = true;\n        break;\n      }\n    } while (++edge != start);\n    if (!decided) {\n      edge = start;\n      do {\n        if (positive_faces[edge->twin()->face()]) {\n          positive_faces[face] = false;\n          negative_faces[face] = true;\n          decided = true;\n          break;\n        }\n      } while (++edge != start);\n    }\n    undecided.push(face);\n  }\n\n  for (Arrangement_2::Face_const_iterator face = arrangement.faces_begin();\n       face != arrangement.faces_end(); ++face) {\n    if (!positive_faces[face]) {\n      continue;\n    }\n    Polygon_2 polygon_boundary;\n\n    Arrangement_2::Ccb_halfedge_const_circulator start = face->outer_ccb();\n    Arrangement_2::Ccb_halfedge_const_circulator edge = start;\n    do {\n      if (edge->source()->point() == edge->target()->point()) {\n        // Skip zero length edges.\n        continue;\n      }\n      polygon_boundary.push_back(edge->source()->point());\n    } while (++edge != start);\n\n    std::vector<Polygon_2> polygon_holes;\n    for (Arrangement_2::Hole_const_iterator hole = face->holes_begin();\n         hole != face->holes_end(); ++hole) {\n      Polygon_2 polygon_hole;\n      Arrangement_2::Ccb_halfedge_const_circulator start = *hole;\n      Arrangement_2::Ccb_halfedge_const_circulator edge = start;\n      do {\n        if (edge->source()->point() == edge->target()->point()) {\n          // Skip zero length edges.\n          continue;\n        }\n        polygon_hole.push_back(edge->source()->point());\n      } while (++edge != start);\n\n      if (polygon_hole.orientation() == CGAL::Sign::POSITIVE) {\n        polygon_hole.reverse_orientation();\n      }\n      polygon_holes.push_back(polygon_hole);\n    }\n    out.push_back(Polygon_with_holes_2(polygon_boundary, polygon_holes.begin(),\n                                       polygon_holes.end()));\n  }\n}\n\nvoid PlanarSurfaceMeshToPolygonSet(const Plane& plane, const Surface_mesh& mesh,\n                                   General_polygon_set_2& set) {\n  typedef CGAL::Arr_segment_traits_2<Kernel> Traits_2;\n  typedef Traits_2::Point_2 Point_2;\n  typedef Traits_2::X_monotone_curve_2 Segment_2;\n  typedef CGAL::Arrangement_2<Traits_2> Arrangement_2;\n  typedef Arrangement_2::Vertex_handle Vertex_handle;\n  typedef Arrangement_2::Halfedge_handle Halfedge_handle;\n\n  Arrangement_2 arrangement;\n\n  std::set<std::vector<Kernel::FT>> segments;\n\n  // Construct the border.\n  for (const Surface_mesh::Edge_index edge : mesh.edges()) {\n    if (!mesh.is_border(edge)) {\n      continue;\n    }\n    Segment_2 segment{\n        plane.to_2d(mesh.point(mesh.source(mesh.halfedge(edge)))),\n        plane.to_2d(mesh.point(mesh.target(mesh.halfedge(edge))))};\n    insert(arrangement, segment);\n  }\n\n  std::vector<Polygon_with_holes_2> polygons;\n  convertArrangementToPolygonsWithHoles(arrangement, polygons);\n  for (const auto& polygon : polygons) {\n    set.join(polygon);\n  }\n}\n\n// This handles potentially overlapping facets.\nvoid PlanarSurfaceMeshFacetsToPolygonSet(const Plane& plane,\n                                         const Surface_mesh& mesh,\n                                         General_polygon_set_2& set) {\n  typedef CGAL::Arr_segment_traits_2<Kernel> Traits_2;\n  typedef Traits_2::Point_2 Point_2;\n  typedef Traits_2::X_monotone_curve_2 Segment_2;\n  typedef CGAL::Arrangement_2<Traits_2> Arrangement_2;\n  typedef Arrangement_2::Vertex_handle Vertex_handle;\n  typedef Arrangement_2::Halfedge_handle Halfedge_handle;\n\n  std::set<std::vector<Kernel::FT>> segments;\n\n  for (const auto& facet : mesh.faces()) {\n    const auto& start = mesh.halfedge(facet);\n    if (mesh.is_removed(start)) {\n      continue;\n    }\n    // Do we really need an arrangement here?\n    Arrangement_2 arrangement;\n    Halfedge_index edge = start;\n    do {\n      Segment_2 segment{plane.to_2d(mesh.point(mesh.source(edge))),\n                        plane.to_2d(mesh.point(mesh.target(edge)))};\n      insert(arrangement, segment);\n      edge = mesh.next(edge);\n    } while (edge != start);\n    // The arrangement shouldn't produce polygons with holes, so this might be\n    // simplified.\n    std::vector<Polygon_with_holes_2> polygons;\n    convertArrangementToPolygonsWithHoles(arrangement, polygons);\n    for (const auto& polygon : polygons) {\n      set.join(polygon);\n    }\n  }\n}\n\nbool IsPlanarSurfaceMesh(Plane& plane, const Surface_mesh& a) {\n  if (CGAL::is_closed(a)) return false;\n  if (a.number_of_vertices() < 3) return false;\n  if (!SomePlaneOfSurfaceMesh(plane, a)) return false;\n  for (const auto& vertex : a.vertices()) {\n    if (!plane.has_on(a.point(vertex))) return false;\n  }\n  return true;\n}\n\nbool IsCoplanarSurfaceMesh(Plane& plane, const Surface_mesh& a) {\n  if (CGAL::is_closed(a)) return false;\n  if (a.number_of_vertices() < 3) return false;\n  for (const auto& vertex : a.vertices()) {\n    if (!plane.has_on(a.point(vertex))) return false;\n  }\n  return true;\n}\n\nbool PolygonsWithHolesToSurfaceMesh(const Plane& plane,\n                                    std::vector<Polygon_with_holes_2>& polygons,\n                                    Surface_mesh& result) {\n  CGAL::Polygon_vertical_decomposition_2<Kernel> convexifier;\n  std::map<Point, Vertex_index> vertex_map;\n  result.clear();\n  for (const auto& polygon : polygons) {\n    std::vector<Polygon_2> facets;\n    if (polygon.number_of_holes() > 0) {\n      // CHECK: Could we just use connect_holes instead?\n      convexifier(polygon, std::back_inserter(facets));\n    } else {\n      facets.push_back(polygon.outer_boundary());\n    }\n    for (const auto& facet : facets) {\n      std::vector<Surface_mesh::Vertex_index> vertices;\n      for (const auto& point : facet) {\n        vertices.push_back(\n            ensureVertex(result, vertex_map, plane.to_3d(point)));\n      }\n      if (result.add_face(vertices) == Surface_mesh::null_face()) {\n        return false;\n      }\n    }\n  }\n  if (CGAL::is_closed(result) && !CGAL::is_empty(result)) {\n    std::cout\n        << \"PolygonsWithHolesToSurfaceMesh: produced non-empty closed mesh: \"\n        << result << std::endl;\n  }\n  CGAL::Polygon_mesh_processing::triangulate_faces(result);\n  return true;\n}\n\nbool GeneralPolygonSetToSurfaceMesh(const Plane& plane,\n                                    General_polygon_set_2& set,\n                                    Surface_mesh& result) {\n  Surface_mesh* c = new Surface_mesh();\n  std::vector<Polygon_with_holes_2> polygons;\n  set.polygons_with_holes(std::back_inserter(polygons));\n  return PolygonsWithHolesToSurfaceMesh(plane, polygons, result);\n}\n\nvoid DifferenceOfCoplanarSurfaceMeshes(const Plane& plane,\n                                       const Surface_mesh& a,\n                                       const Surface_mesh& b,\n                                       Surface_mesh& result) {\n  General_polygon_set_2 set;\n  General_polygon_set_2 subtract;\n  PlanarSurfaceMeshToPolygonSet(plane, a, set);\n  PlanarSurfaceMeshToPolygonSet(plane, b, subtract);\n  set.difference(subtract);\n  GeneralPolygonSetToSurfaceMesh(plane, set, result);\n}\n\nvoid UnionOfCoplanarSurfaceMeshes(const Plane& plane, const Surface_mesh* a,\n                                  const Surface_mesh* b, Surface_mesh& result) {\n  General_polygon_set_2 set;\n  General_polygon_set_2 add;\n  PlanarSurfaceMeshToPolygonSet(plane, *a, set);\n  PlanarSurfaceMeshToPolygonSet(plane, *b, add);\n  set.join(add);\n  GeneralPolygonSetToSurfaceMesh(plane, set, result);\n}\n\nvoid IntersectionOfCoplanarSurfaceMeshes(const Plane& plane,\n                                         const Surface_mesh* a,\n                                         const Surface_mesh* b,\n                                         Surface_mesh& result) {\n  General_polygon_set_2 set;\n  General_polygon_set_2 clip;\n  PlanarSurfaceMeshToPolygonSet(plane, *a, set);\n  PlanarSurfaceMeshToPolygonSet(plane, *b, clip);\n  set.intersection(clip);\n  GeneralPolygonSetToSurfaceMesh(plane, set, result);\n}\n\nvoid SurfaceMeshSectionToPolygonSet(const Plane& plane, const Surface_mesh& a,\n                                    General_polygon_set_2& set) {\n  typedef std::vector<Point> Polyline_type;\n  typedef std::list<Polyline_type> Polylines;\n  CGAL::Polygon_mesh_slicer<Surface_mesh, Kernel> slicer(a);\n  Polylines polylines;\n  slicer(plane, std::back_inserter(polylines));\n  for (const auto& polyline : polylines) {\n    std::size_t length = polyline.size();\n    if (length < 3 || polyline.front() != polyline.back()) {\n      continue;\n    }\n    Polygon_2 polygon;\n    // Skip the duplicated last point in the polyline.\n    for (std::size_t nth = 0; nth < length - 1; nth++) {\n      polygon.push_back(plane.to_2d(polyline[nth]));\n    }\n    if (polygon.orientation() == CGAL::Sign::NEGATIVE) {\n      polygon.reverse_orientation();\n    }\n    set.join(polygon);\n  }\n}\n\nconst double kExtrusionMinimum = 10000.0;\nconst double kExtrusionMinimumSquared = kExtrusionMinimum * kExtrusionMinimum;\n\nconst double kIota = 10e-5;\n\nconst Surface_mesh* DifferenceOfSurfaceMeshes(const Surface_mesh* a,\n                                              const Transformation* a_transform,\n                                              const Surface_mesh* b,\n                                              const Transformation* b_transform,\n                                              bool check, bool fix) {\n  if (a_transform) {\n    Surface_mesh transformed(*a);\n    CGAL::Polygon_mesh_processing::transform(*a_transform, transformed,\n                                             CGAL::parameters::all_default());\n    return DifferenceOfSurfaceMeshes(&transformed, nullptr, b, b_transform,\n                                     check, fix);\n  } else if (b_transform) {\n    Surface_mesh transformed(*b);\n    CGAL::Polygon_mesh_processing::transform(*b_transform, transformed,\n                                             CGAL::parameters::all_default());\n    return DifferenceOfSurfaceMeshes(a, a_transform, &transformed, nullptr,\n                                     check, fix);\n  }\n  Plane plane;\n  if (IsPlanarSurfaceMesh(plane, *a)) {\n    if (IsCoplanarSurfaceMesh(plane, *b)) {\n      Surface_mesh* result = new Surface_mesh();\n      DifferenceOfCoplanarSurfaceMeshes(plane, *a, *b, *result);\n      return result;\n    } else {\n      // Difference with the section of the other.\n      General_polygon_set_2 set;\n      General_polygon_set_2 other;\n      PlanarSurfaceMeshToPolygonSet(plane, *a, set);\n      SurfaceMeshSectionToPolygonSet(plane, *b, other);\n      set.difference(other);\n      Surface_mesh* result = new Surface_mesh();\n      GeneralPolygonSetToSurfaceMesh(plane, set, *result);\n      return result;\n    }\n  } else if (IsPlanarSurfaceMesh(plane, *b)) {\n    return a;\n  }\n  double x = 0, y = 0, z = 0;\n  Surface_mesh* c = new Surface_mesh();\n  for (int shift = 0x11;; shift++) {\n    Surface_mesh working_a(*a);\n    Surface_mesh working_b(*b);\n    if (x != 0 || y != 0 || z != 0) {\n      std::cout << \"Note: Shifting difference by x=\" << x << \" y=\" << y\n                << \" z=\" << z << std::endl;\n      Transformation translation(CGAL::TRANSLATION, Vector(x, y, z));\n      CGAL::Polygon_mesh_processing::transform(translation, working_b,\n                                               CGAL::parameters::all_default());\n    }\n    if (check) {\n      if (CGAL::Polygon_mesh_processing::corefine_and_compute_difference(\n              working_a, working_b, *c,\n              CGAL::Polygon_mesh_processing::parameters::\n                  throw_on_self_intersection(true),\n              CGAL::Polygon_mesh_processing::parameters::\n                  throw_on_self_intersection(true),\n              CGAL::Polygon_mesh_processing::parameters::\n                  throw_on_self_intersection(true))) {\n        return c;\n      }\n    } else {\n      if (CGAL::Polygon_mesh_processing::corefine_and_compute_difference(\n              working_a, working_b, *c, CGAL::parameters::all_default(),\n              CGAL::parameters::all_default(),\n              CGAL::parameters::all_default())) {\n        return c;\n      }\n    }\n    if (!fix) {\n      delete c;\n      return nullptr;\n    }\n    const double direction = ((shift & (1 << 3)) ? -1 : 1) * (shift >> 4);\n    if (shift & (1 << 0)) {\n      x = kIota * direction;\n    } else {\n      x = 0;\n    }\n    if (shift & (1 << 1)) {\n      y = kIota * direction;\n    } else {\n      y = 0;\n    }\n    if (shift & (1 << 2)) {\n      z = kIota * direction;\n    } else {\n      z = 0;\n    }\n  }\n}\n\nint CutClosedSurfaceMeshIncrementally(const Surface_mesh* a,\n                                      const Transformation* a_transform,\n                                      int cutCount, bool check,\n                                      emscripten::val nthMesh,\n                                      emscripten::val nthTransform,\n                                      emscripten::val emit) {\n  Transformation toA = a_transform->inverse();\n  Surface_mesh* result = new Surface_mesh(*a);\n  for (int nth = 0; nth < cutCount; nth++) {\n    if (CGAL::is_empty(*result)) {\n      emit(result);\n      return STATUS_EMPTY;\n    }\n    const Surface_mesh* cutMesh =\n        nthMesh(nth).as<const Surface_mesh*>(emscripten::allow_raw_pointers());\n    if (CGAL::is_empty(*cutMesh)) {\n      continue;\n    }\n    const Transformation* cutTransform =\n        nthTransform(nth).as<const Transformation*>(\n            emscripten::allow_raw_pointers());\n    Surface_mesh workingCutMesh(*cutMesh);\n    CGAL::Polygon_mesh_processing::transform(\n        toA * *cutTransform, workingCutMesh, CGAL::parameters::all_default());\n    if (!CGAL::Polygon_mesh_processing::do_intersect(\n            *result, workingCutMesh,\n            CGAL::Polygon_mesh_processing::parameters::\n                do_overlap_test_of_bounded_sides(true),\n            CGAL::Polygon_mesh_processing::parameters::\n                do_overlap_test_of_bounded_sides(true))) {\n      continue;\n    }\n    if (!CGAL::Polygon_mesh_processing::corefine_and_compute_difference(\n            *result, workingCutMesh, *result, CGAL::parameters::all_default(),\n            CGAL::parameters::all_default(), CGAL::parameters::all_default())) {\n      delete result;\n      std::cout << \"CutClosedSurfaceMeshIncrementally/zero_thickness\"\n                << std::endl;\n      return STATUS_ZERO_THICKNESS;\n    }\n  }\n  emit(result);\n  return STATUS_OK;\n}\n\nint CutSurfaceMeshesIncrementally(\n    size_t target_count, emscripten::val getTargetMesh,\n    emscripten::val getTargetTransform, emscripten::val getTargetIsEmptyPlanar,\n    size_t source_count, emscripten::val getSourceMesh,\n    emscripten::val getSourceTransform, emscripten::val emit) {\n  std::vector<std::unique_ptr<Surface_mesh>> target_meshes(target_count);\n  std::vector<Transformation> to_target_transforms(target_count);\n  std::vector<bool> planar(target_count, false);\n  std::vector<Plane> target_planes(target_count);\n  std::vector<General_polygon_set_2> planar_sets(target_count);\n\n  for (size_t nth_target = 0; nth_target < target_count; nth_target++) {\n    const Surface_mesh* target_mesh =\n        getTargetMesh(nth_target)\n            .as<const Surface_mesh*>(emscripten::allow_raw_pointers());\n    target_meshes[nth_target].reset(new Surface_mesh(*target_mesh));\n    const Transformation* target_transform =\n        getTargetTransform(nth_target)\n            .as<const Transformation*>(emscripten::allow_raw_pointers());\n    to_target_transforms[nth_target] = target_transform->inverse();\n    if (CGAL::is_empty(*target_meshes[nth_target]) &&\n        getTargetIsEmptyPlanar(nth_target).as<bool>()) {\n      // By default an empty mesh will be considered a volumetric target.\n      // So for planar fusion we append a planar target in the xy plane.\n      target_planes[nth_target] = Plane(0, 0, 1, 0);\n      planar[nth_target] = true;\n    } else {\n      planar[nth_target] = IsPlanarSurfaceMesh(target_planes[nth_target],\n                                               *target_meshes[nth_target]);\n      if (planar[nth_target]) {\n        PlanarSurfaceMeshToPolygonSet(target_planes[nth_target],\n                                      *target_meshes[nth_target],\n                                      planar_sets[nth_target]);\n      }\n    }\n  }\n\n  for (size_t nth_source = 0; nth_source < source_count; nth_source++) {\n    const Surface_mesh* source_mesh =\n        getSourceMesh(nth_source)\n            .as<const Surface_mesh*>(emscripten::allow_raw_pointers());\n    if (CGAL::is_empty(*source_mesh)) {\n      continue;\n    }\n    const Transformation* source_transform =\n        getSourceTransform(nth_source)\n            .as<const Transformation*>(emscripten::allow_raw_pointers());\n    for (size_t nth_target = 0; nth_target < target_count; nth_target++) {\n      Surface_mesh working_source_mesh(*source_mesh);\n      CGAL::Polygon_mesh_processing::transform(\n          to_target_transforms[nth_target] * *source_transform,\n          working_source_mesh, CGAL::parameters::all_default());\n      if (planar[nth_target]) {\n        Plane& plane = target_planes[nth_target];\n        General_polygon_set_2 cut;\n        if (IsCoplanarSurfaceMesh(plane, working_source_mesh)) {\n          PlanarSurfaceMeshToPolygonSet(plane, working_source_mesh, cut);\n        } else if (CGAL::is_closed(working_source_mesh)) {\n          SurfaceMeshSectionToPolygonSet(plane, working_source_mesh, cut);\n        }\n        planar_sets[nth_target].difference(cut);\n      } else {\n        if (!CGAL::is_closed(working_source_mesh) ||\n            CGAL::is_empty(working_source_mesh)) {\n          continue;\n        }\n        if (CGAL::Polygon_mesh_processing::do_intersect(\n                *target_meshes[nth_target], working_source_mesh,\n                CGAL::Polygon_mesh_processing::parameters::\n                    do_overlap_test_of_bounded_sides(true),\n                CGAL::Polygon_mesh_processing::parameters::\n                    do_overlap_test_of_bounded_sides(true))) {\n          if (!CGAL::Polygon_mesh_processing::corefine_and_compute_difference(\n                  *target_meshes[nth_target], working_source_mesh,\n                  *target_meshes[nth_target], CGAL::parameters::all_default(),\n                  CGAL::parameters::all_default(),\n                  CGAL::parameters::all_default())) {\n            return STATUS_ZERO_THICKNESS;\n          }\n        }\n      }\n    }\n  }\n  for (size_t nth_target = 0; nth_target < target_count; nth_target++) {\n    if (planar[nth_target]) {\n      if (!GeneralPolygonSetToSurfaceMesh(target_planes[nth_target],\n                                          planar_sets[nth_target],\n                                          *target_meshes[nth_target])) {\n        return STATUS_ZERO_THICKNESS;\n      }\n    }\n  }\n\n  // At this point we are committed to producing a result.\n  for (size_t nth_target = 0; nth_target < target_count; nth_target++) {\n    Surface_mesh* target_mesh = target_meshes[nth_target].release();\n    emit(nth_target, target_mesh);\n  }\n\n  return STATUS_OK;\n}\n\nint JoinSurfaceMeshesIncrementally(\n    size_t target_count, emscripten::val getTargetMesh,\n    emscripten::val getTargetTransform, emscripten::val getTargetIsEmptyPlanar,\n    size_t source_count, emscripten::val getSourceMesh,\n    emscripten::val getSourceTransform, emscripten::val emit) {\n  std::vector<std::unique_ptr<Surface_mesh>> target_meshes(target_count);\n  std::vector<Transformation> to_target_transforms(target_count);\n  std::vector<bool> planar(target_count, false);\n  std::vector<Plane> target_planes(target_count);\n  std::vector<General_polygon_set_2> planar_sets(target_count);\n\n  for (size_t nth_target = 0; nth_target < target_count; nth_target++) {\n    const Surface_mesh* target_mesh =\n        getTargetMesh(nth_target)\n            .as<const Surface_mesh*>(emscripten::allow_raw_pointers());\n    target_meshes[nth_target].reset(new Surface_mesh(*target_mesh));\n    const Transformation* target_transform =\n        getTargetTransform(nth_target)\n            .as<const Transformation*>(emscripten::allow_raw_pointers());\n    to_target_transforms[nth_target] = target_transform->inverse();\n    if (CGAL::is_empty(*target_meshes[nth_target]) &&\n        getTargetIsEmptyPlanar(nth_target).as<bool>()) {\n      // By default an empty mesh will be considered a volumetric target.\n      // So for planar fusion we append a planar target in the xy plane.\n      target_planes[nth_target] = Plane(0, 0, 1, 0);\n      planar[nth_target] = true;\n    } else {\n      planar[nth_target] = IsPlanarSurfaceMesh(target_planes[nth_target],\n                                               *target_meshes[nth_target]);\n      if (planar[nth_target]) {\n        PlanarSurfaceMeshToPolygonSet(target_planes[nth_target],\n                                      *target_meshes[nth_target],\n                                      planar_sets[nth_target]);\n      }\n    }\n  }\n\n  for (size_t nth_source = 0; nth_source < source_count; nth_source++) {\n    const Surface_mesh* source_mesh =\n        getSourceMesh(nth_source)\n            .as<const Surface_mesh*>(emscripten::allow_raw_pointers());\n    if (CGAL::is_empty(*source_mesh)) {\n      continue;\n    }\n    const Transformation* source_transform =\n        getSourceTransform(nth_source)\n            .as<const Transformation*>(emscripten::allow_raw_pointers());\n    for (size_t nth_target = 0; nth_target < target_count; nth_target++) {\n      Surface_mesh working_source_mesh(*source_mesh);\n      CGAL::Polygon_mesh_processing::transform(\n          to_target_transforms[nth_target] * *source_transform,\n          working_source_mesh, CGAL::parameters::all_default());\n      if (planar[nth_target]) {\n        Plane& plane = target_planes[nth_target];\n        if (IsCoplanarSurfaceMesh(plane, working_source_mesh)) {\n          PlanarSurfaceMeshToPolygonSet(plane, working_source_mesh,\n                                        planar_sets[nth_target]);\n        } else if (CGAL::is_closed(working_source_mesh)) {\n          SurfaceMeshSectionToPolygonSet(plane, working_source_mesh,\n                                         planar_sets[nth_target]);\n        }\n      } else {\n        if (!CGAL::is_closed(working_source_mesh) ||\n            CGAL::is_empty(working_source_mesh)) {\n          continue;\n        }\n        if (CGAL::Polygon_mesh_processing::do_intersect(\n                *target_meshes[nth_target], working_source_mesh,\n                CGAL::Polygon_mesh_processing::parameters::\n                    do_overlap_test_of_bounded_sides(true),\n                CGAL::Polygon_mesh_processing::parameters::\n                    do_overlap_test_of_bounded_sides(true))) {\n          if (!CGAL::Polygon_mesh_processing::corefine_and_compute_union(\n                  *target_meshes[nth_target], working_source_mesh,\n                  *target_meshes[nth_target], CGAL::parameters::all_default(),\n                  CGAL::parameters::all_default(),\n                  CGAL::parameters::all_default())) {\n            return STATUS_ZERO_THICKNESS;\n          }\n        } else {\n          // The meshes don't intersect, so we can perform a simple join.\n          if (!target_meshes[nth_target]->join(working_source_mesh)) {\n            return STATUS_ZERO_THICKNESS;\n          }\n        }\n      }\n    }\n  }\n  for (size_t nth_target = 0; nth_target < target_count; nth_target++) {\n    if (planar[nth_target]) {\n      if (!GeneralPolygonSetToSurfaceMesh(target_planes[nth_target],\n                                          planar_sets[nth_target],\n                                          *target_meshes[nth_target])) {\n        return STATUS_ZERO_THICKNESS;\n      }\n    }\n  }\n\n  for (size_t nth_target = 0; nth_target < target_count; nth_target++) {\n    Surface_mesh* target_mesh = target_meshes[nth_target].release();\n    emit(nth_target, target_mesh);\n  }\n  return STATUS_OK;\n}\n\nint DisjointSurfaceMeshesIncrementally(int meshCount, emscripten::val nthMesh,\n                                       emscripten::val nthTransform,\n                                       emscripten::val nthMasked,\n                                       emscripten::val emitMesh) {\n  Surface_mesh mask;\n  std::vector<Surface_mesh> planar_masks;\n  std::vector<Surface_mesh> volume_masks;\n  for (int nth = 0; nth < meshCount; nth++) {\n    bool is_masked = nthMasked(nth).as<bool>();\n    const Surface_mesh* mesh =\n        nthMesh(nth).as<const Surface_mesh*>(emscripten::allow_raw_pointers());\n    if (CGAL::is_empty(*mesh)) {\n      emitMesh(nth, mesh);\n      continue;\n    }\n    const Transformation* transform =\n        nthTransform(nth).as<const Transformation*>(\n            emscripten::allow_raw_pointers());\n    Surface_mesh oriented_mesh(*mesh);\n    // Orient the mesh in the absolute frame of the masks.\n    CGAL::Polygon_mesh_processing::transform(*transform, oriented_mesh,\n                                             CGAL::parameters::all_default());\n    Plane plane;\n    bool planar = IsPlanarSurfaceMesh(plane, oriented_mesh);\n    if (nth > 0) {\n      Surface_mesh* result = new Surface_mesh(oriented_mesh);\n      if (planar) {\n        for (auto& planar_mask : planar_masks) {\n          if (CGAL::is_empty(*result)) {\n            break;\n          }\n          if (IsCoplanarSurfaceMesh(plane, planar_mask)) {\n            DifferenceOfCoplanarSurfaceMeshes(plane, *result, planar_mask,\n                                              *result);\n          }\n        }\n        for (auto& volume_mask : volume_masks) {\n          if (CGAL::is_empty(*result)) {\n            break;\n          }\n          // Now clip to the inverted volume mask to make planar surfaces\n          // disjoint with volumes. (Note that volumes are not made disjoint to\n          // planar surfaces)\n          Surface_mesh inverse_mask(volume_mask);\n          CGAL::Polygon_mesh_processing::reverse_face_orientations(\n              inverse_mask.faces(), inverse_mask);\n          CGAL::Polygon_mesh_processing::clip(*result, inverse_mask,\n                                              CGAL::parameters::all_default(),\n                                              CGAL::parameters::all_default());\n        }\n      } else {\n        for (auto& volume_mask : volume_masks) {\n          if (CGAL::is_empty(*result)) {\n            break;\n          }\n          if (!CGAL::Polygon_mesh_processing::do_intersect(\n                  *result, volume_mask,\n                  CGAL::Polygon_mesh_processing::parameters::\n                      do_overlap_test_of_bounded_sides(true),\n                  CGAL::Polygon_mesh_processing::parameters::\n                      do_overlap_test_of_bounded_sides(true))) {\n            continue;\n          }\n          if (!CGAL::Polygon_mesh_processing::corefine_and_compute_difference(\n                  *result, volume_mask, *result,\n                  CGAL::parameters::all_default(),\n                  CGAL::parameters::all_default(),\n                  CGAL::parameters::all_default())) {\n            delete result;\n            return STATUS_ZERO_THICKNESS;\n          }\n        }\n      }\n      // Now emit the result in the original orientation.\n      CGAL::Polygon_mesh_processing::transform(transform->inverse(), *result,\n                                               CGAL::parameters::all_default());\n      emitMesh(nth, result);\n    }\n    if (!is_masked && !CGAL::is_empty(oriented_mesh)) {\n      if (planar) {\n        planar_masks.push_back(std::move(oriented_mesh));\n      } else {\n        volume_masks.push_back(std::move(oriented_mesh));\n      }\n    }\n  }\n  return STATUS_OK;\n}\n\nvoid RecursiveUnionOfSurfaceMeshes(std::queue<Surface_mesh*>& meshes,\n                                   bool check) {\n  while (meshes.size() >= 2) {\n    Surface_mesh* a = meshes.front();\n    meshes.pop();\n    Surface_mesh* b = meshes.front();\n    meshes.pop();\n    double x = 0, y = 0, z = 0;\n    for (int shift = 0x11;; shift++) {\n      if (x != 0 || y != 0 || z != 0) {\n        std::cout << \"Note: Shifting difference by x=\" << x << \" y=\" << y\n                  << \" z=\" << z << std::endl;\n        Transformation translation(CGAL::TRANSLATION, Vector(x, y, z));\n        CGAL::Polygon_mesh_processing::transform(\n            translation, *a, CGAL::parameters::all_default());\n      }\n      if (check) {\n        if (CGAL::Polygon_mesh_processing::corefine_and_compute_union(\n                *a, *b, *a,\n                CGAL::Polygon_mesh_processing::parameters::\n                    throw_on_self_intersection(true),\n                CGAL::Polygon_mesh_processing::parameters::\n                    throw_on_self_intersection(true),\n                CGAL::Polygon_mesh_processing::parameters::\n                    throw_on_self_intersection(true))) {\n          break;\n        }\n      } else {\n        if (CGAL::Polygon_mesh_processing::corefine_and_compute_union(\n                *a, *b, *a, CGAL::parameters::all_default(),\n                CGAL::parameters::all_default(),\n                CGAL::parameters::all_default())) {\n          break;\n        }\n      }\n      const double direction = ((shift & (1 << 3)) ? -1 : 1) * (shift >> 4);\n      if (shift & (1 << 0)) {\n        x = kIota * direction;\n      } else {\n        x = 0;\n      }\n      if (shift & (1 << 1)) {\n        y = kIota * direction;\n      } else {\n        y = 0;\n      }\n      if (shift & (1 << 2)) {\n        z = kIota * direction;\n      } else {\n        z = 0;\n      }\n    }\n    delete b;\n    meshes.push(a);\n  }\n}\n\nconst Surface_mesh* IntersectionOfSurfaceMeshes(\n    const Surface_mesh* a, const Transformation* a_transform,\n    const Surface_mesh* b, const Transformation* b_transform, bool check,\n    bool fix) {\n  if (a_transform) {\n    Surface_mesh transformed(*a);\n    CGAL::Polygon_mesh_processing::transform(*a_transform, transformed,\n                                             CGAL::parameters::all_default());\n    return IntersectionOfSurfaceMeshes(&transformed, nullptr, b, b_transform,\n                                       check, fix);\n  } else if (b_transform) {\n    Surface_mesh transformed(*b);\n    CGAL::Polygon_mesh_processing::transform(*b_transform, transformed,\n                                             CGAL::parameters::all_default());\n    return IntersectionOfSurfaceMeshes(a, a_transform, &transformed, nullptr,\n                                       check, fix);\n  }\n  Plane plane;\n  if (IsPlanarSurfaceMesh(plane, *a)) {\n    if (IsCoplanarSurfaceMesh(plane, *b)) {\n      Surface_mesh* result = new Surface_mesh();\n      IntersectionOfCoplanarSurfaceMeshes(plane, a, b, *result);\n      return result;\n    } else {\n      // Difference with the section of the other.\n      General_polygon_set_2 set;\n      General_polygon_set_2 other;\n      PlanarSurfaceMeshToPolygonSet(plane, *a, set);\n      SurfaceMeshSectionToPolygonSet(plane, *b, other);\n      set.intersection(other);\n      Surface_mesh* result = new Surface_mesh();\n      GeneralPolygonSetToSurfaceMesh(plane, set, *result);\n      return result;\n    }\n  } else if (IsPlanarSurfaceMesh(plane, *b)) {\n    return new Surface_mesh();\n  }\n  double x = 0, y = 0, z = 0;\n  Surface_mesh* c = new Surface_mesh();\n  for (int shift = 0x11;; shift++) {\n    Surface_mesh working_a(*a);\n    Surface_mesh working_b(*b);\n    if (x != 0 || y != 0 || z != 0) {\n      std::cout << \"Note: Shifting intersection x=\" << x << \" y=\" << y\n                << \" z=\" << z << std::endl;\n      Transformation translation(CGAL::TRANSLATION, Vector(x, y, z));\n      CGAL::Polygon_mesh_processing::transform(translation, working_b,\n                                               CGAL::parameters::all_default());\n    }\n    if (check) {\n      if (CGAL::Polygon_mesh_processing::corefine_and_compute_intersection(\n              working_a, working_b, *c,\n              CGAL::Polygon_mesh_processing::parameters::\n                  throw_on_self_intersection(true),\n              CGAL::Polygon_mesh_processing::parameters::\n                  throw_on_self_intersection(true),\n              CGAL::Polygon_mesh_processing::parameters::\n                  throw_on_self_intersection(true))) {\n        return c;\n      }\n    } else {\n      if (CGAL::Polygon_mesh_processing::corefine_and_compute_intersection(\n              working_a, working_b, *c, CGAL::parameters::all_default(),\n              CGAL::parameters::all_default(),\n              CGAL::parameters::all_default())) {\n        return c;\n      }\n    }\n    if (!fix) {\n      delete c;\n      return nullptr;\n    }\n    const double direction = ((shift & (1 << 3)) ? -1 : 1) * (shift >> 4);\n    if (shift & (1 << 0)) {\n      x = kIota * direction;\n    } else {\n      x = 0;\n    }\n    if (shift & (1 << 1)) {\n      y = kIota * direction;\n    } else {\n      y = 0;\n    }\n    if (shift & (1 << 2)) {\n      z = kIota * direction;\n    } else {\n      z = 0;\n    }\n  }\n}\n\nconst Surface_mesh* UnionOfSurfaceMeshes(const Surface_mesh* a,\n                                         const Transformation* a_transform,\n                                         const Surface_mesh* b,\n                                         const Transformation* b_transform,\n                                         bool check, bool fix) {\n  if (a_transform) {\n    Surface_mesh transformed(*a);\n    CGAL::Polygon_mesh_processing::transform(*a_transform, transformed,\n                                             CGAL::parameters::all_default());\n    return UnionOfSurfaceMeshes(&transformed, nullptr, b, b_transform, check,\n                                fix);\n  } else if (b_transform) {\n    Surface_mesh transformed(*b);\n    CGAL::Polygon_mesh_processing::transform(*b_transform, transformed,\n                                             CGAL::parameters::all_default());\n    return UnionOfSurfaceMeshes(a, a_transform, &transformed, nullptr, check,\n                                fix);\n  }\n  Plane plane;\n  if (IsPlanarSurfaceMesh(plane, *a)) {\n    if (IsCoplanarSurfaceMesh(plane, *b)) {\n      Surface_mesh* result = new Surface_mesh();\n      UnionOfCoplanarSurfaceMeshes(plane, a, b, *result);\n      return result;\n    } else {\n      // Difference with the section of the other.\n      General_polygon_set_2 set;\n      General_polygon_set_2 other;\n      PlanarSurfaceMeshToPolygonSet(plane, *a, set);\n      SurfaceMeshSectionToPolygonSet(plane, *b, other);\n      set.join(other);\n      Surface_mesh* result = new Surface_mesh();\n      GeneralPolygonSetToSurfaceMesh(plane, set, *result);\n      return result;\n    }\n  } else if (IsPlanarSurfaceMesh(plane, *b)) {\n    return a;\n  }\n  double x = 0, y = 0, z = 0;\n  Surface_mesh* c = new Surface_mesh();\n  for (int shift = 0x11;; shift++) {\n    Surface_mesh working_a(*a);\n    Surface_mesh working_b(*b);\n    if (x != 0 || y != 0 || z != 0) {\n      std::cout << \"Note: Shifting union by x=\" << x << \" y=\" << y << \" z=\" << z\n                << std::endl;\n      Transformation translation(CGAL::TRANSLATION, Vector(x, y, z));\n      CGAL::Polygon_mesh_processing::transform(translation, working_b,\n                                               CGAL::parameters::all_default());\n    }\n    if (check) {\n      if (CGAL::Polygon_mesh_processing::corefine_and_compute_union(\n              working_a, working_b, *c,\n              CGAL::Polygon_mesh_processing::parameters::\n                  throw_on_self_intersection(true),\n              CGAL::Polygon_mesh_processing::parameters::\n                  throw_on_self_intersection(true),\n              CGAL::Polygon_mesh_processing::parameters::\n                  throw_on_self_intersection(true))) {\n        return c;\n      }\n    } else {\n      if (CGAL::Polygon_mesh_processing::corefine_and_compute_union(\n              working_a, working_b, *c, CGAL::parameters::all_default(),\n              CGAL::parameters::all_default(),\n              CGAL::parameters::all_default())) {\n        return c;\n      }\n    }\n    if (!fix) {\n      delete c;\n      return nullptr;\n    }\n    const double direction = ((shift & (1 << 3)) ? -1 : 1) * (shift >> 4);\n    if (shift & (1 << 0)) {\n      x = kIota * direction;\n    } else {\n      x = 0;\n    }\n    if (shift & (1 << 1)) {\n      y = kIota * direction;\n    } else {\n      y = 0;\n    }\n    if (shift & (1 << 2)) {\n      z = kIota * direction;\n    } else {\n      z = 0;\n    }\n  }\n}\n\nvoid CutOutOfSurfaceMeshes(const Surface_mesh* a,\n                           const Transformation* a_transform,\n                           const Surface_mesh* b,\n                           const Transformation* b_transform,\n                           emscripten::val emit_mesh) {\n  // Transform b to a's coordinate system.\n  if (b_transform) {\n    Surface_mesh transformed(*b);\n    CGAL::Polygon_mesh_processing::transform(*b_transform, transformed,\n                                             CGAL::parameters::all_default());\n    if (a_transform) {\n      CGAL::Polygon_mesh_processing::transform(\n          a_transform->inverse(), transformed, CGAL::parameters::all_default());\n    }\n    return CutOutOfSurfaceMeshes(a, nullptr, &transformed, nullptr, emit_mesh);\n  }\n  Surface_mesh* a_not_b = new Surface_mesh();\n  Surface_mesh* a_and_b = new Surface_mesh();\n  double x = 0, y = 0, z = 0;\n  for (int shift = 0x11;; shift++) {\n    Surface_mesh working_a(*a);\n    Surface_mesh working_b(*b);\n    if (x != 0 || y != 0 || z != 0) {\n      std::cout << \"Note: Shifting union by x=\" << x << \" y=\" << y << \" z=\" << z\n                << std::endl;\n      Transformation translation(CGAL::TRANSLATION, Vector(x, y, z));\n      CGAL::Polygon_mesh_processing::transform(translation, working_b,\n                                               CGAL::parameters::all_default());\n    }\n    std::array<boost::optional<Surface_mesh*>, 4> output;\n    output[CGAL::Polygon_mesh_processing::Corefinement::TM1_MINUS_TM2] =\n        a_not_b;\n    output[CGAL::Polygon_mesh_processing::Corefinement::INTERSECTION] = a_and_b;\n    std::array<bool, 4> result =\n        CGAL::Polygon_mesh_processing::corefine_and_compute_boolean_operations(\n            working_a, working_b, output,\n            CGAL::Polygon_mesh_processing::parameters::\n                throw_on_self_intersection(true),\n            CGAL::Polygon_mesh_processing::parameters::\n                throw_on_self_intersection(true),\n            std::make_tuple(CGAL::parameters::all_default(),\n                            CGAL::parameters::all_default(),\n                            CGAL::Polygon_mesh_processing::parameters::\n                                throw_on_self_intersection(true),\n                            CGAL::Polygon_mesh_processing::parameters::\n                                throw_on_self_intersection(true)));\n    if (result[CGAL::Polygon_mesh_processing::Corefinement::TM1_MINUS_TM2] &&\n        result[CGAL::Polygon_mesh_processing::Corefinement::INTERSECTION]) {\n      emit_mesh(a_not_b, a_and_b);\n      return;\n    }\n    const double direction = ((shift & (1 << 3)) ? -1 : 1) * (shift >> 4);\n    if (shift & (1 << 0)) {\n      x = kIota * direction;\n    } else {\n      x = 0;\n    }\n    if (shift & (1 << 1)) {\n      y = kIota * direction;\n    } else {\n      y = 0;\n    }\n    if (shift & (1 << 2)) {\n      z = kIota * direction;\n    } else {\n      z = 0;\n    }\n  }\n}\n\nvoid admitPlane(Plane& plane, emscripten::val fill_plane) {\n  Quadruple q;\n  Quadruple* qp = &q;\n  fill_plane(qp);\n  plane = Plane(q[0], q[1], q[2], q[3]);\n}\n\nbool didAdmitPlane(Plane& plane, emscripten::val fill_plane) {\n  Quadruple q;\n  Quadruple* qp = &q;\n  bool result = fill_plane(qp).as<bool>();\n  if (result) {\n    plane = Plane(q[0], q[1], q[2], q[3]);\n    return true;\n  } else {\n    return false;\n  }\n}\n\n// FIX: The case where we take a section coplanar with a surface with a hole in\n// it. CHECK: Should this produce Polygons_with_holes?\nvoid SectionOfSurfaceMesh(const Surface_mesh* input,\n                          const Transformation* transform,\n                          std::size_t plane_count,\n                          emscripten::val get_transform,\n                          emscripten::val emit_mesh, bool profile) {\n  // We could possibly be clever and transform the plane and output?\n  Surface_mesh mesh(*input);\n  CGAL::Polygon_mesh_processing::transform(*transform, mesh,\n                                           CGAL::parameters::all_default());\n\n  typedef Traits_2::X_monotone_curve_2 Segment_2;\n  typedef std::vector<Point> Polyline_type;\n  typedef std::list<Polyline_type> Polylines;\n\n  CGAL::Polygon_mesh_slicer<Surface_mesh, Kernel> slicer(mesh);\n\n  bool has_last_gps = false;\n  General_polygon_set_2 last_gps;\n\n  for (std::size_t nth_plane = 0; nth_plane < plane_count; nth_plane++) {\n    Quadruple q;\n    Quadruple* qp = &q;\n    Plane plane(0, 0, 1, 0);\n    const Transformation* section_transform =\n        get_transform(nth_plane).as<const Transformation*>(\n            emscripten::allow_raw_pointers());\n    plane = plane.transform(*section_transform);\n    if (profile) {\n      // We need the 2d forms to be interoperable.\n      plane = unitPlane(plane);\n    }\n    Arrangement_2 arrangement;\n    Polylines polylines;\n    slicer(plane, std::back_inserter(polylines));\n    for (const auto& polyline : polylines) {\n      for (std::size_t nth = 1; nth < polyline.size(); nth++) {\n        Segment_2 segment{plane.to_2d(polyline[nth - 1]),\n                          plane.to_2d(polyline[nth])};\n        insert(arrangement, segment);\n      }\n    }\n    std::vector<Polygon_with_holes_2> polygons;\n    convertArrangementToPolygonsWithHoles(arrangement, polygons);\n\n    if (profile) {\n      // Clip each section to the previous section, allowing overhangs to be\n      // eliminated.\n      General_polygon_set_2 this_gps;\n      for (const auto& polygon : polygons) {\n        this_gps.join(polygon);\n      }\n      if (has_last_gps) {\n        this_gps.intersection(last_gps);\n        polygons.clear();\n        this_gps.polygons_with_holes(std::back_inserter(polygons));\n      }\n      last_gps = this_gps;\n      has_last_gps = true;\n    }\n\n    Surface_mesh* r = new Surface_mesh();\n    PolygonsWithHolesToSurfaceMesh(plane, polygons, *r);\n    emit_mesh(r);\n  }\n}\n\nPlane ensureFacetPlane(Surface_mesh& mesh,\n                       std::unordered_map<Face_index, Plane>& facet_to_plane,\n                       std::unordered_set<Plane>& planes, Face_index facet) {\n  auto it = facet_to_plane.find(facet);\n  if (it == facet_to_plane.end()) {\n    Plane facet_plane = PlaneOfSurfaceMeshFacet(mesh, facet);\n    // We canonicalize the planes so that the 2d projections match.\n    auto canonical_plane = planes.find(facet_plane);\n    if (canonical_plane == planes.end()) {\n      planes.insert(facet_plane);\n      facet_to_plane[facet] = facet_plane;\n      return facet_plane;\n    } else {\n      facet_to_plane[facet] = *canonical_plane;\n      if (*canonical_plane != facet_plane) {\n        std::cout << \"QQ/ensureFacetPlane/mismatch\" << std::endl;\n      }\n      return *canonical_plane;\n    }\n  } else {\n    return it->second;\n  }\n}\n\nvoid OutlineSurfaceMesh(const Surface_mesh* input,\n                        const Transformation* transform,\n                        emscripten::val emit_approximate_segment) {\n  Surface_mesh mesh(*input);\n  CGAL::Polygon_mesh_processing::transform(*transform, mesh,\n                                           CGAL::parameters::all_default());\n\n  std::unordered_set<Plane> planes;\n  std::unordered_map<Face_index, Plane> facet_to_plane;\n\n  // FIX: Make this more efficient.\n  for (const auto& facet : mesh.faces()) {\n    const auto& start = mesh.halfedge(facet);\n    if (mesh.is_removed(start)) {\n      continue;\n    }\n    const Plane facet_plane =\n        ensureFacetPlane(mesh, facet_to_plane, planes, facet);\n    Vector unitNormal = unitVector(NormalOfSurfaceMeshFacet(mesh, facet));\n    Halfedge_index edge = start;\n    do {\n      bool corner = false;\n      const auto& opposite_facet = mesh.face(mesh.opposite(edge));\n      if (opposite_facet == mesh.null_face()) {\n        corner = true;\n      } else {\n        const Plane opposite_facet_plane =\n            ensureFacetPlane(mesh, facet_to_plane, planes, opposite_facet);\n        if (facet_plane != opposite_facet_plane) {\n          corner = true;\n        }\n      }\n      if (corner) {\n        Point s = mesh.point(mesh.source(edge));\n        Point t = mesh.point(mesh.target(edge));\n        emit_approximate_segment(\n            CGAL::to_double(s.x().exact()), CGAL::to_double(s.y().exact()),\n            CGAL::to_double(s.z().exact()), CGAL::to_double(t.x().exact()),\n            CGAL::to_double(t.y().exact()), CGAL::to_double(t.z().exact()),\n            CGAL::to_double(unitNormal.x().exact()),\n            CGAL::to_double(unitNormal.y().exact()),\n            CGAL::to_double(unitNormal.z().exact()));\n      }\n      const auto& next = mesh.next(edge);\n      edge = next;\n    } while (edge != start);\n  }\n}\n\nconst Surface_mesh* ProjectionToPlaneOfSurfaceMesh(\n    const Surface_mesh* input, const Transformation* transformation,\n    double direction_x, double direction_y, double direction_z, double plane_x,\n    double plane_y, double plane_z, double plane_w) {\n  Surface_mesh mesh(*input);\n  CGAL::Polygon_mesh_processing::transform(*transformation, mesh,\n                                           CGAL::parameters::all_default());\n\n  Surface_mesh* projected_mesh = new Surface_mesh(mesh);\n  auto& input_map = mesh.points();\n  auto& output_map = projected_mesh->points();\n\n  Plane plane(plane_x, plane_y, plane_z, plane_w);\n  Vector vector(direction_x, direction_y, direction_z);\n\n  // Squash the mesh.\n  for (auto& vertex : mesh.vertices()) {\n    auto result = CGAL::intersection(\n        Line(get(input_map, vertex), get(input_map, vertex) + vector), plane);\n    if (result) {\n      if (Point* point = boost::get<Point>(&*result)) {\n        put(output_map, vertex, *point);\n      }\n    }\n  }\n\n  // Simplify the projection.\n  General_polygon_set_2 set;\n  PlanarSurfaceMeshFacetsToPolygonSet(plane, *projected_mesh, set);\n  Surface_mesh* result = new Surface_mesh();\n  GeneralPolygonSetToSurfaceMesh(plane, set, *result);\n  return result;\n}\n\nvoid WireframeSurfaceMesh(const Surface_mesh* input,\n                          const Transformation* transform,\n                          emscripten::val emit_approximate_segment) {\n  Surface_mesh mesh(*input);\n  CGAL::Polygon_mesh_processing::transform(*transform, mesh,\n                                           CGAL::parameters::all_default());\n\n  for (const auto& edge : mesh.edges()) {\n    if (mesh.is_removed(edge)) {\n      continue;\n    }\n    const auto& halfedge = mesh.halfedge(edge);\n    Point s = mesh.point(mesh.source(halfedge));\n    Point t = mesh.point(mesh.target(halfedge));\n    emit_approximate_segment(\n        CGAL::to_double(s.x().exact()), CGAL::to_double(s.y().exact()),\n        CGAL::to_double(s.z().exact()), CGAL::to_double(t.x().exact()),\n        CGAL::to_double(t.y().exact()), CGAL::to_double(t.z().exact()));\n  }\n}\n\ndouble FT__to_double(const FT& ft) { return CGAL::to_double(ft); }\n\nclass Surface_mesh_explorer {\n public:\n  Surface_mesh_explorer(emscripten::val& emit_point, emscripten::val& emit_edge,\n                        emscripten::val& emit_face)\n      : emit_point_(emit_point), emit_edge_(emit_edge), emit_face_(emit_face) {}\n\n  std::map<std::int32_t, std::int32_t> facet_to_face;\n\n  const std::int32_t mapFacetToFace(std::int32_t facet) {\n    std::int32_t face = (std::int32_t)facet;\n    std::set<std::int32_t> seen;\n    for (;;) {\n      seen.insert(face);\n      std::int32_t next_face = facet_to_face[face];\n      if (next_face == face) {\n        break;\n      }\n      if (seen.find(next_face) != seen.end()) {\n        // This should be impossible.\n        std::cout << \"EE/m/cycle\" << std::endl;\n        return face;\n      }\n      face = next_face;\n    }\n    return face;\n  }\n\n  void Explore(const Surface_mesh& mesh) {\n    // Publish the vertices.\n    for (const auto& vertex : mesh.vertices()) {\n      if (mesh.is_removed(vertex)) {\n        continue;\n      }\n      const auto& p = mesh.point(vertex);\n      std::ostringstream x;\n      x << p.x().exact();\n      std::string xs = x.str();\n      std::ostringstream y;\n      y << p.y().exact();\n      std::string ys = y.str();\n      std::ostringstream z;\n      z << p.z().exact();\n      std::string zs = z.str();\n      emit_point_((std::int32_t)vertex, CGAL::to_double(p.x().exact()),\n                  CGAL::to_double(p.y().exact()),\n                  CGAL::to_double(p.z().exact()), xs, ys, zs);\n    }\n\n    facet_to_face[mesh.null_face()] = -1;\n\n    for (const auto& facet : mesh.faces()) {\n      // Initially each facet is an individual face.\n      facet_to_face[(std::int32_t)facet] = (std::int32_t)facet;\n    }\n\n    // FIX: Make this more efficient.\n    for (const auto& facet : mesh.faces()) {\n      const auto& start = mesh.halfedge(facet);\n      if (mesh.is_removed(start)) {\n        continue;\n      }\n      const Plane facet_plane = PlaneOfSurfaceMeshFacet(mesh, facet);\n      std::int32_t face = mapFacetToFace(facet);\n      Halfedge_index edge = start;\n      do {\n        const auto& opposite_facet = mesh.face(mesh.opposite(edge));\n        if (opposite_facet != mesh.null_face()) {\n          const Plane opposite_facet_plane =\n              PlaneOfSurfaceMeshFacet(mesh, opposite_facet);\n          if (facet_plane == opposite_facet_plane) {\n            std::int32_t opposite_face = mapFacetToFace(opposite_facet);\n            if (opposite_face < face) {\n              facet_to_face[face] = opposite_face;\n              face = opposite_face;\n            } else {\n              facet_to_face[opposite_face] = face;\n            }\n          } else {\n          }\n        }\n        const auto& next = mesh.next(edge);\n        edge = next;\n      } while (edge != start);\n    }\n\n    std::map<std::int32_t, Surface_mesh::Vertex_index> facet_to_vertex;\n\n    // Publish the half-edges.\n    for (const auto& edge : mesh.halfedges()) {\n      if (mesh.is_removed(edge)) {\n        continue;\n      }\n      const auto& next = mesh.next(edge);\n      const auto& source = mesh.source(edge);\n      const auto& opposite = mesh.opposite(edge);\n      const auto& facet = mesh.face(edge);\n      facet_to_vertex[facet] = source;\n      std::int32_t face = mapFacetToFace(facet);\n      emit_edge_((std::int32_t)edge, (std::int32_t)source, (std::int32_t)next,\n                 (std::int32_t)opposite, (std::int32_t)facet,\n                 (std::int32_t)face, face);\n    }\n\n    // Publish the faces.\n    for (const auto& entry : facet_to_face) {\n      const auto& facet = entry.first;\n      const auto& face = entry.second;\n      if (face == -1 || facet != face) {\n        continue;\n      }\n      const Plane plane =\n          PlaneOfSurfaceMeshFacet(mesh, Surface_mesh::Face_index(facet));\n      const auto a = plane.a().exact();\n      const auto b = plane.b().exact();\n      const auto c = plane.c().exact();\n      const auto d = plane.d().exact();\n      std::ostringstream x;\n      x << a;\n      std::string xs = x.str();\n      std::ostringstream y;\n      y << b;\n      std::string ys = y.str();\n      std::ostringstream z;\n      z << c;\n      std::string zs = z.str();\n      std::ostringstream w;\n      w << d;\n      std::string ws = w.str();\n      const double xd = CGAL::to_double(a);\n      const double yd = CGAL::to_double(b);\n      const double zd = CGAL::to_double(c);\n      const double ld = std::sqrt(xd * xd + yd * yd + zd * zd);\n      const double wd = CGAL::to_double(d);\n      // Normalize the approximate plane normal.\n      emit_face_(facet, xd / ld, yd / ld, zd / ld, wd, xs, ys, zs, ws);\n    }\n  }\n\n private:\n  emscripten::val& emit_point_;\n  emscripten::val& emit_edge_;\n  emscripten::val& emit_face_;\n};\n\nvoid Surface_mesh__explore(const Surface_mesh* mesh, emscripten::val emit_point,\n                           emscripten::val emit_edge,\n                           emscripten::val emit_face) {\n  Surface_mesh_explorer explorer(emit_point, emit_edge, emit_face);\n  explorer.Explore(*mesh);\n}\n\nstd::string SerializeSurfaceMesh(const Surface_mesh* mesh,\n                                 emscripten::val emit_error) {\n  // CHECK: We assume the mesh is compact.\n\n  std::ostringstream s;\n\n  size_t number_of_vertices = mesh->number_of_vertices();\n\n  s << number_of_vertices << \"\\n\";\n  std::unordered_map<Vertex_index, size_t> vertex_map;\n  size_t vertex_count = 0;\n  for (const Vertex_index vertex : mesh->vertices()) {\n    const Point& p = mesh->point(vertex);\n    s << p.x().exact() << \" \" << p.y().exact() << \" \" << p.z().exact() << \"\\n\";\n    vertex_map[vertex] = vertex_count++;\n  }\n  s << \"\\n\";\n\n  s << mesh->number_of_faces() << \"\\n\";\n  for (const Face_index facet : mesh->faces()) {\n    const auto& start = mesh->halfedge(facet);\n    std::size_t edge_count = 0;\n    {\n      Halfedge_index edge = start;\n      do {\n        edge_count++;\n        edge = mesh->next(edge);\n      } while (edge != start);\n    }\n    s << edge_count;\n    {\n      Halfedge_index edge = start;\n      do {\n        std::size_t vertex(vertex_map[mesh->source(edge)]);\n        if (vertex >= number_of_vertices) {\n          std::cout << \"Vertex \" << vertex << \" out of range \"\n                    << number_of_vertices << std::endl;\n          emit_error(vertex, number_of_vertices);\n        }\n        s << \" \" << vertex;\n        edge = mesh->next(edge);\n      } while (edge != start);\n    }\n    s << \"\\n\";\n  }\n\n  return s.str();\n}\n\nvoid DescribeSurfaceMesh(const Surface_mesh* mesh, emscripten::val emit) {\n  emit(mesh->number_of_vertices(), mesh->number_of_faces());\n}\n\nconst Surface_mesh* DeserializeSurfaceMesh(std::string serialization) {\n  Surface_mesh* mesh = new Surface_mesh();\n  std::istringstream s(serialization);\n\n  std::size_t number_of_vertices;\n\n  s >> number_of_vertices;\n\n  for (std::size_t vertex = 0; vertex < number_of_vertices; vertex++) {\n    FT x;\n    s >> x;\n\n    FT y;\n    s >> y;\n\n    FT z;\n    s >> z;\n\n    mesh->add_vertex(Point{x, y, z});\n  }\n\n  std::size_t number_of_facets;\n\n  s >> number_of_facets;\n\n  for (std::size_t facet = 0; facet < number_of_facets; facet++) {\n    std::size_t number_of_vertices_in_facet;\n    s >> number_of_vertices_in_facet;\n    std::vector<Vertex_index> vertices;\n    for (std::size_t nth = 0; nth < number_of_vertices_in_facet; nth++) {\n      std::size_t vertex;\n      s >> vertex;\n\n      if (vertex > number_of_vertices) {\n        std::cout << \"Vertex \" << vertex << \" out of range \"\n                  << number_of_vertices << std::endl;\n      }\n\n      vertices.push_back(Vertex_index(vertex));\n    }\n    mesh->add_face(vertices);\n  }\n\n  return mesh;\n}\n\nbool Surface_mesh__triangulate_faces(Surface_mesh* mesh) {\n  return CGAL::Polygon_mesh_processing::triangulate_faces(mesh->faces(), *mesh);\n}\n\nconst Surface_mesh* ComputeConvexHullAsSurfaceMesh(emscripten::val fill) {\n  Points points;\n  Points* points_ptr = &points;\n  fill(points_ptr);\n  Surface_mesh* mesh = new Surface_mesh();\n  // compute convex hull of non-collinear points\n  CGAL::convex_hull_3(points.begin(), points.end(), *mesh);\n  return mesh;\n}\n\nconst Surface_mesh* ComputeAlphaShapeAsSurfaceMesh(int component_limit,\n                                                   emscripten::val fill) {\n  typedef CGAL::Alpha_shape_vertex_base_3<Kernel> Vb;\n  typedef CGAL::Alpha_shape_cell_base_3<Kernel> Fb;\n  typedef CGAL::Triangulation_data_structure_3<Vb, Fb> Tds;\n  typedef CGAL::Delaunay_triangulation_3<Kernel, Tds> Triangulation_3;\n  typedef CGAL::Alpha_shape_3<Triangulation_3> Alpha_shape_3;\n  typedef Kernel::Point_3 Point;\n  typedef Alpha_shape_3::Alpha_iterator Alpha_iterator;\n\n  Points points;\n  Points* points_ptr = &points;\n  fill(points_ptr);\n  Alpha_shape_3 alpha_shape(points.begin(), points.end());\n  Alpha_iterator optimizer = alpha_shape.find_optimal_alpha(component_limit);\n  alpha_shape.set_alpha(*optimizer);\n\n  Surface_mesh* mesh = new Surface_mesh();\n\n  std::vector<Alpha_shape_3::Facet> Facets;\n  alpha_shape.get_alpha_shape_facets(std::back_inserter(Facets),\n                                     Alpha_shape_3::REGULAR);\n  for (auto i = 0; i < Facets.size(); i++) {\n    // checks for exterior cells\n    if (alpha_shape.classify(Facets[i].first) != Alpha_shape_3::EXTERIOR) {\n      Facets[i] = alpha_shape.mirror_facet(Facets[i]);\n    }\n\n    CGAL_assertion(alpha_shape.classify(Facets[i].first) ==\n                   Alpha_shape_3::EXTERIOR);\n\n    // gets indices of alpha shape and gets consistent orientation\n    int indices[3] = {(Facets[i].second + 1) % 4, (Facets[i].second + 2) % 4,\n                      (Facets[i].second + 3) % 4};\n    if (Facets[i].second % 2 == 0) {\n      std::swap(indices[0], indices[1]);\n    }\n\n    // adds data to cgal mesh\n    for (auto j = 0; j < 3; ++j) {\n      mesh->add_vertex(Facets[i].first->vertex(indices[j])->point());\n    }\n    auto v0 = static_cast<boost::graph_traits<Surface_mesh>::vertex_descriptor>(\n        3 * i);\n    auto v1 = static_cast<boost::graph_traits<Surface_mesh>::vertex_descriptor>(\n        3 * i + 1);\n    auto v2 = static_cast<boost::graph_traits<Surface_mesh>::vertex_descriptor>(\n        3 * i + 2);\n    mesh->add_face(v0, v1, v2);\n  }\n\n  return mesh;\n}\n\nvoid ComputeAlphaShape2AsPolygonSegments(size_t component_limit, double alpha,\n                                         bool regularized, emscripten::val fill,\n                                         emscripten::val emit) {\n  typedef CGAL::Alpha_shape_vertex_base_2<Kernel> VertexBase;\n  typedef CGAL::Alpha_shape_face_base_2<Kernel> FaceBase;\n  typedef CGAL::Triangulation_data_structure_2<VertexBase, FaceBase>\n      TriangulationData;\n  typedef CGAL::Delaunay_triangulation_2<Kernel, TriangulationData>\n      Triangulation_2;\n  typedef CGAL::Alpha_shape_2<Triangulation_2> Alpha_shape_2;\n  typedef Alpha_shape_2::Alpha_shape_edges_iterator Alpha_shape_edges_iterator;\n\n  Point_2s points;\n  Point_2s* points_ptr = &points;\n  fill(points_ptr);\n\n  Alpha_shape_2 alpha_shape(\n      points.begin(), points.end(), FT(alpha),\n      regularized ? Alpha_shape_2::REGULARIZED : Alpha_shape_2::GENERAL);\n\n  if (component_limit > 0) {\n    auto optimizer = alpha_shape.find_optimal_alpha(component_limit);\n    alpha_shape.set_alpha(*optimizer);\n  }\n\n  Alpha_shape_edges_iterator it;\n  for (it = alpha_shape.alpha_shape_edges_begin();\n       it != alpha_shape.alpha_shape_edges_end(); ++it) {\n    const auto& segment = alpha_shape.segment(*it);\n    const auto& s = segment.source();\n    const auto& t = segment.target();\n    emit(CGAL::to_double(s.x().exact()), CGAL::to_double(s.y().exact()),\n         CGAL::to_double(t.x().exact()), CGAL::to_double(t.y().exact()));\n  }\n}\n\ntemplate <class Kernel, class Container>\nvoid print_polygon(const CGAL::Polygon_2<Kernel, Container>& P) {\n  typename CGAL::Polygon_2<Kernel, Container>::Vertex_const_iterator vit;\n  std::cout << \"[ \" << P.size() << \" vertices:\";\n  for (vit = P.vertices_begin(); vit != P.vertices_end(); ++vit)\n    std::cout << \" (\" << *vit << ')';\n  std::cout << \" ]\" << std::endl;\n}\n\ntemplate <class Kernel, class Container>\nvoid print_polygon_with_holes(\n    const CGAL::Polygon_with_holes_2<Kernel, Container>& pwh) {\n  if (!pwh.is_unbounded()) {\n    std::cout << \"{ Outer boundary = \";\n    print_polygon(pwh.outer_boundary());\n  } else\n    std::cout << \"{ Unbounded polygon.\" << std::endl;\n  typename CGAL::Polygon_with_holes_2<Kernel, Container>::Hole_const_iterator\n      hit;\n  unsigned int k = 1;\n  std::cout << \" \" << pwh.number_of_holes() << \" holes:\" << std::endl;\n  for (hit = pwh.holes_begin(); hit != pwh.holes_end(); ++hit, ++k) {\n    std::cout << \" Hole #\" << k << \" = \";\n    print_polygon(*hit);\n  }\n  std::cout << \" }\" << std::endl;\n}\n\nvoid OffsetOfPolygonWithHoles(double initial, double step, double limit,\n                              std::size_t hole_count,\n                              emscripten::val fill_plane,\n                              emscripten::val fill_boundary,\n                              emscripten::val fill_hole,\n                              emscripten::val emit_polygon,\n                              emscripten::val emit_point) {\n  typedef CGAL::Gps_segment_traits_2<Kernel> Traits;\n  Plane plane;\n  admitPlane(plane, fill_plane);\n  plane = unitPlane(plane);\n\n  Polygon_with_holes_2 insetting_boundary;\n  std::vector<Polygon_2> holes;\n\n  for (std::size_t nth = 0; nth < hole_count; nth++) {\n    Points points;\n    Points* points_ptr = &points;\n    fill_hole(points_ptr, nth);\n    Polygon_2 hole;\n    for (const auto& point : points) {\n      hole.push_back(plane.to_2d(point));\n    }\n    if (hole.orientation() == CGAL::Sign::POSITIVE) {\n      hole.reverse_orientation();\n    }\n    if (!hole.is_simple()) {\n      std::cout << \"Hole is not simple\" << std::endl;\n      return;\n    }\n    holes.push_back(hole);\n  }\n\n  Polygon_2 boundary;\n\n  {\n    Points points;\n    Points* points_ptr = &points;\n    fill_boundary(points_ptr);\n    for (const auto& point : points) {\n      boundary.push_back(plane.to_2d(point));\n    }\n    if (boundary.orientation() == CGAL::Sign::NEGATIVE) {\n      boundary.reverse_orientation();\n    }\n    if (!boundary.is_simple()) {\n      std::cout << \"Boundary is not simple\" << std::endl;\n      return;\n    }\n\n    // Stick a box around the boundary (which will now form a hole).\n    CGAL::Bbox_2 bb = boundary.bbox();\n    bb.dilate(10);\n\n    Polygon_2 frame;\n    frame.push_back(Point_2(bb.xmin(), bb.ymin()));\n    frame.push_back(Point_2(bb.xmax(), bb.ymin()));\n    frame.push_back(Point_2(bb.xmax(), bb.ymax()));\n    frame.push_back(Point_2(bb.xmin(), bb.ymax()));\n    if (frame.orientation() == CGAL::Sign::NEGATIVE) {\n      frame.reverse_orientation();\n    }\n\n    std::vector<Polygon_2> boundaries{boundary};\n\n    insetting_boundary =\n        Polygon_with_holes_2(frame, holes.begin(), holes.end());\n  }\n\n  double offset = initial;\n\n  for (;;) {\n    CGAL::General_polygon_set_2<Traits> boundaries;\n\n    Polygon_2 tool;\n    for (double a = 0; a < CGAL_PI * 2; a += CGAL_PI / 16) {\n      tool.push_back(Point_2(sin(-a) * offset, cos(-a) * offset));\n    }\n    if (tool.orientation() == CGAL::Sign::NEGATIVE) {\n      std::cout << \"Reverse tool\" << std::endl;\n      tool.reverse_orientation();\n    }\n\n    // This computes the offsetting of the holes.\n    Polygon_with_holes_2 inset_boundary =\n        CGAL::minkowski_sum_2(insetting_boundary, tool);\n\n    Polygon_with_holes_2 offset_boundary =\n        CGAL::minkowski_sum_2(boundary, tool);\n\n    boundaries.join(CGAL::General_polygon_set_2<Traits>(offset_boundary));\n\n    // We just extract the holes, which are the offset holes.\n    for (auto hole = inset_boundary.holes_begin();\n         hole != inset_boundary.holes_end(); ++hole) {\n      if (hole->orientation() == CGAL::Sign::NEGATIVE) {\n        Polygon_2 boundary = *hole;\n        boundary.reverse_orientation();\n        boundaries.difference(CGAL::General_polygon_set_2<Traits>(boundary));\n      } else {\n        boundaries.difference(CGAL::General_polygon_set_2<Traits>(*hole));\n      }\n    }\n\n    bool emitted = false;\n\n    std::vector<Traits::Polygon_with_holes_2> polygons;\n    boundaries.polygons_with_holes(std::back_inserter(polygons));\n\n    for (const Traits::Polygon_with_holes_2& polygon : polygons) {\n      const auto& outer = polygon.outer_boundary();\n      emit_polygon(false);\n      for (auto vertex = outer.vertices_begin(); vertex != outer.vertices_end();\n           ++vertex) {\n        auto p = plane.to_3d(Point_2(CGAL::to_double(vertex->x().exact()),\n                                     CGAL::to_double(vertex->y().exact())));\n        std::ostringstream x;\n        x << p.x().exact();\n        std::ostringstream y;\n        y << p.y().exact();\n        std::ostringstream z;\n        z << p.z().exact();\n        emit_point(CGAL::to_double(p.x().exact()),\n                   CGAL::to_double(p.y().exact()),\n                   CGAL::to_double(p.z().exact()), x.str(), y.str(), z.str());\n        emitted = true;\n      }\n      for (auto hole = polygon.holes_begin(); hole != polygon.holes_end();\n           ++hole) {\n        emit_polygon(true);\n        for (auto vertex = hole->vertices_begin();\n             vertex != hole->vertices_end(); ++vertex) {\n          auto p = plane.to_3d(Point_2(CGAL::to_double(vertex->x().exact()),\n                                       CGAL::to_double(vertex->y().exact())));\n          std::ostringstream x;\n          x << p.x().exact();\n          std::ostringstream y;\n          y << p.y().exact();\n          std::ostringstream z;\n          z << p.z().exact();\n          emit_point(CGAL::to_double(p.x().exact()),\n                     CGAL::to_double(p.y().exact()),\n                     CGAL::to_double(p.z().exact()), x.str(), y.str(), z.str());\n          emitted = true;\n        }\n      }\n    }\n\n    if (!emitted) {\n      break;\n    }\n    if (step <= 0) {\n      break;\n    }\n    offset += step;\n    if (limit <= 0) {\n      continue;\n    }\n    if (offset >= limit) {\n      break;\n    }\n  }\n}\n\nvoid InsetOfPolygonWithHoles(double initial, double step, double limit,\n                             std::size_t hole_count, emscripten::val fill_plane,\n                             emscripten::val fill_boundary,\n                             emscripten::val fill_hole,\n                             emscripten::val emit_polygon,\n                             emscripten::val emit_point) {\n  typedef CGAL::Gps_segment_traits_2<Kernel> Traits;\n  Plane plane;\n  admitPlane(plane, fill_plane);\n  plane = unitPlane(plane);\n\n  Polygon_with_holes_2 insetting_boundary;\n\n  {\n    Points points;\n    Points* points_ptr = &points;\n    fill_boundary(points_ptr);\n    Polygon_2 boundary;\n    for (const auto& point : points) {\n      boundary.push_back(plane.to_2d(point));\n    }\n    if (boundary.orientation() == CGAL::Sign::POSITIVE) {\n      boundary.reverse_orientation();\n    }\n    if (!boundary.is_simple()) {\n      std::cout << \"Boundary is not simple\" << std::endl;\n      return;\n    }\n\n    // Stick a box around the boundary (which will now form a hole).\n    CGAL::Bbox_2 bb = boundary.bbox();\n    bb.dilate(10);\n\n    Polygon_2 frame;\n    frame.push_back(Point_2(bb.xmin(), bb.ymin()));\n    frame.push_back(Point_2(bb.xmax(), bb.ymin()));\n    frame.push_back(Point_2(bb.xmax(), bb.ymax()));\n    frame.push_back(Point_2(bb.xmin(), bb.ymax()));\n    if (frame.orientation() == CGAL::Sign::NEGATIVE) {\n      frame.reverse_orientation();\n    }\n\n    std::vector<Polygon_2> boundaries{boundary};\n\n    insetting_boundary =\n        Polygon_with_holes_2(frame, boundaries.begin(), boundaries.end());\n  }\n\n  std::vector<Polygon_2> holes;\n  for (std::size_t nth = 0; nth < hole_count; nth++) {\n    Points points;\n    Points* points_ptr = &points;\n    fill_hole(points_ptr, nth);\n    Polygon_2 hole;\n    for (const auto& point : points) {\n      hole.push_back(plane.to_2d(point));\n    }\n    if (hole.orientation() == CGAL::Sign::NEGATIVE) {\n      hole.reverse_orientation();\n    }\n    if (!hole.is_simple()) {\n      std::cout << \"Hole is not simple\" << std::endl;\n      return;\n    }\n    holes.push_back(hole);\n  }\n\n  double offset = initial;\n\n  for (;;) {\n    CGAL::General_polygon_set_2<Traits> boundaries;\n\n    Polygon_2 tool;\n    for (double a = 0; a < CGAL_PI * 2; a += CGAL_PI / 16) {\n      tool.push_back(Point_2(sin(-a) * offset, cos(-a) * offset));\n    }\n    if (tool.orientation() == CGAL::Sign::NEGATIVE) {\n      std::cout << \"Reverse tool\" << std::endl;\n      tool.reverse_orientation();\n    }\n\n    Polygon_with_holes_2 inset_boundary =\n        CGAL::minkowski_sum_2(insetting_boundary, tool);\n\n    // We just extract the holes, which are the inset boundary.\n    for (auto hole = inset_boundary.holes_begin();\n         hole != inset_boundary.holes_end(); ++hole) {\n      if (hole->orientation() == CGAL::Sign::NEGATIVE) {\n        Polygon_2 boundary = *hole;\n        boundary.reverse_orientation();\n        boundaries.join(CGAL::General_polygon_set_2<Traits>(boundary));\n      } else {\n        boundaries.join(CGAL::General_polygon_set_2<Traits>(*hole));\n      }\n    }\n\n    for (const auto& hole : holes) {\n      Polygon_with_holes_2 offset_hole = CGAL::minkowski_sum_2(hole, tool);\n      boundaries.difference(CGAL::General_polygon_set_2<Traits>(offset_hole));\n    }\n\n    bool emitted = false;\n\n    std::vector<Traits::Polygon_with_holes_2> polygons;\n    boundaries.polygons_with_holes(std::back_inserter(polygons));\n\n    for (const Traits::Polygon_with_holes_2& polygon : polygons) {\n      const auto& outer = polygon.outer_boundary();\n      emit_polygon(false);\n      for (auto edge = outer.edges_begin(); edge != outer.edges_end(); ++edge) {\n        if (edge->source() == edge->target()) {\n          std::cout << \"QQ/skip zero length edge\" << std::endl;\n          continue;\n        }\n        auto p =\n            plane.to_3d(Point_2(CGAL::to_double(edge->source().x().exact()),\n                                CGAL::to_double(edge->source().y().exact())));\n        std::ostringstream x;\n        x << p.x().exact();\n        std::ostringstream y;\n        y << p.y().exact();\n        std::ostringstream z;\n        z << p.z().exact();\n        emit_point(CGAL::to_double(p.x().exact()),\n                   CGAL::to_double(p.y().exact()),\n                   CGAL::to_double(p.z().exact()), x.str(), y.str(), z.str());\n        emitted = true;\n      }\n      for (auto hole = polygon.holes_begin(); hole != polygon.holes_end();\n           ++hole) {\n        emit_polygon(true);\n        for (auto edge = hole->edges_begin(); edge != hole->edges_end();\n             ++edge) {\n          if (edge->source() == edge->target()) {\n            std::cout << \"QQ/skip zero length edge\" << std::endl;\n            continue;\n          }\n          auto p =\n              plane.to_3d(Point_2(CGAL::to_double(edge->source().x().exact()),\n                                  CGAL::to_double(edge->source().y().exact())));\n          std::ostringstream x;\n          x << p.x().exact();\n          std::ostringstream y;\n          y << p.y().exact();\n          std::ostringstream z;\n          z << p.z().exact();\n          emit_point(CGAL::to_double(p.x().exact()),\n                     CGAL::to_double(p.y().exact()),\n                     CGAL::to_double(p.z().exact()), x.str(), y.str(), z.str());\n          emitted = true;\n        }\n      }\n    }\n\n    if (!emitted) {\n      break;\n    }\n    if (step <= 0) {\n      break;\n    }\n    offset += step;\n    if (limit <= 0) {\n      continue;\n    }\n    if (offset >= limit) {\n      break;\n    }\n  }\n}\n\ntemplate <typename P>\nbool admitPolygonWithHoles(std::size_t nth_polygon, const Plane& plane,\n                           P& polygon, emscripten::val fill_boundary,\n                           emscripten::val fill_hole) {\n  Points points;\n  Points* points_ptr = &points;\n  fill_boundary(points_ptr, nth_polygon);\n  if (points.size() == 0) {\n    return false;\n  }\n  Polygon_2 boundary;\n  for (const auto& point : points) {\n    boundary.push_back(plane.to_2d(point));\n  }\n  if (boundary.orientation() == CGAL::Sign::NEGATIVE) {\n    boundary.reverse_orientation();\n  }\n  if (!boundary.is_simple()) {\n    std::cout << \"Boundary is not simple\" << std::endl;\n    return false;\n  }\n\n  std::vector<Polygon_2> holes;\n  for (;;) {\n    Points points;\n    Points* points_ptr = &points;\n    fill_hole(points_ptr, nth_polygon, holes.size());\n    if (points.size() == 0) {\n      break;\n    }\n    Polygon_2 hole;\n    for (const auto& point : points) {\n      hole.push_back(plane.to_2d(point));\n    }\n    if (hole.orientation() == CGAL::Sign::POSITIVE) {\n      hole.reverse_orientation();\n    }\n    if (!hole.is_simple()) {\n      std::cout << \"Hole is not simple\" << std::endl;\n      return false;\n    }\n    holes.push_back(hole);\n  }\n\n  polygon = P(boundary, holes.begin(), holes.end());\n  return true;\n}\n\ntemplate <typename P>\nvoid admitPolygonsWithHoles(const Plane& plane, std::vector<P>& polygons,\n                            emscripten::val fill_boundary,\n                            emscripten::val fill_hole) {\n  for (;;) {\n    Polygon_with_holes_2 polygon;\n    if (!admitPolygonWithHoles(polygons.size(), plane, polygon, fill_boundary,\n                               fill_hole)) {\n      return;\n    }\n    polygons.push_back(polygon);\n  }\n}\n\nvoid emitPlane(const Plane& plane, emscripten::val& emit_plane) {\n  const auto a = plane.a().exact();\n  const auto b = plane.b().exact();\n  const auto c = plane.c().exact();\n  const auto d = plane.d().exact();\n  std::ostringstream x;\n  x << a;\n  std::string xs = x.str();\n  std::ostringstream y;\n  y << b;\n  std::string ys = y.str();\n  std::ostringstream z;\n  z << c;\n  std::string zs = z.str();\n  std::ostringstream w;\n  w << d;\n  std::string ws = w.str();\n  const double xd = CGAL::to_double(a);\n  const double yd = CGAL::to_double(b);\n  const double zd = CGAL::to_double(c);\n  const double ld = std::sqrt(xd * xd + yd * yd + zd * zd);\n  const double wd = CGAL::to_double(d);\n  // Normalize the approximate plane normal.\n  emit_plane(xd / ld, yd / ld, zd / ld, wd, xs, ys, zs, ws);\n}\n\ntemplate <typename P>\nvoid emitPolygonsWithHoles(const Plane& plane, const std::vector<P>& polygons,\n                           emscripten::val& emit_polygon,\n                           emscripten::val& emit_point) {\n  for (const P& polygon : polygons) {\n    // std::cout << \"QQ/emitPolygonsWithHoles: \" << std::endl;\n    // print_polygon_with_holes(polygon);\n    const auto& outer = polygon.outer_boundary();\n    emit_polygon(false);\n    for (auto edge = outer.edges_begin(); edge != outer.edges_end(); ++edge) {\n      if (edge->source() == edge->target()) {\n        // Skip zero length edges.\n        std::cout << \"QQ/skip zero length edge\" << std::endl;\n        continue;\n      }\n      auto p =\n          plane.to_3d(Point_2(CGAL::to_double(edge->source().x().exact()),\n                              CGAL::to_double(edge->source().y().exact())));\n      auto p2 =\n          plane.to_3d(Point_2(CGAL::to_double(edge->target().x().exact()),\n                              CGAL::to_double(edge->target().y().exact())));\n      if (p == p2) {\n        // This produced a zero length edge in 3 space.\n        // CHECK: For some mysterious reason this might not be a zero length\n        // edge in 2 space. std::cout << \"QQ/dup\" << std::endl;\n        continue;\n      }\n      std::ostringstream x;\n      x << p.x().exact();\n      std::ostringstream y;\n      y << p.y().exact();\n      std::ostringstream z;\n      z << p.z().exact();\n      emit_point(CGAL::to_double(p.x().exact()), CGAL::to_double(p.y().exact()),\n                 CGAL::to_double(p.z().exact()), x.str(), y.str(), z.str());\n    }\n    for (auto hole = polygon.holes_begin(); hole != polygon.holes_end();\n         ++hole) {\n      emit_polygon(true);\n      for (auto edge = hole->edges_begin(); edge != hole->edges_end(); ++edge) {\n        if (edge->source() == edge->target()) {\n          // Skip zero length edges.\n          std::cout << \"QQ/skip zero length edge\" << std::endl;\n          continue;\n        }\n        auto p =\n            plane.to_3d(Point_2(CGAL::to_double(edge->source().x().exact()),\n                                CGAL::to_double(edge->source().y().exact())));\n        std::ostringstream x;\n        x << p.x().exact();\n        std::ostringstream y;\n        y << p.y().exact();\n        std::ostringstream z;\n        z << p.z().exact();\n        emit_point(CGAL::to_double(p.x().exact()),\n                   CGAL::to_double(p.y().exact()),\n                   CGAL::to_double(p.z().exact()), x.str(), y.str(), z.str());\n      }\n    }\n  }\n}\n\nconst int kAdd = 1;\nconst int kCut = 2;\nconst int kClip = 3;\n\nvoid BooleansOfPolygonsWithHoles(const Plane& plane,\n                                 emscripten::val get_operation,\n                                 emscripten::val fill_boundary,\n                                 emscripten::val fill_hole,\n                                 emscripten::val emit_polygon,\n                                 emscripten::val emit_point) {\n  typedef CGAL::Gps_segment_traits_2<Kernel> Traits;\n\n  std::vector<Traits::Polygon_with_holes_2> input;\n  std::vector<Traits::Polygon_with_holes_2> output;\n\n  admitPolygonsWithHoles(plane, input, fill_boundary, fill_hole);\n\n  CGAL::General_polygon_set_2<Traits> set;\n  int nthOperation = 0;\n  for (const auto& polygon : input) {\n    switch (get_operation(nthOperation++).as<int>()) {\n      case kAdd:\n        set.join(polygon);\n        break;\n      case kCut:\n        set.difference(polygon);\n        break;\n      case kClip:\n        set.intersection(polygon);\n        break;\n    }\n  }\n  set.polygons_with_holes(std::back_inserter(output));\n\n  emitPolygonsWithHoles(plane, output, emit_polygon, emit_point);\n}\n\nvoid BooleansOfPolygonsWithHolesApproximate(\n    double x, double y, double z, double w, emscripten::val get_operation,\n    emscripten::val fill_boundary, emscripten::val fill_hole,\n    emscripten::val emit_polygon, emscripten::val emit_point) {\n  BooleansOfPolygonsWithHoles(Plane(to_FT(x), to_FT(y), to_FT(z), to_FT(w)),\n                              get_operation, fill_boundary, fill_hole,\n                              emit_polygon, emit_point);\n}\n\nvoid BooleansOfPolygonsWithHolesExact(std::string a, std::string b,\n                                      std::string c, std::string d,\n                                      emscripten::val get_operation,\n                                      emscripten::val fill_boundary,\n                                      emscripten::val fill_hole,\n                                      emscripten::val emit_polygon,\n                                      emscripten::val emit_point) {\n  BooleansOfPolygonsWithHoles(Plane(to_FT(a), to_FT(b), to_FT(c), to_FT(d)),\n                              get_operation, fill_boundary, fill_hole,\n                              emit_polygon, emit_point);\n}\n\nvoid convertSurfaceMeshFacesToArrangements(\n    Surface_mesh& mesh,\n    std::unordered_map<Plane, Arrangement_2>& arrangements) {\n  std::unordered_set<Plane> planes;\n  std::unordered_map<Face_index, Plane> facet_to_plane;\n\n  // FIX: Make this more efficient.\n  for (const auto& facet : mesh.faces()) {\n    const auto& start = mesh.halfedge(facet);\n    if (mesh.is_removed(start)) {\n      continue;\n    }\n    const Plane facet_plane =\n        ensureFacetPlane(mesh, facet_to_plane, planes, facet);\n    if (facet_plane == Plane(0, 0, 0, 0)) {\n      std::cout << \"CSMTA/FIXME: degenerate plane\" << std::endl;\n      continue;\n    }\n    Arrangement_2& arrangement = arrangements[facet_plane];\n    Halfedge_index edge = start;\n    do {\n      bool corner = false;\n      const auto& opposite_facet = mesh.face(mesh.opposite(edge));\n      if (opposite_facet == mesh.null_face()) {\n        corner = true;\n      } else {\n        const Plane opposite_facet_plane =\n            ensureFacetPlane(mesh, facet_to_plane, planes, opposite_facet);\n        if (facet_plane != opposite_facet_plane) {\n          corner = true;\n        }\n      }\n      if (corner) {\n        Point_2 s = facet_plane.to_2d(mesh.point(mesh.source(edge)));\n        Point_2 t = facet_plane.to_2d(mesh.point(mesh.target(edge)));\n\n        Segment_2 segment{s, t};\n        insert(arrangement, segment);\n      }\n      const auto& next = mesh.next(edge);\n      edge = next;\n    } while (edge != start);\n  }\n}\n\nvoid emitArrangementsAsPolygonsWithHoles(\n    const std::unordered_map<Plane, Arrangement_2>& arrangements,\n    emscripten::val emit_plane, emscripten::val emit_polygon,\n    emscripten::val emit_point) {\n  for (const auto& entry : arrangements) {\n    const Plane& plane = entry.first;\n    const Arrangement_2& arrangement = entry.second;\n    std::vector<Polygon_with_holes_2> polygons;\n    convertArrangementToPolygonsWithHoles(arrangement, polygons);\n    emitPlane(plane, emit_plane);\n    emitPolygonsWithHoles(plane, polygons, emit_polygon, emit_point);\n  }\n}\n\nvoid ArrangePolygonsWithHoles(std::size_t count, emscripten::val fill_plane,\n                              emscripten::val fill_boundary,\n                              emscripten::val fill_hole,\n                              emscripten::val emit_plane,\n                              emscripten::val emit_polygon,\n                              emscripten::val emit_point) {\n  std::unordered_map<Plane, Arrangement_2> arrangements;\n\n  for (std::size_t nth_polygon = 0; nth_polygon < count; nth_polygon++) {\n    Plane plane;\n    admitPlane(plane, fill_plane);\n    plane = unitPlane(plane);\n    Arrangement_2& arrangement = arrangements[plane];\n    Polygon_with_holes_2 polygon;\n    admitPolygonWithHoles(nth_polygon, plane, polygon, fill_boundary,\n                          fill_hole);\n    for (auto it = polygon.outer_boundary().edges_begin();\n         it != polygon.outer_boundary().edges_end(); ++it) {\n      insert(arrangement, *it);\n    }\n    for (auto hole = polygon.holes_begin(); hole != polygon.holes_end();\n         ++hole) {\n      for (auto it = hole->edges_begin(); it != hole->edges_end(); ++it) {\n        insert(arrangement, *it);\n      }\n    }\n  }\n\n  emitArrangementsAsPolygonsWithHoles(arrangements, emit_plane, emit_polygon,\n                                      emit_point);\n}\n\n// FIX: Accept exact plane.\nvoid ArrangePaths(Plane plane, bool do_triangulate, emscripten::val fill,\n                  emscripten::val emit_polygon, emscripten::val emit_point) {\n  typedef CGAL::Arr_segment_traits_2<Kernel> Traits_2;\n  typedef Traits_2::Point_2 Point_2;\n  typedef Traits_2::X_monotone_curve_2 Segment_2;\n  typedef CGAL::Arrangement_2<Traits_2> Arrangement_2;\n  typedef Arrangement_2::Vertex_handle Vertex_handle;\n  typedef Arrangement_2::Halfedge_handle Halfedge_handle;\n\n  Arrangement_2 arrangement;\n\n  std::set<std::vector<Kernel::FT>> segments;\n\n  for (;;) {\n    Points points;\n    auto* p = &points;\n    fill(p);\n    if (points.empty()) {\n      break;\n    }\n    Point_2s point_2s;\n    for (const auto& point : points) {\n      auto point_2 = plane.to_2d(point);\n      point_2s.push_back(point_2);\n    }\n    for (std::size_t i = 0; i + 1 < point_2s.size(); i += 2) {\n      if (segments.find({point_2s[i].x(), point_2s[i].y(), point_2s[i + 1].x(),\n                         point_2s[i + 1].y()}) != segments.end()) {\n        continue;\n      }\n      if (point_2s[i] == point_2s[i + 1]) {\n        // Skip zero length segments.\n        continue;\n      }\n      // Add the segment\n      Segment_2 segment{point_2s[i], point_2s[i + 1]};\n      insert(arrangement, segment);\n\n      // Remember the edges we've inserted.\n      segments.insert({point_2s[i].x(), point_2s[i].y(), point_2s[i + 1].x(),\n                       point_2s[i + 1].y()});\n      // In both directions.\n      segments.insert({point_2s[i + 1].x(), point_2s[i + 1].y(),\n                       point_2s[i].x(), point_2s[i].y()});\n    }\n  }\n\n  std::queue<Arrangement_2::Face_const_handle> undecided;\n  CGAL::Unique_hash_map<Arrangement_2::Face_const_handle, bool> positive_faces;\n  CGAL::Unique_hash_map<Arrangement_2::Face_const_handle, bool> negative_faces;\n\n  for (Arrangement_2::Face_iterator face = arrangement.faces_begin();\n       face != arrangement.faces_end(); ++face) {\n    if (!face->has_outer_ccb()) {\n      negative_faces[face] = true;\n    } else {\n      undecided.push(face);\n    }\n  }\n\n  while (!undecided.empty()) {\n    Arrangement_2::Face_const_handle face = undecided.front();\n    undecided.pop();\n    if (positive_faces[face]) {\n      for (Arrangement_2::Hole_const_iterator hole = face->holes_begin();\n           hole != face->holes_end(); ++hole) {\n        negative_faces[(*hole)->twin()->face()] = true;\n        positive_faces[(*hole)->twin()->face()] = false;\n      }\n      continue;\n    }\n    if (negative_faces[face]) {\n      for (Arrangement_2::Hole_const_iterator hole = face->holes_begin();\n           hole != face->holes_end(); ++hole) {\n        positive_faces[(*hole)->twin()->face()] = true;\n        negative_faces[(*hole)->twin()->face()] = false;\n      }\n      continue;\n    }\n    bool decided = false;\n    Arrangement_2::Ccb_halfedge_const_circulator start = face->outer_ccb();\n    Arrangement_2::Ccb_halfedge_const_circulator edge = start;\n    do {\n      if (negative_faces[edge->twin()->face()]) {\n        positive_faces[face] = true;\n        decided = true;\n        break;\n      }\n    } while (++edge != start);\n    if (!decided) {\n      edge = start;\n      do {\n        if (positive_faces[edge->twin()->face()]) {\n          negative_faces[face] = true;\n          decided = true;\n          break;\n        }\n      } while (++edge != start);\n    }\n    undecided.push(face);\n  }\n\n  if (do_triangulate) {\n    CGAL::Polygon_triangulation_decomposition_2<Kernel> triangulate;\n    for (Arrangement_2::Face_iterator face = arrangement.faces_begin();\n         face != arrangement.faces_end(); ++face) {\n      if (!positive_faces[face] || !face->has_outer_ccb()) {\n        continue;\n      }\n      Arrangement_2::Ccb_halfedge_const_circulator start = face->outer_ccb();\n      Arrangement_2::Ccb_halfedge_const_circulator edge = start;\n      Polygon_2 polygon;\n      do {\n        polygon.push_back(edge->source()->point());\n      } while (++edge != start);\n\n      std::vector<Polygon_2> holes;\n      for (Arrangement_2::Hole_iterator hole = face->holes_begin();\n           hole != face->holes_end(); ++hole) {\n        Polygon_2 polygon;\n        Arrangement_2::Ccb_halfedge_const_circulator start = *hole;\n        Arrangement_2::Ccb_halfedge_const_circulator edge = start;\n        do {\n          polygon.push_back(edge->source()->point());\n        } while (++edge != start);\n        holes.push_back(polygon);\n      }\n      Polygon_with_holes_2 polygon_with_holes(polygon, holes.begin(),\n                                              holes.end());\n      std::vector<Polygon_2> triangles;\n      triangulate(polygon_with_holes, std::back_inserter(triangles));\n      for (const auto& triangle : triangles) {\n        emit_polygon(false);\n        for (const auto& p2 : triangle) {\n          Point p3 = plane.to_3d(p2);\n          auto e3 = p3;\n          std::ostringstream x;\n          x << e3.x().exact();\n          std::ostringstream y;\n          y << e3.y().exact();\n          std::ostringstream z;\n          z << e3.z().exact();\n          emit_point(\n              CGAL::to_double(p3.x().exact()), CGAL::to_double(p3.y().exact()),\n              CGAL::to_double(p3.z().exact()), x.str(), y.str(), z.str());\n        }\n      }\n    }\n  } else {\n    for (Arrangement_2::Face_iterator face = arrangement.faces_begin();\n         face != arrangement.faces_end(); ++face) {\n      if (!positive_faces[face] || !face->has_outer_ccb()) {\n        continue;\n      }\n      Arrangement_2::Ccb_halfedge_const_circulator start = face->outer_ccb();\n      Arrangement_2::Ccb_halfedge_const_circulator edge = start;\n      // Can we build Polygon_with_holes_2 here?\n      emit_polygon(false);\n      do {\n        Point p3 = plane.to_3d(edge->source()->point());\n        auto e3 = p3;\n        std::ostringstream x;\n        x << e3.x().exact();\n        std::ostringstream y;\n        y << e3.y().exact();\n        std::ostringstream z;\n        z << e3.z().exact();\n        emit_point(CGAL::to_double(p3.x().exact()),\n                   CGAL::to_double(p3.y().exact()),\n                   CGAL::to_double(p3.z().exact()), x.str(), y.str(), z.str());\n      } while (++edge != start);\n\n      // Emit holes\n      for (Arrangement_2::Hole_iterator hole = face->holes_begin();\n           hole != face->holes_end(); ++hole) {\n        emit_polygon(true);\n        Arrangement_2::Ccb_halfedge_const_circulator start = *hole;\n        Arrangement_2::Ccb_halfedge_const_circulator edge = start;\n        do {\n          Point p3 = plane.to_3d(edge->source()->point());\n          auto e3 = p3;\n          std::ostringstream x;\n          x << e3.x().exact();\n          std::ostringstream y;\n          y << e3.y().exact();\n          std::ostringstream z;\n          z << e3.z().exact();\n          emit_point(\n              CGAL::to_double(p3.x().exact()), CGAL::to_double(p3.y().exact()),\n              CGAL::to_double(p3.z().exact()), x.str(), y.str(), z.str());\n        } while (++edge != start);\n      }\n    }\n  }\n}\n\nvoid ArrangePathsApproximate(double x, double y, double z, double w,\n                             bool triangulate, emscripten::val fill,\n                             emscripten::val emit_polygon,\n                             emscripten::val emit_point) {\n  ArrangePaths(Plane(x, y, z, w), triangulate, fill, emit_polygon, emit_point);\n}\n\nvoid ArrangePathsExact(std::string x, std::string y, std::string z,\n                       std::string w, bool triangulate, emscripten::val fill,\n                       emscripten::val emit_polygon,\n                       emscripten::val emit_point) {\n  ArrangePaths(Plane(to_FT(x), to_FT(y), to_FT(z), to_FT(w)), triangulate, fill,\n               emit_polygon, emit_point);\n}\n\nvoid FromSurfaceMeshToPolygonsWithHoles(const Surface_mesh* input,\n                                        const Transformation* transform,\n                                        emscripten::val emit_plane,\n                                        emscripten::val emit_polygon,\n                                        emscripten::val emit_point) {\n  Surface_mesh mesh(*input);\n  CGAL::Polygon_mesh_processing::transform(*transform, mesh,\n                                           CGAL::parameters::all_default());\n\n  std::unordered_map<Plane, Arrangement_2> arrangements;\n  convertSurfaceMeshFacesToArrangements(mesh, arrangements);\n  emitArrangementsAsPolygonsWithHoles(arrangements, emit_plane, emit_polygon,\n                                      emit_point);\n}\n\nbool computeFitPolygon(const Polygon_with_holes_2& space,\n                       const Polygon_with_holes_2& shape, Point_2& picked) {\n  Polygon_with_holes_2 insetting_boundary;\n\n  {\n    // Stick a box around the boundary (which will now form a hole).\n    CGAL::Bbox_2 bb = space.outer_boundary().bbox();\n    // 10 is wrong -- it should be a dilated boundary box of shape.\n    bb.dilate(10);\n\n    Polygon_2 frame;\n    frame.push_back(Point_2(bb.xmin(), bb.ymin()));\n    frame.push_back(Point_2(bb.xmax(), bb.ymin()));\n    frame.push_back(Point_2(bb.xmax(), bb.ymax()));\n    frame.push_back(Point_2(bb.xmin(), bb.ymax()));\n    if (frame.orientation() == CGAL::Sign::NEGATIVE) {\n      frame.reverse_orientation();\n    }\n\n    std::vector<Polygon_2> boundaries{space.outer_boundary()};\n\n    insetting_boundary =\n        Polygon_with_holes_2(frame, boundaries.begin(), boundaries.end());\n  }\n\n  std::vector<Polygon_2> holes;\n  for (auto it = space.holes_begin(); it != space.holes_end(); ++it) {\n    Polygon_2 hole = *it;\n    if (hole.orientation() == CGAL::Sign::NEGATIVE) {\n      hole.reverse_orientation();\n    }\n    if (!hole.is_simple()) {\n      std::cout << \"Hole is not simple\" << std::endl;\n      return false;\n    }\n    holes.push_back(hole);\n  }\n\n  General_polygon_set_2 boundaries;\n\n  Polygon_with_holes_2 inset_boundary =\n      CGAL::minkowski_sum_2(insetting_boundary, shape);\n\n  // We just extract the holes, which are the inset boundary.\n  for (auto hole = inset_boundary.holes_begin();\n       hole != inset_boundary.holes_end(); ++hole) {\n    if (hole->orientation() == CGAL::Sign::NEGATIVE) {\n      Polygon_2 boundary = *hole;\n      boundary.reverse_orientation();\n      boundaries.join(General_polygon_set_2(boundary));\n    } else {\n      boundaries.join(General_polygon_set_2(*hole));\n    }\n  }\n\n  for (const auto& hole : holes) {\n    Polygon_with_holes_2 offset_hole = CGAL::minkowski_sum_2(hole, shape);\n    boundaries.difference(General_polygon_set_2(offset_hole));\n  }\n\n  std::vector<Polygon_with_holes_2> polygons;\n  boundaries.polygons_with_holes(std::back_inserter(polygons));\n\n  std::vector<Point_2> points;\n  for (const auto& polygon : polygons) {\n    points.insert(std::end(points), polygon.outer_boundary().vertices_begin(),\n                  polygon.outer_boundary().vertices_end());\n    for (const auto& point : polygon.outer_boundary()) {\n      points.push_back(point);\n    }\n    for (auto hole = polygon.holes_begin(); hole != polygon.holes_end();\n         ++hole) {\n      points.insert(std::end(points), hole->vertices_begin(),\n                    hole->vertices_end());\n    }\n  }\n\n  // Just pick the first point for now.\n\n  picked = points[0];\n\n  return true;\n}\n\nconst Surface_mesh* MinkowskiDifferenceOfSurfaceMeshes(\n    const Surface_mesh* input_mesh, const Transformation* input_transform,\n    const Surface_mesh* offset_mesh, const Transformation* offset_transform) {\n  typedef CGAL::Nef_polyhedron_3<Kernel> Nef_polyhedron;\n\n  Nef_polyhedron input_nef(*input_mesh);\n  input_nef.transform(*input_transform);\n  Nef_polyhedron input_nef_boundary = input_nef.boundary();\n  Nef_polyhedron offset_nef(*offset_mesh);\n  offset_nef.transform(*offset_transform);\n  // Subtract the shell of the nef.\n  Nef_polyhedron outer_nef =\n      input_nef - minkowski_sum_3(input_nef_boundary, offset_nef);\n\n  std::vector<Surface_mesh> input_meshes;\n  CGAL::Polygon_mesh_processing::split_connected_components(*input_mesh,\n                                                            input_meshes);\n\n  // Unfortunately minkowski sum doesn't do cavities, so let's do them here and\n  // cut them out.\n\n  for (const Surface_mesh& hole : input_meshes) {\n    if (!CGAL::Polygon_mesh_processing::does_bound_a_volume(hole)) {\n      continue;\n    }\n    if (CGAL::Polygon_mesh_processing::is_outward_oriented(hole)) {\n      // Not a cavity.\n      continue;\n    }\n    Nef_polyhedron input_nef(hole);\n    Nef_polyhedron input_nef_boundary = input_nef.boundary();\n    // Add the shell of the nef.\n    Nef_polyhedron result_nef =\n        input_nef + minkowski_sum_3(input_nef_boundary, offset_nef);\n    outer_nef -= result_nef;\n  }\n\n  Surface_mesh* result_mesh = new Surface_mesh;\n  CGAL::convert_nef_polyhedron_to_polygon_mesh(outer_nef, *result_mesh);\n  return result_mesh;\n}\n\nconst Surface_mesh* MinkowskiSumOfSurfaceMeshes(\n    const Surface_mesh* input_mesh, const Transformation* input_transform,\n    const Surface_mesh* offset_mesh, const Transformation* offset_transform) {\n  typedef CGAL::Nef_polyhedron_3<Kernel> Nef_polyhedron;\n\n  Nef_polyhedron input_nef(*input_mesh);\n  input_nef.transform(*input_transform);\n  Nef_polyhedron input_nef_boundary = input_nef.boundary();\n  Nef_polyhedron offset_nef(*offset_mesh);\n  offset_nef.transform(*offset_transform);\n  // Add the shell of the nef.\n  Nef_polyhedron outer_nef =\n      input_nef + minkowski_sum_3(input_nef_boundary, offset_nef);\n\n  std::vector<Surface_mesh> input_meshes;\n  CGAL::Polygon_mesh_processing::split_connected_components(*input_mesh,\n                                                            input_meshes);\n\n  // Unfortunately minkowski sum doesn't do cavities, so let's do them here and\n  // cut them out.\n\n  for (const Surface_mesh& hole : input_meshes) {\n    if (!CGAL::Polygon_mesh_processing::does_bound_a_volume(hole)) {\n      continue;\n    }\n    if (CGAL::Polygon_mesh_processing::is_outward_oriented(hole)) {\n      // Not a cavity.\n      continue;\n    }\n    Nef_polyhedron input_nef(hole);\n    Nef_polyhedron input_nef_boundary = input_nef.boundary();\n    // Subtract the shell of the nef.\n    Nef_polyhedron result_nef =\n        input_nef - minkowski_sum_3(input_nef_boundary, offset_nef);\n    outer_nef -= result_nef;\n  }\n\n  Surface_mesh* result_mesh = new Surface_mesh;\n  CGAL::convert_nef_polyhedron_to_polygon_mesh(outer_nef, *result_mesh);\n  return result_mesh;\n}\n\nconst Surface_mesh* MinkowskiShellOfSurfaceMeshes(\n    const Surface_mesh* input_mesh, const Transformation* input_transform,\n    const Surface_mesh* offset_mesh, const Transformation* offset_transform) {\n  typedef CGAL::Nef_polyhedron_3<Kernel> Nef_polyhedron;\n\n  Nef_polyhedron input_nef(*input_mesh);\n  input_nef.transform(*input_transform);\n  Nef_polyhedron input_nef_boundary = input_nef.boundary();\n  Nef_polyhedron offset_nef(*offset_mesh);\n  offset_nef.transform(*offset_transform);\n  // Take the shell of the nef.\n  Nef_polyhedron outer_nef = minkowski_sum_3(input_nef_boundary, offset_nef);\n\n  std::vector<Surface_mesh> input_meshes;\n  CGAL::Polygon_mesh_processing::split_connected_components(*input_mesh,\n                                                            input_meshes);\n\n  // Unfortunately minkowski sum doesn't do cavities, so let's do them here and\n  // cut them out.\n\n  for (const Surface_mesh& hole : input_meshes) {\n    if (!CGAL::Polygon_mesh_processing::does_bound_a_volume(hole)) {\n      continue;\n    }\n    if (CGAL::Polygon_mesh_processing::is_outward_oriented(hole)) {\n      // Not a cavity.\n      continue;\n    }\n    Nef_polyhedron input_nef(hole);\n    Nef_polyhedron input_nef_boundary = input_nef.boundary();\n    // Take the shell of the nef.\n    Nef_polyhedron result_nef = minkowski_sum_3(input_nef_boundary, offset_nef);\n    outer_nef += result_nef;\n  }\n\n  Surface_mesh* result_mesh = new Surface_mesh;\n  CGAL::convert_nef_polyhedron_to_polygon_mesh(outer_nef, *result_mesh);\n  return result_mesh;\n}\n\nbool Surface_mesh__is_closed(const Surface_mesh* mesh) {\n  return CGAL::is_closed(*mesh);\n}\n\nbool Surface_mesh__is_empty(const Surface_mesh* mesh) {\n  return CGAL::is_empty(*mesh);\n}\n\nbool Surface_mesh__is_valid_halfedge_graph(const Surface_mesh* mesh) {\n  return CGAL::is_valid_halfedge_graph(*mesh);\n}\n\nbool Surface_mesh__is_valid_face_graph(const Surface_mesh* mesh) {\n  return CGAL::is_valid_face_graph(*mesh);\n}\n\nbool Surface_mesh__is_valid_polygon_mesh(const Surface_mesh* mesh) {\n  return CGAL::is_valid_polygon_mesh(*mesh);\n}\n\nvoid Surface_mesh__bbox(const Surface_mesh* input,\n                        const Transformation* transform, emscripten::val emit) {\n  Surface_mesh mesh(*input);\n  CGAL::Polygon_mesh_processing::transform(*transform, mesh,\n                                           CGAL::parameters::all_default());\n  CGAL::Bbox_3 box = CGAL::Polygon_mesh_processing::bbox(mesh);\n  emit(box.xmin(), box.ymin(), box.zmin(), box.xmax(), box.ymax(), box.zmax());\n}\n\nconst Transformation* Transformation__identity() {\n  return new Transformation(CGAL::IDENTITY);\n}\n\nconst Transformation* Transformation__compose(const Transformation* a,\n                                              const Transformation* b) {\n  return new Transformation(*a * *b);\n}\n\nconst Transformation* Transformation__inverse(const Transformation* a) {\n  return new Transformation(a->inverse());\n}\n\nvoid Transformation__to_exact(const Transformation* t, emscripten::val put) {\n  for (int i = 0; i < 3; i++) {\n    for (int j = 0; j < 4; j++) {\n      auto value = t->cartesian(i, j).exact();\n      std::ostringstream serialization;\n      serialization << value;\n      put(serialization.str());\n    }\n  }\n\n  auto value = t->cartesian(3, 3).exact();\n  std::ostringstream serialization;\n  serialization << value;\n  put(serialization.str());\n}\n\nvoid Transformation__to_approximate(const Transformation* t,\n                                    emscripten::val put) {\n  for (int i = 0; i < 3; i++) {\n    for (int j = 0; j < 4; j++) {\n      FT value = t->cartesian(i, j);\n      put(CGAL::to_double(value.exact()));\n    }\n  }\n\n  FT value = t->cartesian(3, 3);\n  put(CGAL::to_double(value.exact()));\n}\n\nFT get_double(emscripten::val get) { return to_FT(get().as<double>()); }\n\nFT get_string(emscripten::val get) { return to_FT(get().as<std::string>()); }\n\nconst Transformation* Transformation__from_exact(emscripten::val get) {\n  Transformation* t = new Transformation(\n      get_string(get), get_string(get), get_string(get), get_string(get),\n      get_string(get), get_string(get), get_string(get), get_string(get),\n      get_string(get), get_string(get), get_string(get), get_string(get),\n      get_string(get));\n  return t;\n}\n\nconst Transformation* Transformation__from_approximate(emscripten::val get) {\n  Transformation* t = new Transformation(\n      get_double(get), get_double(get), get_double(get), get_double(get),\n      get_double(get), get_double(get), get_double(get), get_double(get),\n      get_double(get), get_double(get), get_double(get), get_double(get),\n      get_double(get));\n  return t;\n}\n\nconst Transformation* Transformation__translate(double x, double y, double z) {\n  return new Transformation(CGAL::TRANSLATION, Vector(x, y, z));\n}\n\nconst Transformation* Transformation__scale(double x, double y, double z) {\n  return new Transformation(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 1);\n}\n\nconst Transformation* Transformation__rotate_x(double a) {\n  RT sin_alpha, cos_alpha, w;\n  compute_degrees(a, sin_alpha, cos_alpha, w);\n  return new Transformation(w, 0, 0, 0, 0, cos_alpha, -sin_alpha, 0, 0,\n                            sin_alpha, cos_alpha, 0, w);\n}\n\nTransformation TransformationFromXTurn(double turn) {\n  RT sin_alpha, cos_alpha, w;\n  compute_turn(turn, sin_alpha, cos_alpha, w);\n  return Transformation(w, 0, 0, 0, 0, cos_alpha, -sin_alpha, 0, 0, sin_alpha,\n                        cos_alpha, 0, w);\n}\n\nconst Transformation* Transformation__rotate_y(double a) {\n  RT sin_alpha, cos_alpha, w;\n  compute_degrees(a, sin_alpha, cos_alpha, w);\n  return new Transformation(cos_alpha, 0, -sin_alpha, 0, 0, w, 0, 0, sin_alpha,\n                            0, cos_alpha, 0, w);\n}\n\nconst Transformation* Transformation__rotate_z(double a) {\n  RT sin_alpha, cos_alpha, w;\n  compute_degrees(a, sin_alpha, cos_alpha, w);\n  return new Transformation(cos_alpha, sin_alpha, 0, 0, -sin_alpha, cos_alpha,\n                            0, 0, 0, 0, w, 0, w);\n}\n\nconst Transformation* Transformation__rotate_z_toward(double x, double y) {\n  RT sin_alpha, cos_alpha, w;\n  CGAL::rational_rotation_approximation(FT(x), FT(y), sin_alpha, cos_alpha, w,\n                                        RT(1), RT(1000));\n  return new Transformation(cos_alpha, sin_alpha, 0, 0, -sin_alpha, cos_alpha,\n                            0, 0, 0, 0, w, 0, w);\n}\n\n// https://gist.github.com/kevinmoran/b45980723e53edeb8a5a43c49f134724\nTransformation Orient(Vector current, Vector target) {\n  if (current == target) {\n    return Transformation(CGAL::IDENTITY);\n  }\n\n  Vector axis = CGAL::cross_product(target, current);\n\n  FT cos_a = target * current;\n\n  FT k = 1 / (1 + cos_a);\n\n  return Transformation(\n      (axis.x() * axis.x() * k) + cos_a, (axis.y() * axis.x() * k) - axis.z(),\n      (axis.z() * axis.x() * k) + axis.y(),\n      (axis.x() * axis.y() * k) + axis.z(), (axis.y() * axis.y() * k) + cos_a,\n      (axis.z() * axis.y() * k) - axis.x(),\n      (axis.x() * axis.z() * k) - axis.y(),\n      (axis.y() * axis.z() * k) + axis.x(), (axis.z() * axis.z() * k) + cos_a);\n}\n\nTransformation Righten(Vector current) {\n  Vector target(0, 0, 1);\n  if (target * current == -1) {\n    return TransformationFromXTurn(0.5);\n  } else {\n    return Orient(current, target);\n  }\n}\n\nconst Transformation* InverseSegmentTransform(double startX, double startY,\n                                              double startZ, double endX,\n                                              double endY, double endZ,\n                                              double normalX, double normalY,\n                                              double normalZ) {\n  Transformation orient =\n      Righten(unitVector(Vector(normalX, normalY, normalZ))) *\n      Transformation(CGAL::TRANSLATION, Vector(-startX, -startY, -startZ));\n\n  Point oriented_end = Point(endX, endY, endZ).transform(orient);\n\n  Transformation align(CGAL::IDENTITY);\n  if (oriented_end.y() != 0) {\n    RT sin_alpha, cos_alpha, w;\n    CGAL::rational_rotation_approximation(oriented_end.x(), oriented_end.y(),\n                                          sin_alpha, cos_alpha, w, RT(1),\n                                          RT(1000));\n    Transformation rotation(cos_alpha, sin_alpha, 0, 0, -sin_alpha, cos_alpha,\n                            0, 0, 0, 0, w, 0, w);\n    align = rotation;  // .inverse();\n  }\n\n  return new Transformation(align * orient);\n}\n\n#else  // TEST_ONLY\n\nstruct TestException : public std::exception {\n  const char* what() const throw() { return \"MyException\"; }\n};\n\nvoid test() {\n#if 1\n  try {\n    std::cout << \"Thrown\" << std::endl;\n    throw TestException();\n  } catch (TestException& e) {\n    std::cout << \"Caught\" << std::endl;\n  }\n#endif\n  std::cout << \"Done\" << std::endl;\n}\n\n#endif\n\nusing emscripten::select_const;\nusing emscripten::select_overload;\n\n#if 0\nunsigned int getTotalMemory()\n{\n  return EM_ASM_INT(return HEAP8.length);\n}\n#endif\n\nEMSCRIPTEN_BINDINGS(module) {\n#ifdef TEST_ONLY\n  emscripten::function(\"test\", &test, emscripten::allow_raw_pointers());\n#else\n\n  emscripten::class_<Transformation>(\"Transformation\").constructor<>();\n  emscripten::function(\"Transformation__compose\", &Transformation__compose,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"Transformation__identity\", &Transformation__identity,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"Transformation__inverse\", &Transformation__inverse,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"Transformation__from_approximate\",\n                       &Transformation__from_approximate,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"Transformation__from_exact\",\n                       &Transformation__from_exact,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"Transformation__to_approximate\",\n                       &Transformation__to_approximate,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"Transformation__to_exact\", &Transformation__to_exact,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"Transformation__translate\", &Transformation__translate,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"Transformation__scale\", &Transformation__scale,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"Transformation__rotate_x\", &Transformation__rotate_x,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"Transformation__rotate_y\", &Transformation__rotate_y,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"Transformation__rotate_z\", &Transformation__rotate_z,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"Transformation__rotate_z_toward\",\n                       &Transformation__rotate_z_toward,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"InverseSegmentTransform\", &InverseSegmentTransform,\n                       emscripten::allow_raw_pointers());\n\n  emscripten::class_<Polygon_2>(\"Polygon_2\").constructor<>();\n  emscripten::class_<Polygon_with_holes_2>(\"Polygon_with_holes_2\")\n      .constructor<>();\n\n  emscripten::class_<SurfaceMeshAndTransform>(\"SurfaceMeshAndTransform\")\n      .constructor<>()\n      .function(\"set_mesh\", &SurfaceMeshAndTransform::set_mesh,\n                emscripten::allow_raw_pointers())\n      .function(\"set_transform\", &SurfaceMeshAndTransform::set_transform,\n                emscripten::allow_raw_pointers());\n\n  emscripten::class_<Triples>(\"Triples\")\n      .constructor<>()\n      .function(\"push_back\",\n                select_overload<void(const Triple&)>(&Triples::push_back))\n      .function(\"size\", select_overload<size_t() const>(&Triples::size));\n\n  emscripten::function(\"addTriple\", &addTriple,\n                       emscripten::allow_raw_pointers());\n\n  emscripten::class_<DoubleTriples>(\"DoubleTriples\")\n      .constructor<>()\n      .function(\"push_back\", select_overload<void(const DoubleTriple&)>(\n                                 &DoubleTriples::push_back))\n      .function(\"size\", select_overload<size_t() const>(&DoubleTriples::size));\n\n  emscripten::function(\"addDoubleTriple\", &addDoubleTriple,\n                       emscripten::allow_raw_pointers());\n\n  emscripten::class_<Quadruple>(\"Quadruple\").constructor<>();\n  emscripten::function(\"fillQuadruple\", &fillQuadruple,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"fillExactQuadruple\", &fillExactQuadruple,\n                       emscripten::allow_raw_pointers());\n\n  emscripten::function(\"addPoint\", &addPoint, emscripten::allow_raw_pointers());\n  emscripten::function(\"addExactPoint\", &addExactPoint,\n                       emscripten::allow_raw_pointers());\n\n  emscripten::class_<Points>(\"Points\")\n      .constructor<>()\n      .function(\"push_back\",\n                select_overload<void(const Point&)>(&Points::push_back))\n      .function(\"size\", select_overload<size_t() const>(&Points::size));\n\n  emscripten::function(\"addPoint_2\", &addPoint_2,\n                       emscripten::allow_raw_pointers());\n\n  emscripten::class_<Point_2s>(\"Point_2s\")\n      .constructor<>()\n      .function(\"push_back\",\n                select_overload<void(const Point&)>(&Points::push_back))\n      .function(\"size\", select_overload<size_t() const>(&Points::size));\n\n  emscripten::class_<Polygon>(\"Polygon\").constructor<>().function(\n      \"size\", select_overload<size_t() const>(&Polygon::size));\n\n  emscripten::function(\"Polygon__push_back\", &Polygon__push_back,\n                       emscripten::allow_raw_pointers());\n\n  emscripten::class_<Polygons>(\"Polygons\")\n      .constructor<>()\n      .function(\"push_back\",\n                select_overload<void(const Polygon&)>(&Polygons::push_back))\n      .function(\"size\", select_overload<size_t() const>(&Polygons::size));\n\n  emscripten::class_<Face_index>(\"Face_index\").constructor<std::size_t>();\n  emscripten::class_<Halfedge_index>(\"Halfedge_index\")\n      .constructor<std::size_t>();\n  emscripten::class_<Vertex_index>(\"Vertex_index\").constructor<std::size_t>();\n\n  emscripten::class_<Surface_mesh>(\"Surface_mesh\")\n      .constructor<>()\n      .function(\"add_vertex_1\", (Vertex_index(Surface_mesh::*)(const Point&)) &\n                                    Surface_mesh::add_vertex)\n      .function(\"add_edge_2\",\n                (Halfedge_index(Surface_mesh::*)(Vertex_index, Vertex_index)) &\n                    Surface_mesh::add_edge)\n      .function(\"add_face_3\", (Face_index(Surface_mesh::*)(\n                                  Vertex_index, Vertex_index, Vertex_index)) &\n                                  Surface_mesh::add_face)\n      .function(\"add_face_4\",\n                (Face_index(Surface_mesh::*)(Vertex_index, Vertex_index,\n                                             Vertex_index, Vertex_index)) &\n                    Surface_mesh::add_face)\n      .function(\"is_valid\",\n                select_overload<bool(bool) const>(&Surface_mesh::is_valid))\n      .function(\"is_empty\", &Surface_mesh::is_empty)\n      .function(\"number_of_vertices\", &Surface_mesh::number_of_vertices)\n      .function(\"number_of_halfedges\", &Surface_mesh::number_of_halfedges)\n      .function(\"number_of_edges\", &Surface_mesh::number_of_edges)\n      .function(\"number_of_faces\", &Surface_mesh::number_of_faces)\n      .function(\"has_garbage\", &Surface_mesh::has_garbage);\n\n  emscripten::function(\"Surface_mesh__EachFace\", &Surface_mesh__EachFace,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"LoftBetweenCongruentSurfaceMeshes\",\n                       &LoftBetweenCongruentSurfaceMeshes,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"ExtrusionOfSurfaceMesh\", &ExtrusionOfSurfaceMesh,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"ExtrusionToPlaneOfSurfaceMesh\",\n                       &ExtrusionToPlaneOfSurfaceMesh,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"ProjectionToPlaneOfSurfaceMesh\",\n                       &ProjectionToPlaneOfSurfaceMesh,\n                       emscripten::allow_raw_pointers());\n\n  emscripten::function(\"Surface_mesh__halfedge_to_target\",\n                       &Surface_mesh__halfedge_to_target,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"Surface_mesh__halfedge_to_face\",\n                       &Surface_mesh__halfedge_to_face,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"Surface_mesh__halfedge_to_next_halfedge\",\n                       &Surface_mesh__halfedge_to_next_halfedge,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"Surface_mesh__halfedge_to_prev_halfedge\",\n                       &Surface_mesh__halfedge_to_prev_halfedge,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"Surface_mesh__halfedge_to_opposite_halfedge\",\n                       &Surface_mesh__halfedge_to_opposite_halfedge,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"Surface_mesh__vertex_to_halfedge\",\n                       &Surface_mesh__vertex_to_halfedge,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"Surface_mesh__face_to_halfedge\",\n                       &Surface_mesh__face_to_halfedge,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"Surface_mesh__vertex_to_point\",\n                       &Surface_mesh__vertex_to_point,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"Surface_mesh__collect_garbage\",\n                       &Surface_mesh__collect_garbage,\n                       emscripten::allow_raw_pointers());\n\n  emscripten::function(\"Surface_mesh__add_vertex\", &Surface_mesh__add_vertex,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"Surface_mesh__add_exact\", &Surface_mesh__add_exact,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"Surface_mesh__add_face\", &Surface_mesh__add_face,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"Surface_mesh__add_face_vertices\",\n                       &Surface_mesh__add_face_vertices,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"Surface_mesh__add_edge\", &Surface_mesh__add_edge,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"Surface_mesh__set_edge_target\",\n                       &Surface_mesh__set_edge_target,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"Surface_mesh__set_edge_next\",\n                       &Surface_mesh__set_edge_next,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"Surface_mesh__set_edge_face\",\n                       &Surface_mesh__set_edge_face,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"Surface_mesh__set_face_edge\",\n                       &Surface_mesh__set_face_edge,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"Surface_mesh__set_vertex_edge\",\n                       &Surface_mesh__set_vertex_edge,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"Surface_mesh__set_vertex_halfedge_to_border_halfedge\",\n                       &Surface_mesh__set_vertex_halfedge_to_border_halfedge,\n                       emscripten::allow_raw_pointers());\n\n  emscripten::class_<Point>(\"Point\")\n      .constructor<float, float, float>()\n      .function(\"hx\", &Point::hx)\n      .function(\"hy\", &Point::hy)\n      .function(\"hz\", &Point::hz)\n      .function(\"hw\", &Point::hw)\n      .function(\"x\", &Point::x)\n      .function(\"y\", &Point::y)\n      .function(\"z\", &Point::z);\n\n  emscripten::class_<SurfaceMeshQuery>(\"SurfaceMeshQuery\")\n      .constructor<const Surface_mesh*, const Transformation*>()\n      .function(\"clipSegmentApproximate\",\n                &SurfaceMeshQuery::clipSegmentApproximate)\n      .function(\"isIntersectingPointApproximate\",\n                &SurfaceMeshQuery::isIntersectingPointApproximate);\n\n  emscripten::function(\"SerializeSurfaceMesh\", &SerializeSurfaceMesh,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"DescribeSurfaceMesh\", &DescribeSurfaceMesh,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"DeserializeSurfaceMesh\", &DeserializeSurfaceMesh,\n                       emscripten::allow_raw_pointers());\n\n  emscripten::function(\"FromPolygonSoupToSurfaceMesh\",\n                       &FromPolygonSoupToSurfaceMesh,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"DifferenceOfSurfaceMeshes\", &DifferenceOfSurfaceMeshes,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"CutClosedSurfaceMeshIncrementally\",\n                       &CutClosedSurfaceMeshIncrementally,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"CutSurfaceMeshesIncrementally\",\n                       &CutSurfaceMeshesIncrementally,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"JoinSurfaceMeshesIncrementally\",\n                       &JoinSurfaceMeshesIncrementally,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"DisjointSurfaceMeshesIncrementally\",\n                       &DisjointSurfaceMeshesIncrementally,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"IntersectionOfSurfaceMeshes\",\n                       &IntersectionOfSurfaceMeshes,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"UnionOfSurfaceMeshes\", &UnionOfSurfaceMeshes,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"CutOutOfSurfaceMeshes\", &CutOutOfSurfaceMeshes,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"SeparateSurfaceMesh\", &SeparateSurfaceMesh,\n                       emscripten::allow_raw_pointers());\n\n  emscripten::function(\"TwistSurfaceMesh\", &TwistSurfaceMesh,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"BendSurfaceMesh\", &BendSurfaceMesh,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"TaperSurfaceMesh\", &TaperSurfaceMesh,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"PushSurfaceMesh\", &PushSurfaceMesh,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"OutlineSurfaceMesh\", &OutlineSurfaceMesh,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"WireframeSurfaceMesh\", &WireframeSurfaceMesh,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"FromSurfaceMeshToPolygonsWithHoles\",\n                       &FromSurfaceMeshToPolygonsWithHoles,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"ComputeCentroidOfSurfaceMesh\",\n                       &ComputeCentroidOfSurfaceMesh,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"ComputeNormalOfSurfaceMesh\",\n                       &ComputeNormalOfSurfaceMesh,\n                       emscripten::allow_raw_pointers());\n\n  emscripten::function(\"BooleansOfPolygonsWithHolesApproximate\",\n                       &BooleansOfPolygonsWithHolesApproximate);\n  emscripten::function(\"BooleansOfPolygonsWithHolesExact\",\n                       &BooleansOfPolygonsWithHolesExact);\n\n  emscripten::function(\"ReverseFaceOrientationsOfSurfaceMesh\",\n                       &ReverseFaceOrientationsOfSurfaceMesh,\n                       emscripten::allow_raw_pointers());\n\n  emscripten::function(\"IsBadSurfaceMesh\", &IsBadSurfaceMesh,\n                       emscripten::allow_raw_pointers());\n\n  emscripten::function(\"FT__to_double\", &FT__to_double,\n                       emscripten::allow_raw_pointers());\n\n  emscripten::function(\"Surface_mesh__explore\", &Surface_mesh__explore,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"Surface_mesh__triangulate_faces\",\n                       &Surface_mesh__triangulate_faces,\n                       emscripten::allow_raw_pointers());\n\n  emscripten::function(\"FromPointsToSurfaceMesh\", &FromPointsToSurfaceMesh,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"FitPlaneToPoints\", &FitPlaneToPoints,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"RemeshSurfaceMesh\", &RemeshSurfaceMesh,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"SubdivideSurfaceMesh\", &SubdivideSurfaceMesh,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"TransformSurfaceMesh\", &TransformSurfaceMesh,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"TransformSurfaceMeshByTransform\",\n                       &TransformSurfaceMeshByTransform,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"FromSurfaceMeshToPolygonSoup\",\n                       &FromSurfaceMeshToPolygonSoup,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"FromFunctionToSurfaceMesh\", &FromFunctionToSurfaceMesh,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"ComputeConvexHullAsSurfaceMesh\",\n                       &ComputeConvexHullAsSurfaceMesh,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"ComputeAlphaShapeAsSurfaceMesh\",\n                       &ComputeAlphaShapeAsSurfaceMesh,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"ComputeAlphaShape2AsPolygonSegments\",\n                       &ComputeAlphaShape2AsPolygonSegments,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"OffsetOfPolygonWithHoles\", &OffsetOfPolygonWithHoles,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"InsetOfPolygonWithHoles\", &InsetOfPolygonWithHoles,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"MinkowskiDifferenceOfSurfaceMeshes\",\n                       &MinkowskiDifferenceOfSurfaceMeshes,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"MinkowskiShellOfSurfaceMeshes\",\n                       &MinkowskiShellOfSurfaceMeshes,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"MinkowskiSumOfSurfaceMeshes\",\n                       &MinkowskiSumOfSurfaceMeshes,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"GrowSurfaceMesh\", &GrowSurfaceMesh,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"SimplifySurfaceMesh\", &SimplifySurfaceMesh,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"RemoveSelfIntersectionsOfSurfaceMesh\",\n                       &RemoveSelfIntersectionsOfSurfaceMesh,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"Surface_mesh__is_closed\", &Surface_mesh__is_closed,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"Surface_mesh__is_empty\", &Surface_mesh__is_empty,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"Surface_mesh__is_valid_halfedge_graph\",\n                       &Surface_mesh__is_valid_halfedge_graph,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"Surface_mesh__is_valid_face_graph\",\n                       &Surface_mesh__is_valid_face_graph,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"Surface_mesh__is_valid_polygon_mesh\",\n                       &Surface_mesh__is_valid_polygon_mesh,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"Surface_mesh__bbox\", &Surface_mesh__bbox,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"ArrangePathsApproximate\", &ArrangePathsApproximate,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"ArrangePathsExact\", &ArrangePathsExact,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"ArrangePolygonsWithHoles\", &ArrangePolygonsWithHoles,\n                       emscripten::allow_raw_pointers());\n  emscripten::function(\"SectionOfSurfaceMesh\", &SectionOfSurfaceMesh,\n                       emscripten::allow_raw_pointers());\n\n  // emscripten::function(\"getTotalMemory\", &getTotalMemory);\n#endif\n}\n", "meta": {"hexsha": "ecac028783b4aad78ccbb2e17a4a4fb69c70492d", "size": 184025, "ext": "cc", "lang": "C++", "max_stars_repo_path": "algorithm/cgal/cgal.cc", "max_stars_repo_name": "BarbourSmith/JSxCAD", "max_stars_repo_head_hexsha": "f96993621d29880a848dc981beadf544ba344b27", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "algorithm/cgal/cgal.cc", "max_issues_repo_name": "BarbourSmith/JSxCAD", "max_issues_repo_head_hexsha": "f96993621d29880a848dc981beadf544ba344b27", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-11-11T20:12:11.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-01T17:41:28.000Z", "max_forks_repo_path": "algorithm/cgal/cgal.cc", "max_forks_repo_name": "BarbourSmith/JSxCAD", "max_forks_repo_head_hexsha": "f96993621d29880a848dc981beadf544ba344b27", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-11-01T18:54:41.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-01T18:54:41.000Z", "avg_line_length": 37.472001629, "max_line_length": 95, "alphanum_fraction": 0.6207689173, "num_tokens": 44891, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152497, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.4514393145535403}}
{"text": "#ifndef _TRAIN_FILTER_HPP_\n#define _TRAIN_FILTER_HPP_\n\n#include <iostream>\n#include <string>\n#include <math.h>\n#include <algorithm>\n#include <Eigen/Dense>\n#include \"parameters.hpp\"\n#include \"matrix_operator.hpp\"\n#include \"ffttools.hpp\"\n#include \"eco_util.hpp\"\n\nnamespace eco_tracker {\n\ntypedef std::vector<std::vector<Eigen::MatrixXcf> > EcoFeats;\n\nstruct CG_state {\n\tEcoFeats p, r_prev;\n\tfloat rho;\n};\n\nvoid trainFilterJoint(\n    const EcoFeats& xlf,\n\tconst EcoFeats& sample_energy,\n    const std::vector<Eigen::MatrixXcf>& reg_filter,\n\tconst std::vector<float>& reg_energy,\n    const std::vector<Eigen::MatrixXcf>& proj_energy,\n    const std::vector<Eigen::MatrixXcf>& yf,\n    const EcoParameters& params,\n    EcoFeats& hf,\n    std::vector<Eigen::MatrixXcf>& projection_matrix);\n\nECO_Train buildLhsOperationJoint(\n    const ECO_Train& f_delta_P,\n    const EcoFeats& samples_f,\n    const std::vector<Eigen::MatrixXcf>& reg_filter,\n    const EcoFeats& init_samplef,\n    const std::vector<Eigen::MatrixXcf>& init_samplef_H,\n    const EcoFeats &init_hf,\n    const float& proj_lambda);\n\nECO_Train runPCGEcoJoint(\n    const ECO_Train& f_delta_P,\n    const ECO_Train& rhs_sample,\n    const ECO_Train& diag_M,\n    const EcoFeats &init_samplef_proj,\n    const std::vector<Eigen::MatrixXcf>& reg_filter,\n    const EcoFeats& init_samplef,\n    const std::vector<Eigen::MatrixXcf>& init_samplef_H,\n    const EcoFeats &init_hf,\n    const EcoParameters& params);\n\nvoid trainFilter(\n    const std::vector<EcoFeats>& samplesf,\n    const std::vector<Eigen::MatrixXcf>& reg_filter,\n    const std::vector<float>& sample_weights,\n    const EcoFeats& sample_energy,\n    const std::vector<float>& reg_energy,\n    const std::vector<Eigen::MatrixXcf>& yf,\n    const EcoParameters& params,\n    EcoFeats& hf);\n\nEcoFeats buildLhsOperation(\n    const EcoFeats& hf,\n    const std::vector<EcoFeats>& samples_f,\n    const std::vector<Eigen::MatrixXcf>& reg_filter,\n    const std::vector<float>& sample_weights);\n\nvoid runPCGEcoFilter(\n    const vector<EcoFeats>& samplesf,\n    const vector<Eigen::MatrixXcf>& reg_filter,\n    const vector<float>& sample_weights,\n    const EcoFeats& rhs_samplef,\n    const EcoFeats& diag_M,\n    const EcoParameters& params,\n    EcoFeats& hf);\n\nEcoFeats computeFeatureMutiply2(\n    const EcoFeats& a,\n    const std::vector<Eigen::MatrixXcf>& b);\n\nstd::vector<Eigen::MatrixXcf> computeFeatureMutiply(\n    const EcoFeats& a,\n    const EcoFeats& b);\n\nECO_Train EcoFeatureDotDivideJoint(\n    const ECO_Train &a,\n    const ECO_Train &b);\n\nfloat getInnerProductJoint(\n    const ECO_Train &a,\n    const ECO_Train &b);\n\nfloat getInnerProduct(\n    const EcoFeats &a,\n    const EcoFeats &b);\n\nvoid FilterSymmetrize(EcoFeats &hf);\n\n} // namespace eco_tracker\n#endif", "meta": {"hexsha": "3135bff7ed5b103b83c253d1a3838c3a300ab8df", "size": 2755, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "app/inc/train_filter.hpp", "max_stars_repo_name": "lygbuaa/eco_tracker", "max_stars_repo_head_hexsha": "d77afb97d356769bfe5f7d9cb5e96b3cf40c4601", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2019-04-20T05:38:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-08T06:30:41.000Z", "max_issues_repo_path": "app/inc/train_filter.hpp", "max_issues_repo_name": "lygbuaa/eco_tracker", "max_issues_repo_head_hexsha": "d77afb97d356769bfe5f7d9cb5e96b3cf40c4601", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-06-06T11:12:06.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-10T11:27:12.000Z", "max_forks_repo_path": "app/inc/train_filter.hpp", "max_forks_repo_name": "lygbuaa/eco_tracker", "max_forks_repo_head_hexsha": "d77afb97d356769bfe5f7d9cb5e96b3cf40c4601", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-07-12T03:47:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-08T06:44:17.000Z", "avg_line_length": 27.0098039216, "max_line_length": 61, "alphanum_fraction": 0.7259528131, "num_tokens": 778, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152497, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.4514393145535403}}
{"text": "// Copyright (c) 2018 Graphcore Ltd. All rights reserved.\n#include \"Constraint.hpp\"\n#include \"Scheduler.hpp\"\n#include <memory>\n#define BOOST_TEST_MODULE Product\n#include <boost/test/unit_test.hpp>\n\nusing namespace popsolver;\n\nBOOST_AUTO_TEST_CASE(PropagateNoChange) {\n  Variable a(0), b(1), c(2);\n  auto product = std::unique_ptr<Product>(new Product(c, a, b));\n  Domains domains;\n  domains.push_back({DataType{7}, DataType{8}});   // a\n  domains.push_back({DataType{2}, DataType{5}});   // b\n  domains.push_back({DataType{14}, DataType{40}}); // c\n  Scheduler scheduler(domains, {product.get()});\n  bool success = product->propagate(scheduler);\n  BOOST_CHECK(success);\n  BOOST_CHECK_EQUAL(scheduler.getDomains()[a].min(), DataType{7});\n  BOOST_CHECK_EQUAL(scheduler.getDomains()[a].max(), DataType{8});\n  BOOST_CHECK_EQUAL(scheduler.getDomains()[b].min(), DataType{2});\n  BOOST_CHECK_EQUAL(scheduler.getDomains()[b].max(), DataType{5});\n  BOOST_CHECK_EQUAL(scheduler.getDomains()[c].min(), DataType{14});\n  BOOST_CHECK_EQUAL(scheduler.getDomains()[c].max(), DataType{40});\n}\n\nBOOST_AUTO_TEST_CASE(PropagateResult) {\n  Variable a(0), b(1), c(2);\n  auto product = std::unique_ptr<Product>(new Product(c, a, b));\n  Domains domains;\n  domains.push_back({DataType{3}, DataType{4}});   // a\n  domains.push_back({DataType{2}, DataType{5}});   // b\n  domains.push_back({DataType{0}, DataType{100}}); // c\n  Scheduler scheduler(domains, {product.get()});\n  bool success = product->propagate(scheduler);\n  BOOST_CHECK(success);\n  BOOST_CHECK_EQUAL(scheduler.getDomains()[a].min(), DataType{3});\n  BOOST_CHECK_EQUAL(scheduler.getDomains()[a].max(), DataType{4});\n  BOOST_CHECK_EQUAL(scheduler.getDomains()[b].min(), DataType{2});\n  BOOST_CHECK_EQUAL(scheduler.getDomains()[b].max(), DataType{5});\n  BOOST_CHECK_EQUAL(scheduler.getDomains()[c].min(), DataType{6});\n  BOOST_CHECK_EQUAL(scheduler.getDomains()[c].max(), DataType{20});\n}\n\nBOOST_AUTO_TEST_CASE(PropagateOperands) {\n  Variable a(0), b(1), c(2);\n  auto product = std::unique_ptr<Product>(new Product(c, a, b));\n  Domains domains;\n  domains.push_back({DataType{2}, DataType{10}});   // a\n  domains.push_back({DataType{4}, DataType{1000}}); // b\n  domains.push_back({DataType{10}, DataType{12}});  // c\n  Scheduler scheduler(domains, {product.get()});\n  bool success = product->propagate(scheduler);\n  BOOST_CHECK(success);\n  BOOST_CHECK_EQUAL(scheduler.getDomains()[a].min(), DataType{2});\n  BOOST_CHECK_EQUAL(scheduler.getDomains()[a].max(), DataType{3});\n  BOOST_CHECK_EQUAL(scheduler.getDomains()[b].min(), DataType{4});\n  BOOST_CHECK_EQUAL(scheduler.getDomains()[b].max(), DataType{6});\n  BOOST_CHECK_EQUAL(scheduler.getDomains()[c].min(), DataType{10});\n  BOOST_CHECK_EQUAL(scheduler.getDomains()[c].max(), DataType{12});\n}\n\nBOOST_AUTO_TEST_CASE(PropagateBoth) {\n  Variable a(0), b(1), c(2);\n  auto product = std::unique_ptr<Product>(new Product(c, a, b));\n  Domains domains;\n  domains.push_back({DataType{2}, DataType{10}});   // a\n  domains.push_back({DataType{4}, DataType{1000}}); // b\n  domains.push_back({DataType{0}, DataType{12}});   // c\n  Scheduler scheduler(domains, {product.get()});\n  bool success = product->propagate(scheduler);\n  BOOST_CHECK(success);\n  BOOST_CHECK_EQUAL(scheduler.getDomains()[a].min(), DataType{2});\n  BOOST_CHECK_EQUAL(scheduler.getDomains()[a].max(), DataType{3});\n  BOOST_CHECK_EQUAL(scheduler.getDomains()[b].min(), DataType{4});\n  BOOST_CHECK_EQUAL(scheduler.getDomains()[b].max(), DataType{6});\n  BOOST_CHECK_EQUAL(scheduler.getDomains()[c].min(), DataType{8});\n  BOOST_CHECK_EQUAL(scheduler.getDomains()[c].max(), DataType{12});\n}\n\nBOOST_AUTO_TEST_CASE(PropagateBoth2) {\n  Variable a(0), b(1), c(2);\n  auto product = std::unique_ptr<Product>(new Product(c, a, b));\n  Domains domains;\n  domains.push_back({DataType{1}, DataType{40}}); // a\n  domains.push_back({DataType{2}, DataType{3}});  // b\n  domains.push_back({DataType{4}, DataType{5}});  // c\n  Scheduler scheduler(domains, {product.get()});\n  bool success = product->propagate(scheduler);\n  BOOST_CHECK(success);\n  BOOST_CHECK_EQUAL(scheduler.getDomains()[a].min(), DataType{2});\n  BOOST_CHECK_EQUAL(scheduler.getDomains()[a].max(), DataType{2});\n  BOOST_CHECK_EQUAL(scheduler.getDomains()[b].min(), DataType{2});\n  BOOST_CHECK_EQUAL(scheduler.getDomains()[b].max(), DataType{2});\n  BOOST_CHECK_EQUAL(scheduler.getDomains()[c].min(), DataType{4});\n  BOOST_CHECK_EQUAL(scheduler.getDomains()[c].max(), DataType{4});\n}\n\nBOOST_AUTO_TEST_CASE(AvoidOverflow) {\n  Variable a(0), b(1), c(2);\n  auto product = std::unique_ptr<Product>(new Product(c, a, b));\n  Domains domains;\n  domains.push_back({DataType{0}, DataType::max() - DataType{1}}); // a\n  domains.push_back({DataType{0}, DataType::max() - DataType{1}}); // b\n  domains.push_back({DataType{27}, DataType{64}});                 // c\n  Scheduler scheduler(domains, {product.get()});\n  bool success = product->propagate(scheduler);\n  BOOST_CHECK(success);\n  BOOST_CHECK_EQUAL(scheduler.getDomains()[a].min(), DataType{1});\n  BOOST_CHECK_EQUAL(scheduler.getDomains()[a].max(), DataType{64});\n  BOOST_CHECK_EQUAL(scheduler.getDomains()[b].min(), DataType{1});\n  BOOST_CHECK_EQUAL(scheduler.getDomains()[b].max(), DataType{64});\n}\n", "meta": {"hexsha": "d235e572c3bc406aff64f61206f16d31229eec3d", "size": 5231, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/popsolver/Product.cpp", "max_stars_repo_name": "graphcore/poplibs", "max_stars_repo_head_hexsha": "3fe5a3ecafe995eddb72675d1b4a7af8a622009e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 95.0, "max_stars_repo_stars_event_min_datetime": "2020-07-06T17:11:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T14:42:28.000Z", "max_issues_repo_path": "tests/popsolver/Product.cpp", "max_issues_repo_name": "giantchen2012/poplibs", "max_issues_repo_head_hexsha": "2bc6b6f3d40863c928b935b5da88f40ddd77078e", "max_issues_repo_licenses": ["MIT"], "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/popsolver/Product.cpp", "max_forks_repo_name": "giantchen2012/poplibs", "max_forks_repo_head_hexsha": "2bc6b6f3d40863c928b935b5da88f40ddd77078e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2020-07-15T12:32:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T14:58:45.000Z", "avg_line_length": 45.4869565217, "max_line_length": 71, "alphanum_fraction": 0.7063658956, "num_tokens": 1402, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.451439309707252}}
{"text": "\n#include <iostream>\nusing namespace std;\n\n#include <boost/foreach.hpp>\n\n#include <lvv/lvv.h>\n#include <lvv/math.h>\nusing lvv::group_mean;\n\n\nint main() { \n\n\tdouble sample_value = 1.;\n\tdouble samples= 20 ;\n\tdouble global_value = 10.;\n\tdouble K = 5.;\n\nfor (int i=1; i < 20; i++)\n\tFMT(\"sv=%f\tsN=%f\t\tgv=%f\tK=%f\t===  GM=%f\\n\") %sample_value %i  %global_value %K %group_mean(sample_value, i, global_value, K);\n}\n", "meta": {"hexsha": "c468bbb905028d133953d571b211ae9ecbcb1aa2", "size": 406, "ext": "cc", "lang": "C++", "max_stars_repo_path": ".old/t-group_mean.cc", "max_stars_repo_name": "lvv/lvvlib", "max_stars_repo_head_hexsha": "b610a089103853e7cf970efde2ce4bed9f505090", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2015-02-05T12:26:16.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-14T23:13:14.000Z", "max_issues_repo_path": ".old/t-group_mean.cc", "max_issues_repo_name": "lvv/lvvlib", "max_issues_repo_head_hexsha": "b610a089103853e7cf970efde2ce4bed9f505090", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": ".old/t-group_mean.cc", "max_forks_repo_name": "lvv/lvvlib", "max_forks_repo_head_hexsha": "b610a089103853e7cf970efde2ce4bed9f505090", "max_forks_repo_licenses": ["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.4545454545, "max_line_length": 126, "alphanum_fraction": 0.645320197, "num_tokens": 135, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8198933183101078, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.4514393000146747}}
{"text": "//==================================================================================================\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#include <boost/simd/function/hmsb.hpp>\n#include <boost/simd/pack.hpp>\n#include <simd_test.hpp>\n\nnamespace bs = boost::simd;\nnamespace bd = boost::dispatch;\n\ntemplate <typename T,int N, typename Env>\nvoid test(Env& $)\n{\n  using p_t = bs::pack<T, N>;\n\n  T a[N];\n  std::bitset<N> r;\n\n  for(int i = 0; i < N; ++i)\n  {\n    a[i] = (i%2) ? T(i) : T(-i);\n    r[i] = bs::bitwise_and(bs::Signmask<bd::as_integer_t<T>>(), a[i]) != 0;\n  }\n\n  p_t aa(&a[0], &a[0]+N);\n  STF_EQUAL(bs::hmsb(aa), r);\n}\n\nSTF_CASE_TPL(\"Check hmsb on pack\" , STF_NUMERIC_TYPES)\n{\n  static const std::size_t N = bs::pack<T>::static_size;\n  test<T, N>($);\n  test<T, N/2>($);\n  test<T, N*2>($);\n}\n", "meta": {"hexsha": "7a73d72482fb2b5c6e925e620efcf18b55b7732c", "size": 1042, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/simd/hmsb.cpp", "max_stars_repo_name": "nickporubsky/boost-simd-clone", "max_stars_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_stars_repo_licenses": ["BSL-1.0"], "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": "test/function/simd/hmsb.cpp", "max_issues_repo_name": "timblechmann/boost.simd", "max_issues_repo_head_hexsha": "2217f1d0102193799469b533e3a7118bf4a77dde", "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/function/simd/hmsb.cpp", "max_forks_repo_name": "timblechmann/boost.simd", "max_forks_repo_head_hexsha": "2217f1d0102193799469b533e3a7118bf4a77dde", "max_forks_repo_licenses": ["BSL-1.0"], "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": 25.4146341463, "max_line_length": 100, "alphanum_fraction": 0.4961612284, "num_tokens": 299, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056167854461, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.451422624417629}}
{"text": "#pragma once\n\n#include <algorithm>\n#include <cassert>\n#include <iterator>\n#include <limits>\n#include <tuple>\n#include <utility>\n#include <vector>\n\n#include <boost/optional.hpp>\n\n#include \"vi_algo.hpp\"\n\nnamespace vi\n{\n    namespace ea\n    {\n        namespace nsga2\n        {\n            bool\n            dominates(const std::vector<double>& objective_values_a, const std::vector<double>& objective_values_b)\n            {\n                assert(objective_values_a.size() == objective_values_b.size());\n\n                auto objective_value_it           = objective_values_a.begin();\n                auto other_objective_value_it     = objective_values_b.begin();\n                const auto objective_value_end_it = objective_values_a.end();\n\n                while (objective_value_it != objective_value_end_it)\n                {\n                    if (*other_objective_value_it <= *objective_value_it)\n                    {\n                        return false;\n                    }\n\n                    ++objective_value_it;\n                    ++other_objective_value_it;\n                }\n\n                return true;\n            }\n\n            template <typename genotype_type>\n            struct individual\n            {\n                genotype_type            genotype{};\n                std::vector<double>      objective_values{};\n                std::vector<individual*> S{};\n                double                   crowding_distance{};\n                unsigned                 n{};\n                unsigned                 rank{};\n\n                individual(genotype_type       genotype,\n                           std::vector<double> objective_values)\n                    : genotype(std::move(genotype)),\n                      objective_values(std::move(objective_values))\n                {\n                }\n\n                bool\n                operator<(const individual& other) const\n                {\n                    return rank < other.rank || (rank == other.rank && crowding_distance > other.crowding_distance);\n                }\n            };\n\n            struct options\n            {\n                double   crossover_rate{};\n                double   mutation_rate{};\n                unsigned objective_count{};\n                unsigned population_size{};\n                unsigned tournament_group_size{};\n                double   tournament_randomness{};\n            };\n\n            template <typename genotype_type,\n                      typename genotype_creator_type,\n                      typename objective_evaluator_type,\n                      typename crossover_operator_type,\n                      typename mutation_operator_type>\n            struct system\n            {\n                using individual_type = individual<genotype_type>;\n\n                options                                       system_options;\n                genotype_creator_type                         genotype_creator;\n                objective_evaluator_type                      objective_evaluator;\n                crossover_operator_type                       crossover_operator;\n                mutation_operator_type                        mutation_operator;\n\n                unsigned                                      generation;\n                std::vector<double>                           range_min;\n                std::vector<double>                           range_max;\n                std::vector<boost::optional<individual_type>> extreme_min;\n                std::vector<boost::optional<individual_type>> extreme_max;\n\n                std::vector<individual_type>                  current_population{};\n                std::vector<individual_type>                  next_population{};\n                std::vector<individual_type>                  offspring{};\n                std::vector<std::vector<individual_type*>>    fronts;\n\n                std::bernoulli_distribution                   crossover_distribution;\n                std::bernoulli_distribution                   mutation_distribution;\n                std::set<unsigned>                            tournament_group{};\n                std::bernoulli_distribution                   tournament_select_best_distribution;\n\n                template <typename random_generator_type>\n                system(random_generator_type&   random_generator,\n                       const options&           system_options,\n                       genotype_creator_type    genotype_creator,\n                       objective_evaluator_type objective_evaluator,\n                       crossover_operator_type  crossover_operator,\n                       mutation_operator_type   mutation_operator)\n                    : system_options{system_options},\n                      genotype_creator{std::move(genotype_creator)},\n                      objective_evaluator{std::move(objective_evaluator)},\n                      crossover_operator{std::move(crossover_operator)},\n                      mutation_operator{std::move(mutation_operator)},\n                      generation{0},\n                      range_min(system_options.objective_count,   +std::numeric_limits<double>::infinity()),\n                      range_max(system_options.objective_count,   -std::numeric_limits<double>::infinity()),\n                      extreme_min(system_options.objective_count),\n                      extreme_max(system_options.objective_count),\n                      fronts(system_options.population_size),\n                      crossover_distribution{system_options.crossover_rate},\n                      mutation_distribution{system_options.mutation_rate},\n                      tournament_select_best_distribution{1.0 - system_options.tournament_randomness}\n                {\n                    current_population.reserve(system_options.population_size);\n                    next_population.reserve(system_options.population_size);\n                    offspring.reserve(system_options.population_size);\n                    create_initial_population(random_generator);\n                }\n\n                template <typename random_generator_type>\n                void\n                create_initial_population(random_generator_type& random_generator)\n                {\n                    current_population.clear();\n\n                    for (auto& front : fronts)\n                    {\n                        front.clear();\n                    }\n\n                    for (auto i = system_options.population_size; i != 0; --i)\n                    {\n                        auto genotype         = genotype_creator(random_generator);\n                        auto objective_values = objective_evaluator(genotype);\n                        current_population.emplace_back(std::move(genotype), std::move(objective_values));\n                    }\n                }\n\n                void\n                assign_crowding_distances(\n                    std::vector<individual_type*>& front, const bool is_non_dominated_front)\n                {\n                    for (auto individual : front)\n                    {\n                        individual->crowding_distance = 0.0;\n                    }\n\n                    for (unsigned objective = 0; objective != system_options.objective_count; ++objective)\n                    {\n                        std::sort(front.begin(), front.end(),\n                            [objective](individual_type* a, individual_type* b)\n                            {\n                                return a->objective_values[objective] < b->objective_values[objective];\n                            });\n\n                        const auto min_individual = *front.begin();\n                        const auto max_individual = *front.rbegin();\n\n                        min_individual->crowding_distance = std::numeric_limits<double>::infinity();\n                        max_individual->crowding_distance = std::numeric_limits<double>::infinity();\n\n                        range_min[objective] = std::min(range_min[objective], min_individual->objective_values[objective]);\n                        range_max[objective] = std::max(range_max[objective], max_individual->objective_values[objective]);\n\n                        if (is_non_dominated_front)\n                        {\n                            extreme_min[objective] = *min_individual;\n                        }\n\n                        if ((!extreme_max[objective]) or\n                            (max_individual->objective_values[objective] > extreme_max[objective]->objective_values[objective]))\n                        {\n                            extreme_max[objective] = *max_individual;\n                        }\n\n                        const auto range_delta   = range_max[objective] - range_min[objective];\n                        const auto range_scaling = range_delta != 0.0 ? 1.0 / range_delta : 1.0;\n\n                        for (typename std::vector<individual_type*>::size_type i = 1; i < front.size() - 1; ++i)\n                        {\n                            front[i]->crowding_distance += range_scaling *\n                                (front[i + 1]->objective_values[objective] -\n                                 front[i - 1]->objective_values[objective]);\n                        }\n                    }\n                }\n\n                template <typename random_generator_type>\n                void\n                evolve(random_generator_type& random_generator)\n                {\n                    for (auto& entry : extreme_max)\n                    {\n                        entry = boost::none;\n                    }\n\n                    offspring.clear();\n                    generate_individuals(random_generator);\n\n                    std::move(offspring.begin(), offspring.end(), std::back_inserter(current_population));\n                    fast_non_dominated_sort();\n\n                    next_population.clear();\n                    auto remaining = system_options.population_size;\n                    auto first = true;\n\n                    for (auto& front : fronts)\n                    {\n                        if (remaining > 0)\n                        {\n                            assign_crowding_distances(front, first);\n                            first = false;\n\n                            const auto front_size = static_cast<unsigned>(front.size());\n\n                            if (front_size <= remaining)\n                            {\n                                for (auto individual : front)\n                                {\n                                    next_population.emplace_back(std::move(*individual));\n                                }\n\n                                remaining -= front_size;\n                            }\n                            else\n                            {\n                                // Shuffle to avoid order bias from crowding_distance_assignment\n                                std::shuffle(front.begin(), front.end(), random_generator);\n                                std::sort(front.begin(), front.end(),\n                                    [](const auto a, const auto b)\n                                    {\n                                        return (*a) < (*b);\n                                    });\n\n                                for (auto individual = front.begin(); individual != front.begin() + remaining; ++individual)\n                                {\n                                    next_population.emplace_back(std::move(**individual));\n                                }\n\n                                remaining = 0;\n                            }\n                        }\n                        else\n                        {\n                            if (!front.empty())\n                            {\n                                front.clear();\n                            }\n                            else\n                            {\n                                break;\n                            }\n                        }\n                    }\n\n                    current_population.clear();\n                    std::swap(current_population, next_population);\n                    ++generation;\n                }\n\n                void\n                fast_non_dominated_sort()\n                {\n                    for (auto& front : fronts)\n                    {\n                        front.clear();\n                    }\n\n                    for (auto& individual : current_population)\n                    {\n                        individual.S.clear();\n                        individual.n = 0U;\n                    }\n\n                    const auto end = current_population.end();\n\n                    for (auto p = current_population.begin(); p != end; ++p)\n                    {\n                        for (auto q = p + 1; q != end; ++q)\n                        {\n                            if (dominates(p->objective_values, q->objective_values))\n                            {\n                                p->S.push_back(&*q);\n                                ++q->n;\n                            }\n                            else if (dominates(q->objective_values, p->objective_values))\n                            {\n                                q->S.push_back(&*p);\n                                ++p->n;\n                            }\n                        }\n\n                        if (p->n == 0)\n                        {\n                            p->rank = 0;\n                            fronts[0].push_back(&*p);\n                        }\n                    }\n\n                    for (auto front_index = 0U; !fronts[front_index].empty(); ++front_index)\n                    {\n                        for (auto p : fronts[front_index])\n                        {\n                            for (auto q : p->S)\n                            {\n                                if (--q->n == 0)\n                                {\n                                    q->rank = front_index + 1U;\n                                    fronts[front_index + 1].push_back(&*q);\n                                }\n                            }\n                        }\n                    }\n                }\n\n                template <typename random_generator_type>\n                void\n                generate_individuals(random_generator_type& random_generator)\n                {\n                    while (offspring.size() < system_options.population_size)\n                    {\n                        const auto parent_a = tournament_selector(random_generator, current_population);\n                        const auto parent_b = tournament_selector(random_generator, current_population);\n\n                        genotype_type child_a_genotype{};\n                        genotype_type child_b_genotype{};\n\n                        if (crossover_distribution(random_generator))\n                        {\n                            std::tie(child_a_genotype, child_b_genotype) = crossover_operator(\n                                random_generator, parent_a->genotype, parent_b->genotype);\n                        }\n                        else\n                        {\n                            child_a_genotype = parent_a->genotype;\n                            child_b_genotype = parent_b->genotype;\n                        }\n\n                        if (mutation_distribution(random_generator))\n                        {\n                            mutation_operator(random_generator, child_a_genotype);\n                        }\n\n                        if (mutation_distribution(random_generator))\n                        {\n                            mutation_operator(random_generator, child_b_genotype);\n                        }\n\n                        auto child_a_objective_values = objective_evaluator(child_a_genotype);\n                        auto child_b_objective_values = objective_evaluator(child_b_genotype);\n\n                        offspring.emplace_back(std::move(child_a_genotype), std::move(child_a_objective_values));\n                        offspring.emplace_back(std::move(child_b_genotype), std::move(child_b_objective_values));\n                    }\n                }\n\n                template <typename random_generator_type>\n                const individual_type*\n                tournament_selector(random_generator_type&                       random_generator,\n                                    const typename std::vector<individual_type>& population)\n                {\n                    const bool select_best_individual = tournament_select_best_distribution(random_generator);\n\n                    if (select_best_individual)\n                    {\n                        ::vi::algo::generate_unique_in_range(\n                            random_generator,\n                            tournament_group,\n                            0U,\n                            system_options.population_size - 1U,\n                            system_options.tournament_group_size);\n\n                        const individual_type* selected_individual = nullptr;\n\n                        for (const auto index : tournament_group)\n                        {\n                            const auto& individual = population[index];\n                            if (!selected_individual or (individual < (*selected_individual)))\n                            {\n                                selected_individual = &individual;\n                            }\n                        }\n\n                        return selected_individual;\n                    }\n                    else\n                    {\n                        const auto random_individual_index = std::uniform_int_distribution<unsigned>{\n                            0U, static_cast<unsigned>(population.size()) - 1U}(random_generator);\n                        return &(population[random_individual_index]);\n                    }\n                }\n            };\n\n            template <typename genotype_type,\n                      typename random_generator_type,\n                      typename genotype_creator_type,\n                      typename objective_evaluator_type,\n                      typename crossover_operator_type,\n                      typename mutation_operator_type>\n            auto\n            build_system(random_generator_type&   random_generator,\n                         const options&           system_options,\n                         genotype_creator_type    genotype_creator,\n                         objective_evaluator_type objective_evaluator,\n                         crossover_operator_type  crossover_operator,\n                         mutation_operator_type   mutation_operator)\n            {\n                using system_type = system<genotype_type,\n                                           genotype_creator_type,\n                                           objective_evaluator_type,\n                                           crossover_operator_type,\n                                           mutation_operator_type>;\n\n                return system_type{random_generator,\n                                   system_options,\n                                   std::move(genotype_creator),\n                                   std::move(objective_evaluator),\n                                   std::move(crossover_operator),\n                                   std::move(mutation_operator)};\n            }\n        }\n    }\n}\n", "meta": {"hexsha": "0d47df6ae955d42b283c5e52bcb1ca8048aed385", "size": 19469, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "project_3_2017/program/vi_ea_nsga2.hpp", "max_stars_repo_name": "pveierland/permve-ntnu-it3708", "max_stars_repo_head_hexsha": "1066d5c1af5c953dbaf129d7e05ce32f2d4292aa", "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": "project_3_2017/program/vi_ea_nsga2.hpp", "max_issues_repo_name": "pveierland/permve-ntnu-it3708", "max_issues_repo_head_hexsha": "1066d5c1af5c953dbaf129d7e05ce32f2d4292aa", "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": "project_3_2017/program/vi_ea_nsga2.hpp", "max_forks_repo_name": "pveierland/permve-ntnu-it3708", "max_forks_repo_head_hexsha": "1066d5c1af5c953dbaf129d7e05ce32f2d4292aa", "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": 44.0475113122, "max_line_length": 128, "alphanum_fraction": 0.4395192357, "num_tokens": 2747, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.689305616785446, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.4514226244176289}}
{"text": "#include <stdexcept>\n\n#include <boost/test/unit_test.hpp>\n\n#include \"base-types.hpp\"\n#include \"triangle.hpp\"\n\nnamespace\n{\n  const double eps = 1e-10;\n}\n\nBOOST_AUTO_TEST_SUITE(TriangleConstructor)\n\nBOOST_AUTO_TEST_CASE(ValidArguments_ValidInitialization)\n{\n  yakovlev::Triangle tri = { { 32.0, -23.0 }, { -5.0, -15.0 }, { 124.3, 54.3 } };\n  yakovlev::point_t pos = { (124.3 + 32.0 - 5.0) / 3.0, (54.3 - 15.0 - 23.0) / 3.0 };\n  BOOST_CHECK_EQUAL(tri.getCenter(), pos);\n}\n\nBOOST_AUTO_TEST_CASE(DegenerateTriangleArguments_ThrowsInvalidArgument)\n{\n  BOOST_CHECK_THROW(yakovlev::Triangle({ 3.2 , 0.0 }, { -622.32, 0.0 }, { 432.2, 0.0 }), std::invalid_argument);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n//=====================================================================================\n\nBOOST_AUTO_TEST_SUITE(TriangleFrame)\n\nBOOST_AUTO_TEST_CASE(ValidTriangle_ValidFraming)\n{\n  yakovlev::Triangle tri = { { 6.0, 2.0 }, { 4.0, -6.0 }, { 3.0, 5.0 } };\n  yakovlev::rectangle_t frame = tri.getFrameRect();\n  BOOST_CHECK_EQUAL(frame.width, 3.0);\n  BOOST_CHECK_EQUAL(frame.height, 11.0);\n  yakovlev::point_t center = { 4.5, -0.5 };\n  BOOST_CHECK_EQUAL(frame.pos, center);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n//=====================================================================================\n\nBOOST_AUTO_TEST_SUITE(TriangleMove)\n\nBOOST_AUTO_TEST_CASE(By_ValidArguments_CenterMoved)\n{\n  yakovlev::Triangle tri = { { 6.0, 2.0 }, { 4.0, -6.0 }, { 3.0, 5.0 } };\n  yakovlev::point_t center = { 13.0 / 3.0, 1.0 / 3.0 };\n  double moveX = 312.4, moveY = -134.27;\n  tri.move(moveX, moveY);\n  yakovlev::point_t movedCenter = tri.getCenter();\n  BOOST_CHECK_EQUAL(movedCenter.x, center.x + moveX);\n  BOOST_CHECK_EQUAL(movedCenter.y, center.y + moveY);\n}\n\nBOOST_AUTO_TEST_CASE(To_ValidArguments_CenterMoved)\n{\n  yakovlev::Triangle tri = { { 6.0, 2.0 }, { 4.0, -6.0 }, { 3.0, 5.0 } };\n  yakovlev::point_t newCenter = { 8654.2, -321.4043 };\n  tri.move(newCenter);\n  BOOST_CHECK_EQUAL(tri.getCenter(), newCenter);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n//=====================================================================================\n\nBOOST_AUTO_TEST_SUITE(TriangleMovePersistence)\n\nBOOST_AUTO_TEST_CASE(By_ValidArguments_AreaPersists)\n{\n  yakovlev::Triangle tri = { { 6.0, 2.0 }, { 4.0, -6.0 }, { 3.0, 5.0 } };\n  double area = tri.getArea();\n  tri.move(-234.4, 0.2134);\n  BOOST_CHECK_CLOSE(tri.getArea(), area, eps);\n}\n\nBOOST_AUTO_TEST_CASE(To_ValidArguments_AreaPersists)\n{\n  yakovlev::Triangle tri = { { 6.0, 2.0 }, { 4.0, -6.0 }, { 3.0, 5.0 } };\n  double area = tri.getArea();\n  tri.move({ 231.23, -231.23 });\n  BOOST_CHECK_CLOSE(tri.getArea(), area, eps);\n}\n\nBOOST_AUTO_TEST_CASE(By_ValidArguments_FramePersists)\n{\n  yakovlev::Triangle tri = { { 6.0, 2.0 }, { 4.0, -6.0 }, { 3.0, 5.0 } };\n  yakovlev::rectangle_t frame = tri.getFrameRect();\n  double moveX = 4234.4, moveY = 123.34;\n  tri.move(moveX, moveY);\n  yakovlev::rectangle_t movedFrame = tri.getFrameRect();\n  BOOST_CHECK_EQUAL(movedFrame.width, frame.width);\n  BOOST_CHECK_EQUAL(movedFrame.height, frame.height);\n  BOOST_CHECK_EQUAL(movedFrame.pos.x, frame.pos.x + moveX);\n  BOOST_CHECK_EQUAL(movedFrame.pos.y, frame.pos.y + moveY);\n}\n\nBOOST_AUTO_TEST_CASE(To_ValidArguments_FramePersists)\n{\n  yakovlev::Triangle tri = { { 6.0, 2.0 }, { 4.0, -6.0 }, { 3.0, 5.0 } };\n  yakovlev::rectangle_t frame = tri.getFrameRect();\n  yakovlev::point_t triCenter = tri.getCenter();\n  yakovlev::point_t centerDist = { frame.pos.x - triCenter.x, frame.pos.y - triCenter.y };\n  tri.move({ 44.4, 4.4 });\n  yakovlev::rectangle_t movedFrame = tri.getFrameRect();\n  BOOST_CHECK_CLOSE(movedFrame.width, frame.width, eps);\n  BOOST_CHECK_CLOSE(movedFrame.height, frame.height, eps);\n  yakovlev::point_t movedTriCenter = tri.getCenter();\n  yakovlev::point_t movedFramePos = { movedTriCenter.x + centerDist.x, movedTriCenter.y + centerDist.y };\n  BOOST_CHECK_CLOSE(movedFrame.pos.x, movedFramePos.x, eps);\n  BOOST_CHECK_CLOSE(movedFrame.pos.y, movedFramePos.y, eps);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n//=====================================================================================\n\nBOOST_AUTO_TEST_SUITE(TriangleRotate)\n\nBOOST_AUTO_TEST_CASE(AnyAngle_AreaPersists)\n{\n  yakovlev::Triangle tri = { { 6.0, 2.0 }, { 4.0, -6.0 }, { 3.0, 5.0 } };\n  double area = tri.getArea();\n  tri.rotate(12);\n  BOOST_CHECK_CLOSE(tri.getArea(), area, eps);\n}\n\nBOOST_AUTO_TEST_CASE(AnyAngle_CenterPersists)\n{\n  yakovlev::Triangle tri = { { 6.0, 2.0 }, { 4.0, -6.0 }, { 3.0, 5.0 } };\n  yakovlev::point_t center = tri.getCenter();\n  tri.rotate(-12);\n  BOOST_CHECK_CLOSE(tri.getCenter().x, center.x, eps);\n  BOOST_CHECK_CLOSE(tri.getCenter().y, center.y, eps);\n}\n\nBOOST_AUTO_TEST_CASE(AnyAngle_FrameUpdates)\n{\n  yakovlev::Triangle tri = { { 6.0, 2.0 }, { 4.0, -6.0 }, { 3.0, 5.0 } };\n  yakovlev::rectangle_t frame = tri.getFrameRect();\n  tri.rotate(90);\n  yakovlev::rectangle_t updatedFrame = tri.getFrameRect();\n  BOOST_CHECK_CLOSE(updatedFrame.height, frame.width, eps);\n  BOOST_CHECK_CLOSE(updatedFrame.width, frame.height, eps);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n//=====================================================================================\n\nBOOST_AUTO_TEST_SUITE(TriangleScale)\n\nBOOST_AUTO_TEST_CASE(ValidCoefficient_AreaScales)\n{\n  yakovlev::Triangle tri = { { 45.0, 2.0 }, { 4.0, -6.0 }, { 3.0, 5.0 } };\n  double area = tri.getArea();\n  double coef = 34.2;\n  tri.scale(coef);\n  BOOST_CHECK_CLOSE(tri.getArea(), area * coef * coef, eps);\n}\n\nBOOST_AUTO_TEST_CASE(InvalidCoefficient_ThrowsInvalidArgument)\n{\n  yakovlev::Triangle tri = { { 6.0, 2.0 }, { 4.0, -6.0 }, { 3.0, 5.0 } };\n  BOOST_CHECK_THROW(tri.scale(-3.4), std::invalid_argument);\n  BOOST_CHECK_THROW(tri.scale(0.0), std::invalid_argument);\n}\n\nBOOST_AUTO_TEST_CASE(ValidCoefficient_FrameUpdates)\n{\n  yakovlev::Triangle tri = { { 6.0, 2.0 }, { 4.0, -6.0 }, { 3.0, 5.0 } };\n  yakovlev::rectangle_t frame = tri.getFrameRect();\n  BOOST_CHECK_CLOSE(frame.width, 3.0, eps);\n  BOOST_CHECK_CLOSE(frame.height, 11.0, eps);\n  double coef = 2.5;\n  tri.scale(coef);\n  yakovlev::rectangle_t scaledFrame = tri.getFrameRect();\n  BOOST_CHECK_CLOSE(scaledFrame.width, frame.width * coef, eps);\n  BOOST_CHECK_CLOSE(scaledFrame.height, frame.height * coef, eps);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "0262ba8fdcc690548c75a9508b7d4e460fb33f4d", "size": 6236, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "508 - A4-spbspu-labs-2020-904-3/spbspu-labs-2020-904-3-master-yakovlev.alexey/3/common/test-triangle.cpp", "max_stars_repo_name": "NekoSilverFox/CPP", "max_stars_repo_head_hexsha": "c6797264fceda4a65ac3452acca496e468d1365a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-02-08T20:57:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-23T06:24:41.000Z", "max_issues_repo_path": "508 - A4-spbspu-labs-2020-904-3/spbspu-labs-2020-904-3-master-yakovlev.alexey/3/common/test-triangle.cpp", "max_issues_repo_name": "NekoSilverFox/CPP", "max_issues_repo_head_hexsha": "c6797264fceda4a65ac3452acca496e468d1365a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-03-02T14:44:55.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-11T16:25:33.000Z", "max_forks_repo_path": "508 - A4-spbspu-labs-2020-904-3/spbspu-labs-2020-904-3-master-yakovlev.alexey/3/common/test-triangle.cpp", "max_forks_repo_name": "NekoSilverFox/CPP", "max_forks_repo_head_hexsha": "c6797264fceda4a65ac3452acca496e468d1365a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-09-27T17:30:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-16T09:48:23.000Z", "avg_line_length": 33.170212766, "max_line_length": 112, "alphanum_fraction": 0.6460872354, "num_tokens": 1957, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.689305616785446, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.4514226197747751}}
{"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#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/two_graphs_common_spanning_trees.hpp>\n#include <exception>\n#include <vector>\n\nusing namespace std;\n\ntypedef boost::adjacency_list< boost::vecS, // OutEdgeList\n    boost::vecS, // VertexList\n    boost::undirectedS, // Directed\n    boost::no_property, // VertexProperties\n    boost::no_property, // EdgeProperties\n    boost::no_property, // GraphProperties\n    boost::listS // EdgeList\n    >\n    Graph;\n\ntypedef boost::graph_traits< Graph >::vertex_descriptor vertex_descriptor;\n\ntypedef boost::graph_traits< Graph >::edge_descriptor edge_descriptor;\n\ntypedef boost::graph_traits< Graph >::vertex_iterator vertex_iterator;\n\ntypedef boost::graph_traits< Graph >::edge_iterator edge_iterator;\n\nint main(int argc, char** argv)\n{\n    Graph iG, vG;\n    vector< edge_descriptor > iG_o;\n    vector< edge_descriptor > vG_o;\n\n    iG_o.push_back(boost::add_edge(0, 1, iG).first);\n    iG_o.push_back(boost::add_edge(0, 2, iG).first);\n    iG_o.push_back(boost::add_edge(0, 3, iG).first);\n    iG_o.push_back(boost::add_edge(0, 4, iG).first);\n    iG_o.push_back(boost::add_edge(1, 2, iG).first);\n    iG_o.push_back(boost::add_edge(3, 4, iG).first);\n\n    vG_o.push_back(boost::add_edge(1, 2, vG).first);\n    vG_o.push_back(boost::add_edge(2, 0, vG).first);\n    vG_o.push_back(boost::add_edge(2, 3, vG).first);\n    vG_o.push_back(boost::add_edge(4, 3, vG).first);\n    vG_o.push_back(boost::add_edge(0, 3, vG).first);\n    vG_o.push_back(boost::add_edge(0, 4, vG).first);\n\n    vector< bool > inL(iG_o.size(), false);\n\n    std::vector< std::vector< bool > > coll;\n    boost::tree_collector< std::vector< std::vector< bool > >,\n        std::vector< bool > >\n        tree_collector(coll);\n    boost::two_graphs_common_spanning_trees(\n        iG, iG_o, vG, vG_o, tree_collector, inL);\n\n    std::vector< std::vector< bool > >::iterator it;\n    for (it = coll.begin(); it != coll.end(); ++it)\n    {\n        // Here you can play with the trees that the algorithm has found.\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "824556dbe85c1a4c99d07c59f649c5c41f966adb", "size": 2490, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/graph/example/two_graphs_common_spanning_trees.cpp", "max_stars_repo_name": "uosorio/heroku_face", "max_stars_repo_head_hexsha": "7d6465e71dba17a15d8edaef520adb2fcd09d91e", "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": "3rdparty/boost_1_73_0/libs/graph/example/two_graphs_common_spanning_trees.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 130.0, "max_issues_repo_issues_event_min_datetime": "2016-06-22T22:11:25.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-29T20:24:09.000Z", "max_forks_repo_path": "3rdparty/boost_1_73_0/libs/graph/example/two_graphs_common_spanning_trees.cpp", "max_forks_repo_name": "qingkouwei/mediaones", "max_forks_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2015-07-08T19:18:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-14T16:39:56.000Z", "avg_line_length": 34.1095890411, "max_line_length": 74, "alphanum_fraction": 0.6787148594, "num_tokens": 730, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.6893056167854461, "lm_q1q2_score": 0.45142261513192133}}
{"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\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include <string>\n#include <iostream>\n\n#include <boost/numeric/mtl/mtl.hpp>\n\n\nusing namespace std;\n\n\ntemplate <typename Matrix, typename Tag>\nvoid two_d_iteration(char const* outer, const Matrix& matrix, Tag)\n{\n    namespace traits = mtl::traits;\n\n    typename traits::row<Matrix>::type                                 row(matrix); \n    typename traits::col<Matrix>::type                                 col(matrix); \n    typename traits::const_value<Matrix>::type                         value(matrix); \n    typedef typename traits::range_generator<Tag, Matrix>::type        cursor_type;\n\n    cout << outer << '\\n';\n    for (cursor_type cursor = mtl::begin<Tag>(matrix), cend = mtl::end<Tag>(matrix); cursor != cend; ++cursor) {\n\ttypedef mtl::tag::nz     inner_tag;\n\tcout << \"---\\n\";\n\ttypedef typename traits::range_generator<inner_tag, cursor_type>::type icursor_type;\n\tfor (icursor_type icursor = mtl::begin<inner_tag>(cursor), icend = mtl::end<inner_tag>(cursor); icursor != icend; ++icursor)\n\t    cout << \"matrix[\" << row(*icursor) << \"][\" << col(*icursor) << \"] = \" << value(*icursor) << '\\n';\n    }\n} \n\n\ntemplate <typename Matrix, typename Tag>\nvoid two_d_iteration(char const* name, const Matrix&, Tag, mtl::complexity_classes::infinite)\n{\n    cout << name << \": Tag has no implementation\\n\";\n}\n\n \ntemplate <typename Matrix, typename Value>\nvoid test(string name, const Matrix& A, Value check)\n{\n    cout << name << '\\n';\n    cout << \"num_rows(A) is \" << num_rows(A) << '\\n';\n    cout << \"num_cols(A) is \" << num_cols(A) << '\\n';\n    cout << \"A[0][0] is \" << A[0][0] << '\\n';\n    cout << name << \", A is\\n\" << A << '\\n';\n    \n    MTL_THROW_IF(A[0][1] != check, mtl::runtime_error(\"Wrong value in A[0][1]!\"));\n\n    two_d_iteration(\"Row-wise\", A, glas::tag::row());\n    two_d_iteration(\"Column-wise\", A, mtl::tag::col());\n    two_d_iteration(\"On Major\", A, mtl::tag::major());\n\n\n    mtl::transposed_view<const Matrix> At(A);\n    cout << \"\\n===\\nA^T is\\n\" << At << '\\n';\n    MTL_THROW_IF(At[1][0] != check, mtl::runtime_error(\"Wrong value in At[1][0]!\"));\n\n    two_d_iteration(\"Transposed row-wise\", At, mtl::tag::row());\n    two_d_iteration(\"Transposed Column-wise\", At, mtl::tag::col());\n    two_d_iteration(\"Transposed On Major\", At, mtl::tag::major());\n\n    mtl::dense2D<double> B(3.0 * A);\n    cout << \"3*A is\\n\" << B << \"\\n\\n\";\n}\n\nint main(int, char**)\n{\n    typedef mtl::dense_vector<double> vt;\n    typedef mtl::dense_vector<double, mtl::vec::parameters<mtl::row_major> >  vrt;\n    vt  v(2), w(3);\n    vrt z(3);\n    v= 1, 2; w= 2, 3, 4; z= trans(w);\n\n#if 0\n    using namespace mtl; \n    cout << \"ashape<v> is \" << typeid(ashape::ashape<vt>::type).name() << \"\\n\";\n    cout << \"ashape<z> is \" << typeid(ashape::ashape<vrt>::type).name() << \"\\n\";\n    cout << \"ashape<v*z> is \" << typeid(ashape::mult_op<ashape::ashape<vt>::type, ashape::ashape<vrt>::type>::type).name() << \"\\n\";\n    cout << \"mult_result<v*z> is \" << typeid(mtl::traits::vec_mult_result<vt, vrt>::type).name() << \"\\n\";\n    cout << \"v * z is \" << typeid(v * z).name() << \"\\n\";\n    return 0;\n#endif\n\n    test(\"ones(2, 3)\", mtl::ones(2, 3), 1);\n    test(\"ones<float>(2, 3)\", mtl::ones<float>(2, 3), 1.f);\n    test(\"v * trans(w)\", mtl::mat::outer_product_matrix<vt, vt>(v, w), 3.0);\n    test(\"v * z\", v * z, 3.0);\n    test(\"v * trans(w)\", v * trans(w), 3.0);\n    test(\"hilbert_matrix(2, 3)\", mtl::mat::hilbert_matrix<>(2, 3), 0.5);\n    \n    return 0;\n}\n \n", "meta": {"hexsha": "59c9af4cb324dd56df66bb2712190dd2a6854d78", "size": 3871, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/implicit_matrix_test.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/mtl/test/implicit_matrix_test.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/mtl/test/implicit_matrix_test.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 36.5188679245, "max_line_length": 131, "alphanum_fraction": 0.5920950659, "num_tokens": 1199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947290421276, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.4514226109520124}}
{"text": "/* ---------------------------------------------------------------------\n *\n * Copyright (C) 1999 - 2019 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 of the deal.II distribution.\n *\n * ---------------------------------------------------------------------\n *\n * based on deal.II step-1\n */\n\n\n#include <deal.II/grid/grid_generator.h>\n#include <deal.II/grid/grid_out.h>\n#include <deal.II/grid/tria.h>\n#include <deal.II/grid/tria_accessor.h>\n#include <deal.II/grid/tria_iterator.h>\n\n#include <cmath>\n#include <fstream>\n#include <iostream>\n\nusing namespace dealii;\n\n\n//! Generate a hypercube, and output it as an svg file.\nvoid first_grid(Triangulation<2> &triangulation)\n{\n  GridGenerator::hyper_cube(triangulation);\n  triangulation.refine_global(4);\n\n  std::ofstream out(\"grid-1.svg\");\n  GridOut       grid_out;\n  grid_out.write_svg(triangulation, out);\n  std::cout << \"Grid written to grid-1.svg\" << std::endl;\n}\n\n\n//! Generate a locally refined hyper_shell, and output it as an svg file.\nvoid second_grid(Triangulation<2> &triangulation)\n{\n  const Point<2> center(1, 0);\n  const double   inner_radius = 0.5, outer_radius = 1.0;\n  GridGenerator::hyper_shell(\n    triangulation, center, inner_radius, outer_radius, 10);\n\n  // triangulation.reset_manifold(0);\n\n  for (unsigned int step = 0; step < 5; ++step)\n    {\n      for (auto &cell : triangulation.active_cell_iterators())\n        {\n          for (const auto v : cell->vertex_indices())\n            {\n              const double distance_from_center =\n                center.distance(cell->vertex(v));\n\n              if (std::fabs(distance_from_center - inner_radius) <=\n                  1e-6 * inner_radius)\n                {\n                  cell->set_refine_flag();\n                  break;\n                }\n            }\n        }\n\n      triangulation.execute_coarsening_and_refinement();\n    }\n\n\n  std::ofstream out(\"grid-2.svg\");\n  GridOut       grid_out;\n  grid_out.write_svg(triangulation, out);\n\n  std::cout << \"Grid written to grid-2.svg\" << std::endl;\n}\n\n//! Create an L-shaped domain with one global refinement, and write it on\n// `third_grid.vtk`.  Refine the L-shaped mesh adaptively around the re-entrant\n// corner three times (after the global refinement you already did), but with a\n// twist: refine all cells with the distance between the center of the cell and\n// re-entrant corner is smaller than 1/3.\nvoid third_grid(Triangulation<2> &tria)\n{\n  // Insert code here\n}\n\n//! Returns a tuple with number of levels, number of cells, number of active\n// cells. Test this with all of  your meshes.\nstd::tuple<unsigned int, unsigned int, unsigned int>\nget_info(const Triangulation<2> &)\n{\n  // Insert code here\n  return std::make_tuple(0, 0, 0);\n}\n\nint\nmain()\n{\n  {\n    Triangulation<2> triangulation;\n    first_grid(triangulation);\n  }\n  {\n    Triangulation<2> triangulation;\n    second_grid(triangulation);\n  }\n}\n", "meta": {"hexsha": "b47eeee3767cd4d08aebd358d47e3d68e98035ba", "size": 3275, "ext": "cc", "lang": "C++", "max_stars_repo_path": "source/step-1.cc", "max_stars_repo_name": "luca-heltai/sissa-mhpc-lab-02", "max_stars_repo_head_hexsha": "b08febd339a9ecf78f26d51b5082bb0483512a0d", "max_stars_repo_licenses": ["MIT"], "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/step-1.cc", "max_issues_repo_name": "luca-heltai/sissa-mhpc-lab-02", "max_issues_repo_head_hexsha": "b08febd339a9ecf78f26d51b5082bb0483512a0d", "max_issues_repo_licenses": ["MIT"], "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/step-1.cc", "max_forks_repo_name": "luca-heltai/sissa-mhpc-lab-02", "max_forks_repo_head_hexsha": "b08febd339a9ecf78f26d51b5082bb0483512a0d", "max_forks_repo_licenses": ["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.2327586207, "max_line_length": 79, "alphanum_fraction": 0.64, "num_tokens": 812, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.4514226109520123}}
{"text": "#ifndef DYN_MOD_H\n#define DYN_MOD_H\n\n#include <Eigen/Dense>\n#include <functional>\n\nclass DynamicModel {\n\n    public:\n\n        // State function type\n        typedef std::function<Eigen::VectorXd\n            (double, const Eigen::VectorXd&, const Eigen::VectorXd&)> stf;\n\n        // State function: dx/dt = f(t,x,w)\n        const stf f;\n\n        // State dimension\n        const int n;\n\n        // Absolute & relative tolerance\n        const double abstol, reltol;\n\n        // Constructor\n        DynamicModel(const stf& f_, int n_,\n            double abstol_, double reltol_);\n\n        // Propagate state from ti to tf with noise w\n        Eigen::VectorXd operator() (double ti, double tf,\n            const Eigen::VectorXd& xi, const Eigen::VectorXd& w);\n\n    private:\n\n        // Workspace\n        Eigen::VectorXd work;\n        int iwork[5];\n\n};\n\n#endif\n", "meta": {"hexsha": "54181397452e7ccf17b636dde51eb7401712dd55", "size": 856, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dyn.hpp", "max_stars_repo_name": "SIOSlab/HOUSE", "max_stars_repo_head_hexsha": "81381a2384bd84be1afc49cace288c0606ee480f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dyn.hpp", "max_issues_repo_name": "SIOSlab/HOUSE", "max_issues_repo_head_hexsha": "81381a2384bd84be1afc49cace288c0606ee480f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dyn.hpp", "max_forks_repo_name": "SIOSlab/HOUSE", "max_forks_repo_head_hexsha": "81381a2384bd84be1afc49cace288c0606ee480f", "max_forks_repo_licenses": ["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.8780487805, "max_line_length": 74, "alphanum_fraction": 0.5864485981, "num_tokens": 198, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.689305616785446, "lm_q2_score": 0.6548947223065754, "lm_q1q2_score": 0.45142261048906734}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2014   LASMEA UMR 6602 CNRS/UBP\n//         Copyright 2009 - 2014   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n// cover for functor pow in scalar mode\n#include <nt2/exponential/include/functions/pow.hpp>\n#include <boost/simd/sdk/simd/io.hpp>\n#include <cmath>\n#include <iostream>\n#include <nt2/sdk/meta/as_integer.hpp>\n#include <nt2/sdk/unit/args.hpp>\n#include <nt2/sdk/unit/module.hpp>\n#include <nt2/sdk/unit/tests/cover.hpp>\n#include <vector>\n\nextern \"C\" { long double cephes_powil(long double,int); }\nextern \"C\" { long double cephes_powl(long double,long double); }\n\nNT2_TEST_CASE_TPL(pow_1,  NT2_REAL_TYPES)\n{\n  using nt2::unit::args;\n  const std::size_t NR = args(\"samples\", NT2_NB_RANDOM_TEST);\n  const double ulpd = args(\"ulpd\", 2);\n\n  const T min1_0 = args(\"min1_0\", T(0));\n  const T max1_0 = args(\"max1_0\", T(100));\n  std::cout << \"Argument samples #0 chosen in range: [\" << min1_0 << \",  \" << max1_0 << \"]\" << std::endl;\n  NT2_CREATE_BUF(a0,T, NR, min1_0, max1_0);\n  const T min1_1 = args(\"min1_1\", T(-10));\n  const T max1_1 = args(\"max1_1\", T(10));\n  std::cout << \"Argument samples #1 chosen in range: [\" << min1_1 << \",  \" << max1_1 << \"]\" << std::endl;\n  NT2_CREATE_BUF(a1,T, NR, min1_1, max1_1);\n\n  std::vector<T> ref(NR);\n  for(std::size_t i=0; i!=NR; ++i)\n    ref[i] = ::cephes_powl(a0[i],a1[i]);\n\n  NT2_COVER_ULP_EQUAL(nt2::tag::pow_, ((T, a0))((T, a1)), ref, ulpd);\n}\n\nNT2_TEST_CASE_TPL(pow_2,  NT2_REAL_TYPES)\n{\n  using nt2::unit::args;\n  const std::size_t NR = args(\"samples\", NT2_NB_RANDOM_TEST);\n  const double ulpd = args(\"ulpd\", 2);\n\n  typedef typename nt2::meta::as_integer<T>::type iT;\n  const T min1_0 = args(\"min1_0\", T(0));\n  const T max1_0 = args(\"max1_0\", T(100));\n  std::cout << \"Argument samples #0 chosen in range: [\" << min1_0 << \",  \" << max1_0 << \"]\" << std::endl;\n  NT2_CREATE_BUF(a0,T, NR, min1_0, max1_0);\n  const iT min1_1 = args(\"min1_1\", iT(-10));\n  const iT max1_1 = args(\"max1_1\", iT(10));\n  std::cout << \"Argument samples #1 chosen in range: [\" << min1_1 << \",  \" << max1_1 << \"]\" << std::endl;\n  NT2_CREATE_BUF(a1,iT, NR, min1_1, max1_1);\n\n  std::vector<T> ref(NR);\n  for(std::size_t i=0; i!=NR; ++i)\n    ref[i] = ::cephes_powl(a0[i],(long double)a1[i]);\n\n  NT2_COVER_ULP_EQUAL(nt2::tag::pow_, ((T, a0))((iT, a1)), ref, ulpd);\n}\n", "meta": {"hexsha": "2f8aec9a44dd694e226cecfbd065fa1bea635b20", "size": 2658, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/core/exponential/cover/scalar/pow.cpp", "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/exponential/cover/scalar/pow.cpp", "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/exponential/cover/scalar/pow.cpp", "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.671641791, "max_line_length": 105, "alphanum_fraction": 0.5906696764, "num_tokens": 885, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947290421276, "lm_q2_score": 0.6893056040203135, "lm_q1q2_score": 0.45142260677210333}}
{"text": "/* ----------------------------------------------------------------------------\n\n* GTSAM Copyright 2010-2020, 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 testDiscreteBayesTree.cpp\n * @date sept 15, 2012\n * @author Frank Dellaert\n */\n\n#include <gtsam/base/Vector.h>\n#include <gtsam/discrete/DiscreteBayesNet.h>\n#include <gtsam/discrete/DiscreteBayesTree.h>\n#include <gtsam/discrete/DiscreteFactorGraph.h>\n#include <gtsam/inference/BayesNet.h>\n\n#include <boost/assign/std/vector.hpp>\nusing namespace boost::assign;\n\n#include <CppUnitLite/TestHarness.h>\n\n#include <iostream>\n#include <vector>\n\nusing namespace std;\nusing namespace gtsam;\nstatic constexpr bool debug = false;\n\n/* ************************************************************************* */\nstruct TestFixture {\n  vector<DiscreteKey> keys;\n  DiscreteBayesNet bayesNet;\n  boost::shared_ptr<DiscreteBayesTree> bayesTree;\n\n  /**\n   * Create a thin-tree Bayesnet, a la Jean-Guillaume Durand (former student),\n   * and then create the Bayes tree from it.\n   */\n  TestFixture() {\n    // Define variables.\n    for (int i = 0; i < 15; i++) {\n      DiscreteKey key_i(i, 2);\n      keys.push_back(key_i);\n    }\n\n    // Create thin-tree Bayesnet.\n    bayesNet.add(keys[14] % \"1/3\");\n\n    bayesNet.add(keys[13] | keys[14] = \"1/3 3/1\");\n    bayesNet.add(keys[12] | keys[14] = \"3/1 3/1\");\n\n    bayesNet.add((keys[11] | keys[13], keys[14]) = \"1/4 2/3 3/2 4/1\");\n    bayesNet.add((keys[10] | keys[13], keys[14]) = \"1/4 3/2 2/3 4/1\");\n    bayesNet.add((keys[9] | keys[12], keys[14]) = \"4/1 2/3 F 1/4\");\n    bayesNet.add((keys[8] | keys[12], keys[14]) = \"T 1/4 3/2 4/1\");\n\n    bayesNet.add((keys[7] | keys[11], keys[13]) = \"1/4 2/3 3/2 4/1\");\n    bayesNet.add((keys[6] | keys[11], keys[13]) = \"1/4 3/2 2/3 4/1\");\n    bayesNet.add((keys[5] | keys[10], keys[13]) = \"4/1 2/3 3/2 1/4\");\n    bayesNet.add((keys[4] | keys[10], keys[13]) = \"2/3 1/4 3/2 4/1\");\n\n    bayesNet.add((keys[3] | keys[9], keys[12]) = \"1/4 2/3 3/2 4/1\");\n    bayesNet.add((keys[2] | keys[9], keys[12]) = \"1/4 8/2 2/3 4/1\");\n    bayesNet.add((keys[1] | keys[8], keys[12]) = \"4/1 2/3 3/2 1/4\");\n    bayesNet.add((keys[0] | keys[8], keys[12]) = \"2/3 1/4 3/2 4/1\");\n\n    // Create a BayesTree out of the Bayes net.\n    bayesTree = DiscreteFactorGraph(bayesNet).eliminateMultifrontal();\n  }\n};\n\n/* ************************************************************************* */\nTEST(DiscreteBayesTree, ThinTree) {\n  const TestFixture self;\n  const auto& keys = self.keys;\n\n  if (debug) {\n    GTSAM_PRINT(self.bayesNet);\n    self.bayesNet.saveGraph(\"/tmp/discreteBayesNet.dot\");\n  }\n\n  // create a BayesTree out of a Bayes net\n  if (debug) {\n    GTSAM_PRINT(*self.bayesTree);\n    self.bayesTree->saveGraph(\"/tmp/discreteBayesTree.dot\");\n  }\n\n  // Check frontals and parents\n  for (size_t i : {13, 14, 9, 3, 2, 8, 1, 0, 10, 5, 4}) {\n    auto clique_i = (*self.bayesTree)[i];\n    EXPECT_LONGS_EQUAL(i, *(clique_i->conditional_->beginFrontals()));\n  }\n\n  auto R = self.bayesTree->roots().front();\n\n  // Check whether BN and BT give the same answer on all configurations\n  auto allPosbValues =\n      cartesianProduct(keys[0] & keys[1] & keys[2] & keys[3] & keys[4] &\n                       keys[5] & keys[6] & keys[7] & keys[8] & keys[9] &\n                       keys[10] & keys[11] & keys[12] & keys[13] & keys[14]);\n  for (size_t i = 0; i < allPosbValues.size(); ++i) {\n    DiscreteValues x = allPosbValues[i];\n    double expected = self.bayesNet.evaluate(x);\n    double actual = self.bayesTree->evaluate(x);\n    DOUBLES_EQUAL(expected, actual, 1e-9);\n  }\n\n  // Calculate all some marginals for DiscreteValues==all1\n  Vector marginals = Vector::Zero(15);\n  double joint_12_14 = 0, joint_9_12_14 = 0, joint_8_12_14 = 0, joint_8_12 = 0,\n         joint82 = 0, joint12 = 0, joint24 = 0, joint45 = 0, joint46 = 0,\n         joint_4_11 = 0, joint_11_13 = 0, joint_11_13_14 = 0,\n         joint_11_12_13_14 = 0, joint_9_11_12_13 = 0, joint_8_11_12_13 = 0;\n  for (size_t i = 0; i < allPosbValues.size(); ++i) {\n    DiscreteValues x = allPosbValues[i];\n    double px = self.bayesTree->evaluate(x);\n    for (size_t i = 0; i < 15; i++)\n      if (x[i]) marginals[i] += px;\n    if (x[12] && x[14]) {\n      joint_12_14 += px;\n      if (x[9]) joint_9_12_14 += px;\n      if (x[8]) joint_8_12_14 += px;\n    }\n    if (x[8] && x[12]) joint_8_12 += px;\n    if (x[2]) {\n      if (x[8]) joint82 += px;\n      if (x[1]) joint12 += px;\n    }\n    if (x[4]) {\n      if (x[2]) joint24 += px;\n      if (x[5]) joint45 += px;\n      if (x[6]) joint46 += px;\n      if (x[11]) joint_4_11 += px;\n    }\n    if (x[11] && x[13]) {\n      joint_11_13 += px;\n      if (x[8] && x[12]) joint_8_11_12_13 += px;\n      if (x[9] && x[12]) joint_9_11_12_13 += px;\n      if (x[14]) {\n        joint_11_13_14 += px;\n        if (x[12]) {\n          joint_11_12_13_14 += px;\n        }\n      }\n    }\n  }\n  DiscreteValues all1 = allPosbValues.back();\n\n  // check separator marginal P(S0)\n  auto clique = (*self.bayesTree)[0];\n  DiscreteFactorGraph separatorMarginal0 =\n      clique->separatorMarginal(EliminateDiscrete);\n  DOUBLES_EQUAL(joint_8_12, separatorMarginal0(all1), 1e-9);\n\n  // check separator marginal P(S9), should be P(14)\n  clique = (*self.bayesTree)[9];\n  DiscreteFactorGraph separatorMarginal9 =\n      clique->separatorMarginal(EliminateDiscrete);\n  DOUBLES_EQUAL(marginals[14], separatorMarginal9(all1), 1e-9);\n\n  // check separator marginal of root, should be empty\n  clique = (*self.bayesTree)[11];\n  DiscreteFactorGraph separatorMarginal11 =\n      clique->separatorMarginal(EliminateDiscrete);\n  LONGS_EQUAL(0, separatorMarginal11.size());\n\n  // check shortcut P(S9||R) to root\n  clique = (*self.bayesTree)[9];\n  DiscreteBayesNet shortcut = clique->shortcut(R, EliminateDiscrete);\n  LONGS_EQUAL(1, shortcut.size());\n  DOUBLES_EQUAL(joint_11_13_14 / joint_11_13, shortcut.evaluate(all1), 1e-9);\n\n  // check shortcut P(S8||R) to root\n  clique = (*self.bayesTree)[8];\n  shortcut = clique->shortcut(R, EliminateDiscrete);\n  DOUBLES_EQUAL(joint_11_12_13_14 / joint_11_13, shortcut.evaluate(all1), 1e-9);\n\n  // check shortcut P(S2||R) to root\n  clique = (*self.bayesTree)[2];\n  shortcut = clique->shortcut(R, EliminateDiscrete);\n  DOUBLES_EQUAL(joint_9_11_12_13 / joint_11_13, shortcut.evaluate(all1), 1e-9);\n\n  // check shortcut P(S0||R) to root\n  clique = (*self.bayesTree)[0];\n  shortcut = clique->shortcut(R, EliminateDiscrete);\n  DOUBLES_EQUAL(joint_8_11_12_13 / joint_11_13, shortcut.evaluate(all1), 1e-9);\n\n  // calculate all shortcuts to root\n  DiscreteBayesTree::Nodes cliques = self.bayesTree->nodes();\n  for (auto clique : cliques) {\n    DiscreteBayesNet shortcut = clique.second->shortcut(R, EliminateDiscrete);\n    if (debug) {\n      clique.second->conditional_->printSignature();\n      shortcut.print(\"shortcut:\");\n    }\n  }\n\n  // Check all marginals\n  DiscreteFactor::shared_ptr marginalFactor;\n  for (size_t i = 0; i < 15; i++) {\n    marginalFactor = self.bayesTree->marginalFactor(i, EliminateDiscrete);\n    double actual = (*marginalFactor)(all1);\n    DOUBLES_EQUAL(marginals[i], actual, 1e-9);\n  }\n\n  DiscreteBayesNet::shared_ptr actualJoint;\n\n  // Check joint P(8, 2)\n  actualJoint = self.bayesTree->jointBayesNet(8, 2, EliminateDiscrete);\n  DOUBLES_EQUAL(joint82, actualJoint->evaluate(all1), 1e-9);\n\n  // Check joint P(1, 2)\n  actualJoint = self.bayesTree->jointBayesNet(1, 2, EliminateDiscrete);\n  DOUBLES_EQUAL(joint12, actualJoint->evaluate(all1), 1e-9);\n\n  // Check joint P(2, 4)\n  actualJoint = self.bayesTree->jointBayesNet(2, 4, EliminateDiscrete);\n  DOUBLES_EQUAL(joint24, actualJoint->evaluate(all1), 1e-9);\n\n  // Check joint P(4, 5)\n  actualJoint = self.bayesTree->jointBayesNet(4, 5, EliminateDiscrete);\n  DOUBLES_EQUAL(joint45, actualJoint->evaluate(all1), 1e-9);\n\n  // Check joint P(4, 6)\n  actualJoint = self.bayesTree->jointBayesNet(4, 6, EliminateDiscrete);\n  DOUBLES_EQUAL(joint46, actualJoint->evaluate(all1), 1e-9);\n\n  // Check joint P(4, 11)\n  actualJoint = self.bayesTree->jointBayesNet(4, 11, EliminateDiscrete);\n  DOUBLES_EQUAL(joint_4_11, actualJoint->evaluate(all1), 1e-9);\n}\n\n/* ************************************************************************* */\nTEST(DiscreteBayesTree, Dot) {\n  const TestFixture self;\n  string actual = self.bayesTree->dot();\n  EXPECT(actual ==\n         \"digraph G{\\n\"\n         \"0[label=\\\"13,11,6,7\\\"];\\n\"\n         \"0->1\\n\"\n         \"1[label=\\\"14 : 11,13\\\"];\\n\"\n         \"1->2\\n\"\n         \"2[label=\\\"9,12 : 14\\\"];\\n\"\n         \"2->3\\n\"\n         \"3[label=\\\"3 : 9,12\\\"];\\n\"\n         \"2->4\\n\"\n         \"4[label=\\\"2 : 9,12\\\"];\\n\"\n         \"2->5\\n\"\n         \"5[label=\\\"8 : 12,14\\\"];\\n\"\n         \"5->6\\n\"\n         \"6[label=\\\"1 : 8,12\\\"];\\n\"\n         \"5->7\\n\"\n         \"7[label=\\\"0 : 8,12\\\"];\\n\"\n         \"1->8\\n\"\n         \"8[label=\\\"10 : 13,14\\\"];\\n\"\n         \"8->9\\n\"\n         \"9[label=\\\"5 : 10,13\\\"];\\n\"\n         \"8->10\\n\"\n         \"10[label=\\\"4 : 10,13\\\"];\\n\"\n         \"}\");\n}\n\n/* ************************************************************************* */\nint main() {\n  TestResult tr;\n  return TestRegistry::runAllTests(tr);\n}\n/* ************************************************************************* */\n", "meta": {"hexsha": "edb5ea46c6dc2a766683b0d5787a399f1e724087", "size": 9390, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/discrete/tests/testDiscreteBayesTree.cpp", "max_stars_repo_name": "cdb0y511/gtsam", "max_stars_repo_head_hexsha": "e5b928c61032cb3aaa9b88a44fbe2ed4ba08b7ca", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gtsam/discrete/tests/testDiscreteBayesTree.cpp", "max_issues_repo_name": "cdb0y511/gtsam", "max_issues_repo_head_hexsha": "e5b928c61032cb3aaa9b88a44fbe2ed4ba08b7ca", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/discrete/tests/testDiscreteBayesTree.cpp", "max_forks_repo_name": "cdb0y511/gtsam", "max_forks_repo_head_hexsha": "e5b928c61032cb3aaa9b88a44fbe2ed4ba08b7ca", "max_forks_repo_licenses": ["BSD-3-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.0217391304, "max_line_length": 80, "alphanum_fraction": 0.5853035144, "num_tokens": 3182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056040203135, "lm_q2_score": 0.6548947290421276, "lm_q1q2_score": 0.45142260677210333}}
{"text": "#include \"SaveFile.h\"\n#include <boost/multiprecision/cpp_int.hpp>\n\nstd::pair<std::array<char, 11>, uint64_t> calculateFileKey(boost::filesystem::path filename) {\n\tuint64_t staticKey = 0x1415926535897932;\n\tuint64_t dynamicKey;\n\n\tif (filename.filename().string().substr(0, 5) == \"slot_\")\n\t\tdynamicKey = *reinterpret_cast<const uint64_t*>(\"@Tokomon\");\n\telse if (filename.filename().string() == \"system_data.bin\")\n\t\tdynamicKey = *reinterpret_cast<const uint64_t*>(\"@Dagomon\");\n\telse\n\t\tdynamicKey = *reinterpret_cast<const uint64_t*>(\"@Lilimon\");\n\n\tuint64_t val = dynamicKey ^ staticKey;\n\tstd::array<char, 11> key1;\n\tkey1[0] = (char) (val >> 0x08);\n\tkey1[1] = (char) (val >> 0x30);\n\tkey1[2] = (char) (val >> 0x18);\n\tkey1[3] = (char) (val >> 0x00);\n\tkey1[4] = (char) (val >> 0x10);\n\tkey1[5] = (char) (val >> 0x03);\n\tkey1[6] = (char) (val >> 0x28);\n\tkey1[7] = (char) (val >> 0x15);\n\tkey1[8] = (char) (val >> 0x20);\n\tkey1[9] = (char) (val >> 0x2F);\n\tkey1[10] = (char) (val >> 0x38);\n\n\treturn std::make_pair(key1, val);\n}\n\nvoid decryptSaveFile(boost::filesystem::path source, boost::filesystem::path target) {\n\tif (boost::filesystem::equivalent(source, target)) {\n\t\tstd::cout << \"Error: input and output path must be different!\" << std::endl;\n\t\treturn;\n\t}\n\tif (!boost::filesystem::is_regular_file(source)) {\n\t\tstd::cout << \"Error: source path is not a regular file.\" << std::endl;\n\t\treturn;\n\t}\n\tif (!boost::filesystem::exists(target))\n\t\tboost::filesystem::create_directories(target.parent_path());\n\telse if (!boost::filesystem::is_regular_file(target)) {\n\t\tstd::cout << \"Error: target path is not a regular file.\" << std::endl;\n\t\treturn;\n\t}\n\n\tboost::filesystem::ifstream input(source, std::ios::in | std::ios::binary);\n\tboost::filesystem::ofstream output(target, std::ios::out | std::ios::binary);\n\n\tauto fileKey = calculateFileKey(source.filename());\n\tstd::array<char, 11> key1 = fileKey.first;\n\tuint64_t val = fileKey.second;\n\n\tinput.seekg(0, std::ios::end);\n\tstd::streamoff length = input.tellg();\n\tinput.seekg(0, std::ios::beg);\n\n\tuint32_t size = (uint32_t) length;\n\tuint32_t offset = 0;\n\tuint32_t remaining = size;\n\n\tchar* buffer = new char[size];\n\tinput.read(buffer, size);\n\n\t{ // rotate bits step\n\t\tboost::multiprecision::uint128_t magic = 0x801302D26B3BEAE5;\n\t\tuint64_t initialVector = (uint64_t) ((magic * val) >> 0x4E);\n\t\tuint32_t rotateParameter = (uint32_t) (((uint32_t) val) - initialVector * 0x7FED);\n\n\t\twhile (remaining) {\n\t\t\tuint32_t read = remaining < 16 ? remaining : 16;\n\n\t\t\tuint32_t tmp2 = (rotateParameter * (uint64_t) 0x24924925) >> 32;\n\t\t\tint32_t rotateCount = (((((rotateParameter - tmp2) >> 1) + tmp2) >> 2) * 7) - rotateParameter - 1;\n\n\t\t\tuint64_t valueSum = 0;\n\t\t\tfor (uint32_t i = 0; i < read; i++) {\n\t\t\t\tuint8_t val = buffer[offset + i];\n\t\t\t\tfor (int j = 0; j < -rotateCount; j++)\n\t\t\t\t\tval = (val >> 1) | (val << 7);\n\n\t\t\t\tvalueSum += val;\n\t\t\t\tbuffer[offset + i] = val;\n\t\t\t}\n\n\t\t\tuint64_t tmp = ((uint64_t) 0x72C62A25 * valueSum) >> 0x28;\n\t\t\ttmp2 = (uint32_t) ((rotateParameter * 0x10DCD + 1) + (valueSum - (tmp * 0x23B)) * 2);\n\t\t\trotateParameter = tmp2 - (((uint64_t) 0x40004001 * tmp2) >> 0x3D) * 0x7FFF7FFF;\n\n\t\t\toffset += 0x10;\n\t\t\tremaining -= 0x10;\n\t\t}\n\t}\n\t{ // xor and math step\n\t\tboost::multiprecision::uint128_t magic2 = 0x3B2153E7529FE1FF;\n\t\tuint64_t tmp = (uint64_t) ((val * magic2) >> 64);\n\t\tuint32_t init = (uint32_t) ((val) -(((((val - tmp) >> 1) + tmp) >> 0xF) * 0xCFF7));\n\n\t\tuint32_t charSum = 0;\n\n\t\tfor (uint32_t i = 0; i < size; i++) {\n\t\t\tuint8_t value = buffer[i];\n\n\t\t\tuint64_t localMagic1 = 0xAB8F69E3;\n\t\t\tuint64_t localMagic2 = 0x2E8BA2E9;\n\n\t\t\tvalue = value - (uint8_t) (((localMagic1 * charSum) >> 0x27) * 0x41);\n\t\t\tvalue = value - (uint8_t) charSum;\n\n\t\t\tuint32_t tmp = (localMagic2 * i) >> 0x21;\n\t\t\tuint32_t keyOffset = i - ((tmp + (tmp >> 0x1F)) * 0xB);\n\n\t\t\tvalue = value ^ key1[keyOffset];\n\t\t\tvalue = value ^ (uint8_t) init;\n\t\t\tbuffer[i] = value;\n\t\t\tcharSum += value;\n\n\t\t\tuint64_t tmp2 = init * 0x10DCD + 0x0D;\n\t\t\tinit = (uint32_t) tmp2 - (((tmp2 * 0x40004001) >> 0x3D) * 0x7FFF7FFF);\n\t\t}\n\t}\n\n\toutput.write(buffer, size);\n\tinput.close();\n\toutput.close();\n\tdelete buffer;\n}\n\nvoid encryptSaveFile(boost::filesystem::path source, boost::filesystem::path target) {\n\tif (boost::filesystem::equivalent(source, target)) {\n\t\tstd::cout << \"Error: input and output path must be different!\" << std::endl;\n\t\treturn;\n\t}\n\tif (!boost::filesystem::is_regular_file(source)) {\n\t\tstd::cout << \"Error: source path is not a regular file.\" << std::endl;\n\t\treturn;\n\t}\n\tif (!boost::filesystem::exists(target))\n\t\tboost::filesystem::create_directories(target.parent_path());\n\telse if (!boost::filesystem::is_regular_file(target)) {\n\t\tstd::cout << \"Error: target path is not a regular file.\" << std::endl;\n\t\treturn;\n\t}\n\n\tboost::filesystem::ifstream input(source, std::ios::in | std::ios::binary);\n\tboost::filesystem::ofstream output(target, std::ios::out | std::ios::binary);\n\n\tauto fileKey = calculateFileKey(source.filename());\n\tstd::array<char, 11> key1 = fileKey.first;\n\tuint64_t val = fileKey.second;\n\n\tinput.seekg(0, std::ios::end);\n\tstd::streamoff length = input.tellg();\n\tinput.seekg(0, std::ios::beg);\n\n\tuint32_t size = (uint32_t) length;\n\tuint32_t offset = 0;\n\tuint32_t remaining = size;\n\n\tchar* buffer = new char[size];\n\tinput.read(buffer, size);\n\n\t{ // xor and math step\n\t\tboost::multiprecision::uint128_t magic2 = 0x3B2153E7529FE1FF;\n\t\tuint64_t tmp = (uint64_t) ((val * magic2) >> 64);\n\t\tuint32_t init = (uint32_t) ((val) -(((((val - tmp) >> 1) + tmp) >> 0xF) * 0xCFF7));\n\n\t\tuint32_t charSum = 0;\n\n\t\tfor (uint32_t i = 0; i < size; i++) {\n\t\t\tuint8_t value = buffer[i];\n\n\t\t\tuint64_t localMagic1 = 0xAB8F69E3;\n\t\t\tuint64_t localMagic2 = 0x2E8BA2E9;\n\t\t\tuint32_t tmp = (localMagic2 * i) >> 0x21;\n\t\t\tuint32_t keyOffset = i - ((tmp + (tmp >> 0x1F)) * 0xB);\n\n\t\t\tvalue = value ^ (uint8_t) init;\n\t\t\tvalue = value ^ key1[keyOffset];\n\t\t\tvalue = value + (uint8_t) charSum;\n\t\t\tvalue = value + (uint8_t) (((localMagic1 * charSum) >> 0x27) * 0x41);\n\t\t\tcharSum += (uint8_t) buffer[i];\n\t\t\tbuffer[i] = value;\n\n\t\t\tuint64_t tmp2 = init * 0x10DCD + 0x0D;\n\t\t\tinit = (uint32_t) tmp2 - (((tmp2 * 0x40004001) >> 0x3D) * 0x7FFF7FFF);\n\t\t}\n\t}\n\t{ // rotate bits step\n\t\tboost::multiprecision::uint128_t magic = 0x801302D26B3BEAE5;\n\t\tuint64_t initialVector = (uint64_t) ((magic * val) >> 0x4E);\n\t\tuint32_t rotateParameter = (uint32_t) (((uint32_t) val) - initialVector * 0x7FED);\n\n\t\twhile (remaining) {\n\t\t\tuint32_t read = remaining < 16 ? remaining : 16;\n\n\t\t\tuint32_t tmp2 = (rotateParameter * (uint64_t) 0x24924925) >> 32;\n\t\t\tint32_t rotateCount = (((((rotateParameter - tmp2) >> 1) + tmp2) >> 2) * 7) - rotateParameter - 1;\n\n\t\t\tuint64_t valueSum = 0;\n\t\t\tfor (uint32_t i = 0; i < read; i++) {\n\t\t\t\tuint8_t val = buffer[offset + i];\n\t\t\t\tvalueSum += val;\n\n\t\t\t\tfor (int j = 0; j < -rotateCount; j++)\n\t\t\t\t\tval = (val << 1) | (val >> 7);\n\n\t\t\t\tbuffer[offset + i] = val;\n\t\t\t}\n\n\t\t\tuint64_t tmp = ((uint64_t) 0x72C62A25 * valueSum) >> 0x28;\n\t\t\ttmp2 = (uint32_t) ((rotateParameter * 0x10DCD + 1) + (valueSum - (tmp * 0x23B)) * 2);\n\t\t\trotateParameter = tmp2 - (((uint64_t) 0x40004001 * tmp2) >> 0x3D) * 0x7FFF7FFF;\n\n\t\t\toffset += 0x10;\n\t\t\tremaining -= 0x10;\n\t\t}\n\t}\n\n\toutput.write(buffer, size);\n\tinput.close();\n\toutput.close();\n\tdelete buffer;\n}\n", "meta": {"hexsha": "2bfb2b2e88874ffa02e3c915d23405dea9a0c6cd", "size": 7228, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "DSCSTools/SaveFile.cpp", "max_stars_repo_name": "arves100/DSCSTools", "max_stars_repo_head_hexsha": "7d8d031563b06e11e1e2148ce26bb7018ebfa6b2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DSCSTools/SaveFile.cpp", "max_issues_repo_name": "arves100/DSCSTools", "max_issues_repo_head_hexsha": "7d8d031563b06e11e1e2148ce26bb7018ebfa6b2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DSCSTools/SaveFile.cpp", "max_forks_repo_name": "arves100/DSCSTools", "max_forks_repo_head_hexsha": "7d8d031563b06e11e1e2148ce26bb7018ebfa6b2", "max_forks_repo_licenses": ["BSD-3-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.982300885, "max_line_length": 101, "alphanum_fraction": 0.6395960155, "num_tokens": 2519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267660487573, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.4513740300450122}}
{"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_ILOGB_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_ILOGB_HPP_INCLUDED\n\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/detail/brigand.hpp>\n#include <boost/simd/function/exponent.hpp>\n#include <boost/simd/function/is_gtz.hpp>\n#include <boost/simd/detail/math.hpp>\n#include <boost/simd/detail/dispatch/function/overload.hpp>\n#include <boost/simd/detail/dispatch/meta/as_floating.hpp>\n#include <boost/simd/detail/dispatch/meta/as_integer.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 ( ilogb_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_< bd::integer_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() ( A0 a0 ) const BOOST_NOEXCEPT\n    {\n      return static_cast<A0>(bs::ilogb(static_cast<bd::as_floating_t<A0>>(a0)));\n    }\n  };\n\n#ifdef BOOST_SIMD_HAS_ILOGB\n  BOOST_DISPATCH_OVERLOAD ( ilogb_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_< bd::double_<A0> >\n                          )\n  {\n    using result_t = bd::as_integer_t<A0, signed>;\n    BOOST_FORCEINLINE result_t operator() ( A0 a0 ) const BOOST_NOEXCEPT\n    {\n      return is_gtz(a0) ? ::ilogb(a0) : Zero<result_t>();\n    }\n  };\n#endif\n\n#ifdef BOOST_SIMD_HAS_ILOGBF\n  BOOST_DISPATCH_OVERLOAD ( ilogb_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_< bd::single_<A0> >\n                          )\n  {\n    using result_t = bd::as_integer_t<A0, signed>;\n    BOOST_FORCEINLINE result_t operator() ( A0 a0 ) const BOOST_NOEXCEPT\n    {\n      return is_gtz(a0) ? ::ilogbf(a0) : Zero<result_t>();\n    }\n  };\n#endif\n\n  BOOST_DISPATCH_OVERLOAD ( ilogb_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_< bd::floating_<A0> >\n                          )\n  {\n    using result_t = bd::as_integer_t<A0, signed>;\n    BOOST_FORCEINLINE result_t operator() ( A0 a0 ) const BOOST_NOEXCEPT\n    {\n      return is_gtz(a0) ? bs::exponent(a0) : Zero<result_t>();\n    }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "ce2d7a83b33e8166f92f50160f3afd82e748f2cd", "size": 2731, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/scalar/function/ilogb.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/scalar/function/ilogb.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/ilogb.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": 31.7558139535, "max_line_length": 100, "alphanum_fraction": 0.5437568656, "num_tokens": 643, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.45134919278793656}}
{"text": "// STL includes.\n#include <string>\n#include <vector>\n#include <cstdlib>\n#include <fstream>\n#include <iostream>\n#include <iterator>\n\n// Boost includes.\n#include <boost/iterator/function_output_iterator.hpp>\n\n// CGAL includes.\n#include <CGAL/Timer.h>\n#include <CGAL/Random.h>\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n\n#include <CGAL/Point_set_3.h>\n#include <CGAL/Point_set_3/IO.h>\n\n#include <CGAL/Shape_detection/Region_growing/Region_growing.h>\n#include <CGAL/Shape_detection/Region_growing/Region_growing_on_point_set.h>\n\n// Type declarations.\nusing Kernel = CGAL::Exact_predicates_inexact_constructions_kernel;\n\nusing FT       = typename Kernel::FT;\nusing Point_3  = typename Kernel::Point_3;\nusing Vector_3 = typename Kernel::Vector_3;\n\nusing Input_range = CGAL::Point_set_3<Point_3>;\nusing Point_map   = typename Input_range::Point_map;\nusing Normal_map  = typename Input_range::Vector_map;\n\nusing Neighbor_query = CGAL::Shape_detection::Point_set::K_neighbor_query<Kernel, Input_range, Point_map>;\nusing Region_type    = CGAL::Shape_detection::Point_set::Least_squares_plane_fit_region<Kernel, Input_range, Point_map, Normal_map>;\nusing Region_growing = CGAL::Shape_detection::Region_growing<Input_range, Neighbor_query, Region_type>;\n\nusing Indices      = std::vector<std::size_t>;\nusing Output_range = CGAL::Point_set_3<Point_3>;\nusing Points_3     = std::vector<Point_3>;\n\n// Define an insert iterator.\nstruct Insert_point_colored_by_region_index {\n\n  using argument_type = Indices;\n  using result_type   = void;\n\n  using Color_map =\n  typename Output_range:: template Property_map<unsigned char>;\n\n  const Input_range& m_input_range;\n  const   Point_map  m_point_map;\n       Output_range& m_output_range;\n        std::size_t& m_number_of_regions;\n\n  Color_map m_red, m_green, m_blue;\n\n  Insert_point_colored_by_region_index(\n    const Input_range& input_range,\n    const   Point_map  point_map,\n         Output_range& output_range,\n          std::size_t& number_of_regions) :\n  m_input_range(input_range),\n  m_point_map(point_map),\n  m_output_range(output_range),\n  m_number_of_regions(number_of_regions) {\n\n    m_red =\n    m_output_range.template add_property_map<unsigned char>(\"red\", 0).first;\n    m_green =\n    m_output_range.template add_property_map<unsigned char>(\"green\", 0).first;\n    m_blue =\n    m_output_range.template add_property_map<unsigned char>(\"blue\", 0).first;\n  }\n\n  result_type operator()(const argument_type& region) {\n\n    CGAL::Random rand(static_cast<unsigned int>(m_number_of_regions));\n    const unsigned char r =\n    static_cast<unsigned char>(64 + rand.get_int(0, 192));\n    const unsigned char g =\n    static_cast<unsigned char>(64 + rand.get_int(0, 192));\n    const unsigned char b =\n    static_cast<unsigned char>(64 + rand.get_int(0, 192));\n\n    for (const std::size_t index : region) {\n      const auto& key = *(m_input_range.begin() + index);\n\n      const Point_3& point = get(m_point_map, key);\n      const auto it = m_output_range.insert(point);\n\n      m_red[*it]   = r;\n      m_green[*it] = g;\n      m_blue[*it]  = b;\n    }\n    ++m_number_of_regions;\n  }\n}; // Insert_point_colored_by_region_index\n\nint main(int argc, char *argv[]) {\n\n  std::cout << std::endl <<\n    \"region_growing_on_point_set_3 example started\"\n  << std::endl << std::endl;\n\n  std::cout <<\n    \"Note: if 0 points are loaded, please specify the path to the file data/point_set_3.xyz by hand!\"\n  << std::endl << std::endl;\n\n  // Load xyz data either from a local folder or a user-provided file.\n  std::ifstream in(argc > 1 ? argv[1] : CGAL::data_file_path(\"points_3/point_set_3.xyz\"));\n  CGAL::IO::set_ascii_mode(in);\n\n  if (!in) {\n    std::cout <<\n    \"Error: cannot read the file point_set_3.xyz!\" << std::endl;\n    std::cout <<\n    \"You can either create a symlink to the data folder or provide this file by hand.\"\n    << std::endl << std::endl;\n    return EXIT_FAILURE;\n  }\n\n  const bool with_normal_map = true;\n  Input_range input_range(with_normal_map);\n\n  in >> input_range;\n  in.close();\n\n  std::cout <<\n    \"* loaded \"\n  << input_range.size() <<\n    \" points with normals\"\n  << std::endl;\n\n  // Default parameter values for the data file point_set_3.xyz.\n  const std::size_t k                     = 12;\n  const FT          max_distance_to_plane = FT(2);\n  const FT          max_accepted_angle    = FT(20);\n  const std::size_t min_region_size       = 50;\n\n  // Create instances of the classes Neighbor_query and Region_type.\n  Neighbor_query neighbor_query(\n    input_range,\n    k,\n    input_range.point_map());\n\n  Region_type region_type(\n    input_range,\n    max_distance_to_plane, max_accepted_angle, min_region_size,\n    input_range.point_map(), input_range.normal_map());\n\n  // Create an instance of the region growing class.\n  Region_growing region_growing(\n    input_range, neighbor_query, region_type);\n\n  // Run the algorithm.\n  Output_range output_range;\n  std::size_t number_of_regions = 0;\n\n  Insert_point_colored_by_region_index inserter(\n     input_range, input_range.point_map(),\n    output_range, number_of_regions);\n\n  CGAL::Timer timer;\n\n  timer.start();\n  region_growing.detect(\n    boost::make_function_output_iterator(inserter));\n  timer.stop();\n\n  // Print the number of found regions.\n  std::cout << \"* \" << number_of_regions <<\n    \" regions have been found in \" << timer.time() << \" seconds\"\n  << std::endl;\n\n  // Save the result to a file in the user-provided path if any.\n  if (argc > 2) {\n\n    const std::string path     = argv[2];\n    const std::string fullpath = path + \"regions_point_set_3.ply\";\n\n    std::ofstream out(fullpath);\n    out << output_range;\n\n    std::cout << \"* found regions are saved in \" << fullpath << std::endl;\n    out.close();\n  }\n\n  // Get all unassigned items.\n  Indices unassigned_items;\n  region_growing.unassigned_items(std::back_inserter(unassigned_items));\n\n  // Print the number of unassigned items.\n  std::cout << \"* \" << unassigned_items.size() <<\n    \" points do not belong to any region\"\n  << std::endl;\n\n  // Store all unassigned points.\n  Points_3 unassigned_points;\n  unassigned_points.reserve(unassigned_items.size());\n\n  for (const auto index : unassigned_items) {\n    const auto& key = *(input_range.begin() + index);\n\n    const Point_3& point = get(input_range.point_map(), key);\n    unassigned_points.push_back(point);\n  }\n\n  std::cout << \"* \" << unassigned_points.size() <<\n    \" unassigned points are stored\"\n  << std::endl;\n\n  std::cout << std::endl <<\n    \"region_growing_on_point_set_3 example finished\"\n  << std::endl << std::endl;\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "eccfa58f1a8ef4b02a2fb02b8825cb9560d00ba0", "size": 6582, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Shape_detection/examples/Shape_detection/region_growing_planes_on_point_set_3.cpp", "max_stars_repo_name": "ffteja/cgal", "max_stars_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 3227.0, "max_stars_repo_stars_event_min_datetime": "2015-03-05T00:19:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:20:35.000Z", "max_issues_repo_path": "Shape_detection/examples/Shape_detection/region_growing_planes_on_point_set_3.cpp", "max_issues_repo_name": "ffteja/cgal", "max_issues_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 5574.0, "max_issues_repo_issues_event_min_datetime": "2015-03-05T00:01:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:08:11.000Z", "max_forks_repo_path": "Shape_detection/examples/Shape_detection/region_growing_planes_on_point_set_3.cpp", "max_forks_repo_name": "ffteja/cgal", "max_forks_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1274.0, "max_forks_repo_forks_event_min_datetime": "2015-03-05T00:01:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:47:56.000Z", "avg_line_length": 30.0547945205, "max_line_length": 132, "alphanum_fraction": 0.7025220298, "num_tokens": 1663, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.45134919278793656}}
{"text": "/*    This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.\n *    See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.\n *    Author(s):       Vincent Rouvreau\n *\n *    Copyright (C) 2015 Inria\n *\n *    Modification(s):\n *      - YYYY/MM Author: Description of the modification\n */\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE \"alpha_complex_3d\"\n#include <boost/test/unit_test.hpp>\n#include <boost/mpl/list.hpp>\n\n#include <cmath>  // float comparison\n#include <limits>\n#include <string>\n#include <vector>\n#include <random>\n#include <cstddef>  // for std::size_t\n\n#include <gudhi/Alpha_complex_3d.h>\n#include <gudhi/graph_simplicial_complex.h>\n#include <gudhi/Simplex_tree.h>\n#include <gudhi/Unitary_tests_utils.h>\n// to construct Alpha_complex from a OFF file of points\n#include <gudhi/Points_3D_off_io.h>\n\n#include <CGAL/Random.h>\n#include <CGAL/point_generators_3.h>\n\nusing Fast_weighted_periodic_alpha_complex_3d =\n    Gudhi::alpha_complex::Alpha_complex_3d<Gudhi::alpha_complex::complexity::FAST, true, true>;\nusing Safe_weighted_periodic_alpha_complex_3d =\n    Gudhi::alpha_complex::Alpha_complex_3d<Gudhi::alpha_complex::complexity::SAFE, true, true>;\nusing Exact_weighted_periodic_alpha_complex_3d =\n    Gudhi::alpha_complex::Alpha_complex_3d<Gudhi::alpha_complex::complexity::EXACT, true, true>;\n\n\ntypedef boost::mpl::list<Fast_weighted_periodic_alpha_complex_3d, Exact_weighted_periodic_alpha_complex_3d,\n                         Safe_weighted_periodic_alpha_complex_3d>\n    wp_variants_type_list;\n\n#ifdef GUDHI_DEBUG\nBOOST_AUTO_TEST_CASE_TEMPLATE(Alpha_complex_weighted_periodic_throw, Weighted_periodic_alpha_complex_3d,\n                              wp_variants_type_list) {\n  std::clog << \"Weighted periodic alpha complex 3d exception throw\" << std::endl;\n\n  using Creator = CGAL::Creator_uniform_3<double, typename Weighted_periodic_alpha_complex_3d::Bare_point_3>;\n  CGAL::Random random(7);\n  CGAL::Random_points_in_cube_3<typename Weighted_periodic_alpha_complex_3d::Bare_point_3, Creator> in_cube(1, random);\n  std::vector<typename Weighted_periodic_alpha_complex_3d::Bare_point_3> wp_points;\n\n  for (int i = 0; i < 50; i++) {\n    typename Weighted_periodic_alpha_complex_3d::Bare_point_3 p = *in_cube++;\n    wp_points.push_back(p);\n  }\n  std::vector<double> p_weights;\n  // Weights must be in range ]0, 1/64 = 0.015625[\n  for (std::size_t i = 0; i < wp_points.size(); ++i) {\n    p_weights.push_back(random.get_double(0., 0.01));\n  }\n\n  std::clog << \"Cuboid is not iso exception\" << std::endl;\n  // Check it throws an exception when the cuboid is not iso\n  BOOST_CHECK_THROW(\n      Weighted_periodic_alpha_complex_3d wp_alpha_complex(wp_points, p_weights, -1., -1., -1., 0.9, 1., 1.),\n      std::invalid_argument);\n  BOOST_CHECK_THROW(\n      Weighted_periodic_alpha_complex_3d wp_alpha_complex(wp_points, p_weights, -1., -1., -1., 1., 0.9, 1.),\n      std::invalid_argument);\n  BOOST_CHECK_THROW(\n      Weighted_periodic_alpha_complex_3d wp_alpha_complex(wp_points, p_weights, -1., -1., -1., 1., 1., 0.9),\n      std::invalid_argument);\n  BOOST_CHECK_THROW(\n      Weighted_periodic_alpha_complex_3d wp_alpha_complex(wp_points, p_weights, -1., -1., -1., 1.1, 1., 1.),\n      std::invalid_argument);\n  BOOST_CHECK_THROW(\n      Weighted_periodic_alpha_complex_3d wp_alpha_complex(wp_points, p_weights, -1., -1., -1., 1., 1.1, 1.),\n      std::invalid_argument);\n  BOOST_CHECK_THROW(\n      Weighted_periodic_alpha_complex_3d wp_alpha_complex(wp_points, p_weights, -1., -1., -1., 1., 1., 1.1),\n      std::invalid_argument);\n\n  std::clog << \"0 <= point.weight() < 1/64 * domain_size * domain_size exception\" << std::endl;\n  // Weights must be in range ]0, 1/64 = 0.015625[\n  double temp = p_weights[25];\n  p_weights[25] = 1.0;\n  BOOST_CHECK_THROW(Weighted_periodic_alpha_complex_3d wp_alpha_complex(wp_points, p_weights, 0., 0., 0., 1., 1., 1.),\n                    std::invalid_argument);\n  // Weights must be in range ]0, 1/64 = 0.015625[\n  p_weights[25] = temp;\n  temp = p_weights[14];\n  p_weights[14] = -1e-10;\n  BOOST_CHECK_THROW(Weighted_periodic_alpha_complex_3d wp_alpha_complex(wp_points, p_weights, 0., 0., 0., 1., 1., 1.),\n                    std::invalid_argument);\n  p_weights[14] = temp;\n\n  std::clog << \"wp_points and p_weights size exception\" << std::endl;\n  // Weights and points must have the same size\n  // + 1\n  p_weights.push_back(1e-10);\n  BOOST_CHECK_THROW(Weighted_periodic_alpha_complex_3d wp_alpha_complex(wp_points, p_weights, 0., 0., 0., 1., 1., 1.),\n                    std::invalid_argument);\n  // - 1\n  p_weights.pop_back();\n  p_weights.pop_back();\n  BOOST_CHECK_THROW(Weighted_periodic_alpha_complex_3d wp_alpha_complex(wp_points, p_weights, 0., 0., 0., 1., 1., 1.),\n                    std::invalid_argument);\n}\n#endif\n\nBOOST_AUTO_TEST_CASE(Alpha_complex_weighted_periodic) {\n  // ---------------------\n  // Fast weighted periodic version\n  // ---------------------\n  std::clog << \"Fast weighted periodic alpha complex 3d\" << std::endl;\n\n  using Creator = CGAL::Creator_uniform_3<double, Fast_weighted_periodic_alpha_complex_3d::Bare_point_3>;\n  CGAL::Random random(7);\n  CGAL::Random_points_in_cube_3<Fast_weighted_periodic_alpha_complex_3d::Bare_point_3, Creator> in_cube(1, random);\n  std::vector<Fast_weighted_periodic_alpha_complex_3d::Bare_point_3> p_points;\n\n  for (int i = 0; i < 50; i++) {\n    Fast_weighted_periodic_alpha_complex_3d::Bare_point_3 p = *in_cube++;\n    p_points.push_back(p);\n  }\n  std::vector<double> p_weights;\n  // Weights must be in range ]0, 1/64 = 0.015625[\n  for (std::size_t i = 0; i < p_points.size(); ++i) {\n    p_weights.push_back(random.get_double(0., 0.01));\n  }\n\n  Fast_weighted_periodic_alpha_complex_3d periodic_alpha_complex(p_points, p_weights, -1., -1., -1., 1., 1., 1.);\n\n  Gudhi::Simplex_tree<> stree;\n  periodic_alpha_complex.create_complex(stree);\n\n  // ----------------------\n  // Exact weighted periodic version\n  // ----------------------\n  std::clog << \"Exact weighted periodic alpha complex 3d\" << std::endl;\n\n  std::vector<Exact_weighted_periodic_alpha_complex_3d::Bare_point_3> e_p_points;\n\n  for (auto p : p_points) {\n    e_p_points.push_back(Exact_weighted_periodic_alpha_complex_3d::Bare_point_3(p[0], p[1], p[2]));\n  }\n\n  Exact_weighted_periodic_alpha_complex_3d exact_alpha_complex(e_p_points, p_weights, -1., -1., -1., 1., 1., 1.);\n\n  Gudhi::Simplex_tree<> exact_stree;\n  exact_alpha_complex.create_complex(exact_stree);\n\n  // ---------------------\n  // Compare both versions\n  // ---------------------\n  std::clog << \"Exact weighted periodic alpha complex 3d is of dimension \" << exact_stree.dimension()\n            << \" - Non exact is \" << stree.dimension() << std::endl;\n  BOOST_CHECK(exact_stree.dimension() == stree.dimension());\n  std::clog << \"Exact weighted periodic alpha complex 3d num_simplices \" << exact_stree.num_simplices()\n            << \" - Non exact is \" << stree.num_simplices() << std::endl;\n  BOOST_CHECK(exact_stree.num_simplices() == stree.num_simplices());\n  std::clog << \"Exact weighted periodic alpha complex 3d num_vertices \" << exact_stree.num_vertices()\n            << \" - Non exact is \" << stree.num_vertices() << std::endl;\n  BOOST_CHECK(exact_stree.num_vertices() == stree.num_vertices());\n\n  // We cannot compare as objects from dispatcher on the alpha shape is not deterministic.\n  // cf. https://github.com/CGAL/cgal/issues/3346\n  auto sh = stree.filtration_simplex_range().begin();\n  auto sh_exact = exact_stree.filtration_simplex_range().begin();\n\n  while (sh != stree.filtration_simplex_range().end() || sh_exact != exact_stree.filtration_simplex_range().end()) {\n    GUDHI_TEST_FLOAT_EQUALITY_CHECK(stree.filtration(*sh), exact_stree.filtration(*sh_exact), 1e-14);\n\n    std::vector<int> vh(stree.simplex_vertex_range(*sh).begin(), stree.simplex_vertex_range(*sh).end());\n    std::vector<int> exact_vh(exact_stree.simplex_vertex_range(*sh_exact).begin(),\n                              exact_stree.simplex_vertex_range(*sh_exact).end());\n\n    BOOST_CHECK(vh.size() == exact_vh.size());\n    ++sh;\n    ++sh_exact;\n  }\n\n  BOOST_CHECK(sh == stree.filtration_simplex_range().end());\n  BOOST_CHECK(sh_exact == exact_stree.filtration_simplex_range().end());\n\n  // ----------------------\n  // Safe weighted periodic version\n  // ----------------------\n  std::clog << \"Safe weighted periodic alpha complex 3d\" << std::endl;\n\n  std::vector<Safe_weighted_periodic_alpha_complex_3d::Bare_point_3> s_p_points;\n\n  for (auto p : p_points) {\n    s_p_points.push_back(Safe_weighted_periodic_alpha_complex_3d::Bare_point_3(p[0], p[1], p[2]));\n  }\n\n  Safe_weighted_periodic_alpha_complex_3d safe_alpha_complex(s_p_points, p_weights, -1., -1., -1., 1., 1., 1.);\n\n  Gudhi::Simplex_tree<> safe_stree;\n  safe_alpha_complex.create_complex(safe_stree);\n\n  // ---------------------\n  // Compare both versions\n  // ---------------------\n  // We cannot compare as objects from dispatcher on the alpha shape is not deterministic.\n  // cf. https://github.com/CGAL/cgal/issues/3346\n  sh = stree.filtration_simplex_range().begin();\n  auto sh_safe = safe_stree.filtration_simplex_range().begin();\n\n  while (sh != stree.filtration_simplex_range().end() || sh_safe != safe_stree.filtration_simplex_range().end()) {\n    GUDHI_TEST_FLOAT_EQUALITY_CHECK(stree.filtration(*sh), safe_stree.filtration(*sh_safe), 1e-14);\n\n    std::vector<int> vh(stree.simplex_vertex_range(*sh).begin(), stree.simplex_vertex_range(*sh).end());\n    std::vector<int> safe_vh(safe_stree.simplex_vertex_range(*sh_safe).begin(),\n                             safe_stree.simplex_vertex_range(*sh_safe).end());\n\n    BOOST_CHECK(vh.size() == safe_vh.size());\n    ++sh;\n    ++sh_safe;\n  }\n\n  BOOST_CHECK(sh == stree.filtration_simplex_range().end());\n  BOOST_CHECK(sh_safe == safe_stree.filtration_simplex_range().end());\n}\n", "meta": {"hexsha": "610b9f3d5790d7d8a2bf089c6ddd113e8ad52ed0", "size": 9877, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Alpha_complex/test/Weighted_periodic_alpha_complex_3d_unit_test.cpp", "max_stars_repo_name": "m0baxter/gudhi-devel", "max_stars_repo_head_hexsha": "6e14ef1f31e09f3875316440303450ff870d9881", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 146.0, "max_stars_repo_stars_event_min_datetime": "2019-03-15T14:10:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T21:14:52.000Z", "max_issues_repo_path": "src/Alpha_complex/test/Weighted_periodic_alpha_complex_3d_unit_test.cpp", "max_issues_repo_name": "m0baxter/gudhi-devel", "max_issues_repo_head_hexsha": "6e14ef1f31e09f3875316440303450ff870d9881", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 398.0, "max_issues_repo_issues_event_min_datetime": "2019-03-07T14:55:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T14:50:40.000Z", "max_forks_repo_path": "src/Alpha_complex/test/Weighted_periodic_alpha_complex_3d_unit_test.cpp", "max_forks_repo_name": "m0baxter/gudhi-devel", "max_forks_repo_head_hexsha": "6e14ef1f31e09f3875316440303450ff870d9881", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 51.0, "max_forks_repo_forks_event_min_datetime": "2019-03-08T15:58:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T10:23:23.000Z", "avg_line_length": 43.3201754386, "max_line_length": 119, "alphanum_fraction": 0.6951503493, "num_tokens": 2856, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.752012562644147, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4513491861164527}}
{"text": "#include <trajopt_utils/macros.h>\nTRAJOPT_IGNORE_WARNINGS_PUSH\n#include <Eigen/Eigenvalues>\n#include <iostream>\nTRAJOPT_IGNORE_WARNINGS_POP\n\n#include <trajopt_sco/expr_ops.hpp>\n#include <trajopt_sco/modeling.hpp>\n#include <trajopt_sco/modeling_utils.hpp>\n#include <trajopt_utils/eigen_conversions.hpp>\n\nnamespace sco\n{\nconst double DEFAULT_EPSILON = 1e-5;\n\nEigen::VectorXd getVec(const DblVec& x, const VarVector& vars)\n{\n  Eigen::VectorXd out(vars.size());\n  for (unsigned i = 0; i < vars.size(); ++i)\n    out[i] = x[static_cast<long unsigned int>(vars[i].var_rep->index)];\n  return out;\n}\n\nDblVec getDblVec(const DblVec& x, const VarVector& vars)\n{\n  DblVec out(vars.size());\n  for (unsigned i = 0; i < vars.size(); ++i)\n    out[i] = x[static_cast<long unsigned int>(vars[i].var_rep->index)];\n  return out;\n}\n\nAffExpr affFromValGrad(double y, const Eigen::VectorXd& x, const Eigen::VectorXd& dydx, const VarVector& vars)\n{\n  AffExpr aff;\n  aff.constant = y - dydx.dot(x);\n  aff.coeffs = util::toDblVec(dydx);\n  aff.vars = vars;\n  aff = cleanupAff(aff);\n  return aff;\n}\n\nCostFromFunc::CostFromFunc(ScalarOfVectorPtr f, const VarVector& vars, const std::string& name, bool full_hessian)\n  : Cost(name), f_(f), vars_(vars), full_hessian_(full_hessian), epsilon_(DEFAULT_EPSILON)\n{\n}\n\ndouble CostFromFunc::value(const DblVec& xin)\n{\n  Eigen::VectorXd x = getVec(xin, vars_);\n  return f_->call(x);\n}\n\nConvexObjectivePtr CostFromFunc::convex(const DblVec& xin, Model* model)\n{\n  Eigen::VectorXd x = getVec(xin, vars_);\n\n  ConvexObjectivePtr out(new ConvexObjective(model));\n  if (!full_hessian_)\n  {\n    double val;\n    Eigen::VectorXd grad, hess;\n    calcGradAndDiagHess(*f_, x, epsilon_, val, grad, hess);\n    hess = hess.cwiseMax(Eigen::VectorXd::Zero(hess.size()));\n    QuadExpr& quad = out->quad_;\n    quad.affexpr.constant = val - grad.dot(x) + .5 * x.dot(hess.cwiseProduct(x));\n    quad.affexpr.vars = vars_;\n    quad.affexpr.coeffs = util::toDblVec(grad - hess.cwiseProduct(x));\n    quad.vars1 = vars_;\n    quad.vars2 = vars_;\n    quad.coeffs = util::toDblVec(hess * .5);\n  }\n  else\n  {\n    double val;\n    Eigen::VectorXd grad;\n    Eigen::MatrixXd hess;\n    calcGradHess(f_, x, epsilon_, val, grad, hess);\n\n    Eigen::MatrixXd pos_hess = Eigen::MatrixXd::Zero(x.size(), x.size());\n    Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(hess);\n    Eigen::VectorXd eigvals = es.eigenvalues();\n    Eigen::MatrixXd eigvecs = es.eigenvectors();\n    for (long int i = 0, end = x.size(); i != end; ++i)\n    {  // tricky --- eigen size() is signed\n      if (eigvals(i) > 0)\n        pos_hess += eigvals(i) * eigvecs.col(i) * eigvecs.col(i).transpose();\n    }\n\n    QuadExpr& quad = out->quad_;\n    quad.affexpr.constant = val - grad.dot(x) + .5 * x.dot(pos_hess * x);\n    quad.affexpr.vars = vars_;\n    quad.affexpr.coeffs = util::toDblVec(grad - pos_hess * x);\n\n    size_t nquadterms = static_cast<size_t>((x.size() * (x.size() - 1)) / 2);\n    quad.coeffs.reserve(nquadterms);\n    quad.vars1.reserve(nquadterms);\n    quad.vars2.reserve(nquadterms);\n    for (long int i = 0, end = x.size(); i != end; ++i)\n    {  // tricky --- eigen size() is signed\n      quad.vars1.push_back(vars_[static_cast<size_t>(i)]);\n      quad.vars2.push_back(vars_[static_cast<size_t>(i)]);\n      quad.coeffs.push_back(pos_hess(i, i) / 2);\n      for (long int j = i + 1; j != end; ++j)\n      {  // tricky --- eigen size() is signed\n        quad.vars1.push_back(vars_[static_cast<size_t>(i)]);\n        quad.vars2.push_back(vars_[static_cast<size_t>(j)]);\n        quad.coeffs.push_back(pos_hess(i, j));\n      }\n    }\n  }\n\n  return out;\n}\n\nCostFromErrFunc::CostFromErrFunc(VectorOfVectorPtr f, const VarVector& vars, const Eigen::VectorXd& coeffs,\n                                 PenaltyType pen_type, const std::string& name)\n  : Cost(name), f_(f), vars_(vars), coeffs_(coeffs), pen_type_(pen_type), epsilon_(DEFAULT_EPSILON)\n{\n}\nCostFromErrFunc::CostFromErrFunc(VectorOfVectorPtr f, MatrixOfVectorPtr dfdx, const VarVector& vars,\n                                 const Eigen::VectorXd& coeffs, PenaltyType pen_type, const std::string& name)\n  : Cost(name), f_(f), dfdx_(dfdx), vars_(vars), coeffs_(coeffs), pen_type_(pen_type), epsilon_(DEFAULT_EPSILON)\n{\n}\ndouble CostFromErrFunc::value(const DblVec& xin)\n{\n  Eigen::VectorXd x = getVec(xin, vars_);\n  Eigen::VectorXd err = f_->call(x);\n\n  switch (pen_type_)\n  {\n    case SQUARED:\n      err = err.array().square();\n      break;\n    case ABS:\n      err = err.array().abs();\n      break;\n    case HINGE:\n      err = err.cwiseMax(Eigen::VectorXd::Zero(err.size()));\n      break;\n    default:\n      assert(0 && \"unreachable\");\n  }\n\n  if (coeffs_.size() > 0)\n    err.array() *= coeffs_.array();\n\n  return err.array().sum();\n}\nConvexObjectivePtr CostFromErrFunc::convex(const DblVec& xin, Model* model)\n{\n  Eigen::VectorXd x = getVec(xin, vars_);\n  Eigen::MatrixXd jac = (dfdx_) ? dfdx_->call(x) : calcForwardNumJac(*f_, x, epsilon_);\n  ConvexObjectivePtr out(new ConvexObjective(model));\n  Eigen::VectorXd y = f_->call(x);\n  for (int i = 0; i < jac.rows(); ++i)\n  {\n    AffExpr aff = affFromValGrad(y[i], x, jac.row(i), vars_);\n    double weight = 1;\n    if (coeffs_.size() > 0)\n    {\n      if (coeffs_[i] == 0)\n        continue;\n\n      weight = coeffs_[i];\n    }\n    switch (pen_type_)\n    {\n      case SQUARED:\n      {\n        QuadExpr quad = exprSquare(aff);\n        exprScale(quad, weight);\n        out->addQuadExpr(quad);\n        break;\n      }\n      case ABS:\n      {\n        exprScale(aff, weight);\n        out->addAbs(aff, 1);\n        break;\n      }\n      case HINGE:\n      {\n        exprScale(aff, weight);\n        out->addHinge(aff, 1);\n        break;\n      }\n      default:\n        assert(0 && \"unreachable\");\n    }\n  }\n  return out;\n}\n\nConstraintFromErrFunc::ConstraintFromErrFunc(VectorOfVectorPtr f, const VarVector& vars, const Eigen::VectorXd& coeffs,\n                                             ConstraintType type, const std::string& name)\n  : Constraint(name), f_(f), vars_(vars), coeffs_(coeffs), type_(type), epsilon_(DEFAULT_EPSILON)\n{\n}\n\nConstraintFromErrFunc::ConstraintFromErrFunc(VectorOfVectorPtr f, MatrixOfVectorPtr dfdx, const VarVector& vars,\n                                             const Eigen::VectorXd& coeffs, ConstraintType type,\n                                             const std::string& name)\n  : Constraint(name), f_(f), dfdx_(dfdx), vars_(vars), coeffs_(coeffs), type_(type), epsilon_(DEFAULT_EPSILON)\n{\n}\n\nDblVec ConstraintFromErrFunc::value(const DblVec& xin)\n{\n  Eigen::VectorXd x = getVec(xin, vars_);\n  Eigen::VectorXd err = f_->call(x);\n  if (coeffs_.size() > 0)\n    err.array() *= coeffs_.array();\n  return util::toDblVec(err);\n}\n\nConvexConstraintsPtr ConstraintFromErrFunc::convex(const DblVec& xin, Model* model)\n{\n  Eigen::VectorXd x = getVec(xin, vars_);\n  Eigen::MatrixXd jac = (dfdx_) ? dfdx_->call(x) : calcForwardNumJac(*f_, x, epsilon_);\n  ConvexConstraintsPtr out(new ConvexConstraints(model));\n  Eigen::VectorXd y = f_->call(x);\n  for (int i = 0; i < jac.rows(); ++i)\n  {\n    AffExpr aff = affFromValGrad(y[i], x, jac.row(i), vars_);\n    if (coeffs_.size() > 0)\n    {\n      if (coeffs_[i] == 0)\n        continue;\n      exprScale(aff, coeffs_[i]);\n    }\n    if (type() == INEQ)\n      out->addIneqCnt(aff);\n    else\n      out->addEqCnt(aff);\n  }\n  return out;\n}\n\nstd::string AffExprToString(const AffExpr& aff)\n{\n  std::string out;\n  for (size_t i = 0; i < aff.vars.size(); i++)\n  {\n    if (i != 0)\n      out.append(\" + \");\n    std::string term = std::to_string(aff.coeffs[i]) + \"*\" + aff.vars[i].var_rep->name;\n    out.append(term);\n  }\n  out.append(\" + \" + std::to_string(aff.constant));\n  return out;\n}\n}\n", "meta": {"hexsha": "760677f0d39d3287ae549db092c598afeee761e3", "size": 7692, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "moveit_planners/trajopt/trajopt_sco/src/modeling_utils.cpp", "max_stars_repo_name": "adam-vonderviszt/moveit", "max_stars_repo_head_hexsha": "b18b8c66963907aa6d03cbee4450fc3d6e740162", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "moveit_planners/trajopt/trajopt_sco/src/modeling_utils.cpp", "max_issues_repo_name": "adam-vonderviszt/moveit", "max_issues_repo_head_hexsha": "b18b8c66963907aa6d03cbee4450fc3d6e740162", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "moveit_planners/trajopt/trajopt_sco/src/modeling_utils.cpp", "max_forks_repo_name": "adam-vonderviszt/moveit", "max_forks_repo_head_hexsha": "b18b8c66963907aa6d03cbee4450fc3d6e740162", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2834645669, "max_line_length": 119, "alphanum_fraction": 0.6289651586, "num_tokens": 2244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.752012562644147, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4513491861164527}}
{"text": "#include <iostream>\n#include <vector>\n#include <cstdlib>\n#include <algorithm>\n\n#include <boost/test/unit_test.hpp>\n\nextern \"C\"\n{\n#include <ccfec/ff.h>\n#include <ccfec/encoder.h>\n#include <ccfec/decoder.h>\n}\n\nBOOST_AUTO_TEST_SUITE(reedsolomonfec)\n\nBOOST_AUTO_TEST_CASE(ff_init_free)\n{\n    init_ff(); // Initialize the finite field arithmetic\n    free_ff();\n}\n\nBOOST_AUTO_TEST_CASE(ff_tables)\n{\n    if (not full_multiplication_table())\n    {\n        return;\n    }\n\n    init_ff();\n\n    const uint8_t * const invert = get_gf2_8_inversion_table();\n\n    for (int a = 0; a < 256; ++a)\n    {\n        const uint8_t * const multiply_a = get_gf2_8_multiplication_table() + (a << 8);\n        BOOST_CHECK_EQUAL(a, multiply_a[1]);\n        BOOST_CHECK_EQUAL(0, multiply_a[0]);\n\n        for (int b = 1; b < 256; ++b)\n        {\n            uint8_t product = multiply_a[b];\n            const uint8_t * const multiply_product = get_gf2_8_multiplication_table() + (product << 8);\n\n            BOOST_CHECK_EQUAL(a, multiply_product[invert[b]]);\n        }\n    }\n\n    free_ff();\n}\n\nBOOST_AUTO_TEST_CASE(encoder_init_free)\n{\n    const int k = 8;\n    const int n = 16;\n    const int symbol_size = 1280;\n    encoder_t e;\n\n    init_encoder(&e, k, symbol_size, n);\n    free_encoder(&e);\n}\n\nBOOST_AUTO_TEST_CASE(encoder_init_coef_free)\n{\n    const int k = 8;\n    const int n = 16;\n    const int symbol_size = 1280;\n    encoder_t e;\n\n    init_ff();\n\n    init_encoder(&e, k, symbol_size, n);\n    init_rs_coef(&e);\n    free_encoder(&e);\n\n    free_ff();\n}\n\nBOOST_AUTO_TEST_CASE(encoder_init_systematic_coef_free)\n{\n    const int k = 8;\n    const int n = 16;\n    const int symbol_size = 1280;\n    encoder_t e;\n\n    init_ff();\n\n    init_encoder(&e, k, symbol_size, n);\n    init_systematic_rs_coef(&e);\n    free_encoder(&e);\n\n    free_ff();\n}\n\nBOOST_AUTO_TEST_CASE(decoder_init_free)\n{\n    const int k = 8;\n    const int symbol_size = 1280;\n    decoder_t d;\n\n    init_decoder(&d, k, symbol_size);\n    free_decoder(&d);\n}\n\nvoid test_reed_solomon(const int k, const int symbol_size, const bool systematic, const bool lossy)\n{\n    const int n = 2 * k;\n    const int N = 2;\n\n    std::vector<uint8_t> payload(payload_size(k, symbol_size));\n\n    encoder_t e;\n    decoder_t d;\n    init_encoder(&e, k, symbol_size, n);\n    if (systematic)\n    {\n        init_systematic_rs_coef(&e);\n    }\n    else\n    {\n        init_rs_coef(&e);\n    }\n    init_decoder(&d, k, symbol_size);\n\n    std::vector<uint8_t> data(symbol_size * k);\n\n    for (int i = 0; i < k; ++i)\n    {\n        std::fill_n(data.begin() + i * symbol_size, symbol_size, i + 0xf);\n    }\n\n    for (int u = 0; u < N; ++u)\n    {\n        for (int i = 0; i < k; ++i)\n        {\n            set_symbol(&e, data.data() + i * symbol_size, i);\n        }\n\n        for (int i = 0; i < n; ++i)\n        {\n            encode(&e, payload.data());\n\n            if (lossy and (i & 1))\n            {\n                continue;\n            }\n\n            decode(&d, payload.data());\n        }\n\n        for (int i = 0; i < k; ++i)\n        {\n            const uint8_t * const original_symbol = data.data() + i * symbol_size;\n            const uint8_t * const decoded_symbol = get_symbol(&d, i);\n            BOOST_CHECK_EQUAL_COLLECTIONS(original_symbol, original_symbol + symbol_size, decoded_symbol, decoded_symbol + symbol_size);\n        }\n\n        reset_encoder(&e);\n        reset_decoder(&d);\n    }\n    free_encoder(&e);\n    free_decoder(&d);\n}\n\nBOOST_AUTO_TEST_CASE(encoder_decoder_full)\n{\n    init_ff();\n\n    for (int k = 1; k < 16; ++k)\n    {\n        for (int symbol_size = 1; symbol_size < 1600; symbol_size += k)\n        {\n            test_reed_solomon(k, symbol_size, false, false);\n            test_reed_solomon(k, symbol_size, true, false);\n        }\n    }\n\n    for (int k = 1; k < 16; k += 2)\n    {\n        test_reed_solomon(k, 101, true, true);\n    }\n\n    free_ff();\n}\n\nBOOST_AUTO_TEST_CASE(simd_check)\n{\n    int simd = SIMD_size();\n    if (simd)\n    {\n        std::cout << \"ccfec SIMD enabled! SIMD size is: \" << simd << '\\n';\n    }\n    else\n    {\n        std::cout << \"ccfec SIMD disabled!\\n\";\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END() // reedsolomonfec\n", "meta": {"hexsha": "c9c67af42925e230265a10de54fc2edf15c54e75", "size": 4153, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/ReedSolomonFecTest.cpp", "max_stars_repo_name": "hrjonashansen/ccfec", "max_stars_repo_head_hexsha": "13392e7bb091e08cd45570271d0336dabbba2f45", "max_stars_repo_licenses": ["MIT"], "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/ReedSolomonFecTest.cpp", "max_issues_repo_name": "hrjonashansen/ccfec", "max_issues_repo_head_hexsha": "13392e7bb091e08cd45570271d0336dabbba2f45", "max_issues_repo_licenses": ["MIT"], "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/ReedSolomonFecTest.cpp", "max_forks_repo_name": "hrjonashansen/ccfec", "max_forks_repo_head_hexsha": "13392e7bb091e08cd45570271d0336dabbba2f45", "max_forks_repo_licenses": ["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.765, "max_line_length": 136, "alphanum_fraction": 0.5788586564, "num_tokens": 1163, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.752012562644147, "lm_q2_score": 0.6001883592602049, "lm_q1q2_score": 0.4513491861164526}}
{"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 \"Ehlers.h\"\n\n#include <boost/math/special_functions/pow.hpp>\n\n#include \"LinearElasticIsotropic.h\"\n#include \"MaterialLib/MPL/Utils/GetSymmetricTensor.h\"\n#include \"MathLib/LinAlg/Eigen/EigenMapTools.h\"\n\nnamespace MPL = MaterialPropertyLib;\n\n/**\n * Common convenitions for naming:\n * x_D              - deviatoric part of tensor x\n * x_V              - volumetric part of tensor x\n * x_p              - a variable related to plastic potential\n * x_prev           - value of x in previous time step\n *\n * Variables used in the code:\n * eps_D            - deviatoric strain\n * eps_p_D_dot      - deviatoric increment of plastic strain\n * eps_p_eff_dot    - increment of effective plastic strain\n * eps_p_V_dot      - volumetric increment of plastic strain\n * sigma_D_inverse_D - deviatoric part of sigma_D_inverse\n *\n * derivation of the flow rule\n * theta            - J3 / J2^(3 / 2) from yield function\n * dtheta_dsigma    - derivative of theta\n * sqrtPhi          - square root of Phi from plastic potential\n * flow_D           - deviatoric part of flow\n * flow_V           - volumetric part of flow\n * lambda_flow_D    - deviatoric increment of plastic strain\n */\n\nnamespace MaterialLib\n{\nnamespace Solids\n{\nnamespace Ehlers\n{\ntemplate <int DisplacementDim>\ndouble StateVariables<DisplacementDim>::getEquivalentPlasticStrain() const\n{\n    return std::sqrt(2.0 / 3.0 * Invariants::FrobeniusNorm(eps_p.D.eval()));\n}\n\n/// Special product of \\c v with itself: \\f$v \\odot v\\f$.\n/// The tensor \\c v is given in Kelvin mapping.\n/// \\note Implementation only for 2 and 3 dimensions.\n/// \\attention Pay attention to the sign of the result, which normally would be\n/// negative, but the returned value is not negated. This has to do with \\f$\n/// d(A^{-1})/dA = -A^{-1} \\odot A^{-1} \\f$.\ntemplate <int DisplacementDim>\nMathLib::KelvinVector::KelvinMatrixType<DisplacementDim> sOdotS(\n    MathLib::KelvinVector::KelvinVectorType<DisplacementDim> const& v);\n\ntemplate <int DisplacementDim>\nstruct PhysicalStressWithInvariants final\n{\n    static int const KelvinVectorSize =\n        MathLib::KelvinVector::kelvin_vector_dimensions(DisplacementDim);\n    using Invariants = MathLib::KelvinVector::Invariants<KelvinVectorSize>;\n    using KelvinVector =\n        MathLib::KelvinVector::KelvinVectorType<DisplacementDim>;\n\n    explicit PhysicalStressWithInvariants(KelvinVector const& stress)\n        : value{stress},\n          D{Invariants::deviatoric_projection * stress},\n          I_1{Invariants::trace(stress)},\n          J_2{Invariants::J2(D)},\n          J_3{Invariants::J3(D)}\n    {\n    }\n\n    KelvinVector value;\n    KelvinVector D;\n    double I_1;\n    double J_2;\n    double J_3;\n\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n};\n\n/// Holds powers of 1 + gamma_p*theta to base 0, m_p, and m_p-1.\nstruct OnePlusGamma_pTheta final\n{\n    OnePlusGamma_pTheta(double const gamma_p, double const theta,\n                        double const m_p)\n        : value{1 + gamma_p * theta},\n          pow_m_p{std::pow(value, m_p)},\n          pow_m_p1{pow_m_p / value}\n    {\n    }\n\n    double const value;\n    double const pow_m_p;\n    double const pow_m_p1;\n};\n\ntemplate <int DisplacementDim>\ndouble plasticFlowVolumetricPart(\n    PhysicalStressWithInvariants<DisplacementDim> const& s,\n    double const sqrtPhi, double const alpha_p, double const beta_p,\n    double const delta_p, double const epsilon_p)\n{\n    return 3 *\n               (alpha_p * s.I_1 +\n                4 * boost::math::pow<2>(delta_p) * boost::math::pow<3>(s.I_1)) /\n               (2 * sqrtPhi) +\n           3 * beta_p + 6 * epsilon_p * s.I_1;\n}\n\ntemplate <int DisplacementDim>\ntypename SolidEhlers<DisplacementDim>::KelvinVector plasticFlowDeviatoricPart(\n    PhysicalStressWithInvariants<DisplacementDim> const& s,\n    OnePlusGamma_pTheta const& one_gt, double const sqrtPhi,\n    typename SolidEhlers<DisplacementDim>::KelvinVector const& dtheta_dsigma,\n    double const gamma_p, double const m_p)\n{\n    return (one_gt.pow_m_p *\n            (s.D + s.J_2 * m_p * gamma_p * dtheta_dsigma / one_gt.value)) /\n           (2 * sqrtPhi);\n}\n\ntemplate <int DisplacementDim>\ndouble yieldFunction(MaterialProperties const& mp,\n                     PhysicalStressWithInvariants<DisplacementDim> const& s,\n                     double const k)\n{\n    double const I_1_squared = boost::math::pow<2>(s.I_1);\n    assert(s.J_2 != 0);\n\n    return std::sqrt(s.J_2 * std::pow(1 + mp.gamma * s.J_3 /\n                                              (s.J_2 * std::sqrt(s.J_2)),\n                                      mp.m) +\n                     mp.alpha / 2. * I_1_squared +\n                     boost::math::pow<2>(mp.delta) *\n                         boost::math::pow<2>(I_1_squared)) +\n           mp.beta * s.I_1 + mp.epsilon * I_1_squared - k;\n}\n\ntemplate <int DisplacementDim>\ntypename SolidEhlers<DisplacementDim>::ResidualVectorType\ncalculatePlasticResidual(\n    MathLib::KelvinVector::KelvinVectorType<DisplacementDim> const& eps_D,\n    double const eps_V,\n    PhysicalStressWithInvariants<DisplacementDim> const& s,\n    MathLib::KelvinVector::KelvinVectorType<DisplacementDim> const& eps_p_D,\n    MathLib::KelvinVector::KelvinVectorType<DisplacementDim> const& eps_p_D_dot,\n    double const eps_p_V,\n    double const eps_p_V_dot,\n    double const eps_p_eff_dot,\n    double const lambda,\n    double const k,\n    MaterialProperties const& mp)\n{\n    static int const KelvinVectorSize =\n        MathLib::KelvinVector::kelvin_vector_dimensions(DisplacementDim);\n    using Invariants = MathLib::KelvinVector::Invariants<KelvinVectorSize>;\n    using KelvinVector =\n        MathLib::KelvinVector::KelvinVectorType<DisplacementDim>;\n\n    auto const& P_dev = Invariants::deviatoric_projection;\n    auto const& identity2 = Invariants::identity2;\n\n    double const theta = s.J_3 / (s.J_2 * std::sqrt(s.J_2));\n\n    typename SolidEhlers<DisplacementDim>::ResidualVectorType residual;\n    // calculate stress residual\n    residual.template segment<KelvinVectorSize>(0).noalias() =\n        s.value / mp.G - 2 * (eps_D - eps_p_D) -\n        mp.K / mp.G * (eps_V - eps_p_V) * identity2;\n\n    // deviatoric plastic strain\n    KelvinVector const sigma_D_inverse_D =\n        P_dev * MathLib::KelvinVector::inverse(s.D);\n    KelvinVector const dtheta_dsigma =\n        theta * sigma_D_inverse_D - 3. / 2. * theta / s.J_2 * s.D;\n\n    OnePlusGamma_pTheta const one_gt{mp.gamma_p, theta, mp.m_p};\n    double const sqrtPhi = std::sqrt(\n        s.J_2 * one_gt.pow_m_p + mp.alpha_p / 2. * boost::math::pow<2>(s.I_1) +\n        boost::math::pow<2>(mp.delta_p) * boost::math::pow<4>(s.I_1));\n    KelvinVector const flow_D = plasticFlowDeviatoricPart(\n        s, one_gt, sqrtPhi, dtheta_dsigma, mp.gamma_p, mp.m_p);\n    KelvinVector const lambda_flow_D = lambda * flow_D;\n\n    residual.template segment<KelvinVectorSize>(KelvinVectorSize).noalias() =\n        eps_p_D_dot - lambda_flow_D;\n\n    // plastic volume strain\n    {\n        double const flow_V = plasticFlowVolumetricPart<DisplacementDim>(\n            s, sqrtPhi, mp.alpha_p, mp.beta_p, mp.delta_p, mp.epsilon_p);\n        residual(2 * KelvinVectorSize, 0) = eps_p_V_dot - lambda * flow_V;\n    }\n\n    // evolution of plastic equivalent strain\n    residual(2 * KelvinVectorSize + 1) =\n        eps_p_eff_dot -\n        std::sqrt(2. / 3. * lambda_flow_D.transpose() * lambda_flow_D);\n\n    // yield function (for plastic multiplier)\n    residual(2 * KelvinVectorSize + 2) = yieldFunction(mp, s, k) / mp.G;\n    return residual;\n}\n\ntemplate <int DisplacementDim>\ntypename SolidEhlers<DisplacementDim>::JacobianMatrix calculatePlasticJacobian(\n    double const dt,\n    PhysicalStressWithInvariants<DisplacementDim> const& s,\n    double const lambda,\n    MaterialProperties const& mp)\n{\n    static int const KelvinVectorSize =\n        MathLib::KelvinVector::kelvin_vector_dimensions(DisplacementDim);\n    using Invariants = MathLib::KelvinVector::Invariants<KelvinVectorSize>;\n    using KelvinVector =\n        MathLib::KelvinVector::KelvinVectorType<DisplacementDim>;\n    using KelvinMatrix =\n        MathLib::KelvinVector::KelvinMatrixType<DisplacementDim>;\n\n    auto const& P_dev = Invariants::deviatoric_projection;\n    auto const& identity2 = Invariants::identity2;\n\n    double const theta = s.J_3 / (s.J_2 * std::sqrt(s.J_2));\n    OnePlusGamma_pTheta const one_gt{mp.gamma_p, theta, mp.m_p};\n\n    // inverse of deviatoric stress tensor\n    if (Invariants::determinant(s.D) == 0)\n    {\n        OGS_FATAL(\"Determinant is zero. Matrix is non-invertable.\");\n    }\n    // inverse of sigma_D\n    KelvinVector const sigma_D_inverse = MathLib::KelvinVector::inverse(s.D);\n    KelvinVector const sigma_D_inverse_D = P_dev * sigma_D_inverse;\n\n    KelvinVector const dtheta_dsigma =\n        theta * sigma_D_inverse_D - 3. / 2. * theta / s.J_2 * s.D;\n\n    // deviatoric flow\n    double const sqrtPhi = std::sqrt(\n        s.J_2 * one_gt.pow_m_p + mp.alpha_p / 2. * boost::math::pow<2>(s.I_1) +\n        boost::math::pow<2>(mp.delta_p) * boost::math::pow<4>(s.I_1));\n    KelvinVector const flow_D = plasticFlowDeviatoricPart(\n        s, one_gt, sqrtPhi, dtheta_dsigma, mp.gamma_p, mp.m_p);\n    KelvinVector const lambda_flow_D = lambda * flow_D;\n\n    typename SolidEhlers<DisplacementDim>::JacobianMatrix jacobian =\n        SolidEhlers<DisplacementDim>::JacobianMatrix::Zero();\n\n    // G_11\n    jacobian.template block<KelvinVectorSize, KelvinVectorSize>(0, 0)\n        .noalias() = KelvinMatrix::Identity();\n\n    // G_12\n    jacobian\n        .template block<KelvinVectorSize, KelvinVectorSize>(0, KelvinVectorSize)\n        .noalias() = 2 * KelvinMatrix::Identity();\n\n    // G_13\n    jacobian.template block<KelvinVectorSize, 1>(0, 2 * KelvinVectorSize)\n        .noalias() = mp.K / mp.G * identity2;\n\n    // G_14 and G_15 are zero\n\n    // G_21 -- derivative of deviatoric flow\n\n    double const gm_p = mp.gamma_p * mp.m_p;\n    // intermediate variable for derivative of deviatoric flow\n    KelvinVector const M0 = s.J_2 / one_gt.value * dtheta_dsigma;\n    // derivative of Phi w.r.t. sigma\n    KelvinVector const dPhi_dsigma =\n        one_gt.pow_m_p * (s.D + gm_p * M0) +\n        (mp.alpha_p * s.I_1 +\n         4 * boost::math::pow<2>(mp.delta_p) * boost::math::pow<3>(s.I_1)) *\n            identity2;\n\n    // intermediate variable for derivative of deviatoric flow\n    KelvinMatrix const M1 =\n        one_gt.pow_m_p *\n        (s.D * dPhi_dsigma.transpose() + gm_p * M0 * dPhi_dsigma.transpose());\n    // intermediate variable for derivative of deviatoric flow\n    KelvinMatrix const M2 =\n        one_gt.pow_m_p * (P_dev + s.D * gm_p * M0.transpose());\n    // second derivative of theta\n    KelvinMatrix const d2theta_dsigma2 =\n        theta * P_dev * sOdotS<DisplacementDim>(sigma_D_inverse) * P_dev +\n        sigma_D_inverse_D * dtheta_dsigma.transpose() -\n        3. / 2. * theta / s.J_2 * P_dev -\n        3. / 2. * dtheta_dsigma / s.J_2 * s.D.transpose() +\n        3. / 2. * theta / boost::math::pow<2>(s.J_2) * s.D * s.D.transpose();\n\n    // intermediate variable for derivative of deviatoric flow\n    KelvinMatrix const M3 =\n        gm_p * one_gt.pow_m_p1 *\n        ((s.D + (gm_p - mp.gamma_p) * M0) * dtheta_dsigma.transpose() +\n         s.J_2 * d2theta_dsigma2);\n\n    // derivative of flow_D w.r.t. sigma\n    KelvinMatrix const dflow_D_dsigma =\n        (-M1 / (4 * boost::math::pow<3>(sqrtPhi)) + (M2 + M3) / (2 * sqrtPhi)) *\n        mp.G;\n    jacobian\n        .template block<KelvinVectorSize, KelvinVectorSize>(KelvinVectorSize, 0)\n        .noalias() = -lambda * dflow_D_dsigma;\n\n    // G_22\n    jacobian\n        .template block<KelvinVectorSize, KelvinVectorSize>(KelvinVectorSize,\n                                                            KelvinVectorSize)\n        .noalias() = KelvinMatrix::Identity() / dt;\n\n    // G_23 and G_24 are zero\n\n    // G_25\n    jacobian\n        .template block<KelvinVectorSize, 1>(KelvinVectorSize,\n                                             2 * KelvinVectorSize + 2)\n        .noalias() = -flow_D;\n\n    // G_31\n    {\n        // derivative of flow_V w.r.t. sigma\n        KelvinVector const dflow_V_dsigma =\n            3 * mp.G *\n            (-(mp.alpha_p * s.I_1 + 4 * boost::math::pow<2>(mp.delta_p) *\n                                        boost::math::pow<3>(s.I_1)) /\n                 (4 * boost::math::pow<3>(sqrtPhi)) * dPhi_dsigma +\n             (mp.alpha_p * identity2 +\n              12 * boost::math::pow<2>(mp.delta_p * s.I_1) * identity2) /\n                 (2 * sqrtPhi) +\n             2 * mp.epsilon_p * identity2);\n\n        jacobian.template block<1, KelvinVectorSize>(2 * KelvinVectorSize, 0)\n            .noalias() = -lambda * dflow_V_dsigma.transpose();\n    }\n\n    // G_32 is zero\n\n    // G_33\n    jacobian(2 * KelvinVectorSize, 2 * KelvinVectorSize) = 1. / dt;\n\n    // G_34 is zero\n\n    // G_35\n    {\n        double const flow_V = plasticFlowVolumetricPart<DisplacementDim>(\n            s, sqrtPhi, mp.alpha_p, mp.beta_p, mp.delta_p, mp.epsilon_p);\n        jacobian(2 * KelvinVectorSize, 2 * KelvinVectorSize + 2) = -flow_V;\n    }\n\n    // increment of effectiv plastic strain\n    double const eff_flow =\n        std::sqrt(2. / 3. * lambda_flow_D.transpose() * lambda_flow_D);\n\n    if (eff_flow > 0)\n    {\n        // intermediate variable for derivative of plastic jacobian\n        KelvinVector const eff_flow23_lambda_flow_D =\n            -2 / 3. / eff_flow * lambda_flow_D;\n        // G_41\n        jacobian\n            .template block<1, KelvinVectorSize>(2 * KelvinVectorSize + 1, 0)\n            .noalias() = lambda * dflow_D_dsigma * eff_flow23_lambda_flow_D;\n        // G_45\n        jacobian(2 * KelvinVectorSize + 1, 2 * KelvinVectorSize + 2) =\n            eff_flow23_lambda_flow_D.transpose() * flow_D;\n    }\n\n    // G_42 and G_43 are zero\n\n    // G_44\n    jacobian(2 * KelvinVectorSize + 1, 2 * KelvinVectorSize + 1) = 1. / dt;\n\n    // G_51\n    {\n        double const one_gt_pow_m = std::pow(one_gt.value, mp.m);\n        double const gm = mp.gamma * mp.m;\n        // derivative of yield function w.r.t. sigma\n        KelvinVector const dF_dsigma =\n            mp.G *\n                (one_gt_pow_m * (s.D + gm * M0) +\n                 (mp.alpha * s.I_1 + 4 * boost::math::pow<2>(mp.delta) *\n                                         boost::math::pow<3>(s.I_1)) *\n                     identity2) /\n                (2. * sqrtPhi) +\n            mp.G * (mp.beta + 2 * mp.epsilon_p * s.I_1) * identity2;\n\n        jacobian\n            .template block<1, KelvinVectorSize>(2 * KelvinVectorSize + 2, 0)\n            .noalias() = dF_dsigma.transpose() / mp.G;\n    }\n\n    // G_54\n    jacobian(2 * KelvinVectorSize + 2, 2 * KelvinVectorSize + 1) =\n        -mp.kappa * mp.hardening_coefficient / mp.G;\n\n    // G_52, G_53, G_55 are zero\n    return jacobian;\n}\n\n/// Calculates the derivative of the residuals with respect to total\n/// strain. Implementation fully implicit only.\ntemplate <int DisplacementDim>\nMathLib::KelvinVector::KelvinMatrixType<DisplacementDim> calculateDResidualDEps(\n    double const K, double const G)\n{\n    static int const KelvinVectorSize =\n        MathLib::KelvinVector::kelvin_vector_dimensions(DisplacementDim);\n    using Invariants = MathLib::KelvinVector::Invariants<KelvinVectorSize>;\n\n    auto const& P_dev = Invariants::deviatoric_projection;\n    auto const& P_sph = Invariants::spherical_projection;\n    auto const& I =\n        MathLib::KelvinVector::KelvinMatrixType<DisplacementDim>::Identity();\n\n    return -2. * I * P_dev - 3. * K / G * I * P_sph;\n}\n\ninline double calculateIsotropicHardening(double const kappa,\n                                          double const hardening_coefficient,\n                                          double const eps_p_eff)\n{\n    return kappa * (1. + eps_p_eff * hardening_coefficient);\n}\n\ntemplate <int DisplacementDim>\ntypename SolidEhlers<DisplacementDim>::KelvinVector predict_sigma(\n    double const G, double const K,\n    typename SolidEhlers<DisplacementDim>::KelvinVector const& sigma_prev,\n    typename SolidEhlers<DisplacementDim>::KelvinVector const& eps,\n    typename SolidEhlers<DisplacementDim>::KelvinVector const& eps_prev,\n    double const eps_V)\n{\n    static int const KelvinVectorSize =\n        MathLib::KelvinVector::kelvin_vector_dimensions(DisplacementDim);\n    using Invariants = MathLib::KelvinVector::Invariants<KelvinVectorSize>;\n    auto const& P_dev = Invariants::deviatoric_projection;\n\n    // dimensionless initial hydrostatic pressure\n    double const pressure_prev = Invariants::trace(sigma_prev) / (-3. * G);\n    // initial strain invariant\n    double const e_prev = Invariants::trace(eps_prev);\n    // dimensioness hydrostatic stress increment\n    double const pressure = pressure_prev - K / G * (eps_V - e_prev);\n    // dimensionless deviatoric initial stress\n    typename SolidEhlers<DisplacementDim>::KelvinVector const sigma_D_prev =\n        P_dev * sigma_prev / G;\n    // dimensionless deviatoric stress\n    typename SolidEhlers<DisplacementDim>::KelvinVector const sigma_D =\n        sigma_D_prev + 2 * P_dev * (eps - eps_prev);\n    return sigma_D - pressure * Invariants::identity2;\n}\n\n/// Split the agglomerated solution vector in separate items. The arrangement\n/// must be the same as in the newton() function.\ntemplate <typename ResidualVector, typename KelvinVector>\nstd::tuple<KelvinVector, PlasticStrain<KelvinVector>, double>\nsplitSolutionVector(ResidualVector const& solution)\n{\n    static auto const size = KelvinVector::SizeAtCompileTime;\n    return std::forward_as_tuple(\n        solution.template segment<size>(size * 0),\n        PlasticStrain<KelvinVector>{solution.template segment<size>(size * 1),\n                                    solution[size * 2], solution[size * 2 + 1]},\n        solution[size * 2 + 2]);\n}\n\ntemplate <int DisplacementDim>\nSolidEhlers<DisplacementDim>::SolidEhlers(\n    NumLib::NewtonRaphsonSolverParameters nonlinear_solver_parameters,\n    MaterialPropertiesParameters material_properties,\n    std::unique_ptr<DamagePropertiesParameters>&& damage_properties,\n    TangentType tangent_type)\n    : _nonlinear_solver_parameters(std::move(nonlinear_solver_parameters)),\n      _mp(std::move(material_properties)),\n      _damage_properties(std::move(damage_properties)),\n      _tangent_type(tangent_type)\n{\n}\n\ntemplate <int DisplacementDim>\ndouble SolidEhlers<DisplacementDim>::computeFreeEnergyDensity(\n    double const /*t*/,\n    ParameterLib::SpatialPosition const& /*x*/,\n    double const /*dt*/,\n    KelvinVector const& eps,\n    KelvinVector const& sigma,\n    typename MechanicsBase<DisplacementDim>::MaterialStateVariables const&\n        material_state_variables) const\n{\n    assert(dynamic_cast<StateVariables<DisplacementDim> const*>(\n               &material_state_variables) != nullptr);\n\n    auto const& eps_p = static_cast<StateVariables<DisplacementDim> const&>(\n                            material_state_variables)\n                            .eps_p;\n    using Invariants = MathLib::KelvinVector::Invariants<KelvinVectorSize>;\n    auto const& identity2 = Invariants::identity2;\n    return (eps - eps_p.D - eps_p.V / 3 * identity2).dot(sigma) / 2;\n}\n\ntemplate <int DisplacementDim>\nstd::optional<std::tuple<typename SolidEhlers<DisplacementDim>::KelvinVector,\n                         std::unique_ptr<typename MechanicsBase<\n                             DisplacementDim>::MaterialStateVariables>,\n                         typename SolidEhlers<DisplacementDim>::KelvinMatrix>>\nSolidEhlers<DisplacementDim>::integrateStress(\n    MaterialPropertyLib::VariableArray const& variable_array_prev,\n    MaterialPropertyLib::VariableArray const& variable_array, double const t,\n    ParameterLib::SpatialPosition const& x, double const dt,\n    typename MechanicsBase<DisplacementDim>::MaterialStateVariables const&\n        material_state_variables) const\n{\n    auto const& eps_m = std::get<MPL::SymmetricTensor<DisplacementDim>>(\n        variable_array[static_cast<int>(MPL::Variable::mechanical_strain)]);\n    auto const& eps_m_prev = std::get<MPL::SymmetricTensor<DisplacementDim>>(\n        variable_array_prev[static_cast<int>(\n            MPL::Variable::mechanical_strain)]);\n    auto const& sigma_prev = std::get<MPL::SymmetricTensor<DisplacementDim>>(\n        variable_array_prev[static_cast<int>(MPL::Variable::stress)]);\n\n    assert(dynamic_cast<StateVariables<DisplacementDim> const*>(\n               &material_state_variables) != nullptr);\n\n    StateVariables<DisplacementDim> state =\n        static_cast<StateVariables<DisplacementDim> const&>(\n            material_state_variables);\n    state.setInitialConditions();\n\n    using Invariants = MathLib::KelvinVector::Invariants<KelvinVectorSize>;\n\n    // volumetric strain\n    double const eps_V = Invariants::trace(eps_m);\n\n    auto const& P_dev = Invariants::deviatoric_projection;\n    // deviatoric strain\n    KelvinVector const eps_D = P_dev * eps_m;\n\n    // do the evaluation once per function call.\n    MaterialProperties const mp(t, x, _mp);\n\n    KelvinVector sigma = predict_sigma<DisplacementDim>(\n        mp.G, mp.K, sigma_prev, eps_m, eps_m_prev, eps_V);\n\n    KelvinMatrix tangentStiffness;\n\n    PhysicalStressWithInvariants<DisplacementDim> s{mp.G * sigma};\n    // Quit early if sigma is zero (nothing to do) or if we are still in elastic\n    // zone.\n    if ((sigma.squaredNorm() == 0 ||\n         yieldFunction(\n             mp, s,\n             calculateIsotropicHardening(mp.kappa, mp.hardening_coefficient,\n                                         state.eps_p.eff)) < 0))\n    {\n        tangentStiffness = elasticTangentStiffness<DisplacementDim>(\n            mp.K - 2. / 3 * mp.G, mp.G);\n    }\n    else\n    {\n        // Linear solver for the newton loop is required after the loop with the\n        // same matrix. This saves one decomposition.\n        Eigen::FullPivLU<Eigen::Matrix<double, JacobianResidualSize,\n                                       JacobianResidualSize, Eigen::RowMajor>>\n            linear_solver;\n\n        {\n            static int const KelvinVectorSize =\n                MathLib::KelvinVector::kelvin_vector_dimensions(\n                    DisplacementDim);\n            using KelvinVector =\n                MathLib::KelvinVector::KelvinVectorType<DisplacementDim>;\n            using ResidualVectorType =\n                Eigen::Matrix<double, JacobianResidualSize, 1>;\n            using JacobianMatrix =\n                Eigen::Matrix<double, JacobianResidualSize,\n                              JacobianResidualSize, Eigen::RowMajor>;\n\n            JacobianMatrix jacobian;\n\n            // Agglomerated solution vector construction.  It is later split\n            // into individual parts by splitSolutionVector().\n            ResidualVectorType solution;\n            solution << sigma, state.eps_p.D, state.eps_p.V, state.eps_p.eff, 0;\n\n            auto const update_residual = [&](ResidualVectorType& residual)\n            {\n                auto const& eps_p_D =\n                    solution.template segment<KelvinVectorSize>(\n                        KelvinVectorSize);\n                KelvinVector const eps_p_D_dot =\n                    (eps_p_D - state.eps_p_prev.D) / dt;\n\n                double const& eps_p_V = solution[KelvinVectorSize * 2];\n                double const eps_p_V_dot = (eps_p_V - state.eps_p_prev.V) / dt;\n\n                double const& eps_p_eff = solution[KelvinVectorSize * 2 + 1];\n                double const eps_p_eff_dot =\n                    (eps_p_eff - state.eps_p_prev.eff) / dt;\n\n                double const k_hardening = calculateIsotropicHardening(\n                    mp.kappa, mp.hardening_coefficient,\n                    solution[KelvinVectorSize * 2 + 1]);\n                residual = calculatePlasticResidual<DisplacementDim>(\n                    eps_D, eps_V, s,\n                    solution.template segment<KelvinVectorSize>(\n                        KelvinVectorSize),\n                    eps_p_D_dot, solution[KelvinVectorSize * 2], eps_p_V_dot,\n                    eps_p_eff_dot, solution[KelvinVectorSize * 2 + 2],\n                    k_hardening, mp);\n            };\n\n            auto const update_jacobian = [&](JacobianMatrix& jacobian)\n            {\n                jacobian = calculatePlasticJacobian<DisplacementDim>(\n                    dt, s, solution[KelvinVectorSize * 2 + 2], mp);\n            };\n\n            auto const update_solution =\n                [&](ResidualVectorType const& increment)\n            {\n                solution += increment;\n                s = PhysicalStressWithInvariants<DisplacementDim>{\n                    mp.G * solution.template segment<KelvinVectorSize>(0)};\n            };\n\n            auto newton_solver = NumLib::NewtonRaphson<\n                decltype(linear_solver), JacobianMatrix,\n                decltype(update_jacobian), ResidualVectorType,\n                decltype(update_residual), 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                return {};\n            }\n\n            // If the Newton loop didn't run, the linear solver will not be\n            // initialized.\n            // This happens usually for the first iteration of the first\n            // timestep.\n            if (*success_iterations == 0)\n            {\n                linear_solver.compute(jacobian);\n            }\n\n            std::tie(sigma, state.eps_p, std::ignore) =\n                splitSolutionVector<ResidualVectorType, KelvinVector>(solution);\n        }\n\n        // Calculate residual derivative w.r.t. strain\n        Eigen::Matrix<double, JacobianResidualSize, KelvinVectorSize,\n                      Eigen::RowMajor>\n            dresidual_deps =\n                Eigen::Matrix<double, JacobianResidualSize, KelvinVectorSize,\n                              Eigen::RowMajor>::Zero();\n        dresidual_deps.template block<KelvinVectorSize, KelvinVectorSize>(0, 0)\n            .noalias() = calculateDResidualDEps<DisplacementDim>(mp.K, mp.G);\n\n        if (_tangent_type == TangentType::Elastic)\n        {\n            tangentStiffness =\n                elasticTangentStiffness<DisplacementDim>(mp.K, mp.G);\n        }\n        else if (_tangent_type == TangentType::Plastic ||\n                 _tangent_type == TangentType::PlasticDamageSecant)\n        {\n            tangentStiffness =\n                mp.G *\n                linear_solver.solve(-dresidual_deps)\n                    .template block<KelvinVectorSize, KelvinVectorSize>(0, 0);\n            if (_tangent_type == TangentType::PlasticDamageSecant)\n            {\n                tangentStiffness *= 1 - state.damage.value();\n            }\n        }\n        else\n        {\n            OGS_FATAL(\n                \"Unimplemented tangent type behaviour for the tangent type \"\n                \"'{:d}'.\",\n                _tangent_type);\n        }\n    }\n\n    KelvinVector sigma_final = mp.G * sigma;\n\n    return {std::make_tuple(\n        sigma_final,\n        std::unique_ptr<\n            typename MechanicsBase<DisplacementDim>::MaterialStateVariables>{\n            new StateVariables<DisplacementDim>{\n                static_cast<StateVariables<DisplacementDim> const&>(state)}},\n        tangentStiffness)};\n}\n\ntemplate <int DisplacementDim>\nstd::vector<typename MechanicsBase<DisplacementDim>::InternalVariable>\nSolidEhlers<DisplacementDim>::getInternalVariables() const\n{\n    return {{\"damage.kappa_d\", 1,\n             [](typename MechanicsBase<\n                    DisplacementDim>::MaterialStateVariables const& state,\n                std::vector<double>& cache) -> std::vector<double> const&\n             {\n                 assert(dynamic_cast<StateVariables<DisplacementDim> const*>(\n                            &state) != nullptr);\n                 auto const& ehlers_state =\n                     static_cast<StateVariables<DisplacementDim> const&>(state);\n\n                 cache.resize(1);\n                 cache.front() = ehlers_state.damage.kappa_d();\n                 return cache;\n             },\n             [](typename MechanicsBase<DisplacementDim>::MaterialStateVariables&\n                    state) -> BaseLib::DynamicSpan<double>\n             {\n                 assert(dynamic_cast<StateVariables<DisplacementDim> const*>(\n                            &state) != nullptr);\n                 auto& ehlers_state =\n                     static_cast<StateVariables<DisplacementDim>&>(state);\n\n                 return {&ehlers_state.damage.kappa_d(), 1};\n             }},\n            {\"damage.value\", 1,\n             [](typename MechanicsBase<\n                    DisplacementDim>::MaterialStateVariables const& state,\n                std::vector<double>& cache) -> std::vector<double> const&\n             {\n                 assert(dynamic_cast<StateVariables<DisplacementDim> const*>(\n                            &state) != nullptr);\n                 auto const& ehlers_state =\n                     static_cast<StateVariables<DisplacementDim> const&>(state);\n\n                 cache.resize(1);\n                 cache.front() = ehlers_state.damage.value();\n                 return cache;\n             },\n             [](typename MechanicsBase<DisplacementDim>::MaterialStateVariables&\n                    state) -> BaseLib::DynamicSpan<double>\n             {\n                 assert(dynamic_cast<StateVariables<DisplacementDim> const*>(\n                            &state) != nullptr);\n                 auto& ehlers_state =\n                     static_cast<StateVariables<DisplacementDim>&>(state);\n\n                 return {&ehlers_state.damage.value(), 1};\n             }},\n            {\"eps_p.D\", KelvinVector::RowsAtCompileTime,\n             [](typename MechanicsBase<\n                    DisplacementDim>::MaterialStateVariables const& state,\n                std::vector<double>& cache) -> std::vector<double> const&\n             {\n                 assert(dynamic_cast<StateVariables<DisplacementDim> const*>(\n                            &state) != nullptr);\n                 auto const& ehlers_state =\n                     static_cast<StateVariables<DisplacementDim> const&>(state);\n\n                 cache.resize(KelvinVector::RowsAtCompileTime);\n                 MathLib::toVector<KelvinVector>(\n                     cache, KelvinVector::RowsAtCompileTime) =\n                     MathLib::KelvinVector::kelvinVectorToSymmetricTensor(\n                         ehlers_state.eps_p.D);\n\n                 return cache;\n             },\n             [](typename MechanicsBase<DisplacementDim>::MaterialStateVariables&\n                    state) -> BaseLib::DynamicSpan<double>\n             {\n                 assert(dynamic_cast<StateVariables<DisplacementDim> const*>(\n                            &state) != nullptr);\n                 auto& ehlers_state =\n                     static_cast<StateVariables<DisplacementDim>&>(state);\n\n                 return {\n                     ehlers_state.eps_p.D.data(),\n                     static_cast<std::size_t>(KelvinVector::RowsAtCompileTime)};\n             }},\n            {\"eps_p.V\", 1,\n             [](typename MechanicsBase<\n                    DisplacementDim>::MaterialStateVariables const& state,\n                std::vector<double>& cache) -> std::vector<double> const&\n             {\n                 assert(dynamic_cast<StateVariables<DisplacementDim> const*>(\n                            &state) != nullptr);\n                 auto const& ehlers_state =\n                     static_cast<StateVariables<DisplacementDim> const&>(state);\n\n                 cache.resize(1);\n                 cache.front() = ehlers_state.eps_p.V;\n                 return cache;\n             },\n             [](typename MechanicsBase<DisplacementDim>::MaterialStateVariables&\n                    state) -> BaseLib::DynamicSpan<double>\n             {\n                 assert(dynamic_cast<StateVariables<DisplacementDim> const*>(\n                            &state) != nullptr);\n                 auto& ehlers_state =\n                     static_cast<StateVariables<DisplacementDim>&>(state);\n\n                 return {&ehlers_state.eps_p.V, 1};\n             }},\n            {\"eps_p.eff\", 1,\n             [](typename MechanicsBase<\n                    DisplacementDim>::MaterialStateVariables const& state,\n                std::vector<double>& cache) -> std::vector<double> const&\n             {\n                 assert(dynamic_cast<StateVariables<DisplacementDim> const*>(\n                            &state) != nullptr);\n                 auto const& ehlers_state =\n                     static_cast<StateVariables<DisplacementDim> const&>(state);\n\n                 cache.resize(1);\n                 cache.front() = ehlers_state.eps_p.eff;\n                 return cache;\n             },\n             [](typename MechanicsBase<DisplacementDim>::MaterialStateVariables&\n                    state) -> BaseLib::DynamicSpan<double>\n             {\n                 assert(dynamic_cast<StateVariables<DisplacementDim> const*>(\n                            &state) != nullptr);\n                 auto& ehlers_state =\n                     static_cast<StateVariables<DisplacementDim>&>(state);\n\n                 return {&ehlers_state.eps_p.eff, 1};\n             }}};\n}\n\ntemplate class SolidEhlers<2>;\ntemplate class SolidEhlers<3>;\n\ntemplate <>\nMathLib::KelvinVector::KelvinMatrixType<3> sOdotS<3>(\n    MathLib::KelvinVector::KelvinVectorType<3> const& v)\n{\n    MathLib::KelvinVector::KelvinMatrixType<3> result;\n\n    result(0, 0) = v(0) * v(0);\n    result(0, 1) = result(1, 0) = v(3) * v(3) / 2.;\n    result(0, 2) = result(2, 0) = v(5) * v(5) / 2.;\n    result(0, 3) = result(3, 0) = v(0) * v(3);\n    result(0, 4) = result(4, 0) = v(3) * v(5) / std::sqrt(2.);\n    result(0, 5) = result(5, 0) = v(0) * v(5);\n\n    result(1, 1) = v(1) * v(1);\n    result(1, 2) = result(2, 1) = v(4) * v(4) / 2.;\n    result(1, 3) = result(3, 1) = v(3) * v(1);\n    result(1, 4) = result(4, 1) = v(1) * v(4);\n    result(1, 5) = result(5, 1) = v(3) * v(4) / std::sqrt(2.);\n\n    result(2, 2) = v(2) * v(2);\n    result(2, 3) = result(3, 2) = v(5) * v(4) / std::sqrt(2.);\n    result(2, 4) = result(4, 2) = v(4) * v(2);\n    result(2, 5) = result(5, 2) = v(5) * v(2);\n\n    result(3, 3) = v(0) * v(1) + v(3) * v(3) / 2.;\n    result(3, 4) = result(4, 3) =\n        v(3) * v(4) / 2. + v(5) * v(1) / std::sqrt(2.);\n    result(3, 5) = result(5, 3) =\n        v(0) * v(4) / std::sqrt(2.) + v(3) * v(5) / 2.;\n\n    result(4, 4) = v(1) * v(2) + v(4) * v(4) / 2.;\n    result(4, 5) = result(5, 4) =\n        v(3) * v(2) / std::sqrt(2.) + v(5) * v(4) / 2.;\n\n    result(5, 5) = v(0) * v(2) + v(5) * v(5) / 2.;\n    return result;\n}\n\ntemplate <>\nMathLib::KelvinVector::KelvinMatrixType<2> sOdotS<2>(\n    MathLib::KelvinVector::KelvinVectorType<2> const& v)\n{\n    MathLib::KelvinVector::KelvinMatrixType<2> result;\n\n    result(0, 0) = v(0) * v(0);\n    result(0, 1) = result(1, 0) = v(3) * v(3) / 2.;\n    result(0, 2) = result(2, 0) = 0;\n    result(0, 3) = result(3, 0) = v(0) * v(3);\n\n    result(1, 1) = v(1) * v(1);\n    result(1, 2) = result(2, 1) = 0;\n    result(1, 3) = result(3, 1) = v(3) * v(1);\n\n    result(2, 2) = v(2) * v(2);\n    result(2, 3) = result(3, 2) = 0;\n\n    result(3, 3) = v(0) * v(1) + v(3) * v(3) / 2.;\n\n    return result;\n}\n\n}  // namespace Ehlers\n}  // namespace Solids\n}  // namespace MaterialLib\n", "meta": {"hexsha": "f5e17124c84a6e9d7dc8eb8c165f9a2f238710ae", "size": 35689, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "MaterialLib/SolidModels/Ehlers.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/SolidModels/Ehlers.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/SolidModels/Ehlers.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": 39.2618261826, "max_line_length": 80, "alphanum_fraction": 0.6073860293, "num_tokens": 9071, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511616741041, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.4513044591043524}}
{"text": "/*\n * Calibration2.hpp\n *\n *  Created on: Jun 25, 2014\n *      Author: atabb\n */\n\n#ifndef CALIBRATION2_HPP_\n#define CALIBRATION2_HPP_\n\n#include <opencv2/core/core.hpp>\n#include <opencv2/core/mat.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/highgui/highgui_c.h>\n#include <opencv2/imgproc/imgproc.hpp>\n#include <opencv2/calib3d/calib3d.hpp>\n\n\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n\nusing namespace Eigen;\n\n#include <math.h>\n#include <cstdlib>\n#include <iostream>\n#include <fstream>\n\n#include \"DirectoryFunctions.hpp\"\n#include \"StringFunctions.hpp\"\n\nusing namespace std;\n\nclass CaliObjectOpenCV2{\npublic:\n\tdouble mm_width;\n\tdouble mm_height;\n\tint chess_w;\n\tint chess_h;\n\tdouble mean_reproj_error;\n\tdouble mean_ext_reproj_error;\n\n\tvector< vector< cv::Point2f> > internal_points;\n\tvector< vector< cv::Point2f> > external_points;\n\tvector< vector< cv::Point2f> > all_points;\n\tvector< vector< cv::Point3f> > all_3d_corners;\n\n\n\tvector<vector<double> > A;\n\tvector< double > k;\n\tvector< vector <double> > Rt;\n\tvector< vector< vector <double> > > Rts;\n\n\tvector<cv::Mat> internal_images;\n\tvector<cv::Mat> external_images;\n\tvector<int> indices;\n\n\tVectorXd PA;\n\tVectorXd PB;\n\n\n\tint number_internal_images_written;\n\n\n\tcv::Size image_size;\n\n\tstring text_file;\n\n\tCaliObjectOpenCV2(int i, int w, int h, double s_w_i, double s_h_i);\n\n\tvoid ReadImages(string internal_dir, bool flag);\n\n\tbool AccumulateCorners(bool draw_corners);\n\n\tbool AccumulateCornersFlexibleExternal(bool draw_corners);\n\n\tvoid Calibrate(std::ofstream& out, string write_directory);\n\n\tvoid CalibrateFlexibleExternal(float initial_focal_px, int zero_tangent_dist, int zero_k3, std::ofstream& out, string write_directory);\n\n\tvoid LevMarCameraCaliNoDistortion(vector< vector<cv::Point2f> >& imagep, vector< vector<cv::Point3f> >& worldp,\n\t\t\tstd::ofstream& out);\n\n};\n\nvoid camera(Matrix3d& Kinv, float max_u, float max_v, float mag, vector< Vector3d >& vertex_coordinates );\n\nint create_camera(Matrix3d& internal, MatrixXd& external, int r, int g, int b, int rows, int cols,\n\t\tstring ply_file, double scale);\n\nvoid create_camera4d(Matrix3d& internal, Matrix4d& external, int r, int g, int b, int rows, int cols,\n\t\tstring ply_file, double scale);\n\n\n#endif /* ROBOTWORLDHANDEYECALIDUALEXP0_SRC_CALIBRATION2_HPP_ */\n", "meta": {"hexsha": "64107dd7f7e0a8fd084f82c6f023a7edb2f0da20", "size": 2289, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "code_src/Calibration2.hpp", "max_stars_repo_name": "kyuhyoung/RWHEC-exp-2019", "max_stars_repo_head_hexsha": "6dfda0ee9fa85d5cffa79db94255eea64a7376da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-08-26T18:13:55.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-13T06:25:04.000Z", "max_issues_repo_path": "code_src/Calibration2.hpp", "max_issues_repo_name": "kyuhyoung/RWHEC-exp-2019", "max_issues_repo_head_hexsha": "6dfda0ee9fa85d5cffa79db94255eea64a7376da", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code_src/Calibration2.hpp", "max_forks_repo_name": "kyuhyoung/RWHEC-exp-2019", "max_forks_repo_head_hexsha": "6dfda0ee9fa85d5cffa79db94255eea64a7376da", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-10-15T09:24:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-15T09:24:16.000Z", "avg_line_length": 23.84375, "max_line_length": 136, "alphanum_fraction": 0.754041066, "num_tokens": 605, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.766293653760418, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4512620036758786}}
{"text": "/*********************************************************************\n * Software License Agreement (BSD License)\n *\n *  Copyright (c) 2019, University of Stuttgart\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions\n *  are met:\n *\n *   * Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *   * Redistributions in binary form must reproduce the above\n *     copyright notice, this list of conditions and the following\n *     disclaimer in the documentation and/or other materials provided\n *     with the distribution.\n *   * Neither the name of the University of Stuttgart nor the names\n *     of its contributors may be used to endorse or promote products\n *     derived from this software without specific prior written\n *     permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n *  \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n *  POSSIBILITY OF SUCH DAMAGE.\n *********************************************************************/\n\n/* Author: Andreas Orthey */\n\n#include <ompl/base/spaces/SE2StateSpace.h>\n#include <ompl/base/spaces/RealVectorStateSpace.h>\n#include <ompl/base/SpaceInformation.h>\n#include <ompl/base/StateSpace.h>\n#include <ompl/multilevel/planners/qrrt/QRRT.h>\n#include <iostream>\n#include <boost/math/constants/constants.hpp>\n\nnamespace ob = ompl::base;\nnamespace og = ompl::geometric;\n\n// Path Planning on fiber bundle SE2 \\rightarrow R2\n\nbool boxConstraint(const double values[])\n{\n    const double &x = values[0] - 0.5;\n    const double &y = values[1] - 0.5;\n    double pos_cnstr = sqrt(x * x + y * y);\n    return (pos_cnstr > 0.2);\n}\nbool isStateValid_SE2(const ob::State *state)\n{\n    const auto *SE2state = state->as<ob::SE2StateSpace::StateType>();\n    const auto *R2 = SE2state->as<ob::RealVectorStateSpace::StateType>(0);\n    const auto *SO2 = SE2state->as<ob::SO2StateSpace::StateType>(1);\n    return boxConstraint(R2->values) && (SO2->value < boost::math::constants::pi<double>() / 2.0);\n}\nbool isStateValid_R2(const ob::State *state)\n{\n    const auto *R2 = state->as<ob::RealVectorStateSpace::StateType>();\n    return boxConstraint(R2->values);\n}\n\nint main()\n{\n    // Setup SE2\n    auto SE2(std::make_shared<ob::SE2StateSpace>());\n    ob::RealVectorBounds bounds(2);\n    bounds.setLow(0);\n    bounds.setHigh(1);\n    SE2->setBounds(bounds);\n    ob::SpaceInformationPtr si_SE2(std::make_shared<ob::SpaceInformation>(SE2));\n    si_SE2->setStateValidityChecker(isStateValid_SE2);\n\n    // Setup Quotient-Space R2\n    auto R2(std::make_shared<ob::RealVectorStateSpace>(2));\n    R2->setBounds(0, 1);\n    ob::SpaceInformationPtr si_R2(std::make_shared<ob::SpaceInformation>(R2));\n    si_R2->setStateValidityChecker(isStateValid_R2);\n\n    // Create vector of spaceinformationptr\n    std::vector<ob::SpaceInformationPtr> si_vec;\n    si_vec.push_back(si_R2);\n    si_vec.push_back(si_SE2);\n\n    // Define Planning Problem\n    using SE2State = ob::ScopedState<ob::SE2StateSpace>;\n    SE2State start_SE2(SE2);\n    SE2State goal_SE2(SE2);\n    start_SE2->setXY(0, 0);\n    start_SE2->setYaw(0);\n    goal_SE2->setXY(1, 1);\n    goal_SE2->setYaw(0);\n\n    ob::ProblemDefinitionPtr pdef = std::make_shared<ob::ProblemDefinition>(si_SE2);\n    pdef->setStartAndGoalStates(start_SE2, goal_SE2);\n\n    // Setup Planner using vector of spaceinformationptr\n    auto planner = std::make_shared<ompl::multilevel::QRRT>(si_vec);\n\n    // Planner can be used as any other OMPL algorithm\n    planner->setProblemDefinition(pdef);\n    planner->setup();\n\n    ob::PlannerStatus solved = planner->ob::Planner::solve(1.0);\n\n    if (solved)\n    {\n        std::cout << std::string(80, '-') << std::endl;\n        std::cout << \"Bundle Space Path (SE2):\" << std::endl;\n        std::cout << std::string(80, '-') << std::endl;\n        pdef->getSolutionPath()->print(std::cout);\n\n        std::cout << std::string(80, '-') << std::endl;\n        std::cout << \"Base Space Path (R2)   :\" << std::endl;\n        std::cout << std::string(80, '-') << std::endl;\n        const ob::ProblemDefinitionPtr pdefR2 = planner->getProblemDefinition(0);\n        pdefR2->getSolutionPath()->print(std::cout);\n        std::cout << std::string(80, '-') << std::endl;\n    }\n    return 0;\n}\n", "meta": {"hexsha": "7249f3cd101daa06d951ffe30a0c4e3b5695000e", "size": 5041, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "demos/multilevel/MultiLevelPlanningRigidBody2D.cpp", "max_stars_repo_name": "orthez/ompl", "max_stars_repo_head_hexsha": "f8aa02485d27e30b4ecfb364ef3178356d42d94a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-28T07:59:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-28T07:59:11.000Z", "max_issues_repo_path": "demos/multilevel/MultiLevelPlanningRigidBody2D.cpp", "max_issues_repo_name": "orthez/ompl", "max_issues_repo_head_hexsha": "f8aa02485d27e30b4ecfb364ef3178356d42d94a", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/multilevel/MultiLevelPlanningRigidBody2D.cpp", "max_forks_repo_name": "orthez/ompl", "max_forks_repo_head_hexsha": "f8aa02485d27e30b4ecfb364ef3178356d42d94a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-08-13T12:41:36.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-25T22:57:38.000Z", "avg_line_length": 38.7769230769, "max_line_length": 98, "alphanum_fraction": 0.6730807379, "num_tokens": 1313, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.766293653760418, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4512620036758786}}
{"text": "#include \"cnn/nodes.h\"\n#include \"cnn/cnn.h\"\n#include \"cnn/training.h\"\n#include \"cnn/gpu-ops.h\"\n#include \"cnn/expr.h\"\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/archive/text_iarchive.hpp>\n\n#include <iostream>\n#include <fstream>\n\nusing namespace std;\nusing namespace cnn;\nusing namespace cnn::expr;\n\n\n// This is a sample class which implements the xor model from xor.cc\n// Everything in this class is just as you would do the usual except for\n// parts with provided comments.\nclass XORModel {\npublic:\n  unsigned hidden_size;\n\n  Expression W, b, V, a;\n  Parameters *pW, *pb, *pV, *pa;\n\n  // It is important to have a null default constructor for the class, as\n  // we would first need to read the class object from the file, followed by\n  // the cnn model which has saved parameters.\n  XORModel() {}\n\n  XORModel(const unsigned& hidden_len, Model *m) {\n    hidden_size = hidden_len;\n    InitParams(m);\n  }\n\n  void InitParams(Model *m) {\n    pW = m->add_parameters({hidden_size, 2});\n    pb = m->add_parameters({hidden_size});\n    pV = m->add_parameters({1, hidden_size});\n    pa = m->add_parameters({1});\n  }\n\n  void AddParamsToCG(ComputationGraph *cg) {\n    W = parameter(*cg, pW);\n    b = parameter(*cg, pb);\n    V = parameter(*cg, pV);\n    a = parameter(*cg, pa);\n  }\n\n  float Train(vector<cnn::real> &input, cnn::real &gold_output,\n              SimpleSGDTrainer *sgd) {\n    ComputationGraph cg;\n    AddParamsToCG(&cg);\n\n    Expression x = cnn::expr::input(cg, {(unsigned int)input.size()}, &input);\n    Expression y = cnn::expr::input(cg, &gold_output);\n\n    Expression h = tanh(W*x + b);\n    Expression y_pred = V*h + a;\n    Expression loss = squared_distance(y_pred, y);\n    float return_loss = as_scalar(cg.forward());\n    cg.backward();\n    sgd->update(1.0);\n    return return_loss;\n  }\n\n  float Decode(vector<cnn::real> &input) {\n    ComputationGraph cg;\n    AddParamsToCG(&cg);\n\n    Expression x = cnn::expr::input(cg, {(unsigned int)input.size()}, &input);\n    Expression h = tanh(W*x + b);\n    Expression y_pred = V*h + a;\n    return as_scalar(cg.forward());\n  }\n\n  // This function should save all those variables in the archive, which\n  // determine the size of other members of the class, here: hidden_size\n  friend class boost::serialization::access;\n  template<class Archive> void serialize(Archive& ar, const unsigned int) {\n\n    // This can either save or read the value of hidden_size from ar,\n    // depending on whether its the output or input archive.\n    ar & hidden_size;\n  }\n};\n\nvoid WriteToFile(string& filename, XORModel &model, Model &cnn_model) {\n  ofstream outfile(filename);\n  if (!outfile.is_open()) {\n    cerr << \"File opening failed\" << endl;\n  }\n\n  boost::archive::text_oarchive oa(outfile);\n  oa & model;  // Write down your class object.\n  oa & cnn_model;  // Write down the cnn::Model object.\n  outfile.close();\n}\n\nvoid ReadFromFile(string& filename, XORModel *model, Model *cnn_model) {\n  ifstream infile(filename);\n  if (!infile.is_open()) {\n    cerr << \"File opening failed\" << endl;\n  }\n\n  boost::archive::text_iarchive ia(infile);\n  ia & *model;  // Read your class object\n\n  // Now determine structure of cnn::Model depending on the\n  // the structure of your class object\n  model->InitParams(cnn_model);\n  ia & *cnn_model;  // Read the cnn::Model\n\n  infile.close();\n}\n\n\nint main(int argc, char** argv) {\n  cnn::Initialize(argc, argv);\n\n  const unsigned HIDDEN = 8;\n  const unsigned ITERATIONS = 20;\n  Model m;\n  SimpleSGDTrainer sgd(&m);\n  XORModel model(HIDDEN, &m);\n\n  vector<cnn::real> x_values(2);  // set x_values to change the inputs\n  cnn::real y_value;  // set y_value to change the target output\n\n  // Train the model\n  for (unsigned iter = 0; iter < ITERATIONS; ++iter) {\n    double loss = 0;\n    for (unsigned mi = 0; mi < 4; ++mi) {\n      bool x1 = mi % 2;\n      bool x2 = (mi / 2) % 2;\n      x_values[0] = x1 ? 1 : -1;\n      x_values[1] = x2 ? 1 : -1;\n      y_value = (x1 != x2) ? 1 : -1;\n      loss += model.Train(x_values, y_value, &sgd);\n    }\n    loss /= 4;\n    cerr << \"E = \" << loss << endl;\n  }\n\n  string outfile = \"out.txt\";\n  cerr << \"Written model to File: \" << outfile << endl;\n  WriteToFile(outfile, model, m);  // Writing objects to file\n\n  // New objects in which the written archive will be read\n  Model read_cnn_model;\n  XORModel read_model;\n\n  cerr << \"Reading model from File: \" << outfile << endl;\n  ReadFromFile(outfile, &read_model, &read_cnn_model);  // Reading from file\n  cerr << \"Output for the input: \" << x_values[0] << \" \" << x_values[1] << endl;\n  cerr << read_model.Decode(x_values);  // Checking output for sanity\n}\n\n", "meta": {"hexsha": "0723d38f9fb473c93a2a8830eeaf4aad1e8f53b9", "size": 4620, "ext": "cc", "lang": "C++", "max_stars_repo_path": "cnn/examples/read-write.cc", "max_stars_repo_name": "miguelballesteros/Spinal", "max_stars_repo_head_hexsha": "0f765e5baeb07a1d068c4eda06b9222e06df2cde", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 219.0, "max_stars_repo_stars_event_min_datetime": "2015-06-27T13:15:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-13T20:45:34.000Z", "max_issues_repo_path": "cnn/examples/read-write.cc", "max_issues_repo_name": "miguelballesteros/Spinal", "max_issues_repo_head_hexsha": "0f765e5baeb07a1d068c4eda06b9222e06df2cde", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 18.0, "max_issues_repo_issues_event_min_datetime": "2015-07-08T05:12:55.000Z", "max_issues_repo_issues_event_max_datetime": "2018-04-23T13:38:10.000Z", "max_forks_repo_path": "cnn/examples/read-write.cc", "max_forks_repo_name": "miguelballesteros/Spinal", "max_forks_repo_head_hexsha": "0f765e5baeb07a1d068c4eda06b9222e06df2cde", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 68.0, "max_forks_repo_forks_event_min_datetime": "2015-06-29T16:51:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-10T20:35:14.000Z", "avg_line_length": 28.875, "max_line_length": 80, "alphanum_fraction": 0.6532467532, "num_tokens": 1290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.766293653760418, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4512620036758786}}
{"text": "#ifndef IMAGE_REPROJECTION_PLUGINS_PINHOLE_CAMERA_MODEL_HPP\n#define IMAGE_REPROJECTION_PLUGINS_PINHOLE_CAMERA_MODEL_HPP\n\n#include <algorithm>\n#include <vector>\n\n#include <image_reprojection/camera_model.hpp>\n#include <sensor_msgs/CameraInfo.h>\n#include <sensor_msgs/distortion_models.h>\n\n#include <opencv2/calib3d/calib3d.hpp>\n#include <opencv2/core/core.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n\n#include <boost/make_shared.hpp>\n#include <boost/thread/locks.hpp>\n#include <boost/thread/shared_mutex.hpp>\n\nnamespace image_reprojection_plugins {\n\nclass PinholeCameraModel : public image_reprojection::CameraModel {\npublic:\n  PinholeCameraModel() {}\n\n  virtual ~PinholeCameraModel() {}\n\n  virtual void fromCameraInfo(const sensor_msgs::CameraInfo &camera_info) override {\n    // assert distortion type and number of distortion parameters\n    CV_Assert(camera_info.distortion_model == sensor_msgs::distortion_models::PLUMB_BOB ||\n              camera_info.distortion_model == sensor_msgs::distortion_models::RATIONAL_POLYNOMIAL);\n    CV_Assert(camera_info.D.size() == 0 || camera_info.D.size() == 4 || camera_info.D.size() == 5 ||\n              camera_info.D.size() == 8 || camera_info.D.size() == 12 ||\n              camera_info.D.size() == 14);\n\n    boost::unique_lock<boost::shared_mutex> write_lock(mutex_);\n\n    // copy entire camera info to return it via toCameraInfo()\n    camera_info_ = camera_info;\n\n    // copy full resolution camera matrix\n    std::copy(camera_info.K.begin(), camera_info.K.end(), camera_matrix_.val);\n\n    // adust offset of principal points.\n    // (this should be performed against full camera matrix\n    // because offsets are written in full resolution)\n    if (camera_info.roi.x_offset != 0) {\n      camera_matrix_(0, 2) -= camera_info.roi.x_offset;\n    }\n    if (camera_info.roi.y_offset != 0) {\n      camera_matrix_(1, 2) -= camera_info.roi.y_offset;\n    }\n\n    // copy ROI info in full resolution\n    frame_.x = camera_info.roi.x_offset;\n    frame_.y = camera_info.roi.y_offset;\n    frame_.width = (camera_info.roi.width == 0 ? camera_info.width : camera_info.roi.width);\n    frame_.height = (camera_info.roi.height == 0 ? camera_info.height : camera_info.roi.height);\n\n    // adust image scaling\n    if (camera_info.binning_x != 0 && camera_info.binning_x != 1) {\n      camera_matrix_(0, 0) /= camera_info.binning_x;\n      camera_matrix_(0, 1) /= camera_info.binning_x;\n      camera_matrix_(0, 2) /= camera_info.binning_x;\n      frame_.x /= camera_info.binning_x;\n      frame_.width /= camera_info.binning_x;\n    }\n    if (camera_info.binning_y != 0 && camera_info.binning_y != 1) {\n      camera_matrix_(1, 0) /= camera_info.binning_y;\n      camera_matrix_(1, 1) /= camera_info.binning_y;\n      camera_matrix_(1, 2) /= camera_info.binning_y;\n      frame_.y /= camera_info.binning_y;\n      frame_.height /= camera_info.binning_y;\n    }\n\n    // copy distortion coefficients which are independent from image resolution\n    dist_coeffs_ = camera_info.D;\n  }\n\n  virtual sensor_msgs::CameraInfoPtr toCameraInfo() const override {\n    boost::shared_lock<boost::shared_mutex> read_lock(mutex_);\n    return boost::make_shared<sensor_msgs::CameraInfo>(camera_info_);\n  }\n\nprivate:\n  virtual void onInit() override {}\n\n  virtual void onProject3dToPixel(const cv::Mat &src, cv::Mat &dst, cv::Mat &mask) const override {\n    boost::shared_lock<boost::shared_mutex> read_lock(mutex_);\n\n    // project 3D points in the camera coordinate into the 2D image coordinate\n    cv::projectPoints(src.reshape(3, src.total()), cv::Vec3d::all(0.), cv::Vec3d::all(0.),\n                      camera_matrix_, dist_coeffs_, dst);\n    dst = dst.reshape(2, src.size().height);\n\n    // update mask to indicate valid output points.\n    // an output point is valid when\n    //   - corresponding input point is valid (input mask is valid)\n    //   - corresponding input point is in front of the camera\n    //   - output pixel is in the image frame\n    mask.forEach<uchar>([this, &src, &dst](uchar &m, const int *const pos) {\n      if (m != 0) {\n        const cv::Point3f &s = *src.ptr<cv::Point3f>(pos[0], pos[1]);\n        cv::Point2f &d = *dst.ptr<cv::Point2f>(pos[0], pos[1]);\n        m = (s.z >= 0 && frame_.contains(d)) ? 1 : 0;\n      }\n    });\n  }\n\n  virtual void onProjectPixelTo3dRay(const cv::Mat &src, cv::Mat &dst,\n                                     cv::Mat &mask) const override {\n    boost::shared_lock<boost::shared_mutex> read_lock(mutex_);\n\n    // reproject 2D points in the image coordinate to the camera coordinate\n    cv::Mat dst_2d;\n    cv::undistortPoints(src.reshape(2, src.total()), dst_2d, camera_matrix_, dist_coeffs_);\n    dst_2d = dst_2d.reshape(2, src.size().height);\n\n    // add z-channel to the points in the camera coordinate\n    dst.create(dst_2d.size(), CV_32FC3);\n    // copy xy-channels\n    dst_2d.reshape(1, dst_2d.total()).copyTo(dst.reshape(1, dst.total()).colRange(0, 2));\n    // fill z-channel to 1.0\n    dst.reshape(1, dst.total()).col(2).setTo(1.);\n\n    // update mask to indicate valid output points.\n    // an output point is valid when\n    //   - corresponding input pixel is valid (input mask is valid)\n    //   - corresponding input pixel is in the image frame\n    mask.forEach<uchar>([this, &src](uchar &m, const int *const pos) {\n      if (m != 0) {\n        const cv::Point2f &s = *src.ptr<cv::Point2f>(pos[0], pos[1]);\n        m = frame_.contains(s) ? 1 : 0;\n      }\n    });\n  }\n\nprivate:\n  mutable boost::shared_mutex mutex_;\n  sensor_msgs::CameraInfo camera_info_;\n  cv::Matx33d camera_matrix_;\n  std::vector<double> dist_coeffs_;\n  cv::Rect_<float> frame_;\n};\n\n} // namespace image_reprojection_plugins\n\n#endif /* IMAGE_REPROJECTION_PLUGINS_PINHOLE_CAMERA_MODEL_HPP */\n", "meta": {"hexsha": "b6a046459987c6685765e8c7ae3ecf7b07ad4916", "size": 5725, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "image_reprojection_plugins/include/image_reprojection_plugins/pinhole_camera_model.hpp", "max_stars_repo_name": "yoshito-n-students/image_reprojection", "max_stars_repo_head_hexsha": "7398c49619f7132ab95d8b9accce90a241d6507a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2018-09-14T05:26:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-04T04:28:03.000Z", "max_issues_repo_path": "image_reprojection_plugins/include/image_reprojection_plugins/pinhole_camera_model.hpp", "max_issues_repo_name": "yoshito-n-students/image_reprojection", "max_issues_repo_head_hexsha": "7398c49619f7132ab95d8b9accce90a241d6507a", "max_issues_repo_licenses": ["MIT"], "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_reprojection_plugins/include/image_reprojection_plugins/pinhole_camera_model.hpp", "max_forks_repo_name": "yoshito-n-students/image_reprojection", "max_forks_repo_head_hexsha": "7398c49619f7132ab95d8b9accce90a241d6507a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-05-14T04:03:35.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-14T04:03:35.000Z", "avg_line_length": 38.6824324324, "max_line_length": 100, "alphanum_fraction": 0.6810480349, "num_tokens": 1518, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.766293653760418, "lm_q2_score": 0.5888891307678319, "lm_q1q2_score": 0.4512620036758785}}
{"text": "#include <type_traits>\n#include <boost/safe_numerics/safe_integer.hpp>\n#include <boost/safe_numerics/safe_integer_range.hpp>\n\n#include <boost/safe_numerics/utility.hpp>\n\nusing namespace boost::safe_numerics;\n\nvoid f(){\n    safe_unsigned_range<7, 24> i;\n    // since the range is included in [0,255], the underlying type of i \n    // will be an unsigned char.\n    i = 0;  // throws out_of_range exception\n    i = 9;  // ok\n    i *= 9; // throws out_of_range exception\n    i = -1; // throws out_of_range exception\n    std::uint8_t j = 4;\n    auto k = i + j;\n\n    // if either or both types are safe types, the result is a safe type\n    // determined by promotion policy.  In this instance\n    // the range of i is [7, 24] and the range of j is [0,255].\n    // so the type of k will be a safe type with a range of [7,279]\n    static_assert(\n        is_safe<decltype(k)>::value\n        && std::numeric_limits<decltype(k)>::min() == 7\n        && std::numeric_limits<decltype(k)>::max() == 279,\n        \"k is a safe range of [7,279]\"\n    );\n}\n\nint main(){}\n", "meta": {"hexsha": "e9cd464880c9f3adf08b942483e81225ce301de7", "size": 1051, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/example19.cpp", "max_stars_repo_name": "giomasce-throwaway/safe_numerics", "max_stars_repo_head_hexsha": "3a1676e5831bab93b9be50caec69c1887a4af7da", "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": "example/example19.cpp", "max_issues_repo_name": "giomasce-throwaway/safe_numerics", "max_issues_repo_head_hexsha": "3a1676e5831bab93b9be50caec69c1887a4af7da", "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": "example/example19.cpp", "max_forks_repo_name": "giomasce-throwaway/safe_numerics", "max_forks_repo_head_hexsha": "3a1676e5831bab93b9be50caec69c1887a4af7da", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 31.8484848485, "max_line_length": 72, "alphanum_fraction": 0.6384395814, "num_tokens": 298, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859598, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.45126199738980616}}
{"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#define BOOST_MATH_MAX_SERIES_ITERATION_POLICY 10000000\n\n#define BOOST_MATH_USE_MPFR\n#include \"mp_t.hpp\"\n#include <boost/math/special_functions/hypergeometric_1f1.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/lexical_cast.hpp>\n#include <fstream>\n#include <map>\n#include <boost/math/tools/test_data.hpp>\n#include <boost/random.hpp>\n\n#include <boost/multiprecision/mpfi.hpp>\n\nusing namespace boost::math::tools;\nusing namespace boost::math;\nusing namespace std;\nusing namespace boost::multiprecision;\n\ntypedef mpfi_float_1000 mpfi_type;\n\nmp_t hypergeometric_1f1_generic_series(mp_t a_, mp_t b_, mp_t z_)\n{\n   using namespace boost::math::tools;\n   using namespace boost::math;\n   using namespace std;\n   using namespace boost::multiprecision;\n\n   mpfi_type a(a_), b(b_), z(z_), sum(0), term(1), diff, term0(0);\n   unsigned n = 0;\n   bool cont = true;\n\n   unsigned max_n;\n   if (b < 0)\n      max_n = itrunc(-b) + 10000;\n   else\n      max_n = 10000000;\n\n   mpfi_type overflow_limit(\"1.189731495357231765e+4900\");  // a bit less than LDBL_MAX for extended long doubles.\n\n   do\n   {\n      sum += term;\n      term *= (((a + n) / ((b + n) * (n + 1))) * z);\n      ++n;\n      diff = fabs(term / sum);\n      if (n > max_n)\n      {\n         std::cout << \"Aborting series evaluation due to too many iterations...\\n\";\n         throw evaluation_error(\"\");\n      }\n      if (fabs(upper(sum)) > overflow_limit)\n      {\n         std::cout << \"Aborting series evaluation due to over large sum...\\n\";\n         throw evaluation_error(\"\");\n      }\n      cont = (fabs(upper(diff)) > 1e-40) || (b + n < 0) || (fabs(term0) < fabs(term));\n      term0 = term;\n      //std::cout << upper(term) << \" \" << upper(sum) << \" \" << upper(diff) << \" \" << cont << std::endl;\n   } while (cont);\n\n   mp_t r = mp_t(width(sum) / median(sum));\n   if (fabs(r) > 1e-40)\n   {\n      std::cout << \"Aborting to to error in result of \" << r << std::endl;\n      throw evaluation_error(\"\");\n   }\n   std::cout << \"Found error in sum was \" << r << std::endl;\n\n   return mp_t(median(sum));\n}\n\n\nstruct hypergeometric_1f1_gen\n{\n   mp_t operator()(mp_t a1, mp_t a2, mp_t z)\n   {\n      mp_t result;\n      try {\n         result = hypergeometric_1f1_generic_series(a1, a2, z);\n         std::cout << a1 << \" \" << a2 << \" \" << z << \" \" << result << std::endl;\n      }\n      catch (...)\n      {\n         throw std::domain_error(\"\");\n      }\n      if (fabs(result) > (std::numeric_limits<double>::max)())\n      {\n         std::cout << \"Rejecting over large value\\n\";\n         throw std::domain_error(\"\");\n      }\n      return result;\n   }\n};\n\n\nint main(int, char* [])\n{\n   parameter_info<mp_t> arg1, arg2, arg3;\n   test_data<mp_t> data;\n\n   std::cout << \"Welcome.\\n\"\n      \"This program will generate spot tests for 1F1 (Yeh!!):\\n\";\n\n   std::string line;\n   //bool cont;\n\n   std::vector<mp_t> v;\n   random_ns::mt19937 rnd;\n   random_ns::uniform_real_distribution<float> ur_a(0, 1);\n\n   mp_t p = ur_a(rnd);\n   p *= 1e6;\n   v.push_back(p);\n   v.push_back(-p);\n   p = ur_a(rnd);\n   p *= 1e5;\n   v.push_back(p);\n   v.push_back(-p);\n   p = ur_a(rnd);\n   p *= 1e4;\n   v.push_back(p);\n   v.push_back(-p);\n   p = ur_a(rnd);\n   p *= 1e3;\n   v.push_back(p);\n   v.push_back(-p);\n   p = ur_a(rnd);\n   p *= 1e2;\n   v.push_back(p);\n   v.push_back(-p);\n   p = ur_a(rnd);\n   p *= 1e-5;\n   v.push_back(p);\n   v.push_back(-p);\n   p = ur_a(rnd);\n   p *= 1e-12;\n   v.push_back(p);\n   v.push_back(-p);\n   p = ur_a(rnd);\n   p *= 1e-30;\n   v.push_back(p);\n   v.push_back(-p);\n\n   for (unsigned i = 0; i < v.size(); ++i)\n   {\n      for (unsigned j = 0; j < v.size(); ++j)\n      {\n         for (unsigned k = 0; k < v.size(); ++k)\n         {\n            std::cout << i << \" \" << j << \" \" << k << std::endl;\n            std::cout << v[i] << \" \" << (v[j] * 3) / 2 << \" \" << (v[j] * 5) / 4 << std::endl;\n            arg1 = make_single_param(v[i]);\n            arg2 = make_single_param(mp_t((v[j] * 3) / 2));\n            arg3 = make_single_param(mp_t((v[k] * 5) / 4));\n            data.insert(hypergeometric_1f1_gen(), arg1, arg2, arg3);\n         }\n      }\n   }\n\n\n   std::cout << \"Enter name of test data file [default=hypergeometric_1f1.ipp]\";\n   std::getline(std::cin, line);\n   boost::algorithm::trim(line);\n   if(line == \"\")\n      line = \"hypergeometric_1f1.ipp\";\n   std::ofstream ofs(line.c_str());\n   ofs << std::scientific << std::setprecision(40);\n   write_code(ofs, data, line.c_str());\n\n   return 0;\n}\n\n\n", "meta": {"hexsha": "e767e242cdd87645c1a5f3e2d3cd8a40464cba7b", "size": 4670, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/tools/hyp_1f1_big_data.cpp", "max_stars_repo_name": "anarthal/boost-unix-mirror", "max_stars_repo_head_hexsha": "8c34eb2fe471d6c3113c680c1fbef29e7a8063a0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-15T13:07:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-15T13:07:07.000Z", "max_issues_repo_path": "libs/math/tools/hyp_1f1_big_data.cpp", "max_issues_repo_name": "anarthal/boost-unix-mirror", "max_issues_repo_head_hexsha": "8c34eb2fe471d6c3113c680c1fbef29e7a8063a0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-10-21T12:42:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-03T08:41:31.000Z", "max_forks_repo_path": "Libs/boost_1_76_0/libs/math/tools/hyp_1f1_big_data.cpp", "max_forks_repo_name": "Antd23rus/S2DE", "max_forks_repo_head_hexsha": "47cc7151c2934cd8f0399a9856c1e54894571553", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-11-03T14:12:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-22T19:20:54.000Z", "avg_line_length": 25.9444444444, "max_line_length": 114, "alphanum_fraction": 0.5683083512, "num_tokens": 1452, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4512619973898061}}
{"text": "#define BOOST_TEST_MODULE \"test_tabulated_lennard_jones_attractive_potential\"\n\n#ifdef BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n#else\n#include <boost/test/included/unit_test.hpp>\n#endif\n\n#include <mjolnir/forcefield/global/LennardJonesPotential.hpp>\n#include <mjolnir/forcefield/global/TabulatedLennardJonesAttractivePotential.hpp>\n#include <mjolnir/core/BoundaryCondition.hpp>\n#include <mjolnir/core/SimulatorTraits.hpp>\n\nBOOST_AUTO_TEST_CASE(LennardJones_double)\n{\n    using traits_type = mjolnir::SimulatorTraits<double, mjolnir::UnlimitedBoundary>;\n    using real_type   = typename traits_type::real_type;\n    using molecule_id_type = mjolnir::Topology::molecule_id_type;\n    using group_id_type    = mjolnir::Topology::group_id_type;\n    using potential_type   = mjolnir::TabulatedLennardJonesAttractivePotential<traits_type>;\n\n    constexpr static std::size_t N = 10000;\n    constexpr static real_type   h = 1e-6;\n\n    const real_type sigma   = 3.0;\n    const real_type epsilon = 1.0;\n    potential_type lj{\n        potential_type::default_cutoff(),\n        {{\"A:B\", {sigma, epsilon}}},\n        {{0, \"A\"}, {1, \"B\"}}, {},\n        mjolnir::IgnoreMolecule<molecule_id_type>(\"Nothing\"),\n        mjolnir::IgnoreGroup   <group_id_type   >({})\n    };\n\n    const real_type x_min = std::pow(2.0, 1.0/6.0) * sigma;\n    const real_type x_max = lj.cutoff_ratio() * sigma;\n    const real_type dx = (x_max - x_min) / N;\n\n    for(std::size_t i=1; i<N; ++i)\n    {\n        const real_type x    = x_min + i * dx;\n        const real_type pot1 = lj.potential(0, 1, x + h);\n        const real_type pot2 = lj.potential(0, 1, x - h);\n        const real_type dpot = (pot1 - pot2) / (2 * h);\n        const real_type deri = lj.derivative(0, 1, x);\n\n        BOOST_TEST(dpot == deri, boost::test_tools::tolerance(h));\n    }\n\n    // -epsilon if x < 2^1/6 sigma\n    for(std::size_t i=0; i<N; ++i)\n    {\n        const real_type x = (double(i) / N) * x_min;\n        const real_type E = lj.potential(0, 1, x);\n        BOOST_TEST(E == -epsilon, boost::test_tools::tolerance(h));\n    }\n\n    const auto param = std::make_pair(sigma, epsilon);\n    mjolnir::LennardJonesPotential<traits_type> ref{\n        potential_type::default_cutoff(),\n        {{0, param}, {1, param}}, {},\n        mjolnir::IgnoreMolecule<molecule_id_type>(\"Nothing\"),\n        mjolnir::IgnoreGroup   <group_id_type   >({})\n    };\n\n    for(std::size_t i=1; i<N; ++i)\n    {\n        const real_type x      = x_min + i * dx;\n        const real_type pot    = lj.potential(0, 1, x);\n        const real_type ref_lj = ref.potential(0, 1, x);\n        BOOST_TEST(pot == ref_lj, boost::test_tools::tolerance(h));\n    }\n}\n", "meta": {"hexsha": "eb3d731b98eed94fd086a7f5a4bd6f18b64abe47", "size": 2663, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/core/test_tabulated_lennard_jones_attractive_potential.cpp", "max_stars_repo_name": "ToruNiina/Mjolnir", "max_stars_repo_head_hexsha": "44435dd3afc12f5c8ea27a66d7ab282df3e588ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2017-02-01T08:28:38.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-25T15:47:51.000Z", "max_issues_repo_path": "test/core/test_tabulated_lennard_jones_attractive_potential.cpp", "max_issues_repo_name": "Mjolnir-MD/Mjolnir", "max_issues_repo_head_hexsha": "043df4080720837042c6b67a5495ecae198bc2b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 60.0, "max_issues_repo_issues_event_min_datetime": "2019-01-14T08:11:33.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-29T08:26:36.000Z", "max_forks_repo_path": "test/core/test_tabulated_lennard_jones_attractive_potential.cpp", "max_forks_repo_name": "Mjolnir-MD/Mjolnir", "max_forks_repo_head_hexsha": "043df4080720837042c6b67a5495ecae198bc2b3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2019-01-13T11:03:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-01T11:38:00.000Z", "avg_line_length": 35.9864864865, "max_line_length": 92, "alphanum_fraction": 0.6473901615, "num_tokens": 796, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4512619973898061}}
{"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_GGEVX_HPP\n#define BOOST_NUMERIC_BINDINGS_LAPACK_DRIVER_GGEVX_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 ggevx 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 ggevx( const char balanc, const char jobvl,\n        const char jobvr, const char sense, const fortran_int_t n, float* a,\n        const fortran_int_t lda, float* b, const fortran_int_t ldb,\n        float* alphar, float* alphai, float* beta, float* vl,\n        const fortran_int_t ldvl, float* vr, const fortran_int_t ldvr,\n        fortran_int_t& ilo, fortran_int_t& ihi, float* lscale, float* rscale,\n        float& abnrm, float& bbnrm, float* rconde, float* rcondv, float* work,\n        const fortran_int_t lwork, fortran_int_t* iwork,\n        fortran_bool_t* bwork ) {\n    fortran_int_t info(0);\n    LAPACK_SGGEVX( &balanc, &jobvl, &jobvr, &sense, &n, a, &lda, b, &ldb,\n            alphar, alphai, beta, vl, &ldvl, vr, &ldvr, &ilo, &ihi, lscale,\n            rscale, &abnrm, &bbnrm, rconde, rcondv, work, &lwork, iwork,\n            bwork, &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 ggevx( const char balanc, const char jobvl,\n        const char jobvr, const char sense, const fortran_int_t n, double* a,\n        const fortran_int_t lda, double* b, const fortran_int_t ldb,\n        double* alphar, double* alphai, double* beta, double* vl,\n        const fortran_int_t ldvl, double* vr, const fortran_int_t ldvr,\n        fortran_int_t& ilo, fortran_int_t& ihi, double* lscale,\n        double* rscale, double& abnrm, double& bbnrm, double* rconde,\n        double* rcondv, double* work, const fortran_int_t lwork,\n        fortran_int_t* iwork, fortran_bool_t* bwork ) {\n    fortran_int_t info(0);\n    LAPACK_DGGEVX( &balanc, &jobvl, &jobvr, &sense, &n, a, &lda, b, &ldb,\n            alphar, alphai, beta, vl, &ldvl, vr, &ldvr, &ilo, &ihi, lscale,\n            rscale, &abnrm, &bbnrm, rconde, rcondv, work, &lwork, iwork,\n            bwork, &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 ggevx( const char balanc, const char jobvl,\n        const char jobvr, const char sense, const fortran_int_t n,\n        std::complex<float>* a, const fortran_int_t lda,\n        std::complex<float>* b, const fortran_int_t ldb,\n        std::complex<float>* alpha, std::complex<float>* beta,\n        std::complex<float>* vl, const fortran_int_t ldvl,\n        std::complex<float>* vr, const fortran_int_t ldvr, fortran_int_t& ilo,\n        fortran_int_t& ihi, float* lscale, float* rscale, float& abnrm,\n        float& bbnrm, float* rconde, float* rcondv, std::complex<float>* work,\n        const fortran_int_t lwork, float* rwork, fortran_int_t* iwork,\n        fortran_bool_t* bwork ) {\n    fortran_int_t info(0);\n    LAPACK_CGGEVX( &balanc, &jobvl, &jobvr, &sense, &n, a, &lda, b, &ldb,\n            alpha, beta, vl, &ldvl, vr, &ldvr, &ilo, &ihi, lscale, rscale,\n            &abnrm, &bbnrm, rconde, rcondv, work, &lwork, rwork, iwork, bwork,\n            &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 ggevx( const char balanc, const char jobvl,\n        const char jobvr, const char sense, const fortran_int_t n,\n        std::complex<double>* a, const fortran_int_t lda,\n        std::complex<double>* b, const fortran_int_t ldb,\n        std::complex<double>* alpha, std::complex<double>* beta,\n        std::complex<double>* vl, const fortran_int_t ldvl,\n        std::complex<double>* vr, const fortran_int_t ldvr,\n        fortran_int_t& ilo, fortran_int_t& ihi, double* lscale,\n        double* rscale, double& abnrm, double& bbnrm, double* rconde,\n        double* rcondv, std::complex<double>* work, const fortran_int_t lwork,\n        double* rwork, fortran_int_t* iwork, fortran_bool_t* bwork ) {\n    fortran_int_t info(0);\n    LAPACK_ZGGEVX( &balanc, &jobvl, &jobvr, &sense, &n, a, &lda, b, &ldb,\n            alpha, beta, vl, &ldvl, vr, &ldvr, &ilo, &ihi, lscale, rscale,\n            &abnrm, &bbnrm, rconde, rcondv, work, &lwork, rwork, iwork, bwork,\n            &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 ggevx.\n//\ntemplate< typename Value, typename Enable = void >\nstruct ggevx_impl {};\n\n//\n// This implementation is enabled if Value is a real type.\n//\ntemplate< typename Value >\nstruct ggevx_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 MatrixB, typename VectorALPHAR,\n            typename VectorALPHAI, typename VectorBETA, typename MatrixVL,\n            typename MatrixVR, typename VectorLSCALE, typename VectorRSCALE,\n            typename VectorRCONDE, typename VectorRCONDV, typename WORK,\n            typename IWORK, typename BWORK >\n    static std::ptrdiff_t invoke( const char balanc, const char jobvl,\n            const char jobvr, const char sense, MatrixA& a, MatrixB& b,\n            VectorALPHAR& alphar, VectorALPHAI& alphai, VectorBETA& beta,\n            MatrixVL& vl, MatrixVR& vr, fortran_int_t& ilo,\n            fortran_int_t& ihi, VectorLSCALE& lscale,\n            VectorRSCALE& rscale, real_type& abnrm, real_type& bbnrm,\n            VectorRCONDE& rconde, VectorRCONDV& rcondv, detail::workspace3<\n            WORK, IWORK, BWORK > 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< MatrixB >::value) );\n        BOOST_STATIC_ASSERT( (bindings::is_column_major< MatrixVL >::value) );\n        BOOST_STATIC_ASSERT( (bindings::is_column_major< MatrixVR >::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                MatrixB >::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                VectorALPHAR >::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                VectorALPHAI >::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                VectorBETA >::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                MatrixVL >::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                MatrixVR >::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                VectorLSCALE >::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                VectorRSCALE >::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                VectorRCONDE >::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                VectorRCONDV >::type >::type >::value) );\n        BOOST_STATIC_ASSERT( (bindings::is_mutable< MatrixA >::value) );\n        BOOST_STATIC_ASSERT( (bindings::is_mutable< MatrixB >::value) );\n        BOOST_STATIC_ASSERT( (bindings::is_mutable< VectorALPHAR >::value) );\n        BOOST_STATIC_ASSERT( (bindings::is_mutable< VectorALPHAI >::value) );\n        BOOST_STATIC_ASSERT( (bindings::is_mutable< VectorBETA >::value) );\n        BOOST_STATIC_ASSERT( (bindings::is_mutable< MatrixVL >::value) );\n        BOOST_STATIC_ASSERT( (bindings::is_mutable< MatrixVR >::value) );\n        BOOST_STATIC_ASSERT( (bindings::is_mutable< VectorLSCALE >::value) );\n        BOOST_STATIC_ASSERT( (bindings::is_mutable< VectorRSCALE >::value) );\n        BOOST_STATIC_ASSERT( (bindings::is_mutable< VectorRCONDE >::value) );\n        BOOST_STATIC_ASSERT( (bindings::is_mutable< VectorRCONDV >::value) );\n        BOOST_ASSERT( bindings::size(alphai) >= bindings::size_column(a) );\n        BOOST_ASSERT( bindings::size(alphar) >= bindings::size_column(a) );\n        BOOST_ASSERT( bindings::size(work.select(fortran_int_t())) >=\n                min_size_iwork( sense, bindings::size_column(a) ));\n        BOOST_ASSERT( bindings::size(work.select(fortran_bool_t())) >=\n                min_size_bwork( sense, bindings::size_column(a) ));\n        BOOST_ASSERT( bindings::size(work.select(real_type())) >=\n                min_size_work( balanc, jobvl, jobvr, sense,\n                bindings::size_column(a) ));\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(b) == 1 ||\n                bindings::stride_minor(b) == 1 );\n        BOOST_ASSERT( bindings::size_minor(vl) == 1 ||\n                bindings::stride_minor(vl) == 1 );\n        BOOST_ASSERT( bindings::size_minor(vr) == 1 ||\n                bindings::stride_minor(vr) == 1 );\n        BOOST_ASSERT( bindings::stride_major(a) >= std::max< std::ptrdiff_t >(1,\n                bindings::size_column(a)) );\n        BOOST_ASSERT( bindings::stride_major(b) >= std::max< std::ptrdiff_t >(1,\n                bindings::size_column(a)) );\n        BOOST_ASSERT( balanc == 'N' || balanc == 'P' || balanc == 'S' ||\n                balanc == 'B' );\n        BOOST_ASSERT( jobvl == 'N' || jobvl == 'V' );\n        BOOST_ASSERT( jobvr == 'N' || jobvr == 'V' );\n        BOOST_ASSERT( sense == 'N' || sense == 'E' || sense == 'V' ||\n                sense == 'B' );\n        return detail::ggevx( balanc, jobvl, jobvr, sense,\n                bindings::size_column(a), bindings::begin_value(a),\n                bindings::stride_major(a), bindings::begin_value(b),\n                bindings::stride_major(b), bindings::begin_value(alphar),\n                bindings::begin_value(alphai), bindings::begin_value(beta),\n                bindings::begin_value(vl), bindings::stride_major(vl),\n                bindings::begin_value(vr), bindings::stride_major(vr), ilo,\n                ihi, bindings::begin_value(lscale),\n                bindings::begin_value(rscale), abnrm, bbnrm,\n                bindings::begin_value(rconde), bindings::begin_value(rcondv),\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                bindings::begin_value(work.select(fortran_bool_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 MatrixB, typename VectorALPHAR,\n            typename VectorALPHAI, typename VectorBETA, typename MatrixVL,\n            typename MatrixVR, typename VectorLSCALE, typename VectorRSCALE,\n            typename VectorRCONDE, typename VectorRCONDV >\n    static std::ptrdiff_t invoke( const char balanc, const char jobvl,\n            const char jobvr, const char sense, MatrixA& a, MatrixB& b,\n            VectorALPHAR& alphar, VectorALPHAI& alphai, VectorBETA& beta,\n            MatrixVL& vl, MatrixVR& vr, fortran_int_t& ilo,\n            fortran_int_t& ihi, VectorLSCALE& lscale,\n            VectorRSCALE& rscale, real_type& abnrm, real_type& bbnrm,\n            VectorRCONDE& rconde, VectorRCONDV& rcondv, minimal_workspace ) {\n        namespace bindings = ::boost::numeric::bindings;\n        bindings::detail::array< real_type > tmp_work( min_size_work( balanc,\n                jobvl, jobvr, sense, bindings::size_column(a) ) );\n        bindings::detail::array< fortran_int_t > tmp_iwork(\n                min_size_iwork( sense, bindings::size_column(a) ) );\n        bindings::detail::array< fortran_bool_t > tmp_bwork( min_size_bwork(\n                sense, bindings::size_column(a) ) );\n        return invoke( balanc, jobvl, jobvr, sense, a, b, alphar, alphai,\n                beta, vl, vr, ilo, ihi, lscale, rscale, abnrm, bbnrm, rconde,\n                rcondv, workspace( tmp_work, tmp_iwork, tmp_bwork ) );\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 MatrixB, typename VectorALPHAR,\n            typename VectorALPHAI, typename VectorBETA, typename MatrixVL,\n            typename MatrixVR, typename VectorLSCALE, typename VectorRSCALE,\n            typename VectorRCONDE, typename VectorRCONDV >\n    static std::ptrdiff_t invoke( const char balanc, const char jobvl,\n            const char jobvr, const char sense, MatrixA& a, MatrixB& b,\n            VectorALPHAR& alphar, VectorALPHAI& alphai, VectorBETA& beta,\n            MatrixVL& vl, MatrixVR& vr, fortran_int_t& ilo,\n            fortran_int_t& ihi, VectorLSCALE& lscale,\n            VectorRSCALE& rscale, real_type& abnrm, real_type& bbnrm,\n            VectorRCONDE& rconde, VectorRCONDV& rcondv, optimal_workspace ) {\n        namespace bindings = ::boost::numeric::bindings;\n        real_type opt_size_work;\n        bindings::detail::array< fortran_int_t > tmp_iwork(\n                min_size_iwork( sense, bindings::size_column(a) ) );\n        bindings::detail::array< fortran_bool_t > tmp_bwork( min_size_bwork(\n                sense, bindings::size_column(a) ) );\n        detail::ggevx( balanc, jobvl, jobvr, sense,\n                bindings::size_column(a), bindings::begin_value(a),\n                bindings::stride_major(a), bindings::begin_value(b),\n                bindings::stride_major(b), bindings::begin_value(alphar),\n                bindings::begin_value(alphai), bindings::begin_value(beta),\n                bindings::begin_value(vl), bindings::stride_major(vl),\n                bindings::begin_value(vr), bindings::stride_major(vr), ilo,\n                ihi, bindings::begin_value(lscale),\n                bindings::begin_value(rscale), abnrm, bbnrm,\n                bindings::begin_value(rconde), bindings::begin_value(rcondv),\n                &opt_size_work, -1, bindings::begin_value(tmp_iwork),\n                bindings::begin_value(tmp_bwork) );\n        bindings::detail::array< real_type > tmp_work(\n                traits::detail::to_int( opt_size_work ) );\n        return invoke( balanc, jobvl, jobvr, sense, a, b, alphar, alphai,\n                beta, vl, vr, ilo, ihi, lscale, rscale, abnrm, bbnrm, rconde,\n                rcondv, workspace( tmp_work, tmp_iwork, tmp_bwork ) );\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 char balanc, const char jobvl,\n            const char jobvr, const char sense, const std::ptrdiff_t n ) {\n        if ( balanc == 'S' || balanc == 'B' || jobvl == 'V' || jobvr == 'V' )\n            return std::max< std::ptrdiff_t >( 1, 6*n );\n        if ( sense == 'E' )\n            return std::max< std::ptrdiff_t >( 1, 10*n );\n        if ( sense == 'V' || sense == 'B' )\n            return 2*n*n + 8*n + 16;\n        return std::max< std::ptrdiff_t >( 1, 2*n );\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 char sense,\n            const std::ptrdiff_t n ) {\n        if ( sense == 'E' )\n          return 0;\n        else\n          return n+6;\n    }\n\n    //\n    // Static member function that returns the minimum size of\n    // workspace-array bwork.\n    //\n    static std::ptrdiff_t min_size_bwork( const char sense,\n            const std::ptrdiff_t n ) {\n        if ( sense == 'N' )\n          return 0;\n        else\n          return n;\n    }\n};\n\n//\n// This implementation is enabled if Value is a complex type.\n//\ntemplate< typename Value >\nstruct ggevx_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 MatrixB, typename VectorALPHA,\n            typename VectorBETA, typename MatrixVL, typename MatrixVR,\n            typename VectorLSCALE, typename VectorRSCALE,\n            typename VectorRCONDE, typename VectorRCONDV, typename WORK,\n            typename RWORK, typename IWORK, typename BWORK >\n    static std::ptrdiff_t invoke( const char balanc, const char jobvl,\n            const char jobvr, const char sense, MatrixA& a, MatrixB& b,\n            VectorALPHA& alpha, VectorBETA& beta, MatrixVL& vl, MatrixVR& vr,\n            fortran_int_t& ilo, fortran_int_t& ihi,\n            VectorLSCALE& lscale, VectorRSCALE& rscale, real_type& abnrm,\n            real_type& bbnrm, VectorRCONDE& rconde, VectorRCONDV& rcondv,\n            detail::workspace4< WORK, RWORK, IWORK, BWORK > 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< MatrixB >::value) );\n        BOOST_STATIC_ASSERT( (bindings::is_column_major< MatrixVL >::value) );\n        BOOST_STATIC_ASSERT( (bindings::is_column_major< MatrixVR >::value) );\n        BOOST_STATIC_ASSERT( (boost::is_same< typename remove_const<\n                typename bindings::value_type< VectorLSCALE >::type >::type,\n                typename remove_const< typename bindings::value_type<\n                VectorRSCALE >::type >::type >::value) );\n        BOOST_STATIC_ASSERT( (boost::is_same< typename remove_const<\n                typename bindings::value_type< VectorLSCALE >::type >::type,\n                typename remove_const< typename bindings::value_type<\n                VectorRCONDE >::type >::type >::value) );\n        BOOST_STATIC_ASSERT( (boost::is_same< typename remove_const<\n                typename bindings::value_type< VectorLSCALE >::type >::type,\n                typename remove_const< typename bindings::value_type<\n                VectorRCONDV >::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                MatrixB >::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                VectorALPHA >::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                VectorBETA >::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                MatrixVL >::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                MatrixVR >::type >::type >::value) );\n        BOOST_STATIC_ASSERT( (bindings::is_mutable< MatrixA >::value) );\n        BOOST_STATIC_ASSERT( (bindings::is_mutable< MatrixB >::value) );\n        BOOST_STATIC_ASSERT( (bindings::is_mutable< VectorALPHA >::value) );\n        BOOST_STATIC_ASSERT( (bindings::is_mutable< VectorBETA >::value) );\n        BOOST_STATIC_ASSERT( (bindings::is_mutable< MatrixVL >::value) );\n        BOOST_STATIC_ASSERT( (bindings::is_mutable< MatrixVR >::value) );\n        BOOST_STATIC_ASSERT( (bindings::is_mutable< VectorLSCALE >::value) );\n        BOOST_STATIC_ASSERT( (bindings::is_mutable< VectorRSCALE >::value) );\n        BOOST_STATIC_ASSERT( (bindings::is_mutable< VectorRCONDE >::value) );\n        BOOST_STATIC_ASSERT( (bindings::is_mutable< VectorRCONDV >::value) );\n        BOOST_ASSERT( bindings::size(alpha) >= bindings::size_column(a) );\n        BOOST_ASSERT( bindings::size(beta) >= bindings::size_column(a) );\n        BOOST_ASSERT( bindings::size(work.select(fortran_int_t())) >=\n                min_size_iwork( sense, bindings::size_column(a) ));\n        BOOST_ASSERT( bindings::size(work.select(fortran_bool_t())) >=\n                min_size_bwork( sense, bindings::size_column(a) ));\n        BOOST_ASSERT( bindings::size(work.select(real_type())) >=\n                min_size_rwork( balanc, bindings::size_column(a) ));\n        BOOST_ASSERT( bindings::size(work.select(value_type())) >=\n                min_size_work( sense, bindings::size_column(a) ));\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(b) == 1 ||\n                bindings::stride_minor(b) == 1 );\n        BOOST_ASSERT( bindings::size_minor(vl) == 1 ||\n                bindings::stride_minor(vl) == 1 );\n        BOOST_ASSERT( bindings::size_minor(vr) == 1 ||\n                bindings::stride_minor(vr) == 1 );\n        BOOST_ASSERT( bindings::stride_major(a) >= std::max< std::ptrdiff_t >(1,\n                bindings::size_column(a)) );\n        BOOST_ASSERT( bindings::stride_major(b) >= std::max< std::ptrdiff_t >(1,\n                bindings::size_column(a)) );\n        BOOST_ASSERT( balanc == 'N' || balanc == 'P' || balanc == 'S' ||\n                balanc == 'B' );\n        BOOST_ASSERT( jobvl == 'N' || jobvl == 'V' );\n        BOOST_ASSERT( jobvr == 'N' || jobvr == 'V' );\n        BOOST_ASSERT( sense == 'N' || sense == 'E' || sense == 'V' ||\n                sense == 'B' );\n        return detail::ggevx( balanc, jobvl, jobvr, sense,\n                bindings::size_column(a), bindings::begin_value(a),\n                bindings::stride_major(a), bindings::begin_value(b),\n                bindings::stride_major(b), bindings::begin_value(alpha),\n                bindings::begin_value(beta), bindings::begin_value(vl),\n                bindings::stride_major(vl), bindings::begin_value(vr),\n                bindings::stride_major(vr), ilo, ihi,\n                bindings::begin_value(lscale), bindings::begin_value(rscale),\n                abnrm, bbnrm, bindings::begin_value(rconde),\n                bindings::begin_value(rcondv),\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                bindings::begin_value(work.select(fortran_bool_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 MatrixB, typename VectorALPHA,\n            typename VectorBETA, typename MatrixVL, typename MatrixVR,\n            typename VectorLSCALE, typename VectorRSCALE,\n            typename VectorRCONDE, typename VectorRCONDV >\n    static std::ptrdiff_t invoke( const char balanc, const char jobvl,\n            const char jobvr, const char sense, MatrixA& a, MatrixB& b,\n            VectorALPHA& alpha, VectorBETA& beta, MatrixVL& vl, MatrixVR& vr,\n            fortran_int_t& ilo, fortran_int_t& ihi,\n            VectorLSCALE& lscale, VectorRSCALE& rscale, real_type& abnrm,\n            real_type& bbnrm, VectorRCONDE& rconde, VectorRCONDV& rcondv,\n            minimal_workspace ) {\n        namespace bindings = ::boost::numeric::bindings;\n        bindings::detail::array< value_type > tmp_work( min_size_work( sense,\n                bindings::size_column(a) ) );\n        bindings::detail::array< real_type > tmp_rwork( min_size_rwork(\n                balanc, bindings::size_column(a) ) );\n        bindings::detail::array< fortran_int_t > tmp_iwork(\n                min_size_iwork( sense, bindings::size_column(a) ) );\n        bindings::detail::array< fortran_bool_t > tmp_bwork( min_size_bwork(\n                sense, bindings::size_column(a) ) );\n        return invoke( balanc, jobvl, jobvr, sense, a, b, alpha, beta, vl, vr,\n                ilo, ihi, lscale, rscale, abnrm, bbnrm, rconde, rcondv,\n                workspace( tmp_work, tmp_rwork, tmp_iwork, tmp_bwork ) );\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 MatrixB, typename VectorALPHA,\n            typename VectorBETA, typename MatrixVL, typename MatrixVR,\n            typename VectorLSCALE, typename VectorRSCALE,\n            typename VectorRCONDE, typename VectorRCONDV >\n    static std::ptrdiff_t invoke( const char balanc, const char jobvl,\n            const char jobvr, const char sense, MatrixA& a, MatrixB& b,\n            VectorALPHA& alpha, VectorBETA& beta, MatrixVL& vl, MatrixVR& vr,\n            fortran_int_t& ilo, fortran_int_t& ihi,\n            VectorLSCALE& lscale, VectorRSCALE& rscale, real_type& abnrm,\n            real_type& bbnrm, VectorRCONDE& rconde, VectorRCONDV& rcondv,\n            optimal_workspace ) {\n        namespace bindings = ::boost::numeric::bindings;\n        value_type opt_size_work;\n        bindings::detail::array< real_type > tmp_rwork( min_size_rwork(\n                balanc, bindings::size_column(a) ) );\n        bindings::detail::array< fortran_int_t > tmp_iwork(\n                min_size_iwork( sense, bindings::size_column(a) ) );\n        bindings::detail::array< fortran_bool_t > tmp_bwork( min_size_bwork(\n                sense, bindings::size_column(a) ) );\n        detail::ggevx( balanc, jobvl, jobvr, sense,\n                bindings::size_column(a), bindings::begin_value(a),\n                bindings::stride_major(a), bindings::begin_value(b),\n                bindings::stride_major(b), bindings::begin_value(alpha),\n                bindings::begin_value(beta), bindings::begin_value(vl),\n                bindings::stride_major(vl), bindings::begin_value(vr),\n                bindings::stride_major(vr), ilo, ihi,\n                bindings::begin_value(lscale), bindings::begin_value(rscale),\n                abnrm, bbnrm, bindings::begin_value(rconde),\n                bindings::begin_value(rcondv), &opt_size_work, -1,\n                bindings::begin_value(tmp_rwork),\n                bindings::begin_value(tmp_iwork),\n                bindings::begin_value(tmp_bwork) );\n        bindings::detail::array< value_type > tmp_work(\n                traits::detail::to_int( opt_size_work ) );\n        return invoke( balanc, jobvl, jobvr, sense, a, b, alpha, beta, vl, vr,\n                ilo, ihi, lscale, rscale, abnrm, bbnrm, rconde, rcondv,\n                workspace( tmp_work, tmp_rwork, tmp_iwork, tmp_bwork ) );\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 char sense,\n            const std::ptrdiff_t n ) {\n        if ( sense == 'N' )\n            return std::max< std::ptrdiff_t >( 1, 2*n );\n        else {\n            if ( sense == 'E' )\n                return std::max< std::ptrdiff_t >( 1, 4*n );\n            else\n                return std::max< std::ptrdiff_t >( 1, 2*n*n+2*n );\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 char balanc,\n            const std::ptrdiff_t n ) {\n        if ( balanc == 'S' || balanc == 'B' )\n            return std::max< std::ptrdiff_t >( 1, 6*n );\n        else\n            return std::max< std::ptrdiff_t >( 1, 2*n );\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 char sense,\n            const std::ptrdiff_t n ) {\n        if ( sense == 'E' )\n          return 0;\n        else\n          return n+2;\n    }\n\n    //\n    // Static member function that returns the minimum size of\n    // workspace-array bwork.\n    //\n    static std::ptrdiff_t min_size_bwork( const char sense,\n            const std::ptrdiff_t n ) {\n        if ( sense == 'N' )\n          return 0;\n        else\n          return n;\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 ggevx_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 ggevx. Its overload differs for\n// * User-defined workspace\n//\ntemplate< typename MatrixA, typename MatrixB, typename VectorALPHAR,\n        typename VectorALPHAI, typename VectorBETA, typename MatrixVL,\n        typename MatrixVR, typename VectorLSCALE, typename VectorRSCALE,\n        typename VectorRCONDE, typename VectorRCONDV, typename Workspace >\ninline typename boost::enable_if< detail::is_workspace< Workspace >,\n        std::ptrdiff_t >::type\nggevx( const char balanc, const char jobvl, const char jobvr,\n        const char sense, MatrixA& a, MatrixB& b, VectorALPHAR& alphar,\n        VectorALPHAI& alphai, VectorBETA& beta, MatrixVL& vl, MatrixVR& vr,\n        fortran_int_t& ilo, fortran_int_t& ihi, VectorLSCALE& lscale,\n        VectorRSCALE& rscale, typename remove_imaginary<\n        typename bindings::value_type< MatrixA >::type >::type& abnrm,\n        typename remove_imaginary< typename bindings::value_type<\n        MatrixA >::type >::type& bbnrm, VectorRCONDE& rconde,\n        VectorRCONDV& rcondv, Workspace work ) {\n    return ggevx_impl< typename bindings::value_type<\n            MatrixA >::type >::invoke( balanc, jobvl, jobvr, sense, a, b,\n            alphar, alphai, beta, vl, vr, ilo, ihi, lscale, rscale, abnrm,\n            bbnrm, rconde, rcondv, work );\n}\n\n//\n// Overloaded function for ggevx. Its overload differs for\n// * Default workspace-type (optimal)\n//\ntemplate< typename MatrixA, typename MatrixB, typename VectorALPHAR,\n        typename VectorALPHAI, typename VectorBETA, typename MatrixVL,\n        typename MatrixVR, typename VectorLSCALE, typename VectorRSCALE,\n        typename VectorRCONDE, typename VectorRCONDV >\ninline typename boost::disable_if< detail::is_workspace< VectorRCONDV >,\n        std::ptrdiff_t >::type\nggevx( const char balanc, const char jobvl, const char jobvr,\n        const char sense, MatrixA& a, MatrixB& b, VectorALPHAR& alphar,\n        VectorALPHAI& alphai, VectorBETA& beta, MatrixVL& vl, MatrixVR& vr,\n        fortran_int_t& ilo, fortran_int_t& ihi, VectorLSCALE& lscale,\n        VectorRSCALE& rscale, typename remove_imaginary<\n        typename bindings::value_type< MatrixA >::type >::type& abnrm,\n        typename remove_imaginary< typename bindings::value_type<\n        MatrixA >::type >::type& bbnrm, VectorRCONDE& rconde,\n        VectorRCONDV& rcondv ) {\n    return ggevx_impl< typename bindings::value_type<\n            MatrixA >::type >::invoke( balanc, jobvl, jobvr, sense, a, b,\n            alphar, alphai, beta, vl, vr, ilo, ihi, lscale, rscale, abnrm,\n            bbnrm, rconde, rcondv, optimal_workspace() );\n}\n\n//\n// Overloaded function for ggevx. Its overload differs for\n// * User-defined workspace\n//\ntemplate< typename MatrixA, typename MatrixB, typename VectorALPHA,\n        typename VectorBETA, typename MatrixVL, typename MatrixVR,\n        typename VectorLSCALE, typename VectorRSCALE, typename VectorRCONDE,\n        typename VectorRCONDV, typename Workspace >\ninline typename boost::enable_if< detail::is_workspace< Workspace >,\n        std::ptrdiff_t >::type\nggevx( const char balanc, const char jobvl, const char jobvr,\n        const char sense, MatrixA& a, MatrixB& b, VectorALPHA& alpha,\n        VectorBETA& beta, MatrixVL& vl, MatrixVR& vr, fortran_int_t& ilo,\n        fortran_int_t& ihi, VectorLSCALE& lscale, VectorRSCALE& rscale,\n        typename remove_imaginary< typename bindings::value_type<\n        MatrixA >::type >::type& abnrm, typename remove_imaginary<\n        typename bindings::value_type< MatrixA >::type >::type& bbnrm,\n        VectorRCONDE& rconde, VectorRCONDV& rcondv, Workspace work ) {\n    return ggevx_impl< typename bindings::value_type<\n            MatrixA >::type >::invoke( balanc, jobvl, jobvr, sense, a, b,\n            alpha, beta, vl, vr, ilo, ihi, lscale, rscale, abnrm, bbnrm,\n            rconde, rcondv, work );\n}\n\n//\n// Overloaded function for ggevx. Its overload differs for\n// * Default workspace-type (optimal)\n//\ntemplate< typename MatrixA, typename MatrixB, typename VectorALPHA,\n        typename VectorBETA, typename MatrixVL, typename MatrixVR,\n        typename VectorLSCALE, typename VectorRSCALE, typename VectorRCONDE,\n        typename VectorRCONDV >\ninline typename boost::disable_if< detail::is_workspace< VectorRCONDV >,\n        std::ptrdiff_t >::type\nggevx( const char balanc, const char jobvl, const char jobvr,\n        const char sense, MatrixA& a, MatrixB& b, VectorALPHA& alpha,\n        VectorBETA& beta, MatrixVL& vl, MatrixVR& vr, fortran_int_t& ilo,\n        fortran_int_t& ihi, VectorLSCALE& lscale, VectorRSCALE& rscale,\n        typename remove_imaginary< typename bindings::value_type<\n        MatrixA >::type >::type& abnrm, typename remove_imaginary<\n        typename bindings::value_type< MatrixA >::type >::type& bbnrm,\n        VectorRCONDE& rconde, VectorRCONDV& rcondv ) {\n    return ggevx_impl< typename bindings::value_type<\n            MatrixA >::type >::invoke( balanc, jobvl, jobvr, sense, a, b,\n            alpha, beta, vl, vr, ilo, ihi, lscale, rscale, abnrm, bbnrm,\n            rconde, rcondv, optimal_workspace() );\n}\n\n} // namespace lapack\n} // namespace bindings\n} // namespace numeric\n} // namespace boost\n\n#endif\n", "meta": {"hexsha": "54eeed0697e59cff7f8aeb330975cca826975819", "size": 38339, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "externals/numeric_bindings/boost/numeric/bindings/lapack/driver/ggevx.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/ggevx.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/ggevx.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": 50.6459709379, "max_line_length": 84, "alphanum_fraction": 0.6372884008, "num_tokens": 9586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.6224593452091672, "lm_q1q2_score": 0.45120227747061453}}
{"text": "//==============================================================================\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#include <nt2/exponential/include/functions/nthroot.hpp>\n\n#include <nt2/sdk/functor/meta/call.hpp>\n#include <boost/simd/sdk/simd/native.hpp>\n#include <nt2/sdk/unit/tests/type_expr.hpp>\n#include <nt2/sdk/unit/tests/ulp.hpp>\n#include <nt2/include/functions/splat.hpp>\n#include <nt2/sdk/unit/module.hpp>\n#include <boost/simd/sdk/config.hpp>\n#include <boost/simd/sdk/simd/io.hpp>\n\n#include <nt2/include/constants/mone.hpp>\n#include <nt2/include/constants/one.hpp>\n#include <nt2/include/constants/zero.hpp>\n#include <nt2/include/constants/inf.hpp>\n#include <nt2/include/constants/minf.hpp>\n#include <nt2/include/constants/nan.hpp>\n#include <nt2/include/constants/half.hpp>\n\nNT2_TEST_CASE_TPL ( nthroot,  NT2_SIMD_REAL_TYPES)\n{\n  using nt2::nthroot;\n  using nt2::tag::nthroot_;\n  using boost::simd::native;\n  typedef BOOST_SIMD_DEFAULT_EXTENSION  ext_t;\n  typedef native<T,ext_t>                  vT;\n  typedef typename nt2::meta::as_integer<vT>::type          ivT;\n  typedef typename nt2::meta::call<nthroot_(vT,ivT)>::type r_t;\n  typedef vT wished_r_t;\n\n  // return type conformity test\n  NT2_TEST_TYPE_IS(r_t, wished_r_t);\n\n\n  // specific values tests\n#ifndef BOOST_SIMD_NO_INVALIDS\n  NT2_TEST_ULP_EQUAL(nthroot(nt2::Inf<vT>(),nt2::splat<ivT>(3)), nt2::Inf<r_t>(), 0.5);\n  NT2_TEST_ULP_EQUAL(nthroot(nt2::Inf<vT>(),nt2::splat<ivT>(4)), nt2::Inf<r_t>(), 0.5);\n  NT2_TEST_ULP_EQUAL(nthroot(nt2::Minf<vT>(),nt2::splat<ivT>(3)), nt2::Minf<r_t>(), 0.5);\n   NT2_TEST_ULP_EQUAL(nthroot(nt2::Minf<vT>(),nt2::splat<ivT>(4)), nt2::Nan<r_t>(), 0.5);\n  NT2_TEST_ULP_EQUAL(nthroot(nt2::Nan<vT>(),nt2::splat<ivT>(3)), nt2::Nan<r_t>(), 0.5);\n  NT2_TEST_ULP_EQUAL(nthroot(nt2::Nan<vT>(),nt2::splat<ivT>(4)), nt2::Nan<r_t>(), 0.5);\n  NT2_TEST_ULP_EQUAL(nthroot(nt2::Mone<vT>(),nt2::splat<ivT>(4)), nt2::Nan<r_t>(), 0.5);\n#endif\n  NT2_TEST_ULP_EQUAL(nthroot(nt2::Mone<vT>(),nt2::splat<ivT>(0)), nt2::Nan<r_t>(), 0.5);\n  NT2_TEST_ULP_EQUAL(nthroot(nt2::One <vT>(),nt2::splat<ivT>(0)), nt2::One<r_t>(), 0.5);\n  NT2_TEST_ULP_EQUAL(nthroot(nt2::Half<vT>(),nt2::splat<ivT>(0)), nt2::Zero<r_t>(), 0.5);\n  NT2_TEST_ULP_EQUAL(nthroot(nt2::Two <vT>(),nt2::splat<ivT>(0)), nt2::Inf <r_t>(), 0.5);\n  NT2_TEST_ULP_EQUAL(nthroot(nt2::Zero<vT>(),nt2::splat<ivT>(0)), nt2::Zero<r_t>(), 0.5);\n  NT2_TEST_ULP_EQUAL(nthroot(nt2::Mone<vT>(),nt2::splat<ivT>(3)), nt2::Mone<r_t>(), 0.5);\n  NT2_TEST_ULP_EQUAL(nthroot(nt2::One<vT>(),nt2::splat<ivT>(3)), nt2::One<r_t>(), 0.5);\n  NT2_TEST_ULP_EQUAL(nthroot(nt2::One<vT>(),nt2::splat<ivT>(4)), nt2::One<r_t>(), 0.5);\n  NT2_TEST_ULP_EQUAL(nthroot(nt2::Zero<vT>(),nt2::splat<ivT>(3)), nt2::Zero<r_t>(), 0.5);\n  NT2_TEST_ULP_EQUAL(nthroot(nt2::Zero<vT>(),nt2::splat<ivT>(4)), nt2::Zero<r_t>(), 0.5);\n  NT2_TEST_ULP_EQUAL(nthroot(nt2::splat<vT>(-8),nt2::splat<ivT>(3)), nt2::splat<r_t>(-2), 0.5);\n  NT2_TEST_ULP_EQUAL(nthroot(nt2::splat<vT>(256),nt2::splat<ivT>(4)), nt2::splat<r_t>(4), 0.5);\n  NT2_TEST_ULP_EQUAL(nthroot(nt2::splat<vT>(8),nt2::splat<ivT>(3)), nt2::splat<r_t>(2), 0.5);\n}\n\n\n", "meta": {"hexsha": "aa3a0322ee9ad29b557c65356d107bc3cd3724e0", "size": 3426, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/core/exponential/unit/simd/nthroot.cpp", "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/exponential/unit/simd/nthroot.cpp", "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/exponential/unit/simd/nthroot.cpp", "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": 50.3823529412, "max_line_length": 95, "alphanum_fraction": 0.6418563923, "num_tokens": 1233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702880639791, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4512022747164001}}
{"text": "#ifndef TRIUMF_NMR_SPECTRAL_DENSITY_HPP\n#define TRIUMF_NMR_SPECTRAL_DENSITY_HPP\n\n// Author: Ryan M. L. McFadden\n// NMR spectral density functions for spin-lattice relaxation in solids.\n//\n// For additional details see:\n//\n// N. Bloembergen, E. M. Purcell, and R. V. Pound, \"Relaxation Effects in\n// Nuclear Magnetic Resonance Absorption\", Phys. Rev. 73, 679-712 (1948).\n// https://dx.doi.org/10.1103/PhysRev.73.679\n//\n// P. M. Richards, \"Effect of low dimensionality on prefactor anomalies in\n// superionic conductors\", Solid State Commun. 25, 1019-1021 (1978).\n// https://dx.doi.org/10.1016/0038-1098(78)90896-7\n//\n// C. A Sholl, \"Nuclear spin relaxation by translational diffusion in liquids\n// and solids: high- and low-frequency limits\", J. Phys. C.: Solid State Phys.\n// 14, 447-464 (1981). https://dx.doi.org/10.1088/0022-3719/14/4/018\n//\n// P. A. Beckmann, \"Spectral densities and nuclear spin relaxation in solids\",\n// Phys. Rep. 171, 85-128 (1988).\n// https://dx.doi.org/10.1016/0370-1573(88)90073-7\n//\n// W. K\u00fcchler, P. Heitjans, A. Payer, and R. Sch\u00f6llhorn, \"7Li NMR relaxation by\n// diffusion in hexagonal and cubic LixTiS2\". Solid State Ionics 70-71, Part 1,\n// 434-438 (1994). https://dx.doi.org/10.1016/0167-2738(94)90350-6\n//\n\n#include <cmath>\n#include <iostream>\n\n#include <boost/math/constants/constants.hpp>\n\n#include <triumf/constants/codata_2018.hpp>\n\n// TRIUMF: Canada's particle accelerator centre\nnamespace triumf {\n\n// Nuclear Magnetic Resonance (NMR)\nnamespace nmr {\n\n// Arrhenius correlation time\ntemplate <typename T = double>\nT tau_c(T temperature, T prefactor, T activation_energy) {\n  constexpr T boltzmann_constant =\n      triumf::constants::codata_2018::Boltzmann_constant_in_eV_K<T>::value();\n  if (temperature <= 0.0 or prefactor <= 0.0 or activation_energy < 0.0) {\n    return 0.0;\n  } else {\n    return prefactor *\n           std::exp(activation_energy / (boltzmann_constant * temperature));\n  }\n}\n\n// Arrhenius correlation rate\ntemplate <typename T = double>\nT nu_c(T temperature, T prefactor, T activation_energy) {\n  constexpr T boltzmann_constant =\n      triumf::constants::codata_2018::Boltzmann_constant_in_eV_K<T>::value();\n  if (temperature <= 0.0 or prefactor <= 0.0 or activation_energy < 0.0) {\n    return 0.0;\n  } else {\n    return prefactor *\n           std::exp(-activation_energy / (boltzmann_constant * temperature));\n  }\n}\n\n// Bloembergen-Purcell-Pound (i.e., Debye) - isotropic 3D fluctuations\ntemplate <typename T = double>\nT j_3d(T correlation_time, T nmr_frequency, T interaction_strength,\n       T stretching_exponent) {\n  if (correlation_time < 0 or nmr_frequency < 0 or interaction_strength <= 0) {\n    return 0.0;\n  }\n  if (stretching_exponent > 2 or stretching_exponent < 1) {\n    std::cout << \"WARNING : stretching exponent outside of bounds : [1, 2]\"\n              << std::endl;\n    return 0.0;\n  }\n  return interaction_strength * 2.0 * correlation_time /\n         (1.0 +\n          std::pow(nmr_frequency * correlation_time, stretching_exponent));\n}\n\n// Richards - empirocal function for 2D fluctuations that gives correct\n// asymptotic limits\ntemplate <typename T = double>\nT j_2d(T correlation_time, T nmr_frequency, T interaction_strength,\n       T stretching_exponent) {\n  if (correlation_time < 0 or nmr_frequency < 0 or interaction_strength <= 0) {\n    return 0.0;\n  }\n  if (stretching_exponent > 2 or stretching_exponent < 1) {\n    std::cout << \"WARNING : stretching exponent outside of bounds : [1, 2]\"\n              << std::endl;\n    return 0.0;\n  }\n  return interaction_strength * correlation_time *\n         std::log1p(\n             std::pow(nmr_frequency * correlation_time, -stretching_exponent));\n}\n\n// Cole-Cole - correlated motion (j_cc -> j_bpp as stretching_exponent -> 1)\ntemplate <typename T = double>\nT j_cc(T correlation_time, T nmr_frequency, T interaction_strength,\n       T stretching_exponent) {\n  if (correlation_time < 0 or nmr_frequency < 0 or interaction_strength <= 0) {\n    return 0.0;\n  }\n  if (stretching_exponent > 1 or stretching_exponent <= 0) {\n    std::cout << \"WARNING : stretching exponent outside of bounds : (0, 1]\"\n              << std::endl;\n    return 0.0;\n  }\n  return interaction_strength * (2.0 / nmr_frequency) *\n         std::sin(stretching_exponent * boost::math::constants::pi<T>() / 2.0) *\n         (std::pow(nmr_frequency * correlation_time, stretching_exponent) /\n          (1.0 +\n           std::pow(nmr_frequency * correlation_time,\n                    2.0 * stretching_exponent) +\n           2.0 *\n               std::cos(stretching_exponent * boost::math::constants::pi<T>() /\n                        2.0) *\n               std::pow(nmr_frequency * correlation_time,\n                        stretching_exponent)));\n}\n\n// Davidson-Cole - distribution of barriers (j_dc -> j_bpp as\n// stretching_exponent -> 1)\ntemplate <typename T = double>\nT j_dc(T correlation_time, T nmr_frequency, T interaction_strength,\n       T stretching_exponent) {\n  if (correlation_time < 0 or nmr_frequency < 0 or interaction_strength <= 0) {\n    return 0.0;\n  }\n  if (stretching_exponent > 1 or stretching_exponent <= 0) {\n    std::cout << \"WARNING : stretching exponent outside of bounds : (0, 1]\"\n              << std::endl;\n    return 0.0;\n  }\n  return interaction_strength * (2.0 / nmr_frequency) *\n         std::sin(stretching_exponent *\n                  std::atan(nmr_frequency * correlation_time)) /\n         std::pow(1.0 + nmr_frequency * nmr_frequency * correlation_time *\n                            correlation_time,\n                  stretching_exponent / 2.0);\n}\n\n// Fang - mirror image of Davidson-Cole\ntemplate <typename T = double>\nT j_fang(T correlation_time, T nmr_frequency, T interaction_strength,\n         T stretching_exponent) {\n  if (correlation_time < 0 or nmr_frequency < 0 or interaction_strength <= 0) {\n    return 0.0;\n  }\n  if (stretching_exponent > 1 or stretching_exponent <= 0) {\n    std::cout << \"WARNING : stretching exponent outside of bounds : (0, 1]\"\n              << std::endl;\n    return 0.0;\n  }\n  return interaction_strength * (2.0 / nmr_frequency) *\n         std::pow(nmr_frequency * correlation_time, stretching_exponent) *\n         std::sin(stretching_exponent *\n                  std::atan(1.0 / (nmr_frequency * correlation_time))) /\n         std::pow(1.0 + std::pow(nmr_frequency * correlation_time, 2.0),\n                  stretching_exponent / 2.0);\n}\n\n// Fuoss-Kirkwood - distribution of correlation times\ntemplate <typename T = double>\nT j_fk(T correlation_time, T nmr_frequency, T interaction_strength,\n       T stretching_exponent) {\n  if (correlation_time < 0 or nmr_frequency < 0 or interaction_strength <= 0) {\n    return 0.0;\n  }\n  if (stretching_exponent > 1 or stretching_exponent <= 0) {\n    std::cout << \"WARNING : stretching exponent outside of bounds : (0, 1]\"\n              << std::endl;\n    return 0.0;\n  }\n  return interaction_strength * (2.0 * stretching_exponent / nmr_frequency) *\n         std::pow(nmr_frequency * correlation_time, stretching_exponent) /\n         (1.0 + std::pow(nmr_frequency * correlation_time,\n                         2.0 * stretching_exponent));\n}\n\n// Havriliak-Negami - correlated motion w/ distribution of barriers\n// - delta ~ measure of correlations\n// - delta*epsilon ~ measure of a spread in barriers\ntemplate <typename T = double>\nT j_hn(T correlation_time, T nmr_frequency, T interaction_strength, T delta,\n       T epsilon) {\n  if (correlation_time < 0 or nmr_frequency < 0 or interaction_strength <= 0) {\n    return 0.0;\n  }\n  if (delta > 1 or delta <= 0 or epsilon > 1.0 / delta or epsilon <= 0) {\n    std::cout << \"WARNING : stretching exponents outside of bounds : delta -> \"\n                 \"(0, 1]\\n\";\n    std::cout << \"                                                   epsilon \"\n                 \"-> (0, 1/delta]\"\n              << std::endl;\n    return 0.0;\n  }\n  return interaction_strength * (2.0 / nmr_frequency) *\n         (std::sin(\n             epsilon *\n             std::atan(\n                 (std::pow(nmr_frequency * correlation_time, delta) *\n                  std::sin(delta * boost::math::constants::pi<T>() / 2.0)) /\n                 (1.0 + std::pow(nmr_frequency * correlation_time, delta) *\n                            std::cos(delta * boost::math::constants::pi<T>() /\n                                     2.0))))) *\n         std::pow(\n             1.0 +\n                 2.0 * std::pow(nmr_frequency * correlation_time, delta) *\n                     std::cos(delta * boost::math::constants::pi<T>() / 2.0) +\n                 std::pow(nmr_frequency * correlation_time, 2.0 * delta),\n             -epsilon / 2.0);\n}\n\n// Bryn-Mawr\n// double j_bm(double correlation_time, double nmr_frequency, double\n// interaction_strength = 1, double epsilon = 1, double eta = 1);\n\n// Wagner (i.e., log-Gaussian)\n// double j_lg(double correlation_time, double nmr_frequency, double\n// interaction_strength = 1, double width = 1);\n\n// log-Lorentzian\n// double j_ll(double correlation_time, double nmr_frequency, double\n// interaction_strength = 1, double width = 1);\n\n// Frolich (i.e., energy box)\n// double j_eb(double correlation_time, double nmr_frequency, double\n// interaction_strength = 1, ...);\n\n// Power law : power = 1 (e.g., Korringa); power = 2 (e.g., phonon); power = 3\n// (e.g., [Dirac] orbital)\ntemplate <typename T = double>\nT j_pow(T temperature, T intercept, T constant, T power) {\n  if (temperature <= 0.0) {\n    return 0.0;\n  }\n  if (constant == 0.0) {\n    return intercept;\n  }\n  return intercept + constant * std::pow(temperature, power);\n}\n\n} // namespace nmr\n\n} // namespace triumf\n\n#endif // TRIUMF_NMR_SPECTRAL_DENSITY_HPP\n", "meta": {"hexsha": "08188b38f5327794acd1708a1a154936071a391a", "size": 9662, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/triumf/nmr/spectral_density.hpp", "max_stars_repo_name": "rmlmcfadden/triumfpp", "max_stars_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_stars_repo_licenses": ["MIT"], "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/triumf/nmr/spectral_density.hpp", "max_issues_repo_name": "rmlmcfadden/triumfpp", "max_issues_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_issues_repo_licenses": ["MIT"], "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/triumf/nmr/spectral_density.hpp", "max_forks_repo_name": "rmlmcfadden/triumfpp", "max_forks_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_forks_repo_licenses": ["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.7421875, "max_line_length": 80, "alphanum_fraction": 0.642413579, "num_tokens": 2672, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702880639791, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4512022747164001}}
{"text": "#ifndef STAN_MATH_PRIM_MAT_FUN_QUAD_FORM_DIAG_HPP\n#define STAN_MATH_PRIM_MAT_FUN_QUAD_FORM_DIAG_HPP\n\n#include <stan/math/prim/mat/fun/Eigen.hpp>\n#include <boost/math/tools/promotion.hpp>\n#include <stan/math/prim/mat/err/check_square.hpp>\n#include <stan/math/prim/mat/err/check_vector.hpp>\n#include <stan/math/prim/scal/err/check_size_match.hpp>\n\nnamespace stan {\nnamespace math {\n\ntemplate <typename T1, typename T2, int R, int C>\ninline Eigen::Matrix<typename boost::math::tools::promote_args<T1, T2>::type,\n                     Eigen::Dynamic, Eigen::Dynamic>\nquad_form_diag(const Eigen::Matrix<T1, Eigen::Dynamic, Eigen::Dynamic>& mat,\n               const Eigen::Matrix<T2, R, C>& vec) {\n  check_vector(\"quad_form_diag\", \"vec\", vec);\n  check_square(\"quad_form_diag\", \"mat\", mat);\n  check_size_match(\"quad_form_diag\", \"rows of mat\", mat.rows(), \"size of vec\",\n                   vec.size());\n  return vec.asDiagonal() * mat * vec.asDiagonal();\n}\n\n}  // namespace math\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "0f21b1eda7c6a9b1bba9e05004febac571103c46", "size": 999, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "venv/lib/python3.7/site-packages/pystan/stan/lib/stan_math/stan/math/prim/mat/fun/quad_form_diag.hpp", "max_stars_repo_name": "vchiapaikeo/prophet", "max_stars_repo_head_hexsha": "e8c250ca7bfffc280baa7dabc80a2c2d1f72c6a7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-07-23T14:57:41.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-23T14:57:41.000Z", "max_issues_repo_path": "venv/lib/python3.7/site-packages/pystan/stan/lib/stan_math/stan/math/prim/mat/fun/quad_form_diag.hpp", "max_issues_repo_name": "vchiapaikeo/prophet", "max_issues_repo_head_hexsha": "e8c250ca7bfffc280baa7dabc80a2c2d1f72c6a7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-09-23T19:58:36.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-24T12:03:41.000Z", "max_forks_repo_path": "stan/math/prim/mat/fun/quad_form_diag.hpp", "max_forks_repo_name": "riddell-stan/math", "max_forks_repo_head_hexsha": "d84ee0d991400d6cf4b08a07a4e8d86e0651baea", "max_forks_repo_licenses": ["BSD-3-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.6785714286, "max_line_length": 78, "alphanum_fraction": 0.7047047047, "num_tokens": 261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.45120226731713}}
{"text": "//    $Id: block_matrix_array.cc 27657 2012-11-21 13:19:08Z bangerth $\n//\n//    Copyright (C) 2005-2006, 2012 by the deal.II authors\n//\n//    This file is subject to QPL and may not be distributed without copyright\n//    and license information. Please refer to the file\n//    deal.II/doc/license.html for the text and further information on this\n//    license.\n//\n//---------------------------------------------------------------------------\n\n// See documentation of BlockMatrixArray for documentation of this example\n\n#include <deal.II/base/logstream.h>\n#include <deal.II/lac/block_matrix_array.h>\n#include <deal.II/lac/full_matrix.h>\n#include <deal.II/lac/vector.h>\n#include <deal.II/lac/block_vector.h>\n#include <deal.II/lac/precondition.h>\n#include <deal.II/lac/solver_cg.h>\n#include <deal.II/lac/solver_gmres.h>\n\n#include <iostream>\n#include <fstream>\n\nusing namespace dealii;\n\ndouble Adata[] =\n{\n  4., .5, .1, 0.,\n  .5, 4., .5, .1,\n  .1, .5, 4., .5,\n  0., .1, .5, 4.\n};\n\ndouble B1data[] =\n{\n  .5, .1,\n  .4, .2,\n  .3, .3,\n  .2, .4\n};\n\ndouble B2data[] =\n{\n  .3, 0., -.3, 0.,\n  -.3, 0., .3, 0.\n};\n\ndouble Cdata[] =\n{\n  8., 1.,\n  1., 8.\n};\n\nint main ()\n{\n  FullMatrix<float> A(4,4);\n  FullMatrix<float> B1(4,2);\n  FullMatrix<float> B2(2,4);\n  FullMatrix<float> C(2,2);\n\n  A.fill(Adata);\n  B1.fill(B1data);\n  B2.fill(B2data);\n  C.fill(Cdata);\n\n  GrowingVectorMemory<Vector<double> > simple_mem;\n\n  BlockMatrixArray<double> matrix(2, 2, simple_mem);\n\n  matrix.enter(A,0,0,2.);\n  matrix.enter(B1,0,1,-1.);\n  matrix.enter(B2,0,1,1., true);\n  matrix.enter(B2,1,0,1.);\n  matrix.enter(B1,1,0,-1., true);\n  matrix.enter(C,1,1);\n  matrix.print_latex(deallog);\n\n  std::vector<unsigned int> block_sizes(2);\n  block_sizes[0] = 4;\n  block_sizes[1] = 2;\n\n  BlockVector<double> result(block_sizes);\n  BlockVector<double> x(block_sizes);\n  BlockVector<double> y(block_sizes);\n  for (unsigned int i=0; i<result.size(); ++i)\n    result(i) = i;\n\n  matrix.vmult(y, result);\n\n  SolverControl control(100,1.e-10);\n  GrowingVectorMemory<BlockVector<double> > mem;\n  PreconditionIdentity id;\n\n  SolverCG<BlockVector<double> > cg(control, mem);\n  cg.solve(matrix, x, y, id);\n  x.add(-1., result);\n  deallog << \"Error \" << x.l2_norm() << std::endl;\n\n  deallog << \"Error A-norm \"\n          << std::sqrt(matrix.matrix_norm_square(x))\n          << std::endl;\n\n  FullMatrix<float> Ainv(4,4);\n  Ainv.invert(A);\n  FullMatrix<float> Cinv(2,2);\n  Cinv.invert(C);\n\n  BlockTrianglePrecondition<double>\n  precondition(2, simple_mem);\n  precondition.enter(Ainv,0,0,.5);\n  precondition.enter(Cinv,1,1);\n\n  cg.solve(matrix, x, y, precondition);\n  x.add(-1., result);\n  deallog << \"Error \" << x.l2_norm() << std::endl;\n\n  precondition.enter(B1,1,0,-1., true);\n  precondition.enter(B2,1,0,1.);\n\n  SolverGMRES<BlockVector<double> > gmres(control, mem);\n  gmres.solve(matrix, x, y, precondition);\n  x.add(-1., result);\n  deallog << \"Error \" << x.l2_norm() << std::endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "51922034dbb3ef298dacd1e834a50b36703b16f2", "size": 2944, "ext": "cc", "lang": "C++", "max_stars_repo_path": "MHD/examples/doxygen/block_matrix_array.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/doxygen/block_matrix_array.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/doxygen/block_matrix_array.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": 22.8217054264, "max_line_length": 78, "alphanum_fraction": 0.6256793478, "num_tokens": 955, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.45120226731713}}
{"text": "/**\n * @file EigenMathUtil.hpp\n * @author Adam Li (adamli@umich.edu)\n * @date 2021-11-12\n * \n * @brief Includes a variety of utility functions for Eigen objects of the same type.\n * \n */\n\n#include <Eigen/Core>\n\nnamespace sel_map::core::EigenMathUtil {\n    \n    template <typename Derived1, typename Derived2>\n    inline double crossProduct2D(const Eigen::EigenBase<Derived1>& x, const Eigen::EigenBase<Derived2>& y){\n        return x.derived()(0)*y.derived()(1) - x.derived()(1)*y.derived()(0);\n    }\n\n    // Convert boolean masks to a sequence usable for slicing vectors\n    template <typename Derived>\n    inline std::vector<unsigned int>& seqLogical(const Eigen::ArrayBase<Derived>& mask, std::vector<unsigned int>& sequence){\n        if (mask.cols() != 1) throw std::invalid_argument(\"Mask should be single dim column array!\");\n        \n        // Create the result\n        // std::vector<unsigned int> sequence;\n        sequence.clear();\n        sequence.resize(mask.count());\n\n        unsigned int accumulator = 0;\n        auto itr = sequence.begin();\n\n        for (auto val : mask){\n            if(val) *(itr++) = (accumulator);\n            ++accumulator;\n        }\n\n        // Make a sequence\n        // Eigen::Array<unsigned int, Eigen::Dynamic, 1>::Map(&sequence[0], sequence.size())\n        //      = mask.template cast<bool>().template cast<unsigned int>() * Eigen::Array<unsigned int, Eigen::Dynamic, 1>::LinSpaced(mask.rows(), 1, mask.rows());\n        \n        // // remove the 0's\n        // auto seq_end = std::remove(sequence.begin(), sequence.end(), 0);\n\n        // // Isolate the actual values\n        // sequence.resize(seq_end - sequence.begin());\n        \n        // // Subtract 1 to make it valid\n        // Eigen::Array<unsigned int, Eigen::Dynamic, 1>::Map(&sequence[0], sequence.size()) -= 1;\n\n        return sequence;\n    }\n}", "meta": {"hexsha": "9320820afe00fff583ef20e937b79f286cf49279", "size": 1852, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sel_map_mesh/include/core/EigenMathUtil.hpp", "max_stars_repo_name": "roahmlab/sel_map", "max_stars_repo_head_hexsha": "51c5ac738eb7475f409f826c0d30f555f98757b3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2022-02-24T21:10:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T20:00:09.000Z", "max_issues_repo_path": "sel_map_mesh/include/core/EigenMathUtil.hpp", "max_issues_repo_name": "roahmlab/sel_map", "max_issues_repo_head_hexsha": "51c5ac738eb7475f409f826c0d30f555f98757b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sel_map_mesh/include/core/EigenMathUtil.hpp", "max_forks_repo_name": "roahmlab/sel_map", "max_forks_repo_head_hexsha": "51c5ac738eb7475f409f826c0d30f555f98757b3", "max_forks_repo_licenses": ["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.6153846154, "max_line_length": 163, "alphanum_fraction": 0.6058315335, "num_tokens": 442, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.45120226731713}}
{"text": "/* Boost example/rational.cpp\r\n * example program of how to use interval< rational<> >\r\n *\r\n * Copyright Sylvain Pion, Guillaume Melquiond 2002-2003\r\n * Permission to use, copy, modify, sell, and distribute this software\r\n * is hereby granted without fee provided that the above copyright notice\r\n * appears in all copies and that both that copyright notice and this\r\n * permission notice appear in supporting documentation.\r\n *\r\n * None of the above authors make any representation about the\r\n * suitability of this software for any purpose. It is provided \"as\r\n * is\" without express or implied warranty.\r\n *\r\n * $Id: rational.cpp,v 1.2 2003/02/05 17:34:35 gmelquio Exp $\r\n */\r\n\r\n// it would have been enough to only include:\r\n//   <boost/numeric/interval.hpp>\r\n// but it's a bit overkill to include processor intrinsics\r\n// and transcendental functions, so we do it by ourselves\r\n\r\n#include <boost/numeric/interval/interval.hpp>      // base class\r\n#include <boost/numeric/interval/rounded_arith.hpp> // default arithmetic rounding policy\r\n#include <boost/numeric/interval/checking.hpp>      // default checking policy\r\n#include <boost/numeric/interval/arith.hpp>         // += *= -= etc\r\n#include <boost/numeric/interval/policies.hpp>      // default policy\r\n\r\n#include <boost/rational.hpp>\r\n#include <iostream>\r\n\r\ntypedef boost::rational<int> Rat;\r\ntypedef boost::numeric::interval<Rat> Interval;\r\n\r\nstd::ostream& operator<<(std::ostream& os, const Interval& r) {\r\n  os << \"[\" << r.lower() << \",\" << r.upper() << \"]\";\r\n  return os;\r\n}\r\n\r\nint main() {\r\n  Rat p(2, 3), q(3, 4);\r\n  Interval z(4, 5);\r\n  Interval a(p, q);\r\n  a += z;\r\n  z *= q;\r\n  a -= p;\r\n  a /= q;\r\n  std::cout << z << std::endl;\r\n  std::cout << a << std::endl;\r\n}\r\n", "meta": {"hexsha": "72fa7eb272d70befbb938d6038caf6d75bb230a0", "size": 1735, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sdk/boost_1_30_0/libs/numeric/interval/examples/rational.cpp", "max_stars_repo_name": "acidicMercury8/xray-1.0", "max_stars_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-01-30T12:51:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-31T08:36:49.000Z", "max_issues_repo_path": "sdk/boost_1_30_0/libs/numeric/interval/examples/rational.cpp", "max_issues_repo_name": "acidicMercury8/xray-1.0", "max_issues_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_issues_repo_licenses": ["Linux-OpenIB"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sdk/boost_1_30_0/libs/numeric/interval/examples/rational.cpp", "max_forks_repo_name": "acidicMercury8/xray-1.0", "max_forks_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7, "max_line_length": 90, "alphanum_fraction": 0.669740634, "num_tokens": 443, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.72487026428967, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.4512022599178595}}
{"text": "///////////////////////////////////////////////////////////////\n//  Copyright 2012 John Maddock. Distributed under the Boost\n//  Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_\n\n#ifdef _MSC_VER\n#  define _SCL_SECURE_NO_WARNINGS\n#endif\n\n#include <boost/multiprecision/cpp_bin_float.hpp>\n\n#include \"libs/multiprecision/test/test_arithmetic.hpp\"\n\ntemplate <unsigned D>\nstruct related_type<boost::multiprecision::number< boost::multiprecision::cpp_bin_float<D> > >\n{\n   typedef boost::multiprecision::number< boost::multiprecision::cpp_bin_float<(D / 2 > std::numeric_limits<long double>::digits10 ? D / 2 : D)> > type;\n};\n\nint main()\n{\n   //test<boost::multiprecision::cpp_bin_float_50>();\n   //test<boost::multiprecision::number<boost::multiprecision::cpp_bin_float<1000, boost::multiprecision::digit_base_10, std::allocator<void> > > >();\n   test<boost::multiprecision::cpp_bin_float_quad>();\n   return boost::report_errors();\n}\n\n", "meta": {"hexsha": "ac86da6d33ec8bcaa49249f0b4e721c06de5c8dd", "size": 998, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/multiprecision/test/test_arithmetic_cpp_bin_float_3.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/multiprecision/test/test_arithmetic_cpp_bin_float_3.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/multiprecision/test/test_arithmetic_cpp_bin_float_3.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": 35.6428571429, "max_line_length": 152, "alphanum_fraction": 0.7004008016, "num_tokens": 243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.4511970392052242}}
{"text": "#include \"RayTracingOpenMP.h\"\n\n#include <boost/math/constants/constants.hpp>\n\n#include \"Camera.h\"\n#include \"KdTree.h\"\n\nnamespace math = boost::math::constants;\n\nconst Color BACKGROUND_COLOR(0, 0, 0);\n\nRayTracingOpenMP::RayTracingOpenMP() {\n    lights = new Light[20];\n    Ia = Color(0.2, 0.2, 0.2);\n}\n\nRayTracingOpenMP::~RayTracingOpenMP() {\n    delete[] data;\n}\n\nImage RayTracingOpenMP::render() {\n    Light light(Point(0, 0, -1), Color(1, 1, 1), Color(1, 1, 1));\n    lights[0] = light;\n    numberOfLights = 1;\n\n    Resolution resolution = Resolution(width, height);\n    Camera camera(Point(0, 0, -1), Point(0, math::pi<float>(), 0),\n                  math::pi<float>() / 2, resolution, 1);\n#pragma omp parallel for\n    for (int y = 0; y < height; ++y) {\n        for (int x = 0; x < width; ++x) {\n            Vector vector = camera.getPrimaryVector(x, y);\n            Color color = trace(vector, 0);\n            camera.update(x, y, color);\n        }\n    }\n\n    data = new Color[width * height];\n#pragma omp parallel for\n    for (int y = 0; y < resolution.height; ++y) {\n        for (int x = 0; x < resolution.width; ++x) {\n            data[width * y + x] = camera.getPixelColor(x, y);\n        }\n    }\n    return Image(resolution.width, resolution.height, data);\n}\n\nColor RayTracingOpenMP::trace(Vector vector, int depth, int ignoredTriangle, float weight) {\n    if (depth > MAX_DEPTH || weight < MINIMUM_WEIGHT) {\n        return BACKGROUND_COLOR;\n    }\n\n    int triangleIndex = kdTree->getNearestTriangle(vector, ignoredTriangle);\n    if (triangleIndex == -1) {\n        return BACKGROUND_COLOR;\n    }\n\n    Triangle &triangle = scene->getTriangles()[triangleIndex];\n    Vector reflectionVector = triangle.getReflectedVector(vector);\n    reflectionVector.normalize();\n\n    Point reflectionPoint = reflectionVector.startPoint;\n\n    Vector normal = scene->getTriangles()[triangleIndex].getNormal();\n\n    Material material = scene->getMaterial((scene->getTriangles()[triangleIndex]).materialCode);\n\n    Vector toViewer = vector.mul(-1);\n    Color refractionColor(0, 0, 0);\n    Color reflectionColor = Ia * material.ambient;\n    float refractivity = 0;\n\n    if (material.dissolve < FULLY_OPAQUE_RATIO) {\n        float ior = material.refractiveIndex;\n        float reflectivity = fresnel(vector, normal, ior);\n        refractivity = (1 - reflectivity) * (1 - material.dissolve);\n        Vector refractionVector = refract(vector, triangle.getNormal(), ior);\n\n        refractionVector.startPoint = reflectionPoint;\n        refractionColor =\n                trace(refractionVector, depth + 1, triangleIndex, weight * refractivity) *\n                material.transparent;\n    }\n\n    if (material.dissolve > FULLY_TRANSPARENT_RATIO) {\n        for (int light = 0; light < numberOfLights; ++light) {\n            Vector toLight = Vector(reflectionPoint, lights[light].point);\n            toLight.normalize();\n\n            // Check if the light is blocked out\n            if (normal.isObtuse(toLight)) {\n                continue;\n            }\n\n            // Cast shadow ray, take refraction into account (simplified version)\n            float intensity = 1;\n            float dist = 0;\n            float lightDistance = lights[light].point.getDist(reflectionPoint);\n            int lightTriangleIndex = triangleIndex;\n            for (int lightDepth = depth;\n                 lightDepth < MAX_DEPTH && intensity > 0.01f; ++lightDepth) {\n                lightTriangleIndex = kdTree->getNearestTriangle(toLight, lightTriangleIndex);\n\n                if (lightTriangleIndex == -1) {\n                    break;\n                }\n                const Intersection &intersection =\n                        scene->getTriangles()[lightTriangleIndex].intersect(toLight);\n                dist += intersection.distance;\n                if (dist >= lightDistance) {\n                    break;\n                }\n\n                toLight.startPoint = intersection.point;\n                intensity *= (1 - scene->getMaterial(triangle.materialCode).dissolve);\n            }\n            if (intensity <= 0.01f) {\n                continue;\n            }\n\n            // Calculate reflection color\n            Vector fromLight(lights[light].point, reflectionPoint);\n            Vector fromLightReflected = scene->getTriangles()[triangleIndex].getReflectedVector(\n                    fromLight);\n            fromLightReflected.normalize();\n\n            reflectionColor +=\n                    lights[light].diffuse * intensity *\n                    std::max(0.f, normal.dot(toLight)) * material.diffuse;\n            reflectionColor +=\n                    lights[light].specular * intensity *\n                    powf(std::max(0.f, toViewer.dot(fromLightReflected)),\n                         material.specularExponent) * material.specular;\n        }\n\n        reflectionColor +=\n                trace(reflectionVector, depth + 1, triangleIndex, weight * (1 - refractivity)) *\n                powf(std::max(0.f, toViewer.dot(normal)), material.specularExponent) *\n                material.specular;\n    }\n\n    if (material.dissolve >= FULLY_OPAQUE_RATIO) {\n        return reflectionColor;\n    } else if (material.dissolve <= FULLY_TRANSPARENT_RATIO) {\n        return refractionColor;\n    }\n\n    return reflectionColor * (1 - refractivity) + refractionColor * refractivity;\n}\n\nVector RayTracingOpenMP::refract(const Vector &vector, const Vector &normal, float ior) const {\n    float dot = vector.dot(normal);\n    float eta1 = 1;\n    float eta2 = ior;\n    Vector localNormal = normal;\n\n    if (dot < 0) {\n        // Ray entering the object\n        dot *= -1;\n    } else {\n        // Ray going out of the object\n        localNormal = normal.mul(-1);\n        std::swap(eta1, eta2);\n    }\n\n    float eta = eta1 / eta2;\n    float k = 1 - eta * eta * (1 - dot * dot);\n    if (k < 0) {\n        // Total internal reflection\n        return Vector::ZERO;\n    }\n\n    Vector returnVector = vector.mul(eta).add(localNormal.mul(eta * dot - sqrtf(k)));\n    returnVector.normalize();\n    return returnVector;\n}\n\nfloat RayTracingOpenMP::fresnel(const Vector &vector, const Vector &normal, float ior) const {\n    float cos1 = vector.dot(normal);\n    float eta1 = 1;\n    float eta2 = ior;\n\n    if (cos1 > 0) {\n        std::swap(eta1, eta2);\n    }\n\n    float sin2 = eta1 / eta2 * sqrtf(std::max(0.f, 1 - cos1 * cos1));\n    if (sin2 >= 1.f) {\n        // Total internal reflection\n        return 1;\n    }\n\n    float cos2 = sqrtf(1 - sin2 * sin2);\n    cos1 = fabsf(cos1);\n    float reflectS = (eta1 * cos1 - eta2 * cos2) / (eta1 * cos1 + eta2 * cos2);\n    float reflectP = (eta1 * cos2 - eta2 * cos1) / (eta1 * cos2 + eta2 * cos1);\n    return (reflectS * reflectS + reflectP * reflectP) / 2;\n}\n\nvoid RayTracingOpenMP::setScene(std::unique_ptr<Scene> scene) {\n    Backend::setScene(std::move(scene));\n    kdTree = std::make_unique<KdTree>(this->scene.get());\n}\n", "meta": {"hexsha": "88d06f513e4bcfeddff8572d6d4ad274988e18f3", "size": 6899, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CUDA-RayTracer/backends/ray_tracing/RayTracingOpenMP.cpp", "max_stars_repo_name": "apardyl/cuda-raytracer", "max_stars_repo_head_hexsha": "cc0f6a148706fb66f7c4b15e67600deb2e00eed1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CUDA-RayTracer/backends/ray_tracing/RayTracingOpenMP.cpp", "max_issues_repo_name": "apardyl/cuda-raytracer", "max_issues_repo_head_hexsha": "cc0f6a148706fb66f7c4b15e67600deb2e00eed1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CUDA-RayTracer/backends/ray_tracing/RayTracingOpenMP.cpp", "max_forks_repo_name": "apardyl/cuda-raytracer", "max_forks_repo_head_hexsha": "cc0f6a148706fb66f7c4b15e67600deb2e00eed1", "max_forks_repo_licenses": ["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.818627451, "max_line_length": 96, "alphanum_fraction": 0.5939991303, "num_tokens": 1715, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.45116574372525}}
{"text": "#include <ros/ros.h>\n#include <nav_msgs/Path.h>\n#include <nav_msgs/Odometry.h>\n#include <geometry_msgs/PoseStamped.h>\n#include <geometry_msgs/PoseWithCovarianceStamped.h>\n#include <tf_conversions/tf_eigen.h>\n#include <eigen_conversions/eigen_msg.h>\n\n#include <Eigen/Eigen>\n#include <Eigen/Geometry>\n\n#include \"orcvio/euroc_gt.h\"\n\nnamespace orcvio \n{\n\n    // this subscribes to the estimated pose\n    void EuRoCPub::gt_odom_path_cb(const nav_msgs::Odometry::ConstPtr &est_odom_ptr){\n\n        double timestamp = est_odom_ptr->header.stamp.toSec();\n        // Our groundtruth state\n        Eigen::Matrix<double,17,1> state_gt;\n\n        // Check that we have the timestamp in our GT file [time(sec),q_GtoI,p_IinG,v_IinG,b_gyro,b_accel]\n        if(!DatasetReader::get_gt_state(timestamp, state_gt, gt_states)) {\n            return;\n        }\n\n        Eigen::Vector4d q_gt;\n        Eigen::Vector3d t_gt;\n\n        q_gt << state_gt(1,0),state_gt(2,0),state_gt(3,0),state_gt(4,0);\n        t_gt << state_gt(5,0),state_gt(6,0),state_gt(7,0);\n\n        Eigen::Quaterniond q_in = Eigen::Quaterniond(q_gt);\n\n        if (first_pose_flag)\n        {\n            t0 = t_gt;\n            // convert to rotation matrix\n            R0 = q_in.normalized().toRotationMatrix();\n\n            // align the estimated pose and groundtruth pose \n            t0 = slamTgt.linear() * t0 + slamTgt.translation(); \n            R0 = slamTgt.linear() * R0;\n\n            first_pose_flag = false;\n        }\n\n        Eigen::Vector3d t1, t1_new;\n        t1 = t_gt;\n\n        // convert to rotation matrix\n        Eigen::Matrix3d R1, R_new; \n        R1 = q_in.normalized().toRotationMatrix();\n\n        // align the estimated pose and groundtruth pose \n        t1_new = slamTgt.linear() * t1 + slamTgt.translation(); \n        // initial position is 0 \n        t1_new = t1_new - t0; \n        // NOTE, rotation is not identity since orcvio initializes using gravity \n        R_new = slamTgt.linear() * R1;\n\n        // convert to quaternion\n        Eigen::Quaterniond q1_normalized = Eigen::Quaterniond(R_new);\n        // normalize the quaternion\n        q1_normalized = q1_normalized.normalized();\n\n        geometry_msgs::PoseStamped cur_pose;\n        cur_pose.header = est_odom_ptr->header;\n        cur_pose.header.frame_id = \"/global\";\n\n        cur_pose.pose.position.x = t1_new(0,0);\n        cur_pose.pose.position.y = t1_new(1,0);\n        cur_pose.pose.position.z = t1_new(2,0);\n\n        cur_pose.pose.orientation.x = q1_normalized.x(); \n        cur_pose.pose.orientation.y = q1_normalized.y(); \n        cur_pose.pose.orientation.z = q1_normalized.z(); \n        cur_pose.pose.orientation.w = q1_normalized.w(); \n\n        path.header = cur_pose.header;\n        path.header.frame_id = \"/global\";\n        path.poses.push_back(cur_pose);\n\n        pub_gt_path.publish(path);\n\n        // save the pose to txt for trajectory evaluation \n        // ============================\n        // TUM format\n        // timestamp tx ty tz qx qy qz qw\n        fStateToSave << std::fixed << std::setprecision(3) << cur_pose.header.stamp.toSec();\n        fStateToSave << \" \"\n            << cur_pose.pose.position.x << \" \" << cur_pose.pose.position.y << \" \" << cur_pose.pose.position.z << \" \"\n            << cur_pose.pose.orientation.x << \" \" << cur_pose.pose.orientation.y << \" \" << cur_pose.pose.orientation.z << \" \" << cur_pose.pose.orientation.w << std::endl; \n                \n\n        return;\n\n    }\n\n}", "meta": {"hexsha": "7537303e433aa8f489e120a28474a8872af62184", "size": 3445, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/euroc_gt.cpp", "max_stars_repo_name": "shanmo/OrcVIO-Stereo", "max_stars_repo_head_hexsha": "78d4cf24cc280af53f4131628983891817fbf070", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2021-08-06T03:24:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-02T14:23:44.000Z", "max_issues_repo_path": "src/euroc_gt.cpp", "max_issues_repo_name": "shanmo/OrcVIO-Stereo", "max_issues_repo_head_hexsha": "78d4cf24cc280af53f4131628983891817fbf070", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-09-30T17:09:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-01T23:41:52.000Z", "max_forks_repo_path": "src/euroc_gt.cpp", "max_forks_repo_name": "shanmo/OrcVIO-Stereo", "max_forks_repo_head_hexsha": "78d4cf24cc280af53f4131628983891817fbf070", "max_forks_repo_licenses": ["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.7745098039, "max_line_length": 171, "alphanum_fraction": 0.6095791001, "num_tokens": 875, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.45116574372525}}
{"text": "#include \"rv/Math.h\"\n#include <algorithm>\n#include <boost/lexical_cast.hpp>\n#include <cstdlib>\n#include <cstring>\n#include <fstream>\n#include <iostream>\n#include <list>\n#include <sstream>\n#include \"rv/IOError.h\"\n#include \"rv/Random.h\"\n#include \"rv/string_utils.h\"\n\nnamespace rv {\n\nnamespace Math {\n\nstruct SortElement {\n  SortElement(unsigned int ind, double val) : index(ind), value(val) {}\n\n  bool operator<(const SortElement& other) { return (value < other.value); }\n\n  uint32_t index;\n  double value;\n};\n\nEigen::MatrixXf cov(const Eigen::MatrixXf& X, const int32_t N) {\n  int n = std::min(1, std::max(N, 0));\n  if (X.rows() == 1) n = 1;\n\n  // calculate the mean\n\n  Eigen::VectorXf mean = X.colwise().sum();\n  mean = mean / X.rows();\n\n  Eigen::MatrixXf X_mean = Eigen::MatrixXf::Zero(X.rows(), X.cols());\n  for (uint32_t i = 0; i < X.rows(); ++i)\n    for (uint32_t j = 0; j < X.cols(); ++j) X_mean(i, j) = X(i, j) - mean[j];\n\n  Eigen::MatrixXf covariance = 1.0 / (double)(X.rows() - 1 + n) * X_mean.transpose() * X_mean;\n\n  return covariance;\n}\n\n// double min(const legacy_fkie::Vector& V)\n//{\n//  return V.min();\n//}\n//\n\nEigen::MatrixXf min(const Eigen::MatrixXf& M) { return M.colwise().minCoeff(); }\n\n//\n// double max(const legacy_fkie::Vector& V)\n//{\n//  return V.max();\n//}\n//\nEigen::MatrixXf max(const Eigen::MatrixXf& M) { return M.colwise().maxCoeff(); }\n\nvoid sort(const Eigen::MatrixXf& M, Eigen::MatrixXf& result, Eigen::MatrixXf& indices) {\n  std::list<SortElement> temp;\n\n  for (uint32_t c = 0; c < M.cols(); ++c) {\n    for (uint32_t r = 0; r < M.rows(); ++r) temp.push_back(SortElement(r, M(r, c)));\n\n    temp.sort();\n\n    uint32_t r = 0;\n    while (!temp.empty()) {\n      indices(r, c) = temp.front().index;\n      result(r, c) = temp.front().value;\n      temp.pop_front();  // clear the list\n      ++r;\n    }\n  }\n}\n//\n// legacy_fkie::Vector prod(const legacy_fkie::Matrix& M, int dim)\n//{\n//  legacy_fkie::Vector result;\n//  if (dim == 0)\n//  {\n//    result = legacy_fkie::Vector(M.cols());\n//    for (unsigned int c = 0; c < M.cols(); ++c)\n//    {\n//      double product = 1.0;\n//      for (unsigned int r = 0; r < M.rows(); ++r)\n//        product *= M(r, c);\n//      result[c] = product;\n//    }\n//  }\n//  else if (dim == 1)\n//  {\n//    result = legacy_fkie::Vector(M.rows());\n//\n//    for (unsigned int r = 0; r < M.rows(); ++r)\n//    {\n//      double product = 1.0;\n//      for (unsigned int c = 0; c < M.cols(); ++c)\n//        product *= M(r, c);\n//      result[r] = product;\n//    }\n//  }\n//\n//  return result;\n//}\n//\n// legacy_fkie::Matrix importdata(const std::string& filename,\n//    const std::string& delimiter, const unsigned int headerline)\n//{\n//  const unsigned int MAX_LENGTH = 64000;\n//  char line[MAX_LENGTH];\n//  memset(line, 0, MAX_LENGTH * sizeof(char));\n//  char* token = 0;\n//\n//  std::ifstream file(filename.c_str());\n//  if (!file.good()) throw legacy_fkie::IOError(\n//      \"importdata: failed opening \" + filename);\n//\n//  // determine the rows and column count\n//  unsigned int lineno = 0;\n//  unsigned int rows = 0;\n//  unsigned int cols = 0;\n//  while (!file.eof())\n//  {\n//    file.getline(line, 64000);\n//    ++lineno;\n//    if (lineno <= headerline) continue;\n//\n//    // count columns\n//    if (rows == 0)\n//    {\n//      token = strtok(line, delimiter.c_str());\n//      while (token != 0)\n//      {\n//        ++cols;\n//        token = strtok(0, delimiter.c_str());\n//      }\n//    }\n//    ++rows;\n//  }\n//  file.close();\n//\n//  legacy_fkie::Matrix result(rows, cols);\n//  file.open(filename.c_str());\n//  unsigned int r = 0;\n//  unsigned int c = 0;\n//  lineno = 0;\n//  while (!file.eof())\n//  {\n//    c = 0;\n//    file.getline(line, 64000);\n//    ++lineno;\n//    if (lineno <= headerline) continue;\n//    // split line\n//    token = strtok(line, delimiter.c_str());\n//    while (token != 0)\n//    {\n//      result(r, c) = atof(token);\n//      token = strtok(0, delimiter.c_str());\n//      ++c;\n//    }\n//    ++r;\n//  }\n//\n//  file.close();\n//\n//  return result;\n//}\n//\n// legacy_fkie::Matrix sqrt(const legacy_fkie::Matrix& M)\n//{\n//  legacy_fkie::Matrix Z = M;\n//  std::vector<double> ev;\n//\n//  int info = legacy_fkie::LA::dsyev('V', 'U', Z, ev);\n//  if (info < 0)\n//  {\n//    throw legacy_fkie::MathError(\n//        \"failed to determine the eigenvalues and eigenvectors of M\");\n//  }\n//  else if (info > 0)\n//  {\n//    throw legacy_fkie::MathError(\"failed to converge!\");\n//  }\n//\n////  std::cout << ev.size() << std::endl;\n//  /* calculate D^(1/2) */\n//  legacy_fkie::Matrix D(ev.size(), ev.size());\n//  for (unsigned int i = 0; i < ev.size(); ++i)\n//  {\n//    // epsilon test for values near zero.\n//    if (std::abs(ev[i]) < 0.0000001)\n//    {\n//      D(i, i) = 0.0;\n//      continue;\n//    }\n//    if (ev[i] < 0)\n//    {\n//      std::stringstream sstr;\n//      sstr\n//          << \"Matrix M is not positive semi-definite. Eigenvalue less than zero: \"\n//          << ev[i];\n//      throw legacy_fkie::MathError(sstr.str());\n//    }\n//    D(i, i) = std::sqrt(ev[i]);\n//  }\n//\n//  return Z * D * Z.transpose();\n//}\n\n// legacy_fkie::Vector randperm(const unsigned int n)\n//{\n//  static legacy_fkie::Random rand;\n//  legacy_fkie::Vector v(n);\n//\n//  for (unsigned int i = 1; i <= n; ++i)\n//    v[i - 1] = i;\n//\n//  std::random_shuffle(v.ptr(), v.ptr() + n, rand);\n//\n//  return v;\n//}\n\nvoid save(const std::string& filename, const std::string& varname, const Eigen::MatrixXf& mat) {\n  std::ofstream out(filename.c_str());\n  assert(out.is_open());\n\n  /** outputting the header information. **/\n  out << \"# name: \" << varname << std::endl;\n  out << \"# type: matrix\" << std::endl;\n  out << \"# rows: \" << mat.rows() << std::endl;\n  out << \"# columns: \" << mat.cols() << std::endl;\n\n  for (uint32_t r = 0; r < mat.rows(); ++r) {\n    for (uint32_t c = 0; c < mat.cols(); ++c) {\n      out << \" \" << mat(r, c);\n    }\n    out << std::endl;\n  }\n\n  out.close();\n}\n\nbool load(const std::string& filename, Eigen::MatrixXf& M) {\n  std::ifstream in(filename.c_str());\n  if (!in.is_open()) {\n    std::cerr << \"unable to open '\" << filename << \"'\" << std::endl;\n    return false;\n  }\n\n  std::string line;\n  std::vector<std::string> tokens;\n\n  bool rows_read = false, cols_read = false;\n  uint32_t rows = 0, cols = 0;\n\n  in.peek();\n  while ((!rows_read || !cols_read) && !in.eof()) {\n    std::getline(in, line);\n    if (line[0] != '#') break;\n    tokens = split(line, \":\");\n    // trim = remove \"# \" in the begining.\n    std::string name = trim(tokens[0], \" #\");\n    std::string value = trim(tokens[1]);\n\n    if (name == \"type\") {\n      if (value != \"matrix\") {\n        std::cerr << \"unknown type '\" << tokens[1] << \"'!\" << std::endl;\n        return false;\n      }\n    }\n\n    if (name == \"rows\") {\n      rows_read = true;\n      // trim = remove leading spaces\n      rows = boost::lexical_cast<uint32_t>(value);\n    }\n\n    if (name == \"columns\") {\n      cols_read = true;\n      // trim = remove leading spaces\n      cols = boost::lexical_cast<uint32_t>(value);\n    }\n    in.peek();\n  }\n\n  if (!rows_read) {\n    std::cerr << \"missing 'rows' entry!\" << std::endl;\n    return false;\n  }\n  if (!cols_read) {\n    std::cerr << \"missing 'cols' entry!\" << std::endl;\n    return false;\n  }\n\n  M = Eigen::MatrixXf(rows, cols);\n\n  in.peek();\n  for (uint32_t r = 0; r < rows; ++r) {\n    if (in.eof()) return false;\n\n    std::getline(in, line);\n    // trim = remove leading space.\n    tokens = split(trim(line));\n    if (tokens.size() < cols) return false;\n\n    for (uint32_t c = 0; c < cols; ++c) M(r, c) = boost::lexical_cast<float>(tokens[c]);\n\n    in.peek();\n  }\n\n  in.close();\n\n  return true;\n}\n\nvoid save(const std::string& filename, const std::string& varname, const Eigen::MatrixXd& mat) {\n  std::ofstream out(filename.c_str());\n  assert(out.is_open());\n\n  /** outputting the header information. **/\n  out << \"# name: \" << varname << std::endl;\n  out << \"# type: matrix\" << std::endl;\n  out << \"# rows: \" << mat.rows() << std::endl;\n  out << \"# columns: \" << mat.cols() << std::endl;\n\n  for (uint32_t r = 0; r < mat.rows(); ++r) {\n    for (uint32_t c = 0; c < mat.cols(); ++c) {\n      out << \" \" << mat(r, c);\n    }\n    out << std::endl;\n  }\n\n  out.close();\n}\n\nbool load(const std::string& filename, Eigen::MatrixXd& M) {\n  std::ifstream in(filename.c_str());\n  if (!in.is_open()) {\n    std::cerr << \"unable to open '\" << filename << \"'\" << std::endl;\n    return false;\n  }\n\n  std::string line;\n  std::vector<std::string> tokens;\n\n  bool rows_read = false, cols_read = false;\n  uint32_t rows = 0, cols = 0;\n\n  in.peek();\n  while ((!rows_read || !cols_read) && !in.eof()) {\n    std::getline(in, line);\n    if (line[0] != '#') break;\n    tokens = split(line, \":\");\n    // trim = remove \"# \" in the begining.\n    std::string name = trim(tokens[0], \" #\");\n    std::string value = trim(tokens[1]);\n\n    if (name == \"type\") {\n      if (value != \"matrix\") {\n        std::cerr << \"unknown type '\" << tokens[1] << \"'!\" << std::endl;\n        return false;\n      }\n    }\n\n    if (name == \"rows\") {\n      rows_read = true;\n      // trim = remove leading spaces\n      rows = boost::lexical_cast<uint32_t>(value);\n    }\n\n    if (name == \"columns\") {\n      cols_read = true;\n      // trim = remove leading spaces\n      cols = boost::lexical_cast<uint32_t>(value);\n    }\n    in.peek();\n  }\n\n  if (!rows_read) {\n    std::cerr << \"missing 'rows' entry!\" << std::endl;\n    return false;\n  }\n  if (!cols_read) {\n    std::cerr << \"missing 'cols' entry!\" << std::endl;\n    return false;\n  }\n\n  M = Eigen::MatrixXd(rows, cols);\n\n  in.peek();\n  for (uint32_t r = 0; r < rows; ++r) {\n    if (in.eof()) return false;\n\n    std::getline(in, line);\n    // trim = remove leading space.\n    tokens = split(trim(line));\n    if (tokens.size() < cols) return false;\n\n    for (uint32_t c = 0; c < cols; ++c) M(r, c) = boost::lexical_cast<double>(tokens[c]);\n\n    in.peek();\n  }\n\n  in.close();\n\n  return true;\n}\n\ndouble normal_pdf(double x, double mu, double sigma) {\n  static const double sqrt2pi = std::sqrt(2.0 * PI);\n\n  double value = 1. / (sigma * sqrt2pi);\n  value *= std::exp(-0.5 * (x - mu) * (x - mu) / (sigma * sigma));\n\n  return value;\n}\n\ndouble exponential_pdf(double x, double lambda) { return lambda * exp(-lambda * x); }\n\ndouble sigmoid2(double x, double loc, double scale) { return 1.0 / (1.0 + std::exp(-scale * x + scale * loc)); }\n\nEigen::Matrix2f diag(float val0, float val1) {\n  Eigen::Matrix2f m = Eigen::Matrix2f::Zero();\n\n  m(0, 0) = val0;\n  m(1, 1) = val1;\n\n  return m;\n}\n\nEigen::Matrix3f diag(float val0, float val1, float val2) {\n  Eigen::Matrix3f m = Eigen::Matrix3f::Zero();\n\n  m(0, 0) = val0;\n  m(1, 1) = val1;\n  m(2, 2) = val2;\n\n  return m;\n}\n}\n}\n", "meta": {"hexsha": "79af7a92c440977c8e8be67857708f750f703622", "size": 10673, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/rv/Math.cpp", "max_stars_repo_name": "jerlomy4ever/568_final_project", "max_stars_repo_head_hexsha": "5f75d673d0236548345a10d8a2c54d8d8971ea92", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 644.0, "max_stars_repo_stars_event_min_datetime": "2019-07-26T18:53:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:37:17.000Z", "max_issues_repo_path": "src/rv/Math.cpp", "max_issues_repo_name": "topcomma/SuMa", "max_issues_repo_head_hexsha": "683f9bbb7298f8f2d1c6d8891362bba3ee8c6c54", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 54.0, "max_issues_repo_issues_event_min_datetime": "2019-08-20T02:46:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T13:34:37.000Z", "max_forks_repo_path": "src/rv/Math.cpp", "max_forks_repo_name": "topcomma/SuMa", "max_forks_repo_head_hexsha": "683f9bbb7298f8f2d1c6d8891362bba3ee8c6c54", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 176.0, "max_forks_repo_forks_event_min_datetime": "2019-10-19T04:57:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T05:52:00.000Z", "avg_line_length": 23.9842696629, "max_line_length": 112, "alphanum_fraction": 0.5482057528, "num_tokens": 3304, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419958239132, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.45115573345191073}}
{"text": "// -*- mode: C++ -*-\n/**\n   Dietrich Bollmann, Kamakura, 2015/01/01\n   \n   DVector-test.h\n\n   Unit tests for class: DVector\n   \n   Copyright (c) 2015 Dietrich Bollmann\n   \n   This software may be modified and distributed under the terms\n   of the MIT license.  See the LICENSE file for details.\n*/\n\n#define BOOST_TEST_DYN_LINK\n#ifdef STAND_ALONE\n#   define BOOST_TEST_MODULE Main\n#endif\n#include <boost/test/unit_test.hpp>\n\n#include \"DVector.h\"\n\nnamespace nsl {\n\nBOOST_AUTO_TEST_SUITE(TestSuite_DVector)\n\n// Test equality operator\nbool test_equality(const std::vector<double> &left, \n\t\t   const std::vector<double> &right)\n{\n  DVector vLeft(left);\n  DVector vRight(right);\n\n  return (vLeft == vRight);\n}\n\nBOOST_AUTO_TEST_CASE(Test_DVector_equality_operator)\n{\n  // equal\n  BOOST_REQUIRE(   test_equality( {},        {}        ) );\n  BOOST_REQUIRE(   test_equality( {1},       {1}       ) );\n  BOOST_REQUIRE(   test_equality( {1, 2},    {1, 2}    ) );\n  BOOST_REQUIRE(   test_equality( {1, 2, 3}, {1, 2, 3} ) );\n\n  // different size\n  BOOST_REQUIRE( ! test_equality( {},        {1}       ) );\n  BOOST_REQUIRE( ! test_equality( {1},       {}        ) );\n  BOOST_REQUIRE( ! test_equality( {1},       {1, 2}    ) );\n  BOOST_REQUIRE( ! test_equality( {1, 2},    {1}       ) );\n\n  // different elements\n  BOOST_REQUIRE( ! test_equality( {1},       {2}       ) );\n  BOOST_REQUIRE( ! test_equality( {1, 2},    {3, 2}    ) );\n  BOOST_REQUIRE( ! test_equality( {1, 2},    {1, 3}    ) );\n  BOOST_REQUIRE( ! test_equality( {1, 2, 3}, {4, 2, 3} ) );\n  BOOST_REQUIRE( ! test_equality( {1, 2, 3}, {1, 4, 3} ) );\n  BOOST_REQUIRE( ! test_equality( {1, 2, 3}, {1, 2, 4} ) );\n}\n\n// Test multiplication\nBOOST_AUTO_TEST_CASE(Test_DVector_multiplication_operator)\n{\n  BOOST_REQUIRE( DVector( (std::vector<double>){4} ) * DVector( (std::vector<double>){7} ) == 28 );\n  BOOST_REQUIRE( DVector(    {3, 4} ) * DVector(    {6, 7} ) == 46 );\n  BOOST_REQUIRE( DVector( {2, 3, 4} ) * DVector( {5, 6, 7} ) == 56 );\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n} // namespace nsl\n\n/* fin */\n", "meta": {"hexsha": "283c276dc35080257572efbe3a1cd48fecfa9153", "size": 2046, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/DVector-test.cpp", "max_stars_repo_name": "newskylabs/nslfem-spring1d", "max_stars_repo_head_hexsha": "40dfb1c52dc62134ed12e49ab1147362c49312ce", "max_stars_repo_licenses": ["MIT"], "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/DVector-test.cpp", "max_issues_repo_name": "newskylabs/nslfem-spring1d", "max_issues_repo_head_hexsha": "40dfb1c52dc62134ed12e49ab1147362c49312ce", "max_issues_repo_licenses": ["MIT"], "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/DVector-test.cpp", "max_forks_repo_name": "newskylabs/nslfem-spring1d", "max_forks_repo_head_hexsha": "40dfb1c52dc62134ed12e49ab1147362c49312ce", "max_forks_repo_licenses": ["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.0273972603, "max_line_length": 99, "alphanum_fraction": 0.6060606061, "num_tokens": 669, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548646660543, "lm_q2_score": 0.6926419958239131, "lm_q1q2_score": 0.4511557334519106}}
{"text": "\n\n/* --------------------------------------------------------------------- \n * \n * Copyright (C) 2007 - 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: Tobias Leicht, 2007 \n */ \n\n\n\n// deal.II\u5305\u62ec\u7684\u6587\u4ef6\u5df2\u7ecf\u5728\u524d\u9762\u7684\u4f8b\u5b50\u4e2d\u4ecb\u7ecd\u8fc7\u4e86\uff0c\u56e0\u6b64\u4e0d\u518d\u505a\u8fdb\u4e00\u6b65\u7684\u8bc4\u8bba\u3002\n\n#include <deal.II/base/function.h> \n#include <deal.II/base/quadrature_lib.h> \n#include <deal.II/base/timer.h> \n#include <deal.II/lac/precondition_block.h> \n#include <deal.II/lac/solver_richardson.h> \n#include <deal.II/lac/sparse_matrix.h> \n#include <deal.II/lac/vector.h> \n#include <deal.II/grid/tria.h> \n#include <deal.II/grid/grid_generator.h> \n#include <deal.II/grid/grid_out.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_values.h> \n#include <deal.II/fe/mapping_q1.h> \n#include <deal.II/fe/fe_dgq.h> \n#include <deal.II/numerics/data_out.h> \n#include <deal.II/numerics/derivative_approximation.h> \n\n// \u800c\u8fd9\u53c8\u662fC++\u3002\n\n#include <array> \n#include <iostream> \n#include <fstream> \n\n// \u6700\u540e\u4e00\u6b65\u548c\u4ee5\u524d\u6240\u6709\u7684\u7a0b\u5e8f\u4e00\u6837\u3002\n\nnamespace Step30 \n{ \n  using namespace dealii; \n// @sect3{Equation data}  \n\n// \u63cf\u8ff0\u65b9\u7a0b\u6570\u636e\u7684\u7c7b\u548c\u5355\u4e2a\u672f\u8bed\u7684\u5b9e\u9645\u88c5\u914d\u51e0\u4e4e\u5b8c\u5168\u7167\u642c\u81ea  step-12  \u3002\u6211\u4eec\u5c06\u5bf9\u5dee\u5f02\u8fdb\u884c\u8bc4\u8bba\u3002\n\n  template <int dim> \n  class RHS : public Function<dim> \n  { \n  public: \n    virtual void value_list(const std::vector<Point<dim>> &points, \n                            std::vector<double> &          values, \n                            const unsigned int /*component*/ = 0) const override \n    { \n      (void)points; \n      Assert(values.size() == points.size(), \n             ExcDimensionMismatch(values.size(), points.size())); \n\n      std::fill(values.begin(), values.end(), 0.); \n    } \n  }; \n\n  template <int dim> \n  class BoundaryValues : public Function<dim> \n  { \n  public: \n    virtual void value_list(const std::vector<Point<dim>> &points, \n                            std::vector<double> &          values, \n                            const unsigned int /*component*/ = 0) const override \n    { \n      Assert(values.size() == points.size(), \n             ExcDimensionMismatch(values.size(), points.size())); \n\n      for (unsigned int i = 0; i < values.size(); ++i) \n        { \n          if (points[i](0) < 0.5) \n            values[i] = 1.; \n          else \n            values[i] = 0.; \n        } \n    } \n  }; \n\n  template <int dim> \n  class Beta \n  { \n  public: \n\n//\u6d41\u573a\u9009\u62e9\u4e3a\u9006\u65f6\u9488\u65b9\u5411\u7684\u56db\u5206\u4e4b\u4e00\u5706\uff0c\u539f\u70b9\u4e3a\u57df\u7684\u53f3\u534a\u90e8\u5206\u7684\u4e2d\u70b9\uff0c\u6570\u503c\u4e3a\u6b63 $x$ \uff0c\u800c\u5728\u57df\u7684\u5de6\u8fb9\u90e8\u5206\uff0c\u6d41\u901f\u53ea\u662f\u5411\u5de6\u8d70\uff0c\u4e0e\u4ece\u53f3\u8fb9\u8fdb\u6765\u7684\u6d41\u901f\u4e00\u81f4\u3002\u5728\u5706\u5f62\u90e8\u5206\uff0c\u6d41\u901f\u7684\u5927\u5c0f\u4e0e\u79bb\u539f\u70b9\u7684\u8ddd\u79bb\u6210\u6b63\u6bd4\u3002\u8fd9\u4e0e step-12 \u4e0d\u540c\uff0c\u5728\u8be5\u5b9a\u4e49\u4e2d\uff0c\u5230\u5904\u90fd\u662f1\u3002\u65b0\u5b9a\u4e49\u5bfc\u81f4 $\\beta$ \u6cbf\u5355\u5143\u7684\u6bcf\u4e2a\u7ed9\u5b9a\u9762\u7684\u7ebf\u6027\u53d8\u5316\u3002\u53e6\u4e00\u65b9\u9762\uff0c $u(x,y)$ \u7684\u89e3\u51b3\u65b9\u6848\u4e0e\u4e4b\u524d\u5b8c\u5168\u76f8\u540c\u3002\n\n    void value_list(const std::vector<Point<dim>> &points, \n                    std::vector<Point<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        { \n          if (points[i](0) > 0) \n            { \n              values[i](0) = -points[i](1); \n              values[i](1) = points[i](0); \n            } \n          else \n            { \n              values[i]    = Point<dim>(); \n              values[i](0) = -points[i](1); \n            } \n        } \n    } \n  }; \n\n//  @sect3{Class: DGTransportEquation}  \n\n// \u8fd9\u4e2a\u7c7b\u7684\u58f0\u660e\u5b8c\u5168\u4e0d\u53d7\u6211\u4eec\u76ee\u524d\u7684\u53d8\u5316\u5f71\u54cd\u3002\n\n  template <int dim> \n  class DGTransportEquation \n  { \n  public: \n    DGTransportEquation(); \n\n    void assemble_cell_term(const FEValues<dim> &fe_v, \n                            FullMatrix<double> & ui_vi_matrix, \n                            Vector<double> &     cell_vector) const; \n\n    void assemble_boundary_term(const FEFaceValues<dim> &fe_v, \n                                FullMatrix<double> &     ui_vi_matrix, \n                                Vector<double> &         cell_vector) const; \n\n    void assemble_face_term(const FEFaceValuesBase<dim> &fe_v, \n                            const FEFaceValuesBase<dim> &fe_v_neighbor, \n                            FullMatrix<double> &         ui_vi_matrix, \n                            FullMatrix<double> &         ue_vi_matrix, \n                            FullMatrix<double> &         ui_ve_matrix, \n                            FullMatrix<double> &         ue_ve_matrix) const; \n\n  private: \n    const Beta<dim>           beta_function; \n    const RHS<dim>            rhs_function; \n    const BoundaryValues<dim> boundary_function; \n  }; \n\n// \u540c\u6837\u5730\uff0c\u8be5\u7c7b\u7684\u6784\u9020\u51fd\u6570\u4ee5\u53ca\u7ec4\u88c5\u5bf9\u5e94\u4e8e\u5355\u5143\u683c\u5185\u90e8\u548c\u8fb9\u754c\u9762\u7684\u672f\u8bed\u7684\u51fd\u6570\u4e0e\u4e4b\u524d\u6ca1\u6709\u53d8\u5316\u3002\u88c5\u914d\u5355\u5143\u95f4\u9762\u672f\u8bed\u7684\u51fd\u6570\u4e5f\u6ca1\u6709\u6539\u53d8\uff0c\u56e0\u4e3a\u5b83\u6240\u505a\u7684\u53ea\u662f\u5bf9\u4e24\u4e2aFEFaceValuesBase\u7c7b\u578b\u7684\u5bf9\u8c61\u8fdb\u884c\u64cd\u4f5c\uff08\u5b83\u662fFEFaceValues\u548cFESubfaceValues\u7684\u57fa\u7c7b\uff09\u3002\u8fd9\u4e9b\u5bf9\u8c61\u4ece\u4f55\u800c\u6765\uff0c\u5373\u5b83\u4eec\u662f\u5982\u4f55\u88ab\u521d\u59cb\u5316\u7684\uff0c\u5bf9\u8fd9\u4e2a\u51fd\u6570\u6765\u8bf4\u5e76\u4e0d\u91cd\u8981\uff1a\u5b83\u53ea\u662f\u5047\u8bbe\u8fd9\u4e24\u4e2a\u5bf9\u8c61\u6240\u4ee3\u8868\u7684\u9762\u6216\u5b50\u9762\u4e0a\u7684\u6b63\u4ea4\u70b9\u4e0e\u7269\u7406\u7a7a\u95f4\u4e2d\u7684\u76f8\u540c\u70b9\u76f8\u5bf9\u5e94\u3002\n\n  template <int dim> \n  DGTransportEquation<dim>::DGTransportEquation() \n    : beta_function() \n    , rhs_function() \n    , boundary_function() \n  {} \n\n  template <int dim> \n  void DGTransportEquation<dim>::assemble_cell_term( \n    const FEValues<dim> &fe_v, \n    FullMatrix<double> & ui_vi_matrix, \n    Vector<double> &     cell_vector) const \n  { \n    const std::vector<double> &JxW = fe_v.get_JxW_values(); \n\n    std::vector<Point<dim>> beta(fe_v.n_quadrature_points); \n    std::vector<double>     rhs(fe_v.n_quadrature_points); \n\n    beta_function.value_list(fe_v.get_quadrature_points(), beta); \n    rhs_function.value_list(fe_v.get_quadrature_points(), rhs); \n\n    for (unsigned int point = 0; point < fe_v.n_quadrature_points; ++point) \n      for (unsigned int i = 0; i < fe_v.dofs_per_cell; ++i) \n        { \n          for (unsigned int j = 0; j < fe_v.dofs_per_cell; ++j) \n            ui_vi_matrix(i, j) -= beta[point] * fe_v.shape_grad(i, point) * \n                                  fe_v.shape_value(j, point) * JxW[point]; \n\n          cell_vector(i) += \n            rhs[point] * fe_v.shape_value(i, point) * JxW[point]; \n        } \n  } \n\n  template <int dim> \n  void DGTransportEquation<dim>::assemble_boundary_term( \n    const FEFaceValues<dim> &fe_v, \n    FullMatrix<double> &     ui_vi_matrix, \n    Vector<double> &         cell_vector) const \n  { \n    const std::vector<double> &        JxW     = fe_v.get_JxW_values(); \n    const std::vector<Tensor<1, dim>> &normals = fe_v.get_normal_vectors(); \n\n    std::vector<Point<dim>> beta(fe_v.n_quadrature_points); \n    std::vector<double>     g(fe_v.n_quadrature_points); \n\n    beta_function.value_list(fe_v.get_quadrature_points(), beta); \n    boundary_function.value_list(fe_v.get_quadrature_points(), g); \n\n    for (unsigned int point = 0; point < fe_v.n_quadrature_points; ++point) \n      { \n        const double beta_n = beta[point] * normals[point]; \n        if (beta_n > 0) \n          for (unsigned int i = 0; i < fe_v.dofs_per_cell; ++i) \n            for (unsigned int j = 0; j < fe_v.dofs_per_cell; ++j) \n              ui_vi_matrix(i, j) += beta_n * fe_v.shape_value(j, point) * \n                                    fe_v.shape_value(i, point) * JxW[point]; \n        else \n          for (unsigned int i = 0; i < fe_v.dofs_per_cell; ++i) \n            cell_vector(i) -= \n              beta_n * g[point] * fe_v.shape_value(i, point) * JxW[point]; \n      } \n  } \n\n  template <int dim> \n  void DGTransportEquation<dim>::assemble_face_term( \n    const FEFaceValuesBase<dim> &fe_v, \n    const FEFaceValuesBase<dim> &fe_v_neighbor, \n    FullMatrix<double> &         ui_vi_matrix, \n    FullMatrix<double> &         ue_vi_matrix, \n    FullMatrix<double> &         ui_ve_matrix, \n    FullMatrix<double> &         ue_ve_matrix) const \n  { \n    const std::vector<double> &        JxW     = fe_v.get_JxW_values(); \n    const std::vector<Tensor<1, dim>> &normals = fe_v.get_normal_vectors(); \n\n    std::vector<Point<dim>> beta(fe_v.n_quadrature_points); \n\n    beta_function.value_list(fe_v.get_quadrature_points(), beta); \n\n    for (unsigned int point = 0; point < fe_v.n_quadrature_points; ++point) \n      { \n        const double beta_n = beta[point] * normals[point]; \n        if (beta_n > 0) \n          { \n            for (unsigned int i = 0; i < fe_v.dofs_per_cell; ++i) \n              for (unsigned int j = 0; j < fe_v.dofs_per_cell; ++j) \n                ui_vi_matrix(i, j) += beta_n * fe_v.shape_value(j, point) * \n                                      fe_v.shape_value(i, point) * JxW[point]; \n\n            for (unsigned int k = 0; k < fe_v_neighbor.dofs_per_cell; ++k) \n              for (unsigned int j = 0; j < fe_v.dofs_per_cell; ++j) \n                ui_ve_matrix(k, j) -= beta_n * fe_v.shape_value(j, point) * \n                                      fe_v_neighbor.shape_value(k, point) * \n                                      JxW[point]; \n          } \n        else \n          { \n            for (unsigned int i = 0; i < fe_v.dofs_per_cell; ++i) \n              for (unsigned int l = 0; l < fe_v_neighbor.dofs_per_cell; ++l) \n                ue_vi_matrix(i, l) += beta_n * \n                                      fe_v_neighbor.shape_value(l, point) * \n                                      fe_v.shape_value(i, point) * JxW[point]; \n\n            for (unsigned int k = 0; k < fe_v_neighbor.dofs_per_cell; ++k) \n              for (unsigned int l = 0; l < fe_v_neighbor.dofs_per_cell; ++l) \n                ue_ve_matrix(k, l) -= \n                  beta_n * fe_v_neighbor.shape_value(l, point) * \n                  fe_v_neighbor.shape_value(k, point) * JxW[point]; \n          } \n      } \n  } \n// @sect3{Class: DGMethod}  \n\n// \u8fd9\u4e2a\u58f0\u660e\u5f88\u50cf  step-12  \u7684\u58f0\u660e\u3002\u7136\u800c\uff0c\u6211\u4eec\u5f15\u5165\u4e86\u4e00\u4e2a\u65b0\u7684\u4f8b\u7a0b\uff08set_anisotropic_flags\uff09\u5e76\u4fee\u6539\u4e86\u53e6\u4e00\u4e2a\u4f8b\u7a0b\uff08refine_grid\uff09\u3002\n\n  template <int dim> \n  class DGMethod \n  { \n  public: \n    DGMethod(const bool anisotropic); \n\n    void run(); \n\n  private: \n    void setup_system(); \n    void assemble_system(); \n    void solve(Vector<double> &solution); \n    void refine_grid(); \n    void set_anisotropic_flags(); \n    void output_results(const unsigned int cycle) const; \n\n    Triangulation<dim>   triangulation; \n    const MappingQ1<dim> mapping; \n\n// \u6211\u4eec\u518d\u6b21\u5e0c\u671b\u4f7f\u7528\u7a0b\u5ea6\u4e3a1\u7684DG\u5143\u7d20\uff08\u4f46\u8fd9\u53ea\u5728\u6784\u9020\u51fd\u6570\u4e2d\u6307\u5b9a\uff09\u3002\u5982\u679c\u4f60\u60f3\u4f7f\u7528\u4e0d\u540c\u7a0b\u5ea6\u7684DG\u65b9\u6cd5\uff0c\u8bf7\u5728\u6784\u9020\u51fd\u6570\u4e2d\u7528\u65b0\u7684\u7a0b\u5ea6\u66ff\u63621\u3002\n\n    const unsigned int degree; \n    FE_DGQ<dim>        fe; \n    DoFHandler<dim>    dof_handler; \n\n    SparsityPattern      sparsity_pattern; \n    SparseMatrix<double> system_matrix; \n\n// \u8fd9\u662f\u65b0\u7684\uff0c\u5728\u4ecb\u7ecd\u4e2d\u89e3\u91ca\u7684\u5404\u5411\u5f02\u6027\u8df3\u8dc3\u6307\u6807\u7684\u8bc4\u4f30\u4e2d\u4f7f\u7528\u7684\u9608\u503c\u3002\u5b83\u7684\u503c\u5728\u6784\u9020\u51fd\u6570\u4e2d\u88ab\u8bbe\u7f6e\u4e3a3.0\uff0c\u4f46\u5b83\u53ef\u4ee5\u5f88\u5bb9\u6613\u5730\u88ab\u6539\u53d8\u4e3a\u4e00\u4e2a\u5927\u4e8e1\u7684\u4e0d\u540c\u503c\u3002\n\n    const double anisotropic_threshold_ratio; \n\n// \u8fd9\u662f\u4e00\u4e2a\u6307\u793a\u662f\u5426\u4f7f\u7528\u5404\u5411\u5f02\u6027\u7ec6\u5316\u7684bool\u6807\u5fd7\u3002\u5b83\u7531\u6784\u9020\u51fd\u6570\u8bbe\u7f6e\uff0c\u6784\u9020\u51fd\u6570\u9700\u8981\u4e00\u4e2a\u540c\u540d\u7684\u53c2\u6570\u3002\n\n    const bool anisotropic; \n\n    const QGauss<dim>     quadrature; \n    const QGauss<dim - 1> face_quadrature; \n\n    Vector<double> solution2; \n    Vector<double> right_hand_side; \n\n    const DGTransportEquation<dim> dg; \n  }; \n\n  template <int dim> \n  DGMethod<dim>::DGMethod(const bool anisotropic) \n    : mapping() \n    , \n\n// \u5bf9\u4e8e\u4e0d\u540c\u7a0b\u5ea6\u7684DG\u65b9\u6cd5\uff0c\u5728\u8fd9\u91cc\u8fdb\u884c\u4fee\u6539\u3002\n\n    degree(1) \n    , fe(degree) \n    , dof_handler(triangulation) \n    , anisotropic_threshold_ratio(3.) \n    , anisotropic(anisotropic) \n    , \n\n// \u7531\u4e8e\u03b2\u662f\u4e00\u4e2a\u7ebf\u6027\u51fd\u6570\uff0c\u6211\u4eec\u53ef\u4ee5\u9009\u62e9\u6b63\u4ea4\u7684\u5ea6\u6570\uff0c\u5bf9\u4e8e\u8fd9\u4e2a\u5ea6\u6570\uff0c\u6240\u5f97\u7684\u79ef\u5206\u662f\u6b63\u786e\u7684\u3002\u56e0\u6b64\uff0c\u6211\u4eec\u9009\u62e9\u4f7f\u7528  <code>degree+1</code>  \u9ad8\u65af\u70b9\uff0c\u8fd9\u4f7f\u6211\u4eec\u80fd\u591f\u51c6\u786e\u5730\u79ef\u5206\u5ea6\u6570\u4e3a  <code>2*degree+1</code>  \u7684\u591a\u9879\u5f0f\uff0c\u8db3\u4ee5\u6ee1\u8db3\u6211\u4eec\u5728\u672c\u7a0b\u5e8f\u4e2d\u8981\u8fdb\u884c\u7684\u6240\u6709\u79ef\u5206\u3002\n\n    quadrature(degree + 1) \n    , face_quadrature(degree + 1) \n    , dg() \n  {} \n\n  template <int dim> \n  void DGMethod<dim>::setup_system() \n  { \n    dof_handler.distribute_dofs(fe); \n    sparsity_pattern.reinit(dof_handler.n_dofs(), \n                            dof_handler.n_dofs(), \n                            (GeometryInfo<dim>::faces_per_cell * \n                               GeometryInfo<dim>::max_children_per_face + \n                             1) * \n                              fe.n_dofs_per_cell()); \n\n    DoFTools::make_flux_sparsity_pattern(dof_handler, sparsity_pattern); \n\n    sparsity_pattern.compress(); \n\n    system_matrix.reinit(sparsity_pattern); \n\n    solution2.reinit(dof_handler.n_dofs()); \n    right_hand_side.reinit(dof_handler.n_dofs()); \n  } \n// @sect4{Function: assemble_system}  \n\n// \u6211\u4eec\u7ee7\u7eed\u4f7f\u7528 <code>assemble_system</code> \u51fd\u6570\u6765\u5b9e\u73b0DG\u79bb\u6563\u5316\u3002\u8fd9\u4e2a\u51fd\u6570\u4e0e step-12 \u4e2d\u7684 <code>assemble_system</code> \u51fd\u6570\u7684\u4f5c\u7528\u76f8\u540c\uff08\u4f46\u6ca1\u6709MeshWorker\uff09\u3002 \u4e00\u4e2a\u5355\u5143\u7684\u90bb\u5c45\u5173\u7cfb\u6240\u8003\u8651\u7684\u56db\u79cd\u60c5\u51b5\u4e0e\u5404\u5411\u540c\u6027\u7684\u60c5\u51b5\u76f8\u540c\uff0c\u5373a)\u5355\u5143\u5728\u8fb9\u754c\u4e0a\uff0cb)\u6709\u66f4\u7ec6\u7684\u90bb\u5c45\u5355\u5143\uff0cc)\u90bb\u5c45\u65e2\u4e0d\u7c97\u4e5f\u4e0d\u7ec6\uff0cd)\u90bb\u5c45\u66f4\u7c97\u3002 \u7136\u800c\uff0c\u6211\u4eec\u51b3\u5b9a\u54ea\u79cd\u60c5\u51b5\u7684\u65b9\u5f0f\u662f\u6309\u7167\u4ecb\u7ecd\u4e2d\u63cf\u8ff0\u7684\u65b9\u5f0f\u8fdb\u884c\u4fee\u6539\u7684\u3002\n\n  template <int dim> \n  void DGMethod<dim>::assemble_system() \n  { \n    const unsigned int dofs_per_cell = dof_handler.get_fe().n_dofs_per_cell(); \n    std::vector<types::global_dof_index> dofs(dofs_per_cell); \n    std::vector<types::global_dof_index> dofs_neighbor(dofs_per_cell); \n\n    const UpdateFlags update_flags = update_values | update_gradients | \n                                     update_quadrature_points | \n                                     update_JxW_values; \n\n    const UpdateFlags face_update_flags = \n      update_values | update_quadrature_points | update_JxW_values | \n      update_normal_vectors; \n\n    const UpdateFlags neighbor_face_update_flags = update_values; \n\n    FEValues<dim>        fe_v(mapping, fe, quadrature, update_flags); \n    FEFaceValues<dim>    fe_v_face(mapping, \n                                fe, \n                                face_quadrature, \n                                face_update_flags); \n    FESubfaceValues<dim> fe_v_subface(mapping, \n                                      fe, \n                                      face_quadrature, \n                                      face_update_flags); \n    FEFaceValues<dim>    fe_v_face_neighbor(mapping, \n                                         fe, \n                                         face_quadrature, \n                                         neighbor_face_update_flags); \n\n    FullMatrix<double> ui_vi_matrix(dofs_per_cell, dofs_per_cell); \n    FullMatrix<double> ue_vi_matrix(dofs_per_cell, dofs_per_cell); \n\n    FullMatrix<double> ui_ve_matrix(dofs_per_cell, dofs_per_cell); \n    FullMatrix<double> ue_ve_matrix(dofs_per_cell, dofs_per_cell); \n\n    Vector<double> cell_vector(dofs_per_cell); \n\n    for (const auto &cell : dof_handler.active_cell_iterators()) \n      { \n        ui_vi_matrix = 0; \n        cell_vector  = 0; \n\n        fe_v.reinit(cell); \n\n        dg.assemble_cell_term(fe_v, ui_vi_matrix, cell_vector); \n\n        cell->get_dof_indices(dofs); \n\n        for (const auto face_no : cell->face_indices()) \n          { \n            const auto face = cell->face(face_no); \n\n// \u60c5\u51b5(a)\u3002\u8be5\u9762\u5728\u8fb9\u754c\u4e0a\u3002\n\n            if (face->at_boundary()) \n              { \n                fe_v_face.reinit(cell, face_no); \n\n                dg.assemble_boundary_term(fe_v_face, ui_vi_matrix, cell_vector); \n              } \n            else \n              { \n                Assert(cell->neighbor(face_no).state() == IteratorState::valid, \n                       ExcInternalError()); \n                const auto neighbor = cell->neighbor(face_no); \n\n// \u60c5\u51b5(b)\u3002\u8fd9\u662f\u4e00\u4e2a\u5185\u90e8\u9762\uff0c\u90bb\u5c45\u662f\u7cbe\u70bc\u7684\uff08\u6211\u4eec\u53ef\u4ee5\u901a\u8fc7\u8be2\u95ee\u5f53\u524d\u5355\u5143\u683c\u7684\u9762\u662f\u5426\u6709\u5b69\u5b50\u6765\u6d4b\u8bd5\uff09\u3002\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0c\u6211\u4eec\u9700\u8981\u5bf9 \"\u5b50\u9762 \"\u8fdb\u884c\u6574\u5408\uff0c\u5373\u5f53\u524d\u5355\u5143\u683c\u7684\u9762\u7684\u5b50\u5973\u3002            (\u6709\u4e00\u4e2a\u7a0d\u5fae\u4ee4\u4eba\u56f0\u60d1\u7684\u89d2\u843d\u6848\u4f8b\u3002\u5982\u679c\u6211\u4eec\u662f\u57281d\u4e2d--\u8bda\u7136\uff0c\u5f53\u524d\u7684\u7a0b\u5e8f\u548c\u5b83\u5bf9\u5404\u5411\u5f02\u6027\u7ec6\u5316\u7684\u6f14\u793a\u5e76\u4e0d\u7279\u522b\u76f8\u5173--\u90a3\u4e48\u5355\u5143\u95f4\u7684\u9762\u603b\u662f\u76f8\u540c\u7684\uff1a\u5b83\u4eec\u53ea\u662f\u9876\u70b9\u3002\u6362\u53e5\u8bdd\u8bf4\uff0c\u57281d\u4e2d\uff0c\u6211\u4eec\u4e0d\u5e0c\u671b\u5bf9\u4e0d\u540c\u5c42\u6b21\u7684\u5355\u5143\u4e4b\u95f4\u7684\u9762\u8fdb\u884c\u4e0d\u540c\u7684\u5904\u7406\u3002\u6211\u4eec\u5728\u8fd9\u91cc\u68c0\u67e5\u7684\u6761\u4ef6`face->has_children()`\u786e\u4fdd\u4e86\u8fd9\u4e00\u70b9\uff1a\u57281d\u4e2d\uff0c\u8fd9\u4e2a\u51fd\u6570\u603b\u662f\u8fd4\u56de`false`\uff0c\u56e0\u6b64\u57281d\u4e2d\u6211\u4eec\u4e0d\u4f1a\u8fdb\u5165\u8fd9\u4e2a`if`\u5206\u652f\u3002\u4f46\u6211\u4eec\u5c06\u4e0d\u5f97\u4e0d\u5728\u4e0b\u9762\u7684\u60c5\u51b5\uff08c\uff09\u4e2d\u56de\u5230\u8fd9\u4e2a\u89d2\u843d\u3002\n\n                if (face->has_children()) \n                  { \n\n// \u6211\u4eec\u9700\u8981\u77e5\u9053\uff0c\u54ea\u4e2a\u90bb\u5c45\u7684\u9762\u671d\u5411\u6211\u4eec\u5355\u5143\u683c\u7684\u65b9\u5411\u3002\u4f7f\u7528  @p  neighbor_face_no \u51fd\u6570\uff0c\u6211\u4eec\u53ef\u4ee5\u5f97\u5230\u7c97\u90bb\u548c\u975e\u7c97\u90bb\u7684\u8fd9\u4e9b\u4fe1\u606f\u3002\n\n                    const unsigned int neighbor2 = \n                      cell->neighbor_face_no(face_no); \n\n// \u73b0\u5728\u6211\u4eec\u5bf9\u6240\u6709\u7684\u5b50\u8138\u8fdb\u884c\u5faa\u73af\uff0c\u4e5f\u5c31\u662f\u5f53\u524d\u8138\u7684\u5b50\u8138\u548c\u53ef\u80fd\u7684\u5b59\u5b50\u8138\u3002\n\n                    for (unsigned int subface_no = 0; \n                         subface_no < face->n_active_descendants(); \n                         ++subface_no) \n                      { \n\n// \u4e3a\u4e86\u5f97\u5230\u5f53\u524d\u5b50\u9762\u540e\u9762\u7684\u5355\u5143\uff0c\u6211\u4eec\u53ef\u4ee5\u4f7f\u7528 @p neighbor_child_on_subface \u51fd\u6570\u3002\u5b83\u7167\u987e\u5230\u4e86\u6240\u6709\u5404\u5411\u5f02\u6027\u7ec6\u5316\u548c\u975e\u6807\u51c6\u9762\u7684\u590d\u6742\u60c5\u51b5\u3002\n\n                        const auto neighbor_child = \n                          cell->neighbor_child_on_subface(face_no, subface_no); \n                        Assert(!neighbor_child->has_children(), \n                               ExcInternalError()); \n\n// \u8fd9\u4e2a\u6848\u4f8b\u7684\u5176\u4f59\u90e8\u5206\u6ca1\u6709\u53d8\u5316\u3002\n\n                        ue_vi_matrix = 0; \n                        ui_ve_matrix = 0; \n                        ue_ve_matrix = 0; \n\n                        fe_v_subface.reinit(cell, face_no, subface_no); \n                        fe_v_face_neighbor.reinit(neighbor_child, neighbor2); \n\n                        dg.assemble_face_term(fe_v_subface, \n                                              fe_v_face_neighbor, \n                                              ui_vi_matrix, \n                                              ue_vi_matrix, \n                                              ui_ve_matrix, \n                                              ue_ve_matrix); \n\n                        neighbor_child->get_dof_indices(dofs_neighbor); \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                              system_matrix.add(dofs[i], \n                                                dofs_neighbor[j], \n                                                ue_vi_matrix(i, j)); \n                              system_matrix.add(dofs_neighbor[i], \n                                                dofs[j], \n                                                ui_ve_matrix(i, j)); \n                              system_matrix.add(dofs_neighbor[i], \n                                                dofs_neighbor[j], \n                                                ue_ve_matrix(i, j)); \n                            } \n                      } \n                  } \n                else \n                  { \n\n//\u60c5\u51b5(c)\u3002\u5982\u679c\u8fd9\u662f\u4e00\u4e2a\u5185\u90e8\u9762\uff0c\u5e76\u4e14\u90bb\u5c45\u6ca1\u6709\u8fdb\u4e00\u6b65\u7ec6\u5316\uff0c\u6211\u4eec\u5c31\u4f1a\u5f97\u5230\u8fd9\u91cc\uff08\u6216\u8005\uff0c\u5982\u4e0a\u6240\u8ff0\uff0c\u6211\u4eec\u662f\u57281d\u4e2d\uff0c\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0c\u6211\u4eec\u5bf9\u6bcf\u4e2a\u5185\u90e8\u9762\u90fd\u4f1a\u5f97\u5230\u8fd9\u91cc\uff09\u3002\u7136\u540e\u6211\u4eec\u9700\u8981\u51b3\u5b9a\u662f\u5426\u8981\u5bf9\u5f53\u524d\u9762\u8fdb\u884c\u6574\u5408\u3002\u5982\u679c\u90bb\u5c45\u5b9e\u9645\u4e0a\u66f4\u7c97\uff0c\u90a3\u4e48\u6211\u4eec\u5c31\u5ffd\u7565\u8fd9\u4e2a\u9762\uff0c\u800c\u662f\u5728\u8bbf\u95ee\u90bb\u5c45\u5355\u5143\u5e76\u67e5\u770b\u5f53\u524d\u9762\u7684\u65f6\u5019\u5904\u7406\u5b83\uff08\u9664\u4e86\u57281d\u4e2d\uff0c\u5982\u4e0a\u6240\u8ff0\uff0c\u8fd9\u4e0d\u4f1a\u53d1\u751f\uff09\u3002\n\n                    if (dim > 1 && cell->neighbor_is_coarser(face_no)) \n                      continue; \n\n// \u53e6\u4e00\u65b9\u9762\uff0c\u5982\u679c\u90bb\u5c45\u662f\u66f4\u7cbe\u7ec6\u7684\uff0c\u90a3\u4e48\u6211\u4eec\u5df2\u7ecf\u5904\u7406\u4e86\u4e0a\u9762(b)\u60c5\u51b5\u4e0b\u7684\u8138\uff081d\u9664\u5916\uff09\u3002\u6240\u4ee5\u5bf9\u4e8e2d\u548c3d\uff0c\u6211\u4eec\u53ea\u9700\u8981\u51b3\u5b9a\u662f\u8981\u5904\u7406\u6765\u81ea\u5f53\u524d\u4e00\u4fa7\u7684\u540c\u4e00\u5c42\u6b21\u7684\u5355\u5143\u683c\u4e4b\u95f4\u7684\u9762\uff0c\u8fd8\u662f\u6765\u81ea\u90bb\u63a5\u4e00\u4fa7\u7684\u9762\u3002 \u6211\u4eec\u901a\u8fc7\u5f15\u5165\u4e00\u4e2a\u5e73\u5c40\u6765\u505a\u5230\u8fd9\u4e00\u70b9\u3002          \u6211\u4eec\u53ea\u53d6\u7d22\u5f15\u8f83\u5c0f\u7684\u5355\u5143\u683c\uff08\u5728\u5f53\u524d\u7ec6\u5316\u7ea7\u522b\u5185\uff09\u3002\u57281d\u4e2d\uff0c\u6211\u4eec\u53d6\u8f83\u7c97\u7684\u5355\u5143\uff0c\u6216\u8005\u5982\u679c\u5b83\u4eec\u5728\u540c\u4e00\u5c42\u6b21\uff0c\u5219\u53d6\u8be5\u5c42\u6b21\u4e2d\u6307\u6570\u8f83\u5c0f\u7684\u5355\u5143\u3002\u8fd9\u5c31\u5bfc\u81f4\u4e86\u4e00\u4e2a\u590d\u6742\u7684\u6761\u4ef6\uff0c\u5e0c\u671b\u5728\u4e0a\u9762\u7684\u63cf\u8ff0\u4e2d\u53ef\u4ee5\u7406\u89e3\u3002\n\n                    if (((dim > 1) && (cell->index() < neighbor->index())) || \n                        ((dim == 1) && ((cell->level() < neighbor->level()) || \n                                        ((cell->level() == neighbor->level()) && \n                                         (cell->index() < neighbor->index()))))) \n                      { \n\n// \u8fd9\u91cc\u6211\u4eec\u77e5\u9053\uff0c\u90bb\u5c45\u4e0d\u662f\u66f4\u7c97\u7684\uff0c\u6240\u4ee5\u6211\u4eec\u53ef\u4ee5\u4f7f\u7528\u901a\u5e38\u7684  @p neighbor_of_neighbor  \u51fd\u6570\u3002\u7136\u800c\uff0c\u6211\u4eec\u4e5f\u53ef\u4ee5\u4f7f\u7528\u66f4\u901a\u7528\u7684 @p neighbor_face_no \u51fd\u6570\u3002\n\n                        const unsigned int neighbor2 = \n                          cell->neighbor_of_neighbor(face_no); \n\n                        ue_vi_matrix = 0; \n                        ui_ve_matrix = 0; \n                        ue_ve_matrix = 0; \n\n                        fe_v_face.reinit(cell, face_no); \n                        fe_v_face_neighbor.reinit(neighbor, neighbor2); \n\n                        dg.assemble_face_term(fe_v_face, \n                                              fe_v_face_neighbor, \n                                              ui_vi_matrix, \n                                              ue_vi_matrix, \n                                              ui_ve_matrix, \n                                              ue_ve_matrix); \n\n                        neighbor->get_dof_indices(dofs_neighbor); \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                              system_matrix.add(dofs[i], \n                                                dofs_neighbor[j], \n                                                ue_vi_matrix(i, j)); \n                              system_matrix.add(dofs_neighbor[i], \n                                                dofs[j], \n                                                ui_ve_matrix(i, j)); \n                              system_matrix.add(dofs_neighbor[i], \n                                                dofs_neighbor[j], \n                                                ue_ve_matrix(i, j)); \n                            } \n                      } \n\n// \u6211\u4eec\u4e0d\u9700\u8981\u8003\u8651\u60c5\u51b5(d)\uff0c\u56e0\u4e3a\u8fd9\u4e9b\u9762\u5728\u60c5\u51b5(b)\u4e2d\u88ab \"\u4ece\u53e6\u4e00\u4fa7 \"\u5904\u7406\u3002\n\n                  } \n              } \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            system_matrix.add(dofs[i], dofs[j], ui_vi_matrix(i, j)); \n\n        for (unsigned int i = 0; i < dofs_per_cell; ++i) \n          right_hand_side(dofs[i]) += cell_vector(i); \n      } \n  } \n// @sect3{Solver}  \n\n// \u5bf9\u4e8e\u8fd9\u4e2a\u7b80\u5355\u7684\u95ee\u9898\uff0c\u6211\u4eec\u518d\u6b21\u4f7f\u7528\u7b80\u5355\u7684Richardson\u8fed\u4ee3\u6cd5\u3002\u8be5\u6c42\u89e3\u5668\u5b8c\u5168\u4e0d\u53d7\u6211\u4eec\u5404\u5411\u5f02\u6027\u53d8\u5316\u7684\u5f71\u54cd\u3002\n\n  template <int dim> \n  void DGMethod<dim>::solve(Vector<double> &solution) \n  { \n    SolverControl                    solver_control(1000, 1e-12, false, false); \n    SolverRichardson<Vector<double>> solver(solver_control); \n\n    PreconditionBlockSSOR<SparseMatrix<double>> preconditioner; \n\n    preconditioner.initialize(system_matrix, fe.n_dofs_per_cell()); \n\n    solver.solve(system_matrix, solution, right_hand_side, preconditioner); \n  } \n// @sect3{Refinement}  \n\n// \u6211\u4eec\u6839\u636e step-12 \u4e2d\u4f7f\u7528\u7684\u76f8\u540c\u7684\u7b80\u5355\u7ec6\u5316\u6807\u51c6\u6765\u7ec6\u5316\u7f51\u683c\uff0c\u5373\u5bf9\u89e3\u7684\u68af\u5ea6\u7684\u8fd1\u4f3c\u3002\n\n  template <int dim> \n  void DGMethod<dim>::refine_grid() \n  { \n    Vector<float> gradient_indicator(triangulation.n_active_cells()); \n\n// \u6211\u4eec\u5bf9\u68af\u5ea6\u8fdb\u884c\u8fd1\u4f3c\u8ba1\u7b97\u3002\n\n    DerivativeApproximation::approximate_gradient(mapping, \n                                                  dof_handler, \n                                                  solution2, \n                                                  gradient_indicator); \n\n//\u5e76\u5bf9\u5176\u8fdb\u884c\u7f29\u653e\uff0c\u4ee5\u83b7\u5f97\u4e00\u4e2a\u8bef\u5dee\u6307\u6807\u3002\n\n    for (const auto &cell : triangulation.active_cell_iterators()) \n      gradient_indicator[cell->active_cell_index()] *= \n        std::pow(cell->diameter(), 1 + 1.0 * dim / 2); \n\n// \u7136\u540e\u6211\u4eec\u7528\u8fd9\u4e2a\u6307\u6807\u6765\u6807\u8bb0\u8bef\u5dee\u6307\u6807\u6700\u9ad8\u768430%\u7684\u5355\u5143\u683c\u6765\u8fdb\u884c\u7cbe\u70bc\u3002\n\n    GridRefinement::refine_and_coarsen_fixed_number(triangulation, \n                                                    gradient_indicator, \n                                                    0.3, \n                                                    0.1); \n\n// \u73b0\u5728\uff0c\u7ec6\u5316\u6807\u5fd7\u88ab\u8bbe\u7f6e\u4e3a\u90a3\u4e9b\u5177\u6709\u5927\u8bef\u5dee\u6307\u6807\u7684\u5355\u5143\u3002\u5982\u679c\u4e0d\u505a\u4efb\u4f55\u6539\u53d8\uff0c\u8fd9\u4e9b\u5355\u5143\u5c06\u88ab\u7b49\u5411\u7ec6\u5316\u3002\u5982\u679c\u7ed9\u8fd9\u4e2a\u51fd\u6570\u7684 @p anisotropic \u6807\u5fd7\u88ab\u8bbe\u7f6e\uff0c\u6211\u4eec\u73b0\u5728\u8c03\u7528set_anisotropic_flags()\u51fd\u6570\uff0c\u8be5\u51fd\u6570\u4f7f\u7528\u8df3\u8f6c\u6307\u6807\u5c06\u4e00\u4e9b\u7ec6\u5316\u6807\u5fd7\u91cd\u7f6e\u4e3a\u5404\u5411\u5f02\u6027\u7ec6\u5316\u3002\n\n    if (anisotropic) \n      set_anisotropic_flags(); \n\n// \u73b0\u5728\u6267\u884c\u8003\u8651\u5404\u5411\u5f02\u6027\u4ee5\u53ca\u5404\u5411\u540c\u6027\u7684\u7ec6\u5316\u6807\u5fd7\u7684\u7ec6\u5316\u3002\n\n    triangulation.execute_coarsening_and_refinement(); \n  } \n\n// \u4e00\u65e6\u9519\u8bef\u6307\u6807\u88ab\u8bc4\u4f30\uff0c\u8bef\u5dee\u6700\u5927\u7684\u5355\u5143\u88ab\u6807\u8bb0\u4e3a\u7ec6\u5316\uff0c\u6211\u4eec\u8981\u518d\u6b21\u5faa\u73af\u8fd9\u4e9b\u88ab\u6807\u8bb0\u7684\u5355\u5143\uff0c\u4ee5\u51b3\u5b9a\u5b83\u4eec\u662f\u5426\u9700\u8981\u5404\u5411\u540c\u6027\u7684\u7ec6\u5316\u6216\u5404\u5411\u5f02\u6027\u7684\u7ec6\u5316\u66f4\u4e3a\u5408\u9002\u3002\u8fd9\u5c31\u662f\u5728\u4ecb\u7ecd\u4e2d\u89e3\u91ca\u7684\u5404\u5411\u5f02\u6027\u8df3\u8dc3\u6307\u6807\u3002\n\n  template <int dim> \n  void DGMethod<dim>::set_anisotropic_flags() \n  { \n\n// \u6211\u4eec\u60f3\u5728\u88ab\u6807\u8bb0\u7684\u5355\u5143\u683c\u7684\u9762\u4e0a\u8bc4\u4f30\u8df3\u8dc3\uff0c\u6240\u4ee5\u6211\u4eec\u9700\u8981\u4e00\u4e9b\u5bf9\u8c61\u6765\u8bc4\u4f30\u9762\u4e0a\u7684\u89e3\u51b3\u65b9\u6848\u7684\u503c\u3002\n\n    UpdateFlags face_update_flags = \n      UpdateFlags(update_values | update_JxW_values); \n\n    FEFaceValues<dim>    fe_v_face(mapping, \n                                fe, \n                                face_quadrature, \n                                face_update_flags); \n    FESubfaceValues<dim> fe_v_subface(mapping, \n                                      fe, \n                                      face_quadrature, \n                                      face_update_flags); \n    FEFaceValues<dim>    fe_v_face_neighbor(mapping, \n                                         fe, \n                                         face_quadrature, \n                                         update_values); \n\n// \u73b0\u5728\u6211\u4eec\u9700\u8981\u5bf9\u6240\u6709\u6d3b\u52a8\u5355\u5143\u8fdb\u884c\u5faa\u73af\u3002\n\n    for (const auto &cell : dof_handler.active_cell_iterators()) \n\n// \u6211\u4eec\u53ea\u9700\u8981\u8003\u8651\u90a3\u4e9b\u88ab\u6807\u8bb0\u4e3a\u7ec6\u5316\u7684\u5355\u5143\u3002\n\n      if (cell->refine_flag_set()) \n        { \n          Point<dim> jump; \n          Point<dim> area; \n\n          for (const auto face_no : cell->face_indices()) \n            { \n              const auto face = cell->face(face_no); \n\n              if (!face->at_boundary()) \n                { \n                  Assert(cell->neighbor(face_no).state() == \n                           IteratorState::valid, \n                         ExcInternalError()); \n                  const auto neighbor = cell->neighbor(face_no); \n\n                  std::vector<double> u(fe_v_face.n_quadrature_points); \n                  std::vector<double> u_neighbor(fe_v_face.n_quadrature_points); \n\n// \u5728\u6c47\u7f16\u4f8b\u7a0b\u4e2d\u770b\u5230\u7684\u56db\u79cd\u4e0d\u540c\u7684\u90bb\u5c45\u5173\u7cfb\u7684\u60c5\u51b5\u5728\u8fd9\u91cc\u4ee5\u540c\u6837\u7684\u65b9\u5f0f\u91cd\u590d\u3002\n\n                  if (face->has_children()) \n                    { \n\n// \u90bb\u5c45\u88ab\u5b8c\u5584\u3002 \u9996\u5148\uff0c\u6211\u4eec\u5b58\u50a8\u4fe1\u606f\uff0c\u5373\u90bb\u5c45\u7684\u54ea\u4e2a\u9762\u6307\u5411\u6211\u4eec\u5f53\u524d\u5355\u5143\u7684\u65b9\u5411\u3002\u8fd9\u4e2a\u5c5e\u6027\u5c06\u88ab\u7ee7\u627f\u7ed9\u5b50\u4ee3\u3002\n\n                      unsigned int neighbor2 = cell->neighbor_face_no(face_no); \n\n// \u73b0\u5728\u6211\u4eec\u5bf9\u6240\u6709\u7684\u5b50\u9762\u8fdb\u884c\u5faa\u73af\u3002\n\n                      for (unsigned int subface_no = 0; \n                           subface_no < face->n_active_descendants(); \n                           ++subface_no) \n                        { \n\n//\u5f97\u5230\u4e00\u4e2a\u8fed\u4ee3\u5668\uff0c\u6307\u5411\u5f53\u524d\u5b50\u9762\u540e\u9762\u7684\u5355\u5143\u683c...\n\n                          const auto neighbor_child = \n                            cell->neighbor_child_on_subface(face_no, \n                                                            subface_no); \n                          Assert(!neighbor_child->has_children(), \n                                 ExcInternalError()); \n\n// ...\u5e76\u91cd\u65b0\u542f\u52a8\u5404\u81ea\u7684FEFaceValues\u548cFESSubFaceValues\u5bf9\u8c61\u3002\n\n                          fe_v_subface.reinit(cell, face_no, subface_no); \n                          fe_v_face_neighbor.reinit(neighbor_child, neighbor2); \n\n// \u6211\u4eec\u83b7\u5f97\u4e86\u51fd\u6570\u503c\n\n                          fe_v_subface.get_function_values(solution2, u); \n                          fe_v_face_neighbor.get_function_values(solution2, \n                                                                 u_neighbor); \n\n//\u4ee5\u53ca\u6b63\u4ea4\u6743\u91cd\uff0c\u4e58\u4ee5\u96c5\u5404\u5e03\u884c\u5217\u5f0f\u3002\n\n                          const std::vector<double> &JxW = \n                            fe_v_subface.get_JxW_values(); \n\n// \u73b0\u5728\u6211\u4eec\u5728\u6240\u6709\u7684\u6b63\u4ea4\u70b9\u4e0a\u5faa\u73af\u3002\n\n                          for (unsigned int x = 0; \n                               x < fe_v_subface.n_quadrature_points; \n                               ++x) \n                            { \n\n//\u5e76\u6574\u5408\u89e3\u51b3\u65b9\u6848\u7684\u8df3\u8dc3\u7684\u7edd\u5bf9\u503c\uff0c\u5373\u5206\u522b\u4ece\u5f53\u524d\u5355\u5143\u548c\u90bb\u8fd1\u5355\u5143\u770b\u5230\u7684\u51fd\u6570\u503c\u7684\u7edd\u5bf9\u503c\u3002\u6211\u4eec\u77e5\u9053\uff0c\u524d\u4e24\u4e2a\u9762\u4e0e\u5355\u5143\u683c\u4e0a\u7684\u7b2c\u4e00\u4e2a\u5750\u6807\u65b9\u5411\u6b63\u4ea4\uff0c\u540e\u4e24\u4e2a\u9762\u4e0e\u7b2c\u4e8c\u4e2a\u5750\u6807\u65b9\u5411\u6b63\u4ea4\uff0c\u4ee5\u6b64\u7c7b\u63a8\uff0c\u6240\u4ee5\u6211\u4eec\u5c06\u8fd9\u4e9b\u503c\u7d2f\u79ef\u6210\u5177\u6709 <code>dim</code> \u6210\u5206\u7684\u5411\u91cf\u3002\n\n                              jump[face_no / 2] += \n                                std::abs(u[x] - u_neighbor[x]) * JxW[x]; \n\n// \u6211\u4eec\u8fd8\u5c06\u7f29\u653e\u540e\u7684\u6743\u91cd\u76f8\u52a0\uff0c\u4ee5\u83b7\u5f97\u8138\u90e8\u7684\u91cf\u5ea6\u3002\n\n                              area[face_no / 2] += JxW[x]; \n                            } \n                        } \n                    } \n                  else \n                    { \n                      if (!cell->neighbor_is_coarser(face_no)) \n                        { \n\n// \u6211\u4eec\u7684\u5f53\u524d\u5355\u5143\u548c\u90bb\u5c45\u5728\u6240\u8003\u8651\u7684\u9762\u6709\u76f8\u540c\u7684\u7ec6\u5316\u3002\u9664\u6b64\u4ee5\u5916\uff0c\u6211\u4eec\u7684\u505a\u6cd5\u4e0e\u4e0a\u8ff0\u60c5\u51b5\u4e0b\u7684\u4e00\u4e2a\u5b50\u5355\u5143\u7684\u505a\u6cd5\u57fa\u672c\u76f8\u540c\u3002\n\n                          unsigned int neighbor2 = \n                            cell->neighbor_of_neighbor(face_no); \n\n                          fe_v_face.reinit(cell, face_no); \n                          fe_v_face_neighbor.reinit(neighbor, neighbor2); \n\n                          fe_v_face.get_function_values(solution2, u); \n                          fe_v_face_neighbor.get_function_values(solution2, \n                                                                 u_neighbor); \n\n                          const std::vector<double> &JxW = \n                            fe_v_face.get_JxW_values(); \n\n                          for (unsigned int x = 0; \n                               x < fe_v_face.n_quadrature_points; \n                               ++x) \n                            { \n                              jump[face_no / 2] += \n                                std::abs(u[x] - u_neighbor[x]) * JxW[x]; \n                              area[face_no / 2] += JxW[x]; \n                            } \n                        } \n                      else // i.e. neighbor is coarser than cell \n                        { \n\n// \u73b0\u5728\u90bb\u5c45\u5b9e\u9645\u4e0a\u66f4\u7c97\u4e86\u3002\u8fd9\u79cd\u60c5\u51b5\u662f\u65b0\u7684\uff0c\u56e0\u4e3a\u5b83\u6ca1\u6709\u51fa\u73b0\u5728\u6c47\u7f16\u7a0b\u5e8f\u4e2d\u3002\u5728\u8fd9\u91cc\uff0c\u6211\u4eec\u5fc5\u987b\u8003\u8651\u5b83\uff0c\u4f46\u8fd9\u5e76\u4e0d\u592a\u590d\u6742\u3002\u6211\u4eec\u53ea\u9700\u4f7f\u7528  @p  neighbor_of_coarser_neighbor \u51fd\u6570\uff0c\u5b83\u518d\u6b21\u81ea\u884c\u5904\u7406\u5404\u5411\u5f02\u6027\u7684\u7ec6\u5316\u548c\u975e\u6807\u51c6\u9762\u7684\u65b9\u5411\u3002\n\n                          std::pair<unsigned int, unsigned int> \n                            neighbor_face_subface = \n                              cell->neighbor_of_coarser_neighbor(face_no); \n                          Assert(neighbor_face_subface.first < cell->n_faces(), \n                                 ExcInternalError()); \n                          Assert(neighbor_face_subface.second < \n                                   neighbor->face(neighbor_face_subface.first) \n                                     ->n_active_descendants(), \n                                 ExcInternalError()); \n                          Assert(neighbor->neighbor_child_on_subface( \n                                   neighbor_face_subface.first, \n                                   neighbor_face_subface.second) == cell, \n                                 ExcInternalError()); \n\n                          fe_v_face.reinit(cell, face_no); \n                          fe_v_subface.reinit(neighbor, \n                                              neighbor_face_subface.first, \n                                              neighbor_face_subface.second); \n\n                          fe_v_face.get_function_values(solution2, u); \n                          fe_v_subface.get_function_values(solution2, \n                                                           u_neighbor); \n\n                          const std::vector<double> &JxW = \n                            fe_v_face.get_JxW_values(); \n\n                          for (unsigned int x = 0; \n                               x < fe_v_face.n_quadrature_points; \n                               ++x) \n                            { \n                              jump[face_no / 2] += \n                                std::abs(u[x] - u_neighbor[x]) * JxW[x]; \n                              area[face_no / 2] += JxW[x]; \n                            } \n                        } \n                    } \n                } \n            } \n\n// \u73b0\u5728\u6211\u4eec\u5206\u6790\u4e00\u4e0b\u5e73\u5747\u8df3\u52a8\u7684\u5927\u5c0f\uff0c\u6211\u4eec\u7528\u8df3\u52a8\u9664\u4ee5\u5404\u9762\u7684\u5ea6\u91cf\u5f97\u5230\u3002\n\n          std::array<double, dim> average_jumps; \n          double                  sum_of_average_jumps = 0.; \n          for (unsigned int i = 0; i < dim; ++i) \n            { \n              average_jumps[i] = jump(i) / area(i); \n              sum_of_average_jumps += average_jumps[i]; \n            } \n\n// \u73b0\u5728\u6211\u4eec\u5728\u5355\u5143\u683c\u7684 <code>dim</code> \u5750\u6807\u65b9\u5411\u4e0a\u8fdb\u884c\u5faa\u73af\uff0c\u5e76\u6bd4\u8f83\u4e0e\u8be5\u65b9\u5411\u6b63\u4ea4\u7684\u9762\u7684\u5e73\u5747\u8df3\u8dc3\u548c\u4e0e\u5176\u4f59\u65b9\u5411\u6b63\u4ea4\u7684\u9762\u7684\u5e73\u5747\u8df3\u8dc3\u3002\u5982\u679c\u524d\u8005\u6bd4\u540e\u8005\u5927\u4e00\u4e2a\u7ed9\u5b9a\u7684\u7cfb\u6570\uff0c\u6211\u4eec\u53ea\u6cbf\u5e3d\u8f74\u8fdb\u884c\u7ec6\u5316\u3002\u5426\u5219\uff0c\u6211\u4eec\u4e0d\u6539\u53d8\u7ec6\u5316\u6807\u5fd7\uff0c\u5bfc\u81f4\u5404\u5411\u540c\u6027\u7684\u7ec6\u5316\u3002\n\n          for (unsigned int i = 0; i < dim; ++i) \n            if (average_jumps[i] > anisotropic_threshold_ratio * \n                                     (sum_of_average_jumps - average_jumps[i])) \n              cell->set_refine_flag(RefinementCase<dim>::cut_axis(i)); \n        } \n  } \n// @sect3{The Rest}  \n\n// \u7a0b\u5e8f\u7684\u5176\u4f59\u90e8\u5206\u975e\u5e38\u9075\u5faa\u4e4b\u524d\u6559\u7a0b\u7a0b\u5e8f\u7684\u65b9\u6848\u3002\u6211\u4eec\u4ee5VTU\u683c\u5f0f\u8f93\u51fa\u7f51\u683c\uff08\u5c31\u50cf\u6211\u4eec\u5728 step-1 \u4e2d\u6240\u505a\u7684\u90a3\u6837\uff0c\u4f8b\u5982\uff09\uff0c\u5e76\u4ee5VTU\u683c\u5f0f\u8f93\u51fa\u53ef\u89c6\u5316\uff0c\u6211\u4eec\u51e0\u4e4e\u603b\u662f\u8fd9\u6837\u505a\u3002\n\n  template <int dim> \n  void DGMethod<dim>::output_results(const unsigned int cycle) const \n  { \n    std::string refine_type; \n    if (anisotropic) \n      refine_type = \".aniso\"; \n    else \n      refine_type = \".iso\"; \n\n    { \n      const std::string filename = \n        \"grid-\" + std::to_string(cycle) + refine_type + \".svg\"; \n      std::cout << \"   Writing grid to <\" << filename << \">...\" << std::endl; \n      std::ofstream svg_output(filename); \n\n      GridOut grid_out; \n      grid_out.write_svg(triangulation, svg_output); \n    } \n\n    { \n      const std::string filename = \n        \"sol-\" + std::to_string(cycle) + refine_type + \".vtu\"; \n      std::cout << \"   Writing solution to <\" << filename << \">...\" \n                << std::endl; \n      std::ofstream gnuplot_output(filename); \n\n      DataOut<dim> data_out; \n      data_out.attach_dof_handler(dof_handler); \n      data_out.add_data_vector(solution2, \"u\"); \n\n      data_out.build_patches(degree); \n\n      data_out.write_vtu(gnuplot_output); \n    } \n  } \n\n  template <int dim> \n  void DGMethod<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\n// \u521b\u5efa\u77e9\u5f62\u57df\u3002\n\n            Point<dim> p1, p2; \n            p1(0) = 0; \n            p1(0) = -1; \n            for (unsigned int i = 0; i < dim; ++i) \n              p2(i) = 1.; \n\n// \u8c03\u6574\u4e0d\u540c\u65b9\u5411\u7684\u5355\u5143\u6570\uff0c\u4ee5\u83b7\u5f97\u539f\u59cb\u7f51\u683c\u7684\u5b8c\u5168\u5404\u5411\u540c\u6027\u7684\u5355\u5143\u3002\n\n            std::vector<unsigned int> repetitions(dim, 1); \n            repetitions[0] = 2; \n            GridGenerator::subdivided_hyper_rectangle(triangulation, \n                                                      repetitions, \n                                                      p1, \n                                                      p2); \n\n            triangulation.refine_global(5 - dim); \n          } \n        else \n          refine_grid(); \n\n        std::cout << \"   Number of active cells:       \" \n                  << triangulation.n_active_cells() << std::endl; \n\n        setup_system(); \n\n        std::cout << \"   Number of degrees of freedom: \" << dof_handler.n_dofs() \n                  << std::endl; \n\n        Timer assemble_timer; \n        assemble_system(); \n        std::cout << \"   Time of assemble_system: \" << assemble_timer.cpu_time() \n                  << std::endl; \n        solve(solution2); \n\n        output_results(cycle); \n\n        std::cout << std::endl; \n      } \n  } \n} // namespace Step30 \n\nint main() \n{ \n  try \n    { \n      using namespace Step30; \n\n// \u5982\u679c\u4f60\u60f3\u4ee53D\u65b9\u5f0f\u8fd0\u884c\u7a0b\u5e8f\uff0c\u53ea\u9700\u5c06\u4e0b\u9762\u4e00\u884c\u6539\u4e3a <code>const unsigned int dim = 3;</code>  \u3002\n\n      const unsigned int dim = 2; \n\n      { \n\n// \u9996\u5148\uff0c\u6211\u4eec\u7528\u5404\u5411\u540c\u6027\u7684\u7ec6\u5316\u65b9\u6cd5\u8fdb\u884c\u4e00\u6b21\u8fd0\u884c\u3002\n\n        std::cout << \"Performing a \" << dim \n                  << \"D run with isotropic refinement...\" << std::endl \n                  << \"------------------------------------------------\" \n                  << std::endl; \n        DGMethod<dim> dgmethod_iso(false); \n        dgmethod_iso.run(); \n      } \n\n      { \n\n// \u73b0\u5728\u6211\u4eec\u8fdb\u884c\u7b2c\u4e8c\u6b21\u8fd0\u884c\uff0c\u8fd9\u6b21\u662f\u5404\u5411\u5f02\u6027\u7684\u7ec6\u5316\u3002\n\n        std::cout << std::endl \n                  << \"Performing a \" << dim \n                  << \"D run with anisotropic refinement...\" << std::endl \n                  << \"--------------------------------------------------\" \n                  << std::endl; \n        DGMethod<dim> dgmethod_aniso(true); \n        dgmethod_aniso.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      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", "meta": {"hexsha": "712d1a46b1f72b8da8d38a5226f4707d758879e4", "size": 34709, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-30/step-30.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-30/step-30.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-30/step-30.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": 36.005186722, "max_line_length": 311, "alphanum_fraction": 0.5032988562, "num_tokens": 10154, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548782017745, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.45115573042958285}}
{"text": "#ifndef pgl_hpp\n#define pgl_hpp\n#include <vector>\n#include <set>\n#include <stdexcept>\n#include <cstring>\n#include <cstdlib>\n#include <ostream>\n#include <functional>\n#include <queue>\n#include <map>\n#include <sstream>\n#include <iostream>\n#include <math.h>\n#include <random>\n#include <fstream>\n#include <regex>\n#ifdef __APPLE__\n#include <sys/uio.h>\n#include <unistd.h>\n#else\n#include <io.h>\n#include <direct.h>\n#include <windows.h>\n#include <tchar.h>\n#endif\n\n#include <stdio.h>\n#include <stdlib.h>\n\n#include <locale>\n#include <codecvt>\n#include <chrono>\n#include <thread>\n\n#include <glm/glm.hpp>\n#include <glm/gtc/type_ptr.hpp>\n#include <glm/gtc/matrix_inverse.hpp>\n#include <glm/gtc/matrix_transform.hpp>\n#include <glm/gtx/norm.hpp>\n#include <glm/gtx/transform.hpp>\n#include <glm/gtc/random.hpp>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n\n//glm modules\n//http://glm.g-truc.net/0.9.8/api/modules.html\n\n\nusing namespace std;\n\nnamespace PGL {\n\n    template <typename datum>\n    using Vector1 = std::vector<datum>;\n\n    template <typename datum>\n    using Vector2 = std::vector<std::vector<datum>>;\n\n    template <typename datum>\n    using Vector3 = std::vector<std::vector<std::vector<datum>>>;\n\n    typedef glm::highp_dvec2 Vector2d;\n    typedef glm::highp_dvec3 Vector3d;\n    typedef glm::highp_ivec2 Vector2i;\n    typedef glm::highp_ivec3 Vector3i;\n\n    typedef Vector1<Vector2d> Vector2d1;\n    typedef Vector2<Vector2d> Vector2d2;\n    typedef Vector3<Vector2d> Vector2d3;\n\n    typedef Vector1<Vector3d> Vector3d1;\n    typedef Vector2<Vector3d> Vector3d2;\n    typedef Vector3<Vector3d> Vector3d3;\n\n    typedef Vector1<bool> Vector1b1;\n    typedef Vector2<bool> Vector1b2;\n    typedef Vector3<bool> Vector1b3;\n\n    typedef Vector1<int> Vector1i1;\n    typedef Vector2<int> Vector1i2;\n    typedef Vector3<int> Vector1i3;\n\n    typedef Vector1<double> Vector1d1;\n    typedef Vector2<double> Vector1d2;\n    typedef Vector3<double> Vector1d3;\n\n    typedef Vector1<std::string> VectorStr1;\n    typedef Vector2<std::string> VectorStr2;\n    typedef Vector3<std::string> VectorStr3;\n\n\n    typedef Vector1<Vector2i> Vector2i1;\n    typedef Vector2<Vector2i> Vector2i2;\n    typedef Vector3<Vector2i> Vector2i3;\n\n    typedef Vector1<Vector3i> Vector3i1;\n    typedef Vector2<Vector3i> Vector3i2;\n    typedef Vector3<Vector3i> Vector3i3;\n\n    typedef Vector1<std::pair<int, int>> VectorPI1;\n    typedef Vector2<std::pair<int, int>> VectorPI2;\n    typedef Vector3<std::pair<int, int>> VectorPI3;\n\n    typedef Vector1<std::pair<bool, bool>> VectorPB1;\n    typedef Vector2<std::pair<bool, bool>> VectorPB2;\n    typedef Vector3<std::pair<bool, bool>> VectorPB3;\n\n    typedef std::tuple<int, int, int> TI3;\n    typedef Vector1<std::tuple<int, int, int>> VectorTI3;\n\n\n    static double DOUBLE_EPSILON = 1.0E-05;\n    static double Math_PI = 3.14159265358979323846;\n    static double SINGLE_EPSILON = 1.0E-05f;\n    static double MAXDOUBLE = 100000000000.0;\n    static std::random_device MATHRD;  //Will be used to obtain a seed for the random number engine\n    static std::mt19937 MATHGEN(0); //Standard mersenne_twister_engine seeded with rd()\n    static std::string CERR_ITER = \"  \";\n\n#ifdef __APPLE__\n    static bool MACEN = true;\n    static bool WINEN = false;\n#else\n    static bool MACEN = false;\n    static bool WINEN = true;\n#endif\n\n    struct PGLTriMesh\n    {\n        Vector3d1 vecs;\n        Vector1i1 face_id_0;\n        Vector1i1 face_id_1;\n        Vector1i1 face_id_2;\n    };\n\n    struct TimeClock\n    {\n    public:\n        TimeClock() :start(0), end(0), duration(0) { start = clock(); };\n        void StartClock() { start = clock(); };\n        double EndClock()\n        {\n            end = clock();\n            duration = static_cast<double>(clock() - start) / CLOCKS_PER_SEC;\n            return duration;\n        };\n        double start, end, duration;\n    };\n\n\n    class Functs\n    {\n    public:\n\n#pragma region StatisticsCombinationSet\n\n        template <class Type>\n        static Type Variance(const std::vector<Type>& resultSet)\n        {\n            Type sum = std::accumulate(std::begin(resultSet), std::end(resultSet), 0.0);\n            Type mean = sum / resultSet.size(); //\u5747\u503c\n            Type accum = 0.0;\n            std::for_each(std::begin(resultSet), std::end(resultSet), [&](const Type d) {accum += (d - mean) * (d - mean); });\n            Type stdev = sqrt(accum / (resultSet.size() - 1)); //\u65b9\u5dee\n\n            return stdev;\n        }\n\n        //nb>=1\n        static int Factorial(const int& n)\n        {\n            if (n > 1)\n                return n * Factorial(n - 1);\n            else\n                return 1;\n        };\n\n        //arrangement and combination\n        static void Combination(const Vector1i3& combs, const int& nb, const Vector1i2& sequence, const int& max_nb, Vector1i3& output)\n        {\n            if (output.size() > max_nb)return;\n\n            if (nb == combs.size())\n            {\n                output.emplace_back(sequence);\n                return;\n            }\n\n            for (int i = 0; i < combs[nb].size(); i++)\n            {\n                Vector1i2 seq = sequence;\n                seq.emplace_back(combs[nb][i]);\n                Combination(combs, nb + 1, seq, max_nb, output);\n            }\n        }\n\n        //arrangement and combination\n        //goups={3,2,3}\n        //0,0,0 //0,0,1 //0,0,2 //0,1,0 //0,1,1 //0,1,2\n        //1,0,0 //1,0,1 //1,0,2 //1,1,0 //1,1,1 //1,1,2\n        //2,0,0 //2,0,1 //2,0,2 //2,1,0 //2,1,1 //2,1,2\n        static Vector1i2 Selection(const Vector1i1& groups)\n        {\n            int nb = 1;\n            for (auto& group : groups) nb = nb * group;\n\n            Functs::MAssert(nb != 0, \"nb == 0 in Selection(const Vector1i1& groups)\");\n\n            Vector1i1 nbs(1, nb);\n            for (auto& group : groups)\n            {\n                nbs.emplace_back(nbs.back() / group);\n            }\n            nbs.erase(nbs.begin());\n\n            Vector1i2 combs;\n            for (int i = 0; i < nb; i++)\n            {\n                int id = i;\n                combs.emplace_back(Vector1i1());\n                for (auto nbs_ : nbs)\n                {\n                    int a = (id - id % nbs_) / nbs_;\n                    combs.back().emplace_back(a);\n                    id = id - a * nbs_;\n                }\n            }\n            return combs;\n        }\n\n        //arrangement and combination\n        //with repeat selection\n        //n=3,m=2\n        //1,2\n        //1,3\n        //2,3\n        static Vector1i2 CombNonRepeat(const int& n, const int& m)\n        {\n            std::vector<std::vector<int>> combs;\n            if (n > m)\n            {\n                vector<int> p, set;\n                p.insert(p.end(), m, 1);\n                p.insert(p.end(), static_cast<int64_t>(n) - m, 0);\n                for (int i = 0; i != p.size(); ++i)\n                    set.push_back(i + 1);\n                vector<int> vec;\n                size_t cnt = 0;\n                do {\n                    for (int i = 0; i != p.size(); ++i)\n                        if (p[i])\n                            vec.push_back(set[i]);\n                    combs.emplace_back(vec);\n                    cnt++;\n                    vec.clear();\n                } while (prev_permutation(p.begin(), p.end()));\n            }\n            else\n            {\n                combs.emplace_back(std::vector<int>());\n                for (int i = 1; i <= n; i++)\n                    combs.back().emplace_back(i);\n            }\n\n            return combs;\n        }\n\n        //arrangement and combination\n        //N=3,K=2\n        //0,0\n        //0,1\n        //0,2\n        //1,1\n        //1,2\n        //2,2\n        static std::vector<std::vector<int>> CombRepeat(const int& N, const int& K)\n        {\n            auto Combination = [](const int& N, const int& K) {\n                std::vector<std::vector<int>> temps;\n                std::string bitmask(K, 1); // K leading 1's\n                bitmask.resize(N, 0); // N-K trailing 0's\n                // print integers and permute bitmask\n                do {\n                    std::vector<int> temp;\n                    for (int i = 0; i < N; ++i) // [0..N-1] integers\n                        if (bitmask[i]) temp.emplace_back(i);\n                    if (!temp.empty()) temps.emplace_back(temp);\n                } while (std::prev_permutation(bitmask.begin(), bitmask.end()));\n                return temps;\n            };\n\n            std::vector<std::vector<int>> combs = Combination(N + K - 1, K);\n\n            std::vector<std::vector<int>> repeatCombs;\n            for (auto& comb : combs) {\n                std::vector<int> nbs((int)(static_cast<int64_t>(N) + static_cast<int64_t>(K) - 1), 1);\n                for (auto& i : comb) nbs[i] = 0;\n                std::vector<int> temp;\n                int sum = 0;\n                for (auto& nb : nbs) {\n                    if (nb == 0)temp.emplace_back(sum);\n                    sum += nb;\n                }\n                if (!temp.empty()) repeatCombs.emplace_back(temp);\n            }\n            return repeatCombs;\n        }\n\n        //remove duplicated elements\n        //vec={3,2,1,2,3,4}\n        //output:{1,2,3,4}\n        static Vector1i1 UniqueSet(const Vector1i1& vec)\n        {\n            Vector1i1 s;\n            for (auto& v : vec)\n            {\n                if (std::find(s.begin(), s.end(), v) == s.end()) s.emplace_back(v);\n            }\n            std::sort(s.begin(), s.end());\n            return s;\n        };\n\n        static Vector1i1 SetUnion(const Vector1i1& first, const Vector1i1& second)\n        {\n            Vector1i1 v = first;\n            for (auto& s : second)\n                if (std::find(first.begin(), first.end(), s) == first.end())\n                    v.emplace_back(s);\n            return v;\n        }\n\n        static Vector1i1 SetUnion(Vector1i2& sets)\n        {\n            Vector1i1 start = sets[0];\n\n            for (int i = 1; i < sets.size(); i++)\n            {\n                start = SetUnion(start, sets[i]);\n            }\n\n            return start;\n        }\n\n        static Vector1i1 SetIntersection(const Vector1i1& first, const Vector1i1& second)\n        {\n            Vector1i1 v;\n            for (auto& s : second)\n                if (std::find(first.begin(), first.end(), s) != first.end())\n                    v.emplace_back(s);\n            return v;\n        }\n        static Vector1i1 SetSubtraction(const Vector1i1& first, const Vector1i1& second)\n        {\n            Vector1i1 v;\n            for (auto& s : first)\n                if (std::find(second.begin(), second.end(), s) == second.end())\n                    v.emplace_back(s);\n            return v;\n        }\n\n\n        static Vector1i1 FindSetCombination(Vector1i2& input_)\n        {\n            auto FSC = [](vector<set<int>>& input, set<int>& target, vector<int>& output)\n            {\n                set<int> full;\n                for (auto it : input) {\n                    full.insert(it.begin(), it.end());\n                }\n\n                if (!includes(full.begin(), full.end(), target.begin(), target.end())) {\n                    return;\n                }\n\n                for (int i = static_cast<int>(input.size()) - 1; i > 0; --i) {\n                    vector<bool> vec(input.size(), false);\n                    fill(vec.begin() + i, vec.end(), true);\n                    set<int> comb;\n\n                    do {\n                        for (int j = 0; j < vec.size(); ++j) {\n                            if (vec[j]) {\n                                comb.insert(input[j].begin(), input[j].end());\n                            }\n                        }\n\n                        if (includes(comb.begin(), comb.end(), target.begin(), target.end())) {\n                            for (int j = 0; j < vec.size(); ++j) {\n                                if (vec[j]) {\n                                    output.push_back(j);\n                                }\n                            }\n                            return;\n                        }\n                        comb.clear();\n\n                    } while (next_permutation(vec.begin(), vec.end()));\n                }\n            };\n\n\n            vector<set<int>> input;\n            set<int> target;\n            for (auto& a : input_)\n            {\n                for (int x : a) target.insert(x);\n                input.emplace_back(ConvertToSet(a));\n            }\n            Vector1i1 output;\n            FSC(input, target, output);\n            return output;\n        }\n\n\n\n#pragma endregion\n\n\n#pragma region StringDataStructure\n\n        static int INe(const int& i)\n        {\n            return i + 1;\n        }\n\n        static int IPr(const int& i)\n        {\n            return i - 1;\n        }\n\n        static bool StringContain(const string& str, const string& sub)\n        {\n            return str.find(sub) != std::string::npos;\n        }\n\n        static std::string StringReplace(const string& source, const string& toReplace, const string& replaceWith)\n        {\n            size_t pos = 0;\n            size_t cursor = 0;\n            int repLen = (int)toReplace.length();\n            stringstream builder;\n\n            do\n            {\n                pos = source.find(toReplace, cursor);\n\n                if (string::npos != pos)\n                {\n                    //copy up to the match, then append the replacement\n                    builder << source.substr(cursor, pos - cursor);\n                    builder << replaceWith;\n\n                    // skip past the match\n                    cursor = pos + repLen;\n                }\n            } while (string::npos != pos);\n\n            //copy the remainder\n            builder << source.substr(cursor);\n\n            return (builder.str());\n        }\n\n\n\n        static std::string IntString(int i, int p =0)\n        {\n            std::stringstream ss;\n            std::string str;\n            ss << i;\n            ss >> str;\n            \n            if(p>0)\n            {\n                if(i<0) str = IntString(abs(i));\n               \n                auto strc = str.c_str();\n                string strp=\"\";\n                for(int j=p;j>=1;j--)\n                    strp+=j<=str.length()?string(1, strc[j-1]):\"0\";\n                if(i<0)strp=\"-\"+strp;\n                return strp;\n            }\n            \n            return str;\n        }\n\n        template <class Type>\n        static std::string IntString(const std::vector<Type>& vecs, bool order = false, std::string insert_str = \"\")\n        {\n            std::vector<Type> a = vecs;\n            if (order)sort(a.begin(), a.end());\n\n            std::string str;\n            for (int i = 0; i < a.size(); i++)\n            {\n                str += IntString(a[i]);\n                if (i != a.size() - 1) str += insert_str;\n            }\n            return str;\n\n        }\n\n        template <class Type>\n        static std::string IntString(const std::vector<std::vector<Type>>& vecs, bool order = false, std::string insert_str_0 = \"\", std::string insert_str_1 = \"\")\n        {\n            std::string str;\n\n            for (int i = 0; i < vecs.size(); i++)\n            {\n                str += IntString(vecs[i], order, insert_str_0);\n                if (i != vecs.size() - 1) str += insert_str_1;\n            }\n\n            return str;\n        }\n        template <class Type>\n        static std::string IntString(const std::vector<std::vector<std::vector<Type>>>& vecs, bool order = false, std::string insert_str_0 = \"\", std::string insert_str_1 = \"\", std::string insert_str_2 = \"\")\n        {\n            std::string str;\n\n            for (int i = 0; i < vecs.size(); i++)\n            {\n                str += IntString(vecs[i], order, insert_str_0, insert_str_1);\n                if (i != vecs.size() - 1) str += insert_str_2;\n            }\n\n            return str;\n        }\n\n        template <class Type>\n        static std::string VectorString(const Type& v, const string insert_str = \"\", int p = 3)\n        {\n            std::string str;\n            for (int i = 0; i < v.length(); i++)\n            {\n                if (i == v.length() - 1)\n                    str += DoubleString(v[i], p);\n                else\n                    str += DoubleString(v[i], p) + insert_str;\n            }\n            return str;\n        };\n\n        static std::string VectorString(const Vector3d1& vecs)\n        {\n            auto Comp = [](Vector3d& v_0, Vector3d& v_1)\n            {\n                if (IsAlmostZero(abs(v_1[0] - v_0[0])))\n                {\n                    if (IsAlmostZero(abs(v_1[1] - v_0[1])))\n                    {\n                        if (IsAlmostZero(abs(v_1[2] - v_0[2])))\n                            return true;\n                        return v_0[2] < v_1[2];\n                    }\n                    return v_0[1] < v_1[1];\n                }\n                return v_0[0] < v_1[0];\n            };\n\n            Vector3d1 vecs_1 = vecs;\n            std::sort(vecs_1.begin(), vecs_1.end(), Comp);\n\n            std::string str;\n            for (auto& p : vecs_1)\n            {\n                double x = floor(p[0] * 10.0f + 0.5) / 10.0f;\n                double y = floor(p[1] * 10.0f + 0.5) / 10.0f;\n                double z = floor(p[2] * 10.0f + 0.5) / 10.0f;\n                str += DoubleString(x);\n                str += DoubleString(y);\n                str += DoubleString(z);\n            }\n\n            return str;\n        }\n\n\n\n        static std::string VectorString(const Vector3d3& vecs_3)\n        {\n            Vector3d1 vecs_1;\n            for (int i = 0; i < vecs_3.size(); i++)\n                for (int j = 0; j < vecs_3[i].size(); j++)\n                    for (int k = 0; k < vecs_3[i][j].size(); k++)\n                        vecs_1.emplace_back(vecs_3[i][j][k]);\n\n            return VectorString(vecs_1);\n        };\n\n        static std::string IntString(const VectorPI2& vecs, bool order = false,\n            const std::string insert_str_0 = \"\", const std::string insert_str_1 = \"\", const std::string insert_str_2 = \"\")\n        {\n            std::string str;\n            for (auto& vec : vecs)\n            {\n                str += IntString(vec, order, insert_str_0, insert_str_1) + insert_str_2;\n            }\n            return str;\n        }\n\n        static std::string IntString(const VectorPI1& vecs, bool order = false, const std::string insert_str_0 = \"\", const std::string insert_str_1 = \"\")\n        {\n            if (order)\n            {\n                std::vector<std::pair<int, int>> a = vecs;\n                sort(a.begin(), a.end());\n                std::string str;\n                for (int i = 0; i < a.size(); i++)\n                {\n                    str += IntString(a[i].first) + insert_str_0 + IntString(a[i].second);\n                    if (i != a.size() - 1)\n                        str += insert_str_1;\n                }\n                return str;\n            }\n            else\n            {\n                std::string str;\n                for (int i = 0; i < vecs.size(); i++)\n                {\n                    str += IntString(vecs[i].first) + insert_str_0 + IntString(vecs[i].second);\n                    if (i != vecs.size() - 1) str += insert_str_1;\n                }\n                return str;\n            }\n        }\n\n        static std::string DoubleString(const double& d, int p = 8)\n        {\n            double d_ = abs(d);\n            double d0 = (int)d_;\n            double d1 = d_ - d0;\n\n            {\n                double d1_ = d1;\n                double d2_ = 0.0;\n                if (!Functs::IsAlmostZero(d1_))\n                {\n                    for (int i = 1; i <= p; i++)\n                    {\n                        int a = (int)(d1_ * pow(10, i));\n                        d1_ = d1_ - (double)a / (double)pow(10, i);\n                        d2_ += (double)a / (double)pow(10, i);\n                    }\n\n                    auto temp_0 = std::pow(10, -p);\n                    auto temp_1 = abs(temp_0 - d1_);\n\n                    if (Functs::IsAlmostZero_Double(temp_1, pow(10, -4)))\n                    {\n                        d1 = d2_ + temp_0;\n                        d_ += (int)d1;\n                        d1 = d1 - (int)d1;\n                    }\n                }\n            }\n\n            std::string str;\n            str = std::to_string((int)d_) + \".\";\n            for (int i = 1; i <= p; i++)\n            {\n                int a = (int)(d1 * pow(10, i));\n                str += std::to_string(a);\n                d1 = d1 - (double)a / (double)pow(10, i);\n            }\n\n            if (d >= 0)\n                return str;\n            else\n                return \"-\" + str;\n        }\n\n        static std::string DoubleString(const Vector1d1& ds_, int p = 8, bool order = false, const std::string insert_str_0 = \"\")\n        {\n            Vector1d1 ds = ds_;\n            if (order)std::sort(ds.begin(), ds.end());\n            std::string str;\n            for (int i = 0; i < ds.size(); i++)\n                str += DoubleString(ds[i], p) + (i == ds.size() - 1 ? \"\" : insert_str_0);\n            return str;\n        }\n\n        static double StringToDouble(const string& str)\n        {\n            istringstream iss(str);\n            double num;\n            iss >> num;\n            return num;\n        }\n\n        template <class Type>\n        static Type StringToNum(const string& str)\n        {\n            istringstream iss(str);\n            Type num;\n            iss >> num;\n            return num;\n        }\n\n        static constexpr unsigned int StringEncode(const char* str, int h = 0)\n        {\n            return !str[h] ? 5381 : (StringEncode(str, h + 1) * 33) ^ str[h];\n        }\n\n        static constexpr unsigned int StringEncode(const string& str, int h = 0)\n        {\n            return StringEncode(str.c_str(), h);\n        }\n\n        static vector<string> SplitStr(const string& str, const char& delimiter)\n        {\n            vector<string> internal_strs;\n            stringstream ss(str); // Turn the string into a stream.\n            string tok;\n            while (getline(ss, tok, delimiter))\n                internal_strs.emplace_back(tok.c_str());\n            return internal_strs;\n        }\n\n        static vector<string> SplitStr(const string& str, const string& delimiter)\n        {\n            vector<string> internal_strs;\n            std::string s = str;\n            size_t pos = 0;\n            std::string token;\n            while ((pos = s.find(delimiter)) != std::string::npos) {\n                token = s.substr(0, pos);\n                internal_strs.push_back(token);\n                s.erase(0, pos + delimiter.length());\n            }\n            internal_strs.push_back(s);\n            return internal_strs;\n        }\n        static vector<double> SplitD(const string& str, const char& delimiter)\n        {\n            vector<double> internal_d;\n            stringstream ss(str); // Turn the string into a stream.\n            string tok;\n            while (getline(ss, tok, delimiter))\n                internal_d.emplace_back(atof(tok.c_str()));\n            return internal_d;\n        };\n\n        static vector<int> SplitI(const string& str, const char& delimiter) {\n            vector<int> internal_d;\n            stringstream ss(str); // Turn the string into a stream.\n            string tok;\n            while (getline(ss, tok, delimiter))\n                internal_d.emplace_back(atoi(tok.c_str()));\n            return internal_d;\n        };\n\n        static Vector1i1 ShuffleVector(const int& size)\n        {\n            Vector1i1 shuffle_vec;\n            for (int i = 0; i < size; i++)\n                shuffle_vec.emplace_back(i);\n            std::shuffle(shuffle_vec.begin(), shuffle_vec.end(), MATHGEN);\n            return shuffle_vec;\n        };\n\n        static Vector1i1 IncreaseVector(const int& minI, const int& maxI)\n        {\n            MAssert(minI >= 0 && maxI >= 0 && minI <= maxI, \"minI>=0&&maxI>=0&&minI<=maxI\");\n            Vector1i1 vec;\n            for (int i = minI; i <= maxI; i++) vec.push_back(i);\n            return vec;\n        }\n\n        static Vector1i1 DecreaseVector(const int& maxI, const int& minI)\n        {\n            MAssert(minI >= 0 && maxI >= 0 && minI <= maxI, \"minI>=0&&maxI>=0&&minI<=maxI\");\n            Vector1i1 vec;\n            for (int i = minI; i <= maxI; i++) vec.push_back(i);\n            std::reverse(vec.begin(), vec.end());\n            return vec;\n        }\n\n        static set<int> ConvertToSet(const vector<int>& v)\n        {\n            set<int> s;\n            for (int x : v) s.insert(x);\n            return s;\n        };\n\n        static vector<int> ConvertToVector(const set<int>& s)\n        {\n            vector<int> v;\n            for (auto x : s)v.emplace_back(x);\n            return v;\n        }\n\n        template <class T1, class T2>\n        static T2 MapFind(const std::map<T1, T2>& mt, const T1& t1)\n        {\n            if (mt.find(t1) == mt.end())\n                Functs::MAssert(\"The input is not in this map.\");\n            return mt.find(t1)->second;\n        }\n\n        template <class T1, class T2>\n        static bool MapContain(const std::map<T1, T2>& mt, const T1& t1)\n        {\n            return mt.find(t1) != mt.end();\n        }\n\n        static Vector1i1 RemoveDuplicate(const Vector1i1& vec_)\n        {\n            Vector1i1 vec = vec_;\n            sort(vec.begin(), vec.end());\n            vec.erase(unique(vec.begin(), vec.end()), vec.end());\n            return vec;\n        }\n\n        static Vector3d EigenVector(const Eigen::Vector3d& vec)\n        {\n            return Vector3d(vec[0], vec[1], vec[2]);\n        };\n\n        static Vector3d1 EigenVector(const std::vector<Eigen::Vector3d>& vecs)\n        {\n            Vector3d1 vs;\n            for (auto& vec : vecs)\n                vs.push_back(EigenVector(vec));\n            return vs;\n        };\n\n#pragma endregion\n\n#pragma region BasicGeomFunctions\n\n        template <class Type>\n        static double GetLength(const Type& v) {\n            return glm::length(v);\n        }\n\n        template <class Type>\n        static double GetAngleBetween(const Type& v1, const Type& v2) {\n            double d = glm::dot(v1, v2) / (glm::length(v1) * glm::length(v2));\n            if (IsAlmostZero(d - 1.0))\n                return 0.0;\n            if (IsAlmostZero(d + 1.0))\n                return Math_PI;\n            return glm::acos(d);\n        }\n\n        static double RadiantoAngle(const double& r)\n        {\n            return r / Math_PI * 180.0;\n        }\n\n        static double Radian2Angle(const double& radian)\n        {\n            return radian / Math_PI * 180.0;\n        }\n\n        static double Angle2Radian(const double& angle)\n        {\n            return angle / 180.0 * Math_PI;\n        }\n\n        static void SetVectorLength(Vector3d& v, const double& length)\n        {\n            v = GetVectorLength(v, length);\n        }\n\n        static void SetVectorLength(Vector2d& v, const double& length)\n        {\n            v = GetVectorLength(v, length);\n        }\n\n\t\tstatic Vector3d GetVectorLength(const Vector3d& v, const double& length)\n\t\t{\n            if (IsAlmostZero(length)) return Vector3d(0.0, 0.0,0.0);\n\t\t\tdouble l = GetLength(v);\n\t\t\tMAssert(!IsAlmostZero(l), \"SetVectorLength: input length is zero.\");\n            return Vector3d(v[0] / l * length, v[1] / l * length, v[2] / l * length);\n\t\t}\n\n\t\tstatic Vector2d GetVectorLength(const Vector2d& v, const double& length)\n\t\t{\n            if (IsAlmostZero(length)) return Vector3d(0.0, 0.0, 0.0);\n\t\t\tdouble l = GetLength(v);\n\t\t\tMAssert(!IsAlmostZero(l), \"SetVectorLength: input length is zero.\");\n            return Vector2d(v[0] / l * length, v[1] / l * length);\n\t\t}\n\n\n        //existing bugs in this function\n        static Vector3d Vector3dBase(const Vector3d& v)\n        {\n            Vector3d n(1.0, 1.0, 1.0);\n            if (!IsAlmostZero(v[0])) {\n                n[0] = -(v[1] + v[2]) / v[0];\n                return n;\n            }\n            if (!IsAlmostZero(v[1])) {\n                n[1] = -(v[0] + v[2]) / v[1];\n                return n;\n            }\n            if (!IsAlmostZero(v[2])) {\n                n[2] = -(v[0] + v[1]) / v[2];\n                return n;\n            }\n            return n;\n        }\n\n        static Vector3d GetNormal(const Vector3d& v0, const Vector3d& v1)\n        {\n            MAssert(!IsAlmostZero(GetLength(v0)), \"v0 is zero.\");\n            MAssert(!IsAlmostZero(GetLength(v1)), \"v1 is zero.\");\n            double angle = GetAngleBetween(v0, v1);\n            if (IsAlmostZero(angle) || IsAlmostZero(angle - Math_PI))return Vector3dBase(v0);\n            return GetCrossproduct(v0, v1);\n        }\n\n        static Vector3d GetCenter(const Vector3d1& points)\n        {\n            Vector3d center(0.0, 0.0, 0.0);\n            for (int i = 0; i < points.size(); i++)\n                center += points[i];\n            center = center / (double)points.size();\n            return center;\n        }\n\n        static Vector3d GetCenter(const Vector3d2& points)\n        {\n            Vector3d center(0.0, 0.0, 0.0);\n            int nb = 0;\n            for (int i = 0; i < points.size(); i++)\n            {\n                for (int j = 0; j < points[i].size(); j++)\n                    center += points[i][j];\n                nb += static_cast<int>(points[i].size());\n            }\n            center = center / (double)nb;\n            return center;\n        }\n\n        static Vector3d GetCenter(const Vector3d3& points)\n        {\n            Vector3d center(0.0, 0.0, 0.0);\n            int nb = 0;\n            for (int i = 0; i < points.size(); i++)\n            {\n                for (int j = 0; j < points[i].size(); j++)\n                {\n                    for (int k = 0; k < points[i][j].size(); k++)\n                    {\n                        center += points[i][j][k];\n                        nb++;\n                    }\n                }\n            }\n            center = center / (double)nb;\n            return center;\n        }\n\n        static Vector2d GetCenter(const std::vector<Vector2d>& points)\n        {\n            Vector2d center(0.0, 0.0);\n            for (int i = 0; i < points.size(); i++)\n                center += points[i];\n            center = center / (double)points.size();\n            return center;\n        }\n\n        static Vector2d GetCenter(const std::vector<std::vector<Vector2d>>& points)\n        {\n            Vector2d center(0.0, 0.0);\n            int nb = 0;\n            for (int i = 0; i < points.size(); i++)\n            {\n                for (int j = 0; j < points[i].size(); j++)\n                    center += points[i][j];\n                nb += static_cast<int>(points[i].size());\n            }\n            center = center / (double)nb;\n            return center;\n        }\n\n        static void GetBoundingBox(const Vector3d2& points, Vector3d& minimal_corner, Vector3d& maximal_corner)\n        {\n            minimal_corner = Vector3d(MAXDOUBLE, MAXDOUBLE, MAXDOUBLE);\n            maximal_corner = Vector3d(-MAXDOUBLE, -MAXDOUBLE, -MAXDOUBLE);\n            for (int i = 0; i < points.size(); i++)\n            {\n                for (int j = 0; j < points[i].size(); j++)\n                {\n                    minimal_corner[0] = min(minimal_corner[0], points[i][j][0]);\n                    minimal_corner[1] = min(minimal_corner[1], points[i][j][1]);\n                    minimal_corner[2] = min(minimal_corner[2], points[i][j][2]);\n                    maximal_corner[0] = max(maximal_corner[0], points[i][j][0]);\n                    maximal_corner[1] = max(maximal_corner[1], points[i][j][1]);\n                    maximal_corner[2] = max(maximal_corner[2], points[i][j][2]);\n                }\n            }\n        }\n\n        static void GetBoundingBox(const Vector3d1& points, Vector3d& minimal_corner, Vector3d& maximal_corner)\n        {\n            minimal_corner = Vector3d(MAXDOUBLE, MAXDOUBLE, MAXDOUBLE);\n            maximal_corner = Vector3d(-MAXDOUBLE, -MAXDOUBLE, -MAXDOUBLE);\n\n            for (int i = 0; i < points.size(); i++)\n            {\n                minimal_corner[0] = min(minimal_corner[0], points[i][0]);\n                minimal_corner[1] = min(minimal_corner[1], points[i][1]);\n                minimal_corner[2] = min(minimal_corner[2], points[i][2]);\n                maximal_corner[0] = max(maximal_corner[0], points[i][0]);\n                maximal_corner[1] = max(maximal_corner[1], points[i][1]);\n                maximal_corner[2] = max(maximal_corner[2], points[i][2]);\n            }\n        }\n\n        static void GetBoundingBox(const std::vector<Vector2d>& points, Vector2d& minimal_corner, Vector2d& maximal_corner)\n        {\n            minimal_corner = Vector2d(MAXDOUBLE, MAXDOUBLE);\n            maximal_corner = Vector2d(-MAXDOUBLE, -MAXDOUBLE);\n            for (int i = 0; i < points.size(); i++)\n            {\n                minimal_corner[0] = min(minimal_corner[0], points[i][0]);\n                minimal_corner[1] = min(minimal_corner[1], points[i][1]);\n                maximal_corner[0] = max(maximal_corner[0], points[i][0]);\n                maximal_corner[1] = max(maximal_corner[1], points[i][1]);\n            }\n        }\n\n        static void GetBoundingBox(const std::vector<std::vector<Vector2d>>& points, Vector2d& minimal_corner, Vector2d& maximal_corner)\n        {\n            minimal_corner = Vector2d(MAXDOUBLE, MAXDOUBLE);\n            maximal_corner = Vector2d(-MAXDOUBLE, -MAXDOUBLE);\n            for (int i = 0; i < points.size(); i++)\n            {\n                for (int j = 0; j < points[i].size(); j++)\n                {\n                    minimal_corner[0] = min(minimal_corner[0], points[i][j][0]);\n                    minimal_corner[1] = min(minimal_corner[1], points[i][j][1]);\n                    maximal_corner[0] = max(maximal_corner[0], points[i][j][0]);\n                    maximal_corner[1] = max(maximal_corner[1], points[i][j][1]);\n                }\n            }\n        }\n\n        static double CircumCircleRaidius(const Vector2d& v0, const Vector2d& v1, const Vector2d& v2)\n        {\n            double a = GetLength(v0 - v1);\n            double b = GetLength(v0 - v2);\n            double c = GetLength(v1 - v2);\n            double p = (a + b + c) / 2.0;\n            double area = (4.0 * pow(p * (p - a) * (p - b) * (p - c), 0.5));\n            double radius;\n\n            if (IsAlmostZero(area))\n            {\n                double max_l = a;\n                max_l = max(max_l, b);\n                max_l = max(max_l, c);\n                radius = 10 * max_l;\n            }\n            else\n                radius = a * b * c / area;\n            return radius;\n        }\n\n        static double GetTriangleArea(const Vector3d& v0, const Vector3d& v1, const Vector3d& v2)\n        {\n            double a = GetDistance(v0, v1);\n            double b = GetDistance(v2, v1);\n            double c = GetDistance(v0, v2);\n            double p = (a + b + c) / 2.0;\n            return sqrt(p * (p - a) * (p - b) * (p - c));\n        }\n\n        template <class Type>\n        static double GetLength(const Type& v0, const Type& v1) {\n            return GetLength(v0 - v1);\n        }\n\n        template <class Type>\n        static double GetDistance(const Type& v0, const Type& v1) {\n            return GetLength(v0 - v1);\n        }\n\n        template <class Type>\n        static double GetDistance(const Type& v, const std::vector<Type>& vs)\n        {\n            double min_d = MAXDOUBLE;\n            for (const auto& iter : vs)\n                min_d = min(min_d, GetDistance(v, iter));\n            return min_d;\n        }\n\n        template <class Type>\n        static double GetDistance(const Type& v, const std::vector<std::vector<Type>>& vs)\n        {\n            double min_d = MAXDOUBLE;\n            for (const auto& iter : vs)\n                min_d = min(min_d, GetDistance(v, iter));\n            return min_d;\n        }\n\n        template <class Type>\n        static double GetDistance(const std::vector<std::vector<Type>>& vs1, const std::vector<std::vector<Type>>& vs2)\n        {\n            double total_d = 0.0;\n            int nb = 0;\n            for (auto& vec : vs1)\n            {\n                for (auto& v : vec)\n                {\n                    total_d = total_d + GetDistance(v, vs2);\n                    nb++;\n                }\n            }\n            if (nb != 0) total_d = total_d / (double)nb;\n            return total_d;\n        }\n\n        template <class Type>\n        static double GetDistanceNONE(\n            const std::vector<std::vector<Type>>& vs1,\n            const std::vector<std::vector<Type>>& vs2)\n        {\n            return (GetDistance(vs1, vs2) + GetDistance(vs2, vs1)) / 2.0;\n        }\n\n        template <class Type>\n        static int GetNearestPointIndex(const Type& v, const std::vector<Type>& vs)\n        {\n            int index = -1;\n            double min_d = MAXDOUBLE;\n            for (int i = 0; i < vs.size(); i++)\n            {\n                double cur_d = GetDistance(v, vs[i]);\n                if (cur_d < min_d)\n                {\n                    min_d = cur_d;\n                    index = 0;\n                }\n            }\n            return index;\n        }\n\n        static double GetLength(const std::vector<Vector2d>& points)\n        {\n            double length = 0.0;\n\n            for (int i = 0; i < points.size(); i++)\n                length += GetLength(points[i], points[(static_cast<int64_t>(i) + 1) % points.size()]);\n\n            return length;\n        }\n\n        static double GetLength(const Vector3d1& points)\n        {\n            double length = 0.0;\n\n            for (int i = 0; i < points.size(); i++)\n                length += GetLength(points[i], points[(static_cast<int64_t>(i) + 1) % points.size()]);\n\n            return length;\n        }\n\n        static Vector2d1 RemoveClosePoints(const Vector2d1& xys_)\n        {\n            Vector2d1 xys = xys_;\n            std::vector<int> remove_int;\n            if (xys.size() > 2)\n            {\n                for (int i = 0; i < xys.size() - 1; i++)\n                {\n                    double d = GetDistance(xys[i], xys[(int)(i + 1)]);\n                    if (d < 0.00001) remove_int.push_back(i + 1);\n                }\n\n                for (int i = (int)(remove_int.size() - 1); i >= 0; i--)\n                {\n                    xys.erase(xys.begin() + remove_int[i]);\n                }\n            }\n            return xys;\n        }\n\n        static Vector3d PlaneProject(const Vector3d& planar_location, const Vector3d& planar_direction, const Vector3d& p)\n        {\n            if (IsAlmostZero(GetLength(planar_location, p)))\n                return planar_location;\n\n            double angle = GetAngleBetween(planar_direction, p - planar_location);\n            double length = GetLength(planar_location, p);\n\n            auto backup_planar_direction = planar_direction;\n\n            if (angle <= Math_PI / 2.0)\n                return p - GetVectorLength(backup_planar_direction, length * sin(Math_PI / 2.0 - angle));\n            else\n                return p + GetVectorLength(backup_planar_direction, length * sin(angle - Math_PI / 2.0));\n\n        }\n\n        static Vector3d GetRandomDirection(const double& direction_length = 1.0)\n        {\n            double alpha_angle = rand() / double(RAND_MAX) * 2.0 * PGL::Math_PI;\n            double alpha_beta = rand() / double(RAND_MAX) * 2.0 * PGL::Math_PI;\n            auto direction_0 = PGL::Functs::RotationAxis(Vector3d(direction_length, 0.0, 0.0), alpha_angle, Vector3d(0.0, 1.0, 0.0));\n            auto direction_axis = PGL::Functs::GetCrossproduct(direction_0, Vector3d(0.0, 1.0, 0.0));\n            return PGL::Functs::RotationAxis(direction_0, alpha_beta, direction_axis);\n        }\n\n\n\n        //https://medium.com/@all2one/generating-uniformly-distributed-points-on-sphere-1f7125978c4c\n\n        //method: NormalDeviate; TrigDeviate; CoordinateApproach;MinimalDistance;RegularDistribution;\n        static Vector3d1 GetRandomDirections(const int& count, const string& method)\n        {\n            if (method == \"NormalDeviate\") return GetRandomDirections_Normal_Deviate(count);\n            if (method == \"TrigDeviate\") return GetRandomDirections_Trig_method(count);\n            if (method == \"CoordinateApproach\") return GetRandomDirections_Coordinate_Approach(count);\n            if (method == \"MinimalDistance\") return GetRandomDirections_Minimal_Distance(count);\n            if (method == \"RegularDistribution\") return GetRandomDirections_Regular_Distribution(count);\n\n            MAssert(\"Input method does not be implemented: \" + method);\n            return Vector3d1();\n        }\n\n        static Vector3d1 GetRandomDirections_Regular_Distribution(const int& count)\n        {\n            Vector3d1 directions;\n            double a = 4.0 * Math_PI * 1.0 / static_cast<double>(count);\n            double d = sqrt(a);\n            size_t num_phi = (size_t)round(Math_PI / d);\n            double d_phi = Math_PI / static_cast<double>(num_phi);\n            double d_theta = a / d_phi;\n            for (int m = 0; m < num_phi; ++m) {\n                double phi = Math_PI * (m + 0.5) / num_phi;\n                size_t num_theta = (size_t)round(2 * Math_PI * sin(phi) / d_theta);\n                for (int n = 0; n < num_theta; ++n) {\n                    double theta = 2 * Math_PI * n / static_cast<double>(num_theta);\n                    Vector3d p;\n                    p.x = sin(phi) * cos(theta);\n                    p.y = sin(phi) * sin(theta);\n                    p.z = cos(phi);\n                    directions.push_back(p);\n                }\n            }\n            return directions;\n        }\n\n\n        static Vector3d1 GetRandomDirections_Normal_Deviate(const int& count)\n        {\n            std::mt19937 rnd;\n            std::normal_distribution<double> dist(0.0, 1.0);\n\n            Vector3d1 directions;\n            for (int i = 0; i < count; ++i)\n            {\n                bool bad_luck = false;\n                do\n                {\n                    double x = dist(rnd);\n                    double y = dist(rnd);\n                    double z = dist(rnd);\n                    double r2 = x * x + y * y + z * z;\n                    if (r2 == 0)\n                        bad_luck = true;\n                    else\n                    {\n                        bad_luck = false;\n                        double r = sqrt(r2);\n                        directions.push_back(Vector3d(x / r, y / r, z / r));\n                    }\n                } while (bad_luck);\n            }\n\n            return directions;\n        }\n\n        static Vector3d1 GetRandomDirections_Trig_method(const int& count)\n        {\n            std::mt19937 rnd;\n            std::uniform_real_distribution<double> dist(0.0, 1.0);\n\n            Vector3d1 directions;\n            for (int i = 0; i < count; ++i)\n            {\n                double z = 2.0 * dist(rnd) - 1.0;\n                double t = 2.0 * Math_PI * dist(rnd);\n                double r = sqrt(1.0 - z * z);\n                directions.push_back(Vector3d(r * cos(t), r * sin(t), z));\n            }\n            return directions;\n        };\n\n        static Vector3d1 GetRandomDirections_Coordinate_Approach(const int& count)\n        {\n            std::mt19937 rnd;\n            std::uniform_real_distribution<double> dist(-1.0, 1.0);\n\n            Vector3d1 directions;\n            for (int i = 0; i < count; ++i)\n            {\n                bool rejected = false;\n                do\n                {\n                    double u = dist(rnd);\n                    double v = dist(rnd);\n                    double s = u * u + v * v;\n                    if (s > 1.0)\n                        rejected = true;\n                    else\n                    {\n                        rejected = false;\n                        double a = 2.0 * sqrt(1.0 - s);\n                        directions.push_back(Vector3d(a * u, a * v, 2.0 * s - 1.0));\n                    }\n                } while (rejected);\n            }\n            return directions;\n        }\n\n        //random sample a set of directions on the Gaussian Sphere\n        static Vector3d1 GetRandomDirections_Minimal_Distance(const int& dns, const int dis_iters = 100)\n        {\n            double gaussion_sphere_radius = 1.0;\n            double idea_distance = 2 * gaussion_sphere_radius / sqrt(dns);\n\n            Vector3d1 directions;\n            for (int i = 0; i < dns; i++)\n            {\n                OutputIterInfo(\"Random Directions\", dns, i, 10);\n\n                for (int j = 0; j < dis_iters; j++)\n                {\n                    //glm::ballRand(gaussion_sphere_radius) is slower than my solution\n                    Vector3d random_direction = GetRandomDirection(gaussion_sphere_radius);\n\n                    auto dis = Functs::GetDistance(random_direction, directions);\n                    if (dis > idea_distance)\n                    {\n                        directions.push_back(random_direction);\n                        break;\n                    }\n                }\n\n            }\n            return directions;\n        }\n\n        static void Connecting_Segments(const Vector3d2& segments, Vector3d2& lines)\n        {\n            //save connecting relations\n            std::vector<bool> used(segments.size(), false);\n            std::vector<int> relations;\n#pragma region get_relations\n            for (int i = 0; i < segments.size(); i++)\n            {\n                for (int j = i + 1; j < segments.size(); j++)\n                {\n                    if (i != j && !used[i] && !used[j])\n                    {\n                        double l_0_0 = GetLength(segments[i][0], segments[j][0]);\n                        double l_0_1 = GetLength(segments[i][0], segments[j][1]);\n                        double l_1_0 = GetLength(segments[i][1], segments[j][0]);\n                        double l_1_1 = GetLength(segments[i][1], segments[j][1]);\n\n                        bool b_0_0 = IsAlmostZero_Double(l_0_0, DOUBLE_EPSILON);\n                        bool b_0_1 = IsAlmostZero_Double(l_0_1, DOUBLE_EPSILON);\n                        bool b_1_0 = IsAlmostZero_Double(l_1_0, DOUBLE_EPSILON);\n                        bool b_1_1 = IsAlmostZero_Double(l_1_1, DOUBLE_EPSILON);\n\n                        if ((b_0_0 && b_1_1) || (b_0_1 && b_1_0))\n                        {\n                            used[j] = true;\n                            continue;\n                        }\n\n                        if (b_0_0)\n                        {\n                            relations.push_back(i);\n                            relations.push_back(0);\n                            relations.push_back(j);\n                            relations.push_back(0);\n                            continue;\n                        }\n                        if (b_0_1)\n                        {\n                            relations.push_back(i);\n                            relations.push_back(0);\n                            relations.push_back(j);\n                            relations.push_back(1);\n                            continue;\n                        }\n                        if (b_1_0)\n                        {\n                            relations.push_back(i);\n                            relations.push_back(1);\n                            relations.push_back(j);\n                            relations.push_back(0);\n                            continue;\n                        }\n                        if (b_1_1)\n                        {\n                            relations.push_back(i);\n                            relations.push_back(1);\n                            relations.push_back(j);\n                            relations.push_back(1);\n                            continue;\n                        }\n                    }\n                }\n            }\n#pragma endregion\n\n            std::vector<std::vector<int>> ones;\n\n\n            while (true)\n            {\n                int index = -1;\n                int end = -1;\n\n                for (int i = 0; i < segments.size(); i++)\n                {\n                    if (!used[i]) {\n                        index = i;\n                        end = 0;\n                        used[i] = true;\n                        break;\n                    }\n                }\n\n                if (index < 0)break;\n\n                Vector3d1 line(1, segments[index][end]);\n\n                std::vector<int> one(1, index);\n\n                while (true)\n                {\n                    end = 1 - end;\n                    bool search = false;\n                    for (int i = 0; i < relations.size(); i = i + 4)\n                    {\n                        if (relations[i] == index && relations[static_cast<int64_t>(i) + 1] == end && !used[relations[static_cast<int64_t>(i) + 2]])\n                        {\n                            line.push_back(segments[relations[static_cast<int64_t>(i) + 2]][relations[static_cast<int64_t>(i) + 3]]);\n                            one.push_back(relations[static_cast<int64_t>(i) + 2]);\n                            index = relations[static_cast<int64_t>(i) + 2];\n                            end = relations[static_cast<int64_t>(i) + 3];\n                            used[index] = true;\n                            search = true;\n                            break;\n                        }\n                        if (relations[static_cast<int64_t>(i) + 2] == index && relations[static_cast<int64_t>(i) + 3] == end && !used[relations[i]])\n                        {\n                            line.push_back(segments[relations[i]][relations[static_cast<int64_t>(i) + 1]]);\n                            one.push_back(relations[i]);\n                            index = relations[i];\n                            end = relations[static_cast<int64_t>(i) + 1];\n                            used[index] = true;\n                            search = true;\n                            break;\n                        }\n                    }\n                    if (!search) { break; }\n                }\n\n                ones.push_back(one);\n                lines.push_back(line);\n            }\n        }\n\n        static Vector3d IntersectPointPlane2Ray(const Vector3d& planar_location, Vector3d& planar_direction,\n            const Vector3d& ray_location, Vector3d& ray_vector)\n        {\n            Vector3d project_point = PlaneProject(planar_location, planar_direction, ray_location);\n            double distance = GetDistance(ray_location, project_point);\n            if (IsAlmostZero(GetLength(project_point, ray_location)))\n                return ray_location;\n            double angle = GetAngleBetween(ray_vector, project_point - ray_location);\n            double length = distance / cos(angle);\n            return ray_location + GetVectorLength(ray_vector, length);\n        }\n\n        static Vector3d ComputeNormalFromPolyline(const Vector3d1& points)\n        {\n            Vector3d planar_direction;\n            planar_direction = GetNormal(points[0] - points[1], points[2] - points[1]);\n            SetVectorLength(planar_direction, 1.0);\n            return planar_direction;\n        }\n\n        static void  ComputePlanarFromPolyline(Vector3d& planar_location, Vector3d& planar_direction, const Vector3d1& points)\n        {\n            planar_location = points[0];\n            planar_direction = GetNormal(points[0] - points[1], points[2] - points[1]);\n            SetVectorLength(planar_direction, 1.0);\n        }\n\n\n\n        // Compute barycentric coordinates (u, v, w) for\n        // point p with respect to triangle (a, b, c)\n        static void Barycentric(const Vector3d& p, const Vector3d& a, const Vector3d& b, const Vector3d& c, double& u, double& v, double& w)\n        {\n            Vector3d v0 = GetMinus(b, a), v1 = GetMinus(c, a), v2 = GetMinus(p, a);\n\n            double d00 = GetDotproduct(v0, v0);\n            double d01 = GetDotproduct(v0, v1);\n            double d11 = GetDotproduct(v1, v1);\n            double d20 = GetDotproduct(v2, v0);\n            double d21 = GetDotproduct(v2, v1);\n            double denom = d00 * d11 - d01 * d01;\n            v = (d11 * d20 - d01 * d21) / denom;\n            w = (d00 * d21 - d01 * d20) / denom;\n            u = 1.0f - v - w;\n        }\n\n        static Vector3d Barycentric(const Vector3d& p, const Vector3d& a, const Vector3d& b, const Vector3d& c)\n        {\n            Vector3d v0 = GetMinus(b, a), v1 = GetMinus(c, a), v2 = GetMinus(p, a);\n            double d00 = GetDotproduct(v0, v0);\n            double d01 = GetDotproduct(v0, v1);\n            double d11 = GetDotproduct(v1, v1);\n            double d20 = GetDotproduct(v2, v0);\n            double d21 = GetDotproduct(v2, v1);\n            double denom = d00 * d11 - d01 * d01;\n            double v = (d11 * d20 - d01 * d21) / denom;\n            double w = (d00 * d21 - d01 * d20) / denom;\n            double u = 1.0f - v - w;\n            return Vector3d(u, v, w);\n        }\n\n        //===============================================================\n        template <class Type>\n        static bool DetectColinear(const Type& v, const Type& s, const Type& e, const double& angle_match_error, const double& dis_match_error)\n        {\n            if (DetectCoincident(v, s, dis_match_error) || DetectCoincident(v, e, dis_match_error)) return true;\n            double angle = GetAngleBetween(v - s, e - s);\n            if (IsAlmostZero_Double(angle, angle_match_error))return true;\n            if (IsAlmostZero_Double(angle - Math_PI, angle_match_error))return true;\n            return false;\n        }\n\n        template <class Type>\n        static bool DetectVertical(const Type& direction_0, const Type& direction_1, const double& angle_match_error, const double& dis_match_error)\n        {\n            auto angle = GetAngleBetween(direction_0, direction_1);\n            return IsAlmostZero_Double(angle - Math_PI / 2.0, angle_match_error);\n        };\n\n        template <class Type>\n        static bool DetectVertical(const Type& seg_0_s, const Type& seg_0_e, const Type& seg_1_s, const Type& seg_1_e, const double& angle_match_error, const double& dis_match_error)\n        {\n            return DetectVertical(seg_0_e - seg_0_s, seg_0_e - seg_0_s, angle_match_error, dis_match_error);\n        };\n\n        template <class Type>\n        static bool DetectVertical(const std::pair<Type, Type>& seg_0, const std::pair<Type, Type>& seg_1,\n            const double& angle_match_error, const double& dis_match_error)\n        {\n            return DetectVertical(seg_0.first, seg_0.second, seg_1.first, seg_1.second, angle_match_error, dis_match_error);\n        };\n\n        template <class Type>\n        static bool DetectCoincident(const Type& v0, const Type& v1, const double& EPSILON = DOUBLE_EPSILON)\n        {\n            return IsAlmostZero_Double(GetDistance(v0, v1), EPSILON);\n        }\n\n        static bool DetectCoplanar(const Vector3d& planar_location_0, const Vector3d& planar_direction_0,\n            const Vector3d& planar_location_1, const Vector3d& planar_direction_1,\n            const double& angle_match_error, const double& dis_match_error)\n        {\n            auto angle = GetAngleBetween(planar_direction_0, planar_direction_1);\n            if (IsAlmostZero_Double(angle - Math_PI, angle_match_error) || IsAlmostZero_Double(angle, angle_match_error))\n            {\n                double dis = GetLength(PlaneProject(planar_location_0, planar_direction_0, planar_location_1), planar_location_1);\n                return IsAlmostZero_Double(dis, dis_match_error);\n            }\n            else\n                return false;\n        }\n\n        template <class Type>\n        static bool DetectParallel(const Type& direction_0, const Type& direction_1, const double& angle_match_error, const double& dis_match_error)\n        {\n            auto angle = GetAngleBetween(direction_0, direction_1);\n            return (IsAlmostZero_Double(angle - Math_PI, angle_match_error) || IsAlmostZero_Double(angle, angle_match_error));\n        };\n\n        template <class Type>\n        static bool DetectParallel(const std::pair<Type, Type>& seg_0, const std::pair<Type, Type>& seg_1,\n            const double& angle_match_error, const double& dis_match_error)\n        {\n            return DetectParallel(seg_0.second - seg_0.first, seg_1.second - seg_1.first, angle_match_error, dis_match_error);\n        };\n        template <class Type>\n        static bool DetectCoDirection(const Type& direction_0, const Type& direction_1, const double& angle_match_error, const double& dis_match_error)\n        {\n            auto angle = GetAngleBetween(direction_0, direction_1);\n            return (IsAlmostZero_Double(angle, angle_match_error));\n        };\n\n        template <class Type>\n        static bool DetectColinear_Direction(const Type& location_0, const Type& direction_0, const Type& location_1, const Type& direction_1, const double& angle_match_error, const double& dis_match_error)\n        {\n            if (DetectParallel(direction_0, direction_1, angle_match_error, dis_match_error))\n            {\n                if (IsAlmostZero_Double(GetLength(location_0 - location_1), dis_match_error))\n                    return true;\n                return DetectParallel(direction_0, location_1 - location_0, angle_match_error, dis_match_error);\n            }\n            else\n                return false;\n        };\n\n        static bool DetectAlign2D(const Vector2d& s_0, const Vector2d& e_0, const Vector2d& s_1, const Vector2d& e_1, const double& angle_match_error, const double& dis_match_error)\n        {\n            double d0 = GetDistance(s_0, s_1);\n            double d1 = GetDistance(s_0, e_1);\n            double d2 = GetDistance(e_0, s_1);\n            double d3 = GetDistance(e_0, e_1);\n            if (IsAlmostZero_Double(d0, dis_match_error) && IsAlmostZero_Double(d3, dis_match_error))\n                return true;\n            if (IsAlmostZero_Double(d1, dis_match_error) && IsAlmostZero_Double(d2, dis_match_error))\n                return true;\n            return false;\n        };\n\n        static bool DetectAlign3D(const Vector3d& s_0, const Vector3d& e_0, const Vector3d& s_1, const Vector3d& e_1, const double& angle_match_error, const double& dis_match_error)\n        {\n            double d0 = GetDistance(s_0, s_1);\n            double d1 = GetDistance(s_0, e_1);\n            double d2 = GetDistance(e_0, s_1);\n            double d3 = GetDistance(e_0, e_1);\n            if (IsAlmostZero_Double(d0, dis_match_error) && IsAlmostZero_Double(d3, dis_match_error))\n                return true;\n            if (IsAlmostZero_Double(d1, dis_match_error) && IsAlmostZero_Double(d2, dis_match_error))\n                return true;\n            return false;\n        };\n\n        //this function has bug ;\n        //Do not use it\n        template <class Type>\n        static bool DetectColinear_Segment(const Type& s_0, const Type& e_0, const Type& s_1, const Type& e_1, const double& angle_match_error, const double& dis_match_error)\n        {\n            return DetectColinear_Direction(s_0, e_0 - s_0, s_1, e_1 - s_1, angle_match_error, dis_match_error);\n        };\n\n        static std::vector<Vector2d> Polygon_Clear(const std::vector<Vector2d>& vecs,\n            const double& angle_match_error, const double& dis_match_error)\n        {\n            //remove duplicate points\n            std::vector<Vector2d> vecs_0;\n            for (int i = 0; i < vecs.size(); i++)\n            {\n                if (i != vecs.size() - 1)\n                {\n                    if (vecs_0.empty()) vecs_0.emplace_back(vecs[i]);\n                    else\n                    {\n                        if (dis_match_error > 0)\n                        {\n                            if (!IsAlmostZero_Double(GetLength(vecs_0.back(), vecs[i]), dis_match_error))\n                                vecs_0.emplace_back(vecs[i]);\n                        }\n                        else\n                        {\n                            if (!IsAlmostZero(GetLength(vecs_0.back(), vecs[i])))\n                                vecs_0.emplace_back(vecs[i]);\n                        }\n                    }\n                }\n                else\n                {\n                    if (vecs_0.empty())\n                        vecs_0.emplace_back(vecs[i]);\n                    else\n                    {\n                        if (dis_match_error > 0)\n                        {\n                            if (!IsAlmostZero_Double(GetLength(vecs_0.back(), vecs[i]), dis_match_error) &&\n                                !IsAlmostZero_Double(GetLength(vecs_0.front(), vecs[i]), dis_match_error))\n                                vecs_0.emplace_back(vecs[i]);\n                        }\n                        else\n                        {\n                            if (!IsAlmostZero(GetLength(vecs_0.back(), vecs[i])) &&\n                                !IsAlmostZero(GetLength(vecs_0.front(), vecs[i])))\n                                vecs_0.emplace_back(vecs[i]);\n                        }\n\n                    }\n                }\n            }\n            //remove collinear points\n            std::vector<Vector2d> vecs_1;\n            for (int i = 0; i < vecs_0.size(); i++)\n            {\n                auto pre_v = vecs_0[(i + vecs_0.size() - 1) % vecs_0.size()];\n                auto cur_v = vecs_0[i];\n                auto next_v = vecs_0[(static_cast<int64_t>(i) + 1) % vecs_0.size()];\n                double angle = GetAngleBetween(cur_v - pre_v, next_v - cur_v);\n                if (angle_match_error > 0.0)\n                {\n                    if (!IsAlmostZero_Double(angle, angle_match_error))\n                        vecs_1.emplace_back(cur_v);\n                }\n                else\n                {\n                    if (!IsAlmostZero(angle))\n                        vecs_1.emplace_back(cur_v);\n                }\n            }\n\n            return vecs_1;\n        };\n\n        static std::vector<Vector2d> GetUnitSquare()\n        {\n            std::vector<Vector2d> square;\n            square.push_back(Vector2d(-0.5, -0.5));\n            square.push_back(Vector2d(0.5, -0.5));\n            square.push_back(Vector2d(0.5, 0.5));\n            square.push_back(Vector2d(-0.5, 0.5));\n            return square;\n        };\n\n        static std::vector<std::pair<Vector3d, Vector3d>> GetUnitCubeFrame(const double& scale = 1.0)\n        {\n            Vector3d1 cube_vecs;\n\n            cube_vecs.push_back(Vector3d(0.5, 0.5, 0.5));\n            cube_vecs.push_back(Vector3d(-0.5, 0.5, 0.5));\n            cube_vecs.push_back(Vector3d(-0.5, 0.5, -0.5));\n            cube_vecs.push_back(Vector3d(0.5, 0.5, -0.5));\n\n            cube_vecs.push_back(Vector3d(0.5, -0.5, 0.5));\n            cube_vecs.push_back(Vector3d(-0.5, -0.5, 0.5));\n            cube_vecs.push_back(Vector3d(-0.5, -0.5, -0.5));\n            cube_vecs.push_back(Vector3d(0.5, -0.5, -0.5));\n\n            auto sm = Functs::ScaleMatrix(Vector3d(scale, scale, scale));\n            cube_vecs = Functs::PosApplyM(cube_vecs, sm);\n\n            VectorPI1 frames_indexes;\n            frames_indexes.push_back(std::pair<int, int>(0, 1));\n            frames_indexes.push_back(std::pair<int, int>(1, 2));\n            frames_indexes.push_back(std::pair<int, int>(2, 3));\n            frames_indexes.push_back(std::pair<int, int>(3, 0));\n            frames_indexes.push_back(std::pair<int, int>(5, 4));\n            frames_indexes.push_back(std::pair<int, int>(4, 7));\n            frames_indexes.push_back(std::pair<int, int>(7, 6));\n            frames_indexes.push_back(std::pair<int, int>(6, 5));\n            frames_indexes.push_back(std::pair<int, int>(5, 1));\n            frames_indexes.push_back(std::pair<int, int>(4, 0));\n            frames_indexes.push_back(std::pair<int, int>(7, 3));\n            frames_indexes.push_back(std::pair<int, int>(6, 2));\n\n            std::vector<std::pair<Vector3d, Vector3d>> frames;\n            for (auto& fi : frames_indexes)\n                frames.push_back(std::pair<Vector3d, Vector3d>(cube_vecs[fi.first], cube_vecs[fi.second]));\n            return frames;\n        }\n\n        static void GetUnitCube(Vector3d1& cube_vecs, Vector1i1& cube_face_id_0, Vector1i1& cube_face_id_1, Vector1i1& cube_face_id_2, const double& scale = 1.0)\n        {\n            cube_vecs.clear();\n            cube_face_id_0.clear();\n            cube_face_id_1.clear();\n            cube_face_id_2.clear();\n\n            cube_vecs.push_back(Vector3d(0.5, 0.5, 0.5));\n            cube_vecs.push_back(Vector3d(-0.5, 0.5, 0.5));\n            cube_vecs.push_back(Vector3d(-0.5, 0.5, -0.5));\n            cube_vecs.push_back(Vector3d(0.5, 0.5, -0.5));\n\n            cube_vecs.push_back(Vector3d(0.5, -0.5, 0.5));\n            cube_vecs.push_back(Vector3d(-0.5, -0.5, 0.5));\n            cube_vecs.push_back(Vector3d(-0.5, -0.5, -0.5));\n            cube_vecs.push_back(Vector3d(0.5, -0.5, -0.5));\n\n            auto sm = Functs::ScaleMatrix(Vector3d(scale, scale, scale));\n            cube_vecs = Functs::PosApplyM(cube_vecs, sm);\n\n            Vector1i2 quad_faces;\n            quad_faces.push_back(Vector1i1{ 0, 1, 2, 3 });\n            quad_faces.push_back(Vector1i1{ 5, 1, 0, 4 });\n            quad_faces.push_back(Vector1i1{ 4, 0, 3, 7 });\n            quad_faces.push_back(Vector1i1{ 5, 4, 7, 6 });\n            quad_faces.push_back(Vector1i1{ 7, 3, 2, 6 });\n            quad_faces.push_back(Vector1i1{ 6, 2, 1, 5 });\n\n            for (auto qf : quad_faces)\n            {\n                cube_face_id_0.push_back(qf[2]);\n                cube_face_id_1.push_back(qf[1]);\n                cube_face_id_2.push_back(qf[0]);\n                cube_face_id_0.push_back(qf[0]);\n                cube_face_id_1.push_back(qf[3]);\n                cube_face_id_2.push_back(qf[2]);\n            }\n        };\n\n        static PGLTriMesh GetUnitCube(const double& scale = 1.0)\n        {\n            PGLTriMesh tm;\n            GetUnitCube(tm.vecs, tm.face_id_0, tm.face_id_1, tm.face_id_2, scale);\n            return tm;\n        }\n\n        static Vector3d1 GetAxisAlignDirections()\n        {\n            Vector3d1 directions;\n            directions.push_back(Vector3d(-1, 0, 0));\n            directions.push_back(Vector3d(1, 0, 0));\n            directions.push_back(Vector3d(0, -1, 0));\n            directions.push_back(Vector3d(0, 1, 0));\n            directions.push_back(Vector3d(0, 0, -1));\n            directions.push_back(Vector3d(0, 0, 1));\n            return directions;\n        }\n\n        static Vector3d1 EmumerateRotations()\n        {\n            Vector3d1 rotations;\n            rotations.emplace_back(Vector3d(90.0, 90.0, 180.0));\n            rotations.emplace_back(Vector3d(-90.0, 0.0, 90.0));\n            rotations.emplace_back(Vector3d(0.0, 180.0, 0.0));\n\n            rotations.emplace_back(Vector3d(90.0, 0.0, 180.0));\n            rotations.emplace_back(Vector3d(0.0, 0.0, 90.0));\n            rotations.emplace_back(Vector3d(0.0, -90.0, 0.0));\n\n            rotations.emplace_back(Vector3d(0.0, 0.0, 0.0));\n            rotations.emplace_back(Vector3d(90.0, 0.0, 90.0));\n            rotations.emplace_back(Vector3d(90.0, -90.0, 180.0));\n\n            rotations.emplace_back(Vector3d(0.0, 90.0, 0.0));\n            rotations.emplace_back(Vector3d(180.0, 0.0, 90.0));\n            rotations.emplace_back(Vector3d(90.0, -180.0, 180.0));\n\n            rotations.emplace_back(Vector3d(0.0, 180.0, 90.0));\n            rotations.emplace_back(Vector3d(-90.0, 90.0, 90.0));\n            rotations.emplace_back(Vector3d(90.0, 180.0, 0.0));\n\n            rotations.emplace_back(Vector3d(0.0, 0.0, 180.0));\n            rotations.emplace_back(Vector3d(0.0, -90.0, 90.0));\n            rotations.emplace_back(Vector3d(90.0, 0.0, -90.0));\n\n            rotations.emplace_back(Vector3d(-90.0, 0.0, -90.0));\n            rotations.emplace_back(Vector3d(180.0, 90.0, 90.0));\n            rotations.emplace_back(Vector3d(0.0, -180.0, 180.0));\n\n            rotations.emplace_back(Vector3d(90.0, 0.0, 0.0));\n            rotations.emplace_back(Vector3d(90.0, -90.0, 90.0));\n            rotations.emplace_back(Vector3d(0.0, 0.0, 270.0));\n\n            for (auto& rotation : rotations)\n            {\n                rotation[0] = rotation[0] / 180.0 * Math_PI;\n                rotation[1] = rotation[1] / 180.0 * Math_PI;\n                rotation[2] = rotation[2] / 180.0 * Math_PI;\n            }\n            return rotations;\n        };\n\n\n#pragma endregion\n\n#pragma region BasicMathFunctions\n\n        static double RandomD(const double& min_d = 0.0, const double& max_d = 1.0)\n        {\n            std::uniform_real_distribution<> dis(min_d, max_d);\n            return dis(MATHGEN);\n        }\n\n        //select a number among 0,1,2,...,s-1\n        //s should be positive int\n        static int RandomI(const int& s)\n        {\n            if (s == 1) return 0;\n            double x = 1.0 / s;\n            double d = RandomD();\n\n            for (int i = 0; i < s; i++)\n            {\n                double min_d = i * x;\n                double max_d = (static_cast<int64_t>(i) + 1)* x;\n                if (d >= min_d && d <= max_d)\n                {\n                    return i;\n                }\n            }\n\n            return -1;\n        }\n\n        static double RandomDD(const double& min_d = 0.0, const double& max_d = 1.0)\n        {\n            std::uniform_real_distribution<> dis(min_d, max_d);\n            return dis(MATHGEN);\n        }\n\n        //select a number among 0,1,2,...,s-1\n        //s should be positive int\n        static int RandomII(int s)\n        {\n            if (s == 1) return 0;\n            double x = 1.0 / s;\n            double d = RandomDD();\n\n            for (int i = 0; i < s; i++)\n            {\n                double min_d = i * x;\n                double max_d = (static_cast<int64_t>(i) + 1)* x;\n                if (d >= min_d && d <= max_d)\n                {\n                    return i;\n                }\n            }\n\n            return -1;\n        }\n\n        static Vector3d GetCrossproduct(const Vector3d& v1, const Vector3d& v2) {\n            return glm::cross(v1, v2);\n        }\n\n        template <class Type>\n        static double GetDotproduct(const Type& v1, const Type& v2) {\n            return glm::dot(v1, v2);\n        }\n\n        template <class Type>\n        static Type GetMinus(const Type& a, const Type& b)\n        {\n            Type c = a;\n            for (int i = 0; i < a.length(); i++)\n                c[i] = a[i] - b[i];\n            return c;\n        }\n\n        static bool AreAlmostEqual(const double& value1, const double& value2) {\n            if (value1 == value2) {\n                return true;\n            }\n            double eps = (glm::abs(value1) + glm::abs(value2) + 10.0) * DOUBLE_EPSILON;\n            double delta = value1 - value2;\n            return (-eps < delta) && (eps > delta);\n        }\n\n        static bool AreAlmostEqual_Double(const double& value1, const double& value2, const double& EPSILON) {\n            return IsAlmostZero_Double(value1 - value2, EPSILON);\n        }\n\n        static bool IsAlmostZero(const double& value) {\n            return (value < DOUBLE_EPSILON) && (value > -DOUBLE_EPSILON);\n        }\n        static bool IsAlmostZero_Double(const double& value, const double& EPSILON) {\n            return (value < EPSILON) && (value > -EPSILON);\n        }\n\n        /// Returns true if two given floating point numbers are epsilon-equal.\n        /// Method automatically adjust the epsilon to the absolute size of given numbers.\n        static bool AreAlmostEqual(const float& value1, const float& value2) {\n            // in case they are Infinities (then epsilon check does not work)\n            if (value1 == value2) {\n                return true;\n            }\n            // computes (|value1-value2| / (|value1| + |value2| + 10.0)) < SINGLE_EPSILON\n            float eps = (float)((glm::abs(value1) + glm::abs(value2) + 10.0) * SINGLE_EPSILON);\n            float delta = value1 - value2;\n            return (-eps < delta) && (eps > delta);\n        }\n\n        static void ZeroVector(Vector3d& v)\n        {\n            if (IsAlmostZero(v[0]))v[0] = 0.0;\n            if (IsAlmostZero(v[1]))v[1] = 0.0;\n            if (IsAlmostZero(v[2]))v[2] = 0.0;\n        }\n\n        template<class Type>\n        static double GetMax(const Type& vec)\n        {\n            double maxd = vec[0];\n            for (int i = 0; i < vec.length(); i++)\n                maxd = max(maxd, vec[i]);\n            return maxd;\n        }\n\n        static void GetMinMax(const Vector1d1& ds, double& mind, double& maxd)\n        {\n            mind = ds[0];\n            maxd = ds[0];\n            for (auto& d : ds)\n            {\n                mind = min(mind, d);\n                maxd = max(maxd, d);\n            }\n        }\n\n        static void GetMinMax(const Vector1d2& ds, double& mind, double& maxd)\n        {\n            mind = ds.front().front();\n            maxd = ds.front().front();\n            for (auto& d : ds)\n            {\n                for (auto& d_ : d)\n                {\n                    mind = min(mind, d_);\n                    maxd = max(maxd, d_);\n                }\n            }\n        }\n\n        template<class Type>\n        static bool VectorInsertNoDuplicate(std::vector<Type>& vecs, const Type& element)\n        {\n            if (CheckContain(vecs, element))\n                return false;\n\n            vecs.emplace_back(element);\n            return true;\n        }\n\n        template<class Type>\n        static void VectorInsertNoDuplicate(std::vector<Type>& vecs, const std::vector<Type>& elements)\n        {\n            for (auto& element : elements)\n                VectorInsertNoDuplicate(vecs, element);\n        }\n\n        template<class Type>\n        static std::vector<Type> VectorMerge(const std::vector<Type>& vecs_0, const std::vector<Type>& vecs_1)\n        {\n            std::vector<Type> result = vecs_0;\n            result.insert(result.end(), vecs_1.begin(), vecs_1.end());\n            return result;\n        }\n\n        template<class Type>\n        static bool CheckContain(const Vector1<Type>& vecs, const Type& element)\n        {\n            return std::find(vecs.begin(), vecs.end(), element) != vecs.end();\n        }\n\n        template<class Type>\n        static bool CheckContain(const Vector2<Type>& vecs, const Type& element)\n        {\n            return VectorIndex(vecs, element) >= 0;\n            //return std::find(vecs.begin(), vecs.end(), element) != vecs.end();\n        }\n\n\n        template <class Type>\n        static int VectorIndex(const std::vector <Type>& vecs, const Type& element)\n        {\n            for (int i = 0; i < vecs.size(); i++)\n            {\n                if (vecs[i] == element)\n                {\n                    return i;\n                }\n            }\n            return -1;\n        }\n\n\n        template <class Type>\n        static int VectorSize(const Vector2<Type>& vecs)\n        {\n            int nb = 0;\n            for (auto& vec : vecs)\n                nb += vec.size();\n            return nb;\n        }\n\n        template <class Type>\n        static int VectorSize(const Vector3<Type>& vecs)\n        {\n            int nb = 0;\n            for (auto& vec : vecs)\n                nb += VectorSize(vec);\n            return nb;\n        }\n\n        template <class Type>\n        static int VectorIndex(const std::vector <std::vector <Type>>& vecs, const Type& element)\n        {\n            for (int i = 0; i < vecs.size(); i++)\n            {\n                if (VectorIndex(vecs[i], element) >= 0)\n                    return i;\n            }\n            return -1;\n        }\n\n        template <class Type>\n        static std::vector <Type> VectorAdd(const std::vector <Type>& vecs, const Type& element)\n        {\n            std::vector <Type> result = vecs;\n            for (auto& r : result)\n                r += element;\n            return result;\n        }\n\n        static bool VectorContain(const std::vector<int>& vecs, const int& element)\n        {\n            for (int i = 0; i < vecs.size(); i++)\n            {\n                if (vecs[i] == element)\n                    return true;\n            }\n\n            return false;\n        }\n\n        static int VectorContainReturnIndex(const std::vector<int>& vecs, const int& element)\n        {\n            for (int i = 0; i < vecs.size(); i++)\n            {\n                if (vecs[i] == element)\n                    return i;\n            }\n\n            return -1;\n        }\n\n        static bool VectorContainForSpecialCase(const std::vector<std::vector<int>>& vecs, const std::vector<int>& element)\n        {\n            for (int i = 0; i < vecs.size(); i++)\n            {\n                if (vecs[i][0] == element[0] && vecs[i][1] == element[1])\n                    return true;\n            }\n\n            return false;\n        }\n        static bool VectorContainForSpecialCase1(const std::vector<std::vector<int>>& vecs, const std::vector<int>& element)\n        {\n            for (int i = 0; i < vecs.size(); i++)\n            {\n                if (vecs[i][0] == element[0] && vecs[i][1] == element[1]) return true;\n                if (vecs[i][0] == element[1] && vecs[i][1] == element[0]) return true;\n            }\n\n            return false;\n        }\n\n        static int VectorContainForSpecialCase2(const std::vector<std::vector<int>>& vecs, const int& element_0, const int& element_1)\n        {\n            for (int i = 0; i < vecs.size(); i++)\n            {\n                if (vecs[i][0] == element_0 && vecs[i][1] == element_1) return i;\n                if (vecs[i][0] == element_1 && vecs[i][1] == element_0) return i;\n            }\n            return -1;\n        }\n\n        static int VectorContainForSpecialCase3(const std::vector<std::vector<int>>& vecs, const int& element_0, const int& element_1)\n        {\n            for (int i = 0; i < vecs.size(); i++)\n            {\n                if (vecs[i][0] == element_0 && vecs[i][1] == element_1) return i;\n            }\n            return -1;\n        }\n#pragma endregion\n\n\n#pragma region Transformation\n\n        static Vector2d Vector3d2d(const Vector3d& v)\n        {\n            return Vector2d(v[0], v[1]);\n        }\n\n        static Vector2d1 Vector3d2d(const Vector3d1& vecs_3d)\n        {\n            Vector2d1 vecs_2d;\n            for (auto& v : vecs_3d)\n                vecs_2d.emplace_back(Vector3d2d(v));\n            return vecs_2d;\n        }\n\n        static Vector2d2 Vector3d2d(const Vector3d2& vecs_3d)\n        {\n            Vector2d2 vecs_2d;\n            for (auto v : vecs_3d)\n                vecs_2d.emplace_back(Vector3d2d(v));\n            return vecs_2d;\n        }\n\n        static Vector3d Vector2d3d(const Vector2d& v, const double& z = 0.0)\n        {\n            return Vector3d(v[0], v[1], z);\n        }\n\n        static Vector3d1 Vector2d3d(const Vector2d1& vecs_2d, double z = 0.0)\n        {\n            Vector3d1 vecs_3d;\n            for (auto v : vecs_2d)\n                vecs_3d.emplace_back(Vector2d3d(v, z));\n            return vecs_3d;\n        }\n\n        static Vector3d2 Vector2d3d(const Vector2d2& vecs_2d, double z = 0.0)\n        {\n            Vector3d2 vecs_3d;\n            for (auto v : vecs_2d)\n                vecs_3d.emplace_back(Vector2d3d(v, z));\n            return vecs_3d;\n        }\n\n        static Vector3d VecApplyM(const Vector3d& v, const  glm::dmat4& M)\n        {\n            return Vector3d(M * glm::vec4(v, 1.0)) - Vector3d(M * glm::vec4(Vector3d(0.0, 0.0, 0.0), 1.0));\n        }\n\n        static Vector3d1 VecApplyM(const Vector3d1& vecs, const glm::dmat4& M)\n        {\n            Vector3d1 ps;\n            for (auto& p : vecs)\n                ps.emplace_back(VecApplyM(p, M));\n            return ps;\n        }\n\n        static Vector3d2 VecApplyM(const Vector3d2& veces, const glm::dmat4& M)\n        {\n            Vector3d2 pses;\n            for (auto vecs : veces)\n                pses.emplace_back(VecApplyM(vecs, M));\n            return pses;\n        }\n\n        static Vector3d PosApplyM(const Vector3d& v, const glm::dmat4& M)\n        {\n            return Vector3d(M * glm::vec4(v, 1.0));\n        }\n\n        static Vector3d1 PosApplyM(const Vector3d1& vecs, const glm::dmat4& M)\n        {\n            Vector3d1 ps;\n            for (auto& p : vecs)\n                ps.emplace_back(PosApplyM(p, M));\n            return ps;\n        }\n\n        static std::pair<Vector3d, Vector3d> PosApplyM(const std::pair<Vector3d, Vector3d>& vecs, const glm::dmat4& M)\n        {\n            return std::pair<Vector3d, Vector3d>(PosApplyM(vecs.first, M), PosApplyM(vecs.second, M));\n        }\n\n        static Vector3d2 PosApplyM(const Vector3d2& veces, const glm::dmat4& M)\n        {\n            Vector3d2 pses;\n            for (auto vecs : veces)\n                pses.emplace_back(PosApplyM(vecs, M));\n            return pses;\n        }\n\n        static Vector3d3 PosApplyM(const Vector3d3& veces, const glm::dmat4& M)\n        {\n            Vector3d3 pses;\n            for (auto vecs : veces)\n                pses.emplace_back(PosApplyM(vecs, M));\n            return pses;\n        }\n\n        static glm::dmat4 RotationMatrixXYZ(const Vector3d& xx, const Vector3d& yy, const Vector3d& zz)\n        {\n            auto x = xx;\n            auto y = yy;\n            auto z = zz;\n\n            ZeroVector(x);\n            ZeroVector(y);\n            ZeroVector(z);\n            x = x / (double)GetLength(x);\n            y = y / (double)GetLength(y);\n            z = z / (double)GetLength(z);\n\n            glm::dmat4  rotationMatrix;\n\n            rotationMatrix[0][0] = x[0];\n            rotationMatrix[0][1] = y[0];\n            rotationMatrix[0][2] = z[0];\n            rotationMatrix[0][3] = 0.0;\n\n            rotationMatrix[1][0] = x[1];\n            rotationMatrix[1][1] = y[1];\n            rotationMatrix[1][2] = z[1];\n            rotationMatrix[1][3] = 0.0;\n\n            rotationMatrix[2][0] = x[2];\n            rotationMatrix[2][1] = y[2];\n            rotationMatrix[2][2] = z[2];\n            rotationMatrix[2][3] = 0.0;\n\n            rotationMatrix[3][0] = 0.0;\n            rotationMatrix[3][1] = 0.0;\n            rotationMatrix[3][2] = 0.0;\n            rotationMatrix[3][3] = 1.0;\n\n            return rotationMatrix;\n\n        }\n\n\n        static glm::dmat4 RotationMatrix(const Vector3d& o, const Vector3d& t, const Vector3d& n)\n        {\n            double angle = GetAngleBetween(o, t);\n\n            if (IsAlmostZero(angle))\n            {\n                glm::dmat4  rotationMatrix;\n\n                rotationMatrix[0][0] = 1.0;\n                rotationMatrix[0][1] = 0.0;\n                rotationMatrix[0][2] = 0.0;\n                rotationMatrix[0][3] = 0.0;\n                rotationMatrix[1][0] = 0.0;\n                rotationMatrix[1][1] = 1.0;\n                rotationMatrix[1][2] = 0.0;\n                rotationMatrix[1][3] = 0.0;\n                rotationMatrix[2][0] = 0.0;\n                rotationMatrix[2][1] = 0.0;\n                rotationMatrix[2][2] = 1.0;\n                rotationMatrix[2][3] = 0.0;\n                rotationMatrix[3][0] = 0.0;\n                rotationMatrix[3][1] = 0.0;\n                rotationMatrix[3][2] = 0.0;\n                rotationMatrix[3][3] = 1.0;\n\n                return rotationMatrix;\n            }\n            else\n            {\n                return RotationMatrix(n, angle);\n            }\n        }\n\n        static void AAA(const Vector3d& v, Vector3d& n)\n        {\n            auto a = v[0];\n            auto b = v[1];\n            auto c = v[2];\n            bool bx = IsAlmostZero(a);\n            bool by = IsAlmostZero(b);\n            bool bz = IsAlmostZero(c);\n\n            if (bx && by && bz)\n            {\n                std::cerr << \"if (bx&&by&&bz)\" << std::endl;\n                system(\"pause\");\n            }\n\n            if (bx && by && !bz)\n            {\n                n[0] = 1.0;\n                n[1] = 1.0;\n                n[2] = 0.0;\n            }\n            if (bx && !by && bz)\n            {\n                n[0] = 1.0;\n                n[1] = 0.0;\n                n[2] = 1.0;\n            }\n\n            if (bx && !by && !bz)\n            {\n                n[0] = 1.0;\n                n[1] = 1.0;\n                n[2] = -b / c;\n            }\n\n            if (!bx && by && bz)\n            {\n                n[0] = 0.0;\n                n[1] = 1.0;\n                n[2] = 1.0;\n            }\n\n            if (!bx && by && !bz)\n            {\n                n[0] = 1.0;\n                n[1] = 1.0;\n                n[2] = -a / c;\n            }\n            if (!bx && !by && bz)\n            {\n                n[0] = 1.0;\n                n[1] = -a / b;\n                n[2] = 1.0;\n            }\n\n            if (!bx && !by && !bz)\n            {\n                n[0] = 1.0;\n                n[1] = 1.0;\n                n[2] = -(a + b) / c;\n            }\n\n        }\n\n        static glm::dmat4 RotationMatrix(const Vector3d& o, const Vector3d& t)\n        {\n            Vector3d n = GetCrossproduct(o, t);\n            double angle = GetAngleBetween(o, t);\n\n            if (IsAlmostZero(angle - Math_PI))\n            {\n                AAA(o, n);\n            }\n\n            if (IsAlmostZero(angle))\n            {\n                glm::dmat4  rotationMatrix;\n\n                rotationMatrix[0][0] = 1.0;\n                rotationMatrix[0][1] = 0.0;\n                rotationMatrix[0][2] = 0.0;\n                rotationMatrix[0][3] = 0.0;\n                rotationMatrix[1][0] = 0.0;\n                rotationMatrix[1][1] = 1.0;\n                rotationMatrix[1][2] = 0.0;\n                rotationMatrix[1][3] = 0.0;\n                rotationMatrix[2][0] = 0.0;\n                rotationMatrix[2][1] = 0.0;\n                rotationMatrix[2][2] = 1.0;\n                rotationMatrix[2][3] = 0.0;\n                rotationMatrix[3][0] = 0.0;\n                rotationMatrix[3][1] = 0.0;\n                rotationMatrix[3][2] = 0.0;\n                rotationMatrix[3][3] = 1.0;\n\n                return rotationMatrix;\n            }\n            else\n            {\n                return RotationMatrix(n, angle);\n            }\n        }\n\n\n\n        static glm::dmat4 RotationMatrix(const Vector3d& n, const double& angle)\n        {\n            //return glm::rotate(angle, n);\n            double u = n[0];\n            double v = n[1];\n            double w = n[2];\n\n            glm::dmat4  rotationMatrix;\n\n            double L = (u * u + v * v + w * w);\n\n            //angle = angle * M_PI / 180.0; //converting to radian value\n            double u2 = u * u;\n            double v2 = v * v;\n            double w2 = w * w;\n\n            rotationMatrix[0][0] = (u2 + (v2 + w2) * cos(angle)) / L;\n            rotationMatrix[0][1] = (u * v * (1 - cos(angle)) - w * sqrt(L) * sin(angle)) / L;\n            rotationMatrix[0][2] = (u * w * (1 - cos(angle)) + v * sqrt(L) * sin(angle)) / L;\n            rotationMatrix[0][3] = 0.0;\n\n            rotationMatrix[1][0] = (u * v * (1 - cos(angle)) + w * sqrt(L) * sin(angle)) / L;\n            rotationMatrix[1][1] = (v2 + (u2 + w2) * cos(angle)) / L;\n            rotationMatrix[1][2] = (v * w * (1 - cos(angle)) - u * sqrt(L) * sin(angle)) / L;\n            rotationMatrix[1][3] = 0.0;\n\n            rotationMatrix[2][0] = (u * w * (1 - cos(angle)) - v * sqrt(L) * sin(angle)) / L;\n            rotationMatrix[2][1] = (v * w * (1 - cos(angle)) + u * sqrt(L) * sin(angle)) / L;\n            rotationMatrix[2][2] = (w2 + (u2 + v2) * cos(angle)) / L;\n            rotationMatrix[2][3] = 0.0;\n\n            rotationMatrix[3][0] = 0.0;\n            rotationMatrix[3][1] = 0.0;\n            rotationMatrix[3][2] = 0.0;\n            rotationMatrix[3][3] = 1.0;\n\n            return rotationMatrix;\n        }\n\n        static Vector3d RotationAxis(const Vector3d& p, const double& angle, const Vector3d& n)\n        {\n            //auto m = RotationMatrix(n, angle);\n            //return PosApplyM(p, m);\n\n            auto rtv = glm::rotate(angle, n)* glm::dvec4(p, 1.0);\n            return Vector3d(rtv[0], rtv[1], rtv[2]);\n            \n            /*\n            glm::dmat4 inputMatrix(0.0);\n            inputMatrix[0][0] = p[0];\n            inputMatrix[1][0] = p[1];\n            inputMatrix[2][0] = p[2];\n            inputMatrix[3][0] = 1.0;\n            double u = n[0];\n            double v = n[1];\n            double w = n[2];\n\n            glm::dmat4  rotationMatrix;\n\n            double L = (u * u + v * v + w * w);\n\n            //angle = angle * M_PI / 180.0; //converting to radian value\n            double u2 = u * u;\n            double v2 = v * v;\n            double w2 = w * w;\n\n            rotationMatrix[0][0] = (u2 + (v2 + w2) * glm::cos(angle)) / L;\n            rotationMatrix[0][1] = (u * v * (1 - glm::cos(angle)) - w * glm::sqrt(L) * glm::sin(angle)) / L;\n            rotationMatrix[0][2] = (u * w * (1 - glm::cos(angle)) + v * glm::sqrt(L) * glm::sin(angle)) / L;\n            rotationMatrix[0][3] = 0.0;\n\n            rotationMatrix[1][0] = (u * v * (1 - glm::cos(angle)) + w * glm::sqrt(L) * glm::sin(angle)) / L;\n            rotationMatrix[1][1] = (v2 + (u2 + w2) * glm::cos(angle)) / L;\n            rotationMatrix[1][2] = (v * w * (1 - glm::cos(angle)) - u * glm::sqrt(L) * glm::sin(angle)) / L;\n            rotationMatrix[1][3] = 0.0;\n\n            rotationMatrix[2][0] = (u * w * (1 - glm::cos(angle)) - v * glm::sqrt(L) * glm::sin(angle)) / L;\n            rotationMatrix[2][1] = (v * w * (1 - glm::cos(angle)) + u * glm::sqrt(L) * glm::sin(angle)) / L;\n            rotationMatrix[2][2] = (w2 + (u2 + v2) * glm::cos(angle)) / L;\n            rotationMatrix[2][3] = 0.0;\n\n            rotationMatrix[3][0] = 0.0;\n            rotationMatrix[3][1] = 0.0;\n            rotationMatrix[3][2] = 0.0;\n            rotationMatrix[3][3] = 1.0;\n\n            double outputMatrix[4][1];\n\n            for (int i = 0; i < 4; i++)\n            {\n                for (int j = 0; j < 1; j++)\n                {\n                    outputMatrix[i][j] = 0;\n                    for (int k = 0; k < 4; k++)\n                    {\n                        outputMatrix[i][j] += rotationMatrix[i][k] * inputMatrix[k][j];\n                    }\n                }\n            }\n            return Vector3d(outputMatrix[0][0], outputMatrix[1][0], outputMatrix[2][0]);\n            */\n        }\n\n        static glm::dmat4 TranslationMatrix(const Vector3d& v)\n        {\n            glm::dmat4  translationMatrix;\n            translationMatrix[0][0] = 1.0;\n            translationMatrix[0][1] = 0.0;\n            translationMatrix[0][2] = 0.0;\n            translationMatrix[0][3] = 0.0;\n\n            translationMatrix[1][0] = 0.0;\n            translationMatrix[1][1] = 1.0;\n            translationMatrix[1][2] = 0.0;\n            translationMatrix[1][3] = 0.0;\n\n            translationMatrix[2][0] = 0.0;\n            translationMatrix[2][1] = 0.0;\n            translationMatrix[2][2] = 1.0;\n            translationMatrix[2][3] = 0.0;\n\n            translationMatrix[3][0] = v[0];\n            translationMatrix[3][1] = v[1];\n            translationMatrix[3][2] = v[2];\n            translationMatrix[3][3] = 1.0;\n\n            return translationMatrix;\n        }\n\n        static glm::dmat4 ScaleMatrix(const Vector3d& v)\n        {\n            glm::dmat4  translationMatrix;\n            translationMatrix[0][0] = v[0];\n            translationMatrix[0][1] = 0.0;\n            translationMatrix[0][2] = 0.0;\n            translationMatrix[0][3] = 0.0;\n\n            translationMatrix[1][0] = 0.0;\n            translationMatrix[1][1] = v[1];\n            translationMatrix[1][2] = 0.0;\n            translationMatrix[1][3] = 0.0;\n\n            translationMatrix[2][0] = 0.0;\n            translationMatrix[2][1] = 0.0;\n            translationMatrix[2][2] = v[2];\n            translationMatrix[2][3] = 0.0;\n\n            translationMatrix[3][0] = 0;\n            translationMatrix[3][1] = 0;\n            translationMatrix[3][2] = 0;\n            translationMatrix[3][3] = 1.0;\n\n            return translationMatrix;\n        }\n\n        static Vector2d RotationAxis2d(const Vector2d& p, const double& angle, const Vector2d& center)\n        {\n            Vector3d r = RotationAxis(Vector3d(p[0] - center[0], 0.0, p[1] - center[1]),\n                angle, Vector3d(0.0, 1.0, 0.0)) + Vector3d(center[0], 0.0, center[1]);\n            return Vector2d(r[0], r[2]);\n        }\n\n        static Vector3d RotationAxis(const Vector3d& p, const double& angle, const Vector3d& ray_point, const Vector3d& ray_vector)\n        {\n            return RotationAxis(p - ray_point, angle, ray_vector) + ray_point;\n        }\n\n        static void RotationAxis(Vector3d1& points, const double& angle, const Vector3d& ray_point, const Vector3d& ray_vector)\n        {\n            for (int i = 0; i < points.size(); i++)\n                points[i] = RotationAxis(points[i], angle, ray_point, ray_vector);\n        }\n\n        static void RotationAxis(Vector3d2& points, const double& angle, const Vector3d& ray_point, const Vector3d& ray_vector)\n        {\n            for (int i = 0; i < points.size(); i++)\n                RotationAxis(points[i], angle, ray_point, ray_vector);\n        }\n        static void RotationAxis(Vector3d3& pointses, const double& angle, const Vector3d& ray_point, const Vector3d& ray_vector)\n        {\n            for (int i = 0; i < pointses.size(); i++)\n                RotationAxis(pointses[i], angle, ray_point, ray_vector);\n        }\n\n        static Vector3d Translate(const Vector3d& p, const Vector3d& v)\n        {\n            return p + v;\n        }\n\n        static void Translate(Vector3d1& points, const Vector3d& v)\n        {\n            for (int i = 0; i < points.size(); i++)\n                points[i] = Translate(points[i], v);\n        }\n\n        static void Translate(Vector3d2& points, const Vector3d& v)\n        {\n            for (int i = 0; i < points.size(); i++)\n                Translate(points[i], v);\n        }\n#pragma endregion\n\n\n#pragma region IOFunctions\n\n        static bool LoadExisting(const std::string& path)\n        {\n            std::ifstream file(path, std::ios::in);\n            if (!file) return false;\n            return true;\n        }\n\n        static bool LoadVectors(const std::string& path, Vector3d3& vec_3)\n        {\n            //zigzag_final_path\n            int nb_0, nb_1, nb_2;\n            std::ifstream file(path, std::ios::in);\n\n            if (!file) return false;\n\n            file >> nb_0;\n            for (int i = 0; i < nb_0; i++)\n            {\n                file >> nb_1;\n                Vector3d2 vec_2;\n                for (int j = 0; j < nb_1; j++)\n                {\n                    file >> nb_2;\n                    Vector3d1 vec_1(nb_2, Vector3d(0.0, 0.0, 0.0));\n                    for (int k = 0; k < nb_2; k++)\n                        file >> vec_1[k][0] >> vec_1[k][1] >> vec_1[k][2];\n                    vec_2.emplace_back(vec_1);\n                }\n                vec_3.emplace_back(vec_2);\n            }\n            file.clear();\n            file.close();\n\n            return true;\n        }\n\n        static bool LoadVectors(const std::string& path, Vector3d1& vec_3)\n        {\n            //zigzag_final_path\n            std::ifstream file(path, std::ios::in);\n\n            if (!file) return false;\n\n            int nb;\n            file >> nb;\n            for (int i = 0; i < nb; i++)\n            {\n                vec_3.emplace_back(Vector3d());\n                file >> vec_3.back()[0] >> vec_3.back()[1] >> vec_3.back()[2];\n            }\n            file.clear();\n            file.close();\n\n            return true;\n        }\n\n        static void OutputVectors(const std::string& out_path, const Vector3d3& vecs)\n        {\n            std::ofstream file(out_path);\n            file << vecs.size() << std::endl;\n\n            for (int i = 0; i < vecs.size(); i++) {\n                file << vecs[i].size() << std::endl;\n                for (int j = 0; j < vecs[i].size(); j++) {\n                    file << vecs[i][j].size() << std::endl;\n                    for (int k = 0; k < vecs[i][j].size(); k++)\n                        file << vecs[i][j][k][0] << \" \" << vecs[i][j][k][1] << \" \" << vecs[i][j][k][2] << \" \";\n                    file << \"\" << std::endl;\n                }\n            }\n\n            file.clear();\n            file.close();\n        }\n\n        static void OutputVectors(const std::string& out_path, const Vector3d1& vecs)\n        {\n            std::ofstream file(out_path);\n            file << vecs.size() << std::endl;\n            for (int i = 0; i < vecs.size(); i++)\n                file << vecs[i][0] << \" \" << vecs[i][1] << \" \" << vecs[i][2] << std::endl;\n            file.clear();\n            file.close();\n        }\n\n#if !defined(UNICODE) && !defined(_UNICODE) && !defined(__APPLE__)\n\n        static HMODULE LoadHMODULE(const string& dll_path)\n        {\n            if (!DetectExisting(dll_path))\n                MAssert(\"The dll does not exist: \" + dll_path);\n\n            HMODULE hModule = LoadLibrary(_T(dll_path.c_str()));\n            if (!hModule)\n            {\n                DWORD dw = GetLastError(); // returns 0xc1 (193)\n                MAssert(\"LoadLibrary failed with error code \" + std::to_string(dw));\n            }\n            else\n                std::cerr << \"LoadLibrary success\\n\";\n\n            return hModule;\n        };\n\n#endif\n\n        static void LoadObj3d(const char* path, std::vector<double>& coords, std::vector<int>& tris)\n        {\n            auto get_first_integer = [](const char* v)\n            {\n                int ival;\n                std::string s(v);\n                std::replace(s.begin(), s.end(), '/', ' ');\n                sscanf(s.c_str(), \"%d\", &ival);\n                return ival;\n            };\n\n            double x, y, z;\n            char line[1024], v0[1024], v1[1024], v2[1024];\n\n            // open the file, return if open fails\n            FILE* fp = fopen(path, \"r\");\n            if (!Functs::DetectExisting(path))\n            {\n                Functs::MAssert(\"This file does not exist: \" + std::string(path));\n                return;\n            };\n\n            while (fgets(line, 1024, fp))\n            {\n                if (line[0] == 'v')\n                {\n                    sscanf(line, \"%*s%lf%lf%lf\", &x, &y, &z);\n                    coords.push_back(x);\n                    coords.push_back(y);\n                    coords.push_back(z);\n                }\n                else\n                {\n                    if (line[0] == 'f')\n                    {\n                        sscanf(line, \"%*s%s%s%s\", v0, v1, v2);\n                        tris.push_back(get_first_integer(v0) - 1);\n                        tris.push_back(get_first_integer(v1) - 1);\n                        tris.push_back(get_first_integer(v2) - 1);\n                    }\n                }\n            }\n            fclose(fp);\n        };\n\n        static void LoadObj3d(const char* path_, Vector3d1& vecs, Vector1i1& face_id_0, Vector1i1& face_id_1, Vector1i1& face_id_2)\n        {\n            std::string path = path_;\n            if (path.substr(path.size() - 3, path.size()) == \"obj\")\n            {\n                std::vector<double> coords;\n                Vector1i1 tris;\n\n                LoadObj3d(path.c_str(), coords, tris);\n\n                if (coords.size() == 0)\n                {\n                    return;\n                }\n\n                for (int i = 0; i < (int)coords.size(); i += 3)\n                {\n                    vecs.push_back(Vector3d(coords[i + 0], coords[i + 1], coords[i + 2]));\n                }\n\n                for (int i = 0; i < (int)tris.size(); i += 3)\n                {\n                    face_id_0.push_back(tris[i + 0]);\n                    face_id_1.push_back(tris[i + 1]);\n                    face_id_2.push_back(tris[i + 2]);\n                }\n                /*********************************************************************************/\n            }\n        };\n\n\n        static void OutputRectangle2d(const std::string& path, const std::vector<Vector2d>& points)\n        {\n            std::ofstream file(path);\n\n            for (int i = 0; i < points.size(); i++)\n            {\n                file << \"v \" << points[i][0] << \" \" << points[i][1] << \" \" << 0.0 << std::endl;\n            }\n\n            int nb = 1;\n\n            file << \"f \";\n            for (int i = 0; i < points.size(); i++)\n            {\n                file << IntString(nb) << \" \";\n                nb++;\n            }\n            file << \"\" << std::endl;\n\n            file.clear();\n            file.close();\n        }\n\n        static void OutputObj3d(const std::string& path, const Vector3d1& points)\n        {\n            Functs::MAssert(points.size() >= 3,\"CGAL_Output_Obj error: vecs.size() < 3 \");\n            \n            std::ofstream file(path);\n            for (auto& p : points)\n                file << \"v \" << p[0] << \" \" << p[1] << \" \" << p[2] << std::endl;\n\n            int nb = 1;\n            file << \"f \";\n            for (int p = 0; p < points.size(); p++)\n            {\n                file << IntString(nb) << \" \";\n                nb++;\n            }\n            file << \"\" << std::endl;\n\n            file.clear();\n            file.close();\n        };\n\n        static void OutputObj3d(const std::string& path, const Vector3d1& points, const Vector3d1& colors)\n        {\n            Functs::MAssert(points.size()==colors.size(),\"points.size()!=colors.size()\");\n            Functs::MAssert(points.size() >= 3,\"CGAL_Output_Obj error: vecs.size() < 3 \");\n\n\n            std::ofstream file(path);\n            for(int i=0;i<points.size();i++)\n            {\n                auto p = points[i], c = colors[i];\n                file << \"v \";\n                file << p[0] << \" \" << p[1] << \" \" << p[2] <<\" \";\n                file << c[0] << \" \" << c[1] << \" \" << c[2];\n                file << std::endl;\n            }\n          \n            int nb = 1;\n            file << \"f \";\n            for (int p = 0; p < points.size(); p++)\n            {\n                file << IntString(nb) << \" \";\n                nb++;\n            }\n            file << \"\" << std::endl;\n\n            file.clear();\n            file.close();\n        };\n        \n        \n        static void OutputObj3d(const std::string& path, const Vector3d2& points, const int output_index = 1, const string str = \"\")\n        {\n            std::ofstream file(path);\n\n            for (auto& points_ : points)\n            {\n                for (auto& p : points_)\n                {\n                    file << \"v \" << p[0] << \" \" << p[1] << \" \" << p[2] << std::endl;\n                }\n            }\n\n            if (output_index == 2) file << \"g \" + str + \"_p_0\" << std::endl;\n\n            int nb = 1;\n            for (int i = 0; i < points.size(); i++)\n            {\n                if (output_index == 1)\n                    file << \"g \" + str + \"_f_\" << i << std::endl;\n                auto points_ = points[i];\n                file << \"f \";\n                for (int p = 0; p < points_.size(); p++)\n                {\n                    file << IntString(nb) << \" \";\n                    nb++;\n                }\n                file << \"\" << std::endl;\n            }\n\n            file.clear();\n            file.close();\n        };\n\n        static void OutputObj3d(const std::string& path, const Vector3d3& points, const int output_index = 1)\n        {\n            std::ofstream file(path);\n\n            for (auto& points_ : points)\n            {\n                for (auto& points__ : points_)\n                {\n                    for (auto& p : points__)\n                    {\n                        file << \"v \" << p[0] << \" \" << p[1] << \" \" << p[2] << std::endl;\n                    }\n                }\n            }\n\n            int nb = 1;\n            if (output_index == 3) file << \"g ps_0\" << std::endl;\n            for (int i = 0; i < points.size(); i++)\n            {\n                if (output_index == 2) file << \"g p_\" << i << std::endl;\n\n                for (int j = 0; j < points[i].size(); j++)\n                {\n                    if (output_index == 1) file << \"g f_\" << i << \"_\" << j << std::endl;\n\n                    auto points_ = points[i][j];\n                    file << \"f \";\n                    for (int p = 0; p < points_.size(); p++)\n                    {\n                        file << IntString(nb) << \" \";\n                        nb++;\n                    }\n                    file << \"\" << std::endl;\n                }\n            }\n            file.clear();\n            file.close();\n        };\n\n        static void OutputObj3d(const std::string& path, const Vector3d3& points, const Vector3d1& colors, const int& output_index = 1)\n        {\n            std::ofstream file(path);\n\n            for (int i = 0; i < points.size(); i++)\n            {\n                auto color = colors[i];\n                for (int j = 0; j < points[i].size(); j++)\n                {\n                    for (int k = 0; k < points[i][j].size(); k++)\n                    {\n                        file << \"v \" << points[i][j][k][0] << \" \" << points[i][j][k][1] << \" \" << points[i][j][k][2] << \" \" << color[0] << \" \" << color[1] << \" \" << color[2] << std::endl;\n                    }\n                }\n            }\n\n            int nb = 1;\n            if (output_index == 3) file << \"g ps_0\" << std::endl;\n            for (int i = 0; i < points.size(); i++)\n            {\n                if (output_index == 2) file << \"g p_\" << i << std::endl;\n\n                for (int j = 0; j < points[i].size(); j++)\n                {\n                    if (output_index == 1) file << \"g f_\" << i << \"_\" << j << std::endl;\n\n                    auto points_ = points[i][j];\n                    file << \"f \";\n                    for (int p = 0; p < points_.size(); p++)\n                    {\n                        file << IntString(nb) << \" \";\n                        nb++;\n                    }\n                    file << \"\" << std::endl;\n                }\n            }\n            file.clear();\n            file.close();\n        };\n\n        static void OutputObj3d(const std::string& path, const Vector3d3& points, const Vector3d2& colors, int output_index = 1)\n        {\n            std::ofstream file(path);\n\n            for (int i = 0; i < points.size(); i++)\n            {\n                for (int j = 0; j < points[i].size(); j++)\n                {\n                    auto color = colors[i][j];\n                    for (int k = 0; k < points[i][j].size(); k++)\n                    {\n                        file << \"v \" << points[i][j][k][0] << \" \" << points[i][j][k][1] << \" \" << points[i][j][k][2] << \" \" << color[0] << \" \" << color[1] << \" \" << color[2] << std::endl;\n                    }\n                }\n            }\n\n            int nb = 1;\n            if (output_index == 3) file << \"g ps_0\" << std::endl;\n            for (int i = 0; i < points.size(); i++)\n            {\n                if (output_index == 2) file << \"g p_\" << i << std::endl;\n\n                for (int j = 0; j < points[i].size(); j++)\n                {\n                    if (output_index == 1) file << \"g f_\" << i << \"_\" << j << std::endl;\n\n                    auto points_ = points[i][j];\n                    file << \"f \";\n                    for (int p = 0; p < points_.size(); p++)\n                    {\n                        file << IntString(nb) << \" \";\n                        nb++;\n                    }\n                    file << \"\" << std::endl;\n                }\n            }\n            file.clear();\n            file.close();\n        };\n\n        static void OutputObj3d(const std::string& path, const PGLTriMesh& tm)\n        {\n            OutputObj3d(path, tm.vecs, tm.face_id_0, tm.face_id_1, tm.face_id_2);\n        }\n\n        static void OutputObj3d(const std::string& path, const Vector3d1& vecs, const std::vector<int>& face_id_0, const std::vector<int>& face_id_1, const std::vector<int>& face_id_2)\n        {\n            if (vecs.size() < 3 || face_id_0.size() < 1 || face_id_1.size() < 1 || face_id_2.size() < 1)\n            {\n                std::cout << \"vecs.size() < 3 || face_id_0.size() < 1 || face_id_1.size() < 1 || face_id_2.size() < 1\" << std::endl;\n                return;\n            }\n\n            for (int i = 0; i < face_id_0.size(); i++)\n            {\n                int index_0 = face_id_0[i];\n                int index_1 = face_id_1[i];\n                int index_2 = face_id_2[i];\n                if (index_0 < 0 || index_0 >= vecs.size() || index_1 < 0 || index_1 >= vecs.size() || index_2 < 0 || index_2 >= vecs.size())\n                {\n                    std::cout << \"index_0 < 0 || index_0 >= vecs.size() || index_1 < 0 || index_1 >= vecs.size() || index_2 < 0 || index_2 >= vecs.size()\" << std::endl;\n                    return;\n                }\n            }\n\n            std::ofstream file(path);\n            for (int i = 0; i < vecs.size(); i++)\n            {\n                OutputIterInfo(\"Output Vecs: \", (int)vecs.size(), i, 10);\n                Vector3d v = vecs[i];\n                file << \"v \" << v[0] << \" \" << v[1] << \" \" << v[2] << std::endl;\n            }\n\n            for (int i = 0; i < face_id_0.size(); i++)\n            {\n                OutputIterInfo(\"Output faces: \", (int)face_id_0.size(), i, 10);\n                int index_0 = face_id_0[i];\n                int index_1 = face_id_1[i];\n                int index_2 = face_id_2[i];\n                if (index_0 != index_1 && index_0 != index_2 && index_1 != index_2)\n                    file << \"f \" << index_0 + 1 << \" \" << index_1 + 1 << \" \" << index_2 + 1 << std::endl;\n            }\n            file.close();\n        };\n\n        static void OutputObj3d(const char* path, const Vector3d1& vecs, const std::vector<std::vector<int>>& face_ids)\n        {\n            std::vector<int> face_id_0;\n            std::vector<int> face_id_1;\n            std::vector<int> face_id_2;\n\n            for (int i = 0; i < face_ids.size(); i++)\n            {\n                face_id_0.push_back(face_ids[i][0]);\n                face_id_1.push_back(face_ids[i][1]);\n                face_id_2.push_back(face_ids[i][2]);\n            }\n\n            OutputObj3d(path, vecs, face_id_0, face_id_1, face_id_2);\n        }\n\n        static void OutputObj3d(const char* path, const Vector3d1& vecs, const std::vector<std::vector<int>>& face_ids, const std::vector<int>& triangles_lables, const int& index)\n        {\n            std::vector<int> face_id_0;\n            std::vector<int> face_id_1;\n            std::vector<int> face_id_2;\n\n            std::vector<int> lables(vecs.size(), -1);\n            for (int i = 0; i < face_ids.size(); i++)\n            {\n                face_id_0.push_back(face_ids[i][0]);\n                face_id_1.push_back(face_ids[i][1]);\n                face_id_2.push_back(face_ids[i][2]);\n                if (triangles_lables[i] == index)\n                {\n                    lables[face_ids[i][0]] = 0;\n                    lables[face_ids[i][1]] = 0;\n                    lables[face_ids[i][2]] = 0;\n                }\n            }\n            Vector3d1 new_vecs;\n            std::vector<int> new_face_id_0;\n            std::vector<int> new_face_id_1;\n            std::vector<int> new_face_id_2;\n\n            int vertices_nb = 0;\n            for (int i = 0; i < vecs.size(); i++)\n            {\n                if (lables[i] == 0)\n                {\n                    Vector3d v = vecs[i];\n                    new_vecs.push_back(v);\n                    lables[i] = vertices_nb;\n                    vertices_nb++;\n                }\n            }\n\n            for (int i = 0; i < face_id_0.size(); i++)\n            {\n                if (triangles_lables[i] == index)\n                {\n                    new_face_id_0.push_back(lables[face_id_0[i]]);\n                    new_face_id_1.push_back(lables[face_id_1[i]]);\n                    new_face_id_2.push_back(lables[face_id_2[i]]);\n                }\n            }\n\n            OutputObj3d(path, new_vecs, new_face_id_0, new_face_id_1, new_face_id_2);\n        }\n\n        static void OutputObj3d(const char* path, const Vector3d1& vecs, const Vector3d1& colors, const std::vector<int>& face_id_0, const std::vector<int>& face_id_1, const std::vector<int>& face_id_2)\n        {\n            if (vecs.size() < 3 || colors.size() < 3 || face_id_0.size() < 1 || face_id_1.size() < 1 || face_id_2.size() < 1)\n            {\n                std::cout << \"CGAL_Output_Obj error: vecs.size() < 3 || face_id_0.size() < 1 || face_id_1.size() < 1 || face_id_2.size() < 1\" << std::endl;\n                return;\n            }\n\n            for (int i = 0; i < face_id_0.size(); i++)\n            {\n                int index_0 = face_id_0[i];\n                int index_1 = face_id_1[i];\n                int index_2 = face_id_2[i];\n\n                if (index_0 < 0 || index_0 >= vecs.size() || index_1 < 0 || index_1 >= vecs.size() || index_2 < 0 || index_2 >= vecs.size())\n                {\n                    std::cout << \"CGAL_Output_Obj error: index_0 < 0 || index_0 >= vecs.size() || index_1 < 0 || index_1 >= vecs.size() || index_2 < 0 || index_2 >= vecs.size()\" << std::endl;\n                    return;\n                }\n            }\n\n            std::ofstream file(path);\n            for (int i = 0; i < vecs.size(); i++)\n            {\n                file << \"v \" << vecs[i][0] << \" \" << vecs[i][1] << \" \" << vecs[i][2] << \" \" << colors[i][0] << \" \" << colors[i][1] << \" \" << colors[i][2] << std::endl;\n            }\n\n            for (int i = 0; i < face_id_0.size(); i++)\n            {\n                int index_0 = face_id_0[i];\n                int index_1 = face_id_1[i];\n                int index_2 = face_id_2[i];\n\n                if (index_0 != index_1 && index_0 != index_2 && index_1 != index_2)\n                    file << \"f \" << index_0 + 1 << \" \" << index_1 + 1 << \" \" << index_2 + 1 << std::endl;\n            }\n            file.close();\n        }\n\n        static void OutputObj3d(const char* path, const Vector3d1& vecs, const Vector3d1& colors, const std::vector<std::vector<int>>& face_ids)\n        {\n            std::vector<int> face_id_0;\n            std::vector<int> face_id_1;\n            std::vector<int> face_id_2;\n            for (int i = 0; i < face_ids.size(); i++)\n            {\n                face_id_0.push_back(face_ids[i][0]);\n                face_id_1.push_back(face_ids[i][1]);\n                face_id_2.push_back(face_ids[i][2]);\n            }\n            OutputObj3d(path, vecs, colors, face_id_0, face_id_1, face_id_2);\n        }\n\n        static void OutputOff3d(const char* path, const Vector3d1& vecs, const std::vector<int>& face_id_0, const std::vector<int>& face_id_1, const std::vector<int>& face_id_2)\n        {\n            if (vecs.size() < 3 || face_id_0.size() < 1 || face_id_1.size() < 1 || face_id_2.size() < 1)\n            {\n                std::cout << \"CGAL_Output_Off error: vecs.size() < 3 || face_id_0.size() < 1 || face_id_1.size() < 1 || face_id_2.size() < 1\" << std::endl;\n                return;\n            }\n\n            for (int i = 0; i < face_id_0.size(); i++)\n            {\n                int index_0 = face_id_0[i];\n                int index_1 = face_id_1[i];\n                int index_2 = face_id_2[i];\n\n                if (index_0 < 0 || index_0 >= vecs.size() || index_1 < 0 || index_1 >= vecs.size() || index_2 < 0 || index_2 >= vecs.size())\n                {\n                    std::cout << \"CGAL_Output_Off error: index_0 < 0 || index_0 >= vecs.size() || index_1 < 0 || index_1 >= vecs.size() || index_2 < 0 || index_2 >= vecs.size()\" << std::endl;\n                    return;\n                }\n            }\n            std::ofstream file(path);\n            file << \"OFF\" << std::endl;\n            file << vecs.size() << \" \" << face_id_0.size() << \" 0\" << std::endl;\n            for (int i = 0; i < vecs.size(); i++)\n                file << vecs[i][0] << \" \" << vecs[i][1] << \" \" << vecs[i][2] << std::endl;\n            for (int i = 0; i < face_id_0.size(); i++)\n                file << \"3 \" << face_id_0[i] << \" \" << face_id_1[i] << \" \" << face_id_2[i] << \" \" << std::endl;\n            file.close();\n        }\n\n        static void OutputMtl(const string& path, const Vector3d1& colors, const string& pre_name)\n        {\n            ofstream file(path);\n            for (int i = 0; i < colors.size(); i++)\n            {\n                auto color = colors[i];\n                file << \"newmtl \" << pre_name << i << std::endl;\n                file << \"illum 4\" << std::endl;\n                file << \"Kd \" << color[0] << \" \" << color[1] << \" \" << color[2] << std::endl;\n                file << \"Ka 0.00 0.00 0.00\" << std::endl;\n                file << \"Tf 1.00 1.00 1.00\" << std::endl;\n                file << \"Ni 1.00\" << std::endl;\n            }\n            file.close();\n        }\n\n\n        static void Export_Segment(std::ofstream& output, int& e_index,\n            const string& s_name, const Vector3d& start, const Vector3d& end,\n            const double& radius, const bool cube_face = true)\n        {\n            Export_Segment(output, e_index, s_name, Vector3d(-1.0, -1.0, -1.0), \"\", start, end, radius, cube_face);\n        }\n\n        static void Export_Segment(std::ofstream& output, int& e_index,\n            const string& s_name, const Vector3d& rgb, const Vector3d& start, const Vector3d& end,\n            const double& radius, const bool cube_face = true)\n        {\n            Export_Segment(output, e_index, s_name, rgb, \"\", start, end, radius, cube_face);\n        }\n\n        static void Export_Segment(std::ofstream& output, int& e_index,\n            const string& s_name, const string& mtl_name, const Vector3d& start, const Vector3d& end,\n            const double& radius, const bool cube_face = true)\n        {\n            Export_Segment(output, e_index, s_name, Vector3d(0.0, 0.0, 0.0), mtl_name, start, end, radius, cube_face);\n        }\n\n        static void Export_Segment(std::ofstream& output, int& e_index,\n            const string& s_name, const Vector3d& rgb, const string& mtl_name, const Vector3d& start, const Vector3d& end,\n            const double& radius, const bool cube_face = true)\n        {\n            Vector3d normal = end - start;\n            Vector3d base_1 = Vector3dBase(normal);\n\n            base_1 = GetVectorLength(base_1, radius);\n\n            Vector3d1 vecs;\n\n            if (cube_face)\n            {\n                for (int i = 0; i < 4; i++) {\n                    double angle = (double)(i)*Math_PI / 2.0;\n                    Vector3d v = Functs::RotationAxis(normal + base_1, angle, normal);\n                    vecs.push_back(v + start);\n                }\n                for (int i = 0; i < 4; i++) {\n                    vecs.push_back(vecs[i] - normal);\n                }\n            }\n            else\n            {\n                for (int i = 0; i < 2; i++) {\n                    double angle = (double)(i)*Math_PI;\n                    Vector3d v = Functs::RotationAxis(normal + base_1, angle, normal);\n                    vecs.push_back(v + start);\n                }\n                for (int i = 0; i < 2; i++) {\n                    vecs.push_back(vecs[i] - normal);\n                }\n            }\n\n            Vector1i2 faces;\n            if (cube_face)\n            {\n                int face_index_0[4] = { 0, 1, 2, 3 };\n                int face_index_1[4] = { 5, 1, 0, 4 };\n                int face_index_2[4] = { 4, 0, 3, 7 };\n                int face_index_3[4] = { 5, 4, 7, 6 };\n                int face_index_4[4] = { 7, 3, 2, 6 };\n                int face_index_5[4] = { 6, 2, 1, 5 };\n\n                faces.push_back(std::vector<int>(face_index_0, face_index_0 + 4));\n                faces.push_back(std::vector<int>(face_index_1, face_index_1 + 4));\n                faces.push_back(std::vector<int>(face_index_2, face_index_2 + 4));\n                faces.push_back(std::vector<int>(face_index_3, face_index_3 + 4));\n                faces.push_back(std::vector<int>(face_index_4, face_index_4 + 4));\n                faces.push_back(std::vector<int>(face_index_5, face_index_5 + 4));\n\n            }\n            else\n            {\n                int face_index_0[4] = { 0, 1, 3, 2 };\n                faces.push_back(std::vector<int>(face_index_0, face_index_0 + 4));\n            }\n\n\n            for (int i = 0; i < vecs.size(); i++)\n            {\n                if (mtl_name.size() != 0)\n                {\n                    output << \"v \" << vecs[i][0] << \" \" << vecs[i][1] << \" \" << vecs[i][2] << std::endl;\n\n                }\n                else\n                {\n                    if (rgb[0] >= 0 && rgb[1] >= 0 && rgb[2] >= 0)\n                        output << \"v \" << vecs[i][0] << \" \" << vecs[i][1] << \" \" << vecs[i][2] << \" \" <<\n                        rgb[0] << \" \" << rgb[1] << \" \" << rgb[2] << std::endl;\n                    else\n                        output << \"v \" << vecs[i][0] << \" \" << vecs[i][1] << \" \" << vecs[i][2] << std::endl;\n                }\n            }\n\n            if (std::string(s_name).size() != 0)\n                output << \"g \" + std::string(s_name) << std::endl;\n\n            if (mtl_name.size() != 0)\n                output << \"usemtl \" << mtl_name << std::endl;\n\n            for (int i = 0; i < faces.size(); i++) {\n                output << \"f \";\n                for (int j = faces[i].size() - 1; j >= 0; j--)\n                {\n                    output << faces[i][j] + e_index << \" \";\n                }\n                output << \"\" << std::endl;\n            }\n\n            e_index += (int)vecs.size();\n        }\n\n        static void Export_Stick(std::ofstream& output, int& e_index,\n            const string& s_name, const Vector3d& rgb, const Vector3d1& start_poly, const Vector3d1& end_poly)\n        {\n            Export_Stick(output, e_index, s_name, rgb, \"\", start_poly, end_poly);\n        }\n\n        static void Export_Stick(std::ofstream& output, int& e_index,\n            const string& s_name, const string& mtl_name, const Vector3d1& start_poly, const Vector3d1& end_poly)\n        {\n            Export_Stick(output, e_index, s_name, Vector3d(-1.0, -1.0, -1.0), mtl_name, start_poly, end_poly);\n        }\n\n        static void Export_Stick(std::ofstream& output, int& e_index,\n            const string& s_name, const Vector3d1& start_poly, const Vector3d1& end_poly)\n        {\n            Export_Stick(output, e_index, s_name, Vector3d(-1.0, -1.0, -1.0), \"\", start_poly, end_poly);\n        }\n\n        static void Export_Stick(std::ofstream& output, int& e_index,\n            const string& s_name, const Vector3d& rgb, const string& mtl_name, const Vector3d1& start_poly, const Vector3d1& end_poly)\n        {\n            //Functs::MAssert(start_poly.size()<3||end_poly.size()<3|| start_poly.size()!=end_poly.size(), \"start_poly.size()<3||end_poly.size()<3|| start_poly.size()!=end_poly.size()\");\n\n            for (int i = 0; i < start_poly.size(); i++)\n            {\n                if (mtl_name.size() != 0)\n                {\n                    output << \"v \" << start_poly[i][0] << \" \" << start_poly[i][1] << \" \" << start_poly[i][2] << std::endl;\n\n                }\n                else\n                {\n                    if (rgb[0] >= 0 && rgb[1] >= 0 && rgb[2] >= 0)\n                        output << \"v \" << start_poly[i][0] << \" \" << start_poly[i][1] << \" \" << start_poly[i][2] << \" \" <<\n                        rgb[0] << \" \" << rgb[1] << \" \" << rgb[2] << std::endl;\n                    else\n                        output << \"v \" << start_poly[i][0] << \" \" << start_poly[i][1] << \" \" << start_poly[i][2] << std::endl;\n                }\n            }\n\n            for (int i = 0; i < end_poly.size(); i++)\n            {\n                if (mtl_name.size() != 0)\n                {\n                    output << \"v \" << end_poly[i][0] << \" \" << end_poly[i][1] << \" \" << end_poly[i][2] << std::endl;\n\n                }\n                else\n                {\n                    if (rgb[0] >= 0 && rgb[1] >= 0 && rgb[2] >= 0)\n                        output << \"v \" << end_poly[i][0] << \" \" << end_poly[i][1] << \" \" << end_poly[i][2] << \" \" <<\n                        rgb[0] << \" \" << rgb[1] << \" \" << rgb[2] << std::endl;\n                    else\n                        output << \"v \" << end_poly[i][0] << \" \" << end_poly[i][1] << \" \" << end_poly[i][2] << std::endl;\n                }\n            }\n\n\n            if (std::string(s_name).size() != 0)\n                output << \"g \" + std::string(s_name) << std::endl;\n\n            if (mtl_name.size() != 0)\n                output << \"usemtl \" << mtl_name << std::endl;\n\n            output << \"f \";\n            for (int i = 0; i < start_poly.size(); i++)\n                output << i + e_index << \" \";\n            output << std::endl;\n\n            output << \"f \";\n            for (int i = end_poly.size() - 1; i >= 0; i--)\n                output << i + e_index + start_poly.size() << \" \";\n            output << std::endl;\n\n            for (int i = 0; i < start_poly.size(); i++)\n            {\n                auto a = std::to_string(e_index + i);\n                auto b = std::to_string(e_index + (i + 1) % start_poly.size());\n                auto a_ = std::to_string(start_poly.size() + e_index + i);\n                auto b_ = std::to_string(start_poly.size() + e_index + (i + 1) % start_poly.size());\n\n                output << \"f \" << a_ << \" \" << b_ << \" \" << b << \" \" << a << std::endl;;\n            }\n\n            e_index += (int)start_poly.size() + (int)end_poly.size();\n        }\n\n        static void Export_Point(std::ofstream& output, int& e_index, const string& s_name, const Vector3d point, const double& radius)\n        {\n            Export_Point(output, e_index, s_name, Vector3d(-1.0, -1.0, -1.0), \"\", point, radius);\n        }\n\n        static void Export_Point(std::ofstream& output, int& e_index, const string& s_name, const Vector3d& rgb, const Vector3d point, const double& radius)\n        {\n            Export_Point(output, e_index, s_name, rgb, \"\", point, radius);\n        }\n\n        static void Export_Point(std::ofstream& output, int& e_index, const string& s_name, const string& mtl_name, const Vector3d point, const double& radius)\n        {\n            Export_Point(output, e_index, s_name, Vector3d(0.0, 0.0, 0.0), mtl_name, point, radius);\n        }\n\n        static void Export_Point(std::ofstream& output, int& e_index, const Vector3d point, const double& radius)\n        {\n            Export_Point(output, e_index, \"\", Vector3d(-1.0, -1.0, -1.0), \"\", point, radius);\n        }\n\n        static void Export_Point(std::ofstream& output, int& e_index, const Vector3d& rgb, const Vector3d point, const double& radius)\n        {\n            Export_Point(output, e_index, \"\", rgb, \"\", point, radius);\n        }\n\n        static void Export_Point\n        (std::ofstream& output, int& e_index, const string& s_name,\n            const Vector3d& rgb, const string& mtl_name, const Vector3d point, const double& radius)\n        {\n            Vector3d1 vecs;\n            vecs.push_back(Vector3d(0.5, 0.5, 0.5));\n            vecs.push_back(Vector3d(-0.5, 0.5, 0.5));\n            vecs.push_back(Vector3d(-0.5, 0.5, -0.5));\n            vecs.push_back(Vector3d(0.5, 0.5, -0.5));\n\n            vecs.push_back(Vector3d(0.5, -0.5, 0.5));\n            vecs.push_back(Vector3d(-0.5, -0.5, 0.5));\n            vecs.push_back(Vector3d(-0.5, -0.5, -0.5));\n            vecs.push_back(Vector3d(0.5, -0.5, -0.5));\n\n            Vector1i2 faces;\n\n            int face_index_0[4] = { 0, 1, 2, 3 };\n            int face_index_1[4] = { 5, 1, 0, 4 };\n            int face_index_2[4] = { 4, 0, 3, 7 };\n            int face_index_3[4] = { 5, 4, 7, 6 };\n            int face_index_4[4] = { 7, 3, 2, 6 };\n            int face_index_5[4] = { 6, 2, 1, 5 };\n\n            faces.push_back(std::vector<int>(face_index_0, face_index_0 + 4));\n            faces.push_back(std::vector<int>(face_index_1, face_index_1 + 4));\n            faces.push_back(std::vector<int>(face_index_2, face_index_2 + 4));\n            faces.push_back(std::vector<int>(face_index_3, face_index_3 + 4));\n            faces.push_back(std::vector<int>(face_index_4, face_index_4 + 4));\n            faces.push_back(std::vector<int>(face_index_5, face_index_5 + 4));\n\n            for (int i = 0; i < vecs.size(); i++) {\n                vecs[i][0] = vecs[i][0] * radius;\n                vecs[i][1] = vecs[i][1] * radius;\n                vecs[i][2] = vecs[i][2] * radius;\n\n                vecs[i][0] += point[0];\n                vecs[i][1] += point[1];\n                vecs[i][2] += point[2];\n\n                if (mtl_name.size() != 0)\n                    output << \"v \" << vecs[i][0] << \" \" << vecs[i][1] << \" \" << vecs[i][2] << std::endl;\n                else\n                {\n                    if (rgb[0] >= 0 && rgb[1] >= 0 && rgb[2] >= 0)\n                        output << \"v \" << vecs[i][0] << \" \" << vecs[i][1] << \" \" << vecs[i][2] << \" \" << rgb[0] << \" \" << rgb[1] << \" \" << rgb[2] << std::endl;\n                    else\n                        output << \"v \" << vecs[i][0] << \" \" << vecs[i][1] << \" \" << vecs[i][2] << std::endl;\n                }\n            }\n\n            if (std::string(s_name).size() != 0)\n                output << \"g \" + std::string(s_name) << std::endl;\n\n            if (mtl_name.size() != 0)\n                output << \"usemtl \" << mtl_name << std::endl;\n\n\n            for (int i = 0; i < faces.size(); i++) {\n                output << \"f \";\n\n                for (int j = (int)faces[i].size() - 1; j >= 0; j--) {\n                    output << faces[i][j] + e_index << \" \";\n                }\n                output << \"\" << std::endl;\n            }\n            e_index += 8;\n        }\n\n        static void Output_tree(const int& nodes_nb, const std::vector<int>& edges,\n            const std::string& path, const std::vector<string> labels = std::vector<string>())\n        {\n            std::ofstream file(path);\n\n            file << \"Mark Newman on Sat Jul 22 05:32:16 2006\" << std::endl;\n            file << \"graph\" << std::endl;\n            file << \"[\" << std::endl;\n            file << \"  directed 0\" << std::endl;\n\n            for (int i = 0; i < nodes_nb; i++)\n            {\n                file << \"node\" << std::endl;\n                file << \"[\" << std::endl;\n                file << \"id \" << i << std::endl;\n\n                if (labels.size() == nodes_nb)\n                    file << \"label \" << labels[i] << std::endl;\n                else\n                    file << \"label \" << i << std::endl;\n\n                file << \"]\" << std::endl;\n            }\n\n            for (int i = 0; i < edges.size(); i = i + 2)\n            {\n                file << \"edge\" << std::endl;\n                file << \"[\" << std::endl;\n\n                file << \"source \" << edges[i] << std::endl;\n                file << \"target \" << edges[static_cast<int64_t>(i) + 1] << std::endl;\n\n                file << \"]\" << std::endl;\n            }\n\n            file << \"]\" << std::endl;\n\n            file.clear();\n            file.close();\n        }\n\n\n#ifndef __APPLE__\n        static void ClearFolder(const std::string& path)\n        {\n\t\t\tif (!DetectExisting(path))\n\t\t\t{\n\t\t\t\tauto folders = SplitStr(StringReplace(path, \"\\\\\", \"/\"), \"/\");\n\t\t\t\tif (folders.back() == \"\")\n\t\t\t\t\tfolders.erase(folders.begin() + folders.size() - 1);\n\t\t\t\tstd::string str;\n\t\t\t\tfor (int i = 0; i < folders.size(); i++)\n\t\t\t\t{\n\t\t\t\t\tstr += folders[i] + \"/\";\n\t\t\t\t\tif (!DetectExisting(str))\n\t\t\t\t\t{\n\t\t\t\t\t\tif (_mkdir(str.c_str())) {};\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\tstd::string del_cmd = \"del /f/s/q \" + path + \" > nul\";\n\t\t\t\tsystem(del_cmd.c_str());\n\t\t\t\tstd::string rmdir_cmd = \"rmdir /s/q \" + path;\n\t\t\t\tsystem(rmdir_cmd.c_str());\n\n\t\t\t\tif (_mkdir(path.c_str())) {};\n\t\t\t}\n        }\n        static bool DetectExisting(const std::string& path)\n        {\n            struct stat buffer;\n            return (stat(path.c_str(), &buffer) == 0);\n        }\n#else\n        static void ClearFolder(const std::string& path)\n        {\n            if (access(path.c_str(), 0) == -1)\n            {\n\t\t\t\tauto folders = SplitStr(StringReplace(path, \"\\\\\", \"/\"), \"/\");\n\t\t\t\tif (folders.back() == \"\")\n\t\t\t\t\tfolders.erase(folders.begin() + folders.size() - 1);\n\t\t\t\tstd::string str;\n\t\t\t\tfor (int i = 0; i < folders.size(); i++)\n\t\t\t\t{\n\t\t\t\t\tstr += folders[i] + \"/\";\n\t\t\t\t\tif (!DetectExisting(str))\n\t\t\t\t\t{\n                        system(std::string(\"mkdir \" + str).c_str());\n\t\t\t\t\t}\n\t\t\t\t}\n            }\n            else\n            {\n\t\t\t\tstd::string del_cmd = \"rm -rf \" + path;\n\t\t\t\tsystem(del_cmd.c_str());\n\t\t\t\tstd::string mkdir_cmd = \"mkdir \" + path;\n\t\t\t\tsystem(mkdir_cmd.c_str());\n            }\n        }\n        \n        static bool DetectExisting(const std::string& path)\n        {\n            if (access(path.c_str(), 0) == -1)\n                return false;\n            else\n                return true;\n        }\n#endif\n\n\n\n\n#ifndef __APPLE__\n        static std::string EXP(const std::string& py_path)\n        {\n            std::string path = std::string(_pgmptr).substr(0, std::string(_pgmptr).find_last_of('\\\\')) + py_path;\n            //std::string path = std::string(_pgmptr).substr(0, std::string(_pgmptr).find_last_of('\\\\')) + py_path;\n            if (!Functs::DetectExisting(path))\n                Functs::MAssert(\"std::string EXP(const std::string py_path=\"\")\");\n            return path;\n        }\n\n        static VectorStr1 GetFilesInDirectory(const std::string& path)\n        {\n\n            vector<string> names;\n\n#if !defined(UNICODE) && !defined(_UNICODE)\n            string search_path = path + \"/*.*\";\n            WIN32_FIND_DATA fd;\n            HANDLE hFind = ::FindFirstFile(search_path.c_str(), &fd);\n            if (hFind != INVALID_HANDLE_VALUE) {\n                do {\n                    // read all (real) files in current folder\n                    // , delete '!' read other 2 default folder . and ..\n                    if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {\n                        names.push_back(fd.cFileName);\n                    }\n                } while (::FindNextFile(hFind, &fd));\n                ::FindClose(hFind);\n            }\n#endif\n\n            return names;\n        }\n#else\n        static VectorStr1 GetFilesInDirectory(const std::string& path)\n        {\n            vector<string> names;\n            //for (const auto & entry : fs::directory_iterator(path))\n             //   names.push_back(entry.path());\n            Functs::MAssert(\"static VectorStr1 GetFilesInDirectory(const std::string& path)\");\n            return names;\n        }\n#endif\n\n\n\n#pragma endregion\n\n#pragma region Graph\n\n        static std::vector<int> MinimalSpanningTreeGeneral(\n            const std::vector<int>& edges,\n            const std::vector<double>& costs)\n        {\n            auto unique_nodes = UniqueSet(edges);\n\n            int node_nb = static_cast<int>(unique_nodes.size());\n\n            std::map<int, int> unique_map_0;\n            std::map<int, int> unique_map_1;\n            for (int i = 0; i < unique_nodes.size(); i++)\n            {\n                unique_map_0.insert(std::pair<int, int>(unique_nodes[i], i));\n                unique_map_1.insert(std::pair<int, int>(i, unique_nodes[i]));\n            }\n\n            std::vector<int> map_edges;\n            for (auto edge : edges) map_edges.emplace_back(unique_map_0.at(edge));\n\n            auto mst = MinimalSpanningTree(node_nb, map_edges, costs);\n\n            std::vector<int> map_mst;\n            for (auto m : mst) map_mst.emplace_back(unique_map_1.at(m));\n\n            return map_mst;\n        }\n\n        static std::vector<int> MinimalSpanningTree(\n            const int& node_nb, const std::vector<int>& edges, const std::vector<double>& costs)\n        {\n            std::vector<int> mst;\n            std::vector<int> nodes;\n\n            for (int i = 0; i < node_nb; i++) nodes.push_back(i);\n\n            std::vector<std::vector<int>> containers;\n            for (int i = 0; i < nodes.size(); i++)\n            {\n                std::vector<int> container;\n                container.push_back(nodes[i]);\n                containers.push_back(container);\n                std::vector<int>().swap(container);\n            }\n\n            std::vector<bool> edges_used;\n            for (int i = 0; i < costs.size(); i++)\n                edges_used.push_back(false);\n\n            do\n            {\n                //find a minimal cost edge\n                int minimal_cost_edge_index = -1;\n                double minimal_cost = MAXDOUBLE;\n#pragma region find_a_minimal_cost_edge\n\n                for (int j = 0; j < costs.size(); j++)\n                {\n                    if (!edges_used[j])\n                    {\n                        if (costs[j] < minimal_cost)\n                        {\n                            minimal_cost = costs[j];\n                            minimal_cost_edge_index = j;\n                        }\n                    }\n                }\n#pragma endregion\n\n                if (minimal_cost_edge_index < 0)\n                    break;\n\n                //check valid\n                int edge_index_0 = static_cast<int>(2)* minimal_cost_edge_index;\n                int edge_index_1 = static_cast<int>(2)* minimal_cost_edge_index + 1;\n                int node_index_0 = edges[edge_index_0];\n                int node_index_1 = edges[edge_index_1];\n\n                int container_0 = -1;\n                int container_0_0 = -1;\n                int container_1 = -1;\n                int container_1_0 = -1;\n\n                for (int j = 0; j < containers.size() && (container_0 < 0 || container_1 < 0); j++)\n                {\n                    for (int k = 0; k < containers[j].size() && (container_0 < 0 || container_1 < 0); k++)\n                    {\n                        if (node_index_0 == containers[j][k])\n                        {\n                            container_0 = j;\n                            container_0_0 = k;\n                        }\n                        if (node_index_1 == containers[j][k])\n                        {\n                            container_1 = j;\n                            container_1_0 = k;\n                        }\n                    }\n                }\n\n                if (!(container_0 >= 0 && container_1 >= 0))\n                {\n                    break;\n                }\n\n                if (container_0 == container_1)\n                {\n                    edges_used[minimal_cost_edge_index] = true;\n                }\n                else\n                {\n                    mst.push_back(node_index_0);\n                    mst.push_back(node_index_1);\n                    edges_used[minimal_cost_edge_index] = true;\n\n                    for (int i = 0; i < containers[container_1].size(); i++)\n                    {\n                        containers[container_0].push_back(containers[container_1][i]);\n                    }\n\n                    containers.erase(containers.begin() + container_1);\n                }\n\n            } while (containers.size() != 1);\n\n            std::vector<bool>().swap(edges_used);\n            std::vector<std::vector<int>>().swap(containers);\n\n            std::vector<int>().swap(nodes);\n\n\n            return mst;\n        };\n\n        static std::vector<std::vector<int>> ConnectedComponents(const int& node_nb, const std::vector<std::pair<int, int>>& tree)\n        {\n            std::vector<int> tree_;\n            for (auto& o : tree)\n            {\n                tree_.emplace_back(o.first);\n                tree_.emplace_back(o.second);\n            }\n            return ConnectedComponents(node_nb, tree_);\n        }\n\n        static std::vector<std::vector<int>> ConnectedComponentsGeneral(const Vector1i1& nodes, const std::vector<std::pair<int, int>>& tree)\n        {\n            std::vector<int> tree_;\n            for (auto& o : tree)\n            {\n                tree_.emplace_back(o.first);\n                tree_.emplace_back(o.second);\n            }\n            return ConnectedComponentsGeneral(nodes, tree_);\n        }\n\n        static std::vector<std::vector<int>> ConnectedComponentsGeneral(const Vector1i1& nodes, const std::vector<int>& tree)\n        {\n            int node_nb = static_cast<int>(nodes.size());\n\n            std::map<int, int> unique_map_0;\n            std::map<int, int> unique_map_1;\n            for (int i = 0; i < nodes.size(); i++)\n            {\n                unique_map_0.insert(std::pair<int, int>(nodes[i], i));\n                unique_map_1.insert(std::pair<int, int>(i, nodes[i]));\n            }\n\n            std::vector<int> map_edges;\n            for (auto edge : tree) map_edges.emplace_back(unique_map_0.at(edge));\n\n            auto components = ConnectedComponents(node_nb, map_edges);\n\n            std::vector<std::vector<int>> map_components;\n            for (auto component : components)\n            {\n                map_components.emplace_back(std::vector<int>());\n                for (auto c : component)\n                    map_components.back().emplace_back(unique_map_1.at(c));\n            }\n            return map_components;\n        }\n\n        static std::vector<std::vector<int>> ConnectedComponents(const int& node_nb, const std::vector<int>& tree)\n        {\n            std::vector<std::vector<int>> components;\n            std::vector<int> index(node_nb, -1);\n            int nb = 0;\n            for (int i = 0; i < tree.size(); i = i + 2)\n            {\n                int ii = i + 1;\n                if (index[tree[i]] == -1 && index[tree[ii]] == -1)\n                {\n                    index[tree[i]] = nb;\n                    index[tree[ii]] = nb;\n                    nb++;\n                }\n                if (index[tree[i]] == -1 && index[tree[ii]] != -1)\n                {\n                    index[tree[i]] = index[tree[ii]];\n                }\n                if (index[tree[i]] != -1 && index[tree[ii]] == -1)\n                {\n                    index[tree[ii]] = index[tree[i]];\n                }\n\n                if (index[tree[i]] != -1 && index[tree[ii]] != -1)\n                {\n                    int min_index = std::min(index[tree[i]], index[tree[ii]]);\n                    int max_index = std::max(index[tree[i]], index[tree[ii]]);\n                    for (auto& index_ : index)\n                    {\n                        if (index_ == max_index)index_ = min_index;\n                    }\n                }\n\n            }\n\n            for (int i = 0; i < nb; i++)\n            {\n                std::vector<int> one;\n                for (int j = 0; j < index.size(); j++)\n                    if (index[j] == i)\n                        one.emplace_back(j);\n                if (!one.empty())components.emplace_back(one);\n            }\n\n            for (int j = 0; j < index.size(); j++) if (index[j] == -1)components.emplace_back(std::vector<int>(1, j));\n\n            for (auto& component : components)\n                std::sort(component.begin(), component.end());\n            return components;\n        };\n\n#pragma endregion\n\n#pragma region DevelopmentRelated\n        static bool CerrLine(const string& line, const int level = 0)\n        {\n            for (int i = 0; i < level; i++)\n                std::cerr << CERR_ITER;\n            std::cerr << line << std::endl;\n            return true;\n        }\n\n        static bool CerrLine(ofstream& file, const std::string& line, const int level = 0)\n        {\n            for (int i = 0; i < level; i++)\n            {\n                file << CERR_ITER;\n                std::cerr << CERR_ITER;\n            }\n            file << line << std::endl;\n            std::cerr << line << std::endl;\n            return true;\n        }\n\n\n        //tn: total number of iterations\n        //cn: current iteration\n        //fn: output frequency number\n        static void OutputIterInfo(const string& title, const int& tn, const int& cn, const int& fn, const int level = 0)\n        {\n            int delta = fn > tn ? 1 : tn / fn;\n\n            if (cn % delta == 0)\n            {\n                if (cn == 0)\n                {\n                    for (int i = 0; i < level; i++)\n                        std::cerr << CERR_ITER;\n                    std::cerr << title << \": \";\n                }\n                std::cerr << Functs::DoubleString((double)(100.0 * cn / tn), 1) << \"% \";\n                if (cn + delta >= tn) std::cerr << std::endl;\n            }\n        }\n\n        static void MAssert(const std::string& str, const double sleep_seconds = -1)\n        {\n            std::cerr << \"Bug: \" << str << std::endl;\n            if (sleep_seconds <= 0)\n            {\n                if (MACEN)system(\"read -p 'Press Enter to continue...' var\");\n                if (WINEN)system(\"pause\");\n            }\n            else\n                MSleep(sleep_seconds);\n        }\n\n        static void MAssert(const char* str, const double sleep_seconds = -1)\n        {\n            MAssert(std::string(str), sleep_seconds);\n        }\n\n\n        static bool MAssert(const bool& b, const std::string& str, const double sleep_seconds = -1)\n        {\n            if (!b)MAssert(str, sleep_seconds);\n            return b;\n        }\n\n        static bool MAssert(const bool& b, const char* str, const double sleep_seconds = -1)\n        {\n            if (!b)MAssert(str, sleep_seconds);\n            return b;\n        }\n\n        static void MSleep(const double& second)\n        {\n            this_thread::sleep_for(chrono::milliseconds((int)(second * 1000)));\n        }\n\n\n#ifndef __APPLE__\n        static void RunPY(const std::string& py_path, const std::string& paras)\n        {\n            std::string cmd = \"python \" + Functs::EXP(py_path) + \" \" + paras;\n            system(cmd.c_str());\n        }\n        static std::string WinGetCurDirectory()\n        {\n            char tmp[256];\n            if (_getcwd(tmp, 256)) {};\n            return std::string(tmp);\n        }\n#else\n        static std::string WinGetCurDirectory()\n        {\n            char tmp[256];\n            if (getcwd(tmp, 256)) {};\n            return std::string(tmp);\n        }\n#endif\n\n        static void RunCMD(const std::string& cmd_str)\n        {\n            std::cerr << \"Command String: \" << cmd_str << std::endl;;\n            system(cmd_str.c_str());\n        }\n\n        static std::string WinGetUserName()\n        {\n            char* user = getenv(\"username\");\n            return std::string(user);\n        }\n\n\n        static bool WinCopy(const std::string& source_file, const std::string& target_folder, const bool& b = true)\n        {\n            if (!Functs::DetectExisting(source_file))\n            {\n                MAssert(\"Source file does not exist: \" + source_file);\n                return false;\n            }\n\n            if (!Functs::DetectExisting(target_folder))\n            {\n                MAssert(\"Target folder does not exist: \" + target_folder);\n                return false;\n            }\n\n            if (WINEN)\n            {\n                std::string str = \"copy \" + source_file + \" \" + target_folder;\n                if (b) std::cerr << \"Command string: \" << str << std::endl;\n                system(str.c_str());\n            }\n            if (MACEN)\n            {\n                //% cp -R ~/Documents/Expenses /Volumes/Data/Expenses\n                std::string str = \"cp -R \" + source_file + \" \" + target_folder;\n                if (b) std::cerr << \"Command string: \" << str << std::endl;\n                system(str.c_str());\n            }\n            return true;\n        }\n\n        static bool WinDel(const std::string& source_file, const bool& b = true)\n        {\n            if (!Functs::DetectExisting(source_file))\n            {\n                //MAssert(\"Source file does not exist: \" + source_file);\n                return false;\n            }\n            std::string str = \"del \" + source_file;\n            if (b) std::cerr << \"Command string: \" << str << std::endl;\n            system(str.c_str());\n            return true;\n        }\n\n        static bool WinRename(const std::string& source_file, const std::string& rename_file, const bool& b = true)\n        {\n            if (!Functs::DetectExisting(source_file))\n            {\n                MAssert(\"Source file does not exist: \" + source_file);\n                return false;\n            }\n\n            std::string str = \"rename \" + source_file + \" \" + rename_file;\n            if (b) std::cerr << \"Command string: \" << str << std::endl;\n            system(str.c_str());\n            return true;\n        }\n\n        template <class Type>\n        static std::string GetTypeId(const Type& t)\n        {\n            return  typeid(t).name();\n        }\n\n#pragma endregion\n\n        static Vector3d ColorMapping(const int& cur, const int& all)\n        {\n            MAssert(cur >= 0 && all >= 0 && cur <= all - 1, \"cur>=0 && all>=0 && cur<all\");\n            double isolevel = (double)cur / (double)all;\n            return ColorMapping(isolevel);\n        }\n\n        static Vector3d ColorMapping(const double& isolevel)\n        {\n            double output_c_0, output_c_1, output_c_2;\n            ColorMapping(isolevel, output_c_0, output_c_1, output_c_2);\n            return Vector3d(output_c_0, output_c_1, output_c_2);\n        }\n\n        static void ColorMapping(const double& isolevel, double& output_c_0, double& output_c_1, double& output_c_2)\n        {\n            MAssert(isolevel >= 0.0 && isolevel <= 1.0, \"isolevel>=0.0&&isolevel<=1.0\");\n\n            Vector3d v;\n            if (isolevel >= 0 && isolevel <= 0.25)\n            {\n                v[0] = 0;\n                v[1] = isolevel / 0.25;\n                v[2] = 1;\n            }\n\n            if (isolevel > 0.25 && isolevel <= 0.50)\n            {\n                v[0] = 0;\n                v[1] = 1;\n                v[2] = 1 - (isolevel - 0.25) / 0.25;\n            }\n\n            if (isolevel > 0.50 && isolevel <= 0.75)\n            {\n                v[0] = (isolevel - 0.50) / 0.25;\n                v[1] = 1;\n                v[2] = 0;\n            }\n\n            if (isolevel > 0.75 && isolevel <= 1.0)\n            {\n                v[0] = 1;\n                v[1] = 1 - (isolevel - 0.75) / 0.25;\n                v[2] = 0;\n            }\n\n            if (isolevel < 0.0)\n            {\n                v[0] = 0.0;\n                v[1] = 0.0;\n                v[2] = 0.0;\n            }\n\n            if (isolevel > 1.0)\n            {\n                v[0] = 0.5;\n                v[1] = 0.0;\n                v[2] = 0.0;\n            }\n            output_c_0 = v[0];\n            output_c_1 = v[1];\n            output_c_2 = v[2];\n        }\n    };\n\n    typedef Functs FF;\n    #define DS FF::DoubleString\n    #define IS FF::IntString\n\t\n    //To debug a release build\n    //Open the Property Pages dialog box for the project.\n    //Click the C / C++ node. Set Debug Information Format to C7 compatible(/ Z7) or Program Database(/ Zi).\n    //Expand Linker and click the General node.Set Enable Incremental Linking to No(/ INCREMENTAL:NO).\n    //Select the Debugging node.Set Generate Debug Info to Yes(/ DEBUG).\n    //Select the Optimization node.Set References to / OPT:REF and Enable COMDAT Folding to / OPT : ICF.\n\n\n}\n#endif\n", "meta": {"hexsha": "2deaadd9cae5abd7fdbee7408d2722d66d7ba993", "size": 150947, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pgl_functs.hpp", "max_stars_repo_name": "haisenzhao/personal-geom-lib", "max_stars_repo_head_hexsha": "d329fb9b6dcfca788e89f6699e721ae10598f0e9", "max_stars_repo_licenses": ["FTL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pgl_functs.hpp", "max_issues_repo_name": "haisenzhao/personal-geom-lib", "max_issues_repo_head_hexsha": "d329fb9b6dcfca788e89f6699e721ae10598f0e9", "max_issues_repo_licenses": ["FTL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pgl_functs.hpp", "max_forks_repo_name": "haisenzhao/personal-geom-lib", "max_forks_repo_head_hexsha": "d329fb9b6dcfca788e89f6699e721ae10598f0e9", "max_forks_repo_licenses": ["FTL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.6343248347, "max_line_length": 206, "alphanum_fraction": 0.4632685645, "num_tokens": 38657, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548782017745, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.45115573042958285}}
{"text": "/*=============================================================================\n    Copyright (c) 2001-2003 Dan Nuffer\n    Copyright (c) 2002-2003 Joel de Guzman\n    http://spirit.sourceforge.net/\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////////////////////////////////////////////////////////////////////////////\n//\n//  Full calculator example using STL functors\n//  This is discussed in the \"Functional\" chapter in the Spirit User's Guide.\n//\n//  Ported to Spirit v1.5 from v1.2/1.3 example by Dan Nuffer\n//  [ JDG 9/18/2002 ]\n//\n////////////////////////////////////////////////////////////////////////////\n#include <boost/spirit/core.hpp>\n#include <iostream>\n#include <stack>\n#include <functional>\n#include <string>\n\n////////////////////////////////////////////////////////////////////////////\nusing namespace std;\nusing namespace boost::spirit;\n\n////////////////////////////////////////////////////////////////////////////\n//\n//  Semantic actions\n//\n////////////////////////////////////////////////////////////////////////////\nstruct push_int\n{\n    push_int(stack<long>& eval_)\n    : eval(eval_) {}\n\n    void operator()(char const* str, char const* /*end*/) const\n    {\n        long n = strtol(str, 0, 10);\n        eval.push(n);\n        cout << \"push\\t\" << long(n) << endl;\n    }\n\n    stack<long>& eval;\n};\n\ntemplate <typename op>\nstruct do_op\n{\n    do_op(op const& the_op, stack<long>& eval_)\n    : m_op(the_op), eval(eval_) {}\n\n    void operator()(char const*, char const*) const\n    {\n        long rhs = eval.top();\n        eval.pop();\n        long lhs = eval.top();\n        eval.pop();\n\n        cout << \"popped \" << lhs << \" and \" << rhs << \" from the stack. \";\n        cout << \"pushing \" << m_op(lhs, rhs) << \" onto the stack.\\n\";\n        eval.push(m_op(lhs, rhs));\n    }\n\n    op m_op;\n    stack<long>& eval;\n};\n\ntemplate <class op>\ndo_op<op>\nmake_op(op const& the_op, stack<long>& eval)\n{\n    return do_op<op>(the_op, eval);\n}\n\nstruct do_negate\n{\n    do_negate(stack<long>& eval_)\n    : eval(eval_) {}\n\n    void operator()(char const*, char const*) const\n    {\n        long lhs = eval.top();\n        eval.pop();\n\n        cout << \"popped \" << lhs << \" from the stack. \";\n        cout << \"pushing \" << -lhs << \" onto the stack.\\n\";\n        eval.push(-lhs);\n    }\n\n    stack<long>& eval;\n};\n\n////////////////////////////////////////////////////////////////////////////\n//\n//  Our calculator grammar\n//\n////////////////////////////////////////////////////////////////////////////\nstruct calculator : public grammar<calculator>\n{\n    calculator(stack<long>& eval_)\n    : eval(eval_) {}\n\n    template <typename ScannerT>\n    struct definition\n    {\n        definition(calculator const& self)\n        {\n            integer =\n                lexeme_d[ (+digit_p)[push_int(self.eval)] ]\n                ;\n\n            factor =\n                    integer\n                |   '(' >> expression >> ')'\n                |   ('-' >> factor)[do_negate(self.eval)]\n                |   ('+' >> factor)\n                ;\n\n            term =\n                factor\n                >> *(   ('*' >> factor)[make_op(multiplies<long>(), self.eval)]\n                    |   ('/' >> factor)[make_op(divides<long>(), self.eval)]\n                    )\n                    ;\n\n            expression =\n                term\n                >> *(  ('+' >> term)[make_op(plus<long>(), self.eval)]\n                    |   ('-' >> term)[make_op(minus<long>(), self.eval)]\n                    )\n                    ;\n        }\n\n        rule<ScannerT> expression, term, factor, integer;\n        rule<ScannerT> const&\n        start() const { return expression; }\n    };\n\n    stack<long>& eval;\n};\n\n////////////////////////////////////////////////////////////////////////////\n//\n//  Main program\n//\n////////////////////////////////////////////////////////////////////////////\nint\nmain()\n{\n    cout << \"/////////////////////////////////////////////////////////\\n\\n\";\n    cout << \"\\t\\tThe simplest working calculator...\\n\\n\";\n    cout << \"/////////////////////////////////////////////////////////\\n\\n\";\n    cout << \"Type an expression...or [q or Q] to quit\\n\\n\";\n\n    stack<long> eval;\n    calculator  calc(eval); //  Our parser\n\n    string str;\n    while (getline(cin, str))\n    {\n        if (str.empty() || str[0] == 'q' || str[0] == 'Q')\n            break;\n\n        parse_info<> info = parse(str.c_str(), calc, space_p);\n\n        if (info.full)\n        {\n            cout << \"-------------------------\\n\";\n            cout << \"Parsing succeeded\\n\";\n            cout << \"-------------------------\\n\";\n        }\n        else\n        {\n            cout << \"-------------------------\\n\";\n            cout << \"Parsing failed\\n\";\n            cout << \"stopped at: \\\": \" << info.stop << \"\\\"\\n\";\n            cout << \"-------------------------\\n\";\n        }\n    }\n\n    cout << \"Bye... :-) \\n\\n\";\n    return 0;\n}\n\n\n", "meta": {"hexsha": "44e56d236713f10c17b70b6f61eca661cd9a531a", "size": 5108, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Source/boost_1_33_1/libs/spirit/example/fundamental/full_calc.cpp", "max_stars_repo_name": "spxuw/RFIM", "max_stars_repo_head_hexsha": "32b78fbb90c7008b1106b0cff4f8023ae83c9b6d", "max_stars_repo_licenses": ["MIT"], "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/boost_1_33_1/libs/spirit/example/fundamental/full_calc.cpp", "max_issues_repo_name": "spxuw/RFIM", "max_issues_repo_head_hexsha": "32b78fbb90c7008b1106b0cff4f8023ae83c9b6d", "max_issues_repo_licenses": ["MIT"], "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/boost_1_33_1/libs/spirit/example/fundamental/full_calc.cpp", "max_forks_repo_name": "spxuw/RFIM", "max_forks_repo_head_hexsha": "32b78fbb90c7008b1106b0cff4f8023ae83c9b6d", "max_forks_repo_licenses": ["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.0264550265, "max_line_length": 79, "alphanum_fraction": 0.3923257635, "num_tokens": 1058, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.6513548714339145, "lm_q1q2_score": 0.4511557298744576}}
{"text": "#define BOOST_TEST_MODULE \"ValueBundleTest\"\n#include <boost/test/included/unit_test.hpp>\n#include \"lib/ValueBundle.hpp\"\n\n\nBOOST_AUTO_TEST_SUITE(ValueBundleTest);\n\nBOOST_AUTO_TEST_CASE(ValueBundleArithmetic)\n{\n\tconst int dataSize = 16;\n\tfloat data1[dataSize];\n\tfloat data2[dataSize];\n\tfloat data3[dataSize];\n\n\tauto reset = [](ValueBundle<float> &b)->void {\n\t\tfor (int i = 0; i < dataSize; ++i) b[i] = float(i);\n\t};\n\n\tValueBundle<float> b1 = ValueBundle<float>(&data1[0], dataSize);\n\tValueBundle<float> b2 = ValueBundle<float>(&data2[0], dataSize);\n\tValueBundle<float> b3 = ValueBundle<float>(&data3[0], dataSize);\n\n\tBOOST_CHECK_EQUAL(b1.size(), dataSize);\n\t\n\treset(b1);\n\tfor (int i = 0; i < dataSize; ++i) BOOST_CHECK_EQUAL(b1[i], float(i));\n\n\treset(b1);\n\treset(b2);\n\tb1.multAdd(2.0f, b2);\n\tfor (int i = 0; i < dataSize; ++i) BOOST_CHECK_EQUAL(b1[i], float(i + 2.0f * i));\n\n\treset(b1);\n\treset(b2);\n\tb1.multAdd(b2, 2.0f);\n\tfor (int i = 0; i < dataSize; ++i) BOOST_CHECK_EQUAL(b1[i], float(i + 2.0f * i));\n\n\treset(b1);\n\treset(b2);\n\treset(b3);\n\tb1.multAdd(b2, b3);\n\tfor (int i = 0; i < dataSize; ++i) BOOST_CHECK_EQUAL(b1[i], float(i + i * i));\n\n\treset(b1);\n\treset(b2);\n\treset(b3);\n\tb1.multAdd(2.0f, b2, b3);\n\tfor (int i = 0; i < dataSize; ++i) BOOST_CHECK_EQUAL(b1[i], float(i + 2.0f * i * i));\n\n\treset(b1);\n\treset(b2);\n\tb1.multSub(2.0f, b2);\n\tfor (int i = 0; i < dataSize; ++i) BOOST_CHECK_EQUAL(b1[i], float(i - 2.0f * i));\n\n\treset(b1);\n\treset(b2);\n\tb1.multSub(b2, 2.0f);\n\tfor (int i = 0; i < dataSize; ++i) BOOST_CHECK_EQUAL(b1[i], float(i - 2.0f * i));\n\n\treset(b1);\n\treset(b2);\n\treset(b3);\n\tb1.multSub(b2, b3);\n\tfor (int i = 0; i < dataSize; ++i) BOOST_CHECK_EQUAL(b1[i], float(i - i * i));\n\n\treset(b1);\n\treset(b2);\n\treset(b3);\n\tb1.multSub(2.0f, b2, b3);\n\tfor (int i = 0; i < dataSize; ++i) BOOST_CHECK_EQUAL(b1[i], float(i - 2.0f * i * i));\n\n\treset(b1);\n\treset(b2);\n\tb1 += b2;\n\tfor (int i = 0; i < dataSize; ++i) BOOST_CHECK_EQUAL(b1[i], float(i + i));\n\n\treset(b1);\n\treset(b2);\n\tb1 -= b2;\n\tfor (int i = 0; i < dataSize; ++i) BOOST_CHECK_EQUAL(b1[i], float(i - i));\n\n\treset(b1);\n\tb1 *= 2.0f;\n\tfor (int i = 0; i < dataSize; ++i) BOOST_CHECK_EQUAL(b1[i], float(i * 2.0f));\n\n\treset(b1);\n\tb1 /= 2.0f;\n\tfor (int i = 0; i < dataSize; ++i) BOOST_CHECK_EQUAL(b1[i], float(i / 2.0f));\n}\n\nBOOST_AUTO_TEST_CASE(ValueSuperbundleArithmetic)\n{\n\tconst int dataSize = 16;\n\n\tauto reset = [](ValueSuperbundle<float,2> &s)->void {\n\t\tfor (int i = 0; i < 2; ++i)\n\t\t{\n\t\t\tauto b = s.bundle(i);\n\t\t\tfor (int j = 0; j < dataSize; ++j) b[j] = float(j);\n\t\t}\n\t};\n\n\tValueSuperbundle<float, 2> s1 = ValueSuperbundle<float, 2>(dataSize);\n\tValueSuperbundle<float, 2> s2 = ValueSuperbundle<float, 2>(dataSize);\n\n\ts1.reset();\n\tfor (int i = 0; i < dataSize; ++i) BOOST_CHECK_EQUAL(s1.bundle(0)[i], 0.0f);\n\tfor (int i = 0; i < dataSize; ++i) BOOST_CHECK_EQUAL(s1.bundle(1)[i], 0.0f);\n\n\tValueSuperbundle<float, 2> s3 = ValueSuperbundle<float, 2>(s1);\n\ts1.bundle(0)[0] = 42.0f;\n\ts3.bundle(0)[1] = 43.0f;\n\tBOOST_CHECK_EQUAL(s3.bundle(0)[0], 42.0f);\n\tBOOST_CHECK_EQUAL(s1.bundle(0)[1], 43.0f);\n\n\treset(s1);\n\treset(s2);\n\ts1.multAdd(2.0f, s2);\n\tfor (int i = 0; i < dataSize; ++i) BOOST_CHECK_EQUAL(s1.bundle(0)[i], float(i + 2.0f * i));\n\tfor (int i = 0; i < dataSize; ++i) BOOST_CHECK_EQUAL(s1.bundle(1)[i], float(i + 2.0f * i));\n\n\treset(s1);\n\ts1 *= 2.0f;\n\tfor (int i = 0; i < dataSize; ++i) BOOST_CHECK_EQUAL(s1.bundle(0)[i], float(2.0f * i));\n\tfor (int i = 0; i < dataSize; ++i) BOOST_CHECK_EQUAL(s1.bundle(1)[i], float(2.0f * i));\n\n\treset(s1);\n\ts1 /= 2.0f;\n\tfor (int i = 0; i < dataSize; ++i) BOOST_CHECK_EQUAL(s1.bundle(0)[i], float(i) / 2.0f);\n\tfor (int i = 0; i < dataSize; ++i) BOOST_CHECK_EQUAL(s1.bundle(1)[i], float(i) / 2.0f);\n\n\treset(s1);\n\treset(s2);\n\ts1 += s2;\n\tfor (int i = 0; i < dataSize; ++i) BOOST_CHECK_EQUAL(s1.bundle(0)[i], float(2.0f * i));\n\tfor (int i = 0; i < dataSize; ++i) BOOST_CHECK_EQUAL(s1.bundle(1)[i], float(2.0f * i));\n}\nBOOST_AUTO_TEST_SUITE_END();", "meta": {"hexsha": "b4653612a0a56993aebefa2fd30bf8272f7a5b24", "size": 3940, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_ValueBundle.cpp", "max_stars_repo_name": "Sourin-chatterjee/SpinParser", "max_stars_repo_head_hexsha": "23fa90c327b8a4543e5afac1b64d18df40975182", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2021-06-03T16:03:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T00:48:53.000Z", "max_issues_repo_path": "test/test_ValueBundle.cpp", "max_issues_repo_name": "Sourin-chatterjee/SpinParser", "max_issues_repo_head_hexsha": "23fa90c327b8a4543e5afac1b64d18df40975182", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-10-08T15:51:51.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T22:20:01.000Z", "max_forks_repo_path": "test/test_ValueBundle.cpp", "max_forks_repo_name": "Sourin-chatterjee/SpinParser", "max_forks_repo_head_hexsha": "23fa90c327b8a4543e5afac1b64d18df40975182", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2022-02-10T17:15:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-11T19:54:27.000Z", "avg_line_length": 28.5507246377, "max_line_length": 92, "alphanum_fraction": 0.6185279188, "num_tokens": 1458, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419704455589, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.45115572629700407}}
{"text": "// This file is part of Eigen, a lightweight C++ template library\n// for linear algebra.\n//\n// Copyright (C) 2013 Gauthier Brun <brun.gauthier@gmail.com>\n// Copyright (C) 2013 Nicolas Carre <nicolas.carre@ensimag.fr>\n// Copyright (C) 2013 Jean Ceccato <jean.ceccato@ensimag.fr>\n// Copyright (C) 2013 Pierre Zoppitelli <pierre.zoppitelli@ensimag.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 \"svd_common.h\"\n#include <iostream>\n#include <Eigen/LU>\n\n// check if \"svd\" is the good image of \"m\"  \ntemplate<typename MatrixType>\nvoid bdcsvd_check_full(const MatrixType& m, const BDCSVD<MatrixType>& svd)\n{\n  svd_check_full< MatrixType, BDCSVD< MatrixType > >(m, svd);\n}\n\n// Compare to a reference value\ntemplate<typename MatrixType>\nvoid bdcsvd_compare_to_full(const MatrixType& m,\n\t\t\t    unsigned int computationOptions,\n\t\t\t    const BDCSVD<MatrixType>& referenceSvd)\n{\n  svd_compare_to_full< MatrixType, BDCSVD< MatrixType > >(m, computationOptions, referenceSvd);\n} // end bdcsvd_compare_to_full\n\n\ntemplate<typename MatrixType>\nvoid bdcsvd_solve(const MatrixType& m, unsigned int computationOptions)\n{\n  svd_solve< MatrixType, BDCSVD< MatrixType > >(m, computationOptions);\n} //  end template bdcsvd_solve\n\n\n// test the computations options\ntemplate<typename MatrixType>\nvoid bdcsvd_test_all_computation_options(const MatrixType& m)\n{\n  BDCSVD<MatrixType> fullSvd(m, ComputeFullU|ComputeFullV);\n  svd_test_computation_options_1< MatrixType, BDCSVD< MatrixType > >(m, fullSvd); \n  svd_test_computation_options_2< MatrixType, BDCSVD< MatrixType > >(m, fullSvd); \n} // end bdcsvd_test_all_computation_options\n\n\n// Call a test with all the computations options\ntemplate<typename MatrixType>\nvoid bdcsvd(const MatrixType& a = MatrixType(), bool pickrandom = true)\n{\n  MatrixType m = pickrandom ? MatrixType::Random(a.rows(), a.cols()) : a;\n  bdcsvd_test_all_computation_options<MatrixType>(m);\n} // end template bdcsvd\n\n\n// verify assert\ntemplate<typename MatrixType> \nvoid bdcsvd_verify_assert(const MatrixType& m)\n{\n  svd_verify_assert< MatrixType, BDCSVD< MatrixType > >(m);\n}// end template bdcsvd_verify_assert\n\n\n// test weird values\ntemplate<typename MatrixType>\nvoid bdcsvd_inf_nan()\n{\n  svd_inf_nan< MatrixType, BDCSVD< MatrixType > >();\n}// end template bdcsvd_inf_nan\n\n\n\nvoid bdcsvd_preallocate()\n{\n  svd_preallocate< BDCSVD< MatrixXf > >();\n} // end bdcsvd_preallocate\n\n\n// compare the Singular values returned with Jacobi and Bdc\ntemplate<typename MatrixType> \nvoid compare_bdc_jacobi(const MatrixType& a = MatrixType(), unsigned int computationOptions = 0)\n{\n  std::cout << \"debut compare\" << std::endl;\n  MatrixType m = MatrixType::Random(a.rows(), a.cols());\n  BDCSVD<MatrixType> bdc_svd(m);\n  JacobiSVD<MatrixType> jacobi_svd(m);\n  VERIFY_IS_APPROX(bdc_svd.singularValues(), jacobi_svd.singularValues());\n  if(computationOptions & ComputeFullU)\n    VERIFY_IS_APPROX(bdc_svd.matrixU(), jacobi_svd.matrixU());\n  if(computationOptions & ComputeThinU)\n    VERIFY_IS_APPROX(bdc_svd.matrixU(), jacobi_svd.matrixU());\n  if(computationOptions & ComputeFullV)\n    VERIFY_IS_APPROX(bdc_svd.matrixV(), jacobi_svd.matrixV());\n  if(computationOptions & ComputeThinV)\n    VERIFY_IS_APPROX(bdc_svd.matrixV(), jacobi_svd.matrixV());\n  std::cout << \"fin compare\" << std::endl;\n} // end template compare_bdc_jacobi\n\n\n// call the tests\nvoid test_bdcsvd()\n{\n  // test of Dynamic defined Matrix (42, 42) of float \n  CALL_SUBTEST_11(( bdcsvd_verify_assert<Matrix<float,Dynamic,Dynamic> >\n\t\t    (Matrix<float,Dynamic,Dynamic>(42,42)) ));\n  CALL_SUBTEST_11(( compare_bdc_jacobi<Matrix<float,Dynamic,Dynamic> >\n\t\t    (Matrix<float,Dynamic,Dynamic>(42,42), 0) ));\n  CALL_SUBTEST_11(( bdcsvd<Matrix<float,Dynamic,Dynamic> >\n\t\t    (Matrix<float,Dynamic,Dynamic>(42,42)) ));\n\n  // test of Dynamic defined Matrix (50, 50) of double \n  CALL_SUBTEST_13(( bdcsvd_verify_assert<Matrix<double,Dynamic,Dynamic> >\n\t\t    (Matrix<double,Dynamic,Dynamic>(50,50)) ));\n  CALL_SUBTEST_13(( compare_bdc_jacobi<Matrix<double,Dynamic,Dynamic> >\n\t\t    (Matrix<double,Dynamic,Dynamic>(50,50), 0) ));\n  CALL_SUBTEST_13(( bdcsvd<Matrix<double,Dynamic,Dynamic> >\n\t\t    (Matrix<double,Dynamic,Dynamic>(50, 50)) )); \n\n  // test of Dynamic defined Matrix (22, 22) of complex double\n  CALL_SUBTEST_14(( bdcsvd_verify_assert<Matrix<std::complex<double>,Dynamic,Dynamic> >\n  \t\t    (Matrix<std::complex<double>,Dynamic,Dynamic>(22,22)) ));\n  CALL_SUBTEST_14(( compare_bdc_jacobi<Matrix<std::complex<double>,Dynamic,Dynamic> >\n  \t\t    (Matrix<std::complex<double>, Dynamic, Dynamic> (22,22), 0) ));\n  CALL_SUBTEST_14(( bdcsvd<Matrix<std::complex<double>,Dynamic,Dynamic> >\n  \t\t    (Matrix<std::complex<double>,Dynamic,Dynamic>(22, 22)) )); \n\n  // test of Dynamic defined Matrix (10, 10) of int\n  //CALL_SUBTEST_15(( bdcsvd_verify_assert<Matrix<int,Dynamic,Dynamic> >\n  //\t\t    (Matrix<int,Dynamic,Dynamic>(10,10)) ));\t\t    \n  //CALL_SUBTEST_15(( compare_bdc_jacobi<Matrix<int,Dynamic,Dynamic> >\n  //\t\t    (Matrix<int,Dynamic,Dynamic>(10,10), 0) ));\n  //CALL_SUBTEST_15(( bdcsvd<Matrix<int,Dynamic,Dynamic> >\n  //\t\t    (Matrix<int,Dynamic,Dynamic>(10, 10)) )); \n  \n\n  // test of Dynamic defined Matrix (8, 6) of double \n \n  CALL_SUBTEST_16(( bdcsvd_verify_assert<Matrix<double,Dynamic,Dynamic> >\n\t\t    (Matrix<double,Dynamic,Dynamic>(8,6)) ));\n  CALL_SUBTEST_16(( compare_bdc_jacobi<Matrix<double,Dynamic,Dynamic> >\n\t\t    (Matrix<double,Dynamic,Dynamic>(8, 6), 0) )); \n  CALL_SUBTEST_16(( bdcsvd<Matrix<double,Dynamic,Dynamic> >\n\t\t    (Matrix<double,Dynamic,Dynamic>(8, 6)) ));\n\n\n  \n  // test of Dynamic defined Matrix (36, 12) of float\n  CALL_SUBTEST_17(( compare_bdc_jacobi<Matrix<float,Dynamic,Dynamic> >\n\t\t    (Matrix<float,Dynamic,Dynamic>(36, 12), 0) )); \n  CALL_SUBTEST_17(( bdcsvd<Matrix<float,Dynamic,Dynamic> >\n\t\t    (Matrix<float,Dynamic,Dynamic>(36, 12)) )); \n\n  // test of Dynamic defined Matrix (5, 8) of double \n  CALL_SUBTEST_18(( compare_bdc_jacobi<Matrix<double,Dynamic,Dynamic> >\n\t\t    (Matrix<double,Dynamic,Dynamic>(5, 8), 0) )); \n  CALL_SUBTEST_18(( bdcsvd<Matrix<double,Dynamic,Dynamic> >\n\t\t    (Matrix<double,Dynamic,Dynamic>(5, 8)) )); \n\n\n  // non regression tests\n  CALL_SUBTEST_3(( bdcsvd_verify_assert(Matrix3f()) ));\n  CALL_SUBTEST_4(( bdcsvd_verify_assert(Matrix4d()) ));\n  CALL_SUBTEST_7(( bdcsvd_verify_assert(MatrixXf(10,12)) ));\n  CALL_SUBTEST_8(( bdcsvd_verify_assert(MatrixXcd(7,5)) ));\n\n  // SUBTESTS 1 and 2 on specifics matrix\n  for(int i = 0; i < g_repeat; i++) {\n    Matrix2cd m;\n    m << 0, 1,\n      0, 1;\n    CALL_SUBTEST_1(( bdcsvd(m, false) ));\n    m << 1, 0,\n      1, 0;\n    CALL_SUBTEST_1(( bdcsvd(m, false) ));\n\n    Matrix2d n;\n    n << 0, 0,\n      0, 0;\n    CALL_SUBTEST_2(( bdcsvd(n, false) ));\n    n << 0, 0,\n      0, 1;\n    CALL_SUBTEST_2(( bdcsvd(n, false) ));\n    \n    // Statics matrix don't work with BDSVD yet\n    // bdc algo on a random 3x3 float matrix\n    // CALL_SUBTEST_3(( bdcsvd<Matrix3f>() ));\n    // bdc algo on a random 4x4 double matrix\n    // CALL_SUBTEST_4(( bdcsvd<Matrix4d>() ));\n    // bdc algo on a random 3x5 float matrix\n    // CALL_SUBTEST_5(( bdcsvd<Matrix<float,3,5> >() ));\n\n    int r = internal::random<int>(1, 30),\n      c = internal::random<int>(1, 30);\n    CALL_SUBTEST_7(( bdcsvd<MatrixXf>(MatrixXf(r,c)) ));\n    CALL_SUBTEST_8(( bdcsvd<MatrixXcd>(MatrixXcd(r,c)) ));\n    (void) r;\n    (void) c;\n\n    // Test on inf/nan matrix\n    CALL_SUBTEST_7( bdcsvd_inf_nan<MatrixXf>() );\n  }\n\n  CALL_SUBTEST_7(( bdcsvd<MatrixXf>(MatrixXf(internal::random<int>(EIGEN_TEST_MAX_SIZE/4, EIGEN_TEST_MAX_SIZE/2), internal::random<int>(EIGEN_TEST_MAX_SIZE/4, EIGEN_TEST_MAX_SIZE/2))) ));\n  CALL_SUBTEST_8(( bdcsvd<MatrixXcd>(MatrixXcd(internal::random<int>(EIGEN_TEST_MAX_SIZE/4, EIGEN_TEST_MAX_SIZE/3), internal::random<int>(EIGEN_TEST_MAX_SIZE/4, EIGEN_TEST_MAX_SIZE/3))) ));\n\n  // Test problem size constructors\n  CALL_SUBTEST_7( BDCSVD<MatrixXf>(10,10) );\n\n} // end test_bdcsvd\n", "meta": {"hexsha": "115a649b0e9a9b286ebb39337220c30202987ca3", "size": 8067, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/PEST++/src/libs/Eigen/unsupported/test/bdcsvd.cpp", "max_stars_repo_name": "usgs/neversink_workflow", "max_stars_repo_head_hexsha": "acd61435b8553e38d4a903c8cd7a3afc612446f9", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 2392.0, "max_stars_repo_stars_event_min_datetime": "2016-12-17T14:14:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T19:40:40.000Z", "max_issues_repo_path": "SCA/eigen_332/unsupported/test/bdcsvd.cpp", "max_issues_repo_name": "JooseRajamaeki/TVCG18", "max_issues_repo_head_hexsha": "ddc73f422c267b1c38ede3ba20046efff46a6d74", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 113.0, "max_issues_repo_issues_event_min_datetime": "2015-07-28T20:31:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-01T15:29:20.000Z", "max_forks_repo_path": "SCA/eigen_332/unsupported/test/bdcsvd.cpp", "max_forks_repo_name": "JooseRajamaeki/TVCG18", "max_forks_repo_head_hexsha": "ddc73f422c267b1c38ede3ba20046efff46a6d74", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 412.0, "max_forks_repo_forks_event_min_datetime": "2015-01-14T07:31:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T08:41:41.000Z", "avg_line_length": 37.6962616822, "max_line_length": 189, "alphanum_fraction": 0.7088136854, "num_tokens": 2530, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419704455589, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.4511557169215961}}
{"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_FPCLASSIFY_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_FPCLASSIFY_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n    @ingroup group-ieee\n    Function object implementing fpclassify capabilities\n\n    Categorizes floating point value arg into the following categories:\n    zero, subnormal, normal, infinite, NAN, or implementation-defined category.\n\n    @code\n    auto r = fpclassify(x);\n    @endcode\n\n    This function is similar to std::fpclassify,  but the return type\n    is the integral signed type associated to the floating input type.\n\n    If you want the standard behaviour which return an int in scalar mode you\n    can use the std_ decorator.\n\n    fpclassify returns a value of integral type that matches one of the classification\n    macro constants, depending on the value of x:\n\n    value description:\n\n    - FP_INFINITE Positive or negative infinity\n    - FP_NAN  Not-A-Number\n    - FP_ZERO Value of zero\n    - FP_SUBNORMAL  Sub-normal value\n    - FP_NORMAL Normal value (none of the above)\n\n    Note that each value pertains to a single category: for fpclassify zero is not a\n    normal value.\n\n    These macro constants of type int are defined in header cmath\n\n    @par Decorators\n\n    std_ for floating entries\n\n    @see is_eqz, is_denormal, is_normal, is_inf, is_nan\n\n  **/\n  as_integer_t<Value> fpclassify(Value const & v0);\n} }\n#endif\n\n#include <boost/simd/function/scalar/fpclassify.hpp>\n#include <boost/simd/function/simd/fpclassify.hpp>\n\n#endif\n", "meta": {"hexsha": "cdb1bd04df387f1f64c473d2ce5588c3c2166bd3", "size": 1918, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/fpclassify.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/fpclassify.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/fpclassify.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": 29.0606060606, "max_line_length": 100, "alphanum_fraction": 0.6631908238, "num_tokens": 411, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347362, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.4511557158113453}}
{"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\n\n    vigra::NumpyAnyArray  regionAffinity(\n        vigra::NumpyArray<2, vigra::Multiband<vigra::UInt64>  >   labelings,\n        vigra::NumpyArray<1, vigra::UInt64>                       nLabels,                      \n        //output\n        vigra::NumpyArray<2, float >    res = vigra::NumpyArray<4, float >()\n    ){ \n        const size_t nSeg = labelings.shape(1);\n        const size_t nReg = labelings.shape(1);\n        // allocate output\n        typedef typename vigra::NumpyArray<2, float >::difference_type Shape2;\n        Shape2 shape(nReg,nReg);\n        res.reshapeIfEmpty(shape);\n        std::fill(res.begin(),res.end(),0.0);\n\n\n        for(size_t s=0;s<nSeg;++s){\n\n            const size_t nL=nLabels(s);\n\n            std::vector< std::vector< vigra::UInt64> > regWithLabel;\n            for(size_t r=0;r<nReg;++r){\n\n                const vigra::UInt64 label=labelings(r,s);\n                regWithLabel[label].push_back(r);\n            }\n\n            for(size_t l=0;l<nL;++l){\n\n                for(size_t r0=0;    r0<regWithLabel[l].size()-1 ;++r0)\n                for(size_t r1=r0+1; r1<regWithLabel[l].size()   ;++r1){\n                    res[r0,r1]+=1.0;\n                    res[r1,r0]+=1.0;\n                }\n            }\n        }\n        return res;\n    }\n\n\n\n    void export_segcompare(){\n\n        python::def(\"_regionAffinity\",vigra::registerConverters(&regionAffinity),\n            (\n                python::arg(\"labelings\"),\n                python::arg(\"nLabels\"),\n                python::arg(\"out\")=python::object()\n            )\n        );\n\n    }\n\n}", "meta": {"hexsha": "81b43f0dae46ed06a7010186a9cd0a91f0b80fd0", "size": 2321, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/python/cgp2d/misc/py_segcompare.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/misc/py_segcompare.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/misc/py_segcompare.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": 27.3058823529, "max_line_length": 96, "alphanum_fraction": 0.5932787592, "num_tokens": 604, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321964553657, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.45113518335664043}}
{"text": "/* Copyright (C) 2012-2019 IBM Corp.\n * This program is Licensed under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *   http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License. See accompanying LICENSE file.\n */\n\n/* Test_bootstrapping.cpp - Testing the recryption procedure */\n\n#if defined(__unix__) || defined(__unix) || defined(unix)\n#include <sys/time.h>\n#include <sys/resource.h>\n#endif\n\n#include <NTL/ZZ.h>\n#include <NTL/fileio.h>\n#include <NTL/BasicThreadPool.h>\nNTL_CLIENT\n#include <cassert>\n#include <helib/EncryptedArray.h>\n#include <helib/EvalMap.h>\n#include <helib/powerful.h>\n#include <helib/matmul.h>\n#include <helib/debugging.h>\n#include <helib/fhe_stats.h>\n#include <helib/ArgMap.h>\n\nusing namespace helib;\n\nstatic bool noPrint = false;\nstatic bool dry = false; // a dry-run flag\nstatic bool debug = 0;   // a debug flag\nstatic int scale = 0;\n\nextern long printFlag;\n\n\n#define OUTER_REP (1)\n#define INNER_REP (1)\n\n\nstatic Vec<long> global_mvec, global_gens, global_ords;\nstatic int c_m = 100;\n\n\nvoid TestIt(long p, long r, long L, long c, long skHwt, int build_cache=0)\n{\n  Vec<long> mvec;\n  vector<long> gens;\n  vector<long> ords;\n\n  long m, phim;\n\n    mvec = global_mvec;\n    convert(gens, global_gens);\n    convert(ords, global_ords);\n\n    m = computeProd(mvec);\n    phim = phi_N(m);\n    helib::assertTrue(GCD(p, m) == 1, \"GCD(p, m) == 1\");\n\n  if (!noPrint) fhe_stats = true;\n\n  if (!noPrint) {\n    cout << \"*** TestIt\";\n    if (isDryRun()) cout << \" (dry run)\";\n    cout << \": p=\" << p\n\t << \", r=\" << r\n\t << \", L=\" << L\n\t << \", t=\" << skHwt\n\t << \", c=\" << c\n\t << \", m=\" << m\n\t << \" (=\" << mvec << \"), gens=\"<<gens<<\", ords=\"<<ords\n\t << endl;\n    cout << \"Computing key-independent tables...\" << std::flush;\n  }\n  setTimersOn();\n  setDryRun(false); // Need to get a \"real context\" to test bootstrapping\n\n  double t = -GetTime();\n  Context context(m, p, r, gens, ords);\n  if (scale) {\n    context.scale = scale;\n  }\n\n\n  context.zMStar.set_cM(c_m/100.0);\n  buildModChain(context, L, c, /*willBeBootstrappable=*/true, /*t=*/skHwt);\n\n  if (!noPrint) {\n    std::cout << \"security=\" << context.securityLevel()<<endl;\n    std::cout << \"# small primes = \" << context.smallPrimes.card() << \"\\n\";\n    std::cout << \"# ctxt primes = \" << context.ctxtPrimes.card() << \"\\n\";\n    std::cout << \"# bits in ctxt primes = \"\n         << long(context.logOfProduct(context.ctxtPrimes)/log(2.0) + 0.5) << \"\\n\";\n    std::cout << \"# special primes = \" << context.specialPrimes.card() << \"\\n\";\n    std::cout << \"# bits in special primes = \"\n         << long(context.logOfProduct(context.specialPrimes)/log(2.0) + 0.5) << \"\\n\";\n    std::cout << \"scale=\" << context.scale<<endl;\n  }\n\n\n\n  context.makeBootstrappable(mvec, /*t=*/skHwt, build_cache);\n  t += GetTime();\n\n  if (!noPrint) {\n    cout << \" done in \"<<t<<\" seconds\\n\";\n    cout << \"  e=\"    << context.rcData.e\n\t << \", e'=\"   << context.rcData.ePrime\n\t << \", t=\"    << context.rcData.skHwt\n\t << \"\\n  \";\n    context.zMStar.printout();\n  }\n  setDryRun(dry); // Now we can set the dry-run flag if desired\n\n  long p2r = context.alMod.getPPowR();\n\n  for (long numkey=0; numkey<OUTER_REP; numkey++) { // test with 3 keys\n\n  t = -GetTime();\n  if (!noPrint) cout << \"Generating keys, \" << std::flush;\n  SecKey secretKey(context);\n  PubKey& publicKey = secretKey;\n  secretKey.GenSecKey(skHwt);      // A +-1/0 secret key\n  addSome1DMatrices(secretKey); // compute key-switching matrices that we need\n  addFrbMatrices(secretKey);\n  if (!noPrint) cout << \"computing key-dependent tables...\" << std::flush;\n  secretKey.genRecryptData();\n  t += GetTime();\n  if (!noPrint) cout << \" done in \"<<t<<\" seconds\\n\";\n\n  zz_p::init(p2r);\n  zz_pX poly_p = random_zz_pX(context.zMStar.getPhiM());\n  zzX poly_p1 = balanced_zzX(poly_p);\n  ZZX ptxt_poly = convert<ZZX>(poly_p1);\n  ZZX ptxt_poly1;\n  PolyRed(ptxt_poly1, ptxt_poly, p2r, true);  \n  // this is the format produced by decryption\n\n#ifdef DEBUG_PRINTOUT\n      dbgEa = (EncryptedArray*) context.ea;\n      dbgKey = &secretKey;\n#endif\n\n  if (debug) {\n    dbgKey = &secretKey; // debugging key \n  }\n\n  ZZX poly2;\n  Ctxt c1(publicKey);\n\n  secretKey.Encrypt(c1,ptxt_poly,p2r);\n\n\n  resetAllTimers();\n  for (long num=0; num<INNER_REP; num++) { // multiple tests with same key\n    publicKey.reCrypt(c1);\n    secretKey.Decrypt(poly2,c1);\n\n    if (ptxt_poly1 == poly2) \n      cout << \"GOOD\\n\";\n    else\n      cout << \"BAD\\n\";\n  }\n  }\n  if (!noPrint) printAllTimers();\n#if (defined(__unix__) || defined(__unix) || defined(unix))\n    struct rusage rusage;\n    getrusage( RUSAGE_SELF, &rusage );\n    if (!noPrint) cout << \"  rusage.ru_maxrss=\"<<rusage.ru_maxrss << endl;\n#endif\n  if (fhe_stats) print_stats(cout);\n}\n\n/********************************************************************\n ********************************************************************/\n\n//extern long fhe_disable_intFactor;\n// extern long fhe_force_chen_han;\n\nint main(int argc, char *argv[]) \n{\n  ArgMap amap;\n\n  long p=2;\n  long r=1;\n  long c=3;\n  long L=600;\n  long N=0;\n  long t=64;\n  long nthreads=1;\n\n  long seed=0;\n  long useCache=1;\n\n  amap.arg(\"p\", p, \"plaintext base\");\n\n  amap.arg(\"r\", r,  \"exponent\");\n  amap.note(\"p^r is the plaintext-space modulus\");\n\n  amap.arg(\"c\", c, \"number of columns in the key-switching matrices\");\n  amap.arg(\"L\", L, \"# of bits in the modulus chain\");\n  amap.arg(\"N\", N, \"lower-bound on phi(m)\");\n  amap.arg(\"t\", t, \"Hamming weight of recryption secret key\", \"heuristic\");\n  amap.arg(\"dry\", dry, \"dry=1 for a dry-run\");\n  amap.arg(\"nthreads\", nthreads, \"number of threads\");\n  amap.arg(\"seed\", seed, \"random number seed\");\n  amap.arg(\"noPrint\", noPrint, \"suppress printouts\");\n  amap.arg(\"useCache\", useCache, \"0: zzX cache, 1: DCRT cache\");\n\n\n  amap.arg(\"force_bsgs\", fhe_test_force_bsgs);\n  amap.arg(\"force_hoist\", fhe_test_force_hoist);\n\n\n  //  amap.arg(\"disable_intFactor\", fhe_disable_intFactor);\n  amap.arg(\"chen_han\", fhe_force_chen_han);\n\n  amap.arg(\"debug\", debug, \"generate debugging output\");\n  amap.arg(\"scale\", scale, \"scale parameter\");\n\n\n  amap.arg(\"gens\", global_gens);\n  amap.arg(\"ords\", global_ords);\n  amap.arg(\"mvec\", global_mvec);\n  amap.arg(\"c_m\", c_m);\n\n  amap.parse(argc, argv);\n\n  if (global_gens.length() == 0 || global_ords.length() == 0 || global_mvec.length() == 0)\n    Error(\"gens, ords, and mvec must be initialized\");\n\n  if (seed) \n    SetSeed(ZZ(seed));\n\n  SetNumThreads(nthreads);\n\n\n  TestIt(p,r,L,c,t,useCache);\n\n  return 0;\n}\n", "meta": {"hexsha": "ebec17421d77092e49ec65c8c9a7cf1532a678b1", "size": 6864, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Test_fatboot.cpp", "max_stars_repo_name": "lparth/homeenc-HElib", "max_stars_repo_head_hexsha": "072ffc8af2662876c445ad5ae8614ca65f20c10b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-02-06T09:26:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-06T09:26:23.000Z", "max_issues_repo_path": "src/Test_fatboot.cpp", "max_issues_repo_name": "lparth/homeenc-HElib", "max_issues_repo_head_hexsha": "072ffc8af2662876c445ad5ae8614ca65f20c10b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Test_fatboot.cpp", "max_forks_repo_name": "lparth/homeenc-HElib", "max_forks_repo_head_hexsha": "072ffc8af2662876c445ad5ae8614ca65f20c10b", "max_forks_repo_licenses": ["Apache-2.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.5662650602, "max_line_length": 90, "alphanum_fraction": 0.627039627, "num_tokens": 2087, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.45113518335664043}}
{"text": "//| Copyright Inria May 2015\n//| This project has received funding from the European Research Council (ERC) under\n//| the European Union's Horizon 2020 research and innovation programme (grant\n//| agreement No 637972) - see http://www.resibots.eu\n//|\n//| Contributor(s):\n//|   - Jean-Baptiste Mouret (jean-baptiste.mouret@inria.fr)\n//|   - Antoine Cully (antoinecully@gmail.com)\n//|   - Konstantinos Chatzilygeroudis (konstantinos.chatzilygeroudis@inria.fr)\n//|   - Federico Allocati (fede.allocati@gmail.com)\n//|   - Vaios Papaspyros (b.papaspyros@gmail.com)\n//|   - Roberto Rama (bertoski@gmail.com)\n//|\n//| This software is a computer library whose purpose is to optimize continuous,\n//| black-box functions. It mainly implements Gaussian processes and Bayesian\n//| optimization.\n//| Main repository: http://github.com/resibots/limbo\n//| Documentation: http://www.resibots.eu/limbo\n//|\n//| This software is governed by the CeCILL-C license under French law and\n//| abiding by the rules of distribution of free software.  You can  use,\n//| modify and/ or redistribute the software under the terms of the CeCILL-C\n//| license as circulated by CEA, CNRS and INRIA at the following URL\n//| \"http://www.cecill.info\".\n//|\n//| As a counterpart to the access to the source code and  rights to copy,\n//| modify and redistribute granted by the license, users are provided only\n//| with a limited warranty  and the software's author,  the holder of the\n//| economic rights,  and the successive licensors  have only  limited\n//| liability.\n//|\n//| In this respect, the user's attention is drawn to the risks associated\n//| with loading,  using,  modifying and/or developing or reproducing the\n//| software by the user in light of its specific status of free software,\n//| that may mean  that it is complicated to manipulate,  and  that  also\n//| therefore means  that it is reserved for developers  and  experienced\n//| professionals having in-depth computer knowledge. Users are therefore\n//| encouraged to load and test the software's suitability as regards their\n//| requirements in conditions enabling the security of their systems and/or\n//| data to be ensured and,  more generally, to use and operate it in the\n//| same conditions as regards security.\n//|\n//| The fact that you are presently reading this means that you have had\n//| knowledge of the CeCILL-C license and that you accept its terms.\n//|\n#ifndef LIMBO_OPT_ADAM_HPP\n#define LIMBO_OPT_ADAM_HPP\n\n#include <algorithm>\n\n#include <Eigen/Core>\n\n#include <limbo/opt/optimizer.hpp>\n#include <limbo/tools/macros.hpp>\n#include <limbo/tools/math.hpp>\n\nnamespace limbo {\n    namespace defaults {\n        struct opt_adam {\n            /// @ingroup opt_defaults\n            /// number of max iterations\n            BO_PARAM(int, iterations, 300);\n\n            /// @ingroup opt_defaults\n            /// alpha - learning rate\n            BO_PARAM(double, alpha, 0.001);\n\n            /// @ingroup opt_defaults\n            /// \u03b21\n            BO_PARAM(double, b1, 0.9);\n\n            /// @ingroup opt_defaults\n            /// \u03b22\n            BO_PARAM(double, b2, 0.999);\n\n            /// @ingroup opt_defaults\n            /// norm epsilon for stopping\n            BO_PARAM(double, eps_stop, 0.0);\n        };\n    } // namespace defaults\n    namespace opt {\n        /// @ingroup opt\n        /// Adam optimizer\n        /// Equations from: http://ruder.io/optimizing-gradient-descent/index.html#gradientdescentoptimizationalgorithms\n        /// (I changed a bit the notation; \u03b7 to \u03b1)\n        ///\n        /// Parameters:\n        /// - int iterations\n        /// - double alpha\n        /// - double b1\n        /// - double b2\n        /// - double eps_stop\n        template <typename Params>\n        struct Adam {\n            template <typename F>\n            Eigen::VectorXd operator()(const F& f, const Eigen::VectorXd& init, bool bounded) const\n            {\n                assert(Params::opt_adam::b1() >= 0. && Params::opt_adam::b1() < 1.);\n                assert(Params::opt_adam::b2() >= 0. && Params::opt_adam::b2() < 1.);\n                assert(Params::opt_adam::alpha() >= 0.);\n\n                size_t param_dim = init.size();\n                double b1 = Params::opt_adam::b1();\n                double b2 = Params::opt_adam::b2();\n                double b1_t = b1;\n                double b2_t = b2;\n                double alpha = Params::opt_adam::alpha();\n                double stop = Params::opt_adam::eps_stop();\n                double epsilon = 1e-8;\n\n                Eigen::VectorXd m = Eigen::VectorXd::Zero(param_dim);\n                Eigen::VectorXd v = Eigen::VectorXd::Zero(param_dim);\n\n                Eigen::VectorXd params = init;\n\n                if (bounded) {\n                    for (int j = 0; j < params.size(); j++) {\n                        if (params(j) < 0)\n                            params(j) = 0;\n                        if (params(j) > 1)\n                            params(j) = 1;\n                    }\n                }\n\n                for (int i = 0; i < Params::opt_adam::iterations(); ++i) {\n                    Eigen::VectorXd prev_params = params;\n                    auto perf = opt::eval_grad(f, params);\n\n                    Eigen::VectorXd grad = opt::grad(perf);\n                    m = b1 * m.array() + (1. - b1) * grad.array();\n                    v = b2 * v.array() + (1. - b2) * grad.array().square();\n\n                    Eigen::VectorXd m_hat = m.array() / (1. - b1_t);\n                    Eigen::VectorXd v_hat = v.array() / (1. - b2_t);\n\n                    params.array() += alpha * m_hat.array() / (v_hat.array().sqrt() + epsilon);\n\n                    b1_t *= b1;\n                    b2_t *= b2;\n\n                    if (bounded) {\n                        for (int j = 0; j < params.size(); j++) {\n                            if (params(j) < 0)\n                                params(j) = 0;\n                            if (params(j) > 1)\n                                params(j) = 1;\n                        }\n                    }\n\n                    if ((prev_params - params).norm() < stop)\n                        break;\n                }\n\n                return params;\n            }\n        };\n    } // namespace opt\n} // namespace limbo\n\n#endif\n", "meta": {"hexsha": "360b1c6164814547dc24f2ec4adb9dab524db3cc", "size": 6251, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "limbo/src/limbo/opt/adam.hpp", "max_stars_repo_name": "yjjuan/automl_cplusplus", "max_stars_repo_head_hexsha": "7c427584ed94915b549d31a2097f952c3cfdef36", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-12-08T09:45:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-27T17:52:18.000Z", "max_issues_repo_path": "limbo/src/limbo/opt/adam.hpp", "max_issues_repo_name": "yjjuan/automl_cplusplus", "max_issues_repo_head_hexsha": "7c427584ed94915b549d31a2097f952c3cfdef36", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "limbo/src/limbo/opt/adam.hpp", "max_forks_repo_name": "yjjuan/automl_cplusplus", "max_forks_repo_head_hexsha": "7c427584ed94915b549d31a2097f952c3cfdef36", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.8260869565, "max_line_length": 120, "alphanum_fraction": 0.5552711566, "num_tokens": 1493, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.4511351756186354}}
{"text": "\n// Copyright 2010-2014, D. E. Shaw Research.\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 <boost/random/uniform_int_distribution.hpp>\n#include <boost/random/counter_based_engine.hpp>\n#include <boost/limits.hpp>\n\ntypedef boost::random::counter_based_engine<BOOST_COUNTER_BASED_ENGINE_RESULT_TYPE, BOOST_PSEUDO_RANDOM_FUNCTION, BOOST_COUNTER_BASED_ENGINE_CTRBITS> engine_t;\n\n#define BOOST_RANDOM_URNG engine_t\n\n#include \"test_generator.ipp\"\n\n// Now we can go on to test other aspects of engine_t...\n\n// counter-based engines can do discards in O(1) time.  Let's\n// check that many such \"random\" discards add up correctly.\nvoid do_test_huge_discard(boost::uintmax_t bigjump){\n    BOOST_RANDOM_URNG urng0;\n    BOOST_RANDOM_URNG urng;\n    BOOST_RANDOM_URNG urng2;\n    BOOST_RANDOM_URNG urng3;\n    BOOST_RANDOM_URNG urngn;\n\n    BOOST_CHECK_EQUAL(urng, urng2);\n    boost::uintmax_t n = 0;\n    bool out_of_bits1 = false;\n    bool out_of_bitsn = false;\n    try{\n        urng2.discard(bigjump);\n    }catch(std::invalid_argument&){\n        // It's ok if bigjump exceeds our sequence length.\n        // It just means that we are testing a counter_based_engine\n        // with a small-ish number of CounterBits.\n        out_of_bits1 = true;\n    }\n    try{\n        while(n < bigjump){\n            if(!out_of_bits1)\n                BOOST_CHECK_NE(urng, urng2);\n            boost::random::uniform_int_distribution<boost::uintmax_t> d(1, 1+(bigjump-n)/73);;\n            boost::uintmax_t smalljump = d(urng3);\n            urng.discard(smalljump);\n            n += smalljump;\n            urngn = urng0;\n            urngn.discard(n);\n            BOOST_CHECK_EQUAL(urng, urngn);\n        }\n    }catch(std::invalid_argument&){\n        out_of_bitsn = true;\n    }\n    BOOST_CHECK_EQUAL(out_of_bits1, out_of_bitsn);\n    if(!out_of_bits1)\n        BOOST_CHECK_EQUAL(urng, urng2);\n}\n\nBOOST_AUTO_TEST_CASE(test_huge_discard)\n{\n    // Run the discard check with numbers large enough to force us to\n    // \"carry\" between the elements of the counter.\n    do_test_huge_discard((std::numeric_limits<boost::uintmax_t>::max)() - 1);\n    do_test_huge_discard(((std::numeric_limits<boost::uintmax_t>::max)()>>1) + 1);\n    do_test_huge_discard(((std::numeric_limits<boost::uintmax_t>::max)()>>32) + 1);\n    do_test_huge_discard((std::numeric_limits<BOOST_RANDOM_URNG::result_type>::max)());\n}        \n\n// TODO: restart, seed(key), constructor(Prf, start), limited counter width.\n\n", "meta": {"hexsha": "eff3df0893a31247ebc8374c93fc16e06e28650d", "size": 2564, "ext": "ipp", "lang": "C++", "max_stars_repo_path": "libs/random/test/test_counter_based_engine.ipp", "max_stars_repo_name": "DEShawResearch/Random123-Boost", "max_stars_repo_head_hexsha": "65e3d874b67aa7b3e02d5ad8306462f52d2079c0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2015-04-08T18:40:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T00:08:25.000Z", "max_issues_repo_path": "libs/random/test/test_counter_based_engine.ipp", "max_issues_repo_name": "DEShawResearch/Random123-Boost", "max_issues_repo_head_hexsha": "65e3d874b67aa7b3e02d5ad8306462f52d2079c0", "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/random/test/test_counter_based_engine.ipp", "max_forks_repo_name": "DEShawResearch/Random123-Boost", "max_forks_repo_head_hexsha": "65e3d874b67aa7b3e02d5ad8306462f52d2079c0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.6111111111, "max_line_length": 159, "alphanum_fraction": 0.6875975039, "num_tokens": 692, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321964553656, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.4511351734991331}}
{"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 basic_metrics.hpp\n * @brief\n * @author Piotr Wygocki\n * @version 1.0\n * @date 2013-02-15\n */\n#ifndef PAAL_BASIC_METRICS_HPP\n#define PAAL_BASIC_METRICS_HPP\n\n#include \"metric_traits.hpp\"\n\n#include <boost/multi_array.hpp>\n#include <boost/range/iterator_range.hpp>\n\n#include <array>\n\nnamespace paal {\nnamespace data_structures {\n\n/**\n * @class rectangle_array_metric\n * @brief \\ref metric implementation on 2 dimensional array\n *        distance calls on this metric are valid opnly when x < N and y  < M\n *        (N and M given in the constructor)\n *        when we know that only certain calls occurs it might be worthwhile to\n * use this metric\n *\n * @tparam DistanceTypeParam\n */\ntemplate <typename DistanceTypeParam> class rectangle_array_metric {\n  public:\n    typedef DistanceTypeParam DistanceType;\n    typedef int VertexType;\n    /**\n     * @brief constructor\n     *\n     * @param N\n     * @param M\n     */\n    rectangle_array_metric(int N = 0, int M = 0)\n        : m_matrix(boost::extents[N][M]) {}\n\n    /**\n     * @brief operator(), valid only when v < N and w < M\n     *\n     * @param v\n     * @param w\n     *\n     * @return\n     */\n    DistanceType operator()(const VertexType &v, const VertexType &w) const {\n        return m_matrix[v][w];\n    }\n\n    /**\n     * @brief operator(), valid only when v < N and w < M, nonconst version\n     *\n     * @param v\n     * @param w\n     *\n     * @return\n     */\n    DistanceType &operator()(const VertexType &v, const VertexType &w) {\n        return m_matrix[v][w];\n    }\n\n    /**\n     * @brief constructor from another metric\n     *\n     * @tparam OtherMetrics\n     * @param other\n     * @param xrange\n     * @param yrange\n     */\n    template <typename OtherMetrics, typename XRange, typename YRange>\n    rectangle_array_metric(const OtherMetrics &other, XRange && xrange\n                           , YRange && yrange)\n        : rectangle_array_metric(boost::distance(xrange),\n                                 boost::distance(yrange)) {\n        int i = 0;\n        for (auto && v : xrange) {\n            int j = 0;\n            for (auto && w : yrange) {\n                m_matrix[i][j] = other(v, w);\n                ++j;\n            }\n            ++i;\n        }\n    }\n\n    /**\n     * @brief operator=\n     *\n     * @param am\n     *\n     * @return\n     */\n    rectangle_array_metric &operator=(const rectangle_array_metric &am) {\n        auto shape = am.m_matrix.shape();\n        std::vector<std::size_t> dim(shape, shape + DIM_NR);\n        m_matrix.resize(dim);\n        m_matrix = am.m_matrix;\n        return *this;\n    }\n\n    ///operator==\n    bool operator==(const rectangle_array_metric & other) const {\n        return m_matrix == other.m_matrix;\n    }\n\n  protected:\n    /**\n     * @brief dimention of multi array\n     */\n    static const int DIM_NR = 2;\n    typedef boost::multi_array<DistanceType, DIM_NR> matrix_type;\n    /// matrix with data\n    matrix_type m_matrix;\n};\n\n\n\n/**\n * @brief this metric is rectangle_array_metric with N == M.\n *\n * @tparam DistanceTypeParam\n */\ntemplate <typename DistanceTypeParam>\nclass array_metric : public rectangle_array_metric<DistanceTypeParam> {\n    typedef rectangle_array_metric<DistanceTypeParam> base;\n\n  public:\n    /**\n     * @brief constructor\n     *\n     * @param N\n     */\n    array_metric(int N = 0) : base(N, N) {}\n\n    /**\n     * @brief returns N\n     *\n     * @return\n     */\n    int size() const { return this->m_matrix.size(); }\n\n    /**\n     * @brief constructor from another metric\n     *\n     * @tparam OtherMetrics\n     * @tparam Items\n     * @param other\n     * @param items\n     */\n    template <typename OtherMetrics, typename Items>\n    array_metric(const OtherMetrics &other, Items && items)\n        : base(other, items, items) {}\n};\n}\n}\n#endif // PAAL_BASIC_METRICS_HPP\n", "meta": {"hexsha": "395bc6bf4956d614e7b528d523b48ee7583994e7", "size": 4147, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/paal/data_structures/metric/basic_metrics.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/data_structures/metric/basic_metrics.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/data_structures/metric/basic_metrics.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": 24.3941176471, "max_line_length": 79, "alphanum_fraction": 0.571497468, "num_tokens": 1014, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.45113517174963275}}
{"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#include <nt2/trigonometric/include/functions/rem_pio2_straight.hpp>\n#include <boost/fusion/tuple.hpp>\n#include <nt2/trigonometric/constants.hpp>\n\n#include <boost/type_traits/is_same.hpp>\n#include <nt2/sdk/functor/meta/call.hpp>\n#include <nt2/sdk/meta/as_integer.hpp>\n#include <nt2/sdk/meta/as_floating.hpp>\n#include <nt2/sdk/meta/as_signed.hpp>\n#include <nt2/sdk/meta/upgrade.hpp>\n#include <nt2/sdk/meta/downgrade.hpp>\n#include <nt2/sdk/meta/scalar_of.hpp>\n#include <boost/dispatch/meta/as_floating.hpp>\n#include <boost/type_traits/common_type.hpp>\n#include <nt2/sdk/unit/tests.hpp>\n#include <nt2/sdk/unit/module.hpp>\n#include <nt2/sdk/memory/buffer.hpp>\n#include <nt2/constant/constant.hpp>\n\n\nNT2_TEST_CASE_TPL ( rem_pio2_straight_real__1_0,  NT2_REAL_TYPES)\n{\n\n  using nt2::rem_pio2_straight;\n  using nt2::tag::rem_pio2_straight_;\n  typedef typename nt2::meta::as_integer<T>::type iT;\n typedef std::pair<iT, T>  r_t;\n\n\n  NT2_TEST_TYPE_IS( (typename boost::dispatch::meta::call<rem_pio2_straight_(T)>::type)\n                  , (std::pair<iT,T>)\n                  );\n\n  {\n    r_t res = rem_pio2_straight(nt2::Pio_2<T>());\n    T r1;\n    NT2_TEST_EQUAL( rem_pio2_straight(nt2::Pio_2<T>(), r1), nt2::One<iT>());\n    NT2_TEST_ULP_EQUAL( r1, nt2::Zero<T>(), 0.5);\n    NT2_TEST_EQUAL( rem_pio2_straight(nt2::Pio_4<T>(), r1), nt2::One<iT>());\n    NT2_TEST_ULP_EQUAL( r1, -nt2::Pio_4<T>(), 0.5);\n  }\n}\n", "meta": {"hexsha": "40ce1f317185befd9aa5baf6d1ea5780c5deb532", "size": 1904, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/core/trigonometric/unit/scalar/rem_pio2_straight.cpp", "max_stars_repo_name": "pbrunet/nt2", "max_stars_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "modules/core/trigonometric/unit/scalar/rem_pio2_straight.cpp", "max_issues_repo_name": "pbrunet/nt2", "max_issues_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/core/trigonometric/unit/scalar/rem_pio2_straight.cpp", "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": 37.3333333333, "max_line_length": 87, "alphanum_fraction": 0.6271008403, "num_tokens": 540, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.45113516576112833}}
{"text": "#include <sys/stat.h>\n#include <sys/types.h>\n#include <unistd.h>\n#include <random>\n#include <Eigen/Cholesky>\n#include <fstream>\n#include <iomanip>\n#include <srrg_system_utils/parse_command_line.h>\n#include <srrg_boss/deserializer.h>\n\n#include \"srrg_solver/solver_core/instances.h\"\n#include \"srrg_solver/solver_core/factor_graph.h\"\n#include \"srrg_solver/variables_and_factors/types_3d/variable_se3_ad.h\"\n#include \"srrg_solver/variables_and_factors/types_3d/variable_point3_ad.h\"\n#include \"srrg_solver/variables_and_factors/types_3d/se3_pose_pose_geodesic_error_factor.h\"\n#include \"srrg_solver/variables_and_factors/types_3d/se3_pose_point_offset_error_factor.h\"\n\n#include \"srrg_solver/variables_and_factors/types_2d/variable_se2_ad.h\"\n#include \"srrg_solver/variables_and_factors/types_2d/variable_point2_ad.h\"\n#include \"srrg_solver/variables_and_factors/types_2d/se2_pose_pose_geodesic_error_factor.h\"\n#include \"srrg_solver/variables_and_factors/types_2d/se2_pose_point_error_factor.h\"\n\n#include \"srrg_solver/utils/factor_graph_initializer.h\"\n#include \"srrg_solver/solver_incremental/factor_graph_incremental_sorter.h\"\n\nusing namespace srrg2_core;\nusing namespace srrg2_solver;\nusing namespace std;\n\nextern char** environ;\nconst std::string exe_name = environ[0];\n#define LOG std::cerr << exe_name << \"|\"\n\n\nstatic const char* banner[] = {\n  \"initializes the factor graph,  attempting first a breadth first on the poses, then a local triangulation of the landmarks\",\n  \"usage: solver_app_graph_initializer -i <input> -o <output>\",\n  0\n};\n\n// ia THE PROGRAM\nint main(int argc, char** argv) {\n  ParseCommandLine cmd_line(argv, banner);\n  ArgumentString input_file          (&cmd_line, \"i\",    \"input-file\",             \"file where to read the input \", \"\");\n  ArgumentString output_file          (&cmd_line, \"o\",    \"output-file\",           \"file where to save the output\", \"\");\n  ArgumentFlag incremental(&cmd_line, \"s\",    \"incremental\",           \"if toggled, triggers incremental initialization\");\n  ArgumentFlag verbose(&cmd_line, \"v\",    \"verbose\",           \"if toggled, bloats the screen with stuff\");\n  ArgumentString path_type          (&cmd_line, \"t\",    \"path-type\",             \"type of the variable used for sorting\", \"VariableSE3QuaternionRightAD\");\n\n  cmd_line.parse();\n\n  FactorGraphInitializer initializer;\n  if (verbose.isSet())\n    initializer.verbose=true;\n  if (! input_file.isSet()) {\n    cerr << \"no input file provided, returning\" << std::endl;\n    return 0;\n  }\n  FactorGraphPtr graph;\n  std::set<VariableBase::Id> parameter_ids;\n  \n  if (! incremental.isSet()) {\n    std::cerr << \"loading file: [\" << input_file.value() << \"]... \";\n    graph = FactorGraph::read(input_file.value());\n    std::cerr << \"done, factors:\" << graph->factors().size() << \" vars: \" << graph->variables().size() << std::endl;\n    std::cerr << \"initializing (batch) ...\";\n    for (auto v_it: graph->variables()) {\n      if (v_it.first!=0 && v_it.second->status()==VariableBase::Fixed) {\n        initializer.parameterIds().insert(v_it.first);\n      }\n    }\n    initializer.setGraph(*graph);\n    initializer.compute();\n    std::cerr << \"done\" << std::endl;\n    int num_initialized=0;\n    for (auto v_it: graph->variables()) {\n      VariableBase* v=v_it.second;\n      if (initializer.isInit(v)) {\n        ++num_initialized;\n      }\n    }\n    std::cerr << \"total intialized: \" << num_initialized << \"/\" << graph->variables().size() << endl;\n  } else {\n    graph = FactorGraphPtr(new FactorGraph);\n    FactorGraphIncrementalReader reader;\n    reader.setGraph(graph);\n    reader.setPathType(path_type.value());\n    reader.setFilePath(input_file.value());\n\n    std::cerr << \"done\" << std::endl;\n    initializer.setGraph(*graph);\n\n    //process the data incrementally\n    std::set<VariableBase::Id> new_vars;\n    std::set<FactorBase::Id> new_factors;\n    cerr << \"Incremental init \" << endl;\n    while (reader.readEpoch(new_vars, new_factors)) {\n      if (new_vars.size()) {\n        cerr << \"\\rEpoch: \" << *new_vars.begin() << \" \" << \" v: \" <<new_vars.size() << \" f:\" << new_factors.size();\n      }\n      initializer.updateGraph();\n      initializer.compute();\n    }\n    cerr << endl;\n    //final batch\n    initializer.updateGraph();\n    initializer.compute();\n  }\n  \n  if (! output_file.isSet()) {\n    cerr << \"no output file provided, skipping output\" << endl;\n    return 0;\n  }\n  std::cerr << \"writing output to file [ \" << output_file.value() << \"]... \";\n  graph->write(output_file.value());\n  cerr << \" done\" << endl;\n  return 0;\n}\n", "meta": {"hexsha": "575685cc3c35815a2af3e25272d7d0723f4a876d", "size": 4524, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "catkin_ws/src/srrg2_solver/srrg2_solver/app/graph_manipulators/solver_app_graph_initializer.cpp", "max_stars_repo_name": "laaners/progetto-labiagi_pick_e_delivery", "max_stars_repo_head_hexsha": "3453bfbc1dd7562c78ba06c0f79b069b0a952c0e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "catkin_ws/src/srrg2_solver/srrg2_solver/app/graph_manipulators/solver_app_graph_initializer.cpp", "max_issues_repo_name": "laaners/progetto-labiagi_pick_e_delivery", "max_issues_repo_head_hexsha": "3453bfbc1dd7562c78ba06c0f79b069b0a952c0e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "catkin_ws/src/srrg2_solver/srrg2_solver/app/graph_manipulators/solver_app_graph_initializer.cpp", "max_forks_repo_name": "laaners/progetto-labiagi_pick_e_delivery", "max_forks_repo_head_hexsha": "3453bfbc1dd7562c78ba06c0f79b069b0a952c0e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.0168067227, "max_line_length": 154, "alphanum_fraction": 0.6792661362, "num_tokens": 1157, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.63341024983754, "lm_q1q2_score": 0.45113516576112817}}
{"text": "/// \\file       include/gslcpp/wrap/sum.hpp\n/// \\copyright  2022 Thomas E. Vaughan, all rights reserved.\n/// \\brief      Definition of gsl::w_sum().\n\n#pragma once\n#include \"container.hpp\" // w_vector\n#include \"element.hpp\" // element_t\n#include <Eigen/Core> // Dynamic, Map, Matrix, Stride\n\nnamespace gsl {\n\n\n/// Sum of elements in vector `v`.\n/// https://www.gnu.org/software/gsl/doc/html/vectors.html#c.gsl_vector_sum\n/// @param v  Pointer to vector.\n/// @return  Sum of elements in `v`.\ninline auto w_sum(w_vector<double const> *v) { return gsl_vector_sum(v); }\n\n\n/// Sum of elements in vector `v`.\n/// https://www.gnu.org/software/gsl/doc/html/vectors.html#c.gsl_vector_sum\n/// @param v  Pointer to vector.\n/// @return  Sum of elements in `v`.\ninline auto w_sum(w_vector<float const> *v) { return gsl_vector_float_sum(v); }\n\n\n/// Sum of elements in vector `v`.\n/// https://www.gnu.org/software/gsl/doc/html/vectors.html#c.gsl_vector_sum\n/// @param v  Pointer to vector.\n/// @return  Sum of elements in `v`.\ninline auto w_sum(w_vector<long double const> *v) {\n  return gsl_vector_long_double_sum(v);\n}\n\n\n/// Sum of elements in vector `v`.\n/// https://www.gnu.org/software/gsl/doc/html/vectors.html#c.gsl_vector_sum\n/// @param v  Pointer to vector.\n/// @return  Sum of elements in `v`.\ninline auto w_sum(w_vector<int const> *v) { return gsl_vector_int_sum(v); }\n\n\n/// Sum of elements in vector `v`.\n/// https://www.gnu.org/software/gsl/doc/html/vectors.html#c.gsl_vector_sum\n/// @param v  Pointer to vector.\n/// @return  Sum of elements in `v`.\ninline auto w_sum(w_vector<unsigned const> *v) {\n  return gsl_vector_uint_sum(v);\n}\n\n\n/// Sum of elements in vector `v`.\n/// https://www.gnu.org/software/gsl/doc/html/vectors.html#c.gsl_vector_sum\n/// @param v  Pointer to vector.\n/// @return  Sum of elements in `v`.\ninline auto w_sum(w_vector<long const> *v) { return gsl_vector_long_sum(v); }\n\n\n/// Sum of elements in vector `v`.\n/// https://www.gnu.org/software/gsl/doc/html/vectors.html#c.gsl_vector_sum\n/// @param v  Pointer to vector.\n/// @return  Sum of elements in `v`.\ninline auto w_sum(w_vector<unsigned long const> *v) {\n  return gsl_vector_ulong_sum(v);\n}\n\n\n/// Sum of elements in vector `v`.\n/// https://www.gnu.org/software/gsl/doc/html/vectors.html#c.gsl_vector_sum\n/// @param v  Pointer to vector.\n/// @return  Sum of elements in `v`.\ninline auto w_sum(w_vector<short const> *v) { return gsl_vector_short_sum(v); }\n\n\n/// Sum of elements in vector `v`.\n/// https://www.gnu.org/software/gsl/doc/html/vectors.html#c.gsl_vector_sum\n/// @param v  Pointer to vector.\n/// @return  Sum of elements in `v`.\ninline auto w_sum(w_vector<unsigned short const> *v) {\n  return gsl_vector_ushort_sum(v);\n}\n\n\n/// Sum of elements in vector `v`.\n/// https://www.gnu.org/software/gsl/doc/html/vectors.html#c.gsl_vector_sum\n/// @param v  Pointer to vector.\n/// @return  Sum of elements in `v`.\ninline auto w_sum(w_vector<char const> *v) { return gsl_vector_char_sum(v); }\n\n\n/// Sum of elements in vector `v`.\n/// https://www.gnu.org/software/gsl/doc/html/vectors.html#c.gsl_vector_sum\n/// @param v  Pointer to vector.\n/// @return  Sum of elements in `v`.\ninline auto w_sum(w_vector<unsigned char const> *v) {\n  return gsl_vector_uchar_sum(v);\n}\n\n\n/// Sum of elements in complex vector, not covered by GSL's sum.\n/// https://www.gnu.org/software/gsl/doc/html/vectors.html#c.gsl_vector_sum\n/// This implementation uses Eigen to compute the sum.\n/// @tparam C  Complex type of vector's element.\n/// @param v  Reference to vector.\n/// @return  Sum of elements.\ntemplate<typename C> C complex_sum(w_vector<C const> *v) {\n  using Eigen::Dynamic;\n  using Eigen::Map;\n  using Eigen::Matrix;\n  using Eigen::Stride;\n  using S= Stride<Dynamic, Dynamic>;\n  using map= Map<Matrix<C, Dynamic, 1> const, 0, S>;\n  S const s(v->size * v->stride, v->stride);\n  return map((C const *)v->data, v->size, s).sum();\n}\n\n\n/// Sum of elements in vector `v`.\n/// https://www.gnu.org/software/gsl/doc/html/vectors.html#c.gsl_vector_sum\n/// @param v  Pointer to vector.\n/// @return  Sum of elements in `v`.\ninline auto w_sum(w_vector<gsl::complex<double> const> *v) {\n  return complex_sum<gsl::complex<double>>(v);\n}\n\n\n/// Sum of elements in vector `v`.\n/// https://www.gnu.org/software/gsl/doc/html/vectors.html#c.gsl_vector_sum\n/// @param v  Pointer to vector.\n/// @return  Sum of elements in `v`.\ninline auto w_sum(w_vector<gsl::complex<float> const> *v) {\n  return complex_sum<gsl::complex<float>>(v);\n}\n\n\n/// Sum of elements in vector `v`.\n/// https://www.gnu.org/software/gsl/doc/html/vectors.html#c.gsl_vector_sum\n/// @param v  Pointer to vector.\n/// @return  Sum of elements in `v`.\ninline auto w_sum(w_vector<gsl::complex<long double> const> *v) {\n  return complex_sum<gsl::complex<long double>>(v);\n}\n\n\n} // namespace gsl\n\n// EOF\n", "meta": {"hexsha": "e95f8cab3094b9a1566c46d2b56c3b1b3802b69f", "size": 4803, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/gslcpp/wrap/sum.hpp", "max_stars_repo_name": "tevaughan/gslcpp", "max_stars_repo_head_hexsha": "5aa83ce436111f21556470b94048545195607aec", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/gslcpp/wrap/sum.hpp", "max_issues_repo_name": "tevaughan/gslcpp", "max_issues_repo_head_hexsha": "5aa83ce436111f21556470b94048545195607aec", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2022-02-17T02:34:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-08T18:01:41.000Z", "max_forks_repo_path": "include/gslcpp/wrap/sum.hpp", "max_forks_repo_name": "tevaughan/gslcpp", "max_forks_repo_head_hexsha": "5aa83ce436111f21556470b94048545195607aec", "max_forks_repo_licenses": ["BSD-3-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.4527027027, "max_line_length": 79, "alphanum_fraction": 0.6924838643, "num_tokens": 1295, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321720225278, "lm_q2_score": 0.6334102567576902, "lm_q1q2_score": 0.4511351629518767}}
{"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_ALGORITHMS_DETAIL_WITHIN_MULTI_POINT_HPP\r\n#define BOOST_GEOMETRY_ALGORITHMS_DETAIL_WITHIN_MULTI_POINT_HPP\r\n\r\n\r\n#include <algorithm>\r\n#include <vector>\r\n\r\n#include <boost/range.hpp>\r\n#include <boost/type_traits/is_same.hpp>\r\n\r\n#include <boost/geometry/algorithms/detail/disjoint/box_box.hpp>\r\n#include <boost/geometry/algorithms/detail/disjoint/point_box.hpp>\r\n#include <boost/geometry/algorithms/detail/expand_by_epsilon.hpp>\r\n#include <boost/geometry/algorithms/detail/relate/less.hpp>\r\n#include <boost/geometry/algorithms/detail/within/point_in_geometry.hpp>\r\n#include <boost/geometry/algorithms/envelope.hpp>\r\n#include <boost/geometry/algorithms/detail/partition.hpp>\r\n#include <boost/geometry/core/tag.hpp>\r\n#include <boost/geometry/core/tag_cast.hpp>\r\n#include <boost/geometry/core/tags.hpp>\r\n\r\n#include <boost/geometry/geometries/box.hpp>\r\n\r\n#include <boost/geometry/index/rtree.hpp>\r\n\r\n#include <boost/geometry/strategies/covered_by.hpp>\r\n#include <boost/geometry/strategies/disjoint.hpp>\r\n\r\n\r\nnamespace boost { namespace geometry {\r\n\r\n#ifndef DOXYGEN_NO_DETAIL\r\nnamespace detail { namespace within {\r\n\r\nstruct multi_point_point\r\n{\r\n    template <typename MultiPoint, typename Point, typename Strategy>\r\n    static inline bool apply(MultiPoint const& multi_point,\r\n                             Point const& point,\r\n                             Strategy const& strategy)\r\n    {\r\n        typedef typename boost::range_const_iterator<MultiPoint>::type iterator;\r\n        for ( iterator it = boost::begin(multi_point) ; it != boost::end(multi_point) ; ++it )\r\n        {\r\n            if (! strategy.apply(*it, point))\r\n            {\r\n                return false;\r\n            }\r\n        }\r\n\r\n        // all points of MultiPoint inside Point\r\n        return true;\r\n    }\r\n};\r\n\r\n// NOTE: currently the strategy is ignored, math::equals() is used inside relate::less\r\nstruct multi_point_multi_point\r\n{\r\n    template <typename MultiPoint1, typename MultiPoint2, typename Strategy>\r\n    static inline bool apply(MultiPoint1 const& multi_point1,\r\n                             MultiPoint2 const& multi_point2,\r\n                             Strategy const& /*strategy*/)\r\n    {\r\n        typedef typename boost::range_value<MultiPoint2>::type point2_type;\r\n\r\n        relate::less const less = relate::less();\r\n\r\n        std::vector<point2_type> points2(boost::begin(multi_point2), boost::end(multi_point2));\r\n        std::sort(points2.begin(), points2.end(), less);\r\n\r\n        bool result = false;\r\n\r\n        typedef typename boost::range_const_iterator<MultiPoint1>::type iterator;\r\n        for ( iterator it = boost::begin(multi_point1) ; it != boost::end(multi_point1) ; ++it )\r\n        {\r\n            if (! std::binary_search(points2.begin(), points2.end(), *it, less))\r\n            {\r\n                return false;\r\n            }\r\n            else\r\n            {\r\n                result = true;\r\n            }\r\n        }\r\n\r\n        return result;\r\n    }\r\n};\r\n\r\n\r\n// TODO: the complexity could be lesser\r\n//   the second geometry could be \"prepared\"/sorted\r\n// For Linear geometries partition could be used\r\n// For Areal geometries point_in_geometry() would have to call the winding\r\n//   strategy differently, currently it linearly calls the strategy for each\r\n//   segment. So the segments would have to be sorted in a way consistent with\r\n//   the strategy and then the strategy called only for the segments in range.\r\ntemplate <bool Within>\r\nstruct multi_point_single_geometry\r\n{\r\n    template <typename MultiPoint, typename LinearOrAreal, typename Strategy>\r\n    static inline bool apply(MultiPoint const& multi_point,\r\n                             LinearOrAreal const& linear_or_areal,\r\n                             Strategy const& strategy)\r\n    {\r\n        typedef typename boost::range_value<MultiPoint>::type point1_type;\r\n        typedef typename point_type<LinearOrAreal>::type point2_type;\r\n        typedef model::box<point2_type> box2_type;\r\n\r\n        // Create envelope of geometry\r\n        box2_type box;\r\n        geometry::envelope(linear_or_areal, box, strategy.get_envelope_strategy());\r\n        geometry::detail::expand_by_epsilon(box);\r\n\r\n        typedef typename strategy::covered_by::services::default_strategy\r\n            <\r\n                point1_type, box2_type\r\n            >::type point_in_box_type;\r\n\r\n        // Test each Point with envelope and then geometry if needed\r\n        // If in the exterior, break\r\n        bool result = false;\r\n\r\n        typedef typename boost::range_const_iterator<MultiPoint>::type iterator;\r\n        for ( iterator it = boost::begin(multi_point) ; it != boost::end(multi_point) ; ++it )\r\n        {\r\n            int in_val = 0;\r\n\r\n            // exterior of box and of geometry\r\n            if (! point_in_box_type::apply(*it, box)\r\n                || (in_val = point_in_geometry(*it, linear_or_areal, strategy)) < 0)\r\n            {\r\n                result = false;\r\n                break;\r\n            }\r\n\r\n            // interior : interior/boundary\r\n            if (Within ? in_val > 0 : in_val >= 0)\r\n            {\r\n                result = true;\r\n            }\r\n        }\r\n\r\n        return result;\r\n    }\r\n};\r\n\r\n\r\n// TODO: same here, probably the complexity could be lesser\r\ntemplate <bool Within>\r\nstruct multi_point_multi_geometry\r\n{\r\n    template <typename MultiPoint, typename LinearOrAreal, typename Strategy>\r\n    static inline bool apply(MultiPoint const& multi_point,\r\n                             LinearOrAreal const& linear_or_areal,\r\n                             Strategy const& strategy)\r\n    {\r\n        typedef typename point_type<LinearOrAreal>::type point2_type;\r\n        typedef model::box<point2_type> box2_type;\r\n        static const bool is_linear = is_same\r\n            <\r\n                typename tag_cast\r\n                    <\r\n                        typename tag<LinearOrAreal>::type,\r\n                        linear_tag\r\n                    >::type,\r\n                linear_tag\r\n            >::value;\r\n\r\n        typename Strategy::envelope_strategy_type const\r\n            envelope_strategy = strategy.get_envelope_strategy();\r\n\r\n        // TODO: box pairs could be constructed on the fly, inside the rtree\r\n\r\n        // Prepare range of envelopes and ids\r\n        std::size_t count2 = boost::size(linear_or_areal);\r\n        typedef std::pair<box2_type, std::size_t> box_pair_type;\r\n        typedef std::vector<box_pair_type> box_pair_vector;\r\n        box_pair_vector boxes(count2);\r\n        for (std::size_t i = 0 ; i < count2 ; ++i)\r\n        {\r\n            geometry::envelope(linear_or_areal, boxes[i].first, envelope_strategy);\r\n            geometry::detail::expand_by_epsilon(boxes[i].first);\r\n            boxes[i].second = i;\r\n        }\r\n\r\n        // Create R-tree\r\n        index::rtree<box_pair_type, index::rstar<4> > rtree(boxes.begin(), boxes.end());\r\n\r\n        // For each point find overlapping envelopes and test corresponding single geometries\r\n        // If a point is in the exterior break\r\n        bool result = false;\r\n\r\n        typedef typename boost::range_const_iterator<MultiPoint>::type iterator;\r\n        for ( iterator it = boost::begin(multi_point) ; it != boost::end(multi_point) ; ++it )\r\n        {\r\n            // TODO: investigate the possibility of using satisfies\r\n            // TODO: investigate the possibility of using iterative queries (optimization below)\r\n            box_pair_vector inters_boxes;\r\n            rtree.query(index::intersects(*it), std::back_inserter(inters_boxes));\r\n\r\n            bool found_interior = false;\r\n            bool found_boundary = false;\r\n            int boundaries = 0;\r\n\r\n            typedef typename box_pair_vector::const_iterator iterator;\r\n            for ( iterator box_it = inters_boxes.begin() ; box_it != inters_boxes.end() ; ++box_it )\r\n            {\r\n                int in_val = point_in_geometry(*it, range::at(linear_or_areal, box_it->second), strategy);\r\n\r\n                if (in_val > 0)\r\n                    found_interior = true;\r\n                else if (in_val == 0)\r\n                    ++boundaries;\r\n\r\n                // If the result was set previously (interior or\r\n                // interior/boundary found) the only thing that needs to be\r\n                // done for other points is to make sure they're not\r\n                // overlapping the exterior no need to analyse boundaries.\r\n                if (result && in_val >= 0)\r\n                {\r\n                    break;\r\n                }\r\n            }\r\n\r\n            if ( boundaries > 0)\r\n            {\r\n                if (is_linear && boundaries % 2 == 0)\r\n                    found_interior = true;\r\n                else\r\n                    found_boundary = true;\r\n            }\r\n\r\n            // exterior\r\n            if (! found_interior && ! found_boundary)\r\n            {\r\n                result = false;\r\n                break;\r\n            }\r\n\r\n            // interior : interior/boundary\r\n            if (Within ? found_interior : (found_interior || found_boundary))\r\n            {\r\n                result = true;\r\n            }\r\n        }\r\n\r\n        return result;\r\n    }\r\n};\r\n\r\n}} // namespace detail::within\r\n#endif // DOXYGEN_NO_DETAIL\r\n\r\n}} // namespace boost::geometry\r\n\r\n\r\n#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_WITHIN_MULTI_POINT_HPP\r\n", "meta": {"hexsha": "2d35a574497d111167994bd14d4870282dc396bb", "size": 9667, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Service/jni/boost/x86_64/include/boost-1_65_1/boost/geometry/algorithms/detail/within/multi_point.hpp", "max_stars_repo_name": "Mattlk13/innoextract-android", "max_stars_repo_head_hexsha": "5a69382ac9104d47383c1af0aaa0bc8a336c9744", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2015-04-27T00:12:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-05T01:52:56.000Z", "max_issues_repo_path": "Service/jni/boost/x86_64/include/boost-1_65_1/boost/geometry/algorithms/detail/within/multi_point.hpp", "max_issues_repo_name": "Mattlk13/innoextract-android", "max_issues_repo_head_hexsha": "5a69382ac9104d47383c1af0aaa0bc8a336c9744", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-11T00:36:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-11T15:39:01.000Z", "max_forks_repo_path": "Service/jni/boost/x86_64/include/boost-1_65_1/boost/geometry/algorithms/detail/within/multi_point.hpp", "max_forks_repo_name": "Mattlk13/innoextract-android", "max_forks_repo_head_hexsha": "5a69382ac9104d47383c1af0aaa0bc8a336c9744", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2015-02-28T01:38:22.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-13T13:36:36.000Z", "avg_line_length": 35.936802974, "max_line_length": 107, "alphanum_fraction": 0.5948070756, "num_tokens": 1989, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321720225278, "lm_q2_score": 0.6334102567576901, "lm_q1q2_score": 0.4511351629518766}}
{"text": "#include <Eigen/Eigen>\n#include <sophus/se3.hpp>\n\n#include <pangolin/pangolin.h>\n#include <pangolin/glcuda.h>\n#include <pangolin/glvbo.h>\n\n#include <SceneGraph/SceneGraph.h>\n\n#include <kangaroo/kangaroo.h>\n#include <kangaroo/BoundedVolume.h>\n#include <kangaroo/MarchingCubes.h>\n#include <kangaroo/extra/ImageSelect.h>\n#include <kangaroo/extra/BaseDisplayCuda.h>\n#include <kangaroo/extra/DisplayUtils.h>\n#include <kangaroo/extra/Handler3dGpuDepth.h>\n#include <kangaroo/extra/SavePPM.h>\n#include <kangaroo/extra/SaveMeshlab.h>\n\n#ifdef HAVE_CVARS\n#include <kangaroo/extra/CVarHelpers.h>\n#endif // HAVE_CVARS\n\n#include <opencv2/opencv.hpp>\n#include <unistd.h>\n\n#include <HAL/Utils/GetPot>\n#include <HAL/Utils/TicToc.h>\n#include <HAL/Camera/CameraDevice.h>\n#include <calibu/Calibu.h>\n#include <CVars/CVar.h>\n\n#include <string>\n\nusing namespace pangolin;\n\nstruct pni {  // pose 'n' intrinsics\n  Sophus::SE3d p;\n  roo::ImageIntrinsics i;\n};\n\n// camera serial number -> camera pose and intrinsics\ntypedef std::map<uint64_t, pni> cameraMap;\n\n// Creates a cameraMap from the calibu camera rig\nvoid getCameraCalibration(const calibu::CameraRig &rig,\n                          cameraMap& Ks);\n\n// Copies a pb image into a kangaroo image\nvoid copyFrom(const std::shared_ptr<pb::Image>& pbim,\n              roo::Image<unsigned short, roo::TargetDevice, roo::Manage>& kim);\n\n// Sets a depth image to the display\nvoid setDepthImages(const std::shared_ptr<pb::ImageArray>& pbim,\n                    std::vector<SceneGraph::ImageView>& views);\n\nint main( int argc, char* argv[] )\n{\n  // Initialise window\n  View& container = SetupPangoGLWithCuda(1024, 768);\n  SceneGraph::GLSceneGraph::ApplyPreferredGlSettings();\n\n  GetPot clArgs(argc, argv);\n\n  ///----- Load camera model.\n  hal::Camera cam(clArgs.follow(\"\", \"-cam\"));\n  std::shared_ptr< pb::ImageArray > vImages = pb::ImageArray::Create();\n  calibu::CameraRig rig;\n  if (!cam.GetDeviceProperty(hal::DeviceDirectory).empty()) {\n    std::cout<<\"Loaded camera: \"<<cam.GetDeviceProperty(hal::DeviceDirectory) + '/' + clArgs.follow(\"cameras.xml\", \"-cmod\")<<std::endl;\n    rig = calibu::ReadXmlRig(cam.GetDeviceProperty(hal::DeviceDirectory) + '/' + clArgs.follow(\"cameras.xml\", \"-cmod\"));\n  }\n  else {\n    std::cout << \"in second option\" << std::endl;\n    rig = calibu::ReadXmlRig(clArgs.follow(\"cameras.xml\", \"-cmod\"));\n  }\n\n  cameraMap Ks;\n  getCameraCalibration(rig, Ks);\n\n  if(Ks.size() != cam.NumChannels())\n  {\n    std::cout << \"Error: the number of cameras (\" << cam.NumChannels()\n              << \") differs from the number of models in the calibration file (\"\n              << Ks.size() << \")\" << std::endl;\n    exit(2);\n  }\n\n  const int w = cam.Width();\n  const int h = cam.Height();\n\n  ///----- Init aux variables and dense tracker.\n\n  const bool use_colour = false;\n\n  const int MaxLevels = 3;\n  const int its[] = {1,0,2,3};\n\n  //roo::ImageIntrinsics K(KL(0, 0),KL(1, 1), KL(0, 2), KL(1, 2) );\n  roo::ImageIntrinsics K = Ks.rbegin()->second.i;\n\n  const double knear = 0.01;\n  const double kfar = 4.0;\n\n  const float volrad = 2.0;\n  const int volres = 256;\n\n  roo::BoundingBox reset_bb(make_float3(-volrad,-volrad,knear), make_float3(volrad,volrad,knear+2*volrad));\n\n#ifdef HAVE_CVARS\n  CVarUtils::AttachCVar<roo::BoundingBox>(\"BoundingBox\", &reset_bb);\n#endif // HAVE_CVARS\n\n  // Camera (rgb) to depth\n  roo::Image<float, roo::TargetDevice, roo::Manage> dKinectMeters(w,h);\n  roo::Image<unsigned short, roo::TargetDevice, roo::Manage> dKinect(w,h);\n  roo::Pyramid<float, MaxLevels, roo::TargetDevice, roo::Manage> kin_d(w,h);\n  roo::Pyramid<float4, MaxLevels, roo::TargetDevice, roo::Manage> kin_v(w,h);\n  roo::Pyramid<float4, MaxLevels, roo::TargetDevice, roo::Manage> kin_n(w,h);\n  roo::Image<float4, roo::TargetDevice, roo::Manage>  dDebug(w,h);\n\n  roo::Pyramid<float, MaxLevels, roo::TargetDevice, roo::Manage> ray_i(w,h);\n  roo::Pyramid<float, MaxLevels, roo::TargetDevice, roo::Manage> ray_d(w,h);\n  roo::Pyramid<float4, MaxLevels, roo::TargetDevice, roo::Manage> ray_n(w,h);\n  roo::Pyramid<float4, MaxLevels, roo::TargetDevice, roo::Manage> ray_v(w,h);\n  roo::Pyramid<float4, MaxLevels, roo::TargetDevice, roo::Manage> ray_c(w,h);\n  roo::BoundedVolume<roo::SDF_t, roo::TargetDevice, roo::Manage> vol(volres,volres,volres,reset_bb);\n  roo::BoundedVolume<float, roo::TargetDevice, roo::Manage> colorVol(volres,volres,volres,reset_bb);\n\n  std::vector<std::unique_ptr<KinectKeyframe> > keyframes;\n  roo::Mat<roo::ImageKeyframe<uchar3>,10> kfs;\n\n  SceneGraph::GLSceneGraph glgraph;\n  SceneGraph::GLAxis glcamera(0.1);\n  SceneGraph::GLAxisAlignedBox glboxfrustum;\n  SceneGraph::GLAxisAlignedBox glboxvol;\n\n  glboxvol.SetBounds(roo::ToEigen(vol.bbox.Min()), roo::ToEigen(vol.bbox.Max()) );\n  glgraph.AddChild(&glcamera);\n  glgraph.AddChild(&glboxvol);\n  glgraph.AddChild(&glboxfrustum);\n\n  pangolin::OpenGlRenderState s_cam(\n        ProjectionMatrixRDF_TopLeft(w,h,K.fu,K.fv,K.u0,K.v0,0.1,1000),\n        ModelViewLookAtRDF(0,0,-2,0,0,0,0,-1,0)\n        );\n\n  Var<bool> reset(\"ui.reset\", true, false);\n  Var<bool> run(\"ui.run\", true, true);\n\n  Var<bool> viewonly(\"ui.view only\", true, true);\n  Var<bool> fuse(\"ui.fuse\", false, true);\n  Var<float> max_rmse(\"ui.Max RMSE\",0.10,0,0.5);\n  Var<float> rmse(\"ui.RMSE\",0);\n\n  Var<int> show_level(\"ui.Show Level\", 0, 0, MaxLevels-1);\n\n  // TODO: This needs to be a function of the inverse depth\n  Var<int>   biwin(\"ui.size\",3, 1, 20);      // Bilateral filter\n  Var<float> bigs(\"ui.gs\",1.5, 1E-3, 5);     // Bilateral filter\n  Var<float> icp_c(\"ui.icp c\",0.1, 1E-3, 1);\n  Var<float> bigr(\"ui.gr\",0.1, 1E-6, 0.2);   // Bilateral filter\n  roo::Image<unsigned char, roo::TargetDevice, roo::Manage> dScratch(w*sizeof(roo::LeastSquaresSystem<float,12>),h);\n  Var<float> trunc_dist_factor(\"ui.trunc vol factor\",2, 1, 4);\n\n  Var<float> max_w(\"ui.max w\", 1000, 1E-2, 1E3);\n  Var<float> mincostheta(\"ui.min cos theta\", 0.1, 0, 1);\n  Var<float> rgb_fl(\"ui.RGB focal length\", 535.7,400,600);\n\n  ActivateDrawPyramid<float,MaxLevels> adrayimg(ray_i, GL_LUMINANCE32F_ARB, true, true);\n  ActivateDrawPyramid<float4,MaxLevels> adraycolor(ray_c, GL_RGBA32F, true, true);\n  ActivateDrawPyramid<float4,MaxLevels> adraynorm(ray_n, GL_RGBA32F, true, true);\n  //    ActivateDrawPyramid<float,MaxLevels> addepth( kin_d, GL_LUMINANCE32F_ARB, false, true);\n  ActivateDrawPyramid<float4,MaxLevels> adnormals( kin_n, GL_RGBA32F_ARB, false, true);\n  ActivateDrawImage<float4> addebug( dDebug, GL_RGBA32F_ARB, false, true);\n\n  Handler3DDepth<float,roo::TargetDevice> rayhandler(ray_d[0], s_cam, AxisNone);\n  SetupContainer(container, 3, (float)w/h);\n  container[0].SetDrawFunction(std::ref(adrayimg))\n      .SetHandler(&rayhandler);\n  container[1].SetDrawFunction(SceneGraph::ActivateDrawFunctor(glgraph, s_cam))\n      .SetHandler( new Handler3D(s_cam, AxisNone) );\n  container[2].SetDrawFunction(std::ref(use_colour?adraycolor:adraynorm))\n      .SetHandler(&rayhandler);\n  //container[3].SetDrawFunction(std::ref(adnormals));\n\n  std::vector<SceneGraph::ImageView> depthViews(cam.NumChannels());\n  for(size_t i = 0; i < depthViews.size(); ++i)\n    container.AddDisplay( depthViews[i] );\n\n  Sophus::SE3d T_wl;\n\n  bool bStep = false;\n  pangolin::RegisterKeyPressCallback(' ', [&viewonly]() { viewonly=!viewonly;} );\n  pangolin::RegisterKeyPressCallback('l', [&vol,&viewonly]() {LoadPXM(\"save.vol\", vol); viewonly = true;} );\n  //    pangolin::RegisterKeyPressCallback('s', [&vol,&colorVol,&keyframes,&rgb_fl,w,h]() {SavePXM(\"save.vol\", vol); SaveMeshlab(vol,keyframes,rgb_fl,rgb_fl,w/2,h/2); } );\n  pangolin::RegisterKeyPressCallback('s', [&vol,&colorVol]() {roo::SaveMesh(\"mesh\",vol,colorVol); } );\n  pangolin::RegisterKeyPressCallback('/', [&]() {bStep = !bStep; } );\n  //    pangolin::RegisterKeyPressCallback('s', [&vol]() {SavePXM(\"save.vol\", vol); } );\n\n  reset = true;\n\n  for(long frame=-1; !pangolin::ShouldQuit();)\n  {\n    const float trunc_dist = trunc_dist_factor*length(vol.VoxelSizeUnits());\n\n    if(pangolin::Pushed(reset)) {\n      vol.bbox = reset_bb;\n      roo::SdfReset(vol, std::numeric_limits<float>::quiet_NaN() );\n      keyframes.clear();\n      frame = -1;\n    }\n\n    if(run)\n    {\n      cam.Capture( *vImages );\n      setDepthImages(vImages, depthViews);\n\n      Sophus::SE3d T_vw(s_cam.GetModelViewMatrix());\n      if(viewonly) {\n\n        const roo::BoundingBox roi(T_vw.inverse().matrix3x4(), w, h, K, 0, 50);\n        roo::BoundedVolume<roo::SDF_t> work_vol = vol.SubBoundingVolume( roi );\n        if(work_vol.IsValid()) {\n          roo::RaycastSdf(ray_d[0], ray_n[0], ray_i[0], work_vol, T_vw.inverse().matrix3x4(), K, 0.1, 50, trunc_dist, true );\n\n          if(keyframes.size() > 0) {\n            // populate kfs\n            for( int k=0; k< kfs.Rows(); k++)\n            {\n              if(k < keyframes.size()) {\n                kfs[k].img = keyframes[k]->img;\n                kfs[k].T_iw = keyframes[k]->T_iw.matrix3x4();\n                kfs[k].K = roo::ImageIntrinsics(rgb_fl, kfs[k].img);\n              }else{\n                kfs[k].img.ptr = 0;\n              }\n            }\n            roo::TextureDepth<float4,uchar3,10>(ray_c[0], kfs, ray_d[0], ray_n[0], ray_i[0], T_vw.inverse().matrix3x4(), K);\n          }\n        }\n      }else{\n        const roo::BoundingBox roi(roo::BoundingBox(T_wl.inverse().matrix3x4(), w, h, K, 0, 50));\n        roo::BoundedVolume<roo::SDF_t> work_vol = vol.SubBoundingVolume( roi );\n        if(work_vol.IsValid()) {\n          for(int l=0; l<MaxLevels; ++l) {\n            if(its[l] > 0) {\n              const roo::ImageIntrinsics Kl = K[l];\n              roo::RaycastSdf(ray_d[l], ray_n[l], ray_i[l], work_vol, T_vw.inverse().matrix3x4(), Kl, knear,kfar, trunc_dist, true );\n              roo::DepthToVbo<float>(ray_v[l], ray_d[l], Kl );\n            }\n          }\n\n          if(fuse) {\n            for (int ii = 0; ii < vImages->Size(); ii++) {\n\n              // Transfer the captured image to the device\n              copyFrom(vImages->at(ii), dKinect);\n\n              roo::ElementwiseScaleBias<float,unsigned short,float>(dKinectMeters, dKinect, 1.0f/1000.0f);  // OpenNI outputs in millimeters\n              roo::BilateralFilter<float,float>(kin_d[0],dKinectMeters,bigs,bigr,biwin,0.2);\n\n              roo::BoxReduceIgnoreInvalid<float,MaxLevels,float>(kin_d);\n              for(int l=0; l<MaxLevels; ++l) {\n                roo::DepthToVbo<float>(kin_v[l], kin_d[l], K[l] );\n                roo::NormalsFromVbo(kin_n[l], kin_v[l]);\n              }\n\n              // Set Image Intrinsics for this particular camera\n              assert(Ks.find(vImages->at(ii)->SerialNumber()) != Ks.end());\n              K = Ks[ vImages->at(ii)->SerialNumber() ].i;\n\n              // Set the pose relative to the rig and then to the\n              // frame of the SDF.\n              Sophus::SE3d tempPose = Ks[ vImages->at(ii)->SerialNumber() ].p;\n\n              const roo::BoundingBox roi(tempPose.matrix3x4(), w, h, K, knear,kfar);\n              roo::BoundedVolume<roo::SDF_t> work_vol = vol.SubBoundingVolume( roi );\n              if(work_vol.IsValid()) {\n                const float trunc_dist = trunc_dist_factor*length(vol.VoxelSizeUnits());\n                roo::SdfFuse(work_vol, kin_d[0], kin_n[0], tempPose.inverse().matrix3x4(), K, trunc_dist, max_w, mincostheta );\n              }\n            }\n          } // if fuse\n        } // if work vol is valid\n      } // if !view only\n    } // if run\n\n    glcamera.SetPose(T_wl.matrix());\n\n    roo::BoundingBox bbox_work(T_wl.matrix3x4(), w, h, K.fu, K.fv, K.u0, K.v0, knear,kfar);\n    bbox_work.Intersect(vol.bbox);\n    glboxfrustum.SetBounds(roo::ToEigen(bbox_work.Min()), roo::ToEigen(bbox_work.Max()) );\n\n    /////////////////////////////////////////////////////////////\n    // Draw\n    addebug.SetImage(dDebug.SubImage(0,0,w>>show_level,h>>show_level));\n    adnormals.SetLevel(show_level);\n    adrayimg.SetLevel(viewonly? 0 : show_level);\n\n    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n    glColor3f(1,1,1);\n    pangolin::FinishFrame();\n  }\n  return 0;\n}\n\nvoid getCameraCalibration(const calibu::CameraRig &rig,\n                          cameraMap& Ks)\n{\n  Ks.clear();\n  for (int ii = 0; ii < rig.cameras.size(); ii++ ){\n    Eigen::Matrix3d KL = rig.cameras[ii].camera.K();\n    pni temp;\n    roo::ImageIntrinsics temp_i(KL(0, 0),KL(1, 1), KL(0, 2), KL(1, 2) );\n    temp.i = temp_i;\n    temp.p = rig.cameras[ii].T_wc;\n    Ks.insert( std::pair<uint64_t, pni >(rig.cameras[ii].camera.SerialNumber() , temp ) );\n  }\n}\n\nvoid copyFrom(const std::shared_ptr<pb::Image>& pbim,\n              roo::Image<unsigned short, roo::TargetDevice, roo::Manage>& kim)\n{\n  cv::Mat mat;\n  if(pbim->Type() == pb::PB_UNSIGNED_SHORT)\n    mat = pbim->Mat();\n  else if(pbim->Type() == pb::PB_FLOAT)\n  {\n    cv::Mat src = pbim->Mat();\n    src.convertTo(mat, CV_16U);\n  }\n  else\n  {\n    std::cerr << \"Unsupported type of image\" << std::endl;\n    exit(1);\n  }\n  kim.CopyFrom(roo::Image<unsigned short, roo::TargetHost>\n               (mat.ptr<unsigned short>(), mat.cols, mat.rows,\n                mat.cols * sizeof(unsigned short)));\n}\n\nvoid setDepthImages(const std::shared_ptr<pb::ImageArray>& pbims,\n                    std::vector<SceneGraph::ImageView>& views)\n{\n  for(int i = 0; i < pbims->Size(); ++i) {\n    views[i].SetImage(pbims->at(i)->data(), pbims->at(i)->Width(),\n                      pbims->at(i)->Height(),\n                      GL_LUMINANCE, GL_LUMINANCE, GL_FLOAT, true);\n    views[i].UpdateGlTexture();\n  }\n}\n", "meta": {"hexsha": "601abf27e79d8f42192c6161d4b5db7b2283993c", "size": 13462, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SingleTest/main.cpp", "max_stars_repo_name": "arpg/D-MoCap", "max_stars_repo_head_hexsha": "e560ee8c8dc6ccd97d065d170d983eb481277dd9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-03-07T13:01:21.000Z", "max_stars_repo_stars_event_max_datetime": "2016-07-01T19:15:36.000Z", "max_issues_repo_path": "SingleTest/main.cpp", "max_issues_repo_name": "arpg/D-MoCap", "max_issues_repo_head_hexsha": "e560ee8c8dc6ccd97d065d170d983eb481277dd9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SingleTest/main.cpp", "max_forks_repo_name": "arpg/D-MoCap", "max_forks_repo_head_hexsha": "e560ee8c8dc6ccd97d065d170d983eb481277dd9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2015-05-14T13:40:04.000Z", "max_forks_repo_forks_event_max_datetime": "2017-07-24T13:10:59.000Z", "avg_line_length": 38.1359773371, "max_line_length": 171, "alphanum_fraction": 0.6348982321, "num_tokens": 4175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.45094662648072126}}
{"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\u00e4nkt), 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_GAUSS_SEIDEL_INCLUDE\n#define ITL_GAUSS_SEIDEL_INCLUDE\n\n#include <boost/assert.hpp>\n#include <boost/numeric/mtl/concept/collection.hpp>\n#include <boost/numeric/mtl/utility/exception.hpp>\n#include <boost/numeric/mtl/utility/is_row_major.hpp>\n#include <boost/numeric/mtl/utility/property_map.hpp>\n#include <boost/numeric/mtl/utility/range_generator.hpp>\n#include <boost/numeric/mtl/utility/tag.hpp>\n#include <boost/numeric/mtl/matrix/compressed2D.hpp>\n#include <boost/numeric/mtl/interface/vpt.hpp>\n\nnamespace itl {\n\n/// Gauss-Seidel smoother\n/** Constructor takes references to a matrix and a right-hand side vector.\n    operator() is applied on a vector and changes it in place. \n    Matrix must be square, stored row-major and free of zero entries in the diagonal.\n    Vectors b and x must have the same number of rows as A. \n**/\ntemplate <typename Matrix>\nclass gauss_seidel\n{\n    typedef typename mtl::Collection<Matrix>::value_type Scalar;\n    typedef typename mtl::Collection<Matrix>::size_type  size_type;\n  public:\n    /// Construct with constant references to matrix and RHS vector\n    gauss_seidel(const Matrix& A) : A(A), dia_inv(num_rows(A)) \n    {\n\tBOOST_STATIC_ASSERT((mtl::traits::is_row_major<Matrix>::value)); // No CCS\n\tassert(num_rows(A) == num_cols(A)); // Matrix must be square\n\tfor (size_type i= 0; i < num_rows(A); ++i) {\n\t    Scalar a= A[i][i];\n\t    MTL_THROW_IF(a == 0, mtl::missing_diagonal());\n\t    dia_inv[i]= 1.0 / a;\n\t}\n    }\n\n    /// Apply Gauss-Seidel on vector \\p x, i.e. \\p x is changed\n    template <typename Vector, typename RHSVector>\n    Vector& operator()(Vector& x, const RHSVector& b) const\n    {\n\tmtl::vampir_trace<8551> tracer;\n\tnamespace tag= mtl::tag; using namespace mtl::traits;\n\tusing mtl::begin; using mtl::end; \n\n        typedef typename range_generator<tag::row, Matrix>::type       a_cur_type;             \n        typedef typename range_generator<tag::nz, a_cur_type>::type    a_icur_type;            \n\ttypename col<Matrix>::type                   col_a(A); \n\ttypename const_value<Matrix>::type           value_a(A); \n\n\ttypedef typename mtl::Collection<Vector>::value_type           value_type;\n\n\ta_cur_type ac= begin<tag::row>(A), aend= end<tag::row>(A);\n\tfor (unsigned i= 0; ac != aend; ++ac, ++i) {\n\t    value_type tmp= b[i];\n\t    for (a_icur_type aic= begin<tag::nz>(ac), aiend= end<tag::nz>(ac); aic != aiend; ++aic) \n\t\tif (col_a(*aic) != i)\n\t\t    tmp-= value_a(*aic) * x[col_a(*aic)];\t\n\t    x[i]= dia_inv[i] * tmp;\n\t}\n \treturn x;\n    }\n\n   private:\n    const Matrix&    A;\n    mtl::dense_vector<Scalar>  dia_inv;\n};\n\n \ntemplate <typename Value, typename Parameters>\nclass gauss_seidel<mtl::mat::compressed2D<Value, Parameters> >\n{\n    typedef mtl::mat::compressed2D<Value, Parameters> Matrix;\n    typedef typename mtl::Collection<Matrix>::value_type Scalar;\n    typedef typename mtl::Collection<Matrix>::size_type  size_type;\n  public:\n    /// Construct with constant references to matrix and RHS vector\n    gauss_seidel(const Matrix& A) \n      : A(A), dia_inv(num_rows(A)), dia_pos(num_rows(A))\n    {\n\tBOOST_STATIC_ASSERT((mtl::traits::is_row_major<Matrix>::value)); // No CCS\n\tassert(num_rows(A) == num_cols(A)); // Matrix must be square\n\tfor (size_type i= 0; i < num_rows(A); ++i) {\n\t    mtl::utilities::maybe<size_type> pos = A.indexer(A, i, i);\n\t    MTL_THROW_IF(!pos, mtl::missing_diagonal());\n\t    dia_inv[i]= 1.0 / A.value_from_offset(pos);\n\t    dia_pos[i]= pos;\n\t}\n    }\n\n    /// Apply Gauss-Seidel on vector \\p x, i.e. \\p x is changed\n    template <typename Vector, typename RHSVector>\n    Vector& operator()(Vector& x, const RHSVector& b) const\n    {\n\tmtl::vampir_trace<8551> tracer;\n\ttypedef typename mtl::Collection<Vector>::value_type           value_type;\n\ttypedef typename mtl::Collection<Matrix>::size_type            size_type; \n\tconst size_type nr= num_rows(A);\n\tsize_type cj1= A.ref_major()[0];\n\tfor (size_type i= 0; i < nr; ++i) {\n\t    value_type tmp= b[i];\n\t    size_type cj0= cj1, cjm= dia_pos[i];\n\t    cj1= A.ref_major()[i+1];\n\t    for (; cj0 < cjm; cj0++)\n\t\ttmp-= A.data[cj0] * x[A.ref_minor()[cj0]];\n\t    for (size_type j= cjm+1; j < cj1; j++)\n\t\ttmp-= A.data[j] * x[A.ref_minor()[j]];\n\t    x[i]= dia_inv[i] * tmp; \n\t}\t\n \treturn x;\n    }\n\n\n  private:\n    const Matrix&    A;\n    mtl::dense_vector<Scalar>     dia_inv;\n    mtl::dense_vector<size_type>  dia_pos;\n};\n\n\n} // namespace itl\n\n#endif // ITL_GAUSS_SEIDEL_INCLUDE\n", "meta": {"hexsha": "c8f8ac4016677ef29b7760e86ee1e64ded6fbd81", "size": 4861, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/itl/smoother/gauss_seidel.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/smoother/gauss_seidel.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/smoother/gauss_seidel.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.2246376812, "max_line_length": 95, "alphanum_fraction": 0.6663238017, "num_tokens": 1368, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.45084056272560613}}
{"text": "/*\n    MIT License\n\n    Copyright (c) 2021 Zhepei Wang (wangzhepei@live.com)\n\n    Permission is hereby granted, free of charge, to any person obtaining a copy\n    of this software and associated documentation files (the \"Software\"), to deal\n    in the Software without restriction, including without limitation the rights\n    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n    copies of the Software, and to permit persons to whom the Software is\n    furnished to do so, subject to the following conditions:\n\n    The above copyright notice and this permission notice shall be included in all\n    copies or substantial portions of the Software.\n\n    THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n    SOFTWARE.\n*/\n\n#ifndef GCOPTER_HPP\n#define GCOPTER_HPP\n\n#include \"gcopter/minco.hpp\"\n#include \"gcopter/flatness.hpp\"\n#include \"gcopter/lbfgs.hpp\"\n\n#include <Eigen/Eigen>\n\n#include <cmath>\n#include <cfloat>\n#include <iostream>\n#include <vector>\n\nnamespace gcopter\n{\n\n    class GCOPTER_PolytopeSFC\n    {\n    public:\n        typedef Eigen::Matrix3Xd PolyhedronV;\n        typedef Eigen::MatrixX4d PolyhedronH;\n        typedef std::vector<PolyhedronV> PolyhedraV;\n        typedef std::vector<PolyhedronH> PolyhedraH;\n\n    private:\n        minco::MINCO_S3NU minco;\n        flatness::FlatnessMap flatmap;\n\n        double rho;\n        Eigen::Matrix3d headPVA;\n        Eigen::Matrix3d tailPVA;\n\n        PolyhedraV vPolytopes;\n        PolyhedraH hPolytopes;\n        Eigen::Matrix3Xd shortPath;\n\n        Eigen::VectorXi pieceIdx;\n        Eigen::VectorXi vPolyIdx;\n        Eigen::VectorXi hPolyIdx;\n\n        int polyN;\n        int pieceN;\n\n        int spatialDim;\n        int temporalDim;\n\n        double smoothEps;\n        int integralRes;\n        Eigen::VectorXd magnitudeBd;\n        Eigen::VectorXd penaltyWt;\n        Eigen::VectorXd physicalPm;\n        double allocSpeed;\n\n        lbfgs::lbfgs_parameter_t lbfgs_params;\n\n        Eigen::Matrix3Xd points;\n        Eigen::VectorXd times;\n        Eigen::Matrix3Xd gradByPoints;\n        Eigen::VectorXd gradByTimes;\n        Eigen::MatrixX3d partialGradByCoeffs;\n        Eigen::VectorXd partialGradByTimes;\n\n    private:\n        static inline void forwardT(const Eigen::VectorXd &tau,\n                                    Eigen::VectorXd &T)\n        {\n            const int sizeTau = tau.size();\n            T.resize(sizeTau);\n            for (int i = 0; i < sizeTau; i++)\n            {\n                T(i) = tau(i) > 0.0\n                           ? ((0.5 * tau(i) + 1.0) * tau(i) + 1.0)\n                           : 1.0 / ((0.5 * tau(i) - 1.0) * tau(i) + 1.0);\n            }\n            return;\n        }\n\n        template <typename EIGENVEC>\n        static inline void backwardT(const Eigen::VectorXd &T,\n                                     EIGENVEC &tau)\n        {\n            const int sizeT = T.size();\n            tau.resize(sizeT);\n            for (int i = 0; i < sizeT; i++)\n            {\n                tau(i) = T(i) > 1.0\n                             ? (sqrt(2.0 * T(i) - 1.0) - 1.0)\n                             : (1.0 - sqrt(2.0 / T(i) - 1.0));\n            }\n\n            return;\n        }\n\n        template <typename EIGENVEC>\n        static inline void backwardGradT(const Eigen::VectorXd &tau,\n                                         const Eigen::VectorXd &gradT,\n                                         EIGENVEC &gradTau)\n        {\n            const int sizeTau = tau.size();\n            gradTau.resize(sizeTau);\n            double denSqrt;\n            for (int i = 0; i < sizeTau; i++)\n            {\n                if (tau(i) > 0)\n                {\n                    gradTau(i) = gradT(i) * (tau(i) + 1.0);\n                }\n                else\n                {\n                    denSqrt = (0.5 * tau(i) - 1.0) * tau(i) + 1.0;\n                    gradTau(i) = gradT(i) * (1.0 - tau(i)) / (denSqrt * denSqrt);\n                }\n            }\n\n            return;\n        }\n\n        static inline void forwardP(const Eigen::VectorXd &xi,\n                                    const Eigen::VectorXi &vIdx,\n                                    const PolyhedraV &vPolys,\n                                    Eigen::Matrix3Xd &P)\n        {\n            const int sizeP = vIdx.size();\n            P.resize(3, sizeP);\n            Eigen::VectorXd q;\n            for (int i = 0, j = 0, k, l; i < sizeP; i++, j += k)\n            {\n                l = vIdx(i);\n                k = vPolys[l].cols();\n                q = xi.segment(j, k).normalized().head(k - 1);\n                P.col(i) = vPolys[l].rightCols(k - 1) * q.cwiseProduct(q) +\n                           vPolys[l].col(0);\n            }\n            return;\n        }\n\n        static inline double costTinyNLS(void *ptr,\n                                         const Eigen::VectorXd &xi,\n                                         Eigen::VectorXd &gradXi)\n        {\n            const int n = xi.size();\n            const Eigen::Matrix3Xd &ovPoly = *(Eigen::Matrix3Xd *)ptr;\n\n            const double sqrNormXi = xi.squaredNorm();\n            const double invNormXi = 1.0 / sqrt(sqrNormXi);\n            const Eigen::VectorXd unitXi = xi * invNormXi;\n            const Eigen::VectorXd r = unitXi.head(n - 1);\n            const Eigen::Vector3d delta = ovPoly.rightCols(n - 1) * r.cwiseProduct(r) +\n                                          ovPoly.col(1) - ovPoly.col(0);\n\n            double cost = delta.squaredNorm();\n            gradXi.head(n - 1) = (ovPoly.rightCols(n - 1).transpose() * (2 * delta)).array() *\n                                 r.array() * 2.0;\n            gradXi(n - 1) = 0.0;\n            gradXi = (gradXi - unitXi.dot(gradXi) * unitXi).eval() * invNormXi;\n\n            const double sqrNormViolation = sqrNormXi - 1.0;\n            if (sqrNormViolation > 0.0)\n            {\n                double c = sqrNormViolation * sqrNormViolation;\n                const double dc = 3.0 * c;\n                c *= sqrNormViolation;\n                cost += c;\n                gradXi += dc * 2.0 * xi;\n            }\n\n            return cost;\n        }\n\n        template <typename EIGENVEC>\n        static inline void backwardP(const Eigen::Matrix3Xd &P,\n                                     const Eigen::VectorXi &vIdx,\n                                     const PolyhedraV &vPolys,\n                                     EIGENVEC &xi)\n        {\n            const int sizeP = P.cols();\n\n            double minSqrD;\n            lbfgs::lbfgs_parameter_t tiny_nls_params;\n            tiny_nls_params.past = 0;\n            tiny_nls_params.delta = 1.0e-5;\n            tiny_nls_params.g_epsilon = FLT_EPSILON;\n            tiny_nls_params.max_iterations = 128;\n\n            Eigen::Matrix3Xd ovPoly;\n            for (int i = 0, j = 0, k, l; i < sizeP; i++, j += k)\n            {\n                l = vIdx(i);\n                k = vPolys[l].cols();\n\n                ovPoly.resize(3, k + 1);\n                ovPoly.col(0) = P.col(i);\n                ovPoly.rightCols(k) = vPolys[l];\n                Eigen::VectorXd x(k);\n                x.setConstant(sqrt(1.0 / k));\n                lbfgs::lbfgs_optimize(x,\n                                      minSqrD,\n                                      &GCOPTER_PolytopeSFC::costTinyNLS,\n                                      nullptr,\n                                      nullptr,\n                                      &ovPoly,\n                                      tiny_nls_params);\n\n                xi.segment(j, k) = x;\n            }\n\n            return;\n        }\n\n        template <typename EIGENVEC>\n        static inline void backwardGradP(const Eigen::VectorXd &xi,\n                                         const Eigen::VectorXi &vIdx,\n                                         const PolyhedraV &vPolys,\n                                         const Eigen::Matrix3Xd &gradP,\n                                         EIGENVEC &gradXi)\n        {\n            const int sizeP = vIdx.size();\n            gradXi.resize(xi.size());\n\n            double normInv;\n            Eigen::VectorXd q, gradQ, unitQ;\n            for (int i = 0, j = 0, k, l; i < sizeP; i++, j += k)\n            {\n                l = vIdx(i);\n                k = vPolys[l].cols();\n                q = xi.segment(j, k);\n                normInv = 1.0 / q.norm();\n                unitQ = q * normInv;\n                gradQ.resize(k);\n                gradQ.head(k - 1) = (vPolys[l].rightCols(k - 1).transpose() * gradP.col(i)).array() *\n                                    unitQ.head(k - 1).array() * 2.0;\n                gradQ(k - 1) = 0.0;\n                gradXi.segment(j, k) = (gradQ - unitQ * unitQ.dot(gradQ)) * normInv;\n            }\n\n            return;\n        }\n\n        template <typename EIGENVEC>\n        static inline void normRetrictionLayer(const Eigen::VectorXd &xi,\n                                               const Eigen::VectorXi &vIdx,\n                                               const PolyhedraV &vPolys,\n                                               double &cost,\n                                               EIGENVEC &gradXi)\n        {\n            const int sizeP = vIdx.size();\n            gradXi.resize(xi.size());\n\n            double sqrNormQ, sqrNormViolation, c, dc;\n            Eigen::VectorXd q;\n            for (int i = 0, j = 0, k; i < sizeP; i++, j += k)\n            {\n                k = vPolys[vIdx(i)].cols();\n\n                q = xi.segment(j, k);\n                sqrNormQ = q.squaredNorm();\n                sqrNormViolation = sqrNormQ - 1.0;\n                if (sqrNormViolation > 0.0)\n                {\n                    c = sqrNormViolation * sqrNormViolation;\n                    dc = 3.0 * c;\n                    c *= sqrNormViolation;\n                    cost += c;\n                    gradXi.segment(j, k) += dc * 2.0 * q;\n                }\n            }\n\n            return;\n        }\n\n        static inline bool smoothedL1(const double &x,\n                                      const double &mu,\n                                      double &f,\n                                      double &df)\n        {\n            if (x < 0.0)\n            {\n                return false;\n            }\n            else if (x > mu)\n            {\n                f = x - 0.5 * mu;\n                df = 1.0;\n                return true;\n            }\n            else\n            {\n                const double xdmu = x / mu;\n                const double sqrxdmu = xdmu * xdmu;\n                const double mumxd2 = mu - 0.5 * x;\n                f = mumxd2 * sqrxdmu * xdmu;\n                df = sqrxdmu * ((-0.5) * xdmu + 3.0 * mumxd2 / mu);\n                return true;\n            }\n        }\n\n        // magnitudeBounds = [v_max, omg_max, theta_max, thrust_min, thrust_max]^T\n        // penaltyWeights = [pos_weight, vel_weight, omg_weight, theta_weight, thrust_weight]^T\n        // physicalParams = [vehicle_mass, gravitational_acceleration, horitonral_drag_coeff,\n        //                   vertical_drag_coeff, parasitic_drag_coeff, speed_smooth_factor]^T\n        static inline void attachPenaltyFunctional(const Eigen::VectorXd &T,\n                                                   const Eigen::MatrixX3d &coeffs,\n                                                   const Eigen::VectorXi &hIdx,\n                                                   const PolyhedraH &hPolys,\n                                                   const double &smoothFactor,\n                                                   const int &integralResolution,\n                                                   const Eigen::VectorXd &magnitudeBounds,\n                                                   const Eigen::VectorXd &penaltyWeights,\n                                                   flatness::FlatnessMap &flatMap,\n                                                   double &cost,\n                                                   Eigen::VectorXd &gradT,\n                                                   Eigen::MatrixX3d &gradC)\n        {\n            const double velSqrMax = magnitudeBounds(0) * magnitudeBounds(0);\n            const double omgSqrMax = magnitudeBounds(1) * magnitudeBounds(1);\n            const double thetaMax = magnitudeBounds(2);\n            const double thrustMean = 0.5 * (magnitudeBounds(3) + magnitudeBounds(4));\n            const double thrustRadi = 0.5 * fabs(magnitudeBounds(4) - magnitudeBounds(3));\n            const double thrustSqrRadi = thrustRadi * thrustRadi;\n\n            const double weightPos = penaltyWeights(0);\n            const double weightVel = penaltyWeights(1);\n            const double weightOmg = penaltyWeights(2);\n            const double weightTheta = penaltyWeights(3);\n            const double weightThrust = penaltyWeights(4);\n\n            Eigen::Vector3d pos, vel, acc, jer, sna;\n            Eigen::Vector3d totalGradPos, totalGradVel, totalGradAcc, totalGradJer;\n            double totalGradPsi, totalGradPsiD;\n            double thr, cos_theta;\n            Eigen::Vector4d quat;\n            Eigen::Vector3d omg;\n            double gradThr;\n            Eigen::Vector4d gradQuat;\n            Eigen::Vector3d gradPos, gradVel, gradOmg;\n\n            double step, alpha;\n            double s1, s2, s3, s4, s5;\n            Eigen::Matrix<double, 6, 1> beta0, beta1, beta2, beta3, beta4;\n            Eigen::Vector3d outerNormal;\n            int K, L;\n            double violaPos, violaVel, violaOmg, violaTheta, violaThrust;\n            double violaPosPenaD, violaVelPenaD, violaOmgPenaD, violaThetaPenaD, violaThrustPenaD;\n            double violaPosPena, violaVelPena, violaOmgPena, violaThetaPena, violaThrustPena;\n            double node, pena;\n\n            const int pieceNum = T.size();\n            const double integralFrac = 1.0 / integralResolution;\n            for (int i = 0; i < pieceNum; i++)\n            {\n                const Eigen::Matrix<double, 6, 3> &c = coeffs.block<6, 3>(i * 6, 0);\n                step = T(i) * integralFrac;\n                for (int j = 0; j <= integralResolution; j++)\n                {\n                    s1 = j * step;\n                    s2 = s1 * s1;\n                    s3 = s2 * s1;\n                    s4 = s2 * s2;\n                    s5 = s4 * s1;\n                    beta0(0) = 1.0, beta0(1) = s1, beta0(2) = s2, beta0(3) = s3, beta0(4) = s4, beta0(5) = s5;\n                    beta1(0) = 0.0, beta1(1) = 1.0, beta1(2) = 2.0 * s1, beta1(3) = 3.0 * s2, beta1(4) = 4.0 * s3, beta1(5) = 5.0 * s4;\n                    beta2(0) = 0.0, beta2(1) = 0.0, beta2(2) = 2.0, beta2(3) = 6.0 * s1, beta2(4) = 12.0 * s2, beta2(5) = 20.0 * s3;\n                    beta3(0) = 0.0, beta3(1) = 0.0, beta3(2) = 0.0, beta3(3) = 6.0, beta3(4) = 24.0 * s1, beta3(5) = 60.0 * s2;\n                    beta4(0) = 0.0, beta4(1) = 0.0, beta4(2) = 0.0, beta4(3) = 0.0, beta4(4) = 24.0, beta4(5) = 120.0 * s1;\n                    pos = c.transpose() * beta0;\n                    vel = c.transpose() * beta1;\n                    acc = c.transpose() * beta2;\n                    jer = c.transpose() * beta3;\n                    sna = c.transpose() * beta4;\n\n                    flatMap.forward(vel, acc, jer, 0.0, 0.0, thr, quat, omg);\n\n                    violaVel = vel.squaredNorm() - velSqrMax;\n                    violaOmg = omg.squaredNorm() - omgSqrMax;\n                    cos_theta = 1.0 - 2.0 * (quat(1) * quat(1) + quat(2) * quat(2));\n                    violaTheta = acos(cos_theta) - thetaMax;\n                    violaThrust = (thr - thrustMean) * (thr - thrustMean) - thrustSqrRadi;\n\n                    gradThr = 0.0;\n                    gradQuat.setZero();\n                    gradPos.setZero(), gradVel.setZero(), gradOmg.setZero();\n                    pena = 0.0;\n\n                    L = hIdx(i);\n                    K = hPolys[L].rows();\n                    for (int k = 0; k < K; k++)\n                    {\n                        outerNormal = hPolys[L].block<1, 3>(k, 0);\n                        violaPos = outerNormal.dot(pos) + hPolys[L](k, 3);\n                        if (smoothedL1(violaPos, smoothFactor, violaPosPena, violaPosPenaD))\n                        {\n                            gradPos += weightPos * violaPosPenaD * outerNormal;\n                            pena += weightPos * violaPosPena;\n                        }\n                    }\n\n                    if (smoothedL1(violaVel, smoothFactor, violaVelPena, violaVelPenaD))\n                    {\n                        gradVel += weightVel * violaVelPenaD * 2.0 * vel;\n                        pena += weightVel * violaVelPena;\n                    }\n\n                    if (smoothedL1(violaOmg, smoothFactor, violaOmgPena, violaOmgPenaD))\n                    {\n                        gradOmg += weightOmg * violaOmgPenaD * 2.0 * omg;\n                        pena += weightOmg * violaOmgPena;\n                    }\n\n                    if (smoothedL1(violaTheta, smoothFactor, violaThetaPena, violaThetaPenaD))\n                    {\n                        gradQuat += weightTheta * violaThetaPenaD /\n                                    sqrt(1.0 - cos_theta * cos_theta) * 4.0 *\n                                    Eigen::Vector4d(0.0, quat(1), quat(2), 0.0);\n                        pena += weightTheta * violaThetaPena;\n                    }\n\n                    if (smoothedL1(violaThrust, smoothFactor, violaThrustPena, violaThrustPenaD))\n                    {\n                        gradThr += weightThrust * violaThrustPenaD * 2.0 * (thr - thrustMean);\n                        pena += weightThrust * violaThrustPena;\n                    }\n\n                    flatMap.backward(gradPos, gradVel, gradThr, gradQuat, gradOmg,\n                                     totalGradPos, totalGradVel, totalGradAcc, totalGradJer,\n                                     totalGradPsi, totalGradPsiD);\n\n                    node = (j == 0 || j == integralResolution) ? 0.5 : 1.0;\n                    alpha = j * integralFrac;\n                    gradC.block<6, 3>(i * 6, 0) += (beta0 * totalGradPos.transpose() +\n                                                    beta1 * totalGradVel.transpose() +\n                                                    beta2 * totalGradAcc.transpose() +\n                                                    beta3 * totalGradJer.transpose()) *\n                                                   node * step;\n                    gradT(i) += (totalGradPos.dot(vel) +\n                                 totalGradVel.dot(acc) +\n                                 totalGradAcc.dot(jer) +\n                                 totalGradJer.dot(sna)) *\n                                    alpha * node * step +\n                                node * integralFrac * pena;\n                    cost += node * step * pena;\n                }\n            }\n\n            return;\n        }\n\n        static inline double costFunctional(void *ptr,\n                                            const Eigen::VectorXd &x,\n                                            Eigen::VectorXd &g)\n        {\n            GCOPTER_PolytopeSFC &obj = *(GCOPTER_PolytopeSFC *)ptr;\n            const int dimTau = obj.temporalDim;\n            const int dimXi = obj.spatialDim;\n            const double weightT = obj.rho;\n            Eigen::Map<const Eigen::VectorXd> tau(x.data(), dimTau);\n            Eigen::Map<const Eigen::VectorXd> xi(x.data() + dimTau, dimXi);\n            Eigen::Map<Eigen::VectorXd> gradTau(g.data(), dimTau);\n            Eigen::Map<Eigen::VectorXd> gradXi(g.data() + dimTau, dimXi);\n\n            forwardT(tau, obj.times);\n            forwardP(xi, obj.vPolyIdx, obj.vPolytopes, obj.points);\n\n            double cost;\n            obj.minco.setParameters(obj.points, obj.times);\n            obj.minco.getEnergy(cost);\n            obj.minco.getEnergyPartialGradByCoeffs(obj.partialGradByCoeffs);\n            obj.minco.getEnergyPartialGradByTimes(obj.partialGradByTimes);\n\n            attachPenaltyFunctional(obj.times, obj.minco.getCoeffs(),\n                                    obj.hPolyIdx, obj.hPolytopes,\n                                    obj.smoothEps, obj.integralRes,\n                                    obj.magnitudeBd, obj.penaltyWt, obj.flatmap,\n                                    cost, obj.partialGradByTimes, obj.partialGradByCoeffs);\n\n            obj.minco.propogateGrad(obj.partialGradByCoeffs, obj.partialGradByTimes,\n                                    obj.gradByPoints, obj.gradByTimes);\n\n            cost += weightT * obj.times.sum();\n            obj.gradByTimes.array() += weightT;\n\n            backwardGradT(tau, obj.gradByTimes, gradTau);\n            backwardGradP(xi, obj.vPolyIdx, obj.vPolytopes, obj.gradByPoints, gradXi);\n            normRetrictionLayer(xi, obj.vPolyIdx, obj.vPolytopes, cost, gradXi);\n\n            return cost;\n        }\n\n        static inline double costDistance(void *ptr,\n                                          const Eigen::VectorXd &xi,\n                                          Eigen::VectorXd &gradXi)\n        {\n            void **dataPtrs = (void **)ptr;\n            const double &dEps = *((const double *)(dataPtrs[0]));\n            const Eigen::Vector3d &ini = *((const Eigen::Vector3d *)(dataPtrs[1]));\n            const Eigen::Vector3d &fin = *((const Eigen::Vector3d *)(dataPtrs[2]));\n            const PolyhedraV &vPolys = *((PolyhedraV *)(dataPtrs[3]));\n\n            double cost = 0.0;\n            const int overlaps = vPolys.size() / 2;\n\n            Eigen::Matrix3Xd gradP = Eigen::Matrix3Xd::Zero(3, overlaps);\n            Eigen::Vector3d a, b, d;\n            Eigen::VectorXd r;\n            double smoothedDistance;\n            for (int i = 0, j = 0, k = 0; i <= overlaps; i++, j += k)\n            {\n                a = i == 0 ? ini : b;\n                if (i < overlaps)\n                {\n                    k = vPolys[2 * i + 1].cols();\n                    Eigen::Map<const Eigen::VectorXd> q(xi.data() + j, k);\n                    r = q.normalized().head(k - 1);\n                    b = vPolys[2 * i + 1].rightCols(k - 1) * r.cwiseProduct(r) +\n                        vPolys[2 * i + 1].col(0);\n                }\n                else\n                {\n                    b = fin;\n                }\n\n                d = b - a;\n                smoothedDistance = sqrt(d.squaredNorm() + dEps);\n                cost += smoothedDistance;\n\n                if (i < overlaps)\n                {\n                    gradP.col(i) += d / smoothedDistance;\n                }\n                if (i > 0)\n                {\n                    gradP.col(i - 1) -= d / smoothedDistance;\n                }\n            }\n\n            Eigen::VectorXd unitQ;\n            double sqrNormQ, invNormQ, sqrNormViolation, c, dc;\n            for (int i = 0, j = 0, k; i < overlaps; i++, j += k)\n            {\n                k = vPolys[2 * i + 1].cols();\n                Eigen::Map<const Eigen::VectorXd> q(xi.data() + j, k);\n                Eigen::Map<Eigen::VectorXd> gradQ(gradXi.data() + j, k);\n                sqrNormQ = q.squaredNorm();\n                invNormQ = 1.0 / sqrt(sqrNormQ);\n                unitQ = q * invNormQ;\n                gradQ.head(k - 1) = (vPolys[2 * i + 1].rightCols(k - 1).transpose() * gradP.col(i)).array() *\n                                    unitQ.head(k - 1).array() * 2.0;\n                gradQ(k - 1) = 0.0;\n                gradQ = (gradQ - unitQ * unitQ.dot(gradQ)).eval() * invNormQ;\n\n                sqrNormViolation = sqrNormQ - 1.0;\n                if (sqrNormViolation > 0.0)\n                {\n                    c = sqrNormViolation * sqrNormViolation;\n                    dc = 3.0 * c;\n                    c *= sqrNormViolation;\n                    cost += c;\n                    gradQ += dc * 2.0 * q;\n                }\n            }\n\n            return cost;\n        }\n\n        static inline void getShortestPath(const Eigen::Vector3d &ini,\n                                           const Eigen::Vector3d &fin,\n                                           const PolyhedraV &vPolys,\n                                           const double &smoothD,\n                                           Eigen::Matrix3Xd &path)\n        {\n            const int overlaps = vPolys.size() / 2;\n            Eigen::VectorXi vSizes(overlaps);\n            for (int i = 0; i < overlaps; i++)\n            {\n                vSizes(i) = vPolys[2 * i + 1].cols();\n            }\n            Eigen::VectorXd xi(vSizes.sum());\n            for (int i = 0, j = 0; i < overlaps; i++)\n            {\n                xi.segment(j, vSizes(i)).setConstant(sqrt(1.0 / vSizes(i)));\n                j += vSizes(i);\n            }\n\n            double minDistance;\n            void *dataPtrs[4];\n            dataPtrs[0] = (void *)(&smoothD);\n            dataPtrs[1] = (void *)(&ini);\n            dataPtrs[2] = (void *)(&fin);\n            dataPtrs[3] = (void *)(&vPolys);\n            lbfgs::lbfgs_parameter_t shortest_path_params;\n            shortest_path_params.past = 3;\n            shortest_path_params.delta = 1.0e-3;\n            shortest_path_params.g_epsilon = 1.0e-5;\n\n            lbfgs::lbfgs_optimize(xi,\n                                  minDistance,\n                                  &GCOPTER_PolytopeSFC::costDistance,\n                                  nullptr,\n                                  nullptr,\n                                  dataPtrs,\n                                  shortest_path_params);\n\n            path.resize(3, overlaps + 2);\n            path.leftCols<1>() = ini;\n            path.rightCols<1>() = fin;\n            Eigen::VectorXd r;\n            for (int i = 0, j = 0, k; i < overlaps; i++, j += k)\n            {\n                k = vPolys[2 * i + 1].cols();\n                Eigen::Map<const Eigen::VectorXd> q(xi.data() + j, k);\n                r = q.normalized().head(k - 1);\n                path.col(i + 1) = vPolys[2 * i + 1].rightCols(k - 1) * r.cwiseProduct(r) +\n                                  vPolys[2 * i + 1].col(0);\n            }\n\n            return;\n        }\n\n        static inline bool processCorridor(const PolyhedraH &hPs,\n                                           PolyhedraV &vPs)\n        {\n            const int sizeCorridor = hPs.size() - 1;\n\n            vPs.clear();\n            vPs.reserve(2 * sizeCorridor + 1);\n\n            int nv;\n            PolyhedronH curIH;\n            PolyhedronV curIV, curIOB;\n            for (int i = 0; i < sizeCorridor; i++)\n            {\n                if (!geo_utils::enumerateVs(hPs[i], curIV))\n                {\n                    return false;\n                }\n                nv = curIV.cols();\n                curIOB.resize(3, nv);\n                curIOB.col(0) = curIV.col(0);\n                curIOB.rightCols(nv - 1) = curIV.rightCols(nv - 1).colwise() - curIV.col(0);\n                vPs.push_back(curIOB);\n\n                curIH.resize(hPs[i].rows() + hPs[i + 1].rows(), 4);\n                curIH.topRows(hPs[i].rows()) = hPs[i];\n                curIH.bottomRows(hPs[i + 1].rows()) = hPs[i + 1];\n                if (!geo_utils::enumerateVs(curIH, curIV))\n                {\n                    return false;\n                }\n                nv = curIV.cols();\n                curIOB.resize(3, nv);\n                curIOB.col(0) = curIV.col(0);\n                curIOB.rightCols(nv - 1) = curIV.rightCols(nv - 1).colwise() - curIV.col(0);\n                vPs.push_back(curIOB);\n            }\n\n            if (!geo_utils::enumerateVs(hPs.back(), curIV))\n            {\n                return false;\n            }\n            nv = curIV.cols();\n            curIOB.resize(3, nv);\n            curIOB.col(0) = curIV.col(0);\n            curIOB.rightCols(nv - 1) = curIV.rightCols(nv - 1).colwise() - curIV.col(0);\n            vPs.push_back(curIOB);\n\n            return true;\n        }\n\n        static inline void setInitial(const Eigen::Matrix3Xd &path,\n                                      const double &speed,\n                                      const Eigen::VectorXi &intervalNs,\n                                      Eigen::Matrix3Xd &innerPoints,\n                                      Eigen::VectorXd &timeAlloc)\n        {\n            const int sizeM = intervalNs.size();\n            const int sizeN = intervalNs.sum();\n            innerPoints.resize(3, sizeN - 1);\n            timeAlloc.resize(sizeN);\n\n            Eigen::Vector3d a, b, c;\n            for (int i = 0, j = 0, k = 0, l; i < sizeM; i++)\n            {\n                l = intervalNs(i);\n                a = path.col(i);\n                b = path.col(i + 1);\n                c = (b - a) / l;\n                timeAlloc.segment(j, l).setConstant(c.norm() / speed);\n                j += l;\n                for (int m = 0; m < l; m++)\n                {\n                    if (i > 0 || m > 0)\n                    {\n                        innerPoints.col(k++) = a + c * m;\n                    }\n                }\n            }\n        }\n\n    public:\n        // magnitudeBounds = [v_max, omg_max, theta_max, thrust_min, thrust_max]^T\n        // penaltyWeights = [pos_weight, vel_weight, omg_weight, theta_weight, thrust_weight]^T\n        // physicalParams = [vehicle_mass, gravitational_acceleration, horitonral_drag_coeff,\n        //                   vertical_drag_coeff, parasitic_drag_coeff, speed_smooth_factor]^T\n        inline bool setup(const double &timeWeight,\n                          const Eigen::Matrix3d &initialPVA,\n                          const Eigen::Matrix3d &terminalPVA,\n                          const PolyhedraH &safeCorridor,\n                          const double &lengthPerPiece,\n                          const double &smoothingFactor,\n                          const int &integralResolution,\n                          const Eigen::VectorXd &magnitudeBounds,\n                          const Eigen::VectorXd &penaltyWeights,\n                          const Eigen::VectorXd &physicalParams)\n        {\n            rho = timeWeight;\n            headPVA = initialPVA;\n            tailPVA = terminalPVA;\n\n            hPolytopes = safeCorridor;\n            for (size_t i = 0; i < hPolytopes.size(); i++)\n            {\n                const Eigen::ArrayXd norms =\n                    hPolytopes[i].leftCols<3>().rowwise().norm();\n                hPolytopes[i].array().colwise() /= norms;\n            }\n            if (!processCorridor(hPolytopes, vPolytopes))\n            {\n                return false;\n            }\n\n            polyN = hPolytopes.size();\n            smoothEps = smoothingFactor;\n            integralRes = integralResolution;\n            magnitudeBd = magnitudeBounds;\n            penaltyWt = penaltyWeights;\n            physicalPm = physicalParams;\n            allocSpeed = magnitudeBd(0) * 3.0;\n\n            getShortestPath(headPVA.col(0), tailPVA.col(0),\n                            vPolytopes, smoothEps, shortPath);\n            const Eigen::Matrix3Xd deltas = shortPath.rightCols(polyN) - shortPath.leftCols(polyN);\n            pieceIdx = (deltas.colwise().norm() / lengthPerPiece).cast<int>().transpose();\n            pieceIdx.array() += 1;\n            pieceN = pieceIdx.sum();\n\n            temporalDim = pieceN;\n            spatialDim = 0;\n            vPolyIdx.resize(pieceN - 1);\n            hPolyIdx.resize(pieceN);\n            for (int i = 0, j = 0, k; i < polyN; i++)\n            {\n                k = pieceIdx(i);\n                for (int l = 0; l < k; l++, j++)\n                {\n                    if (l < k - 1)\n                    {\n                        vPolyIdx(j) = 2 * i;\n                        spatialDim += vPolytopes[2 * i].cols();\n                    }\n                    else if (i < polyN - 1)\n                    {\n                        vPolyIdx(j) = 2 * i + 1;\n                        spatialDim += vPolytopes[2 * i + 1].cols();\n                    }\n                    hPolyIdx(j) = i;\n                }\n            }\n\n            // Setup for MINCO_S3NU, FlatnessMap, and L-BFGS solver\n            minco.setConditions(headPVA, tailPVA, pieceN);\n            flatmap.reset(physicalPm(0), physicalPm(1), physicalPm(2),\n                          physicalPm(3), physicalPm(4), physicalPm(5));\n\n            // Allocate temp variables\n            points.resize(3, pieceN - 1);\n            times.resize(pieceN);\n            gradByPoints.resize(3, pieceN - 1);\n            gradByTimes.resize(pieceN);\n            partialGradByCoeffs.resize(6 * pieceN, 3);\n            partialGradByTimes.resize(pieceN);\n\n            return true;\n        }\n\n        inline double optimize(Trajectory<5> &traj,\n                               const double &relCostTol)\n        {\n            Eigen::VectorXd x(temporalDim + spatialDim);\n            Eigen::Map<Eigen::VectorXd> tau(x.data(), temporalDim);\n            Eigen::Map<Eigen::VectorXd> xi(x.data() + temporalDim, spatialDim);\n\n            setInitial(shortPath, allocSpeed, pieceIdx, points, times);\n            backwardT(times, tau);\n            backwardP(points, vPolyIdx, vPolytopes, xi);\n\n            double minCostFunctional;\n            lbfgs_params.mem_size = 256;\n            lbfgs_params.past = 3;\n            lbfgs_params.min_step = 1.0e-32;\n            lbfgs_params.g_epsilon = 0.0;\n            lbfgs_params.delta = relCostTol;\n\n            int ret = lbfgs::lbfgs_optimize(x,\n                                            minCostFunctional,\n                                            &GCOPTER_PolytopeSFC::costFunctional,\n                                            nullptr,\n                                            nullptr,\n                                            this,\n                                            lbfgs_params);\n\n            if (ret >= 0)\n            {\n                forwardT(tau, times);\n                forwardP(xi, vPolyIdx, vPolytopes, points);\n                minco.setParameters(points, times);\n                minco.getTrajectory(traj);\n            }\n            else\n            {\n                traj.clear();\n                minCostFunctional = INFINITY;\n                std::cout << \"Optimization Failed: \"\n                          << lbfgs::lbfgs_strerror(ret)\n                          << std::endl;\n            }\n\n            return minCostFunctional;\n        }\n    };\n\n}\n\n#endif\n", "meta": {"hexsha": "c076ca93c2aff30207925f8fcf9c523fa036c955", "size": 34583, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "gcopter/include/gcopter/gcopter.hpp", "max_stars_repo_name": "RENyunfan/GCOPTER", "max_stars_repo_head_hexsha": "3b49c46b7467fd0b6b1abb2141912a1357e8da39", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gcopter/include/gcopter/gcopter.hpp", "max_issues_repo_name": "RENyunfan/GCOPTER", "max_issues_repo_head_hexsha": "3b49c46b7467fd0b6b1abb2141912a1357e8da39", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gcopter/include/gcopter/gcopter.hpp", "max_forks_repo_name": "RENyunfan/GCOPTER", "max_forks_repo_head_hexsha": "3b49c46b7467fd0b6b1abb2141912a1357e8da39", "max_forks_repo_licenses": ["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.3065268065, "max_line_length": 135, "alphanum_fraction": 0.4445536824, "num_tokens": 8256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.45084056272560613}}
{"text": "/**\n * @file \tSteinerTreeHeuristic.cpp\n * @author \tFabian Wegscheider\n * @date \tJul 14, 2017\n */\n\n#include <sstream>\n#include <boost/heap/d_ary_heap.hpp>\n#include \"SteinerTreeHeuristic.h\"\n\nusing std::pair;\n\n\n/*\n * Data that is stored in one node of the heap. Contains an integer and a double.\n * Comparisons are made by the double, smaller has higher priority. The int is\n * used for the vertex index and the double for its key during the algorithm\n */\nstruct heap_data {\n\n\tint index;\n\tweight_type key;\n\n    heap_data(int i, weight_type k): index(i), key(k) {\n    }\n\n    bool operator<(heap_data const & rhs) const {\n        return key > rhs.key;\n    }\n};\n\n\n/*\n * Implementation of the improved Shortest-Path-Heuristic. A 4-ary-heap from\n * boost is used and keys are never decreased, but instead new nodes are pushed\n * whenever a better path is found. The resulting tree is stored implicitly\n */\ndouble SteinerTreeHeuristic::compute_steiner_tree(const CSR_Graph& g, int num_vertices,\n\t\tint root, vector<int>& tree_preds, const vector<int>& terminals) {\n\n\tassert((int) tree_preds.size() == num_vertices);\n\n\t// terminals are scanned\n\tint num_terminals = terminals.size();\n\tvector<bool> is_terminal(num_vertices, false);\n\tfor (int i = 0; i < num_terminals; ++i) {\n\t\tassert(terminals[i] < num_vertices);\n\t\tis_terminal[terminals[i]] = true;\n\t}\n\n\tassert(is_terminal[root]);\n\n\theap::d_ary_heap<heap_data, heap::arity<4>> heap;\n\n\t// this vector is used to store the info about predecessor and the respective\n\t// edge together in order to avoid cache misses\n\tvector<pair<int,weight_type>> preds(num_vertices);\n\tpreds[root] = std::make_pair(root, 0);\n\n\t// we expect the tree vector to be filled with -1 already\n\tfor (int i = 0; i < num_vertices; ++i) {\n\t\tassert(tree_preds[i] == -1);\n\t}\n\n\t// initialization of distances. all but the root vertex have infinity\n\tvector<weight_type> dist(num_vertices, std::numeric_limits<weight_type>::infinity());\n\tdist[root] = 0;\n\ttree_preds[root] = root;\n\n\theap.push(heap_data(root, 0));\n\n\n\t// this is just boost syntax so that we can access weights and indices later\n\tproperty_map<CSR_Graph, edge_weight_t>::const_type weights = get(edge_weight, g);\n\tproperty_map<CSR_Graph, vertex_index_t>::const_type index = get(vertex_index, g);\n\n\tint connected_terminals = 1;\n\tweight_type tree_cost = 0;\n\n\t// here the actual algorithm starts\n\twhile (connected_terminals < num_terminals) {\n\n\t\tassert(!heap.empty());\t//heap should never be empty before tree contains all terminals\n\n\t\tint min_idx = heap.top().index;\n\t\tweight_type min_key = heap.top().key;\n\n\t\theap.pop();\n\n\t\tif (dist[min_idx] < min_key) continue;\n\n\t\t// if we scan a terminal, all vertices on shortest path to subtree\n\t\t// are added to heap with weight 0 and included into the tree\n\t\tif (is_terminal[min_idx] && tree_preds[min_idx] == -1) {\n\n\t\t\t++connected_terminals;\n\n\t\t\tmin_key = 0;\n\t\t\tint next_vertex = preds[min_idx].first;\n\t\t\ttree_preds[min_idx] = next_vertex;\n\n\t\t\ttree_cost += preds[min_idx].second;\n\n\t\t\t// here all vertices on path from new terminal to tree are added again with key=0\n\t\t\twhile (tree_preds[next_vertex] == -1) {\n\n\t\t\t\theap.push(heap_data(next_vertex, 0));\n\t\t\t\tdist[next_vertex] = 0;\n\t\t\t\ttree_preds[next_vertex] = preds[next_vertex].first;\n\n\t\t\t\ttree_cost += preds[next_vertex].second;\n\n\t\t\t\tnext_vertex = preds[next_vertex].first;\n\t\t\t}\n\t\t}\n\n\t\ttypename graph_traits<CSR_Graph>::out_edge_iterator it, it_end;\n\n\t\t// this is basically dijkstra with pushes instead of decreasekey operations\n\t\tfor (tie(it,it_end) = out_edges(*(vertices(g).first+min_idx),g); it != it_end; ++it) {\n\n\t\t\tint v_target = index[target(*it, g)];\n\n\t\t\t// we only consider vertices which have not been added to the tree yet\n\t\t\tif (tree_preds[v_target] != -1) continue;\n\n\t\t\tif (min_key + weights[*it] < dist[v_target]) {\n\t\t\t\t// distance is updated\n\t\t\t\tdist[v_target] = min_key + weights[*it];\n\t\t\t\tpreds[v_target].first = min_idx;\n\t\t\t\tpreds[v_target].second = weights[*it];\n\t\t\t\theap.push(heap_data(v_target, dist[v_target]));\n\t\t\t}\n\t\t}\n\t}\n\n\treturn tree_cost;\n}\n\n\n/* note: this method only works if tree_preds actually represents a tree.\n * If not sure, use function testTree(...)\n */\nstring SteinerTreeHeuristic::print_tree(const CSR_Graph& g, int num_vertices, int root,\n\t\tvector<int>& tree_preds, vector<int>& terminals) {\n\n\tstd::stringstream stream;\n\tvector<bool> visited(num_vertices, false);\n\n\t// we iterate through the tree going from each terminal until we arrive at root\n\tfor (unsigned int i = 0; i < terminals.size(); ++i) {\n\t\tint curr = terminals[i];\n\t\tint edge_count = 0;\n\t\twhile (curr != root && !visited[curr]) {\n\t\t\t++edge_count;\n\n\t\t\t// every 50 lines a linebreak is added for the sake of readability\n\t\t\tif (edge_count % 50 == 0) stream << std::endl;\n\t\t\tstream << \"(\" << curr << \",\" << tree_preds[curr] << \") \";\n\n\t\t\tvisited[curr] = true;\n\t\t\tcurr = tree_preds[curr];\n\t\t}\n\t}\n\n\treturn stream.str();\n}\n\n\n\nbool SteinerTreeHeuristic::test_tree(const CSR_Graph& g, int num_vertices, int root,\n\tvector<int>& tree_preds, vector<int>& terminals) {\n\n\tvector<bool> visited(num_vertices, false);\n\n\t// we iterate through the tree going from each terminal until we arrive at\n\t// the root or a vertex that we already visited\n\tfor (unsigned int i = 0; i < terminals.size(); ++i) {\n\t\tint curr = terminals[i];\n\t\tint vertex_count = 1;\n\n\t\twhile (curr != root && !visited[curr] && vertex_count != num_vertices) {\n\t\t\t// if one terminal is not connected to root, result is false\n\t\t\tif (curr == -1) return false;\n\t\t\tvisited[curr] = true;\n\t\t\tcurr = tree_preds[curr];\n\t\t\t++vertex_count;\n\t\t}\n\n\t\t// if a cycle is found, result is false\n\t\tif (vertex_count == num_vertices || curr == -1){\n\t\t\treturn false;\n\t\t}\n\t}\n\n\treturn true;\n}\n\n\n\n", "meta": {"hexsha": "dd50925443a8833c05d8a95bb75f01d5bddede38", "size": 5678, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Wegscheider/ex10/SteinerTreeHeuristic.cpp", "max_stars_repo_name": "appfs/appfs", "max_stars_repo_head_hexsha": "8cbbfa0e40e4d4a75a498ce8dd894bb2fbc3a9e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2017-04-21T11:39:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T20:25:18.000Z", "max_issues_repo_path": "Wegscheider/ex10/SteinerTreeHeuristic.cpp", "max_issues_repo_name": "appfs/appfs", "max_issues_repo_head_hexsha": "8cbbfa0e40e4d4a75a498ce8dd894bb2fbc3a9e3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 69.0, "max_issues_repo_issues_event_min_datetime": "2017-04-26T09:30:38.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-01T11:31:21.000Z", "max_forks_repo_path": "Wegscheider/ex10/SteinerTreeHeuristic.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": 28.2487562189, "max_line_length": 88, "alphanum_fraction": 0.69337795, "num_tokens": 1499, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.45084056272560613}}
{"text": "#include <VoronoiTests.h>\n\n#include <SimilarityGraph.h>\n#include <Heuristics.h>\n\n#pragma warning(push)\n#pragma warning(disable: 4996)\n\n#include <boost/geometry.hpp>\n\n#pragma warning(pop)\n\n#include <set>\n\nTEST_F(VoronoiTests, Build_TriangleConfiguration_1)\n{\n    std::set<std::tuple<std::size_t, std::size_t>> edges;\n\n    /*\n        0   1\n        | \\  \n        2 - 3\n    */\n    edges.insert({ 0, 2 });\n    edges.insert({ 0, 3 });\n    edges.insert({ 2, 3 });\n\n    VoronoiDiagram voronoi{ std::make_tuple(2, 2) };\n    voronoi.build(edges);\n\n    std::ostringstream output;\n    voronoi.printVertices(std::ref(output));\n\n    EXPECT_EQ(getTriangleConfiguration1Answer(), output.str());\n}\n\nTEST_F(VoronoiTests, Build_TriangleConfiguration_2)\n{\n    std::set<std::tuple<std::size_t, std::size_t>> edges;\n\n    /*\n        0 - 1\n        | /\n        2   3\n    */\n    edges.insert({ 0, 1 });\n    edges.insert({ 0, 2 });\n    edges.insert({ 1, 2 });\n\n    VoronoiDiagram voronoi{ std::make_tuple(2, 2) };\n    voronoi.build(edges);\n\n    std::ostringstream output;\n    voronoi.printVertices(std::ref(output));\n\n    EXPECT_EQ(getTriangleConfiguration2Answer(), output.str());\n}\n\nTEST_F(VoronoiTests, Build_TriangleConfiguration_3)\n{\n    std::set<std::tuple<std::size_t, std::size_t>> edges;\n\n    /*\n        0 - 1\n          \\ |\n        2   3\n    */\n    edges.insert({ 0, 1 });\n    edges.insert({ 0, 3 });\n    edges.insert({ 1, 3 });\n\n    VoronoiDiagram voronoi{ std::make_tuple(2, 2) };\n    voronoi.build(edges);\n\n    std::ostringstream output;\n    voronoi.printVertices(std::ref(output));\n\n    EXPECT_EQ(getTriangleConfiguration3Answer(), output.str());\n}\n\nTEST_F(VoronoiTests, Build_TriangleConfiguration_4)\n{\n    std::set<std::tuple<std::size_t, std::size_t>> edges;\n\n    /*\n        0   1\n          / |\n        2 - 3\n    */\n    edges.insert({ 1, 2 });\n    edges.insert({ 1, 3 });\n    edges.insert({ 2, 3 });\n\n    VoronoiDiagram voronoi{ std::make_tuple(2, 2) };\n    voronoi.build(edges);\n\n    std::ostringstream output;\n    voronoi.printVertices(std::ref(output));\n\n    EXPECT_EQ(getTriangleConfiguration4Answer(), output.str());\n}\n\nTEST_F(VoronoiTests, Build_DiagonalConfiguration_1)\n{\n    std::set<std::tuple<std::size_t, std::size_t>> edges;\n\n    /*\n        0   1\n          / \n        2   3\n    */\n\n    edges.insert({ 2, 1 });\n\n    VoronoiDiagram voronoi{ std::make_tuple(2, 2) };\n    voronoi.build(edges);\n\n    std::ostringstream output;\n    voronoi.printVertices(std::ref(output));\n\n    EXPECT_EQ(getDiagonalConfiguration1Answer(), output.str());\n}\n\nTEST_F(VoronoiTests, Build_DiagonalConfiguration_2)\n{\n    std::set<std::tuple<std::size_t, std::size_t>> edges;\n\n    /*\n        0   1\n          \\\n        2   3\n    */\n\n    edges.insert({ 0, 3 });\n\n    VoronoiDiagram voronoi{ std::make_tuple(2, 2) };\n    voronoi.build(edges);\n\n    std::ostringstream output;\n    voronoi.printVertices(std::ref(output));\n\n    EXPECT_EQ(getDiagonalConfiguration2Answer(), output.str());\n}\n\nTEST_F(VoronoiTests, Build_DefaultConfiguration_1)\n{\n    std::set<std::tuple<std::size_t, std::size_t>> edges;\n\n    /*\n        0   1\n        |   |\n        2   3\n    */\n    edges.insert({ 0, 2 });\n    edges.insert({ 1, 3 });\n\n    VoronoiDiagram voronoi{ std::make_tuple(2, 2) };\n    voronoi.build(edges);\n\n    std::ostringstream output;\n    voronoi.printVertices(std::ref(output));\n\n    EXPECT_EQ(getDefaultConfigurationAnswer(), output.str());\n}\n\nTEST_F(VoronoiTests, Build_DefaultConfiguration_2)\n{\n    std::set<std::tuple<std::size_t, std::size_t>> edges;\n\n    /*\n        0 - 1\n           \n        2 - 3\n    */\n    edges.insert({ 0, 1 });\n    edges.insert({ 2, 3 });\n\n    VoronoiDiagram voronoi{ std::make_tuple(2, 2) };\n    voronoi.build(edges);\n\n    std::ostringstream output;\n    voronoi.printVertices(std::ref(output));\n\n    EXPECT_EQ(getDefaultConfigurationAnswer(), output.str());\n}\n\nTEST_F(VoronoiTests, Build_DefaultConfiguration_3)\n{\n    std::set<std::tuple<std::size_t, std::size_t>> edges;\n\n    /*\n        0   1\n        |\n        2   3\n    */\n    edges.insert({ 0, 2 });\n\n    VoronoiDiagram voronoi{ std::make_tuple(2, 2) };\n    voronoi.build(edges);\n\n    std::ostringstream output;\n    voronoi.printVertices(std::ref(output));\n\n    EXPECT_EQ(getDefaultConfigurationAnswer(), output.str());\n}\n\nTEST_F(VoronoiTests, Build_DefaultConfiguration_4)\n{\n    std::set<std::tuple<std::size_t, std::size_t>> edges;\n\n    /*\n        0   1\n            |\n        2   3\n    */\n    edges.insert({ 1, 3 });\n\n    VoronoiDiagram voronoi{ std::make_tuple(2, 2) };\n    voronoi.build(edges);\n\n    std::ostringstream output;\n    voronoi.printVertices(std::ref(output));\n\n    EXPECT_EQ(getDefaultConfigurationAnswer(), output.str());\n}\n\nTEST_F(VoronoiTests, Build_DefaultConfiguration_5)\n{\n    std::set<std::tuple<std::size_t, std::size_t>> edges;\n\n    /*\n        0 - 1\n            \n        2   3\n    */\n    edges.insert({ 0, 1 });\n\n    VoronoiDiagram voronoi{ std::make_tuple(2, 2) };\n    voronoi.build(edges);\n\n    std::ostringstream output;\n    voronoi.printVertices(std::ref(output));\n\n    EXPECT_EQ(getDefaultConfigurationAnswer(), output.str());\n}\n\nTEST_F(VoronoiTests, Build_DefaultConfiguration_6)\n{\n    std::set<std::tuple<std::size_t, std::size_t>> edges;\n\n    /*\n        0   1\n\n        2 - 3\n    */\n    edges.insert({ 2, 3 });\n\n    VoronoiDiagram voronoi{ std::make_tuple(2, 2) };\n    voronoi.build(edges);\n\n    std::ostringstream output;\n    voronoi.printVertices(std::ref(output));\n\n    EXPECT_EQ(getDefaultConfigurationAnswer(), output.str());\n}\n\nTEST_F(VoronoiTests, Weld)\n{\n    using namespace dpa::image;\n    using namespace dpa::graph;\n\n    Image<RGB, stbi_uc> image{ m_curve };\n    \n    SimilarityGraph simGraph;\n    simGraph.build(image);\n\n    auto imageDims = std::make_tuple(image.getWidth(), image.getHeight());\n\n    simGraph.applyHeuristic(heuristics::DissimilarPixels{});\n    simGraph.applyHeuristic(heuristics::Curves{ imageDims });\n    simGraph.applyHeuristic(heuristics::Islands{ imageDims });\n    simGraph.applyHeuristic(heuristics::SparsePixels{ imageDims });\n\n    VoronoiDiagram voronoi{ imageDims };\n    voronoi.build(simGraph.getEdges());\n\n    std::ostringstream output;\n    voronoi.printVertices(std::ref(output));\n\n    std::ifstream input{ m_curves_weld_solution };\n    std::string solution{ std::istreambuf_iterator<char>(input), std::istreambuf_iterator<char>() };\n\n    EXPECT_EQ(solution, output.str());\n}\n", "meta": {"hexsha": "6080f2b9b9544388d8a878d8e170a3d770a6d7f2", "size": 6390, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/reshaper/tests/VoronoiTests.cpp", "max_stars_repo_name": "Hoshiningen/depixelization", "max_stars_repo_head_hexsha": "f1da8fb311c6d92a1dcd0094f714c9d66c07fd29", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2019-09-29T00:55:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-02T06:33:41.000Z", "max_issues_repo_path": "source/reshaper/tests/VoronoiTests.cpp", "max_issues_repo_name": "Hoshiningen/depixelization", "max_issues_repo_head_hexsha": "f1da8fb311c6d92a1dcd0094f714c9d66c07fd29", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2019-04-25T00:08:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-31T13:49:11.000Z", "max_forks_repo_path": "source/reshaper/tests/VoronoiTests.cpp", "max_forks_repo_name": "Hoshiningen/Depixelization", "max_forks_repo_head_hexsha": "f1da8fb311c6d92a1dcd0094f714c9d66c07fd29", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-09-08T09:34:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-10T07:32:26.000Z", "avg_line_length": 21.6610169492, "max_line_length": 100, "alphanum_fraction": 0.6228482003, "num_tokens": 1818, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583124210896, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.45084055455533995}}
{"text": "//==================================================================================================\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_ABS_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_ABS_HPP_INCLUDED\n\n#include <boost/simd/function/std.hpp>\n#include <boost/simd/function/saturated.hpp>\n#include <boost/simd/detail/math.hpp>\n#include <boost/simd/constant/valmax.hpp>\n#include <boost/simd/constant/valmin.hpp>\n#include <boost/simd/function/is_equal.hpp>\n#include <boost/simd/detail/dispatch/meta/as_unsigned.hpp>\n#include <boost/simd/detail/dispatch/function/overload.hpp>\n#include <boost/config.hpp>\n#include <cmath>\n#include <cstdlib>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  namespace bs = boost::simd;\n\n  BOOST_DISPATCH_OVERLOAD ( abs_\n                          , (typename T)\n                          , bd::cpu_\n                          , bd::scalar_<bd::arithmetic_<T>>\n                          )\n  {\n    BOOST_FORCEINLINE T operator()(T a) const BOOST_NOEXCEPT\n    {\n      using utype = dispatch::as_unsigned_t<T>;\n\n      utype mask = a >> (sizeof(T)*8 - 1);\n      return (a + mask) ^ mask;\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( abs_\n                          , (typename T)\n                          , bd::cpu_\n                          , bd::scalar_<bd::single_<T>>\n                          )\n  {\n    BOOST_FORCEINLINE T operator()(T a) const BOOST_NOEXCEPT\n    {\n      #ifdef BOOST_SIMD_HAS_FABSF\n       return ::fabsf(a);\n      #else\n       return (a > 0) ? a : -a;\n      #endif\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( abs_\n                          , (typename T)\n                          , bd::cpu_\n                          , bd::scalar_<bd::double_<T>>\n                          )\n  {\n    BOOST_FORCEINLINE T operator()(T a) const BOOST_NOEXCEPT\n    {\n      return ::fabs(a);\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( abs_\n                          , (typename T)\n                          , bd::cpu_\n                          , bd::scalar_<bd::unsigned_<T>>\n                          )\n  {\n    BOOST_FORCEINLINE T operator()(T a) const BOOST_NOEXCEPT\n    {\n      return a;\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( abs_\n                          , (typename T)\n                          , bd::cpu_\n                          , bd::scalar_<bd::bool_<T>>\n                          )\n  {\n    BOOST_FORCEINLINE T operator()(T a) const BOOST_NOEXCEPT\n    {\n      return a;\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( abs_\n                          , (typename T)\n                          , bd::cpu_\n                          , bs::std_tag\n                          , bd::scalar_<bd::floating_<T>>\n                          )\n  {\n    BOOST_FORCEINLINE T operator()( std_tag const&, T a) const BOOST_NOEXCEPT\n    {\n      return std::fabs(a);\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( abs_\n                          , (typename T)\n                          , bd::cpu_\n                          , bs::std_tag\n                          , bd::scalar_<bd::unsigned_<T>>\n                          )\n  {\n    BOOST_FORCEINLINE T operator()( std_tag const&, T a) const BOOST_NOEXCEPT\n    {\n      return a;\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( abs_\n                          , (typename T)\n                          , bd::cpu_\n                          , boost::simd::std_tag\n                          , bd::scalar_<bd::integer_<T>>\n                          )\n  {\n    BOOST_FORCEINLINE T operator()( std_tag const&,T a) const BOOST_NOEXCEPT\n    {\n      return std::abs(a);\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( abs_\n                          , (typename T)\n                          , bd::cpu_\n                          , bs::saturated_tag\n                          , bd::scalar_<bd::signed_<T>>\n                          )\n  {\n    BOOST_FORCEINLINE T operator()(const saturated_tag &, T const& a0) const BOOST_NOEXCEPT\n    {\n      return (a0==Valmin<T>())?Valmax<T>():bs::abs(a0);\n    }\n  };\n} } }\n\n#include <boost/simd/arch/common/scalar/function/abs_s.hpp>\n\n#endif\n", "meta": {"hexsha": "c1c2dd0e6f73e67ebdbec6e0028f97f2c9aa6432", "size": 4325, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/scalar/function/abs.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/scalar/function/abs.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/abs.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": 28.4539473684, "max_line_length": 100, "alphanum_fraction": 0.4698265896, "num_tokens": 932, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289836, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.45081224250652985}}
{"text": "#pragma once\n#include <Eigen/Dense>\n\nstruct InternalBoundingBox\n{\n\t/// The position of the box's corner that has the least coordinate value in all axes.\n\tEigen::Vector3i pos;\n\t/// The extents of the cube.\n\tEigen::Vector3i span;\n\n\tstatic bool IsPointInCube(const InternalBoundingBox& cube, Eigen::Vector3i point)\n\t{\n\t\tbool xIntersects = cube.pos.x() <= point.x() && cube.pos.x() + cube.span.x() > point.x();\n\t\tbool yIntersects = cube.pos.y() <= point.y() && cube.pos.y() + cube.span.y() > point.y();\n\t\tbool zIntersects = cube.pos.z() <= point.z() && cube.pos.z() + cube.span.z() > point.z();\n\t\treturn xIntersects && yIntersects && zIntersects;\n\t}\n\n\tstatic bool CubesIntersect(const InternalBoundingBox& cube1, const InternalBoundingBox& cube2)\n\t{\n\t\tbool xIntersects = !(cube2.pos.x() + cube2.span.x() <= cube1.pos.x() || cube1.pos.x() + cube1.span.x() <= cube2.pos.x());\n\t\tbool yIntersects = !(cube2.pos.y() + cube2.span.y() <= cube1.pos.y() || cube1.pos.y() + cube1.span.y() <= cube2.pos.y());\n\t\tbool zIntersects = !(cube2.pos.z() + cube2.span.z() <= cube1.pos.z() || cube1.pos.z() + cube1.span.z() <= cube2.pos.z());\n\t\treturn xIntersects && yIntersects && zIntersects;\n\t}\n\n\tstatic void SplitCube(const InternalBoundingBox& cube, InternalBoundingBox children[8])\n\t{\n\t\tEigen::Vector3i newSpan = cube.span / 2;\n\n\t\tchildren[0].pos = { cube.pos.x(), cube.pos.y(), cube.pos.z() };\n\t\tchildren[0].span = newSpan;\n\n\t\tchildren[1].pos = { cube.pos.x(), cube.pos.y(), cube.pos.z() + newSpan.z() };\n\t\tchildren[1].span = newSpan;\n\n\t\tchildren[2].pos = { cube.pos.x(), cube.pos.y() + newSpan.y(), cube.pos.z() };\n\t\tchildren[2].span = newSpan;\n\n\t\tchildren[3].pos = { cube.pos.x(), cube.pos.y() + newSpan.y(), cube.pos.z() + newSpan.z() };\n\t\tchildren[3].span = newSpan;\n\n\t\tchildren[4].pos = { cube.pos.x() + newSpan.x(), cube.pos.y(), cube.pos.z() };\n\t\tchildren[4].span = newSpan;\n\n\t\tchildren[5].pos = { cube.pos.x() + newSpan.x(), cube.pos.y(), cube.pos.z() + newSpan.z() };\n\t\tchildren[5].span = newSpan;\n\n\t\tchildren[6].pos = { cube.pos.x() + newSpan.x(), cube.pos.y() + newSpan.y(), cube.pos.z() };\n\t\tchildren[6].span = newSpan;\n\n\t\tchildren[7].pos = { cube.pos.x() + newSpan.x(), cube.pos.y() + newSpan.y(), cube.pos.z() + newSpan.z() };\n\t\tchildren[7].span = newSpan;\n\t}\n\n\tfriend std::ostream& operator<<(std::ostream& os, const InternalBoundingBox& cube)\n\t{\n\t\tos << '[' << cube.pos.x() << \", \" << cube.pos.y() << \", \" << cube.pos.z() << \"] -> \"\n\t\t\t<< '[' << cube.pos.x() + cube.span.x() - 1 << \", \" << cube.pos.y() + cube.span.y() - 1 <<\n\t\t\t\", \" << cube.pos.z() + cube.span.z() - 1 << ']';\n\t\treturn os;\n\t}\n};", "meta": {"hexsha": "e2b465760a998e8eb9e896ea6e91e46a11b6efe3", "size": 2594, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/HashDAG/BoundingBox.hpp", "max_stars_repo_name": "handsomePirate/VoxelViewer", "max_stars_repo_head_hexsha": "02ca4bd988f985a3bc1023ea751d23e4c240e35b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/HashDAG/BoundingBox.hpp", "max_issues_repo_name": "handsomePirate/VoxelViewer", "max_issues_repo_head_hexsha": "02ca4bd988f985a3bc1023ea751d23e4c240e35b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/HashDAG/BoundingBox.hpp", "max_forks_repo_name": "handsomePirate/VoxelViewer", "max_forks_repo_head_hexsha": "02ca4bd988f985a3bc1023ea751d23e4c240e35b", "max_forks_repo_licenses": ["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.1746031746, "max_line_length": 123, "alphanum_fraction": 0.6040863531, "num_tokens": 797, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289836, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.45081224250652985}}
{"text": "#include \"coredsp/filter.h\"\n#include \"coredsp/noise.h\"\n#include \"coreutil/cpu.h\"\n#include <boost/preprocessor.hpp>\n#include <functional>\n#include <chrono>\n#include <vector>\n\ntypedef std::chrono::steady_clock Clock;\ntypedef Clock::time_point TimePoint;\ntypedef Clock::duration Duration;\n\nstatic unsigned iteration_count = 64 * 1024;\n\nstruct Benchmark {\n  const char *name {};\n  std::function<float()> fn;\n  double run() const;\n};\n\ndouble Benchmark::run() const {\n  TimePoint tstart = Clock::now();\n  this->fn();\n  Duration dur = Clock::now() - tstart;\n  auto ns = std::chrono::duration_cast<std::chrono::nanoseconds>(dur);\n  return ns.count() * 1e-9;\n}\n\n#define IIR_NCOEF_MIN 2\n#define IIR_NCOEF_LIMIT 256\n\nstatic constexpr unsigned niir = IIR_NCOEF_LIMIT - IIR_NCOEF_MIN;\n\n#define DECL_IIR_FLT(z, n, t)                               \\\n  static coredsp::IIR<n, coreutil::simd_t<float>> iirf##n;  \\\n  static coredsp::IIR<n, coreutil::simd_t<double>> iird##n;\n#define DECL_IIRG_FLT(z, n, t)                                 \\\n  static coredsp::IIRg<coreutil::simd_t<float>> iirgf##n(n);   \\\n  static coredsp::IIRg<coreutil::simd_t<double>> iirgd##n(n);\nBOOST_PP_REPEAT_FROM_TO(IIR_NCOEF_MIN, IIR_NCOEF_LIMIT, DECL_IIR_FLT,);\nBOOST_PP_REPEAT_FROM_TO(IIR_NCOEF_MIN, IIR_NCOEF_LIMIT, DECL_IIRG_FLT,);\n\nstatic Benchmark biirf_simd[niir], biirf_scalar[niir];\nstatic Benchmark biirgf_simd[niir], biirgf_scalar[niir];\nstatic Benchmark biird_simd[niir], biird_scalar[niir];\nstatic Benchmark biirgd_simd[niir], biirgd_scalar[niir];\n\ntemplate <class T> std::function<float()> create_iir_simd_fn(T &filter) {\n  return [&filter]() -> float {\n    float out {};\n    coredsp::WhiteNoise source;\n    for (unsigned i = 0; i < iteration_count; ++i)\n      out = filter.impl_simd(source.tick());\n    return out;\n  };\n}\n\ntemplate <class T> std::function<float()> create_iir_scalar_fn(T &filter) {\n  return [&filter]() -> float {\n    float out {};\n    coredsp::WhiteNoise source;\n    for (unsigned i = 0; i < iteration_count; ++i)\n      out = filter.impl_scalar(source.tick());\n    return out;\n  };\n}\n\nint main() {\n  coreutil::disable_denormals();\n\n#define DEF_IIR_BENCHMARK(z, n, t)                                      \\\n  biirf_simd[n - IIR_NCOEF_MIN] = Benchmark{\"IIR<\" #n \"> simd float\", create_iir_simd_fn(iirf##n)}; \\\n  biirf_scalar[n - IIR_NCOEF_MIN] = Benchmark{\"IIR<\" #n \"> scalar float\", create_iir_scalar_fn(iirf##n)}; \\\n  biirgf_simd[n - IIR_NCOEF_MIN] = Benchmark{\"IIRg<\" #n \"> simd float\", create_iir_simd_fn(iirgf##n)}; \\\n  biirgf_scalar[n - IIR_NCOEF_MIN] = Benchmark{\"IIRg<\" #n \"> scalar float\", create_iir_scalar_fn(iirgf##n)}; \\\n  biird_simd[n - IIR_NCOEF_MIN] = Benchmark{\"IIR<\" #n \"> simd double\", create_iir_simd_fn(iird##n)}; \\\n  biird_scalar[n - IIR_NCOEF_MIN] = Benchmark{\"IIR<\" #n \"> scalar double\", create_iir_scalar_fn(iird##n)}; \\\n  biirgd_simd[n - IIR_NCOEF_MIN] = Benchmark{\"IIRg<\" #n \"> simd double\", create_iir_simd_fn(iirgd##n)}; \\\n  biirgd_scalar[n - IIR_NCOEF_MIN] = Benchmark{\"IIRg<\" #n \"> scalar double\", create_iir_scalar_fn(iirgd##n)};\n\n  BOOST_PP_REPEAT_FROM_TO(IIR_NCOEF_MIN, IIR_NCOEF_LIMIT, DEF_IIR_BENCHMARK,);\n\n  setlinebuf(stdout);\n\n  for (unsigned i = 0; i < niir; ++i) {\n    double tsimdf = biirf_simd[i].run();\n    double tscalarf = biirf_scalar[i].run();\n    double tgsimdf = biirgf_simd[i].run();\n    double tgscalarf = biirgf_scalar[i].run();\n    double tsimdd = biird_simd[i].run();\n    double tscalard = biird_scalar[i].run();\n    double tgsimdd = biirgd_simd[i].run();\n    double tgscalard = biirgd_scalar[i].run();\n\n    printf(\"%u %f %f %f %f %f %f %f %f\\n\", i + IIR_NCOEF_MIN,\n           tsimdf, tscalarf, tgsimdf, tgscalarf,\n           tsimdd, tscalard, tgsimdd, tgscalard);\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "04b9cc7353eeaf0a3803e7121fd98784c16a1191", "size": 3728, "ext": "cc", "lang": "C++", "max_stars_repo_path": "programs/iir-benchmark.cc", "max_stars_repo_name": "gerasim13/fast-filters", "max_stars_repo_head_hexsha": "d5d200bff19a404883b55207052d605a852b6245", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 43.0, "max_stars_repo_stars_event_min_datetime": "2017-11-17T08:05:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-05T07:07:40.000Z", "max_issues_repo_path": "programs/iir-benchmark.cc", "max_issues_repo_name": "gerasim13/fast-filters", "max_issues_repo_head_hexsha": "d5d200bff19a404883b55207052d605a852b6245", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-10-05T09:47:49.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-05T11:00:28.000Z", "max_forks_repo_path": "programs/iir-benchmark.cc", "max_forks_repo_name": "gerasim13/fast-filters", "max_forks_repo_head_hexsha": "d5d200bff19a404883b55207052d605a852b6245", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-01-25T09:43:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-09T20:20:35.000Z", "avg_line_length": 36.5490196078, "max_line_length": 110, "alphanum_fraction": 0.6732832618, "num_tokens": 1197, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289835, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4508122425065298}}
{"text": "//\n//  Copyright Karl Meerbergen, 2008\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#include \"../../blas/test/random.hpp\"\n\n#include <boost/numeric/bindings/lapack/driver/ptsv.hpp>\n#include <boost/numeric/bindings/lapack/computational/pttrf.hpp>\n#include <boost/numeric/bindings/lapack/computational/pttrs.hpp>\n#include <boost/numeric/bindings/ublas/matrix.hpp>\n#include <boost/numeric/bindings/ublas/vector.hpp>\n#include <boost/numeric/ublas/operation.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/vector_proxy.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n#include <iostream>\n\n\nnamespace ublas = boost::numeric::ublas;\nnamespace lapack = boost::numeric::bindings::lapack;\nnamespace bindings = boost::numeric::bindings;\n\nstruct apply_real\n{\n  template< typename VectorD, typename VectorE, typename MatrixB >\n  static inline std::ptrdiff_t pttrs(const char uplo, const VectorD& d,\n                                     const VectorE& e, MatrixB& b)\n  {\n    return lapack::pttrs(d, e, b);\n  }\n};\n\nstruct apply_complex\n{\n  template< typename VectorD, typename VectorE, typename MatrixB >\n  static inline std::ptrdiff_t pttrs(const char uplo, const VectorD& d,\n                                     const VectorE& e, MatrixB& b)\n  {\n    return lapack::pttrs(uplo, d, e, b);\n  }\n};\n\ntemplate <typename B, typename X>\nbool check_residual(B const& b, X const& x)\n{\n  typedef typename B::value_type value_type ;\n\n  ublas::matrix<value_type, ublas::column_major> res(b) ;\n  row(res,0).minus_assign(value_type(2.0) * row(x,0) - row(x,1)) ;\n  for(int i=1; i<res.size1()-1; ++i)\n  {\n    row(res,i).minus_assign(value_type(2.0) * row(x,i) - row(x,i+1) - row(x,i-1)) ;\n  }\n  row(res,res.size1()-1).minus_assign(value_type(2.0) * row(x,res.size1()-1) - row(x,res.size1()-2)) ;\n\n  return norm_frobenius(res)<norm_frobenius(b)*1.e-5 ;\n} // check_residual()\n\ntemplate <typename T>\nint do_value_type()\n{\n  typedef typename boost::mpl::if_<boost::is_complex<T>, apply_complex, apply_real>::type apply_t;\n  const int n = 8 ;\n  typedef typename bindings::remove_imaginary<T>::type real_type ;\n\n  typedef ublas::matrix<T, ublas::column_major>     matrix_type ;\n\n  // Set matrix\n  int const nrhs = 1 ;\n  matrix_type b(n, nrhs);\n  ublas::vector< real_type > d(n);\n  ublas::vector<T>           e(n-1);\n\n  std::fill(d.begin(), d.end(), 2.0) ;\n  std::fill(e.begin(), e.end(), -1.0) ;\n\n  for(int i=0; i<b.size1(); ++i) b(i,0) = random_value<T>() ;\n\n  // Factorize and solve\n  matrix_type x(b);\n  if(lapack::ptsv(d, e, x)) return -1 ;\n  if(!check_residual(b,x)) return 1 ;\n\n  // Restart computations\n  std::fill(d.begin(), d.end(), 2.0) ;\n  std::fill(e.begin(), e.end(), -1.0) ;\n\n  // Compute factorization.\n  if(lapack::pttrf(d, e)) return -1 ;\n\n  // Compute solve\n  x.assign(b) ;\n  if(apply_t::pttrs('U', d, e, x)) return -2 ;\n\n  if(!check_residual(b,x)) return 1 ;\n\n  x.assign(b) ;\n  if(apply_t::pttrs('L', d, e, x)) return -3 ;\n\n  if(!check_residual(b,x)) return 2 ;\n\n  return 0 ;\n} // do_value_type()\n\n\nint main()\n{\n  // Run tests for different value_types\n  std::cout << \"double\\n\" ;\n  if(do_value_type< double >()) return 255;\n\n  std::cout << \"float\\n\" ;\n  if(do_value_type< float >()) return 255;\n\n  std::cout << \"complex<double>\\n\" ;\n  if(do_value_type< std::complex<double> >()) return 255;\n\n  std::cout << \"complex<float>\\n\" ;\n  if(do_value_type< std::complex<float> >()) return 255;\n\n  std::cout << \"Regression test succeeded\\n\" ;\n  return 0;\n}\n\n", "meta": {"hexsha": "a94036abdbe5ef3050a06ac5e84480a7291a3911", "size": 3579, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "externals/numeric_bindings/libs/numeric/bindings/lapack/test/ublas_ptsv.cpp", "max_stars_repo_name": "fperignon/sandbox", "max_stars_repo_head_hexsha": "649f09d6db7bbd84c2418de74eb9453c0131f070", "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/lapack/test/ublas_ptsv.cpp", "max_issues_repo_name": "fperignon/sandbox", "max_issues_repo_head_hexsha": "649f09d6db7bbd84c2418de74eb9453c0131f070", "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/lapack/test/ublas_ptsv.cpp", "max_forks_repo_name": "fperignon/sandbox", "max_forks_repo_head_hexsha": "649f09d6db7bbd84c2418de74eb9453c0131f070", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 30.0, "max_forks_repo_forks_event_min_datetime": "2015-08-06T22:57:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T20:30:20.000Z", "avg_line_length": 27.5307692308, "max_line_length": 102, "alphanum_fraction": 0.6549315451, "num_tokens": 1085, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289835, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4508122425065298}}
{"text": "#define TINYPLY_IMPLEMENTATION\n\n#include <fstream>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n\n#include <Eigen/Dense>\n#include <opencv2/opencv.hpp>\n\n#include \"PLY/tinyply.h\"\n\n#include \"PLY/PLY.hpp\"\n\nusing namespace stereo_utils;\n\nvoid stereo_utils::write_ply_with_color(const std::string& fn, const cv::Mat& disp, const cv::Mat& color,\n        const Eigen::MatrixXf &Q, bool flip, const float farLimit, bool binary) {\n    // Check the the dimensions of the input images.\n    const int rows     = disp.rows;\n    const int cols     = disp.cols;\n    const int nPixels  = rows * cols;\n    const int channels = disp.channels();\n\n    if ( rows != color.rows || cols != color.cols )\n    {\n        std::stringstream ss;\n        ss << \"Dimensions of disp[\" << rows << \", \" << cols\n           << \"] and color[\" << color.rows << \",\" << color.rows << \"] are not compatible.\";\n        throw std::runtime_error(ss.str());\n    }\n\n    if ( 1 != channels || 3 != color.channels() )\n    {\n        std::stringstream ss;\n        ss << \"Channel of disp[\" << channels << \"] or color[\" << color.channels() << \"] is wrong.\";\n        throw std::runtime_error(ss.str());\n    }\n\n    if ( 4 != Q.rows() || 4 != Q.cols() )\n    {\n        std::stringstream ss;\n        ss << \"Q.rows = \" << Q.rows() << \", Q.cols = \" << Q.cols() << \". \";\n        throw std::runtime_error(ss.str());\n    }\n\n    // Good to go.\n\n    struct float3_t { float x, y, z; };\n    struct uchar3_t { unsigned char r, g, b; };\n\n    std::vector<float3_t> vertexCoor;\n    std::vector<uchar3_t> vertexColor;\n\n    const float* pDisp = nullptr;\n    const unsigned char* pColor = nullptr;\n\n    cv::Mat colorRGB;\n    cv::cvtColor(color.clone(), colorRGB, cv::COLOR_BGR2RGB);\n\n    // const auto eQ = Eigen::Map<\n    //         const Eigen::Matrix< float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor >,\n    //         Eigen::Unaligned,\n    //         Eigen::Stride<Eigen::Dynamic, Eigen::Dynamic>\n    // >( Q, 4, 4, Eigen::Stride<Eigen::Dynamic, Eigen::Dynamic>(4, 1) );\n\n    // const Eigen::Matrix< \n    //     float, \n    //     Eigen::Dynamic, Eigen::Dynamic, \n    //     Eigen::RowMajor > eQ = Q;\n\n//    std::cout << \"eQ = \" << std::endl << eQ << std::endl;\n\n    // Eigen::Matrix< float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor > eQ_NC = eQ;\n    Eigen::MatrixXf eQ_NC = Q;\n\n    float factor = 1.0;\n\n    if ( flip )\n    {\n        eQ_NC(1,1) *= -1;\n        eQ_NC(1,3) *= -1;\n        eQ_NC(2,3) *= -1;\n\n        factor = -1;\n    }\n\n    Eigen::MatrixXf eCoor(4, nPixels);\n\n    int idx = 0;\n    float d;\n\n    for ( int i = 0; i < rows; ++i )\n    {\n        pDisp = disp.ptr<float>(i);\n\n        for ( int j = 0; j < cols; ++j )\n        {\n            d = pDisp[j];\n\n            if ( d > 0 )\n            {\n                eCoor(0, idx) = j;\n                eCoor(1, idx) = i;\n                eCoor(2, idx) = d;\n                eCoor(3, idx) = 1.0;\n            }\n            else\n            {\n                eCoor(0, idx) =  0.0;\n                eCoor(1, idx) =  0.0;\n                eCoor(2, idx) = -1.0;\n                eCoor(3, idx) =  1.0;\n            }\n\n            idx++;\n        }\n    }\n\n    Eigen::MatrixXf eCoorWorld(4, nPixels);\n\n    eCoorWorld = eQ_NC * eCoor;\n\n    float dOverB;\n    int r, c;\n\n    for ( int i = 0; i < nPixels; ++i )\n    {\n        if ( eCoorWorld(2, i) * factor > 0 )\n        {\n            dOverB = eCoorWorld(3, i);\n\n            if ( std::fabs( eCoorWorld(2, i) / dOverB ) < farLimit )\n            {\n                vertexCoor.push_back({\n                    eCoorWorld(0, i) / dOverB,\n                    eCoorWorld(1, i) / dOverB,\n                    eCoorWorld(2, i) / dOverB });\n\n                r = i / cols;\n                c = i % cols;\n\n                pColor = colorRGB.ptr<unsigned char>(r) + c*3;\n\n                vertexColor.push_back({\n                    pColor[0], pColor[1], pColor[2]\n                });\n            }\n        }\n    }\n\n//    // Debug.\n//    std::cout << \"Size of coordinates = \" << vertexCoor.size() << \".\" << std::endl;\n//    std::cout << \"Size of colors = \" << vertexColor.size() << \".\" << std::endl;\n\n    // Create a buffer.\n    std::filebuf binBuffer;\n    if ( binary )\n    {\n        binBuffer.open( fn, std::ios::out | std::ios::binary );\n    }\n    else\n    {\n        binBuffer.open( fn, std::ios::out );\n    }\n\n    // Create the ostream.\n    std::ostream ofs(&binBuffer);\n    if ( ofs.fail() )\n    {\n        throw std::runtime_error(\"Fail to open \" + fn + \" for output.\");\n    }\n\n    // Create the PlyFile object.\n    tinyply::PlyFile plyFile;\n\n    plyFile.add_properties_to_element(\"vertex\", { \"x\", \"y\", \"z\" },\n            tinyply::Type::FLOAT32,\n            vertexCoor.size(),\n            reinterpret_cast<uint8_t*>(vertexCoor.data()),\n            tinyply::Type::INVALID, 0);\n\n    plyFile.add_properties_to_element(\"vertex\", { \"red\", \"green\", \"blue\" },\n            tinyply::Type::UINT8,\n            vertexColor.size(),\n            reinterpret_cast<uint8_t*>(vertexColor.data()),\n            tinyply::Type::INVALID, 0);\n\n    plyFile.get_comments().emplace_back(\"generated by tinyply 2.2\");\n\n    plyFile.write( ofs, binary );\n}", "meta": {"hexsha": "67f6bcb1654cd744348904c67f24d077898096b9", "size": 5164, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "stereo_utils/src/PLY.cpp", "max_stars_repo_name": "huyaoyu/Tutorial2020_Stereo_ROS", "max_stars_repo_head_hexsha": "32f7427b597ac01674a36a19b8439844d1ea291b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-10-27T03:12:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T07:04:34.000Z", "max_issues_repo_path": "stereo_utils/src/PLY.cpp", "max_issues_repo_name": "huyaoyu/Tutorial2020_Stereo_ROS", "max_issues_repo_head_hexsha": "32f7427b597ac01674a36a19b8439844d1ea291b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stereo_utils/src/PLY.cpp", "max_forks_repo_name": "huyaoyu/Tutorial2020_Stereo_ROS", "max_forks_repo_head_hexsha": "32f7427b597ac01674a36a19b8439844d1ea291b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-08-14T23:05:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-02T11:31:22.000Z", "avg_line_length": 26.7564766839, "max_line_length": 105, "alphanum_fraction": 0.49767622, "num_tokens": 1486, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4508122360750926}}
{"text": "/*  $Id: conecutter.cpp 681 2011-03-23 21:17:32Z anders.e.e.wallin $\n * \n *  Copyright 2010 Anders Wallin (anders.e.e.wallin \"at\" gmail.com)\n *  \n *  This file is part of OpenCAMlib.\n *\n *  OpenCAMlib is free software: you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n *\n *  OpenCAMlib is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n *\n *  You should have received a copy of the GNU General Public License\n *  along with OpenCAMlib.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <boost/foreach.hpp>\n\n#include \"conecutter.h\"\n#include \"compositecutter.h\" // for offsetCutter()\n#include \"numeric.h\"\n\nnamespace ocl\n{\n\nConeCutter::ConeCutter() {\n    assert(0);\n}\n\nConeCutter::ConeCutter(double d, double a, double l) {\n    diameter = d;\n    radius = d/2.0;\n    angle = a;\n    length = radius/tan(angle) + l;\n    center_height = radius/tan(angle);\n    xy_normal_length = radius;\n    normal_length = 0.0;\n}\n\ndouble ConeCutter::height(double r) const {\n    assert( tan(angle) > 0.0 ); // guard against division by zero\n    return r/tan(angle);\n}\n\ndouble ConeCutter::width(double h) const {\n    // grows from zero up to radius\n    // above that (cutter shaft) return radius\n    return (h<center_height) ? h*tan(angle) : radius ;\n}\n\n// ?? Ball-Cone-Bull ??\nMillingCutter* ConeCutter::offsetCutter(double d) const {\n    return new BallConeCutter(2*d,  diameter+2*d, angle) ;\n}\n\n// because this checks for contact with both the tip and the circular edge it is hard to move to the base-class\n// we either hit the tip, when the slope of the plane is smaller than angle\n// or when the slope is steep, the circular edge between the cone and the cylindrical shaft\nbool ConeCutter::facetDrop(CLPoint &cl, const Triangle &t) const {\n    bool result = false;\n    Point normal = t.upNormal(); // facet surface normal    \n    if ( isZero_tol( normal.z ) )  // vertical surface\n        return false;  //can't drop against vertical surface\n    \n    if ( (isZero_tol(normal.x)) && (isZero_tol(normal.y)) ) {  // horizontal plane special case\n        CCPoint cc_tmp( cl.x, cl.y, t.p[0].z, FACET_TIP );  // so any vertex is at the correct height\n        return cl.liftZ_if_inFacet(cc_tmp.z, cc_tmp, t);\n    } else {\n        // define plane containing facet\n        // a*x + b*y + c*z + d = 0, so\n        // d = -a*x - b*y - c*z, where  (a,b,c) = surface normal\n        double a = normal.x;\n        double b = normal.y;\n        double c = normal.z;\n        double d = - normal.dot(t.p[0]); \n        normal.xyNormalize(); // make xy length of normal == 1.0\n        // cylindrical contact point case\n        // find the xy-coordinates of the cc-point\n        CCPoint cyl_cc_tmp =  cl - radius*normal;\n        cyl_cc_tmp.z = (1.0/c)*(-d-a*cyl_cc_tmp.x-b*cyl_cc_tmp.y);\n        double cyl_cl_z = cyl_cc_tmp.z - length; // tip positioned here\n        cyl_cc_tmp.type = FACET_CYL;\n        \n        // tip contact with facet\n        CCPoint tip_cc_tmp(cl.x,cl.y,0.0);\n        tip_cc_tmp.z = (1.0/c)*(-d-a*tip_cc_tmp.x-b*tip_cc_tmp.y);\n        double tip_cl_z = tip_cc_tmp.z;\n        tip_cc_tmp.type = FACET_TIP;\n              \n        result = result || cl.liftZ_if_inFacet( tip_cl_z, tip_cc_tmp, t);\n        result = result || cl.liftZ_if_inFacet( cyl_cl_z, cyl_cc_tmp, t);\n        return result; \n    }\n}\n\n// cone sliced with vertical plane results in a hyperbola as the intersection curve\n// find point where hyperbola and line slopes match\nCC_CLZ_Pair ConeCutter::singleEdgeDropCanonical( const Point& u1, const Point& u2) const {\n    double d = u1.y;\n    double m = (u2.z-u1.z) / (u2.x-u1.x); // slope of edge\n    // the outermost point on the cutter is at   xu = sqrt( R^2 - d^2 )\n    double xu = sqrt( square(radius) - square(u1.y) );                  assert( xu <= radius );\n    // max slope at xu is mu = (L/(R-R2)) * xu /(sqrt( xu^2 + d^2 ))\n    double mu = (center_height/radius ) * xu / sqrt( square(xu) + square(d) ) ;\n    bool hyperbola_case = (fabs(m) <= fabs(mu));\n    // find contact point where slopes match, there are two cases:\n    // 1) if abs(m) <= abs(mu)  we contact the curve at xp = sign(m) * sqrt( R^2 m^2 d^2 / (h^2 - R^2 m^2) )\n    // 2) if abs(m) > abs(mu) there is contact with the circular edge at +/- xu\n    double ccu;\n    if ( hyperbola_case ) { \n        ccu = sign(m) * sqrt( square(radius)*square(m)*square(d) / (square(length) -square(radius)*square(m) ) );\n    } else { \n        ccu = sign(m)*xu;\n    } \n    Point cc_tmp( ccu, d, 0.0); // cc-point in the XY plane\n    cc_tmp.z_projectOntoEdge(u1,u2);\n    double cl_z;\n    if ( hyperbola_case ) {  // 1) zc = zp - Lc + (R - sqrt(xp^2 + d^2)) / tan(beta2)\n        cl_z = cc_tmp.z - center_height + (radius-sqrt(square(ccu) + square(d)))/ tan(angle);\n    } else {  // 2) zc = zp - Lc\n        cl_z = cc_tmp.z - center_height; // case where we hit the edge of the cone\n    } \n    return CC_CLZ_Pair( ccu , cl_z);\n}\n\nbool ConeCutter::facetPush(const Fiber& fib, Interval& i,  const Triangle& t) const {\n    // push two objects: tip, and base-circle\n    bool result = false;\n    if ( generalFacetPush( 0, 0, 0, fib, i, t) ) // TIP\n        result = true;\n    if ( generalFacetPush( 0, this->center_height, this->xy_normal_length , fib, i ,t) ) // BASE\n        result = true;\n        \n    return result;\n}\n\n// cone is pushed along Fiber f into contact with edge p1-p2\nbool ConeCutter::generalEdgePush(const Fiber& f, Interval& i,  const Point& p1, const Point& p2) const {\n    bool result = false;\n    \n    if ( isZero_tol(p2.z-p1.z) ) // guard agains horizontal edge\n        return result;\n    assert( (p2.z-p1.z) != 0.0 );\n    // idea: as the ITO-cone slides along the edge it will pierce a z-plane at the height of the fiber\n    // the shaped of the pierced area is either a circle if the edge is steep\n    // or a 'half-circle' + cone shape if the edge is shallow (ice-cream cone...)\n    // we can now intersect this 2D shape with the fiber and get the CL-points.\n    // how to get the CC-point? (point on edge closest to z-axis of cutter? closest to CL?)\n\n\n    \n    // this is where the ITO cone pierces the plane\n    // edge-line: p1+t*(p2-p1) = zheight\n    // => t = (zheight - p1)/ (p2-p1)  \n    double t_tip = (f.p1.z - p1.z) / (p2.z-p1.z);\n    if (t_tip < 0.0 )\n        t_tip = 0.0;\n    Point p_tip = p1 + t_tip*(p2-p1);\n    assert( isZero_tol( abs(p_tip.z-f.p1.z) ) ); // p_tip should be in plane of fiber\n    \n    // this is where the ITO cone base exits the plane\n    double t_base = (f.p1.z+center_height - p1.z) / (p2.z-p1.z);\n    Point p_base = p1 + t_base*(p2-p1);\n    p_base.z = f.p1.z; // project to plane of fiber\n    //std::cout << \"(t0, t1) (\" << t0 << \" , \" << t1 << \") \\n\";\n    double L = (p_base-p_tip).xyNorm(); \n    \n    if ( L <= radius ) { // this is where the ITO-slice is a circle\n        // find intersection points, if any, between the fiber and the circle\n        // fiber is f.p1 - f.p2\n        // circle is centered at p_base and radius\n        double d = p_base.xyDistanceToLine(f.p1, f.p2);\n        if ( d <= radius ) {\n            // we know there is an intersection point.\n            // http://mathworld.wolfram.com/Circle-LineIntersection.html\n            \n            // subtract circle center, math is for circle centered at (0,0)\n            double dx = f.p2.x - f.p1.x;\n            double dy = f.p2.y - f.p1.y;\n            double dr = sqrt( square(dx) + square(dy) );\n            double det = (f.p1.x-p_base.x) * (f.p2.y-p_base.y) - (f.p2.x-p_base.x) * (f.p1.y-p_base.y);\n            \n            // intersection given by:\n            //  x = det*dy +/- sign(dy) * dx * sqrt( r^2 dr^2 - det^2 )   / dr^2\n            //  y = -det*dx +/- abs(dy)  * sqrt( r^2 dr^2 - det^2 )   / dr^2\n            \n            double discr = square(radius) * square(dr) - square(det);\n            assert( discr > 0.0 ); // this means we have an intersection\n            if ( discr == 0.0 ) { // tangent case\n                double x_tang =  ( det*dy  )/ square(dr);\n                double y_tang = -( det*dx  )/ square(dr);\n                Point p_tang(x_tang+p_base.x, y_tang+p_base.y); // translate back from (0,0) system!\n                double t_tang = f.tval( p_tang );\n                if ( circle_CC( t_tang, p1, p2, f, i) )\n                    result = true;\n            } else {\n                // two intersection points\n                double x_pos = (  det*dy + sign(dy)* dx * sqrt( discr ) ) / square(dr);\n                double y_pos = ( -det*dx + abs(dy)  * sqrt( discr ) ) / square(dr); \n                Point p_pos(x_pos+p_base.x, y_pos+p_base.y);\n                double t_pos = f.tval( p_pos );\n                // the same with \"-\" sign:\n                double x_neg = (  det*dy - sign(dy) * dx * sqrt( discr ) ) / square(dr);\n                double y_neg = ( -det*dx - abs(dy)  * sqrt( discr ) ) / square(dr); \n                Point p_neg(x_neg+p_base.x, y_neg+p_base.y);\n                double t_neg = f.tval( p_neg );\n                if ( circle_CC( t_pos, p1, p2, f, i) ) \n                    result = true;\n                if ( circle_CC( t_neg, p1, p2, f, i) ) \n                    result = true;\n            }\n        }\n        return result;\n    } else {\n        // ITO-slice is cone + half-circle        \n        // lines from p_tip to tangent points\n        assert( L > radius );\n        // http://mathworld.wolfram.com/CircleTangentLine.html\n        // circle centered at x0, y0, radius a\n        // tangent through (0,0)\n        // t = +/- acos(  -a*x0 +/- y0*sqrt(x0^2+y0^2-a^2) / (x0^2+y0^2) )\n        // translate so p_mid is at (0,0)\n        //Point c = p_base - p_mid;\n        //double cos1 = (-radius*c.x + c.y*sqrt(square(c.x)+square(c.y)+square(radius)) )/ (square(c.x) + square(c.y) );\n        //double cos2 = (-radius*c.x - c.y*sqrt(square(c.x)+square(c.y)+square(radius)) )/ (square(c.x) + square(c.y) );\n        \n        \n        return result;\n    }\n}\n\n\n// t is a position along the fiber\n// p1-p2 is the edge\n// Interval& i is updated\nbool ConeCutter::circle_CC( double t, const Point& p1, const Point& p2, const Fiber& f, Interval& i) const {\n    // cone base circle is center_height above fiber\n    double t_cc = (f.p1.z+center_height - p1.z) / (p2.z-p1.z); \n    CCPoint cc_tmp = p1 + t_cc*(p2-p1); // cc-point on the edge\n    cc_tmp.type = EDGE_CONE;\n    return i.update_ifCCinEdgeAndTrue( t, cc_tmp, p1, p2, (true) );\n}\n\n\nstd::string ConeCutter::str() const {\n    std::ostringstream o;\n    o << *this;\n    return o.str();\n}\n\nstd::ostream& operator<<(std::ostream &stream, ConeCutter c) {\n  stream << \"ConeCutter (d=\" << c.diameter << \", angle=\" << c.angle << \", L=\" << c.length << \")\";\n  return stream;\n}\n\n} // end namespace\n// end file conecutter.cpp\n", "meta": {"hexsha": "c073760456368aab8ba2942b5a8913b6508238c3", "size": 11039, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "opencamlib-read-only/src/cutters/conecutter.cpp", "max_stars_repo_name": "play113/swer", "max_stars_repo_head_hexsha": "78764c67885dfacb1fa24e494a20681265f5254c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "opencamlib-read-only/src/cutters/conecutter.cpp", "max_issues_repo_name": "play113/swer", "max_issues_repo_head_hexsha": "78764c67885dfacb1fa24e494a20681265f5254c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "opencamlib-read-only/src/cutters/conecutter.cpp", "max_forks_repo_name": "play113/swer", "max_forks_repo_head_hexsha": "78764c67885dfacb1fa24e494a20681265f5254c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-04T13:58:00.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-04T13:58:00.000Z", "avg_line_length": 42.1335877863, "max_line_length": 120, "alphanum_fraction": 0.5837485279, "num_tokens": 3287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4508122360750926}}
{"text": "#include \"kernel_poly6.hpp\"\n\n#include \"kernel_test.hpp\"\n\n#include <boost/test/unit_test.hpp>\n\nusing namespace GooBalls;\nusing namespace d2;\nusing namespace Physics;\n\nnamespace utf = boost::unit_test;\n\nusing KKernel = Poly6;\n\nBOOST_AUTO_TEST_CASE(poly6_zero_border_1d, *utf::tolerance(0.0001)){\n    KKernel k;\n    testZeroBorder1d(k);\n}\n\nBOOST_AUTO_TEST_CASE(poly6_normalization_1d, *utf::tolerance(0.0001)){\n    KKernel k;\n    testNormalization1d(k, 100);\n}\n\nBOOST_AUTO_TEST_CASE(poly6_zero_border_gradient_1d, *utf::tolerance(0.01)){\n    KKernel k;\n    testZeroBorderGradient1d(k);\n}\n\nBOOST_AUTO_TEST_CASE(poly6_grad_finite_diff_1d, *utf::tolerance(0.001)){\n    KKernel k;\n    testGradientFiniteDifference1d(k, 100);\n}\n\nBOOST_AUTO_TEST_CASE(poly6_lap_grad_finite_diff_1d, *utf::tolerance(0.0001)){\n    KKernel k;\n    testLaplacianFromGradientFiniteDifferences1d(k, 100);\n}\n\nBOOST_AUTO_TEST_CASE(poly6_lap_finite_diff_1d, *utf::tolerance(0.00001)){\n    KKernel k;\n    testLaplacianFiniteDifference1d(k, 100);\n}\n\nBOOST_AUTO_TEST_CASE(poly6_zero_border, *utf::tolerance(0.0001)){\n    KKernel k;\n    testZeroBorder(k, 100);\n}\n\nBOOST_AUTO_TEST_CASE(poly6_zero_border_gradient, *utf::tolerance(0.01)){\n    KKernel k;\n    testZeroBorderGradient(k, 100);\n}\n\nBOOST_AUTO_TEST_CASE(poly6_normalization, *utf::tolerance(0.0001)){\n    KKernel k;\n    testNormalization(k, 100);\n}\n\nBOOST_AUTO_TEST_CASE(poly6_monotonicity, *utf::tolerance(0.0001)){\n    KKernel k;\n    testMonotonicity(k, 10);\n}\n\nBOOST_AUTO_TEST_CASE(poly6_radial_symmetric){\n    KKernel k;\n    testRadialSymmetry(k, 100);\n}\n\nBOOST_AUTO_TEST_CASE(poly6_grad_finite_diff, *utf::tolerance(0.001)){\n    KKernel k;\n    testGradientFiniteDifference(k, 100);\n}\n\nBOOST_AUTO_TEST_CASE(poly6_lap_grad_finite_diff, *utf::tolerance(0.005)){\n    KKernel k;\n    testLaplacianFromGradientFiniteDifferences(k, 100);\n}\n\nBOOST_AUTO_TEST_CASE(poly6_lap_finite_diff, *utf::tolerance(0.001)){\n    KKernel k;\n    testLaplacianFiniteDifference(k, 100);\n}\n\n", "meta": {"hexsha": "46f90a29c475e0140431c3357f7149216569fca5", "size": 1986, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/lib/physics/2d/kernel_poly6.test.cc", "max_stars_repo_name": "Fluci/GooBalls", "max_stars_repo_head_hexsha": "4b68084303e66af368fd6bbf94aaec0950c9c6e3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/lib/physics/2d/kernel_poly6.test.cc", "max_issues_repo_name": "Fluci/GooBalls", "max_issues_repo_head_hexsha": "4b68084303e66af368fd6bbf94aaec0950c9c6e3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lib/physics/2d/kernel_poly6.test.cc", "max_forks_repo_name": "Fluci/GooBalls", "max_forks_repo_head_hexsha": "4b68084303e66af368fd6bbf94aaec0950c9c6e3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.3647058824, "max_line_length": 77, "alphanum_fraction": 0.7542799597, "num_tokens": 614, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4508122360750926}}
{"text": "#include <efanna.hpp>\n#include <iostream>\n#include <fstream>\n#include <ctime>\n#include <malloc.h>\n#include <boost/timer/timer.hpp>\n\nusing namespace efanna;\nusing namespace std;\nvoid load_data(char* filename, float*& data, size_t& num,int& dim){// load data with sift10K pattern\n  ifstream in(filename, ios::binary);\n  if(!in.is_open()){cout<<\"open file error\"<<endl;exit(-1);}\n  in.read((char*)&dim,4);\n  cout<<\"data dimension: \"<<dim<<endl;\n  in.seekg(0,ios::end);\n  ios::pos_type ss = in.tellg();\n  size_t fsize = (size_t)ss;\n  num = fsize / (dim+1) / 4;\n  int cols = (dim + 7)/8*8;\n  data = (float*)memalign(KGRAPH_MATRIX_ALIGN, num * cols * sizeof(float));\nif(dim!=cols)cout<<\"data align to dimension \"<<cols<<\" for avx2 inst\"<<endl;\n\n  in.seekg(0,ios::beg);\n  for(size_t i = 0; i < num; i++){\n    in.seekg(4,ios::cur);\n    in.read((char*)(data+i*cols),dim*4);\n  }\n  in.close();\n}\nint main(int argc, char** argv){\n  if(argc!=10){cout<< argv[0] << \" data_file save_graph_file trees level epoch L K kNN S\" <<endl; exit(-1);}\n\n  float* data_load = NULL;\n  //float* query_load = NULL;\n  size_t points_num;\n  int dim;\n  load_data(argv[1], data_load, points_num,dim);\n  //size_t q_num;\n  //int qdim;\n  //load_data(argv[3], query_load, q_num,qdim);\n  Matrix<float> dataset(points_num,dim,data_load);\n  //Matrix<float> query(q_num,qdim,query_load);\n\n  unsigned int trees = atoi(argv[3]);\n  int mlevel = atoi(argv[4]);\n  unsigned int epochs = atoi(argv[5]);\n  int L = atoi(argv[6]);\n  int checkK = atoi(argv[7]);\n  int kNN = atoi(argv[8]);\n  int S = atoi(argv[9]);\n\n  //srand(time(NULL));\n  FIndex<float> index(dataset, new L2DistanceAVX<float>(), efanna::KDTreeUbIndexParams(true, trees ,mlevel ,epochs,checkK,L, kNN, trees, S));\nboost::timer::auto_cpu_timer timer;\n\n  index.buildIndex();\ncout<<timer.elapsed().wall / 1e9<<endl;\n  index.saveGraph(argv[2]);\n  return 0;\n}\n", "meta": {"hexsha": "0616d43cc8ff8c99572efa16bafbd00f497a8901", "size": 1867, "ext": "cc", "lang": "C++", "max_stars_repo_path": "samples/efanna_index_buildgraph.cc", "max_stars_repo_name": "Tengke-Xiong/efanna", "max_stars_repo_head_hexsha": "a65bb84e5cd5dc771d61ba181da3bcf8024ae8d3", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 143.0, "max_stars_repo_stars_event_min_datetime": "2017-12-20T12:36:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T20:39:40.000Z", "max_issues_repo_path": "samples/efanna_index_buildgraph.cc", "max_issues_repo_name": "Tengke-Xiong/efanna", "max_issues_repo_head_hexsha": "a65bb84e5cd5dc771d61ba181da3bcf8024ae8d3", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2018-06-15T08:28:21.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-09T17:08:09.000Z", "max_forks_repo_path": "samples/efanna_index_buildgraph.cc", "max_forks_repo_name": "ZJULearning/efanna", "max_forks_repo_head_hexsha": "a65bb84e5cd5dc771d61ba181da3bcf8024ae8d3", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 39.0, "max_forks_repo_forks_event_min_datetime": "2018-02-05T18:55:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-15T13:45:09.000Z", "avg_line_length": 30.606557377, "max_line_length": 141, "alphanum_fraction": 0.6572040707, "num_tokens": 581, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.45081223607509247}}
{"text": "/**\n * SemiCluster Algorithm, written by zhigang wang.\n */\n\n#include <string>\n#include <vector>\n#include <set>\n#include <fstream>\n#include <algorithm>\n#include <graphlab.hpp>\n\n#include <boost/range/iterator_range.hpp>\n\nstruct cluster {\n\tstd::set<int> vertices; // set of vertices, no multiple elements\n\tdouble score; // score of current semi_cluster\n\tdouble innerScore; // inner score\n\tdouble boundaryScore; // boundary score\n\n\tcluster() {\n\t\tscore = 1.0;\n\t\tinnerScore = 0.0;\n\t\tboundaryScore = 0.0;\n\t}\n\n\tcluster(const cluster& c) {\n\t\tfor (std::set<int>::const_iterator iter = c.vertices.begin();\n\t\t\t\titer != c.vertices.end(); ++iter) {\n\t\t\tvertices.insert(*iter);\n\t\t}\n\t\tscore = c.score;\n\t\tinnerScore = c.innerScore;\n\t\tboundaryScore = c.boundaryScore;\n\t}\n\n\t~cluster() {\n\t\tvertices.clear();\n\t\tstd::set<int>().swap(vertices);\n\t}\n\n\tvoid addVertex(const int sid,\n\t\t\tconst std::map<int, double>& edges, const double scoreFactor) {\n\t\tif (vertices.insert(sid).second) {\n\t\t\tif (size() == 1) {\n\t\t\t\tfor (std::map<int, double>::const_iterator iter = edges.begin();\n\t\t\t\t\t\titer != edges.end(); ++iter) {\n\t\t\t\t\tboundaryScore += iter->second;\n\t\t\t\t}\n\t\t\t\tscore = 0.0;\n\t\t\t} else {\n\t\t\t\tfor (std::map<int, double>::const_iterator iter = edges.begin();\n\t\t\t\t\t\titer != edges.end(); ++iter) {\n\t\t\t\t\tif (vertices.find(iter->first) != vertices.end()) {\n\t\t\t\t\t\tinnerScore += iter->second;\n\t\t\t\t\t\tboundaryScore -= iter->second;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tboundaryScore += iter->second;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tscore = (innerScore-scoreFactor*boundaryScore)/(size()*(size()-1)/2);\n\t\t\t}\n\t\t} // insert successfully, i.e. new vertex id\n\t}\n\n\tint size() {\n\t\treturn vertices.size();\n\t}\n\n\tvoid save(graphlab::oarchive& oarc) const {\n\t    oarc << vertices << score << innerScore << boundaryScore;\n\t}\n\n\tvoid load(graphlab::iarchive& iarc) {\n\t    iarc >> vertices >> score >> innerScore >> boundaryScore;\n\t}\n\n\t// override the < operator, used for less order\n\tbool operator<(const cluster& other) const {\n\t\treturn (score<other.score);\n\t}\n\n\t// override the > operator, used for greater order\n\tbool operator>(const cluster& other) const {\n\t\treturn (score>other.score);\n\t}\n};\n\nstruct vertex_data {\n\tstd::vector<cluster> cluster_set;\n\n\tvertex_data() {\n\t}\n\n\t/** only maintain the top-maxClusters clusters based on scores */\n\tvoid update(int maxClusters) {\n\t\tstd::sort(cluster_set.begin(), cluster_set.end(), std::greater<cluster>()); // sort, greater\n\t\tint delNum = cluster_set.size() - maxClusters;\n\t\tif (delNum > 0) {\n\t\t\tfor (int i = 0; i < delNum; ++i) {\n\t\t\t\tcluster_set.pop_back(); // delete the cluster with smaller scores\n\t\t\t}\n\t\t}\n\t}\n\n\t/** return the string of vertex data */\n\tstd::string toString() {\n\t\tstd::stringstream strm;\n\t\tfor (std::vector<cluster>::const_iterator cIter = cluster_set.begin();\n\t\t\t\tcIter != cluster_set.end(); ++cIter) {\n\t\t\tcluster c = *cIter;\n\t\t\tstrm << \"  (\";\n\t\t\tfor (std::set<int>::const_iterator vIter = c.vertices.begin();\n\t\t\t\t\tvIter != c.vertices.end(); ++vIter) {\n\t\t\t\tstrm << *vIter << \",\";\n\t\t\t}\n\t\t\tstrm << c.score << \")\";\n\t\t}\n\t\treturn strm.str();\n\t}\n\n\tvoid save(graphlab::oarchive& oarc) const {\n\t\toarc << cluster_set;\n\t}\n\tvoid load(graphlab::iarchive& iarc) {\n\t\tiarc >> cluster_set;\n\t}\n};\n\nstruct gather_data {\n\tstd::map<int, double> edges;\n\tstd::vector<vertex_data> cluster_sets;\n\n\tgather_data() {\n\t}\n\n\t~gather_data() {\n\t\tedges.clear();\n\t\tstd::map<int, double>().swap(edges);\n\t\tcluster_sets.clear();\n\t\tstd::vector<vertex_data>().swap(cluster_sets);\n\t}\n\n\tgather_data& operator+=(const gather_data& other) {\n\t\tfor (std::map<int, double>::const_iterator iter = other.edges.begin();\n\t\t\t\titer != other.edges.end(); ++iter) {\n\t\t\tedges[iter->first] = iter->second;\n\t\t}\n\n\t\tfor (std::vector<vertex_data>::const_iterator iter = other.cluster_sets.begin();\n\t\t\t\titer != other.cluster_sets.end(); ++iter) {\n\t\t\tcluster_sets.push_back(*iter);\n\t\t}\n\n    return *this;\n  }\n\n  void save(graphlab::oarchive& oarc) const {\n    oarc << edges << cluster_sets;\n  }\n\n  void load(graphlab::iarchive& iarc) {\n    iarc >> edges >> cluster_sets;\n  }\n};\n\nsize_t ITERATIONS = 0;\nint MaxClusters = 2;\nint MaxCapacity = 2;\ndouble ScoreFactor = 0.5;\ndouble EdgeWeight = 0.01;\n\ntypedef vertex_data vertex_data_type;\ntypedef graphlab::empty edge_data_type;\ntypedef gather_data gather_data_type;\n\n// The graph type is determined by the vertex and edge data types\ntypedef graphlab::distributed_graph<vertex_data_type, edge_data_type> graph_type;\n\nvoid initialize_vertex(graph_type::vertex_type& v) {\n\tcluster c;\n\tstd::map<int, double> edges;\n\tc.addVertex(v.id(), edges, ScoreFactor);\n\tv.data().cluster_set.push_back(c);\n} // now, we don't have the edge info, just use the null edges\n\nclass semicluster :\n\tpublic graphlab::ivertex_program<graph_type, gather_data_type>,\n\tpublic graphlab::IS_POD_TYPE {\n\n\tpublic:\n\t\tedge_dir_type gather_edges(icontext_type& context,\n\t\t\t\tconst vertex_type& vertex) const {\n\t\t\treturn graphlab::ALL_EDGES;\n\t\t}\n\n\t\tgather_data_type gather(icontext_type& context,\n\t\t\t\tconst vertex_type& vertex, edge_type& edge) const {\n\t\t\t// figure out which data to get from the edge.\n\t\t\tbool isEdgeSource = (vertex.id()==edge.source().id());\n\t\t\tgather_data_type result;\n\t\t\tif (isEdgeSource) {\n\t\t\t\tstd::pair<int, double> p(edge.target().id(), EdgeWeight);\n\t\t\t\tresult.edges.insert(p);\n\t\t\t\tresult.cluster_sets.push_back(edge.target().data());\n\t\t\t} else {\n\t\t\t\tstd::pair<int, double> p(edge.source().id(), EdgeWeight);\n\t\t\t\tresult.edges.insert(p);\n\t\t\t\tresult.cluster_sets.push_back(edge.source().data());\n\t\t\t}\n\n\t\t\treturn result;\n\t\t}\n\n\t\tvoid apply(icontext_type& context, vertex_type& vertex,\n\t\t\t\tconst gather_type& total) {\n\t\t\tbool changed = true;\n\n\t\t\tfor (std::vector<vertex_data>::const_iterator iter = total.cluster_sets.begin();\n\t\t\t\t\titer != total.cluster_sets.end(); ++iter) {\n\t\t\t\tvertex_data neighbor = *iter;\n\t\t\t\tint len = neighbor.cluster_set.size();\n\t\t\t\tfor (int i = 0; i < len; ++i) {\n\t\t\t\t\tcluster c = neighbor.cluster_set[i];\n\t\t\t\t\tbool isContained = (c.vertices.find(vertex.id()) != c.vertices.end());\n\t\t\t\t\tif (!isContained && c.size()<MaxCapacity) {\n\t\t\t\t\t\tcluster newC(c);\n\t\t\t\t\t\tnewC.addVertex(vertex.id(), total.edges, ScoreFactor);\n\t\t\t\t\t\tvertex.data().cluster_set.push_back(newC);\n\t\t\t\t\t} else if (isContained) {\n\t\t\t\t\t\tvertex.data().cluster_set.push_back(c);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tvertex.data().update(MaxClusters);\n\n\t\t\tcontext.setUpdateFlag(changed);\n\t\t\tcontext.signal(vertex);\n\t\t\t//vertex.num_in_edges();\n\t\t\t//std::cout << vertex.id() << \"\\t\" << vertex.data().toString() << \"\\n\";\n\t\t\t//std::cout << vertex.in_edges() << std::endl; // interrupted, no implemented!\n\t\t}\n\n\t\tedge_dir_type scatter_edges(icontext_type& context,\n\t\t\t\tconst vertex_type& vertex) const {\n\t\t\t//return graphlab::ALL_EDGES;\n\t\t\treturn graphlab::NO_EDGES;\n\t\t}\n\n\t\tvoid scatter(icontext_type& context,\n\t\t\t\tconst vertex_type& vertex, edge_type& edge) const {\n\t\t\tbool isEdgeSource = (vertex.id()==edge.source().id());\n\t\t\tcontext.signal(isEdgeSource ? edge.target() : edge.source());\n\t\t}\n\t};\n\nstruct semicluster_writer {\n  std::string save_vertex(graph_type::vertex_type v) {\n    std::stringstream strm;\n    strm << v.id() << \"\\t\" << v.data().toString() << \"\\n\";\n    return strm.str();\n  }\n  std::string save_edge (graph_type::edge_type e) { return \"\"; }\n};\n\n\nint main(int argc, char** argv) {\n  std::cout << \"SemiCluster\\n\";\n\n  // Initialize control plain using mpi\n  graphlab::mpi_tools::init(argc, argv);\n  graphlab::distributed_control dc;\n  global_logger().set_log_level(LOG_INFO);\n\n  // Parse command line options -----------------------------------------------\n  graphlab::command_line_options clopts(\"SemiCluster algorithm.\");\n  std::string graph_dir;\n  std::string saveprefix;\n  std::string format = \"adj\";\n  std::string execution_type = \"synchronous\";\n\n  //disk\n  size_t ver_block_size = 1;\n  size_t ver_buf_block_num = 1;\n  size_t edge_block_size = 1;\n  size_t useVerDisk = 0;\n  size_t useEdgeDisk = 0;\n\n  clopts.attach_option(\"graph\", graph_dir, \"The graph file. Required \");\n  clopts.add_positional(\"graph\");\n  clopts.attach_option(\"format\", format,\n                         \"The graph file format\");\n  clopts.attach_option(\"saveprefix\", saveprefix,\n                       \"If set, will save the resultant label propagation to a \"\n                       \"sequence of files with prefix saveprefix\");\n  clopts.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) label propagation for a fixed \"\n                         \"number of iterations. Also overrides the iterations \"\n                         \"option in the engine\");\n\n  clopts.attach_option(\"ver_block_size\", ver_block_size,\n  \t\t  \"the number of vertices per vertex block\");\n  clopts.add_positional(\"ver_block_size\");\n\n  clopts.attach_option(\"ver_buf_block_num\", ver_buf_block_num,\n\t\t  \"the number of blocks in vertex buffer\");\n  clopts.add_positional(\"ver_buf_block_num\");\n\n  clopts.attach_option(\"edge_block_size\", edge_block_size,\n\t\t  \"the size of each edge block, i.e. the number of source/target vertices\");\n  clopts.add_positional(\"edge_block_size\");\n\n  clopts.attach_option(\"useVerDisk\", useVerDisk,\n  \t\t  \"useVerDisk or not? =0:false, =1:true\");\n  clopts.add_positional(\"useVerDisk\");\n\n  clopts.attach_option(\"useEdgeDisk\", useEdgeDisk,\n  \t\t  \"useEdgeDisk or not? =0:false, =1:true\");\n  clopts.add_positional(\"useEdgeDisk\");\n\n  //! All input parameters cannot be used before .parse() is invoked.\n  if(!clopts.parse(argc, argv)) {\n    dc.cout() << \"Error in parsing command line arguments.\" << std::endl;\n    return EXIT_FAILURE;\n  }\n  if (graph_dir == \"\") {\n    dc.cout() << \"Graph not specified. Cannot continue\";\n    return EXIT_FAILURE;\n  }\n\n  // Enable gather caching in the engine\n  clopts.get_engine_args().set_option(\"use_cache\", false);\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\n  clopts.setVerBlockSize(ver_block_size);\n  clopts.setVerBufBlockNum(ver_buf_block_num);\n  clopts.setEdgeBlockSize(edge_block_size);\n  clopts.setUseVerDisk(useVerDisk);\n  clopts.setUseEdgeDisk(useEdgeDisk);\n\n  // Build the graph ----------------------------------------------------------\n  graph_type graph(dc, clopts);\n  dc.cout() << \"Loading graph in format: \"<< format << std::endl;\n  graphlab::timer load_timer;\n  graph.load_format(graph_dir, format);\n  // must call finalize before querying the graph\n  graph.finalize();\n  graph.transform_vertices(initialize_vertex);\n  dc.cout() << \"Finished loading in \" << load_timer.current_time() << std::endl;\n  dc.cout() << \"global #vertices: \" << graph.num_vertices()\n\t\t    << \"\\nglobal #edges:\" << graph.num_edges() << std::endl;\n\n  // Run the engine\n  graphlab::omni_engine<semicluster> engine(dc, graph, execution_type, clopts);\n  engine.signal_all();\n  engine.start();\n  const float runtime = engine.elapsed_seconds();\n  dc.cout() << \"Finished running engine in \" << runtime << \" seconds.\" << std::endl;\n\n  if (saveprefix != \"\") {\n    graph.save(saveprefix, semicluster_writer(),\n       false,  // do not gzip\n       true,   // save vertices\n       false,  // do not save edges\n       1);     // #_of_files per machine\n  }\n\n  graphlab::mpi_tools::finalize();\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "1903183da2efa8feb7663ec798b1de3d43b181a6", "size": 11612, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "toolkits/graph_analytics/semicluster.cpp", "max_stars_repo_name": "HybridGraph/GraphLab-PowerGraph", "max_stars_repo_head_hexsha": "ba333c1cd82325ab2bfc6dd7ebb871b3fff64a94", "max_stars_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-05-27T15:45:48.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-15T23:47:03.000Z", "max_issues_repo_path": "toolkits/graph_analytics/semicluster.cpp", "max_issues_repo_name": "HybridGraph/GraphLab-PowerGraph", "max_issues_repo_head_hexsha": "ba333c1cd82325ab2bfc6dd7ebb871b3fff64a94", "max_issues_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "toolkits/graph_analytics/semicluster.cpp", "max_forks_repo_name": "HybridGraph/GraphLab-PowerGraph", "max_forks_repo_head_hexsha": "ba333c1cd82325ab2bfc6dd7ebb871b3fff64a94", "max_forks_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4776902887, "max_line_length": 94, "alphanum_fraction": 0.6559593524, "num_tokens": 2990, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.45081223607509247}}
{"text": "\n\n#include <deal.II/base/conditional_ostream.h>\n#include <deal.II/base/function.h>\n#include <deal.II/base/index_set.h>\n#include <deal.II/base/logstream.h>\n#include <deal.II/base/parameter_handler.h>\n#include <deal.II/base/quadrature_lib.h>\n#include <deal.II/base/tensor_function.h>\n#include <deal.II/base/timer.h>\n#include <deal.II/base/utilities.h>\n\n#include <deal.II/lac/generic_linear_algebra.h>\nnamespace LA {\nusing namespace dealii::LinearAlgebraPETSc;\n#define USE_PETSC_LA\n} // namespace LA\n\n#include <deal.II/lac/dynamic_sparsity_pattern.h>\n#include <deal.II/lac/full_matrix.h>\n#include <deal.II/lac/vector.h>\n//#include <deal.II/lac/sparse_matrix.h>\n#include <deal.II/lac/constraint_matrix.h>\n#include <deal.II/lac/precondition.h>\n#include <deal.II/lac/solver_bicgstab.h>\n#include <deal.II/lac/solver_cg.h>\n#include <deal.II/lac/sparsity_tools.h>\n//#include <deal.II/lac/petsc_precondition.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\n#include <deal.II/dofs/dof_accessor.h>\n#include <deal.II/dofs/dof_handler.h>\n#include <deal.II/dofs/dof_tools.h>\n#include <deal.II/dofs/dof_renumbering.h>\n\n#include <deal.II/fe/fe_dgq.h>\n#include <deal.II/fe/fe_q.h>\n#include <deal.II/fe/fe_values.h>\n#include <deal.II/fe/fe_system.h>\n\n#include <deal.II/numerics/data_out.h>\n#include <deal.II/numerics/error_estimator.h>\n#include <deal.II/numerics/vector_tools.h>\n#include <deal.II/numerics/solution_transfer.h>\n//#include <deal.II/numerics/matrix_tools.h>\n\n\n#include <deal.II/lac/petsc_parallel_sparse_matrix.h>\n#include <deal.II/lac/petsc_parallel_vector.h>\n#include <deal.II/lac/petsc_precondition.h>\n#include <deal.II/lac/petsc_solver.h>\n\n#include <deal.II/distributed/grid_refinement.h>\n#include <deal.II/distributed/tria.h>\n#include <deal.II/grid/filtered_iterator.h>\n\n#include <deal.II/distributed/solution_transfer.h>\n\n\n#include <fstream>\n#include <iostream>\n\n#include \"level_set_solver.h\"\n#include \"material_data.h\"\n#include \"my_utility_functions.h\"\n#include \"parameters.h\"\n#include \"physical_functions.h\"\n\nnamespace CPPLS {\nusing namespace dealii;\n\nconstexpr double inflow_rate {-3.15e-11};\n\ntemplate <int dim>\nclass LayerMovementProblem {\npublic:\n    LayerMovementProblem(const CPPLS::Parameters& parameters, const CPPLS::MaterialData& material_data);\n    ~LayerMovementProblem();\n    void run();\n\nprivate:\n\n    // Member Data\n    // runtime parameters\n    const CPPLS::Parameters parameters;\n    const CPPLS::MaterialData material_data;\n\n    // mpi communication\n    MPI_Comm mpi_communicator;\n    const unsigned int n_mpi_processes;\n    const unsigned int this_mpi_process;\n\n    // mesh\n    parallel::distributed::Triangulation<dim> triangulation;\n\n    // FE basis space (for P,T, F, and sigma)\n    // LS separate\n\n    // pressure\n    int degree;\n    DoFHandler<dim> dof_handler;\n    FE_Q<dim> fe;\n    IndexSet locally_owned_dofs;\n    IndexSet locally_relevant_dofs;\n\n\n    int degree_LS;\n    DoFHandler<dim> dof_handler_LS;\n    FE_Q<dim> fe_LS;\n    IndexSet locally_owned_dofs_LS;\n    IndexSet locally_relevant_dofs_LS;\n\n    // output stream where only mpi rank 0 output gets to stdout\n    ConditionalOStream pcout;\n\n    TimerOutput computing_timer;\n\n    double time_step;\n    double current_time;\n    double output_number;\n    double final_time;\n    int timestep_number;\n    int out_index;\n\n    // set timestepping scheme 1 implicit euler, 1/2 CN, 0 explicit euler\n    const double theta;\n\n    ConstraintMatrix constraints_P;\n    ConstraintMatrix constraints_T;\n    ConstraintMatrix constraints_LS;\n    ConstraintMatrix constraints_F;\n    ConstraintMatrix constraints_Sigma;\n\n    // FE Field Solution Vectors\n    // Ghosted\n    // LS\n    LA::MPI::Vector locally_relevant_solution_LS_0; // ls\n    LA::MPI::Vector old_locally_relevant_solution_LS_0;\n\n    // Pressure\n    LA::MPI::Vector locally_relevant_solution_P;\n    LA::MPI::Vector old_locally_relevant_solution_P;\n    // for use in nonlinear iteration\n    LA::MPI::Vector temp_locally_relevant_solution_P;\n    LA::MPI::Vector old_temp_locally_relevant_solution_P;\n\n    // Temperature\n\n    LA::MPI::Vector locally_relevant_solution_T;\n    LA::MPI::Vector old_locally_relevant_solution_T;\n\n    // Speed function\n    LA::MPI::Vector locally_relevant_solution_F;\n\n    // this is 0 now\n    LA::MPI::Vector locally_relevant_solution_Wxy;\n\n    // Overburden\n    LA::MPI::Vector locally_relevant_solution_Sigma;\n    LA::MPI::Vector old_locally_relevant_solution_Sigma;\n    LA::MPI::Vector temp_locally_relevant_solution_Sigma;\n\n    // Non-ghosted\n    LA::MPI::Vector completely_distributed_solution_LS_0;\n    LA::MPI::Vector completely_distributed_solution_P;\n    LA::MPI::Vector completely_distributed_solution_T;\n    LA::MPI::Vector completely_distributed_solution_F;\n    LA::MPI::Vector completely_distributed_solution_Sigma;\n\n    LA::MPI::Vector rhs_P;\n    LA::MPI::Vector old_rhs_P;\n    LA::MPI::Vector system_rhs_P;\n\n    LA::MPI::Vector rhs_T;\n    LA::MPI::Vector old_rhs_T;\n    LA::MPI::Vector system_rhs_T;\n\n    LA::MPI::Vector rhs_Sigma;\n\n    LA::MPI::Vector rhs_F;\n\n    // Sparse Matrices\n    LA::MPI::SparseMatrix laplace_matrix_P;\n    LA::MPI::SparseMatrix mass_matrix_P;\n    LA::MPI::SparseMatrix system_matrix_P;\n\n    LA::MPI::SparseMatrix laplace_matrix_T;\n    LA::MPI::SparseMatrix mass_matrix_T;\n    LA::MPI::SparseMatrix system_matrix_T;\n\n    LA::MPI::SparseMatrix system_matrix_F;\n\n    LA::MPI::SparseMatrix system_matrix_Sigma;\n\n    // for LS boundary conditions\n    std::vector<unsigned int> boundary_values_id_LS;\n    std::vector<double> boundary_values_LS;\n\n    std::vector<std::unique_ptr<LevelSetSolver<dim>>> layers;\n    std::vector<std::unique_ptr<LA::MPI::Vector>> layers_solutions;\n    std::vector<std::unique_ptr<parallel::distributed::SolutionTransfer<dim,LA::MPI::Vector>>> layers_transfers;\n    int n_layers;\n\n\n    // Member Functions\n\n    // create mesh\n    void setup_geometry();\n\n    // create fe space\n    void setup_dofs();\n\n\n    // create appropriately sized vectors and matrices\n    void setup_system_P();\n    void setup_system_T();\n    void setup_system_LS();\n    void setup_system_F();\n    void setup_system_Sigma();\n\n    void initial_conditions();\n    void set_boundary_inlet();\n    void get_boundary_values_LS(std::vector<unsigned int>& boundary_values_id_LS,\n                                std::vector<double>& boundary_values_LS);\n\n    // use level set values to set cell->material_id\n    void setup_material_configuration();\n\n    // Pressure\n    void assemble_matrices_P();\n    void forge_system_P();\n    void solve_time_step_P();\n    // Temperature\n    void assemble_matrices_T();\n    void forge_system_T();\n    void solve_time_step_T();\n\n    // symbol used for overburden is Sigma\n    void assemble_Sigma();\n    void solve_Sigma();\n\n    // Speed function (scalar)\n    void assemble_F();\n    void solve_F();\n\n    double estimate_nl_error();\n    int active_layers_in_time(double time);\n\n    void refine_mesh();\n    void prepare_next_time_step();\n\n    void output_vectors_LS();\n    void output_vectors();\n    void output_results_pp();\n\n    void display_vectors()\n    {\n        output_vectors_LS();\n        output_vectors();\n        output_results_pp();\n        output_number++;\n    }\n\n\n    class Postprocessor;\n\n\n\n};\n\n// Constructor\n\ntemplate <int dim>\nLayerMovementProblem<dim>::LayerMovementProblem(const CPPLS::Parameters& parameters,\n        const CPPLS::MaterialData& material_data)\n    : parameters(parameters)\n    , material_data(material_data)\n    , mpi_communicator(MPI_COMM_WORLD)\n    , n_mpi_processes {Utilities::MPI::n_mpi_processes(mpi_communicator)}\n, this_mpi_process {Utilities::MPI::this_mpi_process(mpi_communicator)}\n, triangulation(mpi_communicator,\n                typename Triangulation<dim>::MeshSmoothing(Triangulation<dim>::smoothing_on_refinement |\n                        Triangulation<dim>::smoothing_on_coarsening))\n, degree(parameters.degree)\n, degree_LS(parameters.degree_LS)\n, fe(degree)\n, fe_LS(degree_LS)\n, dof_handler(triangulation)\n, dof_handler_LS(triangulation)\n, pcout(std::cout, (Utilities::MPI::this_mpi_process(mpi_communicator) == 0))\n, computing_timer(mpi_communicator, pcout, TimerOutput::summary, TimerOutput::wall_times)\n, time_step((parameters.stop_time - parameters.start_time) / parameters.n_time_steps)\n, current_time {0}\n, final_time {parameters.stop_time}\n, output_number {0}\n, out_index{0}\n, theta(parameters.theta)\n{};\n\n// Destructor\ntemplate <int dim>\nLayerMovementProblem<dim>::~LayerMovementProblem()\n{\n    dof_handler.clear();\n    dof_handler_LS.clear();\n    triangulation.clear();\n}\n\n//\ntemplate <int dim>\nvoid LayerMovementProblem<dim>::setup_geometry()\n{\n    TimerOutput::Scope t(computing_timer, \"setup_geometry\");\n    GridGenerator::hyper_cube(triangulation, 0, parameters.box_size, true);\n    // GridGenerator::subdivided_hyper_rectangle(triangulation, 0, parameters.box_size);\n    triangulation.refine_global(parameters.initial_refinement_level);\n    // print_mesh_info(triangulation, \"my_grid\");\n    for (auto cell : filter_iterators(triangulation.active_cell_iterators(), IteratorFilters::LocallyOwnedCell())) {\n        cell->set_material_id(0);\n    }\n}\n\ntemplate <int dim>\nvoid LayerMovementProblem<dim>::setup_dofs()\n{\n    TimerOutput::Scope t(computing_timer, \"setup_dofs\");\n\n\n    dof_handler.distribute_dofs(fe);\n    locally_owned_dofs = dof_handler.locally_owned_dofs();\n    DoFTools::extract_locally_relevant_dofs(dof_handler, locally_relevant_dofs);\n    //TODO: put out the sparsity patterns\n    //Point<dim> direction (0,-1);\n    //locally_owned_dofs = dof_handler.locally_owned_dofs();\n\n    std::vector<types::global_dof_index> starting_indices;\n    starting_indices.clear();\n\n    std::cout<<dof_handler.n_locally_owned_dofs();\n\n\n    //re-check this algorithm for AMR case\n    //how to get face normals without FEFaceValues TODO\n//    const QMidpoint<dim - 1> face_quadrature_formula;\n//    FEFaceValues<dim> fe_face_values(fe, face_quadrature_formula,\n//                                     update_values | update_quadrature_points | update_normal_vectors |\n//                                     update_JxW_values);\n\n//    Tensor<1, dim> u;\n//    Point<dim> down;\n//    down(dim-1)=-1;\n\n\n//    std::vector< types::global_dof_index >dof_indices (fe.n_dofs_per_face(), 0);\n\n\n//    for (const auto &cell: dof_handler.active_cell_iterators())\n//    {\n//        if(cell->is_locally_owned())\n//        {\n\n//            for (unsigned int face = 0; face < GeometryInfo<dim>::faces_per_cell; ++face)\n//            {\n//                if ((cell->face(face)->at_boundary()) || (cell->neighbor(face)->is_ghost()))\n//                {\n//                    fe_face_values.reinit(cell, face);\n//                    u=fe_face_values.normal_vector(0);\n//                    if(u*down< 0)\n//                    {\n//                        cell->face(face)->get_dof_indices(dof_indices);\n//                        starting_indices.insert(std::end(starting_indices),\n//                                                std::begin(dof_indices), std::end(dof_indices));\n//                    }\n//                }\n//            }\n//        }\n//    }\n\n////  //remove duplicates by creating a set\n//    std::set<types::global_dof_index> no_duplicates_please (starting_indices.begin(),\n//            starting_indices.end());\n////  //back to vector for the DoFRenumbering function\n////  starting_indices.clear();\n//    starting_indices.assign(no_duplicates_please.begin(), no_duplicates_please.end());\n////  starting_indices.insert(std::end(starting_indices),\n////                                 std::begin(no_duplicates_please), std::end(no_duplicates_please));\n\n//    //starting_indices=locally_owned_dofs;\n//// DoFTools::extract_locally_owned_dofs(dof_handler, starting_indices);\n     DoFRenumbering::Cuthill_McKee(dof_handler,false, true, starting_indices);\n//    //Not working in parallel now\n//    //DoFRenumbering::downstream(dof_handler, direction, true);\n\n\n    pcout << std::endl\n          << \"============DofHandler===============\" << std::endl\n          << \"Number of active cells: \" << triangulation.n_global_active_cells() << std::endl\n          << \"Number of degrees of freedom: \" << dof_handler.n_dofs() << std::endl\n          << std::endl;\n\n  locally_owned_dofs = dof_handler.locally_owned_dofs();\n  DoFTools::extract_locally_relevant_dofs(dof_handler, locally_relevant_dofs);\n}\n\ntemplate <int dim>\nvoid LayerMovementProblem<dim>::setup_system_P()\n{\n    TimerOutput::Scope t(computing_timer, \"setup_P\");\n\n    pcout << std::endl << \"============Pressure===============\" << std::endl << std::endl;\n\n    // vector setup\n    locally_relevant_solution_P.reinit(locally_owned_dofs, locally_relevant_dofs, mpi_communicator);\n    temp_locally_relevant_solution_P.reinit(locally_owned_dofs, locally_relevant_dofs, mpi_communicator);\n    old_temp_locally_relevant_solution_P.reinit(locally_owned_dofs, locally_relevant_dofs, mpi_communicator);\n\n    completely_distributed_solution_P.reinit(locally_owned_dofs, mpi_communicator);\n\n    old_locally_relevant_solution_P.reinit(locally_owned_dofs, locally_relevant_dofs, mpi_communicator);\n    rhs_P.reinit(locally_owned_dofs, mpi_communicator);\n    old_rhs_P.reinit(locally_owned_dofs, mpi_communicator);\n\n    system_rhs_P.reinit(locally_owned_dofs, mpi_communicator);\n\n    // constraints\n\n    constraints_P.clear();\n\n    constraints_P.reinit(locally_relevant_dofs);\n\n    DoFTools::make_hanging_node_constraints(dof_handler, constraints_P);\n    // zero dirichlet at top\n    //the \"top\" has boundary_id = dim*2-1; (so 3 for 2d, 5 for 3d)\n    VectorTools::interpolate_boundary_values(dof_handler, dim*2-1, ZeroFunction<dim>(),\n            constraints_P);\n    constraints_P.close();\n\n    // create sparsity pattern\n\n    DynamicSparsityPattern dsp(locally_relevant_dofs);\n\n    DoFTools::make_sparsity_pattern(dof_handler, dsp, constraints_P, false);\n    SparsityTools::distribute_sparsity_pattern(dsp, dof_handler.n_locally_owned_dofs_per_processor(), mpi_communicator,\n            locally_relevant_dofs);\n    // setup matrices\n\n    system_matrix_P.reinit(locally_owned_dofs, locally_owned_dofs, dsp, mpi_communicator);\n    laplace_matrix_P.reinit(locally_owned_dofs, locally_owned_dofs, dsp, mpi_communicator);\n    mass_matrix_P.reinit(locally_owned_dofs, locally_owned_dofs, dsp, mpi_communicator);\n}\n\ntemplate <int dim>\nvoid LayerMovementProblem<dim>::setup_system_T()\n{\n    TimerOutput::Scope t(computing_timer, \"setup_system_T\");\n\n    pcout << std::endl << \"============Temperature===============\" << std::endl << std::endl;\n\n    // vector setup\n    locally_relevant_solution_T.reinit(locally_owned_dofs, locally_relevant_dofs, mpi_communicator);\n    old_locally_relevant_solution_T.reinit(locally_owned_dofs, locally_relevant_dofs, mpi_communicator);\n    completely_distributed_solution_T.reinit(locally_owned_dofs, mpi_communicator);\n\n    rhs_T.reinit(locally_owned_dofs, mpi_communicator);\n    old_rhs_T.reinit(locally_owned_dofs, mpi_communicator);\n    system_rhs_T.reinit(locally_owned_dofs, mpi_communicator);\n\n    // constraints\n\n    constraints_T.clear();\n    constraints_T.reinit(locally_relevant_dofs);\n\n    DoFTools::make_hanging_node_constraints(dof_handler, constraints_T);\n    // zero dirichlet at top\n    //the \"top\" has boundary_id = dim*2-1; (so 3 for 2d, 5 for 3d)\n    VectorTools::interpolate_boundary_values(dof_handler, dim*2-1, ZeroFunction<dim>(),\n            constraints_T); // TODO again raw number for boundary_id\n    // Keep top at fixed temperature, TODO check compatibility condition\n    // VectorTools::interpolate_boundary_values(dof_handler_T, 3, ConstantFunction<dim>(20), constraints_T);\n    constraints_T.close();\n\n    // create sparsity pattern\n\n    DynamicSparsityPattern dsp(locally_relevant_dofs);\n    DoFTools::make_sparsity_pattern(dof_handler, dsp, constraints_T, false);\n    SparsityTools::distribute_sparsity_pattern(dsp, dof_handler.n_locally_owned_dofs_per_processor(), mpi_communicator,\n            locally_relevant_dofs);\n    // setup matrices\n\n    system_matrix_T.reinit(locally_owned_dofs, locally_owned_dofs, dsp, mpi_communicator);\n    laplace_matrix_T.reinit(locally_owned_dofs, locally_owned_dofs, dsp, mpi_communicator);\n    mass_matrix_T.reinit(locally_owned_dofs, locally_owned_dofs, dsp, mpi_communicator);\n}\n\ntemplate <int dim>\nvoid LayerMovementProblem<dim>::setup_system_Sigma()\n{\n    // First of two SUPG problems\n    TimerOutput::Scope t(computing_timer, \"setup_system_Sigma\");\n\n    pcout << std::endl << \"============Overburden===============\" << std::endl << std::endl;\n\n    // vector setup\n    locally_relevant_solution_Sigma.reinit(locally_owned_dofs, locally_relevant_dofs, mpi_communicator);\n    old_locally_relevant_solution_Sigma.reinit(locally_owned_dofs, locally_relevant_dofs, mpi_communicator);\n    //temp_locally_relevant_solution_Sigma.reinit(locally_owned_dofs, locally_relevant_dofs, mpi_communicator);\n\n    completely_distributed_solution_Sigma.reinit(locally_owned_dofs, mpi_communicator);\n    rhs_Sigma.reinit(locally_owned_dofs, mpi_communicator);\n\n    // constraints\n\n    constraints_Sigma.clear();\n    constraints_Sigma.reinit(locally_relevant_dofs);\n\n    DoFTools::make_hanging_node_constraints(dof_handler, constraints_Sigma);\n\n    // inflow bc at top\n    //the \"top\" has boundary_id = dim*2-1; (so 3 for 2d, 5 for 3d)\n//VectorTools::interpolate_boundary_values(dof_handler, 3, ConstantFunction<dim>(inflow_rate*15000),\n//                                           constraints_Sigma); // TODO put in sedimentation(x,y,t)\n    VectorTools::interpolate_boundary_values(dof_handler, dim*2-1, ZeroFunction<dim>(),\n            constraints_Sigma);\n    constraints_Sigma.close();\n\n    // create sparsity pattern\n\n    DynamicSparsityPattern dsp(locally_relevant_dofs);\n    DoFTools::make_sparsity_pattern(dof_handler, dsp, constraints_Sigma, false);\n    SparsityTools::distribute_sparsity_pattern(dsp, dof_handler.n_locally_owned_dofs_per_processor(), mpi_communicator,\n            locally_relevant_dofs);\n    // setup matrix\n\n    system_matrix_Sigma.reinit(locally_owned_dofs, locally_owned_dofs, dsp, mpi_communicator);\n}\n\ntemplate <int dim>\nvoid LayerMovementProblem<dim>::setup_system_F()\n{\n    // Second of two SUPG problems\n    TimerOutput::Scope t(computing_timer, \"setup_system_F\");\n\n    pcout << std::endl << \"============Speed Function===============\" << std::endl << std::endl;\n\n    // vector setup\n    locally_relevant_solution_F.reinit(locally_owned_dofs, locally_relevant_dofs, mpi_communicator);\n\n    completely_distributed_solution_F.reinit(locally_owned_dofs, mpi_communicator);\n\n    rhs_F.reinit(locally_owned_dofs, mpi_communicator);\n\n    // constraints\n\n    constraints_F.clear();\n    constraints_F.reinit(locally_relevant_dofs);\n\n    DoFTools::make_hanging_node_constraints(dof_handler, constraints_F);\n    SedimentationRate<dim> sedrate(current_time, parameters);\n    sedrate.set_time(current_time);\n\n    // inflow bc at top\n    //the \"top\" has boundary_id = dim*2-1; (so 3 for 2d, 5 for 3d)\n    VectorTools::interpolate_boundary_values(dof_handler, dim*2-1, sedrate,\n            constraints_F);\n    constraints_F.close();\n\n    // create sparsity pattern\n\n    DynamicSparsityPattern dsp(locally_relevant_dofs);\n    DoFTools::make_sparsity_pattern(dof_handler, dsp, constraints_F, false);\n    SparsityTools::distribute_sparsity_pattern(dsp, dof_handler.n_locally_owned_dofs_per_processor(), mpi_communicator,\n            locally_relevant_dofs);\n    // setup matrix\n\n    system_matrix_F.reinit(locally_owned_dofs, locally_owned_dofs, dsp, mpi_communicator);\n}\n\ntemplate <int dim>\nvoid LayerMovementProblem<dim>::setup_system_LS()\n{\n    // Note: just solution vectors here, no matrices\n    TimerOutput::Scope t(computing_timer, \"setup_system_LS\");\n\n    dof_handler_LS.distribute_dofs(fe_LS);\n\n    pcout << std::endl\n          << \"============LEVEL SETS===============\" << std::endl\n          << \"Number of active cells: \" << triangulation.n_global_active_cells() << std::endl\n          << \"Number of degrees of freedom: \" << dof_handler_LS.n_dofs() << std::endl\n          << std::endl;\n\n    locally_owned_dofs_LS = dof_handler_LS.locally_owned_dofs();\n    DoFTools::extract_locally_relevant_dofs(dof_handler_LS, locally_relevant_dofs_LS);\n\n    // vector setup\n    locally_relevant_solution_LS_0.reinit(locally_owned_dofs_LS, locally_relevant_dofs_LS, mpi_communicator);\n\n    completely_distributed_solution_LS_0.reinit(locally_owned_dofs_LS, mpi_communicator);\n\n    // non-vertical zero vector to feed into LevelSetSolver\n    locally_relevant_solution_Wxy.reinit(locally_owned_dofs_LS, locally_relevant_dofs_LS, mpi_communicator);\n\n\n    // constraints\n\n    constraints_LS.clear();\n\n    constraints_LS.reinit(locally_relevant_dofs_LS);\n\n    DoFTools::make_hanging_node_constraints(dof_handler_LS, constraints_LS);\n\n    constraints_LS.close();\n}\n\ntemplate <int dim>\nvoid LayerMovementProblem<dim>::initial_conditions()\n{\n    // Precondition: the non/ghosted vectors have been initialized, and constraints closed (in setup functions)\n    //For P, T, 0 initial values\n\n    // init condition for P (TODO should use call to VectorTools::interpolate)\n    completely_distributed_solution_P = 0;\n    //VectorTools::interpolate_boundary_values(dof_handler, /*top boundary*/ 3, ZeroFunction<dim>(), constraints_P);\n    VectorTools::interpolate(dof_handler, ZeroFunction<dim>(), completely_distributed_solution_P);\n    constraints_P.distribute(completely_distributed_solution_P);\n    locally_relevant_solution_P = completely_distributed_solution_P;\n\n    // init condition for T   //TODO\n    completely_distributed_solution_T = 0;\n    //VectorTools::interpolate_boundary_values(dof_handler, /*top boundary*/ 3, ZeroFunction<dim>(), constraints_T);\n    VectorTools::interpolate(dof_handler, ZeroFunction<dim>(),completely_distributed_solution_T);\n    constraints_T.distribute(completely_distributed_solution_T);\n    locally_relevant_solution_T = completely_distributed_solution_T;\n\n    // init condition for LS\n    // all the others will share this\n    completely_distributed_solution_LS_0 = 0;\n    const double min_h = GridTools::minimal_cell_diameter(triangulation) / std::sqrt(2);\n    pcout <<\"min_h is:\"<<min_h<<std::endl;\n\n    VectorTools::interpolate(dof_handler_LS, Initial_LS<dim>(min_h, parameters.box_size),\n                             completely_distributed_solution_LS_0);\n    constraints_LS.distribute(completely_distributed_solution_LS_0);\n    locally_relevant_solution_LS_0 = completely_distributed_solution_LS_0;\n\n}\n\ntemplate <int dim>\nvoid LayerMovementProblem<dim>::get_boundary_values_LS(std::vector<unsigned int>& boundary_values_id_LS,\n        std::vector<double>& boundary_values_LS)\n{\n    std::map<unsigned int, double> map_boundary_values_LS;\n    unsigned int boundary_id = 0;\n\n    // set_boundary_inlet();\n    boundary_id = 10; // inlet\n    // we define the inlet to be at the top, i.e. boundary_id=3\n    //the \"top\" has boundary_id = dim*2-1; (so 3 for 2d, 5 for 3d)\n    VectorTools::interpolate_boundary_values(dof_handler_LS, dim*2-1, BoundaryPhi<dim>(1.0), map_boundary_values_LS);\n    boundary_values_id_LS.resize(map_boundary_values_LS.size());\n    boundary_values_LS.resize(map_boundary_values_LS.size());\n    std::map<unsigned int, double>::const_iterator boundary_value_LS = map_boundary_values_LS.begin();\n    for (int i = 0; boundary_value_LS != map_boundary_values_LS.end(); ++boundary_value_LS, ++i) {\n        boundary_values_id_LS[i] = boundary_value_LS->first;\n        boundary_values_LS[i] = boundary_value_LS->second;\n    }\n}\n\ntemplate <int dim>\nvoid LayerMovementProblem<dim>::assemble_Sigma()\n{\n    TimerOutput::Scope t(computing_timer, \"assemble_Sigma\");\n    const AdvectionField<dim> advection_field;\n    const QGauss<dim> quadrature_formula(degree + 2);\n    const QGauss<dim - 1> face_quadrature_formula(degree + 1);\n\n    FEValues<dim> fe_values(fe, quadrature_formula,\n                            update_values | update_quadrature_points | update_JxW_values | update_gradients);\n\n//    FEFaceValues<dim> fe_face_values(fe, face_quadrature_formula,\n//                                     update_values | update_quadrature_points | update_normal_vectors |\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    const unsigned int n_face_q_points = face_quadrature_formula.size();\n\n    std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell);\n\n    std::vector<double> rhs_at_quad(n_q_points);\n    std::vector<Tensor<1, dim>> advection_directions(n_q_points);\n//    std::vector<Tensor<1, dim>> face_advection_directions(n_face_q_points);\n\n\n    std::vector<double> overburden_at_quad(n_q_points);\n    std::vector<double> pressure_at_quad(n_q_points);\n\n    Point<dim> point_for_depth;\n    SedimentationRate<dim> sedRate(current_time, parameters); // rate is a negative quantity\n\n    std::vector<double> sedimentation_rate(n_q_points);\n\n    Vector<double> cell_rhs(dofs_per_cell);\n    FullMatrix<double> cell_matrix(dofs_per_cell, dofs_per_cell);\n\n    rhs_Sigma = 0;\n    system_matrix_Sigma = 0;\n\n    for (auto cell : filter_iterators(dof_handler.active_cell_iterators(), IteratorFilters::LocallyOwnedCell())) {\n\n        fe_values.reinit(cell);\n        fe_values.get_function_values(locally_relevant_solution_P, pressure_at_quad);\n        fe_values.get_function_values(locally_relevant_solution_Sigma, overburden_at_quad);\n\n        // TODO consider moving these properties to the quad point level, not just cell level\n        const double initial_porosity = material_data.get_surface_porosity(cell->material_id());\n        const double compaction_coefficient = material_data.get_compressibility_coefficient(cell->material_id());\n        const double rock_density = material_data.get_solid_density(cell->material_id());\n\n         sedRate.value_list(fe_values.get_quadrature_points(), sedimentation_rate, 1);\n         advection_field.value_list(fe_values.get_quadrature_points(), advection_directions);\n\n        cell_rhs = 0;\n        cell_matrix = 0;\n        const double delta = 1 * cell->diameter();\n\n        for (unsigned int q_point = 0; q_point < n_q_points; ++q_point) {\n            point_for_depth = fe_values.quadrature_point(q_point);\n            const double hydrostatic = 9.81 * material_data.fluid_density *\n                                       (parameters.box_size - point_for_depth[dim-1]);\n            const double phi = porosity(pressure_at_quad[q_point], overburden_at_quad[q_point], initial_porosity,\n                                       compaction_coefficient, hydrostatic);\n            //const double phi = 0.5;\n            Assert(0 < hydrostatic, ExcInternalError());\n            Assert(0 <= phi, ExcInternalError());\n            Assert(phi < 1, ExcInternalError());\n\n            const double rho_b = bulkdensity(phi, material_data.fluid_density, rock_density);\n\n            rhs_at_quad[q_point] = 9.81 * rho_b;\n\n\n            //this should point \"down\"\n            Assert( 0 > advection_directions[q_point][dim-1], ExcInternalError());\n\n            //Assert ( 0 <sedimentation_rate[q_point], ExcInternalError());\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                    cell_matrix(i, j) += ((advection_directions[q_point] * fe_values.shape_grad(j, q_point) *\n                                           (fe_values.shape_value(i, q_point) +\n                                            delta * (advection_directions[q_point] * 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 * (advection_directions[q_point] * fe_values.shape_grad(i, q_point))) *\n                               rhs_at_quad[q_point] * fe_values.JxW(q_point);\n\n            }   // end i\n        }     // end q\n\n        //Rather than implement the boundary term, we specify as an essential condition on the test space\n        //So it is handled in a call to the constraints_Sigma\n\n        // For the inflow boundary term\n//    for (unsigned int face = 0; face < GeometryInfo<dim>::faces_per_cell; ++face)\n//      if (cell->face(face)->at_boundary()) {\n//        fe_face_values.reinit(cell, face);\n\n//        advection_field.value_list(fe_face_values.get_quadrature_points(), face_advection_directions);\n//        for (unsigned int q_point = 0; q_point < n_face_q_points; ++q_point)\n//          // the following determines whether inflow or not\n//          if (fe_face_values.normal_vector(q_point) * face_advection_directions[q_point] < 0)\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) -= (face_advection_directions[q_point] * fe_face_values.normal_vector(q_point) *\n//                                      fe_face_values.shape_value(i, q_point) * fe_face_values.shape_value(j, q_point) *\n//                                      fe_face_values.JxW(q_point));\n//              cell_rhs(i) -=\n//                  (face_advection_directions[q_point] * fe_face_values.normal_vector(q_point) *\n//                   sedimentation_rate[q_point] * fe_face_values.shape_value(i, q_point) * fe_face_values.JxW(q_point));\n//            }\n//      }\n\n        cell->get_dof_indices(local_dof_indices); // distribute to correct globally numbered vector\n\n        constraints_Sigma.distribute_local_to_global(cell_matrix, cell_rhs, local_dof_indices, system_matrix_Sigma,\n                rhs_Sigma);\n    } // end cell loop\n\n    rhs_Sigma.compress(VectorOperation::add);\n    system_matrix_Sigma.compress(VectorOperation::add);\n}\n\ntemplate <int dim>\nvoid LayerMovementProblem<dim>::solve_Sigma()\n{\n    TimerOutput::Scope t(computing_timer, \"solve_Sigma\");\n\n    LA::MPI::Vector completely_distributed_solution(locally_owned_dofs, mpi_communicator);\n\n    SolverControl solver_control(dof_handler.n_dofs(), 1e-6 * rhs_Sigma.l2_norm());\n    //  LA::SolverBicgstab solver(solver_control, mpi_communicator);\n    LA::SolverGMRES solver(solver_control, mpi_communicator);\n    //  LA::MPI::PreconditionAMG preconditioner;\n    //  LA::MPI::PreconditionAMG::AdditionalData data;\n    //  LA::MPI::PreconditionSSOR preconditioner;\n    //  LA::MPI::PreconditionSSOR::AdditionalData data;\n    //LA::MPI::PreconditionJacobi preconditioner;\n    //LA::MPI::PreconditionJacobi::AdditionalData data;\n    //LA::PreconditionSSOR preconditioner;\n    //does not compile with this\n    //LA::MPI::PreconditionBlockJacobi preconditioner;\n    //LA::PreconditionBlockJacobi preconditioner;\n    //does with this\n    PETScWrappers::PreconditionBlockJacobi preconditioner;\n    PETScWrappers::PreconditionBlockJacobi::AdditionalData data;\n    //data.symmetric_operator = false;\n    preconditioner.initialize(system_matrix_Sigma, data);\n\n    solver.solve(system_matrix_Sigma, completely_distributed_solution, rhs_Sigma, preconditioner);\n\n    pcout << \" Overburden supg system solved in \" << solver_control.last_step() << \" iterations.\" << std::endl;\n\n    constraints_Sigma.distribute(completely_distributed_solution);\n    //old_locally_relevant_solution_Sigma=locally_relevant_solution_Sigma;\n    locally_relevant_solution_Sigma = completely_distributed_solution;\n}\n\ntemplate <int dim>\nvoid LayerMovementProblem<dim>::assemble_F()\n{\n\n    TimerOutput::Scope t(computing_timer, \"assemble_F\");\n    const AdvectionField<dim> advection_field;\n    const QGauss<dim> quadrature_formula(degree + 2);\n    const QGauss<dim - 1> face_quadrature_formula(degree + 1);\n\n    FEValues<dim> fe_values(fe, quadrature_formula,\n                            update_values | update_quadrature_points | update_JxW_values | update_gradients);\n\n//    FEFaceValues<dim> fe_face_values(fe, face_quadrature_formula,\n//                                     update_values | update_quadrature_points | update_normal_vectors |\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    const unsigned int n_face_q_points = face_quadrature_formula.size();\n\n    std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell);\n\n    std::vector<double> rhs_at_quad(n_q_points);\n    std::vector<Tensor<1, dim>> advection_directions(n_q_points);\n//    std::vector<Tensor<1, dim>> face_advection_directions(n_face_q_points);\n\n\n    std::vector<double> overburden_at_quad(n_q_points);\n    std::vector<double> old_overburden_at_quad(n_q_points);\n    std::vector<double> pressure_at_quad(n_q_points);\n    std::vector<double> old_pressure_at_quad(n_q_points);\n\n    Point<dim> point_for_depth;\n    SedimentationRate<dim> sedRate(current_time, parameters);\n\n    std::vector<double> sedimentation_rate(n_q_points);\n\n    Vector<double> cell_rhs(dofs_per_cell);\n    FullMatrix<double> cell_matrix(dofs_per_cell, dofs_per_cell);\n\n    rhs_F = 0;\n    system_matrix_F = 0;\n\n    for (auto cell : filter_iterators(dof_handler.active_cell_iterators(), IteratorFilters::LocallyOwnedCell())) {\n\n        fe_values.reinit(cell);\n\n        fe_values.get_function_values(locally_relevant_solution_P, pressure_at_quad);\n        fe_values.get_function_values(locally_relevant_solution_Sigma, overburden_at_quad);\n        fe_values.get_function_values(old_locally_relevant_solution_P, old_pressure_at_quad);\n        fe_values.get_function_values(old_locally_relevant_solution_Sigma, old_overburden_at_quad);\n\n        // TODO consider moving these properties to the quad point level, not just cell level\n        const double initial_porosity = material_data.get_surface_porosity(cell->material_id());\n        const double compaction_coefficient = material_data.get_compressibility_coefficient(cell->material_id());\n        advection_field.value_list(fe_values.get_quadrature_points(), advection_directions);\n        sedRate.value_list(fe_values.get_quadrature_points(), sedimentation_rate, 1);\n\n        cell_rhs = 0;\n        cell_matrix = 0;\n        const double delta = 1 * cell->diameter();\n\n        for (unsigned int q_point = 0; q_point < n_q_points; ++q_point) {\n            point_for_depth = fe_values.quadrature_point(q_point);\n            const double hydrostatic = 9.81 * material_data.fluid_density *\n                                       (parameters.box_size - point_for_depth[dim-1]);\n            Assert(0 < hydrostatic, ExcInternalError());\n            const double phi = porosity(pressure_at_quad[q_point], overburden_at_quad[q_point], initial_porosity,\n                                        compaction_coefficient, hydrostatic);\n\n            Assert(0 <= phi, ExcInternalError());\n            Assert(phi < 1, ExcInternalError());\n\n            const double old_phi = porosity(old_pressure_at_quad[q_point], old_overburden_at_quad[q_point], initial_porosity,\n                                            compaction_coefficient, hydrostatic);\n\n            Assert(0 <= old_phi, ExcInternalError());\n            Assert(old_phi < 1, ExcInternalError());\n\n            const double dphidt = (phi - old_phi) / time_step;\n\n\n            Assert(dphidt <= 0, ExcInternalError());\n\n            rhs_at_quad[q_point] = -1*dphidt / (1 - phi);\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                    cell_matrix(i, j) += ((advection_directions[q_point] * fe_values.shape_grad(j, q_point) *\n                                           (fe_values.shape_value(i, q_point) +\n                                            delta * (advection_directions[q_point] * 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 * (advection_directions[q_point] * fe_values.shape_grad(i, q_point))) *\n                               rhs_at_quad[q_point] * fe_values.JxW(q_point);\n\n            }   // end i\n        }     // end q\n\n        // For the inflow boundary term\n\n//    for (unsigned int face = 0; face < GeometryInfo<dim>::faces_per_cell; ++face)\n//      if (cell->face(face)->at_boundary()) {\n//        fe_face_values.reinit(cell, face);\n\n//        advection_field.value_list(fe_face_values.get_quadrature_points(), face_advection_directions);\n//        for (unsigned int q_point = 0; q_point < n_face_q_points; ++q_point)\n//          // the following determines whether inflow or not\n//          if (fe_face_values.normal_vector(q_point) * face_advection_directions[q_point] < 0)\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) -= (face_advection_directions[q_point] * fe_face_values.normal_vector(q_point) *\n//                                      fe_face_values.shape_value(i, q_point) * fe_face_values.shape_value(j, q_point) *\n//                                      fe_face_values.JxW(q_point));\n//              cell_rhs(i) -=\n//                  (face_advection_directions[q_point] * fe_face_values.normal_vector(q_point) *\n//                   sedimentation_rate[q_point] * fe_face_values.shape_value(i, q_point) * fe_face_values.JxW(q_point));\n//            }\n//      }\n\n        cell->get_dof_indices(local_dof_indices); // distribute to correct globally numbered vector\n\n        constraints_F.distribute_local_to_global(cell_matrix, cell_rhs, local_dof_indices, system_matrix_F, rhs_F);\n    } // end cell loop\n\n    rhs_F.compress(VectorOperation::add);\n    system_matrix_F.compress(VectorOperation::add);\n}\n\ntemplate <int dim>\nvoid LayerMovementProblem<dim>::solve_F()\n{\n    TimerOutput::Scope t(computing_timer, \"solve_F\");\n\n    LA::MPI::Vector completely_distributed_solution(locally_owned_dofs, mpi_communicator);\n\n    SolverControl solver_control(dof_handler.n_dofs(), 1e-6 * rhs_F.l2_norm());\n    //  LA::SolverBicgstab solver(solver_control, mpi_communicator);\n    LA::SolverGMRES solver(solver_control, mpi_communicator);\n    //  LA::MPI::PreconditionAMG preconditioner;\n    //  LA::MPI::PreconditionAMG::AdditionalData data;\n    //  LA::MPI::PreconditionSSOR preconditioner;\n    //  LA::MPI::PreconditionSSOR::AdditionalData data;\n    PETScWrappers::PreconditionBlockJacobi preconditioner;\n    PETScWrappers::PreconditionBlockJacobi::AdditionalData data;\n//  LA::MPI::PreconditionJacobi preconditioner;\n//  LA::MPI::PreconditionJacobi::AdditionalData data;\n\n    // data.symmetric_operator = false;\n    preconditioner.initialize(system_matrix_F, data);\n\n    solver.solve(system_matrix_F, completely_distributed_solution, rhs_F, preconditioner);\n\n    pcout << \" Speed function system solved in \" << solver_control.last_step() << \" iterations.\" << std::endl;\n\n    constraints_F.distribute(completely_distributed_solution);\n\n    locally_relevant_solution_F = completely_distributed_solution;\n}\n\n\n// TODO fold this into P,F,Sigma, T assemblies to assign at quad point level\ntemplate <int dim>\nvoid LayerMovementProblem<dim>::setup_material_configuration()\n{\n    //TODO\n    TimerOutput::Scope t(computing_timer, \"set_material_configuration\");\n    // This function sets material ids of cells based on the location of the interface, i.e. loc_rel_solution_LS\n\n    const QGauss<dim> quadrature_formula(degree + 2);\n\n    FEValues<dim> fe_values(fe_LS, quadrature_formula, update_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    //  std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell);\n\n\n    //TODO: a better structure than vec(vec))\n    std::vector<std::vector<double>> LS_at_quad (n_layers, std::vector<double>(n_q_points));\n\n    // std::vector<double> bulkdensity_at_quad(n_q_points);\n    // double eps= GridTools::minimal_cell_diameter(triangulation)/std::sqrt(2);\n    //      const double eps=0.001;\n    //        double H=0;\n    //          // get rho, nu\n    //          if (phi>eps)\n    //            H=1;\n    //          else if (phi<-eps)\n    //            H=-1;\n    //          else\n    //            H=phi/eps;\n    //          diff_coeff=1000*(1+H)/2.+10*(1-H)/2.;\n\n    // std::vector<double> id_sum(5);\n    std::vector<double> id_sum(n_layers, 0);\n\n    for (auto cell : filter_iterators(dof_handler_LS.active_cell_iterators(), IteratorFilters::LocallyOwnedCell())) {\n\n        std::fill(id_sum.begin(), id_sum.end(), 0);\n\n        fe_values.reinit(cell);\n        int i=0;//for n_layers\n        for(auto & layer_sol : layers_solutions)\n        {\n            fe_values.get_function_values( *layer_sol, LS_at_quad[i]);\n\n            for (unsigned int q_point = 0; q_point < n_q_points; ++q_point)\n            {\n\n//                Assert(LS_at_quad[i][q_point] < 1.5, ExcInternalError());\n//                Assert(-1.5 < LS_at_quad[i][q_point], ExcInternalError());\n                //do the y=2x-1 switch so the -/+ still works\n                id_sum[i] += 2*LS_at_quad[i][q_point]-1;\n            }\n            ++i;\n            //TODO representation of interface (0 level set or 0.5, etc.) needs to be taken\n            //into account in this averaging, as above for 0.5\n        }\n        //defining the negative to be below an interface,\n        //if a LS has takes a positive value on the cell\n        //it is added to the counter (cell is \"inside\" the layer)\n        //the innermost layer is the material id\n        int counter{0};\n        for (i=0; i<n_layers; ++i)\n        {\n\n            if(id_sum[i]>0)\n            {\n                ++counter;\n            }\n        }\n        cell->set_material_id(counter);\n\n    } // end cell loop\n}\n\ntemplate <int dim>\nvoid LayerMovementProblem<dim>::assemble_matrices_P()\n{\n    TimerOutput::Scope t(computing_timer, \"assembly_P\");\n    const QGauss<dim> quadrature_formula(degree + 2);\n\n    FEValues<dim> fe_values(fe, quadrature_formula,\n                            update_values | update_gradients | 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 = quadrature_formula.size();\n\n    FullMatrix<double> cell_laplace_matrix(dofs_per_cell, dofs_per_cell);\n    FullMatrix<double> cell_mass_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    Point<dim> point_for_depth;\n\n    SedimentationRate<dim> sedRate(current_time, parameters );\n\n    std::vector<double> pressure_at_quad(n_q_points);\n    std::vector<double> overburden_at_quad(n_q_points);\n    std::vector<double> old_overburden_at_quad(n_q_points);\n    std::vector<double> old_pressure_at_quad(n_q_points);\n    std::vector<double> sedimentation_rates(n_q_points);\n\n    for (auto cell : filter_iterators(dof_handler.active_cell_iterators(), IteratorFilters::LocallyOwnedCell())) {\n        cell_laplace_matrix = 0;\n        cell_mass_matrix = 0;\n        cell_rhs = 0;\n\n        fe_values.reinit(cell);\n\n        fe_values.get_function_values(locally_relevant_solution_P, pressure_at_quad);\n        fe_values.get_function_values(locally_relevant_solution_Sigma, overburden_at_quad);\n        fe_values.get_function_values(old_locally_relevant_solution_P, old_pressure_at_quad);\n        fe_values.get_function_values(old_locally_relevant_solution_Sigma, old_overburden_at_quad);\n\n        // TODO consider moving these properties to the quad point level, not just cell level\n        const double initial_porosity = material_data.get_surface_porosity(cell->material_id());\n        const double compaction_coefficient = material_data.get_compressibility_coefficient(cell->material_id());\n        const double initial_permeability = material_data.get_surface_permeability(cell->material_id());\n        sedRate.value_list(fe_values.get_quadrature_points(), sedimentation_rates, 1);\n\n        for (unsigned int q_point = 0; q_point < n_q_points; ++q_point) {\n//        if(0 <= pressure_at_quad[q_point]){\n//            output_vectors();\n//            abort();\n//          }\n            Assert( -0.1 <pressure_at_quad[q_point], ExcInternalError());\n            Assert(0 < overburden_at_quad[q_point], ExcInternalError());\n\n            point_for_depth = fe_values.quadrature_point(q_point);\n            const double hydrostatic = 9.81 * material_data.fluid_density *\n                                       (parameters.box_size - point_for_depth[dim-1]);\n            Assert(0 < hydrostatic, ExcInternalError());\n            const double phi = porosity(pressure_at_quad[q_point], overburden_at_quad[q_point], initial_porosity,\n                                        compaction_coefficient, hydrostatic);\n            Assert(0 <= phi, ExcInternalError());\n            Assert(phi < 1, ExcInternalError());\n            //Assert(0< (overburden_at_quad[q_point]-pressure_at_quad[q_point]-hydrostatic), ExcInternalError());\n\n            const double perm_k = permeability(phi, initial_permeability, initial_porosity);\n            // pcout<<\"perm_k\"<<perm_k<<\"init<<\"<< initial_permeability<<std::endl;\n            Assert(0 < perm_k, ExcInternalError());\n            // Assert(perm_k <= initial_permeability, ExcInternalError());\n\n            const double old_phi = porosity(old_pressure_at_quad[q_point], old_overburden_at_quad[q_point], initial_porosity,\n                                            compaction_coefficient, hydrostatic);\n            Assert(0 <= old_phi, ExcInternalError());\n            Assert(old_phi < 1, ExcInternalError());\n\n            const double dphidt = (phi - old_phi) / time_step;\n\n            //Assert(dphidt <= 0, ExcInternalError());\n\n            const double diff_coeff_at_quad = (perm_k / material_data.fluid_viscosity);\n            const double rhs_coeff = material_data.get_compressibility_coefficient(cell->material_id()) * phi / (1 - phi);\n            const double rhs_at_quad =(overburden_at_quad[q_point] - old_overburden_at_quad[q_point]) / time_step -\n                                       (9.8 * material_data.fluid_density * -1*sedimentation_rates[q_point]);\n\n            //Assert (0 <= rhs_at_quad, ExcInternalError());\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                    cell_laplace_matrix(i, j) += diff_coeff_at_quad * (fe_values.shape_grad(i, q_point) *\n                                                 fe_values.shape_grad(j, q_point) * fe_values.JxW(q_point));\n\n                    cell_mass_matrix(i, j) +=\n                        (fe_values.shape_value(i, q_point) * fe_values.shape_value(j, q_point) * fe_values.JxW(q_point));\n                } //end of j\n\n                cell_rhs(i) += rhs_coeff*(rhs_at_quad * fe_values.shape_value(i, q_point) * fe_values.JxW(q_point));\n            } //end of i\n        } // end q\n\n        cell->get_dof_indices(local_dof_indices);\n        constraints_P.distribute_local_to_global(cell_laplace_matrix, cell_rhs, local_dof_indices, laplace_matrix_P, rhs_P);\n        constraints_P.distribute_local_to_global(cell_mass_matrix, local_dof_indices, mass_matrix_P);\n    } // end cell\n\n    laplace_matrix_P.compress(VectorOperation::add);\n    mass_matrix_P.compress(VectorOperation::add);\n    rhs_P.compress(VectorOperation::add);\n}\n\ntemplate <int dim>\nvoid LayerMovementProblem<dim>::forge_system_P()\n{\n    // in this function we manipulate A, M, F, resulting from assemble_matrices_P\n    TimerOutput::Scope t(computing_timer, \"forge_P\");\n    LA::MPI::Vector tmp;\n    LA::MPI::Vector forcing_terms;\n\n    tmp.reinit(locally_owned_dofs, locally_relevant_dofs, mpi_communicator);\n\n    forcing_terms.reinit(locally_owned_dofs, mpi_communicator);\n\n    old_locally_relevant_solution_P = locally_relevant_solution_P;\n    mass_matrix_P.vmult(system_rhs_P, old_locally_relevant_solution_P);\n\n    laplace_matrix_P.vmult(tmp, old_locally_relevant_solution_P);\n    //  pcout << \"laplace symmetric: \" << laplace_matrix.is_symmetric()<<std::endl;\n    system_rhs_P.add(-(1 - theta) * time_step, tmp);\n\n    forcing_terms.add(time_step * theta, rhs_P);\n\n    forcing_terms.add(time_step * (1 - theta), old_rhs_P);\n\n    system_rhs_P += forcing_terms;\n    // system_matrix.compress (VectorOperation::add);\n\n    system_matrix_P.copy_from(mass_matrix_P);\n    // system_matrix.compress (VectorOperation::add);\n\n    system_matrix_P.add(laplace_matrix_P, time_step * (1 - theta));\n}\n\ntemplate <int dim>\nvoid LayerMovementProblem<dim>::solve_time_step_P()\n{\n    TimerOutput::Scope t(computing_timer, \"solve_time_step_P\");\n\n    LA::MPI::Vector completely_distributed_solution(locally_owned_dofs, mpi_communicator);\n\n    SolverControl solver_control(dof_handler.n_dofs(), 1e-12 * system_rhs_P.l2_norm());\n    LA::SolverCG solver(solver_control, mpi_communicator);\n\n    LA::MPI::PreconditionAMG preconditioner;\n\n    LA::MPI::PreconditionAMG::AdditionalData data;\n\n    data.symmetric_operator = true;\n    preconditioner.initialize(system_matrix_P, data);\n\n    solver.solve(system_matrix_P, completely_distributed_solution, system_rhs_P, preconditioner);\n\n    pcout << \" Pressure system solved in \" << solver_control.last_step() << \" iterations.\" << std::endl;\n\n    constraints_P.distribute(completely_distributed_solution);\n\n    locally_relevant_solution_P = completely_distributed_solution;\n}\n\ntemplate <int dim>\nvoid LayerMovementProblem<dim>::assemble_matrices_T()\n{\n    TimerOutput::Scope t(computing_timer, \"assembly_T\");\n    const QGauss<dim> quadrature_formula(degree + 2);\n    const QGauss<dim - 1> face_quadrature_formula(degree + 1);\n\n    FEValues<dim> fe_values(fe, quadrature_formula,\n                            update_values | update_gradients | update_quadrature_points | update_JxW_values);\n    FEFaceValues<dim> fe_face_values(fe, face_quadrature_formula,\n                                     update_values | update_quadrature_points | update_normal_vectors |\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    const unsigned int n_face_q_points = face_quadrature_formula.size();\n\n    FullMatrix<double> cell_laplace_matrix(dofs_per_cell, dofs_per_cell);\n    FullMatrix<double> cell_mass_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    Point<dim> point_for_depth;\n\n    std::vector<double> pressure_at_quad(n_q_points);\n    std::vector<double> overburden_at_quad(n_q_points);\n    std::vector<double> bulkheat_capacity_at_quad(n_q_points);\n    std::vector<double> thermal_conductivity_at_quad(n_q_points);\n\n    for (auto cell : filter_iterators(dof_handler.active_cell_iterators(), IteratorFilters::LocallyOwnedCell())) {\n        cell_laplace_matrix = 0;\n        cell_mass_matrix = 0;\n        cell_rhs = 0;\n\n        fe_values.reinit(cell);\n        fe_values.get_function_values(locally_relevant_solution_P, pressure_at_quad);\n        fe_values.get_function_values(locally_relevant_solution_Sigma, overburden_at_quad);\n\n        // TODO consider moving these properties to the quad point level, not just cell level\n        const double initial_porosity = material_data.get_surface_porosity(cell->material_id());\n        const double compaction_coefficient = material_data.get_compressibility_coefficient(cell->material_id());\n        const double rock_density = material_data.get_solid_density(cell->material_id());\n        const double heat_capacity = material_data.get_heat_capacity(cell->material_id());\n\n        for (unsigned int q_point = 0; q_point < n_q_points; ++q_point) {\n            point_for_depth = fe_values.quadrature_point(q_point);\n            const double hydrostatic = 9.81 * material_data.fluid_density *\n                                       (parameters.box_size - point_for_depth[dim-1]); // TODO make this dim independent\n            const double phi = porosity(pressure_at_quad[q_point], overburden_at_quad[q_point], initial_porosity,\n                                        compaction_coefficient, hydrostatic);\n            //Assert(0 < phi < 1, ExcInternalError());\n\n            const double rho_b = bulkdensity(phi, material_data.fluid_density, rock_density);\n            const double bulk_hc = bulkheatcapacity(phi, material_data.fluid_heat_capacity, heat_capacity);\n\n            //      fe_values.get_function_values(thermal_conductivity, thermal_conductivity_at_quad);\n            // TODO\n            const double diff_coeff_at_quad = 10;\n            //  thermal_conductivity_at_quad[q_point] /(bulkheat_capacity_at_quad[q_point]*bulkdensity_at_quad[q_point] );\n            const double rhs_at_quad = 0; // TODO bottom boundary flux from parameter file\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                    cell_laplace_matrix(i, j) += diff_coeff_at_quad * fe_values.shape_grad(i, q_point) *\n                                                 fe_values.shape_grad(j, q_point) * fe_values.JxW(q_point);\n\n                    cell_mass_matrix(i, j) += (rho_b * bulk_hc * fe_values.shape_value(i, q_point) *\n                                               fe_values.shape_value(j, q_point) * fe_values.JxW(q_point));\n                } // end j\n\n                //          cell_rhs(i) += (right_hand_side.value(fe_values.quadrature_point(q_point)) *\n                //                          fe_values.shape_value(i, q_point) * fe_values.JxW(q_point));\n                cell_rhs(i) += (rhs_at_quad * fe_values.shape_value(i, q_point) * fe_values.JxW(q_point));\n\n            }   // end i\n        }     // end q\n\n        for (unsigned int face_number = 0; face_number < GeometryInfo<dim>::faces_per_cell; ++face_number) {\n            if (cell->face(face_number)->at_boundary() &&\n                    (cell->face(face_number)->boundary_id() == 2)) // bottom of domain TODO remove raw number\n            {\n                fe_face_values.reinit(cell, face_number);\n                for (unsigned int q_point = 0; q_point < n_face_q_points; ++q_point) {\n                    //                const double neumann_value\n                    //                  = (exact_solution.gradient (fe_face_values.quadrature_point(q_point)) *\n                    //                     fe_face_values.normal_vector(q_point));\n                    // TODO pick the right flux value\n                    const double neumann_value = 100; // represents the bottom flux boundary condition\n                    for (unsigned int i = 0; i < dofs_per_cell; ++i) {\n                        cell_rhs(i) += (neumann_value * fe_face_values.shape_value(i, q_point) * fe_face_values.JxW(q_point));\n                    }\n                }\n            }\n        } // end face loop\n\n        cell->get_dof_indices(local_dof_indices);\n        constraints_T.distribute_local_to_global(cell_laplace_matrix, cell_rhs, local_dof_indices, laplace_matrix_T, rhs_T);\n        constraints_T.distribute_local_to_global(cell_mass_matrix, local_dof_indices, mass_matrix_T);\n    } // end cell\n\n    laplace_matrix_T.compress(VectorOperation::add);\n    mass_matrix_T.compress(VectorOperation::add);\n    rhs_T.compress(VectorOperation::add);\n}\n\ntemplate <int dim>\nvoid LayerMovementProblem<dim>::forge_system_T()\n{\n    // in this function we manipulate A, M, F, resulting from assemble_matrices_T\n    TimerOutput::Scope t(computing_timer, \"forge_T\");\n    LA::MPI::Vector tmp;\n    LA::MPI::Vector forcing_terms;\n\n    tmp.reinit(locally_owned_dofs, locally_relevant_dofs, mpi_communicator);\n\n    forcing_terms.reinit(locally_owned_dofs, mpi_communicator);\n\n    old_locally_relevant_solution_T = locally_relevant_solution_T;\n    mass_matrix_T.vmult(system_rhs_T, old_locally_relevant_solution_T);\n\n    laplace_matrix_T.vmult(tmp, old_locally_relevant_solution_T);\n    //  pcout << \"laplace symmetric: \" << laplace_matrix.is_symmetric()<<std::endl;\n    system_rhs_T.add(-(1 - theta) * time_step, tmp);\n\n    forcing_terms.add(time_step * theta, rhs_T);\n\n    forcing_terms.add(time_step * (1 - theta), old_rhs_T);\n\n    system_rhs_T += forcing_terms;\n    // system_matrix.compress (VectorOperation::add);\n\n    system_matrix_T.copy_from(mass_matrix_T);\n    // system_matrix.compress (VectorOperation::add);\n\n    system_matrix_T.add(laplace_matrix_T, time_step * (1 - theta));\n}\n\ntemplate <int dim>\nvoid LayerMovementProblem<dim>::solve_time_step_T()\n{\n    TimerOutput::Scope t(computing_timer, \"solve_time_step_T\");\n\n    LA::MPI::Vector completely_distributed_solution(locally_owned_dofs, mpi_communicator);\n\n    SolverControl solver_control(dof_handler.n_dofs(), 1e-12 * system_rhs_T.l2_norm());\n    LA::SolverCG solver(solver_control, mpi_communicator);\n\n    LA::MPI::PreconditionAMG preconditioner;\n\n    LA::MPI::PreconditionAMG::AdditionalData data;\n\n    data.symmetric_operator = true;\n    preconditioner.initialize(system_matrix_T, data);\n\n    solver.solve(system_matrix_T, completely_distributed_solution, system_rhs_T, preconditioner);\n\n    pcout << \" Temperature system solved in \" << solver_control.last_step() << \" iterations.\" << std::endl;\n\n    constraints_T.distribute(completely_distributed_solution);\n\n    locally_relevant_solution_T = completely_distributed_solution;\n}\n\ntemplate <int dim>\nvoid LayerMovementProblem<dim>::prepare_next_time_step()\n{\n    //  old_porosity = porosity;\n    //  old_overburden = overburden;\n}\n\ntemplate <int dim>\nvoid LayerMovementProblem<dim>::output_vectors_LS()\n{\n    TimerOutput::Scope t(computing_timer, \"output_LS\");\n    DataOut<dim> data_out;\n    data_out.attach_dof_handler(dof_handler_LS);\n    int i=0;\n    for( auto & layer_sol : layers_solutions)\n    {\n        std::string layer_out = \"LS\"+  Utilities::int_to_string(i, 3);\n        data_out.add_data_vector(*layer_sol, layer_out);\n        ++i;\n    }\n//    LA::MPI::Vector ng_material_kind;\n//    ng_material_kind.reinit(locally_owned_dofs,  mpi_communicator);\n//    LA::MPI::Vector g_material_kind;\n//    g_material_kind.reinit(locally_owned_dofs,locally_relevant_dofs,  mpi_communicator);\n\n//    //std::vector<unsigned int> material_kind(triangulation.n_active_cells());\n//     i = 0;\n//    for (auto cell : filter_iterators(triangulation.active_cell_iterators(), IteratorFilters::LocallyOwnedCell())) {\n//    ng_material_kind[i]=cell->material_id();\n//      ++i;\n//    }\n//    ng_material_kind.compress(VectorOperation::insert);\n//    g_material_kind=ng_material_kind;\n//    ComputePorosity<dim> porosity;\n\n\n\n    data_out.add_data_vector(locally_relevant_solution_LS_0, \"LS\");\n    Vector<float> subdomain(triangulation.n_active_cells());\n    for (unsigned int i = 0; i < subdomain.size(); ++i)\n        subdomain(i) = triangulation.locally_owned_subdomain();\n    data_out.add_data_vector(subdomain, \"subdomain\");\n\n    data_out.build_patches();\n\n    const std::string filename = (\"sol_LS_vectors-\" + Utilities::int_to_string(output_number, 3) + \".\" +\n                                  Utilities::int_to_string(triangulation.locally_owned_subdomain(), 4));\n    std::ofstream output((filename + \".vtu\").c_str());\n    data_out.write_vtu(output);\n\n    if (Utilities::MPI::this_mpi_process(mpi_communicator) == 0) {\n        std::vector<std::string> filenames;\n        for (unsigned int i = 0; i < Utilities::MPI::n_mpi_processes(mpi_communicator); ++i)\n            filenames.push_back(\"sol_LS_vectors-\" + Utilities::int_to_string(output_number, 3) + \".\" +\n                                Utilities::int_to_string(i, 4) + \".vtu\");\n\n        std::ofstream master_output((\"sol_LS_vectors-\" + Utilities::int_to_string(output_number, 3) + \".pvtu\").c_str());\n        data_out.write_pvtu_record(master_output, filenames);\n    }\n}\n\n\n\ntemplate <int dim>\nvoid LayerMovementProblem<dim>::output_vectors()\n{\n    TimerOutput::Scope t(computing_timer, \"output\");\n    // output_number++;\n    DataOut<dim> data_out;\n    data_out.attach_dof_handler(dof_handler);\n    data_out.add_data_vector(locally_relevant_solution_P, \"P\");\n    data_out.add_data_vector(old_locally_relevant_solution_P, \"old_P\");\n    data_out.add_data_vector(locally_relevant_solution_T, \"T\");\n    data_out.add_data_vector(old_locally_relevant_solution_T, \"old_T\");\n    data_out.add_data_vector(locally_relevant_solution_Sigma, \"Sigma\");\n    data_out.add_data_vector(old_locally_relevant_solution_Sigma, \"old_Sigma\");\n    data_out.add_data_vector(locally_relevant_solution_F, \"F\");\n\n//    //abuse the temp_locally_relevant_Sigma ghosted vector to output non-ghosted rhs_Sigma\n//    temp_locally_relevant_solution_Sigma=rhs_Sigma;\n//    data_out.add_data_vector(old_locally_relevant_solution_Sigma, \"rhsSigma\");\n\n//  data_out.add_data_vector(system_rhs_P, \"s_rhs_P\");\n//  data_out.add_data_vector(rhs_F, \"rhs_F\" );\n//  data_out.add_data_vector(rhs_Sigma, \"rhs_s\");\n\n\n\n//      Vector<float> material_id(triangulation.n_active_cells());\n//      for (unsigned int i = 0; i < material_id.size(); ++i)\n//          material_id(i) = cell->material_id();\n//      data_out.add_data_vector(material_id, \"material_id\");\n\n    Vector<float> subdomain(triangulation.n_active_cells());\n    for (unsigned int i = 0; i < subdomain.size(); ++i)\n        subdomain(i) = triangulation.locally_owned_subdomain();\n    data_out.add_data_vector(subdomain, \"subdomain\");\n\n    data_out.build_patches();\n\n    const std::string filename = (\"sol_vectors-\" + Utilities::int_to_string(output_number, 3) + \".\" +\n                                  Utilities::int_to_string(triangulation.locally_owned_subdomain(), 4));\n    std::ofstream output((filename + \".vtu\").c_str());\n    data_out.write_vtu(output);\n\n    if (Utilities::MPI::this_mpi_process(mpi_communicator) == 0) {\n        std::vector<std::string> filenames;\n        for (unsigned int i = 0; i < Utilities::MPI::n_mpi_processes(mpi_communicator); ++i)\n            filenames.push_back(\"sol_vectors-\" + Utilities::int_to_string(output_number, 3) + \".\" +\n                                Utilities::int_to_string(i, 4) + \".vtu\");\n\n        std::ofstream master_output((\"sol_vectors-\" + Utilities::int_to_string(output_number, 3) + \".pvtu\").c_str());\n        data_out.write_pvtu_record(master_output, filenames);\n    }\n}\n\ntemplate <int dim>\nint LayerMovementProblem<dim>::active_layers_in_time (double time)\n{\n  //equitemporal division over layers\n  for (int i=1;i<=n_layers;++i)\n    {\n      double current_fraction= static_cast<double>(i)/(n_layers);\n      if(time<(current_fraction*final_time))\n        {\n          pcout<<\"layer\"<<i<<std::endl;\n          return i;\n        }\n\n    }\n\n}\n\n\n\n\ntemplate <int dim>\nclass LayerMovementProblem<dim>::Postprocessor : public DataPostprocessor<dim>\n{\npublic:\n  Postprocessor (const CPPLS::MaterialData& material_data,\n                 const CPPLS::Parameters& parameters);\n  virtual\n  void\n  evaluate_vector_field\n  (const DataPostprocessorInputs::Vector<dim> &inputs,\n   std::vector<Vector<double> >               &computed_quantities) const override;\n  virtual std::vector<std::string> get_names () const override;\n  virtual\n  std::vector<DataComponentInterpretation::DataComponentInterpretation>\n  get_data_component_interpretation () const override;\n  virtual UpdateFlags get_needed_update_flags () const override;\nprivate:\n  const CPPLS::MaterialData& material_data;\n  const CPPLS::Parameters& parameters;\n};\ntemplate <int dim>\nLayerMovementProblem<dim>::Postprocessor::\nPostprocessor (const CPPLS::MaterialData& material_data,\n               const CPPLS::Parameters& parameters)\n  :\n  material_data (material_data),\n  parameters (parameters)\n{}\ntemplate <int dim>\nstd::vector<std::string>\nLayerMovementProblem<dim>::Postprocessor::get_names() const\n{\n  std::vector<std::string> solution_names;\n\n  solution_names.push_back (\"porosity\");\n  solution_names.push_back (\"permeability\");\n  solution_names.push_back (\"VES\");\n  solution_names.push_back (\"material\");\n  solution_names.push_back (\"hydrostatic\");\n  solution_names.push_back (\"overpressure\");\n  solution_names.push_back (\"overburden\");\n  solution_names.push_back (\"pore_pressure\");\n  solution_names.push_back (\"speed_function\");\n\n\n\n  //solution_names.push_back (\"T\");\n\n  return solution_names;\n}\ntemplate <int dim>\nstd::vector<DataComponentInterpretation::DataComponentInterpretation>\nLayerMovementProblem<dim>::Postprocessor::\nget_data_component_interpretation () const\n{\n  std::vector<DataComponentInterpretation::DataComponentInterpretation>\n  interpretation;\n  interpretation.push_back (DataComponentInterpretation::component_is_scalar);\n  interpretation.push_back (DataComponentInterpretation::component_is_scalar);\n  interpretation.push_back (DataComponentInterpretation::component_is_scalar);\n  interpretation.push_back (DataComponentInterpretation::component_is_scalar);\n  interpretation.push_back (DataComponentInterpretation::component_is_scalar);\n  interpretation.push_back (DataComponentInterpretation::component_is_scalar);\n  interpretation.push_back (DataComponentInterpretation::component_is_scalar);\n  interpretation.push_back (DataComponentInterpretation::component_is_scalar);\n  interpretation.push_back (DataComponentInterpretation::component_is_scalar);\n\n  return interpretation;\n}\ntemplate <int dim>\nUpdateFlags\nLayerMovementProblem<dim>::Postprocessor::get_needed_update_flags() const\n{\n  return update_values | update_gradients | update_q_points;\n}\ntemplate <int dim>\nvoid\nLayerMovementProblem<dim>::Postprocessor::\nevaluate_vector_field\n(const DataPostprocessorInputs::Vector<dim> &inputs,\n std::vector<Vector<double> >               &computed_quantities) const\n{\n  const unsigned int n_quadrature_points = inputs.solution_values.size();\n  Assert (inputs.solution_gradients.size() == n_quadrature_points,\n          ExcInternalError());\n  Assert (computed_quantities.size() == n_quadrature_points,\n          ExcInternalError());\n  Assert (inputs.solution_values[0].size() == 3,\n          ExcInternalError());\n\n    //cell properties\n  const typename DoFHandler<dim>::cell_iterator\n    current_cell = inputs.template get_cell<DoFHandler<dim>>();\n  const unsigned int mat_id = current_cell->material_id();\n//  const Point<dim> center = current_cell->center();\n//  const double depth = parameters.box_size- center[1];\n\n  const double initial_porosity = material_data.get_surface_porosity(mat_id);\n  const double compaction_coefficient = material_data.get_compressibility_coefficient(mat_id);\n  const double initial_permeability = material_data.get_surface_permeability(mat_id);\n\n  for (unsigned int q=0; q<n_quadrature_points; ++q)\n    {\n      //point values\n      const Point<dim> point_for_depth = inputs.evaluation_points[q];\n      const double hydrostatic = 9.81*material_data.fluid_density*(parameters.box_size - point_for_depth[dim-1]);//point_for_depth;\n\n      //relabel the incoming components\n      const double overpressure=inputs.solution_values[q](0);\n      const double sigma = inputs.solution_values[q](1);\n      const double speed_function = inputs.solution_values[q](2);\n\n\n      //porosity\n      computed_quantities[q](0)\n          = CPPLS::porosity(overpressure, sigma, initial_porosity, compaction_coefficient, hydrostatic);\n      //permeability\n      computed_quantities[q](1)\n          = CPPLS::permeability(computed_quantities[q](0), initial_permeability, initial_porosity );\n      //VES\n      computed_quantities[q](2)\n          = sigma - overpressure - hydrostatic;\n      //material_id\n      computed_quantities[q](3)\n          =mat_id;\n      computed_quantities[q](4)\n          =hydrostatic;\n      computed_quantities[q](5)\n          =overpressure;\n      computed_quantities[q](6)\n          =sigma;\n      computed_quantities[q](7)\n          =overpressure+hydrostatic;\n      computed_quantities[q](8)\n          =speed_function;\n\n\n\n    }\n}\ntemplate <int dim>\nvoid LayerMovementProblem<dim>::output_results_pp ()\n{\n  TimerOutput::Scope t(computing_timer, \"output_pp\");\n  //computing_timer.enter_section (\"Postprocessing\");\n  //the purpose of this is to create a vector-valued solution vector, composed of\n  //gluing together the scalar solution vectors(i.e., pressure, overburden and speed function)\n  //for use in the Postprocessor class.\n  //Note these all share one DoFHandler (i.e., dof_handler), so there might be a better way to make the\n  //vector-valued solution.\n  //The current method would allow for joining in the dof_handler_LS solution vectors\n\n\n  const FESystem<dim> joint_fe(fe, 1, fe, 1, fe, 1);\n  //FESystem<dim, dim> joint_fe (FE_Q<dim>(2), 2);\n\n  DoFHandler<dim> joint_dof_handler (triangulation);\n  joint_dof_handler.distribute_dofs (joint_fe);\n  Assert (joint_dof_handler.n_dofs() ==\n          dof_handler.n_dofs()*3,\n          ExcInternalError());\n  LA::MPI::Vector joint_solution;\n  joint_solution.reinit (joint_dof_handler.locally_owned_dofs(), mpi_communicator);\n  {\n    std::vector<types::global_dof_index> local_joint_dof_indices (joint_fe.dofs_per_cell);\n    std::vector<types::global_dof_index> local_dof_indices (fe.dofs_per_cell);\n\n    //std::vector<types::global_dof_index> 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    cell      = dof_handler.begin_active();\n//    temperature_cell = temperature_dof_handler.begin_active();\n    for (; joint_cell!=joint_endc;\n         ++joint_cell, ++cell/*, ++temperature_cell*/)\n      if (joint_cell->is_locally_owned())\n        {\n          joint_cell->get_dof_indices (local_joint_dof_indices);\n          cell->get_dof_indices (local_dof_indices);\n//          temperature_cell->get_dof_indices (local_temperature_dof_indices);\n          for (unsigned int i=0; i<joint_fe.dofs_per_cell; ++i)\n            {\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_dof_indices.size(),\n                        ExcInternalError());\n                joint_solution(local_joint_dof_indices[i])\n                  = locally_relevant_solution_P(local_dof_indices\n                                    [joint_fe.system_to_base_index(i).second]);\n              }\n            else if (joint_fe.system_to_base_index(i).first.first == 1)\n              {\n\n                Assert (joint_fe.system_to_base_index(i).second\n                        <\n                        local_dof_indices.size(),\n                        ExcInternalError());\n                joint_solution(local_joint_dof_indices[i])\n                  = locally_relevant_solution_Sigma(local_dof_indices\n                                         [joint_fe.system_to_base_index(i).second]);\n              }\n              else\n              {\n                Assert (joint_fe.system_to_base_index(i).first.first == 2,\n                        ExcInternalError());\n                Assert (joint_fe.system_to_base_index(i).second\n                        <\n                        local_dof_indices.size(),\n                        ExcInternalError());\n                joint_solution(local_joint_dof_indices[i])\n                  = locally_relevant_solution_F(local_dof_indices\n                                         [joint_fe.system_to_base_index(i).second]);\n\n\n               }\n\n            }\n        }\n  }\n\n  joint_solution.compress(VectorOperation::insert);\n  IndexSet locally_relevant_joint_dofs(joint_dof_handler.n_dofs());\n  DoFTools::extract_locally_relevant_dofs (joint_dof_handler, locally_relevant_joint_dofs);\n  LA::MPI::Vector locally_relevant_joint_solution;\n\n  locally_relevant_joint_solution.reinit (joint_dof_handler.locally_owned_dofs(), locally_relevant_joint_dofs, mpi_communicator);\n  locally_relevant_joint_solution = joint_solution;\n  Postprocessor postprocessor ( material_data, parameters);\n  DataOut<dim> data_out;\n  data_out.attach_dof_handler (joint_dof_handler);\n  data_out.add_data_vector (locally_relevant_joint_solution, postprocessor);\n  data_out.build_patches ();\n  static int out_index=0;\n  const std::string filename = (\"solution-\" +\n                                Utilities::int_to_string (out_index, 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  if (Utilities::MPI::this_mpi_process(mpi_communicator) == 0)\n    {\n      std::vector<std::string> filenames;\n      for (unsigned int i=0; i<Utilities::MPI::n_mpi_processes(mpi_communicator); ++i)\n        filenames.push_back (std::string(\"solution-\") +\n                             Utilities::int_to_string (out_index, 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 (out_index, 5) +\n                              \".pvtu\");\n      std::ofstream pvtu_master (pvtu_master_filename.c_str());\n      data_out.write_pvtu_record (pvtu_master, filenames);\n//      const std::string\n//      visit_master_filename = (\"solution-\" +\n//                               Utilities::int_to_string (out_index, 5) +\n//                               \".visit\");\n//      std::ofstream visit_master (visit_master_filename.c_str());\n//      DataOutBase::write_visit_record (visit_master, filenames);\n    }\n  //computing_timer.exit_section ();\n out_index++;\n}\n\n\ntemplate <int dim>\nvoid LayerMovementProblem<dim>::refine_mesh()\n{\n  TimerOutput::Scope t(computing_timer, \"refine_mesh\");\n  const unsigned int max_grid_level=parameters.initial_refinement_level+2;\n  //first: mark cells\n\n  //The strategy here is to refine around kinks in overburden\n  //TODO try to refine around each loc_rel_LS solution\n\n  Vector<float> estimated_error_per_cell (triangulation.n_active_cells());\n  KellyErrorEstimator<dim>::estimate (dof_handler,\n                                      QGauss<dim-1>(degree+1),\n                                      typename FunctionMap<dim>::type(),\n                                      locally_relevant_solution_Sigma,\n                                      estimated_error_per_cell,\n                                      ComponentMask(),\n                                      nullptr,\n                                      0,\n                                      triangulation.locally_owned_subdomain());\n\n  parallel::distributed::GridRefinement::\n  refine_and_coarsen_fixed_fraction (triangulation,\n                                     estimated_error_per_cell,\n                                     0.3, 0.1);\n  if (triangulation.n_levels() > max_grid_level)\n    {\n    for (typename Triangulation<dim>::active_cell_iterator\n         cell = triangulation.begin_active(max_grid_level);\n         cell != triangulation.end(); ++cell)\n      {\n        cell->clear_refine_flag ();\n      }\n    }\n\n  //second: prepare solution vectors for refinement\n\n  //do also for temperature (F need to reinitialize vectors but not transfer solutions)\n  //need old_Sigma\n//  parallel::distributed::SolutionTransfer<dim,LA::MPI::Vector>\n//  my_vectors_trans(dof_handler);\n\n\n//  std::vector<const LA::MPI::Vector *> my_dof_handler (7);\n//  my_dof_handler[0]= &locally_relevant_solution_T;\n//  my_dof_handler[1]= &old_locally_relevant_solution_T;\n//  my_dof_handler[2]= &locally_relevant_solution_P;\n//  my_dof_handler[3]= &old_locally_relevant_solution_P;\n//  my_dof_handler[4]= &locally_relevant_solution_Sigma;\n//  my_dof_handler[5]= &old_locally_relevant_solution_Sigma;\n//  my_dof_handler[6]= &locally_relevant_solution_F;\n\n\n  parallel::distributed::SolutionTransfer<dim,LA::MPI::Vector>\n  temp_trans(dof_handler);\n  parallel::distributed::SolutionTransfer<dim,LA::MPI::Vector>\n  old_temp_trans(dof_handler);\n\n  parallel::distributed::SolutionTransfer<dim,LA::MPI::Vector>\n  overburden_trans(dof_handler);\n  parallel::distributed::SolutionTransfer<dim,LA::MPI::Vector>\n  old_overburden_trans(dof_handler);\n\n  parallel::distributed::SolutionTransfer<dim,LA::MPI::Vector>\n  pressure_trans(dof_handler);\n  parallel::distributed::SolutionTransfer<dim,LA::MPI::Vector>\n  old_pressure_trans(dof_handler);\n\n  parallel::distributed::SolutionTransfer<dim,LA::MPI::Vector>\n  speed_trans(dof_handler);\n\n  //TODO one layer for now\n//  parallel::distributed::SolutionTransfer<dim,LA::MPI::Vector>\n//  ls0_trans(dof_handler_LS);\n\n  for(int i=0; i<n_layers; ++i)\n  {\n      layers_transfers.emplace_back(\n            new  parallel::distributed::SolutionTransfer\n            <dim,LA::MPI::Vector>(dof_handler_LS) );\n   }\n\n\n  triangulation.prepare_coarsening_and_refinement();\n\n//    my_vectors_trans.prepare_for_coarsening_and_refinement(my_dof_handler);\n\n   temp_trans.prepare_for_coarsening_and_refinement(locally_relevant_solution_T);\n   old_temp_trans.prepare_for_coarsening_and_refinement(old_locally_relevant_solution_T);\n\n  pressure_trans.prepare_for_coarsening_and_refinement(locally_relevant_solution_P );\n  old_pressure_trans.prepare_for_coarsening_and_refinement(old_locally_relevant_solution_P);\n\n  overburden_trans.prepare_for_coarsening_and_refinement(locally_relevant_solution_Sigma);\n  old_overburden_trans.prepare_for_coarsening_and_refinement(old_locally_relevant_solution_Sigma);\n   speed_trans.prepare_for_coarsening_and_refinement(locally_relevant_solution_F);\n\n\n//  ls0_trans.prepare_for_coarsening_and_refinement(locally_relevant_solution_LS_0);\n\n  LA::MPI::Vector tmp1,tmp2, tmp3, tmp4, tmp5, tmp6;\n  tmp1.reinit(locally_relevant_solution_LS_0);\n  tmp2.reinit(locally_relevant_solution_LS_0);\n  tmp3.reinit(locally_relevant_solution_LS_0);\n  tmp4.reinit(locally_relevant_solution_LS_0);\n  tmp5.reinit(locally_relevant_solution_LS_0);\n  tmp6.reinit(locally_relevant_solution_LS_0);\n  for(int i=0; i<n_layers; ++i)\n  {\n      std::vector<const LA::MPI::Vector *> all_rel_ls_vectors (7);\n      layers[i]->get_vectors_for_refinement(tmp1, tmp2, tmp3, tmp4, tmp5, tmp6);\n\n      all_rel_ls_vectors[0]= &tmp1;\n      all_rel_ls_vectors[1]= &tmp2;\n      all_rel_ls_vectors[2]= &tmp3;\n      all_rel_ls_vectors[3]= &tmp4;\n      all_rel_ls_vectors[4]= &tmp5;\n      all_rel_ls_vectors[5]= &tmp6;\n\n      all_rel_ls_vectors[6]= &locally_relevant_solution_LS_0;\n\n      layers_transfers[i]->prepare_for_coarsening_and_refinement(all_rel_ls_vectors);\n\n   }\n  //third refine - mesh changes here!\n  triangulation.execute_coarsening_and_refinement ();\n\n\n  setup_dofs();\n  setup_system_P();\n  setup_system_T();\n  setup_system_Sigma();\n  setup_system_F();\n\n  setup_system_LS();\n  get_boundary_values_LS(boundary_values_id_LS, boundary_values_LS);\n\n\n  LA::MPI::Vector tmp (completely_distributed_solution_Sigma);\n\n\n  overburden_trans.interpolate(tmp);\n  constraints_Sigma.distribute(tmp);\n  locally_relevant_solution_Sigma=tmp;\n\n  speed_trans.interpolate(tmp);\n  constraints_F.distribute(tmp);\n  locally_relevant_solution_F=tmp;\n\n  LA::MPI::Vector dtmp1,dtmp2, dtmp3, dtmp4, dtmp5, dtmp6;//d is for distributed (no ghost values)\n  dtmp1.reinit(completely_distributed_solution_LS_0);\n  dtmp2.reinit(completely_distributed_solution_LS_0);\n  dtmp3.reinit(completely_distributed_solution_LS_0);\n  dtmp4.reinit(completely_distributed_solution_LS_0);\n  dtmp5.reinit(completely_distributed_solution_LS_0);\n  dtmp6.reinit(completely_distributed_solution_LS_0);\n  LA::MPI::Vector tmp_ls (completely_distributed_solution_LS_0);\n  for(int i=0; i<n_layers; ++i)\n  {\n      //get new dof indexes and resize the data structures\n      layers[i]->setup();\n\n      layers_solutions[i]->reinit(locally_owned_dofs_LS, locally_relevant_dofs_LS, mpi_communicator);\n      //create a vector of pointers to completely distributed temporary vectors\n\n      std::vector<LA::MPI::Vector *> tempo(7);\n      tempo[0]=&dtmp1;\n      tempo[1]=&dtmp2;\n      tempo[2]=&dtmp3;\n      tempo[3]=&dtmp4;\n      tempo[4]=&dtmp5;\n      tempo[5]=&dtmp6;\n      tempo[6]=&tmp_ls;\n      //p::d::SolutionTransfer carries out the interpolation\n      layers_transfers[i]->interpolate(tempo);\n\n      //constraints applied\n      constraints_LS.distribute(dtmp1);\n      constraints_LS.distribute(dtmp2);\n      constraints_LS.distribute(dtmp3);\n      constraints_LS.distribute(dtmp4);\n      constraints_LS.distribute(dtmp5);\n      constraints_LS.distribute(dtmp6);\n      constraints_LS.distribute(tmp_ls);\n\n      //set the locally relevant vectors\n      tmp1=dtmp1;\n      tmp2=dtmp2;\n      tmp3=dtmp3;\n      tmp4=dtmp4;\n      tmp5=dtmp5;\n      tmp6=dtmp6;\n      locally_relevant_solution_LS_0=tmp_ls;\n\n      //set in the level set solver\n\n      layers[i]->set_vectors_after_refinement(tmp1, tmp2, tmp3, tmp4, tmp5, tmp6);\n\n\n\n      //(*layers_solutions[i])=tmp_ls;\n\n      layers[i]->set_boundary_conditions(boundary_values_id_LS, boundary_values_LS);\n\n      if(dim==3){\n      layers[i]->set_velocity(locally_relevant_solution_Wxy,locally_relevant_solution_Wxy, locally_relevant_solution_F);\n        }\n      else{\n        layers[i]->set_velocity(locally_relevant_solution_Wxy, locally_relevant_solution_F);\n        }\n\n  }\n      //layers[i]->set_boundary_conditions(boundary_values_id_LS, boundary_values_LS);\n\n\n\n  // fourth: interpolate solution vectors onto new mesh\n  {\n    //TODO clarify ghost/non-ghost with old names\n   // completely_distributed_solution_P=locally_relevant_solution_P;\n\n   // LA::MPI::Vector tmp (completely_distributed_solution_P);\n    pressure_trans.interpolate(tmp);\n    constraints_P.distribute(tmp);\n    locally_relevant_solution_P=tmp;\n\n   // completely_distributed_solution_P=old_locally_relevant_solution_P;\n  //  tmp=completely_distributed_solution_P;\n    old_pressure_trans.interpolate(tmp);\n    constraints_P.distribute(tmp);\n    old_locally_relevant_solution_P=tmp;\n\n   // completely_distributed_solution_Sigma=locally_relevant_solution_Sigma;\n   // tmp=completely_distributed_solution_Sigma;\n//    overburden_trans.interpolate(tmp);\n//    constraints_Sigma.distribute(tmp);\n//    locally_relevant_solution_Sigma=tmp;\n\n//     completely_distributed_solution_Sigma=old_locally_relevant_solution_Sigma;\n  //  tmp=completely_distributed_solution_Sigma;\n    old_overburden_trans.interpolate(tmp);\n    constraints_Sigma.distribute(tmp);\n    old_locally_relevant_solution_Sigma=tmp;\n\n//    completely_distributed_solution_T=locally_relevant_solution_T;\n //   tmp=completely_distributed_solution_T;\n    temp_trans.interpolate(tmp);\n    constraints_T.distribute(tmp);\n    locally_relevant_solution_T=tmp;\n\n //   completely_distributed_solution_T=old_locally_relevant_solution_T;\n  //  tmp=completely_distributed_solution_T;\n    old_temp_trans.interpolate(tmp);\n    constraints_T.distribute(tmp);\n    old_locally_relevant_solution_T=tmp;\n\n//  //  completely_distributed_solution_LS_0=locally_relevant_solution_LS_0;\n//    LA::MPI::Vector tmp_ls (completely_distributed_solution_LS_0);\n//    ls0_trans.interpolate(tmp_ls);\n//    constraints_LS.distribute(tmp_ls);\n//    locally_relevant_solution_LS_0=tmp_ls;\n\n\npcout<<\"transferred\";\n//    for(int i=0; i<1; ++i)//TODO 1 layer only\n//    {\n\n////        if(dim==3){\n////        layers[i]->set_velocity(locally_relevant_solution_Wxy,locally_relevant_solution_Wxy, locally_relevant_solution_F);\n////          }\n////        else{\n////          layers[i]->set_velocity(locally_relevant_solution_Wxy, locally_relevant_solution_F);\n////          }\n\n//        layers[i]->setup();\n//        //layers[i]->get_unp1(locally_relevant_solution_LS_0);\n//        (*layers_solutions[i])=locally_relevant_solution_LS_0;\n//      }\n\n\n  }\n//  {\n//    TrilinosWrappers::MPI::BlockVector distributed_stokes (stokes_rhs);\n//    TrilinosWrappers::MPI::BlockVector old_distributed_stokes (stokes_rhs);\n//    std::vector<TrilinosWrappers::MPI::BlockVector *> stokes_tmp (2);\n//    stokes_tmp[0] = &(distributed_stokes);\n//    stokes_tmp[1] = &(old_distributed_stokes);\n//    stokes_trans.interpolate (stokes_tmp);\n//    stokes_constraints.distribute(distributed_stokes);\n//    stokes_constraints.distribute(old_distributed_stokes);\n//    stokes_solution     = distributed_stokes;\n//    old_stokes_solution = old_distributed_stokes;\n//  }\n//  computing_timer.exit_section();\n//}\n\n\n}\n\ntemplate <int dim>\nvoid LayerMovementProblem<dim>::run()\n{\n  constexpr double seconds_in_Myear{60*60*24*365.25*1e6};\n  pcout<<\"CPPLS running in \"<<dim<<\" dimensions\"<<std::endl;\n\n    // common mesh\n    setup_geometry();\n    // common dofhandler, except for LS\n    setup_dofs();\n    // these are the 4 systems treated in this code\n    setup_system_P();\n    setup_system_T();\n    setup_system_Sigma();\n    setup_system_F();\n    // the solution of this system is done in the LevelSetSolver class\n    setup_system_LS();\n\n    initial_conditions();\n    const unsigned int output_interval= parameters.output_interval;\n\n\n    //const SedimentationRate SedRate(parameters);\n    const double base_sedimentation_rate = parameters.base_sedimentation_rate;\n    // initialize level set solver\n    // we use some hardcode defaults for now\n\n    const double min_h = GridTools::minimal_cell_diameter(triangulation) / std::sqrt(2);\n    const double cfl =0.1;// parameters.cfl;\n    const double umax = base_sedimentation_rate;  //max_sedRate\n    time_step = cfl * min_h / umax;\n    // pcout<<\"min_h\"<<min_h;\n\n\n    const double cK = 1.0;//compression coeff\n    const double cE = 1.0;//entropy-visc coeff (non-dimensional cf. p 452 (around eq 18) Guermond, 2017)\n    const bool verbose = true;\n    std::string ALGORITHM = \"MPP_uH\";\n    const unsigned int TIME_INTEGRATION = 0;//1 corresponds to SSP33\n\n\n    n_layers=parameters.n_layers;\n    int n_active_layers=0;\n\n\n    // BOUNDARY CONDITIONS FOR LS\n    get_boundary_values_LS(boundary_values_id_LS, boundary_values_LS);\n\n    locally_relevant_solution_F = -1*base_sedimentation_rate;\n\n\n    //assume locally_relevant_solution_LS_0 is a good initial value for all level sets\n\n    for(int i=0; i<n_layers; ++i)\n    {\n        layers.emplace_back(new LevelSetSolver<dim>(degree_LS, degree, time_step,\n                            cK, cE, verbose, ALGORITHM, TIME_INTEGRATION,\n                            triangulation, mpi_communicator,\n                            dof_handler, dof_handler_LS));\n        layers_solutions.emplace_back(new LA::MPI::Vector);\n        layers_solutions[i]->reinit(locally_owned_dofs_LS, locally_relevant_dofs_LS, mpi_communicator);\n\n        layers[i]->set_boundary_conditions(boundary_values_id_LS, boundary_values_LS);\n        if(dim==3){\n        layers[i]->initial_condition(locally_relevant_solution_LS_0, locally_relevant_solution_Wxy,\n                                     locally_relevant_solution_Wxy, locally_relevant_solution_F);\n          }\n        else\n          {\n            layers[i]->initial_condition(locally_relevant_solution_LS_0, locally_relevant_solution_Wxy,\n                                        locally_relevant_solution_F);\n\n          }\n    }\n\n    //display_vectors();\n\n    // TIME STEPPING\n    timestep_number = 1;\n    for (double time = time_step; time <= final_time; time += time_step, ++timestep_number) {\n        pcout << \"Time step \" << timestep_number << \" at t=\" << time <<\"s: \"<<time/seconds_in_Myear<<\"Ma\"<< std::endl;\n        pcout<< \" % complete:\"<<100*(timestep_number*time_step)/final_time<<std::endl; //for constant time_step\n        Assert (time_step< final_time, ExcNotImplemented());\n\n        current_time=time;\n\n        // Solve for F the scalar speed function which is passed to the LevelSetSolver\n        // which expects the vector (wx,wy) or (wx,wy,wz)\n        // dim=2 we pass F as wy and dim=3 we pass F as wz with 0 otherwise\n\n        // Level set computation\n        // original level_set_solver.set_velocity(locally_relevant_solution_u, locally_relevant_solution_v);\n        n_active_layers=active_layers_in_time(time);\n        {\n            TimerOutput::Scope t(computing_timer, \"LS\");\n            for(int i=0; i<n_active_layers; ++i)\n            {\n\n                if(dim==3){\n                layers[i]->set_velocity(locally_relevant_solution_Wxy,locally_relevant_solution_Wxy, locally_relevant_solution_F);\n                  }\n                else{\n                  layers[i]->set_velocity(locally_relevant_solution_Wxy, locally_relevant_solution_F);\n                  }\n\n                layers[i]->nth_time_step();\n                layers[i]->get_unp1(locally_relevant_solution_LS_0);\n                (*layers_solutions[i])=locally_relevant_solution_LS_0;\n\n            }\n        }\n\n        // set material ids based on locally_relevant_solution_LS\n        setup_material_configuration(); // TODO: move away from cell id to values at quad points\n\n        // First get an overburden solution with the current porosity\n        assemble_Sigma();\n        solve_Sigma();    // generates l_r_s_Sigma\n\n        // pressure solution\n        assemble_matrices_P();\n        forge_system_P();\n        solve_time_step_P(); // temp_loc_r_s_P\n\n        // Solve temperature (coefficients depend on porosity, and TODO: should influence viscosity)\n\n        //    assemble_matrices_T();\n        //    forge_system_T();\n        //    solve_time_step_T();\n        setup_system_F();\n        assemble_F();\n        solve_F();\n        //setup_system_F();\n//locally_relevant_solution_F = -1*base_sedimentation_rate;\n        //    if (get_output && time - (output_number)*output_time > 0)\n        //      output_results();\n        if (timestep_number % output_interval == 0) {\n            display_vectors();\n            pcout<<\"begin local refinement routine\"<<std::endl;\n            refine_mesh();\n            display_vectors();\n        }\n\n\n        prepare_next_time_step();\n    } // end of time loop\n\n    //output once at the end\n   // output_results_pp();\n} //end of run function\n\n\n} // end namespace CPPLS\n\nconstexpr int dim {2};\n//constexpr double inflow_rate{3.15e-11};\n\nint main(int argc, char* argv[])\n{\n    // One of the new features in C++11 is the <code>chrono</code> component of\n    // the standard library. This gives us an easy way to time the output.\n    try {\n        using namespace dealii;\n        using namespace CPPLS;\n\n        auto t0 = std::chrono::high_resolution_clock::now();\n\n        Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv, 1);\n\n        CPPLS::Parameters parameters;\n        parameters.read_parameter_file(\"parameters.prm\");\n        CPPLS::MaterialData material_data;\n        if (parameters.dimension==2)\n        {\n            LayerMovementProblem<2> run_layers(parameters, material_data);\n            run_layers.run();\n        }\n        else if (parameters.dimension==3)\n          {\n            LayerMovementProblem<3> run_layers(parameters, material_data);\n            run_layers.run();\n\n          }\n        else\n          {\n             AssertThrow (false, ExcNotImplemented());\n          }\n\n        auto t1 = std::chrono::high_resolution_clock::now();\n        if (Utilities::MPI::this_mpi_process(MPI_COMM_WORLD) == 0) {\n            std::cout << \"time elapsed: \" << std::chrono::duration_cast<std::chrono::milliseconds>(t1 - t0).count()\n                      << \" milliseconds.\" << std::endl;\n        }\n    }\n    catch (std::exception& exc) {\n        std::cerr << std::endl << std::endl << \"----------------------------------------------------\" << std::endl;\n        std::cerr << \"Exception on processing: \" << std::endl\n                  << exc.what() << std::endl\n                  << \"Aborting!\" << std::endl\n                  << \"----------------------------------------------------\" << std::endl;\n\n        return 1;\n    }\n    catch (...) {\n        std::cerr << std::endl << std::endl << \"----------------------------------------------------\" << std::endl;\n        std::cerr << \"Unknown exception!\" << std::endl\n                  << \"Aborting!\" << std::endl\n                  << \"----------------------------------------------------\" << std::endl;\n        return 1;\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "395eac4ff588be51e1799373074bb72cace9ebd5", "size": 92521, "ext": "cc", "lang": "C++", "max_stars_repo_path": "source/cppls.cc", "max_stars_repo_name": "Sean-GMD/CPPLS_AMR", "max_stars_repo_head_hexsha": "a839cf440cdbbcdd9b6a0db3312b63e8cb7a733d", "max_stars_repo_licenses": ["MIT"], "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/cppls.cc", "max_issues_repo_name": "Sean-GMD/CPPLS_AMR", "max_issues_repo_head_hexsha": "a839cf440cdbbcdd9b6a0db3312b63e8cb7a733d", "max_issues_repo_licenses": ["MIT"], "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/cppls.cc", "max_forks_repo_name": "Sean-GMD/CPPLS_AMR", "max_forks_repo_head_hexsha": "a839cf440cdbbcdd9b6a0db3312b63e8cb7a733d", "max_forks_repo_licenses": ["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.7426975945, "max_line_length": 131, "alphanum_fraction": 0.6852822602, "num_tokens": 21870, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.5926665999540697, "lm_q1q2_score": 0.45081223607509247}}
{"text": "/* ---------------------------------------------------------------------\n *\n * Copyright (C) 1999 - 2019 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\n#include <deal.II/base/function.h>\n#include <deal.II/base/logstream.h>\n#include <deal.II/base/parameter_acceptor.h>\n#include <deal.II/base/quadrature_lib.h>\n\n#include <deal.II/dofs/dof_accessor.h>\n#include <deal.II/dofs/dof_handler.h>\n#include <deal.II/dofs/dof_tools.h>\n\n#include <deal.II/fe/fe_q.h>\n#include <deal.II/fe/fe_values.h>\n\n#include <deal.II/grid/grid_generator.h>\n#include <deal.II/grid/tria.h>\n#include <deal.II/grid/tria_accessor.h>\n#include <deal.II/grid/tria_iterator.h>\n\n#include <deal.II/lac/dynamic_sparsity_pattern.h>\n#include <deal.II/lac/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#include <deal.II/lac/sparse_matrix.h>\n#include <deal.II/lac/vector.h>\n\n#include <deal.II/numerics/data_out.h>\n#include <deal.II/numerics/matrix_tools.h>\n#include <deal.II/numerics/vector_tools.h>\n\n#include <fstream>\n#include <iostream>\n\nusing namespace dealii;\n\n\ntemplate <int dim>\nclass TransportDiffusion : public ParameterAcceptor\n{\npublic:\n  TransportDiffusion();\n  void\n  run();\n\nprivate:\n  void\n  make_grid();\n  void\n  setup_system();\n  void\n  assemble_system();\n  void\n  solve();\n  void\n  output_results() 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\n  Vector<double> solution;\n  Vector<double> system_rhs;\n\n  double         eps           = 1;\n  double         stabilization = 0;\n  unsigned int   n_refinements = 5;\n  Tensor<1, dim> transport_vector;\n};\n\n\ntemplate <int dim>\nTransportDiffusion<dim>::TransportDiffusion()\n  : fe(1)\n  , dof_handler(triangulation)\n{\n  add_parameter(\"Epsilon\", eps);\n  add_parameter(\"N refinements\", n_refinements);\n  add_parameter(\"Transport vector\", transport_vector);\n  add_parameter(\"Stabilization\", stabilization);\n}\n\n\n\ntemplate <int dim>\nvoid\nTransportDiffusion<dim>::make_grid()\n{\n  GridGenerator::hyper_cube(triangulation, -1, 1);\n  triangulation.refine_global(n_refinements);\n\n  std::cout << \"   Number of active cells: \" << triangulation.n_active_cells()\n            << std::endl\n            << \"   Total number of cells: \" << triangulation.n_cells()\n            << std::endl;\n}\n\n\ntemplate <int dim>\nvoid\nTransportDiffusion<dim>::setup_system()\n{\n  dof_handler.distribute_dofs(fe);\n\n  std::cout << \"   Number of degrees of freedom: \" << dof_handler.n_dofs()\n            << std::endl;\n\n  DynamicSparsityPattern dsp(dof_handler.n_dofs());\n  DoFTools::make_sparsity_pattern(dof_handler, dsp);\n  sparsity_pattern.copy_from(dsp);\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\ntemplate <int dim>\nvoid\nTransportDiffusion<dim>::assemble_system()\n{\n  QGauss<dim> quadrature_formula(fe.degree + 1);\n\n  Functions::ConstantFunction<dim> right_hand_side(1);\n\n  FEValues<dim> fe_values(fe,\n                          quadrature_formula,\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    = quadrature_formula.size();\n\n  FullMatrix<double> cell_matrix(dofs_per_cell, dofs_per_cell);\n  Vector<double>     cell_rhs(dofs_per_cell);\n\n  std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell);\n\n  for (const auto &cell : dof_handler.active_cell_iterators())\n    {\n      fe_values.reinit(cell);\n      cell_matrix = 0;\n      cell_rhs    = 0;\n\n      double h = cell->diameter();\n\n      for (unsigned int q_index = 0; q_index < n_q_points; ++q_index)\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) +=\n                ((eps + stabilization * h) * fe_values.shape_grad(i, q_index) *\n                   fe_values.shape_grad(j, q_index) +\n                 fe_values.shape_value(i, q_index) *\n                   (fe_values.shape_grad(j, q_index) * transport_vector)) *\n                fe_values.JxW(q_index);\n\n            const auto x_q = fe_values.quadrature_point(q_index);\n            cell_rhs(i) += (fe_values.shape_value(i, q_index) * // phi_i(x_q)\n                            right_hand_side.value(x_q) *        // f(x_q)\n                            fe_values.JxW(q_index));            // dx\n          }\n\n      cell->get_dof_indices(local_dof_indices);\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    }\n\n\n  std::map<types::global_dof_index, double> boundary_values;\n  VectorTools::interpolate_boundary_values(dof_handler,\n                                           0,\n                                           ZeroFunction<dim>(),\n                                           boundary_values);\n  MatrixTools::apply_boundary_values(boundary_values,\n                                     system_matrix,\n                                     solution,\n                                     system_rhs);\n}\n\n\n\ntemplate <int dim>\nvoid\nTransportDiffusion<dim>::solve()\n{\n  SparseDirectUMFPACK Ainv;\n  Ainv.initialize(system_matrix);\n  Ainv.vmult(solution, system_rhs);\n}\n\n\n\ntemplate <int dim>\nvoid\nTransportDiffusion<dim>::output_results() const\n{\n  DataOut<dim> data_out;\n\n  data_out.attach_dof_handler(dof_handler);\n  data_out.add_data_vector(solution, \"solution\");\n\n  data_out.build_patches();\n\n  std::ofstream output(dim == 2 ? \"solution-2d.vtu\" : \"solution-3d.vtu\");\n  data_out.write_vtu(output);\n}\n\n\n\ntemplate <int dim>\nvoid\nTransportDiffusion<dim>::run()\n{\n  std::cout << \"Solving problem in \" << dim << \" space dimensions.\"\n            << std::endl;\n\n  make_grid();\n  setup_system();\n  assemble_system();\n  solve();\n  output_results();\n}\n\n\n\nint\nmain()\n{\n  deallog.depth_console(0);\n  {\n    TransportDiffusion<2> laplace_problem_2d;\n    laplace_problem_2d.initialize(\"parameters.prm\", \"used_parameters.prm\");\n    laplace_problem_2d.run();\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "242fd2a8e790d6da20fda021e77ef7838cc67f63", "size": 6948, "ext": "cc", "lang": "C++", "max_stars_repo_path": "cpp/05_first_strang_lemma_and_stab/transport-diffusion.cc", "max_stars_repo_name": "luca-heltai/advanced-fem", "max_stars_repo_head_hexsha": "7dc5416db07ee67410819e4f9680471548c6641a", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-03-13T22:07:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-12T07:59:37.000Z", "max_issues_repo_path": "cpp/05_first_strang_lemma_and_stab/transport-diffusion.cc", "max_issues_repo_name": "luca-heltai/advanced-fem", "max_issues_repo_head_hexsha": "7dc5416db07ee67410819e4f9680471548c6641a", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp/05_first_strang_lemma_and_stab/transport-diffusion.cc", "max_forks_repo_name": "luca-heltai/advanced-fem", "max_forks_repo_head_hexsha": "7dc5416db07ee67410819e4f9680471548c6641a", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.2188679245, "max_line_length": 79, "alphanum_fraction": 0.6303972366, "num_tokens": 1690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.45081223607509247}}
{"text": "#include <geometry.h>\n#include <tiny_math_types.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n\n\nBOOST_AUTO_TEST_SUITE(geometry);\n\nBOOST_AUTO_TEST_CASE(raycast_sphere)\n{\n  using std::sqrt;\n\n  typedef tiny::MathTypes<double>   MT;\n  typedef MT::vector3_type          V;\n  typedef MT::real_type             T;\n  typedef MT::value_traits          VT;\n\n\n  V const center = V::make(0.0,0.0,0.0);\n  T const radius = VT::one();\n\n  geometry::Sphere<V> sphere = geometry::make_sphere(center, radius);\n\n  // ray hitting straight on\n  {\n    V const r      = V::make( 0.0, 0.0, 1.0);\n    V const p      = V::make( 0.0, 0.0,-3.0);\n\n    geometry::Ray<V> const ray = geometry::make_ray(p, r);\n\n    T       length = VT::zero();\n    V       q      = V::zero();\n\n    bool hit = geometry::compute_raycast_sphere(ray, sphere, q, length);\n\n    BOOST_CHECK( hit );\n\n    BOOST_CHECK_CLOSE( length, 2.0, 0.01);\n    BOOST_CHECK_CLOSE( q(0),  0.0, 0.01);\n    BOOST_CHECK_CLOSE( q(1),  0.0, 0.01);\n    BOOST_CHECK_CLOSE( q(2), -1.0, 0.01);\n  }\n\n  // ray shooting staright away\n  {\n    V const r      = V::make( 0.0, 0.0,-1.0);\n    V const p      = V::make( 0.0, 0.0,-3.0);\n\n    geometry::Ray<V> const ray = geometry::make_ray(p, r);\n\n    T       length = VT::zero();\n    V       q      = V::zero();\n\n    bool hit = geometry::compute_raycast_sphere(ray, sphere, q, length);\n\n    BOOST_CHECK( !hit );\n\n  }\n\n  // ray starts inside\n  {\n    V const r      = V::make( 0.0, 0.0,-1.0);\n    V const p      = V::make( 0.0, 0.0, 0.5);\n\n    geometry::Ray<V> const ray = geometry::make_ray(p, r);\n\n    T       length = VT::zero();\n    V       q      = V::zero();\n\n    bool hit = geometry::compute_raycast_sphere(ray, sphere, q, length);\n\n    BOOST_CHECK( !hit );\n    \n  }\n\n  // ray shooting pass sphere\n  {\n    V const r      = V::make( 4.0, 0.0, 1.0);\n    V const p      = V::make( 0.0, 0.0,-3.0);\n\n    geometry::Ray<V> const ray = geometry::make_ray(p, r);\n\n    T       length = VT::zero();\n    V       q      = V::zero();\n\n    bool hit = geometry::compute_raycast_sphere(ray, sphere, q, length);\n\n    BOOST_CHECK( !hit );\n  }\n\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "89316e082c8649da46931dd15b7c8ddc3f35a878", "size": 2280, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/FOUNDATION/GEOMETRY/unit_tests/geometry_raycast_sphere/geometry_raycast_sphere.cpp", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-11-27T09:44:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-13T00:24:21.000Z", "max_issues_repo_path": "PROX/FOUNDATION/GEOMETRY/unit_tests/geometry_raycast_sphere/geometry_raycast_sphere.cpp", "max_issues_repo_name": "erleben/matchstick", "max_issues_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_issues_repo_licenses": ["MIT"], "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/FOUNDATION/GEOMETRY/unit_tests/geometry_raycast_sphere/geometry_raycast_sphere.cpp", "max_forks_repo_name": "erleben/matchstick", "max_forks_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_forks_repo_licenses": ["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.2653061224, "max_line_length": 72, "alphanum_fraction": 0.5754385965, "num_tokens": 726, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255928, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.450812229643655}}
{"text": "#include <iostream>\n#include <ctime>\n#include <iomanip>\n#include <map>\n#include <tuple>\n#include \"date.h\"\n#include <boost/property_tree/ptree.hpp>\n#include <boost/property_tree/json_parser.hpp>\n#include <boost/program_options.hpp>\n\nnamespace pt = boost::property_tree;\nnamespace po = boost::program_options;\nusing namespace std;\n\nint main(int argc, char *argv[])\n{\n    if (argc < 2)\n    {\n        cerr<< \"enter json file\";\n        return 1;\n    }\n    string filename = argv[1];\n    cout << \"\u0440\u0430\u0441\u0441\u0447\u0435\u0442 \u043a\u0440\u0435\u0434\u0438\u0442\u0430\" << endl;\n    pt::ptree root;\n    pt::read_json(filename, root);\n    map<Date, double> precents;\n    for (auto& item: root.get_child(\"precents\"))\n    {\n        auto& item0 = item.second.front();\n        auto d = stringToDate(item0.first);\n        precents[d] = item0.second.get_value<double>();\n    }\n\n    map<Date, double> pays;\n    for (auto& item: root.get_child(\"pays\"))\n    {\n        auto& item0 = item.second.front();\n        auto d = stringToDate(item0.first);\n        pays[d] = item0.second.get_value<int>();\n    }\n\n    auto currentDatestr = root.get<string>(\"currentDate\", \"\");\n    auto currentDate = stringToDate(currentDatestr);\n\n    int planedPay = root.get<int>(\"planedPay\", 0);\n    double balance = root.get<int>(\"debt\", 0);\n    int durationYears = root.get<int>(\"duration\", 0);\n\n    for (int i = 0 ; i < 20 && planedPay != 0; ++i)\n    {\n        pays[currentDate] = planedPay;\n        currentDate.monthInc();\n    }\n\n    cout << \"current \" << currentDatestr << endl;\n    Date currentdate = begin(precents)->first;\n    double percent = begin(precents)->second;\n    int duration = durationYears * 12;\n    double debt = balance / duration;\n    double pay;\n    int overpay = 0;\n    while (balance > 0)\n    {\n        currentdate.monthInc();\n        auto currentPercent = precents.find(currentdate);\n        percent = currentPercent != end(precents) ? currentPercent->second : percent;\n        double percentages = balance * (percent/100/12);\n\n        overpay += percentages;\n\n        pay = debt + percentages;\n\n        auto currentPay = pays.find(currentdate);\n        pay = currentPay != end(pays) ? currentPay->second : pay;\n\n        pay = pay < (balance + percentages)? pay : (balance + percentages);\n        balance = balance - (pay - percentages);\n        auto t = currentdate.toTm();\n        cout << \"\u043f\u0435\u0440\u0438\u043e\u0434: \" << put_time(&t, \"%B %t %Y\");\n        cout << \" \u0432\u044b\u043f\u043b\u0430\u0442\u0430: \" << pay;\n        cout << \" \u0434\u043e\u043b\u0433: \" << (pay - percentages);\n        cout << \" \u043f\u0440\u043e\u0446\u0435\u043d\u0442\u044b: \" << percentages;\n        cout << \" \u043e\u0441\u0442\u0430\u0442\u043e\u043a: \" << balance;\n        cout << \" \u043f\u0440\u043e\u0446\u0435\u043d\u0442: \" << percent;\n        cout << \" \u043f\u0435\u0440\u0435\u043f\u043b\u0430\u0442\u0430: \" << overpay;\n        cout << endl;\n    }\n    return 0;\n}\n", "meta": {"hexsha": "ebf62f23924eb716240a57125479b67d23a95715", "size": 2663, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "Alexandr-Galko/CreditCalc", "max_stars_repo_head_hexsha": "2f4da6eb5d30c299d7d6b8db88284e362c7cc68f", "max_stars_repo_licenses": ["Apache-2.0"], "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": "Alexandr-Galko/CreditCalc", "max_issues_repo_head_hexsha": "2f4da6eb5d30c299d7d6b8db88284e362c7cc68f", "max_issues_repo_licenses": ["Apache-2.0"], "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": "Alexandr-Galko/CreditCalc", "max_forks_repo_head_hexsha": "2f4da6eb5d30c299d7d6b8db88284e362c7cc68f", "max_forks_repo_licenses": ["Apache-2.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.5888888889, "max_line_length": 85, "alphanum_fraction": 0.5910627112, "num_tokens": 694, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255928, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.450812229643655}}
{"text": "//==============================================================================\n//         Copyright 2014          LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//         Copyright 2014          NumScale SAS\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef BOOST_NUMERIC_ODEINT_EXTERNAL_NT2_NT2_NORM_INF_HPP_INCLUDED\n#define BOOST_NUMERIC_ODEINT_EXTERNAL_NT2_NT2_NORM_INF_HPP_INCLUDED\n\n#include <nt2/core/container/table/table.hpp>\n#include <nt2/include/functions/globalmax.hpp>\n#include <nt2/include/functions/abs.hpp>\n\n#include <boost/numeric/odeint/algebra/vector_space_algebra.hpp>\n\nnamespace boost { namespace numeric { namespace odeint\n{\n  template<typename T, typename S>\n  struct vector_space_norm_inf<nt2::container::table<T,S> >\n  {\n    typedef T result_type;\n    result_type operator()(const nt2::container::table<T,S> &v1) const\n    {\n      return nt2::globalmax(nt2::abs(v1));\n    }\n  };\n} } }\n\n#endif\n", "meta": {"hexsha": "81f867e35367514b5b0217564c5b2545454d0da1", "size": 1148, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/libboost/boost_1_62_0/boost/numeric/odeint/external/nt2/nt2_norm_inf.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/external/nt2/nt2_norm_inf.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/external/nt2/nt2_norm_inf.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": 35.875, "max_line_length": 80, "alphanum_fraction": 0.5984320557, "num_tokens": 250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255928, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.450812229643655}}
{"text": "#ifndef GRADIENT_PSV_H_\n#define GRADIENT_PSV_H_\n\n#include \"gradient.hpp\"\n#include <Eigen/Dense>\n#include <memory>\n#include <vector>\n\nusing VecMat4cd =\n    std::vector<Eigen::Matrix4cd, Eigen::aligned_allocator<Eigen::Matrix4cd>>;\nusing VecMat24cd = std::vector<\n    Eigen::Matrix<std::complex<double>, 2, 4>,\n    Eigen::aligned_allocator<Eigen::Matrix<std::complex<double>, 2, 4>>>;\n\nnamespace grad_psv {\nclass GRTCoeff {\n  friend class IntegralLayer;\n\npublic:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n  GRTCoeff(const Eigen::Ref<const Eigen::ArrayXXd> model, const double freq,\n           const double c);\n\nprivate:\n  void initialize_gamma();\n  void initialize_nv();\n  void initialize_E();\n  Eigen::Matrix2cd get_Ad(const double z, const int ind_layer) const;\n  Eigen::Matrix2cd get_Au(const double z, const int ind_layer) const;\n  Eigen::Matrix2cd get_Ad_der(const double z, const int ind_layer) const;\n  Eigen::Matrix2cd get_Au_der(const double z, const int ind_layer) const;\n\n  void compute_rtc();\n  void compute_grtc();\n  void compute_CdCu();\n\n  const Eigen::ArrayXd z_, rho_, beta_, alpha_, mu_;\n  const int nl_;\n  const std::complex<double> angfreq_;\n  const double c_;\n\n  Eigen::ArrayXcd gamma_, nv_;\n  std::vector<Eigen::Matrix2cd, Eigen::aligned_allocator<Eigen::Matrix2cd>>\n      e11_, e12_, e21_, e22_,   //\n      t_d_, r_ud_, r_du_, t_u_, //\n      gt_d_, gr_ud_, gr_du_, gt_u_;\n  std::vector<Eigen::Vector2cd, Eigen::aligned_allocator<Eigen::Vector2cd>> Cd_,\n      Cu_;\n\n  const Eigen::Matrix2cd matI_ = Eigen::Matrix2cd::Identity();\n};\n\nclass IntegralLayer {\npublic:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n  IntegralLayer(const Eigen::Ref<const Eigen::ArrayXXd> model,\n                const double freq, const double c);\n\n  double compute_I1();\n  double compute_I2();\n  double compute_I3();\n  Eigen::ArrayXd compute_kvs();\n\nprivate:\n  void initialize_P();\n  void initialize_sigma();\n\n  double intker_us2_top(int id_layer);\n  double intker_ur2_top(int id_layer);\n  double intker_dus2_top(int id_layer);\n  double intker_dur2_top(int id_layer);\n  double intker_urdus_top(int id_layer);\n  double intker_usdur_top(int id_layer);\n\n  double intker_us2_bottom(int id_layer);\n  double intker_ur2_bottom(int id_layer);\n  double intker_dus2_bottom(int id_layer);\n  double intker_dur2_bottom(int id_layer);\n  double intker_urdus_bottom(int id_layer);\n  double intker_usdur_bottom(int id_layer);\n\n  void integrate_us2();\n  void integrate_ur2();\n  void integrate_dus2();\n  void integrate_dur2();\n  void integrate_usdur();\n  void integrate_urdus();\n\n  const std::unique_ptr<GRTCoeff> grtc_;\n  const int nl_;\n  const double k_;\n  const double pvel_;\n  Eigen::ArrayXd z_, alpha_, beta_, rho_, mu_, lamb_;\n  Eigen::ArrayXcd gamma_, nv_;\n  Eigen::ArrayXcd thickness_;\n\n  std::vector<Eigen::Vector2cd, Eigen::aligned_allocator<Eigen::Vector2cd>> Cd_,\n      Cu_;\n  VecMat24cd matE_;\n  VecMat4cd matP_u_u_;\n  VecMat4cd matP_uc_u_;\n  VecMat4cd matP_uc_uc_;\n  VecMat4cd matP_du_du_;\n  VecMat4cd matP_duc_du_;\n  VecMat4cd matP_duc_duc_;\n  VecMat4cd matP_u_du_;\n  VecMat4cd matP_uc_du_;\n  VecMat4cd matP_u_duc_;\n  VecMat4cd matP_uc_duc_;\n  // top is the upper limit of integral\n  VecMat4cd sigma_x_sigma_top_;\n  VecMat4cd sigmac_x_sigma_top_;\n  VecMat4cd sigma_x_sigmac_top_;\n  VecMat4cd sigmac_x_sigmac_top_;\n  // bottom is the lower limit\n  VecMat4cd sigma_x_sigma_bottom_;\n  VecMat4cd sigmac_x_sigma_bottom_;\n  VecMat4cd sigma_x_sigmac_bottom_;\n  VecMat4cd sigmac_x_sigmac_bottom_;\n\n  Eigen::ArrayXd int_us2_;\n  Eigen::ArrayXd int_ur2_;\n  Eigen::ArrayXd int_dus2_;\n  Eigen::ArrayXd int_dur2_;\n  Eigen::ArrayXd int_urdus_;\n  Eigen::ArrayXd int_usdur_;\n};\n\nclass GradientPSV : public Gradient {\npublic:\n  using Gradient::Gradient;\n  ~GradientPSV();\n  Eigen::ArrayXd compute(const double freq, const double c) const override;\n};\n\n} // namespace grad_psv\n\n#endif", "meta": {"hexsha": "d13a7cb81add828df79e47fd1d7b9b1599cc2c65", "size": 3837, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/gradient_psv.hpp", "max_stars_repo_name": "pan3rock/DisbaTomo", "max_stars_repo_head_hexsha": "b1e6ffa3afd911f1934cd6274854b5fa4161a9cc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2021-07-30T03:27:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T14:05:47.000Z", "max_issues_repo_path": "include/gradient_psv.hpp", "max_issues_repo_name": "pan3rock/DisbaTomo", "max_issues_repo_head_hexsha": "b1e6ffa3afd911f1934cd6274854b5fa4161a9cc", "max_issues_repo_licenses": ["MIT"], "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/gradient_psv.hpp", "max_forks_repo_name": "pan3rock/DisbaTomo", "max_forks_repo_head_hexsha": "b1e6ffa3afd911f1934cd6274854b5fa4161a9cc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2021-07-31T12:38:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-17T15:07:53.000Z", "avg_line_length": 27.8043478261, "max_line_length": 80, "alphanum_fraction": 0.7451133698, "num_tokens": 1112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.5117166047041652, "lm_q1q2_score": 0.45071849017619187}}
{"text": "/*\nCopyright 2012, 2013 Rogier van Dalen.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/** \\internal \\file\nArithmetic operations on values stored as logarithms.\nThese also take Boost.Math policies with regard to error handling into account.\n*/\n\n#ifndef MATH_DETAIL_LOG_FLOAT_ARITHMETIC_HPP\n#define MATH_DETAIL_LOG_FLOAT_ARITHMETIC_HPP\n\n#include <cmath>\n#include <cassert>\n#include <limits>\n\n#include <boost/static_assert.hpp>\n#include <boost/math/policies/policy.hpp>\n#include <boost/math/tools/promotion.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n\n#include \"./log-float_fwd.hpp\"\n\nnamespace math { namespace detail {\n\n    /*\n    std::log1p gives exactly the behaviour we need: log1p (-1) should\n    evaluate to -infinity, which indicates a stored value of 0.\n    A policy could be used with boost::math::log1p, but this is slower.\n    */\n    using std::log1p;\n    using std::exp;\n    using std::log;\n\n    /**\n    Multiply two numbers represented as their logs.\n    This is equivalent to adding them.\n    However, this takes care to produce the correct errors where applicable.\n    */\n    template <class RealType1, class RealType2, class Policy,\n            class OverflowPolicy, class IndeterminateResultPolicy>\n        inline typename promote_args <RealType1, RealType2>::type\n            multiply_log_float (RealType1 const & loga, RealType2 const & logb,\n            Policy const & policy,\n            OverflowPolicy const &, IndeterminateResultPolicy const &)\n    {\n        static char const * function_name = \"multiplication of log_float<%1%>\";\n        typedef typename promote_args <RealType1, RealType2>::type\n            result_type;\n        static constexpr RealType1 a_infinity =\n            std::numeric_limits <RealType1>::infinity();\n        static constexpr RealType2 b_infinity =\n            std::numeric_limits <RealType2>::infinity();\n        static constexpr result_type result_infinity =\n            std::numeric_limits <result_type>::infinity();\n        static constexpr result_type result_nan =\n            std::numeric_limits <result_type>::quiet_NaN();\n\n        // This explicitly provides behaviour that IEEE standard floating\n        // point numbers should provide.\n        if (isnan (loga) || isnan (logb))\n            return result_nan;\n        else if (isinf (loga) || isinf (logb))\n        {\n            if (isinf (loga) && isinf (logb))\n            {\n                if (loga == a_infinity && logb == b_infinity) {\n                    // +inf * +inf = +inf.\n                    // Any overflow has happened before this operation.\n                    return result_infinity;\n                } else if (loga == -a_infinity && logb == -b_infinity) {\n                    // 0 * 0 = 0.\n                    // Any underflow has happened before this operation.\n                    return - result_infinity;\n                } else {\n                    // loga and logb are of opposite signs.\n                    return raise_indeterminate_result_error (\n                        function_name, \"%1% * inf is undefined\",\n                        result_type(), result_nan, Policy());\n                }\n            } else {\n                // Either loga or logb is infinity,\n                // either positive or negative.\n                if (loga == -a_infinity || logb == -b_infinity)\n                    // 0 * (finite value) = 0\n                    return - result_infinity;\n                else {\n                    assert (loga == a_infinity || logb == b_infinity);\n                    // +inf * (finite value) = +inf\n                    return result_infinity;\n                }\n            }\n        } else {\n            result_type result = loga + logb;\n            if (isinf (result)) {\n                if (result == -result_infinity) {\n                    raise_underflow_error <result_type> (function_name,\n                        \"Result of multiplication has underflowed\",\n                        Policy());\n                } else {\n                    assert (result == result_infinity);\n                    raise_overflow_error <result_type> (function_name,\n                        \"Result of multiplication has overflowed\",\n                        Policy());\n                }\n            }\n            return result;\n        }\n    }\n\n    /**\n    Multiply two numbers represented as their logs.\n    This is equivalent to adding them.\n    This implementation is used only when errors are ignored.\n    It may be faster than the explicit implementation.\n    */\n    template <class RealType1, class RealType2, class Policy>\n        inline typename promote_args <RealType1, RealType2>::type\n            multiply_log_float (RealType1 const & loga, RealType2 const & logb,\n                Policy const &,\n                boost::math::policies::overflow_error<\n                    boost::math::policies::ignore_error> const &,\n                boost::math::policies::indeterminate_result_error<\n                    boost::math::policies::ignore_error> const &)\n    {\n        return loga + logb;\n    }\n\n    /**\n    Multiply two numbers represented as their logs.\n    */\n    template <class RealType1, class RealType2, class Policy>\n        inline typename promote_args <RealType1, RealType2>::type\n            multiply_log_float (RealType1 const & loga, RealType2 const & logb,\n                Policy const & policy)\n    {\n        // Forward to an appropriate implementation depending on the\n        // error policy.\n        return multiply_log_float (loga, logb, policy,\n            typename Policy::overflow_error_type(),\n            typename Policy::indeterminate_result_error_type());\n    }\n\n    /**\n    Divide two numbers represented as their logs.\n    This is equivalent to subtraction.\n    However, this takes care to produce the correct errors where applicable.\n    */\n    template <class NumeratorType, class DenominatorType, class Policy,\n            class OverflowPolicy, class UnderflowPolicy,\n            class IndeterminateResultPolicy>\n        inline typename promote_args <NumeratorType, DenominatorType>::type\n            divide_log_float (NumeratorType const & log_numerator,\n                DenominatorType const & log_denominator,\n                Policy const & policy,\n                OverflowPolicy const &, UnderflowPolicy const &,\n                IndeterminateResultPolicy const &)\n    {\n        static char const * function_name = \"division of log_float<%1%>\";\n        typedef typename promote_args <NumeratorType, DenominatorType>::type\n            result_type;\n        static constexpr NumeratorType numerator_infinity =\n            std::numeric_limits <NumeratorType>::infinity();\n        static constexpr DenominatorType denominator_infinity =\n            std::numeric_limits <DenominatorType>::infinity();\n        static constexpr result_type result_infinity =\n            std::numeric_limits <result_type>::infinity();\n        static constexpr result_type result_nan =\n            std::numeric_limits <result_type>::quiet_NaN();\n\n        // This explicitly provides behaviour that IEEE standard floating\n        // point numbers should provide.\n        if (isnan (log_numerator) || isnan (log_denominator))\n            return result_nan;\n        else if (isinf (log_numerator) || isinf (log_denominator)) {\n            if (log_denominator == -denominator_infinity) {\n                if (log_numerator == -numerator_infinity) {\n                    return raise_indeterminate_result_error (\n                        function_name, \"%1% / 0 is undefined\",\n                        result_type(), result_nan, Policy());\n                } else {\n                    if (log_numerator == numerator_infinity)\n                        // inf / 0 = inf: not really overflow,\n                        // just propagation of infinity.\n                        return result_infinity;\n                    else\n                        return raise_overflow_error <result_type> (\n                            function_name, \"division by zero causes overflow\",\n                            Policy());\n                }\n            } else if (log_denominator == denominator_infinity) {\n                if (log_numerator == numerator_infinity) {\n                    return raise_indeterminate_result_error (\n                        function_name, \"%1% / %1% is undefined\",\n                        result_type (log_numerator), result_nan, Policy());\n                } else {\n                    // (finite value) / inf = 0.\n                    // The overflow has already happened, so this is not\n                    // classified as underflow.\n                    return -result_infinity;\n                }\n            } else {\n                assert (!isinf (log_denominator));\n                assert (isinf (log_numerator));\n                if (log_numerator == -numerator_infinity)\n                    return -result_infinity;\n                else {\n                    assert (log_numerator == numerator_infinity);\n                    return result_infinity;\n                }\n            }\n        } else {\n            result_type result = log_numerator - log_denominator;\n            if (isinf (result)) {\n                if (result == -result_infinity\n                        && log_numerator != -numerator_infinity) {\n                    raise_underflow_error <result_type> (function_name,\n                        \"Result of division has underflowed\",\n                        Policy());\n                } else {\n                    assert (result == result_infinity);\n                    if (log_numerator != numerator_infinity)\n                        raise_overflow_error <result_type> (function_name,\n                            \"Result of division has overflowed\",\n                            Policy());\n                }\n            }\n            return result;\n        }\n    }\n\n    /**\n    Divide two numbers represented as their logs.\n    This is equivalent to subtraction.\n    This implementation is used only when errors are ignored.\n    It may be faster than the explicity implementation.\n    */\n    template <class NumeratorType, class DenominatorType, class Policy>\n        inline typename promote_args <NumeratorType, DenominatorType>::type\n            divide_log_float (NumeratorType const & log_numerator,\n                DenominatorType const & log_denominator,\n                Policy const &,\n                boost::math::policies::overflow_error<\n                    boost::math::policies::ignore_error> const &,\n                boost::math::policies::underflow_error<\n                    boost::math::policies::ignore_error> const &,\n                boost::math::policies::indeterminate_result_error<\n                    boost::math::policies::ignore_error> const &)\n    { return log_numerator - log_denominator; }\n\n    /**\n    Divide two numbers represented as their logs.\n    This is equivalent to subtraction.\n    */\n    template <class NumeratorType, class DenominatorType, class Policy>\n        inline typename promote_args <NumeratorType, DenominatorType>::type\n            divide_log_float (NumeratorType const & log_numerator,\n                DenominatorType const & log_denominator,\n                Policy const & policy)\n    {\n        // Forward to an appropriate implementation depending on the\n        // error policy.\n        return divide_log_float (log_numerator, log_denominator, policy,\n            typename Policy::overflow_error_type(),\n            typename Policy::underflow_error_type(),\n            typename Policy::indeterminate_result_error_type());\n    }\n\n    /**\n    Add two numbers represented as their logs.\n    This takes care to produce the correct errors where applicable.\n    */\n    template <class RealType1, class RealType2,\n            class Policy, class OverflowPolicy>\n        inline typename promote_args <RealType1, RealType2>::type\n            add_log_float (RealType1 const & loga, RealType2 const & logb,\n            Policy const & policy, OverflowPolicy const &)\n    {\n        static char const * function_name = \"addition of log_float<%1%>\";\n        typedef typename promote_args <RealType1, RealType2>::type\n            result_type;\n        static constexpr RealType1 a_infinity =\n            std::numeric_limits <RealType1>::infinity();\n        static constexpr RealType2 b_infinity =\n            std::numeric_limits <RealType2>::infinity();\n        static constexpr result_type result_infinity =\n            std::numeric_limits <result_type>::infinity();\n        static constexpr result_type result_nan =\n            std::numeric_limits <result_type>::quiet_NaN();\n\n        // This explicitly provides behaviour that IEEE standard floating\n        // point numbers should provide.\n        if (isnan (loga) || isnan (logb))\n            return result_nan;\n        else if (isinf (loga) && isinf (logb)) {\n            if (loga == -a_infinity && logb == -b_infinity)\n                return -result_infinity;\n            else {\n                assert (loga == a_infinity || logb == b_infinity);\n                // 0 + inf = inf\n                // inf + inf = inf\n                return result_infinity;\n            }\n        } else {\n            result_type result;\n            if (loga > logb)\n                result = loga + log1p (exp (logb - loga));\n            else\n                result = logb + log1p (exp (loga - logb));\n\n            if (result == result_infinity &&\n                    loga != a_infinity && logb != b_infinity) {\n                raise_overflow_error <result_type> (function_name,\n                    \"Result of addition has overflowed\",\n                    Policy());\n            }\n            return result;\n        }\n    }\n\n    /**\n    Add two numbers represented as their logs.\n    This implementation, for policies that ignore errors, is somewhat\n    faster.\n    */\n    template <class RealType1, class RealType2, class Policy>\n        inline typename promote_args <RealType1, RealType2>::type\n            add_log_float (RealType1 const & loga, RealType2 const & logb,\n                Policy const & policy,\n                boost::math::policies::overflow_error <\n                    boost::math::policies::ignore_error> const &)\n    {\n        typedef typename promote_args <RealType1, RealType2>::type\n            result_type;\n\n        /*\n        A normal implementation of addition in the log-domain uses,\n        (assuming, without loss of generalisation, that loga >= logb):\n        1)  log (a + b) = loga + log (1 + exp (logb - loga))\n            where implementing log (1 + ...) with log1p yields marginal\n            improvements.\n        Corner cases are NaNs and infinities.\n        The following implementation aims to use as few cases as possible\n        by allowing most corner cases to be dealt with by the IEEE floating\n        point operations:\n        2)  isnan (loga) || isnan (logb):\n            Any computation that involves both loga and logb, such as the\n            one for case (1), returns NaN, which is correct.\n        Infinities (assume again that loga >= logb):\n        3)  If (loga == logb), either both +infinity, or both -infinity:\n            logb - loga = NaN\n            and the result will be NaN, which is incorrect.\n            This requires a special case.\n            A solution is to return loga or logb.\n        4)  Otherwise, (loga == +infinity || logb == -infinity):\n            The default implementation returns loga:\n                logb - loga = -infinity\n                exp (logb - loga) = 0\n                log1p (0) = 0\n                loga + 0 = loga\n            which is correct.\n            No special handling is required.\n        Note, however, that for loga >= logb, (3) and (4) are handled by\n            return loga\n        and vice versa.\n        */\n        using std::abs;\n        using std::max;\n\n        if (!::boost::math::isinf (loga)) {\n            result_type difference = -abs (logb - loga);\n            result_type greatest = (max) (loga, logb);\n            return greatest + log1p (exp (difference));\n        } else {\n            if (!(loga >= logb))\n                return result_type (logb);\n            else\n                return result_type (loga);\n        }\n    }\n\n    /**\n    Add two numbers represented as their logs.\n    */\n    template <class RealType1, class RealType2, class Policy>\n        inline typename promote_args <RealType1, RealType2>::type\n            add_log_float (RealType1 const & loga, RealType2 const & logb,\n            Policy const & policy)\n    {\n        return add_log_float (loga, logb, policy,\n            typename Policy::overflow_error_type());\n    }\n\n    /**\n    \\pre !(loga < logb)\n        (This is not the same as loga >= logb in the face of NaNs.)\n    */\n    template <class RealType1, class RealType2, class Policy,\n            class UnderflowPolicy, class IndeterminateResultPolicy>\n        inline typename promote_args <RealType1, RealType2>::type\n            subtract_log_float (RealType1 const & loga, RealType2 const & logb,\n            Policy const & policy,\n            UnderflowPolicy const &, IndeterminateResultPolicy const &)\n    {\n        assert (!(loga < logb));\n        static char const * function_name = \"subtraction of log_float<%1%>\";\n        typedef typename promote_args <RealType1, RealType2>::type\n            result_type;\n        static constexpr RealType1 a_infinity =\n            std::numeric_limits <RealType1>::infinity();\n        static constexpr RealType2 b_infinity =\n            std::numeric_limits <RealType2>::infinity();\n        static constexpr result_type result_infinity =\n            std::numeric_limits <result_type>::infinity();\n        static constexpr result_type result_nan =\n            std::numeric_limits <result_type>::quiet_NaN();\n\n        // This explicitly provides behaviour that IEEE standard floating\n        // point numbers should provide.\n        if (isnan (loga) || isnan (logb))\n            return result_nan;\n        else if (loga == a_infinity) {\n            if (logb == b_infinity) {\n                return raise_indeterminate_result_error (\n                    function_name, \"%1% - inf is undefined\",\n                    result_infinity, result_nan, policy);\n            } else\n                // Any overflow has taken place already.\n                return result_infinity;\n        } else if (loga == logb) {\n            return -result_infinity;\n        } else {\n            result_type result;\n            result = loga + log1p (-exp (logb - loga));\n\n            if (result == - result_infinity) {\n                raise_underflow_error <result_type> (function_name,\n                    \"Result of subtraction has underflowed\",\n                    Policy());\n            }\n            return result;\n        }\n    }\n\n    template <class RealType1, class RealType2, class Policy>\n        inline typename promote_args <RealType1, RealType2>::type\n            subtract_log_float (RealType1 const & loga, RealType2 const & logb,\n            Policy const & policy,\n                boost::math::policies::underflow_error<\n                    boost::math::policies::ignore_error> const &,\n                boost::math::policies::indeterminate_result_error<\n                    boost::math::policies::ignore_error> const &)\n    {\n        assert (!(loga < logb));\n        if (loga == -std::numeric_limits <RealType1>::infinity())\n            // logb == -infinity or nan.\n            return loga + logb;\n        else\n            return loga + log1p (-exp (logb - loga));\n    }\n\n    /**\n    \\pre !(loga < logb)\n        (This is not the same as loga >= logb in the face of NaNs.)\n    */\n    template <class RealType1, class RealType2, class Policy>\n        inline typename promote_args <RealType1, RealType2>::type\n            subtract_log_float (RealType1 const & loga, RealType2 const & logb,\n            Policy const & policy)\n    {\n        return subtract_log_float (loga, logb, policy,\n            typename Policy::underflow_error_type(),\n            typename Policy::indeterminate_result_error_type());\n    }\n\n    template <class RealType1, class RealType2, class Policy>\n        inline std::pair <\n            typename promote_args <RealType1, RealType2>::type, int>\n        add_signed_log_float (RealType1 const & loga, int sign_a,\n            RealType2 const & logb, int sign_b,\n            Policy const & policy)\n    {\n        if (sign_a == sign_b)\n            return std::make_pair (add_log_float (loga, logb, policy), sign_a);\n        else {\n            if (loga >= logb)\n                return std::make_pair (\n                    subtract_log_float (loga, logb, policy), sign_a);\n            else\n                return std::make_pair (\n                    subtract_log_float (logb, loga, policy), sign_b);\n        }\n    }\n\n}} // namespace math::detail\n\n#endif  // MATH_DETAIL_LOG_FLOAT_ARITHMETIC_HPP\n\n", "meta": {"hexsha": "3beb1aa7daea8553b685e2bf9f32d23ccd7278cd", "size": 21317, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/math/detail/log-float_arithmetic.hpp", "max_stars_repo_name": "rogiervd/math", "max_stars_repo_head_hexsha": "96174afac1a2933d71cb7ae3962437f860fc10ec", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/math/detail/log-float_arithmetic.hpp", "max_issues_repo_name": "rogiervd/math", "max_issues_repo_head_hexsha": "96174afac1a2933d71cb7ae3962437f860fc10ec", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/math/detail/log-float_arithmetic.hpp", "max_forks_repo_name": "rogiervd/math", "max_forks_repo_head_hexsha": "96174afac1a2933d71cb7ae3962437f860fc10ec", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.7162426614, "max_line_length": 79, "alphanum_fraction": 0.579209082, "num_tokens": 4504, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.45071092469975393}}
{"text": "#include <boost/numeric/mtl/mtl.hpp>\n\nint main(int, char**)\n{\n    using namespace mtl; using namespace mtl::mat;\n    \n    const unsigned n= 20;\n    dense2D<double>                            A(n, n), B(n, n);\n    morton_dense<double, doppled_64_row_mask>  C(n, n);\n\n    hessian_setup(A, 3.0); hessian_setup(B, 1.0); \n    hessian_setup(C, 2.0);\n\n    // Corresponds to A= B * B;\n    mult(B, B, A);\n\n    A= B * B;   // use BLAS\n    A= B * C;   // use recursion + tiling from MTL4\n\n    A+= B * C;  // Increment A by the product of B and C\n    A-= B * C;  // Likewise with decrement\n\n    return 0;\n}\n", "meta": {"hexsha": "2c8c7b311a8c5dca02324f45c9033305fc140993", "size": 595, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/examples/matrix_mult_simple.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/matrix_mult_simple.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/matrix_mult_simple.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 23.8, "max_line_length": 64, "alphanum_fraction": 0.5495798319, "num_tokens": 201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.45071092469975393}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// This file is manually converted from PROJ4\n\n// Copyright (c) 2008-2012 Barend Gehrels, Amsterdam, the Netherlands.\n\n// This file was modified by Oracle on 2018.\n// Modifications copyright (c) 2018, Oracle and/or its affiliates.\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n// This file is converted from PROJ4, http://trac.osgeo.org/proj\n// PROJ4 is originally written by Gerald Evenden (then of the USGS)\n// PROJ4 is maintained by Frank Warmerdam\n// 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_AASINCOS_HPP\n#define BOOST_GEOMETRY_PROJECTIONS_IMPL_AASINCOS_HPP\n\n\n#include <cmath>\n\n#include <boost/geometry/srs/projections/exception.hpp>\n#include <boost/geometry/srs/projections/impl/pj_strerrno.hpp>\n#include <boost/geometry/util/math.hpp>\n\n\nnamespace boost { namespace geometry { namespace projections\n{\n\nnamespace detail\n{\n\nnamespace aasincos\n{\n    template <typename T>\n    inline T ONE_TOL() { return 1.00000000000001; }\n    //template <typename T>\n    //inline T TOL() { return 0.000000001; }\n    template <typename T>\n    inline T ATOL() { return 1e-50; }\n}\n\ntemplate <typename T>\ninline T aasin(T const& v)\n{\n    T av = 0;\n\n    if ((av = geometry::math::abs(v)) >= 1.0)\n    {\n        if (av > aasincos::ONE_TOL<T>())\n        {\n            BOOST_THROW_EXCEPTION( projection_exception(error_acos_asin_arg_too_large) );\n        }\n        return (v < 0.0 ? -geometry::math::half_pi<T>() : geometry::math::half_pi<T>());\n    }\n\n    return asin(v);\n}\n\ntemplate <typename T>\ninline T aacos(T const& v)\n{\n    T av = 0;\n\n    if ((av = geometry::math::abs(v)) >= 1.0)\n    {\n        if (av > aasincos::ONE_TOL<T>())\n        {\n            BOOST_THROW_EXCEPTION( projection_exception(error_acos_asin_arg_too_large) );\n        }\n        return (v < 0.0 ? geometry::math::pi<T>() : 0.0);\n    }\n\n    return acos(v);\n}\n\ntemplate <typename T>\ninline T asqrt(T const& v)\n{\n    return ((v <= 0) ? 0 : sqrt(v));\n}\n\ntemplate <typename T>\ninline T aatan2(T const& n, T const& d)\n{\n    return ((geometry::math::abs(n) < aasincos::ATOL<T>()\n        && geometry::math::abs(d) < aasincos::ATOL<T>()) ? 0.0 : atan2(n, d));\n}\n\n\n} // namespace detail\n\n\n}}} // namespace boost::geometry::projections\n\n\n#endif // BOOST_GEOMETRY_PROJECTIONS_IMPL_AASINCOS_HPP\n", "meta": {"hexsha": "b12b5f65ba8d7c4851e81393a086c881747211ce", "size": 3679, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/srs/projections/impl/aasincos.hpp", "max_stars_repo_name": "Harshitha91/Tmdb-react-native-node", "max_stars_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/srs/projections/impl/aasincos.hpp", "max_issues_repo_name": "Harshitha91/Tmdb-react-native-node", "max_issues_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/srs/projections/impl/aasincos.hpp", "max_forks_repo_name": "Harshitha91/Tmdb-react-native-node", "max_forks_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 30.4049586777, "max_line_length": 89, "alphanum_fraction": 0.7015493341, "num_tokens": 953, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.45071092469975393}}
{"text": "#ifndef __QUADROTOR_UKF_HH__\n#define __QUADROTOR_UKF_HH__\n\n#include <list>\n#include <cmath>\n#include <vector>\n#include <string>\n#include <iostream>\n#include <algorithm>\n#include <armadillo>\n\n#include <ros/ros.h>\n\n#include <pose_utils.h>\n\nusing namespace arma;\n\nclass QuadrotorUKF\n{\n\tprivate:\n\n\t\t// State History and Covariance\n\t\tlist<colvec>    xHist;\n\t\tlist<colvec>    uHist;\n\t\tlist<ros::Time> xTimeHist;\n\t\tmat P;\n\n\t\t// Process Covariance Matrix\n\t\tmat Rv;\n\n\t\t// Instance sigma points\n\t\tmat Xa;\n\t\tmat Va;\n\n\t\t// Initial process update indicator\n\t\tbool initMeasure;\n\t\tbool initGravity;\n\n\t\t// Dimemsions\n\t\tint stateCnt;\n\t\tint procNoiseCnt;\n\t\tint measNoiseSLAMCnt;\n\t\tint measNoiseGPSCnt;\n\t\tint L;\n\n\t\t// Gravity\n\t\tdouble g;\n\n\t\t// UKF Parameters\n\t\tdouble alpha;\n\t\tdouble beta;\n\t\tdouble kappa;\n\t\tdouble lambda;\n\t\tdouble gamma;\n\t\t// UKF Weights\n\t\trowvec wm;\n\t\trowvec wc;\n\n\t\t// Private functions\n\t\tvoid GenerateWeights();\n\t\tvoid GenerateSigmaPoints();\n\t\tcolvec ProcessModel(const colvec& x, const colvec& u, const colvec& v, double dt);\n\t\tmat MeasurementModelSLAM();\n\t\tmat MeasurementModelGPS();\n\t\tvoid PropagateAprioriCovariance(const ros::Time time, list<colvec>::iterator& kx, list<colvec>::iterator& ku, list<ros::Time>::iterator& kt);\n\t\tvoid PropagateAposterioriState(list<colvec>::iterator kx, list<colvec>::iterator ku, list<ros::Time>::iterator kt);\n\n\tpublic:\n\n\t\tQuadrotorUKF();\n\t\t~QuadrotorUKF();\n\n\t\tbool      isInitialized();\n\t\tcolvec    GetState();\n\t\tros::Time GetStateTime();\n\t\tmat       GetStateCovariance();\n\n\t\tvoid SetGravity(double _g);\n\t\tvoid SetImuCovariance(const mat& _Rv);\n\t\tvoid SetUKFParameters(double _alpha, double _beta, double _kappa);\n\t\tvoid SetInitPose(colvec p, ros::Time time);\n\n\t\tbool ProcessUpdate(colvec u, ros::Time time);\n\t\tbool MeasurementUpdateSLAM(colvec z, mat RnSLAM, ros::Time time);\n\t\tbool MeasurementUpdateGPS(colvec z, mat RnGPS, ros::Time time);\n};\n\n#endif\n", "meta": {"hexsha": "ea81b51707a0968fe0be89e73feb1eb583616170", "size": 1894, "ext": "hh", "lang": "C++", "max_stars_repo_path": "quadrotor_ukf_lite/include/quadrotor_ukf.hh", "max_stars_repo_name": "ozaslan/estimators", "max_stars_repo_head_hexsha": "ad78f2d395d4a6155f0b6d61541167a99959a1c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "quadrotor_ukf_lite/include/quadrotor_ukf.hh", "max_issues_repo_name": "ozaslan/estimators", "max_issues_repo_head_hexsha": "ad78f2d395d4a6155f0b6d61541167a99959a1c9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "quadrotor_ukf_lite/include/quadrotor_ukf.hh", "max_forks_repo_name": "ozaslan/estimators", "max_forks_repo_head_hexsha": "ad78f2d395d4a6155f0b6d61541167a99959a1c9", "max_forks_repo_licenses": ["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.2808988764, "max_line_length": 143, "alphanum_fraction": 0.7117212249, "num_tokens": 564, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.45071091967253474}}
{"text": "//\n// Created by asem on 01/01/19.\n//\n\n#ifndef MARKOVIAN_FEATURES_AAINDEXCLUSTERING_HPP\n#define MARKOVIAN_FEATURES_AAINDEXCLUSTERING_HPP\n\n#include \"dlib_utilities.hpp\"\n#include <dlib/svm.h>\n\n#include \"SimilarityMetrics.hpp\"\n#include \"LabeledEntry.hpp\"\n#include \"AAIndexDBGET.hpp\"\n#include \"common.hpp\"\n#include \"LUT.hpp\"\n\nnamespace aaindex {\n\nclass AAIndexClustering\n{\n    using SampleType = dlib::matrix<double, 0, 0>;\n\npublic:\n    explicit AAIndexClustering(\n            const std::vector<AAIndex1> &index,\n            size_t nClusters\n    )\n            : _index( index ),\n              _dims( index.size()),\n              _nClusters( nClusters )\n    {}\n\n    virtual void runClustering()\n    {\n\n        auto samplesVector = _samples();\n\n        {\n            std::vector<SampleType> centroids;\n\n            dlib::pick_initial_centers( _nClusters, centroids, samplesVector );\n            dlib::find_clusters_using_kmeans( samplesVector, centroids );\n\n            _centroids.emplace( std::move( centroids ));\n        }\n\n        _clusters.emplace( LUT<char, long>::makeLUT(\n                [this]( char aa ) -> long {\n                    if ( auto point = getPoint( aa ); point )\n                        return _closestIdx( _centroids.value(), point.value());\n                    else return -1;\n                } ));\n    }\n\n    std::optional<SampleType> getPoint( char aa ) const\n    {\n        using namespace dlib_utilities;\n        std::vector<double> point;\n        for (auto &index : _index)\n        {\n            if ( auto component = index.normalizedIndex( aa ); component )\n                point.push_back( component.value());\n            else return std::nullopt;\n        }\n        return vector_to_column_matrix_like( std::move( point ));\n    }\n\n    std::optional<size_t> getCluster( char aa ) const\n    {\n        assert( _centroids.has_value() && _clusters.has_value());\n        if ( auto cluster = _clusters->at( aa ); cluster >= 0 )\n            return size_t( cluster );\n        else return std::nullopt;\n    }\n\nprotected:\n\n    long _closestIdx(\n            const std::vector<SampleType> &centroids,\n            const SampleType &point\n    )\n    {\n        static auto euclidean = Euclidean::template similarityFunctor<SampleType>();\n\n        auto minIt = std::min_element(\n                centroids.cbegin(), centroids.cend(),\n                [&](\n                        SampleType x,\n                        SampleType y\n                ) {\n                    return euclidean( x, point ) < euclidean( y, point );\n                } );\n        return std::distance( centroids.cbegin(), minIt );\n    }\n\n    std::vector<SampleType> _samples() const\n    {\n        std::vector<SampleType> samples;\n        for (auto aa : AMINO_ACIDS20)\n        {\n            auto point = getPoint( aa );\n            assert( point.has_value());\n            samples.emplace_back( getPoint( aa ).value());\n        }\n        return samples;\n    }\n\n\nprivate:\n    const std::vector<AAIndex1> _index;\n    const size_t _nClusters;\n    const size_t _dims;\n\n    std::optional<std::vector<SampleType>> _centroids;\n    std::optional<LUT<char, long>> _clusters;\n};\n\n}\n\n\n#endif //MARKOVIAN_FEATURES_AAINDEXCLUSTERING_HPP\n", "meta": {"hexsha": "f87975dd11b30c46a26e8401b2a1300e632b8b09", "size": 3200, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/data/AAIndexClustering.hpp", "max_stars_repo_name": "aametwally/MC_MicroSimilarities", "max_stars_repo_head_hexsha": "b625fcbe7eb1fcd8f04fedec1a111b4d3a1bde3a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-02-22T03:08:56.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-17T02:30:58.000Z", "max_issues_repo_path": "src/data/AAIndexClustering.hpp", "max_issues_repo_name": "aametwally/MC_MicroSimilarities", "max_issues_repo_head_hexsha": "b625fcbe7eb1fcd8f04fedec1a111b4d3a1bde3a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2019-02-24T13:13:35.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-26T10:10:58.000Z", "max_forks_repo_path": "src/data/AAIndexClustering.hpp", "max_forks_repo_name": "aametwally/MC_MicroSimilarities", "max_forks_repo_head_hexsha": "b625fcbe7eb1fcd8f04fedec1a111b4d3a1bde3a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.2295081967, "max_line_length": 84, "alphanum_fraction": 0.5703125, "num_tokens": 743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.45071091464531543}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n  Copyright (C) 2008, 2009, 2014 Klaus Spanderen\n  Copyright (C) 2014 Johannes G\u00f6ttker-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#include \"fdheston.hpp\"\n#include \"utilities.hpp\"\n\n#include <ql/math/functional.hpp>\n#include <ql/quotes/simplequote.hpp>\n#include <ql/time/calendars/target.hpp>\n#include <ql/time/daycounters/actual360.hpp>\n#include <ql/time/daycounters/actualactual.hpp>\n#include <ql/time/daycounters/actual365fixed.hpp>\n#include <ql/instruments/barrieroption.hpp>\n#include <ql/instruments/dividendvanillaoption.hpp>\n#include <ql/models/equity/hestonmodel.hpp>\n#include <ql/termstructures/yield/zerocurve.hpp>\n#include <ql/termstructures/yield/flatforward.hpp>\n#include <ql/termstructures/volatility/equityfx/localconstantvol.hpp>\n#include <ql/methods/finitedifferences/meshers/fdmhestonvariancemesher.hpp>\n#include <ql/pricingengines/barrier/analyticbarrierengine.hpp>\n#include <ql/pricingengines/vanilla/analytichestonengine.hpp>\n#include <ql/pricingengines/vanilla/analyticeuropeanengine.hpp>\n#include <ql/pricingengines/barrier/fdhestonbarrierengine.hpp>\n#include <ql/pricingengines/vanilla/fdhestonvanillaengine.hpp>\n#include <ql/pricingengines/barrier/fdblackscholesbarrierengine.hpp>\n#include <ql/pricingengines/vanilla/fdblackscholesvanillaengine.hpp>\n\n#include <boost/assign/std/vector.hpp>\n#include <ql/tuple.hpp>\n\nusing namespace QuantLib;\nusing namespace boost::assign;\nusing boost::unit_test_framework::test_suite;\n\n\nnamespace fd_heston_test {\n    struct NewBarrierOptionData {\n        Barrier::Type barrierType;\n        Real barrier;\n        Real rebate;\n        Option::Type type;\n        Real strike;\n        Real s;        // spot\n        Rate q;        // dividend\n        Rate r;        // risk-free rate\n        Time t;        // time to maturity\n        Volatility v;  // volatility\n    };\n\n    class ParableLocalVolatility : public LocalVolTermStructure {\n      public:\n        ParableLocalVolatility(\n            const Date& referenceDate,\n            Real s0,\n            Real alpha,\n            const DayCounter& dayCounter)\n        : LocalVolTermStructure(\n              referenceDate, NullCalendar(), Following, dayCounter),\n          referenceDate_(referenceDate),\n          s0_(s0),\n          alpha_(alpha) {}\n\n        Date maxDate() const override { return Date::maxDate(); }\n        Real minStrike() const override { return 0.0; }\n        Real maxStrike() const override { return std::numeric_limits<Real>::max(); }\n\n      protected:\n        Volatility localVolImpl(Time t, Real s) const override {\n            return alpha_*(square<Real>()(s0_ - s) + 25.0);\n        }\n\n      private:\n        const Date referenceDate_;\n        const Real s0_, alpha_;\n    };\n}\n\nvoid FdHestonTest::testFdmHestonVarianceMesher() {\n    BOOST_TEST_MESSAGE(\"Testing FDM Heston variance mesher...\");\n\n    using namespace fd_heston_test;\n\n    SavedSettings backup;\n\n    const Date today = Date(22, February, 2018);\n    const DayCounter dc = Actual365Fixed();\n    Settings::instance().evaluationDate() = today;\n\n    const ext::shared_ptr<HestonProcess> process(\n        ext::make_shared<HestonProcess>(\n            Handle<YieldTermStructure>(flatRate(0.02, dc)),\n            Handle<YieldTermStructure>(flatRate(0.02, dc)),\n            Handle<Quote>(ext::make_shared<SimpleQuote>(100.0)),\n            0.09, 1.0, 0.09, 0.2, -0.5));\n\n    const ext::shared_ptr<FdmHestonVarianceMesher> mesher\n        = ext::make_shared<FdmHestonVarianceMesher>(5, process, 1.0);\n\n    const std::vector<Real> locations = mesher->locations();\n\n    const Real expected[] = {\n        0.0, 6.652314e-02, 9.000000e-02, 1.095781e-01, 2.563610e-01\n    };\n\n    const Real tol = 1e-6;\n    for (Size i=0; i < locations.size(); ++i) {\n        const Real diff = std::fabs(expected[i] - locations[i]);\n\n        if (diff > tol) {\n            BOOST_ERROR(\"Failed to reproduce Heston variance mesh\"\n                        << \"\\n    calculated: \" << locations[i]\n                        << \"\\n    expected:   \" << expected[i]\n                        << std::scientific\n                        << \"\\n    difference  \" << diff\n                        << \"\\n    tolerance:  \" << tol);\n        }\n    }\n\n    const ext::shared_ptr<LocalVolTermStructure> lVol =\n        ext::make_shared<LocalConstantVol>(today, 2.5, dc);\n\n    const ext::shared_ptr<FdmHestonLocalVolatilityVarianceMesher> constSlvMesher\n        = ext::make_shared<FdmHestonLocalVolatilityVarianceMesher>\n              (5, process, lVol, 1.0);\n\n    const Real expectedVol = 2.5 * mesher->volaEstimate();\n    const Real calculatedVol = constSlvMesher->volaEstimate();\n\n    const Real diff = std::fabs(calculatedVol - expectedVol);\n    if (diff > tol) {\n        BOOST_ERROR(\"Failed to reproduce Heston local volatility \"\n                \"variance estimate\"\n                    << \"\\n    calculated: \" << calculatedVol\n                    << \"\\n    expected:   \" << expectedVol\n                    << std::scientific\n                    << \"\\n    difference  \" << diff\n                    << \"\\n    tolerance:  \" << tol);\n    }\n\n    const Real alpha = 0.01;\n    const ext::shared_ptr<LocalVolTermStructure> leverageFct\n        = ext::make_shared<ParableLocalVolatility>(today, 100.0, alpha, dc);\n\n    const ext::shared_ptr<FdmHestonLocalVolatilityVarianceMesher> slvMesher\n        = ext::make_shared<FdmHestonLocalVolatilityVarianceMesher>(\n              5, process, leverageFct, 0.5, 1, 0.01);\n\n    const Real initialVolEstimate =\n        ext::make_shared<FdmHestonVarianceMesher>(5, process, 0.5, 1, 0.01)->\n            volaEstimate();\n\n    // const Real vEst = leverageFct->localVol(0, 100) * initialVolEstimate;\n    // Mathematica solution\n    //    N[Integrate[\n    //      alpha*((100*Exp[vEst*x*Sqrt[0.5]] - 100)^2 + 25)*\n    //       PDF[NormalDistribution[0, 1], x], {x ,\n    //       InverseCDF[NormalDistribution[0, 1], 0.01],\n    //       InverseCDF[NormalDistribution[0, 1], 0.99]}]]\n\n    const Real leverageAvg = 0.455881 / (1-0.02);\n\n    const Real volaEstExpected =\n        0.5*(leverageAvg + leverageFct->localVol(0, 100)) * initialVolEstimate;\n\n    const Real volaEstCalculated = slvMesher->volaEstimate();\n\n    if (std::fabs(volaEstExpected - volaEstCalculated) > 0.001) {\n        BOOST_ERROR(\"Failed to reproduce Heston local volatility \"\n                \"variance estimate\"\n                    << \"\\n    calculated: \" << calculatedVol\n                    << \"\\n    expected:   \" << expectedVol\n                    << std::scientific\n                    << \"\\n    difference  \" << std::fabs(volaEstExpected - volaEstCalculated)\n                    << \"\\n    tolerance:  \" << tol);\n    }\n}\n\nvoid FdHestonTest::testFdmHestonBarrierVsBlackScholes() {\n\n    BOOST_TEST_MESSAGE(\"Testing FDM with barrier option in Heston model...\");\n\n    using namespace fd_heston_test;\n\n    SavedSettings backup;\n\n    NewBarrierOptionData values[] = {\n        /* The data below are from\n          \"Option pricing formulas\", E.G. Haug, McGraw-Hill 1998 pag. 72\n        */\n        //     barrierType, barrier, rebate,         type, strike,     s,    q,    r,    t,    v\n        { Barrier::DownOut,    95.0,    3.0, Option::Call,     90, 100.0, 0.04, 0.08, 0.50, 0.25},\n        { Barrier::DownOut,    95.0,    3.0, Option::Call,    100, 100.0, 0.00, 0.08, 1.00, 0.30},\n        { Barrier::DownOut,    95.0,    3.0, Option::Call,    110, 100.0, 0.04, 0.08, 0.50, 0.25},\n        { Barrier::DownOut,   100.0,    3.0, Option::Call,     90, 100.0, 0.00, 0.08, 0.25, 0.25},\n        { Barrier::DownOut,   100.0,    3.0, Option::Call,    100, 100.0, 0.04, 0.08, 0.50, 0.25},\n        { Barrier::DownOut,   100.0,    3.0, Option::Call,    110, 100.0, 0.04, 0.08, 0.50, 0.25},\n        { Barrier::UpOut,     105.0,    3.0, Option::Call,     90, 100.0, 0.04, 0.08, 0.50, 0.25},\n        { Barrier::UpOut,     105.0,    3.0, Option::Call,    100, 100.0, 0.04, 0.08, 0.50, 0.25},\n        { Barrier::UpOut,     105.0,    3.0, Option::Call,    110, 100.0, 0.04, 0.08, 0.50, 0.25},\n\n        { Barrier::DownIn,     95.0,    3.0, Option::Call,    90, 100.0, 0.04, 0.08, 0.50, 0.25},\n        { Barrier::DownIn,     95.0,    3.0, Option::Call,   100, 100.0, 0.04, 0.08, 0.50, 0.25},\n        { Barrier::DownIn,     95.0,    3.0, Option::Call,   110, 100.0, 0.04, 0.08, 0.50, 0.25},\n        { Barrier::DownIn,    100.0,    3.0, Option::Call,    90, 100.0, 0.00, 0.08, 0.25, 0.25},\n        { Barrier::DownIn,    100.0,    3.0, Option::Call,   100, 100.0, 0.04, 0.08, 0.50, 0.25},\n        { Barrier::DownIn,    100.0,    3.0, Option::Call,   110, 100.0, 0.04, 0.08, 0.50, 0.25},\n        { Barrier::UpIn,      105.0,    3.0, Option::Call,    90, 100.0, 0.04, 0.08, 0.50, 0.25},\n        { Barrier::UpIn,      105.0,    3.0, Option::Call,   100, 100.0, 0.00, 0.08, 0.40, 0.25},\n        { Barrier::UpIn,      105.0,    3.0, Option::Call,   110, 100.0, 0.04, 0.08, 0.50, 0.15},\n\n        { Barrier::DownOut,    95.0,    3.0, Option::Call,    90, 100.0, 0.04, 0.08, 0.50, 0.30},\n        { Barrier::DownOut,    95.0,    3.0, Option::Call,   100, 100.0, 0.00, 0.08, 0.40, 0.35},\n        { Barrier::DownOut,    95.0,    3.0, Option::Call,   110, 100.0, 0.04, 0.08, 0.50, 0.30},\n        { Barrier::DownOut,   100.0,    3.0, Option::Call,    90, 100.0, 0.04, 0.08, 0.50, 0.15},\n        { Barrier::DownOut,   100.0,    3.0, Option::Call,   100, 100.0, 0.04, 0.08, 0.50, 0.30},\n        { Barrier::DownOut,   100.0,    3.0, Option::Call,   110, 100.0, 0.00, 0.00, 1.00, 0.20},\n        { Barrier::UpOut,     105.0,    3.0, Option::Call,    90, 100.0, 0.04, 0.08, 0.50, 0.30},\n        { Barrier::UpOut,     105.0,    3.0, Option::Call,   100, 100.0, 0.04, 0.08, 0.50, 0.30},\n        { Barrier::UpOut,     105.0,    3.0, Option::Call,   110, 100.0, 0.04, 0.08, 0.50, 0.30},\n\n        { Barrier::DownIn,     95.0,    3.0, Option::Call,    90, 100.0, 0.04, 0.08, 0.50, 0.30},\n        { Barrier::DownIn,     95.0,    3.0, Option::Call,   100, 100.0, 0.04, 0.08, 0.50, 0.30},\n        { Barrier::DownIn,     95.0,    3.0, Option::Call,   110, 100.0, 0.00, 0.08, 1.00, 0.30},\n        { Barrier::DownIn,    100.0,    3.0, Option::Call,    90, 100.0, 0.04, 0.08, 0.50, 0.30},\n        { Barrier::DownIn,    100.0,    3.0, Option::Call,   100, 100.0, 0.04, 0.08, 0.50, 0.30},\n        { Barrier::DownIn,    100.0,    3.0, Option::Call,   110, 100.0, 0.04, 0.08, 0.50, 0.30},\n        { Barrier::UpIn,      105.0,    3.0, Option::Call,    90, 100.0, 0.04, 0.08, 0.50, 0.30},\n        { Barrier::UpIn,      105.0,    3.0, Option::Call,   100, 100.0, 0.04, 0.08, 0.50, 0.30},\n        { Barrier::UpIn,      105.0,    3.0, Option::Call,   110, 100.0, 0.04, 0.08, 0.50, 0.30},\n\n        { Barrier::DownOut,    95.0,    3.0,  Option::Put,    90, 100.0, 0.04, 0.08, 0.50, 0.25},\n        { Barrier::DownOut,    95.0,    3.0,  Option::Put,   100, 100.0, 0.04, 0.08, 0.50, 0.25},\n        { Barrier::DownOut,    95.0,    3.0,  Option::Put,   110, 100.0, 0.04, 0.08, 0.50, 0.25},\n        { Barrier::DownOut,   100.0,    3.0,  Option::Put,    90, 100.0, 0.04, 0.08, 0.50, 0.25},\n        { Barrier::DownOut,   100.0,    3.0,  Option::Put,   100, 100.0, 0.04, 0.08, 0.50, 0.25},\n        { Barrier::DownOut,   100.0,    3.0,  Option::Put,   110, 100.0, 0.04, 0.08, 0.50, 0.25},\n        { Barrier::UpOut,     105.0,    3.0,  Option::Put,    90, 100.0, 0.04, 0.08, 0.50, 0.25},\n        { Barrier::UpOut,     105.0,    3.0,  Option::Put,   100, 100.0, 0.04, 0.08, 0.50, 0.25},\n        { Barrier::UpOut,     105.0,    3.0,  Option::Put,   110, 100.0, 0.04, 0.08, 0.50, 0.25},\n\n        { Barrier::DownIn,     95.0,    3.0,  Option::Put,    90, 100.0, 0.04, 0.08, 0.50, 0.25},\n        { Barrier::DownIn,     95.0,    3.0,  Option::Put,   100, 100.0, 0.04, 0.08, 0.50, 0.25},\n        { Barrier::DownIn,     95.0,    3.0,  Option::Put,   110, 100.0, 0.04, 0.08, 0.50, 0.25},\n        { Barrier::DownIn,    100.0,    3.0,  Option::Put,    90, 100.0, 0.04, 0.08, 0.50, 0.25},\n        { Barrier::DownIn,    100.0,    3.0,  Option::Put,   100, 100.0, 0.04, 0.08, 0.50, 0.25},\n        { Barrier::DownIn,    100.0,    3.0,  Option::Put,   110, 100.0, 0.04, 0.08, 0.50, 0.25},\n        { Barrier::UpIn,      105.0,    3.0,  Option::Put,    90, 100.0, 0.04, 0.08, 0.50, 0.25},\n        { Barrier::UpIn,      105.0,    3.0,  Option::Put,   100, 100.0, 0.04, 0.08, 0.50, 0.25},\n        { Barrier::UpIn,      105.0,    3.0,  Option::Put,   110, 100.0, 0.00, 0.04, 1.00, 0.15},\n\n        { Barrier::DownOut,    95.0,    3.0,  Option::Put,    90, 100.0, 0.04, 0.08, 0.50, 0.30},\n        { Barrier::DownOut,    95.0,    3.0,  Option::Put,   100, 100.0, 0.04, 0.08, 0.50, 0.30},\n        { Barrier::DownOut,    95.0,    3.0,  Option::Put,   110, 100.0, 0.04, 0.08, 0.50, 0.30},\n        { Barrier::DownOut,   100.0,    3.0,  Option::Put,    90, 100.0, 0.04, 0.08, 0.50, 0.30},\n        { Barrier::DownOut,   100.0,    3.0,  Option::Put,   100, 100.0, 0.04, 0.08, 0.50, 0.30},\n        { Barrier::DownOut,   100.0,    3.0,  Option::Put,   110, 100.0, 0.04, 0.08, 0.50, 0.30},\n        { Barrier::UpOut,     105.0,    3.0,  Option::Put,    90, 100.0, 0.04, 0.08, 0.50, 0.30},\n        { Barrier::UpOut,     105.0,    3.0,  Option::Put,   100, 100.0, 0.04, 0.08, 0.50, 0.30},\n        { Barrier::UpOut,     105.0,    3.0,  Option::Put,   110, 100.0, 0.04, 0.08, 0.50, 0.30},\n\n        { Barrier::DownIn,     95.0,    3.0,  Option::Put,    90, 100.0, 0.04, 0.08, 0.50, 0.30},\n        { Barrier::DownIn,     95.0,    3.0,  Option::Put,   100, 100.0, 0.04, 0.08, 0.50, 0.30},\n        { Barrier::DownIn,     95.0,    3.0,  Option::Put,   110, 100.0, 0.04, 0.08, 0.50, 0.30},\n        { Barrier::DownIn,    100.0,    3.0,  Option::Put,    90, 100.0, 0.04, 0.08, 0.50, 0.30},\n        { Barrier::DownIn,    100.0,    3.0,  Option::Put,   100, 100.0, 0.04, 0.08, 0.50, 0.30},\n        { Barrier::DownIn,    100.0,    3.0,  Option::Put,   110, 100.0, 0.04, 0.08, 1.00, 0.15},\n        { Barrier::UpIn,      105.0,    3.0,  Option::Put,    90, 100.0, 0.04, 0.08, 0.50, 0.30},\n        { Barrier::UpIn,      105.0,    3.0,  Option::Put,   100, 100.0, 0.04, 0.08, 0.50, 0.30},\n        { Barrier::UpIn,      105.0,    3.0,  Option::Put,   110, 100.0, 0.04, 0.08, 0.50, 0.30}\n    };\n    \n    const DayCounter dc = Actual365Fixed();     \n    const Date todaysDate(28, March, 2004);\n    const Date exerciseDate(28, March, 2005);\n    Settings::instance().evaluationDate() = todaysDate;\n\n    Handle<Quote> spot(\n            ext::shared_ptr<Quote>(new SimpleQuote(0.0)));\n    ext::shared_ptr<SimpleQuote> qRate(new SimpleQuote(0.0));\n    Handle<YieldTermStructure> qTS(flatRate(qRate, dc));\n    ext::shared_ptr<SimpleQuote> rRate(new SimpleQuote(0.0));\n    Handle<YieldTermStructure> rTS(flatRate(rRate, dc));\n    ext::shared_ptr<SimpleQuote> vol(new SimpleQuote(0.0));\n    Handle<BlackVolTermStructure> volTS(flatVol(vol, dc));\n\n    ext::shared_ptr<BlackScholesMertonProcess> bsProcess(\n                      new BlackScholesMertonProcess(spot, qTS, rTS, volTS));\n\n    ext::shared_ptr<PricingEngine> analyticEngine(\n                                        new AnalyticBarrierEngine(bsProcess));\n\n    for (auto& value : values) {\n        Date exDate = todaysDate + timeToDays(value.t, 365);\n        ext::shared_ptr<Exercise> exercise(new EuropeanExercise(exDate));\n\n        ext::dynamic_pointer_cast<SimpleQuote>(spot.currentLink())->setValue(value.s);\n        qRate->setValue(value.q);\n        rRate->setValue(value.r);\n        vol->setValue(value.v);\n\n        ext::shared_ptr<StrikedTypePayoff> payoff(new PlainVanillaPayoff(value.type, value.strike));\n\n        BarrierOption barrierOption(value.barrierType, value.barrier, value.rebate, payoff,\n                                    exercise);\n\n        const Real v0 = vol->value()*vol->value();\n        ext::shared_ptr<HestonProcess> hestonProcess(\n             new HestonProcess(rTS, qTS, spot, v0, 1.0, v0, 0.005, 0.0));\n\n        barrierOption.setPricingEngine(ext::shared_ptr<PricingEngine>(\n            new FdHestonBarrierEngine(ext::make_shared<HestonModel>(\n                              hestonProcess), 200, 101, 3)));\n\n        const Real calculatedHE = barrierOption.NPV();\n    \n        barrierOption.setPricingEngine(analyticEngine);\n        const Real expected = barrierOption.NPV();\n    \n        const Real tol = 0.0025;\n        if (std::fabs(calculatedHE - expected)/expected > tol) {\n            BOOST_ERROR(\"Failed to reproduce expected Heston npv\"\n                        << \"\\n    calculated: \" << calculatedHE\n                        << \"\\n    expected:   \" << expected\n                        << \"\\n    tolerance:  \" << tol);\n        }\n    }\n}\n\nvoid FdHestonTest::testFdmHestonBarrier() {\n\n    BOOST_TEST_MESSAGE(\"Testing FDM with barrier option for Heston model vs \"\n                       \"Black-Scholes model...\");\n\n    SavedSettings backup;\n\n    Handle<Quote> s0(ext::shared_ptr<Quote>(new SimpleQuote(100.0)));\n\n    Handle<YieldTermStructure> rTS(flatRate(0.05, Actual365Fixed()));\n    Handle<YieldTermStructure> qTS(flatRate(0.0 , Actual365Fixed()));\n\n    ext::shared_ptr<HestonProcess> hestonProcess(\n        new HestonProcess(rTS, qTS, s0, 0.04, 2.5, 0.04, 0.66, -0.8));\n\n    Settings::instance().evaluationDate() = Date(28, March, 2004);\n    Date exerciseDate(28, March, 2005);\n\n    ext::shared_ptr<Exercise> exercise(new EuropeanExercise(exerciseDate));\n\n    ext::shared_ptr<StrikedTypePayoff> payoff(new\n                                      PlainVanillaPayoff(Option::Call, 100));\n\n    BarrierOption barrierOption(Barrier::UpOut, 135, 0.0, payoff, exercise);\n\n    barrierOption.setPricingEngine(ext::shared_ptr<PricingEngine>(\n            new FdHestonBarrierEngine(ext::make_shared<HestonModel>(\n                              hestonProcess), 50, 400, 100)));\n\n    const Real tol = 0.01;\n    const Real npvExpected   =  9.1530;\n    const Real deltaExpected =  0.5218;\n    const Real gammaExpected = -0.0354;\n\n    if (std::fabs(barrierOption.NPV() - npvExpected) > tol) {\n        BOOST_ERROR(\"Failed to reproduce expected npv\"\n                    << \"\\n    calculated: \" << barrierOption.NPV()\n                    << \"\\n    expected:   \" << npvExpected\n                    << \"\\n    tolerance:  \" << tol); \n    }\n    if (std::fabs(barrierOption.delta() - deltaExpected) > tol) {\n        BOOST_ERROR(\"Failed to reproduce expected delta\"\n                    << \"\\n    calculated: \" << barrierOption.delta()\n                    << \"\\n    expected:   \" << deltaExpected\n                    << \"\\n    tolerance:  \" << tol); \n    }\n    if (std::fabs(barrierOption.gamma() - gammaExpected) > tol) {\n        BOOST_ERROR(\"Failed to reproduce expected gamma\"\n                    << \"\\n    calculated: \" << barrierOption.gamma()\n                    << \"\\n    expected:   \" << gammaExpected\n                    << \"\\n    tolerance:  \" << tol); \n    }\n}\n\nvoid FdHestonTest::testFdmHestonAmerican() {\n\n    BOOST_TEST_MESSAGE(\"Testing FDM with American option in Heston model...\");\n\n    SavedSettings backup;\n\n    Handle<Quote> s0(ext::shared_ptr<Quote>(new SimpleQuote(100.0)));\n\n    Handle<YieldTermStructure> rTS(flatRate(0.05, Actual365Fixed()));\n    Handle<YieldTermStructure> qTS(flatRate(0.0 , Actual365Fixed()));\n\n    ext::shared_ptr<HestonProcess> hestonProcess(\n        new HestonProcess(rTS, qTS, s0, 0.04, 2.5, 0.04, 0.66, -0.8));\n\n    Settings::instance().evaluationDate() = Date(28, March, 2004);\n    Date exerciseDate(28, March, 2005);\n\n    ext::shared_ptr<Exercise> exercise(new AmericanExercise(exerciseDate));\n\n    ext::shared_ptr<StrikedTypePayoff> payoff(new\n                                      PlainVanillaPayoff(Option::Put, 100));\n\n    VanillaOption option(payoff, exercise);\n    ext::shared_ptr<PricingEngine> engine(\n         new FdHestonVanillaEngine(ext::make_shared<HestonModel>(\n                             hestonProcess), 200, 100, 50));\n    option.setPricingEngine(engine);\n    \n    const Real tol = 0.01;\n    const Real npvExpected   =  5.66032;\n    const Real deltaExpected = -0.30065;\n    const Real gammaExpected =  0.02202;\n    \n    if (std::fabs(option.NPV() - npvExpected) > tol) {\n        BOOST_ERROR(\"Failed to reproduce expected npv\"\n                    << \"\\n    calculated: \" << option.NPV()\n                    << \"\\n    expected:   \" << npvExpected\n                    << \"\\n    tolerance:  \" << tol); \n    }\n    if (std::fabs(option.delta() - deltaExpected) > tol) {\n        BOOST_ERROR(\"Failed to reproduce expected delta\"\n                    << \"\\n    calculated: \" << option.delta()\n                    << \"\\n    expected:   \" << deltaExpected\n                    << \"\\n    tolerance:  \" << tol); \n    }\n    if (std::fabs(option.gamma() - gammaExpected) > tol) {\n        BOOST_ERROR(\"Failed to reproduce expected gamma\"\n                    << \"\\n    calculated: \" << option.gamma()\n                    << \"\\n    expected:   \" << gammaExpected\n                    << \"\\n    tolerance:  \" << tol); \n    }\n}\n\n\nvoid FdHestonTest::testFdmHestonIkonenToivanen() {\n\n    BOOST_TEST_MESSAGE(\"Testing FDM Heston for Ikonen and Toivanen tests...\");\n\n    /* check prices of american puts as given in:\n       From Efficient numerical methods for pricing American options under \n       stochastic volatility, Samuli Ikonen, Jari Toivanen, \n       http://users.jyu.fi/~tene/papers/reportB12-05.pdf\n    */\n    SavedSettings backup;\n\n    Handle<YieldTermStructure> rTS(flatRate(0.10, Actual360()));\n    Handle<YieldTermStructure> qTS(flatRate(0.0 , Actual360()));\n\n    Settings::instance().evaluationDate() = Date(28, March, 2004);\n    Date exerciseDate(26, June, 2004);\n\n    ext::shared_ptr<Exercise> exercise(new AmericanExercise(exerciseDate));\n\n    ext::shared_ptr<StrikedTypePayoff> payoff(new\n                                      PlainVanillaPayoff(Option::Put, 10));\n\n    VanillaOption option(payoff, exercise);\n\n    Real strikes[]  = { 8, 9, 10, 11, 12 };\n    Real expected[] = { 2.00000, 1.10763, 0.520038, 0.213681, 0.082046 };\n    const Real tol = 0.001;\n    \n    for (Size i=0; i < LENGTH(strikes); ++i) {\n        Handle<Quote> s0(ext::shared_ptr<Quote>(new SimpleQuote(strikes[i])));\n        ext::shared_ptr<HestonProcess> hestonProcess(\n            new HestonProcess(rTS, qTS, s0, 0.0625, 5, 0.16, 0.9, 0.1));\n    \n        ext::shared_ptr<PricingEngine> engine(\n             new FdHestonVanillaEngine(ext::make_shared<HestonModel>(\n                                 hestonProcess), 100, 400));\n        option.setPricingEngine(engine);\n        \n        Real calculated = option.NPV();\n        if (std::fabs(calculated - expected[i]) > tol) {\n            BOOST_ERROR(\"Failed to reproduce expected npv\"\n                        << \"\\n    strike:     \" << strikes[i]\n                        << \"\\n    calculated: \" << calculated\n                        << \"\\n    expected:   \" << expected[i]\n                        << \"\\n    tolerance:  \" << tol); \n        }\n    }\n}\n\nvoid FdHestonTest::testFdmHestonBlackScholes() {\n\n    BOOST_TEST_MESSAGE(\"Testing FDM Heston with Black Scholes model...\");\n\n    SavedSettings backup;\n\n\n    Settings::instance().evaluationDate() = Date(28, March, 2004);\n    Date exerciseDate(26, June, 2004);\n\n    Handle<YieldTermStructure> rTS(flatRate(0.10, Actual360()));\n    Handle<YieldTermStructure> qTS(flatRate(0.0 , Actual360()));\n    Handle<BlackVolTermStructure> volTS(\n                    flatVol(rTS->referenceDate(), 0.25, rTS->dayCounter()));\n    \n    ext::shared_ptr<Exercise> exercise(new EuropeanExercise(exerciseDate));\n\n    ext::shared_ptr<StrikedTypePayoff> payoff(new\n                                      PlainVanillaPayoff(Option::Put, 10));\n\n    VanillaOption option(payoff, exercise);\n\n    Real strikes[]  = { 8, 9, 10, 11, 12 };\n    const Real tol = 0.0001;\n\n    for (double& strike : strikes) {\n        Handle<Quote> s0(ext::shared_ptr<Quote>(new SimpleQuote(strike)));\n\n        ext::shared_ptr<GeneralizedBlackScholesProcess> bsProcess(\n                       new GeneralizedBlackScholesProcess(s0, qTS, rTS, volTS));\n\n        option.setPricingEngine(ext::shared_ptr<PricingEngine>(\n                                        new AnalyticEuropeanEngine(bsProcess)));\n        \n        const Real expected = option.NPV();\n        \n        ext::shared_ptr<HestonProcess> hestonProcess(\n            new HestonProcess(rTS, qTS, s0, 0.0625, 1, 0.0625, 0.0001, 0.0));\n\n        // Hundsdorfer scheme\n        option.setPricingEngine(ext::shared_ptr<PricingEngine>(\n             new FdHestonVanillaEngine(ext::make_shared<HestonModel>(\n                                           hestonProcess), \n                                       100, 400, 3)));\n        \n        Real calculated = option.NPV();\n        if (std::fabs(calculated - expected) > tol) {\n            BOOST_ERROR(\"Failed to reproduce expected npv\"\n                        << \"\\n    strike:     \" << strike << \"\\n    calculated: \" << calculated\n                        << \"\\n    expected:   \" << expected << \"\\n    tolerance:  \" << tol);\n        }\n        \n        // Explicit scheme\n        option.setPricingEngine(ext::shared_ptr<PricingEngine>(\n             new FdHestonVanillaEngine(ext::make_shared<HestonModel>(\n                                           hestonProcess),\n                                       4000, 400, 3, 0,\n                                       FdmSchemeDesc::ExplicitEuler())));\n\n        calculated = option.NPV();\n        if (std::fabs(calculated - expected) > tol) {\n            BOOST_ERROR(\"Failed to reproduce expected npv\"\n                        << \"\\n    strike:     \" << strike << \"\\n    calculated: \" << calculated\n                        << \"\\n    expected:   \" << expected << \"\\n    tolerance:  \" << tol);\n        }\n    }\n}\n\n\n\nvoid FdHestonTest::testFdmHestonEuropeanWithDividends() {\n\n    BOOST_TEST_MESSAGE(\"Testing FDM with European option with dividends\"\n                       \" in Heston model...\");\n\n    SavedSettings backup;\n\n    Handle<Quote> s0(ext::shared_ptr<Quote>(new SimpleQuote(100.0)));\n\n    Handle<YieldTermStructure> rTS(flatRate(0.05, Actual365Fixed()));\n    Handle<YieldTermStructure> qTS(flatRate(0.0 , Actual365Fixed()));\n\n    ext::shared_ptr<HestonProcess> hestonProcess(\n        new HestonProcess(rTS, qTS, s0, 0.04, 2.5, 0.04, 0.66, -0.8));\n\n    Settings::instance().evaluationDate() = Date(28, March, 2004);\n    Date exerciseDate(28, March, 2005);\n\n    ext::shared_ptr<Exercise> exercise(new AmericanExercise(exerciseDate));\n\n    ext::shared_ptr<StrikedTypePayoff> payoff(new\n                                      PlainVanillaPayoff(Option::Put, 100));\n\n    const std::vector<Real> dividends(1, 5);\n    const std::vector<Date> dividendDates(1, Date(28, September, 2004));\n\n    DividendVanillaOption option(payoff, exercise, dividendDates, dividends);\n    ext::shared_ptr<PricingEngine> engine(\n         new FdHestonVanillaEngine(ext::make_shared<HestonModel>(\n                             hestonProcess), 50, 100, 50));\n    option.setPricingEngine(engine);\n    \n    const Real tol = 0.01;\n    const Real gammaTol = 0.001;\n    const Real npvExpected   =  7.365075;\n    const Real deltaExpected = -0.396678;\n    const Real gammaExpected =  0.027681;\n        \n    if (std::fabs(option.NPV() - npvExpected) > tol) {\n        BOOST_ERROR(\"Failed to reproduce expected npv\"\n                    << \"\\n    calculated: \" << option.NPV()\n                    << \"\\n    expected:   \" << npvExpected\n                    << \"\\n    tolerance:  \" << tol); \n    }\n    if (std::fabs(option.delta() - deltaExpected) > tol) {\n        BOOST_ERROR(\"Failed to reproduce expected delta\"\n                    << \"\\n    calculated: \" << option.delta()\n                    << \"\\n    expected:   \" << deltaExpected\n                    << \"\\n    tolerance:  \" << tol); \n    }\n    if (std::fabs(option.gamma() - gammaExpected) > gammaTol) {\n        BOOST_ERROR(\"Failed to reproduce expected gamma\"\n                    << \"\\n    calculated: \" << option.gamma()\n                    << \"\\n    expected:   \" << gammaExpected\n                    << \"\\n    tolerance:  \" << tol); \n    }\n}\n\nnamespace {\n    struct HestonTestData {\n        Real kappa;\n        Real theta;\n        Real sigma;\n        Real rho;\n        Real r;\n        Real q;\n        Real T;\n        Real K;\n    };    \n}\n\nvoid FdHestonTest::testFdmHestonConvergence() {\n\n    /* convergence tests based on \n       ADI finite difference schemes for option pricing in the\n       Heston model with correlation, K.J. in t'Hout and S. Foulon\n    */\n    \n    BOOST_TEST_MESSAGE(\"Testing FDM Heston convergence...\");\n\n    SavedSettings backup;\n    \n    HestonTestData values[] = {\n        { 1.5   , 0.04  , 0.3   , -0.9   , 0.025 , 0.0   , 1.0 , 100 },\n        { 3.0   , 0.12  , 0.04  , 0.6    , 0.01  , 0.04  , 1.0 , 100 },\n        { 0.6067, 0.0707, 0.2928, -0.7571, 0.03  , 0.0   , 3.0 , 100 },\n        { 2.5   , 0.06  , 0.5   , -0.1   , 0.0507, 0.0469, 0.25, 100 }\n    };\n\n    FdmSchemeDesc schemes[] = {\n        FdmSchemeDesc::Hundsdorfer(),\n        FdmSchemeDesc::ModifiedCraigSneyd(),\n        FdmSchemeDesc::ModifiedHundsdorfer(),\n        FdmSchemeDesc::CraigSneyd(),\n        FdmSchemeDesc::TrBDF2(),\n        FdmSchemeDesc::CrankNicolson(),\n    };\n    \n    Size tn[] = { 60 };\n    Real v0[] = { 0.04 };\n    \n    const Date todaysDate(28, March, 2004); \n    Settings::instance().evaluationDate() = todaysDate;\n    \n    Handle<Quote> s0(ext::shared_ptr<Quote>(new SimpleQuote(75.0)));\n\n    for (const auto& scheme : schemes) {\n        for (auto& value : values) {\n            for (unsigned long j : tn) {\n                for (double k : v0) {\n                    Handle<YieldTermStructure> rTS(flatRate(value.r, Actual365Fixed()));\n                    Handle<YieldTermStructure> qTS(flatRate(value.q, Actual365Fixed()));\n\n                    ext::shared_ptr<HestonProcess> hestonProcess(new HestonProcess(\n                        rTS, qTS, s0, k, value.kappa, value.theta, value.sigma, value.rho));\n\n                    Date exerciseDate =\n                        todaysDate + Period(static_cast<Integer>(value.T * 365), Days);\n                    ext::shared_ptr<Exercise> exercise(\n                                          new EuropeanExercise(exerciseDate));\n\n                    ext::shared_ptr<StrikedTypePayoff> payoff(\n                        new PlainVanillaPayoff(Option::Call, value.K));\n\n                    VanillaOption option(payoff, exercise);\n                    ext::shared_ptr<PricingEngine> engine(new FdHestonVanillaEngine(\n                        ext::make_shared<HestonModel>(hestonProcess), j, 101, 51, 0, scheme));\n                    option.setPricingEngine(engine);\n                    \n                    const Real calculated = option.NPV();\n                    \n                    ext::shared_ptr<PricingEngine> analyticEngine(\n                        new AnalyticHestonEngine(\n                            ext::make_shared<HestonModel>(\n                                hestonProcess), 144));\n                    \n                    option.setPricingEngine(analyticEngine);\n                    const Real expected = option.NPV();\n                    if (   std::fabs(expected - calculated)/expected > 0.02\n                        && std::fabs(expected - calculated) > 0.002) {\n                        BOOST_ERROR(\"Failed to reproduce expected npv\"\n                                    << \"\\n    calculated: \" << calculated\n                                    << \"\\n    expected:   \" << expected\n                                    << \"\\n    tolerance:  \" << 0.01); \n                    }\n                }\n            }\n        }\n    }\n}\n\nvoid FdHestonTest::testFdmHestonIntradayPricing() {\n#ifdef QL_HIGH_RESOLUTION_DATE\n\n    BOOST_TEST_MESSAGE(\"Testing FDM Heston intraday pricing ...\");\n\n    SavedSettings backup;\n\n    const Option::Type type(Option::Put);\n    const Real underlying = 36;\n    const Real strike = underlying;\n    const Spread dividendYield = 0.00;\n    const Rate riskFreeRate = 0.06;\n    const Real v0    = 0.2;\n    const Real kappa = 1.0;\n    const Real theta = v0;\n    const Real sigma = 0.0065;\n    const Real rho   = -0.75;\n    const DayCounter dayCounter = Actual365Fixed();\n\n    const Date maturity(17, May, 2014, 17, 30, 0);\n\n    const ext::shared_ptr<Exercise> europeanExercise(\n        new EuropeanExercise(maturity));\n    const ext::shared_ptr<StrikedTypePayoff> payoff(\n        new PlainVanillaPayoff(type, strike));\n    VanillaOption option(payoff, europeanExercise);\n\n    const Handle<Quote> s0(\n         ext::shared_ptr<Quote>(new SimpleQuote(underlying)));\n    RelinkableHandle<BlackVolTermStructure> flatVolTS;\n    RelinkableHandle<YieldTermStructure> flatTermStructure, flatDividendTS;\n    const ext::shared_ptr<HestonProcess> process(\n        new HestonProcess(flatTermStructure, flatDividendTS, s0,\n              v0, kappa, theta, sigma, rho));\n    const ext::shared_ptr<HestonModel> model(new HestonModel(process));\n    const ext::shared_ptr<PricingEngine> fdm(\n        new FdHestonVanillaEngine(model, 20, 100, 26, 0));\n    option.setPricingEngine(fdm);\n\n    const Real gammaExpected[] = {\n        1.46757, 1.54696, 1.6408, 1.75409, 1.89464,\n        2.07548, 2.32046, 2.67944, 3.28164, 4.64096  };\n\n    for (Size i = 0; i < 10; ++i) {\n        const Date now(17, May, 2014, 15, i*15, 0);\n        Settings::instance().evaluationDate() = now;\n\n        flatTermStructure.linkTo(ext::shared_ptr<YieldTermStructure>(\n            new FlatForward(now, riskFreeRate, dayCounter)));\n        flatDividendTS.linkTo(ext::shared_ptr<YieldTermStructure>(\n            new FlatForward(now, dividendYield, dayCounter)));\n\n        const Real gammaCalculated = option.gamma();\n        if (std::fabs(gammaCalculated - gammaExpected[i]) > 1e-4) {\n            BOOST_ERROR(\"unable to reproduce intraday gamma values at time \"\n                        << \"\\n   timestamp : \" << io::iso_datetime(now)\n                        << \"\\n   expiry    : \" << io::iso_datetime(maturity)\n                        << \"\\n   expected  : \" << gammaExpected[i]\n                        << \"\\n   calculated: \"<<  gammaCalculated);\n        }\n    }\n#endif\n}\n\nvoid FdHestonTest::testMethodOfLinesAndCN() {\n    BOOST_TEST_MESSAGE(\"Testing method of lines to solve Heston PDEs...\");\n\n    SavedSettings backup;\n\n    const DayCounter dc = Actual365Fixed();\n    const Date today = Date(21, February, 2018);\n\n    Settings::instance().evaluationDate() = today;\n\n    const Handle<Quote> spot(ext::make_shared<SimpleQuote>(100.0));\n    const Handle<YieldTermStructure> qTS(flatRate(today, 0.0, dc));\n    const Handle<YieldTermStructure> rTS(flatRate(today, 0.0, dc));\n\n    const Real v0    = 0.09;\n    const Real kappa = 1.0;\n    const Real theta = v0;\n    const Real sigma = 0.4;\n    const Real rho   = -0.75;\n\n    const Date maturity = today + Period(3, Months);\n\n    const ext::shared_ptr<HestonModel> model(\n        ext::make_shared<HestonModel>(\n            ext::make_shared<HestonProcess>(\n                rTS, qTS, spot, v0, kappa, theta, sigma, rho)));\n\n    const Size xGrid = 21;\n    const Size vGrid = 7;\n\n    const ext::shared_ptr<PricingEngine> fdmDefault(\n        ext::make_shared<FdHestonVanillaEngine>(model, 10, xGrid, vGrid, 0));\n\n    const ext::shared_ptr<PricingEngine> fdmMol(\n        ext::make_shared<FdHestonVanillaEngine>(\n            model, 10, xGrid, vGrid, 0, FdmSchemeDesc::MethodOfLines()));\n\n    const ext::shared_ptr<PlainVanillaPayoff> payoff =\n        ext::make_shared<PlainVanillaPayoff>(Option::Put, spot->value());\n\n    VanillaOption option(\n        payoff, ext::make_shared<AmericanExercise>(maturity));\n\n    option.setPricingEngine(fdmMol);\n    const Real calculatedMoL = option.NPV();\n\n    option.setPricingEngine(fdmDefault);\n    const Real expected = option.NPV();\n\n    const Real tol = 0.005;\n    const Real diffMoL = std::fabs(expected - calculatedMoL);\n\n    if (diffMoL > tol) {\n        BOOST_FAIL(\"Failed to reproduce european option values with MOL\"\n                   << \"\\n    calculated: \" << calculatedMoL\n                   << \"\\n    expected:   \" << expected\n                   << \"\\n    difference: \" << diffMoL\n                   << \"\\n    tolerance:  \" << tol);\n    }\n\n    const ext::shared_ptr<PricingEngine> fdmCN(\n        ext::make_shared<FdHestonVanillaEngine>(\n            model, 10, xGrid, vGrid, 0, FdmSchemeDesc::CrankNicolson()));\n    option.setPricingEngine(fdmCN);\n\n    const Real calculatedCN = option.NPV();\n    const Real diffCN = std::fabs(expected - calculatedCN);\n\n    if (diffCN > tol) {\n        BOOST_FAIL(\"Failed to reproduce european option values with Crank-Nicolson\"\n                   << \"\\n    calculated: \" << calculatedCN\n                   << \"\\n    expected:   \" << expected\n                   << \"\\n    difference: \" << diffCN\n                   << \"\\n    tolerance:  \" << tol);\n    }\n\n    BarrierOption barrierOption(\n        Barrier::DownOut, 85.0, 10.0,\n        payoff, ext::make_shared<EuropeanExercise>(maturity));\n\n    barrierOption.setPricingEngine(\n        ext::make_shared<FdHestonBarrierEngine>(model, 100, 31, 11));\n\n    const Real expectedBarrier = barrierOption.NPV();\n\n    barrierOption.setPricingEngine(\n        ext::make_shared<FdHestonBarrierEngine>(model, 100, 31, 11, 0,\n            FdmSchemeDesc::MethodOfLines()));\n\n    const Real calculatedBarrierMoL = barrierOption.NPV();\n\n    const Real barrierTol = 0.01;\n    const Real barrierDiffMoL = std::fabs(expectedBarrier - calculatedBarrierMoL);\n\n    if (barrierDiffMoL > barrierTol) {\n        BOOST_FAIL(\"Failed to reproduce barrier option values with MOL\"\n                   << \"\\n    calculated: \" << calculatedBarrierMoL\n                   << \"\\n    expected:   \" << expectedBarrier\n                   << \"\\n    difference: \" << barrierDiffMoL\n                   << \"\\n    tolerance:  \" << barrierTol);\n    }\n\n    barrierOption.setPricingEngine(\n        ext::make_shared<FdHestonBarrierEngine>(model, 100, 31, 11, 0,\n            FdmSchemeDesc::CrankNicolson()));\n\n    const Real calculatedBarrierCN = barrierOption.NPV();\n    const Real barrierDiffCN = std::fabs(expectedBarrier - calculatedBarrierCN);\n\n    if (barrierDiffCN > barrierTol) {\n        BOOST_FAIL(\"Failed to reproduce barrier option values with Crank-Nicolson\"\n                   << \"\\n    calculated: \" << calculatedBarrierCN\n                   << \"\\n    expected:   \" << expectedBarrier\n                   << \"\\n    difference: \" << barrierDiffCN\n                   << \"\\n    tolerance:  \" << barrierTol);\n    }\n}\n\nvoid FdHestonTest::testSpuriousOscillations() {\n    BOOST_TEST_MESSAGE(\"Testing for spurious oscillations when \"\n            \"solving the Heston PDEs...\");\n\n    SavedSettings backup;\n\n    const DayCounter dc = Actual365Fixed();\n    const Date today = Date(7, June, 2018);\n\n    Settings::instance().evaluationDate() = today;\n\n    const Handle<Quote> spot(ext::make_shared<SimpleQuote>(100.0));\n    const Handle<YieldTermStructure> qTS(flatRate(today, 0.1, dc));\n    const Handle<YieldTermStructure> rTS(flatRate(today, 0.0, dc));\n\n    const Real v0    = 0.005;\n    const Real kappa = 1.0;\n    const Real theta = 0.005;\n    const Real sigma = 0.4;\n    const Real rho   = -0.75;\n\n    const Date maturity = today + Period(1, Years);\n\n    const ext::shared_ptr<HestonProcess> process =\n        ext::make_shared<HestonProcess>(\n            rTS, qTS, spot, v0, kappa, theta, sigma, rho);\n\n    const ext::shared_ptr<HestonModel> model =\n        ext::make_shared<HestonModel>(process);\n\n    const ext::shared_ptr<FdHestonVanillaEngine> hestonEngine(\n        ext::make_shared<FdHestonVanillaEngine>(\n            model, 6, 200, 13, 0, FdmSchemeDesc::TrBDF2()));\n\n    VanillaOption option(\n        ext::make_shared<PlainVanillaPayoff>(Option::Call, spot->value()),\n        ext::make_shared<EuropeanExercise>(maturity));\n\n    option.setupArguments(hestonEngine->getArguments());\n\n    const ext::tuple<FdmSchemeDesc, std::string, bool> descs[] = {\n        ext::make_tuple(FdmSchemeDesc::CraigSneyd(), \"Craig-Sneyd\", true),\n        ext::make_tuple(FdmSchemeDesc::Hundsdorfer(), \"Hundsdorfer\", true),\n        ext::make_tuple(\n           FdmSchemeDesc::ModifiedHundsdorfer(), \"Mod. Hundsdorfer\", true),\n        ext::make_tuple(FdmSchemeDesc::Douglas(), \"Douglas\", true),\n        ext::make_tuple(FdmSchemeDesc::CrankNicolson(), \"Crank-Nicolson\", true),\n        ext::make_tuple(FdmSchemeDesc::ImplicitEuler(), \"Implicit\", false),\n        ext::make_tuple(FdmSchemeDesc::TrBDF2(), \"TR-BDF2\", false)\n    };\n\n    for (const auto& desc : descs) {\n        const ext::shared_ptr<FdmHestonSolver> solver = ext::make_shared<FdmHestonSolver>(\n            Handle<HestonProcess>(process), hestonEngine->getSolverDesc(1.0), ext::get<0>(desc));\n\n        std::vector<Real> gammas;\n        for (Real x=99; x < 101.001; x+=0.1) {\n            gammas.push_back(solver->gammaAt(x, v0));\n        }\n\n        Real maximum = QL_MIN_REAL;\n        for (Size i=1; i < gammas.size(); ++i) {\n            const Real diff = std::fabs(gammas[i] - gammas[i-1]);\n            if (diff > maximum)\n                maximum = diff;\n        }\n\n        const Real tol = 0.01;\n        const bool hasSpuriousOscillations = maximum > tol;\n\n        if (hasSpuriousOscillations != ext::get<2>(desc)) {\n            BOOST_ERROR(\"unable to reproduce spurious oscillation behaviour \"\n                        << \"\\n   scheme name          : \" << ext::get<1>(desc)\n                        << \"\\n   oscillations observed: \" << hasSpuriousOscillations\n                        << \"\\n   oscillations expected: \" << ext::get<2>(desc));\n        }\n    }\n}\n\ntest_suite* FdHestonTest::suite(SpeedLevel speed) {\n    auto* suite = BOOST_TEST_SUITE(\"Finite Difference Heston tests\");\n\n    suite->add(QUANTLIB_TEST_CASE(&FdHestonTest::testFdmHestonVarianceMesher));\n    suite->add(QUANTLIB_TEST_CASE(&FdHestonTest::testFdmHestonBarrier));\n    suite->add(QUANTLIB_TEST_CASE(&FdHestonTest::testFdmHestonAmerican));\n    suite->add(QUANTLIB_TEST_CASE(&FdHestonTest::testFdmHestonIkonenToivanen));\n    suite->add(QUANTLIB_TEST_CASE(\n        &FdHestonTest::testFdmHestonEuropeanWithDividends));\n    suite->add(QUANTLIB_TEST_CASE(\n        &FdHestonTest::testFdmHestonIntradayPricing));\n    suite->add(QUANTLIB_TEST_CASE(&FdHestonTest::testMethodOfLinesAndCN));\n    suite->add(QUANTLIB_TEST_CASE(&FdHestonTest::testSpuriousOscillations));\n\n    if (speed <= Fast) {\n        suite->add(QUANTLIB_TEST_CASE(\n            &FdHestonTest::testFdmHestonBlackScholes));\n        suite->add(QUANTLIB_TEST_CASE(\n            &FdHestonTest::testFdmHestonConvergence));\n    }\n\n    if (speed == Slow) {\n        suite->add(QUANTLIB_TEST_CASE(\n            &FdHestonTest::testFdmHestonBarrierVsBlackScholes));\n    }\n\n    return suite;\n}\n\n", "meta": {"hexsha": "33968d10dc41e7a3d5c322129214c16f2a64c843", "size": 43402, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test-suite/fdheston.cpp", "max_stars_repo_name": "thejourneyofman/QuantLib", "max_stars_repo_head_hexsha": "98467eaf6d1a20885f05ea1aa602bb8380c39390", "max_stars_repo_licenses": ["BSD-3-Clause"], "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-suite/fdheston.cpp", "max_issues_repo_name": "thejourneyofman/QuantLib", "max_issues_repo_head_hexsha": "98467eaf6d1a20885f05ea1aa602bb8380c39390", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test-suite/fdheston.cpp", "max_forks_repo_name": "thejourneyofman/QuantLib", "max_forks_repo_head_hexsha": "98467eaf6d1a20885f05ea1aa602bb8380c39390", "max_forks_repo_licenses": ["BSD-3-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.8027613412, "max_line_length": 100, "alphanum_fraction": 0.5774388277, "num_tokens": 13454, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.45071091464531543}}
{"text": "/**\n * \\ file OneMinusFilter.cpp\n */\n\n#include <ATK/Tools/OneMinusFilter.h>\n\n#include <ATK/Core/InPointerFilter.h>\n#include <ATK/Core/OutPointerFilter.h>\n\n#include <gtest/gtest.h>\n\n#include <boost/math/constants/constants.hpp>\n\nconstexpr gsl::index PROCESSSIZE = 1024;\n\nTEST(OneMinusFilter, sinus_test)\n{\n  std::array<double, PROCESSSIZE> data;\n  for(gsl::index i = 0; i < PROCESSSIZE; ++i)\n  {\n    data[i] = std::sin(2 * boost::math::constants::pi<double>() * (i+1.)/48000 * 1000);\n  }\n  \n  ATK::InPointerFilter<double> generator(data.data(), 1, PROCESSSIZE, false);\n  generator.set_output_sampling_rate(48000);\n\n  std::array<double, PROCESSSIZE> outdata;\n\n  ATK::OneMinusFilter<double> filter(1);\n  filter.set_input_sampling_rate(48000);\n  filter.set_input_port(0, &generator, 0);\n\n  ATK::OutPointerFilter<double> output(outdata.data(), 1, PROCESSSIZE, false);\n  output.set_input_sampling_rate(48000);\n  output.set_input_port(0, &filter, 0);\n\n  output.process(PROCESSSIZE);\n  \n  for(gsl::index i = 0; i < PROCESSSIZE; ++i)\n  {\n    ASSERT_NEAR(data[i] + outdata[i], 1., 0.0001);\n  }\n}\n", "meta": {"hexsha": "b4e5270ff004d6d252a321fadf72618f0b8ea37b", "size": 1086, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/Tools/OneMinusFilter.cpp", "max_stars_repo_name": "AudioTK/AudioTK", "max_stars_repo_head_hexsha": "dba42eea68534501efe74692b74edf4792cca231", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2021-02-04T10:47:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T03:45:00.000Z", "max_issues_repo_path": "tests/Tools/OneMinusFilter.cpp", "max_issues_repo_name": "AudioTK/AudioTK", "max_issues_repo_head_hexsha": "dba42eea68534501efe74692b74edf4792cca231", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-02-01T15:45:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-13T19:39:05.000Z", "max_forks_repo_path": "tests/Tools/OneMinusFilter.cpp", "max_forks_repo_name": "AudioTK/AudioTK", "max_forks_repo_head_hexsha": "dba42eea68534501efe74692b74edf4792cca231", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-04-12T03:28:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-17T00:47:11.000Z", "avg_line_length": 24.6818181818, "max_line_length": 87, "alphanum_fraction": 0.6952117864, "num_tokens": 323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581741774411, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4506852191585175}}
{"text": "/*\n********************************************************************************\nMIT License\n\nCopyright(c) 2018 Christopher Brandt\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 <math.h>\n\n#include \"ProjDynRHSInterpol.h\"\n#include \"ProjDynConstraints.h\"\n#include \"ProjDynSimulator.h\"\n#include \"ProjUtils/ProjDynUtil.h\"\n#include <Eigen/Eigenvalues>\n\nPDMatrix PD::RHSInterpolationGroup::snapshotPCA(PDMatrix& Y, PDVector& masses, unsigned int size)\n{\n\t/* PCA via the method of snapshots*/\n\n\tstd::cout << \"Performing snapshot PCA...\" << std::endl;\n\n\tPDMatrix base(Y.rows(), size + 1);\n\n\tstd::cout << \"\tRemoving column wise mean...\" << std::endl;\n\n\t// Remove column wise mean\n\tPROJ_DYN_PARALLEL_FOR\n\t\tfor (int j = 0; j < Y.cols(); j++) {\n\t\t\tPDScalar mean = Y.col(j).mean();\n\t\t\tfor (unsigned int i = 0; i < Y.rows(); i++) {\n\t\t\t\tY(i, j) -= mean;\n\t\t\t}\n\t\t}\n\n\t// We solve the SVD by solving an eigenvalue problem on the smaller matrix A = Y^T M Y\n\t// and converting the eigenvectors to that problem back to v = Y u\n\tstd::cout << \"\tComputing Y^T M Y...\" << std::endl;\n\tPDMatrix A;\n#ifdef PROJ_DYN_USE_CUBLAS_IN_PRE\n\tstd::cout << \"\t\tuploading Y to GPU...\" << std::endl;\n\tCUDAMatrixVectorMultiplier* yMulti = new CUDAMatrixVectorMultiplier(Y, masses);\n\tstd::cout << \"\t\tcomputing Y^T (M Y) on GPU...\" << std::endl;\n\tA.resize(Y.cols(), Y.cols());\n\tfor (unsigned int i = 0; i < Y.cols(); i++) {\n\t\tPDScalar one = 1;\n\t\tyMulti->mult(Y.data() + (i * Y.rows()), A.data() + (i * A.rows()), one, true);\n\t}\n#else\n\tPDMatrix Y_T = Y.transpose();\n\tPROJ_DYN_PARALLEL_FOR\n\t\tfor (int j = 0; j < Y.cols(); j++) {\n\t\t\tY_T.col(j) *= masses(j);\n\t\t}\n\tA.resize(Y.cols(), Y.cols());\n\tPROJ_DYN_PARALLEL_FOR\n\t\tfor (int j = 0; j < Y.cols(); j++) {\n\t\t\tA.col(j) = Y_T * Y.col(j);\n\t\t}\n#endif\n\tstd::cout << \"\tComputing eigenvectors v of Y^T M Y...\" << std::endl;\n\tEigen::EigenSolver< PDMatrix > eSolver;\n\teSolver.compute(A, true);\n\tEigen::Matrix< std::complex< double >, -1, -1> eVecsC = eSolver.eigenvectors();\n\tEigen::Matrix< std::complex< double >, -1, 1> eValsC = eSolver.eigenvalues();\n\tstd::cout << \"\tExtracting PCA vectors as Y v...\" << std::endl;\n\tPDScalar currentEVal = -1;\n\tstd::vector<unsigned int> eVecInds;\n\tfor (int v = 0; v < size; v++) {\n\t\tPDScalar currentLargest = 0;\n\t\tint indOfLargest = -1;\n\t\tfor (int j = 0; j < eValsC.rows(); j++) {\n\t\t\tif (eValsC(j).real() > currentLargest && (currentEVal < 0 || eValsC(j).real() < currentEVal)) {\n\t\t\t\tcurrentLargest = eValsC(j).real();\n\t\t\t\tindOfLargest = v;\n\t\t\t}\n\t\t}\n\t\tif (indOfLargest >= 0) {\n\t\t\teVecInds.push_back(indOfLargest);\n\t\t\tcurrentEVal = eValsC(indOfLargest).real();\n\t\t\t//std::cout << eValsC(indOfLargest).real() << std::endl;\n\t\t}\n\t\telse {\n\t\t\tstd::cout << \"Could only find \" << (v - 1) << \" eigenvectors with strictly positive eigenvalues during snapshot PCA ...\" << std::endl;\n\t\t\tbase.conservativeResize(base.rows(), std::max(1, v - 10));\n\t\t\tbreak;\n\t\t}\n\t}\n\n#ifdef PROJ_DYN_USE_CUBLAS_IN_PRE\n\tfor (int v = 0; v < std::min((int)base.cols(), (int)eVecInds.size()); v++) {\n\t\tPDScalar weight = (1. / std::sqrt(eValsC(eVecInds[v]).real()));\n\t\tPDVector eVec = eVecsC.col(eVecInds[v]).real();\n\t\tyMulti->mult(eVec.data(), base.data() + (v * base.rows()), weight, false);\n\t}\n\tdelete yMulti;\n#else\n\tPROJ_DYN_PARALLEL_FOR\n\t\tfor (int v = 0; v < std::min((int)base.cols(), (int)eVecInds.size()); v++) {\n\t\t\tPDVector eVec = eVecsC.col(eVecInds[v]).real();\n\t\t\tbase.col(v) = Y * eVec;\n\t\t\tPDScalar weight = (1. / std::sqrt(eValsC(eVecInds[v]).real()));\n\t\t\tbase.col(v) *= weight;\n\t\t}\n#endif\n\n\tif (base.hasNaN()) {\n\t\tstd::cout << \"Warning: base contains NaN values!\" << std::endl;\n\t}\n\n\t// Make sure to include global translations since we removed column wise mean\n\tbase.col(base.cols() - 1).setConstant(1.);\n\n\tstd::cout << \"\tDone.\" << std::endl;\n\n\treturn base;\n}\n\n\nPD::RHSInterpolationGroup::RHSInterpolationGroup(std::string groupName, std::vector<ProjDynConstraint*>& constraints, PDPositions& restPositions,\n\tPDVector& vertexMasses, PDTriangles& tris, PDTets& tets, PDScalar regularizationWeight)\n\t:\n\tm_auxiliarySize(0),\n\tm_basis(0, 0),\n\tm_interpolReady(false),\n\tm_basisReady(false),\n\tm_groupName(groupName),\n\tm_regularizationWeight(regularizationWeight),\n\tm_restPositionFull(restPositions)\n{\n\tfor (auto c : constraints) {\n\t\t//ProjDynConstraint* cc = c->copy();\n\t\tm_constraints.push_back(c);\n\t}\n\n\tm_isTetExampleGroup = (m_groupName == \"tetex\");\n\n\tif (m_constraints.size() >= 1) {\n\t\tint dummy = -1;\n\t\tm_auxiliarySize = m_constraints.at(0)->getP(restPositions, dummy).rows();\n\n\t\t// Compute the mass matrix for the unassembled auxiliaries\n\t\tcomputeMassMatrix(vertexMasses, tris, tets);\n\t}\n}\n\nPD::RHSInterpolationGroup::RHSInterpolationGroup(std::string groupName, unsigned int auxiliarySize)\n\t:\n\tm_groupName(groupName),\n\tm_auxiliarySize(auxiliarySize),\n\tm_basis(0, 0),\n\tm_selectionMatrix(0, 0),\n\tm_interpolReady(false),\n\tm_basisReady(false),\n\tm_regularizationWeight(0.),\n\tm_restPositionFull(0, 3)\n{\n}\n\nvoid PD::RHSInterpolationGroup::computeMassMatrix(PDVector& vertexMasses, PDTriangles& tris, PDTets& tets) {\n\t// Compute the mass matrix for the unassembled auxiliaries\n\tm_massMatrix.resize(m_constraints.size() * m_auxiliarySize, m_constraints.size() * m_auxiliarySize);\n\tm_massMatrixDiag.resize(m_constraints.size() * m_auxiliarySize);\n\tint i = 0;\n\tfor (auto& c : m_constraints) {\n\t\tdouble weight = 1.;\n\t\tif (!NO_MASSES_IN_PCA) {\n\t\t\tif (c->getMainVertexIndex() > 0) {\n\t\t\t\tweight = vertexMasses(c->getMainVertexIndex());\n\t\t\t}\n\t\t\telse if (c->getMainTriangleIndex() > 0) {\n\t\t\t\tweight = 0;\n\t\t\t\tfor (int j = 0; j < 3; j++) {\n\t\t\t\t\tweight += vertexMasses(tris(c->getMainTriangleIndex(), j));\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (c->getMainTetIndex() > 0) {\n\t\t\t\tweight = 0;\n\t\t\t\tfor (int j = 0; j < 4; j++) {\n\t\t\t\t\tweight += vertexMasses(tets(c->getMainTetIndex(), j));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor (int j = 0; j < m_auxiliarySize; j++) {\n\t\t\tm_massMatrix.insert(i * m_auxiliarySize + j, i * m_auxiliarySize + j) = weight;\n\t\t\tm_massMatrixDiag(i * m_auxiliarySize + j) = weight;\n\t\t}\n\t\ti++;\n\t}\n}\n\nvoid PD::RHSInterpolationGroup::createBasisViaSkinningWeights(unsigned int size, PDPositions& restPos, PDMatrix& skinningWeights, bool usePCA,\n\tPDTriangles& tris, PDTets &tets)\n{\n\tstd::cout << \"Creating interpolation basis via skinning construction for \" << getName() << \"... \" << std::endl;\n\tstd::cout << \"\tComputing rest state auxiliary variables...\" << std::endl;\n\tPDPositions restStateAuxils = PD::getAssemblyMatrix(m_constraints, true, NO_WEIGHTS_IN_CONSTRUCTION).transpose() * restPos;\n\tstd::cout << \"\tComputing skinning space...\" << std::endl;\n\tPDMatrix Y = PD::createSkinningSpace(restStateAuxils, skinningWeights, &m_constraints, m_auxiliarySize, &tris, &tets);\n\n\tif (!usePCA) {\n\t\tm_basis = Y;\n\t}\n\telse {\n\t\tm_basis = RHSInterpolationGroup::snapshotPCA(Y, m_massMatrixDiag, size);\n\t}\n\tm_basisReady = true;\n\tm_interpolReady = false;\n}\n\nvoid PD::RHSInterpolationGroup::setBasis(PDMatrix & base)\n{\n\tm_basis = base;\n\n\tm_basisReady = true;\n\tm_interpolReady = false;\n\n}\n\nvoid PD::RHSInterpolationGroup::initInterpolation(unsigned int numVertices, std::vector<unsigned int>& sampledElements,\n\tPDSparseMatrix const& positionSubspaceT)\n{\n\tstd::cout << \"Finalizing rhs interpolation for \" << getName() << \"... \" << std::endl;\n\tstd::cout << \"\tComputing assembly, selection and weight matrix...\" << std::endl;\n\n\tstd::vector<unsigned int> sampledElsCopy = sampledElements;\n\n\t// Create assembly matrix \n\tm_assemblyMatrix = PD::getAssemblyMatrix(m_constraints, true, NO_WEIGHTS_IN_CONSTRUCTION);\n\n\t// Create selection and weights matrix\n\tstd::vector<Eigen::Triplet<PDScalar>> selectedInds;\n\tm_weightMatrix.resize(m_constraints.size() * m_auxiliarySize, m_constraints.size() * m_auxiliarySize);\n\tPDVector weightVector(m_constraints.size() * m_auxiliarySize);\n\tweightVector.setConstant(1.);\n\tfor (unsigned int i = 0; i < m_constraints.size(); i++) {\n\t\tProjDynConstraint* c = m_constraints[i];\n\t\tunsigned int constraintElement = -1;\n\t\tif (c->getMainVertexIndex() >= 0) {\n\t\t\tconstraintElement = c->getMainVertexIndex();\n\t\t}\n\t\telse if (c->getMainTriangleIndex() >= 0) {\n\t\t\tconstraintElement = c->getMainTriangleIndex();\n\t\t}\n\t\telse if (c->getMainTetIndex() >= 0) {\n\t\t\tconstraintElement = c->getMainTetIndex();\n\t\t}\n\t\tauto const& it = std::find(sampledElsCopy.begin(), sampledElsCopy.end(), constraintElement);\n\t\tif (m_sampledConstraints.size() < sampledElements.size() && it != sampledElsCopy.end()) {\n\t\t\tsampledElsCopy.erase(it);\n\t\t\tm_sampledConstraints.push_back(c->copy());\n\t\t\tint ind = m_sampledConstraints.size() - 1;\n\t\t\tfor (int d = 0; d < m_auxiliarySize; d++) {\n\t\t\t\tselectedInds.push_back(Eigen::Triplet<PDScalar>(ind * m_auxiliarySize + d, i * m_auxiliarySize + d, 1.));\n\t\t\t}\n\t\t}\n\t\tfor (int j = 0; j < m_auxiliarySize; j++) {\n\t\t\tif (NO_WEIGHTS_IN_CONSTRUCTION) {\n\t\t\t\tm_weightMatrix.insert(i * m_auxiliarySize + j, i * m_auxiliarySize + j) = c->getWeight();\n\t\t\t\tweightVector(i * m_auxiliarySize + j) = c->getWeight();\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// Weights are included in the interpolation problem and snapshot basis\n\t\t\t\tm_weightMatrix.insert(i * m_auxiliarySize + j, i * m_auxiliarySize + j) = 1.;\n\t\t\t}\n\t\t}\n\t}\n\tm_selectionMatrix = PDSparseMatrix(sampledElements.size() * m_auxiliarySize, m_constraints.size() * m_auxiliarySize);\n\tm_selectionMatrix.setZero();\n\tm_selectionMatrix.setFromTriplets(selectedInds.begin(), selectedInds.end());\n\t// If we couldn't find as many constraint samples as we have sampled\n\t// elements, we overestimated the number of rows in the selection matrix\n\t// and need to cut off the rest.\n\tif (m_sampledConstraints.size() < sampledElements.size()) {\n\t\tm_selectionMatrix.conservativeResize(m_sampledConstraints.size() * m_auxiliarySize, m_selectionMatrix.cols());\n\t}\n\tif (m_selectionMatrix.rows() < m_basis.cols() - MIN_OVERSAMPLING) {\n\t\tstd::cout << \"Warning: not enough sampled constraints (\" << m_sampledConstraints.size()\n\t\t\t<< \") for this rhs interpolation base (\" << m_basis.cols() << \").\" << std::endl;\n\t\tstd::cout << \"\tCutting off last vectors in base.\" << std::endl;\n\t\tm_basis.conservativeResize(m_basis.rows(), m_selectionMatrix.rows() - MIN_OVERSAMPLING);\n\t}\n\n\t// Compute lhs and rhs matrices and solver for the inteprolation problem\n\tstd::cout << \"\tComputing lhs and rhs matrices for linear interpolation system and factorizing...\" << std::endl;\n\tm_interpolRHSMatrix = m_basis.transpose() * m_selectionMatrix.transpose();\n\tPDMatrix lhsMat;\n\tif (m_regularizationWeight > 0) {\n\t\tlhsMat = m_basis.transpose() * ((m_selectionMatrix.transpose() * m_selectionMatrix) + m_regularizationWeight * m_massMatrix) * m_basis;\n\t}\n\telse {\n\t\tlhsMat = m_basis.transpose() * ((m_selectionMatrix.transpose() * m_selectionMatrix)) * m_basis;\n\t}\n\tm_interpolSolver.compute(lhsMat);\n\tm_tempSolution.resize(lhsMat.rows(), 3);\n\tm_solutionLastFrame.resize(lhsMat.rows(), 3);\n\tm_tempAuxils.resize(m_selectionMatrix.rows(), 3);\n\tm_tempRHS.resize(lhsMat.rows(), 3);\n\n\t// If regularization is used we have to get some initial value for m_solutionLastFrame\n\t// For this we have to evaluate the auxilaries for the rest state and set up a projection\n\t// problem, which returns the best subspace approximation of these auxilaries in\n\t// the interpolation base.\n\tif (m_regularizationWeight > 0) {\n\t\tstd::cout << \"\tComputing extra stuff for regularization...\" << std::endl;\n\t\tm_regularizationRHSMatrix = m_basis.transpose() * m_massMatrix * m_basis;\n\t\tPDPositions rhsFull(m_constraints.size() * m_auxiliarySize, 3);\n\t\t// Collect auxiliary variables for sampled constraints\n\t\tint didCollide = -1;\n\t\tPROJ_DYN_PARALLEL_FOR\n\t\t\tfor (int i = 0; i < m_constraints.size(); i++) {\n\t\t\t\tPDScalar weight = 1.;\n\t\t\t\tif (!NO_WEIGHTS_IN_CONSTRUCTION) {\n\t\t\t\t\tweight = std::sqrt(m_constraints[i]->getWeight());\n\t\t\t\t}\n\t\t\t\tdidCollide = -1;\n\t\t\t\trhsFull.block(i*m_auxiliarySize, 0, m_auxiliarySize, 3) = m_constraints[i]->getP(m_restPositionFull, didCollide)\n\t\t\t\t\t* weight;\n\t\t\t}\n\t\tPDPositions rhsSub = m_basis.transpose() * m_massMatrix * rhsFull;\n\t\tPDMatrix projLHS = m_basis.transpose() * m_massMatrix * m_basis;\n\t\tEigen::LLT<PDMatrix> projSolver;\n\t\tprojSolver.compute(projLHS);\n\t\tfor (unsigned int d = 0; d < 3; d++) {\n\t\t\tm_solutionLastFrame.col(d) = projSolver.solve(rhsSub.col(d));\n\t\t}\n\t}\n\n\t// Compute the finalization matrix, i.e. the one that maps a vector from the subspace\n\t// spanned by the snapshots' PCA to a fully assembled rhs.\n\t// In case a positions subspace is used, the transpose of the subspace matrix will\n\t// also be applied to the matrix\n\tstd::cout << \"\tComputing 'finalize' matrices...\" << std::endl;\n\tif (positionSubspaceT.rows() > 0) {\n\t\tstd::cout << \"\t\tsparse part...\" << std::endl;\n\t\tPDSparseMatrix finalTemp = positionSubspaceT * m_assemblyMatrix;\n\t\tif (NO_WEIGHTS_IN_CONSTRUCTION) {\n\t\t\tPROJ_DYN_PARALLEL_FOR\n\t\t\t\tfor (int c = 0; c < finalTemp.cols(); c++) {\n\t\t\t\t\tfinalTemp.col(c) *= weightVector(c);\n\t\t\t\t}\n\t\t}\n\t\tstd::cout << \"\t\tdense part...\" << std::endl;\n\t\tm_finalizeMatrix.resize(positionSubspaceT.rows(), m_basis.cols());\n\t\tPROJ_DYN_PARALLEL_FOR\n\t\t\tfor (int c = 0; c < m_basis.cols(); c++) {\n\t\t\t\tm_finalizeMatrix.col(c) = finalTemp * m_basis.col(c);\n\t\t\t}\n\t\tm_usingPositionSubspace = true;\n\t}\n\telse {\n\t\tm_finalizeMatrixBig = m_assemblyMatrix * m_weightMatrix * m_basis;\n\t\tm_usingPositionSubspace = false;\n\t}\n\n\t// Finally compute the solver for the projection problem if desired\n\tif (PROJ_DYN_ENABLE_RHS_PROJECTION) {\n\t\tstd::cout << \"\tComputing projection solver for this group...\" << std::endl;\n\t\tm_projectionSolver.compute(m_basis.transpose() * m_basis);\n\t\tif (m_usingPositionSubspace) {\n\t\t\tm_projectionFinalizeMatrix = positionSubspaceT * m_assemblyMatrix;\n\t\t}\n\t}\n\n\tstd::cout << \"Initiated snapshot interpolation for group \" << m_groupName << \".\" << std::endl;\n\n\tm_interpolReady = true;\n}\n\nvoid PD::RHSInterpolationGroup::approximateRHS(PDPositions & pos, PDPositions & rhs, bool * collidedVertices)\n{\n\tif (!m_interpolReady) {\n\t\tstd::cout << \"Interpolation is not initialized!!!\" << std::endl;\n\t\treturn;\n\t}\n\n\tinterpolate(pos, m_tempSolution, collidedVertices);\n\n\t// Apply finalization matrix and add to current rhs\n\tif (m_usingPositionSubspace) {\n\t\tPROJ_DYN_PARALLEL_FOR\n\t\t\tfor (int d = 0; d < 3; d++) {\n\t\t\t\trhs.col(d) += m_weightFac * m_finalizeMatrix * m_tempSolution.col(d);\n\t\t\t\t//std::cout << m_finalizeMatrix * m_tempSolution.col(d) << std::endl;\n\t\t\t}\n\t}\n\telse {\n\t\tPROJ_DYN_PARALLEL_FOR\n\t\t\tfor (int d = 0; d < 3; d++) {\n\t\t\t\trhs.col(d) += m_weightFac * m_finalizeMatrixBig * m_tempSolution.col(d);\n\t\t\t}\n\t}\n}\n\nvoid PD::RHSInterpolationGroup::evaluateRHS(PDPositions & pos, PDPositions & rhs, bool projectToInterpolationSpaceAndBack, bool forceFull)\n{\n\tif (PROJ_DYN_ENABLE_RHS_PROJECTION) {\n\t\tPDPositions auxils(m_constraints.size() * m_auxiliarySize, 3);\n\t\tPDPositions auxilsNoWeights(m_constraints.size() * m_auxiliarySize, 3);\n\t\t// Collect auxiliary variables for sampled constraints\n\t\tint didCollide = -1;\n\t\tPROJ_DYN_PARALLEL_FOR\n\t\t\tfor (int i = 0; i < m_constraints.size(); i++) {\n\t\t\t\tdidCollide = -1;\n\t\t\t\tPDScalar weight = m_constraints[i]->getWeight();\n\t\t\t\tif (!NO_WEIGHTS_IN_CONSTRUCTION) {\n\t\t\t\t\tweight = std::sqrt(weight);\n\t\t\t\t}\n\t\t\t\tauxils.block(i*m_auxiliarySize, 0, m_auxiliarySize, 3) = m_constraints[i]->getP(pos, didCollide)\n\t\t\t\t\t* weight * m_weightFac;\n\t\t\t\tauxilsNoWeights.block(i*m_auxiliarySize, 0, m_auxiliarySize, 3) = m_constraints[i]->getP(pos, didCollide);\n\t\t\t}\n\n\t\tif (projectToInterpolationSpaceAndBack) {\n\t\t\tPDPositions solutionSub = m_projectionSolver.solve(m_basis.transpose() * auxilsNoWeights);\n\t\t\tauxils = m_basis * solutionSub;\n\t\t\tPROJ_DYN_PARALLEL_FOR\n\t\t\t\tfor (int i = 0; i < m_constraints.size(); i++) {\n\t\t\t\t\tdidCollide = -1;\n\t\t\t\t\tPDScalar weight = m_constraints[i]->getWeight();\n\t\t\t\t\tif (!NO_WEIGHTS_IN_CONSTRUCTION) {\n\t\t\t\t\t\tweight = std::sqrt(weight);\n\t\t\t\t\t}\n\t\t\t\t\tauxils.block(i*m_auxiliarySize, 0, m_auxiliarySize, 3) *= weight * m_weightFac;\n\t\t\t\t}\n\t\t}\n\n\t\tif (m_usingPositionSubspace && !forceFull) {\n\t\t\trhs += m_projectionFinalizeMatrix * auxils;\n\t\t}\n\t\telse {\n\t\t\trhs += m_assemblyMatrix * auxils;\n\t\t}\n\t}\n\telse {\n\t\tstd::cout << \"Enable PROJ_DYN_ENABLE_RHS_PROJECTION if you desire to evaluate full rhs!\" << std::endl;\n\t}\n}\n\nvoid PD::RHSInterpolationGroup::interpolate(PDPositions & pos, PDPositions & interpol, bool* collidedVertices)\n{\n\t// Collect auxiliary variables for sampled constraints\n\tint didCollide = -1;\n\tPROJ_DYN_PARALLEL_FOR\n\t\tfor (int i = 0; i < m_sampledConstraints.size(); i++) {\n\t\t\tdidCollide = -1;\n\t\t\tPDScalar weight = 1.;\n\t\t\tif (!NO_WEIGHTS_IN_CONSTRUCTION) {\n\t\t\t\tweight = std::sqrt(m_sampledConstraints[i]->getWeight());\n\t\t\t}\n\t\t\tm_tempAuxils.block(i*m_auxiliarySize, 0, m_auxiliarySize, 3) = m_sampledConstraints[i]->getP(pos, didCollide)\n\t\t\t\t* weight * m_blowUp;\n\t\t\tif (collidedVertices && didCollide > 0) {\n\t\t\t\tcollidedVertices[didCollide] = true;\n\t\t\t}\n\t\t}\n\n\t// Set up rhs from auxiliaries and solve the system for all three columns\n\tPROJ_DYN_PARALLEL_FOR\n\t\tfor (int d = 0; d < 3; d++) {\n\t\t\tm_tempRHS.col(d) = m_interpolRHSMatrix * m_tempAuxils.col(d);\n\t\t\tif (m_regularizationWeight > 0.) {\n\t\t\t\tm_tempRHS.col(d) += m_regularizationWeight * m_regularizationRHSMatrix * m_solutionLastFrame.col(d);\n\t\t\t}\n\t\t\tinterpol.col(d) = m_interpolSolver.solve(m_tempRHS.col(d));\n\t\t}\n\n\tm_solutionLastFrame = interpol;\n}\n\nPDMatrix PD::RHSInterpolationGroup::getLHSMatrixSubspace(PDMatrix& posSubspaceMat, PDMatrix& posSubspaceMat_T)\n{\n\tif (!m_lhsMatrixSubspaceInitialized) {\n\t\tPDSparseMatrix temp;\n\t\tif (NO_WEIGHTS_IN_CONSTRUCTION) {\n\t\t\ttemp = m_assemblyMatrix * m_weightMatrix * m_assemblyMatrix.transpose();\n\t\t}\n\t\telse {\n\t\t\ttemp = m_assemblyMatrix * m_assemblyMatrix.transpose();\n\t\t}\n\t\tm_lhsMatrixSubspace = posSubspaceMat_T * temp * posSubspaceMat;\n\t\tm_lhsMatrixSubspaceInitialized = true;\n\t}\n\treturn m_lhsMatrixSubspace;\n}\n\nPDSparseMatrix PD::RHSInterpolationGroup::getLHSMatrix()\n{\n\tPDSparseMatrix temp;\n\tif (NO_WEIGHTS_IN_CONSTRUCTION) {\n\t\ttemp = m_assemblyMatrix * m_weightMatrix * m_assemblyMatrix.transpose();\n\t}\n\telse {\n\t\ttemp = m_assemblyMatrix * m_assemblyMatrix.transpose();\n\t}\n\n\treturn temp;\n}\n\nbool PD::RHSInterpolationGroup::hasBasis()\n{\n\treturn m_basis.cols() >= 1 && m_basis.rows() > 1;\n}\n\nstd::vector<ProjDynConstraint*>& PD::RHSInterpolationGroup::getSampledConstraints()\n{\n\treturn m_sampledConstraints;\n}\n\nstd::vector<ProjDynConstraint*>& PD::RHSInterpolationGroup::getConstraints()\n{\n\treturn m_constraints;\n}\n\nvoid PD::RHSInterpolationGroup::setExampleWeights(std::vector<PDScalar>& weights)\n{\n\tif (m_isTetExampleGroup) {\n\t\tfor (ProjDynConstraint* c : m_sampledConstraints) {\n\t\t\tTetExampleBased* tc = (TetExampleBased*)c;\n\t\t\ttc->setExampleWeights(weights);\n\t\t}\n\t}\n\telse if (getName() == \"spring\") {\n\t\tfor (ProjDynConstraint* c : m_sampledConstraints) {\n\t\t\tSpringConstraint* sc = (SpringConstraint*)c;\n\t\t\tsc->setExWeights(weights);\n\t\t}\n\t}\n\telse {\n\t\treturn;\n\t}\n}\n\nvoid PD::RHSInterpolationGroup::setWeightFactor(PDScalar w)\n{\n\tm_weightFac = w;\n}\n\nvoid PD::RHSInterpolationGroup::setBlowup(PDScalar s)\n{\n\tm_blowUp = s;\n}\n\nstd::string PD::RHSInterpolationGroup::getName()\n{\n\treturn m_groupName;\n}\n", "meta": {"hexsha": "79150382af953569391bd0c957eee93890f72180", "size": 20015, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "HRPD/core/ProjDynRHSInterpol.cpp", "max_stars_repo_name": "wghou/pyMOR", "max_stars_repo_head_hexsha": "2d83389127b1b794ef43b8c96f19ab3b9d9a0643", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "HRPD/core/ProjDynRHSInterpol.cpp", "max_issues_repo_name": "wghou/pyMOR", "max_issues_repo_head_hexsha": "2d83389127b1b794ef43b8c96f19ab3b9d9a0643", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HRPD/core/ProjDynRHSInterpol.cpp", "max_forks_repo_name": "wghou/pyMOR", "max_forks_repo_head_hexsha": "2d83389127b1b794ef43b8c96f19ab3b9d9a0643", "max_forks_repo_licenses": ["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.3621908127, "max_line_length": 145, "alphanum_fraction": 0.6979765176, "num_tokens": 5804, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581741774411, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4506852191585175}}
{"text": "// SPDX-License-Identifier: Apache-2.0\n/*\nCopyright 2019 Blue Cheetah Analog Design Inc.\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 <boost/container_hash/hash.hpp>\n\n#include <fmt/core.h>\n\n#include <cbag/layout/track_coloring.h>\n#include <cbag/util/math.h>\n\nnamespace cbag {\nnamespace layout {\n\ncolor_info::color_info() noexcept = default;\n\ncolor_info::color_info(cnt_t mod, offset_t scale, offset_t offset) noexcept\n    : mod_(mod), scale_(scale), offset_(offset) {}\n\nbool color_info::operator==(const color_info &rhs) const noexcept {\n    return mod_ == rhs.mod_ && scale_ == rhs.scale_ && offset_ == rhs.offset_;\n}\n\nbool color_info::is_valid() const noexcept { return mod_ >= 1; }\n\nstd::size_t color_info::get_hash() const noexcept {\n    auto seed = static_cast<std::size_t>(mod_);\n    boost::hash_combine(seed, scale_);\n    boost::hash_combine(seed, offset_);\n    return seed;\n}\n\nstd::string color_info::to_string() const {\n    return fmt::format(\"({}, {}, {})\", mod_, scale_, offset_);\n}\n\ncnt_t color_info::get_htr_parity(htr_t htr) const noexcept {\n    // htr transforms to scale * htr + (scale - 1), since\n    // htr = -1 aligns at the axis.\n    return util::pos_mod(scale_ * htr + scale_ - 1 + offset_, 2 * mod_) / 2;\n}\n\ncnt_t color_info::get_modulus() const noexcept { return mod_; }\n\ncolor_info color_info::get_transform(offset_t axis_scale, htr_t orig_htr) const noexcept {\n    auto new_scale = axis_scale * scale_;\n    auto new_offset = util::pos_mod(scale_ * orig_htr + offset_, 2 * mod_);\n    if (mod_ == 2 && new_scale < 0) {\n        // optimization: for 2 colors, sign flip is equivalent to shifting\n        new_scale = 1;\n        new_offset = 3 - new_offset;\n    }\n    return {mod_, new_scale, new_offset};\n}\n\ntrack_coloring::track_coloring() = default;\n\ntrack_coloring::track_coloring(level_t bot_level, std::vector<color_info> &&data)\n    : bot_level_(bot_level), data_(std::move(data)) {}\n\nbool track_coloring::operator==(const track_coloring &rhs) const noexcept {\n    return data_ == rhs.data_;\n}\n\nstd::size_t track_coloring::size() const noexcept { return data_.size(); }\n\nstd::size_t track_coloring::get_hash() const noexcept {\n    auto seed = static_cast<std::size_t>(0);\n    for (const auto &info : data_) {\n        boost::hash_combine(seed, info.get_hash());\n    }\n    return seed;\n}\n\nstd::string track_coloring::to_string() const {\n    auto n = data_.size();\n    switch (n) {\n    case 0:\n        return \"TrackColoring[]\";\n    case 1:\n        return fmt::format(\"TrackColoring[{}]\", data_.front().to_string());\n    default: {\n        auto ans = fmt::format(\"TrackColoring[{}\", data_.front().to_string());\n        for (decltype(n) idx = 1; idx < n; ++idx) {\n            ans += fmt::format(\", {}\", data_[idx].to_string());\n        }\n        ans += \"]\";\n        return ans;\n    }\n    }\n}\n\ncnt_t track_coloring::get_htr_parity(level_t level, htr_t htr) const noexcept {\n    auto idx = level - bot_level_;\n    if (idx < 0 || static_cast<std::size_t>(idx) >= data_.size())\n        return 0;\n\n    return data_[idx].get_htr_parity(htr);\n}\n\nconst color_info &track_coloring::get_color_info(level_t level) const {\n    return data_[level - bot_level_];\n}\n\n} // namespace layout\n} // namespace cbag\n", "meta": {"hexsha": "9094c195ec2431f98248248916a65dfeae71f940", "size": 3708, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cbag/layout/track_coloring.cpp", "max_stars_repo_name": "growly/cbag", "max_stars_repo_head_hexsha": "468bf580223490a8ce0769471e25abf936b56a4e", "max_stars_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2020-02-13T21:51:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-11T10:01:45.000Z", "max_issues_repo_path": "src/cbag/layout/track_coloring.cpp", "max_issues_repo_name": "growly/cbag", "max_issues_repo_head_hexsha": "468bf580223490a8ce0769471e25abf936b56a4e", "max_issues_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-06-03T19:05:14.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-17T22:59:36.000Z", "max_forks_repo_path": "src/cbag/layout/track_coloring.cpp", "max_forks_repo_name": "growly/cbag", "max_forks_repo_head_hexsha": "468bf580223490a8ce0769471e25abf936b56a4e", "max_forks_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-06-03T17:02:46.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-01T23:03:01.000Z", "avg_line_length": 30.9, "max_line_length": 90, "alphanum_fraction": 0.6782632147, "num_tokens": 965, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581741774411, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4506852191585175}}
{"text": "//\n// Variable for Scheme\n//\n// Author: Zhang Zhenghao (zhangzhenghao@hotmail.com)\n//\n#pragma once\n\n#include <string>\n#include <memory>\n#include <sstream>\n#include <iostream>\n#include <functional>\n#include <unordered_map>\n#include <boost/multiprecision/cpp_int.hpp>\n#include \"exception.hpp\"\n#include \"environment.hpp\"\n#include \"garbage.hpp\"\n\nclass Variable: public GarbageObject\n{\npublic:\n\n\t// Type of variable\n\tenum Type {\n\t\tTYPE_RATIONAL \t= 0x01,\n\t\tTYPE_FLOAT \t\t= 0x02,\n\t\tTYPE_STRING \t= 0x04,\n\t\tTYPE_SYMBOL  \t= 0x08,\n\t\tTYPE_SPEC     \t= 0x10,\n\t\tTYPE_PAIR \t \t= 0x20,\n\t\tTYPE_PRIM \t \t= 0x40,\n\t\tTYPE_COMP \t \t= 0x80,\n\t\t// Type class\n\t\tTYPE_TEXT\t\t= 0x0C,\n\t\tTYPE_NUMBER\t\t= 0x03,\n\t\tTYPE_PROCEDURE\t= 0xC0,\n\t\t// Sub type\n\t\tTYPE_INTEGER\t= 0x100\n\t};\n\t\nprivate:\n\n\t// Indent class\n\tstruct Primitive;\n\tstruct Compound;\n\tfriend Environment;\n\n\t// Type alias\n\tusing string = std::string;\n\tusing ostream = std::ostream;\n\tusing istream = std::istream;\n\tusing ostringstream = std::ostringstream;\n\tusing pair = std::pair<Variable, Variable>;\n\tusing cpp_rational = boost::multiprecision::cpp_rational;\n\tusing function = std::function<Variable(const Variable&, Environment&)>;\n\n\t// Optimization: constant pool\n\tstatic std::unordered_map<std::string, Variable> pool;\n\n\t// Type of variable\n\tType type;\n\n\t// Reference count\n\tint* refCount = nullptr;\n\n\t// Value of variable\n\tunion {\n\t\tcpp_rational*\trationalPtr;\n\t\tdouble*\t\tdoublePtr;\n\t\tstring*\t\tstringPtr;\n\t\tpair*\t\tpairPtr;\n\t\tvoid*\t\tvoidPtr;\n\t\tPrimitive*\tprimPtr;\n\t\tCompound*\tcompPtr;\n\t};\n\npublic:\n\n\t// Constructor for special\n\tVariable();\n\n\t// Constructor for rational\n\tVariable(const cpp_rational& rational);\n\n\t// Constructor for double\n\tVariable(double value);\n\n\t// Constructor for rational, double, string and symbol\n\tVariable(const string &str, Type type);\n\n\t// Constructor for pairs\n\tVariable(const Variable& lhs, const Variable& rhs);\n\n\t// Constructor for primitive procedure\n\tVariable(const string& name, const function& func);\n\n\t// Constructor for compound procedure\n\tVariable(const string& name, const Variable& args, const Variable& body, const Environment& env);\n\n\t// Copy constructor\n\tVariable(const Variable& var);\n\n\t// Destructor\n\t~Variable();\n\n\t// Swap two variables\n\tfriend void swap(Variable& lhs, Variable& rhs);\n\n\t// Assignment\n\tVariable& operator=(Variable var);\n\n\t// Optimization: constant pool\n\tstatic Variable createSymbol(const std::string& str);\n\n\t// Finalize value\n\tvoid finalize() const override;\n\n\t// Scan and tag value in using\n\tvoid scan(int tag) const override;\n\n\t// Standard I/O\n\tfriend ostream& operator<<(ostream& out, const Variable& var);\n\tfriend istream& operator>>(istream& in, Variable& var);\n\n\t// Require type, throw exception if type is wrong\n\tvoid requireType(const string &caller, Type type) const;\n\n\t// Get type name\n\tstatic string getTypeName(Type type);\n\n\t// Convert operations\n\tstring toString() const;\n\tdouble toDouble() const;\n\n\t// Check operations\n\tbool isNull() const;\n\tbool isVoid() const;\n\tbool isPair() const;\n\tbool isNumber() const;\n\tbool isInteger() const;\n\tbool isSymbol() const;\n\tbool isString() const;\n\tbool isPrim() const;\n\tbool isComp() const;\n\tbool isProcedure() const;\n\n\t// Arithmetic operations\n\tfriend Variable operator+(const Variable& lhs, const Variable& rhs);\n\tfriend Variable operator-(const Variable& lhs, const Variable& rhs);\n\tfriend Variable operator*(const Variable& lhs, const Variable& rhs);\n\tfriend Variable operator/(const Variable& lhs, const Variable& rhs);\n\tfriend Variable operator-(const Variable& var);\n\tfriend Variable remainder(const Variable& lhs, const Variable& rhs);\n\tfriend Variable quotient(const Variable& lhs, const Variable& rhs);\n\tfriend Variable gcd(const Variable& lhs, const Variable& rhs);\n\tbool isEven() const;\n\tbool isOdd() const;\n\n\t// Compare operations\n\tfriend bool operator<(const Variable& lhs, const Variable& rhs);\n\tfriend bool operator>(const Variable& lhs, const Variable& rhs);\n\tfriend bool operator<=(const Variable& lhs, const Variable& rhs);\n\tfriend bool operator>=(const Variable& lhs, const Variable& rhs);\n\tfriend bool operator==(const Variable& lhs, const Variable& rhs);\n\tfriend bool operator!=(const Variable& lhs, const Variable& rhs);\n\n\t// Pair operations\n\tVariable& car() const;\n\tVariable& cdr() const;\n\tVariable setCar(const Variable& var) const;\n\tVariable setCdr(const Variable& var) const;\n\n\t// Procedure operations\n\tVariable operator()(const Variable& arg, Environment& env) const;\n\tVariable& getProcedureArgs() const;\n\tVariable& getProcedureBody() const;\n\tstring getProcedureName() const;\n\tEnvironment getProcedureEnv() const;\n};\n\n// Primitive procedure\n\nstruct Variable::Primitive\n{\n\tstring name;\t// Name of procedure\n\tfunction func;\t// Function object\n\tPrimitive(const string& name, const function& func): name(name), func(func) {}\n};\n\n// Compound procedure\n\nstruct Variable::Compound\n{\n\tstring name;\t\t// Name of procedure\n\tVariable args, body;// Argument and body\n\tEnvironment env;\t// Closure\n\tCompound(const string& name, const Variable& args, const Variable& body, const Environment& env):\n\t\tname(name), args(args), body(body), env(env) {}\n};\n\n// Constant values\n\nextern const Variable VAR_NULL;\nextern const Variable VAR_VOID;\nextern const Variable VAR_TRUE;\nextern const Variable VAR_FALSE;\n", "meta": {"hexsha": "292f418d4f3a3dd8fcb4aa4c9e1a88df9944dedb", "size": 5251, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/variable.hpp", "max_stars_repo_name": "ZhangZhenghao/SimpleScheme", "max_stars_repo_head_hexsha": "844c8839fa30a5ef302dd86d1f6d45b37f2cbb13", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-11-06T08:04:35.000Z", "max_stars_repo_stars_event_max_datetime": "2017-07-21T02:22:56.000Z", "max_issues_repo_path": "src/variable.hpp", "max_issues_repo_name": "ZhangZhenghao/SimpleScheme", "max_issues_repo_head_hexsha": "844c8839fa30a5ef302dd86d1f6d45b37f2cbb13", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/variable.hpp", "max_forks_repo_name": "ZhangZhenghao/SimpleScheme", "max_forks_repo_head_hexsha": "844c8839fa30a5ef302dd86d1f6d45b37f2cbb13", "max_forks_repo_licenses": ["Apache-2.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.3671497585, "max_line_length": 98, "alphanum_fraction": 0.729575319, "num_tokens": 1290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.737158174177441, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.45068521915851745}}
{"text": "//  Copyright 2010 Vicente J. Botet Escriba\n//  Distributed under the Boost Software License, Version 1.0.\n//  See http://www.boost.org/LICENSE_1_0.txt\n\n// test ratio typedef's\n\n#include <boost/ratio/ratio.hpp>\n\n#if !defined(BOOST_NO_STATIC_ASSERT)\n#define NOTHING \"\"\n#endif\n\nBOOST_RATIO_STATIC_ASSERT(boost::atto::num == 1 && boost::atto::den == 1000000000000000000ULL, NOTHING, (boost::mpl::integral_c<boost::intmax_t,boost::atto::den>));\nBOOST_RATIO_STATIC_ASSERT(boost::femto::num == 1 && boost::femto::den == 1000000000000000ULL, NOTHING, ());\nBOOST_RATIO_STATIC_ASSERT(boost::pico::num == 1 && boost::pico::den == 1000000000000ULL, NOTHING, ());\nBOOST_RATIO_STATIC_ASSERT(boost::nano::num == 1 && boost::nano::den == 1000000000ULL, NOTHING, ());\nBOOST_RATIO_STATIC_ASSERT(boost::micro::num == 1 && boost::micro::den == 1000000ULL, NOTHING, ());\nBOOST_RATIO_STATIC_ASSERT(boost::milli::num == 1 && boost::milli::den == 1000ULL, NOTHING, ());\nBOOST_RATIO_STATIC_ASSERT(boost::centi::num == 1 && boost::centi::den == 100ULL, NOTHING, ());\nBOOST_RATIO_STATIC_ASSERT(boost::deci::num == 1 && boost::deci::den == 10ULL, NOTHING, ());\nBOOST_RATIO_STATIC_ASSERT(boost::deca::num == 10ULL && boost::deca::den == 1, NOTHING, (boost::mpl::integral_c<boost::intmax_t,boost::deca::den>));\nBOOST_RATIO_STATIC_ASSERT(boost::hecto::num == 100ULL && boost::hecto::den == 1, NOTHING, ());\nBOOST_RATIO_STATIC_ASSERT(boost::kilo::num == 1000ULL && boost::kilo::den == 1, NOTHING, ());\nBOOST_RATIO_STATIC_ASSERT(boost::mega::num == 1000000ULL && boost::mega::den == 1, NOTHING, ());\nBOOST_RATIO_STATIC_ASSERT(boost::giga::num == 1000000000ULL && boost::giga::den == 1, NOTHING, ());\nBOOST_RATIO_STATIC_ASSERT(boost::tera::num == 1000000000000ULL && boost::tera::den == 1, NOTHING, ());\nBOOST_RATIO_STATIC_ASSERT(boost::peta::num == 1000000000000000ULL && boost::peta::den == 1, NOTHING, ());\nBOOST_RATIO_STATIC_ASSERT(boost::exa::num == 1000000000000000000ULL && boost::exa::den == 1, NOTHING, ());\n\n", "meta": {"hexsha": "f59252b89fef8ec6039120cc05de15d8283f7bb4", "size": 1985, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/ratio/test/typedefs_pass.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-01-03T23:52:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-22T17:41:27.000Z", "max_issues_repo_path": "boost/libs/ratio/test/typedefs_pass.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-01-17T10:11:43.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-17T10:11:43.000Z", "max_forks_repo_path": "boost/libs/ratio/test/typedefs_pass.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-11-08T01:56:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-21T09:02:49.000Z", "avg_line_length": 66.1666666667, "max_line_length": 164, "alphanum_fraction": 0.7083123426, "num_tokens": 598, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.737158174177441, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.45068521915851734}}
{"text": "// --------------------------------------------------------------------------\n//                   OpenMS -- Open-Source Mass Spectrometry\n// --------------------------------------------------------------------------\n// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,\n// ETH Zurich, and Freie Universitaet Berlin 2002-2017.\n//\n// This software is released under a three-clause BSD license:\n//  * Redistributions of source code must retain the above copyright\n//    notice, this list of conditions and the following disclaimer.\n//  * Redistributions in binary form must reproduce the above copyright\n//    notice, this list of conditions and the following disclaimer in the\n//    documentation and/or other materials provided with the distribution.\n//  * Neither the name of any author or any participating institution\n//    may be used to endorse or promote products derived from this software\n//    without specific prior written permission.\n// For a full list of authors, refer to the file AUTHORS.\n// --------------------------------------------------------------------------\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL ANY OF THE AUTHORS OR THE CONTRIBUTING\n// INSTITUTIONS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// --------------------------------------------------------------------------\n// $Maintainer: Chris Bielow $\n// $Authors: Andreas Bertsch, Chris Bielow $\n// --------------------------------------------------------------------------\n//\n\n#include <OpenMS/MATH/STATISTICS/GaussFitter.h>\n\n#include <boost/math/distributions/normal.hpp>\n#include <unsupported/Eigen/NonLinearOptimization>\n\nusing namespace std;\n\n// #define GAUSS_FITTER_VERBOSE\n// #undef  GAUSS_FITTER_VERBOSE\n\nnamespace OpenMS\n{\n  namespace Math\n  {\n    GaussFitter::GaussFitter()\n    : init_param_(0.06, 3.0, 0.5)\n    {\n    }\n\n    GaussFitter::~GaussFitter()\n    {\n    }\n\n    void GaussFitter::setInitialParameters(const GaussFitResult & param)\n    {\n      init_param_ = param;\n    }\n\n    struct GaussFunctor\n    {\n      int inputs() const { return m_inputs; }\n      int values() const { return m_values; }\n\n      GaussFunctor(int dimensions, const std::vector<DPosition<2> >* data)\n      : m_inputs(dimensions), \n        m_values(static_cast<int>(data->size())),\n        m_data(data)\n      {}\n\n      int operator()(const Eigen::VectorXd &x, Eigen::VectorXd &fvec) const\n      {\n        const double A = x(0);\n        const double x0 = x(1);\n        const double sig = x(2);\n        const double sig2 = 2 * sig * sig;\n\n        UInt i = 0;\n        for (std::vector<DPosition<2> >::const_iterator it = m_data->begin(); it != m_data->end(); ++it, ++i)\n        {\n          fvec(i) = A * std::exp(- (it->getX() - x0) * (it->getX() - x0) / sig2) - it->getY();\n        }\n\n        return 0;\n      }\n      // compute Jacobian matrix for the different parameters\n      int df(const Eigen::VectorXd &x, Eigen::MatrixXd &J) const\n      {\n        const double A = x(0);\n        const double x0 = x(1);\n        const double sig = x(2);\n        const double sig2 = 2 * sig * sig;\n        const double sig3 = 2 * sig2 * sig;\n\n        UInt i = 0;\n        for (std::vector<DPosition<2> >::const_iterator it = m_data->begin(); it != m_data->end(); ++it, ++i)\n        {\n          const double xd = (it->getX() - x0);\n          const double xd2 = xd*xd;\n          double j0 = std::exp(-1.0 * xd2 / sig2);\n          J(i,0) = j0;\n          J(i,1) = (A * j0 * (-(-2 * it->getX() + 2.0 * x0) / sig2));\n          J(i,2) = (A * j0 * (xd2 / sig3));\n        }\n        return 0;\n      }\n\n      const int m_inputs, m_values;\n      const std::vector<DPosition<2> >* m_data;\n    };\n\n    GaussFitter::GaussFitResult GaussFitter::fit(vector<DPosition<2> > & input) const\n    {\n      Eigen::VectorXd x_init (3);\n      x_init(0) = init_param_.A;\n      x_init(1) = init_param_.x0;\n      x_init(2) = init_param_.sigma;\n      GaussFunctor functor (3, &input);\n      Eigen::LevenbergMarquardt<GaussFunctor> lmSolver (functor);\n      Eigen::LevenbergMarquardtSpace::Status status = lmSolver.minimize(x_init);\n\n      // the states are poorly documented. after checking the source and\n      // http://www.ultimatepp.org/reference%24Eigen_demo%24en-us.html we believe that\n      // all states except TooManyFunctionEvaluation and ImproperInputParameters are good\n      // termination states.\n      if (status == Eigen::LevenbergMarquardtSpace::ImproperInputParameters ||\n          status == Eigen::LevenbergMarquardtSpace::TooManyFunctionEvaluation)\n      {\n          throw Exception::UnableToFit(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, \"UnableToFit-GaussFitter\", \"Could not fit the Gaussian to the data: Error \" + String(status));\n      }\n      \n      x_init(2) = fabs(x_init(2)); // sigma can be negative, but |sigma| would actually be the correct solution\n\n#ifdef GAUSS_FITTER_VERBOSE\n      std::stringstream formula;\n      formula << \"f(x)=\" << result.A << \" * exp(-(x - \" << result.x0 << \") ** 2 / 2 / (\" << result.sigma << \") ** 2)\";\n      std::cout << formular.str() << std::endl;\n#endif\n      \n      return GaussFitResult (x_init(0), x_init(1), x_init(2));\n    }\n\n    // static\n    std::vector<double> GaussFitter::eval(const std::vector<double>& evaluation_points, const GaussFitter::GaussFitResult& model)\n    {\n      std::vector<double> out;\n      out.reserve(evaluation_points.size());\n      boost::math::normal_distribution<> ndf(model.x0, model.sigma);\n      double int0 = model.A / boost::math::pdf(ndf, model.x0); // intensity normalization factor of the max @ x0 (simply multiplying the CDF with A is wrong!)\n      for (Size i = 0; i < evaluation_points.size(); ++i)\n      {\n        out.push_back(boost::math::pdf(ndf, evaluation_points[i]) * int0 );\n      }\n      return out;\n    }\n\n  }   //namespace Math\n} // namespace OpenMS\n", "meta": {"hexsha": "b4cf36d165d84550935c6658df5696b55da50124", "size": 6471, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/openms/source/MATH/STATISTICS/GaussFitter.cpp", "max_stars_repo_name": "raghav17083/OpenMS", "max_stars_repo_head_hexsha": "ddcdd3068a93a7c415675c39bac43d796a845f1d", "max_stars_repo_licenses": ["BSL-1.0", "Apache-2.0", "Zlib"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/openms/source/MATH/STATISTICS/GaussFitter.cpp", "max_issues_repo_name": "raghav17083/OpenMS", "max_issues_repo_head_hexsha": "ddcdd3068a93a7c415675c39bac43d796a845f1d", "max_issues_repo_licenses": ["BSL-1.0", "Apache-2.0", "Zlib"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/openms/source/MATH/STATISTICS/GaussFitter.cpp", "max_forks_repo_name": "raghav17083/OpenMS", "max_forks_repo_head_hexsha": "ddcdd3068a93a7c415675c39bac43d796a845f1d", "max_forks_repo_licenses": ["BSL-1.0", "Apache-2.0", "Zlib"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.6993865031, "max_line_length": 177, "alphanum_fraction": 0.6057796322, "num_tokens": 1598, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4506852120978152}}
{"text": "#ifndef _WORD2VEC_H\n#define _WORD2VEC_H\n\n#define MAX_STRING 100\n#define EXP_TABLE_SIZE 1000\n#define MAX_EXP 6\n#define MAX_SENTENCE_LENGTH 1000\n#define MAX_CODE_LENGTH 40\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <pthread.h>\n#include <Eigen/Dense>\n#include <Eigen/Core>\n#include <iostream>\n#include <thread>\n#include <vector>\n#include \"IEmbeddingModel.hpp\"\n\nusing namespace Eigen;\nusing namespace std;\n\n//typedef float real;\n\nstruct vocab_word {\n  long long cn;\n  int *point;\n  char *word, *code, codelen;\n};\n\n\nclass Word2Vec: public IEmbeddingModel\n{\n  private:\n\n    // internal parameters\n    const int vocab_hash_size = 30000000;  // Maximum 30 * 0.7 = 21M words in the vocabulary\n    int *vocab_hash;\n    float starting_alpha;\n    \n    const int table_size = 1e8;\n    int *table;\n    clock_t start;\n    bool read_vocab_flag;\n\n    //adjustable params\n    char train_file[MAX_STRING];\n    int cbow = 1, debug_mode = 2, window = 5, min_count = 1, num_threads = 10, min_reduce = 1;\n    long long vocab_max_size = 100000, layer1_size = 50;\n    long long train_words = 0, word_count_actual = 0, iter = 1, file_size = 0, classes = 0;\n    float alpha = 0.025, sample = 1e-3;\n    int hs = 0, negative = 5;\n  \n  protected:\n    struct vocab_word *vocab;\n    float *syn0, *syn1, *syn1neg, *expTable;\n    long long vocab_size = 0;\n  \n  public:\n    Word2Vec(char* _train_file);\n    ~Word2Vec();\n    //native functions\n    int AddWordToVocab(char *word);\n    int ArgPos(char* str,int argc, char** argv);\n    void CreateBinaryTree();\n    void InitNet();\n    void InitUnigramTable();\n    void LearnVocabFromTrainFile();\n    void ReadWord(char* word,FILE* fin);\n    int ReadWordIndex(FILE* fin);\n    void ReduceVocab();\n    int GetWordHash(char *word);\n    int SearchVocab(char* word);\n    void SortVocab();\n    //void *TrainModelThread(void* id);\n    void TrainModelThread(int id);\n    friend int VocabCompare(const void*a, const void* b);\n\n    void GetVocab(vector<string> &vocabulary) override;\n    void GetEmbeddingMatrix(MatrixXf &Embeddings) override;\n    void GetEmbeddingMatrix(vector<VectorXf> &Embeddings) override;\n\n    void clear_mem();\n    void word2vecStandartInit();    \n    //modified function\n    void TrainModel();\n    void SaveVocab(char * save_vocab_file);\n    void ReadVocab(char * read_vocab_file);\n};\n\n#endif", "meta": {"hexsha": "99797db822cc2e24f5f097533ea12147ca4b92e4", "size": 2361, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "word2vec.hpp", "max_stars_repo_name": "Astromis/tinyEmbeddingsEngine", "max_stars_repo_head_hexsha": "fea1beb7b3fd32640f788209f79cc47312a20efb", "max_stars_repo_licenses": ["MIT"], "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.hpp", "max_issues_repo_name": "Astromis/tinyEmbeddingsEngine", "max_issues_repo_head_hexsha": "fea1beb7b3fd32640f788209f79cc47312a20efb", "max_issues_repo_licenses": ["MIT"], "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.hpp", "max_forks_repo_name": "Astromis/tinyEmbeddingsEngine", "max_forks_repo_head_hexsha": "fea1beb7b3fd32640f788209f79cc47312a20efb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-28T09:38:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-28T09:38:52.000Z", "avg_line_length": 25.3870967742, "max_line_length": 94, "alphanum_fraction": 0.6895383312, "num_tokens": 661, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4506852120978152}}
{"text": "#include <Eigen/Core>\n#include <mpi.h> // has to be before plasma\n#ifdef USE_MKL\n#include <mkl_cblas.h>\n#include <mkl_lapacke.h>\n#else\n#include <cblas.h>\n#include <lapacke.h>\n#endif\n#ifdef USE_PLASMA\n#include \"coreblas_.h\" // plasma\n#endif\n#include <fstream>\n#include <array>\n#include <random>\n#include <mutex>\n#include <iostream>\n#include <map>\n#include <tuple>\n#include <unordered_map>\n\n\n#include \"tasktorrent/tasktorrent.hpp\"\n#include \"util_shared.hpp\"\n\n// #define DISP\n\n\nusing namespace std;\nusing namespace Eigen;\nusing namespace ttor;\n\ntypedef array<int, 2> int2;\ntypedef array<int, 3> int3;\ntypedef array<int, 4> int4;\ntypedef array<int, 5> int5;\ntypedef array<int, 6> int6;\ntypedef array<int, 7> int7;\n\n\nint VERB = 0;\nbool LOG = false;\nbool TEST = true;\nint n_threads_ = 2;\nint n_ = 2;\nint M_ = 5;\nint N_ = 4;\nint p_ = 1;\nint q_ = 1;\nint t_ = M_/2;\n\n\nstruct hashfunc{\n    size_t operator() (const int2 &i) const{\n        return hash<int>{}(i[0]) ^ hash<int>{}(i[1]);\n    }\n};\n\nint denseQR(int n_threads, int n, int M, int N, int p, int q, int t)\n{\n    // MPI info\n    const int rank = comm_rank();\n    const int nranks = comm_size();\n    if(VERB) printf(\"[%d] Hello from %s\\n\", comm_rank(), processor_name().c_str());\n\n    assert(p * q == nranks);\n    assert(p >= 1);\n    assert(q >= 1);\n\n    int origin = 0; // Not necessary -- origin is always 0\n    int nb = min(32, n); // inner blocking size \n\n    // cout << t << endl;\n\n    // Warmup MKL\n    warmup_mkl(n_threads);\n\n    // Mapper\n    auto block2rank = [&](int2 ij, int3 pqt, int origin){\n        int i = ij[0];\n        int j = ij[1];\n        int p = pqt[0];\n        int q = pqt[1];\n        int t = pqt[2];\n\n        int ii = i % p;\n        int jj = j % q;\n        int r = (ii + jj * p + origin) % nranks; // want the (0,0) block to be in origin rank\n        assert(r <= nranks);\n        return r;\n    };\n\n    auto block2thread = [&](int2 ij, int3 pqt){\n        int i = ij[0];\n        int j = ij[1];\n        int p = pqt[0];\n        int q = pqt[1];\n        int t = pqt[2];\n\n        int ii = i / p;\n        int jj = j / q;\n        \n        int num_blocksit = M/p;\n        int r = (ii + jj * num_blocksit) % n_threads; \n        return r;\n    };\n\n    VectorXd x;\n    VectorXd b;\n    VectorXd bref;\n\n    // Block the matrix for every node\n    vector<MatrixXd> Mat(M*N, MatrixXd::Zero(0,0));\n    int tri_size = (N*(2*M-N+1))/2;\n    vector<MatrixXd> TS(tri_size, MatrixXd::Zero(0,0)); // To store triangular factors obtained from TSQRT\n    vector<MatrixXd> TT(tri_size, MatrixXd::Zero(0,0)); // To store triangular factors obtained from TTQRT \n\n    #ifdef USE_PLASMA\n    vector<VectorXd> tau(tri_size, VectorXd::Zero(0)); // If PLASMA is used\n    vector<VectorXd> work(M*N, VectorXd::Zero(0)); // If PLASMA is used\n    #endif\n\n    MatrixXd A = MatrixXd::Zero(0,0);\n    auto val = [&](int i, int j) { return 1/(double)((i-j)*(i-j)+1); };\n    auto val_vec = [&](int i) {return 1/(double)(i*i+1);};\n\n    \n    if (TEST){\n        A = MatrixXd::NullaryExpr(M*n,N*n, val);\n        \n        if(rank == 0) {\n            x = VectorXd::NullaryExpr(N*n, val_vec);\n            b = A*x;\n            bref = b;\n            if (VERB){\n                cout << A << endl;\n                cout << b << endl;\n            }\n        }\n    }\n\n    // Setup and factorize\n    {\n        // Setup the matrix blocks and workspace\n        {\n            Communicator comm(MPI_COMM_WORLD, VERB);\n\n            // Threadpool\n            Threadpool tp(n_threads, &comm, VERB, \"[\" + to_string(rank) + \"]_\");\n            Taskflow<int2> setup_tf(&tp, VERB); // Set up the matrix block {i,j} and the workspace required\n\n\n            setup_tf.set_mapping([&] (int2 ij){\n                    return block2thread(ij,{p,q,t}); // should be the same mapping as dgeqrt and dtsqrt\n                })\n                .set_indegree([](int2){\n                    return 1;\n                })\n                .set_task([&] (int2 ij) {\n                    int i=ij[0];\n                    int j=ij[1];\n                    auto val_loc = [&](int ii, int jj) {return val(i+ii, j+jj);};\n                    if (TEST) Mat.at(i+j*M) = A.block(i*n, j*n, n, n);\n                    else Mat.at(i+j*M) = MatrixXd::NullaryExpr(n,n,val_loc);\n                    if (i>=j) {\n                        TS.at(i-(j*(j+1))/2+j*M) = MatrixXd::Zero(n,n);\n                        TT.at(i-(j*(j+1))/2+j*M) = MatrixXd::Zero(0,0);\n\n                        #ifdef USE_PLASMA\n                            tau.at(i-(j*(j+1))/2+j*M) = VectorXd::Zero(n);\n                        #endif\n                    }\n                    #ifdef USE_PLASMA\n                        work.at(i+j*M) = VectorXd::Zero(n*nb);\n                    #endif\n                })\n                .set_name([](int2 ij) {\n                    return \"setup_\" + to_string(ij[0]) + \"_\" +to_string(ij[1]);\n                })\n                .set_priority([&](int2) {\n                    return 6;\n                });\n\n            MPI_Barrier(MPI_COMM_WORLD);\n            timer t0 = wctime();\n            for (int j=0; j<N; ++j){\n                for (int i=0; i<M; ++i){\n                    if(block2rank({i,j}, {p,q,t}, origin) == rank) {\n                        setup_tf.fulfill_promise({i,j});\n                    }\n                }\n            }\n            tp.join();\n            timer t1 = wctime();\n            MPI_Barrier(MPI_COMM_WORLD);\n            if(VERB && rank == 0)\n            {\n                cout << \"Time to setup: \" << elapsed(t0, t1) << endl;\n            }\n        }\n\n        // Initialize the communicator structure\n        Communicator comm(MPI_COMM_WORLD, VERB);\n\n        // Threadpool\n        Threadpool tp(n_threads, &comm, VERB, \"[\" + to_string(rank) + \"]_\");\n        Taskflow<int2> dgeqrt_tf(&tp, VERB);  // A[k,k] = QR\n        Taskflow<int3> dtsqrt_tf(&tp, VERB);\n        Taskflow<int3> dlarfb_tf(&tp, VERB);\n        Taskflow<int4> dssrfb_tf(&tp, VERB);\n        Taskflow<int6> dttqrt_tf(&tp, VERB);\n        Taskflow<int7> dttssmqr_tf(&tp, VERB);\n\n        // Log\n        DepsLogger dlog(1000000);\n        Logger log(1000000);\n        if(LOG) {\n            tp.set_logger(&log);\n            comm.set_logger(&log);\n        }\n\n        // Active messages\n        // From dgeqrt\n        auto am_dgeqrt_2_dlarfb = comm.make_active_msg(\n            [&](view<double> &V, view<double> &tau, view<int>& js, int& i, int& j){\n                if (Mat.at(i+j*M).rows()>0){\n                    Mat.at(i+j*M).triangularView<StrictlyLower>() = Map<MatrixXd>(V.data(), n, n).triangularView<StrictlyLower>(); \n                }\n                else {\n                    Mat.at(i+j*M)=Map<MatrixXd>(V.data(), n, n).triangularView<StrictlyLower>();\n                }\n                TS.at(i-(j*(j+1))/2+j*M) = Map<MatrixXd>(tau.data(), n, n); \n                for (auto& jinc: js){\n                    dlarfb_tf.fulfill_promise({i,j,jinc});\n                }\n            }\n        );\n\n        /* Can come from dgeqrt or dtsqrt */\n        auto firstMerge = [&](int i, int j){\n            int domain_index = i/t; // adjust for which column is being operated on\n            int domain_start = max(j,domain_index*t);\n\n            int it = (i-domain_start)/p; // to adjust for which column in which domain is being operated on\n            int itp = (i-domain_start)%p; \n            int stride = n_threads*p;\n\n            if (it%2 == 1){ // Merge within the node -- definitely possible since there should be an \"i\" s.t it=0\n                int iprev = i-p;\n                assert(block2rank({iprev,j},{p,q,t},origin)==rank);\n                dttqrt_tf.fulfill_promise({j,iprev,i,1,0,0}); // first merge \n            }\n            else { // Wait here -- merge within a node //if (i+p<j+stride)\n                assert(it%2==0);\n                dttqrt_tf.fulfill_promise({j,i,i+p,1,0,0});\n            }\n        };\n\n        dgeqrt_tf.set_mapping([&] (int2 ij){\n                return block2thread(ij,{p,q,t}); \n            })\n            .set_indegree([](int2){\n                return 1;\n            })\n            .set_task([&] (int2 ij) {\n                int i = ij[0];\n                int j = ij[1];\n                \n                #ifdef USE_PLASMA\n                int info = CORE_dgeqrt(n, n, nb,\n                                       Mat.at(i+j*M).data(), n, \n                                       TS.at(i-(j*(j+1))/2+j*M).data(), n,\n                                       tau.at(i-(j*(j+1))/2+j*M).data(),\n                                       work.at(i+j*M).data());\n                #else\n                int info = LAPACKE_dgeqrt(LAPACK_COL_MAJOR, n, n, n, // don't use nb here because of dlarfb next step\n                                          Mat.at(i+j*M).data(), n, \n                                          TS.at(i-(j*(j+1))/2+j*M).data(), n);\n                #endif\n                assert(info == 0);\n                \n                #ifdef DISP\n                    cout << \"geqrt_\" + to_string(ij[0]) + \"_\" +to_string(ij[1]) << endl;\n                #endif\n            })\n            .set_fulfill([&](int2 ij) {\n                int i = ij[0];\n                int j = ij[1];\n                // Dependencies -- dlarfb \n                map<int, vector<int>> to_fulfill;\n\n                for(int jinc = j+1; jinc<N; jinc++) { // A[i][jinc] blocks\n                    int r = block2rank({i,jinc},{p,q,t}, origin);\n                    if(to_fulfill.count(r) == 0) {\n                        to_fulfill[r] = {jinc};\n                    } else {\n                        to_fulfill[r].push_back(jinc);\n                    }\n                }\n\n                int domain_index=i/t;\n                int domain_end=min(domain_index*t+t,M);\n                \n                int stride = n_threads*p;\n                if (i+stride<domain_end){ // First dtsqrt will be at +stride distance\n                    int r = block2rank({i+stride,j},{p,q,t},origin); // i+stride will always be in the same rank\n                    assert(r == rank);\n                    dtsqrt_tf.fulfill_promise({i, i+stride, j}); // root row = i\n                }\n                else  { // merge\n                    firstMerge(i,j);\n                }\n\n                // Send data and trigger tasks -- dlarfb\n                for (auto& p: to_fulfill){\n                    int r = p.first; // rank\n                    if (r == rank){\n                        for(auto& jinc: p.second){\n                            dlarfb_tf.fulfill_promise({i, j, jinc}); \n                        }\n                    }\n                    else {\n                        auto V_ij = view<double>(Mat.at(i+j*M).data(), n * n );\n                        auto T_ij = view<double>(TS.at(i-(j*(j+1))/2+j*M).data(), n*n);\n                        auto jsv = view<int>(p.second.data(), p.second.size());\n                        am_dgeqrt_2_dlarfb->send(r, V_ij, T_ij, jsv, i, j);\n                    }\n                }\n\n            })\n            .set_name([](int2 ij) {\n                return \"geqrt_\" + to_string(ij[0]) + \"_\" +to_string(ij[1]);\n            })\n            .set_priority([&](int2 ij) {\n                return 5+ (N-ij[1]); // Include column index in the priority\n            });\n\n\n        // From dtsqrt \n        auto am_dtsqrt_2_dssrfb = comm.make_active_msg(\n            [&](view<double> &V_ij, view<double> &T_ij, int& root, int& j, int& i, view<int>& js){\n                Mat.at(i+j*M)=Map<MatrixXd>(V_ij.data(), n, n);\n                TS.at(i-(j*(j+1))/2+j*M) = Map<MatrixXd>(T_ij.data(), n, n); \n                for(auto& jinc: js){ \n                    dssrfb_tf.fulfill_promise({root, j, i, jinc}); \n                }\n            }\n        );\n\n        dtsqrt_tf.set_mapping([&] (int3 rij){\n               return block2thread({rij[1],rij[2]},{p,q,t});\n            })\n            .set_indegree([](int3 rij){\n                if (rij[2]==0) return 1; // Tiles in column 0\n                return 2;\n            })\n            .set_task([&] (int3 rij) {\n                int root = rij[0]; // root row -- which row is doing the dgeqrt\n                int i = rij[1]; // row to do dtsqrt\n                int j = rij[2]; // col to do dtsqrt\n                #ifdef USE_PLASMA\n                int info = CORE_dtsqrt(n, n, nb,\n                                       Mat.at(root+j*M).data(), n,\n                                       Mat.at(i+j*M).data(), n, \n                                       TS.at(i-(j*(j+1))/2+j*M).data(), n,\n                                       tau.at(i-(j*(j+1))/2+j*M).data(), \n                                       work.at(i+j*M).data());\n                #else\n                int info = LAPACKE_dtpqrt(LAPACK_COL_MAJOR, n, n, 0, nb,\n                                         Mat.at(root+j*M).data(), n,\n                                         Mat.at(i+j*M).data(), n, \n                                         TS.at(i-(j*(j+1))/2+j*M).data(), n);\n                assert(info == 0);\n                #endif\n                #ifdef DISP\n                    cout << \"tsqrt_\" + to_string(rij[0]) + \"_\" + \n                            to_string(rij[1]) + \"_\" +to_string(rij[2]) << endl;\n                #endif\n            })\n            .set_fulfill([&](int3 rij) {\n                int root = rij[0]; // root row -- which row is doing the dgeqrt\n                int i = rij[1]; // row to do dtsqrt\n                int j = rij[2]; // col to do dtsqrt\n                // Dependencies \n                map<int, vector<int>> to_fulfill;\n\n                int domain_index=i/t;\n                int domain_end=min(domain_index*t+t,M);\n                \n                int stride = n_threads*p;\n                if (i+stride<domain_end){ \n                    int r = block2rank({i+stride,j},{p,q,t},origin);\n                    assert(r == rank);\n                    dtsqrt_tf.fulfill_promise({root, i+stride, j}); // Next dtsqrt\n                }\n                else {// last dtsqrt -- trigger merging\n                    firstMerge(root,j);\n                }\n\n                // dssrfb\n                for(int jinc = j+1; jinc<N; jinc++) { \n                    int r = block2rank({i,jinc},{p,q,t},origin); // ssrfb\n                    if(to_fulfill.count(r) == 0) {\n                        to_fulfill[r] = {jinc};\n                    } else {\n                        to_fulfill[r].push_back(jinc);\n                    }\n                }\n\n                // Send data and trigger tasks\n                for (auto& p: to_fulfill){\n                    int r = p.first; // rank\n                    if (r == rank){\n                        for(auto& jinc: p.second){\n                            dssrfb_tf.fulfill_promise({root, j, i, jinc}); \n                        }\n                    }\n                    else {\n                        auto V_ij = view<double>(Mat.at(i+j*M).data(), n * n );\n                        auto T_ij = view<double>(TS.at(i-(j*(j+1))/2+j*M).data(), n*n);\n                        auto jsv = view<int>(p.second.data(), p.second.size());\n\n                        am_dtsqrt_2_dssrfb->send(r, V_ij, T_ij, root, j, i, jsv);\n                    }\n                }\n\n            })\n            .set_name([](int3 rij) {\n                return \"dtsqrt_\" + to_string(rij[0]) + \"_\" +to_string(rij[1]) + \"_\" +to_string(rij[2]);\n            })\n            .set_priority([&](int3 rij) {\n                return 4+(N-rij[2]);\n            });\n\n\n        /* Can come from dgeqrt or dtsqrt */\n        auto firstMergeUpdate = [&](int i, int j, int k){\n            int domain_index = i/t; \n            int domain_start = max(k,domain_index*t); // adjust for which column is being operated on\n\n            // Which dttssmqr to trigger?\n            int it = (i-domain_start)/p;\n            int itp = (i-domain_start)%p; \n            int stride = n_threads*p;\n\n            if (it%2 == 1){// Merge update within a node\n                int r = block2rank({i-p,j}, {p,q,t},origin);\n                assert(r == rank);\n                dttssmqr_tf.fulfill_promise({k, i-p,i, j, 1,0,0});\n            }\n            else  {// wait here -- merge update within a node //if (i+p<k+stride)\n                // i == k will always enter here \n                dttssmqr_tf.fulfill_promise({k, i,i+p, j, 1,0,0}); \n            }\n        };\n\n        // larfb\n        dlarfb_tf.set_mapping([&] (int3 ikj){\n               return block2thread({ikj[0],ikj[2]},{p,q,t});\n            })\n            .set_indegree([](int3 ikj){\n                if (ikj[1]==0) return 1; // Because of dgeqrt on column 0\n                return 2;\n            })\n            .set_task([&] (int3 ikj) {\n                int i=ikj[0]; // who is sending - row\n                int k=ikj[1]; // who is sending - col\n                int j=ikj[2]; // me - col, my row == i\n                #ifdef USE_PLASMA\n                int info = CORE_dormqr(PlasmaLeft,PlasmaTrans,n,n,n, nb,\n                                        Mat.at(i+k*M).data(), n, \n                                        TS.at(i-(k*(k+1))/2+k*M).data(), n,\n                                        Mat.at(i+j*M).data(), n,\n                                        work.at(i+j*M).data(), n);\n                #else\n                MatrixXd Vtemp = Mat.at(i+k*M); // Copying it because the diagonal entries are modified (but restored upon exit)\n                // Not copying might cause race conditions with the dttqrt opn received from the root col\n                int info = LAPACKE_dlarfb(LAPACK_COL_MAJOR, 'L', 'T', 'F', 'C', n, n, n,\n                                             Vtemp.data(), n, \n                                             TS.at(i-(k*(k+1))/2+k*M).data(), n,\n                                             Mat.at(i+j*M).data(), n);\n                assert(info == 0);\n                #endif\n\n                #ifdef DISP\n                cout << \"dlarfb_\" + to_string(ikj[0]) + \"_\" +to_string(ikj[1])  + \"_\" +to_string(ikj[2]) << endl;\n                #endif\n            })\n            .set_fulfill([&](int3 ikj) {\n                int i=ikj[0]; // who is sending - row\n                int k=ikj[1]; // who is sending - col\n                int j=ikj[2]; // me - col, my row == i\n                \n                int domain_index=i/t;\n                int domain_end=min(domain_index*t+t,M);\n                \n                int stride = n_threads*p;\n                if (i+stride<domain_end){ // and next row in the same tile\n                    int r = block2rank({i+stride, j},{p,q,t},origin);\n                    assert(r == rank);  \n                    dssrfb_tf.fulfill_promise({i, k, i+stride, j});\n                }\n                else  { // trigger merging\n                    firstMergeUpdate(i,j,k);\n                }\n            })\n            .set_name([](int3 ikj) {\n                return \"dlarfb_\" + to_string(ikj[0]) + \"_\" +to_string(ikj[1])  + \"_\" +to_string(ikj[2]);\n            })\n            .set_priority([&](int3 ikj) {\n                return 3+(N-ikj[1]);\n            });\n\n        dssrfb_tf.set_mapping([&] (int4 rjik){\n               return block2thread({rjik[2],rjik[3]},{p,q,t});\n            })\n            .set_indegree([](int4 rjik){\n                if (rjik[1]==0) return 2; // Because of dgeqrt and dtsqrt in column 0\n                return 3;\n            })\n            .set_task([&] (int4 rjik) {\n                int root = rjik[0];\n                int j = rjik[1];\n                int i = rjik[2];\n                int jinc = rjik[3];\n                #ifdef USE_PLASMA\n                int info = CORE_dtsmqr(PlasmaLeft,PlasmaTrans,n,n,n,n,n,nb,\n                                        Mat.at(root+jinc*M).data(), n,\n                                        Mat.at(i+jinc*M).data(), n,\n                                        Mat.at(i+j*M).data(), n,\n                                        TS.at(i-(j*(j+1))/2+j*M).data(), n,\n                                        work.at(i+jinc*M).data(), nb);\n                #else\n                int info = LAPACKE_dtpmqrt(LAPACK_COL_MAJOR, 'L', 'T', n, n, n, 0, nb, \n                                           Mat.at(i+j*M).data(), n,\n                                           TS.at(i-(j*(j+1))/2+j*M).data(), n,\n                                           Mat.at(root+jinc*M).data(), n,\n                                           Mat.at(i+jinc*M).data(), n);\n                #endif\n                assert(info == 0);\n                #ifdef DISP\n                cout << \"dssrfb_\" + to_string(rjik[0]) + \"_\" +to_string(rjik[1]) + \"_\" \n                        + to_string(rjik[2]) + \"_\" +to_string(rjik[3]) << endl;\n                #endif\n\n            })\n            .set_fulfill([&](int4 rjik) {\n                int root = rjik[0];\n                int j = rjik[1];\n                int i = rjik[2];\n                int jinc = rjik[3];\n\n                int stride = n_threads*p;\n                int domain_index=i/t;\n                int domain_end=min(domain_index*t+t,M);\n\n                if (i+stride<domain_end){\n                    int r = block2rank({i+stride,jinc},{p,q,t},origin);\n                    assert(r == rank);\n                    dssrfb_tf.fulfill_promise({root, j, i+stride, jinc});\n                }\n                else {\n                    firstMergeUpdate(root,jinc,j);\n                }\n\n                int jnext = j+1;\n                int domain_index_next = i/t;\n                int domain_start_next = max(jnext, domain_index*t);\n                // same rank\n                if (i<stride+domain_start_next){\n                    if (jinc==jnext){\n                        dgeqrt_tf.fulfill_promise({i, jinc});\n                    }\n                    else {\n                        dlarfb_tf.fulfill_promise({i, jnext, jinc});\n                    }\n                }\n                else {\n                    int root_next = (i-domain_start_next)%stride+domain_start_next;\n                    if (jinc==jnext){\n                        dtsqrt_tf.fulfill_promise({root_next, i, jinc}); \n                    }\n                    else {\n                        dssrfb_tf.fulfill_promise({root_next, jnext, i, jinc}); \n                    }\n                }\n            })\n            .set_name([](int4 rjik) {\n                return \"dssrfb_\" + to_string(rjik[0]) + \"_\" +to_string(rjik[1]) + \"_\" \n                        + to_string(rjik[2]) + \"_\" +to_string(rjik[3]);\n            })\n            .set_priority([&](int4 rjik) {\n                return 2+(N-rjik[1]);\n            });   \n\n        // From dttqrt\n        auto am_dttqrt_2_dttqrt = comm.make_active_msg(\n            [&](view<double> &R, int& j, int& k, int& m, int& l, int& lnode, int& ldomain){\n                if (Mat.at(m+j*M).rows() > 0){\n                    Mat.at(m+j*M).triangularView<Upper>() = Map<MatrixXd>(R.data(), n, n).triangularView<Upper>();\n                }\n                else {\n                    Mat.at(m+j*M) = Map<MatrixXd>(R.data(), n, n).triangularView<Upper>(); \n                }\n                // TT.at(m-(j*(j+1))/2+j*M) = MatrixXd::Zero(n,n); // Needed if TT is not resized before execution of dttqrt kernel\n                dttqrt_tf.fulfill_promise({j, k, m, l, lnode,ldomain});\n            }\n        );\n\n        // auto am_dttqrt_2_dttqrt_large = comm.make_large_active_msg( \n        //     [&](int& j, int& k, int& m, int& l, int& lnode, int& ldomain) {\n        //         dttqrt_tf.fulfill_promise({j, k, m, l, lnode,ldomain});\n        //     },\n        //     [&](int& j, int& k, int& m, int& l, int& lnode, int& ldomain) {\n        //         if (Mat.at(m+j*M).rows() > 0){\n        //         }\n        //         else {\n        //             Mat.at(m+j*M).resize(n,n);\n        //         }\n        //         return Mat.at(m+j*M).triangularView<Upper>();\n        //     },\n        //     [&](int& j, int& k, int& m, int& l, int& lnode, int& ldomain){\n        //         return;\n        //     });\n\n        auto am_dttqrt_2_dttssmqr = comm.make_active_msg(\n            [&](view<double> &Mat_mj, view<double> &TT_mj, int& j, int& k, int& m, view<int>& js, int& l, \n                int& lnode, int& ldomain){\n                if (Mat.at(m+j*M).rows() > 0){\n                    Mat.at(m+j*M).triangularView<Upper>() = Map<MatrixXd>(Mat_mj.data(), n, n).triangularView<Upper>();\n                }\n                else {\n                    Mat.at(m+j*M) = Map<MatrixXd>(Mat_mj.data(), n, n).triangularView<Upper>(); \n                }\n                TT.at(m-(j*(j+1))/2+j*M) = Map<MatrixXd>(TT_mj.data(), n, n); \n                for(auto& jinc: js){\n                    dttssmqr_tf.fulfill_promise({j,k,m,jinc,l,lnode,ldomain}); \n                }\n            }\n        );\n\n        // Only needed to gather back on the same node\n        auto am_dttqrt = comm.make_active_msg(\n            [&](view<double> &Mat_mj, view<double> &TT_mj, int& m, int& j){\n                if (Mat.at(m+j*M).rows() > 0){\n                    Mat.at(m+j*M).triangularView<Upper>() = Map<MatrixXd>(Mat_mj.data(), n, n).triangularView<Upper>();\n                }\n                else {\n                    Mat.at(m+j*M) = Map<MatrixXd>(Mat_mj.data(), n, n).triangularView<Upper>(); \n                }\n                TT.at(m-(j*(j+1))/2+j*M) = Map<MatrixXd>(TT_mj.data(), n, n); \n            }\n        );  \n\n        dttqrt_tf.set_mapping([&] (int6 jkmlod){\n                return block2thread({jkmlod[1],jkmlod[0]},{p,q,t});\n            })\n            .set_indegree([&](int6 jkmlod){\n                int j = jkmlod[0]; // To identify colum j\n                int k = jkmlod[1]; // To identify block R_{kj}\n                int m = jkmlod[2]; // To identify block R_{mj}\n                int l = jkmlod[3]; // Level of merging within a node\n                int lnode = jkmlod[4]; // Level of merging between nodes\n                int ldomain = jkmlod[5]; // Level of merging between nodes\n\n                int stride = n_threads*p;\n                int domain_index=k/t;\n                int domain_start=max(j,domain_index*t);\n                int domain_end=min(domain_index*t+t,M);\n\n\n                // Check with valid merge within a node or between nodes or between domains\n                bool run = (lnode==0 && m<min(domain_start+stride,domain_end)) || \n                            (lnode>0 && m<min(domain_start+p,domain_end)) || \n                            (ldomain>0 && k==j && m%t==0) ;\n\n                if (run) return 2;\n                return 1;\n            })\n            .set_task([&] (int6 jkmlod) {\n                int j = jkmlod[0]; // To identify colum j\n                int k = jkmlod[1]; // To identify block R_{kj}\n                int m = jkmlod[2]; // To identify block R_{mj}\n                int l = jkmlod[3]; // Level of merging within a node\n                int lnode = jkmlod[4]; // Level of merging between nodes\n                int ldomain = jkmlod[5]; // Level of merging between domains\n\n                assert(k>=j); // Otherwise no TT[{k,j}] has been assigned\n                assert(m>=j); // Otherwise no TT[{m,j}] has been assigned\n                int stride = n_threads*p;\n                int domain_index=k/t;\n                int domain_start=max(j,domain_index*t);\n                int domain_end=min(domain_index*t+t,M);\n\n                bool run = (lnode==0 && m<min(domain_start+stride,domain_end)) || \n                            (lnode>0 && m<min(domain_start+p,domain_end)) || \n                            (ldomain>0 && k==j && m%t==0) ;\n\n                if (run){\n                    TT.at(m-(j*(j+1))/2+j*M) = MatrixXd::Zero(n,n); \n                    #ifdef USE_PLASMA\n                    int info = CORE_dttqrt(n, n, nb, Mat.at(k+j*M).data(), n,\n                                           Mat.at(m+j*M).data(), n, \n                                           TT.at(m-(j*(j+1))/2+j*M).data(), n,\n                                           tau.at(k-(j*(j+1))/2+j*M).data(), // use (k,j) space because this is on rank block2rank(k,j)\n                                           work.at(k+j*M).data()); // use (k,j) because the thread doing this task is block2thread(k,j)\n                    #else\n                    int info = LAPACKE_dtpqrt(LAPACK_COL_MAJOR, n, n, n, nb, \n                                              Mat.at(k+j*M).data(), n,\n                                              Mat.at(m+j*M).data(), n,\n                                              TT.at(m-(j*(j+1))/2+j*M).data(), n);                \n                    #endif\n                    assert(info == 0);\n                \n                #ifdef DISP\n                cout << \"ttqrt_\" +to_string(jkmlod[0]) + \"_\" +to_string(jkmlod[1])\n                        + \"_\" +to_string(jkmlod[2]) + \"_\" +to_string(jkmlod[3]) + \"_\" +to_string(jkmlod[4])\n                        + \"_\" +to_string(jkmlod[5]) << endl;\n                #endif\n                }\n            })\n            .set_fulfill([&](int6 jkmlod) {\n                int j = jkmlod[0]; // To identify colum j\n                int k = jkmlod[1]; // To identify block R_{kj}\n                int m = jkmlod[2]; // To identify block R_{mj}\n                int l = jkmlod[3]; // Level of merging within a node\n                int lnode = jkmlod[4]; // Level of merging between nodes\n                int ldomain = jkmlod[5]; // Level of merging between domains\n\n                // Next dttqrt\n                int domain_index=k/t;\n                int domain_start=max(j,domain_index*t);\n                int domain_end=min(domain_index*t+t,M);\n                int domain_size=domain_end-domain_start;\n                int rank_start = block2rank({domain_start,j},{p,q,t},origin);\n\n                int domain_left_rank = domain_size/p;\n                domain_left_rank = (rank-rank_start)<(domain_size%p)? domain_left_rank:domain_left_rank+1;\n\n                double l_limit_nodes = log2(min(p,domain_size));\n                double l_limit_threads = log2(min(n_threads,domain_left_rank));\n                double l_limit_domains = M/t-j/t-1;\n                int kt = (k-domain_start)/p; \n                int ktp = (k-domain_start)%p;\n\n                if (l < l_limit_threads){ // Merge within a node\n                    if ((int)(kt/pow(2,l))%2 == 1){\n                        int knext = k-pow(2,l)*p;\n                        int r =  block2rank({knext,j},{p,q,t},origin);\n                        assert(r==rank);\n                        dttqrt_tf.fulfill_promise({j,knext,k,l+1,lnode,ldomain});\n                    }\n                    else {\n                        // Merge with next and wait for info -- happens on the same rank\n                        int mnext = k+pow(2,l)*p;\n                        dttqrt_tf.fulfill_promise({j,k,mnext,l+1,lnode,ldomain});\n                    }\n                }\n                else if (lnode < l_limit_nodes){// Merge between nodes\n                    assert(k-domain_start<p);\n                    // once we enter here index \"l\" is not needed for future runs\n                    // to get uniformity between different nodes and domains set l to a high value = M\n                    int lt_next = M;\n                    if ((int)(ktp/pow(2,lnode))%2==1){\n                        int knext = k-pow(2,lnode);\n                        int r = block2rank({knext,j},{p,q,t},origin);\n                        assert(r!=rank);\n                        int lnext = lnode+1;\n                        // int R_kj_size = n*(n+1)/2;\n                        auto R_kj = view<double>(Mat.at(k+j*M).data(), n*n);\n\n                        am_dttqrt_2_dttqrt->send(r, R_kj,j,knext,k,lt_next,lnext,ldomain);\n                        // am_dttqrt_2_dttqrt_large->send_large(r, R_kj,j,knext,k,lt_next,lnext,ldomain);\n                    }\n                    else {\n                        // Merge with next and wait for info \n                        int mnext = k+pow(2,lnode);\n                        dttqrt_tf.fulfill_promise({j,k,mnext,lt_next,lnode+1,ldomain});\n                    }\n                }\n                else if (ldomain < l_limit_domains) { // Only after merging within and between nodes in a domain are done\n                    // Similarly l and lnode are not needed anymore\n                    int lt_next = M;\n                    int ln_next = M;\n\n                    // Flat tree to merge between domains\n                    if (ldomain>0 && k==j && m%t==0){\n                        // Atleast one step of merging between domains has been done\n                        int mnext = (m/t)*t+t; // First tile of next domain\n                        if (mnext<M){\n                            dttqrt_tf.fulfill_promise({j,k,mnext,lt_next,ln_next,ldomain+1}); // on the same rank\n                        }\n                    }\n                    else if (k==j){\n                        // First domain and start the fist step of merging between domains\n                        int mnext = (k/t)*t+t;\n                        if (mnext<M){\n                            dttqrt_tf.fulfill_promise({j,k,mnext,lt_next,ln_next,ldomain+1}); // on the same rank\n                        }\n                    }\n                    else if (k%t==0){\n                        // Not the first domain and trigger merging with the first domain\n                        int kprev = j; \n                        int r = block2rank({kprev,j},{p,q,t},origin);\n                        if (r==rank) dttqrt_tf.fulfill_promise({j,kprev,k,lt_next,ln_next,k/t-j/t}); \n                        else {\n                            // auto R_kj = view<double>(Mat.at(k+j*M).data(), n*n);\n                            int ldomain_next=k/t-j/t;\n                            // int R_kj_size = n*(n+1)/2;\n                            auto R_kj = view<double>(Mat.at(k+j*M).data(), n*n);\n\n                            am_dttqrt_2_dttqrt->send(r, R_kj,j,kprev,k,lt_next,ln_next,ldomain_next);\n\n                            // am_dttqrt_2_dttqrt_large->send_large(r, R_kj,j,kprev,k,lt_next,ln_next,ldomain_next);\n                        }\n                    }\n                }\n\n                int stride=n_threads*p;\n                bool run = (lnode==0 && m<min(domain_start+stride,domain_end)) || \n                            (lnode>0 && m<min(domain_start+p,domain_end)) || \n                            (ldomain>0 && k==j && m%t==0) ;\n\n                if (run){\n                    // Dependencies \n                    map<int, vector<int>> to_fulfill;\n                    // dttssmqr \n                    for(int jinc = j+1; jinc< N; jinc++) { // everything in the same row m\n                        // Which node to send Mat_{mj} and TT_{mj} data to? -- block2rank({k, jinc})\n                        int r = block2rank({k,jinc},{p,q,t},origin); \n                        if(to_fulfill.count(r) == 0) {\n                            to_fulfill[r] = {jinc};\n                        } else {\n                            to_fulfill[r].push_back(jinc);\n                        }\n                    }\n\n                    // Send data and trigger tasks\n                    for (auto& p: to_fulfill){\n                        int r = p.first; // rank\n                        if (r == rank){\n                            for(auto& jinc: p.second){\n                                dttssmqr_tf.fulfill_promise({j, k, m, jinc, l, lnode,ldomain}); \n                            }\n                        }\n                        else {\n                            auto Mat_mj = view<double>(Mat.at(m+j*M).data(), n*n );\n                            auto TT_mj = view<double>(TT.at(m-(j*(j+1))/2+j*M).data(), n*n);\n                            auto jsv = view<int>(p.second.data(), p.second.size());\n                            am_dttqrt_2_dttssmqr->send(r, Mat_mj, TT_mj, j, k, m, jsv, l, lnode, ldomain);\n                        }\n                    }\n\n                    // send a message to the rank of (m,j) so that it is easy to gather them on one node\n                    int rank_mj = block2rank({m,j},{p,q,t},origin);\n                    if (to_fulfill.count(rank_mj)==0){\n                        auto Mat_mj = view<double>(Mat.at(m+j*M).data(), n*n );\n                        auto TT_mj = view<double>(TT.at(m-(j*(j+1))/2+j*M).data(), n*n);\n                        am_dttqrt->send(rank_mj, Mat_mj, TT_mj,m,j);\n                    }\n                }\n            })\n            .set_name([](int6 jkmlod) {\n                return \"ttqrt_\" +to_string(jkmlod[0]) + \"_\" +to_string(jkmlod[1])\n                        + \"_\" +to_string(jkmlod[2]) + \"_\" +to_string(jkmlod[3]) + \"_\" +to_string(jkmlod[4])\n                        + \"_\" +to_string(jkmlod[5]);\n            })\n            .set_priority([&](int6 jkmlod) {\n                return 3+(N-jkmlod[0]);\n            });\n\n        //From dttsmqr\n        auto am_dttssmqr_2_dgeqrt = comm.make_active_msg(\n            [&](view<double> &R, int& i, int& j){\n                Mat.at(i+j*M) = Map<MatrixXd>(R.data(), n, n); // Check strides\n                dgeqrt_tf.fulfill_promise({i, j});\n            }\n        );\n\n        auto am_dttssmqr_2_dlarfb = comm.make_active_msg(\n            [&](view<double> &R, int& i, int& k, int& j){\n                Mat.at(i+j*M) = Map<MatrixXd>(R.data(), n, n); // Check strides\n                dlarfb_tf.fulfill_promise({i, k, j});\n            }\n        );\n\n        auto am_dttssmqr_2_dttssmqr = comm.make_active_msg(\n            [&](view<double> &R, int& j, int& k, int& m, int& jinc, int& l, int& lnode, int& ldomain){\n                Mat.at(m+jinc*M) = Map<MatrixXd>(R.data(), n, n); \n                dttssmqr_tf.fulfill_promise({j,k,m,jinc,l, lnode, ldomain});\n            }\n        );\n\n        dttssmqr_tf.set_mapping([&] (int7 jkmilod){\n                return block2thread({jkmilod[1],jkmilod[3]},{p,q,t});\n            })\n            .set_indegree([&](int7 jkmilod){ \n                int j = jkmilod[0]; // because of dttqrt between blocks {k, j} and {m, j}\n                int k = jkmilod[1]; // row k -- R_{k jinc}\n                int m = jkmilod[2]; // row m -- R_{m jinc}\n                int jinc = jkmilod[3]; // col jinc\n                int l = jkmilod[4]; // level of merging\n                int lnode = jkmilod[5]; // Level of merging between nodes\n                int ldomain = jkmilod[6]; // Level of merging between nodes\n\n\n                int stride = n_threads*p;\n                int domain_index=k/t;\n                int domain_start=max(j,domain_index*t);\n                int domain_end=min(domain_index*t+t,M);\n\n\n                // Check with valid merge within a node or between nodes or between domains\n                bool run = (lnode==0 && m<min(domain_start+stride,domain_end)) || \n                            (lnode>0 && m<min(domain_start+p,domain_end)) || \n                            (ldomain>0 && k==j && m%t==0) ;\n                if (run) return 3;\n                return 1;\n            })\n            .set_task([&] (int7 jkmilod) {\n                int j = jkmilod[0]; // because of dttqrt between blocks {k, j} and {m, j}\n                int k = jkmilod[1]; // row k -- R_{k jinc}\n                int m = jkmilod[2]; // row m -- R_{m jinc}\n                int jinc = jkmilod[3]; // col jinc\n                int l = jkmilod[4]; // level of merging\n                int lnode = jkmilod[5]; // Level of merging between nodes\n                int ldomain = jkmilod[6]; // Level of merging between domains\n\n                int stride = n_threads*p;\n                int domain_index=k/t;\n                int domain_start=max(j,domain_index*t);\n                int domain_end=min(domain_index*t+t,M);\n\n\n                // Check with valid merge within a node or between nodes or between domains\n                bool run = (lnode==0 && m<min(domain_start+stride,domain_end)) || \n                            (lnode>0 && m<min(domain_start+p,domain_end)) || \n                            (ldomain>0 && k==j && m%t==0) ;\n                if (run){\n                    #ifdef USE_PLASMA\n                    int info = CORE_dttmqr(PlasmaLeft,PlasmaTrans,n,n,n,n,n,nb,\n                                        Mat.at(k+jinc*M).data(), n,\n                                        Mat.at(m+jinc*M).data(), n,\n                                        Mat.at(m+j*M).data(), n,\n                                        TT.at(m-(j*(j+1))/2+j*M).data(), n,\n                                        work.at(k+jinc*M).data(), nb); // use (k,j) because the thread doing this task is block2thread(k,jinc)\n                    #else\n                    int info = LAPACKE_dtpmqrt(LAPACK_COL_MAJOR, 'L', 'T', n, n, n, n, nb, \n                                           Mat.at(m+j*M).data(), n,\n                                           TT.at(m-(j*(j+1))/2+j*M).data(), n,\n                                           Mat.at(k+jinc*M).data(), n, // Receives this from dssrfb or dttssmqr\n                                           Mat.at(m+jinc*M).data(), n); \n                    #endif\n                    assert(info == 0);\n                \n                #ifdef DISP\n                cout << \"ttssmqr_\" + to_string(jkmilod[0]) + \"_\" +to_string(jkmilod[1]) + \"_\" + \n                        to_string(jkmilod[2]) + \"_\" + to_string(jkmilod[3]) + \"_\" + to_string(jkmilod[4])\n                        + \"_\" + to_string(jkmilod[5]) + \"_\" + to_string(jkmilod[6]) << endl;\n                #endif\n                }\n            })\n            .set_fulfill([&](int7 jkmilod) {\n                int j = jkmilod[0]; // because of dttqrt between blocks {k, j} and {m, j}\n                int k = jkmilod[1]; // row k -- R_{k jinc}\n                int m = jkmilod[2]; // row m -- R_{m jinc}\n                int jinc = jkmilod[3]; // col jinc\n                int l = jkmilod[4]; // level of merging\n                int lnode = jkmilod[5]; // Level of merging between nodes\n                int ldomain = jkmilod[6]; // Level of merging between domains\n                // Dependencies \n                map<int, vector<int>> to_fulfill;\n\n                int domain_index=k/t;\n                int domain_start=max(j,domain_index*t);\n                int domain_end=min(domain_index*t+t,M);\n                int domain_size=domain_end-domain_start;\n                int rank_start = block2rank({domain_start,jinc},{p,q,t},origin);\n\n                int domain_left_rank = domain_size/p;\n                domain_left_rank = (rank-rank_start)<(domain_size%p)? domain_left_rank:domain_left_rank+1;\n\n                double l_limit_nodes = log2(min(p,domain_size));\n                double l_limit_threads = log2(min(n_threads,domain_left_rank));\n                int l_limit_domains = M/t-j/t-1;\n\n                int kt = (k-domain_start)/p; \n                int ktp = (k-domain_start)%p;\n\n                if (l<l_limit_threads){// Merge update within a node\n                    if ((int)(kt/pow(2,l))%2 == 1){\n                        int knext = k-pow(2,l)*p;\n                        int r =  block2rank({knext,jinc},{p,q,t},origin);\n                        assert(r==rank);\n                        dttssmqr_tf.fulfill_promise({j,knext,k,jinc,l+1,lnode,ldomain});\n                    }\n                    else {\n                        // Merge with next and wait for info -- happens on the same rank\n                        int mnext = k+pow(2,l)*p;\n                        dttssmqr_tf.fulfill_promise({j,k,mnext,jinc,l+1,lnode,ldomain});\n                    }\n                }\n                else if (lnode<l_limit_nodes){// Merge update between nodes\n                    int lt_next = M;\n                    assert(k-domain_start<p);\n                    if ((int)(ktp/pow(2,lnode))%2==1){\n                        int knext = k-pow(2,lnode);\n                        int r = block2rank({knext,jinc},{p,q,t},origin);\n                        assert(r!=rank);\n                        auto R_kjinc = view<double>(Mat.at(k+jinc*M).data(), n*n);\n                        int lnext = lnode+1;\n                        am_dttssmqr_2_dttssmqr->send(r, R_kjinc,j,knext,k,jinc,lt_next,lnext,ldomain);\n                    }\n                    else{\n                        // Merge with next and wait for info \n                        int mnext = k+pow(2,lnode);\n                        dttssmqr_tf.fulfill_promise({j,k,mnext,jinc,lt_next,lnode+1,ldomain});\n                    }\n                }\n                else if (ldomain < l_limit_domains){\n                    int lt_next = M;\n                    int ln_next = M;\n                    // Flat tree to merge between domains\n                    if (ldomain>0 && k==j && m%t==0){\n                        // Atleast one step of merging between domains has been done\n                        int mnext = (m/t)*t+t; // First tile of next domain\n                        if (mnext<M){\n                            dttssmqr_tf.fulfill_promise({j,k,mnext,jinc,lt_next,ln_next,ldomain+1}); // keep it on the same node and wait\n                        }\n                    }\n                    else if (k==j){\n                        // First domain and start the fist step of merging between domains\n                        assert(k==j);\n                        int mnext = (k/t)*t+t;\n                        if (mnext<M){\n                            dttssmqr_tf.fulfill_promise({j,k,mnext,jinc,lt_next,ln_next,ldomain+1}); // keep it on the same node and wait\n                        }\n                    }\n                    else if (k%t==0){\n                        // Not the first domain and trigger merging with the first domain\n                        int kprev = j; \n                        int r = block2rank({kprev,jinc},{p,q,t},origin);\n                        if (r==rank) dttssmqr_tf.fulfill_promise({j,kprev,k,jinc,lt_next,ln_next,k/t-j/t});\n                        else {\n                            auto R_kjinc = view<double>(Mat.at(k+jinc*M).data(), n*n);\n                            int ldomain_next= k/t-j/t;\n                            am_dttssmqr_2_dttssmqr->send(r, R_kjinc,j,kprev,k,jinc,lt_next,ln_next, ldomain_next);\n                        }\n                    }\n                }\n\n                int stride = n_threads*p;\n                // Check with valid merge within a node or between nodes or between domains\n                bool run = (lnode==0 && m<min(domain_start+stride,domain_end)) || \n                            (lnode>0 && m<min(domain_start+p,domain_end)) || \n                            (ldomain>0 && k==j && m%t==0) ;\n                if (run){\n                    // same row -- m\n                    if (jinc == j+1) { // Next column\n                        int r = block2rank({m,jinc},{p,q,t}, origin);\n                        if (rank == r) dgeqrt_tf.fulfill_promise({m, jinc}); // Next dgeqrt in that tile\n                        else {\n                            auto R_mi = view<double>(Mat.at(m+jinc*M).data(), n * n ); // send to that row\n                            am_dttssmqr_2_dgeqrt->send(r, R_mi, m, jinc);\n                        }\n                    }\n                    else {\n                        int r = block2rank({m,jinc},{p,q,t}, origin);\n                        if (rank == r) dlarfb_tf.fulfill_promise({m, j+1, jinc}); // one dep. on the next dlarfb in that tile\n                        else {\n                            auto R_mi = view<double>(Mat.at(m+jinc*M).data(), n * n ); // send to that row\n                            int jnext = j+1;\n                            am_dttssmqr_2_dlarfb->send(r, R_mi, m, jnext, jinc);\n                        }\n                    }\n                }\n            })\n            .set_name([](int7 jkmilod) {\n                return \"ttssmqr_\" + to_string(jkmilod[0]) + \"_\" +to_string(jkmilod[1]) + \"_\" + \n                        to_string(jkmilod[2]) + \"_\" + to_string(jkmilod[3]) + \"_\" + to_string(jkmilod[4])\n                        + \"_\" + to_string(jkmilod[5]) + \"_\" + to_string(jkmilod[6]);\n                \n            })\n            .set_priority([&](int7 jkmilod) {\n                return 3+(N-jkmilod[0]);\n            });\n\n        // if(rank == 0) printf(\"Starting QR on a dense matrix\\n\");\n        MPI_Barrier(MPI_COMM_WORLD);\n        timer t0 = wctime();\n        int stride = n_threads*p;\n        for (int i=0; i<M; ++i){\n            if (block2rank({i,0},{p,q,t},origin)==rank) { // same node\n                if (i%t<stride){ \n                    // First dgeqrt \n                    dgeqrt_tf.fulfill_promise({i, 0});\n                }\n            }\n        }\n        tp.join();\n        timer t1 = wctime();\n        MPI_Barrier(MPI_COMM_WORLD);\n        if(rank == 0)\n        {\n            cout << \"Time to factorize: \" << elapsed(t0, t1) << endl;\n        }\n\n        if(LOG) {\n            std::ofstream logfile;\n            string filename = \"hqr_\"+ to_string(nranks)+\".log.\"+to_string(rank);\n            logfile.open(filename);\n            logfile << log;\n            logfile.close();\n        }\n    }\n\n    \n    // Gather everything on rank 0 and test for accuracy\n    if (TEST)\n    {\n        Communicator comm(MPI_COMM_WORLD, VERB);\n        Threadpool tp(n_threads, &comm, VERB);\n\n        // 3 active messages with different data\n        auto am_gather_0 = comm.make_active_msg(\n        [&](view<double> &R_ij, int& i, int& j) {\n            A.block(i*n,j*n,n,n) = Map<MatrixXd>(R_ij.data(), n, n); \n        });\n\n        auto am_gather_1 = comm.make_active_msg(\n        [&](view<double> &Mat_ij, view<double> &TS_ij,  int& i, int& j) {\n            A.block(i*n,j*n,n,n) = Map<MatrixXd>(Mat_ij.data(), n, n); \n            TS.at(i-(j*(j+1))/2+j*M)= Map<MatrixXd>(TS_ij.data(), n, n);\n        });\n\n        auto am_gather_2 = comm.make_active_msg(\n        [&](view<double> &Mat_ij,view<double> &TS_ij, view<double> &TT_ij,  int& i, int& j) {\n            A.block(i*n,j*n,n,n) = Map<MatrixXd>(Mat_ij.data(), n, n); \n            TS.at(i-(j*(j+1))/2+j*M) = Map<MatrixXd>(TS_ij.data(), n, n);\n            TT.at(i-(j*(j+1))/2+j*M) = Map<MatrixXd>(TT_ij.data(), n, n);\n        });\n\n        auto am_gather_3 = comm.make_active_msg(\n        [&](view<double> &Mat_j,view<double> &TS_ij, view<double> &TT_j,  int& i, int& j, int& domain_size) {\n            MatrixXd Atemp = Map<MatrixXd>(Mat_j.data(), p*n, n); \n            MatrixXd Ttemp = Map<MatrixXd>(TT_j.data(), p*n, n);\n\n            if (i==j){\n                 A.block(i*n,j*n,n,n) = Atemp.block(0,0,n,n);\n            }\n            else {\n                // Only the V_ij and TS_ij from dgeqrt \n                A.block(i*n,j*n,n,n).triangularView<StrictlyLower>()=Atemp.block(0,0,n,n).triangularView<StrictlyLower>();\n            }\n            TS.at(i-(j*(j+1))/2+j*M) = Map<MatrixXd>(TS_ij.data(), n, n);\n\n            // DTTQRT for the next p rows in the domain\n            for (int kk=1; kk< min(domain_size,p); ++kk){ \n                A.block((i+kk)*n, j*n, n, n).triangularView<Upper>() = Atemp.block(kk*n,0,n,n).triangularView<Upper>(); // Contains all the updates from dttqrt\n                TT.at(i+kk-(j*(j+1))/2+j*M) = Ttemp.block(kk*n,0,n,n);\n            }\n        });\n\n        auto am_gather_4 = comm.make_active_msg(\n        [&](view<double> &Mat_ij, view<double> &TS_ij,  int& i, int& j) {\n            A.block(i*n,j*n,n,n).triangularView<StrictlyLower>() = Map<MatrixXd>(Mat_ij.data(), n, n).triangularView<StrictlyLower>(); \n            TS.at(i-(j*(j+1))/2+j*M)= Map<MatrixXd>(TS_ij.data(), n, n);\n        });\n\n        auto am_gather_5 = comm.make_active_msg(\n        [&](view<double> &Mat_j, view<double> &TT_j,  int& i, int& j) {\n           int num_domains = (M+t-1)/t-j/t-1;\n\n            MatrixXd Atemp = Map<MatrixXd>(Mat_j.data(), num_domains*n, n); \n            MatrixXd Ttemp = Map<MatrixXd>(TT_j.data(), num_domains*n, n);\n\n            // DTTQRT for merging between domains\n            for (int kk=0; kk< num_domains; ++kk){ \n                int next_tile = ((j+t)/t)*t + kk*t;\n                A.block(next_tile*n, j*n, n, n).triangularView<Upper>() = Atemp.block(kk*n,0,n,n).triangularView<Upper>(); // Contains all the updates from dttqrt\n                TT.at(next_tile-(j*(j+1))/2+j*M) = Ttemp.block(kk*n,0,n,n);\n            }\n        });\n\n        int stride = n_threads*p;\n\n        for (int i=0;i<M;++i){\n            for (int j=0;j<N;++j){\n                int domain_index=i/t;\n                int domain_start=max(j,domain_index*t);\n                int domain_end=min(domain_index*t+t,M);\n                int domain_size=domain_end-domain_start;\n\n                if(block2rank({i,j},{p,q,t}, origin) == rank){ // Each block should send its own data otherwise there can be race condition\n                    if (i<j){// Send Mat_ij\n                        if (rank != 0){\n                            auto V_ij = view<double>(Mat.at(i+j*M).data(), n*n);\n                            am_gather_0->send(0, V_ij, i, j);\n                            // cout << \"i: \" << i << \" j: \" << j << endl;\n                            // cout << Mat.at(i+j*M) << endl << endl;\n                        }\n                        else {\n                            A.block(i*n,j*n,n,n)=Mat.at(i+j*M);\n                        }\n                    }\n                    else { // Send (TT_ij + TS_ij) or (TS_ij) and Mat_ij\n                        assert(i>=j);\n                        if (i<domain_start+stride && i>j){\n                            if (rank!=0){\n                                // Send TT_ij and TS_ij and Mat_ij\n                                auto V_ij = view<double>(Mat.at(i+j*M).data(), n*n);\n                                auto TS_ij = view<double>(TS.at(i-(j*(j+1))/2+j*M).data(), n*n);\n                                auto TT_ij = view<double>(TT.at(i-(j*(j+1))/2+j*M).data(), n*n);\n                                am_gather_2->send(0, V_ij, TS_ij, TT_ij, i, j);\n                            }\n                            else {\n                                A.block(i*n,j*n,n,n)=Mat.at(i+j*M);\n                            }\n                        }   \n                        else {\n                            assert(i>=domain_start+stride || i==j);\n                            if (rank!=0){\n                                // Send TS_ij and Mat_ij\n                                auto V_ij = view<double>(Mat.at(i+j*M).data(), n*n);\n                                auto T_ij = view<double>(TS.at(i-(j*(j+1))/2+j*M).data(), n*n);\n                                am_gather_1->send(0, V_ij, T_ij, i, j);\n                            }\n                            else {\n                                A.block(i*n,j*n,n,n)=Mat.at(i+j*M);\n                            }\n                        }\n                    }        \n                }\n            }\n        }\n\n        tp.join();\n        MPI_Barrier(MPI_COMM_WORLD);\n\n        \n        if(rank == 0 && TEST) {\n            cout << \"Entering solve...\" << endl;\n            // cout << A.block(0,n,M*n,n) << endl;\n            // cout << Mat.at(1*M) << endl;\n            // Test 1   \n            // Q^T b\n            int stride = n_threads*p;\n\n            for (int j=0; j< N; ++j){\n                for (int i=j; i<M; ++i){\n                    int domain_index=i/t;\n                    int domain_start=max(j,domain_index*t);\n                    if (i<domain_start+stride){\n                       assert(TS.at(i-(j*(j+1))/2+j*M).rows()>0);\n                       int info = LAPACKE_dlarfb(LAPACK_COL_MAJOR, 'L', 'T', 'F', 'C', n, 1, n, \n                                                 A.block(i*n,j*n,n,n).data(), M*n, \n                                                 TS.at(i-(j*(j+1))/2+j*M).data(), n,\n                                                 b.segment(i*n, n).data(), n);\n                       assert(info == 0); \n                    }\n                    else { // i >= domain_start+stride\n                        assert(TS.at(i-(j*(j+1))/2+j*M).rows()>0);\n                        int root_tile = (i-domain_start)%stride+domain_start;\n                        assert(root_tile<domain_start+stride);\n                        assert(root_tile<M);\n                        int info = LAPACKE_dtpmqrt(LAPACK_COL_MAJOR, 'L', 'T', n, 1, n, 0, nb, \n                                                   A.block(i*n,j*n,n,n).data(), M*n,  // Since A.block() is use, LDA should be the rows of A\n                                                   TS.at(i-(j*(j+1))/2+j*M).data(), n,\n                                                   b.segment(root_tile*n, n).data(), n,\n                                                   b.segment(i*n, n).data(), n);\n                        assert(info ==0);\n                    }\n                }\n                // cout << \"unmerging\" << endl;\n                // unmerging\n                int domain_index=j/t;\n                int num_domains = (M+t-1)/t;\n                for (int d=domain_index;d<num_domains;d+=1){ // In each remaining domain\n                    int domain_start=max(j,d*t);\n                    int domain_end=min(d*t+t,M);\n                    int node_next=domain_start;\n\n                    while(node_next<domain_start+p){ // Merge across threads for each node\n                        int update_stride = p;\n                        while (update_stride<stride){ // Merge across threads\n                            for (int i=node_next;i<min(domain_end,domain_start+stride);i+=2*update_stride){\n                                // unmerge\n                                int merge_row = i+update_stride;\n\n                                if (merge_row < min(domain_end,domain_start+stride)){\n                                    int info = LAPACKE_dtpmqrt(LAPACK_COL_MAJOR, 'L', 'T', n, 1, n, n, nb, \n                                                           A.block(merge_row*n,j*n,n,n).data(), M*n,\n                                                           TT.at(merge_row-(j*(j+1))/2+j*M).data(), n,\n                                                           b.segment(i*n, n).data(), n,\n                                                           b.segment(merge_row*n, n).data(), n);\n                                    assert(info==0);\n                                }\n                            }\n                            update_stride += update_stride;\n                        }\n                        node_next += 1;\n                    }\n                    \n                    // Merge across nodes \n                    int update_stride = 1;\n                    while (update_stride<p){\n                        for (int i=domain_start;i<min(domain_end,domain_start+p);i+=2*update_stride){\n                            int merge_row=i+update_stride;\n                            if (merge_row<min(domain_end,domain_start+p)){\n                                int info = LAPACKE_dtpmqrt(LAPACK_COL_MAJOR, 'L', 'T', n, 1, n, n, nb, \n                                                       A.block(merge_row*n,j*n,n,n).data(), M*n,\n                                                       TT.at(merge_row-(j*(j+1))/2+j*M).data(), n,\n                                                       b.segment(i*n, n).data(), n,\n                                                       b.segment(merge_row*n, n).data(), n);\n                                assert(info==0);\n                            }\n                        }\n                        update_stride += update_stride;\n                    }       \n                }\n                \n                // Merge across domains -- flat tree\n                int first_row_in_next_tile = ((j+t)/t)*t;\n                for (int fn = first_row_in_next_tile; fn < M; fn+=t){\n                    int info = LAPACKE_dtpmqrt(LAPACK_COL_MAJOR, 'L', 'T', n, 1, n, n, nb, \n                                               A.block(fn*n,j*n,n,n).data(), M*n,\n                                               TT.at(fn-(j*(j+1))/2+j*M).data(), n,\n                                               b.segment(j*n, n).data(), n,\n                                               b.segment(fn*n, n).data(), n);\n                    assert(info ==0);\n                }\n\n            }\n            // R^{-1}b\n            auto R = A.triangularView<Upper>();\n            R.solveInPlace(b);\n\n            // cout << b << endl << endl;\n            // cout << x << endl;\n            double error = (b.topRows(N*n) - x).norm() / x.norm();\n            cout << \"Error solve: \" << error << endl;\n            assert(error<=1e-8);\n        }\n        \n    }\n    \n    \n    return 0;\n}\n\n\nint main(int argc, char **argv)\n{\n    int req = MPI_THREAD_FUNNELED;\n    int prov = -1;\n\n    MPI_Init_thread(NULL, NULL, req, &prov);\n\n    assert(prov == req);\n\n    if (argc >= 2)\n    {\n        n_threads_ = atoi(argv[1]);\n    }\n\n    if (argc >= 3)\n    {\n        n_ = atoi(argv[2]);\n    }\n\n    if (argc >= 4)\n    {\n        M_ = atoi(argv[3]);\n    }\n\n    if (argc >= 5)\n    {\n        N_ = atoi(argv[4]);\n    }\n\n    if (argc >= 6)\n    {\n        p_ = atoi(argv[5]);\n    }\n\n    if (argc >= 7)\n    {\n        q_ = atoi(argv[6]);\n    }\n\n    if (argc >= 8){\n        t_ = atoi(argv[7]);\n    }\n\n    if (argc >= 9)\n    {\n        VERB = atoi(argv[8]);\n    }\n\n    if (argc >= 10)\n    {\n        LOG = atoi(argv[9]);\n    }\n\n    if (argc >= 11)\n    {\n        TEST = atoi(argv[10]);\n    }\n    t_ = n_threads_*p_*t_;\n    if (t_>M_){\n        cout << \"Setting t_ to the maximum allowed value...\" << endl;\n        t_ = M_;\n    }\n    const int return_flag = denseQR(n_threads_, n_, M_, N_, p_, q_, t_);\n    MPI_Finalize();\n    return return_flag;\n}\n", "meta": {"hexsha": "2e66ce10d6dbbfc89ea32cc71d4a3702e7f7a71e", "size": 61270, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "miniapp/dense_qr/hqr_improved.cpp", "max_stars_repo_name": "Abeynaya/tasktorrent", "max_stars_repo_head_hexsha": "987718e6e9033ae8aa295323e4699e759d744e7f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "miniapp/dense_qr/hqr_improved.cpp", "max_issues_repo_name": "Abeynaya/tasktorrent", "max_issues_repo_head_hexsha": "987718e6e9033ae8aa295323e4699e759d744e7f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "miniapp/dense_qr/hqr_improved.cpp", "max_forks_repo_name": "Abeynaya/tasktorrent", "max_forks_repo_head_hexsha": "987718e6e9033ae8aa295323e4699e759d744e7f", "max_forks_repo_licenses": ["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.2087447109, "max_line_length": 162, "alphanum_fraction": 0.4188673086, "num_tokens": 15447, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286833, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.45068521209781515}}
{"text": "#ifndef CONFIG_HPP\n#define CONFIG_HPP\n\n#include <Eigen/Core>\n#include <Eigen/Eigen>\n#include <unordered_set>\n\n/** floatBO defines the floating point precision to be used in EchoBay */\ntypedef double floatBO;\ntypedef Eigen::ArrayXd ArrayBO;\ntypedef Eigen::ArrayXi ArrayI;\ntypedef Eigen::Array<int8_t, Eigen::Dynamic, 1> ArrayI8;\ntypedef Eigen::MatrixXd MatrixBO;\ntypedef Eigen::VectorXcd VComplexBO;\ntypedef Eigen::Triplet<floatBO> TripletBO;\ntypedef Eigen::SparseMatrix<floatBO, 0x1> SparseBO;\n\n// Structures for Hash Table and WR Filling\nstruct pair_hash\n{\n    template <class T1, class T2>\n    std::size_t operator() (const std::pair<T1, T2> &pair) const\n    {\n        return std::hash<T1>()(pair.first) ^ std::hash<T2>()(pair.second);\n    }\n};\ntypedef std::unordered_set<std::pair<int,int>, pair_hash >::iterator UOMIterator;\n#endif", "meta": {"hexsha": "7822de0e168d6131bc79e4580469f91a6cf38f81", "size": 835, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/include/EigenConfig.hpp", "max_stars_repo_name": "necst/Echobay", "max_stars_repo_head_hexsha": "923e16f796d5019daa039a5b131061270746d429", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2019-09-04T15:10:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-21T10:14:33.000Z", "max_issues_repo_path": "src/include/EigenConfig.hpp", "max_issues_repo_name": "necst/Echobay", "max_issues_repo_head_hexsha": "923e16f796d5019daa039a5b131061270746d429", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/include/EigenConfig.hpp", "max_forks_repo_name": "necst/Echobay", "max_forks_repo_head_hexsha": "923e16f796d5019daa039a5b131061270746d429", "max_forks_repo_licenses": ["Apache-2.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.8214285714, "max_line_length": 81, "alphanum_fraction": 0.7377245509, "num_tokens": 221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286833, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.45068521209781515}}
{"text": "/*\n    BSD 3-Clause License\n\n    Copyright (c) 2018, Roboy\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    author: Simon Trendel ( simon.trendel@tum.de ), 2018\n    description: least squares minimzer for pose estimation using relative sensor distances\n                  based on \"An Improved Method of Pose Estimation for Lighthouse Base Station Extension\"\n                  https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5677447/\n*/\n\n#pragma once\n\n// Eigen\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <unsupported/Eigen/NonLinearOptimization>\n#include <unsupported/Eigen/NumericalDiff>\n\n// std\n#include <iostream>\n\nusing namespace Eigen;\nusing namespace std;\nnamespace PoseEstimatorMultiLighthouse {\n// Generic functor for Eigen Levenberg-Marquardt minimizer\n    template<typename _Scalar, int NX = Dynamic, int NY = Dynamic>\n    struct Functor {\n        typedef _Scalar Scalar;\n        enum {\n            InputsAtCompileTime = NX,\n            ValuesAtCompileTime = NY\n        };\n        typedef Matrix<Scalar, InputsAtCompileTime, 1> InputType;\n        typedef Matrix<Scalar, ValuesAtCompileTime, 1> ValueType;\n        typedef Matrix<Scalar, ValuesAtCompileTime, InputsAtCompileTime> JacobianType;\n\n        const int m_inputs, m_values;\n\n        Functor() : m_inputs(InputsAtCompileTime), m_values(ValuesAtCompileTime) {}\n\n        Functor(int inputs, int values) : m_inputs(inputs), m_values(values) {}\n\n        int inputs() const { return m_inputs; }\n\n        int values() const { return m_values; }\n    };\n\n    struct PoseEstimator : Functor<double> {\n        /**\n         * Default amount of sensors needed for Eigen templated structure\n         * @param numberOfSensors you can however choose any number of sensors here\n         */\n        PoseEstimator(int numberOfSensors = 4);\n\n        /**\n         * This is the function that is called in each iteration\n         * @param x the pose vector (3 rotational 3 translational parameters)\n         * @param fvec the error function (the difference between the sensor positions)\n         * @return\n         */\n        int operator()(const VectorXd &x, VectorXd &fvec) const;\n\n        VectorXd pose;\n        vector<Matrix4d> lighthousePose;\n        vector<double> elevations, azimuths;\n        vector<Vector3d> rel_pos;\n        int numberOfSensors = 4;\n        vector<int> lighthouse_id;\n    };\n}", "meta": {"hexsha": "11065e4e947f28d426a2ae90b2a3b414b1932bba", "size": 3898, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "darkroom/include/darkroom/PoseEstimatorMultiLighthouse.hpp", "max_stars_repo_name": "mattgil23/test01", "max_stars_repo_head_hexsha": "9464e40caf483eae60fa9c0b490ce8f09e552a53", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "darkroom/include/darkroom/PoseEstimatorMultiLighthouse.hpp", "max_issues_repo_name": "mattgil23/test01", "max_issues_repo_head_hexsha": "9464e40caf483eae60fa9c0b490ce8f09e552a53", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "darkroom/include/darkroom/PoseEstimatorMultiLighthouse.hpp", "max_forks_repo_name": "mattgil23/test01", "max_forks_repo_head_hexsha": "9464e40caf483eae60fa9c0b490ce8f09e552a53", "max_forks_repo_licenses": ["BSD-3-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.1855670103, "max_line_length": 104, "alphanum_fraction": 0.698306824, "num_tokens": 810, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286833, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.45068521209781515}}
{"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//\n//This algorithm is described in \"Network Flows: Theory, Algorithms, and Applications\"\n// by Ahuja, Magnanti, Orlin.\n\n#ifndef BOOST_GRAPH_CYCLE_CANCELING_HPP\n#define BOOST_GRAPH_CYCLE_CANCELING_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/pending/relaxed_heap.hpp>\n#include <boost/graph/bellman_ford_shortest_paths.hpp>\n#include <boost/graph/iteration_macros.hpp>\n#include <boost/graph/detail/augment.hpp>\n#include <boost/graph/find_flow_cost.hpp>\n\nnamespace boost {\n\n\nnamespace detail {\n\ntemplate <typename PredEdgeMap, typename Vertex>\nclass RecordEdgeMapAndCycleVertex\n    : public bellman_visitor<edge_predecessor_recorder<PredEdgeMap, on_edge_relaxed> > {\n        typedef edge_predecessor_recorder<PredEdgeMap, on_edge_relaxed> PredRec;\npublic:\n    RecordEdgeMapAndCycleVertex(PredEdgeMap pred, Vertex & v) :\n        bellman_visitor<PredRec>(PredRec(pred)), m_v(v), m_pred(pred) {}\n\n    template <typename Graph, typename Edge>\n    void edge_not_minimized(Edge e, const Graph & g) const {\n        typename graph_traits<Graph>::vertices_size_type n = num_vertices(g) + 1;\n\n        //edge e is not minimized but does not have to be on the negative weight cycle\n        //to find vertex on negative wieight cycle we move n+1 times backword in the PredEdgeMap graph.\n        while(n > 0) {\n            e = get(m_pred, source(e, g));\n            --n;\n        }\n        m_v = source(e, g);\n    }\nprivate:\n    Vertex & m_v;\n    PredEdgeMap m_pred;\n};\n\n} //detail\n\n\ntemplate <class Graph, class Pred, class Distance, class Reversed, class ResidualCapacity, class Weight>\nvoid cycle_canceling(const Graph &g, Weight weight, Reversed rev, ResidualCapacity residual_capacity, Pred pred, Distance distance) {\n    typedef filtered_graph<const Graph, is_residual_edge<ResidualCapacity> > ResGraph;\n    ResGraph gres = detail::residual_graph(g, residual_capacity);\n\n    typedef graph_traits<ResGraph> ResGTraits;\n    typedef graph_traits<Graph> GTraits;\n    typedef typename ResGTraits::edge_descriptor edge_descriptor;\n    typedef typename ResGTraits::vertex_descriptor vertex_descriptor;\n\n    typename GTraits::vertices_size_type N = num_vertices(g);\n\n    BGL_FORALL_VERTICES_T(v, g, Graph) {\n        put(pred, v, edge_descriptor());\n        put(distance, v, 0);\n    }\n\n    vertex_descriptor cycleStart;\n    while(!bellman_ford_shortest_paths(gres, N,\n            weight_map(weight).\n            distance_map(distance).\n            visitor(detail::RecordEdgeMapAndCycleVertex<Pred, vertex_descriptor>(pred, cycleStart)))) {\n\n        detail::augment(g, cycleStart, cycleStart, pred, residual_capacity, rev);\n\n        BGL_FORALL_VERTICES_T(v, g, Graph) {\n            put(pred, v, edge_descriptor());\n            put(distance, v, 0);\n        }\n    }\n}\n\n\n//in this namespace argument dispatching takes place\nnamespace detail {\n\ntemplate <class Graph, class P, class T, class R, class ResidualCapacity, class Weight, class Reversed, class Pred, class Distance>\nvoid cycle_canceling_dispatch2(\n        const Graph &g,\n        Weight weight,\n        Reversed rev,\n        ResidualCapacity residual_capacity,\n        Pred pred,\n        Distance dist,\n        const bgl_named_params<P, T, R>& params) {\n    cycle_canceling(g, weight, rev, residual_capacity, pred, dist);\n}\n\n//setting default distance map\ntemplate <class Graph, class P, class T, class R, class Pred, class ResidualCapacity, class Weight, class Reversed>\nvoid cycle_canceling_dispatch2(\n        Graph &g,\n        Weight weight,\n        Reversed rev,\n        ResidualCapacity residual_capacity,\n        Pred pred,\n        param_not_found,\n        const bgl_named_params<P, T, R>& params) {\n    typedef typename property_traits<Weight>::value_type D;\n\n    std::vector<D> d_map(num_vertices(g));\n\n    cycle_canceling(g, weight, rev, residual_capacity, pred,\n                    make_iterator_property_map(d_map.begin(), choose_const_pmap(get_param(params, vertex_index), g, vertex_index)));\n}\n\ntemplate <class Graph, class P, class T, class R, class ResidualCapacity, class Weight, class Reversed, class Pred>\nvoid cycle_canceling_dispatch1(\n        Graph &g,\n        Weight weight,\n        Reversed rev,\n        ResidualCapacity residual_capacity,\n        Pred pred,\n        const bgl_named_params<P, T, R>& params) {\n    cycle_canceling_dispatch2(g, weight, rev,residual_capacity,  pred,\n                                get_param(params, vertex_distance), params);\n}\n\n//setting default predecessors map\ntemplate <class Graph, class P, class T, class R, class ResidualCapacity, class Weight, class Reversed>\nvoid cycle_canceling_dispatch1(\n        Graph &g,\n        Weight weight,\n        Reversed rev,\n        ResidualCapacity residual_capacity,\n        param_not_found,\n        const bgl_named_params<P, T, R>& params) {\n    typedef typename graph_traits<Graph>::edge_descriptor edge_descriptor;\n    std::vector<edge_descriptor> p_map(num_vertices(g));\n\n    cycle_canceling_dispatch2(g, weight, rev, residual_capacity,\n                              make_iterator_property_map(p_map.begin(), choose_const_pmap(get_param(params, vertex_index), g, vertex_index)),\n                                get_param(params, vertex_distance), params);\n}\n\n}//detail\n\ntemplate <class Graph, class  P, class T, class R>\nvoid cycle_canceling(Graph &g,\n        const bgl_named_params<P, T, R>& params) {\n    cycle_canceling_dispatch1(g,\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_pmap(get_param(params, edge_residual_capacity),\n                       g, edge_residual_capacity),\n           get_param(params, vertex_predecessor),\n           params);\n}\n\ntemplate <class Graph>\nvoid cycle_canceling(Graph &g) {\n    bgl_named_params<int, buffer_param_t> params(0);\n    cycle_canceling(g, params);\n}\n\n\n}\n\n#endif /* BOOST_GRAPH_CYCLE_CANCELING_HPP */\n", "meta": {"hexsha": "20ad9c89e45bac0e1d4a0505bf0f24926a6f06aa", "size": 6454, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/src/boost_1_65_1/boost/graph/cycle_canceling.hpp", "max_stars_repo_name": "shreyasvj25/turicreate", "max_stars_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11356.0, "max_stars_repo_stars_event_min_datetime": "2017-12-08T19:42:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:55:25.000Z", "max_issues_repo_path": "deps/src/boost_1_65_1/boost/graph/cycle_canceling.hpp", "max_issues_repo_name": "shreyasvj25/turicreate", "max_issues_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2402.0, "max_issues_repo_issues_event_min_datetime": "2017-12-08T22:31:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:25:52.000Z", "max_forks_repo_path": "deps/src/boost_1_65_1/boost/graph/cycle_canceling.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": 35.6574585635, "max_line_length": 141, "alphanum_fraction": 0.6850015494, "num_tokens": 1459, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286833, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.45068521209781515}}
{"text": "#pragma once\n\n#include <Eigen/Core>\n\n#include <interval/interval.hpp>\n\n/// NOTE: Naming Convention\n/// Point: Either a 2D or 3D point in space.\n/// Edge: A line segment in either 2D or 3D defined by its endpoints.\n/// Triangle: A triangle in 3D\n\nnamespace ipc::rigid {\n\nbool is_point_along_edge(\n    const VectorMax3I& p, const VectorMax3I& e0, const VectorMax3I& e1);\n\nbool are_edges_intersecting(\n    const Vector3I& ea0,\n    const Vector3I& ea1,\n    const Vector3I& eb0,\n    const Vector3I& eb1);\n\nbool is_point_inside_triangle(\n    const Vector3I& p,\n    const Vector3I& t0,\n    const Vector3I& t1,\n    const Vector3I& t2);\n\n} // namespace ipc::rigid\n", "meta": {"hexsha": "a508c1a8cb6bc2fc24c1fc0b206e96632bb0f2a8", "size": 655, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/geometry/intersection.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/geometry/intersection.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/geometry/intersection.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": 21.8333333333, "max_line_length": 72, "alphanum_fraction": 0.7038167939, "num_tokens": 198, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.45068521209781515}}
{"text": "#include <fstream>\n#include <iostream>\n#include <stack>\n#include <chrono>\n#include <boost/exception/all.hpp>\n\n#include \"common.h\"\n\n#include \"Array.h\"\n\nnamespace matCUDA\n{\n\t// identity matrix generation\n\ttemplate <typename TElement>\n\tArray<TElement> eye( index_t N )\n\t{\t\n\t\tArray<TElement> result( N, N );\n\n\t\t//// CPU version\n\t\t//for (int i = 0; i < result.GetDescriptor().GetDim(0); i++) {\n\t\t//\tfor (int j = 0; j < result.GetDescriptor().GetDim(1); j++) \n\t\t//\t\tresult(i,j) = ( i == j );\n\t\t//}\n\n\t\t// GPU version\n\t\tcuda_eye<TElement>( result.data(), N );\n\n\t\treturn result;\n\t}\n\n\ttemplate Array<int> eye( index_t N );\n\ttemplate Array<float> eye( index_t N );\n\ttemplate Array<double> eye( index_t N );\n\ttemplate Array<ComplexFloat> eye( index_t N );\n\ttemplate Array<ComplexDouble> eye( index_t N );\n\n\t// dpss generation following Gruenbacher and Hummels, 1994\n\ttemplate <typename TElement>\n\tArray<TElement> dpss( index_t N, double NW, index_t degree )\n\t{\n\t\tcusolverStatus_t stat = CUSOLVER_STATUS_NOT_INITIALIZED;\n\t\tcusolverOperations<TElement> op;\n\t\tArray<TElement> eigenvector( N );\n\n\t\ttry\n\t\t{\n\t\t\tstat = op.dpss( &eigenvector, N, NW, degree );\n\t\t}\n\t\tcatch(std::exception &e)\n\t\t{\n\t\t\tstd::cerr << boost::diagnostic_information(e);\n\t\t}\n\t\n\t\treturn eigenvector;\n\t}\n\n\ttemplate Array<float> dpss( index_t N, double NW, index_t degree );\n\ttemplate Array<double> dpss( index_t N, double NW, index_t degree );\n\n\t//Array<ComplexFloat> fft( Array<float> *in )\n\t//{\n\t//\tcufftResult_t stat = CUFFT_NOT_IMPLEMENTED;\n\t//\tcufftOperations<ComplexFloat> op;\n\t//\tArray<ComplexFloat> result( floor(in->GetDescriptor().GetDim(0)/2)+1, in->GetDescriptor().GetDim(1) );\n\t//\n\t//\ttry\n\t//\t{\n\t//\t\tstat = op.fft_stream( in, &result );\n\t//\t}\n\t//\tcatch(std::exception &e)\n\t//\t{\n\t//\t\tstd::cerr << boost::diagnostic_information(e);\n\t//\t}\n\t//\n\t//\treturn result;\n\t//}\n\t//\n\t//Array<ComplexDouble> fft( Array<double> *in )\n\t//{\n\t//\tcufftResult_t stat = CUFFT_NOT_IMPLEMENTED;\n\t//\tcufftOperations<ComplexDouble> op;\n\t//\tArray<ComplexDouble> result( in->GetDescriptor().GetDim(0)/2+1, in->GetDescriptor().GetDim(1) );\n\t//\n\t//\ttry\n\t//\t{\n\t//\t\tstat = op.fft_stream( in, &result );\n\t//\t}\n\t//\tcatch(std::exception &e)\n\t//\t{\n\t//\t\tstd::cerr << boost::diagnostic_information(e);\n\t//\t}\n\t//\n\t//\treturn result;\n\t//}\n\n\ttemplate<typename TElement>\n\tArray<std::complex<TElement>> fft( Array<TElement> *in )\n\t{\n\t\tcufftResult_t stat = CUFFT_NOT_IMPLEMENTED;\n\t\tcufftOperations<std::complex<TElement>> op;\n\t\tArray<std::complex<TElement>> result( floor(in->GetDescriptor().GetDim(0)/2)+1, in->GetDescriptor().GetDim(1) );\n\n\t\ttry\n\t\t{\n\t\t\tstat = op.fft_stream( in, &result );\n\t\t}\n\t\tcatch(std::exception &e)\n\t\t{\n\t\t\tstd::cerr << boost::diagnostic_information(e);\n\t\t}\n\t\n\t\treturn result;\n\t}\n\n\ttemplate Array<std::complex<float>> fft( Array<float> *in );\n\ttemplate Array<std::complex<double>> fft( Array<double> *in );\n\n\t// read files for unit tests\n\ttemplate<> Array<ComplexFloat> read_file_vector( std::string s )\n\t{\n\t\tconst size_t lim = 128;\n\t\tstd::string aux;\n\t\tstd::ifstream inputFile;\n\t\tinputFile.open( s );\n\t\tif( inputFile.good() )\n\t\t{\n\t\t\tstd::getline( inputFile, aux );\n\t\t\tsize_t dim = std::stoi( aux );\n\t\t\tArray<ComplexFloat> result(dim);\n\n\t\t\tdouble real, imag;\n\t\t\tfor( int i = 0; i < dim; i++ ) {\n\t\t\t\tstd::getline( inputFile, aux );\n\t\t\t\treal = std::stof( aux );\n\t\t\t\tstd::getline( inputFile, aux );\n\t\t\t\timag = std::stof( aux );\n\t\t\t\tresult( i ) = ComplexFloat( real, imag );\n\t\t\t}\n\n\t\t\tinputFile.close();\n\n\t\t\treturn result;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstd::cout<< \"Could not open \" << s << std::endl;\n\t\t\tEXIT_FAILURE;\n\n\t\t\treturn Array<ComplexFloat> (1);\n\t\t}\n\t}\n\n\ttemplate<> Array<ComplexDouble> read_file_vector( std::string s )\n\t{\n\t\tconst size_t lim = 128;\n\t\tstd::string aux;\n\t\tstd::ifstream inputFile;\n\t\tinputFile.open( s );\n\t\tif( inputFile.good() )\n\t\t{\n\t\t\tstd::getline( inputFile, aux );\n\t\t\tsize_t dim = std::stoi( aux );\n\t\t\tArray<ComplexDouble> result(dim);\n\n\t\t\tdouble real, imag;\n\t\t\tfor( int i = 0; i < dim; i++ ) {\n\t\t\t\tstd::getline( inputFile, aux );\n\t\t\t\treal = std::stod( aux );\n\t\t\t\tstd::getline( inputFile, aux );\n\t\t\t\timag = std::stod( aux );\n\t\t\t\tresult( i ) = ComplexDouble( real, imag );\n\t\t\t}\n\n\t\t\tinputFile.close();\n\n\t\t\treturn result;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstd::cout<< \"Could not open \" << s << std::endl;\n\t\t\tEXIT_FAILURE;\n\n\t\t\treturn Array<ComplexDouble> (1);\n\t\t}\n\t}\n\n\ttemplate<> Array<float> read_file_vector( std::string s )\n\t{\n\t\tconst size_t lim = 128;\n\t\tstd::string aux;\n\t\tstd::ifstream inputFile;\n\t\tinputFile.open( s );\n\t\tif( inputFile.good() )\n\t\t{\n\t\t\tstd::getline( inputFile, aux );\n\t\t\tsize_t dim = std::stoi( aux );\n\t\t\tArray<float> result(dim);\n\n\t\t\tfor( int i = 0; i < dim; i++ ) {\n\t\t\t\tstd::getline( inputFile, aux );\n\t\t\t\tresult( i ) = std::stof( aux );\n\t\t\t}\n\n\t\t\tinputFile.close();\n\n\t\t\treturn result;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstd::cout<< \"Could not open \" << s << std::endl;\n\t\t\tEXIT_FAILURE;\n\n\t\t\treturn Array<float> (1);\n\t\t}\n\t}\n\n\ttemplate<> Array<double> read_file_vector( std::string s )\n\t{\n\t\tconst size_t lim = 128;\n\t\tstd::string aux;\n\t\tstd::ifstream inputFile;\n\t\tinputFile.open( s );\n\t\tif( inputFile.good() )\n\t\t{\n\t\t\tstd::getline( inputFile, aux );\n\t\t\tsize_t dim = std::stoi( aux );\n\t\t\tArray<double> result(dim);\n\n\t\t\tfor( int i = 0; i < dim; i++ ) {\n\t\t\t\tstd::getline( inputFile, aux );\n\t\t\t\tresult( i ) = std::stof( aux );\n\t\t\t}\n\n\t\t\tinputFile.close();\n\n\t\t\treturn result;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstd::cout<< \"Could not open \" << s << std::endl;\n\t\t\tEXIT_FAILURE;\n\n\t\t\treturn Array<double> (1);\n\t\t}\n\t}\n\n\ttemplate<> Array<ComplexFloat> read_file_matrix( std::string s )\n\t{\n\t\tconst size_t lim = 128;\n\t\tstd::string aux;\n\t\tstd::ifstream inputFile;\n\t\tinputFile.open( s );\n\t\tif( inputFile.good() )\n\t\t{\n\t\t\tstd::getline( inputFile, aux );\n\t\t\tindex_t idxComma = aux.find_first_of( ',', 0 );\n\t\t\tsize_t rows = std::stoi( aux.substr( 0, idxComma - 1 ) );\n\t\t\tsize_t cols = std::stoi( aux.substr( idxComma + 1, aux.size() ) );\n\t\t\tArray<ComplexFloat> result(rows,cols);\n\n\t\t\tdouble real, imag;\n\t\t\tfor( int i = 0; i < cols; i++ ) {\n\t\t\t\tfor( int j = 0; j < rows; j++ ) {\n\t\t\t\tstd::getline( inputFile, aux );\n\t\t\t\treal = std::stof( aux );\n\t\t\t\tstd::getline( inputFile, aux );\n\t\t\t\timag = std::stof( aux );\n\t\t\t\tresult( j, i ) = ComplexFloat( real, imag );\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tinputFile.close();\n\n\t\t\treturn  result;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstd::cout<< \"Could not open \" << s << std::endl;\n\t\t\tEXIT_FAILURE;\n\n\t\t\treturn Array<ComplexFloat> (1,1);\n\t\t}\n\t}\n\n\ttemplate<> Array<ComplexDouble> read_file_matrix( std::string s )\n\t{\n\t\tconst size_t lim = 128;\n\t\tstd::string aux;\n\t\tstd::ifstream inputFile;\n\t\tinputFile.open( s );\n\t\tif( inputFile.good() )\n\t\t{\n\t\t\tstd::getline( inputFile, aux );\n\t\t\tindex_t idxComma = aux.find_first_of( ',', 0 );\t\t\n\t\t\tsize_t rows = std::stoi( aux.substr( 0, idxComma - 1 ) );\n\t\t\tsize_t cols = std::stoi( aux.substr( idxComma + 1, aux.size() ) );\n\t\t\tArray<ComplexDouble> result(rows,cols);\n\n\t\t\tdouble real, imag;\n\t\t\tfor( int i = 0; i < cols; i++ ) {\n\t\t\t\tfor( int j = 0; j < rows; j++ ) {\n\t\t\t\tstd::getline( inputFile, aux );\n\t\t\t\treal = std::stod( aux );\n\t\t\t\tstd::getline( inputFile, aux );\n\t\t\t\timag = std::stod( aux );\n\t\t\t\tresult( j, i ) = ComplexDouble( real, imag );\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tinputFile.close();\n\n\t\t\treturn result;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstd::cout<< \"Could not open \" << s << std::endl;\n\t\t\tEXIT_FAILURE;\n\n\t\t\treturn Array<ComplexDouble> (1,1);\n\t\t}\n\t}\n\n\ttemplate<> Array<float> read_file_matrix( std::string s )\n\t{\n\t\tconst size_t lim = 128;\n\t\tstd::string aux;\n\t\tstd::ifstream inputFile;\n\t\tinputFile.open( s );\n\t\tif( inputFile.good() )\n\t\t{\n\t\t\tstd::getline( inputFile, aux );\n\t\t\tindex_t idxComma = aux.find_first_of( ',', 0 );\n\t\t\tsize_t rows = std::stoi( aux.substr( 0, idxComma - 1 ) );\n\t\t\tsize_t cols = std::stoi( aux.substr( idxComma + 1, aux.size() ) );\n\t\t\tArray<float> result(rows,cols);\n\n\t\t\tfor( int i = 0; i < cols; i++ ) {\n\t\t\t\tfor( int j = 0; j < rows; j++ ) {\n\t\t\t\t\tstd::getline( inputFile, aux );\n\t\t\t\t\tresult( j, i ) = std::stof( aux );\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tinputFile.close();\n\n\t\t\treturn result;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstd::cout<< \"Could not open \" << s << std::endl;\n\t\t\tEXIT_FAILURE;\n\n\t\t\treturn Array<float> (1,1);\n\t\t}\n\t}\n\n\ttemplate<> Array<double> read_file_matrix( std::string s )\n\t{\n\t\tconst size_t lim = 128;\n\t\tstd::string aux;\n\t\tstd::ifstream inputFile;\n\t\tinputFile.open( s );\n\t\tif( inputFile.good() )\n\t\t{\n\t\t\tstd::getline( inputFile, aux );\n\t\t\tindex_t idxComma = aux.find_first_of( ',', 0 );\n\t\t\tsize_t rows = std::stoi( aux.substr( 0, idxComma - 1 ) );\n\t\t\tsize_t cols = std::stoi( aux.substr( idxComma + 1, aux.size() ) );\n\t\t\tArray<double> result(rows,cols);\n\n\t\t\tfor( int i = 0; i < cols; i++ ) {\n\t\t\t\tfor( int j = 0; j < rows; j++ ) {\n\t\t\t\t\tstd::getline( inputFile, aux );\n\t\t\t\t\tresult( j, i ) = std::stof( aux );\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tinputFile.close();\n\n\t\t\treturn result;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstd::cout<< \"Could not open \" << s << std::endl;\n\t\t\tEXIT_FAILURE;\n\n\t\t\treturn Array<double> (1,1);\n\t\t}\n\t}\n\n\ttemplate <typename TElement>\n\tArray<TElement> rand(index_t u)\n\t{\n\t\tcurandStatus_t stat = CURAND_STATUS_NOT_INITIALIZED;\n\t\tcurandOperations<TElement> op;\n\t\tArray<TElement> result( u );\n\n\t\ttry\n\t\t{\n\t\t\tstat = op.rand( &result );\n\t\t}\n\t\tcatch(std::exception &e)\n\t\t{\n\t\t\tstd::cerr << boost::diagnostic_information(e);\n\t\t}\n\t\n\t\treturn result;\n\t}\n\n\ttemplate Array<float> rand(index_t u);\n\ttemplate Array<double> rand(index_t u);\n\ttemplate Array<ComplexFloat> rand(index_t u);\n\ttemplate Array<ComplexDouble> rand(index_t u);\n\n\ttemplate <typename TElement>\n\tArray<TElement> rand(index_t u1, index_t u2)\n\t{\n\t\tcurandStatus_t stat = CURAND_STATUS_NOT_INITIALIZED;\n\t\tcurandOperations<TElement> op;\n\t\tArray<TElement> result( u1, u2 );\n\n\t\ttry\n\t\t{\n\t\t\tstat = op.rand( &result );\n\t\t\t//stat = op.rand_zerocopy( &result );\n\t\t}\n\t\tcatch(std::exception &e)\n\t\t{\n\t\t\tstd::cerr << boost::diagnostic_information(e);\n\t\t}\n\t\n\t\treturn result;\n\t}\n\n\ttemplate Array<float> rand(index_t u1, index_t u2);\n\ttemplate Array<double> rand(index_t u1, index_t u2);\n\ttemplate Array<ComplexFloat> rand(index_t u1, index_t u2);\n\ttemplate Array<ComplexDouble> rand(index_t u1, index_t u2);\n\n\tstd::stack<std::chrono::system_clock::time_point> tictoc_stack;\n\tvoid tic() {\n\t\ttictoc_stack.push(std::chrono::high_resolution_clock::now());\n\t}\n\tvoid toc() {\n\t\tstd::cout << \"Time elapsed: \"\n\t\t\t\t  << std::setprecision( 8 )\n\t\t\t\t  << std::scientific\n\t\t\t\t  << 1e-9*std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::high_resolution_clock::now() - tictoc_stack.top()).count()\n\t\t\t\t  //<< ((double)(clock() - tictoc_stack.top())) / CLOCKS_PER_SEC\n\t\t\t\t  << \" seconds\"\n\t\t\t\t  << std::endl;\n\t\ttictoc_stack.pop();\n\t}\n\tlong double toc( long double in ) {\n\t\tlong double out = 1e-9*std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::high_resolution_clock::now() - tictoc_stack.top()).count();\n\t\treturn out;\n\t}\n}\n\n//template <typename TElement>\n//Array<TElement> rand(index_t u, ...)\n//{\n//\tva_list args;\n//\tva_start(args, u);\n//\n//\tint count = u;\n//\n//\tfor(int i = 1; i < count; i++)\n//\t\tm_indexer->m_pos[i] = va_arg(args, index_t);\n//\n//\tva_end(args);\n//\treturn Array<TElement>(1);\n//}\n//\n//template Array<int> rand(index_t u, ...);\n//template Array<float> rand(index_t u, ...);\n//template Array<double> rand(index_t u, ...);\n//template Array<ComplexFloat> rand(index_t u, ...);\n//template Array<ComplexDouble> rand(index_t u, ...);", "meta": {"hexsha": "9d4a778ab26f0023dcb22371862fcbe68afdfce6", "size": 11184, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "matCUDA lib/src/global_func.cpp", "max_stars_repo_name": "leomiquelutti/matCUDA", "max_stars_repo_head_hexsha": "95bd7917289288b0137ce23a952d4ccfd43e0d1d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "matCUDA lib/src/global_func.cpp", "max_issues_repo_name": "leomiquelutti/matCUDA", "max_issues_repo_head_hexsha": "95bd7917289288b0137ce23a952d4ccfd43e0d1d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "matCUDA lib/src/global_func.cpp", "max_forks_repo_name": "leomiquelutti/matCUDA", "max_forks_repo_head_hexsha": "95bd7917289288b0137ce23a952d4ccfd43e0d1d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.3486430063, "max_line_length": 150, "alphanum_fraction": 0.6166845494, "num_tokens": 3464, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799253, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.45068520503711273}}
{"text": "#include <catch2/catch.hpp>\n#include <mitama/mana/data/type_list.hpp>\n#include <mitama/mana/algorithm/chunk.hpp>\n#include <mitama/mana/core/metafunc.hpp>\n#include <mitama/mana/utility/iota.hpp>\n#include <type_traits>\n#include <iostream>\n#include <boost/type_index.hpp>\nnamespace mana = mitama::mana;\n\nTEST_CASE(\"chunk<2>\", \"[algorithm][chunk]\") {\n    REQUIRE(std::is_same_v<\n        decltype(mana::chunk<2>(mana::type_list_c<int, int, double, double>)),\n        mana::type_list<mana::type_list<int, int>, mana::type_list<double, double>>>);\n\n    REQUIRE(std::is_same_v<\n        decltype(mana::chunk<2>(mana::iota<0, 10>)),\n        mana::type_list<mana::value_list<0ul, 1ul>,\n                        mana::value_list<2ul, 3ul>,\n                        mana::value_list<4ul, 5ul>,\n                        mana::value_list<6ul, 7ul>,\n                        mana::value_list<8ul, 9ul>\n                        >>);\n}\n", "meta": {"hexsha": "d5d1e27e2bbff787298e355aa641e21a86048fd6", "size": 913, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/algorithm-tests/chunk.cpp", "max_stars_repo_name": "LoliGothick/mitama-mana", "max_stars_repo_head_hexsha": "32ba02356b6e2bbfdbadd4dd6f8054b2aa1af898", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-07-25T01:42:22.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-25T01:42:22.000Z", "max_issues_repo_path": "tests/algorithm-tests/chunk.cpp", "max_issues_repo_name": "LoliGothick/mitama-mana", "max_issues_repo_head_hexsha": "32ba02356b6e2bbfdbadd4dd6f8054b2aa1af898", "max_issues_repo_licenses": ["MIT"], "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/algorithm-tests/chunk.cpp", "max_forks_repo_name": "LoliGothick/mitama-mana", "max_forks_repo_head_hexsha": "32ba02356b6e2bbfdbadd4dd6f8054b2aa1af898", "max_forks_repo_licenses": ["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.52, "max_line_length": 86, "alphanum_fraction": 0.6013143483, "num_tokens": 246, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799252, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.45068520503711257}}
{"text": "///////////////////////////////////////////////////////////////\n//  Copyright 2011 John Maddock. Distributed under the Boost\n//  Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt\n\n//[mpfr_eg\n#include <boost/multiprecision/mpfr.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n#include <iostream>\n\nint main()\n{\n   using namespace boost::multiprecision;\n\n   // Operations at variable precision and no numeric_limits support:\n   mpfr_float a = 2;\n   mpfr_float::default_precision(1000);\n   std::cout << mpfr_float::default_precision() << std::endl;\n   std::cout << sqrt(a) << std::endl; // print root-2\n\n   // Operations at fixed precision and full numeric_limits support:\n   mpfr_float_100 b = 2;\n   std::cout << std::numeric_limits<mpfr_float_100>::digits << std::endl;\n   // We can use any C++ std lib function:\n   std::cout << log(b) << std::endl; // print log(2)\n   // We can also use any function from Boost.Math:\n   std::cout << boost::math::tgamma(b) << std::endl;\n   // These even work when the argument is an expression template:\n   std::cout << boost::math::tgamma(b * b) << std::endl;\n\n   // Access the underlying data:\n   mpfr_t r;\n   mpfr_init(r);\n   mpfr_set(r, b.backend().data(), GMP_RNDN);\n   mpfr_clear(r);\n   return 0;\n}\n//]\n\n\n", "meta": {"hexsha": "e0ac6aebc5efc4b8c4d386c0fbccc2a8a9444d60", "size": 1323, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/libs/multiprecision/example/mpfr_snips.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/mpfr_snips.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/mpfr_snips.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": 32.2682926829, "max_line_length": 73, "alphanum_fraction": 0.6462585034, "num_tokens": 347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799252, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.45068520503711257}}
{"text": "#include <tradelayer/mdex.h>\n#include <tradelayer/dex.h>\n#include <tradelayer/tradelayer.h>\n#include <tradelayer/uint256_extensions.h>\n#include <test/test_bitcoin.h>\n#include <boost/test/unit_test.hpp>\n#include <stdint.h>\n\nusing namespace mastercore;\n\nBOOST_FIXTURE_TEST_SUITE(tradelayer_mdex_functions_tests, BasicTestingSetup)\n\nvoid literVolume(int64_t& amount, uint32_t propertyId, const int& fblock, const int& sblock, const std::map<int, std::map<uint32_t,int64_t>>& aMap)\n{\n    // BOOST_TEST_MESSAGE(\"iter, fblock:\" << fblock);\n    // BOOST_TEST_MESSAGE(\"iter, sblock:\" << sblock);\n    for(const auto &m : aMap)\n    {\n        const int& blk = m.first;\n        // BOOST_TEST_MESSAGE(\"iter, block (after):\" << blk);\n        if(blk < fblock && fblock != 0){\n            continue;\n        } else if(sblock < blk){\n            break;\n        }\n\n        // BOOST_TEST_MESSAGE(\"iter, block:\" << blk);\n\n        const auto &blockMap = m.second;\n        auto itt = blockMap.find(propertyId);\n        // BOOST_TEST_MESSAGE(\"iter, propertyId:\" << propertyId);\n        if (itt != blockMap.end()){\n\n            const int64_t& newAmount = itt->second;\n\n            // overflows?\n            assert(!isOverflow(amount, newAmount));\n            amount += newAmount;\n            // BOOST_TEST_MESSAGE(\"iter, amount (after):\" << amount);\n\n        }\n\n    }\n\n}\n\nint64_t lgetVWap(uint32_t propertyId, int aBlock, const std::map<uint32_t,std::map<int,std::vector<std::pair<int64_t,int64_t>>>>& aMap)\n{\n    int64_t volume = 0;\n    arith_uint256 nvwap = 0;\n    const int rollback = aBlock - 12;\n\n    // BOOST_TEST_MESSAGE(\"rollback:\" << rollback);\n\n    auto it = aMap.find(propertyId);\n    if (it != aMap.end())\n    {\n        auto &vmap = it->second;\n        auto itt = (rollback > 0) ? find_if(vmap.begin(), vmap.end(), [&rollback] (const std::pair<int,std::vector<std::pair<int64_t,int64_t>>>& int_arith_pair) { return (int_arith_pair.first >= rollback);}) : vmap.begin();\n        if (itt != vmap.end())\n        {\n            for ( ; itt != vmap.end(); ++itt)\n            {\n                auto v = itt->second;\n                for_each(v.begin(),v.end(), [&nvwap](const std::pair<int64_t,int64_t>& num){ nvwap += ConvertTo256(num.first * (num.second / COIN));});\n            }\n        }\n\n    }\n    // calculating the volume\n    // BOOST_TEST_MESSAGE(\"rollback:\" << rollback);\n    // BOOST_TEST_MESSAGE(\"aBlock:\" << aBlock);\n    literVolume(volume, propertyId, rollback, aBlock, MapLTCVolume);\n\n    if (volume == 0) BOOST_TEST_MESSAGE(\"volume here is 0\");\n\n    // BOOST_TEST_MESSAGE(\"nvwap:\" << ConvertTo64(nvwap));\n    // BOOST_TEST_MESSAGE(\"volume:\" << volume);\n    return ((volume > 0) ? (COIN *(ConvertTo64(nvwap) / volume)) : 0);\n\n}\n\nint64_t lincreaseLTCVolume(uint32_t propertyId, uint32_t propertyDesired, int aBlock)\n{\n    int64_t total = 0, propertyAmount = 0, propertyDesiredAmount = 0;\n    const int rollback = aBlock - 1000;\n    iterVolume(propertyAmount, propertyId, rollback, aBlock, MapLTCVolume);\n    iterVolume(propertyDesiredAmount, propertyDesired, rollback, aBlock, MapLTCVolume);\n\n    // BOOST_TEST_MESSAGE(\"propertyAmount:\" << propertyAmount);\n    // BOOST_TEST_MESSAGE(\"propertyDesiredAmount:\" << propertyDesiredAmount);\n    // BOOST_TEST_MESSAGE(\"aBlock:\" << aBlock);\n    // BOOST_TEST_MESSAGE(\"rollback:\" << rollback);\n\n    if (1000 * COIN <=  propertyAmount && 1000 * COIN <=  propertyDesiredAmount)\n    {\n\n        // look up the 12-block VWAP of the denominator vs. LTC\n        const int64_t vwap = getVWap(propertyDesired, aBlock, tokenvwap);\n        const arith_uint256 aTotal = (ConvertTo256(propertyDesiredAmount) * ConvertTo256(vwap)) / ConvertTo256(COIN);\n        total = ConvertTo64(aTotal);\n        // BOOST_TEST_MESSAGE(\"vwap:\" << vwap);\n        // BOOST_TEST_MESSAGE(\"propertyDesiredAmount:\" << propertyDesiredAmount);\n        // BOOST_TEST_MESSAGE(\"total:\" << total);\n\n        // increment cumulative LTC volume by tokens traded * the 12-block VWAP\n        MapLTCVolume[aBlock][propertyDesired] += total;\n\n    }\n\n    return total;\n\n}\n\nBOOST_AUTO_TEST_CASE(getvwap_function)\n{\n    const uint32_t propertyId = 3;\n    // actual block\n    const int aBlock = 10250;\n\n    // adding  amount *  price\n    tokenvwap[propertyId][aBlock - 1].push_back(std::make_pair(2000 * COIN, 1500 * COIN));\n    tokenvwap[propertyId][aBlock - 2].push_back(std::make_pair(2000 * COIN, 1600 * COIN));\n    tokenvwap[propertyId][aBlock - 3].push_back(std::make_pair(2000 * COIN, 1700 * COIN));\n    tokenvwap[propertyId][aBlock - 3].push_back(std::make_pair(2000 * COIN, 1800 * COIN));\n    tokenvwap[propertyId][aBlock - 4].push_back(std::make_pair(2000 * COIN, 1900 * COIN));\n\n    // adding some volume\n    MapLTCVolume[aBlock - 1][propertyId] += 2000 * COIN;\n    MapLTCVolume[aBlock - 2][propertyId] += 1000 * COIN;\n    MapLTCVolume[aBlock - 3][propertyId] += 3000 * COIN;\n    MapLTCVolume[aBlock - 4][propertyId] += 4000 * COIN;\n\n    // checking vwap:   17000000 / 10000 = 1700\n    BOOST_CHECK_EQUAL(1700 * COIN, lgetVWap(propertyId, aBlock, tokenvwap));\n\n    // cleaning maps\n    tokenvwap.clear();\n    MapLTCVolume.clear();\n}\n\nBOOST_AUTO_TEST_CASE(increase_ltc_volume_function)\n{\n    const uint32_t propertyId = 1;\n    const uint32_t propertyDesired = 2;\n    // actual block\n    const int aBlock = 10250;\n\n    // adding  amount *  price\n    tokenvwap[propertyId][aBlock - 10].push_back(std::make_pair(1000 * COIN, 1500 * COIN));\n    tokenvwap[propertyId][aBlock - 10].push_back(std::make_pair(3000 * COIN, 1500 * COIN));\n\n    tokenvwap[propertyDesired][aBlock - 10].push_back(std::make_pair(1000 * COIN, 1500 * COIN));\n    tokenvwap[propertyDesired][aBlock - 10].push_back(std::make_pair(3000 * COIN, 1500 * COIN));\n\n\n    // adding some volume\n    MapLTCVolume[aBlock - 10][propertyId] = 2000 * COIN;\n    MapLTCVolume[aBlock - 10][propertyDesired] = 2000 * COIN;\n\n\n    // 12-vwap * amountdesired = 3000 * 2000 = 6000000\n    BOOST_CHECK_EQUAL(6000000 * COIN, lincreaseLTCVolume(propertyId, propertyDesired, aBlock));\n\n\n}\n\n\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "8134fdae73accf1cdba007307d6ff502bce99950", "size": 6048, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tradelayer/test/mdex_functions_tests.cpp", "max_stars_repo_name": "patrickdugan/BlockPo-to-Tradelayer", "max_stars_repo_head_hexsha": "ba1ebf3c329751d414302577a09481ba28db1815", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/tradelayer/test/mdex_functions_tests.cpp", "max_issues_repo_name": "patrickdugan/BlockPo-to-Tradelayer", "max_issues_repo_head_hexsha": "ba1ebf3c329751d414302577a09481ba28db1815", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2021-06-21T21:21:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-22T20:10:16.000Z", "max_forks_repo_path": "src/tradelayer/test/mdex_functions_tests.cpp", "max_forks_repo_name": "patrickdugan/BlockPo-to-Tradelayer", "max_forks_repo_head_hexsha": "ba1ebf3c329751d414302577a09481ba28db1815", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2022-02-23T11:44:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-25T07:49:23.000Z", "avg_line_length": 35.3684210526, "max_line_length": 223, "alphanum_fraction": 0.6506283069, "num_tokens": 1752, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4506170902755016}}
{"text": "/* Copyright (c) 2015, Julian Straub <jstraub@csail.mit.edu>                    \n * Licensed under the MIT license. See the license file LICENSE.                \n */\n\n#pragma once\n#include <Eigen/Dense>\n#include <iostream>\n\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/shared_ptr.hpp>\n\n#include \"sphere.hpp\"\n#include \"karcherMean.hpp\"\n#include \"kmeans.hpp\"\n#include \"clusterer.hpp\"\n\nusing namespace Eigen;\nusing std::cout;\nusing std::endl;\n\ntemplate<class T>\nclass SphericalKMeans : public KMeans<T>\n{\npublic:\n  SphericalKMeans(const boost::shared_ptr<Matrix<T,Dynamic,Dynamic> >& spx, uint32_t K,\n    boost::mt19937* pRndGen);\n  virtual ~SphericalKMeans();\n\n//  void initialize(const Matrix<T,Dynamic,Dynamic>& x);\n\n//  virtual void updateLabels();\n//  virtual void updateCenters();\n//  virtual MatrixXu mostLikelyInds(uint32_t n, Matrix<T,Dynamic,Dynamic>& deviates);\n//  virtual T avgIntraClusterDeviation();\n\n  virtual T dist(const Matrix<T,Dynamic,1>& a, const Matrix<T,Dynamic,1>& b);\n  virtual bool closer(T a, T b);\n  virtual uint32_t indOfClosestCluster(int32_t i);\n  virtual Matrix<T,Dynamic,1> computeCenter(uint32_t k);\n\n};\n\ntemplate<class T>\nclass SphericalKMeansKarcher : public SphericalKMeans<T>\n{\npublic:\n  SphericalKMeansKarcher(const boost::shared_ptr<Matrix<T,Dynamic,Dynamic> >& spx, \n      uint32_t K, boost::mt19937* pRndGen);\n  ~SphericalKMeansKarcher();\n\n//  void initialize(const Matrix<T,Dynamic,Dynamic>& x);\n\n  virtual Matrix<T,Dynamic,1> computeCenter(uint32_t k);\n};\n\n// --------------------------------- impl -------------------------------------\ntemplate<class T>\nSphericalKMeans<T>::SphericalKMeans(\n    const boost::shared_ptr<Matrix<T,Dynamic,Dynamic> >& spx, uint32_t K,\n    boost::mt19937* pRndGen)\n  : KMeans<T>(spx,K, pRndGen)\n{}\n\ntemplate<class T>\nSphericalKMeans<T>::~SphericalKMeans()\n{}\n\ntemplate<class T>\nT SphericalKMeans<T>::dist(const Matrix<T,Dynamic,1>& a, const Matrix<T,Dynamic,1>& b)\n{\n  return acos(min(1.0,max(-1.0,(a.transpose()*b)(0)))); // angular similarity\n//  return a.transpose()*b; // cosine similarity \n};\n\ntemplate<class T>\nbool SphericalKMeans<T>::closer(T a, T b)\n{\n  return a<b; // if dist a is greater than dist b a is closer than b (angular dist)\n//  return a>b; // if dist a is greater than dist b a is closer than b (cosine dist)\n};\n\ntemplate<class T>\nMatrix<T,Dynamic,1> SphericalKMeans<T>::computeCenter(uint32_t k)\n{\n  this->Ns_(k) = 0.0;\n  Matrix<T,Dynamic,1> mean_k(this->D_);\n  mean_k.setZero(this->D_);\n  for(uint32_t i=0; i<this->N_; ++i)\n    if(this->z_(i) == k)\n    {\n      mean_k += this->spx_->col(i); \n      this->Ns_(k) ++;\n    }\n  return mean_k/mean_k.norm();\n}\n\ntemplate<class T>\nuint32_t SphericalKMeans<T>::indOfClosestCluster(int32_t i)\n{\n  // use cosine similarity because it is faster since acos is not computed\n  T sim_closest = this->ps_.col(0).transpose() * this->spx_->col(i);\n  uint32_t z_i = 0;\n  for(uint32_t k=1; k<this->K_; ++k)\n  {\n    T sim_k = this->ps_.col(k).transpose()* this->spx_->col(i);\n    if( sim_k > sim_closest) // because of cosine distance\n    {\n      sim_closest = sim_k;\n      z_i = k;\n    }\n  }\n  return z_i;\n};\n\n//template<class T>\n//void SphericalKMeans<T>::initialize(const Matrix<T,Dynamic,Dynamic>& x)\n//{\n//  \n//}\n//\ntemplate<class T>\nSphericalKMeansKarcher<T>::SphericalKMeansKarcher(\n    const boost::shared_ptr<Matrix<T,Dynamic,Dynamic> >& spx, uint32_t K,\n    boost::mt19937* pRndGen)\n  : SphericalKMeans<T>(spx,K,pRndGen)\n{}\n\ntemplate<class T>\nSphericalKMeansKarcher<T>::~SphericalKMeansKarcher()\n{}\n\ntemplate<class T>\nMatrix<T,Dynamic,1> SphericalKMeansKarcher<T>::computeCenter(uint32_t k)\n{\n  Matrix<T,Dynamic,Dynamic> xPs(this->spx_->rows(),this->spx_->cols());\n  Matrix<T,Dynamic,1> mean_k = karcherMean<T>(this->ps_.col(k), *(this->spx_), \n        xPs, this->z_, k, 100,1);\n  this->Ns_(k) = 0.0;\n  for(uint32_t i=0; i<this->N_; ++i)\n    if(this->z_(i) == k)\n    {\n      this->Ns_(k) ++;\n    }\n  return mean_k;\n}\n\n//template<class T>\n//void SphericalKMeansKarcher<T>::updateCenters()\n//{\n//  Matrix<T,Dynamic,Dynamic> xPs(this->spx_->rows(),this->spx_->cols());\n//#pragma omp parallel for\n//  for(uint32_t k=0; k<this->K_; ++k)\n//  {\n////    Matrix<T,Dynamic,1> w(this->N_);\n////    for(uint32_t i=0; i<this->N_; ++i)\n////      if(this->z_(i) == k) \n////        w(i) = 1.0;\n////      else\n////        w(i) = 0.0;\n////    this->ps_.col(k) = karcherMeanWeighted<T>(this->ps_.col(k), *(this->spx_), w, 100);\n//    this->ps_.col(k) = karcherMean<T>(this->ps_.col(k), *(this->spx_), \n//        xPs, this->z_, k, 100,1);\n//  }\n//}\n", "meta": {"hexsha": "09334c13adb41fe0bd7af92a7522ba2e4391be12", "size": 4578, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/deprecated/sphericalKMeans.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/deprecated/sphericalKMeans.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/deprecated/sphericalKMeans.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": 27.7454545455, "max_line_length": 91, "alphanum_fraction": 0.6465705548, "num_tokens": 1429, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.45061709027550156}}
{"text": "#pragma once\n\n#include <array>\n#include <utility>\n#include <string>\n#include <stdexcept>\n#include <Eigen/Dense>\n\n#include \"fusion_layer/temporal_aligner.hpp\"\n#include \"object_model_msgs/msg/object_model.hpp\"\n#include \"types.hpp\"\n\nclass TemporalAlignerEKF : public TemporalAligner {\n    bool is_initialized;\n\n    ctra_array_t state_array;\n\n    ctra_matrix_t P;\n    ctra_matrix_t Q;\n\n public:\n    TemporalAlignerEKF();\n    TemporalAlignerEKF(const state_t& initial_state);\n\n    /*\n     * Index for ctra_state.\n     *\n     * In this work heading is different from yaw. Heading is about the direction the object is going (velocity vector direction),\n     *   and yaw is the orientation of the object.\n     */\n    enum CTRAIndexes {X_IDX, Y_IDX, HEADING_IDX, VELOCITY_IDX, YAW_RATE_IDX, ACCELERATION_IDX};\n    \n    state_t align(float delta_t);\n    static void align(float delta_t, state_t& state, ctra_squared_t& covariation);\n\n    state_t get_state() const;\n    void update(const state_t& measurement, const ctra_squared_t& measurement_noise_matrix, const capable_vector_t& capable);\n\n    /*\n    * From [x, y, heading, v, yaw_rate, a] to [x, y, vx, vy, ax, ay, yaw, yaw_rate]\n    * yaw must be replaced in the result manually\n    */\n    static state_t format_to_object_model(const ctra_array_t& state, float yaw, float velocity_heading, float acceleration_heading);\n\n    /*\n    * From [x, y, vx, vy, ax, ay, yaw, yaw_rate] to [x, y, heading, v, yaw_rate, a]\n    */\n    static ctra_array_t format_from_object_model(const state_t& state);\n\n    static std::pair<float, float> get_headings(const state_t& state);\n\n private:\n    void predict(float delta_t);\n\n    static void predict(float delta_t, ctra_array_t& state, ctra_matrix_t& covariation);\n\n    static ctra_matrix_t calculate_process_noise(float delta_t);\n\n    static ctra_array_t predict_state(float delta_t, const ctra_array_t& state);\n\n    static ctra_matrix_t predict_covariation(float delta_t, const ctra_array_t& state, const ctra_matrix_t& covariation, const ctra_matrix_t& process_noise);\n\n    static ctra_matrix_t gen_ja_matrix(float delta_t, const ctra_array_t& state);\n\n    static void disable_not_capable_attributes(ctra_matrix_t& JH, const capable_vector_t& capable);\n};\n", "meta": {"hexsha": "212aff24f40b829916bf0a54a39616c5e8a3409f", "size": 2234, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "fusion_layer/include/fusion_layer/temporal_aligner_ekf.hpp", "max_stars_repo_name": "icaropires/objectlevel_fusion", "max_stars_repo_head_hexsha": "ef76835ac5f0475eee8098e66c7a1baa9f4d1f96", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-05-26T18:04:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T14:07:09.000Z", "max_issues_repo_path": "fusion_layer/include/fusion_layer/temporal_aligner_ekf.hpp", "max_issues_repo_name": "icaropires/objectlevel_fusion", "max_issues_repo_head_hexsha": "ef76835ac5f0475eee8098e66c7a1baa9f4d1f96", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fusion_layer/include/fusion_layer/temporal_aligner_ekf.hpp", "max_forks_repo_name": "icaropires/objectlevel_fusion", "max_forks_repo_head_hexsha": "ef76835ac5f0475eee8098e66c7a1baa9f4d1f96", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-23T14:05:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T14:05:28.000Z", "avg_line_length": 33.3432835821, "max_line_length": 157, "alphanum_fraction": 0.7372426141, "num_tokens": 566, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389817407016, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4506170834570813}}
{"text": "//\n// Created by everettjf on 2019-09-29.\n//\n\n#include \"utils.h\"\n#include <unistd.h>\n#include \"networkhandler.h\"\n#include \"dep/logic/tinyformat.h\"\n#include \"dep/logic/anybase.h\"\n#include <boost/algorithm/string.hpp>\n#include <vector>\n#include <boost/lexical_cast.hpp>\n\nnamespace utils {\n\n\nstd::string ip2code(const std::string & ip) {\n    std::vector<std::string> result;\n    boost::split(result, ip, boost::is_any_of(\".\"));\n    if (result.size() != 4) {\n        return \"\";\n    }\n\n    int n0=0,n1=0,n2=0,n3=0;\n    try {\n        n0 = boost::lexical_cast<int>(result[0]);\n        n1 = boost::lexical_cast<int>(result[1]);\n        n2 = boost::lexical_cast<int>(result[2]);\n        n3 = boost::lexical_cast<int>(result[3]);\n    }catch(const boost::bad_lexical_cast &) {\n        return \"\";\n    }\n\n    if (n0 == 192 && n1 == 168) {\n        long codeBase10 = n2 * 256 + n3;\n\n        std::string codeBase36 = anybase::Decimal2AnyBase(codeBase10, 32);\n        return tfm::format(\"x%s\",codeBase36);\n    } else {\n        long codeBase10 = n0 * 256 * 256 * 256 +\n                          n1 * 256 * 256 +\n                          n2 * 256 +\n                          n3;\n\n        std::string codeBase36 = anybase::Decimal2AnyBase(codeBase10, 32);\n        return codeBase36;\n    }\n}\n\n}\n", "meta": {"hexsha": "570226f3c876f969cade042ab3baa109ea0a28ae", "size": 1275, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "android/remotekb/app/src/main/cpp/utils.cpp", "max_stars_repo_name": "remoboard/remoboard-source", "max_stars_repo_head_hexsha": "cb045560f2833ef1a4b1dd1ec0c20b0e9d0da404", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 82.0, "max_stars_repo_stars_event_min_datetime": "2020-08-09T16:44:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-13T03:21:49.000Z", "max_issues_repo_path": "android/remotekb/app/src/main/cpp/utils.cpp", "max_issues_repo_name": "remoboard/remoboard-source", "max_issues_repo_head_hexsha": "cb045560f2833ef1a4b1dd1ec0c20b0e9d0da404", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-08-10T03:24:13.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-10T03:24:13.000Z", "max_forks_repo_path": "android/remotekb/app/src/main/cpp/utils.cpp", "max_forks_repo_name": "remoboard/remoboard-source", "max_forks_repo_head_hexsha": "cb045560f2833ef1a4b1dd1ec0c20b0e9d0da404", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2020-08-09T16:46:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-09T17:19:34.000Z", "avg_line_length": 25.0, "max_line_length": 74, "alphanum_fraction": 0.56, "num_tokens": 367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154240079185319, "lm_q2_score": 0.6297746004557471, "lm_q1q2_score": 0.45055586874334264}}
{"text": "//  (C) Copyright Matt Borland 2021.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n//\n//  Constepxr implementation of fabs (see c.math.abs secion 26.8.2 of the ISO standard)\n\n#ifndef BOOST_MATH_CCMATH_FABS\n#define BOOST_MATH_CCMATH_FABS\n\n#include <boost/math/ccmath/abs.hpp>\n\nnamespace boost::math::ccmath {\n\ntemplate <typename T>\ninline constexpr auto fabs(T x) noexcept\n{\n    return boost::math::ccmath::abs(x);\n}\n\ninline constexpr float fabsf(float x) noexcept\n{\n    return boost::math::ccmath::abs(x);\n}\n\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\ninline constexpr long double fabsl(long double x) noexcept\n{\n    return boost::math::ccmath::abs(x);\n}\n#endif\n\n}\n\n#endif // BOOST_MATH_CCMATH_FABS\n", "meta": {"hexsha": "6d0b565b6d10e9fab45bfaabe132dc42aae83257", "size": 850, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/math/ccmath/fabs.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/ccmath/fabs.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/ccmath/fabs.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": 23.6111111111, "max_line_length": 87, "alphanum_fraction": 0.7458823529, "num_tokens": 228, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.4505558660722336}}
{"text": "#pragma once\n\n#include \"set_stream_precision.hxx\"\n\n#include <boost/multiprecision/mpfr.hpp>\n#include <sstream>\n\nusing Boost_Float = boost::multiprecision::mpfr_float;\n\ninline std::string to_string(const Boost_Float &boost_float)\n{\n  // Using a stringstream seems to the best way to convert between\n  // MPFR and GMP.  It may lose a bit or two since string\n  // conversion is not sufficient for round-tripping.\n  std::stringstream ss;\n  set_stream_precision(ss);\n  ss << boost_float;\n  return ss.str();\n}\n\n", "meta": {"hexsha": "b561a7c27ed628447f2ec779c85eec04b8250844", "size": 505, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "src/Boost_Float.hxx", "max_stars_repo_name": "ChrisPattison/sdpb", "max_stars_repo_head_hexsha": "4668f72c935e7feba705dd8247d9aacb23185f1c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 45.0, "max_stars_repo_stars_event_min_datetime": "2015-02-10T15:45:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T07:45:01.000Z", "max_issues_repo_path": "src/Boost_Float.hxx", "max_issues_repo_name": "ChrisPattison/sdpb", "max_issues_repo_head_hexsha": "4668f72c935e7feba705dd8247d9aacb23185f1c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 58.0, "max_issues_repo_issues_event_min_datetime": "2015-02-27T10:03:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-10T04:21:42.000Z", "max_forks_repo_path": "src/Boost_Float.hxx", "max_forks_repo_name": "ChrisPattison/sdpb", "max_forks_repo_head_hexsha": "4668f72c935e7feba705dd8247d9aacb23185f1c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 38.0, "max_forks_repo_forks_event_min_datetime": "2015-02-10T11:11:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-11T20:59:42.000Z", "avg_line_length": 24.0476190476, "max_line_length": 66, "alphanum_fraction": 0.7465346535, "num_tokens": 119, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.4505558660722336}}
{"text": "//\n// Project: panoramachine\n// File: Momentum.hpp\n//\n// Copyright (c) 2022 Miika 'Lehdari' Lehtim\u00e4ki\n// You may use, distribute and modify this code under the terms\n// of the licence specified in file LICENSE which is distributed\n// with this source code package.\n//\n\n#ifndef PANORAMACHINE_MOMENTUM_HPP\n#define PANORAMACHINE_MOMENTUM_HPP\n\n\n#include <Eigen/Dense>\n\n\ntemplate <typename T>\nclass Momentum {\npublic:\n    Momentum(double momentum, const T& v = T()) :\n        _momentum   (momentum),\n        _variance   (0.0*T()),\n        _v          (v)\n    {}\n\n    const T& operator()(const T& v)\n    {\n        T variance = std::pow(v-_v, 2.0);\n        _variance = _momentum*_variance + (1.0-_momentum)*variance;\n        _v = _momentum*_v + (1.0-_momentum)*v;\n        return _v;\n    }\n\n    operator const T&() const\n    {\n        return _v;\n    }\n\n    const T& variance() const\n    {\n        return std::sqrt(_variance);\n    }\n\nprivate:\n    double      _momentum;\n    T           _variance;\n    T           _v;\n};\n\n\ntemplate <typename T_Scalar, int Rows, int Cols>\nclass Momentum<Eigen::Matrix<T_Scalar, Cols, Rows>> {\nprivate:\n    using T = Eigen::Matrix<T_Scalar, Cols, Rows>;\n\npublic:\n    Momentum(T_Scalar momentum, const T& v = T()) :\n        _momentum   (momentum),\n        _variance   (0.0*T()),\n        _v          (v)\n    {}\n\n    const T& operator()(const T& v)\n    {\n        T variance = (v-_v).array().square().matrix();\n        _variance = _momentum*_variance + (1.0-_momentum)*variance;\n        _v = _momentum*_v + (1.0-_momentum)*v;\n        return _v;\n    }\n\n    operator const T&() const\n    {\n        return _v;\n    }\n\n    T_Scalar variance() const\n    {\n        return _variance.cwiseSqrt().norm();\n    }\n\nprivate:\n    T_Scalar    _momentum;\n    T           _variance;\n    T           _v;\n};\n\n\n\n#endif //PANORAMACHINE_MOMENTUM_HPP\n", "meta": {"hexsha": "9d5ecf53bc2f40f53e53607fa561f425106ad097", "size": 1845, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/Momentum.hpp", "max_stars_repo_name": "Lehdari/Panoramachine", "max_stars_repo_head_hexsha": "af00840e8a2b2f5cd8bde4e8cd4037b9c7d43178", "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": "include/Momentum.hpp", "max_issues_repo_name": "Lehdari/Panoramachine", "max_issues_repo_head_hexsha": "af00840e8a2b2f5cd8bde4e8cd4037b9c7d43178", "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": "include/Momentum.hpp", "max_forks_repo_name": "Lehdari/Panoramachine", "max_forks_repo_head_hexsha": "af00840e8a2b2f5cd8bde4e8cd4037b9c7d43178", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.2747252747, "max_line_length": 67, "alphanum_fraction": 0.5739837398, "num_tokens": 541, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.4505558660722336}}
{"text": "/**\n *  testReachSet.cpp\n *\n *  Test abstraction by using a car kinematics model.\n *\n *  Created by Yinan Li on Nov. 25, 2020.\n *  Hybrid Systems Group, University of Waterloo.\n */\n\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <string>\n#include <algorithm>\n#include <cmath>\n#include <sys/stat.h>\n#include <boost/numeric/odeint.hpp>\n\n#include \"src/grid.h\"\n#include \"src/definitions.h\"\n#include \"src/abstraction.hpp\"\n#include \"src/hdf5io.h\"\n\n\nconst double h = 0.3;  // sampling time\nconst double dt = 0.001; //integration step size for odeint\n\n/* For reachable set computation */\nstruct twoagent {\n    static const int n = 3;  // system dimension\n    static const int nu = 2;  // control dimension\n    rocs::ivec d{rocs::interval(-0.8, 0.8),\n\t\t rocs::interval(-0.8, 0.8)};\n\n    /* template constructor\n     * @param[out] dx\n     * @param[in] x = [xr, yr, psir]\n     * @param u = [v, w]\n     * @param d = [v', w']\n     */\n    template<typename S>\n    twoagent(S *dx, const S *x, rocs::Rn u) {\n\tdx[0] = -u[0] + d[0]*cos(x[2]) + u[1]*x[1];\n\tdx[1] = d[0]*sin(x[2]) - u[1]*x[0];\n\tdx[2] = d[1] - u[1];\n    }\n};\n\n/* For solving ode */\nstruct car_ode {\n    rocs::Rn u;\n    rocs::Rn d;\n    car_ode (const rocs::Rn p1, const rocs::Rn p2): u(p1), d(p2){}\n    /**\n     * ODE model\n     * @param x system state: [x,y,theta], n=3\n     * @param dxdt vector field\n     * @param t time\n     */\n    void operator() (rocs::Rn &x, rocs::Rn &dxdt, double t) const\n    {\n\tdxdt[0] = -u[0] + d[0]*cos(x[2]) + u[1]*x[1];\n\tdxdt[1] = d[0]*sin(x[2]) - u[1]*x[0];\n\tdxdt[2] = d[1] - u[1];\n    }\n};\n\n\nint main()\n{\n    /* Config */\n    clock_t tb, te;\n    boost::numeric::odeint::runge_kutta_cash_karp54<rocs::Rn> rk45;\n\n    /**\n     * Case I\n     */\n    /* Set the state and control space */\n    const int xdim = 3;\n    const int udim = 2;\n    \n    double xlb[] = {-3, -3, -M_PI};\n    double xub[] = {3, 3, M_PI};\n    double eta[] = {0.2, 0.2, 0.2};\n    \n    double ulb[] = {-1.0, -1.0};\n    double uub[] = {1.0, 1.0};\n    double mu[] = {0.3, 0.3};\n\n    /**\n     * Define the two-agent system\n     */\n    double t = 0.3;\n    double delta = 0.01;\n    /* parameters for computing the flow */\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<twoagent> safety(\"collision-free\", t,\n    \t\t\t\t     twoagent::n, twoagent::nu,\n    \t\t\t\t     delta, &controlparams);\n\n    safety.init_workspace(xlb, xub);\n    safety.init_inputset(mu, ulb, uub);\n    safety.allocate_flows();\n\n    rocs::abstraction< rocs::CTCntlSys<twoagent> > abst(&safety);\n    abst.init_state(eta, xlb, xub);\n    std::cout << \"# of in-domain nodes: \" << abst._x._nv << '\\n';\n\n\n    /* Test reachable set computation */\n    int suc = 1;\n    size_t na = safety._ugrid._nv;\n    rocs::Rn x_test{-1.4, 0.6, -1.9};\n    // rocs::Rn x_test{1.4, 0.6, -1.9};\n    rocs::ivec x0 = {rocs::interval(x_test[0]-eta[0]/2., x_test[0]+eta[0]/2.),\n\t\t     rocs::interval(x_test[1]-eta[1]/2., x_test[1]+eta[1]/2.),\n\t\t     rocs::interval(x_test[2]-eta[2]/2., x_test[2]+eta[2]/2.)};\n    std::cout << \"Checking rechable set computation for \" << x0 << \"...\\n\";\n    rocs::Rn u(udim);\n    rocs::Rn xpost(xdim);\n    rocs::ivec box(xdim);\n    std::vector<rocs::ivec> reachset(na, rocs::ivec(xdim));\n    rocs::Rn corner(xdim), p0(xdim);\n    int quo, rem;\n    rocs::ivec margin{rocs::interval(-rocs::EPSIVAL, rocs::EPSIVAL),\n    \t\t      rocs::interval(-rocs::EPSIVAL, rocs::EPSIVAL),\n    \t\t      rocs::interval(-rocs::EPSIVAL, rocs::EPSIVAL)};\n    rocs::ivec yt(xdim);\n    \n    safety.get_reach_set(reachset, x0);\n    std::vector<rocs::Rn> d(4, rocs::Rn {0.7, 0.7});\n    d[1][0] = -0.7;\n    d[2][0] = -0.7;\n    d[2][1] = -0.7;\n    d[3][1] = -0.7;\n    /* Test valid control inputs */\n    for(size_t j = 0; j < na; ++j) {\n\tsafety._ugrid.id_to_val(u, j); //get control values\n\tfor(auto de:d) {\n\t    /* Test if the reachable set covers ode solutions of all corners */\n\t    for(int k = 0; k < std::pow(2, xdim); ++k) {\n\t\tquo = k;\n\t\tfor(int l = 0; l < xdim; ++l) {\n\t\t    if(quo % 2) {\n\t\t\tcorner[l] = x_test[l]+eta[l]/2.; //upper bound\n\t\t\tp0[l] = corner[l];\n\t\t    } else {\n\t\t\tcorner[l] = x_test[l]-eta[l]/2.; //lower bound\n\t\t\tp0[l] = corner[l];\n\t\t    }\n\t\t    quo /= 2;\n\t\t}\n\t\t// std::cout << \"Corner \"\n\t\t// \t  << '(' << corner[0] << ',' << corner[1] << ',' << corner[2] << \")\\n\";\n\t\tboost::numeric::odeint::integrate_const(rk45, car_ode(u,de), corner, 0.0, h, dt);\n\t\tyt = reachset[j] + margin;\n\t\tif(!yt.isin(corner)) {\n\t\t    std::cout << \"Incorrect at u=\" << j\n\t\t\t      << '(' << u[0] << ',' << u[1] << ')'\n\t\t\t      << \", d=\" << '(' << de[0] << ',' << de[1] << \") for \"\n\t\t\t      << '(' << p0[0] << ',' << p0[1] << ',' << p0[2] << \"):\\n\"\n\t\t\t      << '(' << corner[0] << ',' << corner[1] << ',' << corner[2] << ')'\n\t\t\t      << \" is not in \" << yt << '\\n';\n\t\t    suc = 0;\n\t\t}\n\t    }\n\t}\n    }//end for control values\n\n    if(suc)\n\tstd::cout << \"The test point passes the test.\\n\";\n    \n    return suc;\n}\n", "meta": {"hexsha": "0609961f81972224236aa4f23531234476901805", "size": 5015, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/testReachSet.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": "test/testReachSet.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": "test/testReachSet.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": 28.0167597765, "max_line_length": 83, "alphanum_fraction": 0.5268195414, "num_tokens": 1844, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.4505558660722336}}
{"text": "#include <boost/test/unit_test.hpp>\n\n#include \"gridworld_route.h\"\n#include <fstream>\n#include \"logs.h\"\n#include \"types.h\"\n#include \"route.h\"\n\nusing namespace GPS;\n\n// This function generates GPXlogfiles with the given positions\nstd::string GPXlogFiles(std::string RoutePath, GridWorldRoute gridw)\n{\n    std::string routeName = RoutePath + \"_N0731739.gpx\";\n\n    std::ofstream finalroute(LogFiles::GPXRoutesDir + routeName);\n\n    finalroute << gridw.toGPX(true, RoutePath);\n\n    finalroute.close();\n\n    return routeName;\n}\n\n\n\n\nBOOST_AUTO_TEST_SUITE( Route_netLength_No731739)\n\nconst bool isFileName = true;\nconst metres horizontalGridUnit = 30000;\n\n// Single point on the gdidworld\nBOOST_AUTO_TEST_CASE ( SinglePoint )\n{\n    Route Qroute = Route(LogFiles::GPXRoutesDir + \"Q.gpx\", isFileName);\n    BOOST_CHECK_EQUAL( Qroute.netLength(), 0.0);\n}\n\n// First and last location are the same\nBOOST_AUTO_TEST_CASE ( SameFirstLastPoint )\n{\n    GridWorldRoute Logroute = GridWorldRoute(\"LOL\");\n    Route LOLroute = Route(LogFiles::GPXRoutesDir + GPXlogFiles(\"test4\",Logroute), isFileName);\n    BOOST_CHECK_EQUAL( LOLroute.netLength(), 0 );\n}\n// Using different points\nBOOST_AUTO_TEST_CASE ( differentPoints )\n{\n    GridWorldRoute Logroute = GridWorldRoute(\"VITA\");\n    Route VITAroute = Route(LogFiles::GPXRoutesDir + GPXlogFiles(\"test\",Logroute), isFileName);\n    BOOST_CHECK_EQUAL( VITAroute.netLength(), 41254.444525376712  );\n}\n\n// Longitude, latitude and elevation are zero\nBOOST_AUTO_TEST_CASE ( lon_lat_ele_0 )\n{\n    GridWorldRoute Logroute = GridWorldRoute(\"SNHB\" ,GridWorld(Earth::EquatorialMeridian,0,0));\n    Route SNHBroute = Route(LogFiles::GPXRoutesDir + GPXlogFiles(\"test1\",Logroute), isFileName);\n    BOOST_CHECK_EQUAL( SNHBroute.netLength(), 0  );\n}\n// Only longitude is zero\nBOOST_AUTO_TEST_CASE ( longitude_0 )\n{\n    GridWorldRoute Logroute = GridWorldRoute(\"QWERTYUIOP\" ,GridWorld(Earth::NorthPole,0,0));\n    Route QWERTYUIOProute = Route(LogFiles::GPXRoutesDir + GPXlogFiles(\"test2\",Logroute), isFileName);\n    BOOST_CHECK_EQUAL( QWERTYUIOProute.netLength(), 0  );\n}\n\n// Only latitude is zero\nBOOST_AUTO_TEST_CASE ( latitude_0 )\n{\n    GridWorldRoute Logroute = GridWorldRoute(\"MNO\");\n    Route MNOroute = Route(LogFiles::GPXRoutesDir + GPXlogFiles(\"test3\",Logroute), isFileName);\n    BOOST_CHECK_EQUAL( MNOroute.netLength(), 20015.114442036094  );\n}\n\n// Granularity is smaler than the netLength\nBOOST_AUTO_TEST_CASE( GranularityIsSmaler )\n{\n   const metres granularity = horizontalGridUnit * 0.99;\n   Route ABCDroute = Route(LogFiles::GPXRoutesDir + \"ABCD.gpx\", isFileName, granularity);\n   BOOST_CHECK_EQUAL( ABCDroute.netLength(), 30022.523566211392 );\n}\n// Granularity is bigger than the netLength\nBOOST_AUTO_TEST_CASE( GranularityIsBigger )\n{\n   const metres granularity = horizontalGridUnit * 1.01;\n   Route ABCDroute = Route(LogFiles::GPXRoutesDir + \"ABCD.gpx\", isFileName, granularity);\n   BOOST_CHECK_EQUAL( ABCDroute.netLength(), 0 );\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n\n\n\n", "meta": {"hexsha": "700b74fc1a9f8d91e9b9e83ba3db19d207f2f678", "size": 2989, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Unit Testing/netLength-N0731739.cpp", "max_stars_repo_name": "VitalyHarachka/Software-Engineering", "max_stars_repo_head_hexsha": "40a27cf5fd01fbef885b2c80931316482b24a1fe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Unit Testing/netLength-N0731739.cpp", "max_issues_repo_name": "VitalyHarachka/Software-Engineering", "max_issues_repo_head_hexsha": "40a27cf5fd01fbef885b2c80931316482b24a1fe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Unit Testing/netLength-N0731739.cpp", "max_forks_repo_name": "VitalyHarachka/Software-Engineering", "max_forks_repo_head_hexsha": "40a27cf5fd01fbef885b2c80931316482b24a1fe", "max_forks_repo_licenses": ["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.5, "max_line_length": 102, "alphanum_fraction": 0.75008364, "num_tokens": 819, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239836484144, "lm_q2_score": 0.6297746143530797, "lm_q1q2_score": 0.4505558634011242}}
{"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    DoglegOptimizer.h\n * @brief   Unit tests for DoglegOptimizer\n * @author  Richard Roberts\n */\n\n#include <CppUnitLite/TestHarness.h>\n\n#include <tests/smallExample.h>\n#include <gtsam/nonlinear/DoglegOptimizerImpl.h>\n#include <gtsam/inference/Symbol.h>\n#include <gtsam/linear/JacobianFactor.h>\n#include <gtsam/linear/GaussianBayesTree.h>\n#include <gtsam/base/numericalDerivative.h>\n\n#ifdef __GNUC__\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wunused-variable\"\n#endif\n#include <boost/bind.hpp>\n#ifdef __GNUC__\n#pragma GCC diagnostic pop\n#endif\n#include <boost/assign/list_of.hpp> // for 'list_of()'\n#include <functional>\n#include <boost/iterator/counting_iterator.hpp>\n\nusing namespace std;\nusing namespace gtsam;\n\n// Convenience for named keys\nusing symbol_shorthand::X;\nusing symbol_shorthand::L;\n\n/* ************************************************************************* */\nTEST(DoglegOptimizer, ComputeBlend) {\n  // Create an arbitrary Bayes Net\n  GaussianBayesNet gbn;\n  gbn += GaussianConditional::shared_ptr(new GaussianConditional(\n      0, (Vector(2) << 1.0,2.0), (Matrix(2, 2) << 3.0,4.0,0.0,6.0),\n      3, (Matrix(2, 2) << 7.0,8.0,9.0,10.0),\n      4, (Matrix(2, 2) << 11.0,12.0,13.0,14.0)));\n  gbn += GaussianConditional::shared_ptr(new GaussianConditional(\n      1, (Vector(2) << 15.0,16.0), (Matrix(2, 2) << 17.0,18.0,0.0,20.0),\n      2, (Matrix(2, 2) << 21.0,22.0,23.0,24.0),\n      4, (Matrix(2, 2) << 25.0,26.0,27.0,28.0)));\n  gbn += GaussianConditional::shared_ptr(new GaussianConditional(\n      2, (Vector(2) << 29.0,30.0), (Matrix(2, 2) << 31.0,32.0,0.0,34.0),\n      3, (Matrix(2, 2) << 35.0,36.0,37.0,38.0)));\n  gbn += GaussianConditional::shared_ptr(new GaussianConditional(\n      3, (Vector(2) << 39.0,40.0), (Matrix(2, 2) << 41.0,42.0,0.0,44.0),\n      4, (Matrix(2, 2) << 45.0,46.0,47.0,48.0)));\n  gbn += GaussianConditional::shared_ptr(new GaussianConditional(\n      4, (Vector(2) << 49.0,50.0), (Matrix(2, 2) << 51.0,52.0,0.0,54.0)));\n\n  // Compute steepest descent point\n  VectorValues xu = gbn.optimizeGradientSearch();\n\n  // Compute Newton's method point\n  VectorValues xn = gbn.optimize();\n\n  // The Newton's method point should be more \"adventurous\", i.e. larger, than the steepest descent point\n  EXPECT(xu.vector().norm() < xn.vector().norm());\n\n  // Compute blend\n  double Delta = 1.5;\n  VectorValues xb = DoglegOptimizerImpl::ComputeBlend(Delta, xu, xn);\n  DOUBLES_EQUAL(Delta, xb.vector().norm(), 1e-10);\n}\n\n/* ************************************************************************* */\nTEST(DoglegOptimizer, ComputeDoglegPoint) {\n  // Create an arbitrary Bayes Net\n  GaussianBayesNet gbn;\n  gbn += GaussianConditional::shared_ptr(new GaussianConditional(\n      0, (Vector(2) << 1.0,2.0), (Matrix(2, 2) << 3.0,4.0,0.0,6.0),\n      3, (Matrix(2, 2) << 7.0,8.0,9.0,10.0),\n      4, (Matrix(2, 2) << 11.0,12.0,13.0,14.0)));\n  gbn += GaussianConditional::shared_ptr(new GaussianConditional(\n      1, (Vector(2) << 15.0,16.0), (Matrix(2, 2) << 17.0,18.0,0.0,20.0),\n      2, (Matrix(2, 2) << 21.0,22.0,23.0,24.0),\n      4, (Matrix(2, 2) << 25.0,26.0,27.0,28.0)));\n  gbn += GaussianConditional::shared_ptr(new GaussianConditional(\n      2, (Vector(2) << 29.0,30.0), (Matrix(2, 2) << 31.0,32.0,0.0,34.0),\n      3, (Matrix(2, 2) << 35.0,36.0,37.0,38.0)));\n  gbn += GaussianConditional::shared_ptr(new GaussianConditional(\n      3, (Vector(2) << 39.0,40.0), (Matrix(2, 2) << 41.0,42.0,0.0,44.0),\n      4, (Matrix(2, 2) << 45.0,46.0,47.0,48.0)));\n  gbn += GaussianConditional::shared_ptr(new GaussianConditional(\n      4, (Vector(2) << 49.0,50.0), (Matrix(2, 2) << 51.0,52.0,0.0,54.0)));\n\n  // Compute dogleg point for different deltas\n\n  double Delta1 = 0.5;  // Less than steepest descent\n  VectorValues actual1 = DoglegOptimizerImpl::ComputeDoglegPoint(Delta1, gbn.optimizeGradientSearch(), gbn.optimize());\n  DOUBLES_EQUAL(Delta1, actual1.vector().norm(), 1e-5);\n\n  double Delta2 = 1.5;  // Between steepest descent and Newton's method\n  VectorValues expected2 = DoglegOptimizerImpl::ComputeBlend(Delta2, gbn.optimizeGradientSearch(), gbn.optimize());\n  VectorValues actual2 = DoglegOptimizerImpl::ComputeDoglegPoint(Delta2, gbn.optimizeGradientSearch(), gbn.optimize());\n  DOUBLES_EQUAL(Delta2, actual2.vector().norm(), 1e-5);\n  EXPECT(assert_equal(expected2, actual2));\n\n  double Delta3 = 5.0;  // Larger than Newton's method point\n  VectorValues expected3 = gbn.optimize();\n  VectorValues actual3 = DoglegOptimizerImpl::ComputeDoglegPoint(Delta3, gbn.optimizeGradientSearch(), gbn.optimize());\n  EXPECT(assert_equal(expected3, actual3));\n}\n\n/* ************************************************************************* */\nTEST(DoglegOptimizer, Iterate) {\n  // really non-linear factor graph\n  NonlinearFactorGraph fg = example::createReallyNonlinearFactorGraph();\n\n  // config far from minimum\n  Point2 x0(3,0);\n  Values config;\n  config.insert(X(1), x0);\n\n  double Delta = 1.0;\n  for(size_t it=0; it<10; ++it) {\n    GaussianBayesNet gbn = *fg.linearize(config)->eliminateSequential();\n    // Iterate assumes that linear error = nonlinear error at the linearization point, and this should be true\n    double nonlinearError = fg.error(config);\n    double linearError = GaussianFactorGraph(gbn).error(config.zeroVectors());\n    DOUBLES_EQUAL(nonlinearError, linearError, 1e-5);\n//    cout << \"it \" << it << \", Delta = \" << Delta << \", error = \" << fg->error(*config) << endl;\n    VectorValues dx_u = gbn.optimizeGradientSearch();\n    VectorValues dx_n = gbn.optimize();\n    DoglegOptimizerImpl::IterationResult result = DoglegOptimizerImpl::Iterate(Delta, DoglegOptimizerImpl::SEARCH_EACH_ITERATION, dx_u, dx_n, gbn, fg, config, fg.error(config));\n    Delta = result.Delta;\n    EXPECT(result.f_error < fg.error(config)); // Check that error decreases\n    Values newConfig(config.retract(result.dx_d));\n    config = newConfig;\n    DOUBLES_EQUAL(fg.error(config), result.f_error, 1e-5); // Check that error is correctly filled in\n  }\n}\n\n/* ************************************************************************* */\nint main() { TestResult tr; return TestRegistry::runAllTests(tr); }\n/* ************************************************************************* */\n", "meta": {"hexsha": "c4bf0480c5daf8352a511859f75895ede1983284", "size": 6616, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/testDoglegOptimizer.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": "tests/testDoglegOptimizer.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": "tests/testDoglegOptimizer.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": 43.2418300654, "max_line_length": 177, "alphanum_fraction": 0.6234885127, "num_tokens": 2039, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.6297746004557471, "lm_q1q2_score": 0.45055586110099094}}
{"text": "//------------------------------------------------------------------------------\n// \\file NarrowCast_test.cpp\n//------------------------------------------------------------------------------\n\n#include <boost/test/unit_test.hpp>\n#include <iostream>\n#include <stdexcept>\n\n#include \"Utilities/NarrowCast.h\"\n\nusing Utilities::narrow_cast;\n\nBOOST_AUTO_TEST_SUITE(Utilities)\nBOOST_AUTO_TEST_SUITE(NarrowCast_tests)\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\n// cf. Stroustrup. C++ Programming Language, 4th. Ed. pp. 299 Sec. 11.5\nBOOST_AUTO_TEST_CASE(NarrowCastWorks)\n{\n  std::cout << \"\\n NarrowCastIsFun\\n\";\n\n  const auto c1 = narrow_cast<char>(64);\n\n  // Will throw if chars are unsigned.\n  //BOOST_CHECK_THROW(narrow_cast<char>(-64), std::runtime_error); \n  const auto c2 = narrow_cast<char>(-64); // Will throw if chars are unsigned\n\n  //const auto c3 = narrow_cast<char>(264); // will throw if chars are 8-bit and signed\n  BOOST_CHECK_THROW(narrow_cast<char>(264), std::runtime_error);\n\n  const auto d1 = narrow_cast<double>(1/3.0F); // OK\n  \n  //const auto f1 = narrow_cast<float>(1/3.0); // will probably throw\n  BOOST_CHECK_THROW(narrow_cast<float>(1/3.0), std::runtime_error);\n\n  const auto c4 = narrow_cast<char>(42); // may throw\n  const auto f2 = narrow_cast<float>(42.0); // may throw\n\n  //const auto p1 = narrow_cast<char*>(42); // compile-time error, invalid static_cast\n  //const auto i1 = narrow_cast<int>(\"chararray\"); // compile-time error, invalid static_Cast\n\n  const auto d2 = narrow_cast<double>(42); // may throw (but probably will not)\n  const auto i2 = narrow_cast<int>(42.0); // may throw\n\n  BOOST_TEST(true);\n}\n\nBOOST_AUTO_TEST_SUITE_END() // NarrowCast_tests\nBOOST_AUTO_TEST_SUITE_END() // Utilities\n", "meta": {"hexsha": "bdd14aa1373bf2af1cfcfc8a5c30c45006a8b49f", "size": 1843, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Voltron/Source/UnitTests/Utilities/NarrowCast_test.cpp", "max_stars_repo_name": "ernestyalumni/HrdwCCppCUDA", "max_stars_repo_head_hexsha": "17ed937dea06431a4d5ca103f993ea69a6918734", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-02-09T19:44:51.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-09T19:44:51.000Z", "max_issues_repo_path": "Voltron/Source/UnitTests/Utilities/NarrowCast_test.cpp", "max_issues_repo_name": "ernestyalumni/HrdwCCppCUDA", "max_issues_repo_head_hexsha": "17ed937dea06431a4d5ca103f993ea69a6918734", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Voltron/Source/UnitTests/Utilities/NarrowCast_test.cpp", "max_forks_repo_name": "ernestyalumni/HrdwCCppCUDA", "max_forks_repo_head_hexsha": "17ed937dea06431a4d5ca103f993ea69a6918734", "max_forks_repo_licenses": ["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.137254902, "max_line_length": 93, "alphanum_fraction": 0.5952251763, "num_tokens": 420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297745935070808, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.4505558599509242}}
{"text": "//  (C) Copyright Eric Niebler 2005.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include <boost/test/unit_test.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/weighted_mean.hpp>\n#include <boost/accumulators/statistics/variates/covariate.hpp>\n\nusing namespace boost;\nusing namespace unit_test;\nusing namespace accumulators;\n\ntemplate<typename T>\nvoid assert_is_double(T const &)\n{\n    BOOST_MPL_ASSERT((is_same<T, double>));\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// test_stat\n//\nvoid test_stat()\n{\n        accumulator_set<\n        int\n      , stats<\n            tag::weighted_mean\n          , tag::mean_of_weights\n          , tag::weighted_mean_of_variates<int, tag::covariate1>\n        >\n      , int\n    > acc, test_acc(sample = 0);\n\n    acc(1, weight = 2, covariate1 = 3);\n    BOOST_CHECK_CLOSE(1., weighted_mean(acc), 1e-5);\n    BOOST_CHECK_EQUAL(1u, count(acc));\n    BOOST_CHECK_EQUAL(2, sum(acc));\n    BOOST_CHECK_CLOSE(2., mean_of_weights(acc), 1e-5);\n    BOOST_CHECK_CLOSE(3., (weighted_mean_of_variates<int, tag::covariate1>(acc)), 1e-5);\n\n    acc(0, weight = 4, covariate1 = 4);\n    BOOST_CHECK_CLOSE(1./3., weighted_mean(acc), 1e-5);\n    BOOST_CHECK_EQUAL(2u, count(acc));\n    BOOST_CHECK_EQUAL(2, sum(acc));\n    BOOST_CHECK_CLOSE(3., mean_of_weights(acc), 1e-5);\n    BOOST_CHECK_CLOSE(11./3., (weighted_mean_of_variates<int, tag::covariate1>(acc)), 1e-5);\n\n    acc(2, weight = 9, covariate1 = 8);\n    BOOST_CHECK_CLOSE(4./3., weighted_mean(acc), 1e-5);\n    BOOST_CHECK_EQUAL(3u, count(acc));\n    BOOST_CHECK_EQUAL(20, sum(acc));\n    BOOST_CHECK_CLOSE(5., mean_of_weights(acc), 1e-5);\n    BOOST_CHECK_CLOSE(94./15., (weighted_mean_of_variates<int, tag::covariate1>(acc)), 1e-5);\n\n    assert_is_double(mean(acc));\n\n    accumulator_set<\n        int\n      , stats<\n            tag::weighted_mean(immediate)\n          , tag::mean_of_weights(immediate)\n          , tag::weighted_mean_of_variates<int, tag::covariate1>(immediate)\n        >\n      , int\n    > acc2, test_acc2(sample = 0);\n\n    acc2(1, weight = 2, covariate1 = 3);\n    BOOST_CHECK_CLOSE(1., weighted_mean(acc2), 1e-5);\n    BOOST_CHECK_EQUAL(1u, count(acc2));\n    BOOST_CHECK_CLOSE(2., mean_of_weights(acc2), 1e-5);\n    BOOST_CHECK_CLOSE(3., (weighted_mean_of_variates<int, tag::covariate1>(acc2)), 1e-5);\n\n    acc2(0, weight = 4, covariate1 = 4);\n    BOOST_CHECK_CLOSE(1./3., weighted_mean(acc2), 1e-5);\n    BOOST_CHECK_EQUAL(2u, count(acc2));\n    BOOST_CHECK_CLOSE(3., mean_of_weights(acc2), 1e-5);\n    BOOST_CHECK_CLOSE(11./3., (weighted_mean_of_variates<int, tag::covariate1>(acc2)), 1e-5);\n\n    acc2(2, weight = 9, covariate1 = 8);\n    BOOST_CHECK_CLOSE(4./3., weighted_mean(acc2), 1e-5);\n    BOOST_CHECK_EQUAL(3u, count(acc2));\n    BOOST_CHECK_CLOSE(5., mean_of_weights(acc2), 1e-5);\n    BOOST_CHECK_CLOSE(94./15., (mean_of_variates<int, tag::covariate1>(acc2)), 1e-5);\n\n    assert_is_double(mean(acc2));\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// init_unit_test_suite\n//\ntest_suite* init_unit_test_suite( int argc, char* argv[] )\n{\n    test_suite *test = BOOST_TEST_SUITE(\"weighted_mean test\");\n\n    test->add(BOOST_TEST_CASE(&test_stat));\n\n    return test;\n}\n", "meta": {"hexsha": "7324964e70617c7b1526fa9eb5662ad18d0ee95f", "size": 3517, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/accumulators/test/weighted_mean.cpp", "max_stars_repo_name": "mike-code/boost_1_38_0", "max_stars_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/accumulators/test/weighted_mean.cpp", "max_issues_repo_name": "mike-code/boost_1_38_0", "max_issues_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/accumulators/test/weighted_mean.cpp", "max_forks_repo_name": "mike-code/boost_1_38_0", "max_forks_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.145631068, "max_line_length": 93, "alphanum_fraction": 0.6525447825, "num_tokens": 997, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.6297745935070808, "lm_q1q2_score": 0.45055585612974836}}
{"text": "#pragma once\n\n#include <Eigen/Core>\n\n#include <vector>\n#include <array>\n\n#include \"Spirit_Defines.h\"\n\n// Dynamic Eigen typedefs\ntypedef Eigen::Matrix<scalar, -1,  1> VectorX;\ntypedef Eigen::Matrix<scalar,  1, -1> RowVectorX;\ntypedef Eigen::Matrix<scalar, -1, -1> MatrixX;\n\n// 3D Eigen typedefs\ntypedef Eigen::Matrix<scalar, 3, 1> Vector3;\ntypedef Eigen::Matrix<scalar, 1, 3> RowVector3;\ntypedef Eigen::Matrix<scalar, 3, 3> Matrix3;\n\n// Vectorfield and Scalarfield typedefs\n#ifdef USE_CUDA\n    #include \"Managed_Allocator.hpp\"\n    typedef std::vector<int,             managed_allocator<int>>             intfield;\n    typedef std::vector<scalar,          managed_allocator<scalar>>          scalarfield;\n    typedef std::vector<Vector3,         managed_allocator<Vector3>>         vectorfield;\n    struct Pair\n    {\n        // Basis indices of first and second atom of pair\n        int i, j;\n        // Translations of the basis cell of second atom of pair\n        int translations[3];\n    };\n    struct Triplet\n    {\n        int i, j, k;\n        int d_j[3], d_k[3];\n        scalar n[3];\n    };\n    struct Quadruplet\n    {\n        int i, j, k, l;\n        int d_j[3], d_k[3], d_l[3];\n    };\n    struct Neighbour : Pair\n    {\n        // Shell index\n        int idx_shell;\n    };\n    typedef std::vector<Pair,       managed_allocator<Pair>>       pairfield;\n    typedef std::vector<Triplet,    managed_allocator<Triplet>>    tripletfield;\n    typedef std::vector<Quadruplet, managed_allocator<Quadruplet>> quadrupletfield;\n    typedef std::vector<Neighbour,  managed_allocator<Neighbour>>  neighbourfield;\n#else\n    typedef std::vector<int>     intfield;\n    typedef std::vector<scalar>  scalarfield;\n    typedef std::vector<Vector3> vectorfield;\n    struct Pair\n    {\n        int i, j;\n        std::array<int,3> translations;\n    };\n    struct Triplet\n    {\n        int i, j, k;\n        std::array<int,3> d_j, d_k;\n        std::array<scalar, 3> n;\n    };\n    struct Quadruplet\n    {\n        int i, j, k, l;\n        std::array<int,3> d_j, d_k, d_l;\n    };\n    struct Neighbour : Pair\n    {\n        // Shell index\n        int idx_shell;\n    };\n    typedef std::vector<Pair>       pairfield;\n    typedef std::vector<Triplet>    tripletfield;\n    typedef std::vector<Quadruplet> quadrupletfield;\n    typedef std::vector<Neighbour>  neighbourfield;\n\n    // Definition for OpenMP reduction operation using Vector3's\n    #pragma omp declare reduction (+: Vector3: omp_out=omp_out+omp_in)\\\n        initializer(omp_priv=Vector3::Zero())\n#endif", "meta": {"hexsha": "93b0b4401d4c8823ab8cf274ca3dec316e7dbe7e", "size": 2531, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "core/include/engine/Vectormath_Defines.hpp", "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/include/engine/Vectormath_Defines.hpp", "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/include/engine/Vectormath_Defines.hpp", "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": 29.4302325581, "max_line_length": 89, "alphanum_fraction": 0.6218885816, "num_tokens": 689, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.4505145760424795}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// Unit Test\n\n// This file was modified by Oracle on 2015, 2016, 2017.\n// Modifications copyright (c) 2015-2017, Oracle and/or its affiliates.\n// Contributed and/or modified by Vissarion Fysikopoulos, on behalf of Oracle\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\n\n// 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#include <boost/geometry.hpp>\n#include <geometry_test_common.hpp>\n\nnamespace bg = boost::geometry;\n\n//Testing geographic strategies\ntemplate <typename CT>\nvoid test_geo_strategies()\n{\n    std::string poly = \"POLYGON((52 0, 41 -74, -23 -43, -26 28, 52 0))\";\n\n    typedef bg::model::point<CT, 2, bg::cs::geographic<bg::degree> > pt_geo;\n\n    bg::strategy::area::geographic<pt_geo> geographic_default;\n\n    bg::strategy::area::geographic<pt_geo, bg::strategy::andoyer, 1>\n        geographic_andoyer1;\n    bg::strategy::area::geographic<pt_geo, bg::strategy::andoyer, 2>\n        geographic_andoyer2;\n    bg::strategy::area::geographic<pt_geo, bg::strategy::andoyer, 3>\n        geographic_andoyer3;\n    bg::strategy::area::geographic<pt_geo, bg::strategy::andoyer, 4>\n        geographic_andoyer4;\n    bg::strategy::area::geographic<pt_geo, bg::strategy::andoyer, 5>\n        geographic_andoyer5;\n\n    bg::strategy::area::geographic<pt_geo, bg::strategy::thomas, 1>\n        geographic_thomas1;\n    bg::strategy::area::geographic<pt_geo, bg::strategy::thomas, 2>\n        geographic_thomas2;\n    bg::strategy::area::geographic<pt_geo, bg::strategy::thomas, 3>\n        geographic_thomas3;\n    bg::strategy::area::geographic<pt_geo, bg::strategy::thomas, 4>\n        geographic_thomas4;\n    bg::strategy::area::geographic<pt_geo, bg::strategy::thomas, 5>\n        geographic_thomas5;\n\n    bg::strategy::area::geographic<pt_geo, bg::strategy::vincenty, 1>\n        geographic_vincenty1;\n    bg::strategy::area::geographic<pt_geo, bg::strategy::vincenty, 2>\n        geographic_vincenty2;\n    bg::strategy::area::geographic<pt_geo, bg::strategy::vincenty, 3>\n        geographic_vincenty3;\n    bg::strategy::area::geographic<pt_geo, bg::strategy::vincenty, 4>\n        geographic_vincenty4;\n    bg::strategy::area::geographic<pt_geo, bg::strategy::vincenty, 5>\n        geographic_vincenty5;\n\n    bg::strategy::area::geographic<pt_geo, bg::strategy::andoyer>\n        geographic_andoyer_default;\n    bg::strategy::area::geographic<pt_geo, bg::strategy::thomas>\n        geographic_thomas_default;\n    bg::strategy::area::geographic<pt_geo, bg::strategy::vincenty>\n        geographic_vincenty_default;\n\n    bg::model::polygon<pt_geo> geometry_geo;\n\n    //GeographicLib         63316536351834.289\n    //PostGIS (v2.2.2)      6.33946+13\n    //MS SQL SERVER         632930207487035\n\n    bg::read_wkt(poly, geometry_geo);\n    CT area;\n    CT err = 0.0000001;\n\n    CT area_default = bg::area(geometry_geo);\n    BOOST_CHECK_CLOSE(area_default, 63316309346280.18, err);\n    area = bg::area(geometry_geo, geographic_default);\n    BOOST_CHECK_CLOSE(area, 63316309346280.18, err);\n\n    CT area_less_accurate = bg::area(geometry_geo, geographic_andoyer1);\n    BOOST_CHECK_CLOSE(area, 63316309346280.18, err);\n    area = bg::area(geometry_geo, geographic_andoyer2);\n    BOOST_CHECK_CLOSE(area, 63316309224306.5, err);\n    area = bg::area(geometry_geo, geographic_andoyer3);\n    BOOST_CHECK_CLOSE(area, 63316309224411.195, err);\n    area = bg::area(geometry_geo, geographic_andoyer4);\n    BOOST_CHECK_CLOSE(area, 63316309224411.094, err);\n    area = bg::area(geometry_geo, geographic_andoyer5);\n    BOOST_CHECK_CLOSE(area, 63316309224411.094, err);\n\n    area = bg::area(geometry_geo, geographic_thomas1);\n    BOOST_CHECK_CLOSE(area, 63316536214315.32, err);\n    area = bg::area(geometry_geo, geographic_thomas2);\n    BOOST_CHECK_CLOSE(area, 63316536092341.266, err);\n    area = bg::area(geometry_geo, geographic_thomas3);\n    BOOST_CHECK_CLOSE(area, 63316536092445.961, err);\n    area = bg::area(geometry_geo, geographic_thomas4);\n    BOOST_CHECK_CLOSE(area, 63316536092445.859, err);\n    area = bg::area(geometry_geo, geographic_thomas5);\n    BOOST_CHECK_CLOSE(area, 63316536092445.859, err);\n\n    area = bg::area(geometry_geo, geographic_vincenty1);\n    BOOST_CHECK_CLOSE(area, 63316536473798.984, err);\n    area = bg::area(geometry_geo, geographic_vincenty2);\n    BOOST_CHECK_CLOSE(area, 63316536351824.93, err);\n    area = bg::area(geometry_geo, geographic_vincenty3);\n    BOOST_CHECK_CLOSE(area, 63316536351929.625, err);\n    area = bg::area(geometry_geo, geographic_vincenty4);\n    BOOST_CHECK_CLOSE(area, 63316536351929.523, err);\n    CT area_most_accurate = bg::area(geometry_geo, geographic_vincenty5);\n    BOOST_CHECK_CLOSE(area, 63316536351929.523, err);\n\n    area = bg::area(geometry_geo, geographic_andoyer_default);\n    BOOST_CHECK_CLOSE(area, 63316309346280.18, err);\n    area = bg::area(geometry_geo, geographic_thomas_default);\n    BOOST_CHECK_CLOSE(area, 63316536092341.266, err);\n    area = bg::area(geometry_geo, geographic_vincenty_default);\n    BOOST_CHECK_CLOSE(area, 63316536351929.523, err);\n\n    BOOST_CHECK_CLOSE(area_most_accurate, area_less_accurate, .001);\n    BOOST_CHECK_CLOSE(area_most_accurate, area_default, .001);\n/*\n    // timings and accuracy\n    std::cout.precision(25);\n    std::size_t exp_times = 100000;\n    {   clock_t startTime = clock();\n        for (int j=0; j < exp_times; j++) area = bg::area(geometry_geo, geographic_andoyer1);\n        std::cout << double( clock() - startTime ) / (double)CLOCKS_PER_SEC<< \" \";\n        std::cout  << area << std::endl;}\n    {   clock_t startTime = clock();\n        for (int j=0; j < exp_times; j++) area = bg::area(geometry_geo, geographic_andoyer2);\n        std::cout << double( clock() - startTime ) / (double)CLOCKS_PER_SEC<< \" \";\n        std::cout  << area << std::endl;}\n    {   clock_t startTime = clock();\n        for (int j=0; j < exp_times; j++) area = bg::area(geometry_geo, geographic_andoyer3);\n        std::cout << double( clock() - startTime ) / (double)CLOCKS_PER_SEC<< \" \";\n        std::cout  << area << std::endl;}\n    {   clock_t startTime = clock();\n        for (int j=0; j < exp_times; j++) area = bg::area(geometry_geo, geographic_andoyer4);\n        std::cout << double( clock() - startTime ) / (double)CLOCKS_PER_SEC<< \" \";\n        std::cout  << area << std::endl;}\n    {   clock_t startTime = clock();\n        for (int j=0; j < exp_times; j++) area = bg::area(geometry_geo, geographic_andoyer5);\n        std::cout << double( clock() - startTime ) / (double)CLOCKS_PER_SEC<< \" \";\n        std::cout  << area << std::endl;}\n    {   clock_t startTime = clock();\n        for (int j=0; j < exp_times; j++) area = bg::area(geometry_geo, geographic_thomas1);\n        std::cout << double( clock() - startTime ) / (double)CLOCKS_PER_SEC<< \" \";\n        std::cout  << area << std::endl;}\n    {   clock_t startTime = clock();\n        for (int j=0; j < exp_times; j++) area = bg::area(geometry_geo, geographic_thomas2);\n        std::cout << double( clock() - startTime ) / (double)CLOCKS_PER_SEC<< \" \";\n        std::cout  << area << std::endl;}\n    {   clock_t startTime = clock();\n        for (int j=0; j < exp_times; j++) area = bg::area(geometry_geo, geographic_thomas3);\n        std::cout << double( clock() - startTime ) / (double)CLOCKS_PER_SEC<< \" \";\n        std::cout  << area << std::endl;}\n    {   clock_t startTime = clock();\n        for (int j=0; j < exp_times; j++) area = bg::area(geometry_geo, geographic_thomas4);\n        std::cout << double( clock() - startTime ) / (double)CLOCKS_PER_SEC<< \" \";\n        std::cout  << area << std::endl;}\n    {   clock_t startTime = clock();\n        for (int j=0; j < exp_times; j++) area = bg::area(geometry_geo, geographic_thomas5);\n        std::cout << double( clock() - startTime ) / (double)CLOCKS_PER_SEC<< \" \";\n        std::cout  << area << std::endl;}\n    {   clock_t startTime = clock();\n        for (int j=0; j < exp_times; j++) area = bg::area(geometry_geo, geographic_vincenty1);\n        std::cout << double( clock() - startTime ) / (double)CLOCKS_PER_SEC<< \" \";\n        std::cout  << area << std::endl;}\n    {   clock_t startTime = clock();\n        for (int j=0; j < exp_times; j++) area = bg::area(geometry_geo, geographic_vincenty2);\n        std::cout << double( clock() - startTime ) / (double)CLOCKS_PER_SEC<< \" \";\n        std::cout  << area << std::endl;}\n    {   clock_t startTime = clock();\n        for (int j=0; j < exp_times; j++) area = bg::area(geometry_geo, geographic_vincenty3);\n        std::cout << double( clock() - startTime ) / (double)CLOCKS_PER_SEC<< \" \";\n        std::cout  << area << std::endl;}\n    {   clock_t startTime = clock();\n        for (int j=0; j < exp_times; j++) area = bg::area(geometry_geo, geographic_vincenty4);\n        std::cout << double( clock() - startTime ) / (double)CLOCKS_PER_SEC<< \" \";\n        std::cout  << area << std::endl;}\n    {   clock_t startTime = clock();\n        for (int j=0; j < exp_times; j++) area = bg::area(geometry_geo, geographic_vincenty5);\n        std::cout << double( clock() - startTime ) / (double)CLOCKS_PER_SEC<< \" \";\n        std::cout  << area << std::endl;}\n*/\n}\n\nint test_main(int, char* [])\n{\n\n    test_geo_strategies<double>();\n\n    return 0;\n}\n", "meta": {"hexsha": "284d179cdc62abd550ebb23852c4099c7c880028", "size": 9528, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/test/algorithms/area/area_geo.cpp", "max_stars_repo_name": "Manu343726/boost-cmake", "max_stars_repo_head_hexsha": "009c3843b49a56880d988ffdca6d909f881edb3d", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 918.0, "max_stars_repo_stars_event_min_datetime": "2016-12-22T02:53:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T06:21:35.000Z", "max_issues_repo_path": "libs/geometry/test/algorithms/area/area_geo.cpp", "max_issues_repo_name": "Manu343726/boost-cmake", "max_issues_repo_head_hexsha": "009c3843b49a56880d988ffdca6d909f881edb3d", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 203.0, "max_issues_repo_issues_event_min_datetime": "2016-12-27T12:09:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T20:46:55.000Z", "max_forks_repo_path": "libs/geometry/test/algorithms/area/area_geo.cpp", "max_forks_repo_name": "Manu343726/boost-cmake", "max_forks_repo_head_hexsha": "009c3843b49a56880d988ffdca6d909f881edb3d", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 122.0, "max_forks_repo_forks_event_min_datetime": "2016-12-22T17:38:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-22T14:25:49.000Z", "avg_line_length": 47.1683168317, "max_line_length": 94, "alphanum_fraction": 0.6581654072, "num_tokens": 2718, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384735, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4505145702774218}}
{"text": "#include \"plane_engaging.h\"\n\n#include <ctime>    // For time()\n#include <cstdlib>  // For srand() and rand()\n#include <Eigen/SVD>\n\n#include <solvehfvc.h>\n#include <RobotUtilities/utilities.h>\n#include <RobotUtilities/TimerLinux.h>\n\nusing namespace RUT;\n\n\nPlaneEngaging::PlaneEngaging(ForceControlHardware *robot,\n        ForceControlController *controller) {\n  robot_ = robot;\n  controller_ = controller;\n}\n\nPlaneEngaging::~PlaneEngaging() {\n}\n\nbool PlaneEngaging::initialize(const std::string& file_name,\n    const int main_loop_rate, ros::NodeHandle& root_nh) {\n  main_loop_rate_ = main_loop_rate;\n  folder_path_ = file_name;\n  // parameters in file\n  //  G, b_G\n  ifstream fp;\n  fp.open(file_name + \"plane_engaging/para.txt\");\n  if (!fp) {\n    cerr << \"Unable to open parameter file.\";\n    return false;\n  }\n\n  int nRowG, nColG;\n\n  fp >> nRowG >> nColG;\n  G_.resize(nRowG, nColG);\n  b_G_.resize(nRowG);\n  for (int i = 0; i < nRowG; ++i)\n    for (int j = 0; j < nColG; ++j)\n      fp >> G_(i,j);\n\n  for (int i = 0; i < nRowG; ++i) fp >> b_G_(i);\n\n  fp.close();\n\n  // double check\n  cout << \"G_: \" << G_.format(MatlabFmt) << endl;\n  cout << \"b_G_: \" << b_G_.format(MatlabFmt) << endl;\n\n  // parameters in ROS server\n  std::vector<double> scale_force_vector;\n  root_nh.getParam(\"/constraint_estimation/scale_force_vector\", scale_force_vector);\n  if (!root_nh.hasParam(\"/constraint_estimation/scale_force_vector\"))\n    ROS_WARN_STREAM(\"Parameter [/constraint_estimation/scale_force_vector] not found!\");\n\n  force_scale_matrix_inv_ = Matrix6d::Zero();\n  for (int i = 0; i < 6; ++i) force_scale_matrix_inv_(i,i) = 1.0/scale_force_vector[i];\n\n  root_nh.param(string(\"/constraint_estimation/v_singular_value_threshold\"),\n      v_singular_value_threshold_, 0.1);\n  root_nh.param(string(\"/constraint_estimation/f_singular_value_threshold\"),\n      f_singular_value_threshold_, 0.1);\n  if (!root_nh.hasParam(\"/constraint_estimation/v_singular_value_threshold\"))\n      ROS_WARN_STREAM(\"Parameter \"\n      \"[/constraint_estimation/v_singular_value_threshold] not found, \"\n      \" using default: \" << v_singular_value_threshold_);\n  if (!root_nh.hasParam(\"/constraint_estimation/f_singular_value_threshold\"))\n      ROS_WARN_STREAM(\"Parameter \"\n      \"[/constraint_estimation/f_singular_value_threshold] not found, \"\n      \"using default: \" << f_singular_value_threshold_);\n\n  root_nh.param(string(\"/plane_engaging/Number_of_frames\"),\n      N_TRJ_, 1);\n  if (!root_nh.hasParam(\"/plane_engaging/Number_of_frames\"))\n      ROS_WARN_STREAM(\"Parameter \"\n      \"[/plane_engaging/Number_of_frames] not found, \"\n      \" using default: \" << N_TRJ_);\n\n  return true;\n}\n\nbool PlaneEngaging::run() {\n  MatrixXd f_data, v_data;\n  controller_->reset();\n\n  if (controller_->_f_queue.size() < 50) {\n    cout << \"Run update() for \" << main_loop_rate_ << \" frames:\" << endl;\n    // first, run update for 1s to populate the data deques\n    ros::Rate pub_rate(main_loop_rate_);\n    ros::Duration period(EGM_PERIOD);\n    for (int i = 0; i < main_loop_rate_; ++i) {\n      ros::Time time_now = ros::Time::now();\n      bool b_is_safe = controller_->update(time_now, period);\n      if(!b_is_safe) break;\n      pub_rate.sleep();\n    }\n    cout << \"Done.\" << endl;\n  }\n\n  Timer timer;\n  std::srand(std::time(0));\n  for (int fr = 0; fr < N_TRJ_; ++fr) {\n    timer.tic();\n    /* Estimate Natural Constraints from pool of data */\n    // get the weighted data\n    // debug\n    f_data = MatrixXd::Zero(6, controller_->_f_queue.size());\n    v_data = MatrixXd::Zero(6, controller_->_v_queue.size());\n    for (int i = 0; i < controller_->_f_queue.size(); ++i)\n      f_data.col(i) = controller_->_f_queue[i] * controller_->_f_weights[i];\n    for (int i = 0; i < controller_->_v_queue.size(); ++i)\n      v_data.col(i) = controller_->_v_queue[i] * controller_->_v_weights[i];\n\n    // SVD on velocity data\n    Eigen::JacobiSVD<MatrixXd> svd_v(v_data.transpose(), Eigen::ComputeThinV);\n    VectorXd sigma_v = svd_v.singularValues();\n    int DimV = 0;\n    for (int i = 0; i < 6; ++i)\n      if (sigma_v(i) > v_singular_value_threshold_) DimV ++;\n\n    // get a basis for row space of velocity data\n    MatrixXd rowspace_v = svd_v.matrixV().leftCols(DimV);\n\n    // filter out force data that:\n    //    1. has a small weight\n    std::vector<int> f_id;\n    for (int i = 0; i < f_data.cols(); ++i) {\n      double length = f_data.col(i).norm();\n      if (length > 1.5) { // weighted length in newton\n        f_id.push_back(i);\n      }\n    }\n\n    int f_data_length = f_id.size();\n    MatrixXd f_data_filtered = MatrixXd::Zero(6, f_data_length);\n    for (int i = 0; i < f_data_length; ++i)\n      f_data_filtered.col(i) = f_data.col(f_id[i]);\n\n    int DimF = 0;\n    MatrixXd Nf;\n    MatrixXd f_data_selected;\n    if (f_data_length > 5) {\n      // SVD to filtered force data\n      Eigen::JacobiSVD<MatrixXd> svd_f(f_data_filtered.transpose(), Eigen::ComputeThinV);\n      VectorXd sigma_f = svd_f.singularValues();\n      // check dimensions, estimate natural constraints\n      double threshold = max(f_singular_value_threshold_, 0.1*sigma_f(0));\n      for (int i = 0; i < 6; ++i)\n        if (sigma_f(i) > threshold) DimF ++;\n\n      if (DimF > 3) {\n        cout << \"DimF: \" << DimF << endl;\n        cout << \"Press Enter to continue\" << endl;\n        getchar();\n      }\n      // MatrixXd N = SVD_V_f.block<6, DimF>(0, 0).transpose();\n      // Sample DimF force directions\n      MatrixXd f_data_normalized = f_data_filtered;\n      for (int i = 0; i < f_data_length; ++i)\n        f_data_normalized.col(i).normalize();\n\n      int kNFSamples = (int)pow(double(f_data_length), 0.7);\n      f_data_selected = MatrixXd(6, DimF);\n      if (DimF == 1) {\n        f_data_selected = f_data_filtered.rowwise().mean();\n        f_data_selected.normalize();\n      } else {\n        MatrixXd f_data_selected_new(6, DimF);\n        double f_distance = 0;\n        assert(f_data_length < 32767);\n        for (int i = 0; i < kNFSamples; ++i) {\n          // 1. sample\n          for (int s = 0; s < DimF; s++) {\n            int r = (rand() % f_data_length);\n            f_data_selected_new.col(s) = f_data_normalized.col(r);\n          }\n          // 2. compute distance\n          double f_distance_new = 0;\n          for (int ii = 0; ii < DimF-1; ++ii)\n            for (int jj = ii+1; jj < DimF; ++jj)\n              f_distance_new += (f_data_selected_new.col(ii) -\n                  f_data_selected_new.col(jj)).norm();\n          // 3. Update data\n          if (f_distance_new > f_distance) {\n            f_data_selected = f_data_selected_new;\n            f_distance = f_distance_new;\n          }\n        } // end sampling\n      }\n\n      // unscale\n      Nf = f_data_selected.transpose() * force_scale_matrix_inv_;\n    } else {\n      DimF = 0;\n      Nf = MatrixXd(0, 6);\n      f_data_selected = MatrixXd(6, 0);\n    }\n\n    /* Do Hybrid Servoing */\n    HFVC action;\n    int kDimActualized      = 6;\n    int kDimUnActualized    = 0;\n    int kDimSlidingFriction = 0;\n    int kNumSeeds           = 3;\n    int kDimLambda          = DimF;\n    int kPrintLevel         = 1;\n\n    VectorXd F = VectorXd::Zero(6);\n    MatrixXd Aeq(0, DimF+6); // dummy\n    VectorXd beq(0); // dummy\n    MatrixXd A = MatrixXd::Zero(DimF, DimF + 6);\n    VectorXd b_A = VectorXd::Zero(DimF);\n    A.leftCols(DimF) = -MatrixXd::Identity(DimF,DimF);\n    double kLambdaMin = 10.0;\n    for (int i = 0; i < DimF; ++i) b_A(i) = -kLambdaMin;\n\n    solvehfvc(Nf, G_, b_G_, F, Aeq, beq, A, b_A,\n      kDimActualized, kDimUnActualized,\n      kDimSlidingFriction, kDimLambda,\n      kNumSeeds, kPrintLevel,\n      &action);\n\n    double computation_time_ms = timer.toc();\n    /*  Execute the hybrid action */\n    Vector6d v_Tr = Vector6d::Zero();\n    for (int i = 0; i < action.n_av; ++i)  v_Tr(i+action.n_af) = action.w_av(i);\n\n    double pose_fb[7];\n    robot_->getPose(pose_fb);\n    Matrix4d SE3_WT_fb = posemm2SE3(pose_fb);\n    Matrix6d Adj_WT = SE32Adj(SE3_WT_fb);\n    Matrix6d R_a = action.R_a;\n    Matrix6d R_a_inv = R_a.inverse();\n    Vector6d v_T = R_a_inv*v_Tr;\n\n    const double dt = 0.1; // s\n    const double kVMax = 0.002; // m/s,  maximum speed limit\n    const double scale_rot_to_tran = 0.5; // 1m = 2rad\n    Vector6d v_T_scaled = v_T;\n    v_T_scaled.tail(3) *= scale_rot_to_tran;\n    if (v_T_scaled.norm() > kVMax) {\n      double scale_safe = kVMax/v_T_scaled.norm();\n      v_T *= scale_safe;\n    }\n\n    Vector6d v_W = Adj_WT*v_T;\n    Matrix4d SE3_WT_command;\n    SE3_WT_command = SE3_WT_fb + wedge6(v_W)*SE3_WT_fb*dt;\n    double pose_set[7];\n    SE32Posemm(SE3_WT_command, pose_set);\n\n    Vector6d force_Tr_set = Vector6d::Zero();\n    for (int i = 0; i < action.n_af; ++i)  force_Tr_set[i] = action.eta_af(i);\n    Vector6d force_T = R_a_inv*force_Tr_set;\n    Matrix6d Adj_TW = SE32Adj(SE3Inv(SE3_WT_fb));\n    Vector6d force_W = Adj_TW.transpose() * force_T;\n\n    printf(\"V in world: %.3f\\t%.3f\\t%.3f\\t%.3f\\t%.3f\\t%.3f\\n\", v_W[0], v_W[1],\n        v_W[2],v_W[3],v_W[4],v_W[5]);\n    printf(\"F in world: %.3f\\t%.3f\\t%.3f\\t%.3f\\t%.3f\\t%.3f\\n\", force_W[0],\n        force_W[1], force_W[2],force_W[3],force_W[4],force_W[5]);\n    cout << \"Computation Time: \" << computation_time_ms << endl << endl;\n\n    if (fr == N_TRJ_-1) {\n      // print to file\n      ofstream fp;\n      // f_queue\n      fp.open(folder_path_ + \"plane_engaging/f_queue.txt\");\n      if (!fp) {\n        cerr << \"Unable to open file to write.\";\n        return false;\n      }\n      for (int i = 0; i < controller_->_f_queue.size(); ++i) {\n        stream_array_in(fp, controller_->_f_queue[i].data(), 6);\n        fp << endl;\n      }\n      fp.close();\n      // v_queue\n      fp.open(folder_path_ + \"plane_engaging/v_queue.txt\");\n      if (!fp) {\n        cerr << \"Unable to open file to write.\";\n        return false;\n      }\n      for (int i = 0; i < controller_->_v_queue.size(); ++i) {\n        stream_array_in(fp, controller_->_v_queue[i].data(), 6);\n        fp << endl;\n      }\n      fp.close();\n      // f_weights\n      fp.open(folder_path_ + \"plane_engaging/f_weights.txt\");\n      if (!fp) {\n        cerr << \"Unable to open file to write.\";\n        return false;\n      }\n      for (int i = 0; i < controller_->_f_weights.size(); ++i)\n        fp << controller_->_f_weights[i] << endl;\n      fp.close();\n\n      // v_weights\n      fp.open(folder_path_ + \"plane_engaging/v_weights.txt\");\n      if (!fp) {\n        cerr << \"Unable to open file to write.\";\n        return false;\n      }\n      for (int i = 0; i < controller_->_v_weights.size(); ++i)\n        fp << controller_->_v_weights[i] << endl;\n      fp.close();\n\n      // f_data_filtered\n      fp.open(folder_path_ + \"plane_engaging/f_data_filtered.txt\");\n      if (!fp) {\n        cerr << \"Unable to open file to write.\";\n        return false;\n      }\n      fp << f_data_filtered.transpose() << endl;\n      fp.close();\n      // f_data_selected\n      fp.open(folder_path_ + \"plane_engaging/f_data_selected.txt\");\n      if (!fp) {\n        cerr << \"Unable to open file to write.\";\n        return false;\n      }\n      fp << f_data_selected.transpose() << endl;\n      fp.close();\n      // others\n      fp.open(folder_path_ + \"plane_engaging/process.txt\");\n      if (!fp) {\n        cerr << \"Unable to open file to write.\";\n        return false;\n      }\n      fp << DimV << endl << DimF << endl;\n      stream_array_in(fp, v_T.data(), 6);\n      fp << endl;\n      stream_array_in(fp, force_T.data(), 6);\n      fp.close();\n    }\n\n    if (std::isnan(force_Tr_set[0])) {\n      cout << \"================== NaN =====================\" << endl;\n      cout << \"Press Enter to continue..\" << endl;\n      getchar();\n    }\n\n    cout << \"motion begins:\" << endl;\n    controller_->ExecuteHFVC(action.n_af, action.n_av,\n        action.R_a, pose_set, force_Tr_set.data(),\n        HS_CONTINUOUS, main_loop_rate_);\n\n  } // end for\n}\n", "meta": {"hexsha": "f59598c920c09ddebc957ed98433c74395957489", "size": 11790, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "experiments/plane_engaging/plane_engaging.cpp", "max_stars_repo_name": "yifan-hou/hybrid_servoing", "max_stars_repo_head_hexsha": "4d3a2cc047a3bad5ded19934247b5ab5e598f911", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2020-04-15T04:45:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T03:28:46.000Z", "max_issues_repo_path": "experiments/plane_engaging/plane_engaging.cpp", "max_issues_repo_name": "yifan-hou/hybrid_servoing", "max_issues_repo_head_hexsha": "4d3a2cc047a3bad5ded19934247b5ab5e598f911", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "experiments/plane_engaging/plane_engaging.cpp", "max_forks_repo_name": "yifan-hou/hybrid_servoing", "max_forks_repo_head_hexsha": "4d3a2cc047a3bad5ded19934247b5ab5e598f911", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3050847458, "max_line_length": 89, "alphanum_fraction": 0.604749788, "num_tokens": 3457, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.45048579811719264}}
{"text": "//\n// Created by fjh on 17-10-31.\n//\n\n#include <caffe/caffe.hpp>\n#include <net.h>\n#include <boost/shared_ptr.hpp>\n#include <loader/loader.h>\n#include <commons/commons.h>\n#include <math/gemm.h>\n#include <opencv2/core.hpp>\n#include <opencv2/shape.hpp>\n#include <opencv2/highgui.hpp>\n#include <opencv2/imgproc.hpp>\n#include <opencv2/imgcodecs.hpp>\n#define num_channels_ 3\n#define input_geometry_ cv::Size(640,360)\nmdl::Loader* load_net;\ncv::Mat mean_;\nvoid init(){\n    mdl::Gemmer::gemmers.push_back(new mdl::Gemmer);\n    load_net=mdl::Loader::shared_instance();\n    load_net->load(\"tool/model.min.json\",\"tool/data.min.bin\");\n}\nvoid WrapInputLayer(std::vector<cv::Mat>* input_channels,Mtype*in_data) {\n\n    int width = 640;\n    int height = 360;\n    float* input_data = in_data;\n    for (int i = 0; i < 3; ++i) {\n        cv::Mat channel(height, width, CV_32FC1, input_data);\n        input_channels->push_back(channel);\n        input_data += width * height;\n    }\n}\nvoid Preprocess(const cv::Mat& img,\n                std::vector<cv::Mat>* input_channels,Mtype*in_data) {\n    /* Convert the input image to the input image format of the network. */\n    cv::Mat sample;\n    if (img.channels() == 3 && num_channels_ == 1)\n        cv::cvtColor(img, sample, cv::COLOR_BGR2GRAY);\n    else if (img.channels() == 4 && num_channels_ == 1)\n        cv::cvtColor(img, sample, cv::COLOR_BGRA2GRAY);\n    else if (img.channels() == 4 && num_channels_ == 3)\n        cv::cvtColor(img, sample, cv::COLOR_BGRA2BGR);\n    else if (img.channels() == 1 && num_channels_ == 3)\n        cv::cvtColor(img, sample, cv::COLOR_GRAY2BGR);\n    else\n        sample = img;\n\n    cv::Mat sample_resized;\n    if (sample.size() != input_geometry_)\n        cv::resize(sample, sample_resized, input_geometry_);\n    else\n        sample_resized = sample;\n\n    cv::Mat sample_float;\n    if (num_channels_ == 3)\n        sample_resized.convertTo(sample_float, CV_32FC3);\n    else\n        sample_resized.convertTo(sample_float, CV_32FC1);\n\n     cv::Mat sample_normalized;\n     cv::subtract(sample_float, mean_, sample_normalized);\n\n    /* This operation will write the separate BGR planes directly to the\n     * input layer of the network because it is wrapped by the cv::Mat\n     * objects in input_channels. */\n    cv::split(sample_normalized, *input_channels);\n\n    CHECK(reinterpret_cast<float*>(input_channels->at(0).data)\n          == in_data)\n    << \"Input channels are not wrapping the input layer of the network.\";\n}\nvoid SetMean(const string& mean_value) {\n    cv::Scalar channel_mean;\n\n    if (!mean_value.empty()) {\n        stringstream ss(mean_value);\n        vector<float> values;\n        string item;\n        while (getline(ss, item, ',')) {\n            float value = std::atof(item.c_str());\n            values.push_back(value);\n        }\n        CHECK(values.size() == 1 || values.size() == num_channels_) <<\n                                                                    \"Specify either 1 mean_value or as many as channels: \" << num_channels_;\n\n        std::vector<cv::Mat> channels;\n        for (int i = 0; i < num_channels_; ++i) {\n            /* Extract an individual channel. */\n            cv::Mat channel(input_geometry_.height, input_geometry_.width, CV_32FC1,\n                            cv::Scalar(values[i]));\n            channels.push_back(channel);\n        }\n        cv::merge(channels, mean_);\n    }\n    else{\n        LOG(INFO)<<\"there is no mean_value been set!\";\n\n    }\n}\nvoid caffe_WrapInputLayer(std::vector<cv::Mat>* input_channels,caffe::Blob<float>*input_layer) {\n\n    int width = input_layer->width();\n    int height = input_layer->height();\n    float* input_data = input_layer->mutable_cpu_data();\n    for (int i = 0; i < input_layer->channels(); ++i) {\n        cv::Mat channel(height, width, CV_32FC1, input_data);\n        input_channels->push_back(channel);\n        input_data += width * height;\n    }\n}\n\nvoid caffe_Preprocess(const cv::Mat& img,\n                            std::vector<cv::Mat>* input_channels,caffe::Blob<float>*input_layer) {\n    /* Convert the input image to the input image format of the network. */\n    cv::Mat sample;\n    if (img.channels() == 3 && num_channels_ == 1)\n        cv::cvtColor(img, sample, cv::COLOR_BGR2GRAY);\n    else if (img.channels() == 4 && num_channels_ == 1)\n        cv::cvtColor(img, sample, cv::COLOR_BGRA2GRAY);\n    else if (img.channels() == 4 && num_channels_ == 3)\n        cv::cvtColor(img, sample, cv::COLOR_BGRA2BGR);\n    else if (img.channels() == 1 && num_channels_ == 3)\n        cv::cvtColor(img, sample, cv::COLOR_GRAY2BGR);\n    else\n        sample = img;\n\n    cv::Mat sample_resized;\n    if (sample.size() != input_geometry_)\n        cv::resize(sample, sample_resized, input_geometry_);\n    else\n        sample_resized = sample;\n\n    cv::Mat sample_float;\n    if (num_channels_ == 3)\n        sample_resized.convertTo(sample_float, CV_32FC3);\n    else\n        sample_resized.convertTo(sample_float, CV_32FC1);\n\n    cv::Mat sample_normalized;\n    cv::subtract(sample_float, mean_, sample_normalized);\n\n    /* This operation will write the separate BGR planes directly to the\n     * input layer of the network because it is wrapped by the cv::Mat\n     * objects in input_channels. */\n    cv::split(sample_normalized, *input_channels);\n\n    CHECK(reinterpret_cast<float*>(input_channels->at(0).data)\n          == input_layer->cpu_data())\n    << \"Input channels are not wrapping the input layer of the network.\";\n}\nint main(){\n\n\n\n    boost::shared_ptr<caffe::Net<float>> net_;\n    net_.reset(new caffe::Net<float>(\"/home/fjh/CLionProjects/mobile-deep-learning/cmake-build-debug/tools/build/E23.prototxt\",caffe::TEST));\n    net_->CopyTrainedLayersFrom(\"/home/fjh/CLionProjects/mobile-deep-learning/cmake-build-debug/tools/build/E23.caffemodel\");\n    cv::Mat img=cv::imread(\"/home/fjh/123.jpg\");\n    cv::Mat img2;\n    SetMean(\"104,117,123\");\n    cv::resize(img,img2,cv::Size(640,360));\n    float *img_data=new float[640*360*3];\n    std::vector<cv::Mat> input_channels;\n    caffe_WrapInputLayer(&input_channels,net_->input_blobs()[0]);\n    caffe_Preprocess(img2,&input_channels,net_->input_blobs()[0]);\n    net_->Forward();\n    Mtype *img_data2=new Mtype[640*360*3];\n    std::vector<cv::Mat> input_channels2;\n    WrapInputLayer(&input_channels2,img_data2);\n    Preprocess(img2,&input_channels2,img_data2);\n\n    int thread_num = 1;\n    if (mdl::Gemmer::gemmers.size() == 0) {\n\n        mdl::Gemmer::gemmers.push_back(new mdl::Gemmer());\n\n    }\n    mdl::Loader *loader = mdl::Loader::shared_instance();\n    std::string prefix(\"/home/fjh/CLionProjects/mobile-deep-learning/cmake-build-debug/tools/build/\");\n    auto t1 = mdl::time();\n    bool load_success = loader->load(prefix + \"model.min.json\", prefix + \"data.min.bin\");\n    auto t2 = mdl::time();\n    cout << \"load time : \" << mdl::time_diff(t1, t2) << \"ms\" << endl;\n    if (!load_success) {\n        cout << \"load failure\" << endl;\n        loader->clear();\n        return -1;\n    }\n    if (!loader->get_loaded()) {\n        LOG(FATAL)<<\"loader is not loaded yet\";\n    }\n    mdl::Net *net = new mdl::Net(loader->_model);\n    net->set_thread_num(thread_num);\n    int count = 1;\n    double total = 0;\n    vector<Mtype > result;\n    for (int i = 0; i < count; i++) {\n        Time t1 = mdl::time();\n/*\n        for(int j=0;j<net->_layers.size()-1;j++) {\n            if(net_->has_blob(net->_layers[j]->name())) {\n               // std::cout<<net->_layers[j]->name()<<std::endl;\n                for (int k = 0; k < net->_layers[j]->input().size(); k++) {\n                    Mtype *input_data=new Mtype[net->_layers[j]->input()[k]->count(0)];\n\n                    if(net_->has_blob(net->_layers[j]->input()[k]->get_name())) {\n                        std::cout<<net->_layers[j]->input()[k]->get_name()<<\"  \";\n                        for (int l = 0; l < net->_layers[j]->input()[k]->count(0); l++) {\n                            input_data[l] = (Mtype) *(\n                                    net_->blob_by_name(net->_layers[j]->input()[k]->get_name())->cpu_data() + l);\n                        }\n                        net->_layers[j]->input()[k]->set_data(input_data);\n                    }\n                  //  std::cout<<std::endl;\n                }\n                net->_layers[j]->forward();\n                for (int k = 0; k < net->_layers[j]->output().size(); k++) {\n                    int error_perlayer=0;\n                    for(int l=0;l<net->_layers[j]->output()[k]->count(0);l++){\n                        if(abs(abs(*(net->_layers[j]->output()[k]->get_data()+l)-*(net_->blob_by_name(net->_layers[j]->name())->cpu_data()+l))/(*(net->_layers[j]->output()[k]->get_data()+l)))>0.01){\n                            // std::cout<<*(net->_layers[j]->output()[k]->get_data()+l)<<\"    \"<<*(net_->blob_by_name(net->_layers[j]->name())->cpu_data()+l)<<std::endl;\n                            //std::cout<<abs(*(net->_layers[j]->output()[k]->get_data()+l)-*(net_->blob_by_name(net->_layers[j]->name())->cpu_data()+l))/(*(net->_layers[j]->output()[k]->get_data()+l))<<std::endl;\n                            error_perlayer++;\n                        }\n                        //std::cout<<*(net->_layers[j]->output()[k]->get_data()+l)<<\"    \"<<*(net_->blob_by_name(net->_layers[j]->name())->cpu_data()+l)<<std::endl;\n                    }\n                   // std::cout<<net->_layers[j]->output()[0]->descript_dimention()<<std::endl;\n                    //std::cout<<net_->blob_by_name(net->_layers[j]->name())->shape_string()<<std::endl;\n                    std::cout<<net->_layers[j]->name()<<\"::error_ratio:    \"<<(error_perlayer*1.0)/net->_layers[j]->output()[k]->count(0)<<std::endl;\n                    //net->_layers[j]->input()[k]->set_data(input_data);\n                }\n            }\n            for(int k=0;k<net->_layers[j]->input()[0]->count();k++){\n\n            }\n        }\n        net->_layers[net->_layers.size()-1]->forward();\n        */\n/*\n        Mtype *input_data=new Mtype[loader->_matrices[\"mbox_loc\"]->count(0)];\n        std::cout<<net_->has_blob(\"mbox_loc\")<<std::endl;\n\n        for (int k = 0; k < loader->_matrices[\"mbox_loc\"]->count(0); k++) {\n            input_data[k] = net_->bottom_vecs()[net_->layers().size()-1][0]->cpu_data()[k];\n            //std::cout<<input_data[k]<<std::endl;\n        }\n        Mtype *input_data2=new Mtype[loader->_matrices[\"mbox_conf_flatten\"]->count(0)];\n        for (int k = 0; k < loader->_matrices[\"mbox_conf_flatten\"]->count(0); k++) {\n            input_data2[k] = net_->bottom_vecs()[net_->layers().size()-1][1]->cpu_data()[k];\n        }\n        Mtype *input_data3=new Mtype[loader->_matrices[\"mbox_priorbox\"]->count(0)];\n        for (int k = 0; k < loader->_matrices[\"mbox_priorbox\"]->count(0); k++) {\n            input_data3[k] = net_->bottom_vecs()[net_->layers().size()-1][2]->cpu_data()[k];\n        }\n        loader->_matrices[\"mbox_loc\"]->set_data(input_data);\n        loader->_matrices[\"mbox_conf_flatten\"]->set_data(input_data2);\n        loader->_matrices[\"mbox_priorbox\"]->set_data(input_data3);\n        net->_layers[net->_layers.size()-1]->forward();\n        */\n        net->predict(img_data2);\n        Time t2 = mdl::time();\n        double diff = mdl::time_diff(t1, t2);\n        total += diff;\n    }\n    cout << \"total cost: \" << total / count << \"ms.\" << endl;\n    for (int num: result) {\n        cout << num << \" \";\n    }\n    cout <<endl;\n    // uncomment while testing clacissification models\n//    cout << \"the max prob index = \"<<find_max(result)<<endl;\n    cout << \"Done!\" << endl;\n//    cout << \"it \" << (is_correct_result(result) ? \"is\" : \"isn't\") << \" a correct result.\" << endl;\n    int num_weight=0;\n\n    for(int i=0;i<net_->blob_names().size();i++){\n        mdl::Matrix *layer_data=loader->_matrices[net_->blob_names()[i]];\n            if (layer_data!= nullptr) {\n                int error_perlayer=0;\n\n                for(int j=0;j<layer_data->count(0);j++){\n                    if(abs(abs(*(layer_data->get_data()+j)-*(net_->blob_by_name(net_->blob_names()[i])->cpu_data()+j))/(*(layer_data->get_data()+j)))>0.01){\n                       // std::cout<<*(layer_data->get_data()+j)<<\"    \"<<*(net_->blob_by_name(net_->blob_names()[i])->cpu_data()+j)<<std::endl;\n                        error_perlayer++;\n                    }\n                    //std::cout<<*(layer_data->get_data()+j)<<\"    \"<<*(net_->blob_by_name(net_->blob_names()[i])->cpu_data()+j)<<std::endl;\n                }\n                std::cout<<layer_data->get_name()<<\"::error_ratio:    \"<<(error_perlayer*1.0)/layer_data->count(0)<<std::endl;\n              //  std::cout<<layer_data->descript_dimention()<<\"     \"<<net_->blob_by_name(net_->blob_names()[i])->shape_string()<<std::endl;\n            }\n\n    }\n\n\n    Mtype* get_data=net->_layers[net->_layers.size()-1]->output()[0]->get_data();\n    for(int i=0;i<net->_layers[net->_layers.size()-1]->output()[0]->dimension(2);i++) {\n        float score = get_data[2];\n        if (score >= 0.7) {\n            int xmin = static_cast<int>(get_data[3] * img.cols);\n            int ymin = static_cast<int>(get_data[4] * img.rows);\n            int xmax = static_cast<int>(get_data[5] * img.cols);\n            int ymax = static_cast<int>(get_data[6] * img.rows);\n            cv::rectangle(img, cv::Rect(xmin, ymin, (xmax - xmin), (ymax - ymin)), cv::Scalar(255, 0, 0), 2);\n        }\n        get_data+=7;\n    }\n    cv::imshow(\"a\",img);\n    cv::waitKey(0);\n    /*\n    for(int i=0;i<net->_layers.size();i++){\n        if(net->_layers[i]->layer_type()==mdl::LayerType::CONVOLUTION){\n            int error_perlayer=0;\n            for(int j=0;j<net->_layers[i]->_weight[0]->count(0);j++){\n                if(abs(abs(*(net_->params()[num_weight].get()->cpu_data()+j)-*(net->_layers[i]->_weight[0]->get_data()+j))/(*(net_->params()[num_weight].get()->cpu_data()+j)))>0.01){\n                    error_perlayer++;\n                }\n              //  std::cout<<*(net_->params()[num_weight].get()->cpu_data()+j)<<\"    \"<<*(net->_layers[i]->_weight[0]->get_data()+j)<<std::endl;\n            }\n            std::cout<<net->_layers[i]->name()<<\"::error_ratio:    \"<<(error_perlayer*1.0)/net->_layers[i]->_weight[0]->count(0)<<std::endl;\n            num_weight+=2;\n            if(num_weight==20)num_weight+=1;\n        }\n    }\n*/\n\n    loader->clear();\n    delete net;\n\n\n\n    return 1;\n}", "meta": {"hexsha": "0049e3e79f87b9f7ea05d12355ccc8e9addfe146", "size": 14345, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "caffe_test/with_caffe.cpp", "max_stars_repo_name": "superFJH/robbin_site", "max_stars_repo_head_hexsha": "c72ff2615cdbdb39fd2c7a8a34d8a93004ea97a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-11-09T20:53:07.000Z", "max_stars_repo_stars_event_max_datetime": "2017-11-09T20:53:07.000Z", "max_issues_repo_path": "caffe_test/with_caffe.cpp", "max_issues_repo_name": "superFJH/robbin_site", "max_issues_repo_head_hexsha": "c72ff2615cdbdb39fd2c7a8a34d8a93004ea97a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "caffe_test/with_caffe.cpp", "max_forks_repo_name": "superFJH/robbin_site", "max_forks_repo_head_hexsha": "c72ff2615cdbdb39fd2c7a8a34d8a93004ea97a6", "max_forks_repo_licenses": ["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.8208955224, "max_line_length": 212, "alphanum_fraction": 0.5658417567, "num_tokens": 3828, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.45048579249271253}}
{"text": "/**\n * @file banditpam.cpp\n * @date 2021-07-25\n *\n * This file contains the primary C++ implementation of the BanditPAM code.\n *\n */\n#include \"banditpam.hpp\"\n\n#include <carma>\n#include <armadillo>\n#include <unordered_map>\n#include <regex>\n\n/**\n * \\brief Runs BanditPAM algorithm.\n *\n * Run the BanditPAM algorithm to identify a dataset's medoids.\n *\n * @param input_data Input data to find the medoids of\n */\nvoid BanditPAM::fit_bpam(const arma::mat& input_data) {\n  data = input_data;\n  data = arma::trans(data);\n  arma::mat medoids_mat(data.n_rows, n_medoids);\n  arma::rowvec medoid_indices(n_medoids);\n  // runs build step\n  BanditPAM::build(data, medoid_indices, medoids_mat);\n  steps = 0;\n\n  medoid_indices_build = medoid_indices;\n  arma::rowvec assignments(data.n_cols);\n  // runs swap step\n  BanditPAM::swap(data, medoid_indices, medoids_mat, assignments);\n  medoid_indices_final = medoid_indices;\n  labels = assignments;\n}\n\n/**\n * \\brief Build step for BanditPAM\n *\n * Runs build step for the BanditPAM algorithm. Draws batch sizes with replacement\n * from reference set, and uses the estimated reward of the potential medoid\n * solutions on the reference set to update the reward confidence intervals and\n * accordingly narrow the solution set.\n *\n * @param data Transposed input data to find the medoids of\n * @param medoid_indices Uninitialized array of medoids that is modified in place\n * as medoids are identified\n * @param medoids Matrix of possible medoids that is updated as the bandit\n * learns which datapoints will be unlikely to be good candidates\n */\nvoid BanditPAM::build(\n  const arma::mat& data,\n  arma::rowvec& medoid_indices,\n  arma::mat& medoids) {\n    // Parameters\n    size_t N = data.n_cols;\n    arma::rowvec N_mat(N);\n    N_mat.fill(N);\n    size_t p = (buildConfidence * N); // reciprocal of\n    bool use_absolute = true;\n    arma::rowvec estimates(N, arma::fill::zeros);\n    arma::rowvec best_distances(N);\n    best_distances.fill(std::numeric_limits<double>::infinity());\n    arma::rowvec sigma(N); // standard deviation of induced losses on reference points\n    arma::urowvec candidates(\n      N,\n      arma::fill::ones); // one hot encoding of candidates -- points not filtered out yet\n    arma::rowvec lcbs(N);\n    arma::rowvec ucbs(N);\n    arma::rowvec T_samples(N, arma::fill::zeros); // number of times calculating induced loss for reference point\n    arma::rowvec exact_mask(N, arma::fill::zeros); // computed the loss exactly for this datapoint\n\n    for (size_t k = 0; k < n_medoids; k++) {\n        // instantiate medoids one-by-online\n        size_t step_count = 0;\n        candidates.fill(1);\n        T_samples.fill(0);\n        exact_mask.fill(0);\n        estimates.fill(0);\n        sigma = build_sigma(\n                data, best_distances, batchSize, use_absolute); // computes std dev amongst batch of reference points\n\n        while (arma::sum(candidates) > precision) { // while some candidates exist\n            arma::umat compute_exactly =\n              ((T_samples + batchSize) >= N_mat) != exact_mask;\n            if (arma::accu(compute_exactly) > 0) {\n                arma::uvec targets = find(compute_exactly);\n                logHelper.comp_exact_build.push_back(targets.n_rows);\n                arma::rowvec result =\n                  build_target(data, targets, N, best_distances, use_absolute); // induced loss for these targets over all reference points\n                estimates.cols(targets) = result;\n                ucbs.cols(targets) = result;\n                lcbs.cols(targets) = result;\n                exact_mask.cols(targets).fill(1);\n                T_samples.cols(targets) += N;\n                candidates.cols(targets).fill(0);\n            }\n            if (arma::sum(candidates) < precision) {\n                break;\n            }\n            arma::uvec targets = arma::find(candidates);\n            arma::rowvec result = build_target(\n              data, targets, batchSize, best_distances, use_absolute); // induced loss for the targets (sample)\n            estimates.cols(targets) =\n              ((T_samples.cols(targets) % estimates.cols(targets)) +\n               (result * batchSize)) /\n              (batchSize + T_samples.cols(targets)); // update the running average\n            T_samples.cols(targets) += batchSize;\n            arma::rowvec adjust(targets.n_rows);\n            adjust.fill(p);\n            adjust = arma::log(adjust);\n            arma::rowvec cb_delta =\n              sigma.cols(targets) %\n              arma::sqrt(adjust / T_samples.cols(targets));\n            ucbs.cols(targets) = estimates.cols(targets) + cb_delta;\n            lcbs.cols(targets) = estimates.cols(targets) - cb_delta;\n            candidates = (lcbs < ucbs.min()) && (exact_mask == 0);\n            step_count++;\n        }\n\n        medoid_indices.at(k) = lcbs.index_min();\n        medoids.unsafe_col(k) = data.unsafe_col(medoid_indices(k));\n\n        // don't need to do this on final iteration\n        for (size_t i = 0; i < N; i++) {\n            double cost = (this->*lossFn)(data, i, medoid_indices(k));\n            if (cost < best_distances(i)) {\n                best_distances(i) = cost;\n            }\n        }\n        use_absolute = false; // use difference of loss for sigma and sampling,\n                              // not absolute\n        logHelper.loss_build.push_back(arma::mean(arma::mean(best_distances)));\n        logHelper.p_build.push_back(static_cast<float>(1)/static_cast<float>(p));\n    }\n}\n\n/**\n * \\brief Estimates the mean reward for each arm in build step\n *\n * Estimates the mean reward (or loss) for each arm in the identified targets\n * in the build step and returns a list of the estimated reward.\n *\n * @param data Transposed input data to find the medoids of\n * @param target Set of target datapoints to be estimated\n * @param batch_size Number of datapoints sampled for updating confidence\n * intervals\n * @param best_distances Array of best distances from each point to previous set\n * of medoids\n * @param use_absolute Determines whether the absolute cost is added to the total\n */\narma::rowvec BanditPAM::build_target(\n  const arma::mat& data,\n  arma::uvec& target,\n  size_t batch_size,\n  arma::rowvec& best_distances,\n  bool use_absolute) {\n    size_t N = data.n_cols;\n    arma::rowvec estimates(target.n_rows, arma::fill::zeros);\n    arma::uvec tmp_refs = arma::randperm(N,\n                                   batch_size); // without replacement, requires\n                                                // updated version of armadillo\n#pragma omp parallel for\n    for (size_t i = 0; i < target.n_rows; i++) {\n        double total = 0;\n        for (size_t j = 0; j < tmp_refs.n_rows; j++) {\n            double cost =\n              (this->*lossFn)(data, tmp_refs(j), target(i));\n            if (use_absolute) {\n                total += cost;\n            } else {\n                total += cost < best_distances(tmp_refs(j))\n                           ? cost\n                           : best_distances(tmp_refs(j));\n                total -= best_distances(tmp_refs(j));\n            }\n        }\n        estimates(i) = total / batch_size;\n    }\n    return estimates;\n}\n\n/**\n * \\brief Swap step for BanditPAM\n *\n * Runs Swap step for the BanditPAM algorithm. Draws batch sizes with replacement\n * from reference set, and uses the estimated reward of the potential medoid\n * solutions on the reference set to update the reward confidence intervals and\n * accordingly narrow the solution set.\n *\n * @param data Transposed input data to find the medoids of\n * @param medoid_indices Array of medoid indices created from the build step\n * that is modified in place as better medoids are identified\n * @param medoids Matrix of possible medoids that is updated as the bandit\n * learns which datapoints will be unlikely to be good candidates\n * @param assignments Uninitialized array of indices corresponding to each\n * datapoint assigned the index of the medoid it is closest to\n */\nvoid BanditPAM::swap(\n  const arma::mat& data,\n  arma::rowvec& medoid_indices,\n  arma::mat& medoids,\n  arma::rowvec& assignments) {\n    size_t N = data.n_cols;\n    size_t p = (N * n_medoids * swapConfidence); // reciprocal\n\n    arma::mat sigma(n_medoids, N, arma::fill::zeros);\n\n    arma::rowvec best_distances(N);\n    arma::rowvec second_distances(N);\n    size_t iter = 0;\n    bool swap_performed = true;\n    arma::umat candidates(n_medoids, N, arma::fill::ones);\n    arma::umat exact_mask(n_medoids, N, arma::fill::zeros);\n    arma::mat estimates(n_medoids, N, arma::fill::zeros);\n    arma::mat lcbs(n_medoids, N);\n    arma::mat ucbs(n_medoids, N);\n    arma::umat T_samples(n_medoids, N, arma::fill::zeros);\n\n    // continue making swaps while loss is decreasing\n    while (swap_performed && iter < max_iter) {\n        iter++;\n\n        // calculate quantities needed for swap, best_distances and sigma\n        calc_best_distances_swap(\n          data, medoid_indices, best_distances, second_distances, assignments);\n\n        sigma = swap_sigma(data,\n                           batchSize,\n                           best_distances,\n                           second_distances,\n                           assignments);\n\n        candidates.fill(1);\n        exact_mask.fill(0);\n        estimates.fill(0);\n        T_samples.fill(0);\n\n        // while there is at least one candidate (double comparison issues)\n        while (arma::accu(candidates) > 0.5) {\n            calc_best_distances_swap(\n              data, medoid_indices, best_distances, second_distances, assignments);\n\n            // compute exactly if it's been samples more than N times and hasn't\n            // been computed exactly already\n            arma::umat compute_exactly =\n              ((T_samples + batchSize) >= N) != (exact_mask);\n            arma::uvec targets = arma::find(compute_exactly);\n\n            if (targets.size() > 0) {\n                logHelper.comp_exact_swap.push_back(targets.size());\n                arma::vec result = swap_target(data,\n                                               medoid_indices,\n                                               targets,\n                                               N,\n                                               best_distances,\n                                               second_distances,\n                                               assignments);\n                estimates.elem(targets) = result;\n                ucbs.elem(targets) = result;\n                lcbs.elem(targets) = result;\n                exact_mask.elem(targets).fill(1);\n                T_samples.elem(targets) += N;\n\n                candidates = (lcbs < ucbs.min()) && (exact_mask == 0);\n            }\n            if (arma::accu(candidates) < precision) {\n                break;\n            }\n            targets = arma::find(candidates);\n            arma::vec result = swap_target(data,\n                                           medoid_indices,\n                                           targets,\n                                           batchSize,\n                                           best_distances,\n                                           second_distances,\n                                           assignments);\n            estimates.elem(targets) =\n              ((T_samples.elem(targets) % estimates.elem(targets)) +\n               (result * batchSize)) /\n              (batchSize + T_samples.elem(targets));\n            T_samples.elem(targets) += batchSize;\n            arma::vec adjust(targets.n_rows);\n            adjust.fill(p);\n            adjust = arma::log(adjust);\n            arma::vec cb_delta = sigma.elem(targets) %\n                                 arma::sqrt(adjust / T_samples.elem(targets));\n\n            ucbs.elem(targets) = estimates.elem(targets) + cb_delta;\n            lcbs.elem(targets) = estimates.elem(targets) - cb_delta;\n            candidates = (lcbs < ucbs.min()) && (exact_mask == 0);\n            targets = arma::find(candidates);\n        }\n        // now switch medoids\n        arma::uword new_medoid = lcbs.index_min();\n        // extract medoid of swap\n        size_t k = new_medoid % medoids.n_cols;\n\n        // extract data point of swap\n        size_t n = new_medoid / medoids.n_cols;\n        swap_performed = medoid_indices(k) != n;\n        steps++;\n\n        medoid_indices(k) = n;\n        medoids.col(k) = data.col(medoid_indices(k));\n        calc_best_distances_swap(\n          data, medoid_indices, best_distances, second_distances, assignments);\n        sigma_log(sigma);\n        logHelper.loss_swap.push_back(arma::mean(arma::mean(best_distances)));\n        logHelper.p_swap.push_back(static_cast<float>(1)/static_cast<float>(p));\n    }\n}\n\n/**\n * \\brief Estimates the mean reward for each arm in swap step\n *\n * Estimates the mean reward (or loss) for each arm in the identified targets\n * in the swap step and returns a list of the estimated reward.\n *\n * @param data Transposed input data to find the medoids of\n * @param sigma Dispersion paramater for each datapoint\n * @param targets Set of target datapoints to be estimated\n * @param batch_size Number of datapoints sampled for updating confidence\n * intervals\n * @param best_distances Array of best distances from each point to previous set\n * of medoids\n * @param second_best_distances Array of second smallest distances from each\n * point to previous set of medoids\n * @param assignments Assignments of datapoints to their closest medoid\n */\narma::vec BanditPAM::swap_target(\n  const arma::mat& data,\n  arma::rowvec& medoid_indices,\n  arma::uvec& targets,\n  size_t batch_size,\n  arma::rowvec& best_distances,\n  arma::rowvec& second_best_distances,\n  arma::rowvec& assignments) {\n    size_t N = data.n_cols;\n    arma::vec estimates(targets.n_rows, arma::fill::zeros);\n    arma::uvec tmp_refs = arma::randperm(N,\n                                   batch_size); // without replacement, requires\n                                                // updated version of armadillo\n\n// for each considered swap\n#pragma omp parallel for\n    for (size_t i = 0; i < targets.n_rows; i++) {\n        double total = 0;\n        // extract data point of swap\n        size_t n = targets(i) / medoid_indices.n_cols;\n        size_t k = targets(i) % medoid_indices.n_cols;\n        // calculate total loss for some subset of the data\n        for (size_t j = 0; j < batch_size; j++) {\n            double cost = (this->*lossFn)(data, n, tmp_refs(j));\n            if (k == assignments(tmp_refs(j))) {\n                if (cost < second_best_distances(tmp_refs(j))) {\n                    total += cost;\n                } else {\n                    total += second_best_distances(tmp_refs(j));\n                }\n            } else {\n                if (cost < best_distances(tmp_refs(j))) {\n                    total += cost;\n                } else {\n                    total += best_distances(tmp_refs(j));\n                }\n            }\n            total -= best_distances(tmp_refs(j));\n        }\n        estimates(i) = total / tmp_refs.n_rows;\n    }\n    return estimates;\n}\n", "meta": {"hexsha": "82bacce09773f1a982723ef8f54c6ee254364809", "size": 15047, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/banditpam.cpp", "max_stars_repo_name": "ThrunGroup/BanditPAM", "max_stars_repo_head_hexsha": "ca5c8ba2ec8227db979c3b6381c61846cf18d8ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 251.0, "max_stars_repo_stars_event_min_datetime": "2020-10-22T19:37:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T11:21:31.000Z", "max_issues_repo_path": "src/banditpam.cpp", "max_issues_repo_name": "ThrunGroup/BanditPAM", "max_issues_repo_head_hexsha": "ca5c8ba2ec8227db979c3b6381c61846cf18d8ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 152.0, "max_issues_repo_issues_event_min_datetime": "2020-12-05T00:32:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T12:33:47.000Z", "max_forks_repo_path": "src/banditpam.cpp", "max_forks_repo_name": "ThrunGroup/BanditPAM", "max_forks_repo_head_hexsha": "ca5c8ba2ec8227db979c3b6381c61846cf18d8ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20.0, "max_forks_repo_forks_event_min_datetime": "2021-05-07T16:31:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T13:51:54.000Z", "avg_line_length": 40.0186170213, "max_line_length": 139, "alphanum_fraction": 0.595002326, "num_tokens": 3312, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996142, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4504857924927125}}
{"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_EXPONENTIAL_CONSTANTS_LOG_2_HPP_INCLUDED\n#define NT2_EXPONENTIAL_CONSTANTS_LOG_2_HPP_INCLUDED\n\n#include <nt2/include/functor.hpp>\n#include <boost/simd/constant/hierarchy.hpp>\n#include <boost/simd/constant/register.hpp>\n\nnamespace nt2\n{\n  namespace tag\n  {\n    /*!\n      @brief Log_2 generic tag\n\n      Represents the Log_2 constant in generic contexts.\n\n      @par Models:\n      Hierarchy\n    **/\n    BOOST_SIMD_CONSTANT_REGISTER( Log_2, double\n                                , 0, 0x3f317218UL\n                                , 0x3fe62e42fefa39efULL\n                                )\n  }\n  namespace ext\n  {\n    template<class Site, class... Ts>\n    BOOST_FORCEINLINE generic_dispatcher<tag::Log_2, Site> dispatching_Log_2(adl_helper, boost::dispatch::meta::unknown_<Site>, boost::dispatch::meta::unknown_<Ts>...)\n    {\n      return generic_dispatcher<tag::Log_2, Site>();\n    }\n    template<class... Args>\n    struct impl_Log_2;\n  }\n /*!\n    Generates constant Log_2. (\\f$\\log(2)\\f$)\n\n    @par Semantic:\n\n    @code\n    T r = Log_2<T>();\n    @endcode\n\n    is similar to:\n\n    @code\n      r =  T(0.6931471805599453094172321214581765680755001343602553);\n    @endcode\n\n  **/\n  BOOST_SIMD_CONSTANT_IMPLEMENTATION(tag::Log_2, Log_2);\n}\n\n#endif\n", "meta": {"hexsha": "bff737f0914632736f4795bf8bb6fe4fde86d5c9", "size": 1760, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/exponential/include/nt2/exponential/constants/log_2.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "modules/core/exponential/include/nt2/exponential/constants/log_2.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/core/exponential/include/nt2/exponential/constants/log_2.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.9365079365, "max_line_length": 167, "alphanum_fraction": 0.5710227273, "num_tokens": 443, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544335934766, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.4504772714955705}}
{"text": "#include <iostream>\n#include <sferes/phen/parameters.hpp>\n#include <sferes/gen/evo_float.hpp>\n#include <sferes/ea/nsga2.hpp>\n#include <sferes/eval/eval.hpp>\n#include <sferes/stat/pareto_front.hpp>\n#include <sferes/modif/dummy.hpp>\n#include <sferes/run.hpp>\n#include <boost/program_options.hpp>\n\n#include <cuda_runtime.h>\nusing namespace sferes;\nusing namespace sferes::gen::evo_float;\n\nstruct Params\n{\n  struct evo_float\n  {\n\n\tSFERES_CONST float cross_rate = 0.1f;\n\tSFERES_CONST float mutation_rate = 0.1f;\n    SFERES_CONST float eta_m = 15.0f;\n    SFERES_CONST float eta_c = 10.0f;\n    SFERES_CONST mutation_t mutation_type = polynomial;\n    SFERES_CONST cross_over_t cross_over_type = sbx;\n  };\n  struct pop\n  {\n    SFERES_CONST unsigned size = 300;\n    SFERES_CONST unsigned nb_gen = 500;\n    SFERES_CONST int dump_period = 50;\n    SFERES_CONST int initial_aleat = 1;\n  };\n  struct parameters\n  {\n    SFERES_CONST float min = 0.0f;\n    SFERES_CONST float max = 1.0f;\n  };\n};\n\n\ntemplate<typename Indiv>\nfloat _g(const Indiv &ind)\n{\n  float g = 0.0f;\n  assert(ind.size() == 30);\n  for (size_t i = 1; i < 30; ++i)\n    g += ind.data(i);\n  g = 9.0f * g / 29.0f;\n  g += 1.0f;\n  return g;\n}\n\nSFERES_FITNESS(FitZDT2, sferes::fit::Fitness)\n{ \n public:\n  FitZDT2()  {}\n  template<typename Indiv>\n    void eval(Indiv& ind) \n  {\n    this->_objs.resize(2);\n    float f1 = ind.data(0);\n    float g = _g(ind);\n    float h = 1.0f - pow((f1 / g), 2.0);\n    float f2 = g * h;\n    this->_objs[0] = -f1;\n    this->_objs[1] = -f2;\n  }\n};\n\n\n\n\nint main(int argc, char **argv)\n{\n  std::cout<<\"running \"<<argv[0]<<\" ... try --help for options (verbose)\"<<std::endl;\n\n  typedef gen::EvoFloat<30, Params> gen_t;\n  typedef phen::Parameters<gen_t, FitZDT2<Params>, Params> phen_t;\n  typedef eval::Eval<Params> eval_t;\n  typedef boost::fusion::vector<stat::ParetoFront<phen_t, Params> >  stat_t;\n  typedef modif::Dummy<> modifier_t;\n  typedef ea::Nsga2<phen_t, eval_t, stat_t, modifier_t, Params> ea_t;\n  ea_t ea;\n\n  run_ea(argc, argv, ea);\n\n  return 0;\n}\n", "meta": {"hexsha": "1059e7451ae68d526d405d2ef6d434a8d37d318f", "size": 2029, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sferes/exp/example/example.cpp", "max_stars_repo_name": "Evolving-AI-Lab/innovation-engine", "max_stars_repo_head_hexsha": "58c7fcc3cbe3d6f8f59f87d95bdb5f2302f425ba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2015-09-20T03:03:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T06:50:20.000Z", "max_issues_repo_path": "sferes/exp/example/example.cpp", "max_issues_repo_name": "Evolving-AI-Lab/innovation-engine", "max_issues_repo_head_hexsha": "58c7fcc3cbe3d6f8f59f87d95bdb5f2302f425ba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-08-11T07:24:50.000Z", "max_issues_repo_issues_event_max_datetime": "2016-08-17T01:19:57.000Z", "max_forks_repo_path": "sferes/exp/example/example.cpp", "max_forks_repo_name": "Evolving-AI-Lab/innovation-engine", "max_forks_repo_head_hexsha": "58c7fcc3cbe3d6f8f59f87d95bdb5f2302f425ba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2015-11-15T01:52:25.000Z", "max_forks_repo_forks_event_max_datetime": "2018-06-11T23:42:58.000Z", "avg_line_length": 22.5444444444, "max_line_length": 85, "alphanum_fraction": 0.6633809759, "num_tokens": 695, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544335934766, "lm_q2_score": 0.6442251201477015, "lm_q1q2_score": 0.45047727149557043}}
{"text": "#pragma once\n\n#include <memory>\n#include <Eigen/Dense>\n#include <vector>\n#include \"math/fields/ScalarField.h\"\n\nclass VoxelGrid2D {\npublic:\n    /**\n     * Initialize from edge soup using extremely fast winding number\n     * @param edges\n     * @param grid_spacing\n     * @param max_resolution\n     */\n    VoxelGrid2D(const std::vector<std::pair<Eigen::Vector2d, Eigen::Vector2d>> &edges, double grid_spacing, int max_resolution=std::numeric_limits<int>::max());\n\n    /**\n     * Initialize from 2D points\n     * @param points\n     * @param grid_spacing\n     * @param max_resolution\n     */\n    VoxelGrid2D(const Eigen::Ref<const Eigen::MatrixX2d> &points, double grid_spacing, int max_resolution=std::numeric_limits<int>::max());\n\n    /**\n     * Initialize directly from data (x,y) -> data[x + y * x_res]\n     * @param data data in row-major order\n     * @param width number of columns\n     * @param height number of rows (width * height must equal the number of elements in data)\n     * @param min_x x coordinate of element 0\n     * @param min_y y coordinate of element 0\n     * @param spacing spacing between grid elements\n     */\n    VoxelGrid2D(std::vector<double> data, int width, int height, double min_x, double min_y, double spacing);\n    double query(const Eigen::Ref<const Eigen::Vector2d> &pt) const;\n    double query(int row, int col) const;\n    /**\n     * Compute marching squares contours from grid data. Contour is counter-clockwise encircling regions greater than the threshold.\n     * @param hierarchy Map from indices of returned contours to lists of interior contours, if any. If there are N contours,\n     * the index N gives the list of outer contours not contained by any other contours.\n     * @param threshold value at which to extract an isosurface from the voxel grid.\n     * @return\n     */\n    std::vector<std::vector<Eigen::Vector2d>> marching_squares(std::vector<std::vector<int>> &hierarchy, double threshold=NAN, bool bisect=true) const;\n\n    /**\n     * Initialize from a scalar field\n     * @param field 2D scalar field\n     * See data constructor for other argument descriptions\n     */\n    VoxelGrid2D(ScalarField<2>::Handle field, double min_x, double min_y, double max_x, double max_y, double spacing, int max_resolution=std::numeric_limits<int>::max());\n\n    /**\n     * Compute marching squares contours from grid data.\n     * @param threshold value at which to extract an isosurface from the voxel grid.\n     * @return\n     */\n    std::vector<std::vector<Eigen::Vector2d>> marching_squares(double threshold=NAN, bool bisect=true) const;\n    Eigen::Vector2i resolution() const;\n    void dilate(double threshold, bool erode, const Eigen::Ref<const Eigen::MatrixXi> &kernel=Eigen::Matrix3i::Ones(), int centerRow=1, int centerCol=1);\n    void discretize(double threshold);\nprivate:\n    /**\n     * Sets the resolution and grid spacing based on a maximum resolution and the current dimensions\n     * @param grid_spacing\n     * @param max_resolution\n     * @param minPt\n     * @param maxPt\n     * @param clear\n     */\n    void set_resolution(double grid_spacing, int max_resolution, const Eigen::Vector2d &minPt, const Eigen::Vector2d &maxPt, bool clear);\n    std::vector<std::vector<Eigen::Vector2d>> marching_squares(std::vector<std::vector<int>> &hierarchy, bool compute_hierarchy, double threshold, bool bisect=true) const;\n    std::vector<double> data_;\n    Eigen::Vector2d minPt_;\n    Eigen::Array2i res_; //x, y\n    double spacing_;\n    double min_value_;\n    ScalarField<2>::Handle field_;\n};", "meta": {"hexsha": "813d9e4bb5a0f3a06fcfc9ddc7d36d60e62c3fb0", "size": 3531, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/geometry/shapes2/VoxelGrid.hpp", "max_stars_repo_name": "ShnitzelKiller/Reverse-Engineering-Carpentry", "max_stars_repo_head_hexsha": "585b5ff053c7e3bf286b663a584bc83687691bd6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-09-08T07:28:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T21:12:40.000Z", "max_issues_repo_path": "src/geometry/shapes2/VoxelGrid.hpp", "max_issues_repo_name": "ShnitzelKiller/Reverse-Engineering-Carpentry", "max_issues_repo_head_hexsha": "585b5ff053c7e3bf286b663a584bc83687691bd6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-09-21T14:40:55.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-26T01:19:38.000Z", "max_forks_repo_path": "src/geometry/shapes2/VoxelGrid.hpp", "max_forks_repo_name": "ShnitzelKiller/Reverse-Engineering-Carpentry", "max_forks_repo_head_hexsha": "585b5ff053c7e3bf286b663a584bc83687691bd6", "max_forks_repo_licenses": ["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.1375, "max_line_length": 171, "alphanum_fraction": 0.6981025205, "num_tokens": 878, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.4504772634203902}}
{"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/*!\n * \\file\n**/\n#ifndef BOOST_SIMD_TOOLBOX_CONSTANT_CONSTANTS_HALFEPS_HPP_INCLUDED\n#define BOOST_SIMD_TOOLBOX_CONSTANT_CONSTANTS_HALFEPS_HPP_INCLUDED\n\n#include <boost/simd/include/functor.hpp>\n#include <boost/simd/sdk/constant/register.hpp>\n#include <boost/simd/sdk/constant/constant.hpp>\n\n/*!\n * \\ingroup boost_simd_constant\n * \\defgroup boost_simd_constant_halfeps Halfeps\n *\n * \\par Description\n * Constant Halfeps\n * \\arg 1 for integer types\n * \\arg \\f$= \\2^{-53}\\f$ for double\n * \\arg \\f$= \\2^{-24}\\f$ for float\n * \\par\n * The value of this constant is type dependant. This means that for different\n * types it does not represent the same mathematical number.\n *\n * \\par Header file\n *\n * \\code\n * #include <nt2/include/functions/halfeps.hpp>\n * \\endcode\n *\n *\n * \\synopsis\n *\n * \\code\n * namespace boost::simd\n * {\n *   template <class T,class A0>\n *     meta::call<tag::halfeps_(A0)>::type\n *     Halfeps();\n * }\n * \\endcode\n *\n *\n * \\param T template parameter of Halfeps\n *\n * \\return type T value\n *\n *\n**/\n\nnamespace boost { namespace simd\n{\n  namespace tag\n  {\n    /*!\n     * \\brief Define the tag Halfeps of functor Halfeps\n     *        in namespace boost::simd::tag for toolbox boost.simd.constant\n    **/\n    BOOST_SIMD_CONSTANT_REGISTER( Halfeps, double, 1\n                                , 0x33800000, 0x3CA0000000000000ULL\n                                );\n  }\n\n  BOOST_SIMD_CONSTANT_IMPLEMENTATION(boost::simd::tag::Halfeps, Halfeps)\n} }\n\n#include <boost/simd/sdk/constant/common.hpp>\n\n#endif\n", "meta": {"hexsha": "586a04cc65d509970609ba6318a365095de0bb3e", "size": 2023, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/constant/include/boost/simd/toolbox/constant/constants/halfeps.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/constant/include/boost/simd/toolbox/constant/constants/halfeps.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/constant/include/boost/simd/toolbox/constant/constants/halfeps.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": 26.2727272727, "max_line_length": 80, "alphanum_fraction": 0.598615917, "num_tokens": 509, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544335934766, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.45047726194282356}}
{"text": "/*\n\nCopyright (c) 2005-2021, University of Oxford.\nAll rights reserved.\n\nUniversity of Oxford means the Chancellor, Masters and Scholars of the\nUniversity of Oxford, having an administrative office at Wellington\nSquare, Oxford OX1 2JD, UK.\n\nThis file is part of Chaste.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n * Redistributions of source code must retain the above copyright notice,\n   this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice,\n   this list of conditions and the following disclaimer in the documentation\n   and/or other materials provided with the distribution.\n * Neither the name of the University of Oxford nor the names of its\n   contributors may be used to endorse or promote products derived from this\n   software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\nGOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\nHOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\nLIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\nOF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*/\n\n\n#ifndef CHASTEELLIPSOID_HPP_\n#define CHASTEELLIPSOID_HPP_\n\n#include \"ChasteSerialization.hpp\"\n#include <boost/serialization/base_object.hpp>\n\n#include \"AbstractChasteRegion.hpp\"\n#include \"ChastePoint.hpp\"\n\n\n/**\n * This class defines a 3D ellipsoid and provides a method to check\n * if a given point is contained in the volume.\n */\ntemplate <unsigned SPACE_DIM>\nclass ChasteEllipsoid : public AbstractChasteRegion<SPACE_DIM>\n{\n    /** Needed for serialization. */\n    friend class boost::serialization::access;\n    /**\n     * Archive the member variables.\n     *\n     * @param archive\n     * @param version\n     */\n    template<class Archive>\n    void serialize(Archive & archive, const unsigned int version)\n    {\n        archive & boost::serialization::base_object<AbstractChasteRegion<SPACE_DIM> >(*this);\n    }\n\nprivate:\n    /** Centre of the ellipsoid. */\n    ChastePoint<SPACE_DIM> mCentre;\n\n    /** Radii of the ellipsoid. */\n    ChastePoint<SPACE_DIM> mRadii;\n\npublic:\n    /**\n     * The (axis aligned) ellipsoid is defined by its centre and its radii in the x, y and z directions.\n     *\n     * @param rCentre Centre of the ellipsoid.\n     * @param rRadii Radii of the ellipsoid.\n     */\n    ChasteEllipsoid(ChastePoint<SPACE_DIM>& rCentre, ChastePoint<SPACE_DIM>& rRadii);\n\n    /**\n     * @return true if a given point is contained in the ellipsoid.\n     *\n     * @param rPointToCheck Point to be checked to be contained in the ellipsoid.\n     */\n    bool DoesContain(const ChastePoint<SPACE_DIM>& rPointToCheck) const;\n\n    /** @return centre of the ellipsoid */\n    const ChastePoint<SPACE_DIM>& rGetCentre() const;\n\n    /** @return radii of the ellipsoid */\n    const ChastePoint<SPACE_DIM>& rGetRadii() const;\n};\n\n// Declare identifier for the serializer\n#include \"SerializationExportWrapper.hpp\"\nEXPORT_TEMPLATE_CLASS_SAME_DIMS(ChasteEllipsoid)\n\nnamespace boost\n{\nnamespace serialization\n{\n\ntemplate<class Archive, unsigned SPACE_DIM>\ninline void save_construct_data(\n    Archive & ar, const ChasteEllipsoid<SPACE_DIM> * t, const unsigned int file_version)\n{\n    const ChastePoint<SPACE_DIM>* p_centre =  &(t->rGetCentre());\n    const ChastePoint<SPACE_DIM>* p_radii =  &(t->rGetRadii());\n    ar & p_centre;\n    ar & p_radii;\n}\n\n/**\n * Allow us to not need a default constructor, by specifying how Boost should\n * instantiate an instance (using existing constructor)\n */\ntemplate<class Archive, unsigned SPACE_DIM>\ninline void load_construct_data(\n    Archive & ar, ChasteEllipsoid<SPACE_DIM> * t, const unsigned int file_version)\n{\n    ChastePoint<SPACE_DIM>* p_centre;\n    ChastePoint<SPACE_DIM>* p_radii;\n\n    ar & p_centre;\n    ar & p_radii;\n\n    ::new(t)ChasteEllipsoid<SPACE_DIM>((*p_centre), (*p_radii));\n\n    delete p_centre;\n    delete p_radii;\n}\n}\n} // namespace ...\n\n#endif /*CHASTEELLIPSOID_HPP_*/\n", "meta": {"hexsha": "f34d040690cdc0bd5abf1db74ae3660c5906f3e9", "size": 4545, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "mesh/src/utilities/ChasteEllipsoid.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": "mesh/src/utilities/ChasteEllipsoid.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": "mesh/src/utilities/ChasteEllipsoid.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": 32.4642857143, "max_line_length": 104, "alphanum_fraction": 0.7423542354, "num_tokens": 1056, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251064863695, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.4504772579052335}}
{"text": "/* This file is part of the Tomographer project, which is distributed under the\n * terms of the MIT license.\n *\n * The MIT License (MIT)\n *\n * Copyright (c) 2016 ETH Zurich, Institute for Theoretical Physics, Philippe Faist\n * Copyright (c) 2017 Caltech, Institute for Quantum Information and Matter, Philippe Faist\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n#include <cmath>\n\n#include <string>\n#include <sstream>\n#include <random>\n\n#include <boost/math/constants/constants.hpp>\n\n// definitions for Tomographer test framework -- this must be included before any\n// <Eigen/...> or <tomographer/...> header\n#include \"test_tomographer.h\"\n\n#include <tomographer/mathtools/check_derivatives.h>\n#include <tomographer/tools/eigenutil.h>\n\n\n// -----------------------------------------------------------------------------\n// fixture(s)\n\n\ntemplate<typename EigenPointType_, typename EigenDerivativesType_, int XDims, int ValDims>\nstruct check_derivatives_fixture\n{\n  static constexpr int xdims = XDims;\n  static constexpr int valdims = ValDims;\n\n  typedef EigenPointType_ EigenPointType;\n  typedef EigenDerivativesType_ EigenDerivativesType;\n\n  typedef typename EigenPointType::Scalar XScalar;\n  typedef typename EigenDerivativesType::Scalar ValScalar;\n\n  check_derivatives_fixture() { }\n  ~check_derivatives_fixture() { }\n\n  inline EigenPointType random_point(int seed) const\n  {\n    std::mt19937 rng((std::mt19937::result_type)seed);\n    std::uniform_real_distribution<XScalar> dist(0.1, 2.0);\n    return Tomographer::Tools::denseRandom<EigenPointType>(rng, dist, xdims);\n  }\n\n  //\n  // Function: f_j(\\vec x) =  \\sum (1+i+2*j) * x_i^(1+(i%2))\n  //\n  static void fn(Eigen::Ref<Eigen::Matrix<ValScalar, Eigen::Dynamic, 1> > vals,\n                 const Eigen::Ref<const EigenPointType> & x)\n  {\n    vals = Eigen::Matrix<ValScalar, Eigen::Dynamic, 1>::Zero(valdims);\n    for (int j = 0; j < valdims; ++j) {\n      for (int i = 0; i < xdims; ++i) {\n        vals(j) += (1+i+2*j) * std::pow(x(i), 1+(i%2));\n      }\n    }\n  }\n\n  void derivative_at(Eigen::Ref<EigenDerivativesType> derivatives,\n                     const Eigen::Ref<const EigenPointType> & x)\n  {\n    for (int j = 0; j < valdims; ++j) {\n      for (int i = 0; i < xdims; ++i) {\n        derivatives(j,i) = (float)( (1+i+2*j) * (1+(i%2)) * std::pow(x(i),i%2) );\n      }\n    }\n  }\n  \n};\n\ntemplate<typename EigenPointType_, typename EigenDerivativesType_, int XDims, int ValDims>\nconstexpr int check_derivatives_fixture<EigenPointType_,EigenDerivativesType_, XDims, ValDims>::xdims;\ntemplate<typename EigenPointType_, typename EigenDerivativesType_, int XDims, int ValDims>\nconstexpr int check_derivatives_fixture<EigenPointType_,EigenDerivativesType_, XDims, ValDims>::valdims;\n\n// -----------------------------------------------------------------------------\n// test suites\n\n\ntypedef check_derivatives_fixture<Eigen::VectorXd, Eigen::ArrayXXd, 4, 1> Fixture1val;\ntypedef check_derivatives_fixture<Eigen::VectorXd, Eigen::ArrayXXf, 4, 1> Fixture1val_d_f;\ntypedef check_derivatives_fixture<Eigen::VectorXd, Eigen::ArrayXXd, 10, 6> FixtureSeveralVals;\n\nBOOST_AUTO_TEST_SUITE(test_mathtools_check_derivatives)\n\nBOOST_FIXTURE_TEST_CASE(one_val, Fixture1val)\n{\n  BOOST_MESSAGE(\"enter test; xdims=\"<<xdims<<\", valdims=\"<<valdims) ;\n\n  EigenPointType x(random_point(0));\n  EigenDerivativesType der(EigenDerivativesType::Zero(valdims,xdims));\n\n  derivative_at(der, x);\n\n  BOOST_MESSAGE(\"Derivatives = \\n\" << der) ;\n\n  BOOST_MESSAGE(\"test correct ...\") ;\n  {\n    std::stringstream stream;\n    bool ok = Tomographer::MathTools::check_derivatives(der, x, fn, valdims, 1e-6, 1e-4, stream);\n    BOOST_MESSAGE(stream.str()) ;\n    BOOST_CHECK(ok) ;\n  }\n\n  der(0,2) = der(0,2)*2 + 1.0;\n\n  BOOST_MESSAGE(\"test wrong ...\") ;\n  {\n    std::stringstream stream;\n    bool ok = Tomographer::MathTools::check_derivatives(der, x, fn, valdims, 1e-6, 1e-4, stream);\n    BOOST_MESSAGE(stream.str()) ;\n    BOOST_CHECK( !ok ) ;\n  }\n}\n\nBOOST_FIXTURE_TEST_CASE(one_val_d_f, Fixture1val_d_f)\n{\n  EigenPointType x(random_point(90876));\n  EigenDerivativesType der(EigenDerivativesType::Zero(valdims, xdims));\n\n  derivative_at(der, x);\n\n  {\n    std::stringstream stream;\n    bool ok = Tomographer::MathTools::check_derivatives(der, x, fn, valdims, 1e-4, 1e-2f, stream);\n    BOOST_MESSAGE(stream.str()) ;\n    BOOST_CHECK(ok) ;\n  }\n\n  der(0,2) = der(0,2)*2 + 1.f;\n\n  {\n    std::stringstream stream;\n    bool ok = Tomographer::MathTools::check_derivatives(der, x, fn, valdims, 1e-4, 1e-2f, stream);\n    BOOST_MESSAGE(stream.str()) ;\n    BOOST_CHECK( !ok ) ;\n  }\n}\n\nBOOST_FIXTURE_TEST_CASE(several_vals, FixtureSeveralVals)\n{\n  EigenPointType x(random_point(151));\n  EigenDerivativesType der(EigenDerivativesType::Zero(valdims, xdims));\n\n  derivative_at(der, x);\n\n  {\n    std::stringstream stream;\n    bool ok = Tomographer::MathTools::check_derivatives(der, x, fn, valdims, 1e-6, 1e-4, stream);\n    BOOST_MESSAGE(stream.str()) ;\n    BOOST_CHECK(ok) ;\n  }\n\n  der(0,2) = der(0,2)*2 + 1.0;\n\n  {\n    std::stringstream stream;\n    bool ok = Tomographer::MathTools::check_derivatives(der, x, fn, valdims, 1e-6, 1e-4, stream);\n    BOOST_MESSAGE(stream.str()) ;\n    BOOST_CHECK( !ok ) ;\n  }\n}\n\n\n\n// -----------------------------------------------\n\nBOOST_FIXTURE_TEST_CASE(checks_for_nan, Fixture1val)\n{\n  BOOST_MESSAGE(\"enter test; xdims=\"<<xdims<<\", valdims=\"<<valdims) ;\n\n  EigenPointType x(random_point(3242));\n  EigenDerivativesType der(EigenDerivativesType::Zero(valdims,xdims));\n\n  derivative_at(der, x);\n\n  der(0,2) = std::numeric_limits<double>::quiet_NaN();\n\n  BOOST_MESSAGE(\"Derivatives = \\n\" << der) ;\n\n  BOOST_MESSAGE(\"check that check_derivatives() complains for NaN ...\") ;\n  {\n    EigenAssertTest::setting_scope mysettingvar(true);// eigen_assert() should throw an exception.\n    std::stringstream stream;\n    auto call_test = [&]() { Tomographer::MathTools::check_derivatives(der, x, fn, valdims, 1e-6, 1e-4, stream); };\n    BOOST_CHECK_THROW(call_test(), Tomographer::Tools::EigenAssertException);\n    BOOST_MESSAGE(stream.str()) ;\n  }\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n\n", "meta": {"hexsha": "b9c14e3d41e3cd366391cd31be0db919e23cdf79", "size": 7122, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "test/test_mathtools_check_derivatives.cxx", "max_stars_repo_name": "Tomographer/tomographer", "max_stars_repo_head_hexsha": "0a64927e639454175803c1746141bd9288af8b29", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2015-09-24T02:25:11.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-13T02:26:00.000Z", "max_issues_repo_path": "test/test_mathtools_check_derivatives.cxx", "max_issues_repo_name": "Tomographer/tomographer", "max_issues_repo_head_hexsha": "0a64927e639454175803c1746141bd9288af8b29", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-10-12T15:48:55.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-21T15:14:59.000Z", "max_forks_repo_path": "test/test_mathtools_check_derivatives.cxx", "max_forks_repo_name": "Tomographer/tomographer", "max_forks_repo_head_hexsha": "0a64927e639454175803c1746141bd9288af8b29", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2015-10-12T15:32:29.000Z", "max_forks_repo_forks_event_max_datetime": "2018-05-08T11:39:49.000Z", "avg_line_length": 32.5205479452, "max_line_length": 115, "alphanum_fraction": 0.6880089862, "num_tokens": 1925, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544085240401, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.45047725534520977}}
{"text": "#include <iostream>\n#include <pcl/io/pcd_io.h>\n#include <pcl_conversions/pcl_conversions.h>\n#include \"pcl_ros/point_cloud.h\"\n#include <pcl/point_cloud.h>\n#include <pcl/point_types.h>\n#include <pcl/kdtree/kdtree_flann.h>\n#include <pcl/search/kdtree.h>\n#include <pcl/search/impl/kdtree.hpp>\n#include <ros/ros.h>\n#include <ros/console.h>\n#include <sensor_msgs/PointCloud2.h>\n#include <nav_msgs/Odometry.h>\n#include <Eigen/Eigen>\n\n#define TINYCOLORMAP_WITH_EIGEN\n\n#include \"tinycolormap.hpp\"\n\nusing namespace std;\n\n\nros::Publisher color_pc_pub;\ntypedef pcl::PointXYZRGB PointType;\npcl::PointCloud<PointType> color_pc;\nstruct ColorMapParams {\n    double max_height;\n    double min_height;\n    double range;\n    string map_type_name, frame_id;\n    bool init_map_success{false};\n    bool static_pc_mode,inverse_color{false};\n    double publish_rate;\n} cmp_;\n\nvoid PubColorCloudCallback(const ros::TimerEvent &e) {\n    if (!cmp_.init_map_success) {\n        return;\n    }\n    color_pc_pub.publish(color_pc);\n}\n\nvoid DoubleCalp(double &data_in, const double min_value, const double max_value) {\n    data_in = data_in > max_value ? max_value : data_in;\n    data_in = data_in < min_value ? min_value : data_in;\n}\n\nvoid PointCloudCallback(const sensor_msgs::PointCloud2ConstPtr &msg) {\n    if (cmp_.init_map_success) {\n        return;\n    }\n    tinycolormap::ColormapType ct;\n    if (cmp_.map_type_name == \"Parula\") {\n        ct = tinycolormap::ColormapType::Parula;\n    }\n    if (cmp_.map_type_name == \"Heat\") {\n        ct = tinycolormap::ColormapType::Heat;\n    }\n    if (cmp_.map_type_name == \"Jet\") {\n        ct = tinycolormap::ColormapType::Jet;\n    }\n    if (cmp_.map_type_name == \"Turbo\") {\n        ct = tinycolormap::ColormapType::Turbo;\n    }\n    if (cmp_.map_type_name == \"Hot\") {\n        ct = tinycolormap::ColormapType::Hot;\n    }\n    if (cmp_.map_type_name == \"Gray\") {\n        ct = tinycolormap::ColormapType::Gray;\n    }\n    if (cmp_.map_type_name == \"Magma\") {\n        ct = tinycolormap::ColormapType::Magma;\n    }\n    if (cmp_.map_type_name == \"Inferno\") {\n        ct = tinycolormap::ColormapType::Inferno;\n    }\n    if (cmp_.map_type_name == \"Plasma\") {\n        ct = tinycolormap::ColormapType::Plasma;\n    }\n    if (cmp_.map_type_name == \"Viridis\") {\n        ct = tinycolormap::ColormapType::Viridis;\n    }\n    if (cmp_.map_type_name == \"Cividis\") {\n        ct = tinycolormap::ColormapType::Cividis;\n    }\n    if (cmp_.map_type_name == \"Github\") {\n        ct = tinycolormap::ColormapType::Github;\n    }\n    pcl::PCLPointCloud2::Ptr cloud(new pcl::PCLPointCloud2);\n    pcl_conversions::toPCL(*msg, *cloud);\n    pcl::fromPCLPointCloud2( *cloud, color_pc);\n\n    for (size_t i = 0; i < color_pc.size(); i++) {\n        double color_id = color_pc.points[i].z;\n        DoubleCalp(color_id, cmp_.min_height, cmp_.max_height);\n        color_id -= cmp_.min_height;\n        color_id /= cmp_.range;\n        if(cmp_.inverse_color){\n            color_id = 1.0 - color_id;\n        }\n        Eigen::Vector3d color_mag = tinycolormap::GetColor(color_id, ct).ConvertToEigen();\n        color_pc.points[i].r = static_cast<uint8_t>((color_mag[0] * 255));\n        color_pc.points[i].g = static_cast<uint8_t>((color_mag[1] * 255));;\n        color_pc.points[i].b = static_cast<uint8_t>((color_mag[2] * 255));;\n    }\n\n    std_msgs::Header hd;\n    hd.frame_id = cmp_.frame_id;\n    pcl_conversions::toPCL(hd, color_pc.header);\n\n    cmp_.init_map_success = true;\n}\n\nint main(int argc, char **argv) {\n    ros::init(argc, argv, \"color_map_pc2\");\n    ros::NodeHandle n(\"~\");\n\n    ros::Subscriber pc_sub = n.subscribe(\"cloud\", 1, PointCloudCallback);\n\n    color_pc_pub = n.advertise<pcl::PointCloud<pcl::PointXYZRGB>>(\"color_cloud\", 1);\n    n.param(\"color/min_height\", cmp_.min_height, 0.0);\n    n.param(\"color/max_height\", cmp_.max_height, 5.0);\n    n.param(\"color/map_type_name\", cmp_.map_type_name, std::string(\"Turbo\"));\n    n.param(\"color/frame_id\", cmp_.frame_id, std::string(\"world\"));\n    n.param(\"color/publish_rate\", cmp_.publish_rate, 1.0);\n    n.param(\"color/inverse_color\", cmp_.inverse_color, false);\n    cmp_.range = cmp_.max_height - cmp_.min_height;\n    double dt = 1.0 / cmp_.publish_rate;\n    ros::Timer pub_pc_timer = n.createTimer(ros::Duration(dt), &PubColorCloudCallback);\n\n    ros::AsyncSpinner spinner(0);\n    spinner.start();\n\n    ros::waitForShutdown();\n}\n", "meta": {"hexsha": "4087afe30f05eaca86edaa9369ccda3948b8a463", "size": 4357, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "random_map_generator/Apps/color_map_for_pointcloud.cpp", "max_stars_repo_name": "RENyunfan/GCOPTER", "max_stars_repo_head_hexsha": "3b49c46b7467fd0b6b1abb2141912a1357e8da39", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "random_map_generator/Apps/color_map_for_pointcloud.cpp", "max_issues_repo_name": "RENyunfan/GCOPTER", "max_issues_repo_head_hexsha": "3b49c46b7467fd0b6b1abb2141912a1357e8da39", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "random_map_generator/Apps/color_map_for_pointcloud.cpp", "max_forks_repo_name": "RENyunfan/GCOPTER", "max_forks_repo_head_hexsha": "3b49c46b7467fd0b6b1abb2141912a1357e8da39", "max_forks_repo_licenses": ["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.0367647059, "max_line_length": 90, "alphanum_fraction": 0.6621528575, "num_tokens": 1236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.4504772538676434}}
{"text": "/*********************************************************************\n * Software License Agreement (BSD License)\n *\n *  Copyright (c) 2019, University of Stuttgart\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions\n *  are met:\n *\n *   * Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *   * Redistributions in binary form must reproduce the above\n *     copyright notice, this list of conditions and the following\n *     disclaimer in the documentation and/or other materials provided\n *     with the distribution.\n *   * Neither the name of the University of Stuttgart nor the names\n *     of its contributors may be used to endorse or promote products\n *     derived from this software without specific prior written\n *     permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n *  \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n *  POSSIBILITY OF SUCH DAMAGE.\n *********************************************************************/\n\n/* Author: Andreas Orthey */\n\n#include \"MultiLevelPlanningCommon.h\"\n#include \"MultiLevelPlanningHyperCubeCommon.h\"\n#include <ompl/base/spaces/RealVectorStateSpace.h>\n\n#include <ompl/multilevel/planners/qrrt/QRRT.h>\n\n#include <ompl/tools/benchmark/Benchmark.h>\n#include <ompl/util/String.h>\n\n#include <boost/math/constants/constants.hpp>\n#include <boost/format.hpp>\n#include <fstream>\n\nconst unsigned int ndim = 100;\n\nint main()\n{\n    auto space(std::make_shared<ompl::base::RealVectorStateSpace>(ndim));\n    ompl::base::RealVectorBounds bounds(ndim);\n    ompl::geometric::SimpleSetup ss(space);\n    ompl::base::ScopedState<> start(space), goal(space);\n\n    ob::SpaceInformationPtr si = ss.getSpaceInformation();\n\n    bounds.setLow(0.);\n    bounds.setHigh(1.);\n    space->setBounds(bounds);\n    ss.setStateValidityChecker(std::make_shared<HyperCubeValidityChecker>(si, ndim));\n    si->setStateValidityCheckingResolution(0.001);\n    for (unsigned int i = 0; i < ndim; ++i)\n    {\n        start[i] = 0.;\n        goal[i] = 1.;\n    }\n    ss.setStartAndGoalStates(start, goal);\n\n    std::vector<int> admissibleProjection = getHypercubeAdmissibleProjection(ndim);\n    ob::PlannerPtr planner = \n      GetMultiLevelPlanner<ompl::multilevel::QRRT>(admissibleProjection, si, \"QRRT\");\n    ss.setPlanner(planner);\n\n    bool solved = ss.solve(1.0);\n\n    double timeToCompute = ss.getLastPlanComputationTime();\n\n    if (solved)\n    {\n        const ob::ProblemDefinitionPtr pdef = planner->getProblemDefinition();\n        std::cout << std::string(80, '-') << std::endl;\n        pdef->getSolutionPath()->print(std::cout);\n        std::cout << std::string(80, '-') << std::endl;\n        OMPL_INFORM(\"Solved hypercube with %d dimensions after %f seconds.\", ndim, timeToCompute);\n    }else\n    {\n      OMPL_ERROR(\"Failed finding solution after %f seconds.\", timeToCompute);\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "99218fddbbfed5670e15489cb23542834188ef85", "size": 3700, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "demos/multilevel/MultiLevelPlanningHyperCube.cpp", "max_stars_repo_name": "orthez/ompl", "max_stars_repo_head_hexsha": "f8aa02485d27e30b4ecfb364ef3178356d42d94a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-28T07:59:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-28T07:59:11.000Z", "max_issues_repo_path": "demos/multilevel/MultiLevelPlanningHyperCube.cpp", "max_issues_repo_name": "orthez/ompl", "max_issues_repo_head_hexsha": "f8aa02485d27e30b4ecfb364ef3178356d42d94a", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/multilevel/MultiLevelPlanningHyperCube.cpp", "max_forks_repo_name": "orthez/ompl", "max_forks_repo_head_hexsha": "f8aa02485d27e30b4ecfb364ef3178356d42d94a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-08-13T12:41:36.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-25T22:57:38.000Z", "avg_line_length": 38.1443298969, "max_line_length": 98, "alphanum_fraction": 0.6854054054, "num_tokens": 854, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.4504772538676434}}
{"text": "\n#include <boost/numeric/conversion/cast.hpp>\n\n#include <iostream>\n#include <climits>\n#include <cfloat>   // for DBL_MAX (Peter Schmid)\n\n#include \"../third-party/catch.h\"\n#include \"../third-party/half.hpp\"\n\n\nTEST_CASE(\"boost numeric_cast\", \"[boost::numeric_cast]\")\n{\n\n    using namespace std;\n    SECTION(\"Test user-defined type, half_float::half\")\n    {\n        std::cout << \"=========\" << \"half float\" << \"==============\\n\";\n        using namespace half_float;\n\n        int8_t v1 = boost::numeric_cast<int8_t>(half{1});\n        half h1 = boost::numeric_cast<half>(100);\n        std::cout << \"boost::numeric_cast<half>(100) = \" << h1 << std::endl;\n\n        REQUIRE_THROWS_AS( boost::numeric_cast<int8_t>(half{1000}), boost::numeric::bad_numeric_cast);\n        // equal expression \n        try{\n            int8_t v1 = boost::numeric_cast<int8_t>(half{1000});\n            std::cout << \"boost::numeric_cast<int8_t>(half{1000}) = \" << v1 << std::endl;\n        }\n        catch(boost::numeric::bad_numeric_cast& e)\n        {\n            std::cout << \"`boost::numeric_cast<int8_t>(half{1000})` error : \" << e.what() << '\\n'; \n        }\n\n    }\n\n\n    SECTION(\"boost::numeric_cast for builtin types\")\n    {\n\n        REQUIRE_THROWS_AS( boost::numeric_cast<int>( DBL_MAX ) == 0, boost::numeric::bad_numeric_cast);\n\n    }\n\n} \n\n", "meta": {"hexsha": "766961741e6ae0e7decdaa439adf078f6b656efb", "size": 1316, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_boost_numeric_cast.cpp", "max_stars_repo_name": "qingfengxia/cpp_numeric_cast", "max_stars_repo_head_hexsha": "1e7207e43c2ba9228e94e9f7b40bb0ccde88f28a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-04-28T13:49:09.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-28T13:49:09.000Z", "max_issues_repo_path": "tests/test_boost_numeric_cast.cpp", "max_issues_repo_name": "qingfengxia/cpp_to_integer", "max_issues_repo_head_hexsha": "1e7207e43c2ba9228e94e9f7b40bb0ccde88f28a", "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": "tests/test_boost_numeric_cast.cpp", "max_forks_repo_name": "qingfengxia/cpp_to_integer", "max_forks_repo_head_hexsha": "1e7207e43c2ba9228e94e9f7b40bb0ccde88f28a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4166666667, "max_line_length": 103, "alphanum_fraction": 0.5835866261, "num_tokens": 351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.6992544085240401, "lm_q1q2_score": 0.4504772457924632}}
{"text": "//=======================================================================\n// Copyright (c) 2013 Robert Rosolek\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 demand_query_example.cpp\n * @brief\n * @author Robert Rosolek\n * @version 1.0\n * @date 2014-6-9\n */\n\n#include \"paal/auctions/auction_components.hpp\"\n\n#include <boost/optional/optional.hpp>\n#include <boost/range/algorithm/copy.hpp>\n\n#include <algorithm>\n#include <cassert>\n#include <vector>\n\n//! [Demand Query Auction Components Example]\n\nnamespace pa = paal::auctions;\nnamespace pds = paal::data_structures;\n\nusing Bidder = std::string;\nusing Item = std::string;\nusing Items = std::vector<Item>;\nusing Value = int;\n\nconst std::vector<Bidder> bidders {\"Pooh Bear\", \"Rabbit\"};\n\nconst Items items {\"honey\", \"baby carrot\", \"carrot\", \"jam\"};\n\nstruct demand_query_func {\n   template <class GetPrice>\n   std::pair<Items, Value>\n   operator()(Bidder bidder, GetPrice get_price) const\n   {\n      if (bidder == \"Pooh Bear\") {\n         const Value util = 10 - get_price(\"honey\");\n         if (util <= 0) return std::make_pair(Items{}, 0);\n         return std::make_pair(Items{\"honey\"}, util);\n      }\n\n      assert(bidder == \"Rabbit\");\n\n      const Value baby_val = 2, val = 3;\n      auto const baby_price = get_price(\"baby carrot\"), price = get_price(\"carrot\");\n\n      const Value baby_util = baby_val - baby_price,\n         util = val - price, both_util = baby_val + val - baby_price - price;\n\n      if (baby_util <= 0 && util <= 0 && both_util <= 0) return std::make_pair(Items{}, 0);\n\n      if (baby_util >= util && baby_util >= both_util)\n         return std::make_pair(Items{\"baby carrot\"}, baby_util);\n\n      if (util >= both_util)\n         return std::make_pair(Items{\"carrot\"}, util);\n\n      return std::make_pair(Items{\"baby carrot\", \"carrot\"}, both_util);\n   }\n};\n//! [Demand Query Auction Components Example]\n\nint main() {\n   //! [Demand Query Auction Create Example]\n   auto const auction = pa::make_demand_query_auction_components(\n      bidders, items, demand_query_func()\n   );\n   //! [Demand Query Auction Create Example]\n\n   //! [Demand Query Auction Use Example]\n   auto get_price = [](Item item) { return item == \"honey\" ? 5 : 2; };\n\n   std::cout << \"pooh bear buys: \";\n   auto got_pooh_bear = auction.call<pa::demand_query>(\"Pooh Bear\", get_price);\n   boost::copy(got_pooh_bear.first, std::ostream_iterator<Item>(std::cout, \", \"));\n   std::cout << std::endl;\n\n   std::cout << \"rabbit oracle buys: \";\n   auto got_rabbit = auction.call<pa::demand_query>(\"Rabbit\", get_price);\n   boost::copy(got_rabbit.first, std::ostream_iterator<Item>(std::cout, \", \"));\n   std::cout << std::endl;\n   //! [Demand Query Auction Use Example]\n   return 0;\n}\n", "meta": {"hexsha": "bbe7f33100e6603da6ac11e6e296798f8a4f4cd5", "size": 2904, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/auctions/demand_query_example.cpp", "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": "examples/auctions/demand_query_example.cpp", "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": "examples/auctions/demand_query_example.cpp", "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": 31.2258064516, "max_line_length": 91, "alphanum_fraction": 0.6212121212, "num_tokens": 751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544085240401, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.4504772362397164}}
{"text": "#include <app/duplicate_instance_renderer.h>\n#include <glb/camera.h>\n#include <glb/framebuffer.h>\n#include <glb/shader_program_builder.h>\n#include <glb/opengl.h>\n#include <tess/tessellator.h>\n#include <Eigen/Eigenvalues>\n#include <rvm/MaterialTable.h>\n\nnamespace app\n{\n\t// ---------------------------------------------------------------------------------------------------------------------------------------------------------\n\t// global definitions\n\t// ---------------------------------------------------------------------------------------------------------------------------------------------------------\n\n\tstruct EigenOBB\n\t{\n\t\tEigenVec3 center;\n\t\tEigenVec3 half_extents;\n\t\tEigenMat3 basis;\n\t};\n\n\tstruct bbox\n\t{\n\t\tvec3 min = vec3(math::limit_posf());\n\t\tfloat pad0 = 1.0f;\n\t\tvec3 max = vec3(math::limit_negf());\n\t\tfloat pad1 = 1.0f;\n\n\t\tvoid expand(const vec3& v)\n\t\t{\n\t\t\tmin.x = math::min(min.x, v.x);\n\t\t\tmin.y = math::min(min.y, v.y);\n\t\t\tmin.z = math::min(min.z, v.z);\n\t\t\tmax.x = math::max(max.x, v.x);\n\t\t\tmax.y = math::max(max.y, v.y);\n\t\t\tmax.z = math::max(max.z, v.z);\n\t\t}\n\t};\n\n\t// ---------------------------------------------------------------------------------------------------------------------------------------------------------\n\t// global constants\n\t// ---------------------------------------------------------------------------------------------------------------------------------------------------------\n\n\tstatic const unsigned int MAX_BUFFER_SIZE_BYTES = 5 * 1024 * 1024;\n\tstatic const double EPSILON = 1e-3;\n\tstatic const int TRANSFORM_TEX_UNIT = 0;\n\tstatic const int TEX_OFFSET_ATTRIB = 5;\n\tstatic const int COLOR_IDS_TEX_UNIT = 1;\n\tstatic const int COLORS_TEX_UNIT = 2;\n\n\t// ---------------------------------------------------------------------------------------------------------------------------------------------------------\n\t// helper functions\n\t// ---------------------------------------------------------------------------------------------------------------------------------------------------------\n\n\tstatic bool vec3_equal(const vec3& a, const vec3& b)\n\t{\n\t\tconst auto err_x = math::abs(a.x - b.x);\n\t\tconst auto err_y = math::abs(a.y - b.y);\n\t\tconst auto err_z = math::abs(a.z - b.z);\n\t\treturn err_x <= EPSILON && err_y <= EPSILON && err_z <= EPSILON;\n\t}\n\n\tstatic bool eigen3_equal(const EigenVec3& a, const EigenVec3& b)\n\t{\n\t\tconst auto diff = (a-b).cwiseAbs();\n\t\treturn diff.coeff(0) <= EPSILON && diff.coeff(1) <= EPSILON && diff.coeff(2) <= EPSILON;\n\t}\n\n\tstatic bool eigen3_dist_equal(const EigenVec3& a, const EigenVec3& b)\n\t{\n\t\treturn (a-b).norm() <= EPSILON;\n\t}\n\n\tstatic bool eigen4_equal(const EigenVec4& a, const EigenVec4& b)\n\t{\n\t\tconst auto diff = (a-b).cwiseAbs();\n\t\treturn diff.coeff(0) <= EPSILON && diff.coeff(1) <= EPSILON && diff.coeff(2) <= EPSILON && a.coeff(3) == 1.0 && b.coeff(3) == 1.0;\n\t}\n\n\tstatic EigenVec3Array to_eigen(const vector<vec3>& input)\n\t{\n\t\tEigenVec3Array output(3, input.size());\n\n\t\tfor(unsigned int i = 0; i < input.size(); ++i)\n\t\t{\n\t\t\toutput.col(i) = EigenVec3(input[i].x, input[i].y, input[i].z);\n\t\t}\n\n\t\treturn output;\n\t}\n\n\tstatic vector<vec3> to_bl(const EigenVec3Array& input)\n\t{\n\t\tvector<vec3> output(input.cols());\n\n\t\tfor(unsigned int i = 0; i < input.cols(); ++i)\n\t\t{\n\t\t\toutput[i] = vec3(input.col(i).coeff(0), input.col(i).coeff(1), input.col(i).coeff(2));\n\t\t}\n\n\t\treturn output;\n\t}\n\n\tstatic vec3 vec3_to_bl(const EigenVec3& input)\n\t{\n\t\treturn vec3(input.coeff(0), input.coeff(1), input.coeff(2));\n\t}\n\n\tstatic mat4 mat3_to_bl(const EigenMat3& input)\n\t{\n\t\treturn mat4(input.coeff(0,0), input.coeff(0,1), input.coeff(0,2), 0.0f,\n\t\t\t\t\tinput.coeff(1,0), input.coeff(1,1), input.coeff(1,2), 0.0f,\n\t\t\t\t\tinput.coeff(2,0), input.coeff(2,1), input.coeff(2,2), 0.0f,\n\t\t\t\t\t0.0f, 0.0f, 0.0f, 1.0f);\n\t}\n\n\tstatic mat4 mat4_to_bl(const EigenMat4& input)\n\t{\n\t\treturn mat4(input.coeff(0,0), input.coeff(0,1), input.coeff(0,2), input.coeff(0,3),\n\t\t\t\t\tinput.coeff(1,0), input.coeff(1,1), input.coeff(1,2), input.coeff(1,3),\n\t\t\t\t\tinput.coeff(2,0), input.coeff(2,1), input.coeff(2,2), input.coeff(2,3),\n\t\t\t\t\tinput.coeff(3,0), input.coeff(3,1), input.coeff(3,2), input.coeff(3,3));\n\t}\n\n\tstatic EigenMat4 to_mat4(const EigenMat3& input)\n\t{\n\t\tEigenMat4 m;\n\t\tm <<\tinput.coeff(0,0), input.coeff(0,1), input.coeff(0,2), 0.0f,\n\t\t\t\tinput.coeff(1,0), input.coeff(1,1), input.coeff(1,2), 0.0f,\n\t\t\t\tinput.coeff(2,0), input.coeff(2,1), input.coeff(2,2), 0.0f,\n\t\t\t\t0.0f, 0.0f, 0.0f, 1.0f;\n\t\treturn m;\n\t}\n\n\tstatic bool is_identity(const mat4& i)\n\t{\n\t\tstatic const float EPS = 1e-6f;\n\t\treturn  abs(i.at(0,0) - 1.0) <= EPS && abs(i.at(0,1) - 0.0) <= EPS && abs(i.at(0,2) - 0.0) <= EPS && abs(i.at(0,3) - 0.0) <= EPS &&\n\t\t\t\tabs(i.at(1,0) - 0.0) <= EPS && abs(i.at(1,1) - 1.0) <= EPS && abs(i.at(1,2) - 0.0) <= EPS && abs(i.at(1,3) - 0.0) <= EPS &&\n\t\t\t\tabs(i.at(2,0) - 0.0) <= EPS && abs(i.at(2,1) - 0.0) <= EPS && abs(i.at(2,2) - 1.0) <= EPS && abs(i.at(2,3) - 0.0) <= EPS &&\n\t\t\t\tabs(i.at(3,0) - 0.0) <= EPS && abs(i.at(3,1) - 0.0) <= EPS && abs(i.at(3,2) - 0.0) <= EPS && abs(i.at(3,3) - 1.0) <= EPS;\n\t}\n\n\tstatic bool is_identity(const EigenMat3& i)\n\t{\n\t\tstatic const float EPS = 1e-12;\n\t\treturn  abs(i.coeff(0,0) - 1.0) <= EPS && abs(i.coeff(0,1) - 0.0) <= EPS && abs(i.coeff(0,2) - 0.0) <= EPS &&\n\t\t\t\tabs(i.coeff(1,0) - 0.0) <= EPS && abs(i.coeff(1,1) - 1.0) <= EPS && abs(i.coeff(1,2) - 0.0) <= EPS &&\n\t\t\t\tabs(i.coeff(2,0) - 0.0) <= EPS && abs(i.coeff(2,1) - 0.0) <= EPS && abs(i.coeff(2,2) - 1.0) <= EPS;\n\t}\n\n\tstatic bool is_identity(const EigenMat4& i)\n\t{\n\t\tstatic const float EPS = 1e-12;\n\t\treturn  abs(i.coeff(0,0) - 1.0) <= EPS && abs(i.coeff(0,1) - 0.0) <= EPS && abs(i.coeff(0,2) - 0.0) <= EPS && abs(i.coeff(0,3) - 0.0) <= EPS &&\n\t\t\t\tabs(i.coeff(1,0) - 0.0) <= EPS && abs(i.coeff(1,1) - 1.0) <= EPS && abs(i.coeff(1,2) - 0.0) <= EPS && abs(i.coeff(1,3) - 0.0) <= EPS &&\n\t\t\t\tabs(i.coeff(2,0) - 0.0) <= EPS && abs(i.coeff(2,1) - 0.0) <= EPS && abs(i.coeff(2,2) - 1.0) <= EPS && abs(i.coeff(2,3) - 0.0) <= EPS &&\n\t\t\t\tabs(i.coeff(3,0) - 0.0) <= EPS && abs(i.coeff(3,1) - 0.0) <= EPS && abs(i.coeff(3,2) - 0.0) <= EPS && abs(i.coeff(3,3) - 1.0) <= EPS;\n\t}\n\n\tstatic EigenOBB compute_obb(const EigenVec3Array& src)\n\t{\n\t\tEigenOBB obb;\n\n\t\t// 1. compute geometric center\n\t\tEigenVec3 mean = src.rowwise().mean();\n\n\t\t// 2. use PCA to find orthonormal basis centered in average\n\t\tEigenVec3Array centered = src.colwise() - mean;\n\t\tEigenMat3 covariance_matrix = centered * centered.transpose();\n\n\t\tEigen::SelfAdjointEigenSolver<EigenMat3> eig(covariance_matrix);\n\t\tobb.basis = eig.eigenvectors().rightCols(3);\n\n\t\t// 3. describe src points in local basis: subtract by center and project onto basis vectors\n\t\tEigenVec3Array local_src = obb.basis * centered;\n\n\t\t// 4. find minimum and maximum coordinates in local basis\n\t\tEigenVec3 local_min = local_src.rowwise().minCoeff();\n\t\tEigenVec3 local_max = local_src.rowwise().maxCoeff();\n\n\t\t// 5. compute oriented box center\n\t\tEigenVec3 local_center = (local_min + local_max) * 0.5f;\n\t\tobb.center = mean + obb.basis * local_center;\n\n\t\t// 6. compute oriented box half-extents (aka half-scale along each local axis)\n\t\tobb.half_extents = (local_max - local_min) * 0.5f;\n\n\t\treturn obb;\n\t}\n\n\tstatic mat4 estimate_transform_similarity(const vector<vec3>& src_points, const vector<vec3>& dst_points)\n\t{\n\t\treturn mat4_to_bl(Eigen::umeyama(to_eigen(src_points), to_eigen(dst_points), true));\n\t}\n\n\tstatic mat4 estimate_transform_3x3(const EigenVec3Array& src,\n\t\t\t\t\t\t\t\t\t   const EigenVec3& src_mean, const EigenVec3Array& src_local, const EigenMat3& Aqq,\n\t\t\t\t\t\t\t\t\t   const EigenVec3Array& dst,\n\t\t\t\t\t\t\t\t\t   const EigenVec3& dst_mean, const EigenVec3Array& dst_local,\n\t\t\t\t\t\t\t\t\t   double& error)\n\t{\n\t\tEigenMat3 Apq = dst_local * src_local.transpose();\n\n\t\tEigenMat3 A = Apq * Aqq;\n\t\tEigenMat4 A4 = to_mat4(A);\n\n\t\tEigenMat4 M = Eigen::Affine3d(Eigen::Translation3d(dst_mean)).matrix() * A4 * Eigen::Affine3d(Eigen::Translation3d(-src_mean)).matrix();\n\n\t\terror = 0.0;\n\t\tfor(unsigned int i = 0; i < src.cols(); ++i)\n\t\t{\n\t\t\tEigenVec3 s3 = src.col(i);\n\t\t\tEigenVec4 s4(s3.coeff(0), s3.coeff(1), s3.coeff(2), 1.0);\n\t\t\tEigenVec4 ts = M * s4;\n\t\t\tEigenVec3 s(ts.coeff(0), ts.coeff(1), ts.coeff(2));\n\t\t\tEigenVec3 d = dst.col(i);\n\t\t\terror += (d - s).squaredNorm();\n\t\t}\n\n\t\treturn mat4_to_bl(M);\n\t}\n\n\tstatic mat4 estimate_transform_4x4(const vector<vec3>& src_pts, const vector<vec3>& dst_pts, double& error)\n\t{\n\t\tEigenVec3Array src = to_eigen(src_pts);\n\t\tEigenVec3Array dst = to_eigen(dst_pts);\n\n\t\tEigenVec3 src_mean = src.rowwise().mean();\n\t\tEigenVec3Array src_local = src.colwise() - src_mean;\n\n\t\tEigenVec3 dst_mean = dst.rowwise().mean();\n\t\tEigenVec3Array dst_local = dst.colwise() - dst_mean;\n\n\t\tEigenVec4Array src_local4(4, src_local.cols());\n\t\tsrc_local4.row(0) = src_local.row(0);\n\t\tsrc_local4.row(1) = src_local.row(1);\n\t\tsrc_local4.row(2) = src_local.row(2);\n\t\tsrc_local4.row(3).setConstant(1.0);\n\n\t\tEigenVec4Array dst_local4(4, dst_local.cols());\n\t\tdst_local4.row(0) = dst_local.row(0);\n\t\tdst_local4.row(1) = dst_local.row(1);\n\t\tdst_local4.row(2) = dst_local.row(2);\n\t\tdst_local4.row(3).setConstant(1.0);\n\n\t\tEigenMat4 Apq = dst_local4 * src_local4.transpose();\n\t\tEigenMat4 Aqq = (src_local4 * src_local4.transpose()).inverse();\n\n\t\tEigenMat4 A = Apq * Aqq;\n\n\t\tEigenMat4 M = Eigen::Affine3d(Eigen::Translation3d(dst_mean)).matrix() * A * Eigen::Affine3d(Eigen::Translation3d(-src_mean)).matrix();\n\n\t\terror = 0.0;\n\t\tfor(unsigned int i = 0; i < src.cols(); ++i)\n\t\t{\n\t\t\tEigenVec3 s3 = src.col(i);\n\t\t\tEigenVec4 s4(s3.coeff(0), s3.coeff(1), s3.coeff(2), 1.0);\n\t\t\tEigenVec4 ts = M * s4;\n\t\t\tEigenVec3 s(ts.coeff(0), ts.coeff(1), ts.coeff(2));\n\t\t\tEigenVec3 d = dst.col(i);\n\t\t\terror += (d - s).squaredNorm();\n\t\t}\n\n\t\treturn mat4_to_bl(M);\n\t}\n\n\t// ---------------------------------------------------------------------------------------------------------------------------------------------------------\n\t// public\n\t// ---------------------------------------------------------------------------------------------------------------------------------------------------------\n\n\tvoid duplicate_instance_renderer::set_current_color(unsigned char color_id)\n\t{\n\t\t_current_color_id = color_id;\n\t}\n\n\tvoid duplicate_instance_renderer::add_box(const box& b, const mat4& transform)\n\t{\n\t\t_add_mesh(tess::tessellate_box(b.extents), transform);\n\t}\n\n\tvoid duplicate_instance_renderer::add_circular_torus(const circular_torus& c, const mat4& transform)\n\t{\n\t\t_add_mesh(tess::tessellate_circular_torus(c.in_radius, c.out_radius, c.sweep_angle), transform);\n\t}\n\n\tvoid duplicate_instance_renderer::add_cone(const cone& c, const mat4& transform)\n\t{\n\t\t_add_mesh(tess::tessellate_cone(c.top_radius, c.bottom_radius, c.height), transform);\n\t}\n\n\tvoid duplicate_instance_renderer::add_cone_offset(const cone_offset& c, const mat4& transform)\n\t{\n\t\t_add_mesh(tess::tessellate_cone_offset(c.top_radius, c.bottom_radius, c.height, c.offset), transform);\n\t}\n\n\tvoid duplicate_instance_renderer::add_cylinder(const cylinder& c, const mat4& transform)\n\t{\n\t\t_add_mesh(tess::tessellate_cylinder(c.radius, c.height), transform);\n\t}\n\n\tvoid duplicate_instance_renderer::add_cylinder_offset(const cylinder_offset& c, const mat4& transform)\n\t{\n\t\t_add_mesh(tess::tessellate_cylinder_offset(c.radius, c.height, c.offset), transform);\n\t}\n\n\tvoid duplicate_instance_renderer::add_cylinder_slope(const cylinder_slope& c, const mat4& transform)\n\t{\n\t\t_add_mesh(tess::tessellate_cylinder_slope(c.radius, c.height, c.top_slope_angles, c.bottom_slope_angles), transform);\n\t}\n\n\tvoid duplicate_instance_renderer::add_dish(const dish& d, const mat4& transform)\n\t{\n\t\t_add_mesh(tess::tessellate_dish(d.radius, d.height), transform);\n\t}\n\n\tvoid duplicate_instance_renderer::add_mesh(const tess::triangle_mesh& m, const mat4& transform)\n\t{\n\t\t_add_mesh(m, transform, true);\n\t}\n\n\tvoid duplicate_instance_renderer::add_pyramid(const pyramid& p, const mat4& transform)\n\t{\n\t\t_add_mesh(tess::tessellate_pyramid(p.top_extents, p.bottom_extents, p.height, p.offset), transform);\n\t}\n\n\tvoid duplicate_instance_renderer::add_rectangular_torus(const rectangular_torus& rt, const mat4& transform)\n\t{\n\t\t_add_mesh(tess::tessellate_rectangular_torus(rt.in_radius, rt.out_radius, rt.in_height, rt.sweep_angle), transform);\n\t}\n\n\tvoid duplicate_instance_renderer::add_sphere(const sphere& s, const mat4& transform)\n\t{\n\t\t_add_mesh(tess::tessellate_sphere(s.radius), transform);\n\t}\n\n\tvoid duplicate_instance_renderer::end_upload()\n\t{\n//\t\tauto aspect = 1.0f;\n//\t\tauto fovy = math::to_radians(60.0f);\n//\t\tauto yscale = 1.0f / math::tan(fovy*0.5f);\n//\t\tauto xscale = yscale / aspect;\n//\t\tauto znear = 2.0f;\n//\t\tauto zfar = 1000.0f;\n\n//\t\tauto t0 = mat4::translation({0,0,-1});\n//\t\tauto t1 = mat4::translation({5,0,0});\n//\t\tauto glp = mat4::perspective(fovy, aspect, znear, zfar);\n////\t\tglp.at(3,2) = 1.0f;\n\n//\t\tauto dxp = mat4(xscale,   0.0f,                      0.0f,  0.0f,\n//\t\t\t\t\t\t  0.0f, yscale,                      0.0f,  0.0f,\n//\t\t\t\t\t\t  0.0f,   0.0f,         zfar/(znear-zfar), -1.0f,\n//\t\t\t\t\t\t  0.0f,   0.0f, (znear*zfar)/(znear-zfar),  0.0f);\n\n//\t\tadd_box({{1,1,1}}, glp.mul(t0));\n//\t\tadd_pyramid({{1,1}, {2,2}, {0,0}, 1}, t1);\n\n\n\n\n\t\tconst auto unique_mesh_count = _unique_meshes.size();\n\t\t_instance_sets.reserve(unique_mesh_count);\n\n\t\tglb::vertex_specification spec;\n\t\tspec.setup_vertex_buffer(glb::usage_static_draw, _total_vbo_size_bytes);\n\t\tspec.setup_element_buffer(glb::usage_static_draw, _total_ebo_size_bytes);\n\t\tspec.add_vertex_attrib({3, glb::type_float, false, sizeof(tess::vertex), 0});\n\t\tspec.add_vertex_attrib({3, glb::type_float, false, sizeof(tess::vertex), sizeof(vec3)});\n\n\t\tif(!_vao_builder.initialize(spec, glb::mode_triangles, glb::type_uint))\n\t\t{\n\t\t\treturn;\n\t\t}\n\n\t\t_vao_builder.begin();\n\n\t\t_transform_buffer.create(glb::target_texture_buffer, glb::usage_static_draw, _total_geometries * sizeof(mat34));\n\t\t_transform_texture.create(TRANSFORM_TEX_UNIT, glb::target_texture_buffer);\n\t\t_transform_texture.set_data_source(glb::internal_format_rgba32f, _transform_buffer);\n\n\t\t_color_id_buffer.create(glb::target_texture_buffer, glb::usage_static_draw, _total_geometries * sizeof(unsigned char));\n\t\t_color_ids_texture.create(COLOR_IDS_TEX_UNIT, glb::target_texture_buffer);\n\t\t_color_ids_texture.set_data_source(glb::internal_format_r8ui, _color_id_buffer);\n\n//\t\tmap<int, int> histogram;\n//\t\tvector<int> instance_count;\n\n\t\tauto rc = make_random(0.2f, 0.7f);\n\n//#define WRITE(c) {decltype(c) x = c; file.write((char*)&x, sizeof(x));}\n\n//\t\tstd::ofstream file(\"caos.xfm\", std::ios::out | std::ios::binary);\n\n//\t\tWRITE(_unique_meshes.size());\n//\t\tfile.flush();\n\n\t\tfor(auto& itr : _unique_meshes)\n\t\t{\n\t\t\tauto& ps = itr.second;\n\n//\t\t\tstd::vector<mat34> xfms;\n\n//\t\t\tfor(const auto& t : ps.transforms)\n//\t\t\t{\n//\t\t\t\tbbox b;\n//\t\t\t\tfor(const auto& v : ps.mesh.vertices)\n//\t\t\t\t{\n//\t\t\t\t\tb.expand(t.as_mat4().mul(v.position));\n//\t\t\t\t}\n//\t\t\t\tmat4 m = mat4::translation((b.min+b.max)*0.5f).mul(mat4::scale(b.max-b.min));\n//\t\t\t\txfms.push_back(mat34(m));\n//\t\t\t}\n\n//\t\t\tWRITE(xfms.size());\n//\t\t\tfile.flush();\n//\t\t\tfile.write((char*)xfms.data(), sizeof(mat34)*xfms.size());\n//\t\t\tfile.flush();\n\n\t\t\tinstance_set instances;\n\t\t\tinstances.element_count = ps.mesh.elements.size();\n\t\t\tinstances.element_byte_offset = _vao_builder._spec.get_element_buffer().get_size_bytes();\n\t\t\tinstances.tex_offset = _transform_buffer.get_count();\n\t\t\tinstances.count = ps.transforms.size();\n\t\t\tinstances.color = vec3(rc(), rc(), rc());\n\t\t\t_instance_sets.push_back(instances);\n\n\t\t\t_vao_builder.add_mesh(ps.mesh.vertices.data(), ps.mesh.vertices.size(), ps.mesh.elements.data(), ps.mesh.elements.size());\n\n\t\t\t_transform_buffer.add(ps.transforms.data(), ps.transforms.size());\n\t\t\t_color_id_buffer.add(ps.color_ids.data(), ps.color_ids.size());\n\n\t\t\t_cpu_transform_buffer.insert(_cpu_transform_buffer.end(), ps.transforms.begin(), ps.transforms.end());\n\t\t\t_cpu_color_id_buffer.insert(_cpu_color_id_buffer.end(), ps.color_ids.begin(), ps.color_ids.end());\n\n\t\t\t_total_memory += ps.transforms.size() * sizeof(mat34) + ps.color_ids.size() * sizeof(unsigned char);\n\n//\t\t\thistogram[ps.transforms.size()]++;\n//\t\t\tinstance_count.push_back(ps.transforms.size());\n\t\t}\n\n//\t\tfile.close();\n\n//\t\t_cpu_transform_buffer2.resize(_cpu_transform_buffer.size());\n\n\t\t_vao_builder.end();\n\n\t\t_main_vao = _vao_builder.get_vertex_arrays()[0];\n\n//\t\tint max_count = 0;\n//\t\tfor(auto c : instance_count)\n//\t\t{\n//\t\t\tio::print(c);\n//\t\t\tmax_count = math::max(max_count, c);\n//\t\t}\n//\t\tio::print(\"max:\", max_count);\n\n//\t\tfor(auto c : histogram)\n//\t\t{\n//\t\t\tio::print(\"[#instances,#ocurrences]:\", c.first, c.second);\n//\t\t}\n\n\t\t// free memory\n\t\t_unique_meshes = decltype(_unique_meshes)();\n\n\t\t// CAD color table\n\t\trvm::MaterialTable color_table;\n\n\t\tglb::buffer colors_buffer;\n\t\tcolors_buffer.create(glb::target_texture_buffer, glb::usage_static_draw, color_table.getNumberMaterials() * sizeof(color));\n\n\t\tfor(int i = 0; i < color_table.getNumberMaterials(); ++i)\n\t\t{\n\t\t\tauto diffuse = vec3(color_table.getMaterial(i).diffuseColor);\n\t\t\tcolor c;\n\t\t\tc.rgba[0] = 255 * diffuse.x;\n\t\t\tc.rgba[1] = 255 * diffuse.y;\n\t\t\tc.rgba[2] = 255 * diffuse.z;\n\t\t\tif(c.rgba[0] == 0 && c.rgba[1] == 0 && c.rgba[2] == 0)\n\t\t\t{\n\t\t\t\tc.rgba[0] = 64;\n\t\t\t\tc.rgba[1] = 64;\n\t\t\t\tc.rgba[2] = 64;\n\t\t\t}\n\t\t\tcolors_buffer.add(c);\n\t\t}\n\t\t_colors_texture.create(COLORS_TEX_UNIT, glb::target_texture_buffer);\n\t\t_colors_texture.set_data_source(glb::internal_format_rgba8ui, colors_buffer);\n\n\t\tio::print(\"unique meshes:\", unique_mesh_count);\n\t\tio::print(\"geometries:\", _total_geometries);\n\t\tio::print(\"triangles:\", _total_triangles);\n\t\tio::print(\"-- memory matching:\", _total_memory / 1024.0f / 1024.0f, \"MB\");\n\t}\n\n\tbool duplicate_instance_renderer::initialize(glb::framebuffer& fbuffer, glb::camera& cam)\n\t{\n\t\tfbuffer.set_clear_color(0, 1.0f, 1.0f, 1.0f);\n\n\t\tglb::shader_program_builder shader_builder;\n\t\tshader_builder.begin();\n\t\tif(!shader_builder.add_file(glb::shader_vertex, \"../shaders/duplicate_instance.vert\"))\n\t\t{\n\t\t\treturn false;\n\t\t}\n//\t\tif(!shader_builder.add_file(glb::shader_vertex, \"../shaders/pass_through.vert\"))\n//\t\t{\n//\t\t\treturn false;\n//\t\t}\n//\t\tif(!shader_builder.add_file(glb::shader_geometry, \"../shaders/duplicate_instance.geom\"))\n//\t\t{\n//\t\t\treturn false;\n//\t\t}\n\t\tif(!shader_builder.add_file(glb::shader_fragment, \"../shaders/per_pixel_lighting_color.frag\"))\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t\tshader_builder.bind_vertex_attrib(\"in_position\", 0);\n\t\tshader_builder.bind_vertex_attrib(\"in_normal\", 1);\n\t\tshader_builder.bind_vertex_attrib(\"in_tex_offset\", TEX_OFFSET_ATTRIB);\n\t\tshader_builder.bind_vertex_attrib(\"in_color\", 7);\n\t\tshader_builder.bind_draw_buffer(\"out_color\", fbuffer.get_color_buffer_to_display());\n\t\tif(!shader_builder.end())\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t\t_shader = shader_builder.get_shader_program();\n\t\t_shader.bind_uniform_buffer(\"camera_uniform_block\", cam.get_uniform_buffer());\n\t\t_shader.set_uniform(\"tex_transforms\", TRANSFORM_TEX_UNIT);\n\t\t_shader.set_uniform(\"tex_colorIDs\", COLOR_IDS_TEX_UNIT);\n\t\t_shader.set_uniform(\"tex_colors\", COLORS_TEX_UNIT);\n\n\t\treturn true;\n\t}\n\n\tbool duplicate_instance_renderer::finalize()\n\t{\n\t\treturn true;\n\t}\n\n\tvoid duplicate_instance_renderer::render()\n\t{\n//\t\tstatic auto rid = make_random(0, 255);\n//\t\tstatic auto rt = make_random(-1.0f, 1.0f);\n\n\n//\t\tfor(auto& id : _cpu_color_id_buffer)\n//\t\t{\n//\t\t\tid = rid();\n//\t\t}\n//\t\t_color_id_buffer.replace(_cpu_color_id_buffer.data(), _cpu_color_id_buffer.size());\n\n//\t\tfor(unsigned int i = 0; i < _cpu_transform_buffer.size(); ++i)\n//\t\t{\n//\t\t\tconst auto& t = _cpu_transform_buffer[i];\n//\t\t\t_cpu_transform_buffer2[i] = mat34(mat4::translation({rt(), rt(), rt()}).mul(t.as_mat4()));\n//\t\t}\n//\t\t_transform_buffer.replace(_cpu_transform_buffer2.data(), _cpu_transform_buffer2.size());\n\n\n\n\t\t_shader.bind();\n\t\t_transform_texture.bind();\n\t\t_color_ids_texture.bind();\n\t\t_colors_texture.bind();\n\t\t_main_vao.bind();\n\t\tfor(const auto& instances : _instance_sets)\n\t\t{\n\t\t\tglVertexAttribI1i(TEX_OFFSET_ATTRIB, instances.tex_offset);\n//\t\t\tglVertexAttrib3fv(7, instances.color.data());\n\t\t\tglDrawElementsInstanced(GL_TRIANGLES, instances.element_count, GL_UNSIGNED_INT, GLB_BYTE_OFFSET(instances.element_byte_offset), instances.count);\n\t\t}\n\t}\n\n\tvoid duplicate_instance_renderer::render_color(const vec3& color)\n\t{\n\t\t_shader.bind();\n\t\t_transform_texture.bind();\n\t\t_color_ids_texture.bind();\n\t\t_colors_texture.bind();\n\t\t_main_vao.bind();\n\t\tglVertexAttrib3fv(7, color.data());\n\t\tfor(const auto& instances : _instance_sets)\n\t\t{\n\t\t\tglVertexAttribI1i(TEX_OFFSET_ATTRIB, instances.tex_offset);\n\t\t\tglDrawElementsInstanced(GL_TRIANGLES, instances.element_count, GL_UNSIGNED_INT, GLB_BYTE_OFFSET(instances.element_byte_offset), instances.count);\n\t\t}\n\t}\n\n\t// ---------------------------------------------------------------------------------------------------------------------------------------------------------\n\t// private\n\t// ---------------------------------------------------------------------------------------------------------------------------------------------------------\n\n\tvoid duplicate_instance_renderer::_add_mesh(const tess::triangle_mesh& mesh, const mat4& transform, bool remove_duplicate_vertices /*= false*/)\n\t{\n\t\t// 1. apply transform to mesh\n\t\tauto new_mesh = mesh;\n\t\tconst auto ntransform = transform.to_normal_matrix();\n\t\tvector<vec3> all_points;\n\t\tfor(auto& v : new_mesh.vertices)\n\t\t{\n\t\t\tv.position = transform.mul(v.position);\n\t\t\tv.normal = ntransform.mul3x3(v.normal);\n\t\t\tall_points.push_back(v.position);\n\t\t}\n\n\t\t// 2. get unique positions from transformed mesh\n\t\tvector<vec3> new_points;\n\t\tif(remove_duplicate_vertices)\n\t\t{\n\t\t\thash_set<vec3> point_hash;\n\t\t\tpoint_hash.reserve(all_points.size());\n\t\t\tnew_points.reserve(all_points.size());\n\t\t\tfor(const auto& p : all_points)\n\t\t\t{\n\t\t\t\tif(point_hash.find(p) == end(point_hash))\n\t\t\t\t{\n\t\t\t\t\tnew_points.push_back(p);\n\t\t\t\t\tpoint_hash.emplace(p);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tnew_points = all_points;\n\t\t}\n\n\t\tEigenVec3Array dst = to_eigen(new_points);\n\t\tEigenVec3 dst_mean = dst.rowwise().mean();\n\t\tEigenVec3Array dst_local = dst.colwise() - dst_mean;\n\n\t\t// 3. search for candidate mesh with the same number of reference points\n\t\tauto range = _unique_meshes.equal_range(new_points.size());\n\n\t\t// 4. for each candidate mesh\n\t\tauto best_match = range.second;\n\t\tdouble best_error = EPSILON;\n\t\tmat4 best_matrix = mat4::IDENTITY;\n\t\tfor(auto itr = range.first; itr != range.second; ++itr)\n\t\t{\n\t\t\t// 4.1 estimate transformation from candidate mesh to new mesh\n\t\t\tdouble error = 0.0;\n\t\t\tauto m = estimate_transform_3x3(itr->second.src, itr->second.src_mean, itr->second.src_local, itr->second.Aqq,\n\t\t\t\t\t\t\t\t\t\t\tdst, dst_mean, dst_local, error);\n\n\t\t\t// 4.2 save best match so far\n\t\t\tif(error < best_error)\n\t\t\t{\n\t\t\t\tbest_match = itr;\n\t\t\t\tbest_error = error;\n\t\t\t\tbest_matrix = m;\n\t\t\t}\n\t\t}\n\n\t\tif(best_match != range.second)\n\t\t{\n\t\t\tbest_match->second.transforms.push_back(mat34(best_matrix));\n\t\t\tbest_match->second.color_ids.push_back(_current_color_id);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// 5. if no candidate matched, add new mesh as a new candidate\n\t\t\t_total_vbo_size_bytes += new_mesh.vertices.size() * sizeof(tess::vertex);\n\t\t\t_total_ebo_size_bytes += new_mesh.elements.size() * sizeof(tess::element);\n\n\t\t\tpoint_set ps;\n\t\t\tps.mesh = new_mesh;\n\t\t\tps.transforms.push_back(mat34(mat4::IDENTITY));\n\t\t\tps.color_ids.push_back(_current_color_id);\n\n\t\t\tps.src = dst;\n\t\t\tps.src_mean = dst.rowwise().mean();\n\t\t\tps.src_local = dst.colwise() - ps.src_mean;\n\t\t\tps.Aqq = (ps.src_local * ps.src_local.transpose()).inverse();\n\n\t\t\t_unique_meshes.emplace(new_points.size(), ps);\n\n\t\t\tio::print(\"unique meshes:\", _unique_meshes.size());\n\n\t\t\t_total_memory += new_mesh.vertices.size() * sizeof(tess::vertex) + new_mesh.elements.size() * sizeof(tess::element);\n\t\t}\n\n\t\t++_total_geometries;\n\t\t_total_triangles += new_mesh.elements.size()/3;\n\t}\n} // namespace app\n", "meta": {"hexsha": "0a50a26bf8b9d3483c1d4fc53b18f8593a63102a", "size": 23703, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "app/duplicate_instance_renderer.cpp", "max_stars_repo_name": "potato3d/instancing", "max_stars_repo_head_hexsha": "cf5c70533d31a534e6641f21499049b44241116a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-02-13T17:46:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-23T23:55:21.000Z", "max_issues_repo_path": "app/duplicate_instance_renderer.cpp", "max_issues_repo_name": "potato3d/instancing", "max_issues_repo_head_hexsha": "cf5c70533d31a534e6641f21499049b44241116a", "max_issues_repo_licenses": ["MIT"], "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/duplicate_instance_renderer.cpp", "max_forks_repo_name": "potato3d/instancing", "max_forks_repo_head_hexsha": "cf5c70533d31a534e6641f21499049b44241116a", "max_forks_repo_licenses": ["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.4520348837, "max_line_length": 157, "alphanum_fraction": 0.6335063072, "num_tokens": 7056, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.45045957677499465}}
{"text": "#include \"TimeCorr.hxx\"\n#include <string>\n#include <iostream>\n#include <boost/format.hpp>\n#include <cmath>\n#include <ctype.h>\n#include <time.h>\n\n// offset from UTC for the specified grid\nfloat TimeCorr::localTimeOffset(const std::string & grid) {\n  char d1 = grid[0]; \n  char d2 = grid[2]; \n\n  float hrs_per_20deg = 20.0 * 12.0 / 180.0; \n  float fhrs = 0.0; \n  int d1_steps = (int) (toupper(d1) - 'J'); // approximately.. GMT\n  float mult = (d1_steps < 0) ? -1.0 : 1.0; \n  int d2_steps = (int) (d2 - '0');\n\n  float fhrs1 = hrs_per_20deg * ((float) d1_steps);   \n  float fhrs2 = 0.1 * hrs_per_20deg * ((float) d2_steps); \n\n  return fhrs1 + fhrs2; \n}\n\nfloat TimeCorr::circularMean(float maxpos, float a, float b)\n{\n  if(b < a) return circularMean(maxpos, b, a);\n\n  if(((a < 0.0) && (b < 0.0)) ||\n     ((a > 0.0) && (b > 0.0)) || \n     (a * b == 0)) {\n    return 0.5 * (a + b); \n  }\n  else {\n    float m1, m2, ap; \n    m1 = 0.5 * (a + b);\n    ap = a + maxpos; \n    m2 = 0.5 * (ap + b);\n    if (m2 > (0.5 * maxpos)) {\n      m2 = m2 - maxpos; \n    }\n    \n    float lim = maxpos * 0.25; \n    if(fabs(a - m1) <= lim) {\n      return m1; \n    }\n    else return m2; \n  }\n}\n\nfloat TimeCorr::localTimeOffset(const std::string & from, const std::string & to)\n{\n  float f_off = localTimeOffset(from);  // !\n  float t_off = localTimeOffset(to); \n    \n  return circularMean(24.0, f_off, t_off); \n}\n\nfloat TimeCorr::localTime(const std::string & grid, \n\t\t\t  long epoch_time)\n{\n  double h_off = (double) localTimeOffset(grid);\n\n \n  struct tm ts; \n  gmtime_r(&epoch_time, &ts);\n\n  \n  float fhr = (float) ts.tm_hour;\n  float fmin = (float) ts.tm_min; \n  float res = h_off + fhr + fmin / 60.0; // return hours + fraction\n  if(res < -24.0) {\n    std::cerr << boost::format(\"What is going on here.  Grid = [%s] epoch = %ld h_off = %f ts.tm_hour = %d  hr = %f ts.tm_min = %d fmin = %f res = %f\\n\")\n      % grid % epoch_time % h_off % ts.tm_hour % fhr % ts.tm_min % fmin % res;\n  }\n  while(res > 24.0) res -= 24.0; \n  while(res < 0.0) res += 24.0;\n  return res;  \n}\n\n\nfloat TimeCorr::localTime(const std::string & from, \n\t\t\t  const std::string & to, \n\t\t\t  long epoch_time)\n{\n  double h_off = (double) localTimeOffset(from, to);\n\n  struct tm ts; \n  gmtime_r(&epoch_time, &ts);\n\n  float fhr = (float) ts.tm_hour;\n  float fmin = (float) ts.tm_min; \n  float res = h_off + fhr + fmin / 60.0; // return hours + fraction\n  while(res > 24.0) res -= 24.0; \n  while(res < 0.0) res += 24.0;\n  return res;\n}\n", "meta": {"hexsha": "603210c71462d09d0d6aad627a48a49475289dcc", "size": 2471, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/TimeCorr.cxx", "max_stars_repo_name": "kb1vc/WSPRLog", "max_stars_repo_head_hexsha": "0c0121f9050a249905c3e72f2520479d60acba7c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/TimeCorr.cxx", "max_issues_repo_name": "kb1vc/WSPRLog", "max_issues_repo_head_hexsha": "0c0121f9050a249905c3e72f2520479d60acba7c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/TimeCorr.cxx", "max_forks_repo_name": "kb1vc/WSPRLog", "max_forks_repo_head_hexsha": "0c0121f9050a249905c3e72f2520479d60acba7c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.9595959596, "max_line_length": 153, "alphanum_fraction": 0.5774989883, "num_tokens": 908, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059775, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4504569640289147}}
{"text": "// Testing PPR\n#include \"pauli_product.cpp\"\n#include <armadillo>\n#include <chrono>\n#include <iostream>\n#include <stdlib.h>\n\nusing namespace std;\nusing namespace arma;\n\n// Checking that apply_ppr and apply_ppr_slow yields the same result.\nint main()\n{\n  int n = 1024;\n  int n_itt = 100;\n\n  double theta_lower, theta_upper;\n  theta_lower = 0; theta_upper = 3.14159265358979;\n  uniform_real_distribution<double> unif(theta_lower, theta_upper);\n  default_random_engine re;  \n\n  for (int i=0; i<n_itt; i++)\n    {\n      cx_vec psi1, psi2;\n      psi1.randn(n);\n      psi1 = normalise(psi1, 2);\n      psi2 = psi1;\n\n      double theta = unif(re);\n      unsigned x = rand()%n;\n      unsigned z = rand()%n;\n\n      /*      cout << \"Norms before mult\" << endl;\n      cout << norm(psi1, 2) << endl;\n      cout << norm(psi2, 2) << endl;\n\n      cout << \"psi1 before mult\" << endl;\n      cout << psi1 << endl;\n\n      cout << \"psi2 before mult\" << endl;\n      cout << psi2 << endl;*/\n      \n      apply_ppr(x, z, theta, psi1);\n      apply_ppr_slow(x, z, theta, psi2);\n\n      /*      cout << \"Norms after mult\" << endl;\n      cout << norm(psi1, 2) << endl;\n      cout << norm(psi2, 2) << endl;*/\n\n      //      cout << \"theta = \" << theta << endl;\n      cout << \"Difference = \" << norm(psi1-psi2, 2) << endl;\n\n      /*      cout << \"psi1\" << endl;\n      cout << psi1<< endl;\n\n      cout << \"psi2\" << endl;\n      cout << psi2<< endl;\n\n      cout << \"psi1-psi2\" << endl;\n      cout << psi1-psi2 << endl;*/\n    }\n  cx_vec psi1, psi2;\n  psi1.randn(n);\n  psi1 = normalise(psi1, 2);\n  psi2 = psi1;\n  std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now();\n  for (int i=0; i<n_itt; i++)\n    {\n      double theta = unif(re);\n      unsigned x = rand()%n;\n      unsigned z = rand()%n;\n      \n      apply_ppr(x, z, theta, psi1);\n    }\n  std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();\n\n  std::cout << \"PPR Time (fast) = \" << std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count()/n_itt << \"[\u00b5s]\" << std::endl;\n  std::cout << \"PPR Time (fast) = \" << std::chrono::duration_cast<std::chrono::nanoseconds> (end - begin).count()/n_itt << \"[ns]\" << std::endl;\n\n\n  \n  psi1.randn(n);\n  psi1 = normalise(psi1, 2);\n  psi2 = psi1;\n  std::chrono::steady_clock::time_point begin2 = std::chrono::steady_clock::now();\n  for (int i=0; i<n_itt; i++)\n    { \n      double theta = unif(re);\n      unsigned x = rand()%n;\n      unsigned z = rand()%n;\n      \n      apply_ppr_slow(x, z, theta, psi1);\n    }\n  std::chrono::steady_clock::time_point end2 = std::chrono::steady_clock::now();\n\n  std::cout << \"PPR Time (slow) = \" << std::chrono::duration_cast<std::chrono::microseconds>(end2 - begin2).count()/n_itt << \"[\u00b5s]\" << std::endl;\n  std::cout << \"PPR Time (slow) = \" << std::chrono::duration_cast<std::chrono::nanoseconds> (end2 - begin2).count()/n_itt << \"[ns]\" << std::endl;\n\n}\n", "meta": {"hexsha": "f1fa242e522a2d04d9de785ab699d46024b05588", "size": 2904, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "c++/test_ppr.cpp", "max_stars_repo_name": "ikim-quantum/DecodeInterior", "max_stars_repo_head_hexsha": "c07649e8728c784dc1bd2a25602fec14a344a234", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "c++/test_ppr.cpp", "max_issues_repo_name": "ikim-quantum/DecodeInterior", "max_issues_repo_head_hexsha": "c07649e8728c784dc1bd2a25602fec14a344a234", "max_issues_repo_licenses": ["MIT"], "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++/test_ppr.cpp", "max_forks_repo_name": "ikim-quantum/DecodeInterior", "max_forks_repo_head_hexsha": "c07649e8728c784dc1bd2a25602fec14a344a234", "max_forks_repo_licenses": ["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.04, "max_line_length": 145, "alphanum_fraction": 0.5726584022, "num_tokens": 911, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.45045696402891466}}
{"text": "/**\n * @file Data.hpp\n * @author Giulio Romualdi\n * @copyright  Released under the terms of the BSD 3-Clause License\n * @date 2018\n */\n\n#ifndef OSQPEIGEN_DATA_HPP\n#define OSQPEIGEN_DATA_HPP\n\n// Eigen\n#include <Eigen/Dense>\n\n// OSQP\n#include <osqp.h>\n\n// OsqpEigen\n#include <OsqpEigen/SparseMatrixHelper.hpp>\n\n/**\n * OsqpEigen namespace.\n */\nnamespace OsqpEigen\n{\n    /**\n     * Data class is a wrapper of the OSQP OSQPData struct.\n     */\n    class Data\n    {\n        OSQPData *m_data; /**< OSQPData struct. */\n        bool m_isNumberOfVariablesSet; /**< Boolean true if the number of variables is set. */\n        bool m_isNumberOfConstraintsSet; /**< Boolean true if the number of constraints is set. */\n        bool m_isHessianMatrixSet;  /**< Boolean true if the hessian matrix is set. */\n        bool m_isGradientSet; /**< Boolean true if the gradient vector is set. */\n        bool m_isLinearConstraintsMatrixSet; /**< Boolean true if the linear constrain matrix is set. */\n        bool m_isLowerBoundSet; /**< Boolean true if the lower bound vector is set. */\n        bool m_isUpperBoundSet; /**< Boolean true if the upper bound vector is set. */\n\n    public:\n        /**\n         * Constructor.\n         */\n        Data();\n\n        /**\n         * Constructor.\n         * @param n is the number of variables;\n         * @param m is the number of constraints.\n         */\n        Data(int n, int m);\n\n        /**\n         * Deconstructor.\n         */\n        ~Data();\n\n        /**\n         * Clear the hessian matrix.\n         */\n        void clearHessianMatrix();\n\n        /**\n         * Clear the linear constraints matrix.\n         */\n        void clearLinearConstraintsMatrix();\n\n        /**\n         * Set the number of variables.\n         * @param n is the number of variables.\n         */\n        void setNumberOfVariables(int n);\n\n        /**\n         * Set the number of constraints.\n         * @param m is the number of constraints.\n         */\n        void setNumberOfConstraints(int m);\n\n        /**\n         * Set the quadratic part of the cost function (Hessian).\n         * It is assumed to be a simmetric matrix.\n         * @param hessianMatrix is the Hessian matrix.\n         * @return true/false in case of success/failure.\n         */\n        template<typename Derived>\n        bool setHessianMatrix(const Eigen::SparseCompressedBase<Derived> &hessianMatrix);\n\n        /**\n         * Set the linear part of the cost function (Gradient).\n         * @param gradientVector is the Gradient vector.\n         * @note the elements of the gradient are not copied inside the library.\n         * The user has to guarantee that the lifetime of the object passed is the same of the\n         * OsqpEigen object\n         * @return true/false in case of success/failure.\n         */\n        bool setGradient(Eigen::Ref<Eigen::Matrix<c_float, Eigen::Dynamic, 1>> gradientVector);\n\n        Eigen::Matrix<c_float, Eigen::Dynamic, 1> getGradient();\n\n        /**\n         * Set the linear constraint matrix A (size m x n)\n         * @param linearConstraintsMatrix is the linear constraints matrix A.\n         * @return true/false in case of success/failure.\n         */\n        template<typename Derived>\n        bool setLinearConstraintsMatrix(const Eigen::SparseCompressedBase<Derived> &linearConstraintsMatrix);\n\n        /**\n         * Set the array for lower bound (size m).\n         * @param lowerBoundVector is the lower bound constraint.\n         * @note the elements of the lowerBoundVector are not copied inside the library.\n         * The user has to guarantee that the lifetime of the object passed is the same of the\n         * OsqpEigen object\n         * @return true/false in case of success/failure.\n         */\n        bool setLowerBound(Eigen::Ref<Eigen::Matrix<c_float, Eigen::Dynamic, 1>> lowerBoundVector);\n\n        /**\n         * Set the array for upper bound (size m).\n         * @param upperBoundVector is the upper bound constraint.\n         * @note the elements of the upperBoundVector are not copied inside the library.\n         * The user has to guarantee that the lifetime of the object passed is the same of the\n         * OsqpEigen object.\n         * @return true/false in case of success/failure.\n         */\n        bool setUpperBound(Eigen::Ref<Eigen::Matrix<c_float, Eigen::Dynamic, 1>> upperBoundVector);\n\n        /**\n         * Set the array for upper and lower bounds (size m).\n         * @param lowerBound is the lower bound constraint.\n         * @param upperBound is the upper bound constraint.\n         * @note the elements of the upperBound and lowerBound are not copied inside the library.\n         * The user has to guarantee that the lifetime of the object passed is the same of the\n         * OsqpEigen object.\n         * @return true/false in case of success/failure.\n         */\n        bool setBounds(Eigen::Ref<Eigen::Matrix<c_float, Eigen::Dynamic, 1>> lowerBound,\n                       Eigen::Ref<Eigen::Matrix<c_float, Eigen::Dynamic, 1>> upperBound);\n\n        /**\n         * Get the OSQPData struct.\n         * @return a const point to the OSQPData struct.\n         */\n        OSQPData *const & getData() const;\n\n        /**\n         * Verify if all the matrix and vectors are already set.\n         * @return true if all the OSQPData struct are set.\n         */\n        bool isSet() const;\n    };\n}\n\n#include <OsqpEigen/Data.tpp>\n\n#endif\n", "meta": {"hexsha": "f77b57ca9e90b940ef1403fd9778920ef762be2a", "size": 5397, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/OsqpEigen/Data.hpp", "max_stars_repo_name": "marunmurali/osqp-eigen", "max_stars_repo_head_hexsha": "f14aa34fefa4126a9a76e34c77fe3f9dfc2b0c42", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/OsqpEigen/Data.hpp", "max_issues_repo_name": "marunmurali/osqp-eigen", "max_issues_repo_head_hexsha": "f14aa34fefa4126a9a76e34c77fe3f9dfc2b0c42", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/OsqpEigen/Data.hpp", "max_forks_repo_name": "marunmurali/osqp-eigen", "max_forks_repo_head_hexsha": "f14aa34fefa4126a9a76e34c77fe3f9dfc2b0c42", "max_forks_repo_licenses": ["BSD-3-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.3757961783, "max_line_length": 109, "alphanum_fraction": 0.6108949416, "num_tokens": 1202, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.45045696402891466}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2006, 2008, 2010, 2018 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\n/*\n QuantLib Benchmark Suite\n\n Measures the performance of a preselected set of numerically intensive\n test cases. The overall QuantLib Benchmark Index is given by the average\n performance in mflops.\n\n The number of floating point operations of a given test case was measured\n using the perfex library, http://user.it.uu.se/~mikpe/linux/perfctr\n and PAPI, http://icl.cs.utk.edu/papi\n\n Example results: 1. i7 7820X@3.6GHz        :24192.2 mflops\n                  2. i7 4702HQ@2.2GHz       : 6524.9 mflops\n                  3. i7 870@2.93GHz         : 4759.2 mflops\n                  4. Core2 Q9300@2.5Ghz     : 2272.6 mflops\n                  5. Core2 Q6600@2.4Ghz     : 1984.0 mflops\n                  6. i3 540@3.1Ghz          : 1755.3 mflops\n                  7. Core2 Dual@2.0Ghz      :  835.9 mflops\n                  8. Athlon 64 X2 4400+     :  824.2 mflops\n                  9. Core2 Dual@2.0Ghz      :  754.1 mflops\n                 10. Pentium4 Dual@2.8Ghz   :  423.8 mflops\n                 11. Raspberry Pi3@1.2GHz   :  309.2 mflops\n                 12. Pentium4@3.0Ghz        :  266.3 mflops\n                 13. PentiumIII@1.1Ghz      :  146.2 mflops\n                 14. Alpha 2xEV68@833Mhz    :  184.6 mflops\n                 15. Wii PowerPC 750@729MHz :   46.1 mflops\n                 16. Raspberry Pi ARM@700Mhz:   28.3 mflops\n                 17. Strong ARM@206Mhz      :    1.4 mflops\n\n Remarks: OS: Linux, static libs\n  2. g++-6.3.0 -O3 -ffast-math -march=core-avx2\n      Remark: 16 processes\n  2. g++-4.8.1 -O3 -ffast-math -march=core-avx2\n      Remark: eight processes\n  3. gcc-4.6.3, -O3 -ffast-math -mfpmath=sse,387 -march=corei7\n      Remark: eight processes\n  4. icc-11.0,  -gcc-version=420 -fast -fp-model fast=2 -ipo-jobs2\n      Remark: four processes\n  5. icc-11.0,  -gcc-version=420 -fast -fp-model fast=2 -ipo-jobs2\n      Remark: four processes\n  6. gcc-4.4.5, -O3 -ffast-math -mfpmath=sse,387 -msse4.2 -march=core2\n      Remark: four processes\n  7. icc-11.0,  -gcc-version=420 -fast -fp-model fast=2 -ipo-jobs2\n      Remark: two processes\n  8. icc-11.0,  -gcc-version=420 -xSSSE3 -O3 -ipo -no-prec-div -static\n                -fp-model fast=2 -ipo-jobs2, Remark: two processes\n  9. gcc-4.2.1, -O3 -ffast-math -mfpmath=sse,387 -msse3 -funroll-all-loops\n      Remark: two processes\n 10. gcc-4.0.1, -O3 -march=pentium4 -ffast-math\n      -mfpmath=sse,387 -msse2 -funroll-all-loops, Remark: two processes\n 11. gcc-4.9.2  -O2, Remark: four processes\n 12. gcc-4.0.1, -O3 -march=pentium4 -ffast-math\n                -mfpmath=sse,387 -msse2 -funroll-all-loops\n 13. gcc-4.1.1, -O3 -march=pentium3 -ffast-math\n                -mfpmath=sse,387 -msse -funroll-all-loops\n 14. gcc-3.3.5, -O3 -mcpu=e67 -funroll-all-loops, Remark: two processes\n 15. gcc-4.9.2, -O2 -g on a Nintendo Wii\n 16. gcc-4.6.3, -O3\n 17. gcc-3.4.3, -O2 -g on a Zaurus PDA\n\n  This benchmark is derived from quantlibtestsuite.cpp. Please see the\n  copyrights therein.\n*/\n\n#include <ql/types.hpp>\n#include <ql/version.hpp>\n#include <boost/test/unit_test.hpp>\n#include <boost/timer.hpp>\n#include <iostream>\n#include <iomanip>\n#include <list>\n#include <string>\n\n/* PAPI code\n#include <stdio.h\n#include <papi.h>\n*/\n\n/* Use BOOST_MSVC instead of _MSC_VER since some other vendors (Metrowerks,\n   for example) also #define _MSC_VER\n*/\n#ifdef BOOST_MSVC\n#  include <ql/auto_link.hpp>\n#  define BOOST_LIB_NAME boost_unit_test_framework\n#  include <boost/config/auto_link.hpp>\n#  undef BOOST_LIB_NAME\n\n/* uncomment the following lines to unmask floating-point exceptions.\n   See http://www.wilmott.com/messageview.cfm?catid=10&threadid=9481\n*/\n//#  include <float.h>\n//   namespace { unsigned int u = _controlfp(_EM_INEXACT, _MCW_EM); }\n\n#endif\n#include \"utilities.hpp\"\n\n#include \"americanoption.hpp\"\n#include \"asianoptions.hpp\"\n#include \"barrieroption.hpp\"\n#include \"basketoption.hpp\"\n#include \"batesmodel.hpp\"\n#include \"convertiblebonds.hpp\"\n#include \"digitaloption.hpp\"\n#include \"dividendoption.hpp\"\n#include \"europeanoption.hpp\"\n#include \"fdheston.hpp\"\n#include \"hestonmodel.hpp\"\n#include \"interpolations.hpp\"\n#include \"jumpdiffusion.hpp\"\n#include \"marketmodel_smm.hpp\"\n#include \"marketmodel_cms.hpp\"\n#include \"lowdiscrepancysequences.hpp\"\n#include \"quantooption.hpp\"\n#include \"riskstats.hpp\"\n#include \"shortratemodels.hpp\"\n\nusing namespace boost::unit_test_framework;\n\n\nnamespace {\n\n    class Benchmark {\n      public:\n        typedef void (*fct_ptr)();\n        Benchmark(const std::string& name, fct_ptr f, double mflop)\n        : f_(f), name_(name), mflop_(mflop) {\n        }\n\n        test_case* getTestCase() const {\n            return QUANTLIB_TEST_CASE(f_);\n        }\n        double getMflop() const {\n            return mflop_;\n        }\n        std::string getName() const {\n            return name_;\n        }\n      private:\n        fct_ptr f_;\n        const std::string name_;\n        const double mflop_; // total number of mega floating\n                             // point operations (not per sec!)\n    };\n\n    boost::timer t;\n    std::list<double> runTimes;\n    std::list<Benchmark> bm;\n\n    /* PAPI code\n    float real_time, proc_time, mflops;\n    long_long lflop, flop=0;\n    */\n\n    void startTimer() {\n        t.restart();\n\n        /* PAPI code\n        lflop = flop;\n        PAPI_flops(&real_time, &proc_time, &flop, &mflops);\n        */\n    }\n\n    void stopTimer() {\n        runTimes.push_back(t.elapsed());\n\n        /* PAPI code\n        PAPI_flops(&real_time, &proc_time, &flop, &mflops);\n        printf(\"Real_time: %f Proc_time: %f Total mflop: %f\\n\",\n               real_time, proc_time, (flop-lflop)/1e6);\n        */\n    }\n\n    void printResults() {\n        std::string header = \"Benchmark Suite \"\n        #ifdef BOOST_MSVC\n        QL_LIB_NAME;\n        #else\n        \"QuantLib \" QL_VERSION;\n        #endif\n\n        std::cout << std::endl\n                  << std::string(56,'-') << std::endl;\n        std::cout << header << std::endl;\n        std::cout << std::string(56,'-')\n                  << std::endl << std::endl;\n\n        double sum=0;\n        std::list<double>::const_iterator iterT = runTimes.begin();\n        std::list<Benchmark>::const_iterator iterBM = bm.begin();\n\n        while (iterT != runTimes.end()) {\n            const double mflopsPerSec = iterBM->getMflop()/(*iterT);\n            std::cout << iterBM->getName()\n                      << std::string(42-iterBM->getName().length(),' ') << \":\"\n                      << std::fixed << std::setw(6) << std::setprecision(1)\n                      << mflopsPerSec\n                      << \" mflops\" << std::endl;\n\n            sum+=mflopsPerSec;\n            ++iterT;\n            ++iterBM;\n        }\n        std::cout << std::string(56,'-') << std::endl\n                  << \"QuantLib Benchmark Index                  :\"\n                  << std::fixed << std::setw(6) << std::setprecision(1)\n                  << sum/runTimes.size()\n                  << \" mflops\" << std::endl;\n    }\n}\n\n#if defined(QL_ENABLE_SESSIONS)\nnamespace QuantLib {\n    Integer sessionId() { return 0; }\n}\n#endif\n\ntest_suite* init_unit_test_suite(int, char*[]) {\n\n    bm.push_back(Benchmark(\"AmericanOption::FdAmericanGreeks\",\n        &AmericanOptionTest::testFdAmericanGreeks, 518.31));\n    bm.push_back(Benchmark(\"AmericanOption::FdShoutGreeks\",\n        &AmericanOptionTest::testFdShoutGreeks, 546.58));\n    bm.push_back(Benchmark(\"AsianOption::MCArithmeticAveragePrice\",\n        &AsianOptionTest::testMCDiscreteArithmeticAveragePrice, 5186.13));\n    bm.push_back(Benchmark(\"BarrierOption::BabsiriValues\",\n        &BarrierOptionTest::testBabsiriValues, 880.8));\n    bm.push_back(Benchmark(\"BasketOption::EuroTwoValues\",\n        &BasketOptionTest::testEuroTwoValues, 340.04));\n    bm.push_back(Benchmark(\"BasketOption::TavellaValues\",\n        &BasketOptionTest::testTavellaValues, 933.80));\n    bm.push_back(Benchmark(\"BasketOption::OddSamples\",\n        &BasketOptionTest::testOddSamples, 642.46));\n    bm.push_back(Benchmark(\"BatesModel::DAXCalibration\",\n        &BatesModelTest::testDAXCalibration, 1993.35));\n    bm.push_back(Benchmark(\"ConvertibleBondTest::testBond\",\n        &ConvertibleBondTest::testBond, 159.85));\n    bm.push_back(Benchmark(\"DigitalOption::MCCashAtHit\",\n        &DigitalOptionTest::testMCCashAtHit,995.87));\n    bm.push_back(Benchmark(\"DividendOption::FdEuropeanGreeks\",\n        &DividendOptionTest::testFdEuropeanGreeks, 949.52));\n    bm.push_back(Benchmark(\"DividendOption::FdAmericanGreeks\",\n        &DividendOptionTest::testFdAmericanGreeks, 1113.74));\n    bm.push_back(Benchmark(\"EuropeanOption::FdMcEngines\",\n        &EuropeanOptionTest::testMcEngines, 1988.63));\n    bm.push_back(Benchmark(\"EuropeanOption::ImpliedVol\",\n        &EuropeanOptionTest::testImpliedVol, 131.51));\n    bm.push_back(Benchmark(\"EuropeanOption::FdEngines\",\n        &EuropeanOptionTest::testFdEngines, 148.43));\n    bm.push_back(Benchmark(\"EuropeanOption::PriceCurve\",\n        &EuropeanOptionTest::testPriceCurve, 414.76));\n    bm.push_back(Benchmark(\"FdHestonTest::testFdmHestonAmerican\",\n        &FdHestonTest::testFdmHestonAmerican, 234.21));\n    bm.push_back(Benchmark(\"HestonModel::DAXCalibration\",\n        &HestonModelTest::testDAXCalibration, 555.19));\n    bm.push_back(Benchmark(\"InterpolationTest::testSabrInterpolation\",\n        &InterpolationTest::testSabrInterpolation, 2266.06));\n    bm.push_back(Benchmark(\"JumpDiffusion::Greeks\",\n        &JumpDiffusionTest::testGreeks, 433.77));\n    bm.push_back(Benchmark(\"MarketModelCmsTest::testCmSwapsSwaptions\",\n        &MarketModelCmsTest::testMultiStepCmSwapsAndSwaptions,\n        11497.73));\n    bm.push_back(Benchmark(\"MarketModelSmmTest::testMultiSmmSwaptions\",\n        &MarketModelSmmTest::testMultiStepCoterminalSwapsAndSwaptions,\n        11244.95));\n    bm.push_back(Benchmark(\"QuantoOption::ForwardGreeks\",\n        &QuantoOptionTest::testForwardGreeks, 90.98));\n    bm.push_back(Benchmark(\"RandomNumber::MersenneTwisterDescrepancy\",\n        &LowDiscrepancyTest::testMersenneTwisterDiscrepancy, 951.98));\n    bm.push_back(Benchmark(\"RiskStatistics::Results\",\n        &RiskStatisticsTest::testResults, 300.28));\n    bm.push_back(Benchmark(\"ShortRateModel::Swaps\",\n        &ShortRateModelTest::testSwaps, 454.73));\n\n    test_suite* test = BOOST_TEST_SUITE(\"QuantLib benchmark suite\");\n\n    for (std::list<Benchmark>::const_iterator iter = bm.begin();\n         iter != bm.end(); ++iter) {\n        test->add(QUANTLIB_TEST_CASE(startTimer));\n        test->add(iter->getTestCase());\n        test->add(QUANTLIB_TEST_CASE(stopTimer));\n    }\n\n    test->add(QUANTLIB_TEST_CASE(printResults));\n\n    return test;\n}\n", "meta": {"hexsha": "17546fda2b8f1ca5826a83b892b708e323cb76c1", "size": 11433, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test-suite/quantlibbenchmark.cpp", "max_stars_repo_name": "japari/QuantLib", "max_stars_repo_head_hexsha": "c2670bd433289eaf98410e911d87156595ca6d67", "max_stars_repo_licenses": ["BSD-3-Clause"], "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-suite/quantlibbenchmark.cpp", "max_issues_repo_name": "japari/QuantLib", "max_issues_repo_head_hexsha": "c2670bd433289eaf98410e911d87156595ca6d67", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-07-17T18:49:22.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-17T18:49:22.000Z", "max_forks_repo_path": "test-suite/quantlibbenchmark.cpp", "max_forks_repo_name": "TheOnlyDyson/QuantLib", "max_forks_repo_head_hexsha": "78a144bbc5030c9e417e810e44ee48cffe40cf70", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.2410423453, "max_line_length": 79, "alphanum_fraction": 0.6436630806, "num_tokens": 3373, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.45045696402891466}}
{"text": "//==================================================================================================\n/*!\n\n  Copyright 2015 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#include <boost/simd/constant/fact_10.hpp>\n#include <boost/simd/as.hpp>\n#include <simd_test.hpp>\n\n\n\nSTF_CASE_TPL( \"Check fact_10 behavior for integral types\"\n            , (std::uint32_t)(std::uint64_t)(std::int32_t)(std::int64_t)\n            )\n{\n  using boost::simd::as;\n  using boost::simd::detail::fact_10;\n  using boost::simd::Fact_10;\n\n  STF_TYPE_IS(decltype(Fact_10<T>()), T);\n  STF_EQUAL(Fact_10<T>(), T(3628800));\n  STF_EQUAL(fact_10( as(T{}) ),T(3628800));\n}\n\nSTF_CASE_TPL( \"Check fact_10 behavior for floating types\"\n            , (double)(float)\n            )\n{\n  using boost::simd::as;\n  using boost::simd::detail::fact_10;\n  using boost::simd::Fact_10;\n\n  STF_TYPE_IS(decltype(Fact_10<T>()), T);\n  STF_IEEE_EQUAL(Fact_10<T>(), T(3628800));\n  STF_IEEE_EQUAL(fact_10( as(T{}) ), T(3628800));\n}\n", "meta": {"hexsha": "51a382eb7431a1ffeee8d5a9b5ff17883b6a8c54", "size": 1188, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/constant/scalar/fact_10.cpp", "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": "test/constant/scalar/fact_10.cpp", "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": "test/constant/scalar/fact_10.cpp", "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": 28.9756097561, "max_line_length": 100, "alphanum_fraction": 0.5513468013, "num_tokens": 320, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.6187804267137442, "lm_q1q2_score": 0.4504569589111702}}
{"text": "#ifndef ALEPH_TOPOLOGY_PARTITIONS_HH__\n#define ALEPH_TOPOLOGY_PARTITIONS_HH__\n\n#include <aleph/config/Eigen.hh>\n\n#ifdef ALEPH_WITH_EIGEN\n  #include <Eigen/Core>\n  #include <Eigen/Eigenvalues>\n#endif\n\n#include <aleph/geometry/HeatKernel.hh>\n\n#include <aleph/math/Quantiles.hh>\n\n#include <unordered_map>\n#include <stdexcept>\n#include <vector>\n\nnamespace aleph\n{\n\nnamespace topology\n{\n\ntemplate <class SimplicialComplex> std::vector<SimplicialComplex> bisect( const SimplicialComplex& K )\n{\n#ifdef ALEPH_WITH_EIGEN\n\n  auto L = aleph::geometry::weightedLaplacianMatrix( K );\n\n  Eigen::SelfAdjointEigenSolver< decltype(L) > solver;\n  solver.compute( L );\n\n  using Simplex    = typename SimplicialComplex::ValueType;\n  using VertexType = typename Simplex::VertexType;\n  using DataType   = typename Simplex::DataType;\n\n  auto&& eigenvectors = solver.eigenvectors().template cast<DataType>();\n\n  if( eigenvectors.size() < 2 )\n    throw std::runtime_error( \"Laplacian matrix dimensions are insufficient for bisection\" );\n\n  std::vector<DataType> fiedlerVector;\n\n  {\n    auto fiedlerVector_ = eigenvectors.col(1);\n\n    fiedlerVector.assign( fiedlerVector_.data(),\n                          fiedlerVector_.data() + fiedlerVector_.size() );\n  }\n\n  auto median     = aleph::math::median( fiedlerVector.begin(), fiedlerVector.end() );\n  using IndexType = typename std::vector<DataType>::size_type;\n\n  // Prepare map from index to vertex ----------------------------------\n\n  std::unordered_map<IndexType, VertexType> index_to_vertex;\n\n  {\n    std::vector<VertexType> vertices;\n    K.vertices( std::back_inserter( vertices ) );\n\n    IndexType index = IndexType();\n\n    for( auto&& vertex : vertices )\n      index_to_vertex[index++] = vertex;\n  }\n\n  // Partition vertices ------------------------------------------------\n\n  std::unordered_map<VertexType, bool> partition;\n\n  for( IndexType i = 0; i < fiedlerVector.size(); i++ )\n  {\n    auto vertex = index_to_vertex.at(i);\n\n    if( fiedlerVector[i] < median )\n      partition[vertex] = true;\n    else\n      partition[vertex] = false;\n  }\n\n  std::vector<Simplex> simplices( K.begin(), K.end() );\n\n  auto itLeft = std::stable_partition( simplices.begin(), simplices.end(),\n    [&partition] ( const Simplex& s )\n    {\n      // All vertices of the simplex need to be part of the same\n      // partition with respect to the matrix.\n      return s.size() == IndexType( std::count_if( s.begin(), s.end(),\n        [&partition] ( VertexType v )\n        {\n          return partition.at(v);\n        }\n      ) );\n    }\n  );\n\n  auto itRight = std::stable_partition( itLeft, simplices.end(),\n    [&partition] ( const Simplex& s )\n    {\n      // All vertices of the simplex need to be part of the same\n      // partition with respect to the matrix.\n      return s.size() == IndexType( std::count_if( s.begin(), s.end(),\n        [&partition] ( VertexType v )\n        {\n          return !partition.at(v);\n        }\n      ) );\n    }\n  );\n\n  std::vector<SimplicialComplex> complexes;\n  complexes.push_back( SimplicialComplex( simplices.begin(), itLeft ) );\n  complexes.push_back( SimplicialComplex( itLeft, itRight ) );\n\n  return complexes;\n\n#else\n  (void) K;\n  return {};\n#endif\n}\n\n} // namespace topology\n\n} // namespace aleph\n\n#endif\n", "meta": {"hexsha": "18c4cdabea0ffce93a9952e49f289981c0871d0b", "size": 3253, "ext": "hh", "lang": "C++", "max_stars_repo_path": "include/aleph/topology/Partitions.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/topology/Partitions.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/topology/Partitions.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": 25.0230769231, "max_line_length": 102, "alphanum_fraction": 0.6470949892, "num_tokens": 834, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.4504484256509195}}
{"text": "#pragma once\n#include <boost/python.hpp>\n#include \"datatypes.hpp\"\n#include \"vectorize.hpp\"\n\nnamespace gd {\n\nusing namespace boost::python;\n\ntemplate<class ProfileType>\nvoid fill(ProfileType *profile, double_vector r, double_vector target) {\n\tdouble* rp = r.data().begin();\n\tdouble* tp = target.data().begin();\n\tint size = r.size();\n\tfor(int i = 0; i < size; i++) {\n\t\ttp[i] = profile->dphidr(rp[i]);\n\t}\n\t\n}\n\ntemplate<class ProfileType, class Ctor>\n\tvoid py_export_profile_profile(string name) {\n\t\tclass_<ProfileType, bases<Profile, Density> >(name.c_str(), Ctor())\n\t\t\t.def(\"potentialr\", vectorize(&ProfileType::potentialr))\n\t\t\t.def(\"densityr\", vectorize(&ProfileType::densityr))\n\t\t\t.def(\"densityR\", vectorize(&ProfileType::densityR))\n\t\t\t.def(\"dphidr\", vectorize(&ProfileType::dphidr))\n\t\t\t.def(\"fill\", (&fill<ProfileType>))\n\t\t//.def(\"dphidr2\", (&Plummer::dphidr2))\n\t\t\t;\n\t}\n\ntemplate<class ProfileType, class Ctor>\n\tvoid py_export_profile_profile_kw(string name, Ctor ctor) {\n\t\tclass_<ProfileType, bases<Profile, Density> >(name.c_str(), ctor)\n\t\t\t.def(\"potentialr\", vectorize(&ProfileType::potentialr))\n\t\t\t.def(\"densityr\", vectorize(&ProfileType::densityr))\n\t\t\t.def(\"densityR\", vectorize(&ProfileType::densityR))\n\t\t\t.def(\"dphidr\", vectorize(&ProfileType::dphidr))\n\t\t\t.def(\"enclosed_mass\", vectorize(&ProfileType::enclosed_mass))\n\t\t\t.def(\"fill\", (&fill<ProfileType>))\n\t\t//.def(\"dphidr2\", (&Plummer::dphidr2))\n\t\t\t;\n\t}\n\n}", "meta": {"hexsha": "bd18e6503ba876c04835dde978d2e265718859f9", "size": 1415, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "gdfast/src/profile_python.hpp", "max_stars_repo_name": "maartenbreddels/mab", "max_stars_repo_head_hexsha": "112dcfbc4a74b07aff13d489b3776bca58fe9bdf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-12-01T04:10:34.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-01T04:10:34.000Z", "max_issues_repo_path": "gdfast/src/profile_python.hpp", "max_issues_repo_name": "maartenbreddels/mab", "max_issues_repo_head_hexsha": "112dcfbc4a74b07aff13d489b3776bca58fe9bdf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gdfast/src/profile_python.hpp", "max_forks_repo_name": "maartenbreddels/mab", "max_forks_repo_head_hexsha": "112dcfbc4a74b07aff13d489b3776bca58fe9bdf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.7608695652, "max_line_length": 72, "alphanum_fraction": 0.6925795053, "num_tokens": 422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825007, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.450442290681436}}
{"text": "/*\n * test_MACD.cpp\n *\n *  Created on: 2013-4-11\n *      Author: fasiondog\n */\n\n\n#ifdef TEST_ALL_IN_ONE\n    #include <boost/test/unit_test.hpp>\n#else\n    #define BOOST_TEST_MODULE test_hikyuu_indicator_suite\n    #include <boost/test/unit_test.hpp>\n#endif\n\n#include <fstream>\n#include <hikyuu/StockManager.h>\n#include <hikyuu/indicator/crt/KDATA.h>\n#include <hikyuu/indicator/crt/MACD.h>\n#include <hikyuu/indicator/crt/PRICELIST.h>\n#include <hikyuu/indicator/crt/EMA.h>\n\nusing namespace hku;\n\n/**\n * @defgroup test_indicator_MACD test_indicator_MACD\n * @ingroup test_hikyuu_indicator_suite\n * @{\n */\n\n/** @par \u68c0\u6d4b\u70b9 */\nBOOST_AUTO_TEST_CASE( test_MACD ) {\n    PriceList d;\n    for (size_t i = 0; i < 20; ++i) {\n        d.push_back(i);\n    }\n\n    Indicator ind = PRICELIST(d);\n    Indicator macd, bar, diff, dea;\n    Indicator ema1, ema2, fast, slow, bmacd;\n\n    /** @arg \u6e90\u6570\u636e\u4e3a\u7a7a */\n    macd = MACD(Indicator(), 12, 26, 9);\n    BOOST_CHECK(macd.size() == 0);\n    BOOST_CHECK(macd.empty() == true);\n\n    /** @arg n1 = n2 = n3 = 1*/\n    macd = MACD(ind, 1, 1, 1);\n    BOOST_CHECK(macd.getResultNumber() == 3);\n    bar = macd.getResult(0);\n    diff = macd.getResult(1);\n    dea = macd.getResult(2);\n    BOOST_CHECK(bar.size() == 20);\n    BOOST_CHECK(diff.size() == 20);\n    BOOST_CHECK(dea.size() == 20);\n\n    BOOST_CHECK(diff[0] == 0);\n    BOOST_CHECK(diff[1] == 0);\n    BOOST_CHECK(diff[19] == 0);\n\n    BOOST_CHECK(dea[0] == 0);\n    BOOST_CHECK(dea[1] == 0);\n    BOOST_CHECK(dea[19] == 0);\n\n    BOOST_CHECK(bar[0] == 0);\n    BOOST_CHECK(bar[1] == 0);\n    BOOST_CHECK(bar[19] == 0);\n\n    /** @arg n1 = 1 n2 = 2 n3 = 3*/\n    macd = MACD(ind, 1, 2, 3);\n    BOOST_CHECK(macd.size() == 20);\n    BOOST_CHECK(macd.discard() == 0);\n    bar = macd.getResult(0);\n    diff = macd.getResult(1);\n    dea = macd.getResult(2);\n    ema1 = EMA(ind, 1);\n    ema2 = EMA(ind, 2);\n    fast = ema1 - ema2;\n    slow = EMA(fast, 3);\n    bmacd = fast - slow;\n    BOOST_CHECK(bar.size() == 20);\n    BOOST_CHECK(diff.size() == 20);\n    BOOST_CHECK(dea.size() == 20);\n\n    BOOST_CHECK(diff[0] == fast[0]);\n    BOOST_CHECK(diff[1] == fast[1]);\n    BOOST_CHECK(diff[19] == fast[19]);\n\n    BOOST_CHECK(dea[0] == slow[0]);\n    BOOST_CHECK(std::fabs(dea[1] - slow[1]) < 0.0001);\n    BOOST_CHECK(dea[19] == slow[19]);\n\n    BOOST_CHECK(bar[0] == bmacd[0]);\n    BOOST_CHECK(bar[1] == bmacd[1]);\n    BOOST_CHECK(bar[19] == bmacd[19]);\n\n    /** @arg n1 = 3 n2 = 2 n3 = 1*/\n    macd = MACD(ind, 3, 2, 1);\n    BOOST_CHECK(macd.size() == 20);\n    BOOST_CHECK(macd.discard() == 0);\n    bar = macd.getResult(0);\n    diff = macd.getResult(1);\n    dea = macd.getResult(2);\n    ema1 = EMA(ind, 3);\n    ema2 = EMA(ind, 2);\n    fast = ema1 - ema2;\n    slow = EMA(fast, 1);\n    bmacd = fast - slow;\n    BOOST_CHECK(bar.size() == 20);\n    BOOST_CHECK(diff.size() == 20);\n    BOOST_CHECK(dea.size() == 20);\n\n    BOOST_CHECK(diff[0] == fast[0]);\n    BOOST_CHECK(diff[1] == fast[1]);\n    BOOST_CHECK(diff[19] == fast[19]);\n\n    BOOST_CHECK(dea[0] == slow[0]);\n    BOOST_CHECK(dea[1] == slow[1]);\n    BOOST_CHECK(dea[19] == slow[19]);\n\n    BOOST_CHECK(bar[0] == bmacd[0]);\n    BOOST_CHECK(bar[1] == bmacd[1]);\n    BOOST_CHECK(bar[19] == bmacd[19]);\n\n    /** @arg n1 = 3 n2 = 5 n3 = 2*/\n    macd = MACD(ind, 3, 5, 2);\n    BOOST_CHECK(macd.size() == 20);\n    BOOST_CHECK(macd.discard() == 0);\n    bar = macd.getResult(0);\n    diff = macd.getResult(1);\n    dea = macd.getResult(2);\n    ema1 = EMA(ind, 3);\n    ema2 = EMA(ind, 5);\n    fast = ema1 - ema2;\n    slow = EMA(fast, 2);\n    bmacd = fast - slow;\n    BOOST_CHECK(bar.size() == 20);\n    BOOST_CHECK(diff.size() == 20);\n    BOOST_CHECK(dea.size() == 20);\n\n    BOOST_CHECK(diff[0] == fast[0]);\n    BOOST_CHECK(diff[1] == fast[1]);\n    BOOST_CHECK(diff[19] == fast[19]);\n\n    BOOST_CHECK(dea[0] == slow[0]);\n    BOOST_CHECK(dea[1] == slow[1]);\n    BOOST_CHECK(dea[19] == slow[19]);\n\n    BOOST_CHECK(bar[0] == bmacd[0]);\n    BOOST_CHECK(bar[1] == bmacd[1]);\n    BOOST_CHECK(bar[19] == bmacd[19]);\n\n    /** @arg operator() */\n    Indicator expect = MACD(ind, 3, 5, 2);\n    Indicator tmp = MACD(3, 5, 2);\n    Indicator result = tmp(ind);\n    BOOST_CHECK(result.size() == expect.size());\n    for (size_t i = 0; i < expect.size(); ++i) {\n        BOOST_CHECK(result.get(i, 0) == expect.get(i, 0));\n        BOOST_CHECK(result.get(i, 1) == expect.get(i, 1));\n        BOOST_CHECK(result.get(i, 2) == expect.get(i, 2));\n    }\n}\n\n\n//-----------------------------------------------------------------------------\n// test export\n//-----------------------------------------------------------------------------\n#if HKU_SUPPORT_SERIALIZATION\n\n/** @par \u68c0\u6d4b\u70b9 */\nBOOST_AUTO_TEST_CASE( test_MACD_export ) {\n    StockManager& sm = StockManager::instance();\n    string filename(sm.tmpdir());\n    filename += \"/MACD.xml\";\n\n    Stock stock = sm.getStock(\"sh000001\");\n    KData kdata = stock.getKData(KQuery(-20));\n    Indicator ma1 = MACD(CLOSE(kdata));\n    {\n        std::ofstream ofs(filename);\n        boost::archive::xml_oarchive oa(ofs);\n        oa << BOOST_SERIALIZATION_NVP(ma1);\n    }\n\n    Indicator ma2;\n    {\n        std::ifstream ifs(filename);\n        boost::archive::xml_iarchive ia(ifs);\n        ia >> BOOST_SERIALIZATION_NVP(ma2);\n    }\n\n    BOOST_CHECK(ma1.size() == ma2.size());\n    BOOST_CHECK(ma1.discard() == ma2.discard());\n    BOOST_CHECK(ma1.getResultNumber() == ma2.getResultNumber());\n    for (size_t i = 0; i < ma1.size(); ++i) {\n        BOOST_CHECK_CLOSE(ma1.get(i,0), ma2.get(i,0), 0.00001);\n        BOOST_CHECK_CLOSE(ma1.get(i,1), ma2.get(i,1), 0.00001);\n        BOOST_CHECK_CLOSE(ma1.get(i,2), ma2.get(i,2), 0.00001);\n    }\n}\n#endif /* #if HKU_SUPPORT_SERIALIZATION */\n\n/** @} */\n\n\n", "meta": {"hexsha": "dffbac9102b5b6ac3b14592ba408709ad79f695f", "size": 5674, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "hikyuu_cpp/unit_test/libs/hikyuu/indicator/test_MACD.cpp", "max_stars_repo_name": "awesome-archive/hikyuu", "max_stars_repo_head_hexsha": "c9dfcf6635c91e69ac1452fd27633085913806ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-05-12T23:48:13.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-12T23:48:13.000Z", "max_issues_repo_path": "hikyuu_cpp/unit_test/libs/hikyuu/indicator/test_MACD.cpp", "max_issues_repo_name": "allen9mu/hikyuu", "max_issues_repo_head_hexsha": "bed68183029e5a653e3e0ad53510036605e1d610", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-16T03:23:15.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-16T03:23:15.000Z", "max_forks_repo_path": "hikyuu_cpp/unit_test/libs/hikyuu/indicator/test_MACD.cpp", "max_forks_repo_name": "archya/hikyuu", "max_forks_repo_head_hexsha": "2305a977a78bab832bf8fcb4d66482dfef442c9d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-11-23T06:36:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-23T06:36:15.000Z", "avg_line_length": 27.4106280193, "max_line_length": 79, "alphanum_fraction": 0.563623546, "num_tokens": 1875, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825007, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.450442290681436}}
{"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_CONSTANT_FACT_5_HPP_INCLUDED\n#define BOOST_SIMD_CONSTANT_FACT_5_HPP_INCLUDED\n\n/*!\n  @ingroup group-constant\n  @defgroup constant-Fact_5 Fact_5 (function template)\n\n  Generates the @c 5! constant\n\n  @headerref{<boost/simd/constant/fact_5.hpp>}\n\n  @par Description\n\n  1.  @code\n      template<typename T> T Fact_5();\n      @endcode\n\n  2.  @code\n      template<typename T> T Fact_5( boost::simd::as_<T> const& target );\n      @endcode\n\n  Generates a value of type @c T that evaluates to 5!.\n\n  @par Parameters\n\n  | Name                | Description                                                         |\n  |--------------------:|:--------------------------------------------------------------------|\n  | **target**          | a [placeholder](@ref type-as) value encapsulating the constant type |\n\n  @par Return Value\n  A value of type @c T that evaluates to @c T(120).\n\n  @par Requirements\n  - **T** models Value\n**/\n\n#include <boost/simd/constant/scalar/fact_5.hpp>\n#include <boost/simd/constant/simd/fact_5.hpp>\n\n#endif\n", "meta": {"hexsha": "0dd2767ab446debc574fca7b1e9e1f1e5abebf0e", "size": 1433, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/constant/fact_5.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/constant/fact_5.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/constant/fact_5.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": 28.0980392157, "max_line_length": 100, "alphanum_fraction": 0.517794836, "num_tokens": 320, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825006, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.45044229068143593}}
{"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_STATISTICS_FUNCTIONS_GENERIC_LOGNINV_HPP_INCLUDED\n#define NT2_STATISTICS_FUNCTIONS_GENERIC_LOGNINV_HPP_INCLUDED\n#include <nt2/statistics/functions/logninv.hpp>\n#include <boost/assert.hpp>\n#include <boost/dispatch/attributes.hpp>\n#include <nt2/core/container/table/table.hpp>\n#include <nt2/include/constants/half.hpp>\n#include <nt2/include/constants/sqrt_2.hpp>\n#include <nt2/include/constants/two.hpp>\n#include <nt2/include/functions/fma.hpp>\n#include <nt2/include/functions/globalall.hpp>\n#include <nt2/include/functions/simd/erfcinv.hpp>\n#include <nt2/include/functions/exp.hpp>\n#include <nt2/include/functions/fma.hpp>\n#include <nt2/include/functions/is_gtz.hpp>\n#include <nt2/include/functions/is_nltz.hpp>\n#include <nt2/include/functions/norminv.hpp>\n#include <nt2/include/functions/sqrt.hpp>\n\nnamespace nt2 { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT  ( logninv0_, tag::cpu_\n                            , (A0)\n                            , (generic_< floating_<A0> >)\n                            )\n  {\n    typedef A0 result_type;\n    NT2_FUNCTOR_CALL(1)\n    {\n      return  exp(-Sqrt_2<A0>()*erfcinv( nt2::Two<A0>()*a0));\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  ( logninv0_, tag::cpu_\n                            , (A0)(A1)\n                            , (generic_<floating_<A0> > )\n                              (generic_<floating_<A1> >)\n                             )\n  {\n    typedef A0 result_type;\n    NT2_FUNCTOR_CALL(2)\n    {\n\n      return  exp(-Sqrt_2<A0>()*erfcinv( nt2::Two<A0>()*a0)+a1);\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  ( logninv0_, tag::cpu_\n                            , (A0)(A1)(A2)\n                            , (generic_< floating_<A0> >)\n                              (generic_< floating_<A1> >)\n                              (generic_< floating_<A2> >)\n                            )\n  {\n    typedef A0 result_type;\n\n    NT2_FUNCTOR_CALL(3)\n    {\n      BOOST_ASSERT_MSG(nt2::globalall(nt2::is_gtz(a2)), \"sigma(s) must be positive\");\n      return  exp(-Sqrt_2<A0>()*a2*erfcinv( nt2::Two<A0>()*a0)+a1);\n    }\n  };\n\n\n  BOOST_DISPATCH_IMPLEMENT  ( logninv_, tag::cpu_\n                              , (A0)(N0)(A1)(N1)\n                              , ((node_<A0, nt2::tag::logninv_, 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         Out0;\n    typedef typename boost::proto::result_of::child_c<A0&,0>::type          In0;\n    typedef typename boost::proto::result_of::child_c<A0&,1>::type          In1;\n    typedef typename boost::proto::result_of::child_c<A0&,2>::type          In2;\n    typedef typename A0::value_type                                  value_type;\n    BOOST_FORCEINLINE result_type operator()( A0& a0, A1& a1 ) const\n    {\n      doit(a0, a1, N0(), N1());\n    }\n    ////////////////////////////////////////////\n    // No enough inputs to computes all ouputs\n    ////////////////////////////////////////////\n    BOOST_FORCEINLINE static void doit(const A0&, A1&,\n                                       boost::mpl::long_<1> const &, boost::mpl::long_<3> const & )\n    {\n      BOOST_ASSERT_MSG(false, \"Must provide parameter variance to compute confidence bounds.\");\n    }\n    BOOST_FORCEINLINE static void doit(const A0& a0,  A1& a1,\n                                       boost::mpl::long_<2> const &, boost::mpl::long_<3> const & )\n    {\n      BOOST_ASSERT_MSG(false, \"Must provide parameter variance to compute confidence bounds.\");\n      boost::proto::child_c<0>(a1) =  nt2::logninv(boost::proto::child_c<0>(a0),\n                                                   boost::proto::child_c<1>(a0));\n    }\n    BOOST_FORCEINLINE static void doit(const A0&,  A1&,\n                                       boost::mpl::long_<3> const &, boost::mpl::long_<3> const & )\n    {\n      BOOST_ASSERT_MSG(false, \"Must provide parameter variance to compute confidence bounds.\");\n\n    }\n    ////////////////////////////////////////////\n    // No enough output to computes all ouputs\n    ////////////////////////////////////////////\n    template < class T >\n    BOOST_FORCEINLINE static void doit(const A0& a0, A1& a1,\n                                       boost::mpl::long_<4> const &, T const & )\n    {\n      boost::proto::child_c<0>(a1) =  nt2::logninv(boost::proto::child_c<0>(a0),\n                                                   boost::proto::child_c<1>(a0),\n                                                   boost::proto::child_c<2>(a0));\n    }\n    template < class T >\n    BOOST_FORCEINLINE static void doit(const A0& a0, A1& a1,\n                                       boost::mpl::long_<5> const &, T const & )\n    {\n      boost::proto::child_c<0>(a1) =  nt2::logninv(boost::proto::child_c<0>(a0),\n                                                   boost::proto::child_c<1>(a0),\n                                                   boost::proto::child_c<2>(a0));\n    }\n    ////////////////////////////////////////////\n    // Regular cases\n    ////////////////////////////////////////////\n    BOOST_FORCEINLINE static void doit(const A0& a0, A1& a1,\n                                       boost::mpl::long_<4> const &, boost::mpl::long_<3> const & )\n    {\n      conf_bounds(a0, a1, value_type(0.05));\n    }\n    BOOST_FORCEINLINE static void doit(const A0& a0, A1& a1,\n                                       boost::mpl::long_<5> const &, boost::mpl::long_<3> const & )\n    {\n      conf_bounds(a0, a1,boost::proto::child_c<4>(a0));\n    }\n\n\n    BOOST_FORCEINLINE static void conf_bounds(const A0& a0, A1& a1,\n                                              const value_type& alpha )\n    {\n      typedef nt2::memory::container<tag::table_, value_type, nt2::_2D>  semantic;\n      NT2_AS_TERMINAL_IN(semantic, pcov, boost::proto::child_c<3>(a0));\n      const In0& p  = boost::proto::child_c<0>(a0);\n      const In1& mu = boost::proto::child_c<1>(a0);\n      const In2& sigma = boost::proto::child_c<2>(a0);\n      auto logx0 = -Sqrt_2<A0>()*erfcinv( nt2::Two<A0>()*p);\n      auto xvar =   fma(fma(pcov(2,2), logx0, Two<value_type>()*pcov(1,2)), logx0, pcov(1,1));\n      BOOST_ASSERT_MSG(nt2::globalall(nt2::is_nltz(xvar)), \"Covariance matrix must be positive\");\n      value_type normz = -nt2::norminv(alpha*nt2::Half<value_type>());\n      auto halfwidth = normz*nt2::sqrt(xvar);\n      boost::proto::child_c<0>(a1) = exp(fma(sigma, logx0, mu));\n      auto coef = exp(-halfwidth);\n      boost::proto::child_c<1>(a1) = boost::proto::child_c<0>(a1)*coef;\n      boost::proto::child_c<2>(a1) = boost::proto::child_c<0>(a1)/coef;\n    }\n\n  };\n\n} }\n\n#endif\n", "meta": {"hexsha": "cd3a3babcaa2ded6d1dd9ad4ee1d7578398fd602", "size": 7247, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/statistics/include/nt2/statistics/functions/generic/logninv.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/statistics/include/nt2/statistics/functions/generic/logninv.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/statistics/include/nt2/statistics/functions/generic/logninv.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.1369047619, "max_line_length": 99, "alphanum_fraction": 0.5112460328, "num_tokens": 1859, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541067, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4504422847745858}}
{"text": "/*\n * RobotMotionMapUpdater.hpp\n *\n *  Created on: Feb 5, 2014\n *      Author: P\u00e9ter Fankhauser\n *\t Institute: ETH Zurich, ANYbotics\n */\n\n#pragma once\n\n// Elevation Mapping\n#include \"elevation_mapping/ElevationMap.hpp\"\n\n// Eigen\n#include <Eigen/Core>\n\n// Kindr\n#include <kindr/Core>\n\n// ROS\n#include <ros/ros.h>\n\nnamespace elevation_mapping {\n\n/*!\n * Computes the map variance update from the pose covariance of the robot.\n */\nclass RobotMotionMapUpdater {\n public:\n  using Pose = kindr::HomogeneousTransformationPosition3RotationQuaternionD;\n  using Covariance = Eigen::Matrix<double, 3, 3>;\n  using PoseCovariance = Eigen::Matrix<double, 6, 6>;\n  using ReducedCovariance = Eigen::Matrix<double, 4, 4>;\n  using Jacobian = Eigen::Matrix<double, 4, 4>;\n\n  /*!\n   * Constructor.\n   */\n  explicit RobotMotionMapUpdater(ros::NodeHandle nodeHandle);\n\n  /*!\n   * Destructor.\n   */\n  virtual ~RobotMotionMapUpdater();\n\n  /*!\n   * Reads and verifies the ROS parameters.\n   * @return true if successful.\n   */\n  bool readParameters();\n\n  /*!\n   * Computes the model update for the elevation map based on the pose covariance and\n   * adds the update to the map.\n   * @param[in] map the elevation map to be updated.\n   * @param[in] robotPose the current pose.\n   * @param[in] robotPoseCovariance the current pose covariance matrix.\n   * @param[in] time the time of the current update.\n   * @return true if successful.\n   */\n  bool update(ElevationMap& map, const Pose& robotPose, const PoseCovariance& robotPoseCovariance, const ros::Time& time);\n\n private:\n  /*!\n   * Computes the reduced covariance (4x4: x, y, z, yaw) from the full pose covariance (6x6: x, y, z, roll, pitch, yaw).\n   * @param[in] robotPose the robot pose.\n   * @param[in] robotPoseCovariance the full pose covariance matrix (6x6).\n   * @param[out] reducedCovariance the reduced covariance matrix (4x4);\n   * @return true if successful.\n   */\n  static bool computeReducedCovariance(const Pose& robotPose, const PoseCovariance& robotPoseCovariance,\n                                       ReducedCovariance& reducedCovariance);\n\n  /*!\n   * Computes the covariance between the new and the previous pose.\n   * @param[in] robotPose the current robot pose.\n   * @param[in] reducedCovariance the current robot pose covariance matrix (reduced).\n   * @param[out] relativeRobotPoseCovariance the relative covariance between the current and the previous robot pose (reduced form).\n   * @return true if successful.\n   */\n  bool computeRelativeCovariance(const Pose& robotPose, const ReducedCovariance& reducedCovariance, ReducedCovariance& relativeCovariance);\n\n  //! ROS nodehandle.\n  ros::NodeHandle nodeHandle_;\n\n  //! Time of the previous update.\n  ros::Time previousUpdateTime_;\n\n  //! Previous robot pose.\n  Pose previousRobotPose_;\n\n  //! Robot pose covariance (reduced) from the previous update.\n  ReducedCovariance previousReducedCovariance_;\n\n  //! Scaling factor for the covariance matrix (default 1).\n  double covarianceScale_;\n};\n\n}  // namespace elevation_mapping\n", "meta": {"hexsha": "cd5be8bca0465c32aaf6a1130c1f05e2265c5544", "size": 3025, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "elevation_mapping/include/elevation_mapping/RobotMotionMapUpdater.hpp", "max_stars_repo_name": "Pandinosaurus/elevation_mapping", "max_stars_repo_head_hexsha": "553b308c3fc9eefa91525b589d39fc3e3c057efc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 127.0, "max_stars_repo_stars_event_min_datetime": "2015-04-24T12:03:48.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-04T04:07:40.000Z", "max_issues_repo_path": "elevation_mapping/include/elevation_mapping/RobotMotionMapUpdater.hpp", "max_issues_repo_name": "Pandinosaurus/elevation_mapping", "max_issues_repo_head_hexsha": "553b308c3fc9eefa91525b589d39fc3e3c057efc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 41.0, "max_issues_repo_issues_event_min_datetime": "2015-03-29T12:48:54.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-30T07:43:21.000Z", "max_forks_repo_path": "elevation_mapping/include/elevation_mapping/RobotMotionMapUpdater.hpp", "max_forks_repo_name": "Pandinosaurus/elevation_mapping", "max_forks_repo_head_hexsha": "553b308c3fc9eefa91525b589d39fc3e3c057efc", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 89.0, "max_forks_repo_forks_event_min_datetime": "2015-04-15T09:25:29.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-01T15:00:43.000Z", "avg_line_length": 30.25, "max_line_length": 139, "alphanum_fraction": 0.7140495868, "num_tokens": 753, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.4504422847745858}}
{"text": "#pragma once\n\n#include <Eigen/Core>\n#include <functional>\n#include <memory>\n\n#include \"../AgentPosition/agentposition.hh\"\n#include \"../filters/Filter/filter.hh\"\n#include \"../stats/movingaverage.hh\"\n#include \"../stats/lowpassfilter.hh\"\n\nnamespace bold\n{\n  template<typename> class Setting;\n\n  enum class FilterType\n  {\n    Particle = 0,\n    Kalman = 1,\n    UnscentedKalman = 2\n  };\n\n  class Localiser\n  {\n  public:\n    Localiser();\n\n    void update();\n\n    AgentPosition position() const { return d_pos; }\n    AgentPosition smoothedPosition() const { return d_smoothedPos; }\n    double uncertainty() const { return d_uncertainty; }\n\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n  private:\n    typedef Eigen::Vector4d FilterState;\n\n    std::pair<FilterState, double> generateState();\n\n    void predict();\n    void updateSmoothedPos();\n    void updateStateObject();\n\n    bool d_haveLastAgentTransform;\n    Eigen::Affine3d d_lastAgentTransform;\n    Eigen::Quaterniond d_lastQuaternion;\n    double d_preNormWeightSum;\n    LowPassFilter d_preNormWeightSumFilter;\n\n    bool d_shouldRandomise;\n\n    AgentPosition d_pos;\n    AgentPosition d_smoothedPos;\n    MovingAverage<Eigen::Vector4d> d_avgPos;\n    double d_uncertainty;\n\n//    Setting<bool>* d_useLines;\n//    Setting<int>* d_minGoalsNeeded;\n    Setting<double>* d_defaultKidnapWeight;\n    Setting<double>* d_penaltyKidnapWeight;\n    Setting<bool>* d_enablePenaltyRandomise;\n//    Setting<bool>* d_enableDynamicError;\n\n    FilterType d_filterType;\n    std::shared_ptr<Filter<4>> d_filter;\n\n    std::function<double()> d_fieldXRng;\n    std::function<double()> d_fieldYRng;\n    std::function<double()> d_goalAreaXRng;\n    std::function<double()> d_goalAreaYRng;\n    std::function<double()> d_thetaRng;\n  };\n}\n", "meta": {"hexsha": "112543479462f309c0f011d7555e985b96108a6f", "size": 1744, "ext": "hh", "lang": "C++", "max_stars_repo_path": "Localiser/localiser.hh", "max_stars_repo_name": "drewnoakes/bold-humanoid", "max_stars_repo_head_hexsha": "6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Localiser/localiser.hh", "max_issues_repo_name": "drewnoakes/bold-humanoid", "max_issues_repo_head_hexsha": "6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Localiser/localiser.hh", "max_forks_repo_name": "drewnoakes/bold-humanoid", "max_forks_repo_head_hexsha": "6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335", "max_forks_repo_licenses": ["Apache-2.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.5675675676, "max_line_length": 68, "alphanum_fraction": 0.7121559633, "num_tokens": 435, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257127, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4504422788677357}}
{"text": "#include <iostream>\n#include <random>\n\n#include <Eigen/Dense>\n\n#include <h5.hpp>\n\n\nint main()\n{\n    // Create some random matrix.\n    using Matrix = Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;\n    Matrix matrix(1000, 1000);\n\n    std::mt19937 random;\n    std::normal_distribution<double> normal;\n    for (int i = 0; i < matrix.rows(); i++) {\n        for (int j = 0; j < matrix.cols(); j++) {\n            matrix(i, j) = normal(random);\n        }\n    }\n\n    matrix = Matrix(matrix.transpose() * matrix);\n\n    // Store the matrix in an HDF5 file.\n    h5::file file(\"dump.h5\", \"w\");\n\n    file.dataset<h5::f32, 2>(\"eigen/matrix\").write(\n        &matrix(0, 0),\n        {1000, 1000},\n        {.compression = 1, .scaleoffset = 3}\n    );\n    std::clog << \"Matrix is written to dump.h5\\n\";\n\n    // Read back into another matrix.\n    auto dataset = file.dataset<h5::f32, 2>(\"eigen/matrix\");\n    auto shape = dataset.shape();\n\n    Matrix buffer(Matrix::Index(shape.dims[0]), Matrix::Index(shape.dims[1]));\n    dataset.read(&buffer(0, 0), shape);\n\n    std::clog << \"Matrix is read back from the file\\n\";\n}\n", "meta": {"hexsha": "e668a4cc91f215c6889a6e635d4414b2defc3c18", "size": 1120, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/eigen/main.cc", "max_stars_repo_name": "snsinfu/h5", "max_stars_repo_head_hexsha": "64b1865db96dd091932700c80d27e17cac823175", "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/eigen/main.cc", "max_issues_repo_name": "snsinfu/h5", "max_issues_repo_head_hexsha": "64b1865db96dd091932700c80d27e17cac823175", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2020-02-05T08:05:06.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-14T04:17:03.000Z", "max_forks_repo_path": "examples/eigen/main.cc", "max_forks_repo_name": "snsinfu/h5", "max_forks_repo_head_hexsha": "64b1865db96dd091932700c80d27e17cac823175", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.4545454545, "max_line_length": 90, "alphanum_fraction": 0.5883928571, "num_tokens": 319, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4503572377998874}}
{"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\u00e4nkt), 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_BASE_CASE_MATRIX_INCLUDE\n#define MTL_BASE_CASE_MATRIX_INCLUDE\n\n#include <boost/numeric/mtl/utility/static_assert.hpp>\n#include <boost/numeric/meta_math/is_power_of_2.hpp>\n#include <boost/numeric/meta_math/log_2.hpp>\n#include <boost/numeric/mtl/recursion/base_case_test.hpp>\n#include <boost/numeric/mtl/recursion/bit_masking.hpp>\n\nnamespace mtl { namespace recursion {\n\ntemplate <typename Matrix, typename BaseCaseTest>\nstruct base_case_matrix\n{\n    typedef Matrix type;\n};\n\ntemplate <typename Elt, unsigned long Mask, typename Parameters, typename BaseCaseTest>\nstruct base_case_matrix<mtl::mat::morton_dense<Elt, Mask, Parameters>, BaseCaseTest>\n{\n    MTL_STATIC_ASSERT(meta_math::is_power_of_2<BaseCaseTest::base_case_size>::value, \"Static base case size must be power of two\");\n    static const unsigned long base_case_bits= meta_math::log_2<BaseCaseTest::base_case_size>::value;\n\n    typedef typename boost::mpl::if_<\n\tis_k_power_base_case_row_major<base_case_bits, Mask>\n      , mtl::mat::dense2D<Elt, mat::parameters<row_major> >\n      , typename boost::mpl::if_<\n\t    is_k_power_base_case_col_major<base_case_bits, Mask>\n\t  , mtl::mat::dense2D<Elt, mat::parameters<col_major> >\n          , mtl::mat::morton_dense<Elt, Mask, Parameters>\n        >::type\n    >::type type;\n};\n\n\n}} // namespace mtl::recursion\n\n#endif // MTL_BASE_CASE_MATRIX_INCLUDE\n", "meta": {"hexsha": "6e0d29e393ebe7bb04e4e3eea0eaa5a324fd7862", "size": 1809, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/mtl/recursion/base_case_matrix.hpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "boost/numeric/mtl/recursion/base_case_matrix.hpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "boost/numeric/mtl/recursion/base_case_matrix.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.4705882353, "max_line_length": 131, "alphanum_fraction": 0.7490326147, "num_tokens": 460, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4503572377998874}}
{"text": "#include <iostream>\n#include <vector>\n#include <cassert>\n#include <cmath>\n\n#include <boost/program_options.hpp>\n#include <boost/program_options/variables_map.hpp>\n\n#include \"filelib.h\"\n#include \"fdict.h\"\n#include \"weights.h\"\n#include \"sparse_vector.h\"\n#include \"em_utils.h\"\n\nusing namespace std;\nnamespace po = boost::program_options;\n\nvoid InitCommandLine(int argc, char** argv, po::variables_map* conf) {\n  po::options_description opts(\"Configuration options\");\n  opts.add_options()\n        (\"optimization_method,m\", po::value<string>()->default_value(\"em\"), \"Optimization method (em, vb)\")\n        (\"input_format,f\",po::value<string>()->default_value(\"b64\"),\"Encoding of the input (b64 or text)\");\n  po::options_description clo(\"Command line options\");\n  clo.add_options()\n        (\"config\", po::value<string>(), \"Configuration file\")\n        (\"help,h\", \"Print this help message and exit\");\n  po::options_description dconfig_options, dcmdline_options;\n  dconfig_options.add(opts);\n  dcmdline_options.add(opts).add(clo);\n  \n  po::store(parse_command_line(argc, argv, dcmdline_options), *conf);\n  if (conf->count(\"config\")) {\n    ifstream config((*conf)[\"config\"].as<string>().c_str());\n    po::store(po::parse_config_file(config, dconfig_options), *conf);\n  }\n  po::notify(*conf);\n\n  if (conf->count(\"help\")) {\n    cerr << dcmdline_options << endl;\n    exit(1);\n  }\n}\n\ndouble NoZero(const double& x) {\n  if (x) return x;\n  return 1e-35;\n}\n\nvoid Maximize(const bool use_vb,\n              const double& alpha,\n              const int total_event_types,\n              SparseVector<double>* pc) {\n  const SparseVector<double>& counts = *pc;\n\n  if (use_vb)\n    assert(total_event_types >= counts.size());\n\n  double tot = 0;\n  for (SparseVector<double>::const_iterator it = counts.begin();\n       it != counts.end(); ++it)\n    tot += it->second;\n//  cerr << \" = \" << tot << endl;\n  assert(tot > 0.0);\n  double ltot = log(tot);\n  if (use_vb)\n    ltot = digamma(tot + total_event_types * alpha);\n  for (SparseVector<double>::const_iterator it = counts.begin();\n       it != counts.end(); ++it) {\n    if (use_vb) {\n      pc->set_value(it->first, NoZero(digamma(it->second + alpha) - ltot));\n    } else {\n      pc->set_value(it->first, NoZero(log(it->second) - ltot));\n    }\n  }\n#if 0\n  if (counts.size() < 50) {\n    for (SparseVector<double>::const_iterator it = counts.begin();\n         it != counts.end(); ++it) {\n      cerr << \" p(\" << FD::Convert(it->first) << \")=\" << exp(it->second);\n    }\n    cerr << endl;\n  }\n#endif\n}\n\nint main(int argc, char** argv) {\n  po::variables_map conf;\n  InitCommandLine(argc, argv, &conf);\n\n  const bool use_b64 = conf[\"input_format\"].as<string>() == \"b64\";\n  const bool use_vb = conf[\"optimization_method\"].as<string>() == \"vb\";\n  const double alpha = 1e-09;\n  if (use_vb)\n    cerr << \"Using variational Bayes, make sure alphas are set\\n\";\n\n  const string s_obj = \"**OBJ**\";\n  // E-step\n  string cur_key = \"\";\n  SparseVector<double> acc;\n  double logprob = 0;\n  while(cin) {\n    string line;\n    getline(cin, line);\n    if (line.empty()) continue;\n    int feat;\n    double val;\n    size_t i = line.find(\"\\t\");\n    const string key = line.substr(0, i);\n    assert(i != string::npos);\n    ++i;\n    if (key != cur_key) {\n      if  (cur_key.size() > 0) {\n        // TODO shouldn't be num_active, should be total number\n        // of events\n        Maximize(use_vb, alpha, acc.size(), &acc);\n        cout << cur_key << '\\t';\n        if (use_b64)\n          B64::Encode(0.0, acc, &cout);\n        else\n          cout << acc;\n        cout << endl;\n        acc.clear();\n      }\n      cur_key = key;\n    }\n    if (use_b64) {\n      SparseVector<double> g;\n      double obj;\n      if (!B64::Decode(&obj, &g, &line[i], line.size() - i)) {\n        cerr << \"B64 decoder returned error, skipping!\\n\";\n        continue;\n      }\n      logprob += obj;\n      acc += g;\n    } else {       // text encoding - your counts will not be accurate!\n      while (i < line.size()) {\n        size_t start = i;\n        while (line[i] != '=' && i < line.size()) ++i;\n        if (i == line.size()) { cerr << \"FORMAT ERROR\\n\"; break; }\n        string fname = line.substr(start, i - start);\n        if (fname == s_obj) {\n          feat = -1;\n        } else {\n          feat = FD::Convert(line.substr(start, i - start));\n        }\n        ++i;\n        start = i;\n        while (line[i] != ';' && i < line.size()) ++i;\n        if (i - start == 0) continue;\n        val = atof(line.substr(start, i - start).c_str());\n        ++i;\n        if (feat == -1) {\n          logprob += val;\n        } else {\n          acc.add_value(feat, val);\n        }\n      }\n    }\n  }\n  // TODO shouldn't be num_active, should be total number\n  // of events\n  Maximize(use_vb, alpha, acc.size(), &acc);\n  cout << cur_key << '\\t';\n  if (use_b64)\n    B64::Encode(0.0, acc, &cout);\n  else\n    cout << acc;\n  cout << endl << flush;\n\n  cerr << \"LOGPROB: \" << logprob << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "d4c16a2f247f5234c7dc5631a7a3f27773c6e9b6", "size": 4954, "ext": "cc", "lang": "C++", "max_stars_repo_path": "training/mr_em_adapted_reduce.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": "training/mr_em_adapted_reduce.cc", "max_issues_repo_name": "jhclark/cdec", "max_issues_repo_head_hexsha": "237ddc67ffa61da310e19710f902d4771dc323c2", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL", "Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "training/mr_em_adapted_reduce.cc", "max_forks_repo_name": "jhclark/cdec", "max_forks_repo_head_hexsha": "237ddc67ffa61da310e19710f902d4771dc323c2", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL", "Apache-2.0"], "max_forks_count": 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": 28.4712643678, "max_line_length": 107, "alphanum_fraction": 0.5722648365, "num_tokens": 1367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540518, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.45035723779988734}}
{"text": "#pragma once\n\n#include <Eigen/Core>\n#ifndef _MSC_VER\nextern \"C\"{\n#include \"type.h\"\n}\n#else\n#include \"type.h\"\n#endif\n\nDllExport void multi_qubit_dense_matrix_gate_eigen(const UINT* target_qubit_index_list, UINT target_qubit_index_count, const CTYPE* matrix, CTYPE* state, ITYPE dim);\nDllExport void multi_qubit_dense_matrix_gate_eigen(const UINT* target_qubit_index_list, UINT target_qubit_index_count, const Eigen::MatrixXcd& eigen_matrix, CTYPE* state, ITYPE dim);\nDllExport void multi_qubit_dense_matrix_gate_eigen(const UINT* target_qubit_index_list, UINT target_qubit_index_count, const Eigen::Matrix<std::complex<double>,Eigen::Dynamic,Eigen::Dynamic,Eigen::RowMajor>& eigen_matrix, CTYPE* state, ITYPE dim);\n", "meta": {"hexsha": "65fd020c36147949cb2bee92541e2019e5eff784", "size": 714, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/csim/update_ops_cpp.hpp", "max_stars_repo_name": "mshrn/qulacs", "max_stars_repo_head_hexsha": "2fbe8b5f27c093278d33bf6c44c63a09d6332437", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-07-12T18:03:46.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-12T18:03:46.000Z", "max_issues_repo_path": "src/csim/update_ops_cpp.hpp", "max_issues_repo_name": "mshrn/qulacs", "max_issues_repo_head_hexsha": "2fbe8b5f27c093278d33bf6c44c63a09d6332437", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/csim/update_ops_cpp.hpp", "max_forks_repo_name": "mshrn/qulacs", "max_forks_repo_head_hexsha": "2fbe8b5f27c093278d33bf6c44c63a09d6332437", "max_forks_repo_licenses": ["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.6, "max_line_length": 247, "alphanum_fraction": 0.8207282913, "num_tokens": 182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.5660185351961016, "lm_q1q2_score": 0.45035723231465974}}
{"text": "////////////////////////////////////////////////////////////////////////////////\n#include <polyfem/RBFWithLinear.hpp>\n#include <polyfem/Types.hpp>\n#include <polyfem/Logger.hpp>\n\n#include <igl/Timer.h>\n\n#include <Eigen/Dense>\n\n#include <iostream>\n#include <fstream>\n#include <array>\n////////////////////////////////////////////////////////////////////////////////\n\nusing namespace polyfem;\n\nnamespace {\n\n// Harmonic kernel\ndouble kernel(const bool is_volume, const double r) {\n\tif (r < 1e-8) { return 0; }\n\n\tif (is_volume) {\n\t\treturn 1/r;\n\t} else {\n\t\treturn log(r);\n\t}\n}\n\ndouble kernel_prime(const bool is_volume, const double r) {\n\tif (r < 1e-8) { return 0; }\n\n\tif(is_volume) {\n\t\treturn -1/(r*r);\n\t} else {\n\t\treturn 1/r;\n\t}\n}\n\n} // anonymous namespace\n\n////////////////////////////////////////////////////////////////////////////////\n\nRBFWithLinear::RBFWithLinear(\n\t\tconst Eigen::MatrixXd &centers,\n\t\tconst Eigen::MatrixXd &samples,\n\t\tconst Eigen::MatrixXd &local_basis_integral,\n\t\tconst Quadrature &quadr,\n\t\tEigen::MatrixXd &rhs,\n\t\tbool with_constraints)\n\t: centers_(centers)\n{\n\tcompute_weights(samples, local_basis_integral, quadr, rhs, with_constraints);\n}\n\n// -----------------------------------------------------------------------------\n\nvoid RBFWithLinear::basis(const int local_index, const Eigen::MatrixXd &samples, Eigen::MatrixXd &val) const {\n\tEigen::MatrixXd tmp;\n\tbases_values(samples, tmp);\n\tval = tmp.col(local_index);\n}\n\n// -----------------------------------------------------------------------------\n\nvoid RBFWithLinear::grad(const int local_index, const Eigen::MatrixXd &samples, Eigen::MatrixXd &val) const {\n\tEigen::MatrixXd tmp;\n\tconst int dim = centers_.cols();\n\tval.resize(samples.rows(), dim);\n\tfor (int d = 0; d < dim; ++d) {\n\t\tbases_grads(d, samples, tmp);\n\t\tval.col(d) = tmp.col(local_index);\n\t}\n}\n\n////////////////////////////////////////////////////////////////////////////////\n\nvoid RBFWithLinear::bases_values(const Eigen::MatrixXd &samples, Eigen::MatrixXd &val) const {\n\t// Compute A\n\tEigen::MatrixXd A;\n\tcompute_kernels_matrix(samples, A);\n\n\t// Multiply by the weights\n\tval = A * weights_;\n}\n\n// -----------------------------------------------------------------------------\n\nvoid RBFWithLinear::bases_grads(const int axis, const Eigen::MatrixXd &samples, Eigen::MatrixXd &val) const {\n\tconst int num_kernels = centers_.rows();\n\tconst int dim = centers_.cols();\n\n\t// Compute \u2207xA\n\tEigen::MatrixXd A_prime(samples.rows(), num_kernels + 1 + dim);\n\tA_prime.setZero();\n\n\tfor (int j = 0; j < num_kernels; ++j) {\n\t\tA_prime.col(j) = (samples.rowwise() - centers_.row(j)).rowwise().norm().unaryExpr([this](double x)\n\t\t\t{ return kernel_prime(is_volume(), x) / x; });\n\t\tA_prime.col(j) = (samples.col(axis).array() - centers_(j, axis)) * A_prime.col(j).array();\n\t}\n\t// Linear terms\n\tA_prime.middleCols(num_kernels + 1 + axis, 1).setOnes();\n\n\t// Apply weights\n\tval = A_prime * weights_;\n}\n\n////////////////////////////////////////////////////////////////////////////////\n\nvoid RBFWithLinear::compute_kernels_matrix(const Eigen::MatrixXd &samples, Eigen::MatrixXd &A) const {\n\t// Compute A\n\tconst int num_kernels = centers_.rows();\n\tconst int dim = centers_.cols();\n\n\tA.resize(samples.rows(), num_kernels + 1 + dim);\n\tfor (int j = 0; j < num_kernels; ++j) {\n\t\tA.col(j) = (samples.rowwise() - centers_.row(j)).rowwise().norm().unaryExpr([this](double x)\n\t\t\t{ return kernel(is_volume(), x); });\n\t}\n\tA.col(num_kernels).setOnes(); // constant term\n\tA.rightCols(dim) = samples; // linear terms\n}\n\n// -----------------------------------------------------------------------------\n\nvoid RBFWithLinear::compute_constraints_matrix(\n\tconst int num_bases,\n\tconst Quadrature &quadr,\n\tconst Eigen::MatrixXd &local_basis_integral,\n\tEigen::MatrixXd &L,\n\tEigen::MatrixXd &t) const\n{\n\tconst int num_kernels = centers_.rows();\n\tconst int dim = centers_.cols();\n\n\t// Compute KI\n\tEigen::MatrixXd KI(num_kernels, dim);\n\tfor (int j = 0; j < num_kernels; ++j) {\n\t\t// \u222b\u2207x(\u03c6j)(p) = \u03a3_q (xq - xk) * 1/r * h'(r) * wq\n\t\t// - xq is the x coordinate of the q-th quadrature point\n\t\t// - wq is the q-th quadrature weight\n\t\t// - r is the distance from pq to the kernel center\n\t\t// - h is the RBFWithLinear RBF kernel (scalar function)\n\t\tconst Eigen::MatrixXd drdp = quadr.points.rowwise() - centers_.row(j);\n\t\tconst Eigen::VectorXd r = drdp.rowwise().norm();\n\t\tKI.row(j) = (drdp.array().colwise() * (quadr.weights.array() * r.unaryExpr([this](double x)\n\t\t\t{ return kernel_prime(is_volume(), x); }).array() / r.array())).colwise().sum();\n\t}\n\tKI /= quadr.weights.sum();\n\n\t// Compute L\n\tL.resize(num_kernels + dim + 1, num_kernels + 1);\n\tL.setZero();\n\tL.diagonal().setOnes();\n\tL.block(num_kernels + 1, 0, dim, num_kernels) = -KI.transpose();\n\t// std::cout << L.bottomRightCorner(10, 10) << std::endl;\n\n\t// Compute t\n\tt.resize(num_kernels + 1 + dim, num_bases);\n\tt.setZero();\n\tt.bottomRows(dim) = local_basis_integral.transpose().topRows(dim) / quadr.weights.sum();\n}\n\n// -----------------------------------------------------------------------------\n\nvoid RBFWithLinear::compute_weights(const Eigen::MatrixXd &samples,\n\tconst Eigen::MatrixXd &local_basis_integral, const Quadrature &quadr,\n\tEigen::MatrixXd &rhs, bool with_constraints)\n{\n\tlogger().trace(\"#kernel centers: {}\", centers_.rows());\n\tlogger().trace(\"#collocation points: {}\", samples.rows());\n\tlogger().trace(\"#quadrature points: {}\", quadr.weights.size());\n\tlogger().trace(\"#non-vanishing bases: {}\", rhs.cols());\n\n\tif (!with_constraints) {\n\t\t// Compute A\n\t\tEigen::MatrixXd A;\n\t\tcompute_kernels_matrix(samples, A);\n\n\t\t// Solve the system\n\t\tconst int num_kernels = centers_.rows();\n\t\tlogger().trace(\"-- Solving system of size {}x{}\", num_kernels, num_kernels);\n\t\tweights_ = (A.transpose() * A).ldlt().solve(A.transpose() * rhs);\n\t\tlogger().trace(\"-- Solved!\");\n\n\t\treturn;\n\t}\n\n\t// For each basis function f that is nonzero on the element E, we want to\n\t// solve the least square system A w = rhs, where:\n\t//     \u250f                    \u2513\n\t//     \u2503 \u03c6j(pi) ... 1 xi yi \u2503\n\t// A = \u2503   \u250a        \u250a  \u250a  \u250a \u2503 \u220a \u211d^{#S x (#K+1+dim)}\n\t//     \u2503   \u250a        \u250a  \u250a  \u250a \u2503\n\t//     \u2517                    \u251b\n\t//     \u250f                    \u2513^\u22a4\n\t// w = \u2503 wj ... a00 a10 a01 \u2503   \u220a \u211d^{#K+1+dim}\n\t//     \u2517                    \u251b\n\t// - A is the RBF kernels evaluated over the collocation points (#S)\n\t// - b is the expected value of the basis sampled on the boundary (#S)\n\t// - w is the weight of the kernels defining the basis\n\t// - pi = (xi, yi) is the i-th collocation point\n\t//\n\t// Moreover, we want to impose a constraint on the gradients of the kernels\n\t// so that the integral of the gradients over the polytope must be equal to\n\t// the value specified in the argument `local_basis_integral` (#K)\n\t//\n\t// Let `lb` be the precomputed expected value of \u222bf over the rest of the mesh.\n\t// We write down the constraint as:\n\t//\n\t// \u222b_{p \u220a E} \u03a3_j wj \u2207x(\u03c6j)(p) + \u2207x(a^\u22a4\u00b7p + c) dp = lb       (1)\n\t// (1) \u21d4 \u222b_{p \u220a E} \u03a3_j wj \u2207x(\u03c6j)(p) + ax dp = lb\n\t//     \u21d4 lb - \u03a3_j wj \u222b_{p \u220a E} \u2207x(\u03c6j)(p) dp = ax Vol(E)\n\t//\n\t// We now have a relationship w = Lv + t, where the weights (and esp. the\n\t// linear terms in the weight vector w), are expressed as an affine\n\t// combination of unknowns v = [wj ... c] \u220a \u211d^{#K+1} and a translation t\n\t//\n\t// After solving the new least square system A L v = rhs - A t, we can retrieve\n\t// w = L v\n\n\t//\n\t//     \u250f                      \u2513^\u22a4\n\t// t = \u2503 0  \u2508  \u2508  0 0 lbx lby \u2503   / Vol(E) \u220a \u211d^{#K+1+dim}\n\t//     \u2517                      \u251b\n\t//\n\t//     \u250f                  \u2513\n\t//     \u2503   1              \u2503\n\t//     \u2503       1          \u2503\n\t//     \u2503          \u00b7       \u2503\n\t// L = \u2503             \u00b7    \u2503 \u220a \u211d^{ (#K+1+dim) x (#K+1}) }\n\t//     \u2503                1 \u2503\n\t//     \u2503 Lx_j  \u2508        0 \u2503\n\t//     \u2503 Ly_j  \u2508        0 \u2503\n\t//     \u2517                  \u251b\n\t// Where Lx_j = -\u222b\u2207x\u03c6j / Vol(E) = -\u222b_{p \u220a E} \u2207x(\u03c6j)(p) / Vol(E) is integrated numerically\n\t//\n\n\tconst int num_bases = rhs.cols();\n\n\t// Compute A\n\tEigen::MatrixXd A;\n\tcompute_kernels_matrix(samples, A);\n\n\t// Compute L and t\n\t// Note that t is stored into `weights_` for memory efficiency reasons\n\tEigen::MatrixXd L;\n\tcompute_constraints_matrix(num_bases, quadr, local_basis_integral, L, weights_);\n\n\t// Compute b = rhs - A t\n\trhs -= A * weights_;\n\n\t// Solve the system\n\tlogger().trace(\"-- Solving system of size {}x{}\", L.cols(), L.cols());\n\tweights_ += L * (L.transpose() * A.transpose() * A * L).ldlt().solve(L.transpose() * A.transpose() * rhs);\n\tlogger().trace(\"-- Solved!\");\n\n\t// std::cout << weights_.bottomRows(10) << std::endl;\n\n\t// Eigen::MatrixXd M, x, dx;\n\t// grad(0, quadr.points, M);\n\t// for (int d = 0; d < dim; ++d) {\n\t// \tbasis(0, quadr.points, x);\n\t// \tauto asd = quadr.points;\n\t// \tasd.col(d).array() += 1e-7;\n\t// \tbasis(0, asd, dx);\n\t// \tstd::cout << (dx - x) / 1e-7 - M.col(d) << std::endl;\n\t// \tstd::cout << (M.col(d).array() * quadr.weights.array()).sum() - local_basis_integral(0, d) << std::endl;\n\t// }\n}\n", "meta": {"hexsha": "36292d68a38b5da248145b57b9bf8ae4f9c7a2c3", "size": 8881, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/basis/function/RBFWithLinear.cpp", "max_stars_repo_name": "ldXiao/polyfem", "max_stars_repo_head_hexsha": "d4103af16979ff67d461a9ebe46a14bbc4dc8c7c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 228.0, "max_stars_repo_stars_event_min_datetime": "2018-11-23T19:32:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T10:30:51.000Z", "max_issues_repo_path": "src/basis/function/RBFWithLinear.cpp", "max_issues_repo_name": "ldXiao/polyfem", "max_issues_repo_head_hexsha": "d4103af16979ff67d461a9ebe46a14bbc4dc8c7c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2019-03-11T22:44:14.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T14:50:35.000Z", "max_forks_repo_path": "src/basis/function/RBFWithLinear.cpp", "max_forks_repo_name": "ldXiao/polyfem", "max_forks_repo_head_hexsha": "d4103af16979ff67d461a9ebe46a14bbc4dc8c7c", "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": 32.6507352941, "max_line_length": 110, "alphanum_fraction": 0.5554554667, "num_tokens": 2580, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.795658090372256, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.45035722682943163}}
{"text": "#ifndef INCLUDED_STDDEFX\n#include \"stddefx.h\"\n#define INCLUDED_STDDEFX\n#endif\n\n#ifndef INCLUDED_GEO_RIKSNEIGHBOURHOOD\n#include \"geo_riksneighbourhood.h\"\n#define INCLUDED_GEO_RIKSNEIGHBOURHOOD\n#endif\n\n// Library headers.\n\n#ifndef INCLUDED_BOOST_MATH_TR1\n#include <boost/math/tr1.hpp>\n#define INCLUDED_BOOST_MATH_TR1\n#endif\nusing namespace boost::math; // use then tr1\n\n// PCRaster library headers.\n#ifndef INCLUDED_COM_MATH\n#include \"com_math.h\"\n#define INCLUDED_COM_MATH\n#endif\n\n// Module headers.\n\n\n\n/*!\n  \\file\n  This file contains the implementation of the RiksNeighbourhood class.\n*/\n\n\n\n//------------------------------------------------------------------------------\n\n/*\nnamespace geo {\n\nclass RiksNeighbourhoodPrivate\n{\npublic:\n\n  RiksNeighbourhoodPrivate()\n  {\n  }\n\n  ~RiksNeighbourhoodPrivate()\n  {\n  }\n\n};\n\n} // namespace geo\n*/\n\n\n\n//------------------------------------------------------------------------------\n// DEFINITION OF STATIC RIKSNEIGHBOURHOOD MEMBERS\n//------------------------------------------------------------------------------\n\nboost::tuple<size_t, size_t> geo::RiksNeighbourhood::circleCell(double radius)\n{\n  PRECOND(radius > 0.0);\n\n  boost::tuple<size_t, size_t> cell;\n  double currentDifference(0), difference(0);\n\n  // Determine max radius of raster which can contain a circle with given\n  // radius.\n  size_t maxRadius = static_cast<size_t>(std::ceil(radius));\n\n  // Only handle one quarter of the circle.\n  for(size_t row = 0; row <= maxRadius; ++row) {\n    for(size_t col = 0; col <= maxRadius; ++col) {\n\n      if(row == 0 && col == 0) {\n        // First cell handled.\n        difference = std::abs(radius - tr1::hypot<double>(row, col));\n        cell = boost::make_tuple(row, col);\n      }\n      else {\n        currentDifference = std::abs(radius - tr1::hypot<double>(row, col));\n        if(currentDifference < difference) {\n          difference = currentDifference;\n          cell = boost::make_tuple(row, col);\n        }\n      }\n    }\n  }\n\n  return cell;\n}\n\n\n\n//------------------------------------------------------------------------------\n// DEFINITION OF RIKSNEIGHBOURHOOD MEMBERS\n//------------------------------------------------------------------------------\n\ngeo::RiksNeighbourhood::RiksNeighbourhood(double toRadius)\n\n  : Neighbourhood(toRadius)\n\n{\n  init();\n}\n\n\n\ngeo::RiksNeighbourhood::RiksNeighbourhood(double fromRadius, double toRadius)\n\n  : Neighbourhood(fromRadius, toRadius)\n\n{\n  init();\n}\n\n\n\ngeo::RiksNeighbourhood::~RiksNeighbourhood()\n{\n}\n\n\n\n//!\n/*!\n  \\param     .\n  \\return    .\n  \\exception .\n  \\warning   .\n  \\sa        .\n*/\nvoid geo::RiksNeighbourhood::init()\n{\n  // Determine which cells match the given radiusses best. These are the cells\n  // who's centers are closest to the circle defined by the radiusses.\n  boost::tuple<size_t, size_t> fromCircleCell = boost::make_tuple(0, 0);\n  boost::tuple<size_t, size_t> toCircleCell(fromCircleCell);\n\n  if(fromRadius() > 0.0) {\n    fromCircleCell = circleCell(fromRadius());\n  }\n\n  if(toRadius() > 0.0) {\n    toCircleCell = circleCell(toRadius());\n  }\n\n  // Determine the radiusses of the Riks neighbourhoods of which the selected\n  // cells are part.\n  double fromRadius = tr1::hypot<double>(\n         fromCircleCell.get<0>(), fromCircleCell.get<1>());\n  double toRadius = tr1::hypot<double>(\n         toCircleCell.get<0>(), toCircleCell.get<1>());\n\n  // Make sure the current set radius is equal of larger than the selected one.\n  POSTCOND(static_cast<double>(radius()) >= toRadius);\n\n  // Determine which cells are part of the Riks neighbourhood with the\n  // selected radius.\n  size_t offset = radius();\n  for(size_t row = 0; row <= radius(); ++row) {\n    for(size_t col = 0; col <= radius(); ++col) {\n      double radius = tr1::hypot<double>(row, col);\n      if((radius > fromRadius && radius < toRadius) ||\n          com::equal_epsilon(radius, fromRadius) ||\n          com::equal_epsilon(radius, toRadius)) {\n        this->cell(offset + row, offset + col) = 1.0;\n        this->cell(offset + row, offset - col) = 1.0;\n        this->cell(offset - row, offset + col) = 1.0;\n        this->cell(offset - row, offset - col) = 1.0;\n      }\n    }\n  }\n}\n\n\n\n//------------------------------------------------------------------------------\n// DEFINITION OF FREE OPERATORS\n//------------------------------------------------------------------------------\n\n\n\n//------------------------------------------------------------------------------\n// DEFINITION OF FREE FUNCTIONS\n//------------------------------------------------------------------------------\n\n\n\n", "meta": {"hexsha": "101d1c3965ba906a98b7671f88306d1121791514", "size": 4554, "ext": "cc", "lang": "C++", "max_stars_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcrgeo/geo_riksneighbourhood.cc", "max_stars_repo_name": "quanpands/wflow", "max_stars_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcrgeo/geo_riksneighbourhood.cc", "max_issues_repo_name": "quanpands/wflow", "max_issues_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcrgeo/geo_riksneighbourhood.cc", "max_forks_repo_name": "quanpands/wflow", "max_forks_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.4742268041, "max_line_length": 80, "alphanum_fraction": 0.5546772069, "num_tokens": 1053, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.4502823041559679}}
{"text": "/** Copyright 2017-2020 CNRS-AIST JRL and CNRS-UM LIRMM */\n\n#include <tvm/Space.h>\n#include <tvm/Variable.h>\n#include <tvm/constraint/BasicLinearConstraint.h>\n#include <tvm/constraint/abstract/LinearConstraint.h>\n#include <tvm/hint/Substitution.h>\n#include <tvm/hint/internal/DiagonalCalculator.h>\n#include <tvm/hint/internal/GenericCalculator.h>\n#include <tvm/hint/internal/Substitutions.h>\n#include <tvm/internal/MatrixProperties.h>\n#include <tvm/internal/VariableVectorPartition.h>\n\n#include <Eigen/SVD>\n\n//#include <iostream>\n#include <vector>\n\n#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN\n#define DOCTEST_CONFIG_SUPER_FAST_ASSERTS\n#include \"doctest/doctest.h\"\n\nusing namespace tvm;\nusing namespace tvm::hint;\nusing namespace tvm::hint::internal;\nusing namespace Eigen;\n\nTEST_CASE(\"GenericCalculator\")\n{\n  VariablePtr x = Space(5).createVariable(\"x\");\n  VariablePtr y = Space(3).createVariable(\"y\");\n  MatrixXd A = MatrixXd::Random(5, 5);\n  MatrixXd B = MatrixXd::Random(5, 3);\n  VectorXd b = VectorXd::Random(5);\n\n  std::shared_ptr<constraint::BasicLinearConstraint> c(\n      new constraint::BasicLinearConstraint({A, B}, {x, y}, b, constraint::Type::EQUAL));\n\n  auto calc = GenericCalculator().impl({std::static_pointer_cast<constraint::abstract::LinearConstraint>(c)}, {x}, 5);\n  calc->update();\n\n  MatrixXd AsA(5, 5);\n  MatrixXd StA(0, 5);\n  calc->premultiplyByASharpAndSTranspose(AsA, StA, A, false);\n  FAST_CHECK_UNARY(AsA.isIdentity());\n\n  MatrixXd AsB(5, 3);\n  MatrixXd StB(0, 3);\n  calc->premultiplyByASharpAndSTranspose(AsB, StB, B, true);\n  auto qrA = A.colPivHouseholderQr();\n  FAST_CHECK_UNARY(AsB.isApprox(-MatrixXd(qrA.solve(B))));\n\n  MatrixXd C(3, 5);\n  C << 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0;\n  MatrixXd D = MatrixXd::Random(3, 3);\n  VectorXd d = VectorXd::Random(3);\n\n  std::shared_ptr<constraint::BasicLinearConstraint> c2(\n      new constraint::BasicLinearConstraint({C, D}, {x, y}, d, constraint::Type::EQUAL));\n\n  auto calc2 = GenericCalculator().impl({std::static_pointer_cast<constraint::abstract::LinearConstraint>(c2)}, {x}, 2);\n  calc2->update();\n  MatrixXd CsD(5, 3);\n  MatrixXd StD(1, 3);\n  calc2->premultiplyByASharpAndSTranspose(CsD, StD, D, true);\n  FAST_CHECK_UNARY(CsD.topRows(2).isApprox(-D.topRows(2)));\n  FAST_CHECK_UNARY(CsD.bottomRows(3).isZero());\n  FAST_CHECK_UNARY(StD.isApprox(D.row(2)));\n  FAST_CHECK_UNARY(MatrixXd(C * calc2->N()).isZero());\n  FAST_CHECK_EQ(calc2->N().colPivHouseholderQr().rank(), 3);\n}\n\nTEST_CASE(\"Diagonal Calculator\")\n{\n  VariablePtr x = Space(7).createVariable(\"x\");\n  VariablePtr y = Space(3).createVariable(\"y\");\n\n  {\n    MatrixXd A = MatrixXd::Identity(7, 7);\n    MatrixXd B = MatrixXd::Random(7, 3);\n    VectorXd b = VectorXd::Random(7);\n\n    std::shared_ptr<constraint::BasicLinearConstraint> c(\n        new constraint::BasicLinearConstraint({A, B}, {x, y}, b, constraint::Type::EQUAL));\n\n    auto calc =\n        DiagonalCalculator().impl({std::static_pointer_cast<constraint::abstract::LinearConstraint>(c)}, {x}, 7);\n    calc->update();\n\n    MatrixXd AsA(7, 7);\n    MatrixXd StA(0, 7);\n    calc->premultiplyByASharpAndSTranspose(AsA, StA, A, false);\n    FAST_CHECK_UNARY(AsA.isIdentity());\n\n    MatrixXd AsB(7, 3);\n    MatrixXd StB(0, 3);\n    calc->premultiplyByASharpAndSTranspose(AsB, StB, B, false);\n    FAST_CHECK_UNARY(AsB.isApprox(B));\n\n    FAST_CHECK_EQ(calc->N().rows(), 7);\n    FAST_CHECK_EQ(calc->N().cols(), 0);\n  }\n\n  {\n    MatrixXd A(3, 7);\n    A << 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0;\n    MatrixXd B = MatrixXd::Random(3, 3);\n    VectorXd b = VectorXd::Random(3);\n\n    std::shared_ptr<constraint::BasicLinearConstraint> c(\n        new constraint::BasicLinearConstraint({A, B}, {x, y}, b, constraint::Type::EQUAL));\n\n    auto calc = DiagonalCalculator({1, 3, 4}).impl(\n        {std::static_pointer_cast<constraint::abstract::LinearConstraint>(c)}, {x}, 3);\n    calc->update();\n\n    MatrixXd AsA(7, 7);\n    MatrixXd StA(0, 7);\n    calc->premultiplyByASharpAndSTranspose(AsA, StA, A, false);\n    FAST_CHECK_UNARY(AsA.isApprox(A.transpose() * A));\n\n    MatrixXd AsB(7, 3);\n    MatrixXd StB(0, 3);\n    calc->premultiplyByASharpAndSTranspose(AsB, StB, B, false);\n    FAST_CHECK_UNARY(AsB.isApprox(A.transpose() * B));\n\n    MatrixXd N(7, 4);\n    N << 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1;\n    FAST_CHECK_UNARY(N.isApprox(calc->N()));\n  }\n\n  {\n    MatrixXd A(5, 7);\n    A << 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0;\n    MatrixXd B = MatrixXd::Random(5, 3);\n    VectorXd b = VectorXd::Random(5);\n\n    std::shared_ptr<constraint::BasicLinearConstraint> c(\n        new constraint::BasicLinearConstraint({A, B}, {x, y}, b, constraint::Type::EQUAL));\n\n    auto calc = DiagonalCalculator({1, 3, 4}, {0, 2})\n                    .impl({std::static_pointer_cast<constraint::abstract::LinearConstraint>(c)}, {x}, 3);\n    calc->update();\n\n    MatrixXd AsA(7, 7);\n    MatrixXd StA(2, 7);\n    calc->premultiplyByASharpAndSTranspose(AsA, StA, A, false);\n    FAST_CHECK_UNARY(AsA.isApprox(A.transpose() * A));\n    FAST_CHECK_UNARY(StA.isZero());\n\n    MatrixXd AsB(7, 3);\n    MatrixXd StB(2, 3);\n    calc->premultiplyByASharpAndSTranspose(AsB, StB, B, false);\n    FAST_CHECK_UNARY(AsB.isApprox(A.transpose() * B));\n    FAST_CHECK_UNARY(StB.row(0).isApprox(B.row(0)));\n    FAST_CHECK_UNARY(StB.row(1).isApprox(B.row(2)));\n\n    MatrixXd N(7, 4);\n    N << 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1;\n    FAST_CHECK_UNARY(N.isApprox(calc->N()));\n  }\n}\n\nMatrixXd randM(int m, int n, int r = 0)\n{\n  if(r <= 0 || r == std::min(m, n))\n    return MatrixXd::Random(m, n);\n  else\n    return MatrixXd::Random(m, r) * MatrixXd::Random(r, n);\n}\n\n/** check whether the systems given by cstr and by subs are equivalent.\n * The system are supposed to be feasible.\n * From cstr, we deduce a system A [x;y] = b (1)\n * From subs, we deduce C [y;z] = d and x = E y + F z + g (2)\n * We check that any solution of (1) is a solution of (2) by writing a\n * solution of (1) [x;y] = pinv(A)*b + Na u with Na a base of the nullspace of\n * A and u a vector. For size(u) different value of u, we the rewrite (2) as a\n * system of z only, and verify we can find a solution.\n * To check that any solution of (2) yield a solution of (1), we first solve\n * C [y;z] = d to get [y;z] = pinv(C)*d + Nc v. Then for size(v) value of v, we\n * compute x from x = E y + F z + g, and check that [x;y] is a solution of (1).\n */\nvoid checkEquivalence(const std::vector<std::shared_ptr<constraint::BasicLinearConstraint>> & cstr,\n                      Substitutions & subs)\n{\n  subs.updateSubstitutions();\n\n  VariableVector x(subs.variables());\n  VariableVector y;\n  VariableVector z(subs.additionalVariables());\n  tvm::internal::VariableCountingVector partition(true);\n  partition.add(x);\n  for(const auto & c : cstr)\n  {\n    partition.add(c->variables());\n  }\n  int m0 = 0;\n  for(auto & c : cstr)\n  {\n    m0 += c->size();\n    for(const auto & vi : tvm::internal::VariableVectorPartition(c->variables(), partition))\n    {\n      if(!x.contains(*vi))\n      {\n        y.add(vi);\n      }\n    }\n  }\n\n  int m1 = 0;\n  for(auto & c : subs.additionalConstraints())\n  {\n    m1 += c->size();\n  }\n\n  // Create A and b such that the system given by cstr is A [x;y] = b\n  MatrixXd A = MatrixXd::Zero(m0, x.totalSize() + y.totalSize());\n  VectorXd b(m0);\n  m0 = 0;\n  for(const auto & c : cstr)\n  {\n    auto mi = c->size();\n    for(const auto & xi : x.variables())\n    {\n      if(c->variables().contains(*xi))\n      {\n        auto rx = xi->getMappingIn(x);\n        A.block(m0, rx.start, mi, rx.dim) = c->jacobian(*xi);\n      }\n    }\n    for(const auto & yi : y.variables())\n    {\n      if(c->variables().contains(*yi))\n      {\n        auto ry = yi->getMappingIn(y);\n        A.block(m0, ry.start + x.totalSize(), mi, ry.dim) = c->jacobian(*yi);\n      }\n    }\n    switch(c->rhs())\n    {\n      case constraint::RHS::ZERO:\n        b.segment(m0, mi).setZero();\n        break;\n      case constraint::RHS::AS_GIVEN:\n        b.segment(m0, mi) = c->e();\n        break;\n      case constraint::RHS::OPPOSITE:\n        b.segment(m0, mi) = -c->e();\n        break;\n    }\n    m0 += mi;\n  }\n\n  // Create C and d such that the additional constraint of subs write C [y;z] = d\n  MatrixXd C = MatrixXd::Zero(m1, y.totalSize() + z.totalSize());\n  VectorXd d(m1);\n  m1 = 0;\n  for(const auto & c : subs.additionalConstraints())\n  {\n    auto mi = c->size();\n    for(const auto & yi : y.variables())\n    {\n      if(c->variables().contains(*yi))\n      {\n        auto ry = yi->getMappingIn(y);\n        C.block(m1, ry.start, mi, ry.dim) = c->jacobian(*yi);\n      }\n    }\n    for(const auto & zi : z.variables())\n    {\n      if(c->variables().contains(*zi))\n      {\n        auto rz = zi->getMappingIn(z);\n        C.block(m1, rz.start + y.totalSize(), mi, rz.dim) = c->jacobian(*zi);\n      }\n    }\n    switch(c->rhs())\n    {\n      case constraint::RHS::ZERO:\n        d.segment(m1, mi).setZero();\n        break;\n      case constraint::RHS::AS_GIVEN:\n        d.segment(m1, mi) = c->e();\n        break;\n      case constraint::RHS::OPPOSITE:\n        d.segment(m1, mi) = -c->e();\n        break;\n    }\n    m1 += mi;\n  }\n\n  // Create E, F and g such that the substitutions write x = E y + F z + g\n  MatrixXd E = MatrixXd::Zero(x.totalSize(), y.totalSize());\n  MatrixXd F = MatrixXd::Zero(x.totalSize(), z.totalSize());\n  VectorXd g(x.totalSize());\n  for(size_t i = 0; i < x.variables().size(); ++i)\n  {\n    const auto & f = subs.variableSubstitutions()[i];\n    auto rx = x[static_cast<int>(i)]->getMappingIn(x);\n    for(const auto & yi : y.variables())\n    {\n      if(f->variables().contains(*yi))\n      {\n        auto ry = yi->getMappingIn(y);\n        E.block(rx.start, ry.start, rx.dim, ry.dim) = f->jacobian(*yi);\n      }\n    }\n    for(const auto & zi : z.variables())\n    {\n      if(f->variables().contains(*zi))\n      {\n        auto rz = zi->getMappingIn(z);\n        F.block(rx.start, rz.start, rx.dim, rz.dim) = f->jacobian(*zi);\n      }\n    }\n    g.segment(rx.start, rx.dim) = f->b();\n  }\n\n  // Solve A [x;y] = b\n  auto svdA = A.jacobiSvd(ComputeFullU | ComputeFullV);\n  auto sol0 = svdA.solve(b);                                      // least square solution\n  auto r0 = (A * sol0 - b).norm();                                // residual\n  MatrixXd Na = svdA.matrixV().rightCols(A.cols() - svdA.rank()); // nullspace of A0\n  FAST_CHECK_LE(r0, 1e-9);\n\n  // Solve C [y;z] = d\n  VectorXd sol1;\n  MatrixXd Nc;\n  if(C.size() > 0)\n  {\n    auto svdC = C.jacobiSvd(ComputeFullU | ComputeFullV);\n    sol1 = svdC.solve(d);                                  // least square solution\n    Nc = svdC.matrixV().rightCols(C.cols() - svdC.rank()); // nullspace of C\n  }\n  else\n  {\n    sol1 = VectorXd::Zero(C.cols());\n    Nc = MatrixXd::Identity(C.cols(), C.cols());\n  }\n\n  // now check the equivalence:\n  // 1 - The solutions of Solve C [y;z] = d give solutions of A [x;y] = b\n  for(auto i = 0; i < Nc.cols(); ++i)\n  {\n    // one solution to the additional constraints\n    VectorXd yz = sol1 + Nc * VectorXd::Random(Nc.cols());\n    // split it over y and z\n    y.value(yz.head(y.totalSize()));\n    z.value(yz.tail(z.totalSize()));\n    // compute the corresponding x\n    subs.updateVariableValues();\n    // compute the residual for the current x and y\n    VectorXd xy(x.totalSize() + y.totalSize());\n    xy.head(x.totalSize()) = x.value();\n    xy.tail(y.totalSize()) = y.value();\n    double res = (A * xy - b).norm();\n    FAST_CHECK_LE(res, 1e-9);\n  }\n\n  // 2 - The solutions of A [x;y] = b are such that there we can find z for which\n  //   C [y;z] = d and x = E y + F z + g\n  MatrixXd M(C.rows() + F.rows(), z.totalSize());\n  M.topRows(C.rows()) = C.rightCols(z.totalSize());\n  M.bottomRows(F.rows()) = F;\n  JacobiSVD<MatrixXd> svdM;\n  if(z.totalSize() > 0)\n  {\n    svdM.compute(M, ComputeThinU | ComputeThinV);\n  }\n  for(auto i = 0; i < Na.cols(); ++i)\n  {\n    // one solution to the original system\n    VectorXd xy = sol0 + Na * VectorXd::Random(Na.cols());\n    // solve C2 z = d - C1 y and F z = x - E y - g\n    VectorXd u(C.rows() + F.rows());\n    u.head(C.rows()) = d - C.leftCols(y.totalSize()) * xy.tail(y.totalSize());\n    u.tail(F.rows()) = xy.head(x.totalSize()) - E * xy.tail(y.totalSize()) - g;\n    double res;\n    if(z.totalSize() > 0)\n    {\n      VectorXd s = svdM.solve(u);\n      res = (M * s - u).norm();\n    }\n    else\n    {\n      res = u.norm();\n    }\n    FAST_CHECK_LE(res, 1e-9);\n  }\n}\n\nTEST_CASE(\"Substitution construction\")\n{\n  using BLC = constraint::BasicLinearConstraint;\n  auto eq = constraint::Type::EQUAL;\n\n  VariablePtr x = Space(5).createVariable(\"x\");\n  {\n    MatrixXd A = randM(5, 5);\n    VectorXd b = VectorXd::Random(5);\n\n    auto c = std::shared_ptr<BLC>(new BLC(A, x, b, eq));\n    Substitution s(c, x);\n    FAST_CHECK_EQ(s.rank(), 5);\n    FAST_CHECK_EQ(typeid(*s.calculator()).hash_code(), typeid(GenericCalculator::Impl).hash_code());\n  }\n\n  {\n    MatrixXd A = MatrixXd::Identity(5, 5);\n    VectorXd b = VectorXd::Random(5);\n\n    auto c = std::shared_ptr<BLC>(new BLC(5, x, eq));\n    c->A(A, {tvm::internal::MatrixProperties::IDENTITY});\n    Substitution s(c, x);\n    FAST_CHECK_EQ(s.rank(), 5);\n    FAST_CHECK_EQ(typeid(*s.calculator()).hash_code(), typeid(DiagonalCalculator::Impl).hash_code());\n  }\n\n  {\n    MatrixXd A = randM(5, 5);\n    VectorXd b = VectorXd::Random(5);\n\n    auto c = std::shared_ptr<BLC>(new BLC(A, x, b, constraint::Type::LOWER_THAN));\n    CHECK_THROWS(Substitution(c, x));\n\n    VariablePtr y = Space(3).createVariable(\"y\");\n    CHECK_THROWS(Substitution(c, y));\n\n    auto c2 = std::shared_ptr<BLC>(new BLC(3, y, eq));\n    CHECK_THROWS(Substitution({c, c2}, x));\n\n    auto c3 = std::shared_ptr<BLC>(new BLC(5, y, eq));\n    CHECK_THROWS(Substitution(c3, y));\n  }\n}\n\nTEST_CASE(\"Substitution0\")\n{\n  using BLC = constraint::BasicLinearConstraint;\n  auto eq = constraint::Type::EQUAL;\n\n  {\n    // solving A x = b using substitutions\n    VariablePtr x = Space(5).createVariable(\"x\");\n    MatrixXd A = randM(5, 5);\n    VectorXd b = VectorXd::Random(5);\n    VectorXd x0 = A.colPivHouseholderQr().solve(b);\n\n    auto c = std::shared_ptr<BLC>(new BLC(A, x, b, eq));\n    Substitution s(c, x);\n    Substitutions subs;\n    subs.add(s);\n    subs.finalize();\n    FAST_CHECK_EQ(subs.variables().size(), 1);\n    FAST_CHECK_EQ(subs.variables().front(), x);\n    FAST_CHECK_EQ(subs.additionalVariables().size(), 0);\n    FAST_CHECK_EQ(subs.additionalConstraints().size(), 0);\n    FAST_CHECK_EQ(subs.variableSubstitutions().size(), 1);\n\n    auto f = subs.variableSubstitutions().front();\n    FAST_CHECK_EQ(f->variables().totalSize(), 0);\n    subs.updateSubstitutions();\n    FAST_CHECK_UNARY(f->b().isApprox(x0));\n    subs.updateVariableValues();\n    FAST_CHECK_UNARY(x->value().isApprox(x0));\n  }\n}\n\nTEST_CASE(\"Substitution1\")\n{\n  int m1 = 3;\n  int n1 = 4;\n  int r1 = 2;\n  int m2 = 3;\n  int n2 = 3;\n  int r2 = 3;\n  int m3 = 3;\n  int n3 = 6;\n  int r3 = 3;\n  int m4 = 4;\n  int n4 = 4;\n  int r4 = 4;\n  int m5 = 7;\n  int n5 = 8;\n  int r5 = 4;\n  int m6 = 3;\n  int n6 = 3;\n  int r6 = 3;\n  int l1 = 3;\n  int l2 = 7;\n  int l3 = 4;\n  int l4 = 4;\n\n  VariablePtr x1 = Space(n1).createVariable(\"x1\");\n  VariablePtr x2 = Space(n2).createVariable(\"x2\");\n  VariablePtr x3 = Space(n3).createVariable(\"x3\");\n  VariablePtr x4 = Space(n4).createVariable(\"x4\");\n  VariablePtr x5 = Space(n5).createVariable(\"x5\");\n  VariablePtr x6 = Space(n6).createVariable(\"x6\");\n  VariablePtr y1 = Space(l1).createVariable(\"y1\");\n  VariablePtr y2 = Space(l2).createVariable(\"y2\");\n  VariablePtr y3 = Space(l3).createVariable(\"y3\");\n  VariablePtr y4 = Space(l4).createVariable(\"y4\");\n\n  VectorXd b1 = VectorXd::Random(m1);\n  VectorXd b2 = VectorXd::Random(m2);\n  VectorXd b3 = VectorXd::Random(m3);\n  VectorXd b4 = VectorXd::Random(m4);\n  VectorXd b5 = VectorXd::Random(m5);\n  VectorXd b6 = VectorXd::Random(m6);\n\n  //                                             | x1 |\n  //                                             | x2 |\n  // | A11 A12 A13  0   0  A16 B11  0   0   0  | | x3 |   | b1 |\n  // |  0  A22  0  A24  0   0   0   0   0   0  | | x4 |   | b2 |\n  // |  0   0  A33  0  A35 A36 B31  0   0   0  | | x5 |   | b3 |\n  // |  0   0   0  A44 A45  0   0   0   0   0  | | x6 | = | b4 |\n  // |  0   0   0   0  A55  0   0  B52  0  B54 | | y1 |   | b5 |\n  // |  0   0   0   0   0  A66  0  B62 B63  0  | | y2 |   | b6 |\n  //                                             | y3 |\n  //                                             | y4 |\n\n  MatrixXd A11 = randM(m1, n1, r1);\n  MatrixXd A12 = randM(m1, n2);\n  MatrixXd A13 = randM(m1, n3);\n  MatrixXd A16 = randM(m1, n6);\n  MatrixXd B11 = randM(m1, l1);\n  MatrixXd A22 = randM(m2, n2, r2);\n  MatrixXd A24 = randM(m2, n4);\n  MatrixXd A33 = randM(m3, n3, r3);\n  MatrixXd A35 = randM(m3, n5);\n  MatrixXd A36 = randM(m3, n6);\n  MatrixXd B31 = randM(m3, l1);\n  MatrixXd A44 = randM(m4, n4, r4);\n  MatrixXd A45 = randM(m4, n5);\n  MatrixXd A55 = randM(m5, n5, r5);\n  MatrixXd B52 = randM(m5, l2);\n  MatrixXd B54 = randM(m5, l4);\n  MatrixXd A66 = randM(m6, n6, r6);\n  MatrixXd B62 = randM(m6, l2);\n  MatrixXd B63 = randM(m6, l3);\n\n  using BLC = constraint::BasicLinearConstraint;\n  auto eq = constraint::Type::EQUAL;\n  auto c1 = std::shared_ptr<BLC>(new BLC({A11, A12, A13, A16, B11}, {x1, x2, x3, x6, y1}, b1, eq));\n  auto c2 = std::shared_ptr<BLC>(new BLC({A22, A24}, {x2, x4}, b2, eq));\n  auto c3 = std::shared_ptr<BLC>(new BLC({A33, A35, A36, B31}, {x3, x5, x6, y1}, b3, eq));\n  auto c4 = std::shared_ptr<BLC>(new BLC({A44, A45}, {x4, x5}, b4, eq));\n  auto c5 = std::shared_ptr<BLC>(new BLC({A55, B52, B54}, {x5, y2, y4}, b5, eq));\n  auto c6 = std::shared_ptr<BLC>(new BLC({A66, B62, B63}, {x6, y2, y3}, b6, eq));\n\n  Substitution s1(c1, x1, r1);\n  Substitution s2(c2, x2, r2);\n  Substitution s3(c3, x3, r3);\n  Substitution s4(c4, x4, r4);\n  Substitution s5(c5, x5, r5);\n  Substitution s6(c6, x6, r6);\n\n  Substitutions subs;\n  subs.add(s1);\n  subs.add(s2);\n  subs.add(s3);\n  subs.add(s4);\n  subs.add(s5);\n  subs.add(s6);\n\n  subs.finalize();\n\n  checkEquivalence({c1, c2, c3, c4, c5, c6}, subs);\n}\n\nTEST_CASE(\"Substitution2\")\n{\n  int m1 = 3;\n  int n1 = 4;\n  int m2 = 3;\n  int n2 = 3;\n  int m3 = 3;\n  int n3 = 6;\n  int m4 = 5;\n  int n4 = 4;\n  int m5 = 7;\n  int n5 = 5;\n  int m6 = 3;\n  int n6 = 2;\n  int m7 = 6;\n  int n7 = 7;\n  int m8 = 4;\n  int n8 = 4;\n  int m9 = 4;\n  int n9 = 3;\n  int l1 = 3;\n  int l2 = 7;\n\n  VariablePtr x1 = Space(n1).createVariable(\"x1\");\n  VariablePtr x2 = Space(n2).createVariable(\"x2\");\n  VariablePtr x3 = Space(n3).createVariable(\"x3\");\n  VariablePtr x4 = Space(n4).createVariable(\"x4\");\n  VariablePtr x5 = Space(n5).createVariable(\"x5\");\n  VariablePtr x6 = Space(n6).createVariable(\"x6\");\n  VariablePtr x7 = Space(n7).createVariable(\"x7\");\n  VariablePtr x8 = Space(n8).createVariable(\"x8\");\n  VariablePtr x9 = Space(n9).createVariable(\"x9\");\n  VariablePtr y1 = Space(l1).createVariable(\"y1\");\n  VariablePtr y2 = Space(l2).createVariable(\"y2\");\n\n  //                                                 | x1 |\n  // |  0   0   0  A14  0   0  A17  0  A19 B11  0  | | x2 |   | b1 |\n  // |  0  A22  0   0   0   0   0   0   0  B21 B22 | | x3 |   | b2 |\n  // |  0   0   0   0   0  A36  0  A38  0  B31  0  | | x4 |   | b3 |\n  // |  0   0   0   0  A45  0   0   0   0  B41  0  | | x5 |   | b4 |\n  // |  0   0   0  A54  0   0  A57  0  A59  0   0  | | x6 | = | b5 |\n  // |  0   0   0   0   0  A66  0  A68  0  B61 B62 | | x7 |   | b6 |\n  // |  0   0  A73  0  A75  0   0   0   0   0  B72 | | x8 |   | b7 |\n  // | A81  0   0   0   0   0  A87  0   0  B81  0  | | x9 |   | b8 |\n  // |  0   0   0  A94  0   0   0   0   0   0  B92 | | y1 |   | b9 |\n  //                                                 | y2 |\n\n  MatrixXd A14 = randM(m1, n4);\n  MatrixXd A17 = randM(m1, n7);\n  MatrixXd A19 = randM(m1, n9);\n  MatrixXd B11 = randM(m1, l1);\n  MatrixXd A22 = randM(m2, n2);\n  MatrixXd B21 = randM(m2, l1);\n  MatrixXd B22 = randM(m2, l2);\n  MatrixXd A36 = randM(m3, n6);\n  MatrixXd A38 = randM(m3, n8);\n  MatrixXd B31 = randM(m3, l1);\n  MatrixXd A45 = randM(m4, n5);\n  MatrixXd B41 = randM(m4, l1);\n  MatrixXd A54 = randM(m5, n4);\n  MatrixXd A57 = randM(m5, n7);\n  MatrixXd A59 = randM(m5, n9);\n  MatrixXd A66 = randM(m6, n6);\n  MatrixXd A68 = randM(m6, n8);\n  MatrixXd B61 = randM(m6, l1);\n  MatrixXd B62 = randM(m6, l2);\n  MatrixXd A73 = randM(m7, n3);\n  MatrixXd A75 = randM(m7, n5);\n  MatrixXd B72 = randM(m7, l2);\n  MatrixXd A81 = randM(m8, n1);\n  MatrixXd A87 = randM(m8, n7);\n  MatrixXd B81 = randM(m8, l1);\n  MatrixXd A94 = randM(m9, n4);\n  MatrixXd B92 = randM(m9, l2);\n  VectorXd b1 = VectorXd::Random(m1);\n  VectorXd b2 = VectorXd::Random(m2);\n  VectorXd b3 = VectorXd::Random(m3);\n  VectorXd b4 = VectorXd::Random(m4);\n  VectorXd b5 = VectorXd::Random(m5);\n  VectorXd b6 = VectorXd::Random(m6);\n  VectorXd b7 = VectorXd::Random(m7);\n  VectorXd b8 = VectorXd::Random(m8);\n  VectorXd b9 = VectorXd::Random(m9);\n\n  using BLC = constraint::BasicLinearConstraint;\n  auto eq = constraint::Type::EQUAL;\n  auto c1 = std::shared_ptr<BLC>(new BLC({A14, A17, A19, B11}, {x4, x7, x9, y1}, b1, eq));\n  auto c2 = std::shared_ptr<BLC>(new BLC({A22, B21, B22}, {x2, y1, y2}, b2, eq));\n  auto c3 = std::shared_ptr<BLC>(new BLC({A36, A38, B31}, {x6, x8, y1}, b3, eq));\n  auto c4 = std::shared_ptr<BLC>(new BLC({A45, B41}, {x5, y1}, b4, eq));\n  auto c5 = std::shared_ptr<BLC>(new BLC({A54, A57, A59}, {x4, x7, x9}, b5, eq));\n  auto c6 = std::shared_ptr<BLC>(new BLC({A66, A68, B62, B61}, {x6, x8, y2, y1}, b6, eq));\n  auto c7 = std::shared_ptr<BLC>(new BLC({A73, A75, B72}, {x3, x5, y2}, b7, eq));\n  auto c8 = std::shared_ptr<BLC>(new BLC({A81, A87, B81}, {x1, x7, y1}, b8, eq));\n  auto c9 = std::shared_ptr<BLC>(new BLC({A94, B92}, {x4, y2}, b9, eq));\n\n  Substitution s1(c1, x9);\n  Substitution s2(c2, x2);\n  Substitution s3(std::vector<LinearConstraintPtr>{c3, c6}, std::vector<VariablePtr>{x6, x8});\n  Substitution s4(c4, x5);\n  Substitution s5(c5, x7);\n  // no s6: c3 and c6 are merged\n  Substitution s7(c7, x3);\n  Substitution s8(c8, x1);\n  Substitution s9(c9, x4);\n\n  Substitutions subs;\n  subs.add(s1);\n  subs.add(s2);\n  subs.add(s3);\n  subs.add(s4);\n  subs.add(s5);\n  subs.add(s7);\n  subs.add(s8);\n  subs.add(s9);\n\n  subs.finalize();\n  checkEquivalence({c1, c2, c3, c4, c5, c6, c7, c8, c9}, subs);\n}\n\n/** Generate a random number r, min <= r < max*/\nint randI(int min, int max)\n{\n  assert(min < max);\n  return (rand() % (max - min)) + min;\n}\n\n/** Return true with a probability p*/\nbool randP(double p)\n{\n  assert(0 <= p && p <= 1);\n  return static_cast<double>(rand()) / RAND_MAX < p;\n}\n\n/** Create a random system A [x;y] = b*/\nvoid randomSubstitutions()\n{\n  using BLC = constraint::BasicLinearConstraint;\n  auto eq = constraint::Type::EQUAL;\n\n  int nxmin = 4;\n  int nxmax = 16;\n  int nymin = 0;\n  int nymax = 9;\n  int nmin = 2;\n  int nmax = 16;\n  double nonFullRankP = 0.33;\n  int nx = randI(nxmin, nxmax); // number of x variables\n  int ny = randI(nymin, nymax); // number of y variables\n  double px = 0.4;              // probability to have a non-zero off-diagonal block in the 'x part' of A\n  double py = 0.3;              // probability to have a non-zero block in the 'y part' of B\n\n  std::vector<VariablePtr> x;\n  std::vector<VariablePtr> y;\n  std::vector<int> m;\n  std::vector<int> n;\n  std::vector<int> r;\n  std::vector<int> l;\n  std::vector<std::shared_ptr<BLC>> cstr;\n\n  bool fullRankSystem = false;\n\n  // We restart from scratch when we do not get a system that is full rank\n  while(!fullRankSystem)\n  {\n    int ma = 0;\n    int na = 0;\n    x.clear();\n    y.clear();\n    m.clear();\n    n.clear();\n    r.clear();\n    l.clear();\n    cstr.clear();\n    for(int i = 0; i < nx; ++i)\n    {\n      std::stringstream ss;\n      ss << \"x\" << i;\n      int ni = randI(nmin, nmax);\n      int mi = 1 + randI(1, ni);\n      n.push_back(ni);\n      m.push_back(mi);\n      x.push_back(Space(ni).createVariable(ss.str()));\n      if(randP(nonFullRankP))\n      {\n        r.push_back(randI(mi / 2, mi + 1));\n      }\n      else\n      {\n        r.push_back(mi);\n      }\n      ma += mi;\n      na += ni;\n    }\n    for(int i = 0; i < ny; ++i)\n    {\n      std::stringstream ss;\n      ss << \"y\" << i;\n      int ni = randI(nmin, nmax);\n      l.push_back(ni);\n      y.push_back(Space(ni).createVariable(ss.str()));\n      na += l.back();\n    }\n\n    for(size_t i = 0; i < static_cast<size_t>(nx); ++i)\n    {\n      std::vector<VariablePtr> v;\n      std::vector<MatrixXd> M;\n      std::vector<MatrixConstRef> Mr;\n      for(size_t j = 0; j < static_cast<size_t>(nx); ++j)\n      {\n        if(i == j)\n        {\n          M.push_back(randM(m[i], n[j], r[i]));\n          v.push_back(x[j]);\n        }\n        else\n        {\n          if(randP(px))\n          {\n            M.push_back(randM(m[i], n[j]));\n            v.push_back(x[j]);\n          }\n        }\n      }\n      for(size_t j = 0; j < static_cast<size_t>(ny); ++j)\n      {\n        if(randP(py))\n        {\n          M.push_back(randM(m[i], l[j]));\n          v.push_back(y[j]);\n        }\n      }\n      for(const auto & Mi : M)\n      {\n        Mr.push_back(Mi);\n      }\n      VectorXd b = VectorXd::Random(m[i]);\n      auto c = std::shared_ptr<BLC>(new BLC(Mr, v, b, eq));\n      cstr.push_back(c);\n    }\n    // check if the system is feasible\n    MatrixXd A = MatrixXd::Zero(ma, na);\n    int ms = 0;\n    for(const auto & c : cstr)\n    {\n      int ns = 0;\n      int mi = c->size();\n      for(const auto & xi : x)\n      {\n        int ni = xi->size();\n        if(c->variables().contains(*xi))\n        {\n          A.block(ms, ns, mi, ni) = c->jacobian(*xi);\n        }\n        ns += ni;\n      }\n      for(const auto & yi : y)\n      {\n        int ni = yi->size();\n        if(c->variables().contains(*yi))\n        {\n          A.block(ms, ns, mi, ni) = c->jacobian(*yi);\n        }\n        ns += ni;\n      }\n      ms += mi;\n    }\n    auto svd = A.jacobiSvd();\n    fullRankSystem = svd.rank() == A.rows();\n  }\n\n  Substitutions subs;\n  for(size_t i = 0; i < cstr.size(); ++i)\n  {\n    Substitution s(cstr[i], x[i], r[i]);\n    subs.add(s);\n  }\n  subs.finalize();\n  checkEquivalence(cstr, subs);\n}\n\nTEST_CASE(\"Random substitutions\")\n{\n  // In some very rare instance, this test can fail because of rank issues\n  // during the qr decomposition of GenericCalculator. This is because of the\n  // heuristic taken to get the rank of a group of constraints. This is not to\n  // be regarded as an issue.\n  for(int i = 0; i < 10; ++i)\n  {\n    randomSubstitutions();\n  }\n}\n\nTEST_CASE(\"Substitution with subvariables\")\n{\n  VariablePtr x = Space(8).createVariable(\"x\");\n  VariablePtr x1 = x->subvariable(3, \"x1\", 0);\n  VariablePtr x2 = x->subvariable(5, \"x2\", 3);\n\n  MatrixXd M = randM(8, 8);\n  VectorXd r = VectorXd::Random(8);\n\n  auto A1 = M.topRows(5);\n  auto A2 = M.bottomRows(3);\n  auto b1 = r.head(5);\n  auto b2 = r.tail(3);\n\n  using BLC = constraint::BasicLinearConstraint;\n  auto eq = constraint::Type::EQUAL;\n  VectorXd x0 = M.colPivHouseholderQr().solve(r);\n\n  auto c = std::shared_ptr<BLC>(new BLC(A1, x, b1, eq));\n  Substitution s(c, x2);\n  Substitutions subs;\n  subs.add(s);\n  subs.finalize();\n  FAST_CHECK_EQ(subs.variables().size(), 1);\n  FAST_CHECK_EQ(*subs.variables().front(), *x2);\n  FAST_CHECK_EQ(subs.additionalVariables().size(), 0);\n  FAST_CHECK_EQ(subs.otherVariables().size(), 1);\n  FAST_CHECK_EQ(*subs.otherVariables().front(), *x1);\n  FAST_CHECK_EQ(subs.additionalConstraints().size(), 0);\n  FAST_CHECK_EQ(subs.variableSubstitutions().size(), 1);\n\n  auto f = subs.variableSubstitutions().front();\n  FAST_CHECK_EQ(f->variables().numberOfVariables(), 1);\n  FAST_CHECK_EQ(*f->variables()[0], *x1);\n  subs.updateSubstitutions();\n\n  MatrixXd C = A2.leftCols(3) + A2.rightCols(5) * f->jacobian(*x1);\n  VectorXd d = b2 - A2.rightCols(5) * f->b();\n  VectorXd y = C.colPivHouseholderQr().solve(d);\n  x1 << y;\n\n  subs.updateVariableValues();\n  FAST_CHECK_UNARY(x->value().isApprox(x0));\n}\n", "meta": {"hexsha": "1005b4b5f38e093ca986c85458c612cb7e27735d", "size": 27984, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/SubstitutionTest.cpp", "max_stars_repo_name": "BenjaminNavarro/tvm", "max_stars_repo_head_hexsha": "9b273feb05575a39e4b6fab45e17c4d090c2d292", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/SubstitutionTest.cpp", "max_issues_repo_name": "BenjaminNavarro/tvm", "max_issues_repo_head_hexsha": "9b273feb05575a39e4b6fab45e17c4d090c2d292", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/SubstitutionTest.cpp", "max_forks_repo_name": "BenjaminNavarro/tvm", "max_forks_repo_head_hexsha": "9b273feb05575a39e4b6fab45e17c4d090c2d292", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-29T12:05:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-29T12:05:02.000Z", "avg_line_length": 30.7178924259, "max_line_length": 120, "alphanum_fraction": 0.5814036592, "num_tokens": 9845, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.45026771517680136}}
{"text": "/**\n * @file tests/kfn_test.cpp\n *\n * Tests for KFN (k-furthest-neighbors).\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#include <mlpack/core.hpp>\n#include <mlpack/methods/neighbor_search/neighbor_search.hpp>\n#include <mlpack/core/tree/cover_tree.hpp>\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n\nusing namespace mlpack;\nusing namespace mlpack::neighbor;\nusing namespace mlpack::tree;\nusing namespace mlpack::metric;\nusing namespace mlpack::bound;\n\nBOOST_AUTO_TEST_SUITE(KFNTest);\n\n/**\n * Simple furthest-neighbors test with small, synthetic dataset.  This is an\n * exhaustive test, which checks that each method for performing the calculation\n * (dual-tree, single-tree, naive) produces the correct results.  An\n * eleven-point dataset and the ten furthest neighbors are taken.  The dataset\n * is in one dimension for simplicity -- the correct functionality of distance\n * functions is not tested here.\n */\nBOOST_AUTO_TEST_CASE(ExhaustiveSyntheticTest)\n{\n  // Set up our data.\n  arma::mat data(1, 11);\n  data[0] = 0.05; // Row addressing is unnecessary (they are all 0).\n  data[1] = 0.35;\n  data[2] = 0.15;\n  data[3] = 1.25;\n  data[4] = 5.05;\n  data[5] = -0.22;\n  data[6] = -2.00;\n  data[7] = -1.30;\n  data[8] = 0.45;\n  data[9] = 0.90;\n  data[10] = 1.00;\n\n  typedef BinarySpaceTree<EuclideanDistance,\n      NeighborSearchStat<FurthestNeighborSort>, arma::mat> TreeType;\n\n  // We will loop through three times, one for each method of performing the\n  // calculation.  We'll always use 10 neighbors, so set that parameter.\n  std::vector<size_t> oldFromNew;\n  std::vector<size_t> newFromOld;\n  TreeType tree(data, oldFromNew, newFromOld, 1);\n  KFN kfn(std::move(tree));\n\n  for (int i = 0; i < 3; ++i)\n  {\n    switch (i)\n    {\n      case 0: // Use the dual-tree method.\n        kfn.SearchMode() = DUAL_TREE_MODE;\n        break;\n      case 1: // Use the single-tree method.\n        kfn.SearchMode() = SINGLE_TREE_MODE;\n        break;\n      case 2: // Use the naive method.\n        kfn.SearchMode() = NAIVE_MODE;\n        break;\n    }\n\n    // Now perform the actual calculation.\n    arma::Mat<size_t> neighbors;\n    arma::mat distances;\n    kfn.Search(10, neighbors, distances);\n\n    // Now the exhaustive check for correctness.  This will be long.  We must\n    // also remember that the distances returned are squared distances.  As a\n    // result, distance comparisons are written out as (distance * distance) for\n    // readability.\n\n    // Neighbors of point 0.\n    BOOST_REQUIRE_EQUAL(neighbors(9, newFromOld[0]), newFromOld[2]);\n    BOOST_REQUIRE_CLOSE(distances(9, newFromOld[0]), 0.10, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(8, newFromOld[0]), newFromOld[5]);\n    BOOST_REQUIRE_CLOSE(distances(8, newFromOld[0]), 0.27, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(7, newFromOld[0]), newFromOld[1]);\n    BOOST_REQUIRE_CLOSE(distances(7, newFromOld[0]), 0.30, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(6, newFromOld[0]), newFromOld[8]);\n    BOOST_REQUIRE_CLOSE(distances(6, newFromOld[0]), 0.40, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(5, newFromOld[0]), newFromOld[9]);\n    BOOST_REQUIRE_CLOSE(distances(5, newFromOld[0]), 0.85, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(4, newFromOld[0]), newFromOld[10]);\n    BOOST_REQUIRE_CLOSE(distances(4, newFromOld[0]), 0.95, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(3, newFromOld[0]), newFromOld[3]);\n    BOOST_REQUIRE_CLOSE(distances(3, newFromOld[0]), 1.20, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(2, newFromOld[0]), newFromOld[7]);\n    BOOST_REQUIRE_CLOSE(distances(2, newFromOld[0]), 1.35, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(1, newFromOld[0]), newFromOld[6]);\n    BOOST_REQUIRE_CLOSE(distances(1, newFromOld[0]), 2.05, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(0, newFromOld[0]), newFromOld[4]);\n    BOOST_REQUIRE_CLOSE(distances(0, newFromOld[0]), 5.00, 1e-5);\n\n    // Neighbors of point 1.\n    BOOST_REQUIRE_EQUAL(neighbors(9, newFromOld[1]), newFromOld[8]);\n    BOOST_REQUIRE_CLOSE(distances(9, newFromOld[1]), 0.10, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(8, newFromOld[1]), newFromOld[2]);\n    BOOST_REQUIRE_CLOSE(distances(8, newFromOld[1]), 0.20, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(7, newFromOld[1]), newFromOld[0]);\n    BOOST_REQUIRE_CLOSE(distances(7, newFromOld[1]), 0.30, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(6, newFromOld[1]), newFromOld[9]);\n    BOOST_REQUIRE_CLOSE(distances(6, newFromOld[1]), 0.55, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(5, newFromOld[1]), newFromOld[5]);\n    BOOST_REQUIRE_CLOSE(distances(5, newFromOld[1]), 0.57, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(4, newFromOld[1]), newFromOld[10]);\n    BOOST_REQUIRE_CLOSE(distances(4, newFromOld[1]), 0.65, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(3, newFromOld[1]), newFromOld[3]);\n    BOOST_REQUIRE_CLOSE(distances(3, newFromOld[1]), 0.90, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(2, newFromOld[1]), newFromOld[7]);\n    BOOST_REQUIRE_CLOSE(distances(2, newFromOld[1]), 1.65, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(1, newFromOld[1]), newFromOld[6]);\n    BOOST_REQUIRE_CLOSE(distances(1, newFromOld[1]), 2.35, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(0, newFromOld[1]), newFromOld[4]);\n    BOOST_REQUIRE_CLOSE(distances(0, newFromOld[1]), 4.70, 1e-5);\n\n    // Neighbors of point 2.\n    BOOST_REQUIRE_EQUAL(neighbors(9, newFromOld[2]), newFromOld[0]);\n    BOOST_REQUIRE_CLOSE(distances(9, newFromOld[2]), 0.10, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(8, newFromOld[2]), newFromOld[1]);\n    BOOST_REQUIRE_CLOSE(distances(8, newFromOld[2]), 0.20, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(7, newFromOld[2]), newFromOld[8]);\n    BOOST_REQUIRE_CLOSE(distances(7, newFromOld[2]), 0.30, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(6, newFromOld[2]), newFromOld[5]);\n    BOOST_REQUIRE_CLOSE(distances(6, newFromOld[2]), 0.37, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(5, newFromOld[2]), newFromOld[9]);\n    BOOST_REQUIRE_CLOSE(distances(5, newFromOld[2]), 0.75, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(4, newFromOld[2]), newFromOld[10]);\n    BOOST_REQUIRE_CLOSE(distances(4, newFromOld[2]), 0.85, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(3, newFromOld[2]), newFromOld[3]);\n    BOOST_REQUIRE_CLOSE(distances(3, newFromOld[2]), 1.10, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(2, newFromOld[2]), newFromOld[7]);\n    BOOST_REQUIRE_CLOSE(distances(2, newFromOld[2]), 1.45, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(1, newFromOld[2]), newFromOld[6]);\n    BOOST_REQUIRE_CLOSE(distances(1, newFromOld[2]), 2.15, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(0, newFromOld[2]), newFromOld[4]);\n    BOOST_REQUIRE_CLOSE(distances(0, newFromOld[2]), 4.90, 1e-5);\n\n    // Neighbors of point 3.\n    BOOST_REQUIRE_EQUAL(neighbors(9, newFromOld[3]), newFromOld[10]);\n    BOOST_REQUIRE_CLOSE(distances(9, newFromOld[3]), 0.25, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(8, newFromOld[3]), newFromOld[9]);\n    BOOST_REQUIRE_CLOSE(distances(8, newFromOld[3]), 0.35, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(7, newFromOld[3]), newFromOld[8]);\n    BOOST_REQUIRE_CLOSE(distances(7, newFromOld[3]), 0.80, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(6, newFromOld[3]), newFromOld[1]);\n    BOOST_REQUIRE_CLOSE(distances(6, newFromOld[3]), 0.90, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(5, newFromOld[3]), newFromOld[2]);\n    BOOST_REQUIRE_CLOSE(distances(5, newFromOld[3]), 1.10, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(4, newFromOld[3]), newFromOld[0]);\n    BOOST_REQUIRE_CLOSE(distances(4, newFromOld[3]), 1.20, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(3, newFromOld[3]), newFromOld[5]);\n    BOOST_REQUIRE_CLOSE(distances(3, newFromOld[3]), 1.47, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(2, newFromOld[3]), newFromOld[7]);\n    BOOST_REQUIRE_CLOSE(distances(2, newFromOld[3]), 2.55, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(1, newFromOld[3]), newFromOld[6]);\n    BOOST_REQUIRE_CLOSE(distances(1, newFromOld[3]), 3.25, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(0, newFromOld[3]), newFromOld[4]);\n    BOOST_REQUIRE_CLOSE(distances(0, newFromOld[3]), 3.80, 1e-5);\n\n    // Neighbors of point 4.\n    BOOST_REQUIRE_EQUAL(neighbors(9, newFromOld[4]), newFromOld[3]);\n    BOOST_REQUIRE_CLOSE(distances(9, newFromOld[4]), 3.80, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(8, newFromOld[4]), newFromOld[10]);\n    BOOST_REQUIRE_CLOSE(distances(8, newFromOld[4]), 4.05, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(7, newFromOld[4]), newFromOld[9]);\n    BOOST_REQUIRE_CLOSE(distances(7, newFromOld[4]), 4.15, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(6, newFromOld[4]), newFromOld[8]);\n    BOOST_REQUIRE_CLOSE(distances(6, newFromOld[4]), 4.60, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(5, newFromOld[4]), newFromOld[1]);\n    BOOST_REQUIRE_CLOSE(distances(5, newFromOld[4]), 4.70, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(4, newFromOld[4]), newFromOld[2]);\n    BOOST_REQUIRE_CLOSE(distances(4, newFromOld[4]), 4.90, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(3, newFromOld[4]), newFromOld[0]);\n    BOOST_REQUIRE_CLOSE(distances(3, newFromOld[4]), 5.00, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(2, newFromOld[4]), newFromOld[5]);\n    BOOST_REQUIRE_CLOSE(distances(2, newFromOld[4]), 5.27, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(1, newFromOld[4]), newFromOld[7]);\n    BOOST_REQUIRE_CLOSE(distances(1, newFromOld[4]), 6.35, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(0, newFromOld[4]), newFromOld[6]);\n    BOOST_REQUIRE_CLOSE(distances(0, newFromOld[4]), 7.05, 1e-5);\n\n    // Neighbors of point 5.\n    BOOST_REQUIRE_EQUAL(neighbors(9, newFromOld[5]), newFromOld[0]);\n    BOOST_REQUIRE_CLOSE(distances(9, newFromOld[5]), 0.27, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(8, newFromOld[5]), newFromOld[2]);\n    BOOST_REQUIRE_CLOSE(distances(8, newFromOld[5]), 0.37, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(7, newFromOld[5]), newFromOld[1]);\n    BOOST_REQUIRE_CLOSE(distances(7, newFromOld[5]), 0.57, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(6, newFromOld[5]), newFromOld[8]);\n    BOOST_REQUIRE_CLOSE(distances(6, newFromOld[5]), 0.67, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(5, newFromOld[5]), newFromOld[7]);\n    BOOST_REQUIRE_CLOSE(distances(5, newFromOld[5]), 1.08, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(4, newFromOld[5]), newFromOld[9]);\n    BOOST_REQUIRE_CLOSE(distances(4, newFromOld[5]), 1.12, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(3, newFromOld[5]), newFromOld[10]);\n    BOOST_REQUIRE_CLOSE(distances(3, newFromOld[5]), 1.22, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(2, newFromOld[5]), newFromOld[3]);\n    BOOST_REQUIRE_CLOSE(distances(2, newFromOld[5]), 1.47, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(1, newFromOld[5]), newFromOld[6]);\n    BOOST_REQUIRE_CLOSE(distances(1, newFromOld[5]), 1.78, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(0, newFromOld[5]), newFromOld[4]);\n    BOOST_REQUIRE_CLOSE(distances(0, newFromOld[5]), 5.27, 1e-5);\n\n    // Neighbors of point 6.\n    BOOST_REQUIRE_EQUAL(neighbors(9, newFromOld[6]), newFromOld[7]);\n    BOOST_REQUIRE_CLOSE(distances(9, newFromOld[6]), 0.70, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(8, newFromOld[6]), newFromOld[5]);\n    BOOST_REQUIRE_CLOSE(distances(8, newFromOld[6]), 1.78, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(7, newFromOld[6]), newFromOld[0]);\n    BOOST_REQUIRE_CLOSE(distances(7, newFromOld[6]), 2.05, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(6, newFromOld[6]), newFromOld[2]);\n    BOOST_REQUIRE_CLOSE(distances(6, newFromOld[6]), 2.15, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(5, newFromOld[6]), newFromOld[1]);\n    BOOST_REQUIRE_CLOSE(distances(5, newFromOld[6]), 2.35, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(4, newFromOld[6]), newFromOld[8]);\n    BOOST_REQUIRE_CLOSE(distances(4, newFromOld[6]), 2.45, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(3, newFromOld[6]), newFromOld[9]);\n    BOOST_REQUIRE_CLOSE(distances(3, newFromOld[6]), 2.90, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(2, newFromOld[6]), newFromOld[10]);\n    BOOST_REQUIRE_CLOSE(distances(2, newFromOld[6]), 3.00, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(1, newFromOld[6]), newFromOld[3]);\n    BOOST_REQUIRE_CLOSE(distances(1, newFromOld[6]), 3.25, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(0, newFromOld[6]), newFromOld[4]);\n    BOOST_REQUIRE_CLOSE(distances(0, newFromOld[6]), 7.05, 1e-5);\n\n    // Neighbors of point 7.\n    BOOST_REQUIRE_EQUAL(neighbors(9, newFromOld[7]), newFromOld[6]);\n    BOOST_REQUIRE_CLOSE(distances(9, newFromOld[7]), 0.70, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(8, newFromOld[7]), newFromOld[5]);\n    BOOST_REQUIRE_CLOSE(distances(8, newFromOld[7]), 1.08, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(7, newFromOld[7]), newFromOld[0]);\n    BOOST_REQUIRE_CLOSE(distances(7, newFromOld[7]), 1.35, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(6, newFromOld[7]), newFromOld[2]);\n    BOOST_REQUIRE_CLOSE(distances(6, newFromOld[7]), 1.45, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(5, newFromOld[7]), newFromOld[1]);\n    BOOST_REQUIRE_CLOSE(distances(5, newFromOld[7]), 1.65, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(4, newFromOld[7]), newFromOld[8]);\n    BOOST_REQUIRE_CLOSE(distances(4, newFromOld[7]), 1.75, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(3, newFromOld[7]), newFromOld[9]);\n    BOOST_REQUIRE_CLOSE(distances(3, newFromOld[7]), 2.20, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(2, newFromOld[7]), newFromOld[10]);\n    BOOST_REQUIRE_CLOSE(distances(2, newFromOld[7]), 2.30, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(1, newFromOld[7]), newFromOld[3]);\n    BOOST_REQUIRE_CLOSE(distances(1, newFromOld[7]), 2.55, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(0, newFromOld[7]), newFromOld[4]);\n    BOOST_REQUIRE_CLOSE(distances(0, newFromOld[7]), 6.35, 1e-5);\n\n    // Neighbors of point 8.\n    BOOST_REQUIRE_EQUAL(neighbors(9, newFromOld[8]), newFromOld[1]);\n    BOOST_REQUIRE_CLOSE(distances(9, newFromOld[8]), 0.10, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(8, newFromOld[8]), newFromOld[2]);\n    BOOST_REQUIRE_CLOSE(distances(8, newFromOld[8]), 0.30, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(7, newFromOld[8]), newFromOld[0]);\n    BOOST_REQUIRE_CLOSE(distances(7, newFromOld[8]), 0.40, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(6, newFromOld[8]), newFromOld[9]);\n    BOOST_REQUIRE_CLOSE(distances(6, newFromOld[8]), 0.45, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(5, newFromOld[8]), newFromOld[10]);\n    BOOST_REQUIRE_CLOSE(distances(5, newFromOld[8]), 0.55, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(4, newFromOld[8]), newFromOld[5]);\n    BOOST_REQUIRE_CLOSE(distances(4, newFromOld[8]), 0.67, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(3, newFromOld[8]), newFromOld[3]);\n    BOOST_REQUIRE_CLOSE(distances(3, newFromOld[8]), 0.80, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(2, newFromOld[8]), newFromOld[7]);\n    BOOST_REQUIRE_CLOSE(distances(2, newFromOld[8]), 1.75, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(1, newFromOld[8]), newFromOld[6]);\n    BOOST_REQUIRE_CLOSE(distances(1, newFromOld[8]), 2.45, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(0, newFromOld[8]), newFromOld[4]);\n    BOOST_REQUIRE_CLOSE(distances(0, newFromOld[8]), 4.60, 1e-5);\n\n    // Neighbors of point 9.\n    BOOST_REQUIRE_EQUAL(neighbors(9, newFromOld[9]), newFromOld[10]);\n    BOOST_REQUIRE_CLOSE(distances(9, newFromOld[9]), 0.10, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(8, newFromOld[9]), newFromOld[3]);\n    BOOST_REQUIRE_CLOSE(distances(8, newFromOld[9]), 0.35, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(7, newFromOld[9]), newFromOld[8]);\n    BOOST_REQUIRE_CLOSE(distances(7, newFromOld[9]), 0.45, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(6, newFromOld[9]), newFromOld[1]);\n    BOOST_REQUIRE_CLOSE(distances(6, newFromOld[9]), 0.55, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(5, newFromOld[9]), newFromOld[2]);\n    BOOST_REQUIRE_CLOSE(distances(5, newFromOld[9]), 0.75, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(4, newFromOld[9]), newFromOld[0]);\n    BOOST_REQUIRE_CLOSE(distances(4, newFromOld[9]), 0.85, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(3, newFromOld[9]), newFromOld[5]);\n    BOOST_REQUIRE_CLOSE(distances(3, newFromOld[9]), 1.12, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(2, newFromOld[9]), newFromOld[7]);\n    BOOST_REQUIRE_CLOSE(distances(2, newFromOld[9]), 2.20, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(1, newFromOld[9]), newFromOld[6]);\n    BOOST_REQUIRE_CLOSE(distances(1, newFromOld[9]), 2.90, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(0, newFromOld[9]), newFromOld[4]);\n    BOOST_REQUIRE_CLOSE(distances(0, newFromOld[9]), 4.15, 1e-5);\n\n    // Neighbors of point 10.\n    BOOST_REQUIRE_EQUAL(neighbors(9, newFromOld[10]), newFromOld[9]);\n    BOOST_REQUIRE_CLOSE(distances(9, newFromOld[10]), 0.10, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(8, newFromOld[10]), newFromOld[3]);\n    BOOST_REQUIRE_CLOSE(distances(8, newFromOld[10]), 0.25, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(7, newFromOld[10]), newFromOld[8]);\n    BOOST_REQUIRE_CLOSE(distances(7, newFromOld[10]), 0.55, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(6, newFromOld[10]), newFromOld[1]);\n    BOOST_REQUIRE_CLOSE(distances(6, newFromOld[10]), 0.65, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(5, newFromOld[10]), newFromOld[2]);\n    BOOST_REQUIRE_CLOSE(distances(5, newFromOld[10]), 0.85, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(4, newFromOld[10]), newFromOld[0]);\n    BOOST_REQUIRE_CLOSE(distances(4, newFromOld[10]), 0.95, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(3, newFromOld[10]), newFromOld[5]);\n    BOOST_REQUIRE_CLOSE(distances(3, newFromOld[10]), 1.22, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(2, newFromOld[10]), newFromOld[7]);\n    BOOST_REQUIRE_CLOSE(distances(2, newFromOld[10]), 2.30, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(1, newFromOld[10]), newFromOld[6]);\n    BOOST_REQUIRE_CLOSE(distances(1, newFromOld[10]), 3.00, 1e-5);\n    BOOST_REQUIRE_EQUAL(neighbors(0, newFromOld[10]), newFromOld[4]);\n    BOOST_REQUIRE_CLOSE(distances(0, newFromOld[10]), 4.05, 1e-5);\n  }\n}\n\n/**\n * Test the dual-tree furthest-neighbors method with the naive method.  This\n * uses both a query and reference dataset.\n *\n * Errors are produced if the results are not identical.\n */\nBOOST_AUTO_TEST_CASE(DualTreeVsNaive1)\n{\n  arma::mat dataset;\n\n  // Hard-coded filename: bad?\n  if (!data::Load(\"test_data_3_1000.csv\", dataset))\n    BOOST_FAIL(\"Cannot load test dataset test_data_3_1000.csv!\");\n\n  KFN kfn(dataset);\n\n  KFN naive(dataset, NAIVE_MODE);\n\n  arma::Mat<size_t> neighborsTree;\n  arma::mat distancesTree;\n  kfn.Search(dataset, 15, neighborsTree, distancesTree);\n\n  arma::Mat<size_t> neighborsNaive;\n  arma::mat distancesNaive;\n  naive.Search(dataset, 15, neighborsNaive, distancesNaive);\n\n  for (size_t i = 0; i < neighborsTree.n_elem; ++i)\n  {\n    BOOST_REQUIRE(neighborsTree[i] == neighborsNaive[i]);\n    BOOST_REQUIRE_CLOSE(distancesTree[i], distancesNaive[i], 1e-5);\n  }\n}\n\n/**\n * Test the dual-tree furthest-neighbors method with the naive method.  This\n * uses only a reference dataset.\n *\n * Errors are produced if the results are not identical.\n */\nBOOST_AUTO_TEST_CASE(DualTreeVsNaive2)\n{\n  arma::mat dataset;\n\n  // Hard-coded filename: bad?\n  // Code duplication: also bad!\n  if (!data::Load(\"test_data_3_1000.csv\", dataset))\n    BOOST_FAIL(\"Cannot load test dataset test_data_3_1000.csv!\");\n\n  KFN kfn(dataset);\n\n  KFN naive(dataset, NAIVE_MODE);\n\n  arma::Mat<size_t> neighborsTree;\n  arma::mat distancesTree;\n  kfn.Search(15, neighborsTree, distancesTree);\n\n  arma::Mat<size_t> neighborsNaive;\n  arma::mat distancesNaive;\n  naive.Search(15, neighborsNaive, distancesNaive);\n\n  for (size_t i = 0; i < neighborsTree.n_elem; ++i)\n  {\n    BOOST_REQUIRE_EQUAL(neighborsTree[i], neighborsNaive[i]);\n    BOOST_REQUIRE_CLOSE(distancesTree[i], distancesNaive[i], 1e-5);\n  }\n}\n\n/**\n * Test the single-tree furthest-neighbors method with the naive method.  This\n * uses only a reference dataset.\n *\n * Errors are produced if the results are not identical.\n */\nBOOST_AUTO_TEST_CASE(SingleTreeVsNaive)\n{\n  arma::mat dataset;\n\n  // Hard-coded filename: bad!\n  // Code duplication: also bad!\n  if (!data::Load(\"test_data_3_1000.csv\", dataset))\n    BOOST_FAIL(\"Cannot load test dataset test_data_3_1000.csv!\");\n\n  KFN kfn(dataset, SINGLE_TREE_MODE);\n\n  KFN naive(dataset, NAIVE_MODE);\n\n  arma::Mat<size_t> neighborsTree;\n  arma::mat distancesTree;\n  kfn.Search(15, neighborsTree, distancesTree);\n\n  arma::Mat<size_t> neighborsNaive;\n  arma::mat distancesNaive;\n  naive.Search(15, neighborsNaive, distancesNaive);\n\n  for (size_t i = 0; i < neighborsTree.n_elem; ++i)\n  {\n    BOOST_REQUIRE_EQUAL(neighborsTree[i], neighborsNaive[i]);\n    BOOST_REQUIRE_CLOSE(distancesTree[i], distancesNaive[i], 1e-5);\n  }\n}\n\n/**\n * Test the cover tree single-tree furthest-neighbors method against the naive\n * method.  This uses only a random reference dataset.\n *\n * Errors are produced if the results are not identical.\n */\nBOOST_AUTO_TEST_CASE(SingleCoverTreeTest)\n{\n  arma::mat data;\n  data.randu(75, 1000); // 75 dimensional, 1000 points.\n\n  // This depends on the cover tree not mapping points.\n  CoverTree<LMetric<2>, NeighborSearchStat<FurthestNeighborSort>, arma::mat,\n      FirstPointIsRoot> tree(data);\n\n  NeighborSearch<FurthestNeighborSort, LMetric<2>, arma::mat, StandardCoverTree>\n      coverTreeSearch(std::move(tree), SINGLE_TREE_MODE);\n\n  KFN naive(data, NAIVE_MODE);\n\n  arma::Mat<size_t> coverTreeNeighbors;\n  arma::mat coverTreeDistances;\n  coverTreeSearch.Search(data, 15, coverTreeNeighbors, coverTreeDistances);\n\n  arma::Mat<size_t> naiveNeighbors;\n  arma::mat naiveDistances;\n  naive.Search(data, 15, naiveNeighbors, naiveDistances);\n\n  for (size_t i = 0; i < coverTreeNeighbors.n_elem; ++i)\n  {\n    BOOST_REQUIRE_EQUAL(coverTreeNeighbors[i], naiveNeighbors[i]);\n    BOOST_REQUIRE_CLOSE(coverTreeDistances[i], naiveDistances[i], 1e-5);\n  }\n}\n\n/**\n * Test the cover tree dual-tree furthest neighbors method against the naive\n * method.\n */\nBOOST_AUTO_TEST_CASE(DualCoverTreeTest)\n{\n  arma::mat dataset;\n  data::Load(\"test_data_3_1000.csv\", dataset);\n\n  KFN tree(dataset);\n\n  arma::Mat<size_t> kdNeighbors;\n  arma::mat kdDistances;\n  tree.Search(dataset, 5, kdNeighbors, kdDistances);\n\n  typedef CoverTree<LMetric<2, true>, NeighborSearchStat<FurthestNeighborSort>,\n      arma::mat, FirstPointIsRoot> TreeType;\n\n  TreeType referenceTree(dataset);\n\n  NeighborSearch<FurthestNeighborSort, LMetric<2, true>, arma::mat,\n      StandardCoverTree> coverTreeSearch(std::move(referenceTree));\n\n  arma::Mat<size_t> coverNeighbors;\n  arma::mat coverDistances;\n  coverTreeSearch.Search(dataset, 5, coverNeighbors, coverDistances);\n\n  for (size_t i = 0; i < coverNeighbors.n_elem; ++i)\n  {\n    BOOST_REQUIRE_EQUAL(coverNeighbors(i), kdNeighbors(i));\n    BOOST_REQUIRE_CLOSE(coverDistances(i), kdDistances(i), 1e-5);\n  }\n}\n\n/**\n * Test the ball tree single-tree furthest-neighbors method against the naive\n * method.  This uses only a random reference dataset.\n *\n * Errors are produced if the results are not identical.\n */\nBOOST_AUTO_TEST_CASE(SingleBallTreeTest)\n{\n  arma::mat data;\n  data.randu(75, 1000); // 75 dimensional, 1000 points.\n\n  typedef BallTree<EuclideanDistance, NeighborSearchStat<FurthestNeighborSort>,\n      arma::mat> TreeType;\n  TreeType tree(data);\n\n  KFN naive(tree.Dataset(), NAIVE_MODE);\n\n  // BinarySpaceTree modifies data. Use modified data to maintain the\n  // correspondence between points in the dataset for both methods. The order of\n  // query points in both methods should be same.\n  NeighborSearch<FurthestNeighborSort, LMetric<2>, arma::mat, BallTree>\n      ballTreeSearch(std::move(tree), SINGLE_TREE_MODE);\n\n  arma::Mat<size_t> ballTreeNeighbors;\n  arma::mat ballTreeDistances;\n  ballTreeSearch.Search(15, ballTreeNeighbors, ballTreeDistances);\n\n  arma::Mat<size_t> naiveNeighbors;\n  arma::mat naiveDistances;\n  naive.Search(15, naiveNeighbors, naiveDistances);\n\n  for (size_t i = 0; i < ballTreeNeighbors.n_elem; ++i)\n  {\n    BOOST_REQUIRE_EQUAL(ballTreeNeighbors[i], naiveNeighbors[i]);\n    BOOST_REQUIRE_CLOSE(ballTreeDistances[i], naiveDistances[i], 1e-5);\n  }\n}\n\n/**\n * Test the ball tree dual-tree furthest neighbors method against the naive\n * method.\n */\nBOOST_AUTO_TEST_CASE(DualBallTreeTest)\n{\n  arma::mat dataset;\n  data::Load(\"test_data_3_1000.csv\", dataset);\n\n  KFN tree(dataset);\n\n  arma::Mat<size_t> kdNeighbors;\n  arma::mat kdDistances;\n  tree.Search(5, kdNeighbors, kdDistances);\n\n  NeighborSearch<FurthestNeighborSort, LMetric<2, true>, arma::mat, BallTree>\n      ballTreeSearch(dataset);\n\n  arma::Mat<size_t> ballNeighbors;\n  arma::mat ballDistances;\n  ballTreeSearch.Search(5, ballNeighbors, ballDistances);\n\n  for (size_t i = 0; i < ballNeighbors.n_elem; ++i)\n  {\n    BOOST_REQUIRE_EQUAL(ballNeighbors(i), kdNeighbors(i));\n    BOOST_REQUIRE_CLOSE(ballDistances(i), kdDistances(i), 1e-5);\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "a9a9654ff1c082831275e6bf7cd0d128b1a5734f", "size": 24802, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/kfn_test.cpp", "max_stars_repo_name": "birm/mlpack", "max_stars_repo_head_hexsha": "8e906556bbbd5be59481329567c2f9a413e72b11", "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/tests/kfn_test.cpp", "max_issues_repo_name": "birm/mlpack", "max_issues_repo_head_hexsha": "8e906556bbbd5be59481329567c2f9a413e72b11", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mlpack/tests/kfn_test.cpp", "max_forks_repo_name": "birm/mlpack", "max_forks_repo_head_hexsha": "8e906556bbbd5be59481329567c2f9a413e72b11", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.8197879859, "max_line_length": 80, "alphanum_fraction": 0.7174824611, "num_tokens": 7868, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149978955811, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.45025632735721455}}
{"text": "#include <iostream>\r\n#include <fstream>\r\n\r\n#include <opencv2/highgui/highgui.hpp>\r\n#include <opencv2/imgproc/imgproc.hpp>\r\n\r\n#include <imgproc/gradient_adapter.hpp>\r\n#include <imgproc/derivative_gradient.hpp>\r\n#include <imgproc/susan.hpp>\r\n#include <imgproc/rcmg.hpp>\r\n#include <imgproc/quadratureG2.hpp>\r\n#include <imgproc/quadratureS.hpp>\r\n#include <imgproc/quadratureSF.hpp>\r\n#include <imgproc/quadratureLGF.hpp>\r\n#include <imgproc/pc_sqf.hpp>\r\n#include <imgproc/pc_lgf.hpp>\r\n#include <imgproc/pc_matlab.hpp>\r\n#include <imgproc/laplace.hpp>\r\n\r\n#include <boost/filesystem.hpp>\r\n#include <boost/algorithm/string.hpp>  \r\n#include <boost/format.hpp>\r\n\r\n\r\nusing namespace lsfm;\r\nusing namespace std;\r\nnamespace fs = boost::filesystem;\r\n\r\nconstexpr int ENTRY_RGB = 2;\r\n\r\nconstexpr int runs = 10;\r\n\r\ntemplate<class GT, class MT, class FT>\r\nstruct Entry {\r\n    Entry() {}\r\n\r\n    Entry(const cv::Ptr<GradientI<uchar,GT,MT,FT>>& g, const std::string& n, int f = 0)\r\n        : gradient(g), name(n), time(0), images(0), flags(f) {}\r\n\r\n    cv::Ptr<GradientI<uchar, GT, MT, FT>> gradient;\r\n    std::string name;\r\n    int64 time;\r\n    int images, flags;\r\n\r\n    inline bool rgb() const {\r\n        return flags & ENTRY_RGB;\r\n    }\r\n\r\n    inline void process(const cv::Mat src) {\r\n        gradient->process(src);\r\n        gradient->magnitude();\r\n        cv::Mat tmp;\r\n        int64 start;\r\n        for (int i = 0; i != runs; ++i) {\r\n            start = cv::getTickCount();\r\n            gradient->process(src);\r\n            tmp = gradient->magnitude();\r\n            time += cv::getTickCount() - start;\r\n            ++images;\r\n        }\r\n    }\r\n};\r\n\r\nvoid parseFolder(const fs::path &folder, std::vector<fs::path> &files) {\r\n    fs::directory_iterator end_iter;\r\n    for_each(fs::directory_iterator(folder), fs::directory_iterator(), [&files](const fs::path& file) {\r\n        if (fs::is_regular_file(file))\r\n        {\r\n            std::string ext = file.extension().generic_string();\r\n            boost::algorithm::to_lower(ext);\r\n            if (ext == \".jpg\" || ext == \".png\") {\r\n                files.push_back(file);\r\n            }\r\n        }\r\n        if (fs::is_directory(file))\r\n            parseFolder(file, files);\r\n    });\r\n}\r\n\r\ntemplate<class GT, class MT, class DT>\r\nvoid processPath(std::vector<Entry<GT,MT,DT>> &entries, const std::pair<fs::path, std::string> &path) {\r\n    std::cout << \"processing \" << path.first << std::endl;\r\n    std::vector<fs::path> files;\r\n    parseFolder(path.first, files);\r\n\r\n    for_each(entries.begin(), entries.end(), [&](Entry<GT, MT, DT> &e) {\r\n        e.time = 0;\r\n        e.images = 0;\r\n    });\r\n\r\n    std::for_each(files.begin(), files.end(), [&](const fs::path& file) {\r\n        cv::Mat rgb = cv::imread(file.generic_string());\r\n        if (rgb.empty())\r\n        {\r\n            cout << \"Can not open \" << file.generic_string() << endl;\r\n        }\r\n        std::cout << file << std::endl;\r\n        cv::Mat src;\r\n        cv::cvtColor(rgb, src, CV_BGR2GRAY);\r\n\r\n        for_each(entries.begin(), entries.end(), [&](Entry<GT, MT, DT> &e) {\r\n            e.process(e.rgb() ? rgb : src);\r\n        });\r\n    });\r\n}\r\n\r\nint main(int argc, char** argv)\r\n{\r\n    char c;\r\n    std::cin >> c;\r\n\r\n    std::vector<std::pair<fs::path, std::string>> sets;\r\n    //sets.push_back(std::pair<fs::path, std::string>(\"../../images/Selection\", \"Selection\"));\r\n    //sets.push_back(std::pair<fs::path, std::string>(\"../../images/BSDS500\", \"BSDS500\"));\r\n    sets.push_back(std::pair<fs::path, std::string>(\"../../images/MDB/MiddEval3-Q\", \"MDB-Q\"));\r\n    //sets.push_back(std::pair<fs::path, std::string>(\"../../images/MDB/MiddEval3-H\", \"MDB-H\"));\r\n    //sets.push_back(std::pair<fs::path, std::string>(\"../../images/MDB/MiddEval3-F\", \"MDB-F\"));\r\n\r\n    std::vector<Entry<short, int, float>> gradI;\r\n    /*gradI.push_back(Entry<short, int, float>(new DerivativeGradient<uchar, short, int, float, RobertsDerivative<uchar, short>, QuadraticMagnitude>, \"Roberts (2x2)\"));\r\n    gradI.push_back(Entry<short, int, float>(new DerivativeGradient<uchar, short, int, float, PrewittDerivative<uchar, short>, QuadraticMagnitude>, \"Prewitt (3x3)\"));\r\n    gradI.push_back(Entry<short, int, float>(new DerivativeGradient<uchar, short, int, float, ScharrDerivative<uchar, short>, QuadraticMagnitude>, \"Scharr (3x3)\"));\r\n    \r\n    gradI.push_back(Entry<short, int, float>(new DerivativeGradient<uchar, short, int, float, SobelDerivative, QuadraticMagnitude>, \"Sobel (3x3)\"));\r\n    gradI.push_back(Entry<short, int, float>(new DerivativeGradient<uchar, short, int, float, SobelDerivative, QuadraticMagnitude>({ NV(\"grad_kernel_size\",5) }), \"Sobel (5x5)\"));\r\n    gradI.push_back(Entry<short, int, float>(new DerivativeGradient<uchar, short, int, float, SobelDerivative, QuadraticMagnitude>({ NV(\"grad_kernel_size\",7) }), \"Sobel (7x7)\"));\r\n    gradI.push_back(Entry<short, int, float>(new DerivativeGradient<uchar, short, int, float, SobelDerivative, QuadraticMagnitude>({ NV(\"grad_kernel_size\",9) }), \"Sobel (9x9)\"));*/\r\n    gradI.push_back(Entry<short, int, float>(new DerivativeGradient<uchar, short, int, float, SobelDerivative, QuadraticMagnitude>({ NV(\"grad_kernel_size\",11) }), \"Sobel (11x11)\"));\r\n    gradI.push_back(Entry<short, int, float>(new DerivativeGradient<uchar, short, int, float, SobelDerivative, QuadraticMagnitude>({ NV(\"grad_kernel_size\",13) }), \"Sobel (13x13)\"));\r\n    gradI.push_back(Entry<short, int, float>(new DerivativeGradient<uchar, short, int, float, SobelDerivative, QuadraticMagnitude>({ NV(\"grad_kernel_size\",15) }), \"Sobel (15x15)\"));\r\n\r\n    /*gradI.push_back(Entry<short, int, float>(new SusanGradient<short, int>, \"Susan (37)\"));\r\n    gradI.push_back(Entry<short, int, float>(new SusanGradient<short, int>(20, true), \"Susan (3x3)\"));\r\n\r\n    gradI.push_back(Entry<short, int, float>(new RCMGradient<uchar, 1, short, int>(3, 1), \"RMG (3x3)\"));\r\n    gradI.push_back(Entry<short, int, float>(new RCMGradient<uchar, 1, short, int>(5, 3), \"RMG (5x5)\"));\r\n    gradI.push_back(Entry<short, int, float>(new RCMGradient<uchar, 3, short, int>(3, 1), \"RCMG (3x3)\", ENTRY_RGB));*/\r\n\r\n    std::vector<Entry<float, float, float>> gradF;\r\n    /*gradF.push_back(Entry<float, float, float>(new DerivativeGradient<uchar, float, float, float, GaussianDerivative, Magnitude>({ NV(\"grad_kernel_size\",3), NV(\"grad_range\",1.5) }), \"Gauss (3x3)\"));\r\n    gradF.push_back(Entry<float, float, float>(new DerivativeGradient<uchar, float, float, float, GaussianDerivative, Magnitude>({ NV(\"grad_kernel_size\",5), NV(\"grad_range\",2.3) }), \"Gauss (5x5)\"));\r\n    gradF.push_back(Entry<float, float, float>(new DerivativeGradient<uchar, float, float, float, GaussianDerivative, Magnitude>({ NV(\"grad_kernel_size\",7), NV(\"grad_range\",3.0) }), \"Gauss (7x7)\"));\r\n    gradF.push_back(Entry<float, float, float>(new DerivativeGradient<uchar, float, float, float, GaussianDerivative, Magnitude>({ NV(\"grad_kernel_size\",9), NV(\"grad_range\",3.5) }), \"Gauss (9x9)\"));*/\r\n    gradF.push_back(Entry<float, float, float>(new DerivativeGradient<uchar, float, float, float, GaussianDerivative, Magnitude>({ NV(\"grad_kernel_size\",11), NV(\"grad_range\",4) }), \"Gauss (11x11)\"));\r\n    gradF.push_back(Entry<float, float, float>(new DerivativeGradient<uchar, float, float, float, GaussianDerivative, Magnitude>({ NV(\"grad_kernel_size\",13), NV(\"grad_range\",4.5) }), \"Gauss (13x13)\"));\r\n    gradF.push_back(Entry<float, float, float>(new DerivativeGradient<uchar, float, float, float, GaussianDerivative, Magnitude>({ NV(\"grad_kernel_size\",15), NV(\"grad_range\",5) }), \"Gauss (15x15)\"));\r\n    \r\n    /*gradF.push_back(Entry<float, float, float>(new GradientEnergy<QuadratureG2<uchar, float, PolarCV>>({ NV(\"grad_kernel_size\",3), NV(\"grad_kernel_spacing\",1.24008) }), \"QF_StG (3x3)\"));\r\n    gradF.push_back(Entry<float, float, float>(new GradientEnergy<QuadratureG2<uchar, float, PolarCV>>({ NV(\"grad_kernel_size\", 5), NV(\"grad_kernel_spacing\", 1.008) }), \"QF_StG (5x5)\"));\r\n    gradF.push_back(Entry<float, float, float>(new GradientEnergy<QuadratureG2<uchar, float, PolarCV>>({ NV(\"grad_kernel_size\", 7), NV(\"grad_kernel_spacing\", 0.873226) }), \"QF_StG (7x7)\"));\r\n    gradF.push_back(Entry<float, float, float>(new GradientEnergy<QuadratureG2<uchar, float, PolarCV>>({ NV(\"grad_kernel_size\", 9), NV(\"grad_kernel_spacing\", 0.781854) }), \"QF_StG (9x9)\"));*/\r\n    gradF.push_back(Entry<float, float, float>(new GradientEnergy<QuadratureG2<uchar, float, PolarCV>>({ NV(\"grad_kernel_size\", 11), NV(\"grad_kernel_spacing\", 0.7) }), \"QF_StG (11x11)\"));\r\n    gradF.push_back(Entry<float, float, float>(new GradientEnergy<QuadratureG2<uchar, float, PolarCV>>({ NV(\"grad_kernel_size\", 13), NV(\"grad_kernel_spacing\", 0.65) }), \"QF_StG (13x13)\"));\r\n    gradF.push_back(Entry<float, float, float>(new GradientEnergy<QuadratureG2<uchar, float, PolarCV>>({ NV(\"grad_kernel_size\", 15), NV(\"grad_kernel_spacing\", 0.6) }), \"QF_StG (15x15)\"));\r\n    \r\n    /*gradF.push_back(Entry<float, float, float>(new GradientEnergy<QuadratureS<uchar, float, float, PolarCV>>({ NV(\"grad_scale\", 1), NV(\"grad_muls\", 2), NV(\"grad_kernel_size\", 3), NV(\"grad_kernel_spacing\", 1.2) }), \"SQF PO (3x3)\"));\r\n    gradF.push_back(Entry<float, float, float>(new GradientEnergy<QuadratureS<uchar, float, float, PolarCV>>({ NV(\"grad_scale\", 1), NV(\"grad_muls\", 2), NV(\"grad_kernel_size\", 5), NV(\"grad_kernel_spacing\", 1.2) }), \"SQF PO (5x5)\"));\r\n    gradF.push_back(Entry<float, float, float>(new GradientEnergy<QuadratureS<uchar, float, float, PolarCV>>({ NV(\"grad_scale\", 1), NV(\"grad_muls\", 2), NV(\"grad_kernel_size\", 7), NV(\"grad_kernel_spacing\", 1.2) }), \"SQF PO (7x7)\"));\r\n    gradF.push_back(Entry<float, float, float>(new GradientEnergy<QuadratureS<uchar, float, float, PolarCV>>({ NV(\"grad_scale\", 1), NV(\"grad_muls\", 2), NV(\"grad_kernel_size\", 9), NV(\"grad_kernel_spacing\", 1.2) }), \"SQF PO (9x9)\"));*/\r\n    gradF.push_back(Entry<float, float, float>(new GradientEnergy<QuadratureS<uchar, float, float, PolarCV>>({ NV(\"grad_scale\", 1), NV(\"grad_muls\", 2), NV(\"grad_kernel_size\", 11), NV(\"grad_kernel_spacing\", 1.2) }), \"SQF PO (11x11)\"));\r\n    gradF.push_back(Entry<float, float, float>(new GradientEnergy<QuadratureS<uchar, float, float, PolarCV>>({ NV(\"grad_scale\", 1), NV(\"grad_muls\", 2), NV(\"grad_kernel_size\", 13), NV(\"grad_kernel_spacing\", 1.2) }), \"SQF PO (13x13)\"));\r\n    gradF.push_back(Entry<float, float, float>(new GradientEnergy<QuadratureS<uchar, float, float, PolarCV>>({ NV(\"grad_scale\", 1), NV(\"grad_muls\", 2), NV(\"grad_kernel_size\", 15), NV(\"grad_kernel_spacing\", 1.2) }), \"SQF PO (15x15)\"));\r\n    \r\n    //gradF.push_back(Entry<float, float, float>(new GradientEnergy<QuadratureLGF<uchar, float, PolarCV>>({ NV(\"grad_waveLength\", 3), NV(\"grad_sigmaOnf\", 0.55) }), \"SQFF LG\"));\r\n    //gradF.push_back(Entry<float, float, float>(new GradientEnergy<QuadratureSF<uchar, float, PolarCV>>({ NV(\"grad_scale\", 1), NV(\"grad_muls\", 2), NV(\"grad_kernel_spacing\", 1.2) }), \"SQFF PO\"));\r\n    \r\n    //gradF.push_back(Entry<float, float, float>(new GradientPC<PCLgf<uchar, float, PolarCV>>, \"PC LG\"));\r\n    \r\n    //gradF.push_back(Entry<float, float, float>(new GradientPC<PCSqf<uchar, float, PolarCV>>({ NV(\"grad_scale\", 1), NV(\"grad_muls\", 2), NV(\"grad_kernel_spacing\", 1.2) }), \"PC PO\"));\r\n\r\n    std::vector<Entry<double, double, double>> gradD;\r\n    //gradD.push_back(Entry<double, double, double>(new GradientPC<PCMatlab<uchar>>, \"PC ML\"));\r\n\r\n    int cols = gradI.size() + gradF.size() + gradD.size() + 1;\r\n    int rows = sets.size() + 1;\r\n    std::vector<std::vector<std::string>> table;\r\n    table.resize(cols);\r\n    for_each(table.begin(), table.end(), [&](std::vector<std::string> &row) {\r\n        row.resize(rows);\r\n    });\r\n\r\n    table[0][0] = \"Method\";\r\n\r\n    int row = 1;\r\n    for_each(gradI.begin(), gradI.end(), [&](const Entry<short, int, float> &e) {\r\n        table[row++][0] = e.name;\r\n    });\r\n    for_each(gradF.begin(), gradF.end(), [&](const Entry<float, float, float> &e) {\r\n        table[row++][0] = e.name;\r\n    });\r\n    for_each(gradD.begin(), gradD.end(), [&](const Entry<double, double, double> &e) {\r\n        table[row++][0] = e.name;\r\n    });\r\n\r\n    int col = 1;\r\n    for_each(sets.begin(), sets.end(), [&](const std::pair<fs::path, std::string> &data) {\r\n        \r\n        processPath(gradI, data);\r\n        processPath(gradF, data);\r\n        processPath(gradD, data);\r\n\r\n        table[0][col] = data.second;\r\n        row = 1;\r\n        for_each(gradI.begin(), gradI.end(), [&](const Entry<short, int, float> &e) {\r\n            table[row++][col] = boost::str(boost::format(\"%.3f\") % (static_cast<double>(e.time * 1000) / (e.images * cv::getTickFrequency()))) + \"ms\";\r\n        });\r\n\r\n        for_each(gradF.begin(), gradF.end(), [&](const Entry<float, float, float> &e) {\r\n            table[row++][col] = boost::str(boost::format(\"%.3f\") % (static_cast<double>(e.time * 1000) / (e.images * cv::getTickFrequency()))) + \"ms\";\r\n        });\r\n\r\n        for_each(gradD.begin(), gradD.end(), [&](const Entry<double, double, double> &e) {\r\n            table[row++][col] = boost::str(boost::format(\"%.3f\") % (static_cast<double>(e.time * 1000) / (e.images * cv::getTickFrequency()))) + \"ms\";\r\n        });\r\n        ++col;\r\n    });\r\n\r\n    std::ofstream ofs;\r\n    ofs.open(\"gradient_profiling.csv\");\r\n\r\n    for_each(table.begin(), table.end(), [&](const std::vector<std::string> &row) {\r\n        for_each(row.begin(), row.end(), [&](const std::string &cell) {\r\n            std::cout << cell << \"\\t\";\r\n            ofs << cell << \";\";\r\n        });\r\n        std::cout << std::endl;\r\n        ofs << std::endl;\r\n    });\r\n\r\n    ofs.close();\r\n    \r\n    return 0;\r\n}\r\n\r\n", "meta": {"hexsha": "dc7c9532d7e4e0f811f256030e3a4d9571619ded", "size": 13607, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "evaluation/old/lsd_precision.cpp", "max_stars_repo_name": "waterben/LineExtraction", "max_stars_repo_head_hexsha": "d247de45417a1512a3bf5d0ffcd630d40ffb8798", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-12T13:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-12T13:30:56.000Z", "max_issues_repo_path": "evaluation/old/lsd_precision.cpp", "max_issues_repo_name": "waterben/LineExtraction", "max_issues_repo_head_hexsha": "d247de45417a1512a3bf5d0ffcd630d40ffb8798", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "evaluation/old/lsd_precision.cpp", "max_forks_repo_name": "waterben/LineExtraction", "max_forks_repo_head_hexsha": "d247de45417a1512a3bf5d0ffcd630d40ffb8798", "max_forks_repo_licenses": ["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.9021276596, "max_line_length": 235, "alphanum_fraction": 0.6328360403, "num_tokens": 4016, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149978955811, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.45025632735721455}}
{"text": "#pragma once\n\n#include <list>\n#include <string>\n#include <boost/spirit/home/x3/support/ast/variant.hpp>\n#include <boost/foreach.hpp>\n\nnamespace client {\ntypedef unsigned int uint;\nnamespace ast {\n    namespace x3 = boost::spirit::x3;\n    struct nil {};\n    struct binary_op;\n    struct conditional_op;\n    struct expression;\n\n    struct binary_operator {\n        std::string name;\n        std::function<uint(uint, uint)> op;\n\n        uint\n        operator()(uint lhs, uint rhs) const {\n            return op(lhs, rhs);\n        }\n    };\n\n    struct operand : x3::variant<\n                         nil,\n                         uint,\n                         std::string,\n                         x3::forward_ast<binary_op>,\n                         x3::forward_ast<conditional_op>,\n                         x3::forward_ast<expression>> {\n        using base_type::base_type;\n        using base_type::operator=;\n    };\n\n    struct binary_op {\n        binary_operator op;\n        operand lhs;\n        operand rhs;\n    };\n\n    struct conditional_op {\n        operand lhs;\n        operand rhs_true;\n        operand rhs_false;\n    };\n\n    struct operation {\n        binary_operator op;\n        operand rhs;\n    };\n\n    struct expression {\n        operand lhs;\n        std::list<operation> rhs;\n    };\n\n    struct printer {\n        typedef void result_type;\n\n        result_type\n        operator()(operand const& ast) const {\n            boost::apply_visitor(*this, ast.get());\n        }\n\n        result_type\n        operator()(nil) const {}\n\n        result_type\n        operator()(expression const& ast) const {\n            if (ast.rhs.size() > 0) {\n                std::cout << '(';\n            }\n            boost::apply_visitor(*this, ast.lhs);\n            BOOST_FOREACH (operation const& op, ast.rhs) { (*this)(op); }\n            if (ast.rhs.size() > 0) {\n                std::cout << ')';\n            }\n        }\n\n        result_type\n        operator()(operation const& ast) const {\n            std::cout << ' ' << ast.op.name << ' ';\n            boost::apply_visitor(*this, ast.rhs);\n        }\n\n        result_type\n        operator()(binary_op const& ast) const {\n            std::cout << '(';\n            boost::apply_visitor(*this, ast.lhs);\n            boost::apply_visitor(*this, ast.rhs);\n            std::cout << ')';\n        }\n\n        result_type\n        operator()(conditional_op const& ast) const {\n            std::cout << '(';\n            boost::apply_visitor(*this, ast.lhs);\n            std::cout << \" ? \";\n            boost::apply_visitor(*this, ast.rhs_true);\n            std::cout << \" : \";\n            boost::apply_visitor(*this, ast.rhs_false);\n            std::cout << ')';\n        }\n\n        result_type\n        operator()(uint const& ast) const {\n            std::cout << ast;\n        }\n\n        result_type\n        operator()(std::string const& ast) const {\n            std::cout << ast;\n        }\n    };\n\n    struct evaluator {\n        typedef uint result_type;\n\n        evaluator(const result_type variable) : variable(variable) {}\n        result_type variable;\n\n        result_type\n        operator()(operand const& ast) const {\n            return boost::apply_visitor(*this, ast.get());\n        }\n\n        result_type\n        operator()(nil) const {\n            BOOST_ASSERT(0);\n            return 0;\n        }\n\n        result_type\n        operator()(expression const& ast) const {\n            result_type state = boost::apply_visitor(*this, ast.lhs);\n            BOOST_FOREACH (operation const& op, ast.rhs) {\n                state = (*this)(op, state);\n            }\n            return state;\n        }\n\n        result_type\n        operator()(operation const& ast, uint lhs) const {\n            result_type rhs = boost::apply_visitor(*this, ast.rhs);\n            return ast.op(lhs, rhs);\n        }\n\n        result_type\n        operator()(binary_op const& ast) const {\n            result_type lhs = boost::apply_visitor(*this, ast.lhs);\n            result_type rhs = boost::apply_visitor(*this, ast.rhs);\n            return ast.op(lhs, rhs);\n        }\n\n        result_type\n        operator()(conditional_op const& ast) const {\n            bool lhs = boost::apply_visitor(*this, ast.lhs);\n            if (lhs) {\n                return boost::apply_visitor(*this, ast.rhs_true);\n            }\n            return boost::apply_visitor(*this, ast.rhs_false);\n        }\n\n        result_type\n        operator()(uint const& ast) const {\n            return ast;\n        }\n\n        result_type\n        operator()(std::string const& ast) const {\n            return variable;\n        }\n    };\n\n} // namespace ast\n} // namespace client\n", "meta": {"hexsha": "75c44ac044e5b1be4b7fc5df419dc4c19b1e285f", "size": 4650, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ast.hpp", "max_stars_repo_name": "limitz404/plurals-parser-boost", "max_stars_repo_head_hexsha": "c90f226c5b54647e13cc07d83bd9895e8783737b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-27T09:58:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-27T09:58:37.000Z", "max_issues_repo_path": "include/ast.hpp", "max_issues_repo_name": "limitz404/plurals-parser-boost", "max_issues_repo_head_hexsha": "c90f226c5b54647e13cc07d83bd9895e8783737b", "max_issues_repo_licenses": ["MIT"], "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/ast.hpp", "max_forks_repo_name": "limitz404/plurals-parser-boost", "max_forks_repo_head_hexsha": "c90f226c5b54647e13cc07d83bd9895e8783737b", "max_forks_repo_licenses": ["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.8333333333, "max_line_length": 73, "alphanum_fraction": 0.5049462366, "num_tokens": 996, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.754914997895581, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.45025632735721444}}
{"text": "#include <stan/math/rev/mat.hpp>\n#include <gtest/gtest.h>\n#include <stan/math.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/math/distributions.hpp>\n#include <test/unit/math/rev/mat/prob/lkj_corr_cholesky_test_functors.hpp>\n#include <test/unit/math/rev/mat/prob/test_gradients.hpp>\n#include <test/unit/math/rev/mat/util.hpp>\n\nTEST(ProbDistributionsLkjCorr, var) {\n  using stan::math::var;\n  boost::random::mt19937 rng;\n  int K = 4;\n  Eigen::Matrix<var, Eigen::Dynamic, Eigen::Dynamic> Sigma(K, K);\n  Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> Sigma_d(K, K);\n  Sigma.setZero();\n  Sigma.diagonal().setOnes();\n  Sigma_d.setZero();\n  Sigma_d.diagonal().setOnes();\n  var eta = stan::math::uniform_rng(0, 2, rng);\n  var f = stan::math::do_lkj_constant(eta, K);\n  EXPECT_FLOAT_EQ(f.val(), stan::math::lkj_corr_log(Sigma, eta).val());\n  EXPECT_FLOAT_EQ(f.val(), stan::math::lkj_corr_log(Sigma_d, eta).val());\n  eta = 1.0;\n  double eta_d = 1.0;\n  f = stan::math::do_lkj_constant(eta, K);\n  EXPECT_FLOAT_EQ(f.val(), stan::math::lkj_corr_log(Sigma, eta).val());\n  EXPECT_FLOAT_EQ(f.val(), stan::math::lkj_corr_log(Sigma, eta_d).val());\n}\n\nTEST(ProbDistributionsLkjCorrCholesky, var) {\n  using stan::math::var;\n  boost::random::mt19937 rng;\n  int K = 4;\n  Eigen::Matrix<var, Eigen::Dynamic, Eigen::Dynamic> Sigma(K, K);\n  Sigma.setZero();\n  Sigma.diagonal().setOnes();\n  Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> Sigma_d(K, K);\n  Sigma_d.setZero();\n  Sigma_d.diagonal().setOnes();\n  var eta = stan::math::uniform_rng(0, 2, rng);\n  var f = stan::math::do_lkj_constant(eta, K);\n  EXPECT_FLOAT_EQ(f.val(), stan::math::lkj_corr_cholesky_log(Sigma, eta).val());\n  EXPECT_FLOAT_EQ(f.val(),\n                  stan::math::lkj_corr_cholesky_log(Sigma_d, eta).val());\n  eta = 1.0;\n  double eta_d = 1.0;\n  f = stan::math::do_lkj_constant(eta, K);\n  EXPECT_FLOAT_EQ(f.val(), stan::math::lkj_corr_cholesky_log(Sigma, eta).val());\n  EXPECT_FLOAT_EQ(f.val(),\n                  stan::math::lkj_corr_cholesky_log(Sigma, eta_d).val());\n}\n\nTEST(ProbDistributionsLkjCorrCholesky, gradients) {\n  using stan::math::var;\n  int dim_mat = 3;\n  Eigen::Matrix<double, Eigen::Dynamic, 1> x1(dim_mat);\n  Eigen::Matrix<double, Eigen::Dynamic, 1> x2(1);\n  Eigen::Matrix<double, Eigen::Dynamic, 1> x3(dim_mat + 1);\n\n  x2(0) = 2.0;\n\n  for (int i = 0; i < dim_mat; ++i) {\n    x1(i) = i / 10.0;\n    x3(i + 1) = x1(i);\n  }\n  x3(0) = 0.5;\n\n  stan::math::lkj_corr_cholesky_dc test_func_1(dim_mat);\n  stan::math::lkj_corr_cholesky_cd test_func_2(dim_mat);\n  stan::math::lkj_corr_cholesky_dd test_func_3(dim_mat);\n\n  using stan::math::finite_diff_gradient;\n  using stan::math::gradient;\n\n  Eigen::Matrix<double, Eigen::Dynamic, 1> grad;\n  double fx;\n  Eigen::Matrix<double, Eigen::Dynamic, 1> grad_ad;\n  double fx_ad;\n\n  finite_diff_gradient(test_func_3, x3, fx, grad);\n  gradient(test_func_3, x3, fx_ad, grad_ad);\n\n  test_grad_eq(grad, grad_ad);\n  EXPECT_FLOAT_EQ(fx, fx_ad);\n\n  finite_diff_gradient(test_func_2, x2, fx, grad);\n  gradient(test_func_2, x2, fx_ad, grad_ad);\n  test_grad_eq(grad, grad_ad);\n  EXPECT_FLOAT_EQ(fx, fx_ad);\n\n  Eigen::Matrix<double, Eigen::Dynamic, 1> grad_1;\n  double fx_1;\n  Eigen::Matrix<double, Eigen::Dynamic, 1> grad_ad_1;\n  double fx_ad_1;\n\n  finite_diff_gradient(test_func_1, x1, fx_1, grad_1);\n  gradient(test_func_1, x1, fx_ad_1, grad_ad_1);\n  test_grad_eq(grad_1, grad_ad_1);\n  EXPECT_FLOAT_EQ(fx, fx_ad);\n}\n", "meta": {"hexsha": "e19d4bbfd645e471095ff1924047e39c29762296", "size": 3436, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/rev/mat/prob/lkj_corr_test.cpp", "max_stars_repo_name": "jrmie/math", "max_stars_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-07-23T14:57:41.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-23T14:57:41.000Z", "max_issues_repo_path": "test/unit/math/rev/mat/prob/lkj_corr_test.cpp", "max_issues_repo_name": "jrmie/math", "max_issues_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-09-23T19:58:36.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-24T12:03:41.000Z", "max_forks_repo_path": "test/unit/math/rev/mat/prob/lkj_corr_test.cpp", "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": 33.6862745098, "max_line_length": 80, "alphanum_fraction": 0.6915017462, "num_tokens": 1135, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.45025632077977795}}
{"text": "// Copyright 2015-2020 The ALMA Project Developers\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//   http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n// implied. See the License for the specific language governing\n// permissions and limitations under the License.\n\n/// @file\n/// Test the functionality of the psi_calculator.\n\n#include <iostream>\n#include <functional>\n#include <boost/filesystem.hpp>\n#include <boost/mpi.hpp>\n#include \"gtest/gtest.h\"\n#include <utilities.hpp>\n#include <vasp_io.hpp>\n#include <qpoint_grid.hpp>\n#include <processes.hpp>\n#include <bulk_hdf5.hpp>\n#include <analytic1d.hpp>\n\nTEST(analytic1D_psi_case, bulk100_test) {\n    auto basedir = boost::filesystem::path(TEST_RESOURCE_DIR);\n    auto si_dir = basedir / boost::filesystem::path(\"Si\");\n    auto hdf5_path = si_dir / boost::filesystem::path(\"Si_threeph.h5\");\n    boost::mpi::communicator world;\n    auto my_id = world.rank();\n\n    // obtain phonon data from HDF5 file\n    auto hdf5_data = alma::load_bulk_hdf5(hdf5_path.string().c_str(), world);\n    auto description = std::get<0>(hdf5_data);\n    auto poscar = std::move(std::get<1>(hdf5_data));\n    auto syms = std::move(std::get<2>(hdf5_data));\n    auto grid = std::move(std::get<3>(hdf5_data));\n    auto processes = std::move(std::get<4>(hdf5_data));\n\n    double T = 300.0;\n\n    Eigen::ArrayXXd w(alma::calc_w0_threeph(*grid, *processes, T, world));\n\n    // create transport direction\n    Eigen::Vector3d u100(1.0, 0.0, 0.0);\n\n    // general variables\n    int Nxi;\n\n    if (my_id == 0) { // analytic1D code is not parallellised; avoid\n                      // running duplicates.\n        Nxi = 4;\n        alma::analytic1D::psi_calculator psiCalc(\n            poscar.get(), grid.get(), &w, T);\n        psiCalc.setLogGrid(1e3, 1e9, Nxi);\n        Eigen::VectorXd xigrid = psiCalc.getSpatialFrequencies();\n\n        // Calculate psi functions in bulk Si for 3 directions\n        psiCalc.normaliseOutput(true); // turn on optional rescaling\n                                       // (output gets divided by\n                                       // Dbulk*xi^2)\n\n        psiCalc.setDirection(u100);\n        Eigen::VectorXd psi100 = psiCalc.getPsi();\n\n        Eigen::VectorXd psi100_ref(4);\n        psi100_ref << 1.000585888, 0.9864015985, 0.4049977681, 0.005287157147;\n        Eigen::VectorXd ratio100 = psi100.array() / psi100_ref.array();\n\n        for (int nxi = 0; nxi < Nxi; nxi++) {\n            EXPECT_NEAR(ratio100(nxi), 1.0, 5e-3);\n        }\n    }\n}\n\nTEST(analytic1D_psi_case, bulk110_test) {\n    auto basedir = boost::filesystem::path(TEST_RESOURCE_DIR);\n    auto si_dir = basedir / boost::filesystem::path(\"Si\");\n    auto hdf5_path = si_dir / boost::filesystem::path(\"Si_threeph.h5\");\n    boost::mpi::communicator world;\n    auto my_id = world.rank();\n\n    // obtain phonon data from HDF5 file\n    auto hdf5_data = alma::load_bulk_hdf5(hdf5_path.string().c_str(), world);\n    auto description = std::get<0>(hdf5_data);\n    auto poscar = std::move(std::get<1>(hdf5_data));\n    auto syms = std::move(std::get<2>(hdf5_data));\n    auto grid = std::move(std::get<3>(hdf5_data));\n    auto processes = std::move(std::get<4>(hdf5_data));\n\n    double T = 300.0;\n\n    Eigen::ArrayXXd w(alma::calc_w0_threeph(*grid, *processes, T, world));\n\n    // create transport direction\n    Eigen::Vector3d u110(1.0, 1.0, 0.0);\n\n    // general variables\n    int Nxi;\n\n    if (my_id == 0) { // analytic1D code is not parallellised; avoid\n                      // running duplicates.\n        Nxi = 4;\n        alma::analytic1D::psi_calculator psiCalc(\n            poscar.get(), grid.get(), &w, T);\n        psiCalc.setLogGrid(1e3, 1e9, Nxi);\n        Eigen::VectorXd xigrid = psiCalc.getSpatialFrequencies();\n\n        // Calculate psi functions in bulk Si for 3 directions\n        psiCalc.normaliseOutput(true); // turn on optional rescaling\n                                       // (output gets divided by\n                                       // Dbulk*xi^2)\n\n        psiCalc.setDirection(u110);\n        Eigen::VectorXd psi110 = psiCalc.getPsi();\n\n        Eigen::VectorXd psi110_ref(4);\n        psi110_ref << 1.000585549, 0.9834471977, 0.3966867118, 0.005560183293;\n        Eigen::VectorXd ratio110 = psi110.array() / psi110_ref.array();\n\n        for (int nxi = 0; nxi < Nxi; nxi++) {\n            EXPECT_NEAR(ratio110(nxi), 1.0, 5e-3);\n        }\n    }\n}\n\nTEST(analytic1D_psi_case, bulk111_test) {\n    auto basedir = boost::filesystem::path(TEST_RESOURCE_DIR);\n    auto si_dir = basedir / boost::filesystem::path(\"Si\");\n    auto hdf5_path = si_dir / boost::filesystem::path(\"Si_threeph.h5\");\n    boost::mpi::communicator world;\n    auto my_id = world.rank();\n\n    // obtain phonon data from HDF5 file\n    auto hdf5_data = alma::load_bulk_hdf5(hdf5_path.string().c_str(), world);\n    auto description = std::get<0>(hdf5_data);\n    auto poscar = std::move(std::get<1>(hdf5_data));\n    auto syms = std::move(std::get<2>(hdf5_data));\n    auto grid = std::move(std::get<3>(hdf5_data));\n    auto processes = std::move(std::get<4>(hdf5_data));\n\n    double T = 300.0;\n\n    Eigen::ArrayXXd w(alma::calc_w0_threeph(*grid, *processes, T, world));\n\n    // create transport direction\n    Eigen::Vector3d u111(1.0, 1.0, 1.0);\n\n    // general variables\n    int Nxi;\n\n    if (my_id == 0) { // analytic1D code is not parallellised; avoid\n                      // running duplicates.\n        Nxi = 4;\n        alma::analytic1D::psi_calculator psiCalc(\n            poscar.get(), grid.get(), &w, T);\n        psiCalc.setLogGrid(1e3, 1e9, Nxi);\n        Eigen::VectorXd xigrid = psiCalc.getSpatialFrequencies();\n\n        // Calculate psi functions in bulk Si for 3 directions\n        psiCalc.normaliseOutput(true); // turn on optional rescaling\n                                       // (output gets divided by\n                                       // Dbulk*xi^2)\n\n        psiCalc.setDirection(u111);\n        Eigen::VectorXd psi111 = psiCalc.getPsi();\n\n        Eigen::VectorXd psi111_ref(4);\n        psi111_ref << 1.000585193, 0.981217029, 0.4013087323, 0.006630052249;\n        Eigen::VectorXd ratio111 = psi111.array() / psi111_ref.array();\n\n        for (int nxi = 0; nxi < Nxi; nxi++) {\n            EXPECT_NEAR(ratio111(nxi), 1.0, 5e-3);\n        }\n    }\n}\n\nint main(int argc, char** argv) {\n    boost::mpi::environment env;\n\n    ::testing::InitGoogleTest(&argc, argv);\n    return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "a2674258810344dc4136848572d86f5b6a01a2cf", "size": 6729, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/analytic1D_psi_test.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": "test/analytic1D_psi_test.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": "test/analytic1D_psi_test.cpp", "max_forks_repo_name": "sousaw/BTE-Barna", "max_forks_repo_head_hexsha": "029ca43ef096c4b725d3aeb2955bc0df9ca544a9", "max_forks_repo_licenses": ["MIT", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.6031746032, "max_line_length": 78, "alphanum_fraction": 0.6220835191, "num_tokens": 1910, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.45025632077977795}}
{"text": "/**\n *  Copyright (C) 2012  \n *    Ekaterina Potapova\n *    Automation and Control Institute\n *    Vienna University of Technology\n *    Gusshausstra\u00dfe 25-29\n *    1040 Vienna, Austria\n *    potapova(at)acin.tuwien.ac.at\n *\n *  This program is free software: you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n *\n *  This program is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n *\n *  You should have received a copy of the GNU General Public License\n *  along with this program.  If not, see http://www.gnu.org/licenses/\n */\n\n#include \"v4r/attention_segmentation/PCA.h\"\n#include <Eigen/Dense>\n\nnamespace v4r\n{\n \nEigen::Vector4f getMean(pcl::PointCloud<pcl::Normal>::ConstPtr cloud)\n{\n  Eigen::Vector4f mean;\n  mean.setZero();\n\n  for (unsigned int pi=0; pi<cloud->size(); pi++)\n  {\n    mean[0] += cloud->points.at(pi).normal[0];\n    mean[1] += cloud->points.at(pi).normal[1];\n    mean[2] += cloud->points.at(pi).normal[2];\n  }\n\n  mean /= (float)cloud->size();\n  \n  return(mean);\n  \n}\n\nbool computeCovarianceMatrix(pcl::PointCloud<pcl::Normal>::ConstPtr cloud, const Eigen::Vector4f &mean, Eigen::Matrix3f &cov)\n{\n  bool done = false;\n  cov.setZero ();\n\n  for (unsigned pi = 0; pi < cloud->size (); ++pi)\n  {\n    float x = cloud->points.at(pi).normal[0] - mean[0];\n    float y = cloud->points.at(pi).normal[1] - mean[1];\n    float z = cloud->points.at(pi).normal[2] - mean[2];\n\n    cov(0,0) += x*x;\n    cov(0,1) += x*y;\n    cov(0,2) += x*z;\n    \n    cov(1,0) += y*x;\n    cov(1,1) += y*y;\n    cov(1,2) += y*z;\n    \n    cov(2,0) += z*x;\n    cov(2,1) += z*y;\n    cov(2,2) += z*z;\n    \n    done = true;\n  }\n  \n  return(done);\n}\n\nvoid principleAxis(pcl::PointCloud<pcl::Normal>::ConstPtr cloud, std::vector<pcl::Normal> &axis)\n{\n  Eigen::Vector4f mean;\n  EIGEN_ALIGN16 Eigen::Matrix3f cov;\n  EIGEN_ALIGN16 Eigen::Vector3f eigen_values;\n  EIGEN_ALIGN16 Eigen::Matrix3f eigen_vectors;\n  \n  axis.clear();\n  axis.resize(3);\n  \n  mean = getMean(cloud);\n  \n  if(computeCovarianceMatrix(cloud,mean,cov))\n  {\n    Eigen::SelfAdjointEigenSolver<Eigen::Matrix3f> eigensolver(cov);\n    if (eigensolver.info() != Eigen::Success)\n      return;\n     \n    eigen_values = eigensolver.eigenvalues();\n    eigen_vectors = eigensolver.eigenvectors();\n    \n    //pcl::eigen33 (cov, eigen_vectors, eigen_values);\n  \n    //std::cerr << \"inside principleAxis\" << std::endl;\n    \n    axis.at(0).normal[0] = eigen_vectors (0,0);\n    axis.at(0).normal[1] = eigen_vectors (1,0);\n    axis.at(0).normal[2] = eigen_vectors (2,0);\n  \n    axis.at(1).normal[0] = eigen_vectors (0,1);\n    axis.at(1).normal[1] = eigen_vectors (1,1);\n    axis.at(1).normal[2] = eigen_vectors (2,1);\n  \n    axis.at(2).normal[0] = eigen_vectors (0,2);\n    axis.at(2).normal[1] = eigen_vectors (1,2);\n    axis.at(2).normal[2] = eigen_vectors (2,2);\n  }\n  \n}\n  \n} //namespace v4r\n", "meta": {"hexsha": "2eaa99ed4bafe131f7c634b27cec3f43d8a32fc2", "size": 3171, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/attention_segmentation/src/PCA.cpp", "max_stars_repo_name": "ToMadoRe/v4r", "max_stars_repo_head_hexsha": "7cb817e05cb9d99cb2f68db009c27d7144d07f09", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2015-11-16T14:21:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-09T02:57:33.000Z", "max_issues_repo_path": "modules/attention_segmentation/src/PCA.cpp", "max_issues_repo_name": "ToMadoRe/v4r", "max_issues_repo_head_hexsha": "7cb817e05cb9d99cb2f68db009c27d7144d07f09", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 35.0, "max_issues_repo_issues_event_min_datetime": "2015-07-27T15:04:43.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-22T10:52:35.000Z", "max_forks_repo_path": "modules/attention_segmentation/src/PCA.cpp", "max_forks_repo_name": "ToMadoRe/v4r", "max_forks_repo_head_hexsha": "7cb817e05cb9d99cb2f68db009c27d7144d07f09", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2015-08-06T09:26:27.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-03T01:31:00.000Z", "avg_line_length": 26.8728813559, "max_line_length": 125, "alphanum_fraction": 0.6379690949, "num_tokens": 990, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4502563207797779}}
{"text": "/********************************************************************************\n*  This file is part of CinoLib                                                 *\n*  Copyright(C) 2016: Marco Livesu                                              *\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*                                                                               *\n*     Marco Livesu (marco.livesu@gmail.com)                                     *\n*     http://pers.ge.imati.cnr.it/livesu/                                       *\n*                                                                               *\n*     Italian National Research Council (CNR)                                   *\n*     Institute for Applied Mathematics and Information Technologies (IMATI)    *\n*     Via de Marini, 6                                                          *\n*     16149 Genoa,                                                              *\n*     Italy                                                                     *\n*********************************************************************************/\n#include <cinolib/simplicial_map.h>\n#include <Eigen/Dense>\n\nnamespace cinolib\n{\n\nCINO_INLINE\nvoid affine_simplicial_map(const vec3d & A0,\n                           const vec3d & A1,\n                           const vec3d & A2,\n                           const vec3d & A3,\n                           const vec3d & B0,\n                           const vec3d & B1,\n                           const vec3d & B2,\n                           const vec3d & B3,\n                           double        m[3][3],\n                           double        t[3])\n{\n    Eigen::VectorXd rhs(12);\n    Eigen::MatrixXd M;\n    M.setZero(12,12);\n\n    M.coeffRef( 0, 0) = A0.x();\n    M.coeffRef( 0, 1) = A0.y();\n    M.coeffRef( 0, 2) = A0.z();\n    M.coeffRef( 0, 3) = 1.0;\n    M.coeffRef( 1, 4) = A0.x();\n    M.coeffRef( 1, 5) = A0.y();\n    M.coeffRef( 1, 6) = A0.z();\n    M.coeffRef( 1, 7) = 1.0;\n    M.coeffRef( 2, 8) = A0.x();\n    M.coeffRef( 2, 9) = A0.y();\n    M.coeffRef( 2,10) = A0.z();\n    M.coeffRef( 2,11) = 1.0;\n\n    M.coeffRef( 3, 0) = A1.x();\n    M.coeffRef( 3, 1) = A1.y();\n    M.coeffRef( 3, 2) = A1.z();\n    M.coeffRef( 3, 3) = 1.0;\n    M.coeffRef( 4, 4) = A1.x();\n    M.coeffRef( 4, 5) = A1.y();\n    M.coeffRef( 4, 6) = A1.z();\n    M.coeffRef( 4, 7) = 1.0;\n    M.coeffRef( 5, 8) = A1.x();\n    M.coeffRef( 5, 9) = A1.y();\n    M.coeffRef( 5,10) = A1.z();\n    M.coeffRef( 5,11) = 1.0;\n\n    M.coeffRef( 6, 0) = A2.x();\n    M.coeffRef( 6, 1) = A2.y();\n    M.coeffRef( 6, 2) = A2.z();\n    M.coeffRef( 6, 3) = 1.0;\n    M.coeffRef( 7, 4) = A2.x();\n    M.coeffRef( 7, 5) = A2.y();\n    M.coeffRef( 7, 6) = A2.z();\n    M.coeffRef( 7, 7) = 1.0;\n    M.coeffRef( 8, 8) = A2.x();\n    M.coeffRef( 8, 9) = A2.y();\n    M.coeffRef( 8,10) = A2.z();\n    M.coeffRef( 8,11) = 1.0;\n\n    M.coeffRef( 9, 0) = A3.x();\n    M.coeffRef( 9, 1) = A3.y();\n    M.coeffRef( 9, 2) = A3.z();\n    M.coeffRef( 9, 3) = 1.0;\n    M.coeffRef(10, 4) = A3.x();\n    M.coeffRef(10, 5) = A3.y();\n    M.coeffRef(10, 6) = A3.z();\n    M.coeffRef(10, 7) = 1.0;\n    M.coeffRef(11, 8) = A3.x();\n    M.coeffRef(11, 9) = A3.y();\n    M.coeffRef(11,10) = A3.z();\n    M.coeffRef(11,11) = 1.0;\n\n    rhs( 0) = B0.x();\n    rhs( 1) = B0.y();\n    rhs( 2) = B0.z();\n    rhs( 3) = B1.x();\n    rhs( 4) = B1.y();\n    rhs( 5) = B1.z();\n    rhs( 6) = B2.x();\n    rhs( 7) = B2.y();\n    rhs( 8) = B2.z();\n    rhs( 9) = B3.x();\n    rhs(10) = B3.y();\n    rhs(11) = B3.z();\n\n    Eigen::JacobiSVD<Eigen::MatrixXd> svd(M, Eigen::ComputeThinU | Eigen::ComputeThinV);\n    Eigen::VectorXd x = svd.solve(rhs);\n\n    m[0][0]=x(0);   m[0][1]=x(1);   m[0][2]=x(2);   t[0]=x(3);\n    m[1][0]=x(4);   m[1][1]=x(5);   m[1][2]=x(6);   t[1]=x(7);\n    m[2][0]=x(8);   m[2][1]=x(9);   m[2][2]=x(10);  t[2]=x(11);\n\n    // safety checks\n    //\n    //#ifndef NDEBUG\n    //vec3d test0 = A0;\n    //vec3d test1 = A1;\n    //vec3d test2 = A2;\n    //vec3d test3 = A3;\n    //transform(test0, m); test0 += vec3d(t[0], t[1], t[2]);\n    //transform(test1, m); test1 += vec3d(t[0], t[1], t[2]);\n    //transform(test2, m); test2 += vec3d(t[0], t[1], t[2]);\n    //transform(test3, m); test3 += vec3d(t[0], t[1], t[2]);\n    //if((B0 - test0).length() > 1e-10) std::cout << (B0 - test0).length() << \"\\t\" << tet_scaled_jacobian(A0,A1,A2,A3) << \"\\t\" << tet_scaled_jacobian(B0,B1,B2,B3) << std::endl;\n    //if((B1 - test1).length() > 1e-10) std::cout << (B1 - test1).length() << \"\\t\" << tet_scaled_jacobian(A0,A1,A2,A3) << \"\\t\" << tet_scaled_jacobian(B0,B1,B2,B3) << std::endl;\n    //if((B2 - test2).length() > 1e-10) std::cout << (B2 - test2).length() << \"\\t\" << tet_scaled_jacobian(A0,A1,A2,A3) << \"\\t\" << tet_scaled_jacobian(B0,B1,B2,B3) << std::endl;\n    //if((B3 - test3).length() > 1e-10) std::cout << (B3 - test3).length() << \"\\t\" << tet_scaled_jacobian(A0,A1,A2,A3) << \"\\t\" << tet_scaled_jacobian(B0,B1,B2,B3) << std::endl;\n    //assert((B0 - test0).length() < 1e-10);\n    //assert((B1 - test1).length() < 1e-10);\n    //assert((B2 - test2).length() < 1e-10);\n    //assert((B3 - test3).length() < 1e-10);\n    //#endif\n}\n\n}\n", "meta": {"hexsha": "4188f9b6b72dbf64b026e8d519e0a13f197d9841", "size": 6883, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "include/cinolib/simplicial_map.cpp", "max_stars_repo_name": "Deiv99/cinolib", "max_stars_repo_head_hexsha": "fbb6e951703764e5b97f074aede87752c3165d17", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-06-22T00:23:45.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-22T00:23:45.000Z", "max_issues_repo_path": "include/cinolib/simplicial_map.cpp", "max_issues_repo_name": "Deiv99/cinolib", "max_issues_repo_head_hexsha": "fbb6e951703764e5b97f074aede87752c3165d17", "max_issues_repo_licenses": ["MIT"], "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/cinolib/simplicial_map.cpp", "max_forks_repo_name": "Deiv99/cinolib", "max_forks_repo_head_hexsha": "fbb6e951703764e5b97f074aede87752c3165d17", "max_forks_repo_licenses": ["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.9869281046, "max_line_length": 176, "alphanum_fraction": 0.4268487578, "num_tokens": 2141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834649, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.4501625333606373}}
{"text": "// ImGui - standalone example application for GLFW + OpenGL 3, using programmable pipeline\n// If you are new to ImGui, see examples/README.txt and documentation at the top of imgui.cpp.\n// (GLFW is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan graphics context creation, etc.)\n// (GL3W is a helper library to access OpenGL functions since there is no standard header to access modern OpenGL functions easily. Alternatives are GLEW, Glad, etc.)\n\n\n#include <stdio.h>\n#include <GL/glew.h>    \n#include <GLFW/glfw3.h>\n#include <glm/glm.hpp>\n#include <glm/gtc/matrix_transform.hpp>\n#include <glm/gtc/type_ptr.hpp>\n#include \"Shader_m.h\"\n#include \"Camera.h\"\n#include \"Model.h\"\n#include <iostream>\n#include <tuple>\n#define CGAL_EIGEN3_ENABLED \n#include <CGAL/Simple_cartesian.h>\n#include <CGAL/Polyhedron_3.h>\n#include <CGAL/Polyhedron_items_with_id_3.h>\n#include <CGAL/extract_mean_curvature_flow_skeleton.h>\n#include <CGAL/boost/graph/split_graph_into_polylines.h>\n#include <fstream>\n#include <boost/foreach.hpp>\n#include <CGAL\\Surface_mesh_deformation.h>\n#include <CGAL/Polyhedron_items_with_id_3.h>\n#include <CGAL/boost/graph/copy_face_graph.h>\n#include <CGAL\\Surface_mesh.h>\n#include <CGAL/mesh_segmentation.h>\n#include <CGAL/boost/graph/Face_filtered_graph.h>\n#include <CGAL/property_map.h>\n#include <CGAL/Polygon_mesh_processing/transform.h>\n#include <CGAL/Aff_transformation_3.h>\n#include <boost/variant/get.hpp>\n#include <CGAL/aff_transformation_tags.h>\n#include <CGAL/Vector_3.h>\n#include <CGAL\\IO\\read_off_points.h>\n#include <CGAL\\IO\\write_off_points.h>\n#include <CGAL/Polygon_mesh_processing/triangulate_faces.h>\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Polygon_mesh_processing/triangulate_hole.h>\n#include <CGAL/Polygon_mesh_processing/compute_normal.h>\n#include \"TriMeshBuilder.h\"\n#define STB_IMAGE_IMPLEMENTATION\n#include \"stb_image.h\"\n#include \"imgui.h\"\n#include \"imgui_impl_glfw_gl3.h\"\n\n#include \"Image.h\"\n#include \"Interface.h\"\n#include \"TreeGrowApp.h\"\n#include \"AssimpConverter.h\"\n#include \"SkeletalModel.h\"\n\n#include <CGAL/Vector_3.h>\n\n#include <CGAL/Polygon_mesh_processing/corefinement.h>\n\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel\t\t\t\tKernel;\ntypedef Eigen::Vector3d\t\t\t\t\t\t\t\t\t\t\t\t\tVector3d;\ntypedef CGAL::Aff_transformation_3<Kernel>\t\t\t\t\t\t\t\tAff_transformation_3;\ntypedef Kernel::Vector_3\t\t\t\t\t\t\t\t\t\t\t\tVector_3;\ntypedef Kernel::Point_3\t\t\t\t\t\t\t\t\t\t\t\t\tPoint;\ntypedef std::pair<Point, Vector_3>\t\t\t\t\t\t\t\t\t\tPwn;\ntypedef CGAL::Surface_mesh<Point>\t\t\t\t\t\t\t\t\t\tSurfaceMesh;\ntypedef Kernel::FT\t\t\t\t\t\t\t\t\t\t\t\t\t\tpointFT;\ntypedef CGAL::Polyhedron_3<Kernel, CGAL::Polyhedron_items_with_id_3>    Polyhedron;\ntypedef boost::graph_traits<Polyhedron>::vertex_descriptor\t\t\t\tvertex_descriptor;\ntypedef boost::graph_traits<Polyhedron>::vertex_iterator\t\t\t\tvertex_iterator;\ntypedef boost::graph_traits<Polyhedron>::halfedge_descriptor\t\t\thalfedge_descriptor;\ntypedef boost::graph_traits<SurfaceMesh>::halfedge_descriptor\t\t\tSFhalfedge_descriptor;\ntypedef boost::graph_traits<Polyhedron>::out_edge_iterator\t\t\t\tout_edge_iterator;\ntypedef boost::graph_traits<Polyhedron>::face_descriptor\t\t\t\tface_descriptor;\ntypedef boost::graph_traits<SurfaceMesh>::face_descriptor\t\t\t\tSFface_descriptor;\ntypedef CGAL::Mean_curvature_flow_skeletonization<Polyhedron>\t\t\tSkeletonization;\ntypedef CGAL::Surface_mesh<Point>\t\t\t\t\t\t\t\t\t\tSM;\ntypedef Skeletonization::Skeleton\t\t\t\t\t\t\t\t\t\tSkeleton;\ntypedef Skeleton::vertex_descriptor\t\t\t\t\t\t\t\t\t\tSkeleton_vertex;\ntypedef Skeleton::edge_descriptor\t\t\t\t\t\t\t\t\t\tSkeleton_edge;\n/// Define the maps\ntypedef std::map<vertex_descriptor, std::size_t>\t\t\t\t\t\tVertex_id_map;\ntypedef std::map<halfedge_descriptor, std::size_t>\t\t\t\t\t\tHedge_id_map;\ntypedef boost::associative_property_map<Vertex_id_map>\t\t\t\t\tVertex_id_pmap;\ntypedef boost::associative_property_map<Hedge_id_map>\t\t\t\t\tHedge_id_pmap;\ntypedef CGAL::Surface_mesh_deformation<Polyhedron, CGAL::Default, CGAL::Default, CGAL::SRE_ARAP>\tSurface_mesh_deformation;\n//typedef CGAL::Polyhedron_3<Kernel, CGAL::Polyhedron_items_3, CGAL::HalfedgeDS_list>       CgalPolyhedron;\n//typedef CGAL::Surface_mesh<Kernel::Point_3> SM;\n\n/// Property map associating a facet with an integer as id to an\n/// element in a vector stored internally\ntemplate<class ValueType>\nstruct Facet_with_id_pmap\n\t: public boost::put_get_helper<ValueType&,\n\tFacet_with_id_pmap<ValueType> >\n{\n\ttypedef face_descriptor key_type;\n\ttypedef ValueType value_type;\n\ttypedef value_type& reference;\n\ttypedef boost::lvalue_property_map_tag category;\n\tFacet_with_id_pmap(\n\t\tstd::vector<ValueType>& internal_vector\n\t) : internal_vector(internal_vector) { }\n\treference operator[](key_type key) const\n\t{\n\t\treturn internal_vector[key->id()];\n\t}\nprivate:\n\tstd::vector<ValueType>& internal_vector;\n};\n\n/// only needed for the display of the skeleton as maximal polylines\nstruct Display_polylines\n{\n\tconst Skeleton& skeleton;\n\tstd::ofstream& out;\n\tint polyline_size;\n\tstd::stringstream sstr;\n\n\tDisplay_polylines(const Skeleton& skeleton, std::ofstream& out)\n\t\t: skeleton(skeleton), out(out)\n\t{}\n\tvoid start_new_polyline() {\n\t\tpolyline_size = 0;\n\t\tsstr.str(\"\");\n\t\tsstr.clear();\n\t}\n\tvoid add_node(Skeleton_vertex v) {\n\t\t++polyline_size;\n\t\tsstr << \" \" << skeleton[v].point;\n\n\t}\n\tvoid end_polyline()\n\t{\n\t\tout << polyline_size << sstr.str() << \"\\n\";\n\t}\n};\n\n/// Collect the vertices which are at distance less or equal to k\n/// from the vertex v in the graph of vertices connected by the edges of P\nstd::vector<vertex_descriptor> extract_k_ring(const Polyhedron &P, vertex_descriptor v, int k)\n{\n\tstd::map<vertex_descriptor, int>  D;\n\tstd::vector<vertex_descriptor>    Q;\n\tQ.push_back(v); D[v] = 0;\n\tstd::size_t current_index = 0;\n\tint dist_v;\n\twhile (current_index < Q.size() && (dist_v = D[Q[current_index]]) < k) {\n\t\tv = Q[current_index++];\n\t\tout_edge_iterator e, e_end;\n\t\tfor (boost::tie(e, e_end) = out_edges(v, P); e != e_end; e++)\n\t\t{\n\t\t\thalfedge_descriptor he = halfedge(*e, P);\n\t\t\tvertex_descriptor new_v = target(he, P);\n\t\t\tif (D.insert(std::make_pair(new_v, dist_v + 1)).second) {\n\t\t\t\tQ.push_back(new_v);\n\t\t\t}\n\t\t}\n\t}\n\treturn Q;\n}\n\nvoid framebuffer_size_callback(GLFWwindow* window, int width, int height);\nvoid mouse_callback(GLFWwindow* window, double xpos, double ypos);\nvoid scroll_callback(GLFWwindow* window, double xoffset, double yoffset);\nvoid processInput(GLFWwindow *window);\n\n/// settings\nconst unsigned int SCR_WIDTH = 1200;\nconst unsigned int SCR_HEIGHT = 800;\nbool blinn = false;\nbool blinnKeyPressed = false;\n\n/// camera\nCamera camera(glm::vec3(-3.0f, 5.0f, 20.0f));\nfloat lastX = SCR_WIDTH / 2.0f;\nfloat lastY = SCR_HEIGHT / 2.0f;\nbool firstMouse = true;\n\n/// timing\nfloat deltaTime = 0.0f;\nfloat lastFrame = 0.0f;\n\n/// lighting\nglm::vec3 lightPos(0.0f, 10.0f, 0.0f);\n\nbool skeletonWindowFlag = false;\n\nstd::vector<GLfloat> vectorOfEdges;\nstd::vector<Polyhedron> vectorOfSegments;\nstd::vector<Model> vectorOfModelsSegments;\nstd::vector<glm::vec3> vectorOfPosition;\nstd::vector<glm::vec3> vectorOfRotation;\nstd::vector<glm::vec3> vectorOfScale;\nstd::vector<SurfaceMesh> vectorOfKeyframes;\nstd::vector<const aiScene*> vectorOfAiScenes;\nstd::vector<Pwn> points;\n\nGLuint textureTree = 0;\nGLuint textureNormalTree = 0;\nGLuint imageModelTreeSimple = 0;\nGLuint imageModelPinus = 0;\nGLuint imageModelOak = 0;\nModel* modelLoaded;\nint numberOfModelLoaded = 0;\nPolyhedron tmesh;\nSkeleton skeleton;\nint numberOfSegments;\n\n\nvoid loadModelImages()\n{\n\tint imageModelTreeSimpleWidth = 0;\n\tint imageModelTreeSimpleHeight = 0;\n\n\tint imageModelTreePinusWidth = 0;\n\tint imageModelTreePinusHeight = 0;\n\n\tint imageModelTreeOakWidth = 0;\n\tint imageModelTreeOakHeight = 0;\n\n\n\tbool result0 = Image::LoadTextureFromFile(\"resources/images/treegrow.png\", &imageModelTreeSimple, &imageModelTreeSimpleWidth, &imageModelTreeSimpleHeight);\n\tIM_ASSERT(result0);\n\tbool result1 = Image::LoadTextureFromFile(\"resources/images/pinus.png\", &imageModelPinus, &imageModelTreePinusWidth, &imageModelTreePinusHeight);\n\tIM_ASSERT(result1);\n\tbool result2 = Image::LoadTextureFromFile(\"resources/images/oak.png\", &imageModelOak, &imageModelTreeOakWidth, &imageModelTreeOakHeight);\n\tIM_ASSERT(result2);\n\n\tint textureNormalTreeWidth = 0;\n\tint textureNormalTreeHeight = 0;\n\tbool result3 = Image::LoadTextureFromFile(\"resources/textures/worn/normal.png\", &textureNormalTree, &textureNormalTreeWidth, &textureNormalTreeHeight);\n\tIM_ASSERT(result3);\n\n\tint textureTreeWidth = 0;\n\tint textureTreeHeight = 0;\n\tbool result4 = Image::LoadTextureFromFile(\"resources/textures/worn/albedo.png\", &textureTree, &textureTreeWidth, &textureTreeHeight);\n\tIM_ASSERT(result4);\n}\n\n\nvoid loadModel(const int &numberModel)\n{\n\tif (numberModel == 1)\n\t{\n\t\tmodelLoaded = new Model(\"resources/treegrow_materials/treegrow_materials.obj\");\n\t\tcamera = glm::vec3(-3.0f, 5.0f, 20.0f);\n\t}\n\telse if (numberModel == 2)\n\t{\n\t\tmodelLoaded = new Model(\"resources/treegrow_pinus/pinus_final.obj\");\n\t\tcamera = glm::vec3(-2.0f, 4.0f, 15.0f);\n\t}\n\telse if (numberModel == 3)\n\t{\n\t\tmodelLoaded = new Model(\"resources/treegrow_oak/oak_tree.obj\");\n\t\tcamera = glm::vec3(-3.0f, 5.0f, 20.0f);\n\t}\n}\n\nbool generateSkeleton(const int &numberModel)\n{\n\t/// modelos em off para utilizacao da CGAL\n\tstd::ifstream* input;\n\tif (numberModel == 1)\n\t{\n\t\tinput = new std::ifstream(\"resources/treegrow_materials/treegrow_materials.off\");\n\t\tif (!*input || !(*input >> tmesh) || tmesh.is_empty())\n\t\t{\n\t\t\tstd::cerr << \"Cannot open file.off\" << std::endl;\n\t\t\treturn EXIT_FAILURE;\n\t\t}\n\t}\n\tif (numberModel == 2)\n\t{\n\t\tinput = new std::ifstream(\"resources/treegrow_pinus/pinus_final.off\");\n\t\tif (!*input || !(*input >> tmesh) || tmesh.is_empty())\n\t\t{\n\t\t\tstd::cerr << \"Cannot open file.off\" << std::endl;\n\t\t\treturn EXIT_FAILURE;\n\t\t}\n\t}\n\tif (numberModel == 3)\n\t{\n\t\tinput = new std::ifstream(\"resources/treegrow_oak/oak_tree.off\");\n\t\tif (!*input || !(*input >> tmesh) || tmesh.is_empty())\n\t\t{\n\t\t\tstd::cerr << \"Cannot open file.off\" << std::endl;\n\t\t\treturn EXIT_FAILURE;\n\t\t}\n\t}\n\n\tif (!CGAL::is_closed(tmesh))\n\t{\n\t\treturn EXIT_FAILURE;\n\t}\n\tif (!CGAL::is_triangle_mesh(tmesh))\n\t{\n\t\tstd::cout << \"Input geometry is not triangulated.\" << std::endl;\n\t\tstd::cout << \"Tring triangulated Input geometry \" << std::endl;\n\t\tCGAL::Polygon_mesh_processing::triangulate_faces(tmesh);\n\t\tif (!CGAL::is_triangle_mesh(tmesh))\n\t\t{\n\t\t\treturn EXIT_FAILURE;\n\t\t}\n\t}\n\n\t/// Generate skeleton\n\tCGAL::extract_mean_curvature_flow_skeleton(tmesh, skeleton);\n\n\tvectorOfEdges.clear();\n\tBOOST_FOREACH(Skeleton_edge e, edges(skeleton))\n\t{\n\t\tconst Point& s = skeleton[source(e, skeleton)].point;\n\t\tconst Point& t = skeleton[target(e, skeleton)].point;\n\t\tvectorOfEdges.push_back(s.x());\n\t\tvectorOfEdges.push_back(s.y());\n\t\tvectorOfEdges.push_back(s.z());\n\t\tvectorOfEdges.push_back(t.x());\n\t\tvectorOfEdges.push_back(t.y());\n\t\tvectorOfEdges.push_back(t.z());\n\t}\n\tskeletonWindowFlag = true;\n\treturn true;\n}\n\nbool generateSegments(const int &numberModel)\n{\n\t/// init the polyhedron simplex indices\n\tCGAL::set_halfedgeds_items_id(tmesh);\n\t//for each input vertex compute its distance to the skeleton\n\tstd::vector<double> distances(num_vertices(tmesh));\n\tBOOST_FOREACH(Skeleton_vertex v, vertices(skeleton))\n\t{\n\t\tconst Point& skel_pt = skeleton[v].point;\n\t\tBOOST_FOREACH(vertex_descriptor mesh_v, skeleton[v].vertices)\n\t\t{\n\t\t\tconst Point& mesh_pt = mesh_v->point();\n\t\t\tdistances[mesh_v->id()] = std::sqrt(CGAL::squared_distance(skel_pt, mesh_pt));\n\t\t}\n\t}\n\t\n\t/// create a property-map for sdf values\n\tstd::vector<double> sdf_values(num_faces(tmesh));\n\tFacet_with_id_pmap<double> sdf_property_map(sdf_values);\n\t/// compute sdf values with skeleton\n\t\n\tif (numberModel == 1)\n\t{\n\t\tdouble dist = 0;\n\t\tBOOST_FOREACH(face_descriptor f, faces(tmesh))\n\t\t{\n\t\t\tBOOST_FOREACH(halfedge_descriptor hd, halfedges_around_face(halfedge(f, tmesh), tmesh))\n\t\t\t\tdist += distances[target(hd, tmesh)->id()];\n\t\t\tsdf_property_map[f] = dist / 3.;\n\t\t}\n\t}\n\telse\n\t{\n\t\t// create a property-map for SDF values\n\t\ttypedef std::map<face_descriptor, double> Facet_double_map;\n\t\tFacet_double_map internal_sdf_map;\n\t\tboost::associative_property_map<Facet_double_map> sdf_property_map(internal_sdf_map);\n\t\t// compute SDF values using default parameters for number of rays, and cone angle\n\t\tCGAL::sdf_values(tmesh, sdf_property_map);\n\t\t// create a property-map for segment-ids\n\t\ttypedef std::map<face_descriptor, std::size_t> Facet_int_map;\n\t\tFacet_int_map internal_segment_map;\n\t\tboost::associative_property_map<Facet_int_map> segment_property_map(internal_segment_map);\n\n\n\t\t/// segment the mesh using default parameters for number of levels, and smoothing lambda\n\t\t/// Any other scalar values can be used instead of using SDF values computed using the CGAL function\n\t\tstd::size_t number_of_segments = CGAL::segmentation_from_sdf_values(tmesh, sdf_property_map, segment_property_map);\n\t\tstd::cout << \"Number of segments: \" << number_of_segments << \"\\n\";\n\t\ttypedef CGAL::Face_filtered_graph<Polyhedron> Filtered_graph;\n\t\t/// print area of each segment and then put it in a Mesh and print it in an OFF file\n\t\tFiltered_graph segment_mesh(tmesh, 0, segment_property_map);\n\t\tvectorOfSegments.clear();\n\n\t\tfor (std::size_t id = 0; id < number_of_segments; ++id)\n\t\t{\n\t\t\tif (id > 0)\n\t\t\t\tsegment_mesh.set_selected_faces(id, segment_property_map);\n\t\t\tPolyhedron mesh_out;\n\t\t\tCGAL::copy_face_graph(segment_mesh, mesh_out);\n\t\t\tstd::ostringstream oss;\n\t\t\toss << \"resources/segments/Segment_\" << id << \".off\";\n\t\t\tstd::ofstream os(oss.str().data());\n\t\t\tos << mesh_out;\n\t\t\tvectorOfSegments.push_back(mesh_out);\n\t\t}\n\t\treturn true;\n\t}\n\n\t/// post-process the sdf values\n\tCGAL::sdf_values_postprocessing(tmesh, sdf_property_map);\n\t/// create a property-map for segment-ids (it is an adaptor for this case)\n\tstd::vector<std::size_t> segment_ids(num_faces(tmesh));\n\tFacet_with_id_pmap<std::size_t> segment_property_map(segment_ids);\n\n\t/// segment the mesh using default parameters for number of levels, and smoothing lambda\n\t/// Any other scalar values can be used instead of using SDF values computed using the CGAL function\n\tstd::size_t number_of_segments = CGAL::segmentation_from_sdf_values(tmesh, sdf_property_map, segment_property_map);\n\tstd::cout << \"Number of segments: \" << number_of_segments << \"\\n\";\n\ttypedef CGAL::Face_filtered_graph<Polyhedron> Filtered_graph;\n\t/// print area of each segment and then put it in a Mesh and print it in an OFF file\n\tFiltered_graph segment_mesh(tmesh, 0, segment_property_map);\n\tvectorOfSegments.clear();\n\tfor (std::size_t id = 0; id < number_of_segments; ++id)\n\t{\n\t\tif (id > 0)\n\t\t\tsegment_mesh.set_selected_faces(id, segment_property_map);\n\t\tPolyhedron mesh_out;\n\t\tCGAL::copy_face_graph(segment_mesh, mesh_out);\n\t\tstd::ostringstream oss;\n\t\toss << \"resources/segments/Segment_\" << id << \".off\";\n\t\tstd::ofstream os(oss.str().data());\n\t\tos << mesh_out;\n\t\tvectorOfSegments.push_back(mesh_out);\n\t}\n\treturn true;\n}\n\nvoid loadSegments()\n{\n\tnumberOfSegments = vectorOfSegments.size();\n\tvectorOfPosition.reserve(vectorOfSegments.size());\n\tglm::vec3 vec3Position(0.0f, 0.0f, 0.0f);\n\tvectorOfRotation.reserve(vectorOfSegments.size());\n\tglm::vec3 vec3Rotation(0.0f, 1.0f, 0.0f);\n\tvectorOfScale.reserve(vectorOfSegments.size());\n\tglm::vec3 vec3Scale(1.0f, 1.0f, 1.0f);\n\tModel* modelSegment;\n\tfor (size_t i = 0; i < vectorOfSegments.size(); ++i)\n\t{\n\t\tvectorOfPosition.push_back(vec3Position);\n\t\tvectorOfRotation.push_back(vec3Rotation);\n\t\tvectorOfScale.push_back(vec3Scale);\n\t\tstring path = \"resources/segments/Segment_\" + std::to_string(i) + \".off\";\n\t\tmodelSegment = new Model(path);\n\t\tvectorOfModelsSegments.push_back(*modelSegment);\n\t}\n}\n\n/// ------------------------------------------------------------------ INT MAIN ----------------------------------------------------------------- ///\nint main()\n{\n\t/// glfw: initialize and configure\n\tglfwInit();\n\tglfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);\n\tglfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);\n\tglfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);\n\n#ifdef __APPLE__\n\tglfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // uncomment this statement to fix compilation on OS X\n#endif\n\n/// glfw window creation\n\tGLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, \"TreeGrow\", NULL, NULL);\n\tif (window == NULL)\n\t{\n\t\tstd::cout << \"Failed to create GLFW window\" << std::endl;\n\t\tglfwTerminate();\n\t\treturn -1;\n\t}\n\n\tglfwMakeContextCurrent(window);\n\tglfwSetFramebufferSizeCallback(window, framebuffer_size_callback);\n\t//glfwSetCursorPosCallback(window, mouse_callback);\n\tglfwSetScrollCallback(window, scroll_callback);\n\n\t/// tell GLFW to capture our mouse\n\tglfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);\n\tglewExperimental = true;\n\tglewInit();\n\n\t/// configure global opengl state\n\tglEnable(GL_DEPTH_TEST);\n\n\t/// build and compile shaders\n\tShader lightShader(\"VertexShader.glsl\", \"FragmentShader.glsl\");\n\n\tGLuint vertexArrayBones, vertexBufferBones;\n\tglLineWidth(2.0f);\n\tglGenVertexArrays(1, &vertexArrayBones);\n\tglGenBuffers(1, &vertexBufferBones);\n\tglBindVertexArray(vertexArrayBones);\n\tglBindBuffer(GL_ARRAY_BUFFER, vertexBufferBones);\n\n\t///Initialize ImGUI\n\tImGui::CreateContext();\n\tImGuiIO& io = ImGui::GetIO(); (void)io;\n\tio.MouseDrawCursor = true;\n\t//io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;  // Enable Keyboard Controls\n\t//io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad;   // Enable Gamepad Controls\n\tImGui_ImplGlfwGL3_Init(window, true);\n\n\t/// Setup style\n\tImGui::StyleColorsDark();\n\n\t/// shader configuration\n\tlightShader.use();\n\tlightShader.setInt(\"material.diffuse\", 0);\n\tlightShader.setInt(\"material.specular\", 0);\n\n\n\t////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\tbool showWindowModelsFlag = false;\n\tbool imageModelsLoadedFlag = false;\n\tbool generateSkeletonFlag = false;\n\tbool showModelFlag = false;\n\tbool showMenuSegments = false;\n\tbool generateSegmentsFlag = false;\n\tbool showTriangulate = false;\n\tbool loadSegmentsFlag = false;\n\tbool exportKeyFrameFlag = false;\n\tbool showTextKeyFrames = false;\n\tbool exporterDaeFlag = false;\n\tint sizeKeyFramesSaved = 0;\n\n\n\t/// -----------------------------------------------------------------   RENDER LOOP -----------------------------------------------------------/// \n\twhile (!glfwWindowShouldClose(window))\n\t{\n\t\tglfwPollEvents();\n\t\tImGui_ImplGlfwGL3_NewFrame();\n\t\t/// per-frame time logic\n\t\tfloat currentFrame = glfwGetTime();\n\t\tdeltaTime = currentFrame - lastFrame;\n\t\tlastFrame = currentFrame;\n\t\t/// input\n\t\tprocessInput(window);\n\t\t/// render\n\t\t// ------\n\t\tglClearColor(0.3f, 0.3f, 0.3f, 1.0f);\n\t\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n\t\t/// be sure to activate shader when setting uniforms/drawing objects\n\t\tlightShader.use();\n\t\tlightShader.setVec3(\"light.direction\", -0.2f, -1.0f, -0.3f);\n\t\tlightShader.setVec3(\"viewPos\", camera.Position);\n\n\t\t/// light properties\n\t\tlightShader.setVec3(\"light.ambient\", 0.2f, 0.2f, 0.2f);\n\t\tlightShader.setVec3(\"light.diffuse\", 0.5f, 0.5f, 0.5f);\n\t\tlightShader.setVec3(\"light.specular\", 1.0f, 1.0f, 1.0f);\n\n\t\t/// material properties\n\t\tlightShader.setFloat(\"material.shininess\", 32.0f);\n\n\t\t/// view/projection transformations\n\t\tglm::mat4 projection = glm::perspective(glm::radians(camera.Zoom), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f);\n\t\tglm::mat4 view = camera.GetViewMatrix();\n\t\tlightShader.setMat4(\"projection\", projection);\n\t\tlightShader.setMat4(\"view\", view);\n\n\t\t/// render the loaded model\n\t\tglm::mat4 model = glm::mat4(1.0f);\n\t\tmodel = glm::translate(model, glm::vec3(0.0f, 0.0f, 0.0f)); // translate it down so it's at the center of the scene\n\t\tmodel = glm::scale(model, glm::vec3(1.0, 1.0, 1.0));\t// it's a bit too big for our scene, so scale it down\n\t\tlightShader.setMat4(\"model\", model);\n\n\t\t/// draw model\n\t\tif (numberOfModelLoaded != 0 && showModelFlag)\n\t\t{\n\t\t\tglBindTexture(GL_TEXTURE_2D, textureTree);\n\t\t\tmodelLoaded->Draw(lightShader);\n\t\t}\n\n\t\tGLuint vertexArray, vertexBuffer;\n\t\tglLineWidth(1.0f);\n\t\tglGenVertexArrays(1, &vertexArray);\n\t\tglGenBuffers(1, &vertexBuffer);\n\t\tglBindVertexArray(vertexArray);\n\t\tglBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);\n\n\t\tbool treeGrowFlag = true;\n\t\tInterface::setStyleImGui();\n\t\tImGui::Begin(\"TreeGrow\", &treeGrowFlag, ImGuiWindowFlags_MenuBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove);\n\n\t\tif (ImGui::BeginMenuBar())\n\t\t{\n\t\t\tif (ImGui::BeginMenu(\"Arquivo\"))\n\t\t\t{\n\t\t\t\tif (ImGui::MenuItem(\"Abrir modelo 3D\", \"Ctrl+O\"))\n\t\t\t\t{\n\t\t\t\t\tshowWindowModelsFlag = true;\n\t\t\t\t\tshowModelFlag = true;\n\t\t\t\t}\n\t\t\t\tImGui::EndMenu();\n\t\t\t}\n\t\t\tImGui::EndMenuBar();\n\t\t}\n\t\tif (showWindowModelsFlag)\n\t\t{\n\t\t\tif (!imageModelsLoadedFlag)\n\t\t\t{\n\t\t\t\tloadModelImages();\n\t\t\t\timageModelsLoadedFlag = true;\n\t\t\t}\n\n\t\t\tImGui::Begin(\"Modelos 3D disponiveis:\", &showWindowModelsFlag, ImVec2(300, 100), 0.9f, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize);\n\t\t\tif (ImGui::ImageButton((void*)(intptr_t)imageModelTreeSimple, ImVec2(200, 200)))\n\t\t\t{\n\t\t\t\tnumberOfModelLoaded = 1;\n\t\t\t\t//ImportOBJ::loadModel(numberOfModelLoaded, modelLoaded);\n\t\t\t\tloadModel(numberOfModelLoaded);\n\t\t\t\tshowWindowModelsFlag = false;\n\t\t\t}\n\t\t\tImGui::SameLine();\n\t\t\tif (ImGui::ImageButton((void*)(intptr_t)imageModelPinus, ImVec2(200, 200)))\n\t\t\t{\n\t\t\t\tnumberOfModelLoaded = 2;\n\t\t\t\t//ImportOBJ::loadModel(numberOfModelLoaded, modelLoaded);\n\t\t\t\tloadModel(numberOfModelLoaded);\n\t\t\t\tshowWindowModelsFlag = false;\n\t\t\t}\n\t\t\tImGui::SameLine();\n\t\t\tif (ImGui::ImageButton((void*)(intptr_t)imageModelOak, ImVec2(200, 200)))\n\t\t\t{\n\t\t\t\tnumberOfModelLoaded = 3;\n\t\t\t\t//ImportOBJ::loadModel(numberOfModelLoaded, modelLoaded);\n\t\t\t\tloadModel(numberOfModelLoaded);\n\t\t\t\tshowWindowModelsFlag = false;\n\t\t\t}\n\t\t\tImGui::End();\n\t\t}\n\n\t\tImGui::Text(\"Escolha um arquivo! \");\n\t\tImGui::Text(\"Arquivo selecionado : \");\n\n\t\tif (numberOfModelLoaded == 1)\n\t\t{\n\t\t\tImGui::SameLine();\n\t\t\tImGui::Text(\"Arvore Simples\");\n\t\t}\n\t\telse if (numberOfModelLoaded == 2)\n\t\t{\n\t\t\tImGui::SameLine();\n\t\t\tImGui::Text(\"Pinheiro\");\n\t\t}\n\t\telse if (numberOfModelLoaded == 3)\n\t\t{\n\t\t\tImGui::SameLine();\n\t\t\tImGui::Text(\"Carvalho\");\n\t\t}\n\t\tif (numberOfModelLoaded != 0)\n\t\t{\n\t\t\tImGui::Checkbox(\"Ver Triangularizacao\", &showTriangulate);\n\t\t\tif (showTriangulate)\n\t\t\t{\n\t\t\t\tglPolygonMode(GL_FRONT_AND_BACK, GL_LINE);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tglPolygonMode(GL_FRONT_AND_BACK, GL_FILL);\n\t\t\t}\n\n\t\t\tif (ImGui::Button(\"Gerar o Esqueleto da Arvore\"))\n\t\t\t{\n\t\t\t\tgenerateSkeletonFlag = true;\n\t\t\t}\n\t\t}\n\t\tif (generateSkeletonFlag)\n\t\t{\n\t\t\tif (generateSkeleton(numberOfModelLoaded))\n\t\t\t{\n\t\t\t\tgenerateSkeletonFlag = false;\n\t\t\t}\n\t\t}\n\t\tif (skeletonWindowFlag)\n\t\t{\n\t\t\t//ImGui::Begin(\"Esqueleto da Arvore\", &generateSkeletonFlag, ImVec2(300, 100), 0.9f);\n\t\t\tshowModelFlag = false;\n\t\t\tglBufferData(GL_ARRAY_BUFFER, vectorOfEdges.size() * sizeof(GLfloat), vectorOfEdges.data(), GL_STATIC_DRAW);\n\t\t\tglVertexAttribPointer(\n\t\t\t\t0,                  // attribute 0. No particular reason for 0, but must match the layout in the shader.\n\t\t\t\t3,                  // size\n\t\t\t\tGL_FLOAT,           // type\n\t\t\t\tGL_FALSE,           // normalized?\n\t\t\t\t0, // stride\n\t\t\t\t(GLvoid*)0            // array buffer offset\n\t\t\t);\n\t\t\t//Sends the sprite's color information in the the shader\n\t\t\tlightShader.setVec4(\"uniformColor\", 0.5f, 0.5, 0.5, 1.0f);\n\t\t\t//lightShader.use();\n\t\t\t//Activates Vertex Position Information\n\t\t\tglEnableVertexAttribArray(0);\n\t\t\t// Draw the line\n\t\t\tglDrawArrays(GL_LINES, 0, vectorOfEdges.size() * sizeof(GLfloat));\n\t\t\tglBindBuffer(GL_ARRAY_BUFFER, 0);\n\t\t\tglBindVertexArray(0);\n\t\t\t//ImGui::End();\n\t\t\tshowMenuSegments = true;\n\t\t}\n\n\t\tif (showMenuSegments)\n\t\t{\n\t\t\tif (ImGui::Button(\"Separar a malha em segmentos\"))\n\t\t\t{\n\t\t\t\tlightShader.setVec4(\"uniformColor\", 0.0f, 0.0f, 0.0f, 1.0f);\n\t\t\t\tskeletonWindowFlag = false;\n\t\t\t\tshowModelFlag = true;\n\t\t\t\tgenerateSegments(numberOfModelLoaded);\n\t\t\t\tgenerateSegmentsFlag = true;\n\t\t\t\tloadSegmentsFlag = true;\n\t\t\t}\n\t\t}\n\t\tif (generateSegmentsFlag)\n\t\t{\n\t\t\tlightShader.setVec4(\"uniformColor\", 0.5f, 0.5, 0.5, 1.0f);\n\t\t\tif (loadSegmentsFlag)\n\t\t\t{\n\t\t\t\tloadSegments();\n\t\t\t\tloadSegmentsFlag = false;\n\t\t\t\tshowModelFlag = false;\n\t\t\t}\n\t\t\t/// draw segments\n\t\t\tfor (int i = 0; i < vectorOfSegments.size(); ++i)\n\t\t\t{\n\t\t\t\tglm::mat4 model1 = glm::mat4(1.0f);\n\t\t\t\tmodel1 = glm::translate(model1, vectorOfPosition[i]); // translate it down so it's at the center of the scene\n\t\t\t\tmodel1 = glm::rotate(model1, 3.14f, vectorOfRotation[i]);\t// it's a bit too big for our scene, so scale it down\n\t\t\t\tmodel1 = glm::scale(model1, vectorOfScale[i]);\t// it's a bit too big for our scene, so scale it down\n\t\t\t\tlightShader.setMat4(\"model\", model1);\n\t\t\t\tvectorOfModelsSegments[i].Draw(lightShader);\n\t\t\t}\n\n\t\t\tfor (int i = 0; i < vectorOfSegments.size(); ++i)\n\t\t\t{\n\t\t\t\tInterface::showSegments(i, vectorOfPosition, vectorOfScale);\n\t\t\t}\n\t\t\texportKeyFrameFlag = true;\n\t\t}\n\t\tif (exportKeyFrameFlag)\n\t\t{\n\t\t\tif (ImGui::Button(\"Exportar KeyFrame\"))\n\t\t\t{\n\t\t\t\t\n\t\t\t\tshowTextKeyFrames = true;\n\t\t\t\tSurfaceMesh surfaceMeshOut;\n\t\t\t\tbool valid_union;\n\t\t\t\tdouble valueScale = 0;\n\t\t\t\tfor (int i = 0; i < vectorOfSegments.size() - 1; ++i)\n\t\t\t\t{\n\t\t\t\t\t/// Aplicar scala pelo valor da GLM de scala\n\t\t\t\t\tif (i == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tvalueScale = vectorOfScale[i].x;\n\t\t\t\t\t\tAff_transformation_3 scale(CGAL::SCALING, valueScale);\n\t\t\t\t\t\tSurfaceMesh smOut1;\n\t\t\t\t\t\tCGAL::copy_face_graph(vectorOfSegments[i], smOut1);\n\t\t\t\t\t\tCGAL::Polygon_mesh_processing::transform(scale, smOut1);\n\n\t\t\t\t\t\tvalueScale = vectorOfScale[i + 1].x;\n\t\t\t\t\t\tAff_transformation_3 scale1(CGAL::SCALING, valueScale);\n\t\t\t\t\t\tSurfaceMesh smOut2;\n\t\t\t\t\t\tCGAL::copy_face_graph(vectorOfSegments[i + 1], smOut2);\n\t\t\t\t\t\tCGAL::Polygon_mesh_processing::transform(scale1, smOut2);\n\t\t\t\t\t\tvalid_union = CGAL::Polygon_mesh_processing::corefine_and_compute_union(smOut1, smOut2, surfaceMeshOut);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tvalueScale = vectorOfScale[i + 1].x;\n\t\t\t\t\t\tAff_transformation_3 scale(CGAL::SCALING, valueScale);\n\t\t\t\t\t\tSurfaceMesh smOut2;\n\t\t\t\t\t\tCGAL::copy_face_graph(vectorOfSegments[i + 1], smOut2);\n\t\t\t\t\t\tCGAL::Polygon_mesh_processing::transform(scale, smOut2);\n\t\t\t\t\t\tvalid_union = CGAL::Polygon_mesh_processing::corefine_and_compute_union(surfaceMeshOut, smOut2, surfaceMeshOut);\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t\tBOOST_FOREACH(SFhalfedge_descriptor h, halfedges(surfaceMeshOut))\n\t\t\t\t{\n\t\t\t\t\tif (CGAL::is_border(h, surfaceMeshOut))\n\t\t\t\t\t{\n\t\t\t\t\t\tstd::vector<SFface_descriptor>  patch_facets;\n\t\t\t\t\t\tCGAL::Polygon_mesh_processing::triangulate_hole(\n\t\t\t\t\t\t\tsurfaceMeshOut,\n\t\t\t\t\t\t\th,\n\t\t\t\t\t\t\tstd::back_inserter(patch_facets),\n\t\t\t\t\t\t\tCGAL::Polygon_mesh_processing::parameters::vertex_point_map(get(CGAL::vertex_point, surfaceMeshOut)).geom_traits(Kernel()));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (valid_union)\n\t\t\t\t{\n\t\t\t\t\t//\tstd::cout << \"Union was successfully computed\\n\";\n\t\t\t\t\tstring path = \"resources/keyframes/keyframe_\" + std::to_string(sizeKeyFramesSaved) + \".off\";\n\t\t\t\t\tstd::ofstream output(path);\n\t\t\t\t\toutput << surfaceMeshOut;\n\t\t\t\t\t//vectorOfKeyframes.push_back(surfaceMeshOut);\n\t\t\t\t}\n\t\t\t\t++sizeKeyFramesSaved;\n\t\t\t}\n\t\t\tif (showTextKeyFrames)\n\t\t\t{\n\t\t\t\tfor (size_t i = 0; i < sizeKeyFramesSaved; ++i)\n\t\t\t\t{\n\t\t\t\t\tImGui::Text(\"KeyFrame: %d salvo\", i);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (ImGui::Button(\"Exportar formato DAE\"))\n\t\t\t{\n\t\t\t\tAssimp::Importer importer;\n\t\t\t\tAssimp::Exporter exporter;\n\t\t\t\t//aiAnimation* animation;\n\t\t\t\t//std::vector<SA::SkeletalModel> vectorOfSkeletals;\n\t\t\t\tstd::vector<const aiScene*> vectorOfkeyframes;\n\t\t\t\tSA::SkeletalModel g_AnimatedModel;\n\t\t\t\taiScene* AiScene = new aiScene();\n\t\t\t\tconst aiScene* exportAiScene = new aiScene();\n\t\t\t\tfor (size_t i = 0; i < sizeKeyFramesSaved; ++i)\n\t\t\t\t{\n\t\t\t\t\tstring path = \"resources/keyframes/keyframe_\" + std::to_string(i) + \".off\";\n\t\t\t\t\t//const aiScene* keyframe = importer.ReadFile(path, aiProcess_ValidateDataStructure);\n\t\t\t\t\t//vectorOfAiScenes.push_back(keyframe);\n\t\t\t\t\t//const aiScene* keyframe = importer.ReadFile(path, aiProcess_LimitBoneWeights | aiProcess_Triangulate | aiProcess_JoinIdenticalVertices | aiProcess_SortByPType);\n\t\t\t\t\texportAiScene = importer.ReadFile(path, aiProcess_LimitBoneWeights | aiProcess_Triangulate | aiProcess_JoinIdenticalVertices | aiProcess_SortByPType);\n\n\t\t\t\t\t//AssimpConverter::Convert(exportAiScene, g_AnimatedModel);\n\n\t\t\t\t\t{\n\n\t\t\t\t\t}\n\t\t\t\t\t//vectorOfSkeletals.push_back(g_AnimatedModel);\n\t\t\t\t\tvectorOfkeyframes.push_back(exportAiScene);\n\t\t\t\t}\n\n\t\t\t\t//for (size_t i = 0; i < sizeKeyFramesSaved; ++i)\n\t\t\t\t//{\n\t\t\t\t\t//vectorOfSkeletals[i].Update(i);\n\t\t\t\t//}\n\t\t\t\t//AiScene->mRootNode = vectorOfkeyframes[0]->mRootNode;\n\t\t\t\t//AiScene->mNumMeshes = vectorOfkeyframes.size();\n\n\t\t\t\t//for (size_t i = 0; i < vectorOfkeyframes.size(); ++i)\n\t\t\t\t//{\n\t\t\t\t//\tAiScene->mMeshes = vectorOfkeyframes[i]->mMeshes;\n\t\t\t\t//}\n\t\t\t\t//const aiScene* exportAiScene = AiScene;\n\t\t\t\texporter.Export(exportAiScene, \"collada\", \"resources/collada/treegrow.dae\");\n\t\t\t\texporterDaeFlag = true;\n\t\t\t}\n\t\t}\n\t\tif (exporterDaeFlag)\n\t\t{\n\t\t\tImGui::Text(\"Exportou o arquivo para: resources/collada/treegrow.dae\");\n\t\t}\n\t\t//ImGui::ShowDemoWindow();\n\t\tImGui::End();\n\n\t\t/// glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.)\n\t\tImGui::Render();\n\t\tImGui_ImplGlfwGL3_RenderDrawData(ImGui::GetDrawData());\n\t\tglfwSwapBuffers(window);\n\t}\n\n\t/// glfw: terminate, clearing all previously allocated GLFW resources.\n\tImGui_ImplGlfwGL3_Shutdown();\n\tImGui::DestroyContext();\n\tglfwTerminate();\n\treturn 0;\n}\n\n/// process all input: query GLFW whether relevant keys are pressed/released this frame and react accordingly\nvoid processInput(GLFWwindow *window)\n{\n\tif (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)\n\t\tglfwSetWindowShouldClose(window, true);\n\n\tif (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)\n\t\tcamera.ProcessKeyboard(FORWARD, deltaTime);\n\tif (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)\n\t\tcamera.ProcessKeyboard(BACKWARD, deltaTime);\n\tif (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)\n\t\tcamera.ProcessKeyboard(LEFT, deltaTime);\n\tif (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)\n\t\tcamera.ProcessKeyboard(RIGHT, deltaTime);\n}\n\n/// glfw: whenever the window size changed (by OS or user resize) this callback function executes\nvoid framebuffer_size_callback(GLFWwindow* window, int width, int height)\n{\n\t/// make sure the viewport matches the new window dimensions; note that width and \n\t/// height will be significantly larger than specified on retina displays.\n\tglViewport(0, 0, width, height);\n}\n\n/// glfw: whenever the mouse moves, this callback is called\nvoid mouse_callback(GLFWwindow* window, double xpos, double ypos)\n{\n\tif (firstMouse)\n\t{\n\t\tlastX = xpos;\n\t\tlastY = ypos;\n\t\tfirstMouse = false;\n\t}\n\tfloat xoffset = xpos - lastX;\n\tfloat yoffset = lastY - ypos; // reversed since y-coordinates go from bottom to top\n\tlastX = xpos;\n\tlastY = ypos;\n\tcamera.ProcessMouseMovement(xoffset, yoffset);\n}\n\n/// glfw: whenever the mouse scroll wheel scrolls, this callback is called\nvoid scroll_callback(GLFWwindow* window, double xoffset, double yoffset)\n{\n\tcamera.ProcessMouseScroll(yoffset);\n}", "meta": {"hexsha": "d3cd26b9fdcfda7df8dc3f54e20257e9e19e5d62", "size": 30787, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "TreeGrow ImGUI/Main.cpp", "max_stars_repo_name": "LucasGFAlves/Projeto-Final-I", "max_stars_repo_head_hexsha": "042b4a96ce8f02e7a9cb98cd51276596897ff530", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "TreeGrow ImGUI/Main.cpp", "max_issues_repo_name": "LucasGFAlves/Projeto-Final-I", "max_issues_repo_head_hexsha": "042b4a96ce8f02e7a9cb98cd51276596897ff530", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TreeGrow ImGUI/Main.cpp", "max_forks_repo_name": "LucasGFAlves/Projeto-Final-I", "max_forks_repo_head_hexsha": "042b4a96ce8f02e7a9cb98cd51276596897ff530", "max_forks_repo_licenses": ["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.7947310648, "max_line_length": 167, "alphanum_fraction": 0.7144249196, "num_tokens": 8451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936435, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.45016252846583615}}
{"text": "// By Magamedrasul Ibragimov\n\n#include <iostream>\n#include <gtest/gtest.h>\n\n#include <boost/filesystem.hpp>\n#include <boost/program_options.hpp>\n#include <boost/property_tree/ptree.hpp>\n#include <boost/property_tree/json_parser.hpp>\n#include <boost/algorithm/hex.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\n#include <nil/crypto3/algebra/pairing/bls12.hpp>\n#include <nil/crypto3/zk/snark/schemes/ppzksnark/r1cs_gg_ppzksnark.hpp>\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/crypto3/zk/snark/relations/constraint_satisfaction_problems/r1cs.hpp>\n\n#include <nil/crypto3/zk/components/hashes/knapsack/knapsack_component.hpp>\n#include <nil/crypto3/zk/components/hashes/hmac_component.hpp>\n\n#include <nil/crypto3/zk/snark/schemes/ppzksnark/r1cs_gg_ppzksnark/marshalling.hpp>\n\n#define PREIMAGE_SIZE 256\n#define HASHING_LIST_SIZE 4\n\nusing namespace nil::crypto3;\nusing namespace nil::crypto3::zk;\nusing namespace nil::marshalling;\nusing namespace components;\n\ntypedef algebra::curves::bls12<381> curve_type;\ntypedef typename curve_type::scalar_field_type field_type;\ntypedef zk::snark::r1cs_gg_ppzksnark<curve_type> scheme_type;\n\ntypedef verifier_input_serializer_tvm<scheme_type> serializer_tvm;\ntypedef verifier_input_deserializer_tvm<scheme_type> deserializer_tvm;\n\n// Knapsack hash size\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// Convert field_type::value_type to hex string\nstd::string field_element_to_hex(field_type::value_type element);\n\n// Convert hex string to field_type::value_type\nfield_type::value_type hex_to_field_element(const std::string& hex);\n\n// Returns hex string = knapsack hash of bit_vector \nstd::string knapsack_hash(const std::vector<bool>& bv);\n\n// Converts uint256_t to bit vector\nstd::vector<bool> number_to_binary(const multiprecision::uint256_t& preimage);\n\n// Deserializing vkey and pkey\nstd::vector<uint8_t> read_vector_from_disk(boost::filesystem::path file_path);\n\n// Serializing vkey and pkey\nvoid write_vector_to_disk(boost::filesystem::path file_path, const std::vector<uint8_t> &data);\n\n// Generating primary_input file with 4 hashes\nvoid write_primary_input(boost::filesystem::path file_path, const std::vector<std::string>& hashes);\n\n// Reading primary input from file\nstd::vector<field_type::value_type> read_primary_input(boost::filesystem::path file_path);\n\nscheme_type::proving_key_type get_pkey(boost::filesystem::path pkin);\nscheme_type::verification_key_type get_vkey( boost::filesystem::path vkin);\n\nint main(int argc, char *argv[]) {\n\n    boost::program_options::options_description options(\n        \"Knapsack-hash preimage knowledge proof generator / verifier\");\n        options.add_options()\n        (\"hash\", \"Generate public input (hash) from your secret (preimage)\")\n        (\"keys\", \"Generate proof key and verifier key\")\n        (\"proof\", \"Generate proof\")\n        (\"verify\", \"Verify proof\")\n        (\"test\", \"Run tests\");\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 (argc < 2) {\n        std::cout << options << std::endl;\n        return 0;\n    }\n\n    assert(argc == 2);\n\n    if (vm.count(\"test\")) {\n        ::testing::InitGoogleTest();\n        return RUN_ALL_TESTS();\n    }\n\n    // Primary input file generator (Knapsack hash)\n    // Also generates 3 more random hashes, needed for demonstration of PoM\n    if (vm.count(\"hash\")) {\n        multiprecision::uint256_t preimage;\n        uint seed;\n\n        std::cout << \"Enter secret number: \";\n        std::cin >> preimage;\n\n        boost::random::mt19937 rng(std::time(0));\n        boost::random::uniform_int_distribution<> my_rand(10000000, 99999999);\n\n        multiprecision::uint256_t rand1 = my_rand(rng);\n        multiprecision::uint256_t rand2 = my_rand(rng);\n        multiprecision::uint256_t rand3 = my_rand(rng);\n\n        std::string hash1 = knapsack_hash(number_to_binary(rand1));\n        std::string hash2 = knapsack_hash(number_to_binary(rand2));\n        std::string hash3 = knapsack_hash(number_to_binary(rand3));\n        std::string secret_hash = knapsack_hash(number_to_binary(preimage)); \n\n        boost::filesystem::path hout = \"./primary_input.json\";\n\n        write_primary_input(hout, {secret_hash, hash1, hash2, hash3});\n        std::cout << \"Hash of secret was written to \\\"./primary_input.json\\\" file\" << std::endl;\n\n        read_primary_input(hout);\n\n        return 0;\n    }\n\n    // Create blueprint and constraints\n    blueprint<field_type> bp;\n    \n    // Hash list - primary input\n    blueprint_variable_vector<field_type> hash_list;\n    hash_list.allocate(bp, HASHING_LIST_SIZE);\n\n    // Bool mask, needed for building constraint that secret hash is in hash_list (private intermediate var)\n    blueprint_variable_vector<field_type> bool_mask;\n    bool_mask.allocate(bp, HASHING_LIST_SIZE);\n\n    // Secret hash, for building constraint secret_hash = knapsack(preimage) (private intermediate var)\n    blueprint_variable<field_type> secret_hash;\n    secret_hash.allocate(bp);\n\n    // Preimage (auxilary input)\n    block_variable<field_type> secret(bp, PREIMAGE_SIZE);\n\n    bp.set_input_sizes(HASHING_LIST_SIZE);\n\n    // Generating constraints for bool mask\n    for (auto field_var: bool_mask) {\n        generate_boolean_r1cs_constraint<field_type>(bp, field_var);\n    }\n\n    // Constraints for checking that the secret_hash is in hash list\n    bp.add_r1cs_constraint(r1cs_constraint<field_type>(1, blueprint_sum<field_type>(bool_mask), 1));\n\n    for (int i = 0; i < HASHING_LIST_SIZE; i++) {\n        bp.add_r1cs_constraint(r1cs_constraint<field_type>(bool_mask[i], hash_list[i] - secret_hash, 0));\n    }\n\n    // Knapsack component constraint\n    knapsack_crh_with_field_out_component<field_type> \n                f(bp, PREIMAGE_SIZE, secret, blueprint_variable_vector<field_type>(1, secret_hash));\n    f.generate_r1cs_constraints();\n\n    // Keys generation\n    if (vm.count(\"keys\")) {\n        boost::filesystem::path pkout = \"./pk\", vkout = \"./vk\";\n        const snark::r1cs_constraint_system<field_type> constraint_system = bp.get_constraint_system();\n        const typename scheme_type::keypair_type keypair = snark::generate<scheme_type>(constraint_system);\n\n        std::cout << \"Keys generated (pkey - \\\"./pkey\\\", vkey - \\\"./vkey\\\")\" << std::endl;\n\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        return 0;\n    }\n\n    // Proof generation\n    if (vm.count(\"proof\")) {\n        multiprecision::uint256_t preimage;\n\n        std::cout << \"Enter secret (preimage of hash): \";\n        std::cin >> preimage;\n        \n        std::vector<bool> preimage_bv = number_to_binary(preimage);\n        field_type::value_type secret_hash_w = hex_to_field_element(knapsack_hash(preimage_bv));\n\n        boost::filesystem::path path = \"./primary_input.json\";\n        std::vector<field_type::value_type> hashes = read_primary_input(path);\n\n        // Generating witness\n\n        // Filling primary_input\n        for (int i = 0; i < HASHING_LIST_SIZE; i++) {\n            bp.val(hash_list[i]) = hashes[i];\n        }\n        \n        // Filling auxilary input and intermediate variables\n        secret.generate_r1cs_witness(preimage_bv);\n        f.generate_r1cs_witness();\n        bp.val(secret_hash) = secret_hash_w;\n\n        for (int i = 0; i < HASHING_LIST_SIZE; i++) {\n            if (hashes[i] == secret_hash_w) {\n                bp.val(bool_mask[i]) = field_type::value_type::one();\n                continue;\n            }\n            bp.val(bool_mask[i]) = field_type::value_type::zero();\n        }\n\n        assert(bp.is_satisfied());\n\n        // Deserializing pkey\n        boost::filesystem::path pkin = \"./pk\";\n        scheme_type::proving_key_type pkey = get_pkey(pkin);\n\n        std::cout << \"Prooving key was read from \\\"./pkey\\\"\" << std::endl;\n\n        std::cout << \"Start generating the proof\" << std::endl;\n        const typename scheme_type::proof_type proof = snark::prove<scheme_type>(pkey, bp.primary_input(), bp.auxiliary_input());\n\n        // Serializing proof\n        boost::filesystem::path proof_path = \"./proof\";\n        std::vector<std::uint8_t> proof_byteblob =\n            serializer_tvm::process(proof);\n\n        boost::filesystem::ofstream poutf(proof_path);\n        for (const auto &v : proof_byteblob) {\n            poutf << v;\n        } \n        poutf.close();\n\n        std::cout << \"Proof was written to \\\"./proof\\\" file\" << std::endl;\n\n        return 0;\n    }\n\n    // Verify proof\n    if (vm.count(\"verify\")) {\n        boost::filesystem::path path = \"./primary_input.json\";\n        std::vector<field_type::value_type> hashes = read_primary_input(path);\n        std::cout << \"Primary input was read from \\\"./primary_input.json\\\" file\" << std::endl;\n\n        // Filling primary_input\n        for (int i = 0; i < HASHING_LIST_SIZE; i++) {\n            bp.val(hash_list[i]) = hashes[i];\n        }\n\n        // Deserializing vkey\n        boost::filesystem::path vkin = \"./vk\";\n        scheme_type::verification_key_type vkey = get_vkey(vkin);\n        std::cout << \"Verification key was read from \\\"./vkey\\\" file\" << std::endl;\n\n        boost::filesystem::path proof_path = \"./proof\";\n        std::vector<uint8_t> proof_v = read_vector_from_disk(proof_path);\n\n        nil::marshalling::status_type proof_deserialize_status;\n        scheme_type::proof_type proof = deserializer_tvm::proof_process(\n            proof_v.begin(), proof_v.end(), proof_deserialize_status\n        );\n\n        if (proof_deserialize_status != nil::marshalling::status_type::success) {\n            std::cerr << \"Error: Could not deserialize verifying key\" << std::endl;\n            std::cerr << \"Status is:\" << static_cast<int>(proof_deserialize_status) << std::endl;\n            exit(-1);\n        }\n        std::cout << \"Proof was read from \\\"./proof\\\" file\" << std::endl;\n\n        bool verified = snark::verify<scheme_type>(vkey, bp.primary_input(), proof);\n        std::cout << std::endl << \"Verification status: \" << verified << std::endl;\n\n        return 0;\n    }\n    \n    return 0;\n}\n\n// ----------------------------------------------------------------------------------\n// ------------------------------MOVE TO UTILS.CPP-----------------------------------\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\nfield_type::value_type hex_to_field_element(const std::string& hex) {\n    std::vector<uint8_t> hash_bytes(modulus_chunks);\n    boost::algorithm::unhex(hex.begin(), hex.end(), hash_bytes.begin());\n\n    status_type status;\n    field_type::value_type result = \n        deserializer_tvm::field_type_process<field_type>(hash_bytes.begin(), hash_bytes.end(), status);\n\n    return result;\n}\n\nstd::string knapsack_hash(const std::vector<bool>& bv) {\n    field_type::value_type h = knapsack_crh_with_field_out_component<field_type>::get_hash(bv)[0];\n\n    return field_element_to_hex(h);\n}\n\nstd::vector<bool> number_to_binary(const multiprecision::uint256_t& preimage) {\n    std::vector<bool> result_i;\n    std::vector<bool> result(PREIMAGE_SIZE);\n\n    multiprecision::export_bits(preimage, std::back_inserter(result_i), 1);\n    std::swap_ranges(result.begin() + result.size() - result_i.size(), result.end(), result_i.begin());\n\n    return result;\n}\n\nstd::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    instream.close();\n    return data;\n}\n\nvoid 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    ostream.close();\n}\n\nvoid write_primary_input(boost::filesystem::path file_path, const std::vector<std::string>& hashes) {\n    boost::property_tree::ptree root;\n    root.put(\"hash1\", hashes[0]);\n    root.put(\"hash2\", hashes[1]);\n    root.put(\"hash3\", hashes[2]);\n    root.put(\"hash4\", hashes[3]);\n\n    boost::filesystem::ofstream ostream(file_path);\n    boost::property_tree::write_json(ostream, root);\n    ostream.close();\n}\n\nstd::vector<field_type::value_type> read_primary_input(boost::filesystem::path file_path) {\n    boost::filesystem::ifstream instream(file_path);\n\n    boost::property_tree::ptree root;\n    boost::property_tree::read_json(instream, root);\n    instream.close();\n\n    std::vector<std::string> stringHashes;\n\n    for (auto node: root) {\n        stringHashes.push_back(node.second.data());\n    }\n\n    std::vector<field_type::value_type> result(stringHashes.size());\n    for (int i = 0; i < result.size(); i++) {\n        result[i] = hex_to_field_element(stringHashes[i]);\n    }\n    \n    return result;\n}\n\nscheme_type::proving_key_type get_pkey(boost::filesystem::path pkin) {\n    std::vector<uint8_t> proving_key_byteblob = read_vector_from_disk(pkin);\n\n    nil::marshalling::status_type pk_deserialize_status;\n    scheme_type::proving_key_type proving_key =\n            deserializer_tvm::proving_key_process(proving_key_byteblob.begin(),\n                                                proving_key_byteblob.end(),\n                                                pk_deserialize_status);\n\n    if (pk_deserialize_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_deserialize_status) << std::endl;\n        exit(-1);\n    }\n\n    return proving_key;\n}\n\nscheme_type::verification_key_type get_vkey(boost::filesystem::path vkin) {\n    std::vector<uint8_t> verification_key_byteblob = read_vector_from_disk(vkin);\n\n    nil::marshalling::status_type vk_deserialize_status;\n    scheme_type::verification_key_type verification_key =\n            deserializer_tvm::verification_key_process(verification_key_byteblob.begin(),\n                                                verification_key_byteblob.end(),\n                                                vk_deserialize_status);\n\n    if (vk_deserialize_status != nil::marshalling::status_type::success) {\n        std::cerr << \"Error: Could not deserialize verifying key\" << std::endl;\n        std::cerr << \"Status is:\" << static_cast<int>(vk_deserialize_status) << std::endl;\n        exit(-1);\n    }\n\n    return verification_key;\n}\n\n// ----------------------------------------------------------------------------------\n// ------------------------------------TESTS-----------------------------------------\n\nTEST(serializing_deserializing, number_to_bit_vector) {\n    multiprecision::uint256_t number = 1000;\n    std::vector<bool> v = \n       {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, \n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, \n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, \n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, \n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, \n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, \n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, \n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0};\n\n    EXPECT_TRUE(v.size() == 256);\n    EXPECT_TRUE(v == number_to_binary(number));\n}\n\nTEST(serializing_deserializing, hash_correctness) {\n    EXPECT_TRUE(knapsack_hash(number_to_binary(1000)) == \"F4C3926909F99D774211E633EC76CBA1EF65C0B4D7A4D68083EBDCAE5343E918\");\n}\n\nTEST(serializing_deserializing, string_fieldVariable) {\n    std::string hash_hex = knapsack_hash(number_to_binary(1000));\n    field_type::value_type hash_field = hex_to_field_element(hash_hex);\n    EXPECT_TRUE(field_element_to_hex(hash_field) == hash_hex);\n}\n\n// Testing snark - knowledge the preimage of knapsack hash (first constraint in project)\nTEST(snark_tests, knapsack_component) {\n    blueprint<field_type> bp;\n\n    blueprint_variable<field_type> out;\n    out.allocate(bp);\n\n    block_variable<field_type> secret(bp, PREIMAGE_SIZE);\n\n    bp.set_input_sizes(1);\n\n    knapsack_crh_with_field_out_component<field_type> \n                    f(bp, PREIMAGE_SIZE, secret, blueprint_variable_vector<field_type>(1, out));\n                    \n    f.generate_r1cs_constraints();\n\n    std::vector<bool> secret_bv = number_to_binary(1000);\n\n    secret.generate_r1cs_witness(secret_bv);\n\n    secret_bv[0] = !secret_bv[0];\n    f.generate_r1cs_witness();\n    bp.val(out) = hex_to_field_element(knapsack_hash(secret_bv));\n    EXPECT_FALSE(bp.is_satisfied());   \n    \n    secret_bv[0] = !secret_bv[0]; \n    f.generate_r1cs_witness();\n    bp.val(out) = hex_to_field_element(knapsack_hash(secret_bv));\n    EXPECT_TRUE(bp.is_satisfied());\n\n    const snark::r1cs_constraint_system<field_type> constraint_system = bp.get_constraint_system();\n    const typename scheme_type::keypair_type keypair = snark::generate<scheme_type>(constraint_system);\n\n    const typename scheme_type::proof_type proof = snark::prove<scheme_type>(keypair.first, bp.primary_input(), bp.auxiliary_input());\n    EXPECT_TRUE(snark::verify<scheme_type>(keypair.second, bp.primary_input(), proof));\n}\n\n// Testing snark - secret_hash is in hashing_list (Second constraint)\nTEST(snark_tests, list_component) {\n    blueprint<field_type> bp;\n    \n    blueprint_variable_vector<field_type> hash_list;\n    hash_list.allocate(bp, HASHING_LIST_SIZE);\n\n    blueprint_variable_vector<field_type> bool_mask;\n    bool_mask.allocate(bp, HASHING_LIST_SIZE);\n\n    blueprint_variable<field_type> secret_hash;\n    secret_hash.allocate(bp);\n\n    bp.set_input_sizes(HASHING_LIST_SIZE);\n\n    for (auto field_var: bool_mask) {\n        generate_boolean_r1cs_constraint<field_type>(bp, field_var);\n    }\n\n    bp.add_r1cs_constraint(r1cs_constraint<field_type>(1, blueprint_sum<field_type>(bool_mask), 1));\n\n    for (int i = 0; i < HASHING_LIST_SIZE; i++) {\n        bp.add_r1cs_constraint(r1cs_constraint<field_type>(bool_mask[i], hash_list[i] - secret_hash, 0));\n    }\n\n    std::vector<field_type::value_type> hashes(HASHING_LIST_SIZE);\n\n    for (int i = 0; i < HASHING_LIST_SIZE; i++) {\n        hashes[i] = hex_to_field_element(knapsack_hash(number_to_binary(i)));\n        bp.val(hash_list[i]) = hex_to_field_element(knapsack_hash(number_to_binary(i)));\n    }\n\n    field_type::value_type secret_hash_w = hex_to_field_element(knapsack_hash(number_to_binary(5)));\n    bp.val(secret_hash) = secret_hash_w;\n    for (int i = 0; i < HASHING_LIST_SIZE; i++) {\n        if (secret_hash_w == hashes[i]) {\n            bp.val(bool_mask[i]) = field_type::value_type::one();\n            continue;\n        }\n        bp.val(bool_mask[i]) = field_type::value_type::zero();\n    }\n    EXPECT_FALSE(bp.is_satisfied());\n\n    secret_hash_w = hex_to_field_element(knapsack_hash(number_to_binary(0)));\n    bp.val(secret_hash) = secret_hash_w;\n    for (int i = 0; i < HASHING_LIST_SIZE; i++) {\n        if (secret_hash_w == hashes[i]) {\n            bp.val(bool_mask[i]) = field_type::value_type::one();\n            continue;\n        }\n        bp.val(bool_mask[i]) = field_type::value_type::zero();\n    }\n    EXPECT_TRUE(bp.is_satisfied());\n\n    const snark::r1cs_constraint_system<field_type> constraint_system = bp.get_constraint_system();\n    const typename scheme_type::keypair_type keypair = snark::generate<scheme_type>(constraint_system);\n\n    const typename scheme_type::proof_type proof = snark::prove<scheme_type>(keypair.first, bp.primary_input(), bp.auxiliary_input());\n    EXPECT_TRUE(snark::verify<scheme_type>(keypair.second, bp.primary_input(), proof));\n}\n", "meta": {"hexsha": "36d7d39bbf714af62e4d5435826c476147da496d", "size": 21192, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bin/cli/src/main.cpp", "max_stars_repo_name": "Curryrasul/knapsack-snark", "max_stars_repo_head_hexsha": "633515a13906407338a81b9874d964869ddec624", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-14T18:09:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-14T18:09:38.000Z", "max_issues_repo_path": "bin/cli/src/main.cpp", "max_issues_repo_name": "Curryrasul/knapsack-snark", "max_issues_repo_head_hexsha": "633515a13906407338a81b9874d964869ddec624", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bin/cli/src/main.cpp", "max_forks_repo_name": "Curryrasul/knapsack-snark", "max_forks_repo_head_hexsha": "633515a13906407338a81b9874d964869ddec624", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-12T10:53:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-12T10:53:21.000Z", "avg_line_length": 39.0276243094, "max_line_length": 134, "alphanum_fraction": 0.662797282, "num_tokens": 5747, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079209, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.45013023337295177}}
{"text": "#define BOOST_TEST_MODULE \"test_omp_global_pair_debye_huckel_interaction\"\n\n#ifdef BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n#else\n#include <boost/test/included/unit_test.hpp>\n#endif\n\n#include <test/util/utility.hpp>\n\n#include <mjolnir/math/math.hpp>\n#include <mjolnir/core/BoundaryCondition.hpp>\n#include <mjolnir/core/SimulatorTraits.hpp>\n#include <mjolnir/omp/System.hpp>\n#include <mjolnir/omp/RandomNumberGenerator.hpp>\n#include <mjolnir/omp/UnlimitedGridCellList.hpp>\n#include <mjolnir/omp/GlobalPairInteraction.hpp>\n#include <mjolnir/forcefield/global/DebyeHuckelPotential.hpp>\n#include <mjolnir/util/make_unique.hpp>\n\nBOOST_AUTO_TEST_CASE(omp_GlobalPair_DebyeHuckel_calc_force)\n{\n    namespace test = mjolnir::test;\n    constexpr double tol = 1e-8;\n    mjolnir::LoggerManager::set_default_logger(\"test_omp_global_pair_debye_huckel_interaction.log\");\n\n    using omp_traits_type = mjolnir::OpenMPSimulatorTraits<double, mjolnir::UnlimitedBoundary>;\n    using seq_traits_type = mjolnir::SimulatorTraits<double, mjolnir::UnlimitedBoundary>;\n\n    using real_type        = double;\n    using coordinate_type  = typename omp_traits_type::coordinate_type;\n    using boundary_type    = typename omp_traits_type::boundary_type;\n    using topology_type    = mjolnir::Topology;\n\n    using potential_type   = mjolnir::DebyeHuckelPotential<real_type>;\n\n    using omp_system_type         = mjolnir::System<omp_traits_type>;\n    using omp_parameter_list_type = mjolnir::ParameterList<omp_traits_type, potential_type>;\n    using omp_parameter_type      = typename mjolnir::DebyeHuckelParameterList<omp_traits_type>::parameter_type;\n    using omp_partition_type      = mjolnir::UnlimitedGridCellList<omp_traits_type, potential_type>;\n    using omp_interaction_type    = mjolnir::GlobalPairInteraction<omp_traits_type, potential_type>;\n\n    using seq_parameter_list_type = mjolnir::ParameterList<seq_traits_type, potential_type>;\n    using seq_parameter_type      = typename mjolnir::DebyeHuckelParameterList<seq_traits_type>::parameter_type;\n    using seq_system_type         = mjolnir::System<seq_traits_type>;\n    using seq_partition_type      = mjolnir::UnlimitedGridCellList<seq_traits_type, potential_type>;\n    using seq_interaction_type    = mjolnir::GlobalPairInteraction<seq_traits_type, potential_type>;\n\n    const int max_number_of_threads = omp_get_max_threads();\n    BOOST_TEST_WARN(max_number_of_threads > 2);\n    BOOST_TEST_MESSAGE(\"maximum number of threads = \" << max_number_of_threads);\n\n    std::mt19937 rng(123456789);\n\n    const std::size_t N_particle = 64;\n    for(int num_thread=1; num_thread<=max_number_of_threads; ++num_thread)\n    {\n        omp_set_num_threads(num_thread);\n        BOOST_TEST_MESSAGE(\"maximum number of threads = \" << omp_get_max_threads());\n\n        std::vector<std::pair<std::size_t, omp_parameter_type>> omp_parameters(N_particle);\n        for(std::size_t i=0; i<N_particle; ++i)\n        {\n            omp_parameters[i] = std::make_pair(i, omp_parameter_type{1.0});\n        }\n        std::vector<std::pair<std::size_t, seq_parameter_type>> seq_parameters(N_particle);\n        for(std::size_t i=0; i<N_particle; ++i)\n        {\n            seq_parameters[i] = std::make_pair(i, seq_parameter_type{1.0});\n        }\n\n        potential_type potential(5.5);\n\n        mjolnir::DebyeHuckelParameterList<omp_traits_type> omp_rule(omp_parameters, {},\n            typename omp_parameter_list_type::ignore_molecule_type(\"Nothing\"),\n            typename omp_parameter_list_type::ignore_group_type   ({}));\n        omp_parameter_list_type omp_parameter_list(mjolnir::make_unique<\n            mjolnir::DebyeHuckelParameterList<omp_traits_type>>(std::move(omp_rule)));\n\n        mjolnir::DebyeHuckelParameterList<seq_traits_type> seq_rule(seq_parameters, {},\n            typename seq_parameter_list_type::ignore_molecule_type(\"Nothing\"),\n            typename seq_parameter_list_type::ignore_group_type   ({}));\n        seq_parameter_list_type seq_parameter_list(mjolnir::make_unique<\n            mjolnir::DebyeHuckelParameterList<seq_traits_type>>(std::move(seq_rule)));\n\n        topology_type topol(N_particle);\n        topol.construct_molecules();\n\n        omp_system_type omp_sys(N_particle, boundary_type{});\n        seq_system_type seq_sys(N_particle, boundary_type{});\n\n        test::clear_everything(omp_sys);\n        test::clear_everything(seq_sys);\n\n        omp_sys.attribute(\"temperature\")    = 300.0;\n        omp_sys.attribute(\"ionic_strength\") =   0.2;\n\n        seq_sys.attribute(\"temperature\")    = 300.0;\n        seq_sys.attribute(\"ionic_strength\") =   0.2;\n\n        for(std::size_t i=0; i<omp_sys.size(); ++i)\n        {\n            const auto i_x = i % 4;\n            const auto i_y = i / 4;\n            const auto i_z = i / 16;\n\n            omp_sys.position(i) = mjolnir::math::make_coordinate<coordinate_type>(i_x*2.0, i_y*2.0, i_z*2.0);\n        }\n\n        test::apply_random_perturbation(omp_sys, rng, 0.1);\n\n        potential.initialize(omp_sys);\n\n        for(std::size_t i=0; i<omp_sys.size(); ++i)\n        {\n            seq_sys.mass(i)     = omp_sys.mass(i);\n            seq_sys.position(i) = omp_sys.position(i);\n            seq_sys.velocity(i) = omp_sys.velocity(i);\n            seq_sys.force(i)    = omp_sys.force(i);\n            seq_sys.name(i)     = omp_sys.name(i);\n            seq_sys.group(i)    = omp_sys.group(i);\n        }\n\n        omp_interaction_type omp_interaction(potential_type{potential},\n            std::move(omp_parameter_list),\n            mjolnir::SpatialPartition<omp_traits_type, potential_type>(\n                mjolnir::make_unique<omp_partition_type>()));\n\n        seq_interaction_type seq_interaction(potential_type{potential},\n            std::move(seq_parameter_list),\n            mjolnir::SpatialPartition<seq_traits_type, potential_type>(\n                mjolnir::make_unique<seq_partition_type>()));\n\n        omp_interaction.initialize(omp_sys, topol);\n        seq_interaction.initialize(seq_sys, topol);\n\n        test::check_force_consistency              (omp_sys, omp_interaction, seq_sys, seq_interaction, tol);\n        test::check_force_and_energy_consistency   (omp_sys, omp_interaction, seq_sys, seq_interaction, tol);\n        test::check_force_and_virial_consistency   (omp_sys, omp_interaction, seq_sys, seq_interaction, tol);\n        test::check_force_energy_virial_consistency(omp_sys, omp_interaction, seq_sys, seq_interaction, tol);\n        test::check_energy_consistency             (omp_sys, omp_interaction, seq_sys, seq_interaction, tol);\n    }\n}\n", "meta": {"hexsha": "63ee6454eb44f30c9eb990d25b812c5b6c7ab149", "size": 6550, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/omp/test_omp_global_debye_huckel_interaction.cpp", "max_stars_repo_name": "ToruNiina/Mjolnir", "max_stars_repo_head_hexsha": "44435dd3afc12f5c8ea27a66d7ab282df3e588ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2017-02-01T08:28:38.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-25T15:47:51.000Z", "max_issues_repo_path": "test/omp/test_omp_global_debye_huckel_interaction.cpp", "max_issues_repo_name": "Mjolnir-MD/Mjolnir", "max_issues_repo_head_hexsha": "043df4080720837042c6b67a5495ecae198bc2b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 60.0, "max_issues_repo_issues_event_min_datetime": "2019-01-14T08:11:33.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-29T08:26:36.000Z", "max_forks_repo_path": "test/omp/test_omp_global_debye_huckel_interaction.cpp", "max_forks_repo_name": "Mjolnir-MD/Mjolnir", "max_forks_repo_head_hexsha": "043df4080720837042c6b67a5495ecae198bc2b3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2019-01-13T11:03:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-01T11:38:00.000Z", "avg_line_length": 45.4861111111, "max_line_length": 112, "alphanum_fraction": 0.7048854962, "num_tokens": 1617, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079209, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.45013023337295177}}
{"text": "// A rough outline of what a Boost PRF library might look like:\n\n#include <boost/random/counter_based_engine.hpp>\n#include <boost/random/counter_based_urng.hpp>\n#include <boost/random/threefry.hpp>\n#include <boost/random/philox.hpp>\n#include <boost/random/ars.hpp>\n#include <boost/random/aes.hpp>\n\n#include <iostream>\n#include <boost/random/normal_distribution.hpp>\n#include \"rangeIO.hpp\"\n\n//using namespace boost::random;\n\ntemplate <typename Prf>\nvoid doit(){\n    Prf prf;\n    typename Prf::ctr_type c={{}};\n    typename Prf::key_type uk={{}};\n    typename Prf::ctr_type r = prf(c, uk);\n    std::cout << rangeInserter(r.begin(), r.end()) << \"\\n\";\n\n    boost::random::normal_distribution<double> nd(1.0, 2.0);\n    boost::random::counter_based_engine<Prf> e;\n    std::cout << e() << \"\\n\";\n    std::cout << e << \"\\n\";\n    std::cout << nd(e) << \"\\n\";\n\n    boost::random::counter_based_engine<Prf> e2(2);\n    assert(e2 != e);\n    e2.seed();\n    e2();\n    nd.reset();\n    nd(e2);\n    assert(e2 == e);\n\n    boost::random::counter_based_urng<Prf> murng(c, uk, 5);\n    std::cout << nd(murng) << \"\\n\";\n}\n\nint main(int argc, char **argv){\n\n    doit<boost::random::threefry<2, uint64_t> >();\n    doit<boost::random::philox<2, uint64_t> >();\n    doit<boost::random::philox<2, uint32_t> >();\n    doit<boost::random::philox<4, uint32_t> >();\n    doit<boost::random::philox<4, uint64_t> >();\n    boost::random::ars<__m128i, 7> ars128i;\n    \n    boost::random::counter_based_engine<boost::random::ars<uint32_t, 7> > ars7;\n    std::cout << ars7() << \"\\n\";\n    \n    boost::random::counter_based_engine<boost::random::aes<uint64_t> > aese;\n\n    return 0;\n}\n", "meta": {"hexsha": "f846ac80841b25ff43d04611d91c975cfa643c46", "size": 1638, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/random/test/obsolete/outline.cpp", "max_stars_repo_name": "DEShawResearch/Random123-Boost", "max_stars_repo_head_hexsha": "65e3d874b67aa7b3e02d5ad8306462f52d2079c0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2015-04-08T18:40:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T00:08:25.000Z", "max_issues_repo_path": "libs/random/test/obsolete/outline.cpp", "max_issues_repo_name": "DEShawResearch/Random123-Boost", "max_issues_repo_head_hexsha": "65e3d874b67aa7b3e02d5ad8306462f52d2079c0", "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/random/test/obsolete/outline.cpp", "max_forks_repo_name": "DEShawResearch/Random123-Boost", "max_forks_repo_head_hexsha": "65e3d874b67aa7b3e02d5ad8306462f52d2079c0", "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.2413793103, "max_line_length": 79, "alphanum_fraction": 0.6306471306, "num_tokens": 505, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4501302280255477}}
{"text": "//\n//  RTreeND.hpp\n//  AxiSEM3D\n//\n//  Created by Kuangdai Leng on 9/7/19.\n//  Copyright \u00a9 2019 Kuangdai Leng. All rights reserved.\n//\n\n//  boost RTree for searching nearest points\n\n#ifndef RTreeND_hpp\n#define RTreeND_hpp\n\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Weverything\"\n#include <boost/geometry.hpp>\n#pragma clang diagnostic pop\n\n#include \"NetCDF_Reader.hpp\"\n#include \"mpi.hpp\"\n#include \"io.hpp\"\n#include \"timer.hpp\"\n#include \"eigen_tools.hpp\"\n\n// D: dimensions, must be 1 or 2 or 3\n// V: number of variables\n// T: type of variables\ntemplate <int D, int V, typename T>\nclass RTreeND {\n    ///////////// typedef /////////////\n    // coordinates\n    typedef typename std::conditional<D == 1,\n    Eigen::Matrix<double, Eigen::Dynamic, D>,\n    Eigen::Matrix<double, Eigen::Dynamic, D, Eigen::RowMajor>>::type DMatXD_RM;\n    // data\n    typedef typename std::conditional<V == 1,\n    Eigen::Matrix<T, Eigen::Dynamic, V>,\n    Eigen::Matrix<T, Eigen::Dynamic, V, Eigen::RowMajor>>::type TMatXV_RM;\n    // data unit\n    typedef Eigen::Matrix<T, 1, V> TRowV;\n    typedef Eigen::Matrix<double, 1, V> DRowV;\n    // location\n    typedef boost::geometry::model::point<double, D,\n    boost::geometry::cs::cartesian> RTreeLoc;\n    // leaf\n    typedef std::pair<RTreeLoc, TRowV> RTreeLeaf;\n    \n    \n    ///////////// cs array to RTreeLoc /////////////\n    // 1D\n    template <int R = D, typename ArrayCS>\n    static typename std::enable_if<R == 1,\n    RTreeLoc>::type toRTreeLoc(const ArrayCS &loc) {\n        return RTreeLoc(loc[0]);\n    }\n    // 2D\n    template <int R = D, typename ArrayCS>\n    static typename std::enable_if<R == 2,\n    RTreeLoc>::type toRTreeLoc(const ArrayCS &loc) {\n        return RTreeLoc(loc[0], loc[1]);\n    }\n    // 3D\n    template <int R = D, typename ArrayCS>\n    static typename std::enable_if<R == 3,\n    RTreeLoc>::type toRTreeLoc(const ArrayCS &loc) {\n        return RTreeLoc(loc[0], loc[1], loc[2]);\n    }\n    \n    \n    ///////////// public /////////////\npublic:\n    // constructor\n    RTreeND() = default;\n    \n    // constructor\n    RTreeND(const std::string &ncFile, const std::string &coordVarName,\n            const std::array<std::pair<std::string, double>, V> &varInfo) {\n        // read data\n        DMatXD_RM ctrlCrds;\n        TMatXV_RM ctrlVals;\n        timer::gPreloopTimer.begin(\"Reading control-point data\");\n        timer::gPreloopTimer.message(\"data file: \" + io::popInputDir(ncFile));\n        if (mpi::root()) {\n            // open\n            NetCDF_Reader reader(io::popInputDir(ncFile));\n            // read coords\n            reader.readMatrixDouble(coordVarName, ctrlCrds);\n            // read data\n            ctrlVals.resize(ctrlCrds.rows(), V);\n            for (int ivar = 0; ivar < V; ivar++) {\n                // read to double\n                eigen::DColX ctrlVal;\n                reader.readMatrixDouble(varInfo[ivar].first, ctrlVal);\n                ctrlVal *= varInfo[ivar].second;\n                // round\n                if (std::is_integral<T>::value) {\n                    ctrlVal = ctrlVal.array().round();\n                }\n                // cast to Ts\n                ctrlVals.col(ivar) = ctrlVal.template cast<T>();\n            }\n        }\n        timer::gPreloopTimer.ended(\"Reading control-point data\");\n        \n        // broadcast\n        timer::gPreloopTimer.begin(\"Broadcasting control-point data\");\n        mpi::bcastEigen(ctrlCrds);\n        mpi::bcastEigen(ctrlVals);\n        \n        // memory info\n        timer::gPreloopTimer.message\n        (eigen_tools::memoryInfo(ctrlCrds, \"coordinates at control points\"));\n        timer::gPreloopTimer.message\n        (eigen_tools::memoryInfo(ctrlVals, \"values at control points\"));\n        timer::gPreloopTimer.ended(\"Broadcasting control-point data\");\n        \n        // build RTree\n        timer::gPreloopTimer.begin(\"Building R-tree\");\n        addLeafs(ctrlCrds, ctrlVals);\n        timer::gPreloopTimer.ended(\"Building R-tree\");\n    }\n    \n    // add a leaf\n    template <typename ArrayCS>\n    void addLeaf(const ArrayCS &loc, const TRowV &val) {\n        mRTree.insert({toRTreeLoc(loc), val});\n    }\n    \n    // add scalar, only for V = 1\n    template <int VN = V, typename ArrayCS>\n    typename std::enable_if<VN == 1, void>::type\n    addLeaf(const ArrayCS &loc, T val) {\n        static TRowV oneVal;\n        oneVal(0) = val;\n        addLeaf(loc, oneVal);\n    }\n    \n    // add leafs\n    void addLeafs(const DMatXD_RM &locs, const TMatXV_RM &vals) {\n        for (int ir = 0; ir < locs.rows(); ir++) {\n            mRTree.insert({toRTreeLoc(locs.row(ir)), vals.row(ir)});\n        }\n    }\n    \n    // query\n    // difficult to make this collective\n    template <typename ArrayCS>\n    void query(const ArrayCS &loc, int count,\n               std::vector<double> &dists, std::vector<TRowV> &vals) const {\n        // location\n        const RTreeLoc &rloc = toRTreeLoc(loc);\n        // KNN query\n        std::vector<RTreeLeaf> leafs;\n        mRTree.query(boost::geometry::index::nearest(rloc, count),\n                     std::back_inserter(leafs));\n        // get distance\n        dists.clear();\n        dists.reserve(count);\n        std::transform(leafs.begin(), leafs.end(), std::back_inserter(dists),\n                       [&rloc](const auto &leaf) {\n            return boost::geometry::distance(leaf.first, rloc);});\n        // get values\n        vals.clear();\n        vals.reserve(count);\n        std::transform(leafs.begin(), leafs.end(), std::back_inserter(vals),\n                       [](const auto &leaf) {return leaf.second;});\n    }\n    \n    // compute\n    template <typename ArrayCS>\n    TRowV compute(const ArrayCS &loc, int count, double maxDistInRange,\n                  const TRowV &valOutOfRange, double distTolExact) const {\n        // query\n        static std::vector<double> dists;\n        static std::vector<TRowV> vals;\n        query(loc, count, dists, vals);\n        \n        // average vaules by inverse distance\n        double invDistSum = 0.;\n        static DRowV valTarget;\n        valTarget.setZero();\n        int numInRange = 0;\n        for (int ip = 0; ip < dists.size(); ip++) {\n            // exactly on a leaf\n            if (dists[ip] < distTolExact) {\n                return vals[ip];\n            }\n            // out of range\n            if (dists[ip] > maxDistInRange) {\n                continue;\n            }\n            // weight by inverse distance\n            invDistSum += 1. / dists[ip];\n            valTarget += vals[ip].template cast<double>() / dists[ip];\n            numInRange++;\n        }\n        \n        // out of range\n        if (numInRange == 0) {\n            return valOutOfRange;\n        }\n        \n        // average and round\n        valTarget /= invDistSum;\n        if (std::is_integral<T>::value) {\n            valTarget = valTarget.array().round();\n        }\n        return valTarget.template cast<T>();\n    }\n    \n    // compute scalar, only for V = 1\n    template <int VN = V, typename ArrayCS>\n    typename std::enable_if<VN == 1, T>::type\n    compute(const ArrayCS &loc, int count, double maxDistInRange,\n            T valOutOfRange, double distTolExact) const {\n        static TRowV oneVal;\n        oneVal(0) = valOutOfRange;\n        return compute(loc, count, maxDistInRange, oneVal, distTolExact)(0);\n    }\n    \n    // size\n    int size() const {\n        return (int)mRTree.size();\n    }\n    \n    // get all values\n    TMatXV_RM getAllValues() const {\n        // get values\n        std::vector<TRowV> vals;\n        std::transform(mRTree.begin(), mRTree.end(), std::back_inserter(vals),\n                       [](const auto &leaf) {return leaf.second;});\n        // cast to matrix\n        TMatXV_RM mat(vals.size(), V);\n        for (int ip = 0; ip < vals.size(); ip++) {\n            mat.row(ip) = vals[ip];\n        }\n        return mat;\n    }\n    \nprivate:\n    // rtree\n    boost::geometry::index::rtree<RTreeLeaf,\n    boost::geometry::index::quadratic<16>> mRTree;\n};\n\n#endif /* RTreeND_hpp */\n", "meta": {"hexsha": "f60de4f85f8d736983c2719f499e27b84ca6190c", "size": 8004, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "SOLVER/src/shared/data_structure/RTreeND.hpp", "max_stars_repo_name": "nicklinyi/AxiSEM-3D", "max_stars_repo_head_hexsha": "cd11299605cd6b92eb867d4109d2e6a8f15e6b4d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2020-06-05T01:13:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T05:11:50.000Z", "max_issues_repo_path": "SOLVER/src/shared/data_structure/RTreeND.hpp", "max_issues_repo_name": "nicklinyi/AxiSEM-3D", "max_issues_repo_head_hexsha": "cd11299605cd6b92eb867d4109d2e6a8f15e6b4d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 24.0, "max_issues_repo_issues_event_min_datetime": "2020-10-21T19:03:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-17T21:32:02.000Z", "max_forks_repo_path": "SOLVER/src/shared/data_structure/RTreeND.hpp", "max_forks_repo_name": "nicklinyi/AxiSEM-3D", "max_forks_repo_head_hexsha": "cd11299605cd6b92eb867d4109d2e6a8f15e6b4d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-06-21T11:54:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-23T01:02:39.000Z", "avg_line_length": 32.4048582996, "max_line_length": 79, "alphanum_fraction": 0.5627186407, "num_tokens": 2089, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.45013022267814345}}
{"text": "\n/* multiprecision_int_test.cpp\n*\n* Copyright John Maddock 2015\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* Tests all integer related generators and distributions with multiprecision types:\n* discard_block, independent_bits_engine, random_number_generator,\n* xor_combine_engine, uniform_int_distribution, uniform_smallint.\n*\n* Not supported, but could be with more work (but probably not worth while):\n* shuffle_order_engine, binomial_distribution, discrete_distribution, negative_binomial_distribution,\n* poisson_distribution\n*/\n\n#define BOOST_TEST_MAIN\n#include <boost/test/unit_test.hpp>\n\n#include <boost/core/ignore_unused.hpp>\n#include <boost/multiprecision/debug_adaptor.hpp>\n#include <boost/multiprecision/cpp_bin_float.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/random/independent_bits.hpp>\n#include <boost/random/discard_block.hpp>\n#include <boost/random/xor_combine.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/random_number_generator.hpp>\n#include <boost/random/uniform_int.hpp>\n#include <boost/random/uniform_smallint.hpp>\n#include <boost/random/discrete_distribution.hpp>\n#include <sstream>\n\ntypedef boost::mpl::list <\n   boost::random::independent_bits_engine<boost::random::mt19937, 1024, boost::multiprecision::uint1024_t >,\n   boost::random::independent_bits_engine<boost::random::mt19937, 1024, boost::multiprecision::int1024_t >,\n   boost::random::independent_bits_engine<boost::random::mt19937, 1024, boost::multiprecision::checked_uint1024_t >,\n   boost::random::independent_bits_engine<boost::random::mt19937, 1024, boost::multiprecision::checked_int1024_t >,\n   boost::random::independent_bits_engine<boost::random::mt19937, 30000, boost::multiprecision::cpp_int >,\n   boost::random::discard_block_engine<boost::random::independent_bits_engine<boost::random::mt19937, 1024, boost::multiprecision::uint1024_t >, 20, 10>,\n   boost::random::discard_block_engine<boost::random::independent_bits_engine<boost::random::mt19937, 1024, boost::multiprecision::int1024_t >, 20, 10>,\n   boost::random::discard_block_engine<boost::random::independent_bits_engine<boost::random::mt19937, 1024, boost::multiprecision::checked_uint1024_t >, 20, 10>,\n   boost::random::discard_block_engine<boost::random::independent_bits_engine<boost::random::mt19937, 1024, boost::multiprecision::checked_int1024_t >, 20, 10>,\n   boost::random::discard_block_engine<boost::random::independent_bits_engine<boost::random::mt19937, 600, boost::multiprecision::cpp_int >, 20, 10>\n> engines;\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(generator_test, engine_type, engines)\n{\n   typedef typename engine_type::result_type test_type;\n\n   engine_type gen;\n   gen.seed();\n   test_type a = gen.min();\n   test_type b = gen.max();\n   BOOST_CHECK(a < b);\n   a = gen();\n   //\n   // This extracts 32-bit values for use in seeding other sequences,\n   // not really applicable here, and not functional for signed types anyway.\n   //gen.generate(&b, &b + 1);\n   gen.discard(20);\n\n   typename engine_type::base_type base(gen.base());\n   boost::ignore_unused(base);\n\n   std::stringstream ss;\n   ss << gen;\n   engine_type gen2;\n   ss >> gen2;\n   BOOST_CHECK(gen == gen2);\n   gen2();\n   BOOST_CHECK(gen != gen2);\n   //\n   // construction and seeding:\n   //\n   engine_type gen3(0);\n   gen3.seed(2);\n}\n\nBOOST_AUTO_TEST_CASE(xor_combine_test)\n{\n   //\n   // As above but with a few things missing which don't work - for example we have no\n   // way to drill down and get the seed-type of the underlying generator.\n   //\n   typedef boost::random::xor_combine_engine<boost::random::independent_bits_engine<boost::random::mt19937, 512, boost::multiprecision::uint1024_t >, 512, boost::random::independent_bits_engine<boost::random::mt19937, 512, boost::multiprecision::uint1024_t >, 10> engine_type;\n   typedef engine_type::result_type test_type;\n\n   engine_type gen;\n   gen.seed();\n   test_type a = gen.min();\n   test_type b = gen.max();\n   BOOST_CHECK(a < b);\n   a = gen();\n#ifndef BOOST_NO_CXX11_EXPLICIT_CONVERSION_OPERATORS\n   gen.generate(&b, &b + 1);\n#endif\n   gen.discard(20);\n\n   //typename engine_type::base_type base(gen.base());\n\n   std::stringstream ss;\n   ss << gen;\n   engine_type gen2;\n   ss >> gen2;\n   BOOST_CHECK(gen == gen2);\n   gen2();\n   BOOST_CHECK(gen != gen2);\n   //\n   // construction and seeding:\n   //\n   //engine_type gen3(0);\n   //gen3.seed(2);\n}\n\ntypedef boost::mpl::list <\n   boost::random::random_number_generator<boost::random::mt19937, boost::multiprecision::cpp_int>,\n   boost::random::random_number_generator<boost::random::mt19937, boost::multiprecision::uint1024_t>,\n   boost::random::random_number_generator<boost::random::mt19937, boost::multiprecision::checked_uint1024_t>\n> generators;\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(random_number_generator, generator_type, generators)\n{\n   typedef typename generator_type::result_type result_type;\n   typedef typename generator_type::base_type base_type;\n\n   result_type lim = 1;\n   lim <<= 500;\n\n   base_type base;\n   generator_type gen(base);\n\n   for(unsigned i = 0; i < 100; ++i)\n      BOOST_CHECK(gen(lim) < lim);\n}\n\ntypedef boost::mpl::list <\n   boost::random::uniform_int_distribution<boost::multiprecision::cpp_int>,\n   boost::random::uniform_int_distribution<boost::multiprecision::uint1024_t>,\n   boost::random::uniform_int_distribution<boost::multiprecision::checked_uint1024_t>,\n   boost::random::uniform_smallint<boost::multiprecision::cpp_int>,\n   boost::random::uniform_smallint<boost::multiprecision::uint1024_t>,\n   boost::random::uniform_smallint<boost::multiprecision::checked_uint1024_t>\n> uniform_distributions;\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(distributions, distribution_type, uniform_distributions)\n{\n   typedef typename distribution_type::result_type  result_type;\n\n   result_type a = 20;\n   result_type b = 1;\n   b <<= 1000;\n\n   distribution_type d(a, b);\n   boost::random::mt19937 gen;\n\n   BOOST_CHECK_EQUAL(d.a(), a);\n   BOOST_CHECK_EQUAL(d.b(), b);\n   BOOST_CHECK_EQUAL((d.min)(), a);\n   BOOST_CHECK_EQUAL((d.max)(), b);\n\n   for(unsigned i = 0; i < 200; ++i)\n   {\n      result_type r = d(gen);\n      BOOST_CHECK(r <= b);\n      BOOST_CHECK(r >= a);\n   }\n\n   std::stringstream ss;\n   ss << d;\n   distribution_type d2;\n   ss >> d2;\n   BOOST_CHECK(d == d2);\n\n   boost::random::independent_bits_engine<boost::random::mt19937, std::numeric_limits<boost::multiprecision::uint1024_t>::digits, boost::multiprecision::uint1024_t > big_random;\n   for(unsigned i = 0; i < 200; ++i)\n   {\n      result_type r = d(big_random);\n      BOOST_CHECK(r <= b);\n      BOOST_CHECK(r >= a);\n   }\n}\n\n#ifndef BOOST_NO_CXX11_EXPLICIT_CONVERSION_OPERATORS\n\ntypedef boost::mpl::list <\n   boost::random::discrete_distribution < boost::multiprecision::cpp_int, double>,\n   boost::random::discrete_distribution <unsigned int, boost::multiprecision::cpp_bin_float_100>\n> other_distributions;\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(discrete_distributions, distribution_type, other_distributions)\n{\n   typedef typename distribution_type::result_type  result_type;\n   typedef typename distribution_type::input_type   input_type;\n\n   input_type a[] = { 20, 30, 40, 50 };\n\n   distribution_type d(a, a + 4);\n   boost::random::mt19937 gen;\n\n   for(unsigned i = 0; i < 200; ++i)\n   {\n      result_type r = d(gen);\n   }\n\n   std::stringstream ss;\n   ss << std::setprecision(std::numeric_limits<input_type>::digits10 + 3) << d;\n   distribution_type d2;\n   ss >> d2;\n   BOOST_CHECK(d == d2);\n\n   boost::random::independent_bits_engine<boost::random::mt19937, std::numeric_limits<boost::multiprecision::uint1024_t>::digits, boost::multiprecision::uint1024_t > big_random;\n   for(unsigned i = 0; i < 200; ++i)\n   {\n      result_type r = d(big_random);\n   }\n}\n\n#endif\n", "meta": {"hexsha": "ca3e4893545c5d7f002dcd59e1de2685d7d2f7a8", "size": 7840, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/libs/random/test/multiprecision_int_test.cpp", "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/libs/random/test/multiprecision_int_test.cpp", "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/libs/random/test/multiprecision_int_test.cpp", "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": 34.6902654867, "max_line_length": 276, "alphanum_fraction": 0.731505102, "num_tokens": 2037, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.45013022267814345}}
{"text": "//@HEADER\n// ************************************************************************\n// \n//                        miniTri v. 1.0\n//              Copyright (2016) 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? Contact  Jon Berry (jberry@sandia.gov)\n//                     Michael Wolf (mmwolf@sandia.gov)\n// \n// ************************************************************************\n//@HEADER\n\n//////////////////////////////////////////////////////////////////////////////\n//                                                                          //\n// File:      Graph.h                                                       //\n// Project:   miniTri                                                       //  \n// Author:    Michael Wolf                                                  //\n//                                                                          //\n// Description:                                                             //\n//              Header file for graph class.                                //\n//                                                                          //\n//////////////////////////////////////////////////////////////////////////////\n#ifndef GRAPH_H\n#define GRAPH_H\n\n#include <list>\n#include <vector>\n#include <map>\n#include <cmath>\n\n#include <boost/shared_array.hpp>\n\n#include \"CSRmatrix.hpp\"\n#include \"Vector.hpp\"\n\n//////////////////////////////////////////////////////////////////////////////\n// Graph class\n//////////////////////////////////////////////////////////////////////////////\nclass Graph \n{\n\n private:\n  std::string mFilename;\n\n  int mNumVerts;\n  int mNumEdges;\n  CSRMat mMatrix;\n\n  int mNumTriangles;\n  boost::shared_ptr<CSRMat> mTriMat;\n\n  std::map<int,std::map<int,int> > mEdgeIndices;\n\n\n  Vector mVTriDegrees;\n  Vector mETriDegrees;\n\n\n  // K-count frequency table\n  std::vector<int> mKCounts;\n\n public:\n  //////////////////////////////////////////////////////////////////////////\n  // default constructor -- builds empty graph\n  //////////////////////////////////////////////////////////////////////////\n  Graph() \n    :mFilename(\"UNDEFINED\"),mNumVerts(0),mMatrix(), mNumTriangles(0), mTriMat()\n  {\n  };\n  //////////////////////////////////////////////////////////////////////////\n\n  //////////////////////////////////////////////////////////////////////////\n  // Constructor that accepts matrix type as an argument\n  //////////////////////////////////////////////////////////////////////////\n  Graph(std::string _fname,bool binFile=false) \n   :mFilename(_fname),mMatrix(), mNumTriangles(0), mTriMat()\n  {\n    if(binFile==false)\n    {\n      mMatrix.readMMMatrix(mFilename.c_str());\n    }\n    else\n    {\n      mMatrix.readBinMatrix(mFilename.c_str());\n    }\n\n    mNumVerts = mMatrix.getM();\n    mNumEdges = mMatrix.getNNZ()/2;\n\n    int countSize = (int) sqrt(mNumVerts);\n    if(countSize < 10)\n    {\n      countSize = 10;\n    }\n    mKCounts.resize(countSize,0);\n\n  };\n  //////////////////////////////////////////////////////////////////////////\n\n  //////////////////////////////////////////////////////////////////////////\n  // destructor -- deletes matrix\n  //////////////////////////////////////////////////////////////////////////\n  ~Graph()\n  {\n  };\n  //////////////////////////////////////////////////////////////////////////\n\n  //////////////////////////////////////////////////////////////////////////\n  // Enumerate triangles\n  //////////////////////////////////////////////////////////////////////////\n  void triangleEnumerate();\n  //////////////////////////////////////////////////////////////////////////\n\n  // Calculate triangle degrees\n  void calculateTriangleDegrees();\n\n  // Calculate kcounts\n  void calculateKCounts();\n\n  void printTriangles() const;\n  int getNumTriangles() const {return mNumTriangles;};\n\n  void printKCounts();\n\n};\n//////////////////////////////////////////////////////////////////////////////\n\n#endif\n", "meta": {"hexsha": "a17fe2fa7d63b4a8fa59d74683d8041073991e93", "size": 5523, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "SubgraphIsomorphism/triangle/code/cpp/code/linearAlgebra/serial/Graph.hpp", "max_stars_repo_name": "bkmgit/GraphChallenge", "max_stars_repo_head_hexsha": "c89c2bbf01ffea0e17c614b111f3124a1486676c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 30.0, "max_stars_repo_stars_event_min_datetime": "2018-01-30T13:17:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T09:07:40.000Z", "max_issues_repo_path": "SubgraphIsomorphism/triangle/code/cpp/code/linearAlgebra/serial/Graph.hpp", "max_issues_repo_name": "bkmgit/GraphChallenge", "max_issues_repo_head_hexsha": "c89c2bbf01ffea0e17c614b111f3124a1486676c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2017-02-20T02:24:15.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-23T20:38:31.000Z", "max_forks_repo_path": "SubgraphIsomorphism/triangle/code/cpp/code/linearAlgebra/serial/Graph.hpp", "max_forks_repo_name": "bkmgit/GraphChallenge", "max_forks_repo_head_hexsha": "c89c2bbf01ffea0e17c614b111f3124a1486676c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2017-02-19T06:10:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-15T04:38:11.000Z", "avg_line_length": 34.7358490566, "max_line_length": 80, "alphanum_fraction": 0.4506608727, "num_tokens": 916, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300698514777, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.4500659614903448}}
{"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_NEARBYINT_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_NEARBYINT_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n\n    @ingroup group-arithmetic\n    This function object computes the rounded to even value of its parameter.\n\n    @par Header <boost/simd/function/nearbyint.hpp>\n\n    @par Notes:\n    - If x is \\f$\\pm\\infty\\f$, it is returned, unmodified\n    - If x is \\f$\\pm0\\f$, it is returned, unmodified\n    - If x is NaN, NaN is returned\n\n    - to even means that half integer values are rounded to the nearest\n    even value.\n\n    -  This function is in general faster than @ref round which do the rouding on\n        half integer values away from zero.\n\n    @see round, ceil, floor, trunc\n  **/\n  Value nearbyint(Value const& x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/nearbyint.hpp>\n#include <boost/simd/function/simd/nearbyint.hpp>\n\n#endif\n", "meta": {"hexsha": "4d8cd9d763e04944d6f5661ac7323a95968aca06", "size": 1305, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/nearbyint.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/nearbyint.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/nearbyint.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": 28.3695652174, "max_line_length": 100, "alphanum_fraction": 0.6061302682, "num_tokens": 293, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300698514777, "lm_q2_score": 0.6406358617010351, "lm_q1q2_score": 0.45006595667018984}}
{"text": "/*******************************************************************************\n * Copyright 2013-2014 Sebastian Niemann <niemann@sra.uni-hannover.de>.\n * \n * Licensed under the MIT License (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http://opensource.org/licenses/MIT\n * \n * Developers:\n *   Sebastian Niemann - Lead developer\n *   Daniel Kiechle - Unit testing\n ******************************************************************************/\n#include <Expected.hpp>\nusing armadilloJava::Expected;\n\n#include <iostream>\nusing std::cout;\nusing std::endl;\n\n#include <utility>\nusing std::pair;\n\n#include <armadillo>\nusing arma::Row;\nusing arma::Col;\n\n#include <InputClass.hpp>\nusing armadilloJava::InputClass;\n\n#include <Input.hpp>\nusing armadilloJava::Input;\n\nnamespace armadilloJava {\n  class ExpectedElemIndFill : public Expected {\n    public:\n      ExpectedElemIndFill() {\n        cout << \"Compute ExpectedElemIndFill(): \" << endl;\n\n          vector<vector<pair<string, void*>>> inputs = Input::getTestParameters({\n            InputClass::ElemInd,\n            InputClass::Fill\n          });\n\n          for (vector<pair<string, void*>> input : inputs) {\n            _fileSuffix = \"\";\n\n            int n = 0;\n            for (pair<string, void*> value : input) {\n              switch (n) {\n                case 0:\n                  _fileSuffix += value.first;\n                  _elemInd = *static_cast<int*>(value.second);\n                  break;\n                case 1:\n                  _fileSuffix += \",\" + value.first;\n                  _fill = *static_cast<int*>(value.second);\n                  break;\n              }\n              ++n;\n            }\n\n            cout << \"Using input: \" << _fileSuffix << endl;\n\n            expectedRowVecElemIndFill();\n            expectedColVecElemIndFill();\n          }\n\n          cout << \"done.\" << endl;\n        }\n\n    protected:\n      int _elemInd;\n      int _fill;\n\n      void expectedRowVecElemIndFill() {\n        cout << \"- Compute expectedRowVecAt() ... \";\n        Row<double> expected;\n        switch (_fill) {\n          case 0:\n            break;\n          case 1:\n            expected = Row<double>(_elemInd, arma::fill::none);\n            save<double>(\"Row.elemIndFill\", Row<double>(expected));\n            break;\n          case 2:\n            expected = Row<double>(_elemInd, arma::fill::ones);\n            save<double>(\"Row.elemIndFill\", Row<double>(expected));\n            break;\n          case 3:\n            expected = Row<double>(_elemInd, arma::fill::randn);\n            save<double>(\"Row.elemIndFill\", Row<double>(expected));\n            break;\n          case 4:\n            expected = Row<double>(_elemInd, arma::fill::randu);\n            save<double>(\"Row.elemIndFill\", Row<double>(expected));\n            break;\n          case 5:\n            expected = Row<double>(_elemInd, arma::fill::zeros);\n            save<double>(\"Row.elemIndFill\", Row<double>(expected));\n            break;\n        }\n        cout << \"done.\" << endl;\n      }\n\n  void expectedColVecElemIndFill() {\n         cout << \"- Compute expectedRowVecAt() ... \";\n         Col<double> expected;\n         switch (_fill) {\n           case 0:\n             break;\n           case 1:\n             expected = Col<double>(_elemInd, arma::fill::none);\n             save<double>(\"Col.elemIndFill\", Col<double>(expected));\n             break;\n           case 2:\n             expected = Col<double>(_elemInd, arma::fill::ones);\n             save<double>(\"Col.elemIndFill\", Col<double>(expected));\n             break;\n           case 3:\n             expected = Col<double>(_elemInd, arma::fill::randn);\n             save<double>(\"Col.elemIndFill\", Col<double>(expected));\n             break;\n           case 4:\n             expected = Col<double>(_elemInd, arma::fill::randu);\n             save<double>(\"Col.elemIndFill\", Col<double>(expected));\n             break;\n           case 5:\n             expected = Col<double>(_elemInd, arma::fill::zeros);\n             save<double>(\"Col.elemIndFill\", Col<double>(expected));\n             break;\n         }\n         cout << \"done.\" << endl;\n       }\n  };\n}\n\n", "meta": {"hexsha": "da5dbaeb61a1e4b70a630087ae691a0bfc964641", "size": 4208, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/cpp/src/ExpectedElemIndFill.cpp", "max_stars_repo_name": "SebastianNiemann/ArmadilloJava", "max_stars_repo_head_hexsha": "061121e22708111a8df3a2da92f6278c3a581e26", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-01-06T02:13:36.000Z", "max_stars_repo_stars_event_max_datetime": "2018-04-15T07:43:53.000Z", "max_issues_repo_path": "src/test/cpp/src/ExpectedElemIndFill.cpp", "max_issues_repo_name": "sebiniemann/ArmadilloJava", "max_issues_repo_head_hexsha": "061121e22708111a8df3a2da92f6278c3a581e26", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 33.0, "max_issues_repo_issues_event_min_datetime": "2019-10-20T21:53:37.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-20T21:53:47.000Z", "max_forks_repo_path": "src/test/cpp/src/ExpectedElemIndFill.cpp", "max_forks_repo_name": "sebiniemann/ArmadilloJava", "max_forks_repo_head_hexsha": "061121e22708111a8df3a2da92f6278c3a581e26", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-08-06T17:01:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-16T18:45:14.000Z", "avg_line_length": 30.4927536232, "max_line_length": 81, "alphanum_fraction": 0.5066539924, "num_tokens": 908, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.45006595351040996}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n// QuickBook Example\r\n\r\n// Copyright (c) 2011-2012 Barend Gehrels, Amsterdam, the Netherlands.\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n//[assign_3d_point\r\n//` Use assign to set three coordinates of a 3D point\r\n\r\n#include <iostream>\r\n#include <iomanip>\r\n\r\n#include <boost/geometry.hpp>\r\n#include <boost/geometry/geometries/point.hpp>\r\n\r\nint main()\r\n{\r\n    boost::geometry::model::point<double, 3, boost::geometry::cs::cartesian> p;\r\n    boost::geometry::assign_values(p, 1.2345, 2.3456, 3.4567);\r\n\r\n    std::cout << boost::geometry::dsv(p) << std::endl;\r\n\r\n    return 0;\r\n}\r\n\r\n//]\r\n\r\n\r\n//[assign_3d_point_output\r\n/*`\r\nOutput:\r\n[pre\r\n(1.2345, 2.3456, 3.4567)\r\n]\r\n*/\r\n//]\r\n", "meta": {"hexsha": "dcdb70920912a9c54cec0fa62a4f17441bdbc256", "size": 880, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/geometry/doc/src/examples/algorithms/assign_3d_point.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/src/examples/algorithms/assign_3d_point.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/src/examples/algorithms/assign_3d_point.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": 22.0, "max_line_length": 80, "alphanum_fraction": 0.6670454545, "num_tokens": 254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.640635868562172, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.45006595351040996}}
{"text": "#pragma once\n\n#include \"util.hpp\"\n#include <opencv2/core.hpp>\n#include <Eigen/Dense>\n#include <vector>\n#include <range/v3/all.hpp>\n#include <sstream>\n\nnamespace ch {\n\n    using vec = Eigen::Matrix<double, 3, 1>;\n    using matrix = Eigen::Matrix<double, 3, 3>;\n\n    matrix rotation_matrix(double theta);\n    matrix rotation_matrix(double cos_theta, double sin_theta);\n    matrix translation_matrix(double x, double y);\n    matrix translation_matrix(const cv::Point2d& pt);\n    matrix scale_matrix(double x_scale, double y_scale);\n\n    ranges::any_view<polyline> transform(ranges::any_view<polyline> polys, const matrix& mat);\n    std::vector<polyline> transform(const std::vector<polyline>& poly, const matrix& mat);\n    point mean_point(const polyline& poly);\n    polyline transform(const polyline& poly, const matrix& mat);\n    point transform(const point& pt, const matrix& mat);\n    void paint_polyline(cv::Mat& mat, const polyline& p, double thickness, int color, point offset = { 0,0 });\n\n    double euclidean_distance(const point& pt1, const point& pt2);\n\n    template<typename P>\n    std::string poly_to_string(const std::vector<P>& polyline) {\n        std::stringstream ss;\n        ss << \"[ \";\n        for (const auto& pt : polyline) {\n            ss << pt.x << \",\" << pt.y << \" \";\n        }\n        ss << \"]\";\n        return ss.str();\n    }\n\n    template<typename T>\n    cv::Point_<T> normalize_offset(const cv::Point_<T>& pt) {\n        auto offset = pt;\n        offset /= std::max(std::abs(pt.x), std::abs(pt.y));\n        return offset;\n    }\n\n    struct point_hasher\n    {\n        std::size_t operator()(const cv::Point& p) const;\n    };\n\n}", "meta": {"hexsha": "af6c40fed030eaa66e4c0ab0b1acc3a4862446f3", "size": 1651, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/crosshatching/geometry.hpp", "max_stars_repo_name": "jwezorek/crosshatching", "max_stars_repo_head_hexsha": "0811e239998cc68d5d6e900510974d6196638577", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/crosshatching/geometry.hpp", "max_issues_repo_name": "jwezorek/crosshatching", "max_issues_repo_head_hexsha": "0811e239998cc68d5d6e900510974d6196638577", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/crosshatching/geometry.hpp", "max_forks_repo_name": "jwezorek/crosshatching", "max_forks_repo_head_hexsha": "0811e239998cc68d5d6e900510974d6196638577", "max_forks_repo_licenses": ["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.1509433962, "max_line_length": 110, "alphanum_fraction": 0.6396123561, "num_tokens": 407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.6406358617010351, "lm_q1q2_score": 0.45006594869025507}}
{"text": "// Author(s): Wieger Wesselink\n// Copyright: see the accompanying file COPYING or copy at\n// https://github.com/mCRL2org/mCRL2/blob/master/COPYING\n//\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//\n/// \\file normal_form_test.cpp\n/// \\brief Tests for transformations into normal form.\n\n#include \"mcrl2/bes/boolean_equation_system.h\"\n#include \"mcrl2/bes/normal_forms.h\"\n#include \"mcrl2/bes/parse.h\"\n#include \"mcrl2/bes/print.h\"\n#include <boost/test/minimal.hpp>\n#include <sstream>\n#include <string>\n\nusing namespace mcrl2;\nusing namespace mcrl2::bes;\n\nvoid test_standard_recursive_form(const std::string& bes_spec, bool recursive_form = false)\n{\n  boolean_equation_system b;\n  std::stringstream from(bes_spec);\n  from >> b;\n  std::cout << \"before\\n\" << bes::pp(b) << std::endl;\n\n  make_standard_form(b, recursive_form);\n  std::cout << \"after\\n\" << bes::pp(b) << std::endl;\n}\n\nvoid test_standard_recursive_form()\n{\n  std::string bes1 =\n    \"pbes              \\n\"\n    \"                  \\n\"\n    \"nu X1 = X2 && X1; \\n\"\n    \"mu X2 = X1 || X2; \\n\"\n    \"                  \\n\"\n    \"init X1;          \\n\"\n    ;\n  test_standard_recursive_form(bes1, false);\n  test_standard_recursive_form(bes1, true);\n\n  std::string bes2 =\n    \"pbes                    \\n\"\n    \"                        \\n\"\n    \"nu X1 = X2 && true;     \\n\"\n    \"mu X2 = X1 || X2 && X1; \\n\"\n    \"                        \\n\"\n    \"init X1;                \\n\"\n    ;\n\n  test_standard_recursive_form(bes2, false);\n  test_standard_recursive_form(bes2, true);\n\n}\n\nint test_main(int argc, char* argv[])\n{\n  test_standard_recursive_form();\n\n  return 0;\n}\n", "meta": {"hexsha": "f6651358c82c346e88462949f0387d4912c3b00a", "size": 1710, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libraries/bes/test/normal_form_test.cpp", "max_stars_repo_name": "tneele/mCRL2", "max_stars_repo_head_hexsha": "8f2d730d650ffec15130d6419f69c50f81e5125c", "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": "libraries/bes/test/normal_form_test.cpp", "max_issues_repo_name": "tneele/mCRL2", "max_issues_repo_head_hexsha": "8f2d730d650ffec15130d6419f69c50f81e5125c", "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": "libraries/bes/test/normal_form_test.cpp", "max_forks_repo_name": "tneele/mCRL2", "max_forks_repo_head_hexsha": "8f2d730d650ffec15130d6419f69c50f81e5125c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.5223880597, "max_line_length": 91, "alphanum_fraction": 0.614619883, "num_tokens": 488, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300449389326, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.4500659407103199}}
{"text": "/*\n * patSampleFromDiscreteUntilCdf.cc\n *\n *  Created on: Nov 16, 2011\n *      Author: jchen\n */\n\n#include \"patSampleFromDiscreteUntilCdf.h\"\n#include <time.h>\n#include \"patDisplay.h\"\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_real.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <numeric>\n\nboost::mt19937 gen;\npatSampleFromDiscreteUntilCdf::patSampleFromDiscreteUntilCdf(\n\t\tvector<double> probabilities) :\n\t\tm_probabilities(probabilities) {\n\n}\nbool patSampleFromDiscreteUntilCdf::normalizeProbabilities(\n\t\tvector<double>& probas) {\n\tdouble sum = 0.0;\n\tfor (unsigned int i = 0; i < probas.size(); ++i) {\n\t\t//DEBUG_MESSAGE(probas[i]);\n\t\tsum += probas[i];\n\t}\n\n\tif (sum == 0.0) {\n\t\t//WARNING(\"Invalid proba, all zero\");\n\t\treturn false;\n\t}\n\n\tfor (unsigned int i = 0; i < probas.size(); ++i) {\n\t\tprobas[i] /= sum;\n\t}\n\treturn true;\n\n}\npatSampleFromDiscreteUntilCdf::~patSampleFromDiscreteUntilCdf() {\n}\n\nset<int> patSampleFromDiscreteUntilCdf::sample(double cdf) {\n\tset<int> sampled;\n\tif (!normalizeProbabilities(m_probabilities)) {\n\t\treturn sampled;\n\t}\n\n\tvector<double> sampling = m_probabilities;\n\tdouble sampled_cdf = 0.0;\n\twhile (sampled_cdf < cdf) {\n\t\tif (!normalizeProbabilities(sampling)) {\n\t\t\treturn sampled;\n\t\t}\n\t\t/*\n\t\t patDiscreteDistribution discreteDraw(&sampling, &m_ran_uniform);\n\t\t int new_sample = discreteDraw();\n\t\t sampling[new_sample] = 0.0;\n\t\t sampled_cdf += m_probabilities[new_sample];\n\t\t sampled.insert(new_sample);\n\t\t */\n\t}\n\treturn sampled;\n}\n\nvoid patSampleFromDiscreteUntilCdf::setAsLogLike() {\n\n\tdouble largest = -DBL_MAX;\n\tfor (unsigned int i = 0; i < m_probabilities.size(); ++i) {\n\t\tif (m_probabilities[i] > largest) {\n\t\t\tlargest = m_probabilities[i];\n\t\t}\n\t}\n\tfor (unsigned int i = 0; i < m_probabilities.size(); ++i) {\n\t\tm_probabilities[i]= exp(m_probabilities[i]-largest);\n\t}\n\n}\nset<int> patSampleFromDiscreteUntilCdf::sampleByCount(unsigned long count) {\n\tset<int> sampled;\n\tif (!normalizeProbabilities(m_probabilities)) {\n\t\treturn sampled;\n\t}\n\n\tvector<double> sampling = m_probabilities;\n\tunsigned long sampled_count = 0;\n\twhile (sampled_count < count) {\n\t\tif (!normalizeProbabilities(sampling)) {\n\t\t\treturn sampled;\n\t\t}\n\n\t\tvector<double> cumulative;\n\t\tstd::partial_sum(sampling.begin(), sampling.end(),\n\t\t\t\tstd::back_inserter(cumulative));\n\t\tboost::uniform_real<> dist(0, cumulative.back());\n\t\tboost::variate_generator<boost::mt19937&, boost::uniform_real<> > die(\n\t\t\t\tgen, dist);\n\n\t\t//patDiscreteDistribution discreteDraw(&sampling, &m_ran_uniform);\n\t\tint new_sample = std::lower_bound(cumulative.begin(), cumulative.end(),\n\t\t\t\tdie()) - cumulative.begin();\n\t\tsampling[new_sample] = 0.0;\n\t\tsampled_count += 1;\n\t\tsampled.insert(new_sample);\n\t}\n\treturn sampled;\n}\n", "meta": {"hexsha": "56dbe8ea1c2ca4e8dd2ab9a92a3b16d8d706ab93", "size": 2735, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/Utilities/patSampleFromDiscreteUntilCdf.cc", "max_stars_repo_name": "godosou/smaroute", "max_stars_repo_head_hexsha": "e2ccc9492dff54c8ef5c74d5309d2b06758ba342", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2015-02-23T16:02:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-26T17:58:53.000Z", "max_issues_repo_path": "src/Utilities/patSampleFromDiscreteUntilCdf.cc", "max_issues_repo_name": "godosou/smaroute", "max_issues_repo_head_hexsha": "e2ccc9492dff54c8ef5c74d5309d2b06758ba342", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Utilities/patSampleFromDiscreteUntilCdf.cc", "max_forks_repo_name": "godosou/smaroute", "max_forks_repo_head_hexsha": "e2ccc9492dff54c8ef5c74d5309d2b06758ba342", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2015-02-23T16:05:59.000Z", "max_forks_repo_forks_event_max_datetime": "2017-05-04T16:13:16.000Z", "avg_line_length": 25.0917431193, "max_line_length": 76, "alphanum_fraction": 0.7104204753, "num_tokens": 762, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.4500659342297899}}
{"text": "/* ----------------------------------------------------------------------------\n * Copyright 2020, Jesus Tordesillas Torres, Aerospace Controls Laboratory\n * Massachusetts Institute of Technology\n * All Rights Reserved\n * Authors: Jesus Tordesillas, et al.\n * See LICENSE file for the license information\n * -------------------------------------------------------------------------- */\n\n#include \"gurobi_c++.h\"\n#include <sstream>\n#include <Eigen/Dense>\n#include <type_traits>\nusing namespace std;\n\ntemplate <typename T>\nGRBQuadExpr GetNorm2(const std::vector<T>& x)  // Return the squared norm of a vector\n{\n  GRBQuadExpr result = 0;\n  for (int i = 0; i < x.size(); i++)\n  {\n    result = result + x[i] * x[i];\n  }\n  return result;\n}\n\nstd::vector<GRBLinExpr> MatrixMultiply(const std::vector<std::vector<double>>& A, const std::vector<GRBVar>& x)\n{\n  std::vector<GRBLinExpr> result;\n\n  for (int i = 0; i < A.size(); i++)\n  {\n    GRBLinExpr lin_exp = 0;\n    for (int m = 0; m < x.size(); m++)\n    {\n      lin_exp = lin_exp + A[i][m] * x[m];\n    }\n    result.push_back(lin_exp);\n  }\n  return result;\n}\n\ntemplate <typename T>  // Overload + to sum Elementwise std::vectors\nstd::vector<T> operator+(const std::vector<T>& a, const std::vector<T>& b)\n{\n  assert(a.size() == b.size());\n\n  std::vector<T> result;\n  result.reserve(a.size());\n\n  std::transform(a.begin(), a.end(), b.begin(), std::back_inserter(result), std::plus<T>());\n  return result;\n}\n\ntemplate <typename T>  // Overload - to substract Elementwise std::vectors\nstd::vector<T> operator-(const std::vector<T>& a, const std::vector<T>& b)\n{\n  assert(a.size() == b.size());\n\n  std::vector<T> result;\n  result.reserve(a.size());\n\n  std::transform(a.begin(), a.end(), b.begin(), std::back_inserter(result), std::minus<T>());\n  return result;\n}\n\nstd::vector<GRBLinExpr> operator-(const std::vector<GRBVar>& x, const std::vector<double>& b)\n{\n  std::vector<GRBLinExpr> result;\n  for (int i = 0; i < x.size(); i++)\n  {\n    GRBLinExpr tmp = x[i] - b[i];\n    result.push_back(tmp);\n  }\n  return result;\n}\n\ntemplate <typename T>\nstd::vector<T> eigenVector2std(const Eigen::Matrix<T, -1, 1>& x)  // Return the squared norm of a vector\n{\n  std::vector<T> result = 0;\n  for (int i = 0; i < x.rows(); i++)\n  {\n    result.push_back(x(i, 1));\n  }\n  return result;\n}\n\ntemplate <typename T>\nstd::vector<T> GetColumn(std::vector<std::vector<T>> x, int column)\n{\n  std::vector<T> result;\n\n  for (int i = 0; i < x.size(); i++)\n  {\n    result.push_back(x[i][column]);\n  }\n  return result;\n}\n\nint main(int argc, char* argv[])\n{\n  GRBEnv* env = 0;\n  GRBVar* open = 0;\n  GRBVar** transport = 0;\n  int transportCt = 0;\n  try\n  {\n    // Model\n    env = new GRBEnv();\n    GRBModel model = GRBModel(*env);\n    model.set(GRB_StringAttr_ModelName, \"planning\");\n\n    int N = 20;\n    double umax = 5;\n    double q = 20000000000;\n    double dt = 0.4;\n    double dt2 = dt * dt / 2.0;\n    double dt3 = dt * dt * dt / 6.0;\n    std::vector<std::string> states = { \"x\", \"y\", \"z\", \"vx\", \"vy\", \"vz\", \"ax\", \"ay\", \"az\" };\n    std::vector<std::string> inputs = { \"jx\", \"jy\", \"jz\" };\n\n    std::vector<double> x0 = { 5, 11.5, 0.5, 0, 0, 0, 0, 0, 0 };\n\n    std::vector<double> xf = { 14, 5, 2.5, 0, 0, 0, 0, 0, 0 };\n\n    std::vector<std::vector<double>> As = { { 1, 0, 0, dt, 0, 0, dt2, 0, 0 },  /////////////////////////////////\n                                            { 0, 1, 0, 0, dt, 0, 0, dt2, 0 },  /////////////////////////////////\n                                            { 0, 0, 1, 0, 0, dt, 0, 0, dt2 },  /////////////////////////////////\n                                            { 0, 0, 0, 1, 0, 0, dt, 0, 0 },    /////////////////////////////////\n                                            { 0, 0, 0, 0, 1, 0, 0, dt, 0 },    /////////////////////////////////\n                                            { 0, 0, 0, 0, 0, 1, 0, 0, dt },    /////////////////////////////////\n                                            { 0, 0, 0, 0, 0, 0, 1, 0, 0 },     /////////////////////////////////\n                                            { 0, 0, 0, 0, 0, 0, 0, 1, 0 },     /////////////////////////////////\n                                            { 0, 0, 0, 0, 0, 0, 0, 0, 1 } };\n\n    std::vector<std::vector<double>> Bs = { { dt3, 0, 0 },   /////////////////////////////////\n                                            { 0, dt3, 0 },   /////////////////////////////////\n                                            { 0, 0, dt3 },   /////////////////////////////////\n                                            { dt2, 0, 0 },   /////////////////////////////////\n                                            { 0, dt2, 0 },   /////////////////////////////////\n                                            { 0, 0, dt2 },   /////////////////////////////////\n                                            { dt, 0, 0 },    /////////////////////////////////\n                                            { 0, dt, 0 },    /////////////////////////////////\n                                            { 0, 0, dt } };  /////////////////////////////////\n\n    std::cout << \"here1\" << std::endl;\n\n    std::vector<std::vector<GRBVar>> x;\n    std::vector<std::vector<GRBVar>> u;\n    for (int i = 0; i < 9; i++)\n    {\n      std::vector<GRBVar> row_i;\n      for (int t = 0; t < N + 1; t++)\n      {\n        row_i.push_back(model.addVar(-GRB_INFINITY, GRB_INFINITY, 0, GRB_CONTINUOUS, states[i] + std::to_string(t)));\n      }\n      x.push_back(row_i);\n    }\n\n    for (int i = 0; i < 3; i++)\n    {\n      std::vector<GRBVar> row_i;\n      for (int t = 0; t < N; t++)\n      {\n        row_i.push_back(model.addVar(-umax, umax, 0, GRB_CONTINUOUS, inputs[i] + std::to_string(t)));\n      }\n      u.push_back(row_i);\n    }\n\n    // Constraints x_t+1=Ax_t+Bu_t\n    for (int t = 0; t < N; t++)\n    {\n      std::vector<GRBVar> xt = GetColumn(x, t);\n      std::vector<GRBVar> ut = GetColumn(u, t);\n      std::vector<GRBLinExpr> Ax_tm1 = MatrixMultiply(As, xt) + MatrixMultiply(Bs, ut);  //  x_t+1=Ax_t+Bu_t\n\n      for (int i = 0; i < 9; i++)\n      {\n        std::cout << \"i=\" << i << \"  t=\" << t << std::endl;\n        // std::cout << \"x[i][t]\" << x[i][t] << std::endl;\n        model.addConstr(x[i][t + 1] == Ax_tm1[i]);\n        // std::cout << \"Abajo\" << std::endl;\n      }\n    }\n    // model.update();\n\n    // Constraints x_0=x_initial\n    for (int i = 0; i < 9; i++)\n    {\n      model.addConstr(x[i][0] == x0[i]);\n    }\n\n    GRBQuadExpr control_cost = 0;\n    for (int t = 0; t < N; t++)\n    {\n      std::vector<GRBVar> ut = GetColumn(u, t);\n      control_cost = control_cost + GetNorm2(ut);\n    }\n\n    GRBQuadExpr final_state_cost = 0;\n    std::vector<GRBVar> xFinal = GetColumn(x, N);\n    // std::vector<GRBLinExpr> prueba = xFinal - xf;\n    final_state_cost = GetNorm2(xFinal - xf);\n    final_state_cost = q * final_state_cost;\n\n    model.setObjective(control_cost + final_state_cost, GRB_MINIMIZE);\n\n    // Solve*/\n    model.update();\n    model.write(\"debug.lp\");\n    model.optimize();\n\n    std::cout << \"\\nOBJECTIVE: \" << model.get(GRB_DoubleAttr_ObjVal) << std::endl;\n    std::cout << \"Positions X:\" << std::endl;\n    for (int t = 0; t < N + 1; t++)\n    {\n      std::cout << x[0][t].get(GRB_DoubleAttr_X) << std::endl;\n    }\n  }\n\n  catch (GRBException e)\n  {\n    cout << \"Error code = \" << e.getErrorCode() << endl;\n    cout << e.getMessage() << endl;\n  }\n  /*catch (...)\n  {\n    cout << \"Exception during optimization\" << endl;\n  }*/\n\n  delete env;\n  return 0;\n}\n", "meta": {"hexsha": "f8094edee721847f2180e5975c063d7526b34630", "size": 7460, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "faster/other/gurobi_discrete.cpp", "max_stars_repo_name": "wyr501/faster", "max_stars_repo_head_hexsha": "df92802a72b1e5d2acf0682d0772d14a56bf56ab", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 489.0, "max_stars_repo_stars_event_min_datetime": "2020-03-19T15:48:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:22:55.000Z", "max_issues_repo_path": "faster/other/gurobi_discrete.cpp", "max_issues_repo_name": "wyr501/faster", "max_issues_repo_head_hexsha": "df92802a72b1e5d2acf0682d0772d14a56bf56ab", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 37.0, "max_issues_repo_issues_event_min_datetime": "2020-05-08T13:51:32.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T07:43:21.000Z", "max_forks_repo_path": "faster/other/gurobi_discrete.cpp", "max_forks_repo_name": "wyr501/faster", "max_forks_repo_head_hexsha": "df92802a72b1e5d2acf0682d0772d14a56bf56ab", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 116.0, "max_forks_repo_forks_event_min_datetime": "2020-03-19T20:37:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T03:51:21.000Z", "avg_line_length": 31.8803418803, "max_line_length": 117, "alphanum_fraction": 0.4439678284, "num_tokens": 2271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.4500004430344677}}
